asda?‰PNG  IHDR ? f ??C1 sRGB ??é gAMA ±? üa pHYs ? ??o¨d GIDATx^íüL”÷e÷Y?a?("Bh?_ò???¢§?q5k?*:t0A-o??¥]VkJ¢M??f?±8\k2íll£1]q?ù???T gdfontt.h000064400000001042151027430550006361 0ustar00#ifndef _GDFONTT_H_ #define _GDFONTT_H_ 1 #ifdef __cplusplus extern "C" { #endif /* This is a header file for gd font, generated using bdftogd version 0.5 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -Misc-Fixed-Medium-R-Normal--8-80-75-75-C-50-ISO8859-2 at Thu Jan 8 13:49:54 1998. The original bdf was holding following copyright: "Libor Skarvada, libor@informatics.muni.cz" */ #include "gd.h" extern BGD_EXPORT_DATA_PROT gdFontPtr gdFontTiny; BGD_DECLARE(gdFontPtr) gdFontGetTiny(void); #ifdef __cplusplus } #endif #endif wordexp.h000064400000004705151027430550006415 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _WORDEXP_H #define _WORDEXP_H 1 #include #define __need_size_t #include __BEGIN_DECLS /* Bits set in the FLAGS argument to `wordexp'. */ enum { WRDE_DOOFFS = (1 << 0), /* Insert PWORDEXP->we_offs NULLs. */ WRDE_APPEND = (1 << 1), /* Append to results of a previous call. */ WRDE_NOCMD = (1 << 2), /* Don't do command substitution. */ WRDE_REUSE = (1 << 3), /* Reuse storage in PWORDEXP. */ WRDE_SHOWERR = (1 << 4), /* Don't redirect stderr to /dev/null. */ WRDE_UNDEF = (1 << 5), /* Error for expanding undefined variables. */ __WRDE_FLAGS = (WRDE_DOOFFS | WRDE_APPEND | WRDE_NOCMD | WRDE_REUSE | WRDE_SHOWERR | WRDE_UNDEF) }; /* Structure describing a word-expansion run. */ typedef struct { size_t we_wordc; /* Count of words matched. */ char **we_wordv; /* List of expanded words. */ size_t we_offs; /* Slots to reserve in `we_wordv'. */ } wordexp_t; /* Possible nonzero return values from `wordexp'. */ enum { #ifdef __USE_XOPEN WRDE_NOSYS = -1, /* Never used since we support `wordexp'. */ #endif WRDE_NOSPACE = 1, /* Ran out of memory. */ WRDE_BADCHAR, /* A metachar appears in the wrong place. */ WRDE_BADVAL, /* Undefined var reference with WRDE_UNDEF. */ WRDE_CMDSUB, /* Command substitution with WRDE_NOCMD. */ WRDE_SYNTAX /* Shell syntax error. */ }; /* Do word expansion of WORDS into PWORDEXP. */ extern int wordexp (const char *__restrict __words, wordexp_t *__restrict __pwordexp, int __flags); /* Free the storage allocated by a `wordexp' call. */ extern void wordfree (wordexp_t *__wordexp) __THROW; __END_DECLS #endif /* wordexp.h */ dlfcn.h000064400000016106151027430550006011 0ustar00/* User functions for run-time dynamic loading. Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _DLFCN_H #define _DLFCN_H 1 #include #define __need_size_t #include /* Collect various system dependent definitions and declarations. */ #include #ifdef __USE_GNU /* If the first argument of `dlsym' or `dlvsym' is set to RTLD_NEXT the run-time address of the symbol called NAME in the next shared object is returned. The "next" relation is defined by the order the shared objects were loaded. */ # define RTLD_NEXT ((void *) -1l) /* If the first argument to `dlsym' or `dlvsym' is set to RTLD_DEFAULT the run-time address of the symbol called NAME in the global scope is returned. */ # define RTLD_DEFAULT ((void *) 0) /* Type for namespace indeces. */ typedef long int Lmid_t; /* Special namespace ID values. */ # define LM_ID_BASE 0 /* Initial namespace. */ # define LM_ID_NEWLM -1 /* For dlmopen: request new namespace. */ #endif __BEGIN_DECLS /* Open the shared object FILE and map it in; return a handle that can be passed to `dlsym' to get symbol values from it. */ extern void *dlopen (const char *__file, int __mode) __THROWNL; /* Unmap and close a shared object opened by `dlopen'. The handle cannot be used again after calling `dlclose'. */ extern int dlclose (void *__handle) __THROWNL __nonnull ((1)); /* Find the run-time address in the shared object HANDLE refers to of the symbol called NAME. */ extern void *dlsym (void *__restrict __handle, const char *__restrict __name) __THROW __nonnull ((2)); #ifdef __USE_GNU /* Like `dlopen', but request object to be allocated in a new namespace. */ extern void *dlmopen (Lmid_t __nsid, const char *__file, int __mode) __THROWNL; /* Find the run-time address in the shared object HANDLE refers to of the symbol called NAME with VERSION. */ extern void *dlvsym (void *__restrict __handle, const char *__restrict __name, const char *__restrict __version) __THROW __nonnull ((2, 3)); #endif /* When any of the above functions fails, call this function to return a string describing the error. Each call resets the error string so that a following call returns null. */ extern char *dlerror (void) __THROW; #ifdef __USE_GNU /* Structure containing information about object searched using `dladdr'. */ typedef struct { const char *dli_fname; /* File name of defining object. */ void *dli_fbase; /* Load address of that object. */ const char *dli_sname; /* Name of nearest symbol. */ void *dli_saddr; /* Exact value of nearest symbol. */ } Dl_info; /* Fill in *INFO with the following information about ADDRESS. Returns 0 iff no shared object's segments contain that address. */ extern int dladdr (const void *__address, Dl_info *__info) __THROW __nonnull ((2)); /* Same as `dladdr', but additionally sets *EXTRA_INFO according to FLAGS. */ extern int dladdr1 (const void *__address, Dl_info *__info, void **__extra_info, int __flags) __THROW __nonnull ((2)); /* These are the possible values for the FLAGS argument to `dladdr1'. This indicates what extra information is stored at *EXTRA_INFO. It may also be zero, in which case the EXTRA_INFO argument is not used. */ enum { /* Matching symbol table entry (const ElfNN_Sym *). */ RTLD_DL_SYMENT = 1, /* The object containing the address (struct link_map *). */ RTLD_DL_LINKMAP = 2 }; /* Get information about the shared object HANDLE refers to. REQUEST is from among the values below, and determines the use of ARG. On success, returns zero. On failure, returns -1 and records an error message to be fetched with `dlerror'. */ extern int dlinfo (void *__restrict __handle, int __request, void *__restrict __arg) __THROW __nonnull ((1, 3)); /* These are the possible values for the REQUEST argument to `dlinfo'. */ enum { /* Treat ARG as `lmid_t *'; store namespace ID for HANDLE there. */ RTLD_DI_LMID = 1, /* Treat ARG as `struct link_map **'; store the `struct link_map *' for HANDLE there. */ RTLD_DI_LINKMAP = 2, RTLD_DI_CONFIGADDR = 3, /* Unsupported, defined by Solaris. */ /* Treat ARG as `Dl_serinfo *' (see below), and fill in to describe the directories that will be searched for dependencies of this object. RTLD_DI_SERINFOSIZE fills in just the `dls_cnt' and `dls_size' entries to indicate the size of the buffer that must be passed to RTLD_DI_SERINFO to fill in the full information. */ RTLD_DI_SERINFO = 4, RTLD_DI_SERINFOSIZE = 5, /* Treat ARG as `char *', and store there the directory name used to expand $ORIGIN in this shared object's dependency file names. */ RTLD_DI_ORIGIN = 6, RTLD_DI_PROFILENAME = 7, /* Unsupported, defined by Solaris. */ RTLD_DI_PROFILEOUT = 8, /* Unsupported, defined by Solaris. */ /* Treat ARG as `size_t *', and store there the TLS module ID of this object's PT_TLS segment, as used in TLS relocations; store zero if this object does not define a PT_TLS segment. */ RTLD_DI_TLS_MODID = 9, /* Treat ARG as `void **', and store there a pointer to the calling thread's TLS block corresponding to this object's PT_TLS segment. Store a null pointer if this object does not define a PT_TLS segment, or if the calling thread has not allocated a block for it. */ RTLD_DI_TLS_DATA = 10, /* Treat ARG as const ElfW(Phdr) **, and store the address of the program header array at that location. The dlinfo call returns the number of program headers in the array. */ RTLD_DI_PHDR = 11, RTLD_DI_MAX = 11 }; /* This is the type of elements in `Dl_serinfo', below. The `dls_name' member points to space in the buffer passed to `dlinfo'. */ typedef struct { char *dls_name; /* Name of library search path directory. */ unsigned int dls_flags; /* Indicates where this directory came from. */ } Dl_serpath; /* This is the structure that must be passed (by reference) to `dlinfo' for the RTLD_DI_SERINFO and RTLD_DI_SERINFOSIZE requests. */ typedef struct { size_t dls_size; /* Size in bytes of the whole buffer. */ unsigned int dls_cnt; /* Number of elements in `dls_serpath'. */ Dl_serpath dls_serpath[1]; /* Actually longer, dls_cnt elements. */ } Dl_serinfo; #endif /* __USE_GNU */ __END_DECLS #endif /* dlfcn.h */ complex.h000064400000015773151027430550006403 0ustar00/* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * ISO C99: 7.3 Complex arithmetic */ #ifndef _COMPLEX_H #define _COMPLEX_H 1 #define __GLIBC_INTERNAL_STARTING_HEADER_IMPLEMENTATION #include /* Get general and ISO C99 specific information. */ #include /* Gather machine-dependent _FloatN type support. */ #include __BEGIN_DECLS /* We might need to add support for more compilers here. But since ISO C99 is out hopefully all maintained compilers will soon provide the data types `float complex' and `double complex'. */ #if __GNUC_PREREQ (2, 7) && !__GNUC_PREREQ (2, 97) # define _Complex __complex__ #endif #define complex _Complex /* Narrowest imaginary unit. This depends on the floating-point evaluation method. XXX This probably has to go into a gcc related file. */ #define _Complex_I (__extension__ 1.0iF) /* Another more descriptive name is `I'. XXX Once we have the imaginary support switch this to _Imaginary_I. */ #undef I #define I _Complex_I #if defined __USE_ISOC11 && __GNUC_PREREQ (4, 7) /* Macros to expand into expression of specified complex type. */ # define CMPLX(x, y) __builtin_complex ((double) (x), (double) (y)) # define CMPLXF(x, y) __builtin_complex ((float) (x), (float) (y)) # define CMPLXL(x, y) __builtin_complex ((long double) (x), (long double) (y)) #endif #if __HAVE_FLOAT16 && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF16(x, y) __builtin_complex ((_Float16) (x), (_Float16) (y)) #endif #if __HAVE_FLOAT32 && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF32(x, y) __builtin_complex ((_Float32) (x), (_Float32) (y)) #endif #if __HAVE_FLOAT64 && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF64(x, y) __builtin_complex ((_Float64) (x), (_Float64) (y)) #endif #if __HAVE_FLOAT128 && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF128(x, y) __builtin_complex ((_Float128) (x), (_Float128) (y)) #endif #if __HAVE_FLOAT32X && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF32X(x, y) __builtin_complex ((_Float32x) (x), (_Float32x) (y)) #endif #if __HAVE_FLOAT64X && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF64X(x, y) __builtin_complex ((_Float64x) (x), (_Float64x) (y)) #endif #if __HAVE_FLOAT128X && __GLIBC_USE (IEC_60559_TYPES_EXT) # define CMPLXF128X(x, y) \ __builtin_complex ((_Float128x) (x), (_Float128x) (y)) #endif /* The file contains the prototypes for all the actual math functions. These macros are used for those prototypes, so we can easily declare each function as both `name' and `__name', and can declare the float versions `namef' and `__namef'. */ #define __MATHCALL(function, args) \ __MATHDECL (_Mdouble_complex_,function, args) #define __MATHDECL(type, function, args) \ __MATHDECL_1(type, function, args); \ __MATHDECL_1(type, __CONCAT(__,function), args) #define __MATHDECL_1(type, function, args) \ extern type __MATH_PRECNAME(function) args __THROW #define _Mdouble_ double #define __MATH_PRECNAME(name) name #include #undef _Mdouble_ #undef __MATH_PRECNAME /* Now the float versions. */ #define _Mdouble_ float #define __MATH_PRECNAME(name) name##f #include #undef _Mdouble_ #undef __MATH_PRECNAME /* And the long double versions. It is non-critical to define them here unconditionally since `long double' is required in ISO C99. */ #if !(defined __NO_LONG_DOUBLE_MATH && defined _LIBC) \ || defined __LDBL_COMPAT # ifdef __LDBL_COMPAT # undef __MATHDECL_1 # define __MATHDECL_1(type, function, args) \ extern type __REDIRECT_NTH(__MATH_PRECNAME(function), args, function) # endif # define _Mdouble_ long double # define __MATH_PRECNAME(name) name##l # include #endif #undef _Mdouble_ #undef __MATH_PRECNAME #if (__HAVE_DISTINCT_FLOAT16 || (__HAVE_FLOAT16 && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT16 # define _Mdouble_ _Float16 # define __MATH_PRECNAME(name) name##f16 # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #if (__HAVE_DISTINCT_FLOAT32 || (__HAVE_FLOAT32 && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT32 # define _Mdouble_ _Float32 # define __MATH_PRECNAME(name) name##f32 # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #if (__HAVE_DISTINCT_FLOAT64 || (__HAVE_FLOAT64 && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT64 # define _Mdouble_ _Float64 # define __MATH_PRECNAME(name) name##f64 # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #if (__HAVE_DISTINCT_FLOAT128 || (__HAVE_FLOAT128 && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT128 # define _Mdouble_ _Float128 # define __MATH_PRECNAME(name) name##f128 # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #if (__HAVE_DISTINCT_FLOAT32X || (__HAVE_FLOAT32X && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT32X # define _Mdouble_ _Float32x # define __MATH_PRECNAME(name) name##f32x # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #if (__HAVE_DISTINCT_FLOAT64X || (__HAVE_FLOAT64X && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT64X # define _Mdouble_ _Float64x # define __MATH_PRECNAME(name) name##f64x # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #if (__HAVE_DISTINCT_FLOAT128X || (__HAVE_FLOAT128X && !defined _LIBC)) \ && __GLIBC_USE (IEC_60559_TYPES_EXT) # undef _Mdouble_complex_ # define _Mdouble_complex_ __CFLOAT128X # define _Mdouble_ _Float128x # define __MATH_PRECNAME(name) name##f128x # include # undef _Mdouble_ # undef __MATH_PRECNAME # undef _Mdouble_complex_ #endif #undef __MATHDECL_1 #undef __MATHDECL #undef __MATHCALL __END_DECLS #endif /* complex.h */ autosprintf.h000064400000004517151027430550007304 0ustar00/* Class autosprintf - formatted output to an ostream. Copyright (C) 2002, 2012-2016 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef _AUTOSPRINTF_H #define _AUTOSPRINTF_H /* This feature is available in gcc versions 2.5 and later. */ #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__ # define _AUTOSPRINTF_ATTRIBUTE_FORMAT() /* empty */ #else /* The __-protected variants of 'format' and 'printf' attributes are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */ # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7) # define _AUTOSPRINTF_ATTRIBUTE_FORMAT() \ __attribute__ ((__format__ (__printf__, 2, 3))) # else # define _AUTOSPRINTF_ATTRIBUTE_FORMAT() \ __attribute__ ((format (printf, 2, 3))) # endif #endif #include #include namespace gnu { /* A temporary object, usually allocated on the stack, representing the result of an asprintf() call. */ class autosprintf { public: /* Constructor: takes a format string and the printf arguments. */ autosprintf (const char *format, ...) _AUTOSPRINTF_ATTRIBUTE_FORMAT(); /* Copy constructor. */ autosprintf (const autosprintf& src); autosprintf& operator = (autosprintf copy); /* Destructor: frees the temporarily allocated string. */ ~autosprintf (); /* Conversion to string. */ operator char * () const; operator std::string () const; /* Output to an ostream. */ friend inline std::ostream& operator<< (std::ostream& stream, const autosprintf& tmp) { stream << (tmp.str ? tmp.str : "(error in autosprintf)"); return stream; } private: char *str; }; } #endif /* _AUTOSPRINTF_H */ pcre2posix.h000064400000013254151027430550007022 0ustar00/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE2 is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Original API code Copyright (c) 1997-2012 University of Cambridge New API code Copyright (c) 2016 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* Have to include stdlib.h in order to ensure that size_t is defined. */ #include /* Allow for C++ users */ #ifdef __cplusplus extern "C" { #endif /* Options, mostly defined by POSIX, but with some extras. */ #define REG_ICASE 0x0001 /* Maps to PCRE2_CASELESS */ #define REG_NEWLINE 0x0002 /* Maps to PCRE2_MULTILINE */ #define REG_NOTBOL 0x0004 /* Maps to PCRE2_NOTBOL */ #define REG_NOTEOL 0x0008 /* Maps to PCRE2_NOTEOL */ #define REG_DOTALL 0x0010 /* NOT defined by POSIX; maps to PCRE2_DOTALL */ #define REG_NOSUB 0x0020 /* Do not report what was matched */ #define REG_UTF 0x0040 /* NOT defined by POSIX; maps to PCRE2_UTF */ #define REG_STARTEND 0x0080 /* BSD feature: pass subject string by so,eo */ #define REG_NOTEMPTY 0x0100 /* NOT defined by POSIX; maps to PCRE2_NOTEMPTY */ #define REG_UNGREEDY 0x0200 /* NOT defined by POSIX; maps to PCRE2_UNGREEDY */ #define REG_UCP 0x0400 /* NOT defined by POSIX; maps to PCRE2_UCP */ #define REG_PEND 0x0800 /* GNU feature: pass end pattern by re_endp */ #define REG_NOSPEC 0x1000 /* Maps to PCRE2_LITERAL */ /* This is not used by PCRE2, but by defining it we make it easier to slot PCRE2 into existing programs that make POSIX calls. */ #define REG_EXTENDED 0 /* Error values. Not all these are relevant or used by the wrapper. */ enum { REG_ASSERT = 1, /* internal error ? */ REG_BADBR, /* invalid repeat counts in {} */ REG_BADPAT, /* pattern error */ REG_BADRPT, /* ? * + invalid */ REG_EBRACE, /* unbalanced {} */ REG_EBRACK, /* unbalanced [] */ REG_ECOLLATE, /* collation error - not relevant */ REG_ECTYPE, /* bad class */ REG_EESCAPE, /* bad escape sequence */ REG_EMPTY, /* empty expression */ REG_EPAREN, /* unbalanced () */ REG_ERANGE, /* bad range inside [] */ REG_ESIZE, /* expression too big */ REG_ESPACE, /* failed to get memory */ REG_ESUBREG, /* bad back reference */ REG_INVARG, /* bad argument */ REG_NOMATCH /* match failed */ }; /* The structure representing a compiled regular expression. It is also used for passing the pattern end pointer when REG_PEND is set. */ typedef struct { void *re_pcre2_code; void *re_match_data; const char *re_endp; size_t re_nsub; size_t re_erroffset; int re_cflags; } regex_t; /* The structure in which a captured offset is returned. */ typedef int regoff_t; typedef struct { regoff_t rm_so; regoff_t rm_eo; } regmatch_t; /* When an application links to a PCRE2 DLL in Windows, the symbols that are imported have to be identified as such. When building PCRE2, the appropriate export settings are needed, and are set in pcre2posix.c before including this file. */ #if defined(_WIN32) && !defined(PCRE2_STATIC) && !defined(PCRE2POSIX_EXP_DECL) # define PCRE2POSIX_EXP_DECL extern __declspec(dllimport) # define PCRE2POSIX_EXP_DEFN __declspec(dllimport) #endif /* By default, we use the standard "extern" declarations. */ #ifndef PCRE2POSIX_EXP_DECL # ifdef __cplusplus # define PCRE2POSIX_EXP_DECL extern "C" # define PCRE2POSIX_EXP_DEFN extern "C" # else # define PCRE2POSIX_EXP_DECL extern # define PCRE2POSIX_EXP_DEFN extern # endif #endif /* The functions */ PCRE2POSIX_EXP_DECL int regcomp(regex_t *, const char *, int); PCRE2POSIX_EXP_DECL int regexec(const regex_t *, const char *, size_t, regmatch_t *, int); PCRE2POSIX_EXP_DECL size_t regerror(int, const regex_t *, char *, size_t); PCRE2POSIX_EXP_DECL void regfree(regex_t *); #ifdef __cplusplus } /* extern "C" */ #endif /* End of pcre2posix.h */ ctype.h000064400000025323151027430550006050 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * ISO C99 Standard 7.4: Character handling */ #ifndef _CTYPE_H #define _CTYPE_H 1 #include #include __BEGIN_DECLS #ifndef _ISbit /* These are all the characteristics of characters. If there get to be more than 16 distinct characteristics, many things must be changed that use `unsigned short int's. The characteristics are stored always in network byte order (big endian). We define the bit value interpretations here dependent on the machine's byte order. */ # include # if __BYTE_ORDER == __BIG_ENDIAN # define _ISbit(bit) (1 << (bit)) # else /* __BYTE_ORDER == __LITTLE_ENDIAN */ # define _ISbit(bit) ((bit) < 8 ? ((1 << (bit)) << 8) : ((1 << (bit)) >> 8)) # endif enum { _ISupper = _ISbit (0), /* UPPERCASE. */ _ISlower = _ISbit (1), /* lowercase. */ _ISalpha = _ISbit (2), /* Alphabetic. */ _ISdigit = _ISbit (3), /* Numeric. */ _ISxdigit = _ISbit (4), /* Hexadecimal numeric. */ _ISspace = _ISbit (5), /* Whitespace. */ _ISprint = _ISbit (6), /* Printing. */ _ISgraph = _ISbit (7), /* Graphical. */ _ISblank = _ISbit (8), /* Blank (usually SPC and TAB). */ _IScntrl = _ISbit (9), /* Control character. */ _ISpunct = _ISbit (10), /* Punctuation. */ _ISalnum = _ISbit (11) /* Alphanumeric. */ }; #endif /* ! _ISbit */ /* These are defined in ctype-info.c. The declarations here must match those in localeinfo.h. In the thread-specific locale model (see `uselocale' in ) we cannot use global variables for these as was done in the past. Instead, the following accessor functions return the address of each variable, which is local to the current thread if multithreaded. These point into arrays of 384, so they can be indexed by any `unsigned char' value [0,255]; by EOF (-1); or by any `signed char' value [-128,-1). ISO C requires that the ctype functions work for `unsigned char' values and for EOF; we also support negative `signed char' values for broken old programs. The case conversion arrays are of `int's rather than `unsigned char's because tolower (EOF) must be EOF, which doesn't fit into an `unsigned char'. But today more important is that the arrays are also used for multi-byte character sets. */ extern const unsigned short int **__ctype_b_loc (void) __THROW __attribute__ ((__const__)); extern const __int32_t **__ctype_tolower_loc (void) __THROW __attribute__ ((__const__)); extern const __int32_t **__ctype_toupper_loc (void) __THROW __attribute__ ((__const__)); #ifndef __cplusplus # define __isctype(c, type) \ ((*__ctype_b_loc ())[(int) (c)] & (unsigned short int) type) #elif defined __USE_EXTERN_INLINES # define __isctype_f(type) \ __extern_inline int \ is##type (int __c) __THROW \ { \ return (*__ctype_b_loc ())[(int) (__c)] & (unsigned short int) _IS##type; \ } #endif #define __isascii(c) (((c) & ~0x7f) == 0) /* If C is a 7 bit value. */ #define __toascii(c) ((c) & 0x7f) /* Mask off high bits. */ #define __exctype(name) extern int name (int) __THROW /* The following names are all functions: int isCHARACTERISTIC(int c); which return nonzero iff C has CHARACTERISTIC. For the meaning of the characteristic names, see the `enum' above. */ __exctype (isalnum); __exctype (isalpha); __exctype (iscntrl); __exctype (isdigit); __exctype (islower); __exctype (isgraph); __exctype (isprint); __exctype (ispunct); __exctype (isspace); __exctype (isupper); __exctype (isxdigit); /* Return the lowercase version of C. */ extern int tolower (int __c) __THROW; /* Return the uppercase version of C. */ extern int toupper (int __c) __THROW; /* ISO C99 introduced one new function. */ #ifdef __USE_ISOC99 __exctype (isblank); #endif #ifdef __USE_GNU /* Test C for a set of character classes according to MASK. */ extern int isctype (int __c, int __mask) __THROW; #endif #if defined __USE_MISC || defined __USE_XOPEN /* Return nonzero iff C is in the ASCII set (i.e., is no more than 7 bits wide). */ extern int isascii (int __c) __THROW; /* Return the part of C that is in the ASCII set (i.e., the low-order 7 bits of C). */ extern int toascii (int __c) __THROW; /* These are the same as `toupper' and `tolower' except that they do not check the argument for being in the range of a `char'. */ __exctype (_toupper); __exctype (_tolower); #endif /* Use X/Open or use misc. */ /* This code is needed for the optimized mapping functions. */ #define __tobody(c, f, a, args) \ (__extension__ \ ({ int __res; \ if (sizeof (c) > 1) \ { \ if (__builtin_constant_p (c)) \ { \ int __c = (c); \ __res = __c < -128 || __c > 255 ? __c : (a)[__c]; \ } \ else \ __res = f args; \ } \ else \ __res = (a)[(int) (c)]; \ __res; })) #if !defined __NO_CTYPE # ifdef __isctype_f __isctype_f (alnum) __isctype_f (alpha) __isctype_f (cntrl) __isctype_f (digit) __isctype_f (lower) __isctype_f (graph) __isctype_f (print) __isctype_f (punct) __isctype_f (space) __isctype_f (upper) __isctype_f (xdigit) # ifdef __USE_ISOC99 __isctype_f (blank) # endif # elif defined __isctype # define isalnum(c) __isctype((c), _ISalnum) # define isalpha(c) __isctype((c), _ISalpha) # define iscntrl(c) __isctype((c), _IScntrl) # define isdigit(c) __isctype((c), _ISdigit) # define islower(c) __isctype((c), _ISlower) # define isgraph(c) __isctype((c), _ISgraph) # define isprint(c) __isctype((c), _ISprint) # define ispunct(c) __isctype((c), _ISpunct) # define isspace(c) __isctype((c), _ISspace) # define isupper(c) __isctype((c), _ISupper) # define isxdigit(c) __isctype((c), _ISxdigit) # ifdef __USE_ISOC99 # define isblank(c) __isctype((c), _ISblank) # endif # endif # ifdef __USE_EXTERN_INLINES __extern_inline int __NTH (tolower (int __c)) { return __c >= -128 && __c < 256 ? (*__ctype_tolower_loc ())[__c] : __c; } __extern_inline int __NTH (toupper (int __c)) { return __c >= -128 && __c < 256 ? (*__ctype_toupper_loc ())[__c] : __c; } # endif # if __GNUC__ >= 2 && defined __OPTIMIZE__ && !defined __cplusplus # define tolower(c) __tobody (c, tolower, *__ctype_tolower_loc (), (c)) # define toupper(c) __tobody (c, toupper, *__ctype_toupper_loc (), (c)) # endif /* Optimizing gcc */ # if defined __USE_MISC || defined __USE_XOPEN # define isascii(c) __isascii (c) # define toascii(c) __toascii (c) # define _tolower(c) ((int) (*__ctype_tolower_loc ())[(int) (c)]) # define _toupper(c) ((int) (*__ctype_toupper_loc ())[(int) (c)]) # endif #endif /* Not __NO_CTYPE. */ #ifdef __USE_XOPEN2K8 /* POSIX.1-2008 extended locale interface (see locale.h). */ # include /* These definitions are similar to the ones above but all functions take as an argument a handle for the locale which shall be used. */ # define __isctype_l(c, type, locale) \ ((locale)->__ctype_b[(int) (c)] & (unsigned short int) type) # define __exctype_l(name) \ extern int name (int, locale_t) __THROW /* The following names are all functions: int isCHARACTERISTIC(int c, locale_t *locale); which return nonzero iff C has CHARACTERISTIC. For the meaning of the characteristic names, see the `enum' above. */ __exctype_l (isalnum_l); __exctype_l (isalpha_l); __exctype_l (iscntrl_l); __exctype_l (isdigit_l); __exctype_l (islower_l); __exctype_l (isgraph_l); __exctype_l (isprint_l); __exctype_l (ispunct_l); __exctype_l (isspace_l); __exctype_l (isupper_l); __exctype_l (isxdigit_l); __exctype_l (isblank_l); /* Return the lowercase version of C in locale L. */ extern int __tolower_l (int __c, locale_t __l) __THROW; extern int tolower_l (int __c, locale_t __l) __THROW; /* Return the uppercase version of C. */ extern int __toupper_l (int __c, locale_t __l) __THROW; extern int toupper_l (int __c, locale_t __l) __THROW; # if __GNUC__ >= 2 && defined __OPTIMIZE__ && !defined __cplusplus # define __tolower_l(c, locale) \ __tobody (c, __tolower_l, (locale)->__ctype_tolower, (c, locale)) # define __toupper_l(c, locale) \ __tobody (c, __toupper_l, (locale)->__ctype_toupper, (c, locale)) # define tolower_l(c, locale) __tolower_l ((c), (locale)) # define toupper_l(c, locale) __toupper_l ((c), (locale)) # endif /* Optimizing gcc */ # ifndef __NO_CTYPE # define __isalnum_l(c,l) __isctype_l((c), _ISalnum, (l)) # define __isalpha_l(c,l) __isctype_l((c), _ISalpha, (l)) # define __iscntrl_l(c,l) __isctype_l((c), _IScntrl, (l)) # define __isdigit_l(c,l) __isctype_l((c), _ISdigit, (l)) # define __islower_l(c,l) __isctype_l((c), _ISlower, (l)) # define __isgraph_l(c,l) __isctype_l((c), _ISgraph, (l)) # define __isprint_l(c,l) __isctype_l((c), _ISprint, (l)) # define __ispunct_l(c,l) __isctype_l((c), _ISpunct, (l)) # define __isspace_l(c,l) __isctype_l((c), _ISspace, (l)) # define __isupper_l(c,l) __isctype_l((c), _ISupper, (l)) # define __isxdigit_l(c,l) __isctype_l((c), _ISxdigit, (l)) # define __isblank_l(c,l) __isctype_l((c), _ISblank, (l)) # ifdef __USE_MISC # define __isascii_l(c,l) ((l), __isascii (c)) # define __toascii_l(c,l) ((l), __toascii (c)) # endif # define isalnum_l(c,l) __isalnum_l ((c), (l)) # define isalpha_l(c,l) __isalpha_l ((c), (l)) # define iscntrl_l(c,l) __iscntrl_l ((c), (l)) # define isdigit_l(c,l) __isdigit_l ((c), (l)) # define islower_l(c,l) __islower_l ((c), (l)) # define isgraph_l(c,l) __isgraph_l ((c), (l)) # define isprint_l(c,l) __isprint_l ((c), (l)) # define ispunct_l(c,l) __ispunct_l ((c), (l)) # define isspace_l(c,l) __isspace_l ((c), (l)) # define isupper_l(c,l) __isupper_l ((c), (l)) # define isxdigit_l(c,l) __isxdigit_l ((c), (l)) # define isblank_l(c,l) __isblank_l ((c), (l)) # ifdef __USE_MISC # define isascii_l(c,l) __isascii_l ((c), (l)) # define toascii_l(c,l) __toascii_l ((c), (l)) # endif # endif /* Not __NO_CTYPE. */ #endif /* Use POSIX 2008. */ __END_DECLS #endif /* ctype.h */ fpu_control.h000064400000006777151027430550007272 0ustar00/* FPU control word bits. x86 version. Copyright (C) 1993-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Olaf Flebbe. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _FPU_CONTROL_H #define _FPU_CONTROL_H 1 /* Note that this file sets on x86-64 only the x87 FPU, it does not touch the SSE unit. */ /* Here is the dirty part. Set up your 387 through the control word * (cw) register. * * 15-13 12 11-10 9-8 7-6 5 4 3 2 1 0 * | reserved | IC | RC | PC | reserved | PM | UM | OM | ZM | DM | IM * * IM: Invalid operation mask * DM: Denormalized operand mask * ZM: Zero-divide mask * OM: Overflow mask * UM: Underflow mask * PM: Precision (inexact result) mask * * Mask bit is 1 means no interrupt. * * PC: Precision control * 11 - round to extended precision * 10 - round to double precision * 00 - round to single precision * * RC: Rounding control * 00 - rounding to nearest * 01 - rounding down (toward - infinity) * 10 - rounding up (toward + infinity) * 11 - rounding toward zero * * IC: Infinity control * That is for 8087 and 80287 only. * * The hardware default is 0x037f which we use. */ #include /* masking of interrupts */ #define _FPU_MASK_IM 0x01 #define _FPU_MASK_DM 0x02 #define _FPU_MASK_ZM 0x04 #define _FPU_MASK_OM 0x08 #define _FPU_MASK_UM 0x10 #define _FPU_MASK_PM 0x20 /* precision control */ #define _FPU_EXTENDED 0x300 /* libm requires double extended precision. */ #define _FPU_DOUBLE 0x200 #define _FPU_SINGLE 0x0 /* rounding control */ #define _FPU_RC_NEAREST 0x0 /* RECOMMENDED */ #define _FPU_RC_DOWN 0x400 #define _FPU_RC_UP 0x800 #define _FPU_RC_ZERO 0xC00 #define _FPU_RESERVED 0xF0C0 /* Reserved bits in cw */ /* The fdlibm code requires strict IEEE double precision arithmetic, and no interrupts for exceptions, rounding to nearest. */ #define _FPU_DEFAULT 0x037f /* IEEE: same as above. */ #define _FPU_IEEE 0x037f /* Type of the control word. */ typedef unsigned int fpu_control_t __attribute__ ((__mode__ (__HI__))); /* Macros for accessing the hardware control word. "*&" is used to work around a bug in older versions of GCC. __volatile__ is used to support combination of writing the control register and reading it back. Without __volatile__, the old value may be used for reading back under compiler optimization. Note that the use of these macros is not sufficient anymore with recent hardware nor on x86-64. Some floating point operations are executed in the SSE/SSE2 engines which have their own control and status register. */ #define _FPU_GETCW(cw) __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw)) #define _FPU_SETCW(cw) __asm__ __volatile__ ("fldcw %0" : : "m" (*&cw)) /* Default control word set at startup. */ extern fpu_control_t __fpu_control; #endif /* fpu_control.h */ fstab.h000064400000006047151027430550006025 0ustar00/* * Copyright (c) 1980, 1993 * The Regents of the University of California. 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)fstab.h 8.1 (Berkeley) 6/2/93 */ #ifndef _FSTAB_H #define _FSTAB_H 1 #include /* * File system table, see fstab(5). * * Used by dump, mount, umount, swapon, fsck, df, ... * * For ufs fs_spec field is the block special name. Programs that want to * use the character special name must create that name by prepending a 'r' * after the right most slash. Quota files are always named "quotas", so * if type is "rq", then use concatenation of fs_file and "quotas" to locate * quota file. */ #define _PATH_FSTAB "/etc/fstab" #define FSTAB "/etc/fstab" /* deprecated */ #define FSTAB_RW "rw" /* read/write device */ #define FSTAB_RQ "rq" /* read/write with quotas */ #define FSTAB_RO "ro" /* read-only device */ #define FSTAB_SW "sw" /* swap device */ #define FSTAB_XX "xx" /* ignore totally */ struct fstab { char *fs_spec; /* block special device name */ char *fs_file; /* file system path prefix */ char *fs_vfstype; /* File system type, ufs, nfs */ char *fs_mntops; /* Mount options ala -o */ const char *fs_type; /* FSTAB_* from fs_mntops */ int fs_freq; /* dump frequency, in days */ int fs_passno; /* pass number on parallel dump */ }; __BEGIN_DECLS extern struct fstab *getfsent (void) __THROW; extern struct fstab *getfsspec (const char *__name) __THROW; extern struct fstab *getfsfile (const char *__name) __THROW; extern int setfsent (void) __THROW; extern void endfsent (void) __THROW; __END_DECLS #endif /* fstab.h */ unctrl.h000064400000006033151027430550006230 0ustar00/**************************************************************************** * Copyright (c) 1998-2008,2009 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim 1992,1995 * * and: Eric S. Raymond * ****************************************************************************/ /* * unctrl.h * * Display a printable version of a control character. * Control characters are displayed in caret notation (^x), DELETE is displayed * as ^?. Printable characters are displayed as is. */ /* $Id: unctrl.h.in,v 1.11 2009/04/18 21:00:52 tom Exp $ */ #ifndef NCURSES_UNCTRL_H_incl #define NCURSES_UNCTRL_H_incl 1 #undef NCURSES_VERSION #define NCURSES_VERSION "6.1" #ifdef __cplusplus extern "C" { #endif #include #undef unctrl NCURSES_EXPORT(NCURSES_CONST char *) unctrl (chtype); #if 1 NCURSES_EXPORT(NCURSES_CONST char *) NCURSES_SP_NAME(unctrl) (SCREEN*, chtype); #endif #ifdef __cplusplus } #endif #endif /* NCURSES_UNCTRL_H_incl */ ffi.h000064400000001054151027430550005463 0ustar00/* This file is here to prevent a file conflict on multiarch systems. */ #ifdef ffi_wrapper_h #error "Do not define ffi_wrapper_h!" #endif #define ffi_wrapper_h #if defined(__i386__) #include "ffi-i386.h" #elif defined(__powerpc64__) #include "ffi-ppc64.h" #elif defined(__powerpc__) #include "ffi-ppc.h" #elif defined(__s390x__) #include "ffi-s390x.h" #elif defined(__s390__) #include "ffi-s390.h" #elif defined(__x86_64__) #include "ffi-x86_64.h" #else #error "The libffi-devel package is not usable with the architecture." #endif #undef ffi_wrapper_h entities.h000064400000011502151027430550006542 0ustar00/* * Generated file - do not edit directly. * * This file was generated from: * http://www.w3.org/TR/REC-html40/sgml/entities.html * by means of the script: * entities.tcl */ #ifdef __cplusplus extern "C" { #endif static struct entities_s { char *name; int value; } entities[] = { {"AElig", 198}, {"Aacute", 193}, {"Acirc", 194}, {"Agrave", 192}, {"Alpha", 913}, {"Aring", 197}, {"Atilde", 195}, {"Auml", 196}, {"Beta", 914}, {"Ccedil", 199}, {"Chi", 935}, {"Dagger", 8225}, {"Delta", 916}, {"ETH", 208}, {"Eacute", 201}, {"Ecirc", 202}, {"Egrave", 200}, {"Epsilon", 917}, {"Eta", 919}, {"Euml", 203}, {"Gamma", 915}, {"Iacute", 205}, {"Icirc", 206}, {"Igrave", 204}, {"Iota", 921}, {"Iuml", 207}, {"Kappa", 922}, {"Lambda", 923}, {"Mu", 924}, {"Ntilde", 209}, {"Nu", 925}, {"OElig", 338}, {"Oacute", 211}, {"Ocirc", 212}, {"Ograve", 210}, {"Omega", 937}, {"Omicron", 927}, {"Oslash", 216}, {"Otilde", 213}, {"Ouml", 214}, {"Phi", 934}, {"Pi", 928}, {"Prime", 8243}, {"Psi", 936}, {"Rho", 929}, {"Scaron", 352}, {"Sigma", 931}, {"THORN", 222}, {"Tau", 932}, {"Theta", 920}, {"Uacute", 218}, {"Ucirc", 219}, {"Ugrave", 217}, {"Upsilon", 933}, {"Uuml", 220}, {"Xi", 926}, {"Yacute", 221}, {"Yuml", 376}, {"Zeta", 918}, {"aacute", 225}, {"acirc", 226}, {"acute", 180}, {"aelig", 230}, {"agrave", 224}, {"alefsym", 8501}, {"alpha", 945}, {"amp", 38}, {"and", 8743}, {"ang", 8736}, {"aring", 229}, {"asymp", 8776}, {"atilde", 227}, {"auml", 228}, {"bdquo", 8222}, {"beta", 946}, {"brvbar", 166}, {"bull", 8226}, {"cap", 8745}, {"ccedil", 231}, {"cedil", 184}, {"cent", 162}, {"chi", 967}, {"circ", 710}, {"clubs", 9827}, {"cong", 8773}, {"copy", 169}, {"crarr", 8629}, {"cup", 8746}, {"curren", 164}, {"dArr", 8659}, {"dagger", 8224}, {"darr", 8595}, {"deg", 176}, {"delta", 948}, {"diams", 9830}, {"divide", 247}, {"eacute", 233}, {"ecirc", 234}, {"egrave", 232}, {"empty", 8709}, {"emsp", 8195}, {"ensp", 8194}, {"epsilon", 949}, {"equiv", 8801}, {"eta", 951}, {"eth", 240}, {"euml", 235}, {"euro", 8364}, {"exist", 8707}, {"fnof", 402}, {"forall", 8704}, {"frac12", 189}, {"frac14", 188}, {"frac34", 190}, {"frasl", 8260}, {"gamma", 947}, {"ge", 8805}, {"gt", 62}, {"hArr", 8660}, {"harr", 8596}, {"hearts", 9829}, {"hellip", 8230}, {"iacute", 237}, {"icirc", 238}, {"iexcl", 161}, {"igrave", 236}, {"image", 8465}, {"infin", 8734}, {"int", 8747}, {"iota", 953}, {"iquest", 191}, {"isin", 8712}, {"iuml", 239}, {"kappa", 954}, {"lArr", 8656}, {"lambda", 955}, {"lang", 9001}, {"laquo", 171}, {"larr", 8592}, {"lceil", 8968}, {"ldquo", 8220}, {"le", 8804}, {"lfloor", 8970}, {"lowast", 8727}, {"loz", 9674}, {"lrm", 8206}, {"lsaquo", 8249}, {"lsquo", 8216}, {"lt", 60}, {"macr", 175}, {"mdash", 8212}, {"micro", 181}, {"middot", 183}, {"minus", 8722}, {"mu", 956}, {"nabla", 8711}, {"nbsp", 160}, {"ndash", 8211}, {"ne", 8800}, {"ni", 8715}, {"not", 172}, {"notin", 8713}, {"nsub", 8836}, {"ntilde", 241}, {"nu", 957}, {"oacute", 243}, {"ocirc", 244}, {"oelig", 339}, {"ograve", 242}, {"oline", 8254}, {"omega", 969}, {"omicron", 959}, {"oplus", 8853}, {"or", 8744}, {"ordf", 170}, {"ordm", 186}, {"oslash", 248}, {"otilde", 245}, {"otimes", 8855}, {"ouml", 246}, {"para", 182}, {"part", 8706}, {"permil", 8240}, {"perp", 8869}, {"phi", 966}, {"pi", 960}, {"piv", 982}, {"plusmn", 177}, {"pound", 163}, {"prime", 8242}, {"prod", 8719}, {"prop", 8733}, {"psi", 968}, {"quot", 34}, {"rArr", 8658}, {"radic", 8730}, {"rang", 9002}, {"raquo", 187}, {"rarr", 8594}, {"rceil", 8969}, {"rdquo", 8221}, {"real", 8476}, {"reg", 174}, {"rfloor", 8971}, {"rho", 961}, {"rlm", 8207}, {"rsaquo", 8250}, {"rsquo", 8217}, {"sbquo", 8218}, {"scaron", 353}, {"sdot", 8901}, {"sect", 167}, {"shy", 173}, {"sigma", 963}, {"sigmaf", 962}, {"sim", 8764}, {"spades", 9824}, {"sub", 8834}, {"sube", 8838}, {"sum", 8721}, {"sup", 8835}, {"sup1", 185}, {"sup2", 178}, {"sup3", 179}, {"supe", 8839}, {"szlig", 223}, {"tau", 964}, {"there4", 8756}, {"theta", 952}, {"thetasym", 977}, {"thinsp", 8201}, {"thorn", 254}, {"tilde", 732}, {"times", 215}, {"trade", 8482}, {"uArr", 8657}, {"uacute", 250}, {"uarr", 8593}, {"ucirc", 251}, {"ugrave", 249}, {"uml", 168}, {"upsih", 978}, {"upsilon", 965}, {"uuml", 252}, {"weierp", 8472}, {"xi", 958}, {"yacute", 253}, {"yen", 165}, {"yuml", 255}, {"zeta", 950}, {"zwj", 8205}, {"zwnj", 8204}, }; #define ENTITY_NAME_LENGTH_MAX 8 #define NR_OF_ENTITIES 252 #ifdef __cplusplus } #endif jpeglib.h000064400000141323151027430550006337 0ustar00/* * jpeglib.h * * This file was part of the Independent JPEG Group's software: * Copyright (C) 1991-1998, Thomas G. Lane. * Modified 2002-2009 by Guido Vollbeding. * libjpeg-turbo Modifications: * Copyright (C) 2009-2011, 2013-2014, 2016, D. R. Commander. * Copyright (C) 2015, Google, Inc. * For conditions of distribution and use, see the accompanying README.ijg * file. * * This file defines the application interface for the JPEG library. * Most applications using the library need only include this file, * and perhaps jerror.h if they want to know the exact error codes. */ #ifndef JPEGLIB_H #define JPEGLIB_H /* * First we include the configuration files that record how this * installation of the JPEG library is set up. jconfig.h can be * generated automatically for many systems. jmorecfg.h contains * manual configuration options that most people need not worry about. */ #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ #include "jconfig.h" /* widely used configuration options */ #endif #include "jmorecfg.h" /* seldom changed options */ #ifdef __cplusplus #ifndef DONT_USE_EXTERN_C extern "C" { #endif #endif /* Various constants determining the sizes of things. * All of these are specified by the JPEG standard, so don't change them * if you want to be compatible. */ #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */ #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU * to handle it. We even let you do this from the jconfig.h file. However, * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe * sometimes emits noncompliant files doesn't mean you should too. */ #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ #ifndef D_MAX_BLOCKS_IN_MCU #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ #endif /* Data structures for images (arrays of samples and of DCT coefficients). */ typedef JSAMPLE *JSAMPROW; /* ptr to one image row of pixel samples. */ typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ typedef JBLOCK *JBLOCKROW; /* pointer to one row of coefficient blocks */ typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ typedef JCOEF *JCOEFPTR; /* useful in a couple of places */ /* Types for JPEG compression parameters and working tables. */ /* DCT coefficient quantization tables. */ typedef struct { /* This array gives the coefficient quantizers in natural array order * (not the zigzag order in which they are stored in a JPEG DQT marker). * CAUTION: IJG versions prior to v6a kept this array in zigzag order. */ UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ /* This field is used only during compression. It's initialized FALSE when * the table is created, and set TRUE when it's been output to the file. * You could suppress output of a table by setting this to TRUE. * (See jpeg_suppress_tables for an example.) */ boolean sent_table; /* TRUE when table has been output */ } JQUANT_TBL; /* Huffman coding tables. */ typedef struct { /* These two fields directly represent the contents of a JPEG DHT marker */ UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ /* length k bits; bits[0] is unused */ UINT8 huffval[256]; /* The symbols, in order of incr code length */ /* This field is used only during compression. It's initialized FALSE when * the table is created, and set TRUE when it's been output to the file. * You could suppress output of a table by setting this to TRUE. * (See jpeg_suppress_tables for an example.) */ boolean sent_table; /* TRUE when table has been output */ } JHUFF_TBL; /* Basic info about one component (color channel). */ typedef struct { /* These values are fixed over the whole image. */ /* For compression, they must be supplied by parameter setup; */ /* for decompression, they are read from the SOF marker. */ int component_id; /* identifier for this component (0..255) */ int component_index; /* its index in SOF or cinfo->comp_info[] */ int h_samp_factor; /* horizontal sampling factor (1..4) */ int v_samp_factor; /* vertical sampling factor (1..4) */ int quant_tbl_no; /* quantization table selector (0..3) */ /* These values may vary between scans. */ /* For compression, they must be supplied by parameter setup; */ /* for decompression, they are read from the SOS marker. */ /* The decompressor output side may not use these variables. */ int dc_tbl_no; /* DC entropy table selector (0..3) */ int ac_tbl_no; /* AC entropy table selector (0..3) */ /* Remaining fields should be treated as private by applications. */ /* These values are computed during compression or decompression startup: */ /* Component's size in DCT blocks. * Any dummy blocks added to complete an MCU are not counted; therefore * these values do not depend on whether a scan is interleaved or not. */ JDIMENSION width_in_blocks; JDIMENSION height_in_blocks; /* Size of a DCT block in samples. Always DCTSIZE for compression. * For decompression this is the size of the output from one DCT block, * reflecting any scaling we choose to apply during the IDCT step. * Values from 1 to 16 are supported. * Note that different components may receive different IDCT scalings. */ #if JPEG_LIB_VERSION >= 70 int DCT_h_scaled_size; int DCT_v_scaled_size; #else int DCT_scaled_size; #endif /* The downsampled dimensions are the component's actual, unpadded number * of samples at the main buffer (preprocessing/compression interface), thus * downsampled_width = ceil(image_width * Hi/Hmax) * and similarly for height. For decompression, IDCT scaling is included, so * downsampled_width = ceil(image_width * Hi/Hmax * DCT_[h_]scaled_size/DCTSIZE) */ JDIMENSION downsampled_width; /* actual width in samples */ JDIMENSION downsampled_height; /* actual height in samples */ /* This flag is used only for decompression. In cases where some of the * components will be ignored (eg grayscale output from YCbCr image), * we can skip most computations for the unused components. */ boolean component_needed; /* do we need the value of this component? */ /* These values are computed before starting a scan of the component. */ /* The decompressor output side may not use these variables. */ int MCU_width; /* number of blocks per MCU, horizontally */ int MCU_height; /* number of blocks per MCU, vertically */ int MCU_blocks; /* MCU_width * MCU_height */ int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_[h_]scaled_size */ int last_col_width; /* # of non-dummy blocks across in last MCU */ int last_row_height; /* # of non-dummy blocks down in last MCU */ /* Saved quantization table for component; NULL if none yet saved. * See jdinput.c comments about the need for this information. * This field is currently used only for decompression. */ JQUANT_TBL *quant_table; /* Private per-component storage for DCT or IDCT subsystem. */ void *dct_table; } jpeg_component_info; /* The script for encoding a multiple-scan file is an array of these: */ typedef struct { int comps_in_scan; /* number of components encoded in this scan */ int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ int Ss, Se; /* progressive JPEG spectral selection parms */ int Ah, Al; /* progressive JPEG successive approx. parms */ } jpeg_scan_info; /* The decompressor can save APPn and COM markers in a list of these: */ typedef struct jpeg_marker_struct *jpeg_saved_marker_ptr; struct jpeg_marker_struct { jpeg_saved_marker_ptr next; /* next in list, or NULL */ UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */ unsigned int original_length; /* # bytes of data in the file */ unsigned int data_length; /* # bytes of data saved at data[] */ JOCTET *data; /* the data contained in the marker */ /* the marker length word is not counted in data_length or original_length */ }; /* Known color spaces. */ #define JCS_EXTENSIONS 1 #define JCS_ALPHA_EXTENSIONS 1 typedef enum { JCS_UNKNOWN, /* error/unspecified */ JCS_GRAYSCALE, /* monochrome */ JCS_RGB, /* red/green/blue as specified by the RGB_RED, RGB_GREEN, RGB_BLUE, and RGB_PIXELSIZE macros */ JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ JCS_CMYK, /* C/M/Y/K */ JCS_YCCK, /* Y/Cb/Cr/K */ JCS_EXT_RGB, /* red/green/blue */ JCS_EXT_RGBX, /* red/green/blue/x */ JCS_EXT_BGR, /* blue/green/red */ JCS_EXT_BGRX, /* blue/green/red/x */ JCS_EXT_XBGR, /* x/blue/green/red */ JCS_EXT_XRGB, /* x/red/green/blue */ /* When out_color_space it set to JCS_EXT_RGBX, JCS_EXT_BGRX, JCS_EXT_XBGR, or JCS_EXT_XRGB during decompression, the X byte is undefined, and in order to ensure the best performance, libjpeg-turbo can set that byte to whatever value it wishes. Use the following colorspace constants to ensure that the X byte is set to 0xFF, so that it can be interpreted as an opaque alpha channel. */ JCS_EXT_RGBA, /* red/green/blue/alpha */ JCS_EXT_BGRA, /* blue/green/red/alpha */ JCS_EXT_ABGR, /* alpha/blue/green/red */ JCS_EXT_ARGB, /* alpha/red/green/blue */ JCS_RGB565 /* 5-bit red/6-bit green/5-bit blue */ } J_COLOR_SPACE; /* DCT/IDCT algorithm options. */ typedef enum { JDCT_ISLOW, /* slow but accurate integer algorithm */ JDCT_IFAST, /* faster, less accurate integer method */ JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ } J_DCT_METHOD; #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ #define JDCT_DEFAULT JDCT_ISLOW #endif #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ #define JDCT_FASTEST JDCT_IFAST #endif /* Dithering options for decompression. */ typedef enum { JDITHER_NONE, /* no dithering */ JDITHER_ORDERED, /* simple ordered dither */ JDITHER_FS /* Floyd-Steinberg error diffusion dither */ } J_DITHER_MODE; /* Common fields between JPEG compression and decompression master structs. */ #define jpeg_common_fields \ struct jpeg_error_mgr *err; /* Error handler module */\ struct jpeg_memory_mgr *mem; /* Memory manager module */\ struct jpeg_progress_mgr *progress; /* Progress monitor, or NULL if none */\ void *client_data; /* Available for use by application */\ boolean is_decompressor; /* So common code can tell which is which */\ int global_state /* For checking call sequence validity */ /* Routines that are to be used by both halves of the library are declared * to receive a pointer to this structure. There are no actual instances of * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. */ struct jpeg_common_struct { jpeg_common_fields; /* Fields common to both master struct types */ /* Additional fields follow in an actual jpeg_compress_struct or * jpeg_decompress_struct. All three structs must agree on these * initial fields! (This would be a lot cleaner in C++.) */ }; typedef struct jpeg_common_struct *j_common_ptr; typedef struct jpeg_compress_struct *j_compress_ptr; typedef struct jpeg_decompress_struct *j_decompress_ptr; /* Master record for a compression instance */ struct jpeg_compress_struct { jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ /* Destination for compressed data */ struct jpeg_destination_mgr *dest; /* Description of source image --- these fields must be filled in by * outer application before starting compression. in_color_space must * be correct before you can even call jpeg_set_defaults(). */ JDIMENSION image_width; /* input image width */ JDIMENSION image_height; /* input image height */ int input_components; /* # of color components in input image */ J_COLOR_SPACE in_color_space; /* colorspace of input image */ double input_gamma; /* image gamma of input image */ /* Compression parameters --- these fields must be set before calling * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to * initialize everything to reasonable defaults, then changing anything * the application specifically wants to change. That way you won't get * burnt when new parameters are added. Also note that there are several * helper routines to simplify changing parameters. */ #if JPEG_LIB_VERSION >= 70 unsigned int scale_num, scale_denom; /* fraction by which to scale image */ JDIMENSION jpeg_width; /* scaled JPEG image width */ JDIMENSION jpeg_height; /* scaled JPEG image height */ /* Dimensions of actual JPEG image that will be written to file, * derived from input dimensions by scaling factors above. * These fields are computed by jpeg_start_compress(). * You can also use jpeg_calc_jpeg_dimensions() to determine these values * in advance of calling jpeg_start_compress(). */ #endif int data_precision; /* bits of precision in image data */ int num_components; /* # of color components in JPEG image */ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ jpeg_component_info *comp_info; /* comp_info[i] describes component that appears i'th in SOF */ JQUANT_TBL *quant_tbl_ptrs[NUM_QUANT_TBLS]; #if JPEG_LIB_VERSION >= 70 int q_scale_factor[NUM_QUANT_TBLS]; #endif /* ptrs to coefficient quantization tables, or NULL if not defined, * and corresponding scale factors (percentage, initialized 100). */ JHUFF_TBL *dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; JHUFF_TBL *ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; /* ptrs to Huffman coding tables, or NULL if not defined */ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ int num_scans; /* # of entries in scan_info array */ const jpeg_scan_info *scan_info; /* script for multi-scan file, or NULL */ /* The default value of scan_info is NULL, which causes a single-scan * sequential JPEG file to be emitted. To create a multi-scan file, * set num_scans and scan_info to point to an array of scan definitions. */ boolean raw_data_in; /* TRUE=caller supplies downsampled data */ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ boolean CCIR601_sampling; /* TRUE=first samples are cosited */ #if JPEG_LIB_VERSION >= 70 boolean do_fancy_downsampling; /* TRUE=apply fancy downsampling */ #endif int smoothing_factor; /* 1..100, or 0 for no input smoothing */ J_DCT_METHOD dct_method; /* DCT algorithm selector */ /* The restart interval can be specified in absolute MCUs by setting * restart_interval, or in MCU rows by setting restart_in_rows * (in which case the correct restart_interval will be figured * for each scan). */ unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ int restart_in_rows; /* if > 0, MCU rows per restart interval */ /* Parameters controlling emission of special markers. */ boolean write_JFIF_header; /* should a JFIF marker be written? */ UINT8 JFIF_major_version; /* What to write for the JFIF version number */ UINT8 JFIF_minor_version; /* These three values are not used by the JPEG code, merely copied */ /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ /* ratio is defined by X_density/Y_density even when density_unit=0. */ UINT8 density_unit; /* JFIF code for pixel size units */ UINT16 X_density; /* Horizontal pixel density */ UINT16 Y_density; /* Vertical pixel density */ boolean write_Adobe_marker; /* should an Adobe marker be written? */ /* State variable: index of next scanline to be written to * jpeg_write_scanlines(). Application may use this to control its * processing loop, e.g., "while (next_scanline < image_height)". */ JDIMENSION next_scanline; /* 0 .. image_height-1 */ /* Remaining fields are known throughout compressor, but generally * should not be touched by a surrounding application. */ /* * These fields are computed during compression startup */ boolean progressive_mode; /* TRUE if scan script uses progressive mode */ int max_h_samp_factor; /* largest h_samp_factor */ int max_v_samp_factor; /* largest v_samp_factor */ #if JPEG_LIB_VERSION >= 70 int min_DCT_h_scaled_size; /* smallest DCT_h_scaled_size of any component */ int min_DCT_v_scaled_size; /* smallest DCT_v_scaled_size of any component */ #endif JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ /* The coefficient controller receives data in units of MCU rows as defined * for fully interleaved scans (whether the JPEG file is interleaved or not). * There are v_samp_factor * DCTSIZE sample rows of each component in an * "iMCU" (interleaved MCU) row. */ /* * These fields are valid during any one scan. * They describe the components and MCUs actually appearing in the scan. */ int comps_in_scan; /* # of JPEG components in this scan */ jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN]; /* *cur_comp_info[i] describes component that appears i'th in SOS */ JDIMENSION MCUs_per_row; /* # of MCUs across the image */ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ int blocks_in_MCU; /* # of DCT blocks per MCU */ int MCU_membership[C_MAX_BLOCKS_IN_MCU]; /* MCU_membership[i] is index in cur_comp_info of component owning */ /* i'th block in an MCU */ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ #if JPEG_LIB_VERSION >= 80 int block_size; /* the basic DCT block size: 1..16 */ const int *natural_order; /* natural-order position array */ int lim_Se; /* min( Se, DCTSIZE2-1 ) */ #endif /* * Links to compression subobjects (methods and private variables of modules) */ struct jpeg_comp_master *master; struct jpeg_c_main_controller *main; struct jpeg_c_prep_controller *prep; struct jpeg_c_coef_controller *coef; struct jpeg_marker_writer *marker; struct jpeg_color_converter *cconvert; struct jpeg_downsampler *downsample; struct jpeg_forward_dct *fdct; struct jpeg_entropy_encoder *entropy; jpeg_scan_info *script_space; /* workspace for jpeg_simple_progression */ int script_space_size; }; /* Master record for a decompression instance */ struct jpeg_decompress_struct { jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ /* Source of compressed data */ struct jpeg_source_mgr *src; /* Basic description of image --- filled in by jpeg_read_header(). */ /* Application may inspect these values to decide how to process image. */ JDIMENSION image_width; /* nominal image width (from SOF marker) */ JDIMENSION image_height; /* nominal image height */ int num_components; /* # of color components in JPEG image */ J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ /* Decompression processing parameters --- these fields must be set before * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes * them to default values. */ J_COLOR_SPACE out_color_space; /* colorspace for output */ unsigned int scale_num, scale_denom; /* fraction by which to scale image */ double output_gamma; /* image gamma wanted in output */ boolean buffered_image; /* TRUE=multiple output passes */ boolean raw_data_out; /* TRUE=downsampled data wanted */ J_DCT_METHOD dct_method; /* IDCT algorithm selector */ boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ boolean quantize_colors; /* TRUE=colormapped output wanted */ /* the following are ignored if not quantize_colors: */ J_DITHER_MODE dither_mode; /* type of color dithering to use */ boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ int desired_number_of_colors; /* max # colors to use in created colormap */ /* these are significant only in buffered-image mode: */ boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ boolean enable_external_quant;/* enable future use of external colormap */ boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ /* Description of actual output image that will be returned to application. * These fields are computed by jpeg_start_decompress(). * You can also use jpeg_calc_output_dimensions() to determine these values * in advance of calling jpeg_start_decompress(). */ JDIMENSION output_width; /* scaled image width */ JDIMENSION output_height; /* scaled image height */ int out_color_components; /* # of color components in out_color_space */ int output_components; /* # of color components returned */ /* output_components is 1 (a colormap index) when quantizing colors; * otherwise it equals out_color_components. */ int rec_outbuf_height; /* min recommended height of scanline buffer */ /* If the buffer passed to jpeg_read_scanlines() is less than this many rows * high, space and time will be wasted due to unnecessary data copying. * Usually rec_outbuf_height will be 1 or 2, at most 4. */ /* When quantizing colors, the output colormap is described by these fields. * The application can supply a colormap by setting colormap non-NULL before * calling jpeg_start_decompress; otherwise a colormap is created during * jpeg_start_decompress or jpeg_start_output. * The map has out_color_components rows and actual_number_of_colors columns. */ int actual_number_of_colors; /* number of entries in use */ JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ /* State variables: these variables indicate the progress of decompression. * The application may examine these but must not modify them. */ /* Row index of next scanline to be read from jpeg_read_scanlines(). * Application may use this to control its processing loop, e.g., * "while (output_scanline < output_height)". */ JDIMENSION output_scanline; /* 0 .. output_height-1 */ /* Current input scan number and number of iMCU rows completed in scan. * These indicate the progress of the decompressor input side. */ int input_scan_number; /* Number of SOS markers seen so far */ JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ /* The "output scan number" is the notional scan being displayed by the * output side. The decompressor will not allow output scan/row number * to get ahead of input scan/row, but it can fall arbitrarily far behind. */ int output_scan_number; /* Nominal scan number being displayed */ JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ /* Current progression status. coef_bits[c][i] indicates the precision * with which component c's DCT coefficient i (in zigzag order) is known. * It is -1 when no data has yet been received, otherwise it is the point * transform (shift) value for the most recent scan of the coefficient * (thus, 0 at completion of the progression). * This pointer is NULL when reading a non-progressive file. */ int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ /* Internal JPEG parameters --- the application usually need not look at * these fields. Note that the decompressor output side may not use * any parameters that can change between scans. */ /* Quantization and Huffman tables are carried forward across input * datastreams when processing abbreviated JPEG datastreams. */ JQUANT_TBL *quant_tbl_ptrs[NUM_QUANT_TBLS]; /* ptrs to coefficient quantization tables, or NULL if not defined */ JHUFF_TBL *dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; JHUFF_TBL *ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; /* ptrs to Huffman coding tables, or NULL if not defined */ /* These parameters are never carried across datastreams, since they * are given in SOF/SOS markers or defined to be reset by SOI. */ int data_precision; /* bits of precision in image data */ jpeg_component_info *comp_info; /* comp_info[i] describes component that appears i'th in SOF */ #if JPEG_LIB_VERSION >= 80 boolean is_baseline; /* TRUE if Baseline SOF0 encountered */ #endif boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ /* These fields record data obtained from optional markers recognized by * the JPEG library. */ boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */ UINT8 JFIF_major_version; /* JFIF version number */ UINT8 JFIF_minor_version; UINT8 density_unit; /* JFIF code for pixel size units */ UINT16 X_density; /* Horizontal pixel density */ UINT16 Y_density; /* Vertical pixel density */ boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ UINT8 Adobe_transform; /* Color transform code from Adobe marker */ boolean CCIR601_sampling; /* TRUE=first samples are cosited */ /* Aside from the specific data retained from APPn markers known to the * library, the uninterpreted contents of any or all APPn and COM markers * can be saved in a list for examination by the application. */ jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */ /* Remaining fields are known throughout decompressor, but generally * should not be touched by a surrounding application. */ /* * These fields are computed during decompression startup */ int max_h_samp_factor; /* largest h_samp_factor */ int max_v_samp_factor; /* largest v_samp_factor */ #if JPEG_LIB_VERSION >= 70 int min_DCT_h_scaled_size; /* smallest DCT_h_scaled_size of any component */ int min_DCT_v_scaled_size; /* smallest DCT_v_scaled_size of any component */ #else int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ #endif JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ /* The coefficient controller's input and output progress is measured in * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows * in fully interleaved JPEG scans, but are used whether the scan is * interleaved or not. We define an iMCU row as v_samp_factor DCT block * rows of each component. Therefore, the IDCT output contains * v_samp_factor*DCT_[v_]scaled_size sample rows of a component per iMCU row. */ JSAMPLE *sample_range_limit; /* table for fast range-limiting */ /* * These fields are valid during any one scan. * They describe the components and MCUs actually appearing in the scan. * Note that the decompressor output side must not use these fields. */ int comps_in_scan; /* # of JPEG components in this scan */ jpeg_component_info *cur_comp_info[MAX_COMPS_IN_SCAN]; /* *cur_comp_info[i] describes component that appears i'th in SOS */ JDIMENSION MCUs_per_row; /* # of MCUs across the image */ JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ int blocks_in_MCU; /* # of DCT blocks per MCU */ int MCU_membership[D_MAX_BLOCKS_IN_MCU]; /* MCU_membership[i] is index in cur_comp_info of component owning */ /* i'th block in an MCU */ int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ #if JPEG_LIB_VERSION >= 80 /* These fields are derived from Se of first SOS marker. */ int block_size; /* the basic DCT block size: 1..16 */ const int *natural_order; /* natural-order position array for entropy decode */ int lim_Se; /* min( Se, DCTSIZE2-1 ) for entropy decode */ #endif /* This field is shared between entropy decoder and marker parser. * It is either zero or the code of a JPEG marker that has been * read from the data source, but has not yet been processed. */ int unread_marker; /* * Links to decompression subobjects (methods, private variables of modules) */ struct jpeg_decomp_master *master; struct jpeg_d_main_controller *main; struct jpeg_d_coef_controller *coef; struct jpeg_d_post_controller *post; struct jpeg_input_controller *inputctl; struct jpeg_marker_reader *marker; struct jpeg_entropy_decoder *entropy; struct jpeg_inverse_dct *idct; struct jpeg_upsampler *upsample; struct jpeg_color_deconverter *cconvert; struct jpeg_color_quantizer *cquantize; }; /* "Object" declarations for JPEG modules that may be supplied or called * directly by the surrounding application. * As with all objects in the JPEG library, these structs only define the * publicly visible methods and state variables of a module. Additional * private fields may exist after the public ones. */ /* Error handler object */ struct jpeg_error_mgr { /* Error exit handler: does not return to caller */ void (*error_exit) (j_common_ptr cinfo); /* Conditionally emit a trace or warning message */ void (*emit_message) (j_common_ptr cinfo, int msg_level); /* Routine that actually outputs a trace or error message */ void (*output_message) (j_common_ptr cinfo); /* Format a message string for the most recent JPEG error or message */ void (*format_message) (j_common_ptr cinfo, char *buffer); #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ /* Reset error state variables at start of a new image */ void (*reset_error_mgr) (j_common_ptr cinfo); /* The message ID code and any parameters are saved here. * A message can have one string parameter or up to 8 int parameters. */ int msg_code; #define JMSG_STR_PARM_MAX 80 union { int i[8]; char s[JMSG_STR_PARM_MAX]; } msg_parm; /* Standard state variables for error facility */ int trace_level; /* max msg_level that will be displayed */ /* For recoverable corrupt-data errors, we emit a warning message, * but keep going unless emit_message chooses to abort. emit_message * should count warnings in num_warnings. The surrounding application * can check for bad data by seeing if num_warnings is nonzero at the * end of processing. */ long num_warnings; /* number of corrupt-data warnings */ /* These fields point to the table(s) of error message strings. * An application can change the table pointer to switch to a different * message list (typically, to change the language in which errors are * reported). Some applications may wish to add additional error codes * that will be handled by the JPEG library error mechanism; the second * table pointer is used for this purpose. * * First table includes all errors generated by JPEG library itself. * Error code 0 is reserved for a "no such error string" message. */ const char * const *jpeg_message_table; /* Library errors */ int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ /* Second table can be added by application (see cjpeg/djpeg for example). * It contains strings numbered first_addon_message..last_addon_message. */ const char * const *addon_message_table; /* Non-library errors */ int first_addon_message; /* code for first string in addon table */ int last_addon_message; /* code for last string in addon table */ }; /* Progress monitor object */ struct jpeg_progress_mgr { void (*progress_monitor) (j_common_ptr cinfo); long pass_counter; /* work units completed in this pass */ long pass_limit; /* total number of work units in this pass */ int completed_passes; /* passes completed so far */ int total_passes; /* total number of passes expected */ }; /* Data destination object for compression */ struct jpeg_destination_mgr { JOCTET *next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ void (*init_destination) (j_compress_ptr cinfo); boolean (*empty_output_buffer) (j_compress_ptr cinfo); void (*term_destination) (j_compress_ptr cinfo); }; /* Data source object for decompression */ struct jpeg_source_mgr { const JOCTET *next_input_byte; /* => next byte to read from buffer */ size_t bytes_in_buffer; /* # of bytes remaining in buffer */ void (*init_source) (j_decompress_ptr cinfo); boolean (*fill_input_buffer) (j_decompress_ptr cinfo); void (*skip_input_data) (j_decompress_ptr cinfo, long num_bytes); boolean (*resync_to_restart) (j_decompress_ptr cinfo, int desired); void (*term_source) (j_decompress_ptr cinfo); }; /* Memory manager object. * Allocates "small" objects (a few K total), "large" objects (tens of K), * and "really big" objects (virtual arrays with backing store if needed). * The memory manager does not allow individual objects to be freed; rather, * each created object is assigned to a pool, and whole pools can be freed * at once. This is faster and more convenient than remembering exactly what * to free, especially where malloc()/free() are not too speedy. * NB: alloc routines never return NULL. They exit to error_exit if not * successful. */ #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ #define JPOOL_NUMPOOLS 2 typedef struct jvirt_sarray_control *jvirt_sarray_ptr; typedef struct jvirt_barray_control *jvirt_barray_ptr; struct jpeg_memory_mgr { /* Method pointers */ void *(*alloc_small) (j_common_ptr cinfo, int pool_id, size_t sizeofobject); void *(*alloc_large) (j_common_ptr cinfo, int pool_id, size_t sizeofobject); JSAMPARRAY (*alloc_sarray) (j_common_ptr cinfo, int pool_id, JDIMENSION samplesperrow, JDIMENSION numrows); JBLOCKARRAY (*alloc_barray) (j_common_ptr cinfo, int pool_id, JDIMENSION blocksperrow, JDIMENSION numrows); jvirt_sarray_ptr (*request_virt_sarray) (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION samplesperrow, JDIMENSION numrows, JDIMENSION maxaccess); jvirt_barray_ptr (*request_virt_barray) (j_common_ptr cinfo, int pool_id, boolean pre_zero, JDIMENSION blocksperrow, JDIMENSION numrows, JDIMENSION maxaccess); void (*realize_virt_arrays) (j_common_ptr cinfo); JSAMPARRAY (*access_virt_sarray) (j_common_ptr cinfo, jvirt_sarray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable); JBLOCKARRAY (*access_virt_barray) (j_common_ptr cinfo, jvirt_barray_ptr ptr, JDIMENSION start_row, JDIMENSION num_rows, boolean writable); void (*free_pool) (j_common_ptr cinfo, int pool_id); void (*self_destruct) (j_common_ptr cinfo); /* Limit on memory allocation for this JPEG object. (Note that this is * merely advisory, not a guaranteed maximum; it only affects the space * used for virtual-array buffers.) May be changed by outer application * after creating the JPEG object. */ long max_memory_to_use; /* Maximum allocation request accepted by alloc_large. */ long max_alloc_chunk; }; /* Routine signature for application-supplied marker processing methods. * Need not pass marker code since it is stored in cinfo->unread_marker. */ typedef boolean (*jpeg_marker_parser_method) (j_decompress_ptr cinfo); /* Originally, this macro was used as a way of defining function prototypes * for both modern compilers as well as older compilers that did not support * prototype parameters. libjpeg-turbo has never supported these older, * non-ANSI compilers, but the macro is still included because there is some * software out there that uses it. */ #define JPP(arglist) arglist /* Default error-management setup */ EXTERN(struct jpeg_error_mgr *) jpeg_std_error (struct jpeg_error_mgr *err); /* Initialization of JPEG compression objects. * jpeg_create_compress() and jpeg_create_decompress() are the exported * names that applications should call. These expand to calls on * jpeg_CreateCompress and jpeg_CreateDecompress with additional information * passed for version mismatch checking. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. */ #define jpeg_create_compress(cinfo) \ jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \ (size_t) sizeof(struct jpeg_compress_struct)) #define jpeg_create_decompress(cinfo) \ jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \ (size_t) sizeof(struct jpeg_decompress_struct)) EXTERN(void) jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize); EXTERN(void) jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize); /* Destruction of JPEG compression objects */ EXTERN(void) jpeg_destroy_compress (j_compress_ptr cinfo); EXTERN(void) jpeg_destroy_decompress (j_decompress_ptr cinfo); /* Standard data source and destination managers: stdio streams. */ /* Caller is responsible for opening the file before and closing after. */ EXTERN(void) jpeg_stdio_dest (j_compress_ptr cinfo, FILE *outfile); EXTERN(void) jpeg_stdio_src (j_decompress_ptr cinfo, FILE *infile); #if JPEG_LIB_VERSION >= 80 || defined(MEM_SRCDST_SUPPORTED) /* Data source and destination managers: memory buffers. */ EXTERN(void) jpeg_mem_dest (j_compress_ptr cinfo, unsigned char **outbuffer, unsigned long *outsize); EXTERN(void) jpeg_mem_src (j_decompress_ptr cinfo, const unsigned char *inbuffer, unsigned long insize); #endif /* Default parameter setup for compression */ EXTERN(void) jpeg_set_defaults (j_compress_ptr cinfo); /* Compression parameter setup aids */ EXTERN(void) jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace); EXTERN(void) jpeg_default_colorspace (j_compress_ptr cinfo); EXTERN(void) jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline); EXTERN(void) jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor, boolean force_baseline); #if JPEG_LIB_VERSION >= 70 EXTERN(void) jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline); #endif EXTERN(void) jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl, const unsigned int *basic_table, int scale_factor, boolean force_baseline); EXTERN(int) jpeg_quality_scaling (int quality); EXTERN(void) jpeg_simple_progression (j_compress_ptr cinfo); EXTERN(void) jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress); EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table (j_common_ptr cinfo); EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table (j_common_ptr cinfo); /* Main entry points for compression */ EXTERN(void) jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables); EXTERN(JDIMENSION) jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION num_lines); EXTERN(void) jpeg_finish_compress (j_compress_ptr cinfo); #if JPEG_LIB_VERSION >= 70 /* Precalculate JPEG dimensions for current compression parameters. */ EXTERN(void) jpeg_calc_jpeg_dimensions (j_compress_ptr cinfo); #endif /* Replaces jpeg_write_scanlines when writing raw downsampled data. */ EXTERN(JDIMENSION) jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data, JDIMENSION num_lines); /* Write a special marker. See libjpeg.txt concerning safe usage. */ EXTERN(void) jpeg_write_marker (j_compress_ptr cinfo, int marker, const JOCTET *dataptr, unsigned int datalen); /* Same, but piecemeal. */ EXTERN(void) jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen); EXTERN(void) jpeg_write_m_byte (j_compress_ptr cinfo, int val); /* Alternate compression function: just write an abbreviated table file */ EXTERN(void) jpeg_write_tables (j_compress_ptr cinfo); /* Decompression startup: read start of JPEG datastream to see what's there */ EXTERN(int) jpeg_read_header (j_decompress_ptr cinfo, boolean require_image); /* Return value is one of: */ #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ #define JPEG_HEADER_OK 1 /* Found valid image datastream */ #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ /* If you pass require_image = TRUE (normal case), you need not check for * a TABLES_ONLY return code; an abbreviated file will cause an error exit. * JPEG_SUSPENDED is only possible if you use a data source module that can * give a suspension return (the stdio source module doesn't). */ /* Main entry points for decompression */ EXTERN(boolean) jpeg_start_decompress (j_decompress_ptr cinfo); EXTERN(JDIMENSION) jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines); EXTERN(JDIMENSION) jpeg_skip_scanlines (j_decompress_ptr cinfo, JDIMENSION num_lines); EXTERN(void) jpeg_crop_scanline (j_decompress_ptr cinfo, JDIMENSION *xoffset, JDIMENSION *width); EXTERN(boolean) jpeg_finish_decompress (j_decompress_ptr cinfo); /* Replaces jpeg_read_scanlines when reading raw downsampled data. */ EXTERN(JDIMENSION) jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data, JDIMENSION max_lines); /* Additional entry points for buffered-image mode. */ EXTERN(boolean) jpeg_has_multiple_scans (j_decompress_ptr cinfo); EXTERN(boolean) jpeg_start_output (j_decompress_ptr cinfo, int scan_number); EXTERN(boolean) jpeg_finish_output (j_decompress_ptr cinfo); EXTERN(boolean) jpeg_input_complete (j_decompress_ptr cinfo); EXTERN(void) jpeg_new_colormap (j_decompress_ptr cinfo); EXTERN(int) jpeg_consume_input (j_decompress_ptr cinfo); /* Return value is one of: */ /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ #define JPEG_REACHED_SOS 1 /* Reached start of new scan */ #define JPEG_REACHED_EOI 2 /* Reached end of image */ #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ /* Precalculate output dimensions for current decompression parameters. */ #if JPEG_LIB_VERSION >= 80 EXTERN(void) jpeg_core_output_dimensions (j_decompress_ptr cinfo); #endif EXTERN(void) jpeg_calc_output_dimensions (j_decompress_ptr cinfo); /* Control saving of COM and APPn markers into marker_list. */ EXTERN(void) jpeg_save_markers (j_decompress_ptr cinfo, int marker_code, unsigned int length_limit); /* Install a special processing method for COM or APPn markers. */ EXTERN(void) jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code, jpeg_marker_parser_method routine); /* Read or write raw DCT coefficients --- useful for lossless transcoding. */ EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients (j_decompress_ptr cinfo); EXTERN(void) jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr *coef_arrays); EXTERN(void) jpeg_copy_critical_parameters (j_decompress_ptr srcinfo, j_compress_ptr dstinfo); /* If you choose to abort compression or decompression before completing * jpeg_finish_(de)compress, then you need to clean up to release memory, * temporary files, etc. You can just call jpeg_destroy_(de)compress * if you're done with the JPEG object, but if you want to clean it up and * reuse it, call this: */ EXTERN(void) jpeg_abort_compress (j_compress_ptr cinfo); EXTERN(void) jpeg_abort_decompress (j_decompress_ptr cinfo); /* Generic versions of jpeg_abort and jpeg_destroy that work on either * flavor of JPEG object. These may be more convenient in some places. */ EXTERN(void) jpeg_abort (j_common_ptr cinfo); EXTERN(void) jpeg_destroy (j_common_ptr cinfo); /* Default restart-marker-resync procedure for use by data source modules */ EXTERN(boolean) jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired); /* These marker codes are exported since applications and data source modules * are likely to want to use them. */ #define JPEG_RST0 0xD0 /* RST0 marker code */ #define JPEG_EOI 0xD9 /* EOI marker code */ #define JPEG_APP0 0xE0 /* APP0 marker code */ #define JPEG_COM 0xFE /* COM marker code */ /* If we have a brain-damaged compiler that emits warnings (or worse, errors) * for structure definitions that are never filled in, keep it quiet by * supplying dummy definitions for the various substructures. */ #ifdef INCOMPLETE_TYPES_BROKEN #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ struct jvirt_sarray_control { long dummy; }; struct jvirt_barray_control { long dummy; }; struct jpeg_comp_master { long dummy; }; struct jpeg_c_main_controller { long dummy; }; struct jpeg_c_prep_controller { long dummy; }; struct jpeg_c_coef_controller { long dummy; }; struct jpeg_marker_writer { long dummy; }; struct jpeg_color_converter { long dummy; }; struct jpeg_downsampler { long dummy; }; struct jpeg_forward_dct { long dummy; }; struct jpeg_entropy_encoder { long dummy; }; struct jpeg_decomp_master { long dummy; }; struct jpeg_d_main_controller { long dummy; }; struct jpeg_d_coef_controller { long dummy; }; struct jpeg_d_post_controller { long dummy; }; struct jpeg_input_controller { long dummy; }; struct jpeg_marker_reader { long dummy; }; struct jpeg_entropy_decoder { long dummy; }; struct jpeg_inverse_dct { long dummy; }; struct jpeg_upsampler { long dummy; }; struct jpeg_color_deconverter { long dummy; }; struct jpeg_color_quantizer { long dummy; }; #endif /* JPEG_INTERNALS */ #endif /* INCOMPLETE_TYPES_BROKEN */ /* * The JPEG library modules define JPEG_INTERNALS before including this file. * The internal structure declarations are read only when that is true. * Applications using the library should not include jpegint.h, but may wish * to include jerror.h. */ #ifdef JPEG_INTERNALS #include "jpegint.h" /* fetch private declarations */ #include "jerror.h" /* fetch error codes too */ #endif #ifdef __cplusplus #ifndef DONT_USE_EXTERN_C } #endif #endif #endif /* JPEGLIB_H */ libintl.h000064400000010743151027430550006361 0ustar00/* Message catalogs for internationalization. Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. This file is derived from the file libgettext.h in the GNU gettext package. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _LIBINTL_H #define _LIBINTL_H 1 #include /* We define an additional symbol to signal that we use the GNU implementation of gettext. */ #define __USE_GNU_GETTEXT 1 /* Provide information about the supported file formats. Returns the maximum minor revision number supported for a given major revision. */ #define __GNU_GETTEXT_SUPPORTED_REVISION(major) \ ((major) == 0 ? 1 : -1) __BEGIN_DECLS /* Look up MSGID in the current default message catalog for the current LC_MESSAGES locale. If not found, returns MSGID itself (the default text). */ extern char *gettext (const char *__msgid) __THROW __attribute_format_arg__ (1); /* Look up MSGID in the DOMAINNAME message catalog for the current LC_MESSAGES locale. */ extern char *dgettext (const char *__domainname, const char *__msgid) __THROW __attribute_format_arg__ (2); extern char *__dgettext (const char *__domainname, const char *__msgid) __THROW __attribute_format_arg__ (2); /* Look up MSGID in the DOMAINNAME message catalog for the current CATEGORY locale. */ extern char *dcgettext (const char *__domainname, const char *__msgid, int __category) __THROW __attribute_format_arg__ (2); extern char *__dcgettext (const char *__domainname, const char *__msgid, int __category) __THROW __attribute_format_arg__ (2); /* Similar to `gettext' but select the plural form corresponding to the number N. */ extern char *ngettext (const char *__msgid1, const char *__msgid2, unsigned long int __n) __THROW __attribute_format_arg__ (1) __attribute_format_arg__ (2); /* Similar to `dgettext' but select the plural form corresponding to the number N. */ extern char *dngettext (const char *__domainname, const char *__msgid1, const char *__msgid2, unsigned long int __n) __THROW __attribute_format_arg__ (2) __attribute_format_arg__ (3); /* Similar to `dcgettext' but select the plural form corresponding to the number N. */ extern char *dcngettext (const char *__domainname, const char *__msgid1, const char *__msgid2, unsigned long int __n, int __category) __THROW __attribute_format_arg__ (2) __attribute_format_arg__ (3); /* Set the current default message catalog to DOMAINNAME. If DOMAINNAME is null, return the current default. If DOMAINNAME is "", reset to the default of "messages". */ extern char *textdomain (const char *__domainname) __THROW; /* Specify that the DOMAINNAME message catalog will be found in DIRNAME rather than in the system locale data base. */ extern char *bindtextdomain (const char *__domainname, const char *__dirname) __THROW; /* Specify the character encoding in which the messages from the DOMAINNAME message catalog will be returned. */ extern char *bind_textdomain_codeset (const char *__domainname, const char *__codeset) __THROW; /* Optimized version of the function above. */ #if defined __OPTIMIZE__ && !defined __cplusplus /* We need NULL for `gettext'. */ # define __need_NULL # include /* We need LC_MESSAGES for `dgettext'. */ # include /* These must be macros. Inlined functions are useless because the `__builtin_constant_p' predicate in dcgettext would always return false. */ # define gettext(msgid) dgettext (NULL, msgid) # define dgettext(domainname, msgid) \ dcgettext (domainname, msgid, LC_MESSAGES) # define ngettext(msgid1, msgid2, n) dngettext (NULL, msgid1, msgid2, n) # define dngettext(domainname, msgid1, msgid2, n) \ dcngettext (domainname, msgid1, msgid2, n, LC_MESSAGES) #endif /* Optimizing. */ __END_DECLS #endif /* libintl.h */ netrose/rose.h000064400000006157151027430550007357 0ustar00/* Definitions for Rose packet radio address family. Copyright (C) 1998-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* What follows is copied from the 2.1.93 . */ #ifndef _NETROSE_ROSE_H #define _NETROSE_ROSE_H 1 #include #include /* Socket level values. */ #define SOL_ROSE 260 /* These are the public elements of the Linux kernel Rose implementation. For kernel AX.25 see the file ax25.h. This file requires ax25.h for the definition of the ax25_address structure. */ #define ROSE_MTU 251 #define ROSE_MAX_DIGIS 6 #define ROSE_DEFER 1 #define ROSE_T1 2 #define ROSE_T2 3 #define ROSE_T3 4 #define ROSE_IDLE 5 #define ROSE_QBITINCL 6 #define ROSE_HOLDBACK 7 #define SIOCRSGCAUSE (SIOCPROTOPRIVATE + 0) #define SIOCRSSCAUSE (SIOCPROTOPRIVATE + 1) #define SIOCRSL2CALL (SIOCPROTOPRIVATE + 2) #define SIOCRSSL2CALL (SIOCPROTOPRIVATE + 2) #define SIOCRSACCEPT (SIOCPROTOPRIVATE + 3) #define SIOCRSCLRRT (SIOCPROTOPRIVATE + 4) #define SIOCRSGL2CALL (SIOCPROTOPRIVATE + 5) #define SIOCRSGFACILITIES (SIOCPROTOPRIVATE + 6) #define ROSE_DTE_ORIGINATED 0x00 #define ROSE_NUMBER_BUSY 0x01 #define ROSE_INVALID_FACILITY 0x03 #define ROSE_NETWORK_CONGESTION 0x05 #define ROSE_OUT_OF_ORDER 0x09 #define ROSE_ACCESS_BARRED 0x0B #define ROSE_NOT_OBTAINABLE 0x0D #define ROSE_REMOTE_PROCEDURE 0x11 #define ROSE_LOCAL_PROCEDURE 0x13 #define ROSE_SHIP_ABSENT 0x39 typedef struct { char rose_addr[5]; } rose_address; struct sockaddr_rose { sa_family_t srose_family; rose_address srose_addr; ax25_address srose_call; int srose_ndigis; ax25_address srose_digi; }; struct full_sockaddr_rose { sa_family_t srose_family; rose_address srose_addr; ax25_address srose_call; unsigned int srose_ndigis; ax25_address srose_digis[ROSE_MAX_DIGIS]; }; struct rose_route_struct { rose_address address; unsigned short int mask; ax25_address neighbour; char device[16]; unsigned char ndigis; ax25_address digipeaters[AX25_MAX_DIGIS]; }; struct rose_cause_struct { unsigned char cause; unsigned char diagnostic; }; struct rose_facilities_struct { rose_address source_addr, dest_addr; ax25_address source_call, dest_call; unsigned char source_ndigis, dest_ndigis; ax25_address source_digis[ROSE_MAX_DIGIS]; ax25_address dest_digis[ROSE_MAX_DIGIS]; unsigned int rand; rose_address fail_addr; ax25_address fail_call; }; #endif /* netrose/rose.h */ form.h000064400000044251151027430550005670 0ustar00/**************************************************************************** * Copyright (c) 1998-2016,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1995,1997 * ****************************************************************************/ /* $Id: form.h,v 0.27 2017/02/11 16:35:42 tom Exp $ */ #ifndef FORM_H #define FORM_H /* *INDENT-OFF*/ #include #include #ifdef __cplusplus extern "C" { #endif #ifndef FORM_PRIV_H typedef void *FIELD_CELL; #endif #ifndef NCURSES_FIELD_INTERNALS #define NCURSES_FIELD_INTERNALS /* nothing */ #endif typedef int Form_Options; typedef int Field_Options; /********** * _PAGE * **********/ typedef struct pagenode #if !NCURSES_OPAQUE_FORM { short pmin; /* index of first field on page */ short pmax; /* index of last field on page */ short smin; /* index of top leftmost field on page */ short smax; /* index of bottom rightmost field on page */ } #endif /* !NCURSES_OPAQUE_FORM */ _PAGE; /********** * FIELD * **********/ typedef struct fieldnode #if 1 /* not yet: !NCURSES_OPAQUE_FORM */ { unsigned short status; /* flags */ short rows; /* size in rows */ short cols; /* size in cols */ short frow; /* first row */ short fcol; /* first col */ int drows; /* dynamic rows */ int dcols; /* dynamic cols */ int maxgrow; /* maximum field growth */ int nrow; /* off-screen rows */ short nbuf; /* additional buffers */ short just; /* justification */ short page; /* page on form */ short index; /* into form -> field */ int pad; /* pad character */ chtype fore; /* foreground attribute */ chtype back; /* background attribute */ Field_Options opts; /* options */ struct fieldnode * snext; /* sorted order pointer */ struct fieldnode * sprev; /* sorted order pointer */ struct fieldnode * link; /* linked field chain */ struct formnode * form; /* containing form */ struct typenode * type; /* field type */ void * arg; /* argument for type */ FIELD_CELL * buf; /* field buffers */ void * usrptr; /* user pointer */ /* * The wide-character configuration requires extra information. Because * there are existing applications that manipulate the members of FIELD * directly, we cannot make the struct opaque, except by changing the ABI. * Offsets of members up to this point are the same in the narrow- and * wide-character configuration. But note that the type of buf depends on * the configuration, and is made opaque for that reason. */ NCURSES_FIELD_INTERNALS } #endif /* NCURSES_OPAQUE_FORM */ FIELD; /********* * FORM * *********/ typedef struct formnode #if 1 /* not yet: !NCURSES_OPAQUE_FORM */ { unsigned short status; /* flags */ short rows; /* size in rows */ short cols; /* size in cols */ int currow; /* current row in field window */ int curcol; /* current col in field window */ int toprow; /* in scrollable field window */ int begincol; /* in horiz. scrollable field */ short maxfield; /* number of fields */ short maxpage; /* number of pages */ short curpage; /* index into page */ Form_Options opts; /* options */ WINDOW * win; /* window */ WINDOW * sub; /* subwindow */ WINDOW * w; /* window for current field */ FIELD ** field; /* field [maxfield] */ FIELD * current; /* current field */ _PAGE * page; /* page [maxpage] */ void * usrptr; /* user pointer */ void (*forminit)(struct formnode *); void (*formterm)(struct formnode *); void (*fieldinit)(struct formnode *); void (*fieldterm)(struct formnode *); } #endif /* !NCURSES_OPAQUE_FORM */ FORM; /************** * FIELDTYPE * **************/ typedef struct typenode #if !NCURSES_OPAQUE_FORM { unsigned short status; /* flags */ long ref; /* reference count */ struct typenode * left; /* ptr to operand for | */ struct typenode * right; /* ptr to operand for | */ void* (*makearg)(va_list *); /* make fieldtype arg */ void* (*copyarg)(const void *); /* copy fieldtype arg */ void (*freearg)(void *); /* free fieldtype arg */ #if NCURSES_INTEROP_FUNCS union { bool (*ofcheck)(FIELD *,const void *); /* field validation */ bool (*gfcheck)(FORM*,FIELD *,const void*); /* generic field validation */ } fieldcheck; union { bool (*occheck)(int,const void *); /* character validation */ bool (*gccheck)(int,FORM*, FIELD*,const void*); /* generic char validation */ } charcheck; union { bool (*onext)(FIELD *,const void *); /* enumerate next value */ bool (*gnext)(FORM*,FIELD*,const void*); /* generic enumerate next */ } enum_next; union { bool (*oprev)(FIELD *,const void *); /* enumerate prev value */ bool (*gprev)(FORM*,FIELD*,const void*); /* generic enumerate prev */ } enum_prev; void* (*genericarg)(void*); /* Alternate Arg method */ #else bool (*fcheck)(FIELD *,const void *); /* field validation */ bool (*ccheck)(int,const void *); /* character validation */ bool (*next)(FIELD *,const void *); /* enumerate next value */ bool (*prev)(FIELD *,const void *); /* enumerate prev value */ #endif } #endif /* !NCURSES_OPAQUE_FORM */ FIELDTYPE; typedef void (*Form_Hook)(FORM *); /*************************** * miscellaneous #defines * ***************************/ /* field justification */ #define NO_JUSTIFICATION (0) #define JUSTIFY_LEFT (1) #define JUSTIFY_CENTER (2) #define JUSTIFY_RIGHT (3) /* field options */ #define O_VISIBLE (0x0001U) #define O_ACTIVE (0x0002U) #define O_PUBLIC (0x0004U) #define O_EDIT (0x0008U) #define O_WRAP (0x0010U) #define O_BLANK (0x0020U) #define O_AUTOSKIP (0x0040U) #define O_NULLOK (0x0080U) #define O_PASSOK (0x0100U) #define O_STATIC (0x0200U) #define O_DYNAMIC_JUSTIFY (0x0400U) /* ncurses extension */ #define O_NO_LEFT_STRIP (0x0800U) /* ncurses extension */ /* form options */ #define O_NL_OVERLOAD (0x0001U) #define O_BS_OVERLOAD (0x0002U) /* form driver commands */ #define REQ_NEXT_PAGE (KEY_MAX + 1) /* move to next page */ #define REQ_PREV_PAGE (KEY_MAX + 2) /* move to previous page */ #define REQ_FIRST_PAGE (KEY_MAX + 3) /* move to first page */ #define REQ_LAST_PAGE (KEY_MAX + 4) /* move to last page */ #define REQ_NEXT_FIELD (KEY_MAX + 5) /* move to next field */ #define REQ_PREV_FIELD (KEY_MAX + 6) /* move to previous field */ #define REQ_FIRST_FIELD (KEY_MAX + 7) /* move to first field */ #define REQ_LAST_FIELD (KEY_MAX + 8) /* move to last field */ #define REQ_SNEXT_FIELD (KEY_MAX + 9) /* move to sorted next field */ #define REQ_SPREV_FIELD (KEY_MAX + 10) /* move to sorted prev field */ #define REQ_SFIRST_FIELD (KEY_MAX + 11) /* move to sorted first field */ #define REQ_SLAST_FIELD (KEY_MAX + 12) /* move to sorted last field */ #define REQ_LEFT_FIELD (KEY_MAX + 13) /* move to left to field */ #define REQ_RIGHT_FIELD (KEY_MAX + 14) /* move to right to field */ #define REQ_UP_FIELD (KEY_MAX + 15) /* move to up to field */ #define REQ_DOWN_FIELD (KEY_MAX + 16) /* move to down to field */ #define REQ_NEXT_CHAR (KEY_MAX + 17) /* move to next char in field */ #define REQ_PREV_CHAR (KEY_MAX + 18) /* move to prev char in field */ #define REQ_NEXT_LINE (KEY_MAX + 19) /* move to next line in field */ #define REQ_PREV_LINE (KEY_MAX + 20) /* move to prev line in field */ #define REQ_NEXT_WORD (KEY_MAX + 21) /* move to next word in field */ #define REQ_PREV_WORD (KEY_MAX + 22) /* move to prev word in field */ #define REQ_BEG_FIELD (KEY_MAX + 23) /* move to first char in field */ #define REQ_END_FIELD (KEY_MAX + 24) /* move after last char in fld */ #define REQ_BEG_LINE (KEY_MAX + 25) /* move to beginning of line */ #define REQ_END_LINE (KEY_MAX + 26) /* move after last char in line */ #define REQ_LEFT_CHAR (KEY_MAX + 27) /* move left in field */ #define REQ_RIGHT_CHAR (KEY_MAX + 28) /* move right in field */ #define REQ_UP_CHAR (KEY_MAX + 29) /* move up in field */ #define REQ_DOWN_CHAR (KEY_MAX + 30) /* move down in field */ #define REQ_NEW_LINE (KEY_MAX + 31) /* insert/overlay new line */ #define REQ_INS_CHAR (KEY_MAX + 32) /* insert blank char at cursor */ #define REQ_INS_LINE (KEY_MAX + 33) /* insert blank line at cursor */ #define REQ_DEL_CHAR (KEY_MAX + 34) /* delete char at cursor */ #define REQ_DEL_PREV (KEY_MAX + 35) /* delete char before cursor */ #define REQ_DEL_LINE (KEY_MAX + 36) /* delete line at cursor */ #define REQ_DEL_WORD (KEY_MAX + 37) /* delete word at cursor */ #define REQ_CLR_EOL (KEY_MAX + 38) /* clear to end of line */ #define REQ_CLR_EOF (KEY_MAX + 39) /* clear to end of field */ #define REQ_CLR_FIELD (KEY_MAX + 40) /* clear entire field */ #define REQ_OVL_MODE (KEY_MAX + 41) /* begin overlay mode */ #define REQ_INS_MODE (KEY_MAX + 42) /* begin insert mode */ #define REQ_SCR_FLINE (KEY_MAX + 43) /* scroll field forward a line */ #define REQ_SCR_BLINE (KEY_MAX + 44) /* scroll field backward a line */ #define REQ_SCR_FPAGE (KEY_MAX + 45) /* scroll field forward a page */ #define REQ_SCR_BPAGE (KEY_MAX + 46) /* scroll field backward a page */ #define REQ_SCR_FHPAGE (KEY_MAX + 47) /* scroll field forward half page */ #define REQ_SCR_BHPAGE (KEY_MAX + 48) /* scroll field backward half page */ #define REQ_SCR_FCHAR (KEY_MAX + 49) /* horizontal scroll char */ #define REQ_SCR_BCHAR (KEY_MAX + 50) /* horizontal scroll char */ #define REQ_SCR_HFLINE (KEY_MAX + 51) /* horizontal scroll line */ #define REQ_SCR_HBLINE (KEY_MAX + 52) /* horizontal scroll line */ #define REQ_SCR_HFHALF (KEY_MAX + 53) /* horizontal scroll half line */ #define REQ_SCR_HBHALF (KEY_MAX + 54) /* horizontal scroll half line */ #define REQ_VALIDATION (KEY_MAX + 55) /* validate field */ #define REQ_NEXT_CHOICE (KEY_MAX + 56) /* display next field choice */ #define REQ_PREV_CHOICE (KEY_MAX + 57) /* display prev field choice */ #define MIN_FORM_COMMAND (KEY_MAX + 1) /* used by form_driver */ #define MAX_FORM_COMMAND (KEY_MAX + 57) /* used by form_driver */ #if defined(MAX_COMMAND) # if (MAX_FORM_COMMAND > MAX_COMMAND) # error Something is wrong -- MAX_FORM_COMMAND is greater than MAX_COMMAND # elif (MAX_COMMAND != (KEY_MAX + 128)) # error Something is wrong -- MAX_COMMAND is already inconsistently defined. # endif #else # define MAX_COMMAND (KEY_MAX + 128) #endif /************************* * standard field types * *************************/ extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_ALPHA; extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_ALNUM; extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_ENUM; extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_INTEGER; extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_NUMERIC; extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_REGEXP; /************************************ * built-in additional field types * * They are not defined in SVr4 * ************************************/ extern NCURSES_EXPORT_VAR(FIELDTYPE *) TYPE_IPV4; /* Internet IP Version 4 address */ /*********************** * FIELDTYPE routines * ***********************/ extern NCURSES_EXPORT(FIELDTYPE *) new_fieldtype ( bool (* const field_check)(FIELD *,const void *), bool (* const char_check)(int,const void *)); extern NCURSES_EXPORT(FIELDTYPE *) link_fieldtype( FIELDTYPE *, FIELDTYPE *); extern NCURSES_EXPORT(int) free_fieldtype (FIELDTYPE *); extern NCURSES_EXPORT(int) set_fieldtype_arg (FIELDTYPE *, void * (* const make_arg)(va_list *), void * (* const copy_arg)(const void *), void (* const free_arg)(void *)); extern NCURSES_EXPORT(int) set_fieldtype_choice (FIELDTYPE *, bool (* const next_choice)(FIELD *,const void *), bool (* const prev_choice)(FIELD *,const void *)); /******************* * FIELD routines * *******************/ extern NCURSES_EXPORT(FIELD *) new_field (int,int,int,int,int,int); extern NCURSES_EXPORT(FIELD *) dup_field (FIELD *,int,int); extern NCURSES_EXPORT(FIELD *) link_field (FIELD *,int,int); extern NCURSES_EXPORT(int) free_field (FIELD *); extern NCURSES_EXPORT(int) field_info (const FIELD *,int *,int *,int *,int *,int *,int *); extern NCURSES_EXPORT(int) dynamic_field_info (const FIELD *,int *,int *,int *); extern NCURSES_EXPORT(int) set_max_field ( FIELD *,int); extern NCURSES_EXPORT(int) move_field (FIELD *,int,int); extern NCURSES_EXPORT(int) set_field_type (FIELD *,FIELDTYPE *,...); extern NCURSES_EXPORT(int) set_new_page (FIELD *,bool); extern NCURSES_EXPORT(int) set_field_just (FIELD *,int); extern NCURSES_EXPORT(int) field_just (const FIELD *); extern NCURSES_EXPORT(int) set_field_fore (FIELD *,chtype); extern NCURSES_EXPORT(int) set_field_back (FIELD *,chtype); extern NCURSES_EXPORT(int) set_field_pad (FIELD *,int); extern NCURSES_EXPORT(int) field_pad (const FIELD *); extern NCURSES_EXPORT(int) set_field_buffer (FIELD *,int,const char *); extern NCURSES_EXPORT(int) set_field_status (FIELD *,bool); extern NCURSES_EXPORT(int) set_field_userptr (FIELD *, void *); extern NCURSES_EXPORT(int) set_field_opts (FIELD *,Field_Options); extern NCURSES_EXPORT(int) field_opts_on (FIELD *,Field_Options); extern NCURSES_EXPORT(int) field_opts_off (FIELD *,Field_Options); extern NCURSES_EXPORT(chtype) field_fore (const FIELD *); extern NCURSES_EXPORT(chtype) field_back (const FIELD *); extern NCURSES_EXPORT(bool) new_page (const FIELD *); extern NCURSES_EXPORT(bool) field_status (const FIELD *); extern NCURSES_EXPORT(void *) field_arg (const FIELD *); extern NCURSES_EXPORT(void *) field_userptr (const FIELD *); extern NCURSES_EXPORT(FIELDTYPE *) field_type (const FIELD *); extern NCURSES_EXPORT(char *) field_buffer (const FIELD *,int); extern NCURSES_EXPORT(Field_Options) field_opts (const FIELD *); /****************** * FORM routines * ******************/ extern NCURSES_EXPORT(FORM *) new_form (FIELD **); extern NCURSES_EXPORT(FIELD **) form_fields (const FORM *); extern NCURSES_EXPORT(FIELD *) current_field (const FORM *); extern NCURSES_EXPORT(WINDOW *) form_win (const FORM *); extern NCURSES_EXPORT(WINDOW *) form_sub (const FORM *); extern NCURSES_EXPORT(Form_Hook) form_init (const FORM *); extern NCURSES_EXPORT(Form_Hook) form_term (const FORM *); extern NCURSES_EXPORT(Form_Hook) field_init (const FORM *); extern NCURSES_EXPORT(Form_Hook) field_term (const FORM *); extern NCURSES_EXPORT(int) free_form (FORM *); extern NCURSES_EXPORT(int) set_form_fields (FORM *,FIELD **); extern NCURSES_EXPORT(int) field_count (const FORM *); extern NCURSES_EXPORT(int) set_form_win (FORM *,WINDOW *); extern NCURSES_EXPORT(int) set_form_sub (FORM *,WINDOW *); extern NCURSES_EXPORT(int) set_current_field (FORM *,FIELD *); extern NCURSES_EXPORT(int) unfocus_current_field (FORM *); extern NCURSES_EXPORT(int) field_index (const FIELD *); extern NCURSES_EXPORT(int) set_form_page (FORM *,int); extern NCURSES_EXPORT(int) form_page (const FORM *); extern NCURSES_EXPORT(int) scale_form (const FORM *,int *,int *); extern NCURSES_EXPORT(int) set_form_init (FORM *,Form_Hook); extern NCURSES_EXPORT(int) set_form_term (FORM *,Form_Hook); extern NCURSES_EXPORT(int) set_field_init (FORM *,Form_Hook); extern NCURSES_EXPORT(int) set_field_term (FORM *,Form_Hook); extern NCURSES_EXPORT(int) post_form (FORM *); extern NCURSES_EXPORT(int) unpost_form (FORM *); extern NCURSES_EXPORT(int) pos_form_cursor (FORM *); extern NCURSES_EXPORT(int) form_driver (FORM *,int); # if NCURSES_WIDECHAR extern NCURSES_EXPORT(int) form_driver_w (FORM *,int,wchar_t); # endif extern NCURSES_EXPORT(int) set_form_userptr (FORM *,void *); extern NCURSES_EXPORT(int) set_form_opts (FORM *,Form_Options); extern NCURSES_EXPORT(int) form_opts_on (FORM *,Form_Options); extern NCURSES_EXPORT(int) form_opts_off (FORM *,Form_Options); extern NCURSES_EXPORT(int) form_request_by_name (const char *); extern NCURSES_EXPORT(const char *) form_request_name (int); extern NCURSES_EXPORT(void *) form_userptr (const FORM *); extern NCURSES_EXPORT(Form_Options) form_opts (const FORM *); extern NCURSES_EXPORT(bool) data_ahead (const FORM *); extern NCURSES_EXPORT(bool) data_behind (const FORM *); #if NCURSES_SP_FUNCS extern NCURSES_EXPORT(FORM *) NCURSES_SP_NAME(new_form) (SCREEN*, FIELD **); #endif #ifdef __cplusplus } #endif /* *INDENT-ON*/ #endif /* FORM_H */ sys/klog.h000064400000002263151027430550006474 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_KLOG_H #define _SYS_KLOG_H 1 #include __BEGIN_DECLS /* Control the kernel's logging facility. This corresponds exactly to the kernel's syslog system call, but that name is easily confused with the user-level syslog facility, which is something completely different. */ extern int klogctl (int __type, char *__bufp, int __len) __THROW; __END_DECLS #endif /* _SYS_KLOG_H */ sys/raw.h000064400000002235151027430550006330 0ustar00/* Copyright (C) 1999-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_RAW_H #define _SYS_RAW_H 1 #include #include /* The major device number for raw devices. */ #define RAW_MAJOR 162 /* `ioctl' commands for raw devices. */ #define RAW_SETBIND _IO(0xac, 0) #define RAW_GETBIND _IO(0xac, 1) struct raw_config_request { int raw_minor; uint64_t block_major; uint64_t block_minor; }; #endif /* sys/raw.h */ sys/ioctl.h000064400000003313151027430550006647 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_IOCTL_H #define _SYS_IOCTL_H 1 #include __BEGIN_DECLS /* Get the list of `ioctl' requests and related constants. */ #include /* Define some types used by `ioctl' requests. */ #include /* On a Unix system, the system probably defines some of the symbols we define in (usually with the same values). The code to generate has omitted these symbols to avoid the conflict, but a Unix program expects to define them, so we must include here. */ #include /* Perform the I/O control operation specified by REQUEST on FD. One argument may follow; its presence and type depend on REQUEST. Return value depends on REQUEST. Usually -1 indicates error. */ extern int ioctl (int __fd, unsigned long int __request, ...) __THROW; __END_DECLS #endif /* sys/ioctl.h */ sys/signalfd.h000064400000003077151027430550007333 0ustar00/* Copyright (C) 2007-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SIGNALFD_H #define _SYS_SIGNALFD_H 1 #include #include /* Get the platform-dependent flags. */ #include struct signalfd_siginfo { uint32_t ssi_signo; int32_t ssi_errno; int32_t ssi_code; uint32_t ssi_pid; uint32_t ssi_uid; int32_t ssi_fd; uint32_t ssi_tid; uint32_t ssi_band; uint32_t ssi_overrun; uint32_t ssi_trapno; int32_t ssi_status; int32_t ssi_int; uint64_t ssi_ptr; uint64_t ssi_utime; uint64_t ssi_stime; uint64_t ssi_addr; uint8_t __pad[48]; }; __BEGIN_DECLS /* Request notification for delivery of signals in MASK to be performed using descriptor FD.*/ extern int signalfd (int __fd, const sigset_t *__mask, int __flags) __THROW __nonnull ((2)); __END_DECLS #endif /* sys/signalfd.h */ sys/ttychars.h000064400000004703151027430550007402 0ustar00/*- * Copyright (c) 1982, 1986, 1990, 1993 * The Regents of the University of California. 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)ttychars.h 8.2 (Berkeley) 1/4/94 */ /* * 4.3 COMPATIBILITY FILE * * User visible structures and constants related to terminal handling. */ #ifndef _SYS_TTYCHARS_H #define _SYS_TTYCHARS_H 1 struct ttychars { char tc_erase; /* erase last character */ char tc_kill; /* erase entire line */ char tc_intrc; /* interrupt */ char tc_quitc; /* quit */ char tc_startc; /* start output */ char tc_stopc; /* stop output */ char tc_eofc; /* end-of-file */ char tc_brkc; /* input delimiter (like nl) */ char tc_suspc; /* stop process signal */ char tc_dsuspc; /* delayed stop process signal */ char tc_rprntc; /* reprint line */ char tc_flushc; /* flush output (toggles) */ char tc_werasc; /* word erase */ char tc_lnextc; /* literal next character */ }; #ifdef __USE_OLD_TTY #include /* to pick up character defaults */ #endif #endif /* sys/ttychars.h */ sys/dir.h000064400000001631151027430550006314 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_DIR_H #define _SYS_DIR_H 1 #include #include #define direct dirent #endif /* sys/dir.h */ sys/random.h000064400000002643151027430550007022 0ustar00/* Interfaces for obtaining random bytes. Copyright (C) 2016-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_RANDOM_H #define _SYS_RANDOM_H 1 #include #include /* Flags for use with getrandom. */ #define GRND_NONBLOCK 0x01 #define GRND_RANDOM 0x02 __BEGIN_DECLS /* Write LENGTH bytes of randomness starting at BUFFER. Return the number of bytes written, or -1 on error. */ ssize_t getrandom (void *__buffer, size_t __length, unsigned int __flags) __wur; /* Write LENGTH bytes of randomness starting at BUFFER. Return 0 on success or -1 on error. */ int getentropy (void *__buffer, size_t __length) __wur; __END_DECLS #endif /* _SYS_RANDOM_H */ sys/user.h000064400000012127151027430550006516 0ustar00/* Copyright (C) 2001-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_USER_H #define _SYS_USER_H 1 /* The whole purpose of this file is for GDB and GDB only. Don't read too much into it. Don't use it for anything other than GDB unless you know what you are doing. */ #ifdef __x86_64__ struct user_fpregs_struct { unsigned short int cwd; unsigned short int swd; unsigned short int ftw; unsigned short int fop; __extension__ unsigned long long int rip; __extension__ unsigned long long int rdp; unsigned int mxcsr; unsigned int mxcr_mask; unsigned int st_space[32]; /* 8*16 bytes for each FP-reg = 128 bytes */ unsigned int xmm_space[64]; /* 16*16 bytes for each XMM-reg = 256 bytes */ unsigned int padding[24]; }; struct user_regs_struct { __extension__ unsigned long long int r15; __extension__ unsigned long long int r14; __extension__ unsigned long long int r13; __extension__ unsigned long long int r12; __extension__ unsigned long long int rbp; __extension__ unsigned long long int rbx; __extension__ unsigned long long int r11; __extension__ unsigned long long int r10; __extension__ unsigned long long int r9; __extension__ unsigned long long int r8; __extension__ unsigned long long int rax; __extension__ unsigned long long int rcx; __extension__ unsigned long long int rdx; __extension__ unsigned long long int rsi; __extension__ unsigned long long int rdi; __extension__ unsigned long long int orig_rax; __extension__ unsigned long long int rip; __extension__ unsigned long long int cs; __extension__ unsigned long long int eflags; __extension__ unsigned long long int rsp; __extension__ unsigned long long int ss; __extension__ unsigned long long int fs_base; __extension__ unsigned long long int gs_base; __extension__ unsigned long long int ds; __extension__ unsigned long long int es; __extension__ unsigned long long int fs; __extension__ unsigned long long int gs; }; struct user { struct user_regs_struct regs; int u_fpvalid; struct user_fpregs_struct i387; __extension__ unsigned long long int u_tsize; __extension__ unsigned long long int u_dsize; __extension__ unsigned long long int u_ssize; __extension__ unsigned long long int start_code; __extension__ unsigned long long int start_stack; __extension__ long long int signal; int reserved; __extension__ union { struct user_regs_struct* u_ar0; __extension__ unsigned long long int __u_ar0_word; }; __extension__ union { struct user_fpregs_struct* u_fpstate; __extension__ unsigned long long int __u_fpstate_word; }; __extension__ unsigned long long int magic; char u_comm [32]; __extension__ unsigned long long int u_debugreg [8]; }; #else /* These are the 32-bit x86 structures. */ struct user_fpregs_struct { long int cwd; long int swd; long int twd; long int fip; long int fcs; long int foo; long int fos; long int st_space [20]; }; struct user_fpxregs_struct { unsigned short int cwd; unsigned short int swd; unsigned short int twd; unsigned short int fop; long int fip; long int fcs; long int foo; long int fos; long int mxcsr; long int reserved; long int st_space[32]; /* 8*16 bytes for each FP-reg = 128 bytes */ long int xmm_space[32]; /* 8*16 bytes for each XMM-reg = 128 bytes */ long int padding[56]; }; struct user_regs_struct { long int ebx; long int ecx; long int edx; long int esi; long int edi; long int ebp; long int eax; long int xds; long int xes; long int xfs; long int xgs; long int orig_eax; long int eip; long int xcs; long int eflags; long int esp; long int xss; }; struct user { struct user_regs_struct regs; int u_fpvalid; struct user_fpregs_struct i387; unsigned long int u_tsize; unsigned long int u_dsize; unsigned long int u_ssize; unsigned long int start_code; unsigned long int start_stack; long int signal; int reserved; struct user_regs_struct* u_ar0; struct user_fpregs_struct* u_fpstate; unsigned long int magic; char u_comm [32]; int u_debugreg [8]; }; #endif /* __x86_64__ */ #define PAGE_SHIFT 12 #define PAGE_SIZE (1UL << PAGE_SHIFT) #define PAGE_MASK (~(PAGE_SIZE-1)) #define NBPG PAGE_SIZE #define UPAGES 1 #define HOST_TEXT_START_ADDR (u.start_code) #define HOST_STACK_END_ADDR (u.start_stack + u.u_ssize * NBPG) #endif /* _SYS_USER_H */ sys/acct.h000064400000006340151027430550006452 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_ACCT_H #define _SYS_ACCT_H 1 #include #include #include #include __BEGIN_DECLS #define ACCT_COMM 16 /* comp_t is a 16-bit "floating" point number with a 3-bit base 8 exponent and a 13-bit fraction. See linux/kernel/acct.c for the specific encoding system used. */ typedef uint16_t comp_t; struct acct { char ac_flag; /* Flags. */ uint16_t ac_uid; /* Real user ID. */ uint16_t ac_gid; /* Real group ID. */ uint16_t ac_tty; /* Controlling terminal. */ uint32_t ac_btime; /* Beginning time. */ comp_t ac_utime; /* User time. */ comp_t ac_stime; /* System time. */ comp_t ac_etime; /* Elapsed time. */ comp_t ac_mem; /* Average memory usage. */ comp_t ac_io; /* Chars transferred. */ comp_t ac_rw; /* Blocks read or written. */ comp_t ac_minflt; /* Minor pagefaults. */ comp_t ac_majflt; /* Major pagefaults. */ comp_t ac_swaps; /* Number of swaps. */ uint32_t ac_exitcode; /* Process exitcode. */ char ac_comm[ACCT_COMM+1]; /* Command name. */ char ac_pad[10]; /* Padding bytes. */ }; struct acct_v3 { char ac_flag; /* Flags */ char ac_version; /* Always set to ACCT_VERSION */ uint16_t ac_tty; /* Control Terminal */ uint32_t ac_exitcode; /* Exitcode */ uint32_t ac_uid; /* Real User ID */ uint32_t ac_gid; /* Real Group ID */ uint32_t ac_pid; /* Process ID */ uint32_t ac_ppid; /* Parent Process ID */ uint32_t ac_btime; /* Process Creation Time */ float ac_etime; /* Elapsed Time */ comp_t ac_utime; /* User Time */ comp_t ac_stime; /* System Time */ comp_t ac_mem; /* Average Memory Usage */ comp_t ac_io; /* Chars Transferred */ comp_t ac_rw; /* Blocks Read or Written */ comp_t ac_minflt; /* Minor Pagefaults */ comp_t ac_majflt; /* Major Pagefaults */ comp_t ac_swaps; /* Number of Swaps */ char ac_comm[ACCT_COMM]; /* Command Name */ }; enum { AFORK = 0x01, /* Has executed fork, but no exec. */ ASU = 0x02, /* Used super-user privileges. */ ACORE = 0x08, /* Dumped core. */ AXSIG = 0x10 /* Killed by a signal. */ }; #if __BYTE_ORDER == __BIG_ENDIAN # define ACCT_BYTEORDER 0x80 /* Accounting file is big endian. */ #else # define ACCT_BYTEORDER 0x00 /* Accounting file is little endian. */ #endif #define AHZ 100 /* Switch process accounting on and off. */ extern int acct (const char *__filename) __THROW; __END_DECLS #endif /* sys/acct.h */ sys/ptrace.h000064400000013544151027430550007022 0ustar00/* `ptrace' debugger support interface. Linux/x86 version. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_PTRACE_H #define _SYS_PTRACE_H 1 #include #include __BEGIN_DECLS /* Type of the REQUEST argument to `ptrace.' */ enum __ptrace_request { /* Indicate that the process making this request should be traced. All signals received by this process can be intercepted by its parent, and its parent can use the other `ptrace' requests. */ PTRACE_TRACEME = 0, #define PT_TRACE_ME PTRACE_TRACEME /* Return the word in the process's text space at address ADDR. */ PTRACE_PEEKTEXT = 1, #define PT_READ_I PTRACE_PEEKTEXT /* Return the word in the process's data space at address ADDR. */ PTRACE_PEEKDATA = 2, #define PT_READ_D PTRACE_PEEKDATA /* Return the word in the process's user area at offset ADDR. */ PTRACE_PEEKUSER = 3, #define PT_READ_U PTRACE_PEEKUSER /* Write the word DATA into the process's text space at address ADDR. */ PTRACE_POKETEXT = 4, #define PT_WRITE_I PTRACE_POKETEXT /* Write the word DATA into the process's data space at address ADDR. */ PTRACE_POKEDATA = 5, #define PT_WRITE_D PTRACE_POKEDATA /* Write the word DATA into the process's user area at offset ADDR. */ PTRACE_POKEUSER = 6, #define PT_WRITE_U PTRACE_POKEUSER /* Continue the process. */ PTRACE_CONT = 7, #define PT_CONTINUE PTRACE_CONT /* Kill the process. */ PTRACE_KILL = 8, #define PT_KILL PTRACE_KILL /* Single step the process. */ PTRACE_SINGLESTEP = 9, #define PT_STEP PTRACE_SINGLESTEP /* Get all general purpose registers used by a processes. */ PTRACE_GETREGS = 12, #define PT_GETREGS PTRACE_GETREGS /* Set all general purpose registers used by a processes. */ PTRACE_SETREGS = 13, #define PT_SETREGS PTRACE_SETREGS /* Get all floating point registers used by a processes. */ PTRACE_GETFPREGS = 14, #define PT_GETFPREGS PTRACE_GETFPREGS /* Set all floating point registers used by a processes. */ PTRACE_SETFPREGS = 15, #define PT_SETFPREGS PTRACE_SETFPREGS /* Attach to a process that is already running. */ PTRACE_ATTACH = 16, #define PT_ATTACH PTRACE_ATTACH /* Detach from a process attached to with PTRACE_ATTACH. */ PTRACE_DETACH = 17, #define PT_DETACH PTRACE_DETACH /* Get all extended floating point registers used by a processes. */ PTRACE_GETFPXREGS = 18, #define PT_GETFPXREGS PTRACE_GETFPXREGS /* Set all extended floating point registers used by a processes. */ PTRACE_SETFPXREGS = 19, #define PT_SETFPXREGS PTRACE_SETFPXREGS /* Continue and stop at the next entry to or return from syscall. */ PTRACE_SYSCALL = 24, #define PT_SYSCALL PTRACE_SYSCALL /* Get a TLS entry in the GDT. */ PTRACE_GET_THREAD_AREA = 25, #define PT_GET_THREAD_AREA PTRACE_GET_THREAD_AREA /* Change a TLS entry in the GDT. */ PTRACE_SET_THREAD_AREA = 26, #define PT_SET_THREAD_AREA PTRACE_SET_THREAD_AREA #ifdef __x86_64__ /* Access TLS data. */ PTRACE_ARCH_PRCTL = 30, # define PT_ARCH_PRCTL PTRACE_ARCH_PRCTL #endif /* Continue and stop at the next syscall, it will not be executed. */ PTRACE_SYSEMU = 31, #define PT_SYSEMU PTRACE_SYSEMU /* Single step the process, the next syscall will not be executed. */ PTRACE_SYSEMU_SINGLESTEP = 32, #define PT_SYSEMU_SINGLESTEP PTRACE_SYSEMU_SINGLESTEP /* Execute process until next taken branch. */ PTRACE_SINGLEBLOCK = 33, #define PT_STEPBLOCK PTRACE_SINGLEBLOCK /* Set ptrace filter options. */ PTRACE_SETOPTIONS = 0x4200, #define PT_SETOPTIONS PTRACE_SETOPTIONS /* Get last ptrace message. */ PTRACE_GETEVENTMSG = 0x4201, #define PT_GETEVENTMSG PTRACE_GETEVENTMSG /* Get siginfo for process. */ PTRACE_GETSIGINFO = 0x4202, #define PT_GETSIGINFO PTRACE_GETSIGINFO /* Set new siginfo for process. */ PTRACE_SETSIGINFO = 0x4203, #define PT_SETSIGINFO PTRACE_SETSIGINFO /* Get register content. */ PTRACE_GETREGSET = 0x4204, #define PTRACE_GETREGSET PTRACE_GETREGSET /* Set register content. */ PTRACE_SETREGSET = 0x4205, #define PTRACE_SETREGSET PTRACE_SETREGSET /* Like PTRACE_ATTACH, but do not force tracee to trap and do not affect signal or group stop state. */ PTRACE_SEIZE = 0x4206, #define PTRACE_SEIZE PTRACE_SEIZE /* Trap seized tracee. */ PTRACE_INTERRUPT = 0x4207, #define PTRACE_INTERRUPT PTRACE_INTERRUPT /* Wait for next group event. */ PTRACE_LISTEN = 0x4208, #define PTRACE_LISTEN PTRACE_LISTEN /* Retrieve siginfo_t structures without removing signals from a queue. */ PTRACE_PEEKSIGINFO = 0x4209, #define PTRACE_PEEKSIGINFO PTRACE_PEEKSIGINFO /* Get the mask of blocked signals. */ PTRACE_GETSIGMASK = 0x420a, #define PTRACE_GETSIGMASK PTRACE_GETSIGMASK /* Change the mask of blocked signals. */ PTRACE_SETSIGMASK = 0x420b, #define PTRACE_SETSIGMASK PTRACE_SETSIGMASK /* Get seccomp BPF filters. */ PTRACE_SECCOMP_GET_FILTER = 0x420c, #define PTRACE_SECCOMP_GET_FILTER PTRACE_SECCOMP_GET_FILTER /* Get seccomp BPF filter metadata. */ PTRACE_SECCOMP_GET_METADATA = 0x420d #define PTRACE_SECCOMP_GET_METADATA PTRACE_SECCOMP_GET_METADATA }; #include __END_DECLS #endif /* _SYS_PTRACE_H */ sys/quota.h000064400000012064151027430550006671 0ustar00/* This just represents the non-kernel parts of . Copyright (C) 1998-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * Copyright (c) 1982, 1986 Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Robert Elz at The University of Melbourne. * * 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _SYS_QUOTA_H #define _SYS_QUOTA_H 1 #include #include #include /* * Convert diskblocks to blocks and the other way around. * currently only to fool the BSD source. :-) */ #define dbtob(num) ((num) << 10) #define btodb(num) ((num) >> 10) /* * Convert count of filesystem blocks to diskquota blocks, meant for * filesystems where i_blksize != 1024. */ #define fs_to_dq_blocks(num, blksize) (((num) * (blksize)) / 1024) /* * Definitions for disk quotas imposed on the average user * (big brother finally hits Linux). * * The following constants define the amount of time given a user * before the soft limits are treated as hard limits (usually resulting * in an allocation failure). The timer is started when the user crosses * their soft limit, it is reset when they go below their soft limit. */ #define MAX_IQ_TIME 604800 /* (7*24*60*60) 1 week */ #define MAX_DQ_TIME 604800 /* (7*24*60*60) 1 week */ #define QUOTAFILENAME "quota" #define QUOTAGROUP "staff" #define NR_DQHASH 43 /* Just an arbitrary number any suggestions ? */ #define NR_DQUOTS 256 /* Number of quotas active at one time */ /* Old name for struct if_dqblk. */ struct dqblk { __uint64_t dqb_bhardlimit; /* absolute limit on disk quota blocks alloc */ __uint64_t dqb_bsoftlimit; /* preferred limit on disk quota blocks */ __uint64_t dqb_curspace; /* current quota block count */ __uint64_t dqb_ihardlimit; /* maximum # allocated inodes */ __uint64_t dqb_isoftlimit; /* preferred inode limit */ __uint64_t dqb_curinodes; /* current # allocated inodes */ __uint64_t dqb_btime; /* time limit for excessive disk use */ __uint64_t dqb_itime; /* time limit for excessive files */ __uint32_t dqb_valid; /* bitmask of QIF_* constants */ }; /* * Shorthand notation. */ #define dq_bhardlimit dq_dqb.dqb_bhardlimit #define dq_bsoftlimit dq_dqb.dqb_bsoftlimit #define dq_curspace dq_dqb.dqb_curspace #define dq_valid dq_dqb.dqb_valid #define dq_ihardlimit dq_dqb.dqb_ihardlimit #define dq_isoftlimit dq_dqb.dqb_isoftlimit #define dq_curinodes dq_dqb.dqb_curinodes #define dq_btime dq_dqb.dqb_btime #define dq_itime dq_dqb.dqb_itime #define dqoff(UID) ((__loff_t)((UID) * sizeof (struct dqblk))) /* Old name for struct if_dqinfo. */ struct dqinfo { __uint64_t dqi_bgrace; __uint64_t dqi_igrace; __uint32_t dqi_flags; __uint32_t dqi_valid; }; __BEGIN_DECLS extern int quotactl (int __cmd, const char *__special, int __id, __caddr_t __addr) __THROW; __END_DECLS #endif /* sys/quota.h */ sys/vlimit.h000064400000003527151027430550007050 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_VLIMIT_H #define _SYS_VLIMIT_H 1 #include __BEGIN_DECLS /* This interface is obsolete, and is superseded by . */ /* Kinds of resource limit. */ enum __vlimit_resource { /* Setting this non-zero makes it impossible to raise limits. Only the super-use can set it to zero. This is not implemented in recent versions of BSD, nor by the GNU C library. */ LIM_NORAISE, /* CPU time available for each process (seconds). */ LIM_CPU, /* Largest file which can be created (bytes). */ LIM_FSIZE, /* Maximum size of the data segment (bytes). */ LIM_DATA, /* Maximum size of the stack segment (bytes). */ LIM_STACK, /* Largest core file that will be created (bytes). */ LIM_CORE, /* Resident set size (bytes). */ LIM_MAXRSS }; /* This means no limit. */ #define INFINITY 0x7fffffff /* Set the soft limit for RESOURCE to be VALUE. Returns 0 for success, -1 for failure. */ extern int vlimit (enum __vlimit_resource __resource, int __value) __THROW; __END_DECLS #endif /* sys/vlimit.h */ sys/io.h000064400000011735151027430550006153 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_IO_H #define _SYS_IO_H 1 #include __BEGIN_DECLS /* If TURN_ON is TRUE, request for permission to do direct i/o on the port numbers in the range [FROM,FROM+NUM-1]. Otherwise, turn I/O permission off for that range. This call requires root privileges. Portability note: not all Linux platforms support this call. Most platforms based on the PC I/O architecture probably will, however. E.g., Linux/Alpha for Alpha PCs supports this. */ extern int ioperm (unsigned long int __from, unsigned long int __num, int __turn_on) __THROW; /* Set the I/O privilege level to LEVEL. If LEVEL>3, permission to access any I/O port is granted. This call requires root privileges. */ extern int iopl (int __level) __THROW; #if defined __GNUC__ && __GNUC__ >= 2 static __inline unsigned char inb (unsigned short int __port) { unsigned char _v; __asm__ __volatile__ ("inb %w1,%0":"=a" (_v):"Nd" (__port)); return _v; } static __inline unsigned char inb_p (unsigned short int __port) { unsigned char _v; __asm__ __volatile__ ("inb %w1,%0\noutb %%al,$0x80":"=a" (_v):"Nd" (__port)); return _v; } static __inline unsigned short int inw (unsigned short int __port) { unsigned short _v; __asm__ __volatile__ ("inw %w1,%0":"=a" (_v):"Nd" (__port)); return _v; } static __inline unsigned short int inw_p (unsigned short int __port) { unsigned short int _v; __asm__ __volatile__ ("inw %w1,%0\noutb %%al,$0x80":"=a" (_v):"Nd" (__port)); return _v; } static __inline unsigned int inl (unsigned short int __port) { unsigned int _v; __asm__ __volatile__ ("inl %w1,%0":"=a" (_v):"Nd" (__port)); return _v; } static __inline unsigned int inl_p (unsigned short int __port) { unsigned int _v; __asm__ __volatile__ ("inl %w1,%0\noutb %%al,$0x80":"=a" (_v):"Nd" (__port)); return _v; } static __inline void outb (unsigned char __value, unsigned short int __port) { __asm__ __volatile__ ("outb %b0,%w1": :"a" (__value), "Nd" (__port)); } static __inline void outb_p (unsigned char __value, unsigned short int __port) { __asm__ __volatile__ ("outb %b0,%w1\noutb %%al,$0x80": :"a" (__value), "Nd" (__port)); } static __inline void outw (unsigned short int __value, unsigned short int __port) { __asm__ __volatile__ ("outw %w0,%w1": :"a" (__value), "Nd" (__port)); } static __inline void outw_p (unsigned short int __value, unsigned short int __port) { __asm__ __volatile__ ("outw %w0,%w1\noutb %%al,$0x80": :"a" (__value), "Nd" (__port)); } static __inline void outl (unsigned int __value, unsigned short int __port) { __asm__ __volatile__ ("outl %0,%w1": :"a" (__value), "Nd" (__port)); } static __inline void outl_p (unsigned int __value, unsigned short int __port) { __asm__ __volatile__ ("outl %0,%w1\noutb %%al,$0x80": :"a" (__value), "Nd" (__port)); } static __inline void insb (unsigned short int __port, void *__addr, unsigned long int __count) { __asm__ __volatile__ ("cld ; rep ; insb":"=D" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); } static __inline void insw (unsigned short int __port, void *__addr, unsigned long int __count) { __asm__ __volatile__ ("cld ; rep ; insw":"=D" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); } static __inline void insl (unsigned short int __port, void *__addr, unsigned long int __count) { __asm__ __volatile__ ("cld ; rep ; insl":"=D" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); } static __inline void outsb (unsigned short int __port, const void *__addr, unsigned long int __count) { __asm__ __volatile__ ("cld ; rep ; outsb":"=S" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); } static __inline void outsw (unsigned short int __port, const void *__addr, unsigned long int __count) { __asm__ __volatile__ ("cld ; rep ; outsw":"=S" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); } static __inline void outsl (unsigned short int __port, const void *__addr, unsigned long int __count) { __asm__ __volatile__ ("cld ; rep ; outsl":"=S" (__addr), "=c" (__count) :"d" (__port), "0" (__addr), "1" (__count)); } #endif /* GNU C */ __END_DECLS #endif /* _SYS_IO_H */ sys/stat.h000064400000037554151027430550006526 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * POSIX Standard: 5.6 File Characteristics */ #ifndef _SYS_STAT_H #define _SYS_STAT_H 1 #include #include /* For __mode_t and __dev_t. */ #ifdef __USE_XOPEN2K8 # include #endif #if defined __USE_XOPEN || defined __USE_XOPEN2K /* The Single Unix specification says that some more types are available here. */ # include # ifndef __dev_t_defined typedef __dev_t dev_t; # define __dev_t_defined # endif # ifndef __gid_t_defined typedef __gid_t gid_t; # define __gid_t_defined # endif # ifndef __ino_t_defined # ifndef __USE_FILE_OFFSET64 typedef __ino_t ino_t; # else typedef __ino64_t ino_t; # endif # define __ino_t_defined # endif # ifndef __mode_t_defined typedef __mode_t mode_t; # define __mode_t_defined # endif # ifndef __nlink_t_defined typedef __nlink_t nlink_t; # define __nlink_t_defined # endif # ifndef __off_t_defined # ifndef __USE_FILE_OFFSET64 typedef __off_t off_t; # else typedef __off64_t off_t; # endif # define __off_t_defined # endif # ifndef __uid_t_defined typedef __uid_t uid_t; # define __uid_t_defined # endif #endif /* X/Open */ #ifdef __USE_UNIX98 # ifndef __blkcnt_t_defined # ifndef __USE_FILE_OFFSET64 typedef __blkcnt_t blkcnt_t; # else typedef __blkcnt64_t blkcnt_t; # endif # define __blkcnt_t_defined # endif # ifndef __blksize_t_defined typedef __blksize_t blksize_t; # define __blksize_t_defined # endif #endif /* Unix98 */ __BEGIN_DECLS #include #if defined __USE_MISC || defined __USE_XOPEN # define S_IFMT __S_IFMT # define S_IFDIR __S_IFDIR # define S_IFCHR __S_IFCHR # define S_IFBLK __S_IFBLK # define S_IFREG __S_IFREG # ifdef __S_IFIFO # define S_IFIFO __S_IFIFO # endif # ifdef __S_IFLNK # define S_IFLNK __S_IFLNK # endif # if (defined __USE_MISC || defined __USE_XOPEN_EXTENDED) \ && defined __S_IFSOCK # define S_IFSOCK __S_IFSOCK # endif #endif /* Test macros for file types. */ #define __S_ISTYPE(mode, mask) (((mode) & __S_IFMT) == (mask)) #define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) #define S_ISCHR(mode) __S_ISTYPE((mode), __S_IFCHR) #define S_ISBLK(mode) __S_ISTYPE((mode), __S_IFBLK) #define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) #ifdef __S_IFIFO # define S_ISFIFO(mode) __S_ISTYPE((mode), __S_IFIFO) #endif #ifdef __S_IFLNK # define S_ISLNK(mode) __S_ISTYPE((mode), __S_IFLNK) #endif #if defined __USE_MISC && !defined __S_IFLNK # define S_ISLNK(mode) 0 #endif #if (defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K) \ && defined __S_IFSOCK # define S_ISSOCK(mode) __S_ISTYPE((mode), __S_IFSOCK) #elif defined __USE_XOPEN2K # define S_ISSOCK(mode) 0 #endif /* These are from POSIX.1b. If the objects are not implemented using separate distinct file types, the macros always will evaluate to zero. Unlike the other S_* macros the following three take a pointer to a `struct stat' object as the argument. */ #ifdef __USE_POSIX199309 # define S_TYPEISMQ(buf) __S_TYPEISMQ(buf) # define S_TYPEISSEM(buf) __S_TYPEISSEM(buf) # define S_TYPEISSHM(buf) __S_TYPEISSHM(buf) #endif /* Protection bits. */ #define S_ISUID __S_ISUID /* Set user ID on execution. */ #define S_ISGID __S_ISGID /* Set group ID on execution. */ #if defined __USE_MISC || defined __USE_XOPEN /* Save swapped text after use (sticky bit). This is pretty well obsolete. */ # define S_ISVTX __S_ISVTX #endif #define S_IRUSR __S_IREAD /* Read by owner. */ #define S_IWUSR __S_IWRITE /* Write by owner. */ #define S_IXUSR __S_IEXEC /* Execute by owner. */ /* Read, write, and execute by owner. */ #define S_IRWXU (__S_IREAD|__S_IWRITE|__S_IEXEC) #ifdef __USE_MISC # define S_IREAD S_IRUSR # define S_IWRITE S_IWUSR # define S_IEXEC S_IXUSR #endif #define S_IRGRP (S_IRUSR >> 3) /* Read by group. */ #define S_IWGRP (S_IWUSR >> 3) /* Write by group. */ #define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */ /* Read, write, and execute by group. */ #define S_IRWXG (S_IRWXU >> 3) #define S_IROTH (S_IRGRP >> 3) /* Read by others. */ #define S_IWOTH (S_IWGRP >> 3) /* Write by others. */ #define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */ /* Read, write, and execute by others. */ #define S_IRWXO (S_IRWXG >> 3) #ifdef __USE_MISC /* Macros for common mode bit masks. */ # define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO) /* 0777 */ # define ALLPERMS (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)/* 07777 */ # define DEFFILEMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)/* 0666*/ # define S_BLKSIZE 512 /* Block size for `st_blocks'. */ #endif #ifndef __USE_FILE_OFFSET64 /* Get file attributes for FILE and put them in BUF. */ extern int stat (const char *__restrict __file, struct stat *__restrict __buf) __THROW __nonnull ((1, 2)); /* Get file attributes for the file, device, pipe, or socket that file descriptor FD is open on and put them in BUF. */ extern int fstat (int __fd, struct stat *__buf) __THROW __nonnull ((2)); #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (stat, (const char *__restrict __file, struct stat *__restrict __buf), stat64) __nonnull ((1, 2)); extern int __REDIRECT_NTH (fstat, (int __fd, struct stat *__buf), fstat64) __nonnull ((2)); # else # define stat stat64 # define fstat fstat64 # endif #endif #ifdef __USE_LARGEFILE64 extern int stat64 (const char *__restrict __file, struct stat64 *__restrict __buf) __THROW __nonnull ((1, 2)); extern int fstat64 (int __fd, struct stat64 *__buf) __THROW __nonnull ((2)); #endif #ifdef __USE_ATFILE /* Similar to stat, get the attributes for FILE and put them in BUF. Relative path names are interpreted relative to FD unless FD is AT_FDCWD. */ # ifndef __USE_FILE_OFFSET64 extern int fstatat (int __fd, const char *__restrict __file, struct stat *__restrict __buf, int __flag) __THROW __nonnull ((2, 3)); # else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (fstatat, (int __fd, const char *__restrict __file, struct stat *__restrict __buf, int __flag), fstatat64) __nonnull ((2, 3)); # else # define fstatat fstatat64 # endif # endif # ifdef __USE_LARGEFILE64 extern int fstatat64 (int __fd, const char *__restrict __file, struct stat64 *__restrict __buf, int __flag) __THROW __nonnull ((2, 3)); # endif #endif #if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K # ifndef __USE_FILE_OFFSET64 /* Get file attributes about FILE and put them in BUF. If FILE is a symbolic link, do not follow it. */ extern int lstat (const char *__restrict __file, struct stat *__restrict __buf) __THROW __nonnull ((1, 2)); # else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (lstat, (const char *__restrict __file, struct stat *__restrict __buf), lstat64) __nonnull ((1, 2)); # else # define lstat lstat64 # endif # endif # ifdef __USE_LARGEFILE64 extern int lstat64 (const char *__restrict __file, struct stat64 *__restrict __buf) __THROW __nonnull ((1, 2)); # endif #endif /* Set file access permissions for FILE to MODE. If FILE is a symbolic link, this affects its target instead. */ extern int chmod (const char *__file, __mode_t __mode) __THROW __nonnull ((1)); #ifdef __USE_MISC /* Set file access permissions for FILE to MODE. If FILE is a symbolic link, this affects the link itself rather than its target. */ extern int lchmod (const char *__file, __mode_t __mode) __THROW __nonnull ((1)); #endif /* Set file access permissions of the file FD is open on to MODE. */ #if defined __USE_POSIX199309 || defined __USE_XOPEN_EXTENDED extern int fchmod (int __fd, __mode_t __mode) __THROW; #endif #ifdef __USE_ATFILE /* Set file access permissions of FILE relative to the directory FD is open on. */ extern int fchmodat (int __fd, const char *__file, __mode_t __mode, int __flag) __THROW __nonnull ((2)) __wur; #endif /* Use ATFILE. */ /* Set the file creation mask of the current process to MASK, and return the old creation mask. */ extern __mode_t umask (__mode_t __mask) __THROW; #ifdef __USE_GNU /* Get the current `umask' value without changing it. This function is only available under the GNU Hurd. */ extern __mode_t getumask (void) __THROW; #endif /* Create a new directory named PATH, with permission bits MODE. */ extern int mkdir (const char *__path, __mode_t __mode) __THROW __nonnull ((1)); #ifdef __USE_ATFILE /* Like mkdir, create a new directory with permission bits MODE. But interpret relative PATH names relative to the directory associated with FD. */ extern int mkdirat (int __fd, const char *__path, __mode_t __mode) __THROW __nonnull ((2)); #endif /* Create a device file named PATH, with permission and special bits MODE and device number DEV (which can be constructed from major and minor device numbers with the `makedev' macro above). */ #if defined __USE_MISC || defined __USE_XOPEN_EXTENDED extern int mknod (const char *__path, __mode_t __mode, __dev_t __dev) __THROW __nonnull ((1)); # ifdef __USE_ATFILE /* Like mknod, create a new device file with permission bits MODE and device number DEV. But interpret relative PATH names relative to the directory associated with FD. */ extern int mknodat (int __fd, const char *__path, __mode_t __mode, __dev_t __dev) __THROW __nonnull ((2)); # endif #endif /* Create a new FIFO named PATH, with permission bits MODE. */ extern int mkfifo (const char *__path, __mode_t __mode) __THROW __nonnull ((1)); #ifdef __USE_ATFILE /* Like mkfifo, create a new FIFO with permission bits MODE. But interpret relative PATH names relative to the directory associated with FD. */ extern int mkfifoat (int __fd, const char *__path, __mode_t __mode) __THROW __nonnull ((2)); #endif #ifdef __USE_ATFILE /* Set file access and modification times relative to directory file descriptor. */ extern int utimensat (int __fd, const char *__path, const struct timespec __times[2], int __flags) __THROW __nonnull ((2)); #endif #ifdef __USE_XOPEN2K8 /* Set file access and modification times of the file associated with FD. */ extern int futimens (int __fd, const struct timespec __times[2]) __THROW; #endif /* To allow the `struct stat' structure and the file type `mode_t' bits to vary without changing shared library major version number, the `stat' family of functions and `mknod' are in fact inline wrappers around calls to `xstat', `fxstat', `lxstat', and `xmknod', which all take a leading version-number argument designating the data structure and bits used. defines _STAT_VER with the version number corresponding to `struct stat' as defined in that file; and _MKNOD_VER with the version number corresponding to the S_IF* macros defined therein. It is arranged that when not inlined these function are always statically linked; that way a dynamically-linked executable always encodes the version number corresponding to the data structures it uses, so the `x' functions in the shared library can adapt without needing to recompile all callers. */ #ifndef _STAT_VER # define _STAT_VER 0 #endif #ifndef _MKNOD_VER # define _MKNOD_VER 0 #endif /* Wrappers for stat and mknod system calls. */ #ifndef __USE_FILE_OFFSET64 extern int __fxstat (int __ver, int __fildes, struct stat *__stat_buf) __THROW __nonnull ((3)); extern int __xstat (int __ver, const char *__filename, struct stat *__stat_buf) __THROW __nonnull ((2, 3)); extern int __lxstat (int __ver, const char *__filename, struct stat *__stat_buf) __THROW __nonnull ((2, 3)); extern int __fxstatat (int __ver, int __fildes, const char *__filename, struct stat *__stat_buf, int __flag) __THROW __nonnull ((3, 4)); #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (__fxstat, (int __ver, int __fildes, struct stat *__stat_buf), __fxstat64) __nonnull ((3)); extern int __REDIRECT_NTH (__xstat, (int __ver, const char *__filename, struct stat *__stat_buf), __xstat64) __nonnull ((2, 3)); extern int __REDIRECT_NTH (__lxstat, (int __ver, const char *__filename, struct stat *__stat_buf), __lxstat64) __nonnull ((2, 3)); extern int __REDIRECT_NTH (__fxstatat, (int __ver, int __fildes, const char *__filename, struct stat *__stat_buf, int __flag), __fxstatat64) __nonnull ((3, 4)); # else # define __fxstat __fxstat64 # define __xstat __xstat64 # define __lxstat __lxstat64 # endif #endif #ifdef __USE_LARGEFILE64 extern int __fxstat64 (int __ver, int __fildes, struct stat64 *__stat_buf) __THROW __nonnull ((3)); extern int __xstat64 (int __ver, const char *__filename, struct stat64 *__stat_buf) __THROW __nonnull ((2, 3)); extern int __lxstat64 (int __ver, const char *__filename, struct stat64 *__stat_buf) __THROW __nonnull ((2, 3)); extern int __fxstatat64 (int __ver, int __fildes, const char *__filename, struct stat64 *__stat_buf, int __flag) __THROW __nonnull ((3, 4)); #endif extern int __xmknod (int __ver, const char *__path, __mode_t __mode, __dev_t *__dev) __THROW __nonnull ((2, 4)); extern int __xmknodat (int __ver, int __fd, const char *__path, __mode_t __mode, __dev_t *__dev) __THROW __nonnull ((3, 5)); #ifdef __USE_GNU # include #endif #ifdef __USE_EXTERN_INLINES /* Inlined versions of the real stat and mknod functions. */ __extern_inline int __NTH (stat (const char *__path, struct stat *__statbuf)) { return __xstat (_STAT_VER, __path, __statbuf); } # if defined __USE_MISC || defined __USE_XOPEN_EXTENDED __extern_inline int __NTH (lstat (const char *__path, struct stat *__statbuf)) { return __lxstat (_STAT_VER, __path, __statbuf); } # endif __extern_inline int __NTH (fstat (int __fd, struct stat *__statbuf)) { return __fxstat (_STAT_VER, __fd, __statbuf); } # ifdef __USE_ATFILE __extern_inline int __NTH (fstatat (int __fd, const char *__filename, struct stat *__statbuf, int __flag)) { return __fxstatat (_STAT_VER, __fd, __filename, __statbuf, __flag); } # endif # ifdef __USE_MISC __extern_inline int __NTH (mknod (const char *__path, __mode_t __mode, __dev_t __dev)) { return __xmknod (_MKNOD_VER, __path, __mode, &__dev); } # endif # ifdef __USE_ATFILE __extern_inline int __NTH (mknodat (int __fd, const char *__path, __mode_t __mode, __dev_t __dev)) { return __xmknodat (_MKNOD_VER, __fd, __path, __mode, &__dev); } # endif # if defined __USE_LARGEFILE64 \ && (! defined __USE_FILE_OFFSET64 \ || (defined __REDIRECT_NTH && defined __OPTIMIZE__)) __extern_inline int __NTH (stat64 (const char *__path, struct stat64 *__statbuf)) { return __xstat64 (_STAT_VER, __path, __statbuf); } # if defined __USE_MISC || defined __USE_XOPEN_EXTENDED __extern_inline int __NTH (lstat64 (const char *__path, struct stat64 *__statbuf)) { return __lxstat64 (_STAT_VER, __path, __statbuf); } # endif __extern_inline int __NTH (fstat64 (int __fd, struct stat64 *__statbuf)) { return __fxstat64 (_STAT_VER, __fd, __statbuf); } # ifdef __USE_ATFILE __extern_inline int __NTH (fstatat64 (int __fd, const char *__filename, struct stat64 *__statbuf, int __flag)) { return __fxstatat64 (_STAT_VER, __fd, __filename, __statbuf, __flag); } # endif # endif #endif __END_DECLS #endif /* sys/stat.h */ sys/vm86.h000064400000002256151027430550006342 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_VM86_H #define _SYS_VM86_H 1 #include #ifdef __x86_64__ # error This header is unsupported on x86-64. #else /* Get constants and data types from kernel header file. */ # include __BEGIN_DECLS /* Enter virtual 8086 mode. */ extern int vm86 (unsigned long int __subfunction, struct vm86plus_struct *__info) __THROW; __END_DECLS # endif #endif /* _SYS_VM86_H */ sys/wait.h000064400000012744151027430550006511 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * POSIX Standard: 3.2.1 Wait for Process Termination */ #ifndef _SYS_WAIT_H #define _SYS_WAIT_H 1 #include __BEGIN_DECLS #include #ifndef __pid_t_defined typedef __pid_t pid_t; # define __pid_t_defined #endif #if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K8 # include #endif #if defined __USE_XOPEN_EXTENDED && !defined __USE_XOPEN2K8 /* Some older standards require the contents of struct rusage to be defined here. */ # include #endif /* These macros could also be defined in . */ #if !defined _STDLIB_H || (!defined __USE_XOPEN && !defined __USE_XOPEN2K8) /* This will define the `W*' macros for the flag bits to `waitpid', `wait3', and `wait4'. */ # include /* This will define all the `__W*' macros. */ # include # define WEXITSTATUS(status) __WEXITSTATUS (status) # define WTERMSIG(status) __WTERMSIG (status) # define WSTOPSIG(status) __WSTOPSIG (status) # define WIFEXITED(status) __WIFEXITED (status) # define WIFSIGNALED(status) __WIFSIGNALED (status) # define WIFSTOPPED(status) __WIFSTOPPED (status) # ifdef __WIFCONTINUED # define WIFCONTINUED(status) __WIFCONTINUED (status) # endif #endif /* not included. */ #ifdef __USE_MISC # define WCOREFLAG __WCOREFLAG # define WCOREDUMP(status) __WCOREDUMP (status) # define W_EXITCODE(ret, sig) __W_EXITCODE (ret, sig) # define W_STOPCODE(sig) __W_STOPCODE (sig) #endif /* The following values are used by the `waitid' function. */ #if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K8 typedef enum { P_ALL, /* Wait for any child. */ P_PID, /* Wait for specified process. */ P_PGID /* Wait for members of process group. */ } idtype_t; #endif /* Wait for a child to die. When one does, put its status in *STAT_LOC and return its process ID. For errors, return (pid_t) -1. This function is a cancellation point and therefore not marked with __THROW. */ extern __pid_t wait (int *__stat_loc); #ifdef __USE_MISC /* Special values for the PID argument to `waitpid' and `wait4'. */ # define WAIT_ANY (-1) /* Any process. */ # define WAIT_MYPGRP 0 /* Any process in my process group. */ #endif /* Wait for a child matching PID to die. If PID is greater than 0, match any process whose process ID is PID. If PID is (pid_t) -1, match any process. If PID is (pid_t) 0, match any process with the same process group as the current process. If PID is less than -1, match any process whose process group is the absolute value of PID. If the WNOHANG bit is set in OPTIONS, and that child is not already dead, return (pid_t) 0. If successful, return PID and store the dead child's status in STAT_LOC. Return (pid_t) -1 for errors. If the WUNTRACED bit is set in OPTIONS, return status for stopped children; otherwise don't. This function is a cancellation point and therefore not marked with __THROW. */ extern __pid_t waitpid (__pid_t __pid, int *__stat_loc, int __options); #if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K8 # ifndef __id_t_defined typedef __id_t id_t; # define __id_t_defined # endif # include /* Wait for a childing matching IDTYPE and ID to change the status and place appropriate information in *INFOP. If IDTYPE is P_PID, match any process whose process ID is ID. If IDTYPE is P_PGID, match any process whose process group is ID. If IDTYPE is P_ALL, match any process. If the WNOHANG bit is set in OPTIONS, and that child is not already dead, clear *INFOP and return 0. If successful, store exit code and status in *INFOP. This function is a cancellation point and therefore not marked with __THROW. */ extern int waitid (idtype_t __idtype, __id_t __id, siginfo_t *__infop, int __options); #endif #if defined __USE_MISC \ || (defined __USE_XOPEN_EXTENDED && !defined __USE_XOPEN2K) /* This being here makes the prototypes valid whether or not we have already included to define `struct rusage'. */ struct rusage; /* Wait for a child to exit. When one does, put its status in *STAT_LOC and return its process ID. For errors return (pid_t) -1. If USAGE is not nil, store information about the child's resource usage there. If the WUNTRACED bit is set in OPTIONS, return status for stopped children; otherwise don't. */ extern __pid_t wait3 (int *__stat_loc, int __options, struct rusage * __usage) __THROWNL; #endif #ifdef __USE_MISC /* PID is like waitpid. Other args are like wait3. */ extern __pid_t wait4 (__pid_t __pid, int *__stat_loc, int __options, struct rusage *__usage) __THROWNL; #endif /* Use misc. */ __END_DECLS #endif /* sys/wait.h */ sys/syscall.h000064400000002467151027430550007220 0ustar00/* Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYSCALL_H #define _SYSCALL_H 1 /* This file should list the numbers of the system calls the system knows. But instead of duplicating this we use the information available from the kernel sources. */ #include #ifndef _LIBC /* The Linux kernel header file defines macros `__NR_', but some programs expect the traditional form `SYS_'. So in building libc we scan the kernel's list and produce with macros for all the `SYS_' names. */ # include #endif #endif sys/socket.h000064400000023733151027430550007035 0ustar00/* Declarations of socket constants, types, and functions. Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SOCKET_H #define _SYS_SOCKET_H 1 #include __BEGIN_DECLS #include #define __need_size_t #include /* This operating system-specific header file defines the SOCK_*, PF_*, AF_*, MSG_*, SOL_*, and SO_* constants, and the `struct sockaddr', `struct msghdr', and `struct linger' types. */ #include #ifdef __USE_MISC # include #endif /* The following constants should be used for the second parameter of `shutdown'. */ enum { SHUT_RD = 0, /* No more receptions. */ #define SHUT_RD SHUT_RD SHUT_WR, /* No more transmissions. */ #define SHUT_WR SHUT_WR SHUT_RDWR /* No more receptions or transmissions. */ #define SHUT_RDWR SHUT_RDWR }; /* This is the type we use for generic socket address arguments. With GCC 2.7 and later, the funky union causes redeclarations or uses with any of the listed types to be allowed without complaint. G++ 2.7 does not support transparent unions so there we want the old-style declaration, too. */ #if defined __cplusplus || !__GNUC_PREREQ (2, 7) || !defined __USE_GNU # define __SOCKADDR_ARG struct sockaddr *__restrict # define __CONST_SOCKADDR_ARG const struct sockaddr * #else /* Add more `struct sockaddr_AF' types here as necessary. These are all the ones I found on NetBSD and Linux. */ # define __SOCKADDR_ALLTYPES \ __SOCKADDR_ONETYPE (sockaddr) \ __SOCKADDR_ONETYPE (sockaddr_at) \ __SOCKADDR_ONETYPE (sockaddr_ax25) \ __SOCKADDR_ONETYPE (sockaddr_dl) \ __SOCKADDR_ONETYPE (sockaddr_eon) \ __SOCKADDR_ONETYPE (sockaddr_in) \ __SOCKADDR_ONETYPE (sockaddr_in6) \ __SOCKADDR_ONETYPE (sockaddr_inarp) \ __SOCKADDR_ONETYPE (sockaddr_ipx) \ __SOCKADDR_ONETYPE (sockaddr_iso) \ __SOCKADDR_ONETYPE (sockaddr_ns) \ __SOCKADDR_ONETYPE (sockaddr_un) \ __SOCKADDR_ONETYPE (sockaddr_x25) # define __SOCKADDR_ONETYPE(type) struct type *__restrict __##type##__; typedef union { __SOCKADDR_ALLTYPES } __SOCKADDR_ARG __attribute__ ((__transparent_union__)); # undef __SOCKADDR_ONETYPE # define __SOCKADDR_ONETYPE(type) const struct type *__restrict __##type##__; typedef union { __SOCKADDR_ALLTYPES } __CONST_SOCKADDR_ARG __attribute__ ((__transparent_union__)); # undef __SOCKADDR_ONETYPE #endif #ifdef __USE_GNU /* For `recvmmsg' and `sendmmsg'. */ struct mmsghdr { struct msghdr msg_hdr; /* Actual message header. */ unsigned int msg_len; /* Number of received or sent bytes for the entry. */ }; #endif /* Create a new socket of type TYPE in domain DOMAIN, using protocol PROTOCOL. If PROTOCOL is zero, one is chosen automatically. Returns a file descriptor for the new socket, or -1 for errors. */ extern int socket (int __domain, int __type, int __protocol) __THROW; /* Create two new sockets, of type TYPE in domain DOMAIN and using protocol PROTOCOL, which are connected to each other, and put file descriptors for them in FDS[0] and FDS[1]. If PROTOCOL is zero, one will be chosen automatically. Returns 0 on success, -1 for errors. */ extern int socketpair (int __domain, int __type, int __protocol, int __fds[2]) __THROW; /* Give the socket FD the local address ADDR (which is LEN bytes long). */ extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len) __THROW; /* Put the local address of FD into *ADDR and its length in *LEN. */ extern int getsockname (int __fd, __SOCKADDR_ARG __addr, socklen_t *__restrict __len) __THROW; /* Open a connection on socket FD to peer at ADDR (which LEN bytes long). For connectionless socket types, just set the default address to send to and the only address from which to accept transmissions. Return 0 on success, -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern int connect (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len); /* Put the address of the peer connected to socket FD into *ADDR (which is *LEN bytes long), and its actual length into *LEN. */ extern int getpeername (int __fd, __SOCKADDR_ARG __addr, socklen_t *__restrict __len) __THROW; /* Send N bytes of BUF to socket FD. Returns the number sent or -1. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t send (int __fd, const void *__buf, size_t __n, int __flags); /* Read N bytes into BUF from socket FD. Returns the number read or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t recv (int __fd, void *__buf, size_t __n, int __flags); /* Send N bytes of BUF on socket FD to peer at address ADDR (which is ADDR_LEN bytes long). Returns the number sent, or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t sendto (int __fd, const void *__buf, size_t __n, int __flags, __CONST_SOCKADDR_ARG __addr, socklen_t __addr_len); /* Read N bytes into BUF through socket FD. If ADDR is not NULL, fill in *ADDR_LEN bytes of it with tha address of the sender, and store the actual size of the address in *ADDR_LEN. Returns the number of bytes read or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t recvfrom (int __fd, void *__restrict __buf, size_t __n, int __flags, __SOCKADDR_ARG __addr, socklen_t *__restrict __addr_len); /* Send a message described MESSAGE on socket FD. Returns the number of bytes sent, or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t sendmsg (int __fd, const struct msghdr *__message, int __flags); #ifdef __USE_GNU /* Send a VLEN messages as described by VMESSAGES to socket FD. Returns the number of datagrams successfully written or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern int sendmmsg (int __fd, struct mmsghdr *__vmessages, unsigned int __vlen, int __flags); #endif /* Receive a message as described by MESSAGE from socket FD. Returns the number of bytes read or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t recvmsg (int __fd, struct msghdr *__message, int __flags); #ifdef __USE_GNU /* Receive up to VLEN messages as described by VMESSAGES from socket FD. Returns the number of messages received or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern int recvmmsg (int __fd, struct mmsghdr *__vmessages, unsigned int __vlen, int __flags, struct timespec *__tmo); #endif /* Put the current value for socket FD's option OPTNAME at protocol level LEVEL into OPTVAL (which is *OPTLEN bytes long), and set *OPTLEN to the value's actual length. Returns 0 on success, -1 for errors. */ extern int getsockopt (int __fd, int __level, int __optname, void *__restrict __optval, socklen_t *__restrict __optlen) __THROW; /* Set socket FD's option OPTNAME at protocol level LEVEL to *OPTVAL (which is OPTLEN bytes long). Returns 0 on success, -1 for errors. */ extern int setsockopt (int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen) __THROW; /* Prepare to accept connections on socket FD. N connection requests will be queued before further requests are refused. Returns 0 on success, -1 for errors. */ extern int listen (int __fd, int __n) __THROW; /* Await a connection on socket FD. When a connection arrives, open a new socket to communicate with it, set *ADDR (which is *ADDR_LEN bytes long) to the address of the connecting peer and *ADDR_LEN to the address's actual length, and return the new socket's descriptor, or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern int accept (int __fd, __SOCKADDR_ARG __addr, socklen_t *__restrict __addr_len); #ifdef __USE_GNU /* Similar to 'accept' but takes an additional parameter to specify flags. This function is a cancellation point and therefore not marked with __THROW. */ extern int accept4 (int __fd, __SOCKADDR_ARG __addr, socklen_t *__restrict __addr_len, int __flags); #endif /* Shut down all or part of the connection open on socket FD. HOW determines what to shut down: SHUT_RD = No more receptions; SHUT_WR = No more transmissions; SHUT_RDWR = No more receptions or transmissions. Returns 0 on success, -1 for errors. */ extern int shutdown (int __fd, int __how) __THROW; #ifdef __USE_XOPEN2K /* Determine wheter socket is at a out-of-band mark. */ extern int sockatmark (int __fd) __THROW; #endif #ifdef __USE_MISC /* FDTYPE is S_IFSOCK or another S_IF* macro defined in ; returns 1 if FD is open on an object of the indicated type, 0 if not, or -1 for errors (setting errno). */ extern int isfdtype (int __fd, int __fdtype) __THROW; #endif /* Define some macros helping to catch buffer overflows. */ #if __USE_FORTIFY_LEVEL > 0 && defined __fortify_function # include #endif __END_DECLS #endif /* sys/socket.h */ sys/ttydefaults.h000064400000006760151027430550010116 0ustar00/*- * Copyright (c) 1982, 1986, 1993 * The Regents of the University of California. All rights reserved. * (c) UNIX System Laboratories, Inc. * All or some portions of this file are derived from material licensed * to the University of California by American Telephone and Telegraph * Co. or Unix System Laboratories, Inc. and are reproduced herein with * the permission of UNIX System Laboratories, Inc. * * 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)ttydefaults.h 8.4 (Berkeley) 1/21/94 */ /* * System wide defaults for terminal state. Linux version. */ #ifndef _SYS_TTYDEFAULTS_H_ #define _SYS_TTYDEFAULTS_H_ /* * Defaults on "first" open. */ #define TTYDEF_IFLAG (BRKINT | ISTRIP | ICRNL | IMAXBEL | IXON | IXANY) #define TTYDEF_OFLAG (OPOST | ONLCR | XTABS) #define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL) #define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL) #define TTYDEF_SPEED (B9600) /* * Control Character Defaults */ #define CTRL(x) (x&037) #define CEOF CTRL('d') #ifdef _POSIX_VDISABLE # define CEOL _POSIX_VDISABLE #else # define CEOL '\0' /* XXX avoid _POSIX_VDISABLE */ #endif #define CERASE 0177 #define CINTR CTRL('c') #ifdef _POSIX_VDISABLE # define CSTATUS _POSIX_VDISABLE #else # define CSTATUS '\0' /* XXX avoid _POSIX_VDISABLE */ #endif #define CKILL CTRL('u') #define CMIN 1 #define CQUIT 034 /* FS, ^\ */ #define CSUSP CTRL('z') #define CTIME 0 #define CDSUSP CTRL('y') #define CSTART CTRL('q') #define CSTOP CTRL('s') #define CLNEXT CTRL('v') #define CDISCARD CTRL('o') #define CWERASE CTRL('w') #define CREPRINT CTRL('r') #define CEOT CEOF /* compat */ #define CBRK CEOL #define CRPRNT CREPRINT #define CFLUSH CDISCARD /* PROTECTED INCLUSION ENDS HERE */ #endif /* !_SYS_TTYDEFAULTS_H_ */ /* * #define TTYDEFCHARS to include an array of default control characters. */ #ifdef TTYDEFCHARS cc_t ttydefchars[NCCS] = { CEOF, CEOL, CEOL, CERASE, CWERASE, CKILL, CREPRINT, _POSIX_VDISABLE, CINTR, CQUIT, CSUSP, CDSUSP, CSTART, CSTOP, CLNEXT, CDISCARD, CMIN, CTIME, CSTATUS, _POSIX_VDISABLE }; #undef TTYDEFCHARS #endif sys/profil.h000064400000003646151027430550007041 0ustar00/* Copyright (C) 2001-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _PROFIL_H #define _PROFIL_H 1 #include #include #include /* This interface is intended to follow the sprofil() system calls as described by the sprofil(2) man page of Irix v6.5, except that: - there is no a priori limit on number of text sections - pr_scale is declared as unsigned long (instead of "unsigned int") - pr_size is declared as size_t (instead of "unsigned int") - pr_off is declared as void * (instead of "__psunsigned_t") - the overflow bin (pr_base==0, pr_scale==2) can appear anywhere in the profp array - PROF_FAST has no effect */ struct prof { void *pr_base; /* buffer base */ size_t pr_size; /* buffer size */ size_t pr_off; /* pc offset */ unsigned long int pr_scale; /* pc scaling (fixed-point number) */ }; enum { PROF_USHORT = 0, /* use 16-bit counters (default) */ PROF_UINT = 1 << 0, /* use 32-bit counters */ PROF_FAST = 1 << 1 /* profile faster than usual */ }; __BEGIN_DECLS extern int sprofil (struct prof *__profp, int __profcnt, struct timeval *__tvp, unsigned int __flags) __THROW; __END_DECLS #endif /* profil.h */ sys/personality.h000064400000005242151027430550010111 0ustar00/* Copyright (C) 2002-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* Taken verbatim from Linux 2.6 (include/linux/personality.h). */ #ifndef _SYS_PERSONALITY_H #define _SYS_PERSONALITY_H 1 #include /* Flags for bug emulation. These occupy the top three bytes. */ enum { UNAME26 = 0x0020000, ADDR_NO_RANDOMIZE = 0x0040000, FDPIC_FUNCPTRS = 0x0080000, MMAP_PAGE_ZERO = 0x0100000, ADDR_COMPAT_LAYOUT = 0x0200000, READ_IMPLIES_EXEC = 0x0400000, ADDR_LIMIT_32BIT = 0x0800000, SHORT_INODE = 0x1000000, WHOLE_SECONDS = 0x2000000, STICKY_TIMEOUTS = 0x4000000, ADDR_LIMIT_3GB = 0x8000000 }; /* Personality types. These go in the low byte. Avoid using the top bit, it will conflict with error returns. */ enum { PER_LINUX = 0x0000, PER_LINUX_32BIT = 0x0000 | ADDR_LIMIT_32BIT, PER_LINUX_FDPIC = 0x0000 | FDPIC_FUNCPTRS, PER_SVR4 = 0x0001 | STICKY_TIMEOUTS | MMAP_PAGE_ZERO, PER_SVR3 = 0x0002 | STICKY_TIMEOUTS | SHORT_INODE, PER_SCOSVR3 = 0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS | SHORT_INODE, PER_OSR5 = 0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS, PER_WYSEV386 = 0x0004 | STICKY_TIMEOUTS | SHORT_INODE, PER_ISCR4 = 0x0005 | STICKY_TIMEOUTS, PER_BSD = 0x0006, PER_SUNOS = 0x0006 | STICKY_TIMEOUTS, PER_XENIX = 0x0007 | STICKY_TIMEOUTS | SHORT_INODE, PER_LINUX32 = 0x0008, PER_LINUX32_3GB = 0x0008 | ADDR_LIMIT_3GB, PER_IRIX32 = 0x0009 | STICKY_TIMEOUTS, /* IRIX5 32-bit */ PER_IRIXN32 = 0x000a | STICKY_TIMEOUTS, /* IRIX6 new 32-bit */ PER_IRIX64 = 0x000b | STICKY_TIMEOUTS, /* IRIX6 64-bit */ PER_RISCOS = 0x000c, PER_SOLARIS = 0x000d | STICKY_TIMEOUTS, PER_UW7 = 0x000e | STICKY_TIMEOUTS | MMAP_PAGE_ZERO, PER_OSF4 = 0x000f, PER_HPUX = 0x0010, PER_MASK = 0x00ff, }; __BEGIN_DECLS /* Set different ABIs (personalities). */ extern int personality (unsigned long int __persona) __THROW; __END_DECLS #endif /* sys/personality.h */ sys/mount.h000064400000012753151027430550006707 0ustar00/* Header file for mounting/unmount Linux filesystems. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* This is taken from /usr/include/linux/fs.h. */ #ifndef _SYS_MOUNT_H #define _SYS_MOUNT_H 1 #include #include #define BLOCK_SIZE 1024 #define BLOCK_SIZE_BITS 10 /* These are the fs-independent mount-flags: up to 16 flags are supported */ enum { MS_RDONLY = 1, /* Mount read-only. */ #define MS_RDONLY MS_RDONLY MS_NOSUID = 2, /* Ignore suid and sgid bits. */ #define MS_NOSUID MS_NOSUID MS_NODEV = 4, /* Disallow access to device special files. */ #define MS_NODEV MS_NODEV MS_NOEXEC = 8, /* Disallow program execution. */ #define MS_NOEXEC MS_NOEXEC MS_SYNCHRONOUS = 16, /* Writes are synced at once. */ #define MS_SYNCHRONOUS MS_SYNCHRONOUS MS_REMOUNT = 32, /* Alter flags of a mounted FS. */ #define MS_REMOUNT MS_REMOUNT MS_MANDLOCK = 64, /* Allow mandatory locks on an FS. */ #define MS_MANDLOCK MS_MANDLOCK MS_DIRSYNC = 128, /* Directory modifications are synchronous. */ #define MS_DIRSYNC MS_DIRSYNC MS_NOATIME = 1024, /* Do not update access times. */ #define MS_NOATIME MS_NOATIME MS_NODIRATIME = 2048, /* Do not update directory access times. */ #define MS_NODIRATIME MS_NODIRATIME MS_BIND = 4096, /* Bind directory at different place. */ #define MS_BIND MS_BIND MS_MOVE = 8192, #define MS_MOVE MS_MOVE MS_REC = 16384, #define MS_REC MS_REC MS_SILENT = 32768, #define MS_SILENT MS_SILENT MS_POSIXACL = 1 << 16, /* VFS does not apply the umask. */ #define MS_POSIXACL MS_POSIXACL MS_UNBINDABLE = 1 << 17, /* Change to unbindable. */ #define MS_UNBINDABLE MS_UNBINDABLE MS_PRIVATE = 1 << 18, /* Change to private. */ #define MS_PRIVATE MS_PRIVATE MS_SLAVE = 1 << 19, /* Change to slave. */ #define MS_SLAVE MS_SLAVE MS_SHARED = 1 << 20, /* Change to shared. */ #define MS_SHARED MS_SHARED MS_RELATIME = 1 << 21, /* Update atime relative to mtime/ctime. */ #define MS_RELATIME MS_RELATIME MS_KERNMOUNT = 1 << 22, /* This is a kern_mount call. */ #define MS_KERNMOUNT MS_KERNMOUNT MS_I_VERSION = 1 << 23, /* Update inode I_version field. */ #define MS_I_VERSION MS_I_VERSION MS_STRICTATIME = 1 << 24, /* Always perform atime updates. */ #define MS_STRICTATIME MS_STRICTATIME MS_LAZYTIME = 1 << 25, /* Update the on-disk [acm]times lazily. */ #define MS_LAZYTIME MS_LAZYTIME MS_ACTIVE = 1 << 30, #define MS_ACTIVE MS_ACTIVE MS_NOUSER = 1 << 31 #define MS_NOUSER MS_NOUSER }; /* Flags that can be altered by MS_REMOUNT */ #define MS_RMT_MASK (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION \ |MS_LAZYTIME) /* Magic mount flag number. Has to be or-ed to the flag values. */ #define MS_MGC_VAL 0xc0ed0000 /* Magic flag number to indicate "new" flags */ #define MS_MGC_MSK 0xffff0000 /* Magic flag number mask */ /* The read-only stuff doesn't really belong here, but any other place is probably as bad and I don't want to create yet another include file. */ #define BLKROSET _IO(0x12, 93) /* Set device read-only (0 = read-write). */ #define BLKROGET _IO(0x12, 94) /* Get read-only status (0 = read_write). */ #define BLKRRPART _IO(0x12, 95) /* Re-read partition table. */ #define BLKGETSIZE _IO(0x12, 96) /* Return device size. */ #define BLKFLSBUF _IO(0x12, 97) /* Flush buffer cache. */ #define BLKRASET _IO(0x12, 98) /* Set read ahead for block device. */ #define BLKRAGET _IO(0x12, 99) /* Get current read ahead setting. */ #define BLKFRASET _IO(0x12,100) /* Set filesystem read-ahead. */ #define BLKFRAGET _IO(0x12,101) /* Get filesystem read-ahead. */ #define BLKSECTSET _IO(0x12,102) /* Set max sectors per request. */ #define BLKSECTGET _IO(0x12,103) /* Get max sectors per request. */ #define BLKSSZGET _IO(0x12,104) /* Get block device sector size. */ #define BLKBSZGET _IOR(0x12,112,size_t) #define BLKBSZSET _IOW(0x12,113,size_t) #define BLKGETSIZE64 _IOR(0x12,114,size_t) /* return device size. */ /* Possible value for FLAGS parameter of `umount2'. */ enum { MNT_FORCE = 1, /* Force unmounting. */ #define MNT_FORCE MNT_FORCE MNT_DETACH = 2, /* Just detach from the tree. */ #define MNT_DETACH MNT_DETACH MNT_EXPIRE = 4, /* Mark for expiry. */ #define MNT_EXPIRE MNT_EXPIRE UMOUNT_NOFOLLOW = 8 /* Don't follow symlink on umount. */ #define UMOUNT_NOFOLLOW UMOUNT_NOFOLLOW }; __BEGIN_DECLS /* Mount a filesystem. */ extern int mount (const char *__special_file, const char *__dir, const char *__fstype, unsigned long int __rwflag, const void *__data) __THROW; /* Unmount a filesystem. */ extern int umount (const char *__special_file) __THROW; /* Unmount a filesystem. Force unmounting if FLAGS is set to MNT_FORCE. */ extern int umount2 (const char *__special_file, int __flags) __THROW; __END_DECLS #endif /* _SYS_MOUNT_H */ sys/param.h000064400000006114151027430550006637 0ustar00/* Compatibility header for old-style Unix parameters and limits. Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_PARAM_H #define _SYS_PARAM_H 1 #define __need_NULL #include #include #include #include /* Define BYTE_ORDER et al. */ #include /* Define NSIG. */ /* This file defines some things in system-specific ways. */ #include /* BSD names for some values. */ #define NBBY CHAR_BIT #if !defined NGROUPS && defined NGROUPS_MAX # define NGROUPS NGROUPS_MAX #endif #if !defined MAXSYMLINKS && defined SYMLOOP_MAX # define MAXSYMLINKS SYMLOOP_MAX #endif #if !defined CANBSIZ && defined MAX_CANON # define CANBSIZ MAX_CANON #endif #if !defined MAXPATHLEN && defined PATH_MAX # define MAXPATHLEN PATH_MAX #endif #if !defined NOFILE && defined OPEN_MAX # define NOFILE OPEN_MAX #endif #if !defined MAXHOSTNAMELEN && defined HOST_NAME_MAX # define MAXHOSTNAMELEN HOST_NAME_MAX #endif #ifndef NCARGS # ifdef ARG_MAX # define NCARGS ARG_MAX # else /* ARG_MAX is unlimited, but we define NCARGS for BSD programs that want to compare against some fixed limit. */ # define NCARGS INT_MAX # endif #endif /* Magical constants. */ #ifndef NOGROUP # define NOGROUP 65535 /* Marker for empty group set member. */ #endif #ifndef NODEV # define NODEV ((dev_t) -1) /* Non-existent device. */ #endif /* Unit of `st_blocks'. */ #ifndef DEV_BSIZE # define DEV_BSIZE 512 #endif /* Bit map related macros. */ #define setbit(a,i) ((a)[(i)/NBBY] |= 1<<((i)%NBBY)) #define clrbit(a,i) ((a)[(i)/NBBY] &= ~(1<<((i)%NBBY))) #define isset(a,i) ((a)[(i)/NBBY] & (1<<((i)%NBBY))) #define isclr(a,i) (((a)[(i)/NBBY] & (1<<((i)%NBBY))) == 0) /* Macros for counting and rounding. */ #ifndef howmany # define howmany(x, y) (((x) + ((y) - 1)) / (y)) #endif #ifdef __GNUC__ # define roundup(x, y) (__builtin_constant_p (y) && powerof2 (y) \ ? (((x) + (y) - 1) & ~((y) - 1)) \ : ((((x) + ((y) - 1)) / (y)) * (y))) #else # define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) #endif #define powerof2(x) ((((x) - 1) & (x)) == 0) /* Macros for min/max. */ #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) #endif /* sys/param.h */ sys/unistd.h000064400000000024151027430550007037 0ustar00#include sys/sendfile.h000064400000003415151027430550007331 0ustar00/* sendfile -- copy data directly from one file descriptor to another Copyright (C) 1998-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SENDFILE_H #define _SYS_SENDFILE_H 1 #include #include __BEGIN_DECLS /* Send up to COUNT bytes from file associated with IN_FD starting at *OFFSET to descriptor OUT_FD. Set *OFFSET to the IN_FD's file position following the read bytes. If OFFSET is a null pointer, use the normal file position instead. Return the number of written bytes, or -1 in case of error. */ #ifndef __USE_FILE_OFFSET64 extern ssize_t sendfile (int __out_fd, int __in_fd, off_t *__offset, size_t __count) __THROW; #else # ifdef __REDIRECT_NTH extern ssize_t __REDIRECT_NTH (sendfile, (int __out_fd, int __in_fd, __off64_t *__offset, size_t __count), sendfile64); # else # define sendfile sendfile64 # endif #endif #ifdef __USE_LARGEFILE64 extern ssize_t sendfile64 (int __out_fd, int __in_fd, __off64_t *__offset, size_t __count) __THROW; #endif __END_DECLS #endif /* sys/sendfile.h */ sys/kd.h000064400000002127151027430550006135 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_KD_H #define _SYS_KD_H 1 /* Make sure the header is not loaded. */ #ifndef _LINUX_TYPES_H # define _LINUX_TYPES_H 1 # define __undef_LINUX_TYPES_H #endif #include #ifdef __undef_LINUX_TYPES_H # undef _LINUX_TYPES_H # undef __undef_LINUX_TYPES_H #endif #endif /* sys/kd.h */ sys/select.h000064400000010054151027430550007014 0ustar00/* `fd_set' type and related macros, and `select'/`pselect' declarations. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* POSIX 1003.1g: 6.2 Select from File Descriptor Sets */ #ifndef _SYS_SELECT_H #define _SYS_SELECT_H 1 #include /* Get definition of needed basic types. */ #include /* Get __FD_* definitions. */ #include /* Get sigset_t. */ #include /* Get definition of timer specification structures. */ #include #include #ifdef __USE_XOPEN2K # include #endif #ifndef __suseconds_t_defined typedef __suseconds_t suseconds_t; # define __suseconds_t_defined #endif /* The fd_set member is required to be an array of longs. */ typedef long int __fd_mask; /* Some versions of define this macros. */ #undef __NFDBITS /* It's easier to assume 8-bit bytes than to get CHAR_BIT. */ #define __NFDBITS (8 * (int) sizeof (__fd_mask)) #define __FD_ELT(d) ((d) / __NFDBITS) #define __FD_MASK(d) ((__fd_mask) (1UL << ((d) % __NFDBITS))) /* fd_set for select and pselect. */ typedef struct { /* XPG4.2 requires this member name. Otherwise avoid the name from the global namespace. */ #ifdef __USE_XOPEN __fd_mask fds_bits[__FD_SETSIZE / __NFDBITS]; # define __FDS_BITS(set) ((set)->fds_bits) #else __fd_mask __fds_bits[__FD_SETSIZE / __NFDBITS]; # define __FDS_BITS(set) ((set)->__fds_bits) #endif } fd_set; /* Maximum number of file descriptors in `fd_set'. */ #define FD_SETSIZE __FD_SETSIZE #ifdef __USE_MISC /* Sometimes the fd_set member is assumed to have this type. */ typedef __fd_mask fd_mask; /* Number of bits per word of `fd_set' (some code assumes this is 32). */ # define NFDBITS __NFDBITS #endif /* Access macros for `fd_set'. */ #define FD_SET(fd, fdsetp) __FD_SET (fd, fdsetp) #define FD_CLR(fd, fdsetp) __FD_CLR (fd, fdsetp) #define FD_ISSET(fd, fdsetp) __FD_ISSET (fd, fdsetp) #define FD_ZERO(fdsetp) __FD_ZERO (fdsetp) __BEGIN_DECLS /* Check the first NFDS descriptors each in READFDS (if not NULL) for read readiness, in WRITEFDS (if not NULL) for write readiness, and in EXCEPTFDS (if not NULL) for exceptional conditions. If TIMEOUT is not NULL, time out after waiting the interval specified therein. Returns the number of ready descriptors, or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern int select (int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, fd_set *__restrict __exceptfds, struct timeval *__restrict __timeout); #ifdef __USE_XOPEN2K /* Same as above only that the TIMEOUT value is given with higher resolution and a sigmask which is been set temporarily. This version should be used. This function is a cancellation point and therefore not marked with __THROW. */ extern int pselect (int __nfds, fd_set *__restrict __readfds, fd_set *__restrict __writefds, fd_set *__restrict __exceptfds, const struct timespec *__restrict __timeout, const __sigset_t *__restrict __sigmask); #endif /* Define some inlines helping to catch common problems. */ #if __USE_FORTIFY_LEVEL > 0 && defined __GNUC__ # include #endif __END_DECLS #endif /* sys/select.h */ sys/types.h000064400000013120151027430550006676 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * POSIX Standard: 2.6 Primitive System Data Types */ #ifndef _SYS_TYPES_H #define _SYS_TYPES_H 1 #include __BEGIN_DECLS #include #ifdef __USE_MISC # ifndef __u_char_defined typedef __u_char u_char; typedef __u_short u_short; typedef __u_int u_int; typedef __u_long u_long; typedef __quad_t quad_t; typedef __u_quad_t u_quad_t; typedef __fsid_t fsid_t; # define __u_char_defined # endif typedef __loff_t loff_t; #endif #ifndef __ino_t_defined # ifndef __USE_FILE_OFFSET64 typedef __ino_t ino_t; # else typedef __ino64_t ino_t; # endif # define __ino_t_defined #endif #if defined __USE_LARGEFILE64 && !defined __ino64_t_defined typedef __ino64_t ino64_t; # define __ino64_t_defined #endif #ifndef __dev_t_defined typedef __dev_t dev_t; # define __dev_t_defined #endif #ifndef __gid_t_defined typedef __gid_t gid_t; # define __gid_t_defined #endif #ifndef __mode_t_defined typedef __mode_t mode_t; # define __mode_t_defined #endif #ifndef __nlink_t_defined typedef __nlink_t nlink_t; # define __nlink_t_defined #endif #ifndef __uid_t_defined typedef __uid_t uid_t; # define __uid_t_defined #endif #ifndef __off_t_defined # ifndef __USE_FILE_OFFSET64 typedef __off_t off_t; # else typedef __off64_t off_t; # endif # define __off_t_defined #endif #if defined __USE_LARGEFILE64 && !defined __off64_t_defined typedef __off64_t off64_t; # define __off64_t_defined #endif #ifndef __pid_t_defined typedef __pid_t pid_t; # define __pid_t_defined #endif #if (defined __USE_XOPEN || defined __USE_XOPEN2K8) \ && !defined __id_t_defined typedef __id_t id_t; # define __id_t_defined #endif #ifndef __ssize_t_defined typedef __ssize_t ssize_t; # define __ssize_t_defined #endif #ifdef __USE_MISC # ifndef __daddr_t_defined typedef __daddr_t daddr_t; typedef __caddr_t caddr_t; # define __daddr_t_defined # endif #endif #if (defined __USE_MISC || defined __USE_XOPEN) && !defined __key_t_defined typedef __key_t key_t; # define __key_t_defined #endif #if defined __USE_XOPEN || defined __USE_XOPEN2K8 # include #endif #include #include #include #ifdef __USE_XOPEN # ifndef __useconds_t_defined typedef __useconds_t useconds_t; # define __useconds_t_defined # endif # ifndef __suseconds_t_defined typedef __suseconds_t suseconds_t; # define __suseconds_t_defined # endif #endif #define __need_size_t #include #ifdef __USE_MISC /* Old compatibility names for C types. */ typedef unsigned long int ulong; typedef unsigned short int ushort; typedef unsigned int uint; #endif /* These size-specific names are used by some of the inet code. */ #include /* These were defined by ISO C without the first `_'. */ typedef __uint8_t u_int8_t; typedef __uint16_t u_int16_t; typedef __uint32_t u_int32_t; typedef __uint64_t u_int64_t; #if __GNUC_PREREQ (2, 7) typedef int register_t __attribute__ ((__mode__ (__word__))); #else typedef int register_t; #endif /* Some code from BIND tests this macro to see if the types above are defined. */ #define __BIT_TYPES_DEFINED__ 1 #ifdef __USE_MISC /* In BSD is expected to define BYTE_ORDER. */ # include /* It also defines `fd_set' and the FD_* macros for `select'. */ # include #endif /* Use misc. */ #if (defined __USE_UNIX98 || defined __USE_XOPEN2K8) \ && !defined __blksize_t_defined typedef __blksize_t blksize_t; # define __blksize_t_defined #endif /* Types from the Large File Support interface. */ #ifndef __USE_FILE_OFFSET64 # ifndef __blkcnt_t_defined typedef __blkcnt_t blkcnt_t; /* Type to count number of disk blocks. */ # define __blkcnt_t_defined # endif # ifndef __fsblkcnt_t_defined typedef __fsblkcnt_t fsblkcnt_t; /* Type to count file system blocks. */ # define __fsblkcnt_t_defined # endif # ifndef __fsfilcnt_t_defined typedef __fsfilcnt_t fsfilcnt_t; /* Type to count file system inodes. */ # define __fsfilcnt_t_defined # endif #else # ifndef __blkcnt_t_defined typedef __blkcnt64_t blkcnt_t; /* Type to count number of disk blocks. */ # define __blkcnt_t_defined # endif # ifndef __fsblkcnt_t_defined typedef __fsblkcnt64_t fsblkcnt_t; /* Type to count file system blocks. */ # define __fsblkcnt_t_defined # endif # ifndef __fsfilcnt_t_defined typedef __fsfilcnt64_t fsfilcnt_t; /* Type to count file system inodes. */ # define __fsfilcnt_t_defined # endif #endif #ifdef __USE_LARGEFILE64 typedef __blkcnt64_t blkcnt64_t; /* Type to count number of disk blocks. */ typedef __fsblkcnt64_t fsblkcnt64_t; /* Type to count file system blocks. */ typedef __fsfilcnt64_t fsfilcnt64_t; /* Type to count file system inodes. */ #endif /* Now add the thread types. */ #if defined __USE_POSIX199506 || defined __USE_UNIX98 # include #endif __END_DECLS #endif /* sys/types.h */ sys/vt.h000064400000000026151027430550006164 0ustar00#include sys/time.h000064400000015000151027430550006467 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_TIME_H #define _SYS_TIME_H 1 #include #include #include #include #ifndef __suseconds_t_defined typedef __suseconds_t suseconds_t; # define __suseconds_t_defined #endif #include __BEGIN_DECLS #ifdef __USE_GNU /* Macros for converting between `struct timeval' and `struct timespec'. */ # define TIMEVAL_TO_TIMESPEC(tv, ts) { \ (ts)->tv_sec = (tv)->tv_sec; \ (ts)->tv_nsec = (tv)->tv_usec * 1000; \ } # define TIMESPEC_TO_TIMEVAL(tv, ts) { \ (tv)->tv_sec = (ts)->tv_sec; \ (tv)->tv_usec = (ts)->tv_nsec / 1000; \ } #endif #ifdef __USE_MISC /* Structure crudely representing a timezone. This is obsolete and should never be used. */ struct timezone { int tz_minuteswest; /* Minutes west of GMT. */ int tz_dsttime; /* Nonzero if DST is ever in effect. */ }; typedef struct timezone *__restrict __timezone_ptr_t; #else typedef void *__restrict __timezone_ptr_t; #endif /* Get the current time of day and timezone information, putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled. Returns 0 on success, -1 on errors. NOTE: This form of timezone information is obsolete. Use the functions and variables declared in instead. */ extern int gettimeofday (struct timeval *__restrict __tv, __timezone_ptr_t __tz) __THROW __nonnull ((1)); #ifdef __USE_MISC /* Set the current time of day and timezone information. This call is restricted to the super-user. */ extern int settimeofday (const struct timeval *__tv, const struct timezone *__tz) __THROW; /* Adjust the current time of day by the amount in DELTA. If OLDDELTA is not NULL, it is filled in with the amount of time adjustment remaining to be done from the last `adjtime' call. This call is restricted to the super-user. */ extern int adjtime (const struct timeval *__delta, struct timeval *__olddelta) __THROW; #endif /* Values for the first argument to `getitimer' and `setitimer'. */ enum __itimer_which { /* Timers run in real time. */ ITIMER_REAL = 0, #define ITIMER_REAL ITIMER_REAL /* Timers run only when the process is executing. */ ITIMER_VIRTUAL = 1, #define ITIMER_VIRTUAL ITIMER_VIRTUAL /* Timers run when the process is executing and when the system is executing on behalf of the process. */ ITIMER_PROF = 2 #define ITIMER_PROF ITIMER_PROF }; /* Type of the second argument to `getitimer' and the second and third arguments `setitimer'. */ struct itimerval { /* Value to put into `it_value' when the timer expires. */ struct timeval it_interval; /* Time to the next timer expiration. */ struct timeval it_value; }; #if defined __USE_GNU && !defined __cplusplus /* Use the nicer parameter type only in GNU mode and not for C++ since the strict C++ rules prevent the automatic promotion. */ typedef enum __itimer_which __itimer_which_t; #else typedef int __itimer_which_t; #endif /* Set *VALUE to the current setting of timer WHICH. Return 0 on success, -1 on errors. */ extern int getitimer (__itimer_which_t __which, struct itimerval *__value) __THROW; /* Set the timer WHICH to *NEW. If OLD is not NULL, set *OLD to the old value of timer WHICH. Returns 0 on success, -1 on errors. */ extern int setitimer (__itimer_which_t __which, const struct itimerval *__restrict __new, struct itimerval *__restrict __old) __THROW; /* Change the access time of FILE to TVP[0] and the modification time of FILE to TVP[1]. If TVP is a null pointer, use the current time instead. Returns 0 on success, -1 on errors. */ extern int utimes (const char *__file, const struct timeval __tvp[2]) __THROW __nonnull ((1)); #ifdef __USE_MISC /* Same as `utimes', but does not follow symbolic links. */ extern int lutimes (const char *__file, const struct timeval __tvp[2]) __THROW __nonnull ((1)); /* Same as `utimes', but takes an open file descriptor instead of a name. */ extern int futimes (int __fd, const struct timeval __tvp[2]) __THROW; #endif #ifdef __USE_GNU /* Change the access time of FILE relative to FD to TVP[0] and the modification time of FILE to TVP[1]. If TVP is a null pointer, use the current time instead. Returns 0 on success, -1 on errors. */ extern int futimesat (int __fd, const char *__file, const struct timeval __tvp[2]) __THROW; #endif #ifdef __USE_MISC /* Convenience macros for operations on timevals. NOTE: `timercmp' does not work for >= or <=. */ # define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) # define timerclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0) # define timercmp(a, b, CMP) \ (((a)->tv_sec == (b)->tv_sec) ? \ ((a)->tv_usec CMP (b)->tv_usec) : \ ((a)->tv_sec CMP (b)->tv_sec)) # define timeradd(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((result)->tv_usec >= 1000000) \ { \ ++(result)->tv_sec; \ (result)->tv_usec -= 1000000; \ } \ } while (0) # define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif /* Misc. */ __END_DECLS #endif /* sys/time.h */ sys/cdefs.h000064400000050312151027430550006622 0ustar00/* Copyright (C) 1992-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_CDEFS_H #define _SYS_CDEFS_H 1 /* We are almost always included from features.h. */ #ifndef _FEATURES_H # include #endif /* The GNU libc does not support any K&R compilers or the traditional mode of ISO C compilers anymore. Check for some of the combinations not anymore supported. */ #if defined __GNUC__ && !defined __STDC__ # error "You need a ISO C conforming compiler to use the glibc headers" #endif /* Some user header file might have defined this before. */ #undef __P #undef __PMT #ifdef __GNUC__ /* All functions, except those with callbacks or those that synchronize memory, are leaf functions. */ # if __GNUC_PREREQ (4, 6) && !defined _LIBC # define __LEAF , __leaf__ # define __LEAF_ATTR __attribute__ ((__leaf__)) # else # define __LEAF # define __LEAF_ATTR # endif /* GCC can always grok prototypes. For C++ programs we add throw() to help it optimize the function calls. But this works only with gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions as non-throwing using a function attribute since programs can use the -fexceptions options for C code as well. */ # if !defined __cplusplus && __GNUC_PREREQ (3, 3) # define __THROW __attribute__ ((__nothrow__ __LEAF)) # define __THROWNL __attribute__ ((__nothrow__)) # define __NTH(fct) __attribute__ ((__nothrow__ __LEAF)) fct # define __NTHNL(fct) __attribute__ ((__nothrow__)) fct # else # if defined __cplusplus && __GNUC_PREREQ (2,8) # define __THROW throw () # define __THROWNL throw () # define __NTH(fct) __LEAF_ATTR fct throw () # define __NTHNL(fct) fct throw () # else # define __THROW # define __THROWNL # define __NTH(fct) fct # define __NTHNL(fct) fct # endif # endif #else /* Not GCC. */ # if (defined __cplusplus \ || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)) # define __inline inline # else # define __inline /* No inline functions. */ # endif # define __THROW # define __THROWNL # define __NTH(fct) fct #endif /* GCC. */ /* Compilers that are not clang may object to #if defined __clang__ && __has_extension(...) even though they do not need to evaluate the right-hand side of the &&. */ #if defined __clang__ && defined __has_extension # define __glibc_clang_has_extension(ext) __has_extension (ext) #else # define __glibc_clang_has_extension(ext) 0 #endif /* These two macros are not used in glibc anymore. They are kept here only because some other projects expect the macros to be defined. */ #define __P(args) args #define __PMT(args) args /* For these things, GCC behaves the ANSI way normally, and the non-ANSI way under -traditional. */ #define __CONCAT(x,y) x ## y #define __STRING(x) #x /* This is not a typedef so `const __ptr_t' does the right thing. */ #define __ptr_t void * /* C++ needs to know that types and declarations are C, not C++. */ #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS # define __END_DECLS #endif /* Fortify support. */ #define __bos(ptr) __builtin_object_size (ptr, __USE_FORTIFY_LEVEL > 1) #define __bos0(ptr) __builtin_object_size (ptr, 0) /* Use __builtin_dynamic_object_size at _FORTIFY_SOURCE=3 when available. */ #if __USE_FORTIFY_LEVEL == 3 && (__glibc_clang_prereq (9, 0) \ || __GNUC_PREREQ (12, 0)) # define __glibc_objsize0(__o) __builtin_dynamic_object_size (__o, 0) # define __glibc_objsize(__o) __builtin_dynamic_object_size (__o, 1) #else # define __glibc_objsize0(__o) __bos0 (__o) # define __glibc_objsize(__o) __bos (__o) #endif #if __USE_FORTIFY_LEVEL > 0 /* Compile time conditions to choose between the regular, _chk and _chk_warn variants. These conditions should get evaluated to constant and optimized away. */ #define __glibc_safe_len_cond(__l, __s, __osz) ((__l) <= (__osz) / (__s)) #define __glibc_unsigned_or_positive(__l) \ ((__typeof (__l)) 0 < (__typeof (__l)) -1 \ || (__builtin_constant_p (__l) && (__l) > 0)) /* Length is known to be safe at compile time if the __L * __S <= __OBJSZ condition can be folded to a constant and if it is true, or unknown (-1) */ #define __glibc_safe_or_unknown_len(__l, __s, __osz) \ ((__builtin_constant_p (__osz) && (__osz) == (__SIZE_TYPE__) -1) \ || (__glibc_unsigned_or_positive (__l) \ && __builtin_constant_p (__glibc_safe_len_cond ((__SIZE_TYPE__) (__l), \ (__s), (__osz))) \ && __glibc_safe_len_cond ((__SIZE_TYPE__) (__l), (__s), (__osz)))) /* Conversely, we know at compile time that the length is unsafe if the __L * __S <= __OBJSZ condition can be folded to a constant and if it is false. */ #define __glibc_unsafe_len(__l, __s, __osz) \ (__glibc_unsigned_or_positive (__l) \ && __builtin_constant_p (__glibc_safe_len_cond ((__SIZE_TYPE__) (__l), \ __s, __osz)) \ && !__glibc_safe_len_cond ((__SIZE_TYPE__) (__l), __s, __osz)) /* Fortify function f. __f_alias, __f_chk and __f_chk_warn must be declared. */ #define __glibc_fortify(f, __l, __s, __osz, ...) \ (__glibc_safe_or_unknown_len (__l, __s, __osz) \ ? __ ## f ## _alias (__VA_ARGS__) \ : (__glibc_unsafe_len (__l, __s, __osz) \ ? __ ## f ## _chk_warn (__VA_ARGS__, __osz) \ : __ ## f ## _chk (__VA_ARGS__, __osz))) /* Fortify function f, where object size argument passed to f is the number of elements and not total size. */ #define __glibc_fortify_n(f, __l, __s, __osz, ...) \ (__glibc_safe_or_unknown_len (__l, __s, __osz) \ ? __ ## f ## _alias (__VA_ARGS__) \ : (__glibc_unsafe_len (__l, __s, __osz) \ ? __ ## f ## _chk_warn (__VA_ARGS__, (__osz) / (__s)) \ : __ ## f ## _chk (__VA_ARGS__, (__osz) / (__s)))) #endif #if __GNUC_PREREQ (4,3) # define __warndecl(name, msg) \ extern void name (void) __attribute__((__warning__ (msg))) # define __warnattr(msg) __attribute__((__warning__ (msg))) # define __errordecl(name, msg) \ extern void name (void) __attribute__((__error__ (msg))) #else # define __warndecl(name, msg) extern void name (void) # define __warnattr(msg) # define __errordecl(name, msg) extern void name (void) #endif /* Support for flexible arrays. Headers that should use flexible arrays only if they're "real" (e.g. only if they won't affect sizeof()) should test #if __glibc_c99_flexarr_available. */ #if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L # define __flexarr [] # define __glibc_c99_flexarr_available 1 #elif __GNUC_PREREQ (2,97) /* GCC 2.97 supports C99 flexible array members as an extension, even when in C89 mode or compiling C++ (any version). */ # define __flexarr [] # define __glibc_c99_flexarr_available 1 #elif defined __GNUC__ /* Pre-2.97 GCC did not support C99 flexible arrays but did have an equivalent extension with slightly different notation. */ # define __flexarr [0] # define __glibc_c99_flexarr_available 1 #else /* Some other non-C99 compiler. Approximate with [1]. */ # define __flexarr [1] # define __glibc_c99_flexarr_available 0 #endif /* __asm__ ("xyz") is used throughout the headers to rename functions at the assembly language level. This is wrapped by the __REDIRECT macro, in order to support compilers that can do this some other way. When compilers don't support asm-names at all, we have to do preprocessor tricks instead (which don't have exactly the right semantics, but it's the best we can do). Example: int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */ #if defined __GNUC__ && __GNUC__ >= 2 # define __REDIRECT(name, proto, alias) name proto __asm__ (__ASMNAME (#alias)) # ifdef __cplusplus # define __REDIRECT_NTH(name, proto, alias) \ name proto __THROW __asm__ (__ASMNAME (#alias)) # define __REDIRECT_NTHNL(name, proto, alias) \ name proto __THROWNL __asm__ (__ASMNAME (#alias)) # else # define __REDIRECT_NTH(name, proto, alias) \ name proto __asm__ (__ASMNAME (#alias)) __THROW # define __REDIRECT_NTHNL(name, proto, alias) \ name proto __asm__ (__ASMNAME (#alias)) __THROWNL # endif # define __ASMNAME(cname) __ASMNAME2 (__USER_LABEL_PREFIX__, cname) # define __ASMNAME2(prefix, cname) __STRING (prefix) cname /* #elif __SOME_OTHER_COMPILER__ # define __REDIRECT(name, proto, alias) name proto; \ _Pragma("let " #name " = " #alias) */ #endif /* GCC has various useful declarations that can be made with the `__attribute__' syntax. All of the ways we use this do fine if they are omitted for compilers that don't understand it. */ #if !defined __GNUC__ || __GNUC__ < 2 # define __attribute__(xyz) /* Ignore */ #endif /* At some point during the gcc 2.96 development the `malloc' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #if __GNUC_PREREQ (2,96) # define __attribute_malloc__ __attribute__ ((__malloc__)) #else # define __attribute_malloc__ /* Ignore */ #endif /* Tell the compiler which arguments to an allocation function indicate the size of the allocation. */ #if __GNUC_PREREQ (4, 3) # define __attribute_alloc_size__(params) \ __attribute__ ((__alloc_size__ params)) #else # define __attribute_alloc_size__(params) /* Ignore. */ #endif /* At some point during the gcc 2.96 development the `pure' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #if __GNUC_PREREQ (2,96) # define __attribute_pure__ __attribute__ ((__pure__)) #else # define __attribute_pure__ /* Ignore */ #endif /* This declaration tells the compiler that the value is constant. */ #if __GNUC_PREREQ (2,5) # define __attribute_const__ __attribute__ ((__const__)) #else # define __attribute_const__ /* Ignore */ #endif /* At some point during the gcc 3.1 development the `used' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #if __GNUC_PREREQ (3,1) # define __attribute_used__ __attribute__ ((__used__)) # define __attribute_noinline__ __attribute__ ((__noinline__)) #else # define __attribute_used__ __attribute__ ((__unused__)) # define __attribute_noinline__ /* Ignore */ #endif /* Since version 3.2, gcc allows marking deprecated functions. */ #if __GNUC_PREREQ (3,2) # define __attribute_deprecated__ __attribute__ ((__deprecated__)) #else # define __attribute_deprecated__ /* Ignore */ #endif /* Since version 4.5, gcc also allows one to specify the message printed when a deprecated function is used. clang claims to be gcc 4.2, but may also support this feature. */ #if __GNUC_PREREQ (4,5) || \ __glibc_clang_has_extension (__attribute_deprecated_with_message__) # define __attribute_deprecated_msg__(msg) \ __attribute__ ((__deprecated__ (msg))) #else # define __attribute_deprecated_msg__(msg) __attribute_deprecated__ #endif /* At some point during the gcc 2.8 development the `format_arg' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. If several `format_arg' attributes are given for the same function, in gcc-3.0 and older, all but the last one are ignored. In newer gccs, all designated arguments are considered. */ #if __GNUC_PREREQ (2,8) # define __attribute_format_arg__(x) __attribute__ ((__format_arg__ (x))) #else # define __attribute_format_arg__(x) /* Ignore */ #endif /* At some point during the gcc 2.97 development the `strfmon' format attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #if __GNUC_PREREQ (2,97) # define __attribute_format_strfmon__(a,b) \ __attribute__ ((__format__ (__strfmon__, a, b))) #else # define __attribute_format_strfmon__(a,b) /* Ignore */ #endif /* The nonull function attribute allows to mark pointer parameters which must not be NULL. */ #if __GNUC_PREREQ (3,3) # define __nonnull(params) __attribute__ ((__nonnull__ params)) #else # define __nonnull(params) #endif /* If fortification mode, we warn about unused results of certain function calls which can lead to problems. */ #if __GNUC_PREREQ (3,4) # define __attribute_warn_unused_result__ \ __attribute__ ((__warn_unused_result__)) # if __USE_FORTIFY_LEVEL > 0 # define __wur __attribute_warn_unused_result__ # endif #else # define __attribute_warn_unused_result__ /* empty */ #endif #ifndef __wur # define __wur /* Ignore */ #endif /* Forces a function to be always inlined. */ #if __GNUC_PREREQ (3,2) /* The Linux kernel defines __always_inline in stddef.h (283d7573), and it conflicts with this definition. Therefore undefine it first to allow either header to be included first. */ # undef __always_inline # define __always_inline __inline __attribute__ ((__always_inline__)) #else # undef __always_inline # define __always_inline __inline #endif /* Associate error messages with the source location of the call site rather than with the source location inside the function. */ #if __GNUC_PREREQ (4,3) # define __attribute_artificial__ __attribute__ ((__artificial__)) #else # define __attribute_artificial__ /* Ignore */ #endif /* GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99 inline semantics, unless -fgnu89-inline is used. Using __GNUC_STDC_INLINE__ or __GNUC_GNU_INLINE is not a good enough check for gcc because gcc versions older than 4.3 may define these macros and still not guarantee GNU inlining semantics. clang++ identifies itself as gcc-4.2, but has support for GNU inlining semantics, that can be checked fot by using the __GNUC_STDC_INLINE_ and __GNUC_GNU_INLINE__ macro definitions. */ #if (!defined __cplusplus || __GNUC_PREREQ (4,3) \ || (defined __clang__ && (defined __GNUC_STDC_INLINE__ \ || defined __GNUC_GNU_INLINE__))) # if defined __GNUC_STDC_INLINE__ || defined __cplusplus # define __extern_inline extern __inline __attribute__ ((__gnu_inline__)) # define __extern_always_inline \ extern __always_inline __attribute__ ((__gnu_inline__)) # else # define __extern_inline extern __inline # define __extern_always_inline extern __always_inline # endif #endif #ifdef __extern_always_inline # define __fortify_function __extern_always_inline __attribute_artificial__ #endif /* GCC 4.3 and above allow passing all anonymous arguments of an __extern_always_inline function to some other vararg function. */ #if __GNUC_PREREQ (4,3) # define __va_arg_pack() __builtin_va_arg_pack () # define __va_arg_pack_len() __builtin_va_arg_pack_len () #endif /* It is possible to compile containing GCC extensions even if GCC is run in pedantic mode if the uses are carefully marked using the `__extension__' keyword. But this is not generally available before version 2.8. */ #if !__GNUC_PREREQ (2,8) # define __extension__ /* Ignore */ #endif /* __restrict is known in EGCS 1.2 and above. */ #if !__GNUC_PREREQ (2,92) # if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L # define __restrict restrict # else # define __restrict /* Ignore */ # endif #endif /* ISO C99 also allows to declare arrays as non-overlapping. The syntax is array_name[restrict] GCC 3.1 supports this. */ #if __GNUC_PREREQ (3,1) && !defined __GNUG__ # define __restrict_arr __restrict #else # ifdef __GNUC__ # define __restrict_arr /* Not supported in old GCC. */ # else # if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L # define __restrict_arr restrict # else /* Some other non-C99 compiler. */ # define __restrict_arr /* Not supported. */ # endif # endif #endif #if __GNUC__ >= 3 # define __glibc_unlikely(cond) __builtin_expect ((cond), 0) # define __glibc_likely(cond) __builtin_expect ((cond), 1) #else # define __glibc_unlikely(cond) (cond) # define __glibc_likely(cond) (cond) #endif #ifdef __has_attribute # define __glibc_has_attribute(attr) __has_attribute (attr) #else # define __glibc_has_attribute(attr) 0 #endif #if (!defined _Noreturn \ && (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) < 201112 \ && !__GNUC_PREREQ (4,7)) # if __GNUC_PREREQ (2,8) # define _Noreturn __attribute__ ((__noreturn__)) # else # define _Noreturn # endif #endif #if __GNUC_PREREQ (8, 0) /* Describes a char array whose address can safely be passed as the first argument to strncpy and strncat, as the char array is not necessarily a NUL-terminated string. */ # define __attribute_nonstring__ __attribute__ ((__nonstring__)) #else # define __attribute_nonstring__ #endif #if (!defined _Static_assert && !defined __cplusplus \ && (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) < 201112 \ && (!__GNUC_PREREQ (4, 6) || defined __STRICT_ANSI__)) # define _Static_assert(expr, diagnostic) \ extern int (*__Static_assert_function (void)) \ [!!sizeof (struct { int __error_if_negative: (expr) ? 2 : -1; })] #endif #include #include #if defined __LONG_DOUBLE_MATH_OPTIONAL && defined __NO_LONG_DOUBLE_MATH # define __LDBL_COMPAT 1 # ifdef __REDIRECT # define __LDBL_REDIR1(name, proto, alias) __REDIRECT (name, proto, alias) # define __LDBL_REDIR(name, proto) \ __LDBL_REDIR1 (name, proto, __nldbl_##name) # define __LDBL_REDIR1_NTH(name, proto, alias) __REDIRECT_NTH (name, proto, alias) # define __LDBL_REDIR_NTH(name, proto) \ __LDBL_REDIR1_NTH (name, proto, __nldbl_##name) # define __LDBL_REDIR1_DECL(name, alias) \ extern __typeof (name) name __asm (__ASMNAME (#alias)); # define __LDBL_REDIR_DECL(name) \ extern __typeof (name) name __asm (__ASMNAME ("__nldbl_" #name)); # define __REDIRECT_LDBL(name, proto, alias) \ __LDBL_REDIR1 (name, proto, __nldbl_##alias) # define __REDIRECT_NTH_LDBL(name, proto, alias) \ __LDBL_REDIR1_NTH (name, proto, __nldbl_##alias) # endif #endif #if !defined __LDBL_COMPAT || !defined __REDIRECT # define __LDBL_REDIR1(name, proto, alias) name proto # define __LDBL_REDIR(name, proto) name proto # define __LDBL_REDIR1_NTH(name, proto, alias) name proto __THROW # define __LDBL_REDIR_NTH(name, proto) name proto __THROW # define __LDBL_REDIR_DECL(name) # ifdef __REDIRECT # define __REDIRECT_LDBL(name, proto, alias) __REDIRECT (name, proto, alias) # define __REDIRECT_NTH_LDBL(name, proto, alias) \ __REDIRECT_NTH (name, proto, alias) # endif #endif /* __glibc_macro_warning (MESSAGE) issues warning MESSAGE. This is intended for use in preprocessor macros. Note: MESSAGE must be a _single_ string; concatenation of string literals is not supported. */ #if __GNUC_PREREQ (4,8) || __glibc_clang_prereq (3,5) # define __glibc_macro_warning1(message) _Pragma (#message) # define __glibc_macro_warning(message) \ __glibc_macro_warning1 (GCC warning message) #else # define __glibc_macro_warning(msg) #endif /* Generic selection (ISO C11) is a C-only feature, available in GCC since version 4.9. Previous versions do not provide generic selection, even though they might set __STDC_VERSION__ to 201112L, when in -std=c11 mode. Thus, we must check for !defined __GNUC__ when testing __STDC_VERSION__ for generic selection support. On the other hand, Clang also defines __GNUC__, so a clang-specific check is required to enable the use of generic selection. */ #if !defined __cplusplus \ && (__GNUC_PREREQ (4, 9) \ || __glibc_clang_has_extension (c_generic_selections) \ || (!defined __GNUC__ && defined __STDC_VERSION__ \ && __STDC_VERSION__ >= 201112L)) # define __HAVE_GENERIC_SELECTION 1 #else # define __HAVE_GENERIC_SELECTION 0 #endif #endif /* sys/cdefs.h */ sys/timex.h000064400000004235151027430550006667 0ustar00/* Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_TIMEX_H #define _SYS_TIMEX_H 1 #include #include /* These definitions from linux/timex.h as of 2.6.30. */ #include #define NTP_API 4 /* NTP API version */ struct ntptimeval { struct timeval time; /* current time (ro) */ long int maxerror; /* maximum error (us) (ro) */ long int esterror; /* estimated error (us) (ro) */ long int tai; /* TAI offset (ro) */ long int __glibc_reserved1; long int __glibc_reserved2; long int __glibc_reserved3; long int __glibc_reserved4; }; /* Clock states (time_state) */ #define TIME_OK 0 /* clock synchronized, no leap second */ #define TIME_INS 1 /* insert leap second */ #define TIME_DEL 2 /* delete leap second */ #define TIME_OOP 3 /* leap second in progress */ #define TIME_WAIT 4 /* leap second has occurred */ #define TIME_ERROR 5 /* clock not synchronized */ #define TIME_BAD TIME_ERROR /* bw compat */ /* Maximum time constant of the PLL. */ #define MAXTC 6 __BEGIN_DECLS extern int __adjtimex (struct timex *__ntx) __THROW; extern int adjtimex (struct timex *__ntx) __THROW; #ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (ntp_gettime, (struct ntptimeval *__ntv), ntp_gettimex); #else extern int ntp_gettimex (struct ntptimeval *__ntv) __THROW; # define ntp_gettime ntp_gettimex #endif extern int ntp_adjtime (struct timex *__tntx) __THROW; __END_DECLS #endif /* sys/timex.h */ sys/capability.h000064400000016101151027430550007655 0ustar00/* * * * Copyright (C) 1997 Aleph One * Copyright (C) 1997,8, 2008,19,20 Andrew G. Morgan * * defunct POSIX.1e Standard: 25.2 Capabilities */ #ifndef _SYS_CAPABILITY_H #define _SYS_CAPABILITY_H #ifdef __cplusplus extern "C" { #endif /* * This file complements the kernel file by providing prototype * information for the user library. */ #include #include #include #ifndef __user #define __user #endif #include /* * POSIX capability types */ /* * Opaque capability handle (defined internally by libcap) * internal capability representation */ typedef struct _cap_struct *cap_t; /* "external" capability representation is a (void *) */ /* * This is the type used to identify capabilities */ typedef int cap_value_t; /* * libcap initialized first unnamed capability of the running kernel. * capsh includes a runtime test to flag when this is larger than * what is known to libcap... Time for a new libcap release! */ extern cap_value_t cap_max_bits(void); /* * Set identifiers */ typedef enum { CAP_EFFECTIVE = 0, /* Specifies the effective flag */ CAP_PERMITTED = 1, /* Specifies the permitted flag */ CAP_INHERITABLE = 2 /* Specifies the inheritable flag */ } cap_flag_t; typedef enum { CAP_IAB_INH = 2, CAP_IAB_AMB = 3, CAP_IAB_BOUND = 4 } cap_iab_vector_t; /* * An opaque generalization of the inheritable bits that includes both * what ambient bits to raise and what bounding bits to *lower* (aka * drop). None of these bits once set, using cap_iab_set(), affect * the running process but are consulted, through the execve() system * call, by the kernel. Note, the ambient bits ('A') of the running * process are fragile with respect to other aspects of the "posix" * (cap_t) operations: most importantly, 'A' cannot ever hold bits not * present in the intersection of 'pI' and 'pP'. The kernel * immediately drops all ambient caps whenever such a situation * arises. Typically, the ambient bits are used to support a naive * capability inheritance model - at odds with the POSIX (sic) model * of inheritance where inherited (pI) capabilities need to also be * wanted by the executed binary (fI) in order to become raised * through exec. */ typedef struct cap_iab_s *cap_iab_t; /* * These are the states available to each capability */ typedef enum { CAP_CLEAR=0, /* The flag is cleared/disabled */ CAP_SET=1 /* The flag is set/enabled */ } cap_flag_value_t; /* * User-space capability manipulation routines */ typedef unsigned cap_mode_t; #define CAP_MODE_UNCERTAIN ((cap_mode_t) 0) #define CAP_MODE_NOPRIV ((cap_mode_t) 1) #define CAP_MODE_PURE1E_INIT ((cap_mode_t) 2) #define CAP_MODE_PURE1E ((cap_mode_t) 3) /* libcap/cap_alloc.c */ extern cap_t cap_dup(cap_t); extern int cap_free(void *); extern cap_t cap_init(void); extern cap_iab_t cap_iab_init(void); /* libcap/cap_flag.c */ extern int cap_get_flag(cap_t, cap_value_t, cap_flag_t, cap_flag_value_t *); extern int cap_set_flag(cap_t, cap_flag_t, int, const cap_value_t *, cap_flag_value_t); extern int cap_clear(cap_t); extern int cap_clear_flag(cap_t, cap_flag_t); extern cap_flag_value_t cap_iab_get_vector(cap_iab_t, cap_iab_vector_t, cap_value_t); extern int cap_iab_set_vector(cap_iab_t, cap_iab_vector_t, cap_value_t, cap_flag_value_t); extern int cap_iab_fill(cap_iab_t, cap_iab_vector_t, cap_t, cap_flag_t); /* libcap/cap_file.c */ extern cap_t cap_get_fd(int); extern cap_t cap_get_file(const char *); extern uid_t cap_get_nsowner(cap_t); extern int cap_set_fd(int, cap_t); extern int cap_set_file(const char *, cap_t); extern int cap_set_nsowner(cap_t, uid_t); /* libcap/cap_proc.c */ extern cap_t cap_get_proc(void); extern cap_t cap_get_pid(pid_t); extern int cap_set_proc(cap_t); extern int cap_get_bound(cap_value_t); extern int cap_drop_bound(cap_value_t); #define CAP_IS_SUPPORTED(cap) (cap_get_bound(cap) >= 0) extern int cap_get_ambient(cap_value_t); extern int cap_set_ambient(cap_value_t, cap_flag_value_t); extern int cap_reset_ambient(void); #define CAP_AMBIENT_SUPPORTED() (cap_get_ambient(CAP_CHOWN) >= 0) /* libcap/cap_extint.c */ extern ssize_t cap_size(cap_t); extern ssize_t cap_copy_ext(void *, cap_t, ssize_t); extern cap_t cap_copy_int(const void *); /* libcap/cap_text.c */ extern cap_t cap_from_text(const char *); extern char * cap_to_text(cap_t, ssize_t *); extern int cap_from_name(const char *, cap_value_t *); extern char * cap_to_name(cap_value_t); extern char * cap_iab_to_text(cap_iab_t iab); extern cap_iab_t cap_iab_from_text(const char *text); #define CAP_DIFFERS(result, flag) (((result) & (1 << (flag))) != 0) extern int cap_compare(cap_t, cap_t); /* libcap/cap_proc.c */ extern void cap_set_syscall(long int (*new_syscall)(long int, long int, long int, long int), long int (*new_syscall6)(long int, long int, long int, long int, long int, long int, long int)); extern int cap_set_mode(cap_mode_t flavor); extern cap_mode_t cap_get_mode(void); extern const char *cap_mode_name(cap_mode_t flavor); extern unsigned cap_get_secbits(void); extern int cap_set_secbits(unsigned bits); extern int cap_prctl(long int pr_cmd, long int arg1, long int arg2, long int arg3, long int arg4, long int arg5); extern int cap_prctlw(long int pr_cmd, long int arg1, long int arg2, long int arg3, long int arg4, long int arg5); extern int cap_setuid(uid_t uid); extern int cap_setgroups(gid_t gid, size_t ngroups, const gid_t groups[]); extern cap_iab_t cap_iab_get_proc(void); extern int cap_iab_set_proc(cap_iab_t iab); typedef struct cap_launch_s *cap_launch_t; extern cap_launch_t cap_new_launcher(const char *arg0, const char * const *argv, const char * const *envp); extern void cap_launcher_callback(cap_launch_t attr, int (callback_fn)(void *detail)); extern void cap_launcher_setuid(cap_launch_t attr, uid_t uid); extern void cap_launcher_setgroups(cap_launch_t attr, gid_t gid, int ngroups, const gid_t *groups); extern void cap_launcher_set_mode(cap_launch_t attr, cap_mode_t flavor); extern cap_iab_t cap_launcher_set_iab(cap_launch_t attr, cap_iab_t iab); extern void cap_launcher_set_chroot(cap_launch_t attr, const char *chroot); extern pid_t cap_launch(cap_launch_t attr, void *data); /* * system calls - look to libc for function to system call * mapping. Note, libcap does not use capset directly, but permits the * cap_set_syscall() to redirect the system call function. */ extern int capget(cap_user_header_t header, cap_user_data_t data); extern int capset(cap_user_header_t header, const cap_user_data_t data); /* deprecated - use cap_get_pid() */ extern int capgetp(pid_t pid, cap_t cap_d); /* not valid with filesystem capability support - use cap_set_proc() */ extern int capsetp(pid_t pid, cap_t cap_d); #ifdef __cplusplus } #endif #endif /* _SYS_CAPABILITY_H */ sys/un.h000064400000002654151027430550006166 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_UN_H #define _SYS_UN_H 1 #include /* Get the definition of the macro to define the common sockaddr members. */ #include __BEGIN_DECLS /* Structure describing the address of an AF_LOCAL (aka AF_UNIX) socket. */ struct sockaddr_un { __SOCKADDR_COMMON (sun_); char sun_path[108]; /* Path name. */ }; #ifdef __USE_MISC # include /* For prototype of `strlen'. */ /* Evaluate to actual length of the `sockaddr_un' structure. */ # define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \ + strlen ((ptr)->sun_path)) #endif __END_DECLS #endif /* sys/un.h */ sys/mman.h000064400000012657151027430550006500 0ustar00/* Definitions for BSD-style memory management. Copyright (C) 1994-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_MMAN_H #define _SYS_MMAN_H 1 #include #include #define __need_size_t #include #ifndef __off_t_defined # ifndef __USE_FILE_OFFSET64 typedef __off_t off_t; # else typedef __off64_t off_t; # endif # define __off_t_defined #endif #ifndef __mode_t_defined typedef __mode_t mode_t; # define __mode_t_defined #endif #include /* Return value of `mmap' in case of an error. */ #define MAP_FAILED ((void *) -1) __BEGIN_DECLS /* Map addresses starting near ADDR and extending for LEN bytes. from OFFSET into the file FD describes according to PROT and FLAGS. If ADDR is nonzero, it is the desired mapping address. If the MAP_FIXED bit is set in FLAGS, the mapping will be at ADDR exactly (which must be page-aligned); otherwise the system chooses a convenient nearby address. The return value is the actual mapping address chosen or MAP_FAILED for errors (in which case `errno' is set). A successful `mmap' call deallocates any previous mapping for the affected region. */ #ifndef __USE_FILE_OFFSET64 extern void *mmap (void *__addr, size_t __len, int __prot, int __flags, int __fd, __off_t __offset) __THROW; #else # ifdef __REDIRECT_NTH extern void * __REDIRECT_NTH (mmap, (void *__addr, size_t __len, int __prot, int __flags, int __fd, __off64_t __offset), mmap64); # else # define mmap mmap64 # endif #endif #ifdef __USE_LARGEFILE64 extern void *mmap64 (void *__addr, size_t __len, int __prot, int __flags, int __fd, __off64_t __offset) __THROW; #endif /* Deallocate any mapping for the region starting at ADDR and extending LEN bytes. Returns 0 if successful, -1 for errors (and sets errno). */ extern int munmap (void *__addr, size_t __len) __THROW; /* Change the memory protection of the region starting at ADDR and extending LEN bytes to PROT. Returns 0 if successful, -1 for errors (and sets errno). */ extern int mprotect (void *__addr, size_t __len, int __prot) __THROW; /* Synchronize the region starting at ADDR and extending LEN bytes with the file it maps. Filesystem operations on a file being mapped are unpredictable before this is done. Flags are from the MS_* set. This function is a cancellation point and therefore not marked with __THROW. */ extern int msync (void *__addr, size_t __len, int __flags); #ifdef __USE_MISC /* Advise the system about particular usage patterns the program follows for the region starting at ADDR and extending LEN bytes. */ extern int madvise (void *__addr, size_t __len, int __advice) __THROW; #endif #ifdef __USE_XOPEN2K /* This is the POSIX name for this function. */ extern int posix_madvise (void *__addr, size_t __len, int __advice) __THROW; #endif /* Guarantee all whole pages mapped by the range [ADDR,ADDR+LEN) to be memory resident. */ extern int mlock (const void *__addr, size_t __len) __THROW; /* Unlock whole pages previously mapped by the range [ADDR,ADDR+LEN). */ extern int munlock (const void *__addr, size_t __len) __THROW; /* Cause all currently mapped pages of the process to be memory resident until unlocked by a call to the `munlockall', until the process exits, or until the process calls `execve'. */ extern int mlockall (int __flags) __THROW; /* All currently mapped pages of the process' address space become unlocked. */ extern int munlockall (void) __THROW; #ifdef __USE_MISC /* mincore returns the memory residency status of the pages in the current process's address space specified by [start, start + len). The status is returned in a vector of bytes. The least significant bit of each byte is 1 if the referenced page is in memory, otherwise it is zero. */ extern int mincore (void *__start, size_t __len, unsigned char *__vec) __THROW; #endif #ifdef __USE_GNU /* Remap pages mapped by the range [ADDR,ADDR+OLD_LEN) to new length NEW_LEN. If MREMAP_MAYMOVE is set in FLAGS the returned address may differ from ADDR. If MREMAP_FIXED is set in FLAGS the function takes another parameter which is a fixed address at which the block resides after a successful call. */ extern void *mremap (void *__addr, size_t __old_len, size_t __new_len, int __flags, ...) __THROW; /* Remap arbitrary pages of a shared backing store within an existing VMA. */ extern int remap_file_pages (void *__start, size_t __size, int __prot, size_t __pgoff, int __flags) __THROW; #endif /* Open shared memory segment. */ extern int shm_open (const char *__name, int __oflag, mode_t __mode); /* Remove shared memory segment. */ extern int shm_unlink (const char *__name); __END_DECLS #endif /* sys/mman.h */ sys/fanotify.h000064400000002413151027430550007354 0ustar00/* Copyright (C) 2010-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_FANOTIFY_H #define _SYS_FANOTIFY_H 1 #include #include __BEGIN_DECLS /* Create and initialize fanotify group. */ extern int fanotify_init (unsigned int __flags, unsigned int __event_f_flags) __THROW; /* Add, remove, or modify an fanotify mark on a filesystem object. */ extern int fanotify_mark (int __fanotify_fd, unsigned int __flags, uint64_t __mask, int __dfd, const char *__pathname) __THROW; __END_DECLS #endif /* sys/fanotify.h */ sys/procfs.h000064400000011571151027430550007036 0ustar00/* Copyright (C) 2001-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_PROCFS_H #define _SYS_PROCFS_H 1 /* This is somewhat modelled after the file of the same name on SVR4 systems. It provides a definition of the core file format for ELF used on Linux. It doesn't have anything to do with the /proc file system, even though Linux has one. Anyway, the whole purpose of this file is for GDB and GDB only. Don't read too much into it. Don't use it for anything other than GDB unless you know what you are doing. */ #include #include #include #include __BEGIN_DECLS /* Type for a general-purpose register. */ #ifdef __x86_64__ __extension__ typedef unsigned long long elf_greg_t; #else typedef unsigned long elf_greg_t; #endif /* And the whole bunch of them. We could have used `struct user_regs_struct' directly in the typedef, but tradition says that the register set is an array, which does have some peculiar semantics, so leave it that way. */ #define ELF_NGREG (sizeof (struct user_regs_struct) / sizeof(elf_greg_t)) typedef elf_greg_t elf_gregset_t[ELF_NGREG]; #ifndef __x86_64__ /* Register set for the floating-point registers. */ typedef struct user_fpregs_struct elf_fpregset_t; /* Register set for the extended floating-point registers. Includes the Pentium III SSE registers in addition to the classic floating-point stuff. */ typedef struct user_fpxregs_struct elf_fpxregset_t; #else /* Register set for the extended floating-point registers. Includes the Pentium III SSE registers in addition to the classic floating-point stuff. */ typedef struct user_fpregs_struct elf_fpregset_t; #endif /* Signal info. */ struct elf_siginfo { int si_signo; /* Signal number. */ int si_code; /* Extra code. */ int si_errno; /* Errno. */ }; /* Definitions to generate Intel SVR4-like core files. These mostly have the same names as the SVR4 types with "elf_" tacked on the front to prevent clashes with Linux definitions, and the typedef forms have been avoided. This is mostly like the SVR4 structure, but more Linuxy, with things that Linux does not support and which GDB doesn't really use excluded. */ struct elf_prstatus { struct elf_siginfo pr_info; /* Info associated with signal. */ short int pr_cursig; /* Current signal. */ unsigned long int pr_sigpend; /* Set of pending signals. */ unsigned long int pr_sighold; /* Set of held signals. */ __pid_t pr_pid; __pid_t pr_ppid; __pid_t pr_pgrp; __pid_t pr_sid; struct timeval pr_utime; /* User time. */ struct timeval pr_stime; /* System time. */ struct timeval pr_cutime; /* Cumulative user time. */ struct timeval pr_cstime; /* Cumulative system time. */ elf_gregset_t pr_reg; /* GP registers. */ int pr_fpvalid; /* True if math copro being used. */ }; #define ELF_PRARGSZ (80) /* Number of chars for args. */ struct elf_prpsinfo { char pr_state; /* Numeric process state. */ char pr_sname; /* Char for pr_state. */ char pr_zomb; /* Zombie. */ char pr_nice; /* Nice val. */ unsigned long int pr_flag; /* Flags. */ #if __WORDSIZE == 32 unsigned short int pr_uid; unsigned short int pr_gid; #else unsigned int pr_uid; unsigned int pr_gid; #endif int pr_pid, pr_ppid, pr_pgrp, pr_sid; /* Lots missing */ char pr_fname[16]; /* Filename of executable. */ char pr_psargs[ELF_PRARGSZ]; /* Initial part of arg list. */ }; /* The rest of this file provides the types for emulation of the Solaris interfaces that should be implemented by users of libthread_db. */ /* Addresses. */ typedef void *psaddr_t; /* Register sets. Linux has different names. */ typedef elf_gregset_t prgregset_t; typedef elf_fpregset_t prfpregset_t; /* We don't have any differences between processes and threads, therefore have only one PID type. */ typedef __pid_t lwpid_t; /* Process status and info. In the end we do provide typedefs for them. */ typedef struct elf_prstatus prstatus_t; typedef struct elf_prpsinfo prpsinfo_t; __END_DECLS #endif /* sys/procfs.h */ sys/perm.h000064400000002146151027430550006503 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_PERM_H #define _SYS_PERM_H 1 #include __BEGIN_DECLS /* Set port input/output permissions. */ extern int ioperm (unsigned long int __from, unsigned long int __num, int __turn_on) __THROW; /* Change I/O privilege level. */ extern int iopl (int __level) __THROW; __END_DECLS #endif /* _SYS_PERM_H */ sys/inotify.h000064400000007375151027430550007232 0ustar00/* Copyright (C) 2005-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_INOTIFY_H #define _SYS_INOTIFY_H 1 #include /* Get the platform-dependent flags. */ #include /* Structure describing an inotify event. */ struct inotify_event { int wd; /* Watch descriptor. */ uint32_t mask; /* Watch mask. */ uint32_t cookie; /* Cookie to synchronize two events. */ uint32_t len; /* Length (including NULs) of name. */ char name __flexarr; /* Name. */ }; /* Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH. */ #define IN_ACCESS 0x00000001 /* File was accessed. */ #define IN_MODIFY 0x00000002 /* File was modified. */ #define IN_ATTRIB 0x00000004 /* Metadata changed. */ #define IN_CLOSE_WRITE 0x00000008 /* Writtable file was closed. */ #define IN_CLOSE_NOWRITE 0x00000010 /* Unwrittable file closed. */ #define IN_CLOSE (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) /* Close. */ #define IN_OPEN 0x00000020 /* File was opened. */ #define IN_MOVED_FROM 0x00000040 /* File was moved from X. */ #define IN_MOVED_TO 0x00000080 /* File was moved to Y. */ #define IN_MOVE (IN_MOVED_FROM | IN_MOVED_TO) /* Moves. */ #define IN_CREATE 0x00000100 /* Subfile was created. */ #define IN_DELETE 0x00000200 /* Subfile was deleted. */ #define IN_DELETE_SELF 0x00000400 /* Self was deleted. */ #define IN_MOVE_SELF 0x00000800 /* Self was moved. */ /* Events sent by the kernel. */ #define IN_UNMOUNT 0x00002000 /* Backing fs was unmounted. */ #define IN_Q_OVERFLOW 0x00004000 /* Event queued overflowed. */ #define IN_IGNORED 0x00008000 /* File was ignored. */ /* Helper events. */ #define IN_CLOSE (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) /* Close. */ #define IN_MOVE (IN_MOVED_FROM | IN_MOVED_TO) /* Moves. */ /* Special flags. */ #define IN_ONLYDIR 0x01000000 /* Only watch the path if it is a directory. */ #define IN_DONT_FOLLOW 0x02000000 /* Do not follow a sym link. */ #define IN_EXCL_UNLINK 0x04000000 /* Exclude events on unlinked objects. */ #define IN_MASK_ADD 0x20000000 /* Add to the mask of an already existing watch. */ #define IN_ISDIR 0x40000000 /* Event occurred against dir. */ #define IN_ONESHOT 0x80000000 /* Only send event once. */ /* All events which a program can wait on. */ #define IN_ALL_EVENTS (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE \ | IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM \ | IN_MOVED_TO | IN_CREATE | IN_DELETE \ | IN_DELETE_SELF | IN_MOVE_SELF) __BEGIN_DECLS /* Create and initialize inotify instance. */ extern int inotify_init (void) __THROW; /* Create and initialize inotify instance. */ extern int inotify_init1 (int __flags) __THROW; /* Add watch of object NAME to inotify instance FD. Notify about events specified by MASK. */ extern int inotify_add_watch (int __fd, const char *__name, uint32_t __mask) __THROW; /* Remove the watch specified by WD from the inotify instance FD. */ extern int inotify_rm_watch (int __fd, int __wd) __THROW; __END_DECLS #endif /* sys/inotify.h */ sys/sysctl.h000064400000003724151027430550007064 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SYSCTL_H #define _SYS_SYSCTL_H 1 #include #define __need_size_t #include /* Prevent more kernel headers than necessary to be included. */ #ifndef _LINUX_KERNEL_H # define _LINUX_KERNEL_H 1 # define __undef_LINUX_KERNEL_H #endif #ifndef _LINUX_TYPES_H # define _LINUX_TYPES_H 1 # define __undef_LINUX_TYPES_H #endif #ifndef _LINUX_LIST_H # define _LINUX_LIST_H 1 # define __undef_LINUX_LIST_H #endif #ifndef __LINUX_COMPILER_H # define __LINUX_COMPILER_H 1 # define __user # define __undef__LINUX_COMPILER_H #endif #include #ifdef __undef_LINUX_KERNEL_H # undef _LINUX_KERNEL_H # undef __undef_LINUX_KERNEL_H #endif #ifdef __undef_LINUX_TYPES_H # undef _LINUX_TYPES_H # undef __undef_LINUX_TYPES_H #endif #ifdef __undef_LINUX_LIST_H # undef _LINUX_LIST_H # undef __undef_LINUX_LIST_H #endif #ifdef __undef__LINUX_COMPILER_H # undef __LINUX_COMPILER_H # undef __user # undef __undef__LINUX_COMPILER_H #endif #include __BEGIN_DECLS /* Read or write system parameters. */ extern int sysctl (int *__name, int __nlen, void *__oldval, size_t *__oldlenp, void *__newval, size_t __newlen) __THROW; __END_DECLS #endif /* _SYS_SYSCTL_H */ sys/sdt-config.h000064400000000424151027430550007572 0ustar00/* includes/sys/sdt-config.h. Generated from sdt-config.h.in by configure. This file just defines _SDT_ASM_SECTION_AUTOGROUP_SUPPORT to 0 or 1 to indicate whether the assembler supports "?" in .pushsection directives. */ #define _SDT_ASM_SECTION_AUTOGROUP_SUPPORT 1 sys/sysinfo.h000064400000002755151027430550007240 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SYSINFO_H #define _SYS_SYSINFO_H 1 #include /* Get sysinfo structure from kernel header. */ #include __BEGIN_DECLS /* Returns information on overall system statistics. */ extern int sysinfo (struct sysinfo *__info) __THROW; /* Return number of configured processors. */ extern int get_nprocs_conf (void) __THROW; /* Return number of available processors. */ extern int get_nprocs (void) __THROW; /* Return number of physical pages of memory in the system. */ extern long int get_phys_pages (void) __THROW; /* Return number of available physical pages of memory in the system. */ extern long int get_avphys_pages (void) __THROW; __END_DECLS #endif /* sys/sysinfo.h */ sys/sem.h000064400000003764151027430550006333 0ustar00/* Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SEM_H #define _SYS_SEM_H 1 #include #define __need_size_t #include /* Get common definition of System V style IPC. */ #include /* Get system dependent definition of `struct semid_ds' and more. */ #include #ifdef __USE_GNU # include #endif /* The following System V style IPC functions implement a semaphore handling. The definition is found in XPG2. */ /* Structure used for argument to `semop' to describe operations. */ struct sembuf { unsigned short int sem_num; /* semaphore number */ short int sem_op; /* semaphore operation */ short int sem_flg; /* operation flag */ }; __BEGIN_DECLS /* Semaphore control operation. */ extern int semctl (int __semid, int __semnum, int __cmd, ...) __THROW; /* Get semaphore. */ extern int semget (key_t __key, int __nsems, int __semflg) __THROW; /* Operate on semaphore. */ extern int semop (int __semid, struct sembuf *__sops, size_t __nsops) __THROW; #ifdef __USE_GNU /* Operate on semaphore with timeout. */ extern int semtimedop (int __semid, struct sembuf *__sops, size_t __nsops, const struct timespec *__timeout) __THROW; #endif __END_DECLS #endif /* sys/sem.h */ sys/socketvar.h000064400000000215151027430550007534 0ustar00/* This header is used on many systems but for GNU we have everything already defined in the standard header. */ #include sys/termios.h000064400000000112151027430550007211 0ustar00#ifndef _SYS_TERMIOS_H #define _SYS_TERMIOS_H #include #endif sys/sdt.h000064400000053215151027430550006335 0ustar00/* - Systemtap static probe definition macros. This file is dedicated to the public domain, pursuant to CC0 (https://creativecommons.org/publicdomain/zero/1.0/) */ #ifndef _SYS_SDT_H #define _SYS_SDT_H 1 /* This file defines a family of macros STAP_PROBEn(op1, ..., opn) that emit a nop into the instruction stream, and some data into an auxiliary note section. The data in the note section describes the operands, in terms of size and location. Each location is encoded as assembler operand string. Consumer tools such as gdb or systemtap insert breakpoints on top of the nop, and decode the location operand-strings, like an assembler, to find the values being passed. The operand strings are selected by the compiler for each operand. They are constrained by gcc inline-assembler codes. The default is: #define STAP_SDT_ARG_CONSTRAINT nor This is a good default if the operands tend to be integral and moderate in number (smaller than number of registers). In other cases, the compiler may report "'asm' requires impossible reload" or similar. In this case, consider simplifying the macro call (fewer and simpler operands), reduce optimization, or override the default constraints string via: #define STAP_SDT_ARG_CONSTRAINT g #include See also: https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation https://gcc.gnu.org/onlinedocs/gcc/Constraints.html */ #ifdef __ASSEMBLER__ # define _SDT_PROBE(provider, name, n, arglist) \ _SDT_ASM_BODY(provider, name, _SDT_ASM_SUBSTR_1, (_SDT_DEPAREN_##n arglist)) \ _SDT_ASM_BASE # define _SDT_ASM_1(x) x; # define _SDT_ASM_2(a, b) a,b; # define _SDT_ASM_3(a, b, c) a,b,c; # define _SDT_ASM_5(a, b, c, d, e) a,b,c,d,e; # define _SDT_ASM_STRING_1(x) .asciz #x; # define _SDT_ASM_SUBSTR_1(x) .ascii #x; # define _SDT_DEPAREN_0() /* empty */ # define _SDT_DEPAREN_1(a) a # define _SDT_DEPAREN_2(a,b) a b # define _SDT_DEPAREN_3(a,b,c) a b c # define _SDT_DEPAREN_4(a,b,c,d) a b c d # define _SDT_DEPAREN_5(a,b,c,d,e) a b c d e # define _SDT_DEPAREN_6(a,b,c,d,e,f) a b c d e f # define _SDT_DEPAREN_7(a,b,c,d,e,f,g) a b c d e f g # define _SDT_DEPAREN_8(a,b,c,d,e,f,g,h) a b c d e f g h # define _SDT_DEPAREN_9(a,b,c,d,e,f,g,h,i) a b c d e f g h i # define _SDT_DEPAREN_10(a,b,c,d,e,f,g,h,i,j) a b c d e f g h i j # define _SDT_DEPAREN_11(a,b,c,d,e,f,g,h,i,j,k) a b c d e f g h i j k # define _SDT_DEPAREN_12(a,b,c,d,e,f,g,h,i,j,k,l) a b c d e f g h i j k l #else #if defined _SDT_HAS_SEMAPHORES #define _SDT_NOTE_SEMAPHORE_USE(provider, name) \ __asm__ __volatile__ ("" :: "m" (provider##_##name##_semaphore)); #else #define _SDT_NOTE_SEMAPHORE_USE(provider, name) #endif # define _SDT_PROBE(provider, name, n, arglist) \ do { \ _SDT_NOTE_SEMAPHORE_USE(provider, name); \ __asm__ __volatile__ (_SDT_ASM_BODY(provider, name, _SDT_ASM_ARGS, (n)) \ :: _SDT_ASM_OPERANDS_##n arglist); \ __asm__ __volatile__ (_SDT_ASM_BASE); \ } while (0) # define _SDT_S(x) #x # define _SDT_ASM_1(x) _SDT_S(x) "\n" # define _SDT_ASM_2(a, b) _SDT_S(a) "," _SDT_S(b) "\n" # define _SDT_ASM_3(a, b, c) _SDT_S(a) "," _SDT_S(b) "," \ _SDT_S(c) "\n" # define _SDT_ASM_5(a, b, c, d, e) _SDT_S(a) "," _SDT_S(b) "," \ _SDT_S(c) "," _SDT_S(d) "," \ _SDT_S(e) "\n" # define _SDT_ASM_ARGS(n) _SDT_ASM_TEMPLATE_##n # define _SDT_ASM_STRING_1(x) _SDT_ASM_1(.asciz #x) # define _SDT_ASM_SUBSTR_1(x) _SDT_ASM_1(.ascii #x) # define _SDT_ARGFMT(no) _SDT_ASM_1(_SDT_SIGN %n[_SDT_S##no]) \ _SDT_ASM_1(_SDT_SIZE %n[_SDT_S##no]) \ _SDT_ASM_1(_SDT_TYPE %n[_SDT_S##no]) \ _SDT_ASM_SUBSTR(_SDT_ARGTMPL(_SDT_A##no)) # ifndef STAP_SDT_ARG_CONSTRAINT # if defined __powerpc__ # define STAP_SDT_ARG_CONSTRAINT nZr # elif defined __arm__ # define STAP_SDT_ARG_CONSTRAINT g # else # define STAP_SDT_ARG_CONSTRAINT nor # endif # endif # define _SDT_STRINGIFY(x) #x # define _SDT_ARG_CONSTRAINT_STRING(x) _SDT_STRINGIFY(x) /* _SDT_S encodes the size and type as 0xSSTT which is decoded by the assembler macros _SDT_SIZE and _SDT_TYPE */ # define _SDT_ARG(n, x) \ [_SDT_S##n] "n" ((_SDT_ARGSIGNED (x) ? (int)-1 : 1) * (-(((int) _SDT_ARGSIZE (x)) << 8) + (-(0x7f & __builtin_classify_type (x))))), \ [_SDT_A##n] _SDT_ARG_CONSTRAINT_STRING (STAP_SDT_ARG_CONSTRAINT) (_SDT_ARGVAL (x)) #endif #define _SDT_ASM_STRING(x) _SDT_ASM_STRING_1(x) #define _SDT_ASM_SUBSTR(x) _SDT_ASM_SUBSTR_1(x) #define _SDT_ARGARRAY(x) (__builtin_classify_type (x) == 14 \ || __builtin_classify_type (x) == 5) #ifdef __cplusplus # define _SDT_ARGSIGNED(x) (!_SDT_ARGARRAY (x) \ && __sdt_type<__typeof (x)>::__sdt_signed) # define _SDT_ARGSIZE(x) (_SDT_ARGARRAY (x) \ ? sizeof (void *) : sizeof (x)) # define _SDT_ARGVAL(x) (x) # include template struct __sdt_type { static const bool __sdt_signed = false; }; #define __SDT_ALWAYS_SIGNED(T) \ template<> struct __sdt_type { static const bool __sdt_signed = true; }; #define __SDT_COND_SIGNED(T,CT) \ template<> struct __sdt_type { static const bool __sdt_signed = ((CT)(-1) < 1); }; __SDT_ALWAYS_SIGNED(signed char) __SDT_ALWAYS_SIGNED(short) __SDT_ALWAYS_SIGNED(int) __SDT_ALWAYS_SIGNED(long) __SDT_ALWAYS_SIGNED(long long) __SDT_ALWAYS_SIGNED(volatile signed char) __SDT_ALWAYS_SIGNED(volatile short) __SDT_ALWAYS_SIGNED(volatile int) __SDT_ALWAYS_SIGNED(volatile long) __SDT_ALWAYS_SIGNED(volatile long long) __SDT_ALWAYS_SIGNED(const signed char) __SDT_ALWAYS_SIGNED(const short) __SDT_ALWAYS_SIGNED(const int) __SDT_ALWAYS_SIGNED(const long) __SDT_ALWAYS_SIGNED(const long long) __SDT_ALWAYS_SIGNED(const volatile signed char) __SDT_ALWAYS_SIGNED(const volatile short) __SDT_ALWAYS_SIGNED(const volatile int) __SDT_ALWAYS_SIGNED(const volatile long) __SDT_ALWAYS_SIGNED(const volatile long long) __SDT_COND_SIGNED(char, char) __SDT_COND_SIGNED(wchar_t, wchar_t) __SDT_COND_SIGNED(volatile char, char) __SDT_COND_SIGNED(volatile wchar_t, wchar_t) __SDT_COND_SIGNED(const char, char) __SDT_COND_SIGNED(const wchar_t, wchar_t) __SDT_COND_SIGNED(const volatile char, char) __SDT_COND_SIGNED(const volatile wchar_t, wchar_t) #if defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)) /* __SDT_COND_SIGNED(char16_t) */ /* __SDT_COND_SIGNED(char32_t) */ #endif template struct __sdt_type<__sdt_E[]> : public __sdt_type<__sdt_E *> {}; template struct __sdt_type<__sdt_E[__sdt_N]> : public __sdt_type<__sdt_E *> {}; #elif !defined(__ASSEMBLER__) __extension__ extern unsigned long long __sdt_unsp; # define _SDT_ARGINTTYPE(x) \ __typeof (__builtin_choose_expr (((__builtin_classify_type (x) \ + 3) & -4) == 4, (x), 0U)) # define _SDT_ARGSIGNED(x) \ (!__extension__ \ (__builtin_constant_p ((((unsigned long long) \ (_SDT_ARGINTTYPE (x)) __sdt_unsp) \ & ((unsigned long long)1 << (sizeof (unsigned long long) \ * __CHAR_BIT__ - 1))) == 0) \ || (_SDT_ARGINTTYPE (x)) -1 > (_SDT_ARGINTTYPE (x)) 0)) # define _SDT_ARGSIZE(x) \ (_SDT_ARGARRAY (x) ? sizeof (void *) : sizeof (x)) # define _SDT_ARGVAL(x) (x) #endif #if defined __powerpc__ || defined __powerpc64__ # define _SDT_ARGTMPL(id) %I[id]%[id] #elif defined __i386__ # define _SDT_ARGTMPL(id) %k[id] /* gcc.gnu.org/PR80115 sourceware.org/PR24541 */ #else # define _SDT_ARGTMPL(id) %[id] #endif /* NB: gdb PR24541 highlighted an unspecified corner of the sdt.h operand note format. The named register may be a longer or shorter (!) alias for the storage where the value in question is found. For example, on i386, 64-bit value may be put in register pairs, and the register name stored would identify just one of them. Previously, gcc was asked to emit the %w[id] (16-bit alias of some registers holding operands), even when a wider 32-bit value was used. Bottom line: the byte-width given before the @ sign governs. If there is a mismatch between that width and that of the named register, then a sys/sdt.h note consumer may need to employ architecture-specific heuristics to figure out where the compiler has actually put the complete value. */ #ifdef __LP64__ # define _SDT_ASM_ADDR .8byte #else # define _SDT_ASM_ADDR .4byte #endif /* The ia64 and s390 nop instructions take an argument. */ #if defined(__ia64__) || defined(__s390__) || defined(__s390x__) #define _SDT_NOP nop 0 #else #define _SDT_NOP nop #endif #define _SDT_NOTE_NAME "stapsdt" #define _SDT_NOTE_TYPE 3 /* If the assembler supports the necessary feature, then we can play nice with code in COMDAT sections, which comes up in C++ code. Without that assembler support, some combinations of probe placements in certain kinds of C++ code may produce link-time errors. */ #include "sdt-config.h" #if _SDT_ASM_SECTION_AUTOGROUP_SUPPORT # define _SDT_ASM_AUTOGROUP "?" #else # define _SDT_ASM_AUTOGROUP "" #endif #define _SDT_DEF_MACROS \ _SDT_ASM_1(.altmacro) \ _SDT_ASM_1(.macro _SDT_SIGN x) \ _SDT_ASM_1(.iflt \\x) \ _SDT_ASM_1(.ascii "-") \ _SDT_ASM_1(.endif) \ _SDT_ASM_1(.endm) \ _SDT_ASM_1(.macro _SDT_SIZE_ x) \ _SDT_ASM_1(.ascii "\x") \ _SDT_ASM_1(.endm) \ _SDT_ASM_1(.macro _SDT_SIZE x) \ _SDT_ASM_1(_SDT_SIZE_ %%((-(-\\x*((-\\x>0)-(-\\x<0))))>>8)) \ _SDT_ASM_1(.endm) \ _SDT_ASM_1(.macro _SDT_TYPE_ x) \ _SDT_ASM_2(.ifc 8,\\x) \ _SDT_ASM_1(.ascii "f") \ _SDT_ASM_1(.endif) \ _SDT_ASM_1(.ascii "@") \ _SDT_ASM_1(.endm) \ _SDT_ASM_1(.macro _SDT_TYPE x) \ _SDT_ASM_1(_SDT_TYPE_ %%((\\x)&(0xff))) \ _SDT_ASM_1(.endm) #define _SDT_UNDEF_MACROS \ _SDT_ASM_1(.purgem _SDT_SIGN) \ _SDT_ASM_1(.purgem _SDT_SIZE_) \ _SDT_ASM_1(.purgem _SDT_SIZE) \ _SDT_ASM_1(.purgem _SDT_TYPE_) \ _SDT_ASM_1(.purgem _SDT_TYPE) #define _SDT_ASM_BODY(provider, name, pack_args, args, ...) \ _SDT_DEF_MACROS \ _SDT_ASM_1(990: _SDT_NOP) \ _SDT_ASM_3( .pushsection .note.stapsdt,_SDT_ASM_AUTOGROUP,"note") \ _SDT_ASM_1( .balign 4) \ _SDT_ASM_3( .4byte 992f-991f, 994f-993f, _SDT_NOTE_TYPE) \ _SDT_ASM_1(991: .asciz _SDT_NOTE_NAME) \ _SDT_ASM_1(992: .balign 4) \ _SDT_ASM_1(993: _SDT_ASM_ADDR 990b) \ _SDT_ASM_1( _SDT_ASM_ADDR _.stapsdt.base) \ _SDT_SEMAPHORE(provider,name) \ _SDT_ASM_STRING(provider) \ _SDT_ASM_STRING(name) \ pack_args args \ _SDT_ASM_SUBSTR(\x00) \ _SDT_UNDEF_MACROS \ _SDT_ASM_1(994: .balign 4) \ _SDT_ASM_1( .popsection) #define _SDT_ASM_BASE \ _SDT_ASM_1(.ifndef _.stapsdt.base) \ _SDT_ASM_5( .pushsection .stapsdt.base,"aG","progbits", \ .stapsdt.base,comdat) \ _SDT_ASM_1( .weak _.stapsdt.base) \ _SDT_ASM_1( .hidden _.stapsdt.base) \ _SDT_ASM_1( _.stapsdt.base: .space 1) \ _SDT_ASM_2( .size _.stapsdt.base, 1) \ _SDT_ASM_1( .popsection) \ _SDT_ASM_1(.endif) #if defined _SDT_HAS_SEMAPHORES #define _SDT_SEMAPHORE(p,n) \ _SDT_ASM_1( _SDT_ASM_ADDR p##_##n##_semaphore) #else #define _SDT_SEMAPHORE(p,n) _SDT_ASM_1( _SDT_ASM_ADDR 0) #endif #define _SDT_ASM_BLANK _SDT_ASM_SUBSTR(\x20) #define _SDT_ASM_TEMPLATE_0 /* no arguments */ #define _SDT_ASM_TEMPLATE_1 _SDT_ARGFMT(1) #define _SDT_ASM_TEMPLATE_2 _SDT_ASM_TEMPLATE_1 _SDT_ASM_BLANK _SDT_ARGFMT(2) #define _SDT_ASM_TEMPLATE_3 _SDT_ASM_TEMPLATE_2 _SDT_ASM_BLANK _SDT_ARGFMT(3) #define _SDT_ASM_TEMPLATE_4 _SDT_ASM_TEMPLATE_3 _SDT_ASM_BLANK _SDT_ARGFMT(4) #define _SDT_ASM_TEMPLATE_5 _SDT_ASM_TEMPLATE_4 _SDT_ASM_BLANK _SDT_ARGFMT(5) #define _SDT_ASM_TEMPLATE_6 _SDT_ASM_TEMPLATE_5 _SDT_ASM_BLANK _SDT_ARGFMT(6) #define _SDT_ASM_TEMPLATE_7 _SDT_ASM_TEMPLATE_6 _SDT_ASM_BLANK _SDT_ARGFMT(7) #define _SDT_ASM_TEMPLATE_8 _SDT_ASM_TEMPLATE_7 _SDT_ASM_BLANK _SDT_ARGFMT(8) #define _SDT_ASM_TEMPLATE_9 _SDT_ASM_TEMPLATE_8 _SDT_ASM_BLANK _SDT_ARGFMT(9) #define _SDT_ASM_TEMPLATE_10 _SDT_ASM_TEMPLATE_9 _SDT_ASM_BLANK _SDT_ARGFMT(10) #define _SDT_ASM_TEMPLATE_11 _SDT_ASM_TEMPLATE_10 _SDT_ASM_BLANK _SDT_ARGFMT(11) #define _SDT_ASM_TEMPLATE_12 _SDT_ASM_TEMPLATE_11 _SDT_ASM_BLANK _SDT_ARGFMT(12) #define _SDT_ASM_OPERANDS_0() [__sdt_dummy] "g" (0) #define _SDT_ASM_OPERANDS_1(arg1) _SDT_ARG(1, arg1) #define _SDT_ASM_OPERANDS_2(arg1, arg2) \ _SDT_ASM_OPERANDS_1(arg1), _SDT_ARG(2, arg2) #define _SDT_ASM_OPERANDS_3(arg1, arg2, arg3) \ _SDT_ASM_OPERANDS_2(arg1, arg2), _SDT_ARG(3, arg3) #define _SDT_ASM_OPERANDS_4(arg1, arg2, arg3, arg4) \ _SDT_ASM_OPERANDS_3(arg1, arg2, arg3), _SDT_ARG(4, arg4) #define _SDT_ASM_OPERANDS_5(arg1, arg2, arg3, arg4, arg5) \ _SDT_ASM_OPERANDS_4(arg1, arg2, arg3, arg4), _SDT_ARG(5, arg5) #define _SDT_ASM_OPERANDS_6(arg1, arg2, arg3, arg4, arg5, arg6) \ _SDT_ASM_OPERANDS_5(arg1, arg2, arg3, arg4, arg5), _SDT_ARG(6, arg6) #define _SDT_ASM_OPERANDS_7(arg1, arg2, arg3, arg4, arg5, arg6, arg7) \ _SDT_ASM_OPERANDS_6(arg1, arg2, arg3, arg4, arg5, arg6), _SDT_ARG(7, arg7) #define _SDT_ASM_OPERANDS_8(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) \ _SDT_ASM_OPERANDS_7(arg1, arg2, arg3, arg4, arg5, arg6, arg7), \ _SDT_ARG(8, arg8) #define _SDT_ASM_OPERANDS_9(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9) \ _SDT_ASM_OPERANDS_8(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8), \ _SDT_ARG(9, arg9) #define _SDT_ASM_OPERANDS_10(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) \ _SDT_ASM_OPERANDS_9(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9), \ _SDT_ARG(10, arg10) #define _SDT_ASM_OPERANDS_11(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11) \ _SDT_ASM_OPERANDS_10(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10), \ _SDT_ARG(11, arg11) #define _SDT_ASM_OPERANDS_12(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12) \ _SDT_ASM_OPERANDS_11(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11), \ _SDT_ARG(12, arg12) /* These macros can be used in C, C++, or assembly code. In assembly code the arguments should use normal assembly operand syntax. */ #define STAP_PROBE(provider, name) \ _SDT_PROBE(provider, name, 0, ()) #define STAP_PROBE1(provider, name, arg1) \ _SDT_PROBE(provider, name, 1, (arg1)) #define STAP_PROBE2(provider, name, arg1, arg2) \ _SDT_PROBE(provider, name, 2, (arg1, arg2)) #define STAP_PROBE3(provider, name, arg1, arg2, arg3) \ _SDT_PROBE(provider, name, 3, (arg1, arg2, arg3)) #define STAP_PROBE4(provider, name, arg1, arg2, arg3, arg4) \ _SDT_PROBE(provider, name, 4, (arg1, arg2, arg3, arg4)) #define STAP_PROBE5(provider, name, arg1, arg2, arg3, arg4, arg5) \ _SDT_PROBE(provider, name, 5, (arg1, arg2, arg3, arg4, arg5)) #define STAP_PROBE6(provider, name, arg1, arg2, arg3, arg4, arg5, arg6) \ _SDT_PROBE(provider, name, 6, (arg1, arg2, arg3, arg4, arg5, arg6)) #define STAP_PROBE7(provider, name, arg1, arg2, arg3, arg4, arg5, arg6, arg7) \ _SDT_PROBE(provider, name, 7, (arg1, arg2, arg3, arg4, arg5, arg6, arg7)) #define STAP_PROBE8(provider,name,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) \ _SDT_PROBE(provider, name, 8, (arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8)) #define STAP_PROBE9(provider,name,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)\ _SDT_PROBE(provider, name, 9, (arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)) #define STAP_PROBE10(provider,name,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10) \ _SDT_PROBE(provider, name, 10, \ (arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10)) #define STAP_PROBE11(provider,name,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11) \ _SDT_PROBE(provider, name, 11, \ (arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11)) #define STAP_PROBE12(provider,name,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12) \ _SDT_PROBE(provider, name, 12, \ (arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12)) /* This STAP_PROBEV macro can be used in variadic scenarios, where the number of probe arguments is not known until compile time. Since variadic macro support may vary with compiler options, you must pre-#define SDT_USE_VARIADIC to enable this type of probe. The trick to count __VA_ARGS__ was inspired by this post by Laurent Deniau : http://groups.google.com/group/comp.std.c/msg/346fc464319b1ee5 Note that our _SDT_NARG is called with an extra 0 arg that's not counted, so we don't have to worry about the behavior of macros called without any arguments. */ #define _SDT_NARG(...) __SDT_NARG(__VA_ARGS__, 12,11,10,9,8,7,6,5,4,3,2,1,0) #define __SDT_NARG(_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12, N, ...) N #ifdef SDT_USE_VARIADIC #define _SDT_PROBE_N(provider, name, N, ...) \ _SDT_PROBE(provider, name, N, (__VA_ARGS__)) #define STAP_PROBEV(provider, name, ...) \ _SDT_PROBE_N(provider, name, _SDT_NARG(0, ##__VA_ARGS__), ##__VA_ARGS__) #endif /* These macros are for use in asm statements. You must compile with -std=gnu99 or -std=c99 to use the STAP_PROBE_ASM macro. The STAP_PROBE_ASM macro generates a quoted string to be used in the template portion of the asm statement, concatenated with strings that contain the actual assembly code around the probe site. For example: asm ("before\n" STAP_PROBE_ASM(provider, fooprobe, %eax 4(%esi)) "after"); emits the assembly code for "before\nafter", with a probe in between. The probe arguments are the %eax register, and the value of the memory word located 4 bytes past the address in the %esi register. Note that because this is a simple asm, not a GNU C extended asm statement, these % characters do not need to be doubled to generate literal %reg names. In a GNU C extended asm statement, the probe arguments can be specified using the macro STAP_PROBE_ASM_TEMPLATE(n) for n arguments. The paired macro STAP_PROBE_ASM_OPERANDS gives the C values of these probe arguments, and appears in the input operand list of the asm statement. For example: asm ("someinsn %0,%1\n" // %0 is output operand, %1 is input operand STAP_PROBE_ASM(provider, fooprobe, STAP_PROBE_ASM_TEMPLATE(3)) "otherinsn %[namedarg]" : "r" (outvar) : "g" (some_value), [namedarg] "i" (1234), STAP_PROBE_ASM_OPERANDS(3, some_value, some_ptr->field, 1234)); This is just like writing: STAP_PROBE3(provider, fooprobe, some_value, some_ptr->field, 1234)); but the probe site is right between "someinsn" and "otherinsn". The probe arguments in STAP_PROBE_ASM can be given as assembly operands instead, even inside a GNU C extended asm statement. Note that these can use operand templates like %0 or %[name], and likewise they must write %%reg for a literal operand of %reg. */ #define _SDT_ASM_BODY_1(p,n,...) _SDT_ASM_BODY(p,n,_SDT_ASM_SUBSTR,(__VA_ARGS__)) #define _SDT_ASM_BODY_2(p,n,...) _SDT_ASM_BODY(p,n,/*_SDT_ASM_STRING */,__VA_ARGS__) #define _SDT_ASM_BODY_N2(p,n,no,...) _SDT_ASM_BODY_ ## no(p,n,__VA_ARGS__) #define _SDT_ASM_BODY_N1(p,n,no,...) _SDT_ASM_BODY_N2(p,n,no,__VA_ARGS__) #define _SDT_ASM_BODY_N(p,n,...) _SDT_ASM_BODY_N1(p,n,_SDT_NARG(0, __VA_ARGS__),__VA_ARGS__) #if __STDC_VERSION__ >= 199901L # define STAP_PROBE_ASM(provider, name, ...) \ _SDT_ASM_BODY_N(provider, name, __VA_ARGS__) \ _SDT_ASM_BASE # define STAP_PROBE_ASM_OPERANDS(n, ...) _SDT_ASM_OPERANDS_##n(__VA_ARGS__) #else # define STAP_PROBE_ASM(provider, name, args) \ _SDT_ASM_BODY(provider, name, /* _SDT_ASM_STRING */, (args)) \ _SDT_ASM_BASE #endif #define STAP_PROBE_ASM_TEMPLATE(n) _SDT_ASM_TEMPLATE_##n,"use _SDT_ASM_TEMPLATE_" /* DTrace compatible macro names. */ #define DTRACE_PROBE(provider,probe) \ STAP_PROBE(provider,probe) #define DTRACE_PROBE1(provider,probe,parm1) \ STAP_PROBE1(provider,probe,parm1) #define DTRACE_PROBE2(provider,probe,parm1,parm2) \ STAP_PROBE2(provider,probe,parm1,parm2) #define DTRACE_PROBE3(provider,probe,parm1,parm2,parm3) \ STAP_PROBE3(provider,probe,parm1,parm2,parm3) #define DTRACE_PROBE4(provider,probe,parm1,parm2,parm3,parm4) \ STAP_PROBE4(provider,probe,parm1,parm2,parm3,parm4) #define DTRACE_PROBE5(provider,probe,parm1,parm2,parm3,parm4,parm5) \ STAP_PROBE5(provider,probe,parm1,parm2,parm3,parm4,parm5) #define DTRACE_PROBE6(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6) \ STAP_PROBE6(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6) #define DTRACE_PROBE7(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7) \ STAP_PROBE7(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7) #define DTRACE_PROBE8(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8) \ STAP_PROBE8(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8) #define DTRACE_PROBE9(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9) \ STAP_PROBE9(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9) #define DTRACE_PROBE10(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9,parm10) \ STAP_PROBE10(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9,parm10) #define DTRACE_PROBE11(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9,parm10,parm11) \ STAP_PROBE11(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9,parm10,parm11) #define DTRACE_PROBE12(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9,parm10,parm11,parm12) \ STAP_PROBE12(provider,probe,parm1,parm2,parm3,parm4,parm5,parm6,parm7,parm8,parm9,parm10,parm11,parm12) #endif /* sys/sdt.h */ sys/epoll.h000064400000010472151027430550006654 0ustar00/* Copyright (C) 2002-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_EPOLL_H #define _SYS_EPOLL_H 1 #include #include #include /* Get the platform-dependent flags. */ #include #ifndef __EPOLL_PACKED # define __EPOLL_PACKED #endif enum EPOLL_EVENTS { EPOLLIN = 0x001, #define EPOLLIN EPOLLIN EPOLLPRI = 0x002, #define EPOLLPRI EPOLLPRI EPOLLOUT = 0x004, #define EPOLLOUT EPOLLOUT EPOLLRDNORM = 0x040, #define EPOLLRDNORM EPOLLRDNORM EPOLLRDBAND = 0x080, #define EPOLLRDBAND EPOLLRDBAND EPOLLWRNORM = 0x100, #define EPOLLWRNORM EPOLLWRNORM EPOLLWRBAND = 0x200, #define EPOLLWRBAND EPOLLWRBAND EPOLLMSG = 0x400, #define EPOLLMSG EPOLLMSG EPOLLERR = 0x008, #define EPOLLERR EPOLLERR EPOLLHUP = 0x010, #define EPOLLHUP EPOLLHUP EPOLLRDHUP = 0x2000, #define EPOLLRDHUP EPOLLRDHUP EPOLLEXCLUSIVE = 1u << 28, #define EPOLLEXCLUSIVE EPOLLEXCLUSIVE EPOLLWAKEUP = 1u << 29, #define EPOLLWAKEUP EPOLLWAKEUP EPOLLONESHOT = 1u << 30, #define EPOLLONESHOT EPOLLONESHOT EPOLLET = 1u << 31 #define EPOLLET EPOLLET }; /* Valid opcodes ( "op" parameter ) to issue to epoll_ctl(). */ #define EPOLL_CTL_ADD 1 /* Add a file descriptor to the interface. */ #define EPOLL_CTL_DEL 2 /* Remove a file descriptor from the interface. */ #define EPOLL_CTL_MOD 3 /* Change file descriptor epoll_event structure. */ typedef union epoll_data { void *ptr; int fd; uint32_t u32; uint64_t u64; } epoll_data_t; struct epoll_event { uint32_t events; /* Epoll events */ epoll_data_t data; /* User data variable */ } __EPOLL_PACKED; __BEGIN_DECLS /* Creates an epoll instance. Returns an fd for the new instance. The "size" parameter is a hint specifying the number of file descriptors to be associated with the new instance. The fd returned by epoll_create() should be closed with close(). */ extern int epoll_create (int __size) __THROW; /* Same as epoll_create but with an FLAGS parameter. The unused SIZE parameter has been dropped. */ extern int epoll_create1 (int __flags) __THROW; /* Manipulate an epoll instance "epfd". Returns 0 in case of success, -1 in case of error ( the "errno" variable will contain the specific error code ) The "op" parameter is one of the EPOLL_CTL_* constants defined above. The "fd" parameter is the target of the operation. The "event" parameter describes which events the caller is interested in and any associated user data. */ extern int epoll_ctl (int __epfd, int __op, int __fd, struct epoll_event *__event) __THROW; /* Wait for events on an epoll instance "epfd". Returns the number of triggered events returned in "events" buffer. Or -1 in case of error with the "errno" variable set to the specific error code. The "events" parameter is a buffer that will contain triggered events. The "maxevents" is the maximum number of events to be returned ( usually size of "events" ). The "timeout" parameter specifies the maximum wait time in milliseconds (-1 == infinite). This function is a cancellation point and therefore not marked with __THROW. */ extern int epoll_wait (int __epfd, struct epoll_event *__events, int __maxevents, int __timeout); /* Same as epoll_wait, but the thread's signal mask is temporarily and atomically replaced with the one provided as parameter. This function is a cancellation point and therefore not marked with __THROW. */ extern int epoll_pwait (int __epfd, struct epoll_event *__events, int __maxevents, int __timeout, const __sigset_t *__ss); __END_DECLS #endif /* sys/epoll.h */ sys/utsname.h000064400000004660151027430550007217 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * POSIX Standard: 4.4 System Identification */ #ifndef _SYS_UTSNAME_H #define _SYS_UTSNAME_H 1 #include __BEGIN_DECLS #include #ifndef _UTSNAME_SYSNAME_LENGTH # define _UTSNAME_SYSNAME_LENGTH _UTSNAME_LENGTH #endif #ifndef _UTSNAME_NODENAME_LENGTH # define _UTSNAME_NODENAME_LENGTH _UTSNAME_LENGTH #endif #ifndef _UTSNAME_RELEASE_LENGTH # define _UTSNAME_RELEASE_LENGTH _UTSNAME_LENGTH #endif #ifndef _UTSNAME_VERSION_LENGTH # define _UTSNAME_VERSION_LENGTH _UTSNAME_LENGTH #endif #ifndef _UTSNAME_MACHINE_LENGTH # define _UTSNAME_MACHINE_LENGTH _UTSNAME_LENGTH #endif /* Structure describing the system and machine. */ struct utsname { /* Name of the implementation of the operating system. */ char sysname[_UTSNAME_SYSNAME_LENGTH]; /* Name of this node on the network. */ char nodename[_UTSNAME_NODENAME_LENGTH]; /* Current release level of this implementation. */ char release[_UTSNAME_RELEASE_LENGTH]; /* Current version level of this release. */ char version[_UTSNAME_VERSION_LENGTH]; /* Name of the hardware type the system is running on. */ char machine[_UTSNAME_MACHINE_LENGTH]; #if _UTSNAME_DOMAIN_LENGTH - 0 /* Name of the domain of this node on the network. */ # ifdef __USE_GNU char domainname[_UTSNAME_DOMAIN_LENGTH]; # else char __domainname[_UTSNAME_DOMAIN_LENGTH]; # endif #endif }; #ifdef __USE_MISC /* Note that SVID assumes all members have the same size. */ # define SYS_NMLN _UTSNAME_LENGTH #endif /* Put information about the system in NAME. */ extern int uname (struct utsname *__name) __THROW; __END_DECLS #endif /* sys/utsname.h */ sys/ipc.h000064400000002665151027430550006321 0ustar00/* Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_IPC_H #define _SYS_IPC_H 1 #include /* Get system dependent definition of `struct ipc_perm' and more. */ #include #include #ifndef __uid_t_defined typedef __uid_t uid_t; # define __uid_t_defined #endif #ifndef __gid_t_defined typedef __gid_t gid_t; # define __gid_t_defined #endif #ifndef __mode_t_defined typedef __mode_t mode_t; # define __mode_t_defined #endif #ifndef __key_t_defined typedef __key_t key_t; # define __key_t_defined #endif __BEGIN_DECLS /* Generates key for System V style IPC. */ extern key_t ftok (const char *__pathname, int __proj_id) __THROW; __END_DECLS #endif /* sys/ipc.h */ sys/gmon.h000064400000014126151027430550006501 0ustar00/*- * Copyright (c) 1982, 1986, 1992, 1993 * The Regents of the University of California. 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)gmon.h 8.2 (Berkeley) 1/4/94 */ #ifndef _SYS_GMON_H #define _SYS_GMON_H 1 #include #include /* * See gmon_out.h for gmon.out format. */ /* structure emitted by "gcc -a". This must match struct bb in gcc/libgcc2.c. It is OK for gcc to declare a longer structure as long as the members below are present. */ struct __bb { long zero_word; const char *filename; long *counts; long ncounts; struct __bb *next; const unsigned long *addresses; }; extern struct __bb *__bb_head; /* * histogram counters are unsigned shorts (according to the kernel). */ #define HISTCOUNTER unsigned short /* * fraction of text space to allocate for histogram counters here, 1/2 */ #define HISTFRACTION 2 /* * Fraction of text space to allocate for from hash buckets. * The value of HASHFRACTION is based on the minimum number of bytes * of separation between two subroutine call points in the object code. * Given MIN_SUBR_SEPARATION bytes of separation the value of * HASHFRACTION is calculated as: * * HASHFRACTION = MIN_SUBR_SEPARATION / (2 * sizeof(short) - 1); * * For example, on the VAX, the shortest two call sequence is: * * calls $0,(r0) * calls $0,(r0) * * which is separated by only three bytes, thus HASHFRACTION is * calculated as: * * HASHFRACTION = 3 / (2 * 2 - 1) = 1 * * Note that the division above rounds down, thus if MIN_SUBR_FRACTION * is less than three, this algorithm will not work! * * In practice, however, call instructions are rarely at a minimal * distance. Hence, we will define HASHFRACTION to be 2 across all * architectures. This saves a reasonable amount of space for * profiling data structures without (in practice) sacrificing * any granularity. */ #define HASHFRACTION 2 /* * Percent of text space to allocate for tostructs. * This is a heuristic; we will fail with a warning when profiling programs * with a very large number of very small functions, but that's * normally OK. * 2 is probably still a good value for normal programs. * Profiling a test case with 64000 small functions will work if * you raise this value to 3 and link statically (which bloats the * text size, thus raising the number of arcs expected by the heuristic). */ #define ARCDENSITY 3 /* * Always allocate at least this many tostructs. This * hides the inadequacy of the ARCDENSITY heuristic, at least * for small programs. * * Value can be overridden at runtime by glibc.gmon.minarcs tunable. */ #define MINARCS 50 /* * The type used to represent indices into gmonparam.tos[]. */ #define ARCINDEX unsigned long /* * Maximum number of arcs we want to allow. * Used to be max representable value of ARCINDEX minus 2, but now * that ARCINDEX is a long, that's too large; we don't really want * to allow a 48 gigabyte table. * * Value can be overridden at runtime by glibc.gmon.maxarcs tunable. */ #define MAXARCS (1 << 20) struct tostruct { unsigned long selfpc; long count; ARCINDEX link; }; /* * a raw arc, with pointers to the calling site and * the called site and a count. */ struct rawarc { unsigned long raw_frompc; unsigned long raw_selfpc; long raw_count; }; /* * general rounding functions. */ #define ROUNDDOWN(x,y) (((x)/(y))*(y)) #define ROUNDUP(x,y) ((((x)+(y)-1)/(y))*(y)) /* * The profiling data structures are housed in this structure. */ struct gmonparam { long int state; unsigned short *kcount; unsigned long kcountsize; ARCINDEX *froms; unsigned long fromssize; struct tostruct *tos; unsigned long tossize; long tolimit; unsigned long lowpc; unsigned long highpc; unsigned long textsize; unsigned long hashfraction; long log_hashfraction; }; /* * Possible states of profiling. */ #define GMON_PROF_ON 0 #define GMON_PROF_BUSY 1 #define GMON_PROF_ERROR 2 #define GMON_PROF_OFF 3 /* * Sysctl definitions for extracting profiling information from the kernel. */ #define GPROF_STATE 0 /* int: profiling enabling variable */ #define GPROF_COUNT 1 /* struct: profile tick count buffer */ #define GPROF_FROMS 2 /* struct: from location hash bucket */ #define GPROF_TOS 3 /* struct: destination/count structure */ #define GPROF_GMONPARAM 4 /* struct: profiling parameters (see above) */ __BEGIN_DECLS /* Set up data structures and start profiling. */ extern void __monstartup (unsigned long __lowpc, unsigned long __highpc) __THROW; extern void monstartup (unsigned long __lowpc, unsigned long __highpc) __THROW; /* Clean up profiling and write out gmon.out. */ extern void _mcleanup (void) __THROW; __END_DECLS #endif /* sys/gmon.h */ sys/queue.h000064400000046123151027430550006667 0ustar00/* * Copyright (c) 1991, 1993 * The Regents of the University of California. 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. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)queue.h 8.5 (Berkeley) 8/20/94 */ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ /* * This file defines five types of data structures: singly-linked lists, * lists, simple queues, tail queues, and circular queues. * * A singly-linked list is headed by a single forward pointer. The * elements are singly linked for minimum space and pointer manipulation * overhead at the expense of O(n) removal for arbitrary elements. New * elements can be added to the list after an existing element or at the * head of the list. Elements being removed from the head of the list * should use the explicit macro for this purpose for optimum * efficiency. A singly-linked list may only be traversed in the forward * direction. Singly-linked lists are ideal for applications with large * datasets and few or no removals or for implementing a LIFO queue. * * A list is headed by a single forward pointer (or an array of forward * pointers for a hash table header). The elements are doubly linked * so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before * or after an existing element or at the head of the list. A list * may only be traversed in the forward direction. * * A simple queue is headed by a pair of pointers, one the head of the * list and the other to the tail of the list. The elements are singly * linked to save space, so elements can only be removed from the * head of the list. New elements can be added to the list after * an existing element, at the head of the list, or at the end of the * list. A simple queue may only be traversed in the forward direction. * * A tail queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or * after an existing element, at the head of the list, or at the end of * the list. A tail queue may be traversed in either direction. * * A circle queue is headed by a pair of pointers, one to the head of the * list and the other to the tail of the list. The elements are doubly * linked so that an arbitrary element can be removed without a need to * traverse the list. New elements can be added to the list before or after * an existing element, at the head of the list, or at the end of the list. * A circle queue may be traversed in either direction, but has a more * complex end of list detection. * * For details on the use of these macros, see the queue(3) manual page. */ /* * List definitions. */ #define LIST_HEAD(name, type) \ struct name { \ struct type *lh_first; /* first element */ \ } #define LIST_HEAD_INITIALIZER(head) \ { NULL } #define LIST_ENTRY(type) \ struct { \ struct type *le_next; /* next element */ \ struct type **le_prev; /* address of previous next element */ \ } /* * List functions. */ #define LIST_INIT(head) do { \ (head)->lh_first = NULL; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_AFTER(listelm, elm, field) do { \ if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ (listelm)->field.le_next->field.le_prev = \ &(elm)->field.le_next; \ (listelm)->field.le_next = (elm); \ (elm)->field.le_prev = &(listelm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.le_prev = (listelm)->field.le_prev; \ (elm)->field.le_next = (listelm); \ *(listelm)->field.le_prev = (elm); \ (listelm)->field.le_prev = &(elm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.le_next = (head)->lh_first) != NULL) \ (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ (head)->lh_first = (elm); \ (elm)->field.le_prev = &(head)->lh_first; \ } while (/*CONSTCOND*/0) #define LIST_REMOVE(elm, field) do { \ if ((elm)->field.le_next != NULL) \ (elm)->field.le_next->field.le_prev = \ (elm)->field.le_prev; \ *(elm)->field.le_prev = (elm)->field.le_next; \ } while (/*CONSTCOND*/0) #define LIST_FOREACH(var, head, field) \ for ((var) = ((head)->lh_first); \ (var); \ (var) = ((var)->field.le_next)) /* * List access methods. */ #define LIST_EMPTY(head) ((head)->lh_first == NULL) #define LIST_FIRST(head) ((head)->lh_first) #define LIST_NEXT(elm, field) ((elm)->field.le_next) /* * Singly-linked List definitions. */ #define SLIST_HEAD(name, type) \ struct name { \ struct type *slh_first; /* first element */ \ } #define SLIST_HEAD_INITIALIZER(head) \ { NULL } #define SLIST_ENTRY(type) \ struct { \ struct type *sle_next; /* next element */ \ } /* * Singly-linked List functions. */ #define SLIST_INIT(head) do { \ (head)->slh_first = NULL; \ } while (/*CONSTCOND*/0) #define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ (elm)->field.sle_next = (slistelm)->field.sle_next; \ (slistelm)->field.sle_next = (elm); \ } while (/*CONSTCOND*/0) #define SLIST_INSERT_HEAD(head, elm, field) do { \ (elm)->field.sle_next = (head)->slh_first; \ (head)->slh_first = (elm); \ } while (/*CONSTCOND*/0) #define SLIST_REMOVE_HEAD(head, field) do { \ (head)->slh_first = (head)->slh_first->field.sle_next; \ } while (/*CONSTCOND*/0) #define SLIST_REMOVE(head, elm, type, field) do { \ if ((head)->slh_first == (elm)) { \ SLIST_REMOVE_HEAD((head), field); \ } \ else { \ struct type *curelm = (head)->slh_first; \ while(curelm->field.sle_next != (elm)) \ curelm = curelm->field.sle_next; \ curelm->field.sle_next = \ curelm->field.sle_next->field.sle_next; \ } \ } while (/*CONSTCOND*/0) #define SLIST_FOREACH(var, head, field) \ for((var) = (head)->slh_first; (var); (var) = (var)->field.sle_next) /* * Singly-linked List access methods. */ #define SLIST_EMPTY(head) ((head)->slh_first == NULL) #define SLIST_FIRST(head) ((head)->slh_first) #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) /* * Singly-linked Tail queue declarations. */ #define STAILQ_HEAD(name, type) \ struct name { \ struct type *stqh_first; /* first element */ \ struct type **stqh_last; /* addr of last next element */ \ } #define STAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).stqh_first } #define STAILQ_ENTRY(type) \ struct { \ struct type *stqe_next; /* next element */ \ } /* * Singly-linked Tail queue functions. */ #define STAILQ_INIT(head) do { \ (head)->stqh_first = NULL; \ (head)->stqh_last = &(head)->stqh_first; \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.stqe_next = (head)->stqh_first) == NULL) \ (head)->stqh_last = &(elm)->field.stqe_next; \ (head)->stqh_first = (elm); \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.stqe_next = NULL; \ *(head)->stqh_last = (elm); \ (head)->stqh_last = &(elm)->field.stqe_next; \ } while (/*CONSTCOND*/0) #define STAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.stqe_next = (listelm)->field.stqe_next) == NULL)\ (head)->stqh_last = &(elm)->field.stqe_next; \ (listelm)->field.stqe_next = (elm); \ } while (/*CONSTCOND*/0) #define STAILQ_REMOVE_HEAD(head, field) do { \ if (((head)->stqh_first = (head)->stqh_first->field.stqe_next) == NULL) \ (head)->stqh_last = &(head)->stqh_first; \ } while (/*CONSTCOND*/0) #define STAILQ_REMOVE(head, elm, type, field) do { \ if ((head)->stqh_first == (elm)) { \ STAILQ_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->stqh_first; \ while (curelm->field.stqe_next != (elm)) \ curelm = curelm->field.stqe_next; \ if ((curelm->field.stqe_next = \ curelm->field.stqe_next->field.stqe_next) == NULL) \ (head)->stqh_last = &(curelm)->field.stqe_next; \ } \ } while (/*CONSTCOND*/0) #define STAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->stqh_first); \ (var); \ (var) = ((var)->field.stqe_next)) #define STAILQ_CONCAT(head1, head2) do { \ if (!STAILQ_EMPTY((head2))) { \ *(head1)->stqh_last = (head2)->stqh_first; \ (head1)->stqh_last = (head2)->stqh_last; \ STAILQ_INIT((head2)); \ } \ } while (/*CONSTCOND*/0) /* * Singly-linked Tail queue access methods. */ #define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) #define STAILQ_FIRST(head) ((head)->stqh_first) #define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) /* * Simple queue definitions. */ #define SIMPLEQ_HEAD(name, type) \ struct name { \ struct type *sqh_first; /* first element */ \ struct type **sqh_last; /* addr of last next element */ \ } #define SIMPLEQ_HEAD_INITIALIZER(head) \ { NULL, &(head).sqh_first } #define SIMPLEQ_ENTRY(type) \ struct { \ struct type *sqe_next; /* next element */ \ } /* * Simple queue functions. */ #define SIMPLEQ_INIT(head) do { \ (head)->sqh_first = NULL; \ (head)->sqh_last = &(head)->sqh_first; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ (head)->sqh_last = &(elm)->field.sqe_next; \ (head)->sqh_first = (elm); \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.sqe_next = NULL; \ *(head)->sqh_last = (elm); \ (head)->sqh_last = &(elm)->field.sqe_next; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ (head)->sqh_last = &(elm)->field.sqe_next; \ (listelm)->field.sqe_next = (elm); \ } while (/*CONSTCOND*/0) #define SIMPLEQ_REMOVE_HEAD(head, field) do { \ if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ (head)->sqh_last = &(head)->sqh_first; \ } while (/*CONSTCOND*/0) #define SIMPLEQ_REMOVE(head, elm, type, field) do { \ if ((head)->sqh_first == (elm)) { \ SIMPLEQ_REMOVE_HEAD((head), field); \ } else { \ struct type *curelm = (head)->sqh_first; \ while (curelm->field.sqe_next != (elm)) \ curelm = curelm->field.sqe_next; \ if ((curelm->field.sqe_next = \ curelm->field.sqe_next->field.sqe_next) == NULL) \ (head)->sqh_last = &(curelm)->field.sqe_next; \ } \ } while (/*CONSTCOND*/0) #define SIMPLEQ_FOREACH(var, head, field) \ for ((var) = ((head)->sqh_first); \ (var); \ (var) = ((var)->field.sqe_next)) /* * Simple queue access methods. */ #define SIMPLEQ_EMPTY(head) ((head)->sqh_first == NULL) #define SIMPLEQ_FIRST(head) ((head)->sqh_first) #define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) /* * Tail queue definitions. */ #define _TAILQ_HEAD(name, type, qual) \ struct name { \ qual type *tqh_first; /* first element */ \ qual type *qual *tqh_last; /* addr of last next element */ \ } #define TAILQ_HEAD(name, type) _TAILQ_HEAD(name, struct type,) #define TAILQ_HEAD_INITIALIZER(head) \ { NULL, &(head).tqh_first } #define _TAILQ_ENTRY(type, qual) \ struct { \ qual type *tqe_next; /* next element */ \ qual type *qual *tqe_prev; /* address of previous next element */\ } #define TAILQ_ENTRY(type) _TAILQ_ENTRY(struct type,) /* * Tail queue functions. */ #define TAILQ_INIT(head) do { \ (head)->tqh_first = NULL; \ (head)->tqh_last = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_HEAD(head, elm, field) do { \ if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ (head)->tqh_first->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (head)->tqh_first = (elm); \ (elm)->field.tqe_prev = &(head)->tqh_first; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.tqe_next = NULL; \ (elm)->field.tqe_prev = (head)->tqh_last; \ *(head)->tqh_last = (elm); \ (head)->tqh_last = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ (elm)->field.tqe_next->field.tqe_prev = \ &(elm)->field.tqe_next; \ else \ (head)->tqh_last = &(elm)->field.tqe_next; \ (listelm)->field.tqe_next = (elm); \ (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ (elm)->field.tqe_next = (listelm); \ *(listelm)->field.tqe_prev = (elm); \ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_REMOVE(head, elm, field) do { \ if (((elm)->field.tqe_next) != NULL) \ (elm)->field.tqe_next->field.tqe_prev = \ (elm)->field.tqe_prev; \ else \ (head)->tqh_last = (elm)->field.tqe_prev; \ *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ } while (/*CONSTCOND*/0) #define TAILQ_FOREACH(var, head, field) \ for ((var) = ((head)->tqh_first); \ (var); \ (var) = ((var)->field.tqe_next)) #define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ for ((var) = (*(((struct headname *)((head)->tqh_last))->tqh_last)); \ (var); \ (var) = (*(((struct headname *)((var)->field.tqe_prev))->tqh_last))) #define TAILQ_CONCAT(head1, head2, field) do { \ if (!TAILQ_EMPTY(head2)) { \ *(head1)->tqh_last = (head2)->tqh_first; \ (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ (head1)->tqh_last = (head2)->tqh_last; \ TAILQ_INIT((head2)); \ } \ } while (/*CONSTCOND*/0) /* * Tail queue access methods. */ #define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) #define TAILQ_FIRST(head) ((head)->tqh_first) #define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) #define TAILQ_LAST(head, headname) \ (*(((struct headname *)((head)->tqh_last))->tqh_last)) #define TAILQ_PREV(elm, headname, field) \ (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) /* * Circular queue definitions. */ #define CIRCLEQ_HEAD(name, type) \ struct name { \ struct type *cqh_first; /* first element */ \ struct type *cqh_last; /* last element */ \ } #define CIRCLEQ_HEAD_INITIALIZER(head) \ { (void *)&head, (void *)&head } #define CIRCLEQ_ENTRY(type) \ struct { \ struct type *cqe_next; /* next element */ \ struct type *cqe_prev; /* previous element */ \ } /* * Circular queue functions. */ #define CIRCLEQ_INIT(head) do { \ (head)->cqh_first = (void *)(head); \ (head)->cqh_last = (void *)(head); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm)->field.cqe_next; \ (elm)->field.cqe_prev = (listelm); \ if ((listelm)->field.cqe_next == (void *)(head)) \ (head)->cqh_last = (elm); \ else \ (listelm)->field.cqe_next->field.cqe_prev = (elm); \ (listelm)->field.cqe_next = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \ (elm)->field.cqe_next = (listelm); \ (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \ if ((listelm)->field.cqe_prev == (void *)(head)) \ (head)->cqh_first = (elm); \ else \ (listelm)->field.cqe_prev->field.cqe_next = (elm); \ (listelm)->field.cqe_prev = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \ (elm)->field.cqe_next = (head)->cqh_first; \ (elm)->field.cqe_prev = (void *)(head); \ if ((head)->cqh_last == (void *)(head)) \ (head)->cqh_last = (elm); \ else \ (head)->cqh_first->field.cqe_prev = (elm); \ (head)->cqh_first = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \ (elm)->field.cqe_next = (void *)(head); \ (elm)->field.cqe_prev = (head)->cqh_last; \ if ((head)->cqh_first == (void *)(head)) \ (head)->cqh_first = (elm); \ else \ (head)->cqh_last->field.cqe_next = (elm); \ (head)->cqh_last = (elm); \ } while (/*CONSTCOND*/0) #define CIRCLEQ_REMOVE(head, elm, field) do { \ if ((elm)->field.cqe_next == (void *)(head)) \ (head)->cqh_last = (elm)->field.cqe_prev; \ else \ (elm)->field.cqe_next->field.cqe_prev = \ (elm)->field.cqe_prev; \ if ((elm)->field.cqe_prev == (void *)(head)) \ (head)->cqh_first = (elm)->field.cqe_next; \ else \ (elm)->field.cqe_prev->field.cqe_next = \ (elm)->field.cqe_next; \ } while (/*CONSTCOND*/0) #define CIRCLEQ_FOREACH(var, head, field) \ for ((var) = ((head)->cqh_first); \ (var) != (const void *)(head); \ (var) = ((var)->field.cqe_next)) #define CIRCLEQ_FOREACH_REVERSE(var, head, field) \ for ((var) = ((head)->cqh_last); \ (var) != (const void *)(head); \ (var) = ((var)->field.cqe_prev)) /* * Circular queue access methods. */ #define CIRCLEQ_EMPTY(head) ((head)->cqh_first == (void *)(head)) #define CIRCLEQ_FIRST(head) ((head)->cqh_first) #define CIRCLEQ_LAST(head) ((head)->cqh_last) #define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next) #define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev) #define CIRCLEQ_LOOP_NEXT(head, elm, field) \ (((elm)->field.cqe_next == (void *)(head)) \ ? ((head)->cqh_first) \ : (elm->field.cqe_next)) #define CIRCLEQ_LOOP_PREV(head, elm, field) \ (((elm)->field.cqe_prev == (void *)(head)) \ ? ((head)->cqh_last) \ : (elm->field.cqe_prev)) #endif /* sys/queue.h */ sys/msg.h000064400000004475151027430550006335 0ustar00/* Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_MSG_H #define _SYS_MSG_H #include #define __need_size_t #include /* Get common definition of System V style IPC. */ #include /* Get system dependent definition of `struct msqid_ds' and more. */ #include /* Define types required by the standard. */ #include #ifndef __pid_t_defined typedef __pid_t pid_t; # define __pid_t_defined #endif #ifndef __ssize_t_defined typedef __ssize_t ssize_t; # define __ssize_t_defined #endif /* The following System V style IPC functions implement a message queue system. The definition is found in XPG2. */ #ifdef __USE_GNU /* Template for struct to be used as argument for `msgsnd' and `msgrcv'. */ struct msgbuf { __syscall_slong_t mtype; /* type of received/sent message */ char mtext[1]; /* text of the message */ }; #endif __BEGIN_DECLS /* Message queue control operation. */ extern int msgctl (int __msqid, int __cmd, struct msqid_ds *__buf) __THROW; /* Get messages queue. */ extern int msgget (key_t __key, int __msgflg) __THROW; /* Receive message from message queue. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t msgrcv (int __msqid, void *__msgp, size_t __msgsz, long int __msgtyp, int __msgflg); /* Send message to message queue. This function is a cancellation point and therefore not marked with __THROW. */ extern int msgsnd (int __msqid, const void *__msgp, size_t __msgsz, int __msgflg); __END_DECLS #endif /* sys/msg.h */ sys/reg.h000064400000003442151027430550006315 0ustar00/* Copyright (C) 2001-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_REG_H #define _SYS_REG_H 1 #ifdef __x86_64__ /* Index into an array of 8 byte longs returned from ptrace for location of the users' stored general purpose registers. */ # define R15 0 # define R14 1 # define R13 2 # define R12 3 # define RBP 4 # define RBX 5 # define R11 6 # define R10 7 # define R9 8 # define R8 9 # define RAX 10 # define RCX 11 # define RDX 12 # define RSI 13 # define RDI 14 # define ORIG_RAX 15 # define RIP 16 # define CS 17 # define EFLAGS 18 # define RSP 19 # define SS 20 # define FS_BASE 21 # define GS_BASE 22 # define DS 23 # define ES 24 # define FS 25 # define GS 26 #else /* Index into an array of 4 byte integers returned from ptrace for * location of the users' stored general purpose registers. */ # define EBX 0 # define ECX 1 # define EDX 2 # define ESI 3 # define EDI 4 # define EBP 5 # define EAX 6 # define DS 7 # define ES 8 # define FS 9 # define GS 10 # define ORIG_EAX 11 # define EIP 12 # define CS 13 # define EFL 14 # define UESP 15 # define SS 16 #endif #endif sys/fsuid.h000064400000002243151027430550006650 0ustar00/* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_FSUID_H #define _SYS_FSUID_H 1 #include #include __BEGIN_DECLS /* Change uid used for file access control to UID, without affecting other privileges (such as who can send signals at the process). */ extern int setfsuid (__uid_t __uid) __THROW; /* Ditto for group id. */ extern int setfsgid (__gid_t __gid) __THROW; __END_DECLS #endif /* fsuid.h */ sys/sysmacros.h000064400000004066151027430550007566 0ustar00/* Definitions of macros to access `dev_t' values. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SYSMACROS_H #define _SYS_SYSMACROS_H 1 #include #include #include #define __SYSMACROS_DECL_TEMPL(rtype, name, proto) \ extern rtype gnu_dev_##name proto __THROW __attribute_const__; #define __SYSMACROS_IMPL_TEMPL(rtype, name, proto) \ __extension__ __extern_inline __attribute_const__ rtype \ __NTH (gnu_dev_##name proto) __BEGIN_DECLS __SYSMACROS_DECLARE_MAJOR (__SYSMACROS_DECL_TEMPL) __SYSMACROS_DECLARE_MINOR (__SYSMACROS_DECL_TEMPL) __SYSMACROS_DECLARE_MAKEDEV (__SYSMACROS_DECL_TEMPL) #ifdef __USE_EXTERN_INLINES __SYSMACROS_DEFINE_MAJOR (__SYSMACROS_IMPL_TEMPL) __SYSMACROS_DEFINE_MINOR (__SYSMACROS_IMPL_TEMPL) __SYSMACROS_DEFINE_MAKEDEV (__SYSMACROS_IMPL_TEMPL) #endif __END_DECLS #ifndef __SYSMACROS_NEED_IMPLEMENTATION # undef __SYSMACROS_DECL_TEMPL # undef __SYSMACROS_IMPL_TEMPL # undef __SYSMACROS_DECLARE_MAJOR # undef __SYSMACROS_DECLARE_MINOR # undef __SYSMACROS_DECLARE_MAKEDEV # undef __SYSMACROS_DEFINE_MAJOR # undef __SYSMACROS_DEFINE_MINOR # undef __SYSMACROS_DEFINE_MAKEDEV #endif #define major(dev) gnu_dev_major (dev) #define minor(dev) gnu_dev_minor (dev) #define makedev(maj, min) gnu_dev_makedev (maj, min) #endif /* sys/sysmacros.h */ sys/timeb.h000064400000002540151027430550006636 0ustar00/* Copyright (C) 1994-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_TIMEB_H #define _SYS_TIMEB_H 1 #include #include __BEGIN_DECLS /* Structure returned by the `ftime' function. */ struct timeb { time_t time; /* Seconds since epoch, as from `time'. */ unsigned short int millitm; /* Additional milliseconds. */ short int timezone; /* Minutes west of GMT. */ short int dstflag; /* Nonzero if Daylight Savings Time used. */ }; /* Fill in TIMEBUF with information about the current time. */ extern int ftime (struct timeb *__timebuf); __END_DECLS #endif /* sys/timeb.h */ sys/soundcard.h000064400000000035151027430550007515 0ustar00#include sys/bitypes.h000064400000000126151027430550007213 0ustar00/* The GNU defines all the necessary types. */ #include sys/syslog.h000064400000017026151027430550007063 0ustar00/* * Copyright (c) 1982, 1986, 1988, 1993 * The Regents of the University of California. 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)syslog.h 8.1 (Berkeley) 6/2/93 */ #ifndef _SYS_SYSLOG_H #define _SYS_SYSLOG_H 1 #include #define __need___va_list #include /* This file defines _PATH_LOG. */ #include /* * priorities/facilities are encoded into a single 32-bit quantity, where the * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility * (0-big number). Both the priorities and the facilities map roughly * one-to-one to strings in the syslogd(8) source code. This mapping is * included in this file. * * priorities (these are ordered) */ #define LOG_EMERG 0 /* system is unusable */ #define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_CRIT 2 /* critical conditions */ #define LOG_ERR 3 /* error conditions */ #define LOG_WARNING 4 /* warning conditions */ #define LOG_NOTICE 5 /* normal but significant condition */ #define LOG_INFO 6 /* informational */ #define LOG_DEBUG 7 /* debug-level messages */ #define LOG_PRIMASK 0x07 /* mask to extract priority part (internal) */ /* extract priority */ #define LOG_PRI(p) ((p) & LOG_PRIMASK) #define LOG_MAKEPRI(fac, pri) ((fac) | (pri)) #ifdef SYSLOG_NAMES #define INTERNAL_NOPRI 0x10 /* the "no priority" priority */ /* mark "facility" */ #define INTERNAL_MARK LOG_MAKEPRI(LOG_NFACILITIES << 3, 0) typedef struct _code { char *c_name; int c_val; } CODE; CODE prioritynames[] = { { "alert", LOG_ALERT }, { "crit", LOG_CRIT }, { "debug", LOG_DEBUG }, { "emerg", LOG_EMERG }, { "err", LOG_ERR }, { "error", LOG_ERR }, /* DEPRECATED */ { "info", LOG_INFO }, { "none", INTERNAL_NOPRI }, /* INTERNAL */ { "notice", LOG_NOTICE }, { "panic", LOG_EMERG }, /* DEPRECATED */ { "warn", LOG_WARNING }, /* DEPRECATED */ { "warning", LOG_WARNING }, { NULL, -1 } }; #endif /* facility codes */ #define LOG_KERN (0<<3) /* kernel messages */ #define LOG_USER (1<<3) /* random user-level messages */ #define LOG_MAIL (2<<3) /* mail system */ #define LOG_DAEMON (3<<3) /* system daemons */ #define LOG_AUTH (4<<3) /* security/authorization messages */ #define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */ #define LOG_LPR (6<<3) /* line printer subsystem */ #define LOG_NEWS (7<<3) /* network news subsystem */ #define LOG_UUCP (8<<3) /* UUCP subsystem */ #define LOG_CRON (9<<3) /* clock daemon */ #define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */ #define LOG_FTP (11<<3) /* ftp daemon */ /* other codes through 15 reserved for system use */ #define LOG_LOCAL0 (16<<3) /* reserved for local use */ #define LOG_LOCAL1 (17<<3) /* reserved for local use */ #define LOG_LOCAL2 (18<<3) /* reserved for local use */ #define LOG_LOCAL3 (19<<3) /* reserved for local use */ #define LOG_LOCAL4 (20<<3) /* reserved for local use */ #define LOG_LOCAL5 (21<<3) /* reserved for local use */ #define LOG_LOCAL6 (22<<3) /* reserved for local use */ #define LOG_LOCAL7 (23<<3) /* reserved for local use */ #define LOG_NFACILITIES 24 /* current number of facilities */ #define LOG_FACMASK 0x03f8 /* mask to extract facility part */ /* facility of pri */ #define LOG_FAC(p) (((p) & LOG_FACMASK) >> 3) #ifdef SYSLOG_NAMES CODE facilitynames[] = { { "auth", LOG_AUTH }, { "authpriv", LOG_AUTHPRIV }, { "cron", LOG_CRON }, { "daemon", LOG_DAEMON }, { "ftp", LOG_FTP }, { "kern", LOG_KERN }, { "lpr", LOG_LPR }, { "mail", LOG_MAIL }, { "mark", INTERNAL_MARK }, /* INTERNAL */ { "news", LOG_NEWS }, { "security", LOG_AUTH }, /* DEPRECATED */ { "syslog", LOG_SYSLOG }, { "user", LOG_USER }, { "uucp", LOG_UUCP }, { "local0", LOG_LOCAL0 }, { "local1", LOG_LOCAL1 }, { "local2", LOG_LOCAL2 }, { "local3", LOG_LOCAL3 }, { "local4", LOG_LOCAL4 }, { "local5", LOG_LOCAL5 }, { "local6", LOG_LOCAL6 }, { "local7", LOG_LOCAL7 }, { NULL, -1 } }; #endif /* * arguments to setlogmask. */ #define LOG_MASK(pri) (1 << (pri)) /* mask for one priority */ #define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) /* all priorities through pri */ /* * Option flags for openlog. * * LOG_ODELAY no longer does anything. * LOG_NDELAY is the inverse of what it used to be. */ #define LOG_PID 0x01 /* log the pid with each message */ #define LOG_CONS 0x02 /* log on the console if errors in sending */ #define LOG_ODELAY 0x04 /* delay open until first syslog() (default) */ #define LOG_NDELAY 0x08 /* don't delay open */ #define LOG_NOWAIT 0x10 /* don't wait for console forks: DEPRECATED */ #define LOG_PERROR 0x20 /* log to stderr as well */ __BEGIN_DECLS /* Close descriptor used to write to system logger. This function is a possible cancellation point and therefore not marked with __THROW. */ extern void closelog (void); /* Open connection to system logger. This function is a possible cancellation point and therefore not marked with __THROW. */ extern void openlog (const char *__ident, int __option, int __facility); /* Set the log mask level. */ extern int setlogmask (int __mask) __THROW; /* Generate a log message using FMT string and option arguments. This function is a possible cancellation point and therefore not marked with __THROW. */ extern void syslog (int __pri, const char *__fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); #ifdef __USE_MISC /* Generate a log message using FMT and using arguments pointed to by AP. This function is not part of POSIX and therefore no official cancellation point. But due to similarity with an POSIX interface or due to the implementation it is a cancellation point and therefore not marked with __THROW. */ extern void vsyslog (int __pri, const char *__fmt, __gnuc_va_list __ap) __attribute__ ((__format__ (__printf__, 2, 0))); #endif /* Define some macros helping to catch buffer overflows. */ #if __USE_FORTIFY_LEVEL > 0 && defined __fortify_function # include #endif #ifdef __LDBL_COMPAT # include #endif __END_DECLS #endif /* sys/syslog.h */ sys/statfs.h000064400000004055151027430550007045 0ustar00/* Definitions for getting information about a filesystem. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_STATFS_H #define _SYS_STATFS_H 1 #include /* Get the system-specific definition of `struct statfs'. */ #include __BEGIN_DECLS /* Return information about the filesystem on which FILE resides. */ #ifndef __USE_FILE_OFFSET64 extern int statfs (const char *__file, struct statfs *__buf) __THROW __nonnull ((1, 2)); #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (statfs, (const char *__file, struct statfs *__buf), statfs64) __nonnull ((1, 2)); # else # define statfs statfs64 # endif #endif #ifdef __USE_LARGEFILE64 extern int statfs64 (const char *__file, struct statfs64 *__buf) __THROW __nonnull ((1, 2)); #endif /* Return information about the filesystem containing the file FILDES refers to. */ #ifndef __USE_FILE_OFFSET64 extern int fstatfs (int __fildes, struct statfs *__buf) __THROW __nonnull ((2)); #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (fstatfs, (int __fildes, struct statfs *__buf), fstatfs64) __nonnull ((2)); # else # define fstatfs fstatfs64 # endif #endif #ifdef __USE_LARGEFILE64 extern int fstatfs64 (int __fildes, struct statfs64 *__buf) __THROW __nonnull ((2)); #endif __END_DECLS #endif /* sys/statfs.h */ sys/uio.h000064400000014207151027430550006335 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_UIO_H #define _SYS_UIO_H 1 #include #include #include #include #ifdef __IOV_MAX # define UIO_MAXIOV __IOV_MAX #else # undef UIO_MAXIOV #endif __BEGIN_DECLS /* Read data from file descriptor FD, and put the result in the buffers described by IOVEC, which is a vector of COUNT 'struct iovec's. The buffers are filled in the order specified. Operates just like 'read' (see ) except that data are put in IOVEC instead of a contiguous buffer. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t readv (int __fd, const struct iovec *__iovec, int __count) __wur; /* Write data pointed by the buffers described by IOVEC, which is a vector of COUNT 'struct iovec's, to file descriptor FD. The data is written in the order specified. Operates just like 'write' (see ) except that the data are taken from IOVEC instead of a contiguous buffer. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t writev (int __fd, const struct iovec *__iovec, int __count) __wur; #ifdef __USE_MISC # ifndef __USE_FILE_OFFSET64 /* Read data from file descriptor FD at the given position OFFSET without change the file pointer, and put the result in the buffers described by IOVEC, which is a vector of COUNT 'struct iovec's. The buffers are filled in the order specified. Operates just like 'pread' (see ) except that data are put in IOVEC instead of a contiguous buffer. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t preadv (int __fd, const struct iovec *__iovec, int __count, __off_t __offset) __wur; /* Write data pointed by the buffers described by IOVEC, which is a vector of COUNT 'struct iovec's, to file descriptor FD at the given position OFFSET without change the file pointer. The data is written in the order specified. Operates just like 'pwrite' (see ) except that the data are taken from IOVEC instead of a contiguous buffer. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t pwritev (int __fd, const struct iovec *__iovec, int __count, __off_t __offset) __wur; # else # ifdef __REDIRECT extern ssize_t __REDIRECT (preadv, (int __fd, const struct iovec *__iovec, int __count, __off64_t __offset), preadv64) __wur; extern ssize_t __REDIRECT (pwritev, (int __fd, const struct iovec *__iovec, int __count, __off64_t __offset), pwritev64) __wur; # else # define preadv preadv64 # define pwritev pwritev64 # endif # endif # ifdef __USE_LARGEFILE64 /* Read data from file descriptor FD at the given position OFFSET without change the file pointer, and put the result in the buffers described by IOVEC, which is a vector of COUNT 'struct iovec's. The buffers are filled in the order specified. Operates just like 'pread' (see ) except that data are put in IOVEC instead of a contiguous buffer. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t preadv64 (int __fd, const struct iovec *__iovec, int __count, __off64_t __offset) __wur; /* Write data pointed by the buffers described by IOVEC, which is a vector of COUNT 'struct iovec's, to file descriptor FD at the given position OFFSET without change the file pointer. The data is written in the order specified. Operates just like 'pwrite' (see ) except that the data are taken from IOVEC instead of a contiguous buffer. This function is a cancellation point and therefore not marked with __THROW. */ extern ssize_t pwritev64 (int __fd, const struct iovec *__iovec, int __count, __off64_t __offset) __wur; # endif #endif /* Use misc. */ #ifdef __USE_GNU # ifndef __USE_FILE_OFFSET64 /* Same as preadv but with an additional flag argumenti defined at uio.h. */ extern ssize_t preadv2 (int __fp, const struct iovec *__iovec, int __count, __off_t __offset, int ___flags) __wur; /* Same as preadv but with an additional flag argument defined at uio.h. */ extern ssize_t pwritev2 (int __fd, const struct iovec *__iodev, int __count, __off_t __offset, int __flags) __wur; # else # ifdef __REDIRECT extern ssize_t __REDIRECT (pwritev2, (int __fd, const struct iovec *__iovec, int __count, __off64_t __offset, int __flags), pwritev64v2) __wur; extern ssize_t __REDIRECT (preadv2, (int __fd, const struct iovec *__iovec, int __count, __off64_t __offset, int __flags), preadv64v2) __wur; # else # define preadv2 preadv64v2 # define pwritev2 pwritev64v2 # endif # endif # ifdef __USE_LARGEFILE64 /* Same as preadv but with an additional flag argumenti defined at uio.h. */ extern ssize_t preadv64v2 (int __fp, const struct iovec *__iovec, int __count, __off64_t __offset, int ___flags) __wur; /* Same as preadv but with an additional flag argument defined at uio.h. */ extern ssize_t pwritev64v2 (int __fd, const struct iovec *__iodev, int __count, __off64_t __offset, int __flags) __wur; # endif #endif /* Use GNU. */ __END_DECLS /* Some operating systems provide system-specific extensions to this header. */ #ifdef __USE_GNU # include #endif #endif /* sys/uio.h */ sys/times.h000064400000003074151027430550006662 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * POSIX Standard: 4.5.2 Process Times */ #ifndef _SYS_TIMES_H #define _SYS_TIMES_H 1 #include #include __BEGIN_DECLS /* Structure describing CPU time used by a process and its children. */ struct tms { clock_t tms_utime; /* User CPU time. */ clock_t tms_stime; /* System CPU time. */ clock_t tms_cutime; /* User CPU time of dead children. */ clock_t tms_cstime; /* System CPU time of dead children. */ }; /* Store the CPU time used by this process and all its dead children (and their dead children) in BUFFER. Return the elapsed real time, or (clock_t) -1 for errors. All times are in CLK_TCKths of a second. */ extern clock_t times (struct tms *__buffer) __THROW; __END_DECLS #endif /* sys/times.h */ sys/swap.h000064400000003070151027430550006507 0ustar00/* Calls to enable and disable swapping on specified locations. Linux version. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SWAP_H #define _SYS_SWAP_H 1 #include /* The swap priority is encoded as: (prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK */ #define SWAP_FLAG_PREFER 0x8000 /* Set if swap priority is specified. */ #define SWAP_FLAG_PRIO_MASK 0x7fff #define SWAP_FLAG_PRIO_SHIFT 0 #define SWAP_FLAG_DISCARD 0x10000 /* Discard swap cluster after use. */ __BEGIN_DECLS /* Make the block special device PATH available to the system for swapping. This call is restricted to the super-user. */ extern int swapon (const char *__path, int __flags) __THROW; /* Stop using block special device PATH for swapping. */ extern int swapoff (const char *__path) __THROW; __END_DECLS #endif /* _SYS_SWAP_H */ sys/file.h000064400000003212151027430550006452 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_FILE_H #define _SYS_FILE_H 1 #include #ifndef _FCNTL_H # include #endif __BEGIN_DECLS /* Alternate names for values for the WHENCE argument to `lseek'. These are the same as SEEK_SET, SEEK_CUR, and SEEK_END, respectively. */ #ifndef L_SET # define L_SET 0 /* Seek from beginning of file. */ # define L_INCR 1 /* Seek from current position. */ # define L_XTND 2 /* Seek from end of file. */ #endif /* Operations for the `flock' call. */ #define LOCK_SH 1 /* Shared lock. */ #define LOCK_EX 2 /* Exclusive lock. */ #define LOCK_UN 8 /* Unlock. */ /* Can be OR'd in to one of the above. */ #define LOCK_NB 4 /* Don't block when locking. */ /* Apply or remove an advisory lock, according to OPERATION, on the file FD refers to. */ extern int flock (int __fd, int __operation) __THROW; __END_DECLS #endif /* sys/file.h */ sys/reboot.h000064400000003140151027430550007025 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* This file should define RB_* macros to be used as flag bits in the argument to the `reboot' system call. */ #ifndef _SYS_REBOOT_H #define _SYS_REBOOT_H 1 #include /* Perform a hard reset now. */ #define RB_AUTOBOOT 0x01234567 /* Halt the system. */ #define RB_HALT_SYSTEM 0xcdef0123 /* Enable reboot using Ctrl-Alt-Delete keystroke. */ #define RB_ENABLE_CAD 0x89abcdef /* Disable reboot using Ctrl-Alt-Delete keystroke. */ #define RB_DISABLE_CAD 0 /* Stop system and switch power off if possible. */ #define RB_POWER_OFF 0x4321fedc /* Suspend system using software suspend. */ #define RB_SW_SUSPEND 0xd000fce2 /* Reboot system into new kernel. */ #define RB_KEXEC 0x45584543 __BEGIN_DECLS /* Reboot or halt the system. */ extern int reboot (int __howto) __THROW; __END_DECLS #endif /* _SYS_REBOOT_H */ sys/signal.h000064400000000024151027430550007006 0ustar00#include sys/debugreg.h000064400000006767151027430550007341 0ustar00/* Copyright (C) 2001-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_DEBUGREG_H #define _SYS_DEBUGREG_H 1 /* Indicate the register numbers for a number of the specific debug registers. Registers 0-3 contain the addresses we wish to trap on */ #define DR_FIRSTADDR 0 /* u_debugreg[DR_FIRSTADDR] */ #define DR_LASTADDR 3 /* u_debugreg[DR_LASTADDR] */ #define DR_STATUS 6 /* u_debugreg[DR_STATUS] */ #define DR_CONTROL 7 /* u_debugreg[DR_CONTROL] */ /* Define a few things for the status register. We can use this to determine which debugging register was responsible for the trap. The other bits are either reserved or not of interest to us. */ #define DR_TRAP0 (0x1) /* db0 */ #define DR_TRAP1 (0x2) /* db1 */ #define DR_TRAP2 (0x4) /* db2 */ #define DR_TRAP3 (0x8) /* db3 */ #define DR_STEP (0x4000) /* single-step */ #define DR_SWITCH (0x8000) /* task switch */ /* Now define a bunch of things for manipulating the control register. The top two bytes of the control register consist of 4 fields of 4 bits - each field corresponds to one of the four debug registers, and indicates what types of access we trap on, and how large the data field is that we are looking at */ #define DR_CONTROL_SHIFT 16 /* Skip this many bits in ctl register */ #define DR_CONTROL_SIZE 4 /* 4 control bits per register */ #define DR_RW_EXECUTE (0x0) /* Settings for the access types to trap on */ #define DR_RW_WRITE (0x1) #define DR_RW_READ (0x3) #define DR_LEN_1 (0x0) /* Settings for data length to trap on */ #define DR_LEN_2 (0x4) #define DR_LEN_4 (0xC) #ifdef __x86_64__ # define DR_LEN_8 (0x8) #endif /* The low byte to the control register determine which registers are enabled. There are 4 fields of two bits. One bit is "local", meaning that the processor will reset the bit after a task switch and the other is global meaning that we have to explicitly reset the bit. With linux, you can use either one, since we explicitly zero the register when we enter kernel mode. */ #define DR_LOCAL_ENABLE_SHIFT 0 /* Extra shift to the local enable bit */ #define DR_GLOBAL_ENABLE_SHIFT 1 /* Extra shift to the global enable bit */ #define DR_ENABLE_SIZE 2 /* 2 enable bits per register */ #define DR_LOCAL_ENABLE_MASK (0x55) /* Set local bits for all 4 regs */ #define DR_GLOBAL_ENABLE_MASK (0xAA) /* Set global bits for all 4 regs */ /* The second byte to the control register has a few special things. */ #ifdef __x86_64__ # define DR_CONTROL_RESERVED (0xFFFFFFFF0000FC00ULL) /* Reserved */ #else # define DR_CONTROL_RESERVED (0x00FC00U) /* Reserved */ #endif #define DR_LOCAL_SLOWDOWN (0x100) /* Local slow the pipeline */ #define DR_GLOBAL_SLOWDOWN (0x200) /* Global slow the pipeline */ #endif /* sys/debugreg.h */ sys/gmon_out.h000064400000005113151027430550007364 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by David Mosberger . The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* This file specifies the format of gmon.out files. It should have as few external dependencies as possible as it is going to be included in many different programs. That is, minimize the number of #include's. A gmon.out file consists of a header (defined by gmon_hdr) followed by a sequence of records. Each record starts with a one-byte tag identifying the type of records, followed by records specific data. */ #ifndef _SYS_GMON_OUT_H #define _SYS_GMON_OUT_H 1 #include #define GMON_MAGIC "gmon" /* magic cookie */ #define GMON_VERSION 1 /* version number */ /* For profiling shared object we need a new format. */ #define GMON_SHOBJ_VERSION 0x1ffff __BEGIN_DECLS /* * Raw header as it appears on file (without padding). This header * always comes first in gmon.out and is then followed by a series * records defined below. */ struct gmon_hdr { char cookie[4]; char version[4]; char spare[3 * 4]; }; /* types of records in this file: */ typedef enum { GMON_TAG_TIME_HIST = 0, GMON_TAG_CG_ARC = 1, GMON_TAG_BB_COUNT = 2 } GMON_Record_Tag; struct gmon_hist_hdr { char low_pc[sizeof (char *)]; /* base pc address of sample buffer */ char high_pc[sizeof (char *)]; /* max pc address of sampled buffer */ char hist_size[4]; /* size of sample buffer */ char prof_rate[4]; /* profiling clock rate */ char dimen[15]; /* phys. dim., usually "seconds" */ char dimen_abbrev; /* usually 's' for "seconds" */ }; struct gmon_cg_arc_record { char from_pc[sizeof (char *)]; /* address within caller's body */ char self_pc[sizeof (char *)]; /* address within callee's body */ char count[4]; /* number of arc traversals */ }; __END_DECLS #endif /* sys/gmon_out.h */ sys/errno.h000064400000000023151027430550006655 0ustar00#include sys/vfs.h000064400000000241151027430550006330 0ustar00/* Other systems declare `struct statfs' et al in , so we have this file to be compatible with programs expecting it. */ #include sys/elf.h000064400000001777151027430550006317 0ustar00/* Copyright (C) 1998-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_ELF_H #define _SYS_ELF_H 1 #ifdef __x86_64__ # error This header is unsupported on x86-64. #else # warning "This header is obsolete; use instead." # include #endif #endif /* _SYS_ELF_H */ sys/psx_syscall.h000064400000005421151027430550010103 0ustar00/* * Copyright (c) 2019 Andrew G. Morgan * * This header, and the -lpsx library, provide a number of things to * support POSIX semantics for syscalls associated with the pthread * library. Linking this code is tricky and is done as follows: * * ld ... -lpsx -lpthread --wrap=pthread_create * or, gcc ... -lpsx -lpthread -Wl,-wrap,pthread_create * * glibc provides a subset of this functionality natively through the * nptl:setxid mechanism and could implement psx_syscall() directly * using that style of functionality but, as of 2019-11-30, the setxid * mechanism is limited to 9 specific set*() syscalls that do not * support the syscall6 API (needed for prctl functions and the ambient * capabilities set for example). */ #ifndef _SYS_PSX_SYSCALL_H #define _SYS_PSX_SYSCALL_H #ifdef __cplusplus extern "C" { #endif #include /* * psx_syscall performs the specified syscall on all psx registered * threads. The mechanism by which this occurs is much less efficient * than a standard system call on Linux, so it should only be used * when POSIX semantics are required to change process relevant * security state. * * Glibc has native support for POSIX semantics on setgroups() and the * 8 set*[gu]id() functions. So, there is no need to use psx_syscall() * for these calls. This call exists for all the other system calls * that need to maintain parity on all pthreads of a program. * * Some macrology is used to allow the caller to provide only as many * arguments as needed, thus psx_syscall() cannot be used as a * function pointer. For those situations, we define psx_syscall3() * and psx_syscall6(). */ #define psx_syscall(syscall_nr, ...) \ __psx_syscall(syscall_nr, __VA_ARGS__, (long int) 6, (long int) 5, \ (long int) 4, (long int) 3, (long int) 2, \ (long int) 1, (long int) 0) long int __psx_syscall(long int syscall_nr, ...); long int psx_syscall3(long int syscall_nr, long int arg1, long int arg2, long int arg3); long int psx_syscall6(long int syscall_nr, long int arg1, long int arg2, long int arg3, long int arg4, long int arg5, long int arg6); /* * This function should be used by systems to obtain pointers to the * two syscall functions provided by the PSX library. A linkage trick * is to define this function as weak in a library that can optionally * use libpsx and then, should the caller link -lpsx, that library can * implicitly use these POSIX semantics syscalls. See libcap for an * example of this useage. */ void psx_load_syscalls(long int (**syscall_fn)(long int, long int, long int, long int), long int (**syscall6_fn)(long int, long int, long int, long int, long int, long int, long int)); #ifdef __cplusplus } #endif #endif /* _SYS_PSX_SYSCALL_H */ sys/statvfs.h000064400000005403151027430550007231 0ustar00/* Definitions for getting information about a filesystem. Copyright (C) 1998-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_STATVFS_H #define _SYS_STATVFS_H 1 #include /* Get the system-specific definition of `struct statfs'. */ #include #ifndef __USE_FILE_OFFSET64 # ifndef __fsblkcnt_t_defined typedef __fsblkcnt_t fsblkcnt_t; /* Type to count file system blocks. */ # define __fsblkcnt_t_defined # endif # ifndef __fsfilcnt_t_defined typedef __fsfilcnt_t fsfilcnt_t; /* Type to count file system inodes. */ # define __fsfilcnt_t_defined # endif #else # ifndef __fsblkcnt_t_defined typedef __fsblkcnt64_t fsblkcnt_t; /* Type to count file system blocks. */ # define __fsblkcnt_t_defined # endif # ifndef __fsfilcnt_t_defined typedef __fsfilcnt64_t fsfilcnt_t; /* Type to count file system inodes. */ # define __fsfilcnt_t_defined # endif #endif __BEGIN_DECLS /* Return information about the filesystem on which FILE resides. */ #ifndef __USE_FILE_OFFSET64 extern int statvfs (const char *__restrict __file, struct statvfs *__restrict __buf) __THROW __nonnull ((1, 2)); #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (statvfs, (const char *__restrict __file, struct statvfs *__restrict __buf), statvfs64) __nonnull ((1, 2)); # else # define statvfs statvfs64 # endif #endif #ifdef __USE_LARGEFILE64 extern int statvfs64 (const char *__restrict __file, struct statvfs64 *__restrict __buf) __THROW __nonnull ((1, 2)); #endif /* Return information about the filesystem containing the file FILDES refers to. */ #ifndef __USE_FILE_OFFSET64 extern int fstatvfs (int __fildes, struct statvfs *__buf) __THROW __nonnull ((2)); #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (fstatvfs, (int __fildes, struct statvfs *__buf), fstatvfs64) __nonnull ((2)); # else # define fstatvfs fstatvfs64 # endif #endif #ifdef __USE_LARGEFILE64 extern int fstatvfs64 (int __fildes, struct statvfs64 *__buf) __THROW __nonnull ((2)); #endif __END_DECLS #endif /* sys/statvfs.h */ sys/shm.h000064400000003521151027430550006325 0ustar00/* Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_SHM_H #define _SYS_SHM_H 1 #include #define __need_size_t #include /* Get common definition of System V style IPC. */ #include /* Get system dependent definition of `struct shmid_ds' and more. */ #include /* Define types required by the standard. */ #include #ifdef __USE_XOPEN # ifndef __pid_t_defined typedef __pid_t pid_t; # define __pid_t_defined # endif #endif /* X/Open */ __BEGIN_DECLS /* The following System V style IPC functions implement a shared memory facility. The definition is found in XPG4.2. */ /* Shared memory control operation. */ extern int shmctl (int __shmid, int __cmd, struct shmid_ds *__buf) __THROW; /* Get shared memory segment. */ extern int shmget (key_t __key, size_t __size, int __shmflg) __THROW; /* Attach shared memory segment. */ extern void *shmat (int __shmid, const void *__shmaddr, int __shmflg) __THROW; /* Detach shared memory segment. */ extern int shmdt (const void *__shmaddr) __THROW; __END_DECLS #endif /* sys/shm.h */ sys/mtio.h000064400000025632151027430550006515 0ustar00/* Structures and definitions for magnetic tape I/O control commands. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* Written by H. Bergman . */ #ifndef _SYS_MTIO_H #define _SYS_MTIO_H 1 /* Get necessary definitions from system and kernel headers. */ #include #include /* Structure for MTIOCTOP - magnetic tape operation command. */ struct mtop { short int mt_op; /* Operations defined below. */ int mt_count; /* How many of them. */ }; #define _IOT_mtop /* Hurd ioctl type field. */ \ _IOT (_IOTS (short), 1, _IOTS (int), 1, 0, 0) /* Magnetic Tape operations [Not all operations supported by all drivers]. */ #define MTRESET 0 /* +reset drive in case of problems. */ #define MTFSF 1 /* Forward space over FileMark, * position at first record of next file. */ #define MTBSF 2 /* Backward space FileMark (position before FM). */ #define MTFSR 3 /* Forward space record. */ #define MTBSR 4 /* Backward space record. */ #define MTWEOF 5 /* Write an end-of-file record (mark). */ #define MTREW 6 /* Rewind. */ #define MTOFFL 7 /* Rewind and put the drive offline (eject?). */ #define MTNOP 8 /* No op, set status only (read with MTIOCGET). */ #define MTRETEN 9 /* Retension tape. */ #define MTBSFM 10 /* +backward space FileMark, position at FM. */ #define MTFSFM 11 /* +forward space FileMark, position at FM. */ #define MTEOM 12 /* Goto end of recorded media (for appending files). MTEOM positions after the last FM, ready for appending another file. */ #define MTERASE 13 /* Erase tape -- be careful! */ #define MTRAS1 14 /* Run self test 1 (nondestructive). */ #define MTRAS2 15 /* Run self test 2 (destructive). */ #define MTRAS3 16 /* Reserved for self test 3. */ #define MTSETBLK 20 /* Set block length (SCSI). */ #define MTSETDENSITY 21 /* Set tape density (SCSI). */ #define MTSEEK 22 /* Seek to block (Tandberg, etc.). */ #define MTTELL 23 /* Tell block (Tandberg, etc.). */ #define MTSETDRVBUFFER 24 /* Set the drive buffering according to SCSI-2. Ordinary buffered operation with code 1. */ #define MTFSS 25 /* Space forward over setmarks. */ #define MTBSS 26 /* Space backward over setmarks. */ #define MTWSM 27 /* Write setmarks. */ #define MTLOCK 28 /* Lock the drive door. */ #define MTUNLOCK 29 /* Unlock the drive door. */ #define MTLOAD 30 /* Execute the SCSI load command. */ #define MTUNLOAD 31 /* Execute the SCSI unload command. */ #define MTCOMPRESSION 32/* Control compression with SCSI mode page 15. */ #define MTSETPART 33 /* Change the active tape partition. */ #define MTMKPART 34 /* Format the tape with one or two partitions. */ /* structure for MTIOCGET - mag tape get status command */ struct mtget { long int mt_type; /* Type of magtape device. */ long int mt_resid; /* Residual count: (not sure) number of bytes ignored, or number of files not skipped, or number of records not skipped. */ /* The following registers are device dependent. */ long int mt_dsreg; /* Status register. */ long int mt_gstat; /* Generic (device independent) status. */ long int mt_erreg; /* Error register. */ /* The next two fields are not always used. */ __daddr_t mt_fileno; /* Number of current file on tape. */ __daddr_t mt_blkno; /* Current block number. */ }; #define _IOT_mtget /* Hurd ioctl type field. */ \ _IOT (_IOTS (long), 7, 0, 0, 0, 0) /* Constants for mt_type. Not all of these are supported, and these are not all of the ones that are supported. */ #define MT_ISUNKNOWN 0x01 #define MT_ISQIC02 0x02 /* Generic QIC-02 tape streamer. */ #define MT_ISWT5150 0x03 /* Wangtek 5150EQ, QIC-150, QIC-02. */ #define MT_ISARCHIVE_5945L2 0x04 /* Archive 5945L-2, QIC-24, QIC-02?. */ #define MT_ISCMSJ500 0x05 /* CMS Jumbo 500 (QIC-02?). */ #define MT_ISTDC3610 0x06 /* Tandberg 6310, QIC-24. */ #define MT_ISARCHIVE_VP60I 0x07 /* Archive VP60i, QIC-02. */ #define MT_ISARCHIVE_2150L 0x08 /* Archive Viper 2150L. */ #define MT_ISARCHIVE_2060L 0x09 /* Archive Viper 2060L. */ #define MT_ISARCHIVESC499 0x0A /* Archive SC-499 QIC-36 controller. */ #define MT_ISQIC02_ALL_FEATURES 0x0F /* Generic QIC-02 with all features. */ #define MT_ISWT5099EEN24 0x11 /* Wangtek 5099-een24, 60MB, QIC-24. */ #define MT_ISTEAC_MT2ST 0x12 /* Teac MT-2ST 155mb drive, Teac DC-1 card (Wangtek type). */ #define MT_ISEVEREX_FT40A 0x32 /* Everex FT40A (QIC-40). */ #define MT_ISDDS1 0x51 /* DDS device without partitions. */ #define MT_ISDDS2 0x52 /* DDS device with partitions. */ #define MT_ISSCSI1 0x71 /* Generic ANSI SCSI-1 tape unit. */ #define MT_ISSCSI2 0x72 /* Generic ANSI SCSI-2 tape unit. */ /* QIC-40/80/3010/3020 ftape supported drives. 20bit vendor ID + 0x800000 (see vendors.h in ftape distribution). */ #define MT_ISFTAPE_UNKNOWN 0x800000 /* obsolete */ #define MT_ISFTAPE_FLAG 0x800000 struct mt_tape_info { long int t_type; /* Device type id (mt_type). */ char *t_name; /* Descriptive name. */ }; #define MT_TAPE_INFO \ { \ {MT_ISUNKNOWN, "Unknown type of tape device"}, \ {MT_ISQIC02, "Generic QIC-02 tape streamer"}, \ {MT_ISWT5150, "Wangtek 5150, QIC-150"}, \ {MT_ISARCHIVE_5945L2, "Archive 5945L-2"}, \ {MT_ISCMSJ500, "CMS Jumbo 500"}, \ {MT_ISTDC3610, "Tandberg TDC 3610, QIC-24"}, \ {MT_ISARCHIVE_VP60I, "Archive VP60i, QIC-02"}, \ {MT_ISARCHIVE_2150L, "Archive Viper 2150L"}, \ {MT_ISARCHIVE_2060L, "Archive Viper 2060L"}, \ {MT_ISARCHIVESC499, "Archive SC-499 QIC-36 controller"}, \ {MT_ISQIC02_ALL_FEATURES, "Generic QIC-02 tape, all features"}, \ {MT_ISWT5099EEN24, "Wangtek 5099-een24, 60MB"}, \ {MT_ISTEAC_MT2ST, "Teac MT-2ST 155mb data cassette drive"}, \ {MT_ISEVEREX_FT40A, "Everex FT40A, QIC-40"}, \ {MT_ISSCSI1, "Generic SCSI-1 tape"}, \ {MT_ISSCSI2, "Generic SCSI-2 tape"}, \ {0, NULL} \ } /* Structure for MTIOCPOS - mag tape get position command. */ struct mtpos { long int mt_blkno; /* Current block number. */ }; #define _IOT_mtpos /* Hurd ioctl type field. */ \ _IOT_SIMPLE (long) /* Structure for MTIOCGETCONFIG/MTIOCSETCONFIG primarily intended as an interim solution for QIC-02 until DDI is fully implemented. */ struct mtconfiginfo { long int mt_type; /* Drive type. */ long int ifc_type; /* Interface card type. */ unsigned short int irqnr; /* IRQ number to use. */ unsigned short int dmanr; /* DMA channel to use. */ unsigned short int port; /* IO port base address. */ unsigned long int debug; /* Debugging flags. */ unsigned have_dens:1; unsigned have_bsf:1; unsigned have_fsr:1; unsigned have_bsr:1; unsigned have_eod:1; unsigned have_seek:1; unsigned have_tell:1; unsigned have_ras1:1; unsigned have_ras2:1; unsigned have_ras3:1; unsigned have_qfa:1; unsigned pad1:5; char reserved[10]; }; #define _IOT_mtconfiginfo /* Hurd ioctl type field. */ \ _IOT (_IOTS (long), 2, _IOTS (short), 3, _IOTS (long), 1) /* XXX wrong */ /* Magnetic tape I/O control commands. */ #define MTIOCTOP _IOW('m', 1, struct mtop) /* Do a mag tape op. */ #define MTIOCGET _IOR('m', 2, struct mtget) /* Get tape status. */ #define MTIOCPOS _IOR('m', 3, struct mtpos) /* Get tape position.*/ /* The next two are used by the QIC-02 driver for runtime reconfiguration. See tpqic02.h for struct mtconfiginfo. */ #define MTIOCGETCONFIG _IOR('m', 4, struct mtconfiginfo) /* Get tape config.*/ #define MTIOCSETCONFIG _IOW('m', 5, struct mtconfiginfo) /* Set tape config.*/ /* Generic Mag Tape (device independent) status macros for examining mt_gstat -- HP-UX compatible. There is room for more generic status bits here, but I don't know which of them are reserved. At least three or so should be added to make this really useful. */ #define GMT_EOF(x) ((x) & 0x80000000) #define GMT_BOT(x) ((x) & 0x40000000) #define GMT_EOT(x) ((x) & 0x20000000) #define GMT_SM(x) ((x) & 0x10000000) /* DDS setmark */ #define GMT_EOD(x) ((x) & 0x08000000) /* DDS EOD */ #define GMT_WR_PROT(x) ((x) & 0x04000000) /* #define GMT_ ? ((x) & 0x02000000) */ #define GMT_ONLINE(x) ((x) & 0x01000000) #define GMT_D_6250(x) ((x) & 0x00800000) #define GMT_D_1600(x) ((x) & 0x00400000) #define GMT_D_800(x) ((x) & 0x00200000) /* #define GMT_ ? ((x) & 0x00100000) */ /* #define GMT_ ? ((x) & 0x00080000) */ #define GMT_DR_OPEN(x) ((x) & 0x00040000) /* Door open (no tape). */ /* #define GMT_ ? ((x) & 0x00020000) */ #define GMT_IM_REP_EN(x) ((x) & 0x00010000) /* Immediate report mode.*/ /* 16 generic status bits unused. */ /* SCSI-tape specific definitions. Bitfield shifts in the status */ #define MT_ST_BLKSIZE_SHIFT 0 #define MT_ST_BLKSIZE_MASK 0xffffff #define MT_ST_DENSITY_SHIFT 24 #define MT_ST_DENSITY_MASK 0xff000000 #define MT_ST_SOFTERR_SHIFT 0 #define MT_ST_SOFTERR_MASK 0xffff /* Bitfields for the MTSETDRVBUFFER ioctl. */ #define MT_ST_OPTIONS 0xf0000000 #define MT_ST_BOOLEANS 0x10000000 #define MT_ST_SETBOOLEANS 0x30000000 #define MT_ST_CLEARBOOLEANS 0x40000000 #define MT_ST_WRITE_THRESHOLD 0x20000000 #define MT_ST_DEF_BLKSIZE 0x50000000 #define MT_ST_DEF_OPTIONS 0x60000000 #define MT_ST_BUFFER_WRITES 0x1 #define MT_ST_ASYNC_WRITES 0x2 #define MT_ST_READ_AHEAD 0x4 #define MT_ST_DEBUGGING 0x8 #define MT_ST_TWO_FM 0x10 #define MT_ST_FAST_MTEOM 0x20 #define MT_ST_AUTO_LOCK 0x40 #define MT_ST_DEF_WRITES 0x80 #define MT_ST_CAN_BSR 0x100 #define MT_ST_NO_BLKLIMS 0x200 #define MT_ST_CAN_PARTITIONS 0x400 #define MT_ST_SCSI2LOGICAL 0x800 /* The mode parameters to be controlled. Parameter chosen with bits 20-28. */ #define MT_ST_CLEAR_DEFAULT 0xfffff #define MT_ST_DEF_DENSITY (MT_ST_DEF_OPTIONS | 0x100000) #define MT_ST_DEF_COMPRESSION (MT_ST_DEF_OPTIONS | 0x200000) #define MT_ST_DEF_DRVBUFFER (MT_ST_DEF_OPTIONS | 0x300000) /* The offset for the arguments for the special HP changer load command. */ #define MT_ST_HPLOADER_OFFSET 10000 /* Specify default tape device. */ #ifndef DEFTAPE # define DEFTAPE "/dev/tape" #endif #endif /* mtio.h */ sys/xattr.h000064400000010262151027430550006700 0ustar00/* Copyright (C) 2002-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_XATTR_H #define _SYS_XATTR_H 1 #include #include __BEGIN_DECLS /* The following constants should be used for the fifth parameter of `*setxattr'. */ #ifndef __USE_KERNEL_XATTR_DEFS enum { XATTR_CREATE = 1, /* set value, fail if attr already exists. */ #define XATTR_CREATE XATTR_CREATE XATTR_REPLACE = 2 /* set value, fail if attr does not exist. */ #define XATTR_REPLACE XATTR_REPLACE }; #endif /* Set the attribute NAME of the file pointed to by PATH to VALUE (which is SIZE bytes long). Return 0 on success, -1 for errors. */ extern int setxattr (const char *__path, const char *__name, const void *__value, size_t __size, int __flags) __THROW; /* Set the attribute NAME of the file pointed to by PATH to VALUE (which is SIZE bytes long), not following symlinks for the last pathname component. Return 0 on success, -1 for errors. */ extern int lsetxattr (const char *__path, const char *__name, const void *__value, size_t __size, int __flags) __THROW; /* Set the attribute NAME of the file descriptor FD to VALUE (which is SIZE bytes long). Return 0 on success, -1 for errors. */ extern int fsetxattr (int __fd, const char *__name, const void *__value, size_t __size, int __flags) __THROW; /* Get the attribute NAME of the file pointed to by PATH to VALUE (which is SIZE bytes long). Return 0 on success, -1 for errors. */ extern ssize_t getxattr (const char *__path, const char *__name, void *__value, size_t __size) __THROW; /* Get the attribute NAME of the file pointed to by PATH to VALUE (which is SIZE bytes long), not following symlinks for the last pathname component. Return 0 on success, -1 for errors. */ extern ssize_t lgetxattr (const char *__path, const char *__name, void *__value, size_t __size) __THROW; /* Get the attribute NAME of the file descriptor FD to VALUE (which is SIZE bytes long). Return 0 on success, -1 for errors. */ extern ssize_t fgetxattr (int __fd, const char *__name, void *__value, size_t __size) __THROW; /* List attributes of the file pointed to by PATH into the user-supplied buffer LIST (which is SIZE bytes big). Return 0 on success, -1 for errors. */ extern ssize_t listxattr (const char *__path, char *__list, size_t __size) __THROW; /* List attributes of the file pointed to by PATH into the user-supplied buffer LIST (which is SIZE bytes big), not following symlinks for the last pathname component. Return 0 on success, -1 for errors. */ extern ssize_t llistxattr (const char *__path, char *__list, size_t __size) __THROW; /* List attributes of the file descriptor FD into the user-supplied buffer LIST (which is SIZE bytes big). Return 0 on success, -1 for errors. */ extern ssize_t flistxattr (int __fd, char *__list, size_t __size) __THROW; /* Remove the attribute NAME from the file pointed to by PATH. Return 0 on success, -1 for errors. */ extern int removexattr (const char *__path, const char *__name) __THROW; /* Remove the attribute NAME from the file pointed to by PATH, not following symlinks for the last pathname component. Return 0 on success, -1 for errors. */ extern int lremovexattr (const char *__path, const char *__name) __THROW; /* Remove the attribute NAME from the file descriptor FD. Return 0 on success, -1 for errors. */ extern int fremovexattr (int __fd, const char *__name) __THROW; __END_DECLS #endif /* sys/xattr.h */ sys/auxv.h000064400000002353151027430550006523 0ustar00/* Access to the auxiliary vector. Copyright (C) 2012-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_AUXV_H #define _SYS_AUXV_H 1 #include #include #include __BEGIN_DECLS /* Return the value associated with an Elf*_auxv_t type from the auxv list passed to the program on startup. If TYPE was not present in the auxv list, returns zero and sets errno to ENOENT. */ extern unsigned long int getauxval (unsigned long int __type) __THROW; __END_DECLS #endif /* sys/auxv.h */ sys/pci.h000064400000001632151027430550006312 0ustar00/* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_PCI_H #define _SYS_PCI_H 1 /* We use the constants from the kernel. */ #include #endif /* sys/pci.h */ sys/vtimes.h000064400000004636151027430550007055 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_VTIMES_H #define _SYS_VTIMES_H 1 #include __BEGIN_DECLS /* This interface is obsolete; use `getrusage' instead. */ /* Granularity of the `vm_utime' and `vm_stime' fields of a `struct vtimes'. (This is the frequency of the machine's power supply, in Hz.) */ #define VTIMES_UNITS_PER_SECOND 60 struct vtimes { /* User time used in units of 1/VTIMES_UNITS_PER_SECOND seconds. */ int vm_utime; /* System time used in units of 1/VTIMES_UNITS_PER_SECOND seconds. */ int vm_stime; /* Amount of data and stack memory used (kilobyte-seconds). */ unsigned int vm_idsrss; /* Amount of text memory used (kilobyte-seconds). */ unsigned int vm_ixrss; /* Maximum resident set size (text, data, and stack) (kilobytes). */ int vm_maxrss; /* Number of hard page faults (i.e. those that required I/O). */ int vm_majflt; /* Number of soft page faults (i.e. those serviced by reclaiming a page from the list of pages awaiting reallocation. */ int vm_minflt; /* Number of times a process was swapped out of physical memory. */ int vm_nswap; /* Number of input operations via the file system. Note: This and `ru_oublock' do not include operations with the cache. */ int vm_inblk; /* Number of output operations via the file system. */ int vm_oublk; }; /* If CURRENT is not NULL, write statistics for the current process into *CURRENT. If CHILD is not NULL, write statistics for all terminated child processes into *CHILD. Returns 0 for success, -1 for failure. */ extern int vtimes (struct vtimes * __current, struct vtimes * __child) __THROW; __END_DECLS #endif /* sys/vtimes.h */ sys/poll.h000064400000004765151027430550006517 0ustar00/* Compatibility definitions for System V `poll' interface. Copyright (C) 1994-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_POLL_H #define _SYS_POLL_H 1 #include /* Get the platform dependent bits of `poll'. */ #include #ifdef __USE_GNU # include # include #endif /* Type used for the number of file descriptors. */ typedef unsigned long int nfds_t; /* Data structure describing a polling request. */ struct pollfd { int fd; /* File descriptor to poll. */ short int events; /* Types of events poller cares about. */ short int revents; /* Types of events that actually occurred. */ }; __BEGIN_DECLS /* Poll the file descriptors described by the NFDS structures starting at FDS. If TIMEOUT is nonzero and not -1, allow TIMEOUT milliseconds for an event to occur; if TIMEOUT is -1, block until an event occurs. Returns the number of file descriptors with events, zero if timed out, or -1 for errors. This function is a cancellation point and therefore not marked with __THROW. */ extern int poll (struct pollfd *__fds, nfds_t __nfds, int __timeout); #ifdef __USE_GNU /* Like poll, but before waiting the threads signal mask is replaced with that specified in the fourth parameter. For better usability, the timeout value is specified using a TIMESPEC object. This function is a cancellation point and therefore not marked with __THROW. */ extern int ppoll (struct pollfd *__fds, nfds_t __nfds, const struct timespec *__timeout, const __sigset_t *__ss); #endif __END_DECLS /* Define some inlines helping to catch common problems. */ #if __USE_FORTIFY_LEVEL > 0 && defined __fortify_function # include #endif #endif /* sys/poll.h */ sys/ucontext.h000064400000013321151027430550007406 0ustar00/* Copyright (C) 2001-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_UCONTEXT_H #define _SYS_UCONTEXT_H 1 #include #include #include #include #ifdef __USE_MISC # define __ctx(fld) fld #else # define __ctx(fld) __ ## fld #endif #ifdef __x86_64__ /* Type for general register. */ __extension__ typedef long long int greg_t; /* Number of general registers. */ #define __NGREG 23 #ifdef __USE_MISC # define NGREG __NGREG #endif /* Container for all general registers. */ typedef greg_t gregset_t[__NGREG]; #ifdef __USE_GNU /* Number of each register in the `gregset_t' array. */ enum { REG_R8 = 0, # define REG_R8 REG_R8 REG_R9, # define REG_R9 REG_R9 REG_R10, # define REG_R10 REG_R10 REG_R11, # define REG_R11 REG_R11 REG_R12, # define REG_R12 REG_R12 REG_R13, # define REG_R13 REG_R13 REG_R14, # define REG_R14 REG_R14 REG_R15, # define REG_R15 REG_R15 REG_RDI, # define REG_RDI REG_RDI REG_RSI, # define REG_RSI REG_RSI REG_RBP, # define REG_RBP REG_RBP REG_RBX, # define REG_RBX REG_RBX REG_RDX, # define REG_RDX REG_RDX REG_RAX, # define REG_RAX REG_RAX REG_RCX, # define REG_RCX REG_RCX REG_RSP, # define REG_RSP REG_RSP REG_RIP, # define REG_RIP REG_RIP REG_EFL, # define REG_EFL REG_EFL REG_CSGSFS, /* Actually short cs, gs, fs, __pad0. */ # define REG_CSGSFS REG_CSGSFS REG_ERR, # define REG_ERR REG_ERR REG_TRAPNO, # define REG_TRAPNO REG_TRAPNO REG_OLDMASK, # define REG_OLDMASK REG_OLDMASK REG_CR2 # define REG_CR2 REG_CR2 }; #endif struct _libc_fpxreg { unsigned short int __ctx(significand)[4]; unsigned short int __ctx(exponent); unsigned short int __glibc_reserved1[3]; }; struct _libc_xmmreg { __uint32_t __ctx(element)[4]; }; struct _libc_fpstate { /* 64-bit FXSAVE format. */ __uint16_t __ctx(cwd); __uint16_t __ctx(swd); __uint16_t __ctx(ftw); __uint16_t __ctx(fop); __uint64_t __ctx(rip); __uint64_t __ctx(rdp); __uint32_t __ctx(mxcsr); __uint32_t __ctx(mxcr_mask); struct _libc_fpxreg _st[8]; struct _libc_xmmreg _xmm[16]; __uint32_t __glibc_reserved1[24]; }; /* Structure to describe FPU registers. */ typedef struct _libc_fpstate *fpregset_t; /* Context to describe whole processor state. */ typedef struct { gregset_t __ctx(gregs); /* Note that fpregs is a pointer. */ fpregset_t __ctx(fpregs); __extension__ unsigned long long __reserved1 [8]; } mcontext_t; /* Userlevel context. */ typedef struct ucontext_t { unsigned long int __ctx(uc_flags); struct ucontext_t *uc_link; stack_t uc_stack; mcontext_t uc_mcontext; sigset_t uc_sigmask; struct _libc_fpstate __fpregs_mem; __extension__ unsigned long long int __ssp[4]; } ucontext_t; #else /* !__x86_64__ */ /* Type for general register. */ typedef int greg_t; /* Number of general registers. */ #define __NGREG 19 #ifdef __USE_MISC # define NGREG __NGREG #endif /* Container for all general registers. */ typedef greg_t gregset_t[__NGREG]; #ifdef __USE_GNU /* Number of each register is the `gregset_t' array. */ enum { REG_GS = 0, # define REG_GS REG_GS REG_FS, # define REG_FS REG_FS REG_ES, # define REG_ES REG_ES REG_DS, # define REG_DS REG_DS REG_EDI, # define REG_EDI REG_EDI REG_ESI, # define REG_ESI REG_ESI REG_EBP, # define REG_EBP REG_EBP REG_ESP, # define REG_ESP REG_ESP REG_EBX, # define REG_EBX REG_EBX REG_EDX, # define REG_EDX REG_EDX REG_ECX, # define REG_ECX REG_ECX REG_EAX, # define REG_EAX REG_EAX REG_TRAPNO, # define REG_TRAPNO REG_TRAPNO REG_ERR, # define REG_ERR REG_ERR REG_EIP, # define REG_EIP REG_EIP REG_CS, # define REG_CS REG_CS REG_EFL, # define REG_EFL REG_EFL REG_UESP, # define REG_UESP REG_UESP REG_SS # define REG_SS REG_SS }; #endif /* Definitions taken from the kernel headers. */ struct _libc_fpreg { unsigned short int __ctx(significand)[4]; unsigned short int __ctx(exponent); }; struct _libc_fpstate { unsigned long int __ctx(cw); unsigned long int __ctx(sw); unsigned long int __ctx(tag); unsigned long int __ctx(ipoff); unsigned long int __ctx(cssel); unsigned long int __ctx(dataoff); unsigned long int __ctx(datasel); struct _libc_fpreg _st[8]; unsigned long int __ctx(status); }; /* Structure to describe FPU registers. */ typedef struct _libc_fpstate *fpregset_t; /* Context to describe whole processor state. */ typedef struct { gregset_t __ctx(gregs); /* Due to Linux's history we have to use a pointer here. The SysV/i386 ABI requires a struct with the values. */ fpregset_t __ctx(fpregs); unsigned long int __ctx(oldmask); unsigned long int __ctx(cr2); } mcontext_t; /* Userlevel context. */ typedef struct ucontext_t { unsigned long int __ctx(uc_flags); struct ucontext_t *uc_link; stack_t uc_stack; mcontext_t uc_mcontext; sigset_t uc_sigmask; struct _libc_fpstate __fpregs_mem; unsigned long int __ssp[4]; } ucontext_t; #endif /* !__x86_64__ */ #undef __ctx #endif /* sys/ucontext.h */ sys/eventfd.h000064400000002567151027430550007202 0ustar00/* Copyright (C) 2007-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_EVENTFD_H #define _SYS_EVENTFD_H 1 #include /* Get the platform-dependent flags. */ #include /* Type for event counter. */ typedef uint64_t eventfd_t; __BEGIN_DECLS /* Return file descriptor for generic event channel. Set initial value to COUNT. */ extern int eventfd (unsigned int __count, int __flags) __THROW; /* Read event counter and possibly wait for events. */ extern int eventfd_read (int __fd, eventfd_t *__value); /* Increment event counter. */ extern int eventfd_write (int __fd, eventfd_t __value); __END_DECLS #endif /* sys/eventfd.h */ sys/prctl.h000064400000002042151027430550006657 0ustar00/* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_PRCTL_H #define _SYS_PRCTL_H 1 #include #include /* The magic values come from here */ __BEGIN_DECLS /* Control process execution. */ extern int prctl (int __option, ...) __THROW; __END_DECLS #endif /* sys/prctl.h */ sys/timerfd.h000064400000003521151027430550007170 0ustar00/* Copyright (C) 2008-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_TIMERFD_H #define _SYS_TIMERFD_H 1 #include #include /* Get the platform-dependent flags. */ #include /* Bits to be set in the FLAGS parameter of `timerfd_settime'. */ enum { TFD_TIMER_ABSTIME = 1 << 0, #define TFD_TIMER_ABSTIME TFD_TIMER_ABSTIME TFD_TIMER_CANCEL_ON_SET = 1 << 1 #define TFD_TIMER_CANCEL_ON_SET TFD_TIMER_CANCEL_ON_SET }; __BEGIN_DECLS /* Return file descriptor for new interval timer source. */ extern int timerfd_create (__clockid_t __clock_id, int __flags) __THROW; /* Set next expiration time of interval timer source UFD to UTMR. If FLAGS has the TFD_TIMER_ABSTIME flag set the timeout value is absolute. Optionally return the old expiration time in OTMR. */ extern int timerfd_settime (int __ufd, int __flags, const struct itimerspec *__utmr, struct itimerspec *__otmr) __THROW; /* Return the next expiration time of UFD. */ extern int timerfd_gettime (int __ufd, struct itimerspec *__otmr) __THROW; __END_DECLS #endif /* sys/timerfd.h */ sys/fcntl.h000064400000000023151027430550006636 0ustar00#include sys/resource.h000064400000007075151027430550007375 0ustar00/* Copyright (C) 1992-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SYS_RESOURCE_H #define _SYS_RESOURCE_H 1 #include /* Get the system-dependent definitions of structures and bit values. */ #include #ifndef __id_t_defined typedef __id_t id_t; # define __id_t_defined #endif __BEGIN_DECLS /* The X/Open standard defines that all the functions below must use `int' as the type for the first argument. When we are compiling with GNU extensions we change this slightly to provide better error checking. */ #if defined __USE_GNU && !defined __cplusplus typedef enum __rlimit_resource __rlimit_resource_t; typedef enum __rusage_who __rusage_who_t; typedef enum __priority_which __priority_which_t; #else typedef int __rlimit_resource_t; typedef int __rusage_who_t; typedef int __priority_which_t; #endif /* Put the soft and hard limits for RESOURCE in *RLIMITS. Returns 0 if successful, -1 if not (and sets errno). */ #ifndef __USE_FILE_OFFSET64 extern int getrlimit (__rlimit_resource_t __resource, struct rlimit *__rlimits) __THROW; #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (getrlimit, (__rlimit_resource_t __resource, struct rlimit *__rlimits), getrlimit64); # else # define getrlimit getrlimit64 # endif #endif #ifdef __USE_LARGEFILE64 extern int getrlimit64 (__rlimit_resource_t __resource, struct rlimit64 *__rlimits) __THROW; #endif /* Set the soft and hard limits for RESOURCE to *RLIMITS. Only the super-user can increase hard limits. Return 0 if successful, -1 if not (and sets errno). */ #ifndef __USE_FILE_OFFSET64 extern int setrlimit (__rlimit_resource_t __resource, const struct rlimit *__rlimits) __THROW; #else # ifdef __REDIRECT_NTH extern int __REDIRECT_NTH (setrlimit, (__rlimit_resource_t __resource, const struct rlimit *__rlimits), setrlimit64); # else # define setrlimit setrlimit64 # endif #endif #ifdef __USE_LARGEFILE64 extern int setrlimit64 (__rlimit_resource_t __resource, const struct rlimit64 *__rlimits) __THROW; #endif /* Return resource usage information on process indicated by WHO and put it in *USAGE. Returns 0 for success, -1 for failure. */ extern int getrusage (__rusage_who_t __who, struct rusage *__usage) __THROW; /* Return the highest priority of any process specified by WHICH and WHO (see above); if WHO is zero, the current process, process group, or user (as specified by WHO) is used. A lower priority number means higher priority. Priorities range from PRIO_MIN to PRIO_MAX (above). */ extern int getpriority (__priority_which_t __which, id_t __who) __THROW; /* Set the priority of all processes specified by WHICH and WHO (see above) to PRIO. Returns 0 on success, -1 on errors. */ extern int setpriority (__priority_which_t __which, id_t __who, int __prio) __THROW; __END_DECLS #endif /* sys/resource.h */ ltdl.h000064400000013115151027430550005657 0ustar00/* ltdl.h -- generic dlopen functions Copyright (C) 1998-2000, 2004-2005, 2007-2008, 2011-2015 Free Software Foundation, Inc. Written by Thomas Tanner, 1998 NOTE: The canonical source of this file is maintained with the GNU Libtool package. Report bugs to bug-libtool@gnu.org. GNU Libltdl is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. As a special exception to the GNU Lesser General Public License, if you distribute this file as part of a program or library that is built using GNU Libtool, you may include this file under the same distribution terms that you use for the rest of that program. GNU Libltdl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU Libltdl; see the file COPYING.LIB. If not, a copy can be downloaded from http://www.gnu.org/licenses/lgpl.html, or obtained by writing to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Only include this header file once. */ #if !defined LTDL_H #define LTDL_H 1 #include #include #include LT_BEGIN_C_DECLS /* LT_STRLEN can be used safely on NULL pointers. */ #define LT_STRLEN(s) (((s) && (s)[0]) ? strlen (s) : 0) /* --- DYNAMIC MODULE LOADING API --- */ typedef struct lt__handle *lt_dlhandle; /* A loaded module. */ /* Initialisation and finalisation functions for libltdl. */ LT_SCOPE int lt_dlinit (void); LT_SCOPE int lt_dlexit (void); /* Module search path manipulation. */ LT_SCOPE int lt_dladdsearchdir (const char *search_dir); LT_SCOPE int lt_dlinsertsearchdir (const char *before, const char *search_dir); LT_SCOPE int lt_dlsetsearchpath (const char *search_path); LT_SCOPE const char *lt_dlgetsearchpath (void); LT_SCOPE int lt_dlforeachfile ( const char *search_path, int (*func) (const char *filename, void *data), void *data); /* User module loading advisors. */ LT_SCOPE int lt_dladvise_init (lt_dladvise *advise); LT_SCOPE int lt_dladvise_destroy (lt_dladvise *advise); LT_SCOPE int lt_dladvise_ext (lt_dladvise *advise); LT_SCOPE int lt_dladvise_resident (lt_dladvise *advise); LT_SCOPE int lt_dladvise_local (lt_dladvise *advise); LT_SCOPE int lt_dladvise_global (lt_dladvise *advise); LT_SCOPE int lt_dladvise_preload (lt_dladvise *advise); /* Portable libltdl versions of the system dlopen() API. */ LT_SCOPE lt_dlhandle lt_dlopen (const char *filename); LT_SCOPE lt_dlhandle lt_dlopenext (const char *filename); LT_SCOPE lt_dlhandle lt_dlopenadvise (const char *filename, lt_dladvise advise); LT_SCOPE void * lt_dlsym (lt_dlhandle handle, const char *name); LT_SCOPE const char *lt_dlerror (void); LT_SCOPE int lt_dlclose (lt_dlhandle handle); /* --- PRELOADED MODULE SUPPORT --- */ /* A preopened symbol. Arrays of this type comprise the exported symbols for a dlpreopened module. */ typedef struct { const char *name; void *address; } lt_dlsymlist; typedef int lt_dlpreload_callback_func (lt_dlhandle handle); LT_SCOPE int lt_dlpreload (const lt_dlsymlist *preloaded); LT_SCOPE int lt_dlpreload_default (const lt_dlsymlist *preloaded); LT_SCOPE int lt_dlpreload_open (const char *originator, lt_dlpreload_callback_func *func); #define lt_preloaded_symbols lt__PROGRAM__LTX_preloaded_symbols /* Ensure C linkage. */ extern LT_DLSYM_CONST lt_dlsymlist lt__PROGRAM__LTX_preloaded_symbols[]; #define LTDL_SET_PRELOADED_SYMBOLS() \ lt_dlpreload_default(lt_preloaded_symbols) /* --- MODULE INFORMATION --- */ /* Associating user data with loaded modules. */ typedef void * lt_dlinterface_id; typedef int lt_dlhandle_interface (lt_dlhandle handle, const char *id_string); LT_SCOPE lt_dlinterface_id lt_dlinterface_register (const char *id_string, lt_dlhandle_interface *iface); LT_SCOPE void lt_dlinterface_free (lt_dlinterface_id key); LT_SCOPE void * lt_dlcaller_set_data (lt_dlinterface_id key, lt_dlhandle handle, void *data); LT_SCOPE void * lt_dlcaller_get_data (lt_dlinterface_id key, lt_dlhandle handle); /* Read only information pertaining to a loaded module. */ typedef struct { char * filename; /* file name */ char * name; /* module name */ int ref_count; /* number of times lt_dlopened minus number of times lt_dlclosed. */ unsigned int is_resident:1; /* module can't be unloaded. */ unsigned int is_symglobal:1; /* module symbols can satisfy subsequently loaded modules. */ unsigned int is_symlocal:1; /* module symbols are only available locally. */ } lt_dlinfo; LT_SCOPE const lt_dlinfo *lt_dlgetinfo (lt_dlhandle handle); LT_SCOPE lt_dlhandle lt_dlhandle_iterate (lt_dlinterface_id iface, lt_dlhandle place); LT_SCOPE lt_dlhandle lt_dlhandle_fetch (lt_dlinterface_id iface, const char *module_name); LT_SCOPE int lt_dlhandle_map (lt_dlinterface_id iface, int (*func) (lt_dlhandle handle, void *data), void *data); /* Deprecated module residency management API. */ LT_SCOPE int lt_dlmakeresident (lt_dlhandle handle); LT_SCOPE int lt_dlisresident (lt_dlhandle handle); #define lt_ptr void * LT_END_C_DECLS #endif /*!defined LTDL_H*/ utime.h000064400000002735151027430550006051 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * POSIX Standard: 5.6.6 Set File Access and Modification Times */ #ifndef _UTIME_H #define _UTIME_H 1 #include __BEGIN_DECLS #include #if defined __USE_XOPEN || defined __USE_XOPEN2K # include #endif /* Structure describing file times. */ struct utimbuf { __time_t actime; /* Access time. */ __time_t modtime; /* Modification time. */ }; /* Set the access and modification times of FILE to those given in *FILE_TIMES. If FILE_TIMES is NULL, set them to the current time. */ extern int utime (const char *__file, const struct utimbuf *__file_times) __THROW __nonnull ((1)); __END_DECLS #endif /* utime.h */ tic.h000064400000032506151027430550005504 0ustar00/**************************************************************************** * Copyright (c) 1998-2012,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim 1992,1995 * * and: Eric S. Raymond * * and: Thomas E. Dickey 1996 on * ****************************************************************************/ /* * $Id: tic.h,v 1.75 2017/07/29 23:21:06 tom Exp $ * tic.h - Global variables and structures for the terminfo compiler. */ #ifndef __TIC_H #define __TIC_H /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif #include #include /* for the _tracef() prototype, ERR/OK, bool defs */ /* ** The format of SVr2 compiled terminfo files is as follows: ** ** Header (12 bytes), containing information given below ** Names Section, containing the names of the terminal ** Boolean Section, containing the values of all of the ** boolean capabilities ** A null byte may be inserted here to make ** sure that the Number Section begins on an ** even word boundary. ** Number Section, containing the values of all of the numeric ** capabilities, each as a short integer ** String Section, containing short integer offsets into the ** String Table, one per string capability ** String Table, containing the actual characters of the string ** capabilities. ** ** In the SVr2 format, "short" means signed 16-bit numbers, which is sometimes ** inconvenient. The numbers are signed, to provide for absent and canceled ** values. ncurses6.1 introduced an extension to this compiled format, by ** making the Number Section a list of signed 32-bit integers. ** ** NOTE that all short integers in the file are stored using VAX/PDP-style ** byte-order, i.e., least-significant byte first. ** ** There is no structure definition here because it would only confuse ** matters. Terminfo format is a raw byte layout, not a structure ** dump. If you happen to be on a little-endian machine with 16-bit ** shorts that requires no padding between short members in a struct, ** then there is a natural C structure that captures the header, but ** not very helpfully. */ #define MAGIC 0432 /* first two bytes of a compiled entry */ #define MAGIC2 01036 /* first two bytes of a compiled 32-bit entry */ #undef BYTE #define BYTE(p,n) (unsigned char)((p)[n]) #define IS_NEG1(p) ((BYTE(p,0) == 0377) && (BYTE(p,1) == 0377)) #define IS_NEG2(p) ((BYTE(p,0) == 0376) && (BYTE(p,1) == 0377)) #define LOW_MSB(p) (BYTE(p,0) + 256*BYTE(p,1)) #define IS_TIC_MAGIC(p) (LOW_MSB(p) == MAGIC || LOW_MSB(p) == MAGIC2) #define quick_prefix(s) (!strncmp((s), "b64:", 4) || !strncmp((s), "hex:", 4)) /* * The "maximum" here is misleading; XSI guarantees minimum values, which a * given implementation may exceed. */ #define MAX_NAME_SIZE 512 /* maximum legal name field size (XSI:127) */ #define MAX_ENTRY_SIZE1 4096 /* maximum legal entry size (SVr2) */ #define MAX_ENTRY_SIZE2 32768 /* maximum legal entry size (ncurses6.1) */ #if NCURSES_EXT_COLORS && HAVE_INIT_EXTENDED_COLOR #define MAX_ENTRY_SIZE MAX_ENTRY_SIZE2 #else #define MAX_ENTRY_SIZE MAX_ENTRY_SIZE1 #endif /* * The maximum size of individual name or alias is guaranteed in XSI to be at * least 14, since that corresponds to the older filename lengths. Newer * systems allow longer aliases, though not many terminal descriptions are * written to use them. The MAX_ALIAS symbol is used for warnings. */ #if HAVE_LONG_FILE_NAMES #define MAX_ALIAS 32 /* smaller than POSIX minimum for PATH_MAX */ #else #define MAX_ALIAS 14 /* SVr3 filename length */ #endif /* location of user's personal info directory */ #define PRIVATE_INFO "%s/.terminfo" /* plug getenv("HOME") into %s */ /* * Some traces are designed to be used via tic's verbose option (and similar in * infocmp and toe) rather than the 'trace()' function. So we use the bits * above the normal trace() parameter as a debug-level. */ #define MAX_DEBUG_LEVEL 15 #define DEBUG_LEVEL(n) ((n) << TRACE_SHIFT) #define set_trace_level(n) \ _nc_tracing &= DEBUG_LEVEL(MAX_DEBUG_LEVEL) \ + DEBUG_LEVEL(MAX_DEBUG_LEVEL) - 1, \ _nc_tracing |= DEBUG_LEVEL(n) #ifdef TRACE #define DEBUG(n, a) if (_nc_tracing >= DEBUG_LEVEL(n)) _tracef a #else #define DEBUG(n, a) /*nothing*/ #endif /* * These are the types of tokens returned by the scanner. The first * three are also used in the hash table of capability names. The scanner * returns one of these values after loading the specifics into the global * structure curr_token. */ #define BOOLEAN 0 /* Boolean capability */ #define NUMBER 1 /* Numeric capability */ #define STRING 2 /* String-valued capability */ #define CANCEL 3 /* Capability to be cancelled in following tc's */ #define NAMES 4 /* The names for a terminal type */ #define UNDEF 5 /* Undefined */ #define NO_PUSHBACK -1 /* used in pushtype to indicate no pushback */ /* * The global structure in which the specific parts of a * scanned token are returned. */ struct token { char *tk_name; /* name of capability */ int tk_valnumber; /* value of capability (if a number) */ char *tk_valstring; /* value of capability (if a string) */ }; /* * Offsets to string capabilities, with the corresponding functionkey codes. */ struct tinfo_fkeys { unsigned offset; chtype code; }; typedef short HashValue; /* * The file comp_captab.c contains an array of these structures, one per * possible capability. These are indexed by a hash table array of pointers to * the same structures for use by the parser. */ struct name_table_entry { const char *nte_name; /* name to hash on */ int nte_type; /* BOOLEAN, NUMBER or STRING */ HashValue nte_index; /* index of associated variable in its array */ HashValue nte_link; /* index in table of next hash, or -1 */ }; /* * Use this structure to hide differences between terminfo and termcap tables. */ typedef struct { unsigned table_size; const HashValue *table_data; HashValue (*hash_of)(const char *); int (*compare_names)(const char *, const char *); } HashData; struct alias { const char *from; const char *to; const char *source; }; #define NOTFOUND ((struct name_table_entry *) 0) /* * The casts are required for correct sign-propagation with systems such as * AIX, IRIX64, Solaris which default to unsigned characters. The C standard * leaves this detail unspecified. */ /* out-of-band values for representing absent capabilities */ #define ABSENT_BOOLEAN ((signed char)-1) /* 255 */ #define ABSENT_NUMERIC (-1) #define ABSENT_STRING (char *)0 /* out-of-band values for representing cancels */ #define CANCELLED_BOOLEAN ((signed char)-2) /* 254 */ #define CANCELLED_NUMERIC (-2) #define CANCELLED_STRING (char *)(-1) #define VALID_BOOLEAN(s) ((unsigned char)(s) <= 1) /* reject "-1" */ #define VALID_NUMERIC(s) ((s) >= 0) #define VALID_STRING(s) ((s) != CANCELLED_STRING && (s) != ABSENT_STRING) /* termcap entries longer than this may break old binaries */ #define MAX_TERMCAP_LENGTH 1023 /* this is a documented limitation of terminfo */ #define MAX_TERMINFO_LENGTH 4096 #ifndef TERMINFO #define TERMINFO "/usr/share/terminfo" #endif #ifdef NCURSES_TERM_ENTRY_H_incl /* * These entrypoints are used only by the ncurses utilities such as tic. */ #ifdef NCURSES_INTERNALS /* access.c */ extern NCURSES_EXPORT(unsigned) _nc_pathlast (const char *); extern NCURSES_EXPORT(bool) _nc_is_abs_path (const char *); extern NCURSES_EXPORT(bool) _nc_is_dir_path (const char *); extern NCURSES_EXPORT(bool) _nc_is_file_path (const char *); extern NCURSES_EXPORT(char *) _nc_basename (char *); extern NCURSES_EXPORT(char *) _nc_rootname (char *); /* comp_captab.c */ extern NCURSES_EXPORT(const struct name_table_entry *) _nc_get_table (bool); extern NCURSES_EXPORT(const HashData *) _nc_get_hash_info (bool); extern NCURSES_EXPORT(const struct alias *) _nc_get_alias_table (bool); /* comp_hash.c: name lookup */ extern NCURSES_EXPORT(struct name_table_entry const *) _nc_find_type_entry (const char *, int, bool); /* comp_scan.c: lexical analysis */ extern NCURSES_EXPORT(int) _nc_get_token (bool); extern NCURSES_EXPORT(void) _nc_panic_mode (char); extern NCURSES_EXPORT(void) _nc_push_token (int); extern NCURSES_EXPORT_VAR(int) _nc_curr_col; extern NCURSES_EXPORT_VAR(int) _nc_curr_line; extern NCURSES_EXPORT_VAR(int) _nc_syntax; extern NCURSES_EXPORT_VAR(int) _nc_strict_bsd; extern NCURSES_EXPORT_VAR(long) _nc_comment_end; extern NCURSES_EXPORT_VAR(long) _nc_comment_start; extern NCURSES_EXPORT_VAR(long) _nc_curr_file_pos; extern NCURSES_EXPORT_VAR(long) _nc_start_line; #define SYN_TERMINFO 0 #define SYN_TERMCAP 1 /* comp_error.c: warning & abort messages */ extern NCURSES_EXPORT(const char *) _nc_get_source (void); extern NCURSES_EXPORT(void) _nc_err_abort (const char *const,...) GCC_PRINTFLIKE(1,2) GCC_NORETURN; extern NCURSES_EXPORT(void) _nc_get_type (char *name); extern NCURSES_EXPORT(void) _nc_set_source (const char *const); extern NCURSES_EXPORT(void) _nc_set_type (const char *const); extern NCURSES_EXPORT(void) _nc_syserr_abort (const char *const,...) GCC_PRINTFLIKE(1,2) GCC_NORETURN; extern NCURSES_EXPORT(void) _nc_warning (const char *const,...) GCC_PRINTFLIKE(1,2); extern NCURSES_EXPORT_VAR(bool) _nc_suppress_warnings; /* comp_scan.c */ extern NCURSES_EXPORT_VAR(struct token) _nc_curr_token; /* captoinfo.c: capability conversion */ extern NCURSES_EXPORT(char *) _nc_captoinfo (const char *, const char *, int const); extern NCURSES_EXPORT(char *) _nc_infotocap (const char *, const char *, int const); /* home_terminfo.c */ extern NCURSES_EXPORT(char *) _nc_home_terminfo (void); /* init_keytry.c */ #if BROKEN_LINKER #define _nc_tinfo_fkeys _nc_tinfo_fkeysf() extern NCURSES_EXPORT(const struct tinfo_fkeys *) _nc_tinfo_fkeysf (void); #else extern NCURSES_EXPORT_VAR(const struct tinfo_fkeys) _nc_tinfo_fkeys[]; #endif /* lib_tparm.c */ #define NUM_PARM 9 extern NCURSES_EXPORT_VAR(int) _nc_tparm_err; extern NCURSES_EXPORT(int) _nc_tparm_analyze(const char *, char **, int *); /* lib_trace.c */ extern NCURSES_EXPORT_VAR(unsigned) _nc_tracing; extern NCURSES_EXPORT(const char *) _nc_visbuf (const char *); extern NCURSES_EXPORT(const char *) _nc_visbuf2 (int, const char *); /* lib_tputs.c */ extern NCURSES_EXPORT_VAR(int) _nc_nulls_sent; /* Add one for every null sent */ /* comp_main.c: compiler main */ extern const char * _nc_progname; /* db_iterator.c */ extern NCURSES_EXPORT(const char *) _nc_next_db(DBDIRS *, int *); extern NCURSES_EXPORT(const char *) _nc_tic_dir (const char *); extern NCURSES_EXPORT(void) _nc_first_db(DBDIRS *, int *); extern NCURSES_EXPORT(void) _nc_last_db(void); /* write_entry.c */ extern NCURSES_EXPORT(int) _nc_tic_written (void); #endif /* NCURSES_INTERNALS */ /* * These entrypoints are used by tack. */ /* comp_hash.c: name lookup */ extern NCURSES_EXPORT(struct name_table_entry const *) _nc_find_entry (const char *, const HashValue *); extern NCURSES_EXPORT(const HashValue *) _nc_get_hash_table (bool); /* comp_scan.c: lexical analysis */ extern NCURSES_EXPORT(void) _nc_reset_input (FILE *, char *); /* comp_expand.c: expand string into readable form */ extern NCURSES_EXPORT(char *) _nc_tic_expand (const char *, bool, int); /* comp_scan.c: decode string from readable form */ extern NCURSES_EXPORT(int) _nc_trans_string (char *, char *); #endif /* NCURSES_TERM_ENTRY_H_incl */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* __TIC_H */ zbuff.h000064400000026354151027430550006045 0ustar00/* * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the BSD-style license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ /* *************************************************************** * NOTES/WARNINGS ******************************************************************/ /* The streaming API defined here is deprecated. * Consider migrating towards ZSTD_compressStream() API in `zstd.h` * See 'lib/README.md'. *****************************************************************/ #if defined (__cplusplus) extern "C" { #endif #ifndef ZSTD_BUFFERED_H_23987 #define ZSTD_BUFFERED_H_23987 /* ************************************* * Dependencies ***************************************/ #include /* size_t */ #include "zstd.h" /* ZSTD_CStream, ZSTD_DStream, ZSTDLIB_API */ /* *************************************************************** * Compiler specifics *****************************************************************/ /* Deprecation warnings */ /* Should these warnings be a problem, * it is generally possible to disable them, * typically with -Wno-deprecated-declarations for gcc * or _CRT_SECURE_NO_WARNINGS in Visual. * Otherwise, it's also possible to define ZBUFF_DISABLE_DEPRECATE_WARNINGS */ #ifdef ZBUFF_DISABLE_DEPRECATE_WARNINGS # define ZBUFF_DEPRECATED(message) ZSTDLIB_API /* disable deprecation warnings */ #else # if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ # define ZBUFF_DEPRECATED(message) [[deprecated(message)]] ZSTDLIB_API # elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) # define ZBUFF_DEPRECATED(message) ZSTDLIB_API __attribute__((deprecated(message))) # elif defined(__GNUC__) && (__GNUC__ >= 3) # define ZBUFF_DEPRECATED(message) ZSTDLIB_API __attribute__((deprecated)) # elif defined(_MSC_VER) # define ZBUFF_DEPRECATED(message) ZSTDLIB_API __declspec(deprecated(message)) # else # pragma message("WARNING: You need to implement ZBUFF_DEPRECATED for this compiler") # define ZBUFF_DEPRECATED(message) ZSTDLIB_API # endif #endif /* ZBUFF_DISABLE_DEPRECATE_WARNINGS */ /* ************************************* * Streaming functions ***************************************/ /* This is the easier "buffered" streaming API, * using an internal buffer to lift all restrictions on user-provided buffers * which can be any size, any place, for both input and output. * ZBUFF and ZSTD are 100% interoperable, * frames created by one can be decoded by the other one */ typedef ZSTD_CStream ZBUFF_CCtx; ZBUFF_DEPRECATED("use ZSTD_createCStream") ZBUFF_CCtx* ZBUFF_createCCtx(void); ZBUFF_DEPRECATED("use ZSTD_freeCStream") size_t ZBUFF_freeCCtx(ZBUFF_CCtx* cctx); ZBUFF_DEPRECATED("use ZSTD_initCStream") size_t ZBUFF_compressInit(ZBUFF_CCtx* cctx, int compressionLevel); ZBUFF_DEPRECATED("use ZSTD_initCStream_usingDict") size_t ZBUFF_compressInitDictionary(ZBUFF_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel); ZBUFF_DEPRECATED("use ZSTD_compressStream") size_t ZBUFF_compressContinue(ZBUFF_CCtx* cctx, void* dst, size_t* dstCapacityPtr, const void* src, size_t* srcSizePtr); ZBUFF_DEPRECATED("use ZSTD_flushStream") size_t ZBUFF_compressFlush(ZBUFF_CCtx* cctx, void* dst, size_t* dstCapacityPtr); ZBUFF_DEPRECATED("use ZSTD_endStream") size_t ZBUFF_compressEnd(ZBUFF_CCtx* cctx, void* dst, size_t* dstCapacityPtr); /*-************************************************* * Streaming compression - howto * * A ZBUFF_CCtx object is required to track streaming operation. * Use ZBUFF_createCCtx() and ZBUFF_freeCCtx() to create/release resources. * ZBUFF_CCtx objects can be reused multiple times. * * Start by initializing ZBUF_CCtx. * Use ZBUFF_compressInit() to start a new compression operation. * Use ZBUFF_compressInitDictionary() for a compression which requires a dictionary. * * Use ZBUFF_compressContinue() repetitively to consume input stream. * *srcSizePtr and *dstCapacityPtr can be any size. * The function will report how many bytes were read or written within *srcSizePtr and *dstCapacityPtr. * Note that it may not consume the entire input, in which case it's up to the caller to present again remaining data. * The content of `dst` will be overwritten (up to *dstCapacityPtr) at each call, so save its content if it matters or change @dst . * @return : a hint to preferred nb of bytes to use as input for next function call (it's just a hint, to improve latency) * or an error code, which can be tested using ZBUFF_isError(). * * At any moment, it's possible to flush whatever data remains within buffer, using ZBUFF_compressFlush(). * The nb of bytes written into `dst` will be reported into *dstCapacityPtr. * Note that the function cannot output more than *dstCapacityPtr, * therefore, some content might still be left into internal buffer if *dstCapacityPtr is too small. * @return : nb of bytes still present into internal buffer (0 if it's empty) * or an error code, which can be tested using ZBUFF_isError(). * * ZBUFF_compressEnd() instructs to finish a frame. * It will perform a flush and write frame epilogue. * The epilogue is required for decoders to consider a frame completed. * Similar to ZBUFF_compressFlush(), it may not be able to output the entire internal buffer content if *dstCapacityPtr is too small. * In which case, call again ZBUFF_compressFlush() to complete the flush. * @return : nb of bytes still present into internal buffer (0 if it's empty) * or an error code, which can be tested using ZBUFF_isError(). * * Hint : _recommended buffer_ sizes (not compulsory) : ZBUFF_recommendedCInSize() / ZBUFF_recommendedCOutSize() * input : ZBUFF_recommendedCInSize==128 KB block size is the internal unit, use this value to reduce intermediate stages (better latency) * output : ZBUFF_recommendedCOutSize==ZSTD_compressBound(128 KB) + 3 + 3 : ensures it's always possible to write/flush/end a full block. Skip some buffering. * By using both, it ensures that input will be entirely consumed, and output will always contain the result, reducing intermediate buffering. * **************************************************/ typedef ZSTD_DStream ZBUFF_DCtx; ZBUFF_DEPRECATED("use ZSTD_createDStream") ZBUFF_DCtx* ZBUFF_createDCtx(void); ZBUFF_DEPRECATED("use ZSTD_freeDStream") size_t ZBUFF_freeDCtx(ZBUFF_DCtx* dctx); ZBUFF_DEPRECATED("use ZSTD_initDStream") size_t ZBUFF_decompressInit(ZBUFF_DCtx* dctx); ZBUFF_DEPRECATED("use ZSTD_initDStream_usingDict") size_t ZBUFF_decompressInitDictionary(ZBUFF_DCtx* dctx, const void* dict, size_t dictSize); ZBUFF_DEPRECATED("use ZSTD_decompressStream") size_t ZBUFF_decompressContinue(ZBUFF_DCtx* dctx, void* dst, size_t* dstCapacityPtr, const void* src, size_t* srcSizePtr); /*-*************************************************************************** * Streaming decompression howto * * A ZBUFF_DCtx object is required to track streaming operations. * Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources. * Use ZBUFF_decompressInit() to start a new decompression operation, * or ZBUFF_decompressInitDictionary() if decompression requires a dictionary. * Note that ZBUFF_DCtx objects can be re-init multiple times. * * Use ZBUFF_decompressContinue() repetitively to consume your input. * *srcSizePtr and *dstCapacityPtr can be any size. * The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. * Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. * The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`. * @return : 0 when a frame is completely decoded and fully flushed, * 1 when there is still some data left within internal buffer to flush, * >1 when more data is expected, with value being a suggested next input size (it's just a hint, which helps latency), * or an error code, which can be tested using ZBUFF_isError(). * * Hint : recommended buffer sizes (not compulsory) : ZBUFF_recommendedDInSize() and ZBUFF_recommendedDOutSize() * output : ZBUFF_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. * input : ZBUFF_recommendedDInSize == 128KB + 3; * just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . * *******************************************************************************/ /* ************************************* * Tool functions ***************************************/ ZBUFF_DEPRECATED("use ZSTD_isError") unsigned ZBUFF_isError(size_t errorCode); ZBUFF_DEPRECATED("use ZSTD_getErrorName") const char* ZBUFF_getErrorName(size_t errorCode); /** Functions below provide recommended buffer sizes for Compression or Decompression operations. * These sizes are just hints, they tend to offer better latency */ ZBUFF_DEPRECATED("use ZSTD_CStreamInSize") size_t ZBUFF_recommendedCInSize(void); ZBUFF_DEPRECATED("use ZSTD_CStreamOutSize") size_t ZBUFF_recommendedCOutSize(void); ZBUFF_DEPRECATED("use ZSTD_DStreamInSize") size_t ZBUFF_recommendedDInSize(void); ZBUFF_DEPRECATED("use ZSTD_DStreamOutSize") size_t ZBUFF_recommendedDOutSize(void); #endif /* ZSTD_BUFFERED_H_23987 */ #ifdef ZBUFF_STATIC_LINKING_ONLY #ifndef ZBUFF_STATIC_H_30298098432 #define ZBUFF_STATIC_H_30298098432 /* ==================================================================================== * The definitions in this section are considered experimental. * They should never be used in association with a dynamic library, as they may change in the future. * They are provided for advanced usages. * Use them only in association with static linking. * ==================================================================================== */ /*--- Dependency ---*/ #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_parameters, ZSTD_customMem */ #include "zstd.h" /*--- Custom memory allocator ---*/ /*! ZBUFF_createCCtx_advanced() : * Create a ZBUFF compression context using external alloc and free functions */ ZBUFF_DEPRECATED("use ZSTD_createCStream_advanced") ZBUFF_CCtx* ZBUFF_createCCtx_advanced(ZSTD_customMem customMem); /*! ZBUFF_createDCtx_advanced() : * Create a ZBUFF decompression context using external alloc and free functions */ ZBUFF_DEPRECATED("use ZSTD_createDStream_advanced") ZBUFF_DCtx* ZBUFF_createDCtx_advanced(ZSTD_customMem customMem); /*--- Advanced Streaming Initialization ---*/ ZBUFF_DEPRECATED("use ZSTD_initDStream_usingDict") size_t ZBUFF_compressInit_advanced(ZBUFF_CCtx* zbc, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); #endif /* ZBUFF_STATIC_H_30298098432 */ #endif /* ZBUFF_STATIC_LINKING_ONLY */ #if defined (__cplusplus) } #endif libltdl/lt_dlloader.h000064400000006213151027430550010634 0ustar00/* lt_dlloader.h -- dynamic library loader interface Copyright (C) 2004, 2007-2008, 2011-2015 Free Software Foundation, Inc. Written by Gary V. Vaughan, 2004 NOTE: The canonical source of this file is maintained with the GNU Libtool package. Report bugs to bug-libtool@gnu.org. GNU Libltdl is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. As a special exception to the GNU Lesser General Public License, if you distribute this file as part of a program or library that is built using GNU Libtool, you may include this file under the same distribution terms that you use for the rest of that program. GNU Libltdl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU Libltdl; see the file COPYING.LIB. If not, a copy can be downloaded from http://www.gnu.org/licenses/lgpl.html, or obtained by writing to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #if !defined LT_DLLOADER_H #define LT_DLLOADER_H 1 #include LT_BEGIN_C_DECLS typedef void * lt_dlloader; typedef void * lt_module; typedef void * lt_user_data; typedef struct lt__advise * lt_dladvise; /* Function pointer types for module loader vtable entries: */ typedef lt_module lt_module_open (lt_user_data data, const char *filename, lt_dladvise advise); typedef int lt_module_close (lt_user_data data, lt_module module); typedef void * lt_find_sym (lt_user_data data, lt_module module, const char *symbolname); typedef int lt_dlloader_init (lt_user_data data); typedef int lt_dlloader_exit (lt_user_data data); /* Default priority is LT_DLLOADER_PREPEND if none is explicitly given. */ typedef enum { LT_DLLOADER_PREPEND = 0, LT_DLLOADER_APPEND } lt_dlloader_priority; /* This structure defines a module loader, as populated by the get_vtable entry point of each loader. */ typedef struct { const char * name; const char * sym_prefix; lt_module_open * module_open; lt_module_close * module_close; lt_find_sym * find_sym; lt_dlloader_init * dlloader_init; lt_dlloader_exit * dlloader_exit; lt_user_data dlloader_data; lt_dlloader_priority priority; } lt_dlvtable; LT_SCOPE int lt_dlloader_add (const lt_dlvtable *vtable); LT_SCOPE lt_dlloader lt_dlloader_next (const lt_dlloader loader); LT_SCOPE lt_dlvtable * lt_dlloader_remove (const char *name); LT_SCOPE const lt_dlvtable *lt_dlloader_find (const char *name); LT_SCOPE const lt_dlvtable *lt_dlloader_get (lt_dlloader loader); /* Type of a function to get a loader's vtable: */ typedef const lt_dlvtable *lt_get_vtable (lt_user_data data); #ifdef LT_DEBUG_LOADERS LT_SCOPE void lt_dlloader_dump (void); #endif LT_END_C_DECLS #endif /*!defined LT_DLLOADER_H*/ libltdl/lt_error.h000064400000007077151027430550010210 0ustar00/* lt_error.h -- error propagation interface Copyright (C) 1999-2001, 2004, 2007, 2011-2015 Free Software Foundation, Inc. Written by Thomas Tanner, 1999 NOTE: The canonical source of this file is maintained with the GNU Libtool package. Report bugs to bug-libtool@gnu.org. GNU Libltdl is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. As a special exception to the GNU Lesser General Public License, if you distribute this file as part of a program or library that is built using GNU Libtool, you may include this file under the same distribution terms that you use for the rest of that program. GNU Libltdl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU Libltdl; see the file COPYING.LIB. If not, a copy can be downloaded from http://www.gnu.org/licenses/lgpl.html, or obtained by writing to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Only include this header file once. */ #if !defined LT_ERROR_H #define LT_ERROR_H 1 #include LT_BEGIN_C_DECLS /* Defining error strings alongside their symbolic names in a macro in this way allows us to expand the macro in different contexts with confidence that the enumeration of symbolic names will map correctly onto the table of error strings. \0 is appended to the strings to expilicitely initialize the string terminator. */ #define lt_dlerror_table \ LT_ERROR(UNKNOWN, "unknown error\0") \ LT_ERROR(DLOPEN_NOT_SUPPORTED, "dlopen support not available\0") \ LT_ERROR(INVALID_LOADER, "invalid loader\0") \ LT_ERROR(INIT_LOADER, "loader initialization failed\0") \ LT_ERROR(REMOVE_LOADER, "loader removal failed\0") \ LT_ERROR(FILE_NOT_FOUND, "file not found\0") \ LT_ERROR(DEPLIB_NOT_FOUND, "dependency library not found\0") \ LT_ERROR(NO_SYMBOLS, "no symbols defined\0") \ LT_ERROR(CANNOT_OPEN, "can't open the module\0") \ LT_ERROR(CANNOT_CLOSE, "can't close the module\0") \ LT_ERROR(SYMBOL_NOT_FOUND, "symbol not found\0") \ LT_ERROR(NO_MEMORY, "not enough memory\0") \ LT_ERROR(INVALID_HANDLE, "invalid module handle\0") \ LT_ERROR(BUFFER_OVERFLOW, "internal buffer overflow\0") \ LT_ERROR(INVALID_ERRORCODE, "invalid errorcode\0") \ LT_ERROR(SHUTDOWN, "library already shutdown\0") \ LT_ERROR(CLOSE_RESIDENT_MODULE, "can't close resident module\0") \ LT_ERROR(INVALID_MUTEX_ARGS, "internal error (code withdrawn)\0")\ LT_ERROR(INVALID_POSITION, "invalid search path insert position\0")\ LT_ERROR(CONFLICTING_FLAGS, "symbol visibility can be global or local\0") /* Enumerate the symbolic error names. */ enum { #define LT_ERROR(name, diagnostic) LT_CONC(LT_ERROR_, name), lt_dlerror_table #undef LT_ERROR LT_ERROR_MAX }; /* Should be max of the error string lengths above (plus one for C++) */ #define LT_ERROR_LEN_MAX (41) /* These functions are only useful from inside custom module loaders. */ LT_SCOPE int lt_dladderror (const char *diagnostic); LT_SCOPE int lt_dlseterror (int errorcode); LT_END_C_DECLS #endif /*!defined LT_ERROR_H*/ libltdl/lt_system.h000064400000012336151027430550010375 0ustar00/* lt_system.h -- system portability abstraction layer Copyright (C) 2004, 2007, 2010-2015 Free Software Foundation, Inc. Written by Gary V. Vaughan, 2004 NOTE: The canonical source of this file is maintained with the GNU Libtool package. Report bugs to bug-libtool@gnu.org. GNU Libltdl is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. As a special exception to the GNU Lesser General Public License, if you distribute this file as part of a program or library that is built using GNU Libtool, you may include this file under the same distribution terms that you use for the rest of that program. GNU Libltdl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU Libltdl; see the file COPYING.LIB. If not, a copy can be downloaded from http://www.gnu.org/licenses/lgpl.html, or obtained by writing to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #if !defined LT_SYSTEM_H #define LT_SYSTEM_H 1 #include #include #include /* Some systems do not define EXIT_*, even with STDC_HEADERS. */ #if !defined EXIT_SUCCESS # define EXIT_SUCCESS 0 #endif #if !defined EXIT_FAILURE # define EXIT_FAILURE 1 #endif /* Just pick a big number... */ #define LT_FILENAME_MAX 2048 /* Saves on those hard to debug '\0' typos.... */ #define LT_EOS_CHAR '\0' /* LTDL_BEGIN_C_DECLS should be used at the beginning of your declarations, so that C++ compilers don't mangle their names. Use LTDL_END_C_DECLS at the end of C declarations. */ #if defined __cplusplus # define LT_BEGIN_C_DECLS extern "C" { # define LT_END_C_DECLS } #else # define LT_BEGIN_C_DECLS /* empty */ # define LT_END_C_DECLS /* empty */ #endif /* LT_STMT_START/END are used to create macros that expand to a a single compound statement in a portable way. */ #if defined __GNUC__ && !defined __STRICT_ANSI__ && !defined __cplusplus # define LT_STMT_START (void)( # define LT_STMT_END ) #else # if (defined sun || defined __sun__) # define LT_STMT_START if (1) # define LT_STMT_END else (void)0 # else # define LT_STMT_START do # define LT_STMT_END while (0) # endif #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined __osf__ /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif /* Canonicalise Windows and Cygwin recognition macros. To match the values set by recent Cygwin compilers, make sure that if __CYGWIN__ is defined (after canonicalisation), __WINDOWS__ is NOT! */ #if defined __CYGWIN32__ && !defined __CYGWIN__ # define __CYGWIN__ __CYGWIN32__ #endif #if defined __CYGWIN__ # if defined __WINDOWS__ # undef __WINDOWS__ # endif #elif defined _WIN32 # define __WINDOWS__ _WIN32 #elif defined WIN32 # define __WINDOWS__ WIN32 #endif #if defined __CYGWIN__ && defined __WINDOWS__ # undef __WINDOWS__ #endif /* DLL building support on win32 hosts; mostly to workaround their ridiculous implementation of data symbol exporting. */ #if !defined LT_SCOPE # if defined __WINDOWS__ || defined __CYGWIN__ # if defined DLL_EXPORT /* defined by libtool (if required) */ # define LT_SCOPE extern __declspec(dllexport) # endif # if defined LIBLTDL_DLL_IMPORT /* define if linking with this dll */ /* note: cygwin/mingw compilers can rely instead on auto-import */ # define LT_SCOPE extern __declspec(dllimport) # endif # endif # if !defined LT_SCOPE /* static linking or !__WINDOWS__ */ # define LT_SCOPE extern # endif #endif #if defined __WINDOWS__ /* LT_DIRSEP_CHAR is accepted *in addition* to '/' as a directory separator when it is set. */ # define LT_DIRSEP_CHAR '\\' # define LT_PATHSEP_CHAR ';' #else # define LT_PATHSEP_CHAR ':' #endif #if defined _MSC_VER /* Visual Studio */ # define R_OK 4 #endif /* fopen() mode flags for reading a text file */ #undef LT_READTEXT_MODE #if defined __WINDOWS__ || defined __CYGWIN__ # define LT_READTEXT_MODE "rt" #else # define LT_READTEXT_MODE "r" #endif /* The extra indirection to the LT__STR and LT__CONC macros is required so that if the arguments to LT_STR() (or LT_CONC()) are themselves macros, they will be expanded before being quoted. */ #ifndef LT_STR # define LT__STR(arg) #arg # define LT_STR(arg) LT__STR(arg) #endif #ifndef LT_CONC # define LT__CONC(a, b) a##b # define LT_CONC(a, b) LT__CONC(a, b) #endif #ifndef LT_CONC3 # define LT__CONC3(a, b, c) a##b##c # define LT_CONC3(a, b, c) LT__CONC3(a, b, c) #endif #endif /*!defined LT_SYSTEM_H*/ argp.h000064400000061506151027430550005660 0ustar00/* Hierarchial argument parsing, layered over getopt. Copyright (C) 1995-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Miles Bader . The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _ARGP_H #define _ARGP_H #include #include #include #include #include __BEGIN_DECLS /* error_t may or may not be available from errno.h, depending on the operating system. */ #ifndef __error_t_defined # define __error_t_defined 1 typedef int error_t; #endif /* A description of a particular option. A pointer to an array of these is passed in the OPTIONS field of an argp structure. Each option entry can correspond to one long option and/or one short option; more names for the same option can be added by following an entry in an option array with options having the OPTION_ALIAS flag set. */ struct argp_option { /* The long option name. For more than one name for the same option, you can use following options with the OPTION_ALIAS flag set. */ const char *name; /* What key is returned for this option. If > 0 and printable, then it's also accepted as a short option. */ int key; /* If non-NULL, this is the name of the argument associated with this option, which is required unless the OPTION_ARG_OPTIONAL flag is set. */ const char *arg; /* OPTION_ flags. */ int flags; /* The doc string for this option. If both NAME and KEY are 0, This string will be printed outdented from the normal option column, making it useful as a group header (it will be the first thing printed in its group); in this usage, it's conventional to end the string with a `:'. */ const char *doc; /* The group this option is in. In a long help message, options are sorted alphabetically within each group, and the groups presented in the order 0, 1, 2, ..., n, -m, ..., -2, -1. Every entry in an options array with if this field 0 will inherit the group number of the previous entry, or zero if it's the first one, unless its a group header (NAME and KEY both 0), in which case, the previous entry + 1 is the default. Automagic options such as --help are put into group -1. */ int group; }; /* The argument associated with this option is optional. */ #define OPTION_ARG_OPTIONAL 0x1 /* This option isn't displayed in any help messages. */ #define OPTION_HIDDEN 0x2 /* This option is an alias for the closest previous non-alias option. This means that it will be displayed in the same help entry, and will inherit fields other than NAME and KEY from the aliased option. */ #define OPTION_ALIAS 0x4 /* This option isn't actually an option (and so should be ignored by the actual option parser), but rather an arbitrary piece of documentation that should be displayed in much the same manner as the options. If this flag is set, then the option NAME field is displayed unmodified (e.g., no `--' prefix is added) at the left-margin (where a *short* option would normally be displayed), and the documentation string in the normal place. For purposes of sorting, any leading whitespace and punctuation is ignored, except that if the first non-whitespace character is not `-', this entry is displayed after all options (and OPTION_DOC entries with a leading `-') in the same group. */ #define OPTION_DOC 0x8 /* This option shouldn't be included in `long' usage messages (but is still included in help messages). This is mainly intended for options that are completely documented in an argp's ARGS_DOC field, in which case including the option in the generic usage list would be redundant. For instance, if ARGS_DOC is "FOO BAR\n-x BLAH", and the `-x' option's purpose is to distinguish these two cases, -x should probably be marked OPTION_NO_USAGE. */ #define OPTION_NO_USAGE 0x10 struct argp; /* fwd declare this type */ struct argp_state; /* " */ struct argp_child; /* " */ /* The type of a pointer to an argp parsing function. */ typedef error_t (*argp_parser_t) (int __key, char *__arg, struct argp_state *__state); /* What to return for unrecognized keys. For special ARGP_KEY_ keys, such returns will simply be ignored. For user keys, this error will be turned into EINVAL (if the call to argp_parse is such that errors are propagated back to the user instead of exiting); returning EINVAL itself would result in an immediate stop to parsing in *all* cases. */ #define ARGP_ERR_UNKNOWN E2BIG /* Hurd should never need E2BIG. XXX */ /* Special values for the KEY argument to an argument parsing function. ARGP_ERR_UNKNOWN should be returned if they aren't understood. The sequence of keys to a parsing function is either (where each uppercased word should be prefixed by `ARGP_KEY_' and opt is a user key): INIT opt... NO_ARGS END SUCCESS -- No non-option arguments at all or INIT (opt | ARG)... END SUCCESS -- All non-option args parsed or INIT (opt | ARG)... SUCCESS -- Some non-option arg unrecognized The third case is where every parser returned ARGP_KEY_UNKNOWN for an argument, in which case parsing stops at that argument (returning the unparsed arguments to the caller of argp_parse if requested, or stopping with an error message if not). If an error occurs (either detected by argp, or because the parsing function returned an error value), then the parser is called with ARGP_KEY_ERROR, and no further calls are made. */ /* This is not an option at all, but rather a command line argument. If a parser receiving this key returns success, the fact is recorded, and the ARGP_KEY_NO_ARGS case won't be used. HOWEVER, if while processing the argument, a parser function decrements the NEXT field of the state it's passed, the option won't be considered processed; this is to allow you to actually modify the argument (perhaps into an option), and have it processed again. */ #define ARGP_KEY_ARG 0 /* There are remaining arguments not parsed by any parser, which may be found starting at (STATE->argv + STATE->next). If success is returned, but STATE->next left untouched, it's assumed that all arguments were consume, otherwise, the parser should adjust STATE->next to reflect any arguments consumed. */ #define ARGP_KEY_ARGS 0x1000006 /* There are no more command line arguments at all. */ #define ARGP_KEY_END 0x1000001 /* Because it's common to want to do some special processing if there aren't any non-option args, user parsers are called with this key if they didn't successfully process any non-option arguments. Called just before ARGP_KEY_END (where more general validity checks on previously parsed arguments can take place). */ #define ARGP_KEY_NO_ARGS 0x1000002 /* Passed in before any parsing is done. Afterwards, the values of each element of the CHILD_INPUT field, if any, in the state structure is copied to each child's state to be the initial value of the INPUT field. */ #define ARGP_KEY_INIT 0x1000003 /* Use after all other keys, including SUCCESS & END. */ #define ARGP_KEY_FINI 0x1000007 /* Passed in when parsing has successfully been completed (even if there are still arguments remaining). */ #define ARGP_KEY_SUCCESS 0x1000004 /* Passed in if an error occurs. */ #define ARGP_KEY_ERROR 0x1000005 /* An argp structure contains a set of options declarations, a function to deal with parsing one, documentation string, a possible vector of child argp's, and perhaps a function to filter help output. When actually parsing options, getopt is called with the union of all the argp structures chained together through their CHILD pointers, with conflicts being resolved in favor of the first occurrence in the chain. */ struct argp { /* An array of argp_option structures, terminated by an entry with both NAME and KEY having a value of 0. */ const struct argp_option *options; /* What to do with an option from this structure. KEY is the key associated with the option, and ARG is any associated argument (NULL if none was supplied). If KEY isn't understood, ARGP_ERR_UNKNOWN should be returned. If a non-zero, non-ARGP_ERR_UNKNOWN value is returned, then parsing is stopped immediately, and that value is returned from argp_parse(). For special (non-user-supplied) values of KEY, see the ARGP_KEY_ definitions below. */ argp_parser_t parser; /* A string describing what other arguments are wanted by this program. It is only used by argp_usage to print the `Usage:' message. If it contains newlines, the strings separated by them are considered alternative usage patterns, and printed on separate lines (lines after the first are prefix by ` or: ' instead of `Usage:'). */ const char *args_doc; /* If non-NULL, a string containing extra text to be printed before and after the options in a long help message (separated by a vertical tab `\v' character). */ const char *doc; /* A vector of argp_children structures, terminated by a member with a 0 argp field, pointing to child argps should be parsed with this one. Any conflicts are resolved in favor of this argp, or early argps in the CHILDREN list. This field is useful if you use libraries that supply their own argp structure, which you want to use in conjunction with your own. */ const struct argp_child *children; /* If non-zero, this should be a function to filter the output of help messages. KEY is either a key from an option, in which case TEXT is that option's help text, or a special key from the ARGP_KEY_HELP_ defines, below, describing which other help text TEXT is. The function should return either TEXT, if it should be used as-is, a replacement string, which should be malloced, and will be freed by argp, or NULL, meaning `print nothing'. The value for TEXT is *after* any translation has been done, so if any of the replacement text also needs translation, that should be done by the filter function. INPUT is either the input supplied to argp_parse, or NULL, if argp_help was called directly. */ char *(*help_filter) (int __key, const char *__text, void *__input); /* If non-zero the strings used in the argp library are translated using the domain described by this string. Otherwise the currently installed default domain is used. */ const char *argp_domain; }; /* Possible KEY arguments to a help filter function. */ #define ARGP_KEY_HELP_PRE_DOC 0x2000001 /* Help text preceeding options. */ #define ARGP_KEY_HELP_POST_DOC 0x2000002 /* Help text following options. */ #define ARGP_KEY_HELP_HEADER 0x2000003 /* Option header string. */ #define ARGP_KEY_HELP_EXTRA 0x2000004 /* After all other documentation; TEXT is NULL for this key. */ /* Explanatory note emitted when duplicate option arguments have been suppressed. */ #define ARGP_KEY_HELP_DUP_ARGS_NOTE 0x2000005 #define ARGP_KEY_HELP_ARGS_DOC 0x2000006 /* Argument doc string. */ /* When an argp has a non-zero CHILDREN field, it should point to a vector of argp_child structures, each of which describes a subsidiary argp. */ struct argp_child { /* The child parser. */ const struct argp *argp; /* Flags for this child. */ int flags; /* If non-zero, an optional header to be printed in help output before the child options. As a side-effect, a non-zero value forces the child options to be grouped together; to achieve this effect without actually printing a header string, use a value of "". */ const char *header; /* Where to group the child options relative to the other (`consolidated') options in the parent argp; the values are the same as the GROUP field in argp_option structs, but all child-groupings follow parent options at a particular group level. If both this field and HEADER are zero, then they aren't grouped at all, but rather merged with the parent options (merging the child's grouping levels with the parents). */ int group; }; /* Parsing state. This is provided to parsing functions called by argp, which may examine and, as noted, modify fields. */ struct argp_state { /* The top level ARGP being parsed. */ const struct argp *root_argp; /* The argument vector being parsed. May be modified. */ int argc; char **argv; /* The index in ARGV of the next arg that to be parsed. May be modified. */ int next; /* The flags supplied to argp_parse. May be modified. */ unsigned flags; /* While calling a parsing function with a key of ARGP_KEY_ARG, this is the number of the current arg, starting at zero, and incremented after each such call returns. At all other times, this is the number of such arguments that have been processed. */ unsigned arg_num; /* If non-zero, the index in ARGV of the first argument following a special `--' argument (which prevents anything following being interpreted as an option). Only set once argument parsing has proceeded past this point. */ int quoted; /* An arbitrary pointer passed in from the user. */ void *input; /* Values to pass to child parsers. This vector will be the same length as the number of children for the current parser. */ void **child_inputs; /* For the parser's use. Initialized to 0. */ void *hook; /* The name used when printing messages. This is initialized to ARGV[0], or PROGRAM_INVOCATION_NAME if that is unavailable. */ char *name; /* Streams used when argp prints something. */ FILE *err_stream; /* For errors; initialized to stderr. */ FILE *out_stream; /* For information; initialized to stdout. */ void *pstate; /* Private, for use by argp. */ }; /* Flags for argp_parse (note that the defaults are those that are convenient for program command line parsing): */ /* Don't ignore the first element of ARGV. Normally (and always unless ARGP_NO_ERRS is set) the first element of the argument vector is skipped for option parsing purposes, as it corresponds to the program name in a command line. */ #define ARGP_PARSE_ARGV0 0x01 /* Don't print error messages for unknown options to stderr; unless this flag is set, ARGP_PARSE_ARGV0 is ignored, as ARGV[0] is used as the program name in the error messages. This flag implies ARGP_NO_EXIT (on the assumption that silent exiting upon errors is bad behaviour). */ #define ARGP_NO_ERRS 0x02 /* Don't parse any non-option args. Normally non-option args are parsed by calling the parse functions with a key of ARGP_KEY_ARG, and the actual arg as the value. Since it's impossible to know which parse function wants to handle it, each one is called in turn, until one returns 0 or an error other than ARGP_ERR_UNKNOWN; if an argument is handled by no one, the argp_parse returns prematurely (but with a return value of 0). If all args have been parsed without error, all parsing functions are called one last time with a key of ARGP_KEY_END. This flag needn't normally be set, as the normal behavior is to stop parsing as soon as some argument can't be handled. */ #define ARGP_NO_ARGS 0x04 /* Parse options and arguments in the same order they occur on the command line -- normally they're rearranged so that all options come first. */ #define ARGP_IN_ORDER 0x08 /* Don't provide the standard long option --help, which causes usage and option help information to be output to stdout, and exit (0) called. */ #define ARGP_NO_HELP 0x10 /* Don't exit on errors (they may still result in error messages). */ #define ARGP_NO_EXIT 0x20 /* Use the gnu getopt `long-only' rules for parsing arguments. */ #define ARGP_LONG_ONLY 0x40 /* Turns off any message-printing/exiting options. */ #define ARGP_SILENT (ARGP_NO_EXIT | ARGP_NO_ERRS | ARGP_NO_HELP) /* Parse the options strings in ARGC & ARGV according to the options in ARGP. FLAGS is one of the ARGP_ flags above. If ARG_INDEX is non-NULL, the index in ARGV of the first unparsed option is returned in it. If an unknown option is present, ARGP_ERR_UNKNOWN is returned; if some parser routine returned a non-zero value, it is returned; otherwise 0 is returned. This function may also call exit unless the ARGP_NO_HELP flag is set. INPUT is a pointer to a value to be passed in to the parser. */ extern error_t argp_parse (const struct argp *__restrict __argp, int __argc, char **__restrict __argv, unsigned __flags, int *__restrict __arg_index, void *__restrict __input); extern error_t __argp_parse (const struct argp *__restrict __argp, int __argc, char **__restrict __argv, unsigned __flags, int *__restrict __arg_index, void *__restrict __input); /* Global variables. */ /* If defined or set by the user program to a non-zero value, then a default option --version is added (unless the ARGP_NO_HELP flag is used), which will print this string followed by a newline and exit (unless the ARGP_NO_EXIT flag is used). Overridden by ARGP_PROGRAM_VERSION_HOOK. */ extern const char *argp_program_version; /* If defined or set by the user program to a non-zero value, then a default option --version is added (unless the ARGP_NO_HELP flag is used), which calls this function with a stream to print the version to and a pointer to the current parsing state, and then exits (unless the ARGP_NO_EXIT flag is used). This variable takes precedent over ARGP_PROGRAM_VERSION. */ extern void (*argp_program_version_hook) (FILE *__restrict __stream, struct argp_state *__restrict __state); /* If defined or set by the user program, it should point to string that is the bug-reporting address for the program. It will be printed by argp_help if the ARGP_HELP_BUG_ADDR flag is set (as it is by various standard help messages), embedded in a sentence that says something like `Report bugs to ADDR.'. */ extern const char *argp_program_bug_address; /* The exit status that argp will use when exiting due to a parsing error. If not defined or set by the user program, this defaults to EX_USAGE from . */ extern error_t argp_err_exit_status; /* Flags for argp_help. */ #define ARGP_HELP_USAGE 0x01 /* a Usage: message. */ #define ARGP_HELP_SHORT_USAGE 0x02 /* " but don't actually print options. */ #define ARGP_HELP_SEE 0x04 /* a `Try ... for more help' message. */ #define ARGP_HELP_LONG 0x08 /* a long help message. */ #define ARGP_HELP_PRE_DOC 0x10 /* doc string preceding long help. */ #define ARGP_HELP_POST_DOC 0x20 /* doc string following long help. */ #define ARGP_HELP_DOC (ARGP_HELP_PRE_DOC | ARGP_HELP_POST_DOC) #define ARGP_HELP_BUG_ADDR 0x40 /* bug report address */ #define ARGP_HELP_LONG_ONLY 0x80 /* modify output appropriately to reflect ARGP_LONG_ONLY mode. */ /* These ARGP_HELP flags are only understood by argp_state_help. */ #define ARGP_HELP_EXIT_ERR 0x100 /* Call exit(1) instead of returning. */ #define ARGP_HELP_EXIT_OK 0x200 /* Call exit(0) instead of returning. */ /* The standard thing to do after a program command line parsing error, if an error message has already been printed. */ #define ARGP_HELP_STD_ERR \ (ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR) /* The standard thing to do after a program command line parsing error, if no more specific error message has been printed. */ #define ARGP_HELP_STD_USAGE \ (ARGP_HELP_SHORT_USAGE | ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR) /* The standard thing to do in response to a --help option. */ #define ARGP_HELP_STD_HELP \ (ARGP_HELP_SHORT_USAGE | ARGP_HELP_LONG | ARGP_HELP_EXIT_OK \ | ARGP_HELP_DOC | ARGP_HELP_BUG_ADDR) /* Output a usage message for ARGP to STREAM. FLAGS are from the set ARGP_HELP_*. */ extern void argp_help (const struct argp *__restrict __argp, FILE *__restrict __stream, unsigned __flags, char *__restrict __name); extern void __argp_help (const struct argp *__restrict __argp, FILE *__restrict __stream, unsigned __flags, char *__name); /* The following routines are intended to be called from within an argp parsing routine (thus taking an argp_state structure as the first argument). They may or may not print an error message and exit, depending on the flags in STATE -- in any case, the caller should be prepared for them *not* to exit, and should return an appropiate error after calling them. [argp_usage & argp_error should probably be called argp_state_..., but they're used often enough that they should be short] */ /* Output, if appropriate, a usage message for STATE to STREAM. FLAGS are from the set ARGP_HELP_*. */ extern void argp_state_help (const struct argp_state *__restrict __state, FILE *__restrict __stream, unsigned int __flags); extern void __argp_state_help (const struct argp_state *__restrict __state, FILE *__restrict __stream, unsigned int __flags); /* Possibly output the standard usage message for ARGP to stderr and exit. */ extern void argp_usage (const struct argp_state *__state); extern void __argp_usage (const struct argp_state *__state); /* If appropriate, print the printf string FMT and following args, preceded by the program name and `:', to stderr, and followed by a `Try ... --help' message, then exit (1). */ extern void argp_error (const struct argp_state *__restrict __state, const char *__restrict __fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); extern void __argp_error (const struct argp_state *__restrict __state, const char *__restrict __fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); /* Similar to the standard gnu error-reporting function error(), but will respect the ARGP_NO_EXIT and ARGP_NO_ERRS flags in STATE, and will print to STATE->err_stream. This is useful for argument parsing code that is shared between program startup (when exiting is desired) and runtime option parsing (when typically an error code is returned instead). The difference between this function and argp_error is that the latter is for *parsing errors*, and the former is for other problems that occur during parsing but don't reflect a (syntactic) problem with the input. */ extern void argp_failure (const struct argp_state *__restrict __state, int __status, int __errnum, const char *__restrict __fmt, ...) __attribute__ ((__format__ (__printf__, 4, 5))); extern void __argp_failure (const struct argp_state *__restrict __state, int __status, int __errnum, const char *__restrict __fmt, ...) __attribute__ ((__format__ (__printf__, 4, 5))); /* Returns true if the option OPT is a valid short option. */ extern int _option_is_short (const struct argp_option *__opt) __THROW; extern int __option_is_short (const struct argp_option *__opt) __THROW; /* Returns true if the option OPT is in fact the last (unused) entry in an options array. */ extern int _option_is_end (const struct argp_option *__opt) __THROW; extern int __option_is_end (const struct argp_option *__opt) __THROW; /* Return the input field for ARGP in the parser corresponding to STATE; used by the help routines. */ extern void *_argp_input (const struct argp *__restrict __argp, const struct argp_state *__restrict __state) __THROW; extern void *__argp_input (const struct argp *__restrict __argp, const struct argp_state *__restrict __state) __THROW; #ifdef __USE_EXTERN_INLINES # if !(defined _LIBC && _LIBC) # define __argp_usage argp_usage # define __argp_state_help argp_state_help # define __option_is_short _option_is_short # define __option_is_end _option_is_end # endif # ifndef ARGP_EI # define ARGP_EI __extern_inline # endif ARGP_EI void __argp_usage (const struct argp_state *__state) { __argp_state_help (__state, stderr, ARGP_HELP_STD_USAGE); } ARGP_EI int __NTH (__option_is_short (const struct argp_option *__opt)) { if (__opt->flags & OPTION_DOC) return 0; else { int __key = __opt->key; return __key > 0 && __key <= UCHAR_MAX && isprint (__key); } } ARGP_EI int __NTH (__option_is_end (const struct argp_option *__opt)) { return !__opt->key && !__opt->name && !__opt->doc && !__opt->group; } # if !(defined _LIBC && _LIBC) # undef __argp_usage # undef __argp_state_help # undef __option_is_short # undef __option_is_end # endif #endif /* Use extern inlines. */ __END_DECLS #endif /* argp.h */ bzlib.h000064400000014145151027430550006026 0ustar00 /*-------------------------------------------------------------*/ /*--- Public header file for the library. ---*/ /*--- bzlib.h ---*/ /*-------------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ #ifndef _BZLIB_H #define _BZLIB_H #ifdef __cplusplus extern "C" { #endif #define BZ_RUN 0 #define BZ_FLUSH 1 #define BZ_FINISH 2 #define BZ_OK 0 #define BZ_RUN_OK 1 #define BZ_FLUSH_OK 2 #define BZ_FINISH_OK 3 #define BZ_STREAM_END 4 #define BZ_SEQUENCE_ERROR (-1) #define BZ_PARAM_ERROR (-2) #define BZ_MEM_ERROR (-3) #define BZ_DATA_ERROR (-4) #define BZ_DATA_ERROR_MAGIC (-5) #define BZ_IO_ERROR (-6) #define BZ_UNEXPECTED_EOF (-7) #define BZ_OUTBUFF_FULL (-8) #define BZ_CONFIG_ERROR (-9) typedef struct { char *next_in; unsigned int avail_in; unsigned int total_in_lo32; unsigned int total_in_hi32; char *next_out; unsigned int avail_out; unsigned int total_out_lo32; unsigned int total_out_hi32; void *state; void *(*bzalloc)(void *,int,int); void (*bzfree)(void *,void *); void *opaque; } bz_stream; #ifndef BZ_IMPORT #define BZ_EXPORT #endif #ifndef BZ_NO_STDIO /* Need a definitition for FILE */ #include #endif #ifdef _WIN32 # include # ifdef small /* windows.h define small to char */ # undef small # endif # ifdef BZ_EXPORT # define BZ_API(func) WINAPI func # define BZ_EXTERN extern # else /* import windows dll dynamically */ # define BZ_API(func) (WINAPI * func) # define BZ_EXTERN # endif #else # define BZ_API(func) func # define BZ_EXTERN extern #endif /*-- Core (low-level) library functions --*/ BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( bz_stream* strm, int blockSize100k, int verbosity, int workFactor ); BZ_EXTERN int BZ_API(BZ2_bzCompress) ( bz_stream* strm, int action ); BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( bz_stream* strm ); BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( bz_stream *strm, int verbosity, int small ); BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( bz_stream* strm ); BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ); /*-- High(er) level library functions --*/ #ifndef BZ_NO_STDIO #define BZ_MAX_UNUSED 5000 typedef void BZFILE; BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( int* bzerror, FILE* f, int verbosity, int small, void* unused, int nUnused ); BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( int* bzerror, BZFILE* b ); BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( int* bzerror, BZFILE* b, void** unused, int* nUnused ); BZ_EXTERN int BZ_API(BZ2_bzRead) ( int* bzerror, BZFILE* b, void* buf, int len ); BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( int* bzerror, FILE* f, int blockSize100k, int verbosity, int workFactor ); BZ_EXTERN void BZ_API(BZ2_bzWrite) ( int* bzerror, BZFILE* b, void* buf, int len ); BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( int* bzerror, BZFILE* b, int abandon, unsigned int* nbytes_in, unsigned int* nbytes_out ); BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( int* bzerror, BZFILE* b, int abandon, unsigned int* nbytes_in_lo32, unsigned int* nbytes_in_hi32, unsigned int* nbytes_out_lo32, unsigned int* nbytes_out_hi32 ); #endif /*-- Utility functions --*/ BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( char* dest, unsigned int* destLen, char* source, unsigned int sourceLen, int blockSize100k, int verbosity, int workFactor ); BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( char* dest, unsigned int* destLen, char* source, unsigned int sourceLen, int small, int verbosity ); /*-- Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) to support better zlib compatibility. This code is not _officially_ part of libbzip2 (yet); I haven't tested it, documented it, or considered the threading-safeness of it. If this code breaks, please contact both Yoshioka and me. --*/ BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( void ); #ifndef BZ_NO_STDIO BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( const char *path, const char *mode ); BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( int fd, const char *mode ); BZ_EXTERN int BZ_API(BZ2_bzread) ( BZFILE* b, void* buf, int len ); BZ_EXTERN int BZ_API(BZ2_bzwrite) ( BZFILE* b, void* buf, int len ); BZ_EXTERN int BZ_API(BZ2_bzflush) ( BZFILE* b ); BZ_EXTERN void BZ_API(BZ2_bzclose) ( BZFILE* b ); BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( BZFILE *b, int *errnum ); #endif #ifdef __cplusplus } #endif #endif /*-------------------------------------------------------------*/ /*--- end bzlib.h ---*/ /*-------------------------------------------------------------*/ zlib.h000064400000274005151027430550005667 0ustar00/* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.11, January 15th, 2017 Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef ZLIB_H #define ZLIB_H #include "zconf.h" #ifdef __cplusplus extern "C" { #endif #define ZLIB_VERSION "1.2.11" #define ZLIB_VERNUM 0x12b0 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 #define ZLIB_VER_REVISION 11 #define ZLIB_VER_SUBREVISION 0 /* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough, or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip and raw deflate streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in the case of corrupted input. */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { z_const Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ uLong total_in; /* total number of input bytes read so far */ Bytef *next_out; /* next output byte will go here */ uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total number of bytes output so far */ z_const char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ free_func zfree; /* used to free the internal state */ voidpf opaque; /* private data object passed to zalloc and zfree */ int data_type; /* best guess about the data type: binary or text for deflate, or the decoding state for inflate */ uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. */ typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ uLong time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ Bytef *extra; /* pointer to extra field or Z_NULL if none */ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ uInt extra_max; /* space at extra (only when reading header) */ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ uInt name_max; /* space at name (only when reading header) */ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. In that case, zlib is thread-safe. When zalloc and zfree are Z_NULL on entry to the initialization function, they are set to internal routines that use the standard library functions malloc() and free(). On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use by the decompressor (particularly if the decompressor wants to decompress everything in a single step). */ /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 #define Z_TREES 6 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field for deflate() */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ /* basic functions */ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); /* The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. */ /* ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. deflate performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Generate more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary. Some output may be provided even if flush is zero. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. See deflatePending(), which can be used if desired to determine whether or not there is more ouput in that case. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before producing output, in order to maximize compression. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. This completes the current deflate block and follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes (00 00 ff ff). If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the output buffer, but the output is not aligned to a byte boundary. All of the input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. This completes the current deflate block and follows it with an empty fixed codes block that is 10 bits long. This assures that enough bytes are output in order for the decompressor to finish the block before the empty fixed codes block. If flush is set to Z_BLOCK, a deflate block is completed and emitted, as for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to seven bits of the current block are held to be written as the next byte after the next deflate block is completed. In this case, the decompressor may not be provided enough bits at this point in order to complete decompression of the data provided so far to the compressor. It may need to wait for the next block to be emitted. This is for advanced applications that need to control the emission of deflate blocks. If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return. If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used in the first deflate call after deflateInit if all the compression is to be done in a single step. In order to complete in one call, avail_out must be at least the value returned by deflateBound (see below). Then deflate is guaranteed to return Z_STREAM_END. If not enough output space is provided, deflate will not return Z_STREAM_END, and it must be called again as described above. deflate() sets strm->adler to the Adler-32 checksum of all input read so far (that is, total_in bytes). If a gzip stream is being generated, then strm->adler will be the CRC-32 checksum of the input read so far. (See deflateInit2 below.) deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL or the state was inadvertently written over by the application), or Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing. */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. In the current version of inflate, the provided input is not read or consumed. The allocation of a sliding window will be deferred to the first call of inflate (if the decompression does not complete on the first call). If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression. Actual decompression will be done by inflate(). So next_in, and avail_in, next_out, and avail_out are unused and unchanged. The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), then next_in and avail_in are updated accordingly, and processing will resume at this point for the next call of inflate(). - Generate more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. If the caller of inflate() does not provide both available input and available output space, it is possible that there will be no progress made. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. The Z_BLOCK option assists in appending to or combining deflate streams. To assist in this, on return inflate() always sets strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits. The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all of the uncompressed data for the operation to complete. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The use of Z_FINISH is not required to perform an inflation in one step. However it may be used to inform inflate that a faster approach can be used for the single inflate() call. Z_FINISH also informs inflate to not maintain a sliding window if the stream completes, which reduces inflate's memory footprint. If the stream does not complete, either because not all of the stream is provided or not enough output space is provided, then a sliding window will be allocated and inflate() can be called again to continue the operation as if Z_NO_FLUSH had been used. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the effects of the flush parameter in this implementation are on the return value of inflate() as noted below, when inflate() returns early when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of memory for a sliding window when Z_FINISH is used. If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed Adler-32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() can decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained unless inflateGetHeader() is used. When processing gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output produced so far. The CRC-32 is checked against the gzip trailer, as is the uncompressed length, modulo 2^32. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value, in which case strm->msg points to a string with a more specific error), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL, or the state was inadvertently written over by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress was possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is to be attempted. */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state was inconsistent. */ /* Advanced functions */ /* The following functions are needed only in some special applications. */ /* ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy)); This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. For the current implementation of deflate(), a windowBits value of 8 (a window size of 256 bytes) is not supported. As a result, a request for 8 will result in 9 (a 512-byte window). In that case, providing 8 to inflateInit2() will result in an error when the zlib header with 9 is checked against the initialization of inflate(). The remedy is to not use 8 with deflateInit2() with this initialization, or at least in that case use 9 with inflateInit2(). windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute a check value. windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to the appropriate value, if the operating system was determined at compile time. If a gzip stream is being written, strm->adler is a CRC-32 instead of an Adler-32. For raw deflate or gzip encoding, a request for a 256-byte window is rejected as invalid, since only the zlib header provides a means of transmitting the window size to the decompressor. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence without producing any compressed output. When using the zlib format, this function must be called immediately after deflateInit, deflateInit2 or deflateReset, and before any call of deflate. When doing raw deflate, this function must be called either before any call of deflate, or immediately after the completion of a deflate block, i.e. after all input has been consumed and all output has been delivered when using any of the flush options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the Adler-32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The Adler-32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the Adler-32 value is not computed and strm->adler is not set. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if not at a block boundary for raw deflate). deflateSetDictionary does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, Bytef *dictionary, uInt *dictLength)); /* Returns the sliding dictionary being maintained by deflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If deflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set. deflateGetDictionary() may return a length less than the window size, even when more than the window size in input has been provided. It may return up to 258 bytes less in that case, due to how zlib's implementation of deflate manages the sliding window and lookahead for matches, where matches can be up to 258 bytes long. If the application needs the last window-size bytes of input, then that would need to be saved by the application outside of zlib. deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent. */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate the internal compression state. The stream will leave the compression level and any other attributes that may have been set unchanged. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, int level, int strategy)); /* Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2(). This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression approach (which is a function of the level) or the strategy is changed, and if there have been any deflate() calls since the state was initialized or reset, then the input available so far is compressed with the old level and strategy using deflate(strm, Z_BLOCK). There are three approaches for the compression levels 0, 1..3, and 4..9 respectively. The new level and strategy will take effect at the next call of deflate(). If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does not have enough output space to complete, then the parameter change will not take effect. In this case, deflateParams() can be called again with the same parameters and more output space to try again. In order to assure a change in the parameters on the first try, the deflate stream should be flushed using deflate() with Z_BLOCK or other flush request until strm.avail_out is not zero, before calling deflateParams(). Then no more input data should be provided before the deflateParams() call. If this is done, the old level and strategy will be applied to the data compressed before deflateParams(), and the new level and strategy will be applied to the the data compressed after deflateParams(). deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if there was not enough output space to complete the compression of the available input data before a change in the strategy or approach. Note that in the case of a Z_BUF_ERROR, the parameters are not changed. A return value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be retried with more output space. */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)); /* Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters. deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, uLong sourceLen)); /* deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). If that first deflate() call is provided the sourceLen input bytes, an output buffer allocated to the size returned by deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it is possible for the compressed size to be larger than the value returned by deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used. */ ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, unsigned *pending, int *bits)); /* deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not provided would be due to the available output space having being consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set. deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); /* deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output. deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, gz_headerp head)); /* deflateSetHeader() provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up. If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset(). deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, int windowBits)); This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an Adler-32 or a CRC-32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits. windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see below), inflate() will not automatically decode concatenated gzip streams. inflate() will return Z_STREAM_END at the end of the gzip stream. The state would need to be reset to continue decoding a subsequent gzip stream. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler-32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called at any time to set the dictionary. If the provided dictionary is smaller than the window and there is already data in the window, then the provided dictionary will amend what's there. The application must insure that the dictionary that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler-32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate(). */ ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, Bytef *dictionary, uInt *dictLength)); /* Returns the sliding dictionary being maintained by inflate. dictLength is set to the number of bytes in the dictionary, and that many bytes are copied to dictionary. dictionary must have enough space, where 32768 bytes is always enough. If inflateGetDictionary() is called with dictionary equal to Z_NULL, then only the dictionary length is returned, and nothing is copied. Similary, if dictLength is Z_NULL, then it is not set. inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the stream state is inconsistent. */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* Skips invalid compressed data until a possible full flush point (see above for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync searches for a 00 00 FF FF pattern in the compressed data. All full flush points have this pattern, but not all occurrences of this pattern are full flush points. inflateSync returns Z_OK if a possible full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, int windowBits)); /* This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. If the window size is changed, then the memory allocated for the window is freed, and the window will be reallocated by inflate() if needed. inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid. */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, int bits, int value)); /* This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input. If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); /* This function returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code. A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data. inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate. inflateMark returns the value noted above, or -65536 if the provided source stream state was inconsistent. */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, gz_headerp head)); /* inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed. The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, unsigned char FAR *window)); Initialize the internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams. See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of the parameters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ typedef unsigned (*in_func) OF((void FAR *, z_const unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)); /* inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is potentially more efficient than inflate() for file i/o applications, in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. inflate() can be faster on modern CPUs when used with large buffers. inflateBack() trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns. inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state. A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the default behavior of inflate(), which expects a zlib header and trailer around the deflate stream. inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero -- buf is ignored in that case -- and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in(). For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1]. The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job. On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK. */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* All memory allocated by inflateBackInit() is freed. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent. */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); /* Return flags indicating compile-time options. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 1.0: size of uInt 3.2: size of uLong 5.4: size of voidpf (pointer) 7.6: size of z_off_t Compiler, assembler, and debug options: 8: ZLIB_DEBUG 9: ASMV or ASMINF -- use ASM code 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 11: 0 (reserved) One-time table building (smaller code, but not thread-safe if true): 12: BUILDFIXED -- build static block decoding tables when needed 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 14,15: 0 (reserved) Library content (indicates missing functionality): 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking deflate code when not needed) 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect and decode gzip streams (to avoid linking crc code) 18-19: 0 (reserved) Operation variations (changes in library functionality): 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 21: FASTEST -- deflate algorithm with only one, lowest compression level 22,23: 0 (reserved) The sprintf variant used by gzprintf (zero is best): 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 26: 0 = returns value, 1 = void -- 1 means inferred string length returned Remainder: 27-31: 0 (reserved) */ #ifndef Z_SOLO /* utility functions */ /* The following utility functions are implemented on top of the basic stream-oriented functions. To simplify the interface, some default options are assumed (compression level and memory usage, standard memory allocation functions). The source code of these utility functions can be modified if you need special options. */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress() is equivalent to compress2() with a level parameter of Z_DEFAULT_COMPRESSION. compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer. */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)); /* Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed data. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer. */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the uncompressed data. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In the case where there is not enough room, uncompress() will fill the output buffer with the uncompressed data up to that point. */ ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong *sourceLen)); /* Same as uncompress, except that sourceLen is a pointer, where the length of the source is *sourceLen. On return, *sourceLen is the number of source bytes consumed. */ /* gzip file access functions */ /* This library supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio, using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. */ typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) 'T' will request transparent writing or appending with no compression and not using the gzip format. "a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. The addition of "x" when writing will create the file exclusively, which fails if the file already exists. On systems that support it, the addition of "e" when reading or writing will set the flag to close the file on an execve() call. These functions, as well as gzip, will read and decode a sequence of gzip streams in a file. The append function of gzopen() can be used to create such a file. (Also see gzflush() for another way to do this.) When appending, gzopen does not test whether the file begins with a gzip stream, nor does it look for the end of the gzip streams to begin appending. gzopen will simply append a gzip stream to the existing file. gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. When reading, this will be detected automatically by looking for the magic two- byte gzip header. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened. */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* gzdopen associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen. The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. If you are using fileno() to get the file descriptor from a FILE *, then you will have to use dup() to avoid double-close()ing the file descriptor. Both gzclose() and fclose() will close the associated file descriptor, so they need to have different file descriptors. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1). */ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); /* Set the internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Three times that size in buffer space is allocated. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading). The new buffer size also affects the maximum length for gzprintf(). gzbuffer() returns 0 on success, or -1 on failure, such as being called too late. */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. Previously provided data is flushed before the parameter change. gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not opened for writing, Z_ERRNO if there is an error writing the flushed data, or Z_MEM_ERROR if there is a memory allocation error. */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If the input file is not in gzip format, gzread copies the given number of bytes into the buffer directly from the file. After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream. Any number of gzip streams may be concatenated in the input file, and will all be decompressed by gzread(). If something other than a gzip stream is encountered after a gzip stream, that remaining trailing garbage is ignored (and no error is returned). gzread can be used to read a gzip file that is being concurrently written. Upon reaching the end of the input, gzread will return with the available data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then gzclearerr can be used to clear the end of file indicator in order to permit gzread to be tried again. Z_OK indicates that a gzip stream was completed on the last gzread. Z_BUF_ERROR indicates that the input file ended in the middle of a gzip stream. Note that gzread does not return -1 in the event of an incomplete gzip stream. This error is deferred until gzclose(), which will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip stream. Alternatively, gzerror can be used before gzclose to detect this case. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. If len is too large to fit in an int, then nothing is read, -1 is returned, and the error state is set to Z_STREAM_ERROR. */ ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, gzFile file)); /* Read up to nitems items of size size from file to buf, otherwise operating as gzread() does. This duplicates the interface of stdio's fread(), with size_t request and return types. If the library defines size_t, then z_size_t is identical to size_t. If not, then z_size_t is an unsigned integer type that can contain a pointer. gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in order to determine if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a z_size_t, then nothing is read, zero is returned, and the error state is set to Z_STREAM_ERROR. In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a multiple of size, then the final partial item is nevetheless read into buf and the end-of-file flag is set. The length of the partial item read is not provided, but could be inferred from the result of gztell(). This behavior is the same as the behavior of fread() implementations in common libraries, but it prevents the direct use of gzfread() to read a concurrently written file, reseting and retrying on end-of-file, when size is not 1. */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); /* Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error. */ ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, z_size_t nitems, gzFile file)); /* gzfwrite() writes nitems items of size size from buf to file, duplicating the interface of stdio's fwrite(), with size_t request and return types. If the library defines size_t, then z_size_t is identical to size_t. If not, then z_size_t is an unsigned integer type that can contain a pointer. gzfwrite() returns the number of full items written of size size, or zero if there was an error. If the multiplication of size and nitems overflows, i.e. the product does not fit in a z_size_t, then nothing is written, zero is returned, and the error state is set to Z_STREAM_ERROR. */ ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or a negative zlib error code in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags(). */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* Writes the given null-terminated string to the compressed file, excluding the terminating null character. gzputs returns the number of characters written, or -1 in case of error. */ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched. gzgets returns buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate. */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* Writes c, converted to an unsigned char, into the compressed file. gzputc returns the value that was written, or -1 in case of error. */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. This is implemented as a macro for speed. As such, it does not do all of the checking the other functions do. I.e. it does not check to see if file is NULL, nor whether the structure file points to has been clobbered or not. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* Push one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind(). */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing. If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatenated gzip streams. gzflush should be called only when strictly necessary because it will degrade compression if called too often. */ /* ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, z_off_t offset, int whence)); Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position. gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position. */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* Rewinds the given file. This function is supported only for reading. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) */ /* ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen(). gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) */ /* ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); Returns the current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1. */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size. If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected. */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). When writing, gzdirect() returns true (1) if transparent writing was requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: gzdirect() is not needed when writing. Transparent writing must be explicitly requested, so the application already knows the answer. When linking statically, using gzdirect() will include all of the zlib code for gzip file reading and decompression, which may not be desired.) */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the last read ended in the middle of a gzip stream, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); /* Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library. */ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); /* Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available. gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values. */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently. */ #endif /* !Z_SOLO */ /* checksum functions */ /* These functions are not related to compression but are exported anyway because they might be useful in applications using the compression library. */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed much faster. Usage example: uLong adler = adler32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { adler = adler32(adler, buffer, length); } if (adler != original_adler) error(); */ ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, z_size_t len)); /* Same as adler32(), but with a size_t length. */ /* ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, z_off_t len2)); Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note that the z_off_t type (like off_t) is a signed integer. If len2 is negative, the result has no meaning or utility. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error(); */ ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf, z_size_t len)); /* Same as crc32(), but with a size_t length. */ /* ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2. */ /* various hacks, don't look :) */ /* deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)); #ifdef Z_PREFIX_SET # define z_deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) # define z_inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ (int)sizeof(z_stream)) # define z_inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, (int)sizeof(z_stream)) #else # define deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) # define inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) # define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) # define inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ (int)sizeof(z_stream)) # define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, (int)sizeof(z_stream)) #endif #ifndef Z_SOLO /* gzgetc() macro and its supporting function and exposed data structure. Note * that the real internal state is much larger than the exposed structure. * This abbreviated structure exposes just enough for the gzgetc() macro. The * user should not mess with these exposed elements, since their names or * behavior could change in the future, perhaps even capriciously. They can * only be used by the gzgetc() macro. You have been warned. */ struct gzFile_s { unsigned have; unsigned char *next; z_off64_t pos; }; ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ #ifdef Z_PREFIX_SET # undef z_gzgetc # define z_gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) #else # define gzgetc(g) \ ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) #endif /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ #ifdef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif #if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) # ifdef Z_PREFIX_SET # define z_gzopen z_gzopen64 # define z_gzseek z_gzseek64 # define z_gztell z_gztell64 # define z_gzoffset z_gzoffset64 # define z_adler32_combine z_adler32_combine64 # define z_crc32_combine z_crc32_combine64 # else # define gzopen gzopen64 # define gzseek gzseek64 # define gztell gztell64 # define gzoffset gzoffset64 # define adler32_combine adler32_combine64 # define crc32_combine crc32_combine64 # endif # ifndef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif #else /* Z_SOLO */ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif /* !Z_SOLO */ /* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF ((z_streamp)); ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); #if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO) ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, const char *mode)); #endif #if defined(STDC) || defined(Z_HAVE_STDARG_H) # ifndef Z_SOLO ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, const char *format, va_list va)); # endif #endif #ifdef __cplusplus } #endif #endif /* ZLIB_H */ assert.h000064400000010721151027430550006221 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * ISO C99 Standard: 7.2 Diagnostics */ #ifdef _ASSERT_H # undef _ASSERT_H # undef assert # undef __ASSERT_VOID_CAST # ifdef __USE_GNU # undef assert_perror # endif #endif /* assert.h */ #define _ASSERT_H 1 #include #if defined __cplusplus && __GNUC_PREREQ (2,95) # define __ASSERT_VOID_CAST static_cast #else # define __ASSERT_VOID_CAST (void) #endif /* void assert (int expression); If NDEBUG is defined, do nothing. If not, and EXPRESSION is zero, print an error message and abort. */ #ifdef NDEBUG # define assert(expr) (__ASSERT_VOID_CAST (0)) /* void assert_perror (int errnum); If NDEBUG is defined, do nothing. If not, and ERRNUM is not zero, print an error message with the error text for ERRNUM and abort. (This is a GNU extension.) */ # ifdef __USE_GNU # define assert_perror(errnum) (__ASSERT_VOID_CAST (0)) # endif #else /* Not NDEBUG. */ __BEGIN_DECLS /* This prints an "Assertion failed" message and aborts. */ extern void __assert_fail (const char *__assertion, const char *__file, unsigned int __line, const char *__function) __THROW __attribute__ ((__noreturn__)); /* Likewise, but prints the error text for ERRNUM. */ extern void __assert_perror_fail (int __errnum, const char *__file, unsigned int __line, const char *__function) __THROW __attribute__ ((__noreturn__)); /* The following is not at all used here but needed for standard compliance. */ extern void __assert (const char *__assertion, const char *__file, int __line) __THROW __attribute__ ((__noreturn__)); __END_DECLS /* When possible, define assert so that it does not add extra parentheses around EXPR. Otherwise, those added parentheses would suppress warnings we'd expect to be detected by gcc's -Wparentheses. */ # if defined __cplusplus # define assert(expr) \ (static_cast (expr) \ ? void (0) \ : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION)) # elif !defined __GNUC__ || defined __STRICT_ANSI__ # define assert(expr) \ ((expr) \ ? __ASSERT_VOID_CAST (0) \ : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION)) # else /* The first occurrence of EXPR is not evaluated due to the sizeof, but will trigger any pedantic warnings masked by the __extension__ for the second occurrence. The ternary operator is required to support function pointers and bit fields in this context, and to suppress the evaluation of variable length arrays. */ # define assert(expr) \ ((void) sizeof ((expr) ? 1 : 0), __extension__ ({ \ if (expr) \ ; /* empty */ \ else \ __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \ })) # endif # ifdef __USE_GNU # define assert_perror(errnum) \ (!(errnum) \ ? __ASSERT_VOID_CAST (0) \ : __assert_perror_fail ((errnum), __FILE__, __LINE__, __ASSERT_FUNCTION)) # endif /* Version 2.4 and later of GCC define a magical variable `__PRETTY_FUNCTION__' which contains the name of the function currently being defined. This is broken in G++ before version 2.6. C9x has a similar variable called __func__, but prefer the GCC one since it demangles C++ function names. */ # if defined __cplusplus ? __GNUC_PREREQ (2, 6) : __GNUC_PREREQ (2, 4) # define __ASSERT_FUNCTION __extension__ __PRETTY_FUNCTION__ # else # if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L # define __ASSERT_FUNCTION __func__ # else # define __ASSERT_FUNCTION ((const char *) 0) # endif # endif #endif /* NDEBUG. */ #if defined __USE_ISOC11 && !defined __cplusplus # undef static_assert # define static_assert _Static_assert #endif sepol/iface_record.h000064400000003460151027430550010451 0ustar00#ifndef _SEPOL_IFACE_RECORD_H_ #define _SEPOL_IFACE_RECORD_H_ #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_iface; struct sepol_iface_key; typedef struct sepol_iface sepol_iface_t; typedef struct sepol_iface_key sepol_iface_key_t; /* Key */ extern int sepol_iface_compare(const sepol_iface_t * iface, const sepol_iface_key_t * key); extern int sepol_iface_compare2(const sepol_iface_t * iface, const sepol_iface_t * iface2); extern void sepol_iface_key_unpack(const sepol_iface_key_t * key, const char **name); extern int sepol_iface_key_create(sepol_handle_t * handle, const char *name, sepol_iface_key_t ** key_ptr); extern int sepol_iface_key_extract(sepol_handle_t * handle, const sepol_iface_t * iface, sepol_iface_key_t ** key_ptr); extern void sepol_iface_key_free(sepol_iface_key_t * key); /* Name */ extern const char *sepol_iface_get_name(const sepol_iface_t * iface); extern int sepol_iface_set_name(sepol_handle_t * handle, sepol_iface_t * iface, const char *name); /* Context */ extern sepol_context_t *sepol_iface_get_ifcon(const sepol_iface_t * iface); extern int sepol_iface_set_ifcon(sepol_handle_t * handle, sepol_iface_t * iface, sepol_context_t * con); extern sepol_context_t *sepol_iface_get_msgcon(const sepol_iface_t * iface); extern int sepol_iface_set_msgcon(sepol_handle_t * handle, sepol_iface_t * iface, sepol_context_t * con); /* Create/Clone/Destroy */ extern int sepol_iface_create(sepol_handle_t * handle, sepol_iface_t ** iface_ptr); extern int sepol_iface_clone(sepol_handle_t * handle, const sepol_iface_t * iface, sepol_iface_t ** iface_ptr); extern void sepol_iface_free(sepol_iface_t * iface); #ifdef __cplusplus } #endif #endif sepol/roles.h000064400000000523151027430550007165 0ustar00#ifndef _SEPOL_ROLES_H_ #define _SEPOL_ROLES_H_ #ifdef __cplusplus extern "C" { #endif extern int sepol_role_exists(const sepol_policydb_t * policydb, const char *role, int *response); extern int sepol_role_list(const sepol_policydb_t * policydb, char ***roles, unsigned int *nroles); #ifdef __cplusplus } #endif #endif sepol/cil/cil.h000064400000006645151027430550007372 0ustar00/* * Copyright 2011 Tresys Technology, LLC. 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. * * THIS SOFTWARE IS PROVIDED BY TRESYS TECHNOLOGY, LLC ``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 TRESYS TECHNOLOGY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of Tresys Technology, LLC. */ #ifndef CIL_H_ #define CIL_H_ #include #ifdef __cplusplus extern "C" { #endif struct cil_db; typedef struct cil_db cil_db_t; extern void cil_db_init(cil_db_t **db); extern void cil_db_destroy(cil_db_t **db); extern int cil_add_file(cil_db_t *db, char *name, char *data, size_t size); extern int cil_compile(cil_db_t *db); extern int cil_build_policydb(cil_db_t *db, sepol_policydb_t **sepol_db); extern int cil_userprefixes_to_string(cil_db_t *db, char **out, size_t *size); extern int cil_selinuxusers_to_string(cil_db_t *db, char **out, size_t *size); extern int cil_filecons_to_string(cil_db_t *db, char **out, size_t *size); extern void cil_set_disable_dontaudit(cil_db_t *db, int disable_dontaudit); extern void cil_set_multiple_decls(cil_db_t *db, int multiple_decls); extern void cil_set_disable_neverallow(cil_db_t *db, int disable_neverallow); extern void cil_set_preserve_tunables(cil_db_t *db, int preserve_tunables); extern int cil_set_handle_unknown(cil_db_t *db, int handle_unknown); extern void cil_set_mls(cil_db_t *db, int mls); extern void cil_set_attrs_expand_generated(struct cil_db *db, int attrs_expand_generated); extern void cil_set_attrs_expand_size(struct cil_db *db, unsigned attrs_expand_size); extern void cil_set_target_platform(cil_db_t *db, int target_platform); extern void cil_set_policy_version(cil_db_t *db, int policy_version); extern void cil_write_policy_conf(FILE *out, struct cil_db *db); enum cil_log_level { CIL_ERR = 1, CIL_WARN, CIL_INFO }; extern void cil_set_log_level(enum cil_log_level lvl); extern void cil_set_log_handler(void (*handler)(int lvl, char *msg)); #ifdef __GNUC__ __attribute__ ((format(printf, 2, 3))) #endif extern void cil_log(enum cil_log_level lvl, const char *msg, ...); extern void cil_set_malloc_error_handler(void (*handler)(void)); #ifdef __cplusplus } #endif #endif sepol/module_to_cil.h000064400000000511151027430550010654 0ustar00#include #include #include int sepol_module_policydb_to_cil(FILE *fp, struct policydb *pdb, int linked); int sepol_module_package_to_cil(FILE *fp, struct sepol_module_package *mod_pkg); int sepol_ppfile_to_module_package(FILE *fp, struct sepol_module_package **mod_pkg); sepol/port_record.h000064400000003737151027430550010375 0ustar00#ifndef _SEPOL_PORT_RECORD_H_ #define _SEPOL_PORT_RECORD_H_ #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_port; struct sepol_port_key; typedef struct sepol_port sepol_port_t; typedef struct sepol_port_key sepol_port_key_t; #define SEPOL_PROTO_UDP 0 #define SEPOL_PROTO_TCP 1 #define SEPOL_PROTO_DCCP 2 #define SEPOL_PROTO_SCTP 3 /* Key */ extern int sepol_port_compare(const sepol_port_t * port, const sepol_port_key_t * key); extern int sepol_port_compare2(const sepol_port_t * port, const sepol_port_t * port2); extern int sepol_port_key_create(sepol_handle_t * handle, int low, int high, int proto, sepol_port_key_t ** key_ptr); extern void sepol_port_key_unpack(const sepol_port_key_t * key, int *low, int *high, int *proto); extern int sepol_port_key_extract(sepol_handle_t * handle, const sepol_port_t * port, sepol_port_key_t ** key_ptr); extern void sepol_port_key_free(sepol_port_key_t * key); /* Protocol */ extern int sepol_port_get_proto(const sepol_port_t * port); extern void sepol_port_set_proto(sepol_port_t * port, int proto); extern const char *sepol_port_get_proto_str(int proto); /* Port */ extern int sepol_port_get_low(const sepol_port_t * port); extern int sepol_port_get_high(const sepol_port_t * port); extern void sepol_port_set_port(sepol_port_t * port, int port_num); extern void sepol_port_set_range(sepol_port_t * port, int low, int high); /* Context */ extern sepol_context_t *sepol_port_get_con(const sepol_port_t * port); extern int sepol_port_set_con(sepol_handle_t * handle, sepol_port_t * port, sepol_context_t * con); /* Create/Clone/Destroy */ extern int sepol_port_create(sepol_handle_t * handle, sepol_port_t ** port_ptr); extern int sepol_port_clone(sepol_handle_t * handle, const sepol_port_t * port, sepol_port_t ** port_ptr); extern void sepol_port_free(sepol_port_t * port); #ifdef __cplusplus } #endif #endif sepol/nodes.h000064400000002440151027430550007151 0ustar00#ifndef _SEPOL_NODES_H_ #define _SEPOL_NODES_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Return the number of nodes */ extern int sepol_node_count(sepol_handle_t * handle, const sepol_policydb_t * p, unsigned int *response); /* Check if a node exists */ extern int sepol_node_exists(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_node_key_t * key, int *response); /* Query a node - returns the node, or NULL if not found */ extern int sepol_node_query(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_node_key_t * key, sepol_node_t ** response); /* Modify a node, or add it, if the key is not found */ extern int sepol_node_modify(sepol_handle_t * handle, sepol_policydb_t * policydb, const sepol_node_key_t * key, const sepol_node_t * data); /* Iterate the nodes * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_node_iterate(sepol_handle_t * handle, const sepol_policydb_t * policydb, int (*fn) (const sepol_node_t * node, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/booleans.h000064400000004304151027430550007644 0ustar00#ifndef _SEPOL_BOOLEANS_H_ #define _SEPOL_BOOLEANS_H_ #include #include #include #include #ifdef __cplusplus extern "C" { #endif /*--------------compatibility--------------*/ /* Given an existing binary policy (starting at 'data', with length 'len') and a boolean configuration file named by 'boolpath', rewrite the binary policy for the boolean settings in the boolean configuration file. The binary policy is rewritten in place in memory. Returns 0 upon success, or -1 otherwise. */ extern int sepol_genbools(void *data, size_t len, const char *boolpath); /* Given an existing binary policy (starting at 'data', with length 'len') and boolean settings specified by the parallel arrays ('names', 'values') with 'nel' elements, rewrite the binary policy for the boolean settings. The binary policy is rewritten in place in memory. Returns 0 upon success or -1 otherwise. */ extern int sepol_genbools_array(void *data, size_t len, char **names, int *values, int nel); /*---------------end compatbility------------*/ /* Set the specified boolean */ extern int sepol_bool_set(sepol_handle_t * handle, sepol_policydb_t * policydb, const sepol_bool_key_t * key, const sepol_bool_t * data); /* Return the number of booleans */ extern int sepol_bool_count(sepol_handle_t * handle, const sepol_policydb_t * p, unsigned int *response); /* Check if the specified boolean exists */ extern int sepol_bool_exists(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_bool_key_t * key, int *response); /* Query a boolean - returns the boolean, or NULL if not found */ extern int sepol_bool_query(sepol_handle_t * handle, const sepol_policydb_t * p, const sepol_bool_key_t * key, sepol_bool_t ** response); /* Iterate the booleans * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_bool_iterate(sepol_handle_t * handle, const sepol_policydb_t * policydb, int (*fn) (const sepol_bool_t * boolean, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/policydb.h000064400000011127151027430550007650 0ustar00#ifndef _SEPOL_POLICYDB_H_ #define _SEPOL_POLICYDB_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_policy_file; typedef struct sepol_policy_file sepol_policy_file_t; struct sepol_policydb; typedef struct sepol_policydb sepol_policydb_t; /* Policy file public interfaces. */ /* Create and free memory associated with a policy file. */ extern int sepol_policy_file_create(sepol_policy_file_t ** pf); extern void sepol_policy_file_free(sepol_policy_file_t * pf); /* * Set the policy file to represent a binary policy memory image. * Subsequent operations using the policy file will read and write * the image located at the specified address with the specified length. * If 'len' is 0, then merely compute the necessary length upon * subsequent policydb write operations in order to determine the * necessary buffer size to allocate. */ extern void sepol_policy_file_set_mem(sepol_policy_file_t * pf, char *data, size_t len); /* * Get the size of the buffer needed to store a policydb write * previously done on this policy file. */ extern int sepol_policy_file_get_len(sepol_policy_file_t * pf, size_t * len); /* * Set the policy file to represent a FILE. * Subsequent operations using the policy file will read and write * to the FILE. */ extern void sepol_policy_file_set_fp(sepol_policy_file_t * pf, FILE * fp); /* * Associate a handle with a policy file, for use in * error reporting from subsequent calls that take the * policy file as an argument. */ extern void sepol_policy_file_set_handle(sepol_policy_file_t * pf, sepol_handle_t * handle); /* Policydb public interfaces. */ /* Create and free memory associated with a policydb. */ extern int sepol_policydb_create(sepol_policydb_t ** p); extern void sepol_policydb_free(sepol_policydb_t * p); /* Legal types of policies that the policydb can represent. */ #define SEPOL_POLICY_KERN 0 #define SEPOL_POLICY_BASE 1 #define SEPOL_POLICY_MOD 2 /* * Range of policy versions for the kernel policy type supported * by this library. */ extern int sepol_policy_kern_vers_min(void); extern int sepol_policy_kern_vers_max(void); /* * Set the policy type as specified, and automatically initialize the * policy version accordingly to the maximum version supported for the * policy type. * Returns -1 if the policy type is not legal. */ extern int sepol_policydb_set_typevers(sepol_policydb_t * p, unsigned int type); /* * Set the policy version to a different value. * Returns -1 if the policy version is not in the supported range for * the (previously set) policy type. */ extern int sepol_policydb_set_vers(sepol_policydb_t * p, unsigned int vers); /* Set how to handle unknown class/perms. */ #define SEPOL_DENY_UNKNOWN 0 #define SEPOL_REJECT_UNKNOWN 2 #define SEPOL_ALLOW_UNKNOWN 4 extern int sepol_policydb_set_handle_unknown(sepol_policydb_t * p, unsigned int handle_unknown); /* Set the target platform */ #define SEPOL_TARGET_SELINUX 0 #define SEPOL_TARGET_XEN 1 extern int sepol_policydb_set_target_platform(sepol_policydb_t * p, int target_platform); /* * Read a policydb from a policy file. * This automatically sets the type and version based on the * image contents. */ extern int sepol_policydb_read(sepol_policydb_t * p, sepol_policy_file_t * pf); /* * Write a policydb to a policy file. * The generated image will be in the binary format corresponding * to the policy version associated with the policydb. */ extern int sepol_policydb_write(sepol_policydb_t * p, sepol_policy_file_t * pf); /* * Extract a policydb from a binary policy memory image. * This is equivalent to sepol_policydb_read with a policy file * set to refer to memory. */ extern int sepol_policydb_from_image(sepol_handle_t * handle, void *data, size_t len, sepol_policydb_t * p); /* * Generate a binary policy memory image from a policydb. * This is equivalent to sepol_policydb_write with a policy file * set to refer to memory, but internally handles computing the * necessary length and allocating an appropriately sized memory * buffer for the caller. */ extern int sepol_policydb_to_image(sepol_handle_t * handle, sepol_policydb_t * p, void **newdata, size_t * newlen); /* * Check whether the policydb has MLS enabled. */ extern int sepol_policydb_mls_enabled(const sepol_policydb_t * p); /* * Check whether the compatibility mode for SELinux network * checks should be enabled when using this policy. */ extern int sepol_policydb_compat_net(const sepol_policydb_t * p); #ifdef __cplusplus } #endif #endif sepol/kernel_to_cil.h000064400000000175151027430550010655 0ustar00#include #include int sepol_kernel_policydb_to_cil(FILE *fp, struct policydb *pdb); sepol/context_record.h000064400000003206151027430550011064 0ustar00#ifndef _SEPOL_CONTEXT_RECORD_H_ #define _SEPOL_CONTEXT_RECORD_H_ #include #ifdef __cplusplus extern "C" { #endif struct sepol_context; typedef struct sepol_context sepol_context_t; /* We don't need a key, because the context is never stored * in a data collection by itself */ /* User */ extern const char *sepol_context_get_user(const sepol_context_t * con); extern int sepol_context_set_user(sepol_handle_t * handle, sepol_context_t * con, const char *user); /* Role */ extern const char *sepol_context_get_role(const sepol_context_t * con); extern int sepol_context_set_role(sepol_handle_t * handle, sepol_context_t * con, const char *role); /* Type */ extern const char *sepol_context_get_type(const sepol_context_t * con); extern int sepol_context_set_type(sepol_handle_t * handle, sepol_context_t * con, const char *type); /* MLS */ extern const char *sepol_context_get_mls(const sepol_context_t * con); extern int sepol_context_set_mls(sepol_handle_t * handle, sepol_context_t * con, const char *mls_range); /* Create/Clone/Destroy */ extern int sepol_context_create(sepol_handle_t * handle, sepol_context_t ** con_ptr); extern int sepol_context_clone(sepol_handle_t * handle, const sepol_context_t * con, sepol_context_t ** con_ptr); extern void sepol_context_free(sepol_context_t * con); /* Parse to/from string */ extern int sepol_context_from_string(sepol_handle_t * handle, const char *str, sepol_context_t ** con); extern int sepol_context_to_string(sepol_handle_t * handle, const sepol_context_t * con, char **str_ptr); #ifdef __cplusplus } #endif #endif sepol/interfaces.h000064400000002573151027430550010173 0ustar00#ifndef __SEPOL_INTERFACES_H_ #define __SEPOL_INTERFACES_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Return the number of interfaces */ extern int sepol_iface_count(sepol_handle_t * handle, const sepol_policydb_t * policydb, unsigned int *response); /* Check if an interface exists */ extern int sepol_iface_exists(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_iface_key_t * key, int *response); /* Query an interface - returns the interface, * or NULL if not found */ extern int sepol_iface_query(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_iface_key_t * key, sepol_iface_t ** response); /* Modify an interface, or add it, if the key * is not found */ extern int sepol_iface_modify(sepol_handle_t * handle, sepol_policydb_t * policydb, const sepol_iface_key_t * key, const sepol_iface_t * data); /* Iterate the interfaces * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_iface_iterate(sepol_handle_t * handle, const sepol_policydb_t * policydb, int (*fn) (const sepol_iface_t * iface, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/policydb/avtab.h000064400000011207151027430550010744 0ustar00 /* Author : Stephen Smalley, */ /* * Updated: Yuichi Nakamura * Tuned number of hash slots for avtab to reduce memory usage */ /* Updated: Frank Mayer and Karl MacMillan * * Added conditional policy language extensions * * Copyright (C) 2003 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* FLASK */ /* * An access vector table (avtab) is a hash table * of access vectors and transition types indexed * by a type pair and a class. An access vector * table is used to represent the type enforcement * tables. */ #ifndef _SEPOL_POLICYDB_AVTAB_H_ #define _SEPOL_POLICYDB_AVTAB_H_ #include #include #ifdef __cplusplus extern "C" { #endif typedef struct avtab_key { uint16_t source_type; uint16_t target_type; uint16_t target_class; #define AVTAB_ALLOWED 0x0001 #define AVTAB_AUDITALLOW 0x0002 #define AVTAB_AUDITDENY 0x0004 #define AVTAB_NEVERALLOW 0x0080 #define AVTAB_AV (AVTAB_ALLOWED | AVTAB_AUDITALLOW | AVTAB_AUDITDENY) #define AVTAB_TRANSITION 0x0010 #define AVTAB_MEMBER 0x0020 #define AVTAB_CHANGE 0x0040 #define AVTAB_TYPE (AVTAB_TRANSITION | AVTAB_MEMBER | AVTAB_CHANGE) #define AVTAB_XPERMS_ALLOWED 0x0100 #define AVTAB_XPERMS_AUDITALLOW 0x0200 #define AVTAB_XPERMS_DONTAUDIT 0x0400 #define AVTAB_XPERMS_NEVERALLOW 0x0800 #define AVTAB_XPERMS (AVTAB_XPERMS_ALLOWED | AVTAB_XPERMS_AUDITALLOW | AVTAB_XPERMS_DONTAUDIT) #define AVTAB_ENABLED_OLD 0x80000000 #define AVTAB_ENABLED 0x8000 /* reserved for used in cond_avtab */ uint16_t specified; /* what fields are specified */ } avtab_key_t; typedef struct avtab_extended_perms { #define AVTAB_XPERMS_IOCTLFUNCTION 0x01 #define AVTAB_XPERMS_IOCTLDRIVER 0x02 /* extension of the avtab_key specified */ uint8_t specified; uint8_t driver; uint32_t perms[8]; } avtab_extended_perms_t; typedef struct avtab_datum { uint32_t data; /* access vector or type */ avtab_extended_perms_t *xperms; } avtab_datum_t; typedef struct avtab_node *avtab_ptr_t; struct avtab_node { avtab_key_t key; avtab_datum_t datum; avtab_ptr_t next; void *parse_context; /* generic context pointer used by parser; * not saved in binary policy */ unsigned merged; /* flag for avtab_write only; not saved in binary policy */ }; typedef struct avtab { avtab_ptr_t *htable; uint32_t nel; /* number of elements */ uint32_t nslot; /* number of hash slots */ uint32_t mask; /* mask to compute hash func */ } avtab_t; extern int avtab_init(avtab_t *); extern int avtab_alloc(avtab_t *, uint32_t); extern int avtab_insert(avtab_t * h, avtab_key_t * k, avtab_datum_t * d); extern avtab_datum_t *avtab_search(avtab_t * h, avtab_key_t * k); extern void avtab_destroy(avtab_t * h); extern int avtab_map(avtab_t * h, int (*apply) (avtab_key_t * k, avtab_datum_t * d, void *args), void *args); extern void avtab_hash_eval(avtab_t * h, char *tag); struct policy_file; extern int avtab_read_item(struct policy_file *fp, uint32_t vers, avtab_t * a, int (*insert) (avtab_t * a, avtab_key_t * k, avtab_datum_t * d, void *p), void *p); extern int avtab_read(avtab_t * a, struct policy_file *fp, uint32_t vers); extern avtab_ptr_t avtab_insert_nonunique(avtab_t * h, avtab_key_t * key, avtab_datum_t * datum); extern avtab_ptr_t avtab_insert_with_parse_context(avtab_t * h, avtab_key_t * key, avtab_datum_t * datum, void *parse_context); extern avtab_ptr_t avtab_search_node(avtab_t * h, avtab_key_t * key); extern avtab_ptr_t avtab_search_node_next(avtab_ptr_t node, int specified); #define MAX_AVTAB_HASH_BITS 20 #define MAX_AVTAB_HASH_BUCKETS (1 << MAX_AVTAB_HASH_BITS) #define MAX_AVTAB_HASH_MASK (MAX_AVTAB_HASH_BUCKETS-1) /* avtab_alloc uses one bucket per 2-4 elements, so adjust to get maximum buckets */ #define MAX_AVTAB_SIZE (MAX_AVTAB_HASH_BUCKETS << 1) #ifdef __cplusplus } #endif #endif /* _AVTAB_H_ */ /* FLASK */ sepol/policydb/hierarchy.h000064400000003432151027430550011626 0ustar00/* Authors: Jason Tang * Joshua Brindle * Karl MacMillan * * A set of utility functions that aid policy decision when dealing * with hierarchal items. * * Copyright (C) 2005 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SEPOL_POLICYDB_HIERARCHY_H_ #define _SEPOL_POLICYDB_HIERARCHY_H_ #include #include #ifdef __cplusplus extern "C" { #endif extern int hierarchy_add_bounds(sepol_handle_t *handle, policydb_t *p); extern void bounds_destroy_bad(avtab_ptr_t cur); extern int bounds_check_type(sepol_handle_t *handle, policydb_t *p, uint32_t child, uint32_t parent, avtab_ptr_t *bad, int *numbad); extern int bounds_check_users(sepol_handle_t *handle, policydb_t *p); extern int bounds_check_roles(sepol_handle_t *handle, policydb_t *p); extern int bounds_check_types(sepol_handle_t *handle, policydb_t *p); extern int hierarchy_check_constraints(sepol_handle_t * handle, policydb_t * p); #ifdef __cplusplus } #endif #endif sepol/policydb/expand.h000064400000007110151027430550011124 0ustar00/* Authors: Jason Tang * Joshua Brindle * Karl MacMillan * * A set of utility functions that aid policy decision when dealing * with hierarchal items. * * Copyright (C) 2005 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SEPOL_POLICYDB_EXPAND_H #define _SEPOL_POLICYDB_EXPAND_H #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Expand only the avrules for a module. It is valid for this function * to expand base into itself (i.e. base == out); the typemap for * this special case should map type[i] to i+1. Likewise the boolmap * should map bool[i] to i + 1. This function optionally expands * neverallow rules. If neverallow rules are expanded, there is no * need to copy them and doing so could cause duplicate entries when * base == out. If the neverallow rules are not expanded, they are * just copied to the destination policy so that assertion checking * can be performed after expand. No assertion or hierarchy checking * is performed by this function. */ extern int expand_module_avrules(sepol_handle_t * handle, policydb_t * base, policydb_t * out, uint32_t * typemap, uint32_t * boolmap, uint32_t * rolemap, uint32_t * usermap, int verbose, int expand_neverallow); /* * Expand all parts of a module. Neverallow rules are not expanded (only * copied). It is not valid to expand base into itself. If check is non-zero, * performs hierarchy and assertion checking. */ extern int expand_module(sepol_handle_t * handle, policydb_t * base, policydb_t * out, int verbose, int check); extern int convert_type_ebitmap(ebitmap_t * src, ebitmap_t * dst, uint32_t * typemap); extern int expand_convert_type_set(policydb_t * p, uint32_t * typemap, type_set_t * set, ebitmap_t * types, unsigned char alwaysexpand); extern int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p, unsigned char alwaysexpand); extern int role_set_expand(role_set_t * x, ebitmap_t * r, policydb_t * out, policydb_t * base, uint32_t * rolemap); extern int mls_semantic_level_expand(mls_semantic_level_t *sl, mls_level_t *l, policydb_t *p, sepol_handle_t *h); extern int mls_semantic_range_expand(mls_semantic_range_t *sr, mls_range_t *r, policydb_t *p, sepol_handle_t *h); extern int expand_rule(sepol_handle_t * handle, policydb_t * source_pol, avrule_t * source_rule, avtab_t * dest_avtab, cond_av_list_t ** cond, cond_av_list_t ** other, int enabled); extern int expand_avtab(policydb_t * p, avtab_t * a, avtab_t * expa); extern int expand_cond_av_list(policydb_t * p, cond_av_list_t * l, cond_av_list_t ** newl, avtab_t * expa); #ifdef __cplusplus } #endif #endif sepol/policydb/hashtab.h000064400000010450151027430550011260 0ustar00/* Author : Stephen Smalley, */ /* FLASK */ /* * A hash table (hashtab) maintains associations between * key values and datum values. The type of the key values * and the type of the datum values is arbitrary. The * functions for hash computation and key comparison are * provided by the creator of the table. */ #ifndef _SEPOL_POLICYDB_HASHTAB_H_ #define _SEPOL_POLICYDB_HASHTAB_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif typedef char *hashtab_key_t; /* generic key type */ typedef const char *const_hashtab_key_t; /* constant generic key type */ typedef void *hashtab_datum_t; /* generic datum type */ typedef struct hashtab_node *hashtab_ptr_t; typedef struct hashtab_node { hashtab_key_t key; hashtab_datum_t datum; hashtab_ptr_t next; } hashtab_node_t; typedef struct hashtab_val { hashtab_ptr_t *htable; /* hash table */ unsigned int size; /* number of slots in hash table */ uint32_t nel; /* number of elements in hash table */ unsigned int (*hash_value) (struct hashtab_val * h, const_hashtab_key_t key); /* hash function */ int (*keycmp) (struct hashtab_val * h, const_hashtab_key_t key1, const_hashtab_key_t key2); /* key comparison function */ } hashtab_val_t; typedef hashtab_val_t *hashtab_t; /* Creates a new hash table with the specified characteristics. Returns NULL if insufficent space is available or the new hash table otherwise. */ extern hashtab_t hashtab_create(unsigned int (*hash_value) (hashtab_t h, const_hashtab_key_t key), int (*keycmp) (hashtab_t h, const_hashtab_key_t key1, const_hashtab_key_t key2), unsigned int size); /* Inserts the specified (key, datum) pair into the specified hash table. Returns SEPOL_ENOMEM if insufficient space is available or SEPOL_EEXIST if there is already an entry with the same key or SEPOL_OK otherwise. */ extern int hashtab_insert(hashtab_t h, hashtab_key_t k, hashtab_datum_t d); /* Removes the entry with the specified key from the hash table. Applies the specified destroy function to (key,datum,args) for the entry. Returns SEPOL_ENOENT if no entry has the specified key or SEPOL_OK otherwise. */ extern int hashtab_remove(hashtab_t h, hashtab_key_t k, void (*destroy) (hashtab_key_t k, hashtab_datum_t d, void *args), void *args); /* Insert or replace the specified (key, datum) pair in the specified hash table. If an entry for the specified key already exists, then the specified destroy function is applied to (key,datum,args) for the entry prior to replacing the entry's contents. Returns SEPOL_ENOMEM if insufficient space is available or SEPOL_OK otherwise. */ extern int hashtab_replace(hashtab_t h, hashtab_key_t k, hashtab_datum_t d, void (*destroy) (hashtab_key_t k, hashtab_datum_t d, void *args), void *args); /* Searches for the entry with the specified key in the hash table. Returns NULL if no entry has the specified key or the datum of the entry otherwise. */ extern hashtab_datum_t hashtab_search(hashtab_t h, const_hashtab_key_t k); /* Destroys the specified hash table. */ extern void hashtab_destroy(hashtab_t h); /* Applies the specified apply function to (key,datum,args) for each entry in the specified hash table. The order in which the function is applied to the entries is dependent upon the internal structure of the hash table. If apply returns a non-zero status, then hashtab_map will cease iterating through the hash table and will propagate the error return to its caller. */ extern int hashtab_map(hashtab_t h, int (*apply) (hashtab_key_t k, hashtab_datum_t d, void *args), void *args); /* Same as hashtab_map, except that if apply returns a non-zero status, then the (key,datum) pair will be removed from the hashtab and the destroy function will be applied to (key,datum,args). */ extern void hashtab_map_remove_on_error(hashtab_t h, int (*apply) (hashtab_key_t k, hashtab_datum_t d, void *args), void (*destroy) (hashtab_key_t k, hashtab_datum_t d, void *args), void *args); extern void hashtab_hash_eval(hashtab_t h, char *tag); #ifdef __cplusplus } #endif #endif sepol/policydb/link.h000064400000001005151027430550010577 0ustar00/* Authors: Jason Tang * Joshua Brindle * Karl MacMillan */ #ifndef _SEPOL_POLICYDB_LINK_H #define _SEPOL_POLICYDB_LINK_H #include #include #include #include #ifdef __cplusplus extern "C" { #endif extern int link_modules(sepol_handle_t * handle, policydb_t * b, policydb_t ** mods, int len, int verbose); #ifdef __cplusplus } #endif #endif sepol/policydb/symtab.h000064400000002116151027430550011145 0ustar00 /* Author : Stephen Smalley, */ /* FLASK */ /* * A symbol table (symtab) maintains associations between symbol * strings and datum values. The type of the datum values * is arbitrary. The symbol table type is implemented * using the hash table type (hashtab). */ #ifndef _SEPOL_POLICYDB_SYMTAB_H_ #define _SEPOL_POLICYDB_SYMTAB_H_ #include #ifdef __cplusplus extern "C" { #endif /* The symtab_datum struct stores the common information for * all symtab datums. It should the first element in every * struct that will be used in a symtab to allow the specific * datum types to be freely cast to this type. * * The values start at 1 - 0 is never a valid value. */ typedef struct symtab_datum { uint32_t value; } symtab_datum_t; typedef struct { hashtab_t table; /* hash table (keyed on a string) */ uint32_t nprim; /* number of primary names in table */ } symtab_t; extern int symtab_init(symtab_t *, unsigned int size); extern void symtab_destroy(symtab_t *); #ifdef __cplusplus } #endif #endif /* _SYMTAB_H_ */ /* FLASK */ sepol/policydb/sidtab.h000064400000003670151027430550011122 0ustar00/* Author : Stephen Smalley, */ /* FLASK */ /* * A security identifier table (sidtab) is a hash table * of security context structures indexed by SID value. */ #ifndef _SEPOL_POLICYDB_SIDTAB_H_ #define _SEPOL_POLICYDB_SIDTAB_H_ #include #ifdef __cplusplus extern "C" { #endif typedef struct sidtab_node { sepol_security_id_t sid; /* security identifier */ context_struct_t context; /* security context structure */ struct sidtab_node *next; } sidtab_node_t; typedef struct sidtab_node *sidtab_ptr_t; #define SIDTAB_HASH_BITS 7 #define SIDTAB_HASH_BUCKETS (1 << SIDTAB_HASH_BITS) #define SIDTAB_HASH_MASK (SIDTAB_HASH_BUCKETS-1) #define SIDTAB_SIZE SIDTAB_HASH_BUCKETS typedef struct { sidtab_ptr_t *htable; unsigned int nel; /* number of elements */ unsigned int next_sid; /* next SID to allocate */ unsigned char shutdown; } sidtab_t; extern int sepol_sidtab_init(sidtab_t * s); extern int sepol_sidtab_insert(sidtab_t * s, sepol_security_id_t sid, context_struct_t * context); extern context_struct_t *sepol_sidtab_search(sidtab_t * s, sepol_security_id_t sid); extern int sepol_sidtab_map(sidtab_t * s, int (*apply) (sepol_security_id_t sid, context_struct_t * context, void *args), void *args); extern void sepol_sidtab_map_remove_on_error(sidtab_t * s, int (*apply) (sepol_security_id_t s, context_struct_t * context, void *args), void *args); extern int sepol_sidtab_context_to_sid(sidtab_t * s, /* IN */ context_struct_t * context, /* IN */ sepol_security_id_t * sid); /* OUT */ extern void sepol_sidtab_hash_eval(sidtab_t * h, char *tag); extern void sepol_sidtab_destroy(sidtab_t * s); extern void sepol_sidtab_set(sidtab_t * dst, sidtab_t * src); extern void sepol_sidtab_shutdown(sidtab_t * s); #ifdef __cplusplus } #endif #endif /* _SIDTAB_H_ */ /* FLASK */ sepol/policydb/policydb.h000064400000062570151027430550011465 0ustar00/* Author : Stephen Smalley, */ /* * Updated: Joshua Brindle * Karl MacMillan * Jason Tang * * Module support * * Updated: Trusted Computer Solutions, Inc. * * Support for enhanced MLS infrastructure. * * Updated: Frank Mayer and Karl MacMillan * * Added conditional policy language extensions * * Updated: Red Hat, Inc. James Morris * * Fine-grained netlink support * IPv6 support * Code cleanup * * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc. * Copyright (C) 2003 - 2004 Tresys Technology, LLC * Copyright (C) 2003 - 2004 Red Hat, Inc. * Copyright (C) 2017 Mellanox Techonolgies Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* FLASK */ /* * A policy database (policydb) specifies the * configuration data for the security policy. */ #ifndef _SEPOL_POLICYDB_POLICYDB_H_ #define _SEPOL_POLICYDB_POLICYDB_H_ #include #include #include #include #include #include #include #include #include #define ERRMSG_LEN 1024 #define POLICYDB_SUCCESS 0 #define POLICYDB_ERROR -1 #define POLICYDB_UNSUPPORTED -2 #ifdef __cplusplus extern "C" { #endif #define IB_DEVICE_NAME_MAX 64 /* * A datum type is defined for each kind of symbol * in the configuration data: individual permissions, * common prefixes for access vectors, classes, * users, roles, types, sensitivities, categories, etc. */ /* type set preserves data needed by modules such as *, ~ and attributes */ typedef struct type_set { ebitmap_t types; ebitmap_t negset; #define TYPE_STAR 1 #define TYPE_COMP 2 uint32_t flags; } type_set_t; typedef struct role_set { ebitmap_t roles; #define ROLE_STAR 1 #define ROLE_COMP 2 uint32_t flags; } role_set_t; /* Permission attributes */ typedef struct perm_datum { symtab_datum_t s; } perm_datum_t; /* Attributes of a common prefix for access vectors */ typedef struct common_datum { symtab_datum_t s; symtab_t permissions; /* common permissions */ } common_datum_t; /* Class attributes */ typedef struct class_datum { symtab_datum_t s; char *comkey; /* common name */ common_datum_t *comdatum; /* common datum */ symtab_t permissions; /* class-specific permission symbol table */ constraint_node_t *constraints; /* constraints on class permissions */ constraint_node_t *validatetrans; /* special transition rules */ /* Options how a new object user and role should be decided */ #define DEFAULT_SOURCE 1 #define DEFAULT_TARGET 2 char default_user; char default_role; char default_type; /* Options how a new object range should be decided */ #define DEFAULT_SOURCE_LOW 1 #define DEFAULT_SOURCE_HIGH 2 #define DEFAULT_SOURCE_LOW_HIGH 3 #define DEFAULT_TARGET_LOW 4 #define DEFAULT_TARGET_HIGH 5 #define DEFAULT_TARGET_LOW_HIGH 6 char default_range; } class_datum_t; /* Role attributes */ typedef struct role_datum { symtab_datum_t s; ebitmap_t dominates; /* set of roles dominated by this role */ type_set_t types; /* set of authorized types for role */ ebitmap_t cache; /* This is an expanded set used for context validation during parsing */ uint32_t bounds; /* bounds role, if exist */ #define ROLE_ROLE 0 /* regular role in kernel policies */ #define ROLE_ATTRIB 1 /* attribute */ uint32_t flavor; ebitmap_t roles; /* roles with this attribute */ } role_datum_t; typedef struct role_trans { uint32_t role; /* current role */ uint32_t type; /* program executable type, or new object type */ uint32_t tclass; /* process class, or new object class */ uint32_t new_role; /* new role */ struct role_trans *next; } role_trans_t; typedef struct role_allow { uint32_t role; /* current role */ uint32_t new_role; /* new role */ struct role_allow *next; } role_allow_t; /* filename_trans rules */ typedef struct filename_trans { uint32_t stype; uint32_t ttype; uint32_t tclass; char *name; } filename_trans_t; typedef struct filename_trans_datum { uint32_t otype; /* expected of new object */ } filename_trans_datum_t; /* Type attributes */ typedef struct type_datum { symtab_datum_t s; uint32_t primary; /* primary name? can be set to primary value if below is TYPE_ */ #define TYPE_TYPE 0 /* regular type or alias in kernel policies */ #define TYPE_ATTRIB 1 /* attribute */ #define TYPE_ALIAS 2 /* alias in modular policy */ uint32_t flavor; ebitmap_t types; /* types with this attribute */ #define TYPE_FLAGS_PERMISSIVE (1 << 0) #define TYPE_FLAGS_EXPAND_ATTR_TRUE (1 << 1) #define TYPE_FLAGS_EXPAND_ATTR_FALSE (1 << 2) #define TYPE_FLAGS_EXPAND_ATTR (TYPE_FLAGS_EXPAND_ATTR_TRUE | \ TYPE_FLAGS_EXPAND_ATTR_FALSE) uint32_t flags; uint32_t bounds; /* bounds type, if exist */ } type_datum_t; /* * Properties of type_datum * available on the policy version >= (MOD_)POLICYDB_VERSION_BOUNDARY */ #define TYPEDATUM_PROPERTY_PRIMARY 0x0001 #define TYPEDATUM_PROPERTY_ATTRIBUTE 0x0002 #define TYPEDATUM_PROPERTY_ALIAS 0x0004 /* userspace only */ #define TYPEDATUM_PROPERTY_PERMISSIVE 0x0008 /* userspace only */ /* User attributes */ typedef struct user_datum { symtab_datum_t s; role_set_t roles; /* set of authorized roles for user */ mls_semantic_range_t range; /* MLS range (min. - max.) for user */ mls_semantic_level_t dfltlevel; /* default login MLS level for user */ ebitmap_t cache; /* This is an expanded set used for context validation during parsing */ mls_range_t exp_range; /* expanded range used for validation */ mls_level_t exp_dfltlevel; /* expanded range used for validation */ uint32_t bounds; /* bounds user, if exist */ } user_datum_t; /* Sensitivity attributes */ typedef struct level_datum { mls_level_t *level; /* sensitivity and associated categories */ unsigned char isalias; /* is this sensitivity an alias for another? */ unsigned char defined; } level_datum_t; /* Category attributes */ typedef struct cat_datum { symtab_datum_t s; unsigned char isalias; /* is this category an alias for another? */ } cat_datum_t; typedef struct range_trans { uint32_t source_type; uint32_t target_type; uint32_t target_class; } range_trans_t; /* Boolean data type */ typedef struct cond_bool_datum { symtab_datum_t s; int state; #define COND_BOOL_FLAGS_TUNABLE 0x01 /* is this a tunable? */ uint32_t flags; } cond_bool_datum_t; struct cond_node; typedef struct cond_node cond_list_t; struct cond_av_list; typedef struct class_perm_node { uint32_t tclass; uint32_t data; /* permissions or new type */ struct class_perm_node *next; } class_perm_node_t; #define xperm_test(x, p) (1 & (p[x >> 5] >> (x & 0x1f))) #define xperm_set(x, p) (p[x >> 5] |= (1 << (x & 0x1f))) #define xperm_clear(x, p) (p[x >> 5] &= ~(1 << (x & 0x1f))) #define EXTENDED_PERMS_LEN 8 typedef struct av_extended_perms { #define AVRULE_XPERMS_IOCTLFUNCTION 0x01 #define AVRULE_XPERMS_IOCTLDRIVER 0x02 uint8_t specified; uint8_t driver; /* 256 bits of permissions */ uint32_t perms[EXTENDED_PERMS_LEN]; } av_extended_perms_t; typedef struct avrule { /* these typedefs are almost exactly the same as those in avtab.h - they are * here because of the need to include neverallow and dontaudit messages */ #define AVRULE_ALLOWED AVTAB_ALLOWED #define AVRULE_AUDITALLOW AVTAB_AUDITALLOW #define AVRULE_AUDITDENY AVTAB_AUDITDENY #define AVRULE_DONTAUDIT 0x0008 #define AVRULE_NEVERALLOW AVTAB_NEVERALLOW #define AVRULE_AV (AVRULE_ALLOWED | AVRULE_AUDITALLOW | AVRULE_AUDITDENY | AVRULE_DONTAUDIT | AVRULE_NEVERALLOW) #define AVRULE_TRANSITION AVTAB_TRANSITION #define AVRULE_MEMBER AVTAB_MEMBER #define AVRULE_CHANGE AVTAB_CHANGE #define AVRULE_TYPE (AVRULE_TRANSITION | AVRULE_MEMBER | AVRULE_CHANGE) #define AVRULE_XPERMS_ALLOWED AVTAB_XPERMS_ALLOWED #define AVRULE_XPERMS_AUDITALLOW AVTAB_XPERMS_AUDITALLOW #define AVRULE_XPERMS_DONTAUDIT AVTAB_XPERMS_DONTAUDIT #define AVRULE_XPERMS_NEVERALLOW AVTAB_XPERMS_NEVERALLOW #define AVRULE_XPERMS (AVRULE_XPERMS_ALLOWED | AVRULE_XPERMS_AUDITALLOW | \ AVRULE_XPERMS_DONTAUDIT | AVRULE_XPERMS_NEVERALLOW) uint32_t specified; #define RULE_SELF 1 uint32_t flags; type_set_t stypes; type_set_t ttypes; class_perm_node_t *perms; av_extended_perms_t *xperms; unsigned long line; /* line number from policy.conf where * this rule originated */ /* source file name and line number (e.g. .te file) */ char *source_filename; unsigned long source_line; struct avrule *next; } avrule_t; typedef struct role_trans_rule { role_set_t roles; /* current role */ type_set_t types; /* program executable type, or new object type */ ebitmap_t classes; /* process class, or new object class */ uint32_t new_role; /* new role */ struct role_trans_rule *next; } role_trans_rule_t; typedef struct role_allow_rule { role_set_t roles; /* current role */ role_set_t new_roles; /* new roles */ struct role_allow_rule *next; } role_allow_rule_t; typedef struct filename_trans_rule { type_set_t stypes; type_set_t ttypes; uint32_t tclass; char *name; uint32_t otype; /* new type */ struct filename_trans_rule *next; } filename_trans_rule_t; typedef struct range_trans_rule { type_set_t stypes; type_set_t ttypes; ebitmap_t tclasses; mls_semantic_range_t trange; struct range_trans_rule *next; } range_trans_rule_t; /* * The configuration data includes security contexts for * initial SIDs, unlabeled file systems, TCP and UDP port numbers, * network interfaces, and nodes. This structure stores the * relevant data for one such entry. Entries of the same kind * (e.g. all initial SIDs) are linked together into a list. */ typedef struct ocontext { union { char *name; /* name of initial SID, fs, netif, fstype, path */ struct { uint8_t protocol; uint16_t low_port; uint16_t high_port; } port; /* TCP or UDP port information */ struct { uint32_t addr; /* network order */ uint32_t mask; /* network order */ } node; /* node information */ struct { uint32_t addr[4]; /* network order */ uint32_t mask[4]; /* network order */ } node6; /* IPv6 node information */ uint32_t device; uint16_t pirq; struct { uint64_t low_iomem; uint64_t high_iomem; } iomem; struct { uint32_t low_ioport; uint32_t high_ioport; } ioport; struct { uint64_t subnet_prefix; uint16_t low_pkey; uint16_t high_pkey; } ibpkey; struct { char *dev_name; uint8_t port; } ibendport; } u; union { uint32_t sclass; /* security class for genfs */ uint32_t behavior; /* labeling behavior for fs_use */ } v; context_struct_t context[2]; /* security context(s) */ sepol_security_id_t sid[2]; /* SID(s) */ struct ocontext *next; } ocontext_t; typedef struct genfs { char *fstype; struct ocontext *head; struct genfs *next; } genfs_t; /* symbol table array indices */ #define SYM_COMMONS 0 #define SYM_CLASSES 1 #define SYM_ROLES 2 #define SYM_TYPES 3 #define SYM_USERS 4 #define SYM_BOOLS 5 #define SYM_LEVELS 6 #define SYM_CATS 7 #define SYM_NUM 8 /* object context array indices */ #define OCON_ISID 0 /* initial SIDs */ #define OCON_FS 1 /* unlabeled file systems */ #define OCON_PORT 2 /* TCP and UDP port numbers */ #define OCON_NETIF 3 /* network interfaces */ #define OCON_NODE 4 /* nodes */ #define OCON_FSUSE 5 /* fs_use */ #define OCON_NODE6 6 /* IPv6 nodes */ #define OCON_IBPKEY 7 /* Infiniband PKEY */ #define OCON_IBENDPORT 8 /* Infiniband End Port */ /* object context array indices for Xen */ #define OCON_XEN_ISID 0 /* initial SIDs */ #define OCON_XEN_PIRQ 1 /* physical irqs */ #define OCON_XEN_IOPORT 2 /* io ports */ #define OCON_XEN_IOMEM 3 /* io memory */ #define OCON_XEN_PCIDEVICE 4 /* pci devices */ #define OCON_XEN_DEVICETREE 5 /* device tree node */ /* OCON_NUM needs to be the largest index in any platform's ocontext array */ #define OCON_NUM 9 /* section: module information */ /* scope_index_t holds all of the symbols that are in scope in a * particular situation. The bitmaps are indices (and thus must * subtract one) into the global policydb->scope array. */ typedef struct scope_index { ebitmap_t scope[SYM_NUM]; #define p_classes_scope scope[SYM_CLASSES] #define p_roles_scope scope[SYM_ROLES] #define p_types_scope scope[SYM_TYPES] #define p_users_scope scope[SYM_USERS] #define p_bools_scope scope[SYM_BOOLS] #define p_sens_scope scope[SYM_LEVELS] #define p_cat_scope scope[SYM_CATS] /* this array maps from class->value to the permissions within * scope. if bit (perm->value - 1) is set in map * class_perms_map[class->value - 1] then that permission is * enabled for this class within this decl. */ ebitmap_t *class_perms_map; /* total number of classes in class_perms_map array */ uint32_t class_perms_len; } scope_index_t; /* a list of declarations for a particular avrule_decl */ /* These two structs declare a block of policy that has TE and RBAC * statements and declarations. The root block (the global policy) * can never have an ELSE branch. */ typedef struct avrule_decl { uint32_t decl_id; uint32_t enabled; /* whether this block is enabled */ cond_list_t *cond_list; avrule_t *avrules; role_trans_rule_t *role_tr_rules; role_allow_rule_t *role_allow_rules; range_trans_rule_t *range_tr_rules; scope_index_t required; /* symbols needed to activate this block */ scope_index_t declared; /* symbols declared within this block */ /* type transition rules with a 'name' component */ filename_trans_rule_t *filename_trans_rules; /* for additive statements (type attribute, roles, and users) */ symtab_t symtab[SYM_NUM]; /* In a linked module this will contain the name of the module * from which this avrule_decl originated. */ char *module_name; struct avrule_decl *next; } avrule_decl_t; typedef struct avrule_block { avrule_decl_t *branch_list; avrule_decl_t *enabled; /* pointer to which branch is enabled. this is used in linking and never written to disk */ #define AVRULE_OPTIONAL 1 uint32_t flags; /* any flags for this block, currently just optional */ struct avrule_block *next; } avrule_block_t; /* Every identifier has its own scope datum. The datum describes if * the item is to be included into the final policy during * expansion. */ typedef struct scope_datum { /* Required for this decl */ #define SCOPE_REQ 1 /* Declared in this decl */ #define SCOPE_DECL 2 uint32_t scope; uint32_t *decl_ids; uint32_t decl_ids_len; /* decl_ids is a list of avrule_decl's that declare/require * this symbol. If scope==SCOPE_DECL then this is a list of * declarations. If the symbol may only be declared once * (types, bools) then decl_ids_len will be exactly 1. For * implicitly declared things (roles, users) then decl_ids_len * will be at least 1. */ } scope_datum_t; /* The policy database */ typedef struct policydb { #define POLICY_KERN SEPOL_POLICY_KERN #define POLICY_BASE SEPOL_POLICY_BASE #define POLICY_MOD SEPOL_POLICY_MOD uint32_t policy_type; char *name; char *version; int target_platform; /* Set when the policydb is modified such that writing is unsupported */ int unsupported_format; /* Whether this policydb is mls, should always be set */ int mls; /* symbol tables */ symtab_t symtab[SYM_NUM]; #define p_commons symtab[SYM_COMMONS] #define p_classes symtab[SYM_CLASSES] #define p_roles symtab[SYM_ROLES] #define p_types symtab[SYM_TYPES] #define p_users symtab[SYM_USERS] #define p_bools symtab[SYM_BOOLS] #define p_levels symtab[SYM_LEVELS] #define p_cats symtab[SYM_CATS] /* symbol names indexed by (value - 1) */ char **sym_val_to_name[SYM_NUM]; #define p_common_val_to_name sym_val_to_name[SYM_COMMONS] #define p_class_val_to_name sym_val_to_name[SYM_CLASSES] #define p_role_val_to_name sym_val_to_name[SYM_ROLES] #define p_type_val_to_name sym_val_to_name[SYM_TYPES] #define p_user_val_to_name sym_val_to_name[SYM_USERS] #define p_bool_val_to_name sym_val_to_name[SYM_BOOLS] #define p_sens_val_to_name sym_val_to_name[SYM_LEVELS] #define p_cat_val_to_name sym_val_to_name[SYM_CATS] /* class, role, and user attributes indexed by (value - 1) */ class_datum_t **class_val_to_struct; role_datum_t **role_val_to_struct; user_datum_t **user_val_to_struct; type_datum_t **type_val_to_struct; /* module stuff section -- used in parsing and for modules */ /* keep track of the scope for every identifier. these are * hash tables, where the key is the identifier name and value * a scope_datum_t. as a convenience, one may use the * p_*_macros (cf. struct scope_index_t declaration). */ symtab_t scope[SYM_NUM]; /* module rule storage */ avrule_block_t *global; /* avrule_decl index used for link/expand */ avrule_decl_t **decl_val_to_struct; /* compiled storage of rules - use for the kernel policy */ /* type enforcement access vectors and transitions */ avtab_t te_avtab; /* bools indexed by (value - 1) */ cond_bool_datum_t **bool_val_to_struct; /* type enforcement conditional access vectors and transitions */ avtab_t te_cond_avtab; /* linked list indexing te_cond_avtab by conditional */ cond_list_t *cond_list; /* role transitions */ role_trans_t *role_tr; /* role allows */ role_allow_t *role_allow; /* security contexts of initial SIDs, unlabeled file systems, TCP or UDP port numbers, network interfaces and nodes */ ocontext_t *ocontexts[OCON_NUM]; /* security contexts for files in filesystems that cannot support a persistent label mapping or use another fixed labeling behavior. */ genfs_t *genfs; /* range transitions table (range_trans_key -> mls_range) */ hashtab_t range_tr; /* file transitions with the last path component */ hashtab_t filename_trans; ebitmap_t *type_attr_map; ebitmap_t *attr_type_map; /* not saved in the binary policy */ ebitmap_t policycaps; /* this bitmap is referenced by type NOT the typical type-1 used in other bitmaps. Someday the 0 bit may be used for global permissive */ ebitmap_t permissive_map; unsigned policyvers; unsigned handle_unknown; } policydb_t; struct sepol_policydb { struct policydb p; }; extern int policydb_init(policydb_t * p); extern int policydb_from_image(sepol_handle_t * handle, void *data, size_t len, policydb_t * policydb); extern int policydb_to_image(sepol_handle_t * handle, policydb_t * policydb, void **newdata, size_t * newlen); extern int policydb_index_classes(policydb_t * p); extern int policydb_index_bools(policydb_t * p); extern int policydb_index_others(sepol_handle_t * handle, policydb_t * p, unsigned int verbose); extern int policydb_role_cache(hashtab_key_t key, hashtab_datum_t datum, void *arg); extern int policydb_user_cache(hashtab_key_t key, hashtab_datum_t datum, void *arg); extern int policydb_reindex_users(policydb_t * p); extern void policydb_destroy(policydb_t * p); extern int policydb_load_isids(policydb_t * p, sidtab_t * s); extern int policydb_sort_ocontexts(policydb_t *p); /* Deprecated */ extern int policydb_context_isvalid(const policydb_t * p, const context_struct_t * c); extern void symtabs_destroy(symtab_t * symtab); extern int scope_destroy(hashtab_key_t key, hashtab_datum_t datum, void *p); extern void class_perm_node_init(class_perm_node_t * x); extern void type_set_init(type_set_t * x); extern void type_set_destroy(type_set_t * x); extern int type_set_cpy(type_set_t * dst, type_set_t * src); extern int type_set_or_eq(type_set_t * dst, type_set_t * other); extern void role_set_init(role_set_t * x); extern void role_set_destroy(role_set_t * x); extern void avrule_init(avrule_t * x); extern void avrule_destroy(avrule_t * x); extern void avrule_list_destroy(avrule_t * x); extern void role_trans_rule_init(role_trans_rule_t * x); extern void role_trans_rule_list_destroy(role_trans_rule_t * x); extern void filename_trans_rule_init(filename_trans_rule_t * x); extern void filename_trans_rule_list_destroy(filename_trans_rule_t * x); extern void role_datum_init(role_datum_t * x); extern void role_datum_destroy(role_datum_t * x); extern void role_allow_rule_init(role_allow_rule_t * x); extern void role_allow_rule_destroy(role_allow_rule_t * x); extern void role_allow_rule_list_destroy(role_allow_rule_t * x); extern void range_trans_rule_init(range_trans_rule_t *x); extern void range_trans_rule_destroy(range_trans_rule_t *x); extern void range_trans_rule_list_destroy(range_trans_rule_t *x); extern void type_datum_init(type_datum_t * x); extern void type_datum_destroy(type_datum_t * x); extern void user_datum_init(user_datum_t * x); extern void user_datum_destroy(user_datum_t * x); extern void level_datum_init(level_datum_t * x); extern void level_datum_destroy(level_datum_t * x); extern void cat_datum_init(cat_datum_t * x); extern void cat_datum_destroy(cat_datum_t * x); extern int check_assertion(policydb_t *p, avrule_t *avrule); extern int check_assertions(sepol_handle_t * handle, policydb_t * p, avrule_t * avrules); extern int symtab_insert(policydb_t * x, uint32_t sym, hashtab_key_t key, hashtab_datum_t datum, uint32_t scope, uint32_t avrule_decl_id, uint32_t * value); /* A policy "file" may be a memory region referenced by a (data, len) pair or a file referenced by a FILE pointer. */ typedef struct policy_file { #define PF_USE_MEMORY 0 #define PF_USE_STDIO 1 #define PF_LEN 2 /* total up length in len field */ unsigned type; char *data; size_t len; size_t size; FILE *fp; struct sepol_handle *handle; } policy_file_t; struct sepol_policy_file { struct policy_file pf; }; extern void policy_file_init(policy_file_t * x); extern int policydb_read(policydb_t * p, struct policy_file *fp, unsigned int verbose); extern int avrule_read_list(policydb_t * p, avrule_t ** avrules, struct policy_file *fp); extern int policydb_write(struct policydb *p, struct policy_file *pf); extern int policydb_set_target_platform(policydb_t *p, int platform); #define PERM_SYMTAB_SIZE 32 /* Identify specific policy version changes */ #define POLICYDB_VERSION_BASE 15 #define POLICYDB_VERSION_BOOL 16 #define POLICYDB_VERSION_IPV6 17 #define POLICYDB_VERSION_NLCLASS 18 #define POLICYDB_VERSION_VALIDATETRANS 19 #define POLICYDB_VERSION_MLS 19 #define POLICYDB_VERSION_AVTAB 20 #define POLICYDB_VERSION_RANGETRANS 21 #define POLICYDB_VERSION_POLCAP 22 #define POLICYDB_VERSION_PERMISSIVE 23 #define POLICYDB_VERSION_BOUNDARY 24 #define POLICYDB_VERSION_FILENAME_TRANS 25 #define POLICYDB_VERSION_ROLETRANS 26 #define POLICYDB_VERSION_NEW_OBJECT_DEFAULTS 27 #define POLICYDB_VERSION_DEFAULT_TYPE 28 #define POLICYDB_VERSION_CONSTRAINT_NAMES 29 #define POLICYDB_VERSION_XEN_DEVICETREE 30 /* Xen-specific */ #define POLICYDB_VERSION_XPERMS_IOCTL 30 /* Linux-specific */ #define POLICYDB_VERSION_INFINIBAND 31 /* Linux-specific */ /* Range of policy versions we understand*/ #define POLICYDB_VERSION_MIN POLICYDB_VERSION_BASE #define POLICYDB_VERSION_MAX POLICYDB_VERSION_INFINIBAND /* Module versions and specific changes*/ #define MOD_POLICYDB_VERSION_BASE 4 #define MOD_POLICYDB_VERSION_VALIDATETRANS 5 #define MOD_POLICYDB_VERSION_MLS 5 #define MOD_POLICYDB_VERSION_RANGETRANS 6 #define MOD_POLICYDB_VERSION_MLS_USERS 6 #define MOD_POLICYDB_VERSION_POLCAP 7 #define MOD_POLICYDB_VERSION_PERMISSIVE 8 #define MOD_POLICYDB_VERSION_BOUNDARY 9 #define MOD_POLICYDB_VERSION_BOUNDARY_ALIAS 10 #define MOD_POLICYDB_VERSION_FILENAME_TRANS 11 #define MOD_POLICYDB_VERSION_ROLETRANS 12 #define MOD_POLICYDB_VERSION_ROLEATTRIB 13 #define MOD_POLICYDB_VERSION_TUNABLE_SEP 14 #define MOD_POLICYDB_VERSION_NEW_OBJECT_DEFAULTS 15 #define MOD_POLICYDB_VERSION_DEFAULT_TYPE 16 #define MOD_POLICYDB_VERSION_CONSTRAINT_NAMES 17 #define MOD_POLICYDB_VERSION_XPERMS_IOCTL 18 #define MOD_POLICYDB_VERSION_INFINIBAND 19 #define MOD_POLICYDB_VERSION_MIN MOD_POLICYDB_VERSION_BASE #define MOD_POLICYDB_VERSION_MAX MOD_POLICYDB_VERSION_INFINIBAND #define POLICYDB_CONFIG_MLS 1 /* macros to check policy feature */ /* TODO: add other features here */ #define policydb_has_boundary_feature(p) \ (((p)->policy_type == POLICY_KERN \ && p->policyvers >= POLICYDB_VERSION_BOUNDARY) || \ ((p)->policy_type != POLICY_KERN \ && p->policyvers >= MOD_POLICYDB_VERSION_BOUNDARY)) /* the config flags related to unknown classes/perms are bits 2 and 3 */ #define DENY_UNKNOWN SEPOL_DENY_UNKNOWN #define REJECT_UNKNOWN SEPOL_REJECT_UNKNOWN #define ALLOW_UNKNOWN SEPOL_ALLOW_UNKNOWN #define POLICYDB_CONFIG_UNKNOWN_MASK (DENY_UNKNOWN | REJECT_UNKNOWN | ALLOW_UNKNOWN) #define OBJECT_R "object_r" #define OBJECT_R_VAL 1 #define POLICYDB_MAGIC SELINUX_MAGIC #define POLICYDB_STRING "SE Linux" #define POLICYDB_XEN_STRING "XenFlask" #define POLICYDB_STRING_MAX_LENGTH 32 #define POLICYDB_MOD_MAGIC SELINUX_MOD_MAGIC #define POLICYDB_MOD_STRING "SE Linux Module" #ifdef __cplusplus } #endif #endif /* _POLICYDB_H_ */ /* FLASK */ sepol/policydb/constraint.h000064400000005013151027430550012031 0ustar00/* Author : Stephen Smalley, */ /* FLASK */ /* * A constraint is a condition that must be satisfied in * order for one or more permissions to be granted. * Constraints are used to impose additional restrictions * beyond the type-based rules in `te' or the role-based * transition rules in `rbac'. Constraints are typically * used to prevent a process from transitioning to a new user * identity or role unless it is in a privileged type. * Constraints are likewise typically used to prevent a * process from labeling an object with a different user * identity. */ #ifndef _SEPOL_POLICYDB_CONSTRAINT_H_ #define _SEPOL_POLICYDB_CONSTRAINT_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif #define CEXPR_MAXDEPTH 5 struct type_set; typedef struct constraint_expr { #define CEXPR_NOT 1 /* not expr */ #define CEXPR_AND 2 /* expr and expr */ #define CEXPR_OR 3 /* expr or expr */ #define CEXPR_ATTR 4 /* attr op attr */ #define CEXPR_NAMES 5 /* attr op names */ uint32_t expr_type; /* expression type */ #define CEXPR_USER 1 /* user */ #define CEXPR_ROLE 2 /* role */ #define CEXPR_TYPE 4 /* type */ #define CEXPR_TARGET 8 /* target if set, source otherwise */ #define CEXPR_XTARGET 16 /* special 3rd target for validatetrans rule */ #define CEXPR_L1L2 32 /* low level 1 vs. low level 2 */ #define CEXPR_L1H2 64 /* low level 1 vs. high level 2 */ #define CEXPR_H1L2 128 /* high level 1 vs. low level 2 */ #define CEXPR_H1H2 256 /* high level 1 vs. high level 2 */ #define CEXPR_L1H1 512 /* low level 1 vs. high level 1 */ #define CEXPR_L2H2 1024 /* low level 2 vs. high level 2 */ uint32_t attr; /* attribute */ #define CEXPR_EQ 1 /* == or eq */ #define CEXPR_NEQ 2 /* != */ #define CEXPR_DOM 3 /* dom */ #define CEXPR_DOMBY 4 /* domby */ #define CEXPR_INCOMP 5 /* incomp */ uint32_t op; /* operator */ ebitmap_t names; /* names */ struct type_set *type_names; struct constraint_expr *next; /* next expression */ } constraint_expr_t; typedef struct constraint_node { sepol_access_vector_t permissions; /* constrained permissions */ constraint_expr_t *expr; /* constraint on permissions */ struct constraint_node *next; /* next constraint */ } constraint_node_t; struct policydb; extern int constraint_expr_init(constraint_expr_t * expr); extern void constraint_expr_destroy(constraint_expr_t * expr); #ifdef __cplusplus } #endif #endif /* _CONSTRAINT_H_ */ /* FLASK */ sepol/policydb/services.h000064400000020607151027430550011476 0ustar00 /* -*- linux-c -*- */ /* * Author : Stephen Smalley, */ #ifndef _SEPOL_POLICYDB_SERVICES_H_ #define _SEPOL_POLICYDB_SERVICES_H_ /* * Security server interface. */ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Set the policydb and sidtab structures to be used by the service functions. If not set, then these default to private structures within libsepol that can only be initialized and accessed via the service functions themselves. Setting the structures explicitly allows a program to directly manipulate them, e.g. checkpolicy populates the structures directly from a source policy rather than from a binary policy. */ extern int sepol_set_policydb(policydb_t * p); extern int sepol_set_sidtab(sidtab_t * s); /* Modify a policydb for boolean settings. */ int sepol_genbools_policydb(policydb_t * policydb, const char *booleans); /* Modify a policydb for user settings. */ int sepol_genusers_policydb(policydb_t * policydb, const char *usersdir); /* Load the security policy. This initializes the policydb and sidtab based on the provided binary policy. */ extern int sepol_load_policy(void *data, size_t len); /* * Compute access vectors based on a SID pair for * the permissions in a particular class. */ extern int sepol_compute_av(sepol_security_id_t ssid, /* IN */ sepol_security_id_t tsid, /* IN */ sepol_security_class_t tclass, /* IN */ sepol_access_vector_t requested, /* IN */ struct sepol_av_decision *avd); /* OUT */ /* Same as above, but also return the reason(s) for any denials of the requested permissions. */ #define SEPOL_COMPUTEAV_TE 0x1U #define SEPOL_COMPUTEAV_CONS 0x2U #define SEPOL_COMPUTEAV_RBAC 0x4U #define SEPOL_COMPUTEAV_BOUNDS 0x8U extern int sepol_compute_av_reason(sepol_security_id_t ssid, sepol_security_id_t tsid, sepol_security_class_t tclass, sepol_access_vector_t requested, struct sepol_av_decision *avd, unsigned int *reason); /* * Same as above, but also returns the constraint expression calculations * whether allowed or denied in a buffer. This buffer is allocated by * this call and must be free'd by the caller using free(3). The contraint * buffer will contain any constraints in infix notation. * If the SHOW_GRANTED flag is set it will show granted and denied * constraints. The default is to show only denied constraints. */ #define SHOW_GRANTED 1 extern int sepol_compute_av_reason_buffer(sepol_security_id_t ssid, sepol_security_id_t tsid, sepol_security_class_t tclass, sepol_access_vector_t requested, struct sepol_av_decision *avd, unsigned int *reason, char **reason_buf, unsigned int flags); /* * Returns the mls/validatetrans constraint expression calculations in * a buffer that must be free'd by the caller using free(3). * If the SHOW_GRANTED flag is set it will show granted and denied * mls/validatetrans (the default is to show only those denied). */ extern int sepol_validate_transition_reason_buffer(sepol_security_id_t oldsid, sepol_security_id_t newsid, sepol_security_id_t tasksid, sepol_security_class_t tclass, char **reason_buf, unsigned int flags); /* * Return a class ID associated with the class string representation * specified by `class_name'. */ extern int sepol_string_to_security_class(const char *class_name, sepol_security_class_t *tclass); /* * Return a permission av bit associated with tclass and the string * representation of the `perm_name'. */ extern int sepol_string_to_av_perm(sepol_security_class_t tclass, const char *perm_name, sepol_access_vector_t *av); /* * Compute a SID to use for labeling a new object in the * class `tclass' based on a SID pair. */ extern int sepol_transition_sid(sepol_security_id_t ssid, /* IN */ sepol_security_id_t tsid, /* IN */ sepol_security_class_t tclass, /* IN */ sepol_security_id_t * out_sid); /* OUT */ /* * Compute a SID to use when selecting a member of a * polyinstantiated object of class `tclass' based on * a SID pair. */ extern int sepol_member_sid(sepol_security_id_t ssid, /* IN */ sepol_security_id_t tsid, /* IN */ sepol_security_class_t tclass, /* IN */ sepol_security_id_t * out_sid); /* OUT */ /* * Compute a SID to use for relabeling an object in the * class `tclass' based on a SID pair. */ extern int sepol_change_sid(sepol_security_id_t ssid, /* IN */ sepol_security_id_t tsid, /* IN */ sepol_security_class_t tclass, /* IN */ sepol_security_id_t * out_sid); /* OUT */ /* * Write the security context string representation of * the context associated with `sid' into a dynamically * allocated string of the correct size. Set `*scontext' * to point to this string and set `*scontext_len' to * the length of the string. */ extern int sepol_sid_to_context(sepol_security_id_t sid, /* IN */ sepol_security_context_t * scontext, /* OUT */ size_t * scontext_len); /* OUT */ /* * Return a SID associated with the security context that * has the string representation specified by `scontext'. */ extern int sepol_context_to_sid(const sepol_security_context_t scontext, /* IN */ size_t scontext_len, /* IN */ sepol_security_id_t * out_sid); /* OUT */ /* * Generate the set of SIDs for legal security contexts * for a given user that can be reached by `fromsid'. * Set `*sids' to point to a dynamically allocated * array containing the set of SIDs. Set `*nel' to the * number of elements in the array. */ extern int sepol_get_user_sids(sepol_security_id_t callsid, char *username, sepol_security_id_t ** sids, uint32_t * nel); /* * Return the SIDs to use for an unlabeled file system * that is being mounted from the device with the * the kdevname `name'. The `fs_sid' SID is returned for * the file system and the `file_sid' SID is returned * for all files within that file system. */ extern int sepol_fs_sid(char *dev, /* IN */ sepol_security_id_t * fs_sid, /* OUT */ sepol_security_id_t * file_sid); /* OUT */ /* * Return the SID of the port specified by * `domain', `type', `protocol', and `port'. */ extern int sepol_port_sid(uint16_t domain, uint16_t type, uint8_t protocol, uint16_t port, sepol_security_id_t * out_sid); /* * Return the SID of the ibpkey specified by * `subnet prefix', and `pkey'. */ extern int sepol_ibpkey_sid(uint64_t subnet_prefix_p, uint16_t pkey, sepol_security_id_t *out_sid); /* * Return the SID of the ibendport specified by * `dev_name', and `port'. */ extern int sepol_ibendport_sid(char *dev_name, uint8_t port, sepol_security_id_t *out_sid); /* * Return the SIDs to use for a network interface * with the name `name'. The `if_sid' SID is returned for * the interface and the `msg_sid' SID is returned as * the default SID for messages received on the * interface. */ extern int sepol_netif_sid(char *name, sepol_security_id_t * if_sid, sepol_security_id_t * msg_sid); /* * Return the SID of the node specified by the address * `addr' where `addrlen' is the length of the address * in bytes and `domain' is the communications domain or * address family in which the address should be interpreted. */ extern int sepol_node_sid(uint16_t domain, void *addr, size_t addrlen, sepol_security_id_t * out_sid); /* * Return a value indicating how to handle labeling for the * the specified filesystem type, and optionally return a SID * for the filesystem object. */ #define SECURITY_FS_USE_XATTR 1 /* use xattr */ #define SECURITY_FS_USE_TRANS 2 /* use transition SIDs, e.g. devpts/tmpfs */ #define SECURITY_FS_USE_TASK 3 /* use task SIDs, e.g. pipefs/sockfs */ #define SECURITY_FS_USE_GENFS 4 /* use the genfs support */ #define SECURITY_FS_USE_NONE 5 /* no labeling support */ extern int sepol_fs_use(const char *fstype, /* IN */ unsigned int *behavior, /* OUT */ sepol_security_id_t * sid); /* OUT */ /* * Return the SID to use for a file in a filesystem * that cannot support a persistent label mapping or use another * fixed labeling behavior like transition SIDs or task SIDs. */ extern int sepol_genfs_sid(const char *fstype, /* IN */ const char *name, /* IN */ sepol_security_class_t sclass, /* IN */ sepol_security_id_t * sid); /* OUT */ #ifdef __cplusplus } #endif #endif sepol/policydb/context.h000064400000006404151027430550011336 0ustar00/* Author : Stephen Smalley, */ /* FLASK */ /* * A security context is a set of security attributes * associated with each subject and object controlled * by the security policy. Security contexts are * externally represented as variable-length strings * that can be interpreted by a user or application * with an understanding of the security policy. * Internally, the security server uses a simple * structure. This structure is private to the * security server and can be changed without affecting * clients of the security server. */ #ifndef _SEPOL_POLICYDB_CONTEXT_H_ #define _SEPOL_POLICYDB_CONTEXT_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* * A security context consists of an authenticated user * identity, a role, a type and a MLS range. */ typedef struct context_struct { uint32_t user; uint32_t role; uint32_t type; mls_range_t range; } context_struct_t; static inline void mls_context_init(context_struct_t * c) { mls_range_init(&c->range); } static inline int mls_context_cpy(context_struct_t * dst, context_struct_t * src) { if (mls_range_cpy(&dst->range, &src->range) < 0) return -1; return 0; } /* * Sets both levels in the MLS range of 'dst' to the low level of 'src'. */ static inline int mls_context_cpy_low(context_struct_t *dst, context_struct_t *src) { int rc; dst->range.level[0].sens = src->range.level[0].sens; rc = ebitmap_cpy(&dst->range.level[0].cat, &src->range.level[0].cat); if (rc) goto out; dst->range.level[1].sens = src->range.level[0].sens; rc = ebitmap_cpy(&dst->range.level[1].cat, &src->range.level[0].cat); if (rc) ebitmap_destroy(&dst->range.level[0].cat); out: return rc; } /* * Sets both levels in the MLS range of 'dst' to the high level of 'src'. */ static inline int mls_context_cpy_high(context_struct_t *dst, context_struct_t *src) { int rc; dst->range.level[0].sens = src->range.level[1].sens; rc = ebitmap_cpy(&dst->range.level[0].cat, &src->range.level[1].cat); if (rc) goto out; dst->range.level[1].sens = src->range.level[1].sens; rc = ebitmap_cpy(&dst->range.level[1].cat, &src->range.level[1].cat); if (rc) ebitmap_destroy(&dst->range.level[0].cat); out: return rc; } static inline int mls_context_cmp(context_struct_t * c1, context_struct_t * c2) { return (mls_level_eq(&c1->range.level[0], &c2->range.level[0]) && mls_level_eq(&c1->range.level[1], &c2->range.level[1])); } static inline void mls_context_destroy(context_struct_t * c) { if (c == NULL) return; mls_range_destroy(&c->range); mls_context_init(c); } static inline void context_init(context_struct_t * c) { memset(c, 0, sizeof(*c)); } static inline int context_cpy(context_struct_t * dst, context_struct_t * src) { dst->user = src->user; dst->role = src->role; dst->type = src->type; return mls_context_cpy(dst, src); } static inline void context_destroy(context_struct_t * c) { if (c == NULL) return; c->user = c->role = c->type = 0; mls_context_destroy(c); } static inline int context_cmp(context_struct_t * c1, context_struct_t * c2) { return ((c1->user == c2->user) && (c1->role == c2->role) && (c1->type == c2->type) && mls_context_cmp(c1, c2)); } #ifdef __cplusplus } #endif #endif sepol/policydb/mls_types.h000064400000010430151027430550011663 0ustar00/* Author : Stephen Smalley, */ /* * Updated: Trusted Computer Solutions, Inc. * * Support for enhanced MLS infrastructure. * * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* FLASK */ /* * Type definitions for the multi-level security (MLS) policy. */ #ifndef _SEPOL_POLICYDB_MLS_TYPES_H_ #define _SEPOL_POLICYDB_MLS_TYPES_H_ #include #include #include #include #ifdef __cplusplus extern "C" { #endif typedef struct mls_level { uint32_t sens; /* sensitivity */ ebitmap_t cat; /* category set */ } mls_level_t; typedef struct mls_range { mls_level_t level[2]; /* low == level[0], high == level[1] */ } mls_range_t; static inline int mls_level_cpy(struct mls_level *dst, struct mls_level *src) { dst->sens = src->sens; if (ebitmap_cpy(&dst->cat, &src->cat) < 0) return -1; return 0; } static inline void mls_level_init(struct mls_level *level) { memset(level, 0, sizeof(mls_level_t)); } static inline void mls_level_destroy(struct mls_level *level) { if (level == NULL) return; ebitmap_destroy(&level->cat); mls_level_init(level); } static inline int mls_level_eq(const struct mls_level *l1, const struct mls_level *l2) { return ((l1->sens == l2->sens) && ebitmap_cmp(&l1->cat, &l2->cat)); } static inline int mls_level_dom(const struct mls_level *l1, const struct mls_level *l2) { return ((l1->sens >= l2->sens) && ebitmap_contains(&l1->cat, &l2->cat)); } #define mls_level_incomp(l1, l2) \ (!mls_level_dom((l1), (l2)) && !mls_level_dom((l2), (l1))) #define mls_level_between(l1, l2, l3) \ (mls_level_dom((l1), (l2)) && mls_level_dom((l3), (l1))) #define mls_range_contains(r1, r2) \ (mls_level_dom(&(r2).level[0], &(r1).level[0]) && \ mls_level_dom(&(r1).level[1], &(r2).level[1])) static inline int mls_range_cpy(mls_range_t * dst, mls_range_t * src) { if (mls_level_cpy(&dst->level[0], &src->level[0]) < 0) goto err; if (mls_level_cpy(&dst->level[1], &src->level[1]) < 0) goto err_destroy; return 0; err_destroy: mls_level_destroy(&dst->level[0]); err: return -1; } static inline void mls_range_init(struct mls_range *r) { mls_level_init(&r->level[0]); mls_level_init(&r->level[1]); } static inline void mls_range_destroy(struct mls_range *r) { mls_level_destroy(&r->level[0]); mls_level_destroy(&r->level[1]); } static inline int mls_range_eq(struct mls_range *r1, struct mls_range *r2) { return (mls_level_eq(&r1->level[0], &r2->level[0]) && mls_level_eq(&r1->level[1], &r2->level[1])); } typedef struct mls_semantic_cat { uint32_t low; /* first bit this struct represents */ uint32_t high; /* last bit represented - equals low for a single cat */ struct mls_semantic_cat *next; } mls_semantic_cat_t; typedef struct mls_semantic_level { uint32_t sens; mls_semantic_cat_t *cat; } mls_semantic_level_t; typedef struct mls_semantic_range { mls_semantic_level_t level[2]; } mls_semantic_range_t; extern void mls_semantic_cat_init(mls_semantic_cat_t *c); extern void mls_semantic_cat_destroy(mls_semantic_cat_t *c); extern void mls_semantic_level_init(mls_semantic_level_t *l); extern void mls_semantic_level_destroy(mls_semantic_level_t *l); extern int mls_semantic_level_cpy(mls_semantic_level_t *dst, mls_semantic_level_t *src); extern void mls_semantic_range_init(mls_semantic_range_t *r); extern void mls_semantic_range_destroy(mls_semantic_range_t *r); extern int mls_semantic_range_cpy(mls_semantic_range_t *dst, mls_semantic_range_t *src); #ifdef __cplusplus } #endif #endif sepol/policydb/flask_types.h000064400000003363151027430550012177 0ustar00/* -*- linux-c -*- */ /* * Author : Stephen Smalley, */ #ifndef _SEPOL_POLICYDB_FLASK_TYPES_H_ #define _SEPOL_POLICYDB_FLASK_TYPES_H_ /* * The basic Flask types and constants. */ #include #include #ifdef __cplusplus extern "C" { #endif /* * A security context is a set of security attributes * associated with each subject and object controlled * by the security policy. The security context type * is defined as a variable-length string that can be * interpreted by any application or user with an * understanding of the security policy. */ typedef char *sepol_security_context_t; /* * An access vector (AV) is a collection of related permissions * for a pair of SIDs. The bits within an access vector * are interpreted differently depending on the class of * the object. The access vector interpretations are specified * in flask/access_vectors, and the corresponding constants * for permissions are defined in the automatically generated * header file av_permissions.h. */ typedef uint32_t sepol_access_vector_t; /* * Each object class is identified by a fixed-size value. * The set of security classes is specified in flask/security_classes, * with the corresponding constants defined in the automatically * generated header file flask.h. */ typedef uint16_t sepol_security_class_t; #define SEPOL_SECCLASS_NULL 0x0000 /* no class */ #define SELINUX_MAGIC 0xf97cff8c #define SELINUX_MOD_MAGIC 0xf97cff8d typedef uint32_t sepol_security_id_t; #define SEPOL_SECSID_NULL 0 struct sepol_av_decision { sepol_access_vector_t allowed; sepol_access_vector_t decided; sepol_access_vector_t auditallow; sepol_access_vector_t auditdeny; uint32_t seqno; }; #ifdef __cplusplus } #endif #endif sepol/policydb/flask.h000064400000011600151027430550010744 0ustar00/* This file is automatically generated. Do not edit. */ #ifndef _SEPOL_POLICYDB_FLASK_H_ #define _SEPOL_POLICYDB_FLASK_H_ /* * Security object class definitions */ #define SECCLASS_SECURITY 1 #define SECCLASS_PROCESS 2 #define SECCLASS_SYSTEM 3 #define SECCLASS_CAPABILITY 4 #define SECCLASS_FILESYSTEM 5 #define SECCLASS_FILE 6 #define SECCLASS_DIR 7 #define SECCLASS_FD 8 #define SECCLASS_LNK_FILE 9 #define SECCLASS_CHR_FILE 10 #define SECCLASS_BLK_FILE 11 #define SECCLASS_SOCK_FILE 12 #define SECCLASS_FIFO_FILE 13 #define SECCLASS_SOCKET 14 #define SECCLASS_TCP_SOCKET 15 #define SECCLASS_UDP_SOCKET 16 #define SECCLASS_RAWIP_SOCKET 17 #define SECCLASS_NODE 18 #define SECCLASS_NETIF 19 #define SECCLASS_NETLINK_SOCKET 20 #define SECCLASS_PACKET_SOCKET 21 #define SECCLASS_KEY_SOCKET 22 #define SECCLASS_UNIX_STREAM_SOCKET 23 #define SECCLASS_UNIX_DGRAM_SOCKET 24 #define SECCLASS_SEM 25 #define SECCLASS_MSG 26 #define SECCLASS_MSGQ 27 #define SECCLASS_SHM 28 #define SECCLASS_IPC 29 #define SECCLASS_PASSWD 30 #define SECCLASS_DRAWABLE 31 #define SECCLASS_WINDOW 32 #define SECCLASS_GC 33 #define SECCLASS_FONT 34 #define SECCLASS_COLORMAP 35 #define SECCLASS_PROPERTY 36 #define SECCLASS_CURSOR 37 #define SECCLASS_XCLIENT 38 #define SECCLASS_XINPUT 39 #define SECCLASS_XSERVER 40 #define SECCLASS_XEXTENSION 41 #define SECCLASS_PAX 42 #define SECCLASS_NETLINK_ROUTE_SOCKET 43 #define SECCLASS_NETLINK_FIREWALL_SOCKET 44 #define SECCLASS_NETLINK_TCPDIAG_SOCKET 45 #define SECCLASS_NETLINK_NFLOG_SOCKET 46 #define SECCLASS_NETLINK_XFRM_SOCKET 47 #define SECCLASS_NETLINK_SELINUX_SOCKET 48 #define SECCLASS_NETLINK_AUDIT_SOCKET 49 #define SECCLASS_NETLINK_IP6FW_SOCKET 50 #define SECCLASS_NETLINK_DNRT_SOCKET 51 #define SECCLASS_DBUS 52 /* * Security identifier indices for initial entities */ #define SECINITSID_KERNEL 1 #define SECINITSID_SECURITY 2 #define SECINITSID_UNLABELED 3 #define SECINITSID_FS 4 #define SECINITSID_FILE 5 #define SECINITSID_FILE_LABELS 6 #define SECINITSID_INIT 7 #define SECINITSID_ANY_SOCKET 8 #define SECINITSID_PORT 9 #define SECINITSID_NETIF 10 #define SECINITSID_NETMSG 11 #define SECINITSID_NODE 12 #define SECINITSID_IGMP_PACKET 13 #define SECINITSID_ICMP_SOCKET 14 #define SECINITSID_TCP_SOCKET 15 #define SECINITSID_SYSCTL_MODPROBE 16 #define SECINITSID_SYSCTL 17 #define SECINITSID_SYSCTL_FS 18 #define SECINITSID_SYSCTL_KERNEL 19 #define SECINITSID_SYSCTL_NET 20 #define SECINITSID_SYSCTL_NET_UNIX 21 #define SECINITSID_SYSCTL_VM 22 #define SECINITSID_SYSCTL_DEV 23 #define SECINITSID_KMOD 24 #define SECINITSID_POLICY 25 #define SECINITSID_SCMP_PACKET 26 #define SECINITSID_DEVNULL 27 #define SECINITSID_NUM 27 #endif sepol/policydb/util.h000064400000002665151027430550010634 0ustar00/* Authors: Karl MacMillan * * A set of utility functions that aid policy decision when dealing * with hierarchal namespaces. * * Copyright (C) 2006 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __SEPOL_UTIL_H__ #define __SEPOL_UTIL_H__ #ifdef __cplusplus extern "C" { #endif extern int add_i_to_a(uint32_t i, uint32_t * cnt, uint32_t ** a); extern char *sepol_av_to_string(policydb_t * policydbp, uint32_t tclass, sepol_access_vector_t av); char *sepol_extended_perms_to_string(avtab_extended_perms_t *xperms); /* * The tokenize function may be used to * replace sscanf */ extern int tokenize(char *line_buf, char delim, int num_args, ...); #ifdef __cplusplus } #endif #endif sepol/policydb/polcaps.h000064400000001321151027430550011304 0ustar00#ifndef _SEPOL_POLICYDB_POLCAPS_H_ #define _SEPOL_POLICYDB_POLCAPS_H_ #ifdef __cplusplus extern "C" { #endif /* Policy capabilities */ enum { POLICYDB_CAPABILITY_NETPEER, POLICYDB_CAPABILITY_OPENPERM, POLICYDB_CAPABILITY_EXTSOCKCLASS, POLICYDB_CAPABILITY_ALWAYSNETWORK, POLICYDB_CAPABILITY_CGROUPSECLABEL, POLICYDB_CAPABILITY_NNP_NOSUID_TRANSITION, __POLICYDB_CAPABILITY_MAX }; #define POLICYDB_CAPABILITY_MAX (__POLICYDB_CAPABILITY_MAX - 1) /* Convert a capability name to number. */ extern int sepol_polcap_getnum(const char *name); /* Convert a capability number to name. */ extern const char *sepol_polcap_getname(unsigned int capnum); #ifdef __cplusplus } #endif #endif /* _SEPOL_POLICYDB_POLCAPS_H_ */ sepol/policydb/module.h000064400000002774151027430550011145 0ustar00/* Author: Karl MacMillan * * Copyright (C) 2004-2005 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SEPOL_POLICYDB_MODULE_H_ #define _SEPOL_POLICYDB_MODULE_H_ #include #include #include #include #include #define SEPOL_MODULE_PACKAGE_MAGIC 0xf97cff8f #ifdef __cplusplus extern "C" { #endif struct sepol_module_package { sepol_policydb_t *policy; uint32_t version; char *file_contexts; size_t file_contexts_len; char *seusers; size_t seusers_len; char *user_extra; size_t user_extra_len; char *netfilter_contexts; size_t netfilter_contexts_len; }; extern int sepol_module_package_init(sepol_module_package_t * p); #ifdef __cplusplus } #endif #endif sepol/policydb/conditional.h000064400000011175151027430550012156 0ustar00/* Authors: Karl MacMillan * Frank Mayer * * Copyright (C) 2003 - 2005 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SEPOL_POLICYDB_CONDITIONAL_H_ #define _SEPOL_POLICYDB_CONDITIONAL_H_ #include #include #include #include #ifdef __cplusplus extern "C" { #endif #define COND_EXPR_MAXDEPTH 10 /* this is the max unique bools in a conditional expression * for which we precompute all outcomes for the expression. * * NOTE - do _NOT_ use value greater than 5 because * cond_node_t->expr_pre_comp can only hold at most 32 values */ #define COND_MAX_BOOLS 5 /* * A conditional expression is a list of operators and operands * in reverse polish notation. */ typedef struct cond_expr { #define COND_BOOL 1 /* plain bool */ #define COND_NOT 2 /* !bool */ #define COND_OR 3 /* bool || bool */ #define COND_AND 4 /* bool && bool */ #define COND_XOR 5 /* bool ^ bool */ #define COND_EQ 6 /* bool == bool */ #define COND_NEQ 7 /* bool != bool */ #define COND_LAST COND_NEQ uint32_t expr_type; uint32_t bool; struct cond_expr *next; } cond_expr_t; /* * Each cond_node_t contains a list of rules to be enabled/disabled * depending on the current value of the conditional expression. This * struct is for that list. */ typedef struct cond_av_list { avtab_ptr_t node; struct cond_av_list *next; } cond_av_list_t; /* * A cond node represents a conditional block in a policy. It * contains a conditional expression, the current state of the expression, * two lists of rules to enable/disable depending on the value of the * expression (the true list corresponds to if and the false list corresponds * to else).. */ typedef struct cond_node { int cur_state; cond_expr_t *expr; /* these true/false lists point into te_avtab when that is used */ cond_av_list_t *true_list; cond_av_list_t *false_list; /* and these are used during parsing and for modules */ avrule_t *avtrue_list; avrule_t *avfalse_list; /* these fields are not written to binary policy */ unsigned int nbools; uint32_t bool_ids[COND_MAX_BOOLS]; uint32_t expr_pre_comp; struct cond_node *next; /* a tunable conditional, calculated and used at expansion */ #define COND_NODE_FLAGS_TUNABLE 0x01 uint32_t flags; } cond_node_t; extern int cond_evaluate_expr(policydb_t * p, cond_expr_t * expr); extern cond_expr_t *cond_copy_expr(cond_expr_t * expr); extern int cond_expr_equal(cond_node_t * a, cond_node_t * b); extern int cond_normalize_expr(policydb_t * p, cond_node_t * cn); extern void cond_node_destroy(cond_node_t * node); extern void cond_expr_destroy(cond_expr_t * expr); extern cond_node_t *cond_node_find(policydb_t * p, cond_node_t * needle, cond_node_t * haystack, int *was_created); extern cond_node_t *cond_node_create(policydb_t * p, cond_node_t * node); extern cond_node_t *cond_node_search(policydb_t * p, cond_node_t * list, cond_node_t * cn); extern int evaluate_conds(policydb_t * p); extern avtab_datum_t *cond_av_list_search(avtab_key_t * key, cond_av_list_t * cond_list); extern void cond_av_list_destroy(cond_av_list_t * list); extern void cond_optimize_lists(cond_list_t * cl); extern int cond_policydb_init(policydb_t * p); extern void cond_policydb_destroy(policydb_t * p); extern void cond_list_destroy(cond_list_t * list); extern int cond_init_bool_indexes(policydb_t * p); extern int cond_destroy_bool(hashtab_key_t key, hashtab_datum_t datum, void *p); extern int cond_index_bool(hashtab_key_t key, hashtab_datum_t datum, void *datap); extern int cond_read_bool(policydb_t * p, hashtab_t h, struct policy_file *fp); extern int cond_read_list(policydb_t * p, cond_list_t ** list, void *fp); extern void cond_compute_av(avtab_t * ctab, avtab_key_t * key, struct sepol_av_decision *avd); #ifdef __cplusplus } #endif #endif /* _CONDITIONAL_H_ */ sepol/policydb/ebitmap.h000064400000006150151027430550011271 0ustar00/* Author : Stephen Smalley, */ /* FLASK */ /* * An extensible bitmap is a bitmap that supports an * arbitrary number of bits. Extensible bitmaps are * used to represent sets of values, such as types, * roles, categories, and classes. * * Each extensible bitmap is implemented as a linked * list of bitmap nodes, where each bitmap node has * an explicitly specified starting bit position within * the total bitmap. */ #ifndef _SEPOL_POLICYDB_EBITMAP_H_ #define _SEPOL_POLICYDB_EBITMAP_H_ #include #include #ifdef __cplusplus extern "C" { #endif #define MAPTYPE uint64_t /* portion of bitmap in each node */ #define MAPSIZE (sizeof(MAPTYPE) * 8) /* number of bits in node bitmap */ #define MAPBIT 1ULL /* a bit in the node bitmap */ typedef struct ebitmap_node { uint32_t startbit; /* starting position in the total bitmap */ MAPTYPE map; /* this node's portion of the bitmap */ struct ebitmap_node *next; } ebitmap_node_t; typedef struct ebitmap { ebitmap_node_t *node; /* first node in the bitmap */ uint32_t highbit; /* highest position in the total bitmap */ } ebitmap_t; #define ebitmap_length(e) ((e)->highbit) #define ebitmap_startbit(e) ((e)->node ? (e)->node->startbit : 0) #define ebitmap_startnode(e) ((e)->node) static inline unsigned int ebitmap_start(const ebitmap_t * e, ebitmap_node_t ** n) { *n = e->node; return ebitmap_startbit(e); } static inline void ebitmap_init(ebitmap_t * e) { memset(e, 0, sizeof(*e)); } static inline unsigned int ebitmap_next(ebitmap_node_t ** n, unsigned int bit) { if ((bit == ((*n)->startbit + MAPSIZE - 1)) && (*n)->next) { *n = (*n)->next; return (*n)->startbit; } return (bit + 1); } static inline int ebitmap_node_get_bit(ebitmap_node_t * n, unsigned int bit) { if (n->map & (MAPBIT << (bit - n->startbit))) return 1; return 0; } #define ebitmap_for_each_bit(e, n, bit) \ for (bit = ebitmap_start(e, &n); bit < ebitmap_length(e); bit = ebitmap_next(&n, bit)) \ extern int ebitmap_cmp(const ebitmap_t * e1, const ebitmap_t * e2); extern int ebitmap_or(ebitmap_t * dst, const ebitmap_t * e1, const ebitmap_t * e2); extern int ebitmap_union(ebitmap_t * dst, const ebitmap_t * e1); extern int ebitmap_and(ebitmap_t *dst, ebitmap_t *e1, ebitmap_t *e2); extern int ebitmap_xor(ebitmap_t *dst, ebitmap_t *e1, ebitmap_t *e2); extern int ebitmap_not(ebitmap_t *dst, ebitmap_t *e1, unsigned int maxbit); extern int ebitmap_andnot(ebitmap_t *dst, ebitmap_t *e1, ebitmap_t *e2, unsigned int maxbit); extern unsigned int ebitmap_cardinality(ebitmap_t *e1); extern int ebitmap_hamming_distance(ebitmap_t * e1, ebitmap_t * e2); extern int ebitmap_cpy(ebitmap_t * dst, const ebitmap_t * src); extern int ebitmap_contains(const ebitmap_t * e1, const ebitmap_t * e2); extern int ebitmap_match_any(const ebitmap_t *e1, const ebitmap_t *e2); extern int ebitmap_get_bit(const ebitmap_t * e, unsigned int bit); extern int ebitmap_set_bit(ebitmap_t * e, unsigned int bit, int value); extern void ebitmap_destroy(ebitmap_t * e); extern int ebitmap_read(ebitmap_t * e, void *fp); #ifdef __cplusplus } #endif #endif /* _EBITMAP_H_ */ /* FLASK */ sepol/policydb/avrule_block.h000064400000003145151027430550012321 0ustar00/* Authors: Jason Tang * * Copyright (C) 2005 Tresys Technology, LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SEPOL_AVRULE_BLOCK_H_ #define _SEPOL_AVRULE_BLOCK_H_ #include #ifdef __cplusplus extern "C" { #endif extern avrule_block_t *avrule_block_create(void); extern void avrule_block_destroy(avrule_block_t * x); extern avrule_decl_t *avrule_decl_create(uint32_t decl_id); extern void avrule_decl_destroy(avrule_decl_t * x); extern void avrule_block_list_destroy(avrule_block_t * x); extern avrule_decl_t *get_avrule_decl(policydb_t * p, uint32_t decl_id); extern cond_list_t *get_decl_cond_list(policydb_t * p, avrule_decl_t * decl, cond_list_t * cond); extern int is_id_enabled(char *id, policydb_t * p, int symbol_table); extern int is_perm_enabled(char *class_id, char *perm_id, policydb_t * p); #ifdef __cplusplus } #endif #endif sepol/context.h000064400000001360151027430550007525 0ustar00#ifndef _SEPOL_CONTEXT_H_ #define _SEPOL_CONTEXT_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* -- Deprecated -- */ extern int sepol_check_context(const char *context); /* -- End deprecated -- */ extern int sepol_context_check(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_context_t * context); extern int sepol_mls_contains(sepol_handle_t * handle, const sepol_policydb_t * policydb, const char *mls1, const char *mls2, int *response); extern int sepol_mls_check(sepol_handle_t * handle, const sepol_policydb_t * policydb, const char *mls); #ifdef __cplusplus } #endif #endif sepol/users.h000064400000003747151027430550007215 0ustar00#ifndef _SEPOL_USERS_H_ #define _SEPOL_USERS_H_ #include #include #include #include #ifdef __cplusplus extern "C" { #endif /*---------compatibility------------*/ /* Given an existing binary policy (starting at 'data with length 'len') and user configurations living in 'usersdir', generate a new binary policy for the new user configurations. Sets '*newdata' and '*newlen' to refer to the new binary policy image. */ extern int sepol_genusers(void *data, size_t len, const char *usersdir, void **newdata, size_t * newlen); /* Enable or disable deletion of users by sepol_genusers(3) when a user in original binary policy image is not defined by the new user configurations. Defaults to disabled. */ extern void sepol_set_delusers(int on); /*--------end compatibility----------*/ /* Modify the user, or add it, if the key is not found */ extern int sepol_user_modify(sepol_handle_t * handle, sepol_policydb_t * policydb, const sepol_user_key_t * key, const sepol_user_t * data); /* Return the number of users */ extern int sepol_user_count(sepol_handle_t * handle, const sepol_policydb_t * p, unsigned int *response); /* Check if the specified user exists */ extern int sepol_user_exists(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_user_key_t * key, int *response); /* Query a user - returns the user or NULL if not found */ extern int sepol_user_query(sepol_handle_t * handle, const sepol_policydb_t * p, const sepol_user_key_t * key, sepol_user_t ** response); /* Iterate the users * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_user_iterate(sepol_handle_t * handle, const sepol_policydb_t * policydb, int (*fn) (const sepol_user_t * user, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/boolean_record.h000064400000003017151027430550011017 0ustar00#ifndef _SEPOL_BOOLEAN_RECORD_H_ #define _SEPOL_BOOLEAN_RECORD_H_ #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_bool; struct sepol_bool_key; typedef struct sepol_bool sepol_bool_t; typedef struct sepol_bool_key sepol_bool_key_t; /* Key */ extern int sepol_bool_key_create(sepol_handle_t * handle, const char *name, sepol_bool_key_t ** key); extern void sepol_bool_key_unpack(const sepol_bool_key_t * key, const char **name); extern int sepol_bool_key_extract(sepol_handle_t * handle, const sepol_bool_t * boolean, sepol_bool_key_t ** key_ptr); extern void sepol_bool_key_free(sepol_bool_key_t * key); extern int sepol_bool_compare(const sepol_bool_t * boolean, const sepol_bool_key_t * key); extern int sepol_bool_compare2(const sepol_bool_t * boolean, const sepol_bool_t * boolean2); /* Name */ extern const char *sepol_bool_get_name(const sepol_bool_t * boolean); extern int sepol_bool_set_name(sepol_handle_t * handle, sepol_bool_t * boolean, const char *name); /* Value */ extern int sepol_bool_get_value(const sepol_bool_t * boolean); extern void sepol_bool_set_value(sepol_bool_t * boolean, int value); /* Create/Clone/Destroy */ extern int sepol_bool_create(sepol_handle_t * handle, sepol_bool_t ** bool_ptr); extern int sepol_bool_clone(sepol_handle_t * handle, const sepol_bool_t * boolean, sepol_bool_t ** bool_ptr); extern void sepol_bool_free(sepol_bool_t * boolean); #ifdef __cplusplus } #endif #endif sepol/ibpkeys.h000064400000002503151027430550007507 0ustar00#ifndef _SEPOL_IBPKEYS_H_ #define _SEPOL_IBPKEYS_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Return the number of ibpkeys */ extern int sepol_ibpkey_count(sepol_handle_t *handle, const sepol_policydb_t *p, unsigned int *response); /* Check if a ibpkey exists */ extern int sepol_ibpkey_exists(sepol_handle_t *handle, const sepol_policydb_t *policydb, const sepol_ibpkey_key_t *key, int *response); /* Query a ibpkey - returns the ibpkey, or NULL if not found */ extern int sepol_ibpkey_query(sepol_handle_t *handle, const sepol_policydb_t *policydb, const sepol_ibpkey_key_t *key, sepol_ibpkey_t **response); /* Modify a ibpkey, or add it, if the key is not found */ extern int sepol_ibpkey_modify(sepol_handle_t *handle, sepol_policydb_t *policydb, const sepol_ibpkey_key_t *key, const sepol_ibpkey_t *data); /* Iterate the ibpkeys * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_ibpkey_iterate(sepol_handle_t *handle, const sepol_policydb_t *policydb, int (*fn)(const sepol_ibpkey_t *ibpkey, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/ibendports.h000064400000002553151027430550010217 0ustar00#ifndef _SEPOL_IBENDPORTS_H_ #define _SEPOL_IBENDPORTS_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Return the number of ibendports */ extern int sepol_ibendport_count(sepol_handle_t *handle, const sepol_policydb_t *p, unsigned int *response); /* Check if a ibendport exists */ extern int sepol_ibendport_exists(sepol_handle_t *handle, const sepol_policydb_t *policydb, const sepol_ibendport_key_t *key, int *response); /* Query a ibendport - returns the ibendport, or NULL if not found */ extern int sepol_ibendport_query(sepol_handle_t *handle, const sepol_policydb_t *policydb, const sepol_ibendport_key_t *key, sepol_ibendport_t **response); /* Modify a ibendport, or add it, if the key is not found */ extern int sepol_ibendport_modify(sepol_handle_t *handle, sepol_policydb_t *policydb, const sepol_ibendport_key_t *key, const sepol_ibendport_t *data); /* Iterate the ibendports * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_ibendport_iterate(sepol_handle_t *handle, const sepol_policydb_t *policydb, int (*fn)(const sepol_ibendport_t *ibendport, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/module.h000064400000005170151027430550007331 0ustar00#ifndef _SEPOL_MODULE_H_ #define _SEPOL_MODULE_H_ #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_module_package; typedef struct sepol_module_package sepol_module_package_t; /* Module package public interfaces. */ extern int sepol_module_package_create(sepol_module_package_t ** p); extern void sepol_module_package_free(sepol_module_package_t * p); extern char *sepol_module_package_get_file_contexts(sepol_module_package_t * p); extern size_t sepol_module_package_get_file_contexts_len(sepol_module_package_t * p); extern int sepol_module_package_set_file_contexts(sepol_module_package_t * p, char *data, size_t len); extern char *sepol_module_package_get_seusers(sepol_module_package_t * p); extern size_t sepol_module_package_get_seusers_len(sepol_module_package_t * p); extern int sepol_module_package_set_seusers(sepol_module_package_t * p, char *data, size_t len); extern char *sepol_module_package_get_user_extra(sepol_module_package_t * p); extern size_t sepol_module_package_get_user_extra_len(sepol_module_package_t * p); extern int sepol_module_package_set_user_extra(sepol_module_package_t * p, char *data, size_t len); extern char *sepol_module_package_get_netfilter_contexts(sepol_module_package_t * p); extern size_t sepol_module_package_get_netfilter_contexts_len(sepol_module_package_t * p); extern int sepol_module_package_set_netfilter_contexts(sepol_module_package_t * p, char *data, size_t len); extern sepol_policydb_t *sepol_module_package_get_policy(sepol_module_package_t * p); extern int sepol_link_packages(sepol_handle_t * handle, sepol_module_package_t * base, sepol_module_package_t ** modules, int num_modules, int verbose); extern int sepol_module_package_read(sepol_module_package_t * mod, struct sepol_policy_file *file, int verbose); extern int sepol_module_package_info(struct sepol_policy_file *file, int *type, char **name, char **version); extern int sepol_module_package_write(sepol_module_package_t * p, struct sepol_policy_file *file); /* Module linking/expanding public interfaces. */ extern int sepol_link_modules(sepol_handle_t * handle, sepol_policydb_t * base, sepol_policydb_t ** modules, size_t len, int verbose); extern int sepol_expand_module(sepol_handle_t * handle, sepol_policydb_t * base, sepol_policydb_t * out, int verbose, int check); #ifdef __cplusplus } #endif #endif sepol/node_record.h000064400000005366151027430550010336 0ustar00#ifndef _SEPOL_NODE_RECORD_H_ #define _SEPOL_NODE_RECORD_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_node; struct sepol_node_key; typedef struct sepol_node sepol_node_t; typedef struct sepol_node_key sepol_node_key_t; #define SEPOL_PROTO_IP4 0 #define SEPOL_PROTO_IP6 1 /* Key */ extern int sepol_node_compare(const sepol_node_t * node, const sepol_node_key_t * key); extern int sepol_node_compare2(const sepol_node_t * node, const sepol_node_t * node2); extern int sepol_node_key_create(sepol_handle_t * handle, const char *addr, const char *mask, int proto, sepol_node_key_t ** key_ptr); extern void sepol_node_key_unpack(const sepol_node_key_t * key, const char **addr, const char **mask, int *proto); extern int sepol_node_key_extract(sepol_handle_t * handle, const sepol_node_t * node, sepol_node_key_t ** key_ptr); extern void sepol_node_key_free(sepol_node_key_t * key); /* Address */ extern int sepol_node_get_addr(sepol_handle_t * handle, const sepol_node_t * node, char **addr); extern int sepol_node_get_addr_bytes(sepol_handle_t * handle, const sepol_node_t * node, char **addr, size_t * addr_sz); extern int sepol_node_set_addr(sepol_handle_t * handle, sepol_node_t * node, int proto, const char *addr); extern int sepol_node_set_addr_bytes(sepol_handle_t * handle, sepol_node_t * node, const char *addr, size_t addr_sz); /* Netmask */ extern int sepol_node_get_mask(sepol_handle_t * handle, const sepol_node_t * node, char **mask); extern int sepol_node_get_mask_bytes(sepol_handle_t * handle, const sepol_node_t * node, char **mask, size_t * mask_sz); extern int sepol_node_set_mask(sepol_handle_t * handle, sepol_node_t * node, int proto, const char *mask); extern int sepol_node_set_mask_bytes(sepol_handle_t * handle, sepol_node_t * node, const char *mask, size_t mask_sz); /* Protocol */ extern int sepol_node_get_proto(const sepol_node_t * node); extern void sepol_node_set_proto(sepol_node_t * node, int proto); extern const char *sepol_node_get_proto_str(int proto); /* Context */ extern sepol_context_t *sepol_node_get_con(const sepol_node_t * node); extern int sepol_node_set_con(sepol_handle_t * handle, sepol_node_t * node, sepol_context_t * con); /* Create/Clone/Destroy */ extern int sepol_node_create(sepol_handle_t * handle, sepol_node_t ** node_ptr); extern int sepol_node_clone(sepol_handle_t * handle, const sepol_node_t * node, sepol_node_t ** node_ptr); extern void sepol_node_free(sepol_node_t * node); #ifdef __cplusplus } #endif #endif sepol/errcodes.h000064400000001523151027430550007650 0ustar00/* Author: Karl MacMillan */ #ifndef __sepol_errno_h__ #define __sepol_errno_h__ #include #ifdef __cplusplus extern "C" { #endif #define SEPOL_OK 0 /* These first error codes are defined for compatibility with * previous version of libsepol. In the future, custom error * codes that don't map to system error codes should be defined * outside of the range of system error codes. */ #define SEPOL_ERR -1 #define SEPOL_ENOTSUP -2 /* feature not supported in module language */ #define SEPOL_EREQ -3 /* requirements not met */ /* Error codes that map to system error codes */ #define SEPOL_ENOMEM -ENOMEM #define SEPOL_ERANGE -ERANGE #define SEPOL_EEXIST -EEXIST #define SEPOL_ENOENT -ENOENT #ifdef __cplusplus } #endif #endif sepol/user_record.h000064400000004520151027430550010356 0ustar00#ifndef _SEPOL_USER_RECORD_H_ #define _SEPOL_USER_RECORD_H_ #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_user; struct sepol_user_key; typedef struct sepol_user sepol_user_t; typedef struct sepol_user_key sepol_user_key_t; /* Key */ extern int sepol_user_key_create(sepol_handle_t * handle, const char *name, sepol_user_key_t ** key); extern void sepol_user_key_unpack(const sepol_user_key_t * key, const char **name); extern int sepol_user_key_extract(sepol_handle_t * handle, const sepol_user_t * user, sepol_user_key_t ** key_ptr); extern void sepol_user_key_free(sepol_user_key_t * key); extern int sepol_user_compare(const sepol_user_t * user, const sepol_user_key_t * key); extern int sepol_user_compare2(const sepol_user_t * user, const sepol_user_t * user2); /* Name */ extern const char *sepol_user_get_name(const sepol_user_t * user); extern int sepol_user_set_name(sepol_handle_t * handle, sepol_user_t * user, const char *name); /* MLS */ extern const char *sepol_user_get_mlslevel(const sepol_user_t * user); extern int sepol_user_set_mlslevel(sepol_handle_t * handle, sepol_user_t * user, const char *mls_level); extern const char *sepol_user_get_mlsrange(const sepol_user_t * user); extern int sepol_user_set_mlsrange(sepol_handle_t * handle, sepol_user_t * user, const char *mls_range); /* Role management */ extern int sepol_user_get_num_roles(const sepol_user_t * user); extern int sepol_user_add_role(sepol_handle_t * handle, sepol_user_t * user, const char *role); extern void sepol_user_del_role(sepol_user_t * user, const char *role); extern int sepol_user_has_role(const sepol_user_t * user, const char *role); extern int sepol_user_get_roles(sepol_handle_t * handle, const sepol_user_t * user, const char ***roles_arr, unsigned int *num_roles); extern int sepol_user_set_roles(sepol_handle_t * handle, sepol_user_t * user, const char **roles_arr, unsigned int num_roles); /* Create/Clone/Destroy */ extern int sepol_user_create(sepol_handle_t * handle, sepol_user_t ** user_ptr); extern int sepol_user_clone(sepol_handle_t * handle, const sepol_user_t * user, sepol_user_t ** user_ptr); extern void sepol_user_free(sepol_user_t * user); #ifdef __cplusplus } #endif #endif sepol/ports.h000064400000002440151027430550007210 0ustar00#ifndef _SEPOL_PORTS_H_ #define _SEPOL_PORTS_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Return the number of ports */ extern int sepol_port_count(sepol_handle_t * handle, const sepol_policydb_t * p, unsigned int *response); /* Check if a port exists */ extern int sepol_port_exists(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_port_key_t * key, int *response); /* Query a port - returns the port, or NULL if not found */ extern int sepol_port_query(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_port_key_t * key, sepol_port_t ** response); /* Modify a port, or add it, if the key is not found */ extern int sepol_port_modify(sepol_handle_t * handle, sepol_policydb_t * policydb, const sepol_port_key_t * key, const sepol_port_t * data); /* Iterate the ports * The handler may return: * -1 to signal an error condition, * 1 to signal successful exit * 0 to signal continue */ extern int sepol_port_iterate(sepol_handle_t * handle, const sepol_policydb_t * policydb, int (*fn) (const sepol_port_t * port, void *fn_arg), void *arg); #ifdef __cplusplus } #endif #endif sepol/sepol.h000064400000001536151027430550007170 0ustar00#ifndef _SEPOL_H_ #define _SEPOL_H_ #include #include #ifdef __cplusplus extern "C" { #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* Set internal policydb from a file for subsequent service calls. */ extern int sepol_set_policydb_from_file(FILE * fp); #ifdef __cplusplus } #endif #endif sepol/kernel_to_conf.h000064400000000176151027430550011034 0ustar00#include #include int sepol_kernel_policydb_to_conf(FILE *fp, struct policydb *pdb); sepol/ibendport_record.h000064400000004206151027430550011367 0ustar00#ifndef _SEPOL_IBENDPORT_RECORD_H_ #define _SEPOL_IBENDPORT_RECORD_H_ #include #include #include #ifdef __cplusplus extern "C" { #endif struct sepol_ibendport; struct sepol_ibendport_key; typedef struct sepol_ibendport sepol_ibendport_t; typedef struct sepol_ibendport_key sepol_ibendport_key_t; extern int sepol_ibendport_compare(const sepol_ibendport_t *ibendport, const sepol_ibendport_key_t *key); extern int sepol_ibendport_compare2(const sepol_ibendport_t *ibendport, const sepol_ibendport_t *ibendport2); extern int sepol_ibendport_key_create(sepol_handle_t *handle, const char *ibdev_name, int port, sepol_ibendport_key_t **key_ptr); extern void sepol_ibendport_key_unpack(const sepol_ibendport_key_t *key, const char **ibdev_name, int *port); extern int sepol_ibendport_alloc_ibdev_name(sepol_handle_t *handle, char **ibdev_name); extern int sepol_ibendport_key_extract(sepol_handle_t *handle, const sepol_ibendport_t *ibendport, sepol_ibendport_key_t **key_ptr); extern void sepol_ibendport_key_free(sepol_ibendport_key_t *key); extern void sepol_ibendport_set_port(sepol_ibendport_t *ibendport, int port); extern int sepol_ibendport_get_port(const sepol_ibendport_t *ibendport); extern int sepol_ibendport_get_ibdev_name(sepol_handle_t *handle, const sepol_ibendport_t *ibendport, char **ibdev_name); extern int sepol_ibendport_set_ibdev_name(sepol_handle_t *handle, sepol_ibendport_t *ibendport, const char *ibdev_name); extern sepol_context_t *sepol_ibendport_get_con(const sepol_ibendport_t *ibendport); extern int sepol_ibendport_set_con(sepol_handle_t *handle, sepol_ibendport_t *ibendport, sepol_context_t *con); extern int sepol_ibendport_create(sepol_handle_t *handle, sepol_ibendport_t **ibendport_ptr); extern int sepol_ibendport_clone(sepol_handle_t *handle, const sepol_ibendport_t *ibendport, sepol_ibendport_t **ibendport_ptr); extern void sepol_ibendport_free(sepol_ibendport_t *ibendport); #ifdef __cplusplus } #endif #endif sepol/ibpkey_record.h000064400000004375151027430550010673 0ustar00#ifndef _SEPOL_IBPKEY_RECORD_H_ #define _SEPOL_IBPKEY_RECORD_H_ #include #include #include #include #define INET6_ADDRLEN 16 #ifdef __cplusplus extern "C" { #endif struct sepol_ibpkey; struct sepol_ibpkey_key; typedef struct sepol_ibpkey sepol_ibpkey_t; typedef struct sepol_ibpkey_key sepol_ibpkey_key_t; extern int sepol_ibpkey_compare(const sepol_ibpkey_t *ibpkey, const sepol_ibpkey_key_t *key); extern int sepol_ibpkey_compare2(const sepol_ibpkey_t *ibpkey, const sepol_ibpkey_t *ibpkey2); extern int sepol_ibpkey_key_create(sepol_handle_t *handle, const char *subnet_prefix, int low, int high, sepol_ibpkey_key_t **key_ptr); extern void sepol_ibpkey_key_unpack(const sepol_ibpkey_key_t *key, uint64_t *subnet_prefix, int *low, int *high); extern int sepol_ibpkey_key_extract(sepol_handle_t *handle, const sepol_ibpkey_t *ibpkey, sepol_ibpkey_key_t **key_ptr); extern void sepol_ibpkey_key_free(sepol_ibpkey_key_t *key); extern int sepol_ibpkey_get_low(const sepol_ibpkey_t *ibpkey); extern int sepol_ibpkey_get_high(const sepol_ibpkey_t *ibpkey); extern void sepol_ibpkey_set_pkey(sepol_ibpkey_t *ibpkey, int pkey_num); extern void sepol_ibpkey_set_range(sepol_ibpkey_t *ibpkey, int low, int high); extern int sepol_ibpkey_get_subnet_prefix(sepol_handle_t *handle, const sepol_ibpkey_t *ibpkey, char **subnet_prefix); extern uint64_t sepol_ibpkey_get_subnet_prefix_bytes(const sepol_ibpkey_t *ibpkey); extern int sepol_ibpkey_set_subnet_prefix(sepol_handle_t *handle, sepol_ibpkey_t *ibpkey, const char *subnet_prefix); extern void sepol_ibpkey_set_subnet_prefix_bytes(sepol_ibpkey_t *ibpkey, uint64_t subnet_prefix); extern sepol_context_t *sepol_ibpkey_get_con(const sepol_ibpkey_t *ibpkey); extern int sepol_ibpkey_set_con(sepol_handle_t *handle, sepol_ibpkey_t *ibpkey, sepol_context_t *con); extern int sepol_ibpkey_create(sepol_handle_t *handle, sepol_ibpkey_t **ibpkey_ptr); extern int sepol_ibpkey_clone(sepol_handle_t *handle, const sepol_ibpkey_t *ibpkey, sepol_ibpkey_t **ibpkey_ptr); extern void sepol_ibpkey_free(sepol_ibpkey_t *ibpkey); #ifdef __cplusplus } #endif #endif sepol/handle.h000064400000002561151027430550007300 0ustar00#ifndef _SEPOL_HANDLE_H_ #define _SEPOL_HANDLE_H_ #ifdef __cplusplus extern "C" { #endif struct sepol_handle; typedef struct sepol_handle sepol_handle_t; /* Create and return a sepol handle. */ sepol_handle_t *sepol_handle_create(void); /* Get whether or not dontaudits will be disabled, same values as * specified by set_disable_dontaudit. This value reflects the state * your system will be set to upon commit, not necessarily its * current state.*/ int sepol_get_disable_dontaudit(sepol_handle_t * sh); /* Set whether or not to disable dontaudits, 0 is default and does * not disable dontaudits, 1 disables them */ void sepol_set_disable_dontaudit(sepol_handle_t * sh, int disable_dontaudit); /* Set whether module_expand() should consume the base policy passed in. * This should reduce the amount of memory required to expand the policy. */ void sepol_set_expand_consume_base(sepol_handle_t * sh, int consume_base); /* Destroy a sepol handle. */ void sepol_handle_destroy(sepol_handle_t *); /* Get whether or not needless unused branch of tunables would be preserved */ int sepol_get_preserve_tunables(sepol_handle_t * sh); /* Set whether or not to preserve the needless unused branch of tunables, * 0 is default and discard such branch, 1 preserves them */ void sepol_set_preserve_tunables(sepol_handle_t * sh, int preserve_tunables); #ifdef __cplusplus } #endif #endif sepol/debug.h000064400000001717151027430550007135 0ustar00#ifndef _SEPOL_DEBUG_H_ #define _SEPOL_DEBUG_H_ #include #ifdef __cplusplus extern "C" { #endif /* Deprecated */ extern void sepol_debug(int on); /* End deprecated */ #define SEPOL_MSG_ERR 1 #define SEPOL_MSG_WARN 2 #define SEPOL_MSG_INFO 3 extern int sepol_msg_get_level(sepol_handle_t * handle); extern const char *sepol_msg_get_channel(sepol_handle_t * handle); extern const char *sepol_msg_get_fname(sepol_handle_t * handle); /* Set the messaging callback. * By the default, the callback will print * the message on standard output, in a * particular format. Passing NULL here * indicates that messaging should be suppressed */ extern void sepol_msg_set_callback(sepol_handle_t * handle, #ifdef __GNUC__ __attribute__ ((format(printf, 3, 4))) #endif void (*msg_callback) (void *varg, sepol_handle_t * handle, const char *fmt, ...), void *msg_callback_arg); #ifdef __cplusplus } #endif #endif lastlog.h000064400000000176151027430550006370 0ustar00/* This header file is used in 4.3BSD to define `struct lastlog', which we define in . */ #include fmtmsg.h000064400000006247151027430550006225 0ustar00/* Message display handling. Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef __FMTMSG_H #define __FMTMSG_H 1 #include __BEGIN_DECLS /* Values to control `fmtmsg' function. */ enum { MM_HARD = 0x001, /* Source of the condition is hardware. */ #define MM_HARD MM_HARD MM_SOFT = 0x002, /* Source of the condition is software. */ #define MM_SOFT MM_SOFT MM_FIRM = 0x004, /* Source of the condition is firmware. */ #define MM_FIRM MM_FIRM MM_APPL = 0x008, /* Condition detected by application. */ #define MM_APPL MM_APPL MM_UTIL = 0x010, /* Condition detected by utility. */ #define MM_UTIL MM_UTIL MM_OPSYS = 0x020, /* Condition detected by operating system. */ #define MM_OPSYS MM_OPSYS MM_RECOVER = 0x040, /* Recoverable error. */ #define MM_RECOVER MM_RECOVER MM_NRECOV = 0x080, /* Non-recoverable error. */ #define MM_NRECOV MM_NRECOV MM_PRINT = 0x100, /* Display message in standard error. */ #define MM_PRINT MM_PRINT MM_CONSOLE = 0x200 /* Display message on system console. */ #define MM_CONSOLE MM_CONSOLE }; /* Values to be for SEVERITY parameter of `fmtmsg'. */ enum { MM_NOSEV = 0, /* No severity level provided for the message. */ #define MM_NOSEV MM_NOSEV MM_HALT, /* Error causing application to halt. */ #define MM_HALT MM_HALT MM_ERROR, /* Application has encountered a non-fatal fault. */ #define MM_ERROR MM_ERROR MM_WARNING, /* Application has detected unusual non-error condition. */ #define MM_WARNING MM_WARNING MM_INFO /* Informative message. */ #define MM_INFO MM_INFO }; /* Macros which can be used as null values for the arguments of `fmtmsg'. */ #define MM_NULLLBL ((char *) 0) #define MM_NULLSEV 0 #define MM_NULLMC ((long int) 0) #define MM_NULLTXT ((char *) 0) #define MM_NULLACT ((char *) 0) #define MM_NULLTAG ((char *) 0) /* Possible return values of `fmtmsg'. */ enum { MM_NOTOK = -1, #define MM_NOTOK MM_NOTOK MM_OK = 0, #define MM_OK MM_OK MM_NOMSG = 1, #define MM_NOMSG MM_NOMSG MM_NOCON = 4 #define MM_NOCON MM_NOCON }; /* Print message with given CLASSIFICATION, LABEL, SEVERITY, TEXT, ACTION and TAG to console or standard error. */ extern int fmtmsg (long int __classification, const char *__label, int __severity, const char *__text, const char *__action, const char *__tag); #ifdef __USE_MISC /* Add or remove severity level. */ extern int addseverity (int __severity, const char *__string) __THROW; #endif __END_DECLS #endif /* fmtmsg.h */ X11/DECkeysym.h000064400000005377151027430550007141 0ustar00/*********************************************************** Copyright 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1988 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * DEC private keysyms * (29th bit set) */ /* two-key compose sequence initiators, chosen to map to Latin1 characters */ #define DXK_ring_accent 0x1000FEB0 #define DXK_circumflex_accent 0x1000FE5E #define DXK_cedilla_accent 0x1000FE2C #define DXK_acute_accent 0x1000FE27 #define DXK_grave_accent 0x1000FE60 #define DXK_tilde 0x1000FE7E #define DXK_diaeresis 0x1000FE22 /* special keysym for LK2** "Remove" key on editing keypad */ #define DXK_Remove 0x1000FF00 /* Remove */ X11/Xw32defs.h000064400000003565151027430550006706 0ustar00#ifndef _XW32DEFS_H # define _XW32DEFS_H # ifdef __GNUC__ /* mingw is more close to unix than msvc */ # if !defined(__daddr_t_defined) typedef char *caddr_t; # endif # define lstat stat # else typedef char *caddr_t; # define access _access # define alloca _alloca # define chdir _chdir # define chmod _chmod # define close _close # define creat _creat # define dup _dup # define dup2 _dup2 # define environ _environ # define execl _execl # define execle _execle # define execlp _execlp # define execlpe _execlpe # define execv _execv # define execve _execve # define execvp _execvp # define execvpe _execvpe # define fdopen _fdopen # define fileno _fileno # define fstat _fstat # define getcwd _getcwd # define getpid _getpid # define hypot _hypot # define isascii __isascii # define isatty _isatty # define lseek _lseek # define mkdir _mkdir # define mktemp _mktemp # define open _open # define putenv _putenv # define read _read # define rmdir _rmdir # define sleep(x) Sleep((x) * 1000) # define stat _stat # define sys_errlist _sys_errlist # define sys_nerr _sys_nerr # define umask _umask # define unlink _unlink # define write _write # define random rand # define srandom srand # define O_RDONLY _O_RDONLY # define O_WRONLY _O_WRONLY # define O_RDWR _O_RDWR # define O_APPEND _O_APPEND # define O_CREAT _O_CREAT # define O_TRUNC _O_TRUNC # define O_EXCL _O_EXCL # define O_TEXT _O_TEXT # define O_BINARY _O_BINARY # define O_RAW _O_BINARY # define S_IFMT _S_IFMT # define S_IFDIR _S_IFDIR # define S_IFCHR _S_IFCHR # define S_IFREG _S_IFREG # define S_IREAD _S_IREAD # define S_IWRITE _S_IWRITE # define S_IEXEC _S_IEXEC # define F_OK 0 # define X_OK 1 # define W_OK 2 # define R_OK 4 # endif /* __GNUC__ */ #endif X11/Xlib-xcb.h000064400000000772151027430550006746 0ustar00/* Copyright (C) 2003-2006 Jamey Sharp, Josh Triplett * This file is licensed under the MIT license. See the file COPYING. */ #ifndef _X11_XLIB_XCB_H_ #define _X11_XLIB_XCB_H_ #include #include #include _XFUNCPROTOBEGIN xcb_connection_t *XGetXCBConnection(Display *dpy); enum XEventQueueOwner { XlibOwnsEventQueue = 0, XCBOwnsEventQueue }; void XSetEventQueueOwner(Display *dpy, enum XEventQueueOwner owner); _XFUNCPROTOEND #endif /* _X11_XLIB_XCB_H_ */ X11/Xlocale.h000064400000002421151027430550006656 0ustar00/* Copyright 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _X11_XLOCALE_H_ #define _X11_XLOCALE_H_ #include #include #include #endif /* _X11_XLOCALE_H_ */ X11/Xalloca.h000064400000010753151027430550006661 0ustar00/* Copyright 1995, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * The purpose of this header is to define the macros ALLOCATE_LOCAL and * DEALLOCATE_LOCAL appropriately for the platform being compiled on. * These macros are used to make fast, function-local memory allocations. * Their characteristics are as follows: * * void *ALLOCATE_LOCAL(size_t size) * Returns a pointer to size bytes of memory, or NULL if the allocation * failed. The memory must be freed with DEALLOCATE_LOCAL before the * function that made the allocation returns. You should not ask for * large blocks of memory with this function, since on many platforms * the memory comes from the stack, which may have limited size. * * void DEALLOCATE_LOCAL(void *) * Frees the memory allocated by ALLOCATE_LOCAL. Omission of this * step may be harmless on some platforms, but will result in * memory leaks or worse on others. * * Before including this file, you should define two macros, * ALLOCATE_LOCAL_FALLBACK and DEALLOCATE_LOCAL_FALLBACK, that have the * same characteristics as ALLOCATE_LOCAL and DEALLOCATE_LOCAL. The * header uses the fallbacks if it doesn't know a "better" way to define * ALLOCATE_LOCAL and DEALLOCATE_LOCAL. Typical usage would be: * * #define ALLOCATE_LOCAL_FALLBACK(_size) malloc(_size) * #define DEALLOCATE_LOCAL_FALLBACK(_ptr) free(_ptr) * #include "Xalloca.h" */ #ifndef XALLOCA_H #define XALLOCA_H 1 #ifndef INCLUDE_ALLOCA_H /* Need to add more here to match Imake *.cf's */ # if defined(HAVE_ALLOCA_H) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) # define INCLUDE_ALLOCA_H # endif #endif #ifdef INCLUDE_ALLOCA_H # include #endif #ifndef NO_ALLOCA /* * os-dependent definition of local allocation and deallocation * If you want something other than (DE)ALLOCATE_LOCAL_FALLBACK * for ALLOCATE/DEALLOCATE_LOCAL then you add that in here. */ # ifdef __GNUC__ # ifndef alloca # define alloca __builtin_alloca # endif /* !alloca */ # define ALLOCATE_LOCAL(size) alloca((size_t)(size)) # else /* ! __GNUC__ */ /* * warning: old mips alloca (pre 2.10) is unusable, new one is built in * Test is easy, the new one is named __builtin_alloca and comes * from alloca.h which #defines alloca. */ # if defined(__sun) || defined(alloca) /* * Some System V boxes extract alloca.o from /lib/libPW.a; if you * decide that you don't want to use alloca, you might want to fix it here. */ /* alloca might be a macro taking one arg (hi, Sun!), so give it one. */ # if !defined(__cplusplus) # define __Xnullarg /* as nothing */ extern void *alloca(__Xnullarg); # endif # define ALLOCATE_LOCAL(size) alloca((size_t)(size)) # endif /* who does alloca */ # endif /* __GNUC__ */ #endif /* NO_ALLOCA */ #if !defined(ALLOCATE_LOCAL) # if defined(ALLOCATE_LOCAL_FALLBACK) && defined(DEALLOCATE_LOCAL_FALLBACK) # define ALLOCATE_LOCAL(_size) ALLOCATE_LOCAL_FALLBACK(_size) # define DEALLOCATE_LOCAL(_ptr) DEALLOCATE_LOCAL_FALLBACK(_ptr) # else /* no fallbacks supplied; error */ # define ALLOCATE_LOCAL(_size) ALLOCATE_LOCAL_FALLBACK undefined! # define DEALLOCATE_LOCAL(_ptr) DEALLOCATE_LOCAL_FALLBACK undefined! # endif /* defined(ALLOCATE_LOCAL_FALLBACK && DEALLOCATE_LOCAL_FALLBACK) */ #else # if !defined(DEALLOCATE_LOCAL) # define DEALLOCATE_LOCAL(_ptr) do {} while(0) # endif #endif /* defined(ALLOCATE_LOCAL) */ #endif /* XALLOCA_H */ X11/XWDFile.h000064400000007440151027430550006537 0ustar00/* Copyright 1985, 1986, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * XWDFile.h MIT Project Athena, X Window system window raster * image dumper, dump file format header file. * * Author: Tony Della Fera, DEC * 27-Jun-85 * * Modifier: William F. Wyatt, SAO * 18-Nov-86 - version 6 for saving/restoring color maps */ #ifndef XWDFILE_H #define XWDFILE_H #include #define XWD_FILE_VERSION 7 #define sz_XWDheader 100 #define sz_XWDColor 12 typedef CARD32 xwdval; /* for old broken programs */ /* Values in the file are most significant byte first. */ typedef struct _xwd_file_header { /* header_size = SIZEOF(XWDheader) + length of null-terminated * window name. */ CARD32 header_size; CARD32 file_version; /* = XWD_FILE_VERSION above */ CARD32 pixmap_format; /* ZPixmap or XYPixmap */ CARD32 pixmap_depth; /* Pixmap depth */ CARD32 pixmap_width; /* Pixmap width */ CARD32 pixmap_height; /* Pixmap height */ CARD32 xoffset; /* Bitmap x offset, normally 0 */ CARD32 byte_order; /* of image data: MSBFirst, LSBFirst */ /* bitmap_unit applies to bitmaps (depth 1 format XY) only. * It is the number of bits that each scanline is padded to. */ CARD32 bitmap_unit; CARD32 bitmap_bit_order; /* bitmaps only: MSBFirst, LSBFirst */ /* bitmap_pad applies to pixmaps (non-bitmaps) only. * It is the number of bits that each scanline is padded to. */ CARD32 bitmap_pad; CARD32 bits_per_pixel; /* Bits per pixel */ /* bytes_per_line is pixmap_width padded to bitmap_unit (bitmaps) * or bitmap_pad (pixmaps). It is the delta (in bytes) to get * to the same x position on an adjacent row. */ CARD32 bytes_per_line; CARD32 visual_class; /* Class of colormap */ CARD32 red_mask; /* Z red mask */ CARD32 green_mask; /* Z green mask */ CARD32 blue_mask; /* Z blue mask */ CARD32 bits_per_rgb; /* Log2 of distinct color values */ CARD32 colormap_entries; /* Number of entries in colormap; not used? */ CARD32 ncolors; /* Number of XWDColor structures */ CARD32 window_width; /* Window width */ CARD32 window_height; /* Window height */ CARD32 window_x; /* Window upper left X coordinate */ CARD32 window_y; /* Window upper left Y coordinate */ CARD32 window_bdrwidth; /* Window border width */ } XWDFileHeader; /* Null-terminated window name follows the above structure. */ /* Next comes XWDColor structures, at offset XWDFileHeader.header_size in * the file. XWDFileHeader.ncolors tells how many XWDColor structures * there are. */ typedef struct { CARD32 pixel; CARD16 red; CARD16 green; CARD16 blue; CARD8 flags; CARD8 pad; } XWDColor; /* Last comes the image data in the format described by XWDFileHeader. */ #endif /* XWDFILE_H */ X11/Xauth.h000064400000007351151027430550006367 0ustar00/* Copyright 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _Xauth_h #define _Xauth_h /* struct xauth is full of implicit padding to properly align the pointers after the length fields. We can't clean that up without breaking ABI, so tell clang not to bother complaining about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif typedef struct xauth { unsigned short family; unsigned short address_length; char *address; unsigned short number_length; char *number; unsigned short name_length; char *name; unsigned short data_length; char *data; } Xauth; #ifdef __clang__ #pragma clang diagnostic pop #endif #ifndef _XAUTH_STRUCT_ONLY # include # include # include # define FamilyLocal (256) /* not part of X standard (i.e. X.h) */ # define FamilyWild (65535) # define FamilyNetname (254) /* not part of X standard */ # define FamilyKrb5Principal (253) /* Kerberos 5 principal name */ # define FamilyLocalHost (252) /* for local non-net authentication */ _XFUNCPROTOBEGIN char *XauFileName(void); Xauth *XauReadAuth( FILE* /* auth_file */ ); int XauLockAuth( _Xconst char* /* file_name */, int /* retries */, int /* timeout */, long /* dead */ ); int XauUnlockAuth( _Xconst char* /* file_name */ ); int XauWriteAuth( FILE* /* auth_file */, Xauth* /* auth */ ); Xauth *XauGetAuthByAddr( #if NeedWidePrototypes unsigned int /* family */, unsigned int /* address_length */, #else unsigned short /* family */, unsigned short /* address_length */, #endif _Xconst char* /* address */, #if NeedWidePrototypes unsigned int /* number_length */, #else unsigned short /* number_length */, #endif _Xconst char* /* number */, #if NeedWidePrototypes unsigned int /* name_length */, #else unsigned short /* name_length */, #endif _Xconst char* /* name */ ); Xauth *XauGetBestAuthByAddr( #if NeedWidePrototypes unsigned int /* family */, unsigned int /* address_length */, #else unsigned short /* family */, unsigned short /* address_length */, #endif _Xconst char* /* address */, #if NeedWidePrototypes unsigned int /* number_length */, #else unsigned short /* number_length */, #endif _Xconst char* /* number */, int /* types_length */, char** /* type_names */, _Xconst int* /* type_lengths */ ); void XauDisposeAuth( Xauth* /* auth */ ); _XFUNCPROTOEND /* Return values from XauLockAuth */ # define LOCK_SUCCESS 0 /* lock succeeded */ # define LOCK_ERROR 1 /* lock unexpectely failed, check errno */ # define LOCK_TIMEOUT 2 /* lock failed, timeouts expired */ #endif /* _XAUTH_STRUCT_ONLY */ #endif /* _Xauth_h */ X11/X.h000064400000047251151027430550005510 0ustar00/* Definitions for the X window system likely to be used by applications */ #ifndef X_H #define X_H /*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #define X_PROTOCOL 11 /* current protocol version */ #define X_PROTOCOL_REVISION 0 /* current minor version */ /* Resources */ /* * _XSERVER64 must ONLY be defined when compiling X server sources on * systems where unsigned long is not 32 bits, must NOT be used in * client or library code. */ #ifndef _XSERVER64 # ifndef _XTYPEDEF_XID # define _XTYPEDEF_XID typedef unsigned long XID; # endif # ifndef _XTYPEDEF_MASK # define _XTYPEDEF_MASK typedef unsigned long Mask; # endif # ifndef _XTYPEDEF_ATOM # define _XTYPEDEF_ATOM typedef unsigned long Atom; /* Also in Xdefs.h */ # endif typedef unsigned long VisualID; typedef unsigned long Time; #else # include # ifndef _XTYPEDEF_XID # define _XTYPEDEF_XID typedef CARD32 XID; # endif # ifndef _XTYPEDEF_MASK # define _XTYPEDEF_MASK typedef CARD32 Mask; # endif # ifndef _XTYPEDEF_ATOM # define _XTYPEDEF_ATOM typedef CARD32 Atom; # endif typedef CARD32 VisualID; typedef CARD32 Time; #endif typedef XID Window; typedef XID Drawable; #ifndef _XTYPEDEF_FONT # define _XTYPEDEF_FONT typedef XID Font; #endif typedef XID Pixmap; typedef XID Cursor; typedef XID Colormap; typedef XID GContext; typedef XID KeySym; typedef unsigned char KeyCode; /***************************************************************** * RESERVED RESOURCE AND CONSTANT DEFINITIONS *****************************************************************/ #ifndef None #define None 0L /* universal null resource or null atom */ #endif #define ParentRelative 1L /* background pixmap in CreateWindow and ChangeWindowAttributes */ #define CopyFromParent 0L /* border pixmap in CreateWindow and ChangeWindowAttributes special VisualID and special window class passed to CreateWindow */ #define PointerWindow 0L /* destination window in SendEvent */ #define InputFocus 1L /* destination window in SendEvent */ #define PointerRoot 1L /* focus window in SetInputFocus */ #define AnyPropertyType 0L /* special Atom, passed to GetProperty */ #define AnyKey 0L /* special Key Code, passed to GrabKey */ #define AnyButton 0L /* special Button Code, passed to GrabButton */ #define AllTemporary 0L /* special Resource ID passed to KillClient */ #define CurrentTime 0L /* special Time */ #define NoSymbol 0L /* special KeySym */ /***************************************************************** * EVENT DEFINITIONS *****************************************************************/ /* Input Event Masks. Used as event-mask window attribute and as arguments to Grab requests. Not to be confused with event names. */ #define NoEventMask 0L #define KeyPressMask (1L<<0) #define KeyReleaseMask (1L<<1) #define ButtonPressMask (1L<<2) #define ButtonReleaseMask (1L<<3) #define EnterWindowMask (1L<<4) #define LeaveWindowMask (1L<<5) #define PointerMotionMask (1L<<6) #define PointerMotionHintMask (1L<<7) #define Button1MotionMask (1L<<8) #define Button2MotionMask (1L<<9) #define Button3MotionMask (1L<<10) #define Button4MotionMask (1L<<11) #define Button5MotionMask (1L<<12) #define ButtonMotionMask (1L<<13) #define KeymapStateMask (1L<<14) #define ExposureMask (1L<<15) #define VisibilityChangeMask (1L<<16) #define StructureNotifyMask (1L<<17) #define ResizeRedirectMask (1L<<18) #define SubstructureNotifyMask (1L<<19) #define SubstructureRedirectMask (1L<<20) #define FocusChangeMask (1L<<21) #define PropertyChangeMask (1L<<22) #define ColormapChangeMask (1L<<23) #define OwnerGrabButtonMask (1L<<24) /* Event names. Used in "type" field in XEvent structures. Not to be confused with event masks above. They start from 2 because 0 and 1 are reserved in the protocol for errors and replies. */ #define KeyPress 2 #define KeyRelease 3 #define ButtonPress 4 #define ButtonRelease 5 #define MotionNotify 6 #define EnterNotify 7 #define LeaveNotify 8 #define FocusIn 9 #define FocusOut 10 #define KeymapNotify 11 #define Expose 12 #define GraphicsExpose 13 #define NoExpose 14 #define VisibilityNotify 15 #define CreateNotify 16 #define DestroyNotify 17 #define UnmapNotify 18 #define MapNotify 19 #define MapRequest 20 #define ReparentNotify 21 #define ConfigureNotify 22 #define ConfigureRequest 23 #define GravityNotify 24 #define ResizeRequest 25 #define CirculateNotify 26 #define CirculateRequest 27 #define PropertyNotify 28 #define SelectionClear 29 #define SelectionRequest 30 #define SelectionNotify 31 #define ColormapNotify 32 #define ClientMessage 33 #define MappingNotify 34 #define GenericEvent 35 #define LASTEvent 36 /* must be bigger than any event # */ /* Key masks. Used as modifiers to GrabButton and GrabKey, results of QueryPointer, state in various key-, mouse-, and button-related events. */ #define ShiftMask (1<<0) #define LockMask (1<<1) #define ControlMask (1<<2) #define Mod1Mask (1<<3) #define Mod2Mask (1<<4) #define Mod3Mask (1<<5) #define Mod4Mask (1<<6) #define Mod5Mask (1<<7) /* modifier names. Used to build a SetModifierMapping request or to read a GetModifierMapping request. These correspond to the masks defined above. */ #define ShiftMapIndex 0 #define LockMapIndex 1 #define ControlMapIndex 2 #define Mod1MapIndex 3 #define Mod2MapIndex 4 #define Mod3MapIndex 5 #define Mod4MapIndex 6 #define Mod5MapIndex 7 /* button masks. Used in same manner as Key masks above. Not to be confused with button names below. */ #define Button1Mask (1<<8) #define Button2Mask (1<<9) #define Button3Mask (1<<10) #define Button4Mask (1<<11) #define Button5Mask (1<<12) #define AnyModifier (1<<15) /* used in GrabButton, GrabKey */ /* button names. Used as arguments to GrabButton and as detail in ButtonPress and ButtonRelease events. Not to be confused with button masks above. Note that 0 is already defined above as "AnyButton". */ #define Button1 1 #define Button2 2 #define Button3 3 #define Button4 4 #define Button5 5 /* Notify modes */ #define NotifyNormal 0 #define NotifyGrab 1 #define NotifyUngrab 2 #define NotifyWhileGrabbed 3 #define NotifyHint 1 /* for MotionNotify events */ /* Notify detail */ #define NotifyAncestor 0 #define NotifyVirtual 1 #define NotifyInferior 2 #define NotifyNonlinear 3 #define NotifyNonlinearVirtual 4 #define NotifyPointer 5 #define NotifyPointerRoot 6 #define NotifyDetailNone 7 /* Visibility notify */ #define VisibilityUnobscured 0 #define VisibilityPartiallyObscured 1 #define VisibilityFullyObscured 2 /* Circulation request */ #define PlaceOnTop 0 #define PlaceOnBottom 1 /* protocol families */ #define FamilyInternet 0 /* IPv4 */ #define FamilyDECnet 1 #define FamilyChaos 2 #define FamilyInternet6 6 /* IPv6 */ /* authentication families not tied to a specific protocol */ #define FamilyServerInterpreted 5 /* Property notification */ #define PropertyNewValue 0 #define PropertyDelete 1 /* Color Map notification */ #define ColormapUninstalled 0 #define ColormapInstalled 1 /* GrabPointer, GrabButton, GrabKeyboard, GrabKey Modes */ #define GrabModeSync 0 #define GrabModeAsync 1 /* GrabPointer, GrabKeyboard reply status */ #define GrabSuccess 0 #define AlreadyGrabbed 1 #define GrabInvalidTime 2 #define GrabNotViewable 3 #define GrabFrozen 4 /* AllowEvents modes */ #define AsyncPointer 0 #define SyncPointer 1 #define ReplayPointer 2 #define AsyncKeyboard 3 #define SyncKeyboard 4 #define ReplayKeyboard 5 #define AsyncBoth 6 #define SyncBoth 7 /* Used in SetInputFocus, GetInputFocus */ #define RevertToNone (int)None #define RevertToPointerRoot (int)PointerRoot #define RevertToParent 2 /***************************************************************** * ERROR CODES *****************************************************************/ #define Success 0 /* everything's okay */ #define BadRequest 1 /* bad request code */ #define BadValue 2 /* int parameter out of range */ #define BadWindow 3 /* parameter not a Window */ #define BadPixmap 4 /* parameter not a Pixmap */ #define BadAtom 5 /* parameter not an Atom */ #define BadCursor 6 /* parameter not a Cursor */ #define BadFont 7 /* parameter not a Font */ #define BadMatch 8 /* parameter mismatch */ #define BadDrawable 9 /* parameter not a Pixmap or Window */ #define BadAccess 10 /* depending on context: - key/button already grabbed - attempt to free an illegal cmap entry - attempt to store into a read-only color map entry. - attempt to modify the access control list from other than the local host. */ #define BadAlloc 11 /* insufficient resources */ #define BadColor 12 /* no such colormap */ #define BadGC 13 /* parameter not a GC */ #define BadIDChoice 14 /* choice not in range or already used */ #define BadName 15 /* font or color name doesn't exist */ #define BadLength 16 /* Request length incorrect */ #define BadImplementation 17 /* server is defective */ #define FirstExtensionError 128 #define LastExtensionError 255 /***************************************************************** * WINDOW DEFINITIONS *****************************************************************/ /* Window classes used by CreateWindow */ /* Note that CopyFromParent is already defined as 0 above */ #define InputOutput 1 #define InputOnly 2 /* Window attributes for CreateWindow and ChangeWindowAttributes */ #define CWBackPixmap (1L<<0) #define CWBackPixel (1L<<1) #define CWBorderPixmap (1L<<2) #define CWBorderPixel (1L<<3) #define CWBitGravity (1L<<4) #define CWWinGravity (1L<<5) #define CWBackingStore (1L<<6) #define CWBackingPlanes (1L<<7) #define CWBackingPixel (1L<<8) #define CWOverrideRedirect (1L<<9) #define CWSaveUnder (1L<<10) #define CWEventMask (1L<<11) #define CWDontPropagate (1L<<12) #define CWColormap (1L<<13) #define CWCursor (1L<<14) /* ConfigureWindow structure */ #define CWX (1<<0) #define CWY (1<<1) #define CWWidth (1<<2) #define CWHeight (1<<3) #define CWBorderWidth (1<<4) #define CWSibling (1<<5) #define CWStackMode (1<<6) /* Bit Gravity */ #define ForgetGravity 0 #define NorthWestGravity 1 #define NorthGravity 2 #define NorthEastGravity 3 #define WestGravity 4 #define CenterGravity 5 #define EastGravity 6 #define SouthWestGravity 7 #define SouthGravity 8 #define SouthEastGravity 9 #define StaticGravity 10 /* Window gravity + bit gravity above */ #define UnmapGravity 0 /* Used in CreateWindow for backing-store hint */ #define NotUseful 0 #define WhenMapped 1 #define Always 2 /* Used in GetWindowAttributes reply */ #define IsUnmapped 0 #define IsUnviewable 1 #define IsViewable 2 /* Used in ChangeSaveSet */ #define SetModeInsert 0 #define SetModeDelete 1 /* Used in ChangeCloseDownMode */ #define DestroyAll 0 #define RetainPermanent 1 #define RetainTemporary 2 /* Window stacking method (in configureWindow) */ #define Above 0 #define Below 1 #define TopIf 2 #define BottomIf 3 #define Opposite 4 /* Circulation direction */ #define RaiseLowest 0 #define LowerHighest 1 /* Property modes */ #define PropModeReplace 0 #define PropModePrepend 1 #define PropModeAppend 2 /***************************************************************** * GRAPHICS DEFINITIONS *****************************************************************/ /* graphics functions, as in GC.alu */ #define GXclear 0x0 /* 0 */ #define GXand 0x1 /* src AND dst */ #define GXandReverse 0x2 /* src AND NOT dst */ #define GXcopy 0x3 /* src */ #define GXandInverted 0x4 /* NOT src AND dst */ #define GXnoop 0x5 /* dst */ #define GXxor 0x6 /* src XOR dst */ #define GXor 0x7 /* src OR dst */ #define GXnor 0x8 /* NOT src AND NOT dst */ #define GXequiv 0x9 /* NOT src XOR dst */ #define GXinvert 0xa /* NOT dst */ #define GXorReverse 0xb /* src OR NOT dst */ #define GXcopyInverted 0xc /* NOT src */ #define GXorInverted 0xd /* NOT src OR dst */ #define GXnand 0xe /* NOT src OR NOT dst */ #define GXset 0xf /* 1 */ /* LineStyle */ #define LineSolid 0 #define LineOnOffDash 1 #define LineDoubleDash 2 /* capStyle */ #define CapNotLast 0 #define CapButt 1 #define CapRound 2 #define CapProjecting 3 /* joinStyle */ #define JoinMiter 0 #define JoinRound 1 #define JoinBevel 2 /* fillStyle */ #define FillSolid 0 #define FillTiled 1 #define FillStippled 2 #define FillOpaqueStippled 3 /* fillRule */ #define EvenOddRule 0 #define WindingRule 1 /* subwindow mode */ #define ClipByChildren 0 #define IncludeInferiors 1 /* SetClipRectangles ordering */ #define Unsorted 0 #define YSorted 1 #define YXSorted 2 #define YXBanded 3 /* CoordinateMode for drawing routines */ #define CoordModeOrigin 0 /* relative to the origin */ #define CoordModePrevious 1 /* relative to previous point */ /* Polygon shapes */ #define Complex 0 /* paths may intersect */ #define Nonconvex 1 /* no paths intersect, but not convex */ #define Convex 2 /* wholly convex */ /* Arc modes for PolyFillArc */ #define ArcChord 0 /* join endpoints of arc */ #define ArcPieSlice 1 /* join endpoints to center of arc */ /* GC components: masks used in CreateGC, CopyGC, ChangeGC, OR'ed into GC.stateChanges */ #define GCFunction (1L<<0) #define GCPlaneMask (1L<<1) #define GCForeground (1L<<2) #define GCBackground (1L<<3) #define GCLineWidth (1L<<4) #define GCLineStyle (1L<<5) #define GCCapStyle (1L<<6) #define GCJoinStyle (1L<<7) #define GCFillStyle (1L<<8) #define GCFillRule (1L<<9) #define GCTile (1L<<10) #define GCStipple (1L<<11) #define GCTileStipXOrigin (1L<<12) #define GCTileStipYOrigin (1L<<13) #define GCFont (1L<<14) #define GCSubwindowMode (1L<<15) #define GCGraphicsExposures (1L<<16) #define GCClipXOrigin (1L<<17) #define GCClipYOrigin (1L<<18) #define GCClipMask (1L<<19) #define GCDashOffset (1L<<20) #define GCDashList (1L<<21) #define GCArcMode (1L<<22) #define GCLastBit 22 /***************************************************************** * FONTS *****************************************************************/ /* used in QueryFont -- draw direction */ #define FontLeftToRight 0 #define FontRightToLeft 1 #define FontChange 255 /***************************************************************** * IMAGING *****************************************************************/ /* ImageFormat -- PutImage, GetImage */ #define XYBitmap 0 /* depth 1, XYFormat */ #define XYPixmap 1 /* depth == drawable depth */ #define ZPixmap 2 /* depth == drawable depth */ /***************************************************************** * COLOR MAP STUFF *****************************************************************/ /* For CreateColormap */ #define AllocNone 0 /* create map with no entries */ #define AllocAll 1 /* allocate entire map writeable */ /* Flags used in StoreNamedColor, StoreColors */ #define DoRed (1<<0) #define DoGreen (1<<1) #define DoBlue (1<<2) /***************************************************************** * CURSOR STUFF *****************************************************************/ /* QueryBestSize Class */ #define CursorShape 0 /* largest size that can be displayed */ #define TileShape 1 /* size tiled fastest */ #define StippleShape 2 /* size stippled fastest */ /***************************************************************** * KEYBOARD/POINTER STUFF *****************************************************************/ #define AutoRepeatModeOff 0 #define AutoRepeatModeOn 1 #define AutoRepeatModeDefault 2 #define LedModeOff 0 #define LedModeOn 1 /* masks for ChangeKeyboardControl */ #define KBKeyClickPercent (1L<<0) #define KBBellPercent (1L<<1) #define KBBellPitch (1L<<2) #define KBBellDuration (1L<<3) #define KBLed (1L<<4) #define KBLedMode (1L<<5) #define KBKey (1L<<6) #define KBAutoRepeatMode (1L<<7) #define MappingSuccess 0 #define MappingBusy 1 #define MappingFailed 2 #define MappingModifier 0 #define MappingKeyboard 1 #define MappingPointer 2 /***************************************************************** * SCREEN SAVER STUFF *****************************************************************/ #define DontPreferBlanking 0 #define PreferBlanking 1 #define DefaultBlanking 2 #define DisableScreenSaver 0 #define DisableScreenInterval 0 #define DontAllowExposures 0 #define AllowExposures 1 #define DefaultExposures 2 /* for ForceScreenSaver */ #define ScreenSaverReset 0 #define ScreenSaverActive 1 /***************************************************************** * HOSTS AND CONNECTIONS *****************************************************************/ /* for ChangeHosts */ #define HostInsert 0 #define HostDelete 1 /* for ChangeAccessControl */ #define EnableAccess 1 #define DisableAccess 0 /* Display classes used in opening the connection * Note that the statically allocated ones are even numbered and the * dynamically changeable ones are odd numbered */ #define StaticGray 0 #define GrayScale 1 #define StaticColor 2 #define PseudoColor 3 #define TrueColor 4 #define DirectColor 5 /* Byte order used in imageByteOrder and bitmapBitOrder */ #define LSBFirst 0 #define MSBFirst 1 #endif /* X_H */ X11/Xthreads.h000064400000030153151027430550007054 0ustar00/* * Copyright 1993, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * * */ #ifndef _XTHREADS_H_ # define _XTHREADS_H_ /* Redefine these to XtMalloc/XtFree or whatever you want before including * this header file. */ # ifndef xmalloc # define xmalloc malloc # endif # ifndef xfree # define xfree free # endif # ifdef CTHREADS # include typedef cthread_t xthread_t; typedef struct condition xcondition_rec; typedef struct mutex xmutex_rec; # define xthread_init() cthread_init() # define xthread_self cthread_self # define xthread_fork(func,closure) cthread_fork(func,closure) # define xthread_yield() cthread_yield() # define xthread_exit(v) cthread_exit(v) # define xthread_set_name(t,str) cthread_set_name(t,str) # define xmutex_init(m) mutex_init(m) # define xmutex_clear(m) mutex_clear(m) # define xmutex_lock(m) mutex_lock(m) # define xmutex_unlock(m) mutex_unlock(m) # define xmutex_set_name(m,str) mutex_set_name(m,str) # define xcondition_init(cv) condition_init(cv) # define xcondition_clear(cv) condition_clear(cv) # define xcondition_wait(cv,m) condition_wait(cv,m) # define xcondition_signal(cv) condition_signal(cv) # define xcondition_broadcast(cv) condition_broadcast(cv) # define xcondition_set_name(cv,str) condition_set_name(cv,str) # else /* !CTHREADS */ # if defined(SVR4) # include # include typedef thread_t xthread_t; typedef thread_key_t xthread_key_t; typedef cond_t xcondition_rec; typedef mutex_t xmutex_rec; # if defined(__UNIXWARE__) extern xthread_t (*_x11_thr_self)(); # define xthread_self (_x11_thr_self) # else # define xthread_self thr_self # endif # define xthread_fork(func,closure) thr_create(NULL,0,func,closure,THR_NEW_LWP|THR_DETACHED,NULL) # define xthread_yield() thr_yield() # define xthread_exit(v) thr_exit(v) # define xthread_key_create(kp,d) thr_keycreate(kp,d) # ifdef __sun # define xthread_key_delete(k) 0 # else # define xthread_key_delete(k) thr_keydelete(k) # endif # define xthread_set_specific(k,v) thr_setspecific(k,v) # define xthread_get_specific(k,vp) thr_getspecific(k,vp) # define xmutex_init(m) mutex_init(m,USYNC_THREAD,0) # define xmutex_clear(m) mutex_destroy(m) # define xmutex_lock(m) mutex_lock(m) # define xmutex_unlock(m) mutex_unlock(m) # define xcondition_init(cv) cond_init(cv,USYNC_THREAD,0) # define xcondition_clear(cv) cond_destroy(cv) # define xcondition_wait(cv,m) cond_wait(cv,m) # define xcondition_signal(cv) cond_signal(cv) # define xcondition_broadcast(cv) cond_broadcast(cv) # else /* !SVR4 */ # ifdef WIN32 # include typedef DWORD xthread_t; typedef DWORD xthread_key_t; struct _xthread_waiter { HANDLE sem; struct _xthread_waiter *next; }; typedef struct { CRITICAL_SECTION cs; struct _xthread_waiter *waiters; } xcondition_rec; typedef CRITICAL_SECTION xmutex_rec; extern void _Xthread_init(void); # define xthread_init() _Xthread_init() # define xthread_self GetCurrentThreadId # define xthread_fork(func,closure) { \ DWORD _tmptid; \ CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func, (LPVOID)closure, 0, \ &_tmptid); \ } # define xthread_yield() Sleep(0) # define xthread_exit(v) ExitThread((DWORD)(v)) # define xthread_key_create(kp,d) *(kp) = TlsAlloc() # define xthread_key_delete(k) TlsFree(k) # define xthread_set_specific(k,v) TlsSetValue(k,v) # define xthread_get_specific(k,vp) TlsGetValue(k) # define xmutex_init(m) InitializeCriticalSection(m) # define xmutex_clear(m) DeleteCriticalSection(m) # define _XMUTEX_NESTS # define xmutex_lock(m) EnterCriticalSection(m) # define xmutex_unlock(m) LeaveCriticalSection(m) # define xcondition_init(cv) { \ InitializeCriticalSection(&(cv)->cs); \ (cv)->waiters = NULL; \ } # define xcondition_clear(cv) DeleteCriticalSection(&(cv)->cs) extern struct _xthread_waiter *_Xthread_waiter(); # define xcondition_wait(cv,m) { \ struct _xthread_waiter *_tmpthr = _Xthread_waiter(); \ EnterCriticalSection(&(cv)->cs); \ _tmpthr->next = (cv)->waiters; \ (cv)->waiters = _tmpthr; \ LeaveCriticalSection(&(cv)->cs); \ LeaveCriticalSection(m); \ WaitForSingleObject(_tmpthr->sem, INFINITE); \ EnterCriticalSection(m); \ } # define xcondition_signal(cv) { \ EnterCriticalSection(&(cv)->cs); \ if ((cv)->waiters) { \ ReleaseSemaphore((cv)->waiters->sem, 1, NULL); \ (cv)->waiters = (cv)->waiters->next; \ } \ LeaveCriticalSection(&(cv)->cs); \ } # define xcondition_broadcast(cv) { \ struct _xthread_waiter *_tmpthr; \ EnterCriticalSection(&(cv)->cs); \ for (_tmpthr = (cv)->waiters; _tmpthr; _tmpthr = _tmpthr->next) \ ReleaseSemaphore(_tmpthr->sem, 1, NULL); \ (cv)->waiters = NULL; \ LeaveCriticalSection(&(cv)->cs); \ } # else /* !WIN32 */ # ifdef USE_TIS_SUPPORT /* * TIS support is intended for thread safe libraries. * This should not be used for general client programming. */ # include typedef pthread_t xthread_t; typedef pthread_key_t xthread_key_t; typedef pthread_cond_t xcondition_rec; typedef pthread_mutex_t xmutex_rec; # define xthread_self tis_self # define xthread_fork(func,closure) { pthread_t _tmpxthr; \ pthread_create(&_tmpxthr,NULL,func,closure); } # define xthread_yield() pthread_yield_np() # define xthread_exit(v) pthread_exit(v) # define xthread_key_create(kp,d) tis_key_create(kp,d) # define xthread_key_delete(k) tis_key_delete(k) # define xthread_set_specific(k,v) tis_setspecific(k,v) # define xthread_get_specific(k,vp) *(vp) = tis_getspecific(k) # define XMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER # define xmutex_init(m) tis_mutex_init(m) # define xmutex_clear(m) tis_mutex_destroy(m) # define xmutex_lock(m) tis_mutex_lock(m) # define xmutex_unlock(m) tis_mutex_unlock(m) # define xcondition_init(c) tis_cond_init(c) # define xcondition_clear(c) tis_cond_destroy(c) # define xcondition_wait(c,m) tis_cond_wait(c,m) # define xcondition_signal(c) tis_cond_signal(c) # define xcondition_broadcast(c) tis_cond_broadcast(c) # else # ifdef USE_NBSD_THREADLIB /* * NetBSD threadlib support is intended for thread safe libraries. * This should not be used for general client programming. */ # include typedef thr_t xthread_t; typedef thread_key_t xthread_key_t; typedef cond_t xcondition_rec; typedef mutex_t xmutex_rec; # define xthread_self thr_self # define xthread_fork(func,closure) { thr_t _tmpxthr; \ /* XXX Create it detached? --thorpej */ \ thr_create(&_tmpxthr,NULL,func,closure); } # define xthread_yield() thr_yield() # define xthread_exit(v) thr_exit(v) # define xthread_key_create(kp,d) thr_keycreate(kp,d) # define xthread_key_delete(k) thr_keydelete(k) # define xthread_set_specific(k,v) thr_setspecific(k,v) # define xthread_get_specific(k,vp) *(vp) = thr_getspecific(k) # define XMUTEX_INITIALIZER MUTEX_INITIALIZER # define xmutex_init(m) mutex_init(m, 0) # define xmutex_clear(m) mutex_destroy(m) # define xmutex_lock(m) mutex_lock(m) # define xmutex_unlock(m) mutex_unlock(m) # define xcondition_init(c) cond_init(c, 0, 0) # define xcondition_clear(c) cond_destroy(c) # define xcondition_wait(c,m) cond_wait(c,m) # define xcondition_signal(c) cond_signal(c) # define xcondition_broadcast(c) cond_broadcast(c) # else # include typedef pthread_t xthread_t; typedef pthread_key_t xthread_key_t; typedef pthread_cond_t xcondition_rec; typedef pthread_mutex_t xmutex_rec; # define xthread_self pthread_self # define xthread_yield() pthread_yield() # define xthread_exit(v) pthread_exit(v) # define xthread_set_specific(k,v) pthread_setspecific(k,v) # define xmutex_clear(m) pthread_mutex_destroy(m) # define xmutex_lock(m) pthread_mutex_lock(m) # define xmutex_unlock(m) pthread_mutex_unlock(m) # ifndef XPRE_STANDARD_API # define xthread_key_create(kp,d) pthread_key_create(kp,d) # define xthread_key_delete(k) pthread_key_delete(k) # define xthread_get_specific(k,vp) *(vp) = pthread_getspecific(k) # define xthread_fork(func,closure) { pthread_t _tmpxthr; \ pthread_create(&_tmpxthr,NULL,func,closure); } # define XMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER # define xmutex_init(m) pthread_mutex_init(m, NULL) # define xcondition_init(c) pthread_cond_init(c, NULL) # else /* XPRE_STANDARD_API */ # define xthread_key_create(kp,d) pthread_keycreate(kp,d) # define xthread_key_delete(k) 0 # define xthread_get_specific(k,vp) pthread_getspecific(k,vp) # define xthread_fork(func,closure) { pthread_t _tmpxthr; \ pthread_create(&_tmpxthr,pthread_attr_default,func,closure); } # define xmutex_init(m) pthread_mutex_init(m, pthread_mutexattr_default) # define xcondition_init(c) pthread_cond_init(c, pthread_condattr_default) # endif /* XPRE_STANDARD_API */ # define xcondition_clear(c) pthread_cond_destroy(c) # define xcondition_wait(c,m) pthread_cond_wait(c,m) # define xcondition_signal(c) pthread_cond_signal(c) # define xcondition_broadcast(c) pthread_cond_broadcast(c) # if defined(_DECTHREADS_) static xthread_t _X_no_thread_id; # define xthread_have_id(id) !pthread_equal(id, _X_no_thread_id) # define xthread_clear_id(id) id = _X_no_thread_id # define xthread_equal(id1,id2) pthread_equal(id1, id2) # endif /* _DECTHREADS_ */ # if defined(__linux__) # define xthread_have_id(id) !pthread_equal(id, 0) # define xthread_clear_id(id) id = 0 # define xthread_equal(id1,id2) pthread_equal(id1, id2) # endif /* linux */ # if defined(_CMA_VENDOR_) && defined(_CMA__IBM) && (_CMA_VENDOR_ == _CMA__IBM) # ifdef DEBUG /* too much of a hack to enable normally */ /* see also cma__obj_set_name() */ # define xmutex_set_name(m,str) ((char**)(m)->field1)[5] = (str) # define xcondition_set_name(cv,str) ((char**)(cv)->field1)[5] = (str) # endif /* DEBUG */ # endif /* _CMA_VENDOR_ == _CMA__IBM */ # endif /* USE_NBSD_THREADLIB */ # endif /* USE_TIS_SUPPORT */ # endif /* WIN32 */ # endif /* SVR4 */ # endif /* CTHREADS */ typedef xcondition_rec *xcondition_t; typedef xmutex_rec *xmutex_t; # ifndef xcondition_malloc # define xcondition_malloc() (xcondition_t)xmalloc(sizeof(xcondition_rec)) # endif # ifndef xcondition_free # define xcondition_free(c) xfree((char *)c) # endif # ifndef xmutex_malloc # define xmutex_malloc() (xmutex_t)xmalloc(sizeof(xmutex_rec)) # endif # ifndef xmutex_free # define xmutex_free(m) xfree((char *)m) # endif # ifndef xthread_have_id # define xthread_have_id(id) id # endif # ifndef xthread_clear_id # define xthread_clear_id(id) id = 0 # endif # ifndef xthread_equal # define xthread_equal(id1,id2) ((id1) == (id2)) # endif /* aids understood by some debuggers */ # ifndef xthread_set_name # define xthread_set_name(t,str) # endif # ifndef xmutex_set_name # define xmutex_set_name(m,str) # endif # ifndef xcondition_set_name # define xcondition_set_name(cv,str) # endif #endif /* _XTHREADS_H_ */ X11/Xutil.h000064400000051551151027430550006404 0ustar00 /*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef _X11_XUTIL_H_ #define _X11_XUTIL_H_ /* You must include before including this file */ #include #include /* The Xlib structs are full of implicit padding to properly align members. We can't clean that up without breaking ABI, so tell clang not to bother complaining about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif /* * Bitmask returned by XParseGeometry(). Each bit tells if the corresponding * value (x, y, width, height) was found in the parsed string. */ #define NoValue 0x0000 #define XValue 0x0001 #define YValue 0x0002 #define WidthValue 0x0004 #define HeightValue 0x0008 #define AllValues 0x000F #define XNegative 0x0010 #define YNegative 0x0020 /* * new version containing base_width, base_height, and win_gravity fields; * used with WM_NORMAL_HINTS. */ typedef struct { long flags; /* marks which fields in this structure are defined */ int x, y; /* obsolete for new window mgrs, but clients */ int width, height; /* should set so old wm's don't mess up */ int min_width, min_height; int max_width, max_height; int width_inc, height_inc; struct { int x; /* numerator */ int y; /* denominator */ } min_aspect, max_aspect; int base_width, base_height; /* added by ICCCM version 1 */ int win_gravity; /* added by ICCCM version 1 */ } XSizeHints; /* * The next block of definitions are for window manager properties that * clients and applications use for communication. */ /* flags argument in size hints */ #define USPosition (1L << 0) /* user specified x, y */ #define USSize (1L << 1) /* user specified width, height */ #define PPosition (1L << 2) /* program specified position */ #define PSize (1L << 3) /* program specified size */ #define PMinSize (1L << 4) /* program specified minimum size */ #define PMaxSize (1L << 5) /* program specified maximum size */ #define PResizeInc (1L << 6) /* program specified resize increments */ #define PAspect (1L << 7) /* program specified min and max aspect ratios */ #define PBaseSize (1L << 8) /* program specified base for incrementing */ #define PWinGravity (1L << 9) /* program specified window gravity */ /* obsolete */ #define PAllHints (PPosition|PSize|PMinSize|PMaxSize|PResizeInc|PAspect) typedef struct { long flags; /* marks which fields in this structure are defined */ Bool input; /* does this application rely on the window manager to get keyboard input? */ int initial_state; /* see below */ Pixmap icon_pixmap; /* pixmap to be used as icon */ Window icon_window; /* window to be used as icon */ int icon_x, icon_y; /* initial position of icon */ Pixmap icon_mask; /* icon mask bitmap */ XID window_group; /* id of related window group */ /* this structure may be extended in the future */ } XWMHints; /* definition for flags of XWMHints */ #define InputHint (1L << 0) #define StateHint (1L << 1) #define IconPixmapHint (1L << 2) #define IconWindowHint (1L << 3) #define IconPositionHint (1L << 4) #define IconMaskHint (1L << 5) #define WindowGroupHint (1L << 6) #define AllHints (InputHint|StateHint|IconPixmapHint|IconWindowHint| \ IconPositionHint|IconMaskHint|WindowGroupHint) #define XUrgencyHint (1L << 8) /* definitions for initial window state */ #define WithdrawnState 0 /* for windows that are not mapped */ #define NormalState 1 /* most applications want to start this way */ #define IconicState 3 /* application wants to start as an icon */ /* * Obsolete states no longer defined by ICCCM */ #define DontCareState 0 /* don't know or care */ #define ZoomState 2 /* application wants to start zoomed */ #define InactiveState 4 /* application believes it is seldom used; */ /* some wm's may put it on inactive menu */ /* * new structure for manipulating TEXT properties; used with WM_NAME, * WM_ICON_NAME, WM_CLIENT_MACHINE, and WM_COMMAND. */ typedef struct { unsigned char *value; /* same as Property routines */ Atom encoding; /* prop type */ int format; /* prop data format: 8, 16, or 32 */ unsigned long nitems; /* number of data items in value */ } XTextProperty; #define XNoMemory -1 #define XLocaleNotSupported -2 #define XConverterNotFound -3 typedef enum { XStringStyle, /* STRING */ XCompoundTextStyle, /* COMPOUND_TEXT */ XTextStyle, /* text in owner's encoding (current locale)*/ XStdICCTextStyle, /* STRING, else COMPOUND_TEXT */ /* The following is an XFree86 extension, introduced in November 2000 */ XUTF8StringStyle /* UTF8_STRING */ } XICCEncodingStyle; typedef struct { int min_width, min_height; int max_width, max_height; int width_inc, height_inc; } XIconSize; typedef struct { char *res_name; char *res_class; } XClassHint; #ifdef XUTIL_DEFINE_FUNCTIONS extern int XDestroyImage( XImage *ximage); extern unsigned long XGetPixel( XImage *ximage, int x, int y); extern int XPutPixel( XImage *ximage, int x, int y, unsigned long pixel); extern XImage *XSubImage( XImage *ximage, int x, int y, unsigned int width, unsigned int height); extern int XAddPixel( XImage *ximage, long value); #else /* * These macros are used to give some sugar to the image routines so that * naive people are more comfortable with them. */ #define XDestroyImage(ximage) \ ((*((ximage)->f.destroy_image))((ximage))) #define XGetPixel(ximage, x, y) \ ((*((ximage)->f.get_pixel))((ximage), (x), (y))) #define XPutPixel(ximage, x, y, pixel) \ ((*((ximage)->f.put_pixel))((ximage), (x), (y), (pixel))) #define XSubImage(ximage, x, y, width, height) \ ((*((ximage)->f.sub_image))((ximage), (x), (y), (width), (height))) #define XAddPixel(ximage, value) \ ((*((ximage)->f.add_pixel))((ximage), (value))) #endif /* * Compose sequence status structure, used in calling XLookupString. */ typedef struct _XComposeStatus { XPointer compose_ptr; /* state table pointer */ int chars_matched; /* match state */ } XComposeStatus; /* * Keysym macros, used on Keysyms to test for classes of symbols */ #define IsKeypadKey(keysym) \ (((KeySym)(keysym) >= XK_KP_Space) && ((KeySym)(keysym) <= XK_KP_Equal)) #define IsPrivateKeypadKey(keysym) \ (((KeySym)(keysym) >= 0x11000000) && ((KeySym)(keysym) <= 0x1100FFFF)) #define IsCursorKey(keysym) \ (((KeySym)(keysym) >= XK_Home) && ((KeySym)(keysym) < XK_Select)) #define IsPFKey(keysym) \ (((KeySym)(keysym) >= XK_KP_F1) && ((KeySym)(keysym) <= XK_KP_F4)) #define IsFunctionKey(keysym) \ (((KeySym)(keysym) >= XK_F1) && ((KeySym)(keysym) <= XK_F35)) #define IsMiscFunctionKey(keysym) \ (((KeySym)(keysym) >= XK_Select) && ((KeySym)(keysym) <= XK_Break)) #ifdef XK_XKB_KEYS #define IsModifierKey(keysym) \ ((((KeySym)(keysym) >= XK_Shift_L) && ((KeySym)(keysym) <= XK_Hyper_R)) \ || (((KeySym)(keysym) >= XK_ISO_Lock) && \ ((KeySym)(keysym) <= XK_ISO_Level5_Lock)) \ || ((KeySym)(keysym) == XK_Mode_switch) \ || ((KeySym)(keysym) == XK_Num_Lock)) #else #define IsModifierKey(keysym) \ ((((KeySym)(keysym) >= XK_Shift_L) && ((KeySym)(keysym) <= XK_Hyper_R)) \ || ((KeySym)(keysym) == XK_Mode_switch) \ || ((KeySym)(keysym) == XK_Num_Lock)) #endif /* * opaque reference to Region data type */ typedef struct _XRegion *Region; /* Return values from XRectInRegion() */ #define RectangleOut 0 #define RectangleIn 1 #define RectanglePart 2 /* * Information used by the visual utility routines to find desired visual * type from the many visuals a display may support. */ typedef struct { Visual *visual; VisualID visualid; int screen; int depth; #if defined(__cplusplus) || defined(c_plusplus) int c_class; /* C++ */ #else int class; #endif unsigned long red_mask; unsigned long green_mask; unsigned long blue_mask; int colormap_size; int bits_per_rgb; } XVisualInfo; #define VisualNoMask 0x0 #define VisualIDMask 0x1 #define VisualScreenMask 0x2 #define VisualDepthMask 0x4 #define VisualClassMask 0x8 #define VisualRedMaskMask 0x10 #define VisualGreenMaskMask 0x20 #define VisualBlueMaskMask 0x40 #define VisualColormapSizeMask 0x80 #define VisualBitsPerRGBMask 0x100 #define VisualAllMask 0x1FF /* * This defines a window manager property that clients may use to * share standard color maps of type RGB_COLOR_MAP: */ typedef struct { Colormap colormap; unsigned long red_max; unsigned long red_mult; unsigned long green_max; unsigned long green_mult; unsigned long blue_max; unsigned long blue_mult; unsigned long base_pixel; VisualID visualid; /* added by ICCCM version 1 */ XID killid; /* added by ICCCM version 1 */ } XStandardColormap; #define ReleaseByFreeingColormap ((XID) 1L) /* for killid field above */ /* * return codes for XReadBitmapFile and XWriteBitmapFile */ #define BitmapSuccess 0 #define BitmapOpenFailed 1 #define BitmapFileInvalid 2 #define BitmapNoMemory 3 /**************************************************************** * * Context Management * ****************************************************************/ /* Associative lookup table return codes */ #define XCSUCCESS 0 /* No error. */ #define XCNOMEM 1 /* Out of memory */ #define XCNOENT 2 /* No entry in table */ typedef int XContext; #define XUniqueContext() ((XContext) XrmUniqueQuark()) #define XStringToContext(string) ((XContext) XrmStringToQuark(string)) _XFUNCPROTOBEGIN /* The following declarations are alphabetized. */ extern XClassHint *XAllocClassHint ( void ); extern XIconSize *XAllocIconSize ( void ); extern XSizeHints *XAllocSizeHints ( void ); extern XStandardColormap *XAllocStandardColormap ( void ); extern XWMHints *XAllocWMHints ( void ); extern int XClipBox( Region /* r */, XRectangle* /* rect_return */ ); extern Region XCreateRegion( void ); extern const char *XDefaultString (void); extern int XDeleteContext( Display* /* display */, XID /* rid */, XContext /* context */ ); extern int XDestroyRegion( Region /* r */ ); extern int XEmptyRegion( Region /* r */ ); extern int XEqualRegion( Region /* r1 */, Region /* r2 */ ); extern int XFindContext( Display* /* display */, XID /* rid */, XContext /* context */, XPointer* /* data_return */ ); extern Status XGetClassHint( Display* /* display */, Window /* w */, XClassHint* /* class_hints_return */ ); extern Status XGetIconSizes( Display* /* display */, Window /* w */, XIconSize** /* size_list_return */, int* /* count_return */ ); extern Status XGetNormalHints( Display* /* display */, Window /* w */, XSizeHints* /* hints_return */ ); extern Status XGetRGBColormaps( Display* /* display */, Window /* w */, XStandardColormap** /* stdcmap_return */, int* /* count_return */, Atom /* property */ ); extern Status XGetSizeHints( Display* /* display */, Window /* w */, XSizeHints* /* hints_return */, Atom /* property */ ); extern Status XGetStandardColormap( Display* /* display */, Window /* w */, XStandardColormap* /* colormap_return */, Atom /* property */ ); extern Status XGetTextProperty( Display* /* display */, Window /* window */, XTextProperty* /* text_prop_return */, Atom /* property */ ); extern XVisualInfo *XGetVisualInfo( Display* /* display */, long /* vinfo_mask */, XVisualInfo* /* vinfo_template */, int* /* nitems_return */ ); extern Status XGetWMClientMachine( Display* /* display */, Window /* w */, XTextProperty* /* text_prop_return */ ); extern XWMHints *XGetWMHints( Display* /* display */, Window /* w */ ); extern Status XGetWMIconName( Display* /* display */, Window /* w */, XTextProperty* /* text_prop_return */ ); extern Status XGetWMName( Display* /* display */, Window /* w */, XTextProperty* /* text_prop_return */ ); extern Status XGetWMNormalHints( Display* /* display */, Window /* w */, XSizeHints* /* hints_return */, long* /* supplied_return */ ); extern Status XGetWMSizeHints( Display* /* display */, Window /* w */, XSizeHints* /* hints_return */, long* /* supplied_return */, Atom /* property */ ); extern Status XGetZoomHints( Display* /* display */, Window /* w */, XSizeHints* /* zhints_return */ ); extern int XIntersectRegion( Region /* sra */, Region /* srb */, Region /* dr_return */ ); extern void XConvertCase( KeySym /* sym */, KeySym* /* lower */, KeySym* /* upper */ ); extern int XLookupString( XKeyEvent* /* event_struct */, char* /* buffer_return */, int /* bytes_buffer */, KeySym* /* keysym_return */, XComposeStatus* /* status_in_out */ ); extern Status XMatchVisualInfo( Display* /* display */, int /* screen */, int /* depth */, int /* class */, XVisualInfo* /* vinfo_return */ ); extern int XOffsetRegion( Region /* r */, int /* dx */, int /* dy */ ); extern Bool XPointInRegion( Region /* r */, int /* x */, int /* y */ ); extern Region XPolygonRegion( XPoint* /* points */, int /* n */, int /* fill_rule */ ); extern int XRectInRegion( Region /* r */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */ ); extern int XSaveContext( Display* /* display */, XID /* rid */, XContext /* context */, _Xconst char* /* data */ ); extern int XSetClassHint( Display* /* display */, Window /* w */, XClassHint* /* class_hints */ ); extern int XSetIconSizes( Display* /* display */, Window /* w */, XIconSize* /* size_list */, int /* count */ ); extern int XSetNormalHints( Display* /* display */, Window /* w */, XSizeHints* /* hints */ ); extern void XSetRGBColormaps( Display* /* display */, Window /* w */, XStandardColormap* /* stdcmaps */, int /* count */, Atom /* property */ ); extern int XSetSizeHints( Display* /* display */, Window /* w */, XSizeHints* /* hints */, Atom /* property */ ); extern int XSetStandardProperties( Display* /* display */, Window /* w */, _Xconst char* /* window_name */, _Xconst char* /* icon_name */, Pixmap /* icon_pixmap */, char** /* argv */, int /* argc */, XSizeHints* /* hints */ ); extern void XSetTextProperty( Display* /* display */, Window /* w */, XTextProperty* /* text_prop */, Atom /* property */ ); extern void XSetWMClientMachine( Display* /* display */, Window /* w */, XTextProperty* /* text_prop */ ); extern int XSetWMHints( Display* /* display */, Window /* w */, XWMHints* /* wm_hints */ ); extern void XSetWMIconName( Display* /* display */, Window /* w */, XTextProperty* /* text_prop */ ); extern void XSetWMName( Display* /* display */, Window /* w */, XTextProperty* /* text_prop */ ); extern void XSetWMNormalHints( Display* /* display */, Window /* w */, XSizeHints* /* hints */ ); extern void XSetWMProperties( Display* /* display */, Window /* w */, XTextProperty* /* window_name */, XTextProperty* /* icon_name */, char** /* argv */, int /* argc */, XSizeHints* /* normal_hints */, XWMHints* /* wm_hints */, XClassHint* /* class_hints */ ); extern void XmbSetWMProperties( Display* /* display */, Window /* w */, _Xconst char* /* window_name */, _Xconst char* /* icon_name */, char** /* argv */, int /* argc */, XSizeHints* /* normal_hints */, XWMHints* /* wm_hints */, XClassHint* /* class_hints */ ); extern void Xutf8SetWMProperties( Display* /* display */, Window /* w */, _Xconst char* /* window_name */, _Xconst char* /* icon_name */, char** /* argv */, int /* argc */, XSizeHints* /* normal_hints */, XWMHints* /* wm_hints */, XClassHint* /* class_hints */ ); extern void XSetWMSizeHints( Display* /* display */, Window /* w */, XSizeHints* /* hints */, Atom /* property */ ); extern int XSetRegion( Display* /* display */, GC /* gc */, Region /* r */ ); extern void XSetStandardColormap( Display* /* display */, Window /* w */, XStandardColormap* /* colormap */, Atom /* property */ ); extern int XSetZoomHints( Display* /* display */, Window /* w */, XSizeHints* /* zhints */ ); extern int XShrinkRegion( Region /* r */, int /* dx */, int /* dy */ ); extern Status XStringListToTextProperty( char** /* list */, int /* count */, XTextProperty* /* text_prop_return */ ); extern int XSubtractRegion( Region /* sra */, Region /* srb */, Region /* dr_return */ ); extern int XmbTextListToTextProperty( Display* display, char** list, int count, XICCEncodingStyle style, XTextProperty* text_prop_return ); extern int XwcTextListToTextProperty( Display* display, wchar_t** list, int count, XICCEncodingStyle style, XTextProperty* text_prop_return ); extern int Xutf8TextListToTextProperty( Display* display, char** list, int count, XICCEncodingStyle style, XTextProperty* text_prop_return ); extern void XwcFreeStringList( wchar_t** list ); extern Status XTextPropertyToStringList( XTextProperty* /* text_prop */, char*** /* list_return */, int* /* count_return */ ); extern int XmbTextPropertyToTextList( Display* display, const XTextProperty* text_prop, char*** list_return, int* count_return ); extern int XwcTextPropertyToTextList( Display* display, const XTextProperty* text_prop, wchar_t*** list_return, int* count_return ); extern int Xutf8TextPropertyToTextList( Display* display, const XTextProperty* text_prop, char*** list_return, int* count_return ); extern int XUnionRectWithRegion( XRectangle* /* rectangle */, Region /* src_region */, Region /* dest_region_return */ ); extern int XUnionRegion( Region /* sra */, Region /* srb */, Region /* dr_return */ ); extern int XWMGeometry( Display* /* display */, int /* screen_number */, _Xconst char* /* user_geometry */, _Xconst char* /* default_geometry */, unsigned int /* border_width */, XSizeHints* /* hints */, int* /* x_return */, int* /* y_return */, int* /* width_return */, int* /* height_return */, int* /* gravity_return */ ); extern int XXorRegion( Region /* sra */, Region /* srb */, Region /* dr_return */ ); #ifdef __clang__ #pragma clang diagnostic pop #endif _XFUNCPROTOEND #endif /* _X11_XUTIL_H_ */ X11/Xprotostr.h000064400000005267151027430550007326 0ustar00#ifndef XPROTOSTRUCTS_H #define XPROTOSTRUCTS_H /*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #include /* Used by PolySegment */ typedef struct _xSegment { INT16 x1, y1, x2, y2; } xSegment; /* POINT */ typedef struct _xPoint { INT16 x, y; } xPoint; typedef struct _xRectangle { INT16 x, y; CARD16 width, height; } xRectangle; /* ARC */ typedef struct _xArc { INT16 x, y; CARD16 width, height; INT16 angle1, angle2; } xArc; #endif /* XPROTOSTRUCTS_H */ X11/Xpoll.h000064400000017077151027430550006402 0ustar00/* Copyright 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * Copyright © 2005 Daniel Stone * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Daniel Stone not be used in advertising * or publicity pertaining to distribution of the software without specific, * written prior permission. Daniel Stone makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * DANIEL STONE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * DANIEL STONE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _XPOLL_H_ #define _XPOLL_H_ #if !defined(WIN32) || defined(__CYGWIN__) #ifndef USE_POLL #include #include /* Get the FD_* macros. */ #include #ifdef CSRG_BASED #include # if BSD < 199103 typedef long fd_mask; # endif #endif #if defined(FD_SETSIZE) && FD_SETSIZE < 512 # define XFD_SETSIZE FD_SETSIZE #else # define XFD_SETSIZE 512 # ifndef FD_SETSIZE # define FD_SETSIZE XFD_SETSIZE # endif #endif #ifndef NBBY #define NBBY 8 /* number of bits in a byte */ #endif #ifndef NFDBITS #define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */ #endif #ifndef howmany #define howmany(x,y) (((x)+((y)-1))/(y)) #endif #if defined(BSD) && BSD < 198911 typedef struct fd_set { fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)]; } fd_set; #endif # define Select(n,r,w,e,t) select(n,(fd_set*)r,(fd_set*)w,(fd_set*)e,(struct timeval*)t) #define __X_FDS_BITS __fds_bits #ifndef __FDS_BITS # define __FDS_BITS(p) ((p)->__X_FDS_BITS) #endif #define __XFDS_BITS(p, n) (__FDS_BITS(p))[n] #ifndef FD_SET #define FD_SET(n, p) (__XFDS_BITS(p, ((n)/NFDBITS)) |= ((fd_mask)1 << ((n) % NFDBITS))) #endif #ifndef FD_CLR #define FD_CLR(n, p) (__XFDS_BITS((p), ((n)/NFDBITS)) &= ~((fd_mask)1 << ((n) % NFDBITS))) #endif #ifndef FD_ISSET #define FD_ISSET(n, p) ((__XFDS_BITS((p), ((n)/NFDBITS))) & ((fd_mask)1 << ((n) % NFDBITS))) #endif #ifndef FD_ZERO #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p))) #endif /* * The howmany(FD_SETSIZE, NFDBITS) computes the number of elements in the * array. before accessing an element in the array we check it exists. * If it does not exist then the compiler discards the code to access it. */ #define XFD_ANYSET(p) \ ((howmany(FD_SETSIZE, NFDBITS) > 0 && (__XFDS_BITS(p, 0))) || \ (howmany(FD_SETSIZE, NFDBITS) > 1 && (__XFDS_BITS(p, 1))) || \ (howmany(FD_SETSIZE, NFDBITS) > 2 && (__XFDS_BITS(p, 2))) || \ (howmany(FD_SETSIZE, NFDBITS) > 3 && (__XFDS_BITS(p, 3))) || \ (howmany(FD_SETSIZE, NFDBITS) > 4 && (__XFDS_BITS(p, 4))) || \ (howmany(FD_SETSIZE, NFDBITS) > 5 && (__XFDS_BITS(p, 5))) || \ (howmany(FD_SETSIZE, NFDBITS) > 6 && (__XFDS_BITS(p, 6))) || \ (howmany(FD_SETSIZE, NFDBITS) > 7 && (__XFDS_BITS(p, 7))) || \ (howmany(FD_SETSIZE, NFDBITS) > 8 && (__XFDS_BITS(p, 8))) || \ (howmany(FD_SETSIZE, NFDBITS) > 9 && (__XFDS_BITS(p, 9))) || \ (howmany(FD_SETSIZE, NFDBITS) > 10 && (__XFDS_BITS(p, 10))) || \ (howmany(FD_SETSIZE, NFDBITS) > 11 && (__XFDS_BITS(p, 11))) || \ (howmany(FD_SETSIZE, NFDBITS) > 12 && (__XFDS_BITS(p, 12))) || \ (howmany(FD_SETSIZE, NFDBITS) > 13 && (__XFDS_BITS(p, 13))) || \ (howmany(FD_SETSIZE, NFDBITS) > 14 && (__XFDS_BITS(p, 14))) || \ (howmany(FD_SETSIZE, NFDBITS) > 15 && (__XFDS_BITS(p, 15)))) #define XFD_COPYSET(src,dst) { \ int __i__; \ for (__i__ = 0; __i__ < howmany(FD_SETSIZE, NFDBITS); __i__++) \ __XFDS_BITS((dst), __i__) = __XFDS_BITS((src), __i__); \ } #define XFD_ANDSET(dst,b1,b2) { \ int __i__; \ for (__i__ = 0; __i__ < howmany(FD_SETSIZE, NFDBITS); __i__++) \ __XFDS_BITS((dst), __i__) = ((__XFDS_BITS((b1), __i__)) & (__XFDS_BITS((b2), __i__))); \ } #define XFD_ORSET(dst,b1,b2) { \ int __i__; \ for (__i__ = 0; __i__ < howmany(FD_SETSIZE, NFDBITS); __i__++) \ __XFDS_BITS((dst), __i__) = ((__XFDS_BITS((b1), __i__)) | (__XFDS_BITS((b2), __i__))); \ } #define XFD_UNSET(dst,b1) { \ int __i__; \ for (__i__ = 0; __i__ < howmany(FD_SETSIZE, NFDBITS); __i__++) \ __XFDS_BITS((dst), __i__) &= ~(__XFDS_BITS((b1), __i__)); \ } #else /* USE_POLL */ #include #endif /* USE_POLL */ #else /* WIN32 */ #define XFD_SETSIZE 512 #ifndef FD_SETSIZE #define FD_SETSIZE XFD_SETSIZE #endif #include #define Select(n,r,w,e,t) select(0,(fd_set*)r,(fd_set*)w,(fd_set*)e,(struct timeval*)t) #define XFD_SETCOUNT(p) (((fd_set FAR *)(p))->fd_count) #define XFD_FD(p,i) (((fd_set FAR *)(p))->fd_array[i]) #define XFD_ANYSET(p) XFD_SETCOUNT(p) #define XFD_COPYSET(src,dst) { \ u_int __i; \ FD_ZERO(dst); \ for (__i = 0; __i < XFD_SETCOUNT(src) ; __i++) { \ XFD_FD(dst,__i) = XFD_FD(src,__i); \ } \ XFD_SETCOUNT(dst) = XFD_SETCOUNT(src); \ } #define XFD_ANDSET(dst,b1,b2) { \ u_int __i; \ FD_ZERO(dst); \ for (__i = 0; __i < XFD_SETCOUNT(b1) ; __i++) { \ if (FD_ISSET(XFD_FD(b1,__i), b2)) \ FD_SET(XFD_FD(b1,__i), dst); \ } \ } #define XFD_ORSET(dst,b1,b2) { \ u_int __i; \ if (dst != b1) XFD_COPYSET(b1,dst); \ for (__i = 0; __i < XFD_SETCOUNT(b2) ; __i++) { \ if (!FD_ISSET(XFD_FD(b2,__i), dst)) \ FD_SET(XFD_FD(b2,__i), dst); \ } \ } /* this one is really sub-optimal */ #define XFD_UNSET(dst,b1) { \ u_int __i; \ for (__i = 0; __i < XFD_SETCOUNT(b1) ; __i++) { \ FD_CLR(XFD_FD(b1,__i), dst); \ } \ } /* we have to pay the price of having an array here, unlike with bitmasks calling twice FD_SET with the same fd is not transparent, so be careful */ #undef FD_SET #define FD_SET(fd,set) do { \ if (XFD_SETCOUNT(set) < FD_SETSIZE && !FD_ISSET(fd,set)) \ XFD_FD(set,XFD_SETCOUNT(set)++)=(fd); \ } while(0) #define getdtablesize() FD_SETSIZE #endif /* WIN32 */ #endif /* _XPOLL_H_ */ X11/Xwindows.h000064400000006323151027430550007116 0ustar00/* Copyright 1996, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABIL- ITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * This header file has the sole purpose of allowing the inclusion of * windows.h without getting any name conflicts with X headers code, by * renaming or disabling the conflicting definitions from windows.h */ /* * Mingw.org versions of the Windows API headers actually avoid * making the conflicting definitions if XFree86Server is defined, so we * need to remember if that was defined and undefine it during including * windows.h (so the conflicting definitions get wrapped correctly), and * then redefine it afterwards. (This was never the correct thing to * do as it's no help at all to X11 clients which also need to use the * Win32 API) */ #undef _XFree86Server #ifdef XFree86Server # define _XFree86Server # undef XFree86Server #endif /* * There doesn't seem to be a good way to wrap the min/max macros from * windows.h, so we simply avoid defining them completely, allowing any * pre-existing definition to stand. * */ #define NOMINMAX /* * mingw-w64 headers define BOOL as a typedef, protecting against macros * mingw.org headers define BOOL in terms of WINBOOL * ... so try to come up with something which works with both :-) */ #define _NO_BOOL_TYPEDEF #define BOOL WINBOOL #define INT32 wINT32 #ifdef __x86_64__ #define INT64 wINT64 #define LONG64 wLONG64 #endif #undef Status #define Status wStatus #define ATOM wATOM #define BYTE wBYTE #define FreeResource wFreeResource #include #undef NOMINMAX #undef Status #define Status int #undef BYTE #undef BOOL #undef INT32 #undef INT64 #undef LONG64 #undef ATOM #undef FreeResource #undef CreateWindowA /* * Older version of this header used to name the windows API bool type wBOOL, * rather than more standard name WINBOOL */ #define wBOOL WINBOOL #ifdef RESOURCE_H # undef RT_FONT # undef RT_CURSOR # define RT_FONT ((RESTYPE)4) # define RT_CURSOR ((RESTYPE)5) #endif #ifndef __CYGWIN__ #define sleep(x) Sleep((x) * 1000) #endif #if defined(WIN32) && (!defined(PATH_MAX) || PATH_MAX < 1024) # undef PATH_MAX # define PATH_MAX 1024 #endif #ifdef _XFree86Server # define XFree86Server # undef _XFree86Server #endif X11/HPkeysym.h000064400000013636151027430550007052 0ustar00/* Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts, All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Hewlett Packard or Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. HEWLETT-PACKARD MAKES NO WARRANTY OF ANY KIND WITH REGARD TO THIS SOFWARE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Hewlett-Packard shall not be liable for errors contained herein or direct, indirect, special, incidental or consequential damages in connection with the furnishing, performance, or use of this material. */ #ifndef _HPKEYSYM_H #define _HPKEYSYM_H #define hpXK_ClearLine 0x1000FF6F #define hpXK_InsertLine 0x1000FF70 #define hpXK_DeleteLine 0x1000FF71 #define hpXK_InsertChar 0x1000FF72 #define hpXK_DeleteChar 0x1000FF73 #define hpXK_BackTab 0x1000FF74 #define hpXK_KP_BackTab 0x1000FF75 #define hpXK_Modelock1 0x1000FF48 #define hpXK_Modelock2 0x1000FF49 #define hpXK_Reset 0x1000FF6C #define hpXK_System 0x1000FF6D #define hpXK_User 0x1000FF6E #define hpXK_mute_acute 0x100000A8 #define hpXK_mute_grave 0x100000A9 #define hpXK_mute_asciicircum 0x100000AA #define hpXK_mute_diaeresis 0x100000AB #define hpXK_mute_asciitilde 0x100000AC #define hpXK_lira 0x100000AF #define hpXK_guilder 0x100000BE #define hpXK_Ydiaeresis 0x100000EE #define hpXK_IO 0x100000EE #define hpXK_longminus 0x100000F6 #define hpXK_block 0x100000FC #ifndef _OSF_Keysyms #define _OSF_Keysyms #define osfXK_Copy 0x1004FF02 #define osfXK_Cut 0x1004FF03 #define osfXK_Paste 0x1004FF04 #define osfXK_BackTab 0x1004FF07 #define osfXK_BackSpace 0x1004FF08 #define osfXK_Clear 0x1004FF0B #define osfXK_Escape 0x1004FF1B #define osfXK_AddMode 0x1004FF31 #define osfXK_PrimaryPaste 0x1004FF32 #define osfXK_QuickPaste 0x1004FF33 #define osfXK_PageLeft 0x1004FF40 #define osfXK_PageUp 0x1004FF41 #define osfXK_PageDown 0x1004FF42 #define osfXK_PageRight 0x1004FF43 #define osfXK_Activate 0x1004FF44 #define osfXK_MenuBar 0x1004FF45 #define osfXK_Left 0x1004FF51 #define osfXK_Up 0x1004FF52 #define osfXK_Right 0x1004FF53 #define osfXK_Down 0x1004FF54 #define osfXK_EndLine 0x1004FF57 #define osfXK_BeginLine 0x1004FF58 #define osfXK_EndData 0x1004FF59 #define osfXK_BeginData 0x1004FF5A #define osfXK_PrevMenu 0x1004FF5B #define osfXK_NextMenu 0x1004FF5C #define osfXK_PrevField 0x1004FF5D #define osfXK_NextField 0x1004FF5E #define osfXK_Select 0x1004FF60 #define osfXK_Insert 0x1004FF63 #define osfXK_Undo 0x1004FF65 #define osfXK_Menu 0x1004FF67 #define osfXK_Cancel 0x1004FF69 #define osfXK_Help 0x1004FF6A #define osfXK_SelectAll 0x1004FF71 #define osfXK_DeselectAll 0x1004FF72 #define osfXK_Reselect 0x1004FF73 #define osfXK_Extend 0x1004FF74 #define osfXK_Restore 0x1004FF78 #define osfXK_Delete 0x1004FFFF #endif /* _OSF_Keysyms */ /************************************************************** * The use of the following macros is deprecated. * They are listed below only for backwards compatibility. */ #define XK_Reset 0x1000FF6C #define XK_System 0x1000FF6D #define XK_User 0x1000FF6E #define XK_ClearLine 0x1000FF6F #define XK_InsertLine 0x1000FF70 #define XK_DeleteLine 0x1000FF71 #define XK_InsertChar 0x1000FF72 #define XK_DeleteChar 0x1000FF73 #define XK_BackTab 0x1000FF74 #define XK_KP_BackTab 0x1000FF75 #define XK_Ext16bit_L 0x1000FF76 #define XK_Ext16bit_R 0x1000FF77 #define XK_mute_acute 0x100000a8 #define XK_mute_grave 0x100000a9 #define XK_mute_asciicircum 0x100000aa #define XK_mute_diaeresis 0x100000ab #define XK_mute_asciitilde 0x100000ac #define XK_lira 0x100000af #define XK_guilder 0x100000be #ifndef XK_Ydiaeresis #define XK_Ydiaeresis 0x100000ee #endif #define XK_IO 0x100000ee #define XK_longminus 0x100000f6 #define XK_block 0x100000fc #endif /* _HPKEYSYM_H */ X11/Xregion.h000064400000013475151027430550006715 0ustar00/************************************************************************ Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ************************************************************************/ #ifndef _X11_XREGION_H_ #define _X11_XREGION_H_ typedef struct { short x1, x2, y1, y2; } Box, BOX, BoxRec, *BoxPtr; typedef struct { short x, y, width, height; }RECTANGLE, RectangleRec, *RectanglePtr; #define TRUE 1 #define FALSE 0 #define MAXSHORT 32767 #define MINSHORT -MAXSHORT #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif /* * clip region */ typedef struct _XRegion { long size; long numRects; BOX *rects; BOX extents; } REGION; /* Xutil.h contains the declaration: * typedef struct _XRegion *Region; */ /* 1 if two BOXs overlap. * 0 if two BOXs do not overlap. * Remember, x2 and y2 are not in the region */ #define EXTENTCHECK(r1, r2) \ ((r1)->x2 > (r2)->x1 && \ (r1)->x1 < (r2)->x2 && \ (r1)->y2 > (r2)->y1 && \ (r1)->y1 < (r2)->y2) /* * update region extents */ #define EXTENTS(r,idRect){\ if((r)->x1 < (idRect)->extents.x1)\ (idRect)->extents.x1 = (r)->x1;\ if((r)->y1 < (idRect)->extents.y1)\ (idRect)->extents.y1 = (r)->y1;\ if((r)->x2 > (idRect)->extents.x2)\ (idRect)->extents.x2 = (r)->x2;\ if((r)->y2 > (idRect)->extents.y2)\ (idRect)->extents.y2 = (r)->y2;\ } /* * Check to see if there is enough memory in the present region. */ #define MEMCHECK(reg, rect, firstrect){\ if ((reg)->numRects >= ((reg)->size - 1)){\ BoxPtr tmpRect = Xrealloc ((firstrect), \ (2 * (sizeof(BOX)) * ((reg)->size))); \ if (tmpRect == NULL) \ return(0);\ (firstrect) = tmpRect; \ (reg)->size *= 2;\ (rect) = &(firstrect)[(reg)->numRects];\ }\ } /* this routine checks to see if the previous rectangle is the same * or subsumes the new rectangle to add. */ #define CHECK_PREVIOUS(Reg, R, Rx1, Ry1, Rx2, Ry2)\ (!(((Reg)->numRects > 0)&&\ ((R-1)->y1 == (Ry1)) &&\ ((R-1)->y2 == (Ry2)) &&\ ((R-1)->x1 <= (Rx1)) &&\ ((R-1)->x2 >= (Rx2)))) /* add a rectangle to the given Region */ #define ADDRECT(reg, r, rx1, ry1, rx2, ry2){\ if (((rx1) < (rx2)) && ((ry1) < (ry2)) &&\ CHECK_PREVIOUS((reg), (r), (rx1), (ry1), (rx2), (ry2))){\ (r)->x1 = (rx1);\ (r)->y1 = (ry1);\ (r)->x2 = (rx2);\ (r)->y2 = (ry2);\ EXTENTS((r), (reg));\ (reg)->numRects++;\ (r)++;\ }\ } /* add a rectangle to the given Region */ #define ADDRECTNOX(reg, r, rx1, ry1, rx2, ry2){\ if ((rx1 < rx2) && (ry1 < ry2) &&\ CHECK_PREVIOUS((reg), (r), (rx1), (ry1), (rx2), (ry2))){\ (r)->x1 = (rx1);\ (r)->y1 = (ry1);\ (r)->x2 = (rx2);\ (r)->y2 = (ry2);\ (reg)->numRects++;\ (r)++;\ }\ } #define EMPTY_REGION(pReg) pReg->numRects = 0 #define REGION_NOT_EMPTY(pReg) pReg->numRects #define INBOX(r, x, y) \ ( ( ((r).x2 > x)) && \ ( ((r).x1 <= x)) && \ ( ((r).y2 > y)) && \ ( ((r).y1 <= y)) ) /* * number of points to buffer before sending them off * to scanlines() : Must be an even number */ #define NUMPTSTOBUFFER 200 /* * used to allocate buffers for points and link * the buffers together */ typedef struct _POINTBLOCK { XPoint pts[NUMPTSTOBUFFER]; struct _POINTBLOCK *next; } POINTBLOCK; #endif /* _X11_XREGION_H_ */ X11/Sunkeysym.h000064400000007666151027430550007316 0ustar00/* * Copyright (c) 1991, Oracle and/or its affiliates. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /************************************************************ Copyright 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ***********************************************************/ /* * Floating Accent */ #define SunXK_FA_Grave 0x1005FF00 #define SunXK_FA_Circum 0x1005FF01 #define SunXK_FA_Tilde 0x1005FF02 #define SunXK_FA_Acute 0x1005FF03 #define SunXK_FA_Diaeresis 0x1005FF04 #define SunXK_FA_Cedilla 0x1005FF05 /* * Miscellaneous Functions */ #define SunXK_F36 0x1005FF10 /* Labeled F11 */ #define SunXK_F37 0x1005FF11 /* Labeled F12 */ #define SunXK_Sys_Req 0x1005FF60 #define SunXK_Print_Screen 0x0000FF61 /* Same as XK_Print */ /* * International & Multi-Key Character Composition */ #define SunXK_Compose 0x0000FF20 /* Same as XK_Multi_key */ #define SunXK_AltGraph 0x0000FF7E /* Same as XK_Mode_switch */ /* * Cursor Control */ #define SunXK_PageUp 0x0000FF55 /* Same as XK_Prior */ #define SunXK_PageDown 0x0000FF56 /* Same as XK_Next */ /* * Open Look Functions */ #define SunXK_Undo 0x0000FF65 /* Same as XK_Undo */ #define SunXK_Again 0x0000FF66 /* Same as XK_Redo */ #define SunXK_Find 0x0000FF68 /* Same as XK_Find */ #define SunXK_Stop 0x0000FF69 /* Same as XK_Cancel */ #define SunXK_Props 0x1005FF70 #define SunXK_Front 0x1005FF71 #define SunXK_Copy 0x1005FF72 #define SunXK_Open 0x1005FF73 #define SunXK_Paste 0x1005FF74 #define SunXK_Cut 0x1005FF75 #define SunXK_PowerSwitch 0x1005FF76 #define SunXK_AudioLowerVolume 0x1005FF77 #define SunXK_AudioMute 0x1005FF78 #define SunXK_AudioRaiseVolume 0x1005FF79 #define SunXK_VideoDegauss 0x1005FF7A #define SunXK_VideoLowerBrightness 0x1005FF7B #define SunXK_VideoRaiseBrightness 0x1005FF7C #define SunXK_PowerSwitchShift 0x1005FF7D X11/Xcms.h000064400000051542151027430550006211 0ustar00 /* * Code and supporting documentation (c) Copyright 1990 1991 Tektronix, Inc. * All Rights Reserved * * This file is a component of an X Window System-specific implementation * of Xcms based on the TekColor Color Management System. Permission is * hereby granted to use, copy, modify, sell, and otherwise distribute this * software and its documentation for any purpose and without fee, provided * that this copyright, permission, and disclaimer notice is reproduced in * all copies of this software and in supporting documentation. TekColor * is a trademark of Tektronix, Inc. * * Tektronix makes no representation about the suitability of this software * for any purpose. It is provided "as is" and with all faults. * * TEKTRONIX DISCLAIMS ALL WARRANTIES APPLICABLE TO THIS SOFTWARE, * INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL TEKTRONIX BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER * RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR THE PERFORMANCE OF THIS SOFTWARE. * * * DESCRIPTION * Public include file for X Color Management System */ #ifndef _X11_XCMS_H_ #define _X11_XCMS_H_ #include /* The Xcms structs are full of implicit padding to properly align members. We can't clean that up without breaking ABI, so tell clang not to bother complaining about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif /* * XCMS Status Values */ #define XcmsFailure 0 #define XcmsSuccess 1 #define XcmsSuccessWithCompression 2 /* * Color Space Format ID's * Color Space ID's are of XcmsColorFormat type. * * bit 31 * 0 == Device-Independent * 1 == Device-Dependent * * bit 30: * 0 == Registered with X Consortium * 1 == Unregistered */ #define XcmsUndefinedFormat (XcmsColorFormat)0x00000000 #define XcmsCIEXYZFormat (XcmsColorFormat)0x00000001 #define XcmsCIEuvYFormat (XcmsColorFormat)0x00000002 #define XcmsCIExyYFormat (XcmsColorFormat)0x00000003 #define XcmsCIELabFormat (XcmsColorFormat)0x00000004 #define XcmsCIELuvFormat (XcmsColorFormat)0x00000005 #define XcmsTekHVCFormat (XcmsColorFormat)0x00000006 #define XcmsRGBFormat (XcmsColorFormat)0x80000000 #define XcmsRGBiFormat (XcmsColorFormat)0x80000001 /* * State of XcmsPerScrnInfo */ #define XcmsInitNone 0x00 /* no initialization attempted */ #define XcmsInitSuccess 0x01 /* initialization successful */ #define XcmsInitFailure 0xff /* failure, use defaults */ #define DisplayOfCCC(ccc) ((ccc)->dpy) #define ScreenNumberOfCCC(ccc) ((ccc)->screenNumber) #define VisualOfCCC(ccc) ((ccc)->visual) #define ClientWhitePointOfCCC(ccc) (&(ccc)->clientWhitePt) #define ScreenWhitePointOfCCC(ccc) (&(ccc)->pPerScrnInfo->screenWhitePt) #define FunctionSetOfCCC(ccc) ((ccc)->pPerScrnInfo->functionSet) typedef unsigned long XcmsColorFormat; /* Color Space Format ID */ typedef double XcmsFloat; /* * Device RGB */ typedef struct { unsigned short red; /* scaled from 0x0000 to 0xffff */ unsigned short green; /* scaled from 0x0000 to 0xffff */ unsigned short blue; /* scaled from 0x0000 to 0xffff */ } XcmsRGB; /* * RGB Intensity */ typedef struct { XcmsFloat red; /* 0.0 - 1.0 */ XcmsFloat green; /* 0.0 - 1.0 */ XcmsFloat blue; /* 0.0 - 1.0 */ } XcmsRGBi; /* * CIE XYZ */ typedef struct { XcmsFloat X; XcmsFloat Y; XcmsFloat Z; } XcmsCIEXYZ; /* * CIE u'v'Y */ typedef struct { XcmsFloat u_prime; /* 0.0 - 1.0 */ XcmsFloat v_prime; /* 0.0 - 1.0 */ XcmsFloat Y; /* 0.0 - 1.0 */ } XcmsCIEuvY; /* * CIE xyY */ typedef struct { XcmsFloat x; /* 0.0 - 1.0 */ XcmsFloat y; /* 0.0 - 1.0 */ XcmsFloat Y; /* 0.0 - 1.0 */ } XcmsCIExyY; /* * CIE L*a*b* */ typedef struct { XcmsFloat L_star; /* 0.0 - 100.0 */ XcmsFloat a_star; XcmsFloat b_star; } XcmsCIELab; /* * CIE L*u*v* */ typedef struct { XcmsFloat L_star; /* 0.0 - 100.0 */ XcmsFloat u_star; XcmsFloat v_star; } XcmsCIELuv; /* * TekHVC */ typedef struct { XcmsFloat H; /* 0.0 - 360.0 */ XcmsFloat V; /* 0.0 - 100.0 */ XcmsFloat C; /* 0.0 - 100.0 */ } XcmsTekHVC; /* * PAD */ typedef struct { XcmsFloat pad0; XcmsFloat pad1; XcmsFloat pad2; XcmsFloat pad3; } XcmsPad; /* * XCMS Color Structure */ typedef struct { union { XcmsRGB RGB; XcmsRGBi RGBi; XcmsCIEXYZ CIEXYZ; XcmsCIEuvY CIEuvY; XcmsCIExyY CIExyY; XcmsCIELab CIELab; XcmsCIELuv CIELuv; XcmsTekHVC TekHVC; XcmsPad Pad; } spec; /* the color specification */ unsigned long pixel; /* pixel value (as needed) */ XcmsColorFormat format; /* the specification format */ } XcmsColor; /* * XCMS Per Screen related data */ typedef struct _XcmsPerScrnInfo { XcmsColor screenWhitePt; /* Screen White point */ XPointer functionSet; /* pointer to Screen Color Characterization */ /* Function Set structure */ XPointer screenData; /* pointer to corresponding Screen Color*/ /* Characterization Data */ unsigned char state; /* XcmsInitNone, XcmsInitSuccess, XcmsInitFailure */ char pad[3]; } XcmsPerScrnInfo; typedef struct _XcmsCCC *XcmsCCC; typedef Status (*XcmsCompressionProc)( /* Gamut Compression Proc */ XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); typedef Status (*XcmsWhiteAdjustProc)( /* White Point Adjust Proc */ XcmsCCC /* ccc */, XcmsColor* /* initial_white_point*/, XcmsColor* /* target_white_point*/, XcmsColorFormat /* target_format */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); /* * XCMS Color Conversion Context */ typedef struct _XcmsCCC { Display *dpy; /* X Display */ int screenNumber; /* X screen number */ Visual *visual; /* X Visual */ XcmsColor clientWhitePt; /* Client White Point */ XcmsCompressionProc gamutCompProc; /* Gamut Compression Function */ XPointer gamutCompClientData; /* Gamut Comp Func Client Data */ XcmsWhiteAdjustProc whitePtAdjProc; /* White Point Adjustment Function */ XPointer whitePtAdjClientData; /* White Pt Adj Func Client Data */ XcmsPerScrnInfo *pPerScrnInfo; /* pointer to per screen information */ /* associated with the above display */ /* screenNumber */ } XcmsCCCRec; typedef Status (*XcmsScreenInitProc)( /* Screen Initialization Proc */ Display* /* dpy */, int /* screen_number */, XcmsPerScrnInfo* /* screen_info */ ); typedef void (*XcmsScreenFreeProc)( XPointer /* screenData */ ); /* * Function List Pointer -- pointer to an array of function pointers. * The end of list is indicated by a NULL pointer. */ /* * XXX: The use of the XcmsConversionProc type is broken. The * device-independent colour conversion code uses it as: typedef Status (*XcmsConversionProc)(XcmsCCC, XcmsColor *, XcmsColor *, unsigned int); * while the device-dependent code uses it as: typedef Status (*XcmsConversionProc)(XcmsCCC, XcmsColor *, unsigned int, Bool *); * Until this is reworked, it's probably best to leave it unprotoized. * The code works regardless. */ typedef Status (*XcmsDDConversionProc)( /* using device-dependent version */ XcmsCCC /* ccc */, XcmsColor* /* pcolors_in_out */, unsigned int /* ncolors */, Bool* /* pCompressed */ ); typedef Status (*XcmsDIConversionProc)( /* using device-independent version */ XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* pcolors_in_out */, unsigned int /* ncolors */ ); typedef XcmsDIConversionProc XcmsConversionProc; typedef XcmsConversionProc *XcmsFuncListPtr; typedef int (*XcmsParseStringProc)( /* Color String Parsing Proc */ char* /* color_string */, XcmsColor* /* color_return */ ); /* * Color Space -- per Color Space related data (Device-Independent * or Device-Dependent) */ typedef struct _XcmsColorSpace { const char *prefix; /* Prefix of string format. */ XcmsColorFormat id; /* Format ID number. */ XcmsParseStringProc parseString; /* String format parsing function */ XcmsFuncListPtr to_CIEXYZ; /* Pointer to an array of function */ /* pointers such that when the */ /* functions are executed in sequence */ /* will convert a XcmsColor structure */ /* from this color space to CIEXYZ */ /* space. */ XcmsFuncListPtr from_CIEXYZ;/* Pointer to an array of function */ /* pointers such that when the */ /* functions are executed in sequence */ /* will convert a XcmsColor structure */ /* from CIEXYZ space to this color */ /* space. */ int inverse_flag; /* If 1, indicates that for 0 <= i < n */ /* where n is the number of function */ /* pointers in the lists to_CIEXYZ */ /* and from_CIEXYZ; for each function */ /* to_CIEXYZ[i] its inverse function */ /* is from_CIEXYZ[n - i]. */ } XcmsColorSpace; /* * Screen Color Characterization Function Set -- per device class * color space conversion functions. */ typedef struct _XcmsFunctionSet { XcmsColorSpace **DDColorSpaces; /* Pointer to an array of pointers to */ /* Device-DEPENDENT color spaces */ /* understood by this SCCFuncSet. */ XcmsScreenInitProc screenInitProc; /* Screen initialization function that */ /* reads Screen Color Characterization*/ /* Data off properties on the screen's*/ /* root window. */ XcmsScreenFreeProc screenFreeProc; /* Function that frees the SCCData */ /* structures. */ } XcmsFunctionSet; _XFUNCPROTOBEGIN extern Status XcmsAddColorSpace ( XcmsColorSpace* /* pColorSpace */ ); extern Status XcmsAddFunctionSet ( XcmsFunctionSet* /* functionSet */ ); extern Status XcmsAllocColor ( Display* /* dpy */, Colormap /* colormap */, XcmsColor* /* color_in_out */, XcmsColorFormat /* result_format */ ); extern Status XcmsAllocNamedColor ( Display* /* dpy */, Colormap /* colormap */, _Xconst char* /* color_string */, XcmsColor* /* color_scrn_return */, XcmsColor* /* color_exact_return */, XcmsColorFormat /* result_format */ ); extern XcmsCCC XcmsCCCOfColormap ( Display* /* dpy */, Colormap /* colormap */ ); extern Status XcmsCIELabClipab( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELabClipL( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELabClipLab( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELabQueryMaxC ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsFloat /* L_star */, XcmsColor* /* color_return */ ); extern Status XcmsCIELabQueryMaxL ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsFloat /* chroma */, XcmsColor* /* color_return */ ); extern Status XcmsCIELabQueryMaxLC ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsColor* /* color_return */ ); extern Status XcmsCIELabQueryMinL ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsFloat /* chroma */, XcmsColor* /* color_return */ ); extern Status XcmsCIELabToCIEXYZ ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIELabWhiteShiftColors( XcmsCCC /* ccc */, XcmsColor* /* initial_white_point*/, XcmsColor* /* target_white_point*/, XcmsColorFormat /* target_format */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELuvClipL( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELuvClipLuv( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELuvClipuv( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsCIELuvQueryMaxC ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsFloat /* L_star */, XcmsColor* /* color_return */ ); extern Status XcmsCIELuvQueryMaxL ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsFloat /* chroma */, XcmsColor* /* color_return */ ); extern Status XcmsCIELuvQueryMaxLC ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsColor* /* color_return */ ); extern Status XcmsCIELuvQueryMinL ( XcmsCCC /* ccc */, XcmsFloat /* hue_angle */, XcmsFloat /* chroma */, XcmsColor* /* color_return */ ); extern Status XcmsCIELuvToCIEuvY ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIELuvWhiteShiftColors( XcmsCCC /* ccc */, XcmsColor* /* initial_white_point*/, XcmsColor* /* target_white_point*/, XcmsColorFormat /* target_format */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern Status XcmsCIEXYZToCIELab ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIEXYZToCIEuvY ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIEXYZToCIExyY ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIEXYZToRGBi ( XcmsCCC /* ccc */, XcmsColor* /* colors */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern Status XcmsCIEuvYToCIELuv ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIEuvYToCIEXYZ ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIEuvYToTekHVC ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsCIExyYToCIEXYZ ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern XcmsColor *XcmsClientWhitePointOfCCC ( XcmsCCC /* ccc */ ); extern Status XcmsConvertColors ( XcmsCCC /* ccc */, XcmsColor* /* colorArry_in_out */, unsigned int /* nColors */, XcmsColorFormat /* targetFormat */, Bool* /* compArry_return */ ); extern XcmsCCC XcmsCreateCCC ( Display* /* dpy */, int /* screenNumber */, Visual* /* visual */, XcmsColor* /* clientWhitePt */, XcmsCompressionProc /* gamutCompProc */, XPointer /* gamutCompClientData */, XcmsWhiteAdjustProc /* whitePtAdjProc */, XPointer /* whitePtAdjClientData */ ); extern XcmsCCC XcmsDefaultCCC ( Display* /* dpy */, int /* screenNumber */ ); extern Display *XcmsDisplayOfCCC ( XcmsCCC /* ccc */ ); extern XcmsColorFormat XcmsFormatOfPrefix ( char* /* prefix */ ); extern void XcmsFreeCCC ( XcmsCCC /* ccc */ ); extern Status XcmsLookupColor ( Display* /* dpy */, Colormap /* colormap */, _Xconst char* /* color_string */, XcmsColor* /* pColor_exact_in_out */, XcmsColor* /* pColor_scrn_in_out */, XcmsColorFormat /* result_format */ ); extern char *XcmsPrefixOfFormat ( XcmsColorFormat /* id */ ); extern Status XcmsQueryBlack ( XcmsCCC /* ccc */, XcmsColorFormat /* target_format */, XcmsColor* /* color_return */ ); extern Status XcmsQueryBlue ( XcmsCCC /* ccc */, XcmsColorFormat /* target_format */, XcmsColor* /* color_return */ ); extern Status XcmsQueryColor ( Display* /* dpy */, Colormap /* colormap */, XcmsColor* /* pColor_in_out */, XcmsColorFormat /* result_format */ ); extern Status XcmsQueryColors ( Display* /* dpy */, Colormap /* colormap */, XcmsColor* /* colorArry_in_out */, unsigned int /* nColors */, XcmsColorFormat /* result_format */ ); extern Status XcmsQueryGreen ( XcmsCCC /* ccc */, XcmsColorFormat /* target_format */, XcmsColor* /* color_return */ ); extern Status XcmsQueryRed ( XcmsCCC /* ccc */, XcmsColorFormat /* target_format */, XcmsColor* /* color_return */ ); extern Status XcmsQueryWhite ( XcmsCCC /* ccc */, XcmsColorFormat /* target_format */, XcmsColor* /* color_return */ ); extern Status XcmsRGBiToCIEXYZ ( XcmsCCC /* ccc */, XcmsColor* /* colors */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern Status XcmsRGBiToRGB ( XcmsCCC /* ccc */, XcmsColor* /* colors */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern Status XcmsRGBToRGBi ( XcmsCCC /* ccc */, XcmsColor* /* colors */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern int XcmsScreenNumberOfCCC ( XcmsCCC /* ccc */ ); extern XcmsColor *XcmsScreenWhitePointOfCCC ( XcmsCCC /* ccc */ ); extern XcmsCCC XcmsSetCCCOfColormap( Display* /* dpy */, Colormap /* colormap */, XcmsCCC /* ccc */ ); extern XcmsCompressionProc XcmsSetCompressionProc ( XcmsCCC /* ccc */, XcmsCompressionProc /* compression_proc */, XPointer /* client_data */ ); extern XcmsWhiteAdjustProc XcmsSetWhiteAdjustProc ( XcmsCCC /* ccc */, XcmsWhiteAdjustProc /* white_adjust_proc */, XPointer /* client_data */ ); extern Status XcmsSetWhitePoint ( XcmsCCC /* ccc */, XcmsColor* /* color */ ); extern Status XcmsStoreColor ( Display* /* dpy */, Colormap /* colormap */, XcmsColor* /* pColor_in */ ); extern Status XcmsStoreColors ( Display* /* dpy */, Colormap /* colormap */, XcmsColor* /* colorArry_in */, unsigned int /* nColors */, Bool* /* compArry_return */ ); extern Status XcmsTekHVCClipC( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsTekHVCClipV( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsTekHVCClipVC( XcmsCCC /* ccc */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, unsigned int /* index */, Bool* /* compression_flags_return */ ); extern Status XcmsTekHVCQueryMaxC ( XcmsCCC /* ccc */, XcmsFloat /* hue */, XcmsFloat /* value */, XcmsColor* /* color_return */ ); extern Status XcmsTekHVCQueryMaxV ( XcmsCCC /* ccc */, XcmsFloat /* hue */, XcmsFloat /* chroma */, XcmsColor* /* color_return */ ); extern Status XcmsTekHVCQueryMaxVC ( XcmsCCC /* ccc */, XcmsFloat /* hue */, XcmsColor* /* color_return */ ); extern Status XcmsTekHVCQueryMaxVSamples ( XcmsCCC /* ccc */, XcmsFloat /* hue */, XcmsColor* /* colors_return */, unsigned int /* nsamples */ ); extern Status XcmsTekHVCQueryMinV ( XcmsCCC /* ccc */, XcmsFloat /* hue */, XcmsFloat /* chroma */, XcmsColor* /* color_return */ ); extern Status XcmsTekHVCToCIEuvY ( XcmsCCC /* ccc */, XcmsColor* /* white_point */, XcmsColor* /* colors */, unsigned int /* ncolors */ ); extern Status XcmsTekHVCWhiteShiftColors( XcmsCCC /* ccc */, XcmsColor* /* initial_white_point*/, XcmsColor* /* target_white_point*/, XcmsColorFormat /* target_format */, XcmsColor* /* colors_in_out */, unsigned int /* ncolors */, Bool* /* compression_flags_return */ ); extern Visual *XcmsVisualOfCCC ( XcmsCCC /* ccc */ ); #ifdef __clang__ #pragma clang diagnostic pop #endif _XFUNCPROTOEND #endif /* _X11_XCMS_H_ */ X11/Xdefs.h000064400000004541151027430550006345 0ustar00/*********************************************************** Copyright (c) 1999 The XFree86 Project Inc. All Rights Reserved. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The XFree86 Project Inc. shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The XFree86 Project Inc.. */ /** ** Types definitions shared between server and clients **/ #ifndef _XDEFS_H #define _XDEFS_H #ifdef _XSERVER64 #include #endif #ifndef _XTYPEDEF_ATOM # define _XTYPEDEF_ATOM # ifndef _XSERVER64 typedef unsigned long Atom; # else typedef CARD32 Atom; # endif #endif #ifndef Bool # ifndef _XTYPEDEF_BOOL # define _XTYPEDEF_BOOL typedef int Bool; # endif #endif #ifndef _XTYPEDEF_POINTER # define _XTYPEDEF_POINTER typedef void *pointer; #endif #ifndef _XTYPEDEF_CLIENTPTR typedef struct _Client *ClientPtr; # define _XTYPEDEF_CLIENTPTR #endif #ifndef _XTYPEDEF_XID # define _XTYPEDEF_XID # ifndef _XSERVER64 typedef unsigned long XID; # else typedef CARD32 XID; # endif #endif #ifndef _XTYPEDEF_MASK # define _XTYPEDEF_MASK # ifndef _XSERVER64 typedef unsigned long Mask; # else typedef CARD32 Mask; # endif #endif #ifndef _XTYPEDEF_FONTPTR # define _XTYPEDEF_FONTPTR typedef struct _Font *FontPtr; /* also in fonts/include/font.h */ #endif #ifndef _XTYPEDEF_FONT # define _XTYPEDEF_FONT typedef XID Font; #endif #ifndef _XTYPEDEF_FSID # ifndef _XSERVER64 typedef unsigned long FSID; # else typedef CARD32 FSID; # endif #endif typedef FSID AccContext; /* OS independent time value XXX Should probably go in Xos.h */ typedef struct timeval **OSTimePtr; typedef void (* BlockHandlerProcPtr)(void * /* blockData */, OSTimePtr /* pTimeout */, void * /* pReadmask */); #endif X11/keysym.h000064400000005321151027430550006612 0ustar00/*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* default keysyms */ #define XK_MISCELLANY #define XK_XKB_KEYS #define XK_LATIN1 #define XK_LATIN2 #define XK_LATIN3 #define XK_LATIN4 #define XK_LATIN8 #define XK_LATIN9 #define XK_CAUCASUS #define XK_GREEK #define XK_KATAKANA #define XK_ARABIC #define XK_CYRILLIC #define XK_HEBREW #define XK_THAI #define XK_KOREAN #define XK_ARMENIAN #define XK_GEORGIAN #define XK_VIETNAMESE #define XK_CURRENCY #define XK_MATHEMATICAL #define XK_BRAILLE #define XK_SINHALA #include X11/Xos_r.h000064400000101635151027430550006370 0ustar00/* Copyright 1996, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * Various and sundry Thread-Safe functions used by X11, Motif, and CDE. * * Use this file in MT-safe code where you would have included * for readdir() * for getgrgid() or getgrnam() * for gethostbyname(), gethostbyaddr(), or getservbyname() * for getpwnam() or getpwuid() * for strtok() * for asctime(), ctime(), localtime(), or gmtime() * for getlogin() or ttyname() * or their thread-safe analogs. * * If you are on a platform that defines XTHREADS but does not have * MT-safe system API (e.g. UnixWare) you must define _Xos_processLock * and _Xos_processUnlock macros before including this header. * * For convenience XOS_USE_XLIB_LOCKING or XOS_USE_XT_LOCKING may be defined * to obtain either Xlib-only or Xt-based versions of these macros. These * macros won't result in truly thread-safe calls, but they are better than * nothing. If you do not want locking in this situation define * XOS_USE_NO_LOCKING. * * NOTE: On systems lacking appropriate _r functions Gethostbyname(), * Gethostbyaddr(), and Getservbyname() do NOT copy the host or * protocol lists! * * NOTE: On systems lacking appropriate _r functions Getgrgid() and * Getgrnam() do NOT copy the list of group members! * * This header is nominally intended to simplify porting X11, Motif, and * CDE; it may be useful to other people too. The structure below is * complicated, mostly because P1003.1c (the IEEE POSIX Threads spec) * went through lots of drafts, and some vendors shipped systems based * on draft API that were changed later. Unfortunately POSIX did not * provide a feature-test macro for distinguishing each of the drafts. */ /* * This header has several parts. Search for "Effective prototypes" * to locate the beginning of a section. */ /* This header can be included multiple times with different defines! */ #ifndef _XOS_R_H_ # define _XOS_R_H_ # include # include # ifndef X_NOT_POSIX # ifdef _POSIX_SOURCE # include # else # define _POSIX_SOURCE # include # undef _POSIX_SOURCE # endif # ifndef LINE_MAX # define X_LINE_MAX 2048 # else # define X_LINE_MAX LINE_MAX # endif # endif #endif /* _XOS_R_H */ #ifndef WIN32 #ifdef __cplusplus extern "C" { #endif # if defined(XOS_USE_XLIB_LOCKING) # ifndef XAllocIDs /* Xlibint.h does not have multiple include protection */ typedef struct _LockInfoRec *LockInfoPtr; extern LockInfoPtr _Xglobal_lock; # endif # ifndef _Xos_isThreadInitialized # define _Xos_isThreadInitialized (_Xglobal_lock) # endif # if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE) # ifndef XAllocIDs /* Xlibint.h does not have multiple include protection */ # include /* for NeedFunctionPrototypes */ extern void (*_XLockMutex_fn)( # if NeedFunctionPrototypes LockInfoPtr /* lock */, char * /* file */, int /* line */ # endif ); extern void (*_XUnlockMutex_fn)( # if NeedFunctionPrototypes LockInfoPtr /* lock */, char * /* file */, int /* line */ # endif ); # endif # ifndef _Xos_processLock # define _Xos_processLock \ (_XLockMutex_fn ? (*_XLockMutex_fn)(_Xglobal_lock,__FILE__,__LINE__) : 0) # endif # ifndef _Xos_processUnlock # define _Xos_processUnlock \ (_XUnlockMutex_fn ? (*_XUnlockMutex_fn)(_Xglobal_lock,__FILE__,__LINE__) : 0) # endif # else # ifndef XAllocIDs /* Xlibint.h does not have multiple include protection */ # include /* for NeedFunctionPrototypes */ extern void (*_XLockMutex_fn)( # if NeedFunctionPrototypes LockInfoPtr /* lock */ # endif ); extern void (*_XUnlockMutex_fn)( # if NeedFunctionPrototypes LockInfoPtr /* lock */ # endif ); # endif # ifndef _Xos_processLock # define _Xos_processLock \ (_XLockMutex_fn ? ((*_XLockMutex_fn)(_Xglobal_lock), 0) : 0) # endif # ifndef _Xos_processUnlock # define _Xos_processUnlock \ (_XUnlockMutex_fn ? ((*_XUnlockMutex_fn)(_Xglobal_lock), 0) : 0) # endif # endif # elif defined(XOS_USE_XT_LOCKING) # ifndef _XtThreadsI_h extern void (*_XtProcessLock)(void); # endif # ifndef _XtintrinsicP_h # include /* for NeedFunctionPrototypes */ extern void XtProcessLock( # if NeedFunctionPrototypes void # endif ); extern void XtProcessUnlock( # if NeedFunctionPrototypes void # endif ); # endif # ifndef _Xos_isThreadInitialized # define _Xos_isThreadInitialized _XtProcessLock # endif # ifndef _Xos_processLock # define _Xos_processLock XtProcessLock() # endif # ifndef _Xos_processUnlock # define _Xos_processUnlock XtProcessUnlock() # endif # elif defined(XOS_USE_NO_LOCKING) # ifndef _Xos_isThreadInitialized # define _Xos_isThreadInitialized 0 # endif # ifndef _Xos_processLock # define _Xos_processLock 0 # endif # ifndef _Xos_processUnlock # define _Xos_processUnlock 0 # endif # endif #endif /* !defined WIN32 */ /* * Solaris defines the POSIX thread-safe feature test macro, but * uses the older SVR4 thread-safe functions unless the POSIX ones * are specifically requested. Fix the feature test macro. */ #if defined(__sun) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && \ (_POSIX_C_SOURCE - 0 < 199506L) && !defined(_POSIX_PTHREAD_SEMANTICS) # undef _POSIX_THREAD_SAFE_FUNCTIONS #endif /***** wrappers *****/ /* * Effective prototypes for wrappers: * * #define X_INCLUDE_PWD_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xgetpwparams; * * struct passwd* _XGetpwnam(const char *name, _Xgetpwparams); * struct passwd* _XGetpwuid(uid_t uid, _Xgetpwparams); */ #if defined(X_INCLUDE_PWD_H) && !defined(_XOS_INCLUDED_PWD_H) # include # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_PWDAPI) # define XOS_USE_MTSAFE_PWDAPI 1 # endif #endif #undef X_NEEDS_PWPARAMS #if !defined(X_INCLUDE_PWD_H) || defined(_XOS_INCLUDED_PWD_H) /* Do nothing */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ # if defined(X_NOT_POSIX) && !defined(__i386__) && !defined(SYSV) extern struct passwd *getpwuid(), *getpwnam(); # endif typedef int _Xgetpwparams; /* dummy */ # define _XGetpwuid(u,p) getpwuid((u)) # define _XGetpwnam(u,p) getpwnam((u)) #elif !defined(XOS_USE_MTSAFE_PWDAPI) || defined(XNO_MTSAFE_PWDAPI) /* UnixWare 2.0, or other systems with thread support but no _r API. */ # define X_NEEDS_PWPARAMS typedef struct { struct passwd pws; char pwbuf[1024]; struct passwd* pwp; size_t len; } _Xgetpwparams; /* * NetBSD and FreeBSD, at least, are missing several of the unixware passwd * fields. */ #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \ defined(__APPLE__) || defined(__DragonFly__) static __inline__ void _Xpw_copyPasswd(_Xgetpwparams p) { memcpy(&(p).pws, (p).pwp, sizeof(struct passwd)); (p).pws.pw_name = (p).pwbuf; (p).len = strlen((p).pwp->pw_name); strcpy((p).pws.pw_name, (p).pwp->pw_name); (p).pws.pw_passwd = (p).pws.pw_name + (p).len + 1; (p).len = strlen((p).pwp->pw_passwd); strcpy((p).pws.pw_passwd,(p).pwp->pw_passwd); (p).pws.pw_class = (p).pws.pw_passwd + (p).len + 1; (p).len = strlen((p).pwp->pw_class); strcpy((p).pws.pw_class, (p).pwp->pw_class); (p).pws.pw_gecos = (p).pws.pw_class + (p).len + 1; (p).len = strlen((p).pwp->pw_gecos); strcpy((p).pws.pw_gecos, (p).pwp->pw_gecos); (p).pws.pw_dir = (p).pws.pw_gecos + (p).len + 1; (p).len = strlen((p).pwp->pw_dir); strcpy((p).pws.pw_dir, (p).pwp->pw_dir); (p).pws.pw_shell = (p).pws.pw_dir + (p).len + 1; (p).len = strlen((p).pwp->pw_shell); strcpy((p).pws.pw_shell, (p).pwp->pw_shell); (p).pwp = &(p).pws; } #else # define _Xpw_copyPasswd(p) \ (memcpy(&(p).pws, (p).pwp, sizeof(struct passwd)), \ ((p).pws.pw_name = (p).pwbuf), \ ((p).len = strlen((p).pwp->pw_name)), \ strcpy((p).pws.pw_name, (p).pwp->pw_name), \ ((p).pws.pw_passwd = (p).pws.pw_name + (p).len + 1), \ ((p).len = strlen((p).pwp->pw_passwd)), \ strcpy((p).pws.pw_passwd,(p).pwp->pw_passwd), \ ((p).pws.pw_age = (p).pws.pw_passwd + (p).len + 1), \ ((p).len = strlen((p).pwp->pw_age)), \ strcpy((p).pws.pw_age, (p).pwp->pw_age), \ ((p).pws.pw_comment = (p).pws.pw_age + (p).len + 1), \ ((p).len = strlen((p).pwp->pw_comment)), \ strcpy((p).pws.pw_comment, (p).pwp->pw_comment), \ ((p).pws.pw_gecos = (p).pws.pw_comment + (p).len + 1), \ ((p).len = strlen((p).pwp->pw_gecos)), \ strcpy((p).pws.pw_gecos, (p).pwp->pw_gecos), \ ((p).pws.pw_dir = (p).pws.pw_comment + (p).len + 1), \ ((p).len = strlen((p).pwp->pw_dir)), \ strcpy((p).pws.pw_dir, (p).pwp->pw_dir), \ ((p).pws.pw_shell = (p).pws.pw_dir + (p).len + 1), \ ((p).len = strlen((p).pwp->pw_shell)), \ strcpy((p).pws.pw_shell, (p).pwp->pw_shell), \ ((p).pwp = &(p).pws), \ 0 ) #endif # define _XGetpwuid(u,p) \ ( (_Xos_processLock), \ (((p).pwp = getpwuid((u))) ? _Xpw_copyPasswd(p), 0 : 0), \ (_Xos_processUnlock), \ (p).pwp ) # define _XGetpwnam(u,p) \ ( (_Xos_processLock), \ (((p).pwp = getpwnam((u))) ? _Xpw_copyPasswd(p), 0 : 0), \ (_Xos_processUnlock), \ (p).pwp ) #elif !defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(__APPLE__) # define X_NEEDS_PWPARAMS typedef struct { struct passwd pws; char pwbuf[X_LINE_MAX]; } _Xgetpwparams; # if defined(_POSIX_REENTRANT_FUNCTIONS) || !defined(SVR4) # define _XGetpwuid(u,p) \ ((getpwuid_r((u),&(p).pws,(p).pwbuf,sizeof((p).pwbuf)) == -1) ? NULL : &(p).pws) # define _XGetpwnam(u,p) \ ((getpwnam_r((u),&(p).pws,(p).pwbuf,sizeof((p).pwbuf)) == -1) ? NULL : &(p).pws) # else /* SVR4 */ # define _XGetpwuid(u,p) \ ((getpwuid_r((u),&(p).pws,(p).pwbuf,sizeof((p).pwbuf)) == NULL) ? NULL : &(p).pws) # define _XGetpwnam(u,p) \ ((getpwnam_r((u),&(p).pws,(p).pwbuf,sizeof((p).pwbuf)) == NULL) ? NULL : &(p).pws) # endif /* SVR4 */ #else /* _POSIX_THREAD_SAFE_FUNCTIONS */ # define X_NEEDS_PWPARAMS typedef struct { struct passwd pws; char pwbuf[X_LINE_MAX]; struct passwd* pwp; } _Xgetpwparams; typedef int _Xgetpwret; # define _XGetpwuid(u,p) \ ((getpwuid_r((u),&(p).pws,(p).pwbuf,sizeof((p).pwbuf),&(p).pwp) == 0) ? \ (p).pwp : NULL) # define _XGetpwnam(u,p) \ ((getpwnam_r((u),&(p).pws,(p).pwbuf,sizeof((p).pwbuf),&(p).pwp) == 0) ? \ (p).pwp : NULL) #endif /* X_INCLUDE_PWD_H */ #if defined(X_INCLUDE_PWD_H) && !defined(_XOS_INCLUDED_PWD_H) # define _XOS_INCLUDED_PWD_H #endif /***** wrappers *****/ /* * Effective prototypes for wrappers: * * NOTE: On systems lacking the appropriate _r functions Gethostbyname(), * Gethostbyaddr(), and Getservbyname() do NOT copy the host or * protocol lists! * * #define X_INCLUDE_NETDB_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xgethostbynameparams; * typedef ... _Xgetservbynameparams; * * struct hostent* _XGethostbyname(const char* name,_Xgethostbynameparams); * struct hostent* _XGethostbyaddr(const char* addr, int len, int type, * _Xgethostbynameparams); * struct servent* _XGetservbyname(const char* name, const char* proto, * _Xgetservbynameparams); */ #undef XTHREADS_NEEDS_BYNAMEPARAMS #if defined(X_INCLUDE_NETDB_H) && !defined(_XOS_INCLUDED_NETDB_H) \ && !defined(WIN32) # include # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_NETDBAPI) # define XOS_USE_MTSAFE_NETDBAPI 1 # endif #endif #if !defined(X_INCLUDE_NETDB_H) || defined(_XOS_INCLUDED_NETDB_H) /* Do nothing. */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ typedef int _Xgethostbynameparams; /* dummy */ typedef int _Xgetservbynameparams; /* dummy */ # define _XGethostbyname(h,hp) gethostbyname((h)) # define _XGethostbyaddr(a,al,t,hp) gethostbyaddr((a),(al),(t)) # define _XGetservbyname(s,p,sp) getservbyname((s),(p)) #elif !defined(XOS_USE_MTSAFE_NETDBAPI) || defined(XNO_MTSAFE_NETDBAPI) /* WARNING: The h_addr_list and s_aliases values are *not* copied! */ #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__DragonFly__) #include #endif typedef struct { struct hostent hent; char h_name[MAXHOSTNAMELEN]; struct hostent *hptr; } _Xgethostbynameparams; typedef struct { struct servent sent; char s_name[255]; char s_proto[255]; struct servent *sptr; } _Xgetservbynameparams; # define XTHREADS_NEEDS_BYNAMEPARAMS # define _Xg_copyHostent(hp) \ (memcpy(&(hp).hent, (hp).hptr, sizeof(struct hostent)), \ strcpy((hp).h_name, (hp).hptr->h_name), \ ((hp).hent.h_name = (hp).h_name), \ ((hp).hptr = &(hp).hent), \ 0 ) # define _Xg_copyServent(sp) \ (memcpy(&(sp).sent, (sp).sptr, sizeof(struct servent)), \ strcpy((sp).s_name, (sp).sptr->s_name), \ ((sp).sent.s_name = (sp).s_name), \ strcpy((sp).s_proto, (sp).sptr->s_proto), \ ((sp).sent.s_proto = (sp).s_proto), \ ((sp).sptr = &(sp).sent), \ 0 ) # define _XGethostbyname(h,hp) \ ((_Xos_processLock), \ (((hp).hptr = gethostbyname((h))) ? _Xg_copyHostent(hp) : 0), \ (_Xos_processUnlock), \ (hp).hptr ) # define _XGethostbyaddr(a,al,t,hp) \ ((_Xos_processLock), \ (((hp).hptr = gethostbyaddr((a),(al),(t))) ? _Xg_copyHostent(hp) : 0), \ (_Xos_processUnlock), \ (hp).hptr ) # define _XGetservbyname(s,p,sp) \ ((_Xos_processLock), \ (((sp).sptr = getservbyname((s),(p))) ? _Xg_copyServent(sp) : 0), \ (_Xos_processUnlock), \ (sp).sptr ) #elif defined(XUSE_NETDB_R_API) /* * POSIX does not specify _r equivalents for API, but some * vendors provide them anyway. Use them only when explicitly asked. */ # ifdef _POSIX_REENTRANT_FUNCTIONS # ifndef _POSIX_THREAD_SAFE_FUNCTIONS # endif # endif # ifdef _POSIX_THREAD_SAFE_FUNCTIONS # define X_POSIX_THREAD_SAFE_FUNCTIONS 1 # endif # define XTHREADS_NEEDS_BYNAMEPARAMS # ifndef X_POSIX_THREAD_SAFE_FUNCTIONS typedef struct { struct hostent hent; char hbuf[X_LINE_MAX]; int herr; } _Xgethostbynameparams; typedef struct { struct servent sent; char sbuf[X_LINE_MAX]; } _Xgetservbynameparams; # define _XGethostbyname(h,hp) \ gethostbyname_r((h),&(hp).hent,(hp).hbuf,sizeof((hp).hbuf),&(hp).herr) # define _XGethostbyaddr(a,al,t,hp) \ gethostbyaddr_r((a),(al),(t),&(hp).hent,(hp).hbuf,sizeof((hp).hbuf),&(hp).herr) # define _XGetservbyname(s,p,sp) \ getservbyname_r((s),(p),&(sp).sent,(sp).sbuf,sizeof((sp).sbuf)) # else typedef struct { struct hostent hent; struct hostent_data hdata; } _Xgethostbynameparams; typedef struct { struct servent sent; struct servent_data sdata; } _Xgetservbynameparams; # define _XGethostbyname(h,hp) \ (bzero((char*)&(hp).hdata,sizeof((hp).hdata)), \ ((gethostbyname_r((h),&(hp).hent,&(hp).hdata) == -1) ? NULL : &(hp).hent)) # define _XGethostbyaddr(a,al,t,hp) \ (bzero((char*)&(hp).hdata,sizeof((hp).hdata)), \ ((gethostbyaddr_r((a),(al),(t),&(hp).hent,&(hp).hdata) == -1) ? NULL : &(hp).hent)) # define _XGetservbyname(s,p,sp) \ (bzero((char*)&(sp).sdata,sizeof((sp).sdata)), \ ((getservbyname_r((s),(p),&(sp).sent,&(sp).sdata) == -1) ? NULL : &(sp).sent) ) # endif # ifdef X_POSIX_THREAD_SAFE_FUNCTIONS # undef X_POSIX_THREAD_SAFE_FUNCTIONS # endif #else /* The regular API is assumed to be MT-safe under POSIX. */ typedef int _Xgethostbynameparams; /* dummy */ typedef int _Xgetservbynameparams; /* dummy */ # define _XGethostbyname(h,hp) gethostbyname((h)) # define _XGethostbyaddr(a,al,t,hp) gethostbyaddr((a),(al),(t)) # define _XGetservbyname(s,p,sp) getservbyname((s),(p)) #endif /* X_INCLUDE_NETDB_H */ #if defined(X_INCLUDE_NETDB_H) && !defined(_XOS_INCLUDED_NETDB_H) # define _XOS_INCLUDED_NETDB_H #endif /***** wrappers *****/ /* * Effective prototypes for wrappers: * * #define X_INCLUDE_DIRENT_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xreaddirparams; * * struct dirent *_XReaddir(DIR *dir_pointer, _Xreaddirparams); */ #if defined(X_INCLUDE_DIRENT_H) && !defined(_XOS_INCLUDED_DIRENT_H) # include # if !defined(X_NOT_POSIX) || defined(SYSV) # include # else # include # ifndef dirent # define dirent direct # endif # endif # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_DIRENTAPI) # define XOS_USE_MTSAFE_DIRENTAPI 1 # endif #endif #if !defined(X_INCLUDE_DIRENT_H) || defined(_XOS_INCLUDED_DIRENT_H) /* Do nothing. */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ typedef int _Xreaddirparams; /* dummy */ # define _XReaddir(d,p) readdir(d) #elif !defined(XOS_USE_MTSAFE_DIRENTAPI) || defined(XNO_MTSAFE_DIRENTAPI) /* Systems with thread support but no _r API. */ typedef struct { struct dirent *result; struct dirent dir_entry; # ifdef _POSIX_PATH_MAX char buf[_POSIX_PATH_MAX]; # elif defined(NAME_MAX) char buf[NAME_MAX]; # else char buf[255]; # endif } _Xreaddirparams; # define _XReaddir(d,p) \ ( (_Xos_processLock), \ (((p).result = readdir((d))) ? \ (memcpy(&((p).dir_entry), (p).result, (p).result->d_reclen), \ ((p).result = &(p).dir_entry), 0) : \ 0), \ (_Xos_processUnlock), \ (p).result ) #else typedef struct { struct dirent *result; struct dirent dir_entry; # ifdef _POSIX_PATH_MAX char buf[_POSIX_PATH_MAX]; # elif defined(NAME_MAX) char buf[NAME_MAX]; # else char buf[255]; # endif } _Xreaddirparams; # if defined(_POSIX_THREAD_SAFE_FUNCTIONS) || defined(__APPLE__) /* POSIX final API, returns (int)0 on success. */ # define _XReaddir(d,p) \ (readdir_r((d), &((p).dir_entry), &((p).result)) ? NULL : (p).result) # elif defined(_POSIX_REENTRANT_FUNCTIONS) /* POSIX draft API, returns (int)0 on success. */ # define _XReaddir(d,p) \ (readdir_r((d),&((p).dir_entry)) ? NULL : &((p).dir_entry)) # elif defined(SVR4) /* Pre-POSIX API, returns non-NULL on success. */ # define _XReaddir(d,p) (readdir_r((d), &(p).dir_entry)) # else /* We have no idea what is going on. Fake it all using process locks. */ # define _XReaddir(d,p) \ ( (_Xos_processLock), \ (((p).result = readdir((d))) ? \ (memcpy(&((p).dir_entry), (p).result, (p).result->d_reclen), \ ((p).result = &(p).dir_entry), 0) : \ 0), \ (_Xos_processUnlock), \ (p).result ) # endif #endif /* X_INCLUDE_DIRENT_H */ #if defined(X_INCLUDE_DIRENT_H) && !defined(_XOS_INCLUDED_DIRENT_H) # define _XOS_INCLUDED_DIRENT_H #endif /***** wrappers *****/ /* * Effective prototypes for wrappers: * * #define X_INCLUDE_UNISTD_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xgetloginparams; * typedef ... _Xttynameparams; * * char *_XGetlogin(_Xgetloginparams); * char *_XTtyname(int, _Xttynameparams); */ #if defined(X_INCLUDE_UNISTD_H) && !defined(_XOS_INCLUDED_UNISTD_H) /* already included by */ # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_UNISTDAPI) # define XOS_USE_MTSAFE_UNISTDAPI 1 # endif #endif #if !defined(X_INCLUDE_UNISTD_H) || defined(_XOS_INCLUDED_UNISTD_H) /* Do nothing. */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ typedef int _Xgetloginparams; /* dummy */ typedef int _Xttynameparams; /* dummy */ # define _XGetlogin(p) getlogin() # define _XTtyname(f) ttyname((f)) #elif !defined(XOS_USE_MTSAFE_UNISTDAPI) || defined(XNO_MTSAFE_UNISTDAPI) /* Systems with thread support but no _r API. */ typedef struct { char *result; # if defined(MAXLOGNAME) char buf[MAXLOGNAME]; # elif defined(LOGIN_NAME_MAX) char buf[LOGIN_NAME_MAX]; # else char buf[64]; # endif } _Xgetloginparams; typedef struct { char *result; # ifdef TTY_NAME_MAX char buf[TTY_NAME_MAX]; # elif defined(_POSIX_TTY_NAME_MAX) char buf[_POSIX_TTY_NAME_MAX]; # elif defined(_POSIX_PATH_MAX) char buf[_POSIX_PATH_MAX]; # else char buf[256]; # endif } _Xttynameparams; # define _XGetlogin(p) \ ( (_Xos_processLock), \ (((p).result = getlogin()) ? \ (strncpy((p).buf, (p).result, sizeof((p).buf)), \ ((p).buf[sizeof((p).buf)-1] = '\0'), \ ((p).result = (p).buf), 0) : 0), \ (_Xos_processUnlock), \ (p).result ) #define _XTtyname(f,p) \ ( (_Xos_processLock), \ (((p).result = ttyname(f)) ? \ (strncpy((p).buf, (p).result, sizeof((p).buf)), \ ((p).buf[sizeof((p).buf)-1] = '\0'), \ ((p).result = (p).buf), 0) : 0), \ (_Xos_processUnlock), \ (p).result ) #elif defined(_POSIX_THREAD_SAFE_FUNCTIONS) || defined(_POSIX_REENTRANT_FUNCTIONS) /* POSIX API. * * extern int getlogin_r(char *, size_t); * extern int ttyname_r(int, char *, size_t); */ typedef struct { # if defined(MAXLOGNAME) char buf[MAXLOGNAME]; # elif defined(LOGIN_NAME_MAX) char buf[LOGIN_NAME_MAX]; # else char buf[64]; # endif } _Xgetloginparams; typedef struct { # ifdef TTY_NAME_MAX char buf[TTY_NAME_MAX]; # elif defined(_POSIX_TTY_NAME_MAX) char buf[_POSIX_TTY_NAME_MAX]; # elif defined(_POSIX_PATH_MAX) char buf[_POSIX_PATH_MAX]; # else char buf[256]; # endif } _Xttynameparams; # define _XGetlogin(p) (getlogin_r((p).buf, sizeof((p).buf)) ? NULL : (p).buf) # define _XTtyname(f,p) \ (ttyname_r((f), (p).buf, sizeof((p).buf)) ? NULL : (p).buf) #else /* Pre-POSIX API. * * extern char *getlogin_r(char *, size_t); * extern char *ttyname_r(int, char *, size_t); */ typedef struct { # if defined(MAXLOGNAME) char buf[MAXLOGNAME]; # elif defined(LOGIN_NAME_MAX) char buf[LOGIN_NAME_MAX]; # else char buf[64]; # endif } _Xgetloginparams; typedef struct { # ifdef TTY_NAME_MAX char buf[TTY_NAME_MAX]; # elif defined(_POSIX_TTY_NAME_MAX) char buf[_POSIX_TTY_NAME_MAX]; # elif defined(_POSIX_PATH_MAX) char buf[_POSIX_PATH_MAX]; # else char buf[256]; # endif } _Xttynameparams; # define _XGetlogin(p) getlogin_r((p).buf, sizeof((p).buf)) # define _XTtyname(f,p) ttyname_r((f), (p).buf, sizeof((p).buf)) #endif /* X_INCLUDE_UNISTD_H */ #if defined(X_INCLUDE_UNISTD_H) && !defined(_XOS_INCLUDED_UNISTD_H) # define _XOS_INCLUDED_UNISTD_H #endif /***** wrappers *****/ /* * Effective prototypes for wrappers: * * #define X_INCLUDE_STRING_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xstrtokparams; * * char *_XStrtok(char *, const char*, _Xstrtokparams); */ #if defined(X_INCLUDE_STRING_H) && !defined(_XOS_INCLUDED_STRING_H) /* has already been included by */ # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_STRINGAPI) # define XOS_USE_MTSAFE_STRINGAPI 1 # endif #endif #if !defined(X_INCLUDE_STRING_H) || defined(_XOS_INCLUDED_STRING_H) /* Do nothing. */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ typedef int _Xstrtokparams; /* dummy */ # define _XStrtok(s1,s2,p) \ ( p = 0, (void)p, strtok((s1),(s2)) ) #elif !defined(XOS_USE_MTSAFE_STRINGAPI) || defined(XNO_MTSAFE_STRINGAPI) /* Systems with thread support but no _r API. */ typedef char *_Xstrtokparams; # define _XStrtok(s1,s2,p) \ ( (_Xos_processLock), \ ((p) = strtok((s1),(s2))), \ (_Xos_processUnlock), \ (p) ) #else /* POSIX or pre-POSIX API. */ typedef char * _Xstrtokparams; # define _XStrtok(s1,s2,p) strtok_r((s1),(s2),&(p)) #endif /* X_INCLUDE_STRING_H */ /***** wrappers *****/ /* * Effective prototypes for wrappers: * * #define X_INCLUDE_TIME_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xatimeparams; * typedef ... _Xctimeparams; * typedef ... _Xgtimeparams; * typedef ... _Xltimeparams; * * char *_XAsctime(const struct tm *, _Xatimeparams); * char *_XCtime(const time_t *, _Xctimeparams); * struct tm *_XGmtime(const time_t *, _Xgtimeparams); * struct tm *_XLocaltime(const time_t *, _Xltimeparams); */ #if defined(X_INCLUDE_TIME_H) && !defined(_XOS_INCLUDED_TIME_H) # include # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_TIMEAPI) # define XOS_USE_MTSAFE_TIMEAPI 1 # endif #endif #if !defined(X_INCLUDE_TIME_H) || defined(_XOS_INCLUDED_TIME_H) /* Do nothing. */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ typedef int _Xatimeparams; /* dummy */ # define _XAsctime(t,p) asctime((t)) typedef int _Xctimeparams; /* dummy */ # define _XCtime(t,p) ctime((t)) typedef int _Xgtimeparams; /* dummy */ # define _XGmtime(t,p) gmtime((t)) typedef int _Xltimeparams; /* dummy */ # define _XLocaltime(t,p) localtime((t)) #elif !defined(XOS_USE_MTSAFE_TIMEAPI) || defined(XNO_MTSAFE_TIMEAPI) /* Systems with thread support but no _r API. */ typedef struct { # ifdef TIMELEN char buf[TIMELEN]; # else char buf[26]; # endif char *result; } _Xctimeparams, _Xatimeparams; typedef struct { struct tm buf; struct tm *result; } _Xgtimeparams, _Xltimeparams; # define _XAsctime(t,p) \ ( (_Xos_processLock), \ (((p).result = asctime((t))) ? \ (strncpy((p).buf, (p).result, sizeof((p).buf)), (p).result = &(p).buf) : \ 0), \ (_Xos_processUnlock), \ (p).result ) # define _XCtime(t,p) \ ( (_Xos_processLock), \ (((p).result = ctime((t))) ? \ (strncpy((p).buf, (p).result, sizeof((p).buf)), (p).result = &(p).buf) : \ 0), \ (_Xos_processUnlock), \ (p).result ) # define _XGmtime(t,p) \ ( (_Xos_processLock), \ (((p).result = gmtime(t)) ? \ (memcpy(&(p).buf, (p).result, sizeof((p).buf)), (p).result = &(p).buf) : \ 0), \ (_Xos_processUnlock), \ (p).result ) # define _XLocaltime(t,p) \ ( (_Xos_processLock), \ (((p).result = localtime(t)) ? \ (memcpy(&(p).buf, (p).result, sizeof((p).buf)), (p).result = &(p).buf) : \ 0), \ (_Xos_processUnlock), \ (p).result ) #elif !defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(hpV4) /* Returns (int)0 on success. * * extern int asctime_r(const struct tm *timeptr, char *buffer, int buflen); * extern int ctime_r(const time_t *timer, char *buffer, int buflen); * extern int gmtime_r(const time_t *timer, struct tm *result); * extern int localtime_r(const time_t *timer, struct tm *result); */ # ifdef TIMELEN typedef char _Xatimeparams[TIMELEN]; typedef char _Xctimeparams[TIMELEN]; # else typedef char _Xatimeparams[26]; typedef char _Xctimeparams[26]; # endif typedef struct tm _Xgtimeparams; typedef struct tm _Xltimeparams; # define _XAsctime(t,p) (asctime_r((t),(p),sizeof((p))) ? NULL : (p)) # define _XCtime(t,p) (ctime_r((t),(p),sizeof((p))) ? NULL : (p)) # define _XGmtime(t,p) (gmtime_r((t),&(p)) ? NULL : &(p)) # define _XLocaltime(t,p) (localtime_r((t),&(p)) ? NULL : &(p)) #elif !defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(__sun) /* Returns NULL on failure. Solaris 2.5 * * extern char *asctime_r(const struct tm *tm,char *buf, int buflen); * extern char *ctime_r(const time_t *clock, char *buf, int buflen); * extern struct tm *gmtime_r(const time_t *clock, struct tm *res); * extern struct tm *localtime_r(const time_t *clock, struct tm *res); */ # ifdef TIMELEN typedef char _Xatimeparams[TIMELEN]; typedef char _Xctimeparams[TIMELEN]; # else typedef char _Xatimeparams[26]; typedef char _Xctimeparams[26]; # endif typedef struct tm _Xgtimeparams; typedef struct tm _Xltimeparams; # define _XAsctime(t,p) asctime_r((t),(p),sizeof((p))) # define _XCtime(t,p) ctime_r((t),(p),sizeof((p))) # define _XGmtime(t,p) gmtime_r((t),&(p)) # define _XLocaltime(t,p) localtime_r((t),&(p)) #else /* defined(_POSIX_THREAD_SAFE_FUNCTIONS) */ /* POSIX final API. * extern char *asctime_r(const struct tm *timeptr, char *buffer); * extern char *ctime_r(const time_t *timer, char *buffer); * extern struct tm *gmtime_r(const time_t *timer, struct tm *result); * extern struct tm *localtime_r(const time_t *timer, struct tm *result); */ # ifdef TIMELEN typedef char _Xatimeparams[TIMELEN]; typedef char _Xctimeparams[TIMELEN]; # else typedef char _Xatimeparams[26]; typedef char _Xctimeparams[26]; # endif typedef struct tm _Xgtimeparams; typedef struct tm _Xltimeparams; # define _XAsctime(t,p) asctime_r((t),(p)) # define _XCtime(t,p) ctime_r((t),(p)) # define _XGmtime(t,p) gmtime_r((t),&(p)) # define _XLocaltime(t,p) localtime_r((t),&(p)) #endif /* X_INCLUDE_TIME_H */ #if defined(X_INCLUDE_TIME_H) && !defined(_XOS_INCLUDED_TIME_H) # define _XOS_INCLUDED_TIME_H #endif /***** wrappers *****/ /* * Effective prototypes for wrappers: * * NOTE: On systems lacking appropriate _r functions Getgrgid() and * Getgrnam() do NOT copy the list of group members! * * Remember that fgetgrent(), setgrent(), getgrent(), and endgrent() * are not included in POSIX. * * #define X_INCLUDE_GRP_H * #define XOS_USE_..._LOCKING * #include * * typedef ... _Xgetgrparams; * * struct group *_XGetgrgid(gid_t, _Xgetgrparams); * struct group *_XGetgrnam(const char *, _Xgetgrparams); */ #if defined(X_INCLUDE_GRP_H) && !defined(_XOS_INCLUDED_GRP_H) # include # if defined(XUSE_MTSAFE_API) || defined(XUSE_MTSAFE_GRPAPI) # define XOS_USE_MTSAFE_GRPAPI 1 # endif #endif #if !defined(X_INCLUDE_GRP_H) || defined(_XOS_INCLUDED_GRP_H) /* Do nothing. */ #elif !defined(XTHREADS) && !defined(X_FORCE_USE_MTSAFE_API) /* Use regular, unsafe API. */ typedef int _Xgetgrparams; /* dummy */ #define _XGetgrgid(g,p) getgrgid((g)) #define _XGetgrnam(n,p) getgrnam((n)) #elif !defined(XOS_USE_MTSAFE_GRPAPI) || defined(XNO_MTSAFE_GRPAPI) /* Systems with thread support but no _r API. UnixWare 2.0. */ typedef struct { struct group grp; char buf[X_LINE_MAX]; /* Should be sysconf(_SC_GETGR_R_SIZE_MAX)? */ struct group *pgrp; size_t len; } _Xgetgrparams; #ifdef SVR4 /* Copy the gr_passwd field too. */ # define _Xgrp_copyGroup(p) \ ( memcpy(&(p).grp, (p).pgrp, sizeof(struct group)), \ ((p).grp.gr_name = (p).buf), \ ((p).len = strlen((p).pgrp->gr_name)), \ strcpy((p).grp.gr_name, (p).pgrp->gr_name), \ ((p).grp.gr_passwd = (p).grp.gr_name + (p).len + 1), \ ((p).pgrp = &(p).grp), \ 0 ) #else # define _Xgrp_copyGroup(p) \ ( memcpy(&(p).grp, (p).pgrp, sizeof(struct group)), \ ((p).grp.gr_name = (p).buf), \ strcpy((p).grp.gr_name, (p).pgrp->gr_name), \ ((p).pgrp = &(p).grp), \ 0 ) #endif #define _XGetgrgid(g,p) \ ( (_Xos_processLock), \ (((p).pgrp = getgrgid((g))) ? _Xgrp_copyGroup(p) : 0), \ (_Xos_processUnlock), \ (p).pgrp ) #define _XGetgrnam(n,p) \ ( (_Xos_processLock), \ (((p).pgrp = getgrnam((n))) ? _Xgrp_copyGroup(p) : 0), \ (_Xos_processUnlock), \ (p).pgrp ) #elif !defined(_POSIX_THREAD_SAFE_FUNCTIONS) && defined(__sun) /* Non-POSIX API. Solaris. * * extern struct group *getgrgid_r(gid_t, struct group *, char *, int); * extern struct group *getgrnam_r(const char *, struct group *, char *, int); */ typedef struct { struct group grp; char buf[X_LINE_MAX]; /* Should be sysconf(_SC_GETGR_R_SIZE_MAX)? */ } _Xgetgrparams; #define _XGetgrgid(g,p) getgrgid_r((g), &(p).grp, (p).buf, sizeof((p).buf)) #define _XGetgrnam(n,p) getgrnam_r((n), &(p).grp, (p).buf, sizeof((p).buf)) #elif !defined(_POSIX_THREAD_SAFE_FUNCTIONS) /* Non-POSIX API. * extern int getgrgid_r(gid_t, struct group *, char *, int); * extern int getgrnam_r(const char *, struct group *, char *, int); */ typedef struct { struct group grp; char buf[X_LINE_MAX]; /* Should be sysconf(_SC_GETGR_R_SIZE_MAX)? */ } _Xgetgrparams; #define _XGetgrgid(g,p) \ ((getgrgid_r((g), &(p).grp, (p).buf, sizeof((p).buf)) ? NULL : &(p).grp)) #define _XGetgrnam(n,p) \ ((getgrnam_r((n), &(p).grp, (p).buf, sizeof((p).buf)) ? NULL : &(p).grp)) #else /* POSIX final API. * * int getgrgid_r(gid_t, struct group *, char *, size_t, struct group **); * int getgrnam_r(const char *, struct group *, char *, size_t, struct group **); */ typedef struct { struct group grp; char buf[X_LINE_MAX]; /* Should be sysconf(_SC_GETGR_R_SIZE_MAX)? */ struct group *result; } _Xgetgrparams; #define _XGetgrgid(g,p) \ ((getgrgid_r((g), &(p).grp, (p).buf, sizeof((p).buf), &(p).result) ? \ NULL : (p).result)) #define _XGetgrnam(n,p) \ ((getgrnam_r((n), &(p).grp, (p).buf, sizeof((p).buf), &(p).result) ? \ NULL : (p).result)) #endif #if defined(X_INCLUDE_GRP_H) && !defined(_XOS_INCLUDED_GRP_H) # define _XOS_INCLUDED_GRP_H #endif #ifdef __cplusplus } /* Close scope of 'extern "C"' declaration which encloses file. */ #endif X11/Xfuncs.h000064400000004320151027430550006535 0ustar00/* * Copyright 1990, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * */ #ifndef _XFUNCS_H_ # define _XFUNCS_H_ # include /* the old Xfuncs.h, for pre-R6 */ # if !(defined(XFree86LOADER) && defined(IN_MODULE)) # ifdef X_USEBFUNCS void bcopy(); void bzero(); int bcmp(); # else # if defined(SYSV) && !defined(__SCO__) && !defined(__sun) && !defined(__UNIXWARE__) && !defined(_AIX) # include void bcopy(); # define bzero(b,len) memset(b, 0, len) # define bcmp(b1,b2,len) memcmp(b1, b2, len) # else # include # if defined(__SCO__) || defined(__sun) || defined(__UNIXWARE__) || defined(__CYGWIN__) || defined(_AIX) || defined(__APPLE__) # include # endif # define _XFUNCS_H_INCLUDED_STRING_H # endif # endif /* X_USEBFUNCS */ /* the new Xfuncs.h */ /* the ANSI C way */ # ifndef _XFUNCS_H_INCLUDED_STRING_H # include # endif # undef bzero # define bzero(b,len) memset(b,0,len) # if defined WIN32 && defined __MINGW32__ # define bcopy(b1,b2,len) memmove(b2, b1, (size_t)(len)) # endif # endif /* !(defined(XFree86LOADER) && defined(IN_MODULE)) */ #endif /* _XFUNCS_H_ */ X11/Xosdefs.h000064400000006053151027430550006707 0ustar00/* * O/S-dependent (mis)feature macro definitions * Copyright 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _XOSDEFS_H_ # define _XOSDEFS_H_ /* * X_NOT_POSIX means does not have POSIX header files. Lack of this * symbol does NOT mean that the POSIX environment is the default. * You may still have to define _POSIX_SOURCE to get it. */ # ifdef _SCO_DS # ifndef __SCO__ # define __SCO__ # endif # endif # ifdef __i386__ # ifdef SYSV # if !defined(__SCO__) && \ !defined(__UNIXWARE__) && !defined(__sun) # if !defined(_POSIX_SOURCE) # define X_NOT_POSIX # endif # endif # endif # endif # ifdef __sun /* Imake configs define SVR4 on Solaris, but cc & gcc only define __SVR4 * This check allows non-Imake configured programs to build correctly. */ # if defined(__SVR4) && !defined(SVR4) # define SVR4 1 # endif # ifdef SVR4 /* define this to whatever it needs to be */ # define X_POSIX_C_SOURCE 199300L # endif # endif # ifdef WIN32 # ifndef _POSIX_ # define X_NOT_POSIX # endif # endif # ifdef __APPLE__ # define NULL_NOT_ZERO /* Defining any of these will sanitize the namespace to JUST want is defined by * that particular standard. If that happens, we don't get some expected * prototypes, typedefs, etc (like fd_mask). We can define _DARWIN_C_SOURCE to * loosen our belts a tad. */ # if defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) # ifndef _DARWIN_C_SOURCE # define _DARWIN_C_SOURCE # endif # endif # endif # ifdef __GNU__ # ifndef PATH_MAX # define PATH_MAX 4096 # endif # ifndef MAXPATHLEN # define MAXPATHLEN 4096 # endif # endif # if defined(__SCO__) || defined(__UNIXWARE__) # ifndef PATH_MAX # define PATH_MAX 1024 # endif # ifndef MAXPATHLEN # define MAXPATHLEN 1024 # endif # endif # if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) \ || defined(__APPLE__) || defined(__DragonFly__) # ifndef CSRG_BASED # define CSRG_BASED # endif # endif #endif /* _XOSDEFS_H_ */ X11/Xos.h000064400000010412151027430550006037 0ustar00/* * Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * * The X Window System is a Trademark of The Open Group. * */ /* This is a collection of things to try and minimize system dependencies * in a "significant" number of source files. */ #ifndef _XOS_H_ # define _XOS_H_ # include /* * Get major data types (esp. caddr_t) */ # include # if defined(__SCO__) || defined(__UNIXWARE__) # include # endif /* * Just about everyone needs the strings routines. We provide both forms here, * index/rindex and strchr/strrchr, so any systems that don't provide them all * need to have #defines here. * * These macros are defined this way, rather than, e.g.: * #defined index(s,c) strchr(s,c) * because someone might be using them as function pointers, and such * a change would break compatibility for anyone who's relying on them * being the way they currently are. So we're stuck with them this way, * which can be really inconvenient. :-( */ # include # if defined(__SCO__) || defined(__UNIXWARE__) || defined(__sun) || defined(__CYGWIN__) || defined(_AIX) || defined(__APPLE__) # include # else # ifndef index # define index(s,c) (strchr((s),(c))) # endif # ifndef rindex # define rindex(s,c) (strrchr((s),(c))) # endif # endif /* * Get open(2) constants */ # if defined(X_NOT_POSIX) # include # if defined(USL) || defined(__i386__) && (defined(SYSV) || defined(SVR4)) # include # endif # ifdef WIN32 # include # else # include # endif # else /* X_NOT_POSIX */ # include # include # endif /* X_NOT_POSIX else */ /* * Get struct timeval and struct tm */ # if defined(_POSIX_SOURCE) && defined(SVR4) /* need to omit _POSIX_SOURCE in order to get what we want in SVR4 */ # undef _POSIX_SOURCE # include # define _POSIX_SOURCE # elif defined(WIN32) # include # if !defined(_WINSOCKAPI_) && !defined(_WILLWINSOCK_) && !defined(_TIMEVAL_DEFINED) && !defined(_STRUCT_TIMEVAL) struct timeval { long tv_sec; /* seconds */ long tv_usec; /* and microseconds */ }; # define _TIMEVAL_DEFINED # endif # include # define gettimeofday(t) \ { \ struct _timeb _gtodtmp; \ _ftime (&_gtodtmp); \ (t)->tv_sec = _gtodtmp.time; \ (t)->tv_usec = _gtodtmp.millitm * 1000; \ } # else # include # include # endif /* defined(_POSIX_SOURCE) && defined(SVR4) */ /* define X_GETTIMEOFDAY macro, a portable gettimeofday() */ # if defined(_XOPEN_XPG4) || defined(_XOPEN_UNIX) /* _XOPEN_UNIX is XPG4.2 */ # define X_GETTIMEOFDAY(t) gettimeofday(t, (struct timezone*)0) # else # if defined(SVR4) || defined(__SVR4) || defined(WIN32) # define X_GETTIMEOFDAY(t) gettimeofday(t) # else # define X_GETTIMEOFDAY(t) gettimeofday(t, (struct timezone*)0) # endif # endif /* XPG4 else */ # ifdef __GNU__ # define PATH_MAX 4096 # define MAXPATHLEN 4096 # define OPEN_MAX 256 /* We define a reasonable limit. */ # endif /* use POSIX name for signal */ # if defined(X_NOT_POSIX) && defined(SYSV) && !defined(SIGCHLD) # define SIGCHLD SIGCLD # endif # include #endif /* _XOS_H_ */ X11/Xmd.h000064400000012002151027430550006013 0ustar00/*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef XMD_H # define XMD_H 1 /* * Xmd.h: MACHINE DEPENDENT DECLARATIONS. */ /* * Special per-machine configuration flags. */ # if defined(__sun) && defined(__SVR4) # include /* Solaris: defines _LP64 if necessary */ # endif # if defined (_LP64) || defined(__LP64__) || \ defined(__alpha) || defined(__alpha__) || \ defined(__ia64__) || defined(ia64) || \ defined(__sparc64__) || \ defined(__s390x__) || \ defined(__amd64__) || defined(amd64) || \ defined(__powerpc64__) # if !defined(__ILP32__) /* amd64-x32 is 32bit */ # define LONG64 /* 32/64-bit architecture */ # endif /* !__ILP32__ */ # endif /* * Definition of macro used to set constants for size of network structures; * machines with preprocessors that can't handle all of the sz_ symbols * can define this macro to be sizeof(x) if and only if their compiler doesn't * pad out structures (esp. the xTextElt structure which contains only two * one-byte fields). Network structures should always define sz_symbols. * * The sz_ prefix is used instead of something more descriptive so that the * symbols are no more than 32 characters long (which causes problems for some * compilers and preprocessors). * * The extra indirection is to get macro arguments to expand correctly before * the concatenation, rather than afterward. */ # define _SIZEOF(x) sz_##x # define SIZEOF(x) _SIZEOF(x) /* * Bitfield suffixes for the protocol structure elements, if you * need them. Note that bitfields are not guaranteed to be signed * (or even unsigned) according to ANSI C. */ # define B32 /* bitfield not needed on architectures with native 32-bit type */ # define B16 /* bitfield not needed on architectures with native 16-bit type */ # ifdef LONG64 typedef long INT64; typedef int INT32; # else typedef long INT32; # endif typedef short INT16; typedef signed char INT8; # ifdef LONG64 typedef unsigned long CARD64; typedef unsigned int CARD32; # else typedef unsigned long long CARD64; typedef unsigned long CARD32; # endif typedef unsigned short CARD16; typedef unsigned char CARD8; typedef CARD32 BITS32; typedef CARD16 BITS16; typedef CARD8 BYTE; typedef CARD8 BOOL; /* * was definitions for sign-extending bitfields on architectures without * native types smaller than 64-bit, now just backwards compatibility */ # define cvtINT8toInt(val) (val) # define cvtINT16toInt(val) (val) # define cvtINT32toInt(val) (val) # define cvtINT8toShort(val) (val) # define cvtINT16toShort(val) (val) # define cvtINT32toShort(val) (val) # define cvtINT8toLong(val) (val) # define cvtINT16toLong(val) (val) # define cvtINT32toLong(val) (val) /* * this version should leave result of type (t *), but that should only be * used when not in MUSTCOPY */ # define NEXTPTR(p,t) (((t *)(p)) + 1) #endif /* XMD_H */ X11/xpm.h000064400000037525151027430550006110 0ustar00/* * Copyright (C) 1989-95 GROUPE BULL * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * GROUPE BULL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of GROUPE BULL shall not be * used in advertising or otherwise to promote the sale, use or other dealings * in this Software without prior written authorization from GROUPE BULL. */ /*****************************************************************************\ * xpm.h: * * * * XPM library * * Include file * * * * Developed by Arnaud Le Hors * \*****************************************************************************/ /* * The code related to FOR_MSW has been added by * HeDu (hedu@cul-ipn.uni-kiel.de) 4/94 */ /* * The code related to AMIGA has been added by * Lorens Younes (d93-hyo@nada.kth.se) 4/96 */ #ifndef XPM_h #define XPM_h /* * first some identification numbers: * the version and revision numbers are determined with the following rule: * SO Major number = LIB minor version number. * SO Minor number = LIB sub-minor version number. * e.g: Xpm version 3.2f * we forget the 3 which is the format number, 2 gives 2, and f gives 6. * thus we have XpmVersion = 2 and XpmRevision = 6 * which gives SOXPMLIBREV = 2.6 * * Then the XpmIncludeVersion number is built from these numbers. */ #define XpmFormat 3 #define XpmVersion 4 #define XpmRevision 11 #define XpmIncludeVersion ((XpmFormat * 100 + XpmVersion) * 100 + XpmRevision) #ifndef XPM_NUMBERS #ifdef FOR_MSW # define SYSV /* uses memcpy string.h etc. */ # include # include "simx.h" /* defines some X stuff using MSW types */ #define NEED_STRCASECMP /* at least for MSVC++ */ #else /* FOR_MSW */ # ifdef AMIGA # include "amigax.h" # else /* not AMIGA */ # include # include # endif /* not AMIGA */ #endif /* FOR_MSW */ /* let's define Pixel if it is not done yet */ #if ! defined(_XtIntrinsic_h) && ! defined(PIXEL_ALREADY_TYPEDEFED) typedef unsigned long Pixel; /* Index into colormap */ # define PIXEL_ALREADY_TYPEDEFED #endif /* Return ErrorStatus codes: * null if full success * positive if partial success * negative if failure */ #define XpmColorError 1 #define XpmSuccess 0 #define XpmOpenFailed -1 #define XpmFileInvalid -2 #define XpmNoMemory -3 #define XpmColorFailed -4 typedef struct { char *name; /* Symbolic color name */ char *value; /* Color value */ Pixel pixel; /* Color pixel */ } XpmColorSymbol; typedef struct { char *name; /* name of the extension */ unsigned int nlines; /* number of lines in this extension */ char **lines; /* pointer to the extension array of strings */ } XpmExtension; typedef struct { char *string; /* characters string */ char *symbolic; /* symbolic name */ char *m_color; /* monochrom default */ char *g4_color; /* 4 level grayscale default */ char *g_color; /* other level grayscale default */ char *c_color; /* color default */ } XpmColor; typedef struct { unsigned int width; /* image width */ unsigned int height; /* image height */ unsigned int cpp; /* number of characters per pixel */ unsigned int ncolors; /* number of colors */ XpmColor *colorTable; /* list of related colors */ unsigned int *data; /* image data */ } XpmImage; typedef struct { unsigned long valuemask; /* Specifies which attributes are defined */ char *hints_cmt; /* Comment of the hints section */ char *colors_cmt; /* Comment of the colors section */ char *pixels_cmt; /* Comment of the pixels section */ unsigned int x_hotspot; /* Returns the x hotspot's coordinate */ unsigned int y_hotspot; /* Returns the y hotspot's coordinate */ unsigned int nextensions; /* number of extensions */ XpmExtension *extensions; /* pointer to array of extensions */ } XpmInfo; typedef int (*XpmAllocColorFunc)( Display* /* display */, Colormap /* colormap */, char* /* colorname */, XColor* /* xcolor */, void* /* closure */ ); typedef int (*XpmFreeColorsFunc)( Display* /* display */, Colormap /* colormap */, Pixel* /* pixels */, int /* npixels */, void* /* closure */ ); typedef struct { unsigned long valuemask; /* Specifies which attributes are defined */ Visual *visual; /* Specifies the visual to use */ Colormap colormap; /* Specifies the colormap to use */ unsigned int depth; /* Specifies the depth */ unsigned int width; /* Returns the width of the created pixmap */ unsigned int height; /* Returns the height of the created pixmap */ unsigned int x_hotspot; /* Returns the x hotspot's coordinate */ unsigned int y_hotspot; /* Returns the y hotspot's coordinate */ unsigned int cpp; /* Specifies the number of char per pixel */ Pixel *pixels; /* List of used color pixels */ unsigned int npixels; /* Number of used pixels */ XpmColorSymbol *colorsymbols; /* List of color symbols to override */ unsigned int numsymbols; /* Number of symbols */ char *rgb_fname; /* RGB text file name */ unsigned int nextensions; /* Number of extensions */ XpmExtension *extensions; /* List of extensions */ unsigned int ncolors; /* Number of colors */ XpmColor *colorTable; /* List of colors */ /* 3.2 backward compatibility code */ char *hints_cmt; /* Comment of the hints section */ char *colors_cmt; /* Comment of the colors section */ char *pixels_cmt; /* Comment of the pixels section */ /* end 3.2 bc */ unsigned int mask_pixel; /* Color table index of transparent color */ /* Color Allocation Directives */ Bool exactColors; /* Only use exact colors for visual */ unsigned int closeness; /* Allowable RGB deviation */ unsigned int red_closeness; /* Allowable red deviation */ unsigned int green_closeness; /* Allowable green deviation */ unsigned int blue_closeness; /* Allowable blue deviation */ int color_key; /* Use colors from this color set */ Pixel *alloc_pixels; /* Returns the list of alloc'ed color pixels */ int nalloc_pixels; /* Returns the number of alloc'ed color pixels */ Bool alloc_close_colors; /* Specify whether close colors should be allocated using XAllocColor or not */ int bitmap_format; /* Specify the format of 1bit depth images: ZPixmap or XYBitmap */ /* Color functions */ XpmAllocColorFunc alloc_color; /* Application color allocator */ XpmFreeColorsFunc free_colors; /* Application color de-allocator */ void *color_closure; /* Application private data to pass to alloc_color and free_colors */ } XpmAttributes; /* XpmAttributes value masks bits */ #define XpmVisual (1L<<0) #define XpmColormap (1L<<1) #define XpmDepth (1L<<2) #define XpmSize (1L<<3) /* width & height */ #define XpmHotspot (1L<<4) /* x_hotspot & y_hotspot */ #define XpmCharsPerPixel (1L<<5) #define XpmColorSymbols (1L<<6) #define XpmRgbFilename (1L<<7) /* 3.2 backward compatibility code */ #define XpmInfos (1L<<8) #define XpmReturnInfos XpmInfos /* end 3.2 bc */ #define XpmReturnPixels (1L<<9) #define XpmExtensions (1L<<10) #define XpmReturnExtensions XpmExtensions #define XpmExactColors (1L<<11) #define XpmCloseness (1L<<12) #define XpmRGBCloseness (1L<<13) #define XpmColorKey (1L<<14) #define XpmColorTable (1L<<15) #define XpmReturnColorTable XpmColorTable #define XpmReturnAllocPixels (1L<<16) #define XpmAllocCloseColors (1L<<17) #define XpmBitmapFormat (1L<<18) #define XpmAllocColor (1L<<19) #define XpmFreeColors (1L<<20) #define XpmColorClosure (1L<<21) /* XpmInfo value masks bits */ #define XpmComments XpmInfos #define XpmReturnComments XpmComments /* XpmAttributes mask_pixel value when there is no mask */ #ifndef FOR_MSW #define XpmUndefPixel 0x80000000 #else /* int is only 16 bit for MSW */ #define XpmUndefPixel 0x8000 #endif /* * color keys for visual type, they must fit along with the number key of * each related element in xpmColorKeys[] defined in XpmI.h */ #define XPM_MONO 2 #define XPM_GREY4 3 #define XPM_GRAY4 3 #define XPM_GREY 4 #define XPM_GRAY 4 #define XPM_COLOR 5 /* macros for forward declarations of functions with prototypes */ #define FUNC(f, t, p) extern t f p #define LFUNC(f, t, p) static t f p /* * functions declarations */ _XFUNCPROTOBEGIN /* FOR_MSW, all ..Pixmap.. are excluded, only the ..XImage.. are used */ /* Same for Amiga! */ #if !defined(FOR_MSW) && !defined(AMIGA) FUNC(XpmCreatePixmapFromData, int, (Display *display, Drawable d, char **data, Pixmap *pixmap_return, Pixmap *shapemask_return, XpmAttributes *attributes)); FUNC(XpmCreateDataFromPixmap, int, (Display *display, char ***data_return, Pixmap pixmap, Pixmap shapemask, XpmAttributes *attributes)); FUNC(XpmReadFileToPixmap, int, (Display *display, Drawable d, const char *filename, Pixmap *pixmap_return, Pixmap *shapemask_return, XpmAttributes *attributes)); FUNC(XpmWriteFileFromPixmap, int, (Display *display, const char *filename, Pixmap pixmap, Pixmap shapemask, XpmAttributes *attributes)); #endif FUNC(XpmCreateImageFromData, int, (Display *display, char **data, XImage **image_return, XImage **shapemask_return, XpmAttributes *attributes)); FUNC(XpmCreateDataFromImage, int, (Display *display, char ***data_return, XImage *image, XImage *shapeimage, XpmAttributes *attributes)); FUNC(XpmReadFileToImage, int, (Display *display, const char *filename, XImage **image_return, XImage **shapeimage_return, XpmAttributes *attributes)); FUNC(XpmWriteFileFromImage, int, (Display *display, const char *filename, XImage *image, XImage *shapeimage, XpmAttributes *attributes)); FUNC(XpmCreateImageFromBuffer, int, (Display *display, char *buffer, XImage **image_return, XImage **shapemask_return, XpmAttributes *attributes)); #if !defined(FOR_MSW) && !defined(AMIGA) FUNC(XpmCreatePixmapFromBuffer, int, (Display *display, Drawable d, char *buffer, Pixmap *pixmap_return, Pixmap *shapemask_return, XpmAttributes *attributes)); FUNC(XpmCreateBufferFromImage, int, (Display *display, char **buffer_return, XImage *image, XImage *shapeimage, XpmAttributes *attributes)); FUNC(XpmCreateBufferFromPixmap, int, (Display *display, char **buffer_return, Pixmap pixmap, Pixmap shapemask, XpmAttributes *attributes)); #endif FUNC(XpmReadFileToBuffer, int, (const char *filename, char **buffer_return)); FUNC(XpmWriteFileFromBuffer, int, (const char *filename, char *buffer)); FUNC(XpmReadFileToData, int, (const char *filename, char ***data_return)); FUNC(XpmWriteFileFromData, int, (const char *filename, char **data)); FUNC(XpmAttributesSize, int, (void)); FUNC(XpmFreeAttributes, void, (XpmAttributes *attributes)); FUNC(XpmFreeExtensions, void, (XpmExtension *extensions, int nextensions)); FUNC(XpmFreeXpmImage, void, (XpmImage *image)); FUNC(XpmFreeXpmInfo, void, (XpmInfo *info)); FUNC(XpmGetErrorString, char *, (int errcode)); FUNC(XpmLibraryVersion, int, (void)); /* XpmImage functions */ FUNC(XpmReadFileToXpmImage, int, (const char *filename, XpmImage *image, XpmInfo *info)); FUNC(XpmWriteFileFromXpmImage, int, (const char *filename, XpmImage *image, XpmInfo *info)); #if !defined(FOR_MSW) && !defined(AMIGA) FUNC(XpmCreatePixmapFromXpmImage, int, (Display *display, Drawable d, XpmImage *image, Pixmap *pixmap_return, Pixmap *shapemask_return, XpmAttributes *attributes)); #endif FUNC(XpmCreateImageFromXpmImage, int, (Display *display, XpmImage *image, XImage **image_return, XImage **shapeimage_return, XpmAttributes *attributes)); FUNC(XpmCreateXpmImageFromImage, int, (Display *display, XImage *image, XImage *shapeimage, XpmImage *xpmimage, XpmAttributes *attributes)); #if !defined(FOR_MSW) && !defined(AMIGA) FUNC(XpmCreateXpmImageFromPixmap, int, (Display *display, Pixmap pixmap, Pixmap shapemask, XpmImage *xpmimage, XpmAttributes *attributes)); #endif FUNC(XpmCreateDataFromXpmImage, int, (char ***data_return, XpmImage *image, XpmInfo *info)); FUNC(XpmCreateXpmImageFromData, int, (char **data, XpmImage *image, XpmInfo *info)); FUNC(XpmCreateXpmImageFromBuffer, int, (char *buffer, XpmImage *image, XpmInfo *info)); FUNC(XpmCreateBufferFromXpmImage, int, (char **buffer_return, XpmImage *image, XpmInfo *info)); FUNC(XpmGetParseError, int, (char *filename, int *linenum_return, int *charnum_return)); FUNC(XpmFree, void, (void *ptr)); _XFUNCPROTOEND /* backward compatibility */ /* for version 3.0c */ #define XpmPixmapColorError XpmColorError #define XpmPixmapSuccess XpmSuccess #define XpmPixmapOpenFailed XpmOpenFailed #define XpmPixmapFileInvalid XpmFileInvalid #define XpmPixmapNoMemory XpmNoMemory #define XpmPixmapColorFailed XpmColorFailed #define XpmReadPixmapFile(dpy, d, file, pix, mask, att) \ XpmReadFileToPixmap(dpy, d, file, pix, mask, att) #define XpmWritePixmapFile(dpy, file, pix, mask, att) \ XpmWriteFileFromPixmap(dpy, file, pix, mask, att) /* for version 3.0b */ #define PixmapColorError XpmColorError #define PixmapSuccess XpmSuccess #define PixmapOpenFailed XpmOpenFailed #define PixmapFileInvalid XpmFileInvalid #define PixmapNoMemory XpmNoMemory #define PixmapColorFailed XpmColorFailed #define ColorSymbol XpmColorSymbol #define XReadPixmapFile(dpy, d, file, pix, mask, att) \ XpmReadFileToPixmap(dpy, d, file, pix, mask, att) #define XWritePixmapFile(dpy, file, pix, mask, att) \ XpmWriteFileFromPixmap(dpy, file, pix, mask, att) #define XCreatePixmapFromData(dpy, d, data, pix, mask, att) \ XpmCreatePixmapFromData(dpy, d, data, pix, mask, att) #define XCreateDataFromPixmap(dpy, data, pix, mask, att) \ XpmCreateDataFromPixmap(dpy, data, pix, mask, att) #endif /* XPM_NUMBERS */ #endif X11/XlibConf.h000064400000003037151027430550006777 0ustar00/* include/X11/XlibConf.h. Generated from XlibConf.h.in by configure. */ /* * Copyright © 2005 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _XLIBCONF_H_ #define _XLIBCONF_H_ /* * This header file exports defines necessary to correctly * use Xlibint.h both inside Xlib and by external libraries * such as extensions. */ /* Threading support? */ #define XTHREADS 1 /* Use multi-threaded libc functions? */ #define XUSE_MTSAFE_API 1 #endif /* _XLIBCONF_H_ */ X11/Xlib.h000064400000302314151027430550006171 0ustar00/* Copyright 1985, 1986, 1987, 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * Xlib.h - Header definition and support file for the C subroutine * interface library (Xlib) to the X Window System Protocol (V11). * Structures and symbols starting with "_" are private to the library. */ #ifndef _X11_XLIB_H_ #define _X11_XLIB_H_ #define XlibSpecificationRelease 6 #include #if defined(__SCO__) || defined(__UNIXWARE__) #include #endif #include /* applications should not depend on these two headers being included! */ #include #include #ifndef X_WCHAR #include #else #ifdef __UNIXOS2__ #include #else /* replace this with #include or typedef appropriate for your system */ typedef unsigned long wchar_t; #endif #endif extern int _Xmblen( char *str, int len ); /* API mentioning "UTF8" or "utf8" is an XFree86 extension, introduced in November 2000. Its presence is indicated through the following macro. */ #define X_HAVE_UTF8_STRING 1 /* The Xlib structs are full of implicit padding to properly align members. We can't clean that up without breaking ABI, so tell clang not to bother complaining about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif typedef char *XPointer; #define Bool int #define Status int #define True 1 #define False 0 #define QueuedAlready 0 #define QueuedAfterReading 1 #define QueuedAfterFlush 2 #define ConnectionNumber(dpy) (((_XPrivDisplay)(dpy))->fd) #define RootWindow(dpy, scr) (ScreenOfDisplay(dpy,scr)->root) #define DefaultScreen(dpy) (((_XPrivDisplay)(dpy))->default_screen) #define DefaultRootWindow(dpy) (ScreenOfDisplay(dpy,DefaultScreen(dpy))->root) #define DefaultVisual(dpy, scr) (ScreenOfDisplay(dpy,scr)->root_visual) #define DefaultGC(dpy, scr) (ScreenOfDisplay(dpy,scr)->default_gc) #define BlackPixel(dpy, scr) (ScreenOfDisplay(dpy,scr)->black_pixel) #define WhitePixel(dpy, scr) (ScreenOfDisplay(dpy,scr)->white_pixel) #define AllPlanes ((unsigned long)~0L) #define QLength(dpy) (((_XPrivDisplay)(dpy))->qlen) #define DisplayWidth(dpy, scr) (ScreenOfDisplay(dpy,scr)->width) #define DisplayHeight(dpy, scr) (ScreenOfDisplay(dpy,scr)->height) #define DisplayWidthMM(dpy, scr)(ScreenOfDisplay(dpy,scr)->mwidth) #define DisplayHeightMM(dpy, scr)(ScreenOfDisplay(dpy,scr)->mheight) #define DisplayPlanes(dpy, scr) (ScreenOfDisplay(dpy,scr)->root_depth) #define DisplayCells(dpy, scr) (DefaultVisual(dpy,scr)->map_entries) #define ScreenCount(dpy) (((_XPrivDisplay)(dpy))->nscreens) #define ServerVendor(dpy) (((_XPrivDisplay)(dpy))->vendor) #define ProtocolVersion(dpy) (((_XPrivDisplay)(dpy))->proto_major_version) #define ProtocolRevision(dpy) (((_XPrivDisplay)(dpy))->proto_minor_version) #define VendorRelease(dpy) (((_XPrivDisplay)(dpy))->release) #define DisplayString(dpy) (((_XPrivDisplay)(dpy))->display_name) #define DefaultDepth(dpy, scr) (ScreenOfDisplay(dpy,scr)->root_depth) #define DefaultColormap(dpy, scr)(ScreenOfDisplay(dpy,scr)->cmap) #define BitmapUnit(dpy) (((_XPrivDisplay)(dpy))->bitmap_unit) #define BitmapBitOrder(dpy) (((_XPrivDisplay)(dpy))->bitmap_bit_order) #define BitmapPad(dpy) (((_XPrivDisplay)(dpy))->bitmap_pad) #define ImageByteOrder(dpy) (((_XPrivDisplay)(dpy))->byte_order) #define NextRequest(dpy) (((_XPrivDisplay)(dpy))->request + 1) #define LastKnownRequestProcessed(dpy) (((_XPrivDisplay)(dpy))->last_request_read) /* macros for screen oriented applications (toolkit) */ #define ScreenOfDisplay(dpy, scr)(&((_XPrivDisplay)(dpy))->screens[scr]) #define DefaultScreenOfDisplay(dpy) ScreenOfDisplay(dpy,DefaultScreen(dpy)) #define DisplayOfScreen(s) ((s)->display) #define RootWindowOfScreen(s) ((s)->root) #define BlackPixelOfScreen(s) ((s)->black_pixel) #define WhitePixelOfScreen(s) ((s)->white_pixel) #define DefaultColormapOfScreen(s)((s)->cmap) #define DefaultDepthOfScreen(s) ((s)->root_depth) #define DefaultGCOfScreen(s) ((s)->default_gc) #define DefaultVisualOfScreen(s)((s)->root_visual) #define WidthOfScreen(s) ((s)->width) #define HeightOfScreen(s) ((s)->height) #define WidthMMOfScreen(s) ((s)->mwidth) #define HeightMMOfScreen(s) ((s)->mheight) #define PlanesOfScreen(s) ((s)->root_depth) #define CellsOfScreen(s) (DefaultVisualOfScreen((s))->map_entries) #define MinCmapsOfScreen(s) ((s)->min_maps) #define MaxCmapsOfScreen(s) ((s)->max_maps) #define DoesSaveUnders(s) ((s)->save_unders) #define DoesBackingStore(s) ((s)->backing_store) #define EventMaskOfScreen(s) ((s)->root_input_mask) /* * Extensions need a way to hang private data on some structures. */ typedef struct _XExtData { int number; /* number returned by XRegisterExtension */ struct _XExtData *next; /* next item on list of data for structure */ int (*free_private)( /* called to free private storage */ struct _XExtData *extension ); XPointer private_data; /* data private to this extension. */ } XExtData; /* * This file contains structures used by the extension mechanism. */ typedef struct { /* public to extension, cannot be changed */ int extension; /* extension number */ int major_opcode; /* major op-code assigned by server */ int first_event; /* first event number for the extension */ int first_error; /* first error number for the extension */ } XExtCodes; /* * Data structure for retrieving info about pixmap formats. */ typedef struct { int depth; int bits_per_pixel; int scanline_pad; } XPixmapFormatValues; /* * Data structure for setting graphics context. */ typedef struct { int function; /* logical operation */ unsigned long plane_mask;/* plane mask */ unsigned long foreground;/* foreground pixel */ unsigned long background;/* background pixel */ int line_width; /* line width */ int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */ int cap_style; /* CapNotLast, CapButt, CapRound, CapProjecting */ int join_style; /* JoinMiter, JoinRound, JoinBevel */ int fill_style; /* FillSolid, FillTiled, FillStippled, FillOpaeueStippled */ int fill_rule; /* EvenOddRule, WindingRule */ int arc_mode; /* ArcChord, ArcPieSlice */ Pixmap tile; /* tile pixmap for tiling operations */ Pixmap stipple; /* stipple 1 plane pixmap for stipping */ int ts_x_origin; /* offset for tile or stipple operations */ int ts_y_origin; Font font; /* default text font for text operations */ int subwindow_mode; /* ClipByChildren, IncludeInferiors */ Bool graphics_exposures;/* boolean, should exposures be generated */ int clip_x_origin; /* origin for clipping */ int clip_y_origin; Pixmap clip_mask; /* bitmap clipping; other calls for rects */ int dash_offset; /* patterned/dashed line information */ char dashes; } XGCValues; /* * Graphics context. The contents of this structure are implementation * dependent. A GC should be treated as opaque by application code. */ typedef struct _XGC #ifdef XLIB_ILLEGAL_ACCESS { XExtData *ext_data; /* hook for extension to hang data */ GContext gid; /* protocol ID for graphics context */ /* there is more to this structure, but it is private to Xlib */ } #endif *GC; /* * Visual structure; contains information about colormapping possible. */ typedef struct { XExtData *ext_data; /* hook for extension to hang data */ VisualID visualid; /* visual id of this visual */ #if defined(__cplusplus) || defined(c_plusplus) int c_class; /* C++ class of screen (monochrome, etc.) */ #else int class; /* class of screen (monochrome, etc.) */ #endif unsigned long red_mask, green_mask, blue_mask; /* mask values */ int bits_per_rgb; /* log base 2 of distinct color values */ int map_entries; /* color map entries */ } Visual; /* * Depth structure; contains information for each possible depth. */ typedef struct { int depth; /* this depth (Z) of the depth */ int nvisuals; /* number of Visual types at this depth */ Visual *visuals; /* list of visuals possible at this depth */ } Depth; /* * Information about the screen. The contents of this structure are * implementation dependent. A Screen should be treated as opaque * by application code. */ struct _XDisplay; /* Forward declare before use for C++ */ typedef struct { XExtData *ext_data; /* hook for extension to hang data */ struct _XDisplay *display;/* back pointer to display structure */ Window root; /* Root window id. */ int width, height; /* width and height of screen */ int mwidth, mheight; /* width and height of in millimeters */ int ndepths; /* number of depths possible */ Depth *depths; /* list of allowable depths on the screen */ int root_depth; /* bits per pixel */ Visual *root_visual; /* root visual */ GC default_gc; /* GC for the root root visual */ Colormap cmap; /* default color map */ unsigned long white_pixel; unsigned long black_pixel; /* White and Black pixel values */ int max_maps, min_maps; /* max and min color maps */ int backing_store; /* Never, WhenMapped, Always */ Bool save_unders; long root_input_mask; /* initial root input mask */ } Screen; /* * Format structure; describes ZFormat data the screen will understand. */ typedef struct { XExtData *ext_data; /* hook for extension to hang data */ int depth; /* depth of this image format */ int bits_per_pixel; /* bits/pixel at this depth */ int scanline_pad; /* scanline must padded to this multiple */ } ScreenFormat; /* * Data structure for setting window attributes. */ typedef struct { Pixmap background_pixmap; /* background or None or ParentRelative */ unsigned long background_pixel; /* background pixel */ Pixmap border_pixmap; /* border of the window */ unsigned long border_pixel; /* border pixel value */ int bit_gravity; /* one of bit gravity values */ int win_gravity; /* one of the window gravity values */ int backing_store; /* NotUseful, WhenMapped, Always */ unsigned long backing_planes;/* planes to be preseved if possible */ unsigned long backing_pixel;/* value to use in restoring planes */ Bool save_under; /* should bits under be saved? (popups) */ long event_mask; /* set of events that should be saved */ long do_not_propagate_mask; /* set of events that should not propagate */ Bool override_redirect; /* boolean value for override-redirect */ Colormap colormap; /* color map to be associated with window */ Cursor cursor; /* cursor to be displayed (or None) */ } XSetWindowAttributes; typedef struct { int x, y; /* location of window */ int width, height; /* width and height of window */ int border_width; /* border width of window */ int depth; /* depth of window */ Visual *visual; /* the associated visual structure */ Window root; /* root of screen containing window */ #if defined(__cplusplus) || defined(c_plusplus) int c_class; /* C++ InputOutput, InputOnly*/ #else int class; /* InputOutput, InputOnly*/ #endif int bit_gravity; /* one of bit gravity values */ int win_gravity; /* one of the window gravity values */ int backing_store; /* NotUseful, WhenMapped, Always */ unsigned long backing_planes;/* planes to be preserved if possible */ unsigned long backing_pixel;/* value to be used when restoring planes */ Bool save_under; /* boolean, should bits under be saved? */ Colormap colormap; /* color map to be associated with window */ Bool map_installed; /* boolean, is color map currently installed*/ int map_state; /* IsUnmapped, IsUnviewable, IsViewable */ long all_event_masks; /* set of events all people have interest in*/ long your_event_mask; /* my event mask */ long do_not_propagate_mask; /* set of events that should not propagate */ Bool override_redirect; /* boolean value for override-redirect */ Screen *screen; /* back pointer to correct screen */ } XWindowAttributes; /* * Data structure for host setting; getting routines. * */ typedef struct { int family; /* for example FamilyInternet */ int length; /* length of address, in bytes */ char *address; /* pointer to where to find the bytes */ } XHostAddress; /* * Data structure for ServerFamilyInterpreted addresses in host routines */ typedef struct { int typelength; /* length of type string, in bytes */ int valuelength; /* length of value string, in bytes */ char *type; /* pointer to where to find the type string */ char *value; /* pointer to where to find the address */ } XServerInterpretedAddress; /* * Data structure for "image" data, used by image manipulation routines. */ typedef struct _XImage { int width, height; /* size of image */ int xoffset; /* number of pixels offset in X direction */ int format; /* XYBitmap, XYPixmap, ZPixmap */ char *data; /* pointer to image data */ int byte_order; /* data byte order, LSBFirst, MSBFirst */ int bitmap_unit; /* quant. of scanline 8, 16, 32 */ int bitmap_bit_order; /* LSBFirst, MSBFirst */ int bitmap_pad; /* 8, 16, 32 either XY or ZPixmap */ int depth; /* depth of image */ int bytes_per_line; /* accelarator to next line */ int bits_per_pixel; /* bits per pixel (ZPixmap) */ unsigned long red_mask; /* bits in z arrangment */ unsigned long green_mask; unsigned long blue_mask; XPointer obdata; /* hook for the object routines to hang on */ struct funcs { /* image manipulation routines */ struct _XImage *(*create_image)( struct _XDisplay* /* display */, Visual* /* visual */, unsigned int /* depth */, int /* format */, int /* offset */, char* /* data */, unsigned int /* width */, unsigned int /* height */, int /* bitmap_pad */, int /* bytes_per_line */); int (*destroy_image) (struct _XImage *); unsigned long (*get_pixel) (struct _XImage *, int, int); int (*put_pixel) (struct _XImage *, int, int, unsigned long); struct _XImage *(*sub_image)(struct _XImage *, int, int, unsigned int, unsigned int); int (*add_pixel) (struct _XImage *, long); } f; } XImage; /* * Data structure for XReconfigureWindow */ typedef struct { int x, y; int width, height; int border_width; Window sibling; int stack_mode; } XWindowChanges; /* * Data structure used by color operations */ typedef struct { unsigned long pixel; unsigned short red, green, blue; char flags; /* do_red, do_green, do_blue */ char pad; } XColor; /* * Data structures for graphics operations. On most machines, these are * congruent with the wire protocol structures, so reformatting the data * can be avoided on these architectures. */ typedef struct { short x1, y1, x2, y2; } XSegment; typedef struct { short x, y; } XPoint; typedef struct { short x, y; unsigned short width, height; } XRectangle; typedef struct { short x, y; unsigned short width, height; short angle1, angle2; } XArc; /* Data structure for XChangeKeyboardControl */ typedef struct { int key_click_percent; int bell_percent; int bell_pitch; int bell_duration; int led; int led_mode; int key; int auto_repeat_mode; /* On, Off, Default */ } XKeyboardControl; /* Data structure for XGetKeyboardControl */ typedef struct { int key_click_percent; int bell_percent; unsigned int bell_pitch, bell_duration; unsigned long led_mask; int global_auto_repeat; char auto_repeats[32]; } XKeyboardState; /* Data structure for XGetMotionEvents. */ typedef struct { Time time; short x, y; } XTimeCoord; /* Data structure for X{Set,Get}ModifierMapping */ typedef struct { int max_keypermod; /* The server's max # of keys per modifier */ KeyCode *modifiermap; /* An 8 by max_keypermod array of modifiers */ } XModifierKeymap; /* * Display datatype maintaining display specific data. * The contents of this structure are implementation dependent. * A Display should be treated as opaque by application code. */ #ifndef XLIB_ILLEGAL_ACCESS typedef struct _XDisplay Display; #endif struct _XPrivate; /* Forward declare before use for C++ */ struct _XrmHashBucketRec; typedef struct #ifdef XLIB_ILLEGAL_ACCESS _XDisplay #endif { XExtData *ext_data; /* hook for extension to hang data */ struct _XPrivate *private1; int fd; /* Network socket. */ int private2; int proto_major_version;/* major version of server's X protocol */ int proto_minor_version;/* minor version of servers X protocol */ char *vendor; /* vendor of the server hardware */ XID private3; XID private4; XID private5; int private6; XID (*resource_alloc)( /* allocator function */ struct _XDisplay* ); int byte_order; /* screen byte order, LSBFirst, MSBFirst */ int bitmap_unit; /* padding and data requirements */ int bitmap_pad; /* padding requirements on bitmaps */ int bitmap_bit_order; /* LeastSignificant or MostSignificant */ int nformats; /* number of pixmap formats in list */ ScreenFormat *pixmap_format; /* pixmap format list */ int private8; int release; /* release of the server */ struct _XPrivate *private9, *private10; int qlen; /* Length of input event queue */ unsigned long last_request_read; /* seq number of last event read */ unsigned long request; /* sequence number of last request. */ XPointer private11; XPointer private12; XPointer private13; XPointer private14; unsigned max_request_size; /* maximum number 32 bit words in request*/ struct _XrmHashBucketRec *db; int (*private15)( struct _XDisplay* ); char *display_name; /* "host:display" string used on this connect*/ int default_screen; /* default screen for operations */ int nscreens; /* number of screens on this server*/ Screen *screens; /* pointer to list of screens */ unsigned long motion_buffer; /* size of motion buffer */ unsigned long private16; int min_keycode; /* minimum defined keycode */ int max_keycode; /* maximum defined keycode */ XPointer private17; XPointer private18; int private19; char *xdefaults; /* contents of defaults from server */ /* there is more to this structure, but it is private to Xlib */ } #ifdef XLIB_ILLEGAL_ACCESS Display, #endif *_XPrivDisplay; #undef _XEVENT_ #ifndef _XEVENT_ /* * Definitions of specific events. */ typedef struct { int type; /* of event */ unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; /* "event" window it is reported relative to */ Window root; /* root window that the event occurred on */ Window subwindow; /* child window */ Time time; /* milliseconds */ int x, y; /* pointer x, y coordinates in event window */ int x_root, y_root; /* coordinates relative to root */ unsigned int state; /* key or button mask */ unsigned int keycode; /* detail */ Bool same_screen; /* same screen flag */ } XKeyEvent; typedef XKeyEvent XKeyPressedEvent; typedef XKeyEvent XKeyReleasedEvent; typedef struct { int type; /* of event */ unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; /* "event" window it is reported relative to */ Window root; /* root window that the event occurred on */ Window subwindow; /* child window */ Time time; /* milliseconds */ int x, y; /* pointer x, y coordinates in event window */ int x_root, y_root; /* coordinates relative to root */ unsigned int state; /* key or button mask */ unsigned int button; /* detail */ Bool same_screen; /* same screen flag */ } XButtonEvent; typedef XButtonEvent XButtonPressedEvent; typedef XButtonEvent XButtonReleasedEvent; typedef struct { int type; /* of event */ unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; /* "event" window reported relative to */ Window root; /* root window that the event occurred on */ Window subwindow; /* child window */ Time time; /* milliseconds */ int x, y; /* pointer x, y coordinates in event window */ int x_root, y_root; /* coordinates relative to root */ unsigned int state; /* key or button mask */ char is_hint; /* detail */ Bool same_screen; /* same screen flag */ } XMotionEvent; typedef XMotionEvent XPointerMovedEvent; typedef struct { int type; /* of event */ unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; /* "event" window reported relative to */ Window root; /* root window that the event occurred on */ Window subwindow; /* child window */ Time time; /* milliseconds */ int x, y; /* pointer x, y coordinates in event window */ int x_root, y_root; /* coordinates relative to root */ int mode; /* NotifyNormal, NotifyGrab, NotifyUngrab */ int detail; /* * NotifyAncestor, NotifyVirtual, NotifyInferior, * NotifyNonlinear,NotifyNonlinearVirtual */ Bool same_screen; /* same screen flag */ Bool focus; /* boolean focus */ unsigned int state; /* key or button mask */ } XCrossingEvent; typedef XCrossingEvent XEnterWindowEvent; typedef XCrossingEvent XLeaveWindowEvent; typedef struct { int type; /* FocusIn or FocusOut */ unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; /* window of event */ int mode; /* NotifyNormal, NotifyWhileGrabbed, NotifyGrab, NotifyUngrab */ int detail; /* * NotifyAncestor, NotifyVirtual, NotifyInferior, * NotifyNonlinear,NotifyNonlinearVirtual, NotifyPointer, * NotifyPointerRoot, NotifyDetailNone */ } XFocusChangeEvent; typedef XFocusChangeEvent XFocusInEvent; typedef XFocusChangeEvent XFocusOutEvent; /* generated on EnterWindow and FocusIn when KeyMapState selected */ typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; char key_vector[32]; } XKeymapEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; int x, y; int width, height; int count; /* if non-zero, at least this many more */ } XExposeEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Drawable drawable; int x, y; int width, height; int count; /* if non-zero, at least this many more */ int major_code; /* core is CopyArea or CopyPlane */ int minor_code; /* not defined in the core */ } XGraphicsExposeEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Drawable drawable; int major_code; /* core is CopyArea or CopyPlane */ int minor_code; /* not defined in the core */ } XNoExposeEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; int state; /* Visibility state */ } XVisibilityEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window parent; /* parent of the window */ Window window; /* window id of window created */ int x, y; /* window location */ int width, height; /* size of window */ int border_width; /* border width */ Bool override_redirect; /* creation should be overridden */ } XCreateWindowEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; } XDestroyWindowEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; Bool from_configure; } XUnmapEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; Bool override_redirect; /* boolean, is override set... */ } XMapEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window parent; Window window; } XMapRequestEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; Window parent; int x, y; Bool override_redirect; } XReparentEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; int x, y; int width, height; int border_width; Window above; Bool override_redirect; } XConfigureEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; int x, y; } XGravityEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; int width, height; } XResizeRequestEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window parent; Window window; int x, y; int width, height; int border_width; Window above; int detail; /* Above, Below, TopIf, BottomIf, Opposite */ unsigned long value_mask; } XConfigureRequestEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window event; Window window; int place; /* PlaceOnTop, PlaceOnBottom */ } XCirculateEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window parent; Window window; int place; /* PlaceOnTop, PlaceOnBottom */ } XCirculateRequestEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; Atom atom; Time time; int state; /* NewValue, Deleted */ } XPropertyEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; Atom selection; Time time; } XSelectionClearEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window owner; Window requestor; Atom selection; Atom target; Atom property; Time time; } XSelectionRequestEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window requestor; Atom selection; Atom target; Atom property; /* ATOM or None */ Time time; } XSelectionEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; Colormap colormap; /* COLORMAP or None */ #if defined(__cplusplus) || defined(c_plusplus) Bool c_new; /* C++ */ #else Bool new; #endif int state; /* ColormapInstalled, ColormapUninstalled */ } XColormapEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; Atom message_type; int format; union { char b[20]; short s[10]; long l[5]; } data; } XClientMessageEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display; /* Display the event was read from */ Window window; /* unused */ int request; /* one of MappingModifier, MappingKeyboard, MappingPointer */ int first_keycode; /* first keycode */ int count; /* defines range of change w. first_keycode*/ } XMappingEvent; typedef struct { int type; Display *display; /* Display the event was read from */ XID resourceid; /* resource id */ unsigned long serial; /* serial number of failed request */ unsigned char error_code; /* error code of failed request */ unsigned char request_code; /* Major op-code of failed request */ unsigned char minor_code; /* Minor op-code of failed request */ } XErrorEvent; typedef struct { int type; unsigned long serial; /* # of last request processed by server */ Bool send_event; /* true if this came from a SendEvent request */ Display *display;/* Display the event was read from */ Window window; /* window on which event was requested in event mask */ } XAnyEvent; /*************************************************************** * * GenericEvent. This event is the standard event for all newer extensions. */ typedef struct { int type; /* of event. Always GenericEvent */ unsigned long serial; /* # of last request processed */ Bool send_event; /* true if from SendEvent request */ Display *display; /* Display the event was read from */ int extension; /* major opcode of extension that caused the event */ int evtype; /* actual event type. */ } XGenericEvent; typedef struct { int type; /* of event. Always GenericEvent */ unsigned long serial; /* # of last request processed */ Bool send_event; /* true if from SendEvent request */ Display *display; /* Display the event was read from */ int extension; /* major opcode of extension that caused the event */ int evtype; /* actual event type. */ unsigned int cookie; void *data; } XGenericEventCookie; /* * this union is defined so Xlib can always use the same sized * event structure internally, to avoid memory fragmentation. */ typedef union _XEvent { int type; /* must not be changed; first element */ XAnyEvent xany; XKeyEvent xkey; XButtonEvent xbutton; XMotionEvent xmotion; XCrossingEvent xcrossing; XFocusChangeEvent xfocus; XExposeEvent xexpose; XGraphicsExposeEvent xgraphicsexpose; XNoExposeEvent xnoexpose; XVisibilityEvent xvisibility; XCreateWindowEvent xcreatewindow; XDestroyWindowEvent xdestroywindow; XUnmapEvent xunmap; XMapEvent xmap; XMapRequestEvent xmaprequest; XReparentEvent xreparent; XConfigureEvent xconfigure; XGravityEvent xgravity; XResizeRequestEvent xresizerequest; XConfigureRequestEvent xconfigurerequest; XCirculateEvent xcirculate; XCirculateRequestEvent xcirculaterequest; XPropertyEvent xproperty; XSelectionClearEvent xselectionclear; XSelectionRequestEvent xselectionrequest; XSelectionEvent xselection; XColormapEvent xcolormap; XClientMessageEvent xclient; XMappingEvent xmapping; XErrorEvent xerror; XKeymapEvent xkeymap; XGenericEvent xgeneric; XGenericEventCookie xcookie; long pad[24]; } XEvent; #endif #define XAllocID(dpy) ((*((_XPrivDisplay)(dpy))->resource_alloc)((dpy))) /* * per character font metric information. */ typedef struct { short lbearing; /* origin to left edge of raster */ short rbearing; /* origin to right edge of raster */ short width; /* advance to next char's origin */ short ascent; /* baseline to top edge of raster */ short descent; /* baseline to bottom edge of raster */ unsigned short attributes; /* per char flags (not predefined) */ } XCharStruct; /* * To allow arbitrary information with fonts, there are additional properties * returned. */ typedef struct { Atom name; unsigned long card32; } XFontProp; typedef struct { XExtData *ext_data; /* hook for extension to hang data */ Font fid; /* Font id for this font */ unsigned direction; /* hint about direction the font is painted */ unsigned min_char_or_byte2;/* first character */ unsigned max_char_or_byte2;/* last character */ unsigned min_byte1; /* first row that exists */ unsigned max_byte1; /* last row that exists */ Bool all_chars_exist;/* flag if all characters have non-zero size*/ unsigned default_char; /* char to print for undefined character */ int n_properties; /* how many properties there are */ XFontProp *properties; /* pointer to array of additional properties*/ XCharStruct min_bounds; /* minimum bounds over all existing char*/ XCharStruct max_bounds; /* maximum bounds over all existing char*/ XCharStruct *per_char; /* first_char to last_char information */ int ascent; /* log. extent above baseline for spacing */ int descent; /* log. descent below baseline for spacing */ } XFontStruct; /* * PolyText routines take these as arguments. */ typedef struct { char *chars; /* pointer to string */ int nchars; /* number of characters */ int delta; /* delta between strings */ Font font; /* font to print it in, None don't change */ } XTextItem; typedef struct { /* normal 16 bit characters are two bytes */ unsigned char byte1; unsigned char byte2; } XChar2b; typedef struct { XChar2b *chars; /* two byte characters */ int nchars; /* number of characters */ int delta; /* delta between strings */ Font font; /* font to print it in, None don't change */ } XTextItem16; typedef union { Display *display; GC gc; Visual *visual; Screen *screen; ScreenFormat *pixmap_format; XFontStruct *font; } XEDataObject; typedef struct { XRectangle max_ink_extent; XRectangle max_logical_extent; } XFontSetExtents; /* unused: typedef void (*XOMProc)(); */ typedef struct _XOM *XOM; typedef struct _XOC *XOC, *XFontSet; typedef struct { char *chars; int nchars; int delta; XFontSet font_set; } XmbTextItem; typedef struct { wchar_t *chars; int nchars; int delta; XFontSet font_set; } XwcTextItem; #define XNRequiredCharSet "requiredCharSet" #define XNQueryOrientation "queryOrientation" #define XNBaseFontName "baseFontName" #define XNOMAutomatic "omAutomatic" #define XNMissingCharSet "missingCharSet" #define XNDefaultString "defaultString" #define XNOrientation "orientation" #define XNDirectionalDependentDrawing "directionalDependentDrawing" #define XNContextualDrawing "contextualDrawing" #define XNFontInfo "fontInfo" typedef struct { int charset_count; char **charset_list; } XOMCharSetList; typedef enum { XOMOrientation_LTR_TTB, XOMOrientation_RTL_TTB, XOMOrientation_TTB_LTR, XOMOrientation_TTB_RTL, XOMOrientation_Context } XOrientation; typedef struct { int num_orientation; XOrientation *orientation; /* Input Text description */ } XOMOrientation; typedef struct { int num_font; XFontStruct **font_struct_list; char **font_name_list; } XOMFontInfo; typedef struct _XIM *XIM; typedef struct _XIC *XIC; typedef void (*XIMProc)( XIM, XPointer, XPointer ); typedef Bool (*XICProc)( XIC, XPointer, XPointer ); typedef void (*XIDProc)( Display*, XPointer, XPointer ); typedef unsigned long XIMStyle; typedef struct { unsigned short count_styles; XIMStyle *supported_styles; } XIMStyles; #define XIMPreeditArea 0x0001L #define XIMPreeditCallbacks 0x0002L #define XIMPreeditPosition 0x0004L #define XIMPreeditNothing 0x0008L #define XIMPreeditNone 0x0010L #define XIMStatusArea 0x0100L #define XIMStatusCallbacks 0x0200L #define XIMStatusNothing 0x0400L #define XIMStatusNone 0x0800L #define XNVaNestedList "XNVaNestedList" #define XNQueryInputStyle "queryInputStyle" #define XNClientWindow "clientWindow" #define XNInputStyle "inputStyle" #define XNFocusWindow "focusWindow" #define XNResourceName "resourceName" #define XNResourceClass "resourceClass" #define XNGeometryCallback "geometryCallback" #define XNDestroyCallback "destroyCallback" #define XNFilterEvents "filterEvents" #define XNPreeditStartCallback "preeditStartCallback" #define XNPreeditDoneCallback "preeditDoneCallback" #define XNPreeditDrawCallback "preeditDrawCallback" #define XNPreeditCaretCallback "preeditCaretCallback" #define XNPreeditStateNotifyCallback "preeditStateNotifyCallback" #define XNPreeditAttributes "preeditAttributes" #define XNStatusStartCallback "statusStartCallback" #define XNStatusDoneCallback "statusDoneCallback" #define XNStatusDrawCallback "statusDrawCallback" #define XNStatusAttributes "statusAttributes" #define XNArea "area" #define XNAreaNeeded "areaNeeded" #define XNSpotLocation "spotLocation" #define XNColormap "colorMap" #define XNStdColormap "stdColorMap" #define XNForeground "foreground" #define XNBackground "background" #define XNBackgroundPixmap "backgroundPixmap" #define XNFontSet "fontSet" #define XNLineSpace "lineSpace" #define XNCursor "cursor" #define XNQueryIMValuesList "queryIMValuesList" #define XNQueryICValuesList "queryICValuesList" #define XNVisiblePosition "visiblePosition" #define XNR6PreeditCallback "r6PreeditCallback" #define XNStringConversionCallback "stringConversionCallback" #define XNStringConversion "stringConversion" #define XNResetState "resetState" #define XNHotKey "hotKey" #define XNHotKeyState "hotKeyState" #define XNPreeditState "preeditState" #define XNSeparatorofNestedList "separatorofNestedList" #define XBufferOverflow -1 #define XLookupNone 1 #define XLookupChars 2 #define XLookupKeySym 3 #define XLookupBoth 4 typedef void *XVaNestedList; typedef struct { XPointer client_data; XIMProc callback; } XIMCallback; typedef struct { XPointer client_data; XICProc callback; } XICCallback; typedef unsigned long XIMFeedback; #define XIMReverse 1L #define XIMUnderline (1L<<1) #define XIMHighlight (1L<<2) #define XIMPrimary (1L<<5) #define XIMSecondary (1L<<6) #define XIMTertiary (1L<<7) #define XIMVisibleToForward (1L<<8) #define XIMVisibleToBackword (1L<<9) #define XIMVisibleToCenter (1L<<10) typedef struct _XIMText { unsigned short length; XIMFeedback *feedback; Bool encoding_is_wchar; union { char *multi_byte; wchar_t *wide_char; } string; } XIMText; typedef unsigned long XIMPreeditState; #define XIMPreeditUnKnown 0L #define XIMPreeditEnable 1L #define XIMPreeditDisable (1L<<1) typedef struct _XIMPreeditStateNotifyCallbackStruct { XIMPreeditState state; } XIMPreeditStateNotifyCallbackStruct; typedef unsigned long XIMResetState; #define XIMInitialState 1L #define XIMPreserveState (1L<<1) typedef unsigned long XIMStringConversionFeedback; #define XIMStringConversionLeftEdge (0x00000001) #define XIMStringConversionRightEdge (0x00000002) #define XIMStringConversionTopEdge (0x00000004) #define XIMStringConversionBottomEdge (0x00000008) #define XIMStringConversionConcealed (0x00000010) #define XIMStringConversionWrapped (0x00000020) typedef struct _XIMStringConversionText { unsigned short length; XIMStringConversionFeedback *feedback; Bool encoding_is_wchar; union { char *mbs; wchar_t *wcs; } string; } XIMStringConversionText; typedef unsigned short XIMStringConversionPosition; typedef unsigned short XIMStringConversionType; #define XIMStringConversionBuffer (0x0001) #define XIMStringConversionLine (0x0002) #define XIMStringConversionWord (0x0003) #define XIMStringConversionChar (0x0004) typedef unsigned short XIMStringConversionOperation; #define XIMStringConversionSubstitution (0x0001) #define XIMStringConversionRetrieval (0x0002) typedef enum { XIMForwardChar, XIMBackwardChar, XIMForwardWord, XIMBackwardWord, XIMCaretUp, XIMCaretDown, XIMNextLine, XIMPreviousLine, XIMLineStart, XIMLineEnd, XIMAbsolutePosition, XIMDontChange } XIMCaretDirection; typedef struct _XIMStringConversionCallbackStruct { XIMStringConversionPosition position; XIMCaretDirection direction; XIMStringConversionOperation operation; unsigned short factor; XIMStringConversionText *text; } XIMStringConversionCallbackStruct; typedef struct _XIMPreeditDrawCallbackStruct { int caret; /* Cursor offset within pre-edit string */ int chg_first; /* Starting change position */ int chg_length; /* Length of the change in character count */ XIMText *text; } XIMPreeditDrawCallbackStruct; typedef enum { XIMIsInvisible, /* Disable caret feedback */ XIMIsPrimary, /* UI defined caret feedback */ XIMIsSecondary /* UI defined caret feedback */ } XIMCaretStyle; typedef struct _XIMPreeditCaretCallbackStruct { int position; /* Caret offset within pre-edit string */ XIMCaretDirection direction; /* Caret moves direction */ XIMCaretStyle style; /* Feedback of the caret */ } XIMPreeditCaretCallbackStruct; typedef enum { XIMTextType, XIMBitmapType } XIMStatusDataType; typedef struct _XIMStatusDrawCallbackStruct { XIMStatusDataType type; union { XIMText *text; Pixmap bitmap; } data; } XIMStatusDrawCallbackStruct; typedef struct _XIMHotKeyTrigger { KeySym keysym; int modifier; int modifier_mask; } XIMHotKeyTrigger; typedef struct _XIMHotKeyTriggers { int num_hot_key; XIMHotKeyTrigger *key; } XIMHotKeyTriggers; typedef unsigned long XIMHotKeyState; #define XIMHotKeyStateON (0x0001L) #define XIMHotKeyStateOFF (0x0002L) typedef struct { unsigned short count_values; char **supported_values; } XIMValuesList; _XFUNCPROTOBEGIN #if defined(WIN32) && !defined(_XLIBINT_) #define _Xdebug (*_Xdebug_p) #endif extern int _Xdebug; extern XFontStruct *XLoadQueryFont( Display* /* display */, _Xconst char* /* name */ ); extern XFontStruct *XQueryFont( Display* /* display */, XID /* font_ID */ ); extern XTimeCoord *XGetMotionEvents( Display* /* display */, Window /* w */, Time /* start */, Time /* stop */, int* /* nevents_return */ ); extern XModifierKeymap *XDeleteModifiermapEntry( XModifierKeymap* /* modmap */, #if NeedWidePrototypes unsigned int /* keycode_entry */, #else KeyCode /* keycode_entry */, #endif int /* modifier */ ); extern XModifierKeymap *XGetModifierMapping( Display* /* display */ ); extern XModifierKeymap *XInsertModifiermapEntry( XModifierKeymap* /* modmap */, #if NeedWidePrototypes unsigned int /* keycode_entry */, #else KeyCode /* keycode_entry */, #endif int /* modifier */ ); extern XModifierKeymap *XNewModifiermap( int /* max_keys_per_mod */ ); extern XImage *XCreateImage( Display* /* display */, Visual* /* visual */, unsigned int /* depth */, int /* format */, int /* offset */, char* /* data */, unsigned int /* width */, unsigned int /* height */, int /* bitmap_pad */, int /* bytes_per_line */ ); extern Status XInitImage( XImage* /* image */ ); extern XImage *XGetImage( Display* /* display */, Drawable /* d */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, unsigned long /* plane_mask */, int /* format */ ); extern XImage *XGetSubImage( Display* /* display */, Drawable /* d */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, unsigned long /* plane_mask */, int /* format */, XImage* /* dest_image */, int /* dest_x */, int /* dest_y */ ); /* * X function declarations. */ extern Display *XOpenDisplay( _Xconst char* /* display_name */ ); extern void XrmInitialize( void ); extern char *XFetchBytes( Display* /* display */, int* /* nbytes_return */ ); extern char *XFetchBuffer( Display* /* display */, int* /* nbytes_return */, int /* buffer */ ); extern char *XGetAtomName( Display* /* display */, Atom /* atom */ ); extern Status XGetAtomNames( Display* /* dpy */, Atom* /* atoms */, int /* count */, char** /* names_return */ ); extern char *XGetDefault( Display* /* display */, _Xconst char* /* program */, _Xconst char* /* option */ ); extern char *XDisplayName( _Xconst char* /* string */ ); extern char *XKeysymToString( KeySym /* keysym */ ); extern int (*XSynchronize( Display* /* display */, Bool /* onoff */ ))( Display* /* display */ ); extern int (*XSetAfterFunction( Display* /* display */, int (*) ( Display* /* display */ ) /* procedure */ ))( Display* /* display */ ); extern Atom XInternAtom( Display* /* display */, _Xconst char* /* atom_name */, Bool /* only_if_exists */ ); extern Status XInternAtoms( Display* /* dpy */, char** /* names */, int /* count */, Bool /* onlyIfExists */, Atom* /* atoms_return */ ); extern Colormap XCopyColormapAndFree( Display* /* display */, Colormap /* colormap */ ); extern Colormap XCreateColormap( Display* /* display */, Window /* w */, Visual* /* visual */, int /* alloc */ ); extern Cursor XCreatePixmapCursor( Display* /* display */, Pixmap /* source */, Pixmap /* mask */, XColor* /* foreground_color */, XColor* /* background_color */, unsigned int /* x */, unsigned int /* y */ ); extern Cursor XCreateGlyphCursor( Display* /* display */, Font /* source_font */, Font /* mask_font */, unsigned int /* source_char */, unsigned int /* mask_char */, XColor _Xconst * /* foreground_color */, XColor _Xconst * /* background_color */ ); extern Cursor XCreateFontCursor( Display* /* display */, unsigned int /* shape */ ); extern Font XLoadFont( Display* /* display */, _Xconst char* /* name */ ); extern GC XCreateGC( Display* /* display */, Drawable /* d */, unsigned long /* valuemask */, XGCValues* /* values */ ); extern GContext XGContextFromGC( GC /* gc */ ); extern void XFlushGC( Display* /* display */, GC /* gc */ ); extern Pixmap XCreatePixmap( Display* /* display */, Drawable /* d */, unsigned int /* width */, unsigned int /* height */, unsigned int /* depth */ ); extern Pixmap XCreateBitmapFromData( Display* /* display */, Drawable /* d */, _Xconst char* /* data */, unsigned int /* width */, unsigned int /* height */ ); extern Pixmap XCreatePixmapFromBitmapData( Display* /* display */, Drawable /* d */, char* /* data */, unsigned int /* width */, unsigned int /* height */, unsigned long /* fg */, unsigned long /* bg */, unsigned int /* depth */ ); extern Window XCreateSimpleWindow( Display* /* display */, Window /* parent */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, unsigned int /* border_width */, unsigned long /* border */, unsigned long /* background */ ); extern Window XGetSelectionOwner( Display* /* display */, Atom /* selection */ ); extern Window XCreateWindow( Display* /* display */, Window /* parent */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, unsigned int /* border_width */, int /* depth */, unsigned int /* class */, Visual* /* visual */, unsigned long /* valuemask */, XSetWindowAttributes* /* attributes */ ); extern Colormap *XListInstalledColormaps( Display* /* display */, Window /* w */, int* /* num_return */ ); extern char **XListFonts( Display* /* display */, _Xconst char* /* pattern */, int /* maxnames */, int* /* actual_count_return */ ); extern char **XListFontsWithInfo( Display* /* display */, _Xconst char* /* pattern */, int /* maxnames */, int* /* count_return */, XFontStruct** /* info_return */ ); extern char **XGetFontPath( Display* /* display */, int* /* npaths_return */ ); extern char **XListExtensions( Display* /* display */, int* /* nextensions_return */ ); extern Atom *XListProperties( Display* /* display */, Window /* w */, int* /* num_prop_return */ ); extern XHostAddress *XListHosts( Display* /* display */, int* /* nhosts_return */, Bool* /* state_return */ ); _X_DEPRECATED extern KeySym XKeycodeToKeysym( Display* /* display */, #if NeedWidePrototypes unsigned int /* keycode */, #else KeyCode /* keycode */, #endif int /* index */ ); extern KeySym XLookupKeysym( XKeyEvent* /* key_event */, int /* index */ ); extern KeySym *XGetKeyboardMapping( Display* /* display */, #if NeedWidePrototypes unsigned int /* first_keycode */, #else KeyCode /* first_keycode */, #endif int /* keycode_count */, int* /* keysyms_per_keycode_return */ ); extern KeySym XStringToKeysym( _Xconst char* /* string */ ); extern long XMaxRequestSize( Display* /* display */ ); extern long XExtendedMaxRequestSize( Display* /* display */ ); extern char *XResourceManagerString( Display* /* display */ ); extern char *XScreenResourceString( Screen* /* screen */ ); extern unsigned long XDisplayMotionBufferSize( Display* /* display */ ); extern VisualID XVisualIDFromVisual( Visual* /* visual */ ); /* multithread routines */ extern Status XInitThreads( void ); extern void XLockDisplay( Display* /* display */ ); extern void XUnlockDisplay( Display* /* display */ ); /* routines for dealing with extensions */ extern XExtCodes *XInitExtension( Display* /* display */, _Xconst char* /* name */ ); extern XExtCodes *XAddExtension( Display* /* display */ ); extern XExtData *XFindOnExtensionList( XExtData** /* structure */, int /* number */ ); extern XExtData **XEHeadOfExtensionList( XEDataObject /* object */ ); /* these are routines for which there are also macros */ extern Window XRootWindow( Display* /* display */, int /* screen_number */ ); extern Window XDefaultRootWindow( Display* /* display */ ); extern Window XRootWindowOfScreen( Screen* /* screen */ ); extern Visual *XDefaultVisual( Display* /* display */, int /* screen_number */ ); extern Visual *XDefaultVisualOfScreen( Screen* /* screen */ ); extern GC XDefaultGC( Display* /* display */, int /* screen_number */ ); extern GC XDefaultGCOfScreen( Screen* /* screen */ ); extern unsigned long XBlackPixel( Display* /* display */, int /* screen_number */ ); extern unsigned long XWhitePixel( Display* /* display */, int /* screen_number */ ); extern unsigned long XAllPlanes( void ); extern unsigned long XBlackPixelOfScreen( Screen* /* screen */ ); extern unsigned long XWhitePixelOfScreen( Screen* /* screen */ ); extern unsigned long XNextRequest( Display* /* display */ ); extern unsigned long XLastKnownRequestProcessed( Display* /* display */ ); extern char *XServerVendor( Display* /* display */ ); extern char *XDisplayString( Display* /* display */ ); extern Colormap XDefaultColormap( Display* /* display */, int /* screen_number */ ); extern Colormap XDefaultColormapOfScreen( Screen* /* screen */ ); extern Display *XDisplayOfScreen( Screen* /* screen */ ); extern Screen *XScreenOfDisplay( Display* /* display */, int /* screen_number */ ); extern Screen *XDefaultScreenOfDisplay( Display* /* display */ ); extern long XEventMaskOfScreen( Screen* /* screen */ ); extern int XScreenNumberOfScreen( Screen* /* screen */ ); typedef int (*XErrorHandler) ( /* WARNING, this type not in Xlib spec */ Display* /* display */, XErrorEvent* /* error_event */ ); extern XErrorHandler XSetErrorHandler ( XErrorHandler /* handler */ ); typedef int (*XIOErrorHandler) ( /* WARNING, this type not in Xlib spec */ Display* /* display */ ); extern XIOErrorHandler XSetIOErrorHandler ( XIOErrorHandler /* handler */ ); extern XPixmapFormatValues *XListPixmapFormats( Display* /* display */, int* /* count_return */ ); extern int *XListDepths( Display* /* display */, int /* screen_number */, int* /* count_return */ ); /* ICCCM routines for things that don't require special include files; */ /* other declarations are given in Xutil.h */ extern Status XReconfigureWMWindow( Display* /* display */, Window /* w */, int /* screen_number */, unsigned int /* mask */, XWindowChanges* /* changes */ ); extern Status XGetWMProtocols( Display* /* display */, Window /* w */, Atom** /* protocols_return */, int* /* count_return */ ); extern Status XSetWMProtocols( Display* /* display */, Window /* w */, Atom* /* protocols */, int /* count */ ); extern Status XIconifyWindow( Display* /* display */, Window /* w */, int /* screen_number */ ); extern Status XWithdrawWindow( Display* /* display */, Window /* w */, int /* screen_number */ ); extern Status XGetCommand( Display* /* display */, Window /* w */, char*** /* argv_return */, int* /* argc_return */ ); extern Status XGetWMColormapWindows( Display* /* display */, Window /* w */, Window** /* windows_return */, int* /* count_return */ ); extern Status XSetWMColormapWindows( Display* /* display */, Window /* w */, Window* /* colormap_windows */, int /* count */ ); extern void XFreeStringList( char** /* list */ ); extern int XSetTransientForHint( Display* /* display */, Window /* w */, Window /* prop_window */ ); /* The following are given in alphabetical order */ extern int XActivateScreenSaver( Display* /* display */ ); extern int XAddHost( Display* /* display */, XHostAddress* /* host */ ); extern int XAddHosts( Display* /* display */, XHostAddress* /* hosts */, int /* num_hosts */ ); extern int XAddToExtensionList( struct _XExtData** /* structure */, XExtData* /* ext_data */ ); extern int XAddToSaveSet( Display* /* display */, Window /* w */ ); extern Status XAllocColor( Display* /* display */, Colormap /* colormap */, XColor* /* screen_in_out */ ); extern Status XAllocColorCells( Display* /* display */, Colormap /* colormap */, Bool /* contig */, unsigned long* /* plane_masks_return */, unsigned int /* nplanes */, unsigned long* /* pixels_return */, unsigned int /* npixels */ ); extern Status XAllocColorPlanes( Display* /* display */, Colormap /* colormap */, Bool /* contig */, unsigned long* /* pixels_return */, int /* ncolors */, int /* nreds */, int /* ngreens */, int /* nblues */, unsigned long* /* rmask_return */, unsigned long* /* gmask_return */, unsigned long* /* bmask_return */ ); extern Status XAllocNamedColor( Display* /* display */, Colormap /* colormap */, _Xconst char* /* color_name */, XColor* /* screen_def_return */, XColor* /* exact_def_return */ ); extern int XAllowEvents( Display* /* display */, int /* event_mode */, Time /* time */ ); extern int XAutoRepeatOff( Display* /* display */ ); extern int XAutoRepeatOn( Display* /* display */ ); extern int XBell( Display* /* display */, int /* percent */ ); extern int XBitmapBitOrder( Display* /* display */ ); extern int XBitmapPad( Display* /* display */ ); extern int XBitmapUnit( Display* /* display */ ); extern int XCellsOfScreen( Screen* /* screen */ ); extern int XChangeActivePointerGrab( Display* /* display */, unsigned int /* event_mask */, Cursor /* cursor */, Time /* time */ ); extern int XChangeGC( Display* /* display */, GC /* gc */, unsigned long /* valuemask */, XGCValues* /* values */ ); extern int XChangeKeyboardControl( Display* /* display */, unsigned long /* value_mask */, XKeyboardControl* /* values */ ); extern int XChangeKeyboardMapping( Display* /* display */, int /* first_keycode */, int /* keysyms_per_keycode */, KeySym* /* keysyms */, int /* num_codes */ ); extern int XChangePointerControl( Display* /* display */, Bool /* do_accel */, Bool /* do_threshold */, int /* accel_numerator */, int /* accel_denominator */, int /* threshold */ ); extern int XChangeProperty( Display* /* display */, Window /* w */, Atom /* property */, Atom /* type */, int /* format */, int /* mode */, _Xconst unsigned char* /* data */, int /* nelements */ ); extern int XChangeSaveSet( Display* /* display */, Window /* w */, int /* change_mode */ ); extern int XChangeWindowAttributes( Display* /* display */, Window /* w */, unsigned long /* valuemask */, XSetWindowAttributes* /* attributes */ ); extern Bool XCheckIfEvent( Display* /* display */, XEvent* /* event_return */, Bool (*) ( Display* /* display */, XEvent* /* event */, XPointer /* arg */ ) /* predicate */, XPointer /* arg */ ); extern Bool XCheckMaskEvent( Display* /* display */, long /* event_mask */, XEvent* /* event_return */ ); extern Bool XCheckTypedEvent( Display* /* display */, int /* event_type */, XEvent* /* event_return */ ); extern Bool XCheckTypedWindowEvent( Display* /* display */, Window /* w */, int /* event_type */, XEvent* /* event_return */ ); extern Bool XCheckWindowEvent( Display* /* display */, Window /* w */, long /* event_mask */, XEvent* /* event_return */ ); extern int XCirculateSubwindows( Display* /* display */, Window /* w */, int /* direction */ ); extern int XCirculateSubwindowsDown( Display* /* display */, Window /* w */ ); extern int XCirculateSubwindowsUp( Display* /* display */, Window /* w */ ); extern int XClearArea( Display* /* display */, Window /* w */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, Bool /* exposures */ ); extern int XClearWindow( Display* /* display */, Window /* w */ ); extern int XCloseDisplay( Display* /* display */ ); extern int XConfigureWindow( Display* /* display */, Window /* w */, unsigned int /* value_mask */, XWindowChanges* /* values */ ); extern int XConnectionNumber( Display* /* display */ ); extern int XConvertSelection( Display* /* display */, Atom /* selection */, Atom /* target */, Atom /* property */, Window /* requestor */, Time /* time */ ); extern int XCopyArea( Display* /* display */, Drawable /* src */, Drawable /* dest */, GC /* gc */, int /* src_x */, int /* src_y */, unsigned int /* width */, unsigned int /* height */, int /* dest_x */, int /* dest_y */ ); extern int XCopyGC( Display* /* display */, GC /* src */, unsigned long /* valuemask */, GC /* dest */ ); extern int XCopyPlane( Display* /* display */, Drawable /* src */, Drawable /* dest */, GC /* gc */, int /* src_x */, int /* src_y */, unsigned int /* width */, unsigned int /* height */, int /* dest_x */, int /* dest_y */, unsigned long /* plane */ ); extern int XDefaultDepth( Display* /* display */, int /* screen_number */ ); extern int XDefaultDepthOfScreen( Screen* /* screen */ ); extern int XDefaultScreen( Display* /* display */ ); extern int XDefineCursor( Display* /* display */, Window /* w */, Cursor /* cursor */ ); extern int XDeleteProperty( Display* /* display */, Window /* w */, Atom /* property */ ); extern int XDestroyWindow( Display* /* display */, Window /* w */ ); extern int XDestroySubwindows( Display* /* display */, Window /* w */ ); extern int XDoesBackingStore( Screen* /* screen */ ); extern Bool XDoesSaveUnders( Screen* /* screen */ ); extern int XDisableAccessControl( Display* /* display */ ); extern int XDisplayCells( Display* /* display */, int /* screen_number */ ); extern int XDisplayHeight( Display* /* display */, int /* screen_number */ ); extern int XDisplayHeightMM( Display* /* display */, int /* screen_number */ ); extern int XDisplayKeycodes( Display* /* display */, int* /* min_keycodes_return */, int* /* max_keycodes_return */ ); extern int XDisplayPlanes( Display* /* display */, int /* screen_number */ ); extern int XDisplayWidth( Display* /* display */, int /* screen_number */ ); extern int XDisplayWidthMM( Display* /* display */, int /* screen_number */ ); extern int XDrawArc( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, int /* angle1 */, int /* angle2 */ ); extern int XDrawArcs( Display* /* display */, Drawable /* d */, GC /* gc */, XArc* /* arcs */, int /* narcs */ ); extern int XDrawImageString( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, _Xconst char* /* string */, int /* length */ ); extern int XDrawImageString16( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, _Xconst XChar2b* /* string */, int /* length */ ); extern int XDrawLine( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x1 */, int /* y1 */, int /* x2 */, int /* y2 */ ); extern int XDrawLines( Display* /* display */, Drawable /* d */, GC /* gc */, XPoint* /* points */, int /* npoints */, int /* mode */ ); extern int XDrawPoint( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */ ); extern int XDrawPoints( Display* /* display */, Drawable /* d */, GC /* gc */, XPoint* /* points */, int /* npoints */, int /* mode */ ); extern int XDrawRectangle( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */ ); extern int XDrawRectangles( Display* /* display */, Drawable /* d */, GC /* gc */, XRectangle* /* rectangles */, int /* nrectangles */ ); extern int XDrawSegments( Display* /* display */, Drawable /* d */, GC /* gc */, XSegment* /* segments */, int /* nsegments */ ); extern int XDrawString( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, _Xconst char* /* string */, int /* length */ ); extern int XDrawString16( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, _Xconst XChar2b* /* string */, int /* length */ ); extern int XDrawText( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, XTextItem* /* items */, int /* nitems */ ); extern int XDrawText16( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, XTextItem16* /* items */, int /* nitems */ ); extern int XEnableAccessControl( Display* /* display */ ); extern int XEventsQueued( Display* /* display */, int /* mode */ ); extern Status XFetchName( Display* /* display */, Window /* w */, char** /* window_name_return */ ); extern int XFillArc( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */, int /* angle1 */, int /* angle2 */ ); extern int XFillArcs( Display* /* display */, Drawable /* d */, GC /* gc */, XArc* /* arcs */, int /* narcs */ ); extern int XFillPolygon( Display* /* display */, Drawable /* d */, GC /* gc */, XPoint* /* points */, int /* npoints */, int /* shape */, int /* mode */ ); extern int XFillRectangle( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */ ); extern int XFillRectangles( Display* /* display */, Drawable /* d */, GC /* gc */, XRectangle* /* rectangles */, int /* nrectangles */ ); extern int XFlush( Display* /* display */ ); extern int XForceScreenSaver( Display* /* display */, int /* mode */ ); extern int XFree( void* /* data */ ); extern int XFreeColormap( Display* /* display */, Colormap /* colormap */ ); extern int XFreeColors( Display* /* display */, Colormap /* colormap */, unsigned long* /* pixels */, int /* npixels */, unsigned long /* planes */ ); extern int XFreeCursor( Display* /* display */, Cursor /* cursor */ ); extern int XFreeExtensionList( char** /* list */ ); extern int XFreeFont( Display* /* display */, XFontStruct* /* font_struct */ ); extern int XFreeFontInfo( char** /* names */, XFontStruct* /* free_info */, int /* actual_count */ ); extern int XFreeFontNames( char** /* list */ ); extern int XFreeFontPath( char** /* list */ ); extern int XFreeGC( Display* /* display */, GC /* gc */ ); extern int XFreeModifiermap( XModifierKeymap* /* modmap */ ); extern int XFreePixmap( Display* /* display */, Pixmap /* pixmap */ ); extern int XGeometry( Display* /* display */, int /* screen */, _Xconst char* /* position */, _Xconst char* /* default_position */, unsigned int /* bwidth */, unsigned int /* fwidth */, unsigned int /* fheight */, int /* xadder */, int /* yadder */, int* /* x_return */, int* /* y_return */, int* /* width_return */, int* /* height_return */ ); extern int XGetErrorDatabaseText( Display* /* display */, _Xconst char* /* name */, _Xconst char* /* message */, _Xconst char* /* default_string */, char* /* buffer_return */, int /* length */ ); extern int XGetErrorText( Display* /* display */, int /* code */, char* /* buffer_return */, int /* length */ ); extern Bool XGetFontProperty( XFontStruct* /* font_struct */, Atom /* atom */, unsigned long* /* value_return */ ); extern Status XGetGCValues( Display* /* display */, GC /* gc */, unsigned long /* valuemask */, XGCValues* /* values_return */ ); extern Status XGetGeometry( Display* /* display */, Drawable /* d */, Window* /* root_return */, int* /* x_return */, int* /* y_return */, unsigned int* /* width_return */, unsigned int* /* height_return */, unsigned int* /* border_width_return */, unsigned int* /* depth_return */ ); extern Status XGetIconName( Display* /* display */, Window /* w */, char** /* icon_name_return */ ); extern int XGetInputFocus( Display* /* display */, Window* /* focus_return */, int* /* revert_to_return */ ); extern int XGetKeyboardControl( Display* /* display */, XKeyboardState* /* values_return */ ); extern int XGetPointerControl( Display* /* display */, int* /* accel_numerator_return */, int* /* accel_denominator_return */, int* /* threshold_return */ ); extern int XGetPointerMapping( Display* /* display */, unsigned char* /* map_return */, int /* nmap */ ); extern int XGetScreenSaver( Display* /* display */, int* /* timeout_return */, int* /* interval_return */, int* /* prefer_blanking_return */, int* /* allow_exposures_return */ ); extern Status XGetTransientForHint( Display* /* display */, Window /* w */, Window* /* prop_window_return */ ); extern int XGetWindowProperty( Display* /* display */, Window /* w */, Atom /* property */, long /* long_offset */, long /* long_length */, Bool /* delete */, Atom /* req_type */, Atom* /* actual_type_return */, int* /* actual_format_return */, unsigned long* /* nitems_return */, unsigned long* /* bytes_after_return */, unsigned char** /* prop_return */ ); extern Status XGetWindowAttributes( Display* /* display */, Window /* w */, XWindowAttributes* /* window_attributes_return */ ); extern int XGrabButton( Display* /* display */, unsigned int /* button */, unsigned int /* modifiers */, Window /* grab_window */, Bool /* owner_events */, unsigned int /* event_mask */, int /* pointer_mode */, int /* keyboard_mode */, Window /* confine_to */, Cursor /* cursor */ ); extern int XGrabKey( Display* /* display */, int /* keycode */, unsigned int /* modifiers */, Window /* grab_window */, Bool /* owner_events */, int /* pointer_mode */, int /* keyboard_mode */ ); extern int XGrabKeyboard( Display* /* display */, Window /* grab_window */, Bool /* owner_events */, int /* pointer_mode */, int /* keyboard_mode */, Time /* time */ ); extern int XGrabPointer( Display* /* display */, Window /* grab_window */, Bool /* owner_events */, unsigned int /* event_mask */, int /* pointer_mode */, int /* keyboard_mode */, Window /* confine_to */, Cursor /* cursor */, Time /* time */ ); extern int XGrabServer( Display* /* display */ ); extern int XHeightMMOfScreen( Screen* /* screen */ ); extern int XHeightOfScreen( Screen* /* screen */ ); extern int XIfEvent( Display* /* display */, XEvent* /* event_return */, Bool (*) ( Display* /* display */, XEvent* /* event */, XPointer /* arg */ ) /* predicate */, XPointer /* arg */ ); extern int XImageByteOrder( Display* /* display */ ); extern int XInstallColormap( Display* /* display */, Colormap /* colormap */ ); extern KeyCode XKeysymToKeycode( Display* /* display */, KeySym /* keysym */ ); extern int XKillClient( Display* /* display */, XID /* resource */ ); extern Status XLookupColor( Display* /* display */, Colormap /* colormap */, _Xconst char* /* color_name */, XColor* /* exact_def_return */, XColor* /* screen_def_return */ ); extern int XLowerWindow( Display* /* display */, Window /* w */ ); extern int XMapRaised( Display* /* display */, Window /* w */ ); extern int XMapSubwindows( Display* /* display */, Window /* w */ ); extern int XMapWindow( Display* /* display */, Window /* w */ ); extern int XMaskEvent( Display* /* display */, long /* event_mask */, XEvent* /* event_return */ ); extern int XMaxCmapsOfScreen( Screen* /* screen */ ); extern int XMinCmapsOfScreen( Screen* /* screen */ ); extern int XMoveResizeWindow( Display* /* display */, Window /* w */, int /* x */, int /* y */, unsigned int /* width */, unsigned int /* height */ ); extern int XMoveWindow( Display* /* display */, Window /* w */, int /* x */, int /* y */ ); extern int XNextEvent( Display* /* display */, XEvent* /* event_return */ ); extern int XNoOp( Display* /* display */ ); extern Status XParseColor( Display* /* display */, Colormap /* colormap */, _Xconst char* /* spec */, XColor* /* exact_def_return */ ); extern int XParseGeometry( _Xconst char* /* parsestring */, int* /* x_return */, int* /* y_return */, unsigned int* /* width_return */, unsigned int* /* height_return */ ); extern int XPeekEvent( Display* /* display */, XEvent* /* event_return */ ); extern int XPeekIfEvent( Display* /* display */, XEvent* /* event_return */, Bool (*) ( Display* /* display */, XEvent* /* event */, XPointer /* arg */ ) /* predicate */, XPointer /* arg */ ); extern int XPending( Display* /* display */ ); extern int XPlanesOfScreen( Screen* /* screen */ ); extern int XProtocolRevision( Display* /* display */ ); extern int XProtocolVersion( Display* /* display */ ); extern int XPutBackEvent( Display* /* display */, XEvent* /* event */ ); extern int XPutImage( Display* /* display */, Drawable /* d */, GC /* gc */, XImage* /* image */, int /* src_x */, int /* src_y */, int /* dest_x */, int /* dest_y */, unsigned int /* width */, unsigned int /* height */ ); extern int XQLength( Display* /* display */ ); extern Status XQueryBestCursor( Display* /* display */, Drawable /* d */, unsigned int /* width */, unsigned int /* height */, unsigned int* /* width_return */, unsigned int* /* height_return */ ); extern Status XQueryBestSize( Display* /* display */, int /* class */, Drawable /* which_screen */, unsigned int /* width */, unsigned int /* height */, unsigned int* /* width_return */, unsigned int* /* height_return */ ); extern Status XQueryBestStipple( Display* /* display */, Drawable /* which_screen */, unsigned int /* width */, unsigned int /* height */, unsigned int* /* width_return */, unsigned int* /* height_return */ ); extern Status XQueryBestTile( Display* /* display */, Drawable /* which_screen */, unsigned int /* width */, unsigned int /* height */, unsigned int* /* width_return */, unsigned int* /* height_return */ ); extern int XQueryColor( Display* /* display */, Colormap /* colormap */, XColor* /* def_in_out */ ); extern int XQueryColors( Display* /* display */, Colormap /* colormap */, XColor* /* defs_in_out */, int /* ncolors */ ); extern Bool XQueryExtension( Display* /* display */, _Xconst char* /* name */, int* /* major_opcode_return */, int* /* first_event_return */, int* /* first_error_return */ ); extern int XQueryKeymap( Display* /* display */, char [32] /* keys_return */ ); extern Bool XQueryPointer( Display* /* display */, Window /* w */, Window* /* root_return */, Window* /* child_return */, int* /* root_x_return */, int* /* root_y_return */, int* /* win_x_return */, int* /* win_y_return */, unsigned int* /* mask_return */ ); extern int XQueryTextExtents( Display* /* display */, XID /* font_ID */, _Xconst char* /* string */, int /* nchars */, int* /* direction_return */, int* /* font_ascent_return */, int* /* font_descent_return */, XCharStruct* /* overall_return */ ); extern int XQueryTextExtents16( Display* /* display */, XID /* font_ID */, _Xconst XChar2b* /* string */, int /* nchars */, int* /* direction_return */, int* /* font_ascent_return */, int* /* font_descent_return */, XCharStruct* /* overall_return */ ); extern Status XQueryTree( Display* /* display */, Window /* w */, Window* /* root_return */, Window* /* parent_return */, Window** /* children_return */, unsigned int* /* nchildren_return */ ); extern int XRaiseWindow( Display* /* display */, Window /* w */ ); extern int XReadBitmapFile( Display* /* display */, Drawable /* d */, _Xconst char* /* filename */, unsigned int* /* width_return */, unsigned int* /* height_return */, Pixmap* /* bitmap_return */, int* /* x_hot_return */, int* /* y_hot_return */ ); extern int XReadBitmapFileData( _Xconst char* /* filename */, unsigned int* /* width_return */, unsigned int* /* height_return */, unsigned char** /* data_return */, int* /* x_hot_return */, int* /* y_hot_return */ ); extern int XRebindKeysym( Display* /* display */, KeySym /* keysym */, KeySym* /* list */, int /* mod_count */, _Xconst unsigned char* /* string */, int /* bytes_string */ ); extern int XRecolorCursor( Display* /* display */, Cursor /* cursor */, XColor* /* foreground_color */, XColor* /* background_color */ ); extern int XRefreshKeyboardMapping( XMappingEvent* /* event_map */ ); extern int XRemoveFromSaveSet( Display* /* display */, Window /* w */ ); extern int XRemoveHost( Display* /* display */, XHostAddress* /* host */ ); extern int XRemoveHosts( Display* /* display */, XHostAddress* /* hosts */, int /* num_hosts */ ); extern int XReparentWindow( Display* /* display */, Window /* w */, Window /* parent */, int /* x */, int /* y */ ); extern int XResetScreenSaver( Display* /* display */ ); extern int XResizeWindow( Display* /* display */, Window /* w */, unsigned int /* width */, unsigned int /* height */ ); extern int XRestackWindows( Display* /* display */, Window* /* windows */, int /* nwindows */ ); extern int XRotateBuffers( Display* /* display */, int /* rotate */ ); extern int XRotateWindowProperties( Display* /* display */, Window /* w */, Atom* /* properties */, int /* num_prop */, int /* npositions */ ); extern int XScreenCount( Display* /* display */ ); extern int XSelectInput( Display* /* display */, Window /* w */, long /* event_mask */ ); extern Status XSendEvent( Display* /* display */, Window /* w */, Bool /* propagate */, long /* event_mask */, XEvent* /* event_send */ ); extern int XSetAccessControl( Display* /* display */, int /* mode */ ); extern int XSetArcMode( Display* /* display */, GC /* gc */, int /* arc_mode */ ); extern int XSetBackground( Display* /* display */, GC /* gc */, unsigned long /* background */ ); extern int XSetClipMask( Display* /* display */, GC /* gc */, Pixmap /* pixmap */ ); extern int XSetClipOrigin( Display* /* display */, GC /* gc */, int /* clip_x_origin */, int /* clip_y_origin */ ); extern int XSetClipRectangles( Display* /* display */, GC /* gc */, int /* clip_x_origin */, int /* clip_y_origin */, XRectangle* /* rectangles */, int /* n */, int /* ordering */ ); extern int XSetCloseDownMode( Display* /* display */, int /* close_mode */ ); extern int XSetCommand( Display* /* display */, Window /* w */, char** /* argv */, int /* argc */ ); extern int XSetDashes( Display* /* display */, GC /* gc */, int /* dash_offset */, _Xconst char* /* dash_list */, int /* n */ ); extern int XSetFillRule( Display* /* display */, GC /* gc */, int /* fill_rule */ ); extern int XSetFillStyle( Display* /* display */, GC /* gc */, int /* fill_style */ ); extern int XSetFont( Display* /* display */, GC /* gc */, Font /* font */ ); extern int XSetFontPath( Display* /* display */, char** /* directories */, int /* ndirs */ ); extern int XSetForeground( Display* /* display */, GC /* gc */, unsigned long /* foreground */ ); extern int XSetFunction( Display* /* display */, GC /* gc */, int /* function */ ); extern int XSetGraphicsExposures( Display* /* display */, GC /* gc */, Bool /* graphics_exposures */ ); extern int XSetIconName( Display* /* display */, Window /* w */, _Xconst char* /* icon_name */ ); extern int XSetInputFocus( Display* /* display */, Window /* focus */, int /* revert_to */, Time /* time */ ); extern int XSetLineAttributes( Display* /* display */, GC /* gc */, unsigned int /* line_width */, int /* line_style */, int /* cap_style */, int /* join_style */ ); extern int XSetModifierMapping( Display* /* display */, XModifierKeymap* /* modmap */ ); extern int XSetPlaneMask( Display* /* display */, GC /* gc */, unsigned long /* plane_mask */ ); extern int XSetPointerMapping( Display* /* display */, _Xconst unsigned char* /* map */, int /* nmap */ ); extern int XSetScreenSaver( Display* /* display */, int /* timeout */, int /* interval */, int /* prefer_blanking */, int /* allow_exposures */ ); extern int XSetSelectionOwner( Display* /* display */, Atom /* selection */, Window /* owner */, Time /* time */ ); extern int XSetState( Display* /* display */, GC /* gc */, unsigned long /* foreground */, unsigned long /* background */, int /* function */, unsigned long /* plane_mask */ ); extern int XSetStipple( Display* /* display */, GC /* gc */, Pixmap /* stipple */ ); extern int XSetSubwindowMode( Display* /* display */, GC /* gc */, int /* subwindow_mode */ ); extern int XSetTSOrigin( Display* /* display */, GC /* gc */, int /* ts_x_origin */, int /* ts_y_origin */ ); extern int XSetTile( Display* /* display */, GC /* gc */, Pixmap /* tile */ ); extern int XSetWindowBackground( Display* /* display */, Window /* w */, unsigned long /* background_pixel */ ); extern int XSetWindowBackgroundPixmap( Display* /* display */, Window /* w */, Pixmap /* background_pixmap */ ); extern int XSetWindowBorder( Display* /* display */, Window /* w */, unsigned long /* border_pixel */ ); extern int XSetWindowBorderPixmap( Display* /* display */, Window /* w */, Pixmap /* border_pixmap */ ); extern int XSetWindowBorderWidth( Display* /* display */, Window /* w */, unsigned int /* width */ ); extern int XSetWindowColormap( Display* /* display */, Window /* w */, Colormap /* colormap */ ); extern int XStoreBuffer( Display* /* display */, _Xconst char* /* bytes */, int /* nbytes */, int /* buffer */ ); extern int XStoreBytes( Display* /* display */, _Xconst char* /* bytes */, int /* nbytes */ ); extern int XStoreColor( Display* /* display */, Colormap /* colormap */, XColor* /* color */ ); extern int XStoreColors( Display* /* display */, Colormap /* colormap */, XColor* /* color */, int /* ncolors */ ); extern int XStoreName( Display* /* display */, Window /* w */, _Xconst char* /* window_name */ ); extern int XStoreNamedColor( Display* /* display */, Colormap /* colormap */, _Xconst char* /* color */, unsigned long /* pixel */, int /* flags */ ); extern int XSync( Display* /* display */, Bool /* discard */ ); extern int XTextExtents( XFontStruct* /* font_struct */, _Xconst char* /* string */, int /* nchars */, int* /* direction_return */, int* /* font_ascent_return */, int* /* font_descent_return */, XCharStruct* /* overall_return */ ); extern int XTextExtents16( XFontStruct* /* font_struct */, _Xconst XChar2b* /* string */, int /* nchars */, int* /* direction_return */, int* /* font_ascent_return */, int* /* font_descent_return */, XCharStruct* /* overall_return */ ); extern int XTextWidth( XFontStruct* /* font_struct */, _Xconst char* /* string */, int /* count */ ); extern int XTextWidth16( XFontStruct* /* font_struct */, _Xconst XChar2b* /* string */, int /* count */ ); extern Bool XTranslateCoordinates( Display* /* display */, Window /* src_w */, Window /* dest_w */, int /* src_x */, int /* src_y */, int* /* dest_x_return */, int* /* dest_y_return */, Window* /* child_return */ ); extern int XUndefineCursor( Display* /* display */, Window /* w */ ); extern int XUngrabButton( Display* /* display */, unsigned int /* button */, unsigned int /* modifiers */, Window /* grab_window */ ); extern int XUngrabKey( Display* /* display */, int /* keycode */, unsigned int /* modifiers */, Window /* grab_window */ ); extern int XUngrabKeyboard( Display* /* display */, Time /* time */ ); extern int XUngrabPointer( Display* /* display */, Time /* time */ ); extern int XUngrabServer( Display* /* display */ ); extern int XUninstallColormap( Display* /* display */, Colormap /* colormap */ ); extern int XUnloadFont( Display* /* display */, Font /* font */ ); extern int XUnmapSubwindows( Display* /* display */, Window /* w */ ); extern int XUnmapWindow( Display* /* display */, Window /* w */ ); extern int XVendorRelease( Display* /* display */ ); extern int XWarpPointer( Display* /* display */, Window /* src_w */, Window /* dest_w */, int /* src_x */, int /* src_y */, unsigned int /* src_width */, unsigned int /* src_height */, int /* dest_x */, int /* dest_y */ ); extern int XWidthMMOfScreen( Screen* /* screen */ ); extern int XWidthOfScreen( Screen* /* screen */ ); extern int XWindowEvent( Display* /* display */, Window /* w */, long /* event_mask */, XEvent* /* event_return */ ); extern int XWriteBitmapFile( Display* /* display */, _Xconst char* /* filename */, Pixmap /* bitmap */, unsigned int /* width */, unsigned int /* height */, int /* x_hot */, int /* y_hot */ ); extern Bool XSupportsLocale (void); extern char *XSetLocaleModifiers( const char* /* modifier_list */ ); extern XOM XOpenOM( Display* /* display */, struct _XrmHashBucketRec* /* rdb */, _Xconst char* /* res_name */, _Xconst char* /* res_class */ ); extern Status XCloseOM( XOM /* om */ ); extern char *XSetOMValues( XOM /* om */, ... ) _X_SENTINEL(0); extern char *XGetOMValues( XOM /* om */, ... ) _X_SENTINEL(0); extern Display *XDisplayOfOM( XOM /* om */ ); extern char *XLocaleOfOM( XOM /* om */ ); extern XOC XCreateOC( XOM /* om */, ... ) _X_SENTINEL(0); extern void XDestroyOC( XOC /* oc */ ); extern XOM XOMOfOC( XOC /* oc */ ); extern char *XSetOCValues( XOC /* oc */, ... ) _X_SENTINEL(0); extern char *XGetOCValues( XOC /* oc */, ... ) _X_SENTINEL(0); extern XFontSet XCreateFontSet( Display* /* display */, _Xconst char* /* base_font_name_list */, char*** /* missing_charset_list */, int* /* missing_charset_count */, char** /* def_string */ ); extern void XFreeFontSet( Display* /* display */, XFontSet /* font_set */ ); extern int XFontsOfFontSet( XFontSet /* font_set */, XFontStruct*** /* font_struct_list */, char*** /* font_name_list */ ); extern char *XBaseFontNameListOfFontSet( XFontSet /* font_set */ ); extern char *XLocaleOfFontSet( XFontSet /* font_set */ ); extern Bool XContextDependentDrawing( XFontSet /* font_set */ ); extern Bool XDirectionalDependentDrawing( XFontSet /* font_set */ ); extern Bool XContextualDrawing( XFontSet /* font_set */ ); extern XFontSetExtents *XExtentsOfFontSet( XFontSet /* font_set */ ); extern int XmbTextEscapement( XFontSet /* font_set */, _Xconst char* /* text */, int /* bytes_text */ ); extern int XwcTextEscapement( XFontSet /* font_set */, _Xconst wchar_t* /* text */, int /* num_wchars */ ); extern int Xutf8TextEscapement( XFontSet /* font_set */, _Xconst char* /* text */, int /* bytes_text */ ); extern int XmbTextExtents( XFontSet /* font_set */, _Xconst char* /* text */, int /* bytes_text */, XRectangle* /* overall_ink_return */, XRectangle* /* overall_logical_return */ ); extern int XwcTextExtents( XFontSet /* font_set */, _Xconst wchar_t* /* text */, int /* num_wchars */, XRectangle* /* overall_ink_return */, XRectangle* /* overall_logical_return */ ); extern int Xutf8TextExtents( XFontSet /* font_set */, _Xconst char* /* text */, int /* bytes_text */, XRectangle* /* overall_ink_return */, XRectangle* /* overall_logical_return */ ); extern Status XmbTextPerCharExtents( XFontSet /* font_set */, _Xconst char* /* text */, int /* bytes_text */, XRectangle* /* ink_extents_buffer */, XRectangle* /* logical_extents_buffer */, int /* buffer_size */, int* /* num_chars */, XRectangle* /* overall_ink_return */, XRectangle* /* overall_logical_return */ ); extern Status XwcTextPerCharExtents( XFontSet /* font_set */, _Xconst wchar_t* /* text */, int /* num_wchars */, XRectangle* /* ink_extents_buffer */, XRectangle* /* logical_extents_buffer */, int /* buffer_size */, int* /* num_chars */, XRectangle* /* overall_ink_return */, XRectangle* /* overall_logical_return */ ); extern Status Xutf8TextPerCharExtents( XFontSet /* font_set */, _Xconst char* /* text */, int /* bytes_text */, XRectangle* /* ink_extents_buffer */, XRectangle* /* logical_extents_buffer */, int /* buffer_size */, int* /* num_chars */, XRectangle* /* overall_ink_return */, XRectangle* /* overall_logical_return */ ); extern void XmbDrawText( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, XmbTextItem* /* text_items */, int /* nitems */ ); extern void XwcDrawText( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, XwcTextItem* /* text_items */, int /* nitems */ ); extern void Xutf8DrawText( Display* /* display */, Drawable /* d */, GC /* gc */, int /* x */, int /* y */, XmbTextItem* /* text_items */, int /* nitems */ ); extern void XmbDrawString( Display* /* display */, Drawable /* d */, XFontSet /* font_set */, GC /* gc */, int /* x */, int /* y */, _Xconst char* /* text */, int /* bytes_text */ ); extern void XwcDrawString( Display* /* display */, Drawable /* d */, XFontSet /* font_set */, GC /* gc */, int /* x */, int /* y */, _Xconst wchar_t* /* text */, int /* num_wchars */ ); extern void Xutf8DrawString( Display* /* display */, Drawable /* d */, XFontSet /* font_set */, GC /* gc */, int /* x */, int /* y */, _Xconst char* /* text */, int /* bytes_text */ ); extern void XmbDrawImageString( Display* /* display */, Drawable /* d */, XFontSet /* font_set */, GC /* gc */, int /* x */, int /* y */, _Xconst char* /* text */, int /* bytes_text */ ); extern void XwcDrawImageString( Display* /* display */, Drawable /* d */, XFontSet /* font_set */, GC /* gc */, int /* x */, int /* y */, _Xconst wchar_t* /* text */, int /* num_wchars */ ); extern void Xutf8DrawImageString( Display* /* display */, Drawable /* d */, XFontSet /* font_set */, GC /* gc */, int /* x */, int /* y */, _Xconst char* /* text */, int /* bytes_text */ ); extern XIM XOpenIM( Display* /* dpy */, struct _XrmHashBucketRec* /* rdb */, char* /* res_name */, char* /* res_class */ ); extern Status XCloseIM( XIM /* im */ ); extern char *XGetIMValues( XIM /* im */, ... ) _X_SENTINEL(0); extern char *XSetIMValues( XIM /* im */, ... ) _X_SENTINEL(0); extern Display *XDisplayOfIM( XIM /* im */ ); extern char *XLocaleOfIM( XIM /* im*/ ); extern XIC XCreateIC( XIM /* im */, ... ) _X_SENTINEL(0); extern void XDestroyIC( XIC /* ic */ ); extern void XSetICFocus( XIC /* ic */ ); extern void XUnsetICFocus( XIC /* ic */ ); extern wchar_t *XwcResetIC( XIC /* ic */ ); extern char *XmbResetIC( XIC /* ic */ ); extern char *Xutf8ResetIC( XIC /* ic */ ); extern char *XSetICValues( XIC /* ic */, ... ) _X_SENTINEL(0); extern char *XGetICValues( XIC /* ic */, ... ) _X_SENTINEL(0); extern XIM XIMOfIC( XIC /* ic */ ); extern Bool XFilterEvent( XEvent* /* event */, Window /* window */ ); extern int XmbLookupString( XIC /* ic */, XKeyPressedEvent* /* event */, char* /* buffer_return */, int /* bytes_buffer */, KeySym* /* keysym_return */, Status* /* status_return */ ); extern int XwcLookupString( XIC /* ic */, XKeyPressedEvent* /* event */, wchar_t* /* buffer_return */, int /* wchars_buffer */, KeySym* /* keysym_return */, Status* /* status_return */ ); extern int Xutf8LookupString( XIC /* ic */, XKeyPressedEvent* /* event */, char* /* buffer_return */, int /* bytes_buffer */, KeySym* /* keysym_return */, Status* /* status_return */ ); extern XVaNestedList XVaCreateNestedList( int /*unused*/, ... ) _X_SENTINEL(0); /* internal connections for IMs */ extern Bool XRegisterIMInstantiateCallback( Display* /* dpy */, struct _XrmHashBucketRec* /* rdb */, char* /* res_name */, char* /* res_class */, XIDProc /* callback */, XPointer /* client_data */ ); extern Bool XUnregisterIMInstantiateCallback( Display* /* dpy */, struct _XrmHashBucketRec* /* rdb */, char* /* res_name */, char* /* res_class */, XIDProc /* callback */, XPointer /* client_data */ ); typedef void (*XConnectionWatchProc)( Display* /* dpy */, XPointer /* client_data */, int /* fd */, Bool /* opening */, /* open or close flag */ XPointer* /* watch_data */ /* open sets, close uses */ ); extern Status XInternalConnectionNumbers( Display* /* dpy */, int** /* fd_return */, int* /* count_return */ ); extern void XProcessInternalConnection( Display* /* dpy */, int /* fd */ ); extern Status XAddConnectionWatch( Display* /* dpy */, XConnectionWatchProc /* callback */, XPointer /* client_data */ ); extern void XRemoveConnectionWatch( Display* /* dpy */, XConnectionWatchProc /* callback */, XPointer /* client_data */ ); extern void XSetAuthorization( char * /* name */, int /* namelen */, char * /* data */, int /* datalen */ ); extern int _Xmbtowc( wchar_t * /* wstr */, char * /* str */, int /* len */ ); extern int _Xwctomb( char * /* str */, wchar_t /* wc */ ); extern Bool XGetEventData( Display* /* dpy */, XGenericEventCookie* /* cookie*/ ); extern void XFreeEventData( Display* /* dpy */, XGenericEventCookie* /* cookie*/ ); #ifdef __clang__ #pragma clang diagnostic pop #endif _XFUNCPROTOEND #endif /* _X11_XLIB_H_ */ X11/keysymdef.h000064400000526220151027430550007277 0ustar00/*********************************************************** Copyright 1987, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* * The "X11 Window System Protocol" standard defines in Appendix A the * keysym codes. These 29-bit integer values identify characters or * functions associated with each key (e.g., via the visible * engraving) of a keyboard layout. This file assigns mnemonic macro * names for these keysyms. * * This file is also compiled (by src/util/makekeys.c in libX11) into * hash tables that can be accessed with X11 library functions such as * XStringToKeysym() and XKeysymToString(). * * Where a keysym corresponds one-to-one to an ISO 10646 / Unicode * character, this is noted in a comment that provides both the U+xxxx * Unicode position, as well as the official Unicode name of the * character. * * Where the correspondence is either not one-to-one or semantically * unclear, the Unicode position and name are enclosed in * parentheses. Such legacy keysyms should be considered deprecated * and are not recommended for use in future keyboard mappings. * * For any future extension of the keysyms with characters already * found in ISO 10646 / Unicode, the following algorithm shall be * used. The new keysym code position will simply be the character's * Unicode number plus 0x01000000. The keysym values in the range * 0x01000100 to 0x0110ffff are reserved to represent Unicode * characters in the range U+0100 to U+10FFFF. * * While most newer Unicode-based X11 clients do already accept * Unicode-mapped keysyms in the range 0x01000100 to 0x0110ffff, it * will remain necessary for clients -- in the interest of * compatibility with existing servers -- to also understand the * existing legacy keysym values in the range 0x0100 to 0x20ff. * * Where several mnemonic names are defined for the same keysym in this * file, all but the first one listed should be considered deprecated. * * Mnemonic names for keysyms are defined in this file with lines * that match one of these Perl regular expressions: * * /^\#define XK_([a-zA-Z_0-9]+)\s+0x([0-9a-f]+)\s*\/\* U+([0-9A-F]{4,6}) (.*) \*\/\s*$/ * /^\#define XK_([a-zA-Z_0-9]+)\s+0x([0-9a-f]+)\s*\/\*\(U+([0-9A-F]{4,6}) (.*)\)\*\/\s*$/ * /^\#define XK_([a-zA-Z_0-9]+)\s+0x([0-9a-f]+)\s*(\/\*\s*(.*)\s*\*\/)?\s*$/ * * Before adding new keysyms, please do consider the following: In * addition to the keysym names defined in this file, the * XStringToKeysym() and XKeysymToString() functions will also handle * any keysym string of the form "U0020" to "U007E" and "U00A0" to * "U10FFFF" for all possible Unicode characters. In other words, * every possible Unicode character has already a keysym string * defined algorithmically, even if it is not listed here. Therefore, * defining an additional keysym macro is only necessary where a * non-hexadecimal mnemonic name is needed, or where the new keysym * does not represent any existing Unicode character. * * When adding new keysyms to this file, do not forget to also update the * following as needed: * * - the mappings in src/KeyBind.c in the libX11 repo * https://gitlab.freedesktop.org/xorg/lib/libx11 * * - the protocol specification in specs/keysyms.xml in this repo * https://gitlab.freedesktop.org/xorg/proto/xorgproto * */ #define XK_VoidSymbol 0xffffff /* Void symbol */ #ifdef XK_MISCELLANY /* * TTY function keys, cleverly chosen to map to ASCII, for convenience of * programming, but could have been arbitrary (at the cost of lookup * tables in client code). */ #define XK_BackSpace 0xff08 /* Back space, back char */ #define XK_Tab 0xff09 #define XK_Linefeed 0xff0a /* Linefeed, LF */ #define XK_Clear 0xff0b #define XK_Return 0xff0d /* Return, enter */ #define XK_Pause 0xff13 /* Pause, hold */ #define XK_Scroll_Lock 0xff14 #define XK_Sys_Req 0xff15 #define XK_Escape 0xff1b #define XK_Delete 0xffff /* Delete, rubout */ /* International & multi-key character composition */ #define XK_Multi_key 0xff20 /* Multi-key character compose */ #define XK_Codeinput 0xff37 #define XK_SingleCandidate 0xff3c #define XK_MultipleCandidate 0xff3d #define XK_PreviousCandidate 0xff3e /* Japanese keyboard support */ #define XK_Kanji 0xff21 /* Kanji, Kanji convert */ #define XK_Muhenkan 0xff22 /* Cancel Conversion */ #define XK_Henkan_Mode 0xff23 /* Start/Stop Conversion */ #define XK_Henkan 0xff23 /* Alias for Henkan_Mode */ #define XK_Romaji 0xff24 /* to Romaji */ #define XK_Hiragana 0xff25 /* to Hiragana */ #define XK_Katakana 0xff26 /* to Katakana */ #define XK_Hiragana_Katakana 0xff27 /* Hiragana/Katakana toggle */ #define XK_Zenkaku 0xff28 /* to Zenkaku */ #define XK_Hankaku 0xff29 /* to Hankaku */ #define XK_Zenkaku_Hankaku 0xff2a /* Zenkaku/Hankaku toggle */ #define XK_Touroku 0xff2b /* Add to Dictionary */ #define XK_Massyo 0xff2c /* Delete from Dictionary */ #define XK_Kana_Lock 0xff2d /* Kana Lock */ #define XK_Kana_Shift 0xff2e /* Kana Shift */ #define XK_Eisu_Shift 0xff2f /* Alphanumeric Shift */ #define XK_Eisu_toggle 0xff30 /* Alphanumeric toggle */ #define XK_Kanji_Bangou 0xff37 /* Codeinput */ #define XK_Zen_Koho 0xff3d /* Multiple/All Candidate(s) */ #define XK_Mae_Koho 0xff3e /* Previous Candidate */ /* 0xff31 thru 0xff3f are under XK_KOREAN */ /* Cursor control & motion */ #define XK_Home 0xff50 #define XK_Left 0xff51 /* Move left, left arrow */ #define XK_Up 0xff52 /* Move up, up arrow */ #define XK_Right 0xff53 /* Move right, right arrow */ #define XK_Down 0xff54 /* Move down, down arrow */ #define XK_Prior 0xff55 /* Prior, previous */ #define XK_Page_Up 0xff55 #define XK_Next 0xff56 /* Next */ #define XK_Page_Down 0xff56 #define XK_End 0xff57 /* EOL */ #define XK_Begin 0xff58 /* BOL */ /* Misc functions */ #define XK_Select 0xff60 /* Select, mark */ #define XK_Print 0xff61 #define XK_Execute 0xff62 /* Execute, run, do */ #define XK_Insert 0xff63 /* Insert, insert here */ #define XK_Undo 0xff65 #define XK_Redo 0xff66 /* Redo, again */ #define XK_Menu 0xff67 #define XK_Find 0xff68 /* Find, search */ #define XK_Cancel 0xff69 /* Cancel, stop, abort, exit */ #define XK_Help 0xff6a /* Help */ #define XK_Break 0xff6b #define XK_Mode_switch 0xff7e /* Character set switch */ #define XK_script_switch 0xff7e /* Alias for mode_switch */ #define XK_Num_Lock 0xff7f /* Keypad functions, keypad numbers cleverly chosen to map to ASCII */ #define XK_KP_Space 0xff80 /* Space */ #define XK_KP_Tab 0xff89 #define XK_KP_Enter 0xff8d /* Enter */ #define XK_KP_F1 0xff91 /* PF1, KP_A, ... */ #define XK_KP_F2 0xff92 #define XK_KP_F3 0xff93 #define XK_KP_F4 0xff94 #define XK_KP_Home 0xff95 #define XK_KP_Left 0xff96 #define XK_KP_Up 0xff97 #define XK_KP_Right 0xff98 #define XK_KP_Down 0xff99 #define XK_KP_Prior 0xff9a #define XK_KP_Page_Up 0xff9a #define XK_KP_Next 0xff9b #define XK_KP_Page_Down 0xff9b #define XK_KP_End 0xff9c #define XK_KP_Begin 0xff9d #define XK_KP_Insert 0xff9e #define XK_KP_Delete 0xff9f #define XK_KP_Equal 0xffbd /* Equals */ #define XK_KP_Multiply 0xffaa #define XK_KP_Add 0xffab #define XK_KP_Separator 0xffac /* Separator, often comma */ #define XK_KP_Subtract 0xffad #define XK_KP_Decimal 0xffae #define XK_KP_Divide 0xffaf #define XK_KP_0 0xffb0 #define XK_KP_1 0xffb1 #define XK_KP_2 0xffb2 #define XK_KP_3 0xffb3 #define XK_KP_4 0xffb4 #define XK_KP_5 0xffb5 #define XK_KP_6 0xffb6 #define XK_KP_7 0xffb7 #define XK_KP_8 0xffb8 #define XK_KP_9 0xffb9 /* * Auxiliary functions; note the duplicate definitions for left and right * function keys; Sun keyboards and a few other manufacturers have such * function key groups on the left and/or right sides of the keyboard. * We've not found a keyboard with more than 35 function keys total. */ #define XK_F1 0xffbe #define XK_F2 0xffbf #define XK_F3 0xffc0 #define XK_F4 0xffc1 #define XK_F5 0xffc2 #define XK_F6 0xffc3 #define XK_F7 0xffc4 #define XK_F8 0xffc5 #define XK_F9 0xffc6 #define XK_F10 0xffc7 #define XK_F11 0xffc8 #define XK_L1 0xffc8 #define XK_F12 0xffc9 #define XK_L2 0xffc9 #define XK_F13 0xffca #define XK_L3 0xffca #define XK_F14 0xffcb #define XK_L4 0xffcb #define XK_F15 0xffcc #define XK_L5 0xffcc #define XK_F16 0xffcd #define XK_L6 0xffcd #define XK_F17 0xffce #define XK_L7 0xffce #define XK_F18 0xffcf #define XK_L8 0xffcf #define XK_F19 0xffd0 #define XK_L9 0xffd0 #define XK_F20 0xffd1 #define XK_L10 0xffd1 #define XK_F21 0xffd2 #define XK_R1 0xffd2 #define XK_F22 0xffd3 #define XK_R2 0xffd3 #define XK_F23 0xffd4 #define XK_R3 0xffd4 #define XK_F24 0xffd5 #define XK_R4 0xffd5 #define XK_F25 0xffd6 #define XK_R5 0xffd6 #define XK_F26 0xffd7 #define XK_R6 0xffd7 #define XK_F27 0xffd8 #define XK_R7 0xffd8 #define XK_F28 0xffd9 #define XK_R8 0xffd9 #define XK_F29 0xffda #define XK_R9 0xffda #define XK_F30 0xffdb #define XK_R10 0xffdb #define XK_F31 0xffdc #define XK_R11 0xffdc #define XK_F32 0xffdd #define XK_R12 0xffdd #define XK_F33 0xffde #define XK_R13 0xffde #define XK_F34 0xffdf #define XK_R14 0xffdf #define XK_F35 0xffe0 #define XK_R15 0xffe0 /* Modifiers */ #define XK_Shift_L 0xffe1 /* Left shift */ #define XK_Shift_R 0xffe2 /* Right shift */ #define XK_Control_L 0xffe3 /* Left control */ #define XK_Control_R 0xffe4 /* Right control */ #define XK_Caps_Lock 0xffe5 /* Caps lock */ #define XK_Shift_Lock 0xffe6 /* Shift lock */ #define XK_Meta_L 0xffe7 /* Left meta */ #define XK_Meta_R 0xffe8 /* Right meta */ #define XK_Alt_L 0xffe9 /* Left alt */ #define XK_Alt_R 0xffea /* Right alt */ #define XK_Super_L 0xffeb /* Left super */ #define XK_Super_R 0xffec /* Right super */ #define XK_Hyper_L 0xffed /* Left hyper */ #define XK_Hyper_R 0xffee /* Right hyper */ #endif /* XK_MISCELLANY */ /* * Keyboard (XKB) Extension function and modifier keys * (from Appendix C of "The X Keyboard Extension: Protocol Specification") * Byte 3 = 0xfe */ #ifdef XK_XKB_KEYS #define XK_ISO_Lock 0xfe01 #define XK_ISO_Level2_Latch 0xfe02 #define XK_ISO_Level3_Shift 0xfe03 #define XK_ISO_Level3_Latch 0xfe04 #define XK_ISO_Level3_Lock 0xfe05 #define XK_ISO_Level5_Shift 0xfe11 #define XK_ISO_Level5_Latch 0xfe12 #define XK_ISO_Level5_Lock 0xfe13 #define XK_ISO_Group_Shift 0xff7e /* Alias for mode_switch */ #define XK_ISO_Group_Latch 0xfe06 #define XK_ISO_Group_Lock 0xfe07 #define XK_ISO_Next_Group 0xfe08 #define XK_ISO_Next_Group_Lock 0xfe09 #define XK_ISO_Prev_Group 0xfe0a #define XK_ISO_Prev_Group_Lock 0xfe0b #define XK_ISO_First_Group 0xfe0c #define XK_ISO_First_Group_Lock 0xfe0d #define XK_ISO_Last_Group 0xfe0e #define XK_ISO_Last_Group_Lock 0xfe0f #define XK_ISO_Left_Tab 0xfe20 #define XK_ISO_Move_Line_Up 0xfe21 #define XK_ISO_Move_Line_Down 0xfe22 #define XK_ISO_Partial_Line_Up 0xfe23 #define XK_ISO_Partial_Line_Down 0xfe24 #define XK_ISO_Partial_Space_Left 0xfe25 #define XK_ISO_Partial_Space_Right 0xfe26 #define XK_ISO_Set_Margin_Left 0xfe27 #define XK_ISO_Set_Margin_Right 0xfe28 #define XK_ISO_Release_Margin_Left 0xfe29 #define XK_ISO_Release_Margin_Right 0xfe2a #define XK_ISO_Release_Both_Margins 0xfe2b #define XK_ISO_Fast_Cursor_Left 0xfe2c #define XK_ISO_Fast_Cursor_Right 0xfe2d #define XK_ISO_Fast_Cursor_Up 0xfe2e #define XK_ISO_Fast_Cursor_Down 0xfe2f #define XK_ISO_Continuous_Underline 0xfe30 #define XK_ISO_Discontinuous_Underline 0xfe31 #define XK_ISO_Emphasize 0xfe32 #define XK_ISO_Center_Object 0xfe33 #define XK_ISO_Enter 0xfe34 #define XK_dead_grave 0xfe50 #define XK_dead_acute 0xfe51 #define XK_dead_circumflex 0xfe52 #define XK_dead_tilde 0xfe53 #define XK_dead_perispomeni 0xfe53 /* alias for dead_tilde */ #define XK_dead_macron 0xfe54 #define XK_dead_breve 0xfe55 #define XK_dead_abovedot 0xfe56 #define XK_dead_diaeresis 0xfe57 #define XK_dead_abovering 0xfe58 #define XK_dead_doubleacute 0xfe59 #define XK_dead_caron 0xfe5a #define XK_dead_cedilla 0xfe5b #define XK_dead_ogonek 0xfe5c #define XK_dead_iota 0xfe5d #define XK_dead_voiced_sound 0xfe5e #define XK_dead_semivoiced_sound 0xfe5f #define XK_dead_belowdot 0xfe60 #define XK_dead_hook 0xfe61 #define XK_dead_horn 0xfe62 #define XK_dead_stroke 0xfe63 #define XK_dead_abovecomma 0xfe64 #define XK_dead_psili 0xfe64 /* alias for dead_abovecomma */ #define XK_dead_abovereversedcomma 0xfe65 #define XK_dead_dasia 0xfe65 /* alias for dead_abovereversedcomma */ #define XK_dead_doublegrave 0xfe66 #define XK_dead_belowring 0xfe67 #define XK_dead_belowmacron 0xfe68 #define XK_dead_belowcircumflex 0xfe69 #define XK_dead_belowtilde 0xfe6a #define XK_dead_belowbreve 0xfe6b #define XK_dead_belowdiaeresis 0xfe6c #define XK_dead_invertedbreve 0xfe6d #define XK_dead_belowcomma 0xfe6e #define XK_dead_currency 0xfe6f /* extra dead elements for German T3 layout */ #define XK_dead_lowline 0xfe90 #define XK_dead_aboveverticalline 0xfe91 #define XK_dead_belowverticalline 0xfe92 #define XK_dead_longsolidusoverlay 0xfe93 /* dead vowels for universal syllable entry */ #define XK_dead_a 0xfe80 #define XK_dead_A 0xfe81 #define XK_dead_e 0xfe82 #define XK_dead_E 0xfe83 #define XK_dead_i 0xfe84 #define XK_dead_I 0xfe85 #define XK_dead_o 0xfe86 #define XK_dead_O 0xfe87 #define XK_dead_u 0xfe88 #define XK_dead_U 0xfe89 #define XK_dead_small_schwa 0xfe8a #define XK_dead_capital_schwa 0xfe8b #define XK_dead_greek 0xfe8c #define XK_First_Virtual_Screen 0xfed0 #define XK_Prev_Virtual_Screen 0xfed1 #define XK_Next_Virtual_Screen 0xfed2 #define XK_Last_Virtual_Screen 0xfed4 #define XK_Terminate_Server 0xfed5 #define XK_AccessX_Enable 0xfe70 #define XK_AccessX_Feedback_Enable 0xfe71 #define XK_RepeatKeys_Enable 0xfe72 #define XK_SlowKeys_Enable 0xfe73 #define XK_BounceKeys_Enable 0xfe74 #define XK_StickyKeys_Enable 0xfe75 #define XK_MouseKeys_Enable 0xfe76 #define XK_MouseKeys_Accel_Enable 0xfe77 #define XK_Overlay1_Enable 0xfe78 #define XK_Overlay2_Enable 0xfe79 #define XK_AudibleBell_Enable 0xfe7a #define XK_Pointer_Left 0xfee0 #define XK_Pointer_Right 0xfee1 #define XK_Pointer_Up 0xfee2 #define XK_Pointer_Down 0xfee3 #define XK_Pointer_UpLeft 0xfee4 #define XK_Pointer_UpRight 0xfee5 #define XK_Pointer_DownLeft 0xfee6 #define XK_Pointer_DownRight 0xfee7 #define XK_Pointer_Button_Dflt 0xfee8 #define XK_Pointer_Button1 0xfee9 #define XK_Pointer_Button2 0xfeea #define XK_Pointer_Button3 0xfeeb #define XK_Pointer_Button4 0xfeec #define XK_Pointer_Button5 0xfeed #define XK_Pointer_DblClick_Dflt 0xfeee #define XK_Pointer_DblClick1 0xfeef #define XK_Pointer_DblClick2 0xfef0 #define XK_Pointer_DblClick3 0xfef1 #define XK_Pointer_DblClick4 0xfef2 #define XK_Pointer_DblClick5 0xfef3 #define XK_Pointer_Drag_Dflt 0xfef4 #define XK_Pointer_Drag1 0xfef5 #define XK_Pointer_Drag2 0xfef6 #define XK_Pointer_Drag3 0xfef7 #define XK_Pointer_Drag4 0xfef8 #define XK_Pointer_Drag5 0xfefd #define XK_Pointer_EnableKeys 0xfef9 #define XK_Pointer_Accelerate 0xfefa #define XK_Pointer_DfltBtnNext 0xfefb #define XK_Pointer_DfltBtnPrev 0xfefc /* Single-Stroke Multiple-Character N-Graph Keysyms For The X Input Method */ #define XK_ch 0xfea0 #define XK_Ch 0xfea1 #define XK_CH 0xfea2 #define XK_c_h 0xfea3 #define XK_C_h 0xfea4 #define XK_C_H 0xfea5 #endif /* XK_XKB_KEYS */ /* * 3270 Terminal Keys * Byte 3 = 0xfd */ #ifdef XK_3270 #define XK_3270_Duplicate 0xfd01 #define XK_3270_FieldMark 0xfd02 #define XK_3270_Right2 0xfd03 #define XK_3270_Left2 0xfd04 #define XK_3270_BackTab 0xfd05 #define XK_3270_EraseEOF 0xfd06 #define XK_3270_EraseInput 0xfd07 #define XK_3270_Reset 0xfd08 #define XK_3270_Quit 0xfd09 #define XK_3270_PA1 0xfd0a #define XK_3270_PA2 0xfd0b #define XK_3270_PA3 0xfd0c #define XK_3270_Test 0xfd0d #define XK_3270_Attn 0xfd0e #define XK_3270_CursorBlink 0xfd0f #define XK_3270_AltCursor 0xfd10 #define XK_3270_KeyClick 0xfd11 #define XK_3270_Jump 0xfd12 #define XK_3270_Ident 0xfd13 #define XK_3270_Rule 0xfd14 #define XK_3270_Copy 0xfd15 #define XK_3270_Play 0xfd16 #define XK_3270_Setup 0xfd17 #define XK_3270_Record 0xfd18 #define XK_3270_ChangeScreen 0xfd19 #define XK_3270_DeleteWord 0xfd1a #define XK_3270_ExSelect 0xfd1b #define XK_3270_CursorSelect 0xfd1c #define XK_3270_PrintScreen 0xfd1d #define XK_3270_Enter 0xfd1e #endif /* XK_3270 */ /* * Latin 1 * (ISO/IEC 8859-1 = Unicode U+0020..U+00FF) * Byte 3 = 0 */ #ifdef XK_LATIN1 #define XK_space 0x0020 /* U+0020 SPACE */ #define XK_exclam 0x0021 /* U+0021 EXCLAMATION MARK */ #define XK_quotedbl 0x0022 /* U+0022 QUOTATION MARK */ #define XK_numbersign 0x0023 /* U+0023 NUMBER SIGN */ #define XK_dollar 0x0024 /* U+0024 DOLLAR SIGN */ #define XK_percent 0x0025 /* U+0025 PERCENT SIGN */ #define XK_ampersand 0x0026 /* U+0026 AMPERSAND */ #define XK_apostrophe 0x0027 /* U+0027 APOSTROPHE */ #define XK_quoteright 0x0027 /* deprecated */ #define XK_parenleft 0x0028 /* U+0028 LEFT PARENTHESIS */ #define XK_parenright 0x0029 /* U+0029 RIGHT PARENTHESIS */ #define XK_asterisk 0x002a /* U+002A ASTERISK */ #define XK_plus 0x002b /* U+002B PLUS SIGN */ #define XK_comma 0x002c /* U+002C COMMA */ #define XK_minus 0x002d /* U+002D HYPHEN-MINUS */ #define XK_period 0x002e /* U+002E FULL STOP */ #define XK_slash 0x002f /* U+002F SOLIDUS */ #define XK_0 0x0030 /* U+0030 DIGIT ZERO */ #define XK_1 0x0031 /* U+0031 DIGIT ONE */ #define XK_2 0x0032 /* U+0032 DIGIT TWO */ #define XK_3 0x0033 /* U+0033 DIGIT THREE */ #define XK_4 0x0034 /* U+0034 DIGIT FOUR */ #define XK_5 0x0035 /* U+0035 DIGIT FIVE */ #define XK_6 0x0036 /* U+0036 DIGIT SIX */ #define XK_7 0x0037 /* U+0037 DIGIT SEVEN */ #define XK_8 0x0038 /* U+0038 DIGIT EIGHT */ #define XK_9 0x0039 /* U+0039 DIGIT NINE */ #define XK_colon 0x003a /* U+003A COLON */ #define XK_semicolon 0x003b /* U+003B SEMICOLON */ #define XK_less 0x003c /* U+003C LESS-THAN SIGN */ #define XK_equal 0x003d /* U+003D EQUALS SIGN */ #define XK_greater 0x003e /* U+003E GREATER-THAN SIGN */ #define XK_question 0x003f /* U+003F QUESTION MARK */ #define XK_at 0x0040 /* U+0040 COMMERCIAL AT */ #define XK_A 0x0041 /* U+0041 LATIN CAPITAL LETTER A */ #define XK_B 0x0042 /* U+0042 LATIN CAPITAL LETTER B */ #define XK_C 0x0043 /* U+0043 LATIN CAPITAL LETTER C */ #define XK_D 0x0044 /* U+0044 LATIN CAPITAL LETTER D */ #define XK_E 0x0045 /* U+0045 LATIN CAPITAL LETTER E */ #define XK_F 0x0046 /* U+0046 LATIN CAPITAL LETTER F */ #define XK_G 0x0047 /* U+0047 LATIN CAPITAL LETTER G */ #define XK_H 0x0048 /* U+0048 LATIN CAPITAL LETTER H */ #define XK_I 0x0049 /* U+0049 LATIN CAPITAL LETTER I */ #define XK_J 0x004a /* U+004A LATIN CAPITAL LETTER J */ #define XK_K 0x004b /* U+004B LATIN CAPITAL LETTER K */ #define XK_L 0x004c /* U+004C LATIN CAPITAL LETTER L */ #define XK_M 0x004d /* U+004D LATIN CAPITAL LETTER M */ #define XK_N 0x004e /* U+004E LATIN CAPITAL LETTER N */ #define XK_O 0x004f /* U+004F LATIN CAPITAL LETTER O */ #define XK_P 0x0050 /* U+0050 LATIN CAPITAL LETTER P */ #define XK_Q 0x0051 /* U+0051 LATIN CAPITAL LETTER Q */ #define XK_R 0x0052 /* U+0052 LATIN CAPITAL LETTER R */ #define XK_S 0x0053 /* U+0053 LATIN CAPITAL LETTER S */ #define XK_T 0x0054 /* U+0054 LATIN CAPITAL LETTER T */ #define XK_U 0x0055 /* U+0055 LATIN CAPITAL LETTER U */ #define XK_V 0x0056 /* U+0056 LATIN CAPITAL LETTER V */ #define XK_W 0x0057 /* U+0057 LATIN CAPITAL LETTER W */ #define XK_X 0x0058 /* U+0058 LATIN CAPITAL LETTER X */ #define XK_Y 0x0059 /* U+0059 LATIN CAPITAL LETTER Y */ #define XK_Z 0x005a /* U+005A LATIN CAPITAL LETTER Z */ #define XK_bracketleft 0x005b /* U+005B LEFT SQUARE BRACKET */ #define XK_backslash 0x005c /* U+005C REVERSE SOLIDUS */ #define XK_bracketright 0x005d /* U+005D RIGHT SQUARE BRACKET */ #define XK_asciicircum 0x005e /* U+005E CIRCUMFLEX ACCENT */ #define XK_underscore 0x005f /* U+005F LOW LINE */ #define XK_grave 0x0060 /* U+0060 GRAVE ACCENT */ #define XK_quoteleft 0x0060 /* deprecated */ #define XK_a 0x0061 /* U+0061 LATIN SMALL LETTER A */ #define XK_b 0x0062 /* U+0062 LATIN SMALL LETTER B */ #define XK_c 0x0063 /* U+0063 LATIN SMALL LETTER C */ #define XK_d 0x0064 /* U+0064 LATIN SMALL LETTER D */ #define XK_e 0x0065 /* U+0065 LATIN SMALL LETTER E */ #define XK_f 0x0066 /* U+0066 LATIN SMALL LETTER F */ #define XK_g 0x0067 /* U+0067 LATIN SMALL LETTER G */ #define XK_h 0x0068 /* U+0068 LATIN SMALL LETTER H */ #define XK_i 0x0069 /* U+0069 LATIN SMALL LETTER I */ #define XK_j 0x006a /* U+006A LATIN SMALL LETTER J */ #define XK_k 0x006b /* U+006B LATIN SMALL LETTER K */ #define XK_l 0x006c /* U+006C LATIN SMALL LETTER L */ #define XK_m 0x006d /* U+006D LATIN SMALL LETTER M */ #define XK_n 0x006e /* U+006E LATIN SMALL LETTER N */ #define XK_o 0x006f /* U+006F LATIN SMALL LETTER O */ #define XK_p 0x0070 /* U+0070 LATIN SMALL LETTER P */ #define XK_q 0x0071 /* U+0071 LATIN SMALL LETTER Q */ #define XK_r 0x0072 /* U+0072 LATIN SMALL LETTER R */ #define XK_s 0x0073 /* U+0073 LATIN SMALL LETTER S */ #define XK_t 0x0074 /* U+0074 LATIN SMALL LETTER T */ #define XK_u 0x0075 /* U+0075 LATIN SMALL LETTER U */ #define XK_v 0x0076 /* U+0076 LATIN SMALL LETTER V */ #define XK_w 0x0077 /* U+0077 LATIN SMALL LETTER W */ #define XK_x 0x0078 /* U+0078 LATIN SMALL LETTER X */ #define XK_y 0x0079 /* U+0079 LATIN SMALL LETTER Y */ #define XK_z 0x007a /* U+007A LATIN SMALL LETTER Z */ #define XK_braceleft 0x007b /* U+007B LEFT CURLY BRACKET */ #define XK_bar 0x007c /* U+007C VERTICAL LINE */ #define XK_braceright 0x007d /* U+007D RIGHT CURLY BRACKET */ #define XK_asciitilde 0x007e /* U+007E TILDE */ #define XK_nobreakspace 0x00a0 /* U+00A0 NO-BREAK SPACE */ #define XK_exclamdown 0x00a1 /* U+00A1 INVERTED EXCLAMATION MARK */ #define XK_cent 0x00a2 /* U+00A2 CENT SIGN */ #define XK_sterling 0x00a3 /* U+00A3 POUND SIGN */ #define XK_currency 0x00a4 /* U+00A4 CURRENCY SIGN */ #define XK_yen 0x00a5 /* U+00A5 YEN SIGN */ #define XK_brokenbar 0x00a6 /* U+00A6 BROKEN BAR */ #define XK_section 0x00a7 /* U+00A7 SECTION SIGN */ #define XK_diaeresis 0x00a8 /* U+00A8 DIAERESIS */ #define XK_copyright 0x00a9 /* U+00A9 COPYRIGHT SIGN */ #define XK_ordfeminine 0x00aa /* U+00AA FEMININE ORDINAL INDICATOR */ #define XK_guillemotleft 0x00ab /* U+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */ #define XK_notsign 0x00ac /* U+00AC NOT SIGN */ #define XK_hyphen 0x00ad /* U+00AD SOFT HYPHEN */ #define XK_registered 0x00ae /* U+00AE REGISTERED SIGN */ #define XK_macron 0x00af /* U+00AF MACRON */ #define XK_degree 0x00b0 /* U+00B0 DEGREE SIGN */ #define XK_plusminus 0x00b1 /* U+00B1 PLUS-MINUS SIGN */ #define XK_twosuperior 0x00b2 /* U+00B2 SUPERSCRIPT TWO */ #define XK_threesuperior 0x00b3 /* U+00B3 SUPERSCRIPT THREE */ #define XK_acute 0x00b4 /* U+00B4 ACUTE ACCENT */ #define XK_mu 0x00b5 /* U+00B5 MICRO SIGN */ #define XK_paragraph 0x00b6 /* U+00B6 PILCROW SIGN */ #define XK_periodcentered 0x00b7 /* U+00B7 MIDDLE DOT */ #define XK_cedilla 0x00b8 /* U+00B8 CEDILLA */ #define XK_onesuperior 0x00b9 /* U+00B9 SUPERSCRIPT ONE */ #define XK_masculine 0x00ba /* U+00BA MASCULINE ORDINAL INDICATOR */ #define XK_guillemotright 0x00bb /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */ #define XK_onequarter 0x00bc /* U+00BC VULGAR FRACTION ONE QUARTER */ #define XK_onehalf 0x00bd /* U+00BD VULGAR FRACTION ONE HALF */ #define XK_threequarters 0x00be /* U+00BE VULGAR FRACTION THREE QUARTERS */ #define XK_questiondown 0x00bf /* U+00BF INVERTED QUESTION MARK */ #define XK_Agrave 0x00c0 /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */ #define XK_Aacute 0x00c1 /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */ #define XK_Acircumflex 0x00c2 /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */ #define XK_Atilde 0x00c3 /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */ #define XK_Adiaeresis 0x00c4 /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS */ #define XK_Aring 0x00c5 /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */ #define XK_AE 0x00c6 /* U+00C6 LATIN CAPITAL LETTER AE */ #define XK_Ccedilla 0x00c7 /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */ #define XK_Egrave 0x00c8 /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */ #define XK_Eacute 0x00c9 /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */ #define XK_Ecircumflex 0x00ca /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */ #define XK_Ediaeresis 0x00cb /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS */ #define XK_Igrave 0x00cc /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */ #define XK_Iacute 0x00cd /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */ #define XK_Icircumflex 0x00ce /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */ #define XK_Idiaeresis 0x00cf /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS */ #define XK_ETH 0x00d0 /* U+00D0 LATIN CAPITAL LETTER ETH */ #define XK_Eth 0x00d0 /* deprecated */ #define XK_Ntilde 0x00d1 /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */ #define XK_Ograve 0x00d2 /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */ #define XK_Oacute 0x00d3 /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */ #define XK_Ocircumflex 0x00d4 /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */ #define XK_Otilde 0x00d5 /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */ #define XK_Odiaeresis 0x00d6 /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS */ #define XK_multiply 0x00d7 /* U+00D7 MULTIPLICATION SIGN */ #define XK_Oslash 0x00d8 /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ #define XK_Ooblique 0x00d8 /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */ #define XK_Ugrave 0x00d9 /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */ #define XK_Uacute 0x00da /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */ #define XK_Ucircumflex 0x00db /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */ #define XK_Udiaeresis 0x00dc /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS */ #define XK_Yacute 0x00dd /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */ #define XK_THORN 0x00de /* U+00DE LATIN CAPITAL LETTER THORN */ #define XK_Thorn 0x00de /* deprecated */ #define XK_ssharp 0x00df /* U+00DF LATIN SMALL LETTER SHARP S */ #define XK_agrave 0x00e0 /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */ #define XK_aacute 0x00e1 /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */ #define XK_acircumflex 0x00e2 /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX */ #define XK_atilde 0x00e3 /* U+00E3 LATIN SMALL LETTER A WITH TILDE */ #define XK_adiaeresis 0x00e4 /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */ #define XK_aring 0x00e5 /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */ #define XK_ae 0x00e6 /* U+00E6 LATIN SMALL LETTER AE */ #define XK_ccedilla 0x00e7 /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */ #define XK_egrave 0x00e8 /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */ #define XK_eacute 0x00e9 /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */ #define XK_ecircumflex 0x00ea /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX */ #define XK_ediaeresis 0x00eb /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */ #define XK_igrave 0x00ec /* U+00EC LATIN SMALL LETTER I WITH GRAVE */ #define XK_iacute 0x00ed /* U+00ED LATIN SMALL LETTER I WITH ACUTE */ #define XK_icircumflex 0x00ee /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX */ #define XK_idiaeresis 0x00ef /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */ #define XK_eth 0x00f0 /* U+00F0 LATIN SMALL LETTER ETH */ #define XK_ntilde 0x00f1 /* U+00F1 LATIN SMALL LETTER N WITH TILDE */ #define XK_ograve 0x00f2 /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */ #define XK_oacute 0x00f3 /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */ #define XK_ocircumflex 0x00f4 /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX */ #define XK_otilde 0x00f5 /* U+00F5 LATIN SMALL LETTER O WITH TILDE */ #define XK_odiaeresis 0x00f6 /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */ #define XK_division 0x00f7 /* U+00F7 DIVISION SIGN */ #define XK_oslash 0x00f8 /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ #define XK_ooblique 0x00f8 /* U+00F8 LATIN SMALL LETTER O WITH STROKE */ #define XK_ugrave 0x00f9 /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */ #define XK_uacute 0x00fa /* U+00FA LATIN SMALL LETTER U WITH ACUTE */ #define XK_ucircumflex 0x00fb /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX */ #define XK_udiaeresis 0x00fc /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */ #define XK_yacute 0x00fd /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */ #define XK_thorn 0x00fe /* U+00FE LATIN SMALL LETTER THORN */ #define XK_ydiaeresis 0x00ff /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */ #endif /* XK_LATIN1 */ /* * Latin 2 * Byte 3 = 1 */ #ifdef XK_LATIN2 #define XK_Aogonek 0x01a1 /* U+0104 LATIN CAPITAL LETTER A WITH OGONEK */ #define XK_breve 0x01a2 /* U+02D8 BREVE */ #define XK_Lstroke 0x01a3 /* U+0141 LATIN CAPITAL LETTER L WITH STROKE */ #define XK_Lcaron 0x01a5 /* U+013D LATIN CAPITAL LETTER L WITH CARON */ #define XK_Sacute 0x01a6 /* U+015A LATIN CAPITAL LETTER S WITH ACUTE */ #define XK_Scaron 0x01a9 /* U+0160 LATIN CAPITAL LETTER S WITH CARON */ #define XK_Scedilla 0x01aa /* U+015E LATIN CAPITAL LETTER S WITH CEDILLA */ #define XK_Tcaron 0x01ab /* U+0164 LATIN CAPITAL LETTER T WITH CARON */ #define XK_Zacute 0x01ac /* U+0179 LATIN CAPITAL LETTER Z WITH ACUTE */ #define XK_Zcaron 0x01ae /* U+017D LATIN CAPITAL LETTER Z WITH CARON */ #define XK_Zabovedot 0x01af /* U+017B LATIN CAPITAL LETTER Z WITH DOT ABOVE */ #define XK_aogonek 0x01b1 /* U+0105 LATIN SMALL LETTER A WITH OGONEK */ #define XK_ogonek 0x01b2 /* U+02DB OGONEK */ #define XK_lstroke 0x01b3 /* U+0142 LATIN SMALL LETTER L WITH STROKE */ #define XK_lcaron 0x01b5 /* U+013E LATIN SMALL LETTER L WITH CARON */ #define XK_sacute 0x01b6 /* U+015B LATIN SMALL LETTER S WITH ACUTE */ #define XK_caron 0x01b7 /* U+02C7 CARON */ #define XK_scaron 0x01b9 /* U+0161 LATIN SMALL LETTER S WITH CARON */ #define XK_scedilla 0x01ba /* U+015F LATIN SMALL LETTER S WITH CEDILLA */ #define XK_tcaron 0x01bb /* U+0165 LATIN SMALL LETTER T WITH CARON */ #define XK_zacute 0x01bc /* U+017A LATIN SMALL LETTER Z WITH ACUTE */ #define XK_doubleacute 0x01bd /* U+02DD DOUBLE ACUTE ACCENT */ #define XK_zcaron 0x01be /* U+017E LATIN SMALL LETTER Z WITH CARON */ #define XK_zabovedot 0x01bf /* U+017C LATIN SMALL LETTER Z WITH DOT ABOVE */ #define XK_Racute 0x01c0 /* U+0154 LATIN CAPITAL LETTER R WITH ACUTE */ #define XK_Abreve 0x01c3 /* U+0102 LATIN CAPITAL LETTER A WITH BREVE */ #define XK_Lacute 0x01c5 /* U+0139 LATIN CAPITAL LETTER L WITH ACUTE */ #define XK_Cacute 0x01c6 /* U+0106 LATIN CAPITAL LETTER C WITH ACUTE */ #define XK_Ccaron 0x01c8 /* U+010C LATIN CAPITAL LETTER C WITH CARON */ #define XK_Eogonek 0x01ca /* U+0118 LATIN CAPITAL LETTER E WITH OGONEK */ #define XK_Ecaron 0x01cc /* U+011A LATIN CAPITAL LETTER E WITH CARON */ #define XK_Dcaron 0x01cf /* U+010E LATIN CAPITAL LETTER D WITH CARON */ #define XK_Dstroke 0x01d0 /* U+0110 LATIN CAPITAL LETTER D WITH STROKE */ #define XK_Nacute 0x01d1 /* U+0143 LATIN CAPITAL LETTER N WITH ACUTE */ #define XK_Ncaron 0x01d2 /* U+0147 LATIN CAPITAL LETTER N WITH CARON */ #define XK_Odoubleacute 0x01d5 /* U+0150 LATIN CAPITAL LETTER O WITH DOUBLE ACUTE */ #define XK_Rcaron 0x01d8 /* U+0158 LATIN CAPITAL LETTER R WITH CARON */ #define XK_Uring 0x01d9 /* U+016E LATIN CAPITAL LETTER U WITH RING ABOVE */ #define XK_Udoubleacute 0x01db /* U+0170 LATIN CAPITAL LETTER U WITH DOUBLE ACUTE */ #define XK_Tcedilla 0x01de /* U+0162 LATIN CAPITAL LETTER T WITH CEDILLA */ #define XK_racute 0x01e0 /* U+0155 LATIN SMALL LETTER R WITH ACUTE */ #define XK_abreve 0x01e3 /* U+0103 LATIN SMALL LETTER A WITH BREVE */ #define XK_lacute 0x01e5 /* U+013A LATIN SMALL LETTER L WITH ACUTE */ #define XK_cacute 0x01e6 /* U+0107 LATIN SMALL LETTER C WITH ACUTE */ #define XK_ccaron 0x01e8 /* U+010D LATIN SMALL LETTER C WITH CARON */ #define XK_eogonek 0x01ea /* U+0119 LATIN SMALL LETTER E WITH OGONEK */ #define XK_ecaron 0x01ec /* U+011B LATIN SMALL LETTER E WITH CARON */ #define XK_dcaron 0x01ef /* U+010F LATIN SMALL LETTER D WITH CARON */ #define XK_dstroke 0x01f0 /* U+0111 LATIN SMALL LETTER D WITH STROKE */ #define XK_nacute 0x01f1 /* U+0144 LATIN SMALL LETTER N WITH ACUTE */ #define XK_ncaron 0x01f2 /* U+0148 LATIN SMALL LETTER N WITH CARON */ #define XK_odoubleacute 0x01f5 /* U+0151 LATIN SMALL LETTER O WITH DOUBLE ACUTE */ #define XK_rcaron 0x01f8 /* U+0159 LATIN SMALL LETTER R WITH CARON */ #define XK_uring 0x01f9 /* U+016F LATIN SMALL LETTER U WITH RING ABOVE */ #define XK_udoubleacute 0x01fb /* U+0171 LATIN SMALL LETTER U WITH DOUBLE ACUTE */ #define XK_tcedilla 0x01fe /* U+0163 LATIN SMALL LETTER T WITH CEDILLA */ #define XK_abovedot 0x01ff /* U+02D9 DOT ABOVE */ #endif /* XK_LATIN2 */ /* * Latin 3 * Byte 3 = 2 */ #ifdef XK_LATIN3 #define XK_Hstroke 0x02a1 /* U+0126 LATIN CAPITAL LETTER H WITH STROKE */ #define XK_Hcircumflex 0x02a6 /* U+0124 LATIN CAPITAL LETTER H WITH CIRCUMFLEX */ #define XK_Iabovedot 0x02a9 /* U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE */ #define XK_Gbreve 0x02ab /* U+011E LATIN CAPITAL LETTER G WITH BREVE */ #define XK_Jcircumflex 0x02ac /* U+0134 LATIN CAPITAL LETTER J WITH CIRCUMFLEX */ #define XK_hstroke 0x02b1 /* U+0127 LATIN SMALL LETTER H WITH STROKE */ #define XK_hcircumflex 0x02b6 /* U+0125 LATIN SMALL LETTER H WITH CIRCUMFLEX */ #define XK_idotless 0x02b9 /* U+0131 LATIN SMALL LETTER DOTLESS I */ #define XK_gbreve 0x02bb /* U+011F LATIN SMALL LETTER G WITH BREVE */ #define XK_jcircumflex 0x02bc /* U+0135 LATIN SMALL LETTER J WITH CIRCUMFLEX */ #define XK_Cabovedot 0x02c5 /* U+010A LATIN CAPITAL LETTER C WITH DOT ABOVE */ #define XK_Ccircumflex 0x02c6 /* U+0108 LATIN CAPITAL LETTER C WITH CIRCUMFLEX */ #define XK_Gabovedot 0x02d5 /* U+0120 LATIN CAPITAL LETTER G WITH DOT ABOVE */ #define XK_Gcircumflex 0x02d8 /* U+011C LATIN CAPITAL LETTER G WITH CIRCUMFLEX */ #define XK_Ubreve 0x02dd /* U+016C LATIN CAPITAL LETTER U WITH BREVE */ #define XK_Scircumflex 0x02de /* U+015C LATIN CAPITAL LETTER S WITH CIRCUMFLEX */ #define XK_cabovedot 0x02e5 /* U+010B LATIN SMALL LETTER C WITH DOT ABOVE */ #define XK_ccircumflex 0x02e6 /* U+0109 LATIN SMALL LETTER C WITH CIRCUMFLEX */ #define XK_gabovedot 0x02f5 /* U+0121 LATIN SMALL LETTER G WITH DOT ABOVE */ #define XK_gcircumflex 0x02f8 /* U+011D LATIN SMALL LETTER G WITH CIRCUMFLEX */ #define XK_ubreve 0x02fd /* U+016D LATIN SMALL LETTER U WITH BREVE */ #define XK_scircumflex 0x02fe /* U+015D LATIN SMALL LETTER S WITH CIRCUMFLEX */ #endif /* XK_LATIN3 */ /* * Latin 4 * Byte 3 = 3 */ #ifdef XK_LATIN4 #define XK_kra 0x03a2 /* U+0138 LATIN SMALL LETTER KRA */ #define XK_kappa 0x03a2 /* deprecated */ #define XK_Rcedilla 0x03a3 /* U+0156 LATIN CAPITAL LETTER R WITH CEDILLA */ #define XK_Itilde 0x03a5 /* U+0128 LATIN CAPITAL LETTER I WITH TILDE */ #define XK_Lcedilla 0x03a6 /* U+013B LATIN CAPITAL LETTER L WITH CEDILLA */ #define XK_Emacron 0x03aa /* U+0112 LATIN CAPITAL LETTER E WITH MACRON */ #define XK_Gcedilla 0x03ab /* U+0122 LATIN CAPITAL LETTER G WITH CEDILLA */ #define XK_Tslash 0x03ac /* U+0166 LATIN CAPITAL LETTER T WITH STROKE */ #define XK_rcedilla 0x03b3 /* U+0157 LATIN SMALL LETTER R WITH CEDILLA */ #define XK_itilde 0x03b5 /* U+0129 LATIN SMALL LETTER I WITH TILDE */ #define XK_lcedilla 0x03b6 /* U+013C LATIN SMALL LETTER L WITH CEDILLA */ #define XK_emacron 0x03ba /* U+0113 LATIN SMALL LETTER E WITH MACRON */ #define XK_gcedilla 0x03bb /* U+0123 LATIN SMALL LETTER G WITH CEDILLA */ #define XK_tslash 0x03bc /* U+0167 LATIN SMALL LETTER T WITH STROKE */ #define XK_ENG 0x03bd /* U+014A LATIN CAPITAL LETTER ENG */ #define XK_eng 0x03bf /* U+014B LATIN SMALL LETTER ENG */ #define XK_Amacron 0x03c0 /* U+0100 LATIN CAPITAL LETTER A WITH MACRON */ #define XK_Iogonek 0x03c7 /* U+012E LATIN CAPITAL LETTER I WITH OGONEK */ #define XK_Eabovedot 0x03cc /* U+0116 LATIN CAPITAL LETTER E WITH DOT ABOVE */ #define XK_Imacron 0x03cf /* U+012A LATIN CAPITAL LETTER I WITH MACRON */ #define XK_Ncedilla 0x03d1 /* U+0145 LATIN CAPITAL LETTER N WITH CEDILLA */ #define XK_Omacron 0x03d2 /* U+014C LATIN CAPITAL LETTER O WITH MACRON */ #define XK_Kcedilla 0x03d3 /* U+0136 LATIN CAPITAL LETTER K WITH CEDILLA */ #define XK_Uogonek 0x03d9 /* U+0172 LATIN CAPITAL LETTER U WITH OGONEK */ #define XK_Utilde 0x03dd /* U+0168 LATIN CAPITAL LETTER U WITH TILDE */ #define XK_Umacron 0x03de /* U+016A LATIN CAPITAL LETTER U WITH MACRON */ #define XK_amacron 0x03e0 /* U+0101 LATIN SMALL LETTER A WITH MACRON */ #define XK_iogonek 0x03e7 /* U+012F LATIN SMALL LETTER I WITH OGONEK */ #define XK_eabovedot 0x03ec /* U+0117 LATIN SMALL LETTER E WITH DOT ABOVE */ #define XK_imacron 0x03ef /* U+012B LATIN SMALL LETTER I WITH MACRON */ #define XK_ncedilla 0x03f1 /* U+0146 LATIN SMALL LETTER N WITH CEDILLA */ #define XK_omacron 0x03f2 /* U+014D LATIN SMALL LETTER O WITH MACRON */ #define XK_kcedilla 0x03f3 /* U+0137 LATIN SMALL LETTER K WITH CEDILLA */ #define XK_uogonek 0x03f9 /* U+0173 LATIN SMALL LETTER U WITH OGONEK */ #define XK_utilde 0x03fd /* U+0169 LATIN SMALL LETTER U WITH TILDE */ #define XK_umacron 0x03fe /* U+016B LATIN SMALL LETTER U WITH MACRON */ #endif /* XK_LATIN4 */ /* * Latin 8 */ #ifdef XK_LATIN8 #define XK_Wcircumflex 0x1000174 /* U+0174 LATIN CAPITAL LETTER W WITH CIRCUMFLEX */ #define XK_wcircumflex 0x1000175 /* U+0175 LATIN SMALL LETTER W WITH CIRCUMFLEX */ #define XK_Ycircumflex 0x1000176 /* U+0176 LATIN CAPITAL LETTER Y WITH CIRCUMFLEX */ #define XK_ycircumflex 0x1000177 /* U+0177 LATIN SMALL LETTER Y WITH CIRCUMFLEX */ #define XK_Babovedot 0x1001e02 /* U+1E02 LATIN CAPITAL LETTER B WITH DOT ABOVE */ #define XK_babovedot 0x1001e03 /* U+1E03 LATIN SMALL LETTER B WITH DOT ABOVE */ #define XK_Dabovedot 0x1001e0a /* U+1E0A LATIN CAPITAL LETTER D WITH DOT ABOVE */ #define XK_dabovedot 0x1001e0b /* U+1E0B LATIN SMALL LETTER D WITH DOT ABOVE */ #define XK_Fabovedot 0x1001e1e /* U+1E1E LATIN CAPITAL LETTER F WITH DOT ABOVE */ #define XK_fabovedot 0x1001e1f /* U+1E1F LATIN SMALL LETTER F WITH DOT ABOVE */ #define XK_Mabovedot 0x1001e40 /* U+1E40 LATIN CAPITAL LETTER M WITH DOT ABOVE */ #define XK_mabovedot 0x1001e41 /* U+1E41 LATIN SMALL LETTER M WITH DOT ABOVE */ #define XK_Pabovedot 0x1001e56 /* U+1E56 LATIN CAPITAL LETTER P WITH DOT ABOVE */ #define XK_pabovedot 0x1001e57 /* U+1E57 LATIN SMALL LETTER P WITH DOT ABOVE */ #define XK_Sabovedot 0x1001e60 /* U+1E60 LATIN CAPITAL LETTER S WITH DOT ABOVE */ #define XK_sabovedot 0x1001e61 /* U+1E61 LATIN SMALL LETTER S WITH DOT ABOVE */ #define XK_Tabovedot 0x1001e6a /* U+1E6A LATIN CAPITAL LETTER T WITH DOT ABOVE */ #define XK_tabovedot 0x1001e6b /* U+1E6B LATIN SMALL LETTER T WITH DOT ABOVE */ #define XK_Wgrave 0x1001e80 /* U+1E80 LATIN CAPITAL LETTER W WITH GRAVE */ #define XK_wgrave 0x1001e81 /* U+1E81 LATIN SMALL LETTER W WITH GRAVE */ #define XK_Wacute 0x1001e82 /* U+1E82 LATIN CAPITAL LETTER W WITH ACUTE */ #define XK_wacute 0x1001e83 /* U+1E83 LATIN SMALL LETTER W WITH ACUTE */ #define XK_Wdiaeresis 0x1001e84 /* U+1E84 LATIN CAPITAL LETTER W WITH DIAERESIS */ #define XK_wdiaeresis 0x1001e85 /* U+1E85 LATIN SMALL LETTER W WITH DIAERESIS */ #define XK_Ygrave 0x1001ef2 /* U+1EF2 LATIN CAPITAL LETTER Y WITH GRAVE */ #define XK_ygrave 0x1001ef3 /* U+1EF3 LATIN SMALL LETTER Y WITH GRAVE */ #endif /* XK_LATIN8 */ /* * Latin 9 * Byte 3 = 0x13 */ #ifdef XK_LATIN9 #define XK_OE 0x13bc /* U+0152 LATIN CAPITAL LIGATURE OE */ #define XK_oe 0x13bd /* U+0153 LATIN SMALL LIGATURE OE */ #define XK_Ydiaeresis 0x13be /* U+0178 LATIN CAPITAL LETTER Y WITH DIAERESIS */ #endif /* XK_LATIN9 */ /* * Katakana * Byte 3 = 4 */ #ifdef XK_KATAKANA #define XK_overline 0x047e /* U+203E OVERLINE */ #define XK_kana_fullstop 0x04a1 /* U+3002 IDEOGRAPHIC FULL STOP */ #define XK_kana_openingbracket 0x04a2 /* U+300C LEFT CORNER BRACKET */ #define XK_kana_closingbracket 0x04a3 /* U+300D RIGHT CORNER BRACKET */ #define XK_kana_comma 0x04a4 /* U+3001 IDEOGRAPHIC COMMA */ #define XK_kana_conjunctive 0x04a5 /* U+30FB KATAKANA MIDDLE DOT */ #define XK_kana_middledot 0x04a5 /* deprecated */ #define XK_kana_WO 0x04a6 /* U+30F2 KATAKANA LETTER WO */ #define XK_kana_a 0x04a7 /* U+30A1 KATAKANA LETTER SMALL A */ #define XK_kana_i 0x04a8 /* U+30A3 KATAKANA LETTER SMALL I */ #define XK_kana_u 0x04a9 /* U+30A5 KATAKANA LETTER SMALL U */ #define XK_kana_e 0x04aa /* U+30A7 KATAKANA LETTER SMALL E */ #define XK_kana_o 0x04ab /* U+30A9 KATAKANA LETTER SMALL O */ #define XK_kana_ya 0x04ac /* U+30E3 KATAKANA LETTER SMALL YA */ #define XK_kana_yu 0x04ad /* U+30E5 KATAKANA LETTER SMALL YU */ #define XK_kana_yo 0x04ae /* U+30E7 KATAKANA LETTER SMALL YO */ #define XK_kana_tsu 0x04af /* U+30C3 KATAKANA LETTER SMALL TU */ #define XK_kana_tu 0x04af /* deprecated */ #define XK_prolongedsound 0x04b0 /* U+30FC KATAKANA-HIRAGANA PROLONGED SOUND MARK */ #define XK_kana_A 0x04b1 /* U+30A2 KATAKANA LETTER A */ #define XK_kana_I 0x04b2 /* U+30A4 KATAKANA LETTER I */ #define XK_kana_U 0x04b3 /* U+30A6 KATAKANA LETTER U */ #define XK_kana_E 0x04b4 /* U+30A8 KATAKANA LETTER E */ #define XK_kana_O 0x04b5 /* U+30AA KATAKANA LETTER O */ #define XK_kana_KA 0x04b6 /* U+30AB KATAKANA LETTER KA */ #define XK_kana_KI 0x04b7 /* U+30AD KATAKANA LETTER KI */ #define XK_kana_KU 0x04b8 /* U+30AF KATAKANA LETTER KU */ #define XK_kana_KE 0x04b9 /* U+30B1 KATAKANA LETTER KE */ #define XK_kana_KO 0x04ba /* U+30B3 KATAKANA LETTER KO */ #define XK_kana_SA 0x04bb /* U+30B5 KATAKANA LETTER SA */ #define XK_kana_SHI 0x04bc /* U+30B7 KATAKANA LETTER SI */ #define XK_kana_SU 0x04bd /* U+30B9 KATAKANA LETTER SU */ #define XK_kana_SE 0x04be /* U+30BB KATAKANA LETTER SE */ #define XK_kana_SO 0x04bf /* U+30BD KATAKANA LETTER SO */ #define XK_kana_TA 0x04c0 /* U+30BF KATAKANA LETTER TA */ #define XK_kana_CHI 0x04c1 /* U+30C1 KATAKANA LETTER TI */ #define XK_kana_TI 0x04c1 /* deprecated */ #define XK_kana_TSU 0x04c2 /* U+30C4 KATAKANA LETTER TU */ #define XK_kana_TU 0x04c2 /* deprecated */ #define XK_kana_TE 0x04c3 /* U+30C6 KATAKANA LETTER TE */ #define XK_kana_TO 0x04c4 /* U+30C8 KATAKANA LETTER TO */ #define XK_kana_NA 0x04c5 /* U+30CA KATAKANA LETTER NA */ #define XK_kana_NI 0x04c6 /* U+30CB KATAKANA LETTER NI */ #define XK_kana_NU 0x04c7 /* U+30CC KATAKANA LETTER NU */ #define XK_kana_NE 0x04c8 /* U+30CD KATAKANA LETTER NE */ #define XK_kana_NO 0x04c9 /* U+30CE KATAKANA LETTER NO */ #define XK_kana_HA 0x04ca /* U+30CF KATAKANA LETTER HA */ #define XK_kana_HI 0x04cb /* U+30D2 KATAKANA LETTER HI */ #define XK_kana_FU 0x04cc /* U+30D5 KATAKANA LETTER HU */ #define XK_kana_HU 0x04cc /* deprecated */ #define XK_kana_HE 0x04cd /* U+30D8 KATAKANA LETTER HE */ #define XK_kana_HO 0x04ce /* U+30DB KATAKANA LETTER HO */ #define XK_kana_MA 0x04cf /* U+30DE KATAKANA LETTER MA */ #define XK_kana_MI 0x04d0 /* U+30DF KATAKANA LETTER MI */ #define XK_kana_MU 0x04d1 /* U+30E0 KATAKANA LETTER MU */ #define XK_kana_ME 0x04d2 /* U+30E1 KATAKANA LETTER ME */ #define XK_kana_MO 0x04d3 /* U+30E2 KATAKANA LETTER MO */ #define XK_kana_YA 0x04d4 /* U+30E4 KATAKANA LETTER YA */ #define XK_kana_YU 0x04d5 /* U+30E6 KATAKANA LETTER YU */ #define XK_kana_YO 0x04d6 /* U+30E8 KATAKANA LETTER YO */ #define XK_kana_RA 0x04d7 /* U+30E9 KATAKANA LETTER RA */ #define XK_kana_RI 0x04d8 /* U+30EA KATAKANA LETTER RI */ #define XK_kana_RU 0x04d9 /* U+30EB KATAKANA LETTER RU */ #define XK_kana_RE 0x04da /* U+30EC KATAKANA LETTER RE */ #define XK_kana_RO 0x04db /* U+30ED KATAKANA LETTER RO */ #define XK_kana_WA 0x04dc /* U+30EF KATAKANA LETTER WA */ #define XK_kana_N 0x04dd /* U+30F3 KATAKANA LETTER N */ #define XK_voicedsound 0x04de /* U+309B KATAKANA-HIRAGANA VOICED SOUND MARK */ #define XK_semivoicedsound 0x04df /* U+309C KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK */ #define XK_kana_switch 0xff7e /* Alias for mode_switch */ #endif /* XK_KATAKANA */ /* * Arabic * Byte 3 = 5 */ #ifdef XK_ARABIC #define XK_Farsi_0 0x10006f0 /* U+06F0 EXTENDED ARABIC-INDIC DIGIT ZERO */ #define XK_Farsi_1 0x10006f1 /* U+06F1 EXTENDED ARABIC-INDIC DIGIT ONE */ #define XK_Farsi_2 0x10006f2 /* U+06F2 EXTENDED ARABIC-INDIC DIGIT TWO */ #define XK_Farsi_3 0x10006f3 /* U+06F3 EXTENDED ARABIC-INDIC DIGIT THREE */ #define XK_Farsi_4 0x10006f4 /* U+06F4 EXTENDED ARABIC-INDIC DIGIT FOUR */ #define XK_Farsi_5 0x10006f5 /* U+06F5 EXTENDED ARABIC-INDIC DIGIT FIVE */ #define XK_Farsi_6 0x10006f6 /* U+06F6 EXTENDED ARABIC-INDIC DIGIT SIX */ #define XK_Farsi_7 0x10006f7 /* U+06F7 EXTENDED ARABIC-INDIC DIGIT SEVEN */ #define XK_Farsi_8 0x10006f8 /* U+06F8 EXTENDED ARABIC-INDIC DIGIT EIGHT */ #define XK_Farsi_9 0x10006f9 /* U+06F9 EXTENDED ARABIC-INDIC DIGIT NINE */ #define XK_Arabic_percent 0x100066a /* U+066A ARABIC PERCENT SIGN */ #define XK_Arabic_superscript_alef 0x1000670 /* U+0670 ARABIC LETTER SUPERSCRIPT ALEF */ #define XK_Arabic_tteh 0x1000679 /* U+0679 ARABIC LETTER TTEH */ #define XK_Arabic_peh 0x100067e /* U+067E ARABIC LETTER PEH */ #define XK_Arabic_tcheh 0x1000686 /* U+0686 ARABIC LETTER TCHEH */ #define XK_Arabic_ddal 0x1000688 /* U+0688 ARABIC LETTER DDAL */ #define XK_Arabic_rreh 0x1000691 /* U+0691 ARABIC LETTER RREH */ #define XK_Arabic_comma 0x05ac /* U+060C ARABIC COMMA */ #define XK_Arabic_fullstop 0x10006d4 /* U+06D4 ARABIC FULL STOP */ #define XK_Arabic_0 0x1000660 /* U+0660 ARABIC-INDIC DIGIT ZERO */ #define XK_Arabic_1 0x1000661 /* U+0661 ARABIC-INDIC DIGIT ONE */ #define XK_Arabic_2 0x1000662 /* U+0662 ARABIC-INDIC DIGIT TWO */ #define XK_Arabic_3 0x1000663 /* U+0663 ARABIC-INDIC DIGIT THREE */ #define XK_Arabic_4 0x1000664 /* U+0664 ARABIC-INDIC DIGIT FOUR */ #define XK_Arabic_5 0x1000665 /* U+0665 ARABIC-INDIC DIGIT FIVE */ #define XK_Arabic_6 0x1000666 /* U+0666 ARABIC-INDIC DIGIT SIX */ #define XK_Arabic_7 0x1000667 /* U+0667 ARABIC-INDIC DIGIT SEVEN */ #define XK_Arabic_8 0x1000668 /* U+0668 ARABIC-INDIC DIGIT EIGHT */ #define XK_Arabic_9 0x1000669 /* U+0669 ARABIC-INDIC DIGIT NINE */ #define XK_Arabic_semicolon 0x05bb /* U+061B ARABIC SEMICOLON */ #define XK_Arabic_question_mark 0x05bf /* U+061F ARABIC QUESTION MARK */ #define XK_Arabic_hamza 0x05c1 /* U+0621 ARABIC LETTER HAMZA */ #define XK_Arabic_maddaonalef 0x05c2 /* U+0622 ARABIC LETTER ALEF WITH MADDA ABOVE */ #define XK_Arabic_hamzaonalef 0x05c3 /* U+0623 ARABIC LETTER ALEF WITH HAMZA ABOVE */ #define XK_Arabic_hamzaonwaw 0x05c4 /* U+0624 ARABIC LETTER WAW WITH HAMZA ABOVE */ #define XK_Arabic_hamzaunderalef 0x05c5 /* U+0625 ARABIC LETTER ALEF WITH HAMZA BELOW */ #define XK_Arabic_hamzaonyeh 0x05c6 /* U+0626 ARABIC LETTER YEH WITH HAMZA ABOVE */ #define XK_Arabic_alef 0x05c7 /* U+0627 ARABIC LETTER ALEF */ #define XK_Arabic_beh 0x05c8 /* U+0628 ARABIC LETTER BEH */ #define XK_Arabic_tehmarbuta 0x05c9 /* U+0629 ARABIC LETTER TEH MARBUTA */ #define XK_Arabic_teh 0x05ca /* U+062A ARABIC LETTER TEH */ #define XK_Arabic_theh 0x05cb /* U+062B ARABIC LETTER THEH */ #define XK_Arabic_jeem 0x05cc /* U+062C ARABIC LETTER JEEM */ #define XK_Arabic_hah 0x05cd /* U+062D ARABIC LETTER HAH */ #define XK_Arabic_khah 0x05ce /* U+062E ARABIC LETTER KHAH */ #define XK_Arabic_dal 0x05cf /* U+062F ARABIC LETTER DAL */ #define XK_Arabic_thal 0x05d0 /* U+0630 ARABIC LETTER THAL */ #define XK_Arabic_ra 0x05d1 /* U+0631 ARABIC LETTER REH */ #define XK_Arabic_zain 0x05d2 /* U+0632 ARABIC LETTER ZAIN */ #define XK_Arabic_seen 0x05d3 /* U+0633 ARABIC LETTER SEEN */ #define XK_Arabic_sheen 0x05d4 /* U+0634 ARABIC LETTER SHEEN */ #define XK_Arabic_sad 0x05d5 /* U+0635 ARABIC LETTER SAD */ #define XK_Arabic_dad 0x05d6 /* U+0636 ARABIC LETTER DAD */ #define XK_Arabic_tah 0x05d7 /* U+0637 ARABIC LETTER TAH */ #define XK_Arabic_zah 0x05d8 /* U+0638 ARABIC LETTER ZAH */ #define XK_Arabic_ain 0x05d9 /* U+0639 ARABIC LETTER AIN */ #define XK_Arabic_ghain 0x05da /* U+063A ARABIC LETTER GHAIN */ #define XK_Arabic_tatweel 0x05e0 /* U+0640 ARABIC TATWEEL */ #define XK_Arabic_feh 0x05e1 /* U+0641 ARABIC LETTER FEH */ #define XK_Arabic_qaf 0x05e2 /* U+0642 ARABIC LETTER QAF */ #define XK_Arabic_kaf 0x05e3 /* U+0643 ARABIC LETTER KAF */ #define XK_Arabic_lam 0x05e4 /* U+0644 ARABIC LETTER LAM */ #define XK_Arabic_meem 0x05e5 /* U+0645 ARABIC LETTER MEEM */ #define XK_Arabic_noon 0x05e6 /* U+0646 ARABIC LETTER NOON */ #define XK_Arabic_ha 0x05e7 /* U+0647 ARABIC LETTER HEH */ #define XK_Arabic_heh 0x05e7 /* deprecated */ #define XK_Arabic_waw 0x05e8 /* U+0648 ARABIC LETTER WAW */ #define XK_Arabic_alefmaksura 0x05e9 /* U+0649 ARABIC LETTER ALEF MAKSURA */ #define XK_Arabic_yeh 0x05ea /* U+064A ARABIC LETTER YEH */ #define XK_Arabic_fathatan 0x05eb /* U+064B ARABIC FATHATAN */ #define XK_Arabic_dammatan 0x05ec /* U+064C ARABIC DAMMATAN */ #define XK_Arabic_kasratan 0x05ed /* U+064D ARABIC KASRATAN */ #define XK_Arabic_fatha 0x05ee /* U+064E ARABIC FATHA */ #define XK_Arabic_damma 0x05ef /* U+064F ARABIC DAMMA */ #define XK_Arabic_kasra 0x05f0 /* U+0650 ARABIC KASRA */ #define XK_Arabic_shadda 0x05f1 /* U+0651 ARABIC SHADDA */ #define XK_Arabic_sukun 0x05f2 /* U+0652 ARABIC SUKUN */ #define XK_Arabic_madda_above 0x1000653 /* U+0653 ARABIC MADDAH ABOVE */ #define XK_Arabic_hamza_above 0x1000654 /* U+0654 ARABIC HAMZA ABOVE */ #define XK_Arabic_hamza_below 0x1000655 /* U+0655 ARABIC HAMZA BELOW */ #define XK_Arabic_jeh 0x1000698 /* U+0698 ARABIC LETTER JEH */ #define XK_Arabic_veh 0x10006a4 /* U+06A4 ARABIC LETTER VEH */ #define XK_Arabic_keheh 0x10006a9 /* U+06A9 ARABIC LETTER KEHEH */ #define XK_Arabic_gaf 0x10006af /* U+06AF ARABIC LETTER GAF */ #define XK_Arabic_noon_ghunna 0x10006ba /* U+06BA ARABIC LETTER NOON GHUNNA */ #define XK_Arabic_heh_doachashmee 0x10006be /* U+06BE ARABIC LETTER HEH DOACHASHMEE */ #define XK_Farsi_yeh 0x10006cc /* U+06CC ARABIC LETTER FARSI YEH */ #define XK_Arabic_farsi_yeh 0x10006cc /* U+06CC ARABIC LETTER FARSI YEH */ #define XK_Arabic_yeh_baree 0x10006d2 /* U+06D2 ARABIC LETTER YEH BARREE */ #define XK_Arabic_heh_goal 0x10006c1 /* U+06C1 ARABIC LETTER HEH GOAL */ #define XK_Arabic_switch 0xff7e /* Alias for mode_switch */ #endif /* XK_ARABIC */ /* * Cyrillic * Byte 3 = 6 */ #ifdef XK_CYRILLIC #define XK_Cyrillic_GHE_bar 0x1000492 /* U+0492 CYRILLIC CAPITAL LETTER GHE WITH STROKE */ #define XK_Cyrillic_ghe_bar 0x1000493 /* U+0493 CYRILLIC SMALL LETTER GHE WITH STROKE */ #define XK_Cyrillic_ZHE_descender 0x1000496 /* U+0496 CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER */ #define XK_Cyrillic_zhe_descender 0x1000497 /* U+0497 CYRILLIC SMALL LETTER ZHE WITH DESCENDER */ #define XK_Cyrillic_KA_descender 0x100049a /* U+049A CYRILLIC CAPITAL LETTER KA WITH DESCENDER */ #define XK_Cyrillic_ka_descender 0x100049b /* U+049B CYRILLIC SMALL LETTER KA WITH DESCENDER */ #define XK_Cyrillic_KA_vertstroke 0x100049c /* U+049C CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE */ #define XK_Cyrillic_ka_vertstroke 0x100049d /* U+049D CYRILLIC SMALL LETTER KA WITH VERTICAL STROKE */ #define XK_Cyrillic_EN_descender 0x10004a2 /* U+04A2 CYRILLIC CAPITAL LETTER EN WITH DESCENDER */ #define XK_Cyrillic_en_descender 0x10004a3 /* U+04A3 CYRILLIC SMALL LETTER EN WITH DESCENDER */ #define XK_Cyrillic_U_straight 0x10004ae /* U+04AE CYRILLIC CAPITAL LETTER STRAIGHT U */ #define XK_Cyrillic_u_straight 0x10004af /* U+04AF CYRILLIC SMALL LETTER STRAIGHT U */ #define XK_Cyrillic_U_straight_bar 0x10004b0 /* U+04B0 CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE */ #define XK_Cyrillic_u_straight_bar 0x10004b1 /* U+04B1 CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE */ #define XK_Cyrillic_HA_descender 0x10004b2 /* U+04B2 CYRILLIC CAPITAL LETTER HA WITH DESCENDER */ #define XK_Cyrillic_ha_descender 0x10004b3 /* U+04B3 CYRILLIC SMALL LETTER HA WITH DESCENDER */ #define XK_Cyrillic_CHE_descender 0x10004b6 /* U+04B6 CYRILLIC CAPITAL LETTER CHE WITH DESCENDER */ #define XK_Cyrillic_che_descender 0x10004b7 /* U+04B7 CYRILLIC SMALL LETTER CHE WITH DESCENDER */ #define XK_Cyrillic_CHE_vertstroke 0x10004b8 /* U+04B8 CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE */ #define XK_Cyrillic_che_vertstroke 0x10004b9 /* U+04B9 CYRILLIC SMALL LETTER CHE WITH VERTICAL STROKE */ #define XK_Cyrillic_SHHA 0x10004ba /* U+04BA CYRILLIC CAPITAL LETTER SHHA */ #define XK_Cyrillic_shha 0x10004bb /* U+04BB CYRILLIC SMALL LETTER SHHA */ #define XK_Cyrillic_SCHWA 0x10004d8 /* U+04D8 CYRILLIC CAPITAL LETTER SCHWA */ #define XK_Cyrillic_schwa 0x10004d9 /* U+04D9 CYRILLIC SMALL LETTER SCHWA */ #define XK_Cyrillic_I_macron 0x10004e2 /* U+04E2 CYRILLIC CAPITAL LETTER I WITH MACRON */ #define XK_Cyrillic_i_macron 0x10004e3 /* U+04E3 CYRILLIC SMALL LETTER I WITH MACRON */ #define XK_Cyrillic_O_bar 0x10004e8 /* U+04E8 CYRILLIC CAPITAL LETTER BARRED O */ #define XK_Cyrillic_o_bar 0x10004e9 /* U+04E9 CYRILLIC SMALL LETTER BARRED O */ #define XK_Cyrillic_U_macron 0x10004ee /* U+04EE CYRILLIC CAPITAL LETTER U WITH MACRON */ #define XK_Cyrillic_u_macron 0x10004ef /* U+04EF CYRILLIC SMALL LETTER U WITH MACRON */ #define XK_Serbian_dje 0x06a1 /* U+0452 CYRILLIC SMALL LETTER DJE */ #define XK_Macedonia_gje 0x06a2 /* U+0453 CYRILLIC SMALL LETTER GJE */ #define XK_Cyrillic_io 0x06a3 /* U+0451 CYRILLIC SMALL LETTER IO */ #define XK_Ukrainian_ie 0x06a4 /* U+0454 CYRILLIC SMALL LETTER UKRAINIAN IE */ #define XK_Ukranian_je 0x06a4 /* deprecated */ #define XK_Macedonia_dse 0x06a5 /* U+0455 CYRILLIC SMALL LETTER DZE */ #define XK_Ukrainian_i 0x06a6 /* U+0456 CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I */ #define XK_Ukranian_i 0x06a6 /* deprecated */ #define XK_Ukrainian_yi 0x06a7 /* U+0457 CYRILLIC SMALL LETTER YI */ #define XK_Ukranian_yi 0x06a7 /* deprecated */ #define XK_Cyrillic_je 0x06a8 /* U+0458 CYRILLIC SMALL LETTER JE */ #define XK_Serbian_je 0x06a8 /* deprecated */ #define XK_Cyrillic_lje 0x06a9 /* U+0459 CYRILLIC SMALL LETTER LJE */ #define XK_Serbian_lje 0x06a9 /* deprecated */ #define XK_Cyrillic_nje 0x06aa /* U+045A CYRILLIC SMALL LETTER NJE */ #define XK_Serbian_nje 0x06aa /* deprecated */ #define XK_Serbian_tshe 0x06ab /* U+045B CYRILLIC SMALL LETTER TSHE */ #define XK_Macedonia_kje 0x06ac /* U+045C CYRILLIC SMALL LETTER KJE */ #define XK_Ukrainian_ghe_with_upturn 0x06ad /* U+0491 CYRILLIC SMALL LETTER GHE WITH UPTURN */ #define XK_Byelorussian_shortu 0x06ae /* U+045E CYRILLIC SMALL LETTER SHORT U */ #define XK_Cyrillic_dzhe 0x06af /* U+045F CYRILLIC SMALL LETTER DZHE */ #define XK_Serbian_dze 0x06af /* deprecated */ #define XK_numerosign 0x06b0 /* U+2116 NUMERO SIGN */ #define XK_Serbian_DJE 0x06b1 /* U+0402 CYRILLIC CAPITAL LETTER DJE */ #define XK_Macedonia_GJE 0x06b2 /* U+0403 CYRILLIC CAPITAL LETTER GJE */ #define XK_Cyrillic_IO 0x06b3 /* U+0401 CYRILLIC CAPITAL LETTER IO */ #define XK_Ukrainian_IE 0x06b4 /* U+0404 CYRILLIC CAPITAL LETTER UKRAINIAN IE */ #define XK_Ukranian_JE 0x06b4 /* deprecated */ #define XK_Macedonia_DSE 0x06b5 /* U+0405 CYRILLIC CAPITAL LETTER DZE */ #define XK_Ukrainian_I 0x06b6 /* U+0406 CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */ #define XK_Ukranian_I 0x06b6 /* deprecated */ #define XK_Ukrainian_YI 0x06b7 /* U+0407 CYRILLIC CAPITAL LETTER YI */ #define XK_Ukranian_YI 0x06b7 /* deprecated */ #define XK_Cyrillic_JE 0x06b8 /* U+0408 CYRILLIC CAPITAL LETTER JE */ #define XK_Serbian_JE 0x06b8 /* deprecated */ #define XK_Cyrillic_LJE 0x06b9 /* U+0409 CYRILLIC CAPITAL LETTER LJE */ #define XK_Serbian_LJE 0x06b9 /* deprecated */ #define XK_Cyrillic_NJE 0x06ba /* U+040A CYRILLIC CAPITAL LETTER NJE */ #define XK_Serbian_NJE 0x06ba /* deprecated */ #define XK_Serbian_TSHE 0x06bb /* U+040B CYRILLIC CAPITAL LETTER TSHE */ #define XK_Macedonia_KJE 0x06bc /* U+040C CYRILLIC CAPITAL LETTER KJE */ #define XK_Ukrainian_GHE_WITH_UPTURN 0x06bd /* U+0490 CYRILLIC CAPITAL LETTER GHE WITH UPTURN */ #define XK_Byelorussian_SHORTU 0x06be /* U+040E CYRILLIC CAPITAL LETTER SHORT U */ #define XK_Cyrillic_DZHE 0x06bf /* U+040F CYRILLIC CAPITAL LETTER DZHE */ #define XK_Serbian_DZE 0x06bf /* deprecated */ #define XK_Cyrillic_yu 0x06c0 /* U+044E CYRILLIC SMALL LETTER YU */ #define XK_Cyrillic_a 0x06c1 /* U+0430 CYRILLIC SMALL LETTER A */ #define XK_Cyrillic_be 0x06c2 /* U+0431 CYRILLIC SMALL LETTER BE */ #define XK_Cyrillic_tse 0x06c3 /* U+0446 CYRILLIC SMALL LETTER TSE */ #define XK_Cyrillic_de 0x06c4 /* U+0434 CYRILLIC SMALL LETTER DE */ #define XK_Cyrillic_ie 0x06c5 /* U+0435 CYRILLIC SMALL LETTER IE */ #define XK_Cyrillic_ef 0x06c6 /* U+0444 CYRILLIC SMALL LETTER EF */ #define XK_Cyrillic_ghe 0x06c7 /* U+0433 CYRILLIC SMALL LETTER GHE */ #define XK_Cyrillic_ha 0x06c8 /* U+0445 CYRILLIC SMALL LETTER HA */ #define XK_Cyrillic_i 0x06c9 /* U+0438 CYRILLIC SMALL LETTER I */ #define XK_Cyrillic_shorti 0x06ca /* U+0439 CYRILLIC SMALL LETTER SHORT I */ #define XK_Cyrillic_ka 0x06cb /* U+043A CYRILLIC SMALL LETTER KA */ #define XK_Cyrillic_el 0x06cc /* U+043B CYRILLIC SMALL LETTER EL */ #define XK_Cyrillic_em 0x06cd /* U+043C CYRILLIC SMALL LETTER EM */ #define XK_Cyrillic_en 0x06ce /* U+043D CYRILLIC SMALL LETTER EN */ #define XK_Cyrillic_o 0x06cf /* U+043E CYRILLIC SMALL LETTER O */ #define XK_Cyrillic_pe 0x06d0 /* U+043F CYRILLIC SMALL LETTER PE */ #define XK_Cyrillic_ya 0x06d1 /* U+044F CYRILLIC SMALL LETTER YA */ #define XK_Cyrillic_er 0x06d2 /* U+0440 CYRILLIC SMALL LETTER ER */ #define XK_Cyrillic_es 0x06d3 /* U+0441 CYRILLIC SMALL LETTER ES */ #define XK_Cyrillic_te 0x06d4 /* U+0442 CYRILLIC SMALL LETTER TE */ #define XK_Cyrillic_u 0x06d5 /* U+0443 CYRILLIC SMALL LETTER U */ #define XK_Cyrillic_zhe 0x06d6 /* U+0436 CYRILLIC SMALL LETTER ZHE */ #define XK_Cyrillic_ve 0x06d7 /* U+0432 CYRILLIC SMALL LETTER VE */ #define XK_Cyrillic_softsign 0x06d8 /* U+044C CYRILLIC SMALL LETTER SOFT SIGN */ #define XK_Cyrillic_yeru 0x06d9 /* U+044B CYRILLIC SMALL LETTER YERU */ #define XK_Cyrillic_ze 0x06da /* U+0437 CYRILLIC SMALL LETTER ZE */ #define XK_Cyrillic_sha 0x06db /* U+0448 CYRILLIC SMALL LETTER SHA */ #define XK_Cyrillic_e 0x06dc /* U+044D CYRILLIC SMALL LETTER E */ #define XK_Cyrillic_shcha 0x06dd /* U+0449 CYRILLIC SMALL LETTER SHCHA */ #define XK_Cyrillic_che 0x06de /* U+0447 CYRILLIC SMALL LETTER CHE */ #define XK_Cyrillic_hardsign 0x06df /* U+044A CYRILLIC SMALL LETTER HARD SIGN */ #define XK_Cyrillic_YU 0x06e0 /* U+042E CYRILLIC CAPITAL LETTER YU */ #define XK_Cyrillic_A 0x06e1 /* U+0410 CYRILLIC CAPITAL LETTER A */ #define XK_Cyrillic_BE 0x06e2 /* U+0411 CYRILLIC CAPITAL LETTER BE */ #define XK_Cyrillic_TSE 0x06e3 /* U+0426 CYRILLIC CAPITAL LETTER TSE */ #define XK_Cyrillic_DE 0x06e4 /* U+0414 CYRILLIC CAPITAL LETTER DE */ #define XK_Cyrillic_IE 0x06e5 /* U+0415 CYRILLIC CAPITAL LETTER IE */ #define XK_Cyrillic_EF 0x06e6 /* U+0424 CYRILLIC CAPITAL LETTER EF */ #define XK_Cyrillic_GHE 0x06e7 /* U+0413 CYRILLIC CAPITAL LETTER GHE */ #define XK_Cyrillic_HA 0x06e8 /* U+0425 CYRILLIC CAPITAL LETTER HA */ #define XK_Cyrillic_I 0x06e9 /* U+0418 CYRILLIC CAPITAL LETTER I */ #define XK_Cyrillic_SHORTI 0x06ea /* U+0419 CYRILLIC CAPITAL LETTER SHORT I */ #define XK_Cyrillic_KA 0x06eb /* U+041A CYRILLIC CAPITAL LETTER KA */ #define XK_Cyrillic_EL 0x06ec /* U+041B CYRILLIC CAPITAL LETTER EL */ #define XK_Cyrillic_EM 0x06ed /* U+041C CYRILLIC CAPITAL LETTER EM */ #define XK_Cyrillic_EN 0x06ee /* U+041D CYRILLIC CAPITAL LETTER EN */ #define XK_Cyrillic_O 0x06ef /* U+041E CYRILLIC CAPITAL LETTER O */ #define XK_Cyrillic_PE 0x06f0 /* U+041F CYRILLIC CAPITAL LETTER PE */ #define XK_Cyrillic_YA 0x06f1 /* U+042F CYRILLIC CAPITAL LETTER YA */ #define XK_Cyrillic_ER 0x06f2 /* U+0420 CYRILLIC CAPITAL LETTER ER */ #define XK_Cyrillic_ES 0x06f3 /* U+0421 CYRILLIC CAPITAL LETTER ES */ #define XK_Cyrillic_TE 0x06f4 /* U+0422 CYRILLIC CAPITAL LETTER TE */ #define XK_Cyrillic_U 0x06f5 /* U+0423 CYRILLIC CAPITAL LETTER U */ #define XK_Cyrillic_ZHE 0x06f6 /* U+0416 CYRILLIC CAPITAL LETTER ZHE */ #define XK_Cyrillic_VE 0x06f7 /* U+0412 CYRILLIC CAPITAL LETTER VE */ #define XK_Cyrillic_SOFTSIGN 0x06f8 /* U+042C CYRILLIC CAPITAL LETTER SOFT SIGN */ #define XK_Cyrillic_YERU 0x06f9 /* U+042B CYRILLIC CAPITAL LETTER YERU */ #define XK_Cyrillic_ZE 0x06fa /* U+0417 CYRILLIC CAPITAL LETTER ZE */ #define XK_Cyrillic_SHA 0x06fb /* U+0428 CYRILLIC CAPITAL LETTER SHA */ #define XK_Cyrillic_E 0x06fc /* U+042D CYRILLIC CAPITAL LETTER E */ #define XK_Cyrillic_SHCHA 0x06fd /* U+0429 CYRILLIC CAPITAL LETTER SHCHA */ #define XK_Cyrillic_CHE 0x06fe /* U+0427 CYRILLIC CAPITAL LETTER CHE */ #define XK_Cyrillic_HARDSIGN 0x06ff /* U+042A CYRILLIC CAPITAL LETTER HARD SIGN */ #endif /* XK_CYRILLIC */ /* * Greek * (based on an early draft of, and not quite identical to, ISO/IEC 8859-7) * Byte 3 = 7 */ #ifdef XK_GREEK #define XK_Greek_ALPHAaccent 0x07a1 /* U+0386 GREEK CAPITAL LETTER ALPHA WITH TONOS */ #define XK_Greek_EPSILONaccent 0x07a2 /* U+0388 GREEK CAPITAL LETTER EPSILON WITH TONOS */ #define XK_Greek_ETAaccent 0x07a3 /* U+0389 GREEK CAPITAL LETTER ETA WITH TONOS */ #define XK_Greek_IOTAaccent 0x07a4 /* U+038A GREEK CAPITAL LETTER IOTA WITH TONOS */ #define XK_Greek_IOTAdieresis 0x07a5 /* U+03AA GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */ #define XK_Greek_IOTAdiaeresis 0x07a5 /* old typo */ #define XK_Greek_OMICRONaccent 0x07a7 /* U+038C GREEK CAPITAL LETTER OMICRON WITH TONOS */ #define XK_Greek_UPSILONaccent 0x07a8 /* U+038E GREEK CAPITAL LETTER UPSILON WITH TONOS */ #define XK_Greek_UPSILONdieresis 0x07a9 /* U+03AB GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */ #define XK_Greek_OMEGAaccent 0x07ab /* U+038F GREEK CAPITAL LETTER OMEGA WITH TONOS */ #define XK_Greek_accentdieresis 0x07ae /* U+0385 GREEK DIALYTIKA TONOS */ #define XK_Greek_horizbar 0x07af /* U+2015 HORIZONTAL BAR */ #define XK_Greek_alphaaccent 0x07b1 /* U+03AC GREEK SMALL LETTER ALPHA WITH TONOS */ #define XK_Greek_epsilonaccent 0x07b2 /* U+03AD GREEK SMALL LETTER EPSILON WITH TONOS */ #define XK_Greek_etaaccent 0x07b3 /* U+03AE GREEK SMALL LETTER ETA WITH TONOS */ #define XK_Greek_iotaaccent 0x07b4 /* U+03AF GREEK SMALL LETTER IOTA WITH TONOS */ #define XK_Greek_iotadieresis 0x07b5 /* U+03CA GREEK SMALL LETTER IOTA WITH DIALYTIKA */ #define XK_Greek_iotaaccentdieresis 0x07b6 /* U+0390 GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */ #define XK_Greek_omicronaccent 0x07b7 /* U+03CC GREEK SMALL LETTER OMICRON WITH TONOS */ #define XK_Greek_upsilonaccent 0x07b8 /* U+03CD GREEK SMALL LETTER UPSILON WITH TONOS */ #define XK_Greek_upsilondieresis 0x07b9 /* U+03CB GREEK SMALL LETTER UPSILON WITH DIALYTIKA */ #define XK_Greek_upsilonaccentdieresis 0x07ba /* U+03B0 GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */ #define XK_Greek_omegaaccent 0x07bb /* U+03CE GREEK SMALL LETTER OMEGA WITH TONOS */ #define XK_Greek_ALPHA 0x07c1 /* U+0391 GREEK CAPITAL LETTER ALPHA */ #define XK_Greek_BETA 0x07c2 /* U+0392 GREEK CAPITAL LETTER BETA */ #define XK_Greek_GAMMA 0x07c3 /* U+0393 GREEK CAPITAL LETTER GAMMA */ #define XK_Greek_DELTA 0x07c4 /* U+0394 GREEK CAPITAL LETTER DELTA */ #define XK_Greek_EPSILON 0x07c5 /* U+0395 GREEK CAPITAL LETTER EPSILON */ #define XK_Greek_ZETA 0x07c6 /* U+0396 GREEK CAPITAL LETTER ZETA */ #define XK_Greek_ETA 0x07c7 /* U+0397 GREEK CAPITAL LETTER ETA */ #define XK_Greek_THETA 0x07c8 /* U+0398 GREEK CAPITAL LETTER THETA */ #define XK_Greek_IOTA 0x07c9 /* U+0399 GREEK CAPITAL LETTER IOTA */ #define XK_Greek_KAPPA 0x07ca /* U+039A GREEK CAPITAL LETTER KAPPA */ #define XK_Greek_LAMDA 0x07cb /* U+039B GREEK CAPITAL LETTER LAMDA */ #define XK_Greek_LAMBDA 0x07cb /* U+039B GREEK CAPITAL LETTER LAMDA */ #define XK_Greek_MU 0x07cc /* U+039C GREEK CAPITAL LETTER MU */ #define XK_Greek_NU 0x07cd /* U+039D GREEK CAPITAL LETTER NU */ #define XK_Greek_XI 0x07ce /* U+039E GREEK CAPITAL LETTER XI */ #define XK_Greek_OMICRON 0x07cf /* U+039F GREEK CAPITAL LETTER OMICRON */ #define XK_Greek_PI 0x07d0 /* U+03A0 GREEK CAPITAL LETTER PI */ #define XK_Greek_RHO 0x07d1 /* U+03A1 GREEK CAPITAL LETTER RHO */ #define XK_Greek_SIGMA 0x07d2 /* U+03A3 GREEK CAPITAL LETTER SIGMA */ #define XK_Greek_TAU 0x07d4 /* U+03A4 GREEK CAPITAL LETTER TAU */ #define XK_Greek_UPSILON 0x07d5 /* U+03A5 GREEK CAPITAL LETTER UPSILON */ #define XK_Greek_PHI 0x07d6 /* U+03A6 GREEK CAPITAL LETTER PHI */ #define XK_Greek_CHI 0x07d7 /* U+03A7 GREEK CAPITAL LETTER CHI */ #define XK_Greek_PSI 0x07d8 /* U+03A8 GREEK CAPITAL LETTER PSI */ #define XK_Greek_OMEGA 0x07d9 /* U+03A9 GREEK CAPITAL LETTER OMEGA */ #define XK_Greek_alpha 0x07e1 /* U+03B1 GREEK SMALL LETTER ALPHA */ #define XK_Greek_beta 0x07e2 /* U+03B2 GREEK SMALL LETTER BETA */ #define XK_Greek_gamma 0x07e3 /* U+03B3 GREEK SMALL LETTER GAMMA */ #define XK_Greek_delta 0x07e4 /* U+03B4 GREEK SMALL LETTER DELTA */ #define XK_Greek_epsilon 0x07e5 /* U+03B5 GREEK SMALL LETTER EPSILON */ #define XK_Greek_zeta 0x07e6 /* U+03B6 GREEK SMALL LETTER ZETA */ #define XK_Greek_eta 0x07e7 /* U+03B7 GREEK SMALL LETTER ETA */ #define XK_Greek_theta 0x07e8 /* U+03B8 GREEK SMALL LETTER THETA */ #define XK_Greek_iota 0x07e9 /* U+03B9 GREEK SMALL LETTER IOTA */ #define XK_Greek_kappa 0x07ea /* U+03BA GREEK SMALL LETTER KAPPA */ #define XK_Greek_lamda 0x07eb /* U+03BB GREEK SMALL LETTER LAMDA */ #define XK_Greek_lambda 0x07eb /* U+03BB GREEK SMALL LETTER LAMDA */ #define XK_Greek_mu 0x07ec /* U+03BC GREEK SMALL LETTER MU */ #define XK_Greek_nu 0x07ed /* U+03BD GREEK SMALL LETTER NU */ #define XK_Greek_xi 0x07ee /* U+03BE GREEK SMALL LETTER XI */ #define XK_Greek_omicron 0x07ef /* U+03BF GREEK SMALL LETTER OMICRON */ #define XK_Greek_pi 0x07f0 /* U+03C0 GREEK SMALL LETTER PI */ #define XK_Greek_rho 0x07f1 /* U+03C1 GREEK SMALL LETTER RHO */ #define XK_Greek_sigma 0x07f2 /* U+03C3 GREEK SMALL LETTER SIGMA */ #define XK_Greek_finalsmallsigma 0x07f3 /* U+03C2 GREEK SMALL LETTER FINAL SIGMA */ #define XK_Greek_tau 0x07f4 /* U+03C4 GREEK SMALL LETTER TAU */ #define XK_Greek_upsilon 0x07f5 /* U+03C5 GREEK SMALL LETTER UPSILON */ #define XK_Greek_phi 0x07f6 /* U+03C6 GREEK SMALL LETTER PHI */ #define XK_Greek_chi 0x07f7 /* U+03C7 GREEK SMALL LETTER CHI */ #define XK_Greek_psi 0x07f8 /* U+03C8 GREEK SMALL LETTER PSI */ #define XK_Greek_omega 0x07f9 /* U+03C9 GREEK SMALL LETTER OMEGA */ #define XK_Greek_switch 0xff7e /* Alias for mode_switch */ #endif /* XK_GREEK */ /* * Technical * (from the DEC VT330/VT420 Technical Character Set, http://vt100.net/charsets/technical.html) * Byte 3 = 8 */ #ifdef XK_TECHNICAL #define XK_leftradical 0x08a1 /* U+23B7 RADICAL SYMBOL BOTTOM */ #define XK_topleftradical 0x08a2 /*(U+250C BOX DRAWINGS LIGHT DOWN AND RIGHT)*/ #define XK_horizconnector 0x08a3 /*(U+2500 BOX DRAWINGS LIGHT HORIZONTAL)*/ #define XK_topintegral 0x08a4 /* U+2320 TOP HALF INTEGRAL */ #define XK_botintegral 0x08a5 /* U+2321 BOTTOM HALF INTEGRAL */ #define XK_vertconnector 0x08a6 /*(U+2502 BOX DRAWINGS LIGHT VERTICAL)*/ #define XK_topleftsqbracket 0x08a7 /* U+23A1 LEFT SQUARE BRACKET UPPER CORNER */ #define XK_botleftsqbracket 0x08a8 /* U+23A3 LEFT SQUARE BRACKET LOWER CORNER */ #define XK_toprightsqbracket 0x08a9 /* U+23A4 RIGHT SQUARE BRACKET UPPER CORNER */ #define XK_botrightsqbracket 0x08aa /* U+23A6 RIGHT SQUARE BRACKET LOWER CORNER */ #define XK_topleftparens 0x08ab /* U+239B LEFT PARENTHESIS UPPER HOOK */ #define XK_botleftparens 0x08ac /* U+239D LEFT PARENTHESIS LOWER HOOK */ #define XK_toprightparens 0x08ad /* U+239E RIGHT PARENTHESIS UPPER HOOK */ #define XK_botrightparens 0x08ae /* U+23A0 RIGHT PARENTHESIS LOWER HOOK */ #define XK_leftmiddlecurlybrace 0x08af /* U+23A8 LEFT CURLY BRACKET MIDDLE PIECE */ #define XK_rightmiddlecurlybrace 0x08b0 /* U+23AC RIGHT CURLY BRACKET MIDDLE PIECE */ #define XK_topleftsummation 0x08b1 #define XK_botleftsummation 0x08b2 #define XK_topvertsummationconnector 0x08b3 #define XK_botvertsummationconnector 0x08b4 #define XK_toprightsummation 0x08b5 #define XK_botrightsummation 0x08b6 #define XK_rightmiddlesummation 0x08b7 #define XK_lessthanequal 0x08bc /* U+2264 LESS-THAN OR EQUAL TO */ #define XK_notequal 0x08bd /* U+2260 NOT EQUAL TO */ #define XK_greaterthanequal 0x08be /* U+2265 GREATER-THAN OR EQUAL TO */ #define XK_integral 0x08bf /* U+222B INTEGRAL */ #define XK_therefore 0x08c0 /* U+2234 THEREFORE */ #define XK_variation 0x08c1 /* U+221D PROPORTIONAL TO */ #define XK_infinity 0x08c2 /* U+221E INFINITY */ #define XK_nabla 0x08c5 /* U+2207 NABLA */ #define XK_approximate 0x08c8 /* U+223C TILDE OPERATOR */ #define XK_similarequal 0x08c9 /* U+2243 ASYMPTOTICALLY EQUAL TO */ #define XK_ifonlyif 0x08cd /* U+21D4 LEFT RIGHT DOUBLE ARROW */ #define XK_implies 0x08ce /* U+21D2 RIGHTWARDS DOUBLE ARROW */ #define XK_identical 0x08cf /* U+2261 IDENTICAL TO */ #define XK_radical 0x08d6 /* U+221A SQUARE ROOT */ #define XK_includedin 0x08da /* U+2282 SUBSET OF */ #define XK_includes 0x08db /* U+2283 SUPERSET OF */ #define XK_intersection 0x08dc /* U+2229 INTERSECTION */ #define XK_union 0x08dd /* U+222A UNION */ #define XK_logicaland 0x08de /* U+2227 LOGICAL AND */ #define XK_logicalor 0x08df /* U+2228 LOGICAL OR */ #define XK_partialderivative 0x08ef /* U+2202 PARTIAL DIFFERENTIAL */ #define XK_function 0x08f6 /* U+0192 LATIN SMALL LETTER F WITH HOOK */ #define XK_leftarrow 0x08fb /* U+2190 LEFTWARDS ARROW */ #define XK_uparrow 0x08fc /* U+2191 UPWARDS ARROW */ #define XK_rightarrow 0x08fd /* U+2192 RIGHTWARDS ARROW */ #define XK_downarrow 0x08fe /* U+2193 DOWNWARDS ARROW */ #endif /* XK_TECHNICAL */ /* * Special * (from the DEC VT100 Special Graphics Character Set) * Byte 3 = 9 */ #ifdef XK_SPECIAL #define XK_blank 0x09df #define XK_soliddiamond 0x09e0 /* U+25C6 BLACK DIAMOND */ #define XK_checkerboard 0x09e1 /* U+2592 MEDIUM SHADE */ #define XK_ht 0x09e2 /* U+2409 SYMBOL FOR HORIZONTAL TABULATION */ #define XK_ff 0x09e3 /* U+240C SYMBOL FOR FORM FEED */ #define XK_cr 0x09e4 /* U+240D SYMBOL FOR CARRIAGE RETURN */ #define XK_lf 0x09e5 /* U+240A SYMBOL FOR LINE FEED */ #define XK_nl 0x09e8 /* U+2424 SYMBOL FOR NEWLINE */ #define XK_vt 0x09e9 /* U+240B SYMBOL FOR VERTICAL TABULATION */ #define XK_lowrightcorner 0x09ea /* U+2518 BOX DRAWINGS LIGHT UP AND LEFT */ #define XK_uprightcorner 0x09eb /* U+2510 BOX DRAWINGS LIGHT DOWN AND LEFT */ #define XK_upleftcorner 0x09ec /* U+250C BOX DRAWINGS LIGHT DOWN AND RIGHT */ #define XK_lowleftcorner 0x09ed /* U+2514 BOX DRAWINGS LIGHT UP AND RIGHT */ #define XK_crossinglines 0x09ee /* U+253C BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */ #define XK_horizlinescan1 0x09ef /* U+23BA HORIZONTAL SCAN LINE-1 */ #define XK_horizlinescan3 0x09f0 /* U+23BB HORIZONTAL SCAN LINE-3 */ #define XK_horizlinescan5 0x09f1 /* U+2500 BOX DRAWINGS LIGHT HORIZONTAL */ #define XK_horizlinescan7 0x09f2 /* U+23BC HORIZONTAL SCAN LINE-7 */ #define XK_horizlinescan9 0x09f3 /* U+23BD HORIZONTAL SCAN LINE-9 */ #define XK_leftt 0x09f4 /* U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT */ #define XK_rightt 0x09f5 /* U+2524 BOX DRAWINGS LIGHT VERTICAL AND LEFT */ #define XK_bott 0x09f6 /* U+2534 BOX DRAWINGS LIGHT UP AND HORIZONTAL */ #define XK_topt 0x09f7 /* U+252C BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */ #define XK_vertbar 0x09f8 /* U+2502 BOX DRAWINGS LIGHT VERTICAL */ #endif /* XK_SPECIAL */ /* * Publishing * (these are probably from a long forgotten DEC Publishing * font that once shipped with DECwrite) * Byte 3 = 0x0a */ #ifdef XK_PUBLISHING #define XK_emspace 0x0aa1 /* U+2003 EM SPACE */ #define XK_enspace 0x0aa2 /* U+2002 EN SPACE */ #define XK_em3space 0x0aa3 /* U+2004 THREE-PER-EM SPACE */ #define XK_em4space 0x0aa4 /* U+2005 FOUR-PER-EM SPACE */ #define XK_digitspace 0x0aa5 /* U+2007 FIGURE SPACE */ #define XK_punctspace 0x0aa6 /* U+2008 PUNCTUATION SPACE */ #define XK_thinspace 0x0aa7 /* U+2009 THIN SPACE */ #define XK_hairspace 0x0aa8 /* U+200A HAIR SPACE */ #define XK_emdash 0x0aa9 /* U+2014 EM DASH */ #define XK_endash 0x0aaa /* U+2013 EN DASH */ #define XK_signifblank 0x0aac /*(U+2423 OPEN BOX)*/ #define XK_ellipsis 0x0aae /* U+2026 HORIZONTAL ELLIPSIS */ #define XK_doubbaselinedot 0x0aaf /* U+2025 TWO DOT LEADER */ #define XK_onethird 0x0ab0 /* U+2153 VULGAR FRACTION ONE THIRD */ #define XK_twothirds 0x0ab1 /* U+2154 VULGAR FRACTION TWO THIRDS */ #define XK_onefifth 0x0ab2 /* U+2155 VULGAR FRACTION ONE FIFTH */ #define XK_twofifths 0x0ab3 /* U+2156 VULGAR FRACTION TWO FIFTHS */ #define XK_threefifths 0x0ab4 /* U+2157 VULGAR FRACTION THREE FIFTHS */ #define XK_fourfifths 0x0ab5 /* U+2158 VULGAR FRACTION FOUR FIFTHS */ #define XK_onesixth 0x0ab6 /* U+2159 VULGAR FRACTION ONE SIXTH */ #define XK_fivesixths 0x0ab7 /* U+215A VULGAR FRACTION FIVE SIXTHS */ #define XK_careof 0x0ab8 /* U+2105 CARE OF */ #define XK_figdash 0x0abb /* U+2012 FIGURE DASH */ #define XK_leftanglebracket 0x0abc /*(U+27E8 MATHEMATICAL LEFT ANGLE BRACKET)*/ #define XK_decimalpoint 0x0abd /*(U+002E FULL STOP)*/ #define XK_rightanglebracket 0x0abe /*(U+27E9 MATHEMATICAL RIGHT ANGLE BRACKET)*/ #define XK_marker 0x0abf #define XK_oneeighth 0x0ac3 /* U+215B VULGAR FRACTION ONE EIGHTH */ #define XK_threeeighths 0x0ac4 /* U+215C VULGAR FRACTION THREE EIGHTHS */ #define XK_fiveeighths 0x0ac5 /* U+215D VULGAR FRACTION FIVE EIGHTHS */ #define XK_seveneighths 0x0ac6 /* U+215E VULGAR FRACTION SEVEN EIGHTHS */ #define XK_trademark 0x0ac9 /* U+2122 TRADE MARK SIGN */ #define XK_signaturemark 0x0aca /*(U+2613 SALTIRE)*/ #define XK_trademarkincircle 0x0acb #define XK_leftopentriangle 0x0acc /*(U+25C1 WHITE LEFT-POINTING TRIANGLE)*/ #define XK_rightopentriangle 0x0acd /*(U+25B7 WHITE RIGHT-POINTING TRIANGLE)*/ #define XK_emopencircle 0x0ace /*(U+25CB WHITE CIRCLE)*/ #define XK_emopenrectangle 0x0acf /*(U+25AF WHITE VERTICAL RECTANGLE)*/ #define XK_leftsinglequotemark 0x0ad0 /* U+2018 LEFT SINGLE QUOTATION MARK */ #define XK_rightsinglequotemark 0x0ad1 /* U+2019 RIGHT SINGLE QUOTATION MARK */ #define XK_leftdoublequotemark 0x0ad2 /* U+201C LEFT DOUBLE QUOTATION MARK */ #define XK_rightdoublequotemark 0x0ad3 /* U+201D RIGHT DOUBLE QUOTATION MARK */ #define XK_prescription 0x0ad4 /* U+211E PRESCRIPTION TAKE */ #define XK_permille 0x0ad5 /* U+2030 PER MILLE SIGN */ #define XK_minutes 0x0ad6 /* U+2032 PRIME */ #define XK_seconds 0x0ad7 /* U+2033 DOUBLE PRIME */ #define XK_latincross 0x0ad9 /* U+271D LATIN CROSS */ #define XK_hexagram 0x0ada #define XK_filledrectbullet 0x0adb /*(U+25AC BLACK RECTANGLE)*/ #define XK_filledlefttribullet 0x0adc /*(U+25C0 BLACK LEFT-POINTING TRIANGLE)*/ #define XK_filledrighttribullet 0x0add /*(U+25B6 BLACK RIGHT-POINTING TRIANGLE)*/ #define XK_emfilledcircle 0x0ade /*(U+25CF BLACK CIRCLE)*/ #define XK_emfilledrect 0x0adf /*(U+25AE BLACK VERTICAL RECTANGLE)*/ #define XK_enopencircbullet 0x0ae0 /*(U+25E6 WHITE BULLET)*/ #define XK_enopensquarebullet 0x0ae1 /*(U+25AB WHITE SMALL SQUARE)*/ #define XK_openrectbullet 0x0ae2 /*(U+25AD WHITE RECTANGLE)*/ #define XK_opentribulletup 0x0ae3 /*(U+25B3 WHITE UP-POINTING TRIANGLE)*/ #define XK_opentribulletdown 0x0ae4 /*(U+25BD WHITE DOWN-POINTING TRIANGLE)*/ #define XK_openstar 0x0ae5 /*(U+2606 WHITE STAR)*/ #define XK_enfilledcircbullet 0x0ae6 /*(U+2022 BULLET)*/ #define XK_enfilledsqbullet 0x0ae7 /*(U+25AA BLACK SMALL SQUARE)*/ #define XK_filledtribulletup 0x0ae8 /*(U+25B2 BLACK UP-POINTING TRIANGLE)*/ #define XK_filledtribulletdown 0x0ae9 /*(U+25BC BLACK DOWN-POINTING TRIANGLE)*/ #define XK_leftpointer 0x0aea /*(U+261C WHITE LEFT POINTING INDEX)*/ #define XK_rightpointer 0x0aeb /*(U+261E WHITE RIGHT POINTING INDEX)*/ #define XK_club 0x0aec /* U+2663 BLACK CLUB SUIT */ #define XK_diamond 0x0aed /* U+2666 BLACK DIAMOND SUIT */ #define XK_heart 0x0aee /* U+2665 BLACK HEART SUIT */ #define XK_maltesecross 0x0af0 /* U+2720 MALTESE CROSS */ #define XK_dagger 0x0af1 /* U+2020 DAGGER */ #define XK_doubledagger 0x0af2 /* U+2021 DOUBLE DAGGER */ #define XK_checkmark 0x0af3 /* U+2713 CHECK MARK */ #define XK_ballotcross 0x0af4 /* U+2717 BALLOT X */ #define XK_musicalsharp 0x0af5 /* U+266F MUSIC SHARP SIGN */ #define XK_musicalflat 0x0af6 /* U+266D MUSIC FLAT SIGN */ #define XK_malesymbol 0x0af7 /* U+2642 MALE SIGN */ #define XK_femalesymbol 0x0af8 /* U+2640 FEMALE SIGN */ #define XK_telephone 0x0af9 /* U+260E BLACK TELEPHONE */ #define XK_telephonerecorder 0x0afa /* U+2315 TELEPHONE RECORDER */ #define XK_phonographcopyright 0x0afb /* U+2117 SOUND RECORDING COPYRIGHT */ #define XK_caret 0x0afc /* U+2038 CARET */ #define XK_singlelowquotemark 0x0afd /* U+201A SINGLE LOW-9 QUOTATION MARK */ #define XK_doublelowquotemark 0x0afe /* U+201E DOUBLE LOW-9 QUOTATION MARK */ #define XK_cursor 0x0aff #endif /* XK_PUBLISHING */ /* * APL * Byte 3 = 0x0b */ #ifdef XK_APL #define XK_leftcaret 0x0ba3 /*(U+003C LESS-THAN SIGN)*/ #define XK_rightcaret 0x0ba6 /*(U+003E GREATER-THAN SIGN)*/ #define XK_downcaret 0x0ba8 /*(U+2228 LOGICAL OR)*/ #define XK_upcaret 0x0ba9 /*(U+2227 LOGICAL AND)*/ #define XK_overbar 0x0bc0 /*(U+00AF MACRON)*/ #define XK_downtack 0x0bc2 /* U+22A4 DOWN TACK */ #define XK_upshoe 0x0bc3 /*(U+2229 INTERSECTION)*/ #define XK_downstile 0x0bc4 /* U+230A LEFT FLOOR */ #define XK_underbar 0x0bc6 /*(U+005F LOW LINE)*/ #define XK_jot 0x0bca /* U+2218 RING OPERATOR */ #define XK_quad 0x0bcc /* U+2395 APL FUNCTIONAL SYMBOL QUAD */ #define XK_uptack 0x0bce /* U+22A5 UP TACK */ #define XK_circle 0x0bcf /* U+25CB WHITE CIRCLE */ #define XK_upstile 0x0bd3 /* U+2308 LEFT CEILING */ #define XK_downshoe 0x0bd6 /*(U+222A UNION)*/ #define XK_rightshoe 0x0bd8 /*(U+2283 SUPERSET OF)*/ #define XK_leftshoe 0x0bda /*(U+2282 SUBSET OF)*/ #define XK_lefttack 0x0bdc /* U+22A3 LEFT TACK */ #define XK_righttack 0x0bfc /* U+22A2 RIGHT TACK */ #endif /* XK_APL */ /* * Hebrew * Byte 3 = 0x0c */ #ifdef XK_HEBREW #define XK_hebrew_doublelowline 0x0cdf /* U+2017 DOUBLE LOW LINE */ #define XK_hebrew_aleph 0x0ce0 /* U+05D0 HEBREW LETTER ALEF */ #define XK_hebrew_bet 0x0ce1 /* U+05D1 HEBREW LETTER BET */ #define XK_hebrew_beth 0x0ce1 /* deprecated */ #define XK_hebrew_gimel 0x0ce2 /* U+05D2 HEBREW LETTER GIMEL */ #define XK_hebrew_gimmel 0x0ce2 /* deprecated */ #define XK_hebrew_dalet 0x0ce3 /* U+05D3 HEBREW LETTER DALET */ #define XK_hebrew_daleth 0x0ce3 /* deprecated */ #define XK_hebrew_he 0x0ce4 /* U+05D4 HEBREW LETTER HE */ #define XK_hebrew_waw 0x0ce5 /* U+05D5 HEBREW LETTER VAV */ #define XK_hebrew_zain 0x0ce6 /* U+05D6 HEBREW LETTER ZAYIN */ #define XK_hebrew_zayin 0x0ce6 /* deprecated */ #define XK_hebrew_chet 0x0ce7 /* U+05D7 HEBREW LETTER HET */ #define XK_hebrew_het 0x0ce7 /* deprecated */ #define XK_hebrew_tet 0x0ce8 /* U+05D8 HEBREW LETTER TET */ #define XK_hebrew_teth 0x0ce8 /* deprecated */ #define XK_hebrew_yod 0x0ce9 /* U+05D9 HEBREW LETTER YOD */ #define XK_hebrew_finalkaph 0x0cea /* U+05DA HEBREW LETTER FINAL KAF */ #define XK_hebrew_kaph 0x0ceb /* U+05DB HEBREW LETTER KAF */ #define XK_hebrew_lamed 0x0cec /* U+05DC HEBREW LETTER LAMED */ #define XK_hebrew_finalmem 0x0ced /* U+05DD HEBREW LETTER FINAL MEM */ #define XK_hebrew_mem 0x0cee /* U+05DE HEBREW LETTER MEM */ #define XK_hebrew_finalnun 0x0cef /* U+05DF HEBREW LETTER FINAL NUN */ #define XK_hebrew_nun 0x0cf0 /* U+05E0 HEBREW LETTER NUN */ #define XK_hebrew_samech 0x0cf1 /* U+05E1 HEBREW LETTER SAMEKH */ #define XK_hebrew_samekh 0x0cf1 /* deprecated */ #define XK_hebrew_ayin 0x0cf2 /* U+05E2 HEBREW LETTER AYIN */ #define XK_hebrew_finalpe 0x0cf3 /* U+05E3 HEBREW LETTER FINAL PE */ #define XK_hebrew_pe 0x0cf4 /* U+05E4 HEBREW LETTER PE */ #define XK_hebrew_finalzade 0x0cf5 /* U+05E5 HEBREW LETTER FINAL TSADI */ #define XK_hebrew_finalzadi 0x0cf5 /* deprecated */ #define XK_hebrew_zade 0x0cf6 /* U+05E6 HEBREW LETTER TSADI */ #define XK_hebrew_zadi 0x0cf6 /* deprecated */ #define XK_hebrew_qoph 0x0cf7 /* U+05E7 HEBREW LETTER QOF */ #define XK_hebrew_kuf 0x0cf7 /* deprecated */ #define XK_hebrew_resh 0x0cf8 /* U+05E8 HEBREW LETTER RESH */ #define XK_hebrew_shin 0x0cf9 /* U+05E9 HEBREW LETTER SHIN */ #define XK_hebrew_taw 0x0cfa /* U+05EA HEBREW LETTER TAV */ #define XK_hebrew_taf 0x0cfa /* deprecated */ #define XK_Hebrew_switch 0xff7e /* Alias for mode_switch */ #endif /* XK_HEBREW */ /* * Thai * Byte 3 = 0x0d */ #ifdef XK_THAI #define XK_Thai_kokai 0x0da1 /* U+0E01 THAI CHARACTER KO KAI */ #define XK_Thai_khokhai 0x0da2 /* U+0E02 THAI CHARACTER KHO KHAI */ #define XK_Thai_khokhuat 0x0da3 /* U+0E03 THAI CHARACTER KHO KHUAT */ #define XK_Thai_khokhwai 0x0da4 /* U+0E04 THAI CHARACTER KHO KHWAI */ #define XK_Thai_khokhon 0x0da5 /* U+0E05 THAI CHARACTER KHO KHON */ #define XK_Thai_khorakhang 0x0da6 /* U+0E06 THAI CHARACTER KHO RAKHANG */ #define XK_Thai_ngongu 0x0da7 /* U+0E07 THAI CHARACTER NGO NGU */ #define XK_Thai_chochan 0x0da8 /* U+0E08 THAI CHARACTER CHO CHAN */ #define XK_Thai_choching 0x0da9 /* U+0E09 THAI CHARACTER CHO CHING */ #define XK_Thai_chochang 0x0daa /* U+0E0A THAI CHARACTER CHO CHANG */ #define XK_Thai_soso 0x0dab /* U+0E0B THAI CHARACTER SO SO */ #define XK_Thai_chochoe 0x0dac /* U+0E0C THAI CHARACTER CHO CHOE */ #define XK_Thai_yoying 0x0dad /* U+0E0D THAI CHARACTER YO YING */ #define XK_Thai_dochada 0x0dae /* U+0E0E THAI CHARACTER DO CHADA */ #define XK_Thai_topatak 0x0daf /* U+0E0F THAI CHARACTER TO PATAK */ #define XK_Thai_thothan 0x0db0 /* U+0E10 THAI CHARACTER THO THAN */ #define XK_Thai_thonangmontho 0x0db1 /* U+0E11 THAI CHARACTER THO NANGMONTHO */ #define XK_Thai_thophuthao 0x0db2 /* U+0E12 THAI CHARACTER THO PHUTHAO */ #define XK_Thai_nonen 0x0db3 /* U+0E13 THAI CHARACTER NO NEN */ #define XK_Thai_dodek 0x0db4 /* U+0E14 THAI CHARACTER DO DEK */ #define XK_Thai_totao 0x0db5 /* U+0E15 THAI CHARACTER TO TAO */ #define XK_Thai_thothung 0x0db6 /* U+0E16 THAI CHARACTER THO THUNG */ #define XK_Thai_thothahan 0x0db7 /* U+0E17 THAI CHARACTER THO THAHAN */ #define XK_Thai_thothong 0x0db8 /* U+0E18 THAI CHARACTER THO THONG */ #define XK_Thai_nonu 0x0db9 /* U+0E19 THAI CHARACTER NO NU */ #define XK_Thai_bobaimai 0x0dba /* U+0E1A THAI CHARACTER BO BAIMAI */ #define XK_Thai_popla 0x0dbb /* U+0E1B THAI CHARACTER PO PLA */ #define XK_Thai_phophung 0x0dbc /* U+0E1C THAI CHARACTER PHO PHUNG */ #define XK_Thai_fofa 0x0dbd /* U+0E1D THAI CHARACTER FO FA */ #define XK_Thai_phophan 0x0dbe /* U+0E1E THAI CHARACTER PHO PHAN */ #define XK_Thai_fofan 0x0dbf /* U+0E1F THAI CHARACTER FO FAN */ #define XK_Thai_phosamphao 0x0dc0 /* U+0E20 THAI CHARACTER PHO SAMPHAO */ #define XK_Thai_moma 0x0dc1 /* U+0E21 THAI CHARACTER MO MA */ #define XK_Thai_yoyak 0x0dc2 /* U+0E22 THAI CHARACTER YO YAK */ #define XK_Thai_rorua 0x0dc3 /* U+0E23 THAI CHARACTER RO RUA */ #define XK_Thai_ru 0x0dc4 /* U+0E24 THAI CHARACTER RU */ #define XK_Thai_loling 0x0dc5 /* U+0E25 THAI CHARACTER LO LING */ #define XK_Thai_lu 0x0dc6 /* U+0E26 THAI CHARACTER LU */ #define XK_Thai_wowaen 0x0dc7 /* U+0E27 THAI CHARACTER WO WAEN */ #define XK_Thai_sosala 0x0dc8 /* U+0E28 THAI CHARACTER SO SALA */ #define XK_Thai_sorusi 0x0dc9 /* U+0E29 THAI CHARACTER SO RUSI */ #define XK_Thai_sosua 0x0dca /* U+0E2A THAI CHARACTER SO SUA */ #define XK_Thai_hohip 0x0dcb /* U+0E2B THAI CHARACTER HO HIP */ #define XK_Thai_lochula 0x0dcc /* U+0E2C THAI CHARACTER LO CHULA */ #define XK_Thai_oang 0x0dcd /* U+0E2D THAI CHARACTER O ANG */ #define XK_Thai_honokhuk 0x0dce /* U+0E2E THAI CHARACTER HO NOKHUK */ #define XK_Thai_paiyannoi 0x0dcf /* U+0E2F THAI CHARACTER PAIYANNOI */ #define XK_Thai_saraa 0x0dd0 /* U+0E30 THAI CHARACTER SARA A */ #define XK_Thai_maihanakat 0x0dd1 /* U+0E31 THAI CHARACTER MAI HAN-AKAT */ #define XK_Thai_saraaa 0x0dd2 /* U+0E32 THAI CHARACTER SARA AA */ #define XK_Thai_saraam 0x0dd3 /* U+0E33 THAI CHARACTER SARA AM */ #define XK_Thai_sarai 0x0dd4 /* U+0E34 THAI CHARACTER SARA I */ #define XK_Thai_saraii 0x0dd5 /* U+0E35 THAI CHARACTER SARA II */ #define XK_Thai_saraue 0x0dd6 /* U+0E36 THAI CHARACTER SARA UE */ #define XK_Thai_sarauee 0x0dd7 /* U+0E37 THAI CHARACTER SARA UEE */ #define XK_Thai_sarau 0x0dd8 /* U+0E38 THAI CHARACTER SARA U */ #define XK_Thai_sarauu 0x0dd9 /* U+0E39 THAI CHARACTER SARA UU */ #define XK_Thai_phinthu 0x0dda /* U+0E3A THAI CHARACTER PHINTHU */ #define XK_Thai_maihanakat_maitho 0x0dde #define XK_Thai_baht 0x0ddf /* U+0E3F THAI CURRENCY SYMBOL BAHT */ #define XK_Thai_sarae 0x0de0 /* U+0E40 THAI CHARACTER SARA E */ #define XK_Thai_saraae 0x0de1 /* U+0E41 THAI CHARACTER SARA AE */ #define XK_Thai_sarao 0x0de2 /* U+0E42 THAI CHARACTER SARA O */ #define XK_Thai_saraaimaimuan 0x0de3 /* U+0E43 THAI CHARACTER SARA AI MAIMUAN */ #define XK_Thai_saraaimaimalai 0x0de4 /* U+0E44 THAI CHARACTER SARA AI MAIMALAI */ #define XK_Thai_lakkhangyao 0x0de5 /* U+0E45 THAI CHARACTER LAKKHANGYAO */ #define XK_Thai_maiyamok 0x0de6 /* U+0E46 THAI CHARACTER MAIYAMOK */ #define XK_Thai_maitaikhu 0x0de7 /* U+0E47 THAI CHARACTER MAITAIKHU */ #define XK_Thai_maiek 0x0de8 /* U+0E48 THAI CHARACTER MAI EK */ #define XK_Thai_maitho 0x0de9 /* U+0E49 THAI CHARACTER MAI THO */ #define XK_Thai_maitri 0x0dea /* U+0E4A THAI CHARACTER MAI TRI */ #define XK_Thai_maichattawa 0x0deb /* U+0E4B THAI CHARACTER MAI CHATTAWA */ #define XK_Thai_thanthakhat 0x0dec /* U+0E4C THAI CHARACTER THANTHAKHAT */ #define XK_Thai_nikhahit 0x0ded /* U+0E4D THAI CHARACTER NIKHAHIT */ #define XK_Thai_leksun 0x0df0 /* U+0E50 THAI DIGIT ZERO */ #define XK_Thai_leknung 0x0df1 /* U+0E51 THAI DIGIT ONE */ #define XK_Thai_leksong 0x0df2 /* U+0E52 THAI DIGIT TWO */ #define XK_Thai_leksam 0x0df3 /* U+0E53 THAI DIGIT THREE */ #define XK_Thai_leksi 0x0df4 /* U+0E54 THAI DIGIT FOUR */ #define XK_Thai_lekha 0x0df5 /* U+0E55 THAI DIGIT FIVE */ #define XK_Thai_lekhok 0x0df6 /* U+0E56 THAI DIGIT SIX */ #define XK_Thai_lekchet 0x0df7 /* U+0E57 THAI DIGIT SEVEN */ #define XK_Thai_lekpaet 0x0df8 /* U+0E58 THAI DIGIT EIGHT */ #define XK_Thai_lekkao 0x0df9 /* U+0E59 THAI DIGIT NINE */ #endif /* XK_THAI */ /* * Korean * Byte 3 = 0x0e */ #ifdef XK_KOREAN #define XK_Hangul 0xff31 /* Hangul start/stop(toggle) */ #define XK_Hangul_Start 0xff32 /* Hangul start */ #define XK_Hangul_End 0xff33 /* Hangul end, English start */ #define XK_Hangul_Hanja 0xff34 /* Start Hangul->Hanja Conversion */ #define XK_Hangul_Jamo 0xff35 /* Hangul Jamo mode */ #define XK_Hangul_Romaja 0xff36 /* Hangul Romaja mode */ #define XK_Hangul_Codeinput 0xff37 /* Hangul code input mode */ #define XK_Hangul_Jeonja 0xff38 /* Jeonja mode */ #define XK_Hangul_Banja 0xff39 /* Banja mode */ #define XK_Hangul_PreHanja 0xff3a /* Pre Hanja conversion */ #define XK_Hangul_PostHanja 0xff3b /* Post Hanja conversion */ #define XK_Hangul_SingleCandidate 0xff3c /* Single candidate */ #define XK_Hangul_MultipleCandidate 0xff3d /* Multiple candidate */ #define XK_Hangul_PreviousCandidate 0xff3e /* Previous candidate */ #define XK_Hangul_Special 0xff3f /* Special symbols */ #define XK_Hangul_switch 0xff7e /* Alias for mode_switch */ /* Hangul Consonant Characters */ #define XK_Hangul_Kiyeog 0x0ea1 #define XK_Hangul_SsangKiyeog 0x0ea2 #define XK_Hangul_KiyeogSios 0x0ea3 #define XK_Hangul_Nieun 0x0ea4 #define XK_Hangul_NieunJieuj 0x0ea5 #define XK_Hangul_NieunHieuh 0x0ea6 #define XK_Hangul_Dikeud 0x0ea7 #define XK_Hangul_SsangDikeud 0x0ea8 #define XK_Hangul_Rieul 0x0ea9 #define XK_Hangul_RieulKiyeog 0x0eaa #define XK_Hangul_RieulMieum 0x0eab #define XK_Hangul_RieulPieub 0x0eac #define XK_Hangul_RieulSios 0x0ead #define XK_Hangul_RieulTieut 0x0eae #define XK_Hangul_RieulPhieuf 0x0eaf #define XK_Hangul_RieulHieuh 0x0eb0 #define XK_Hangul_Mieum 0x0eb1 #define XK_Hangul_Pieub 0x0eb2 #define XK_Hangul_SsangPieub 0x0eb3 #define XK_Hangul_PieubSios 0x0eb4 #define XK_Hangul_Sios 0x0eb5 #define XK_Hangul_SsangSios 0x0eb6 #define XK_Hangul_Ieung 0x0eb7 #define XK_Hangul_Jieuj 0x0eb8 #define XK_Hangul_SsangJieuj 0x0eb9 #define XK_Hangul_Cieuc 0x0eba #define XK_Hangul_Khieuq 0x0ebb #define XK_Hangul_Tieut 0x0ebc #define XK_Hangul_Phieuf 0x0ebd #define XK_Hangul_Hieuh 0x0ebe /* Hangul Vowel Characters */ #define XK_Hangul_A 0x0ebf #define XK_Hangul_AE 0x0ec0 #define XK_Hangul_YA 0x0ec1 #define XK_Hangul_YAE 0x0ec2 #define XK_Hangul_EO 0x0ec3 #define XK_Hangul_E 0x0ec4 #define XK_Hangul_YEO 0x0ec5 #define XK_Hangul_YE 0x0ec6 #define XK_Hangul_O 0x0ec7 #define XK_Hangul_WA 0x0ec8 #define XK_Hangul_WAE 0x0ec9 #define XK_Hangul_OE 0x0eca #define XK_Hangul_YO 0x0ecb #define XK_Hangul_U 0x0ecc #define XK_Hangul_WEO 0x0ecd #define XK_Hangul_WE 0x0ece #define XK_Hangul_WI 0x0ecf #define XK_Hangul_YU 0x0ed0 #define XK_Hangul_EU 0x0ed1 #define XK_Hangul_YI 0x0ed2 #define XK_Hangul_I 0x0ed3 /* Hangul syllable-final (JongSeong) Characters */ #define XK_Hangul_J_Kiyeog 0x0ed4 #define XK_Hangul_J_SsangKiyeog 0x0ed5 #define XK_Hangul_J_KiyeogSios 0x0ed6 #define XK_Hangul_J_Nieun 0x0ed7 #define XK_Hangul_J_NieunJieuj 0x0ed8 #define XK_Hangul_J_NieunHieuh 0x0ed9 #define XK_Hangul_J_Dikeud 0x0eda #define XK_Hangul_J_Rieul 0x0edb #define XK_Hangul_J_RieulKiyeog 0x0edc #define XK_Hangul_J_RieulMieum 0x0edd #define XK_Hangul_J_RieulPieub 0x0ede #define XK_Hangul_J_RieulSios 0x0edf #define XK_Hangul_J_RieulTieut 0x0ee0 #define XK_Hangul_J_RieulPhieuf 0x0ee1 #define XK_Hangul_J_RieulHieuh 0x0ee2 #define XK_Hangul_J_Mieum 0x0ee3 #define XK_Hangul_J_Pieub 0x0ee4 #define XK_Hangul_J_PieubSios 0x0ee5 #define XK_Hangul_J_Sios 0x0ee6 #define XK_Hangul_J_SsangSios 0x0ee7 #define XK_Hangul_J_Ieung 0x0ee8 #define XK_Hangul_J_Jieuj 0x0ee9 #define XK_Hangul_J_Cieuc 0x0eea #define XK_Hangul_J_Khieuq 0x0eeb #define XK_Hangul_J_Tieut 0x0eec #define XK_Hangul_J_Phieuf 0x0eed #define XK_Hangul_J_Hieuh 0x0eee /* Ancient Hangul Consonant Characters */ #define XK_Hangul_RieulYeorinHieuh 0x0eef #define XK_Hangul_SunkyeongeumMieum 0x0ef0 #define XK_Hangul_SunkyeongeumPieub 0x0ef1 #define XK_Hangul_PanSios 0x0ef2 #define XK_Hangul_KkogjiDalrinIeung 0x0ef3 #define XK_Hangul_SunkyeongeumPhieuf 0x0ef4 #define XK_Hangul_YeorinHieuh 0x0ef5 /* Ancient Hangul Vowel Characters */ #define XK_Hangul_AraeA 0x0ef6 #define XK_Hangul_AraeAE 0x0ef7 /* Ancient Hangul syllable-final (JongSeong) Characters */ #define XK_Hangul_J_PanSios 0x0ef8 #define XK_Hangul_J_KkogjiDalrinIeung 0x0ef9 #define XK_Hangul_J_YeorinHieuh 0x0efa /* Korean currency symbol */ #define XK_Korean_Won 0x0eff /*(U+20A9 WON SIGN)*/ #endif /* XK_KOREAN */ /* * Armenian */ #ifdef XK_ARMENIAN #define XK_Armenian_ligature_ew 0x1000587 /* U+0587 ARMENIAN SMALL LIGATURE ECH YIWN */ #define XK_Armenian_full_stop 0x1000589 /* U+0589 ARMENIAN FULL STOP */ #define XK_Armenian_verjaket 0x1000589 /* U+0589 ARMENIAN FULL STOP */ #define XK_Armenian_separation_mark 0x100055d /* U+055D ARMENIAN COMMA */ #define XK_Armenian_but 0x100055d /* U+055D ARMENIAN COMMA */ #define XK_Armenian_hyphen 0x100058a /* U+058A ARMENIAN HYPHEN */ #define XK_Armenian_yentamna 0x100058a /* U+058A ARMENIAN HYPHEN */ #define XK_Armenian_exclam 0x100055c /* U+055C ARMENIAN EXCLAMATION MARK */ #define XK_Armenian_amanak 0x100055c /* U+055C ARMENIAN EXCLAMATION MARK */ #define XK_Armenian_accent 0x100055b /* U+055B ARMENIAN EMPHASIS MARK */ #define XK_Armenian_shesht 0x100055b /* U+055B ARMENIAN EMPHASIS MARK */ #define XK_Armenian_question 0x100055e /* U+055E ARMENIAN QUESTION MARK */ #define XK_Armenian_paruyk 0x100055e /* U+055E ARMENIAN QUESTION MARK */ #define XK_Armenian_AYB 0x1000531 /* U+0531 ARMENIAN CAPITAL LETTER AYB */ #define XK_Armenian_ayb 0x1000561 /* U+0561 ARMENIAN SMALL LETTER AYB */ #define XK_Armenian_BEN 0x1000532 /* U+0532 ARMENIAN CAPITAL LETTER BEN */ #define XK_Armenian_ben 0x1000562 /* U+0562 ARMENIAN SMALL LETTER BEN */ #define XK_Armenian_GIM 0x1000533 /* U+0533 ARMENIAN CAPITAL LETTER GIM */ #define XK_Armenian_gim 0x1000563 /* U+0563 ARMENIAN SMALL LETTER GIM */ #define XK_Armenian_DA 0x1000534 /* U+0534 ARMENIAN CAPITAL LETTER DA */ #define XK_Armenian_da 0x1000564 /* U+0564 ARMENIAN SMALL LETTER DA */ #define XK_Armenian_YECH 0x1000535 /* U+0535 ARMENIAN CAPITAL LETTER ECH */ #define XK_Armenian_yech 0x1000565 /* U+0565 ARMENIAN SMALL LETTER ECH */ #define XK_Armenian_ZA 0x1000536 /* U+0536 ARMENIAN CAPITAL LETTER ZA */ #define XK_Armenian_za 0x1000566 /* U+0566 ARMENIAN SMALL LETTER ZA */ #define XK_Armenian_E 0x1000537 /* U+0537 ARMENIAN CAPITAL LETTER EH */ #define XK_Armenian_e 0x1000567 /* U+0567 ARMENIAN SMALL LETTER EH */ #define XK_Armenian_AT 0x1000538 /* U+0538 ARMENIAN CAPITAL LETTER ET */ #define XK_Armenian_at 0x1000568 /* U+0568 ARMENIAN SMALL LETTER ET */ #define XK_Armenian_TO 0x1000539 /* U+0539 ARMENIAN CAPITAL LETTER TO */ #define XK_Armenian_to 0x1000569 /* U+0569 ARMENIAN SMALL LETTER TO */ #define XK_Armenian_ZHE 0x100053a /* U+053A ARMENIAN CAPITAL LETTER ZHE */ #define XK_Armenian_zhe 0x100056a /* U+056A ARMENIAN SMALL LETTER ZHE */ #define XK_Armenian_INI 0x100053b /* U+053B ARMENIAN CAPITAL LETTER INI */ #define XK_Armenian_ini 0x100056b /* U+056B ARMENIAN SMALL LETTER INI */ #define XK_Armenian_LYUN 0x100053c /* U+053C ARMENIAN CAPITAL LETTER LIWN */ #define XK_Armenian_lyun 0x100056c /* U+056C ARMENIAN SMALL LETTER LIWN */ #define XK_Armenian_KHE 0x100053d /* U+053D ARMENIAN CAPITAL LETTER XEH */ #define XK_Armenian_khe 0x100056d /* U+056D ARMENIAN SMALL LETTER XEH */ #define XK_Armenian_TSA 0x100053e /* U+053E ARMENIAN CAPITAL LETTER CA */ #define XK_Armenian_tsa 0x100056e /* U+056E ARMENIAN SMALL LETTER CA */ #define XK_Armenian_KEN 0x100053f /* U+053F ARMENIAN CAPITAL LETTER KEN */ #define XK_Armenian_ken 0x100056f /* U+056F ARMENIAN SMALL LETTER KEN */ #define XK_Armenian_HO 0x1000540 /* U+0540 ARMENIAN CAPITAL LETTER HO */ #define XK_Armenian_ho 0x1000570 /* U+0570 ARMENIAN SMALL LETTER HO */ #define XK_Armenian_DZA 0x1000541 /* U+0541 ARMENIAN CAPITAL LETTER JA */ #define XK_Armenian_dza 0x1000571 /* U+0571 ARMENIAN SMALL LETTER JA */ #define XK_Armenian_GHAT 0x1000542 /* U+0542 ARMENIAN CAPITAL LETTER GHAD */ #define XK_Armenian_ghat 0x1000572 /* U+0572 ARMENIAN SMALL LETTER GHAD */ #define XK_Armenian_TCHE 0x1000543 /* U+0543 ARMENIAN CAPITAL LETTER CHEH */ #define XK_Armenian_tche 0x1000573 /* U+0573 ARMENIAN SMALL LETTER CHEH */ #define XK_Armenian_MEN 0x1000544 /* U+0544 ARMENIAN CAPITAL LETTER MEN */ #define XK_Armenian_men 0x1000574 /* U+0574 ARMENIAN SMALL LETTER MEN */ #define XK_Armenian_HI 0x1000545 /* U+0545 ARMENIAN CAPITAL LETTER YI */ #define XK_Armenian_hi 0x1000575 /* U+0575 ARMENIAN SMALL LETTER YI */ #define XK_Armenian_NU 0x1000546 /* U+0546 ARMENIAN CAPITAL LETTER NOW */ #define XK_Armenian_nu 0x1000576 /* U+0576 ARMENIAN SMALL LETTER NOW */ #define XK_Armenian_SHA 0x1000547 /* U+0547 ARMENIAN CAPITAL LETTER SHA */ #define XK_Armenian_sha 0x1000577 /* U+0577 ARMENIAN SMALL LETTER SHA */ #define XK_Armenian_VO 0x1000548 /* U+0548 ARMENIAN CAPITAL LETTER VO */ #define XK_Armenian_vo 0x1000578 /* U+0578 ARMENIAN SMALL LETTER VO */ #define XK_Armenian_CHA 0x1000549 /* U+0549 ARMENIAN CAPITAL LETTER CHA */ #define XK_Armenian_cha 0x1000579 /* U+0579 ARMENIAN SMALL LETTER CHA */ #define XK_Armenian_PE 0x100054a /* U+054A ARMENIAN CAPITAL LETTER PEH */ #define XK_Armenian_pe 0x100057a /* U+057A ARMENIAN SMALL LETTER PEH */ #define XK_Armenian_JE 0x100054b /* U+054B ARMENIAN CAPITAL LETTER JHEH */ #define XK_Armenian_je 0x100057b /* U+057B ARMENIAN SMALL LETTER JHEH */ #define XK_Armenian_RA 0x100054c /* U+054C ARMENIAN CAPITAL LETTER RA */ #define XK_Armenian_ra 0x100057c /* U+057C ARMENIAN SMALL LETTER RA */ #define XK_Armenian_SE 0x100054d /* U+054D ARMENIAN CAPITAL LETTER SEH */ #define XK_Armenian_se 0x100057d /* U+057D ARMENIAN SMALL LETTER SEH */ #define XK_Armenian_VEV 0x100054e /* U+054E ARMENIAN CAPITAL LETTER VEW */ #define XK_Armenian_vev 0x100057e /* U+057E ARMENIAN SMALL LETTER VEW */ #define XK_Armenian_TYUN 0x100054f /* U+054F ARMENIAN CAPITAL LETTER TIWN */ #define XK_Armenian_tyun 0x100057f /* U+057F ARMENIAN SMALL LETTER TIWN */ #define XK_Armenian_RE 0x1000550 /* U+0550 ARMENIAN CAPITAL LETTER REH */ #define XK_Armenian_re 0x1000580 /* U+0580 ARMENIAN SMALL LETTER REH */ #define XK_Armenian_TSO 0x1000551 /* U+0551 ARMENIAN CAPITAL LETTER CO */ #define XK_Armenian_tso 0x1000581 /* U+0581 ARMENIAN SMALL LETTER CO */ #define XK_Armenian_VYUN 0x1000552 /* U+0552 ARMENIAN CAPITAL LETTER YIWN */ #define XK_Armenian_vyun 0x1000582 /* U+0582 ARMENIAN SMALL LETTER YIWN */ #define XK_Armenian_PYUR 0x1000553 /* U+0553 ARMENIAN CAPITAL LETTER PIWR */ #define XK_Armenian_pyur 0x1000583 /* U+0583 ARMENIAN SMALL LETTER PIWR */ #define XK_Armenian_KE 0x1000554 /* U+0554 ARMENIAN CAPITAL LETTER KEH */ #define XK_Armenian_ke 0x1000584 /* U+0584 ARMENIAN SMALL LETTER KEH */ #define XK_Armenian_O 0x1000555 /* U+0555 ARMENIAN CAPITAL LETTER OH */ #define XK_Armenian_o 0x1000585 /* U+0585 ARMENIAN SMALL LETTER OH */ #define XK_Armenian_FE 0x1000556 /* U+0556 ARMENIAN CAPITAL LETTER FEH */ #define XK_Armenian_fe 0x1000586 /* U+0586 ARMENIAN SMALL LETTER FEH */ #define XK_Armenian_apostrophe 0x100055a /* U+055A ARMENIAN APOSTROPHE */ #endif /* XK_ARMENIAN */ /* * Georgian */ #ifdef XK_GEORGIAN #define XK_Georgian_an 0x10010d0 /* U+10D0 GEORGIAN LETTER AN */ #define XK_Georgian_ban 0x10010d1 /* U+10D1 GEORGIAN LETTER BAN */ #define XK_Georgian_gan 0x10010d2 /* U+10D2 GEORGIAN LETTER GAN */ #define XK_Georgian_don 0x10010d3 /* U+10D3 GEORGIAN LETTER DON */ #define XK_Georgian_en 0x10010d4 /* U+10D4 GEORGIAN LETTER EN */ #define XK_Georgian_vin 0x10010d5 /* U+10D5 GEORGIAN LETTER VIN */ #define XK_Georgian_zen 0x10010d6 /* U+10D6 GEORGIAN LETTER ZEN */ #define XK_Georgian_tan 0x10010d7 /* U+10D7 GEORGIAN LETTER TAN */ #define XK_Georgian_in 0x10010d8 /* U+10D8 GEORGIAN LETTER IN */ #define XK_Georgian_kan 0x10010d9 /* U+10D9 GEORGIAN LETTER KAN */ #define XK_Georgian_las 0x10010da /* U+10DA GEORGIAN LETTER LAS */ #define XK_Georgian_man 0x10010db /* U+10DB GEORGIAN LETTER MAN */ #define XK_Georgian_nar 0x10010dc /* U+10DC GEORGIAN LETTER NAR */ #define XK_Georgian_on 0x10010dd /* U+10DD GEORGIAN LETTER ON */ #define XK_Georgian_par 0x10010de /* U+10DE GEORGIAN LETTER PAR */ #define XK_Georgian_zhar 0x10010df /* U+10DF GEORGIAN LETTER ZHAR */ #define XK_Georgian_rae 0x10010e0 /* U+10E0 GEORGIAN LETTER RAE */ #define XK_Georgian_san 0x10010e1 /* U+10E1 GEORGIAN LETTER SAN */ #define XK_Georgian_tar 0x10010e2 /* U+10E2 GEORGIAN LETTER TAR */ #define XK_Georgian_un 0x10010e3 /* U+10E3 GEORGIAN LETTER UN */ #define XK_Georgian_phar 0x10010e4 /* U+10E4 GEORGIAN LETTER PHAR */ #define XK_Georgian_khar 0x10010e5 /* U+10E5 GEORGIAN LETTER KHAR */ #define XK_Georgian_ghan 0x10010e6 /* U+10E6 GEORGIAN LETTER GHAN */ #define XK_Georgian_qar 0x10010e7 /* U+10E7 GEORGIAN LETTER QAR */ #define XK_Georgian_shin 0x10010e8 /* U+10E8 GEORGIAN LETTER SHIN */ #define XK_Georgian_chin 0x10010e9 /* U+10E9 GEORGIAN LETTER CHIN */ #define XK_Georgian_can 0x10010ea /* U+10EA GEORGIAN LETTER CAN */ #define XK_Georgian_jil 0x10010eb /* U+10EB GEORGIAN LETTER JIL */ #define XK_Georgian_cil 0x10010ec /* U+10EC GEORGIAN LETTER CIL */ #define XK_Georgian_char 0x10010ed /* U+10ED GEORGIAN LETTER CHAR */ #define XK_Georgian_xan 0x10010ee /* U+10EE GEORGIAN LETTER XAN */ #define XK_Georgian_jhan 0x10010ef /* U+10EF GEORGIAN LETTER JHAN */ #define XK_Georgian_hae 0x10010f0 /* U+10F0 GEORGIAN LETTER HAE */ #define XK_Georgian_he 0x10010f1 /* U+10F1 GEORGIAN LETTER HE */ #define XK_Georgian_hie 0x10010f2 /* U+10F2 GEORGIAN LETTER HIE */ #define XK_Georgian_we 0x10010f3 /* U+10F3 GEORGIAN LETTER WE */ #define XK_Georgian_har 0x10010f4 /* U+10F4 GEORGIAN LETTER HAR */ #define XK_Georgian_hoe 0x10010f5 /* U+10F5 GEORGIAN LETTER HOE */ #define XK_Georgian_fi 0x10010f6 /* U+10F6 GEORGIAN LETTER FI */ #endif /* XK_GEORGIAN */ /* * Azeri (and other Turkic or Caucasian languages) */ #ifdef XK_CAUCASUS /* latin */ #define XK_Xabovedot 0x1001e8a /* U+1E8A LATIN CAPITAL LETTER X WITH DOT ABOVE */ #define XK_Ibreve 0x100012c /* U+012C LATIN CAPITAL LETTER I WITH BREVE */ #define XK_Zstroke 0x10001b5 /* U+01B5 LATIN CAPITAL LETTER Z WITH STROKE */ #define XK_Gcaron 0x10001e6 /* U+01E6 LATIN CAPITAL LETTER G WITH CARON */ #define XK_Ocaron 0x10001d1 /* U+01D1 LATIN CAPITAL LETTER O WITH CARON */ #define XK_Obarred 0x100019f /* U+019F LATIN CAPITAL LETTER O WITH MIDDLE TILDE */ #define XK_xabovedot 0x1001e8b /* U+1E8B LATIN SMALL LETTER X WITH DOT ABOVE */ #define XK_ibreve 0x100012d /* U+012D LATIN SMALL LETTER I WITH BREVE */ #define XK_zstroke 0x10001b6 /* U+01B6 LATIN SMALL LETTER Z WITH STROKE */ #define XK_gcaron 0x10001e7 /* U+01E7 LATIN SMALL LETTER G WITH CARON */ #define XK_ocaron 0x10001d2 /* U+01D2 LATIN SMALL LETTER O WITH CARON */ #define XK_obarred 0x1000275 /* U+0275 LATIN SMALL LETTER BARRED O */ #define XK_SCHWA 0x100018f /* U+018F LATIN CAPITAL LETTER SCHWA */ #define XK_schwa 0x1000259 /* U+0259 LATIN SMALL LETTER SCHWA */ #define XK_EZH 0x10001b7 /* U+01B7 LATIN CAPITAL LETTER EZH */ #define XK_ezh 0x1000292 /* U+0292 LATIN SMALL LETTER EZH */ /* those are not really Caucasus */ /* For Inupiak */ #define XK_Lbelowdot 0x1001e36 /* U+1E36 LATIN CAPITAL LETTER L WITH DOT BELOW */ #define XK_lbelowdot 0x1001e37 /* U+1E37 LATIN SMALL LETTER L WITH DOT BELOW */ #endif /* XK_CAUCASUS */ /* * Vietnamese */ #ifdef XK_VIETNAMESE #define XK_Abelowdot 0x1001ea0 /* U+1EA0 LATIN CAPITAL LETTER A WITH DOT BELOW */ #define XK_abelowdot 0x1001ea1 /* U+1EA1 LATIN SMALL LETTER A WITH DOT BELOW */ #define XK_Ahook 0x1001ea2 /* U+1EA2 LATIN CAPITAL LETTER A WITH HOOK ABOVE */ #define XK_ahook 0x1001ea3 /* U+1EA3 LATIN SMALL LETTER A WITH HOOK ABOVE */ #define XK_Acircumflexacute 0x1001ea4 /* U+1EA4 LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE */ #define XK_acircumflexacute 0x1001ea5 /* U+1EA5 LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE */ #define XK_Acircumflexgrave 0x1001ea6 /* U+1EA6 LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE */ #define XK_acircumflexgrave 0x1001ea7 /* U+1EA7 LATIN SMALL LETTER A WITH CIRCUMFLEX AND GRAVE */ #define XK_Acircumflexhook 0x1001ea8 /* U+1EA8 LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE */ #define XK_acircumflexhook 0x1001ea9 /* U+1EA9 LATIN SMALL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE */ #define XK_Acircumflextilde 0x1001eaa /* U+1EAA LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE */ #define XK_acircumflextilde 0x1001eab /* U+1EAB LATIN SMALL LETTER A WITH CIRCUMFLEX AND TILDE */ #define XK_Acircumflexbelowdot 0x1001eac /* U+1EAC LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW */ #define XK_acircumflexbelowdot 0x1001ead /* U+1EAD LATIN SMALL LETTER A WITH CIRCUMFLEX AND DOT BELOW */ #define XK_Abreveacute 0x1001eae /* U+1EAE LATIN CAPITAL LETTER A WITH BREVE AND ACUTE */ #define XK_abreveacute 0x1001eaf /* U+1EAF LATIN SMALL LETTER A WITH BREVE AND ACUTE */ #define XK_Abrevegrave 0x1001eb0 /* U+1EB0 LATIN CAPITAL LETTER A WITH BREVE AND GRAVE */ #define XK_abrevegrave 0x1001eb1 /* U+1EB1 LATIN SMALL LETTER A WITH BREVE AND GRAVE */ #define XK_Abrevehook 0x1001eb2 /* U+1EB2 LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE */ #define XK_abrevehook 0x1001eb3 /* U+1EB3 LATIN SMALL LETTER A WITH BREVE AND HOOK ABOVE */ #define XK_Abrevetilde 0x1001eb4 /* U+1EB4 LATIN CAPITAL LETTER A WITH BREVE AND TILDE */ #define XK_abrevetilde 0x1001eb5 /* U+1EB5 LATIN SMALL LETTER A WITH BREVE AND TILDE */ #define XK_Abrevebelowdot 0x1001eb6 /* U+1EB6 LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW */ #define XK_abrevebelowdot 0x1001eb7 /* U+1EB7 LATIN SMALL LETTER A WITH BREVE AND DOT BELOW */ #define XK_Ebelowdot 0x1001eb8 /* U+1EB8 LATIN CAPITAL LETTER E WITH DOT BELOW */ #define XK_ebelowdot 0x1001eb9 /* U+1EB9 LATIN SMALL LETTER E WITH DOT BELOW */ #define XK_Ehook 0x1001eba /* U+1EBA LATIN CAPITAL LETTER E WITH HOOK ABOVE */ #define XK_ehook 0x1001ebb /* U+1EBB LATIN SMALL LETTER E WITH HOOK ABOVE */ #define XK_Etilde 0x1001ebc /* U+1EBC LATIN CAPITAL LETTER E WITH TILDE */ #define XK_etilde 0x1001ebd /* U+1EBD LATIN SMALL LETTER E WITH TILDE */ #define XK_Ecircumflexacute 0x1001ebe /* U+1EBE LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE */ #define XK_ecircumflexacute 0x1001ebf /* U+1EBF LATIN SMALL LETTER E WITH CIRCUMFLEX AND ACUTE */ #define XK_Ecircumflexgrave 0x1001ec0 /* U+1EC0 LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE */ #define XK_ecircumflexgrave 0x1001ec1 /* U+1EC1 LATIN SMALL LETTER E WITH CIRCUMFLEX AND GRAVE */ #define XK_Ecircumflexhook 0x1001ec2 /* U+1EC2 LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE */ #define XK_ecircumflexhook 0x1001ec3 /* U+1EC3 LATIN SMALL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE */ #define XK_Ecircumflextilde 0x1001ec4 /* U+1EC4 LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE */ #define XK_ecircumflextilde 0x1001ec5 /* U+1EC5 LATIN SMALL LETTER E WITH CIRCUMFLEX AND TILDE */ #define XK_Ecircumflexbelowdot 0x1001ec6 /* U+1EC6 LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW */ #define XK_ecircumflexbelowdot 0x1001ec7 /* U+1EC7 LATIN SMALL LETTER E WITH CIRCUMFLEX AND DOT BELOW */ #define XK_Ihook 0x1001ec8 /* U+1EC8 LATIN CAPITAL LETTER I WITH HOOK ABOVE */ #define XK_ihook 0x1001ec9 /* U+1EC9 LATIN SMALL LETTER I WITH HOOK ABOVE */ #define XK_Ibelowdot 0x1001eca /* U+1ECA LATIN CAPITAL LETTER I WITH DOT BELOW */ #define XK_ibelowdot 0x1001ecb /* U+1ECB LATIN SMALL LETTER I WITH DOT BELOW */ #define XK_Obelowdot 0x1001ecc /* U+1ECC LATIN CAPITAL LETTER O WITH DOT BELOW */ #define XK_obelowdot 0x1001ecd /* U+1ECD LATIN SMALL LETTER O WITH DOT BELOW */ #define XK_Ohook 0x1001ece /* U+1ECE LATIN CAPITAL LETTER O WITH HOOK ABOVE */ #define XK_ohook 0x1001ecf /* U+1ECF LATIN SMALL LETTER O WITH HOOK ABOVE */ #define XK_Ocircumflexacute 0x1001ed0 /* U+1ED0 LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE */ #define XK_ocircumflexacute 0x1001ed1 /* U+1ED1 LATIN SMALL LETTER O WITH CIRCUMFLEX AND ACUTE */ #define XK_Ocircumflexgrave 0x1001ed2 /* U+1ED2 LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE */ #define XK_ocircumflexgrave 0x1001ed3 /* U+1ED3 LATIN SMALL LETTER O WITH CIRCUMFLEX AND GRAVE */ #define XK_Ocircumflexhook 0x1001ed4 /* U+1ED4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE */ #define XK_ocircumflexhook 0x1001ed5 /* U+1ED5 LATIN SMALL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE */ #define XK_Ocircumflextilde 0x1001ed6 /* U+1ED6 LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE */ #define XK_ocircumflextilde 0x1001ed7 /* U+1ED7 LATIN SMALL LETTER O WITH CIRCUMFLEX AND TILDE */ #define XK_Ocircumflexbelowdot 0x1001ed8 /* U+1ED8 LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW */ #define XK_ocircumflexbelowdot 0x1001ed9 /* U+1ED9 LATIN SMALL LETTER O WITH CIRCUMFLEX AND DOT BELOW */ #define XK_Ohornacute 0x1001eda /* U+1EDA LATIN CAPITAL LETTER O WITH HORN AND ACUTE */ #define XK_ohornacute 0x1001edb /* U+1EDB LATIN SMALL LETTER O WITH HORN AND ACUTE */ #define XK_Ohorngrave 0x1001edc /* U+1EDC LATIN CAPITAL LETTER O WITH HORN AND GRAVE */ #define XK_ohorngrave 0x1001edd /* U+1EDD LATIN SMALL LETTER O WITH HORN AND GRAVE */ #define XK_Ohornhook 0x1001ede /* U+1EDE LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE */ #define XK_ohornhook 0x1001edf /* U+1EDF LATIN SMALL LETTER O WITH HORN AND HOOK ABOVE */ #define XK_Ohorntilde 0x1001ee0 /* U+1EE0 LATIN CAPITAL LETTER O WITH HORN AND TILDE */ #define XK_ohorntilde 0x1001ee1 /* U+1EE1 LATIN SMALL LETTER O WITH HORN AND TILDE */ #define XK_Ohornbelowdot 0x1001ee2 /* U+1EE2 LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW */ #define XK_ohornbelowdot 0x1001ee3 /* U+1EE3 LATIN SMALL LETTER O WITH HORN AND DOT BELOW */ #define XK_Ubelowdot 0x1001ee4 /* U+1EE4 LATIN CAPITAL LETTER U WITH DOT BELOW */ #define XK_ubelowdot 0x1001ee5 /* U+1EE5 LATIN SMALL LETTER U WITH DOT BELOW */ #define XK_Uhook 0x1001ee6 /* U+1EE6 LATIN CAPITAL LETTER U WITH HOOK ABOVE */ #define XK_uhook 0x1001ee7 /* U+1EE7 LATIN SMALL LETTER U WITH HOOK ABOVE */ #define XK_Uhornacute 0x1001ee8 /* U+1EE8 LATIN CAPITAL LETTER U WITH HORN AND ACUTE */ #define XK_uhornacute 0x1001ee9 /* U+1EE9 LATIN SMALL LETTER U WITH HORN AND ACUTE */ #define XK_Uhorngrave 0x1001eea /* U+1EEA LATIN CAPITAL LETTER U WITH HORN AND GRAVE */ #define XK_uhorngrave 0x1001eeb /* U+1EEB LATIN SMALL LETTER U WITH HORN AND GRAVE */ #define XK_Uhornhook 0x1001eec /* U+1EEC LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE */ #define XK_uhornhook 0x1001eed /* U+1EED LATIN SMALL LETTER U WITH HORN AND HOOK ABOVE */ #define XK_Uhorntilde 0x1001eee /* U+1EEE LATIN CAPITAL LETTER U WITH HORN AND TILDE */ #define XK_uhorntilde 0x1001eef /* U+1EEF LATIN SMALL LETTER U WITH HORN AND TILDE */ #define XK_Uhornbelowdot 0x1001ef0 /* U+1EF0 LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW */ #define XK_uhornbelowdot 0x1001ef1 /* U+1EF1 LATIN SMALL LETTER U WITH HORN AND DOT BELOW */ #define XK_Ybelowdot 0x1001ef4 /* U+1EF4 LATIN CAPITAL LETTER Y WITH DOT BELOW */ #define XK_ybelowdot 0x1001ef5 /* U+1EF5 LATIN SMALL LETTER Y WITH DOT BELOW */ #define XK_Yhook 0x1001ef6 /* U+1EF6 LATIN CAPITAL LETTER Y WITH HOOK ABOVE */ #define XK_yhook 0x1001ef7 /* U+1EF7 LATIN SMALL LETTER Y WITH HOOK ABOVE */ #define XK_Ytilde 0x1001ef8 /* U+1EF8 LATIN CAPITAL LETTER Y WITH TILDE */ #define XK_ytilde 0x1001ef9 /* U+1EF9 LATIN SMALL LETTER Y WITH TILDE */ #define XK_Ohorn 0x10001a0 /* U+01A0 LATIN CAPITAL LETTER O WITH HORN */ #define XK_ohorn 0x10001a1 /* U+01A1 LATIN SMALL LETTER O WITH HORN */ #define XK_Uhorn 0x10001af /* U+01AF LATIN CAPITAL LETTER U WITH HORN */ #define XK_uhorn 0x10001b0 /* U+01B0 LATIN SMALL LETTER U WITH HORN */ #endif /* XK_VIETNAMESE */ #ifdef XK_CURRENCY #define XK_EcuSign 0x10020a0 /* U+20A0 EURO-CURRENCY SIGN */ #define XK_ColonSign 0x10020a1 /* U+20A1 COLON SIGN */ #define XK_CruzeiroSign 0x10020a2 /* U+20A2 CRUZEIRO SIGN */ #define XK_FFrancSign 0x10020a3 /* U+20A3 FRENCH FRANC SIGN */ #define XK_LiraSign 0x10020a4 /* U+20A4 LIRA SIGN */ #define XK_MillSign 0x10020a5 /* U+20A5 MILL SIGN */ #define XK_NairaSign 0x10020a6 /* U+20A6 NAIRA SIGN */ #define XK_PesetaSign 0x10020a7 /* U+20A7 PESETA SIGN */ #define XK_RupeeSign 0x10020a8 /* U+20A8 RUPEE SIGN */ #define XK_WonSign 0x10020a9 /* U+20A9 WON SIGN */ #define XK_NewSheqelSign 0x10020aa /* U+20AA NEW SHEQEL SIGN */ #define XK_DongSign 0x10020ab /* U+20AB DONG SIGN */ #define XK_EuroSign 0x20ac /* U+20AC EURO SIGN */ #endif /* XK_CURRENCY */ #ifdef XK_MATHEMATICAL /* one, two and three are defined above. */ #define XK_zerosuperior 0x1002070 /* U+2070 SUPERSCRIPT ZERO */ #define XK_foursuperior 0x1002074 /* U+2074 SUPERSCRIPT FOUR */ #define XK_fivesuperior 0x1002075 /* U+2075 SUPERSCRIPT FIVE */ #define XK_sixsuperior 0x1002076 /* U+2076 SUPERSCRIPT SIX */ #define XK_sevensuperior 0x1002077 /* U+2077 SUPERSCRIPT SEVEN */ #define XK_eightsuperior 0x1002078 /* U+2078 SUPERSCRIPT EIGHT */ #define XK_ninesuperior 0x1002079 /* U+2079 SUPERSCRIPT NINE */ #define XK_zerosubscript 0x1002080 /* U+2080 SUBSCRIPT ZERO */ #define XK_onesubscript 0x1002081 /* U+2081 SUBSCRIPT ONE */ #define XK_twosubscript 0x1002082 /* U+2082 SUBSCRIPT TWO */ #define XK_threesubscript 0x1002083 /* U+2083 SUBSCRIPT THREE */ #define XK_foursubscript 0x1002084 /* U+2084 SUBSCRIPT FOUR */ #define XK_fivesubscript 0x1002085 /* U+2085 SUBSCRIPT FIVE */ #define XK_sixsubscript 0x1002086 /* U+2086 SUBSCRIPT SIX */ #define XK_sevensubscript 0x1002087 /* U+2087 SUBSCRIPT SEVEN */ #define XK_eightsubscript 0x1002088 /* U+2088 SUBSCRIPT EIGHT */ #define XK_ninesubscript 0x1002089 /* U+2089 SUBSCRIPT NINE */ #define XK_partdifferential 0x1002202 /* U+2202 PARTIAL DIFFERENTIAL */ #define XK_emptyset 0x1002205 /* U+2205 NULL SET */ #define XK_elementof 0x1002208 /* U+2208 ELEMENT OF */ #define XK_notelementof 0x1002209 /* U+2209 NOT AN ELEMENT OF */ #define XK_containsas 0x100220B /* U+220B CONTAINS AS MEMBER */ #define XK_squareroot 0x100221A /* U+221A SQUARE ROOT */ #define XK_cuberoot 0x100221B /* U+221B CUBE ROOT */ #define XK_fourthroot 0x100221C /* U+221C FOURTH ROOT */ #define XK_dintegral 0x100222C /* U+222C DOUBLE INTEGRAL */ #define XK_tintegral 0x100222D /* U+222D TRIPLE INTEGRAL */ #define XK_because 0x1002235 /* U+2235 BECAUSE */ #define XK_approxeq 0x1002248 /* U+2245 ALMOST EQUAL TO */ #define XK_notapproxeq 0x1002247 /* U+2247 NOT ALMOST EQUAL TO */ #define XK_notidentical 0x1002262 /* U+2262 NOT IDENTICAL TO */ #define XK_stricteq 0x1002263 /* U+2263 STRICTLY EQUIVALENT TO */ #endif /* XK_MATHEMATICAL */ #ifdef XK_BRAILLE #define XK_braille_dot_1 0xfff1 #define XK_braille_dot_2 0xfff2 #define XK_braille_dot_3 0xfff3 #define XK_braille_dot_4 0xfff4 #define XK_braille_dot_5 0xfff5 #define XK_braille_dot_6 0xfff6 #define XK_braille_dot_7 0xfff7 #define XK_braille_dot_8 0xfff8 #define XK_braille_dot_9 0xfff9 #define XK_braille_dot_10 0xfffa #define XK_braille_blank 0x1002800 /* U+2800 BRAILLE PATTERN BLANK */ #define XK_braille_dots_1 0x1002801 /* U+2801 BRAILLE PATTERN DOTS-1 */ #define XK_braille_dots_2 0x1002802 /* U+2802 BRAILLE PATTERN DOTS-2 */ #define XK_braille_dots_12 0x1002803 /* U+2803 BRAILLE PATTERN DOTS-12 */ #define XK_braille_dots_3 0x1002804 /* U+2804 BRAILLE PATTERN DOTS-3 */ #define XK_braille_dots_13 0x1002805 /* U+2805 BRAILLE PATTERN DOTS-13 */ #define XK_braille_dots_23 0x1002806 /* U+2806 BRAILLE PATTERN DOTS-23 */ #define XK_braille_dots_123 0x1002807 /* U+2807 BRAILLE PATTERN DOTS-123 */ #define XK_braille_dots_4 0x1002808 /* U+2808 BRAILLE PATTERN DOTS-4 */ #define XK_braille_dots_14 0x1002809 /* U+2809 BRAILLE PATTERN DOTS-14 */ #define XK_braille_dots_24 0x100280a /* U+280a BRAILLE PATTERN DOTS-24 */ #define XK_braille_dots_124 0x100280b /* U+280b BRAILLE PATTERN DOTS-124 */ #define XK_braille_dots_34 0x100280c /* U+280c BRAILLE PATTERN DOTS-34 */ #define XK_braille_dots_134 0x100280d /* U+280d BRAILLE PATTERN DOTS-134 */ #define XK_braille_dots_234 0x100280e /* U+280e BRAILLE PATTERN DOTS-234 */ #define XK_braille_dots_1234 0x100280f /* U+280f BRAILLE PATTERN DOTS-1234 */ #define XK_braille_dots_5 0x1002810 /* U+2810 BRAILLE PATTERN DOTS-5 */ #define XK_braille_dots_15 0x1002811 /* U+2811 BRAILLE PATTERN DOTS-15 */ #define XK_braille_dots_25 0x1002812 /* U+2812 BRAILLE PATTERN DOTS-25 */ #define XK_braille_dots_125 0x1002813 /* U+2813 BRAILLE PATTERN DOTS-125 */ #define XK_braille_dots_35 0x1002814 /* U+2814 BRAILLE PATTERN DOTS-35 */ #define XK_braille_dots_135 0x1002815 /* U+2815 BRAILLE PATTERN DOTS-135 */ #define XK_braille_dots_235 0x1002816 /* U+2816 BRAILLE PATTERN DOTS-235 */ #define XK_braille_dots_1235 0x1002817 /* U+2817 BRAILLE PATTERN DOTS-1235 */ #define XK_braille_dots_45 0x1002818 /* U+2818 BRAILLE PATTERN DOTS-45 */ #define XK_braille_dots_145 0x1002819 /* U+2819 BRAILLE PATTERN DOTS-145 */ #define XK_braille_dots_245 0x100281a /* U+281a BRAILLE PATTERN DOTS-245 */ #define XK_braille_dots_1245 0x100281b /* U+281b BRAILLE PATTERN DOTS-1245 */ #define XK_braille_dots_345 0x100281c /* U+281c BRAILLE PATTERN DOTS-345 */ #define XK_braille_dots_1345 0x100281d /* U+281d BRAILLE PATTERN DOTS-1345 */ #define XK_braille_dots_2345 0x100281e /* U+281e BRAILLE PATTERN DOTS-2345 */ #define XK_braille_dots_12345 0x100281f /* U+281f BRAILLE PATTERN DOTS-12345 */ #define XK_braille_dots_6 0x1002820 /* U+2820 BRAILLE PATTERN DOTS-6 */ #define XK_braille_dots_16 0x1002821 /* U+2821 BRAILLE PATTERN DOTS-16 */ #define XK_braille_dots_26 0x1002822 /* U+2822 BRAILLE PATTERN DOTS-26 */ #define XK_braille_dots_126 0x1002823 /* U+2823 BRAILLE PATTERN DOTS-126 */ #define XK_braille_dots_36 0x1002824 /* U+2824 BRAILLE PATTERN DOTS-36 */ #define XK_braille_dots_136 0x1002825 /* U+2825 BRAILLE PATTERN DOTS-136 */ #define XK_braille_dots_236 0x1002826 /* U+2826 BRAILLE PATTERN DOTS-236 */ #define XK_braille_dots_1236 0x1002827 /* U+2827 BRAILLE PATTERN DOTS-1236 */ #define XK_braille_dots_46 0x1002828 /* U+2828 BRAILLE PATTERN DOTS-46 */ #define XK_braille_dots_146 0x1002829 /* U+2829 BRAILLE PATTERN DOTS-146 */ #define XK_braille_dots_246 0x100282a /* U+282a BRAILLE PATTERN DOTS-246 */ #define XK_braille_dots_1246 0x100282b /* U+282b BRAILLE PATTERN DOTS-1246 */ #define XK_braille_dots_346 0x100282c /* U+282c BRAILLE PATTERN DOTS-346 */ #define XK_braille_dots_1346 0x100282d /* U+282d BRAILLE PATTERN DOTS-1346 */ #define XK_braille_dots_2346 0x100282e /* U+282e BRAILLE PATTERN DOTS-2346 */ #define XK_braille_dots_12346 0x100282f /* U+282f BRAILLE PATTERN DOTS-12346 */ #define XK_braille_dots_56 0x1002830 /* U+2830 BRAILLE PATTERN DOTS-56 */ #define XK_braille_dots_156 0x1002831 /* U+2831 BRAILLE PATTERN DOTS-156 */ #define XK_braille_dots_256 0x1002832 /* U+2832 BRAILLE PATTERN DOTS-256 */ #define XK_braille_dots_1256 0x1002833 /* U+2833 BRAILLE PATTERN DOTS-1256 */ #define XK_braille_dots_356 0x1002834 /* U+2834 BRAILLE PATTERN DOTS-356 */ #define XK_braille_dots_1356 0x1002835 /* U+2835 BRAILLE PATTERN DOTS-1356 */ #define XK_braille_dots_2356 0x1002836 /* U+2836 BRAILLE PATTERN DOTS-2356 */ #define XK_braille_dots_12356 0x1002837 /* U+2837 BRAILLE PATTERN DOTS-12356 */ #define XK_braille_dots_456 0x1002838 /* U+2838 BRAILLE PATTERN DOTS-456 */ #define XK_braille_dots_1456 0x1002839 /* U+2839 BRAILLE PATTERN DOTS-1456 */ #define XK_braille_dots_2456 0x100283a /* U+283a BRAILLE PATTERN DOTS-2456 */ #define XK_braille_dots_12456 0x100283b /* U+283b BRAILLE PATTERN DOTS-12456 */ #define XK_braille_dots_3456 0x100283c /* U+283c BRAILLE PATTERN DOTS-3456 */ #define XK_braille_dots_13456 0x100283d /* U+283d BRAILLE PATTERN DOTS-13456 */ #define XK_braille_dots_23456 0x100283e /* U+283e BRAILLE PATTERN DOTS-23456 */ #define XK_braille_dots_123456 0x100283f /* U+283f BRAILLE PATTERN DOTS-123456 */ #define XK_braille_dots_7 0x1002840 /* U+2840 BRAILLE PATTERN DOTS-7 */ #define XK_braille_dots_17 0x1002841 /* U+2841 BRAILLE PATTERN DOTS-17 */ #define XK_braille_dots_27 0x1002842 /* U+2842 BRAILLE PATTERN DOTS-27 */ #define XK_braille_dots_127 0x1002843 /* U+2843 BRAILLE PATTERN DOTS-127 */ #define XK_braille_dots_37 0x1002844 /* U+2844 BRAILLE PATTERN DOTS-37 */ #define XK_braille_dots_137 0x1002845 /* U+2845 BRAILLE PATTERN DOTS-137 */ #define XK_braille_dots_237 0x1002846 /* U+2846 BRAILLE PATTERN DOTS-237 */ #define XK_braille_dots_1237 0x1002847 /* U+2847 BRAILLE PATTERN DOTS-1237 */ #define XK_braille_dots_47 0x1002848 /* U+2848 BRAILLE PATTERN DOTS-47 */ #define XK_braille_dots_147 0x1002849 /* U+2849 BRAILLE PATTERN DOTS-147 */ #define XK_braille_dots_247 0x100284a /* U+284a BRAILLE PATTERN DOTS-247 */ #define XK_braille_dots_1247 0x100284b /* U+284b BRAILLE PATTERN DOTS-1247 */ #define XK_braille_dots_347 0x100284c /* U+284c BRAILLE PATTERN DOTS-347 */ #define XK_braille_dots_1347 0x100284d /* U+284d BRAILLE PATTERN DOTS-1347 */ #define XK_braille_dots_2347 0x100284e /* U+284e BRAILLE PATTERN DOTS-2347 */ #define XK_braille_dots_12347 0x100284f /* U+284f BRAILLE PATTERN DOTS-12347 */ #define XK_braille_dots_57 0x1002850 /* U+2850 BRAILLE PATTERN DOTS-57 */ #define XK_braille_dots_157 0x1002851 /* U+2851 BRAILLE PATTERN DOTS-157 */ #define XK_braille_dots_257 0x1002852 /* U+2852 BRAILLE PATTERN DOTS-257 */ #define XK_braille_dots_1257 0x1002853 /* U+2853 BRAILLE PATTERN DOTS-1257 */ #define XK_braille_dots_357 0x1002854 /* U+2854 BRAILLE PATTERN DOTS-357 */ #define XK_braille_dots_1357 0x1002855 /* U+2855 BRAILLE PATTERN DOTS-1357 */ #define XK_braille_dots_2357 0x1002856 /* U+2856 BRAILLE PATTERN DOTS-2357 */ #define XK_braille_dots_12357 0x1002857 /* U+2857 BRAILLE PATTERN DOTS-12357 */ #define XK_braille_dots_457 0x1002858 /* U+2858 BRAILLE PATTERN DOTS-457 */ #define XK_braille_dots_1457 0x1002859 /* U+2859 BRAILLE PATTERN DOTS-1457 */ #define XK_braille_dots_2457 0x100285a /* U+285a BRAILLE PATTERN DOTS-2457 */ #define XK_braille_dots_12457 0x100285b /* U+285b BRAILLE PATTERN DOTS-12457 */ #define XK_braille_dots_3457 0x100285c /* U+285c BRAILLE PATTERN DOTS-3457 */ #define XK_braille_dots_13457 0x100285d /* U+285d BRAILLE PATTERN DOTS-13457 */ #define XK_braille_dots_23457 0x100285e /* U+285e BRAILLE PATTERN DOTS-23457 */ #define XK_braille_dots_123457 0x100285f /* U+285f BRAILLE PATTERN DOTS-123457 */ #define XK_braille_dots_67 0x1002860 /* U+2860 BRAILLE PATTERN DOTS-67 */ #define XK_braille_dots_167 0x1002861 /* U+2861 BRAILLE PATTERN DOTS-167 */ #define XK_braille_dots_267 0x1002862 /* U+2862 BRAILLE PATTERN DOTS-267 */ #define XK_braille_dots_1267 0x1002863 /* U+2863 BRAILLE PATTERN DOTS-1267 */ #define XK_braille_dots_367 0x1002864 /* U+2864 BRAILLE PATTERN DOTS-367 */ #define XK_braille_dots_1367 0x1002865 /* U+2865 BRAILLE PATTERN DOTS-1367 */ #define XK_braille_dots_2367 0x1002866 /* U+2866 BRAILLE PATTERN DOTS-2367 */ #define XK_braille_dots_12367 0x1002867 /* U+2867 BRAILLE PATTERN DOTS-12367 */ #define XK_braille_dots_467 0x1002868 /* U+2868 BRAILLE PATTERN DOTS-467 */ #define XK_braille_dots_1467 0x1002869 /* U+2869 BRAILLE PATTERN DOTS-1467 */ #define XK_braille_dots_2467 0x100286a /* U+286a BRAILLE PATTERN DOTS-2467 */ #define XK_braille_dots_12467 0x100286b /* U+286b BRAILLE PATTERN DOTS-12467 */ #define XK_braille_dots_3467 0x100286c /* U+286c BRAILLE PATTERN DOTS-3467 */ #define XK_braille_dots_13467 0x100286d /* U+286d BRAILLE PATTERN DOTS-13467 */ #define XK_braille_dots_23467 0x100286e /* U+286e BRAILLE PATTERN DOTS-23467 */ #define XK_braille_dots_123467 0x100286f /* U+286f BRAILLE PATTERN DOTS-123467 */ #define XK_braille_dots_567 0x1002870 /* U+2870 BRAILLE PATTERN DOTS-567 */ #define XK_braille_dots_1567 0x1002871 /* U+2871 BRAILLE PATTERN DOTS-1567 */ #define XK_braille_dots_2567 0x1002872 /* U+2872 BRAILLE PATTERN DOTS-2567 */ #define XK_braille_dots_12567 0x1002873 /* U+2873 BRAILLE PATTERN DOTS-12567 */ #define XK_braille_dots_3567 0x1002874 /* U+2874 BRAILLE PATTERN DOTS-3567 */ #define XK_braille_dots_13567 0x1002875 /* U+2875 BRAILLE PATTERN DOTS-13567 */ #define XK_braille_dots_23567 0x1002876 /* U+2876 BRAILLE PATTERN DOTS-23567 */ #define XK_braille_dots_123567 0x1002877 /* U+2877 BRAILLE PATTERN DOTS-123567 */ #define XK_braille_dots_4567 0x1002878 /* U+2878 BRAILLE PATTERN DOTS-4567 */ #define XK_braille_dots_14567 0x1002879 /* U+2879 BRAILLE PATTERN DOTS-14567 */ #define XK_braille_dots_24567 0x100287a /* U+287a BRAILLE PATTERN DOTS-24567 */ #define XK_braille_dots_124567 0x100287b /* U+287b BRAILLE PATTERN DOTS-124567 */ #define XK_braille_dots_34567 0x100287c /* U+287c BRAILLE PATTERN DOTS-34567 */ #define XK_braille_dots_134567 0x100287d /* U+287d BRAILLE PATTERN DOTS-134567 */ #define XK_braille_dots_234567 0x100287e /* U+287e BRAILLE PATTERN DOTS-234567 */ #define XK_braille_dots_1234567 0x100287f /* U+287f BRAILLE PATTERN DOTS-1234567 */ #define XK_braille_dots_8 0x1002880 /* U+2880 BRAILLE PATTERN DOTS-8 */ #define XK_braille_dots_18 0x1002881 /* U+2881 BRAILLE PATTERN DOTS-18 */ #define XK_braille_dots_28 0x1002882 /* U+2882 BRAILLE PATTERN DOTS-28 */ #define XK_braille_dots_128 0x1002883 /* U+2883 BRAILLE PATTERN DOTS-128 */ #define XK_braille_dots_38 0x1002884 /* U+2884 BRAILLE PATTERN DOTS-38 */ #define XK_braille_dots_138 0x1002885 /* U+2885 BRAILLE PATTERN DOTS-138 */ #define XK_braille_dots_238 0x1002886 /* U+2886 BRAILLE PATTERN DOTS-238 */ #define XK_braille_dots_1238 0x1002887 /* U+2887 BRAILLE PATTERN DOTS-1238 */ #define XK_braille_dots_48 0x1002888 /* U+2888 BRAILLE PATTERN DOTS-48 */ #define XK_braille_dots_148 0x1002889 /* U+2889 BRAILLE PATTERN DOTS-148 */ #define XK_braille_dots_248 0x100288a /* U+288a BRAILLE PATTERN DOTS-248 */ #define XK_braille_dots_1248 0x100288b /* U+288b BRAILLE PATTERN DOTS-1248 */ #define XK_braille_dots_348 0x100288c /* U+288c BRAILLE PATTERN DOTS-348 */ #define XK_braille_dots_1348 0x100288d /* U+288d BRAILLE PATTERN DOTS-1348 */ #define XK_braille_dots_2348 0x100288e /* U+288e BRAILLE PATTERN DOTS-2348 */ #define XK_braille_dots_12348 0x100288f /* U+288f BRAILLE PATTERN DOTS-12348 */ #define XK_braille_dots_58 0x1002890 /* U+2890 BRAILLE PATTERN DOTS-58 */ #define XK_braille_dots_158 0x1002891 /* U+2891 BRAILLE PATTERN DOTS-158 */ #define XK_braille_dots_258 0x1002892 /* U+2892 BRAILLE PATTERN DOTS-258 */ #define XK_braille_dots_1258 0x1002893 /* U+2893 BRAILLE PATTERN DOTS-1258 */ #define XK_braille_dots_358 0x1002894 /* U+2894 BRAILLE PATTERN DOTS-358 */ #define XK_braille_dots_1358 0x1002895 /* U+2895 BRAILLE PATTERN DOTS-1358 */ #define XK_braille_dots_2358 0x1002896 /* U+2896 BRAILLE PATTERN DOTS-2358 */ #define XK_braille_dots_12358 0x1002897 /* U+2897 BRAILLE PATTERN DOTS-12358 */ #define XK_braille_dots_458 0x1002898 /* U+2898 BRAILLE PATTERN DOTS-458 */ #define XK_braille_dots_1458 0x1002899 /* U+2899 BRAILLE PATTERN DOTS-1458 */ #define XK_braille_dots_2458 0x100289a /* U+289a BRAILLE PATTERN DOTS-2458 */ #define XK_braille_dots_12458 0x100289b /* U+289b BRAILLE PATTERN DOTS-12458 */ #define XK_braille_dots_3458 0x100289c /* U+289c BRAILLE PATTERN DOTS-3458 */ #define XK_braille_dots_13458 0x100289d /* U+289d BRAILLE PATTERN DOTS-13458 */ #define XK_braille_dots_23458 0x100289e /* U+289e BRAILLE PATTERN DOTS-23458 */ #define XK_braille_dots_123458 0x100289f /* U+289f BRAILLE PATTERN DOTS-123458 */ #define XK_braille_dots_68 0x10028a0 /* U+28a0 BRAILLE PATTERN DOTS-68 */ #define XK_braille_dots_168 0x10028a1 /* U+28a1 BRAILLE PATTERN DOTS-168 */ #define XK_braille_dots_268 0x10028a2 /* U+28a2 BRAILLE PATTERN DOTS-268 */ #define XK_braille_dots_1268 0x10028a3 /* U+28a3 BRAILLE PATTERN DOTS-1268 */ #define XK_braille_dots_368 0x10028a4 /* U+28a4 BRAILLE PATTERN DOTS-368 */ #define XK_braille_dots_1368 0x10028a5 /* U+28a5 BRAILLE PATTERN DOTS-1368 */ #define XK_braille_dots_2368 0x10028a6 /* U+28a6 BRAILLE PATTERN DOTS-2368 */ #define XK_braille_dots_12368 0x10028a7 /* U+28a7 BRAILLE PATTERN DOTS-12368 */ #define XK_braille_dots_468 0x10028a8 /* U+28a8 BRAILLE PATTERN DOTS-468 */ #define XK_braille_dots_1468 0x10028a9 /* U+28a9 BRAILLE PATTERN DOTS-1468 */ #define XK_braille_dots_2468 0x10028aa /* U+28aa BRAILLE PATTERN DOTS-2468 */ #define XK_braille_dots_12468 0x10028ab /* U+28ab BRAILLE PATTERN DOTS-12468 */ #define XK_braille_dots_3468 0x10028ac /* U+28ac BRAILLE PATTERN DOTS-3468 */ #define XK_braille_dots_13468 0x10028ad /* U+28ad BRAILLE PATTERN DOTS-13468 */ #define XK_braille_dots_23468 0x10028ae /* U+28ae BRAILLE PATTERN DOTS-23468 */ #define XK_braille_dots_123468 0x10028af /* U+28af BRAILLE PATTERN DOTS-123468 */ #define XK_braille_dots_568 0x10028b0 /* U+28b0 BRAILLE PATTERN DOTS-568 */ #define XK_braille_dots_1568 0x10028b1 /* U+28b1 BRAILLE PATTERN DOTS-1568 */ #define XK_braille_dots_2568 0x10028b2 /* U+28b2 BRAILLE PATTERN DOTS-2568 */ #define XK_braille_dots_12568 0x10028b3 /* U+28b3 BRAILLE PATTERN DOTS-12568 */ #define XK_braille_dots_3568 0x10028b4 /* U+28b4 BRAILLE PATTERN DOTS-3568 */ #define XK_braille_dots_13568 0x10028b5 /* U+28b5 BRAILLE PATTERN DOTS-13568 */ #define XK_braille_dots_23568 0x10028b6 /* U+28b6 BRAILLE PATTERN DOTS-23568 */ #define XK_braille_dots_123568 0x10028b7 /* U+28b7 BRAILLE PATTERN DOTS-123568 */ #define XK_braille_dots_4568 0x10028b8 /* U+28b8 BRAILLE PATTERN DOTS-4568 */ #define XK_braille_dots_14568 0x10028b9 /* U+28b9 BRAILLE PATTERN DOTS-14568 */ #define XK_braille_dots_24568 0x10028ba /* U+28ba BRAILLE PATTERN DOTS-24568 */ #define XK_braille_dots_124568 0x10028bb /* U+28bb BRAILLE PATTERN DOTS-124568 */ #define XK_braille_dots_34568 0x10028bc /* U+28bc BRAILLE PATTERN DOTS-34568 */ #define XK_braille_dots_134568 0x10028bd /* U+28bd BRAILLE PATTERN DOTS-134568 */ #define XK_braille_dots_234568 0x10028be /* U+28be BRAILLE PATTERN DOTS-234568 */ #define XK_braille_dots_1234568 0x10028bf /* U+28bf BRAILLE PATTERN DOTS-1234568 */ #define XK_braille_dots_78 0x10028c0 /* U+28c0 BRAILLE PATTERN DOTS-78 */ #define XK_braille_dots_178 0x10028c1 /* U+28c1 BRAILLE PATTERN DOTS-178 */ #define XK_braille_dots_278 0x10028c2 /* U+28c2 BRAILLE PATTERN DOTS-278 */ #define XK_braille_dots_1278 0x10028c3 /* U+28c3 BRAILLE PATTERN DOTS-1278 */ #define XK_braille_dots_378 0x10028c4 /* U+28c4 BRAILLE PATTERN DOTS-378 */ #define XK_braille_dots_1378 0x10028c5 /* U+28c5 BRAILLE PATTERN DOTS-1378 */ #define XK_braille_dots_2378 0x10028c6 /* U+28c6 BRAILLE PATTERN DOTS-2378 */ #define XK_braille_dots_12378 0x10028c7 /* U+28c7 BRAILLE PATTERN DOTS-12378 */ #define XK_braille_dots_478 0x10028c8 /* U+28c8 BRAILLE PATTERN DOTS-478 */ #define XK_braille_dots_1478 0x10028c9 /* U+28c9 BRAILLE PATTERN DOTS-1478 */ #define XK_braille_dots_2478 0x10028ca /* U+28ca BRAILLE PATTERN DOTS-2478 */ #define XK_braille_dots_12478 0x10028cb /* U+28cb BRAILLE PATTERN DOTS-12478 */ #define XK_braille_dots_3478 0x10028cc /* U+28cc BRAILLE PATTERN DOTS-3478 */ #define XK_braille_dots_13478 0x10028cd /* U+28cd BRAILLE PATTERN DOTS-13478 */ #define XK_braille_dots_23478 0x10028ce /* U+28ce BRAILLE PATTERN DOTS-23478 */ #define XK_braille_dots_123478 0x10028cf /* U+28cf BRAILLE PATTERN DOTS-123478 */ #define XK_braille_dots_578 0x10028d0 /* U+28d0 BRAILLE PATTERN DOTS-578 */ #define XK_braille_dots_1578 0x10028d1 /* U+28d1 BRAILLE PATTERN DOTS-1578 */ #define XK_braille_dots_2578 0x10028d2 /* U+28d2 BRAILLE PATTERN DOTS-2578 */ #define XK_braille_dots_12578 0x10028d3 /* U+28d3 BRAILLE PATTERN DOTS-12578 */ #define XK_braille_dots_3578 0x10028d4 /* U+28d4 BRAILLE PATTERN DOTS-3578 */ #define XK_braille_dots_13578 0x10028d5 /* U+28d5 BRAILLE PATTERN DOTS-13578 */ #define XK_braille_dots_23578 0x10028d6 /* U+28d6 BRAILLE PATTERN DOTS-23578 */ #define XK_braille_dots_123578 0x10028d7 /* U+28d7 BRAILLE PATTERN DOTS-123578 */ #define XK_braille_dots_4578 0x10028d8 /* U+28d8 BRAILLE PATTERN DOTS-4578 */ #define XK_braille_dots_14578 0x10028d9 /* U+28d9 BRAILLE PATTERN DOTS-14578 */ #define XK_braille_dots_24578 0x10028da /* U+28da BRAILLE PATTERN DOTS-24578 */ #define XK_braille_dots_124578 0x10028db /* U+28db BRAILLE PATTERN DOTS-124578 */ #define XK_braille_dots_34578 0x10028dc /* U+28dc BRAILLE PATTERN DOTS-34578 */ #define XK_braille_dots_134578 0x10028dd /* U+28dd BRAILLE PATTERN DOTS-134578 */ #define XK_braille_dots_234578 0x10028de /* U+28de BRAILLE PATTERN DOTS-234578 */ #define XK_braille_dots_1234578 0x10028df /* U+28df BRAILLE PATTERN DOTS-1234578 */ #define XK_braille_dots_678 0x10028e0 /* U+28e0 BRAILLE PATTERN DOTS-678 */ #define XK_braille_dots_1678 0x10028e1 /* U+28e1 BRAILLE PATTERN DOTS-1678 */ #define XK_braille_dots_2678 0x10028e2 /* U+28e2 BRAILLE PATTERN DOTS-2678 */ #define XK_braille_dots_12678 0x10028e3 /* U+28e3 BRAILLE PATTERN DOTS-12678 */ #define XK_braille_dots_3678 0x10028e4 /* U+28e4 BRAILLE PATTERN DOTS-3678 */ #define XK_braille_dots_13678 0x10028e5 /* U+28e5 BRAILLE PATTERN DOTS-13678 */ #define XK_braille_dots_23678 0x10028e6 /* U+28e6 BRAILLE PATTERN DOTS-23678 */ #define XK_braille_dots_123678 0x10028e7 /* U+28e7 BRAILLE PATTERN DOTS-123678 */ #define XK_braille_dots_4678 0x10028e8 /* U+28e8 BRAILLE PATTERN DOTS-4678 */ #define XK_braille_dots_14678 0x10028e9 /* U+28e9 BRAILLE PATTERN DOTS-14678 */ #define XK_braille_dots_24678 0x10028ea /* U+28ea BRAILLE PATTERN DOTS-24678 */ #define XK_braille_dots_124678 0x10028eb /* U+28eb BRAILLE PATTERN DOTS-124678 */ #define XK_braille_dots_34678 0x10028ec /* U+28ec BRAILLE PATTERN DOTS-34678 */ #define XK_braille_dots_134678 0x10028ed /* U+28ed BRAILLE PATTERN DOTS-134678 */ #define XK_braille_dots_234678 0x10028ee /* U+28ee BRAILLE PATTERN DOTS-234678 */ #define XK_braille_dots_1234678 0x10028ef /* U+28ef BRAILLE PATTERN DOTS-1234678 */ #define XK_braille_dots_5678 0x10028f0 /* U+28f0 BRAILLE PATTERN DOTS-5678 */ #define XK_braille_dots_15678 0x10028f1 /* U+28f1 BRAILLE PATTERN DOTS-15678 */ #define XK_braille_dots_25678 0x10028f2 /* U+28f2 BRAILLE PATTERN DOTS-25678 */ #define XK_braille_dots_125678 0x10028f3 /* U+28f3 BRAILLE PATTERN DOTS-125678 */ #define XK_braille_dots_35678 0x10028f4 /* U+28f4 BRAILLE PATTERN DOTS-35678 */ #define XK_braille_dots_135678 0x10028f5 /* U+28f5 BRAILLE PATTERN DOTS-135678 */ #define XK_braille_dots_235678 0x10028f6 /* U+28f6 BRAILLE PATTERN DOTS-235678 */ #define XK_braille_dots_1235678 0x10028f7 /* U+28f7 BRAILLE PATTERN DOTS-1235678 */ #define XK_braille_dots_45678 0x10028f8 /* U+28f8 BRAILLE PATTERN DOTS-45678 */ #define XK_braille_dots_145678 0x10028f9 /* U+28f9 BRAILLE PATTERN DOTS-145678 */ #define XK_braille_dots_245678 0x10028fa /* U+28fa BRAILLE PATTERN DOTS-245678 */ #define XK_braille_dots_1245678 0x10028fb /* U+28fb BRAILLE PATTERN DOTS-1245678 */ #define XK_braille_dots_345678 0x10028fc /* U+28fc BRAILLE PATTERN DOTS-345678 */ #define XK_braille_dots_1345678 0x10028fd /* U+28fd BRAILLE PATTERN DOTS-1345678 */ #define XK_braille_dots_2345678 0x10028fe /* U+28fe BRAILLE PATTERN DOTS-2345678 */ #define XK_braille_dots_12345678 0x10028ff /* U+28ff BRAILLE PATTERN DOTS-12345678 */ #endif /* XK_BRAILLE */ /* * Sinhala (http://unicode.org/charts/PDF/U0D80.pdf) * http://www.nongnu.org/sinhala/doc/transliteration/sinhala-transliteration_6.html */ #ifdef XK_SINHALA #define XK_Sinh_ng 0x1000d82 /* U+0D82 SINHALA ANUSVARAYA */ #define XK_Sinh_h2 0x1000d83 /* U+0D83 SINHALA VISARGAYA */ #define XK_Sinh_a 0x1000d85 /* U+0D85 SINHALA AYANNA */ #define XK_Sinh_aa 0x1000d86 /* U+0D86 SINHALA AAYANNA */ #define XK_Sinh_ae 0x1000d87 /* U+0D87 SINHALA AEYANNA */ #define XK_Sinh_aee 0x1000d88 /* U+0D88 SINHALA AEEYANNA */ #define XK_Sinh_i 0x1000d89 /* U+0D89 SINHALA IYANNA */ #define XK_Sinh_ii 0x1000d8a /* U+0D8A SINHALA IIYANNA */ #define XK_Sinh_u 0x1000d8b /* U+0D8B SINHALA UYANNA */ #define XK_Sinh_uu 0x1000d8c /* U+0D8C SINHALA UUYANNA */ #define XK_Sinh_ri 0x1000d8d /* U+0D8D SINHALA IRUYANNA */ #define XK_Sinh_rii 0x1000d8e /* U+0D8E SINHALA IRUUYANNA */ #define XK_Sinh_lu 0x1000d8f /* U+0D8F SINHALA ILUYANNA */ #define XK_Sinh_luu 0x1000d90 /* U+0D90 SINHALA ILUUYANNA */ #define XK_Sinh_e 0x1000d91 /* U+0D91 SINHALA EYANNA */ #define XK_Sinh_ee 0x1000d92 /* U+0D92 SINHALA EEYANNA */ #define XK_Sinh_ai 0x1000d93 /* U+0D93 SINHALA AIYANNA */ #define XK_Sinh_o 0x1000d94 /* U+0D94 SINHALA OYANNA */ #define XK_Sinh_oo 0x1000d95 /* U+0D95 SINHALA OOYANNA */ #define XK_Sinh_au 0x1000d96 /* U+0D96 SINHALA AUYANNA */ #define XK_Sinh_ka 0x1000d9a /* U+0D9A SINHALA KAYANNA */ #define XK_Sinh_kha 0x1000d9b /* U+0D9B SINHALA MAHA. KAYANNA */ #define XK_Sinh_ga 0x1000d9c /* U+0D9C SINHALA GAYANNA */ #define XK_Sinh_gha 0x1000d9d /* U+0D9D SINHALA MAHA. GAYANNA */ #define XK_Sinh_ng2 0x1000d9e /* U+0D9E SINHALA KANTAJA NAASIKYAYA */ #define XK_Sinh_nga 0x1000d9f /* U+0D9F SINHALA SANYAKA GAYANNA */ #define XK_Sinh_ca 0x1000da0 /* U+0DA0 SINHALA CAYANNA */ #define XK_Sinh_cha 0x1000da1 /* U+0DA1 SINHALA MAHA. CAYANNA */ #define XK_Sinh_ja 0x1000da2 /* U+0DA2 SINHALA JAYANNA */ #define XK_Sinh_jha 0x1000da3 /* U+0DA3 SINHALA MAHA. JAYANNA */ #define XK_Sinh_nya 0x1000da4 /* U+0DA4 SINHALA TAALUJA NAASIKYAYA */ #define XK_Sinh_jnya 0x1000da5 /* U+0DA5 SINHALA TAALUJA SANYOOGA NAASIKYAYA */ #define XK_Sinh_nja 0x1000da6 /* U+0DA6 SINHALA SANYAKA JAYANNA */ #define XK_Sinh_tta 0x1000da7 /* U+0DA7 SINHALA TTAYANNA */ #define XK_Sinh_ttha 0x1000da8 /* U+0DA8 SINHALA MAHA. TTAYANNA */ #define XK_Sinh_dda 0x1000da9 /* U+0DA9 SINHALA DDAYANNA */ #define XK_Sinh_ddha 0x1000daa /* U+0DAA SINHALA MAHA. DDAYANNA */ #define XK_Sinh_nna 0x1000dab /* U+0DAB SINHALA MUURDHAJA NAYANNA */ #define XK_Sinh_ndda 0x1000dac /* U+0DAC SINHALA SANYAKA DDAYANNA */ #define XK_Sinh_tha 0x1000dad /* U+0DAD SINHALA TAYANNA */ #define XK_Sinh_thha 0x1000dae /* U+0DAE SINHALA MAHA. TAYANNA */ #define XK_Sinh_dha 0x1000daf /* U+0DAF SINHALA DAYANNA */ #define XK_Sinh_dhha 0x1000db0 /* U+0DB0 SINHALA MAHA. DAYANNA */ #define XK_Sinh_na 0x1000db1 /* U+0DB1 SINHALA DANTAJA NAYANNA */ #define XK_Sinh_ndha 0x1000db3 /* U+0DB3 SINHALA SANYAKA DAYANNA */ #define XK_Sinh_pa 0x1000db4 /* U+0DB4 SINHALA PAYANNA */ #define XK_Sinh_pha 0x1000db5 /* U+0DB5 SINHALA MAHA. PAYANNA */ #define XK_Sinh_ba 0x1000db6 /* U+0DB6 SINHALA BAYANNA */ #define XK_Sinh_bha 0x1000db7 /* U+0DB7 SINHALA MAHA. BAYANNA */ #define XK_Sinh_ma 0x1000db8 /* U+0DB8 SINHALA MAYANNA */ #define XK_Sinh_mba 0x1000db9 /* U+0DB9 SINHALA AMBA BAYANNA */ #define XK_Sinh_ya 0x1000dba /* U+0DBA SINHALA YAYANNA */ #define XK_Sinh_ra 0x1000dbb /* U+0DBB SINHALA RAYANNA */ #define XK_Sinh_la 0x1000dbd /* U+0DBD SINHALA DANTAJA LAYANNA */ #define XK_Sinh_va 0x1000dc0 /* U+0DC0 SINHALA VAYANNA */ #define XK_Sinh_sha 0x1000dc1 /* U+0DC1 SINHALA TAALUJA SAYANNA */ #define XK_Sinh_ssha 0x1000dc2 /* U+0DC2 SINHALA MUURDHAJA SAYANNA */ #define XK_Sinh_sa 0x1000dc3 /* U+0DC3 SINHALA DANTAJA SAYANNA */ #define XK_Sinh_ha 0x1000dc4 /* U+0DC4 SINHALA HAYANNA */ #define XK_Sinh_lla 0x1000dc5 /* U+0DC5 SINHALA MUURDHAJA LAYANNA */ #define XK_Sinh_fa 0x1000dc6 /* U+0DC6 SINHALA FAYANNA */ #define XK_Sinh_al 0x1000dca /* U+0DCA SINHALA AL-LAKUNA */ #define XK_Sinh_aa2 0x1000dcf /* U+0DCF SINHALA AELA-PILLA */ #define XK_Sinh_ae2 0x1000dd0 /* U+0DD0 SINHALA AEDA-PILLA */ #define XK_Sinh_aee2 0x1000dd1 /* U+0DD1 SINHALA DIGA AEDA-PILLA */ #define XK_Sinh_i2 0x1000dd2 /* U+0DD2 SINHALA IS-PILLA */ #define XK_Sinh_ii2 0x1000dd3 /* U+0DD3 SINHALA DIGA IS-PILLA */ #define XK_Sinh_u2 0x1000dd4 /* U+0DD4 SINHALA PAA-PILLA */ #define XK_Sinh_uu2 0x1000dd6 /* U+0DD6 SINHALA DIGA PAA-PILLA */ #define XK_Sinh_ru2 0x1000dd8 /* U+0DD8 SINHALA GAETTA-PILLA */ #define XK_Sinh_e2 0x1000dd9 /* U+0DD9 SINHALA KOMBUVA */ #define XK_Sinh_ee2 0x1000dda /* U+0DDA SINHALA DIGA KOMBUVA */ #define XK_Sinh_ai2 0x1000ddb /* U+0DDB SINHALA KOMBU DEKA */ #define XK_Sinh_o2 0x1000ddc /* U+0DDC SINHALA KOMBUVA HAA AELA-PILLA*/ #define XK_Sinh_oo2 0x1000ddd /* U+0DDD SINHALA KOMBUVA HAA DIGA AELA-PILLA*/ #define XK_Sinh_au2 0x1000dde /* U+0DDE SINHALA KOMBUVA HAA GAYANUKITTA */ #define XK_Sinh_lu2 0x1000ddf /* U+0DDF SINHALA GAYANUKITTA */ #define XK_Sinh_ruu2 0x1000df2 /* U+0DF2 SINHALA DIGA GAETTA-PILLA */ #define XK_Sinh_luu2 0x1000df3 /* U+0DF3 SINHALA DIGA GAYANUKITTA */ #define XK_Sinh_kunddaliya 0x1000df4 /* U+0DF4 SINHALA KUNDDALIYA */ #endif /* XK_SINHALA */ X11/dri/xf86dri.h000064400000004615151027430550007346 0ustar00/************************************************************************** Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas. Copyright 2000 VA Linux Systems, Inc. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ /** * \file xf86dri.h * Protocol numbers and function prototypes for DRI X protocol. * * \author Kevin E. Martin * \author Jens Owen * \author Rickard E. (Rik) Faith */ #ifndef _XF86DRI_H_ #define _XF86DRI_H_ #include #define X_XF86DRIQueryVersion 0 #define X_XF86DRIQueryDirectRenderingCapable 1 #define X_XF86DRIOpenConnection 2 #define X_XF86DRICloseConnection 3 #define X_XF86DRIGetClientDriverName 4 #define X_XF86DRICreateContext 5 #define X_XF86DRIDestroyContext 6 #define X_XF86DRICreateDrawable 7 #define X_XF86DRIDestroyDrawable 8 #define X_XF86DRIGetDrawableInfo 9 #define X_XF86DRIGetDeviceInfo 10 #define X_XF86DRIAuthConnection 11 #define X_XF86DRIOpenFullScreen 12 /* Deprecated */ #define X_XF86DRICloseFullScreen 13 /* Deprecated */ #define XF86DRINumberEvents 0 #define XF86DRIClientNotLocal 0 #define XF86DRIOperationNotSupported 1 #define XF86DRINumberErrors (XF86DRIOperationNotSupported + 1) #endif /* _XF86DRI_H_ */ X11/dri/xf86driproto.h000064400000022705151027430550010432 0ustar00/************************************************************************** Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas. Copyright 2000 VA Linux Systems, Inc. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ /* * Authors: * Kevin E. Martin * Jens Owen * Rickard E. (Rik) Faith * */ #ifndef _XF86DRISTR_H_ #define _XF86DRISTR_H_ #include "xf86dri.h" #define XF86DRINAME "XFree86-DRI" /* The DRI version number. This was originally set to be the same of the * XFree86 version number. However, this version is really independent of * the XFree86 version. * * Version History: * 4.0.0: Original * 4.0.1: Patch to bump clipstamp when windows are destroyed, 28 May 02 * 4.1.0: Add transition from single to multi in DRMInfo rec, 24 Jun 02 */ #define XF86DRI_MAJOR_VERSION 4 #define XF86DRI_MINOR_VERSION 1 #define XF86DRI_PATCH_VERSION 0 typedef struct _XF86DRIQueryVersion { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIQueryVersion */ CARD16 length; } xXF86DRIQueryVersionReq; #define sz_xXF86DRIQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of DRI protocol */ CARD16 minorVersion; /* minor version of DRI protocol */ CARD32 patchVersion; /* patch version of DRI protocol */ CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86DRIQueryVersionReply; #define sz_xXF86DRIQueryVersionReply 32 typedef struct _XF86DRIQueryDirectRenderingCapable { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* X_DRIQueryDirectRenderingCapable */ CARD16 length; CARD32 screen; } xXF86DRIQueryDirectRenderingCapableReq; #define sz_xXF86DRIQueryDirectRenderingCapableReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; BOOL isCapable; BOOL pad2; BOOL pad3; BOOL pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; CARD32 pad8; CARD32 pad9; } xXF86DRIQueryDirectRenderingCapableReply; #define sz_xXF86DRIQueryDirectRenderingCapableReply 32 typedef struct _XF86DRIOpenConnection { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIOpenConnection */ CARD16 length; CARD32 screen; } xXF86DRIOpenConnectionReq; #define sz_xXF86DRIOpenConnectionReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 hSAREALow; CARD32 hSAREAHigh; CARD32 busIdStringLength; CARD32 pad6; CARD32 pad7; CARD32 pad8; } xXF86DRIOpenConnectionReply; #define sz_xXF86DRIOpenConnectionReply 32 typedef struct _XF86DRIAuthConnection { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRICloseConnection */ CARD16 length; CARD32 screen; CARD32 magic; } xXF86DRIAuthConnectionReq; #define sz_xXF86DRIAuthConnectionReq 12 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 authenticated; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86DRIAuthConnectionReply; #define zx_xXF86DRIAuthConnectionReply 32 typedef struct _XF86DRICloseConnection { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRICloseConnection */ CARD16 length; CARD32 screen; } xXF86DRICloseConnectionReq; #define sz_xXF86DRICloseConnectionReq 8 typedef struct _XF86DRIGetClientDriverName { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIGetClientDriverName */ CARD16 length; CARD32 screen; } xXF86DRIGetClientDriverNameReq; #define sz_xXF86DRIGetClientDriverNameReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 ddxDriverMajorVersion; CARD32 ddxDriverMinorVersion; CARD32 ddxDriverPatchVersion; CARD32 clientDriverNameLength; CARD32 pad5; CARD32 pad6; } xXF86DRIGetClientDriverNameReply; #define sz_xXF86DRIGetClientDriverNameReply 32 typedef struct _XF86DRICreateContext { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRICreateContext */ CARD16 length; CARD32 screen; CARD32 visual; CARD32 context; } xXF86DRICreateContextReq; #define sz_xXF86DRICreateContextReq 16 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 hHWContext; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86DRICreateContextReply; #define sz_xXF86DRICreateContextReply 32 typedef struct _XF86DRIDestroyContext { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIDestroyContext */ CARD16 length; CARD32 screen; CARD32 context; } xXF86DRIDestroyContextReq; #define sz_xXF86DRIDestroyContextReq 12 typedef struct _XF86DRICreateDrawable { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRICreateDrawable */ CARD16 length; CARD32 screen; CARD32 drawable; } xXF86DRICreateDrawableReq; #define sz_xXF86DRICreateDrawableReq 12 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 hHWDrawable; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86DRICreateDrawableReply; #define sz_xXF86DRICreateDrawableReply 32 typedef struct _XF86DRIDestroyDrawable { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIDestroyDrawable */ CARD16 length; CARD32 screen; CARD32 drawable; } xXF86DRIDestroyDrawableReq; #define sz_xXF86DRIDestroyDrawableReq 12 typedef struct _XF86DRIGetDrawableInfo { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIGetDrawableInfo */ CARD16 length; CARD32 screen; CARD32 drawable; } xXF86DRIGetDrawableInfoReq; #define sz_xXF86DRIGetDrawableInfoReq 12 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 drawableTableIndex; CARD32 drawableTableStamp; INT16 drawableX; INT16 drawableY; INT16 drawableWidth; INT16 drawableHeight; CARD32 numClipRects; INT16 backX; INT16 backY; CARD32 numBackClipRects; } xXF86DRIGetDrawableInfoReply; #define sz_xXF86DRIGetDrawableInfoReply 36 typedef struct _XF86DRIGetDeviceInfo { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIGetDeviceInfo */ CARD16 length; CARD32 screen; } xXF86DRIGetDeviceInfoReq; #define sz_xXF86DRIGetDeviceInfoReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 hFrameBufferLow; CARD32 hFrameBufferHigh; CARD32 framebufferOrigin; CARD32 framebufferSize; CARD32 framebufferStride; CARD32 devPrivateSize; } xXF86DRIGetDeviceInfoReply; #define sz_xXF86DRIGetDeviceInfoReply 32 typedef struct _XF86DRIOpenFullScreen { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRIOpenFullScreen */ CARD16 length; CARD32 screen; CARD32 drawable; } xXF86DRIOpenFullScreenReq; #define sz_xXF86DRIOpenFullScreenReq 12 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 isFullScreen; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86DRIOpenFullScreenReply; #define sz_xXF86DRIOpenFullScreenReply 32 typedef struct _XF86DRICloseFullScreen { CARD8 reqType; /* always DRIReqCode */ CARD8 driReqType; /* always X_DRICloseFullScreen */ CARD16 length; CARD32 screen; CARD32 drawable; } xXF86DRICloseFullScreenReq; #define sz_xXF86DRICloseFullScreenReq 12 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xXF86DRICloseFullScreenReply; #define sz_xXF86DRICloseFullScreenReply 32 #endif /* _XF86DRISTR_H_ */ X11/dri/xf86dristr.h000064400000000256151027430550010074 0ustar00#warning "xf86dristr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/cursorfont.h000064400000006056151027430550007503 0ustar00/* Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _X11_CURSORFONT_H_ #define _X11_CURSORFONT_H_ #define XC_num_glyphs 154 #define XC_X_cursor 0 #define XC_arrow 2 #define XC_based_arrow_down 4 #define XC_based_arrow_up 6 #define XC_boat 8 #define XC_bogosity 10 #define XC_bottom_left_corner 12 #define XC_bottom_right_corner 14 #define XC_bottom_side 16 #define XC_bottom_tee 18 #define XC_box_spiral 20 #define XC_center_ptr 22 #define XC_circle 24 #define XC_clock 26 #define XC_coffee_mug 28 #define XC_cross 30 #define XC_cross_reverse 32 #define XC_crosshair 34 #define XC_diamond_cross 36 #define XC_dot 38 #define XC_dotbox 40 #define XC_double_arrow 42 #define XC_draft_large 44 #define XC_draft_small 46 #define XC_draped_box 48 #define XC_exchange 50 #define XC_fleur 52 #define XC_gobbler 54 #define XC_gumby 56 #define XC_hand1 58 #define XC_hand2 60 #define XC_heart 62 #define XC_icon 64 #define XC_iron_cross 66 #define XC_left_ptr 68 #define XC_left_side 70 #define XC_left_tee 72 #define XC_leftbutton 74 #define XC_ll_angle 76 #define XC_lr_angle 78 #define XC_man 80 #define XC_middlebutton 82 #define XC_mouse 84 #define XC_pencil 86 #define XC_pirate 88 #define XC_plus 90 #define XC_question_arrow 92 #define XC_right_ptr 94 #define XC_right_side 96 #define XC_right_tee 98 #define XC_rightbutton 100 #define XC_rtl_logo 102 #define XC_sailboat 104 #define XC_sb_down_arrow 106 #define XC_sb_h_double_arrow 108 #define XC_sb_left_arrow 110 #define XC_sb_right_arrow 112 #define XC_sb_up_arrow 114 #define XC_sb_v_double_arrow 116 #define XC_shuttle 118 #define XC_sizing 120 #define XC_spider 122 #define XC_spraycan 124 #define XC_star 126 #define XC_target 128 #define XC_tcross 130 #define XC_top_left_arrow 132 #define XC_top_left_corner 134 #define XC_top_right_corner 136 #define XC_top_side 138 #define XC_top_tee 140 #define XC_trek 142 #define XC_ul_angle 144 #define XC_umbrella 146 #define XC_ur_angle 148 #define XC_watch 150 #define XC_xterm 152 #endif /* _X11_CURSORFONT_H_ */ X11/Xfuncproto.h000064400000017267151027430550007454 0ustar00/* * Copyright 1989, 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * */ /* Definitions to make function prototypes manageable */ #ifndef _XFUNCPROTO_H_ #define _XFUNCPROTO_H_ #ifndef NeedFunctionPrototypes #define NeedFunctionPrototypes 1 #endif /* NeedFunctionPrototypes */ #ifndef NeedVarargsPrototypes #define NeedVarargsPrototypes 1 #endif /* NeedVarargsPrototypes */ #if NeedFunctionPrototypes #ifndef NeedNestedPrototypes #define NeedNestedPrototypes 1 #endif /* NeedNestedPrototypes */ #ifndef _Xconst #define _Xconst const #endif /* _Xconst */ /* Function prototype configuration (see configure for more info) */ #if !defined(NARROWPROTO) && \ (defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) #define NARROWPROTO #endif #ifndef FUNCPROTO #define FUNCPROTO 15 #endif #ifndef NeedWidePrototypes #ifdef NARROWPROTO #define NeedWidePrototypes 0 #else #define NeedWidePrototypes 1 /* default to make interropt. easier */ #endif #endif /* NeedWidePrototypes */ #endif /* NeedFunctionPrototypes */ #ifndef _XFUNCPROTOBEGIN #if defined(__cplusplus) || defined(c_plusplus) /* for C++ V2.0 */ #define _XFUNCPROTOBEGIN extern "C" { /* do not leave open across includes */ #define _XFUNCPROTOEND } #else #define _XFUNCPROTOBEGIN #define _XFUNCPROTOEND #endif #endif /* _XFUNCPROTOBEGIN */ /* http://clang.llvm.org/docs/LanguageExtensions.html#has-attribute */ #ifndef __has_attribute # define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ #endif #ifndef __has_feature # define __has_feature(x) 0 /* Compatibility with non-clang compilers. */ #endif #ifndef __has_extension # define __has_extension(x) 0 /* Compatibility with non-clang compilers. */ #endif /* Added in X11R6.9, so available in any version of modular xproto */ #if __has_attribute(__sentinel__) || (defined(__GNUC__) && (__GNUC__ >= 4)) # define _X_SENTINEL(x) __attribute__ ((__sentinel__(x))) #else # define _X_SENTINEL(x) #endif /* GNUC >= 4 */ /* Added in X11R6.9, so available in any version of modular xproto */ #if (__has_attribute(visibility) || (defined(__GNUC__) && (__GNUC__ >= 4))) \ && !defined(__CYGWIN__) && !defined(__MINGW32__) # define _X_EXPORT __attribute__((visibility("default"))) # define _X_HIDDEN __attribute__((visibility("hidden"))) # define _X_INTERNAL __attribute__((visibility("internal"))) #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550) # define _X_EXPORT __global # define _X_HIDDEN __hidden # define _X_INTERNAL __hidden #else /* not gcc >= 4 and not Sun Studio >= 8 */ # define _X_EXPORT # define _X_HIDDEN # define _X_INTERNAL #endif /* GNUC >= 4 */ /* Branch prediction hints for individual conditionals */ /* requires xproto >= 7.0.9 */ #if defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 303) # define _X_LIKELY(x) __builtin_expect(!!(x), 1) # define _X_UNLIKELY(x) __builtin_expect(!!(x), 0) #else /* not gcc >= 3.3 */ # define _X_LIKELY(x) (x) # define _X_UNLIKELY(x) (x) #endif /* Bulk branch prediction hints via marking error path functions as "cold" */ /* requires xproto >= 7.0.25 */ #if __has_attribute(__cold__) || \ (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 403)) /* 4.3+ */ # define _X_COLD __attribute__((__cold__)) #else # define _X_COLD /* nothing */ #endif /* Added in X11R6.9, so available in any version of modular xproto */ #if __has_attribute(deprecated) \ || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 301)) \ || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5130)) # define _X_DEPRECATED __attribute__((deprecated)) #else /* not gcc >= 3.1 */ # define _X_DEPRECATED #endif /* requires xproto >= 7.0.30 */ #if __has_extension(attribute_deprecated_with_message) || \ (defined(__GNUC__) && ((__GNUC__ >= 5) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)))) # define _X_DEPRECATED_MSG(_msg) __attribute__((deprecated(_msg))) #else # define _X_DEPRECATED_MSG(_msg) _X_DEPRECATED #endif /* requires xproto >= 7.0.17 */ #if __has_attribute(noreturn) \ || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 205)) \ || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)) # define _X_NORETURN __attribute((noreturn)) #else # define _X_NORETURN #endif /* GNUC */ /* Added in X11R6.9, so available in any version of modular xproto */ #if __has_attribute(__format__) \ || defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 203) # define _X_ATTRIBUTE_PRINTF(x,y) __attribute__((__format__(__printf__,x,y))) #else /* not gcc >= 2.3 */ # define _X_ATTRIBUTE_PRINTF(x,y) #endif /* requires xproto >= 7.0.22 - since this uses either gcc or C99 variable argument macros, must be only used inside #ifdef _X_NONNULL guards, as many legacy X clients are compiled in C89 mode still. */ #if __has_attribute(nonnull) \ && defined(__STDC_VERSION__) && (__STDC_VERSION__ - 0 >= 199901L) /* C99 */ #define _X_NONNULL(...) __attribute__((nonnull(__VA_ARGS__))) #elif __has_attribute(nonnull) \ || defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 303) #define _X_NONNULL(args...) __attribute__((nonnull(args))) #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ - 0 >= 199901L) /* C99 */ #define _X_NONNULL(...) /* */ #endif /* requires xproto >= 7.0.22 */ #if __has_attribute(__unused__) \ || defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 205) #define _X_UNUSED __attribute__((__unused__)) #else #define _X_UNUSED /* */ #endif /* C99 keyword "inline" or equivalent extensions in pre-C99 compilers */ /* requires xproto >= 7.0.9 (introduced in 7.0.8 but didn't support all compilers until 7.0.9) */ #if defined(inline) /* assume autoconf set it correctly */ || \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ - 0 >= 199901L)) /* C99 */ || \ (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550)) # define _X_INLINE inline #elif defined(__GNUC__) && !defined(__STRICT_ANSI__) /* gcc w/C89+extensions */ # define _X_INLINE __inline__ #else # define _X_INLINE #endif /* C99 keyword "restrict" or equivalent extensions in pre-C99 compilers */ /* requires xproto >= 7.0.21 */ #ifndef _X_RESTRICT_KYWD # if defined(restrict) /* assume autoconf set it correctly */ || \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ - 0 >= 199901L) /* C99 */ \ && !defined(__cplusplus)) /* Workaround g++ issue on Solaris */ # define _X_RESTRICT_KYWD restrict # elif defined(__GNUC__) && !defined(__STRICT_ANSI__) /* gcc w/C89+extensions */ # define _X_RESTRICT_KYWD __restrict__ # else # define _X_RESTRICT_KYWD # endif #endif /* requires xproto >= 7.0.30 */ #if __has_attribute(no_sanitize_thread) # define _X_NOTSAN __attribute__((no_sanitize_thread)) #else # define _X_NOTSAN #endif #endif /* _XFUNCPROTO_H_ */ X11/Xwinsock.h000064400000004325151027430550007101 0ustar00/* Copyright 1996, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABIL- ITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * This header file has for sole purpose to allow to include winsock.h * without getting any name conflicts with our code. * Conflicts come from the fact that including winsock.h actually pulls * in the whole Windows API... */ #undef _XFree86Server #ifdef XFree86Server # define _XFree86Server # undef XFree86Server #endif /* * mingw-w64 headers define BOOL as a typedef, protecting against macros * mingw.org headers define BOOL in terms of WINBOOL * ... so try to come up with something which works with both :-) */ #define _NO_BOOL_TYPEDEF #define BOOL WINBOOL #define INT32 wINT32 #undef Status #define Status wStatus #define ATOM wATOM #define BYTE wBYTE #define FreeResource wFreeResource #include #undef Status #define Status int #undef BYTE #undef BOOL #undef INT32 #undef ATOM #undef FreeResource #undef CreateWindowA #undef RT_FONT #undef RT_CURSOR /* * Older version of this header used to name the windows API bool type wBOOL, * rather than more standard name WINBOOL */ #define wBOOL WINBOOL #ifdef _XFree86Server # define XFree86Server # undef _XFree86Server #endif X11/ap_keysym.h000064400000004365151027430550007301 0ustar00/****************************************************************** Copyright 1987 by Apollo Computer Inc., Chelmsford, Massachusetts. Copyright 1989 by Hewlett-Packard Company. All Rights Reserved Permission to use, duplicate, change, and distribute this software and its documentation for any purpose and without fee is granted, provided that the above copyright notice appear in such copy and that this copyright notice appear in all supporting documentation, and that the names of Apollo Computer Inc., the Hewlett-Packard Company, or the X Consortium not be used in advertising or publicity pertaining to distribution of the software without written prior permission. HEWLETT-PACKARD MAKES NO WARRANTY OF ANY KIND WITH REGARD TO THIS SOFWARE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Hewlett-Packard shall not be liable for errors contained herein or direct, indirect, special, incidental or consequential damages in connection with the furnishing, performance, or use of this material. This software is not subject to any license of the American Telephone and Telegraph Company or of the Regents of the University of California. ******************************************************************/ #define apXK_LineDel 0x1000FF00 #define apXK_CharDel 0x1000FF01 #define apXK_Copy 0x1000FF02 #define apXK_Cut 0x1000FF03 #define apXK_Paste 0x1000FF04 #define apXK_Move 0x1000FF05 #define apXK_Grow 0x1000FF06 #define apXK_Cmd 0x1000FF07 #define apXK_Shell 0x1000FF08 #define apXK_LeftBar 0x1000FF09 #define apXK_RightBar 0x1000FF0A #define apXK_LeftBox 0x1000FF0B #define apXK_RightBox 0x1000FF0C #define apXK_UpBox 0x1000FF0D #define apXK_DownBox 0x1000FF0E #define apXK_Pop 0x1000FF0F #define apXK_Read 0x1000FF10 #define apXK_Edit 0x1000FF11 #define apXK_Save 0x1000FF12 #define apXK_Exit 0x1000FF13 #define apXK_Repeat 0x1000FF14 #define apXK_KP_parenleft 0x1000FFA8 #define apXK_KP_parenright 0x1000FFA9 X11/Xatom.h000064400000004726151027430550006371 0ustar00#ifndef XATOM_H #define XATOM_H 1 /* THIS IS A GENERATED FILE * * Do not change! Changing this file implies a protocol change! */ #define XA_PRIMARY ((Atom) 1) #define XA_SECONDARY ((Atom) 2) #define XA_ARC ((Atom) 3) #define XA_ATOM ((Atom) 4) #define XA_BITMAP ((Atom) 5) #define XA_CARDINAL ((Atom) 6) #define XA_COLORMAP ((Atom) 7) #define XA_CURSOR ((Atom) 8) #define XA_CUT_BUFFER0 ((Atom) 9) #define XA_CUT_BUFFER1 ((Atom) 10) #define XA_CUT_BUFFER2 ((Atom) 11) #define XA_CUT_BUFFER3 ((Atom) 12) #define XA_CUT_BUFFER4 ((Atom) 13) #define XA_CUT_BUFFER5 ((Atom) 14) #define XA_CUT_BUFFER6 ((Atom) 15) #define XA_CUT_BUFFER7 ((Atom) 16) #define XA_DRAWABLE ((Atom) 17) #define XA_FONT ((Atom) 18) #define XA_INTEGER ((Atom) 19) #define XA_PIXMAP ((Atom) 20) #define XA_POINT ((Atom) 21) #define XA_RECTANGLE ((Atom) 22) #define XA_RESOURCE_MANAGER ((Atom) 23) #define XA_RGB_COLOR_MAP ((Atom) 24) #define XA_RGB_BEST_MAP ((Atom) 25) #define XA_RGB_BLUE_MAP ((Atom) 26) #define XA_RGB_DEFAULT_MAP ((Atom) 27) #define XA_RGB_GRAY_MAP ((Atom) 28) #define XA_RGB_GREEN_MAP ((Atom) 29) #define XA_RGB_RED_MAP ((Atom) 30) #define XA_STRING ((Atom) 31) #define XA_VISUALID ((Atom) 32) #define XA_WINDOW ((Atom) 33) #define XA_WM_COMMAND ((Atom) 34) #define XA_WM_HINTS ((Atom) 35) #define XA_WM_CLIENT_MACHINE ((Atom) 36) #define XA_WM_ICON_NAME ((Atom) 37) #define XA_WM_ICON_SIZE ((Atom) 38) #define XA_WM_NAME ((Atom) 39) #define XA_WM_NORMAL_HINTS ((Atom) 40) #define XA_WM_SIZE_HINTS ((Atom) 41) #define XA_WM_ZOOM_HINTS ((Atom) 42) #define XA_MIN_SPACE ((Atom) 43) #define XA_NORM_SPACE ((Atom) 44) #define XA_MAX_SPACE ((Atom) 45) #define XA_END_SPACE ((Atom) 46) #define XA_SUPERSCRIPT_X ((Atom) 47) #define XA_SUPERSCRIPT_Y ((Atom) 48) #define XA_SUBSCRIPT_X ((Atom) 49) #define XA_SUBSCRIPT_Y ((Atom) 50) #define XA_UNDERLINE_POSITION ((Atom) 51) #define XA_UNDERLINE_THICKNESS ((Atom) 52) #define XA_STRIKEOUT_ASCENT ((Atom) 53) #define XA_STRIKEOUT_DESCENT ((Atom) 54) #define XA_ITALIC_ANGLE ((Atom) 55) #define XA_X_HEIGHT ((Atom) 56) #define XA_QUAD_WIDTH ((Atom) 57) #define XA_WEIGHT ((Atom) 58) #define XA_POINT_SIZE ((Atom) 59) #define XA_RESOLUTION ((Atom) 60) #define XA_COPYRIGHT ((Atom) 61) #define XA_NOTICE ((Atom) 62) #define XA_FONT_NAME ((Atom) 63) #define XA_FAMILY_NAME ((Atom) 64) #define XA_FULL_NAME ((Atom) 65) #define XA_CAP_HEIGHT ((Atom) 66) #define XA_WM_CLASS ((Atom) 67) #define XA_WM_TRANSIENT_FOR ((Atom) 68) #define XA_LAST_PREDEFINED ((Atom) 68) #endif /* XATOM_H */ X11/ImUtil.h000064400000000713151027430550006474 0ustar00 #ifndef _X11_IMUTIL_H_ #define _X11_IMUTIL_H_ extern int _XGetScanlinePad( Display *dpy, int depth); extern int _XGetBitsPerPixel( Display *dpy, int depth); extern int _XSetImage( XImage *srcimg, register XImage *dstimg, register int x, register int y); extern int _XReverse_Bytes( register unsigned char *bpt, register int nb); extern void _XInitImageFuncPtrs( register XImage *image); #endif /* _X11_IMUTIL_H_ */ X11/XKBlib.h000064400000074423151027430550006415 0ustar00/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _X11_XKBLIB_H_ #define _X11_XKBLIB_H_ #include #include typedef struct _XkbAnyEvent { int type; /* XkbAnyEvent */ unsigned long serial; /* # of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XKB event minor code */ unsigned int device; /* device ID */ } XkbAnyEvent; typedef struct _XkbNewKeyboardNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbNewKeyboardNotify */ int device; /* device ID */ int old_device; /* device ID of previous keyboard */ int min_key_code; /* minimum key code */ int max_key_code; /* maximum key code */ int old_min_key_code;/* min key code of previous kbd */ int old_max_key_code;/* max key code of previous kbd */ unsigned int changed; /* changed aspects of the keyboard */ char req_major; /* major and minor opcode of req */ char req_minor; /* that caused change, if applicable */ } XkbNewKeyboardNotifyEvent; typedef struct _XkbMapNotifyEvent { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbMapNotify */ int device; /* device ID */ unsigned int changed; /* fields which have been changed */ unsigned int flags; /* reserved */ int first_type; /* first changed key type */ int num_types; /* number of changed key types */ KeyCode min_key_code; KeyCode max_key_code; KeyCode first_key_sym; KeyCode first_key_act; KeyCode first_key_behavior; KeyCode first_key_explicit; KeyCode first_modmap_key; KeyCode first_vmodmap_key; int num_key_syms; int num_key_acts; int num_key_behaviors; int num_key_explicit; int num_modmap_keys; int num_vmodmap_keys; unsigned int vmods; /* mask of changed virtual mods */ } XkbMapNotifyEvent; typedef struct _XkbStateNotifyEvent { int type; /* XkbAnyEvent */ unsigned long serial; /* # of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbStateNotify */ int device; /* device ID */ unsigned int changed; /* mask of changed state components */ int group; /* keyboard group */ int base_group; /* base keyboard group */ int latched_group; /* latched keyboard group */ int locked_group; /* locked keyboard group */ unsigned int mods; /* modifier state */ unsigned int base_mods; /* base modifier state */ unsigned int latched_mods; /* latched modifiers */ unsigned int locked_mods; /* locked modifiers */ int compat_state; /* compatibility state */ unsigned char grab_mods; /* mods used for grabs */ unsigned char compat_grab_mods;/* grab mods for non-XKB clients */ unsigned char lookup_mods; /* mods sent to clients */ unsigned char compat_lookup_mods; /* mods sent to non-XKB clients */ int ptr_buttons; /* pointer button state */ KeyCode keycode; /* keycode that caused the change */ char event_type; /* KeyPress or KeyRelease */ char req_major; /* Major opcode of request */ char req_minor; /* Minor opcode of request */ } XkbStateNotifyEvent; typedef struct _XkbControlsNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbControlsNotify */ int device; /* device ID */ unsigned int changed_ctrls; /* controls with changed sub-values */ unsigned int enabled_ctrls; /* controls currently enabled */ unsigned int enabled_ctrl_changes;/* controls just {en,dis}abled */ int num_groups; /* total groups on keyboard */ KeyCode keycode; /* key that caused change or 0 */ char event_type; /* type of event that caused change */ char req_major; /* if keycode==0, major and minor */ char req_minor; /* opcode of req that caused change */ } XkbControlsNotifyEvent; typedef struct _XkbIndicatorNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbIndicatorNotify */ int device; /* device ID */ unsigned int changed; /* indicators with new state or map */ unsigned int state; /* current state of all indicators */ } XkbIndicatorNotifyEvent; typedef struct _XkbNamesNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbNamesNotify */ int device; /* device ID */ unsigned int changed; /* names that have changed */ int first_type; /* first key type with new name */ int num_types; /* number of key types with new names */ int first_lvl; /* first key type new new level names */ int num_lvls; /* # of key types w/new level names */ int num_aliases; /* total number of key aliases*/ int num_radio_groups;/* total number of radio groups */ unsigned int changed_vmods; /* virtual modifiers with new names */ unsigned int changed_groups; /* groups with new names */ unsigned int changed_indicators;/* indicators with new names */ int first_key; /* first key with new name */ int num_keys; /* number of keys with new names */ } XkbNamesNotifyEvent; typedef struct _XkbCompatMapNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbCompatMapNotify */ int device; /* device ID */ unsigned int changed_groups; /* groups with new compat maps */ int first_si; /* first new symbol interp */ int num_si; /* number of new symbol interps */ int num_total_si; /* total # of symbol interps */ } XkbCompatMapNotifyEvent; typedef struct _XkbBellNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbBellNotify */ int device; /* device ID */ int percent; /* requested volume as a % of maximum */ int pitch; /* requested pitch in Hz */ int duration; /* requested duration in useconds */ int bell_class; /* (input extension) feedback class */ int bell_id; /* (input extension) ID of feedback */ Atom name; /* "name" of requested bell */ Window window; /* window associated with event */ Bool event_only; /* "event only" requested */ } XkbBellNotifyEvent; typedef struct _XkbActionMessage { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbActionMessage */ int device; /* device ID */ KeyCode keycode; /* key that generated the event */ Bool press; /* true if act caused by key press */ Bool key_event_follows;/* true if key event also generated */ int group; /* effective group */ unsigned int mods; /* effective mods */ char message[XkbActionMessageLength+1]; /* message -- leave space for NUL */ } XkbActionMessageEvent; typedef struct _XkbAccessXNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbAccessXNotify */ int device; /* device ID */ int detail; /* XkbAXN_* */ int keycode; /* key of event */ int sk_delay; /* current slow keys delay */ int debounce_delay; /* current debounce delay */ } XkbAccessXNotifyEvent; typedef struct _XkbExtensionDeviceNotify { int type; /* XkbAnyEvent */ unsigned long serial; /* of last req processed by server */ Bool send_event; /* is this from a SendEvent request? */ Display * display; /* Display the event was read from */ Time time; /* milliseconds */ int xkb_type; /* XkbExtensionDeviceNotify */ int device; /* device ID */ unsigned int reason; /* reason for the event */ unsigned int supported; /* mask of supported features */ unsigned int unsupported; /* mask of unsupported features */ /* that some app tried to use */ int first_btn; /* first button that changed */ int num_btns; /* range of buttons changed */ unsigned int leds_defined; /* indicators with names or maps */ unsigned int led_state; /* current state of the indicators */ int led_class; /* feedback class for led changes */ int led_id; /* feedback id for led changes */ } XkbExtensionDeviceNotifyEvent; typedef union _XkbEvent { int type; XkbAnyEvent any; XkbNewKeyboardNotifyEvent new_kbd; XkbMapNotifyEvent map; XkbStateNotifyEvent state; XkbControlsNotifyEvent ctrls; XkbIndicatorNotifyEvent indicators; XkbNamesNotifyEvent names; XkbCompatMapNotifyEvent compat; XkbBellNotifyEvent bell; XkbActionMessageEvent message; XkbAccessXNotifyEvent accessx; XkbExtensionDeviceNotifyEvent device; XEvent core; } XkbEvent; typedef struct _XkbKbdDpyState XkbKbdDpyStateRec,*XkbKbdDpyStatePtr; /* XkbOpenDisplay error codes */ #define XkbOD_Success 0 #define XkbOD_BadLibraryVersion 1 #define XkbOD_ConnectionRefused 2 #define XkbOD_NonXkbServer 3 #define XkbOD_BadServerVersion 4 /* Values for XlibFlags */ #define XkbLC_ForceLatin1Lookup (1<<0) #define XkbLC_ConsumeLookupMods (1<<1) #define XkbLC_AlwaysConsumeShiftAndLock (1<<2) #define XkbLC_IgnoreNewKeyboards (1<<3) #define XkbLC_ControlFallback (1<<4) #define XkbLC_ConsumeKeysOnComposeFail (1<<29) #define XkbLC_ComposeLED (1<<30) #define XkbLC_BeepOnComposeFail (1<<31) #define XkbLC_AllComposeControls (0xc0000000) #define XkbLC_AllControls (0xc000001f) _XFUNCPROTOBEGIN extern Bool XkbIgnoreExtension( Bool /* ignore */ ); extern Display *XkbOpenDisplay( char * /* name */, int * /* ev_rtrn */, int * /* err_rtrn */, int * /* major_rtrn */, int * /* minor_rtrn */, int * /* reason */ ); extern Bool XkbQueryExtension( Display * /* dpy */, int * /* opcodeReturn */, int * /* eventBaseReturn */, int * /* errorBaseReturn */, int * /* majorRtrn */, int * /* minorRtrn */ ); extern Bool XkbUseExtension( Display * /* dpy */, int * /* major_rtrn */, int * /* minor_rtrn */ ); extern Bool XkbLibraryVersion( int * /* libMajorRtrn */, int * /* libMinorRtrn */ ); extern unsigned int XkbSetXlibControls( Display* /* dpy */, unsigned int /* affect */, unsigned int /* values */ ); extern unsigned int XkbGetXlibControls( Display* /* dpy */ ); extern unsigned int XkbXlibControlsImplemented(void); typedef Atom (*XkbInternAtomFunc)( Display * /* dpy */, _Xconst char * /* name */, Bool /* only_if_exists */ ); typedef char * (*XkbGetAtomNameFunc)( Display * /* dpy */, Atom /* atom */ ); extern void XkbSetAtomFuncs( XkbInternAtomFunc /* getAtom */, XkbGetAtomNameFunc /* getName */ ); extern KeySym XkbKeycodeToKeysym( Display * /* dpy */, #if NeedWidePrototypes unsigned int /* kc */, #else KeyCode /* kc */, #endif int /* group */, int /* level */ ); extern unsigned int XkbKeysymToModifiers( Display * /* dpy */, KeySym /* ks */ ); extern Bool XkbLookupKeySym( Display * /* dpy */, KeyCode /* keycode */, unsigned int /* modifiers */, unsigned int * /* modifiers_return */, KeySym * /* keysym_return */ ); extern int XkbLookupKeyBinding( Display * /* dpy */, KeySym /* sym_rtrn */, unsigned int /* mods */, char * /* buffer */, int /* nbytes */, int * /* extra_rtrn */ ); extern Bool XkbTranslateKeyCode( XkbDescPtr /* xkb */, KeyCode /* keycode */, unsigned int /* modifiers */, unsigned int * /* modifiers_return */, KeySym * /* keysym_return */ ); extern int XkbTranslateKeySym( Display * /* dpy */, register KeySym * /* sym_return */, unsigned int /* modifiers */, char * /* buffer */, int /* nbytes */, int * /* extra_rtrn */ ); extern Bool XkbSetAutoRepeatRate( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* delay */, unsigned int /* interval */ ); extern Bool XkbGetAutoRepeatRate( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int * /* delayRtrn */, unsigned int * /* intervalRtrn */ ); extern Bool XkbChangeEnabledControls( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* affect */, unsigned int /* values */ ); extern Bool XkbDeviceBell( Display * /* dpy */, Window /* win */, int /* deviceSpec */, int /* bellClass */, int /* bellID */, int /* percent */, Atom /* name */ ); extern Bool XkbForceDeviceBell( Display * /* dpy */, int /* deviceSpec */, int /* bellClass */, int /* bellID */, int /* percent */ ); extern Bool XkbDeviceBellEvent( Display * /* dpy */, Window /* win */, int /* deviceSpec */, int /* bellClass */, int /* bellID */, int /* percent */, Atom /* name */ ); extern Bool XkbBell( Display * /* dpy */, Window /* win */, int /* percent */, Atom /* name */ ); extern Bool XkbForceBell( Display * /* dpy */, int /* percent */ ); extern Bool XkbBellEvent( Display * /* dpy */, Window /* win */, int /* percent */, Atom /* name */ ); extern Bool XkbSelectEvents( Display * /* dpy */, unsigned int /* deviceID */, unsigned int /* affect */, unsigned int /* values */ ); extern Bool XkbSelectEventDetails( Display * /* dpy */, unsigned int /* deviceID */, unsigned int /* eventType */, unsigned long /* affect */, unsigned long /* details */ ); extern void XkbNoteMapChanges( XkbMapChangesPtr /* old */, XkbMapNotifyEvent * /* new */, unsigned int /* wanted */ ); extern void XkbNoteNameChanges( XkbNameChangesPtr /* old */, XkbNamesNotifyEvent * /* new */, unsigned int /* wanted */ ); extern Status XkbGetIndicatorState( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int * /* pStateRtrn */ ); extern Status XkbGetDeviceIndicatorState( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* ledClass */, unsigned int /* ledID */, unsigned int * /* pStateRtrn */ ); extern Status XkbGetIndicatorMap( Display * /* dpy */, unsigned long /* which */, XkbDescPtr /* desc */ ); extern Bool XkbSetIndicatorMap( Display * /* dpy */, unsigned long /* which */, XkbDescPtr /* desc */ ); #define XkbNoteIndicatorMapChanges(o,n,w) \ ((o)->map_changes|=((n)->map_changes&(w))) #define XkbNoteIndicatorStateChanges(o,n,w)\ ((o)->state_changes|=((n)->state_changes&(w))) #define XkbGetIndicatorMapChanges(d,x,c) \ (XkbGetIndicatorMap((d),(c)->map_changes,x)) #define XkbChangeIndicatorMaps(d,x,c) \ (XkbSetIndicatorMap((d),(c)->map_changes,x)) extern Bool XkbGetNamedIndicator( Display * /* dpy */, Atom /* name */, int * /* pNdxRtrn */, Bool * /* pStateRtrn */, XkbIndicatorMapPtr /* pMapRtrn */, Bool * /* pRealRtrn */ ); extern Bool XkbGetNamedDeviceIndicator( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* ledClass */, unsigned int /* ledID */, Atom /* name */, int * /* pNdxRtrn */, Bool * /* pStateRtrn */, XkbIndicatorMapPtr /* pMapRtrn */, Bool * /* pRealRtrn */ ); extern Bool XkbSetNamedIndicator( Display * /* dpy */, Atom /* name */, Bool /* changeState */, Bool /* state */, Bool /* createNewMap */, XkbIndicatorMapPtr /* pMap */ ); extern Bool XkbSetNamedDeviceIndicator( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* ledClass */, unsigned int /* ledID */, Atom /* name */, Bool /* changeState */, Bool /* state */, Bool /* createNewMap */, XkbIndicatorMapPtr /* pMap */ ); extern Bool XkbLockModifiers( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* affect */, unsigned int /* values */ ); extern Bool XkbLatchModifiers( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* affect */, unsigned int /* values */ ); extern Bool XkbLockGroup( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* group */ ); extern Bool XkbLatchGroup( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* group */ ); extern Bool XkbSetServerInternalMods( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* affectReal */, unsigned int /* realValues */, unsigned int /* affectVirtual */, unsigned int /* virtualValues */ ); extern Bool XkbSetIgnoreLockMods( Display * /* dpy */, unsigned int /* deviceSpec */, unsigned int /* affectReal */, unsigned int /* realValues */, unsigned int /* affectVirtual */, unsigned int /* virtualValues */ ); extern Bool XkbVirtualModsToReal( XkbDescPtr /* xkb */, unsigned int /* virtual_mask */, unsigned int * /* mask_rtrn */ ); extern Bool XkbComputeEffectiveMap( XkbDescPtr /* xkb */, XkbKeyTypePtr /* type */, unsigned char * /* map_rtrn */ ); extern Status XkbInitCanonicalKeyTypes( XkbDescPtr /* xkb */, unsigned int /* which */, int /* keypadVMod */ ); extern XkbDescPtr XkbAllocKeyboard( void ); extern void XkbFreeKeyboard( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeDesc */ ); extern Status XkbAllocClientMap( XkbDescPtr /* xkb */, unsigned int /* which */, unsigned int /* nTypes */ ); extern Status XkbAllocServerMap( XkbDescPtr /* xkb */, unsigned int /* which */, unsigned int /* nActions */ ); extern void XkbFreeClientMap( XkbDescPtr /* xkb */, unsigned int /* what */, Bool /* freeMap */ ); extern void XkbFreeServerMap( XkbDescPtr /* xkb */, unsigned int /* what */, Bool /* freeMap */ ); extern XkbKeyTypePtr XkbAddKeyType( XkbDescPtr /* xkb */, Atom /* name */, int /* map_count */, Bool /* want_preserve */, int /* num_lvls */ ); extern Status XkbAllocIndicatorMaps( XkbDescPtr /* xkb */ ); extern void XkbFreeIndicatorMaps( XkbDescPtr /* xkb */ ); extern XkbDescPtr XkbGetMap( Display * /* dpy */, unsigned int /* which */, unsigned int /* deviceSpec */ ); extern Status XkbGetUpdatedMap( Display * /* dpy */, unsigned int /* which */, XkbDescPtr /* desc */ ); extern Status XkbGetMapChanges( Display * /* dpy */, XkbDescPtr /* xkb */, XkbMapChangesPtr /* changes */ ); extern Status XkbRefreshKeyboardMapping( XkbMapNotifyEvent * /* event */ ); extern Status XkbGetKeyTypes( Display * /* dpy */, unsigned int /* first */, unsigned int /* num */, XkbDescPtr /* xkb */ ); extern Status XkbGetKeySyms( Display * /* dpy */, unsigned int /* first */, unsigned int /* num */, XkbDescPtr /* xkb */ ); extern Status XkbGetKeyActions( Display * /* dpy */, unsigned int /* first */, unsigned int /* num */, XkbDescPtr /* xkb */ ); extern Status XkbGetKeyBehaviors( Display * /* dpy */, unsigned int /* firstKey */, unsigned int /* nKeys */, XkbDescPtr /* desc */ ); extern Status XkbGetVirtualMods( Display * /* dpy */, unsigned int /* which */, XkbDescPtr /* desc */ ); extern Status XkbGetKeyExplicitComponents( Display * /* dpy */, unsigned int /* firstKey */, unsigned int /* nKeys */, XkbDescPtr /* desc */ ); extern Status XkbGetKeyModifierMap( Display * /* dpy */, unsigned int /* firstKey */, unsigned int /* nKeys */, XkbDescPtr /* desc */ ); extern Status XkbGetKeyVirtualModMap( Display * /* dpy */, unsigned int /* first */, unsigned int /* num */, XkbDescPtr /* xkb */ ); extern Status XkbAllocControls( XkbDescPtr /* xkb */, unsigned int /* which*/ ); extern void XkbFreeControls( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeMap */ ); extern Status XkbGetControls( Display * /* dpy */, unsigned long /* which */, XkbDescPtr /* desc */ ); extern Bool XkbSetControls( Display * /* dpy */, unsigned long /* which */, XkbDescPtr /* desc */ ); extern void XkbNoteControlsChanges( XkbControlsChangesPtr /* old */, XkbControlsNotifyEvent * /* new */, unsigned int /* wanted */ ); #define XkbGetControlsChanges(d,x,c) XkbGetControls(d,(c)->changed_ctrls,x) #define XkbChangeControls(d,x,c) XkbSetControls(d,(c)->changed_ctrls,x) extern Status XkbAllocCompatMap( XkbDescPtr /* xkb */, unsigned int /* which */, unsigned int /* nInterpret */ ); extern void XkbFreeCompatMap( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeMap */ ); extern Status XkbGetCompatMap( Display * /* dpy */, unsigned int /* which */, XkbDescPtr /* xkb */ ); extern Bool XkbSetCompatMap( Display * /* dpy */, unsigned int /* which */, XkbDescPtr /* xkb */, Bool /* updateActions */ ); extern XkbSymInterpretPtr XkbAddSymInterpret( XkbDescPtr /* xkb */, XkbSymInterpretPtr /* si */, Bool /* updateMap */, XkbChangesPtr /* changes */ ); extern Status XkbAllocNames( XkbDescPtr /* xkb */, unsigned int /* which */, int /* nTotalRG */, int /* nTotalAliases */ ); extern Status XkbGetNames( Display * /* dpy */, unsigned int /* which */, XkbDescPtr /* desc */ ); extern Bool XkbSetNames( Display * /* dpy */, unsigned int /* which */, unsigned int /* firstType */, unsigned int /* nTypes */, XkbDescPtr /* desc */ ); extern Bool XkbChangeNames( Display * /* dpy */, XkbDescPtr /* xkb */, XkbNameChangesPtr /* changes */ ); extern void XkbFreeNames( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeMap */ ); extern Status XkbGetState( Display * /* dpy */, unsigned int /* deviceSpec */, XkbStatePtr /* rtrnState */ ); extern Bool XkbSetMap( Display * /* dpy */, unsigned int /* which */, XkbDescPtr /* desc */ ); extern Bool XkbChangeMap( Display* /* dpy */, XkbDescPtr /* desc */, XkbMapChangesPtr /* changes */ ); extern Bool XkbSetDetectableAutoRepeat( Display * /* dpy */, Bool /* detectable */, Bool * /* supported */ ); extern Bool XkbGetDetectableAutoRepeat( Display * /* dpy */, Bool * /* supported */ ); extern Bool XkbSetAutoResetControls( Display * /* dpy */, unsigned int /* changes */, unsigned int * /* auto_ctrls */, unsigned int * /* auto_values */ ); extern Bool XkbGetAutoResetControls( Display * /* dpy */, unsigned int * /* auto_ctrls */, unsigned int * /* auto_ctrl_values */ ); extern Bool XkbSetPerClientControls( Display * /* dpy */, unsigned int /* change */, unsigned int * /* values */ ); extern Bool XkbGetPerClientControls( Display * /* dpy */, unsigned int * /* ctrls */ ); extern Status XkbCopyKeyType( XkbKeyTypePtr /* from */, XkbKeyTypePtr /* into */ ); extern Status XkbCopyKeyTypes( XkbKeyTypePtr /* from */, XkbKeyTypePtr /* into */, int /* num_types */ ); extern Status XkbResizeKeyType( XkbDescPtr /* xkb */, int /* type_ndx */, int /* map_count */, Bool /* want_preserve */, int /* new_num_lvls */ ); extern KeySym *XkbResizeKeySyms( XkbDescPtr /* desc */, int /* forKey */, int /* symsNeeded */ ); extern XkbAction *XkbResizeKeyActions( XkbDescPtr /* desc */, int /* forKey */, int /* actsNeeded */ ); extern Status XkbChangeTypesOfKey( XkbDescPtr /* xkb */, int /* key */, int /* num_groups */, unsigned int /* groups */, int * /* newTypes */, XkbMapChangesPtr /* pChanges */ ); extern Status XkbChangeKeycodeRange( XkbDescPtr /* xkb */, int /* minKC */, int /* maxKC */, XkbChangesPtr /* changes */ ); /***====================================================================***/ extern XkbComponentListPtr XkbListComponents( Display * /* dpy */, unsigned int /* deviceSpec */, XkbComponentNamesPtr /* ptrns */, int * /* max_inout */ ); extern void XkbFreeComponentList( XkbComponentListPtr /* list */ ); extern XkbDescPtr XkbGetKeyboard( Display * /* dpy */, unsigned int /* which */, unsigned int /* deviceSpec */ ); extern XkbDescPtr XkbGetKeyboardByName( Display * /* dpy */, unsigned int /* deviceSpec */, XkbComponentNamesPtr /* names */, unsigned int /* want */, unsigned int /* need */, Bool /* load */ ); /***====================================================================***/ extern int XkbKeyTypesForCoreSymbols( /* returns # of groups */ XkbDescPtr /* xkb */, /* keyboard device */ int /* map_width */, /* width of core KeySym array */ KeySym * /* core_syms */, /* always mapWidth symbols */ unsigned int /* protected */, /* explicit key types */ int * /* types_inout */, /* always four type indices */ KeySym * /* xkb_syms_rtrn */ /* must have enough space */ ); extern Bool XkbApplyCompatMapToKey( /* False only on error */ XkbDescPtr /* xkb */, /* keymap to be edited */ KeyCode /* key */, /* key to be updated */ XkbChangesPtr /* changes */ /* resulting changes to map */ ); extern Bool XkbUpdateMapFromCore( /* False only on error */ XkbDescPtr /* xkb */, /* XKB keyboard to be edited */ KeyCode /* first_key */, /* first changed key */ int /* num_keys */, /* number of changed keys */ int /* map_width */, /* width of core keymap */ KeySym * /* core_keysyms */, /* symbols from core keymap */ XkbChangesPtr /* changes */ /* resulting changes */ ); /***====================================================================***/ extern XkbDeviceLedInfoPtr XkbAddDeviceLedInfo( XkbDeviceInfoPtr /* devi */, unsigned int /* ledClass */, unsigned int /* ledId */ ); extern Status XkbResizeDeviceButtonActions( XkbDeviceInfoPtr /* devi */, unsigned int /* newTotal */ ); extern XkbDeviceInfoPtr XkbAllocDeviceInfo( unsigned int /* deviceSpec */, unsigned int /* nButtons */, unsigned int /* szLeds */ ); extern void XkbFreeDeviceInfo( XkbDeviceInfoPtr /* devi */, unsigned int /* which */, Bool /* freeDevI */ ); extern void XkbNoteDeviceChanges( XkbDeviceChangesPtr /* old */, XkbExtensionDeviceNotifyEvent * /* new */, unsigned int /* wanted */ ); extern XkbDeviceInfoPtr XkbGetDeviceInfo( Display * /* dpy */, unsigned int /* which */, unsigned int /* deviceSpec */, unsigned int /* ledClass */, unsigned int /* ledID */ ); extern Status XkbGetDeviceInfoChanges( Display * /* dpy */, XkbDeviceInfoPtr /* devi */, XkbDeviceChangesPtr /* changes */ ); extern Status XkbGetDeviceButtonActions( Display * /* dpy */, XkbDeviceInfoPtr /* devi */, Bool /* all */, unsigned int /* first */, unsigned int /* nBtns */ ); extern Status XkbGetDeviceLedInfo( Display * /* dpy */, XkbDeviceInfoPtr /* devi */, unsigned int /* ledClass (class, XIDflt, XIAll) */, unsigned int /* ledId (id, XIDflt, XIAll) */, unsigned int /* which (XkbXI_Indicator{Names,Map}Mask */ ); extern Bool XkbSetDeviceInfo( Display * /* dpy */, unsigned int /* which */, XkbDeviceInfoPtr /* devi */ ); extern Bool XkbChangeDeviceInfo( Display* /* dpy */, XkbDeviceInfoPtr /* desc */, XkbDeviceChangesPtr /* changes */ ); extern Bool XkbSetDeviceLedInfo( Display * /* dpy */, XkbDeviceInfoPtr /* devi */, unsigned int /* ledClass */, unsigned int /* ledID */, unsigned int /* which */ ); extern Bool XkbSetDeviceButtonActions( Display * /* dpy */, XkbDeviceInfoPtr /* devi */, unsigned int /* first */, unsigned int /* nBtns */ ); /***====================================================================***/ extern char XkbToControl( char /* c */ ); /***====================================================================***/ extern Bool XkbSetDebuggingFlags( Display * /* dpy */, unsigned int /* mask */, unsigned int /* flags */, char * /* msg */, unsigned int /* ctrls_mask */, unsigned int /* ctrls */, unsigned int * /* rtrn_flags */, unsigned int * /* rtrn_ctrls */ ); extern Bool XkbApplyVirtualModChanges( XkbDescPtr /* xkb */, unsigned int /* changed */, XkbChangesPtr /* changes */ ); extern Bool XkbUpdateActionVirtualMods( XkbDescPtr /* xkb */, XkbAction * /* act */, unsigned int /* changed */ ); extern void XkbUpdateKeyTypeVirtualMods( XkbDescPtr /* xkb */, XkbKeyTypePtr /* type */, unsigned int /* changed */, XkbChangesPtr /* changes */ ); _XFUNCPROTOEND #endif /* _X11_XKBLIB_H_ */ X11/Xproto.h000064400000146257151027430550006602 0ustar00/* Definitions for the X window system used by server and c bindings */ /* * This packet-construction scheme makes the following assumptions: * * 1. The compiler is able * to generate code which addresses one- and two-byte quantities. * In the worst case, this would be done with bit-fields. If bit-fields * are used it may be necessary to reorder the request fields in this file, * depending on the order in which the machine assigns bit fields to * machine words. There may also be a problem with sign extension, * as K+R specify that bitfields are always unsigned. * * 2. 2- and 4-byte fields in packet structures must be ordered by hand * such that they are naturally-aligned, so that no compiler will ever * insert padding bytes. * * 3. All packets are hand-padded to a multiple of 4 bytes, for * the same reason. */ #ifndef XPROTO_H #define XPROTO_H /*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #include #include /* * Define constants for the sizes of the network packets. The sz_ prefix is * used instead of something more descriptive so that the symbols are no more * than 32 characters in length (which causes problems for some compilers). */ #define sz_xSegment 8 #define sz_xPoint 4 #define sz_xRectangle 8 #define sz_xArc 12 #define sz_xConnClientPrefix 12 #define sz_xConnSetupPrefix 8 #define sz_xConnSetup 32 #define sz_xPixmapFormat 8 #define sz_xDepth 8 #define sz_xVisualType 24 #define sz_xWindowRoot 40 #define sz_xTimecoord 8 #define sz_xHostEntry 4 #define sz_xCharInfo 12 #define sz_xFontProp 8 #define sz_xTextElt 2 #define sz_xColorItem 12 #define sz_xrgb 8 #define sz_xGenericReply 32 #define sz_xGetWindowAttributesReply 44 #define sz_xGetGeometryReply 32 #define sz_xQueryTreeReply 32 #define sz_xInternAtomReply 32 #define sz_xGetAtomNameReply 32 #define sz_xGetPropertyReply 32 #define sz_xListPropertiesReply 32 #define sz_xGetSelectionOwnerReply 32 #define sz_xGrabPointerReply 32 #define sz_xQueryPointerReply 32 #define sz_xGetMotionEventsReply 32 #define sz_xTranslateCoordsReply 32 #define sz_xGetInputFocusReply 32 #define sz_xQueryKeymapReply 40 #define sz_xQueryFontReply 60 #define sz_xQueryTextExtentsReply 32 #define sz_xListFontsReply 32 #define sz_xGetFontPathReply 32 #define sz_xGetImageReply 32 #define sz_xListInstalledColormapsReply 32 #define sz_xAllocColorReply 32 #define sz_xAllocNamedColorReply 32 #define sz_xAllocColorCellsReply 32 #define sz_xAllocColorPlanesReply 32 #define sz_xQueryColorsReply 32 #define sz_xLookupColorReply 32 #define sz_xQueryBestSizeReply 32 #define sz_xQueryExtensionReply 32 #define sz_xListExtensionsReply 32 #define sz_xSetMappingReply 32 #define sz_xGetKeyboardControlReply 52 #define sz_xGetPointerControlReply 32 #define sz_xGetScreenSaverReply 32 #define sz_xListHostsReply 32 #define sz_xSetModifierMappingReply 32 #define sz_xError 32 #define sz_xEvent 32 #define sz_xKeymapEvent 32 #define sz_xReq 4 #define sz_xResourceReq 8 #define sz_xCreateWindowReq 32 #define sz_xChangeWindowAttributesReq 12 #define sz_xChangeSaveSetReq 8 #define sz_xReparentWindowReq 16 #define sz_xConfigureWindowReq 12 #define sz_xCirculateWindowReq 8 #define sz_xInternAtomReq 8 #define sz_xChangePropertyReq 24 #define sz_xDeletePropertyReq 12 #define sz_xGetPropertyReq 24 #define sz_xSetSelectionOwnerReq 16 #define sz_xConvertSelectionReq 24 #define sz_xSendEventReq 44 #define sz_xGrabPointerReq 24 #define sz_xGrabButtonReq 24 #define sz_xUngrabButtonReq 12 #define sz_xChangeActivePointerGrabReq 16 #define sz_xGrabKeyboardReq 16 #define sz_xGrabKeyReq 16 #define sz_xUngrabKeyReq 12 #define sz_xAllowEventsReq 8 #define sz_xGetMotionEventsReq 16 #define sz_xTranslateCoordsReq 16 #define sz_xWarpPointerReq 24 #define sz_xSetInputFocusReq 12 #define sz_xOpenFontReq 12 #define sz_xQueryTextExtentsReq 8 #define sz_xListFontsReq 8 #define sz_xSetFontPathReq 8 #define sz_xCreatePixmapReq 16 #define sz_xCreateGCReq 16 #define sz_xChangeGCReq 12 #define sz_xCopyGCReq 16 #define sz_xSetDashesReq 12 #define sz_xSetClipRectanglesReq 12 #define sz_xCopyAreaReq 28 #define sz_xCopyPlaneReq 32 #define sz_xPolyPointReq 12 #define sz_xPolySegmentReq 12 #define sz_xFillPolyReq 16 #define sz_xPutImageReq 24 #define sz_xGetImageReq 20 #define sz_xPolyTextReq 16 #define sz_xImageTextReq 16 #define sz_xCreateColormapReq 16 #define sz_xCopyColormapAndFreeReq 12 #define sz_xAllocColorReq 16 #define sz_xAllocNamedColorReq 12 #define sz_xAllocColorCellsReq 12 #define sz_xAllocColorPlanesReq 16 #define sz_xFreeColorsReq 12 #define sz_xStoreColorsReq 8 #define sz_xStoreNamedColorReq 16 #define sz_xQueryColorsReq 8 #define sz_xLookupColorReq 12 #define sz_xCreateCursorReq 32 #define sz_xCreateGlyphCursorReq 32 #define sz_xRecolorCursorReq 20 #define sz_xQueryBestSizeReq 12 #define sz_xQueryExtensionReq 8 #define sz_xChangeKeyboardControlReq 8 #define sz_xBellReq 4 #define sz_xChangePointerControlReq 12 #define sz_xSetScreenSaverReq 12 #define sz_xChangeHostsReq 8 #define sz_xListHostsReq 4 #define sz_xChangeModeReq 4 #define sz_xRotatePropertiesReq 12 #define sz_xReply 32 #define sz_xGrabKeyboardReply 32 #define sz_xListFontsWithInfoReply 60 #define sz_xSetPointerMappingReply 32 #define sz_xGetKeyboardMappingReply 32 #define sz_xGetPointerMappingReply 32 #define sz_xGetModifierMappingReply 32 #define sz_xListFontsWithInfoReq 8 #define sz_xPolyLineReq 12 #define sz_xPolyArcReq 12 #define sz_xPolyRectangleReq 12 #define sz_xPolyFillRectangleReq 12 #define sz_xPolyFillArcReq 12 #define sz_xPolyText8Req 16 #define sz_xPolyText16Req 16 #define sz_xImageText8Req 16 #define sz_xImageText16Req 16 #define sz_xSetPointerMappingReq 4 #define sz_xForceScreenSaverReq 4 #define sz_xSetCloseDownModeReq 4 #define sz_xClearAreaReq 16 #define sz_xSetAccessControlReq 4 #define sz_xGetKeyboardMappingReq 8 #define sz_xSetModifierMappingReq 4 #define sz_xPropIconSize 24 #define sz_xChangeKeyboardMappingReq 8 /* For the purpose of the structure definitions in this file, we must redefine the following types in terms of Xmd.h's types, which may include bit fields. All of these are #undef'd at the end of this file, restoring the definitions in X.h. */ #define Window CARD32 #define Drawable CARD32 #define Font CARD32 #define Pixmap CARD32 #define Cursor CARD32 #define Colormap CARD32 #define GContext CARD32 #define Atom CARD32 #define VisualID CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define X_TCP_PORT 6000 /* add display number */ #define xTrue 1 #define xFalse 0 typedef CARD16 KeyButMask; /***************** Connection setup structures. See Chapter 8: Connection Setup of the X Window System Protocol specification for details. *****************/ /* Client initiates handshake with this data, followed by the strings * for the auth protocol & data. */ typedef struct { CARD8 byteOrder; BYTE pad; CARD16 majorVersion, minorVersion; CARD16 nbytesAuthProto; /* Authorization protocol */ CARD16 nbytesAuthString; /* Authorization string */ CARD16 pad2; } xConnClientPrefix; /* Server response to xConnClientPrefix. * * If success == Success, this is followed by xConnSetup and * numRoots xWindowRoot structs. * * If success == Failure, this is followed by a reason string. * * The protocol also defines a case of success == Authenticate, but * that doesn't seem to have ever been implemented by the X Consortium. */ typedef struct { CARD8 success; BYTE lengthReason; /*num bytes in string following if failure */ CARD16 majorVersion, minorVersion; CARD16 length; /* 1/4 additional bytes in setup info */ } xConnSetupPrefix; typedef struct { CARD32 release; CARD32 ridBase, ridMask; CARD32 motionBufferSize; CARD16 nbytesVendor; /* number of bytes in vendor string */ CARD16 maxRequestSize; CARD8 numRoots; /* number of roots structs to follow */ CARD8 numFormats; /* number of pixmap formats */ CARD8 imageByteOrder; /* LSBFirst, MSBFirst */ CARD8 bitmapBitOrder; /* LeastSignificant, MostSign...*/ CARD8 bitmapScanlineUnit, /* 8, 16, 32 */ bitmapScanlinePad; /* 8, 16, 32 */ KeyCode minKeyCode, maxKeyCode; CARD32 pad2; } xConnSetup; typedef struct { CARD8 depth; CARD8 bitsPerPixel; CARD8 scanLinePad; CARD8 pad1; CARD32 pad2; } xPixmapFormat; /* window root */ typedef struct { CARD8 depth; CARD8 pad1; CARD16 nVisuals; /* number of xVisualType structures following */ CARD32 pad2; } xDepth; typedef struct { VisualID visualID; #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 bitsPerRGB; CARD16 colormapEntries; CARD32 redMask, greenMask, blueMask; CARD32 pad; } xVisualType; typedef struct { Window windowId; Colormap defaultColormap; CARD32 whitePixel, blackPixel; CARD32 currentInputMask; CARD16 pixWidth, pixHeight; CARD16 mmWidth, mmHeight; CARD16 minInstalledMaps, maxInstalledMaps; VisualID rootVisualID; CARD8 backingStore; BOOL saveUnders; CARD8 rootDepth; CARD8 nDepths; /* number of xDepth structures following */ } xWindowRoot; /***************************************************************** * Structure Defns * Structures needed for replies *****************************************************************/ /* Used in GetMotionEvents */ typedef struct { CARD32 time; INT16 x, y; } xTimecoord; typedef struct { CARD8 family; BYTE pad; CARD16 length; } xHostEntry; typedef struct { INT16 leftSideBearing, rightSideBearing, characterWidth, ascent, descent; CARD16 attributes; } xCharInfo; typedef struct { Atom name; CARD32 value; } xFontProp; /* * non-aligned big-endian font ID follows this struct */ typedef struct { /* followed by string */ CARD8 len; /* number of *characters* in string, or FontChange (255) for font change, or 0 if just delta given */ INT8 delta; } xTextElt; typedef struct { CARD32 pixel; CARD16 red, green, blue; CARD8 flags; /* DoRed, DoGreen, DoBlue booleans */ CARD8 pad; } xColorItem; typedef struct { CARD16 red, green, blue, pad; } xrgb; typedef CARD8 KEYCODE; /***************** * XRep: * meant to be 32 byte quantity *****************/ /* GenericReply is the common format of all replies. The "data" items are specific to each individual reply type. */ typedef struct { BYTE type; /* X_Reply */ BYTE data1; /* depends on reply type */ CARD16 sequenceNumber; /* of last request received by server */ CARD32 length; /* 4 byte quantities beyond size of GenericReply */ CARD32 data00; CARD32 data01; CARD32 data02; CARD32 data03; CARD32 data04; CARD32 data05; } xGenericReply; /* Individual reply formats. */ typedef struct { BYTE type; /* X_Reply */ CARD8 backingStore; CARD16 sequenceNumber; CARD32 length; /* NOT 0; this is an extra-large reply */ VisualID visualID; #if defined(__cplusplus) || defined(c_plusplus) CARD16 c_class; #else CARD16 class; #endif CARD8 bitGravity; CARD8 winGravity; CARD32 backingBitPlanes; CARD32 backingPixel; BOOL saveUnder; BOOL mapInstalled; CARD8 mapState; BOOL override; Colormap colormap; CARD32 allEventMasks; CARD32 yourEventMask; CARD16 doNotPropagateMask; CARD16 pad; } xGetWindowAttributesReply; typedef struct { BYTE type; /* X_Reply */ CARD8 depth; CARD16 sequenceNumber; CARD32 length; /* 0 */ Window root; INT16 x, y; CARD16 width, height; CARD16 borderWidth; CARD16 pad1; CARD32 pad2; CARD32 pad3; } xGetGeometryReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; Window root, parent; CARD16 nChildren; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xQueryTreeReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ Atom atom; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xInternAtomReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* of additional bytes */ CARD16 nameLength; /* # of characters in name */ CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xGetAtomNameReply; typedef struct { BYTE type; /* X_Reply */ CARD8 format; CARD16 sequenceNumber; CARD32 length; /* of additional bytes */ Atom propertyType; CARD32 bytesAfter; CARD32 nItems; /* # of 8, 16, or 32-bit entities in reply */ CARD32 pad1; CARD32 pad2; CARD32 pad3; } xGetPropertyReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nProperties; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xListPropertiesReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ Window owner; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetSelectionOwnerReply; typedef struct { BYTE type; /* X_Reply */ BYTE status; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGrabPointerReply; typedef xGrabPointerReply xGrabKeyboardReply; typedef struct { BYTE type; /* X_Reply */ BOOL sameScreen; CARD16 sequenceNumber; CARD32 length; /* 0 */ Window root, child; INT16 rootX, rootY, winX, winY; CARD16 mask; CARD16 pad1; CARD32 pad; } xQueryPointerReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 nEvents; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetMotionEventsReply; typedef struct { BYTE type; /* X_Reply */ BOOL sameScreen; CARD16 sequenceNumber; CARD32 length; /* 0 */ Window child; INT16 dstX, dstY; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xTranslateCoordsReply; typedef struct { BYTE type; /* X_Reply */ CARD8 revertTo; CARD16 sequenceNumber; CARD32 length; /* 0 */ Window focus; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xGetInputFocusReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 2, NOT 0; this is an extra-large reply */ BYTE map[32]; } xQueryKeymapReply; /* Warning: this MUST match (up to component renaming) xListFontsWithInfoReply */ typedef struct _xQueryFontReply { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* definitely > 0, even if "nCharInfos" is 0 */ xCharInfo minBounds; CARD32 walign1; xCharInfo maxBounds; CARD32 walign2; CARD16 minCharOrByte2, maxCharOrByte2; CARD16 defaultChar; CARD16 nFontProps; /* followed by this many xFontProp structures */ CARD8 drawDirection; CARD8 minByte1, maxByte1; BOOL allCharsExist; INT16 fontAscent, fontDescent; CARD32 nCharInfos; /* followed by this many xCharInfo structures */ } xQueryFontReply; typedef struct { BYTE type; /* X_Reply */ CARD8 drawDirection; CARD16 sequenceNumber; CARD32 length; /* 0 */ INT16 fontAscent, fontDescent; INT16 overallAscent, overallDescent; INT32 overallWidth, overallLeft, overallRight; CARD32 pad; } xQueryTextExtentsReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nFonts; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xListFontsReply; /* Warning: this MUST match (up to component renaming) xQueryFontReply */ typedef struct { BYTE type; /* X_Reply */ CARD8 nameLength; /* 0 indicates end-of-reply-sequence */ CARD16 sequenceNumber; CARD32 length; /* definitely > 0, even if "nameLength" is 0 */ xCharInfo minBounds; CARD32 walign1; xCharInfo maxBounds; CARD32 walign2; CARD16 minCharOrByte2, maxCharOrByte2; CARD16 defaultChar; CARD16 nFontProps; /* followed by this many xFontProp structures */ CARD8 drawDirection; CARD8 minByte1, maxByte1; BOOL allCharsExist; INT16 fontAscent, fontDescent; CARD32 nReplies; /* hint as to how many more replies might be coming */ } xListFontsWithInfoReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nPaths; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xGetFontPathReply; typedef struct { BYTE type; /* X_Reply */ CARD8 depth; CARD16 sequenceNumber; CARD32 length; VisualID visual; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xGetImageReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nColormaps; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xListInstalledColormapsReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD16 red, green, blue; CARD16 pad2; CARD32 pixel; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xAllocColorReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD32 pixel; CARD16 exactRed, exactGreen, exactBlue; CARD16 screenRed, screenGreen, screenBlue; CARD32 pad2; CARD32 pad3; } xAllocNamedColorReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nPixels, nMasks; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xAllocColorCellsReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nPixels; CARD16 pad2; CARD32 redMask, greenMask, blueMask; CARD32 pad3; CARD32 pad4; } xAllocColorPlanesReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 nColors; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xQueryColorsReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD16 exactRed, exactGreen, exactBlue; CARD16 screenRed, screenGreen, screenBlue; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xLookupColorReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD16 width, height; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xQueryBestSizeReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ BOOL present; CARD8 major_opcode; CARD8 first_event; CARD8 first_error; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xQueryExtensionReply; typedef struct { BYTE type; /* X_Reply */ CARD8 nExtensions; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xListExtensionsReply; typedef struct { BYTE type; /* X_Reply */ CARD8 success; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xSetMappingReply; typedef xSetMappingReply xSetPointerMappingReply; typedef xSetMappingReply xSetModifierMappingReply; typedef struct { BYTE type; /* X_Reply */ CARD8 nElts; /* how many elements does the map have */ CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xGetPointerMappingReply; typedef struct { BYTE type; CARD8 keySymsPerKeyCode; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xGetKeyboardMappingReply; typedef struct { BYTE type; CARD8 numKeyPerModifier; CARD16 sequenceNumber; CARD32 length; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetModifierMappingReply; typedef struct { BYTE type; /* X_Reply */ BOOL globalAutoRepeat; CARD16 sequenceNumber; CARD32 length; /* 5 */ CARD32 ledMask; CARD8 keyClickPercent, bellPercent; CARD16 bellPitch, bellDuration; CARD16 pad; BYTE map[32]; /* bit masks start here */ } xGetKeyboardControlReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD16 accelNumerator, accelDenominator; CARD16 threshold; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetPointerControlReply; typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD16 timeout, interval; BOOL preferBlanking; BOOL allowExposures; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetScreenSaverReply; typedef struct { BYTE type; /* X_Reply */ BOOL enabled; CARD16 sequenceNumber; CARD32 length; CARD16 nHosts; CARD16 pad1; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xListHostsReply; /***************************************************************** * Xerror * All errors are 32 bytes *****************************************************************/ typedef struct { BYTE type; /* X_Error */ BYTE errorCode; CARD16 sequenceNumber; /* the nth request from this client */ CARD32 resourceID; CARD16 minorCode; CARD8 majorCode; BYTE pad1; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xError; /***************************************************************** * xEvent * All events are 32 bytes *****************************************************************/ typedef struct _xEvent { union { struct { BYTE type; BYTE detail; CARD16 sequenceNumber; } u; struct { CARD32 pad00; Time time; Window root, event, child; INT16 rootX, rootY, eventX, eventY; KeyButMask state; BOOL sameScreen; BYTE pad1; } keyButtonPointer; struct { CARD32 pad00; Time time; Window root, event, child; INT16 rootX, rootY, eventX, eventY; KeyButMask state; BYTE mode; /* really XMode */ BYTE flags; /* sameScreen and focus booleans, packed together */ #define ELFlagFocus (1<<0) #define ELFlagSameScreen (1<<1) } enterLeave; struct { CARD32 pad00; Window window; BYTE mode; /* really XMode */ BYTE pad1, pad2, pad3; } focus; struct { CARD32 pad00; Window window; CARD16 x, y, width, height; CARD16 count; CARD16 pad2; } expose; struct { CARD32 pad00; Drawable drawable; CARD16 x, y, width, height; CARD16 minorEvent; CARD16 count; BYTE majorEvent; BYTE pad1, pad2, pad3; } graphicsExposure; struct { CARD32 pad00; Drawable drawable; CARD16 minorEvent; BYTE majorEvent; BYTE bpad; } noExposure; struct { CARD32 pad00; Window window; CARD8 state; BYTE pad1, pad2, pad3; } visibility; struct { CARD32 pad00; Window parent, window; INT16 x, y; CARD16 width, height, borderWidth; BOOL override; BYTE bpad; } createNotify; /* * The event fields in the structures for DestroyNotify, UnmapNotify, * MapNotify, ReparentNotify, ConfigureNotify, CirculateNotify, GravityNotify, * must be at the same offset because server internal code is depending upon * this to patch up the events before they are delivered. * Also note that MapRequest, ConfigureRequest and CirculateRequest have * the same offset for the event window. */ struct { CARD32 pad00; Window event, window; } destroyNotify; struct { CARD32 pad00; Window event, window; BOOL fromConfigure; BYTE pad1, pad2, pad3; } unmapNotify; struct { CARD32 pad00; Window event, window; BOOL override; BYTE pad1, pad2, pad3; } mapNotify; struct { CARD32 pad00; Window parent, window; } mapRequest; struct { CARD32 pad00; Window event, window, parent; INT16 x, y; BOOL override; BYTE pad1, pad2, pad3; } reparent; struct { CARD32 pad00; Window event, window, aboveSibling; INT16 x, y; CARD16 width, height, borderWidth; BOOL override; BYTE bpad; } configureNotify; struct { CARD32 pad00; Window parent, window, sibling; INT16 x, y; CARD16 width, height, borderWidth; CARD16 valueMask; CARD32 pad1; } configureRequest; struct { CARD32 pad00; Window event, window; INT16 x, y; CARD32 pad1, pad2, pad3, pad4; } gravity; struct { CARD32 pad00; Window window; CARD16 width, height; } resizeRequest; struct { /* The event field in the circulate record is really the parent when this is used as a CirculateRequest instead of a CirculateNotify */ CARD32 pad00; Window event, window, parent; BYTE place; /* Top or Bottom */ BYTE pad1, pad2, pad3; } circulate; struct { CARD32 pad00; Window window; Atom atom; Time time; BYTE state; /* NewValue or Deleted */ BYTE pad1; CARD16 pad2; } property; struct { CARD32 pad00; Time time; Window window; Atom atom; } selectionClear; struct { CARD32 pad00; Time time; Window owner, requestor; Atom selection, target, property; } selectionRequest; struct { CARD32 pad00; Time time; Window requestor; Atom selection, target, property; } selectionNotify; struct { CARD32 pad00; Window window; Colormap colormap; #if defined(__cplusplus) || defined(c_plusplus) BOOL c_new; #else BOOL new; #endif BYTE state; /* Installed or UnInstalled */ BYTE pad1, pad2; } colormap; struct { CARD32 pad00; CARD8 request; KeyCode firstKeyCode; CARD8 count; BYTE pad1; } mappingNotify; struct { CARD32 pad00; Window window; union { struct { Atom type; INT32 longs0; INT32 longs1; INT32 longs2; INT32 longs3; INT32 longs4; } l; struct { Atom type; INT16 shorts0; INT16 shorts1; INT16 shorts2; INT16 shorts3; INT16 shorts4; INT16 shorts5; INT16 shorts6; INT16 shorts7; INT16 shorts8; INT16 shorts9; } s; struct { Atom type; INT8 bytes[20]; } b; } u; } clientMessage; } u; } xEvent; /********************************************************* * * Generic event * * Those events are not part of the core protocol spec and can be used by * various extensions. * type is always GenericEvent * extension is the minor opcode of the extension the event belongs to. * evtype is the actual event type, unique __per extension__. * * GenericEvents can be longer than 32 bytes, with the length field * specifying the number of 4 byte blocks after the first 32 bytes. * * */ typedef struct { BYTE type; CARD8 extension; CARD16 sequenceNumber; CARD32 length; CARD16 evtype; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xGenericEvent; /* KeymapNotify events are not included in the above union because they are different from all other events: they do not have a "detail" or "sequenceNumber", so there is room for a 248-bit key mask. */ typedef struct { BYTE type; BYTE map[31]; } xKeymapEvent; #define XEventSize (sizeof(xEvent)) /* XReply is the union of all the replies above whose "fixed part" fits in 32 bytes. It does NOT include GetWindowAttributesReply, QueryFontReply, QueryKeymapReply, or GetKeyboardControlReply ListFontsWithInfoReply */ typedef union { xGenericReply generic; xGetGeometryReply geom; xQueryTreeReply tree; xInternAtomReply atom; xGetAtomNameReply atomName; xGetPropertyReply property; xListPropertiesReply listProperties; xGetSelectionOwnerReply selection; xGrabPointerReply grabPointer; xGrabKeyboardReply grabKeyboard; xQueryPointerReply pointer; xGetMotionEventsReply motionEvents; xTranslateCoordsReply coords; xGetInputFocusReply inputFocus; xQueryTextExtentsReply textExtents; xListFontsReply fonts; xGetFontPathReply fontPath; xGetImageReply image; xListInstalledColormapsReply colormaps; xAllocColorReply allocColor; xAllocNamedColorReply allocNamedColor; xAllocColorCellsReply colorCells; xAllocColorPlanesReply colorPlanes; xQueryColorsReply colors; xLookupColorReply lookupColor; xQueryBestSizeReply bestSize; xQueryExtensionReply extension; xListExtensionsReply extensions; xSetModifierMappingReply setModifierMapping; xGetModifierMappingReply getModifierMapping; xSetPointerMappingReply setPointerMapping; xGetKeyboardMappingReply getKeyboardMapping; xGetPointerMappingReply getPointerMapping; xGetPointerControlReply pointerControl; xGetScreenSaverReply screenSaver; xListHostsReply hosts; xError error; xEvent event; } xReply; /***************************************************************** * REQUESTS *****************************************************************/ /* Request structure */ typedef struct _xReq { CARD8 reqType; CARD8 data; /* meaning depends on request type */ CARD16 length; /* length in 4 bytes quantities of whole request, including this header */ } xReq; /***************************************************************** * structures that follow request. *****************************************************************/ /* ResourceReq is used for any request which has a resource ID (or Atom or Time) as its one and only argument. */ typedef struct { CARD8 reqType; BYTE pad; CARD16 length; CARD32 id; /* a Window, Drawable, Font, GContext, Pixmap, etc. */ } xResourceReq; typedef struct { CARD8 reqType; CARD8 depth; CARD16 length; Window wid, parent; INT16 x, y; CARD16 width, height, borderWidth; #if defined(__cplusplus) || defined(c_plusplus) CARD16 c_class; #else CARD16 class; #endif VisualID visual; CARD32 mask; } xCreateWindowReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window window; CARD32 valueMask; } xChangeWindowAttributesReq; typedef struct { CARD8 reqType; BYTE mode; CARD16 length; Window window; } xChangeSaveSetReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window window, parent; INT16 x, y; } xReparentWindowReq; typedef struct { CARD8 reqType; CARD8 pad; CARD16 length; Window window; CARD16 mask; CARD16 pad2; } xConfigureWindowReq; typedef struct { CARD8 reqType; CARD8 direction; CARD16 length; Window window; } xCirculateWindowReq; typedef struct { /* followed by padded string */ CARD8 reqType; BOOL onlyIfExists; CARD16 length; CARD16 nbytes; /* number of bytes in string */ CARD16 pad; } xInternAtomReq; typedef struct { CARD8 reqType; CARD8 mode; CARD16 length; Window window; Atom property, type; CARD8 format; BYTE pad[3]; CARD32 nUnits; /* length of stuff following, depends on format */ } xChangePropertyReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window window; Atom property; } xDeletePropertyReq; typedef struct { CARD8 reqType; #if defined(__cplusplus) || defined(c_plusplus) BOOL c_delete; #else BOOL delete; #endif CARD16 length; Window window; Atom property, type; CARD32 longOffset; CARD32 longLength; } xGetPropertyReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window window; Atom selection; Time time; } xSetSelectionOwnerReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window requestor; Atom selection, target, property; Time time; } xConvertSelectionReq; typedef struct { CARD8 reqType; BOOL propagate; CARD16 length; Window destination; CARD32 eventMask; xEvent event; } xSendEventReq; typedef struct { CARD8 reqType; BOOL ownerEvents; CARD16 length; Window grabWindow; CARD16 eventMask; BYTE pointerMode, keyboardMode; Window confineTo; Cursor cursor; Time time; } xGrabPointerReq; typedef struct { CARD8 reqType; BOOL ownerEvents; CARD16 length; Window grabWindow; CARD16 eventMask; BYTE pointerMode, keyboardMode; Window confineTo; Cursor cursor; CARD8 button; BYTE pad; CARD16 modifiers; } xGrabButtonReq; typedef struct { CARD8 reqType; CARD8 button; CARD16 length; Window grabWindow; CARD16 modifiers; CARD16 pad; } xUngrabButtonReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Cursor cursor; Time time; CARD16 eventMask; CARD16 pad2; } xChangeActivePointerGrabReq; typedef struct { CARD8 reqType; BOOL ownerEvents; CARD16 length; Window grabWindow; Time time; BYTE pointerMode, keyboardMode; CARD16 pad; } xGrabKeyboardReq; typedef struct { CARD8 reqType; BOOL ownerEvents; CARD16 length; Window grabWindow; CARD16 modifiers; CARD8 key; BYTE pointerMode, keyboardMode; BYTE pad1, pad2, pad3; } xGrabKeyReq; typedef struct { CARD8 reqType; CARD8 key; CARD16 length; Window grabWindow; CARD16 modifiers; CARD16 pad; } xUngrabKeyReq; typedef struct { CARD8 reqType; CARD8 mode; CARD16 length; Time time; } xAllowEventsReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window window; Time start, stop; } xGetMotionEventsReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window srcWid, dstWid; INT16 srcX, srcY; } xTranslateCoordsReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Window srcWid, dstWid; INT16 srcX, srcY; CARD16 srcWidth, srcHeight; INT16 dstX, dstY; } xWarpPointerReq; typedef struct { CARD8 reqType; CARD8 revertTo; CARD16 length; Window focus; Time time; } xSetInputFocusReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Font fid; CARD16 nbytes; BYTE pad1, pad2; /* string follows on word boundary */ } xOpenFontReq; typedef struct { CARD8 reqType; BOOL oddLength; CARD16 length; Font fid; } xQueryTextExtentsReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; CARD16 maxNames; CARD16 nbytes; /* followed immediately by string bytes */ } xListFontsReq; typedef xListFontsReq xListFontsWithInfoReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; CARD16 nFonts; BYTE pad1, pad2; /* LISTofSTRING8 follows on word boundary */ } xSetFontPathReq; typedef struct { CARD8 reqType; CARD8 depth; CARD16 length; Pixmap pid; Drawable drawable; CARD16 width, height; } xCreatePixmapReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; GContext gc; Drawable drawable; CARD32 mask; } xCreateGCReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; GContext gc; CARD32 mask; } xChangeGCReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; GContext srcGC, dstGC; CARD32 mask; } xCopyGCReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; GContext gc; CARD16 dashOffset; CARD16 nDashes; /* length LISTofCARD8 of values following */ } xSetDashesReq; typedef struct { CARD8 reqType; BYTE ordering; CARD16 length; GContext gc; INT16 xOrigin, yOrigin; } xSetClipRectanglesReq; typedef struct { CARD8 reqType; BOOL exposures; CARD16 length; Window window; INT16 x, y; CARD16 width, height; } xClearAreaReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Drawable srcDrawable, dstDrawable; GContext gc; INT16 srcX, srcY, dstX, dstY; CARD16 width, height; } xCopyAreaReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Drawable srcDrawable, dstDrawable; GContext gc; INT16 srcX, srcY, dstX, dstY; CARD16 width, height; CARD32 bitPlane; } xCopyPlaneReq; typedef struct { CARD8 reqType; BYTE coordMode; CARD16 length; Drawable drawable; GContext gc; } xPolyPointReq; typedef xPolyPointReq xPolyLineReq; /* same request structure */ /* The following used for PolySegment, PolyRectangle, PolyArc, PolyFillRectangle, PolyFillArc */ typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Drawable drawable; GContext gc; } xPolySegmentReq; typedef xPolySegmentReq xPolyArcReq; typedef xPolySegmentReq xPolyRectangleReq; typedef xPolySegmentReq xPolyFillRectangleReq; typedef xPolySegmentReq xPolyFillArcReq; typedef struct _FillPolyReq { CARD8 reqType; BYTE pad; CARD16 length; Drawable drawable; GContext gc; BYTE shape; BYTE coordMode; CARD16 pad1; } xFillPolyReq; typedef struct _PutImageReq { CARD8 reqType; CARD8 format; CARD16 length; Drawable drawable; GContext gc; CARD16 width, height; INT16 dstX, dstY; CARD8 leftPad; CARD8 depth; CARD16 pad; } xPutImageReq; typedef struct { CARD8 reqType; CARD8 format; CARD16 length; Drawable drawable; INT16 x, y; CARD16 width, height; CARD32 planeMask; } xGetImageReq; /* the following used by PolyText8 and PolyText16 */ typedef struct { CARD8 reqType; CARD8 pad; CARD16 length; Drawable drawable; GContext gc; INT16 x, y; /* items (xTextElt) start after struct */ } xPolyTextReq; typedef xPolyTextReq xPolyText8Req; typedef xPolyTextReq xPolyText16Req; typedef struct { CARD8 reqType; BYTE nChars; CARD16 length; Drawable drawable; GContext gc; INT16 x, y; } xImageTextReq; typedef xImageTextReq xImageText8Req; typedef xImageTextReq xImageText16Req; typedef struct { CARD8 reqType; BYTE alloc; CARD16 length; Colormap mid; Window window; VisualID visual; } xCreateColormapReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Colormap mid; Colormap srcCmap; } xCopyColormapAndFreeReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Colormap cmap; CARD16 red, green, blue; CARD16 pad2; } xAllocColorReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Colormap cmap; CARD16 nbytes; /* followed by structure */ BYTE pad1, pad2; } xAllocNamedColorReq; typedef struct { CARD8 reqType; BOOL contiguous; CARD16 length; Colormap cmap; CARD16 colors, planes; } xAllocColorCellsReq; typedef struct { CARD8 reqType; BOOL contiguous; CARD16 length; Colormap cmap; CARD16 colors, red, green, blue; } xAllocColorPlanesReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Colormap cmap; CARD32 planeMask; } xFreeColorsReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Colormap cmap; } xStoreColorsReq; typedef struct { CARD8 reqType; CARD8 flags; /* DoRed, DoGreen, DoBlue, as in xColorItem */ CARD16 length; Colormap cmap; CARD32 pixel; CARD16 nbytes; /* number of name string bytes following structure */ BYTE pad1, pad2; } xStoreNamedColorReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Colormap cmap; } xQueryColorsReq; typedef struct { /* followed by string of length len */ CARD8 reqType; BYTE pad; CARD16 length; Colormap cmap; CARD16 nbytes; /* number of string bytes following structure*/ BYTE pad1, pad2; } xLookupColorReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Cursor cid; Pixmap source, mask; CARD16 foreRed, foreGreen, foreBlue; CARD16 backRed, backGreen, backBlue; CARD16 x, y; } xCreateCursorReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Cursor cid; Font source, mask; CARD16 sourceChar, maskChar; CARD16 foreRed, foreGreen, foreBlue; CARD16 backRed, backGreen, backBlue; } xCreateGlyphCursorReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Cursor cursor; CARD16 foreRed, foreGreen, foreBlue; CARD16 backRed, backGreen, backBlue; } xRecolorCursorReq; typedef struct { CARD8 reqType; #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD16 length; Drawable drawable; CARD16 width, height; } xQueryBestSizeReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; CARD16 nbytes; /* number of string bytes following structure */ BYTE pad1, pad2; } xQueryExtensionReq; typedef struct { CARD8 reqType; CARD8 numKeyPerModifier; CARD16 length; } xSetModifierMappingReq; typedef struct { CARD8 reqType; CARD8 nElts; /* how many elements in the map */ CARD16 length; } xSetPointerMappingReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; KeyCode firstKeyCode; CARD8 count; CARD16 pad1; } xGetKeyboardMappingReq; typedef struct { CARD8 reqType; CARD8 keyCodes; CARD16 length; KeyCode firstKeyCode; CARD8 keySymsPerKeyCode; CARD16 pad1; } xChangeKeyboardMappingReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; CARD32 mask; } xChangeKeyboardControlReq; typedef struct { CARD8 reqType; INT8 percent; /* -100 to 100 */ CARD16 length; } xBellReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; INT16 accelNum, accelDenum; INT16 threshold; BOOL doAccel, doThresh; } xChangePointerControlReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; INT16 timeout, interval; BYTE preferBlank, allowExpose; CARD16 pad2; } xSetScreenSaverReq; typedef struct { CARD8 reqType; BYTE mode; CARD16 length; CARD8 hostFamily; BYTE pad; CARD16 hostLength; } xChangeHostsReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; } xListHostsReq; typedef struct { CARD8 reqType; BYTE mode; CARD16 length; } xChangeModeReq; typedef xChangeModeReq xSetAccessControlReq; typedef xChangeModeReq xSetCloseDownModeReq; typedef xChangeModeReq xForceScreenSaverReq; typedef struct { /* followed by LIST of ATOM */ CARD8 reqType; BYTE pad; CARD16 length; Window window; CARD16 nAtoms; INT16 nPositions; } xRotatePropertiesReq; /* Reply codes */ #define X_Reply 1 /* Normal reply */ #define X_Error 0 /* Error */ /* Request codes */ #define X_CreateWindow 1 #define X_ChangeWindowAttributes 2 #define X_GetWindowAttributes 3 #define X_DestroyWindow 4 #define X_DestroySubwindows 5 #define X_ChangeSaveSet 6 #define X_ReparentWindow 7 #define X_MapWindow 8 #define X_MapSubwindows 9 #define X_UnmapWindow 10 #define X_UnmapSubwindows 11 #define X_ConfigureWindow 12 #define X_CirculateWindow 13 #define X_GetGeometry 14 #define X_QueryTree 15 #define X_InternAtom 16 #define X_GetAtomName 17 #define X_ChangeProperty 18 #define X_DeleteProperty 19 #define X_GetProperty 20 #define X_ListProperties 21 #define X_SetSelectionOwner 22 #define X_GetSelectionOwner 23 #define X_ConvertSelection 24 #define X_SendEvent 25 #define X_GrabPointer 26 #define X_UngrabPointer 27 #define X_GrabButton 28 #define X_UngrabButton 29 #define X_ChangeActivePointerGrab 30 #define X_GrabKeyboard 31 #define X_UngrabKeyboard 32 #define X_GrabKey 33 #define X_UngrabKey 34 #define X_AllowEvents 35 #define X_GrabServer 36 #define X_UngrabServer 37 #define X_QueryPointer 38 #define X_GetMotionEvents 39 #define X_TranslateCoords 40 #define X_WarpPointer 41 #define X_SetInputFocus 42 #define X_GetInputFocus 43 #define X_QueryKeymap 44 #define X_OpenFont 45 #define X_CloseFont 46 #define X_QueryFont 47 #define X_QueryTextExtents 48 #define X_ListFonts 49 #define X_ListFontsWithInfo 50 #define X_SetFontPath 51 #define X_GetFontPath 52 #define X_CreatePixmap 53 #define X_FreePixmap 54 #define X_CreateGC 55 #define X_ChangeGC 56 #define X_CopyGC 57 #define X_SetDashes 58 #define X_SetClipRectangles 59 #define X_FreeGC 60 #define X_ClearArea 61 #define X_CopyArea 62 #define X_CopyPlane 63 #define X_PolyPoint 64 #define X_PolyLine 65 #define X_PolySegment 66 #define X_PolyRectangle 67 #define X_PolyArc 68 #define X_FillPoly 69 #define X_PolyFillRectangle 70 #define X_PolyFillArc 71 #define X_PutImage 72 #define X_GetImage 73 #define X_PolyText8 74 #define X_PolyText16 75 #define X_ImageText8 76 #define X_ImageText16 77 #define X_CreateColormap 78 #define X_FreeColormap 79 #define X_CopyColormapAndFree 80 #define X_InstallColormap 81 #define X_UninstallColormap 82 #define X_ListInstalledColormaps 83 #define X_AllocColor 84 #define X_AllocNamedColor 85 #define X_AllocColorCells 86 #define X_AllocColorPlanes 87 #define X_FreeColors 88 #define X_StoreColors 89 #define X_StoreNamedColor 90 #define X_QueryColors 91 #define X_LookupColor 92 #define X_CreateCursor 93 #define X_CreateGlyphCursor 94 #define X_FreeCursor 95 #define X_RecolorCursor 96 #define X_QueryBestSize 97 #define X_QueryExtension 98 #define X_ListExtensions 99 #define X_ChangeKeyboardMapping 100 #define X_GetKeyboardMapping 101 #define X_ChangeKeyboardControl 102 #define X_GetKeyboardControl 103 #define X_Bell 104 #define X_ChangePointerControl 105 #define X_GetPointerControl 106 #define X_SetScreenSaver 107 #define X_GetScreenSaver 108 #define X_ChangeHosts 109 #define X_ListHosts 110 #define X_SetAccessControl 111 #define X_SetCloseDownMode 112 #define X_KillClient 113 #define X_RotateProperties 114 #define X_ForceScreenSaver 115 #define X_SetPointerMapping 116 #define X_GetPointerMapping 117 #define X_SetModifierMapping 118 #define X_GetModifierMapping 119 #define X_NoOperation 127 /* restore these definitions back to the typedefs in X.h */ #undef Window #undef Drawable #undef Font #undef Pixmap #undef Cursor #undef Colormap #undef GContext #undef Atom #undef VisualID #undef Time #undef KeyCode #undef KeySym #endif /* XPROTO_H */ X11/Xresource.h000064400000024604151027430550007255 0ustar00 /*********************************************************** Copyright 1987, 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef _X11_XRESOURCE_H_ #define _X11_XRESOURCE_H_ #ifndef _XP_PRINT_SERVER_ #include #endif /**************************************************************** **************************************************************** *** *** *** *** *** X Resource Manager Intrinsics *** *** *** *** *** **************************************************************** ****************************************************************/ _XFUNCPROTOBEGIN /**************************************************************** * * Memory Management * ****************************************************************/ extern char *Xpermalloc( unsigned int /* size */ ); /**************************************************************** * * Quark Management * ****************************************************************/ typedef int XrmQuark, *XrmQuarkList; #define NULLQUARK ((XrmQuark) 0) typedef char *XrmString; #define NULLSTRING ((XrmString) 0) /* find quark for string, create new quark if none already exists */ extern XrmQuark XrmStringToQuark( _Xconst char* /* string */ ); extern XrmQuark XrmPermStringToQuark( _Xconst char* /* string */ ); /* find string for quark */ extern XrmString XrmQuarkToString( XrmQuark /* quark */ ); extern XrmQuark XrmUniqueQuark( void ); #define XrmStringsEqual(a1, a2) (strcmp(a1, a2) == 0) /**************************************************************** * * Conversion of Strings to Lists * ****************************************************************/ typedef enum {XrmBindTightly, XrmBindLoosely} XrmBinding, *XrmBindingList; extern void XrmStringToQuarkList( _Xconst char* /* string */, XrmQuarkList /* quarks_return */ ); extern void XrmStringToBindingQuarkList( _Xconst char* /* string */, XrmBindingList /* bindings_return */, XrmQuarkList /* quarks_return */ ); /**************************************************************** * * Name and Class lists. * ****************************************************************/ typedef XrmQuark XrmName; typedef XrmQuarkList XrmNameList; #define XrmNameToString(name) XrmQuarkToString(name) #define XrmStringToName(string) XrmStringToQuark(string) #define XrmStringToNameList(str, name) XrmStringToQuarkList(str, name) typedef XrmQuark XrmClass; typedef XrmQuarkList XrmClassList; #define XrmClassToString(c_class) XrmQuarkToString(c_class) #define XrmStringToClass(c_class) XrmStringToQuark(c_class) #define XrmStringToClassList(str,c_class) XrmStringToQuarkList(str, c_class) /**************************************************************** * * Resource Representation Types and Values * ****************************************************************/ typedef XrmQuark XrmRepresentation; #define XrmStringToRepresentation(string) XrmStringToQuark(string) #define XrmRepresentationToString(type) XrmQuarkToString(type) typedef struct { unsigned int size; XPointer addr; } XrmValue, *XrmValuePtr; /**************************************************************** * * Resource Manager Functions * ****************************************************************/ typedef struct _XrmHashBucketRec *XrmHashBucket; typedef XrmHashBucket *XrmHashTable; typedef XrmHashTable XrmSearchList[]; typedef struct _XrmHashBucketRec *XrmDatabase; extern void XrmDestroyDatabase( XrmDatabase /* database */ ); extern void XrmQPutResource( XrmDatabase* /* database */, XrmBindingList /* bindings */, XrmQuarkList /* quarks */, XrmRepresentation /* type */, XrmValue* /* value */ ); extern void XrmPutResource( XrmDatabase* /* database */, _Xconst char* /* specifier */, _Xconst char* /* type */, XrmValue* /* value */ ); extern void XrmQPutStringResource( XrmDatabase* /* database */, XrmBindingList /* bindings */, XrmQuarkList /* quarks */, _Xconst char* /* value */ ); extern void XrmPutStringResource( XrmDatabase* /* database */, _Xconst char* /* specifier */, _Xconst char* /* value */ ); extern void XrmPutLineResource( XrmDatabase* /* database */, _Xconst char* /* line */ ); extern Bool XrmQGetResource( XrmDatabase /* database */, XrmNameList /* quark_name */, XrmClassList /* quark_class */, XrmRepresentation* /* quark_type_return */, XrmValue* /* value_return */ ); extern Bool XrmGetResource( XrmDatabase /* database */, _Xconst char* /* str_name */, _Xconst char* /* str_class */, char** /* str_type_return */, XrmValue* /* value_return */ ); extern Bool XrmQGetSearchList( XrmDatabase /* database */, XrmNameList /* names */, XrmClassList /* classes */, XrmSearchList /* list_return */, int /* list_length */ ); extern Bool XrmQGetSearchResource( XrmSearchList /* list */, XrmName /* name */, XrmClass /* class */, XrmRepresentation* /* type_return */, XrmValue* /* value_return */ ); /**************************************************************** * * Resource Database Management * ****************************************************************/ #ifndef _XP_PRINT_SERVER_ extern void XrmSetDatabase( Display* /* display */, XrmDatabase /* database */ ); extern XrmDatabase XrmGetDatabase( Display* /* display */ ); #endif /* !_XP_PRINT_SERVER_ */ extern XrmDatabase XrmGetFileDatabase( _Xconst char* /* filename */ ); extern Status XrmCombineFileDatabase( _Xconst char* /* filename */, XrmDatabase* /* target */, Bool /* override */ ); extern XrmDatabase XrmGetStringDatabase( _Xconst char* /* data */ /* null terminated string */ ); extern void XrmPutFileDatabase( XrmDatabase /* database */, _Xconst char* /* filename */ ); extern void XrmMergeDatabases( XrmDatabase /* source_db */, XrmDatabase* /* target_db */ ); extern void XrmCombineDatabase( XrmDatabase /* source_db */, XrmDatabase* /* target_db */, Bool /* override */ ); #define XrmEnumAllLevels 0 #define XrmEnumOneLevel 1 extern Bool XrmEnumerateDatabase( XrmDatabase /* db */, XrmNameList /* name_prefix */, XrmClassList /* class_prefix */, int /* mode */, Bool (*)( XrmDatabase* /* db */, XrmBindingList /* bindings */, XrmQuarkList /* quarks */, XrmRepresentation* /* type */, XrmValue* /* value */, XPointer /* closure */ ) /* proc */, XPointer /* closure */ ); extern const char *XrmLocaleOfDatabase( XrmDatabase /* database */ ); /**************************************************************** * * Command line option mapping to resource entries * ****************************************************************/ typedef enum { XrmoptionNoArg, /* Value is specified in OptionDescRec.value */ XrmoptionIsArg, /* Value is the option string itself */ XrmoptionStickyArg, /* Value is characters immediately following option */ XrmoptionSepArg, /* Value is next argument in argv */ XrmoptionResArg, /* Resource and value in next argument in argv */ XrmoptionSkipArg, /* Ignore this option and the next argument in argv */ XrmoptionSkipLine, /* Ignore this option and the rest of argv */ XrmoptionSkipNArgs /* Ignore this option and the next OptionDescRes.value arguments in argv */ } XrmOptionKind; typedef struct { char *option; /* Option abbreviation in argv */ char *specifier; /* Resource specifier */ XrmOptionKind argKind; /* Which style of option it is */ XPointer value; /* Value to provide if XrmoptionNoArg */ } XrmOptionDescRec, *XrmOptionDescList; extern void XrmParseCommand( XrmDatabase* /* database */, XrmOptionDescList /* table */, int /* table_count */, _Xconst char* /* name */, int* /* argc_in_out */, char** /* argv_in_out */ ); _XFUNCPROTOEND #endif /* _X11_XRESOURCE_H_ */ /* DON'T ADD STUFF AFTER THIS #endif */ X11/fonts/fsmasks.h000064400000007630151027430550010076 0ustar00/* * Copyright 1990, 1991 Network Computing Devices; * Portions Copyright 1987 by Digital Equipment Corporation * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the names of Network Computing Devices or Digital * not be used in advertising or publicity pertaining to distribution * of the software without specific, written prior permission. * Network Computing Devices and Digital make no representations * about the suitability of this software for any purpose. It is provided * "as is" without express or implied warranty. * * NETWORK COMPUTING DEVICES AND DIGITAL DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL NETWORK COMPUTING DEVICES * OR DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ /* Portions Copyright 1987, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * masks & values used by the font lib and the font server */ #ifndef _FSMASKS_H_ #define _FSMASKS_H_ #include /* font format macros */ #define BitmapFormatByteOrderMask (1L << 0) #define BitmapFormatBitOrderMask (1L << 1) #define BitmapFormatImageRectMask (3L << 2) #define BitmapFormatScanlinePadMask (3L << 8) #define BitmapFormatScanlineUnitMask (3L << 12) #define BitmapFormatByteOrderLSB (0) #define BitmapFormatByteOrderMSB (1L << 0) #define BitmapFormatBitOrderLSB (0) #define BitmapFormatBitOrderMSB (1L << 1) #define BitmapFormatImageRectMin (0L << 2) #define BitmapFormatImageRectMaxWidth (1L << 2) #define BitmapFormatImageRectMax (2L << 2) #define BitmapFormatScanlinePad8 (0L << 8) #define BitmapFormatScanlinePad16 (1L << 8) #define BitmapFormatScanlinePad32 (2L << 8) #define BitmapFormatScanlinePad64 (3L << 8) #define BitmapFormatScanlineUnit8 (0L << 12) #define BitmapFormatScanlineUnit16 (1L << 12) #define BitmapFormatScanlineUnit32 (2L << 12) #define BitmapFormatScanlineUnit64 (3L << 12) #define BitmapFormatMaskByte (1L << 0) #define BitmapFormatMaskBit (1L << 1) #define BitmapFormatMaskImageRectangle (1L << 2) #define BitmapFormatMaskScanLinePad (1L << 3) #define BitmapFormatMaskScanLineUnit (1L << 4) typedef CARD32 fsBitmapFormat; typedef CARD32 fsBitmapFormatMask; #endif /* _FSMASKS_H_ */ X11/fonts/FS.h000064400000007753151027430550006745 0ustar00/* * Copyright 1990, 1991 Network Computing Devices; * Portions Copyright 1987 by Digital Equipment Corporation * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the names of Network Computing Devices or Digital * not be used in advertising or publicity pertaining to distribution * of the software without specific, written prior permission. * Network Computing Devices and Digital make no representations * about the suitability of this software for any purpose. It is provided * "as is" without express or implied warranty. * * NETWORK COMPUTING DEVICES AND DIGITAL DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL NETWORK COMPUTING DEVICES * OR DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ /* Portions Copyright 1987, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _FS_H_ #define _FS_H_ #include #include #define FS_PROTOCOL 2 #define FS_PROTOCOL_MINOR 0 #ifndef X_PROTOCOL /* protocol familes */ #define FamilyInternet 0 #define FamilyDECnet 1 #define FamilyChaos 2 #define FamilyInternet6 6 typedef unsigned int FSDrawDirection; #endif #ifndef None #define None 0L #endif #define LeftToRightDrawDirection 0 #define RightToLeftDrawDirection 1 /* font info flags */ #define FontInfoAllCharsExist (1L << 0) #define FontInfoInkInside (1L << 1) #define FontInfoHorizontalOverlap (1L << 2) /* auth status flags */ #define AuthSuccess 0 #define AuthContinue 1 #define AuthBusy 2 #define AuthDenied 3 /* property types */ #define PropTypeString 0 #define PropTypeUnsigned 1 #define PropTypeSigned 2 #ifndef LSBFirst /* byte order */ #define LSBFirst 0 #define MSBFirst 1 #endif /* event masks */ #define CatalogueChangeNotifyMask (1L << 0) #define FontChangeNotifyMask (1L << 1) /* errors */ #define FSSuccess -1 #define FSBadRequest 0 #define FSBadFormat 1 #define FSBadFont 2 #define FSBadRange 3 #define FSBadEventMask 4 #define FSBadAccessContext 5 #define FSBadIDChoice 6 #define FSBadName 7 #define FSBadResolution 8 #define FSBadAlloc 9 #define FSBadLength 10 #define FSBadImplementation 11 #define FirstExtensionError 128 #define LastExtensionError 255 /* events */ #define KeepAlive 0 #define CatalogueChangeNotify 1 #define FontChangeNotify 2 #define FSLASTEvent 3 #endif /* _FS_H_ */ X11/fonts/font.h000064400000010235151027430550007370 0ustar00/*********************************************************** Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef FONT_H #define FONT_H #include #ifndef BitmapFormatByteOrderMask #include "fsmasks.h" #endif /* data structures */ #ifndef _XTYPEDEF_FONTPTR typedef struct _Font *FontPtr; #define _XTYPEDEF_FONTPTR #endif typedef struct _FontInfo *FontInfoPtr; typedef struct _FontProp *FontPropPtr; typedef struct _ExtentInfo *ExtentInfoPtr; typedef struct _FontPathElement *FontPathElementPtr; #ifndef _XTYPEDEF_CHARINFOPTR typedef struct _CharInfo *CharInfoPtr; #define _XTYPEDEF_CHARINFOPTR #endif typedef struct _FontNames *FontNamesPtr; typedef struct _FontResolution *FontResolutionPtr; #define NullCharInfo ((CharInfoPtr) 0) #define NullFont ((FontPtr) 0) #define NullFontInfo ((FontInfoPtr) 0) /* draw direction */ #define LeftToRight 0 #define RightToLeft 1 #define BottomToTop 2 #define TopToBottom 3 typedef int DrawDirection; #define NO_SUCH_CHAR -1 #define FontAliasType 0x1000 #define AllocError 80 #define StillWorking 81 #define FontNameAlias 82 #define BadFontName 83 #define Suspended 84 #define Successful 85 #define BadFontPath 86 #define BadCharRange 87 #define BadFontFormat 88 #define FPEResetFailed 89 /* for when an FPE reset won't work */ /* OpenFont flags */ #define FontLoadInfo 0x0001 #define FontLoadProps 0x0002 #define FontLoadMetrics 0x0004 #define FontLoadBitmaps 0x0008 #define FontLoadAll 0x000f #define FontOpenSync 0x0010 #define FontReopen 0x0020 /* Query flags */ #define LoadAll 0x1 #define FinishRamge 0x2 #define EightBitFont 0x4 #define SixteenBitFont 0x8 /* Glyph Caching Modes */ #define CACHING_OFF 0 #define CACHE_16_BIT_GLYPHS 1 #define CACHE_ALL_GLYPHS 2 #define DEFAULT_GLYPH_CACHING_MODE CACHE_16_BIT_GLYPHS extern int glyphCachingMode; struct _Client; extern int StartListFontsWithInfo( struct _Client * /*client*/, int /*length*/, unsigned char * /*pattern*/, int /*max_names*/ ); extern FontNamesPtr MakeFontNamesRecord( unsigned /* size */ ); extern void FreeFontNames( FontNamesPtr /* pFN*/ ); extern int AddFontNamesName( FontNamesPtr /* names */, char * /* name */, int /* length */ ); #if 0 /* unused */ extern int FontToFSError(); extern FontResolutionPtr GetClientResolution(); #endif typedef struct _FontPatternCache *FontPatternCachePtr; extern FontPatternCachePtr MakeFontPatternCache ( void ); extern void FreeFontPatternCache ( FontPatternCachePtr /* cache */ ); extern void EmptyFontPatternCache ( FontPatternCachePtr /* cache */ ); extern void CacheFontPattern ( FontPatternCachePtr /* cache */, const char * /* pattern */, int /* patlen */, FontPtr /* pFont */ ); extern _X_EXPORT FontResolutionPtr GetClientResolutions( int * /* num */ ); extern FontPtr FindCachedFontPattern ( FontPatternCachePtr /* cache */, const char * /* pattern */, int /* patlen */ ); extern void RemoveCachedFontPattern ( FontPatternCachePtr /* cache */, FontPtr /* pFont */ ); typedef enum { Linear8Bit, TwoD8Bit, Linear16Bit, TwoD16Bit } FontEncoding; #endif /* FONT_H */ X11/fonts/fontproto.h000064400000006572151027430550010465 0ustar00/*********************************************************** Copyright (c) 1999 The XFree86 Project Inc. All Rights Reserved. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The XFree86 Project Inc. shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The XFree86 Project Inc.. */ #ifndef _FONTPROTO_H #define _FONTPROTO_H #include /* Externally provided functions required by libXfont */ extern _X_EXPORT int RegisterFPEFunctions ( NameCheckFunc name_func, InitFpeFunc init_func, FreeFpeFunc free_func, ResetFpeFunc reset_func, OpenFontFunc open_func, CloseFontFunc close_func, ListFontsFunc list_func, StartLfwiFunc start_lfwi_func, NextLfwiFunc next_lfwi_func, WakeupFpeFunc wakeup_func, ClientDiedFunc client_died, LoadGlyphsFunc load_glyphs, StartLaFunc start_list_alias_func, NextLaFunc next_list_alias_func, SetPathFunc set_path_func); extern _X_EXPORT int GetDefaultPointSize ( void ); extern _X_EXPORT int init_fs_handlers ( FontPathElementPtr fpe, BlockHandlerProcPtr block_handler); extern _X_EXPORT void remove_fs_handlers ( FontPathElementPtr fpe, BlockHandlerProcPtr block_handler, Bool all ); extern _X_EXPORT int client_auth_generation ( ClientPtr client ); #ifndef ___CLIENTSIGNAL_DEFINED___ #define ___CLIENTSIGNAL_DEFINED___ extern Bool ClientSignal ( ClientPtr client ); #endif /* ___CLIENTSIGNAL_DEFINED___ */ extern _X_EXPORT void DeleteFontClientID ( Font id ); extern _X_EXPORT Font GetNewFontClientID ( void ); extern _X_EXPORT int StoreFontClientFont ( FontPtr pfont, Font id ); extern _X_EXPORT void FontFileRegisterFpeFunctions ( void ); extern _X_EXPORT void FontFileCheckRegisterFpeFunctions ( void ); extern Bool XpClientIsBitmapClient ( ClientPtr client ); extern Bool XpClientIsPrintClient( ClientPtr client, FontPathElementPtr fpe ); extern void PrinterFontRegisterFpeFunctions ( void ); extern void fs_register_fpe_functions ( void ); extern void check_fs_register_fpe_functions ( void ); /* util/private.c */ extern FontPtr CreateFontRec (void); extern void DestroyFontRec (FontPtr font); extern Bool _FontSetNewPrivate (FontPtr /* pFont */, int /* n */, void * /* ptr */); extern int AllocateFontPrivateIndex (void); extern void ResetFontPrivateIndex (void); /* Type1/t1funcs.c */ extern void Type1RegisterFontFileFunctions(void); extern void CIDRegisterFontFileFunctions(void); /* Speedo/spfuncs.c */ extern void SpeedoRegisterFontFileFunctions(void); /* FreeType/ftfuncs.c */ extern void FreeTypeRegisterFontFileFunctions(void); #endif X11/fonts/fontstruct.h000064400000022271151027430550010640 0ustar00/*********************************************************** Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef FONTSTR_H #define FONTSTR_H #include #include "font.h" #include #include /* * This version of the server font data structure is only for describing * the in memory data structure. The file structure is not necessarily a * copy of this. That is up to the compiler and the OS layer font loading * machinery. */ #define GLYPHPADOPTIONS 4 /* 1, 2, 4, or 8 */ typedef struct _FontProp { long name; long value; /* assumes ATOM is not larger than INT32 */ } FontPropRec; typedef struct _FontResolution { unsigned short x_resolution; unsigned short y_resolution; unsigned short point_size; } FontResolutionRec; typedef struct _ExtentInfo { DrawDirection drawDirection; int fontAscent; int fontDescent; int overallAscent; int overallDescent; int overallWidth; int overallLeft; int overallRight; } ExtentInfoRec; typedef struct _CharInfo { xCharInfo metrics; /* info preformatted for Queries */ char *bits; /* pointer to glyph image */ } CharInfoRec; /* * Font is created at font load time. It is specific to a single encoding. * e.g. not all of the glyphs in a font may be part of a single encoding. */ typedef struct _FontInfo { unsigned short firstCol; unsigned short lastCol; unsigned short firstRow; unsigned short lastRow; unsigned short defaultCh; unsigned int noOverlap:1; unsigned int terminalFont:1; unsigned int constantMetrics:1; unsigned int constantWidth:1; unsigned int inkInside:1; unsigned int inkMetrics:1; unsigned int allExist:1; unsigned int drawDirection:2; unsigned int cachable:1; unsigned int anamorphic:1; short maxOverlap; short pad; xCharInfo maxbounds; xCharInfo minbounds; xCharInfo ink_maxbounds; xCharInfo ink_minbounds; short fontAscent; short fontDescent; int nprops; FontPropPtr props; char *isStringProp; } FontInfoRec; typedef struct _Font { int refcnt; FontInfoRec info; char bit; char byte; char glyph; char scan; fsBitmapFormat format; int (*get_glyphs) (FontPtr /* font */, unsigned long /* count */, unsigned char * /* chars */, FontEncoding /* encoding */, unsigned long * /* count */, CharInfoPtr * /* glyphs */); int (*get_metrics) (FontPtr /* font */, unsigned long /* count */, unsigned char * /* chars */, FontEncoding /* encoding */, unsigned long * /* count */, xCharInfo ** /* glyphs */); void (*unload_font) (FontPtr /* font */); void (*unload_glyphs) (FontPtr /* font */); FontPathElementPtr fpe; void *svrPrivate; void *fontPrivate; void *fpePrivate; int maxPrivate; void **devPrivates; } FontRec; #define FontGetPrivate(pFont,n) ((n) > (pFont)->maxPrivate ? (void *) 0 : \ (pFont)->devPrivates[n]) #define FontSetPrivate(pFont,n,ptr) ((n) > (pFont)->maxPrivate ? \ _FontSetNewPrivate (pFont, n, ptr) : \ ((((pFont)->devPrivates[n] = (ptr)) != 0) || TRUE)) typedef struct _FontNames { int nnames; int size; int *length; char **names; } FontNamesRec; /* External view of font paths */ typedef struct _FontPathElement { int name_length; #if FONT_PATH_ELEMENT_NAME_CONST const #endif char *name; int type; int refcount; void *private; } FontPathElementRec; typedef Bool (*NameCheckFunc) (const char *name); typedef int (*InitFpeFunc) (FontPathElementPtr fpe); typedef int (*FreeFpeFunc) (FontPathElementPtr fpe); typedef int (*ResetFpeFunc) (FontPathElementPtr fpe); typedef int (*OpenFontFunc) ( void *client, FontPathElementPtr fpe, Mask flags, const char* name, int namelen, fsBitmapFormat format, fsBitmapFormatMask fmask, XID id, FontPtr* pFont, char** aliasName, FontPtr non_cachable_font); typedef void (*CloseFontFunc) (FontPathElementPtr fpe, FontPtr pFont); typedef int (*ListFontsFunc) (void *client, FontPathElementPtr fpe, const char* pat, int len, int max, FontNamesPtr names); typedef int (*StartLfwiFunc) (void *client, FontPathElementPtr fpe, const char* pat, int len, int max, void ** privatep); typedef int (*NextLfwiFunc) (void *client, FontPathElementPtr fpe, char** name, int* namelen, FontInfoPtr* info, int* numFonts, void *private); typedef int (*WakeupFpeFunc) (FontPathElementPtr fpe, unsigned long* LastSelectMask); typedef void (*ClientDiedFunc) (void *client, FontPathElementPtr fpe); typedef int (*LoadGlyphsFunc) (void *client, FontPtr pfont, Bool range_flag, unsigned int nchars, int item_size, unsigned char* data); typedef int (*StartLaFunc) (void *client, FontPathElementPtr fpe, const char* pat, int len, int max, void ** privatep); typedef int (*NextLaFunc) (void *client, FontPathElementPtr fpe, char** namep, int* namelenp, char** resolvedp, int* resolvedlenp, void *private); typedef void (*SetPathFunc)(void); typedef struct _FPEFunctions { NameCheckFunc name_check; InitFpeFunc init_fpe; ResetFpeFunc reset_fpe; FreeFpeFunc free_fpe; OpenFontFunc open_font; CloseFontFunc close_font; ListFontsFunc list_fonts; StartLaFunc start_list_fonts_and_aliases; NextLaFunc list_next_font_or_alias; StartLfwiFunc start_list_fonts_with_info; NextLfwiFunc list_next_font_with_info; WakeupFpeFunc wakeup_fpe; ClientDiedFunc client_died; /* for load_glyphs, range_flag = 0 -> nchars = # of characters in data item_size = bytes/char data = list of characters range_flag = 1 -> nchars = # of fsChar2b's in data item_size is ignored data = list of fsChar2b's */ LoadGlyphsFunc load_glyphs; SetPathFunc set_path_hook; } FPEFunctionsRec, FPEFunctions; /* * Various macros for computing values based on contents of * the above structures */ #define GLYPHWIDTHPIXELS(pci) \ ((pci)->metrics.rightSideBearing - (pci)->metrics.leftSideBearing) #define GLYPHHEIGHTPIXELS(pci) \ ((pci)->metrics.ascent + (pci)->metrics.descent) #define GLYPHWIDTHBYTES(pci) (((GLYPHWIDTHPIXELS(pci))+7) >> 3) #define GLYPHWIDTHPADDED(bc) (((bc)+7) & ~0x7) #define BYTES_PER_ROW(bits, nbytes) \ ((nbytes) == 1 ? (((bits)+7)>>3) /* pad to 1 byte */ \ :(nbytes) == 2 ? ((((bits)+15)>>3)&~1) /* pad to 2 bytes */ \ :(nbytes) == 4 ? ((((bits)+31)>>3)&~3) /* pad to 4 bytes */ \ :(nbytes) == 8 ? ((((bits)+63)>>3)&~7) /* pad to 8 bytes */ \ : 0) #define BYTES_FOR_GLYPH(ci,pad) (GLYPHHEIGHTPIXELS(ci) * \ BYTES_PER_ROW(GLYPHWIDTHPIXELS(ci),pad)) /* * Macros for computing different bounding boxes for fonts; from * the font protocol */ #define FONT_MAX_ASCENT(pi) ((pi)->fontAscent > (pi)->ink_maxbounds.ascent ? \ (pi)->fontAscent : (pi)->ink_maxbounds.ascent) #define FONT_MAX_DESCENT(pi) ((pi)->fontDescent > (pi)->ink_maxbounds.descent ? \ (pi)->fontDescent : (pi)->ink_maxbounds.descent) #define FONT_MAX_HEIGHT(pi) (FONT_MAX_ASCENT(pi) + FONT_MAX_DESCENT(pi)) #define FONT_MIN_LEFT(pi) ((pi)->ink_minbounds.leftSideBearing < 0 ? \ (pi)->ink_minbounds.leftSideBearing : 0) #define FONT_MAX_RIGHT(pi) ((pi)->ink_maxbounds.rightSideBearing > \ (pi)->ink_maxbounds.characterWidth ? \ (pi)->ink_maxbounds.rightSideBearing : \ (pi)->ink_maxbounds.characterWidth) #define FONT_MAX_WIDTH(pi) (FONT_MAX_RIGHT(pi) - FONT_MIN_LEFT(pi)) #include "fontproto.h" #endif /* FONTSTR_H */ X11/fonts/FSproto.h000064400000046661151027430550010032 0ustar00/* Copyright 1990, 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. * Copyright 1990, 1991 Network Computing Devices; * Portions Copyright 1987 by Digital Equipment Corporation * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the names of Network Computing Devices, or Digital * not be used in advertising or publicity pertaining to distribution * of the software without specific, written prior permission. * * NETWORK COMPUTING DEVICES, AND DIGITAL DISCLAIM ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL NETWORK COMPUTING DEVICES, * OR DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ #ifndef _FS_PROTO_H_ #define _FS_PROTO_H_ #include #define sz_fsPropOffset 20 #define sz_fsPropInfo 8 #define sz_fsResolution 6 #define sz_fsChar2b 2 #define sz_fsChar2b_version1 2 #define sz_fsOffset32 8 #define sz_fsRange 4 #define sz_fsXCharInfo 12 #define sz_fsXFontInfoHeader 40 #define sz_fsConnClientPrefix 8 #define sz_fsConnSetup 12 #define sz_fsConnSetupExtra 8 #define sz_fsConnSetupAccept 12 /* request sizes */ #define sz_fsReq 4 #define sz_fsListExtensionsReq 4 #define sz_fsResourceReq 8 #define sz_fsNoopReq 4 #define sz_fsListExtensionReq 4 #define sz_fsQueryExtensionReq 4 #define sz_fsListCataloguesReq 12 #define sz_fsSetCataloguesReq 4 #define sz_fsGetCataloguesReq 4 #define sz_fsSetEventMaskReq 8 #define sz_fsGetEventMaskReq 4 #define sz_fsCreateACReq 8 #define sz_fsFreeACReq 8 #define sz_fsSetAuthorizationReq 8 #define sz_fsSetResolutionReq 4 #define sz_fsGetResolutionReq 4 #define sz_fsListFontsReq 12 #define sz_fsListFontsWithXInfoReq 12 #define sz_fsOpenBitmapFontReq 16 #define sz_fsQueryXInfoReq 8 #define sz_fsQueryXExtents8Req 12 #define sz_fsQueryXExtents16Req 12 #define sz_fsQueryXBitmaps8Req 16 #define sz_fsQueryXBitmaps16Req 16 #define sz_fsCloseReq 8 /* reply sizes */ #define sz_fsReply 8 #define sz_fsGenericReply 8 #define sz_fsListExtensionsReply 8 #define sz_fsQueryExtensionReply 20 #define sz_fsListCataloguesReply 16 #define sz_fsGetCataloguesReply 8 #define sz_fsGetEventMaskReply 12 #define sz_fsCreateACReply 12 #define sz_fsGetResolutionReply 8 #define sz_fsListFontsReply 16 #define sz_fsListFontsWithXInfoReply (12 + sz_fsXFontInfoHeader) #define sz_fsOpenBitmapFontReply 16 #define sz_fsQueryXInfoReply (8 + sz_fsXFontInfoHeader) #define sz_fsQueryXExtents8Reply 12 #define sz_fsQueryXExtents16Reply 12 #define sz_fsQueryXBitmaps8Reply 20 #define sz_fsQueryXBitmaps16Reply 20 #define sz_fsError 16 #define sz_fsEvent 12 #define sz_fsKeepAliveEvent 12 #define fsTrue 1 #define fsFalse 0 /* temp decls */ #define Mask CARD32 #define Font CARD32 #define AccContext CARD32 typedef CARD32 fsTimestamp; #ifdef NOTDEF /* in fsmasks.h */ typedef CARD32 fsBitmapFormat; typedef CARD32 fsBitmapFormatMask; #endif #define sz_fsBitmapFormat 4 typedef struct { INT16 left, right; INT16 width; INT16 ascent, descent; CARD16 attributes; } fsXCharInfo; typedef struct { CARD8 high; CARD8 low; } fsChar2b; typedef struct { CARD8 low; CARD8 high; } fsChar2b_version1; typedef struct { CARD8 min_char_high; CARD8 min_char_low; CARD8 max_char_high; CARD8 max_char_low; } fsRange; typedef struct { CARD32 position; CARD32 length; } fsOffset32; typedef struct { fsOffset32 name; fsOffset32 value; CARD8 type; BYTE pad0; CARD16 pad1; } fsPropOffset; typedef struct { CARD32 num_offsets; CARD32 data_len; /* offsets */ /* data */ } fsPropInfo; typedef struct { CARD16 x_resolution; CARD16 y_resolution; CARD16 point_size; } fsResolution; typedef struct { CARD32 flags; CARD8 char_range_min_char_high; CARD8 char_range_min_char_low; CARD8 char_range_max_char_high; CARD8 char_range_max_char_low; CARD8 draw_direction; CARD8 pad; CARD8 default_char_high; CARD8 default_char_low; INT16 min_bounds_left; INT16 min_bounds_right; INT16 min_bounds_width; INT16 min_bounds_ascent; INT16 min_bounds_descent; CARD16 min_bounds_attributes; INT16 max_bounds_left; INT16 max_bounds_right; INT16 max_bounds_width; INT16 max_bounds_ascent; INT16 max_bounds_descent; CARD16 max_bounds_attributes; INT16 font_ascent; INT16 font_descent; /* propinfo */ } fsXFontInfoHeader; /* requests */ typedef struct { BYTE byteOrder; CARD8 num_auths; CARD16 major_version; CARD16 minor_version; CARD16 auth_len; /* auth data */ } fsConnClientPrefix; typedef struct { CARD16 status; CARD16 major_version; CARD16 minor_version; CARD8 num_alternates; CARD8 auth_index; CARD16 alternate_len; CARD16 auth_len; /* alternates */ /* auth data */ } fsConnSetup; typedef struct { CARD32 length; CARD16 status; CARD16 pad; /* more auth data */ } fsConnSetupExtra; typedef struct { CARD32 length; CARD16 max_request_len; CARD16 vendor_len; CARD32 release_number; /* vendor string */ } fsConnSetupAccept; typedef struct { CARD8 reqType; CARD8 data; CARD16 length; } fsReq; /* * The fsFakeReq structure is never used in the protocol; it is prepended * to incoming packets when setting up a connection so we can index * through InitialVector. To avoid alignment problems, it is padded * to the size of a word on the largest machine this code runs on. * Hence no sz_fsFakeReq constant is necessary. */ typedef struct { CARD8 reqType; CARD8 data; CARD16 length; CARD32 pad; /* to fill out to multiple of 64 bits */ } fsFakeReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Font id; } fsResourceReq; typedef fsReq fsNoopReq; typedef fsReq fsListExtensionsReq; typedef struct { CARD8 reqType; BYTE nbytes; CARD16 length; /* name */ } fsQueryExtensionReq; typedef struct { CARD8 reqType; CARD8 data; CARD16 length; CARD32 maxNames; CARD16 nbytes; CARD16 pad2; /* pattern */ } fsListCataloguesReq; typedef struct { CARD8 reqType; BYTE num_catalogues; CARD16 length; /* catalogues */ } fsSetCataloguesReq; typedef fsReq fsGetCataloguesReq; typedef struct { CARD8 reqType; CARD8 ext_opcode; CARD16 length; Mask event_mask; } fsSetEventMaskReq; typedef struct { CARD8 reqType; CARD8 ext_opcode; CARD16 length; } fsGetEventMaskReq; typedef struct { CARD8 reqType; BYTE num_auths; CARD16 length; AccContext acid; /* auth protocols */ } fsCreateACReq; typedef fsResourceReq fsFreeACReq; typedef fsResourceReq fsSetAuthorizationReq; typedef struct { CARD8 reqType; BYTE num_resolutions; CARD16 length; /* resolutions */ } fsSetResolutionReq; typedef fsReq fsGetResolutionReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; CARD32 maxNames; CARD16 nbytes; CARD16 pad2; /* pattern */ } fsListFontsReq; typedef fsListFontsReq fsListFontsWithXInfoReq; typedef struct { CARD8 reqType; BYTE pad; CARD16 length; Font fid; fsBitmapFormatMask format_mask; fsBitmapFormat format_hint; /* pattern */ } fsOpenBitmapFontReq; typedef fsResourceReq fsQueryXInfoReq; typedef struct { CARD8 reqType; BOOL range; CARD16 length; Font fid; CARD32 num_ranges; /* list of chars */ } fsQueryXExtents8Req; typedef fsQueryXExtents8Req fsQueryXExtents16Req; typedef struct { CARD8 reqType; BOOL range; CARD16 length; Font fid; fsBitmapFormat format; CARD32 num_ranges; /* list of chars */ } fsQueryXBitmaps8Req; typedef fsQueryXBitmaps8Req fsQueryXBitmaps16Req; typedef fsResourceReq fsCloseReq; /* replies */ typedef struct { BYTE type; BYTE data1; CARD16 sequenceNumber; CARD32 length; } fsGenericReply; typedef struct { BYTE type; CARD8 nExtensions; CARD16 sequenceNumber; CARD32 length; /* extension names */ } fsListExtensionsReply; typedef struct { BYTE type; CARD8 present; CARD16 sequenceNumber; CARD32 length; CARD16 major_version; CARD16 minor_version; CARD8 major_opcode; CARD8 first_event; CARD8 num_events; CARD8 first_error; CARD8 num_errors; CARD8 pad1; CARD16 pad2; } fsQueryExtensionReply; typedef struct { BYTE type; BYTE pad; CARD16 sequenceNumber; CARD32 length; CARD32 num_replies; CARD32 num_catalogues; /* catalog names */ } fsListCataloguesReply; typedef struct { BYTE type; CARD8 num_catalogues; CARD16 sequenceNumber; CARD32 length; /* catalogue names */ } fsGetCataloguesReply; typedef struct { BYTE type; BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 event_mask; } fsGetEventMaskReply; typedef struct { BYTE type; CARD8 auth_index; CARD16 sequenceNumber; CARD32 length; CARD16 status; CARD16 pad; /* auth data */ } fsCreateACReply; typedef struct { CARD32 length; CARD16 status; CARD16 pad; /* auth data */ } fsCreateACExtraReply; typedef struct { BYTE type; CARD8 num_resolutions; CARD16 sequenceNumber; CARD32 length; /* resolutions */ } fsGetResolutionReply; typedef struct { BYTE type; BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 following; CARD32 nFonts; /* font names */ } fsListFontsReply; /* * this one is messy. the reply itself is variable length (unknown * number of replies) and the contents of each is variable (unknown * number of properties) * */ typedef struct { BYTE type; CARD8 nameLength; /* 0 is end-of-reply */ CARD16 sequenceNumber; CARD32 length; CARD32 nReplies; CARD32 font_header_flags; CARD8 font_hdr_char_range_min_char_high; CARD8 font_hdr_char_range_min_char_low; CARD8 font_hdr_char_range_max_char_high; CARD8 font_hdr_char_range_max_char_low; CARD8 font_header_draw_direction; CARD8 font_header_pad; CARD8 font_header_default_char_high; CARD8 font_header_default_char_low; INT16 font_header_min_bounds_left; INT16 font_header_min_bounds_right; INT16 font_header_min_bounds_width; INT16 font_header_min_bounds_ascent; INT16 font_header_min_bounds_descent; CARD16 font_header_min_bounds_attributes; INT16 font_header_max_bounds_left; INT16 font_header_max_bounds_right; INT16 font_header_max_bounds_width; INT16 font_header_max_bounds_ascent; INT16 font_header_max_bounds_descent; CARD16 font_header_max_bounds_attributes; INT16 font_header_font_ascent; INT16 font_header_font_descent; /* propinfo */ /* name */ } fsListFontsWithXInfoReply; typedef struct { BYTE type; CARD8 otherid_valid; CARD16 sequenceNumber; CARD32 length; CARD32 otherid; BYTE cachable; BYTE pad1; CARD16 pad2; } fsOpenBitmapFontReply; typedef struct { BYTE type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 font_header_flags; CARD8 font_hdr_char_range_min_char_high; CARD8 font_hdr_char_range_min_char_low; CARD8 font_hdr_char_range_max_char_high; CARD8 font_hdr_char_range_max_char_low; CARD8 font_header_draw_direction; CARD8 font_header_pad; CARD8 font_header_default_char_high; CARD8 font_header_default_char_low; INT16 font_header_min_bounds_left; INT16 font_header_min_bounds_right; INT16 font_header_min_bounds_width; INT16 font_header_min_bounds_ascent; INT16 font_header_min_bounds_descent; CARD16 font_header_min_bounds_attributes; INT16 font_header_max_bounds_left; INT16 font_header_max_bounds_right; INT16 font_header_max_bounds_width; INT16 font_header_max_bounds_ascent; INT16 font_header_max_bounds_descent; CARD16 font_header_max_bounds_attributes; INT16 font_header_font_ascent; INT16 font_header_font_descent; /* propinfo */ } fsQueryXInfoReply; typedef struct { BYTE type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 num_extents; /* extents */ } fsQueryXExtents8Reply; typedef fsQueryXExtents8Reply fsQueryXExtents16Reply; typedef struct { BYTE type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 replies_hint; CARD32 num_chars; CARD32 nbytes; /* offsets */ /* glyphs */ } fsQueryXBitmaps8Reply; typedef fsQueryXBitmaps8Reply fsQueryXBitmaps16Reply; typedef union { fsGenericReply generic; fsListExtensionsReply extensions; fsGetResolutionReply getres; } fsReply; /* errors */ typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; } fsError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; } fsRequestError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; fsBitmapFormat format; } fsFormatError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; Font fontid; } fsFontError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; fsRange range; } fsRangeError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; Mask event_mask; } fsEventMaskError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; AccContext acid; } fsAccessContextError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; Font fontid; } fsIDChoiceError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; } fsNameError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; fsResolution resolution; } fsResolutionError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; } fsAllocError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; CARD32 bad_length; } fsLengthError; typedef struct { BYTE type; BYTE request; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; CARD8 major_opcode; CARD8 minor_opcode; CARD16 pad; } fsImplementationError; /* events */ typedef struct { BYTE type; BYTE event_code; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; } fsKeepAliveEvent; typedef struct { BYTE type; BYTE event_code; CARD16 sequenceNumber; CARD32 length; fsTimestamp timestamp; BOOL added; BOOL deleted; CARD16 pad; } fsCatalogueChangeNotifyEvent; typedef fsCatalogueChangeNotifyEvent fsFontChangeNotifyEvent; typedef fsCatalogueChangeNotifyEvent fsEvent; /* reply codes */ #define FS_Reply 0 /* normal reply */ #define FS_Error 1 /* error */ #define FS_Event 2 /* request codes */ #define FS_Noop 0 #define FS_ListExtensions 1 #define FS_QueryExtension 2 #define FS_ListCatalogues 3 #define FS_SetCatalogues 4 #define FS_GetCatalogues 5 #define FS_SetEventMask 6 #define FS_GetEventMask 7 #define FS_CreateAC 8 #define FS_FreeAC 9 #define FS_SetAuthorization 10 #define FS_SetResolution 11 #define FS_GetResolution 12 #define FS_ListFonts 13 #define FS_ListFontsWithXInfo 14 #define FS_OpenBitmapFont 15 #define FS_QueryXInfo 16 #define FS_QueryXExtents8 17 #define FS_QueryXExtents16 18 #define FS_QueryXBitmaps8 19 #define FS_QueryXBitmaps16 20 #define FS_CloseFont 21 /* restore decls */ #undef Mask #undef Font #undef AccContext #endif /* _FS_PROTO_H_ */ X11/extensions/xf86dga.h000064400000000561151027430550010740 0ustar00#ifdef _XF86DGA_SERVER_ #warning "xf86dga.h is obsolete and may be removed in the future." #warning "include instead." #include #else #warning "xf86dga.h is obsolete and may be removed in the future." #warning "include instead." #include #endif X11/extensions/cupproto.h000064400000005771151027430550011354 0ustar00/* Copyright 1987, 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _XCUPPROTO_H_ /* { */ #define _XCUPPROTO_H_ #include #define X_XcupQueryVersion 0 #define X_XcupGetReservedColormapEntries 1 #define X_XcupStoreColors 2 typedef struct _XcupQueryVersion { CARD8 reqType; /* always XcupReqCode */ CARD8 xcupReqType; /* always X_XcupQueryVersion */ CARD16 length; CARD16 client_major_version; CARD16 client_minor_version; } xXcupQueryVersionReq; #define sz_xXcupQueryVersionReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequence_number; CARD32 length; CARD16 server_major_version; CARD16 server_minor_version; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXcupQueryVersionReply; #define sz_xXcupQueryVersionReply 32 typedef struct _XcupGetReservedColormapEntries { CARD8 reqType; /* always XcupReqCode */ CARD8 xcupReqType; /* always X_XcupGetReservedColormapEntries */ CARD16 length; CARD32 screen; } xXcupGetReservedColormapEntriesReq; #define sz_xXcupGetReservedColormapEntriesReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequence_number; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xXcupGetReservedColormapEntriesReply; #define sz_xXcupGetReservedColormapEntriesReply 32 typedef struct _XcupStoreColors { CARD8 reqType; /* always XcupReqCode */ CARD8 xcupReqType; /* always X_XcupStoreColors */ CARD16 length; CARD32 cmap; } xXcupStoreColorsReq; #define sz_xXcupStoreColorsReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequence_number; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xXcupStoreColorsReply; #define sz_xXcupStoreColorsReply 32 #endif /* } _XCUPPROTO_H_ */ X11/extensions/recordstr.h000064400000000402151027430550011472 0ustar00#warning "recordstr.h is obsolete and may be removed in the future." #warning "include for the library interfaces." #warning "include for the protocol defines." #include X11/extensions/lbxproto.h000064400000060316151027430550011346 0ustar00/* * Copyright 1992 Network Computing Devices * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of NCD. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. NCD. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * NCD. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL NCD. * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef _LBXPROTO_H_ #define _LBXPROTO_H_ #include /* * NOTE: any changes or additions to the opcodes needs to be reflected * in the lbxCacheable array in Xserver/lbx/lbxmain.c */ #define X_LbxQueryVersion 0 #define X_LbxStartProxy 1 #define X_LbxStopProxy 2 #define X_LbxSwitch 3 #define X_LbxNewClient 4 #define X_LbxCloseClient 5 #define X_LbxModifySequence 6 #define X_LbxAllowMotion 7 #define X_LbxIncrementPixel 8 #define X_LbxDelta 9 #define X_LbxGetModifierMapping 10 #define X_LbxInvalidateTag 12 #define X_LbxPolyPoint 13 #define X_LbxPolyLine 14 #define X_LbxPolySegment 15 #define X_LbxPolyRectangle 16 #define X_LbxPolyArc 17 #define X_LbxFillPoly 18 #define X_LbxPolyFillRectangle 19 #define X_LbxPolyFillArc 20 #define X_LbxGetKeyboardMapping 21 #define X_LbxQueryFont 22 #define X_LbxChangeProperty 23 #define X_LbxGetProperty 24 #define X_LbxTagData 25 #define X_LbxCopyArea 26 #define X_LbxCopyPlane 27 #define X_LbxPolyText8 28 #define X_LbxPolyText16 29 #define X_LbxImageText8 30 #define X_LbxImageText16 31 #define X_LbxQueryExtension 32 #define X_LbxPutImage 33 #define X_LbxGetImage 34 #define X_LbxBeginLargeRequest 35 #define X_LbxLargeRequestData 36 #define X_LbxEndLargeRequest 37 #define X_LbxInternAtoms 38 #define X_LbxGetWinAttrAndGeom 39 #define X_LbxGrabCmap 40 #define X_LbxReleaseCmap 41 #define X_LbxAllocColor 42 #define X_LbxSync 43 /* * Redefine some basic types used by structures defined herein. This removes * any possibility on 64-bit architectures of one entity viewing communicated * data as 32-bit quantities and another entity viewing the same data as 64-bit * quantities. */ #define XID CARD32 #define Atom CARD32 #define Colormap CARD32 #define Drawable CARD32 #define VisualID CARD32 #define Window CARD32 typedef struct { BOOL success; /* TRUE */ BOOL changeType; CARD16 majorVersion, minorVersion; CARD16 length; /* 1/4 additional bytes in setup info */ CARD32 tag; } xLbxConnSetupPrefix; typedef struct _LbxQueryVersion { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxQueryVersion */ CARD16 length; } xLbxQueryVersionReq; #define sz_xLbxQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of LBX protocol */ CARD16 minorVersion; /* minor version of LBX protocol */ CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxQueryVersionReply; #define sz_xLbxQueryVersionReply 32 typedef struct _LbxStartProxy { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxStartProxy */ CARD16 length; } xLbxStartProxyReq; #define sz_xLbxStartProxyReq 4 typedef struct _LbxStopProxy { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxStopProxy */ CARD16 length; } xLbxStopProxyReq; #define sz_xLbxStopProxyReq 4 typedef struct _LbxSwitch { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxSwitch */ CARD16 length; CARD32 client; /* new client */ } xLbxSwitchReq; #define sz_xLbxSwitchReq 8 typedef struct _LbxNewClient { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxNewClient */ CARD16 length; CARD32 client; /* new client */ } xLbxNewClientReq; #define sz_xLbxNewClientReq 8 typedef struct _LbxCloseClient { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxCloseClient */ CARD16 length; CARD32 client; /* new client */ } xLbxCloseClientReq; #define sz_xLbxCloseClientReq 8 typedef struct _LbxModifySequence { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxModifySequence */ CARD16 length; CARD32 adjust; } xLbxModifySequenceReq; #define sz_xLbxModifySequenceReq 8 typedef struct _LbxAllowMotion { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxAllowMotion */ CARD16 length; CARD32 num; } xLbxAllowMotionReq; #define sz_xLbxAllowMotionReq 8 typedef struct { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxGrabCmap */ CARD16 length; Colormap cmap; } xLbxGrabCmapReq; #define sz_xLbxGrabCmapReq 8 #define LBX_SMART_GRAB 0x80 #define LBX_AUTO_RELEASE 0x40 #define LBX_3CHANNELS 0x20 #define LBX_2BYTE_PIXELS 0x10 #define LBX_RGB_BITS_MASK 0x0f #define LBX_LIST_END 0 #define LBX_PIXEL_PRIVATE 1 #define LBX_PIXEL_SHARED 2 #define LBX_PIXEL_RANGE_PRIVATE 3 #define LBX_PIXEL_RANGE_SHARED 4 #define LBX_NEXT_CHANNEL 5 typedef struct { BYTE type; /* X_Reply */ CARD8 flags; CARD16 sequenceNumber; CARD32 length; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xLbxGrabCmapReply; #define sz_xLbxGrabCmapReply 32 #define sz_xLbxGrabCmapReplyHdr 8 typedef struct { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxReleaseCmap */ CARD16 length; Colormap cmap; } xLbxReleaseCmapReq; #define sz_xLbxReleaseCmapReq 8 typedef struct { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxAllocColor */ CARD16 length; Colormap cmap; CARD32 pixel; CARD16 red, green, blue; CARD16 pad; } xLbxAllocColorReq; #define sz_xLbxAllocColorReq 20 typedef struct _LbxIncrementPixel { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxIncrementPixel */ CARD16 length; CARD32 cmap; CARD32 pixel; } xLbxIncrementPixelReq; #define sz_xLbxIncrementPixelReq 12 typedef struct _LbxDelta { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxDelta */ CARD16 length; CARD8 diffs; /* number of diffs */ CARD8 cindex; /* cache index */ /* list of diffs follows */ } xLbxDeltaReq; #define sz_xLbxDeltaReq 6 typedef struct _LbxGetModifierMapping { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxGetModifierMapping */ CARD16 length; } xLbxGetModifierMappingReq; #define sz_xLbxGetModifierMappingReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 keyspermod; CARD16 sequenceNumber; CARD32 length; CARD32 tag; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxGetModifierMappingReply; #define sz_xLbxGetModifierMappingReply 32 typedef struct _LbxGetKeyboardMapping { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxGetKeyboardMapping */ CARD16 length; KeyCode firstKeyCode; CARD8 count; CARD16 pad1; } xLbxGetKeyboardMappingReq; #define sz_xLbxGetKeyboardMappingReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 keysperkeycode; CARD16 sequenceNumber; CARD32 length; CARD32 tag; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxGetKeyboardMappingReply; #define sz_xLbxGetKeyboardMappingReply 32 typedef struct _LbxQueryFont { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxQueryFont */ CARD16 length; CARD32 fid; } xLbxQueryFontReq; #define sz_xLbxQueryFontReq 8 typedef struct _LbxInternAtoms { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxInternAtoms */ CARD16 length; CARD16 num; } xLbxInternAtomsReq; #define sz_xLbxInternAtomsReq 6 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 atomsStart; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxInternAtomsReply; #define sz_xLbxInternAtomsReply 32 #define sz_xLbxInternAtomsReplyHdr 8 typedef struct _LbxGetWinAttrAndGeom { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxGetWinAttrAndGeom */ CARD16 length; CARD32 id; /* window id */ } xLbxGetWinAttrAndGeomReq; #define sz_xLbxGetWinAttrAndGeomReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 backingStore; CARD16 sequenceNumber; CARD32 length; /* NOT 0; this is an extra-large reply */ VisualID visualID; #if defined(__cplusplus) || defined(c_plusplus) CARD16 c_class; #else CARD16 class; #endif CARD8 bitGravity; CARD8 winGravity; CARD32 backingBitPlanes; CARD32 backingPixel; BOOL saveUnder; BOOL mapInstalled; CARD8 mapState; BOOL override; Colormap colormap; CARD32 allEventMasks; CARD32 yourEventMask; CARD16 doNotPropagateMask; CARD16 pad1; Window root; INT16 x, y; CARD16 width, height; CARD16 borderWidth; CARD8 depth; CARD8 pad2; } xLbxGetWinAttrAndGeomReply; #define sz_xLbxGetWinAttrAndGeomReply 60 typedef struct { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxSync */ CARD16 length; } xLbxSyncReq; #define sz_xLbxSyncReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xLbxSyncReply; #define sz_xLbxSyncReply 32 /* an LBX squished charinfo packs the data in a CARD32 as follows */ #define LBX_WIDTH_SHIFT 26 #define LBX_LEFT_SHIFT 20 #define LBX_RIGHT_SHIFT 13 #define LBX_ASCENT_SHIFT 7 #define LBX_DESCENT_SHIFT 0 #define LBX_WIDTH_BITS 6 #define LBX_LEFT_BITS 6 #define LBX_RIGHT_BITS 7 #define LBX_ASCENT_BITS 6 #define LBX_DESCENT_BITS 7 #define LBX_WIDTH_MASK 0xfc000000 #define LBX_LEFT_MASK 0x03f00000 #define LBX_RIGHT_MASK 0x000fe000 #define LBX_ASCENT_MASK 0x00001f80 #define LBX_DESCENT_MASK 0x0000007f #define LBX_MASK_BITS(val, n) ((unsigned int) ((val) & ((1 << (n)) - 1))) typedef struct { CARD32 metrics; } xLbxCharInfo; /* note that this is identical to xQueryFontReply except for missing * first 2 words */ typedef struct { xCharInfo minBounds; /* XXX do we need to leave this gunk? */ #ifndef WORD64 CARD32 walign1; #endif xCharInfo maxBounds; #ifndef WORD64 CARD32 walign2; #endif CARD16 minCharOrByte2, maxCharOrByte2; CARD16 defaultChar; CARD16 nFontProps; /* followed by this many xFontProp structures */ CARD8 drawDirection; CARD8 minByte1, maxByte1; BOOL allCharsExist; INT16 fontAscent, fontDescent; CARD32 nCharInfos; /* followed by this many xLbxCharInfo structures */ } xLbxFontInfo; typedef struct { BYTE type; /* X_Reply */ CARD8 compression; CARD16 sequenceNumber; CARD32 length; CARD32 tag; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; /* X_QueryFont sticks much of the data in the base reply packet, * but we hope that it won't be needed, (and it won't fit in 32 bytes * with the tag anyways) * * if any additional data is needed, its sent in a xLbxFontInfo */ } xLbxQueryFontReply; #define sz_xLbxQueryFontReply 32 typedef struct _LbxChangeProperty { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxChangeProperty */ CARD16 length; Window window; Atom property; Atom type; CARD8 format; CARD8 mode; BYTE pad[2]; CARD32 nUnits; } xLbxChangePropertyReq; #define sz_xLbxChangePropertyReq 24 typedef struct { BYTE type; /* X_Reply */ CARD8 pad; CARD16 sequenceNumber; CARD32 length; CARD32 tag; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxChangePropertyReply; #define sz_xLbxChangePropertyReply 32 typedef struct _LbxGetProperty { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxGetProperty */ CARD16 length; Window window; Atom property; Atom type; CARD8 delete; BYTE pad[3]; CARD32 longOffset; CARD32 longLength; } xLbxGetPropertyReq; #define sz_xLbxGetPropertyReq 28 typedef struct { BYTE type; /* X_Reply */ CARD8 format; CARD16 sequenceNumber; CARD32 length; Atom propertyType; CARD32 bytesAfter; CARD32 nItems; CARD32 tag; CARD32 pad1; CARD32 pad2; } xLbxGetPropertyReply; #define sz_xLbxGetPropertyReply 32 typedef struct _LbxTagData { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxTagData */ CARD16 length; XID tag; CARD32 real_length; /* data */ } xLbxTagDataReq; #define sz_xLbxTagDataReq 12 typedef struct _LbxInvalidateTag { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxInvalidateTag */ CARD16 length; CARD32 tag; } xLbxInvalidateTagReq; #define sz_xLbxInvalidateTagReq 8 typedef struct _LbxPutImage { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxPutImage */ CARD16 length; CARD8 compressionMethod; CARD8 cacheEnts; CARD8 bitPacked; /* rest is variable */ } xLbxPutImageReq; #define sz_xLbxPutImageReq 7 typedef struct { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxGetImage */ CARD16 length; Drawable drawable; INT16 x, y; CARD16 width, height; CARD32 planeMask; CARD8 format; CARD8 pad1; CARD16 pad2; } xLbxGetImageReq; #define sz_xLbxGetImageReq 24 typedef struct { BYTE type; /* X_Reply */ CARD8 depth; CARD16 sequenceNumber; CARD32 lbxLength; CARD32 xLength; VisualID visual; CARD8 compressionMethod; CARD8 pad1; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xLbxGetImageReply; #define sz_xLbxGetImageReply 32 /* Following used for LbxPolyPoint, LbxPolyLine, LbxPolySegment, LbxPolyRectangle, LbxPolyArc, LbxPolyFillRectangle and LbxPolyFillArc */ #define GFX_CACHE_SIZE 15 #define GFXdCacheEnt(e) ((e) & 0xf) #define GFXgCacheEnt(e) (((e) >> 4) & 0xf) #define GFXCacheEnts(d,g) (((d) & 0xf) | (((g) & 0xf) << 4)) #define GFXCacheNone 0xf typedef struct _LbxPolyPoint { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; CARD16 length; CARD8 cacheEnts; CARD8 padBytes; } xLbxPolyPointReq; #define sz_xLbxPolyPointReq 6 typedef xLbxPolyPointReq xLbxPolyLineReq; typedef xLbxPolyPointReq xLbxPolySegmentReq; typedef xLbxPolyPointReq xLbxPolyRectangleReq; typedef xLbxPolyPointReq xLbxPolyArcReq; typedef xLbxPolyPointReq xLbxPolyFillRectangleReq; typedef xLbxPolyPointReq xLbxPolyFillArcReq; #define sz_xLbxPolyLineReq sz_xLbxPolyPointReq #define sz_xLbxPolySegmentReq sz_xLbxPolyPointReq #define sz_xLbxPolyRectangleReq sz_xLbxPolyPointReq #define sz_xLbxPolyArcReq sz_xLbxPolyPointReq #define sz_xLbxPolyFillRectangleReq sz_xLbxPolyPointReq #define sz_xLbxPolyFillArc sz_xLbxPolyPointReq typedef struct _LbxFillPoly { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; CARD16 length; CARD8 cacheEnts; BYTE shape; CARD8 padBytes; } xLbxFillPolyReq; #define sz_xLbxFillPolyReq 7 typedef struct _LbxCopyArea { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; CARD16 length; CARD8 srcCache; /* source drawable */ CARD8 cacheEnts; /* dest drawable and gc */ /* followed by encoded src x, src y, dst x, dst y, width, height */ } xLbxCopyAreaReq; #define sz_xLbxCopyAreaReq 6 typedef struct _LbxCopyPlane { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; CARD16 length; CARD32 bitPlane; CARD8 srcCache; /* source drawable */ CARD8 cacheEnts; /* dest drawable and gc */ /* followed by encoded src x, src y, dst x, dst y, width, height */ } xLbxCopyPlaneReq; #define sz_xLbxCopyPlaneReq 10 typedef struct _LbxPolyText { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; CARD16 length; CARD8 cacheEnts; /* followed by encoded src x, src y coordinates and text elts */ } xLbxPolyTextReq; #define sz_xLbxPolyTextReq 5 typedef xLbxPolyTextReq xLbxPolyText8Req; typedef xLbxPolyTextReq xLbxPolyText16Req; #define sz_xLbxPolyTextReq 5 #define sz_xLbxPolyText8Req 5 #define sz_xLbxPolyText16Req 5 typedef struct _LbxImageText { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; CARD16 length; CARD8 cacheEnts; CARD8 nChars; /* followed by encoded src x, src y coordinates and string */ } xLbxImageTextReq; typedef xLbxImageTextReq xLbxImageText8Req; typedef xLbxImageTextReq xLbxImageText16Req; #define sz_xLbxImageTextReq 6 #define sz_xLbxImageText8Req 6 #define sz_xLbxImageText16Req 6 typedef struct { CARD8 offset; CARD8 diff; } xLbxDiffItem; #define sz_xLbxDiffItem 2 typedef struct { BYTE type; /* X_Reply */ CARD8 nOpts; CARD16 sequenceNumber; CARD32 length; CARD32 optDataStart; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxStartReply; #define sz_xLbxStartReply 32 #define sz_xLbxStartReplyHdr 8 typedef struct _LbxQueryExtension { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxQueryExtension */ CARD16 length; CARD32 nbytes; } xLbxQueryExtensionReq; #define sz_xLbxQueryExtensionReq 8 typedef struct _LbxQueryExtensionReply { BYTE type; /* X_Reply */ CARD8 numReqs; CARD16 sequenceNumber; CARD32 length; BOOL present; CARD8 major_opcode; CARD8 first_event; CARD8 first_error; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; /* reply & event generating requests */ } xLbxQueryExtensionReply; #define sz_xLbxQueryExtensionReply 32 typedef struct _LbxBeginLargeRequest { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxBeginLargeRequest */ CARD16 length; CARD32 largeReqLength; } xLbxBeginLargeRequestReq; #define sz_BeginLargeRequestReq 8 typedef struct _LbxLargeRequestData { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxLargeRequestData */ CARD16 length; /* followed by LISTofCARD8 data */ } xLbxLargeRequestDataReq; #define sz_LargeRequestDataReq 4 typedef struct _LbxEndLargeRequest { CARD8 reqType; /* always LbxReqCode */ CARD8 lbxReqType; /* always X_LbxEndLargeRequest */ CARD16 length; } xLbxEndLargeRequestReq; #define sz_EndLargeRequestReq 4 typedef struct _LbxSwitchEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxSwitchEvent */ CARD16 pad; CARD32 client; } xLbxSwitchEvent; #define sz_xLbxSwitchEvent 8 typedef struct _LbxCloseEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxCloseEvent */ CARD16 sequenceNumber; CARD32 client; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xLbxCloseEvent; #define sz_xLbxCloseEvent 32 typedef struct _LbxInvalidateTagEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxInvalidateTagEvent */ CARD16 sequenceNumber; CARD32 tag; CARD32 tagType; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xLbxInvalidateTagEvent; #define sz_xLbxInvalidateTagEvent 32 typedef struct _LbxSendTagDataEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxSendTagDataEvent */ CARD16 sequenceNumber; CARD32 tag; CARD32 tagType; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xLbxSendTagDataEvent; #define sz_xLbxSendTagDataEvent 32 typedef struct _LbxListenToOneEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxListenToOneEvent */ CARD16 sequenceNumber; CARD32 client; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xLbxListenToOneEvent; #define sz_xLbxListenToOneEvent 32 typedef struct _LbxListenToAllEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxListenToAllEvent */ CARD16 sequenceNumber; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xLbxListenToAllEvent; #define sz_xLbxListenToOneEvent 32 typedef struct _LbxReleaseCmapEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxReleaseCmapEvent */ CARD16 sequenceNumber; Colormap colormap; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xLbxReleaseCmapEvent; #define sz_xLbxReleaseCmapEvent 32 typedef struct _LbxFreeCellsEvent { BYTE type; /* always eventBase + LbxEvent */ BYTE lbxType; /* LbxFreeCellsEvent */ CARD16 sequenceNumber; Colormap colormap; CARD32 pixelStart; CARD32 pixelEnd; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xLbxFreeCellsEvent; #define sz_xLbxFreeCellsEvent 32 /* * squished X event sizes. If these change, be sure to update lbxquish.c * and unsquish.c appropriately * * lbxsz_* is the padded squished length * lbxupsz_* is the unpadded squished length */ #define lbxsz_KeyButtonEvent 32 #define lbxupsz_KeyButtonEvent 31 #define lbxsz_EnterLeaveEvent 32 #define lbxupsz_EnterLeaveEvent 32 #define lbxsz_FocusEvent 12 #define lbxupsz_FocusEvent 9 #define lbxsz_KeymapEvent 32 #define lbxupsz_KeymapEvent 32 #define lbxsz_ExposeEvent 20 #define lbxupsz_ExposeEvent 18 #define lbxsz_GfxExposeEvent 24 #define lbxupsz_GfxExposeEvent 21 #define lbxsz_NoExposeEvent 12 #define lbxupsz_NoExposeEvent 11 #define lbxsz_VisibilityEvent 12 #define lbxupsz_VisibilityEvent 9 #define lbxsz_CreateNotifyEvent 24 #define lbxupsz_CreateNotifyEvent 23 #define lbxsz_DestroyNotifyEvent 12 #define lbxupsz_DestroyNotifyEvent 12 #define lbxsz_UnmapNotifyEvent 16 #define lbxupsz_UnmapNotifyEvent 13 #define lbxsz_MapNotifyEvent 16 #define lbxupsz_MapNotifyEvent 13 #define lbxsz_MapRequestEvent 12 #define lbxupsz_MapRequestEvent 12 #define lbxsz_ReparentEvent 24 #define lbxupsz_ReparentEvent 21 #define lbxsz_ConfigureNotifyEvent 28 #define lbxupsz_ConfigureNotifyEvent 27 #define lbxsz_ConfigureRequestEvent 28 #define lbxupsz_ConfigureRequestEvent 28 #define lbxsz_GravityEvent 16 #define lbxupsz_GravityEvent 16 #define lbxsz_ResizeRequestEvent 12 #define lbxupsz_ResizeRequestEvent 12 #define lbxsz_CirculateEvent 20 #define lbxupsz_CirculateEvent 17 #define lbxsz_PropertyEvent 20 #define lbxupsz_PropertyEvent 17 #define lbxsz_SelectionClearEvent 16 #define lbxupsz_SelectionClearEvent 16 #define lbxsz_SelectionRequestEvent 28 #define lbxupsz_SelectionRequestEvent 28 #define lbxsz_SelectionNotifyEvent 24 #define lbxupsz_SelectionNotifyEvent 24 #define lbxsz_ColormapEvent 16 #define lbxupsz_ColormapEvent 14 #define lbxsz_MappingNotifyEvent 8 #define lbxupsz_MappingNotifyEvent 7 #define lbxsz_ClientMessageEvent 32 #define lbxupsz_ClientMessageEvent 32 #define lbxsz_UnknownEvent 32 #ifdef DEBUG #define DBG_SWITCH 0x00000001 #define DBG_CLOSE 0x00000002 #define DBG_IO 0x00000004 #define DBG_READ_REQ 0x00000008 #define DBG_LEN 0x00000010 #define DBG_BLOCK 0x00000020 #define DBG_CLIENT 0x00000040 #define DBG_DELTA 0x00000080 #endif /* * Cancel the previous redefinition of the basic types, thus restoring their * X.h definitions. */ #undef XID #undef Atom #undef Colormap #undef Drawable #undef VisualID #undef Window #endif /* _LBXPROTO_H_ */ X11/extensions/presenttokens.h000064400000007015151027430550012376 0ustar00/* * Copyright © 2013 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of the copyright holders not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no representations * about the suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #ifndef _PRESENT_TOKENS_H_ #define _PRESENT_TOKENS_H_ #define PRESENT_NAME "Present" #define PRESENT_MAJOR 1 #define PRESENT_MINOR 2 #define PresentNumberErrors 0 #define PresentNumberEvents 0 /* Requests */ #define X_PresentQueryVersion 0 #define X_PresentPixmap 1 #define X_PresentNotifyMSC 2 #define X_PresentSelectInput 3 #define X_PresentQueryCapabilities 4 #define PresentNumberRequests 5 /* Present operation options */ #define PresentOptionNone 0 #define PresentOptionAsync (1 << 0) #define PresentOptionCopy (1 << 1) #define PresentOptionUST (1 << 2) #define PresentOptionSuboptimal (1 << 3) #define PresentAllOptions (PresentOptionAsync | \ PresentOptionCopy | \ PresentOptionUST | \ PresentOptionSuboptimal) /* Present capabilities */ #define PresentCapabilityNone 0 #define PresentCapabilityAsync 1 #define PresentCapabilityFence 2 #define PresentCapabilityUST 4 #define PresentAllCapabilities (PresentCapabilityAsync | \ PresentCapabilityFence | \ PresentCapabilityUST) /* Events */ #define PresentConfigureNotify 0 #define PresentCompleteNotify 1 #define PresentIdleNotify 2 #if PRESENT_FUTURE_VERSION #define PresentRedirectNotify 3 #endif /* Event Masks */ #define PresentConfigureNotifyMask 1 #define PresentCompleteNotifyMask 2 #define PresentIdleNotifyMask 4 #if PRESENT_FUTURE_VERSION #define PresentRedirectNotifyMask 8 #endif #if PRESENT_FUTURE_VERSION #define PRESENT_REDIRECT_NOTIFY_MASK PresentRedirectNotifyMask #else #define PRESENT_REDIRECT_NOTIFY_MASK 0 #endif #define PresentAllEvents (PresentConfigureNotifyMask | \ PresentCompleteNotifyMask | \ PresentIdleNotifyMask | \ PRESENT_REDIRECT_NOTIFY_MASK) /* Complete Kinds */ #define PresentCompleteKindPixmap 0 #define PresentCompleteKindNotifyMSC 1 /* Complete Modes */ #define PresentCompleteModeCopy 0 #define PresentCompleteModeFlip 1 #define PresentCompleteModeSkip 2 #define PresentCompleteModeSuboptimalCopy 3 #endif X11/extensions/shapeproto.h000064400000015112151027430550011653 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ #ifndef _SHAPEPROTO_H_ #define _SHAPEPROTO_H_ #include /* * Protocol requests constants and alignment values * These would really be in SHAPE's X.h and Xproto.h equivalents */ #define Window CARD32 #define Time CARD32 #define X_ShapeQueryVersion 0 #define X_ShapeRectangles 1 #define X_ShapeMask 2 #define X_ShapeCombine 3 #define X_ShapeOffset 4 #define X_ShapeQueryExtents 5 #define X_ShapeSelectInput 6 #define X_ShapeInputSelected 7 #define X_ShapeGetRectangles 8 typedef struct _ShapeQueryVersion { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeQueryVersion */ CARD16 length; } xShapeQueryVersionReq; #define sz_xShapeQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of SHAPE protocol */ CARD16 minorVersion; /* minor version of SHAPE protocol */ CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xShapeQueryVersionReply; #define sz_xShapeQueryVersionReply 32 typedef struct _ShapeRectangles { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeRectangles */ CARD16 length; CARD8 op; /* Set, ... */ CARD8 destKind; /* ShapeBounding or ShapeClip */ CARD8 ordering; /* UnSorted, YSorted, YXSorted, YXBanded */ CARD8 pad0; /* not used */ Window dest; INT16 xOff; INT16 yOff; } xShapeRectanglesReq; /* followed by xRects */ #define sz_xShapeRectanglesReq 16 typedef struct _ShapeMask { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeMask */ CARD16 length; CARD8 op; /* Set, ... */ CARD8 destKind; /* ShapeBounding or ShapeClip */ CARD16 junk; /* not used */ Window dest; INT16 xOff; INT16 yOff; CARD32 src; /* 1 bit pixmap */ } xShapeMaskReq; #define sz_xShapeMaskReq 20 typedef struct _ShapeCombine { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeCombine */ CARD16 length; CARD8 op; /* Set, ... */ CARD8 destKind; /* ShapeBounding or ShapeClip */ CARD8 srcKind; /* ShapeBounding or ShapeClip */ CARD8 junk; /* not used */ Window dest; INT16 xOff; INT16 yOff; Window src; } xShapeCombineReq; #define sz_xShapeCombineReq 20 typedef struct _ShapeOffset { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeOffset */ CARD16 length; CARD8 destKind; /* ShapeBounding or ShapeClip */ CARD8 junk1; /* not used */ CARD16 junk2; /* not used */ Window dest; INT16 xOff; INT16 yOff; } xShapeOffsetReq; #define sz_xShapeOffsetReq 16 typedef struct _ShapeQueryExtents { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeQueryExtents */ CARD16 length; Window window; } xShapeQueryExtentsReq; #define sz_xShapeQueryExtentsReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD8 boundingShaped; /* window has bounding shape */ CARD8 clipShaped; /* window has clip shape */ CARD16 unused1; INT16 xBoundingShape; /* extents of bounding shape */ INT16 yBoundingShape; CARD16 widthBoundingShape; CARD16 heightBoundingShape; INT16 xClipShape; /* extents of clip shape */ INT16 yClipShape; CARD16 widthClipShape; CARD16 heightClipShape; CARD32 pad1; } xShapeQueryExtentsReply; #define sz_xShapeQueryExtentsReply 32 typedef struct _ShapeSelectInput { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeSelectInput */ CARD16 length; Window window; BYTE enable; /* xTrue -> send events */ BYTE pad1; CARD16 pad2; } xShapeSelectInputReq; #define sz_xShapeSelectInputReq 12 typedef struct _ShapeNotify { BYTE type; /* always eventBase + ShapeNotify */ BYTE kind; /* either ShapeBounding or ShapeClip */ CARD16 sequenceNumber; Window window; INT16 x; INT16 y; /* extents of new shape */ CARD16 width; CARD16 height; Time time; /* time of change */ BYTE shaped; /* set when a shape actual exists */ BYTE pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; } xShapeNotifyEvent; #define sz_xShapeNotifyEvent 32 typedef struct _ShapeInputSelected { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeInputSelected */ CARD16 length; Window window; } xShapeInputSelectedReq; #define sz_xShapeInputSelectedReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 enabled; /* current status */ CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD32 pad1; /* unused */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xShapeInputSelectedReply; #define sz_xShapeInputSelectedReply 32 typedef struct _ShapeGetRectangles { CARD8 reqType; /* always ShapeReqCode */ CARD8 shapeReqType; /* always X_ShapeGetRectangles */ CARD16 length; Window window; CARD8 kind; /* ShapeBounding or ShapeClip */ CARD8 junk1; CARD16 junk2; } xShapeGetRectanglesReq; #define sz_xShapeGetRectanglesReq 12 typedef struct { BYTE type; /* X_Reply */ CARD8 ordering; /* UnSorted, YSorted, YXSorted, YXBanded */ CARD16 sequenceNumber; CARD32 length; /* not zero */ CARD32 nrects; /* number of rectangles */ CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xShapeGetRectanglesReply; /* followed by xRectangles */ #define sz_xShapeGetRectanglesReply 32 #undef Window #undef Time #endif /* _SHAPEPROTO_H_ */ X11/extensions/mitmiscconst.h000064400000002745151027430550012213 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ /* RANDOM CRUFT! THIS HAS NO OFFICIAL X CONSORTIUM OR X PROJECT TEAM BLESSING */ #ifndef _MITMISCCONST_H_ #define _MITMISCCONST_H_ #define MITMiscNumberEvents 0 #define MITMiscNumberErrors 0 #define MITMISCNAME "MIT-SUNDRY-NONSTANDARD" #endif X11/extensions/xf86dgaproto.h000064400000015702151027430550012027 0ustar00/* Copyright (c) 1995 Jon Tombs Copyright (c) 1995 XFree86 Inc. */ #ifndef _XF86DGAPROTO_H_ #define _XF86DGAPROTO_H_ #include #include #define XF86DGANAME "XFree86-DGA" #define XDGA_MAJOR_VERSION 2 /* current version numbers */ #define XDGA_MINOR_VERSION 0 typedef struct _XDGAQueryVersion { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_DGAQueryVersion */ CARD16 length; } xXDGAQueryVersionReq; #define sz_xXDGAQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of DGA protocol */ CARD16 minorVersion; /* minor version of DGA protocol */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXDGAQueryVersionReply; #define sz_xXDGAQueryVersionReply 32 typedef struct _XDGAQueryModes { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; } xXDGAQueryModesReq; #define sz_xXDGAQueryModesReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 number; /* number of modes available */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXDGAQueryModesReply; #define sz_xXDGAQueryModesReply 32 typedef struct _XDGASetMode { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD32 mode; /* mode number to init */ CARD32 pid; /* Pixmap descriptor */ } xXDGASetModeReq; #define sz_xXDGASetModeReq 16 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 offset; /* offset into framebuffer map */ CARD32 flags; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXDGASetModeReply; #define sz_xXDGASetModeReply 32 typedef struct { CARD8 byte_order; CARD8 depth; CARD16 num; CARD16 bpp; CARD16 name_size; CARD32 vsync_num; CARD32 vsync_den; CARD32 flags; CARD16 image_width; CARD16 image_height; CARD16 pixmap_width; CARD16 pixmap_height; CARD32 bytes_per_scanline; CARD32 red_mask; CARD32 green_mask; CARD32 blue_mask; CARD16 visual_class; CARD16 pad1; CARD16 viewport_width; CARD16 viewport_height; CARD16 viewport_xstep; CARD16 viewport_ystep; CARD16 viewport_xmax; CARD16 viewport_ymax; CARD32 viewport_flags; CARD32 reserved1; CARD32 reserved2; } xXDGAModeInfo; #define sz_xXDGAModeInfo 72 typedef struct _XDGAOpenFramebuffer { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; } xXDGAOpenFramebufferReq; #define sz_xXDGAOpenFramebufferReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; /* device name size if there is one */ CARD32 mem1; /* physical memory */ CARD32 mem2; /* spillover for _alpha_ */ CARD32 size; /* size of map in bytes */ CARD32 offset; /* optional offset into device */ CARD32 extra; /* extra info associated with the map */ CARD32 pad2; } xXDGAOpenFramebufferReply; #define sz_xXDGAOpenFramebufferReply 32 typedef struct _XDGACloseFramebuffer { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; } xXDGACloseFramebufferReq; #define sz_xXDGACloseFramebufferReq 8 typedef struct _XDGASetViewport { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD16 x; CARD16 y; CARD32 flags; } xXDGASetViewportReq; #define sz_xXDGASetViewportReq 16 typedef struct _XDGAInstallColormap { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD32 cmap; } xXDGAInstallColormapReq; #define sz_xXDGAInstallColormapReq 12 typedef struct _XDGASelectInput { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD32 mask; } xXDGASelectInputReq; #define sz_xXDGASelectInputReq 12 typedef struct _XDGAFillRectangle { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD16 x; CARD16 y; CARD16 width; CARD16 height; CARD32 color; } xXDGAFillRectangleReq; #define sz_xXDGAFillRectangleReq 20 typedef struct _XDGACopyArea { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD16 srcx; CARD16 srcy; CARD16 width; CARD16 height; CARD16 dstx; CARD16 dsty; } xXDGACopyAreaReq; #define sz_xXDGACopyAreaReq 20 typedef struct _XDGACopyTransparentArea { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD16 srcx; CARD16 srcy; CARD16 width; CARD16 height; CARD16 dstx; CARD16 dsty; CARD32 key; } xXDGACopyTransparentAreaReq; #define sz_xXDGACopyTransparentAreaReq 24 typedef struct _XDGAGetViewportStatus { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; } xXDGAGetViewportStatusReq; #define sz_xXDGAGetViewportStatusReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXDGAGetViewportStatusReply; #define sz_xXDGAGetViewportStatusReply 32 typedef struct _XDGASync { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; } xXDGASyncReq; #define sz_xXDGASyncReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xXDGASyncReply; #define sz_xXDGASyncReply 32 typedef struct _XDGASetClientVersion { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD16 major; CARD16 minor; } xXDGASetClientVersionReq; #define sz_xXDGASetClientVersionReq 8 typedef struct { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD16 x; CARD16 y; CARD32 flags; } xXDGAChangePixmapModeReq; #define sz_xXDGAChangePixmapModeReq 16 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 x; CARD16 y; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xXDGAChangePixmapModeReply; #define sz_xXDGAChangePixmapModeReply 32 typedef struct _XDGACreateColormap { CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD32 screen; CARD32 id; CARD32 mode; CARD8 alloc; CARD8 pad1; CARD16 pad2; } xXDGACreateColormapReq; #define sz_xXDGACreateColormapReq 20 typedef struct { union { struct { BYTE type; BYTE detail; CARD16 sequenceNumber; } u; struct { CARD32 pad0; CARD32 time; INT16 dx; INT16 dy; INT16 screen; CARD16 state; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } event; } u; } dgaEvent; #endif /* _XF86DGAPROTO_H_ */ X11/extensions/mitmiscproto.h000064400000004265151027430550012227 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ /* RANDOM CRUFT! THIS HAS NO OFFICIAL X CONSORTIUM OR X PROJECT TEAM BLESSING */ #ifndef _MITMISCPROTO_H_ #define _MITMISCPROTO_H_ #include #define X_MITSetBugMode 0 #define X_MITGetBugMode 1 typedef struct _SetBugMode { CARD8 reqType; /* always MITReqCode */ CARD8 mitReqType; /* always X_MITSetBugMode */ CARD16 length; BOOL onOff; BYTE pad0; CARD16 pad1; } xMITSetBugModeReq; #define sz_xMITSetBugModeReq 8 typedef struct _GetBugMode { CARD8 reqType; /* always MITReqCode */ CARD8 mitReqType; /* always X_MITGetBugMode */ CARD16 length; } xMITGetBugModeReq; #define sz_xMITGetBugModeReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL onOff; CARD16 sequenceNumber; CARD32 length; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xMITGetBugModeReply; #define sz_xMITGetBugModeReply 32 #endif /* _MITMISCPROTO_H_ */ X11/extensions/XI.h000064400000023137151027430550010015 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1989 by Hewlett-Packard Company, Palo Alto, California. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Hewlett-Packard not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL HEWLETT-PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ /* Definitions used by the server, library and client */ #ifndef _XI_H_ #define _XI_H_ #define sz_xGetExtensionVersionReq 8 #define sz_xGetExtensionVersionReply 32 #define sz_xListInputDevicesReq 4 #define sz_xListInputDevicesReply 32 #define sz_xOpenDeviceReq 8 #define sz_xOpenDeviceReply 32 #define sz_xCloseDeviceReq 8 #define sz_xSetDeviceModeReq 8 #define sz_xSetDeviceModeReply 32 #define sz_xSelectExtensionEventReq 12 #define sz_xGetSelectedExtensionEventsReq 8 #define sz_xGetSelectedExtensionEventsReply 32 #define sz_xChangeDeviceDontPropagateListReq 12 #define sz_xGetDeviceDontPropagateListReq 8 #define sz_xGetDeviceDontPropagateListReply 32 #define sz_xGetDeviceMotionEventsReq 16 #define sz_xGetDeviceMotionEventsReply 32 #define sz_xChangeKeyboardDeviceReq 8 #define sz_xChangeKeyboardDeviceReply 32 #define sz_xChangePointerDeviceReq 8 #define sz_xChangePointerDeviceReply 32 #define sz_xGrabDeviceReq 20 #define sz_xGrabDeviceReply 32 #define sz_xUngrabDeviceReq 12 #define sz_xGrabDeviceKeyReq 20 #define sz_xGrabDeviceKeyReply 32 #define sz_xUngrabDeviceKeyReq 16 #define sz_xGrabDeviceButtonReq 20 #define sz_xGrabDeviceButtonReply 32 #define sz_xUngrabDeviceButtonReq 16 #define sz_xAllowDeviceEventsReq 12 #define sz_xGetDeviceFocusReq 8 #define sz_xGetDeviceFocusReply 32 #define sz_xSetDeviceFocusReq 16 #define sz_xGetFeedbackControlReq 8 #define sz_xGetFeedbackControlReply 32 #define sz_xChangeFeedbackControlReq 12 #define sz_xGetDeviceKeyMappingReq 8 #define sz_xGetDeviceKeyMappingReply 32 #define sz_xChangeDeviceKeyMappingReq 8 #define sz_xGetDeviceModifierMappingReq 8 #define sz_xSetDeviceModifierMappingReq 8 #define sz_xSetDeviceModifierMappingReply 32 #define sz_xGetDeviceButtonMappingReq 8 #define sz_xGetDeviceButtonMappingReply 32 #define sz_xSetDeviceButtonMappingReq 8 #define sz_xSetDeviceButtonMappingReply 32 #define sz_xQueryDeviceStateReq 8 #define sz_xQueryDeviceStateReply 32 #define sz_xSendExtensionEventReq 16 #define sz_xDeviceBellReq 8 #define sz_xSetDeviceValuatorsReq 8 #define sz_xSetDeviceValuatorsReply 32 #define sz_xGetDeviceControlReq 8 #define sz_xGetDeviceControlReply 32 #define sz_xChangeDeviceControlReq 8 #define sz_xChangeDeviceControlReply 32 #define sz_xListDevicePropertiesReq 8 #define sz_xListDevicePropertiesReply 32 #define sz_xChangeDevicePropertyReq 20 #define sz_xDeleteDevicePropertyReq 12 #define sz_xGetDevicePropertyReq 24 #define sz_xGetDevicePropertyReply 32 #define INAME "XInputExtension" #define XI_KEYBOARD "KEYBOARD" #define XI_MOUSE "MOUSE" #define XI_TABLET "TABLET" #define XI_TOUCHSCREEN "TOUCHSCREEN" #define XI_TOUCHPAD "TOUCHPAD" #define XI_BARCODE "BARCODE" #define XI_BUTTONBOX "BUTTONBOX" #define XI_KNOB_BOX "KNOB_BOX" #define XI_ONE_KNOB "ONE_KNOB" #define XI_NINE_KNOB "NINE_KNOB" #define XI_TRACKBALL "TRACKBALL" #define XI_QUADRATURE "QUADRATURE" #define XI_ID_MODULE "ID_MODULE" #define XI_SPACEBALL "SPACEBALL" #define XI_DATAGLOVE "DATAGLOVE" #define XI_EYETRACKER "EYETRACKER" #define XI_CURSORKEYS "CURSORKEYS" #define XI_FOOTMOUSE "FOOTMOUSE" #define XI_JOYSTICK "JOYSTICK" /* Indices into the versions[] array (XExtInt.c). Used as a index to * retrieve the minimum version of XI from _XiCheckExtInit */ #define Dont_Check 0 #define XInput_Initial_Release 1 #define XInput_Add_XDeviceBell 2 #define XInput_Add_XSetDeviceValuators 3 #define XInput_Add_XChangeDeviceControl 4 #define XInput_Add_DevicePresenceNotify 5 #define XInput_Add_DeviceProperties 6 /* DO NOT ADD TO HERE -> XI2 */ #define XI_Absent 0 #define XI_Present 1 #define XI_Initial_Release_Major 1 #define XI_Initial_Release_Minor 0 #define XI_Add_XDeviceBell_Major 1 #define XI_Add_XDeviceBell_Minor 1 #define XI_Add_XSetDeviceValuators_Major 1 #define XI_Add_XSetDeviceValuators_Minor 2 #define XI_Add_XChangeDeviceControl_Major 1 #define XI_Add_XChangeDeviceControl_Minor 3 #define XI_Add_DevicePresenceNotify_Major 1 #define XI_Add_DevicePresenceNotify_Minor 4 #define XI_Add_DeviceProperties_Major 1 #define XI_Add_DeviceProperties_Minor 5 #define DEVICE_RESOLUTION 1 #define DEVICE_ABS_CALIB 2 #define DEVICE_CORE 3 #define DEVICE_ENABLE 4 #define DEVICE_ABS_AREA 5 #define NoSuchExtension 1 #define COUNT 0 #define CREATE 1 #define NewPointer 0 #define NewKeyboard 1 #define XPOINTER 0 #define XKEYBOARD 1 #define UseXKeyboard 0xFF #define IsXPointer 0 #define IsXKeyboard 1 #define IsXExtensionDevice 2 #define IsXExtensionKeyboard 3 #define IsXExtensionPointer 4 #define AsyncThisDevice 0 #define SyncThisDevice 1 #define ReplayThisDevice 2 #define AsyncOtherDevices 3 #define AsyncAll 4 #define SyncAll 5 #define FollowKeyboard 3 #ifndef RevertToFollowKeyboard #define RevertToFollowKeyboard 3 #endif #define DvAccelNum (1L << 0) #define DvAccelDenom (1L << 1) #define DvThreshold (1L << 2) #define DvKeyClickPercent (1L<<0) #define DvPercent (1L<<1) #define DvPitch (1L<<2) #define DvDuration (1L<<3) #define DvLed (1L<<4) #define DvLedMode (1L<<5) #define DvKey (1L<<6) #define DvAutoRepeatMode (1L<<7) #define DvString (1L << 0) #define DvInteger (1L << 0) #define DeviceMode (1L << 0) #define Relative 0 #define Absolute 1 #define ProximityState (1L << 1) #define InProximity (0L << 1) #define OutOfProximity (1L << 1) #define AddToList 0 #define DeleteFromList 1 #define KeyClass 0 #define ButtonClass 1 #define ValuatorClass 2 #define FeedbackClass 3 #define ProximityClass 4 #define FocusClass 5 #define OtherClass 6 #define AttachClass 7 #define KbdFeedbackClass 0 #define PtrFeedbackClass 1 #define StringFeedbackClass 2 #define IntegerFeedbackClass 3 #define LedFeedbackClass 4 #define BellFeedbackClass 5 #define _devicePointerMotionHint 0 #define _deviceButton1Motion 1 #define _deviceButton2Motion 2 #define _deviceButton3Motion 3 #define _deviceButton4Motion 4 #define _deviceButton5Motion 5 #define _deviceButtonMotion 6 #define _deviceButtonGrab 7 #define _deviceOwnerGrabButton 8 #define _noExtensionEvent 9 #define _devicePresence 0 #define _deviceEnter 0 #define _deviceLeave 1 /* Device presence notify states */ #define DeviceAdded 0 #define DeviceRemoved 1 #define DeviceEnabled 2 #define DeviceDisabled 3 #define DeviceUnrecoverable 4 #define DeviceControlChanged 5 /* XI Errors */ #define XI_BadDevice 0 #define XI_BadEvent 1 #define XI_BadMode 2 #define XI_DeviceBusy 3 #define XI_BadClass 4 /* * Make XEventClass be a CARD32 for 64 bit servers. Don't affect client * definition of XEventClass since that would be a library interface change. * See the top of X.h for more _XSERVER64 magic. * * But, don't actually use the CARD32 type. We can't get it defined here * without polluting the namespace. */ #ifdef _XSERVER64 typedef unsigned int XEventClass; #else typedef unsigned long XEventClass; #endif /******************************************************************* * * Extension version structure. * */ typedef struct { int present; short major_version; short minor_version; } XExtensionVersion; #endif /* _XI_H_ */ X11/extensions/dpmsconst.h000064400000003362151027430550011505 0ustar00/***************************************************************** Copyright (c) 1996 Digital Equipment Corporation, Maynard, Massachusetts. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING, BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Digital Equipment Corporation shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Digital Equipment Corporation. ******************************************************************/ #ifndef _DPMSCONST_H #define _DPMSCONST_H 1 #define DPMSMajorVersion 1 #define DPMSMinorVersion 2 #define DPMSExtensionName "DPMS" #define DPMSModeOn 0 #define DPMSModeStandby 1 #define DPMSModeSuspend 2 #define DPMSModeOff 3 #define DPMSInfoNotifyMask (1L << 0) #define DPMSInfoNotify 0 #endif /* !_DPMSCONST_H */ X11/extensions/recordproto.h000064400000016722151027430550012041 0ustar00/*************************************************************************** * Copyright 1995 Network Computing Devices * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Network Computing Devices * not be used in advertising or publicity pertaining to distribution * of the software without specific, written prior permission. * * NETWORK COMPUTING DEVICES DISCLAIMs ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL NETWORK COMPUTING DEVICES BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **************************************************************************/ #ifndef _RECORDPROTO_H_ #define _RECORDPROTO_H_ #include /* only difference between 1.12 and 1.13 is byte order of device events, which the library doesn't deal with. */ /********************************************************* * * Protocol request constants * */ #define X_RecordQueryVersion 0 /* First request from client */ #define X_RecordCreateContext 1 /* Create client RC */ #define X_RecordRegisterClients 2 /* Add to client RC */ #define X_RecordUnregisterClients 3 /* Delete from client RC */ #define X_RecordGetContext 4 /* Query client RC */ #define X_RecordEnableContext 5 /* Enable interception and reporting */ #define X_RecordDisableContext 6 /* Disable interception and reporting */ #define X_RecordFreeContext 7 /* Free client RC */ #define sz_XRecordRange 32 #define sz_XRecordClientInfo 12 #define sz_XRecordState 16 #define sz_XRecordDatum 32 #define XRecordGlobaldef #define XRecordGlobalref extern #define RecordMaxEvent (128L-1L) #define RecordMinDeviceEvent (2L) #define RecordMaxDeviceEvent (6L) #define RecordMaxError (256L-1L) #define RecordMaxCoreRequest (128L-1L) #define RecordMaxExtRequest (256L-1L) #define RecordMinExtRequest (129L-1L) #define RECORD_RC CARD32 #define RECORD_XIDBASE CARD32 #define RECORD_CLIENTSPEC CARD32 #define RECORD_ELEMENT_HEADER CARD8 typedef RECORD_CLIENTSPEC RecordClientSpec, *RecordClientSpecPtr; typedef struct { CARD8 first; CARD8 last; } RECORD_RANGE8; typedef struct { CARD16 first; CARD16 last; } RECORD_RANGE16; typedef struct { RECORD_RANGE8 majorCode; RECORD_RANGE16 minorCode; } RECORD_EXTRANGE; typedef struct { RECORD_RANGE8 coreRequests; RECORD_RANGE8 coreReplies; RECORD_EXTRANGE extRequests; RECORD_EXTRANGE extReplies; RECORD_RANGE8 deliveredEvents; RECORD_RANGE8 deviceEvents; RECORD_RANGE8 errors; BOOL clientStarted; BOOL clientDied; } RECORDRANGE; #define sz_RECORDRANGE 24 /* typedef RECORDRANGE xRecordRange, *xRecordRangePtr; #define sz_xRecordRange 24 */ /* Cannot have structures within structures going over the wire */ typedef struct { CARD8 coreRequestsFirst; CARD8 coreRequestsLast; CARD8 coreRepliesFirst; CARD8 coreRepliesLast; CARD8 extRequestsMajorFirst; CARD8 extRequestsMajorLast; CARD16 extRequestsMinorFirst; CARD16 extRequestsMinorLast; CARD8 extRepliesMajorFirst; CARD8 extRepliesMajorLast; CARD16 extRepliesMinorFirst; CARD16 extRepliesMinorLast; CARD8 deliveredEventsFirst; CARD8 deliveredEventsLast; CARD8 deviceEventsFirst; CARD8 deviceEventsLast; CARD8 errorsFirst; CARD8 errorsLast; BOOL clientStarted; BOOL clientDied; } xRecordRange; #define sz_xRecordRange 24 typedef struct { RECORD_CLIENTSPEC clientResource; CARD32 nRanges; /* LISTofRECORDRANGE */ } RECORD_CLIENT_INFO; typedef RECORD_CLIENT_INFO xRecordClientInfo; /* * Initialize */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; CARD16 majorVersion; CARD16 minorVersion; } xRecordQueryVersionReq; #define sz_xRecordQueryVersionReq 8 typedef struct { CARD8 type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; CARD16 minorVersion; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRecordQueryVersionReply; #define sz_xRecordQueryVersionReply 32 /* * Create RC */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; RECORD_ELEMENT_HEADER elementHeader; CARD8 pad; CARD16 pad0; CARD32 nClients; CARD32 nRanges; /* LISTofRECORD_CLIENTSPEC */ /* LISTofRECORDRANGE */ } xRecordCreateContextReq; #define sz_xRecordCreateContextReq 20 /* * Add to RC */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; RECORD_ELEMENT_HEADER elementHeader; CARD8 pad; CARD16 pad0; CARD32 nClients; CARD32 nRanges; /* LISTofRECORD_CLIENTSPEC */ /* LISTofRECORDRANGE */ } xRecordRegisterClientsReq; #define sz_xRecordRegisterClientsReq 20 /* * Delete from RC */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; CARD32 nClients; /* LISTofRECORD_CLIENTSPEC */ } xRecordUnregisterClientsReq; #define sz_xRecordUnregisterClientsReq 12 /* * Query RC */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; } xRecordGetContextReq; #define sz_xRecordGetContextReq 8 typedef struct { CARD8 type; BOOL enabled; CARD16 sequenceNumber; CARD32 length; RECORD_ELEMENT_HEADER elementHeader; CARD8 pad; CARD16 pad0; CARD32 nClients; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; /* LISTofCLIENT_INFO */ /* intercepted-clients */ } xRecordGetContextReply; #define sz_xRecordGetContextReply 32 /* * Enable data interception */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; } xRecordEnableContextReq; #define sz_xRecordEnableContextReq 8 typedef struct { CARD8 type; CARD8 category; CARD16 sequenceNumber; CARD32 length; RECORD_ELEMENT_HEADER elementHeader; BOOL clientSwapped; CARD16 pad1; RECORD_XIDBASE idBase; CARD32 serverTime; CARD32 recordedSequenceNumber; CARD32 pad3; CARD32 pad4; /* BYTE data; */ } xRecordEnableContextReply; #define sz_xRecordEnableContextReply 32 /* * Disable data interception */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; } xRecordDisableContextReq; #define sz_xRecordDisableContextReq 8 /* * Free RC */ typedef struct { CARD8 reqType; CARD8 recordReqType; CARD16 length; RECORD_RC context; } xRecordFreeContextReq; #define sz_xRecordFreeContextReq 8 #undef RECORD_RC #undef RECORD_XIDBASE #undef RECORD_ELEMENT_HEADER #undef RECORD_CLIENTSPEC #endif X11/extensions/saverproto.h000064400000012014151027430550011671 0ustar00/* Copyright (c) 1992 X Consortium Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. * * Author: Keith Packard, MIT X Consortium */ #ifndef _SAVERPROTO_H_ #define _SAVERPROTO_H_ #include #define Window CARD32 #define Drawable CARD32 #define Font CARD32 #define Pixmap CARD32 #define Cursor CARD32 #define Colormap CARD32 #define GContext CARD32 #define Atom CARD32 #define VisualID CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define X_ScreenSaverQueryVersion 0 typedef struct _ScreenSaverQueryVersion { CARD8 reqType; /* always ScreenSaverReqCode */ CARD8 saverReqType; /* always X_ScreenSaverQueryVersion */ CARD16 length; CARD8 clientMajor; CARD8 clientMinor; CARD16 unused; } xScreenSaverQueryVersionReq; #define sz_xScreenSaverQueryVersionReq 8 typedef struct { CARD8 type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of protocol */ CARD16 minorVersion; /* minor version of protocol */ CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xScreenSaverQueryVersionReply; #define sz_xScreenSaverQueryVersionReply 32 #define X_ScreenSaverQueryInfo 1 typedef struct _ScreenSaverQueryInfo { CARD8 reqType; /* always ScreenSaverReqCode */ CARD8 saverReqType; /* always X_ScreenSaverQueryInfo */ CARD16 length; Drawable drawable; } xScreenSaverQueryInfoReq; #define sz_xScreenSaverQueryInfoReq 8 typedef struct { CARD8 type; /* X_Reply */ BYTE state; /* Off, On */ CARD16 sequenceNumber; CARD32 length; Window window; CARD32 tilOrSince; CARD32 idle; CARD32 eventMask; BYTE kind; /* Blanked, Internal, External */ CARD8 pad0; CARD16 pad1; CARD32 pad2; } xScreenSaverQueryInfoReply; #define sz_xScreenSaverQueryInfoReply 32 #define X_ScreenSaverSelectInput 2 typedef struct _ScreenSaverSelectInput { CARD8 reqType; /* always ScreenSaverReqCode */ CARD8 saverReqType; /* always X_ScreenSaverSelectInput */ CARD16 length; Drawable drawable; CARD32 eventMask; } xScreenSaverSelectInputReq; #define sz_xScreenSaverSelectInputReq 12 #define X_ScreenSaverSetAttributes 3 typedef struct _ScreenSaverSetAttributes { CARD8 reqType; /* always ScreenSaverReqCode */ CARD8 saverReqType; /* always X_ScreenSaverSetAttributes */ CARD16 length; Drawable drawable; INT16 x, y; CARD16 width, height, borderWidth; BYTE c_class; CARD8 depth; VisualID visualID; CARD32 mask; } xScreenSaverSetAttributesReq; #define sz_xScreenSaverSetAttributesReq 28 #define X_ScreenSaverUnsetAttributes 4 typedef struct _ScreenSaverUnsetAttributes { CARD8 reqType; /* always ScreenSaverReqCode */ CARD8 saverReqType; /* always X_ScreenSaverUnsetAttributes */ CARD16 length; Drawable drawable; } xScreenSaverUnsetAttributesReq; #define sz_xScreenSaverUnsetAttributesReq 8 #define X_ScreenSaverSuspend 5 typedef struct _ScreenSaverSuspend { CARD8 reqType; CARD8 saverReqType; CARD16 length; CARD32 suspend; /* a boolean, but using the wrong encoding */ } xScreenSaverSuspendReq; #define sz_xScreenSaverSuspendReq 8 typedef struct _ScreenSaverNotify { CARD8 type; /* always eventBase + ScreenSaverNotify */ BYTE state; /* off, on, cycle */ CARD16 sequenceNumber; Time timestamp; Window root; Window window; /* screen saver window */ BYTE kind; /* blanked, internal, external */ BYTE forced; CARD16 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xScreenSaverNotifyEvent; #define sz_xScreenSaverNotifyEvent 32 #undef Window #undef Drawable #undef Font #undef Pixmap #undef Cursor #undef Colormap #undef GContext #undef Atom #undef VisualID #undef Time #undef KeyCode #undef KeySym #endif /* _SAVERPROTO_H_ */ X11/extensions/xf86dga1str.h000064400000000277151027430550011556 0ustar00#warning "xf86dga1str.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/extensions/syncconst.h000064400000015136151027430550011520 0ustar00/* Copyright 1991, 1993, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /*********************************************************** Copyright 1991,1993 by Digital Equipment Corporation, Maynard, Massachusetts, and Olivetti Research Limited, Cambridge, England. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Digital or Olivetti not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL AND OLIVETTI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THEY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef _SYNCCONST_H_ #define _SYNCCONST_H_ #define SYNC_NAME "SYNC" #define SYNC_MAJOR_VERSION 3 #define SYNC_MINOR_VERSION 1 #define XSyncCounterNotify 0 #define XSyncAlarmNotify 1 #define XSyncAlarmNotifyMask (1L << XSyncAlarmNotify) #define XSyncNumberEvents 2L #define XSyncBadCounter 0L #define XSyncBadAlarm 1L #define XSyncBadFence 2L #define XSyncNumberErrors (XSyncBadFence + 1) /* * Flags for Alarm Attributes */ #define XSyncCACounter (1L<<0) #define XSyncCAValueType (1L<<1) #define XSyncCAValue (1L<<2) #define XSyncCATestType (1L<<3) #define XSyncCADelta (1L<<4) #define XSyncCAEvents (1L<<5) /* The _XSync macros below are for library internal use only. They exist * so that if we have to make a fix, we can change it in this one place * and have both the macro and function variants inherit the fix. */ #define _XSyncIntToValue(pv, i) ((pv)->hi=((i<0)?~0:0),(pv)->lo=(i)) #define _XSyncIntsToValue(pv, l, h) ((pv)->lo = (l), (pv)->hi = (h)) #define _XSyncValueGreaterThan(a, b)\ ((a).hi>(b).hi || ((a).hi==(b).hi && (a).lo>(b).lo)) #define _XSyncValueLessThan(a, b)\ ((a).hi<(b).hi || ((a).hi==(b).hi && (a).lo<(b).lo)) #define _XSyncValueGreaterOrEqual(a, b)\ ((a).hi>(b).hi || ((a).hi==(b).hi && (a).lo>=(b).lo)) #define _XSyncValueLessOrEqual(a, b)\ ((a).hi<(b).hi || ((a).hi==(b).hi && (a).lo<=(b).lo)) #define _XSyncValueEqual(a, b) ((a).lo==(b).lo && (a).hi==(b).hi) #define _XSyncValueIsNegative(v) (((v).hi & 0x80000000) ? 1 : 0) #define _XSyncValueIsZero(a) ((a).lo==0 && (a).hi==0) #define _XSyncValueIsPositive(v) (((v).hi & 0x80000000) ? 0 : 1) #define _XSyncValueLow32(v) ((v).lo) #define _XSyncValueHigh32(v) ((v).hi) #define _XSyncValueAdd(presult,a,b,poverflow) {\ int t = (a).lo;\ Bool signa = XSyncValueIsNegative(a);\ Bool signb = XSyncValueIsNegative(b);\ ((presult)->lo = (a).lo + (b).lo);\ ((presult)->hi = (a).hi + (b).hi);\ if (t>(presult)->lo) (presult)->hi++;\ *poverflow = ((signa == signb) && !(signa == XSyncValueIsNegative(*presult)));\ } #define _XSyncValueSubtract(presult,a,b,poverflow) {\ int t = (a).lo;\ Bool signa = XSyncValueIsNegative(a);\ Bool signb = XSyncValueIsNegative(b);\ ((presult)->lo = (a).lo - (b).lo);\ ((presult)->hi = (a).hi - (b).hi);\ if (t<(presult)->lo) (presult)->hi--;\ *poverflow = ((signa == signb) && !(signa == XSyncValueIsNegative(*presult)));\ } #define _XSyncMaxValue(pv) ((pv)->hi = 0x7fffffff, (pv)->lo = 0xffffffff) #define _XSyncMinValue(pv) ((pv)->hi = 0x80000000, (pv)->lo = 0) /* * These are the publically usable macros. If you want the function version * of one of these, just #undef the macro to uncover the function. * (This is the same convention that the ANSI C library uses.) */ #define XSyncIntToValue(pv, i) _XSyncIntToValue(pv, i) #define XSyncIntsToValue(pv, l, h) _XSyncIntsToValue(pv, l, h) #define XSyncValueGreaterThan(a, b) _XSyncValueGreaterThan(a, b) #define XSyncValueLessThan(a, b) _XSyncValueLessThan(a, b) #define XSyncValueGreaterOrEqual(a, b) _XSyncValueGreaterOrEqual(a, b) #define XSyncValueLessOrEqual(a, b) _XSyncValueLessOrEqual(a, b) #define XSyncValueEqual(a, b) _XSyncValueEqual(a, b) #define XSyncValueIsNegative(v) _XSyncValueIsNegative(v) #define XSyncValueIsZero(a) _XSyncValueIsZero(a) #define XSyncValueIsPositive(v) _XSyncValueIsPositive(v) #define XSyncValueLow32(v) _XSyncValueLow32(v) #define XSyncValueHigh32(v) _XSyncValueHigh32(v) #define XSyncValueAdd(presult,a,b,poverflow) _XSyncValueAdd(presult,a,b,poverflow) #define XSyncValueSubtract(presult,a,b,poverflow) _XSyncValueSubtract(presult,a,b,poverflow) #define XSyncMaxValue(pv) _XSyncMaxValue(pv) #define XSyncMinValue(pv) _XSyncMinValue(pv) /* * Constants for the value_type argument of various requests */ typedef enum { XSyncAbsolute, XSyncRelative } XSyncValueType; /* * Alarm Test types */ typedef enum { XSyncPositiveTransition, XSyncNegativeTransition, XSyncPositiveComparison, XSyncNegativeComparison } XSyncTestType; /* * Alarm state constants */ typedef enum { XSyncAlarmActive, XSyncAlarmInactive, XSyncAlarmDestroyed } XSyncAlarmState; typedef XID XSyncCounter; typedef XID XSyncAlarm; typedef XID XSyncFence; typedef struct _XSyncValue { int hi; unsigned int lo; } XSyncValue; #endif /* _SYNCCONST_H_ */ X11/extensions/shapestr.h000064400000000374151027430550011324 0ustar00#ifndef _SHAPESTR_H_ #define _SHAPESTR_H_ #warning "shapestr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include #endif /* _SHAPESTR_H_ */ X11/extensions/XvMC.h000064400000007044151027430550010311 0ustar00#ifndef _XVMC_H_ #define _XVMC_H_ #include #include #define XvMCName "XVideo-MotionCompensation" #define XvMCNumEvents 0 #define XvMCNumErrors 3 #define XvMCVersion 1 #define XvMCRevision 1 #define XvMCBadContext 0 #define XvMCBadSurface 1 #define XvMCBadSubpicture 2 /* Chroma formats */ #define XVMC_CHROMA_FORMAT_420 0x00000001 #define XVMC_CHROMA_FORMAT_422 0x00000002 #define XVMC_CHROMA_FORMAT_444 0x00000003 /* XvMCSurfaceInfo Flags */ #define XVMC_OVERLAID_SURFACE 0x00000001 #define XVMC_BACKEND_SUBPICTURE 0x00000002 #define XVMC_SUBPICTURE_INDEPENDENT_SCALING 0x00000004 #define XVMC_INTRA_UNSIGNED 0x00000008 /* Motion Compensation types */ #define XVMC_MOCOMP 0x00000000 #define XVMC_IDCT 0x00010000 #define XVMC_MPEG_1 0x00000001 #define XVMC_MPEG_2 0x00000002 #define XVMC_H263 0x00000003 #define XVMC_MPEG_4 0x00000004 #define XVMC_MB_TYPE_MOTION_FORWARD 0x02 #define XVMC_MB_TYPE_MOTION_BACKWARD 0x04 #define XVMC_MB_TYPE_PATTERN 0x08 #define XVMC_MB_TYPE_INTRA 0x10 #define XVMC_PREDICTION_FIELD 0x01 #define XVMC_PREDICTION_FRAME 0x02 #define XVMC_PREDICTION_DUAL_PRIME 0x03 #define XVMC_PREDICTION_16x8 0x02 #define XVMC_PREDICTION_4MV 0x04 #define XVMC_SELECT_FIRST_FORWARD 0x01 #define XVMC_SELECT_FIRST_BACKWARD 0x02 #define XVMC_SELECT_SECOND_FORWARD 0x04 #define XVMC_SELECT_SECOND_BACKWARD 0x08 #define XVMC_DCT_TYPE_FRAME 0x00 #define XVMC_DCT_TYPE_FIELD 0x01 #define XVMC_TOP_FIELD 0x00000001 #define XVMC_BOTTOM_FIELD 0x00000002 #define XVMC_FRAME_PICTURE (XVMC_TOP_FIELD | XVMC_BOTTOM_FIELD) #define XVMC_SECOND_FIELD 0x00000004 #define XVMC_DIRECT 0x00000001 #define XVMC_RENDERING 0x00000001 #define XVMC_DISPLAYING 0x00000002 typedef struct { int surface_type_id; int chroma_format; unsigned short max_width; unsigned short max_height; unsigned short subpicture_max_width; unsigned short subpicture_max_height; int mc_type; int flags; } XvMCSurfaceInfo; typedef struct { XID context_id; int surface_type_id; unsigned short width; unsigned short height; XvPortID port; int flags; void * privData; /* private to the library */ } XvMCContext; typedef struct { XID surface_id; XID context_id; int surface_type_id; unsigned short width; unsigned short height; void *privData; /* private to the library */ } XvMCSurface; typedef struct { XID subpicture_id; XID context_id; int xvimage_id; unsigned short width; unsigned short height; int num_palette_entries; int entry_bytes; char component_order[4]; void *privData; /* private to the library */ } XvMCSubpicture; typedef struct { unsigned int num_blocks; XID context_id; void *privData; short *blocks; } XvMCBlockArray; typedef struct { unsigned short x; unsigned short y; unsigned char macroblock_type; unsigned char motion_type; unsigned char motion_vertical_field_select; unsigned char dct_type; short PMV[2][2][2]; unsigned int index; unsigned short coded_block_pattern; unsigned short pad0; } XvMCMacroBlock; typedef struct { unsigned int num_blocks; XID context_id; void *privData; XvMCMacroBlock *macro_blocks; } XvMCMacroBlockArray; #endif X11/extensions/Xvproto.h000064400000027515151027430550011162 0ustar00/*********************************************************** Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts, and the Massachusetts Institute of Technology, Cambridge, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Digital or MIT not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef XVPROTO_H #define XVPROTO_H /* ** File: ** ** Xvproto.h --- Xv protocol header file ** ** Author: ** ** David Carver (Digital Workstation Engineering/Project Athena) ** ** Revisions: ** ** 11.06.91 Carver ** - changed SetPortControl to SetPortAttribute ** - changed GetPortControl to GetPortAttribute ** - changed QueryBestSize ** ** 15.05.91 Carver ** - version 2.0 upgrade ** ** 24.01.91 Carver ** - version 1.4 upgrade ** */ #include /* Symbols: These are undefined at the end of this file to restore the values they have in Xv.h */ #define XvPortID CARD32 #define XvEncodingID CARD32 #define ShmSeg CARD32 #define VisualID CARD32 #define Drawable CARD32 #define GContext CARD32 #define Time CARD32 #define Atom CARD32 /* Structures */ typedef struct { INT32 numerator; INT32 denominator; } xvRational; #define sz_xvRational 8 typedef struct { XvPortID base_id; CARD16 name_size; CARD16 num_ports; CARD16 num_formats; CARD8 type; CARD8 pad; } xvAdaptorInfo; #define sz_xvAdaptorInfo 12 typedef struct { XvEncodingID encoding; CARD16 name_size; CARD16 width, height; CARD16 pad; xvRational rate; } xvEncodingInfo; #define sz_xvEncodingInfo (12 + sz_xvRational) typedef struct { VisualID visual; CARD8 depth; CARD8 pad1; CARD16 pad2; } xvFormat; #define sz_xvFormat 8 typedef struct { CARD32 flags; INT32 min; INT32 max; CARD32 size; } xvAttributeInfo; #define sz_xvAttributeInfo 16 typedef struct { CARD32 id; CARD8 type; CARD8 byte_order; CARD16 pad1; CARD8 guid[16]; CARD8 bpp; CARD8 num_planes; CARD16 pad2; CARD8 depth; CARD8 pad3; CARD16 pad4; CARD32 red_mask; CARD32 green_mask; CARD32 blue_mask; CARD8 format; CARD8 pad5; CARD16 pad6; CARD32 y_sample_bits; CARD32 u_sample_bits; CARD32 v_sample_bits; CARD32 horz_y_period; CARD32 horz_u_period; CARD32 horz_v_period; CARD32 vert_y_period; CARD32 vert_u_period; CARD32 vert_v_period; CARD8 comp_order[32]; CARD8 scanline_order; CARD8 pad7; CARD16 pad8; CARD32 pad9; CARD32 pad10; } xvImageFormatInfo; #define sz_xvImageFormatInfo 128 /* Requests */ #define xv_QueryExtension 0 #define xv_QueryAdaptors 1 #define xv_QueryEncodings 2 #define xv_GrabPort 3 #define xv_UngrabPort 4 #define xv_PutVideo 5 #define xv_PutStill 6 #define xv_GetVideo 7 #define xv_GetStill 8 #define xv_StopVideo 9 #define xv_SelectVideoNotify 10 #define xv_SelectPortNotify 11 #define xv_QueryBestSize 12 #define xv_SetPortAttribute 13 #define xv_GetPortAttribute 14 #define xv_QueryPortAttributes 15 #define xv_ListImageFormats 16 #define xv_QueryImageAttributes 17 #define xv_PutImage 18 #define xv_ShmPutImage 19 #define xv_LastRequest xv_ShmPutImage #define xvNumRequests (xv_LastRequest + 1) typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; } xvQueryExtensionReq; #define sz_xvQueryExtensionReq 4 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; CARD32 window; } xvQueryAdaptorsReq; #define sz_xvQueryAdaptorsReq 8 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; CARD32 port; } xvQueryEncodingsReq; #define sz_xvQueryEncodingsReq 8 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; GContext gc; INT16 vid_x; INT16 vid_y; CARD16 vid_w; CARD16 vid_h; INT16 drw_x; INT16 drw_y; CARD16 drw_w; CARD16 drw_h; } xvPutVideoReq; #define sz_xvPutVideoReq 32 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; GContext gc; INT16 vid_x; INT16 vid_y; CARD16 vid_w; CARD16 vid_h; INT16 drw_x; INT16 drw_y; CARD16 drw_w; CARD16 drw_h; } xvPutStillReq; #define sz_xvPutStillReq 32 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; GContext gc; INT16 vid_x; INT16 vid_y; CARD16 vid_w; CARD16 vid_h; INT16 drw_x; INT16 drw_y; CARD16 drw_w; CARD16 drw_h; } xvGetVideoReq; #define sz_xvGetVideoReq 32 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; GContext gc; INT16 vid_x; INT16 vid_y; CARD16 vid_w; CARD16 vid_h; INT16 drw_x; INT16 drw_y; CARD16 drw_w; CARD16 drw_h; } xvGetStillReq; #define sz_xvGetStillReq 32 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Time time; } xvGrabPortReq; #define sz_xvGrabPortReq 12 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Time time; } xvUngrabPortReq; #define sz_xvUngrabPortReq 12 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; Drawable drawable; BOOL onoff; CARD8 pad1; CARD16 pad2; } xvSelectVideoNotifyReq; #define sz_xvSelectVideoNotifyReq 12 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; BOOL onoff; CARD8 pad1; CARD16 pad2; } xvSelectPortNotifyReq; #define sz_xvSelectPortNotifyReq 12 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; } xvStopVideoReq; #define sz_xvStopVideoReq 12 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Atom attribute; INT32 value; } xvSetPortAttributeReq; #define sz_xvSetPortAttributeReq 16 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Atom attribute; } xvGetPortAttributeReq; #define sz_xvGetPortAttributeReq 12 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; CARD16 vid_w; CARD16 vid_h; CARD16 drw_w; CARD16 drw_h; CARD8 motion; CARD8 pad1; CARD16 pad2; } xvQueryBestSizeReq; #define sz_xvQueryBestSizeReq 20 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; } xvQueryPortAttributesReq; #define sz_xvQueryPortAttributesReq 8 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; GContext gc; CARD32 id; INT16 src_x; INT16 src_y; CARD16 src_w; CARD16 src_h; INT16 drw_x; INT16 drw_y; CARD16 drw_w; CARD16 drw_h; CARD16 width; CARD16 height; } xvPutImageReq; #define sz_xvPutImageReq 40 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; Drawable drawable; GContext gc; ShmSeg shmseg; CARD32 id; CARD32 offset; INT16 src_x; INT16 src_y; CARD16 src_w; CARD16 src_h; INT16 drw_x; INT16 drw_y; CARD16 drw_w; CARD16 drw_h; CARD16 width; CARD16 height; CARD8 send_event; CARD8 pad1; CARD16 pad2; } xvShmPutImageReq; #define sz_xvShmPutImageReq 52 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; XvPortID port; } xvListImageFormatsReq; #define sz_xvListImageFormatsReq 8 typedef struct { CARD8 reqType; CARD8 xvReqType; CARD16 length; CARD32 port; CARD32 id; CARD16 width; CARD16 height; } xvQueryImageAttributesReq; #define sz_xvQueryImageAttributesReq 16 /* Replies */ typedef struct _QueryExtensionReply { BYTE type; /* X_Reply */ CARD8 padb1; CARD16 sequenceNumber; CARD32 length; CARD16 version; CARD16 revision; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvQueryExtensionReply; #define sz_xvQueryExtensionReply 32 typedef struct _QueryAdaptorsReply { BYTE type; /* X_Reply */ CARD8 padb1; CARD16 sequenceNumber; CARD32 length; CARD16 num_adaptors; CARD16 pads3; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvQueryAdaptorsReply; #define sz_xvQueryAdaptorsReply 32 typedef struct _QueryEncodingsReply { BYTE type; /* X_Reply */ CARD8 padb1; CARD16 sequenceNumber; CARD32 length; CARD16 num_encodings; CARD16 padl3; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvQueryEncodingsReply; #define sz_xvQueryEncodingsReply 32 typedef struct { BYTE type; /* X_Reply */ BYTE result; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD32 padl3; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvGrabPortReply; #define sz_xvGrabPortReply 32 typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; /* 0 */ INT32 value; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvGetPortAttributeReply; #define sz_xvGetPortAttributeReply 32 typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD16 actual_width; CARD16 actual_height; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvQueryBestSizeReply; #define sz_xvQueryBestSizeReply 32 typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD32 num_attributes; CARD32 text_size; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvQueryPortAttributesReply; #define sz_xvQueryPortAttributesReply 32 typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 num_formats; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvListImageFormatsReply; #define sz_xvListImageFormatsReply 32 typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 num_planes; CARD32 data_size; CARD16 width; CARD16 height; CARD32 padl6; CARD32 padl7; CARD32 padl8; } xvQueryImageAttributesReply; #define sz_xvQueryImageAttributesReply 32 /* DEFINE EVENT STRUCTURE */ typedef struct { union { struct { BYTE type; BYTE detail; CARD16 sequenceNumber; } u; struct { BYTE type; BYTE reason; CARD16 sequenceNumber; Time time; Drawable drawable; XvPortID port; CARD32 padl5; CARD32 padl6; CARD32 padl7; CARD32 padl8; } videoNotify; struct { BYTE type; BYTE padb1; CARD16 sequenceNumber; Time time; XvPortID port; Atom attribute; INT32 value; CARD32 padl6; CARD32 padl7; CARD32 padl8; } portNotify; } u; } xvEvent; #undef XvPortID #undef XvEncodingID #undef ShmSeg #undef VisualID #undef Drawable #undef GContext #undef Time #undef Atom #endif /* XVPROTO_H */ X11/extensions/dpmsproto.h000064400000012250151027430550011516 0ustar00/***************************************************************** Copyright (c) 1996 Digital Equipment Corporation, Maynard, Massachusetts. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING, BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Digital Equipment Corporation shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Digital Equipment Corporation. ******************************************************************/ #ifndef _DPMSPROTO_H_ #define _DPMSPROTO_H_ #include #define X_DPMSGetVersion 0 #define X_DPMSCapable 1 #define X_DPMSGetTimeouts 2 #define X_DPMSSetTimeouts 3 #define X_DPMSEnable 4 #define X_DPMSDisable 5 #define X_DPMSForceLevel 6 #define X_DPMSInfo 7 #define X_DPMSSelectInput 8 #define DPMSNumberEvents 0 #define DPMSNumberErrors 0 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSGetVersion */ CARD16 length; CARD16 majorVersion; CARD16 minorVersion; } xDPMSGetVersionReq; #define sz_xDPMSGetVersionReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; CARD16 minorVersion; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDPMSGetVersionReply; #define sz_xDPMSGetVersionReply 32 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSCapable */ CARD16 length; } xDPMSCapableReq; #define sz_xDPMSCapableReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; BOOL capable; CARD8 pad1; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xDPMSCapableReply; #define sz_xDPMSCapableReply 32 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSGetTimeouts */ CARD16 length; } xDPMSGetTimeoutsReq; #define sz_xDPMSGetTimeoutsReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 standby; CARD16 suspend; CARD16 off; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDPMSGetTimeoutsReply; #define sz_xDPMSGetTimeoutsReply 32 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSSetTimeouts */ CARD16 length; CARD16 standby; CARD16 suspend; CARD16 off; CARD16 pad0; } xDPMSSetTimeoutsReq; #define sz_xDPMSSetTimeoutsReq 12 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSEnable */ CARD16 length; } xDPMSEnableReq; #define sz_xDPMSEnableReq 4 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSDisable */ CARD16 length; } xDPMSDisableReq; #define sz_xDPMSDisableReq 4 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSForceLevel */ CARD16 length; CARD16 level; /* power level requested */ CARD16 pad0; } xDPMSForceLevelReq; #define sz_xDPMSForceLevelReq 8 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSInfo */ CARD16 length; } xDPMSInfoReq; #define sz_xDPMSInfoReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 power_level; BOOL state; CARD8 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xDPMSInfoReply; #define sz_xDPMSInfoReply 32 typedef struct { CARD8 reqType; /* always DPMSCode */ CARD8 dpmsReqType; /* always X_DPMSSelectInput */ CARD16 length B16; CARD32 eventMask B32; } xDPMSSelectInputReq; #define sz_xDPMSSelectInputReq 8 typedef struct { CARD8 type; CARD8 extension; CARD16 sequenceNumber B16; CARD32 length; CARD16 evtype B16; CARD16 pad0 B16; Time timestamp B32; CARD16 power_level B16; BOOL state; CARD8 pad1; CARD32 pad2 B32; CARD32 pad3 B32; CARD32 pad4 B32; } xDPMSInfoNotifyEvent; #define sz_xDPMSInfoNotifyEvent 32 #endif /* _DPMSPROTO_H_ */ X11/extensions/dri3proto.h000064400000013761151027430550011424 0ustar00/* * Copyright © 2013 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of the copyright holders not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no representations * about the suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #ifndef _DRI3_PROTO_H_ #define _DRI3_PROTO_H_ #define DRI3_NAME "DRI3" #define DRI3_MAJOR 1 #define DRI3_MINOR 2 #define DRI3NumberErrors 0 #define DRI3NumberEvents 0 #define X_DRI3QueryVersion 0 #define X_DRI3Open 1 #define X_DRI3PixmapFromBuffer 2 #define X_DRI3BufferFromPixmap 3 #define X_DRI3FenceFromFD 4 #define X_DRI3FDFromFence 5 /* v1.2 */ #define xDRI3GetSupportedModifiers 6 #define xDRI3PixmapFromBuffers 7 #define xDRI3BuffersFromPixmap 8 #define DRI3NumberRequests 9 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xDRI3QueryVersionReq; #define sz_xDRI3QueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDRI3QueryVersionReply; #define sz_xDRI3QueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 drawable; CARD32 provider; } xDRI3OpenReq; #define sz_xDRI3OpenReq 12 typedef struct { BYTE type; /* X_Reply */ CARD8 nfd; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xDRI3OpenReply; #define sz_xDRI3OpenReply 32 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 pixmap; CARD32 drawable; CARD32 size; CARD16 width; CARD16 height; CARD16 stride; CARD8 depth; CARD8 bpp; } xDRI3PixmapFromBufferReq; #define sz_xDRI3PixmapFromBufferReq 24 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 pixmap; } xDRI3BufferFromPixmapReq; #define sz_xDRI3BufferFromPixmapReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 nfd; /* Number of file descriptors returned (1) */ CARD16 sequenceNumber; CARD32 length; CARD32 size; CARD16 width; CARD16 height; CARD16 stride; CARD8 depth; CARD8 bpp; CARD32 pad20; CARD32 pad24; CARD32 pad28; } xDRI3BufferFromPixmapReply; #define sz_xDRI3BufferFromPixmapReply 32 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 drawable; CARD32 fence; BOOL initially_triggered; CARD8 pad13; CARD16 pad14; } xDRI3FenceFromFDReq; #define sz_xDRI3FenceFromFDReq 16 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 drawable; CARD32 fence; } xDRI3FDFromFenceReq; #define sz_xDRI3FDFromFenceReq 12 typedef struct { BYTE type; /* X_Reply */ CARD8 nfd; /* Number of file descriptors returned (1) */ CARD16 sequenceNumber; CARD32 length; CARD32 pad08; CARD32 pad12; CARD32 pad16; CARD32 pad20; CARD32 pad24; CARD32 pad28; } xDRI3FDFromFenceReply; #define sz_xDRI3FDFromFenceReply 32 /* v1.2 */ typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 window; CARD8 depth; CARD8 bpp; CARD16 pad10; } xDRI3GetSupportedModifiersReq; #define sz_xDRI3GetSupportedModifiersReq 12 typedef struct { BYTE type; /* X_Reply */ CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 numWindowModifiers; CARD32 numScreenModifiers; CARD32 pad16; CARD32 pad20; CARD32 pad24; CARD32 pad28; } xDRI3GetSupportedModifiersReply; #define sz_xDRI3GetSupportedModifiersReply 32 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 pixmap; CARD32 window; CARD8 num_buffers; /* Number of file descriptors passed */ CARD8 pad13; CARD16 pad14; CARD16 width; CARD16 height; CARD32 stride0; CARD32 offset0; CARD32 stride1; CARD32 offset1; CARD32 stride2; CARD32 offset2; CARD32 stride3; CARD32 offset3; CARD8 depth; CARD8 bpp; CARD16 pad54; CARD64 modifier; } xDRI3PixmapFromBuffersReq; #define sz_xDRI3PixmapFromBuffersReq 64 typedef struct { CARD8 reqType; CARD8 dri3ReqType; CARD16 length; CARD32 pixmap; } xDRI3BuffersFromPixmapReq; #define sz_xDRI3BuffersFromPixmapReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 nfd; /* Number of file descriptors returned */ CARD16 sequenceNumber; CARD32 length; CARD16 width; CARD16 height; CARD32 pad12; CARD64 modifier; CARD8 depth; CARD8 bpp; CARD16 pad26; CARD32 pad28; } xDRI3BuffersFromPixmapReply; #define sz_xDRI3BuffersFromPixmapReply 32 #endif X11/extensions/xfixesproto.h000064400000030720151027430550012063 0ustar00/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright 2010 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * Copyright © 2002 Keith Packard, member of The XFree86 Project, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _XFIXESPROTO_H_ #define _XFIXESPROTO_H_ #include #include #include #define Window CARD32 #define Drawable CARD32 #define Font CARD32 #define Pixmap CARD32 #define Cursor CARD32 #define Colormap CARD32 #define GContext CARD32 #define Atom CARD32 #define VisualID CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define Picture CARD32 /*************** Version 1 ******************/ typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; } xXFixesReq; /* * requests and replies */ typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xXFixesQueryVersionReq; #define sz_xXFixesQueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXFixesQueryVersionReply; #define sz_xXFixesQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; BYTE mode; /* SetModeInsert/SetModeDelete*/ BYTE target; /* SaveSetNearest/SaveSetRoot*/ BYTE map; /* SaveSetMap/SaveSetUnmap */ BYTE pad1; Window window; } xXFixesChangeSaveSetReq; #define sz_xXFixesChangeSaveSetReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Window window; Atom selection; CARD32 eventMask; } xXFixesSelectSelectionInputReq; #define sz_xXFixesSelectSelectionInputReq 16 typedef struct { CARD8 type; CARD8 subtype; CARD16 sequenceNumber; Window window; Window owner; Atom selection; Time timestamp; Time selectionTimestamp; CARD32 pad2; CARD32 pad3; } xXFixesSelectionNotifyEvent; typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Window window; CARD32 eventMask; } xXFixesSelectCursorInputReq; #define sz_xXFixesSelectCursorInputReq 12 typedef struct { CARD8 type; CARD8 subtype; CARD16 sequenceNumber; Window window; CARD32 cursorSerial; Time timestamp; Atom name; /* Version 2 */ CARD32 pad1; CARD32 pad2; CARD32 pad3; } xXFixesCursorNotifyEvent; typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; } xXFixesGetCursorImageReq; #define sz_xXFixesGetCursorImageReq 4 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; INT16 x; INT16 y; CARD16 width; CARD16 height; CARD16 xhot; CARD16 yhot; CARD32 cursorSerial; CARD32 pad2; CARD32 pad3; } xXFixesGetCursorImageReply; #define sz_xXFixesGetCursorImageReply 32 /*************** Version 2 ******************/ #define Region CARD32 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; /* LISTofRECTANGLE */ } xXFixesCreateRegionReq; #define sz_xXFixesCreateRegionReq 8 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; Pixmap bitmap; } xXFixesCreateRegionFromBitmapReq; #define sz_xXFixesCreateRegionFromBitmapReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; Window window; CARD8 kind; CARD8 pad1; CARD16 pad2; } xXFixesCreateRegionFromWindowReq; #define sz_xXFixesCreateRegionFromWindowReq 16 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; GContext gc; } xXFixesCreateRegionFromGCReq; #define sz_xXFixesCreateRegionFromGCReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; Picture picture; } xXFixesCreateRegionFromPictureReq; #define sz_xXFixesCreateRegionFromPictureReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; } xXFixesDestroyRegionReq; #define sz_xXFixesDestroyRegionReq 8 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; /* LISTofRECTANGLE */ } xXFixesSetRegionReq; #define sz_xXFixesSetRegionReq 8 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region source; Region destination; } xXFixesCopyRegionReq; #define sz_xXFixesCopyRegionReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region source1; Region source2; Region destination; } xXFixesCombineRegionReq, xXFixesUnionRegionReq, xXFixesIntersectRegionReq, xXFixesSubtractRegionReq; #define sz_xXFixesCombineRegionReq 16 #define sz_xXFixesUnionRegionReq sz_xXFixesCombineRegionReq #define sz_xXFixesIntersectRegionReq sz_xXFixesCombineRegionReq #define sz_xXFixesSubtractRegionReq sz_xXFixesCombineRegionReq typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region source; INT16 x, y; CARD16 width, height; Region destination; } xXFixesInvertRegionReq; #define sz_xXFixesInvertRegionReq 20 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; INT16 dx, dy; } xXFixesTranslateRegionReq; #define sz_xXFixesTranslateRegionReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region source; Region destination; } xXFixesRegionExtentsReq; #define sz_xXFixesRegionExtentsReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region region; } xXFixesFetchRegionReq; #define sz_xXFixesFetchRegionReq 8 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; INT16 x, y; CARD16 width, height; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXFixesFetchRegionReply; #define sz_xXFixesFetchRegionReply 32 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; GContext gc; Region region; INT16 xOrigin, yOrigin; } xXFixesSetGCClipRegionReq; #define sz_xXFixesSetGCClipRegionReq 16 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Window dest; BYTE destKind; CARD8 pad1; CARD16 pad2; INT16 xOff, yOff; Region region; } xXFixesSetWindowShapeRegionReq; #define sz_xXFixesSetWindowShapeRegionReq 20 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Picture picture; Region region; INT16 xOrigin, yOrigin; } xXFixesSetPictureClipRegionReq; #define sz_xXFixesSetPictureClipRegionReq 16 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Cursor cursor; CARD16 nbytes; CARD16 pad; } xXFixesSetCursorNameReq; #define sz_xXFixesSetCursorNameReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Cursor cursor; } xXFixesGetCursorNameReq; #define sz_xXFixesGetCursorNameReq 8 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; Atom atom; CARD16 nbytes; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXFixesGetCursorNameReply; #define sz_xXFixesGetCursorNameReply 32 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; } xXFixesGetCursorImageAndNameReq; #define sz_xXFixesGetCursorImageAndNameReq 4 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; INT16 x; INT16 y; CARD16 width; CARD16 height; CARD16 xhot; CARD16 yhot; CARD32 cursorSerial; Atom cursorName; CARD16 nbytes; CARD16 pad; } xXFixesGetCursorImageAndNameReply; #define sz_xXFixesGetCursorImageAndNameReply 32 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Cursor source; Cursor destination; } xXFixesChangeCursorReq; #define sz_xXFixesChangeCursorReq 12 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Cursor source; CARD16 nbytes; CARD16 pad; } xXFixesChangeCursorByNameReq; #define sz_xXFixesChangeCursorByNameReq 12 /*************** Version 3 ******************/ typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Region source; Region destination; CARD16 left; CARD16 right; CARD16 top; CARD16 bottom; } xXFixesExpandRegionReq; #define sz_xXFixesExpandRegionReq 20 /*************** Version 4.0 ******************/ typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Window window; } xXFixesHideCursorReq; #define sz_xXFixesHideCursorReq sizeof(xXFixesHideCursorReq) typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Window window; } xXFixesShowCursorReq; #define sz_xXFixesShowCursorReq sizeof(xXFixesShowCursorReq) /*************** Version 5.0 ******************/ #define Barrier CARD32 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Barrier barrier; Window window; INT16 x1; INT16 y1; INT16 x2; INT16 y2; CARD32 directions; CARD16 pad; CARD16 num_devices; /* array of CARD16 devices */ } xXFixesCreatePointerBarrierReq; #define sz_xXFixesCreatePointerBarrierReq 28 typedef struct { CARD8 reqType; CARD8 xfixesReqType; CARD16 length; Barrier barrier; } xXFixesDestroyPointerBarrierReq; #define sz_xXFixesDestroyPointerBarrierReq 8 #undef Barrier #undef Region #undef Picture #undef Window #undef Drawable #undef Font #undef Pixmap #undef Cursor #undef Colormap #undef GContext #undef Atom #undef VisualID #undef Time #undef KeyCode #undef KeySym #endif /* _XFIXESPROTO_H_ */ X11/extensions/EVI.h000064400000003033151027430550010111 0ustar00/************************************************************ Copyright (c) 1997 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _EVI_H_ #define _EVI_H_ #define XEVI_TRANSPARENCY_NONE 0 #define XEVI_TRANSPARENCY_PIXEL 1 #define XEVI_TRANSPARENCY_MASK 2 #define EVINAME "Extended-Visual-Information" #define XEVI_MAJOR_VERSION 1 /* current version numbers */ #define XEVI_MINOR_VERSION 0 #endif X11/extensions/securproto.h000064400000006151151027430550011677 0ustar00/* Copyright 1996, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _SECURPROTO_H #define _SECURPROTO_H #include #define X_SecurityQueryVersion 0 #define X_SecurityGenerateAuthorization 1 #define X_SecurityRevokeAuthorization 2 typedef struct { CARD8 reqType; CARD8 securityReqType; CARD16 length; CARD16 majorVersion; CARD16 minorVersion; } xSecurityQueryVersionReq; #define sz_xSecurityQueryVersionReq 8 typedef struct { CARD8 type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; CARD16 minorVersion; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xSecurityQueryVersionReply; #define sz_xSecurityQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 securityReqType; CARD16 length; CARD16 nbytesAuthProto; CARD16 nbytesAuthData; CARD32 valueMask; /* auth protocol name padded to 4 bytes */ /* auth protocol data padded to 4 bytes */ /* list of CARD32 values, if any */ } xSecurityGenerateAuthorizationReq; #define sz_xSecurityGenerateAuthorizationReq 12 typedef struct { CARD8 type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 authId; CARD16 dataLength; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xSecurityGenerateAuthorizationReply; #define sz_xSecurityGenerateAuthorizationReply 32 typedef struct { CARD8 reqType; CARD8 securityReqType; CARD16 length; CARD32 authId; } xSecurityRevokeAuthorizationReq; #define sz_xSecurityRevokeAuthorizationReq 8 typedef struct _xSecurityAuthorizationRevokedEvent { BYTE type; BYTE detail; CARD16 sequenceNumber; CARD32 authId; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xSecurityAuthorizationRevokedEvent; #define sz_xSecurityAuthorizationRevokedEvent 32 #endif /* _SECURPROTO_H */ X11/extensions/shmproto.h000064400000013635151027430550011352 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ /* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */ #ifndef _SHMPROTO_H_ #define _SHMPROTO_H_ #include #define ShmSeg CARD32 #define Drawable CARD32 #define VisualID CARD32 #define GContext CARD32 #define Pixmap CARD32 #define X_ShmQueryVersion 0 #define X_ShmAttach 1 #define X_ShmDetach 2 #define X_ShmPutImage 3 #define X_ShmGetImage 4 #define X_ShmCreatePixmap 5 #define X_ShmAttachFd 6 #define X_ShmCreateSegment 7 typedef struct _ShmQueryVersion { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmQueryVersion */ CARD16 length; } xShmQueryVersionReq; #define sz_xShmQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL sharedPixmaps; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of SHM protocol */ CARD16 minorVersion; /* minor version of SHM protocol */ CARD16 uid; CARD16 gid; CARD8 pixmapFormat; CARD8 pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xShmQueryVersionReply; #define sz_xShmQueryVersionReply 32 typedef struct _ShmAttach { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmAttach */ CARD16 length; ShmSeg shmseg; CARD32 shmid; BOOL readOnly; BYTE pad0; CARD16 pad1; } xShmAttachReq; #define sz_xShmAttachReq 16 typedef struct _ShmDetach { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmDetach */ CARD16 length; ShmSeg shmseg; } xShmDetachReq; #define sz_xShmDetachReq 8 typedef struct _ShmPutImage { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmPutImage */ CARD16 length; Drawable drawable; GContext gc; CARD16 totalWidth; CARD16 totalHeight; CARD16 srcX; CARD16 srcY; CARD16 srcWidth; CARD16 srcHeight; INT16 dstX; INT16 dstY; CARD8 depth; CARD8 format; CARD8 sendEvent; CARD8 bpad; ShmSeg shmseg; CARD32 offset; } xShmPutImageReq; #define sz_xShmPutImageReq 40 typedef struct _ShmGetImage { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmGetImage */ CARD16 length; Drawable drawable; INT16 x; INT16 y; CARD16 width; CARD16 height; CARD32 planeMask; CARD8 format; CARD8 pad0; CARD8 pad1; CARD8 pad2; ShmSeg shmseg; CARD32 offset; } xShmGetImageReq; #define sz_xShmGetImageReq 32 typedef struct _ShmGetImageReply { BYTE type; /* X_Reply */ CARD8 depth; CARD16 sequenceNumber; CARD32 length; VisualID visual; CARD32 size; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xShmGetImageReply; #define sz_xShmGetImageReply 32 typedef struct _ShmCreatePixmap { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmCreatePixmap */ CARD16 length; Pixmap pid; Drawable drawable; CARD16 width; CARD16 height; CARD8 depth; CARD8 pad0; CARD8 pad1; CARD8 pad2; ShmSeg shmseg; CARD32 offset; } xShmCreatePixmapReq; #define sz_xShmCreatePixmapReq 28 typedef struct _ShmCompletion { BYTE type; /* always eventBase + ShmCompletion */ BYTE bpad0; CARD16 sequenceNumber; Drawable drawable; CARD16 minorEvent; BYTE majorEvent; BYTE bpad1; ShmSeg shmseg; CARD32 offset; CARD32 pad0; CARD32 pad1; CARD32 pad2; } xShmCompletionEvent; #define sz_xShmCompletionEvent 32 /* Version 1.2 additions */ typedef struct _ShmAttachFd { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmAttachFd */ CARD16 length; ShmSeg shmseg; BOOL readOnly; BYTE pad0; CARD16 pad1; } xShmAttachFdReq; /* File descriptor is passed with this request */ #define sz_xShmAttachFdReq 12 typedef struct _ShmCreateSegment { CARD8 reqType; /* always ShmReqCode */ CARD8 shmReqType; /* always X_ShmAttachFd */ CARD16 length; ShmSeg shmseg; CARD32 size; BOOL readOnly; BYTE pad0; CARD16 pad1; } xShmCreateSegmentReq; #define sz_xShmCreateSegmentReq 16 typedef struct { CARD8 type; /* must be X_Reply */ CARD8 nfd; /* must be 1 */ CARD16 sequenceNumber; /* last sequence number */ CARD32 length; /* 0 */ CARD32 pad2; /* unused */ CARD32 pad3; /* unused */ CARD32 pad4; /* unused */ CARD32 pad5; /* unused */ CARD32 pad6; /* unused */ CARD32 pad7; /* unused */ } xShmCreateSegmentReply; /* File descriptor is passed with this reply */ #define sz_xShmCreateSegmentReply 32 #undef ShmSeg #undef Drawable #undef VisualID #undef GContext #undef Pixmap #endif /* _SHMPROTO_H_ */ X11/extensions/xf86bigfont.h000064400000000636151027430550011640 0ustar00/* * Declarations for the BIGFONT extension. * * Copyright (c) 1999-2000 Bruno Haible * Copyright (c) 1999-2000 The XFree86 Project, Inc. */ /* THIS IS NOT AN X CONSORTIUM STANDARD */ #ifndef _XF86BIGFONT_H_ #define _XF86BIGFONT_H_ #define X_XF86BigfontQueryVersion 0 #define X_XF86BigfontQueryFont 1 #define XF86BigfontNumberEvents 0 #define XF86BigfontNumberErrors 0 #endif /* _XF86BIGFONT_H_ */ X11/extensions/randrproto.h000064400000062227151027430550011672 0ustar00/* * Copyright © 2000 Compaq Computer Corporation * Copyright © 2002 Hewlett-Packard Company * Copyright © 2006 Intel Corporation * Copyright © 2008 Red Hat, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of the copyright holders not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no representations * about the suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. * * Author: Jim Gettys, Hewlett-Packard Company, Inc. * Keith Packard, Intel Corporation */ /* note that RANDR 1.0 is incompatible with version 0.0, or 0.1 */ /* V1.0 removes depth switching from the protocol */ #ifndef _XRANDRP_H_ #define _XRANDRP_H_ #include #include #define Window CARD32 #define Drawable CARD32 #define Font CARD32 #define Pixmap CARD32 #define Cursor CARD32 #define Colormap CARD32 #define GContext CARD32 #define Atom CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define RROutput CARD32 #define RRMode CARD32 #define RRCrtc CARD32 #define RRProvider CARD32 #define RRModeFlags CARD32 #define RRLease CARD32 #define Rotation CARD16 #define SizeID CARD16 #define SubpixelOrder CARD16 /* * data structures */ typedef struct { CARD16 widthInPixels; CARD16 heightInPixels; CARD16 widthInMillimeters; CARD16 heightInMillimeters; } xScreenSizes; #define sz_xScreenSizes 8 /* * requests and replies */ typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xRRQueryVersionReq; #define sz_xRRQueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRQueryVersionReply; #define sz_xRRQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; } xRRGetScreenInfoReq; #define sz_xRRGetScreenInfoReq 8 /* * the xRRScreenInfoReply structure is followed by: * * the size information */ typedef struct { BYTE type; /* X_Reply */ BYTE setOfRotations; CARD16 sequenceNumber; CARD32 length; Window root; Time timestamp; Time configTimestamp; CARD16 nSizes; SizeID sizeID; Rotation rotation; CARD16 rate; CARD16 nrateEnts; CARD16 pad; } xRRGetScreenInfoReply; #define sz_xRRGetScreenInfoReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Drawable drawable; Time timestamp; Time configTimestamp; SizeID sizeID; Rotation rotation; } xRR1_0SetScreenConfigReq; #define sz_xRR1_0SetScreenConfigReq 20 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Drawable drawable; Time timestamp; Time configTimestamp; SizeID sizeID; Rotation rotation; CARD16 rate; CARD16 pad; } xRRSetScreenConfigReq; #define sz_xRRSetScreenConfigReq 24 typedef struct { BYTE type; /* X_Reply */ CARD8 status; CARD16 sequenceNumber; CARD32 length; Time newTimestamp; Time newConfigTimestamp; Window root; CARD16 subpixelOrder; CARD16 pad4; CARD32 pad5; CARD32 pad6; } xRRSetScreenConfigReply; #define sz_xRRSetScreenConfigReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; CARD16 enable; CARD16 pad2; } xRRSelectInputReq; #define sz_xRRSelectInputReq 12 /* * Additions for version 1.2 */ typedef struct _xRRModeInfo { RRMode id; CARD16 width; CARD16 height; CARD32 dotClock; CARD16 hSyncStart; CARD16 hSyncEnd; CARD16 hTotal; CARD16 hSkew; CARD16 vSyncStart; CARD16 vSyncEnd; CARD16 vTotal; CARD16 nameLength; RRModeFlags modeFlags; } xRRModeInfo; #define sz_xRRModeInfo 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; } xRRGetScreenSizeRangeReq; #define sz_xRRGetScreenSizeRangeReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 pad; CARD16 sequenceNumber; CARD32 length; CARD16 minWidth; CARD16 minHeight; CARD16 maxWidth; CARD16 maxHeight; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xRRGetScreenSizeRangeReply; #define sz_xRRGetScreenSizeRangeReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; CARD16 width; CARD16 height; CARD32 widthInMillimeters; CARD32 heightInMillimeters; } xRRSetScreenSizeReq; #define sz_xRRSetScreenSizeReq 20 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; } xRRGetScreenResourcesReq; #define sz_xRRGetScreenResourcesReq 8 typedef struct { BYTE type; CARD8 pad; CARD16 sequenceNumber; CARD32 length; Time timestamp; Time configTimestamp; CARD16 nCrtcs; CARD16 nOutputs; CARD16 nModes; CARD16 nbytesNames; CARD32 pad1; CARD32 pad2; } xRRGetScreenResourcesReply; #define sz_xRRGetScreenResourcesReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; Time configTimestamp; } xRRGetOutputInfoReq; #define sz_xRRGetOutputInfoReq 12 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time timestamp; RRCrtc crtc; CARD32 mmWidth; CARD32 mmHeight; CARD8 connection; CARD8 subpixelOrder; CARD16 nCrtcs; CARD16 nModes; CARD16 nPreferred; CARD16 nClones; CARD16 nameLength; } xRRGetOutputInfoReply; #define sz_xRRGetOutputInfoReply 36 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; } xRRListOutputPropertiesReq; #define sz_xRRListOutputPropertiesReq 8 typedef struct { BYTE type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 nAtoms; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRRListOutputPropertiesReply; #define sz_xRRListOutputPropertiesReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; Atom property; } xRRQueryOutputPropertyReq; #define sz_xRRQueryOutputPropertyReq 12 typedef struct { BYTE type; BYTE pad0; CARD16 sequenceNumber; CARD32 length; BOOL pending; BOOL range; BOOL immutable; BYTE pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRRQueryOutputPropertyReply; #define sz_xRRQueryOutputPropertyReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; Atom property; BOOL pending; BOOL range; CARD16 pad; } xRRConfigureOutputPropertyReq; #define sz_xRRConfigureOutputPropertyReq 16 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; Atom property; Atom type; CARD8 format; CARD8 mode; CARD16 pad; CARD32 nUnits; } xRRChangeOutputPropertyReq; #define sz_xRRChangeOutputPropertyReq 24 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; Atom property; } xRRDeleteOutputPropertyReq; #define sz_xRRDeleteOutputPropertyReq 12 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; Atom property; Atom type; CARD32 longOffset; CARD32 longLength; #ifdef __cplusplus BOOL _delete; #else BOOL delete; #endif BOOL pending; CARD16 pad1; } xRRGetOutputPropertyReq; #define sz_xRRGetOutputPropertyReq 28 typedef struct { BYTE type; CARD8 format; CARD16 sequenceNumber; CARD32 length; Atom propertyType; CARD32 bytesAfter; CARD32 nItems; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xRRGetOutputPropertyReply; #define sz_xRRGetOutputPropertyReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; xRRModeInfo modeInfo; } xRRCreateModeReq; #define sz_xRRCreateModeReq 40 typedef struct { BYTE type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; RRMode mode; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRCreateModeReply; #define sz_xRRCreateModeReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRMode mode; } xRRDestroyModeReq; #define sz_xRRDestroyModeReq 8 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; RRMode mode; } xRRAddOutputModeReq; #define sz_xRRAddOutputModeReq 12 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RROutput output; RRMode mode; } xRRDeleteOutputModeReq; #define sz_xRRDeleteOutputModeReq 12 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; Time configTimestamp; } xRRGetCrtcInfoReq; #define sz_xRRGetCrtcInfoReq 12 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time timestamp; INT16 x; INT16 y; CARD16 width; CARD16 height; RRMode mode; Rotation rotation; Rotation rotations; CARD16 nOutput; CARD16 nPossibleOutput; } xRRGetCrtcInfoReply; #define sz_xRRGetCrtcInfoReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; Time timestamp; Time configTimestamp; INT16 x; INT16 y; RRMode mode; Rotation rotation; CARD16 pad; } xRRSetCrtcConfigReq; #define sz_xRRSetCrtcConfigReq 28 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time newTimestamp; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRSetCrtcConfigReply; #define sz_xRRSetCrtcConfigReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; } xRRGetCrtcGammaSizeReq; #define sz_xRRGetCrtcGammaSizeReq 8 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; CARD16 size; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRRGetCrtcGammaSizeReply; #define sz_xRRGetCrtcGammaSizeReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; } xRRGetCrtcGammaReq; #define sz_xRRGetCrtcGammaReq 8 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; CARD16 size; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRRGetCrtcGammaReply; #define sz_xRRGetCrtcGammaReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; CARD16 size; CARD16 pad1; } xRRSetCrtcGammaReq; #define sz_xRRSetCrtcGammaReq 12 /* * Additions for V1.3 */ typedef xRRGetScreenResourcesReq xRRGetScreenResourcesCurrentReq; #define sz_xRRGetScreenResourcesCurrentReq sz_xRRGetScreenResourcesReq typedef xRRGetScreenResourcesReply xRRGetScreenResourcesCurrentReply; #define sz_xRRGetScreenResourcesCurrentReply sz_xRRGetScreenResourcesReply typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; xRenderTransform transform; CARD16 nbytesFilter; /* number of bytes in filter name */ CARD16 pad; } xRRSetCrtcTransformReq; #define sz_xRRSetCrtcTransformReq 48 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; } xRRGetCrtcTransformReq; #define sz_xRRGetCrtcTransformReq 8 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; xRenderTransform pendingTransform; BYTE hasTransforms; CARD8 pad0; CARD16 pad1; xRenderTransform currentTransform; CARD32 pad2; CARD16 pendingNbytesFilter; /* number of bytes in filter name */ CARD16 pendingNparamsFilter; /* number of filter params */ CARD16 currentNbytesFilter; /* number of bytes in filter name */ CARD16 currentNparamsFilter; /* number of filter params */ } xRRGetCrtcTransformReply; #define sz_xRRGetCrtcTransformReply 96 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; RROutput output; } xRRSetOutputPrimaryReq; #define sz_xRRSetOutputPrimaryReq 12 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; } xRRGetOutputPrimaryReq; #define sz_xRRGetOutputPrimaryReq 8 typedef struct { BYTE type; CARD8 pad; CARD16 sequenceNumber; CARD32 length; RROutput output; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRGetOutputPrimaryReply; #define sz_xRRGetOutputPrimaryReply 32 /* * Additions for V1.4 */ typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; } xRRGetProvidersReq; #define sz_xRRGetProvidersReq 8 typedef struct { BYTE type; CARD8 pad; CARD16 sequenceNumber; CARD32 length; Time timestamp; CARD16 nProviders; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRGetProvidersReply; #define sz_xRRGetProvidersReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; Time configTimestamp; } xRRGetProviderInfoReq; #define sz_xRRGetProviderInfoReq 12 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time timestamp; CARD32 capabilities; CARD16 nCrtcs; CARD16 nOutputs; CARD16 nAssociatedProviders; CARD16 nameLength; CARD32 pad1; CARD32 pad2; } xRRGetProviderInfoReply; #define sz_xRRGetProviderInfoReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; RRProvider source_provider; Time configTimestamp; } xRRSetProviderOutputSourceReq; #define sz_xRRSetProviderOutputSourceReq 16 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; RRProvider sink_provider; Time configTimestamp; } xRRSetProviderOffloadSinkReq; #define sz_xRRSetProviderOffloadSinkReq 16 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; } xRRListProviderPropertiesReq; #define sz_xRRListProviderPropertiesReq 8 typedef struct { BYTE type; CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 nAtoms; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRRListProviderPropertiesReply; #define sz_xRRListProviderPropertiesReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; Atom property; } xRRQueryProviderPropertyReq; #define sz_xRRQueryProviderPropertyReq 12 typedef struct { BYTE type; BYTE pad0; CARD16 sequenceNumber; CARD32 length; BOOL pending; BOOL range; BOOL immutable; BYTE pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRRQueryProviderPropertyReply; #define sz_xRRQueryProviderPropertyReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; Atom property; BOOL pending; BOOL range; CARD16 pad; } xRRConfigureProviderPropertyReq; #define sz_xRRConfigureProviderPropertyReq 16 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; Atom property; Atom type; CARD8 format; CARD8 mode; CARD16 pad; CARD32 nUnits; } xRRChangeProviderPropertyReq; #define sz_xRRChangeProviderPropertyReq 24 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; Atom property; } xRRDeleteProviderPropertyReq; #define sz_xRRDeleteProviderPropertyReq 12 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRProvider provider; Atom property; Atom type; CARD32 longOffset; CARD32 longLength; #ifdef __cplusplus BOOL _delete; #else BOOL delete; #endif BOOL pending; CARD16 pad1; } xRRGetProviderPropertyReq; #define sz_xRRGetProviderPropertyReq 28 typedef struct { BYTE type; CARD8 format; CARD16 sequenceNumber; CARD32 length; Atom propertyType; CARD32 bytesAfter; CARD32 nItems; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xRRGetProviderPropertyReply; #define sz_xRRGetProviderPropertyReply 32 /* * Additions for V1.6 */ typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; RRLease lid; CARD16 nCrtcs; CARD16 nOutputs; } xRRCreateLeaseReq; #define sz_xRRCreateLeaseReq 16 typedef struct { BYTE type; CARD8 nfd; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xRRCreateLeaseReply; #define sz_xRRCreateLeaseReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRLease lid; BYTE terminate; CARD8 pad1; CARD16 pad2; } xRRFreeLeaseReq; #define sz_xRRFreeLeaseReq 12 /* * event */ typedef struct { CARD8 type; /* always evBase + ScreenChangeNotify */ CARD8 rotation; /* new rotation */ CARD16 sequenceNumber; Time timestamp; /* time screen was changed */ Time configTimestamp; /* time config data was changed */ Window root; /* root window */ Window window; /* window requesting notification */ SizeID sizeID; /* new size ID */ CARD16 subpixelOrder; /* subpixel order */ CARD16 widthInPixels; /* new size */ CARD16 heightInPixels; CARD16 widthInMillimeters; CARD16 heightInMillimeters; } xRRScreenChangeNotifyEvent; #define sz_xRRScreenChangeNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_CrtcChange */ CARD16 sequenceNumber; Time timestamp; /* time crtc was changed */ Window window; /* window requesting notification */ RRCrtc crtc; /* affected CRTC */ RRMode mode; /* current mode */ CARD16 rotation; /* rotation and reflection */ CARD16 pad1; /* unused */ INT16 x; /* new location */ INT16 y; CARD16 width; /* new size */ CARD16 height; } xRRCrtcChangeNotifyEvent; #define sz_xRRCrtcChangeNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_OutputChange */ CARD16 sequenceNumber; Time timestamp; /* time output was changed */ Time configTimestamp; /* time config was changed */ Window window; /* window requesting notification */ RROutput output; /* affected output */ RRCrtc crtc; /* current crtc */ RRMode mode; /* current mode */ CARD16 rotation; /* rotation and reflection */ CARD8 connection; /* connection status */ CARD8 subpixelOrder; /* subpixel order */ } xRROutputChangeNotifyEvent; #define sz_xRROutputChangeNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_OutputProperty */ CARD16 sequenceNumber; Window window; /* window requesting notification */ RROutput output; /* affected output */ Atom atom; /* property name */ Time timestamp; /* time crtc was changed */ CARD8 state; /* NewValue or Deleted */ CARD8 pad1; CARD16 pad2; CARD32 pad3; CARD32 pad4; } xRROutputPropertyNotifyEvent; #define sz_xRROutputPropertyNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_ProviderChange */ CARD16 sequenceNumber; Time timestamp; /* time provider was changed */ Window window; /* window requesting notification */ RRProvider provider; /* affected provider */ CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xRRProviderChangeNotifyEvent; #define sz_xRRProviderChangeNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_ProviderProperty */ CARD16 sequenceNumber; Window window; /* window requesting notification */ RRProvider provider; /* affected provider */ Atom atom; /* property name */ Time timestamp; /* time provider was changed */ CARD8 state; /* NewValue or Deleted */ CARD8 pad1; CARD16 pad2; CARD32 pad3; CARD32 pad4; } xRRProviderPropertyNotifyEvent; #define sz_xRRProviderPropertyNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_ResourceChange */ CARD16 sequenceNumber; Time timestamp; /* time resource was changed */ Window window; /* window requesting notification */ CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRResourceChangeNotifyEvent; #define sz_xRRResourceChangeNotifyEvent 32 typedef struct { CARD8 type; /* always evBase + RRNotify */ CARD8 subCode; /* RRNotify_Lease */ CARD16 sequenceNumber; Time timestamp; /* time resource was changed */ Window window; /* window requesting notification */ RRLease lease; CARD8 created; /* created/deleted */ CARD8 pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xRRLeaseNotifyEvent; #define sz_xRRLeaseNotifyEvent 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; } xRRGetPanningReq; #define sz_xRRGetPanningReq 8 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time timestamp; CARD16 left; CARD16 top; CARD16 width; CARD16 height; CARD16 track_left; CARD16 track_top; CARD16 track_width; CARD16 track_height; INT16 border_left; INT16 border_top; INT16 border_right; INT16 border_bottom; } xRRGetPanningReply; #define sz_xRRGetPanningReply 36 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; RRCrtc crtc; Time timestamp; CARD16 left; CARD16 top; CARD16 width; CARD16 height; CARD16 track_left; CARD16 track_top; CARD16 track_width; CARD16 track_height; INT16 border_left; INT16 border_top; INT16 border_right; INT16 border_bottom; } xRRSetPanningReq; #define sz_xRRSetPanningReq 36 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time newTimestamp; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRRSetPanningReply; #define sz_xRRSetPanningReply 32 typedef struct { Atom name; BOOL primary; BOOL automatic; CARD16 noutput; INT16 x; INT16 y; CARD16 width; CARD16 height; CARD32 widthInMillimeters; CARD32 heightInMillimeters; } xRRMonitorInfo; #define sz_xRRMonitorInfo 24 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; BOOL get_active; CARD8 pad; CARD16 pad2; } xRRGetMonitorsReq; #define sz_xRRGetMonitorsReq 12 typedef struct { BYTE type; CARD8 status; CARD16 sequenceNumber; CARD32 length; Time timestamp; CARD32 nmonitors; CARD32 noutputs; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xRRGetMonitorsReply; #define sz_xRRGetMonitorsReply 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; xRRMonitorInfo monitor; } xRRSetMonitorReq; #define sz_xRRSetMonitorReq 32 typedef struct { CARD8 reqType; CARD8 randrReqType; CARD16 length; Window window; Atom name; } xRRDeleteMonitorReq; #define sz_xRRDeleteMonitorReq 12 #undef RRLease #undef RRModeFlags #undef RRCrtc #undef RRMode #undef RROutput #undef RRMode #undef RRCrtc #undef RRProvider #undef Drawable #undef Window #undef Font #undef Pixmap #undef Cursor #undef Colormap #undef GContext #undef Atom #undef Time #undef KeyCode #undef KeySym #undef Rotation #undef SizeID #undef SubpixelOrder #endif /* _XRANDRP_H_ */ X11/extensions/ag.h000064400000003251151027430550010057 0ustar00/* Copyright 1996, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _AG_H_ #define _AG_H_ #define XAGNAME "XC-APPGROUP" #define XAG_MAJOR_VERSION 1 /* current version numbers */ #define XAG_MINOR_VERSION 0 #define XagWindowTypeX11 0 #define XagWindowTypeMacintosh 1 #define XagWindowTypeWin32 2 #define XagWindowTypeWin16 3 #define XagBadAppGroup 0 #define XagNumberErrors (XagBadAppGroup + 1) #define XagNsingleScreen 7 #define XagNdefaultRoot 1 #define XagNrootVisual 2 #define XagNdefaultColormap 3 #define XagNblackPixel 4 #define XagNwhitePixel 5 #define XagNappGroupLeader 6 #endif /* _AG_H_ */ X11/extensions/agproto.h000064400000011615151027430550011146 0ustar00/* Copyright 1996, 1998, 2001 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _AGPROTO_H_ /* { */ #define _AGPROTO_H_ #include #define X_XagQueryVersion 0 #define X_XagCreate 1 #define X_XagDestroy 2 #define X_XagGetAttr 3 #define X_XagQuery 4 #define X_XagCreateAssoc 5 #define X_XagDestroyAssoc 6 #define XAppGroup CARD32 /* * Redefine some basic types used by structures defined herein. This allows * both the library and server to view communicated data as 32-bit entities, * thus preventing problems on 64-bit architectures where libXext sees this * data as 64 bits and the server sees it as 32 bits. */ #define Colormap CARD32 #define VisualID CARD32 #define Window CARD32 typedef struct _XagQueryVersion { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagQueryVersion */ CARD16 length; CARD16 client_major_version; CARD16 client_minor_version; } xXagQueryVersionReq; #define sz_xXagQueryVersionReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequence_number; CARD32 length; CARD16 server_major_version; CARD16 server_minor_version; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXagQueryVersionReply; #define sz_xXagQueryVersionReply 32 /* Set AppGroup Attributes masks */ #define XagSingleScreenMask 1 << 0 #define XagDefaultRootMask 1 << XagNdefaultRoot #define XagRootVisualMask 1 << XagNrootVisual #define XagDefaultColormapMask 1 << XagNdefaultColormap #define XagBlackPixelMask 1 << XagNblackPixel #define XagWhitePixelMask 1 << XagNwhitePixel #define XagAppGroupLeaderMask 1 << XagNappGroupLeader typedef struct _XagCreate { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagCreate */ CARD16 length; XAppGroup app_group; CARD32 attrib_mask; /* LISTofVALUE follows */ } xXagCreateReq; #define sz_xXagCreateReq 12 typedef struct _XagDestroy { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagDestroy */ CARD16 length; XAppGroup app_group; } xXagDestroyReq; #define sz_xXagDestroyReq 8 typedef struct _XagGetAttr { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagGetAttr */ CARD16 length; XAppGroup app_group; } xXagGetAttrReq; #define sz_xXagGetAttrReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequence_number; CARD32 length; Window default_root; VisualID root_visual; Colormap default_colormap; CARD32 black_pixel; CARD32 white_pixel; BOOL single_screen; BOOL app_group_leader; CARD16 pad2; } xXagGetAttrReply; #define sz_xXagGetAttrReply 32 typedef struct _XagQuery { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagQuery */ CARD16 length; CARD32 resource; } xXagQueryReq; #define sz_xXagQueryReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequence_number; CARD32 length; XAppGroup app_group; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXagQueryReply; #define sz_xXagQueryReply 32 typedef struct _XagCreateAssoc { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagCreateAssoc */ CARD16 length; Window window; CARD16 window_type; CARD16 system_window_len; /* LISTofCARD8 follows */ } xXagCreateAssocReq; #define sz_xXagCreateAssocReq 12 typedef struct _XagDestroyAssoc { CARD8 reqType; /* always XagReqCode */ CARD8 xagReqType; /* always X_XagDestroyAssoc */ CARD16 length; Window window; } xXagDestroyAssocReq; #define sz_xXagDestroyAssocReq 8 #undef XAppGroup /* * Cancel the previous redefinition of the basic types, thus restoring their * X.h definitions. */ #undef Window #undef Colormap #undef VisualID #endif /* } _AGPROTO_H_ */ X11/extensions/XKB.h000064400000067063151027430550010127 0ustar00/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XKB_H_ #define _XKB_H_ /* * XKB request codes, used in: * - xkbReqType field of all requests * - requestMinor field of some events */ #define X_kbUseExtension 0 #define X_kbSelectEvents 1 #define X_kbBell 3 #define X_kbGetState 4 #define X_kbLatchLockState 5 #define X_kbGetControls 6 #define X_kbSetControls 7 #define X_kbGetMap 8 #define X_kbSetMap 9 #define X_kbGetCompatMap 10 #define X_kbSetCompatMap 11 #define X_kbGetIndicatorState 12 #define X_kbGetIndicatorMap 13 #define X_kbSetIndicatorMap 14 #define X_kbGetNamedIndicator 15 #define X_kbSetNamedIndicator 16 #define X_kbGetNames 17 #define X_kbSetNames 18 #define X_kbGetGeometry 19 #define X_kbSetGeometry 20 #define X_kbPerClientFlags 21 #define X_kbListComponents 22 #define X_kbGetKbdByName 23 #define X_kbGetDeviceInfo 24 #define X_kbSetDeviceInfo 25 #define X_kbSetDebuggingFlags 101 /* * In the X sense, XKB reports only one event. * The type field of all XKB events is XkbEventCode */ #define XkbEventCode 0 #define XkbNumberEvents (XkbEventCode+1) /* * XKB has a minor event code so it can use one X event code for * multiple purposes. * - reported in the xkbType field of all XKB events. * - XkbSelectEventDetails: Indicates the event for which event details * are being changed */ #define XkbNewKeyboardNotify 0 #define XkbMapNotify 1 #define XkbStateNotify 2 #define XkbControlsNotify 3 #define XkbIndicatorStateNotify 4 #define XkbIndicatorMapNotify 5 #define XkbNamesNotify 6 #define XkbCompatMapNotify 7 #define XkbBellNotify 8 #define XkbActionMessage 9 #define XkbAccessXNotify 10 #define XkbExtensionDeviceNotify 11 /* * Event Mask: * - XkbSelectEvents: Specifies event interest. */ #define XkbNewKeyboardNotifyMask (1L << 0) #define XkbMapNotifyMask (1L << 1) #define XkbStateNotifyMask (1L << 2) #define XkbControlsNotifyMask (1L << 3) #define XkbIndicatorStateNotifyMask (1L << 4) #define XkbIndicatorMapNotifyMask (1L << 5) #define XkbNamesNotifyMask (1L << 6) #define XkbCompatMapNotifyMask (1L << 7) #define XkbBellNotifyMask (1L << 8) #define XkbActionMessageMask (1L << 9) #define XkbAccessXNotifyMask (1L << 10) #define XkbExtensionDeviceNotifyMask (1L << 11) #define XkbAllEventsMask (0xFFF) /* * NewKeyboardNotify event details: */ #define XkbNKN_KeycodesMask (1L << 0) #define XkbNKN_GeometryMask (1L << 1) #define XkbNKN_DeviceIDMask (1L << 2) #define XkbAllNewKeyboardEventsMask (0x7) /* * AccessXNotify event types: * - The 'what' field of AccessXNotify events reports the * reason that the event was generated. */ #define XkbAXN_SKPress 0 #define XkbAXN_SKAccept 1 #define XkbAXN_SKReject 2 #define XkbAXN_SKRelease 3 #define XkbAXN_BKAccept 4 #define XkbAXN_BKReject 5 #define XkbAXN_AXKWarning 6 /* * AccessXNotify details: * - Used as an event detail mask to limit the conditions under which * AccessXNotify events are reported */ #define XkbAXN_SKPressMask (1L << 0) #define XkbAXN_SKAcceptMask (1L << 1) #define XkbAXN_SKRejectMask (1L << 2) #define XkbAXN_SKReleaseMask (1L << 3) #define XkbAXN_BKAcceptMask (1L << 4) #define XkbAXN_BKRejectMask (1L << 5) #define XkbAXN_AXKWarningMask (1L << 6) #define XkbAllAccessXEventsMask (0x7f) /* * Miscellaneous event details: * - event detail masks for assorted events that don't reall * have any details. */ #define XkbAllStateEventsMask XkbAllStateComponentsMask #define XkbAllMapEventsMask XkbAllMapComponentsMask #define XkbAllControlEventsMask XkbAllControlsMask #define XkbAllIndicatorEventsMask XkbAllIndicatorsMask #define XkbAllNameEventsMask XkbAllNamesMask #define XkbAllCompatMapEventsMask XkbAllCompatMask #define XkbAllBellEventsMask (1L << 0) #define XkbAllActionMessagesMask (1L << 0) /* * XKB reports one error: BadKeyboard * A further reason for the error is encoded into to most significant * byte of the resourceID for the error: * XkbErr_BadDevice - the device in question was not found * XkbErr_BadClass - the device was found but it doesn't belong to * the appropriate class. * XkbErr_BadId - the device was found and belongs to the right * class, but not feedback with a matching id was * found. * The low byte of the resourceID for this error contains the device * id, class specifier or feedback id that failed. */ #define XkbKeyboard 0 #define XkbNumberErrors 1 #define XkbErr_BadDevice 0xff #define XkbErr_BadClass 0xfe #define XkbErr_BadId 0xfd /* * Keyboard Components Mask: * - Specifies the components that follow a GetKeyboardByNameReply */ #define XkbClientMapMask (1L << 0) #define XkbServerMapMask (1L << 1) #define XkbCompatMapMask (1L << 2) #define XkbIndicatorMapMask (1L << 3) #define XkbNamesMask (1L << 4) #define XkbGeometryMask (1L << 5) #define XkbControlsMask (1L << 6) #define XkbAllComponentsMask (0x7f) /* * State detail mask: * - The 'changed' field of StateNotify events reports which of * the keyboard state components have changed. * - Used as an event detail mask to limit the conditions under * which StateNotify events are reported. */ #define XkbModifierStateMask (1L << 0) #define XkbModifierBaseMask (1L << 1) #define XkbModifierLatchMask (1L << 2) #define XkbModifierLockMask (1L << 3) #define XkbGroupStateMask (1L << 4) #define XkbGroupBaseMask (1L << 5) #define XkbGroupLatchMask (1L << 6) #define XkbGroupLockMask (1L << 7) #define XkbCompatStateMask (1L << 8) #define XkbGrabModsMask (1L << 9) #define XkbCompatGrabModsMask (1L << 10) #define XkbLookupModsMask (1L << 11) #define XkbCompatLookupModsMask (1L << 12) #define XkbPointerButtonMask (1L << 13) #define XkbAllStateComponentsMask (0x3fff) /* * Controls detail masks: * The controls specified in XkbAllControlsMask: * - The 'changed' field of ControlsNotify events reports which of * the keyboard controls have changed. * - The 'changeControls' field of the SetControls request specifies * the controls for which values are to be changed. * - Used as an event detail mask to limit the conditions under * which ControlsNotify events are reported. * * The controls specified in the XkbAllBooleanCtrlsMask: * - The 'enabledControls' field of ControlsNotify events reports the * current status of the boolean controls. * - The 'enabledControlsChanges' field of ControlsNotify events reports * any boolean controls that have been turned on or off. * - The 'affectEnabledControls' and 'enabledControls' fields of the * kbSetControls request change the set of enabled controls. * - The 'accessXTimeoutMask' and 'accessXTimeoutValues' fields of * an XkbControlsRec specify the controls to be changed if the keyboard * times out and the values to which they should be changed. * - The 'autoCtrls' and 'autoCtrlsValues' fields of the PerClientFlags * request specifies the specify the controls to be reset when the * client exits and the values to which they should be reset. * - The 'ctrls' field of an indicator map specifies the controls * that drive the indicator. * - Specifies the boolean controls affected by the SetControls and * LockControls key actions. */ #define XkbRepeatKeysMask (1L << 0) #define XkbSlowKeysMask (1L << 1) #define XkbBounceKeysMask (1L << 2) #define XkbStickyKeysMask (1L << 3) #define XkbMouseKeysMask (1L << 4) #define XkbMouseKeysAccelMask (1L << 5) #define XkbAccessXKeysMask (1L << 6) #define XkbAccessXTimeoutMask (1L << 7) #define XkbAccessXFeedbackMask (1L << 8) #define XkbAudibleBellMask (1L << 9) #define XkbOverlay1Mask (1L << 10) #define XkbOverlay2Mask (1L << 11) #define XkbIgnoreGroupLockMask (1L << 12) #define XkbGroupsWrapMask (1L << 27) #define XkbInternalModsMask (1L << 28) #define XkbIgnoreLockModsMask (1L << 29) #define XkbPerKeyRepeatMask (1L << 30) #define XkbControlsEnabledMask (1L << 31) #define XkbAccessXOptionsMask (XkbStickyKeysMask|XkbAccessXFeedbackMask) #define XkbAllBooleanCtrlsMask (0x00001FFF) #define XkbAllControlsMask (0xF8001FFF) #define XkbAllControlEventsMask XkbAllControlsMask /* * AccessX Options Mask * - The 'accessXOptions' field of an XkbControlsRec specifies the * AccessX options that are currently in effect. * - The 'accessXTimeoutOptionsMask' and 'accessXTimeoutOptionsValues' * fields of an XkbControlsRec specify the Access X options to be * changed if the keyboard times out and the values to which they * should be changed. */ #define XkbAX_SKPressFBMask (1L << 0) #define XkbAX_SKAcceptFBMask (1L << 1) #define XkbAX_FeatureFBMask (1L << 2) #define XkbAX_SlowWarnFBMask (1L << 3) #define XkbAX_IndicatorFBMask (1L << 4) #define XkbAX_StickyKeysFBMask (1L << 5) #define XkbAX_TwoKeysMask (1L << 6) #define XkbAX_LatchToLockMask (1L << 7) #define XkbAX_SKReleaseFBMask (1L << 8) #define XkbAX_SKRejectFBMask (1L << 9) #define XkbAX_BKRejectFBMask (1L << 10) #define XkbAX_DumbBellFBMask (1L << 11) #define XkbAX_FBOptionsMask (0xF3F) #define XkbAX_SKOptionsMask (0x0C0) #define XkbAX_AllOptionsMask (0xFFF) /* * XkbUseCoreKbd is used to specify the core keyboard without having * to look up its X input extension identifier. * XkbUseCorePtr is used to specify the core pointer without having * to look up its X input extension identifier. * XkbDfltXIClass is used to specify "don't care" any place that the * XKB protocol is looking for an X Input Extension * device class. * XkbDfltXIId is used to specify "don't care" any place that the * XKB protocol is looking for an X Input Extension * feedback identifier. * XkbAllXIClasses is used to get information about all device indicators, * whether they're part of the indicator feedback class * or the keyboard feedback class. * XkbAllXIIds is used to get information about all device indicator * feedbacks without having to list them. * XkbXINone is used to indicate that no class or id has been specified. * XkbLegalXILedClass(c) True if 'c' specifies a legal class with LEDs * XkbLegalXIBellClass(c) True if 'c' specifies a legal class with bells * XkbExplicitXIDevice(d) True if 'd' explicitly specifies a device * XkbExplicitXIClass(c) True if 'c' explicitly specifies a device class * XkbExplicitXIId(c) True if 'i' explicitly specifies a device id * XkbSingleXIClass(c) True if 'c' specifies exactly one device class, * including the default. * XkbSingleXIId(i) True if 'i' specifies exactly one device * identifier, including the default. */ #define XkbUseCoreKbd 0x0100 #define XkbUseCorePtr 0x0200 #define XkbDfltXIClass 0x0300 #define XkbDfltXIId 0x0400 #define XkbAllXIClasses 0x0500 #define XkbAllXIIds 0x0600 #define XkbXINone 0xff00 #define XkbLegalXILedClass(c) (((c)==KbdFeedbackClass)||\ ((c)==LedFeedbackClass)||\ ((c)==XkbDfltXIClass)||\ ((c)==XkbAllXIClasses)) #define XkbLegalXIBellClass(c) (((c)==KbdFeedbackClass)||\ ((c)==BellFeedbackClass)||\ ((c)==XkbDfltXIClass)||\ ((c)==XkbAllXIClasses)) #define XkbExplicitXIDevice(c) (((c)&(~0xff))==0) #define XkbExplicitXIClass(c) (((c)&(~0xff))==0) #define XkbExplicitXIId(c) (((c)&(~0xff))==0) #define XkbSingleXIClass(c) ((((c)&(~0xff))==0)||((c)==XkbDfltXIClass)) #define XkbSingleXIId(c) ((((c)&(~0xff))==0)||((c)==XkbDfltXIId)) #define XkbNoModifier 0xff #define XkbNoShiftLevel 0xff #define XkbNoShape 0xff #define XkbNoIndicator 0xff #define XkbNoModifierMask 0 #define XkbAllModifiersMask 0xff #define XkbAllVirtualModsMask 0xffff #define XkbNumKbdGroups 4 #define XkbMaxKbdGroup (XkbNumKbdGroups-1) #define XkbMaxMouseKeysBtn 4 /* * Group Index and Mask: * - Indices into the kt_index array of a key type. * - Mask specifies types to be changed for XkbChangeTypesOfKey */ #define XkbGroup1Index 0 #define XkbGroup2Index 1 #define XkbGroup3Index 2 #define XkbGroup4Index 3 #define XkbAnyGroup 254 #define XkbAllGroups 255 #define XkbGroup1Mask (1<<0) #define XkbGroup2Mask (1<<1) #define XkbGroup3Mask (1<<2) #define XkbGroup4Mask (1<<3) #define XkbAnyGroupMask (1<<7) #define XkbAllGroupsMask (0xf) /* * BuildCoreState: Given a keyboard group and a modifier state, * construct the value to be reported an event. * GroupForCoreState: Given the state reported in an event, * determine the keyboard group. * IsLegalGroup: Returns TRUE if 'g' is a valid group index. */ #define XkbBuildCoreState(m,g) ((((g)&0x3)<<13)|((m)&0xff)) #define XkbGroupForCoreState(s) (((s)>>13)&0x3) #define XkbIsLegalGroup(g) (((g)>=0)&&((g)type>=Xkb_SASetMods)&&((a)->type<=XkbSA_LockMods)) #define XkbIsGroupAction(a) (((a)->type>=XkbSA_SetGroup)&&((a)->type<=XkbSA_LockGroup)) #define XkbIsPtrAction(a) (((a)->type>=XkbSA_MovePtr)&&((a)->type<=XkbSA_SetPtrDflt)) /* * Key Behavior Qualifier: * KB_Permanent indicates that the behavior describes an unalterable * characteristic of the keyboard, not an XKB software-simulation of * the listed behavior. * Key Behavior Types: * Specifies the behavior of the underlying key. */ #define XkbKB_Permanent 0x80 #define XkbKB_OpMask 0x7f #define XkbKB_Default 0x00 #define XkbKB_Lock 0x01 #define XkbKB_RadioGroup 0x02 #define XkbKB_Overlay1 0x03 #define XkbKB_Overlay2 0x04 #define XkbKB_RGAllowNone 0x80 /* * Various macros which describe the range of legal keycodes. */ #define XkbMinLegalKeyCode 8 #define XkbMaxLegalKeyCode 255 #define XkbMaxKeyCount (XkbMaxLegalKeyCode-XkbMinLegalKeyCode+1) #define XkbPerKeyBitArraySize ((XkbMaxLegalKeyCode+1)/8) /* Seems kinda silly to check that an unsigned char is <= 255... */ #define XkbIsLegalKeycode(k) ((k)>=XkbMinLegalKeyCode) /* * Assorted constants and limits. */ #define XkbNumModifiers 8 #define XkbNumVirtualMods 16 #define XkbNumIndicators 32 #define XkbAllIndicatorsMask (0xffffffff) #define XkbMaxRadioGroups 32 #define XkbAllRadioGroupsMask (0xffffffff) #define XkbMaxShiftLevel 63 #define XkbMaxSymsPerKey (XkbMaxShiftLevel*XkbNumKbdGroups) #define XkbRGMaxMembers 12 #define XkbActionMessageLength 6 #define XkbKeyNameLength 4 #define XkbMaxRedirectCount 8 #define XkbGeomPtsPerMM 10 #define XkbGeomMaxColors 32 #define XkbGeomMaxLabelColors 3 #define XkbGeomMaxPriority 255 /* * Key Type index and mask for the four standard key types. */ #define XkbOneLevelIndex 0 #define XkbTwoLevelIndex 1 #define XkbAlphabeticIndex 2 #define XkbKeypadIndex 3 #define XkbLastRequiredType XkbKeypadIndex #define XkbNumRequiredTypes (XkbLastRequiredType+1) #define XkbMaxKeyTypes 255 #define XkbOneLevelMask (1<<0) #define XkbTwoLevelMask (1<<1) #define XkbAlphabeticMask (1<<2) #define XkbKeypadMask (1<<3) #define XkbAllRequiredTypes (0xf) #define XkbShiftLevel(n) ((n)-1) #define XkbShiftLevelMask(n) (1<<((n)-1)) /* * Extension name and version information */ #define XkbName "XKEYBOARD" #define XkbMajorVersion 1 #define XkbMinorVersion 0 /* * Explicit map components: * - Used in the 'explicit' field of an XkbServerMap. Specifies * the keyboard components that should _not_ be updated automatically * in response to core protocol keyboard mapping requests. */ #define XkbExplicitKeyTypesMask (0x0f) #define XkbExplicitKeyType1Mask (1<<0) #define XkbExplicitKeyType2Mask (1<<1) #define XkbExplicitKeyType3Mask (1<<2) #define XkbExplicitKeyType4Mask (1<<3) #define XkbExplicitInterpretMask (1<<4) #define XkbExplicitAutoRepeatMask (1<<5) #define XkbExplicitBehaviorMask (1<<6) #define XkbExplicitVModMapMask (1<<7) #define XkbAllExplicitMask (0xff) /* * Map components masks: * Those in AllMapComponentsMask: * - Specifies the individual fields to be loaded or changed for the * GetMap and SetMap requests. * Those in ClientInfoMask: * - Specifies the components to be allocated by XkbAllocClientMap. * Those in ServerInfoMask: * - Specifies the components to be allocated by XkbAllocServerMap. */ #define XkbKeyTypesMask (1<<0) #define XkbKeySymsMask (1<<1) #define XkbModifierMapMask (1<<2) #define XkbExplicitComponentsMask (1<<3) #define XkbKeyActionsMask (1<<4) #define XkbKeyBehaviorsMask (1<<5) #define XkbVirtualModsMask (1<<6) #define XkbVirtualModMapMask (1<<7) #define XkbAllClientInfoMask (XkbKeyTypesMask|XkbKeySymsMask|XkbModifierMapMask) #define XkbAllServerInfoMask (XkbExplicitComponentsMask|XkbKeyActionsMask|XkbKeyBehaviorsMask|XkbVirtualModsMask|XkbVirtualModMapMask) #define XkbAllMapComponentsMask (XkbAllClientInfoMask|XkbAllServerInfoMask) /* * Symbol interpretations flags: * - Used in the flags field of a symbol interpretation */ #define XkbSI_AutoRepeat (1<<0) #define XkbSI_LockingKey (1<<1) /* * Symbol interpretations match specification: * - Used in the match field of a symbol interpretation to specify * the conditions under which an interpretation is used. */ #define XkbSI_LevelOneOnly (0x80) #define XkbSI_OpMask (0x7f) #define XkbSI_NoneOf (0) #define XkbSI_AnyOfOrNone (1) #define XkbSI_AnyOf (2) #define XkbSI_AllOf (3) #define XkbSI_Exactly (4) /* * Indicator map flags: * - Used in the flags field of an indicator map to indicate the * conditions under which and indicator can be changed and the * effects of changing the indicator. */ #define XkbIM_NoExplicit (1L << 7) #define XkbIM_NoAutomatic (1L << 6) #define XkbIM_LEDDrivesKB (1L << 5) /* * Indicator map component specifications: * - Used by the 'which_groups' and 'which_mods' fields of an indicator * map to specify which keyboard components should be used to drive * the indicator. */ #define XkbIM_UseBase (1L << 0) #define XkbIM_UseLatched (1L << 1) #define XkbIM_UseLocked (1L << 2) #define XkbIM_UseEffective (1L << 3) #define XkbIM_UseCompat (1L << 4) #define XkbIM_UseNone 0 #define XkbIM_UseAnyGroup (XkbIM_UseBase|XkbIM_UseLatched|XkbIM_UseLocked\ |XkbIM_UseEffective) #define XkbIM_UseAnyMods (XkbIM_UseAnyGroup|XkbIM_UseCompat) /* * Compatibility Map Components: * - Specifies the components to be allocated in XkbAllocCompatMap. */ #define XkbSymInterpMask (1<<0) #define XkbGroupCompatMask (1<<1) #define XkbAllCompatMask (0x3) /* * Names component mask: * - Specifies the names to be loaded or changed for the GetNames and * SetNames requests. * - Specifies the names that have changed in a NamesNotify event. * - Specifies the names components to be allocated by XkbAllocNames. */ #define XkbKeycodesNameMask (1<<0) #define XkbGeometryNameMask (1<<1) #define XkbSymbolsNameMask (1<<2) #define XkbPhysSymbolsNameMask (1<<3) #define XkbTypesNameMask (1<<4) #define XkbCompatNameMask (1<<5) #define XkbKeyTypeNamesMask (1<<6) #define XkbKTLevelNamesMask (1<<7) #define XkbIndicatorNamesMask (1<<8) #define XkbKeyNamesMask (1<<9) #define XkbKeyAliasesMask (1<<10) #define XkbVirtualModNamesMask (1<<11) #define XkbGroupNamesMask (1<<12) #define XkbRGNamesMask (1<<13) #define XkbComponentNamesMask (0x3f) #define XkbAllNamesMask (0x3fff) /* * GetByName components: * - Specifies desired or necessary components to GetKbdByName request. * - Reports the components that were found in a GetKbdByNameReply */ #define XkbGBN_TypesMask (1L << 0) #define XkbGBN_CompatMapMask (1L << 1) #define XkbGBN_ClientSymbolsMask (1L << 2) #define XkbGBN_ServerSymbolsMask (1L << 3) #define XkbGBN_SymbolsMask (XkbGBN_ClientSymbolsMask|XkbGBN_ServerSymbolsMask) #define XkbGBN_IndicatorMapMask (1L << 4) #define XkbGBN_KeyNamesMask (1L << 5) #define XkbGBN_GeometryMask (1L << 6) #define XkbGBN_OtherNamesMask (1L << 7) #define XkbGBN_AllComponentsMask (0xff) /* * ListComponents flags */ #define XkbLC_Hidden (1L << 0) #define XkbLC_Default (1L << 1) #define XkbLC_Partial (1L << 2) #define XkbLC_AlphanumericKeys (1L << 8) #define XkbLC_ModifierKeys (1L << 9) #define XkbLC_KeypadKeys (1L << 10) #define XkbLC_FunctionKeys (1L << 11) #define XkbLC_AlternateGroup (1L << 12) /* * X Input Extension Interactions * - Specifies the possible interactions between XKB and the X input * extension * - Used to request (XkbGetDeviceInfo) or change (XKbSetDeviceInfo) * XKB information about an extension device. * - Reports the list of supported optional features in the reply to * XkbGetDeviceInfo or in an XkbExtensionDeviceNotify event. * XkbXI_UnsupportedFeature is reported in XkbExtensionDeviceNotify * events to indicate an attempt to use an unsupported feature. */ #define XkbXI_KeyboardsMask (1L << 0) #define XkbXI_ButtonActionsMask (1L << 1) #define XkbXI_IndicatorNamesMask (1L << 2) #define XkbXI_IndicatorMapsMask (1L << 3) #define XkbXI_IndicatorStateMask (1L << 4) #define XkbXI_UnsupportedFeatureMask (1L << 15) #define XkbXI_AllFeaturesMask (0x001f) #define XkbXI_AllDeviceFeaturesMask (0x001e) #define XkbXI_IndicatorsMask (0x001c) #define XkbAllExtensionDeviceEventsMask (0x801f) /* * Per-Client Flags: * - Specifies flags to be changed by the PerClientFlags request. */ #define XkbPCF_DetectableAutoRepeatMask (1L << 0) #define XkbPCF_GrabsUseXKBStateMask (1L << 1) #define XkbPCF_AutoResetControlsMask (1L << 2) #define XkbPCF_LookupStateWhenGrabbed (1L << 3) #define XkbPCF_SendEventUsesXKBState (1L << 4) #define XkbPCF_AllFlagsMask (0x1F) /* * Debugging flags and controls */ #define XkbDF_DisableLocks (1<<0) #endif /* _XKB_H_ */ X11/extensions/syncstr.h000064400000012746151027430550011206 0ustar00/* Copyright 1991, 1993, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /*********************************************************** Copyright 1991,1993 by Digital Equipment Corporation, Maynard, Massachusetts, and Olivetti Research Limited, Cambridge, England. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Digital or Olivetti not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL AND OLIVETTI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THEY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef _SYNCSTR_H_ #define _SYNCSTR_H_ #include #ifdef _SYNC_SERVER #define CARD64 XSyncValue /* XXX temporary! need real 64 bit values for Alpha */ typedef struct _SyncCounter { ClientPtr client; /* Owning client. 0 for system counters */ XSyncCounter id; /* resource ID */ CARD64 value; /* counter value */ struct _SyncTriggerList *pTriglist; /* list of triggers */ Bool beingDestroyed; /* in process of going away */ struct _SysCounterInfo *pSysCounterInfo; /* NULL if not a system counter */ } SyncCounter; /* * The System Counter interface */ typedef enum { XSyncCounterNeverChanges, XSyncCounterNeverIncreases, XSyncCounterNeverDecreases, XSyncCounterUnrestricted } SyncCounterType; typedef struct _SysCounterInfo { char *name; CARD64 resolution; CARD64 bracket_greater; CARD64 bracket_less; SyncCounterType counterType; /* how can this counter change */ void (*QueryValue)( pointer /*pCounter*/, CARD64 * /*freshvalue*/ ); void (*BracketValues)( pointer /*pCounter*/, CARD64 * /*lessthan*/, CARD64 * /*greaterthan*/ ); } SysCounterInfo; typedef struct _SyncTrigger { SyncCounter *pCounter; CARD64 wait_value; /* wait value */ unsigned int value_type; /* Absolute or Relative */ unsigned int test_type; /* transition or Comparision type */ CARD64 test_value; /* trigger event threshold value */ Bool (*CheckTrigger)( struct _SyncTrigger * /*pTrigger*/, CARD64 /*newval*/ ); void (*TriggerFired)( struct _SyncTrigger * /*pTrigger*/ ); void (*CounterDestroyed)( struct _SyncTrigger * /*pTrigger*/ ); } SyncTrigger; typedef struct _SyncTriggerList { SyncTrigger *pTrigger; struct _SyncTriggerList *next; } SyncTriggerList; typedef struct _SyncAlarmClientList { ClientPtr client; XID delete_id; struct _SyncAlarmClientList *next; } SyncAlarmClientList; typedef struct _SyncAlarm { SyncTrigger trigger; ClientPtr client; XSyncAlarm alarm_id; CARD64 delta; int events; int state; SyncAlarmClientList *pEventClients; } SyncAlarm; typedef struct { ClientPtr client; CARD32 delete_id; int num_waitconditions; } SyncAwaitHeader; typedef struct { SyncTrigger trigger; CARD64 event_threshold; SyncAwaitHeader *pHeader; } SyncAwait; typedef union { SyncAwaitHeader header; SyncAwait await; } SyncAwaitUnion; extern pointer SyncCreateSystemCounter( char * /* name */, CARD64 /* initial_value */, CARD64 /* resolution */, SyncCounterType /* change characterization */, void (* /*QueryValue*/ ) ( pointer /* pCounter */, CARD64 * /* pValue_return */), /* XXX prototype */ void (* /*BracketValues*/) ( pointer /* pCounter */, CARD64 * /* pbracket_less */, CARD64 * /* pbracket_greater */) ); extern void SyncChangeCounter( SyncCounter * /* pCounter*/, CARD64 /* new_value */ ); extern void SyncDestroySystemCounter( pointer pCounter ); extern void InitServertime(void); #endif /* _SYNC_SERVER */ #endif /* _SYNCSTR_H_ */ X11/extensions/shapeconst.h000064400000003526151027430550011644 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ #ifndef _SHAPECONST_H_ #define _SHAPECONST_H_ /* * Protocol requests constants and alignment values * These would really be in SHAPE's X.h and Xproto.h equivalents */ #define SHAPENAME "SHAPE" #define SHAPE_MAJOR_VERSION 1 /* current version numbers */ #define SHAPE_MINOR_VERSION 1 #define ShapeSet 0 #define ShapeUnion 1 #define ShapeIntersect 2 #define ShapeSubtract 3 #define ShapeInvert 4 #define ShapeBounding 0 #define ShapeClip 1 #define ShapeInput 2 #define ShapeNotifyMask (1L << 0) #define ShapeNotify 0 #define ShapeNumberEvents (ShapeNotify + 1) #endif /* _SHAPECONST_H_ */ X11/extensions/dri2proto.h000064400000020176151027430550011421 0ustar00/* * Copyright © 2008 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Soft- * ware"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, provided that the above copyright * notice(s) and this permission notice appear in all copies of the Soft- * ware and that both the above copyright notice(s) and this permission * notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- * ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY * RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN * THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSE- * QUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFOR- * MANCE OF THIS SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall * not be used in advertising or otherwise to promote the sale, use or * other dealings in this Software without prior written authorization of * the copyright holder. * * Authors: * Kristian Høgsberg (krh@redhat.com) */ #ifndef _DRI2_PROTO_H_ #define _DRI2_PROTO_H_ #define DRI2_NAME "DRI2" #define DRI2_MAJOR 1 #define DRI2_MINOR 4 #define DRI2NumberErrors 0 #define DRI2NumberEvents 2 #define DRI2NumberRequests 14 #define X_DRI2QueryVersion 0 #define X_DRI2Connect 1 #define X_DRI2Authenticate 2 #define X_DRI2CreateDrawable 3 #define X_DRI2DestroyDrawable 4 #define X_DRI2GetBuffers 5 #define X_DRI2CopyRegion 6 #define X_DRI2GetBuffersWithFormat 7 #define X_DRI2SwapBuffers 8 #define X_DRI2GetMSC 9 #define X_DRI2WaitMSC 10 #define X_DRI2WaitSBC 11 #define X_DRI2SwapInterval 12 #define X_DRI2GetParam 13 /* * Events */ #define DRI2_BufferSwapComplete 0 #define DRI2_InvalidateBuffers 1 typedef struct { CARD32 attachment; CARD32 name; CARD32 pitch; CARD32 cpp; CARD32 flags; } xDRI2Buffer; typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xDRI2QueryVersionReq; #define sz_xDRI2QueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDRI2QueryVersionReply; #define sz_xDRI2QueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 window; CARD32 driverType; } xDRI2ConnectReq; #define sz_xDRI2ConnectReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 driverNameLength; CARD32 deviceNameLength; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDRI2ConnectReply; #define sz_xDRI2ConnectReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 window; CARD32 magic; } xDRI2AuthenticateReq; #define sz_xDRI2AuthenticateReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 authenticated; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xDRI2AuthenticateReply; #define sz_xDRI2AuthenticateReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; } xDRI2CreateDrawableReq; #define sz_xDRI2CreateDrawableReq 8 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; } xDRI2DestroyDrawableReq; #define sz_xDRI2DestroyDrawableReq 8 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 count; } xDRI2GetBuffersReq; #define sz_xDRI2GetBuffersReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 width; CARD32 height; CARD32 count; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDRI2GetBuffersReply; #define sz_xDRI2GetBuffersReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 region; CARD32 dest; CARD32 src; } xDRI2CopyRegionReq; #define sz_xDRI2CopyRegionReq 20 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xDRI2CopyRegionReply; #define sz_xDRI2CopyRegionReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 target_msc_hi; CARD32 target_msc_lo; CARD32 divisor_hi; CARD32 divisor_lo; CARD32 remainder_hi; CARD32 remainder_lo; } xDRI2SwapBuffersReq; #define sz_xDRI2SwapBuffersReq 32 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 swap_hi; CARD32 swap_lo; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDRI2SwapBuffersReply; #define sz_xDRI2SwapBuffersReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; } xDRI2GetMSCReq; #define sz_xDRI2GetMSCReq 8 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 target_msc_hi; CARD32 target_msc_lo; CARD32 divisor_hi; CARD32 divisor_lo; CARD32 remainder_hi; CARD32 remainder_lo; } xDRI2WaitMSCReq; #define sz_xDRI2WaitMSCReq 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 target_sbc_hi; CARD32 target_sbc_lo; } xDRI2WaitSBCReq; #define sz_xDRI2WaitSBCReq 16 typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 ust_hi; CARD32 ust_lo; CARD32 msc_hi; CARD32 msc_lo; CARD32 sbc_hi; CARD32 sbc_lo; } xDRI2MSCReply; #define sz_xDRI2MSCReply 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 interval; } xDRI2SwapIntervalReq; #define sz_xDRI2SwapIntervalReq 12 typedef struct { CARD8 type; CARD8 pad; CARD16 sequenceNumber; CARD16 event_type; CARD16 pad2; CARD32 drawable; CARD32 ust_hi; CARD32 ust_lo; CARD32 msc_hi; CARD32 msc_lo; CARD32 sbc_hi; CARD32 sbc_lo; } xDRI2BufferSwapComplete; #define sz_xDRI2BufferSwapComplete 32 typedef struct { CARD8 type; CARD8 pad; CARD16 sequenceNumber; CARD16 event_type; CARD16 pad2; CARD32 drawable; CARD32 ust_hi; CARD32 ust_lo; CARD32 msc_hi; CARD32 msc_lo; CARD32 sbc; } xDRI2BufferSwapComplete2; #define sz_xDRI2BufferSwapComplete2 32 typedef struct { CARD8 type; CARD8 pad; CARD16 sequenceNumber; CARD32 drawable; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xDRI2InvalidateBuffers; #define sz_xDRI2InvalidateBuffers 32 typedef struct { CARD8 reqType; CARD8 dri2ReqType; CARD16 length; CARD32 drawable; CARD32 param; } xDRI2GetParamReq; #define sz_xDRI2GetParamReq 12 typedef struct { BYTE type; /*X_Reply*/ BOOL is_param_recognized; CARD16 sequenceNumber; CARD32 length; CARD32 value_hi; CARD32 value_lo; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDRI2GetParamReply; #define sz_xDRI2GetParamReply 32 #endif X11/extensions/randr.h000064400000015375151027430550010610 0ustar00/* * Copyright © 2000 Compaq Computer Corporation * Copyright © 2002 Hewlett Packard Company * Copyright © 2006 Intel Corporation * Copyright © 2008 Red Hat, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of the copyright holders not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no representations * about the suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. * * Author: Jim Gettys, HP Labs, Hewlett-Packard, Inc. * Keith Packard, Intel Corporation */ #ifndef _RANDR_H_ #define _RANDR_H_ typedef unsigned short Rotation; typedef unsigned short SizeID; typedef unsigned short SubpixelOrder; typedef unsigned short Connection; typedef unsigned short XRandrRotation; typedef unsigned short XRandrSizeID; typedef unsigned short XRandrSubpixelOrder; typedef unsigned long XRandrModeFlags; #define RANDR_NAME "RANDR" #define RANDR_MAJOR 1 #define RANDR_MINOR 6 #define RRNumberErrors 5 #define RRNumberEvents 2 #define RRNumberRequests 47 #define X_RRQueryVersion 0 /* we skip 1 to make old clients fail pretty immediately */ #define X_RROldGetScreenInfo 1 #define X_RR1_0SetScreenConfig 2 /* V1.0 apps share the same set screen config request id */ #define X_RRSetScreenConfig 2 #define X_RROldScreenChangeSelectInput 3 /* 3 used to be ScreenChangeSelectInput; deprecated */ #define X_RRSelectInput 4 #define X_RRGetScreenInfo 5 /* V1.2 additions */ #define X_RRGetScreenSizeRange 6 #define X_RRSetScreenSize 7 #define X_RRGetScreenResources 8 #define X_RRGetOutputInfo 9 #define X_RRListOutputProperties 10 #define X_RRQueryOutputProperty 11 #define X_RRConfigureOutputProperty 12 #define X_RRChangeOutputProperty 13 #define X_RRDeleteOutputProperty 14 #define X_RRGetOutputProperty 15 #define X_RRCreateMode 16 #define X_RRDestroyMode 17 #define X_RRAddOutputMode 18 #define X_RRDeleteOutputMode 19 #define X_RRGetCrtcInfo 20 #define X_RRSetCrtcConfig 21 #define X_RRGetCrtcGammaSize 22 #define X_RRGetCrtcGamma 23 #define X_RRSetCrtcGamma 24 /* V1.3 additions */ #define X_RRGetScreenResourcesCurrent 25 #define X_RRSetCrtcTransform 26 #define X_RRGetCrtcTransform 27 #define X_RRGetPanning 28 #define X_RRSetPanning 29 #define X_RRSetOutputPrimary 30 #define X_RRGetOutputPrimary 31 #define RRTransformUnit (1L << 0) #define RRTransformScaleUp (1L << 1) #define RRTransformScaleDown (1L << 2) #define RRTransformProjective (1L << 3) /* v1.4 */ #define X_RRGetProviders 32 #define X_RRGetProviderInfo 33 #define X_RRSetProviderOffloadSink 34 #define X_RRSetProviderOutputSource 35 #define X_RRListProviderProperties 36 #define X_RRQueryProviderProperty 37 #define X_RRConfigureProviderProperty 38 #define X_RRChangeProviderProperty 39 #define X_RRDeleteProviderProperty 40 #define X_RRGetProviderProperty 41 /* v1.5 */ #define X_RRGetMonitors 42 #define X_RRSetMonitor 43 #define X_RRDeleteMonitor 44 /* v1.6 */ #define X_RRCreateLease 45 #define X_RRFreeLease 46 /* Event selection bits */ #define RRScreenChangeNotifyMask (1L << 0) /* V1.2 additions */ #define RRCrtcChangeNotifyMask (1L << 1) #define RROutputChangeNotifyMask (1L << 2) #define RROutputPropertyNotifyMask (1L << 3) /* V1.4 additions */ #define RRProviderChangeNotifyMask (1L << 4) #define RRProviderPropertyNotifyMask (1L << 5) #define RRResourceChangeNotifyMask (1L << 6) /* V1.6 additions */ #define RRLeaseNotifyMask (1L << 7) /* Event codes */ #define RRScreenChangeNotify 0 /* V1.2 additions */ #define RRNotify 1 /* RRNotify Subcodes */ #define RRNotify_CrtcChange 0 #define RRNotify_OutputChange 1 #define RRNotify_OutputProperty 2 #define RRNotify_ProviderChange 3 #define RRNotify_ProviderProperty 4 #define RRNotify_ResourceChange 5 /* V1.6 additions */ #define RRNotify_Lease 6 /* used in the rotation field; rotation and reflection in 0.1 proto. */ #define RR_Rotate_0 1 #define RR_Rotate_90 2 #define RR_Rotate_180 4 #define RR_Rotate_270 8 /* new in 1.0 protocol, to allow reflection of screen */ #define RR_Reflect_X 16 #define RR_Reflect_Y 32 #define RRSetConfigSuccess 0 #define RRSetConfigInvalidConfigTime 1 #define RRSetConfigInvalidTime 2 #define RRSetConfigFailed 3 /* new in 1.2 protocol */ #define RR_HSyncPositive 0x00000001 #define RR_HSyncNegative 0x00000002 #define RR_VSyncPositive 0x00000004 #define RR_VSyncNegative 0x00000008 #define RR_Interlace 0x00000010 #define RR_DoubleScan 0x00000020 #define RR_CSync 0x00000040 #define RR_CSyncPositive 0x00000080 #define RR_CSyncNegative 0x00000100 #define RR_HSkewPresent 0x00000200 #define RR_BCast 0x00000400 #define RR_PixelMultiplex 0x00000800 #define RR_DoubleClock 0x00001000 #define RR_ClockDivideBy2 0x00002000 #define RR_Connected 0 #define RR_Disconnected 1 #define RR_UnknownConnection 2 #define BadRROutput 0 #define BadRRCrtc 1 #define BadRRMode 2 #define BadRRProvider 3 #define BadRRLease 4 /* Conventional RandR output properties */ #define RR_PROPERTY_BACKLIGHT "Backlight" #define RR_PROPERTY_RANDR_EDID "EDID" #define RR_PROPERTY_SIGNAL_FORMAT "SignalFormat" #define RR_PROPERTY_SIGNAL_PROPERTIES "SignalProperties" #define RR_PROPERTY_CONNECTOR_TYPE "ConnectorType" #define RR_PROPERTY_CONNECTOR_NUMBER "ConnectorNumber" #define RR_PROPERTY_COMPATIBILITY_LIST "CompatibilityList" #define RR_PROPERTY_CLONE_LIST "CloneList" #define RR_PROPERTY_BORDER "Border" #define RR_PROPERTY_BORDER_DIMENSIONS "BorderDimensions" #define RR_PROPERTY_GUID "GUID" #define RR_PROPERTY_RANDR_TILE "TILE" #define RR_PROPERTY_NON_DESKTOP "non-desktop" /* roles this device can carry out */ #define RR_Capability_None 0 #define RR_Capability_SourceOutput 1 #define RR_Capability_SinkOutput 2 #define RR_Capability_SourceOffload 4 #define RR_Capability_SinkOffload 8 #endif /* _RANDR_H_ */ X11/extensions/EVIproto.h000064400000005676151027430550011214 0ustar00/************************************************************ Copyright (c) 1997 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _EVIPROTO_H_ #define _EVIPROTO_H_ #include #define X_EVIQueryVersion 0 #define X_EVIGetVisualInfo 1 #define VisualID CARD32 typedef CARD32 VisualID32; #define sz_VisualID32 4 typedef struct _xExtendedVisualInfo { VisualID core_visual_id; INT8 screen; INT8 level; CARD8 transparency_type; CARD8 pad0; CARD32 transparency_value; CARD8 min_hw_colormaps; CARD8 max_hw_colormaps; CARD16 num_colormap_conflicts; } xExtendedVisualInfo; #define sz_xExtendedVisualInfo 16 typedef struct _XEVIQueryVersion { CARD8 reqType; /* always XEVIReqCode */ CARD8 xeviReqType; /* always X_EVIQueryVersion */ CARD16 length; } xEVIQueryVersionReq; #define sz_xEVIQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of EVI protocol */ CARD16 minorVersion; /* minor version of EVI protocol */ CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xEVIQueryVersionReply; #define sz_xEVIQueryVersionReply 32 typedef struct _XEVIGetVisualInfoReq { CARD8 reqType; /* always XEVIReqCode */ CARD8 xeviReqType; /* always X_EVIGetVisualInfo */ CARD16 length; CARD32 n_visual; } xEVIGetVisualInfoReq; #define sz_xEVIGetVisualInfoReq 8 typedef struct _XEVIGetVisualInfoReply { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 n_info; CARD32 n_conflicts; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xEVIGetVisualInfoReply; #define sz_xEVIGetVisualInfoReply 32 #undef VisualID #endif /* _EVIPROTO_H_ */ X11/extensions/render.h000064400000015425151027430550010755 0ustar00/* * Copyright © 2000 SuSE, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of SuSE not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. SuSE makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Author: Keith Packard, SuSE, Inc. */ #ifndef _RENDER_H_ #define _RENDER_H_ #include typedef XID Glyph; typedef XID GlyphSet; typedef XID Picture; typedef XID PictFormat; #define RENDER_NAME "RENDER" #define RENDER_MAJOR 0 #define RENDER_MINOR 11 #define X_RenderQueryVersion 0 #define X_RenderQueryPictFormats 1 #define X_RenderQueryPictIndexValues 2 /* 0.7 */ #define X_RenderQueryDithers 3 #define X_RenderCreatePicture 4 #define X_RenderChangePicture 5 #define X_RenderSetPictureClipRectangles 6 #define X_RenderFreePicture 7 #define X_RenderComposite 8 #define X_RenderScale 9 #define X_RenderTrapezoids 10 #define X_RenderTriangles 11 #define X_RenderTriStrip 12 #define X_RenderTriFan 13 #define X_RenderColorTrapezoids 14 #define X_RenderColorTriangles 15 /* #define X_RenderTransform 16 */ #define X_RenderCreateGlyphSet 17 #define X_RenderReferenceGlyphSet 18 #define X_RenderFreeGlyphSet 19 #define X_RenderAddGlyphs 20 #define X_RenderAddGlyphsFromPicture 21 #define X_RenderFreeGlyphs 22 #define X_RenderCompositeGlyphs8 23 #define X_RenderCompositeGlyphs16 24 #define X_RenderCompositeGlyphs32 25 #define X_RenderFillRectangles 26 /* 0.5 */ #define X_RenderCreateCursor 27 /* 0.6 */ #define X_RenderSetPictureTransform 28 #define X_RenderQueryFilters 29 #define X_RenderSetPictureFilter 30 /* 0.8 */ #define X_RenderCreateAnimCursor 31 /* 0.9 */ #define X_RenderAddTraps 32 /* 0.10 */ #define X_RenderCreateSolidFill 33 #define X_RenderCreateLinearGradient 34 #define X_RenderCreateRadialGradient 35 #define X_RenderCreateConicalGradient 36 #define RenderNumberRequests (X_RenderCreateConicalGradient+1) #define BadPictFormat 0 #define BadPicture 1 #define BadPictOp 2 #define BadGlyphSet 3 #define BadGlyph 4 #define RenderNumberErrors (BadGlyph+1) #define PictTypeIndexed 0 #define PictTypeDirect 1 #define PictOpMinimum 0 #define PictOpClear 0 #define PictOpSrc 1 #define PictOpDst 2 #define PictOpOver 3 #define PictOpOverReverse 4 #define PictOpIn 5 #define PictOpInReverse 6 #define PictOpOut 7 #define PictOpOutReverse 8 #define PictOpAtop 9 #define PictOpAtopReverse 10 #define PictOpXor 11 #define PictOpAdd 12 #define PictOpSaturate 13 #define PictOpMaximum 13 /* * Operators only available in version 0.2 */ #define PictOpDisjointMinimum 0x10 #define PictOpDisjointClear 0x10 #define PictOpDisjointSrc 0x11 #define PictOpDisjointDst 0x12 #define PictOpDisjointOver 0x13 #define PictOpDisjointOverReverse 0x14 #define PictOpDisjointIn 0x15 #define PictOpDisjointInReverse 0x16 #define PictOpDisjointOut 0x17 #define PictOpDisjointOutReverse 0x18 #define PictOpDisjointAtop 0x19 #define PictOpDisjointAtopReverse 0x1a #define PictOpDisjointXor 0x1b #define PictOpDisjointMaximum 0x1b #define PictOpConjointMinimum 0x20 #define PictOpConjointClear 0x20 #define PictOpConjointSrc 0x21 #define PictOpConjointDst 0x22 #define PictOpConjointOver 0x23 #define PictOpConjointOverReverse 0x24 #define PictOpConjointIn 0x25 #define PictOpConjointInReverse 0x26 #define PictOpConjointOut 0x27 #define PictOpConjointOutReverse 0x28 #define PictOpConjointAtop 0x29 #define PictOpConjointAtopReverse 0x2a #define PictOpConjointXor 0x2b #define PictOpConjointMaximum 0x2b /* * Operators only available in version 0.11 */ #define PictOpBlendMinimum 0x30 #define PictOpMultiply 0x30 #define PictOpScreen 0x31 #define PictOpOverlay 0x32 #define PictOpDarken 0x33 #define PictOpLighten 0x34 #define PictOpColorDodge 0x35 #define PictOpColorBurn 0x36 #define PictOpHardLight 0x37 #define PictOpSoftLight 0x38 #define PictOpDifference 0x39 #define PictOpExclusion 0x3a #define PictOpHSLHue 0x3b #define PictOpHSLSaturation 0x3c #define PictOpHSLColor 0x3d #define PictOpHSLLuminosity 0x3e #define PictOpBlendMaximum 0x3e #define PolyEdgeSharp 0 #define PolyEdgeSmooth 1 #define PolyModePrecise 0 #define PolyModeImprecise 1 #define CPRepeat (1 << 0) #define CPAlphaMap (1 << 1) #define CPAlphaXOrigin (1 << 2) #define CPAlphaYOrigin (1 << 3) #define CPClipXOrigin (1 << 4) #define CPClipYOrigin (1 << 5) #define CPClipMask (1 << 6) #define CPGraphicsExposure (1 << 7) #define CPSubwindowMode (1 << 8) #define CPPolyEdge (1 << 9) #define CPPolyMode (1 << 10) #define CPDither (1 << 11) #define CPComponentAlpha (1 << 12) #define CPLastBit 12 /* Filters included in 0.6 */ #define FilterNearest "nearest" #define FilterBilinear "bilinear" /* Filters included in 0.10 */ #define FilterConvolution "convolution" #define FilterFast "fast" #define FilterGood "good" #define FilterBest "best" #define FilterAliasNone -1 /* Subpixel orders included in 0.6 */ #define SubPixelUnknown 0 #define SubPixelHorizontalRGB 1 #define SubPixelHorizontalBGR 2 #define SubPixelVerticalRGB 3 #define SubPixelVerticalBGR 4 #define SubPixelNone 5 /* Extended repeat attributes included in 0.10 */ #define RepeatNone 0 #define RepeatNormal 1 #define RepeatPad 2 #define RepeatReflect 3 #endif /* _RENDER_H_ */ X11/extensions/xf86vm.h000064400000004072151027430550010630 0ustar00/* Copyright 1995 Kaleb S. KEITHLEY Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL Kaleb S. KEITHLEY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Kaleb S. KEITHLEY shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Kaleb S. KEITHLEY */ /* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */ #ifndef _XF86VM_H_ #define _XF86VM_H_ #include #define CLKFLAG_PROGRAMABLE 1 #ifdef XF86VIDMODE_EVENTS #define XF86VidModeNotify 0 #define XF86VidModeNumberEvents (XF86VidModeNotify + 1) #define XF86VidModeNotifyMask 0x00000001 #define XF86VidModeNonEvent 0 #define XF86VidModeModeChange 1 #else #define XF86VidModeNumberEvents 0 #endif #define XF86VidModeBadClock 0 #define XF86VidModeBadHTimings 1 #define XF86VidModeBadVTimings 2 #define XF86VidModeModeUnsuitable 3 #define XF86VidModeExtensionDisabled 4 #define XF86VidModeClientNotLocal 5 #define XF86VidModeZoomLocked 6 #define XF86VidModeNumberErrors (XF86VidModeZoomLocked + 1) #define XF86VM_READ_PERMISSION 1 #define XF86VM_WRITE_PERMISSION 2 #endif X11/extensions/compositeproto.h000064400000012526151027430550012563 0ustar00/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * Copyright © 2003 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _COMPOSITEPROTO_H_ #define _COMPOSITEPROTO_H_ #include #include #define Window CARD32 #define Region CARD32 #define Pixmap CARD32 /* * requests and replies */ typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xCompositeQueryVersionReq; #define sz_xCompositeQueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xCompositeQueryVersionReply; #define sz_xCompositeQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; CARD8 update; CARD8 pad1; CARD16 pad2; } xCompositeRedirectWindowReq; #define sz_xCompositeRedirectWindowReq 12 typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; CARD8 update; CARD8 pad1; CARD16 pad2; } xCompositeRedirectSubwindowsReq; #define sz_xCompositeRedirectSubwindowsReq 12 typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; CARD8 update; CARD8 pad1; CARD16 pad2; } xCompositeUnredirectWindowReq; #define sz_xCompositeUnredirectWindowReq 12 typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; CARD8 update; CARD8 pad1; CARD16 pad2; } xCompositeUnredirectSubwindowsReq; #define sz_xCompositeUnredirectSubwindowsReq 12 typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Region region; Window window; } xCompositeCreateRegionFromBorderClipReq; #define sz_xCompositeCreateRegionFromBorderClipReq 12 /* Version 0.2 additions */ typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; Pixmap pixmap; } xCompositeNameWindowPixmapReq; #define sz_xCompositeNameWindowPixmapReq 12 /* Version 0.3 additions */ typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; } xCompositeGetOverlayWindowReq; #define sz_xCompositeGetOverlayWindowReq sizeof(xCompositeGetOverlayWindowReq) typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; Window overlayWin; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xCompositeGetOverlayWindowReply; #define sz_xCompositeGetOverlayWindowReply sizeof(xCompositeGetOverlayWindowReply) typedef struct { CARD8 reqType; CARD8 compositeReqType; CARD16 length; Window window; } xCompositeReleaseOverlayWindowReq; #define sz_xCompositeReleaseOverlayWindowReq sizeof(xCompositeReleaseOverlayWindowReq) #undef Window #undef Region #undef Pixmap #endif /* _COMPOSITEPROTO_H_ */ X11/extensions/xtestproto.h000064400000006266151027430550011734 0ustar00/* Copyright 1992, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _XTESTPROTO_H_ #define _XTESTPROTO_H_ #include #define Window CARD32 #define Time CARD32 #define Cursor CARD32 #define X_XTestGetVersion 0 #define X_XTestCompareCursor 1 #define X_XTestFakeInput 2 #define X_XTestGrabControl 3 typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 xtReqType; /* always X_XTestGetVersion */ CARD16 length; CARD8 majorVersion; CARD8 pad; CARD16 minorVersion; } xXTestGetVersionReq; #define sz_xXTestGetVersionReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 majorVersion; CARD16 sequenceNumber; CARD32 length; CARD16 minorVersion; CARD16 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXTestGetVersionReply; #define sz_xXTestGetVersionReply 32 typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 xtReqType; /* always X_XTestCompareCursor */ CARD16 length; Window window; Cursor cursor; } xXTestCompareCursorReq; #define sz_xXTestCompareCursorReq 12 typedef struct { BYTE type; /* X_Reply */ BOOL same; CARD16 sequenceNumber; CARD32 length; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXTestCompareCursorReply; #define sz_xXTestCompareCursorReply 32 /* used only on the client side */ typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 xtReqType; /* always X_XTestFakeInput */ CARD16 length; BYTE type; BYTE detail; CARD16 pad0; Time time; Window root; CARD32 pad1; CARD32 pad2; INT16 rootX, rootY; CARD32 pad3; CARD16 pad4; CARD8 pad5; CARD8 deviceid; } xXTestFakeInputReq; #define sz_xXTestFakeInputReq 36 typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 xtReqType; /* always X_XTestGrabControl */ CARD16 length; BOOL impervious; CARD8 pad0; CARD8 pad1; CARD8 pad2; } xXTestGrabControlReq; #define sz_xXTestGrabControlReq 8 #undef Window #undef Time #undef Cursor #endif /* _XTESTPROTO_H_ */ X11/extensions/xf86dga1const.h000064400000001643151027430550012072 0ustar00/* Copyright (c) 1995 Jon Tombs Copyright (c) 1995 XFree86 Inc */ /************************************************************************ THIS IS THE OLD DGA API AND IS OBSOLETE. PLEASE DO NOT USE IT ANYMORE ************************************************************************/ #ifndef _XF86DGA1CONST_H_ #define _XF86DGA1CONST_H_ #define X_XF86DGAQueryVersion 0 #define X_XF86DGAGetVideoLL 1 #define X_XF86DGADirectVideo 2 #define X_XF86DGAGetViewPortSize 3 #define X_XF86DGASetViewPort 4 #define X_XF86DGAGetVidPage 5 #define X_XF86DGASetVidPage 6 #define X_XF86DGAInstallColormap 7 #define X_XF86DGAQueryDirectVideo 8 #define X_XF86DGAViewPortChanged 9 #define XF86DGADirectPresent 0x0001 #define XF86DGADirectGraphics 0x0002 #define XF86DGADirectMouse 0x0004 #define XF86DGADirectKeyb 0x0008 #define XF86DGAHasColormap 0x0100 #define XF86DGADirectColormap 0x0200 #endif /* _XF86DGA1CONST_H_ */ X11/extensions/saver.h000064400000003554151027430550010616 0ustar00/* Copyright (c) 1992 X Consortium Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. * * Author: Keith Packard, MIT X Consortium */ #ifndef _SAVER_H_ #define _SAVER_H_ #define ScreenSaverName "MIT-SCREEN-SAVER" #define ScreenSaverPropertyName "_MIT_SCREEN_SAVER_ID" #define ScreenSaverNotifyMask 0x00000001 #define ScreenSaverCycleMask 0x00000002 #define ScreenSaverMajorVersion 1 #define ScreenSaverMinorVersion 1 #define ScreenSaverOff 0 #define ScreenSaverOn 1 #define ScreenSaverCycle 2 #define ScreenSaverDisabled 3 #define ScreenSaverBlanked 0 #define ScreenSaverInternal 1 #define ScreenSaverExternal 2 #define ScreenSaverNotify 0 #define ScreenSaverNumberEvents 1 #endif /* _SAVER_H_ */ X11/extensions/xcmiscstr.h000064400000000271151027430550011506 0ustar00#warning "xcmiscstr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/extensions/renderproto.h000064400000031642151027430550012040 0ustar00/* * Copyright © 2000 SuSE, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of SuSE not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. SuSE makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Author: Keith Packard, SuSE, Inc. */ #ifndef _XRENDERP_H_ #define _XRENDERP_H_ #include #include #define Window CARD32 #define Drawable CARD32 #define Font CARD32 #define Pixmap CARD32 #define Cursor CARD32 #define Colormap CARD32 #define GContext CARD32 #define Atom CARD32 #define VisualID CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define Picture CARD32 #define PictFormat CARD32 #define Fixed INT32 #define Glyphset CARD32 /* * data structures */ typedef struct { CARD16 red; CARD16 redMask; CARD16 green; CARD16 greenMask; CARD16 blue; CARD16 blueMask; CARD16 alpha; CARD16 alphaMask; } xDirectFormat; #define sz_xDirectFormat 16 typedef struct { PictFormat id; CARD8 type; CARD8 depth; CARD16 pad1; xDirectFormat direct; Colormap colormap; } xPictFormInfo; #define sz_xPictFormInfo 28 typedef struct { VisualID visual; PictFormat format; } xPictVisual; #define sz_xPictVisual 8 typedef struct { CARD8 depth; CARD8 pad1; CARD16 nPictVisuals; CARD32 pad2; } xPictDepth; #define sz_xPictDepth 8 typedef struct { CARD32 nDepth; PictFormat fallback; } xPictScreen; #define sz_xPictScreen 8 typedef struct { CARD32 pixel; CARD16 red; CARD16 green; CARD16 blue; CARD16 alpha; } xIndexValue; #define sz_xIndexValue 12 typedef struct { CARD16 red; CARD16 green; CARD16 blue; CARD16 alpha; } xRenderColor; #define sz_xRenderColor 8 typedef struct { Fixed x; Fixed y; } xPointFixed; #define sz_xPointFixed 8 typedef struct { xPointFixed p1; xPointFixed p2; } xLineFixed; #define sz_xLineFixed 16 typedef struct { xPointFixed p1, p2, p3; } xTriangle; #define sz_xTriangle 24 typedef struct { Fixed top; Fixed bottom; xLineFixed left; xLineFixed right; } xTrapezoid; #define sz_xTrapezoid 40 typedef struct { CARD16 width; CARD16 height; INT16 x; INT16 y; INT16 xOff; INT16 yOff; } xGlyphInfo; #define sz_xGlyphInfo 12 typedef struct { CARD8 len; CARD8 pad1; CARD16 pad2; INT16 deltax; INT16 deltay; } xGlyphElt; #define sz_xGlyphElt 8 typedef struct { Fixed l, r, y; } xSpanFix; #define sz_xSpanFix 12 typedef struct { xSpanFix top, bot; } xTrap; #define sz_xTrap 24 /* * requests and replies */ typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xRenderQueryVersionReq; #define sz_xRenderQueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRenderQueryVersionReply; #define sz_xRenderQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; } xRenderQueryPictFormatsReq; #define sz_xRenderQueryPictFormatsReq 4 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 numFormats; CARD32 numScreens; CARD32 numDepths; CARD32 numVisuals; CARD32 numSubpixel; /* Version 0.6 */ CARD32 pad5; } xRenderQueryPictFormatsReply; #define sz_xRenderQueryPictFormatsReply 32 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; PictFormat format; } xRenderQueryPictIndexValuesReq; #define sz_xRenderQueryPictIndexValuesReq 8 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 numIndexValues; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xRenderQueryPictIndexValuesReply; #define sz_xRenderQueryPictIndexValuesReply 32 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture pid; Drawable drawable; PictFormat format; CARD32 mask; } xRenderCreatePictureReq; #define sz_xRenderCreatePictureReq 20 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture picture; CARD32 mask; } xRenderChangePictureReq; #define sz_xRenderChangePictureReq 12 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture picture; INT16 xOrigin; INT16 yOrigin; } xRenderSetPictureClipRectanglesReq; #define sz_xRenderSetPictureClipRectanglesReq 12 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture picture; } xRenderFreePictureReq; #define sz_xRenderFreePictureReq 8 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture src; Picture mask; Picture dst; INT16 xSrc; INT16 ySrc; INT16 xMask; INT16 yMask; INT16 xDst; INT16 yDst; CARD16 width; CARD16 height; } xRenderCompositeReq; #define sz_xRenderCompositeReq 36 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture src; Picture dst; CARD32 colorScale; CARD32 alphaScale; INT16 xSrc; INT16 ySrc; INT16 xDst; INT16 yDst; CARD16 width; CARD16 height; } xRenderScaleReq; #define sz_xRenderScaleReq 32 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture src; Picture dst; PictFormat maskFormat; INT16 xSrc; INT16 ySrc; } xRenderTrapezoidsReq; #define sz_xRenderTrapezoidsReq 24 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture src; Picture dst; PictFormat maskFormat; INT16 xSrc; INT16 ySrc; } xRenderTrianglesReq; #define sz_xRenderTrianglesReq 24 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture src; Picture dst; PictFormat maskFormat; INT16 xSrc; INT16 ySrc; } xRenderTriStripReq; #define sz_xRenderTriStripReq 24 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture src; Picture dst; PictFormat maskFormat; INT16 xSrc; INT16 ySrc; } xRenderTriFanReq; #define sz_xRenderTriFanReq 24 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Glyphset gsid; PictFormat format; } xRenderCreateGlyphSetReq; #define sz_xRenderCreateGlyphSetReq 12 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Glyphset gsid; Glyphset existing; } xRenderReferenceGlyphSetReq; #define sz_xRenderReferenceGlyphSetReq 24 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Glyphset glyphset; } xRenderFreeGlyphSetReq; #define sz_xRenderFreeGlyphSetReq 8 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Glyphset glyphset; CARD32 nglyphs; } xRenderAddGlyphsReq; #define sz_xRenderAddGlyphsReq 12 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Glyphset glyphset; } xRenderFreeGlyphsReq; #define sz_xRenderFreeGlyphsReq 8 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture src; Picture dst; PictFormat maskFormat; Glyphset glyphset; INT16 xSrc; INT16 ySrc; } xRenderCompositeGlyphsReq, xRenderCompositeGlyphs8Req, xRenderCompositeGlyphs16Req, xRenderCompositeGlyphs32Req; #define sz_xRenderCompositeGlyphs8Req 28 #define sz_xRenderCompositeGlyphs16Req 28 #define sz_xRenderCompositeGlyphs32Req 28 /* 0.1 and higher */ typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; CARD8 op; CARD8 pad1; CARD16 pad2; Picture dst; xRenderColor color; } xRenderFillRectanglesReq; #define sz_xRenderFillRectanglesReq 20 /* 0.5 and higher */ typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Cursor cid; Picture src; CARD16 x; CARD16 y; } xRenderCreateCursorReq; #define sz_xRenderCreateCursorReq 16 /* 0.6 and higher */ /* * This can't use an array because 32-bit values may be in bitfields */ typedef struct { Fixed matrix11; Fixed matrix12; Fixed matrix13; Fixed matrix21; Fixed matrix22; Fixed matrix23; Fixed matrix31; Fixed matrix32; Fixed matrix33; } xRenderTransform; #define sz_xRenderTransform 36 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture picture; xRenderTransform transform; } xRenderSetPictureTransformReq; #define sz_xRenderSetPictureTransformReq 44 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Drawable drawable; } xRenderQueryFiltersReq; #define sz_xRenderQueryFiltersReq 8 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 numAliases; /* LISTofCARD16 */ CARD32 numFilters; /* LISTofSTRING8 */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xRenderQueryFiltersReply; #define sz_xRenderQueryFiltersReply 32 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture picture; CARD16 nbytes; /* number of bytes in name */ CARD16 pad; } xRenderSetPictureFilterReq; #define sz_xRenderSetPictureFilterReq 12 /* 0.8 and higher */ typedef struct { Cursor cursor; CARD32 delay; } xAnimCursorElt; #define sz_xAnimCursorElt 8 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Cursor cid; } xRenderCreateAnimCursorReq; #define sz_xRenderCreateAnimCursorReq 8 /* 0.9 and higher */ typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture picture; INT16 xOff; INT16 yOff; } xRenderAddTrapsReq; #define sz_xRenderAddTrapsReq 12 /* 0.10 and higher */ typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture pid; xRenderColor color; } xRenderCreateSolidFillReq; #define sz_xRenderCreateSolidFillReq 16 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture pid; xPointFixed p1; xPointFixed p2; CARD32 nStops; } xRenderCreateLinearGradientReq; #define sz_xRenderCreateLinearGradientReq 28 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture pid; xPointFixed inner; xPointFixed outer; Fixed inner_radius; Fixed outer_radius; CARD32 nStops; } xRenderCreateRadialGradientReq; #define sz_xRenderCreateRadialGradientReq 36 typedef struct { CARD8 reqType; CARD8 renderReqType; CARD16 length; Picture pid; xPointFixed center; Fixed angle; /* in degrees */ CARD32 nStops; } xRenderCreateConicalGradientReq; #define sz_xRenderCreateConicalGradientReq 24 #undef Window #undef Drawable #undef Font #undef Pixmap #undef Cursor #undef Colormap #undef GContext #undef Atom #undef VisualID #undef Time #undef KeyCode #undef KeySym #undef Picture #undef PictFormat #undef Fixed #undef Glyphset #endif /* _XRENDERP_H_ */ X11/extensions/XKBproto.h000064400000070661151027430550011211 0ustar00/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XKBPROTO_H_ #define _XKBPROTO_H_ #include #include #define Window CARD32 #define Atom CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define XkbPaddedSize(n) ((((unsigned int)(n)+3) >> 2) << 2) typedef struct _xkbUseExtension { CARD8 reqType; CARD8 xkbReqType; /* always X_KBUseExtension */ CARD16 length; CARD16 wantedMajor; CARD16 wantedMinor; } xkbUseExtensionReq; #define sz_xkbUseExtensionReq 8 typedef struct _xkbUseExtensionReply { BYTE type; /* X_Reply */ BOOL supported; CARD16 sequenceNumber; CARD32 length; CARD16 serverMajor; CARD16 serverMinor; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xkbUseExtensionReply; #define sz_xkbUseExtensionReply 32 typedef struct _xkbSelectEvents { CARD8 reqType; CARD8 xkbReqType; /* X_KBSelectEvents */ CARD16 length; CARD16 deviceSpec; CARD16 affectWhich; CARD16 clear; CARD16 selectAll; CARD16 affectMap; CARD16 map; } xkbSelectEventsReq; #define sz_xkbSelectEventsReq 16 typedef struct _xkbBell { CARD8 reqType; CARD8 xkbReqType; /* X_KBBell */ CARD16 length; CARD16 deviceSpec; CARD16 bellClass; CARD16 bellID; INT8 percent; BOOL forceSound; BOOL eventOnly; CARD8 pad1; INT16 pitch; INT16 duration; CARD16 pad2; Atom name; Window window; } xkbBellReq; #define sz_xkbBellReq 28 typedef struct _xkbGetState { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetState */ CARD16 length; CARD16 deviceSpec; CARD16 pad; } xkbGetStateReq; #define sz_xkbGetStateReq 8 typedef struct _xkbGetStateReply { BYTE type; BYTE deviceID; CARD16 sequenceNumber; CARD32 length; CARD8 mods; CARD8 baseMods; CARD8 latchedMods; CARD8 lockedMods; CARD8 group; CARD8 lockedGroup; INT16 baseGroup; INT16 latchedGroup; CARD8 compatState; CARD8 grabMods; CARD8 compatGrabMods; CARD8 lookupMods; CARD8 compatLookupMods; CARD8 pad1; CARD16 ptrBtnState; CARD16 pad2; CARD32 pad3; } xkbGetStateReply; #define sz_xkbGetStateReply 32 typedef struct _xkbLatchLockState { CARD8 reqType; CARD8 xkbReqType; /* always X_KBLatchLockState */ CARD16 length; CARD16 deviceSpec; CARD8 affectModLocks; CARD8 modLocks; BOOL lockGroup; CARD8 groupLock; CARD8 affectModLatches; CARD8 modLatches; CARD8 pad; BOOL latchGroup; INT16 groupLatch; } xkbLatchLockStateReq; #define sz_xkbLatchLockStateReq 16 typedef struct _xkbGetControls { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetControls */ CARD16 length; CARD16 deviceSpec; CARD16 pad; } xkbGetControlsReq; #define sz_xkbGetControlsReq 8 typedef struct _xkbGetControlsReply { BYTE type; /* X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD8 mkDfltBtn; CARD8 numGroups; CARD8 groupsWrap; CARD8 internalMods; CARD8 ignoreLockMods; CARD8 internalRealMods; CARD8 ignoreLockRealMods; CARD8 pad1; CARD16 internalVMods; CARD16 ignoreLockVMods; CARD16 repeatDelay; CARD16 repeatInterval; CARD16 slowKeysDelay; CARD16 debounceDelay; CARD16 mkDelay; CARD16 mkInterval; CARD16 mkTimeToMax; CARD16 mkMaxSpeed; INT16 mkCurve; CARD16 axOptions; CARD16 axTimeout; CARD16 axtOptsMask; CARD16 axtOptsValues; CARD16 pad2; CARD32 axtCtrlsMask; CARD32 axtCtrlsValues; CARD32 enabledCtrls; BYTE perKeyRepeat[XkbPerKeyBitArraySize]; } xkbGetControlsReply; #define sz_xkbGetControlsReply 92 typedef struct _xkbSetControls { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetControls */ CARD16 length; CARD16 deviceSpec; CARD8 affectInternalMods; CARD8 internalMods; CARD8 affectIgnoreLockMods; CARD8 ignoreLockMods; CARD16 affectInternalVMods; CARD16 internalVMods; CARD16 affectIgnoreLockVMods; CARD16 ignoreLockVMods; CARD8 mkDfltBtn; CARD8 groupsWrap; CARD16 axOptions; CARD16 pad1; CARD32 affectEnabledCtrls; CARD32 enabledCtrls; CARD32 changeCtrls; CARD16 repeatDelay; CARD16 repeatInterval; CARD16 slowKeysDelay; CARD16 debounceDelay; CARD16 mkDelay; CARD16 mkInterval; CARD16 mkTimeToMax; CARD16 mkMaxSpeed; INT16 mkCurve; CARD16 axTimeout; CARD32 axtCtrlsMask; CARD32 axtCtrlsValues; CARD16 axtOptsMask; CARD16 axtOptsValues; BYTE perKeyRepeat[XkbPerKeyBitArraySize]; } xkbSetControlsReq; #define sz_xkbSetControlsReq 100 typedef struct _xkbKTMapEntryWireDesc { BOOL active; CARD8 mask; CARD8 level; CARD8 realMods; CARD16 virtualMods; CARD16 pad; } xkbKTMapEntryWireDesc; #define sz_xkbKTMapEntryWireDesc 8 typedef struct _xkbKTSetMapEntryWireDesc { CARD8 level; CARD8 realMods; CARD16 virtualMods; } xkbKTSetMapEntryWireDesc; #define sz_xkbKTSetMapEntryWireDesc 4 typedef struct _xkbModsWireDesc { CARD8 mask; /* GetMap only */ CARD8 realMods; CARD16 virtualMods; } xkbModsWireDesc; #define sz_xkbModsWireDesc 4 typedef struct _xkbKeyTypeWireDesc { CARD8 mask; CARD8 realMods; CARD16 virtualMods; CARD8 numLevels; CARD8 nMapEntries; BOOL preserve; CARD8 pad; } xkbKeyTypeWireDesc; #define sz_xkbKeyTypeWireDesc 8 typedef struct _xkbSymMapWireDesc { CARD8 ktIndex[XkbNumKbdGroups]; CARD8 groupInfo; CARD8 width; CARD16 nSyms; } xkbSymMapWireDesc; #define sz_xkbSymMapWireDesc 8 typedef struct _xkbVModMapWireDesc { KeyCode key; CARD8 pad; CARD16 vmods; } xkbVModMapWireDesc; #define sz_xkbVModMapWireDesc 4 typedef struct _xkbBehaviorWireDesc { CARD8 key; CARD8 type; CARD8 data; CARD8 pad; } xkbBehaviorWireDesc; #define sz_xkbBehaviorWireDesc 4 typedef struct _xkbActionWireDesc { CARD8 type; CARD8 data[7]; } xkbActionWireDesc; #define sz_xkbActionWireDesc 8 typedef struct _xkbGetMap { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetMap */ CARD16 length; CARD16 deviceSpec; CARD16 full; CARD16 partial; CARD8 firstType; CARD8 nTypes; KeyCode firstKeySym; CARD8 nKeySyms; KeyCode firstKeyAct; CARD8 nKeyActs; KeyCode firstKeyBehavior; CARD8 nKeyBehaviors; CARD16 virtualMods; KeyCode firstKeyExplicit; CARD8 nKeyExplicit; KeyCode firstModMapKey; CARD8 nModMapKeys; KeyCode firstVModMapKey; CARD8 nVModMapKeys; CARD16 pad1; } xkbGetMapReq; #define sz_xkbGetMapReq 28 typedef struct _xkbGetMapReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD16 pad1; KeyCode minKeyCode; KeyCode maxKeyCode; CARD16 present; CARD8 firstType; CARD8 nTypes; CARD8 totalTypes; KeyCode firstKeySym; CARD16 totalSyms; CARD8 nKeySyms; KeyCode firstKeyAct; CARD16 totalActs; CARD8 nKeyActs; KeyCode firstKeyBehavior; CARD8 nKeyBehaviors; CARD8 totalKeyBehaviors; KeyCode firstKeyExplicit; CARD8 nKeyExplicit; CARD8 totalKeyExplicit; KeyCode firstModMapKey; CARD8 nModMapKeys; CARD8 totalModMapKeys; KeyCode firstVModMapKey; CARD8 nVModMapKeys; CARD8 totalVModMapKeys; CARD8 pad2; CARD16 virtualMods; } xkbGetMapReply; #define sz_xkbGetMapReply 40 #define XkbSetMapResizeTypes (1L<<0) #define XkbSetMapRecomputeActions (1L<<1) #define XkbSetMapAllFlags (0x3) typedef struct _xkbSetMap { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetMap */ CARD16 length; CARD16 deviceSpec; CARD16 present; CARD16 flags; KeyCode minKeyCode; KeyCode maxKeyCode; CARD8 firstType; CARD8 nTypes; KeyCode firstKeySym; CARD8 nKeySyms; CARD16 totalSyms; KeyCode firstKeyAct; CARD8 nKeyActs; CARD16 totalActs; KeyCode firstKeyBehavior; CARD8 nKeyBehaviors; CARD8 totalKeyBehaviors; KeyCode firstKeyExplicit; CARD8 nKeyExplicit; CARD8 totalKeyExplicit; KeyCode firstModMapKey; CARD8 nModMapKeys; CARD8 totalModMapKeys; KeyCode firstVModMapKey; CARD8 nVModMapKeys; CARD8 totalVModMapKeys; CARD16 virtualMods; } xkbSetMapReq; #define sz_xkbSetMapReq 36 typedef struct _xkbSymInterpretWireDesc { CARD32 sym; CARD8 mods; CARD8 match; CARD8 virtualMod; CARD8 flags; xkbActionWireDesc act; } xkbSymInterpretWireDesc; #define sz_xkbSymInterpretWireDesc 16 typedef struct _xkbGetCompatMap { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetCompatMap */ CARD16 length; CARD16 deviceSpec; CARD8 groups; BOOL getAllSI; CARD16 firstSI; CARD16 nSI; } xkbGetCompatMapReq; #define sz_xkbGetCompatMapReq 12 typedef struct _xkbGetCompatMapReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD8 groups; CARD8 pad1; CARD16 firstSI; CARD16 nSI; CARD16 nTotalSI; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xkbGetCompatMapReply; #define sz_xkbGetCompatMapReply 32 typedef struct _xkbSetCompatMap { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetCompatMap */ CARD16 length; CARD16 deviceSpec; CARD8 pad1; BOOL recomputeActions; BOOL truncateSI; CARD8 groups; CARD16 firstSI; CARD16 nSI; CARD16 pad2; } xkbSetCompatMapReq; #define sz_xkbSetCompatMapReq 16 typedef struct _xkbGetIndicatorState { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetIndicatorState */ CARD16 length; CARD16 deviceSpec; CARD16 pad1; } xkbGetIndicatorStateReq; #define sz_xkbGetIndicatorStateReq 8 typedef struct _xkbGetIndicatorStateReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD32 state; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xkbGetIndicatorStateReply; #define sz_xkbGetIndicatorStateReply 32 typedef struct _xkbGetIndicatorMap { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetIndicatorMap */ CARD16 length; CARD16 deviceSpec; CARD16 pad; CARD32 which; } xkbGetIndicatorMapReq; #define sz_xkbGetIndicatorMapReq 12 typedef struct _xkbGetIndicatorMapReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD32 which; CARD32 realIndicators; CARD8 nIndicators; CARD8 pad1; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xkbGetIndicatorMapReply; #define sz_xkbGetIndicatorMapReply 32 typedef struct _xkbIndicatorMapWireDesc { CARD8 flags; CARD8 whichGroups; CARD8 groups; CARD8 whichMods; CARD8 mods; CARD8 realMods; CARD16 virtualMods; CARD32 ctrls; } xkbIndicatorMapWireDesc; #define sz_xkbIndicatorMapWireDesc 12 typedef struct _xkbSetIndicatorMap { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetIndicatorMap */ CARD16 length; CARD16 deviceSpec; CARD16 pad1; CARD32 which; } xkbSetIndicatorMapReq; #define sz_xkbSetIndicatorMapReq 12 typedef struct _xkbGetNamedIndicator { CARD8 reqType; CARD8 xkbReqType; /* X_KBGetNamedIndicator */ CARD16 length; CARD16 deviceSpec; CARD16 ledClass; CARD16 ledID; CARD16 pad1; Atom indicator; } xkbGetNamedIndicatorReq; #define sz_xkbGetNamedIndicatorReq 16 typedef struct _xkbGetNamedIndicatorReply { BYTE type; BYTE deviceID; CARD16 sequenceNumber; CARD32 length; Atom indicator; BOOL found; BOOL on; BOOL realIndicator; CARD8 ndx; CARD8 flags; CARD8 whichGroups; CARD8 groups; CARD8 whichMods; CARD8 mods; CARD8 realMods; CARD16 virtualMods; CARD32 ctrls; BOOL supported; CARD8 pad1; CARD16 pad2; } xkbGetNamedIndicatorReply; #define sz_xkbGetNamedIndicatorReply 32 typedef struct _xkbSetNamedIndicator { CARD8 reqType; CARD8 xkbReqType; /* X_KBSetNamedIndicator */ CARD16 length; CARD16 deviceSpec; CARD16 ledClass; CARD16 ledID; CARD16 pad1; Atom indicator; BOOL setState; BOOL on; BOOL setMap; BOOL createMap; CARD8 pad2; CARD8 flags; CARD8 whichGroups; CARD8 groups; CARD8 whichMods; CARD8 realMods; CARD16 virtualMods; CARD32 ctrls; } xkbSetNamedIndicatorReq; #define sz_xkbSetNamedIndicatorReq 32 typedef struct _xkbGetNames { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetNames */ CARD16 length; CARD16 deviceSpec; CARD16 pad; CARD32 which; } xkbGetNamesReq; #define sz_xkbGetNamesReq 12 typedef struct _xkbGetNamesReply { BYTE type; BYTE deviceID; CARD16 sequenceNumber; CARD32 length; CARD32 which; KeyCode minKeyCode; KeyCode maxKeyCode; CARD8 nTypes; CARD8 groupNames; CARD16 virtualMods; KeyCode firstKey; CARD8 nKeys; CARD32 indicators; CARD8 nRadioGroups; CARD8 nKeyAliases; CARD16 nKTLevels; CARD32 pad3; } xkbGetNamesReply; #define sz_xkbGetNamesReply 32 typedef struct _xkbSetNames { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetNames */ CARD16 length; CARD16 deviceSpec; CARD16 virtualMods; CARD32 which; CARD8 firstType; CARD8 nTypes; CARD8 firstKTLevel; CARD8 nKTLevels; CARD32 indicators; CARD8 groupNames; CARD8 nRadioGroups; KeyCode firstKey; CARD8 nKeys; CARD8 nKeyAliases; CARD8 pad1; CARD16 totalKTLevelNames; } xkbSetNamesReq; #define sz_xkbSetNamesReq 28 typedef struct _xkbPointWireDesc { INT16 x; INT16 y; } xkbPointWireDesc; #define sz_xkbPointWireDesc 4 typedef struct _xkbOutlineWireDesc { CARD8 nPoints; CARD8 cornerRadius; CARD16 pad; } xkbOutlineWireDesc; #define sz_xkbOutlineWireDesc 4 typedef struct _xkbShapeWireDesc { Atom name; CARD8 nOutlines; CARD8 primaryNdx; CARD8 approxNdx; CARD8 pad; } xkbShapeWireDesc; #define sz_xkbShapeWireDesc 8 typedef struct _xkbSectionWireDesc { Atom name; INT16 top; INT16 left; CARD16 width; CARD16 height; INT16 angle; CARD8 priority; CARD8 nRows; CARD8 nDoodads; CARD8 nOverlays; CARD16 pad; } xkbSectionWireDesc; #define sz_xkbSectionWireDesc 20 typedef struct _xkbRowWireDesc { INT16 top; INT16 left; CARD8 nKeys; BOOL vertical; CARD16 pad; } xkbRowWireDesc; #define sz_xkbRowWireDesc 8 typedef struct _xkbKeyWireDesc { CARD8 name[XkbKeyNameLength]; INT16 gap; CARD8 shapeNdx; CARD8 colorNdx; } xkbKeyWireDesc; #define sz_xkbKeyWireDesc 8 typedef struct _xkbOverlayWireDesc { Atom name; CARD8 nRows; CARD8 pad1; CARD16 pad2; } xkbOverlayWireDesc; #define sz_xkbOverlayWireDesc 8 typedef struct _xkbOverlayRowWireDesc { CARD8 rowUnder; CARD8 nKeys; CARD16 pad1; } xkbOverlayRowWireDesc; #define sz_xkbOverlayRowWireDesc 4 typedef struct _xkbOverlayKeyWireDesc { CARD8 over[XkbKeyNameLength]; CARD8 under[XkbKeyNameLength]; } xkbOverlayKeyWireDesc; #define sz_xkbOverlayKeyWireDesc 8 typedef struct _xkbShapeDoodadWireDesc { Atom name; CARD8 type; CARD8 priority; INT16 top; INT16 left; INT16 angle; CARD8 colorNdx; CARD8 shapeNdx; CARD16 pad1; CARD32 pad2; } xkbShapeDoodadWireDesc; #define sz_xkbShapeDoodadWireDesc 20 typedef struct _xkbTextDoodadWireDesc { Atom name; CARD8 type; CARD8 priority; INT16 top; INT16 left; INT16 angle; CARD16 width; CARD16 height; CARD8 colorNdx; CARD8 pad1; CARD16 pad2; } xkbTextDoodadWireDesc; #define sz_xkbTextDoodadWireDesc 20 typedef struct _xkbIndicatorDoodadWireDesc { Atom name; CARD8 type; CARD8 priority; INT16 top; INT16 left; INT16 angle; CARD8 shapeNdx; CARD8 onColorNdx; CARD8 offColorNdx; CARD8 pad1; CARD32 pad2; } xkbIndicatorDoodadWireDesc; #define sz_xkbIndicatorDoodadWireDesc 20 typedef struct _xkbLogoDoodadWireDesc { Atom name; CARD8 type; CARD8 priority; INT16 top; INT16 left; INT16 angle; CARD8 colorNdx; CARD8 shapeNdx; CARD16 pad1; CARD32 pad2; } xkbLogoDoodadWireDesc; #define sz_xkbLogoDoodadWireDesc 20 typedef struct _xkbAnyDoodadWireDesc { Atom name; CARD8 type; CARD8 priority; INT16 top; INT16 left; INT16 angle; CARD32 pad2; CARD32 pad3; } xkbAnyDoodadWireDesc; #define sz_xkbAnyDoodadWireDesc 20 typedef union _xkbDoodadWireDesc { xkbAnyDoodadWireDesc any; xkbShapeDoodadWireDesc shape; xkbTextDoodadWireDesc text; xkbIndicatorDoodadWireDesc indicator; xkbLogoDoodadWireDesc logo; } xkbDoodadWireDesc; #define sz_xkbDoodadWireDesc 20 typedef struct _xkbGetGeometry { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetGeometry */ CARD16 length; CARD16 deviceSpec; CARD16 pad; Atom name; } xkbGetGeometryReq; #define sz_xkbGetGeometryReq 12 typedef struct _xkbGetGeometryReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; Atom name; BOOL found; CARD8 pad; CARD16 widthMM; CARD16 heightMM; CARD16 nProperties; CARD16 nColors; CARD16 nShapes; CARD16 nSections; CARD16 nDoodads; CARD16 nKeyAliases; CARD8 baseColorNdx; CARD8 labelColorNdx; } xkbGetGeometryReply; #define sz_xkbGetGeometryReply 32 typedef struct _xkbSetGeometry { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetGeometry */ CARD16 length; CARD16 deviceSpec; CARD8 nShapes; CARD8 nSections; Atom name; CARD16 widthMM; CARD16 heightMM; CARD16 nProperties; CARD16 nColors; CARD16 nDoodads; CARD16 nKeyAliases; CARD8 baseColorNdx; CARD8 labelColorNdx; CARD16 pad; } xkbSetGeometryReq; #define sz_xkbSetGeometryReq 28 typedef struct _xkbPerClientFlags { CARD8 reqType; CARD8 xkbReqType;/* always X_KBPerClientFlags */ CARD16 length; CARD16 deviceSpec; CARD16 pad1; CARD32 change; CARD32 value; CARD32 ctrlsToChange; CARD32 autoCtrls; CARD32 autoCtrlValues; } xkbPerClientFlagsReq; #define sz_xkbPerClientFlagsReq 28 typedef struct _xkbPerClientFlagsReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD32 supported; CARD32 value; CARD32 autoCtrls; CARD32 autoCtrlValues; CARD32 pad1; CARD32 pad2; } xkbPerClientFlagsReply; #define sz_xkbPerClientFlagsReply 32 typedef struct _xkbListComponents { CARD8 reqType; CARD8 xkbReqType; /* always X_KBListComponents */ CARD16 length; CARD16 deviceSpec; CARD16 maxNames; } xkbListComponentsReq; #define sz_xkbListComponentsReq 8 typedef struct _xkbListComponentsReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD16 nKeymaps; CARD16 nKeycodes; CARD16 nTypes; CARD16 nCompatMaps; CARD16 nSymbols; CARD16 nGeometries; CARD16 extra; CARD16 pad1; CARD32 pad2; CARD32 pad3; } xkbListComponentsReply; #define sz_xkbListComponentsReply 32 typedef struct _xkbGetKbdByName { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetKbdByName */ CARD16 length; CARD16 deviceSpec; CARD16 need; /* combination of XkbGBN_* */ CARD16 want; /* combination of XkbGBN_* */ BOOL load; CARD8 pad; } xkbGetKbdByNameReq; #define sz_xkbGetKbdByNameReq 12 typedef struct _xkbGetKbdByNameReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; KeyCode minKeyCode; KeyCode maxKeyCode; BOOL loaded; BOOL newKeyboard; CARD16 found; /* combination of XkbGBN_* */ CARD16 reported; /* combination of XkbAllComponents */ CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xkbGetKbdByNameReply; #define sz_xkbGetKbdByNameReply 32 typedef struct _xkbDeviceLedsWireDesc { CARD16 ledClass; CARD16 ledID; CARD32 namesPresent; CARD32 mapsPresent; CARD32 physIndicators; CARD32 state; } xkbDeviceLedsWireDesc; #define sz_xkbDeviceLedsWireDesc 20 typedef struct _xkbGetDeviceInfo { CARD8 reqType; CARD8 xkbReqType; /* always X_KBGetDeviceInfo */ CARD16 length; CARD16 deviceSpec; CARD16 wanted; BOOL allBtns; CARD8 firstBtn; CARD8 nBtns; CARD8 pad; CARD16 ledClass; CARD16 ledID; } xkbGetDeviceInfoReq; #define sz_xkbGetDeviceInfoReq 16 typedef struct _xkbGetDeviceInfoReply { CARD8 type; /* always X_Reply */ CARD8 deviceID; CARD16 sequenceNumber; CARD32 length; CARD16 present; CARD16 supported; CARD16 unsupported; CARD16 nDeviceLedFBs; CARD8 firstBtnWanted; CARD8 nBtnsWanted; CARD8 firstBtnRtrn; CARD8 nBtnsRtrn; CARD8 totalBtns; BOOL hasOwnState; CARD16 dfltKbdFB; CARD16 dfltLedFB; CARD16 pad; Atom devType; } xkbGetDeviceInfoReply; #define sz_xkbGetDeviceInfoReply 32 typedef struct _xkbSetDeviceInfo { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetDeviceInfo */ CARD16 length; CARD16 deviceSpec; CARD8 firstBtn; CARD8 nBtns; CARD16 change; CARD16 nDeviceLedFBs; } xkbSetDeviceInfoReq; #define sz_xkbSetDeviceInfoReq 12 typedef struct _xkbSetDebuggingFlags { CARD8 reqType; CARD8 xkbReqType; /* always X_KBSetDebuggingFlags */ CARD16 length; CARD16 msgLength; CARD16 pad; CARD32 affectFlags; CARD32 flags; CARD32 affectCtrls; CARD32 ctrls; } xkbSetDebuggingFlagsReq; #define sz_xkbSetDebuggingFlagsReq 24 typedef struct _xkbSetDebuggingFlagsReply { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 currentFlags; CARD32 currentCtrls; CARD32 supportedFlags; CARD32 supportedCtrls; CARD32 pad1; CARD32 pad2; } xkbSetDebuggingFlagsReply; #define sz_xkbSetDebuggingFlagsReply 32 /* * X KEYBOARD EXTENSION EVENT STRUCTURES */ typedef struct _xkbAnyEvent { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 pad1; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xkbAnyEvent; #define sz_xkbAnyEvent 32 typedef struct _xkbNewKeyboardNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 oldDeviceID; KeyCode minKeyCode; KeyCode maxKeyCode; KeyCode oldMinKeyCode; KeyCode oldMaxKeyCode; CARD8 requestMajor; CARD8 requestMinor; CARD16 changed; CARD8 detail; CARD8 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xkbNewKeyboardNotify; #define sz_xkbNewKeyboardNotify 32 typedef struct _xkbMapNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 ptrBtnActions; CARD16 changed; KeyCode minKeyCode; KeyCode maxKeyCode; CARD8 firstType; CARD8 nTypes; KeyCode firstKeySym; CARD8 nKeySyms; KeyCode firstKeyAct; CARD8 nKeyActs; KeyCode firstKeyBehavior; CARD8 nKeyBehaviors; KeyCode firstKeyExplicit; CARD8 nKeyExplicit; KeyCode firstModMapKey; CARD8 nModMapKeys; KeyCode firstVModMapKey; CARD8 nVModMapKeys; CARD16 virtualMods; CARD16 pad1; } xkbMapNotify; #define sz_xkbMapNotify 32 typedef struct _xkbStateNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 mods; CARD8 baseMods; CARD8 latchedMods; CARD8 lockedMods; CARD8 group; INT16 baseGroup; INT16 latchedGroup; CARD8 lockedGroup; CARD8 compatState; CARD8 grabMods; CARD8 compatGrabMods; CARD8 lookupMods; CARD8 compatLookupMods; CARD16 ptrBtnState; CARD16 changed; KeyCode keycode; CARD8 eventType; CARD8 requestMajor; CARD8 requestMinor; } xkbStateNotify; #define sz_xkbStateNotify 32 typedef struct _xkbControlsNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 numGroups; CARD16 pad1; CARD32 changedControls; CARD32 enabledControls; CARD32 enabledControlChanges; KeyCode keycode; CARD8 eventType; CARD8 requestMajor; CARD8 requestMinor; CARD32 pad2; } xkbControlsNotify; #define sz_xkbControlsNotify 32 typedef struct _xkbIndicatorNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 pad1; CARD16 pad2; CARD32 state; CARD32 changed; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xkbIndicatorNotify; #define sz_xkbIndicatorNotify 32 typedef struct _xkbNamesNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 pad1; CARD16 changed; CARD8 firstType; CARD8 nTypes; CARD8 firstLevelName; CARD8 nLevelNames; CARD8 pad2; CARD8 nRadioGroups; CARD8 nAliases; CARD8 changedGroupNames; CARD16 changedVirtualMods; CARD8 firstKey; CARD8 nKeys; CARD32 changedIndicators; CARD32 pad3; } xkbNamesNotify; #define sz_xkbNamesNotify 32 typedef struct _xkbCompatMapNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 changedGroups; CARD16 firstSI; CARD16 nSI; CARD16 nTotalSI; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xkbCompatMapNotify; #define sz_xkbCompatMapNotify 32 typedef struct _xkbBellNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 bellClass; CARD8 bellID; CARD8 percent; CARD16 pitch; CARD16 duration; Atom name; Window window; BOOL eventOnly; CARD8 pad1; CARD16 pad2; CARD32 pad3; } xkbBellNotify; #define sz_xkbBellNotify 32 typedef struct _xkbActionMessage { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; KeyCode keycode; BOOL press; BOOL keyEventFollows; CARD8 mods; CARD8 group; CARD8 message[8]; CARD16 pad1; CARD32 pad2; CARD32 pad3; } xkbActionMessage; #define sz_xkbActionMessage 32 typedef struct _xkbAccessXNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; KeyCode keycode; CARD16 detail; CARD16 slowKeysDelay; CARD16 debounceDelay; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xkbAccessXNotify; #define sz_xkbAccessXNotify 32 typedef struct _xkbExtensionDeviceNotify { BYTE type; BYTE xkbType; CARD16 sequenceNumber; Time time; CARD8 deviceID; CARD8 pad1; CARD16 reason; CARD16 ledClass; CARD16 ledID; CARD32 ledsDefined; CARD32 ledState; CARD8 firstBtn; CARD8 nBtns; CARD16 supported; CARD16 unsupported; CARD16 pad3; } xkbExtensionDeviceNotify; #define sz_xkbExtensionDeviceNotify 32 typedef struct _xkbEvent { union { xkbAnyEvent any; xkbNewKeyboardNotify new_kbd; xkbMapNotify map; xkbStateNotify state; xkbControlsNotify ctrls; xkbIndicatorNotify indicators; xkbNamesNotify names; xkbCompatMapNotify compat; xkbBellNotify bell; xkbActionMessage message; xkbAccessXNotify accessx; xkbExtensionDeviceNotify device; } u; } xkbEvent; #define sz_xkbEvent 32 #undef Window #undef Atom #undef Time #undef KeyCode #undef KeySym #endif /* _XKBPROTO_H_ */ X11/extensions/xf86bigfstr.h000064400000000277151027430550011651 0ustar00#warning "xf86bigfstr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/extensions/XvMCproto.h000064400000010604151027430550011371 0ustar00#ifndef _XVMCPROTO_H_ #define _XVMCPROTO_H_ #define xvmc_QueryVersion 0 #define xvmc_ListSurfaceTypes 1 #define xvmc_CreateContext 2 #define xvmc_DestroyContext 3 #define xvmc_CreateSurface 4 #define xvmc_DestroySurface 5 #define xvmc_CreateSubpicture 6 #define xvmc_DestroySubpicture 7 #define xvmc_ListSubpictureTypes 8 #define xvmc_GetDRInfo 9 #define xvmc_LastRequest xvmc_GetDRInfo #define xvmcNumRequest (xvmc_LastRequest + 1) typedef struct { CARD32 surface_type_id; CARD16 chroma_format; CARD16 pad0; CARD16 max_width; CARD16 max_height; CARD16 subpicture_max_width; CARD16 subpicture_max_height; CARD32 mc_type; CARD32 flags; } xvmcSurfaceInfo; #define sz_xvmcSurfaceInfo 24; typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; } xvmcQueryVersionReq; #define sz_xvmcQueryVersionReq 4; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 major; CARD32 minor; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; } xvmcQueryVersionReply; #define sz_xvmcQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 port; } xvmcListSurfaceTypesReq; #define sz_xvmcListSurfaceTypesReq 8; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 num; CARD32 padl3; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; } xvmcListSurfaceTypesReply; #define sz_xvmcListSurfaceTypesReply 32 typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 context_id; CARD32 port; CARD32 surface_type_id; CARD16 width; CARD16 height; CARD32 flags; } xvmcCreateContextReq; #define sz_xvmcCreateContextReq 24; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD16 width_actual; CARD16 height_actual; CARD32 flags_return; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; } xvmcCreateContextReply; #define sz_xvmcCreateContextReply 32 typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 context_id; } xvmcDestroyContextReq; #define sz_xvmcDestroyContextReq 8; typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 surface_id; CARD32 context_id; } xvmcCreateSurfaceReq; #define sz_xvmcCreateSurfaceReq 12; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 padl2; CARD32 padl3; CARD32 padl4; CARD32 padl5; CARD32 padl6; CARD32 padl7; } xvmcCreateSurfaceReply; #define sz_xvmcCreateSurfaceReply 32 typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 surface_id; } xvmcDestroySurfaceReq; #define sz_xvmcDestroySurfaceReq 8; typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 subpicture_id; CARD32 context_id; CARD32 xvimage_id; CARD16 width; CARD16 height; } xvmcCreateSubpictureReq; #define sz_xvmcCreateSubpictureReq 20; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD16 width_actual; CARD16 height_actual; CARD16 num_palette_entries; CARD16 entry_bytes; CARD8 component_order[4]; CARD32 padl5; CARD32 padl6; CARD32 padl7; } xvmcCreateSubpictureReply; #define sz_xvmcCreateSubpictureReply 32 typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 subpicture_id; } xvmcDestroySubpictureReq; #define sz_xvmcDestroySubpictureReq 8; typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 port; CARD32 surface_type_id; } xvmcListSubpictureTypesReq; #define sz_xvmcListSubpictureTypesReq 12; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 num; CARD32 padl2; CARD32 padl3; CARD32 padl4; CARD32 padl5; CARD32 padl6; } xvmcListSubpictureTypesReply; #define sz_xvmcListSubpictureTypesReply 32 typedef struct { CARD8 reqType; CARD8 xvmcReqType; CARD16 length; CARD32 port; CARD32 shmKey; CARD32 magic; } xvmcGetDRInfoReq; #define sz_xvmcGetDRInfoReq 16; typedef struct { BYTE type; /* X_Reply */ BYTE padb1; CARD16 sequenceNumber; CARD32 length; CARD32 major; CARD32 minor; CARD32 patchLevel; CARD32 nameLen; CARD32 busIDLen; CARD32 isLocal; } xvmcGetDRInfoReply; #define sz_xvmcGetDRInfoReply 32 #endif X11/extensions/panoramiXproto.h000064400000012541151027430550012514 0ustar00/***************************************************************** Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING, BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Digital Equipment Corporation shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Digital Equipment Corporation. ******************************************************************/ /* THIS IS NOT AN X PROJECT TEAM SPECIFICATION */ #ifndef _PANORAMIXPROTO_H_ #define _PANORAMIXPROTO_H_ #define PANORAMIX_MAJOR_VERSION 1 /* current version number */ #define PANORAMIX_MINOR_VERSION 1 #define PANORAMIX_PROTOCOL_NAME "XINERAMA" #define X_PanoramiXQueryVersion 0 #define X_PanoramiXGetState 1 #define X_PanoramiXGetScreenCount 2 #define X_PanoramiXGetScreenSize 3 #define X_XineramaIsActive 4 #define X_XineramaQueryScreens 5 typedef struct _PanoramiXQueryVersion { CARD8 reqType; /* always PanoramiXReqCode */ CARD8 panoramiXReqType; /* always X_PanoramiXQueryVersion */ CARD16 length; CARD8 clientMajor; CARD8 clientMinor; CARD16 unused; } xPanoramiXQueryVersionReq; #define sz_xPanoramiXQueryVersionReq 8 typedef struct { CARD8 type; /* must be X_Reply */ CARD8 pad1; /* unused */ CARD16 sequenceNumber; /* last sequence number */ CARD32 length; /* 0 */ CARD16 majorVersion; CARD16 minorVersion; CARD32 pad2; /* unused */ CARD32 pad3; /* unused */ CARD32 pad4; /* unused */ CARD32 pad5; /* unused */ CARD32 pad6; /* unused */ } xPanoramiXQueryVersionReply; #define sz_xPanoramiXQueryVersionReply 32 typedef struct _PanoramiXGetState { CARD8 reqType; /* always PanoramiXReqCode */ CARD8 panoramiXReqType; /* always X_PanoramiXGetState */ CARD16 length; CARD32 window; } xPanoramiXGetStateReq; #define sz_xPanoramiXGetStateReq 8 typedef struct { BYTE type; BYTE state; CARD16 sequenceNumber; CARD32 length; CARD32 window; CARD32 pad1; /* unused */ CARD32 pad2; /* unused */ CARD32 pad3; /* unused */ CARD32 pad4; /* unused */ CARD32 pad5; /* unused */ } xPanoramiXGetStateReply; #define sz_panoramiXGetStateReply 32 typedef struct _PanoramiXGetScreenCount { CARD8 reqType; /* always PanoramiXReqCode */ CARD8 panoramiXReqType; /* always X_PanoramiXGetScreenCount */ CARD16 length; CARD32 window; } xPanoramiXGetScreenCountReq; #define sz_xPanoramiXGetScreenCountReq 8 typedef struct { BYTE type; BYTE ScreenCount; CARD16 sequenceNumber; CARD32 length; CARD32 window; CARD32 pad1; /* unused */ CARD32 pad2; /* unused */ CARD32 pad3; /* unused */ CARD32 pad4; /* unused */ CARD32 pad5; /* unused */ } xPanoramiXGetScreenCountReply; #define sz_panoramiXGetScreenCountReply 32 typedef struct _PanoramiXGetScreenSize { CARD8 reqType; /* always PanoramiXReqCode */ CARD8 panoramiXReqType; /* always X_PanoramiXGetState */ CARD16 length; CARD32 window; CARD32 screen; } xPanoramiXGetScreenSizeReq; #define sz_xPanoramiXGetScreenSizeReq 12 typedef struct { BYTE type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 width; CARD32 height; CARD32 window; CARD32 screen; CARD32 pad2; /* unused */ CARD32 pad3; /* unused */ } xPanoramiXGetScreenSizeReply; #define sz_panoramiXGetScreenSizeReply 32 /************ Alternate protocol ******************/ typedef struct { CARD8 reqType; CARD8 panoramiXReqType; CARD16 length; } xXineramaIsActiveReq; #define sz_xXineramaIsActiveReq 4 typedef struct { BYTE type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 state; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXineramaIsActiveReply; #define sz_XineramaIsActiveReply 32 typedef struct { CARD8 reqType; CARD8 panoramiXReqType; CARD16 length; } xXineramaQueryScreensReq; #define sz_xXineramaQueryScreensReq 4 typedef struct { BYTE type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 number; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXineramaQueryScreensReply; #define sz_XineramaQueryScreensReply 32 typedef struct { INT16 x_org; INT16 y_org; CARD16 width; CARD16 height; } xXineramaScreenInfo; #define sz_XineramaScreenInfo 8 #endif X11/extensions/xf86dgastr.h000064400000000274151027430550011472 0ustar00#warning "xf86dgastr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/extensions/xcmiscproto.h000064400000005761151027430550012052 0ustar00/* Copyright 1993, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _XCMISCPROTO_H_ #define _XCMISCPROTO_H_ #define X_XCMiscGetVersion 0 #define X_XCMiscGetXIDRange 1 #define X_XCMiscGetXIDList 2 #define XCMiscNumberEvents 0 #define XCMiscNumberErrors 0 #define XCMiscMajorVersion 1 #define XCMiscMinorVersion 1 #define XCMiscExtensionName "XC-MISC" typedef struct { CARD8 reqType; /* always XCMiscCode */ CARD8 miscReqType; /* always X_XCMiscGetVersion */ CARD16 length; CARD16 majorVersion; CARD16 minorVersion; } xXCMiscGetVersionReq; #define sz_xXCMiscGetVersionReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; CARD16 minorVersion; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXCMiscGetVersionReply; #define sz_xXCMiscGetVersionReply 32 typedef struct { CARD8 reqType; /* always XCMiscCode */ CARD8 miscReqType; /* always X_XCMiscGetXIDRange */ CARD16 length; } xXCMiscGetXIDRangeReq; #define sz_xXCMiscGetXIDRangeReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 start_id; CARD32 count; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xXCMiscGetXIDRangeReply; #define sz_xXCMiscGetXIDRangeReply 32 typedef struct { CARD8 reqType; /* always XCMiscCode */ CARD8 miscReqType; /* always X_XCMiscGetXIDList */ CARD16 length; CARD32 count; /* number of IDs requested */ } xXCMiscGetXIDListReq; #define sz_xXCMiscGetXIDListReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 count; /* number of IDs requested */ CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXCMiscGetXIDListReply; #define sz_xXCMiscGetXIDListReply 32 #endif /* _XCMISCPROTO_H_ */ X11/extensions/geproto.h000064400000004457151027430550011160 0ustar00/* * Copyright © 2007-2008 Peter Hutterer * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: Peter Hutterer, University of South Australia, NICTA * */ #ifndef _GEPROTO_H_ #define _GEPROTO_H_ #include #include #include /********************************************************* * * Protocol request constants * */ #define X_GEGetExtensionVersion 1 /********************************************************* * * XGE protocol requests/replies * */ /* generic request */ typedef struct { CARD8 reqType; CARD8 ReqType; CARD16 length; } xGEReq; /* QueryVersion */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GEQueryVersion */ CARD16 length; CARD16 majorVersion; CARD16 minorVersion; } xGEQueryVersionReq; #define sz_xGEQueryVersionReq 8 typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GEQueryVersion */ CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; CARD16 minorVersion; CARD32 pad00; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; } xGEQueryVersionReply; #define sz_xGEQueryVersionReply 32 #endif /* _GEPROTO_H_ */ X11/extensions/XKBsrv.h000064400000066562151027430550010665 0ustar00/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XKBSRV_H_ #define _XKBSRV_H_ #ifdef XKB_IN_SERVER #define XkbAllocClientMap SrvXkbAllocClientMap #define XkbAllocServerMap SrvXkbAllocServerMap #define XkbChangeTypesOfKey SrvXkbChangeTypesOfKey #define XkbAddKeyType SrvXkbAddKeyType #define XkbCopyKeyType SrvXkbCopyKeyType #define XkbCopyKeyTypes SrvXkbCopyKeyTypes #define XkbFreeClientMap SrvXkbFreeClientMap #define XkbFreeServerMap SrvXkbFreeServerMap #define XkbInitCanonicalKeyTypes SrvXkbInitCanonicalKeyTypes #define XkbKeyTypesForCoreSymbols SrvXkbKeyTypesForCoreSymbols #define XkbApplyCompatMapToKey SrvXkbApplyCompatMapToKey #define XkbUpdateMapFromCore SrvXkbUpdateMapFromCore #define XkbResizeKeyActions SrvXkbResizeKeyActions #define XkbResizeKeySyms SrvXkbResizeKeySyms #define XkbResizeKeyType SrvXkbResizeKeyType #define XkbAllocCompatMap SrvXkbAllocCompatMap #define XkbAllocControls SrvXkbAllocControls #define XkbAllocIndicatorMaps SrvXkbAllocIndicatorMaps #define XkbAllocKeyboard SrvXkbAllocKeyboard #define XkbAllocNames SrvXkbAllocNames #define XkbFreeCompatMap SrvXkbFreeCompatMap #define XkbFreeControls SrvXkbFreeControls #define XkbFreeIndicatorMaps SrvXkbFreeIndicatorMaps #define XkbFreeKeyboard SrvXkbFreeKeyboard #define XkbFreeNames SrvXkbFreeNames #define XkbAddDeviceLedInfo SrvXkbAddDeviceLedInfo #define XkbAllocDeviceInfo SrvXkbAllocDeviceInfo #define XkbFreeDeviceInfo SrvXkbFreeDeviceInfo #define XkbResizeDeviceButtonActions SrvXkbResizeDeviceButtonActions #define XkbLatchModifiers SrvXkbLatchModifiers #define XkbLatchGroup SrvXkbLatchGroup #define XkbVirtualModsToReal SrvXkbVirtualModsToReal #define XkbChangeKeycodeRange SrvXkbChangeKeycodeRange #define XkbApplyVirtualModChanges SrvXkbApplyVirtualModChanges #define XkbUpdateActionVirtualMods SrvXkbUpdateActionVirtualMods #define XkbUpdateKeyTypeVirtualMods SrvXkbUpdateKeyTypeVirtualMods #endif #include #include #include "inputstr.h" typedef struct _XkbInterest { DeviceIntPtr dev; ClientPtr client; XID resource; struct _XkbInterest * next; CARD16 extDevNotifyMask; CARD16 stateNotifyMask; CARD16 namesNotifyMask; CARD32 ctrlsNotifyMask; CARD8 compatNotifyMask; BOOL bellNotifyMask; BOOL actionMessageMask; CARD16 accessXNotifyMask; CARD32 iStateNotifyMask; CARD32 iMapNotifyMask; CARD16 altSymsNotifyMask; CARD32 autoCtrls; CARD32 autoCtrlValues; } XkbInterestRec,*XkbInterestPtr; typedef struct _XkbRadioGroup { CARD8 flags; CARD8 nMembers; CARD8 dfltDown; CARD8 currentDown; CARD8 members[XkbRGMaxMembers]; } XkbRadioGroupRec, *XkbRadioGroupPtr; typedef struct _XkbEventCause { CARD8 kc; CARD8 event; CARD8 mjr; CARD8 mnr; ClientPtr client; } XkbEventCauseRec,*XkbEventCausePtr; #define XkbSetCauseKey(c,k,e) { (c)->kc= (k),(c)->event= (e),\ (c)->mjr= (c)->mnr= 0; \ (c)->client= NULL; } #define XkbSetCauseReq(c,j,n,cl) { (c)->kc= (c)->event= 0,\ (c)->mjr= (j),(c)->mnr= (n);\ (c)->client= (cl); } #define XkbSetCauseCoreReq(c,e,cl) XkbSetCauseReq(c,e,0,cl) #define XkbSetCauseXkbReq(c,e,cl) XkbSetCauseReq(c,XkbReqCode,e,cl) #define XkbSetCauseUnknown(c) XkbSetCauseKey(c,0,0) #define _OFF_TIMER 0 #define _KRG_WARN_TIMER 1 #define _KRG_TIMER 2 #define _SK_TIMEOUT_TIMER 3 #define _ALL_TIMEOUT_TIMER 4 #define _BEEP_NONE 0 #define _BEEP_FEATURE_ON 1 #define _BEEP_FEATURE_OFF 2 #define _BEEP_FEATURE_CHANGE 3 #define _BEEP_SLOW_WARN 4 #define _BEEP_SLOW_PRESS 5 #define _BEEP_SLOW_ACCEPT 6 #define _BEEP_SLOW_REJECT 7 #define _BEEP_SLOW_RELEASE 8 #define _BEEP_STICKY_LATCH 9 #define _BEEP_STICKY_LOCK 10 #define _BEEP_STICKY_UNLOCK 11 #define _BEEP_LED_ON 12 #define _BEEP_LED_OFF 13 #define _BEEP_LED_CHANGE 14 #define _BEEP_BOUNCE_REJECT 15 typedef struct _XkbSrvInfo { XkbStateRec prev_state; XkbStateRec state; XkbDescPtr desc; DeviceIntPtr device; KbdCtrlProcPtr kbdProc; XkbRadioGroupPtr radioGroups; CARD8 nRadioGroups; CARD8 clearMods; CARD8 setMods; INT16 groupChange; CARD16 dfltPtrDelta; double mouseKeysCurve; double mouseKeysCurveFactor; INT16 mouseKeysDX; INT16 mouseKeysDY; CARD8 mouseKeysFlags; Bool mouseKeysAccel; CARD8 mouseKeysCounter; CARD8 lockedPtrButtons; CARD8 shiftKeyCount; KeyCode mouseKey; KeyCode inactiveKey; KeyCode slowKey; KeyCode repeatKey; CARD8 krgTimerActive; CARD8 beepType; CARD8 beepCount; CARD32 flags; CARD32 lastPtrEventTime; CARD32 lastShiftEventTime; OsTimerPtr beepTimer; OsTimerPtr mouseKeyTimer; OsTimerPtr slowKeysTimer; OsTimerPtr bounceKeysTimer; OsTimerPtr repeatKeyTimer; OsTimerPtr krgTimer; } XkbSrvInfoRec, *XkbSrvInfoPtr; #define XkbSLI_IsDefault (1L<<0) #define XkbSLI_HasOwnState (1L<<1) typedef struct _XkbSrvLedInfo { CARD16 flags; CARD16 class; CARD16 id; union { KbdFeedbackPtr kf; LedFeedbackPtr lf; } fb; CARD32 physIndicators; CARD32 autoState; CARD32 explicitState; CARD32 effectiveState; CARD32 mapsPresent; CARD32 namesPresent; XkbIndicatorMapPtr maps; Atom * names; CARD32 usesBase; CARD32 usesLatched; CARD32 usesLocked; CARD32 usesEffective; CARD32 usesCompat; CARD32 usesControls; CARD32 usedComponents; } XkbSrvLedInfoRec, *XkbSrvLedInfoPtr; /* * Settings for xkbClientFlags field (used by DIX) * These flags _must_ not overlap with XkbPCF_* */ #define _XkbClientInitialized (1<<15) #define _XkbWantsDetectableAutoRepeat(c)\ ((c)->xkbClientFlags&XkbPCF_DetectableAutoRepeatMask) /* * Settings for flags field */ #define _XkbStateNotifyInProgress (1<<0) typedef struct { ProcessInputProc processInputProc; ProcessInputProc realInputProc; DeviceUnwrapProc unwrapProc; } xkbDeviceInfoRec, *xkbDeviceInfoPtr; #define WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \ device->public.processInputProc = proc; \ oldprocs->processInputProc = \ oldprocs->realInputProc = device->public.realInputProc; \ device->public.realInputProc = proc; \ oldprocs->unwrapProc = device->unwrapProc; \ device->unwrapProc = unwrapproc; #define COND_WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \ if (device->public.processInputProc == device->public.realInputProc)\ device->public.processInputProc = proc; \ oldprocs->processInputProc = \ oldprocs->realInputProc = device->public.realInputProc; \ device->public.realInputProc = proc; \ oldprocs->unwrapProc = device->unwrapProc; \ device->unwrapProc = unwrapproc; #define UNWRAP_PROCESS_INPUT_PROC(device, oldprocs) \ device->public.processInputProc = oldprocs->processInputProc; \ device->public.realInputProc = oldprocs->realInputProc; \ device->unwrapProc = oldprocs->unwrapProc; #define XKBDEVICEINFO(dev) ((xkbDeviceInfoPtr) (dev)->devPrivates[xkbDevicePrivateIndex].ptr) /***====================================================================***/ /***====================================================================***/ #define XkbAX_KRGMask (XkbSlowKeysMask|XkbBounceKeysMask) #define XkbAllFilteredEventsMask \ (XkbAccessXKeysMask|XkbRepeatKeysMask|XkbMouseKeysAccelMask|XkbAX_KRGMask) /***====================================================================***/ extern int XkbReqCode; extern int XkbEventBase; extern int XkbKeyboardErrorCode; extern int XkbDisableLockActions; extern char * XkbBaseDirectory; extern char * XkbBinDirectory; extern char * XkbInitialMap; extern int _XkbClientMajor; extern int _XkbClientMinor; extern unsigned int XkbXIUnsupported; extern char * XkbModelUsed,*XkbLayoutUsed,*XkbVariantUsed,*XkbOptionsUsed; extern Bool noXkbExtension; extern Bool XkbWantRulesProp; extern pointer XkbLastRepeatEvent; extern CARD32 xkbDebugFlags; extern CARD32 xkbDebugCtrls; #define _XkbAlloc(s) xalloc((s)) #define _XkbCalloc(n,s) Xcalloc((n)*(s)) #define _XkbRealloc(o,s) Xrealloc((o),(s)) #define _XkbTypedAlloc(t) ((t *)xalloc(sizeof(t))) #define _XkbTypedCalloc(n,t) ((t *)Xcalloc((n)*sizeof(t))) #define _XkbTypedRealloc(o,n,t) \ ((o)?(t *)Xrealloc((o),(n)*sizeof(t)):_XkbTypedCalloc(n,t)) #define _XkbClearElems(a,f,l,t) bzero(&(a)[f],((l)-(f)+1)*sizeof(t)) #define _XkbFree(p) Xfree(p) #define _XkbLibError(c,l,d) \ { _XkbErrCode= (c); _XkbErrLocation= (l); _XkbErrData= (d); } #define _XkbErrCode2(a,b) ((XID)((((unsigned int)(a))<<24)|((b)&0xffffff))) #define _XkbErrCode3(a,b,c) _XkbErrCode2(a,(((unsigned int)(b))<<16)|(c)) #define _XkbErrCode4(a,b,c,d) _XkbErrCode3(a,b,((((unsigned int)(c))<<8)|(d))) extern int DeviceKeyPress,DeviceKeyRelease; extern int DeviceButtonPress,DeviceButtonRelease; #ifdef XINPUT #define _XkbIsPressEvent(t) (((t)==KeyPress)||((t)==DeviceKeyPress)) #define _XkbIsReleaseEvent(t) (((t)==KeyRelease)||((t)==DeviceKeyRelease)) #else #define _XkbIsPressEvent(t) ((t)==KeyPress) #define _XkbIsReleaseEvent(t) ((t)==KeyRelease) #endif #define _XkbCoreKeycodeInRange(c,k) (((k)>=(c)->curKeySyms.minKeyCode)&&\ ((k)<=(c)->curKeySyms.maxKeyCode)) #define _XkbCoreNumKeys(c) ((c)->curKeySyms.maxKeyCode-\ (c)->curKeySyms.minKeyCode+1) #define XConvertCase(s,l,u) XkbConvertCase(s,l,u) #undef IsKeypadKey #define IsKeypadKey(s) XkbKSIsKeypad(s) typedef int Status; typedef pointer XPointer; typedef struct _XDisplay Display; #ifndef True #define True 1 #define False 0 #endif #ifndef PATH_MAX #ifdef MAXPATHLEN #define PATH_MAX MAXPATHLEN #else #define PATH_MAX 1024 #endif #endif _XFUNCPROTOBEGIN extern void XkbUseMsg( void ); extern int XkbProcessArguments( int /* argc */, char ** /* argv */, int /* i */ ); extern void XkbSetExtension(DeviceIntPtr device, ProcessInputProc proc); extern void XkbFreeCompatMap( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeMap */ ); extern void XkbFreeNames( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeMap */ ); extern DeviceIntPtr _XkbLookupAnyDevice( int /* id */, int * /* why_rtrn */ ); extern DeviceIntPtr _XkbLookupKeyboard( int /* id */, int * /* why_rtrn */ ); extern DeviceIntPtr _XkbLookupBellDevice( int /* id */, int * /* why_rtrn */ ); extern DeviceIntPtr _XkbLookupLedDevice( int /* id */, int * /* why_rtrn */ ); extern DeviceIntPtr _XkbLookupButtonDevice( int /* id */, int * /* why_rtrn */ ); extern XkbDescPtr XkbAllocKeyboard( void ); extern Status XkbAllocClientMap( XkbDescPtr /* xkb */, unsigned int /* which */, unsigned int /* nTypes */ ); extern Status XkbAllocServerMap( XkbDescPtr /* xkb */, unsigned int /* which */, unsigned int /* nNewActions */ ); extern void XkbFreeClientMap( XkbDescPtr /* xkb */, unsigned int /* what */, Bool /* freeMap */ ); extern void XkbFreeServerMap( XkbDescPtr /* xkb */, unsigned int /* what */, Bool /* freeMap */ ); extern Status XkbAllocIndicatorMaps( XkbDescPtr /* xkb */ ); extern Status XkbAllocCompatMap( XkbDescPtr /* xkb */, unsigned int /* which */, unsigned int /* nInterpret */ ); extern Status XkbAllocNames( XkbDescPtr /* xkb */, unsigned int /* which */, int /* nTotalRG */, int /* nTotalAliases */ ); extern Status XkbAllocControls( XkbDescPtr /* xkb */, unsigned int /* which*/ ); extern Status XkbCopyKeyType( XkbKeyTypePtr /* from */, XkbKeyTypePtr /* into */ ); extern Status XkbCopyKeyTypes( XkbKeyTypePtr /* from */, XkbKeyTypePtr /* into */, int /* num_types */ ); extern Status XkbResizeKeyType( XkbDescPtr /* xkb */, int /* type_ndx */, int /* map_count */, Bool /* want_preserve */, int /* new_num_lvls */ ); extern void XkbFreeKeyboard( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeDesc */ ); extern void XkbSetActionKeyMods( XkbDescPtr /* xkb */, XkbAction * /* act */, unsigned int /* mods */ ); extern Bool XkbCheckActionVMods( XkbDescPtr /* xkb */, XkbAction * /* act */, unsigned int /* changed */ ); extern Bool XkbApplyVModChanges( XkbSrvInfoPtr /* xkbi */, unsigned int /* changed */, XkbChangesPtr /* pChanges */, unsigned int * /* needChecksRtrn */, XkbEventCausePtr /* cause */ ); extern void XkbApplyVModChangesToAllDevices( DeviceIntPtr /* dev */, XkbDescPtr /* xkb */, unsigned int /* changed */, XkbEventCausePtr /* cause */ ); extern unsigned int XkbMaskForVMask( XkbDescPtr /* xkb */, unsigned int /* vmask */ ); extern Bool XkbVirtualModsToReal( XkbDescPtr /* xkb */, unsigned int /* virtua_mask */, unsigned int * /* mask_rtrn */ ); extern unsigned int XkbAdjustGroup( int /* group */, XkbControlsPtr /* ctrls */ ); extern KeySym *XkbResizeKeySyms( XkbDescPtr /* xkb */, int /* key */, int /* needed */ ); extern XkbAction *XkbResizeKeyActions( XkbDescPtr /* xkb */, int /* key */, int /* needed */ ); extern void XkbUpdateKeyTypesFromCore( DeviceIntPtr /* pXDev */, KeyCode /* first */, CARD8 /* num */, XkbChangesPtr /* pChanges */ ); extern void XkbUpdateDescActions( XkbDescPtr /* xkb */, KeyCode /* first */, CARD8 /* num */, XkbChangesPtr /* changes */ ); extern void XkbUpdateActions( DeviceIntPtr /* pXDev */, KeyCode /* first */, CARD8 /* num */, XkbChangesPtr /* pChanges */, unsigned int * /* needChecksRtrn */, XkbEventCausePtr /* cause */ ); extern void XkbUpdateCoreDescription( DeviceIntPtr /* keybd */, Bool /* resize */ ); extern void XkbApplyMappingChange( DeviceIntPtr /* pXDev */, CARD8 /* request */, KeyCode /* firstKey */, CARD8 /* num */, ClientPtr /* client */ ); extern void XkbSetIndicators( DeviceIntPtr /* pXDev */, CARD32 /* affect */, CARD32 /* values */, XkbEventCausePtr /* cause */ ); extern void XkbUpdateIndicators( DeviceIntPtr /* keybd */, CARD32 /* changed */, Bool /* check_edevs */, XkbChangesPtr /* pChanges */, XkbEventCausePtr /* cause */ ); extern XkbSrvLedInfoPtr XkbAllocSrvLedInfo( DeviceIntPtr /* dev */, KbdFeedbackPtr /* kf */, LedFeedbackPtr /* lf */, unsigned int /* needed_parts */ ); extern XkbSrvLedInfoPtr XkbFindSrvLedInfo( DeviceIntPtr /* dev */, unsigned int /* class */, unsigned int /* id */, unsigned int /* needed_parts */ ); extern void XkbApplyLedNameChanges( DeviceIntPtr /* dev */, XkbSrvLedInfoPtr /* sli */, unsigned int /* changed_names */, xkbExtensionDeviceNotify * /* ed */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void XkbApplyLedMapChanges( DeviceIntPtr /* dev */, XkbSrvLedInfoPtr /* sli */, unsigned int /* changed_maps */, xkbExtensionDeviceNotify * /* ed */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void XkbApplyLedStateChanges( DeviceIntPtr /* dev */, XkbSrvLedInfoPtr /* sli */, unsigned int /* changed_leds */, xkbExtensionDeviceNotify * /* ed */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void XkbUpdateLedAutoState( DeviceIntPtr /* dev */, XkbSrvLedInfoPtr /* sli */, unsigned int /* maps_to_check */, xkbExtensionDeviceNotify * /* ed */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void XkbFlushLedEvents( DeviceIntPtr /* dev */, DeviceIntPtr /* kbd */, XkbSrvLedInfoPtr /* sli */, xkbExtensionDeviceNotify * /* ed */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void XkbUpdateAllDeviceIndicators( XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern unsigned int XkbIndicatorsToUpdate( DeviceIntPtr /* dev */, unsigned long /* state_changes */, Bool /* enabled_ctrl_changes */ ); extern void XkbComputeDerivedState( XkbSrvInfoPtr /* xkbi */ ); extern void XkbCheckSecondaryEffects( XkbSrvInfoPtr /* xkbi */, unsigned int /* which */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void XkbCheckIndicatorMaps( DeviceIntPtr /* dev */, XkbSrvLedInfoPtr /* sli */, unsigned int /* which */ ); extern unsigned int XkbStateChangedFlags( XkbStatePtr /* old */, XkbStatePtr /* new */ ); extern void XkbSendStateNotify( DeviceIntPtr /* kbd */, xkbStateNotify * /* pSN */ ); extern void XkbSendMapNotify( DeviceIntPtr /* kbd */, xkbMapNotify * /* ev */ ); extern int XkbComputeControlsNotify( DeviceIntPtr /* kbd */, XkbControlsPtr /* old */, XkbControlsPtr /* new */, xkbControlsNotify * /* pCN */, Bool /* forceCtrlProc */ ); extern void XkbSendControlsNotify( DeviceIntPtr /* kbd */, xkbControlsNotify * /* ev */ ); extern void XkbSendCompatMapNotify( DeviceIntPtr /* kbd */, xkbCompatMapNotify * /* ev */ ); extern void XkbSendIndicatorNotify( DeviceIntPtr /* kbd */, int /* xkbType */, xkbIndicatorNotify * /* ev */ ); extern void XkbHandleBell( BOOL /* force */, BOOL /* eventOnly */, DeviceIntPtr /* kbd */, CARD8 /* percent */, pointer /* ctrl */, CARD8 /* class */, Atom /* name */, WindowPtr /* pWin */, ClientPtr /* pClient */ ); extern void XkbSendAccessXNotify( DeviceIntPtr /* kbd */, xkbAccessXNotify * /* pEv */ ); extern void XkbSendNamesNotify( DeviceIntPtr /* kbd */, xkbNamesNotify * /* ev */ ); extern void XkbSendCompatNotify( DeviceIntPtr /* kbd */, xkbCompatMapNotify * /* ev */ ); extern void XkbSendActionMessage( DeviceIntPtr /* kbd */, xkbActionMessage * /* ev */ ); extern void XkbSendExtensionDeviceNotify( DeviceIntPtr /* kbd */, ClientPtr /* client */, xkbExtensionDeviceNotify * /* ev */ ); extern void XkbSendNotification( DeviceIntPtr /* kbd */, XkbChangesPtr /* pChanges */, XkbEventCausePtr /* cause */ ); extern void XkbProcessKeyboardEvent( struct _xEvent * /* xE */, DeviceIntPtr /* keybd */, int /* count */ ); extern void XkbProcessOtherEvent( struct _xEvent * /* xE */, DeviceIntPtr /* keybd */, int /* count */ ); extern void XkbHandleActions( DeviceIntPtr /* dev */, DeviceIntPtr /* kbd */, struct _xEvent * /* xE */, int /* count */ ); extern Bool XkbEnableDisableControls( XkbSrvInfoPtr /* xkbi */, unsigned long /* change */, unsigned long /* newValues */, XkbChangesPtr /* changes */, XkbEventCausePtr /* cause */ ); extern void AccessXInit( DeviceIntPtr /* dev */ ); extern Bool AccessXFilterPressEvent( register struct _xEvent * /* xE */, register DeviceIntPtr /* keybd */, int /* count */ ); extern Bool AccessXFilterReleaseEvent( register struct _xEvent * /* xE */, register DeviceIntPtr /* keybd */, int /* count */ ); extern void AccessXCancelRepeatKey( XkbSrvInfoPtr /* xkbi */, KeyCode /* key */ ); extern void AccessXComputeCurveFactor( XkbSrvInfoPtr /* xkbi */, XkbControlsPtr /* ctrls */ ); extern XkbDeviceLedInfoPtr XkbAddDeviceLedInfo( XkbDeviceInfoPtr /* devi */, unsigned int /* ledClass */, unsigned int /* ledId */ ); extern XkbDeviceInfoPtr XkbAllocDeviceInfo( unsigned int /* deviceSpec */, unsigned int /* nButtons */, unsigned int /* szLeds */ ); extern void XkbFreeDeviceInfo( XkbDeviceInfoPtr /* devi */, unsigned int /* which */, Bool /* freeDevI */ ); extern Status XkbResizeDeviceButtonActions( XkbDeviceInfoPtr /* devi */, unsigned int /* newTotal */ ); extern XkbInterestPtr XkbFindClientResource( DevicePtr /* inDev */, ClientPtr /* client */ ); extern XkbInterestPtr XkbAddClientResource( DevicePtr /* inDev */, ClientPtr /* client */, XID /* id */ ); extern int XkbRemoveClient( DevicePtr /* inDev */, ClientPtr /* client */ ); extern int XkbRemoveResourceClient( DevicePtr /* inDev */, XID /* id */ ); extern int XkbDDXInitDevice( DeviceIntPtr /* dev */ ); extern int XkbDDXAccessXBeep( DeviceIntPtr /* dev */, unsigned int /* what */, unsigned int /* which */ ); extern void XkbDDXKeyClick( DeviceIntPtr /* dev */, int /* keycode */, int /* synthetic */ ); extern int XkbDDXUsesSoftRepeat( DeviceIntPtr /* dev */ ); extern void XkbDDXKeybdCtrlProc( DeviceIntPtr /* dev */, KeybdCtrl * /* ctrl */ ); extern void XkbDDXChangeControls( DeviceIntPtr /* dev */, XkbControlsPtr /* old */, XkbControlsPtr /* new */ ); extern void XkbDDXUpdateIndicators( DeviceIntPtr /* keybd */, CARD32 /* newState */ ); extern void XkbDDXUpdateDeviceIndicators( DeviceIntPtr /* dev */, XkbSrvLedInfoPtr /* sli */, CARD32 /* newState */ ); extern void XkbDDXFakePointerButton( int /* event */, int /* button */ ); extern void XkbDDXFakePointerMotion( unsigned int /* flags */, int /* x */, int /* y */ ); extern void XkbDDXFakeDeviceButton( DeviceIntPtr /* dev */, Bool /* press */, int /* button */ ); extern int XkbDDXTerminateServer( DeviceIntPtr /* dev */, KeyCode /* key */, XkbAction * /* act */ ); extern int XkbDDXSwitchScreen( DeviceIntPtr /* dev */, KeyCode /* key */, XkbAction * /* act */ ); extern int XkbDDXPrivate( DeviceIntPtr /* dev */, KeyCode /* key */, XkbAction * /* act */ ); extern void XkbDisableComputedAutoRepeats( DeviceIntPtr /* pXDev */, unsigned int /* key */ ); extern void XkbSetRepeatKeys( DeviceIntPtr /* pXDev */, int /* key */, int /* onoff */ ); extern int XkbLatchModifiers( DeviceIntPtr /* pXDev */, CARD8 /* mask */, CARD8 /* latches */ ); extern int XkbLatchGroup( DeviceIntPtr /* pXDev */, int /* group */ ); extern void XkbClearAllLatchesAndLocks( DeviceIntPtr /* dev */, XkbSrvInfoPtr /* xkbi */, Bool /* genEv */, XkbEventCausePtr /* cause */ ); extern void XkbSetRulesDflts( char * /* rulesFile */, char * /* model */, char * /* layout */, char * /* variant */, char * /* options */ ); extern void XkbInitDevice( DeviceIntPtr /* pXDev */ ); extern Bool XkbInitKeyboardDeviceStruct( DeviceIntPtr /* pXDev */, XkbComponentNamesPtr /* pNames */, KeySymsPtr /* pSyms */, CARD8 /* pMods */[], BellProcPtr /* bellProc */, KbdCtrlProcPtr /* ctrlProc */ ); extern int SProcXkbDispatch( ClientPtr /* client */ ); extern XkbGeometryPtr XkbLookupNamedGeometry( DeviceIntPtr /* dev */, Atom /* name */, Bool * /* shouldFree */ ); extern char * _XkbDupString( char * /* str */ ); extern void XkbConvertCase( KeySym /* sym */, KeySym * /* lower */, KeySym * /* upper */ ); extern Status XkbChangeKeycodeRange( XkbDescPtr /* xkb */, int /* minKC */, int /* maxKC */, XkbChangesPtr /* changes */ ); extern int XkbFinishDeviceInit( DeviceIntPtr /* pXDev */ ); extern void XkbFreeSrvLedInfo( XkbSrvLedInfoPtr /* sli */ ); extern void XkbFreeInfo( XkbSrvInfoPtr /* xkbi */ ); extern Status XkbChangeTypesOfKey( XkbDescPtr /* xkb */, int /* key */, int /* nGroups */, unsigned int /* groups */, int * /* newTypesIn */, XkbMapChangesPtr /* changes */ ); extern XkbKeyTypePtr XkbAddKeyType( XkbDescPtr /* xkb */, Atom /* name */, int /* map_count */, Bool /* want_preserve */, int /* num_lvls */ ); extern Status XkbInitCanonicalKeyTypes( XkbDescPtr /* xkb */, unsigned int /* which */, int /* keypadVMod */ ); extern int XkbKeyTypesForCoreSymbols( XkbDescPtr /* xkb */, int /* map_width */, KeySym * /* core_syms */, unsigned int /* protected */, int * /* types_inout */, KeySym * /* xkb_syms_rtrn */ ); extern Bool XkbApplyCompatMapToKey( XkbDescPtr /* xkb */, KeyCode /* key */, XkbChangesPtr /* changes */ ); extern Bool XkbUpdateMapFromCore( XkbDescPtr /* xkb */, KeyCode /* first_key */, int /* num_keys */, int /* map_width */, KeySym * /* core_keysyms */, XkbChangesPtr /* changes */ ); extern void XkbFreeControls( XkbDescPtr /* xkb */, unsigned int /* which */, Bool /* freeMap */ ); extern void XkbFreeIndicatorMaps( XkbDescPtr /* xkb */ ); extern Bool XkbApplyVirtualModChanges( XkbDescPtr /* xkb */, unsigned int /* changed */, XkbChangesPtr /* changes */ ); extern Bool XkbUpdateActionVirtualMods( XkbDescPtr /* xkb */, XkbAction * /* act */, unsigned int /* changed */ ); extern void XkbUpdateKeyTypeVirtualMods( XkbDescPtr /* xkb */, XkbKeyTypePtr /* type */, unsigned int /* changed */, XkbChangesPtr /* changes */ ); extern void XkbSendNewKeyboardNotify( DeviceIntPtr /* kbd */, xkbNewKeyboardNotify * /* pNKN */ ); #ifdef XKBSRV_NEED_FILE_FUNCS #include #include #include #define _XkbListKeymaps 0 #define _XkbListKeycodes 1 #define _XkbListTypes 2 #define _XkbListCompat 3 #define _XkbListSymbols 4 #define _XkbListGeometry 5 #define _XkbListNumComponents 6 typedef struct _XkbSrvListInfo { int szPool; int nPool; char * pool; int maxRtrn; int nTotal; char * pattern[_XkbListNumComponents]; int nFound[_XkbListNumComponents]; } XkbSrvListInfoRec,*XkbSrvListInfoPtr; char * XkbGetRulesDflts( XkbRF_VarDefsPtr /* defs */ ); extern void XkbSetRulesUsed( XkbRF_VarDefsPtr /* defs */ ); extern Status XkbDDXList( DeviceIntPtr /* dev */, XkbSrvListInfoPtr /* listing */, ClientPtr /* client */ ); extern unsigned int XkbDDXLoadKeymapByNames( DeviceIntPtr /* keybd */, XkbComponentNamesPtr /* names */, unsigned int /* want */, unsigned int /* need */, XkbFileInfoPtr /* finfoRtrn */, char * /* keymapNameRtrn */, int /* keymapNameRtrnLen */ ); extern Bool XkbDDXNamesFromRules( DeviceIntPtr /* keybd */, char * /* rules */, XkbRF_VarDefsPtr /* defs */, XkbComponentNamesPtr /* names */ ); extern FILE *XkbDDXOpenConfigFile( char * /* mapName */, char * /* fileNameRtrn */, int /* fileNameRtrnLen */ ); extern Bool XkbDDXApplyConfig( XPointer /* cfg_in */, XkbSrvInfoPtr /* xkbi */ ); extern XPointer XkbDDXPreloadConfig( char ** /* rulesFileRtrn */, XkbRF_VarDefsPtr /* defs */, XkbComponentNamesPtr /* names */, DeviceIntPtr /* dev */ ); extern int _XkbStrCaseCmp( char * /* str1 */, char * /* str2 */ ); #endif /* XKBSRV_NEED_FILE_FUNCS */ _XFUNCPROTOEND #define XkbAtomGetString(d,s) NameForAtom(s) #endif /* _XKBSRV_H_ */ X11/extensions/Xv.h000064400000005723151027430550010073 0ustar00/*********************************************************** Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts, and the Massachusetts Institute of Technology, Cambridge, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Digital or MIT not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef XV_H #define XV_H /* ** File: ** ** Xv.h --- Xv shared library and server header file ** ** Author: ** ** David Carver (Digital Workstation Engineering/Project Athena) ** ** Revisions: ** ** 05.15.91 Carver ** - version 2.0 upgrade ** ** 01.24.91 Carver ** - version 1.4 upgrade ** */ #include #define XvName "XVideo" #define XvVersion 2 #define XvRevision 2 /* Symbols */ typedef XID XvPortID; typedef XID XvEncodingID; #define XvNone 0 #define XvInput 0 #define XvOutput 1 #define XvInputMask (1< #define X_XDGAQueryVersion 0 /* 1 through 9 are in xf86dga1.h */ /* 10 and 11 are reserved to avoid conflicts with rogue DGA extensions */ #define X_XDGAQueryModes 12 #define X_XDGASetMode 13 #define X_XDGASetViewport 14 #define X_XDGAInstallColormap 15 #define X_XDGASelectInput 16 #define X_XDGAFillRectangle 17 #define X_XDGACopyArea 18 #define X_XDGACopyTransparentArea 19 #define X_XDGAGetViewportStatus 20 #define X_XDGASync 21 #define X_XDGAOpenFramebuffer 22 #define X_XDGACloseFramebuffer 23 #define X_XDGASetClientVersion 24 #define X_XDGAChangePixmapMode 25 #define X_XDGACreateColormap 26 #define XDGAConcurrentAccess 0x00000001 #define XDGASolidFillRect 0x00000002 #define XDGABlitRect 0x00000004 #define XDGABlitTransRect 0x00000008 #define XDGAPixmap 0x00000010 #define XDGAInterlaced 0x00010000 #define XDGADoublescan 0x00020000 #define XDGAFlipImmediate 0x00000001 #define XDGAFlipRetrace 0x00000002 #define XDGANeedRoot 0x00000001 #define XF86DGANumberEvents 7 #define XDGAPixmapModeLarge 0 #define XDGAPixmapModeSmall 1 #define XF86DGAClientNotLocal 0 #define XF86DGANoDirectVideoMode 1 #define XF86DGAScreenNotActive 2 #define XF86DGADirectNotActivated 3 #define XF86DGAOperationNotSupported 4 #define XF86DGANumberErrors (XF86DGAOperationNotSupported + 1) typedef struct { int num; /* A unique identifier for the mode (num > 0) */ char *name; /* name of mode given in the XF86Config */ float verticalRefresh; int flags; /* DGA_CONCURRENT_ACCESS, etc... */ int imageWidth; /* linear accessible portion (pixels) */ int imageHeight; int pixmapWidth; /* Xlib accessible portion (pixels) */ int pixmapHeight; /* both fields ignored if no concurrent access */ int bytesPerScanline; int byteOrder; /* MSBFirst, LSBFirst */ int depth; int bitsPerPixel; unsigned long redMask; unsigned long greenMask; unsigned long blueMask; short visualClass; int viewportWidth; int viewportHeight; int xViewportStep; /* viewport position granularity */ int yViewportStep; int maxViewportX; /* max viewport origin */ int maxViewportY; int viewportFlags; /* types of page flipping possible */ int reserved1; int reserved2; } XDGAMode; typedef struct { XDGAMode mode; unsigned char *data; Pixmap pixmap; } XDGADevice; #endif /* _XF86DGACONST_H_ */ X11/extensions/composite.h000064400000006072151027430550011476 0ustar00/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * Copyright © 2003 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _COMPOSITE_H_ #define _COMPOSITE_H_ #include #define COMPOSITE_NAME "Composite" #define COMPOSITE_MAJOR 0 #define COMPOSITE_MINOR 4 #define CompositeRedirectAutomatic 0 #define CompositeRedirectManual 1 #define X_CompositeQueryVersion 0 #define X_CompositeRedirectWindow 1 #define X_CompositeRedirectSubwindows 2 #define X_CompositeUnredirectWindow 3 #define X_CompositeUnredirectSubwindows 4 #define X_CompositeCreateRegionFromBorderClip 5 #define X_CompositeNameWindowPixmap 6 #define X_CompositeGetOverlayWindow 7 #define X_CompositeReleaseOverlayWindow 8 #define CompositeNumberRequests (X_CompositeReleaseOverlayWindow + 1) #define CompositeNumberEvents 0 #endif /* _COMPOSITE_H_ */ X11/extensions/XI2.h000064400000024456151027430550010104 0ustar00/* * Copyright © 2009 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #ifndef _XI2_H_ #define _XI2_H_ #define XInput_2_0 7 /* DO NOT ADD TO THIS LIST. These are libXi-specific defines. See commit libXi-1.4.2-21-ge8531dd */ #define XI_2_Major 2 #define XI_2_Minor 3 /* Property event flags */ #define XIPropertyDeleted 0 #define XIPropertyCreated 1 #define XIPropertyModified 2 /* Property modes */ #define XIPropModeReplace 0 #define XIPropModePrepend 1 #define XIPropModeAppend 2 /* Special property type used for XIGetProperty */ #define XIAnyPropertyType 0L /* Enter/Leave and Focus In/Out modes */ #define XINotifyNormal 0 #define XINotifyGrab 1 #define XINotifyUngrab 2 #define XINotifyWhileGrabbed 3 #define XINotifyPassiveGrab 4 #define XINotifyPassiveUngrab 5 /* Enter/Leave and focus In/out detail */ #define XINotifyAncestor 0 #define XINotifyVirtual 1 #define XINotifyInferior 2 #define XINotifyNonlinear 3 #define XINotifyNonlinearVirtual 4 #define XINotifyPointer 5 #define XINotifyPointerRoot 6 #define XINotifyDetailNone 7 /* Grab modes */ #define XIGrabModeSync 0 #define XIGrabModeAsync 1 #define XIGrabModeTouch 2 /* Grab reply status codes */ #define XIGrabSuccess 0 #define XIAlreadyGrabbed 1 #define XIGrabInvalidTime 2 #define XIGrabNotViewable 3 #define XIGrabFrozen 4 /* Grab owner events values */ #define XIOwnerEvents True #define XINoOwnerEvents False /* Passive grab types */ #define XIGrabtypeButton 0 #define XIGrabtypeKeycode 1 #define XIGrabtypeEnter 2 #define XIGrabtypeFocusIn 3 #define XIGrabtypeTouchBegin 4 /* Passive grab modifier */ #define XIAnyModifier (1U << 31) #define XIAnyButton 0 #define XIAnyKeycode 0 /* XIAllowEvents event-modes */ #define XIAsyncDevice 0 #define XISyncDevice 1 #define XIReplayDevice 2 #define XIAsyncPairedDevice 3 #define XIAsyncPair 4 #define XISyncPair 5 #define XIAcceptTouch 6 #define XIRejectTouch 7 /* DeviceChangedEvent change reasons */ #define XISlaveSwitch 1 #define XIDeviceChange 2 /* Hierarchy flags */ #define XIMasterAdded (1 << 0) #define XIMasterRemoved (1 << 1) #define XISlaveAdded (1 << 2) #define XISlaveRemoved (1 << 3) #define XISlaveAttached (1 << 4) #define XISlaveDetached (1 << 5) #define XIDeviceEnabled (1 << 6) #define XIDeviceDisabled (1 << 7) /* ChangeHierarchy constants */ #define XIAddMaster 1 #define XIRemoveMaster 2 #define XIAttachSlave 3 #define XIDetachSlave 4 #define XIAttachToMaster 1 #define XIFloating 2 /* Valuator modes */ #define XIModeRelative 0 #define XIModeAbsolute 1 /* Device types */ #define XIMasterPointer 1 #define XIMasterKeyboard 2 #define XISlavePointer 3 #define XISlaveKeyboard 4 #define XIFloatingSlave 5 /* Device classes: classes that are not identical to Xi 1.x classes must be * numbered starting from 8. */ #define XIKeyClass 0 #define XIButtonClass 1 #define XIValuatorClass 2 #define XIScrollClass 3 #define XITouchClass 8 /* Scroll class types */ #define XIScrollTypeVertical 1 #define XIScrollTypeHorizontal 2 /* Scroll class flags */ #define XIScrollFlagNoEmulation (1 << 0) #define XIScrollFlagPreferred (1 << 1) /* Device event flags (common) */ /* Device event flags (key events only) */ #define XIKeyRepeat (1 << 16) /* Device event flags (pointer events only) */ #define XIPointerEmulated (1 << 16) /* Device event flags (touch events only) */ #define XITouchPendingEnd (1 << 16) #define XITouchEmulatingPointer (1 << 17) /* Barrier event flags */ #define XIBarrierPointerReleased (1 << 0) #define XIBarrierDeviceIsGrabbed (1 << 1) /* Touch modes */ #define XIDirectTouch 1 #define XIDependentTouch 2 /* XI2 event mask macros */ #define XISetMask(ptr, event) (((unsigned char*)(ptr))[(event)>>3] |= (1 << ((event) & 7))) #define XIClearMask(ptr, event) (((unsigned char*)(ptr))[(event)>>3] &= ~(1 << ((event) & 7))) #define XIMaskIsSet(ptr, event) (((unsigned char*)(ptr))[(event)>>3] & (1 << ((event) & 7))) #define XIMaskLen(event) (((event) >> 3) + 1) /* Fake device ID's for event selection */ #define XIAllDevices 0 #define XIAllMasterDevices 1 /* Event types */ #define XI_DeviceChanged 1 #define XI_KeyPress 2 #define XI_KeyRelease 3 #define XI_ButtonPress 4 #define XI_ButtonRelease 5 #define XI_Motion 6 #define XI_Enter 7 #define XI_Leave 8 #define XI_FocusIn 9 #define XI_FocusOut 10 #define XI_HierarchyChanged 11 #define XI_PropertyEvent 12 #define XI_RawKeyPress 13 #define XI_RawKeyRelease 14 #define XI_RawButtonPress 15 #define XI_RawButtonRelease 16 #define XI_RawMotion 17 #define XI_TouchBegin 18 /* XI 2.2 */ #define XI_TouchUpdate 19 #define XI_TouchEnd 20 #define XI_TouchOwnership 21 #define XI_RawTouchBegin 22 #define XI_RawTouchUpdate 23 #define XI_RawTouchEnd 24 #define XI_BarrierHit 25 /* XI 2.3 */ #define XI_BarrierLeave 26 #define XI_LASTEVENT XI_BarrierLeave /* NOTE: XI2LASTEVENT in xserver/include/inputstr.h must be the same value * as XI_LASTEVENT if the server is supposed to handle masks etc. for this * type of event. */ /* Event masks. * Note: the protocol spec defines a mask to be of (1 << type). Clients are * free to create masks by bitshifting instead of using these defines. */ #define XI_DeviceChangedMask (1 << XI_DeviceChanged) #define XI_KeyPressMask (1 << XI_KeyPress) #define XI_KeyReleaseMask (1 << XI_KeyRelease) #define XI_ButtonPressMask (1 << XI_ButtonPress) #define XI_ButtonReleaseMask (1 << XI_ButtonRelease) #define XI_MotionMask (1 << XI_Motion) #define XI_EnterMask (1 << XI_Enter) #define XI_LeaveMask (1 << XI_Leave) #define XI_FocusInMask (1 << XI_FocusIn) #define XI_FocusOutMask (1 << XI_FocusOut) #define XI_HierarchyChangedMask (1 << XI_HierarchyChanged) #define XI_PropertyEventMask (1 << XI_PropertyEvent) #define XI_RawKeyPressMask (1 << XI_RawKeyPress) #define XI_RawKeyReleaseMask (1 << XI_RawKeyRelease) #define XI_RawButtonPressMask (1 << XI_RawButtonPress) #define XI_RawButtonReleaseMask (1 << XI_RawButtonRelease) #define XI_RawMotionMask (1 << XI_RawMotion) #define XI_TouchBeginMask (1 << XI_TouchBegin) #define XI_TouchEndMask (1 << XI_TouchEnd) #define XI_TouchOwnershipChangedMask (1 << XI_TouchOwnership) #define XI_TouchUpdateMask (1 << XI_TouchUpdate) #define XI_RawTouchBeginMask (1 << XI_RawTouchBegin) #define XI_RawTouchEndMask (1 << XI_RawTouchEnd) #define XI_RawTouchUpdateMask (1 << XI_RawTouchUpdate) #define XI_BarrierHitMask (1 << XI_BarrierHit) #define XI_BarrierLeaveMask (1 << XI_BarrierLeave) #endif /* _XI2_H_ */ X11/extensions/damagewire.h000064400000003545151027430550011603 0ustar00/* * Copyright © 2003 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _DAMAGEWIRE_H_ #define _DAMAGEWIRE_H_ #define DAMAGE_NAME "DAMAGE" #define DAMAGE_MAJOR 1 #define DAMAGE_MINOR 1 /************* Version 1 ****************/ /* Constants */ #define XDamageReportRawRectangles 0 #define XDamageReportDeltaRectangles 1 #define XDamageReportBoundingBox 2 #define XDamageReportNonEmpty 3 /* Requests */ #define X_DamageQueryVersion 0 #define X_DamageCreate 1 #define X_DamageDestroy 2 #define X_DamageSubtract 3 #define X_DamageAdd 4 #define XDamageNumberRequests (X_DamageAdd + 1) /* Events */ #define XDamageNotify 0 #define XDamageNumberEvents (XDamageNotify + 1) /* Errors */ #define BadDamage 0 #define XDamageNumberErrors (BadDamage + 1) #endif /* _DAMAGEWIRE_H_ */ X11/extensions/xtestconst.h000064400000002560151027430550011710 0ustar00/* Copyright 1992, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _XTEST_CONST_H_ #define _XTEST_CONST_H_ #define XTestNumberEvents 0 #define XTestNumberErrors 0 #define XTestCurrentCursor ((Cursor)1) #define XTestMajorVersion 2 #define XTestMinorVersion 2 #define XTestExtensionName "XTEST" #endif X11/extensions/dbe.h000064400000004157151027430550010230 0ustar00/****************************************************************************** * * Copyright (c) 1994, 1995 Hewlett-Packard Company * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL HEWLETT-PACKARD COMPANY BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of the Hewlett-Packard * Company shall not be used in advertising or otherwise to promote the * sale, use or other dealings in this Software without prior written * authorization from the Hewlett-Packard Company. * * Header file for Xlib-related DBE * *****************************************************************************/ #ifndef DBE_H #define DBE_H /* Values for swap_action field of XdbeSwapInfo structure */ #define XdbeUndefined 0 #define XdbeBackground 1 #define XdbeUntouched 2 #define XdbeCopied 3 /* Errors */ #define XdbeBadBuffer 0 #define DBE_PROTOCOL_NAME "DOUBLE-BUFFER" /* Current version numbers */ #define DBE_MAJOR_VERSION 1 #define DBE_MINOR_VERSION 0 /* Used when adding extension; also used in Xdbe macros */ #define DbeNumberEvents 0 #define DbeBadBuffer 0 #define DbeNumberErrors (DbeBadBuffer + 1) #endif /* DBE_H */ X11/extensions/presentproto.h000064400000012441151027430550012235 0ustar00/* * Copyright © 2013 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that copyright * notice and this permission notice appear in supporting documentation, and * that the name of the copyright holders not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. The copyright holders make no representations * about the suitability of this software for any purpose. It is provided "as * is" without express or implied warranty. * * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #ifndef _PRESENT_PROTO_H_ #define _PRESENT_PROTO_H_ #include #define Window CARD32 #define Pixmap CARD32 #define Region CARD32 #define XSyncFence CARD32 #define EventID CARD32 typedef struct { Window window; CARD32 serial; } xPresentNotify; #define sz_xPresentNotify 8 typedef struct { CARD8 reqType; CARD8 presentReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xPresentQueryVersionReq; #define sz_xPresentQueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xPresentQueryVersionReply; #define sz_xPresentQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 presentReqType; CARD16 length; Window window; Pixmap pixmap; CARD32 serial; Region valid; Region update; INT16 x_off; INT16 y_off; CARD32 target_crtc; XSyncFence wait_fence; XSyncFence idle_fence; CARD32 options; CARD32 pad1; CARD64 target_msc; CARD64 divisor; CARD64 remainder; /* followed by a LISTofPRESENTNOTIFY */ } xPresentPixmapReq; #define sz_xPresentPixmapReq 72 typedef struct { CARD8 reqType; CARD8 presentReqType; CARD16 length; Window window; CARD32 serial; CARD32 pad0; CARD64 target_msc; CARD64 divisor; CARD64 remainder; } xPresentNotifyMSCReq; #define sz_xPresentNotifyMSCReq 40 typedef struct { CARD8 reqType; CARD8 presentReqType; CARD16 length; CARD32 eid; CARD32 window; CARD32 eventMask; } xPresentSelectInputReq; #define sz_xPresentSelectInputReq 16 typedef struct { CARD8 reqType; CARD8 presentReqType; CARD16 length; CARD32 target; } xPresentQueryCapabilitiesReq; #define sz_xPresentQueryCapabilitiesReq 8 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 capabilities; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; CARD32 pad7; } xPresentQueryCapabilitiesReply; #define sz_xPresentQueryCapabilitiesReply 32 /* * Events * * All Present events are X Generic Events */ typedef struct { CARD8 type; CARD8 extension; CARD16 sequenceNumber; CARD32 length; CARD16 evtype; CARD16 pad2; CARD32 eid; CARD32 window; INT16 x; INT16 y; CARD16 width; CARD16 height; INT16 off_x; INT16 off_y; CARD16 pixmap_width; CARD16 pixmap_height; CARD32 pixmap_flags; } xPresentConfigureNotify; #define sz_xPresentConfigureNotify 40 typedef struct { CARD8 type; CARD8 extension; CARD16 sequenceNumber; CARD32 length; CARD16 evtype; CARD8 kind; CARD8 mode; CARD32 eid; Window window; CARD32 serial; CARD64 ust; CARD64 msc; } xPresentCompleteNotify; #define sz_xPresentCompleteNotify 40 typedef struct { CARD8 type; CARD8 extension; CARD16 sequenceNumber; CARD32 length; CARD16 evtype; CARD16 pad2; CARD32 eid; Window window; CARD32 serial; Pixmap pixmap; CARD32 idle_fence; } xPresentIdleNotify; #define sz_xPresentIdleNotify 32 #if PRESENT_FUTURE_VERSION typedef struct { CARD8 type; CARD8 extension; CARD16 sequenceNumber; CARD32 length; CARD16 evtype; CARD8 update_window; CARD8 pad1; CARD32 eid; Window event_window; Window window; Pixmap pixmap; CARD32 serial; /* 32-byte boundary */ Region valid_region; Region update_region; xRectangle valid_rect; xRectangle update_rect; INT16 x_off; INT16 y_off; CARD32 target_crtc; XSyncFence wait_fence; XSyncFence idle_fence; CARD32 options; CARD32 pad2; CARD64 target_msc; CARD64 divisor; CARD64 remainder; } xPresentRedirectNotify; #define sz_xPresentRedirectNotify 104 #endif #undef Window #undef Pixmap #undef Region #undef XSyncFence #undef EventID #endif X11/extensions/ge.h000064400000003366151027430550010072 0ustar00/* * Copyright © 2007-2008 Peter Hutterer * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * Authors: Peter Hutterer, University of South Australia, NICTA * */ #ifndef _GE_H_ #define _GE_H_ #define GE_NAME "Generic Event Extension" #define GE_MAJOR 1 #define GE_MINOR 0 /********************************************************* * * Requests * */ #define X_GEQueryVersion 0 #define GENumberRequests (X_GEQueryVersion + 1) /********************************************************* * * Events * */ #define GENumberEvents 0 /********************************************************* * * Errors * */ #define GENumberErrors 0 #endif /* _GE_H_ */ X11/extensions/xf86dga1proto.h000064400000010632151027430550012105 0ustar00/* Copyright (c) 1995 Jon Tombs Copyright (c) 1995 XFree86 Inc. */ #ifndef _XF86DGAPROTO1_H_ #define _XF86DGAPROTO1_H_ #include typedef struct _XF86DGAQueryVersion { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_DGAQueryVersion */ CARD16 length; } xXF86DGAQueryVersionReq; #define sz_xXF86DGAQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of DGA protocol */ CARD16 minorVersion; /* minor version of DGA protocol */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86DGAQueryVersionReply; #define sz_xXF86DGAQueryVersionReply 32 typedef struct _XF86DGAGetVideoLL { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_XF86DGAGetVideoLL */ CARD16 length; CARD16 screen; CARD16 pad; } xXF86DGAGetVideoLLReq; #define sz_xXF86DGAGetVideoLLReq 8 typedef struct _XF86DGAInstallColormap{ CARD8 reqType; CARD8 dgaReqType; CARD16 length; CARD16 screen; CARD16 pad2; CARD32 id; /* colormap. */ } xXF86DGAInstallColormapReq; #define sz_xXF86DGAInstallColormapReq 12 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 offset; CARD32 width; CARD32 bank_size; CARD32 ram_size; CARD32 pad4; CARD32 pad5; } xXF86DGAGetVideoLLReply; #define sz_xXF86DGAGetVideoLLReply 32 typedef struct _XF86DGADirectVideo { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_XF86DGADirectVideo */ CARD16 length; CARD16 screen; CARD16 enable; } xXF86DGADirectVideoReq; #define sz_xXF86DGADirectVideoReq 8 typedef struct _XF86DGAGetViewPortSize { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_XF86DGAGetViewPort */ CARD16 length; CARD16 screen; CARD16 pad; } xXF86DGAGetViewPortSizeReq; #define sz_xXF86DGAGetViewPortSizeReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 width; CARD32 height; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86DGAGetViewPortSizeReply; #define sz_xXF86DGAGetViewPortSizeReply 32 typedef struct _XF86DGASetViewPort { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_XF86DGASetViewPort */ CARD16 length; CARD16 screen; CARD16 pad; CARD32 x; CARD32 y; } xXF86DGASetViewPortReq; #define sz_xXF86DGASetViewPortReq 16 typedef struct _XF86DGAGetVidPage { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_XF86DGAGetVidPage */ CARD16 length; CARD16 screen; CARD16 pad; } xXF86DGAGetVidPageReq; #define sz_xXF86DGAGetVidPageReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 vpage; CARD32 pad; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86DGAGetVidPageReply; #define sz_xXF86DGAGetVidPageReply 32 typedef struct _XF86DGASetVidPage { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_XF86DGASetVidPage */ CARD16 length; CARD16 screen; CARD16 vpage; } xXF86DGASetVidPageReq; #define sz_xXF86DGASetVidPageReq 8 typedef struct _XF86DGAQueryDirectVideo { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_DGAQueryVersion */ CARD16 length; CARD16 screen; CARD16 pad; } xXF86DGAQueryDirectVideoReq; #define sz_xXF86DGAQueryDirectVideoReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 flags; CARD32 pad; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86DGAQueryDirectVideoReply; #define sz_xXF86DGAQueryDirectVideoReply 32 typedef struct _XF86DGAViewPortChanged { CARD8 reqType; /* always DGAReqCode */ CARD8 dgaReqType; /* always X_DGAQueryVersion */ CARD16 length; CARD16 screen; CARD16 n; } xXF86DGAViewPortChangedReq; #define sz_xXF86DGAViewPortChangedReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 result; CARD32 pad; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86DGAViewPortChangedReply; #define sz_xXF86DGAViewPortChangedReply 32 #endif /* _XF86DGAPROTO1_H_ */ X11/extensions/multibufproto.h000064400000020630151027430550012403 0ustar00/* Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _MULTIBUFPROTO_H_ #define _MULTIBUFPROTO_H_ #include /* * Protocol requests constants and alignment values */ #define Window CARD32 #define Drawable CARD32 #define VisualID CARD32 #define Multibuffer CARD32 #define X_MbufGetBufferVersion 0 #define X_MbufCreateImageBuffers 1 #define X_MbufDestroyImageBuffers 2 #define X_MbufDisplayImageBuffers 3 #define X_MbufSetMBufferAttributes 4 #define X_MbufGetMBufferAttributes 5 #define X_MbufSetBufferAttributes 6 #define X_MbufGetBufferAttributes 7 #define X_MbufGetBufferInfo 8 #define X_MbufCreateStereoWindow 9 #define X_MbufClearImageBufferArea 10 typedef struct xMbufBufferInfo { CARD32 visualID; /* associated visual */ CARD16 maxBuffers; /* maximum supported buffers */ CARD8 depth; /* depth of visual (redundant) */ CARD8 unused; } xMbufBufferInfo; #define sz_xMbufBufferInfo 8 typedef struct { BYTE type; BYTE unused; CARD16 sequenceNumber; CARD32 buffer; /* affected buffer */ BYTE state; /* current status */ CARD8 unused1; CARD16 unused2; CARD32 unused3; CARD32 unused4; CARD32 unused5; CARD32 unused6; CARD32 unused7; } xMbufClobberNotifyEvent; typedef struct { BYTE type; BYTE unused; CARD16 sequenceNumber; CARD32 buffer; /* affected buffer */ CARD32 timeStamp; /* update time */ CARD32 unused1; CARD32 unused2; CARD32 unused3; CARD32 unused4; CARD32 unused5; CARD32 unused6; } xMbufUpdateNotifyEvent; typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufGetBufferVersion */ CARD16 length; } xMbufGetBufferVersionReq; #define sz_xMbufGetBufferVersionReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD8 majorVersion; /* major version of Multi-Buffering protocol */ CARD8 minorVersion; /* minor version of Multi-Buffering protocol */ CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xMbufGetBufferVersionReply; #define sz_xMbufGetBufferVersionReply 32 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufCreateImageBuffers */ CARD16 length; CARD32 window; /* associated window */ CARD8 updateAction; /* action at update */ CARD8 updateHint; /* hint as to frequency of updates */ CARD16 unused; } xMbufCreateImageBuffersReq; /* followed by buffer ids */ #define sz_xMbufCreateImageBuffersReq 12 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD16 numberBuffer; /* number successfully allocated */ CARD16 unused1; CARD32 unused2; CARD32 unused3; CARD32 unused4; CARD32 unused5; CARD32 unused6; } xMbufCreateImageBuffersReply; #define sz_xMbufCreateImageBuffersReply 32 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufDestroyImageBuffers */ CARD16 length; CARD32 window; /* associated window */ } xMbufDestroyImageBuffersReq; #define sz_xMbufDestroyImageBuffersReq 8 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufDisplayImageBuffers */ CARD16 length; CARD16 minDelay; /* minimum time between last update and now */ CARD16 maxDelay; /* maximum time between last update and now */ } xMbufDisplayImageBuffersReq; /* followed by list of buffers */ #define sz_xMbufDisplayImageBuffersReq 8 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufSetMBufferAttributes */ CARD16 length; CARD32 window; /* associated window */ CARD32 valueMask; /* modified entries */ } xMbufSetMBufferAttributesReq; /* followed by values */ #define sz_xMbufSetMBufferAttributesReq 12 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufGetMBufferAttributes */ CARD16 length; CARD32 window; /* associated window */ } xMbufGetMBufferAttributesReq; #define sz_xMbufGetMBufferAttributesReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD16 displayedBuffer; /* currently visible buffer */ CARD8 updateAction; CARD8 updateHint; CARD8 windowMode; CARD8 unused0; CARD16 unused1; CARD32 unused2; CARD32 unused3; CARD32 unused4; CARD32 unused5; } xMbufGetMBufferAttributesReply; #define sz_xMbufGetMBufferAttributesReply 32 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufSetBufferAttributes */ CARD16 length; CARD32 buffer; CARD32 valueMask; } xMbufSetBufferAttributesReq; /* followed by values */ #define sz_xMbufSetBufferAttributesReq 12 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufGetBufferAttributes */ CARD16 length; CARD32 buffer; } xMbufGetBufferAttributesReq; #define sz_xMbufGetBufferAttributesReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD32 window; CARD32 eventMask; CARD16 bufferIndex; CARD8 side; CARD8 unused0; CARD32 unused1; CARD32 unused2; CARD32 unused3; } xMbufGetBufferAttributesReply; #define sz_xMbufGetBufferAttributesReply 32 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufGetBufferInfo */ CARD16 length; Drawable drawable; } xMbufGetBufferInfoReq; #define sz_xMbufGetBufferInfoReq 8 typedef struct { BYTE type; /* X_Reply */ CARD8 unused; /* not used */ CARD16 sequenceNumber; CARD32 length; CARD16 normalInfo; CARD16 stereoInfo; CARD32 unused1; CARD32 unused2; CARD32 unused3; CARD32 unused4; CARD32 unused5; } xMbufGetBufferInfoReply; /* followed by buffer infos */ #define sz_xMbufGetBufferInfoReply 32 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufCreateStereoWindow */ CARD16 length; CARD8 unused0; CARD8 unused1; CARD8 unused2; CARD8 depth; Window wid; Window parent; Multibuffer left; /* associated buffers */ Multibuffer right; INT16 x; INT16 y; CARD16 width; CARD16 height; CARD16 borderWidth; #if defined(__cplusplus) || defined(c_plusplus) CARD16 c_class; #else CARD16 class; #endif VisualID visual; CARD32 mask; } xMbufCreateStereoWindowReq; /* followed by value list */ #define sz_xMbufCreateStereoWindowReq 44 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 mbufReqType; /* always X_MbufClearImageBufferArea */ CARD16 length; Multibuffer buffer; INT16 x; INT16 y; CARD16 width; CARD16 height; CARD8 unused0; CARD8 unused1; CARD8 unused2; BOOL exposures; } xMbufClearImageBufferAreaReq; #define sz_xMbufClearImageBufferAreaReq 20 #undef Window #undef Drawable #undef VisualID #undef Multibuffer #endif /* _MULTIBUFPROTO_H_ */ X11/extensions/xf86vmstr.h000064400000000271151027430550011356 0ustar00#warning "xf86vmstr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/extensions/multibufconst.h000064400000005017151027430550012370 0ustar00/* Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _MULTIBUFCONST_H_ #define _MULTIBUFCONST_H_ #define MULTIBUFFER_PROTOCOL_NAME "Multi-Buffering" #define MULTIBUFFER_MAJOR_VERSION 1 /* current version numbers */ #define MULTIBUFFER_MINOR_VERSION 1 /* has ClearImageBufferArea */ /* * update_action field */ #define MultibufferUpdateActionUndefined 0 #define MultibufferUpdateActionBackground 1 #define MultibufferUpdateActionUntouched 2 #define MultibufferUpdateActionCopied 3 /* * update_hint field */ #define MultibufferUpdateHintFrequent 0 #define MultibufferUpdateHintIntermittent 1 #define MultibufferUpdateHintStatic 2 /* * valuemask fields */ #define MultibufferWindowUpdateHint (1L << 0) #define MultibufferBufferEventMask (1L << 0) /* * mono vs. stereo and left vs. right */ #define MultibufferModeMono 0 #define MultibufferModeStereo 1 #define MultibufferSideMono 0 #define MultibufferSideLeft 1 #define MultibufferSideRight 2 /* * clobber state */ #define MultibufferUnclobbered 0 #define MultibufferPartiallyClobbered 1 #define MultibufferFullyClobbered 2 /* * event stuff */ #define MultibufferClobberNotifyMask 0x02000000 #define MultibufferUpdateNotifyMask 0x04000000 #define MultibufferClobberNotify 0 #define MultibufferUpdateNotify 1 #define MultibufferNumberEvents (MultibufferUpdateNotify + 1) #define MultibufferBadBuffer 0 #define MultibufferNumberErrors (MultibufferBadBuffer + 1) #endif /* _MULTIBUFCONST_H_ */ X11/extensions/syncproto.h000064400000025371151027430550011537 0ustar00/* Copyright 1991, 1993, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /*********************************************************** Copyright 1991,1993 by Digital Equipment Corporation, Maynard, Massachusetts, and Olivetti Research Limited, Cambridge, England. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Digital or Olivetti not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL AND OLIVETTI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THEY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ #ifndef _SYNCPROTO_H_ #define _SYNCPROTO_H_ #include #define X_SyncInitialize 0 #define X_SyncListSystemCounters 1 #define X_SyncCreateCounter 2 #define X_SyncSetCounter 3 #define X_SyncChangeCounter 4 #define X_SyncQueryCounter 5 #define X_SyncDestroyCounter 6 #define X_SyncAwait 7 #define X_SyncCreateAlarm 8 #define X_SyncChangeAlarm 9 #define X_SyncQueryAlarm 10 #define X_SyncDestroyAlarm 11 #define X_SyncSetPriority 12 #define X_SyncGetPriority 13 #define X_SyncCreateFence 14 #define X_SyncTriggerFence 15 #define X_SyncResetFence 16 #define X_SyncDestroyFence 17 #define X_SyncQueryFence 18 #define X_SyncAwaitFence 19 /* cover up types from sync.h to make sure they're the right size for * protocol packaging. These will be undef'ed after all the protocol * structures are defined. */ #define XSyncCounter CARD32 #define XSyncAlarm CARD32 #define XSyncFence CARD32 #define Drawable CARD32 /* * Initialize */ typedef struct _xSyncInitialize { CARD8 reqType; CARD8 syncReqType; CARD16 length; CARD8 majorVersion; CARD8 minorVersion; CARD16 pad; } xSyncInitializeReq; #define sz_xSyncInitializeReq 8 typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD8 majorVersion; CARD8 minorVersion; CARD16 pad; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xSyncInitializeReply; #define sz_xSyncInitializeReply 32 /* * ListSystemCounters */ typedef struct _xSyncListSystemCounters { CARD8 reqType; CARD8 syncReqType; CARD16 length; } xSyncListSystemCountersReq; #define sz_xSyncListSystemCountersReq 4 typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; INT32 nCounters; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xSyncListSystemCountersReply; #define sz_xSyncListSystemCountersReply 32 typedef struct { XSyncCounter counter; INT32 resolution_hi; CARD32 resolution_lo; CARD16 name_length; } xSyncSystemCounter; #define sz_xSyncSystemCounter 14 /* * Create Counter */ typedef struct _xSyncCreateCounterReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncCounter cid; INT32 initial_value_hi; CARD32 initial_value_lo; } xSyncCreateCounterReq; #define sz_xSyncCreateCounterReq 16 /* * Change Counter */ typedef struct _xSyncChangeCounterReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncCounter cid; INT32 value_hi; CARD32 value_lo; } xSyncChangeCounterReq; #define sz_xSyncChangeCounterReq 16 /* * Set Counter */ typedef struct _xSyncSetCounterReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncCounter cid; INT32 value_hi; CARD32 value_lo; } xSyncSetCounterReq; #define sz_xSyncSetCounterReq 16 /* * Destroy Counter */ typedef struct _xSyncDestroyCounterReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncCounter counter; } xSyncDestroyCounterReq; #define sz_xSyncDestroyCounterReq 8 /* * Query Counter */ typedef struct _xSyncQueryCounterReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncCounter counter; } xSyncQueryCounterReq; #define sz_xSyncQueryCounterReq 8 typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; INT32 value_hi; CARD32 value_lo; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xSyncQueryCounterReply; #define sz_xSyncQueryCounterReply 32 /* * Await */ typedef struct _xSyncAwaitReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; } xSyncAwaitReq; #define sz_xSyncAwaitReq 4 typedef struct _xSyncWaitCondition { XSyncCounter counter; CARD32 value_type; INT32 wait_value_hi; CARD32 wait_value_lo; CARD32 test_type; INT32 event_threshold_hi; CARD32 event_threshold_lo; } xSyncWaitCondition; #define sz_xSyncWaitCondition 28 /* * Create Alarm */ typedef struct _xSyncCreateAlarmReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncAlarm id; CARD32 valueMask; } xSyncCreateAlarmReq; #define sz_xSyncCreateAlarmReq 12 /* * Destroy Alarm */ typedef struct _xSyncDestroyAlarmReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncAlarm alarm; } xSyncDestroyAlarmReq; #define sz_xSyncDestroyAlarmReq 8 /* * Query Alarm */ typedef struct _xSyncQueryAlarmReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncAlarm alarm; } xSyncQueryAlarmReq; #define sz_xSyncQueryAlarmReq 8 typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; XSyncCounter counter; CARD32 value_type; INT32 wait_value_hi; CARD32 wait_value_lo; CARD32 test_type; INT32 delta_hi; CARD32 delta_lo; BOOL events; BYTE state; BYTE pad0; BYTE pad1; } xSyncQueryAlarmReply; #define sz_xSyncQueryAlarmReply 40 /* * Change Alarm */ typedef struct _xSyncChangeAlarmReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncAlarm alarm; CARD32 valueMask; } xSyncChangeAlarmReq; #define sz_xSyncChangeAlarmReq 12 /* * SetPriority */ typedef struct _xSyncSetPriority{ CARD8 reqType; CARD8 syncReqType; CARD16 length; CARD32 id; INT32 priority; } xSyncSetPriorityReq; #define sz_xSyncSetPriorityReq 12 /* * Get Priority */ typedef struct _xSyncGetPriority{ CARD8 reqType; CARD8 syncReqType; CARD16 length; CARD32 id; /*XXX XID? */ } xSyncGetPriorityReq; #define sz_xSyncGetPriorityReq 8 typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; INT32 priority; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xSyncGetPriorityReply; #define sz_xSyncGetPriorityReply 32 /* * Create Fence */ typedef struct _xSyncCreateFenceReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; Drawable d; XSyncFence fid; BOOL initially_triggered; CARD8 pad0; CARD16 pad1; } xSyncCreateFenceReq; #define sz_xSyncCreateFenceReq 16 /* * Put a fence object in the "triggered" state. */ typedef struct _xSyncTriggerFenceReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncFence fid; } xSyncTriggerFenceReq; #define sz_xSyncTriggerFenceReq 8 /* * Put a fence in the "untriggered" state. */ typedef struct _xSyncResetFenceReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncFence fid; } xSyncResetFenceReq; #define sz_xSyncResetFenceReq 8 /* * Destroy a fence object */ typedef struct _xSyncDestroyFenceReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncFence fid; } xSyncDestroyFenceReq; #define sz_xSyncDestroyFenceReq 8 /* * Query a fence object */ typedef struct _xSyncQueryFenceReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; XSyncFence fid; } xSyncQueryFenceReq; #define sz_xSyncQueryFenceReq 8 /* * Wait for any of a list of fence sync objects * to reach the "triggered" state. */ typedef struct _xSyncAwaitFenceReq { CARD8 reqType; CARD8 syncReqType; CARD16 length; } xSyncAwaitFenceReq; #define sz_xSyncAwaitFenceReq 4 typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; BOOL triggered; BYTE pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xSyncQueryFenceReply; #define sz_xSyncQueryFenceReply 32 /* * Events */ typedef struct _xSyncCounterNotifyEvent { BYTE type; BYTE kind; CARD16 sequenceNumber; XSyncCounter counter; INT32 wait_value_hi; CARD32 wait_value_lo; INT32 counter_value_hi; CARD32 counter_value_lo; CARD32 time; CARD16 count; BOOL destroyed; BYTE pad0; } xSyncCounterNotifyEvent; typedef struct _xSyncAlarmNotifyEvent { BYTE type; BYTE kind; CARD16 sequenceNumber; XSyncAlarm alarm; INT32 counter_value_hi; CARD32 counter_value_lo; INT32 alarm_value_hi; CARD32 alarm_value_lo; CARD32 time; CARD8 state; BYTE pad0; BYTE pad1; BYTE pad2; } xSyncAlarmNotifyEvent; #undef XSyncCounter #undef XSyncAlarm #undef XSyncFence #undef Drawable #endif /* _SYNCPROTO_H_ */ X11/extensions/dbeproto.h000064400000016257151027430550011320 0ustar00/****************************************************************************** * * Copyright (c) 1994, 1995 Hewlett-Packard Company * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL HEWLETT-PACKARD COMPANY BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of the Hewlett-Packard * Company shall not be used in advertising or otherwise to promote the * sale, use or other dealings in this Software without prior written * authorization from the Hewlett-Packard Company. * * Header file for Xlib-related DBE * *****************************************************************************/ #ifndef DBE_PROTO_H #define DBE_PROTO_H #include /* Request values used in (S)ProcDbeDispatch() */ #define X_DbeGetVersion 0 #define X_DbeAllocateBackBufferName 1 #define X_DbeDeallocateBackBufferName 2 #define X_DbeSwapBuffers 3 #define X_DbeBeginIdiom 4 #define X_DbeEndIdiom 5 #define X_DbeGetVisualInfo 6 #define X_DbeGetBackBufferAttributes 7 typedef CARD8 xDbeSwapAction; typedef CARD32 xDbeBackBuffer; /* TYPEDEFS */ /* Protocol data types */ typedef struct { CARD32 window; /* window */ xDbeSwapAction swapAction; /* swap action */ CARD8 pad1; /* unused */ CARD16 pad2; } xDbeSwapInfo; typedef struct { CARD32 visualID; /* associated visual */ CARD8 depth; /* depth of visual */ CARD8 perfLevel; /* performance level hint */ CARD16 pad1; } xDbeVisInfo; #define sz_xDbeVisInfo 8 typedef struct { CARD32 n; /* number of visual info items in list */ } xDbeScreenVisInfo; /* followed by n xDbeVisInfo items */ typedef struct { CARD32 window; /* window */ } xDbeBufferAttributes; /* Requests and replies */ typedef struct { CARD8 reqType; /* major-opcode: always codes->major_opcode */ CARD8 dbeReqType; /* minor-opcode: always X_DbeGetVersion (0) */ CARD16 length; /* request length: (2) */ CARD8 majorVersion; /* client-major-version */ CARD8 minorVersion; /* client-minor-version */ CARD16 unused; /* unused */ } xDbeGetVersionReq; #define sz_xDbeGetVersionReq 8 typedef struct { BYTE type; /* Reply: X_Reply (1) */ CARD8 unused; /* unused */ CARD16 sequenceNumber; /* sequence number */ CARD32 length; /* reply length: (0) */ CARD8 majorVersion; /* server-major-version */ CARD8 minorVersion; /* server-minor-version */ CARD16 pad1; /* unused */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xDbeGetVersionReply; #define sz_xDbeGetVersionReply 32 typedef struct { CARD8 reqType; /* major-opcode: codes->major_opcode */ CARD8 dbeReqType; /* X_DbeAllocateBackBufferName (1) */ CARD16 length; /* request length: (4) */ CARD32 window; /* window */ xDbeBackBuffer buffer; /* back buffer name */ xDbeSwapAction swapAction; /* swap action hint */ CARD8 pad1; /* unused */ CARD16 pad2; } xDbeAllocateBackBufferNameReq; #define sz_xDbeAllocateBackBufferNameReq 16 typedef struct { CARD8 reqType; /* major-opcode: codes->major_opcode */ CARD8 dbeReqType; /* X_DbeDeallocateBackBufferName (2) */ CARD16 length; /* request length: (2) */ xDbeBackBuffer buffer; /* back buffer name */ } xDbeDeallocateBackBufferNameReq; #define sz_xDbeDeallocateBackBufferNameReq 8 typedef struct { CARD8 reqType; /* major-opcode: always codes->major_opcode */ CARD8 dbeReqType; /* minor-opcode: always X_DbeSwapBuffers (3) */ CARD16 length; /* request length: (2+2n) */ CARD32 n; /* n, number of window/swap action pairs */ } xDbeSwapBuffersReq; /* followed by n window/swap action pairs */ #define sz_xDbeSwapBuffersReq 8 typedef struct { CARD8 reqType; /* major-opcode: always codes->major_opcode */ CARD8 dbeReqType; /* minor-opcode: always X_DbeBeginIdom (4) */ CARD16 length; /* request length: (1) */ } xDbeBeginIdiomReq; #define sz_xDbeBeginIdiomReq 4 typedef struct { CARD8 reqType; /* major-opcode: always codes->major_opcode */ CARD8 dbeReqType; /* minor-opcode: always X_DbeEndIdom (5) */ CARD16 length; /* request length: (1) */ } xDbeEndIdiomReq; #define sz_xDbeEndIdiomReq 4 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 dbeReqType; /* always X_DbeGetVisualInfo (6) */ CARD16 length; /* request length: (2+n) */ CARD32 n; /* n, number of drawables in list */ } xDbeGetVisualInfoReq; /* followed by n drawables */ #define sz_xDbeGetVisualInfoReq 8 typedef struct { BYTE type; /* Reply: X_Reply (1) */ CARD8 unused; /* unused */ CARD16 sequenceNumber; /* sequence number */ CARD32 length; /* reply length */ CARD32 m; /* m, number of visual infos in list */ CARD32 pad1; /* unused */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDbeGetVisualInfoReply; /* followed by m visual infos */ #define sz_xDbeGetVisualInfoReply 32 typedef struct { CARD8 reqType; /* always codes->major_opcode */ CARD8 dbeReqType; /* X_DbeGetBackBufferAttributes (7) */ CARD16 length; /* request length: (2) */ xDbeBackBuffer buffer; /* back buffer name */ } xDbeGetBackBufferAttributesReq; #define sz_xDbeGetBackBufferAttributesReq 8 typedef struct { BYTE type; /* Reply: X_Reply (1) */ CARD8 unused; /* unused */ CARD16 sequenceNumber; /* sequence number */ CARD32 length; /* reply length: (0) */ CARD32 attributes; /* attributes */ CARD32 pad1; /* unused */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDbeGetBackBufferAttributesReply; #define sz_xDbeGetBackBufferAttributesReply 32 #endif /* DBE_PROTO_H */ X11/extensions/shmstr.h000064400000004113151027430550011006 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ /* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */ #ifndef _SHMSTR_H_ #define _SHMSTR_H_ #include #ifdef _XSHM_SERVER_ #define XSHM_PUT_IMAGE_ARGS \ DrawablePtr /* dst */, \ GCPtr /* pGC */, \ int /* depth */, \ unsigned int /* format */, \ int /* w */, \ int /* h */, \ int /* sx */, \ int /* sy */, \ int /* sw */, \ int /* sh */, \ int /* dx */, \ int /* dy */, \ char * /* data */ #define XSHM_CREATE_PIXMAP_ARGS \ ScreenPtr /* pScreen */, \ int /* width */, \ int /* height */, \ int /* depth */, \ char * /* addr */ typedef struct _ShmFuncs { PixmapPtr (* CreatePixmap)(XSHM_CREATE_PIXMAP_ARGS); void (* PutImage)(XSHM_PUT_IMAGE_ARGS); } ShmFuncs, *ShmFuncsPtr; #endif #endif /* _SHMSTR_H_ */ X11/extensions/xfixeswire.h000064400000012424151027430550011667 0ustar00/* * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * Copyright 2010 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * Copyright © 2002 Keith Packard, member of The XFree86 Project, Inc. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _XFIXESWIRE_H_ #define _XFIXESWIRE_H_ #define XFIXES_NAME "XFIXES" #define XFIXES_MAJOR 5 #define XFIXES_MINOR 0 /*************** Version 1 ******************/ #define X_XFixesQueryVersion 0 #define X_XFixesChangeSaveSet 1 #define X_XFixesSelectSelectionInput 2 #define X_XFixesSelectCursorInput 3 #define X_XFixesGetCursorImage 4 /*************** Version 2 ******************/ #define X_XFixesCreateRegion 5 #define X_XFixesCreateRegionFromBitmap 6 #define X_XFixesCreateRegionFromWindow 7 #define X_XFixesCreateRegionFromGC 8 #define X_XFixesCreateRegionFromPicture 9 #define X_XFixesDestroyRegion 10 #define X_XFixesSetRegion 11 #define X_XFixesCopyRegion 12 #define X_XFixesUnionRegion 13 #define X_XFixesIntersectRegion 14 #define X_XFixesSubtractRegion 15 #define X_XFixesInvertRegion 16 #define X_XFixesTranslateRegion 17 #define X_XFixesRegionExtents 18 #define X_XFixesFetchRegion 19 #define X_XFixesSetGCClipRegion 20 #define X_XFixesSetWindowShapeRegion 21 #define X_XFixesSetPictureClipRegion 22 #define X_XFixesSetCursorName 23 #define X_XFixesGetCursorName 24 #define X_XFixesGetCursorImageAndName 25 #define X_XFixesChangeCursor 26 #define X_XFixesChangeCursorByName 27 /*************** Version 3 ******************/ #define X_XFixesExpandRegion 28 /*************** Version 4 ******************/ #define X_XFixesHideCursor 29 #define X_XFixesShowCursor 30 /*************** Version 5 ******************/ #define X_XFixesCreatePointerBarrier 31 #define X_XFixesDestroyPointerBarrier 32 #define XFixesNumberRequests (X_XFixesDestroyPointerBarrier+1) /* Selection events share one event number */ #define XFixesSelectionNotify 0 /* Within the selection, the 'subtype' field distinguishes */ #define XFixesSetSelectionOwnerNotify 0 #define XFixesSelectionWindowDestroyNotify 1 #define XFixesSelectionClientCloseNotify 2 #define XFixesSetSelectionOwnerNotifyMask (1L << 0) #define XFixesSelectionWindowDestroyNotifyMask (1L << 1) #define XFixesSelectionClientCloseNotifyMask (1L << 2) /* There's only one cursor event so far */ #define XFixesCursorNotify 1 #define XFixesDisplayCursorNotify 0 #define XFixesDisplayCursorNotifyMask (1L << 0) #define XFixesNumberEvents (2) /* errors */ #define BadRegion 0 #define BadBarrier 1 #define XFixesNumberErrors (BadBarrier+1) #define SaveSetNearest 0 #define SaveSetRoot 1 #define SaveSetMap 0 #define SaveSetUnmap 1 /*************** Version 2 ******************/ #define WindowRegionBounding 0 #define WindowRegionClip 1 /*************** Version 5 ******************/ #define BarrierPositiveX (1L << 0) #define BarrierPositiveY (1L << 1) #define BarrierNegativeX (1L << 2) #define BarrierNegativeY (1L << 3) #endif /* _XFIXESWIRE_H_ */ X11/extensions/recordconst.h000064400000004020151027430550012010 0ustar00/*************************************************************************** * Copyright 1995 Network Computing Devices * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Network Computing Devices * not be used in advertising or publicity pertaining to distribution * of the software without specific, written prior permission. * * NETWORK COMPUTING DEVICES DISCLAIMs ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL NETWORK COMPUTING DEVICES BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **************************************************************************/ #ifndef _RECORDCONST_H_ #define _RECORDCONST_H_ #define RECORD_NAME "RECORD" #define RECORD_MAJOR_VERSION 1 #define RECORD_MINOR_VERSION 13 #define RECORD_LOWEST_MAJOR_VERSION 1 #define RECORD_LOWEST_MINOR_VERSION 12 #define XRecordBadContext 0 /* Not a valid RC */ #define RecordNumErrors (XRecordBadContext + 1) #define RecordNumEvents 0L /* * Constants for arguments of various requests */ #define XRecordFromServerTime 0x01 #define XRecordFromClientTime 0x02 #define XRecordFromClientSequence 0x04 #define XRecordCurrentClients 1 #define XRecordFutureClients 2 #define XRecordAllClients 3 #define XRecordFromServer 0 #define XRecordFromClient 1 #define XRecordClientStarted 2 #define XRecordClientDied 3 #define XRecordStartOfData 4 #define XRecordEndOfData 5 #endif /* _RECORD_H_ */ X11/extensions/secur.h000064400000004135151027430550010613 0ustar00/* Copyright 1996, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _SECUR_H #define _SECUR_H #define SECURITY_EXTENSION_NAME "SECURITY" #define SECURITY_MAJOR_VERSION 1 #define SECURITY_MINOR_VERSION 0 #define XSecurityNumberEvents 1 #define XSecurityNumberErrors 2 #define XSecurityBadAuthorization 0 #define XSecurityBadAuthorizationProtocol 1 /* trust levels */ #define XSecurityClientTrusted 0 #define XSecurityClientUntrusted 1 /* authorization attribute masks */ #define XSecurityTimeout (1<<0) #define XSecurityTrustLevel (1<<1) #define XSecurityGroup (1<<2) #define XSecurityEventMask (1<<3) #define XSecurityAllAuthorizationAttributes \ (XSecurityTimeout | XSecurityTrustLevel | XSecurityGroup | XSecurityEventMask) /* event masks */ #define XSecurityAuthorizationRevokedMask (1<<0) #define XSecurityAllEventMasks XSecurityAuthorizationRevokedMask /* event offsets */ #define XSecurityAuthorizationRevoked 0 #define XSecurityAuthorizationName "XC-QUERY-SECURITY-1" #define XSecurityAuthorizationNameLen 19 #endif /* _SECUR_H */ X11/extensions/dmxproto.h000064400000032037151027430550011350 0ustar00/* * Copyright 2002-2004 Red Hat Inc., Durham, North Carolina. * * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation on the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* * Authors: * Rickard E. (Rik) Faith * */ /** \file * This file describes the structures necessary to implement the wire * protocol for the DMX protocol extension. It should be included only * in files that implement the client-side (or server-side) part of the * protocol (i.e., client-side applications should \b not include this * file). */ #ifndef _DMXSTR_H_ #define _DMXSTR_H_ #define DMX_EXTENSION_NAME "DMX" #define DMX_EXTENSION_MAJOR 2 #define DMX_EXTENSION_MINOR 2 #define DMX_EXTENSION_PATCH 20040604 /* These values must be larger than LastExtensionError. The values in dmxext.h and dmxproto.h *MUST* match. */ #define DMX_BAD_XINERAMA 1001 #define DMX_BAD_VALUE 1002 #define X_DMXQueryVersion 0 #define X_DMXGetScreenCount 1 #define X_DMXGetScreenInformationDEPRECATED 2 #define X_DMXGetWindowAttributes 3 #define X_DMXGetInputCount 4 #define X_DMXGetInputAttributes 5 #define X_DMXForceWindowCreationDEPRECATED 6 #define X_DMXReconfigureScreenDEPRECATED 7 #define X_DMXSync 8 #define X_DMXForceWindowCreation 9 #define X_DMXGetScreenAttributes 10 #define X_DMXChangeScreensAttributes 11 #define X_DMXAddScreen 12 #define X_DMXRemoveScreen 13 #define X_DMXGetDesktopAttributes 14 #define X_DMXChangeDesktopAttributes 15 #define X_DMXAddInput 16 #define X_DMXRemoveInput 17 /** Wire-level description of DMXQueryVersion protocol request. */ typedef struct { CARD8 reqType; /* dmxcode */ CARD8 dmxReqType; /* X_DMXQueryVersion */ CARD16 length; } xDMXQueryVersionReq; #define sz_xDMXQueryVersionReq 4 /** Wire-level description of DMXQueryVersion protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 ununsed; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 patchVersion; CARD32 pad0; CARD32 pad1; CARD32 pad2; } xDMXQueryVersionReply; #define sz_xDMXQueryVersionReply 32 /** Wire-level description of DMXSync protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXSync */ CARD16 length; } xDMXSyncReq; #define sz_xDMXSyncReq 4 /** Wire-level description of DMXSync protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXSyncReply; #define sz_xDMXSyncReply 32 /** Wire-level description of DMXForceWindowCreation protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXForceWindowCreation */ CARD16 length; CARD32 window; } xDMXForceWindowCreationReq; #define sz_xDMXForceWindowCreationReq 8 /** Wire-level description of DMXForceWindowCreation protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXForceWindowCreationReply; #define sz_xDMXForceWindowCreationReply 32 /** Wire-level description of DMXGetScreenCount protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXGetScreenCount */ CARD16 length; } xDMXGetScreenCountReq; #define sz_xDMXGetScreenCountReq 4 /** Wire-level description of DMXGetScreenCount protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 screenCount; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXGetScreenCountReply; #define sz_xDMXGetScreenCountReply 32 /** Wire-level description of DMXGetScreenAttributes protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXGetScreenAttributes */ CARD16 length; CARD32 physicalScreen; } xDMXGetScreenAttributesReq; #define sz_xDMXGetScreenAttributesReq 8 /** Wire-level description of DMXGetScreenAttributes protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 displayNameLength; CARD32 logicalScreen; CARD16 screenWindowWidth; CARD16 screenWindowHeight; INT16 screenWindowXoffset; INT16 screenWindowYoffset; CARD16 rootWindowWidth; CARD16 rootWindowHeight; INT16 rootWindowXoffset; INT16 rootWindowYoffset; INT16 rootWindowXorigin; INT16 rootWindowYorigin; } xDMXGetScreenAttributesReply; #define sz_xDMXGetScreenAttributesReply 36 /** Wire-level description of DMXChangeScreensAttributes protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXChangeScreensAttributes */ CARD16 length; CARD32 screenCount; CARD32 maskCount; } xDMXChangeScreensAttributesReq; #define sz_xDMXChangeScreensAttributesReq 12 /** Wire-level description of DMXChangeScreensAttributes protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 errorScreen; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xDMXChangeScreensAttributesReply; #define sz_xDMXChangeScreensAttributesReply 32 /** Wire-level description of DMXAddScreen protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXAddScreen */ CARD16 length; CARD32 displayNameLength; CARD32 physicalScreen; CARD32 valueMask; } xDMXAddScreenReq; #define sz_xDMXAddScreenReq 16 /** Wire-level description of DMXAddScreen protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 physicalScreen; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xDMXAddScreenReply; #define sz_xDMXAddScreenReply 32 /** Wire-level description of DMXRemoveScreen protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXRemoveScreen */ CARD16 length; CARD32 physicalScreen; } xDMXRemoveScreenReq; #define sz_xDMXRemoveScreenReq 8 /** Wire-level description of DMXRemoveScreen protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXRemoveScreenReply; #define sz_xDMXRemoveScreenReply 32 /** Wire-level description of DMXGetWindowAttributes protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXGetWindowAttributes */ CARD16 length; CARD32 window; } xDMXGetWindowAttributesReq; #define sz_xDMXGetWindowAttributesReq 8 /** Wire-level description of DMXGetWindowAttributes protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 screenCount; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXGetWindowAttributesReply; #define sz_xDMXGetWindowAttributesReply 32 /** Wire-level description of DMXGetDesktopAttributes protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXGetDesktopAttributes */ CARD16 length; } xDMXGetDesktopAttributesReq; #define sz_xDMXGetDesktopAttributesReq 4 /** Wire-level description of DMXGetDesktopAttributes protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; INT16 width; INT16 height; INT16 shiftX; INT16 shiftY; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xDMXGetDesktopAttributesReply; #define sz_xDMXGetDesktopAttributesReply 32 /** Wire-level description of DMXChangeDesktopAttributes protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXChangeDesktopAttributes */ CARD16 length; CARD32 valueMask; } xDMXChangeDesktopAttributesReq; #define sz_xDMXChangeDesktopAttributesReq 8 /** Wire-level description of DMXChangeDesktopAttributes protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXChangeDesktopAttributesReply; #define sz_xDMXChangeDesktopAttributesReply 32 /** Wire-level description of DMXGetInputCount protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXGetInputCount */ CARD16 length; } xDMXGetInputCountReq; #define sz_xDMXGetInputCountReq 4 /** Wire-level description of DMXGetInputCount protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 inputCount; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXGetInputCountReply; #define sz_xDMXGetInputCountReply 32 /** Wire-level description of DMXGetInputAttributes protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXGetInputAttributes */ CARD16 length; CARD32 deviceId; } xDMXGetInputAttributesReq; #define sz_xDMXGetInputAttributesReq 8 /** Wire-level description of DMXGetInputAttributes protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 inputType; CARD32 physicalScreen; CARD32 physicalId; CARD32 nameLength; BOOL isCore; BOOL sendsCore; BOOL detached; CARD8 pad0; CARD32 pad1; } xDMXGetInputAttributesReply; #define sz_xDMXGetInputAttributesReply 32 /** Wire-level description of DMXAddInput protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXAddInput */ CARD16 length; CARD32 displayNameLength; CARD32 valueMask; } xDMXAddInputReq; #define sz_xDMXAddInputReq 12 /** Wire-level description of DMXAddInput protocol reply. */ typedef struct { BYTE type; /* X_Reply */ CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 physicalId; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xDMXAddInputReply; #define sz_xDMXAddInputReply 32 /** Wire-level description of DMXRemoveInput protocol request. */ typedef struct { CARD8 reqType; /* DMXCode */ CARD8 dmxReqType; /* X_DMXRemoveInput */ CARD16 length; CARD32 physicalId; } xDMXRemoveInputReq; #define sz_xDMXRemoveInputReq 8 /** Wire-level description of DMXRemoveInput protocol reply. */ typedef struct { BYTE type; CARD8 unused; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xDMXRemoveInputReply; #define sz_xDMXRemoveInputReply 32 #endif X11/extensions/shm.h000064400000003155151027430560010263 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. ********************************************************/ /* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */ #ifndef _SHM_H_ #define _SHM_H_ #define SHMNAME "MIT-SHM" #define SHM_MAJOR_VERSION 1 /* current version numbers */ #define SHM_MINOR_VERSION 2 #define ShmCompletion 0 #define ShmNumberEvents (ShmCompletion + 1) #define BadShmSeg 0 #define ShmNumberErrors (BadShmSeg + 1) #endif /* _SHM_H_ */ X11/extensions/XKBgeom.h000064400000036700151027430560010772 0ustar00/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XKBGEOM_H_ #define _XKBGEOM_H_ #include #ifdef XKB_IN_SERVER #define XkbAddGeomKeyAlias SrvXkbAddGeomKeyAlias #define XkbAddGeomColor SrvXkbAddGeomColor #define XkbAddGeomDoodad SrvXkbAddGeomDoodad #define XkbAddGeomKey SrvXkbAddGeomKey #define XkbAddGeomOutline SrvXkbAddGeomOutline #define XkbAddGeomOverlay SrvXkbAddGeomOverlay #define XkbAddGeomOverlayRow SrvXkbAddGeomOverlayRow #define XkbAddGeomOverlayKey SrvXkbAddGeomOverlayKey #define XkbAddGeomProperty SrvXkbAddGeomProperty #define XkbAddGeomRow SrvXkbAddGeomRow #define XkbAddGeomSection SrvXkbAddGeomSection #define XkbAddGeomShape SrvXkbAddGeomShape #define XkbAllocGeomKeyAliases SrvXkbAllocGeomKeyAliases #define XkbAllocGeomColors SrvXkbAllocGeomColors #define XkbAllocGeomDoodads SrvXkbAllocGeomDoodads #define XkbAllocGeomKeys SrvXkbAllocGeomKeys #define XkbAllocGeomOutlines SrvXkbAllocGeomOutlines #define XkbAllocGeomPoints SrvXkbAllocGeomPoints #define XkbAllocGeomProps SrvXkbAllocGeomProps #define XkbAllocGeomRows SrvXkbAllocGeomRows #define XkbAllocGeomSectionDoodads SrvXkbAllocGeomSectionDoodads #define XkbAllocGeomSections SrvXkbAllocGeomSections #define XkbAllocGeomOverlays SrvXkbAllocGeomOverlays #define XkbAllocGeomOverlayRows SrvXkbAllocGeomOverlayRows #define XkbAllocGeomOverlayKeys SrvXkbAllocGeomOverlayKeys #define XkbAllocGeomShapes SrvXkbAllocGeomShapes #define XkbAllocGeometry SrvXkbAllocGeometry #define XkbFreeGeomKeyAliases SrvXkbFreeGeomKeyAliases #define XkbFreeGeomColors SrvXkbFreeGeomColors #define XkbFreeGeomDoodads SrvXkbFreeGeomDoodads #define XkbFreeGeomProperties SrvXkbFreeGeomProperties #define XkbFreeGeomOverlayKeys SrvXkbFreeGeomOverlayKeys #define XkbFreeGeomOverlayRows SrvXkbFreeGeomOverlayRows #define XkbFreeGeomOverlays SrvXkbFreeGeomOverlays #define XkbFreeGeomKeys SrvXkbFreeGeomKeys #define XkbFreeGeomRows SrvXkbFreeGeomRows #define XkbFreeGeomSections SrvXkbFreeGeomSections #define XkbFreeGeomPoints SrvXkbFreeGeomPoints #define XkbFreeGeomOutlines SrvXkbFreeGeomOutlines #define XkbFreeGeomShapes SrvXkbFreeGeomShapes #define XkbFreeGeometry SrvXkbFreeGeometry #endif typedef struct _XkbProperty { char *name; char *value; } XkbPropertyRec,*XkbPropertyPtr; typedef struct _XkbColor { unsigned int pixel; char * spec; } XkbColorRec,*XkbColorPtr; typedef struct _XkbPoint { short x; short y; } XkbPointRec, *XkbPointPtr; typedef struct _XkbBounds { short x1,y1; short x2,y2; } XkbBoundsRec, *XkbBoundsPtr; #define XkbBoundsWidth(b) (((b)->x2)-((b)->x1)) #define XkbBoundsHeight(b) (((b)->y2)-((b)->y1)) /* * In the following structs, this pattern is used for dynamically sized arrays: * foo is an array for which sz_foo entries are allocated & num_foo are used */ typedef struct _XkbOutline { unsigned short num_points; unsigned short sz_points; unsigned short corner_radius; XkbPointPtr points; } XkbOutlineRec, *XkbOutlinePtr; typedef struct _XkbShape { Atom name; unsigned short num_outlines; unsigned short sz_outlines; XkbOutlinePtr outlines; XkbOutlinePtr approx; XkbOutlinePtr primary; XkbBoundsRec bounds; } XkbShapeRec, *XkbShapePtr; #define XkbOutlineIndex(s,o) ((int)((o)-&(s)->outlines[0])) typedef struct _XkbShapeDoodad { Atom name; unsigned char type; unsigned char priority; short top; short left; short angle; unsigned short color_ndx; unsigned short shape_ndx; } XkbShapeDoodadRec, *XkbShapeDoodadPtr; #define XkbShapeDoodadColor(g,d) (&(g)->colors[(d)->color_ndx]) #define XkbShapeDoodadShape(g,d) (&(g)->shapes[(d)->shape_ndx]) #define XkbSetShapeDoodadColor(g,d,c) ((d)->color_ndx= (c)-&(g)->colors[0]) #define XkbSetShapeDoodadShape(g,d,s) ((d)->shape_ndx= (s)-&(g)->shapes[0]) typedef struct _XkbTextDoodad { Atom name; unsigned char type; unsigned char priority; short top; short left; short angle; short width; short height; unsigned short color_ndx; char * text; char * font; } XkbTextDoodadRec, *XkbTextDoodadPtr; #define XkbTextDoodadColor(g,d) (&(g)->colors[(d)->color_ndx]) #define XkbSetTextDoodadColor(g,d,c) ((d)->color_ndx= (c)-&(g)->colors[0]) typedef struct _XkbIndicatorDoodad { Atom name; unsigned char type; unsigned char priority; short top; short left; short angle; unsigned short shape_ndx; unsigned short on_color_ndx; unsigned short off_color_ndx; } XkbIndicatorDoodadRec, *XkbIndicatorDoodadPtr; #define XkbIndicatorDoodadShape(g,d) (&(g)->shapes[(d)->shape_ndx]) #define XkbIndicatorDoodadOnColor(g,d) (&(g)->colors[(d)->on_color_ndx]) #define XkbIndicatorDoodadOffColor(g,d) (&(g)->colors[(d)->off_color_ndx]) #define XkbSetIndicatorDoodadOnColor(g,d,c) \ ((d)->on_color_ndx= (c)-&(g)->colors[0]) #define XkbSetIndicatorDoodadOffColor(g,d,c) \ ((d)->off_color_ndx= (c)-&(g)->colors[0]) #define XkbSetIndicatorDoodadShape(g,d,s) \ ((d)->shape_ndx= (s)-&(g)->shapes[0]) typedef struct _XkbLogoDoodad { Atom name; unsigned char type; unsigned char priority; short top; short left; short angle; unsigned short color_ndx; unsigned short shape_ndx; char * logo_name; } XkbLogoDoodadRec, *XkbLogoDoodadPtr; #define XkbLogoDoodadColor(g,d) (&(g)->colors[(d)->color_ndx]) #define XkbLogoDoodadShape(g,d) (&(g)->shapes[(d)->shape_ndx]) #define XkbSetLogoDoodadColor(g,d,c) ((d)->color_ndx= (c)-&(g)->colors[0]) #define XkbSetLogoDoodadShape(g,d,s) ((d)->shape_ndx= (s)-&(g)->shapes[0]) typedef struct _XkbAnyDoodad { Atom name; unsigned char type; unsigned char priority; short top; short left; short angle; } XkbAnyDoodadRec, *XkbAnyDoodadPtr; typedef union _XkbDoodad { XkbAnyDoodadRec any; XkbShapeDoodadRec shape; XkbTextDoodadRec text; XkbIndicatorDoodadRec indicator; XkbLogoDoodadRec logo; } XkbDoodadRec, *XkbDoodadPtr; #define XkbUnknownDoodad 0 #define XkbOutlineDoodad 1 #define XkbSolidDoodad 2 #define XkbTextDoodad 3 #define XkbIndicatorDoodad 4 #define XkbLogoDoodad 5 typedef struct _XkbKey { XkbKeyNameRec name; short gap; unsigned char shape_ndx; unsigned char color_ndx; } XkbKeyRec, *XkbKeyPtr; #define XkbKeyShape(g,k) (&(g)->shapes[(k)->shape_ndx]) #define XkbKeyColor(g,k) (&(g)->colors[(k)->color_ndx]) #define XkbSetKeyShape(g,k,s) ((k)->shape_ndx= (s)-&(g)->shapes[0]) #define XkbSetKeyColor(g,k,c) ((k)->color_ndx= (c)-&(g)->colors[0]) typedef struct _XkbRow { short top; short left; unsigned short num_keys; unsigned short sz_keys; int vertical; XkbKeyPtr keys; XkbBoundsRec bounds; } XkbRowRec, *XkbRowPtr; typedef struct _XkbSection { Atom name; unsigned char priority; short top; short left; unsigned short width; unsigned short height; short angle; unsigned short num_rows; unsigned short num_doodads; unsigned short num_overlays; unsigned short sz_rows; unsigned short sz_doodads; unsigned short sz_overlays; XkbRowPtr rows; XkbDoodadPtr doodads; XkbBoundsRec bounds; struct _XkbOverlay *overlays; } XkbSectionRec, *XkbSectionPtr; typedef struct _XkbOverlayKey { XkbKeyNameRec over; XkbKeyNameRec under; } XkbOverlayKeyRec,*XkbOverlayKeyPtr; typedef struct _XkbOverlayRow { unsigned short row_under; unsigned short num_keys; unsigned short sz_keys; XkbOverlayKeyPtr keys; } XkbOverlayRowRec,*XkbOverlayRowPtr; typedef struct _XkbOverlay { Atom name; XkbSectionPtr section_under; unsigned short num_rows; unsigned short sz_rows; XkbOverlayRowPtr rows; XkbBoundsPtr bounds; } XkbOverlayRec,*XkbOverlayPtr; typedef struct _XkbGeometry { Atom name; unsigned short width_mm; unsigned short height_mm; char * label_font; XkbColorPtr label_color; XkbColorPtr base_color; unsigned short sz_properties; unsigned short sz_colors; unsigned short sz_shapes; unsigned short sz_sections; unsigned short sz_doodads; unsigned short sz_key_aliases; unsigned short num_properties; unsigned short num_colors; unsigned short num_shapes; unsigned short num_sections; unsigned short num_doodads; unsigned short num_key_aliases; XkbPropertyPtr properties; XkbColorPtr colors; XkbShapePtr shapes; XkbSectionPtr sections; XkbDoodadPtr doodads; XkbKeyAliasPtr key_aliases; } XkbGeometryRec; #define XkbGeomColorIndex(g,c) ((int)((c)-&(g)->colors[0])) #define XkbGeomPropertiesMask (1<<0) #define XkbGeomColorsMask (1<<1) #define XkbGeomShapesMask (1<<2) #define XkbGeomSectionsMask (1<<3) #define XkbGeomDoodadsMask (1<<4) #define XkbGeomKeyAliasesMask (1<<5) #define XkbGeomAllMask (0x3f) typedef struct _XkbGeometrySizes { unsigned int which; unsigned short num_properties; unsigned short num_colors; unsigned short num_shapes; unsigned short num_sections; unsigned short num_doodads; unsigned short num_key_aliases; } XkbGeometrySizesRec,*XkbGeometrySizesPtr; _XFUNCPROTOBEGIN extern XkbPropertyPtr XkbAddGeomProperty( XkbGeometryPtr /* geom */, char * /* name */, char * /* value */ ); extern XkbKeyAliasPtr XkbAddGeomKeyAlias( XkbGeometryPtr /* geom */, char * /* alias */, char * /* real */ ); extern XkbColorPtr XkbAddGeomColor( XkbGeometryPtr /* geom */, char * /* spec */, unsigned int /* pixel */ ); extern XkbOutlinePtr XkbAddGeomOutline( XkbShapePtr /* shape */, int /* sz_points */ ); extern XkbShapePtr XkbAddGeomShape( XkbGeometryPtr /* geom */, Atom /* name */, int /* sz_outlines */ ); extern XkbKeyPtr XkbAddGeomKey( XkbRowPtr /* row */ ); extern XkbRowPtr XkbAddGeomRow( XkbSectionPtr /* section */, int /* sz_keys */ ); extern XkbSectionPtr XkbAddGeomSection( XkbGeometryPtr /* geom */, Atom /* name */, int /* sz_rows */, int /* sz_doodads */, int /* sz_overlays */ ); extern XkbOverlayPtr XkbAddGeomOverlay( XkbSectionPtr /* section */, Atom /* name */, int /* sz_rows */ ); extern XkbOverlayRowPtr XkbAddGeomOverlayRow( XkbOverlayPtr /* overlay */, int /* row_under */, int /* sz_keys */ ); extern XkbOverlayKeyPtr XkbAddGeomOverlayKey( XkbOverlayPtr /* overlay */, XkbOverlayRowPtr /* row */, char * /* over */, char * /* under */ ); extern XkbDoodadPtr XkbAddGeomDoodad( XkbGeometryPtr /* geom */, XkbSectionPtr /* section */, Atom /* name */ ); extern void XkbFreeGeomKeyAliases( XkbGeometryPtr /* geom */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomColors( XkbGeometryPtr /* geom */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomDoodads( XkbDoodadPtr /* doodads */, int /* nDoodads */, Bool /* freeAll */ ); extern void XkbFreeGeomProperties( XkbGeometryPtr /* geom */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomOverlayKeys( XkbOverlayRowPtr /* row */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomOverlayRows( XkbOverlayPtr /* overlay */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomOverlays( XkbSectionPtr /* section */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomKeys( XkbRowPtr /* row */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomRows( XkbSectionPtr /* section */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomSections( XkbGeometryPtr /* geom */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomPoints( XkbOutlinePtr /* outline */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomOutlines( XkbShapePtr /* shape */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeomShapes( XkbGeometryPtr /* geom */, int /* first */, int /* count */, Bool /* freeAll */ ); extern void XkbFreeGeometry( XkbGeometryPtr /* geom */, unsigned int /* which */, Bool /* freeMap */ ); extern Status XkbAllocGeomProps( XkbGeometryPtr /* geom */, int /* nProps */ ); extern Status XkbAllocGeomKeyAliases( XkbGeometryPtr /* geom */, int /* nAliases */ ); extern Status XkbAllocGeomColors( XkbGeometryPtr /* geom */, int /* nColors */ ); extern Status XkbAllocGeomShapes( XkbGeometryPtr /* geom */, int /* nShapes */ ); extern Status XkbAllocGeomSections( XkbGeometryPtr /* geom */, int /* nSections */ ); extern Status XkbAllocGeomOverlays( XkbSectionPtr /* section */, int /* num_needed */ ); extern Status XkbAllocGeomOverlayRows( XkbOverlayPtr /* overlay */, int /* num_needed */ ); extern Status XkbAllocGeomOverlayKeys( XkbOverlayRowPtr /* row */, int /* num_needed */ ); extern Status XkbAllocGeomDoodads( XkbGeometryPtr /* geom */, int /* nDoodads */ ); extern Status XkbAllocGeomSectionDoodads( XkbSectionPtr /* section */, int /* nDoodads */ ); extern Status XkbAllocGeomOutlines( XkbShapePtr /* shape */, int /* nOL */ ); extern Status XkbAllocGeomRows( XkbSectionPtr /* section */, int /* nRows */ ); extern Status XkbAllocGeomPoints( XkbOutlinePtr /* ol */, int /* nPts */ ); extern Status XkbAllocGeomKeys( XkbRowPtr /* row */, int /* nKeys */ ); extern Status XkbAllocGeometry( XkbDescPtr /* xkb */, XkbGeometrySizesPtr /* sizes */ ); extern Status XkbSetGeometry( Display * /* dpy */, unsigned /* deviceSpec */, XkbGeometryPtr /* geom */ ); extern Bool XkbComputeShapeTop( XkbShapePtr /* shape */, XkbBoundsPtr /* bounds */ ); extern Bool XkbComputeShapeBounds( XkbShapePtr /* shape */ ); extern Bool XkbComputeRowBounds( XkbGeometryPtr /* geom */, XkbSectionPtr /* section */, XkbRowPtr /* row */ ); extern Bool XkbComputeSectionBounds( XkbGeometryPtr /* geom */, XkbSectionPtr /* section */ ); extern char * XkbFindOverlayForKey( XkbGeometryPtr /* geom */, XkbSectionPtr /* wanted */, char * /* under */ ); extern Status XkbGetGeometry( Display * /* dpy */, XkbDescPtr /* xkb */ ); extern Status XkbGetNamedGeometry( Display * /* dpy */, XkbDescPtr /* xkb */, Atom /* name */ ); _XFUNCPROTOEND #endif /* _XKBSTR_H_ */ X11/extensions/bigreqsproto.h000064400000003565151027430560012221 0ustar00/* Copyright 1992, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _BIGREQSPROTO_H_ #define _BIGREQSPROTO_H_ #define X_BigReqEnable 0 #define XBigReqNumberEvents 0 #define XBigReqNumberErrors 0 #define XBigReqExtensionName "BIG-REQUESTS" typedef struct { CARD8 reqType; /* always XBigReqCode */ CARD8 brReqType; /* always X_BigReqEnable */ CARD16 length; } xBigReqEnableReq; #define sz_xBigReqEnableReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 pad0; CARD16 sequenceNumber; CARD32 length; CARD32 max_request_size; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xBigReqEnableReply; #define sz_xBigReqEnableReply 32 typedef struct { CARD8 reqType; CARD8 data; CARD16 zero; CARD32 length; } xBigReq; #endif /* _BIGREQSPROTO_H_ */ X11/extensions/cup.h000064400000002511151027430560010256 0ustar00/* Copyright 1987, 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _CUP_H_ #define _CUP_H_ #define XCUPNAME "TOG-CUP" #define XCUP_MAJOR_VERSION 1 /* current version numbers */ #define XCUP_MINOR_VERSION 0 #define XcupNumberErrors 0 #endif /* _CUP_H_ */ X11/extensions/XResproto.h000064400000012060151027430560011434 0ustar00/* Copyright (c) 2002 XFree86 Inc */ #ifndef _XRESPROTO_H #define _XRESPROTO_H #define XRES_MAJOR_VERSION 1 #define XRES_MINOR_VERSION 2 #define XRES_NAME "X-Resource" /* v1.0 */ #define X_XResQueryVersion 0 #define X_XResQueryClients 1 #define X_XResQueryClientResources 2 #define X_XResQueryClientPixmapBytes 3 /* Version 1.1 has been accidentally released from the version */ /* control and while it doesn't have differences to version 1.0, the */ /* next version is labeled 1.2 in order to remove the risk of confusion. */ /* v1.2 */ #define X_XResQueryClientIds 4 #define X_XResQueryResourceBytes 5 typedef struct { CARD32 resource_base; CARD32 resource_mask; } xXResClient; #define sz_xXResClient 8 typedef struct { CARD32 resource_type; CARD32 count; } xXResType; #define sz_xXResType 8 /* XResQueryVersion */ typedef struct _XResQueryVersion { CARD8 reqType; CARD8 XResReqType; CARD16 length; CARD8 client_major; CARD8 client_minor; CARD16 unused; } xXResQueryVersionReq; #define sz_xXResQueryVersionReq 8 typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD16 server_major; CARD16 server_minor; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXResQueryVersionReply; #define sz_xXResQueryVersionReply 32 /* XResQueryClients */ typedef struct _XResQueryClients { CARD8 reqType; CARD8 XResReqType; CARD16 length; } xXResQueryClientsReq; #define sz_xXResQueryClientsReq 4 typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 num_clients; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXResQueryClientsReply; #define sz_xXResQueryClientsReply 32 /* XResQueryClientResources */ typedef struct _XResQueryClientResources { CARD8 reqType; CARD8 XResReqType; CARD16 length; CARD32 xid; } xXResQueryClientResourcesReq; #define sz_xXResQueryClientResourcesReq 8 typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 num_types; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXResQueryClientResourcesReply; #define sz_xXResQueryClientResourcesReply 32 /* XResQueryClientPixmapBytes */ typedef struct _XResQueryClientPixmapBytes { CARD8 reqType; CARD8 XResReqType; CARD16 length; CARD32 xid; } xXResQueryClientPixmapBytesReq; #define sz_xXResQueryClientPixmapBytesReq 8 typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 bytes; CARD32 bytes_overflow; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXResQueryClientPixmapBytesReply; #define sz_xXResQueryClientPixmapBytesReply 32 /* v1.2 XResQueryClientIds */ #define X_XResClientXIDMask 0x01 #define X_XResLocalClientPIDMask 0x02 typedef struct _XResClientIdSpec { CARD32 client; CARD32 mask; } xXResClientIdSpec; #define sz_xXResClientIdSpec 8 typedef struct _XResClientIdValue { xXResClientIdSpec spec; CARD32 length; // followed by length CARD32s } xXResClientIdValue; #define sz_xResClientIdValue (sz_xXResClientIdSpec + 4) typedef struct _XResQueryClientIds { CARD8 reqType; CARD8 XResReqType; CARD16 length; CARD32 numSpecs; // followed by numSpecs times XResClientIdSpec } xXResQueryClientIdsReq; #define sz_xXResQueryClientIdsReq 8 typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 numIds; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; // followed by numIds times XResClientIdValue } xXResQueryClientIdsReply; #define sz_xXResQueryClientIdsReply 32 /* v1.2 XResQueryResourceBytes */ typedef struct _XResResourceIdSpec { CARD32 resource; CARD32 type; } xXResResourceIdSpec; #define sz_xXResResourceIdSpec 8 typedef struct _XResQueryResourceBytes { CARD8 reqType; CARD8 XResReqType; CARD16 length; CARD32 client; CARD32 numSpecs; // followed by numSpecs times XResResourceIdSpec } xXResQueryResourceBytesReq; #define sz_xXResQueryResourceBytesReq 12 typedef struct _XResResourceSizeSpec { xXResResourceIdSpec spec; CARD32 bytes; CARD32 refCount; CARD32 useCount; } xXResResourceSizeSpec; #define sz_xXResResourceSizeSpec (sz_xXResResourceIdSpec + 12) typedef struct _XResResourceSizeValue { xXResResourceSizeSpec size; CARD32 numCrossReferences; // followed by numCrossReferences times XResResourceSizeSpec } xXResResourceSizeValue; #define sz_xXResResourceSizeValue (sz_xXResResourceSizeSpec + 4) typedef struct { CARD8 type; CARD8 pad1; CARD16 sequenceNumber; CARD32 length; CARD32 numSizes; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; // followed by numSizes times XResResourceSizeValue } xXResQueryResourceBytesReply; #define sz_xXResQueryResourceBytesReply 32 #endif /* _XRESPROTO_H */ X11/extensions/XKBstr.h000064400000046256151027430560010662 0ustar00/************************************************************ Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics not be used in advertising or publicity pertaining to distribution of the software without specific prior written permission. Silicon Graphics makes no representation about the suitability of this software for any purpose. It is provided "as is" without any express or implied warranty. SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XKBSTR_H_ #define _XKBSTR_H_ #include #define XkbCharToInt(v) ((v)&0x80?(int)((v)|(~0xff)):(int)((v)&0x7f)) #define XkbIntTo2Chars(i,h,l) (((h)=((i>>8)&0xff)),((l)=((i)&0xff))) #define Xkb2CharsToInt(h,l) ((short)(((h)<<8)|(l))) /* * The Xkb structs are full of implicit padding to properly align members. * We can't clean that up without breaking ABI, so tell clang not to bother * complaining about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif /* * Common data structures and access macros */ typedef struct _XkbStateRec { unsigned char group; unsigned char locked_group; unsigned short base_group; unsigned short latched_group; unsigned char mods; unsigned char base_mods; unsigned char latched_mods; unsigned char locked_mods; unsigned char compat_state; unsigned char grab_mods; unsigned char compat_grab_mods; unsigned char lookup_mods; unsigned char compat_lookup_mods; unsigned short ptr_buttons; } XkbStateRec,*XkbStatePtr; #define XkbModLocks(s) ((s)->locked_mods) #define XkbStateMods(s) ((s)->base_mods|(s)->latched_mods|XkbModLocks(s)) #define XkbGroupLock(s) ((s)->locked_group) #define XkbStateGroup(s) ((s)->base_group+(s)->latched_group+XkbGroupLock(s)) #define XkbStateFieldFromRec(s) XkbBuildCoreState((s)->lookup_mods,(s)->group) #define XkbGrabStateFromRec(s) XkbBuildCoreState((s)->grab_mods,(s)->group) typedef struct _XkbMods { unsigned char mask; /* effective mods */ unsigned char real_mods; unsigned short vmods; } XkbModsRec,*XkbModsPtr; typedef struct _XkbKTMapEntry { Bool active; unsigned char level; XkbModsRec mods; } XkbKTMapEntryRec,*XkbKTMapEntryPtr; typedef struct _XkbKeyType { XkbModsRec mods; unsigned char num_levels; unsigned char map_count; /* map is an array of map_count XkbKTMapEntryRec structs */ XkbKTMapEntryPtr map; /* preserve is an array of map_count XkbModsRec structs */ XkbModsPtr preserve; Atom name; /* level_names is an array of num_levels Atoms */ Atom * level_names; } XkbKeyTypeRec, *XkbKeyTypePtr; #define XkbNumGroups(g) ((g)&0x0f) #define XkbOutOfRangeGroupInfo(g) ((g)&0xf0) #define XkbOutOfRangeGroupAction(g) ((g)&0xc0) #define XkbOutOfRangeGroupNumber(g) (((g)&0x30)>>4) #define XkbSetGroupInfo(g,w,n) (((w)&0xc0)|(((n)&3)<<4)|((g)&0x0f)) #define XkbSetNumGroups(g,n) (((g)&0xf0)|((n)&0x0f)) /* * Structures and access macros used primarily by the server */ typedef struct _XkbBehavior { unsigned char type; unsigned char data; } XkbBehavior; #define XkbAnyActionDataSize 7 typedef struct _XkbAnyAction { unsigned char type; unsigned char data[XkbAnyActionDataSize]; } XkbAnyAction; typedef struct _XkbModAction { unsigned char type; unsigned char flags; unsigned char mask; unsigned char real_mods; unsigned char vmods1; unsigned char vmods2; } XkbModAction; #define XkbModActionVMods(a) \ ((short)(((a)->vmods1<<8)|((a)->vmods2))) #define XkbSetModActionVMods(a,v) \ (((a)->vmods1=(((v)>>8)&0xff)),(a)->vmods2=((v)&0xff)) typedef struct _XkbGroupAction { unsigned char type; unsigned char flags; char group_XXX; } XkbGroupAction; #define XkbSAGroup(a) (XkbCharToInt((a)->group_XXX)) #define XkbSASetGroup(a,g) ((a)->group_XXX=(g)) typedef struct _XkbISOAction { unsigned char type; unsigned char flags; unsigned char mask; unsigned char real_mods; char group_XXX; unsigned char affect; unsigned char vmods1; unsigned char vmods2; } XkbISOAction; typedef struct _XkbPtrAction { unsigned char type; unsigned char flags; unsigned char high_XXX; unsigned char low_XXX; unsigned char high_YYY; unsigned char low_YYY; } XkbPtrAction; #define XkbPtrActionX(a) (Xkb2CharsToInt((a)->high_XXX,(a)->low_XXX)) #define XkbPtrActionY(a) (Xkb2CharsToInt((a)->high_YYY,(a)->low_YYY)) #define XkbSetPtrActionX(a,x) (XkbIntTo2Chars(x,(a)->high_XXX,(a)->low_XXX)) #define XkbSetPtrActionY(a,y) (XkbIntTo2Chars(y,(a)->high_YYY,(a)->low_YYY)) typedef struct _XkbPtrBtnAction { unsigned char type; unsigned char flags; unsigned char count; unsigned char button; } XkbPtrBtnAction; typedef struct _XkbPtrDfltAction { unsigned char type; unsigned char flags; unsigned char affect; char valueXXX; } XkbPtrDfltAction; #define XkbSAPtrDfltValue(a) (XkbCharToInt((a)->valueXXX)) #define XkbSASetPtrDfltValue(a,c) ((a)->valueXXX= ((c)&0xff)) typedef struct _XkbSwitchScreenAction { unsigned char type; unsigned char flags; char screenXXX; } XkbSwitchScreenAction; #define XkbSAScreen(a) (XkbCharToInt((a)->screenXXX)) #define XkbSASetScreen(a,s) ((a)->screenXXX= ((s)&0xff)) typedef struct _XkbCtrlsAction { unsigned char type; unsigned char flags; unsigned char ctrls3; unsigned char ctrls2; unsigned char ctrls1; unsigned char ctrls0; } XkbCtrlsAction; #define XkbActionSetCtrls(a,c) (((a)->ctrls3=(((c)>>24)&0xff)),\ ((a)->ctrls2=(((c)>>16)&0xff)),\ ((a)->ctrls1=(((c)>>8)&0xff)),\ ((a)->ctrls0=((c)&0xff))) #define XkbActionCtrls(a) ((((unsigned int)(a)->ctrls3)<<24)|\ (((unsigned int)(a)->ctrls2)<<16)|\ (((unsigned int)(a)->ctrls1)<<8)|\ ((unsigned int)((a)->ctrls0))) typedef struct _XkbMessageAction { unsigned char type; unsigned char flags; unsigned char message[6]; } XkbMessageAction; typedef struct _XkbRedirectKeyAction { unsigned char type; unsigned char new_key; unsigned char mods_mask; unsigned char mods; unsigned char vmods_mask0; unsigned char vmods_mask1; unsigned char vmods0; unsigned char vmods1; } XkbRedirectKeyAction; #define XkbSARedirectVMods(a) ((((unsigned int)(a)->vmods1)<<8)|\ ((unsigned int)(a)->vmods0)) #define XkbSARedirectSetVMods(a,m) (((a)->vmods1=(((m)>>8)&0xff)),\ ((a)->vmods0=((m)&0xff))) #define XkbSARedirectVModsMask(a) ((((unsigned int)(a)->vmods_mask1)<<8)|\ ((unsigned int)(a)->vmods_mask0)) #define XkbSARedirectSetVModsMask(a,m) (((a)->vmods_mask1=(((m)>>8)&0xff)),\ ((a)->vmods_mask0=((m)&0xff))) typedef struct _XkbDeviceBtnAction { unsigned char type; unsigned char flags; unsigned char count; unsigned char button; unsigned char device; } XkbDeviceBtnAction; typedef struct _XkbDeviceValuatorAction { unsigned char type; unsigned char device; unsigned char v1_what; unsigned char v1_ndx; unsigned char v1_value; unsigned char v2_what; unsigned char v2_ndx; unsigned char v2_value; } XkbDeviceValuatorAction; typedef union _XkbAction { XkbAnyAction any; XkbModAction mods; XkbGroupAction group; XkbISOAction iso; XkbPtrAction ptr; XkbPtrBtnAction btn; XkbPtrDfltAction dflt; XkbSwitchScreenAction screen; XkbCtrlsAction ctrls; XkbMessageAction msg; XkbRedirectKeyAction redirect; XkbDeviceBtnAction devbtn; XkbDeviceValuatorAction devval; unsigned char type; } XkbAction; typedef struct _XkbControls { unsigned char mk_dflt_btn; unsigned char num_groups; unsigned char groups_wrap; XkbModsRec internal; XkbModsRec ignore_lock; unsigned int enabled_ctrls; unsigned short repeat_delay; unsigned short repeat_interval; unsigned short slow_keys_delay; unsigned short debounce_delay; unsigned short mk_delay; unsigned short mk_interval; unsigned short mk_time_to_max; unsigned short mk_max_speed; short mk_curve; unsigned short ax_options; unsigned short ax_timeout; unsigned short axt_opts_mask; unsigned short axt_opts_values; unsigned int axt_ctrls_mask; unsigned int axt_ctrls_values; unsigned char per_key_repeat[XkbPerKeyBitArraySize]; } XkbControlsRec, *XkbControlsPtr; #define XkbAX_AnyFeedback(c) ((c)->enabled_ctrls&XkbAccessXFeedbackMask) #define XkbAX_NeedOption(c,w) ((c)->ax_options&(w)) #define XkbAX_NeedFeedback(c,w) (XkbAX_AnyFeedback(c)&&XkbAX_NeedOption(c,w)) typedef struct _XkbServerMapRec { /* acts is an array of XkbActions structs, with size_acts entries allocated, and num_acts entries used. */ unsigned short num_acts; unsigned short size_acts; XkbAction *acts; /* behaviors, key_acts, explicit, & vmodmap are all arrays with (xkb->max_key_code + 1) entries allocated for each. */ XkbBehavior *behaviors; unsigned short *key_acts; #if defined(__cplusplus) || defined(c_plusplus) /* explicit is a C++ reserved word */ unsigned char *c_explicit; #else unsigned char *explicit; #endif unsigned char vmods[XkbNumVirtualMods]; unsigned short *vmodmap; } XkbServerMapRec, *XkbServerMapPtr; #define XkbSMKeyActionsPtr(m,k) (&(m)->acts[(m)->key_acts[k]]) /* * Structures and access macros used primarily by clients */ typedef struct _XkbSymMapRec { unsigned char kt_index[XkbNumKbdGroups]; unsigned char group_info; unsigned char width; unsigned short offset; } XkbSymMapRec, *XkbSymMapPtr; typedef struct _XkbClientMapRec { /* types is an array of XkbKeyTypeRec structs, with size_types entries allocated, and num_types entries used. */ unsigned char size_types; unsigned char num_types; XkbKeyTypePtr types; /* syms is an array of size_syms KeySyms, in which num_syms are used */ unsigned short size_syms; unsigned short num_syms; KeySym *syms; /* key_sym_map is an array of (max_key_code + 1) XkbSymMapRec structs */ XkbSymMapPtr key_sym_map; /* modmap is an array of (max_key_code + 1) unsigned chars */ unsigned char *modmap; } XkbClientMapRec, *XkbClientMapPtr; #define XkbCMKeyGroupInfo(m,k) ((m)->key_sym_map[k].group_info) #define XkbCMKeyNumGroups(m,k) (XkbNumGroups((m)->key_sym_map[k].group_info)) #define XkbCMKeyGroupWidth(m,k,g) (XkbCMKeyType(m,k,g)->num_levels) #define XkbCMKeyGroupsWidth(m,k) ((m)->key_sym_map[k].width) #define XkbCMKeyTypeIndex(m,k,g) ((m)->key_sym_map[k].kt_index[g&0x3]) #define XkbCMKeyType(m,k,g) (&(m)->types[XkbCMKeyTypeIndex(m,k,g)]) #define XkbCMKeyNumSyms(m,k) (XkbCMKeyGroupsWidth(m,k)*XkbCMKeyNumGroups(m,k)) #define XkbCMKeySymsOffset(m,k) ((m)->key_sym_map[k].offset) #define XkbCMKeySymsPtr(m,k) (&(m)->syms[XkbCMKeySymsOffset(m,k)]) /* * Compatibility structures and access macros */ typedef struct _XkbSymInterpretRec { KeySym sym; unsigned char flags; unsigned char match; unsigned char mods; unsigned char virtual_mod; XkbAnyAction act; } XkbSymInterpretRec,*XkbSymInterpretPtr; typedef struct _XkbCompatMapRec { /* sym_interpret is an array of XkbSymInterpretRec structs, in which size_si are allocated & num_si are used. */ XkbSymInterpretPtr sym_interpret; XkbModsRec groups[XkbNumKbdGroups]; unsigned short num_si; unsigned short size_si; } XkbCompatMapRec, *XkbCompatMapPtr; typedef struct _XkbIndicatorMapRec { unsigned char flags; unsigned char which_groups; unsigned char groups; unsigned char which_mods; XkbModsRec mods; unsigned int ctrls; } XkbIndicatorMapRec, *XkbIndicatorMapPtr; #define XkbIM_IsAuto(i) ((((i)->flags&XkbIM_NoAutomatic)==0)&&\ (((i)->which_groups&&(i)->groups)||\ ((i)->which_mods&&(i)->mods.mask)||\ ((i)->ctrls))) #define XkbIM_InUse(i) (((i)->flags)||((i)->which_groups)||\ ((i)->which_mods)||((i)->ctrls)) typedef struct _XkbIndicatorRec { unsigned long phys_indicators; XkbIndicatorMapRec maps[XkbNumIndicators]; } XkbIndicatorRec,*XkbIndicatorPtr; typedef struct _XkbKeyNameRec { char name[XkbKeyNameLength]; } XkbKeyNameRec,*XkbKeyNamePtr; typedef struct _XkbKeyAliasRec { char real[XkbKeyNameLength]; char alias[XkbKeyNameLength]; } XkbKeyAliasRec,*XkbKeyAliasPtr; /* * Names for everything */ typedef struct _XkbNamesRec { Atom keycodes; Atom geometry; Atom symbols; Atom types; Atom compat; Atom vmods[XkbNumVirtualMods]; Atom indicators[XkbNumIndicators]; Atom groups[XkbNumKbdGroups]; /* keys is an array of (xkb->max_key_code + 1) XkbKeyNameRec entries */ XkbKeyNamePtr keys; /* key_aliases is an array of num_key_aliases XkbKeyAliasRec entries */ XkbKeyAliasPtr key_aliases; /* radio_groups is an array of num_rg Atoms */ Atom *radio_groups; Atom phys_symbols; /* num_keys seems to be unused in libX11 */ unsigned char num_keys; unsigned char num_key_aliases; unsigned short num_rg; } XkbNamesRec,*XkbNamesPtr; typedef struct _XkbGeometry *XkbGeometryPtr; /* * Tie it all together into one big keyboard description */ typedef struct _XkbDesc { struct _XDisplay * dpy; unsigned short flags; unsigned short device_spec; KeyCode min_key_code; KeyCode max_key_code; XkbControlsPtr ctrls; XkbServerMapPtr server; XkbClientMapPtr map; XkbIndicatorPtr indicators; XkbNamesPtr names; XkbCompatMapPtr compat; XkbGeometryPtr geom; } XkbDescRec, *XkbDescPtr; #define XkbKeyKeyTypeIndex(d,k,g) (XkbCMKeyTypeIndex((d)->map,k,g)) #define XkbKeyKeyType(d,k,g) (XkbCMKeyType((d)->map,k,g)) #define XkbKeyGroupWidth(d,k,g) (XkbCMKeyGroupWidth((d)->map,k,g)) #define XkbKeyGroupsWidth(d,k) (XkbCMKeyGroupsWidth((d)->map,k)) #define XkbKeyGroupInfo(d,k) (XkbCMKeyGroupInfo((d)->map,(k))) #define XkbKeyNumGroups(d,k) (XkbCMKeyNumGroups((d)->map,(k))) #define XkbKeyNumSyms(d,k) (XkbCMKeyNumSyms((d)->map,(k))) #define XkbKeySymsPtr(d,k) (XkbCMKeySymsPtr((d)->map,(k))) #define XkbKeySym(d,k,n) (XkbKeySymsPtr(d,k)[n]) #define XkbKeySymEntry(d,k,sl,g) \ (XkbKeySym(d,k,((XkbKeyGroupsWidth(d,k)*(g))+(sl)))) #define XkbKeyAction(d,k,n) \ (XkbKeyHasActions(d,k)?&XkbKeyActionsPtr(d,k)[n]:NULL) #define XkbKeyActionEntry(d,k,sl,g) \ (XkbKeyHasActions(d,k)?\ XkbKeyAction(d,k,((XkbKeyGroupsWidth(d,k)*(g))+(sl))):NULL) #define XkbKeyHasActions(d,k) ((d)->server->key_acts[k]!=0) #define XkbKeyNumActions(d,k) (XkbKeyHasActions(d,k)?XkbKeyNumSyms(d,k):1) #define XkbKeyActionsPtr(d,k) (XkbSMKeyActionsPtr((d)->server,k)) #define XkbKeycodeInRange(d,k) (((k)>=(d)->min_key_code)&&\ ((k)<=(d)->max_key_code)) #define XkbNumKeys(d) ((d)->max_key_code-(d)->min_key_code+1) /* * The following structures can be used to track changes * to a keyboard device */ typedef struct _XkbMapChanges { unsigned short changed; KeyCode min_key_code; KeyCode max_key_code; unsigned char first_type; unsigned char num_types; KeyCode first_key_sym; unsigned char num_key_syms; KeyCode first_key_act; unsigned char num_key_acts; KeyCode first_key_behavior; unsigned char num_key_behaviors; KeyCode first_key_explicit; unsigned char num_key_explicit; KeyCode first_modmap_key; unsigned char num_modmap_keys; KeyCode first_vmodmap_key; unsigned char num_vmodmap_keys; unsigned char pad; unsigned short vmods; } XkbMapChangesRec,*XkbMapChangesPtr; typedef struct _XkbControlsChanges { unsigned int changed_ctrls; unsigned int enabled_ctrls_changes; Bool num_groups_changed; } XkbControlsChangesRec,*XkbControlsChangesPtr; typedef struct _XkbIndicatorChanges { unsigned int state_changes; unsigned int map_changes; } XkbIndicatorChangesRec,*XkbIndicatorChangesPtr; typedef struct _XkbNameChanges { unsigned int changed; unsigned char first_type; unsigned char num_types; unsigned char first_lvl; unsigned char num_lvls; unsigned char num_aliases; unsigned char num_rg; unsigned char first_key; unsigned char num_keys; unsigned short changed_vmods; unsigned long changed_indicators; unsigned char changed_groups; } XkbNameChangesRec,*XkbNameChangesPtr; typedef struct _XkbCompatChanges { unsigned char changed_groups; unsigned short first_si; unsigned short num_si; } XkbCompatChangesRec,*XkbCompatChangesPtr; typedef struct _XkbChanges { unsigned short device_spec; unsigned short state_changes; XkbMapChangesRec map; XkbControlsChangesRec ctrls; XkbIndicatorChangesRec indicators; XkbNameChangesRec names; XkbCompatChangesRec compat; } XkbChangesRec, *XkbChangesPtr; /* * These data structures are used to construct a keymap from * a set of components or to list components in the server * database. */ typedef struct _XkbComponentNames { char * keymap; char * keycodes; char * types; char * compat; char * symbols; char * geometry; } XkbComponentNamesRec, *XkbComponentNamesPtr; typedef struct _XkbComponentName { unsigned short flags; char * name; } XkbComponentNameRec,*XkbComponentNamePtr; typedef struct _XkbComponentList { int num_keymaps; int num_keycodes; int num_types; int num_compat; int num_symbols; int num_geometry; XkbComponentNamePtr keymaps; XkbComponentNamePtr keycodes; XkbComponentNamePtr types; XkbComponentNamePtr compat; XkbComponentNamePtr symbols; XkbComponentNamePtr geometry; } XkbComponentListRec, *XkbComponentListPtr; /* * The following data structures describe and track changes to a * non-keyboard extension device */ typedef struct _XkbDeviceLedInfo { unsigned short led_class; unsigned short led_id; unsigned int phys_indicators; unsigned int maps_present; unsigned int names_present; unsigned int state; Atom names[XkbNumIndicators]; XkbIndicatorMapRec maps[XkbNumIndicators]; } XkbDeviceLedInfoRec,*XkbDeviceLedInfoPtr; typedef struct _XkbDeviceInfo { char * name; Atom type; unsigned short device_spec; Bool has_own_state; unsigned short supported; unsigned short unsupported; /* btn_acts is an array of num_btn XkbAction entries */ unsigned short num_btns; XkbAction * btn_acts; unsigned short sz_leds; unsigned short num_leds; unsigned short dflt_kbd_fb; unsigned short dflt_led_fb; /* leds is an array of XkbDeviceLedInfoRec in which sz_leds entries are allocated and num_leds entries are used */ XkbDeviceLedInfoPtr leds; } XkbDeviceInfoRec,*XkbDeviceInfoPtr; #define XkbXI_DevHasBtnActs(d) (((d)->num_btns>0)&&((d)->btn_acts!=NULL)) #define XkbXI_LegalDevBtn(d,b) (XkbXI_DevHasBtnActs(d)&&((b)<(d)->num_btns)) #define XkbXI_DevHasLeds(d) (((d)->num_leds>0)&&((d)->leds!=NULL)) typedef struct _XkbDeviceLedChanges { unsigned short led_class; unsigned short led_id; unsigned int defined; /* names or maps changed */ struct _XkbDeviceLedChanges *next; } XkbDeviceLedChangesRec,*XkbDeviceLedChangesPtr; typedef struct _XkbDeviceChanges { unsigned int changed; unsigned short first_btn; unsigned short num_btns; XkbDeviceLedChangesRec leds; } XkbDeviceChangesRec,*XkbDeviceChangesPtr; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif /* _XKBSTR_H_ */ X11/extensions/xf86bigfproto.h000064400000004760151027430560012206 0ustar00/* * Declarations of request structures for the BIGFONT extension. * * Copyright (c) 1999-2000 Bruno Haible * Copyright (c) 1999-2000 The XFree86 Project, Inc. */ /* THIS IS NOT AN X CONSORTIUM STANDARD */ #ifndef _XF86BIGFPROTO_H_ #define _XF86BIGFPROTO_H_ #include #define XF86BIGFONTNAME "XFree86-Bigfont" #define XF86BIGFONT_MAJOR_VERSION 1 /* current version numbers */ #define XF86BIGFONT_MINOR_VERSION 1 typedef struct _XF86BigfontQueryVersion { CARD8 reqType; /* always XF86BigfontReqCode */ CARD8 xf86bigfontReqType; /* always X_XF86BigfontQueryVersion */ CARD16 length; } xXF86BigfontQueryVersionReq; #define sz_xXF86BigfontQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ CARD8 capabilities; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of XFree86-Bigfont */ CARD16 minorVersion; /* minor version of XFree86-Bigfont */ CARD32 uid; CARD32 gid; CARD32 signature; CARD32 pad1; CARD32 pad2; } xXF86BigfontQueryVersionReply; #define sz_xXF86BigfontQueryVersionReply 32 /* Bit masks that can be set in the capabilities */ #define XF86Bigfont_CAP_LocalShm 1 typedef struct _XF86BigfontQueryFont { CARD8 reqType; /* always XF86BigfontReqCode */ CARD8 xf86bigfontReqType; /* always X_XF86BigfontQueryFont */ CARD16 length; CARD32 id; CARD32 flags; } xXF86BigfontQueryFontReq; #define sz_xXF86BigfontQueryFontReq 12 typedef struct { BYTE type; /* X_Reply */ CARD8 pad1; CARD16 sequenceNumber; CARD32 length; xCharInfo minBounds; #ifndef WORD64 CARD32 walign1; #endif xCharInfo maxBounds; #ifndef WORD64 CARD32 walign2; #endif CARD16 minCharOrByte2; CARD16 maxCharOrByte2; CARD16 defaultChar; CARD16 nFontProps; CARD8 drawDirection; CARD8 minByte1; CARD8 maxByte1; BOOL allCharsExist; INT16 fontAscent; INT16 fontDescent; CARD32 nCharInfos; CARD32 nUniqCharInfos; CARD32 shmid; CARD32 shmsegoffset; /* followed by nFontProps xFontProp structures */ /* and if nCharInfos > 0 && shmid == -1, followed by nUniqCharInfos xCharInfo structures and then by nCharInfos CARD16 indices (each >= 0, < nUniqCharInfos) and then, if nCharInfos is odd, one more CARD16 for padding. */ } xXF86BigfontQueryFontReply; #define sz_xXF86BigfontQueryFontReply 72 /* Bit masks that can be set in the flags */ #define XF86Bigfont_FLAGS_Shm 1 #endif /* _XF86BIGFPROTO_H_ */ X11/extensions/bigreqstr.h000064400000000273151027430560011474 0ustar00#warning "bigreqstr.h is obsolete and may be removed in the future." #warning "include for the protocol defines." #include X11/extensions/damageproto.h000064400000007037151027430560012001 0ustar00/* * Copyright © 2003 Keith Packard * Copyright © 2007 Eric Anholt * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef _DAMAGEPROTO_H_ #define _DAMAGEPROTO_H_ #include #include #include #define Window CARD32 #define Drawable CARD32 #define Font CARD32 #define Pixmap CARD32 #define Cursor CARD32 #define Colormap CARD32 #define GContext CARD32 #define Atom CARD32 #define VisualID CARD32 #define Time CARD32 #define KeyCode CARD8 #define KeySym CARD32 #define Picture CARD32 #define Region CARD32 #define Damage CARD32 /************** Version 0 ******************/ typedef struct { CARD8 reqType; CARD8 damageReqType; CARD16 length; } xDamageReq; /* * requests and replies */ typedef struct { CARD8 reqType; CARD8 damageReqType; CARD16 length; CARD32 majorVersion; CARD32 minorVersion; } xDamageQueryVersionReq; #define sz_xDamageQueryVersionReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD32 majorVersion; CARD32 minorVersion; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xDamageQueryVersionReply; #define sz_xDamageQueryVersionReply 32 typedef struct { CARD8 reqType; CARD8 damageReqType; CARD16 length; Damage damage; Drawable drawable; CARD8 level; CARD8 pad1; CARD16 pad2; } xDamageCreateReq; #define sz_xDamageCreateReq 16 typedef struct { CARD8 reqType; CARD8 damageReqType; CARD16 length; Damage damage; } xDamageDestroyReq; #define sz_xDamageDestroyReq 8 typedef struct { CARD8 reqType; CARD8 damageReqType; CARD16 length; Damage damage; Region repair; Region parts; } xDamageSubtractReq; #define sz_xDamageSubtractReq 16 typedef struct { CARD8 reqType; CARD8 damageReqType; CARD16 length; Drawable drawable; Region region; } xDamageAddReq; #define sz_xDamageAddReq 12 /* Events */ #define DamageNotifyMore 0x80 typedef struct { CARD8 type; CARD8 level; CARD16 sequenceNumber; Drawable drawable; Damage damage; Time timestamp; xRectangle area; xRectangle geometry; } xDamageNotifyEvent; #undef Damage #undef Region #undef Picture #undef Window #undef Drawable #undef Font #undef Pixmap #undef Cursor #undef Colormap #undef GContext #undef Atom #undef VisualID #undef Time #undef KeyCode #undef KeySym #endif /* _DAMAGEPROTO_H_ */ X11/extensions/lbx.h000064400000004274151027430560010264 0ustar00/* * Copyright 1992 Network Computing Devices * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of NCD. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. NCD. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * NCD. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL NCD. * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef _LBX_H_ #define _LBX_H_ #define LBXNAME "LBX" #define LBX_MAJOR_VERSION 1 #define LBX_MINOR_VERSION 0 #define LbxNumberReqs 44 #define LbxEvent 0 #define LbxQuickMotionDeltaEvent 1 #define LbxNumberEvents 2 /* This is always the master client */ #define LbxMasterClientIndex 0 /* LbxEvent lbxType sub-fields */ #define LbxSwitchEvent 0 #define LbxCloseEvent 1 #define LbxDeltaEvent 2 #define LbxInvalidateTagEvent 3 #define LbxSendTagDataEvent 4 #define LbxListenToOne 5 #define LbxListenToAll 6 #define LbxMotionDeltaEvent 7 #define LbxReleaseCmapEvent 8 #define LbxFreeCellsEvent 9 /* * Lbx image compression methods * * No compression is always assigned the value of 0. * * The rest of the compression method opcodes are assigned dynamically * at option negotiation time. */ #define LbxImageCompressNone 0 #define BadLbxClient 0 #define LbxNumberErrors (BadLbxClient + 1) /* tagged data types */ #define LbxTagTypeModmap 1 #define LbxTagTypeKeymap 2 #define LbxTagTypeProperty 3 #define LbxTagTypeFont 4 #define LbxTagTypeConnInfo 5 #endif X11/extensions/xf86mscstr.h000064400000013730151027430560011523 0ustar00/* $XFree86: xc/include/extensions/xf86mscstr.h,v 3.12 2002/11/20 04:04:56 dawes Exp $ */ /* * Copyright (c) 1995, 1996 The XFree86 Project, Inc */ /* THIS IS NOT AN X CONSORTIUM STANDARD */ #ifndef _XF86MISCSTR_H_ #define _XF86MISCSTR_H_ #include #define XF86MISCNAME "XFree86-Misc" #define XF86MISC_MAJOR_VERSION 0 /* current version numbers */ #define XF86MISC_MINOR_VERSION 9 typedef struct _XF86MiscQueryVersion { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscQueryVersion */ CARD16 length; } xXF86MiscQueryVersionReq; #define sz_xXF86MiscQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of XFree86-Misc */ CARD16 minorVersion; /* minor version of XFree86-Misc */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86MiscQueryVersionReply; #define sz_xXF86MiscQueryVersionReply 32 #ifdef _XF86MISC_SAVER_COMPAT_ typedef struct _XF86MiscGetSaver { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscGetSaver */ CARD16 length; CARD16 screen; CARD16 pad; } xXF86MiscGetSaverReq; #define sz_xXF86MiscGetSaverReq 8 typedef struct _XF86MiscSetSaver { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscSetSaver */ CARD16 length; CARD16 screen; CARD16 pad; CARD32 suspendTime; CARD32 offTime; } xXF86MiscSetSaverReq; #define sz_xXF86MiscSetSaverReq 16 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 suspendTime; CARD32 offTime; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86MiscGetSaverReply; #define sz_xXF86MiscGetSaverReply 32 #endif typedef struct _XF86MiscGetMouseSettings { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscGetMouseSettings */ CARD16 length; } xXF86MiscGetMouseSettingsReq; #define sz_xXF86MiscGetMouseSettingsReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 mousetype; CARD32 baudrate; CARD32 samplerate; CARD32 resolution; CARD32 buttons; BOOL emulate3buttons; BOOL chordmiddle; CARD16 pad2; CARD32 emulate3timeout; CARD32 flags; CARD32 devnamelen; /* strlen(device)+1 */ } xXF86MiscGetMouseSettingsReply; #define sz_xXF86MiscGetMouseSettingsReply 44 typedef struct _XF86MiscGetKbdSettings { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscGetKbdSettings */ CARD16 length; } xXF86MiscGetKbdSettingsReq; #define sz_xXF86MiscGetKbdSettingsReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 kbdtype; CARD32 rate; CARD32 delay; BOOL servnumlock; BOOL pad2; CARD16 pad3; CARD32 pad4; CARD32 pad5; } xXF86MiscGetKbdSettingsReply; #define sz_xXF86MiscGetKbdSettingsReply 32 typedef struct _XF86MiscSetMouseSettings { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscSetMouseSettings */ CARD16 length; CARD32 mousetype; CARD32 baudrate; CARD32 samplerate; CARD32 resolution; CARD32 buttons; BOOL emulate3buttons; BOOL chordmiddle; CARD16 devnamelen; CARD32 emulate3timeout; CARD32 flags; } xXF86MiscSetMouseSettingsReq; #define sz_xXF86MiscSetMouseSettingsReq 36 typedef struct _XF86MiscSetKbdSettings { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscSetKbdSettings */ CARD16 length; CARD32 kbdtype; CARD32 rate; CARD32 delay; BOOL servnumlock; BOOL pad1; CARD16 pad2; } xXF86MiscSetKbdSettingsReq; #define sz_xXF86MiscSetKbdSettingsReq 20 typedef struct _XF86MiscSetGrabKeysState { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscSetKbdSettings */ CARD16 length; BOOL enable; BOOL pad1; CARD16 pad2; } xXF86MiscSetGrabKeysStateReq; #define sz_xXF86MiscSetGrabKeysStateReq 8 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86MiscSetGrabKeysStateReply; #define sz_xXF86MiscSetGrabKeysStateReply 32 typedef struct _XF86MiscSetClientVersion { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; CARD16 length; CARD16 major; CARD16 minor; } xXF86MiscSetClientVersionReq; #define sz_xXF86MiscSetClientVersionReq 8 typedef struct _XF86MiscGetFilePaths { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscGetFilePaths */ CARD16 length; } xXF86MiscGetFilePathsReq; #define sz_xXF86MiscGetFilePathsReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 configlen; CARD16 modulelen; CARD16 loglen; CARD16 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86MiscGetFilePathsReply; #define sz_xXF86MiscGetFilePathsReply 32 typedef struct _XF86MiscPassMessage { CARD8 reqType; /* always XF86MiscReqCode */ CARD8 xf86miscReqType; /* always X_XF86MiscPassMessage */ CARD16 length; CARD16 typelen; CARD16 vallen; CARD16 screen; CARD16 pad; } xXF86MiscPassMessageReq; #define sz_xXF86MiscPassMessageReq 12 typedef struct { BYTE type; /* X_Reply */ BYTE pad1; CARD16 sequenceNumber; CARD32 length; CARD16 mesglen; CARD16 pad2; CARD32 status; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86MiscPassMessageReply; #define sz_xXF86MiscPassMessageReply 32 #endif /* _XF86MISCSTR_H_ */ X11/extensions/dri2tokens.h000064400000004644151027430560011564 0ustar00/* * Copyright © 2008 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Soft- * ware"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, provided that the above copyright * notice(s) and this permission notice appear in all copies of the Soft- * ware and that both the above copyright notice(s) and this permission * notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- * ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY * RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN * THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSE- * QUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFOR- * MANCE OF THIS SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall * not be used in advertising or otherwise to promote the sale, use or * other dealings in this Software without prior written authorization of * the copyright holder. * * Authors: * Kristian Høgsberg (krh@redhat.com) */ #ifndef _DRI2_TOKENS_H_ #define _DRI2_TOKENS_H_ #define DRI2BufferFrontLeft 0 #define DRI2BufferBackLeft 1 #define DRI2BufferFrontRight 2 #define DRI2BufferBackRight 3 #define DRI2BufferDepth 4 #define DRI2BufferStencil 5 #define DRI2BufferAccum 6 #define DRI2BufferFakeFrontLeft 7 #define DRI2BufferFakeFrontRight 8 #define DRI2BufferDepthStencil 9 #define DRI2BufferHiz 10 /* keep bits 16 and above for prime IDs */ #define DRI2DriverPrimeMask 7 /* 0 - 7 - allows for 6 devices*/ #define DRI2DriverPrimeShift 16 #define DRI2DriverPrimeId(x) (((x) >> DRI2DriverPrimeShift) & (DRI2DriverPrimeMask)) #define DRI2DriverDRI 0 #define DRI2DriverVDPAU 1 /* Event sub-types for the swap complete event */ #define DRI2_EXCHANGE_COMPLETE 0x1 #define DRI2_BLIT_COMPLETE 0x2 #define DRI2_FLIP_COMPLETE 0x3 #endif X11/extensions/xf86vmproto.h000064400000036524151027430560011724 0ustar00/* Copyright 1995 Kaleb S. KEITHLEY Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL Kaleb S. KEITHLEY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Kaleb S. KEITHLEY shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Kaleb S. KEITHLEY */ /* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */ #ifndef _XF86VIDMODEPROTO_H_ #define _XF86VIDMODEPROTO_H_ #include #define XF86VIDMODENAME "XFree86-VidModeExtension" #define XF86VIDMODE_MAJOR_VERSION 2 /* current version numbers */ #define XF86VIDMODE_MINOR_VERSION 2 #define X_XF86VidModeQueryVersion 0 #define X_XF86VidModeGetModeLine 1 #define X_XF86VidModeModModeLine 2 #define X_XF86VidModeSwitchMode 3 #define X_XF86VidModeGetMonitor 4 #define X_XF86VidModeLockModeSwitch 5 #define X_XF86VidModeGetAllModeLines 6 #define X_XF86VidModeAddModeLine 7 #define X_XF86VidModeDeleteModeLine 8 #define X_XF86VidModeValidateModeLine 9 #define X_XF86VidModeSwitchToMode 10 #define X_XF86VidModeGetViewPort 11 #define X_XF86VidModeSetViewPort 12 /* new for version 2.x of this extension */ #define X_XF86VidModeGetDotClocks 13 #define X_XF86VidModeSetClientVersion 14 #define X_XF86VidModeSetGamma 15 #define X_XF86VidModeGetGamma 16 #define X_XF86VidModeGetGammaRamp 17 #define X_XF86VidModeSetGammaRamp 18 #define X_XF86VidModeGetGammaRampSize 19 #define X_XF86VidModeGetPermissions 20 /* * major version 0 == uses parameter-to-wire functions in XFree86 libXxf86vm. * major version 1 == uses parameter-to-wire functions hard-coded in xvidtune * client. * major version 2 == uses new protocol version in XFree86 4.0. */ typedef struct _XF86VidModeQueryVersion { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeQueryVersion */ CARD16 length; } xXF86VidModeQueryVersionReq; #define sz_xXF86VidModeQueryVersionReq 4 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD16 majorVersion; /* major version of XF86VidMode */ CARD16 minorVersion; /* minor version of XF86VidMode */ CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86VidModeQueryVersionReply; #define sz_xXF86VidModeQueryVersionReply 32 typedef struct _XF86VidModeGetModeLine { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 screen; CARD16 pad; } xXF86VidModeGetModeLineReq, xXF86VidModeGetAllModeLinesReq, xXF86VidModeGetMonitorReq, xXF86VidModeGetViewPortReq, xXF86VidModeGetDotClocksReq, xXF86VidModeGetPermissionsReq; #define sz_xXF86VidModeGetModeLineReq 8 #define sz_xXF86VidModeGetAllModeLinesReq 8 #define sz_xXF86VidModeGetMonitorReq 8 #define sz_xXF86VidModeGetViewPortReq 8 #define sz_xXF86VidModeGetDotClocksReq 8 #define sz_xXF86VidModeGetPermissionsReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 hskew; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD16 pad2; CARD32 flags; CARD32 reserved1; CARD32 reserved2; CARD32 reserved3; CARD32 privsize; } xXF86VidModeGetModeLineReply; #define sz_xXF86VidModeGetModeLineReply 52 /* 0.x version */ typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD32 flags; CARD32 privsize; } xXF86OldVidModeGetModeLineReply; #define sz_xXF86OldVidModeGetModeLineReply 36 typedef struct { CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD32 hskew; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD16 pad1; CARD32 flags; CARD32 reserved1; CARD32 reserved2; CARD32 reserved3; CARD32 privsize; } xXF86VidModeModeInfo; /* 0.x version */ typedef struct { CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD32 flags; CARD32 privsize; } xXF86OldVidModeModeInfo; typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 modecount; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86VidModeGetAllModeLinesReply; #define sz_xXF86VidModeGetAllModeLinesReply 32 typedef struct _XF86VidModeAddModeLine { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */ CARD16 length; CARD32 screen; /* could be CARD16 but need the pad */ CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 hskew; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD16 pad1; CARD32 flags; CARD32 reserved1; CARD32 reserved2; CARD32 reserved3; CARD32 privsize; CARD32 after_dotclock; CARD16 after_hdisplay; CARD16 after_hsyncstart; CARD16 after_hsyncend; CARD16 after_htotal; CARD16 after_hskew; CARD16 after_vdisplay; CARD16 after_vsyncstart; CARD16 after_vsyncend; CARD16 after_vtotal; CARD16 pad2; CARD32 after_flags; CARD32 reserved4; CARD32 reserved5; CARD32 reserved6; } xXF86VidModeAddModeLineReq; #define sz_xXF86VidModeAddModeLineReq 92 /* 0.x version */ typedef struct _XF86OldVidModeAddModeLine { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeAddMode */ CARD16 length; CARD32 screen; /* could be CARD16 but need the pad */ CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD32 flags; CARD32 privsize; CARD32 after_dotclock; CARD16 after_hdisplay; CARD16 after_hsyncstart; CARD16 after_hsyncend; CARD16 after_htotal; CARD16 after_vdisplay; CARD16 after_vsyncstart; CARD16 after_vsyncend; CARD16 after_vtotal; CARD32 after_flags; } xXF86OldVidModeAddModeLineReq; #define sz_xXF86OldVidModeAddModeLineReq 60 typedef struct _XF86VidModeModModeLine { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeModModeLine */ CARD16 length; CARD32 screen; /* could be CARD16 but need the pad */ CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 hskew; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD16 pad1; CARD32 flags; CARD32 reserved1; CARD32 reserved2; CARD32 reserved3; CARD32 privsize; } xXF86VidModeModModeLineReq; #define sz_xXF86VidModeModModeLineReq 48 /* 0.x version */ typedef struct _XF86OldVidModeModModeLine { CARD8 reqType; /* always XF86OldVidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86OldVidModeModModeLine */ CARD16 length; CARD32 screen; /* could be CARD16 but need the pad */ CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD32 flags; CARD32 privsize; } xXF86OldVidModeModModeLineReq; #define sz_xXF86OldVidModeModModeLineReq 32 typedef struct _XF86VidModeValidateModeLine { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD32 screen; /* could be CARD16 but need the pad */ CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 hskew; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD16 pad1; CARD32 flags; CARD32 reserved1; CARD32 reserved2; CARD32 reserved3; CARD32 privsize; } xXF86VidModeDeleteModeLineReq, xXF86VidModeValidateModeLineReq, xXF86VidModeSwitchToModeReq; #define sz_xXF86VidModeDeleteModeLineReq 52 #define sz_xXF86VidModeValidateModeLineReq 52 #define sz_xXF86VidModeSwitchToModeReq 52 /* 0.x version */ typedef struct _XF86OldVidModeValidateModeLine { CARD8 reqType; /* always XF86OldVidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD32 screen; /* could be CARD16 but need the pad */ CARD32 dotclock; CARD16 hdisplay; CARD16 hsyncstart; CARD16 hsyncend; CARD16 htotal; CARD16 vdisplay; CARD16 vsyncstart; CARD16 vsyncend; CARD16 vtotal; CARD32 flags; CARD32 privsize; } xXF86OldVidModeDeleteModeLineReq, xXF86OldVidModeValidateModeLineReq, xXF86OldVidModeSwitchToModeReq; #define sz_xXF86OldVidModeDeleteModeLineReq 36 #define sz_xXF86OldVidModeValidateModeLineReq 36 #define sz_xXF86OldVidModeSwitchToModeReq 36 typedef struct _XF86VidModeSwitchMode { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSwitchMode */ CARD16 length; CARD16 screen; CARD16 zoom; } xXF86VidModeSwitchModeReq; #define sz_xXF86VidModeSwitchModeReq 8 typedef struct _XF86VidModeLockModeSwitch { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeLockModeSwitch */ CARD16 length; CARD16 screen; CARD16 lock; } xXF86VidModeLockModeSwitchReq; #define sz_xXF86VidModeLockModeSwitchReq 8 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 status; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86VidModeValidateModeLineReply; #define sz_xXF86VidModeValidateModeLineReply 32 typedef struct { BYTE type; /* X_Reply */ BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD8 vendorLength; CARD8 modelLength; CARD8 nhsync; CARD8 nvsync; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86VidModeGetMonitorReply; #define sz_xXF86VidModeGetMonitorReply 32 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 x; CARD32 y; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86VidModeGetViewPortReply; #define sz_xXF86VidModeGetViewPortReply 32 typedef struct _XF86VidModeSetViewPort { CARD8 reqType; /* always VidModeReqCode */ CARD8 xf86vidmodeReqType; /* always X_XF86VidModeSetViewPort */ CARD16 length; CARD16 screen; CARD16 pad; CARD32 x; CARD32 y; } xXF86VidModeSetViewPortReq; #define sz_xXF86VidModeSetViewPortReq 16 typedef struct { BYTE type; BOOL pad1; CARD16 sequenceNumber; CARD32 length; CARD32 flags; CARD32 clocks; CARD32 maxclocks; CARD32 pad2; CARD32 pad3; CARD32 pad4; } xXF86VidModeGetDotClocksReply; #define sz_xXF86VidModeGetDotClocksReply 32 typedef struct _XF86VidModeSetClientVersion { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 major; CARD16 minor; } xXF86VidModeSetClientVersionReq; #define sz_xXF86VidModeSetClientVersionReq 8 typedef struct _XF86VidModeGetGamma { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 screen; CARD16 pad; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xXF86VidModeGetGammaReq; #define sz_xXF86VidModeGetGammaReq 32 typedef struct { BYTE type; BOOL pad; CARD16 sequenceNumber; CARD32 length; CARD32 red; CARD32 green; CARD32 blue; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xXF86VidModeGetGammaReply; #define sz_xXF86VidModeGetGammaReply 32 typedef struct _XF86VidModeSetGamma { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 screen; CARD16 pad; CARD32 red; CARD32 green; CARD32 blue; CARD32 pad1; CARD32 pad2; CARD32 pad3; } xXF86VidModeSetGammaReq; #define sz_xXF86VidModeSetGammaReq 32 typedef struct _XF86VidModeSetGammaRamp { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 screen; CARD16 size; } xXF86VidModeSetGammaRampReq; #define sz_xXF86VidModeSetGammaRampReq 8 typedef struct _XF86VidModeGetGammaRamp { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 screen; CARD16 size; } xXF86VidModeGetGammaRampReq; #define sz_xXF86VidModeGetGammaRampReq 8 typedef struct { BYTE type; BOOL pad; CARD16 sequenceNumber; CARD32 length; CARD16 size; CARD16 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86VidModeGetGammaRampReply; #define sz_xXF86VidModeGetGammaRampReply 32 typedef struct _XF86VidModeGetGammaRampSize { CARD8 reqType; /* always XF86VidModeReqCode */ CARD8 xf86vidmodeReqType; CARD16 length; CARD16 screen; CARD16 pad; } xXF86VidModeGetGammaRampSizeReq; #define sz_xXF86VidModeGetGammaRampSizeReq 8 typedef struct { BYTE type; BOOL pad; CARD16 sequenceNumber; CARD32 length; CARD16 size; CARD16 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86VidModeGetGammaRampSizeReply; #define sz_xXF86VidModeGetGammaRampSizeReply 32 typedef struct { BYTE type; BOOL pad; CARD16 sequenceNumber; CARD32 length; CARD32 permissions; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; } xXF86VidModeGetPermissionsReply; #define sz_xXF86VidModeGetPermissionsReply 32 #endif /* _XF86VIDMODEPROTO_H_ */ X11/extensions/xf86misc.h000064400000007475151027430560011154 0ustar00/* $XFree86: xc/include/extensions/xf86misc.h,v 3.16 2002/11/20 04:04:56 dawes Exp $ */ /* * Copyright (c) 1995, 1996 The XFree86 Project, Inc */ /* THIS IS NOT AN X CONSORTIUM STANDARD */ #ifndef _XF86MISC_H_ #define _XF86MISC_H_ #include #define X_XF86MiscQueryVersion 0 #ifdef _XF86MISC_SAVER_COMPAT_ #define X_XF86MiscGetSaver 1 #define X_XF86MiscSetSaver 2 #endif #define X_XF86MiscGetMouseSettings 3 #define X_XF86MiscGetKbdSettings 4 #define X_XF86MiscSetMouseSettings 5 #define X_XF86MiscSetKbdSettings 6 #define X_XF86MiscSetGrabKeysState 7 #define X_XF86MiscSetClientVersion 8 #define X_XF86MiscGetFilePaths 9 #define X_XF86MiscPassMessage 10 #define XF86MiscNumberEvents 0 #define XF86MiscBadMouseProtocol 0 #define XF86MiscBadMouseBaudRate 1 #define XF86MiscBadMouseFlags 2 #define XF86MiscBadMouseCombo 3 #define XF86MiscBadKbdType 4 #define XF86MiscModInDevDisabled 5 #define XF86MiscModInDevClientNotLocal 6 #define XF86MiscNoModule 7 #define XF86MiscNumberErrors (XF86MiscNoModule + 1) /* Never renumber these */ #define MTYPE_MICROSOFT 0 #define MTYPE_MOUSESYS 1 #define MTYPE_MMSERIES 2 #define MTYPE_LOGITECH 3 #define MTYPE_BUSMOUSE 4 #define MTYPE_LOGIMAN 5 #define MTYPE_PS_2 6 #define MTYPE_MMHIT 7 #define MTYPE_GLIDEPOINT 8 #define MTYPE_IMSERIAL 9 #define MTYPE_THINKING 10 #define MTYPE_IMPS2 11 #define MTYPE_THINKINGPS2 12 #define MTYPE_MMANPLUSPS2 13 #define MTYPE_GLIDEPOINTPS2 14 #define MTYPE_NETPS2 15 #define MTYPE_NETSCROLLPS2 16 #define MTYPE_SYSMOUSE 17 #define MTYPE_AUTOMOUSE 18 #define MTYPE_ACECAD 19 #define MTYPE_EXPPS2 20 #define MTYPE_XQUEUE 127 #define MTYPE_OSMOUSE 126 #define MTYPE_UNKNOWN 125 #define KTYPE_UNKNOWN 0 #define KTYPE_84KEY 1 #define KTYPE_101KEY 2 #define KTYPE_OTHER 3 #define KTYPE_XQUEUE 4 #define MF_CLEAR_DTR 1 #define MF_CLEAR_RTS 2 #define MF_REOPEN 128 #ifndef _XF86MISC_SERVER_ /* return values for XF86MiscSetGrabKeysState */ #define MiscExtGrabStateSuccess 0 /* No errors */ #define MiscExtGrabStateLocked 1 /* A client already requested that * grabs cannot be removed/killed */ #define MiscExtGrabStateAlready 2 /* Request for enabling/disabling * grab removal/kill already done */ _XFUNCPROTOBEGIN typedef struct { char* device; int type; int baudrate; int samplerate; int resolution; int buttons; Bool emulate3buttons; int emulate3timeout; Bool chordmiddle; int flags; } XF86MiscMouseSettings; typedef struct { int type; int rate; int delay; Bool servnumlock; } XF86MiscKbdSettings; typedef struct { char* configfile; char* modulepath; char* logfile; } XF86MiscFilePaths; Bool XF86MiscQueryVersion( Display* /* dpy */, int* /* majorVersion */, int* /* minorVersion */ ); Bool XF86MiscQueryExtension( Display* /* dpy */, int* /* event_base */, int* /* error_base */ ); Bool XF86MiscSetClientVersion( Display *dpy /* dpy */ ); Status XF86MiscGetMouseSettings( Display* /* dpy */, XF86MiscMouseSettings* /* mouse info */ ); Status XF86MiscGetKbdSettings( Display* /* dpy */, XF86MiscKbdSettings* /* keyboard info */ ); Status XF86MiscSetMouseSettings( Display* /* dpy */, XF86MiscMouseSettings* /* mouse info */ ); Status XF86MiscSetKbdSettings( Display* /* dpy */, XF86MiscKbdSettings* /* keyboard info */ ); int XF86MiscSetGrabKeysState( Display* /* dpy */, Bool /* enabled */ ); Status XF86MiscGetFilePaths( Display* /* dpy */, XF86MiscFilePaths* /* file paths/locations */ ); Status XF86MiscPassMessage( Display* /* dpy */, int /* screen */, const char* /* message name/type */, const char* /* message contents/value */, char ** /* returned message */ ); _XFUNCPROTOEND #endif #endif X11/extensions/XI2proto.h000064400000111311151027430560011154 0ustar00/* * Copyright © 2009 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /* Conventions for this file: * Names: * structs: always typedef'd, prefixed with xXI, CamelCase * struct members: lower_case_with_underscores * Exceptions: reqType, ReqType, repType, RepType, sequenceNumber are * named as such for historical reasons. * request opcodes: X_XIRequestName as CamelCase * defines: defines used in client applications must go in XI2.h * defines used only in protocol handling: XISOMENAME * * Data types: unless there is a historical name for a datatype (e.g. * Window), use stdint types specifying the size of the datatype. * historical data type names must be defined and undefined at the top and * end of the file. * * General: * spaces, not tabs. * structs specific to a request or reply added before the request * definition. structs used in more than one request, reply or event * appended to the common structs section before the definition of the * first request. * members of structs vertically aligned on column 16 if datatypes permit. * otherwise aligned on next available 8n column. */ /** * Protocol definitions for the XI2 protocol. * This file should not be included by clients that merely use XI2, but do not * need the wire protocol. Such clients should include XI2.h, or the matching * header from the library. * */ #ifndef _XI2PROTO_H_ #define _XI2PROTO_H_ #include #include #include #include /* make sure types have right sizes for protocol structures. */ #define Window uint32_t #define Time uint32_t #define Atom uint32_t #define Cursor uint32_t #define Barrier uint32_t /** * XI2 Request opcodes */ #define X_XIQueryPointer 40 #define X_XIWarpPointer 41 #define X_XIChangeCursor 42 #define X_XIChangeHierarchy 43 #define X_XISetClientPointer 44 #define X_XIGetClientPointer 45 #define X_XISelectEvents 46 #define X_XIQueryVersion 47 #define X_XIQueryDevice 48 #define X_XISetFocus 49 #define X_XIGetFocus 50 #define X_XIGrabDevice 51 #define X_XIUngrabDevice 52 #define X_XIAllowEvents 53 #define X_XIPassiveGrabDevice 54 #define X_XIPassiveUngrabDevice 55 #define X_XIListProperties 56 #define X_XIChangeProperty 57 #define X_XIDeleteProperty 58 #define X_XIGetProperty 59 #define X_XIGetSelectedEvents 60 #define X_XIBarrierReleasePointer 61 /** Number of XI requests */ #define XI2REQUESTS (X_XIBarrierReleasePointer - X_XIQueryPointer + 1) /** Number of XI2 events */ #define XI2EVENTS (XI_LASTEVENT + 1) /************************************************************************************* * * * COMMON STRUCTS * * * *************************************************************************************/ /** Fixed point 16.16 */ typedef int32_t FP1616; /** Fixed point 32.32 */ typedef struct { int32_t integral; uint32_t frac; } FP3232; /** * Struct to describe a device. * * For a MasterPointer or a MasterKeyboard, 'attachment' specifies the * paired master device. * For a SlaveKeyboard or SlavePointer, 'attachment' specifies the master * device this device is attached to. * For a FloatingSlave, 'attachment' is undefined. */ typedef struct { uint16_t deviceid; uint16_t use; /**< ::XIMasterPointer, ::XIMasterKeyboard, ::XISlavePointer, ::XISlaveKeyboard, ::XIFloatingSlave */ uint16_t attachment; /**< Current attachment or pairing.*/ uint16_t num_classes; /**< Number of classes following this struct. */ uint16_t name_len; /**< Length of name in bytes. */ uint8_t enabled; /**< TRUE if device is enabled. */ uint8_t pad; } xXIDeviceInfo; /** * Default template for a device class. * A device class is equivalent to a device's capabilities. Multiple classes * are supported per device. */ typedef struct { uint16_t type; /**< One of *class */ uint16_t length; /**< Length in 4 byte units */ uint16_t sourceid; /**< source device for this class */ uint16_t pad; } xXIAnyInfo; /** * Denotes button capability on a device. * Struct is followed by a button bit-mask (padded to four byte chunks) and * then num_buttons * Atom that names the buttons in the device-native setup * (i.e. ignoring button mappings). */ typedef struct { uint16_t type; /**< Always ButtonClass */ uint16_t length; /**< Length in 4 byte units */ uint16_t sourceid; /**< source device for this class */ uint16_t num_buttons; /**< Number of buttons provided */ } xXIButtonInfo; /** * Denotes key capability on a device. * Struct is followed by num_keys * CARD32 that lists the keycodes available * on the device. */ typedef struct { uint16_t type; /**< Always KeyClass */ uint16_t length; /**< Length in 4 byte units */ uint16_t sourceid; /**< source device for this class */ uint16_t num_keycodes; /**< Number of keys provided */ } xXIKeyInfo; /** * Denotes an valuator capability on a device. * One XIValuatorInfo describes exactly one valuator (axis) on the device. */ typedef struct { uint16_t type; /**< Always ValuatorClass */ uint16_t length; /**< Length in 4 byte units */ uint16_t sourceid; /**< source device for this class */ uint16_t number; /**< Valuator number */ Atom label; /**< Axis label */ FP3232 min; /**< Min value */ FP3232 max; /**< Max value */ FP3232 value; /**< Last published value */ uint32_t resolution; /**< Resolutions in units/m */ uint8_t mode; /**< ModeRelative or ModeAbsolute */ uint8_t pad1; uint16_t pad2; } xXIValuatorInfo; /*** * Denotes a scroll valuator on a device. * One XIScrollInfo describes exactly one scroll valuator that must have a * XIValuatorInfo struct. */ typedef struct { uint16_t type; /**< Always ValuatorClass */ uint16_t length; /**< Length in 4 byte units */ uint16_t sourceid; /**< source device for this class */ uint16_t number; /**< Valuator number */ uint16_t scroll_type; /**< ::XIScrollTypeVertical, ::XIScrollTypeHorizontal */ uint16_t pad0; uint32_t flags; /**< ::XIScrollFlagEmulate, ::XIScrollFlagPreferred */ FP3232 increment; /**< Increment for one unit of scrolling */ } xXIScrollInfo; /** * Denotes multitouch capability on a device. */ typedef struct { uint16_t type; /**< Always TouchClass */ uint16_t length; /**< Length in 4 byte units */ uint16_t sourceid; /**< source device for this class */ uint8_t mode; /**< DirectTouch or DependentTouch */ uint8_t num_touches; /**< Maximum number of touches (0==unlimited) */ } xXITouchInfo; /** * Used to select for events on a given window. * Struct is followed by (mask_len * CARD8), with each bit set representing * the event mask for the given type. A mask bit represents an event type if * (mask == (1 << type)). */ typedef struct { uint16_t deviceid; /**< Device id to select for */ uint16_t mask_len; /**< Length of mask in 4 byte units */ } xXIEventMask; /** * XKB modifier information. * The effective modifier is a binary mask of base, latched, and locked * modifiers. */ typedef struct { uint32_t base_mods; /**< Logically pressed modifiers */ uint32_t latched_mods; /**< Logically latched modifiers */ uint32_t locked_mods; /**< Logically locked modifiers */ uint32_t effective_mods; /**< Effective modifiers */ } xXIModifierInfo; /** * XKB group information. * The effective group is the mathematical sum of base, latched, and locked * group after group wrapping is taken into account. */ typedef struct { uint8_t base_group; /**< Logically "pressed" group */ uint8_t latched_group; /**< Logically latched group */ uint8_t locked_group; /**< Logically locked group */ uint8_t effective_group; /**< Effective group */ } xXIGroupInfo; /************************************************************************************* * * * REQUESTS * * * *************************************************************************************/ /** * Query the server for the supported X Input extension version. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIQueryVersion */ uint16_t length; /**< Length in 4 byte units */ uint16_t major_version; uint16_t minor_version; } xXIQueryVersionReq; #define sz_xXIQueryVersionReq 8 typedef struct { uint8_t repType; /**< ::X_Reply */ uint8_t RepType; /**< Always ::X_XIQueryVersion */ uint16_t sequenceNumber; uint32_t length; uint16_t major_version; uint16_t minor_version; uint32_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; } xXIQueryVersionReply; #define sz_xXIQueryVersionReply 32 /** * Query the server for information about a specific device or all input * devices. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIQueryDevice */ uint16_t length; /**< Length in 4 byte units */ uint16_t deviceid; uint16_t pad; } xXIQueryDeviceReq; #define sz_xXIQueryDeviceReq 8 typedef struct { uint8_t repType; /**< ::X_Reply */ uint8_t RepType; /**< Always ::X_XIQueryDevice */ uint16_t sequenceNumber; uint32_t length; uint16_t num_devices; uint16_t pad0; uint32_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; } xXIQueryDeviceReply; #define sz_xXIQueryDeviceReply 32 /** * Select for events on a given window. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XISelectEvents */ uint16_t length; /**< Length in 4 byte units */ Window win; uint16_t num_masks; uint16_t pad; } xXISelectEventsReq; #define sz_xXISelectEventsReq 12 /** * Query for selected events on a given window. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIGetSelectedEvents */ uint16_t length; /**< Length in 4 byte units */ Window win; } xXIGetSelectedEventsReq; #define sz_xXIGetSelectedEventsReq 8 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_XIGetSelectedEvents */ uint16_t sequenceNumber; uint32_t length; uint16_t num_masks; /**< Number of xXIEventMask structs trailing the reply */ uint16_t pad0; uint32_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; } xXIGetSelectedEventsReply; #define sz_xXIGetSelectedEventsReply 32 /** * Query the given device's screen/window coordinates. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIQueryPointer */ uint16_t length; /**< Length in 4 byte units */ Window win; uint16_t deviceid; uint16_t pad1; } xXIQueryPointerReq; #define sz_xXIQueryPointerReq 12 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_XIQueryPointer */ uint16_t sequenceNumber; uint32_t length; Window root; Window child; FP1616 root_x; FP1616 root_y; FP1616 win_x; FP1616 win_y; uint8_t same_screen; uint8_t pad0; uint16_t buttons_len; xXIModifierInfo mods; xXIGroupInfo group; } xXIQueryPointerReply; #define sz_xXIQueryPointerReply 56 /** * Warp the given device's pointer to the specified position. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIWarpPointer */ uint16_t length; /**< Length in 4 byte units */ Window src_win; Window dst_win; FP1616 src_x; FP1616 src_y; uint16_t src_width; uint16_t src_height; FP1616 dst_x; FP1616 dst_y; uint16_t deviceid; uint16_t pad1; } xXIWarpPointerReq; #define sz_xXIWarpPointerReq 36 /** * Change the given device's sprite to the given cursor. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIChangeCursor */ uint16_t length; /**< Length in 4 byte units */ Window win; Cursor cursor; uint16_t deviceid; uint16_t pad1; } xXIChangeCursorReq; #define sz_xXIChangeCursorReq 16 /** * Modify the device hierarchy. */ typedef struct { uint8_t reqType; /**< Input extension major code */ uint8_t ReqType; /**< Always ::X_XIChangeHierarchy */ uint16_t length; /**< Length in 4 byte units */ uint8_t num_changes; uint8_t pad0; uint16_t pad1; } xXIChangeHierarchyReq; #define sz_xXIChangeHierarchyReq 8 /** * Generic header for any hierarchy change. */ typedef struct { uint16_t type; uint16_t length; /**< Length in 4 byte units */ } xXIAnyHierarchyChangeInfo; /** * Create a new master device. * Name of new master follows struct (4-byte padded) */ typedef struct { uint16_t type; /**< Always ::XIAddMaster */ uint16_t length; /**< 2 + (namelen + padding)/4 */ uint16_t name_len; uint8_t send_core; uint8_t enable; } xXIAddMasterInfo; /** * Delete a master device. Will automatically delete the master device paired * with the given master device. */ typedef struct { uint16_t type; /**< Always ::XIRemoveMaster */ uint16_t length; /**< 3 */ uint16_t deviceid; uint8_t return_mode; /**< ::XIAttachToMaster, ::XIFloating */ uint8_t pad; uint16_t return_pointer; /**< Pointer to attach slave ptr devices to */ uint16_t return_keyboard; /**< keyboard to attach slave keybd devices to*/ } xXIRemoveMasterInfo; /** * Attach an SD to a new device. * NewMaster has to be of same type (pointer->pointer, keyboard->keyboard); */ typedef struct { uint16_t type; /**< Always ::XIAttachSlave */ uint16_t length; /**< 2 */ uint16_t deviceid; uint16_t new_master; /**< id of new master device */ } xXIAttachSlaveInfo; /** * Detach an SD from its current master device. */ typedef struct { uint16_t type; /**< Always ::XIDetachSlave */ uint16_t length; /**< 2 */ uint16_t deviceid; uint16_t pad; } xXIDetachSlaveInfo; /** * Set the window/client's ClientPointer. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XISetClientPointer */ uint16_t length; /**< Length in 4 byte units */ Window win; uint16_t deviceid; uint16_t pad1; } xXISetClientPointerReq; #define sz_xXISetClientPointerReq 12 /** * Query the given window/client's ClientPointer setting. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_GetClientPointer */ uint16_t length; /**< Length in 4 byte units */ Window win; } xXIGetClientPointerReq; #define sz_xXIGetClientPointerReq 8 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_GetClientPointer */ uint16_t sequenceNumber; uint32_t length; BOOL set; /**< client pointer is set? */ uint8_t pad0; uint16_t deviceid; uint32_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; } xXIGetClientPointerReply; #define sz_xXIGetClientPointerReply 32 /** * Set the input focus to the specified window. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XISetFocus */ uint16_t length; /**< Length in 4 byte units */ Window focus; Time time; uint16_t deviceid; uint16_t pad0; } xXISetFocusReq; #define sz_xXISetFocusReq 16 /** * Query the current input focus. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIGetDeviceFocus */ uint16_t length; /**< Length in 4 byte units */ uint16_t deviceid; uint16_t pad0; } xXIGetFocusReq; #define sz_xXIGetFocusReq 8 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_XIGetFocus */ uint16_t sequenceNumber; uint32_t length; Window focus; uint32_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; } xXIGetFocusReply; #define sz_xXIGetFocusReply 32 /** * Grab the given device. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIGrabDevice */ uint16_t length; /**< Length in 4 byte units */ Window grab_window; Time time; Cursor cursor; uint16_t deviceid; uint8_t grab_mode; uint8_t paired_device_mode; uint8_t owner_events; uint8_t pad; uint16_t mask_len; } xXIGrabDeviceReq; #define sz_xXIGrabDeviceReq 24 /** * Return codes from a XIPassiveGrabDevice request. */ typedef struct { uint32_t modifiers; /**< Modifier state */ uint8_t status; /**< Grab status code */ uint8_t pad0; uint16_t pad1; } xXIGrabModifierInfo; typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_XIGrabDevice */ uint16_t sequenceNumber; uint32_t length; uint8_t status; uint8_t pad0; uint16_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; uint32_t pad6; } xXIGrabDeviceReply; #define sz_xXIGrabDeviceReply 32 /** * Ungrab the specified device. * */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIUngrabDevice */ uint16_t length; /**< Length in 4 byte units */ Time time; uint16_t deviceid; uint16_t pad; } xXIUngrabDeviceReq; #define sz_xXIUngrabDeviceReq 12 /** * Allow or replay events on the specified grabbed device. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIAllowEvents */ uint16_t length; /**< Length in 4 byte units */ Time time; uint16_t deviceid; uint8_t mode; uint8_t pad; } xXIAllowEventsReq; #define sz_xXIAllowEventsReq 12 /** * Allow or replay events on the specified grabbed device. * Since XI 2.2 */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIAllowEvents */ uint16_t length; /**< Length in 4 byte units */ Time time; uint16_t deviceid; uint8_t mode; uint8_t pad; uint32_t touchid; /**< Since XI 2.2 */ Window grab_window; /**< Since XI 2.2 */ } xXI2_2AllowEventsReq; #define sz_xXI2_2AllowEventsReq 20 /** * Passively grab the device. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIPassiveGrabDevice */ uint16_t length; /**< Length in 4 byte units */ Time time; Window grab_window; Cursor cursor; uint32_t detail; uint16_t deviceid; uint16_t num_modifiers; uint16_t mask_len; uint8_t grab_type; uint8_t grab_mode; uint8_t paired_device_mode; uint8_t owner_events; uint16_t pad1; } xXIPassiveGrabDeviceReq; #define sz_xXIPassiveGrabDeviceReq 32 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_XIPassiveGrabDevice */ uint16_t sequenceNumber; uint32_t length; uint16_t num_modifiers; uint16_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; uint32_t pad6; } xXIPassiveGrabDeviceReply; #define sz_xXIPassiveGrabDeviceReply 32 /** * Delete a passive grab for the given device. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIPassiveUngrabDevice */ uint16_t length; /**< Length in 4 byte units */ Window grab_window; uint32_t detail; uint16_t deviceid; uint16_t num_modifiers; uint8_t grab_type; uint8_t pad0; uint16_t pad1; } xXIPassiveUngrabDeviceReq; #define sz_xXIPassiveUngrabDeviceReq 20 /** * List all device properties on the specified device. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIListProperties */ uint16_t length; /**< Length in 4 byte units */ uint16_t deviceid; uint16_t pad; } xXIListPropertiesReq; #define sz_xXIListPropertiesReq 8 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always ::X_XIListProperties */ uint16_t sequenceNumber; uint32_t length; uint16_t num_properties; uint16_t pad0; uint32_t pad1; uint32_t pad2; uint32_t pad3; uint32_t pad4; uint32_t pad5; } xXIListPropertiesReply; #define sz_xXIListPropertiesReply 32 /** * Change a property on the specified device. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always ::X_XIChangeProperty */ uint16_t length; /**< Length in 4 byte units */ uint16_t deviceid; uint8_t mode; uint8_t format; Atom property; Atom type; uint32_t num_items; } xXIChangePropertyReq; #define sz_xXIChangePropertyReq 20 /** * Delete the specified property. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always X_XIDeleteProperty */ uint16_t length; /**< Length in 4 byte units */ uint16_t deviceid; uint16_t pad0; Atom property; } xXIDeletePropertyReq; #define sz_xXIDeletePropertyReq 12 /** * Query the specified property's values. */ typedef struct { uint8_t reqType; uint8_t ReqType; /**< Always X_XIGetProperty */ uint16_t length; /**< Length in 4 byte units */ uint16_t deviceid; #if defined(__cplusplus) || defined(c_plusplus) uint8_t c_delete; #else uint8_t delete; #endif uint8_t pad0; Atom property; Atom type; uint32_t offset; uint32_t len; } xXIGetPropertyReq; #define sz_xXIGetPropertyReq 24 typedef struct { uint8_t repType; /**< Input extension major opcode */ uint8_t RepType; /**< Always X_XIGetProperty */ uint16_t sequenceNumber; uint32_t length; Atom type; uint32_t bytes_after; uint32_t num_items; uint8_t format; uint8_t pad0; uint16_t pad1; uint32_t pad2; uint32_t pad3; } xXIGetPropertyReply; #define sz_xXIGetPropertyReply 32 typedef struct { uint16_t deviceid; uint16_t pad; Barrier barrier; uint32_t eventid; } xXIBarrierReleasePointerInfo; typedef struct { uint8_t reqType; /**< Input extension major opcode */ uint8_t ReqType; /**< Always X_XIBarrierReleasePointer */ uint16_t length; uint32_t num_barriers; /* array of xXIBarrierReleasePointerInfo */ } xXIBarrierReleasePointerReq; #define sz_xXIBarrierReleasePointerReq 8 /************************************************************************************* * * * EVENTS * * * *************************************************************************************/ /** * Generic XI2 event header. All XI2 events use the same header. */ typedef struct { uint8_t type; uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; uint16_t evtype; uint16_t deviceid; Time time; } xXIGenericDeviceEvent; /** * Device hierarchy information. */ typedef struct { uint16_t deviceid; uint16_t attachment; /**< ID of master or paired device */ uint8_t use; /**< ::XIMasterKeyboard, ::XIMasterPointer, ::XISlaveKeyboard, ::XISlavePointer, ::XIFloatingSlave */ BOOL enabled; /**< TRUE if the device is enabled */ uint16_t pad; uint32_t flags; /**< ::XIMasterAdded, ::XIMasterRemoved, ::XISlaveAttached, ::XISlaveDetached, ::XISlaveAdded, ::XISlaveRemoved, ::XIDeviceEnabled, ::XIDeviceDisabled */ } xXIHierarchyInfo; /** * The device hierarchy has been modified. This event includes the device * hierarchy after the modification has been applied. */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte units */ uint16_t evtype; /**< ::XI_Hierarchy */ uint16_t deviceid; Time time; uint32_t flags; /**< ::XIMasterAdded, ::XIMasterDeleted, ::XISlaveAttached, ::XISlaveDetached, ::XISlaveAdded, ::XISlaveRemoved, ::XIDeviceEnabled, ::XIDeviceDisabled */ uint16_t num_info; uint16_t pad0; uint32_t pad1; uint32_t pad2; } xXIHierarchyEvent; /** * A device has changed capabilities. */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte units */ uint16_t evtype; /**< XI_DeviceChanged */ uint16_t deviceid; /**< Device that has changed */ Time time; uint16_t num_classes; /**< Number of classes that have changed */ uint16_t sourceid; /**< Source of the new classes */ uint8_t reason; /**< ::XISlaveSwitch, ::XIDeviceChange */ uint8_t pad0; uint16_t pad1; uint32_t pad2; uint32_t pad3; } xXIDeviceChangedEvent; /** * The owner of a touch stream has passed on ownership to another client. */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte units */ uint16_t evtype; /**< XI_TouchOwnership */ uint16_t deviceid; /**< Device that has changed */ Time time; uint32_t touchid; Window root; Window event; Window child; /* └──────── 32 byte boundary ────────┘ */ uint16_t sourceid; uint16_t pad0; uint32_t flags; uint32_t pad1; uint32_t pad2; } xXITouchOwnershipEvent; /** * Default input event for pointer, keyboard or touch input. */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte uints */ uint16_t evtype; uint16_t deviceid; Time time; uint32_t detail; /**< Keycode or button */ Window root; Window event; Window child; /* └──────── 32 byte boundary ────────┘ */ FP1616 root_x; /**< Always screen coords, 16.16 fixed point */ FP1616 root_y; FP1616 event_x; /**< Always screen coords, 16.16 fixed point */ FP1616 event_y; uint16_t buttons_len; /**< Len of button flags in 4 b units */ uint16_t valuators_len; /**< Len of val. flags in 4 b units */ uint16_t sourceid; /**< The source device */ uint16_t pad0; uint32_t flags; /**< ::XIKeyRepeat */ xXIModifierInfo mods; xXIGroupInfo group; } xXIDeviceEvent; /** * Sent when an input event is generated. RawEvents include valuator * information in both device-specific data (i.e. unaccelerated) and * processed data (i.e. accelerated, if applicable). */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte uints */ uint16_t evtype; /**< ::XI_RawEvent */ uint16_t deviceid; Time time; uint32_t detail; uint16_t sourceid; /**< The source device (XI 2.1) */ uint16_t valuators_len; /**< Length of trailing valuator mask in 4 byte units */ uint32_t flags; /**< ::XIKeyRepeat */ uint32_t pad2; } xXIRawEvent; /** * Note that the layout of root, event, child, root_x, root_y, event_x, * event_y must be identical to the xXIDeviceEvent. */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte uints */ uint16_t evtype; /**< ::XI_Enter */ uint16_t deviceid; Time time; uint16_t sourceid; uint8_t mode; uint8_t detail; Window root; Window event; Window child; /* └──────── 32 byte boundary ────────┘ */ FP1616 root_x; FP1616 root_y; FP1616 event_x; FP1616 event_y; BOOL same_screen; BOOL focus; uint16_t buttons_len; /**< Length of trailing button mask in 4 byte units */ xXIModifierInfo mods; xXIGroupInfo group; } xXIEnterEvent; typedef xXIEnterEvent xXILeaveEvent; typedef xXIEnterEvent xXIFocusInEvent; typedef xXIEnterEvent xXIFocusOutEvent; /** * Sent when a device property is created, modified or deleted. Does not * include property data, the client is required to query the data. */ typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte units */ uint16_t evtype; /**< ::XI_PropertyEvent */ uint16_t deviceid; Time time; Atom property; uint8_t what; /**< ::XIPropertyDeleted, ::XIPropertyCreated, ::XIPropertyMotified */ uint8_t pad0; uint16_t pad1; uint32_t pad2; uint32_t pad3; } xXIPropertyEvent; typedef struct { uint8_t type; /**< Always GenericEvent */ uint8_t extension; /**< XI extension offset */ uint16_t sequenceNumber; uint32_t length; /**< Length in 4 byte units */ uint16_t evtype; /**< ::XI_BarrierHit or ::XI_BarrierLeave */ uint16_t deviceid; Time time; uint32_t eventid; Window root; Window event; Barrier barrier; /* └──────── 32 byte boundary ────────┘ */ uint32_t dtime; uint32_t flags; /**< ::XIBarrierPointerReleased ::XIBarrierDeviceIsGrabbed */ uint16_t sourceid; int16_t pad; FP1616 root_x; FP1616 root_y; FP3232 dx; FP3232 dy; } xXIBarrierEvent; typedef xXIBarrierEvent xXIBarrierHitEvent; typedef xXIBarrierEvent xXIBarrierPointerReleasedEvent; typedef xXIBarrierEvent xXIBarrierLeaveEvent; #undef Window #undef Time #undef Atom #undef Cursor #undef Barrier #endif /* _XI2PROTO_H_ */ X11/extensions/xtestext1proto.h000064400000017156151027430560012537 0ustar00/* * xtestext1.h * * X11 Input Synthesis Extension include file */ /* Copyright 1986, 1987, 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1986, 1987, 1988 by Hewlett-Packard Corporation Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Hewlett-Packard not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Hewlett-Packard makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. This software is not subject to any license of the American Telephone and Telegraph Company or of the Regents of the University of California. */ #ifndef _XTESTEXT1PROTO_H #define _XTESTEXT1PROTO_H 1 #include /* * the typedefs for CARD8, CARD16, and CARD32 are defined in Xmd.h */ /* * XTest request type values * * used in the XTest extension protocol requests */ #define X_TestFakeInput 1 #define X_TestGetInput 2 #define X_TestStopInput 3 #define X_TestReset 4 #define X_TestQueryInputSize 5 /* * This defines the maximum size of a list of input actions * to be sent to the server. It should always be a multiple of * 4 so that the entire xTestFakeInputReq structure size is a * multiple of 4. */ typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 XTestReqType; /* always X_TestFakeInput */ CARD16 length; /* 2 + XTestMAX_ACTION_LIST_SIZE/4 */ CARD32 ack; CARD8 action_list[XTestMAX_ACTION_LIST_SIZE]; } xTestFakeInputReq; #define sz_xTestFakeInputReq (XTestMAX_ACTION_LIST_SIZE + 8) typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 XTestReqType; /* always X_TestGetInput */ CARD16 length; /* 2 */ CARD32 mode; } xTestGetInputReq; #define sz_xTestGetInputReq 8 typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 XTestReqType; /* always X_TestStopInput */ CARD16 length; /* 1 */ } xTestStopInputReq; #define sz_xTestStopInputReq 4 typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 XTestReqType; /* always X_TestReset */ CARD16 length; /* 1 */ } xTestResetReq; #define sz_xTestResetReq 4 typedef struct { CARD8 reqType; /* always XTestReqCode */ CARD8 XTestReqType; /* always X_TestQueryInputSize */ CARD16 length; /* 1 */ } xTestQueryInputSizeReq; #define sz_xTestQueryInputSizeReq 4 /* * This is the definition of the reply for the xTestQueryInputSize * request. It should remain the same minimum size as other replies * (32 bytes). */ typedef struct { CARD8 type; /* always X_Reply */ CARD8 pad1; CARD16 sequenceNumber; CARD32 length; /* always 0 */ CARD32 size_return; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xTestQueryInputSizeReply; /* * This is the definition for the input action wire event structure. * This event is sent to the client when the server has one or * more user input actions to report to the client. It must * remain the same size as all other wire events (32 bytes). */ typedef struct { CARD8 type; /* always XTestInputActionType */ CARD8 pad00; CARD16 sequenceNumber; CARD8 actions[XTestACTIONS_SIZE]; } xTestInputActionEvent; /* * This is the definition for the xTestFakeAck wire event structure. * This event is sent to the client when the server has completely * processed its input action buffer, and is ready for more. * It must remain the same size as all other wire events (32 bytes). */ typedef struct { CARD8 type; /* always XTestFakeAckType */ CARD8 pad00; CARD16 sequenceNumber; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; CARD32 pad06; CARD32 pad07; CARD32 pad08; } xTestFakeAckEvent; /* * These are the definitions for key/button motion input actions. */ typedef struct { CARD8 header; /* which device, key up/down */ CARD8 keycode; /* which key/button to move */ CARD16 delay_time; /* how long to delay (in ms) */ } XTestKeyInfo; /* * This is the definition for pointer jump input actions. */ typedef struct { CARD8 header; /* which pointer */ CARD8 pad1; /* unused padding byte */ CARD16 jumpx; /* x coord to jump to */ CARD16 jumpy; /* y coord to jump to */ CARD16 delay_time; /* how long to delay (in ms) */ } XTestJumpInfo; /* * These are the definitions for pointer relative motion input * actions. * * The sign bits for the x and y relative motions are contained * in the header byte. The x and y relative motions are packed * into one byte to make things fit in 32 bits. If the relative * motion range is larger than +/-15, use the pointer jump action. */ typedef struct { CARD8 header; /* which pointer */ CARD8 motion_data; /* x,y relative motion */ CARD16 delay_time; /* how long to delay (in ms) */ } XTestMotionInfo; /* * These are the definitions for a long delay input action. It is * used when more than XTestSHORT_DELAY_TIME milliseconds of delay * (approximately one minute) is needed. * * The device ID for a delay is always set to XTestDELAY_DEVICE_ID. * This guarantees that a header byte with a value of 0 is not * a valid header, so it can be used as a flag to indicate that * there are no more input actions in an XTestInputAction event. */ typedef struct { CARD8 header; /* always XTestDELAY_DEVICE_ID */ CARD8 pad1; /* unused padding byte */ CARD16 pad2; /* unused padding word */ CARD32 delay_time; /* how long to delay (in ms) */ } XTestDelayInfo; #endif /* _XTESTEXT1PROTO_H */ X11/extensions/dmx.h000064400000004505151027430560010264 0ustar00/* * Copyright 2002-2004 Red Hat Inc., Durham, North Carolina. * * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation on the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* * Authors: * Rickard E. (Rik) Faith * */ /** \file * This file describes the interface to the client-side libdmx.a * library. All DMX-aware client-side applications should include this * file. */ #ifndef _DMX_H_ #define _DMX_H_ /* These values must be larger than LastExtensionError. The values in dmxext.h and dmxproto.h *MUST* match. */ #define DmxBadXinerama 1001 #define DmxBadValue 1002 #define DmxBadReply 1003 #define DMXScreenWindowWidth (1L<<0) #define DMXScreenWindowHeight (1L<<1) #define DMXScreenWindowXoffset (1L<<2) #define DMXScreenWindowYoffset (1L<<3) #define DMXRootWindowWidth (1L<<4) #define DMXRootWindowHeight (1L<<5) #define DMXRootWindowXoffset (1L<<6) #define DMXRootWindowYoffset (1L<<7) #define DMXRootWindowXorigin (1L<<8) #define DMXRootWindowYorigin (1L<<9) #define DMXDesktopWidth (1L<<0) #define DMXDesktopHeight (1L<<1) #define DMXDesktopShiftX (1L<<2) #define DMXDesktopShiftY (1L<<3) #define DMXInputType (1L<<0) #define DMXInputPhysicalScreen (1L<<1) #define DMXInputSendsCore (1L<<2) #endif X11/extensions/XIproto.h000064400000120062151027430560011075 0ustar00/************************************************************ Copyright 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1989 by Hewlett-Packard Company, Palo Alto, California. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Hewlett-Packard not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL HEWLETT-PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ********************************************************/ #ifndef _XIPROTO_H #define _XIPROTO_H #include #include /* make sure types have right sizes for protocol structures. */ #define Window CARD32 #define Time CARD32 #define KeyCode CARD8 #define Mask CARD32 #define Atom CARD32 #define Cursor CARD32 /********************************************************* * * number of events, errors, and extension name. * */ #define MORE_EVENTS 0x80 #define DEVICE_BITS 0x7F #define InputClassBits 0x3F /* bits in mode field for input classes */ #define ModeBitsShift 6 /* amount to shift the remaining bits */ #define numInputClasses 7 #define IEVENTS 17 /* does NOT include generic events */ #define IERRORS 5 #define IREQUESTS 39 #define CLIENT_REQ 1 typedef struct _XExtEventInfo { Mask mask; BYTE type; BYTE word; } XExtEventInfo; #ifndef _XITYPEDEF_POINTER typedef void *Pointer; #endif struct tmask { Mask mask; void *dev; }; /********************************************************* * * Event constants used by library. * */ #define XI_DeviceValuator 0 #define XI_DeviceKeyPress 1 #define XI_DeviceKeyRelease 2 #define XI_DeviceButtonPress 3 #define XI_DeviceButtonRelease 4 #define XI_DeviceMotionNotify 5 #define XI_DeviceFocusIn 6 #define XI_DeviceFocusOut 7 #define XI_ProximityIn 8 #define XI_ProximityOut 9 #define XI_DeviceStateNotify 10 #define XI_DeviceMappingNotify 11 #define XI_ChangeDeviceNotify 12 #define XI_DeviceKeystateNotify 13 #define XI_DeviceButtonstateNotify 14 #define XI_DevicePresenceNotify 15 #define XI_DevicePropertyNotify 16 /********************************************************* * * Protocol request constants * */ #define X_GetExtensionVersion 1 #define X_ListInputDevices 2 #define X_OpenDevice 3 #define X_CloseDevice 4 #define X_SetDeviceMode 5 #define X_SelectExtensionEvent 6 #define X_GetSelectedExtensionEvents 7 #define X_ChangeDeviceDontPropagateList 8 #define X_GetDeviceDontPropagateList 9 #define X_GetDeviceMotionEvents 10 #define X_ChangeKeyboardDevice 11 #define X_ChangePointerDevice 12 #define X_GrabDevice 13 #define X_UngrabDevice 14 #define X_GrabDeviceKey 15 #define X_UngrabDeviceKey 16 #define X_GrabDeviceButton 17 #define X_UngrabDeviceButton 18 #define X_AllowDeviceEvents 19 #define X_GetDeviceFocus 20 #define X_SetDeviceFocus 21 #define X_GetFeedbackControl 22 #define X_ChangeFeedbackControl 23 #define X_GetDeviceKeyMapping 24 #define X_ChangeDeviceKeyMapping 25 #define X_GetDeviceModifierMapping 26 #define X_SetDeviceModifierMapping 27 #define X_GetDeviceButtonMapping 28 #define X_SetDeviceButtonMapping 29 #define X_QueryDeviceState 30 #define X_SendExtensionEvent 31 #define X_DeviceBell 32 #define X_SetDeviceValuators 33 #define X_GetDeviceControl 34 #define X_ChangeDeviceControl 35 /* XI 1.5 */ #define X_ListDeviceProperties 36 #define X_ChangeDeviceProperty 37 #define X_DeleteDeviceProperty 38 #define X_GetDeviceProperty 39 /********************************************************* * * Protocol request and reply structures. * * GetExtensionVersion. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GetExtensionVersion */ CARD16 length; CARD16 nbytes; CARD8 pad1, pad2; } xGetExtensionVersionReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetExtensionVersion */ CARD16 sequenceNumber; CARD32 length; CARD16 major_version; CARD16 minor_version; BOOL present; CARD8 pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; } xGetExtensionVersionReply; /********************************************************* * * ListInputDevices. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_ListInputDevices */ CARD16 length; } xListInputDevicesReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_ListInputDevices */ CARD16 sequenceNumber; CARD32 length; CARD8 ndevices; CARD8 pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xListInputDevicesReply; typedef struct _xDeviceInfo *xDeviceInfoPtr; typedef struct _xAnyClassinfo *xAnyClassPtr; typedef struct _xAnyClassinfo { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; } xAnyClassInfo; typedef struct _xDeviceInfo { CARD32 type; CARD8 id; CARD8 num_classes; CARD8 use; /* IsXPointer | IsXKeyboard | IsXExtension... */ CARD8 attached; /* id of master dev (if IsXExtension..) */ } xDeviceInfo; typedef struct _xKeyInfo *xKeyInfoPtr; typedef struct _xKeyInfo { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; KeyCode min_keycode; KeyCode max_keycode; CARD16 num_keys; CARD8 pad1,pad2; } xKeyInfo; typedef struct _xButtonInfo *xButtonInfoPtr; typedef struct _xButtonInfo { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; CARD16 num_buttons; } xButtonInfo; typedef struct _xValuatorInfo *xValuatorInfoPtr; typedef struct _xValuatorInfo { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; CARD8 num_axes; CARD8 mode; CARD32 motion_buffer_size; } xValuatorInfo; typedef struct _xAxisInfo *xAxisInfoPtr; typedef struct _xAxisInfo { CARD32 resolution; CARD32 min_value; CARD32 max_value; } xAxisInfo; /********************************************************* * * OpenDevice. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_OpenDevice */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xOpenDeviceReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_OpenDevice */ CARD16 sequenceNumber; CARD32 length; CARD8 num_classes; BYTE pad1, pad2, pad3; CARD32 pad00; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; } xOpenDeviceReply; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 event_type_base; } xInputClassInfo; /********************************************************* * * CloseDevice. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_CloseDevice */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xCloseDeviceReq; /********************************************************* * * SetDeviceMode. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_SetDeviceMode */ CARD16 length; CARD8 deviceid; CARD8 mode; BYTE pad1, pad2; } xSetDeviceModeReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_SetDeviceMode */ CARD16 sequenceNumber; CARD32 length; CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xSetDeviceModeReply; /********************************************************* * * SelectExtensionEvent. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_SelectExtensionEvent */ CARD16 length; Window window; CARD16 count; CARD16 pad00; } xSelectExtensionEventReq; /********************************************************* * * GetSelectedExtensionEvent. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_GetSelectedExtensionEvents */ CARD16 length; Window window; } xGetSelectedExtensionEventsReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* GetSelectedExtensionEvents */ CARD16 sequenceNumber; CARD32 length; CARD16 this_client_count; CARD16 all_clients_count; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xGetSelectedExtensionEventsReply; /********************************************************* * * ChangeDeviceDontPropagateList. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_ChangeDeviceDontPropagateList */ CARD16 length; Window window; CARD16 count; CARD8 mode; BYTE pad; } xChangeDeviceDontPropagateListReq; /********************************************************* * * GetDeviceDontPropagateList. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_GetDeviceDontPropagateList */ CARD16 length; Window window; } xGetDeviceDontPropagateListReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* GetDeviceDontPropagateList */ CARD16 sequenceNumber; CARD32 length; CARD16 count; CARD16 pad00; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xGetDeviceDontPropagateListReply; /********************************************************* * * GetDeviceMotionEvents. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GetDeviceMotionEvents*/ CARD16 length; Time start; Time stop; CARD8 deviceid; BYTE pad1, pad2, pad3; } xGetDeviceMotionEventsReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceMotionEvents */ CARD16 sequenceNumber; CARD32 length; CARD32 nEvents; CARD8 axes; CARD8 mode; BYTE pad1, pad2; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; } xGetDeviceMotionEventsReply; /********************************************************* * * ChangeKeyboardDevice. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_ChangeKeyboardDevice */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xChangeKeyboardDeviceReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_ChangeKeyboardDevice*/ CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xChangeKeyboardDeviceReply; /********************************************************* * * ChangePointerDevice. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_ChangePointerDevice */ CARD16 length; CARD8 xaxis; CARD8 yaxis; CARD8 deviceid; BYTE pad1; } xChangePointerDeviceReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_ChangePointerDevice */ CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xChangePointerDeviceReply; /********************************************************* * * GrabDevice. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GrabDevice */ CARD16 length; Window grabWindow; Time time; CARD16 event_count; CARD8 this_device_mode; CARD8 other_devices_mode; BOOL ownerEvents; CARD8 deviceid; CARD16 pad01; } xGrabDeviceReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GrabDevice */ CARD16 sequenceNumber; CARD32 length; /* 0 */ CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xGrabDeviceReply; /********************************************************* * * UngrabDevice. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_UnGrabDevice */ CARD16 length; Time time; CARD8 deviceid; BYTE pad1, pad2, pad3; } xUngrabDeviceReq; /********************************************************* * * GrabDeviceKey. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GrabDeviceKey */ CARD16 length; Window grabWindow; CARD16 event_count; CARD16 modifiers; CARD8 modifier_device; CARD8 grabbed_device; CARD8 key; BYTE this_device_mode; BYTE other_devices_mode; BOOL ownerEvents; BYTE pad1, pad2; } xGrabDeviceKeyReq; /********************************************************* * * UngrabDeviceKey. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_UngrabDeviceKey */ CARD16 length; Window grabWindow; CARD16 modifiers; CARD8 modifier_device; CARD8 key; CARD8 grabbed_device; BYTE pad1, pad2, pad3; } xUngrabDeviceKeyReq; /********************************************************* * * GrabDeviceButton. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GrabDeviceButton */ CARD16 length; Window grabWindow; CARD8 grabbed_device; CARD8 modifier_device; CARD16 event_count; CARD16 modifiers; BYTE this_device_mode; BYTE other_devices_mode; CARD8 button; BOOL ownerEvents; BYTE pad1, pad2; } xGrabDeviceButtonReq; /********************************************************* * * UngrabDeviceButton. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_UngrabDeviceButton */ CARD16 length; Window grabWindow; CARD16 modifiers; CARD8 modifier_device; CARD8 button; CARD8 grabbed_device; BYTE pad1, pad2, pad3; } xUngrabDeviceButtonReq; /********************************************************* * * AllowDeviceEvents. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_AllowDeviceEvents */ CARD16 length; Time time; CARD8 mode; CARD8 deviceid; BYTE pad1, pad2; } xAllowDeviceEventsReq; /********************************************************* * * GetDeviceFocus. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GetDeviceFocus */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xGetDeviceFocusReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceFocus */ CARD16 sequenceNumber; CARD32 length; CARD32 focus; Time time; CARD8 revertTo; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; } xGetDeviceFocusReply; /********************************************************* * * SetDeviceFocus. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_SetDeviceFocus */ CARD16 length; Window focus; Time time; CARD8 revertTo; CARD8 device; CARD16 pad01; } xSetDeviceFocusReq; /********************************************************* * * GetFeedbackControl. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_GetFeedbackControl */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xGetFeedbackControlReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetFeedbackControl */ CARD16 sequenceNumber; CARD32 length; CARD16 num_feedbacks; CARD16 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; CARD32 pad06; } xGetFeedbackControlReply; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class */ #else CARD8 class; /* feedback class */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ } xFeedbackState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 id; CARD16 length; CARD16 pitch; CARD16 duration; CARD32 led_mask; CARD32 led_values; BOOL global_auto_repeat; CARD8 click; CARD8 percent; BYTE pad; BYTE auto_repeats[32]; } xKbdFeedbackState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 id; CARD16 length; CARD8 pad1,pad2; CARD16 accelNum; CARD16 accelDenom; CARD16 threshold; } xPtrFeedbackState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; CARD16 length; /* feedback length */ CARD32 resolution; INT32 min_value; INT32 max_value; } xIntegerFeedbackState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; CARD16 length; /* feedback length */ CARD16 max_symbols; CARD16 num_syms_supported; } xStringFeedbackState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; CARD16 length; /* feedback length */ CARD8 percent; BYTE pad1, pad2, pad3; CARD16 pitch; CARD16 duration; } xBellFeedbackState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; CARD16 length; /* feedback length */ CARD32 led_mask; CARD32 led_values; } xLedFeedbackState; /********************************************************* * * ChangeFeedbackControl. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_ChangeFeedbackControl */ CARD16 length; CARD32 mask; CARD8 deviceid; CARD8 feedbackid; BYTE pad1, pad2; } xChangeFeedbackControlReq; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ } xFeedbackCtl; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback length */ CARD16 length; /* feedback length */ KeyCode key; CARD8 auto_repeat_mode; INT8 click; INT8 percent; INT16 pitch; INT16 duration; CARD32 led_mask; CARD32 led_values; } xKbdFeedbackCtl; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ CARD8 pad1,pad2; INT16 num; INT16 denom; INT16 thresh; } xPtrFeedbackCtl; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ INT32 int_to_display; } xIntegerFeedbackCtl; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ CARD8 pad1,pad2; CARD16 num_keysyms; } xStringFeedbackCtl; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ INT8 percent; BYTE pad1, pad2, pad3; INT16 pitch; INT16 duration; } xBellFeedbackCtl; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; /* feedback class id */ #else CARD8 class; /* feedback class id */ #endif CARD8 id; /* feedback id */ CARD16 length; /* feedback length */ CARD32 led_mask; CARD32 led_values; } xLedFeedbackCtl; /********************************************************* * * GetDeviceKeyMapping. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GetDeviceKeyMapping */ CARD16 length; CARD8 deviceid; KeyCode firstKeyCode; CARD8 count; BYTE pad1; } xGetDeviceKeyMappingReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceKeyMapping */ CARD16 sequenceNumber; CARD32 length; CARD8 keySymsPerKeyCode; CARD8 pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetDeviceKeyMappingReply; /********************************************************* * * ChangeDeviceKeyMapping. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_ChangeDeviceKeyMapping */ CARD16 length; CARD8 deviceid; KeyCode firstKeyCode; CARD8 keySymsPerKeyCode; CARD8 keyCodes; } xChangeDeviceKeyMappingReq; /********************************************************* * * GetDeviceModifierMapping. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GetDeviceModifierMapping */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xGetDeviceModifierMappingReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceModifierMapping */ CARD16 sequenceNumber; CARD32 length; CARD8 numKeyPerModifier; CARD8 pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xGetDeviceModifierMappingReply; /********************************************************* * * SetDeviceModifierMapping. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_SetDeviceModifierMapping */ CARD16 length; CARD8 deviceid; CARD8 numKeyPerModifier; CARD16 pad1; } xSetDeviceModifierMappingReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_SetDeviceModifierMapping */ CARD16 sequenceNumber; CARD32 length; CARD8 success; CARD8 pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xSetDeviceModifierMappingReply; /********************************************************* * * GetDeviceButtonMapping. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_GetDeviceButtonMapping */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xGetDeviceButtonMappingReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceButtonMapping */ CARD16 sequenceNumber; CARD32 length; CARD8 nElts; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xGetDeviceButtonMappingReply; /********************************************************* * * SetDeviceButtonMapping. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* X_SetDeviceButtonMapping */ CARD16 length; CARD8 deviceid; CARD8 map_length; BYTE pad1, pad2; } xSetDeviceButtonMappingReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_SetDeviceButtonMapping */ CARD16 sequenceNumber; CARD32 length; CARD8 status; BYTE pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xSetDeviceButtonMappingReply; /********************************************************* * * QueryDeviceState. * */ typedef struct { CARD8 reqType; CARD8 ReqType; /* always X_QueryDeviceState */ CARD16 length; CARD8 deviceid; BYTE pad1, pad2, pad3; } xQueryDeviceStateReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_QueryDeviceState */ CARD16 sequenceNumber; CARD32 length; CARD8 num_classes; BYTE pad0; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xQueryDeviceStateReply; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; CARD8 num_keys; BYTE pad1; CARD8 keys[32]; } xKeyState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; CARD8 num_buttons; BYTE pad1; CARD8 buttons[32]; } xButtonState; typedef struct { #if defined(__cplusplus) || defined(c_plusplus) CARD8 c_class; #else CARD8 class; #endif CARD8 length; CARD8 num_valuators; CARD8 mode; } xValuatorState; /********************************************************* * * SendExtensionEvent. * THIS REQUEST MUST BE KEPT A MULTIPLE OF 8 BYTES IN LENGTH! * MORE EVENTS MAY FOLLOW AND THEY MUST BE QUAD-ALIGNED! * */ typedef struct { CARD8 reqType; CARD8 ReqType; /* always X_SendExtensionEvent */ CARD16 length; Window destination; CARD8 deviceid; BOOL propagate; CARD16 count; CARD8 num_events; BYTE pad1,pad2,pad3; } xSendExtensionEventReq; /********************************************************* * * DeviceBell. * */ typedef struct { CARD8 reqType; CARD8 ReqType; /* always X_DeviceBell */ CARD16 length; CARD8 deviceid; CARD8 feedbackid; CARD8 feedbackclass; INT8 percent; } xDeviceBellReq; /********************************************************* * * SetDeviceValuators. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_SetDeviceValuators */ CARD16 length; CARD8 deviceid; CARD8 first_valuator; CARD8 num_valuators; BYTE pad1; } xSetDeviceValuatorsReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_SetDeviceValuators */ CARD16 sequenceNumber; CARD32 length; CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xSetDeviceValuatorsReply; /********************************************************* * * GetDeviceControl. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_GetDeviceControl */ CARD16 length; CARD16 control; CARD8 deviceid; BYTE pad2; } xGetDeviceControlReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceControl */ CARD16 sequenceNumber; CARD32 length; CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xGetDeviceControlReply; typedef struct { CARD16 control; /* control type */ CARD16 length; /* control length */ } xDeviceState; typedef struct { CARD16 control; /* control type */ CARD16 length; /* control length */ CARD32 num_valuators; /* number of valuators */ } xDeviceResolutionState; typedef struct { CARD16 control; CARD16 length; INT32 min_x; INT32 max_x; INT32 min_y; INT32 max_y; CARD32 flip_x; CARD32 flip_y; CARD32 rotation; CARD32 button_threshold; } xDeviceAbsCalibState; typedef struct { CARD16 control; CARD16 length; CARD32 offset_x; CARD32 offset_y; CARD32 width; CARD32 height; CARD32 screen; CARD32 following; } xDeviceAbsAreaState; typedef struct { CARD16 control; /* control type */ CARD16 length; /* control length */ CARD8 status; CARD8 iscore; CARD16 pad1; } xDeviceCoreState; typedef struct { CARD16 control; /* control type */ CARD16 length; /* control length */ CARD8 enable; CARD8 pad0; CARD16 pad1; } xDeviceEnableState; /********************************************************* * * ChangeDeviceControl. * */ typedef struct { CARD8 reqType; /* input extension major code */ CARD8 ReqType; /* always X_ChangeDeviceControl */ CARD16 length; CARD16 control; CARD8 deviceid; BYTE pad0; } xChangeDeviceControlReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_ChangeDeviceControl */ CARD16 sequenceNumber; CARD32 length; CARD8 status; BYTE pad1, pad2, pad3; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; } xChangeDeviceControlReply; typedef struct { CARD16 control; /* control type */ CARD16 length; /* control length */ } xDeviceCtl; typedef struct { CARD16 control; /* control type */ CARD16 length; /* control length */ CARD8 first_valuator; /* first valuator to change */ CARD8 num_valuators; /* number of valuators to change*/ CARD8 pad1,pad2; } xDeviceResolutionCtl; typedef struct { CARD16 control; CARD16 length; INT32 min_x; INT32 max_x; INT32 min_y; INT32 max_y; CARD32 flip_x; CARD32 flip_y; CARD32 rotation; CARD32 button_threshold; } xDeviceAbsCalibCtl; typedef struct { CARD16 control; CARD16 length; CARD32 offset_x; CARD32 offset_y; INT32 width; INT32 height; INT32 screen; CARD32 following; } xDeviceAbsAreaCtl; typedef struct { CARD16 control; CARD16 length; CARD8 status; CARD8 pad0; CARD16 pad1; } xDeviceCoreCtl; typedef struct { CARD16 control; CARD16 length; CARD8 enable; CARD8 pad0; CARD16 pad1; } xDeviceEnableCtl; /* XI 1.5 */ /********************************************************* * * ListDeviceProperties. * */ typedef struct { CARD8 reqType; /* input extension major opcode */ CARD8 ReqType; /* always X_ListDeviceProperties */ CARD16 length; CARD8 deviceid; CARD8 pad0; CARD16 pad1; } xListDevicePropertiesReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_ListDeviceProperties */ CARD16 sequenceNumber; CARD32 length; CARD16 nAtoms; CARD16 pad1; CARD32 pad2; CARD32 pad3; CARD32 pad4; CARD32 pad5; CARD32 pad6; } xListDevicePropertiesReply; /********************************************************* * * ChangeDeviceProperty. * */ typedef struct { CARD8 reqType; /* input extension major opcode */ CARD8 ReqType; /* always X_ChangeDeviceProperty */ CARD16 length; Atom property; Atom type; CARD8 deviceid; CARD8 format; CARD8 mode; CARD8 pad; CARD32 nUnits; } xChangeDevicePropertyReq; /********************************************************* * * DeleteDeviceProperty. * */ typedef struct { CARD8 reqType; /* input extension major opcode */ CARD8 ReqType; /* always X_DeleteDeviceProperty */ CARD16 length; Atom property; CARD8 deviceid; CARD8 pad0; CARD16 pad1; } xDeleteDevicePropertyReq; /********************************************************* * * GetDeviceProperty. * */ typedef struct { CARD8 reqType; /* input extension major opcode */ CARD8 ReqType; /* always X_GetDeviceProperty */ CARD16 length; Atom property; Atom type; CARD32 longOffset; CARD32 longLength; CARD8 deviceid; #if defined(__cplusplus) || defined(c_plusplus) BOOL c_delete; #else BOOL delete; #endif CARD16 pad; } xGetDevicePropertyReq; typedef struct { CARD8 repType; /* X_Reply */ CARD8 RepType; /* always X_GetDeviceProperty */ CARD16 sequenceNumber; CARD32 length; Atom propertyType; CARD32 bytesAfter; CARD32 nItems; CARD8 format; CARD8 deviceid; CARD16 pad1; CARD32 pad2; CARD32 pad3; } xGetDevicePropertyReply; /********************************************************** * * Input extension events. * * DeviceValuator * */ typedef struct { BYTE type; CARD8 deviceid; CARD16 sequenceNumber; KeyButMask device_state; CARD8 num_valuators; CARD8 first_valuator; INT32 valuator0; INT32 valuator1; INT32 valuator2; INT32 valuator3; INT32 valuator4; INT32 valuator5; } deviceValuator; /********************************************************** * * DeviceKeyButtonPointer. * * Used for: DeviceKeyPress, DeviceKeyRelease, * DeviceButtonPress, DeviceButtonRelease, * ProximityIn, ProximityOut * DeviceMotionNotify, * */ typedef struct { BYTE type; BYTE detail; CARD16 sequenceNumber; Time time; Window root; Window event; Window child; INT16 root_x; INT16 root_y; INT16 event_x; INT16 event_y; KeyButMask state; BOOL same_screen; CARD8 deviceid; } deviceKeyButtonPointer; /********************************************************** * * DeviceFocus. * */ typedef struct { BYTE type; BYTE detail; CARD16 sequenceNumber; Time time; Window window; BYTE mode; CARD8 deviceid; BYTE pad1, pad2; CARD32 pad00; CARD32 pad01; CARD32 pad02; CARD32 pad03; } deviceFocus; /********************************************************** * * DeviceStateNotify. * * Note that the two high-order bits in the classes_reported * field are the proximity state (InProximity or OutOfProximity), * and the device mode (Absolute or Relative), respectively. * */ typedef struct { BYTE type; BYTE deviceid; CARD16 sequenceNumber; Time time; CARD8 num_keys; CARD8 num_buttons; CARD8 num_valuators; CARD8 classes_reported; CARD8 buttons[4]; CARD8 keys[4]; INT32 valuator0; INT32 valuator1; INT32 valuator2; } deviceStateNotify; /********************************************************** * * DeviceKeyStateNotify. * */ typedef struct { BYTE type; BYTE deviceid; CARD16 sequenceNumber; CARD8 keys[28]; } deviceKeyStateNotify; /********************************************************** * * DeviceButtonStateNotify. * */ typedef struct { BYTE type; BYTE deviceid; CARD16 sequenceNumber; CARD8 buttons[28]; } deviceButtonStateNotify; /********************************************************** * * DeviceMappingNotify. * Fields must be kept in sync with core mappingnotify event. * */ typedef struct { BYTE type; BYTE deviceid; CARD16 sequenceNumber; CARD8 request; KeyCode firstKeyCode; CARD8 count; BYTE pad1; Time time; CARD32 pad00; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; } deviceMappingNotify; /********************************************************** * * ChangeDeviceNotify. * */ typedef struct { BYTE type; BYTE deviceid; CARD16 sequenceNumber; Time time; CARD8 request; BYTE pad1, pad2, pad3; CARD32 pad00; CARD32 pad01; CARD32 pad02; CARD32 pad03; CARD32 pad04; } changeDeviceNotify; /********************************************************** * * devicePresenceNotify. * */ typedef struct { BYTE type; BYTE pad00; CARD16 sequenceNumber; Time time; BYTE devchange; /* Device{Added|Removed|Enabled|Disabled|ControlChanged} */ BYTE deviceid; CARD16 control; CARD32 pad02; CARD32 pad03; CARD32 pad04; CARD32 pad05; CARD32 pad06; } devicePresenceNotify; /********************************************************* * DevicePropertyNotifyEvent * * Sent whenever a device's property changes. * */ typedef struct { BYTE type; BYTE state; /* NewValue or Deleted */ CARD16 sequenceNumber; CARD32 time; Atom atom; /* affected property */ CARD32 pad0; CARD32 pad1; CARD32 pad2; CARD32 pad3; CARD16 pad5; CARD8 pad4; CARD8 deviceid; /* id of device */ } devicePropertyNotify; #undef Window #undef Time #undef KeyCode #undef Mask #undef Atom #undef Cursor #endif X11/extensions/xtestext1const.h000064400000012477151027430560012523 0ustar00/* * xtestext1.h * * X11 Input Synthesis Extension include file */ /* Copyright 1986, 1987, 1988, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1986, 1987, 1988 by Hewlett-Packard Corporation Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Hewlett-Packard not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. Hewlett-Packard makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. This software is not subject to any license of the American Telephone and Telegraph Company or of the Regents of the University of California. */ #ifndef _XTESTEXT1CONST_H #define _XTESTEXT1CONST_H 1 #define XTestMAX_ACTION_LIST_SIZE 64 #define XTestACTIONS_SIZE 28 /* * used in the XTestPressButton and XTestPressKey functions */ #define XTestPRESS 1 << 0 #define XTestRELEASE 1 << 1 #define XTestSTROKE 1 << 2 /* * When doing a key or button stroke, the number of milliseconds * to delay between the press and the release of a key or button * in the XTestPressButton and XTestPressKey functions. */ #define XTestSTROKE_DELAY_TIME 10 /* * used in the XTestGetInput function */ #define XTestEXCLUSIVE 1 << 0 #define XTestPACKED_ACTIONS 1 << 1 #define XTestPACKED_MOTION 1 << 2 /* * used in the XTestFakeInput function */ #define XTestFAKE_ACK_NOT_NEEDED 0 #define XTestFAKE_ACK_REQUEST 1 /* * used in the XTest extension initialization routine */ #define XTestEXTENSION_NAME "XTestExtension1" #define XTestEVENT_COUNT 2 /* * This is the definition for the format of the header byte * in the input action structures. */ #define XTestACTION_TYPE_MASK 0x03 /* bits 0 and 1 */ #define XTestKEY_STATE_MASK 0x04 /* bit 2 (key action) */ #define XTestX_SIGN_BIT_MASK 0x04 /* bit 2 (motion action) */ #define XTestY_SIGN_BIT_MASK 0x08 /* bit 3 (motion action) */ #define XTestDEVICE_ID_MASK 0xf0 /* bits 4 through 7 */ #define XTestMAX_DEVICE_ID 0x0f #define XTestPackDeviceID(x) (((x) & XTestMAX_DEVICE_ID) << 4) #define XTestUnpackDeviceID(x) (((x) & XTestDEVICE_ID_MASK) >> 4) /* * These are the possible action types. */ #define XTestDELAY_ACTION 0 #define XTestKEY_ACTION 1 #define XTestMOTION_ACTION 2 #define XTestJUMP_ACTION 3 /* * These are the definitions for key/button motion input actions. */ #define XTestKEY_UP 0x04 #define XTestKEY_DOWN 0x00 /* * These are the definitions for pointer relative motion input * actions. * * The sign bits for the x and y relative motions are contained * in the header byte. The x and y relative motions are packed * into one byte to make things fit in 32 bits. If the relative * motion range is larger than +/-15, use the pointer jump action. */ #define XTestMOTION_MAX 15 #define XTestMOTION_MIN -15 #define XTestX_NEGATIVE 0x04 #define XTestY_NEGATIVE 0x08 #define XTestX_MOTION_MASK 0x0f #define XTestY_MOTION_MASK 0xf0 #define XTestPackXMotionValue(x) ((x) & XTestX_MOTION_MASK) #define XTestPackYMotionValue(x) (((x) << 4) & XTestY_MOTION_MASK) #define XTestUnpackXMotionValue(x) ((x) & XTestX_MOTION_MASK) #define XTestUnpackYMotionValue(x) (((x) & XTestY_MOTION_MASK) >> 4) /* * These are the definitions for a long delay input action. It is * used when more than XTestSHORT_DELAY_TIME milliseconds of delay * (approximately one minute) is needed. * * The device ID for a delay is always set to XTestDELAY_DEVICE_ID. * This guarantees that a header byte with a value of 0 is not * a valid header, so it can be used as a flag to indicate that * there are no more input actions in an XTestInputAction event. */ #define XTestSHORT_DELAY_TIME 0xffff #define XTestDELAY_DEVICE_ID 0x0f #endif /* _XTESTEXT1CONST_H */ X11/XF86keysym.h000064400000032454151027430560007236 0ustar00/* * XFree86 vendor specific keysyms. * * The XFree86 keysym range is 0x10080001 - 0x1008FFFF. * * X.Org will not be adding to the XF86 set of keysyms, though they have * been adopted and are considered a "standard" part of X keysym definitions. * XFree86 never properly commented these keysyms, so we have done our * best to explain the semantic meaning of these keys. * * XFree86 has removed their mail archives of the period, that might have * shed more light on some of these definitions. Until/unless we resurrect * these archives, these are from memory and usage. */ /* * ModeLock * * This one is old, and not really used any more since XKB offers this * functionality. */ #define XF86XK_ModeLock 0x1008FF01 /* Mode Switch Lock */ /* Backlight controls. */ #define XF86XK_MonBrightnessUp 0x1008FF02 /* Monitor/panel brightness */ #define XF86XK_MonBrightnessDown 0x1008FF03 /* Monitor/panel brightness */ #define XF86XK_KbdLightOnOff 0x1008FF04 /* Keyboards may be lit */ #define XF86XK_KbdBrightnessUp 0x1008FF05 /* Keyboards may be lit */ #define XF86XK_KbdBrightnessDown 0x1008FF06 /* Keyboards may be lit */ #define XF86XK_MonBrightnessCycle 0x1008FF07 /* Monitor/panel brightness */ /* * Keys found on some "Internet" keyboards. */ #define XF86XK_Standby 0x1008FF10 /* System into standby mode */ #define XF86XK_AudioLowerVolume 0x1008FF11 /* Volume control down */ #define XF86XK_AudioMute 0x1008FF12 /* Mute sound from the system */ #define XF86XK_AudioRaiseVolume 0x1008FF13 /* Volume control up */ #define XF86XK_AudioPlay 0x1008FF14 /* Start playing of audio > */ #define XF86XK_AudioStop 0x1008FF15 /* Stop playing audio */ #define XF86XK_AudioPrev 0x1008FF16 /* Previous track */ #define XF86XK_AudioNext 0x1008FF17 /* Next track */ #define XF86XK_HomePage 0x1008FF18 /* Display user's home page */ #define XF86XK_Mail 0x1008FF19 /* Invoke user's mail program */ #define XF86XK_Start 0x1008FF1A /* Start application */ #define XF86XK_Search 0x1008FF1B /* Search */ #define XF86XK_AudioRecord 0x1008FF1C /* Record audio application */ /* These are sometimes found on PDA's (e.g. Palm, PocketPC or elsewhere) */ #define XF86XK_Calculator 0x1008FF1D /* Invoke calculator program */ #define XF86XK_Memo 0x1008FF1E /* Invoke Memo taking program */ #define XF86XK_ToDoList 0x1008FF1F /* Invoke To Do List program */ #define XF86XK_Calendar 0x1008FF20 /* Invoke Calendar program */ #define XF86XK_PowerDown 0x1008FF21 /* Deep sleep the system */ #define XF86XK_ContrastAdjust 0x1008FF22 /* Adjust screen contrast */ #define XF86XK_RockerUp 0x1008FF23 /* Rocker switches exist up */ #define XF86XK_RockerDown 0x1008FF24 /* and down */ #define XF86XK_RockerEnter 0x1008FF25 /* and let you press them */ /* Some more "Internet" keyboard symbols */ #define XF86XK_Back 0x1008FF26 /* Like back on a browser */ #define XF86XK_Forward 0x1008FF27 /* Like forward on a browser */ #define XF86XK_Stop 0x1008FF28 /* Stop current operation */ #define XF86XK_Refresh 0x1008FF29 /* Refresh the page */ #define XF86XK_PowerOff 0x1008FF2A /* Power off system entirely */ #define XF86XK_WakeUp 0x1008FF2B /* Wake up system from sleep */ #define XF86XK_Eject 0x1008FF2C /* Eject device (e.g. DVD) */ #define XF86XK_ScreenSaver 0x1008FF2D /* Invoke screensaver */ #define XF86XK_WWW 0x1008FF2E /* Invoke web browser */ #define XF86XK_Sleep 0x1008FF2F /* Put system to sleep */ #define XF86XK_Favorites 0x1008FF30 /* Show favorite locations */ #define XF86XK_AudioPause 0x1008FF31 /* Pause audio playing */ #define XF86XK_AudioMedia 0x1008FF32 /* Launch media collection app */ #define XF86XK_MyComputer 0x1008FF33 /* Display "My Computer" window */ #define XF86XK_VendorHome 0x1008FF34 /* Display vendor home web site */ #define XF86XK_LightBulb 0x1008FF35 /* Light bulb keys exist */ #define XF86XK_Shop 0x1008FF36 /* Display shopping web site */ #define XF86XK_History 0x1008FF37 /* Show history of web surfing */ #define XF86XK_OpenURL 0x1008FF38 /* Open selected URL */ #define XF86XK_AddFavorite 0x1008FF39 /* Add URL to favorites list */ #define XF86XK_HotLinks 0x1008FF3A /* Show "hot" links */ #define XF86XK_BrightnessAdjust 0x1008FF3B /* Invoke brightness adj. UI */ #define XF86XK_Finance 0x1008FF3C /* Display financial site */ #define XF86XK_Community 0x1008FF3D /* Display user's community */ #define XF86XK_AudioRewind 0x1008FF3E /* "rewind" audio track */ #define XF86XK_BackForward 0x1008FF3F /* ??? */ #define XF86XK_Launch0 0x1008FF40 /* Launch Application */ #define XF86XK_Launch1 0x1008FF41 /* Launch Application */ #define XF86XK_Launch2 0x1008FF42 /* Launch Application */ #define XF86XK_Launch3 0x1008FF43 /* Launch Application */ #define XF86XK_Launch4 0x1008FF44 /* Launch Application */ #define XF86XK_Launch5 0x1008FF45 /* Launch Application */ #define XF86XK_Launch6 0x1008FF46 /* Launch Application */ #define XF86XK_Launch7 0x1008FF47 /* Launch Application */ #define XF86XK_Launch8 0x1008FF48 /* Launch Application */ #define XF86XK_Launch9 0x1008FF49 /* Launch Application */ #define XF86XK_LaunchA 0x1008FF4A /* Launch Application */ #define XF86XK_LaunchB 0x1008FF4B /* Launch Application */ #define XF86XK_LaunchC 0x1008FF4C /* Launch Application */ #define XF86XK_LaunchD 0x1008FF4D /* Launch Application */ #define XF86XK_LaunchE 0x1008FF4E /* Launch Application */ #define XF86XK_LaunchF 0x1008FF4F /* Launch Application */ #define XF86XK_ApplicationLeft 0x1008FF50 /* switch to application, left */ #define XF86XK_ApplicationRight 0x1008FF51 /* switch to application, right*/ #define XF86XK_Book 0x1008FF52 /* Launch bookreader */ #define XF86XK_CD 0x1008FF53 /* Launch CD/DVD player */ #define XF86XK_Calculater 0x1008FF54 /* Launch Calculater */ #define XF86XK_Clear 0x1008FF55 /* Clear window, screen */ #define XF86XK_Close 0x1008FF56 /* Close window */ #define XF86XK_Copy 0x1008FF57 /* Copy selection */ #define XF86XK_Cut 0x1008FF58 /* Cut selection */ #define XF86XK_Display 0x1008FF59 /* Output switch key */ #define XF86XK_DOS 0x1008FF5A /* Launch DOS (emulation) */ #define XF86XK_Documents 0x1008FF5B /* Open documents window */ #define XF86XK_Excel 0x1008FF5C /* Launch spread sheet */ #define XF86XK_Explorer 0x1008FF5D /* Launch file explorer */ #define XF86XK_Game 0x1008FF5E /* Launch game */ #define XF86XK_Go 0x1008FF5F /* Go to URL */ #define XF86XK_iTouch 0x1008FF60 /* Logitech iTouch- don't use */ #define XF86XK_LogOff 0x1008FF61 /* Log off system */ #define XF86XK_Market 0x1008FF62 /* ?? */ #define XF86XK_Meeting 0x1008FF63 /* enter meeting in calendar */ #define XF86XK_MenuKB 0x1008FF65 /* distinguish keyboard from PB */ #define XF86XK_MenuPB 0x1008FF66 /* distinguish PB from keyboard */ #define XF86XK_MySites 0x1008FF67 /* Favourites */ #define XF86XK_New 0x1008FF68 /* New (folder, document... */ #define XF86XK_News 0x1008FF69 /* News */ #define XF86XK_OfficeHome 0x1008FF6A /* Office home (old Staroffice)*/ #define XF86XK_Open 0x1008FF6B /* Open */ #define XF86XK_Option 0x1008FF6C /* ?? */ #define XF86XK_Paste 0x1008FF6D /* Paste */ #define XF86XK_Phone 0x1008FF6E /* Launch phone; dial number */ #define XF86XK_Q 0x1008FF70 /* Compaq's Q - don't use */ #define XF86XK_Reply 0x1008FF72 /* Reply e.g., mail */ #define XF86XK_Reload 0x1008FF73 /* Reload web page, file, etc. */ #define XF86XK_RotateWindows 0x1008FF74 /* Rotate windows e.g. xrandr */ #define XF86XK_RotationPB 0x1008FF75 /* don't use */ #define XF86XK_RotationKB 0x1008FF76 /* don't use */ #define XF86XK_Save 0x1008FF77 /* Save (file, document, state */ #define XF86XK_ScrollUp 0x1008FF78 /* Scroll window/contents up */ #define XF86XK_ScrollDown 0x1008FF79 /* Scrool window/contentd down */ #define XF86XK_ScrollClick 0x1008FF7A /* Use XKB mousekeys instead */ #define XF86XK_Send 0x1008FF7B /* Send mail, file, object */ #define XF86XK_Spell 0x1008FF7C /* Spell checker */ #define XF86XK_SplitScreen 0x1008FF7D /* Split window or screen */ #define XF86XK_Support 0x1008FF7E /* Get support (??) */ #define XF86XK_TaskPane 0x1008FF7F /* Show tasks */ #define XF86XK_Terminal 0x1008FF80 /* Launch terminal emulator */ #define XF86XK_Tools 0x1008FF81 /* toolbox of desktop/app. */ #define XF86XK_Travel 0x1008FF82 /* ?? */ #define XF86XK_UserPB 0x1008FF84 /* ?? */ #define XF86XK_User1KB 0x1008FF85 /* ?? */ #define XF86XK_User2KB 0x1008FF86 /* ?? */ #define XF86XK_Video 0x1008FF87 /* Launch video player */ #define XF86XK_WheelButton 0x1008FF88 /* button from a mouse wheel */ #define XF86XK_Word 0x1008FF89 /* Launch word processor */ #define XF86XK_Xfer 0x1008FF8A #define XF86XK_ZoomIn 0x1008FF8B /* zoom in view, map, etc. */ #define XF86XK_ZoomOut 0x1008FF8C /* zoom out view, map, etc. */ #define XF86XK_Away 0x1008FF8D /* mark yourself as away */ #define XF86XK_Messenger 0x1008FF8E /* as in instant messaging */ #define XF86XK_WebCam 0x1008FF8F /* Launch web camera app. */ #define XF86XK_MailForward 0x1008FF90 /* Forward in mail */ #define XF86XK_Pictures 0x1008FF91 /* Show pictures */ #define XF86XK_Music 0x1008FF92 /* Launch music application */ #define XF86XK_Battery 0x1008FF93 /* Display battery information */ #define XF86XK_Bluetooth 0x1008FF94 /* Enable/disable Bluetooth */ #define XF86XK_WLAN 0x1008FF95 /* Enable/disable WLAN */ #define XF86XK_UWB 0x1008FF96 /* Enable/disable UWB */ #define XF86XK_AudioForward 0x1008FF97 /* fast-forward audio track */ #define XF86XK_AudioRepeat 0x1008FF98 /* toggle repeat mode */ #define XF86XK_AudioRandomPlay 0x1008FF99 /* toggle shuffle mode */ #define XF86XK_Subtitle 0x1008FF9A /* cycle through subtitle */ #define XF86XK_AudioCycleTrack 0x1008FF9B /* cycle through audio tracks */ #define XF86XK_CycleAngle 0x1008FF9C /* cycle through angles */ #define XF86XK_FrameBack 0x1008FF9D /* video: go one frame back */ #define XF86XK_FrameForward 0x1008FF9E /* video: go one frame forward */ #define XF86XK_Time 0x1008FF9F /* display, or shows an entry for time seeking */ #define XF86XK_Select 0x1008FFA0 /* Select button on joypads and remotes */ #define XF86XK_View 0x1008FFA1 /* Show a view options/properties */ #define XF86XK_TopMenu 0x1008FFA2 /* Go to a top-level menu in a video */ #define XF86XK_Red 0x1008FFA3 /* Red button */ #define XF86XK_Green 0x1008FFA4 /* Green button */ #define XF86XK_Yellow 0x1008FFA5 /* Yellow button */ #define XF86XK_Blue 0x1008FFA6 /* Blue button */ #define XF86XK_Suspend 0x1008FFA7 /* Sleep to RAM */ #define XF86XK_Hibernate 0x1008FFA8 /* Sleep to disk */ #define XF86XK_TouchpadToggle 0x1008FFA9 /* Toggle between touchpad/trackstick */ #define XF86XK_TouchpadOn 0x1008FFB0 /* The touchpad got switched on */ #define XF86XK_TouchpadOff 0x1008FFB1 /* The touchpad got switched off */ #define XF86XK_AudioMicMute 0x1008FFB2 /* Mute the Mic from the system */ #define XF86XK_Keyboard 0x1008FFB3 /* User defined keyboard related action */ #define XF86XK_WWAN 0x1008FFB4 /* Toggle WWAN (LTE, UMTS, etc.) radio */ #define XF86XK_RFKill 0x1008FFB5 /* Toggle radios on/off */ #define XF86XK_AudioPreset 0x1008FFB6 /* Select equalizer preset, e.g. theatre-mode */ #define XF86XK_RotationLockToggle 0x1008FFB7 /* Toggle screen rotation lock on/off */ #define XF86XK_FullScreen 0x1008FFB8 /* Toggle fullscreen */ /* Keys for special action keys (hot keys) */ /* Virtual terminals on some operating systems */ #define XF86XK_Switch_VT_1 0x1008FE01 #define XF86XK_Switch_VT_2 0x1008FE02 #define XF86XK_Switch_VT_3 0x1008FE03 #define XF86XK_Switch_VT_4 0x1008FE04 #define XF86XK_Switch_VT_5 0x1008FE05 #define XF86XK_Switch_VT_6 0x1008FE06 #define XF86XK_Switch_VT_7 0x1008FE07 #define XF86XK_Switch_VT_8 0x1008FE08 #define XF86XK_Switch_VT_9 0x1008FE09 #define XF86XK_Switch_VT_10 0x1008FE0A #define XF86XK_Switch_VT_11 0x1008FE0B #define XF86XK_Switch_VT_12 0x1008FE0C #define XF86XK_Ungrab 0x1008FE20 /* force ungrab */ #define XF86XK_ClearGrab 0x1008FE21 /* kill application with grab */ #define XF86XK_Next_VMode 0x1008FE22 /* next video mode available */ #define XF86XK_Prev_VMode 0x1008FE23 /* prev. video mode available */ #define XF86XK_LogWindowTree 0x1008FE24 /* print window tree to log */ #define XF86XK_LogGrabInfo 0x1008FE25 /* print all active grabs to log */ X11/Xlibint.h000064400000117077151027430560006717 0ustar00 /* Copyright 1984, 1985, 1987, 1989, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifndef _X11_XLIBINT_H_ #define _X11_XLIBINT_H_ 1 /* * Xlibint.h - Header definition and support file for the internal * support routines used by the C subroutine interface * library (Xlib) to the X Window System. * * Warning, there be dragons here.... */ #include #include #include /* to declare xEvent */ #include /* for configured options like XTHREADS */ /* The Xlib structs are full of implicit padding to properly align members. We can't clean that up without breaking ABI, so tell clang not to bother complaining about it. */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif #ifdef WIN32 #define _XFlush _XFlushIt #endif struct _XGC { XExtData *ext_data; /* hook for extension to hang data */ GContext gid; /* protocol ID for graphics context */ Bool rects; /* boolean: TRUE if clipmask is list of rectangles */ Bool dashes; /* boolean: TRUE if dash-list is really a list */ unsigned long dirty;/* cache dirty bits */ XGCValues values; /* shadow structure of values */ }; struct _XDisplay { XExtData *ext_data; /* hook for extension to hang data */ struct _XFreeFuncs *free_funcs; /* internal free functions */ int fd; /* Network socket. */ int conn_checker; /* ugly thing used by _XEventsQueued */ int proto_major_version;/* maj. version of server's X protocol */ int proto_minor_version;/* minor version of server's X protocol */ char *vendor; /* vendor of the server hardware */ XID resource_base; /* resource ID base */ XID resource_mask; /* resource ID mask bits */ XID resource_id; /* allocator current ID */ int resource_shift; /* allocator shift to correct bits */ XID (*resource_alloc)( /* allocator function */ struct _XDisplay* ); int byte_order; /* screen byte order, LSBFirst, MSBFirst */ int bitmap_unit; /* padding and data requirements */ int bitmap_pad; /* padding requirements on bitmaps */ int bitmap_bit_order; /* LeastSignificant or MostSignificant */ int nformats; /* number of pixmap formats in list */ ScreenFormat *pixmap_format; /* pixmap format list */ int vnumber; /* Xlib's X protocol version number. */ int release; /* release of the server */ struct _XSQEvent *head, *tail; /* Input event queue. */ int qlen; /* Length of input event queue */ unsigned long last_request_read; /* seq number of last event read */ unsigned long request; /* sequence number of last request. */ char *last_req; /* beginning of last request, or dummy */ char *buffer; /* Output buffer starting address. */ char *bufptr; /* Output buffer index pointer. */ char *bufmax; /* Output buffer maximum+1 address. */ unsigned max_request_size; /* maximum number 32 bit words in request*/ struct _XrmHashBucketRec *db; int (*synchandler)( /* Synchronization handler */ struct _XDisplay* ); char *display_name; /* "host:display" string used on this connect*/ int default_screen; /* default screen for operations */ int nscreens; /* number of screens on this server*/ Screen *screens; /* pointer to list of screens */ unsigned long motion_buffer; /* size of motion buffer */ volatile unsigned long flags; /* internal connection flags */ int min_keycode; /* minimum defined keycode */ int max_keycode; /* maximum defined keycode */ KeySym *keysyms; /* This server's keysyms */ XModifierKeymap *modifiermap; /* This server's modifier keymap */ int keysyms_per_keycode;/* number of rows */ char *xdefaults; /* contents of defaults from server */ char *scratch_buffer; /* place to hang scratch buffer */ unsigned long scratch_length; /* length of scratch buffer */ int ext_number; /* extension number on this display */ struct _XExten *ext_procs; /* extensions initialized on this display */ /* * the following can be fixed size, as the protocol defines how * much address space is available. * While this could be done using the extension vector, there * may be MANY events processed, so a search through the extension * list to find the right procedure for each event might be * expensive if many extensions are being used. */ Bool (*event_vec[128])( /* vector for wire to event */ Display * /* dpy */, XEvent * /* re */, xEvent * /* event */ ); Status (*wire_vec[128])( /* vector for event to wire */ Display * /* dpy */, XEvent * /* re */, xEvent * /* event */ ); KeySym lock_meaning; /* for XLookupString */ struct _XLockInfo *lock; /* multi-thread state, display lock */ struct _XInternalAsync *async_handlers; /* for internal async */ unsigned long bigreq_size; /* max size of big requests */ struct _XLockPtrs *lock_fns; /* pointers to threads functions */ void (*idlist_alloc)( /* XID list allocator function */ Display * /* dpy */, XID * /* ids */, int /* count */ ); /* things above this line should not move, for binary compatibility */ struct _XKeytrans *key_bindings; /* for XLookupString */ Font cursor_font; /* for XCreateFontCursor */ struct _XDisplayAtoms *atoms; /* for XInternAtom */ unsigned int mode_switch; /* keyboard group modifiers */ unsigned int num_lock; /* keyboard numlock modifiers */ struct _XContextDB *context_db; /* context database */ Bool (**error_vec)( /* vector for wire to error */ Display * /* display */, XErrorEvent * /* he */, xError * /* we */ ); /* * Xcms information */ struct { XPointer defaultCCCs; /* pointer to an array of default XcmsCCC */ XPointer clientCmaps; /* pointer to linked list of XcmsCmapRec */ XPointer perVisualIntensityMaps; /* linked list of XcmsIntensityMap */ } cms; struct _XIMFilter *im_filters; struct _XSQEvent *qfree; /* unallocated event queue elements */ unsigned long next_event_serial_num; /* inserted into next queue elt */ struct _XExten *flushes; /* Flush hooks */ struct _XConnectionInfo *im_fd_info; /* _XRegisterInternalConnection */ int im_fd_length; /* number of im_fd_info */ struct _XConnWatchInfo *conn_watchers; /* XAddConnectionWatch */ int watcher_count; /* number of conn_watchers */ XPointer filedes; /* struct pollfd cache for _XWaitForReadable */ int (*savedsynchandler)( /* user synchandler when Xlib usurps */ Display * /* dpy */ ); XID resource_max; /* allocator max ID */ int xcmisc_opcode; /* major opcode for XC-MISC */ struct _XkbInfoRec *xkb_info; /* XKB info */ struct _XtransConnInfo *trans_conn; /* transport connection object */ struct _X11XCBPrivate *xcb; /* XCB glue private data */ /* Generic event cookie handling */ unsigned int next_cookie; /* next event cookie */ /* vector for wire to generic event, index is (extension - 128) */ Bool (*generic_event_vec[128])( Display * /* dpy */, XGenericEventCookie * /* Xlib event */, xEvent * /* wire event */); /* vector for event copy, index is (extension - 128) */ Bool (*generic_event_copy_vec[128])( Display * /* dpy */, XGenericEventCookie * /* in */, XGenericEventCookie * /* out*/); void *cookiejar; /* cookie events returned but not claimed */ #ifndef LONG64 unsigned long last_request_read_upper32bit; unsigned long request_upper32bit; #endif struct _XErrorThreadInfo *error_threads; }; #define XAllocIDs(dpy,ids,n) (*(dpy)->idlist_alloc)(dpy,ids,n) /* * access "last_request_read" and "request" with 64bit * warning: the value argument of the SET-macros must not * have any side-effects because it may get called twice. */ #ifndef LONG64 /* accessors for 32-bit unsigned long */ #define X_DPY_GET_REQUEST(dpy) \ ( \ ((uint64_t)(((struct _XDisplay*)dpy)->request)) \ + (((uint64_t)(((struct _XDisplay*)dpy)->request_upper32bit)) << 32) \ ) #define X_DPY_SET_REQUEST(dpy, value) \ ( \ (((struct _XDisplay*)dpy)->request = \ (value) & 0xFFFFFFFFUL), \ (((struct _XDisplay*)dpy)->request_upper32bit = \ ((uint64_t)(value)) >> 32), \ (void)0 /* don't use the result */ \ ) #define X_DPY_GET_LAST_REQUEST_READ(dpy) \ ( \ ((uint64_t)(((struct _XDisplay*)dpy)->last_request_read)) \ + ( \ ((uint64_t)( \ ((struct _XDisplay*)dpy)->last_request_read_upper32bit \ )) << 32 \ ) \ ) #define X_DPY_SET_LAST_REQUEST_READ(dpy, value) \ ( \ (((struct _XDisplay*)dpy)->last_request_read = \ (value) & 0xFFFFFFFFUL), \ (((struct _XDisplay*)dpy)->last_request_read_upper32bit = \ ((uint64_t)(value)) >> 32), \ (void)0 /* don't use the result */ \ ) /* * widen a 32-bit sequence number to a 64 sequence number. * This macro makes the following assumptions: * - ulseq refers to a sequence that has already been sent * - ulseq means the most recent possible sequence number * with these lower 32 bits. * * The following optimization is used: * The comparison result is taken a 0 or 1 to avoid a branch. */ #define X_DPY_WIDEN_UNSIGNED_LONG_SEQ(dpy, ulseq) \ ( \ ((uint64_t)ulseq) \ + \ (( \ ((uint64_t)(((struct _XDisplay*)dpy)->request_upper32bit)) \ - (uint64_t)( \ (ulseq) > (((struct _XDisplay*)dpy)->request) \ ) \ ) << 32) \ ) #define X_DPY_REQUEST_INCREMENT(dpy) \ ( \ ((struct _XDisplay*)dpy)->request++, \ ( \ (((struct _XDisplay*)dpy)->request == 0) ? ( \ ((struct _XDisplay*)dpy)->request_upper32bit++ \ ) : 0 \ ), \ (void)0 /* don't use the result */ \ ) #define X_DPY_REQUEST_DECREMENT(dpy) \ ( \ ( \ (((struct _XDisplay*)dpy)->request == 0) ? (\ ((struct _XDisplay*)dpy)->request--, /* wrap */ \ ((struct _XDisplay*)dpy)->request_upper32bit-- \ ) : ( \ ((struct _XDisplay*)dpy)->request-- \ ) \ ), \ (void)0 /* don't use the result */ \ ) #else /* accessors for 64-bit unsigned long */ #define X_DPY_GET_REQUEST(dpy) \ (((struct _XDisplay*)dpy)->request) #define X_DPY_SET_REQUEST(dpy, value) \ ((struct _XDisplay*)dpy)->request = (value) #define X_DPY_GET_LAST_REQUEST_READ(dpy) \ (((struct _XDisplay*)dpy)->last_request_read) #define X_DPY_SET_LAST_REQUEST_READ(dpy, value) \ ((struct _XDisplay*)dpy)->last_request_read = (value) #define X_DPY_WIDEN_UNSIGNED_LONG_SEQ(dpy, ulseq) ulseq #define X_DPY_REQUEST_INCREMENT(dpy) ((struct _XDisplay*)dpy)->request++ #define X_DPY_REQUEST_DECREMENT(dpy) ((struct _XDisplay*)dpy)->request-- #endif #ifndef _XEVENT_ /* * _QEvent datatype for use in input queueing. */ typedef struct _XSQEvent { struct _XSQEvent *next; XEvent event; unsigned long qserial_num; /* so multi-threaded code can find new ones */ } _XQEvent; #endif #include #ifdef __sgi #define _SGI_MP_SOURCE /* turn this on to get MP safe errno */ #endif #include #define _XBCOPYFUNC _Xbcopy #include #include /* Utek leaves kernel macros around in include files (bleah) */ #ifdef dirty #undef dirty #endif #include #include #include _XFUNCPROTOBEGIN /* * The following definitions can be used for locking requests in multi-threaded * address spaces. */ #ifdef XTHREADS /* Author: Stephen Gildea, MIT X Consortium * * declarations for C Threads locking */ typedef struct _LockInfoRec *LockInfoPtr; /* interfaces for locking.c */ struct _XLockPtrs { /* used by all, including extensions; do not move */ void (*lock_display)( Display *dpy #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE) , char *file , int line #endif ); void (*unlock_display)( Display *dpy #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE) , char *file , int line #endif ); }; #if defined(WIN32) && !defined(_XLIBINT_) #define _XCreateMutex_fn (*_XCreateMutex_fn_p) #define _XFreeMutex_fn (*_XFreeMutex_fn_p) #define _XLockMutex_fn (*_XLockMutex_fn_p) #define _XUnlockMutex_fn (*_XUnlockMutex_fn_p) #define _Xglobal_lock (*_Xglobal_lock_p) #endif /* in XlibInt.c */ extern void (*_XCreateMutex_fn)( LockInfoPtr /* lock */ ); extern void (*_XFreeMutex_fn)( LockInfoPtr /* lock */ ); extern void (*_XLockMutex_fn)( LockInfoPtr /* lock */ #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE) , char * /* file */ , int /* line */ #endif ); extern void (*_XUnlockMutex_fn)( LockInfoPtr /* lock */ #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE) , char * /* file */ , int /* line */ #endif ); extern LockInfoPtr _Xglobal_lock; #if defined(XTHREADS_WARN) || defined(XTHREADS_FILE_LINE) #define LockDisplay(d) if ((d)->lock_fns) (*(d)->lock_fns->lock_display)((d),__FILE__,__LINE__) #define UnlockDisplay(d) if ((d)->lock_fns) (*(d)->lock_fns->unlock_display)((d),__FILE__,__LINE__) #define _XLockMutex(lock) if (_XLockMutex_fn) (*_XLockMutex_fn)(lock,__FILE__,__LINE__) #define _XUnlockMutex(lock) if (_XUnlockMutex_fn) (*_XUnlockMutex_fn)(lock,__FILE__,__LINE__) #else /* used everywhere, so must be fast if not using threads */ #define LockDisplay(d) if ((d)->lock_fns) (*(d)->lock_fns->lock_display)(d) #define UnlockDisplay(d) if ((d)->lock_fns) (*(d)->lock_fns->unlock_display)(d) #define _XLockMutex(lock) if (_XLockMutex_fn) (*_XLockMutex_fn)(lock) #define _XUnlockMutex(lock) if (_XUnlockMutex_fn) (*_XUnlockMutex_fn)(lock) #endif #define _XCreateMutex(lock) if (_XCreateMutex_fn) (*_XCreateMutex_fn)(lock); #define _XFreeMutex(lock) if (_XFreeMutex_fn) (*_XFreeMutex_fn)(lock); #else /* XTHREADS */ #define LockDisplay(dis) #define _XLockMutex(lock) #define _XUnlockMutex(lock) #define UnlockDisplay(dis) #define _XCreateMutex(lock) #define _XFreeMutex(lock) #endif #define Xfree(ptr) free((ptr)) /* * Note that some machines do not return a valid pointer for malloc(0), in * which case we provide an alternate under the control of the * define MALLOC_0_RETURNS_NULL. This is necessary because some * Xlib code expects malloc(0) to return a valid pointer to storage. */ #if defined(MALLOC_0_RETURNS_NULL) || defined(__clang_analyzer__) # define Xmalloc(size) malloc(((size) == 0 ? 1 : (size))) # define Xrealloc(ptr, size) realloc((ptr), ((size) == 0 ? 1 : (size))) # define Xcalloc(nelem, elsize) calloc(((nelem) == 0 ? 1 : (nelem)), (elsize)) #else # define Xmalloc(size) malloc((size)) # define Xrealloc(ptr, size) realloc((ptr), (size)) # define Xcalloc(nelem, elsize) calloc((nelem), (elsize)) #endif #include #define LOCKED 1 #define UNLOCKED 0 #ifndef BUFSIZE #define BUFSIZE 2048 /* X output buffer size. */ #endif #ifndef PTSPERBATCH #define PTSPERBATCH 1024 /* point batching */ #endif #ifndef WLNSPERBATCH #define WLNSPERBATCH 50 /* wide line batching */ #endif #ifndef ZLNSPERBATCH #define ZLNSPERBATCH 1024 /* thin line batching */ #endif #ifndef WRCTSPERBATCH #define WRCTSPERBATCH 10 /* wide line rectangle batching */ #endif #ifndef ZRCTSPERBATCH #define ZRCTSPERBATCH 256 /* thin line rectangle batching */ #endif #ifndef FRCTSPERBATCH #define FRCTSPERBATCH 256 /* filled rectangle batching */ #endif #ifndef FARCSPERBATCH #define FARCSPERBATCH 256 /* filled arc batching */ #endif #ifndef CURSORFONT #define CURSORFONT "cursor" /* standard cursor fonts */ #endif /* * Display flags */ #define XlibDisplayIOError (1L << 0) #define XlibDisplayClosing (1L << 1) #define XlibDisplayNoXkb (1L << 2) #define XlibDisplayPrivSync (1L << 3) #define XlibDisplayProcConni (1L << 4) /* in _XProcessInternalConnection */ #define XlibDisplayReadEvents (1L << 5) /* in _XReadEvents */ #define XlibDisplayReply (1L << 5) /* in _XReply */ #define XlibDisplayWriting (1L << 6) /* in _XFlushInt, _XSend */ #define XlibDisplayDfltRMDB (1L << 7) /* mark if RM db from XGetDefault */ /* * X Protocol packetizing macros. */ /* Leftover from CRAY support - was defined empty on all non-Cray systems */ #define WORD64ALIGN /** * Return a len-sized request buffer for the request type. This function may * flush the output queue. * * @param dpy The display connection * @param type The request type * @param len Length of the request in bytes * * @returns A pointer to the request buffer with a few default values * initialized. */ extern void *_XGetRequest(Display *dpy, CARD8 type, size_t len); /* GetReqSized is the same as GetReq but allows the caller to specify the * size in bytes. 'sz' must be a multiple of 4! */ #define GetReqSized(name, sz, req) \ req = (x##name##Req *) _XGetRequest(dpy, X_##name, sz) /* * GetReq - Get the next available X request packet in the buffer and * return it. * * "name" is the name of the request, e.g. CreatePixmap, OpenFont, etc. * "req" is the name of the request pointer. * */ #define GetReq(name, req) \ GetReqSized(name, SIZEOF(x##name##Req), req) /* GetReqExtra is the same as GetReq, but allocates "n" additional bytes after the request. "n" must be a multiple of 4! */ #define GetReqExtra(name, n, req) \ GetReqSized(name, SIZEOF(x##name##Req) + n, req) /* * GetResReq is for those requests that have a resource ID * (Window, Pixmap, GContext, etc.) as their single argument. * "rid" is the name of the resource. */ #define GetResReq(name, rid, req) \ req = (xResourceReq *) _XGetRequest(dpy, X_##name, SIZEOF(xResourceReq)); \ req->id = (rid) /* * GetEmptyReq is for those requests that have no arguments * at all. */ #define GetEmptyReq(name, req) \ req = (xReq *) _XGetRequest(dpy, X_##name, SIZEOF(xReq)) /* * MakeBigReq sets the CARD16 "req->length" to 0 and inserts a new CARD32 * length, after req->length, before the data in the request. The new length * includes the "n" extra 32-bit words. * * Do not use MakeBigReq if there is no data already in the request. * req->length must already be >= 2. */ #ifdef LONG64 #define MakeBigReq(req,n) \ { \ CARD64 _BRdat; \ CARD32 _BRlen = req->length - 1; \ req->length = 0; \ _BRdat = ((CARD32 *)req)[_BRlen]; \ memmove(((char *)req) + 8, ((char *)req) + 4, (_BRlen - 1) << 2); \ ((CARD32 *)req)[1] = _BRlen + n + 2; \ Data32(dpy, &_BRdat, 4); \ } #else #define MakeBigReq(req,n) \ { \ CARD32 _BRdat; \ CARD32 _BRlen = req->length - 1; \ req->length = 0; \ _BRdat = ((CARD32 *)req)[_BRlen]; \ memmove(((char *)req) + 8, ((char *)req) + 4, (_BRlen - 1) << 2); \ ((CARD32 *)req)[1] = _BRlen + n + 2; \ Data32(dpy, &_BRdat, 4); \ } #endif /* * SetReqLen increases the count of 32-bit words in the request by "n", * or by "badlen" if "n" is too large. * * Do not use SetReqLen if "req" does not already have data after the * xReq header. req->length must already be >= 2. */ #ifndef __clang_analyzer__ #define SetReqLen(req,n,badlen) \ if ((req->length + n) > (unsigned)65535) { \ if (dpy->bigreq_size) { \ MakeBigReq(req,n) \ } else { \ n = badlen; \ req->length += n; \ } \ } else \ req->length += n #else #define SetReqLen(req,n,badlen) \ req->length += n #endif #define SyncHandle() \ if (dpy->synchandler) (*dpy->synchandler)(dpy) extern void _XFlushGCCache(Display *dpy, GC gc); #define FlushGC(dpy, gc) \ if ((gc)->dirty) _XFlushGCCache((dpy), (gc)) /* * Data - Place data in the buffer and pad the end to provide * 32 bit word alignment. Transmit if the buffer fills. * * "dpy" is a pointer to a Display. * "data" is a pointer to a data buffer. * "len" is the length of the data buffer. */ #ifndef DataRoutineIsProcedure #define Data(dpy, data, len) {\ if (dpy->bufptr + (len) <= dpy->bufmax) {\ memcpy(dpy->bufptr, data, (int)len);\ dpy->bufptr += ((len) + 3) & ~3;\ } else\ _XSend(dpy, data, len);\ } #endif /* DataRoutineIsProcedure */ /* Allocate bytes from the buffer. No padding is done, so if * the length is not a multiple of 4, the caller must be * careful to leave the buffer aligned after sending the * current request. * * "type" is the type of the pointer being assigned to. * "ptr" is the pointer being assigned to. * "n" is the number of bytes to allocate. * * Example: * xTextElt *elt; * BufAlloc (xTextElt *, elt, nbytes) */ #define BufAlloc(type, ptr, n) \ if (dpy->bufptr + (n) > dpy->bufmax) \ _XFlush (dpy); \ ptr = (type) dpy->bufptr; \ memset(ptr, '\0', n); \ dpy->bufptr += (n); #define Data16(dpy, data, len) Data((dpy), (_Xconst char *)(data), (len)) #define _XRead16Pad(dpy, data, len) _XReadPad((dpy), (char *)(data), (len)) #define _XRead16(dpy, data, len) _XRead((dpy), (char *)(data), (len)) #ifdef LONG64 #define Data32(dpy, data, len) _XData32(dpy, (_Xconst long *)data, len) extern int _XData32( Display *dpy, register _Xconst long *data, unsigned len ); extern void _XRead32( Display *dpy, register long *data, long len ); #else #define Data32(dpy, data, len) Data((dpy), (_Xconst char *)(data), (len)) #define _XRead32(dpy, data, len) _XRead((dpy), (char *)(data), (len)) #endif #define PackData16(dpy,data,len) Data16 (dpy, data, len) #define PackData32(dpy,data,len) Data32 (dpy, data, len) /* Xlib manual is bogus */ #define PackData(dpy,data,len) PackData16 (dpy, data, len) #define min(a,b) (((a) < (b)) ? (a) : (b)) #define max(a,b) (((a) > (b)) ? (a) : (b)) #define CI_NONEXISTCHAR(cs) (((cs)->width == 0) && \ (((cs)->rbearing|(cs)->lbearing| \ (cs)->ascent|(cs)->descent) == 0)) /* * CI_GET_CHAR_INFO_1D - return the charinfo struct for the indicated 8bit * character. If the character is in the column and exists, then return the * appropriate metrics (note that fonts with common per-character metrics will * return min_bounds). If none of these hold true, try again with the default * char. */ #define CI_GET_CHAR_INFO_1D(fs,col,def,cs) \ { \ cs = def; \ if (col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \ if (fs->per_char == NULL) { \ cs = &fs->min_bounds; \ } else { \ cs = &fs->per_char[(col - fs->min_char_or_byte2)]; \ if (CI_NONEXISTCHAR(cs)) cs = def; \ } \ } \ } #define CI_GET_DEFAULT_INFO_1D(fs,cs) \ CI_GET_CHAR_INFO_1D (fs, fs->default_char, NULL, cs) /* * CI_GET_CHAR_INFO_2D - return the charinfo struct for the indicated row and * column. This is used for fonts that have more than row zero. */ #define CI_GET_CHAR_INFO_2D(fs,row,col,def,cs) \ { \ cs = def; \ if (row >= fs->min_byte1 && row <= fs->max_byte1 && \ col >= fs->min_char_or_byte2 && col <= fs->max_char_or_byte2) { \ if (fs->per_char == NULL) { \ cs = &fs->min_bounds; \ } else { \ cs = &fs->per_char[((row - fs->min_byte1) * \ (fs->max_char_or_byte2 - \ fs->min_char_or_byte2 + 1)) + \ (col - fs->min_char_or_byte2)]; \ if (CI_NONEXISTCHAR(cs)) cs = def; \ } \ } \ } #define CI_GET_DEFAULT_INFO_2D(fs,cs) \ { \ unsigned int r = (fs->default_char >> 8); \ unsigned int c = (fs->default_char & 0xff); \ CI_GET_CHAR_INFO_2D (fs, r, c, NULL, cs); \ } /* srcvar must be a variable for large architecture version */ #define OneDataCard32(dpy,dstaddr,srcvar) \ { *(CARD32 *)(dstaddr) = (srcvar); } typedef struct _XInternalAsync { struct _XInternalAsync *next; /* * handler arguments: * rep is the generic reply that caused this handler * to be invoked. It must also be passed to _XGetAsyncReply. * buf and len are opaque values that must be passed to * _XGetAsyncReply or _XGetAsyncData. * data is the closure stored in this struct. * The handler returns True iff it handled this reply. */ Bool (*handler)( Display* /* dpy */, xReply* /* rep */, char* /* buf */, int /* len */, XPointer /* data */ ); XPointer data; } _XAsyncHandler; /* * This struct is part of the ABI and is defined by value * in user-code. This means that we cannot make * the sequence-numbers 64bit. */ typedef struct _XAsyncEState { unsigned long min_sequence_number; unsigned long max_sequence_number; unsigned char error_code; unsigned char major_opcode; unsigned short minor_opcode; unsigned char last_error_received; int error_count; } _XAsyncErrorState; extern void _XDeqAsyncHandler(Display *dpy, _XAsyncHandler *handler); #define DeqAsyncHandler(dpy,handler) { \ if (dpy->async_handlers == (handler)) \ dpy->async_handlers = (handler)->next; \ else \ _XDeqAsyncHandler(dpy, handler); \ } typedef void (*FreeFuncType) ( Display* /* display */ ); typedef int (*FreeModmapType) ( XModifierKeymap* /* modmap */ ); /* * This structure is private to the library. */ typedef struct _XFreeFuncs { FreeFuncType atoms; /* _XFreeAtomTable */ FreeModmapType modifiermap; /* XFreeModifiermap */ FreeFuncType key_bindings; /* _XFreeKeyBindings */ FreeFuncType context_db; /* _XFreeContextDB */ FreeFuncType defaultCCCs; /* _XcmsFreeDefaultCCCs */ FreeFuncType clientCmaps; /* _XcmsFreeClientCmaps */ FreeFuncType intensityMaps; /* _XcmsFreeIntensityMaps */ FreeFuncType im_filters; /* _XFreeIMFilters */ FreeFuncType xkb; /* _XkbFreeInfo */ } _XFreeFuncRec; /* types for InitExt.c */ typedef int (*CreateGCType) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ); typedef int (*CopyGCType)( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ); typedef int (*FlushGCType) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ); typedef int (*FreeGCType) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ); typedef int (*CreateFontType) ( Display* /* display */, XFontStruct* /* fs */, XExtCodes* /* codes */ ); typedef int (*FreeFontType) ( Display* /* display */, XFontStruct* /* fs */, XExtCodes* /* codes */ ); typedef int (*CloseDisplayType) ( Display* /* display */, XExtCodes* /* codes */ ); typedef int (*ErrorType) ( Display* /* display */, xError* /* err */, XExtCodes* /* codes */, int* /* ret_code */ ); typedef char* (*ErrorStringType) ( Display* /* display */, int /* code */, XExtCodes* /* codes */, char* /* buffer */, int /* nbytes */ ); typedef void (*PrintErrorType)( Display* /* display */, XErrorEvent* /* ev */, void* /* fp */ ); typedef void (*BeforeFlushType)( Display* /* display */, XExtCodes* /* codes */, _Xconst char* /* data */, long /* len */ ); /* * This structure is private to the library. */ typedef struct _XExten { /* private to extension mechanism */ struct _XExten *next; /* next in list */ XExtCodes codes; /* public information, all extension told */ CreateGCType create_GC; /* routine to call when GC created */ CopyGCType copy_GC; /* routine to call when GC copied */ FlushGCType flush_GC; /* routine to call when GC flushed */ FreeGCType free_GC; /* routine to call when GC freed */ CreateFontType create_Font; /* routine to call when Font created */ FreeFontType free_Font; /* routine to call when Font freed */ CloseDisplayType close_display; /* routine to call when connection closed */ ErrorType error; /* who to call when an error occurs */ ErrorStringType error_string; /* routine to supply error string */ char *name; /* name of this extension */ PrintErrorType error_values; /* routine to supply error values */ BeforeFlushType before_flush; /* routine to call when sending data */ struct _XExten *next_flush; /* next in list of those with flushes */ } _XExtension; /* Temporary definition until we can depend on an xproto release with it */ #ifdef _X_COLD # define _XLIB_COLD _X_COLD #elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 403) /* 4.3+ */ # define _XLIB_COLD __attribute__((__cold__)) #else # define _XLIB_COLD /* nothing */ #endif /* extension hooks */ #ifdef DataRoutineIsProcedure extern void Data(Display *dpy, char *data, long len); #endif extern int _XError( Display* /* dpy */, xError* /* rep */ ); extern int _XIOError( Display* /* dpy */ ) _X_NORETURN; extern int (*_XIOErrorFunction)( Display* /* dpy */ ); extern int (*_XErrorFunction)( Display* /* dpy */, XErrorEvent* /* error_event */ ); extern void _XEatData( Display* /* dpy */, unsigned long /* n */ ) _XLIB_COLD; extern void _XEatDataWords( Display* /* dpy */, unsigned long /* n */ ) _XLIB_COLD; #if defined(__SUNPRO_C) /* Studio compiler alternative to "cold" attribute */ # pragma rarely_called(_XEatData, _XEatDataWords) #endif extern char *_XAllocScratch( Display* /* dpy */, unsigned long /* nbytes */ ); extern char *_XAllocTemp( Display* /* dpy */, unsigned long /* nbytes */ ); extern void _XFreeTemp( Display* /* dpy */, char* /* buf */, unsigned long /* nbytes */ ); extern Visual *_XVIDtoVisual( Display* /* dpy */, VisualID /* id */ ); extern unsigned long _XSetLastRequestRead( Display* /* dpy */, xGenericReply* /* rep */ ); extern int _XGetHostname( char* /* buf */, int /* maxlen */ ); extern Screen *_XScreenOfWindow( Display* /* dpy */, Window /* w */ ); extern Bool _XAsyncErrorHandler( Display* /* dpy */, xReply* /* rep */, char* /* buf */, int /* len */, XPointer /* data */ ); extern char *_XGetAsyncReply( Display* /* dpy */, char* /* replbuf */, xReply* /* rep */, char* /* buf */, int /* len */, int /* extra */, Bool /* discard */ ); extern void _XGetAsyncData( Display* /* dpy */, char * /* data */, char * /* buf */, int /* len */, int /* skip */, int /* datalen */, int /* discardtotal */ ); extern void _XFlush( Display* /* dpy */ ); extern int _XEventsQueued( Display* /* dpy */, int /* mode */ ); extern void _XReadEvents( Display* /* dpy */ ); extern int _XRead( Display* /* dpy */, char* /* data */, long /* size */ ); extern void _XReadPad( Display* /* dpy */, char* /* data */, long /* size */ ); extern void _XSend( Display* /* dpy */, _Xconst char* /* data */, long /* size */ ); extern Status _XReply( Display* /* dpy */, xReply* /* rep */, int /* extra */, Bool /* discard */ ); extern void _XEnq( Display* /* dpy */, xEvent* /* event */ ); extern void _XDeq( Display* /* dpy */, _XQEvent* /* prev */, _XQEvent* /* qelt */ ); extern Bool _XUnknownWireEvent( Display* /* dpy */, XEvent* /* re */, xEvent* /* event */ ); extern Bool _XUnknownWireEventCookie( Display* /* dpy */, XGenericEventCookie* /* re */, xEvent* /* event */ ); extern Bool _XUnknownCopyEventCookie( Display* /* dpy */, XGenericEventCookie* /* in */, XGenericEventCookie* /* out */ ); extern Status _XUnknownNativeEvent( Display* /* dpy */, XEvent* /* re */, xEvent* /* event */ ); extern Bool _XWireToEvent(Display *dpy, XEvent *re, xEvent *event); extern Bool _XDefaultWireError(Display *display, XErrorEvent *he, xError *we); extern Bool _XPollfdCacheInit(Display *dpy); extern void _XPollfdCacheAdd(Display *dpy, int fd); extern void _XPollfdCacheDel(Display *dpy, int fd); extern XID _XAllocID(Display *dpy); extern void _XAllocIDs(Display *dpy, XID *ids, int count); extern int _XFreeExtData( XExtData* /* extension */ ); extern int (*XESetCreateGC( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, GC, XExtCodes* ); extern int (*XESetCopyGC( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, GC, XExtCodes* ); extern int (*XESetFlushGC( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, GC, XExtCodes* ); extern int (*XESetFreeGC( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, GC /* gc */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, GC, XExtCodes* ); extern int (*XESetCreateFont( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, XFontStruct* /* fs */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, XFontStruct*, XExtCodes* ); extern int (*XESetFreeFont( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, XFontStruct* /* fs */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, XFontStruct*, XExtCodes* ); extern int (*XESetCloseDisplay( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, XExtCodes* /* codes */ ) /* proc */ ))( Display*, XExtCodes* ); extern int (*XESetError( Display* /* display */, int /* extension */, int (*) ( Display* /* display */, xError* /* err */, XExtCodes* /* codes */, int* /* ret_code */ ) /* proc */ ))( Display*, xError*, XExtCodes*, int* ); extern char* (*XESetErrorString( Display* /* display */, int /* extension */, char* (*) ( Display* /* display */, int /* code */, XExtCodes* /* codes */, char* /* buffer */, int /* nbytes */ ) /* proc */ ))( Display*, int, XExtCodes*, char*, int ); extern void (*XESetPrintErrorValues ( Display* /* display */, int /* extension */, void (*)( Display* /* display */, XErrorEvent* /* ev */, void* /* fp */ ) /* proc */ ))( Display*, XErrorEvent*, void* ); extern Bool (*XESetWireToEvent( Display* /* display */, int /* event_number */, Bool (*) ( Display* /* display */, XEvent* /* re */, xEvent* /* event */ ) /* proc */ ))( Display*, XEvent*, xEvent* ); extern Bool (*XESetWireToEventCookie( Display* /* display */, int /* extension */, Bool (*) ( Display* /* display */, XGenericEventCookie* /* re */, xEvent* /* event */ ) /* proc */ ))( Display*, XGenericEventCookie*, xEvent* ); extern Bool (*XESetCopyEventCookie( Display* /* display */, int /* extension */, Bool (*) ( Display* /* display */, XGenericEventCookie* /* in */, XGenericEventCookie* /* out */ ) /* proc */ ))( Display*, XGenericEventCookie*, XGenericEventCookie* ); extern Status (*XESetEventToWire( Display* /* display */, int /* event_number */, Status (*) ( Display* /* display */, XEvent* /* re */, xEvent* /* event */ ) /* proc */ ))( Display*, XEvent*, xEvent* ); extern Bool (*XESetWireToError( Display* /* display */, int /* error_number */, Bool (*) ( Display* /* display */, XErrorEvent* /* he */, xError* /* we */ ) /* proc */ ))( Display*, XErrorEvent*, xError* ); extern void (*XESetBeforeFlush( Display* /* display */, int /* error_number */, void (*) ( Display* /* display */, XExtCodes* /* codes */, _Xconst char* /* data */, long /* len */ ) /* proc */ ))( Display*, XExtCodes*, _Xconst char*, long ); /* internal connections for IMs */ typedef void (*_XInternalConnectionProc)( Display* /* dpy */, int /* fd */, XPointer /* call_data */ ); extern Status _XRegisterInternalConnection( Display* /* dpy */, int /* fd */, _XInternalConnectionProc /* callback */, XPointer /* call_data */ ); extern void _XUnregisterInternalConnection( Display* /* dpy */, int /* fd */ ); extern void _XProcessInternalConnection( Display* /* dpy */, struct _XConnectionInfo* /* conn_info */ ); /* Display structure has pointers to these */ struct _XConnectionInfo { /* info from _XRegisterInternalConnection */ int fd; _XInternalConnectionProc read_callback; XPointer call_data; XPointer *watch_data; /* set/used by XConnectionWatchProc */ struct _XConnectionInfo *next; }; struct _XConnWatchInfo { /* info from XAddConnectionWatch */ XConnectionWatchProc fn; XPointer client_data; struct _XConnWatchInfo *next; }; #ifdef __UNIXOS2__ extern char* __XOS2RedirRoot( char* ); #endif extern int _XTextHeight( XFontStruct* /* font_struct */, _Xconst char* /* string */, int /* count */ ); extern int _XTextHeight16( XFontStruct* /* font_struct */, _Xconst XChar2b* /* string */, int /* count */ ); #if defined(WIN32) extern int _XOpenFile( _Xconst char* /* path */, int /* flags */ ); extern int _XOpenFileMode( _Xconst char* /* path */, int /* flags */, mode_t /* mode */ ); extern void* _XFopenFile( _Xconst char* /* path */, _Xconst char* /* mode */ ); extern int _XAccessFile( _Xconst char* /* path */ ); #else #define _XOpenFile(path,flags) open(path,flags) #define _XOpenFileMode(path,flags,mode) open(path,flags,mode) #define _XFopenFile(path,mode) fopen(path,mode) #endif /* EvToWire.c */ extern Status _XEventToWire(Display *dpy, XEvent *re, xEvent *event); extern int _XF86LoadQueryLocaleFont( Display* /* dpy */, _Xconst char* /* name*/, XFontStruct** /* xfp*/, Font* /* fidp */ ); extern void _XProcessWindowAttributes ( register Display *dpy, xChangeWindowAttributesReq *req, register unsigned long valuemask, register XSetWindowAttributes *attributes); extern int _XDefaultError( Display *dpy, XErrorEvent *event); extern int _XDefaultIOError( Display *dpy); extern void _XSetClipRectangles ( register Display *dpy, GC gc, int clip_x_origin, int clip_y_origin, XRectangle *rectangles, int n, int ordering); Status _XGetWindowAttributes( register Display *dpy, Window w, XWindowAttributes *attr); int _XPutBackEvent ( register Display *dpy, register XEvent *event); extern Bool _XIsEventCookie( Display *dpy, XEvent *ev); extern void _XFreeEventCookies( Display *dpy); extern void _XStoreEventCookie( Display *dpy, XEvent *ev); extern Bool _XFetchEventCookie( Display *dpy, XGenericEventCookie *ev); extern Bool _XCopyEventCookie( Display *dpy, XGenericEventCookie *in, XGenericEventCookie *out); /* lcFile.c */ extern void xlocaledir( char *buf, int buf_len ); #ifdef __clang__ #pragma clang diagnostic pop #endif _XFUNCPROTOEND #endif /* _X11_XLIBINT_H_ */ X11/Xarch.h000064400000005607151027430560006346 0ustar00#ifndef _XARCH_H_ # define _XARCH_H_ /* * Copyright 1997 Metro Link Incorporated * * All Rights Reserved * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the names of the above listed copyright holder(s) * not be used in advertising or publicity pertaining to distribution of * the software without specific, written prior permission. The above listed * copyright holder(s) make(s) no representations about the suitability of * this software for any purpose. It is provided "as is" without express or * implied warranty. * * THE ABOVE LISTED COPYRIGHT HOLDER(S) DISCLAIM(S) ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE * LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Determine the machine's byte order. */ /* See if it is set in the imake config first */ # ifdef X_BYTE_ORDER # define X_BIG_ENDIAN 4321 # define X_LITTLE_ENDIAN 1234 # else # if defined(SVR4) || defined(__SVR4) # include # include # elif defined(CSRG_BASED) # if defined(__NetBSD__) || defined(__OpenBSD__) # include # endif # include # elif defined(linux) # if defined __STRICT_ANSI__ # undef __STRICT_ANSI__ # include # define __STRICT_ANSI__ # else # include # endif /* 'endian.h' might have been included before 'Xarch.h' */ # if !defined(LITTLE_ENDIAN) && defined(__LITTLE_ENDIAN) # define LITTLE_ENDIAN __LITTLE_ENDIAN # endif # if !defined(BIG_ENDIAN) && defined(__BIG_ENDIAN) # define BIG_ENDIAN __BIG_ENDIAN # endif # if !defined(PDP_ENDIAN) && defined(__PDP_ENDIAN) # define PDP_ENDIAN __PDP_ENDIAN # endif # if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) # define BYTE_ORDER __BYTE_ORDER # endif # endif # ifndef BYTE_ORDER # define LITTLE_ENDIAN 1234 # define BIG_ENDIAN 4321 # if defined(__sun) && defined(__SVR4) # include # ifdef _LITTLE_ENDIAN # define BYTE_ORDER LITTLE_ENDIAN # endif # ifdef _BIG_ENDIAN # define BYTE_ORDER BIG_ENDIAN # endif # endif /* sun */ # endif /* BYTE_ORDER */ # define X_BYTE_ORDER BYTE_ORDER # define X_BIG_ENDIAN BIG_ENDIAN # define X_LITTLE_ENDIAN LITTLE_ENDIAN # endif /* not in imake config */ #endif /* _XARCH_H_ */ expat_external.h000064400000012634151027430560007751 0ustar00/* __ __ _ ___\ \/ /_ __ __ _| |_ / _ \\ /| '_ \ / _` | __| | __// \| |_) | (_| | |_ \___/_/\_\ .__/ \__,_|\__| |_| XML parser Copyright (c) 1997-2000 Thai Open Source Software Center Ltd Copyright (c) 2000-2017 Expat development team Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef Expat_External_INCLUDED #define Expat_External_INCLUDED 1 /* External API definitions */ #if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) # define XML_USE_MSC_EXTENSIONS 1 #endif /* Expat tries very hard to make the API boundary very specifically defined. There are two macros defined to control this boundary; each of these can be defined before including this header to achieve some different behavior, but doing so it not recommended or tested frequently. XMLCALL - The calling convention to use for all calls across the "library boundary." This will default to cdecl, and try really hard to tell the compiler that's what we want. XMLIMPORT - Whatever magic is needed to note that a function is to be imported from a dynamically loaded library (.dll, .so, or .sl, depending on your platform). The XMLCALL macro was added in Expat 1.95.7. The only one which is expected to be directly useful in client code is XMLCALL. Note that on at least some Unix versions, the Expat library must be compiled with the cdecl calling convention as the default since system headers may assume the cdecl convention. */ #ifndef XMLCALL # if defined(_MSC_VER) # define XMLCALL __cdecl # elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) # define XMLCALL __attribute__((cdecl)) # else /* For any platform which uses this definition and supports more than one calling convention, we need to extend this definition to declare the convention used on that platform, if it's possible to do so. If this is the case for your platform, please file a bug report with information on how to identify your platform via the C pre-processor and how to specify the same calling convention as the platform's malloc() implementation. */ # define XMLCALL # endif #endif /* not defined XMLCALL */ #if !defined(XML_STATIC) && !defined(XMLIMPORT) # ifndef XML_BUILDING_EXPAT /* using Expat from an application */ # ifdef XML_USE_MSC_EXTENSIONS # define XMLIMPORT __declspec(dllimport) # endif # endif #endif /* not defined XML_STATIC */ #if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4) # define XMLIMPORT __attribute__ ((visibility ("default"))) #endif /* If we didn't define it above, define it away: */ #ifndef XMLIMPORT # define XMLIMPORT #endif #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) # define XML_ATTR_MALLOC __attribute__((__malloc__)) #else # define XML_ATTR_MALLOC #endif #if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) # define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) #else # define XML_ATTR_ALLOC_SIZE(x) #endif #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL #ifdef __cplusplus extern "C" { #endif #ifdef XML_UNICODE_WCHAR_T # ifndef XML_UNICODE # define XML_UNICODE # endif # if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2) # error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc" # endif #endif #ifdef XML_UNICODE /* Information is UTF-16 encoded. */ # ifdef XML_UNICODE_WCHAR_T typedef wchar_t XML_Char; typedef wchar_t XML_LChar; # else typedef unsigned short XML_Char; typedef char XML_LChar; # endif /* XML_UNICODE_WCHAR_T */ #else /* Information is UTF-8 encoded. */ typedef char XML_Char; typedef char XML_LChar; #endif /* XML_UNICODE */ #ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */ # if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 typedef __int64 XML_Index; typedef unsigned __int64 XML_Size; # else typedef long long XML_Index; typedef unsigned long long XML_Size; # endif #else typedef long XML_Index; typedef unsigned long XML_Size; #endif /* XML_LARGE_SIZE */ #ifdef __cplusplus } #endif #endif /* not Expat_External_INCLUDED */ krb5/localauth_plugin.h000064400000013371151027430560011122 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2013 by the Massachusetts Institute of Technology. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for localauth plugin module implementors. * * The localauth pluggable interface currently has only one supported major * version, which is 1. Major version 1 has a current minor version number of * 1. * * Localauth plugin modules should define a function named * localauth__initvt, matching the signature: * * krb5_error_code * localauth_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_localauth_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_LOCALAUTH_PLUGIN_H #define KRB5_LOCALAUTH_PLUGIN_H #include #include /* An abstract type for localauth module data. */ typedef struct krb5_localauth_moddata_st *krb5_localauth_moddata; /*** Method type declarations ***/ /* Optional: Initialize module data. */ typedef krb5_error_code (*krb5_localauth_init_fn)(krb5_context context, krb5_localauth_moddata *data); /* Optional: Release resources used by module data. */ typedef void (*krb5_localauth_fini_fn)(krb5_context context, krb5_localauth_moddata data); /* * Optional: Determine whether aname is authorized to log in as the local * account lname. Return 0 if aname is authorized, EPERM if aname is * authoritatively not authorized, KRB5_PLUGIN_NO_HANDLE if the module cannot * determine whether aname is authorized, and any other error code for a * serious failure to process the request. aname will be considered authorized * if at least one module returns 0 and all other modules return * KRB5_PLUGIN_NO_HANDLE. */ typedef krb5_error_code (*krb5_localauth_userok_fn)(krb5_context context, krb5_localauth_moddata data, krb5_const_principal aname, const char *lname); /* * Optional (mandatory if an2ln_types is set): Determine the local account name * corresponding to aname. Return 0 and set *lname_out if a mapping can be * determined; the contents of *lname_out will later be released with a call to * the module's free_string method. Return KRB5_LNAME_NOTRANS if no mapping * can be determined. Return any other error code for a serious failure to * process the request; this will halt the krb5_aname_to_localname operation. * * If the module's an2ln_types field is set, this method will only be invoked * when a profile "auth_to_local" value references one of the module's types. * type and residual will be set to the type and residual of the auth_to_local * value. * * If the module's an2ln_types field is not set but the an2ln method is * implemented, this method will be invoked independently of the profile's * auth_to_local settings, with type and residual set to NULL. If multiple * modules are registered with an2ln methods but no an2ln_types field, the * order of invocation is not defined, but all such modules will be consulted * before the built-in mechanisms are tried. */ typedef krb5_error_code (*krb5_localauth_an2ln_fn)(krb5_context context, krb5_localauth_moddata data, const char *type, const char *residual, krb5_const_principal aname, char **lname_out); /* * Optional (mandatory if an2ln is implemented): Release the memory returned by * an invocation of an2ln. */ typedef void (*krb5_localauth_free_string_fn)(krb5_context context, krb5_localauth_moddata data, char *str); /* localauth vtable for major version 1. */ typedef struct krb5_localauth_vtable_st { const char *name; /* Mandatory: name of module. */ const char **an2ln_types; /* Optional: uppercase auth_to_local types */ krb5_localauth_init_fn init; krb5_localauth_fini_fn fini; krb5_localauth_userok_fn userok; krb5_localauth_an2ln_fn an2ln; krb5_localauth_free_string_fn free_string; /* Minor version 1 ends here. */ } *krb5_localauth_vtable; #endif /* KRB5_LOCALAUTH_PLUGIN_H */ krb5/clpreauth_plugin.h000064400000036243151027430560011140 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (c) 2006 Red Hat, Inc. * Portions copyright (c) 2006, 2011 Massachusetts Institute of Technology * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Red Hat, Inc., nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for clpreauth plugin module implementors. * * The clpreauth interface has a single supported major version, which is * 1. Major version 1 has a current minor version of 2. clpreauth modules * should define a function named clpreauth__initvt, matching * the signature: * * krb5_error_code * clpreauth_modname_initvt(krb5_context context, int maj_ver, * int min_ver, krb5_plugin_vtable vtable); * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for the interface and maj_ver: * maj_ver == 1: Cast to krb5_clpreauth_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_CLPREAUTH_PLUGIN_H #define KRB5_CLPREAUTH_PLUGIN_H #include #include /* clpreauth mechanism property flags */ /* Provides a real answer which we can send back to the KDC. The client * assumes that one real answer will be enough. */ #define PA_REAL 0x00000001 /* Doesn't provide a real answer, but must be given a chance to run before any * REAL mechanism callbacks. */ #define PA_INFO 0x00000002 /* Abstract type for a client request information handle. */ typedef struct krb5_clpreauth_rock_st *krb5_clpreauth_rock; /* Abstract types for module data and per-request module data. */ typedef struct krb5_clpreauth_moddata_st *krb5_clpreauth_moddata; typedef struct krb5_clpreauth_modreq_st *krb5_clpreauth_modreq; /* Before using a callback after version 1, modules must check the vers * field of the callback structure. */ typedef struct krb5_clpreauth_callbacks_st { int vers; /* * If an AS-REP has been received, return the enctype of the AS-REP * encrypted part. Otherwise return the enctype chosen from etype-info, or * the first requested enctype if no etype-info was received. */ krb5_enctype (*get_etype)(krb5_context context, krb5_clpreauth_rock rock); /* Get a pointer to the FAST armor key, or NULL if the client is not using * FAST. The returned pointer is an alias and should not be freed. */ krb5_keyblock *(*fast_armor)(krb5_context context, krb5_clpreauth_rock rock); /* * Get a pointer to the client-supplied reply key, possibly invoking the * prompter to ask for a password if this has not already been done. The * returned pointer is an alias and should not be freed. */ krb5_error_code (*get_as_key)(krb5_context context, krb5_clpreauth_rock rock, krb5_keyblock **keyblock); /* Replace the reply key to be used to decrypt the AS response. */ krb5_error_code (*set_as_key)(krb5_context context, krb5_clpreauth_rock rock, const krb5_keyblock *keyblock); /* End of version 1 clpreauth callbacks. */ /* * Get the current time for use in a preauth response. If * allow_unauth_time is true and the library has been configured to allow * it, the current time will be offset using unauthenticated timestamp * information received from the KDC in the preauth-required error, if one * has been received. Otherwise, the timestamp in a preauth-required error * will only be used if it is protected by a FAST channel. Only set * allow_unauth_time if using an unauthenticated time offset would not * create a security issue. */ krb5_error_code (*get_preauth_time)(krb5_context context, krb5_clpreauth_rock rock, krb5_boolean allow_unauth_time, krb5_timestamp *time_out, krb5_int32 *usec_out); /* Set a question to be answered by the responder and optionally provide * a challenge. */ krb5_error_code (*ask_responder_question)(krb5_context context, krb5_clpreauth_rock rock, const char *question, const char *challenge); /* Get an answer from the responder, or NULL if the question was * unanswered. */ const char *(*get_responder_answer)(krb5_context context, krb5_clpreauth_rock rock, const char *question); /* Indicate interest in the AS key through the responder interface. */ void (*need_as_key)(krb5_context context, krb5_clpreauth_rock rock); /* * Get a configuration/state item from an input ccache, which may allow it * to retrace the steps it took last time. The returned data string is an * alias and should not be freed. */ const char *(*get_cc_config)(krb5_context context, krb5_clpreauth_rock rock, const char *key); /* * Set a configuration/state item which will be recorded to an output * ccache, if the calling application supplied one. Both key and data * should be valid UTF-8 text. */ krb5_error_code (*set_cc_config)(krb5_context context, krb5_clpreauth_rock rock, const char *key, const char *data); /* End of version 2 clpreauth callbacks (added in 1.11). */ /* * Prevent further fallbacks to other preauth mechanisms if the KDC replies * with an error. (The module itself can still respond to errors with its * tryagain method, or continue after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED * errors with its process method.) A module should invoke this callback * from the process method when it generates an authenticated request using * credentials; often this will be the first or only client message * generated by the mechanism. */ void (*disable_fallback)(krb5_context context, krb5_clpreauth_rock rock); /* End of version 3 clpreauth callbacks (added in 1.17). */ } *krb5_clpreauth_callbacks; /* * Optional: per-plugin initialization/cleanup. The init function is called by * libkrb5 when the plugin is loaded, and the fini function is called before * the plugin is unloaded. These may be called multiple times in case the * plugin is used in multiple contexts. The returned context lives the * lifetime of the krb5_context. */ typedef krb5_error_code (*krb5_clpreauth_init_fn)(krb5_context context, krb5_clpreauth_moddata *moddata_out); typedef void (*krb5_clpreauth_fini_fn)(krb5_context context, krb5_clpreauth_moddata moddata); /* * Optional (mandatory before MIT krb5 1.12): pa_type will be a member of the * vtable's pa_type_list. Return PA_REAL if pa_type is a real * preauthentication type or PA_INFO if it is an informational type. If this * function is not defined in 1.12 or later, all pa_type values advertised by * the module will be assumed to be real. */ typedef int (*krb5_clpreauth_get_flags_fn)(krb5_context context, krb5_preauthtype pa_type); /* * Optional: per-request initialization/cleanup. The request_init function is * called when beginning to process a get_init_creds request and the * request_fini function is called when processing of the request is complete. * This is optional. It may be called multiple times in the lifetime of a * krb5_context. */ typedef void (*krb5_clpreauth_request_init_fn)(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq *modreq_out); typedef void (*krb5_clpreauth_request_fini_fn)(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq); /* * Optional: process server-supplied data in pa_data and set responder * questions. * * encoded_previous_request may be NULL if there has been no previous request * in the AS exchange. */ typedef krb5_error_code (*krb5_clpreauth_prep_questions_fn)(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_pa_data *pa_data); /* * Mandatory: process server-supplied data in pa_data and return created data * in pa_data_out. Also called after the AS-REP is received if the AS-REP * includes preauthentication data of the associated type. * * as_key contains the client-supplied key if known, or an empty keyblock if * not. If it is empty, the module may use gak_fct to fill it in. * * encoded_previous_request may be NULL if there has been no previous request * in the AS exchange. */ typedef krb5_error_code (*krb5_clpreauth_process_fn)(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_pa_data *pa_data, krb5_prompter_fct prompter, void *prompter_data, krb5_pa_data ***pa_data_out); /* * Optional: Attempt to use error and error_padata to try to recover from the * given error. To work with both FAST and non-FAST errors, an implementation * should generally consult error_padata rather than decoding error->e_data. * For non-FAST errors, it contains the e_data decoded as either pa-data or * typed-data. * * If this function is provided, and it returns 0 and stores data in * pa_data_out, then the client library will retransmit the request. */ typedef krb5_error_code (*krb5_clpreauth_tryagain_fn)(krb5_context context, krb5_clpreauth_moddata moddata, krb5_clpreauth_modreq modreq, krb5_get_init_creds_opt *opt, krb5_clpreauth_callbacks cb, krb5_clpreauth_rock rock, krb5_kdc_req *request, krb5_data *encoded_request_body, krb5_data *encoded_previous_request, krb5_preauthtype pa_type, krb5_error *error, krb5_pa_data **error_padata, krb5_prompter_fct prompter, void *prompter_data, krb5_pa_data ***pa_data_out); /* * Optional: receive krb5_get_init_creds_opt information. The attr and value * information supplied should be copied into moddata by the module if it * wishes to reference it after returning from this call. */ typedef krb5_error_code (*krb5_clpreauth_supply_gic_opts_fn)(krb5_context context, krb5_clpreauth_moddata moddata, krb5_get_init_creds_opt *opt, const char *attr, const char *value); typedef struct krb5_clpreauth_vtable_st { /* Mandatory: name of module. */ char *name; /* Mandatory: pointer to zero-terminated list of pa_types which this module * can provide services for. */ krb5_preauthtype *pa_type_list; /* Optional: pointer to zero-terminated list of enc_types which this module * claims to add support for. */ krb5_enctype *enctype_list; krb5_clpreauth_init_fn init; krb5_clpreauth_fini_fn fini; krb5_clpreauth_get_flags_fn flags; krb5_clpreauth_request_init_fn request_init; krb5_clpreauth_request_fini_fn request_fini; krb5_clpreauth_process_fn process; krb5_clpreauth_tryagain_fn tryagain; krb5_clpreauth_supply_gic_opts_fn gic_opts; /* Minor version 1 ends here. */ krb5_clpreauth_prep_questions_fn prep_questions; /* Minor version 2 ends here. */ } *krb5_clpreauth_vtable; /* * This function allows a clpreauth plugin to obtain preauth options. The * preauth_data returned from this function should be freed by calling * krb5_get_init_creds_opt_free_pa(). */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_get_pa(krb5_context context, krb5_get_init_creds_opt *opt, int *num_preauth_data, krb5_gic_opt_pa_data **preauth_data); /* * This function frees the preauth_data that was returned by * krb5_get_init_creds_opt_get_pa(). */ void KRB5_CALLCONV krb5_get_init_creds_opt_free_pa(krb5_context context, int num_preauth_data, krb5_gic_opt_pa_data *preauth_data); #endif /* KRB5_CLPREAUTH_PLUGIN_H */ krb5/krb5.h000064400001256744151027430560006451 0ustar00/* This file is generated, please don't edit it directly. */ #ifndef KRB5_KRB5_H_INCLUDED #define KRB5_KRB5_H_INCLUDED /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* General definitions for Kerberos version 5. */ /* * Copyright 1989, 1990, 1995, 2001, 2003, 2007, 2011 by the Massachusetts * Institute of Technology. All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Copyright (C) 1998 by the FundsXpress, INC. * * All rights reserved. * * Export of this software from the United States of America may require * a specific license from the United States Government. It is the * responsibility of any person or organization contemplating export to * obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of FundsXpress. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. FundsXpress makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef KRB5_GENERAL__ #define KRB5_GENERAL__ /** @defgroup KRB5_H krb5 library API * @{ */ /* By default, do not expose deprecated interfaces. */ #ifndef KRB5_DEPRECATED #define KRB5_DEPRECATED 0 #endif #if defined(__MACH__) && defined(__APPLE__) # include # if TARGET_RT_MAC_CFM # error "Use KfM 4.0 SDK headers for CFM compilation." # endif #endif #if defined(_MSDOS) || defined(_WIN32) #include #endif #ifndef KRB5_CONFIG__ #ifndef KRB5_CALLCONV #define KRB5_CALLCONV #define KRB5_CALLCONV_C #endif /* !KRB5_CALLCONV */ #endif /* !KRB5_CONFIG__ */ #ifndef KRB5_CALLCONV_WRONG #define KRB5_CALLCONV_WRONG #endif #ifndef THREEPARAMOPEN #define THREEPARAMOPEN(x,y,z) open(x,y,z) #endif #if KRB5_PRIVATE #ifndef WRITABLEFOPEN #define WRITABLEFOPEN(x,y) fopen(x,y) #endif #endif #define KRB5_OLD_CRYPTO #include #include /* for *_MAX */ #include #include #ifndef KRB5INT_BEGIN_DECLS #if defined(__cplusplus) #define KRB5INT_BEGIN_DECLS extern "C" { #define KRB5INT_END_DECLS } #else #define KRB5INT_BEGIN_DECLS #define KRB5INT_END_DECLS #endif #endif KRB5INT_BEGIN_DECLS #if defined(TARGET_OS_MAC) && TARGET_OS_MAC # pragma pack(push,2) #endif #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) >= 30203 # define KRB5_ATTR_DEPRECATED __attribute__((deprecated)) #elif defined _WIN32 # define KRB5_ATTR_DEPRECATED __declspec(deprecated) #else # define KRB5_ATTR_DEPRECATED #endif /* from profile.h */ struct _profile_t; /* typedef struct _profile_t *profile_t; */ /* * begin wordsize.h */ /* * Word-size related definition. */ typedef uint8_t krb5_octet; typedef int16_t krb5_int16; typedef uint16_t krb5_ui_2; typedef int32_t krb5_int32; typedef uint32_t krb5_ui_4; #define VALID_INT_BITS INT_MAX #define VALID_UINT_BITS UINT_MAX #define KRB5_INT32_MAX 2147483647 /* this strange form is necessary since - is a unary operator, not a sign indicator */ #define KRB5_INT32_MIN (-KRB5_INT32_MAX-1) #define KRB5_INT16_MAX 65535 /* this strange form is necessary since - is a unary operator, not a sign indicator */ #define KRB5_INT16_MIN (-KRB5_INT16_MAX-1) /* * end wordsize.h */ /* * begin "base-defs.h" */ /* * Basic definitions for Kerberos V5 library */ #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif typedef unsigned int krb5_boolean; typedef unsigned int krb5_msgtype; typedef unsigned int krb5_kvno; typedef krb5_int32 krb5_addrtype; typedef krb5_int32 krb5_enctype; typedef krb5_int32 krb5_cksumtype; typedef krb5_int32 krb5_authdatatype; typedef krb5_int32 krb5_keyusage; typedef krb5_int32 krb5_cryptotype; typedef krb5_int32 krb5_preauthtype; /* This may change, later on */ typedef krb5_int32 krb5_flags; /** * Represents a timestamp in seconds since the POSIX epoch. This legacy type * is used frequently in the ABI, but cannot represent timestamps after 2038 as * a positive number. Code which uses this type should cast values of it to * uint32_t so that negative values are treated as timestamps between 2038 and * 2106 on platforms with 64-bit time_t. */ typedef krb5_int32 krb5_timestamp; typedef krb5_int32 krb5_deltat; /** * Used to convey an operation status. The value 0 indicates success; any * other values are com_err codes. Use krb5_get_error_message() to obtain a * string describing the error. */ typedef krb5_int32 krb5_error_code; typedef krb5_error_code krb5_magic; typedef struct _krb5_data { krb5_magic magic; unsigned int length; char *data; } krb5_data; /* Originally introduced for PKINIT; now unused. Do not use this. */ typedef struct _krb5_octet_data { krb5_magic magic; unsigned int length; krb5_octet *data; } krb5_octet_data; /* Originally used to recognize AFS and default salts. No longer used. */ #define SALT_TYPE_AFS_LENGTH UINT_MAX #define SALT_TYPE_NO_LENGTH UINT_MAX typedef void * krb5_pointer; typedef void const * krb5_const_pointer; typedef struct krb5_principal_data { krb5_magic magic; krb5_data realm; krb5_data *data; /**< An array of strings */ krb5_int32 length; krb5_int32 type; } krb5_principal_data; typedef krb5_principal_data * krb5_principal; /* * Per V5 spec on definition of principal types */ #define KRB5_NT_UNKNOWN 0 /**< Name type not known */ #define KRB5_NT_PRINCIPAL 1 /**< Just the name of the principal as in DCE, or for users */ #define KRB5_NT_SRV_INST 2 /**< Service and other unique instance (krbtgt) */ #define KRB5_NT_SRV_HST 3 /**< Service with host name as instance (telnet, rcommands) */ #define KRB5_NT_SRV_XHST 4 /**< Service with host as remaining components */ #define KRB5_NT_UID 5 /**< Unique ID */ #define KRB5_NT_X500_PRINCIPAL 6 /**< PKINIT */ #define KRB5_NT_SMTP_NAME 7 /**< Name in form of SMTP email name */ #define KRB5_NT_ENTERPRISE_PRINCIPAL 10 /**< Windows 2000 UPN */ #define KRB5_NT_WELLKNOWN 11 /**< Well-known (special) principal */ #define KRB5_WELLKNOWN_NAMESTR "WELLKNOWN" /**< First component of NT_WELLKNOWN principals */ #define KRB5_NT_MS_PRINCIPAL -128 /**< Windows 2000 UPN and SID */ #define KRB5_NT_MS_PRINCIPAL_AND_ID -129 /**< NT 4 style name */ #define KRB5_NT_ENT_PRINCIPAL_AND_ID -130 /**< NT 4 style name and SID */ /** Constant version of krb5_principal_data */ typedef const krb5_principal_data *krb5_const_principal; #define krb5_princ_realm(context, princ) (&(princ)->realm) #define krb5_princ_set_realm(context, princ,value) ((princ)->realm = *(value)) #define krb5_princ_set_realm_length(context, princ,value) (princ)->realm.length = (value) #define krb5_princ_set_realm_data(context, princ,value) (princ)->realm.data = (value) #define krb5_princ_size(context, princ) (princ)->length #define krb5_princ_type(context, princ) (princ)->type #define krb5_princ_name(context, princ) (princ)->data #define krb5_princ_component(context, princ,i) \ (((i) < krb5_princ_size(context, princ)) \ ? (princ)->data + (i) \ : NULL) /** Constant for realm referrals. */ #define KRB5_REFERRAL_REALM "" /* * Referral-specific functions. */ /** * Check for a match with KRB5_REFERRAL_REALM. * * @param [in] r Realm to check * * @return @c TRUE if @a r is zero-length, @c FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_is_referral_realm(const krb5_data *r); /** * Return an anonymous realm data. * * This function returns constant storage that must not be freed. * * @sa #KRB5_ANONYMOUS_REALMSTR */ const krb5_data *KRB5_CALLCONV krb5_anonymous_realm(void); /** * Build an anonymous principal. * * This function returns constant storage that must not be freed. * * @sa #KRB5_ANONYMOUS_PRINCSTR */ krb5_const_principal KRB5_CALLCONV krb5_anonymous_principal(void); #define KRB5_ANONYMOUS_REALMSTR "WELLKNOWN:ANONYMOUS" /**< Anonymous realm */ #define KRB5_ANONYMOUS_PRINCSTR "ANONYMOUS" /**< Anonymous principal name */ /* * end "base-defs.h" */ /* * begin "hostaddr.h" */ /** Structure for address */ typedef struct _krb5_address { krb5_magic magic; krb5_addrtype addrtype; unsigned int length; krb5_octet *contents; } krb5_address; /* per Kerberos v5 protocol spec */ #define ADDRTYPE_INET 0x0002 #define ADDRTYPE_CHAOS 0x0005 #define ADDRTYPE_XNS 0x0006 #define ADDRTYPE_ISO 0x0007 #define ADDRTYPE_DDP 0x0010 #define ADDRTYPE_NETBIOS 0x0014 #define ADDRTYPE_INET6 0x0018 /* not yet in the spec... */ #define ADDRTYPE_ADDRPORT 0x0100 #define ADDRTYPE_IPPORT 0x0101 /* macros to determine if a type is a local type */ #define ADDRTYPE_IS_LOCAL(addrtype) (addrtype & 0x8000) /* * end "hostaddr.h" */ struct _krb5_context; typedef struct _krb5_context * krb5_context; struct _krb5_auth_context; typedef struct _krb5_auth_context * krb5_auth_context; struct _krb5_cryptosystem_entry; /* * begin "encryption.h" */ /** Exposed contents of a key. */ typedef struct _krb5_keyblock { krb5_magic magic; krb5_enctype enctype; unsigned int length; krb5_octet *contents; } krb5_keyblock; struct krb5_key_st; /** * Opaque identifier for a key. * * Use with the krb5_k APIs for better performance for repeated operations with * the same key and usage. Key identifiers must not be used simultaneously * within multiple threads, as they may contain mutable internal state and are * not mutex-protected. */ typedef struct krb5_key_st *krb5_key; #ifdef KRB5_OLD_CRYPTO typedef struct _krb5_encrypt_block { krb5_magic magic; krb5_enctype crypto_entry; /* to call krb5_encrypt_size, you need this. it was a pointer, but it doesn't have to be. gross. */ krb5_keyblock *key; } krb5_encrypt_block; #endif typedef struct _krb5_checksum { krb5_magic magic; krb5_cksumtype checksum_type; /* checksum type */ unsigned int length; krb5_octet *contents; } krb5_checksum; typedef struct _krb5_enc_data { krb5_magic magic; krb5_enctype enctype; krb5_kvno kvno; krb5_data ciphertext; } krb5_enc_data; /** * Structure to describe a region of text to be encrypted or decrypted. * * The @a flags member describes the type of the iov. * The @a data member points to the memory that will be manipulated. * All iov APIs take a pointer to the first element of an array of krb5_crypto_iov's * along with the size of that array. Buffer contents are manipulated in-place; * data is overwritten. Callers must allocate the right number of krb5_crypto_iov * structures before calling into an iov API. */ typedef struct _krb5_crypto_iov { krb5_cryptotype flags; /**< @ref KRB5_CRYPTO_TYPE type of the iov */ krb5_data data; } krb5_crypto_iov; /* per Kerberos v5 protocol spec */ #define ENCTYPE_NULL 0x0000 #define ENCTYPE_DES_CBC_CRC 0x0001 /**< @deprecated no longer supported */ #define ENCTYPE_DES_CBC_MD4 0x0002 /**< @deprecated no longer supported */ #define ENCTYPE_DES_CBC_MD5 0x0003 /**< @deprecated no longer supported */ #define ENCTYPE_DES_CBC_RAW 0x0004 /**< @deprecated no longer supported */ #define ENCTYPE_DES3_CBC_SHA 0x0005 /**< @deprecated no longer supported */ #define ENCTYPE_DES3_CBC_RAW 0x0006 /**< @deprecated no longer supported */ #define ENCTYPE_DES_HMAC_SHA1 0x0008 /**< @deprecated no longer supported */ /* PKINIT */ #define ENCTYPE_DSA_SHA1_CMS 0x0009 /**< DSA with SHA1, CMS signature */ #define ENCTYPE_MD5_RSA_CMS 0x000a /**< MD5 with RSA, CMS signature */ #define ENCTYPE_SHA1_RSA_CMS 0x000b /**< SHA1 with RSA, CMS signature */ #define ENCTYPE_RC2_CBC_ENV 0x000c /**< RC2 cbc mode, CMS enveloped data */ #define ENCTYPE_RSA_ENV 0x000d /**< RSA encryption, CMS enveloped data */ #define ENCTYPE_RSA_ES_OAEP_ENV 0x000e /**< RSA w/OEAP encryption, CMS enveloped data */ #define ENCTYPE_DES3_CBC_ENV 0x000f /**< @deprecated no longer supported */ #define ENCTYPE_DES3_CBC_SHA1 0x0010 /**< @deprecated removed */ #define ENCTYPE_AES128_CTS_HMAC_SHA1_96 0x0011 /**< RFC 3962 */ #define ENCTYPE_AES256_CTS_HMAC_SHA1_96 0x0012 /**< RFC 3962 */ #define ENCTYPE_AES128_CTS_HMAC_SHA256_128 0x0013 /**< RFC 8009 */ #define ENCTYPE_AES256_CTS_HMAC_SHA384_192 0x0014 /**< RFC 8009 */ #define ENCTYPE_ARCFOUR_HMAC 0x0017 /**< RFC 4757 */ #define ENCTYPE_ARCFOUR_HMAC_EXP 0x0018 /**< RFC 4757 */ #define ENCTYPE_CAMELLIA128_CTS_CMAC 0x0019 /**< RFC 6803 */ #define ENCTYPE_CAMELLIA256_CTS_CMAC 0x001a /**< RFC 6803 */ #define ENCTYPE_UNKNOWN 0x01ff /* * Historically we used the value 9 for unkeyed SHA-1. RFC 3961 assigns this * value to rsa-md5-des3, which fortunately is unused. For ABI compatibility * we allow either 9 or 14 for SHA-1. */ #define CKSUMTYPE_CRC32 0x0001 #define CKSUMTYPE_RSA_MD4 0x0002 #define CKSUMTYPE_RSA_MD4_DES 0x0003 #define CKSUMTYPE_DESCBC 0x0004 /* des-mac-k */ /* rsa-md4-des-k */ #define CKSUMTYPE_RSA_MD5 0x0007 #define CKSUMTYPE_RSA_MD5_DES 0x0008 #define CKSUMTYPE_NIST_SHA 0x0009 #define CKSUMTYPE_HMAC_SHA1_DES3 0x000c /* @deprecated removed */ #define CKSUMTYPE_SHA1 0x000d /**< RFC 3962 */ #define CKSUMTYPE_HMAC_SHA1_96_AES128 0x000f /**< RFC 3962. Used with ENCTYPE_AES128_CTS_HMAC_SHA1_96 */ #define CKSUMTYPE_HMAC_SHA1_96_AES256 0x0010 /**< RFC 3962. Used with ENCTYPE_AES256_CTS_HMAC_SHA1_96 */ #define CKSUMTYPE_HMAC_SHA256_128_AES128 0x0013 /**< RFC 8009 */ #define CKSUMTYPE_HMAC_SHA384_192_AES256 0x0014 /**< RFC 8009 */ #define CKSUMTYPE_CMAC_CAMELLIA128 0x0011 /**< RFC 6803 */ #define CKSUMTYPE_CMAC_CAMELLIA256 0x0012 /**< RFC 6803 */ #define CKSUMTYPE_MD5_HMAC_ARCFOUR -137 /* Microsoft netlogon */ #define CKSUMTYPE_HMAC_MD5_ARCFOUR -138 /**< RFC 4757 */ /* * The following are entropy source designations. Whenever * krb5_C_random_add_entropy is called, one of these source ids is passed in. * This allows the library to better estimate bits of entropy in the sample and * to keep track of what sources of entropy have contributed enough entropy. * Sources marked internal MUST NOT be used by applications outside the * Kerberos library */ enum { KRB5_C_RANDSOURCE_OLDAPI = 0, /*calls to krb5_C_RANDOM_SEED (INTERNAL)*/ KRB5_C_RANDSOURCE_OSRAND = 1, /* /dev/random or equivalent (internal)*/ KRB5_C_RANDSOURCE_TRUSTEDPARTY = 2, /* From KDC or other trusted party*/ /* * This source should be used carefully; data in this category * should be from a third party trusted to give random bits * For example keys issued by the KDC in the application server. */ KRB5_C_RANDSOURCE_TIMING = 3, /* Timing of operations*/ KRB5_C_RANDSOURCE_EXTERNAL_PROTOCOL = 4, /*Protocol data possibly from attacker*/ KRB5_C_RANDSOURCE_MAX = 5 /*Do not use; maximum source ID*/ }; #ifndef krb5_roundup /* round x up to nearest multiple of y */ #define krb5_roundup(x, y) ((((x) + (y) - 1)/(y))*(y)) #endif /* roundup */ /* macro function definitions to help clean up code */ #if 1 #define krb5_x(ptr,args) ((ptr)?((*(ptr)) args):(abort(),1)) #define krb5_xc(ptr,args) ((ptr)?((*(ptr)) args):(abort(),(char*)0)) #else #define krb5_x(ptr,args) ((*(ptr)) args) #define krb5_xc(ptr,args) ((*(ptr)) args) #endif /** * Encrypt data using a key (operates on keyblock). * * @param [in] context Library context * @param [in] key Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in,out] cipher_state Cipher state; specify NULL if not needed * @param [in] input Data to be encrypted * @param [out] output Encrypted data * * This function encrypts the data block @a input and stores the output into @a * output. The actual encryption key will be derived from @a key and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the encryption operation, and * is updated with the state to be passed as input to the next operation. * * @note The caller must initialize @a output and allocate at least enough * space for the result (using krb5_c_encrypt_length() to determine the amount * of space needed). @a output->length will be set to the actual length of the * ciphertext. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_encrypt(krb5_context context, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *cipher_state, const krb5_data *input, krb5_enc_data *output); /** * Decrypt data using a key (operates on keyblock). * * @param [in] context Library context * @param [in] key Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in,out] cipher_state Cipher state; specify NULL if not needed * @param [in] input Encrypted data * @param [out] output Decrypted data * * This function decrypts the data block @a input and stores the output into @a * output. The actual decryption key will be derived from @a key and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the decryption operation, and * is updated with the state to be passed as input to the next operation. * * @note The caller must initialize @a output and allocate at least enough * space for the result. The usual practice is to allocate an output buffer as * long as the ciphertext, and let krb5_c_decrypt() trim @a output->length. * For some enctypes, the resulting @a output->length may include padding * bytes. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_decrypt(krb5_context context, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *cipher_state, const krb5_enc_data *input, krb5_data *output); /** * Compute encrypted data length. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] inputlen Length of the data to be encrypted * @param [out] length Length of the encrypted data * * This function computes the length of the ciphertext produced by encrypting * @a inputlen bytes including padding, confounder, and checksum. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_encrypt_length(krb5_context context, krb5_enctype enctype, size_t inputlen, size_t *length); /** * Return cipher block size. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [out] blocksize Block size for @a enctype * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_block_size(krb5_context context, krb5_enctype enctype, size_t *blocksize); /** * Return length of the specified key in bytes. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [out] keybytes Number of bytes required to make a key * @param [out] keylength Length of final key * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_keylengths(krb5_context context, krb5_enctype enctype, size_t *keybytes, size_t *keylength); /** * Initialize a new cipher state. * * @param [in] context Library context * @param [in] key Key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [out] new_state New cipher state * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_init_state(krb5_context context, const krb5_keyblock *key, krb5_keyusage usage, krb5_data *new_state); /** * Free a cipher state previously allocated by krb5_c_init_state(). * * @param [in] context Library context * @param [in] key Key * @param [in] state Cipher state to be freed * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_free_state(krb5_context context, const krb5_keyblock *key, krb5_data *state); /** * Generate enctype-specific pseudo-random bytes. * * @param [in] context Library context * @param [in] keyblock Key * @param [in] input Input data * @param [out] output Output data * * This function selects a pseudo-random function based on @a keyblock and * computes its value over @a input, placing the result into @a output. * The caller must preinitialize @a output and allocate space for the * result, using krb5_c_prf_length() to determine the required length. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_prf(krb5_context context, const krb5_keyblock *keyblock, krb5_data *input, krb5_data *output); /** * Get the output length of pseudo-random functions for an encryption type. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [out] len Length of PRF output * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_prf_length(krb5_context context, krb5_enctype enctype, size_t *len); /** * Generate pseudo-random bytes using RFC 6113 PRF+. * * @param [in] context Library context * @param [in] k KDC contribution key * @param [in] input Input data * @param [out] output Pseudo-random output buffer * * This function fills @a output with PRF+(k, input) as defined in RFC 6113 * section 5.1. The caller must preinitialize @a output and allocate the * desired amount of space. The length of the pseudo-random output will match * the length of @a output. * * @note RFC 4402 defines a different PRF+ operation. This function does not * implement that operation. * * @return 0 on success, @c E2BIG if output->length is too large for PRF+ to * generate, @c ENOMEM on allocation failure, or an error code from * krb5_c_prf() */ krb5_error_code KRB5_CALLCONV krb5_c_prfplus(krb5_context context, const krb5_keyblock *k, const krb5_data *input, krb5_data *output); /** * Derive a key using some input data (via RFC 6113 PRF+). * * @param [in] context Library context * @param [in] k KDC contribution key * @param [in] input Input string * @param [in] enctype Output key enctype (or @c ENCTYPE_NULL) * @param [out] out Derived keyblock * * This function uses PRF+ as defined in RFC 6113 to derive a key from another * key and an input string. If @a enctype is @c ENCTYPE_NULL, the output key * will have the same enctype as the input key. */ krb5_error_code KRB5_CALLCONV krb5_c_derive_prfplus(krb5_context context, const krb5_keyblock *k, const krb5_data *input, krb5_enctype enctype, krb5_keyblock **out); /** * Compute the KRB-FX-CF2 combination of two keys and pepper strings. * * @param [in] context Library context * @param [in] k1 KDC contribution key * @param [in] pepper1 String "PKINIT" * @param [in] k2 Reply key * @param [in] pepper2 String "KeyExchange" * @param [out] out Output key * * This function computes the KRB-FX-CF2 function over its inputs and places * the results in a newly allocated keyblock. This function is simple in that * it assumes that @a pepper1 and @a pepper2 are C strings with no internal * nulls and that the enctype of the result will be the same as that of @a k1. * @a k1 and @a k2 may be of different enctypes. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_fx_cf2_simple(krb5_context context, const krb5_keyblock *k1, const char *pepper1, const krb5_keyblock *k2, const char *pepper2, krb5_keyblock **out); /** * Generate an enctype-specific random encryption key. * * @param [in] context Library context * @param [in] enctype Encryption type of the generated key * @param [out] k5_random_key An allocated and initialized keyblock * * Use krb5_free_keyblock_contents() to free @a k5_random_key when * no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_make_random_key(krb5_context context, krb5_enctype enctype, krb5_keyblock *k5_random_key); /** * Generate an enctype-specific key from random data. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] random_data Random input data * @param [out] k5_random_key Resulting key * * This function takes random input data @a random_data and produces a valid * key @a k5_random_key for a given @a enctype. * * @note It is assumed that @a k5_random_key has already been initialized and * @a k5_random_key->contents has been allocated with the correct length. * * @sa krb5_c_keylengths() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_random_to_key(krb5_context context, krb5_enctype enctype, krb5_data *random_data, krb5_keyblock *k5_random_key); /** * Add entropy to the pseudo-random number generator. * * @param [in] context Library context * @param [in] randsource Entropy source (see KRB5_RANDSOURCE types) * @param [in] data Data * * Contribute entropy to the PRNG used by krb5 crypto operations. This may or * may not affect the output of the next crypto operation requiring random * data. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_random_add_entropy(krb5_context context, unsigned int randsource, const krb5_data *data); /** * Generate pseudo-random bytes. * * @param [in] context Library context * @param [out] data Random data * * Fills in @a data with bytes from the PRNG used by krb5 crypto operations. * The caller must preinitialize @a data and allocate the desired amount of * space. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_random_make_octets(krb5_context context, krb5_data *data); /** * Collect entropy from the OS if possible. * * @param [in] context Library context * @param [in] strong Strongest available source of entropy * @param [out] success 1 if OS provides entropy, 0 otherwise * * If @a strong is non-zero, this function attempts to use the strongest * available source of entropy. Setting this flag may cause the function to * block on some operating systems. Good uses include seeding the PRNG for * kadmind and realm setup. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_random_os_entropy(krb5_context context, int strong, int *success); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_c_random_seed(krb5_context context, krb5_data *data); /** * Convert a string (such a password) to a key. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] string String to be converted * @param [in] salt Salt value * @param [out] key Generated key * * This function converts @a string to a @a key of encryption type @a enctype, * using the specified @a salt. The newly created @a key must be released by * calling krb5_free_keyblock_contents() when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_string_to_key(krb5_context context, krb5_enctype enctype, const krb5_data *string, const krb5_data *salt, krb5_keyblock *key); /** * Convert a string (such as a password) to a key with additional parameters. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] string String to be converted * @param [in] salt Salt value * @param [in] params Parameters * @param [out] key Generated key * * This function is similar to krb5_c_string_to_key(), but also takes * parameters which may affect the algorithm in an enctype-dependent way. The * newly created @a key must be released by calling * krb5_free_keyblock_contents() when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_string_to_key_with_params(krb5_context context, krb5_enctype enctype, const krb5_data *string, const krb5_data *salt, const krb5_data *params, krb5_keyblock *key); /** * Compare two encryption types. * * @param [in] context Library context * @param [in] e1 First encryption type * @param [in] e2 Second encryption type * @param [out] similar @c TRUE if types are similar, @c FALSE if not * * This function determines whether two encryption types use the same kind of * keys. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_enctype_compare(krb5_context context, krb5_enctype e1, krb5_enctype e2, krb5_boolean *similar); /** * Compute a checksum (operates on keyblock). * * @param [in] context Library context * @param [in] cksumtype Checksum type (0 for mandatory type) * @param [in] key Encryption key for a keyed checksum * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] input Input data * @param [out] cksum Generated checksum * * This function computes a checksum of type @a cksumtype over @a input, using * @a key if the checksum type is a keyed checksum. If @a cksumtype is 0 and * @a key is non-null, the checksum type will be the mandatory-to-implement * checksum type for the key's encryption type. The actual checksum key will * be derived from @a key and @a usage if key derivation is specified for the * checksum type. The newly created @a cksum must be released by calling * krb5_free_checksum_contents() when it is no longer needed. * * @note This function is similar to krb5_k_make_checksum(), but operates * on keyblock @a key. * * @sa krb5_c_verify_checksum() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_make_checksum(krb5_context context, krb5_cksumtype cksumtype, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *input, krb5_checksum *cksum); /** * Verify a checksum (operates on keyblock). * * @param [in] context Library context * @param [in] key Encryption key for a keyed checksum * @param [in] usage @a key usage * @param [in] data Data to be used to compute a new checksum * using @a key to compare @a cksum against * @param [in] cksum Checksum to be verified * @param [out] valid Non-zero for success, zero for failure * * This function verifies that @a cksum is a valid checksum for @a data. If * the checksum type of @a cksum is a keyed checksum, @a key is used to verify * the checksum. If the checksum type in @a cksum is 0 and @a key is not NULL, * the mandatory checksum type for @a key will be used. The actual checksum * key will be derived from @a key and @a usage if key derivation is specified * for the checksum type. * * @note This function is similar to krb5_k_verify_checksum(), but operates * on keyblock @a key. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_verify_checksum(krb5_context context, const krb5_keyblock *key, krb5_keyusage usage, const krb5_data *data, const krb5_checksum *cksum, krb5_boolean *valid); /** * Return the length of checksums for a checksum type. * * @param [in] context Library context * @param [in] cksumtype Checksum type * @param [out] length Checksum length * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_checksum_length(krb5_context context, krb5_cksumtype cksumtype, size_t *length); /** * Return a list of keyed checksum types usable with an encryption type. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [out] count Count of allowable checksum types * @param [out] cksumtypes Array of allowable checksum types * * Use krb5_free_cksumtypes() to free @a cksumtypes when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_keyed_checksum_types(krb5_context context, krb5_enctype enctype, unsigned int *count, krb5_cksumtype **cksumtypes); /** @defgroup KRB5_KEYUSAGE KRB5_KEYUSAGE * @{ */ #define KRB5_KEYUSAGE_AS_REQ_PA_ENC_TS 1 #define KRB5_KEYUSAGE_KDC_REP_TICKET 2 #define KRB5_KEYUSAGE_AS_REP_ENCPART 3 #define KRB5_KEYUSAGE_TGS_REQ_AD_SESSKEY 4 #define KRB5_KEYUSAGE_TGS_REQ_AD_SUBKEY 5 #define KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM 6 #define KRB5_KEYUSAGE_TGS_REQ_AUTH 7 #define KRB5_KEYUSAGE_TGS_REP_ENCPART_SESSKEY 8 #define KRB5_KEYUSAGE_TGS_REP_ENCPART_SUBKEY 9 #define KRB5_KEYUSAGE_AP_REQ_AUTH_CKSUM 10 #define KRB5_KEYUSAGE_AP_REQ_AUTH 11 #define KRB5_KEYUSAGE_AP_REP_ENCPART 12 #define KRB5_KEYUSAGE_KRB_PRIV_ENCPART 13 #define KRB5_KEYUSAGE_KRB_CRED_ENCPART 14 #define KRB5_KEYUSAGE_KRB_SAFE_CKSUM 15 #define KRB5_KEYUSAGE_APP_DATA_ENCRYPT 16 #define KRB5_KEYUSAGE_APP_DATA_CKSUM 17 #define KRB5_KEYUSAGE_KRB_ERROR_CKSUM 18 #define KRB5_KEYUSAGE_AD_KDCISSUED_CKSUM 19 #define KRB5_KEYUSAGE_AD_MTE 20 #define KRB5_KEYUSAGE_AD_ITE 21 /* XXX need to register these */ #define KRB5_KEYUSAGE_GSS_TOK_MIC 22 #define KRB5_KEYUSAGE_GSS_TOK_WRAP_INTEG 23 #define KRB5_KEYUSAGE_GSS_TOK_WRAP_PRIV 24 /* Defined in Integrating SAM Mechanisms with Kerberos draft */ #define KRB5_KEYUSAGE_PA_SAM_CHALLENGE_CKSUM 25 /** Note conflict with @ref KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST */ #define KRB5_KEYUSAGE_PA_SAM_CHALLENGE_TRACKID 26 /** Note conflict with @ref KRB5_KEYUSAGE_PA_S4U_X509_USER_REPLY */ #define KRB5_KEYUSAGE_PA_SAM_RESPONSE 27 /* Defined in [MS-SFU] */ /** Note conflict with @ref KRB5_KEYUSAGE_PA_SAM_CHALLENGE_TRACKID */ #define KRB5_KEYUSAGE_PA_S4U_X509_USER_REQUEST 26 /** Note conflict with @ref KRB5_KEYUSAGE_PA_SAM_RESPONSE */ #define KRB5_KEYUSAGE_PA_S4U_X509_USER_REPLY 27 /* unused */ #define KRB5_KEYUSAGE_PA_REFERRAL 26 #define KRB5_KEYUSAGE_AD_SIGNEDPATH -21 #define KRB5_KEYUSAGE_IAKERB_FINISHED 42 #define KRB5_KEYUSAGE_PA_PKINIT_KX 44 #define KRB5_KEYUSAGE_PA_OTP_REQUEST 45 /**< See RFC 6560 section 4.2 */ /* define in draft-ietf-krb-wg-preauth-framework*/ #define KRB5_KEYUSAGE_FAST_REQ_CHKSUM 50 #define KRB5_KEYUSAGE_FAST_ENC 51 #define KRB5_KEYUSAGE_FAST_REP 52 #define KRB5_KEYUSAGE_FAST_FINISHED 53 #define KRB5_KEYUSAGE_ENC_CHALLENGE_CLIENT 54 #define KRB5_KEYUSAGE_ENC_CHALLENGE_KDC 55 #define KRB5_KEYUSAGE_AS_REQ 56 #define KRB5_KEYUSAGE_CAMMAC 64 #define KRB5_KEYUSAGE_SPAKE 65 /* Key usage values 512-1023 are reserved for uses internal to a Kerberos * implementation. */ #define KRB5_KEYUSAGE_PA_FX_COOKIE 513 /**< Used for encrypted FAST cookies */ #define KRB5_KEYUSAGE_PA_AS_FRESHNESS 514 /**< Used for freshness tokens */ /** @} */ /* end of KRB5_KEYUSAGE group */ /** * Verify that a specified encryption type is a valid Kerberos encryption type. * * @param [in] ktype Encryption type * * @return @c TRUE if @a ktype is valid, @c FALSE if not */ krb5_boolean KRB5_CALLCONV krb5_c_valid_enctype(krb5_enctype ktype); /** * Verify that specified checksum type is a valid Kerberos checksum type. * * @param [in] ctype Checksum type * * @return @c TRUE if @a ctype is valid, @c FALSE if not */ krb5_boolean KRB5_CALLCONV krb5_c_valid_cksumtype(krb5_cksumtype ctype); /** * Test whether a checksum type is collision-proof. * * @param [in] ctype Checksum type * * @return @c TRUE if @a ctype is collision-proof, @c FALSE if it is not * collision-proof or not a valid checksum type. */ krb5_boolean KRB5_CALLCONV krb5_c_is_coll_proof_cksum(krb5_cksumtype ctype); /** * Test whether a checksum type is keyed. * * @param [in] ctype Checksum type * * @return @c TRUE if @a ctype is a keyed checksum type, @c FALSE otherwise. */ krb5_boolean KRB5_CALLCONV krb5_c_is_keyed_cksum(krb5_cksumtype ctype); /* AEAD APIs */ /** @defgroup KRB5_CRYPTO_TYPE KRB5_CRYPTO_TYPE * @{ */ #define KRB5_CRYPTO_TYPE_EMPTY 0 /**< [in] ignored */ #define KRB5_CRYPTO_TYPE_HEADER 1 /**< [out] header */ #define KRB5_CRYPTO_TYPE_DATA 2 /**< [in, out] plaintext */ #define KRB5_CRYPTO_TYPE_SIGN_ONLY 3 /**< [in] associated data */ #define KRB5_CRYPTO_TYPE_PADDING 4 /**< [out] padding */ #define KRB5_CRYPTO_TYPE_TRAILER 5 /**< [out] checksum for encrypt */ #define KRB5_CRYPTO_TYPE_CHECKSUM 6 /**< [out] checksum for MIC */ #define KRB5_CRYPTO_TYPE_STREAM 7 /**< [in] entire message without decomposing the structure into header, data and trailer buffers */ /** @} */ /* end of KRB5_CRYPTO_TYPE group */ /** * Fill in a checksum element in IOV array (operates on keyblock) * * @param [in] context Library context * @param [in] cksumtype Checksum type (0 for mandatory type) * @param [in] key Encryption key for a keyed checksum * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in,out] data IOV array * @param [in] num_data Size of @a data * * Create a checksum in the #KRB5_CRYPTO_TYPE_CHECKSUM element over * #KRB5_CRYPTO_TYPE_DATA and #KRB5_CRYPTO_TYPE_SIGN_ONLY chunks in @a data. * Only the #KRB5_CRYPTO_TYPE_CHECKSUM region is modified. * * @note This function is similar to krb5_k_make_checksum_iov(), but operates * on keyblock @a key. * * @sa krb5_c_verify_checksum_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_make_checksum_iov(krb5_context context, krb5_cksumtype cksumtype, const krb5_keyblock *key, krb5_keyusage usage, krb5_crypto_iov *data, size_t num_data); /** * Validate a checksum element in IOV array (operates on keyblock). * * @param [in] context Library context * @param [in] cksumtype Checksum type (0 for mandatory type) * @param [in] key Encryption key for a keyed checksum * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] data IOV array * @param [in] num_data Size of @a data * @param [out] valid Non-zero for success, zero for failure * * Confirm that the checksum in the #KRB5_CRYPTO_TYPE_CHECKSUM element is a * valid checksum of the #KRB5_CRYPTO_TYPE_DATA and #KRB5_CRYPTO_TYPE_SIGN_ONLY * regions in the iov. * * @note This function is similar to krb5_k_verify_checksum_iov(), but operates * on keyblock @a key. * * @sa krb5_c_make_checksum_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_verify_checksum_iov(krb5_context context, krb5_cksumtype cksumtype, const krb5_keyblock *key, krb5_keyusage usage, const krb5_crypto_iov *data, size_t num_data, krb5_boolean *valid); /** * Encrypt data in place supporting AEAD (operates on keyblock). * * @param [in] context Library context * @param [in] keyblock Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] cipher_state Cipher state; specify NULL if not needed * @param [in,out] data IOV array. Modified in-place. * @param [in] num_data Size of @a data * * This function encrypts the data block @a data and stores the output in-place. * The actual encryption key will be derived from @a keyblock and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the encryption operation, and * is updated with the state to be passed as input to the next operation. * The caller must allocate the right number of krb5_crypto_iov * structures before calling into this API. * * @note On return from a krb5_c_encrypt_iov() call, the @a data->length in the * iov structure are adjusted to reflect actual lengths of the ciphertext used. * For example, if the padding length is too large, the length will be reduced. * Lengths are never increased. * * @note This function is similar to krb5_k_encrypt_iov(), but operates * on keyblock @a keyblock. * * @sa krb5_c_decrypt_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_encrypt_iov(krb5_context context, const krb5_keyblock *keyblock, krb5_keyusage usage, const krb5_data *cipher_state, krb5_crypto_iov *data, size_t num_data); /** * Decrypt data in place supporting AEAD (operates on keyblock). * * @param [in] context Library context * @param [in] keyblock Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] cipher_state Cipher state; specify NULL if not needed * @param [in,out] data IOV array. Modified in-place. * @param [in] num_data Size of @a data * * This function decrypts the data block @a data and stores the output in-place. * The actual decryption key will be derived from @a keyblock and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the decryption operation, and * is updated with the state to be passed as input to the next operation. * The caller must allocate the right number of krb5_crypto_iov * structures before calling into this API. * * @note On return from a krb5_c_decrypt_iov() call, the @a data->length in the * iov structure are adjusted to reflect actual lengths of the ciphertext used. * For example, if the padding length is too large, the length will be reduced. * Lengths are never increased. * * @note This function is similar to krb5_k_decrypt_iov(), but operates * on keyblock @a keyblock. * * @sa krb5_c_decrypt_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_decrypt_iov(krb5_context context, const krb5_keyblock *keyblock, krb5_keyusage usage, const krb5_data *cipher_state, krb5_crypto_iov *data, size_t num_data); /** * Return a length of a message field specific to the encryption type. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] type Type field (See @ref KRB5_CRYPTO_TYPE types) * @param [out] size Length of the @a type specific to @a enctype * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_crypto_length(krb5_context context, krb5_enctype enctype, krb5_cryptotype type, unsigned int *size); /** * Fill in lengths for header, trailer and padding in a IOV array. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in,out] data IOV array * @param [in] num_data Size of @a data * * Padding is set to the actual padding required based on the provided * @a data buffers. Typically this API is used after setting up the data * buffers and #KRB5_CRYPTO_TYPE_SIGN_ONLY buffers, but before actually * allocating header, trailer and padding. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_c_crypto_length_iov(krb5_context context, krb5_enctype enctype, krb5_crypto_iov *data, size_t num_data); /** * Return a number of padding octets. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] data_length Length of the plaintext to pad * @param [out] size Number of padding octets * * This function returns the number of the padding octets required to pad * @a data_length octets of plaintext. * * @retval 0 Success; otherwise - KRB5_BAD_ENCTYPE */ krb5_error_code KRB5_CALLCONV krb5_c_padding_length(krb5_context context, krb5_enctype enctype, size_t data_length, unsigned int *size); /** * Create a krb5_key from the enctype and key data in a keyblock. * * @param [in] context Library context * @param [in] key_data Keyblock * @param [out] out Opaque key * * The reference count on a key @a out is set to 1. * Use krb5_k_free_key() to free @a out when it is no longer needed. * * @retval 0 Success; otherwise - KRB5_BAD_ENCTYPE */ krb5_error_code KRB5_CALLCONV krb5_k_create_key(krb5_context context, const krb5_keyblock *key_data, krb5_key *out); /** Increment the reference count on a key. */ void KRB5_CALLCONV krb5_k_reference_key(krb5_context context, krb5_key key); /** Decrement the reference count on a key and free it if it hits zero. */ void KRB5_CALLCONV krb5_k_free_key(krb5_context context, krb5_key key); /** Retrieve a copy of the keyblock from a krb5_key structure. */ krb5_error_code KRB5_CALLCONV krb5_k_key_keyblock(krb5_context context, krb5_key key, krb5_keyblock **key_data); /** Retrieve the enctype of a krb5_key structure. */ krb5_enctype KRB5_CALLCONV krb5_k_key_enctype(krb5_context context, krb5_key key); /** * Encrypt data using a key (operates on opaque key). * * @param [in] context Library context * @param [in] key Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in,out] cipher_state Cipher state; specify NULL if not needed * @param [in] input Data to be encrypted * @param [out] output Encrypted data * * This function encrypts the data block @a input and stores the output into @a * output. The actual encryption key will be derived from @a key and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the encryption operation, and * is updated with the state to be passed as input to the next operation. * * @note The caller must initialize @a output and allocate at least enough * space for the result (using krb5_c_encrypt_length() to determine the amount * of space needed). @a output->length will be set to the actual length of the * ciphertext. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_encrypt(krb5_context context, krb5_key key, krb5_keyusage usage, const krb5_data *cipher_state, const krb5_data *input, krb5_enc_data *output); /** * Encrypt data in place supporting AEAD (operates on opaque key). * * @param [in] context Library context * @param [in] key Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] cipher_state Cipher state; specify NULL if not needed * @param [in,out] data IOV array. Modified in-place. * @param [in] num_data Size of @a data * * This function encrypts the data block @a data and stores the output in-place. * The actual encryption key will be derived from @a key and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the encryption operation, and * is updated with the state to be passed as input to the next operation. * The caller must allocate the right number of krb5_crypto_iov * structures before calling into this API. * * @note On return from a krb5_c_encrypt_iov() call, the @a data->length in the * iov structure are adjusted to reflect actual lengths of the ciphertext used. * For example, if the padding length is too large, the length will be reduced. * Lengths are never increased. * * @note This function is similar to krb5_c_encrypt_iov(), but operates * on opaque key @a key. * * @sa krb5_k_decrypt_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_encrypt_iov(krb5_context context, krb5_key key, krb5_keyusage usage, const krb5_data *cipher_state, krb5_crypto_iov *data, size_t num_data); /** * Decrypt data using a key (operates on opaque key). * * @param [in] context Library context * @param [in] key Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in,out] cipher_state Cipher state; specify NULL if not needed * @param [in] input Encrypted data * @param [out] output Decrypted data * * This function decrypts the data block @a input and stores the output into @a * output. The actual decryption key will be derived from @a key and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the decryption operation, and * is updated with the state to be passed as input to the next operation. * * @note The caller must initialize @a output and allocate at least enough * space for the result. The usual practice is to allocate an output buffer as * long as the ciphertext, and let krb5_c_decrypt() trim @a output->length. * For some enctypes, the resulting @a output->length may include padding * bytes. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_decrypt(krb5_context context, krb5_key key, krb5_keyusage usage, const krb5_data *cipher_state, const krb5_enc_data *input, krb5_data *output); /** * Decrypt data in place supporting AEAD (operates on opaque key). * * @param [in] context Library context * @param [in] key Encryption key * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] cipher_state Cipher state; specify NULL if not needed * @param [in,out] data IOV array. Modified in-place. * @param [in] num_data Size of @a data * * This function decrypts the data block @a data and stores the output in-place. * The actual decryption key will be derived from @a key and @a usage * if key derivation is specified for the encryption type. If non-null, @a * cipher_state specifies the beginning state for the decryption operation, and * is updated with the state to be passed as input to the next operation. * The caller must allocate the right number of krb5_crypto_iov * structures before calling into this API. * * @note On return from a krb5_c_decrypt_iov() call, the @a data->length in the * iov structure are adjusted to reflect actual lengths of the ciphertext used. * For example, if the padding length is too large, the length will be reduced. * Lengths are never increased. * * @note This function is similar to krb5_c_decrypt_iov(), but operates * on opaque key @a key. * * @sa krb5_k_encrypt_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_decrypt_iov(krb5_context context, krb5_key key, krb5_keyusage usage, const krb5_data *cipher_state, krb5_crypto_iov *data, size_t num_data); /** * Compute a checksum (operates on opaque key). * * @param [in] context Library context * @param [in] cksumtype Checksum type (0 for mandatory type) * @param [in] key Encryption key for a keyed checksum * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] input Input data * @param [out] cksum Generated checksum * * This function computes a checksum of type @a cksumtype over @a input, using * @a key if the checksum type is a keyed checksum. If @a cksumtype is 0 and * @a key is non-null, the checksum type will be the mandatory-to-implement * checksum type for the key's encryption type. The actual checksum key will * be derived from @a key and @a usage if key derivation is specified for the * checksum type. The newly created @a cksum must be released by calling * krb5_free_checksum_contents() when it is no longer needed. * * @note This function is similar to krb5_c_make_checksum(), but operates * on opaque @a key. * * @sa krb5_c_verify_checksum() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_make_checksum(krb5_context context, krb5_cksumtype cksumtype, krb5_key key, krb5_keyusage usage, const krb5_data *input, krb5_checksum *cksum); /** * Fill in a checksum element in IOV array (operates on opaque key) * * @param [in] context Library context * @param [in] cksumtype Checksum type (0 for mandatory type) * @param [in] key Encryption key for a keyed checksum * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in,out] data IOV array * @param [in] num_data Size of @a data * * Create a checksum in the #KRB5_CRYPTO_TYPE_CHECKSUM element over * #KRB5_CRYPTO_TYPE_DATA and #KRB5_CRYPTO_TYPE_SIGN_ONLY chunks in @a data. * Only the #KRB5_CRYPTO_TYPE_CHECKSUM region is modified. * * @note This function is similar to krb5_c_make_checksum_iov(), but operates * on opaque @a key. * * @sa krb5_k_verify_checksum_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_make_checksum_iov(krb5_context context, krb5_cksumtype cksumtype, krb5_key key, krb5_keyusage usage, krb5_crypto_iov *data, size_t num_data); /** * Verify a checksum (operates on opaque key). * * @param [in] context Library context * @param [in] key Encryption key for a keyed checksum * @param [in] usage @a key usage * @param [in] data Data to be used to compute a new checksum * using @a key to compare @a cksum against * @param [in] cksum Checksum to be verified * @param [out] valid Non-zero for success, zero for failure * * This function verifies that @a cksum is a valid checksum for @a data. If * the checksum type of @a cksum is a keyed checksum, @a key is used to verify * the checksum. If the checksum type in @a cksum is 0 and @a key is not NULL, * the mandatory checksum type for @a key will be used. The actual checksum * key will be derived from @a key and @a usage if key derivation is specified * for the checksum type. * * @note This function is similar to krb5_c_verify_checksum(), but operates * on opaque @a key. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_verify_checksum(krb5_context context, krb5_key key, krb5_keyusage usage, const krb5_data *data, const krb5_checksum *cksum, krb5_boolean *valid); /** * Validate a checksum element in IOV array (operates on opaque key). * * @param [in] context Library context * @param [in] cksumtype Checksum type (0 for mandatory type) * @param [in] key Encryption key for a keyed checksum * @param [in] usage Key usage (see @ref KRB5_KEYUSAGE types) * @param [in] data IOV array * @param [in] num_data Size of @a data * @param [out] valid Non-zero for success, zero for failure * * Confirm that the checksum in the #KRB5_CRYPTO_TYPE_CHECKSUM element is a * valid checksum of the #KRB5_CRYPTO_TYPE_DATA and #KRB5_CRYPTO_TYPE_SIGN_ONLY * regions in the iov. * * @note This function is similar to krb5_c_verify_checksum_iov(), but operates * on opaque @a key. * * @sa krb5_k_make_checksum_iov() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_verify_checksum_iov(krb5_context context, krb5_cksumtype cksumtype, krb5_key key, krb5_keyusage usage, const krb5_crypto_iov *data, size_t num_data, krb5_boolean *valid); /** * Generate enctype-specific pseudo-random bytes (operates on opaque key). * * @param [in] context Library context * @param [in] key Key * @param [in] input Input data * @param [out] output Output data * * This function selects a pseudo-random function based on @a key and * computes its value over @a input, placing the result into @a output. * The caller must preinitialize @a output and allocate space for the * result. * * @note This function is similar to krb5_c_prf(), but operates * on opaque @a key. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_k_prf(krb5_context context, krb5_key key, krb5_data *input, krb5_data *output); #ifdef KRB5_OLD_CRYPTO /* * old cryptosystem routine prototypes. These are now layered * on top of the functions above. */ /** @deprecated Replaced by krb5_c_* API family.*/ krb5_error_code KRB5_CALLCONV krb5_encrypt(krb5_context context, krb5_const_pointer inptr, krb5_pointer outptr, size_t size, krb5_encrypt_block *eblock, krb5_pointer ivec); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_decrypt(krb5_context context, krb5_const_pointer inptr, krb5_pointer outptr, size_t size, krb5_encrypt_block *eblock, krb5_pointer ivec); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_process_key(krb5_context context, krb5_encrypt_block *eblock, const krb5_keyblock * key); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_finish_key(krb5_context context, krb5_encrypt_block * eblock); /** @deprecated See krb5_c_string_to_key() */ krb5_error_code KRB5_CALLCONV krb5_string_to_key(krb5_context context, const krb5_encrypt_block *eblock, krb5_keyblock * keyblock, const krb5_data *data, const krb5_data *salt); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_init_random_key(krb5_context context, const krb5_encrypt_block *eblock, const krb5_keyblock *keyblock, krb5_pointer *ptr); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_finish_random_key(krb5_context context, const krb5_encrypt_block *eblock, krb5_pointer *ptr); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_random_key(krb5_context context, const krb5_encrypt_block *eblock, krb5_pointer ptr, krb5_keyblock **keyblock); /** @deprecated Replaced by krb5_c_* API family. */ krb5_enctype KRB5_CALLCONV krb5_eblock_enctype(krb5_context context, const krb5_encrypt_block *eblock); /** @deprecated Replaced by krb5_c_* API family. */ krb5_error_code KRB5_CALLCONV krb5_use_enctype(krb5_context context, krb5_encrypt_block *eblock, krb5_enctype enctype); /** @deprecated Replaced by krb5_c_* API family. */ size_t KRB5_CALLCONV krb5_encrypt_size(size_t length, krb5_enctype crypto); /** @deprecated See krb5_c_checksum_length() */ size_t KRB5_CALLCONV krb5_checksum_size(krb5_context context, krb5_cksumtype ctype); /** @deprecated See krb5_c_make_checksum() */ krb5_error_code KRB5_CALLCONV krb5_calculate_checksum(krb5_context context, krb5_cksumtype ctype, krb5_const_pointer in, size_t in_length, krb5_const_pointer seed, size_t seed_length, krb5_checksum * outcksum); /** @deprecated See krb5_c_verify_checksum() */ krb5_error_code KRB5_CALLCONV krb5_verify_checksum(krb5_context context, krb5_cksumtype ctype, const krb5_checksum * cksum, krb5_const_pointer in, size_t in_length, krb5_const_pointer seed, size_t seed_length); #endif /* KRB5_OLD_CRYPTO */ /* * end "encryption.h" */ /* * begin "fieldbits.h" */ /* kdc_options for kdc_request */ /* options is 32 bits; each host is responsible to put the 4 bytes representing these bits into net order before transmission */ /* #define KDC_OPT_RESERVED 0x80000000 */ #define KDC_OPT_FORWARDABLE 0x40000000 #define KDC_OPT_FORWARDED 0x20000000 #define KDC_OPT_PROXIABLE 0x10000000 #define KDC_OPT_PROXY 0x08000000 #define KDC_OPT_ALLOW_POSTDATE 0x04000000 #define KDC_OPT_POSTDATED 0x02000000 /* #define KDC_OPT_UNUSED 0x01000000 */ #define KDC_OPT_RENEWABLE 0x00800000 /* #define KDC_OPT_UNUSED 0x00400000 */ /* #define KDC_OPT_RESERVED 0x00200000 */ /* #define KDC_OPT_RESERVED 0x00100000 */ /* #define KDC_OPT_RESERVED 0x00080000 */ /* #define KDC_OPT_RESERVED 0x00040000 */ #define KDC_OPT_CNAME_IN_ADDL_TKT 0x00020000 #define KDC_OPT_CANONICALIZE 0x00010000 #define KDC_OPT_REQUEST_ANONYMOUS 0x00008000 /* #define KDC_OPT_RESERVED 0x00004000 */ /* #define KDC_OPT_RESERVED 0x00002000 */ /* #define KDC_OPT_RESERVED 0x00001000 */ /* #define KDC_OPT_RESERVED 0x00000800 */ /* #define KDC_OPT_RESERVED 0x00000400 */ /* #define KDC_OPT_RESERVED 0x00000200 */ /* #define KDC_OPT_RESERVED 0x00000100 */ /* #define KDC_OPT_RESERVED 0x00000080 */ /* #define KDC_OPT_RESERVED 0x00000040 */ #define KDC_OPT_DISABLE_TRANSITED_CHECK 0x00000020 #define KDC_OPT_RENEWABLE_OK 0x00000010 #define KDC_OPT_ENC_TKT_IN_SKEY 0x00000008 /* #define KDC_OPT_UNUSED 0x00000004 */ #define KDC_OPT_RENEW 0x00000002 #define KDC_OPT_VALIDATE 0x00000001 /* * Mask of ticket flags in the TGT which should be converted into KDC * options when using the TGT to get derivative tickets. * * New mask = KDC_OPT_FORWARDABLE | KDC_OPT_PROXIABLE | * KDC_OPT_ALLOW_POSTDATE | KDC_OPT_RENEWABLE */ #define KDC_TKT_COMMON_MASK 0x54800000 /* definitions for ap_options fields */ /** @defgroup AP_OPTS AP_OPTS * * ap_options are 32 bits; each host is responsible to put the 4 bytes * representing these bits into net order before transmission * @{ */ #define AP_OPTS_RESERVED 0x80000000 #define AP_OPTS_USE_SESSION_KEY 0x40000000 /**< Use session key */ #define AP_OPTS_MUTUAL_REQUIRED 0x20000000 /**< Perform a mutual authentication exchange */ #define AP_OPTS_ETYPE_NEGOTIATION 0x00000002 #define AP_OPTS_USE_SUBKEY 0x00000001 /**< Generate a subsession key from the current session key obtained from the credentials */ /* #define AP_OPTS_RESERVED 0x10000000 */ /* #define AP_OPTS_RESERVED 0x08000000 */ /* #define AP_OPTS_RESERVED 0x04000000 */ /* #define AP_OPTS_RESERVED 0x02000000 */ /* #define AP_OPTS_RESERVED 0x01000000 */ /* #define AP_OPTS_RESERVED 0x00800000 */ /* #define AP_OPTS_RESERVED 0x00400000 */ /* #define AP_OPTS_RESERVED 0x00200000 */ /* #define AP_OPTS_RESERVED 0x00100000 */ /* #define AP_OPTS_RESERVED 0x00080000 */ /* #define AP_OPTS_RESERVED 0x00040000 */ /* #define AP_OPTS_RESERVED 0x00020000 */ /* #define AP_OPTS_RESERVED 0x00010000 */ /* #define AP_OPTS_RESERVED 0x00008000 */ /* #define AP_OPTS_RESERVED 0x00004000 */ /* #define AP_OPTS_RESERVED 0x00002000 */ /* #define AP_OPTS_RESERVED 0x00001000 */ /* #define AP_OPTS_RESERVED 0x00000800 */ /* #define AP_OPTS_RESERVED 0x00000400 */ /* #define AP_OPTS_RESERVED 0x00000200 */ /* #define AP_OPTS_RESERVED 0x00000100 */ /* #define AP_OPTS_RESERVED 0x00000080 */ /* #define AP_OPTS_RESERVED 0x00000040 */ /* #define AP_OPTS_RESERVED 0x00000020 */ /* #define AP_OPTS_RESERVED 0x00000010 */ /* #define AP_OPTS_RESERVED 0x00000008 */ /* #define AP_OPTS_RESERVED 0x00000004 */ #define AP_OPTS_WIRE_MASK 0xfffffff0 /** @} */ /* end of AP_OPTS group */ /* definitions for ad_type fields. */ #define AD_TYPE_RESERVED 0x8000 #define AD_TYPE_EXTERNAL 0x4000 #define AD_TYPE_REGISTERED 0x2000 #define AD_TYPE_FIELD_TYPE_MASK 0x1fff /* Ticket flags */ /* flags are 32 bits; each host is responsible to put the 4 bytes representing these bits into net order before transmission */ /* #define TKT_FLG_RESERVED 0x80000000 */ #define TKT_FLG_FORWARDABLE 0x40000000 #define TKT_FLG_FORWARDED 0x20000000 #define TKT_FLG_PROXIABLE 0x10000000 #define TKT_FLG_PROXY 0x08000000 #define TKT_FLG_MAY_POSTDATE 0x04000000 #define TKT_FLG_POSTDATED 0x02000000 #define TKT_FLG_INVALID 0x01000000 #define TKT_FLG_RENEWABLE 0x00800000 #define TKT_FLG_INITIAL 0x00400000 #define TKT_FLG_PRE_AUTH 0x00200000 #define TKT_FLG_HW_AUTH 0x00100000 #define TKT_FLG_TRANSIT_POLICY_CHECKED 0x00080000 #define TKT_FLG_OK_AS_DELEGATE 0x00040000 #define TKT_FLG_ENC_PA_REP 0x00010000 #define TKT_FLG_ANONYMOUS 0x00008000 /* #define TKT_FLG_RESERVED 0x00004000 */ /* #define TKT_FLG_RESERVED 0x00002000 */ /* #define TKT_FLG_RESERVED 0x00001000 */ /* #define TKT_FLG_RESERVED 0x00000800 */ /* #define TKT_FLG_RESERVED 0x00000400 */ /* #define TKT_FLG_RESERVED 0x00000200 */ /* #define TKT_FLG_RESERVED 0x00000100 */ /* #define TKT_FLG_RESERVED 0x00000080 */ /* #define TKT_FLG_RESERVED 0x00000040 */ /* #define TKT_FLG_RESERVED 0x00000020 */ /* #define TKT_FLG_RESERVED 0x00000010 */ /* #define TKT_FLG_RESERVED 0x00000008 */ /* #define TKT_FLG_RESERVED 0x00000004 */ /* #define TKT_FLG_RESERVED 0x00000002 */ /* #define TKT_FLG_RESERVED 0x00000001 */ /* definitions for lr_type fields. */ #define LR_TYPE_THIS_SERVER_ONLY 0x8000 #define LR_TYPE_INTERPRETATION_MASK 0x7fff /* definitions for msec direction bit for KRB_SAFE, KRB_PRIV */ #define MSEC_DIRBIT 0x8000 #define MSEC_VAL_MASK 0x7fff /* * end "fieldbits.h" */ /* * begin "proto.h" */ /** Protocol version number */ #define KRB5_PVNO 5 /* Message types */ #define KRB5_AS_REQ ((krb5_msgtype)10) /**< Initial authentication request */ #define KRB5_AS_REP ((krb5_msgtype)11) /**< Response to AS request */ #define KRB5_TGS_REQ ((krb5_msgtype)12) /**< Ticket granting server request */ #define KRB5_TGS_REP ((krb5_msgtype)13) /**< Response to TGS request */ #define KRB5_AP_REQ ((krb5_msgtype)14) /**< Auth req to application server */ #define KRB5_AP_REP ((krb5_msgtype)15) /**< Response to mutual AP request */ #define KRB5_SAFE ((krb5_msgtype)20) /**< Safe application message */ #define KRB5_PRIV ((krb5_msgtype)21) /**< Private application message */ #define KRB5_CRED ((krb5_msgtype)22) /**< Cred forwarding message */ #define KRB5_ERROR ((krb5_msgtype)30) /**< Error response */ /* LastReq types */ #define KRB5_LRQ_NONE 0 #define KRB5_LRQ_ALL_LAST_TGT 1 #define KRB5_LRQ_ONE_LAST_TGT (-1) #define KRB5_LRQ_ALL_LAST_INITIAL 2 #define KRB5_LRQ_ONE_LAST_INITIAL (-2) #define KRB5_LRQ_ALL_LAST_TGT_ISSUED 3 #define KRB5_LRQ_ONE_LAST_TGT_ISSUED (-3) #define KRB5_LRQ_ALL_LAST_RENEWAL 4 #define KRB5_LRQ_ONE_LAST_RENEWAL (-4) #define KRB5_LRQ_ALL_LAST_REQ 5 #define KRB5_LRQ_ONE_LAST_REQ (-5) #define KRB5_LRQ_ALL_PW_EXPTIME 6 #define KRB5_LRQ_ONE_PW_EXPTIME (-6) #define KRB5_LRQ_ALL_ACCT_EXPTIME 7 #define KRB5_LRQ_ONE_ACCT_EXPTIME (-7) /* PADATA types */ #define KRB5_PADATA_NONE 0 #define KRB5_PADATA_AP_REQ 1 #define KRB5_PADATA_TGS_REQ KRB5_PADATA_AP_REQ #define KRB5_PADATA_ENC_TIMESTAMP 2 /**< RFC 4120 */ #define KRB5_PADATA_PW_SALT 3 /**< RFC 4120 */ #if 0 /* Not used */ #define KRB5_PADATA_ENC_ENCKEY 4 /* Key encrypted within itself */ #endif #define KRB5_PADATA_ENC_UNIX_TIME 5 /**< timestamp encrypted in key. RFC 4120 */ #define KRB5_PADATA_ENC_SANDIA_SECURID 6 /**< SecurId passcode. RFC 4120 */ #define KRB5_PADATA_SESAME 7 /**< Sesame project. RFC 4120 */ #define KRB5_PADATA_OSF_DCE 8 /**< OSF DCE. RFC 4120 */ #define KRB5_CYBERSAFE_SECUREID 9 /**< Cybersafe. RFC 4120 */ #define KRB5_PADATA_AFS3_SALT 10 /**< Cygnus. RFC 4120, 3961 */ #define KRB5_PADATA_ETYPE_INFO 11 /**< Etype info for preauth. RFC 4120 */ #define KRB5_PADATA_SAM_CHALLENGE 12 /**< SAM/OTP */ #define KRB5_PADATA_SAM_RESPONSE 13 /**< SAM/OTP */ #define KRB5_PADATA_PK_AS_REQ_OLD 14 /**< PKINIT */ #define KRB5_PADATA_PK_AS_REP_OLD 15 /**< PKINIT */ #define KRB5_PADATA_PK_AS_REQ 16 /**< PKINIT. RFC 4556 */ #define KRB5_PADATA_PK_AS_REP 17 /**< PKINIT. RFC 4556 */ #define KRB5_PADATA_ETYPE_INFO2 19 /**< RFC 4120 */ #define KRB5_PADATA_USE_SPECIFIED_KVNO 20 /**< RFC 4120 */ #define KRB5_PADATA_SVR_REFERRAL_INFO 20 /**< Windows 2000 referrals. RFC 6820 */ #define KRB5_PADATA_SAM_REDIRECT 21 /**< SAM/OTP. RFC 4120 */ #define KRB5_PADATA_GET_FROM_TYPED_DATA 22 /**< Embedded in typed data. RFC 4120 */ #define KRB5_PADATA_REFERRAL 25 /**< draft referral system */ #define KRB5_PADATA_SAM_CHALLENGE_2 30 /**< draft challenge system, updated */ #define KRB5_PADATA_SAM_RESPONSE_2 31 /**< draft challenge system, updated */ /* MS-KILE */ #define KRB5_PADATA_PAC_REQUEST 128 /**< include Windows PAC */ #define KRB5_PADATA_FOR_USER 129 /**< username protocol transition request */ #define KRB5_PADATA_S4U_X509_USER 130 /**< certificate protocol transition request */ #define KRB5_PADATA_AS_CHECKSUM 132 /**< AS checksum */ #define KRB5_PADATA_FX_COOKIE 133 /**< RFC 6113 */ #define KRB5_PADATA_FX_FAST 136 /**< RFC 6113 */ #define KRB5_PADATA_FX_ERROR 137 /**< RFC 6113 */ #define KRB5_PADATA_ENCRYPTED_CHALLENGE 138 /**< RFC 6113 */ #define KRB5_PADATA_OTP_CHALLENGE 141 /**< RFC 6560 section 4.1 */ #define KRB5_PADATA_OTP_REQUEST 142 /**< RFC 6560 section 4.2 */ #define KRB5_PADATA_OTP_PIN_CHANGE 144 /**< RFC 6560 section 4.3 */ #define KRB5_PADATA_PKINIT_KX 147 /**< RFC 6112 */ #define KRB5_ENCPADATA_REQ_ENC_PA_REP 149 /**< RFC 6806 */ #define KRB5_PADATA_AS_FRESHNESS 150 /**< RFC 8070 */ #define KRB5_PADATA_SPAKE 151 #define KRB5_PADATA_PAC_OPTIONS 167 /**< MS-KILE and MS-SFU */ #define KRB5_SAM_USE_SAD_AS_KEY 0x80000000 #define KRB5_SAM_SEND_ENCRYPTED_SAD 0x40000000 #define KRB5_SAM_MUST_PK_ENCRYPT_SAD 0x20000000 /**< currently must be zero */ /** Transited encoding types */ #define KRB5_DOMAIN_X500_COMPRESS 1 /** alternate authentication types */ #define KRB5_ALTAUTH_ATT_CHALLENGE_RESPONSE 64 /* authorization data types. See RFC 4120 section 5.2.6 */ /** @defgroup KRB5_AUTHDATA KRB5_AUTHDATA * @{ */ #define KRB5_AUTHDATA_IF_RELEVANT 1 #define KRB5_AUTHDATA_KDC_ISSUED 4 #define KRB5_AUTHDATA_AND_OR 5 #define KRB5_AUTHDATA_MANDATORY_FOR_KDC 8 #define KRB5_AUTHDATA_INITIAL_VERIFIED_CAS 9 #define KRB5_AUTHDATA_OSF_DCE 64 #define KRB5_AUTHDATA_SESAME 65 #define KRB5_AUTHDATA_CAMMAC 96 #define KRB5_AUTHDATA_WIN2K_PAC 128 #define KRB5_AUTHDATA_ETYPE_NEGOTIATION 129 /**< RFC 4537 */ #define KRB5_AUTHDATA_SIGNTICKET 512 /**< @deprecated use PAC */ #define KRB5_AUTHDATA_FX_ARMOR 71 #define KRB5_AUTHDATA_AUTH_INDICATOR 97 #define KRB5_AUTHDATA_AP_OPTIONS 143 /** @} */ /* end of KRB5_AUTHDATA group */ /* password change constants */ #define KRB5_KPASSWD_SUCCESS 0 /**< Success */ #define KRB5_KPASSWD_MALFORMED 1 /**< Malformed request */ #define KRB5_KPASSWD_HARDERROR 2 /**< Server error */ #define KRB5_KPASSWD_AUTHERROR 3 /**< Authentication error */ #define KRB5_KPASSWD_SOFTERROR 4 /**< Password change rejected */ /* These are Microsoft's extensions in RFC 3244, and it looks like they'll become standardized, possibly with other additions. */ #define KRB5_KPASSWD_ACCESSDENIED 5 /**< Not authorized */ #define KRB5_KPASSWD_BAD_VERSION 6 /**< Unknown RPC version */ /** The presented credentials were not obtained using a password directly */ #define KRB5_KPASSWD_INITIAL_FLAG_NEEDED 7 /* * end "proto.h" */ /* Time set */ /** Ticket start time, end time, and renewal duration. */ typedef struct _krb5_ticket_times { krb5_timestamp authtime; /**< Time at which KDC issued the initial ticket that corresponds to this ticket */ /* XXX ? should ktime in KDC_REP == authtime in ticket? otherwise client can't get this */ krb5_timestamp starttime; /**< optional in ticket, if not present, use @a authtime */ krb5_timestamp endtime; /**< Ticket expiration time */ krb5_timestamp renew_till; /**< Latest time at which renewal of ticket can be valid */ } krb5_ticket_times; /** Structure for auth data */ typedef struct _krb5_authdata { krb5_magic magic; krb5_authdatatype ad_type; /**< ADTYPE */ unsigned int length; /**< Length of data */ krb5_octet *contents; /**< Data */ } krb5_authdata; /** Structure for transited encoding */ typedef struct _krb5_transited { krb5_magic magic; krb5_octet tr_type; /**< Transited encoding type */ krb5_data tr_contents; /**< Contents */ } krb5_transited; /** Encrypted part of ticket. */ typedef struct _krb5_enc_tkt_part { krb5_magic magic; /* to-be-encrypted portion */ krb5_flags flags; /**< flags */ krb5_keyblock *session; /**< session key: includes enctype */ krb5_principal client; /**< client name/realm */ krb5_transited transited; /**< list of transited realms */ krb5_ticket_times times; /**< auth, start, end, renew_till */ krb5_address **caddrs; /**< array of ptrs to addresses */ krb5_authdata **authorization_data; /**< auth data */ } krb5_enc_tkt_part; /** * Ticket structure. * * The C representation of the ticket message, with a pointer to the * C representation of the encrypted part. */ typedef struct _krb5_ticket { krb5_magic magic; /* cleartext portion */ krb5_principal server; /**< server name/realm */ krb5_enc_data enc_part; /**< encryption type, kvno, encrypted encoding */ krb5_enc_tkt_part *enc_part2; /**< ptr to decrypted version, if available */ } krb5_ticket; /* the unencrypted version */ /** * Ticket authenticator. * * The C representation of an unencrypted authenticator. */ typedef struct _krb5_authenticator { krb5_magic magic; krb5_principal client; /**< client name/realm */ krb5_checksum *checksum; /**< checksum, includes type, optional */ krb5_int32 cusec; /**< client usec portion */ krb5_timestamp ctime; /**< client sec portion */ krb5_keyblock *subkey; /**< true session key, optional */ krb5_ui_4 seq_number; /**< sequence #, optional */ krb5_authdata **authorization_data; /**< authoriazation data */ } krb5_authenticator; /** Ticket authentication data. */ typedef struct _krb5_tkt_authent { krb5_magic magic; krb5_ticket *ticket; krb5_authenticator *authenticator; krb5_flags ap_options; } krb5_tkt_authent; /** Credentials structure including ticket, session key, and lifetime info. */ typedef struct _krb5_creds { krb5_magic magic; krb5_principal client; /**< client's principal identifier */ krb5_principal server; /**< server's principal identifier */ krb5_keyblock keyblock; /**< session encryption key info */ krb5_ticket_times times; /**< lifetime info */ krb5_boolean is_skey; /**< true if ticket is encrypted in another ticket's skey */ krb5_flags ticket_flags; /**< flags in ticket */ krb5_address **addresses; /**< addrs in ticket */ krb5_data ticket; /**< ticket string itself */ krb5_data second_ticket; /**< second ticket, if related to ticket (via DUPLICATE-SKEY or ENC-TKT-IN-SKEY) */ krb5_authdata **authdata; /**< authorization data */ } krb5_creds; /** Last request entry */ typedef struct _krb5_last_req_entry { krb5_magic magic; krb5_int32 lr_type; /**< LR type */ krb5_timestamp value; /**< Timestamp */ } krb5_last_req_entry; /** Pre-authentication data */ typedef struct _krb5_pa_data { krb5_magic magic; krb5_preauthtype pa_type; /**< Preauthentication data type */ unsigned int length; /**< Length of data */ krb5_octet *contents; /**< Data */ } krb5_pa_data; /* Don't use this; use krb5_pa_data instead. */ typedef struct _krb5_typed_data { krb5_magic magic; krb5_int32 type; unsigned int length; krb5_octet *data; } krb5_typed_data; /** C representation of KDC-REQ protocol message, including KDC-REQ-BODY */ typedef struct _krb5_kdc_req { krb5_magic magic; krb5_msgtype msg_type; /**< KRB5_AS_REQ or KRB5_TGS_REQ */ krb5_pa_data **padata; /**< Preauthentication data */ /* real body */ krb5_flags kdc_options; /**< Requested options */ krb5_principal client; /**< Client principal and realm */ krb5_principal server; /**< Server principal and realm */ krb5_timestamp from; /**< Requested start time */ krb5_timestamp till; /**< Requested end time */ krb5_timestamp rtime; /**< Requested renewable end time */ krb5_int32 nonce; /**< Nonce to match request and response */ int nktypes; /**< Number of enctypes */ krb5_enctype *ktype; /**< Requested enctypes */ krb5_address **addresses; /**< Requested addresses (optional) */ krb5_enc_data authorization_data; /**< Encrypted authz data (optional) */ krb5_authdata **unenc_authdata; /**< Unencrypted authz data */ krb5_ticket **second_ticket; /**< Second ticket array (optional) */ } krb5_kdc_req; /** * C representation of @c EncKDCRepPart protocol message. * * This is the cleartext message that is encrypted and inserted in @c KDC-REP. */ typedef struct _krb5_enc_kdc_rep_part { krb5_magic magic; /* encrypted part: */ krb5_msgtype msg_type; /**< krb5 message type */ krb5_keyblock *session; /**< Session key */ krb5_last_req_entry **last_req; /**< Array of pointers to entries */ krb5_int32 nonce; /**< Nonce from request */ krb5_timestamp key_exp; /**< Expiration date */ krb5_flags flags; /**< Ticket flags */ krb5_ticket_times times; /**< Lifetime info */ krb5_principal server; /**< Server's principal identifier */ krb5_address **caddrs; /**< Array of ptrs to addrs, optional */ krb5_pa_data **enc_padata; /**< Encrypted preauthentication data */ } krb5_enc_kdc_rep_part; /** Representation of the @c KDC-REP protocol message. */ typedef struct _krb5_kdc_rep { krb5_magic magic; /* cleartext part: */ krb5_msgtype msg_type; /**< KRB5_AS_REP or KRB5_KDC_REP */ krb5_pa_data **padata; /**< Preauthentication data from KDC */ krb5_principal client; /**< Client principal and realm */ krb5_ticket *ticket; /**< Ticket */ krb5_enc_data enc_part; /**< Encrypted part of reply */ krb5_enc_kdc_rep_part *enc_part2; /**< Unencrypted version, if available */ } krb5_kdc_rep; /** Error message structure */ typedef struct _krb5_error { krb5_magic magic; /* some of these may be meaningless in certain contexts */ krb5_timestamp ctime; /**< Client sec portion; optional */ krb5_int32 cusec; /**< Client usec portion; optional */ krb5_int32 susec; /**< Server usec portion */ krb5_timestamp stime; /**< Server sec portion */ krb5_ui_4 error; /**< Error code (protocol error #'s) */ krb5_principal client; /**< Client principal and realm */ krb5_principal server; /**< Server principal and realm */ krb5_data text; /**< Descriptive text */ krb5_data e_data; /**< Additional error-describing data */ } krb5_error; /** Authentication header. */ typedef struct _krb5_ap_req { krb5_magic magic; krb5_flags ap_options; /**< Requested options */ krb5_ticket *ticket; /**< Ticket */ krb5_enc_data authenticator; /**< Encrypted authenticator */ } krb5_ap_req; /** * C representaton of AP-REP message. * * The server's response to a client's request for mutual authentication. */ typedef struct _krb5_ap_rep { krb5_magic magic; krb5_enc_data enc_part; /**< Ciphertext of ApRepEncPart */ } krb5_ap_rep; /** Cleartext that is encrypted and put into @c _krb5_ap_rep. */ typedef struct _krb5_ap_rep_enc_part { krb5_magic magic; krb5_timestamp ctime; /**< Client time, seconds portion */ krb5_int32 cusec; /**< Client time, microseconds portion */ krb5_keyblock *subkey; /**< Subkey (optional) */ krb5_ui_4 seq_number; /**< Sequence number */ } krb5_ap_rep_enc_part; /* Unused */ typedef struct _krb5_response { krb5_magic magic; krb5_octet message_type; krb5_data response; krb5_int32 expected_nonce; krb5_timestamp request_time; } krb5_response; /** Credentials information inserted into @c EncKrbCredPart. */ typedef struct _krb5_cred_info { krb5_magic magic; krb5_keyblock *session; /**< Session key used to encrypt ticket */ krb5_principal client; /**< Client principal and realm */ krb5_principal server; /**< Server principal and realm */ krb5_flags flags; /**< Ticket flags */ krb5_ticket_times times; /**< Auth, start, end, renew_till */ krb5_address **caddrs; /**< Array of pointers to addrs (optional) */ } krb5_cred_info; /** Cleartext credentials information. */ typedef struct _krb5_cred_enc_part { krb5_magic magic; krb5_int32 nonce; /**< Nonce (optional) */ krb5_timestamp timestamp; /**< Generation time, seconds portion */ krb5_int32 usec; /**< Generation time, microseconds portion */ krb5_address *s_address; /**< Sender address (optional) */ krb5_address *r_address; /**< Recipient address (optional) */ krb5_cred_info **ticket_info; } krb5_cred_enc_part; /** Credentials data structure.*/ typedef struct _krb5_cred { krb5_magic magic; krb5_ticket **tickets; /**< Tickets */ krb5_enc_data enc_part; /**< Encrypted part */ krb5_cred_enc_part *enc_part2; /**< Unencrypted version, if available */ } krb5_cred; /* Unused, but here for API compatibility. */ typedef struct _passwd_phrase_element { krb5_magic magic; krb5_data *passwd; krb5_data *phrase; } passwd_phrase_element; /* Unused, but here for API compatibility. */ typedef struct _krb5_pwd_data { krb5_magic magic; int sequence_count; passwd_phrase_element **element; } krb5_pwd_data; /* Unused, but here for API compatibility. */ typedef struct _krb5_pa_svr_referral_data { /** Referred name, only realm is required */ krb5_principal principal; } krb5_pa_svr_referral_data; /* Unused, but here for API compatibility. */ typedef struct _krb5_pa_server_referral_data { krb5_data *referred_realm; krb5_principal true_principal_name; krb5_principal requested_principal_name; krb5_timestamp referral_valid_until; krb5_checksum rep_cksum; } krb5_pa_server_referral_data; typedef struct _krb5_pa_pac_req { /** TRUE if a PAC should be included in TGS-REP */ krb5_boolean include_pac; } krb5_pa_pac_req; /* * begin "safepriv.h" */ /** @defgroup KRB5_AUTH_CONTEXT KRB5_AUTH_CONTEXT * @{ */ /** Prevent replays with timestamps and replay cache. */ #define KRB5_AUTH_CONTEXT_DO_TIME 0x00000001 /** Save timestamps for application. */ #define KRB5_AUTH_CONTEXT_RET_TIME 0x00000002 /** Prevent replays with sequence numbers. */ #define KRB5_AUTH_CONTEXT_DO_SEQUENCE 0x00000004 /** Save sequence numbers for application. */ #define KRB5_AUTH_CONTEXT_RET_SEQUENCE 0x00000008 #define KRB5_AUTH_CONTEXT_PERMIT_ALL 0x00000010 #define KRB5_AUTH_CONTEXT_USE_SUBKEY 0x00000020 /** @} */ /* end of KRB5_AUTH_CONTEXT group */ /** * Replay data. * * Sequence number and timestamp information output by krb5_rd_priv() and * krb5_rd_safe(). */ typedef struct krb5_replay_data { krb5_timestamp timestamp; /**< Timestamp, seconds portion */ krb5_int32 usec; /**< Timestamp, microseconds portion */ krb5_ui_4 seq; /**< Sequence number */ } krb5_replay_data; /* Flags for krb5_auth_con_genaddrs(). */ /** Generate the local network address. */ #define KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR 0x00000001 /** Generate the remote network address. */ #define KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR 0x00000002 /** Generate the local network address and the local port. */ #define KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR 0x00000004 /** Generate the remote network address and the remote port. */ #define KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR 0x00000008 /** Type of function used as a callback to generate checksum data for mk_req */ typedef krb5_error_code (KRB5_CALLCONV * krb5_mk_req_checksum_func)(krb5_context, krb5_auth_context, void *, krb5_data **); /* * end "safepriv.h" */ /* * begin "ccache.h" */ /** Cursor for sequential lookup */ typedef krb5_pointer krb5_cc_cursor; struct _krb5_ccache; typedef struct _krb5_ccache *krb5_ccache; struct _krb5_cc_ops; typedef struct _krb5_cc_ops krb5_cc_ops; struct _krb5_cccol_cursor; /** Cursor for iterating over all ccaches */ typedef struct _krb5_cccol_cursor *krb5_cccol_cursor; /* Flags for krb5_cc_retrieve_cred. */ /** The requested lifetime must be at least as great as the time specified. */ #define KRB5_TC_MATCH_TIMES 0x00000001 /** The is_skey field must match exactly. */ #define KRB5_TC_MATCH_IS_SKEY 0x00000002 /** All the flags set in the match credentials must be set. */ #define KRB5_TC_MATCH_FLAGS 0x00000004 /** All the time fields must match exactly. */ #define KRB5_TC_MATCH_TIMES_EXACT 0x00000008 /** All the flags must match exactly. */ #define KRB5_TC_MATCH_FLAGS_EXACT 0x00000010 /** The authorization data must match. */ #define KRB5_TC_MATCH_AUTHDATA 0x00000020 /** Only the name portion of the principal name must match. */ #define KRB5_TC_MATCH_SRV_NAMEONLY 0x00000040 /** The second ticket must match. */ #define KRB5_TC_MATCH_2ND_TKT 0x00000080 /** The encryption key type must match. */ #define KRB5_TC_MATCH_KTYPE 0x00000100 /** The supported key types must match. */ #define KRB5_TC_SUPPORTED_KTYPES 0x00000200 /* Flags for krb5_cc_set_flags and similar. */ /** Open and close the file for each cache operation. */ #define KRB5_TC_OPENCLOSE 0x00000001 /**< @deprecated has no effect */ #define KRB5_TC_NOTICKET 0x00000002 /** * Retrieve the name, but not type of a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * * @warning Returns the name of the credential cache. The result is an alias * into @a cache and should not be freed or modified by the caller. This name * does not include the cache type, so should not be used as input to * krb5_cc_resolve(). * * @return * On success - the name of the credential cache. */ const char * KRB5_CALLCONV krb5_cc_get_name(krb5_context context, krb5_ccache cache); /** * Retrieve the full name of a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [out] fullname_out Full name of cache * * Use krb5_free_string() to free @a fullname_out when it is no longer needed. * * @version New in 1.10 */ krb5_error_code KRB5_CALLCONV krb5_cc_get_full_name(krb5_context context, krb5_ccache cache, char **fullname_out); #if KRB5_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_cc_gen_new(krb5_context context, krb5_ccache *cache); #endif /* KRB5_DEPRECATED */ /** * Initialize a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] principal Default principal name * * Destroy any existing contents of @a cache and initialize it for the default * principal @a principal. * * @retval * 0 Success * @return * System errors; Permission errors; Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_initialize(krb5_context context, krb5_ccache cache, krb5_principal principal); /** * Destroy a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * * This function destroys any existing contents of @a cache and closes the * handle to it. * * @retval * 0 Success * @return * Permission errors */ krb5_error_code KRB5_CALLCONV krb5_cc_destroy(krb5_context context, krb5_ccache cache); /** * Close a credential cache handle. * * @param [in] context Library context * @param [in] cache Credential cache handle * * This function closes a credential cache handle @a cache without affecting * the contents of the cache. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_close(krb5_context context, krb5_ccache cache); /** * Store credentials in a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] creds Credentials to be stored in cache * * This function stores @a creds into @a cache. If @a creds->server and the * server in the decoded ticket @a creds->ticket differ, the credentials will * be stored under both server principal names. * * @retval * 0 Success * @return Permission errors; storage failure errors; Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_store_cred(krb5_context context, krb5_ccache cache, krb5_creds *creds); /** * Retrieve a specified credentials from a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] flags Flags bit mask * @param [in] mcreds Credentials to match * @param [out] creds Credentials matching the requested value * * This function searches a credential cache for credentials matching @a mcreds * and returns it if found. * * Valid values for @a flags are: * * @li #KRB5_TC_MATCH_TIMES The requested lifetime must be at least as * great as in @a mcreds . * @li #KRB5_TC_MATCH_IS_SKEY The @a is_skey field much match exactly. * @li #KRB5_TC_MATCH_FLAGS Flags set in @a mcreds must be set. * @li #KRB5_TC_MATCH_TIMES_EXACT The requested lifetime must match exactly. * @li #KRB5_TC_MATCH_FLAGS_EXACT Flags must match exactly. * @li #KRB5_TC_MATCH_AUTHDATA The authorization data must match. * @li #KRB5_TC_MATCH_SRV_NAMEONLY Only the name portion of the principal * name must match, not the realm. * @li #KRB5_TC_MATCH_2ND_TKT The second tickets must match. * @li #KRB5_TC_MATCH_KTYPE The encryption key types must match. * @li #KRB5_TC_SUPPORTED_KTYPES Check all matching entries that have any * supported encryption type and return the * one with the encryption type listed earliest. * * Use krb5_free_cred_contents() to free @a creds when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_retrieve_cred(krb5_context context, krb5_ccache cache, krb5_flags flags, krb5_creds *mcreds, krb5_creds *creds); /** * Get the default principal of a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [out] principal Primary principal * * Returns the default client principal of a credential cache as set by * krb5_cc_initialize(). * * Use krb5_free_principal() to free @a principal when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_get_principal(krb5_context context, krb5_ccache cache, krb5_principal *principal); /** * Prepare to sequentially read every credential in a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [out] cursor Cursor * * krb5_cc_end_seq_get() must be called to complete the retrieve operation. * * @note If the cache represented by @a cache is modified between the time of * the call to this function and the time of the final krb5_cc_end_seq_get(), * these changes may not be reflected in the results of krb5_cc_next_cred() * calls. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_start_seq_get(krb5_context context, krb5_ccache cache, krb5_cc_cursor *cursor); /** * Retrieve the next entry from the credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] cursor Cursor * @param [out] creds Next credential cache entry * * This function fills in @a creds with the next entry in @a cache and advances * @a cursor. * * Use krb5_free_cred_contents() to free @a creds when it is no longer needed. * * @sa krb5_cc_start_seq_get(), krb5_end_seq_get() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_next_cred(krb5_context context, krb5_ccache cache, krb5_cc_cursor *cursor, krb5_creds *creds); /** * Finish a series of sequential processing credential cache entries. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] cursor Cursor * * This function finishes processing credential cache entries and invalidates * @a cursor. * * @sa krb5_cc_start_seq_get(), krb5_cc_next_cred() * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_cc_end_seq_get(krb5_context context, krb5_ccache cache, krb5_cc_cursor *cursor); /** * Remove credentials from a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] flags Bitwise-ORed search flags * @param [in] creds Credentials to be matched * * @warning This function is not implemented for some cache types. * * This function accepts the same flag values as krb5_cc_retrieve_cred(). * * @retval KRB5_CC_NOSUPP Not implemented for this cache type * @return No matches found; Data cannot be deleted; Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_remove_cred(krb5_context context, krb5_ccache cache, krb5_flags flags, krb5_creds *creds); /** * Set options flags on a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [in] flags Flag bit mask * * This function resets @a cache flags to @a flags. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_set_flags(krb5_context context, krb5_ccache cache, krb5_flags flags); /** * Retrieve flags from a credential cache structure. * * @param [in] context Library context * @param [in] cache Credential cache handle * @param [out] flags Flag bit mask * * @warning For memory credential cache always returns a flag mask of 0. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_get_flags(krb5_context context, krb5_ccache cache, krb5_flags *flags); /** * Retrieve the type of a credential cache. * * @param [in] context Library context * @param [in] cache Credential cache handle * * @return The type of a credential cache as an alias that must not be modified * or freed by the caller. */ const char * KRB5_CALLCONV krb5_cc_get_type(krb5_context context, krb5_ccache cache); /** * Move a credential cache. * * @param [in] context Library context * @param [in] src The credential cache to move the content from * @param [in] dst The credential cache to move the content to * * This function reinitializes @a dst and populates it with the credentials and * default principal of @a src; then, if successful, destroys @a src. * * @retval * 0 Success; @a src is closed. * @return * Kerberos error codes; @a src is still allocated. */ krb5_error_code KRB5_CALLCONV krb5_cc_move(krb5_context context, krb5_ccache src, krb5_ccache dst); /** * Prepare to iterate over the collection of known credential caches. * * @param [in] context Library context * @param [out] cursor Cursor * * Get a new cache iteration @a cursor that will iterate over all known * credential caches independent of type. * * Use krb5_cccol_cursor_free() to release @a cursor when it is no longer * needed. * * @sa krb5_cccol_cursor_next() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cccol_cursor_new(krb5_context context, krb5_cccol_cursor *cursor); /** * Get the next credential cache in the collection. * * @param [in] context Library context * @param [in] cursor Cursor * @param [out] ccache Credential cache handle * * @note When all caches are iterated over and the end of the list is reached, * @a ccache is set to NULL. * * Use krb5_cc_close() to close @a ccache when it is no longer needed. * * @sa krb5_cccol_cursor_new(), krb5_cccol_cursor_free() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cccol_cursor_next(krb5_context context, krb5_cccol_cursor cursor, krb5_ccache *ccache); /** * Free a credential cache collection cursor. * * @param [in] context Library context * @param [in] cursor Cursor * * @sa krb5_cccol_cursor_new(), krb5_cccol_cursor_next() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cccol_cursor_free(krb5_context context, krb5_cccol_cursor *cursor); /** * Check if the credential cache collection contains any credentials. * * @param [in] context Library context * * @version New in 1.11 * * @retval 0 Credentials are available in the collection * @retval KRB5_CC_NOTFOUND The collection contains no credentials */ krb5_error_code KRB5_CALLCONV krb5_cccol_have_content(krb5_context context); /** * Create a new credential cache of the specified type with a unique name. * * @param [in] context Library context * @param [in] type Credential cache type name * @param [in] hint Unused * @param [out] id Credential cache handle * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_new_unique(krb5_context context, const char *type, const char *hint, krb5_ccache *id); /* * end "ccache.h" */ /* * begin "rcache.h" */ struct krb5_rc_st; typedef struct krb5_rc_st *krb5_rcache; /* * end "rcache.h" */ /* * begin "keytab.h" */ /* XXX */ #define MAX_KEYTAB_NAME_LEN 1100 /**< Long enough for MAXPATHLEN + some extra */ typedef krb5_pointer krb5_kt_cursor; /** A key table entry. */ typedef struct krb5_keytab_entry_st { krb5_magic magic; krb5_principal principal; /**< Principal of this key */ krb5_timestamp timestamp; /**< Time entry written to keytable */ krb5_kvno vno; /**< Key version number */ krb5_keyblock key; /**< The secret key */ } krb5_keytab_entry; struct _krb5_kt; typedef struct _krb5_kt *krb5_keytab; /** * Return the type of a key table. * * @param [in] context Library context * @param [in] keytab Key table handle * * @return The type of a key table as an alias that must not be modified or * freed by the caller. */ const char * KRB5_CALLCONV krb5_kt_get_type(krb5_context context, krb5_keytab keytab); /** * Get a key table name. * * @param [in] context Library context * @param [in] keytab Key table handle * @param [out] name Key table name * @param [in] namelen Maximum length to fill in name * * Fill @a name with the name of @a keytab including the type and delimiter. * * @sa MAX_KEYTAB_NAME_LEN * * @retval * 0 Success * @retval * KRB5_KT_NAME_TOOLONG Key table name does not fit in @a namelen bytes * * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_get_name(krb5_context context, krb5_keytab keytab, char *name, unsigned int namelen); /** * Close a key table handle. * * @param [in] context Library context * @param [in] keytab Key table handle * * @retval 0 */ krb5_error_code KRB5_CALLCONV krb5_kt_close(krb5_context context, krb5_keytab keytab); /** * Get an entry from a key table. * * @param [in] context Library context * @param [in] keytab Key table handle * @param [in] principal Principal name * @param [in] vno Key version number (0 for highest available) * @param [in] enctype Encryption type (0 zero for any enctype) * @param [out] entry Returned entry from key table * * Retrieve an entry from a key table which matches the @a keytab, @a * principal, @a vno, and @a enctype. If @a vno is zero, retrieve the * highest-numbered kvno matching the other fields. If @a enctype is 0, match * any enctype. * * Use krb5_free_keytab_entry_contents() to free @a entry when it is no longer * needed. * * @note If @a vno is zero, the function retrieves the highest-numbered-kvno * entry that matches the specified principal. * * @retval * 0 Success * @retval * Kerberos error codes on failure */ krb5_error_code KRB5_CALLCONV krb5_kt_get_entry(krb5_context context, krb5_keytab keytab, krb5_const_principal principal, krb5_kvno vno, krb5_enctype enctype, krb5_keytab_entry *entry); /** * Start a sequential retrieval of key table entries. * * @param [in] context Library context * @param [in] keytab Key table handle * @param [out] cursor Cursor * * Prepare to read sequentially every key in the specified key table. Use * krb5_kt_end_seq_get() to release the cursor when it is no longer needed. * * @sa krb5_kt_next_entry(), krb5_kt_end_seq_get() * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_start_seq_get(krb5_context context, krb5_keytab keytab, krb5_kt_cursor *cursor); /** * Retrieve the next entry from the key table. * * @param [in] context Library context * @param [in] keytab Key table handle * @param [out] entry Returned key table entry * @param [in] cursor Key table cursor * * Return the next sequential entry in @a keytab and advance @a cursor. * Callers must release the returned entry with krb5_kt_free_entry(). * * @sa krb5_kt_start_seq_get(), krb5_kt_end_seq_get() * * @retval * 0 Success * @retval * KRB5_KT_END - if the last entry was reached * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_next_entry(krb5_context context, krb5_keytab keytab, krb5_keytab_entry *entry, krb5_kt_cursor *cursor); /** * Release a keytab cursor. * * @param [in] context Library context * @param [in] keytab Key table handle * @param [out] cursor Cursor * * This function should be called to release the cursor created by * krb5_kt_start_seq_get(). * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_end_seq_get(krb5_context context, krb5_keytab keytab, krb5_kt_cursor *cursor); /** * Check if a keytab exists and contains entries. * * @param [in] context Library context * @param [in] keytab Key table handle * * @version New in 1.11 * * @retval 0 Keytab exists and contains entries * @retval KRB5_KT_NOTFOUND Keytab does not contain entries */ krb5_error_code KRB5_CALLCONV krb5_kt_have_content(krb5_context context, krb5_keytab keytab); /* * end "keytab.h" */ /* * begin "func-proto.h" */ #define KRB5_INIT_CONTEXT_SECURE 0x1 /**< Use secure context configuration */ #define KRB5_INIT_CONTEXT_KDC 0x2 /**< Use KDC configuration if available */ /** * Create a krb5 library context. * * @param [out] context Library context * * The @a context must be released by calling krb5_free_context() when * it is no longer needed. * * @warning Any program or module that needs the Kerberos code to not trust the * environment must use krb5_init_secure_context(), or clean out the * environment. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_context(krb5_context *context); /** * Create a krb5 library context using only configuration files. * * @param [out] context Library context * * Create a context structure, using only system configuration files. All * information passed through the environment variables is ignored. * * The @a context must be released by calling krb5_free_context() when * it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_secure_context(krb5_context *context); /** * Create a krb5 library context using a specified profile. * * @param [in] profile Profile object (NULL to create default profile) * @param [in] flags Context initialization flags * @param [out] context Library context * * Create a context structure, optionally using a specified profile and * initialization flags. If @a profile is NULL, the default profile will be * created from config files. If @a profile is non-null, a copy of it will be * made for the new context; the caller should still clean up its copy. Valid * flag values are: * * @li #KRB5_INIT_CONTEXT_SECURE Ignore environment variables * @li #KRB5_INIT_CONTEXT_KDC Use KDC configuration if creating profile */ krb5_error_code KRB5_CALLCONV krb5_init_context_profile(struct _profile_t *profile, krb5_flags flags, krb5_context *context); /** * Free a krb5 library context. * * @param [in] context Library context * * This function frees a @a context that was created by krb5_init_context() * or krb5_init_secure_context(). */ void KRB5_CALLCONV krb5_free_context(krb5_context context); /** * Copy a krb5_context structure. * * @param [in] ctx Library context * @param [out] nctx_out New context structure * * The newly created context must be released by calling krb5_free_context() * when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_context(krb5_context ctx, krb5_context *nctx_out); /** * Set default TGS encryption types in a krb5_context structure. * * @param [in] context Library context * @param [in] etypes Encryption type(s) to set * * This function sets the default enctype list for TGS requests * made using @a context to @a etypes. * * @note This overrides the default list (from config file or built-in). * * @retval * 0 Success * @retval * KRB5_PROG_ETYPE_NOSUPP Program lacks support for encryption type * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_set_default_tgs_enctypes(krb5_context context, const krb5_enctype *etypes); /** * Return a list of encryption types permitted for session keys. * * @param [in] context Library context * @param [out] ktypes Zero-terminated list of encryption types * * This function returns the list of encryption types permitted for session * keys within @a context, as determined by configuration or by a previous call * to krb5_set_default_tgs_enctypes(). * * Use krb5_free_enctypes() to free @a ktypes when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_permitted_enctypes(krb5_context context, krb5_enctype **ktypes); /** * Test whether the Kerberos library was built with multithread support. * * @retval * TRUE if the library is threadsafe; FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_is_thread_safe(void); /* libkrb.spec */ /** * Decrypt a ticket using the specified key table. * * @param [in] context Library context * @param [in] kt Key table * @param [in] ticket Ticket to be decrypted * * This function takes a @a ticket as input and decrypts it using * key data from @a kt. The result is placed into @a ticket->enc_part2. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_server_decrypt_ticket_keytab(krb5_context context, const krb5_keytab kt, krb5_ticket *ticket); /** * Free an array of credential structures. * * @param [in] context Library context * @param [in] tgts Null-terminated array of credentials to free * * @note The last entry in the array @a tgts must be a NULL pointer. */ void KRB5_CALLCONV krb5_free_tgt_creds(krb5_context context, krb5_creds **tgts); /** @defgroup KRB5_GC KRB5_GC * @{ */ #define KRB5_GC_USER_USER 1 /**< Want user-user ticket */ #define KRB5_GC_CACHED 2 /**< Want cached ticket only */ #define KRB5_GC_CANONICALIZE 4 /**< Set canonicalize KDC option */ #define KRB5_GC_NO_STORE 8 /**< Do not store in credential cache */ #define KRB5_GC_FORWARDABLE 16 /**< Acquire forwardable tickets */ #define KRB5_GC_NO_TRANSIT_CHECK 32 /**< Disable transited check */ #define KRB5_GC_CONSTRAINED_DELEGATION 64 /**< Constrained delegation */ /** @} */ /* end of KRB5_GC group */ /** * Get an additional ticket. * * @param [in] context Library context * @param [in] options Options * @param [in] ccache Credential cache handle * @param [in] in_creds Input credentials * @param [out] out_creds Output updated credentials * * Use @a ccache or a TGS exchange to get a service ticket matching @a * in_creds. * * Valid values for @a options are: * @li #KRB5_GC_CACHED Search only credential cache for the ticket * @li #KRB5_GC_USER_USER Return a user to user authentication ticket * * @a in_creds must be non-null. @a in_creds->client and @a in_creds->server * must be filled in to specify the client and the server respectively. If any * authorization data needs to be requested for the service ticket (such as * restrictions on how the ticket can be used), specify it in @a * in_creds->authdata; otherwise set @a in_creds->authdata to NULL. The * session key type is specified in @a in_creds->keyblock.enctype, if it is * nonzero. * * The expiration date is specified in @a in_creds->times.endtime. * The KDC may return tickets with an earlier expiration date. * If @a in_creds->times.endtime is set to 0, the latest possible * expiration date will be requested. * * Any returned ticket and intermediate ticket-granting tickets are stored * in @a ccache. * * Use krb5_free_creds() to free @a out_creds when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_credentials(krb5_context context, krb5_flags options, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds); /** * Serialize a @c krb5_creds object. * * @param [in] context Library context * @param [in] creds The credentials object to serialize * @param [out] data_out The serialized credentials * * Serialize @a creds in the format used by the FILE ccache format (vesion 4) * and KCM ccache protocol. * * Use krb5_free_data() to free @a data_out when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_marshal_credentials(krb5_context context, krb5_creds *in_creds, krb5_data **data_out); /** * Deserialize a @c krb5_creds object. * * @param [in] context Library context * @param [in] data The serialized credentials * @param [out] creds_out The resulting creds object * * Deserialize @a data to credentials in the format used by the FILE ccache * format (vesion 4) and KCM ccache protocol. * * Use krb5_free_creds() to free @a creds_out when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_unmarshal_credentials(krb5_context context, const krb5_data *data, krb5_creds **creds_out); /** @deprecated Replaced by krb5_get_validated_creds. */ krb5_error_code KRB5_CALLCONV krb5_get_credentials_validate(krb5_context context, krb5_flags options, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds); /** @deprecated Replaced by krb5_get_renewed_creds. */ krb5_error_code KRB5_CALLCONV krb5_get_credentials_renew(krb5_context context, krb5_flags options, krb5_ccache ccache, krb5_creds *in_creds, krb5_creds **out_creds); /** * Create a @c KRB_AP_REQ message. * * @param [in] context Library context * @param [in,out] auth_context Pre-existing or newly created auth context * @param [in] ap_req_options @ref AP_OPTS options * @param [in] service Service name, or NULL to use @c "host" * @param [in] hostname Host name, or NULL to use local hostname * @param [in] in_data Application data to be checksummed in the * authenticator, or NULL * @param [in] ccache Credential cache used to obtain credentials * for the desired service. * @param [out] outbuf @c AP-REQ message * * This function is similar to krb5_mk_req_extended() except that it uses a * given @a hostname, @a service, and @a ccache to construct a service * principal name and obtain credentials. * * Use krb5_free_data_contents() to free @a outbuf when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_req(krb5_context context, krb5_auth_context *auth_context, krb5_flags ap_req_options, const char *service, const char *hostname, krb5_data *in_data, krb5_ccache ccache, krb5_data *outbuf); /** * Create a @c KRB_AP_REQ message using supplied credentials. * * @param [in] context Library context * @param [in,out] auth_context Pre-existing or newly created auth context * @param [in] ap_req_options @ref AP_OPTS options * @param [in] in_data Application data to be checksummed in the * authenticator, or NULL * @param [in] in_creds Credentials for the service with valid ticket * and key * @param [out] outbuf @c AP-REQ message * * Valid @a ap_req_options are: * @li #AP_OPTS_USE_SESSION_KEY - Use the session key when creating the * request used for user to user * authentication. * @li #AP_OPTS_MUTUAL_REQUIRED - Request a mutual authentication packet from * the receiver. * @li #AP_OPTS_USE_SUBKEY - Generate a subsession key from the current * session key obtained from the credentials. * * This function creates a KRB_AP_REQ message using supplied credentials @a * in_creds. @a auth_context may point to an existing auth context or to NULL, * in which case a new one will be created. If @a in_data is non-null, a * checksum of it will be included in the authenticator contained in the * KRB_AP_REQ message. Use krb5_free_data_contents() to free @a outbuf when it * is no longer needed. * * On successful return, the authenticator is stored in @a auth_context with * the @a client and @a checksum fields nulled out. (This is to prevent * pointer-sharing problems; the caller should not need these fields anyway, * since the caller supplied them.) * * @sa krb5_mk_req() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_req_extended(krb5_context context, krb5_auth_context *auth_context, krb5_flags ap_req_options, krb5_data *in_data, krb5_creds *in_creds, krb5_data *outbuf); /** * Format and encrypt a @c KRB_AP_REP message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] outbuf @c AP-REP message * * This function fills in @a outbuf with an AP-REP message using information * from @a auth_context. * * If the flags in @a auth_context indicate that a sequence number should be * used (either #KRB5_AUTH_CONTEXT_DO_SEQUENCE or * #KRB5_AUTH_CONTEXT_RET_SEQUENCE) and the local sequence number in @a * auth_context is 0, a new number will be generated with * krb5_generate_seq_number(). * * Use krb5_free_data_contents() to free @a outbuf when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_rep(krb5_context context, krb5_auth_context auth_context, krb5_data *outbuf); /** * Format and encrypt a @c KRB_AP_REP message for DCE RPC. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] outbuf @c AP-REP message * * Use krb5_free_data_contents() to free @a outbuf when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_rep_dce(krb5_context context, krb5_auth_context auth_context, krb5_data *outbuf); /** * Parse and decrypt a @c KRB_AP_REP message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] inbuf AP-REP message * @param [out] repl Decrypted reply message * * This function parses, decrypts and verifies a message from @a inbuf and * fills in @a repl with a pointer to allocated memory containing the fields * from the encrypted response. * * Use krb5_free_ap_rep_enc_part() to free @a repl when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_rep(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_ap_rep_enc_part **repl); /** * Parse and decrypt a @c KRB_AP_REP message for DCE RPC. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] inbuf AP-REP message * @param [out] nonce Sequence number from the decrypted reply * * This function parses, decrypts and verifies a message from @a inbuf and * fills in @a nonce with a decrypted reply sequence number. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_rep_dce(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_ui_4 *nonce); /** * Format and encode a @c KRB_ERROR message. * * @param [in] context Library context * @param [in] dec_err Error structure to be encoded * @param [out] enc_err Encoded error structure * * This function creates a @c KRB_ERROR message in @a enc_err. Use * krb5_free_data_contents() to free @a enc_err when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_error(krb5_context context, const krb5_error *dec_err, krb5_data *enc_err); /** * Decode a @c KRB-ERROR message. * * @param [in] context Library context * @param [in] enc_errbuf Encoded error message * @param [out] dec_error Decoded error message * * This function processes @c KRB-ERROR message @a enc_errbuf and returns * an allocated structure @a dec_error containing the error message. * Use krb5_free_error() to free @a dec_error when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_error(krb5_context context, const krb5_data *enc_errbuf, krb5_error **dec_error); /** * Process @c KRB-SAFE message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] inbuf @c KRB-SAFE message to be parsed * @param [out] userdata_out Data parsed from @c KRB-SAFE message * @param [out] rdata_out Replay data. Specify NULL if not needed * * This function parses a @c KRB-SAFE message, verifies its integrity, and * stores its data into @a userdata_out. * * @note The @a rdata_out argument is required if the * #KRB5_AUTH_CONTEXT_RET_TIME or #KRB5_AUTH_CONTEXT_RET_SEQUENCE flag is set * in @a auth_context. * * If @a auth_context has a remote address set, the address will be used to * verify the sender address in the KRB-SAFE message. If @a auth_context has a * local address set, it will be used to verify the receiver address in the * KRB-SAFE message if the message contains one. * * If the #KRB5_AUTH_CONTEXT_DO_SEQUENCE flag is set in @a auth_context, the * sequence number of the KRB-SAFE message is checked against the remote * sequence number field of @a auth_context. Otherwise, the sequence number is * not used. * * If the #KRB5_AUTH_CONTEXT_DO_TIME flag is set in @a auth_context, then the * timestamp in the message is verified to be within the permitted clock skew * of the current time, and the message is checked against an in-memory replay * cache to detect reflections or replays. * * Use krb5_free_data_contents() to free @a userdata_out when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_safe(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_data *userdata_out, krb5_replay_data *rdata_out); /** * Process a @c KRB-PRIV message. * * @param [in] context Library context * @param [in] auth_context Authentication structure * @param [in] inbuf @c KRB-PRIV message to be parsed * @param [out] userdata_out Data parsed from @c KRB-PRIV message * @param [out] rdata_out Replay data. Specify NULL if not needed * * This function parses a @c KRB-PRIV message, verifies its integrity, and * stores its unencrypted data into @a userdata_out. * * @note The @a rdata_out argument is required if the * #KRB5_AUTH_CONTEXT_RET_TIME or #KRB5_AUTH_CONTEXT_RET_SEQUENCE flag is set * in @a auth_context. * * If @a auth_context has a remote address set, the address will be used to * verify the sender address in the KRB-PRIV message. If @a auth_context has a * local address set, it will be used to verify the receiver address in the * KRB-PRIV message if the message contains one. * * If the #KRB5_AUTH_CONTEXT_DO_SEQUENCE flag is set in @a auth_context, the * sequence number of the KRB-PRIV message is checked against the remote * sequence number field of @a auth_context. Otherwise, the sequence number is * not used. * * If the #KRB5_AUTH_CONTEXT_DO_TIME flag is set in @a auth_context, then the * timestamp in the message is verified to be within the permitted clock skew * of the current time, and the message is checked against an in-memory replay * cache to detect reflections or replays. * * Use krb5_free_data_contents() to free @a userdata_out when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_priv(krb5_context context, krb5_auth_context auth_context, const krb5_data *inbuf, krb5_data *userdata_out, krb5_replay_data *rdata_out); /** * Convert a string principal name to a krb5_principal structure. * * @param [in] context Library context * @param [in] name String representation of a principal name * @param [out] principal_out New principal * * Convert a string representation of a principal name to a krb5_principal * structure. * * A string representation of a Kerberos name consists of one or more principal * name components, separated by slashes, optionally followed by the \@ * character and a realm name. If the realm name is not specified, the local * realm is used. * * To use the slash and \@ symbols as part of a component (quoted) instead of * using them as a component separator or as a realm prefix), put a backslash * (\) character in front of the symbol. Similarly, newline, tab, backspace, * and NULL characters can be included in a component by using @c n, @c t, @c b * or @c 0, respectively. * * @note The realm in a Kerberos @a name cannot contain slash, colon, * or NULL characters. * * Use krb5_free_principal() to free @a principal_out when it is no longer * needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_parse_name(krb5_context context, const char *name, krb5_principal *principal_out); #define KRB5_PRINCIPAL_PARSE_NO_REALM 0x1 /**< Error if realm is present */ #define KRB5_PRINCIPAL_PARSE_REQUIRE_REALM 0x2 /**< Error if realm is not present */ #define KRB5_PRINCIPAL_PARSE_ENTERPRISE 0x4 /**< Create single-component enterprise principle */ #define KRB5_PRINCIPAL_PARSE_IGNORE_REALM 0x8 /**< Ignore realm if present */ /** * Convert a string principal name to a krb5_principal with flags. * * @param [in] context Library context * @param [in] name String representation of a principal name * @param [in] flags Flag * @param [out] principal_out New principal * * Similar to krb5_parse_name(), this function converts a single-string * representation of a principal name to a krb5_principal structure. * * The following flags are valid: * @li #KRB5_PRINCIPAL_PARSE_NO_REALM - no realm must be present in @a name * @li #KRB5_PRINCIPAL_PARSE_REQUIRE_REALM - realm must be present in @a name * @li #KRB5_PRINCIPAL_PARSE_ENTERPRISE - create single-component enterprise * principal * @li #KRB5_PRINCIPAL_PARSE_IGNORE_REALM - ignore realm if present in @a name * * If @c KRB5_PRINCIPAL_PARSE_NO_REALM or @c KRB5_PRINCIPAL_PARSE_IGNORE_REALM * is specified in @a flags, the realm of the new principal will be empty. * Otherwise, the default realm for @a context will be used if @a name does not * specify a realm. * * Use krb5_free_principal() to free @a principal_out when it is no longer * needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_parse_name_flags(krb5_context context, const char *name, int flags, krb5_principal *principal_out); /** * Convert a krb5_principal structure to a string representation. * * @param [in] context Library context * @param [in] principal Principal * @param [out] name String representation of principal name * * The resulting string representation uses the format and quoting conventions * described for krb5_parse_name(). * * Use krb5_free_unparsed_name() to free @a name when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_unparse_name(krb5_context context, krb5_const_principal principal, char **name); /** * Convert krb5_principal structure to string and length. * * @param [in] context Library context * @param [in] principal Principal * @param [in,out] name String representation of principal name * @param [in,out] size Size of unparsed name * * This function is similar to krb5_unparse_name(), but allows the use of an * existing buffer for the result. If size is not NULL, then @a name must * point to either NULL or an existing buffer of at least the size pointed to * by @a size. The buffer will be allocated or resized if necessary, with the * new pointer stored into @a name. Whether or not the buffer is resized, the * necessary space for the result, including null terminator, will be stored * into @a size. * * If size is NULL, this function behaves exactly as krb5_unparse_name(). * * @retval * 0 Success * @return * Kerberos error codes. On failure @a name is set to NULL */ krb5_error_code KRB5_CALLCONV krb5_unparse_name_ext(krb5_context context, krb5_const_principal principal, char **name, unsigned int *size); #define KRB5_PRINCIPAL_UNPARSE_SHORT 0x1 /**< Omit realm if it is the local realm */ #define KRB5_PRINCIPAL_UNPARSE_NO_REALM 0x2 /**< Omit realm always */ #define KRB5_PRINCIPAL_UNPARSE_DISPLAY 0x4 /**< Don't escape special characters */ /** * Convert krb5_principal structure to a string with flags. * * @param [in] context Library context * @param [in] principal Principal * @param [in] flags Flags * @param [out] name String representation of principal name * * Similar to krb5_unparse_name(), this function converts a krb5_principal * structure to a string representation. * * The following flags are valid: * @li #KRB5_PRINCIPAL_UNPARSE_SHORT - omit realm if it is the local realm * @li #KRB5_PRINCIPAL_UNPARSE_NO_REALM - omit realm * @li #KRB5_PRINCIPAL_UNPARSE_DISPLAY - do not quote special characters * * Use krb5_free_unparsed_name() to free @a name when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes. On failure @a name is set to NULL */ krb5_error_code KRB5_CALLCONV krb5_unparse_name_flags(krb5_context context, krb5_const_principal principal, int flags, char **name); /** * Convert krb5_principal structure to string format with flags. * * @param [in] context Library context * @param [in] principal Principal * @param [in] flags Flags * @param [out] name Single string format of principal name * @param [out] size Size of unparsed name buffer * * @sa krb5_unparse_name() krb5_unparse_name_flags() krb5_unparse_name_ext() * * @retval * 0 Success * @return * Kerberos error codes. On failure @a name is set to NULL */ krb5_error_code KRB5_CALLCONV krb5_unparse_name_flags_ext(krb5_context context, krb5_const_principal principal, int flags, char **name, unsigned int *size); /** * Set the realm field of a principal * * @param [in] context Library context * @param [in] principal Principal name * @param [in] realm Realm name * * Set the realm name part of @a principal to @a realm, overwriting the * previous realm. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_set_principal_realm(krb5_context context, krb5_principal principal, const char *realm); /** * Search a list of addresses for a specified address. * * @param [in] context Library context * @param [in] addr Address to search for * @param [in] addrlist Address list to be searched (or NULL) * * @note If @a addrlist contains only a NetBIOS addresses, it will be treated * as a null list. * * @return * TRUE if @a addr is listed in @a addrlist, or @c addrlist is NULL; FALSE * otherwise */ krb5_boolean KRB5_CALLCONV_WRONG krb5_address_search(krb5_context context, const krb5_address *addr, krb5_address *const *addrlist); /** * Compare two Kerberos addresses. * * @param [in] context Library context * @param [in] addr1 First address to be compared * @param [in] addr2 Second address to be compared * * @return * TRUE if the addresses are the same, FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_address_compare(krb5_context context, const krb5_address *addr1, const krb5_address *addr2); /** * Return an ordering of the specified addresses. * * @param [in] context Library context * @param [in] addr1 First address * @param [in] addr2 Second address * * @retval * 0 The two addresses are the same * @retval * \< 0 First address is less than second * @retval * \> 0 First address is greater than second */ int KRB5_CALLCONV krb5_address_order(krb5_context context, const krb5_address *addr1, const krb5_address *addr2); /** * Compare the realms of two principals. * * @param [in] context Library context * @param [in] princ1 First principal * @param [in] princ2 Second principal * * @retval * TRUE if the realm names are the same; FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_realm_compare(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2); /** * Compare two principals. * * @param [in] context Library context * @param [in] princ1 First principal * @param [in] princ2 Second principal * * @retval * TRUE if the principals are the same; FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_principal_compare(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2); /** * Compare two principals ignoring realm components. * * @param [in] context Library context * @param [in] princ1 First principal * @param [in] princ2 Second principal * * Similar to krb5_principal_compare(), but do not compare the realm * components of the principals. * * @retval * TRUE if the principals are the same; FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_principal_compare_any_realm(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2); #define KRB5_PRINCIPAL_COMPARE_IGNORE_REALM 1 /**< ignore realm component */ #define KRB5_PRINCIPAL_COMPARE_ENTERPRISE 2 /**< UPNs as real principals */ #define KRB5_PRINCIPAL_COMPARE_CASEFOLD 4 /**< case-insensitive */ #define KRB5_PRINCIPAL_COMPARE_UTF8 8 /**< treat principals as UTF-8 */ /** * Compare two principals with additional flags. * * @param [in] context Library context * @param [in] princ1 First principal * @param [in] princ2 Second principal * @param [in] flags Flags * * Valid flags are: * @li #KRB5_PRINCIPAL_COMPARE_IGNORE_REALM - ignore realm component * @li #KRB5_PRINCIPAL_COMPARE_ENTERPRISE - UPNs as real principals * @li #KRB5_PRINCIPAL_COMPARE_CASEFOLD case-insensitive * @li #KRB5_PRINCIPAL_COMPARE_UTF8 - treat principals as UTF-8 * * @sa krb5_principal_compare() * * @retval * TRUE if the principal names are the same; FALSE otherwise */ krb5_boolean KRB5_CALLCONV krb5_principal_compare_flags(krb5_context context, krb5_const_principal princ1, krb5_const_principal princ2, int flags); /** * Initialize an empty @c krb5_keyblock. * * @param [in] context Library context * @param [in] enctype Encryption type * @param [in] length Length of keyblock (or 0) * @param [out] out New keyblock structure * * Initialize a new keyblock and allocate storage for the contents of the key. * It is legal to pass in a length of 0, in which case contents are left * unallocated. Use krb5_free_keyblock() to free @a out when it is no longer * needed. * * @note If @a length is set to 0, contents are left unallocated. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_keyblock(krb5_context context, krb5_enctype enctype, size_t length, krb5_keyblock **out); /** * Copy a keyblock. * * @param [in] context Library context * @param [in] from Keyblock to be copied * @param [out] to Copy of keyblock @a from * * This function creates a new keyblock with the same contents as @a from. Use * krb5_free_keyblock() to free @a to when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_keyblock(krb5_context context, const krb5_keyblock *from, krb5_keyblock **to); /** * Copy the contents of a keyblock. * * @param [in] context Library context * @param [in] from Key to be copied * @param [out] to Output key * * This function copies the contents of @a from to @a to. Use * krb5_free_keyblock_contents() to free @a to when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_keyblock_contents(krb5_context context, const krb5_keyblock *from, krb5_keyblock *to); /** * Copy a krb5_creds structure. * * @param [in] context Library context * @param [in] incred Credentials structure to be copied * @param [out] outcred Copy of @a incred * * This function creates a new credential with the contents of @a incred. Use * krb5_free_creds() to free @a outcred when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_creds(krb5_context context, const krb5_creds *incred, krb5_creds **outcred); /** * Copy a krb5_data object. * * @param [in] context Library context * @param [in] indata Data object to be copied * @param [out] outdata Copy of @a indata * * This function creates a new krb5_data object with the contents of @a indata. * Use krb5_free_data() to free @a outdata when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_data(krb5_context context, const krb5_data *indata, krb5_data **outdata); /** * Copy a principal. * * @param [in] context Library context * @param [in] inprinc Principal to be copied * @param [out] outprinc Copy of @a inprinc * * This function creates a new principal structure with the contents of @a * inprinc. Use krb5_free_principal() to free @a outprinc when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_principal(krb5_context context, krb5_const_principal inprinc, krb5_principal *outprinc); /** * Copy an array of addresses. * * @param [in] context Library context * @param [in] inaddr Array of addresses to be copied * @param [out] outaddr Copy of array of addresses * * This function creates a new address array containing a copy of @a inaddr. * Use krb5_free_addresses() to free @a outaddr when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_addresses(krb5_context context, krb5_address *const *inaddr, krb5_address ***outaddr); /** * Copy a krb5_ticket structure. * * @param [in] context Library context * @param [in] from Ticket to be copied * @param [out] pto Copy of ticket * * This function creates a new krb5_ticket structure containing the contents of * @a from. Use krb5_free_ticket() to free @a pto when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_ticket(krb5_context context, const krb5_ticket *from, krb5_ticket **pto); /** * Copy an authorization data list. * * @param [in] context Library context * @param [in] in_authdat List of @a krb5_authdata structures * @param [out] out New array of @a krb5_authdata structures * * This function creates a new authorization data list containing a copy of @a * in_authdat, which must be null-terminated. Use krb5_free_authdata() to free * @a out when it is no longer needed. * * @note The last array entry in @a in_authdat must be a NULL pointer. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_authdata(krb5_context context, krb5_authdata *const *in_authdat, krb5_authdata ***out); /** * Find authorization data elements. * * @param [in] context Library context * @param [in] ticket_authdata Authorization data list from ticket * @param [in] ap_req_authdata Authorization data list from AP request * @param [in] ad_type Authorization data type to find * @param [out] results List of matching entries * * This function searches @a ticket_authdata and @a ap_req_authdata for * elements of type @a ad_type. Either input list may be NULL, in which case * it will not be searched; otherwise, the input lists must be terminated by * NULL entries. This function will search inside AD-IF-RELEVANT containers if * found in either list. Use krb5_free_authdata() to free @a results when it * is no longer needed. * * @version New in 1.10 */ krb5_error_code KRB5_CALLCONV krb5_find_authdata(krb5_context context, krb5_authdata *const *ticket_authdata, krb5_authdata *const *ap_req_authdata, krb5_authdatatype ad_type, krb5_authdata ***results); /** * Merge two authorization data lists into a new list. * * @param [in] context Library context * @param [in] inauthdat1 First list of @a krb5_authdata structures * @param [in] inauthdat2 Second list of @a krb5_authdata structures * @param [out] outauthdat Merged list of @a krb5_authdata structures * * Merge two authdata arrays, such as the array from a ticket * and authenticator. * Use krb5_free_authdata() to free @a outauthdat when it is no longer needed. * * @note The last array entry in @a inauthdat1 and @a inauthdat2 * must be a NULL pointer. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_merge_authdata(krb5_context context, krb5_authdata *const *inauthdat1, krb5_authdata * const *inauthdat2, krb5_authdata ***outauthdat); /** * Copy a krb5_authenticator structure. * * @param [in] context Library context * @param [in] authfrom krb5_authenticator structure to be copied * @param [out] authto Copy of krb5_authenticator structure * * This function creates a new krb5_authenticator structure with the content of * @a authfrom. Use krb5_free_authenticator() to free @a authto when it is no * longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_authenticator(krb5_context context, const krb5_authenticator *authfrom, krb5_authenticator **authto); /** * Copy a krb5_checksum structure. * * @param [in] context Library context * @param [in] ckfrom Checksum to be copied * @param [out] ckto Copy of krb5_checksum structure * * This function creates a new krb5_checksum structure with the contents of @a * ckfrom. Use krb5_free_checksum() to free @a ckto when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_copy_checksum(krb5_context context, const krb5_checksum *ckfrom, krb5_checksum **ckto); /** * Generate a replay cache object for server use and open it. * * @param [in] context Library context * @param [in] piece Unused (replay cache identifier) * @param [out] rcptr Handle to an open rcache * * This function creates a handle to the default replay cache. Use * krb5_rc_close() to close @a rcptr when it is no longer needed. * * @version Prior to release 1.18, this function creates a handle to a * different replay cache for each unique value of @a piece. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_server_rcache(krb5_context context, const krb5_data *piece, krb5_rcache *rcptr); /** * Build a principal name using length-counted strings. * * @param [in] context Library context * @param [out] princ Principal name * @param [in] rlen Realm name length * @param [in] realm Realm name * @param [in] ... List of unsigned int/char * components, followed by 0 * * This function creates a principal from a length-counted string and a * variable-length list of length-counted components. The list of components * ends with the first 0 length argument (so it is not possible to specify an * empty component with this function). Call krb5_free_principal() to free * allocated memory for principal when it is no longer needed. * * @code * Example of how to build principal WELLKNOWN/ANONYMOUS@R * krb5_build_principal_ext(context, &principal, strlen("R"), "R", * (unsigned int)strlen(KRB5_WELLKNOWN_NAMESTR), * KRB5_WELLKNOWN_NAMESTR, * (unsigned int)strlen(KRB5_ANONYMOUS_PRINCSTR), * KRB5_ANONYMOUS_PRINCSTR, 0); * @endcode * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV_C krb5_build_principal_ext(krb5_context context, krb5_principal * princ, unsigned int rlen, const char * realm, ...); /** * Build a principal name using null-terminated strings. * * @param [in] context Library context * @param [out] princ Principal name * @param [in] rlen Realm name length * @param [in] realm Realm name * @param [in] ... List of char * components, ending with NULL * * Call krb5_free_principal() to free @a princ when it is no longer needed. * * @note krb5_build_principal() and krb5_build_principal_alloc_va() perform the * same task. krb5_build_principal() takes variadic arguments. * krb5_build_principal_alloc_va() takes a pre-computed @a varargs pointer. * * @code * Example of how to build principal H/S@R * krb5_build_principal(context, &principal, * strlen("R"), "R", "H", "S", (char*)NULL); * @endcode * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV_C krb5_build_principal(krb5_context context, krb5_principal * princ, unsigned int rlen, const char * realm, ...) #if __GNUC__ >= 4 __attribute__ ((sentinel)) #endif ; #if KRB5_DEPRECATED /** @deprecated Replaced by krb5_build_principal_alloc_va(). */ KRB5_ATTR_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_build_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap); #endif /** * Build a principal name, using a precomputed variable argument list * * @param [in] context Library context * @param [out] princ Principal structure * @param [in] rlen Realm name length * @param [in] realm Realm name * @param [in] ap List of char * components, ending with NULL * * Similar to krb5_build_principal(), this function builds a principal name, * but its name components are specified as a va_list. * * Use krb5_free_principal() to deallocate @a princ when it is no longer * needed. * * @code * Function usage example: * va_list ap; * va_start(ap, realm); * krb5_build_principal_alloc_va(context, princ, rlen, realm, ap); * va_end(ap); * @endcode * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_build_principal_alloc_va(krb5_context context, krb5_principal *princ, unsigned int rlen, const char *realm, va_list ap); /** * Convert a Kerberos V4 principal to a Kerberos V5 principal. * * @param [in] context Library context * @param [in] name V4 name * @param [in] instance V4 instance * @param [in] realm Realm * @param [out] princ V5 principal * * This function builds a @a princ from V4 specification based on given input * @a name.instance\@realm. * * Use krb5_free_principal() to free @a princ when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_425_conv_principal(krb5_context context, const char *name, const char *instance, const char *realm, krb5_principal *princ); /** * Convert a Kerberos V5 principal to a Kerberos V4 principal. * * @param [in] context Library context * @param [in] princ V5 Principal * @param [out] name V4 principal's name to be filled in * @param [out] inst V4 principal's instance name to be filled in * @param [out] realm Principal's realm name to be filled in * * This function separates a V5 principal @a princ into @a name, @a instance, * and @a realm. * * @retval * 0 Success * @retval * KRB5_INVALID_PRINCIPAL Invalid principal name * @retval * KRB5_CONFIG_CANTOPEN Can't open or find Kerberos configuration file * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_524_conv_principal(krb5_context context, krb5_const_principal princ, char *name, char *inst, char *realm); /** *@deprecated */ struct credentials; /** * Convert a Kerberos V5 credentials to a Kerberos V4 credentials * * @note Not implemented * * @retval KRB524_KRB4_DISABLED (always) */ int KRB5_CALLCONV krb5_524_convert_creds(krb5_context context, krb5_creds *v5creds, struct credentials *v4creds); #if KRB5_DEPRECATED #define krb524_convert_creds_kdc krb5_524_convert_creds #define krb524_init_ets(x) (0) #endif /* libkt.spec */ /** * Get a handle for a key table. * * @param [in] context Library context * @param [in] name Name of the key table * @param [out] ktid Key table handle * * Resolve the key table name @a name and set @a ktid to a handle identifying * the key table. Use krb5_kt_close() to free @a ktid when it is no longer * needed. * * @a name must be of the form @c type:residual, where @a type must be a type * known to the library and @a residual portion should be specific to the * particular keytab type. If no @a type is given, the default is @c FILE. * * If @a name is of type @c FILE, the keytab file is not opened by this call. * * @code * Example: krb5_kt_resolve(context, "FILE:/tmp/filename", &ktid); * @endcode * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_resolve(krb5_context context, const char *name, krb5_keytab *ktid); /** * Duplicate keytab handle. * * @param [in] context Library context * @param [in] in Key table handle to be duplicated * @param [out] out Key table handle * * Create a new handle referring to the same key table as @a in. The new * handle and @a in can be closed independently. * * @version New in 1.12 */ krb5_error_code KRB5_CALLCONV krb5_kt_dup(krb5_context context, krb5_keytab in, krb5_keytab *out); /** * Get the default key table name. * * @param [in] context Library context * @param [out] name Default key table name * @param [in] name_size Space available in @a name * * Fill @a name with the name of the default key table for @a context. * * @sa MAX_KEYTAB_NAME_LEN * * @retval * 0 Success * @retval * KRB5_CONFIG_NOTENUFSPACE Buffer is too short * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_default_name(krb5_context context, char *name, int name_size); /** * Resolve the default key table. * * @param [in] context Library context * @param [out] id Key table handle * * Set @a id to a handle to the default key table. The key table is not * opened. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_default(krb5_context context, krb5_keytab *id); /** * Resolve the default client key table. * * @param [in] context Library context * @param [out] keytab_out Key table handle * * Fill @a keytab_out with a handle to the default client key table. * * @version New in 1.11 * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_client_default(krb5_context context, krb5_keytab *keytab_out); /** * Free the contents of a key table entry. * * @param [in] context Library context * @param [in] entry Key table entry whose contents are to be freed * * @note The pointer is not freed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_free_keytab_entry_contents(krb5_context context, krb5_keytab_entry *entry); /** @deprecated Use krb5_free_keytab_entry_contents instead. */ krb5_error_code KRB5_CALLCONV krb5_kt_free_entry(krb5_context context, krb5_keytab_entry *entry); /* remove and add are functions, so that they can return NOWRITE if not a writable keytab */ /** * Remove an entry from a key table. * * @param [in] context Library context * @param [in] id Key table handle * @param [in] entry Entry to remove from key table * * @retval * 0 Success * @retval * KRB5_KT_NOWRITE Key table is not writable * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_remove_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry); /** * Add a new entry to a key table. * * @param [in] context Library context * @param [in] id Key table handle * @param [in] entry Entry to be added * * @retval * 0 Success * @retval * ENOMEM Insufficient memory * @retval * KRB5_KT_NOWRITE Key table is not writeable * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_kt_add_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry); /** * Convert a principal name into the default salt for that principal. * * @param [in] context Library context * @param [in] pr Principal name * @param [out] ret Default salt for @a pr to be filled in * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV_WRONG krb5_principal2salt(krb5_context context, krb5_const_principal pr, krb5_data *ret); /* librc.spec--see rcache.h */ /* libcc.spec */ /** * Resolve a credential cache name. * * @param [in] context Library context * @param [in] name Credential cache name to be resolved * @param [out] cache Credential cache handle * * Fills in @a cache with a @a cache handle that corresponds to the name in @a * name. @a name should be of the form @c type:residual, and @a type must be a * type known to the library. If the @a name does not contain a colon, * interpret it as a file name. * * @code * Example: krb5_cc_resolve(context, "MEMORY:C_", &cache); * @endcode * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_resolve(krb5_context context, const char *name, krb5_ccache *cache); /** * Duplicate ccache handle. * * @param [in] context Library context * @param [in] in Credential cache handle to be duplicated * @param [out] out Credential cache handle * * Create a new handle referring to the same cache as @a in. * The new handle and @a in can be closed independently. */ krb5_error_code KRB5_CALLCONV krb5_cc_dup(krb5_context context, krb5_ccache in, krb5_ccache *out); /** * Return the name of the default credential cache. * * @param [in] context Library context * * Return a pointer to the default credential cache name for @a context, as * determined by a prior call to krb5_cc_set_default_name(), by the KRB5CCNAME * environment variable, by the default_ccache_name profile variable, or by the * operating system or build-time default value. The returned value must not * be modified or freed by the caller. The returned value becomes invalid when * @a context is destroyed krb5_free_context() or if a subsequent call to * krb5_cc_set_default_name() is made on @a context. * * The default credential cache name is cached in @a context between calls to * this function, so if the value of KRB5CCNAME changes in the process * environment after the first call to this function on, that change will not * be reflected in later calls with the same context. The caller can invoke * krb5_cc_set_default_name() with a NULL value of @a name to clear the cached * value and force the default name to be recomputed. * * @return * Name of default credential cache for the current user. */ const char *KRB5_CALLCONV krb5_cc_default_name(krb5_context context); /** * Set the default credential cache name. * * @param [in] context Library context * @param [in] name Default credential cache name or NULL * * Set the default credential cache name to @a name for future operations using * @a context. If @a name is NULL, clear any previous application-set default * name and forget any cached value of the default name for @a context. * * Calls to this function invalidate the result of any previous calls to * krb5_cc_default_name() using @a context. * * @retval * 0 Success * @retval * KV5M_CONTEXT Bad magic number for @c _krb5_context structure * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_set_default_name(krb5_context context, const char *name); /** * Resolve the default credential cache name. * * @param [in] context Library context * @param [out] ccache Pointer to credential cache name * * Create a handle to the default credential cache as given by * krb5_cc_default_name(). * * @retval * 0 Success * @retval * KV5M_CONTEXT Bad magic number for @c _krb5_context structure * @retval * KRB5_FCC_INTERNAL The name of the default credential cache cannot be * obtained * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_default(krb5_context context, krb5_ccache *ccache); /** * Copy a credential cache. * * @param [in] context Library context * @param [in] incc Credential cache to be copied * @param [out] outcc Copy of credential cache to be filled in * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_copy_creds(krb5_context context, krb5_ccache incc, krb5_ccache outcc); /** * Get a configuration value from a credential cache. * * @param [in] context Library context * @param [in] id Credential cache handle * @param [in] principal Configuration for this principal; * if NULL, global for the whole cache * @param [in] key Name of config variable * @param [out] data Data to be fetched * * Use krb5_free_data_contents() to free @a data when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_get_config(krb5_context context, krb5_ccache id, krb5_const_principal principal, const char *key, krb5_data *data); /** * Store a configuration value in a credential cache. * * @param [in] context Library context * @param [in] id Credential cache handle * @param [in] principal Configuration for a specific principal; * if NULL, global for the whole cache * @param [in] key Name of config variable * @param [in] data Data to store, or NULL to remove * * @note Existing configuration under the same key is over-written. * * @warning Before version 1.10 @a data was assumed to be always non-null. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_set_config(krb5_context context, krb5_ccache id, krb5_const_principal principal, const char *key, krb5_data *data); /** * Test whether a principal is a configuration principal. * * @param [in] context Library context * @param [in] principal Principal to check * * @return * @c TRUE if the principal is a configuration principal (generated part of * krb5_cc_set_config()); @c FALSE otherwise. */ krb5_boolean KRB5_CALLCONV krb5_is_config_principal(krb5_context context, krb5_const_principal principal); /** * Make a credential cache the primary cache for its collection. * * @param [in] context Library context * @param [in] cache Credential cache handle * * If the type of @a cache supports it, set @a cache to be the primary * credential cache for the collection it belongs to. * * @retval * 0 Success, or the type of @a cache doesn't support switching * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cc_switch(krb5_context context, krb5_ccache cache); /** * Determine whether a credential cache type supports switching. * * @param [in] context Library context * @param [in] type Credential cache type * * @version New in 1.10 * * @retval TRUE if @a type supports switching * @retval FALSE if it does not or is not a valid credential cache type. */ krb5_boolean KRB5_CALLCONV krb5_cc_support_switch(krb5_context context, const char *type); /** * Find a credential cache with a specified client principal. * * @param [in] context Library context * @param [in] client Client principal * @param [out] cache_out Credential cache handle * * Find a cache within the collection whose default principal is @a client. * Use @a krb5_cc_close to close @a ccache when it is no longer needed. * * @retval 0 Success * @retval KRB5_CC_NOTFOUND * * @sa krb5_cccol_cursor_new * * @version New in 1.10 */ krb5_error_code KRB5_CALLCONV krb5_cc_cache_match(krb5_context context, krb5_principal client, krb5_ccache *cache_out); /** * Select a credential cache to use with a server principal. * * @param [in] context Library context * @param [in] server Server principal * @param [out] cache_out Credential cache handle * @param [out] princ_out Client principal * * Select a cache within the collection containing credentials most appropriate * for use with @a server, according to configured rules and heuristics. * * Use krb5_cc_close() to release @a cache_out when it is no longer needed. * Use krb5_free_principal() to release @a princ_out when it is no longer * needed. Note that @a princ_out is set in some error conditions. * * @return * If an appropriate cache is found, 0 is returned, @a cache_out is set to the * selected cache, and @a princ_out is set to the default principal of that * cache. * * If the appropriate client principal can be authoritatively determined but * the cache collection contains no credentials for that principal, then * KRB5_CC_NOTFOUND is returned, @a cache_out is set to NULL, and @a princ_out * is set to the appropriate client principal. * * If no configured mechanism can determine the appropriate cache or principal, * KRB5_CC_NOTFOUND is returned and @a cache_out and @a princ_out are set to * NULL. * * Any other error code indicates a fatal error in the processing of a cache * selection mechanism. * * @version New in 1.10 */ krb5_error_code KRB5_CALLCONV krb5_cc_select(krb5_context context, krb5_principal server, krb5_ccache *cache_out, krb5_principal *princ_out); /* krb5_free.c */ /** * Free the storage assigned to a principal. * * @param [in] context Library context * @param [in] val Principal to be freed */ void KRB5_CALLCONV krb5_free_principal(krb5_context context, krb5_principal val); /** * Free a krb5_authenticator structure. * * @param [in] context Library context * @param [in] val Authenticator structure to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_authenticator(krb5_context context, krb5_authenticator *val); /** * Free the data stored in array of addresses. * * @param [in] context Library context * @param [in] val Array of addresses to be freed * * This function frees the contents of @a val and the array itself. * * @note The last entry in the array must be a NULL pointer. */ void KRB5_CALLCONV krb5_free_addresses(krb5_context context, krb5_address **val); /** * Free the storage assigned to array of authentication data. * * @param [in] context Library context * @param [in] val Array of authentication data to be freed * * This function frees the contents of @a val and the array itself. * * @note The last entry in the array must be a NULL pointer. */ void KRB5_CALLCONV krb5_free_authdata(krb5_context context, krb5_authdata **val); /** * Free a ticket. * * @param [in] context Library context * @param [in] val Ticket to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_ticket(krb5_context context, krb5_ticket *val); /** * Free an error allocated by krb5_read_error() or krb5_sendauth(). * * @param [in] context Library context * @param [in] val Error data structure to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_error(krb5_context context, krb5_error *val); /** * Free a krb5_creds structure. * * @param [in] context Library context * @param [in] val Credential structure to be freed. * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_creds(krb5_context context, krb5_creds *val); /** * Free the contents of a krb5_creds structure. * * @param [in] context Library context * @param [in] val Credential structure to free contents of * * This function frees the contents of @a val, but not the structure itself. */ void KRB5_CALLCONV krb5_free_cred_contents(krb5_context context, krb5_creds *val); /** * Free a krb5_checksum structure. * * @param [in] context Library context * @param [in] val Checksum structure to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_checksum(krb5_context context, krb5_checksum *val); /** * Free the contents of a krb5_checksum structure. * * @param [in] context Library context * @param [in] val Checksum structure to free contents of * * This function frees the contents of @a val, but not the structure itself. */ void KRB5_CALLCONV krb5_free_checksum_contents(krb5_context context, krb5_checksum *val); /** * Free a krb5_keyblock structure. * * @param [in] context Library context * @param [in] val Keyblock to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_keyblock(krb5_context context, krb5_keyblock *val); /** * Free the contents of a krb5_keyblock structure. * * @param [in] context Library context * @param [in] key Keyblock to be freed * * This function frees the contents of @a key, but not the structure itself. */ void KRB5_CALLCONV krb5_free_keyblock_contents(krb5_context context, krb5_keyblock *key); /** * Free a krb5_ap_rep_enc_part structure. * * @param [in] context Library context * @param [in] val AP-REP enc part to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_ap_rep_enc_part(krb5_context context, krb5_ap_rep_enc_part *val); /** * Free a krb5_data structure. * * @param [in] context Library context * @param [in] val Data structure to be freed * * This function frees the contents of @a val and the structure itself. */ void KRB5_CALLCONV krb5_free_data(krb5_context context, krb5_data *val); /* Free a krb5_octet_data structure (should be unused). */ void KRB5_CALLCONV krb5_free_octet_data(krb5_context context, krb5_octet_data *val); /** * Free the contents of a krb5_data structure and zero the data field. * * @param [in] context Library context * @param [in] val Data structure to free contents of * * This function frees the contents of @a val, but not the structure itself. */ void KRB5_CALLCONV krb5_free_data_contents(krb5_context context, krb5_data *val); /** * Free a string representation of a principal. * * @param [in] context Library context * @param [in] val Name string to be freed */ void KRB5_CALLCONV krb5_free_unparsed_name(krb5_context context, char *val); /** * Free a string allocated by a krb5 function. * * @param [in] context Library context * @param [in] val String to be freed * * @version New in 1.10 */ void KRB5_CALLCONV krb5_free_string(krb5_context context, char *val); /** * Free an array of encryption types. * * @param [in] context Library context * @param [in] val Array of enctypes to be freed * * @version New in 1.12 */ void KRB5_CALLCONV krb5_free_enctypes(krb5_context context, krb5_enctype *val); /** * Free an array of checksum types. * * @param [in] context Library context * @param [in] val Array of checksum types to be freed */ void KRB5_CALLCONV krb5_free_cksumtypes(krb5_context context, krb5_cksumtype *val); /* From krb5/os, but needed by the outside world */ /** * Retrieve the system time of day, in sec and ms, since the epoch. * * @param [in] context Library context * @param [out] seconds System timeofday, seconds portion * @param [out] microseconds System timeofday, microseconds portion * * This function retrieves the system time of day with the context * specific time offset adjustment. * * @sa krb5_crypto_us_timeofday() * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_us_timeofday(krb5_context context, krb5_timestamp *seconds, krb5_int32 *microseconds); /** * Retrieve the current time with context specific time offset adjustment. * * @param [in] context Library context * @param [out] timeret Timestamp to fill in * * This function retrieves the system time of day with the context specific * time offset adjustment. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_timeofday(krb5_context context, krb5_timestamp *timeret); /** * Check if a timestamp is within the allowed clock skew of the current time. * * @param [in] context Library context * @param [in] date Timestamp to check * * This function checks if @a date is close enough to the current time * according to the configured allowable clock skew. * * @version New in 1.10 * * @retval 0 Success * @retval KRB5KRB_AP_ERR_SKEW @a date is not within allowable clock skew */ krb5_error_code KRB5_CALLCONV krb5_check_clockskew(krb5_context context, krb5_timestamp date); /** * Return all interface addresses for this host. * * @param [in] context Library context * @param [out] addr Array of krb5_address pointers, ending with * NULL * * Use krb5_free_addresses() to free @a addr when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_os_localaddr(krb5_context context, krb5_address ***addr); /** * Retrieve the default realm. * * @param [in] context Library context * @param [out] lrealm Default realm name * * Retrieves the default realm to be used if no user-specified realm is * available. * * Use krb5_free_default_realm() to free @a lrealm when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_default_realm(krb5_context context, char **lrealm); /** * Override the default realm for the specified context. * * @param [in] context Library context * @param [in] lrealm Realm name for the default realm * * If @a lrealm is NULL, clear the default realm setting. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_set_default_realm(krb5_context context, const char *lrealm); /** * Free a default realm string returned by krb5_get_default_realm(). * * @param [in] context Library context * @param [in] lrealm Realm to be freed */ void KRB5_CALLCONV krb5_free_default_realm(krb5_context context, char *lrealm); /** * Canonicalize a hostname, possibly using name service. * * @param [in] context Library context * @param [in] host Input hostname * @param [out] canonhost_out Canonicalized hostname * * This function canonicalizes orig_hostname, possibly using name service * lookups if configuration permits. Use krb5_free_string() to free @a * canonhost_out when it is no longer needed. * * @version New in 1.15 */ krb5_error_code KRB5_CALLCONV krb5_expand_hostname(krb5_context context, const char *host, char **canonhost_out); /** * Generate a full principal name from a service name. * * @param [in] context Library context * @param [in] hostname Host name, or NULL to use local host * @param [in] sname Service name, or NULL to use @c "host" * @param [in] type Principal type * @param [out] ret_princ Generated principal * * This function converts a @a hostname and @a sname into @a krb5_principal * structure @a ret_princ. The returned principal will be of the form @a * sname\/hostname\@REALM where REALM is determined by krb5_get_host_realm(). * In some cases this may be the referral (empty) realm. * * The @a type can be one of the following: * * @li #KRB5_NT_SRV_HST canonicalizes the host name before looking up the * realm and generating the principal. * * @li #KRB5_NT_UNKNOWN accepts the hostname as given, and does not * canonicalize it. * * Use krb5_free_principal to free @a ret_princ when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_sname_to_principal(krb5_context context, const char *hostname, const char *sname, krb5_int32 type, krb5_principal *ret_princ); /** * Test whether a principal matches a matching principal. * * @param [in] context Library context * @param [in] matching Matching principal * @param [in] princ Principal to test * * @note A matching principal is a host-based principal with an empty realm * and/or second data component (hostname). Profile configuration may cause * the hostname to be ignored even if it is present. A principal matches a * matching principal if the former has the same non-empty (and non-ignored) * components of the latter. * * If @a matching is NULL, return TRUE. If @a matching is not a matching * principal, return the value of krb5_principal_compare(context, matching, * princ). * * @return * TRUE if @a princ matches @a matching, FALSE otherwise. */ krb5_boolean KRB5_CALLCONV krb5_sname_match(krb5_context context, krb5_const_principal matching, krb5_const_principal princ); /** * Change a password for an existing Kerberos account. * * @param [in] context Library context * @param [in] creds Credentials for kadmin/changepw service * @param [in] newpw New password * @param [out] result_code Numeric error code from server * @param [out] result_code_string String equivalent to @a result_code * @param [out] result_string Change password response from the KDC * * Change the password for the existing principal identified by @a creds. * * The possible values of the output @a result_code are: * * @li #KRB5_KPASSWD_SUCCESS (0) - success * @li #KRB5_KPASSWD_MALFORMED (1) - Malformed request error * @li #KRB5_KPASSWD_HARDERROR (2) - Server error * @li #KRB5_KPASSWD_AUTHERROR (3) - Authentication error * @li #KRB5_KPASSWD_SOFTERROR (4) - Password change rejected * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_change_password(krb5_context context, krb5_creds *creds, const char *newpw, int *result_code, krb5_data *result_code_string, krb5_data *result_string); /** * Set a password for a principal using specified credentials. * * @param [in] context Library context * @param [in] creds Credentials for kadmin/changepw service * @param [in] newpw New password * @param [in] change_password_for Change the password for this principal * @param [out] result_code Numeric error code from server * @param [out] result_code_string String equivalent to @a result_code * @param [out] result_string Data returned from the remote system * * This function uses the credentials @a creds to set the password @a newpw for * the principal @a change_password_for. It implements the set password * operation of RFC 3244, for interoperability with Microsoft Windows * implementations. * * @note If @a change_password_for is NULL, the change is performed on the * current principal. If @a change_password_for is non-null, the change is * performed on the principal name passed in @a change_password_for. * * The error code and strings are returned in @a result_code, * @a result_code_string and @a result_string. * * @sa krb5_set_password_using_ccache() * * @retval * 0 Success and result_code is set to #KRB5_KPASSWD_SUCCESS. * @return * Kerberos error codes. */ krb5_error_code KRB5_CALLCONV krb5_set_password(krb5_context context, krb5_creds *creds, const char *newpw, krb5_principal change_password_for, int *result_code, krb5_data *result_code_string, krb5_data *result_string); /** * Set a password for a principal using cached credentials. * * @param [in] context Library context * @param [in] ccache Credential cache * @param [in] newpw New password * @param [in] change_password_for Change the password for this principal * @param [out] result_code Numeric error code from server * @param [out] result_code_string String equivalent to @a result_code * @param [out] result_string Data returned from the remote system * * This function uses the cached credentials from @a ccache to set the password * @a newpw for the principal @a change_password_for. It implements RFC 3244 * set password operation (interoperable with MS Windows implementations) using * the credential cache. * * The error code and strings are returned in @a result_code, * @a result_code_string and @a result_string. * * @note If @a change_password_for is set to NULL, the change is performed on * the default principal in @a ccache. If @a change_password_for is non null, * the change is performed on the specified principal. * * @sa krb5_set_password() * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_set_password_using_ccache(krb5_context context, krb5_ccache ccache, const char *newpw, krb5_principal change_password_for, int *result_code, krb5_data *result_code_string, krb5_data *result_string); /** * Get a result message for changing or setting a password. * * @param [in] context Library context * @param [in] server_string Data returned from the remote system * @param [out] message_out A message displayable to the user * * This function processes the @a server_string returned in the @a * result_string parameter of krb5_change_password(), krb5_set_password(), and * related functions, and returns a displayable string. If @a server_string * contains Active Directory structured policy information, it will be * converted into human-readable text. * * Use krb5_free_string() to free @a message_out when it is no longer needed. * * @retval * 0 Success * @return * Kerberos error codes * * @version New in 1.11 */ krb5_error_code KRB5_CALLCONV krb5_chpw_message(krb5_context context, const krb5_data *server_string, char **message_out); /** * Retrieve configuration profile from the context. * * @param [in] context Library context * @param [out] profile Pointer to data read from a configuration file * * This function creates a new @a profile object that reflects profile * in the supplied @a context. * * The @a profile object may be freed with profile_release() function. * See profile.h and profile API for more details. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_profile(krb5_context context, struct _profile_t ** profile); #if KRB5_DEPRECATED /** @deprecated Replaced by krb5_get_init_creds_password().*/ KRB5_ATTR_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_get_in_tkt_with_password(krb5_context context, krb5_flags options, krb5_address *const *addrs, krb5_enctype *ktypes, krb5_preauthtype *pre_auth_types, const char *password, krb5_ccache ccache, krb5_creds *creds, krb5_kdc_rep **ret_as_reply); /** @deprecated Replaced by krb5_get_init_creds(). */ KRB5_ATTR_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_get_in_tkt_with_skey(krb5_context context, krb5_flags options, krb5_address *const *addrs, krb5_enctype *ktypes, krb5_preauthtype *pre_auth_types, const krb5_keyblock *key, krb5_ccache ccache, krb5_creds *creds, krb5_kdc_rep **ret_as_reply); /** @deprecated Replaced by krb5_get_init_creds_keytab(). */ KRB5_ATTR_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_get_in_tkt_with_keytab(krb5_context context, krb5_flags options, krb5_address *const *addrs, krb5_enctype *ktypes, krb5_preauthtype *pre_auth_types, krb5_keytab arg_keytab, krb5_ccache ccache, krb5_creds *creds, krb5_kdc_rep **ret_as_reply); #endif /* KRB5_DEPRECATED */ /** * Parse and decrypt a @c KRB_AP_REQ message. * * @param [in] context Library context * @param [in,out] auth_context Pre-existing or newly created auth context * @param [in] inbuf AP-REQ message to be parsed * @param [in] server Matching principal for server, or NULL to * allow any principal in keytab * @param [in] keytab Key table, or NULL to use the default * @param [out] ap_req_options If non-null, the AP-REQ flags on output * @param [out] ticket If non-null, ticket from the AP-REQ message * * This function parses, decrypts and verifies a AP-REQ message from @a inbuf * and stores the authenticator in @a auth_context. * * If a keyblock was specified in @a auth_context using * krb5_auth_con_setuseruserkey(), that key is used to decrypt the ticket in * AP-REQ message and @a keytab is ignored. In this case, @a server should be * specified as a complete principal name to allow for proper transited-path * checking and replay cache selection. * * Otherwise, the decryption key is obtained from @a keytab, or from the * default keytab if it is NULL. In this case, @a server may be a complete * principal name, a matching principal (see krb5_sname_match()), or NULL to * match any principal name. The keys tried against the encrypted part of the * ticket are determined as follows: * * - If @a server is a complete principal name, then its entry in @a keytab is * tried. * - Otherwise, if @a keytab is iterable, then all entries in @a keytab which * match @a server are tried. * - Otherwise, the server principal in the ticket must match @a server, and * its entry in @a keytab is tried. * * The client specified in the decrypted authenticator must match the client * specified in the decrypted ticket. * * If the @a remote_addr field of @a auth_context is set, the request must come * from that address. * * If a replay cache handle is provided in the @a auth_context, the * authenticator and ticket are verified against it. If no conflict is found, * the new authenticator is then stored in the replay cache of @a auth_context. * * Various other checks are performed on the decoded data, including * cross-realm policy, clockskew, and ticket validation times. * * On success the authenticator, subkey, and remote sequence number of the * request are stored in @a auth_context. If the #AP_OPTS_MUTUAL_REQUIRED * bit is set, the local sequence number is XORed with the remote sequence * number in the request. * * Use krb5_free_ticket() to free @a ticket when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_req(krb5_context context, krb5_auth_context *auth_context, const krb5_data *inbuf, krb5_const_principal server, krb5_keytab keytab, krb5_flags *ap_req_options, krb5_ticket **ticket); /** * Retrieve a service key from a key table. * * @param [in] context Library context * @param [in] keyprocarg Name of a key table (NULL to use default name) * @param [in] principal Service principal * @param [in] vno Key version number (0 for highest available) * @param [in] enctype Encryption type (0 for any type) * @param [out] key Service key from key table * * Open and search the specified key table for the entry identified by @a * principal, @a enctype, and @a vno. If no key is found, return an error code. * * The default key table is used, unless @a keyprocarg is non-null. * @a keyprocarg designates a specific key table. * * Use krb5_free_keyblock() to free @a key when it is no longer needed. * * @retval * 0 Success * @return Kerberos error code if not found or @a keyprocarg is invalid. */ krb5_error_code KRB5_CALLCONV krb5_kt_read_service_key(krb5_context context, krb5_pointer keyprocarg, krb5_principal principal, krb5_kvno vno, krb5_enctype enctype, krb5_keyblock **key); /** * Format a @c KRB-SAFE message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] userdata User data in the message * @param [out] der_out Formatted @c KRB-SAFE buffer * @param [out] rdata_out Replay data. Specify NULL if not needed * * This function creates an integrity protected @c KRB-SAFE message * using data supplied by the application. * * Fields in @a auth_context specify the checksum type, the keyblock that * can be used to seed the checksum, full addresses (host and port) for * the sender and receiver, and @ref KRB5_AUTH_CONTEXT flags. * * The local address in @a auth_context must be set, and is used to form the * sender address used in the KRB-SAFE message. The remote address is * optional; if specified, it will be used to form the receiver address used in * the message. * * @note The @a rdata_out argument is required if the * #KRB5_AUTH_CONTEXT_RET_TIME or #KRB5_AUTH_CONTEXT_RET_SEQUENCE flag is set * in @a auth_context. * * If the #KRB5_AUTH_CONTEXT_DO_TIME flag is set in @a auth_context, a * timestamp is included in the KRB-SAFE message, and an entry for the message * is entered in an in-memory replay cache to detect if the message is * reflected by an attacker. If #KRB5_AUTH_CONTEXT_DO_TIME is not set, no * replay cache is used. If #KRB5_AUTH_CONTEXT_RET_TIME is set in @a * auth_context, a timestamp is included in the KRB-SAFE message and is stored * in @a rdata_out. * * If either #KRB5_AUTH_CONTEXT_DO_SEQUENCE or #KRB5_AUTH_CONTEXT_RET_SEQUENCE * is set, the @a auth_context local sequence number is included in the * KRB-SAFE message and then incremented. If #KRB5_AUTH_CONTEXT_RET_SEQUENCE * is set, the sequence number used is stored in @a rdata_out. * * Use krb5_free_data_contents() to free @a der_out when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_safe(krb5_context context, krb5_auth_context auth_context, const krb5_data *userdata, krb5_data *der_out, krb5_replay_data *rdata_out); /** * Format a @c KRB-PRIV message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] userdata User data for @c KRB-PRIV message * @param [out] der_out Formatted @c KRB-PRIV message * @param [out] rdata_out Replay data (NULL if not needed) * * This function is similar to krb5_mk_safe(), but the message is encrypted and * integrity-protected, not just integrity-protected. * * The local address in @a auth_context must be set, and is used to form the * sender address used in the KRB-PRIV message. The remote address is * optional; if specified, it will be used to form the receiver address used in * the message. * * @note The @a rdata_out argument is required if the * #KRB5_AUTH_CONTEXT_RET_TIME or #KRB5_AUTH_CONTEXT_RET_SEQUENCE flag is set * in @a auth_context. * * If the #KRB5_AUTH_CONTEXT_DO_TIME flag is set in @a auth_context, a * timestamp is included in the KRB-PRIV message, and an entry for the message * is entered in an in-memory replay cache to detect if the message is * reflected by an attacker. If #KRB5_AUTH_CONTEXT_DO_TIME is not set, no * replay cache is used. If #KRB5_AUTH_CONTEXT_RET_TIME is set in @a * auth_context, a timestamp is included in the KRB-PRIV message and is stored * in @a rdata_out. * * If either #KRB5_AUTH_CONTEXT_DO_SEQUENCE or #KRB5_AUTH_CONTEXT_RET_SEQUENCE * is set, the @a auth_context local sequence number is included in the * KRB-PRIV message and then incremented. If #KRB5_AUTH_CONTEXT_RET_SEQUENCE * is set, the sequence number used is stored in @a rdata_out. * * Use krb5_free_data_contents() to free @a der_out when it is no longer * needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_priv(krb5_context context, krb5_auth_context auth_context, const krb5_data *userdata, krb5_data *der_out, krb5_replay_data *rdata_out); /** * Client function for @c sendauth protocol. * * @param [in] context Library context * @param [in,out] auth_context Pre-existing or newly created auth context * @param [in] fd File descriptor that describes network socket * @param [in] appl_version Application protocol version to be matched * with the receiver's application version * @param [in] client Client principal * @param [in] server Server principal * @param [in] ap_req_options @ref AP_OPTS options * @param [in] in_data Data to be sent to the server * @param [in] in_creds Input credentials, or NULL to use @a ccache * @param [in] ccache Credential cache * @param [out] error If non-null, contains KRB_ERROR message * returned from server * @param [out] rep_result If non-null and @a ap_req_options is * #AP_OPTS_MUTUAL_REQUIRED, contains the result * of mutual authentication exchange * @param [out] out_creds If non-null, the retrieved credentials * * This function performs the client side of a sendauth/recvauth exchange by * sending and receiving messages over @a fd. * * Credentials may be specified in three ways: * * @li If @a in_creds is NULL, credentials are obtained with * krb5_get_credentials() using the principals @a client and @a server. @a * server must be non-null; @a client may NULL to use the default principal of * @a ccache. * * @li If @a in_creds is non-null, but does not contain a ticket, credentials * for the exchange are obtained with krb5_get_credentials() using @a in_creds. * In this case, the values of @a client and @a server are unused. * * @li If @a in_creds is a complete credentials structure, it used directly. * In this case, the values of @a client, @a server, and @a ccache are unused. * * If the server is using a different application protocol than that specified * in @a appl_version, an error will be returned. * * Use krb5_free_creds() to free @a out_creds, krb5_free_ap_rep_enc_part() to * free @a rep_result, and krb5_free_error() to free @a error when they are no * longer needed. * * @sa krb5_recvauth() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_sendauth(krb5_context context, krb5_auth_context *auth_context, krb5_pointer fd, char *appl_version, krb5_principal client, krb5_principal server, krb5_flags ap_req_options, krb5_data *in_data, krb5_creds *in_creds, krb5_ccache ccache, krb5_error **error, krb5_ap_rep_enc_part **rep_result, krb5_creds **out_creds); /** * Server function for @a sendauth protocol. * * @param [in] context Library context * @param [in,out] auth_context Pre-existing or newly created auth context * @param [in] fd File descriptor * @param [in] appl_version Application protocol version to be matched * against the client's application version * @param [in] server Server principal (NULL for any in @a keytab) * @param [in] flags Additional specifications * @param [in] keytab Key table containing service keys * @param [out] ticket Ticket (NULL if not needed) * * This function performs the server side of a sendauth/recvauth exchange by * sending and receiving messages over @a fd. * * Use krb5_free_ticket() to free @a ticket when it is no longer needed. * * @sa krb5_sendauth() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_recvauth(krb5_context context, krb5_auth_context *auth_context, krb5_pointer fd, char *appl_version, krb5_principal server, krb5_int32 flags, krb5_keytab keytab, krb5_ticket **ticket); /** * Server function for @a sendauth protocol with version parameter. * * @param [in] context Library context * @param [in,out] auth_context Pre-existing or newly created auth context * @param [in] fd File descriptor * @param [in] server Server principal (NULL for any in @a keytab) * @param [in] flags Additional specifications * @param [in] keytab Decryption key * @param [out] ticket Ticket (NULL if not needed) * @param [out] version sendauth protocol version (NULL if not needed) * * This function is similar to krb5_recvauth() with the additional output * information place into @a version. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_recvauth_version(krb5_context context, krb5_auth_context *auth_context, krb5_pointer fd, krb5_principal server, krb5_int32 flags, krb5_keytab keytab, krb5_ticket **ticket, krb5_data *version); /** * Format a @c KRB-CRED message for an array of credentials. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] creds Null-terminated array of credentials * @param [out] der_out Encoded credentials * @param [out] rdata_out Replay cache information (NULL if not needed) * * This function takes an array of credentials @a creds and formats * a @c KRB-CRED message @a der_out to pass to krb5_rd_cred(). * * The local and remote addresses in @a auth_context are optional; if either is * specified, they are used to form the sender and receiver addresses in the * KRB-CRED message. * * @note The @a rdata_out argument is required if the * #KRB5_AUTH_CONTEXT_RET_TIME or #KRB5_AUTH_CONTEXT_RET_SEQUENCE flag is set * in @a auth_context. * * If the #KRB5_AUTH_CONTEXT_DO_TIME flag is set in @a auth_context, an entry * for the message is entered in an in-memory replay cache to detect if the * message is reflected by an attacker. If #KRB5_AUTH_CONTEXT_DO_TIME is not * set, no replay cache is used. If #KRB5_AUTH_CONTEXT_RET_TIME is set in @a * auth_context, the timestamp used for the KRB-CRED message is stored in @a * rdata_out. * * If either #KRB5_AUTH_CONTEXT_DO_SEQUENCE or #KRB5_AUTH_CONTEXT_RET_SEQUENCE * is set, the @a auth_context local sequence number is included in the * KRB-CRED message and then incremented. If #KRB5_AUTH_CONTEXT_RET_SEQUENCE * is set, the sequence number used is stored in @a rdata_out. * * Use krb5_free_data_contents() to free @a der_out when it is no longer * needed. * * The message will be encrypted using the send subkey of @a auth_context if it * is present, or the session key otherwise. If neither key is present, the * credentials will not be encrypted, and the message should only be sent over * a secure channel. No replay cache entry is used in this case. * * @retval * 0 Success * @retval * ENOMEM Insufficient memory * @retval * KRB5_RC_REQUIRED Message replay detection requires @a rcache parameter * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_ncred(krb5_context context, krb5_auth_context auth_context, krb5_creds **creds, krb5_data **der_out, krb5_replay_data *rdata_out); /** * Format a @c KRB-CRED message for a single set of credentials. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] creds Pointer to credentials * @param [out] der_out Encoded credentials * @param [out] rdata_out Replay cache data (NULL if not needed) * * This is a convenience function that calls krb5_mk_ncred() with a single set * of credentials. * * @retval * 0 Success * @retval * ENOMEM Insufficient memory * @retval * KRB5_RC_REQUIRED Message replay detection requires @a rcache parameter * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_mk_1cred(krb5_context context, krb5_auth_context auth_context, krb5_creds *creds, krb5_data **der_out, krb5_replay_data *rdata_out); /** * Read and validate a @c KRB-CRED message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] creddata @c KRB-CRED message * @param [out] creds_out Null-terminated array of forwarded credentials * @param [out] rdata_out Replay data (NULL if not needed) * * @note The @a rdata_out argument is required if the * #KRB5_AUTH_CONTEXT_RET_TIME or #KRB5_AUTH_CONTEXT_RET_SEQUENCE flag is set * in @a auth_context.` * * @a creddata will be decrypted using the receiving subkey if it is present in * @a auth_context, or the session key if the receiving subkey is not present * or fails to decrypt the message. * * Use krb5_free_tgt_creds() to free @a creds_out when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_rd_cred(krb5_context context, krb5_auth_context auth_context, krb5_data *creddata, krb5_creds ***creds_out, krb5_replay_data *rdata_out); /** * Get a forwarded TGT and format a @c KRB-CRED message. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] rhost Remote host * @param [in] client Client principal of TGT * @param [in] server Principal of server to receive TGT * @param [in] cc Credential cache handle (NULL to use default) * @param [in] forwardable Whether TGT should be forwardable * @param [out] outbuf KRB-CRED message * * Get a TGT for use at the remote host @a rhost and format it into a KRB-CRED * message. If @a rhost is NULL and @a server is of type #KRB5_NT_SRV_HST, * the second component of @a server will be used. * * @retval * 0 Success * @retval * ENOMEM Insufficient memory * @retval * KRB5_PRINC_NOMATCH Requested principal and ticket do not match * @retval * KRB5_NO_TKT_SUPPLIED Request did not supply a ticket * @retval * KRB5_CC_BADNAME Credential cache name or principal name malformed * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_fwd_tgt_creds(krb5_context context, krb5_auth_context auth_context, const char *rhost, krb5_principal client, krb5_principal server, krb5_ccache cc, int forwardable, krb5_data *outbuf); /** * Create and initialize an authentication context. * * @param [in] context Library context * @param [out] auth_context Authentication context * * This function creates an authentication context to hold configuration and * state relevant to krb5 functions for authenticating principals and * protecting messages once authentication has occurred. * * By default, flags for the context are set to enable the use of the replay * cache (#KRB5_AUTH_CONTEXT_DO_TIME), but not sequence numbers. Use * krb5_auth_con_setflags() to change the flags. * * The allocated @a auth_context must be freed with krb5_auth_con_free() when * it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_init(krb5_context context, krb5_auth_context *auth_context); /** * Free a krb5_auth_context structure. * * @param [in] context Library context * @param [in] auth_context Authentication context to be freed * * This function frees an auth context allocated by krb5_auth_con_init(). * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_auth_con_free(krb5_context context, krb5_auth_context auth_context); /** * Set a flags field in a krb5_auth_context structure. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] flags Flags bit mask * * Valid values for @a flags are: * @li #KRB5_AUTH_CONTEXT_DO_TIME Use timestamps * @li #KRB5_AUTH_CONTEXT_RET_TIME Save timestamps * @li #KRB5_AUTH_CONTEXT_DO_SEQUENCE Use sequence numbers * @li #KRB5_AUTH_CONTEXT_RET_SEQUENCE Save sequence numbers * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setflags(krb5_context context, krb5_auth_context auth_context, krb5_int32 flags); /** * Retrieve flags from a krb5_auth_context structure. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] flags Flags bit mask * * Valid values for @a flags are: * @li #KRB5_AUTH_CONTEXT_DO_TIME Use timestamps * @li #KRB5_AUTH_CONTEXT_RET_TIME Save timestamps * @li #KRB5_AUTH_CONTEXT_DO_SEQUENCE Use sequence numbers * @li #KRB5_AUTH_CONTEXT_RET_SEQUENCE Save sequence numbers * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getflags(krb5_context context, krb5_auth_context auth_context, krb5_int32 *flags); /** * Set a checksum callback in an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] func Checksum callback * @param [in] data Callback argument * * Set a callback to obtain checksum data in krb5_mk_req(). The callback will * be invoked after the subkey and local sequence number are stored in @a * auth_context. * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_auth_con_set_checksum_func( krb5_context context, krb5_auth_context auth_context, krb5_mk_req_checksum_func func, void *data); /** * Get the checksum callback from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] func Checksum callback * @param [out] data Callback argument * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_auth_con_get_checksum_func( krb5_context context, krb5_auth_context auth_context, krb5_mk_req_checksum_func *func, void **data); /** * Set the local and remote addresses in an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] local_addr Local address * @param [in] remote_addr Remote address * * This function releases the storage assigned to the contents of the local and * remote addresses of @a auth_context and then sets them to @a local_addr and * @a remote_addr respectively. * * @sa krb5_auth_con_genaddrs() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV_WRONG krb5_auth_con_setaddrs(krb5_context context, krb5_auth_context auth_context, krb5_address *local_addr, krb5_address *remote_addr); /** * Retrieve address fields from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] local_addr Local address (NULL if not needed) * @param [out] remote_addr Remote address (NULL if not needed) * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getaddrs(krb5_context context, krb5_auth_context auth_context, krb5_address **local_addr, krb5_address **remote_addr); /** * Set local and remote port fields in an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] local_port Local port * @param [in] remote_port Remote port * * This function releases the storage assigned to the contents of the local and * remote ports of @a auth_context and then sets them to @a local_port and @a * remote_port respectively. * * @sa krb5_auth_con_genaddrs() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setports(krb5_context context, krb5_auth_context auth_context, krb5_address *local_port, krb5_address *remote_port); /** * Set the session key in an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] keyblock User key * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setuseruserkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock *keyblock); /** * Retrieve the session key from an auth context as a keyblock. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] keyblock Session key * * This function creates a keyblock containing the session key from @a * auth_context. Use krb5_free_keyblock() to free @a keyblock when it is no * longer needed * * @retval 0 Success. Otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock); /** * Retrieve the session key from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] key Session key * * This function sets @a key to the session key from @a auth_context. Use * krb5_k_free_key() to release @a key when it is no longer needed. * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getkey_k(krb5_context context, krb5_auth_context auth_context, krb5_key *key); /** * Retrieve the send subkey from an auth context as a keyblock. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [out] keyblock Send subkey * * This function creates a keyblock containing the send subkey from @a * auth_context. Use krb5_free_keyblock() to free @a keyblock when it is no * longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getsendsubkey(krb5_context ctx, krb5_auth_context ac, krb5_keyblock **keyblock); /** * Retrieve the send subkey from an auth context. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [out] key Send subkey * * This function sets @a key to the send subkey from @a auth_context. Use * krb5_k_free_key() to release @a key when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getsendsubkey_k(krb5_context ctx, krb5_auth_context ac, krb5_key *key); /** * Retrieve the receiving subkey from an auth context as a keyblock. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [out] keyblock Receiving subkey * * This function creates a keyblock containing the receiving subkey from @a * auth_context. Use krb5_free_keyblock() to free @a keyblock when it is no * longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getrecvsubkey(krb5_context ctx, krb5_auth_context ac, krb5_keyblock **keyblock); /** * Retrieve the receiving subkey from an auth context as a keyblock. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [out] key Receiving subkey * * This function sets @a key to the receiving subkey from @a auth_context. Use * krb5_k_free_key() to release @a key when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getrecvsubkey_k(krb5_context ctx, krb5_auth_context ac, krb5_key *key); /** * Set the send subkey in an auth context with a keyblock. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [in] keyblock Send subkey * * This function sets the send subkey in @a ac to a copy of @a keyblock. * * @retval 0 Success. Otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setsendsubkey(krb5_context ctx, krb5_auth_context ac, krb5_keyblock *keyblock); /** * Set the send subkey in an auth context. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [out] key Send subkey * * This function sets the send subkey in @a ac to @a key, incrementing its * reference count. * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setsendsubkey_k(krb5_context ctx, krb5_auth_context ac, krb5_key key); /** * Set the receiving subkey in an auth context with a keyblock. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [in] keyblock Receiving subkey * * This function sets the receiving subkey in @a ac to a copy of @a keyblock. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setrecvsubkey(krb5_context ctx, krb5_auth_context ac, krb5_keyblock *keyblock); /** * Set the receiving subkey in an auth context. * * @param [in] ctx Library context * @param [in] ac Authentication context * @param [in] key Receiving subkey * * This function sets the receiving subkey in @a ac to @a key, incrementing its * reference count. * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setrecvsubkey_k(krb5_context ctx, krb5_auth_context ac, krb5_key key); #if KRB5_DEPRECATED /** @deprecated Replaced by krb5_auth_con_getsendsubkey(). */ KRB5_ATTR_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_auth_con_getlocalsubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock); /** @deprecated Replaced by krb5_auth_con_getrecvsubkey(). */ KRB5_ATTR_DEPRECATED krb5_error_code KRB5_CALLCONV krb5_auth_con_getremotesubkey(krb5_context context, krb5_auth_context auth_context, krb5_keyblock **keyblock); #endif /** * Retrieve the local sequence number from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] seqnumber Local sequence number * * Retrieve the local sequence number from @a auth_context and return it in @a * seqnumber. The #KRB5_AUTH_CONTEXT_DO_SEQUENCE flag must be set in @a * auth_context for this function to be useful. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getlocalseqnumber(krb5_context context, krb5_auth_context auth_context, krb5_int32 *seqnumber); /** * Retrieve the remote sequence number from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] seqnumber Remote sequence number * * Retrieve the remote sequence number from @a auth_context and return it in @a * seqnumber. The #KRB5_AUTH_CONTEXT_DO_SEQUENCE flag must be set in @a * auth_context for this function to be useful. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getremoteseqnumber(krb5_context context, krb5_auth_context auth_context, krb5_int32 *seqnumber); /** * Cause an auth context to use cipher state. * * @param [in] context Library context * @param [in] auth_context Authentication context * * Prepare @a auth_context to use cipher state when krb5_mk_priv() or * krb5_rd_priv() encrypt or decrypt data. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_initivector(krb5_context context, krb5_auth_context auth_context); /** * Set the replay cache in an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] rcache Replay cache haddle * * This function sets the replay cache in @a auth_context to @a rcache. @a * rcache will be closed when @a auth_context is freed, so the caller should * relinquish that responsibility. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_setrcache(krb5_context context, krb5_auth_context auth_context, krb5_rcache rcache); /** * Retrieve the replay cache from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] rcache Replay cache handle * * This function fetches the replay cache from @a auth_context. The caller * should not close @a rcache. * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV_WRONG krb5_auth_con_getrcache(krb5_context context, krb5_auth_context auth_context, krb5_rcache *rcache); /** * Retrieve the authenticator from an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [out] authenticator Authenticator * * Use krb5_free_authenticator() to free @a authenticator when it is no longer * needed. * * @retval 0 Success. Otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_getauthenticator(krb5_context context, krb5_auth_context auth_context, krb5_authenticator **authenticator); /** * Set checksum type in an an auth context. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] cksumtype Checksum type * * This function sets the checksum type in @a auth_context to be used by * krb5_mk_req() for the authenticator checksum. * * @retval 0 Success. Otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_set_req_cksumtype(krb5_context context, krb5_auth_context auth_context, krb5_cksumtype cksumtype); #define KRB5_REALM_BRANCH_CHAR '.' /* * end "func-proto.h" */ /* * begin stuff from libos.h */ /** * @brief Read a password from keyboard input. * * @param [in] context Library context * @param [in] prompt First user prompt when reading password * @param [in] prompt2 Second user prompt (NULL to prompt only once) * @param [out] return_pwd Returned password * @param [in,out] size_return On input, maximum size of password; on output, * size of password read * * This function reads a password from keyboard input and stores it in @a * return_pwd. @a size_return should be set by the caller to the amount of * storage space available in @a return_pwd; on successful return, it will be * set to the length of the password read. * * @a prompt is printed to the terminal, followed by ": ", and then a password * is read from the keyboard. * * If @a prompt2 is NULL, the password is read only once. Otherwise, @a * prompt2 is printed to the terminal and a second password is read. If the * two passwords entered are not identical, KRB5_LIBOS_BADPWDMATCH is returned. * * Echoing is turned off when the password is read. * * @retval * 0 Success * @return * Error in reading or verifying the password * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_read_password(krb5_context context, const char *prompt, const char *prompt2, char *return_pwd, unsigned int *size_return); /** * Convert a principal name to a local name. * * @param [in] context Library context * @param [in] aname Principal name * @param [in] lnsize_in Space available in @a lname * @param [out] lname Local name buffer to be filled in * * If @a aname does not correspond to any local account, KRB5_LNAME_NOTRANS is * returned. If @a lnsize_in is too small for the local name, * KRB5_CONFIG_NOTENUFSPACE is returned. * * Local names, rather than principal names, can be used by programs that * translate to an environment-specific name (for example, a user account * name). * * @retval * 0 Success * @retval * System errors * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_aname_to_localname(krb5_context context, krb5_const_principal aname, int lnsize_in, char *lname); /** * Get the Kerberos realm names for a host. * * @param [in] context Library context * @param [in] host Host name (or NULL) * @param [out] realmsp Null-terminated list of realm names * * Fill in @a realmsp with a pointer to a null-terminated list of realm names. * If there are no known realms for the host, a list containing the referral * (empty) realm is returned. * * If @a host is NULL, the local host's realms are determined. * * Use krb5_free_host_realm() to release @a realmsp when it is no longer * needed. * * @retval * 0 Success * @retval * ENOMEM Insufficient memory * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_host_realm(krb5_context context, const char *host, char ***realmsp); /** * * @param [in] context Library context * @param [in] hdata Host name (or NULL) * @param [out] realmsp Null-terminated list of realm names * * Fill in @a realmsp with a pointer to a null-terminated list of realm names * obtained through heuristics or insecure resolution methods which have lower * priority than KDC referrals. * * If @a host is NULL, the local host's realms are determined. * * Use krb5_free_host_realm() to release @a realmsp when it is no longer * needed. */ krb5_error_code KRB5_CALLCONV krb5_get_fallback_host_realm(krb5_context context, krb5_data *hdata, char ***realmsp); /** * Free the memory allocated by krb5_get_host_realm(). * * @param [in] context Library context * @param [in] realmlist List of realm names to be released * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_free_host_realm(krb5_context context, char *const *realmlist); /** * Determine if a principal is authorized to log in as a local user. * * @param [in] context Library context * @param [in] principal Principal name * @param [in] luser Local username * * Determine whether @a principal is authorized to log in as a local user @a * luser. * * @retval * TRUE Principal is authorized to log in as user; FALSE otherwise. */ krb5_boolean KRB5_CALLCONV krb5_kuserok(krb5_context context, krb5_principal principal, const char *luser); /** * Generate auth context addresses from a connected socket. * * @param [in] context Library context * @param [in] auth_context Authentication context * @param [in] infd Connected socket descriptor * @param [in] flags Flags * * This function sets the local and/or remote addresses in @a auth_context * based on the local and remote endpoints of the socket @a infd. The * following flags determine the operations performed: * * @li #KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR Generate local address. * @li #KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR Generate remote address. * @li #KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR Generate local address and port. * @li #KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR Generate remote address and port. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_auth_con_genaddrs(krb5_context context, krb5_auth_context auth_context, int infd, int flags); /** * Set time offset field in a krb5_context structure. * * @param [in] context Library context * @param [in] seconds Real time, seconds portion * @param [in] microseconds Real time, microseconds portion * * This function sets the time offset in @a context to the difference between * the system time and the real time as determined by @a seconds and @a * microseconds. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_set_real_time(krb5_context context, krb5_timestamp seconds, krb5_int32 microseconds); /** * Return the time offsets from the os context. * * @param [in] context Library context * @param [out] seconds Time offset, seconds portion * @param [out] microseconds Time offset, microseconds portion * * This function returns the time offsets in @a context. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_time_offsets(krb5_context context, krb5_timestamp *seconds, krb5_int32 *microseconds); /* str_conv.c */ /** * Convert a string to an encryption type. * * @param [in] string String to convert to an encryption type * @param [out] enctypep Encryption type * * @retval 0 Success; otherwise - EINVAL */ krb5_error_code KRB5_CALLCONV krb5_string_to_enctype(char *string, krb5_enctype *enctypep); /** * Convert a string to a salt type. * * @param [in] string String to convert to an encryption type * @param [out] salttypep Salt type to be filled in * * @retval 0 Success; otherwise - EINVAL */ krb5_error_code KRB5_CALLCONV krb5_string_to_salttype(char *string, krb5_int32 *salttypep); /** * Convert a string to a checksum type. * * @param [in] string String to be converted * @param [out] cksumtypep Checksum type to be filled in * * @retval 0 Success; otherwise - EINVAL */ krb5_error_code KRB5_CALLCONV krb5_string_to_cksumtype(char *string, krb5_cksumtype *cksumtypep); /** * Convert a string to a timestamp. * * @param [in] string String to be converted * @param [out] timestampp Pointer to timestamp * * @retval 0 Success; otherwise - EINVAL */ krb5_error_code KRB5_CALLCONV krb5_string_to_timestamp(char *string, krb5_timestamp *timestampp); /** * Convert a string to a delta time value. * * @param [in] string String to be converted * @param [out] deltatp Delta time to be filled in * * @retval 0 Success; otherwise - KRB5_DELTAT_BADFORMAT */ krb5_error_code KRB5_CALLCONV krb5_string_to_deltat(char *string, krb5_deltat *deltatp); /** * Convert an encryption type to a string. * * @param [in] enctype Encryption type * @param [out] buffer Buffer to hold encryption type string * @param [in] buflen Storage available in @a buffer * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_enctype_to_string(krb5_enctype enctype, char *buffer, size_t buflen); /** * Convert an encryption type to a name or alias. * * @param [in] enctype Encryption type * @param [in] shortest Flag * @param [out] buffer Buffer to hold encryption type string * @param [in] buflen Storage available in @a buffer * * If @a shortest is FALSE, this function returns the enctype's canonical name * (like "aes128-cts-hmac-sha1-96"). If @a shortest is TRUE, it return the * enctype's shortest alias (like "aes128-cts"). * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_enctype_to_name(krb5_enctype enctype, krb5_boolean shortest, char *buffer, size_t buflen); /** * Convert a salt type to a string. * * @param [in] salttype Salttype to convert * @param [out] buffer Buffer to receive the converted string * @param [in] buflen Storage available in @a buffer * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_salttype_to_string(krb5_int32 salttype, char *buffer, size_t buflen); /** * Convert a checksum type to a string. * * @param [in] cksumtype Checksum type * @param [out] buffer Buffer to hold converted checksum type * @param [in] buflen Storage available in @a buffer * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_cksumtype_to_string(krb5_cksumtype cksumtype, char *buffer, size_t buflen); /** * Convert a timestamp to a string. * * @param [in] timestamp Timestamp to convert * @param [out] buffer Buffer to hold converted timestamp * @param [in] buflen Storage available in @a buffer * * The string is returned in the locale's appropriate date and time * representation. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_timestamp_to_string(krb5_timestamp timestamp, char *buffer, size_t buflen); /** * Convert a timestamp to a string, with optional output padding * * @param [in] timestamp Timestamp to convert * @param [out] buffer Buffer to hold the converted timestamp * @param [in] buflen Length of buffer * @param [in] pad Optional value to pad @a buffer if converted * timestamp does not fill it * * If @a pad is not NULL, @a buffer is padded out to @a buflen - 1 characters * with the value of *@a pad. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_timestamp_to_sfstring(krb5_timestamp timestamp, char *buffer, size_t buflen, char *pad); /** * Convert a relative time value to a string. * * @param [in] deltat Relative time value to convert * @param [out] buffer Buffer to hold time string * @param [in] buflen Storage available in @a buffer * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_deltat_to_string(krb5_deltat deltat, char *buffer, size_t buflen); /* The name of the Kerberos ticket granting service... and its size */ #define KRB5_TGS_NAME "krbtgt" #define KRB5_TGS_NAME_SIZE 6 /* flags for recvauth */ #define KRB5_RECVAUTH_SKIP_VERSION 0x0001 #define KRB5_RECVAUTH_BADAUTHVERS 0x0002 /* initial ticket api functions */ /** Text for prompt used in prompter callback function. */ typedef struct _krb5_prompt { char *prompt; /**< The prompt to show to the user */ int hidden; /**< Boolean; informative prompt or hidden (e.g. PIN) */ krb5_data *reply; /**< Must be allocated before call to prompt routine */ } krb5_prompt; /** Pointer to a prompter callback function. */ typedef krb5_error_code (KRB5_CALLCONV *krb5_prompter_fct)(krb5_context context, void *data, const char *name, const char *banner, int num_prompts, krb5_prompt prompts[]); /** * Prompt user for password. * * @param [in] context Library context * @param data Unused (callback argument) * @param [in] name Name to output during prompt * @param [in] banner Banner to output during prompt * @param [in] num_prompts Number of prompts in @a prompts * @param [in] prompts Array of prompts and replies * * This function is intended to be used as a prompter callback for * krb5_get_init_creds_password() or krb5_init_creds_init(). * * Writes @a name and @a banner to stdout, each followed by a newline, then * writes each prompt field in the @a prompts array, followed by ": ", and sets * the reply field of the entry to a line of input read from stdin. If the * hidden flag is set for a prompt, then terminal echoing is turned off when * input is read. * * @retval * 0 Success * @return * Kerberos error codes * */ krb5_error_code KRB5_CALLCONV krb5_prompter_posix(krb5_context context, void *data, const char *name, const char *banner, int num_prompts, krb5_prompt prompts[]); /** * Long-term password responder question * * This question is asked when the long-term password is needed. It has no * challenge and the response is simply the password string. * * @version New in 1.11 */ #define KRB5_RESPONDER_QUESTION_PASSWORD "password" /** * OTP responder question * * The OTP responder question is asked when the KDC indicates that an OTP * value is required in order to complete the authentication. The JSON format * of the challenge is: * * @n { * @n "service": , * @n "tokenInfo": [ * @n { * @n "flags": , * @n "vendor": , * @n "challenge": , * @n "length": , * @n "format": , * @n "tokenID": , * @n "algID": , * @n }, * @n ... * @n ] * @n } * * The answer to the question MUST be JSON formatted: * * @n { * @n "tokeninfo": , * @n "value": , * @n "pin": , * @n } * * For more detail, please see RFC 6560. * * @version New in 1.11 */ #define KRB5_RESPONDER_QUESTION_OTP "otp" /** * These format constants identify the format of the token value. */ #define KRB5_RESPONDER_OTP_FORMAT_DECIMAL 0 #define KRB5_RESPONDER_OTP_FORMAT_HEXADECIMAL 1 #define KRB5_RESPONDER_OTP_FORMAT_ALPHANUMERIC 2 /** * This flag indicates that the token value MUST be collected. */ #define KRB5_RESPONDER_OTP_FLAGS_COLLECT_TOKEN 0x0001 /** * This flag indicates that the PIN value MUST be collected. */ #define KRB5_RESPONDER_OTP_FLAGS_COLLECT_PIN 0x0002 /** * This flag indicates that the token is now in re-synchronization mode with * the server. The user is expected to reply with the next code displayed on * the token. */ #define KRB5_RESPONDER_OTP_FLAGS_NEXTOTP 0x0004 /** * This flag indicates that the PIN MUST be returned as a separate item. This * flag only takes effect if KRB5_RESPONDER_OTP_FLAGS_COLLECT_PIN is set. If * this flag is not set, the responder may either concatenate PIN + token value * and store it as "value" in the answer or it may return them separately. If * they are returned separately, they will be concatenated internally. */ #define KRB5_RESPONDER_OTP_FLAGS_SEPARATE_PIN 0x0008 /** * PKINIT responder question * * The PKINIT responder question is asked when the client needs a password * that's being used to protect key information, and is formatted as a JSON * object. A specific identity's flags value, if not zero, is the bitwise-OR * of one or more of the KRB5_RESPONDER_PKINIT_FLAGS_TOKEN_* flags defined * below, and possibly other flags to be added later. Any resemblance to * similarly-named CKF_* values in the PKCS#11 API should not be depended on. * * @n { * @n identity : flags , * @n ... * @n } * * The answer to the question MUST be JSON formatted: * * @n { * @n identity : password , * @n ... * @n } * * @version New in 1.12 */ #define KRB5_RESPONDER_QUESTION_PKINIT "pkinit" /** * This flag indicates that an incorrect PIN was supplied at least once since * the last time the correct PIN was supplied. */ #define KRB5_RESPONDER_PKINIT_FLAGS_TOKEN_USER_PIN_COUNT_LOW (1 << 0) /** * This flag indicates that supplying an incorrect PIN will cause the token to * lock itself. */ #define KRB5_RESPONDER_PKINIT_FLAGS_TOKEN_USER_PIN_FINAL_TRY (1 << 1) /** * This flag indicates that the user PIN is locked, and you can't log in to the * token with it. */ #define KRB5_RESPONDER_PKINIT_FLAGS_TOKEN_USER_PIN_LOCKED (1 << 2) /** * A container for a set of preauthentication questions and answers * * A responder context is supplied by the krb5 authentication system to a @ref * krb5_responder_fn callback. It contains a list of questions and can receive * answers. Questions contained in a responder context can be listed using * krb5_responder_list_questions(), retrieved using * krb5_responder_get_challenge(), or answered using * krb5_responder_set_answer(). The form of a question's challenge and * answer depend on the question name. * * @version New in 1.11 */ typedef struct krb5_responder_context_st *krb5_responder_context; /** * List the question names contained in the responder context. * * @param [in] ctx Library context * @param [in] rctx Responder context * * Return a pointer to a null-terminated list of question names which are * present in @a rctx. The pointer is an alias, valid only as long as the * lifetime of @a rctx, and should not be modified or freed by the caller. A * question's challenge can be retrieved using krb5_responder_get_challenge() * and answered using krb5_responder_set_answer(). * * @version New in 1.11 */ const char * const * KRB5_CALLCONV krb5_responder_list_questions(krb5_context ctx, krb5_responder_context rctx); /** * Retrieve the challenge data for a given question in the responder context. * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [in] question Question name * * Return a pointer to a C string containing the challenge for @a question * within @a rctx, or NULL if the question is not present in @a rctx. The * structure of the question depends on the question name, but will always be * printable UTF-8 text. The returned pointer is an alias, valid only as long * as the lifetime of @a rctx, and should not be modified or freed by the * caller. * * @version New in 1.11 */ const char * KRB5_CALLCONV krb5_responder_get_challenge(krb5_context ctx, krb5_responder_context rctx, const char *question); /** * Answer a named question in the responder context. * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [in] question Question name * @param [in] answer The string to set (MUST be printable UTF-8) * * This function supplies an answer to @a question within @a rctx. The * appropriate form of the answer depends on the question name. * * @retval EINVAL @a question is not present within @a rctx * * @version New in 1.11 */ krb5_error_code KRB5_CALLCONV krb5_responder_set_answer(krb5_context ctx, krb5_responder_context rctx, const char *question, const char *answer); /** * Responder function for an initial credential exchange. * * @param [in] ctx Library context * @param [in] data Callback data * @param [in] rctx Responder context * * A responder function is like a prompter function, but is used for handling * questions and answers as potentially complex data types. Client * preauthentication modules will insert a set of named "questions" into * the responder context. Each question may optionally contain a challenge. * This challenge is printable UTF-8, but may be an encoded value. The * precise encoding and contents of the challenge are specific to the question * asked. When the responder is called, it should answer all the questions it * understands. Like the challenge, the answer MUST be printable UTF-8, but * may contain structured/encoded data formatted to the expected answer format * of the question. * * If a required question is unanswered, the prompter may be called. */ typedef krb5_error_code (KRB5_CALLCONV *krb5_responder_fn)(krb5_context ctx, void *data, krb5_responder_context rctx); typedef struct _krb5_responder_otp_tokeninfo { krb5_flags flags; krb5_int32 format; /* -1 when not specified. */ krb5_int32 length; /* -1 when not specified. */ char *vendor; char *challenge; char *token_id; char *alg_id; } krb5_responder_otp_tokeninfo; typedef struct _krb5_responder_otp_challenge { char *service; krb5_responder_otp_tokeninfo **tokeninfo; } krb5_responder_otp_challenge; /** * Decode the KRB5_RESPONDER_QUESTION_OTP to a C struct. * * A convenience function which parses the KRB5_RESPONDER_QUESTION_OTP * question challenge data, making it available in native C. The main feature * of this function is the ability to interact with OTP tokens without parsing * the JSON. * * The returned value must be passed to krb5_responder_otp_challenge_free() to * be freed. * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [out] chl Challenge structure * * @version New in 1.11 */ krb5_error_code KRB5_CALLCONV krb5_responder_otp_get_challenge(krb5_context ctx, krb5_responder_context rctx, krb5_responder_otp_challenge **chl); /** * Answer the KRB5_RESPONDER_QUESTION_OTP question. * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [in] ti The index of the tokeninfo selected * @param [in] value The value to set, or NULL for none * @param [in] pin The pin to set, or NULL for none * * @version New in 1.11 */ krb5_error_code KRB5_CALLCONV krb5_responder_otp_set_answer(krb5_context ctx, krb5_responder_context rctx, size_t ti, const char *value, const char *pin); /** * Free the value returned by krb5_responder_otp_get_challenge(). * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [in] chl The challenge to free * * @version New in 1.11 */ void KRB5_CALLCONV krb5_responder_otp_challenge_free(krb5_context ctx, krb5_responder_context rctx, krb5_responder_otp_challenge *chl); typedef struct _krb5_responder_pkinit_identity { char *identity; krb5_int32 token_flags; /* 0 when not specified or not applicable. */ } krb5_responder_pkinit_identity; typedef struct _krb5_responder_pkinit_challenge { krb5_responder_pkinit_identity **identities; } krb5_responder_pkinit_challenge; /** * Decode the KRB5_RESPONDER_QUESTION_PKINIT to a C struct. * * A convenience function which parses the KRB5_RESPONDER_QUESTION_PKINIT * question challenge data, making it available in native C. The main feature * of this function is the ability to read the challenge without parsing * the JSON. * * The returned value must be passed to krb5_responder_pkinit_challenge_free() * to be freed. * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [out] chl_out Challenge structure * * @version New in 1.12 */ krb5_error_code KRB5_CALLCONV krb5_responder_pkinit_get_challenge(krb5_context ctx, krb5_responder_context rctx, krb5_responder_pkinit_challenge **chl_out); /** * Answer the KRB5_RESPONDER_QUESTION_PKINIT question for one identity. * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [in] identity The identity for which a PIN is being supplied * @param [in] pin The provided PIN, or NULL for none * * @version New in 1.12 */ krb5_error_code KRB5_CALLCONV krb5_responder_pkinit_set_answer(krb5_context ctx, krb5_responder_context rctx, const char *identity, const char *pin); /** * Free the value returned by krb5_responder_pkinit_get_challenge(). * * @param [in] ctx Library context * @param [in] rctx Responder context * @param [in] chl The challenge to free * * @version New in 1.12 */ void KRB5_CALLCONV krb5_responder_pkinit_challenge_free(krb5_context ctx, krb5_responder_context rctx, krb5_responder_pkinit_challenge *chl); /** Store options for @c _krb5_get_init_creds */ typedef struct _krb5_get_init_creds_opt { krb5_flags flags; krb5_deltat tkt_life; krb5_deltat renew_life; int forwardable; int proxiable; krb5_enctype *etype_list; int etype_list_length; krb5_address **address_list; krb5_preauthtype *preauth_list; int preauth_list_length; krb5_data *salt; } krb5_get_init_creds_opt; #define KRB5_GET_INIT_CREDS_OPT_TKT_LIFE 0x0001 #define KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE 0x0002 #define KRB5_GET_INIT_CREDS_OPT_FORWARDABLE 0x0004 #define KRB5_GET_INIT_CREDS_OPT_PROXIABLE 0x0008 #define KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST 0x0010 #define KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST 0x0020 #define KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST 0x0040 #define KRB5_GET_INIT_CREDS_OPT_SALT 0x0080 #define KRB5_GET_INIT_CREDS_OPT_CHG_PWD_PRMPT 0x0100 #define KRB5_GET_INIT_CREDS_OPT_CANONICALIZE 0x0200 #define KRB5_GET_INIT_CREDS_OPT_ANONYMOUS 0x0400 /** * Allocate a new initial credential options structure. * * @param [in] context Library context * @param [out] opt New options structure * * This function is the preferred way to create an options structure for * getting initial credentials, and is required to make use of certain options. * Use krb5_get_init_creds_opt_free() to free @a opt when it is no longer * needed. * * @retval 0 - Success; Kerberos errors otherwise. */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_alloc(krb5_context context, krb5_get_init_creds_opt **opt); /** * Free initial credential options. * * @param [in] context Library context * @param [in] opt Options structure to free * * @sa krb5_get_init_creds_opt_alloc() */ void KRB5_CALLCONV krb5_get_init_creds_opt_free(krb5_context context, krb5_get_init_creds_opt *opt); /** @deprecated Use krb5_get_init_creds_opt_alloc() instead. */ void KRB5_CALLCONV krb5_get_init_creds_opt_init(krb5_get_init_creds_opt *opt); /** * Set the ticket lifetime in initial credential options. * * @param [in] opt Options structure * @param [in] tkt_life Ticket lifetime */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_tkt_life(krb5_get_init_creds_opt *opt, krb5_deltat tkt_life); /** * Set the ticket renewal lifetime in initial credential options. * * @param [in] opt Pointer to @a options field * @param [in] renew_life Ticket renewal lifetime */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_renew_life(krb5_get_init_creds_opt *opt, krb5_deltat renew_life); /** * Set or unset the forwardable flag in initial credential options. * * @param [in] opt Options structure * @param [in] forwardable Whether credentials should be forwardable */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_forwardable(krb5_get_init_creds_opt *opt, int forwardable); /** * Set or unset the proxiable flag in initial credential options. * * @param [in] opt Options structure * @param [in] proxiable Whether credentials should be proxiable */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_proxiable(krb5_get_init_creds_opt *opt, int proxiable); /** * Set or unset the canonicalize flag in initial credential options. * * @param [in] opt Options structure * @param [in] canonicalize Whether to canonicalize client principal */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_canonicalize(krb5_get_init_creds_opt *opt, int canonicalize); /** * Set or unset the anonymous flag in initial credential options. * * @param [in] opt Options structure * @param [in] anonymous Whether to make an anonymous request * * This function may be used to request anonymous credentials from the KDC by * setting @a anonymous to non-zero. Note that anonymous credentials are only * a request; clients must verify that credentials are anonymous if that is a * requirement. */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_anonymous(krb5_get_init_creds_opt *opt, int anonymous); /** * Set allowable encryption types in initial credential options. * * @param [in] opt Options structure * @param [in] etype_list Array of encryption types * @param [in] etype_list_length Length of @a etype_list */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_etype_list(krb5_get_init_creds_opt *opt, krb5_enctype *etype_list, int etype_list_length); /** * Set address restrictions in initial credential options. * * @param [in] opt Options structure * @param [in] addresses Null-terminated array of addresses */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_address_list(krb5_get_init_creds_opt *opt, krb5_address **addresses); /** * Set preauthentication types in initial credential options. * * @param [in] opt Options structure * @param [in] preauth_list Array of preauthentication types * @param [in] preauth_list_length Length of @a preauth_list * * This function can be used to perform optimistic preauthentication when * getting initial credentials, in combination with * krb5_get_init_creds_opt_set_salt() and krb5_get_init_creds_opt_set_pa(). */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt, krb5_preauthtype *preauth_list, int preauth_list_length); /** * Set salt for optimistic preauthentication in initial credential options. * * @param [in] opt Options structure * @param [in] salt Salt data * * When getting initial credentials with a password, a salt string it used to * convert the password to a key. Normally this salt is obtained from the * first KDC reply, but when performing optimistic preauthentication, the * client may need to supply the salt string with this function. */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt, krb5_data *salt); /** * Set or unset change-password-prompt flag in initial credential options. * * @param [in] opt Options structure * @param [in] prompt Whether to prompt to change password * * This flag is on by default. It controls whether * krb5_get_init_creds_password() will react to an expired-password error by * prompting for a new password and attempting to change the old one. */ void KRB5_CALLCONV krb5_get_init_creds_opt_set_change_password_prompt(krb5_get_init_creds_opt *opt, int prompt); /** Generic preauth option attribute/value pairs */ typedef struct _krb5_gic_opt_pa_data { char *attr; char *value; } krb5_gic_opt_pa_data; /** * Supply options for preauthentication in initial credential options. * * @param [in] context Library context * @param [in] opt Options structure * @param [in] attr Preauthentication option name * @param [in] value Preauthentication option value * * This function allows the caller to supply options for preauthentication. * The values of @a attr and @a value are supplied to each preauthentication * module available within @a context. */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_pa(krb5_context context, krb5_get_init_creds_opt *opt, const char *attr, const char *value); /** * Set location of FAST armor ccache in initial credential options. * * @param [in] context Library context * @param [in] opt Options * @param [in] fast_ccache_name Credential cache name * * Sets the location of a credential cache containing an armor ticket to * protect an initial credential exchange using the FAST protocol extension. * * In version 1.7, setting an armor ccache requires that FAST be used for the * exchange. In version 1.8 or later, setting the armor ccache causes FAST to * be used if the KDC supports it; krb5_get_init_creds_opt_set_fast_flags() * must be used to require that FAST be used. */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_fast_ccache_name(krb5_context context, krb5_get_init_creds_opt *opt, const char *fast_ccache_name); /** * Set FAST armor cache in initial credential options. * * @param [in] context Library context * @param [in] opt Options * @param [in] ccache Credential cache handle * * This function is similar to krb5_get_init_creds_opt_set_fast_ccache_name(), * but uses a credential cache handle instead of a name. * * @version New in 1.9 */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_fast_ccache(krb5_context context, krb5_get_init_creds_opt *opt, krb5_ccache ccache); /** * Set an input credential cache in initial credential options. * * @param [in] context Library context * @param [in] opt Options * @param [in] ccache Credential cache handle * * If an input credential cache is set, then the krb5_get_init_creds family of * APIs will read settings from it. Setting an input ccache is desirable when * the application wishes to perform authentication in the same way (using the * same preauthentication mechanisms, and making the same non-security- * sensitive choices) as the previous authentication attempt, which stored * information in the passed-in ccache. * * @version New in 1.11 */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_in_ccache(krb5_context context, krb5_get_init_creds_opt *opt, krb5_ccache ccache); /** * Set an output credential cache in initial credential options. * * @param [in] context Library context * @param [in] opt Options * @param [in] ccache Credential cache handle * * If an output credential cache is set, then the krb5_get_init_creds family of * APIs will write credentials to it. Setting an output ccache is desirable * both because it simplifies calling code and because it permits the * krb5_get_init_creds APIs to write out configuration information about the * realm to the ccache. */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_out_ccache(krb5_context context, krb5_get_init_creds_opt *opt, krb5_ccache ccache); /** * @brief Ask the KDC to include or not include a PAC in the ticket * * @param [in] context Library context * @param [in] opt Options structure * @param [in] req_pac Whether to request a PAC or not * * If this option is set, the AS request will include a PAC-REQUEST pa-data * item explicitly asking the KDC to either include or not include a privilege * attribute certificate in the ticket authorization data. By default, no * request is made; typically the KDC will default to including a PAC if it * supports them. * * @version New in 1.15 */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_pac_request(krb5_context context, krb5_get_init_creds_opt *opt, krb5_boolean req_pac); /** * Set FAST flags in initial credential options. * * @param [in] context Library context * @param [in] opt Options * @param [in] flags FAST flags * * The following flag values are valid: * @li #KRB5_FAST_REQUIRED - Require FAST to be used * * @retval * 0 - Success; Kerberos errors otherwise. */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_fast_flags(krb5_context context, krb5_get_init_creds_opt *opt, krb5_flags flags); /** * Retrieve FAST flags from initial credential options. * * @param [in] context Library context * @param [in] opt Options * @param [out] out_flags FAST flags * * @retval * 0 - Success; Kerberos errors otherwise. */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_get_fast_flags(krb5_context context, krb5_get_init_creds_opt *opt, krb5_flags *out_flags); /* Fast flags*/ #define KRB5_FAST_REQUIRED 0x0001 /**< Require KDC to support FAST*/ typedef void (KRB5_CALLCONV *krb5_expire_callback_func)(krb5_context context, void *data, krb5_timestamp password_expiration, krb5_timestamp account_expiration, krb5_boolean is_last_req); /** * Set an expiration callback in initial credential options. * * @param [in] context Library context * @param [in] opt Options structure * @param [in] cb Callback function * @param [in] data Callback argument * * Set a callback to receive password and account expiration times. * * @a cb will be invoked if and only if credentials are successfully acquired. * The callback will receive the @a context from the calling function and the * @a data argument supplied with this API. The remaining arguments should be * interpreted as follows: * * If @a is_last_req is true, then the KDC reply contained last-req entries * which unambiguously indicated the password expiration, account expiration, * or both. (If either value was not present, the corresponding argument will * be 0.) Furthermore, a non-zero @a password_expiration should be taken as a * suggestion from the KDC that a warning be displayed. * * If @a is_last_req is false, then @a account_expiration will be 0 and @a * password_expiration will contain the expiration time of either the password * or account, or 0 if no expiration time was indicated in the KDC reply. The * callback should independently decide whether to display a password * expiration warning. * * Note that @a cb may be invoked even if credentials are being acquired for * the kadmin/changepw service in order to change the password. It is the * caller's responsibility to avoid displaying a password expiry warning in * this case. * * @warning Setting an expire callback with this API will cause * krb5_get_init_creds_password() not to send password expiry warnings to the * prompter, as it ordinarily may. * * @version New in 1.9 */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_expire_callback(krb5_context context, krb5_get_init_creds_opt *opt, krb5_expire_callback_func cb, void *data); /** * Set the responder function in initial credential options. * * @param [in] context Library context * @param [in] opt Options structure * @param [in] responder Responder function * @param [in] data Responder data argument * * @version New in 1.11 */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_opt_set_responder(krb5_context context, krb5_get_init_creds_opt *opt, krb5_responder_fn responder, void *data); /** * Get initial credentials using a password. * * @param [in] context Library context * @param [out] creds New credentials * @param [in] client Client principal * @param [in] password Password (or NULL) * @param [in] prompter Prompter function * @param [in] data Prompter callback data * @param [in] start_time Time when ticket becomes valid (0 for now) * @param [in] in_tkt_service Service name of initial credentials (or NULL) * @param [in] k5_gic_options Initial credential options * * This function requests KDC for an initial credentials for @a client using @a * password. If @a password is NULL, a password will be prompted for using @a * prompter if necessary. If @a in_tkt_service is specified, it is parsed as a * principal name (with the realm ignored) and used as the service principal * for the request; otherwise the ticket-granting service is used. * * @sa krb5_verify_init_creds() * * @retval * 0 Success * @retval * EINVAL Invalid argument * @retval * KRB5_KDC_UNREACH Cannot contact any KDC for requested realm * @retval * KRB5_PREAUTH_FAILED Generic Pre-athentication failure * @retval * KRB5_LIBOS_PWDINTR Password read interrupted * @retval * KRB5_REALM_CANT_RESOLVE Cannot resolve network address for KDC in requested realm * @retval * KRB5KDC_ERR_KEY_EXP Password has expired * @retval * KRB5_LIBOS_BADPWDMATCH Password mismatch * @retval * KRB5_CHPW_PWDNULL New password cannot be zero length * @retval * KRB5_CHPW_FAIL Password change failed * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_password(krb5_context context, krb5_creds *creds, krb5_principal client, const char *password, krb5_prompter_fct prompter, void *data, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *k5_gic_options); /** * Retrieve enctype, salt and s2kparams from KDC * * @param [in] context Library context * @param [in] principal Principal whose information is requested * @param [in] opt Initial credential options * @param [out] enctype_out The enctype chosen by KDC * @param [out] salt_out Salt returned from KDC * @param [out] s2kparams_out String-to-key parameters returned from KDC * * Send an initial ticket request for @a principal and extract the encryption * type, salt type, and string-to-key parameters from the KDC response. If the * KDC provides no etype-info, set @a enctype_out to @c ENCTYPE_NULL and set @a * salt_out and @a s2kparams_out to empty. If the KDC etype-info provides no * salt, compute the default salt and place it in @a salt_out. If the KDC * etype-info provides no string-to-key parameters, set @a s2kparams_out to * empty. * * @a opt may be used to specify options which affect the initial request, such * as request encryption types or a FAST armor cache (see * krb5_get_init_creds_opt_set_etype_list() and * krb5_get_init_creds_opt_set_fast_ccache_name()). * * Use krb5_free_data_contents() to free @a salt_out and @a s2kparams_out when * they are no longer needed. * * @version New in 1.17 * * @retval 0 Success * @return A Kerberos error code */ krb5_error_code KRB5_CALLCONV krb5_get_etype_info(krb5_context context, krb5_principal principal, krb5_get_init_creds_opt *opt, krb5_enctype *enctype_out, krb5_data *salt_out, krb5_data *s2kparams_out); struct _krb5_init_creds_context; typedef struct _krb5_init_creds_context *krb5_init_creds_context; #define KRB5_INIT_CREDS_STEP_FLAG_CONTINUE 0x1 /**< More responses needed */ /** * Free an initial credentials context. * * @param [in] context Library context * @param [in] ctx Initial credentials context * * @a context must be the same as the one passed to krb5_init_creds_init() for * this initial credentials context. */ void KRB5_CALLCONV krb5_init_creds_free(krb5_context context, krb5_init_creds_context ctx); /** * Acquire credentials using an initial credentials context. * * @param [in] context Library context * @param [in] ctx Initial credentials context * * This function synchronously obtains credentials using a context created by * krb5_init_creds_init(). On successful return, the credentials can be * retrieved with krb5_init_creds_get_creds(). * * @a context must be the same as the one passed to krb5_init_creds_init() for * this initial credentials context. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx); /** * Retrieve acquired credentials from an initial credentials context. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [out] creds Acquired credentials * * This function copies the acquired initial credentials from @a ctx into @a * creds, after the successful completion of krb5_init_creds_get() or * krb5_init_creds_step(). Use krb5_free_cred_contents() to free @a creds when * it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_get_creds(krb5_context context, krb5_init_creds_context ctx, krb5_creds *creds); /** * Get the last error from KDC from an initial credentials context. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [out] error Error from KDC, or NULL if none was received * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_get_error(krb5_context context, krb5_init_creds_context ctx, krb5_error **error); /** * Create a context for acquiring initial credentials. * * @param [in] context Library context * @param [in] client Client principal to get initial creds for * @param [in] prompter Prompter callback * @param [in] data Prompter callback argument * @param [in] start_time Time when credentials become valid (0 for now) * @param [in] options Options structure (NULL for default) * @param [out] ctx New initial credentials context * * This function creates a new context for acquiring initial credentials. Use * krb5_init_creds_free() to free @a ctx when it is no longer needed. * * Any subsequent calls to krb5_init_creds_step(), krb5_init_creds_get(), or * krb5_init_creds_free() for this initial credentials context must use the * same @a context argument as the one passed to this function. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_init(krb5_context context, krb5_principal client, krb5_prompter_fct prompter, void *data, krb5_deltat start_time, krb5_get_init_creds_opt *options, krb5_init_creds_context *ctx); /** * Specify a keytab to use for acquiring initial credentials. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [in] keytab Key table handle * * This function supplies a keytab containing the client key for an initial * credentials request. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_set_keytab(krb5_context context, krb5_init_creds_context ctx, krb5_keytab keytab); /** * Get the next KDC request for acquiring initial credentials. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [in] in KDC response (empty on the first call) * @param [out] out Next KDC request * @param [out] realm Realm for next KDC request * @param [out] flags Output flags * * This function constructs the next KDC request in an initial credential * exchange, allowing the caller to control the transport of KDC requests and * replies. On the first call, @a in should be set to an empty buffer; on * subsequent calls, it should be set to the KDC's reply to the previous * request. * * If more requests are needed, @a flags will be set to * #KRB5_INIT_CREDS_STEP_FLAG_CONTINUE and the next request will be placed in * @a out. If no more requests are needed, @a flags will not contain * #KRB5_INIT_CREDS_STEP_FLAG_CONTINUE and @a out will be empty. * * If this function returns @c KRB5KRB_ERR_RESPONSE_TOO_BIG, the caller should * transmit the next request using TCP rather than UDP. If this function * returns any other error, the initial credential exchange has failed. * * @a context must be the same as the one passed to krb5_init_creds_init() for * this initial credentials context. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_step(krb5_context context, krb5_init_creds_context ctx, krb5_data *in, krb5_data *out, krb5_data *realm, unsigned int *flags); /** * Set a password for acquiring initial credentials. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [in] password Password * * This function supplies a password to be used to construct the client key for * an initial credentials request. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_set_password(krb5_context context, krb5_init_creds_context ctx, const char *password); /** * Specify a service principal for acquiring initial credentials. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [in] service Service principal string * * This function supplies a service principal string to acquire initial * credentials for instead of the default krbtgt service. @a service is parsed * as a principal name; any realm part is ignored. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_set_service(krb5_context context, krb5_init_creds_context ctx, const char *service); /** * Retrieve ticket times from an initial credentials context. * * @param [in] context Library context * @param [in] ctx Initial credentials context * @param [out] times Ticket times for acquired credentials * * The initial credentials context must have completed obtaining credentials * via either krb5_init_creds_get() or krb5_init_creds_step(). * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_init_creds_get_times(krb5_context context, krb5_init_creds_context ctx, krb5_ticket_times *times); struct _krb5_tkt_creds_context; typedef struct _krb5_tkt_creds_context *krb5_tkt_creds_context; /** * Create a context to get credentials from a KDC's Ticket Granting Service. * * @param[in] context Library context * @param[in] ccache Credential cache handle * @param[in] creds Input credentials * @param[in] options @ref KRB5_GC options for this request. * @param[out] ctx New TGS request context * * This function prepares to obtain credentials matching @a creds, either by * retrieving them from @a ccache or by making requests to ticket-granting * services beginning with a ticket-granting ticket for the client principal's * realm. * * The resulting TGS acquisition context can be used asynchronously with * krb5_tkt_creds_step() or synchronously with krb5_tkt_creds_get(). See also * krb5_get_credentials() for synchronous use. * * Use krb5_tkt_creds_free() to free @a ctx when it is no longer needed. * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_tkt_creds_init(krb5_context context, krb5_ccache ccache, krb5_creds *creds, krb5_flags options, krb5_tkt_creds_context *ctx); /** * Synchronously obtain credentials using a TGS request context. * * @param[in] context Library context * @param[in] ctx TGS request context * * This function synchronously obtains credentials using a context created by * krb5_tkt_creds_init(). On successful return, the credentials can be * retrieved with krb5_tkt_creds_get_creds(). * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_tkt_creds_get(krb5_context context, krb5_tkt_creds_context ctx); /** * Retrieve acquired credentials from a TGS request context. * * @param[in] context Library context * @param[in] ctx TGS request context * @param[out] creds Acquired credentials * * This function copies the acquired initial credentials from @a ctx into @a * creds, after the successful completion of krb5_tkt_creds_get() or * krb5_tkt_creds_step(). Use krb5_free_cred_contents() to free @a creds when * it is no longer needed. * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_tkt_creds_get_creds(krb5_context context, krb5_tkt_creds_context ctx, krb5_creds *creds); /** * Free a TGS request context. * * @param[in] context Library context * @param[in] ctx TGS request context * * @version New in 1.9 */ void KRB5_CALLCONV krb5_tkt_creds_free(krb5_context context, krb5_tkt_creds_context ctx); #define KRB5_TKT_CREDS_STEP_FLAG_CONTINUE 0x1 /**< More responses needed */ /** * Get the next KDC request in a TGS exchange. * * @param[in] context Library context * @param[in] ctx TGS request context * @param[in] in KDC response (empty on the first call) * @param[out] out Next KDC request * @param[out] realm Realm for next KDC request * @param[out] flags Output flags * * This function constructs the next KDC request for a TGS exchange, allowing * the caller to control the transport of KDC requests and replies. On the * first call, @a in should be set to an empty buffer; on subsequent calls, it * should be set to the KDC's reply to the previous request. * * If more requests are needed, @a flags will be set to * #KRB5_TKT_CREDS_STEP_FLAG_CONTINUE and the next request will be placed in @a * out. If no more requests are needed, @a flags will not contain * #KRB5_TKT_CREDS_STEP_FLAG_CONTINUE and @a out will be empty. * * If this function returns @c KRB5KRB_ERR_RESPONSE_TOO_BIG, the caller should * transmit the next request using TCP rather than UDP. If this function * returns any other error, the TGS exchange has failed. * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_tkt_creds_step(krb5_context context, krb5_tkt_creds_context ctx, krb5_data *in, krb5_data *out, krb5_data *realm, unsigned int *flags); /** * Retrieve ticket times from a TGS request context. * * @param[in] context Library context * @param[in] ctx TGS request context * @param[out] times Ticket times for acquired credentials * * The TGS request context must have completed obtaining credentials via either * krb5_tkt_creds_get() or krb5_tkt_creds_step(). * * @version New in 1.9 * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_tkt_creds_get_times(krb5_context context, krb5_tkt_creds_context ctx, krb5_ticket_times *times); /** * Get initial credentials using a key table. * * @param [in] context Library context * @param [out] creds New credentials * @param [in] client Client principal * @param [in] arg_keytab Key table handle * @param [in] start_time Time when ticket becomes valid (0 for now) * @param [in] in_tkt_service Service name of initial credentials (or NULL) * @param [in] k5_gic_options Initial credential options * * This function requests KDC for an initial credentials for @a client using a * client key stored in @a arg_keytab. If @a in_tkt_service is specified, it * is parsed as a principal name (with the realm ignored) and used as the * service principal for the request; otherwise the ticket-granting service is * used. * * @sa krb5_verify_init_creds() * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_init_creds_keytab(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_keytab arg_keytab, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *k5_gic_options); typedef struct _krb5_verify_init_creds_opt { krb5_flags flags; int ap_req_nofail; /**< boolean */ } krb5_verify_init_creds_opt; #define KRB5_VERIFY_INIT_CREDS_OPT_AP_REQ_NOFAIL 0x0001 /** * Initialize a credential verification options structure. * * @param [in] k5_vic_options Verification options structure */ void KRB5_CALLCONV krb5_verify_init_creds_opt_init(krb5_verify_init_creds_opt *k5_vic_options); /** * Set whether credential verification is required. * * @param [in] k5_vic_options Verification options structure * @param [in] ap_req_nofail Whether to require successful verification * * This function determines how krb5_verify_init_creds() behaves if no keytab * information is available. If @a ap_req_nofail is @c FALSE, verification * will be skipped in this case and krb5_verify_init_creds() will return * successfully. If @a ap_req_nofail is @c TRUE, krb5_verify_init_creds() will * not return successfully unless verification can be performed. * * If this function is not used, the behavior of krb5_verify_init_creds() is * determined through configuration. */ void KRB5_CALLCONV krb5_verify_init_creds_opt_set_ap_req_nofail(krb5_verify_init_creds_opt * k5_vic_options, int ap_req_nofail); /** * Verify initial credentials against a keytab. * * @param [in] context Library context * @param [in] creds Initial credentials to be verified * @param [in] server Server principal (or NULL) * @param [in] keytab Key table (NULL to use default keytab) * @param [in] ccache Credential cache for fetched creds (or NULL) * @param [in] options Verification options (NULL for default options) * * This function attempts to verify that @a creds were obtained from a KDC with * knowledge of a key in @a keytab, or the default keytab if @a keytab is NULL. * If @a server is provided, the highest-kvno key entry for that principal name * is used to verify the credentials; otherwise, all unique "host" service * principals in the keytab are tried. * * If the specified keytab does not exist, or is empty, or cannot be read, or * does not contain an entry for @a server, then credential verification may be * skipped unless configuration demands that it succeed. The caller can * control this behavior by providing a verification options structure; see * krb5_verify_init_creds_opt_init() and * krb5_verify_init_creds_opt_set_ap_req_nofail(). * * If @a ccache is NULL, any additional credentials fetched during the * verification process will be destroyed. If @a ccache points to NULL, a * memory ccache will be created for the additional credentials and returned in * @a ccache. If @a ccache points to a valid credential cache handle, the * additional credentials will be stored in that cache. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_verify_init_creds(krb5_context context, krb5_creds *creds, krb5_principal server, krb5_keytab keytab, krb5_ccache *ccache, krb5_verify_init_creds_opt *options); /** * Get validated credentials from the KDC. * * @param [in] context Library context * @param [out] creds Validated credentials * @param [in] client Client principal name * @param [in] ccache Credential cache * @param [in] in_tkt_service Server principal string (or NULL) * * This function gets a validated credential using a postdated credential from * @a ccache. If @a in_tkt_service is specified, it is parsed (with the realm * part ignored) and used as the server principal of the credential; * otherwise, the ticket-granting service is used. * * If successful, the validated credential is placed in @a creds. * * @sa krb5_get_renewed_creds() * * @retval * 0 Success * @retval * KRB5_NO_2ND_TKT Request missing second ticket * @retval * KRB5_NO_TKT_SUPPLIED Request did not supply a ticket * @retval * KRB5_PRINC_NOMATCH Requested principal and ticket do not match * @retval * KRB5_KDCREP_MODIFIED KDC reply did not match expectations * @retval * KRB5_KDCREP_SKEW Clock skew too great in KDC reply * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_validated_creds(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_ccache ccache, const char *in_tkt_service); /** * Get renewed credential from KDC using an existing credential. * * @param [in] context Library context * @param [out] creds Renewed credentials * @param [in] client Client principal name * @param [in] ccache Credential cache * @param [in] in_tkt_service Server principal string (or NULL) * * This function gets a renewed credential using an existing one from @a * ccache. If @a in_tkt_service is specified, it is parsed (with the realm * part ignored) and used as the server principal of the credential; otherwise, * the ticket-granting service is used. * * If successful, the renewed credential is placed in @a creds. * * @retval * 0 Success * @return * Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_get_renewed_creds(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_ccache ccache, const char *in_tkt_service); /** * Decode an ASN.1-formatted ticket. * * @param [in] code ASN.1-formatted ticket * @param [out] rep Decoded ticket information * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_decode_ticket(const krb5_data *code, krb5_ticket **rep); /** * Retrieve a string value from the appdefaults section of krb5.conf. * * @param [in] context Library context * @param [in] appname Application name * @param [in] realm Realm name * @param [in] option Option to be checked * @param [in] default_value Default value to return if no match is found * @param [out] ret_value String value of @a option * * This function gets the application defaults for @a option based on the given * @a appname and/or @a realm. * * @sa krb5_appdefault_boolean() */ void KRB5_CALLCONV krb5_appdefault_string(krb5_context context, const char *appname, const krb5_data *realm, const char *option, const char *default_value, char ** ret_value); /** * Retrieve a boolean value from the appdefaults section of krb5.conf. * * @param [in] context Library context * @param [in] appname Application name * @param [in] realm Realm name * @param [in] option Option to be checked * @param [in] default_value Default value to return if no match is found * @param [out] ret_value Boolean value of @a option * * This function gets the application defaults for @a option based on the given * @a appname and/or @a realm. * * @sa krb5_appdefault_string() */ void KRB5_CALLCONV krb5_appdefault_boolean(krb5_context context, const char *appname, const krb5_data *realm, const char *option, int default_value, int *ret_value); /* * Prompter enhancements */ /** Prompt for password */ #define KRB5_PROMPT_TYPE_PASSWORD 0x1 /** Prompt for new password (during password change) */ #define KRB5_PROMPT_TYPE_NEW_PASSWORD 0x2 /** Prompt for new password again */ #define KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN 0x3 /** Prompt for preauthentication data (such as an OTP value) */ #define KRB5_PROMPT_TYPE_PREAUTH 0x4 typedef krb5_int32 krb5_prompt_type; /** * Get prompt types array from a context. * * @param [in] context Library context * * @return * Pointer to an array of prompt types corresponding to the prompter's @a * prompts arguments. Each type has one of the following values: * @li #KRB5_PROMPT_TYPE_PASSWORD * @li #KRB5_PROMPT_TYPE_NEW_PASSWORD * @li #KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN * @li #KRB5_PROMPT_TYPE_PREAUTH */ krb5_prompt_type* KRB5_CALLCONV krb5_get_prompt_types(krb5_context context); /* Error reporting */ /** * Set an extended error message for an error code. * * @param [in] ctx Library context * @param [in] code Error code * @param [in] fmt Error string for the error code * @param [in] ... printf(3) style parameters */ void KRB5_CALLCONV_C krb5_set_error_message(krb5_context ctx, krb5_error_code code, const char *fmt, ...) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 3, 4))) #endif ; /** * Set an extended error message for an error code using a va_list. * * @param [in] ctx Library context * @param [in] code Error code * @param [in] fmt Error string for the error code * @param [in] args List of vprintf(3) style arguments */ void KRB5_CALLCONV krb5_vset_error_message(krb5_context ctx, krb5_error_code code, const char *fmt, va_list args) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 3, 0))) #endif ; /** * Add a prefix to the message for an error code. * * @param [in] ctx Library context * @param [in] code Error code * @param [in] fmt Format string for error message prefix * @param [in] ... printf(3) style parameters * * Format a message and prepend it to the current message for @a code. The * prefix will be separated from the old message with a colon and space. */ void KRB5_CALLCONV_C krb5_prepend_error_message(krb5_context ctx, krb5_error_code code, const char *fmt, ...) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 3, 4))) #endif ; /** * Add a prefix to the message for an error code using a va_list. * * @param [in] ctx Library context * @param [in] code Error code * @param [in] fmt Format string for error message prefix * @param [in] args List of vprintf(3) style arguments * * This function is similar to krb5_prepend_error_message(), but uses a * va_list instead of variadic arguments. */ void KRB5_CALLCONV krb5_vprepend_error_message(krb5_context ctx, krb5_error_code code, const char *fmt, va_list args) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 3, 0))) #endif ; /** * Add a prefix to a different error code's message. * * @param [in] ctx Library context * @param [in] old_code Previous error code * @param [in] code Error code * @param [in] fmt Format string for error message prefix * @param [in] ... printf(3) style parameters * * Format a message and prepend it to the message for @a old_code. The prefix * will be separated from the old message with a colon and space. Set the * resulting message as the extended error message for @a code. */ void KRB5_CALLCONV_C krb5_wrap_error_message(krb5_context ctx, krb5_error_code old_code, krb5_error_code code, const char *fmt, ...) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 4, 5))) #endif ; /** * Add a prefix to a different error code's message using a va_list. * * @param [in] ctx Library context * @param [in] old_code Previous error code * @param [in] code Error code * @param [in] fmt Format string for error message prefix * @param [in] args List of vprintf(3) style arguments * * This function is similar to krb5_wrap_error_message(), but uses a * va_list instead of variadic arguments. */ void KRB5_CALLCONV krb5_vwrap_error_message(krb5_context ctx, krb5_error_code old_code, krb5_error_code code, const char *fmt, va_list args) #if !defined(__cplusplus) && (__GNUC__ > 2) __attribute__((__format__(__printf__, 4, 0))) #endif ; /** * Copy the most recent extended error message from one context to another. * * @param [in] dest_ctx Library context to copy message to * @param [in] src_ctx Library context with current message */ void KRB5_CALLCONV krb5_copy_error_message(krb5_context dest_ctx, krb5_context src_ctx); /** * Get the (possibly extended) error message for a code. * * @param [in] ctx Library context * @param [in] code Error code * * The behavior of krb5_get_error_message() is only defined the first time it * is called after a failed call to a krb5 function using the same context, and * only when the error code passed in is the same as that returned by the krb5 * function. * * This function never returns NULL, so its result may be used unconditionally * as a C string. * * The string returned by this function must be freed using * krb5_free_error_message() * * @note Future versions may return the same string for the second * and following calls. */ const char * KRB5_CALLCONV krb5_get_error_message(krb5_context ctx, krb5_error_code code); /** * Free an error message generated by krb5_get_error_message(). * * @param [in] ctx Library context * @param [in] msg Pointer to error message */ void KRB5_CALLCONV krb5_free_error_message(krb5_context ctx, const char *msg); /** * Clear the extended error message in a context. * * @param [in] ctx Library context * * This function unsets the extended error message in a context, to ensure that * it is not mistakenly applied to another occurrence of the same error code. */ void KRB5_CALLCONV krb5_clear_error_message(krb5_context ctx); /** * Unwrap authorization data. * * @param [in] context Library context * @param [in] type @ref KRB5_AUTHDATA type of @a container * @param [in] container Authorization data to be decoded * @param [out] authdata List of decoded authorization data * * @sa krb5_encode_authdata_container() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_decode_authdata_container(krb5_context context, krb5_authdatatype type, const krb5_authdata *container, krb5_authdata ***authdata); /** * Wrap authorization data in a container. * * @param [in] context Library context * @param [in] type @ref KRB5_AUTHDATA type of @a container * @param [in] authdata List of authorization data to be encoded * @param [out] container List of encoded authorization data * * The result is returned in @a container as a single-element list. * * @sa krb5_decode_authdata_container() * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_encode_authdata_container(krb5_context context, krb5_authdatatype type, krb5_authdata * const*authdata, krb5_authdata ***container); /* * AD-KDCIssued */ /** * Encode and sign AD-KDCIssued authorization data. * * @param [in] context Library context * @param [in] key Session key * @param [in] issuer The name of the issuing principal * @param [in] authdata List of authorization data to be signed * @param [out] ad_kdcissued List containing AD-KDCIssued authdata * * This function wraps a list of authorization data entries @a authdata in an * AD-KDCIssued container (see RFC 4120 section 5.2.6.2) signed with @a key. * The result is returned in @a ad_kdcissued as a single-element list. */ krb5_error_code KRB5_CALLCONV krb5_make_authdata_kdc_issued(krb5_context context, const krb5_keyblock *key, krb5_const_principal issuer, krb5_authdata *const *authdata, krb5_authdata ***ad_kdcissued); /** * Unwrap and verify AD-KDCIssued authorization data. * * @param [in] context Library context * @param [in] key Session key * @param [in] ad_kdcissued AD-KDCIssued authorization data to be unwrapped * @param [out] issuer Name of issuing principal (or NULL) * @param [out] authdata Unwrapped list of authorization data * * This function unwraps an AD-KDCIssued authdatum (see RFC 4120 section * 5.2.6.2) and verifies its signature against @a key. The issuer field of the * authdatum element is returned in @a issuer, and the unwrapped list of * authdata is returned in @a authdata. */ krb5_error_code KRB5_CALLCONV krb5_verify_authdata_kdc_issued(krb5_context context, const krb5_keyblock *key, const krb5_authdata *ad_kdcissued, krb5_principal *issuer, krb5_authdata ***authdata); /* * Windows PAC */ /* Microsoft defined types of data */ #define KRB5_PAC_LOGON_INFO 1 /**< Logon information */ #define KRB5_PAC_CREDENTIALS_INFO 2 /**< Credentials information */ #define KRB5_PAC_SERVER_CHECKSUM 6 /**< Server checksum */ #define KRB5_PAC_PRIVSVR_CHECKSUM 7 /**< KDC checksum */ #define KRB5_PAC_CLIENT_INFO 10 /**< Client name and ticket info */ #define KRB5_PAC_DELEGATION_INFO 11 /**< Constrained delegation info */ #define KRB5_PAC_UPN_DNS_INFO 12 /**< User principal name and DNS info */ #define KRB5_PAC_CLIENT_CLAIMS 13 /**< Client claims information */ #define KRB5_PAC_DEVICE_INFO 14 /**< Device information */ #define KRB5_PAC_DEVICE_CLAIMS 15 /**< Device claims information */ #define KRB5_PAC_TICKET_CHECKSUM 16 /**< Ticket checksum */ #define KRB5_PAC_ATTRIBUTES_INFO 17 /**< PAC attributes */ #define KRB5_PAC_REQUESTOR 18 /**< PAC requestor SID */ #define KRB5_PAC_FULL_CHECKSUM 19 /**< KDC full checksum */ struct krb5_pac_data; /** PAC data structure to convey authorization information */ typedef struct krb5_pac_data *krb5_pac; /** * Add a buffer to a PAC handle. * * @param [in] context Library context * @param [in] pac PAC handle * @param [in] type Buffer type * @param [in] data contents * * This function adds a buffer of type @a type and contents @a data to @a pac * if there isn't already a buffer of this type present. * * The valid values of @a type is one of the following: * @li #KRB5_PAC_LOGON_INFO - Logon information * @li #KRB5_PAC_CREDENTIALS_INFO - Credentials information * @li #KRB5_PAC_SERVER_CHECKSUM - Server checksum * @li #KRB5_PAC_PRIVSVR_CHECKSUM - KDC checksum * @li #KRB5_PAC_CLIENT_INFO - Client name and ticket information * @li #KRB5_PAC_DELEGATION_INFO - Constrained delegation information * @li #KRB5_PAC_UPN_DNS_INFO - User principal name and DNS information * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_pac_add_buffer(krb5_context context, krb5_pac pac, krb5_ui_4 type, const krb5_data *data); /** * Free a PAC handle. * * @param [in] context Library context * @param [in] pac PAC to be freed * * This function frees the contents of @a pac and the structure itself. */ void KRB5_CALLCONV krb5_pac_free(krb5_context context, krb5_pac pac); /** * Retrieve a buffer value from a PAC. * * @param [in] context Library context * @param [in] pac PAC handle * @param [in] type Type of buffer to retrieve * @param [out] data Buffer value * * Use krb5_free_data_contents() to free @a data when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_pac_get_buffer(krb5_context context, krb5_pac pac, krb5_ui_4 type, krb5_data *data); /** * Return an array of buffer types in a PAC handle. * * @param [in] context Library context * @param [in] pac PAC handle * @param [out] len Number of entries in @a types * @param [out] types Array of buffer types * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_pac_get_types(krb5_context context, krb5_pac pac, size_t *len, krb5_ui_4 **types); /** * Create an empty Privilege Attribute Certificate (PAC) handle. * * @param [in] context Library context * @param [out] pac New PAC handle * * Use krb5_pac_free() to free @a pac when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_pac_init(krb5_context context, krb5_pac *pac); /** * Unparse an encoded PAC into a new handle. * * @param [in] context Library context * @param [in] ptr PAC buffer * @param [in] len Length of @a ptr * @param [out] pac PAC handle * * Use krb5_pac_free() to free @a pac when it is no longer needed. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_pac_parse(krb5_context context, const void *ptr, size_t len, krb5_pac *pac); /** * Verify a PAC. * * @param [in] context Library context * @param [in] pac PAC handle * @param [in] authtime Expected timestamp * @param [in] principal Expected principal name (or NULL) * @param [in] server Key to validate server checksum (or NULL) * @param [in] privsvr Key to validate KDC checksum (or NULL) * * This function validates @a pac against the supplied @a server, @a privsvr, * @a principal and @a authtime. If @a principal is NULL, the principal and * authtime are not verified. If @a server or @a privsvr is NULL, the * corresponding checksum is not verified. * * If successful, @a pac is marked as verified. * * @note A checksum mismatch can occur if the PAC was copied from a cross-realm * TGT by an ignorant KDC; also macOS Server Open Directory (as of 10.6) * generates PACs with no server checksum at all. One should consider not * failing the whole authentication because of this reason, but, instead, * treating the ticket as if it did not contain a PAC or marking the PAC * information as non-verified. * * @retval 0 Success; otherwise - Kerberos error codes */ krb5_error_code KRB5_CALLCONV krb5_pac_verify(krb5_context context, const krb5_pac pac, krb5_timestamp authtime, krb5_const_principal principal, const krb5_keyblock *server, const krb5_keyblock *privsvr); /** * Verify a PAC, possibly from a specified realm. * * @param [in] context Library context * @param [in] pac PAC handle * @param [in] authtime Expected timestamp * @param [in] principal Expected principal name (or NULL) * @param [in] server Key to validate server checksum (or NULL) * @param [in] privsvr Key to validate KDC checksum (or NULL) * @param [in] with_realm If true, expect the realm of @a principal * * This function is similar to krb5_pac_verify(), but adds a parameter * @a with_realm. If @a with_realm is true, the PAC_CLIENT_INFO field is * expected to include the realm of @a principal as well as the name. This * flag is necessary to verify PACs in cross-realm S4U2Self referral TGTs. * * @version New in 1.17 */ krb5_error_code KRB5_CALLCONV krb5_pac_verify_ext(krb5_context context, const krb5_pac pac, krb5_timestamp authtime, krb5_const_principal principal, const krb5_keyblock *server, const krb5_keyblock *privsvr, krb5_boolean with_realm); /** * Verify a PAC, possibly including ticket signature * * @param [in] context Library context * @param [in] enc_tkt Ticket enc-part, possibly containing a PAC * @param [in] server_princ Canonicalized name of ticket server * @param [in] server Key to validate server checksum (or NULL) * @param [in] privsvr Key to validate KDC checksum (or NULL) * @param [out] pac_out Verified PAC (NULL if no PAC included) * * If a PAC is present in @a enc_tkt, verify its signatures. If @a privsvr is * not NULL and @a server_princ is not a krbtgt or kadmin/changepw service, * require a ticket signature over @a enc_tkt in addition to the KDC signature. * Place the verified PAC in @a pac_out. If an invalid PAC signature is found, * return an error matching the Windows KDC protocol code for that condition as * closely as possible. * * If no PAC is present in @a enc_tkt, set @a pac_out to NULL and return * successfully. * * @note This function does not validate the PAC_CLIENT_INFO buffer. If a * specific value is expected, the caller can make a separate call to * krb5_pac_verify_ext() with a principal but no keys. * * @retval 0 Success; otherwise - Kerberos error codes * * @version New in 1.20 */ krb5_error_code KRB5_CALLCONV krb5_kdc_verify_ticket(krb5_context context, const krb5_enc_tkt_part *enc_tkt, krb5_const_principal server_princ, const krb5_keyblock *server, const krb5_keyblock *privsvr, krb5_pac *pac_out); /** @deprecated Use krb5_kdc_sign_ticket() instead. */ krb5_error_code KRB5_CALLCONV krb5_pac_sign(krb5_context context, krb5_pac pac, krb5_timestamp authtime, krb5_const_principal principal, const krb5_keyblock *server_key, const krb5_keyblock *privsvr_key, krb5_data *data); /** @deprecated Use krb5_kdc_sign_ticket() instead. */ krb5_error_code KRB5_CALLCONV krb5_pac_sign_ext(krb5_context context, krb5_pac pac, krb5_timestamp authtime, krb5_const_principal principal, const krb5_keyblock *server_key, const krb5_keyblock *privsvr_key, krb5_boolean with_realm, krb5_data *data); /** * Compatibility function used by IPA if the 1.20 KDB diver API is not * available. It generates PAC signatures, including the extended KDC one when * relevant. * * It is similar to krb5_kdc_sign_ticket(), except it will not generate the * PAC ticket signature, and therefore does not expect encrypted ticket part as * parameter. * * @param [in] context Library context * @param [in] pac PAC handle * @param [in] authtime Expected timestamp * @param [in] client_princ Client principal name (or NULL) * @param [in] server_princ Server principal name * @param [in] server_key Key for server checksum * @param [in] privsvr_key Key for KDC checksum * @param [in] with_realm If true, include the realm of @a client_princ * @param [out] data Signed PAC encoding * * This function signs @a pac using the keys @a server_key and @a privsvr_key * and returns the signed encoding in @a data. @a pac is modified to include * the server and KDC checksum buffers. Use krb5_free_data_contents() to free * @a data when it is no longer needed. * * If @a with_realm is true, the PAC_CLIENT_INFO field of the signed PAC will * include the realm of @a client_princ as well as the name. This flag is * necessary to generate PACs for cross-realm S4U2Self referrals. */ krb5_error_code KRB5_CALLCONV krb5_pac_full_sign_compat(krb5_context context, krb5_pac pac, krb5_timestamp authtime, krb5_const_principal client_princ, krb5_const_principal server_princ, const krb5_keyblock *server_key, const krb5_keyblock *privsvr_key, krb5_boolean with_realm, krb5_data *data); /** * Sign a PAC, possibly including a ticket signature * * @param [in] context Library context * @param [in] enc_tkt The ticket for the signature * @param [in] pac PAC handle * @param [in] server_princ Canonical ticket server name * @param [in] client_princ PAC_CLIENT_INFO principal (or NULL) * @param [in] server Key for server checksum * @param [in] privsvr Key for KDC and ticket checksum * @param [in] with_realm If true, include the realm of @a principal * * Sign @a pac using the keys @a server and @a privsvr. Include a ticket * signature over @a enc_tkt if @a server_princ is not a TGS or kadmin/changepw * principal name. Add the signed PAC's encoding to the authorization data of * @a enc_tkt in the first slot, wrapped in an AD-IF-RELEVANT container. If @a * client_princ is non-null, add a PAC_CLIENT_INFO buffer, including the realm * if @a with_realm is true. * * @retval 0 on success, otherwise - Kerberos error codes * * @version New in 1.20 */ krb5_error_code KRB5_CALLCONV krb5_kdc_sign_ticket(krb5_context context, krb5_enc_tkt_part *enc_tkt, const krb5_pac pac, krb5_const_principal server_princ, krb5_const_principal client_princ, const krb5_keyblock *server, const krb5_keyblock *privsvr, krb5_boolean with_realm); /** * Read client information from a PAC. * * @param [in] context Library context * @param [in] pac PAC handle * @param [out] authtime_out Authentication timestamp (NULL if not needed) * @param [out] princname_out Client account name * * Read the PAC_CLIENT_INFO buffer in @a pac. Place the client account name as * a string in @a princname_out. If @a authtime_out is not NULL, place the * initial authentication timestamp in @a authtime_out. * * @retval 0 on success, ENOENT if no PAC_CLIENT_INFO buffer is present in @a * pac, ERANGE if the buffer contains invalid lengths. * * @version New in 1.18 */ krb5_error_code KRB5_CALLCONV krb5_pac_get_client_info(krb5_context context, const krb5_pac pac, krb5_timestamp *authtime_out, char **princname_out); /** * Allow the application to override the profile's allow_weak_crypto setting. * * @param [in] context Library context * @param [in] enable Boolean flag * * This function allows an application to override the allow_weak_crypto * setting. It is primarily for use by aklog. * * @retval 0 (always) */ krb5_error_code KRB5_CALLCONV krb5_allow_weak_crypto(krb5_context context, krb5_boolean enable); /** * A wrapper for passing information to a @c krb5_trace_callback. * * Currently, it only contains the formatted message as determined * the the format string and arguments of the tracing macro, but it * may be extended to contain more fields in the future. */ typedef struct _krb5_trace_info { const char *message; } krb5_trace_info; typedef void (KRB5_CALLCONV *krb5_trace_callback)(krb5_context context, const krb5_trace_info *info, void *cb_data); /** * Specify a callback function for trace events. * * @param [in] context Library context * @param [in] fn Callback function * @param [in] cb_data Callback data * * Specify a callback for trace events occurring in krb5 operations performed * within @a context. @a fn will be invoked with @a context as the first * argument, @a cb_data as the last argument, and a pointer to a * krb5_trace_info as the second argument. If the trace callback is reset via * this function or @a context is destroyed, @a fn will be invoked with a NULL * second argument so it can clean up @a cb_data. Supply a NULL value for @a * fn to disable trace callbacks within @a context. * * @note This function overrides the information passed through the * @a KRB5_TRACE environment variable. * * @version New in 1.9 * * @return Returns KRB5_TRACE_NOSUPP if tracing is not supported in the library * (unless @a fn is NULL). */ krb5_error_code KRB5_CALLCONV krb5_set_trace_callback(krb5_context context, krb5_trace_callback fn, void *cb_data); /** * Specify a file name for directing trace events. * * @param [in] context Library context * @param [in] filename File name * * Open @a filename for appending (creating it, if necessary) and set up a * callback to write trace events to it. * * @note This function overrides the information passed through the * @a KRB5_TRACE environment variable. * * @version New in 1.9 * * @retval KRB5_TRACE_NOSUPP Tracing is not supported in the library. */ krb5_error_code KRB5_CALLCONV krb5_set_trace_filename(krb5_context context, const char *filename); /** * Hook function for inspecting or modifying messages sent to KDCs. * * @param [in] context Library context * @param [in] data Callback data * @param [in] realm The realm the message will be sent to * @param [in] message The original message to be sent to the KDC * @param [out] new_message_out Optional replacement message to be sent * @param [out] reply_out Optional synthetic reply * * If the hook function returns an error code, the KDC communication will be * aborted and the error code will be returned to the library operation which * initiated the communication. * * If the hook function sets @a reply_out, @a message will not be sent to the * KDC, and the given reply will used instead. * * If the hook function sets @a new_message_out, the given message will be sent * to the KDC in place of @a message. * * If the hook function returns successfully without setting either output, * @a message will be sent to the KDC normally. * * The hook function should use krb5_copy_data() to construct the value for * @a new_message_out or @a reply_out, to ensure that it can be freed correctly * by the library. * * @version New in 1.15 * * @retval 0 Success * @return A Kerberos error code */ typedef krb5_error_code (KRB5_CALLCONV *krb5_pre_send_fn)(krb5_context context, void *data, const krb5_data *realm, const krb5_data *message, krb5_data **new_message_out, krb5_data **new_reply_out); /** * Hook function for inspecting or overriding KDC replies. * * @param [in] context Library context * @param [in] data Callback data * @param [in] code Status of KDC communication * @param [in] realm The realm the reply was received from * @param [in] message The message sent to the realm's KDC * @param [in] reply The reply received from the KDC * @param [out] new_reply_out Optional replacement reply * * If @a code is zero, @a reply contains the reply received from the KDC. The * hook function may return an error code to simulate an error, may synthesize * a different reply by setting @a new_reply_out, or may simply return * successfully to do nothing. * * If @a code is non-zero, KDC communication failed and @a reply should be * ignored. The hook function may return @a code or a different error code, or * may synthesize a reply by setting @a new_reply_out and return successfully. * * The hook function should use krb5_copy_data() to construct the value for * @a new_reply_out, to ensure that it can be freed correctly by the library. * * @version New in 1.15 * * @retval 0 Success * @return A Kerberos error code */ typedef krb5_error_code (KRB5_CALLCONV *krb5_post_recv_fn)(krb5_context context, void *data, krb5_error_code code, const krb5_data *realm, const krb5_data *message, const krb5_data *reply, krb5_data **new_reply_out); /** * Set a KDC pre-send hook function. * * @param [in] context Library context * @param [in] send_hook Hook function (or NULL to disable the hook) * @param [in] data Callback data to be passed to @a send_hook * * @a send_hook will be called before messages are sent to KDCs by library * functions such as krb5_get_credentials(). The hook function may inspect, * override, or synthesize its own reply to the message. * * @version New in 1.15 */ void KRB5_CALLCONV krb5_set_kdc_send_hook(krb5_context context, krb5_pre_send_fn send_hook, void *data); /** * Set a KDC post-receive hook function. * * @param [in] context The library context. * @param [in] recv_hook Hook function (or NULL to disable the hook) * @param [in] data Callback data to be passed to @a recv_hook * * @a recv_hook will be called after a reply is received from a KDC during a * call to a library function such as krb5_get_credentials(). The hook * function may inspect or override the reply. This hook will not be executed * if the pre-send hook returns a synthetic reply. * * @version New in 1.15 */ void KRB5_CALLCONV krb5_set_kdc_recv_hook(krb5_context context, krb5_post_recv_fn recv_hook, void *data); #if defined(TARGET_OS_MAC) && TARGET_OS_MAC # pragma pack(pop) #endif KRB5INT_END_DECLS /* Don't use this! We're going to phase it out. It's just here to keep applications from breaking right away. */ #define krb5_const const #undef KRB5_ATTR_DEPRECATED /** @} */ /* end of KRB5_H group */ #endif /* KRB5_GENERAL__ */ /* * et-h-krb5_err.h: * This file is automatically generated; please do not edit it. */ #include #define KRB5KDC_ERR_NONE (-1765328384L) #define KRB5KDC_ERR_NAME_EXP (-1765328383L) #define KRB5KDC_ERR_SERVICE_EXP (-1765328382L) #define KRB5KDC_ERR_BAD_PVNO (-1765328381L) #define KRB5KDC_ERR_C_OLD_MAST_KVNO (-1765328380L) #define KRB5KDC_ERR_S_OLD_MAST_KVNO (-1765328379L) #define KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN (-1765328378L) #define KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN (-1765328377L) #define KRB5KDC_ERR_PRINCIPAL_NOT_UNIQUE (-1765328376L) #define KRB5KDC_ERR_NULL_KEY (-1765328375L) #define KRB5KDC_ERR_CANNOT_POSTDATE (-1765328374L) #define KRB5KDC_ERR_NEVER_VALID (-1765328373L) #define KRB5KDC_ERR_POLICY (-1765328372L) #define KRB5KDC_ERR_BADOPTION (-1765328371L) #define KRB5KDC_ERR_ETYPE_NOSUPP (-1765328370L) #define KRB5KDC_ERR_SUMTYPE_NOSUPP (-1765328369L) #define KRB5KDC_ERR_PADATA_TYPE_NOSUPP (-1765328368L) #define KRB5KDC_ERR_TRTYPE_NOSUPP (-1765328367L) #define KRB5KDC_ERR_CLIENT_REVOKED (-1765328366L) #define KRB5KDC_ERR_SERVICE_REVOKED (-1765328365L) #define KRB5KDC_ERR_TGT_REVOKED (-1765328364L) #define KRB5KDC_ERR_CLIENT_NOTYET (-1765328363L) #define KRB5KDC_ERR_SERVICE_NOTYET (-1765328362L) #define KRB5KDC_ERR_KEY_EXP (-1765328361L) #define KRB5KDC_ERR_PREAUTH_FAILED (-1765328360L) #define KRB5KDC_ERR_PREAUTH_REQUIRED (-1765328359L) #define KRB5KDC_ERR_SERVER_NOMATCH (-1765328358L) #define KRB5KDC_ERR_MUST_USE_USER2USER (-1765328357L) #define KRB5KDC_ERR_PATH_NOT_ACCEPTED (-1765328356L) #define KRB5KDC_ERR_SVC_UNAVAILABLE (-1765328355L) #define KRB5PLACEHOLD_30 (-1765328354L) #define KRB5KRB_AP_ERR_BAD_INTEGRITY (-1765328353L) #define KRB5KRB_AP_ERR_TKT_EXPIRED (-1765328352L) #define KRB5KRB_AP_ERR_TKT_NYV (-1765328351L) #define KRB5KRB_AP_ERR_REPEAT (-1765328350L) #define KRB5KRB_AP_ERR_NOT_US (-1765328349L) #define KRB5KRB_AP_ERR_BADMATCH (-1765328348L) #define KRB5KRB_AP_ERR_SKEW (-1765328347L) #define KRB5KRB_AP_ERR_BADADDR (-1765328346L) #define KRB5KRB_AP_ERR_BADVERSION (-1765328345L) #define KRB5KRB_AP_ERR_MSG_TYPE (-1765328344L) #define KRB5KRB_AP_ERR_MODIFIED (-1765328343L) #define KRB5KRB_AP_ERR_BADORDER (-1765328342L) #define KRB5KRB_AP_ERR_ILL_CR_TKT (-1765328341L) #define KRB5KRB_AP_ERR_BADKEYVER (-1765328340L) #define KRB5KRB_AP_ERR_NOKEY (-1765328339L) #define KRB5KRB_AP_ERR_MUT_FAIL (-1765328338L) #define KRB5KRB_AP_ERR_BADDIRECTION (-1765328337L) #define KRB5KRB_AP_ERR_METHOD (-1765328336L) #define KRB5KRB_AP_ERR_BADSEQ (-1765328335L) #define KRB5KRB_AP_ERR_INAPP_CKSUM (-1765328334L) #define KRB5KRB_AP_PATH_NOT_ACCEPTED (-1765328333L) #define KRB5KRB_ERR_RESPONSE_TOO_BIG (-1765328332L) #define KRB5PLACEHOLD_53 (-1765328331L) #define KRB5PLACEHOLD_54 (-1765328330L) #define KRB5PLACEHOLD_55 (-1765328329L) #define KRB5PLACEHOLD_56 (-1765328328L) #define KRB5PLACEHOLD_57 (-1765328327L) #define KRB5PLACEHOLD_58 (-1765328326L) #define KRB5PLACEHOLD_59 (-1765328325L) #define KRB5KRB_ERR_GENERIC (-1765328324L) #define KRB5KRB_ERR_FIELD_TOOLONG (-1765328323L) #define KRB5KDC_ERR_CLIENT_NOT_TRUSTED (-1765328322L) #define KRB5KDC_ERR_KDC_NOT_TRUSTED (-1765328321L) #define KRB5KDC_ERR_INVALID_SIG (-1765328320L) #define KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED (-1765328319L) #define KRB5KDC_ERR_CERTIFICATE_MISMATCH (-1765328318L) #define KRB5KRB_AP_ERR_NO_TGT (-1765328317L) #define KRB5KDC_ERR_WRONG_REALM (-1765328316L) #define KRB5KRB_AP_ERR_USER_TO_USER_REQUIRED (-1765328315L) #define KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE (-1765328314L) #define KRB5KDC_ERR_INVALID_CERTIFICATE (-1765328313L) #define KRB5KDC_ERR_REVOKED_CERTIFICATE (-1765328312L) #define KRB5KDC_ERR_REVOCATION_STATUS_UNKNOWN (-1765328311L) #define KRB5KDC_ERR_REVOCATION_STATUS_UNAVAILABLE (-1765328310L) #define KRB5KDC_ERR_CLIENT_NAME_MISMATCH (-1765328309L) #define KRB5KDC_ERR_KDC_NAME_MISMATCH (-1765328308L) #define KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE (-1765328307L) #define KRB5KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED (-1765328306L) #define KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED (-1765328305L) #define KRB5KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED (-1765328304L) #define KRB5KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED (-1765328303L) #define KRB5PLACEHOLD_82 (-1765328302L) #define KRB5PLACEHOLD_83 (-1765328301L) #define KRB5PLACEHOLD_84 (-1765328300L) #define KRB5KRB_AP_ERR_IAKERB_KDC_NOT_FOUND (-1765328299L) #define KRB5KRB_AP_ERR_IAKERB_KDC_NO_RESPONSE (-1765328298L) #define KRB5PLACEHOLD_87 (-1765328297L) #define KRB5PLACEHOLD_88 (-1765328296L) #define KRB5PLACEHOLD_89 (-1765328295L) #define KRB5KDC_ERR_PREAUTH_EXPIRED (-1765328294L) #define KRB5KDC_ERR_MORE_PREAUTH_DATA_REQUIRED (-1765328293L) #define KRB5PLACEHOLD_92 (-1765328292L) #define KRB5KDC_ERR_UNKNOWN_CRITICAL_FAST_OPTION (-1765328291L) #define KRB5PLACEHOLD_94 (-1765328290L) #define KRB5PLACEHOLD_95 (-1765328289L) #define KRB5PLACEHOLD_96 (-1765328288L) #define KRB5PLACEHOLD_97 (-1765328287L) #define KRB5PLACEHOLD_98 (-1765328286L) #define KRB5PLACEHOLD_99 (-1765328285L) #define KRB5KDC_ERR_NO_ACCEPTABLE_KDF (-1765328284L) #define KRB5PLACEHOLD_101 (-1765328283L) #define KRB5PLACEHOLD_102 (-1765328282L) #define KRB5PLACEHOLD_103 (-1765328281L) #define KRB5PLACEHOLD_104 (-1765328280L) #define KRB5PLACEHOLD_105 (-1765328279L) #define KRB5PLACEHOLD_106 (-1765328278L) #define KRB5PLACEHOLD_107 (-1765328277L) #define KRB5PLACEHOLD_108 (-1765328276L) #define KRB5PLACEHOLD_109 (-1765328275L) #define KRB5PLACEHOLD_110 (-1765328274L) #define KRB5PLACEHOLD_111 (-1765328273L) #define KRB5PLACEHOLD_112 (-1765328272L) #define KRB5PLACEHOLD_113 (-1765328271L) #define KRB5PLACEHOLD_114 (-1765328270L) #define KRB5PLACEHOLD_115 (-1765328269L) #define KRB5PLACEHOLD_116 (-1765328268L) #define KRB5PLACEHOLD_117 (-1765328267L) #define KRB5PLACEHOLD_118 (-1765328266L) #define KRB5PLACEHOLD_119 (-1765328265L) #define KRB5PLACEHOLD_120 (-1765328264L) #define KRB5PLACEHOLD_121 (-1765328263L) #define KRB5PLACEHOLD_122 (-1765328262L) #define KRB5PLACEHOLD_123 (-1765328261L) #define KRB5PLACEHOLD_124 (-1765328260L) #define KRB5PLACEHOLD_125 (-1765328259L) #define KRB5PLACEHOLD_126 (-1765328258L) #define KRB5PLACEHOLD_127 (-1765328257L) #define KRB5_ERR_RCSID (-1765328256L) #define KRB5_LIBOS_BADLOCKFLAG (-1765328255L) #define KRB5_LIBOS_CANTREADPWD (-1765328254L) #define KRB5_LIBOS_BADPWDMATCH (-1765328253L) #define KRB5_LIBOS_PWDINTR (-1765328252L) #define KRB5_PARSE_ILLCHAR (-1765328251L) #define KRB5_PARSE_MALFORMED (-1765328250L) #define KRB5_CONFIG_CANTOPEN (-1765328249L) #define KRB5_CONFIG_BADFORMAT (-1765328248L) #define KRB5_CONFIG_NOTENUFSPACE (-1765328247L) #define KRB5_BADMSGTYPE (-1765328246L) #define KRB5_CC_BADNAME (-1765328245L) #define KRB5_CC_UNKNOWN_TYPE (-1765328244L) #define KRB5_CC_NOTFOUND (-1765328243L) #define KRB5_CC_END (-1765328242L) #define KRB5_NO_TKT_SUPPLIED (-1765328241L) #define KRB5KRB_AP_WRONG_PRINC (-1765328240L) #define KRB5KRB_AP_ERR_TKT_INVALID (-1765328239L) #define KRB5_PRINC_NOMATCH (-1765328238L) #define KRB5_KDCREP_MODIFIED (-1765328237L) #define KRB5_KDCREP_SKEW (-1765328236L) #define KRB5_IN_TKT_REALM_MISMATCH (-1765328235L) #define KRB5_PROG_ETYPE_NOSUPP (-1765328234L) #define KRB5_PROG_KEYTYPE_NOSUPP (-1765328233L) #define KRB5_WRONG_ETYPE (-1765328232L) #define KRB5_PROG_SUMTYPE_NOSUPP (-1765328231L) #define KRB5_REALM_UNKNOWN (-1765328230L) #define KRB5_SERVICE_UNKNOWN (-1765328229L) #define KRB5_KDC_UNREACH (-1765328228L) #define KRB5_NO_LOCALNAME (-1765328227L) #define KRB5_MUTUAL_FAILED (-1765328226L) #define KRB5_RC_TYPE_EXISTS (-1765328225L) #define KRB5_RC_MALLOC (-1765328224L) #define KRB5_RC_TYPE_NOTFOUND (-1765328223L) #define KRB5_RC_UNKNOWN (-1765328222L) #define KRB5_RC_REPLAY (-1765328221L) #define KRB5_RC_IO (-1765328220L) #define KRB5_RC_NOIO (-1765328219L) #define KRB5_RC_PARSE (-1765328218L) #define KRB5_RC_IO_EOF (-1765328217L) #define KRB5_RC_IO_MALLOC (-1765328216L) #define KRB5_RC_IO_PERM (-1765328215L) #define KRB5_RC_IO_IO (-1765328214L) #define KRB5_RC_IO_UNKNOWN (-1765328213L) #define KRB5_RC_IO_SPACE (-1765328212L) #define KRB5_TRANS_CANTOPEN (-1765328211L) #define KRB5_TRANS_BADFORMAT (-1765328210L) #define KRB5_LNAME_CANTOPEN (-1765328209L) #define KRB5_LNAME_NOTRANS (-1765328208L) #define KRB5_LNAME_BADFORMAT (-1765328207L) #define KRB5_CRYPTO_INTERNAL (-1765328206L) #define KRB5_KT_BADNAME (-1765328205L) #define KRB5_KT_UNKNOWN_TYPE (-1765328204L) #define KRB5_KT_NOTFOUND (-1765328203L) #define KRB5_KT_END (-1765328202L) #define KRB5_KT_NOWRITE (-1765328201L) #define KRB5_KT_IOERR (-1765328200L) #define KRB5_NO_TKT_IN_RLM (-1765328199L) #define KRB5DES_BAD_KEYPAR (-1765328198L) #define KRB5DES_WEAK_KEY (-1765328197L) #define KRB5_BAD_ENCTYPE (-1765328196L) #define KRB5_BAD_KEYSIZE (-1765328195L) #define KRB5_BAD_MSIZE (-1765328194L) #define KRB5_CC_TYPE_EXISTS (-1765328193L) #define KRB5_KT_TYPE_EXISTS (-1765328192L) #define KRB5_CC_IO (-1765328191L) #define KRB5_FCC_PERM (-1765328190L) #define KRB5_FCC_NOFILE (-1765328189L) #define KRB5_FCC_INTERNAL (-1765328188L) #define KRB5_CC_WRITE (-1765328187L) #define KRB5_CC_NOMEM (-1765328186L) #define KRB5_CC_FORMAT (-1765328185L) #define KRB5_CC_NOT_KTYPE (-1765328184L) #define KRB5_INVALID_FLAGS (-1765328183L) #define KRB5_NO_2ND_TKT (-1765328182L) #define KRB5_NOCREDS_SUPPLIED (-1765328181L) #define KRB5_SENDAUTH_BADAUTHVERS (-1765328180L) #define KRB5_SENDAUTH_BADAPPLVERS (-1765328179L) #define KRB5_SENDAUTH_BADRESPONSE (-1765328178L) #define KRB5_SENDAUTH_REJECTED (-1765328177L) #define KRB5_PREAUTH_BAD_TYPE (-1765328176L) #define KRB5_PREAUTH_NO_KEY (-1765328175L) #define KRB5_PREAUTH_FAILED (-1765328174L) #define KRB5_RCACHE_BADVNO (-1765328173L) #define KRB5_CCACHE_BADVNO (-1765328172L) #define KRB5_KEYTAB_BADVNO (-1765328171L) #define KRB5_PROG_ATYPE_NOSUPP (-1765328170L) #define KRB5_RC_REQUIRED (-1765328169L) #define KRB5_ERR_BAD_HOSTNAME (-1765328168L) #define KRB5_ERR_HOST_REALM_UNKNOWN (-1765328167L) #define KRB5_SNAME_UNSUPP_NAMETYPE (-1765328166L) #define KRB5KRB_AP_ERR_V4_REPLY (-1765328165L) #define KRB5_REALM_CANT_RESOLVE (-1765328164L) #define KRB5_TKT_NOT_FORWARDABLE (-1765328163L) #define KRB5_FWD_BAD_PRINCIPAL (-1765328162L) #define KRB5_GET_IN_TKT_LOOP (-1765328161L) #define KRB5_CONFIG_NODEFREALM (-1765328160L) #define KRB5_SAM_UNSUPPORTED (-1765328159L) #define KRB5_SAM_INVALID_ETYPE (-1765328158L) #define KRB5_SAM_NO_CHECKSUM (-1765328157L) #define KRB5_SAM_BAD_CHECKSUM (-1765328156L) #define KRB5_KT_NAME_TOOLONG (-1765328155L) #define KRB5_KT_KVNONOTFOUND (-1765328154L) #define KRB5_APPL_EXPIRED (-1765328153L) #define KRB5_LIB_EXPIRED (-1765328152L) #define KRB5_CHPW_PWDNULL (-1765328151L) #define KRB5_CHPW_FAIL (-1765328150L) #define KRB5_KT_FORMAT (-1765328149L) #define KRB5_NOPERM_ETYPE (-1765328148L) #define KRB5_CONFIG_ETYPE_NOSUPP (-1765328147L) #define KRB5_OBSOLETE_FN (-1765328146L) #define KRB5_EAI_FAIL (-1765328145L) #define KRB5_EAI_NODATA (-1765328144L) #define KRB5_EAI_NONAME (-1765328143L) #define KRB5_EAI_SERVICE (-1765328142L) #define KRB5_ERR_NUMERIC_REALM (-1765328141L) #define KRB5_ERR_BAD_S2K_PARAMS (-1765328140L) #define KRB5_ERR_NO_SERVICE (-1765328139L) #define KRB5_CC_READONLY (-1765328138L) #define KRB5_CC_NOSUPP (-1765328137L) #define KRB5_DELTAT_BADFORMAT (-1765328136L) #define KRB5_PLUGIN_NO_HANDLE (-1765328135L) #define KRB5_PLUGIN_OP_NOTSUPP (-1765328134L) #define KRB5_ERR_INVALID_UTF8 (-1765328133L) #define KRB5_ERR_FAST_REQUIRED (-1765328132L) #define KRB5_LOCAL_ADDR_REQUIRED (-1765328131L) #define KRB5_REMOTE_ADDR_REQUIRED (-1765328130L) #define KRB5_TRACE_NOSUPP (-1765328129L) extern const struct error_table et_krb5_error_table; extern void initialize_krb5_error_table(void); /* For compatibility with Heimdal */ extern void initialize_krb5_error_table_r(struct et_list **list); #define ERROR_TABLE_BASE_krb5 (-1765328384L) /* for compatibility with older versions... */ #define init_krb5_err_tbl initialize_krb5_error_table #define krb5_err_base ERROR_TABLE_BASE_krb5 /* * et-h-k5e1_err.h: * This file is automatically generated; please do not edit it. */ #include #define KRB5_PLUGIN_VER_NOTSUPP (-1750600192L) #define KRB5_PLUGIN_BAD_MODULE_SPEC (-1750600191L) #define KRB5_PLUGIN_NAME_NOTFOUND (-1750600190L) #define KRB5KDC_ERR_DISCARD (-1750600189L) #define KRB5_DCC_CANNOT_CREATE (-1750600188L) #define KRB5_KCC_INVALID_ANCHOR (-1750600187L) #define KRB5_KCC_UNKNOWN_VERSION (-1750600186L) #define KRB5_KCC_INVALID_UID (-1750600185L) #define KRB5_KCM_MALFORMED_REPLY (-1750600184L) #define KRB5_KCM_RPC_ERROR (-1750600183L) #define KRB5_KCM_REPLY_TOO_BIG (-1750600182L) #define KRB5_KCM_NO_SERVER (-1750600181L) #define KRB5_CERTAUTH_HWAUTH (-1750600180L) extern const struct error_table et_k5e1_error_table; extern void initialize_k5e1_error_table(void); /* For compatibility with Heimdal */ extern void initialize_k5e1_error_table_r(struct et_list **list); #define ERROR_TABLE_BASE_k5e1 (-1750600192L) /* for compatibility with older versions... */ #define init_k5e1_err_tbl initialize_k5e1_error_table #define k5e1_err_base ERROR_TABLE_BASE_k5e1 /* * et-h-kdb5_err.h: * This file is automatically generated; please do not edit it. */ #include #define KRB5_KDB_RCSID (-1780008448L) #define KRB5_KDB_INUSE (-1780008447L) #define KRB5_KDB_UK_SERROR (-1780008446L) #define KRB5_KDB_UK_RERROR (-1780008445L) #define KRB5_KDB_UNAUTH (-1780008444L) #define KRB5_KDB_NOENTRY (-1780008443L) #define KRB5_KDB_ILL_WILDCARD (-1780008442L) #define KRB5_KDB_DB_INUSE (-1780008441L) #define KRB5_KDB_DB_CHANGED (-1780008440L) #define KRB5_KDB_TRUNCATED_RECORD (-1780008439L) #define KRB5_KDB_RECURSIVELOCK (-1780008438L) #define KRB5_KDB_NOTLOCKED (-1780008437L) #define KRB5_KDB_BADLOCKMODE (-1780008436L) #define KRB5_KDB_DBNOTINITED (-1780008435L) #define KRB5_KDB_DBINITED (-1780008434L) #define KRB5_KDB_ILLDIRECTION (-1780008433L) #define KRB5_KDB_NOMASTERKEY (-1780008432L) #define KRB5_KDB_BADMASTERKEY (-1780008431L) #define KRB5_KDB_INVALIDKEYSIZE (-1780008430L) #define KRB5_KDB_CANTREAD_STORED (-1780008429L) #define KRB5_KDB_BADSTORED_MKEY (-1780008428L) #define KRB5_KDB_NOACTMASTERKEY (-1780008427L) #define KRB5_KDB_KVNONOMATCH (-1780008426L) #define KRB5_KDB_STORED_MKEY_NOTCURRENT (-1780008425L) #define KRB5_KDB_CANTLOCK_DB (-1780008424L) #define KRB5_KDB_DB_CORRUPT (-1780008423L) #define KRB5_KDB_BAD_VERSION (-1780008422L) #define KRB5_KDB_BAD_SALTTYPE (-1780008421L) #define KRB5_KDB_BAD_ENCTYPE (-1780008420L) #define KRB5_KDB_BAD_CREATEFLAGS (-1780008419L) #define KRB5_KDB_NO_PERMITTED_KEY (-1780008418L) #define KRB5_KDB_NO_MATCHING_KEY (-1780008417L) #define KRB5_KDB_DBTYPE_NOTFOUND (-1780008416L) #define KRB5_KDB_DBTYPE_NOSUP (-1780008415L) #define KRB5_KDB_DBTYPE_INIT (-1780008414L) #define KRB5_KDB_SERVER_INTERNAL_ERR (-1780008413L) #define KRB5_KDB_ACCESS_ERROR (-1780008412L) #define KRB5_KDB_INTERNAL_ERROR (-1780008411L) #define KRB5_KDB_CONSTRAINT_VIOLATION (-1780008410L) #define KRB5_LOG_CONV (-1780008409L) #define KRB5_LOG_UNSTABLE (-1780008408L) #define KRB5_LOG_CORRUPT (-1780008407L) #define KRB5_LOG_ERROR (-1780008406L) #define KRB5_KDB_DBTYPE_MISMATCH (-1780008405L) #define KRB5_KDB_POLICY_REF (-1780008404L) #define KRB5_KDB_STRINGS_TOOLONG (-1780008403L) extern const struct error_table et_kdb5_error_table; extern void initialize_kdb5_error_table(void); /* For compatibility with Heimdal */ extern void initialize_kdb5_error_table_r(struct et_list **list); #define ERROR_TABLE_BASE_kdb5 (-1780008448L) /* for compatibility with older versions... */ #define init_kdb5_err_tbl initialize_kdb5_error_table #define kdb5_err_base ERROR_TABLE_BASE_kdb5 /* * et-h-kv5m_err.h: * This file is automatically generated; please do not edit it. */ #include #define KV5M_NONE (-1760647424L) #define KV5M_PRINCIPAL (-1760647423L) #define KV5M_DATA (-1760647422L) #define KV5M_KEYBLOCK (-1760647421L) #define KV5M_CHECKSUM (-1760647420L) #define KV5M_ENCRYPT_BLOCK (-1760647419L) #define KV5M_ENC_DATA (-1760647418L) #define KV5M_CRYPTOSYSTEM_ENTRY (-1760647417L) #define KV5M_CS_TABLE_ENTRY (-1760647416L) #define KV5M_CHECKSUM_ENTRY (-1760647415L) #define KV5M_AUTHDATA (-1760647414L) #define KV5M_TRANSITED (-1760647413L) #define KV5M_ENC_TKT_PART (-1760647412L) #define KV5M_TICKET (-1760647411L) #define KV5M_AUTHENTICATOR (-1760647410L) #define KV5M_TKT_AUTHENT (-1760647409L) #define KV5M_CREDS (-1760647408L) #define KV5M_LAST_REQ_ENTRY (-1760647407L) #define KV5M_PA_DATA (-1760647406L) #define KV5M_KDC_REQ (-1760647405L) #define KV5M_ENC_KDC_REP_PART (-1760647404L) #define KV5M_KDC_REP (-1760647403L) #define KV5M_ERROR (-1760647402L) #define KV5M_AP_REQ (-1760647401L) #define KV5M_AP_REP (-1760647400L) #define KV5M_AP_REP_ENC_PART (-1760647399L) #define KV5M_RESPONSE (-1760647398L) #define KV5M_SAFE (-1760647397L) #define KV5M_PRIV (-1760647396L) #define KV5M_PRIV_ENC_PART (-1760647395L) #define KV5M_CRED (-1760647394L) #define KV5M_CRED_INFO (-1760647393L) #define KV5M_CRED_ENC_PART (-1760647392L) #define KV5M_PWD_DATA (-1760647391L) #define KV5M_ADDRESS (-1760647390L) #define KV5M_KEYTAB_ENTRY (-1760647389L) #define KV5M_CONTEXT (-1760647388L) #define KV5M_OS_CONTEXT (-1760647387L) #define KV5M_ALT_METHOD (-1760647386L) #define KV5M_ETYPE_INFO_ENTRY (-1760647385L) #define KV5M_DB_CONTEXT (-1760647384L) #define KV5M_AUTH_CONTEXT (-1760647383L) #define KV5M_KEYTAB (-1760647382L) #define KV5M_RCACHE (-1760647381L) #define KV5M_CCACHE (-1760647380L) #define KV5M_PREAUTH_OPS (-1760647379L) #define KV5M_SAM_CHALLENGE (-1760647378L) #define KV5M_SAM_CHALLENGE_2 (-1760647377L) #define KV5M_SAM_KEY (-1760647376L) #define KV5M_ENC_SAM_RESPONSE_ENC (-1760647375L) #define KV5M_ENC_SAM_RESPONSE_ENC_2 (-1760647374L) #define KV5M_SAM_RESPONSE (-1760647373L) #define KV5M_SAM_RESPONSE_2 (-1760647372L) #define KV5M_PREDICTED_SAM_RESPONSE (-1760647371L) #define KV5M_PASSWD_PHRASE_ELEMENT (-1760647370L) #define KV5M_GSS_OID (-1760647369L) #define KV5M_GSS_QUEUE (-1760647368L) #define KV5M_FAST_ARMORED_REQ (-1760647367L) #define KV5M_FAST_REQ (-1760647366L) #define KV5M_FAST_RESPONSE (-1760647365L) #define KV5M_AUTHDATA_CONTEXT (-1760647364L) extern const struct error_table et_kv5m_error_table; extern void initialize_kv5m_error_table(void); /* For compatibility with Heimdal */ extern void initialize_kv5m_error_table_r(struct et_list **list); #define ERROR_TABLE_BASE_kv5m (-1760647424L) /* for compatibility with older versions... */ #define init_kv5m_err_tbl initialize_kv5m_error_table #define kv5m_err_base ERROR_TABLE_BASE_kv5m /* * et-h-krb524_err.h: * This file is automatically generated; please do not edit it. */ #include #define KRB524_BADKEY (-1750206208L) #define KRB524_BADADDR (-1750206207L) #define KRB524_BADPRINC (-1750206206L) #define KRB524_BADREALM (-1750206205L) #define KRB524_V4ERR (-1750206204L) #define KRB524_ENCFULL (-1750206203L) #define KRB524_DECEMPTY (-1750206202L) #define KRB524_NOTRESP (-1750206201L) #define KRB524_KRB4_DISABLED (-1750206200L) extern const struct error_table et_k524_error_table; extern void initialize_k524_error_table(void); /* For compatibility with Heimdal */ extern void initialize_k524_error_table_r(struct et_list **list); #define ERROR_TABLE_BASE_k524 (-1750206208L) /* for compatibility with older versions... */ #define init_k524_err_tbl initialize_k524_error_table #define k524_err_base ERROR_TABLE_BASE_k524 /* * et-h-asn1_err.h: * This file is automatically generated; please do not edit it. */ #include #define ASN1_BAD_TIMEFORMAT (1859794432L) #define ASN1_MISSING_FIELD (1859794433L) #define ASN1_MISPLACED_FIELD (1859794434L) #define ASN1_TYPE_MISMATCH (1859794435L) #define ASN1_OVERFLOW (1859794436L) #define ASN1_OVERRUN (1859794437L) #define ASN1_BAD_ID (1859794438L) #define ASN1_BAD_LENGTH (1859794439L) #define ASN1_BAD_FORMAT (1859794440L) #define ASN1_PARSE_ERROR (1859794441L) #define ASN1_BAD_GMTIME (1859794442L) #define ASN1_MISMATCH_INDEF (1859794443L) #define ASN1_MISSING_EOC (1859794444L) #define ASN1_OMITTED (1859794445L) extern const struct error_table et_asn1_error_table; extern void initialize_asn1_error_table(void); /* For compatibility with Heimdal */ extern void initialize_asn1_error_table_r(struct et_list **list); #define ERROR_TABLE_BASE_asn1 (1859794432L) /* for compatibility with older versions... */ #define init_asn1_err_tbl initialize_asn1_error_table #define asn1_err_base ERROR_TABLE_BASE_asn1 #endif /* KRB5_KRB5_H_INCLUDED */ krb5/ccselect_plugin.h000064400000010165151027430560010731 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2011 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Declarations for credential cache selection module implementors. * * The ccselect pluggable interface currently has only one supported major * version, which is 1. Major version 1 has a current minor version number of * 1. * * Credential cache selection modules should define a function named * ccselect__initvt, matching the signature: * * krb5_error_code * ccselect_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_ccselect_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_CCSELECT_PLUGIN_H #define KRB5_CCSELECT_PLUGIN_H #include #include /* An abstract type for credential cache selection module data. */ typedef struct krb5_ccselect_moddata_st *krb5_ccselect_moddata; #define KRB5_CCSELECT_PRIORITY_AUTHORITATIVE 2 #define KRB5_CCSELECT_PRIORITY_HEURISTIC 1 /*** Method type declarations ***/ /* * Mandatory: Initialize module data and set *priority_out to one of the * KRB5_CCSELECT_PRIORITY constants above. Authoritative modules will be * consulted before heuristic ones. */ typedef krb5_error_code (*krb5_ccselect_init_fn)(krb5_context context, krb5_ccselect_moddata *data_out, int *priority_out); /* * Mandatory: Select a cache based on a server principal. Return 0 on success, * with *cache_out set to the selected cache and *princ_out set to its default * principal. Return KRB5_PLUGIN_NO_HANDLE to defer to other modules. Return * KRB5_CC_NOTFOUND with *princ_out set if the client principal can be * authoritatively determined but no cache exists for it. Return other errors * as appropriate. */ typedef krb5_error_code (*krb5_ccselect_choose_fn)(krb5_context context, krb5_ccselect_moddata data, krb5_principal server, krb5_ccache *cache_out, krb5_principal *princ_out); /* Optional: Release resources used by module data. */ typedef void (*krb5_ccselect_fini_fn)(krb5_context context, krb5_ccselect_moddata data); /*** vtable declarations **/ /* Credential cache selection plugin vtable for major version 1. */ typedef struct krb5_ccselect_vtable_st { const char *name; /* Mandatory: name of module. */ krb5_ccselect_init_fn init; krb5_ccselect_choose_fn choose; krb5_ccselect_fini_fn fini; /* Minor version 1 ends here. */ } *krb5_ccselect_vtable; #endif /* KRB5_CCSELECT_PLUGIN_H */ krb5/kdcpolicy_plugin.h000064400000012310151027430560011117 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* include/krb5/kdcpolicy_plugin.h - KDC policy plugin interface */ /* * Copyright (C) 2017 by Red Hat, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for kdcpolicy plugin module implementors. * * The kdcpolicy pluggable interface currently has only one supported major * version, which is 1. Major version 1 has a current minor version number of * 1. * * kdcpolicy plugin modules should define a function named * kdcpolicy__initvt, matching the signature: * * krb5_error_code * kdcpolicy_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_kdcpolicy_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_POLICY_PLUGIN_H #define KRB5_POLICY_PLUGIN_H #include /* Abstract module datatype. */ typedef struct krb5_kdcpolicy_moddata_st *krb5_kdcpolicy_moddata; /* A module can optionally include kdb.h to inspect principal entries when * authorizing requests. */ struct _krb5_db_entry_new; /* * Optional: Initialize module data. Return 0 on success, * KRB5_PLUGIN_NO_HANDLE if the module is inoperable (due to configuration, for * example), and any other error code to abort KDC startup. Optionally set * *data_out to a module data object to be passed to future calls. */ typedef krb5_error_code (*krb5_kdcpolicy_init_fn)(krb5_context context, krb5_kdcpolicy_moddata *data_out); /* Optional: Clean up module data. */ typedef krb5_error_code (*krb5_kdcpolicy_fini_fn)(krb5_context context, krb5_kdcpolicy_moddata moddata); /* * Optional: return an error code and set status to an appropriate string * literal to deny an AS request; otherwise return 0. lifetime_out, if set, * restricts the ticket lifetime. renew_lifetime_out, if set, restricts the * ticket renewable lifetime. */ typedef krb5_error_code (*krb5_kdcpolicy_check_as_fn)(krb5_context context, krb5_kdcpolicy_moddata moddata, const krb5_kdc_req *request, const struct _krb5_db_entry_new *client, const struct _krb5_db_entry_new *server, const char *const *auth_indicators, const char **status, krb5_deltat *lifetime_out, krb5_deltat *renew_lifetime_out); /* * Optional: return an error code and set status to an appropriate string * literal to deny a TGS request; otherwise return 0. lifetime_out, if set, * restricts the ticket lifetime. renew_lifetime_out, if set, restricts the * ticket renewable lifetime. */ typedef krb5_error_code (*krb5_kdcpolicy_check_tgs_fn)(krb5_context context, krb5_kdcpolicy_moddata moddata, const krb5_kdc_req *request, const struct _krb5_db_entry_new *server, const krb5_ticket *ticket, const char *const *auth_indicators, const char **status, krb5_deltat *lifetime_out, krb5_deltat *renew_lifetime_out); typedef struct krb5_kdcpolicy_vtable_st { const char *name; krb5_kdcpolicy_init_fn init; krb5_kdcpolicy_fini_fn fini; krb5_kdcpolicy_check_as_fn check_as; krb5_kdcpolicy_check_tgs_fn check_tgs; } *krb5_kdcpolicy_vtable; #endif /* KRB5_POLICY_PLUGIN_H */ krb5/locate_plugin.h000064400000005100151027430560010404 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2006 Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * * Service location plugin definitions for Kerberos 5. */ #ifndef KRB5_LOCATE_PLUGIN_H_INCLUDED #define KRB5_LOCATE_PLUGIN_H_INCLUDED #include enum locate_service_type { locate_service_kdc = 1, locate_service_master_kdc, locate_service_kadmin, locate_service_krb524, locate_service_kpasswd }; typedef struct krb5plugin_service_locate_ftable { int minor_version; /* currently 0 */ /* Per-context setup and teardown. Returned void* blob is private to the plugin. */ krb5_error_code (*init)(krb5_context, void **); void (*fini)(void *); /* Callback function returns non-zero if the plugin function should quit and return; this may be because of an error, or may indicate we've already contacted the service, whatever. The lookup function should only return an error if it detects a problem, not if the callback function tells it to quit. */ krb5_error_code (*lookup)(void *, enum locate_service_type svc, const char *realm, int socktype, int family, int (*cbfunc)(void *,int,struct sockaddr *), void *cbdata); } krb5plugin_service_locate_ftable; /* extern krb5plugin_service_locate_ftable service_locator; */ #endif krb5/kdcpreauth_plugin.h000064400000042172151027430560011301 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (c) 2006 Red Hat, Inc. * Portions copyright (c) 2006, 2011 Massachusetts Institute of Technology * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Red Hat, Inc., nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for kdcpreauth plugin module implementors. * * The kdcpreauth interface has a single supported major version, which is 1. * Major version 1 has a current minor version of 2. kdcpreauth modules should * define a function named kdcpreauth__initvt, matching the * signature: * * krb5_error_code * kdcpreauth_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for the interface and maj_ver: * kdcpreauth, maj_ver == 1: Cast to krb5_kdcpreauth_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_KDCPREAUTH_PLUGIN_H #define KRB5_KDCPREAUTH_PLUGIN_H #include #include /* kdcpreauth mechanism property flags */ /* * Causes the KDC to include this mechanism in a list of supported preauth * types if the user's DB entry flags the user as requiring hardware-based * preauthentication. */ #define PA_HARDWARE 0x00000004 /* * Causes the KDC to include this mechanism in a list of supported preauth * types if the user's DB entry flags the user as requiring preauthentication, * and to fail preauthentication if we can't verify the client data. The * flipside of PA_SUFFICIENT. */ #define PA_REQUIRED 0x00000008 /* * Causes the KDC to include this mechanism in a list of supported preauth * types if the user's DB entry flags the user as requiring preauthentication, * and to mark preauthentication as successful if we can verify the client * data. The flipside of PA_REQUIRED. */ #define PA_SUFFICIENT 0x00000010 /* * Marks this preauthentication mechanism as one which changes the key which is * used for encrypting the response to the client. Modules which have this * flag have their server_return_fn called before modules which do not, and are * passed over if a previously-called module has modified the encrypting key. */ #define PA_REPLACES_KEY 0x00000020 /* * Not really a padata type, so don't include it in any list of preauth types * which gets sent over the wire. */ #define PA_PSEUDO 0x00000080 /* * Indicates that e_data in non-FAST errors should be encoded as typed data * instead of padata. */ #define PA_TYPED_E_DATA 0x00000100 /* Abstract type for a KDC callback data handle. */ typedef struct krb5_kdcpreauth_rock_st *krb5_kdcpreauth_rock; /* Abstract type for module data and per-request module data. */ typedef struct krb5_kdcpreauth_moddata_st *krb5_kdcpreauth_moddata; typedef struct krb5_kdcpreauth_modreq_st *krb5_kdcpreauth_modreq; /* The verto context structure type (typedef is in verto.h; we want to avoid a * header dependency for the moment). */ struct verto_ctx; /* Before using a callback after version 1, modules must check the vers * field of the callback structure. */ typedef struct krb5_kdcpreauth_callbacks_st { int vers; krb5_deltat (*max_time_skew)(krb5_context context, krb5_kdcpreauth_rock rock); /* * Get an array of krb5_keyblock structures containing the client keys * matching the request enctypes, terminated by an entry with key type = 0. * Returns ENOENT if no keys are available for the request enctypes. Free * the resulting object with the free_keys callback. */ krb5_error_code (*client_keys)(krb5_context context, krb5_kdcpreauth_rock rock, krb5_keyblock **keys_out); /* Free the result of client_keys. */ void (*free_keys)(krb5_context context, krb5_kdcpreauth_rock rock, krb5_keyblock *keys); /* * Get the encoded request body, which is sometimes needed for checksums. * For a FAST request this is the encoded inner request body. The returned * pointer is an alias and should not be freed. */ krb5_data *(*request_body)(krb5_context context, krb5_kdcpreauth_rock rock); /* Get a pointer to the FAST armor key, or NULL if the request did not use * FAST. The returned pointer is an alias and should not be freed. */ krb5_keyblock *(*fast_armor)(krb5_context context, krb5_kdcpreauth_rock rock); /* Retrieve a string attribute from the client DB entry, or NULL if no such * attribute is set. Free the result with the free_string callback. */ krb5_error_code (*get_string)(krb5_context context, krb5_kdcpreauth_rock rock, const char *key, char **value_out); /* Free the result of get_string. */ void (*free_string)(krb5_context context, krb5_kdcpreauth_rock rock, char *string); /* Get a pointer to the client DB entry (returned as a void pointer to * avoid a dependency on a libkdb5 type). */ void *(*client_entry)(krb5_context context, krb5_kdcpreauth_rock rock); /* Get a pointer to the verto context which should be used by an * asynchronous edata or verify method. */ struct verto_ctx *(*event_context)(krb5_context context, krb5_kdcpreauth_rock rock); /* End of version 1 kdcpreauth callbacks. */ /* Return true if the client DB entry contains any keys matching the * request enctypes. */ krb5_boolean (*have_client_keys)(krb5_context context, krb5_kdcpreauth_rock rock); /* End of version 2 kdcpreauth callbacks. */ /* * Get the decrypted client long-term key chosen according to the request * enctype list, or NULL if no matching key was found. The returned * pointer is an alias and should not be freed. If invoked from * return_padata, the result will be the same as the encrypting_key * parameter if it is not NULL, and will therefore reflect the modified * reply key if a return_padata handler has replaced the reply key. */ const krb5_keyblock *(*client_keyblock)(krb5_context context, krb5_kdcpreauth_rock rock); /* Assert an authentication indicator in the AS-REP authdata. Duplicate * indicators will be ignored. */ krb5_error_code (*add_auth_indicator)(krb5_context context, krb5_kdcpreauth_rock rock, const char *indicator); /* * Read a data value for pa_type from the request cookie, placing it in * *out. The value placed there is an alias and must not be freed. * Returns true if a value for pa_type was retrieved, false if not. */ krb5_boolean (*get_cookie)(krb5_context context, krb5_kdcpreauth_rock rock, krb5_preauthtype pa_type, krb5_data *out); /* * Set a data value for pa_type to be sent in a secure cookie in the next * error response. If pa_type is already present, the value is ignored. * If the preauth mechanism has different preauth types for requests and * responses, use the request type. Secure cookies are encrypted in a key * known only to the KDCs, but can be replayed within a short time window * for requests using the same client principal. */ krb5_error_code (*set_cookie)(krb5_context context, krb5_kdcpreauth_rock rock, krb5_preauthtype pa_type, const krb5_data *data); /* End of version 3 kdcpreauth callbacks. */ /* * Return true if princ matches the principal named in the request or the * client principal (possibly canonicalized). If princ does not match, * attempt a database lookup of princ with aliases allowed and compare the * result to the client principal, returning true if it matches. * Otherwise, return false. */ krb5_boolean (*match_client)(krb5_context context, krb5_kdcpreauth_rock rock, krb5_principal princ); /* * Get an alias to the client DB entry principal (possibly canonicalized). */ krb5_principal (*client_name)(krb5_context context, krb5_kdcpreauth_rock rock); /* End of version 4 kdcpreauth callbacks. */ /* * Instruct the KDC to send a freshness token in the method data * accompanying a PREAUTH_REQUIRED or PREAUTH_FAILED error, if the client * indicated support for freshness tokens. This callback should only be * invoked from the edata method. */ void (*send_freshness_token)(krb5_context context, krb5_kdcpreauth_rock rock); /* Validate a freshness token sent by the client. Return 0 on success, * KRB5KDC_ERR_PREAUTH_EXPIRED on error. */ krb5_error_code (*check_freshness_token)(krb5_context context, krb5_kdcpreauth_rock rock, const krb5_data *token); /* End of version 5 kdcpreauth callbacks. */ } *krb5_kdcpreauth_callbacks; /* Optional: preauth plugin initialization function. */ typedef krb5_error_code (*krb5_kdcpreauth_init_fn)(krb5_context context, krb5_kdcpreauth_moddata *moddata_out, const char **realmnames); /* Optional: preauth plugin cleanup function. */ typedef void (*krb5_kdcpreauth_fini_fn)(krb5_context context, krb5_kdcpreauth_moddata moddata); /* * Optional: return the flags which the KDC should use for this module. This * is a callback instead of a static value because the module may or may not * wish to count itself as a hardware preauthentication module (in other words, * the flags may be affected by the configuration, for example if a site * administrator can force a particular preauthentication type to be supported * using only hardware). This function is called for each entry entry in the * server_pa_type_list. */ typedef int (*krb5_kdcpreauth_flags_fn)(krb5_context context, krb5_preauthtype pa_type); /* * Responder for krb5_kdcpreauth_edata_fn. If invoked with a non-zero code, pa * will be ignored and the padata type will not be included in the hint list. * If invoked with a zero code and a null pa value, the padata type will be * included in the list with an empty value. If invoked with a zero code and a * non-null pa value, pa will be included in the hint list and will later be * freed by the KDC. */ typedef void (*krb5_kdcpreauth_edata_respond_fn)(void *arg, krb5_error_code code, krb5_pa_data *pa); /* * Optional: provide pa_data to send to the client as part of the "you need to * use preauthentication" error. The implementation must invoke the respond * when complete, whether successful or not, either before returning or * asynchronously using the verto context returned by cb->event_context(). * * This function is not allowed to create a modreq object because we have no * guarantee that the client will ever make a follow-up request, or that it * will hit this KDC if it does. */ typedef void (*krb5_kdcpreauth_edata_fn)(krb5_context context, krb5_kdc_req *request, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_preauthtype pa_type, krb5_kdcpreauth_edata_respond_fn respond, void *arg); /* * Responder for krb5_kdcpreauth_verify_fn. Invoke with the arg parameter * supplied to verify, the error code (0 for success), an optional module * request state object to be consumed by return_fn or free_modreq_fn, optional * e_data to be passed to the caller if code is nonzero, and optional * authorization data to be included in the ticket. In non-FAST replies, * e_data will be encoded as typed-data if the module sets the PA_TYPED_E_DATA * flag, and as pa-data otherwise. e_data and authz_data will be freed by the * KDC. */ typedef void (*krb5_kdcpreauth_verify_respond_fn)(void *arg, krb5_error_code code, krb5_kdcpreauth_modreq modreq, krb5_pa_data **e_data, krb5_authdata **authz_data); /* * Optional: verify preauthentication data sent by the client, setting the * TKT_FLG_PRE_AUTH or TKT_FLG_HW_AUTH flag in the enc_tkt_reply's "flags" * field as appropriate. The implementation must invoke the respond function * when complete, whether successful or not, either before returning or * asynchronously using the verto context returned by cb->event_context(). */ typedef void (*krb5_kdcpreauth_verify_fn)(krb5_context context, krb5_data *req_pkt, krb5_kdc_req *request, krb5_enc_tkt_part *enc_tkt_reply, krb5_pa_data *data, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_verify_respond_fn respond, void *arg); /* * Optional: generate preauthentication response data to send to the client as * part of the AS-REP. If it needs to override the key which is used to * encrypt the response, it can do so. */ typedef krb5_error_code (*krb5_kdcpreauth_return_fn)(krb5_context context, krb5_pa_data *padata, krb5_data *req_pkt, krb5_kdc_req *request, krb5_kdc_rep *reply, krb5_keyblock *encrypting_key, krb5_pa_data **send_pa_out, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_modreq modreq); /* Optional: free a per-request context. */ typedef void (*krb5_kdcpreauth_free_modreq_fn)(krb5_context, krb5_kdcpreauth_moddata moddata, krb5_kdcpreauth_modreq modreq); /* Optional: invoked after init_fn to provide the module with a pointer to the * verto main loop. */ typedef krb5_error_code (*krb5_kdcpreauth_loop_fn)(krb5_context context, krb5_kdcpreauth_moddata moddata, struct verto_ctx *ctx); typedef struct krb5_kdcpreauth_vtable_st { /* Mandatory: name of module. */ char *name; /* Mandatory: pointer to zero-terminated list of pa_types which this module * can provide services for. */ krb5_preauthtype *pa_type_list; krb5_kdcpreauth_init_fn init; krb5_kdcpreauth_fini_fn fini; krb5_kdcpreauth_flags_fn flags; krb5_kdcpreauth_edata_fn edata; krb5_kdcpreauth_verify_fn verify; krb5_kdcpreauth_return_fn return_padata; krb5_kdcpreauth_free_modreq_fn free_modreq; /* Minor 1 ends here. */ krb5_kdcpreauth_loop_fn loop; /* Minor 2 ends here. */ } *krb5_kdcpreauth_vtable; #endif /* KRB5_KDCPREAUTH_PLUGIN_H */ krb5/plugin.h000064400000004052151027430560007062 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2010 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* Generic declarations for dynamic modules implementing krb5 plugin * modules. */ #ifndef KRB5_PLUGIN_H #define KRB5_PLUGIN_H /* krb5_plugin_vtable is an abstract type. Module initvt functions will cast * it to the appropriate interface-specific vtable type. */ typedef struct krb5_plugin_vtable_st *krb5_plugin_vtable; /* * krb5_plugin_initvt_fn is the type of all module initvt functions. Based on * the maj_ver argument, the initvt function should cast vtable to the * appropriate type and then fill it in. If a vtable has been expanded, * min_ver indicates which version of the vtable is being filled in. */ typedef krb5_error_code (*krb5_plugin_initvt_fn)(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable); #endif /* KRB5_PLUGIN_H */ krb5/certauth_plugin.h000064400000011771151027430560010767 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* include/krb5/certauth_plugin.h - certauth plugin header. */ /* * Copyright (C) 2017 by Red Hat, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for certauth plugin module implementors. * * The certauth pluggable interface currently has only one supported major * version, which is 1. Major version 1 has a current minor version number of * 1. * * certauth plugin modules should define a function named * certauth__initvt, matching the signature: * * krb5_error_code * certauth_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_certauth_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_CERTAUTH_PLUGIN_H #define KRB5_CERTAUTH_PLUGIN_H #include #include /* Abstract module data type. */ typedef struct krb5_certauth_moddata_st *krb5_certauth_moddata; /* A module can optionally include to inspect the client principal * entry when authorizing a request. */ struct _krb5_db_entry_new; /* * Optional: Initialize module data. */ typedef krb5_error_code (*krb5_certauth_init_fn)(krb5_context context, krb5_certauth_moddata *moddata_out); /* * Optional: Clean up the module data. */ typedef void (*krb5_certauth_fini_fn)(krb5_context context, krb5_certauth_moddata moddata); /* * Mandatory: return 0 or KRB5_CERTAUTH_HWAUTH if the DER-encoded cert is * authorized for PKINIT authentication by princ; otherwise return one of the * following error codes: * - KRB5KDC_ERR_CLIENT_NAME_MISMATCH - incorrect SAN value * - KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE - incorrect EKU * - KRB5KDC_ERR_CERTIFICATE_MISMATCH - other extension error * - KRB5_PLUGIN_NO_HANDLE - the module has no opinion about cert * * Returning KRB5_CERTAUTH_HWAUTH will cause the hw-authent flag to be set in * the issued ticket (new in release 1.19). * * - opts is used by built-in modules to receive internal data, and must be * ignored by other modules. * - db_entry receives the client principal database entry, and can be ignored * by modules that do not link with libkdb5. * - *authinds_out optionally returns a null-terminated list of authentication * indicator strings upon KRB5_PLUGIN_NO_HANDLE or accepted authorization. */ typedef krb5_error_code (*krb5_certauth_authorize_fn)(krb5_context context, krb5_certauth_moddata moddata, const uint8_t *cert, size_t cert_len, krb5_const_principal princ, const void *opts, const struct _krb5_db_entry_new *db_entry, char ***authinds_out); /* * Free indicators allocated by a module. Mandatory if authorize returns * authentication indicators. */ typedef void (*krb5_certauth_free_indicator_fn)(krb5_context context, krb5_certauth_moddata moddata, char **authinds); typedef struct krb5_certauth_vtable_st { const char *name; krb5_certauth_init_fn init; krb5_certauth_fini_fn fini; krb5_certauth_authorize_fn authorize; krb5_certauth_free_indicator_fn free_ind; } *krb5_certauth_vtable; #endif /* KRB5_CERTAUTH_PLUGIN_H */ krb5/hostrealm_plugin.h000064400000012524151027430560011143 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2013 by the Massachusetts Institute of Technology. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for hostrealm plugin module implementors. * * The hostrealm pluggable interface currently has only one supported major * version, which is 1. Major version 1 has a current minor version number of * 1. * * Hostrealm plugin modules should define a function named * hostrealm__initvt, matching the signature: * * krb5_error_code * hostrealm_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_hostrealm_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_HOSTREALM_PLUGIN_H #define KRB5_HOSTREALM_PLUGIN_H #include #include /* An abstract type for hostrealm module data. */ typedef struct krb5_hostrealm_moddata_st *krb5_hostrealm_moddata; /*** Method type declarations ***/ /* Optional: Initialize module data. */ typedef krb5_error_code (*krb5_hostrealm_init_fn)(krb5_context context, krb5_hostrealm_moddata *data); /* * Optional: Determine the possible realms of a hostname, using only secure, * authoritative mechanisms (ones which should be used prior to trying * referrals when getting a service ticket). Return success with a * null-terminated list of realms in *realms_out, KRB5_PLUGIN_NO_HANDLE to * defer to later modules, or another error to terminate processing. */ typedef krb5_error_code (*krb5_hostrealm_host_realm_fn)(krb5_context context, krb5_hostrealm_moddata data, const char *host, char ***realms_out); /* * Optional: Determine the possible realms of a hostname, using heuristic or * less secure mechanisms (ones which should be used after trying referrals * when getting a service ticket). Return success with a null-terminated list * of realms in *realms_out, KRB5_PLUGIN_NO_HANDLE to defer to later modules, * or another error to terminate processing. */ typedef krb5_error_code (*krb5_hostrealm_fallback_realm_fn)(krb5_context context, krb5_hostrealm_moddata data, const char *host, char ***realms_out); /* * Optional: Determine the possible default realms of the local host. Return * success with a null-terminated list of realms in *realms_out, * KRB5_PLUGIN_NO_HANDLE to defer to later modules, or another error to * terminate processing. */ typedef krb5_error_code (*krb5_hostrealm_default_realm_fn)(krb5_context context, krb5_hostrealm_moddata data, char ***realms_out); /* * Mandatory (if any of the query methods are implemented): Release the memory * returned by one of the interface methods. */ typedef void (*krb5_hostrealm_free_list_fn)(krb5_context context, krb5_hostrealm_moddata data, char **list); /* Optional: Release resources used by module data. */ typedef void (*krb5_hostrealm_fini_fn)(krb5_context context, krb5_hostrealm_moddata data); /* hostrealm vtable for major version 1. */ typedef struct krb5_hostrealm_vtable_st { const char *name; /* Mandatory: name of module. */ krb5_hostrealm_init_fn init; krb5_hostrealm_fini_fn fini; krb5_hostrealm_host_realm_fn host_realm; krb5_hostrealm_fallback_realm_fn fallback_realm; krb5_hostrealm_default_realm_fn default_realm; krb5_hostrealm_free_list_fn free_list; /* Minor version 1 ends here. */ } *krb5_hostrealm_vtable; #endif /* KRB5_HOSTREALM_PLUGIN_H */ krb5/pwqual_plugin.h000064400000010512151027430560010451 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2010 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Declarations for password quality plugin module implementors. * * The password quality pluggable interface currently has only one supported * major version, which is 1. Major version 1 has a current minor version * number of 1. * * Password quality plugin modules should define a function named * pwqual__initvt, matching the signature: * * krb5_error_code * pwqual_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_pwqual_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_PWQUAL_PLUGIN_H #define KRB5_PWQUAL_PLUGIN_H #include #include #include /* An abstract type for password quality module data. */ typedef struct krb5_pwqual_moddata_st *krb5_pwqual_moddata; /*** Method type declarations ***/ /* Optional: Initialize module data. dictfile is the realm's configured * dictionary filename. */ typedef krb5_error_code (*krb5_pwqual_open_fn)(krb5_context context, const char *dict_file, krb5_pwqual_moddata *data); /* * Mandatory: Check a password for the principal princ, which has an associated * password policy named policy_name (or no associated policy if policy_name is * NULL). The parameter languages, if not NULL, contains a null-terminated * list of client-specified language tags as defined in RFC 5646. The method * should return one of the following errors if the password fails quality * standards: * * - KADM5_PASS_Q_TOOSHORT: password should be longer * - KADM5_PASS_Q_CLASS: password must have more character classes * - KADM5_PASS_Q_DICT: password contains dictionary words * - KADM5_PASS_Q_GENERIC: unspecified quality failure * * The module should also set an extended error message with * krb5_set_error_message(). The message may be localized according to one of * the language tags in languages. */ typedef krb5_error_code (*krb5_pwqual_check_fn)(krb5_context context, krb5_pwqual_moddata data, const char *password, const char *policy_name, krb5_principal princ, const char **languages); /* Optional: Release resources used by module data. */ typedef void (*krb5_pwqual_close_fn)(krb5_context context, krb5_pwqual_moddata data); /*** vtable declarations **/ /* Password quality plugin vtable for major version 1. */ typedef struct krb5_pwqual_vtable_st { const char *name; /* Mandatory: name of module. */ krb5_pwqual_open_fn open; krb5_pwqual_check_fn check; krb5_pwqual_close_fn close; /* Minor version 1 ends here. */ } *krb5_pwqual_vtable; #endif /* KRB5_PWQUAL_PLUGIN_H */ krb5/kadm5_auth_plugin.h000064400000030302151027430560011161 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2017 by the Massachusetts Institute of Technology. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Declarations for kadm5_auth plugin module implementors. * * The kadm5_auth pluggable interface currently has only one supported major * version, which is 1. Major version 1 has a current minor version number of * 1. * * kadm5_auth plugin modules should define a function named * kadm5_auth__initvt, matching the signature: * * krb5_error_code * kadm5_auth_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to krb5_kadm5_auth_vtable * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #ifndef KRB5_KADM5_AUTH_PLUGIN_H #define KRB5_KADM5_AUTH_PLUGIN_H #include #include /* An abstract type for kadm5_auth module data. */ typedef struct kadm5_auth_moddata_st *kadm5_auth_moddata; /* * A module can optionally include to inspect principal or * policy records from requests that add or modify principals or policies. * Note that fields of principal and policy structures are only valid if the * corresponding bit is set in the accompanying mask parameter. */ struct _kadm5_principal_ent_t; struct _kadm5_policy_ent_t; /* * A module can optionally generate restrictions when checking permissions for * adding or modifying a principal entry. Restriction fields will only be * honored if the corresponding mask bit is set. The operable mask bits are * defined in and are: * * - KADM5_ATTRIBUTES for require_attrs, forbid_attrs * - KADM5_POLICY for policy * - KADM5_POLICY_CLR to require that policy be unset * - KADM5_PRINC_EXPIRE_TIME for princ_lifetime * - KADM5_PW_EXPIRATION for pw_lifetime * - KADM5_MAX_LIFE for max_life * - KADM5_MAX_RLIFE for max_renewable_life */ struct kadm5_auth_restrictions { long mask; krb5_flags require_attrs; krb5_flags forbid_attrs; krb5_deltat princ_lifetime; krb5_deltat pw_lifetime; krb5_deltat max_life; krb5_deltat max_renewable_life; char *policy; }; /*** Method type declarations ***/ /* * Optional: Initialize module data. acl_file is the realm's configured ACL * file, or NULL if none was configured. Return 0 on success, * KRB5_PLUGIN_NO_HANDLE if the module is inoperable (due to configuration, for * example), and any other error code to abort kadmind startup. Optionally set * *data_out to a module data object to be passed to future calls. */ typedef krb5_error_code (*kadm5_auth_init_fn)(krb5_context context, const char *acl_file, kadm5_auth_moddata *data_out); /* Optional: Release resources used by module data. */ typedef void (*kadm5_auth_fini_fn)(krb5_context context, kadm5_auth_moddata data); /* * Each check method below should return 0 to explicitly authorize the request, * KRB5_PLUGIN_NO_HANDLE to neither authorize nor deny the request, and any * other error code (such as EPERM) to explicitly deny the request. If a check * method is not defined, the module will neither authorize nor deny the * request. A request succeeds if at least one kadm5_auth module explicitly * authorizes the request and none of the modules explicitly deny it. */ /* Optional: authorize an add-principal operation, and optionally generate * restrictions. */ typedef krb5_error_code (*kadm5_auth_addprinc_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target, const struct _kadm5_principal_ent_t *ent, long mask, struct kadm5_auth_restrictions **rs_out); /* Optional: authorize a modify-principal operation, and optionally generate * restrictions. */ typedef krb5_error_code (*kadm5_auth_modprinc_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target, const struct _kadm5_principal_ent_t *ent, long mask, struct kadm5_auth_restrictions **rs_out); /* Optional: authorize a set-string operation. */ typedef krb5_error_code (*kadm5_auth_setstr_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target, const char *key, const char *value); /* Optional: authorize a change-password operation. */ typedef krb5_error_code (*kadm5_auth_cpw_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a randomize-keys operation. */ typedef krb5_error_code (*kadm5_auth_chrand_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a set-key operation. */ typedef krb5_error_code (*kadm5_auth_setkey_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a purgekeys operation. */ typedef krb5_error_code (*kadm5_auth_purgekeys_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a delete-principal operation. */ typedef krb5_error_code (*kadm5_auth_delprinc_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a rename-principal operation. */ typedef krb5_error_code (*kadm5_auth_renprinc_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal src, krb5_const_principal dest); /* Optional: authorize a get-principal operation. */ typedef krb5_error_code (*kadm5_auth_getprinc_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a get-strings operation. */ typedef krb5_error_code (*kadm5_auth_getstrs_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize an extract-keys operation. */ typedef krb5_error_code (*kadm5_auth_extract_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, krb5_const_principal target); /* Optional: authorize a list-principals operation. */ typedef krb5_error_code (*kadm5_auth_listprincs_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client); /* Optional: authorize an add-policy operation. */ typedef krb5_error_code (*kadm5_auth_addpol_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, const char *policy, const struct _kadm5_policy_ent_t *ent, long mask); /* Optional: authorize a modify-policy operation. */ typedef krb5_error_code (*kadm5_auth_modpol_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, const char *policy, const struct _kadm5_policy_ent_t *ent, long mask); /* Optional: authorize a delete-policy operation. */ typedef krb5_error_code (*kadm5_auth_delpol_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, const char *policy); /* Optional: authorize a get-policy operation. client_policy is the client * principal's policy name, or NULL if it does not have one. */ typedef krb5_error_code (*kadm5_auth_getpol_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client, const char *policy, const char *client_policy); /* Optional: authorize a list-policies operation. */ typedef krb5_error_code (*kadm5_auth_listpols_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client); /* Optional: authorize an iprop operation. */ typedef krb5_error_code (*kadm5_auth_iprop_fn)(krb5_context context, kadm5_auth_moddata data, krb5_const_principal client); /* * Optional: receive a notification that the most recent authorized operation * has ended. If a kadm5_auth module is also a KDB module, it can assume that * all KDB methods invoked between a kadm5_auth authorization method invocation * and a kadm5_auth end invocation are performed as part of the authorized * operation. * * The end method may be invoked without a preceding authorization method in * some cases; the module must be prepared to ignore such calls. */ typedef void (*kadm5_auth_end_fn)(krb5_context context, kadm5_auth_moddata data); /* * Optional: free a restrictions object. This method does not need to be * defined if the module does not generate restrictions objects, or if it * returns aliases to restrictions objects contained from within the module * data. */ typedef void (*kadm5_auth_free_restrictions_fn)(krb5_context context, kadm5_auth_moddata data, struct kadm5_auth_restrictions *rs); /* kadm5_auth vtable for major version 1. */ typedef struct kadm5_auth_vtable_st { const char *name; /* Mandatory: name of module. */ kadm5_auth_init_fn init; kadm5_auth_fini_fn fini; kadm5_auth_addprinc_fn addprinc; kadm5_auth_modprinc_fn modprinc; kadm5_auth_setstr_fn setstr; kadm5_auth_cpw_fn cpw; kadm5_auth_chrand_fn chrand; kadm5_auth_setkey_fn setkey; kadm5_auth_purgekeys_fn purgekeys; kadm5_auth_delprinc_fn delprinc; kadm5_auth_renprinc_fn renprinc; kadm5_auth_getprinc_fn getprinc; kadm5_auth_getstrs_fn getstrs; kadm5_auth_extract_fn extract; kadm5_auth_listprincs_fn listprincs; kadm5_auth_addpol_fn addpol; kadm5_auth_modpol_fn modpol; kadm5_auth_delpol_fn delpol; kadm5_auth_getpol_fn getpol; kadm5_auth_listpols_fn listpols; kadm5_auth_iprop_fn iprop; kadm5_auth_end_fn end; kadm5_auth_free_restrictions_fn free_restrictions; /* Minor version 1 ends here. */ } *kadm5_auth_vtable; #endif /* KRB5_KADM5_AUTH_PLUGIN_H */ krb5/kadm5_hook_plugin.h000064400000014021151027430560011160 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2010 by the Massachusetts Institute of Technology. * All rights reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ #ifndef H_KRB5_KADM5_HOOK_PLUGIN #define H_KRB5_KADM5_HOOK_PLUGIN /** * @file krb5/krb5_kadm5_hook_plugin.h * Provide a plugin interface for kadm5 operations. This interface * permits a plugin to intercept principal modification, creation and * change password operations. Operations run at two stages: a * precommit stage that runs before the operation is committed to the * database and a postcommit operation that runs after the database * is updated; see #kadm5_hook_stage for details on semantics. * * This interface is based on a proposed extension to Heimdal by Russ * Allbery; it is likely that Heimdal will adopt an approach based on * stacked kdb modules rather than this interface. For MIT, writing a * plugin to this interface is significantly easier than stacking kdb * modules. Also, the kadm5 interface is significantly more stable * than the kdb interface, so this approach is more desirable than * stacked kdb modules. * * This interface depends on kadm5/admin.h. As such, the interface * does not provide strong guarantees of ABI stability. * * The kadm5_hook interface currently has only one supported major version, * which is 1. Major version 1 has a current minor version number of 2. * * kadm5_hook plugins should: * kadm5_hook__initvt, matching the signature: * * krb5_error_code * kadm5_hook_modname_initvt(krb5_context context, int maj_ver, int min_ver, * krb5_plugin_vtable vtable); * * The initvt function should: * * - Check that the supplied maj_ver number is supported by the module, or * return KRB5_PLUGIN_VER_NOTSUPP if it is not. * * - Cast the vtable pointer as appropriate for maj_ver: * maj_ver == 1: Cast to kadm5_hook_vftable_1 * * - Initialize the methods of the vtable, stopping as appropriate for the * supplied min_ver. Optional methods may be left uninitialized. * * Memory for the vtable is allocated by the caller, not by the module. */ #include #include #include /** * Whether the operation is being run before or after the database * update. */ enum kadm5_hook_stage { /** In this stage, any plugin failure prevents following plugins from * running and aborts the operation.*/ KADM5_HOOK_STAGE_PRECOMMIT, /** In this stage, plugin failures are logged but otherwise ignored.*/ KADM5_HOOK_STAGE_POSTCOMMIT }; /** Opaque module data pointer. */ typedef struct kadm5_hook_modinfo_st kadm5_hook_modinfo; /** * Interface for the v1 virtual table for the kadm5_hook plugin. * All entry points are optional. The name field must be provided. */ typedef struct kadm5_hook_vtable_1_st { /** A text string identifying the plugin for logging messages. */ const char *name; /** Initialize a plugin module. * @param modinfo returns newly allocated module info for future * calls. Cleaned up by the fini() function. */ kadm5_ret_t (*init)(krb5_context, kadm5_hook_modinfo **modinfo); /** Clean up a module and free @a modinfo. */ void (*fini)(krb5_context, kadm5_hook_modinfo *modinfo); /** Indicates that the password is being changed. * @param stage is an integer from #kadm5_hook_stage enumeration * @param keepold is true if existing keys are being kept. * @param newpass is NULL if the key sare being randomized. */ kadm5_ret_t (*chpass)(krb5_context, kadm5_hook_modinfo *modinfo, int stage, krb5_principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, const char *newpass); /** Indicate a principal is created. */ kadm5_ret_t (*create)(krb5_context, kadm5_hook_modinfo *, int stage, kadm5_principal_ent_t, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, const char *password); /** Modify a principal. */ kadm5_ret_t (*modify)(krb5_context, kadm5_hook_modinfo *, int stage, kadm5_principal_ent_t, long mask); /** Indicate a principal is deleted. */ kadm5_ret_t (*remove)(krb5_context, kadm5_hook_modinfo *modinfo, int stage, krb5_principal); /* End of minor version 1. */ /** Indicate a principal is renamed. */ kadm5_ret_t (*rename)(krb5_context, kadm5_hook_modinfo *modinfo, int stage, krb5_principal, krb5_principal); /* End of minor version 2. */ } kadm5_hook_vftable_1; #endif /*H_KRB5_KADM5_HOOK_PLUGIN*/ krb5/preauth_plugin.h000064400000003356151027430560010620 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright (C) 2012 by the Massachusetts Institute of Technology. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This header includes the clpreauth and kdcpreauth interface declarations, * for backward compatibility and convenience. */ #ifndef KRB5_PREAUTH_PLUGIN_H #define KRB5_PREAUTH_PLUGIN_H #include #include #endif /* KRB5_PREAUTH_PLUGIN_H */ fnmatch.h000064400000004367151027430560006352 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _FNMATCH_H #define _FNMATCH_H 1 #ifdef __cplusplus extern "C" { #endif /* We #undef these before defining them because some losing systems (HP-UX A.08.07 for example) define these in . */ #undef FNM_PATHNAME #undef FNM_NOESCAPE #undef FNM_PERIOD /* Bits set in the FLAGS argument to `fnmatch'. */ #define FNM_PATHNAME (1 << 0) /* No wildcard can ever match `/'. */ #define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */ #define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */ #if !defined _POSIX_C_SOURCE || _POSIX_C_SOURCE < 2 || defined _GNU_SOURCE # define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */ # define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */ # define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */ # define FNM_EXTMATCH (1 << 5) /* Use ksh-like extended matching. */ #endif /* Value returned by `fnmatch' if STRING does not match PATTERN. */ #define FNM_NOMATCH 1 /* This value is returned if the implementation does not support `fnmatch'. Since this is not the case here it will never be returned but the conformance test suites still require the symbol to be defined. */ #ifdef _XOPEN_SOURCE # define FNM_NOSYS (-1) #endif /* Match NAME against the filename pattern PATTERN, returning zero if it matches, FNM_NOMATCH if not. */ extern int fnmatch (const char *__pattern, const char *__name, int __flags); #ifdef __cplusplus } #endif #endif /* fnmatch.h */ asm-generic/ioctl.h000064400000006626151027430560010236 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_IOCTL_H #define _ASM_GENERIC_IOCTL_H /* ioctl command encoding: 32 bits total, command in lower 16 bits, * size of the parameter structure in the lower 14 bits of the * upper 16 bits. * Encoding the size of the parameter structure in the ioctl request * is useful for catching programs compiled with old versions * and to avoid overwriting user space outside the user buffer area. * The highest 2 bits are reserved for indicating the ``access mode''. * NOTE: This limits the max parameter size to 16kB -1 ! */ /* * The following is for compatibility across the various Linux * platforms. The generic ioctl numbering scheme doesn't really enforce * a type field. De facto, however, the top 8 bits of the lower 16 * bits are indeed used as a type field, so we might just as well make * this explicit here. Please be sure to use the decoding macros * below from now on. */ #define _IOC_NRBITS 8 #define _IOC_TYPEBITS 8 /* * Let any architecture override either of the following before * including this file. */ #ifndef _IOC_SIZEBITS # define _IOC_SIZEBITS 14 #endif #ifndef _IOC_DIRBITS # define _IOC_DIRBITS 2 #endif #define _IOC_NRMASK ((1 << _IOC_NRBITS)-1) #define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS)-1) #define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS)-1) #define _IOC_DIRMASK ((1 << _IOC_DIRBITS)-1) #define _IOC_NRSHIFT 0 #define _IOC_TYPESHIFT (_IOC_NRSHIFT+_IOC_NRBITS) #define _IOC_SIZESHIFT (_IOC_TYPESHIFT+_IOC_TYPEBITS) #define _IOC_DIRSHIFT (_IOC_SIZESHIFT+_IOC_SIZEBITS) /* * Direction bits, which any architecture can choose to override * before including this file. * * NOTE: _IOC_WRITE means userland is writing and kernel is * reading. _IOC_READ means userland is reading and kernel is writing. */ #ifndef _IOC_NONE # define _IOC_NONE 0U #endif #ifndef _IOC_WRITE # define _IOC_WRITE 1U #endif #ifndef _IOC_READ # define _IOC_READ 2U #endif #define _IOC(dir,type,nr,size) \ (((dir) << _IOC_DIRSHIFT) | \ ((type) << _IOC_TYPESHIFT) | \ ((nr) << _IOC_NRSHIFT) | \ ((size) << _IOC_SIZESHIFT)) #define _IOC_TYPECHECK(t) (sizeof(t)) /* * Used to create numbers. * * NOTE: _IOW means userland is writing and kernel is reading. _IOR * means userland is reading and kernel is writing. */ #define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0) #define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOR_BAD(type,nr,size) _IOC(_IOC_READ,(type),(nr),sizeof(size)) #define _IOW_BAD(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),sizeof(size)) #define _IOWR_BAD(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),sizeof(size)) /* used to decode ioctl numbers.. */ #define _IOC_DIR(nr) (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK) #define _IOC_TYPE(nr) (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK) #define _IOC_NR(nr) (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK) #define _IOC_SIZE(nr) (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK) /* ...and for the drivers/sound files... */ #define IOC_IN (_IOC_WRITE << _IOC_DIRSHIFT) #define IOC_OUT (_IOC_READ << _IOC_DIRSHIFT) #define IOC_INOUT ((_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT) #define IOCSIZE_MASK (_IOC_SIZEMASK << _IOC_SIZESHIFT) #define IOCSIZE_SHIFT (_IOC_SIZESHIFT) #endif /* _ASM_GENERIC_IOCTL_H */ asm-generic/msgbuf.h000064400000003122151027430560010373 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_MSGBUF_H #define __ASM_GENERIC_MSGBUF_H #include /* * generic msqid64_ds structure. * * Note extra padding because this structure is passed back and forth * between kernel and user space. * * msqid64_ds was originally meant to be architecture specific, but * everyone just ended up making identical copies without specific * optimizations, so we may just as well all use the same one. * * 64 bit architectures typically define a 64 bit __kernel_time_t, * so they do not need the first three padding words. * On big-endian systems, the padding is in the wrong place. * * Pad space is left for: * - 2 miscellaneous 32-bit values */ struct msqid64_ds { struct ipc64_perm msg_perm; #if __BITS_PER_LONG == 64 __kernel_time_t msg_stime; /* last msgsnd time */ __kernel_time_t msg_rtime; /* last msgrcv time */ __kernel_time_t msg_ctime; /* last change time */ #else unsigned long msg_stime; /* last msgsnd time */ unsigned long msg_stime_high; unsigned long msg_rtime; /* last msgrcv time */ unsigned long msg_rtime_high; unsigned long msg_ctime; /* last change time */ unsigned long msg_ctime_high; #endif unsigned long msg_cbytes; /* current number of bytes on queue */ unsigned long msg_qnum; /* number of messages in queue */ unsigned long msg_qbytes; /* max number of bytes on queue */ __kernel_pid_t msg_lspid; /* pid of last msgsnd */ __kernel_pid_t msg_lrpid; /* last receive pid */ unsigned long __unused4; unsigned long __unused5; }; #endif /* __ASM_GENERIC_MSGBUF_H */ asm-generic/mman-common.h000064400000006724151027430560011341 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_MMAN_COMMON_H #define __ASM_GENERIC_MMAN_COMMON_H /* Author: Michael S. Tsirkin , Mellanox Technologies Ltd. Based on: asm-xxx/mman.h */ #define PROT_READ 0x1 /* page can be read */ #define PROT_WRITE 0x2 /* page can be written */ #define PROT_EXEC 0x4 /* page can be executed */ #define PROT_SEM 0x8 /* page may be used for atomic ops */ #define PROT_NONE 0x0 /* page can not be accessed */ #define PROT_GROWSDOWN 0x01000000 /* mprotect flag: extend change to start of growsdown vma */ #define PROT_GROWSUP 0x02000000 /* mprotect flag: extend change to end of growsup vma */ #define MAP_SHARED 0x01 /* Share changes */ #define MAP_PRIVATE 0x02 /* Changes are private */ #define MAP_SHARED_VALIDATE 0x03 /* share + validate extension flags */ #define MAP_TYPE 0x0f /* Mask for type of mapping */ #define MAP_FIXED 0x10 /* Interpret addr exactly */ #define MAP_ANONYMOUS 0x20 /* don't use a file */ /* 0x0100 - 0x4000 flags are defined in asm-generic/mman.h */ #define MAP_POPULATE 0x008000 /* populate (prefault) pagetables */ #define MAP_NONBLOCK 0x010000 /* do not block on IO */ #define MAP_STACK 0x020000 /* give out an address that is best suited for process/thread stacks */ #define MAP_HUGETLB 0x040000 /* create a huge page mapping */ #define MAP_SYNC 0x080000 /* perform synchronous page faults for the mapping */ #define MAP_FIXED_NOREPLACE 0x100000 /* MAP_FIXED which doesn't unmap underlying mapping */ #define MAP_UNINITIALIZED 0x4000000 /* For anonymous mmap, memory could be * uninitialized */ /* * Flags for mlock */ #define MLOCK_ONFAULT 0x01 /* Lock pages in range after they are faulted in, do not prefault */ #define MS_ASYNC 1 /* sync memory asynchronously */ #define MS_INVALIDATE 2 /* invalidate the caches */ #define MS_SYNC 4 /* synchronous memory sync */ #define MADV_NORMAL 0 /* no further special treatment */ #define MADV_RANDOM 1 /* expect random page references */ #define MADV_SEQUENTIAL 2 /* expect sequential page references */ #define MADV_WILLNEED 3 /* will need these pages */ #define MADV_DONTNEED 4 /* don't need these pages */ /* common parameters: try to keep these consistent across architectures */ #define MADV_FREE 8 /* free pages only if memory pressure */ #define MADV_REMOVE 9 /* remove these pages & resources */ #define MADV_DONTFORK 10 /* don't inherit across fork */ #define MADV_DOFORK 11 /* do inherit across fork */ #define MADV_HWPOISON 100 /* poison a page for testing */ #define MADV_SOFT_OFFLINE 101 /* soft offline page for testing */ #define MADV_MERGEABLE 12 /* KSM may merge identical pages */ #define MADV_UNMERGEABLE 13 /* KSM may not merge identical pages */ #define MADV_HUGEPAGE 14 /* Worth backing with hugepages */ #define MADV_NOHUGEPAGE 15 /* Not worth backing with hugepages */ #define MADV_DONTDUMP 16 /* Explicity exclude from the core dump, overrides the coredump filter bits */ #define MADV_DODUMP 17 /* Clear the MADV_DONTDUMP flag */ #define MADV_WIPEONFORK 18 /* Zero memory on fork, child only */ #define MADV_KEEPONFORK 19 /* Undo MADV_WIPEONFORK */ #define MADV_COLD 20 /* deactivate these pages */ #define MADV_PAGEOUT 21 /* reclaim these pages */ /* compatibility flags */ #define MAP_FILE 0 #define PKEY_DISABLE_ACCESS 0x1 #define PKEY_DISABLE_WRITE 0x2 #define PKEY_ACCESS_MASK (PKEY_DISABLE_ACCESS |\ PKEY_DISABLE_WRITE) #endif /* __ASM_GENERIC_MMAN_COMMON_H */ asm-generic/stat.h000064400000005111151027430560010063 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_STAT_H #define __ASM_GENERIC_STAT_H /* * Everybody gets this wrong and has to stick with it for all * eternity. Hopefully, this version gets used by new architectures * so they don't fall into the same traps. * * stat64 is copied from powerpc64, with explicit padding added. * stat is the same structure layout on 64-bit, without the 'long long' * types. * * By convention, 64 bit architectures use the stat interface, while * 32 bit architectures use the stat64 interface. Note that we don't * provide an __old_kernel_stat here, which new architecture should * not have to start with. */ #include #define STAT_HAVE_NSEC 1 struct stat { unsigned long st_dev; /* Device. */ unsigned long st_ino; /* File serial number. */ unsigned int st_mode; /* File mode. */ unsigned int st_nlink; /* Link count. */ unsigned int st_uid; /* User ID of the file's owner. */ unsigned int st_gid; /* Group ID of the file's group. */ unsigned long st_rdev; /* Device number, if device. */ unsigned long __pad1; long st_size; /* Size of file, in bytes. */ int st_blksize; /* Optimal block size for I/O. */ int __pad2; long st_blocks; /* Number 512-byte blocks allocated. */ long st_atime; /* Time of last access. */ unsigned long st_atime_nsec; long st_mtime; /* Time of last modification. */ unsigned long st_mtime_nsec; long st_ctime; /* Time of last status change. */ unsigned long st_ctime_nsec; unsigned int __unused4; unsigned int __unused5; }; /* This matches struct stat64 in glibc2.1. Only used for 32 bit. */ #if __BITS_PER_LONG != 64 || defined(__ARCH_WANT_STAT64) struct stat64 { unsigned long long st_dev; /* Device. */ unsigned long long st_ino; /* File serial number. */ unsigned int st_mode; /* File mode. */ unsigned int st_nlink; /* Link count. */ unsigned int st_uid; /* User ID of the file's owner. */ unsigned int st_gid; /* Group ID of the file's group. */ unsigned long long st_rdev; /* Device number, if device. */ unsigned long long __pad1; long long st_size; /* Size of file, in bytes. */ int st_blksize; /* Optimal block size for I/O. */ int __pad2; long long st_blocks; /* Number 512-byte blocks allocated. */ int st_atime; /* Time of last access. */ unsigned int st_atime_nsec; int st_mtime; /* Time of last modification. */ unsigned int st_mtime_nsec; int st_ctime; /* Time of last status change. */ unsigned int st_ctime_nsec; unsigned int __unused4; unsigned int __unused5; }; #endif #endif /* __ASM_GENERIC_STAT_H */ asm-generic/socket.h000064400000004651151027430560010410 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SOCKET_H #define __ASM_GENERIC_SOCKET_H #include /* For setsockopt(2) */ #define SOL_SOCKET 1 #define SO_DEBUG 1 #define SO_REUSEADDR 2 #define SO_TYPE 3 #define SO_ERROR 4 #define SO_DONTROUTE 5 #define SO_BROADCAST 6 #define SO_SNDBUF 7 #define SO_RCVBUF 8 #define SO_SNDBUFFORCE 32 #define SO_RCVBUFFORCE 33 #define SO_KEEPALIVE 9 #define SO_OOBINLINE 10 #define SO_NO_CHECK 11 #define SO_PRIORITY 12 #define SO_LINGER 13 #define SO_BSDCOMPAT 14 #define SO_REUSEPORT 15 #ifndef SO_PASSCRED /* powerpc only differs in these */ #define SO_PASSCRED 16 #define SO_PEERCRED 17 #define SO_RCVLOWAT 18 #define SO_SNDLOWAT 19 #define SO_RCVTIMEO 20 #define SO_SNDTIMEO 21 #endif /* Security levels - as per NRL IPv6 - don't actually do anything */ #define SO_SECURITY_AUTHENTICATION 22 #define SO_SECURITY_ENCRYPTION_TRANSPORT 23 #define SO_SECURITY_ENCRYPTION_NETWORK 24 #define SO_BINDTODEVICE 25 /* Socket filtering */ #define SO_ATTACH_FILTER 26 #define SO_DETACH_FILTER 27 #define SO_GET_FILTER SO_ATTACH_FILTER #define SO_PEERNAME 28 #define SO_TIMESTAMP 29 #define SCM_TIMESTAMP SO_TIMESTAMP #define SO_ACCEPTCONN 30 #define SO_PEERSEC 31 #define SO_PASSSEC 34 #define SO_TIMESTAMPNS 35 #define SCM_TIMESTAMPNS SO_TIMESTAMPNS #define SO_MARK 36 #define SO_TIMESTAMPING 37 #define SCM_TIMESTAMPING SO_TIMESTAMPING #define SO_PROTOCOL 38 #define SO_DOMAIN 39 #define SO_RXQ_OVFL 40 #define SO_WIFI_STATUS 41 #define SCM_WIFI_STATUS SO_WIFI_STATUS #define SO_PEEK_OFF 42 /* Instruct lower device to use last 4-bytes of skb data as FCS */ #define SO_NOFCS 43 #define SO_LOCK_FILTER 44 #define SO_SELECT_ERR_QUEUE 45 #define SO_BUSY_POLL 46 #define SO_MAX_PACING_RATE 47 #define SO_BPF_EXTENSIONS 48 #define SO_INCOMING_CPU 49 #define SO_ATTACH_BPF 50 #define SO_DETACH_BPF SO_DETACH_FILTER #define SO_ATTACH_REUSEPORT_CBPF 51 #define SO_ATTACH_REUSEPORT_EBPF 52 #define SO_CNX_ADVICE 53 #define SCM_TIMESTAMPING_OPT_STATS 54 #define SO_MEMINFO 55 #define SO_INCOMING_NAPI_ID 56 #define SO_COOKIE 57 #define SCM_TIMESTAMPING_PKTINFO 58 #define SO_PEERGROUPS 59 #define SO_ZEROCOPY 60 #define SO_TXTIME 61 #define SCM_TXTIME SO_TXTIME #define SO_BINDTOIFINDEX 62 #define SO_DETACH_REUSEPORT_BPF 68 #define SO_PREFER_BUSY_POLL 69 #define SO_BUSY_POLL_BUDGET 70 #endif /* __ASM_GENERIC_SOCKET_H */ asm-generic/ioctls.h000064400000007623151027430560010417 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_IOCTLS_H #define __ASM_GENERIC_IOCTLS_H #include /* * These are the most common definitions for tty ioctl numbers. * Most of them do not use the recommended _IOC(), but there is * probably some source code out there hardcoding the number, * so we might as well use them for all new platforms. * * The architectures that use different values here typically * try to be compatible with some Unix variants for the same * architecture. */ /* 0x54 is just a magic number to make these relatively unique ('T') */ #define TCGETS 0x5401 #define TCSETS 0x5402 #define TCSETSW 0x5403 #define TCSETSF 0x5404 #define TCGETA 0x5405 #define TCSETA 0x5406 #define TCSETAW 0x5407 #define TCSETAF 0x5408 #define TCSBRK 0x5409 #define TCXONC 0x540A #define TCFLSH 0x540B #define TIOCEXCL 0x540C #define TIOCNXCL 0x540D #define TIOCSCTTY 0x540E #define TIOCGPGRP 0x540F #define TIOCSPGRP 0x5410 #define TIOCOUTQ 0x5411 #define TIOCSTI 0x5412 #define TIOCGWINSZ 0x5413 #define TIOCSWINSZ 0x5414 #define TIOCMGET 0x5415 #define TIOCMBIS 0x5416 #define TIOCMBIC 0x5417 #define TIOCMSET 0x5418 #define TIOCGSOFTCAR 0x5419 #define TIOCSSOFTCAR 0x541A #define FIONREAD 0x541B #define TIOCINQ FIONREAD #define TIOCLINUX 0x541C #define TIOCCONS 0x541D #define TIOCGSERIAL 0x541E #define TIOCSSERIAL 0x541F #define TIOCPKT 0x5420 #define FIONBIO 0x5421 #define TIOCNOTTY 0x5422 #define TIOCSETD 0x5423 #define TIOCGETD 0x5424 #define TCSBRKP 0x5425 /* Needed for POSIX tcsendbreak() */ #define TIOCSBRK 0x5427 /* BSD compatibility */ #define TIOCCBRK 0x5428 /* BSD compatibility */ #define TIOCGSID 0x5429 /* Return the session ID of FD */ #define TCGETS2 _IOR('T', 0x2A, struct termios2) #define TCSETS2 _IOW('T', 0x2B, struct termios2) #define TCSETSW2 _IOW('T', 0x2C, struct termios2) #define TCSETSF2 _IOW('T', 0x2D, struct termios2) #define TIOCGRS485 0x542E #ifndef TIOCSRS485 #define TIOCSRS485 0x542F #endif #define TIOCGPTN _IOR('T', 0x30, unsigned int) /* Get Pty Number (of pty-mux device) */ #define TIOCSPTLCK _IOW('T', 0x31, int) /* Lock/unlock Pty */ #define TIOCGDEV _IOR('T', 0x32, unsigned int) /* Get primary device node of /dev/console */ #define TCGETX 0x5432 /* SYS5 TCGETX compatibility */ #define TCSETX 0x5433 #define TCSETXF 0x5434 #define TCSETXW 0x5435 #define TIOCSIG _IOW('T', 0x36, int) /* pty: generate signal */ #define TIOCVHANGUP 0x5437 #define TIOCGPKT _IOR('T', 0x38, int) /* Get packet mode state */ #define TIOCGPTLCK _IOR('T', 0x39, int) /* Get Pty lock state */ #define TIOCGEXCL _IOR('T', 0x40, int) /* Get exclusive mode state */ #define TIOCGPTPEER _IO('T', 0x41) /* Safely open the slave */ #define TIOCGISO7816 _IOR('T', 0x42, struct serial_iso7816) #define TIOCSISO7816 _IOWR('T', 0x43, struct serial_iso7816) #define FIONCLEX 0x5450 #define FIOCLEX 0x5451 #define FIOASYNC 0x5452 #define TIOCSERCONFIG 0x5453 #define TIOCSERGWILD 0x5454 #define TIOCSERSWILD 0x5455 #define TIOCGLCKTRMIOS 0x5456 #define TIOCSLCKTRMIOS 0x5457 #define TIOCSERGSTRUCT 0x5458 /* For debugging only */ #define TIOCSERGETLSR 0x5459 /* Get line status register */ #define TIOCSERGETMULTI 0x545A /* Get multiport config */ #define TIOCSERSETMULTI 0x545B /* Set multiport config */ #define TIOCMIWAIT 0x545C /* wait for a change on serial input line(s) */ #define TIOCGICOUNT 0x545D /* read serial port __inline__ interrupt counts */ /* * Some arches already define FIOQSIZE due to a historical * conflict with a Hayes modem-specific ioctl value. */ #ifndef FIOQSIZE # define FIOQSIZE 0x5460 #endif /* Used for packet mode */ #define TIOCPKT_DATA 0 #define TIOCPKT_FLUSHREAD 1 #define TIOCPKT_FLUSHWRITE 2 #define TIOCPKT_STOP 4 #define TIOCPKT_START 8 #define TIOCPKT_NOSTOP 16 #define TIOCPKT_DOSTOP 32 #define TIOCPKT_IOCTL 64 #define TIOCSER_TEMT 0x01 /* Transmitter physically empty */ #endif /* __ASM_GENERIC_IOCTLS_H */ asm-generic/param.h000064400000000541151027430560010212 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_PARAM_H #define __ASM_GENERIC_PARAM_H #ifndef HZ #define HZ 100 #endif #ifndef EXEC_PAGESIZE #define EXEC_PAGESIZE 4096 #endif #ifndef NOGROUP #define NOGROUP (-1) #endif #define MAXHOSTNAMELEN 64 /* max length of hostname */ #endif /* __ASM_GENERIC_PARAM_H */ asm-generic/unistd.h000064400000067026151027430560010433 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #include /* * This file contains the system call numbers, based on the * layout of the x86-64 architecture, which embeds the * pointer to the syscall in the table. * * As a basic principle, no duplication of functionality * should be added, e.g. we don't use lseek when llseek * is present. New architectures should use this file * and implement the less feature-full calls in user space. */ #ifndef __SYSCALL #define __SYSCALL(x, y) #endif #if __BITS_PER_LONG == 32 || defined(__SYSCALL_COMPAT) #define __SC_3264(_nr, _32, _64) __SYSCALL(_nr, _32) #else #define __SC_3264(_nr, _32, _64) __SYSCALL(_nr, _64) #endif #ifdef __SYSCALL_COMPAT #define __SC_COMP(_nr, _sys, _comp) __SYSCALL(_nr, _comp) #define __SC_COMP_3264(_nr, _32, _64, _comp) __SYSCALL(_nr, _comp) #else #define __SC_COMP(_nr, _sys, _comp) __SYSCALL(_nr, _sys) #define __SC_COMP_3264(_nr, _32, _64, _comp) __SC_3264(_nr, _32, _64) #endif #define __NR_io_setup 0 __SC_COMP(__NR_io_setup, sys_io_setup, compat_sys_io_setup) #define __NR_io_destroy 1 __SYSCALL(__NR_io_destroy, sys_io_destroy) #define __NR_io_submit 2 __SC_COMP(__NR_io_submit, sys_io_submit, compat_sys_io_submit) #define __NR_io_cancel 3 __SYSCALL(__NR_io_cancel, sys_io_cancel) #define __NR_io_getevents 4 __SC_COMP(__NR_io_getevents, sys_io_getevents, compat_sys_io_getevents) /* fs/xattr.c */ #define __NR_setxattr 5 __SYSCALL(__NR_setxattr, sys_setxattr) #define __NR_lsetxattr 6 __SYSCALL(__NR_lsetxattr, sys_lsetxattr) #define __NR_fsetxattr 7 __SYSCALL(__NR_fsetxattr, sys_fsetxattr) #define __NR_getxattr 8 __SYSCALL(__NR_getxattr, sys_getxattr) #define __NR_lgetxattr 9 __SYSCALL(__NR_lgetxattr, sys_lgetxattr) #define __NR_fgetxattr 10 __SYSCALL(__NR_fgetxattr, sys_fgetxattr) #define __NR_listxattr 11 __SYSCALL(__NR_listxattr, sys_listxattr) #define __NR_llistxattr 12 __SYSCALL(__NR_llistxattr, sys_llistxattr) #define __NR_flistxattr 13 __SYSCALL(__NR_flistxattr, sys_flistxattr) #define __NR_removexattr 14 __SYSCALL(__NR_removexattr, sys_removexattr) #define __NR_lremovexattr 15 __SYSCALL(__NR_lremovexattr, sys_lremovexattr) #define __NR_fremovexattr 16 __SYSCALL(__NR_fremovexattr, sys_fremovexattr) /* fs/dcache.c */ #define __NR_getcwd 17 __SYSCALL(__NR_getcwd, sys_getcwd) /* fs/cookies.c */ #define __NR_lookup_dcookie 18 __SC_COMP(__NR_lookup_dcookie, sys_lookup_dcookie, compat_sys_lookup_dcookie) /* fs/eventfd.c */ #define __NR_eventfd2 19 __SYSCALL(__NR_eventfd2, sys_eventfd2) /* fs/eventpoll.c */ #define __NR_epoll_create1 20 __SYSCALL(__NR_epoll_create1, sys_epoll_create1) #define __NR_epoll_ctl 21 __SYSCALL(__NR_epoll_ctl, sys_epoll_ctl) #define __NR_epoll_pwait 22 __SC_COMP(__NR_epoll_pwait, sys_epoll_pwait, compat_sys_epoll_pwait) /* fs/fcntl.c */ #define __NR_dup 23 __SYSCALL(__NR_dup, sys_dup) #define __NR_dup3 24 __SYSCALL(__NR_dup3, sys_dup3) #define __NR3264_fcntl 25 __SC_COMP_3264(__NR3264_fcntl, sys_fcntl64, sys_fcntl, compat_sys_fcntl64) /* fs/inotify_user.c */ #define __NR_inotify_init1 26 __SYSCALL(__NR_inotify_init1, sys_inotify_init1) #define __NR_inotify_add_watch 27 __SYSCALL(__NR_inotify_add_watch, sys_inotify_add_watch) #define __NR_inotify_rm_watch 28 __SYSCALL(__NR_inotify_rm_watch, sys_inotify_rm_watch) /* fs/ioctl.c */ #define __NR_ioctl 29 __SC_COMP(__NR_ioctl, sys_ioctl, compat_sys_ioctl) /* fs/ioprio.c */ #define __NR_ioprio_set 30 __SYSCALL(__NR_ioprio_set, sys_ioprio_set) #define __NR_ioprio_get 31 __SYSCALL(__NR_ioprio_get, sys_ioprio_get) /* fs/locks.c */ #define __NR_flock 32 __SYSCALL(__NR_flock, sys_flock) /* fs/namei.c */ #define __NR_mknodat 33 __SYSCALL(__NR_mknodat, sys_mknodat) #define __NR_mkdirat 34 __SYSCALL(__NR_mkdirat, sys_mkdirat) #define __NR_unlinkat 35 __SYSCALL(__NR_unlinkat, sys_unlinkat) #define __NR_symlinkat 36 __SYSCALL(__NR_symlinkat, sys_symlinkat) #define __NR_linkat 37 __SYSCALL(__NR_linkat, sys_linkat) #ifdef __ARCH_WANT_RENAMEAT /* renameat is superseded with flags by renameat2 */ #define __NR_renameat 38 __SYSCALL(__NR_renameat, sys_renameat) #endif /* __ARCH_WANT_RENAMEAT */ /* fs/namespace.c */ #define __NR_umount2 39 __SYSCALL(__NR_umount2, sys_umount) #define __NR_mount 40 __SC_COMP(__NR_mount, sys_mount, compat_sys_mount) #define __NR_pivot_root 41 __SYSCALL(__NR_pivot_root, sys_pivot_root) /* fs/nfsctl.c */ #define __NR_nfsservctl 42 __SYSCALL(__NR_nfsservctl, sys_ni_syscall) /* fs/open.c */ #define __NR3264_statfs 43 __SC_COMP_3264(__NR3264_statfs, sys_statfs64, sys_statfs, \ compat_sys_statfs64) #define __NR3264_fstatfs 44 __SC_COMP_3264(__NR3264_fstatfs, sys_fstatfs64, sys_fstatfs, \ compat_sys_fstatfs64) #define __NR3264_truncate 45 __SC_COMP_3264(__NR3264_truncate, sys_truncate64, sys_truncate, \ compat_sys_truncate64) #define __NR3264_ftruncate 46 __SC_COMP_3264(__NR3264_ftruncate, sys_ftruncate64, sys_ftruncate, \ compat_sys_ftruncate64) #define __NR_fallocate 47 __SC_COMP(__NR_fallocate, sys_fallocate, compat_sys_fallocate) #define __NR_faccessat 48 __SYSCALL(__NR_faccessat, sys_faccessat) #define __NR_chdir 49 __SYSCALL(__NR_chdir, sys_chdir) #define __NR_fchdir 50 __SYSCALL(__NR_fchdir, sys_fchdir) #define __NR_chroot 51 __SYSCALL(__NR_chroot, sys_chroot) #define __NR_fchmod 52 __SYSCALL(__NR_fchmod, sys_fchmod) #define __NR_fchmodat 53 __SYSCALL(__NR_fchmodat, sys_fchmodat) #define __NR_fchownat 54 __SYSCALL(__NR_fchownat, sys_fchownat) #define __NR_fchown 55 __SYSCALL(__NR_fchown, sys_fchown) #define __NR_openat 56 __SC_COMP(__NR_openat, sys_openat, compat_sys_openat) #define __NR_close 57 __SYSCALL(__NR_close, sys_close) #define __NR_vhangup 58 __SYSCALL(__NR_vhangup, sys_vhangup) /* fs/pipe.c */ #define __NR_pipe2 59 __SYSCALL(__NR_pipe2, sys_pipe2) /* fs/quota.c */ #define __NR_quotactl 60 __SYSCALL(__NR_quotactl, sys_quotactl) /* fs/readdir.c */ #define __NR_getdents64 61 __SYSCALL(__NR_getdents64, sys_getdents64) /* fs/read_write.c */ #define __NR3264_lseek 62 __SC_3264(__NR3264_lseek, sys_llseek, sys_lseek) #define __NR_read 63 __SYSCALL(__NR_read, sys_read) #define __NR_write 64 __SYSCALL(__NR_write, sys_write) #define __NR_readv 65 __SC_COMP(__NR_readv, sys_readv, compat_sys_readv) #define __NR_writev 66 __SC_COMP(__NR_writev, sys_writev, compat_sys_writev) #define __NR_pread64 67 __SC_COMP(__NR_pread64, sys_pread64, compat_sys_pread64) #define __NR_pwrite64 68 __SC_COMP(__NR_pwrite64, sys_pwrite64, compat_sys_pwrite64) #define __NR_preadv 69 __SC_COMP(__NR_preadv, sys_preadv, compat_sys_preadv) #define __NR_pwritev 70 __SC_COMP(__NR_pwritev, sys_pwritev, compat_sys_pwritev) /* fs/sendfile.c */ #define __NR3264_sendfile 71 __SYSCALL(__NR3264_sendfile, sys_sendfile64) /* fs/select.c */ #define __NR_pselect6 72 __SC_COMP(__NR_pselect6, sys_pselect6, compat_sys_pselect6) #define __NR_ppoll 73 __SC_COMP(__NR_ppoll, sys_ppoll, compat_sys_ppoll) /* fs/signalfd.c */ #define __NR_signalfd4 74 __SC_COMP(__NR_signalfd4, sys_signalfd4, compat_sys_signalfd4) /* fs/splice.c */ #define __NR_vmsplice 75 __SC_COMP(__NR_vmsplice, sys_vmsplice, compat_sys_vmsplice) #define __NR_splice 76 __SYSCALL(__NR_splice, sys_splice) #define __NR_tee 77 __SYSCALL(__NR_tee, sys_tee) /* fs/stat.c */ #define __NR_readlinkat 78 __SYSCALL(__NR_readlinkat, sys_readlinkat) #define __NR3264_fstatat 79 __SC_3264(__NR3264_fstatat, sys_fstatat64, sys_newfstatat) #define __NR3264_fstat 80 __SC_3264(__NR3264_fstat, sys_fstat64, sys_newfstat) /* fs/sync.c */ #define __NR_sync 81 __SYSCALL(__NR_sync, sys_sync) #define __NR_fsync 82 __SYSCALL(__NR_fsync, sys_fsync) #define __NR_fdatasync 83 __SYSCALL(__NR_fdatasync, sys_fdatasync) #ifdef __ARCH_WANT_SYNC_FILE_RANGE2 #define __NR_sync_file_range2 84 __SC_COMP(__NR_sync_file_range2, sys_sync_file_range2, \ compat_sys_sync_file_range2) #else #define __NR_sync_file_range 84 __SC_COMP(__NR_sync_file_range, sys_sync_file_range, \ compat_sys_sync_file_range) #endif /* fs/timerfd.c */ #define __NR_timerfd_create 85 __SYSCALL(__NR_timerfd_create, sys_timerfd_create) #define __NR_timerfd_settime 86 __SC_COMP(__NR_timerfd_settime, sys_timerfd_settime, \ compat_sys_timerfd_settime) #define __NR_timerfd_gettime 87 __SC_COMP(__NR_timerfd_gettime, sys_timerfd_gettime, \ compat_sys_timerfd_gettime) /* fs/utimes.c */ #define __NR_utimensat 88 __SC_COMP(__NR_utimensat, sys_utimensat, compat_sys_utimensat) /* kernel/acct.c */ #define __NR_acct 89 __SYSCALL(__NR_acct, sys_acct) /* kernel/capability.c */ #define __NR_capget 90 __SYSCALL(__NR_capget, sys_capget) #define __NR_capset 91 __SYSCALL(__NR_capset, sys_capset) /* kernel/exec_domain.c */ #define __NR_personality 92 __SYSCALL(__NR_personality, sys_personality) /* kernel/exit.c */ #define __NR_exit 93 __SYSCALL(__NR_exit, sys_exit) #define __NR_exit_group 94 __SYSCALL(__NR_exit_group, sys_exit_group) #define __NR_waitid 95 __SC_COMP(__NR_waitid, sys_waitid, compat_sys_waitid) /* kernel/fork.c */ #define __NR_set_tid_address 96 __SYSCALL(__NR_set_tid_address, sys_set_tid_address) #define __NR_unshare 97 __SYSCALL(__NR_unshare, sys_unshare) /* kernel/futex.c */ #define __NR_futex 98 __SC_COMP(__NR_futex, sys_futex, compat_sys_futex) #define __NR_set_robust_list 99 __SC_COMP(__NR_set_robust_list, sys_set_robust_list, \ compat_sys_set_robust_list) #define __NR_get_robust_list 100 __SC_COMP(__NR_get_robust_list, sys_get_robust_list, \ compat_sys_get_robust_list) /* kernel/hrtimer.c */ #define __NR_nanosleep 101 __SC_COMP(__NR_nanosleep, sys_nanosleep, compat_sys_nanosleep) /* kernel/itimer.c */ #define __NR_getitimer 102 __SC_COMP(__NR_getitimer, sys_getitimer, compat_sys_getitimer) #define __NR_setitimer 103 __SC_COMP(__NR_setitimer, sys_setitimer, compat_sys_setitimer) /* kernel/kexec.c */ #define __NR_kexec_load 104 __SC_COMP(__NR_kexec_load, sys_kexec_load, compat_sys_kexec_load) /* kernel/module.c */ #define __NR_init_module 105 __SYSCALL(__NR_init_module, sys_init_module) #define __NR_delete_module 106 __SYSCALL(__NR_delete_module, sys_delete_module) /* kernel/posix-timers.c */ #define __NR_timer_create 107 __SC_COMP(__NR_timer_create, sys_timer_create, compat_sys_timer_create) #define __NR_timer_gettime 108 __SC_COMP(__NR_timer_gettime, sys_timer_gettime, compat_sys_timer_gettime) #define __NR_timer_getoverrun 109 __SYSCALL(__NR_timer_getoverrun, sys_timer_getoverrun) #define __NR_timer_settime 110 __SC_COMP(__NR_timer_settime, sys_timer_settime, compat_sys_timer_settime) #define __NR_timer_delete 111 __SYSCALL(__NR_timer_delete, sys_timer_delete) #define __NR_clock_settime 112 __SC_COMP(__NR_clock_settime, sys_clock_settime, compat_sys_clock_settime) #define __NR_clock_gettime 113 __SC_COMP(__NR_clock_gettime, sys_clock_gettime, compat_sys_clock_gettime) #define __NR_clock_getres 114 __SC_COMP(__NR_clock_getres, sys_clock_getres, compat_sys_clock_getres) #define __NR_clock_nanosleep 115 __SC_COMP(__NR_clock_nanosleep, sys_clock_nanosleep, \ compat_sys_clock_nanosleep) /* kernel/printk.c */ #define __NR_syslog 116 __SYSCALL(__NR_syslog, sys_syslog) /* kernel/ptrace.c */ #define __NR_ptrace 117 __SYSCALL(__NR_ptrace, sys_ptrace) /* kernel/sched/core.c */ #define __NR_sched_setparam 118 __SYSCALL(__NR_sched_setparam, sys_sched_setparam) #define __NR_sched_setscheduler 119 __SYSCALL(__NR_sched_setscheduler, sys_sched_setscheduler) #define __NR_sched_getscheduler 120 __SYSCALL(__NR_sched_getscheduler, sys_sched_getscheduler) #define __NR_sched_getparam 121 __SYSCALL(__NR_sched_getparam, sys_sched_getparam) #define __NR_sched_setaffinity 122 __SC_COMP(__NR_sched_setaffinity, sys_sched_setaffinity, \ compat_sys_sched_setaffinity) #define __NR_sched_getaffinity 123 __SC_COMP(__NR_sched_getaffinity, sys_sched_getaffinity, \ compat_sys_sched_getaffinity) #define __NR_sched_yield 124 __SYSCALL(__NR_sched_yield, sys_sched_yield) #define __NR_sched_get_priority_max 125 __SYSCALL(__NR_sched_get_priority_max, sys_sched_get_priority_max) #define __NR_sched_get_priority_min 126 __SYSCALL(__NR_sched_get_priority_min, sys_sched_get_priority_min) #define __NR_sched_rr_get_interval 127 __SC_COMP(__NR_sched_rr_get_interval, sys_sched_rr_get_interval, \ compat_sys_sched_rr_get_interval) /* kernel/signal.c */ #define __NR_restart_syscall 128 __SYSCALL(__NR_restart_syscall, sys_restart_syscall) #define __NR_kill 129 __SYSCALL(__NR_kill, sys_kill) #define __NR_tkill 130 __SYSCALL(__NR_tkill, sys_tkill) #define __NR_tgkill 131 __SYSCALL(__NR_tgkill, sys_tgkill) #define __NR_sigaltstack 132 __SC_COMP(__NR_sigaltstack, sys_sigaltstack, compat_sys_sigaltstack) #define __NR_rt_sigsuspend 133 __SC_COMP(__NR_rt_sigsuspend, sys_rt_sigsuspend, compat_sys_rt_sigsuspend) #define __NR_rt_sigaction 134 __SC_COMP(__NR_rt_sigaction, sys_rt_sigaction, compat_sys_rt_sigaction) #define __NR_rt_sigprocmask 135 __SC_COMP(__NR_rt_sigprocmask, sys_rt_sigprocmask, compat_sys_rt_sigprocmask) #define __NR_rt_sigpending 136 __SC_COMP(__NR_rt_sigpending, sys_rt_sigpending, compat_sys_rt_sigpending) #define __NR_rt_sigtimedwait 137 __SC_COMP(__NR_rt_sigtimedwait, sys_rt_sigtimedwait, \ compat_sys_rt_sigtimedwait) #define __NR_rt_sigqueueinfo 138 __SC_COMP(__NR_rt_sigqueueinfo, sys_rt_sigqueueinfo, \ compat_sys_rt_sigqueueinfo) #define __NR_rt_sigreturn 139 __SC_COMP(__NR_rt_sigreturn, sys_rt_sigreturn, compat_sys_rt_sigreturn) /* kernel/sys.c */ #define __NR_setpriority 140 __SYSCALL(__NR_setpriority, sys_setpriority) #define __NR_getpriority 141 __SYSCALL(__NR_getpriority, sys_getpriority) #define __NR_reboot 142 __SYSCALL(__NR_reboot, sys_reboot) #define __NR_setregid 143 __SYSCALL(__NR_setregid, sys_setregid) #define __NR_setgid 144 __SYSCALL(__NR_setgid, sys_setgid) #define __NR_setreuid 145 __SYSCALL(__NR_setreuid, sys_setreuid) #define __NR_setuid 146 __SYSCALL(__NR_setuid, sys_setuid) #define __NR_setresuid 147 __SYSCALL(__NR_setresuid, sys_setresuid) #define __NR_getresuid 148 __SYSCALL(__NR_getresuid, sys_getresuid) #define __NR_setresgid 149 __SYSCALL(__NR_setresgid, sys_setresgid) #define __NR_getresgid 150 __SYSCALL(__NR_getresgid, sys_getresgid) #define __NR_setfsuid 151 __SYSCALL(__NR_setfsuid, sys_setfsuid) #define __NR_setfsgid 152 __SYSCALL(__NR_setfsgid, sys_setfsgid) #define __NR_times 153 __SC_COMP(__NR_times, sys_times, compat_sys_times) #define __NR_setpgid 154 __SYSCALL(__NR_setpgid, sys_setpgid) #define __NR_getpgid 155 __SYSCALL(__NR_getpgid, sys_getpgid) #define __NR_getsid 156 __SYSCALL(__NR_getsid, sys_getsid) #define __NR_setsid 157 __SYSCALL(__NR_setsid, sys_setsid) #define __NR_getgroups 158 __SYSCALL(__NR_getgroups, sys_getgroups) #define __NR_setgroups 159 __SYSCALL(__NR_setgroups, sys_setgroups) #define __NR_uname 160 __SYSCALL(__NR_uname, sys_newuname) #define __NR_sethostname 161 __SYSCALL(__NR_sethostname, sys_sethostname) #define __NR_setdomainname 162 __SYSCALL(__NR_setdomainname, sys_setdomainname) #define __NR_getrlimit 163 __SC_COMP(__NR_getrlimit, sys_getrlimit, compat_sys_getrlimit) #define __NR_setrlimit 164 __SC_COMP(__NR_setrlimit, sys_setrlimit, compat_sys_setrlimit) #define __NR_getrusage 165 __SC_COMP(__NR_getrusage, sys_getrusage, compat_sys_getrusage) #define __NR_umask 166 __SYSCALL(__NR_umask, sys_umask) #define __NR_prctl 167 __SYSCALL(__NR_prctl, sys_prctl) #define __NR_getcpu 168 __SYSCALL(__NR_getcpu, sys_getcpu) /* kernel/time.c */ #define __NR_gettimeofday 169 __SC_COMP(__NR_gettimeofday, sys_gettimeofday, compat_sys_gettimeofday) #define __NR_settimeofday 170 __SC_COMP(__NR_settimeofday, sys_settimeofday, compat_sys_settimeofday) #define __NR_adjtimex 171 __SC_COMP(__NR_adjtimex, sys_adjtimex, compat_sys_adjtimex) /* kernel/timer.c */ #define __NR_getpid 172 __SYSCALL(__NR_getpid, sys_getpid) #define __NR_getppid 173 __SYSCALL(__NR_getppid, sys_getppid) #define __NR_getuid 174 __SYSCALL(__NR_getuid, sys_getuid) #define __NR_geteuid 175 __SYSCALL(__NR_geteuid, sys_geteuid) #define __NR_getgid 176 __SYSCALL(__NR_getgid, sys_getgid) #define __NR_getegid 177 __SYSCALL(__NR_getegid, sys_getegid) #define __NR_gettid 178 __SYSCALL(__NR_gettid, sys_gettid) #define __NR_sysinfo 179 __SC_COMP(__NR_sysinfo, sys_sysinfo, compat_sys_sysinfo) /* ipc/mqueue.c */ #define __NR_mq_open 180 __SC_COMP(__NR_mq_open, sys_mq_open, compat_sys_mq_open) #define __NR_mq_unlink 181 __SYSCALL(__NR_mq_unlink, sys_mq_unlink) #define __NR_mq_timedsend 182 __SC_COMP(__NR_mq_timedsend, sys_mq_timedsend, compat_sys_mq_timedsend) #define __NR_mq_timedreceive 183 __SC_COMP(__NR_mq_timedreceive, sys_mq_timedreceive, \ compat_sys_mq_timedreceive) #define __NR_mq_notify 184 __SC_COMP(__NR_mq_notify, sys_mq_notify, compat_sys_mq_notify) #define __NR_mq_getsetattr 185 __SC_COMP(__NR_mq_getsetattr, sys_mq_getsetattr, compat_sys_mq_getsetattr) /* ipc/msg.c */ #define __NR_msgget 186 __SYSCALL(__NR_msgget, sys_msgget) #define __NR_msgctl 187 __SC_COMP(__NR_msgctl, sys_msgctl, compat_sys_msgctl) #define __NR_msgrcv 188 __SC_COMP(__NR_msgrcv, sys_msgrcv, compat_sys_msgrcv) #define __NR_msgsnd 189 __SC_COMP(__NR_msgsnd, sys_msgsnd, compat_sys_msgsnd) /* ipc/sem.c */ #define __NR_semget 190 __SYSCALL(__NR_semget, sys_semget) #define __NR_semctl 191 __SC_COMP(__NR_semctl, sys_semctl, compat_sys_semctl) #define __NR_semtimedop 192 __SC_COMP(__NR_semtimedop, sys_semtimedop, compat_sys_semtimedop) #define __NR_semop 193 __SYSCALL(__NR_semop, sys_semop) /* ipc/shm.c */ #define __NR_shmget 194 __SYSCALL(__NR_shmget, sys_shmget) #define __NR_shmctl 195 __SC_COMP(__NR_shmctl, sys_shmctl, compat_sys_shmctl) #define __NR_shmat 196 __SC_COMP(__NR_shmat, sys_shmat, compat_sys_shmat) #define __NR_shmdt 197 __SYSCALL(__NR_shmdt, sys_shmdt) /* net/socket.c */ #define __NR_socket 198 __SYSCALL(__NR_socket, sys_socket) #define __NR_socketpair 199 __SYSCALL(__NR_socketpair, sys_socketpair) #define __NR_bind 200 __SYSCALL(__NR_bind, sys_bind) #define __NR_listen 201 __SYSCALL(__NR_listen, sys_listen) #define __NR_accept 202 __SYSCALL(__NR_accept, sys_accept) #define __NR_connect 203 __SYSCALL(__NR_connect, sys_connect) #define __NR_getsockname 204 __SYSCALL(__NR_getsockname, sys_getsockname) #define __NR_getpeername 205 __SYSCALL(__NR_getpeername, sys_getpeername) #define __NR_sendto 206 __SYSCALL(__NR_sendto, sys_sendto) #define __NR_recvfrom 207 __SC_COMP(__NR_recvfrom, sys_recvfrom, compat_sys_recvfrom) #define __NR_setsockopt 208 __SC_COMP(__NR_setsockopt, sys_setsockopt, compat_sys_setsockopt) #define __NR_getsockopt 209 __SC_COMP(__NR_getsockopt, sys_getsockopt, compat_sys_getsockopt) #define __NR_shutdown 210 __SYSCALL(__NR_shutdown, sys_shutdown) #define __NR_sendmsg 211 __SC_COMP(__NR_sendmsg, sys_sendmsg, compat_sys_sendmsg) #define __NR_recvmsg 212 __SC_COMP(__NR_recvmsg, sys_recvmsg, compat_sys_recvmsg) /* mm/filemap.c */ #define __NR_readahead 213 __SC_COMP(__NR_readahead, sys_readahead, compat_sys_readahead) /* mm/nommu.c, also with MMU */ #define __NR_brk 214 __SYSCALL(__NR_brk, sys_brk) #define __NR_munmap 215 __SYSCALL(__NR_munmap, sys_munmap) #define __NR_mremap 216 __SYSCALL(__NR_mremap, sys_mremap) /* security/keys/keyctl.c */ #define __NR_add_key 217 __SYSCALL(__NR_add_key, sys_add_key) #define __NR_request_key 218 __SYSCALL(__NR_request_key, sys_request_key) #define __NR_keyctl 219 __SC_COMP(__NR_keyctl, sys_keyctl, compat_sys_keyctl) /* arch/example/kernel/sys_example.c */ #define __NR_clone 220 __SYSCALL(__NR_clone, sys_clone) #define __NR_execve 221 __SC_COMP(__NR_execve, sys_execve, compat_sys_execve) #define __NR3264_mmap 222 __SC_3264(__NR3264_mmap, sys_mmap2, sys_mmap) /* mm/fadvise.c */ #define __NR3264_fadvise64 223 __SC_COMP(__NR3264_fadvise64, sys_fadvise64_64, compat_sys_fadvise64_64) /* mm/, CONFIG_MMU only */ #ifndef __ARCH_NOMMU #define __NR_swapon 224 __SYSCALL(__NR_swapon, sys_swapon) #define __NR_swapoff 225 __SYSCALL(__NR_swapoff, sys_swapoff) #define __NR_mprotect 226 __SYSCALL(__NR_mprotect, sys_mprotect) #define __NR_msync 227 __SYSCALL(__NR_msync, sys_msync) #define __NR_mlock 228 __SYSCALL(__NR_mlock, sys_mlock) #define __NR_munlock 229 __SYSCALL(__NR_munlock, sys_munlock) #define __NR_mlockall 230 __SYSCALL(__NR_mlockall, sys_mlockall) #define __NR_munlockall 231 __SYSCALL(__NR_munlockall, sys_munlockall) #define __NR_mincore 232 __SYSCALL(__NR_mincore, sys_mincore) #define __NR_madvise 233 __SYSCALL(__NR_madvise, sys_madvise) #define __NR_remap_file_pages 234 __SYSCALL(__NR_remap_file_pages, sys_remap_file_pages) #define __NR_mbind 235 __SC_COMP(__NR_mbind, sys_mbind, compat_sys_mbind) #define __NR_get_mempolicy 236 __SC_COMP(__NR_get_mempolicy, sys_get_mempolicy, compat_sys_get_mempolicy) #define __NR_set_mempolicy 237 __SC_COMP(__NR_set_mempolicy, sys_set_mempolicy, compat_sys_set_mempolicy) #define __NR_migrate_pages 238 __SC_COMP(__NR_migrate_pages, sys_migrate_pages, compat_sys_migrate_pages) #define __NR_move_pages 239 __SC_COMP(__NR_move_pages, sys_move_pages, compat_sys_move_pages) #endif #define __NR_rt_tgsigqueueinfo 240 __SC_COMP(__NR_rt_tgsigqueueinfo, sys_rt_tgsigqueueinfo, \ compat_sys_rt_tgsigqueueinfo) #define __NR_perf_event_open 241 __SYSCALL(__NR_perf_event_open, sys_perf_event_open) #define __NR_accept4 242 __SYSCALL(__NR_accept4, sys_accept4) #define __NR_recvmmsg 243 __SC_COMP(__NR_recvmmsg, sys_recvmmsg, compat_sys_recvmmsg) /* * Architectures may provide up to 16 syscalls of their own * starting with this value. */ #define __NR_arch_specific_syscall 244 #define __NR_wait4 260 __SC_COMP(__NR_wait4, sys_wait4, compat_sys_wait4) #define __NR_prlimit64 261 __SYSCALL(__NR_prlimit64, sys_prlimit64) #define __NR_fanotify_init 262 __SYSCALL(__NR_fanotify_init, sys_fanotify_init) #define __NR_fanotify_mark 263 __SYSCALL(__NR_fanotify_mark, sys_fanotify_mark) #define __NR_name_to_handle_at 264 __SYSCALL(__NR_name_to_handle_at, sys_name_to_handle_at) #define __NR_open_by_handle_at 265 __SC_COMP(__NR_open_by_handle_at, sys_open_by_handle_at, \ compat_sys_open_by_handle_at) #define __NR_clock_adjtime 266 __SC_COMP(__NR_clock_adjtime, sys_clock_adjtime, compat_sys_clock_adjtime) #define __NR_syncfs 267 __SYSCALL(__NR_syncfs, sys_syncfs) #define __NR_setns 268 __SYSCALL(__NR_setns, sys_setns) #define __NR_sendmmsg 269 __SC_COMP(__NR_sendmmsg, sys_sendmmsg, compat_sys_sendmmsg) #define __NR_process_vm_readv 270 __SC_COMP(__NR_process_vm_readv, sys_process_vm_readv, \ compat_sys_process_vm_readv) #define __NR_process_vm_writev 271 __SC_COMP(__NR_process_vm_writev, sys_process_vm_writev, \ compat_sys_process_vm_writev) #define __NR_kcmp 272 __SYSCALL(__NR_kcmp, sys_kcmp) #define __NR_finit_module 273 __SYSCALL(__NR_finit_module, sys_finit_module) #define __NR_sched_setattr 274 __SYSCALL(__NR_sched_setattr, sys_sched_setattr) #define __NR_sched_getattr 275 __SYSCALL(__NR_sched_getattr, sys_sched_getattr) #define __NR_renameat2 276 __SYSCALL(__NR_renameat2, sys_renameat2) #define __NR_seccomp 277 __SYSCALL(__NR_seccomp, sys_seccomp) #define __NR_getrandom 278 __SYSCALL(__NR_getrandom, sys_getrandom) #define __NR_memfd_create 279 __SYSCALL(__NR_memfd_create, sys_memfd_create) #define __NR_bpf 280 __SYSCALL(__NR_bpf, sys_bpf) #define __NR_execveat 281 __SC_COMP(__NR_execveat, sys_execveat, compat_sys_execveat) #define __NR_userfaultfd 282 __SYSCALL(__NR_userfaultfd, sys_userfaultfd) #define __NR_membarrier 283 __SYSCALL(__NR_membarrier, sys_membarrier) #define __NR_mlock2 284 __SYSCALL(__NR_mlock2, sys_mlock2) #define __NR_copy_file_range 285 __SYSCALL(__NR_copy_file_range, sys_copy_file_range) #define __NR_preadv2 286 __SC_COMP(__NR_preadv2, sys_preadv2, compat_sys_preadv2) #define __NR_pwritev2 287 __SC_COMP(__NR_pwritev2, sys_pwritev2, compat_sys_pwritev2) #define __NR_pkey_mprotect 288 __SYSCALL(__NR_pkey_mprotect, sys_pkey_mprotect) #define __NR_pkey_alloc 289 __SYSCALL(__NR_pkey_alloc, sys_pkey_alloc) #define __NR_pkey_free 290 __SYSCALL(__NR_pkey_free, sys_pkey_free) #define __NR_statx 291 __SYSCALL(__NR_statx, sys_statx) #define __NR_io_pgetevents 292 __SC_COMP(__NR_io_pgetevents, sys_io_pgetevents, compat_sys_io_pgetevents) #define __NR_rseq 293 __SYSCALL(__NR_rseq, sys_rseq) #define __NR_kexec_file_load 294 __SYSCALL(__NR_kexec_file_load, sys_kexec_file_load) #if __BITS_PER_LONG == 32 #define __NR_clock_gettime64 403 __SYSCALL(__NR_clock_gettime64, sys_clock_gettime) #define __NR_clock_settime64 404 __SYSCALL(__NR_clock_settime64, sys_clock_settime) #define __NR_clock_adjtime64 405 __SYSCALL(__NR_clock_adjtime64, sys_clock_adjtime) #define __NR_clock_getres_time64 406 __SYSCALL(__NR_clock_getres_time64, sys_clock_getres) #define __NR_clock_nanosleep_time64 407 __SYSCALL(__NR_clock_nanosleep_time64, sys_clock_nanosleep) #define __NR_timer_gettime64 408 __SYSCALL(__NR_timer_gettime64, sys_timer_gettime) #define __NR_timer_settime64 409 __SYSCALL(__NR_timer_settime64, sys_timer_settime) #define __NR_timerfd_gettime64 410 __SYSCALL(__NR_timerfd_gettime64, sys_timerfd_gettime) #define __NR_timerfd_settime64 411 __SYSCALL(__NR_timerfd_settime64, sys_timerfd_settime) #define __NR_utimensat_time64 412 __SYSCALL(__NR_utimensat_time64, sys_utimensat) #define __NR_io_pgetevents_time64 416 __SYSCALL(__NR_io_pgetevents_time64, sys_io_pgetevents) #define __NR_mq_timedsend_time64 418 __SYSCALL(__NR_mq_timedsend_time64, sys_mq_timedsend) #define __NR_mq_timedreceive_time64 419 __SYSCALL(__NR_mq_timedreceive_time64, sys_mq_timedreceive) #define __NR_semtimedop_time64 420 __SYSCALL(__NR_semtimedop_time64, sys_semtimedop) #define __NR_futex_time64 422 __SYSCALL(__NR_futex_time64, sys_futex) #define __NR_sched_rr_get_interval_time64 423 __SYSCALL(__NR_sched_rr_get_interval_time64, sys_sched_rr_get_interval) #endif #define __NR_pidfd_send_signal 424 __SYSCALL(__NR_pidfd_send_signal, sys_pidfd_send_signal) #define __NR_io_uring_setup 425 __SYSCALL(__NR_io_uring_setup, sys_io_uring_setup) #define __NR_io_uring_enter 426 __SYSCALL(__NR_io_uring_enter, sys_io_uring_enter) #define __NR_io_uring_register 427 __SYSCALL(__NR_io_uring_register, sys_io_uring_register) #define __NR_open_tree 428 __SYSCALL(__NR_open_tree, sys_open_tree) #define __NR_move_mount 429 __SYSCALL(__NR_move_mount, sys_move_mount) #define __NR_fsopen 430 __SYSCALL(__NR_fsopen, sys_fsopen) #define __NR_fsconfig 431 __SYSCALL(__NR_fsconfig, sys_fsconfig) #define __NR_fsmount 432 __SYSCALL(__NR_fsmount, sys_fsmount) #define __NR_fspick 433 __SYSCALL(__NR_fspick, sys_fspick) #define __NR_close_range 436 __SYSCALL(__NR_close_range, sys_close_range) #define __NR_faccessat2 439 __SYSCALL(__NR_faccessat2, sys_faccessat2) #define __NR_openat2 437 __SYSCALL(__NR_openat2, sys_openat2) #undef __NR_syscalls #define __NR_syscalls 441 /* * 32 bit systems traditionally used different * syscalls for off_t and loff_t arguments, while * 64 bit systems only need the off_t version. * For new 32 bit platforms, there is no need to * implement the old 32 bit off_t syscalls, so * they take different names. * Here we map the numbers so that both versions * use the same syscall table layout. */ #if __BITS_PER_LONG == 64 && !defined(__SYSCALL_COMPAT) #define __NR_fcntl __NR3264_fcntl #define __NR_statfs __NR3264_statfs #define __NR_fstatfs __NR3264_fstatfs #define __NR_truncate __NR3264_truncate #define __NR_ftruncate __NR3264_ftruncate #define __NR_lseek __NR3264_lseek #define __NR_sendfile __NR3264_sendfile #define __NR_newfstatat __NR3264_fstatat #define __NR_fstat __NR3264_fstat #define __NR_mmap __NR3264_mmap #define __NR_fadvise64 __NR3264_fadvise64 #ifdef __NR3264_stat #define __NR_stat __NR3264_stat #define __NR_lstat __NR3264_lstat #endif #else #define __NR_fcntl64 __NR3264_fcntl #define __NR_statfs64 __NR3264_statfs #define __NR_fstatfs64 __NR3264_fstatfs #define __NR_truncate64 __NR3264_truncate #define __NR_ftruncate64 __NR3264_ftruncate #define __NR_llseek __NR3264_lseek #define __NR_sendfile64 __NR3264_sendfile #define __NR_fstatat64 __NR3264_fstatat #define __NR_fstat64 __NR3264_fstat #define __NR_mmap2 __NR3264_mmap #define __NR_fadvise64_64 __NR3264_fadvise64 #ifdef __NR3264_stat #define __NR_stat64 __NR3264_stat #define __NR_lstat64 __NR3264_lstat #endif #endif asm-generic/int-ll64.h000064400000001540151027430560010463 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * asm-generic/int-ll64.h * * Integer declarations for architectures which use "long long" * for 64-bit types. */ #ifndef _ASM_GENERIC_INT_LL64_H #define _ASM_GENERIC_INT_LL64_H #include #ifndef __ASSEMBLY__ /* * __xx is ok: it doesn't pollute the POSIX namespace. Use these in the * header files exported to user space */ typedef __signed__ char __s8; typedef unsigned char __u8; typedef __signed__ short __s16; typedef unsigned short __u16; typedef __signed__ int __s32; typedef unsigned int __u32; #ifdef __GNUC__ __extension__ typedef __signed__ long long __s64; __extension__ typedef unsigned long long __u64; #else typedef __signed__ long long __s64; typedef unsigned long long __u64; #endif #endif /* __ASSEMBLY__ */ #endif /* _ASM_GENERIC_INT_LL64_H */ asm-generic/setup.h000064400000000276151027430560010257 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SETUP_H #define __ASM_GENERIC_SETUP_H #define COMMAND_LINE_SIZE 512 #endif /* __ASM_GENERIC_SETUP_H */ asm-generic/bpf_perf_event.h000064400000000356151027430560012102 0ustar00#ifndef __ASM_GENERIC_BPF_PERF_EVENT_H__ #define __ASM_GENERIC_BPF_PERF_EVENT_H__ #include /* Export kernel pt_regs structure */ typedef struct pt_regs bpf_user_pt_regs_t; #endif /* __ASM_GENERIC_BPF_PERF_EVENT_H__ */ asm-generic/bitsperlong.h000064400000001064151027430560011443 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_BITS_PER_LONG #define __ASM_GENERIC_BITS_PER_LONG /* * There seems to be no way of detecting this automatically from user * space, so 64 bit architectures should override this in their * bitsperlong.h. In particular, an architecture that supports * both 32 and 64 bit user space must not rely on CONFIG_64BIT * to decide it, but rather check a compiler provided macro. */ #ifndef __BITS_PER_LONG #define __BITS_PER_LONG 32 #endif #endif /* __ASM_GENERIC_BITS_PER_LONG */ asm-generic/int-l64.h000064400000001316151027430560010310 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * asm-generic/int-l64.h * * Integer declarations for architectures which use "long" * for 64-bit types. */ #ifndef _ASM_GENERIC_INT_L64_H #define _ASM_GENERIC_INT_L64_H #include #ifndef __ASSEMBLY__ /* * __xx is ok: it doesn't pollute the POSIX namespace. Use these in the * header files exported to user space */ typedef __signed__ char __s8; typedef unsigned char __u8; typedef __signed__ short __s16; typedef unsigned short __u16; typedef __signed__ int __s32; typedef unsigned int __u32; typedef __signed__ long __s64; typedef unsigned long __u64; #endif /* __ASSEMBLY__ */ #endif /* _ASM_GENERIC_INT_L64_H */ asm-generic/types.h000064400000000351151027430560010255 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_TYPES_H #define _ASM_GENERIC_TYPES_H /* * int-ll64 is used everywhere now. */ #include #endif /* _ASM_GENERIC_TYPES_H */ asm-generic/shmparam.h000064400000000347151027430560010726 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SHMPARAM_H #define __ASM_GENERIC_SHMPARAM_H #define SHMLBA PAGE_SIZE /* attach addr a multiple of this */ #endif /* _ASM_GENERIC_SHMPARAM_H */ asm-generic/auxvec.h000064400000000332151027430560010403 0ustar00#ifndef __ASM_GENERIC_AUXVEC_H #define __ASM_GENERIC_AUXVEC_H /* * Not all architectures need their own auxvec.h, the most * common definitions are already in linux/auxvec.h. */ #endif /* __ASM_GENERIC_AUXVEC_H */ asm-generic/errno-base.h000064400000003114151027430560011146 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_ERRNO_BASE_H #define _ASM_GENERIC_ERRNO_BASE_H #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */ #endif asm-generic/mman.h000064400000001344151027430560010044 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_MMAN_H #define __ASM_GENERIC_MMAN_H #include #define MAP_GROWSDOWN 0x0100 /* stack-like segment */ #define MAP_DENYWRITE 0x0800 /* ETXTBSY */ #define MAP_EXECUTABLE 0x1000 /* mark it as an executable */ #define MAP_LOCKED 0x2000 /* pages are locked */ #define MAP_NORESERVE 0x4000 /* don't check for reservations */ /* * Bits [26:31] are reserved, see asm-generic/hugetlb_encode.h * for MAP_HUGETLB usage */ #define MCL_CURRENT 1 /* lock all current mappings */ #define MCL_FUTURE 2 /* lock all future mappings */ #define MCL_ONFAULT 4 /* lock all pages that are faulted in */ #endif /* __ASM_GENERIC_MMAN_H */ asm-generic/termios.h000064400000002541151027430560010576 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_TERMIOS_H #define _ASM_GENERIC_TERMIOS_H /* * Most architectures have straight copies of the x86 code, with * varying levels of bug fixes on top. Usually it's a good idea * to use this generic version instead, but be careful to avoid * ABI changes. * New architectures should not provide their own version. */ #include #include struct winsize { unsigned short ws_row; unsigned short ws_col; unsigned short ws_xpixel; unsigned short ws_ypixel; }; #define NCC 8 struct termio { unsigned short c_iflag; /* input mode flags */ unsigned short c_oflag; /* output mode flags */ unsigned short c_cflag; /* control mode flags */ unsigned short c_lflag; /* local mode flags */ unsigned char c_line; /* line discipline */ unsigned char c_cc[NCC]; /* control characters */ }; /* modem lines */ #define TIOCM_LE 0x001 #define TIOCM_DTR 0x002 #define TIOCM_RTS 0x004 #define TIOCM_ST 0x008 #define TIOCM_SR 0x010 #define TIOCM_CTS 0x020 #define TIOCM_CAR 0x040 #define TIOCM_RNG 0x080 #define TIOCM_DSR 0x100 #define TIOCM_CD TIOCM_CAR #define TIOCM_RI TIOCM_RNG #define TIOCM_OUT1 0x2000 #define TIOCM_OUT2 0x4000 #define TIOCM_LOOP 0x8000 /* ioctl (fd, TIOCSERGETLSR, &result) where result may be as below */ #endif /* _ASM_GENERIC_TERMIOS_H */ asm-generic/siginfo.h000064400000030334151027430560010553 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_SIGINFO_H #define _ASM_GENERIC_SIGINFO_H #include typedef union sigval { int sival_int; void *sival_ptr; } sigval_t; #define SI_MAX_SIZE 128 /* * The default "si_band" type is "long", as specified by POSIX. * However, some architectures want to override this to "int" * for historical compatibility reasons, so we allow that. */ #ifndef __ARCH_SI_BAND_T #define __ARCH_SI_BAND_T long #endif #ifndef __ARCH_SI_CLOCK_T #define __ARCH_SI_CLOCK_T __kernel_clock_t #endif #ifndef __ARCH_SI_ATTRIBUTES #define __ARCH_SI_ATTRIBUTES #endif /* * RHEL8: The old and new siginfo structures have the same offsets for * their fields. They are just constructed in different ways. */ #ifdef __GENKSYMS__ #define __ARCH_SI_PREAMBLE_SIZE (4 * sizeof(int)) #define SI_PAD_SIZE ((SI_MAX_SIZE - __ARCH_SI_PREAMBLE_SIZE) / sizeof(int)) typedef struct siginfo { int si_signo; #ifndef __ARCH_HAS_SWAPPED_SIGINFO int si_errno; int si_code; #else int si_code; int si_errno; #endif union { int _pad[SI_PAD_SIZE]; /* kill() */ struct { __kernel_pid_t _pid; /* sender's pid */ __kernel_uid32_t _uid; /* sender's uid */ } _kill; /* POSIX.1b timers */ struct { __kernel_timer_t _tid; /* timer id */ int _overrun; /* overrun count */ sigval_t _sigval; /* same as below */ int _sys_private; /* not to be passed to user */ } _timer; /* POSIX.1b signals */ struct { __kernel_pid_t _pid; /* sender's pid */ __kernel_uid32_t _uid; /* sender's uid */ sigval_t _sigval; } _rt; /* SIGCHLD */ struct { __kernel_pid_t _pid; /* which child */ __kernel_uid32_t _uid; /* sender's uid */ int _status; /* exit code */ __ARCH_SI_CLOCK_T _utime; __ARCH_SI_CLOCK_T _stime; } _sigchld; /* SIGILL, SIGFPE, SIGSEGV, SIGBUS, SIGTRAP, SIGEMT */ struct { void *_addr; /* faulting insn/memory ref. */ #ifdef __ARCH_SI_TRAPNO int _trapno; /* TRAP # which caused the signal */ #endif #ifdef __ia64__ int _imm; /* immediate value for "break" */ unsigned int _flags; /* see ia64 si_flags */ unsigned long _isr; /* isr */ #endif #define __ADDR_BND_PKEY_PAD (__alignof__(void *) < sizeof(short) ? \ sizeof(short) : __alignof__(void *)) union { /* * used when si_code=BUS_MCEERR_AR or * used when si_code=BUS_MCEERR_AO */ short _addr_lsb; /* LSB of the reported address */ /* used when si_code=SEGV_BNDERR */ struct { char _dummy_bnd[__ADDR_BND_PKEY_PAD]; void *_lower; void *_upper; } _addr_bnd; /* used when si_code=SEGV_PKUERR */ struct { char _dummy_pkey[__ADDR_BND_PKEY_PAD]; __u32 _pkey; } _addr_pkey; }; } _sigfault; /* SIGPOLL */ struct { __ARCH_SI_BAND_T _band; /* POLL_IN, POLL_OUT, POLL_MSG */ int _fd; } _sigpoll; /* SIGSYS */ struct { void *_call_addr; /* calling user insn */ int _syscall; /* triggering system call number */ unsigned int _arch; /* AUDIT_ARCH_* of syscall */ } _sigsys; } _sifields; } __ARCH_SI_ATTRIBUTES siginfo_t; #else /* __GENKSYMS__ */ union __sifields { /* kill() */ struct { __kernel_pid_t _pid; /* sender's pid */ __kernel_uid32_t _uid; /* sender's uid */ } _kill; /* POSIX.1b timers */ struct { __kernel_timer_t _tid; /* timer id */ int _overrun; /* overrun count */ sigval_t _sigval; /* same as below */ int _sys_private; /* not to be passed to user */ } _timer; /* POSIX.1b signals */ struct { __kernel_pid_t _pid; /* sender's pid */ __kernel_uid32_t _uid; /* sender's uid */ sigval_t _sigval; } _rt; /* SIGCHLD */ struct { __kernel_pid_t _pid; /* which child */ __kernel_uid32_t _uid; /* sender's uid */ int _status; /* exit code */ __ARCH_SI_CLOCK_T _utime; __ARCH_SI_CLOCK_T _stime; } _sigchld; /* SIGILL, SIGFPE, SIGSEGV, SIGBUS, SIGTRAP, SIGEMT */ struct { void *_addr; /* faulting insn/memory ref. */ #ifdef __ARCH_SI_TRAPNO int _trapno; /* TRAP # which caused the signal */ #endif #ifdef __ia64__ int _imm; /* immediate value for "break" */ unsigned int _flags; /* see ia64 si_flags */ unsigned long _isr; /* isr */ #endif #define __ADDR_BND_PKEY_PAD (__alignof__(void *) < sizeof(short) ? \ sizeof(short) : __alignof__(void *)) union { /* * used when si_code=BUS_MCEERR_AR or * used when si_code=BUS_MCEERR_AO */ short _addr_lsb; /* LSB of the reported address */ /* used when si_code=SEGV_BNDERR */ struct { char _dummy_bnd[__ADDR_BND_PKEY_PAD]; void *_lower; void *_upper; } _addr_bnd; /* used when si_code=SEGV_PKUERR */ struct { char _dummy_pkey[__ADDR_BND_PKEY_PAD]; __u32 _pkey; } _addr_pkey; }; } _sigfault; /* SIGPOLL */ struct { __ARCH_SI_BAND_T _band; /* POLL_IN, POLL_OUT, POLL_MSG */ int _fd; } _sigpoll; /* SIGSYS */ struct { void *_call_addr; /* calling user insn */ int _syscall; /* triggering system call number */ unsigned int _arch; /* AUDIT_ARCH_* of syscall */ } _sigsys; }; #ifndef __ARCH_HAS_SWAPPED_SIGINFO #define __SIGINFO \ struct { \ int si_signo; \ int si_errno; \ int si_code; \ union __sifields _sifields; \ } #else #define __SIGINFO \ struct { \ int si_signo; \ int si_code; \ int si_errno; \ union __sifields _sifields; \ } #endif /* __ARCH_HAS_SWAPPED_SIGINFO */ typedef struct siginfo { union { __SIGINFO; int _si_pad[SI_MAX_SIZE/sizeof(int)]; }; } __ARCH_SI_ATTRIBUTES siginfo_t; #endif /* __GENKSYMS__ */ /* * How these fields are to be accessed. */ #define si_pid _sifields._kill._pid #define si_uid _sifields._kill._uid #define si_tid _sifields._timer._tid #define si_overrun _sifields._timer._overrun #define si_sys_private _sifields._timer._sys_private #define si_status _sifields._sigchld._status #define si_utime _sifields._sigchld._utime #define si_stime _sifields._sigchld._stime #define si_value _sifields._rt._sigval #define si_int _sifields._rt._sigval.sival_int #define si_ptr _sifields._rt._sigval.sival_ptr #define si_addr _sifields._sigfault._addr #ifdef __ARCH_SI_TRAPNO #define si_trapno _sifields._sigfault._trapno #endif #define si_addr_lsb _sifields._sigfault._addr_lsb #define si_lower _sifields._sigfault._addr_bnd._lower #define si_upper _sifields._sigfault._addr_bnd._upper #define si_pkey _sifields._sigfault._addr_pkey._pkey #define si_band _sifields._sigpoll._band #define si_fd _sifields._sigpoll._fd #define si_call_addr _sifields._sigsys._call_addr #define si_syscall _sifields._sigsys._syscall #define si_arch _sifields._sigsys._arch /* * si_code values * Digital reserves positive values for kernel-generated signals. */ #define SI_USER 0 /* sent by kill, sigsend, raise */ #define SI_KERNEL 0x80 /* sent by the kernel from somewhere */ #define SI_QUEUE -1 /* sent by sigqueue */ #define SI_TIMER -2 /* sent by timer expiration */ #define SI_MESGQ -3 /* sent by real time mesq state change */ #define SI_ASYNCIO -4 /* sent by AIO completion */ #define SI_SIGIO -5 /* sent by queued SIGIO */ #define SI_TKILL -6 /* sent by tkill system call */ #define SI_DETHREAD -7 /* sent by execve() killing subsidiary threads */ #define SI_ASYNCNL -60 /* sent by glibc async name lookup completion */ #define SI_FROMUSER(siptr) ((siptr)->si_code <= 0) #define SI_FROMKERNEL(siptr) ((siptr)->si_code > 0) /* * SIGILL si_codes */ #define ILL_ILLOPC 1 /* illegal opcode */ #define ILL_ILLOPN 2 /* illegal operand */ #define ILL_ILLADR 3 /* illegal addressing mode */ #define ILL_ILLTRP 4 /* illegal trap */ #define ILL_PRVOPC 5 /* privileged opcode */ #define ILL_PRVREG 6 /* privileged register */ #define ILL_COPROC 7 /* coprocessor error */ #define ILL_BADSTK 8 /* internal stack error */ #define ILL_BADIADDR 9 /* unimplemented instruction address */ #define __ILL_BREAK 10 /* illegal break */ #define __ILL_BNDMOD 11 /* bundle-update (modification) in progress */ #define NSIGILL 11 /* * SIGFPE si_codes */ #define FPE_INTDIV 1 /* integer divide by zero */ #define FPE_INTOVF 2 /* integer overflow */ #define FPE_FLTDIV 3 /* floating point divide by zero */ #define FPE_FLTOVF 4 /* floating point overflow */ #define FPE_FLTUND 5 /* floating point underflow */ #define FPE_FLTRES 6 /* floating point inexact result */ #define FPE_FLTINV 7 /* floating point invalid operation */ #define FPE_FLTSUB 8 /* subscript out of range */ #define __FPE_DECOVF 9 /* decimal overflow */ #define __FPE_DECDIV 10 /* decimal division by zero */ #define __FPE_DECERR 11 /* packed decimal error */ #define __FPE_INVASC 12 /* invalid ASCII digit */ #define __FPE_INVDEC 13 /* invalid decimal digit */ #define FPE_FLTUNK 14 /* undiagnosed floating-point exception */ #define FPE_CONDTRAP 15 /* trap on condition */ #define NSIGFPE 15 /* * SIGSEGV si_codes */ #define SEGV_MAPERR 1 /* address not mapped to object */ #define SEGV_ACCERR 2 /* invalid permissions for mapped object */ #define SEGV_BNDERR 3 /* failed address bound checks */ #ifdef __ia64__ # define __SEGV_PSTKOVF 4 /* paragraph stack overflow */ #else # define SEGV_PKUERR 4 /* failed protection key checks */ #endif #define SEGV_ACCADI 5 /* ADI not enabled for mapped object */ #define SEGV_ADIDERR 6 /* Disrupting MCD error */ #define SEGV_ADIPERR 7 /* Precise MCD exception */ #define NSIGSEGV 7 /* * SIGBUS si_codes */ #define BUS_ADRALN 1 /* invalid address alignment */ #define BUS_ADRERR 2 /* non-existent physical address */ #define BUS_OBJERR 3 /* object specific hardware error */ /* hardware memory error consumed on a machine check: action required */ #define BUS_MCEERR_AR 4 /* hardware memory error detected in process but not consumed: action optional*/ #define BUS_MCEERR_AO 5 #define NSIGBUS 5 /* * SIGTRAP si_codes */ #define TRAP_BRKPT 1 /* process breakpoint */ #define TRAP_TRACE 2 /* process trace trap */ #define TRAP_BRANCH 3 /* process taken branch trap */ #define TRAP_HWBKPT 4 /* hardware breakpoint/watchpoint */ #define TRAP_UNK 5 /* undiagnosed trap */ #define NSIGTRAP 5 /* * There is an additional set of SIGTRAP si_codes used by ptrace * that are of the form: ((PTRACE_EVENT_XXX << 8) | SIGTRAP) */ /* * SIGCHLD si_codes */ #define CLD_EXITED 1 /* child has exited */ #define CLD_KILLED 2 /* child was killed */ #define CLD_DUMPED 3 /* child terminated abnormally */ #define CLD_TRAPPED 4 /* traced child has trapped */ #define CLD_STOPPED 5 /* child has stopped */ #define CLD_CONTINUED 6 /* stopped child has continued */ #define NSIGCHLD 6 /* * SIGPOLL (or any other signal without signal specific si_codes) si_codes */ #define POLL_IN 1 /* data input available */ #define POLL_OUT 2 /* output buffers available */ #define POLL_MSG 3 /* input message available */ #define POLL_ERR 4 /* i/o error */ #define POLL_PRI 5 /* high priority input available */ #define POLL_HUP 6 /* device disconnected */ #define NSIGPOLL 6 /* * SIGSYS si_codes */ #define SYS_SECCOMP 1 /* seccomp triggered */ #define NSIGSYS 1 /* * SIGEMT si_codes */ #define EMT_TAGOVF 1 /* tag overflow */ #define NSIGEMT 1 /* * sigevent definitions * * It seems likely that SIGEV_THREAD will have to be handled from * userspace, libpthread transmuting it to SIGEV_SIGNAL, which the * thread manager then catches and does the appropriate nonsense. * However, everything is written out here so as to not get lost. */ #define SIGEV_SIGNAL 0 /* notify via signal */ #define SIGEV_NONE 1 /* other notification: meaningless */ #define SIGEV_THREAD 2 /* deliver via thread creation */ #define SIGEV_THREAD_ID 4 /* deliver to thread */ /* * This works because the alignment is ok on all current architectures * but we leave open this being overridden in the future */ #ifndef __ARCH_SIGEV_PREAMBLE_SIZE #define __ARCH_SIGEV_PREAMBLE_SIZE (sizeof(int) * 2 + sizeof(sigval_t)) #endif #define SIGEV_MAX_SIZE 64 #define SIGEV_PAD_SIZE ((SIGEV_MAX_SIZE - __ARCH_SIGEV_PREAMBLE_SIZE) \ / sizeof(int)) typedef struct sigevent { sigval_t sigev_value; int sigev_signo; int sigev_notify; union { int _pad[SIGEV_PAD_SIZE]; int _tid; struct { void (*_function)(sigval_t); void *_attribute; /* really pthread_attr_t */ } _sigev_thread; } _sigev_un; } sigevent_t; #define sigev_notify_function _sigev_un._sigev_thread._function #define sigev_notify_attributes _sigev_un._sigev_thread._attribute #define sigev_notify_thread_id _sigev_un._tid #endif /* _ASM_GENERIC_SIGINFO_H */ asm-generic/hugetlb_encode.h000064400000003417151027430560012066 0ustar00#ifndef _ASM_GENERIC_HUGETLB_ENCODE_H_ #define _ASM_GENERIC_HUGETLB_ENCODE_H_ /* * Several system calls take a flag to request "hugetlb" huge pages. * Without further specification, these system calls will use the * system's default huge page size. If a system supports multiple * huge page sizes, the desired huge page size can be specified in * bits [26:31] of the flag arguments. The value in these 6 bits * will encode the log2 of the huge page size. * * The following definitions are associated with this huge page size * encoding in flag arguments. System call specific header files * that use this encoding should include this file. They can then * provide definitions based on these with their own specific prefix. * for example: * #define MAP_HUGE_SHIFT HUGETLB_FLAG_ENCODE_SHIFT */ #define HUGETLB_FLAG_ENCODE_SHIFT 26 #define HUGETLB_FLAG_ENCODE_MASK 0x3f #define HUGETLB_FLAG_ENCODE_16KB (14 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_64KB (16 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_512KB (19 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_1MB (20 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_2MB (21 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_8MB (23 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_16MB (24 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_32MB (25 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_256MB (28 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_512MB (29 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_1GB (30 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_2GB (31 << HUGETLB_FLAG_ENCODE_SHIFT) #define HUGETLB_FLAG_ENCODE_16GB (34 << HUGETLB_FLAG_ENCODE_SHIFT) #endif /* _ASM_GENERIC_HUGETLB_ENCODE_H_ */ asm-generic/ipcbuf.h000064400000001753151027430560010370 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_IPCBUF_H #define __ASM_GENERIC_IPCBUF_H /* * The generic ipc64_perm structure: * Note extra padding because this structure is passed back and forth * between kernel and user space. * * ipc64_perm was originally meant to be architecture specific, but * everyone just ended up making identical copies without specific * optimizations, so we may just as well all use the same one. * * Pad space is left for: * - 32-bit mode_t on architectures that only had 16 bit * - 32-bit seq * - 2 miscellaneous 32-bit values */ struct ipc64_perm { __kernel_key_t key; __kernel_uid32_t uid; __kernel_gid32_t gid; __kernel_uid32_t cuid; __kernel_gid32_t cgid; __kernel_mode_t mode; /* pad if mode_t is u16: */ unsigned char __pad1[4 - sizeof(__kernel_mode_t)]; unsigned short seq; unsigned short __pad2; __kernel_ulong_t __unused1; __kernel_ulong_t __unused2; }; #endif /* __ASM_GENERIC_IPCBUF_H */ asm-generic/kvm_para.h000064400000000140151027430560010705 0ustar00/* * There isn't anything here, but the file must not be empty or patch * will delete it. */ asm-generic/statfs.h000064400000003457151027430560010427 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _GENERIC_STATFS_H #define _GENERIC_STATFS_H #include /* * Most 64-bit platforms use 'long', while most 32-bit platforms use '__u32'. * Yes, they differ in signedness as well as size. * Special cases can override it for themselves -- except for S390x, which * is just a little too special for us. And MIPS, which I'm not touching * with a 10' pole. */ #ifndef __statfs_word #if __BITS_PER_LONG == 64 #define __statfs_word __kernel_long_t #else #define __statfs_word __u32 #endif #endif struct statfs { __statfs_word f_type; __statfs_word f_bsize; __statfs_word f_blocks; __statfs_word f_bfree; __statfs_word f_bavail; __statfs_word f_files; __statfs_word f_ffree; __kernel_fsid_t f_fsid; __statfs_word f_namelen; __statfs_word f_frsize; __statfs_word f_flags; __statfs_word f_spare[4]; }; /* * ARM needs to avoid the 32-bit padding at the end, for consistency * between EABI and OABI */ #ifndef ARCH_PACK_STATFS64 #define ARCH_PACK_STATFS64 #endif struct statfs64 { __statfs_word f_type; __statfs_word f_bsize; __u64 f_blocks; __u64 f_bfree; __u64 f_bavail; __u64 f_files; __u64 f_ffree; __kernel_fsid_t f_fsid; __statfs_word f_namelen; __statfs_word f_frsize; __statfs_word f_flags; __statfs_word f_spare[4]; } ARCH_PACK_STATFS64; /* * IA64 and x86_64 need to avoid the 32-bit padding at the end, * to be compatible with the i386 ABI */ #ifndef ARCH_PACK_COMPAT_STATFS64 #define ARCH_PACK_COMPAT_STATFS64 #endif struct compat_statfs64 { __u32 f_type; __u32 f_bsize; __u64 f_blocks; __u64 f_bfree; __u64 f_bavail; __u64 f_files; __u64 f_ffree; __kernel_fsid_t f_fsid; __u32 f_namelen; __u32 f_frsize; __u32 f_flags; __u32 f_spare[4]; } ARCH_PACK_COMPAT_STATFS64; #endif /* _GENERIC_STATFS_H */ asm-generic/swab.h000064400000000766151027430560010057 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_SWAB_H #define _ASM_GENERIC_SWAB_H #include /* * 32 bit architectures typically (but not always) want to * set __SWAB_64_THRU_32__. In user space, this is only * valid if the compiler supports 64 bit data types. */ #if __BITS_PER_LONG == 32 #if defined(__GNUC__) && !defined(__STRICT_ANSI__) || defined(__KERNEL__) #define __SWAB_64_THRU_32__ #endif #endif #endif /* _ASM_GENERIC_SWAB_H */ asm-generic/sockios.h000064400000000667151027430560010575 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SOCKIOS_H #define __ASM_GENERIC_SOCKIOS_H /* Socket-level I/O control calls. */ #define FIOSETOWN 0x8901 #define SIOCSPGRP 0x8902 #define FIOGETOWN 0x8903 #define SIOCGPGRP 0x8904 #define SIOCATMARK 0x8905 #define SIOCGSTAMP 0x8906 /* Get stamp (timeval) */ #define SIOCGSTAMPNS 0x8907 /* Get stamp (timespec) */ #endif /* __ASM_GENERIC_SOCKIOS_H */ asm-generic/signal.h000064400000005225151027430560010373 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SIGNAL_H #define __ASM_GENERIC_SIGNAL_H #include #define _NSIG 64 #define _NSIG_BPW __BITS_PER_LONG #define _NSIG_WORDS (_NSIG / _NSIG_BPW) #define SIGHUP 1 #define SIGINT 2 #define SIGQUIT 3 #define SIGILL 4 #define SIGTRAP 5 #define SIGABRT 6 #define SIGIOT 6 #define SIGBUS 7 #define SIGFPE 8 #define SIGKILL 9 #define SIGUSR1 10 #define SIGSEGV 11 #define SIGUSR2 12 #define SIGPIPE 13 #define SIGALRM 14 #define SIGTERM 15 #define SIGSTKFLT 16 #define SIGCHLD 17 #define SIGCONT 18 #define SIGSTOP 19 #define SIGTSTP 20 #define SIGTTIN 21 #define SIGTTOU 22 #define SIGURG 23 #define SIGXCPU 24 #define SIGXFSZ 25 #define SIGVTALRM 26 #define SIGPROF 27 #define SIGWINCH 28 #define SIGIO 29 #define SIGPOLL SIGIO /* #define SIGLOST 29 */ #define SIGPWR 30 #define SIGSYS 31 #define SIGUNUSED 31 /* These should not be considered constants from userland. */ #define SIGRTMIN 32 #ifndef SIGRTMAX #define SIGRTMAX _NSIG #endif /* * SA_FLAGS values: * * SA_ONSTACK indicates that a registered stack_t will be used. * SA_RESTART flag to get restarting signals (which were the default long ago) * SA_NOCLDSTOP flag to turn off SIGCHLD when children stop. * SA_RESETHAND clears the handler when the signal is delivered. * SA_NOCLDWAIT flag on SIGCHLD to inhibit zombies. * SA_NODEFER prevents the current signal from being masked in the handler. * * SA_ONESHOT and SA_NOMASK are the historical Linux names for the Single * Unix names RESETHAND and NODEFER respectively. */ #define SA_NOCLDSTOP 0x00000001 #define SA_NOCLDWAIT 0x00000002 #define SA_SIGINFO 0x00000004 #define SA_ONSTACK 0x08000000 #define SA_RESTART 0x10000000 #define SA_NODEFER 0x40000000 #define SA_RESETHAND 0x80000000 #define SA_NOMASK SA_NODEFER #define SA_ONESHOT SA_RESETHAND /* * New architectures should not define the obsolete * SA_RESTORER 0x04000000 */ #if !defined MINSIGSTKSZ || !defined SIGSTKSZ #define MINSIGSTKSZ 2048 #define SIGSTKSZ 8192 #endif #ifndef __ASSEMBLY__ typedef struct { unsigned long sig[_NSIG_WORDS]; } sigset_t; /* not actually used, but required for linux/syscalls.h */ typedef unsigned long old_sigset_t; #include #ifdef SA_RESTORER #define __ARCH_HAS_SA_RESTORER #endif struct sigaction { __sighandler_t sa_handler; unsigned long sa_flags; #ifdef SA_RESTORER __sigrestore_t sa_restorer; #endif sigset_t sa_mask; /* mask last for extensibility */ }; typedef struct sigaltstack { void *ss_sp; int ss_flags; size_t ss_size; } stack_t; #endif /* __ASSEMBLY__ */ #endif /* __ASM_GENERIC_SIGNAL_H */ asm-generic/errno.h000064400000013020151027430560010233 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_ERRNO_H #define _ASM_GENERIC_ERRNO_H #include #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ /* * This error code is special: arch syscall entry code will return * -ENOSYS if users try to call a syscall that doesn't exist. To keep * failures of syscalls that really do exist distinguishable from * failures due to attempts to use a nonexistent syscall, syscall * implementations should refrain from returning -ENOSYS. */ #define ENOSYS 38 /* Invalid system call number */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ECANCELED 125 /* Operation Canceled */ #define ENOKEY 126 /* Required key not available */ #define EKEYEXPIRED 127 /* Key has expired */ #define EKEYREVOKED 128 /* Key has been revoked */ #define EKEYREJECTED 129 /* Key was rejected by service */ /* for robust mutexes */ #define EOWNERDEAD 130 /* Owner died */ #define ENOTRECOVERABLE 131 /* State not recoverable */ #define ERFKILL 132 /* Operation not possible due to RF-kill */ #define EHWPOISON 133 /* Memory page has hardware error */ #endif asm-generic/signal-defs.h000064400000001440151027430560011305 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SIGNAL_DEFS_H #define __ASM_GENERIC_SIGNAL_DEFS_H #ifndef SIG_BLOCK #define SIG_BLOCK 0 /* for blocking signals */ #endif #ifndef SIG_UNBLOCK #define SIG_UNBLOCK 1 /* for unblocking signals */ #endif #ifndef SIG_SETMASK #define SIG_SETMASK 2 /* for setting the signal mask */ #endif #ifndef __ASSEMBLY__ typedef void __signalfn_t(int); typedef __signalfn_t *__sighandler_t; typedef void __restorefn_t(void); typedef __restorefn_t *__sigrestore_t; #define SIG_DFL ((__sighandler_t)0) /* default signal handling */ #define SIG_IGN ((__sighandler_t)1) /* ignore signal */ #define SIG_ERR ((__sighandler_t)-1) /* error return from signal */ #endif #endif /* __ASM_GENERIC_SIGNAL_DEFS_H */ asm-generic/poll.h000064400000001556151027430560010067 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_POLL_H #define __ASM_GENERIC_POLL_H /* These are specified by iBCS2 */ #define POLLIN 0x0001 #define POLLPRI 0x0002 #define POLLOUT 0x0004 #define POLLERR 0x0008 #define POLLHUP 0x0010 #define POLLNVAL 0x0020 /* The rest seem to be more-or-less nonstandard. Check them! */ #define POLLRDNORM 0x0040 #define POLLRDBAND 0x0080 #ifndef POLLWRNORM #define POLLWRNORM 0x0100 #endif #ifndef POLLWRBAND #define POLLWRBAND 0x0200 #endif #ifndef POLLMSG #define POLLMSG 0x0400 #endif #ifndef POLLREMOVE #define POLLREMOVE 0x1000 #endif #ifndef POLLRDHUP #define POLLRDHUP 0x2000 #endif #define POLLFREE (__poll_t)0x4000 /* currently only for epoll */ #define POLL_BUSY_LOOP (__poll_t)0x8000 struct pollfd { int fd; short events; short revents; }; #endif /* __ASM_GENERIC_POLL_H */ asm-generic/ucontext.h000064400000000545151027430560010767 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_UCONTEXT_H #define __ASM_GENERIC_UCONTEXT_H struct ucontext { unsigned long uc_flags; struct ucontext *uc_link; stack_t uc_stack; struct sigcontext uc_mcontext; sigset_t uc_sigmask; /* mask last for extensibility */ }; #endif /* __ASM_GENERIC_UCONTEXT_H */ asm-generic/sembuf.h000064400000003016151027430560010373 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SEMBUF_H #define __ASM_GENERIC_SEMBUF_H #include /* * The semid64_ds structure for x86 architecture. * Note extra padding because this structure is passed back and forth * between kernel and user space. * * semid64_ds was originally meant to be architecture specific, but * everyone just ended up making identical copies without specific * optimizations, so we may just as well all use the same one. * * 64 bit architectures use a 64-bit __kernel_time_t here, while * 32 bit architectures have a pair of unsigned long values. * so they do not need the first two padding words. * * On big-endian systems, the padding is in the wrong place for * historic reasons, so user space has to reconstruct a time_t * value using * * user_semid_ds.sem_otime = kernel_semid64_ds.sem_otime + * ((long long)kernel_semid64_ds.sem_otime_high << 32) * * Pad space is left for 2 miscellaneous 32-bit values */ struct semid64_ds { struct ipc64_perm sem_perm; /* permissions .. see ipc.h */ #if __BITS_PER_LONG == 64 __kernel_time_t sem_otime; /* last semop time */ __kernel_time_t sem_ctime; /* last change time */ #else unsigned long sem_otime; /* last semop time */ unsigned long sem_otime_high; unsigned long sem_ctime; /* last change time */ unsigned long sem_ctime_high; #endif unsigned long sem_nsems; /* no. of semaphores in array */ unsigned long __unused3; unsigned long __unused4; }; #endif /* __ASM_GENERIC_SEMBUF_H */ asm-generic/termbits.h000064400000011154151027430560010745 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_TERMBITS_H #define __ASM_GENERIC_TERMBITS_H #include typedef unsigned char cc_t; typedef unsigned int speed_t; typedef unsigned int tcflag_t; #define NCCS 19 struct termios { tcflag_t c_iflag; /* input mode flags */ tcflag_t c_oflag; /* output mode flags */ tcflag_t c_cflag; /* control mode flags */ tcflag_t c_lflag; /* local mode flags */ cc_t c_line; /* line discipline */ cc_t c_cc[NCCS]; /* control characters */ }; struct termios2 { tcflag_t c_iflag; /* input mode flags */ tcflag_t c_oflag; /* output mode flags */ tcflag_t c_cflag; /* control mode flags */ tcflag_t c_lflag; /* local mode flags */ cc_t c_line; /* line discipline */ cc_t c_cc[NCCS]; /* control characters */ speed_t c_ispeed; /* input speed */ speed_t c_ospeed; /* output speed */ }; struct ktermios { tcflag_t c_iflag; /* input mode flags */ tcflag_t c_oflag; /* output mode flags */ tcflag_t c_cflag; /* control mode flags */ tcflag_t c_lflag; /* local mode flags */ cc_t c_line; /* line discipline */ cc_t c_cc[NCCS]; /* control characters */ speed_t c_ispeed; /* input speed */ speed_t c_ospeed; /* output speed */ }; /* c_cc characters */ #define VINTR 0 #define VQUIT 1 #define VERASE 2 #define VKILL 3 #define VEOF 4 #define VTIME 5 #define VMIN 6 #define VSWTC 7 #define VSTART 8 #define VSTOP 9 #define VSUSP 10 #define VEOL 11 #define VREPRINT 12 #define VDISCARD 13 #define VWERASE 14 #define VLNEXT 15 #define VEOL2 16 /* c_iflag bits */ #define IGNBRK 0000001 #define BRKINT 0000002 #define IGNPAR 0000004 #define PARMRK 0000010 #define INPCK 0000020 #define ISTRIP 0000040 #define INLCR 0000100 #define IGNCR 0000200 #define ICRNL 0000400 #define IUCLC 0001000 #define IXON 0002000 #define IXANY 0004000 #define IXOFF 0010000 #define IMAXBEL 0020000 #define IUTF8 0040000 /* c_oflag bits */ #define OPOST 0000001 #define OLCUC 0000002 #define ONLCR 0000004 #define OCRNL 0000010 #define ONOCR 0000020 #define ONLRET 0000040 #define OFILL 0000100 #define OFDEL 0000200 #define NLDLY 0000400 #define NL0 0000000 #define NL1 0000400 #define CRDLY 0003000 #define CR0 0000000 #define CR1 0001000 #define CR2 0002000 #define CR3 0003000 #define TABDLY 0014000 #define TAB0 0000000 #define TAB1 0004000 #define TAB2 0010000 #define TAB3 0014000 #define XTABS 0014000 #define BSDLY 0020000 #define BS0 0000000 #define BS1 0020000 #define VTDLY 0040000 #define VT0 0000000 #define VT1 0040000 #define FFDLY 0100000 #define FF0 0000000 #define FF1 0100000 /* c_cflag bit meaning */ #define CBAUD 0010017 #define B0 0000000 /* hang up */ #define B50 0000001 #define B75 0000002 #define B110 0000003 #define B134 0000004 #define B150 0000005 #define B200 0000006 #define B300 0000007 #define B600 0000010 #define B1200 0000011 #define B1800 0000012 #define B2400 0000013 #define B4800 0000014 #define B9600 0000015 #define B19200 0000016 #define B38400 0000017 #define EXTA B19200 #define EXTB B38400 #define CSIZE 0000060 #define CS5 0000000 #define CS6 0000020 #define CS7 0000040 #define CS8 0000060 #define CSTOPB 0000100 #define CREAD 0000200 #define PARENB 0000400 #define PARODD 0001000 #define HUPCL 0002000 #define CLOCAL 0004000 #define CBAUDEX 0010000 #define BOTHER 0010000 #define B57600 0010001 #define B115200 0010002 #define B230400 0010003 #define B460800 0010004 #define B500000 0010005 #define B576000 0010006 #define B921600 0010007 #define B1000000 0010010 #define B1152000 0010011 #define B1500000 0010012 #define B2000000 0010013 #define B2500000 0010014 #define B3000000 0010015 #define B3500000 0010016 #define B4000000 0010017 #define CIBAUD 002003600000 /* input baud rate */ #define CMSPAR 010000000000 /* mark or space (stick) parity */ #define CRTSCTS 020000000000 /* flow control */ #define IBSHIFT 16 /* Shift from CBAUD to CIBAUD */ /* c_lflag bits */ #define ISIG 0000001 #define ICANON 0000002 #define XCASE 0000004 #define ECHO 0000010 #define ECHOE 0000020 #define ECHOK 0000040 #define ECHONL 0000100 #define NOFLSH 0000200 #define TOSTOP 0000400 #define ECHOCTL 0001000 #define ECHOPRT 0002000 #define ECHOKE 0004000 #define FLUSHO 0010000 #define PENDIN 0040000 #define IEXTEN 0100000 #define EXTPROC 0200000 /* tcflow() and TCXONC use these */ #define TCOOFF 0 #define TCOON 1 #define TCIOFF 2 #define TCION 3 /* tcflush() and TCFLSH use these */ #define TCIFLUSH 0 #define TCOFLUSH 1 #define TCIOFLUSH 2 /* tcsetattr uses these */ #define TCSANOW 0 #define TCSADRAIN 1 #define TCSAFLUSH 2 #endif /* __ASM_GENERIC_TERMBITS_H */ asm-generic/fcntl.h000064400000012457151027430560010231 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_FCNTL_H #define _ASM_GENERIC_FCNTL_H #include /* * FMODE_EXEC is 0x20 * FMODE_NONOTIFY is 0x4000000 * These cannot be used by userspace O_* until internal and external open * flags are split. * -Eric Paris */ /* * When introducing new O_* bits, please check its uniqueness in fcntl_init(). */ #define O_ACCMODE 00000003 #define O_RDONLY 00000000 #define O_WRONLY 00000001 #define O_RDWR 00000002 #ifndef O_CREAT #define O_CREAT 00000100 /* not fcntl */ #endif #ifndef O_EXCL #define O_EXCL 00000200 /* not fcntl */ #endif #ifndef O_NOCTTY #define O_NOCTTY 00000400 /* not fcntl */ #endif #ifndef O_TRUNC #define O_TRUNC 00001000 /* not fcntl */ #endif #ifndef O_APPEND #define O_APPEND 00002000 #endif #ifndef O_NONBLOCK #define O_NONBLOCK 00004000 #endif #ifndef O_DSYNC #define O_DSYNC 00010000 /* used to be O_SYNC, see below */ #endif #ifndef FASYNC #define FASYNC 00020000 /* fcntl, for BSD compatibility */ #endif #ifndef O_DIRECT #define O_DIRECT 00040000 /* direct disk access hint */ #endif #ifndef O_LARGEFILE #define O_LARGEFILE 00100000 #endif #ifndef O_DIRECTORY #define O_DIRECTORY 00200000 /* must be a directory */ #endif #ifndef O_NOFOLLOW #define O_NOFOLLOW 00400000 /* don't follow links */ #endif #ifndef O_NOATIME #define O_NOATIME 01000000 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 02000000 /* set close_on_exec */ #endif /* * Before Linux 2.6.33 only O_DSYNC semantics were implemented, but using * the O_SYNC flag. We continue to use the existing numerical value * for O_DSYNC semantics now, but using the correct symbolic name for it. * This new value is used to request true Posix O_SYNC semantics. It is * defined in this strange way to make sure applications compiled against * new headers get at least O_DSYNC semantics on older kernels. * * This has the nice side-effect that we can simply test for O_DSYNC * wherever we do not care if O_DSYNC or O_SYNC is used. * * Note: __O_SYNC must never be used directly. */ #ifndef O_SYNC #define __O_SYNC 04000000 #define O_SYNC (__O_SYNC|O_DSYNC) #endif #ifndef O_PATH #define O_PATH 010000000 #endif #ifndef __O_TMPFILE #define __O_TMPFILE 020000000 #endif /* a horrid kludge trying to make sure that this will fail on old kernels */ #define O_TMPFILE (__O_TMPFILE | O_DIRECTORY) #define O_TMPFILE_MASK (__O_TMPFILE | O_DIRECTORY | O_CREAT) #ifndef O_NDELAY #define O_NDELAY O_NONBLOCK #endif #define F_DUPFD 0 /* dup */ #define F_GETFD 1 /* get close_on_exec */ #define F_SETFD 2 /* set/clear close_on_exec */ #define F_GETFL 3 /* get file->f_flags */ #define F_SETFL 4 /* set file->f_flags */ #ifndef F_GETLK #define F_GETLK 5 #define F_SETLK 6 #define F_SETLKW 7 #endif #ifndef F_SETOWN #define F_SETOWN 8 /* for sockets. */ #define F_GETOWN 9 /* for sockets. */ #endif #ifndef F_SETSIG #define F_SETSIG 10 /* for sockets. */ #define F_GETSIG 11 /* for sockets. */ #endif #ifndef CONFIG_64BIT #ifndef F_GETLK64 #define F_GETLK64 12 /* using 'struct flock64' */ #define F_SETLK64 13 #define F_SETLKW64 14 #endif #endif #ifndef F_SETOWN_EX #define F_SETOWN_EX 15 #define F_GETOWN_EX 16 #endif #ifndef F_GETOWNER_UIDS #define F_GETOWNER_UIDS 17 #endif /* * Open File Description Locks * * Usually record locks held by a process are released on *any* close and are * not inherited across a fork(). * * These cmd values will set locks that conflict with process-associated * record locks, but are "owned" by the open file description, not the * process. This means that they are inherited across fork() like BSD (flock) * locks, and they are only released automatically when the last reference to * the the open file against which they were acquired is put. */ #define F_OFD_GETLK 36 #define F_OFD_SETLK 37 #define F_OFD_SETLKW 38 #define F_OWNER_TID 0 #define F_OWNER_PID 1 #define F_OWNER_PGRP 2 struct f_owner_ex { int type; __kernel_pid_t pid; }; /* for F_[GET|SET]FL */ #define FD_CLOEXEC 1 /* actually anything with low bit set goes */ /* for posix fcntl() and lockf() */ #ifndef F_RDLCK #define F_RDLCK 0 #define F_WRLCK 1 #define F_UNLCK 2 #endif /* for old implementation of bsd flock () */ #ifndef F_EXLCK #define F_EXLCK 4 /* or 3 */ #define F_SHLCK 8 /* or 4 */ #endif /* operations for bsd flock(), also used by the kernel implementation */ #define LOCK_SH 1 /* shared lock */ #define LOCK_EX 2 /* exclusive lock */ #define LOCK_NB 4 /* or'd with one of the above to prevent blocking */ #define LOCK_UN 8 /* remove lock */ #define LOCK_MAND 32 /* This is a mandatory flock ... */ #define LOCK_READ 64 /* which allows concurrent read operations */ #define LOCK_WRITE 128 /* which allows concurrent write operations */ #define LOCK_RW 192 /* which allows concurrent read & write ops */ #define F_LINUX_SPECIFIC_BASE 1024 #ifndef HAVE_ARCH_STRUCT_FLOCK #ifndef __ARCH_FLOCK_PAD #define __ARCH_FLOCK_PAD #endif struct flock { short l_type; short l_whence; __kernel_off_t l_start; __kernel_off_t l_len; __kernel_pid_t l_pid; __ARCH_FLOCK_PAD }; #endif #ifndef HAVE_ARCH_STRUCT_FLOCK64 #ifndef __ARCH_FLOCK64_PAD #define __ARCH_FLOCK64_PAD #endif struct flock64 { short l_type; short l_whence; __kernel_loff_t l_start; __kernel_loff_t l_len; __kernel_pid_t l_pid; __ARCH_FLOCK64_PAD }; #endif #endif /* _ASM_GENERIC_FCNTL_H */ asm-generic/shmbuf.h000064400000003455151027430560010405 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_SHMBUF_H #define __ASM_GENERIC_SHMBUF_H #include /* * The shmid64_ds structure for x86 architecture. * Note extra padding because this structure is passed back and forth * between kernel and user space. * * shmid64_ds was originally meant to be architecture specific, but * everyone just ended up making identical copies without specific * optimizations, so we may just as well all use the same one. * * 64 bit architectures typically define a 64 bit __kernel_time_t, * so they do not need the first two padding words. * On big-endian systems, the padding is in the wrong place. * * * Pad space is left for: * - 2 miscellaneous 32-bit values */ struct shmid64_ds { struct ipc64_perm shm_perm; /* operation perms */ size_t shm_segsz; /* size of segment (bytes) */ #if __BITS_PER_LONG == 64 __kernel_time_t shm_atime; /* last attach time */ __kernel_time_t shm_dtime; /* last detach time */ __kernel_time_t shm_ctime; /* last change time */ #else unsigned long shm_atime; /* last attach time */ unsigned long shm_atime_high; unsigned long shm_dtime; /* last detach time */ unsigned long shm_dtime_high; unsigned long shm_ctime; /* last change time */ unsigned long shm_ctime_high; #endif __kernel_pid_t shm_cpid; /* pid of creator */ __kernel_pid_t shm_lpid; /* pid of last operator */ unsigned long shm_nattch; /* no. of current attaches */ unsigned long __unused4; unsigned long __unused5; }; struct shminfo64 { unsigned long shmmax; unsigned long shmmin; unsigned long shmmni; unsigned long shmseg; unsigned long shmall; unsigned long __unused1; unsigned long __unused2; unsigned long __unused3; unsigned long __unused4; }; #endif /* __ASM_GENERIC_SHMBUF_H */ asm-generic/posix_types.h000064400000004510151027430560011500 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_GENERIC_POSIX_TYPES_H #define __ASM_GENERIC_POSIX_TYPES_H #include /* * This file is generally used by user-level software, so you need to * be a little careful about namespace pollution etc. * * First the types that are often defined in different ways across * architectures, so that you can override them. */ #ifndef __kernel_long_t typedef long __kernel_long_t; typedef unsigned long __kernel_ulong_t; #endif #ifndef __kernel_ino_t typedef __kernel_ulong_t __kernel_ino_t; #endif #ifndef __kernel_mode_t typedef unsigned int __kernel_mode_t; #endif #ifndef __kernel_pid_t typedef int __kernel_pid_t; #endif #ifndef __kernel_ipc_pid_t typedef int __kernel_ipc_pid_t; #endif #ifndef __kernel_uid_t typedef unsigned int __kernel_uid_t; typedef unsigned int __kernel_gid_t; #endif #ifndef __kernel_suseconds_t typedef __kernel_long_t __kernel_suseconds_t; #endif #ifndef __kernel_daddr_t typedef int __kernel_daddr_t; #endif #ifndef __kernel_uid32_t typedef unsigned int __kernel_uid32_t; typedef unsigned int __kernel_gid32_t; #endif #ifndef __kernel_old_uid_t typedef __kernel_uid_t __kernel_old_uid_t; typedef __kernel_gid_t __kernel_old_gid_t; #endif #ifndef __kernel_old_dev_t typedef unsigned int __kernel_old_dev_t; #endif /* * Most 32 bit architectures use "unsigned int" size_t, * and all 64 bit architectures use "unsigned long" size_t. */ #ifndef __kernel_size_t #if __BITS_PER_LONG != 64 typedef unsigned int __kernel_size_t; typedef int __kernel_ssize_t; typedef int __kernel_ptrdiff_t; #else typedef __kernel_ulong_t __kernel_size_t; typedef __kernel_long_t __kernel_ssize_t; typedef __kernel_long_t __kernel_ptrdiff_t; #endif #endif #ifndef __kernel_fsid_t typedef struct { int val[2]; } __kernel_fsid_t; #endif /* * anything below here should be completely generic */ typedef __kernel_long_t __kernel_off_t; typedef long long __kernel_loff_t; typedef __kernel_long_t __kernel_old_time_t; typedef __kernel_long_t __kernel_time_t; typedef long long __kernel_time64_t; typedef __kernel_long_t __kernel_clock_t; typedef int __kernel_timer_t; typedef int __kernel_clockid_t; typedef char * __kernel_caddr_t; typedef unsigned short __kernel_uid16_t; typedef unsigned short __kernel_gid16_t; #endif /* __ASM_GENERIC_POSIX_TYPES_H */ asm-generic/resource.h000064400000003520151027430560010741 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_GENERIC_RESOURCE_H #define _ASM_GENERIC_RESOURCE_H /* * Resource limit IDs * * ( Compatibility detail: there are architectures that have * a different rlimit ID order in the 5-9 range and want * to keep that order for binary compatibility. The reasons * are historic and all new rlimits are identical across all * arches. If an arch has such special order for some rlimits * then it defines them prior including asm-generic/resource.h. ) */ #define RLIMIT_CPU 0 /* CPU time in sec */ #define RLIMIT_FSIZE 1 /* Maximum filesize */ #define RLIMIT_DATA 2 /* max data size */ #define RLIMIT_STACK 3 /* max stack size */ #define RLIMIT_CORE 4 /* max core file size */ #ifndef RLIMIT_RSS # define RLIMIT_RSS 5 /* max resident set size */ #endif #ifndef RLIMIT_NPROC # define RLIMIT_NPROC 6 /* max number of processes */ #endif #ifndef RLIMIT_NOFILE # define RLIMIT_NOFILE 7 /* max number of open files */ #endif #ifndef RLIMIT_MEMLOCK # define RLIMIT_MEMLOCK 8 /* max locked-in-memory address space */ #endif #ifndef RLIMIT_AS # define RLIMIT_AS 9 /* address space limit */ #endif #define RLIMIT_LOCKS 10 /* maximum file locks held */ #define RLIMIT_SIGPENDING 11 /* max number of pending signals */ #define RLIMIT_MSGQUEUE 12 /* maximum bytes in POSIX mqueues */ #define RLIMIT_NICE 13 /* max nice prio allowed to raise to 0-39 for nice level 19 .. -20 */ #define RLIMIT_RTPRIO 14 /* maximum realtime priority */ #define RLIMIT_RTTIME 15 /* timeout for RT tasks in us */ #define RLIM_NLIMITS 16 /* * SuS says limits have to be unsigned. * Which makes a ton more sense anyway. * * Some architectures override this (for compatibility reasons): */ #ifndef RLIM_INFINITY # define RLIM_INFINITY (~0UL) #endif #endif /* _ASM_GENERIC_RESOURCE_H */ gcrypt.h000064400000211331151027430560006231 0ustar00/* gcrypt.h - GNU Cryptographic Library Interface -*- c -*- * Copyright (C) 1998-2017 Free Software Foundation, Inc. * Copyright (C) 2012-2017 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * * File: src/gcrypt.h. Generated from gcrypt.h.in by configure. */ #ifndef _GCRYPT_H #define _GCRYPT_H #include #include #include #include #include #if defined _WIN32 || defined __WIN32__ # include # include # include # ifndef __GNUC__ typedef long ssize_t; typedef int pid_t; # endif /*!__GNUC__*/ #else # include # include # include #endif /*!_WIN32*/ typedef socklen_t gcry_socklen_t; /* This is required for error code compatibility. */ #define _GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_GCRYPT #ifdef __cplusplus extern "C" { #if 0 /* (Keep Emacsens' auto-indent happy.) */ } #endif #endif /* The version of this header should match the one of the library. It should not be used by a program because gcry_check_version() should return the same version. The purpose of this macro is to let autoconf (using the AM_PATH_GCRYPT macro) check that this header matches the installed library. */ #define GCRYPT_VERSION "1.8.5" /* The version number of this header. It may be used to handle minor API incompatibilities. */ #define GCRYPT_VERSION_NUMBER 0x010805 /* Internal: We can't use the convenience macros for the multi precision integer functions when building this library. */ #ifdef _GCRYPT_IN_LIBGCRYPT #ifndef GCRYPT_NO_MPI_MACROS #define GCRYPT_NO_MPI_MACROS 1 #endif #endif /* We want to use gcc attributes when possible. Warning: Don't use these macros in your programs: As indicated by the leading underscore they are subject to change without notice. */ #ifdef __GNUC__ #define _GCRY_GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if _GCRY_GCC_VERSION >= 30100 #define _GCRY_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__)) #endif #if _GCRY_GCC_VERSION >= 29600 #define _GCRY_GCC_ATTR_PURE __attribute__ ((__pure__)) #endif #if _GCRY_GCC_VERSION >= 30200 #define _GCRY_GCC_ATTR_MALLOC __attribute__ ((__malloc__)) #endif #define _GCRY_GCC_ATTR_PRINTF(f,a) __attribute__ ((format (printf,f,a))) #if _GCRY_GCC_VERSION >= 40000 #define _GCRY_GCC_ATTR_SENTINEL(a) __attribute__ ((sentinel(a))) #endif #endif /*__GNUC__*/ #ifndef _GCRY_GCC_ATTR_DEPRECATED #define _GCRY_GCC_ATTR_DEPRECATED #endif #ifndef _GCRY_GCC_ATTR_PURE #define _GCRY_GCC_ATTR_PURE #endif #ifndef _GCRY_GCC_ATTR_MALLOC #define _GCRY_GCC_ATTR_MALLOC #endif #ifndef _GCRY_GCC_ATTR_PRINTF #define _GCRY_GCC_ATTR_PRINTF(f,a) #endif #ifndef _GCRY_GCC_ATTR_SENTINEL #define _GCRY_GCC_ATTR_SENTINEL(a) #endif /* Make up an attribute to mark functions and types as deprecated but allow internal use by Libgcrypt. */ #ifdef _GCRYPT_IN_LIBGCRYPT #define _GCRY_ATTR_INTERNAL #else #define _GCRY_ATTR_INTERNAL _GCRY_GCC_ATTR_DEPRECATED #endif /* Wrappers for the libgpg-error library. */ typedef gpg_error_t gcry_error_t; typedef gpg_err_code_t gcry_err_code_t; typedef gpg_err_source_t gcry_err_source_t; static GPG_ERR_INLINE gcry_error_t gcry_err_make (gcry_err_source_t source, gcry_err_code_t code) { return gpg_err_make (source, code); } /* The user can define GPG_ERR_SOURCE_DEFAULT before including this file to specify a default source for gpg_error. */ #ifndef GCRY_ERR_SOURCE_DEFAULT #define GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_USER_1 #endif static GPG_ERR_INLINE gcry_error_t gcry_error (gcry_err_code_t code) { return gcry_err_make (GCRY_ERR_SOURCE_DEFAULT, code); } static GPG_ERR_INLINE gcry_err_code_t gcry_err_code (gcry_error_t err) { return gpg_err_code (err); } static GPG_ERR_INLINE gcry_err_source_t gcry_err_source (gcry_error_t err) { return gpg_err_source (err); } /* Return a pointer to a string containing a description of the error code in the error value ERR. */ const char *gcry_strerror (gcry_error_t err); /* Return a pointer to a string containing a description of the error source in the error value ERR. */ const char *gcry_strsource (gcry_error_t err); /* Retrieve the error code for the system error ERR. This returns GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report this). */ gcry_err_code_t gcry_err_code_from_errno (int err); /* Retrieve the system error for the error code CODE. This returns 0 if CODE is not a system error code. */ int gcry_err_code_to_errno (gcry_err_code_t code); /* Return an error value with the error source SOURCE and the system error ERR. */ gcry_error_t gcry_err_make_from_errno (gcry_err_source_t source, int err); /* Return an error value with the system error ERR. */ gcry_error_t gcry_error_from_errno (int err); /* NOTE: Since Libgcrypt 1.6 the thread callbacks are not anymore used. However we keep it to allow for some source code compatibility if used in the standard way. */ /* Constants defining the thread model to use. Used with the OPTION field of the struct gcry_thread_cbs. */ #define GCRY_THREAD_OPTION_DEFAULT 0 #define GCRY_THREAD_OPTION_USER 1 #define GCRY_THREAD_OPTION_PTH 2 #define GCRY_THREAD_OPTION_PTHREAD 3 /* The version number encoded in the OPTION field of the struct gcry_thread_cbs. */ #define GCRY_THREAD_OPTION_VERSION 1 /* Wrapper for struct ath_ops. */ struct gcry_thread_cbs { /* The OPTION field encodes the thread model and the version number of this structure. Bits 7 - 0 are used for the thread model Bits 15 - 8 are used for the version number. */ unsigned int option; } _GCRY_ATTR_INTERNAL; #define GCRY_THREAD_OPTION_PTH_IMPL \ static struct gcry_thread_cbs gcry_threads_pth = { \ (GCRY_THREAD_OPTION_PTH | (GCRY_THREAD_OPTION_VERSION << 8))} #define GCRY_THREAD_OPTION_PTHREAD_IMPL \ static struct gcry_thread_cbs gcry_threads_pthread = { \ (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8))} /* A generic context object as used by some functions. */ struct gcry_context; typedef struct gcry_context *gcry_ctx_t; /* The data objects used to hold multi precision integers. */ struct gcry_mpi; typedef struct gcry_mpi *gcry_mpi_t; struct gcry_mpi_point; typedef struct gcry_mpi_point *gcry_mpi_point_t; #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_mpi *GCRY_MPI _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_mpi *GcryMPI _GCRY_GCC_ATTR_DEPRECATED; #endif /* A structure used for scatter gather hashing. */ typedef struct { size_t size; /* The allocated size of the buffer or 0. */ size_t off; /* Offset into the buffer. */ size_t len; /* The used length of the buffer. */ void *data; /* The buffer. */ } gcry_buffer_t; /* Check that the library fulfills the version requirement. */ const char *gcry_check_version (const char *req_version); /* Codes for function dispatchers. */ /* Codes used with the gcry_control function. */ enum gcry_ctl_cmds { /* Note: 1 .. 2 are not anymore used. */ GCRYCTL_CFB_SYNC = 3, GCRYCTL_RESET = 4, /* e.g. for MDs */ GCRYCTL_FINALIZE = 5, GCRYCTL_GET_KEYLEN = 6, GCRYCTL_GET_BLKLEN = 7, GCRYCTL_TEST_ALGO = 8, GCRYCTL_IS_SECURE = 9, GCRYCTL_GET_ASNOID = 10, GCRYCTL_ENABLE_ALGO = 11, GCRYCTL_DISABLE_ALGO = 12, GCRYCTL_DUMP_RANDOM_STATS = 13, GCRYCTL_DUMP_SECMEM_STATS = 14, GCRYCTL_GET_ALGO_NPKEY = 15, GCRYCTL_GET_ALGO_NSKEY = 16, GCRYCTL_GET_ALGO_NSIGN = 17, GCRYCTL_GET_ALGO_NENCR = 18, GCRYCTL_SET_VERBOSITY = 19, GCRYCTL_SET_DEBUG_FLAGS = 20, GCRYCTL_CLEAR_DEBUG_FLAGS = 21, GCRYCTL_USE_SECURE_RNDPOOL= 22, GCRYCTL_DUMP_MEMORY_STATS = 23, GCRYCTL_INIT_SECMEM = 24, GCRYCTL_TERM_SECMEM = 25, GCRYCTL_DISABLE_SECMEM_WARN = 27, GCRYCTL_SUSPEND_SECMEM_WARN = 28, GCRYCTL_RESUME_SECMEM_WARN = 29, GCRYCTL_DROP_PRIVS = 30, GCRYCTL_ENABLE_M_GUARD = 31, GCRYCTL_START_DUMP = 32, GCRYCTL_STOP_DUMP = 33, GCRYCTL_GET_ALGO_USAGE = 34, GCRYCTL_IS_ALGO_ENABLED = 35, GCRYCTL_DISABLE_INTERNAL_LOCKING = 36, GCRYCTL_DISABLE_SECMEM = 37, GCRYCTL_INITIALIZATION_FINISHED = 38, GCRYCTL_INITIALIZATION_FINISHED_P = 39, GCRYCTL_ANY_INITIALIZATION_P = 40, GCRYCTL_SET_CBC_CTS = 41, GCRYCTL_SET_CBC_MAC = 42, /* Note: 43 is not anymore used. */ GCRYCTL_ENABLE_QUICK_RANDOM = 44, GCRYCTL_SET_RANDOM_SEED_FILE = 45, GCRYCTL_UPDATE_RANDOM_SEED_FILE = 46, GCRYCTL_SET_THREAD_CBS = 47, GCRYCTL_FAST_POLL = 48, GCRYCTL_SET_RANDOM_DAEMON_SOCKET = 49, GCRYCTL_USE_RANDOM_DAEMON = 50, GCRYCTL_FAKED_RANDOM_P = 51, GCRYCTL_SET_RNDEGD_SOCKET = 52, GCRYCTL_PRINT_CONFIG = 53, GCRYCTL_OPERATIONAL_P = 54, GCRYCTL_FIPS_MODE_P = 55, GCRYCTL_FORCE_FIPS_MODE = 56, GCRYCTL_SELFTEST = 57, /* Note: 58 .. 62 are used internally. */ GCRYCTL_DISABLE_HWF = 63, GCRYCTL_SET_ENFORCED_FIPS_FLAG = 64, GCRYCTL_SET_PREFERRED_RNG_TYPE = 65, GCRYCTL_GET_CURRENT_RNG_TYPE = 66, GCRYCTL_DISABLE_LOCKED_SECMEM = 67, GCRYCTL_DISABLE_PRIV_DROP = 68, GCRYCTL_SET_CCM_LENGTHS = 69, GCRYCTL_CLOSE_RANDOM_DEVICE = 70, GCRYCTL_INACTIVATE_FIPS_FLAG = 71, GCRYCTL_REACTIVATE_FIPS_FLAG = 72, GCRYCTL_SET_SBOX = 73, GCRYCTL_DRBG_REINIT = 74, GCRYCTL_SET_TAGLEN = 75, GCRYCTL_GET_TAGLEN = 76, GCRYCTL_REINIT_SYSCALL_CLAMP = 77 }; /* Perform various operations defined by CMD. */ gcry_error_t gcry_control (enum gcry_ctl_cmds CMD, ...); /* S-expression management. */ /* The object to represent an S-expression as used with the public key functions. */ struct gcry_sexp; typedef struct gcry_sexp *gcry_sexp_t; #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_sexp *GCRY_SEXP _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_sexp *GcrySexp _GCRY_GCC_ATTR_DEPRECATED; #endif /* The possible values for the S-expression format. */ enum gcry_sexp_format { GCRYSEXP_FMT_DEFAULT = 0, GCRYSEXP_FMT_CANON = 1, GCRYSEXP_FMT_BASE64 = 2, GCRYSEXP_FMT_ADVANCED = 3 }; /* Create an new S-expression object from BUFFER of size LENGTH and return it in RETSEXP. With AUTODETECT set to 0 the data in BUFFER is expected to be in canonized format. */ gcry_error_t gcry_sexp_new (gcry_sexp_t *retsexp, const void *buffer, size_t length, int autodetect); /* Same as gcry_sexp_new but allows to pass a FREEFNC which has the effect to transfer ownership of BUFFER to the created object. */ gcry_error_t gcry_sexp_create (gcry_sexp_t *retsexp, void *buffer, size_t length, int autodetect, void (*freefnc) (void *)); /* Scan BUFFER and return a new S-expression object in RETSEXP. This function expects a printf like string in BUFFER. */ gcry_error_t gcry_sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff, const char *buffer, size_t length); /* Same as gcry_sexp_sscan but expects a string in FORMAT and can thus only be used for certain encodings. */ gcry_error_t gcry_sexp_build (gcry_sexp_t *retsexp, size_t *erroff, const char *format, ...); /* Like gcry_sexp_build, but uses an array instead of variable function arguments. */ gcry_error_t gcry_sexp_build_array (gcry_sexp_t *retsexp, size_t *erroff, const char *format, void **arg_list); /* Release the S-expression object SEXP */ void gcry_sexp_release (gcry_sexp_t sexp); /* Calculate the length of an canonized S-expression in BUFFER and check for a valid encoding. */ size_t gcry_sexp_canon_len (const unsigned char *buffer, size_t length, size_t *erroff, gcry_error_t *errcode); /* Copies the S-expression object SEXP into BUFFER using the format specified in MODE. */ size_t gcry_sexp_sprint (gcry_sexp_t sexp, int mode, void *buffer, size_t maxlength); /* Dumps the S-expression object A in a format suitable for debugging to Libgcrypt's logging stream. */ void gcry_sexp_dump (const gcry_sexp_t a); gcry_sexp_t gcry_sexp_cons (const gcry_sexp_t a, const gcry_sexp_t b); gcry_sexp_t gcry_sexp_alist (const gcry_sexp_t *array); gcry_sexp_t gcry_sexp_vlist (const gcry_sexp_t a, ...); gcry_sexp_t gcry_sexp_append (const gcry_sexp_t a, const gcry_sexp_t n); gcry_sexp_t gcry_sexp_prepend (const gcry_sexp_t a, const gcry_sexp_t n); /* Scan the S-expression for a sublist with a type (the car of the list) matching the string TOKEN. If TOKLEN is not 0, the token is assumed to be raw memory of this length. The function returns a newly allocated S-expression consisting of the found sublist or `NULL' when not found. */ gcry_sexp_t gcry_sexp_find_token (gcry_sexp_t list, const char *tok, size_t toklen); /* Return the length of the LIST. For a valid S-expression this should be at least 1. */ int gcry_sexp_length (const gcry_sexp_t list); /* Create and return a new S-expression from the element with index NUMBER in LIST. Note that the first element has the index 0. If there is no such element, `NULL' is returned. */ gcry_sexp_t gcry_sexp_nth (const gcry_sexp_t list, int number); /* Create and return a new S-expression from the first element in LIST; this called the "type" and should always exist and be a string. `NULL' is returned in case of a problem. */ gcry_sexp_t gcry_sexp_car (const gcry_sexp_t list); /* Create and return a new list form all elements except for the first one. Note, that this function may return an invalid S-expression because it is not guaranteed, that the type exists and is a string. However, for parsing a complex S-expression it might be useful for intermediate lists. Returns `NULL' on error. */ gcry_sexp_t gcry_sexp_cdr (const gcry_sexp_t list); gcry_sexp_t gcry_sexp_cadr (const gcry_sexp_t list); /* This function is used to get data from a LIST. A pointer to the actual data with index NUMBER is returned and the length of this data will be stored to DATALEN. If there is no data at the given index or the index represents another list, `NULL' is returned. *Note:* The returned pointer is valid as long as LIST is not modified or released. */ const char *gcry_sexp_nth_data (const gcry_sexp_t list, int number, size_t *datalen); /* This function is used to get data from a LIST. A malloced buffer to the data with index NUMBER is returned and the length of this data will be stored to RLENGTH. If there is no data at the given index or the index represents another list, `NULL' is returned. */ void *gcry_sexp_nth_buffer (const gcry_sexp_t list, int number, size_t *rlength); /* This function is used to get and convert data from a LIST. The data is assumed to be a Nul terminated string. The caller must release the returned value using `gcry_free'. If there is no data at the given index, the index represents a list or the value can't be converted to a string, `NULL' is returned. */ char *gcry_sexp_nth_string (gcry_sexp_t list, int number); /* This function is used to get and convert data from a LIST. This data is assumed to be an MPI stored in the format described by MPIFMT and returned as a standard Libgcrypt MPI. The caller must release this returned value using `gcry_mpi_release'. If there is no data at the given index, the index represents a list or the value can't be converted to an MPI, `NULL' is returned. */ gcry_mpi_t gcry_sexp_nth_mpi (gcry_sexp_t list, int number, int mpifmt); /* Extract MPIs from an s-expression using a list of parameters. The * names of these parameters are given by the string LIST. Some * special characters may be given to control the conversion: * * + :: Switch to unsigned integer format (default). * - :: Switch to standard signed format. * / :: Switch to opaque format. * & :: Switch to buffer descriptor mode - see below. * ? :: The previous parameter is optional. * * In general parameter names are single letters. To use a string for * a parameter name, enclose the name in single quotes. * * Unless in gcry_buffer_t mode for each parameter name a pointer to * an MPI variable is expected that must be set to NULL prior to * invoking this function, and finally a NULL is expected. Example: * * _gcry_sexp_extract_param (key, NULL, "n/x+ed", * &mpi_n, &mpi_x, &mpi_e, NULL) * * This stores the parameter "N" from KEY as an unsigned MPI into * MPI_N, the parameter "X" as an opaque MPI into MPI_X, and the * parameter "E" again as an unsigned MPI into MPI_E. * * If in buffer descriptor mode a pointer to gcry_buffer_t descriptor * is expected instead of a pointer to an MPI. The caller may use two * different operation modes: If the DATA field of the provided buffer * descriptor is NULL, the function allocates a new buffer and stores * it at DATA; the other fields are set accordingly with OFF being 0. * If DATA is not NULL, the function assumes that DATA, SIZE, and OFF * describe a buffer where to but the data; on return the LEN field * receives the number of bytes copied to that buffer; if the buffer * is too small, the function immediately returns with an error code * (and LEN set to 0). * * PATH is an optional string used to locate a token. The exclamation * mark separated tokens are used to via gcry_sexp_find_token to find * a start point inside SEXP. * * The function returns 0 on success. On error an error code is * returned, all passed MPIs that might have been allocated up to this * point are deallocated and set to NULL, and all passed buffers are * either truncated if the caller supplied the buffer, or deallocated * if the function allocated the buffer. */ gpg_error_t gcry_sexp_extract_param (gcry_sexp_t sexp, const char *path, const char *list, ...) _GCRY_GCC_ATTR_SENTINEL(0); /******************************************* * * * Multi Precision Integer Functions * * * *******************************************/ /* Different formats of external big integer representation. */ enum gcry_mpi_format { GCRYMPI_FMT_NONE= 0, GCRYMPI_FMT_STD = 1, /* Twos complement stored without length. */ GCRYMPI_FMT_PGP = 2, /* As used by OpenPGP (unsigned only). */ GCRYMPI_FMT_SSH = 3, /* As used by SSH (like STD but with length). */ GCRYMPI_FMT_HEX = 4, /* Hex format. */ GCRYMPI_FMT_USG = 5, /* Like STD but unsigned. */ GCRYMPI_FMT_OPAQUE = 8 /* Opaque format (some functions only). */ }; /* Flags used for creating big integers. */ enum gcry_mpi_flag { GCRYMPI_FLAG_SECURE = 1, /* Allocate the number in "secure" memory. */ GCRYMPI_FLAG_OPAQUE = 2, /* The number is not a real one but just a way to store some bytes. This is useful for encrypted big integers. */ GCRYMPI_FLAG_IMMUTABLE = 4, /* Mark the MPI as immutable. */ GCRYMPI_FLAG_CONST = 8, /* Mark the MPI as a constant. */ GCRYMPI_FLAG_USER1 = 0x0100,/* User flag 1. */ GCRYMPI_FLAG_USER2 = 0x0200,/* User flag 2. */ GCRYMPI_FLAG_USER3 = 0x0400,/* User flag 3. */ GCRYMPI_FLAG_USER4 = 0x0800 /* User flag 4. */ }; /* Macros to return pre-defined MPI constants. */ #define GCRYMPI_CONST_ONE (_gcry_mpi_get_const (1)) #define GCRYMPI_CONST_TWO (_gcry_mpi_get_const (2)) #define GCRYMPI_CONST_THREE (_gcry_mpi_get_const (3)) #define GCRYMPI_CONST_FOUR (_gcry_mpi_get_const (4)) #define GCRYMPI_CONST_EIGHT (_gcry_mpi_get_const (8)) /* Allocate a new big integer object, initialize it with 0 and initially allocate memory for a number of at least NBITS. */ gcry_mpi_t gcry_mpi_new (unsigned int nbits); /* Same as gcry_mpi_new() but allocate in "secure" memory. */ gcry_mpi_t gcry_mpi_snew (unsigned int nbits); /* Release the number A and free all associated resources. */ void gcry_mpi_release (gcry_mpi_t a); /* Create a new number with the same value as A. */ gcry_mpi_t gcry_mpi_copy (const gcry_mpi_t a); /* Store the big integer value U in W and release U. */ void gcry_mpi_snatch (gcry_mpi_t w, gcry_mpi_t u); /* Store the big integer value U in W. */ gcry_mpi_t gcry_mpi_set (gcry_mpi_t w, const gcry_mpi_t u); /* Store the unsigned integer value U in W. */ gcry_mpi_t gcry_mpi_set_ui (gcry_mpi_t w, unsigned long u); /* Swap the values of A and B. */ void gcry_mpi_swap (gcry_mpi_t a, gcry_mpi_t b); /* Return 1 if A is negative; 0 if zero or positive. */ int gcry_mpi_is_neg (gcry_mpi_t a); /* W = - U */ void gcry_mpi_neg (gcry_mpi_t w, gcry_mpi_t u); /* W = [W] */ void gcry_mpi_abs (gcry_mpi_t w); /* Compare the big integer number U and V returning 0 for equality, a positive value for U > V and a negative for U < V. */ int gcry_mpi_cmp (const gcry_mpi_t u, const gcry_mpi_t v); /* Compare the big integer number U with the unsigned integer V returning 0 for equality, a positive value for U > V and a negative for U < V. */ int gcry_mpi_cmp_ui (const gcry_mpi_t u, unsigned long v); /* Convert the external representation of an integer stored in BUFFER with a length of BUFLEN into a newly create MPI returned in RET_MPI. If NSCANNED is not NULL, it will receive the number of bytes actually scanned after a successful operation. */ gcry_error_t gcry_mpi_scan (gcry_mpi_t *ret_mpi, enum gcry_mpi_format format, const void *buffer, size_t buflen, size_t *nscanned); /* Convert the big integer A into the external representation described by FORMAT and store it in the provided BUFFER which has been allocated by the user with a size of BUFLEN bytes. NWRITTEN receives the actual length of the external representation unless it has been passed as NULL. */ gcry_error_t gcry_mpi_print (enum gcry_mpi_format format, unsigned char *buffer, size_t buflen, size_t *nwritten, const gcry_mpi_t a); /* Convert the big integer A into the external representation described by FORMAT and store it in a newly allocated buffer which address will be put into BUFFER. NWRITTEN receives the actual lengths of the external representation. */ gcry_error_t gcry_mpi_aprint (enum gcry_mpi_format format, unsigned char **buffer, size_t *nwritten, const gcry_mpi_t a); /* Dump the value of A in a format suitable for debugging to Libgcrypt's logging stream. Note that one leading space but no trailing space or linefeed will be printed. It is okay to pass NULL for A. */ void gcry_mpi_dump (const gcry_mpi_t a); /* W = U + V. */ void gcry_mpi_add (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); /* W = U + V. V is an unsigned integer. */ void gcry_mpi_add_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v); /* W = U + V mod M. */ void gcry_mpi_addm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); /* W = U - V. */ void gcry_mpi_sub (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); /* W = U - V. V is an unsigned integer. */ void gcry_mpi_sub_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v ); /* W = U - V mod M */ void gcry_mpi_subm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); /* W = U * V. */ void gcry_mpi_mul (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); /* W = U * V. V is an unsigned integer. */ void gcry_mpi_mul_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v ); /* W = U * V mod M. */ void gcry_mpi_mulm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); /* W = U * (2 ^ CNT). */ void gcry_mpi_mul_2exp (gcry_mpi_t w, gcry_mpi_t u, unsigned long cnt); /* Q = DIVIDEND / DIVISOR, R = DIVIDEND % DIVISOR, Q or R may be passed as NULL. ROUND should be negative or 0. */ void gcry_mpi_div (gcry_mpi_t q, gcry_mpi_t r, gcry_mpi_t dividend, gcry_mpi_t divisor, int round); /* R = DIVIDEND % DIVISOR */ void gcry_mpi_mod (gcry_mpi_t r, gcry_mpi_t dividend, gcry_mpi_t divisor); /* W = B ^ E mod M. */ void gcry_mpi_powm (gcry_mpi_t w, const gcry_mpi_t b, const gcry_mpi_t e, const gcry_mpi_t m); /* Set G to the greatest common divisor of A and B. Return true if the G is 1. */ int gcry_mpi_gcd (gcry_mpi_t g, gcry_mpi_t a, gcry_mpi_t b); /* Set X to the multiplicative inverse of A mod M. Return true if the value exists. */ int gcry_mpi_invm (gcry_mpi_t x, gcry_mpi_t a, gcry_mpi_t m); /* Create a new point object. NBITS is usually 0. */ gcry_mpi_point_t gcry_mpi_point_new (unsigned int nbits); /* Release the object POINT. POINT may be NULL. */ void gcry_mpi_point_release (gcry_mpi_point_t point); /* Return a copy of POINT. */ gcry_mpi_point_t gcry_mpi_point_copy (gcry_mpi_point_t point); /* Store the projective coordinates from POINT into X, Y, and Z. */ void gcry_mpi_point_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, gcry_mpi_point_t point); /* Store the projective coordinates from POINT into X, Y, and Z and release POINT. */ void gcry_mpi_point_snatch_get (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z, gcry_mpi_point_t point); /* Store the projective coordinates X, Y, and Z into POINT. */ gcry_mpi_point_t gcry_mpi_point_set (gcry_mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z); /* Store the projective coordinates X, Y, and Z into POINT and release X, Y, and Z. */ gcry_mpi_point_t gcry_mpi_point_snatch_set (gcry_mpi_point_t point, gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_t z); /* Allocate a new context for elliptic curve operations based on the parameters given by KEYPARAM or using CURVENAME. */ gpg_error_t gcry_mpi_ec_new (gcry_ctx_t *r_ctx, gcry_sexp_t keyparam, const char *curvename); /* Get a named MPI from an elliptic curve context. */ gcry_mpi_t gcry_mpi_ec_get_mpi (const char *name, gcry_ctx_t ctx, int copy); /* Get a named point from an elliptic curve context. */ gcry_mpi_point_t gcry_mpi_ec_get_point (const char *name, gcry_ctx_t ctx, int copy); /* Store a named MPI into an elliptic curve context. */ gpg_error_t gcry_mpi_ec_set_mpi (const char *name, gcry_mpi_t newvalue, gcry_ctx_t ctx); /* Store a named point into an elliptic curve context. */ gpg_error_t gcry_mpi_ec_set_point (const char *name, gcry_mpi_point_t newvalue, gcry_ctx_t ctx); /* Decode and store VALUE into RESULT. */ gpg_error_t gcry_mpi_ec_decode_point (gcry_mpi_point_t result, gcry_mpi_t value, gcry_ctx_t ctx); /* Store the affine coordinates of POINT into X and Y. */ int gcry_mpi_ec_get_affine (gcry_mpi_t x, gcry_mpi_t y, gcry_mpi_point_t point, gcry_ctx_t ctx); /* W = 2 * U. */ void gcry_mpi_ec_dup (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_ctx_t ctx); /* W = U + V. */ void gcry_mpi_ec_add (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_mpi_point_t v, gcry_ctx_t ctx); /* W = U - V. */ void gcry_mpi_ec_sub (gcry_mpi_point_t w, gcry_mpi_point_t u, gcry_mpi_point_t v, gcry_ctx_t ctx); /* W = N * U. */ void gcry_mpi_ec_mul (gcry_mpi_point_t w, gcry_mpi_t n, gcry_mpi_point_t u, gcry_ctx_t ctx); /* Return true if POINT is on the curve described by CTX. */ int gcry_mpi_ec_curve_point (gcry_mpi_point_t w, gcry_ctx_t ctx); /* Return the number of bits required to represent A. */ unsigned int gcry_mpi_get_nbits (gcry_mpi_t a); /* Return true when bit number N (counting from 0) is set in A. */ int gcry_mpi_test_bit (gcry_mpi_t a, unsigned int n); /* Set bit number N in A. */ void gcry_mpi_set_bit (gcry_mpi_t a, unsigned int n); /* Clear bit number N in A. */ void gcry_mpi_clear_bit (gcry_mpi_t a, unsigned int n); /* Set bit number N in A and clear all bits greater than N. */ void gcry_mpi_set_highbit (gcry_mpi_t a, unsigned int n); /* Clear bit number N in A and all bits greater than N. */ void gcry_mpi_clear_highbit (gcry_mpi_t a, unsigned int n); /* Shift the value of A by N bits to the right and store the result in X. */ void gcry_mpi_rshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n); /* Shift the value of A by N bits to the left and store the result in X. */ void gcry_mpi_lshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n); /* Store NBITS of the value P points to in A and mark A as an opaque value. On success A received the the ownership of the value P. WARNING: Never use an opaque MPI for anything thing else than gcry_mpi_release, gcry_mpi_get_opaque. */ gcry_mpi_t gcry_mpi_set_opaque (gcry_mpi_t a, void *p, unsigned int nbits); /* Store NBITS of the value P points to in A and mark A as an opaque value. The function takes a copy of the provided value P. WARNING: Never use an opaque MPI for anything thing else than gcry_mpi_release, gcry_mpi_get_opaque. */ gcry_mpi_t gcry_mpi_set_opaque_copy (gcry_mpi_t a, const void *p, unsigned int nbits); /* Return a pointer to an opaque value stored in A and return its size in NBITS. Note that the returned pointer is still owned by A and that the function should never be used for an non-opaque MPI. */ void *gcry_mpi_get_opaque (gcry_mpi_t a, unsigned int *nbits); /* Set the FLAG for the big integer A. Currently only the flag GCRYMPI_FLAG_SECURE is allowed to convert A into an big intger stored in "secure" memory. */ void gcry_mpi_set_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Clear FLAG for the big integer A. Note that this function is currently useless as no flags are allowed. */ void gcry_mpi_clear_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Return true if the FLAG is set for A. */ int gcry_mpi_get_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); /* Private function - do not use. */ gcry_mpi_t _gcry_mpi_get_const (int no); /* Unless the GCRYPT_NO_MPI_MACROS is used, provide a couple of convenience macros for the big integer functions. */ #ifndef GCRYPT_NO_MPI_MACROS #define mpi_new(n) gcry_mpi_new( (n) ) #define mpi_secure_new( n ) gcry_mpi_snew( (n) ) #define mpi_release(a) \ do \ { \ gcry_mpi_release ((a)); \ (a) = NULL; \ } \ while (0) #define mpi_copy( a ) gcry_mpi_copy( (a) ) #define mpi_snatch( w, u) gcry_mpi_snatch( (w), (u) ) #define mpi_set( w, u) gcry_mpi_set( (w), (u) ) #define mpi_set_ui( w, u) gcry_mpi_set_ui( (w), (u) ) #define mpi_abs( w ) gcry_mpi_abs( (w) ) #define mpi_neg( w, u) gcry_mpi_neg( (w), (u) ) #define mpi_cmp( u, v ) gcry_mpi_cmp( (u), (v) ) #define mpi_cmp_ui( u, v ) gcry_mpi_cmp_ui( (u), (v) ) #define mpi_is_neg( a ) gcry_mpi_is_neg ((a)) #define mpi_add_ui(w,u,v) gcry_mpi_add_ui((w),(u),(v)) #define mpi_add(w,u,v) gcry_mpi_add ((w),(u),(v)) #define mpi_addm(w,u,v,m) gcry_mpi_addm ((w),(u),(v),(m)) #define mpi_sub_ui(w,u,v) gcry_mpi_sub_ui ((w),(u),(v)) #define mpi_sub(w,u,v) gcry_mpi_sub ((w),(u),(v)) #define mpi_subm(w,u,v,m) gcry_mpi_subm ((w),(u),(v),(m)) #define mpi_mul_ui(w,u,v) gcry_mpi_mul_ui ((w),(u),(v)) #define mpi_mul_2exp(w,u,v) gcry_mpi_mul_2exp ((w),(u),(v)) #define mpi_mul(w,u,v) gcry_mpi_mul ((w),(u),(v)) #define mpi_mulm(w,u,v,m) gcry_mpi_mulm ((w),(u),(v),(m)) #define mpi_powm(w,b,e,m) gcry_mpi_powm ( (w), (b), (e), (m) ) #define mpi_tdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), 0) #define mpi_fdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), -1) #define mpi_mod(r,a,m) gcry_mpi_mod ((r), (a), (m)) #define mpi_gcd(g,a,b) gcry_mpi_gcd ( (g), (a), (b) ) #define mpi_invm(g,a,b) gcry_mpi_invm ( (g), (a), (b) ) #define mpi_point_new(n) gcry_mpi_point_new((n)) #define mpi_point_release(p) \ do \ { \ gcry_mpi_point_release ((p)); \ (p) = NULL; \ } \ while (0) #define mpi_point_copy(p) gcry_mpi_point_copy((p)) #define mpi_point_get(x,y,z,p) gcry_mpi_point_get((x),(y),(z),(p)) #define mpi_point_snatch_get(x,y,z,p) gcry_mpi_point_snatch_get((x),(y),(z),(p)) #define mpi_point_set(p,x,y,z) gcry_mpi_point_set((p),(x),(y),(z)) #define mpi_point_snatch_set(p,x,y,z) gcry_mpi_point_snatch_set((p),(x),(y),(z)) #define mpi_get_nbits(a) gcry_mpi_get_nbits ((a)) #define mpi_test_bit(a,b) gcry_mpi_test_bit ((a),(b)) #define mpi_set_bit(a,b) gcry_mpi_set_bit ((a),(b)) #define mpi_set_highbit(a,b) gcry_mpi_set_highbit ((a),(b)) #define mpi_clear_bit(a,b) gcry_mpi_clear_bit ((a),(b)) #define mpi_clear_highbit(a,b) gcry_mpi_clear_highbit ((a),(b)) #define mpi_rshift(a,b,c) gcry_mpi_rshift ((a),(b),(c)) #define mpi_lshift(a,b,c) gcry_mpi_lshift ((a),(b),(c)) #define mpi_set_opaque(a,b,c) gcry_mpi_set_opaque( (a), (b), (c) ) #define mpi_get_opaque(a,b) gcry_mpi_get_opaque( (a), (b) ) #endif /* GCRYPT_NO_MPI_MACROS */ /************************************ * * * Symmetric Cipher Functions * * * ************************************/ /* The data object used to hold a handle to an encryption object. */ struct gcry_cipher_handle; typedef struct gcry_cipher_handle *gcry_cipher_hd_t; #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_cipher_handle *GCRY_CIPHER_HD _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_cipher_handle *GcryCipherHd _GCRY_GCC_ATTR_DEPRECATED; #endif /* All symmetric encryption algorithms are identified by their IDs. More IDs may be registered at runtime. */ enum gcry_cipher_algos { GCRY_CIPHER_NONE = 0, GCRY_CIPHER_IDEA = 1, GCRY_CIPHER_3DES = 2, GCRY_CIPHER_CAST5 = 3, GCRY_CIPHER_BLOWFISH = 4, GCRY_CIPHER_SAFER_SK128 = 5, GCRY_CIPHER_DES_SK = 6, GCRY_CIPHER_AES = 7, GCRY_CIPHER_AES192 = 8, GCRY_CIPHER_AES256 = 9, GCRY_CIPHER_TWOFISH = 10, /* Other cipher numbers are above 300 for OpenPGP reasons. */ GCRY_CIPHER_ARCFOUR = 301, /* Fully compatible with RSA's RC4 (tm). */ GCRY_CIPHER_DES = 302, /* Yes, this is single key 56 bit DES. */ GCRY_CIPHER_TWOFISH128 = 303, GCRY_CIPHER_SERPENT128 = 304, GCRY_CIPHER_SERPENT192 = 305, GCRY_CIPHER_SERPENT256 = 306, GCRY_CIPHER_RFC2268_40 = 307, /* Ron's Cipher 2 (40 bit). */ GCRY_CIPHER_RFC2268_128 = 308, /* Ron's Cipher 2 (128 bit). */ GCRY_CIPHER_SEED = 309, /* 128 bit cipher described in RFC4269. */ GCRY_CIPHER_CAMELLIA128 = 310, GCRY_CIPHER_CAMELLIA192 = 311, GCRY_CIPHER_CAMELLIA256 = 312, GCRY_CIPHER_SALSA20 = 313, GCRY_CIPHER_SALSA20R12 = 314, GCRY_CIPHER_GOST28147 = 315, GCRY_CIPHER_CHACHA20 = 316 }; /* The Rijndael algorithm is basically AES, so provide some macros. */ #define GCRY_CIPHER_AES128 GCRY_CIPHER_AES #define GCRY_CIPHER_RIJNDAEL GCRY_CIPHER_AES #define GCRY_CIPHER_RIJNDAEL128 GCRY_CIPHER_AES128 #define GCRY_CIPHER_RIJNDAEL192 GCRY_CIPHER_AES192 #define GCRY_CIPHER_RIJNDAEL256 GCRY_CIPHER_AES256 /* The supported encryption modes. Note that not all of them are supported for each algorithm. */ enum gcry_cipher_modes { GCRY_CIPHER_MODE_NONE = 0, /* Not yet specified. */ GCRY_CIPHER_MODE_ECB = 1, /* Electronic codebook. */ GCRY_CIPHER_MODE_CFB = 2, /* Cipher feedback. */ GCRY_CIPHER_MODE_CBC = 3, /* Cipher block chaining. */ GCRY_CIPHER_MODE_STREAM = 4, /* Used with stream ciphers. */ GCRY_CIPHER_MODE_OFB = 5, /* Outer feedback. */ GCRY_CIPHER_MODE_CTR = 6, /* Counter. */ GCRY_CIPHER_MODE_AESWRAP = 7, /* AES-WRAP algorithm. */ GCRY_CIPHER_MODE_CCM = 8, /* Counter with CBC-MAC. */ GCRY_CIPHER_MODE_GCM = 9, /* Galois Counter Mode. */ GCRY_CIPHER_MODE_POLY1305 = 10, /* Poly1305 based AEAD mode. */ GCRY_CIPHER_MODE_OCB = 11, /* OCB3 mode. */ GCRY_CIPHER_MODE_CFB8 = 12, /* Cipher feedback (8 bit mode). */ GCRY_CIPHER_MODE_XTS = 13 /* XTS mode. */ }; /* Flags used with the open function. */ enum gcry_cipher_flags { GCRY_CIPHER_SECURE = 1, /* Allocate in secure memory. */ GCRY_CIPHER_ENABLE_SYNC = 2, /* Enable CFB sync mode. */ GCRY_CIPHER_CBC_CTS = 4, /* Enable CBC cipher text stealing (CTS). */ GCRY_CIPHER_CBC_MAC = 8 /* Enable CBC message auth. code (MAC). */ }; /* GCM works only with blocks of 128 bits */ #define GCRY_GCM_BLOCK_LEN (128 / 8) /* CCM works only with blocks of 128 bits. */ #define GCRY_CCM_BLOCK_LEN (128 / 8) /* OCB works only with blocks of 128 bits. */ #define GCRY_OCB_BLOCK_LEN (128 / 8) /* XTS works only with blocks of 128 bits. */ #define GCRY_XTS_BLOCK_LEN (128 / 8) /* Create a handle for algorithm ALGO to be used in MODE. FLAGS may be given as an bitwise OR of the gcry_cipher_flags values. */ gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *handle, int algo, int mode, unsigned int flags); /* Close the cipher handle H and release all resource. */ void gcry_cipher_close (gcry_cipher_hd_t h); /* Perform various operations on the cipher object H. */ gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer, size_t buflen); /* Retrieve various information about the cipher object H. */ gcry_error_t gcry_cipher_info (gcry_cipher_hd_t h, int what, void *buffer, size_t *nbytes); /* Retrieve various information about the cipher algorithm ALGO. */ gcry_error_t gcry_cipher_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Map the cipher algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this function returns "?". */ const char *gcry_cipher_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm name NAME to an cipher algorithm ID. Return 0 if the algorithm name is not known. */ int gcry_cipher_map_name (const char *name) _GCRY_GCC_ATTR_PURE; /* Given an ASN.1 object identifier in standard IETF dotted decimal format in STRING, return the encryption mode associated with that OID or 0 if not known or applicable. */ int gcry_cipher_mode_from_oid (const char *string) _GCRY_GCC_ATTR_PURE; /* Encrypt the plaintext of size INLEN in IN using the cipher handle H into the buffer OUT which has an allocated length of OUTSIZE. For most algorithms it is possible to pass NULL for in and 0 for INLEN and do a in-place decryption of the data provided in OUT. */ gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen); /* The counterpart to gcry_cipher_encrypt. */ gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t h, void *out, size_t outsize, const void *in, size_t inlen); /* Set KEY of length KEYLEN bytes for the cipher handle HD. */ gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t hd, const void *key, size_t keylen); /* Set initialization vector IV of length IVLEN for the cipher handle HD. */ gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t hd, const void *iv, size_t ivlen); /* Provide additional authentication data for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_authenticate (gcry_cipher_hd_t hd, const void *abuf, size_t abuflen); /* Get authentication tag for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_gettag (gcry_cipher_hd_t hd, void *outtag, size_t taglen); /* Check authentication tag for AEAD modes/ciphers. */ gcry_error_t gcry_cipher_checktag (gcry_cipher_hd_t hd, const void *intag, size_t taglen); /* Reset the handle to the state after open. */ #define gcry_cipher_reset(h) gcry_cipher_ctl ((h), GCRYCTL_RESET, NULL, 0) /* Perform the OpenPGP sync operation if this is enabled for the cipher handle H. */ #define gcry_cipher_sync(h) gcry_cipher_ctl( (h), GCRYCTL_CFB_SYNC, NULL, 0) /* Enable or disable CTS in future calls to gcry_encrypt(). CBC mode only. */ #define gcry_cipher_cts(h,on) gcry_cipher_ctl( (h), GCRYCTL_SET_CBC_CTS, \ NULL, on ) #define gcry_cipher_set_sbox(h,oid) gcry_cipher_ctl( (h), GCRYCTL_SET_SBOX, \ (void *) oid, 0); /* Indicate to the encrypt and decrypt functions that the next call provides the final data. Only used with some modes. */ #define gcry_cipher_final(a) \ gcry_cipher_ctl ((a), GCRYCTL_FINALIZE, NULL, 0) /* Set counter for CTR mode. (CTR,CTRLEN) must denote a buffer of block size length, or (NULL,0) to set the CTR to the all-zero block. */ gpg_error_t gcry_cipher_setctr (gcry_cipher_hd_t hd, const void *ctr, size_t ctrlen); /* Retrieve the key length in bytes used with algorithm A. */ size_t gcry_cipher_get_algo_keylen (int algo); /* Retrieve the block length in bytes used with algorithm A. */ size_t gcry_cipher_get_algo_blklen (int algo); /* Return 0 if the algorithm A is available for use. */ #define gcry_cipher_test_algo(a) \ gcry_cipher_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /************************************ * * * Asymmetric Cipher Functions * * * ************************************/ /* The algorithms and their IDs we support. */ enum gcry_pk_algos { GCRY_PK_RSA = 1, /* RSA */ GCRY_PK_RSA_E = 2, /* (deprecated: use 1). */ GCRY_PK_RSA_S = 3, /* (deprecated: use 1). */ GCRY_PK_ELG_E = 16, /* (deprecated: use 20). */ GCRY_PK_DSA = 17, /* Digital Signature Algorithm. */ GCRY_PK_ECC = 18, /* Generic ECC. */ GCRY_PK_ELG = 20, /* Elgamal */ GCRY_PK_ECDSA = 301, /* (only for external use). */ GCRY_PK_ECDH = 302, /* (only for external use). */ GCRY_PK_EDDSA = 303 /* (only for external use). */ }; /* Flags describing usage capabilities of a PK algorithm. */ #define GCRY_PK_USAGE_SIGN 1 /* Good for signatures. */ #define GCRY_PK_USAGE_ENCR 2 /* Good for encryption. */ #define GCRY_PK_USAGE_CERT 4 /* Good to certify other keys. */ #define GCRY_PK_USAGE_AUTH 8 /* Good for authentication. */ #define GCRY_PK_USAGE_UNKN 128 /* Unknown usage flag. */ /* Modes used with gcry_pubkey_get_sexp. */ #define GCRY_PK_GET_PUBKEY 1 #define GCRY_PK_GET_SECKEY 2 /* Encrypt the DATA using the public key PKEY and store the result as a newly created S-expression at RESULT. */ gcry_error_t gcry_pk_encrypt (gcry_sexp_t *result, gcry_sexp_t data, gcry_sexp_t pkey); /* Decrypt the DATA using the private key SKEY and store the result as a newly created S-expression at RESULT. */ gcry_error_t gcry_pk_decrypt (gcry_sexp_t *result, gcry_sexp_t data, gcry_sexp_t skey); /* Sign the DATA using the private key SKEY and store the result as a newly created S-expression at RESULT. */ gcry_error_t gcry_pk_sign (gcry_sexp_t *result, gcry_sexp_t data, gcry_sexp_t skey); /* Check the signature SIGVAL on DATA using the public key PKEY. */ gcry_error_t gcry_pk_verify (gcry_sexp_t sigval, gcry_sexp_t data, gcry_sexp_t pkey); /* Check that private KEY is sane. */ gcry_error_t gcry_pk_testkey (gcry_sexp_t key); /* Generate a new key pair according to the parameters given in S_PARMS. The new key pair is returned in as an S-expression in R_KEY. */ gcry_error_t gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms); /* Catch all function for miscellaneous operations. */ gcry_error_t gcry_pk_ctl (int cmd, void *buffer, size_t buflen); /* Retrieve information about the public key algorithm ALGO. */ gcry_error_t gcry_pk_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Map the public key algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this functions returns "?". */ const char *gcry_pk_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm NAME to a public key algorithm Id. Return 0 if the algorithm name is not known. */ int gcry_pk_map_name (const char* name) _GCRY_GCC_ATTR_PURE; /* Return what is commonly referred as the key length for the given public or private KEY. */ unsigned int gcry_pk_get_nbits (gcry_sexp_t key) _GCRY_GCC_ATTR_PURE; /* Return the so called KEYGRIP which is the SHA-1 hash of the public key parameters expressed in a way depending on the algorithm. */ unsigned char *gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array); /* Return the name of the curve matching KEY. */ const char *gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits); /* Return an S-expression with the parameters of the named ECC curve NAME. ALGO must be set to an ECC algorithm. */ gcry_sexp_t gcry_pk_get_param (int algo, const char *name); /* Return 0 if the public key algorithm A is available for use. */ #define gcry_pk_test_algo(a) \ gcry_pk_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /* Return an S-expression representing the context CTX. */ gcry_error_t gcry_pubkey_get_sexp (gcry_sexp_t *r_sexp, int mode, gcry_ctx_t ctx); /************************************ * * * Cryptograhic Hash Functions * * * ************************************/ /* Algorithm IDs for the hash functions we know about. Not all of them are implemented. */ enum gcry_md_algos { GCRY_MD_NONE = 0, GCRY_MD_MD5 = 1, GCRY_MD_SHA1 = 2, GCRY_MD_RMD160 = 3, GCRY_MD_MD2 = 5, GCRY_MD_TIGER = 6, /* TIGER/192 as used by gpg <= 1.3.2. */ GCRY_MD_HAVAL = 7, /* HAVAL, 5 pass, 160 bit. */ GCRY_MD_SHA256 = 8, GCRY_MD_SHA384 = 9, GCRY_MD_SHA512 = 10, GCRY_MD_SHA224 = 11, GCRY_MD_MD4 = 301, GCRY_MD_CRC32 = 302, GCRY_MD_CRC32_RFC1510 = 303, GCRY_MD_CRC24_RFC2440 = 304, GCRY_MD_WHIRLPOOL = 305, GCRY_MD_TIGER1 = 306, /* TIGER fixed. */ GCRY_MD_TIGER2 = 307, /* TIGER2 variant. */ GCRY_MD_GOSTR3411_94 = 308, /* GOST R 34.11-94. */ GCRY_MD_STRIBOG256 = 309, /* GOST R 34.11-2012, 256 bit. */ GCRY_MD_STRIBOG512 = 310, /* GOST R 34.11-2012, 512 bit. */ GCRY_MD_GOSTR3411_CP = 311, /* GOST R 34.11-94 with CryptoPro-A S-Box. */ GCRY_MD_SHA3_224 = 312, GCRY_MD_SHA3_256 = 313, GCRY_MD_SHA3_384 = 314, GCRY_MD_SHA3_512 = 315, GCRY_MD_SHAKE128 = 316, GCRY_MD_SHAKE256 = 317, GCRY_MD_BLAKE2B_512 = 318, GCRY_MD_BLAKE2B_384 = 319, GCRY_MD_BLAKE2B_256 = 320, GCRY_MD_BLAKE2B_160 = 321, GCRY_MD_BLAKE2S_256 = 322, GCRY_MD_BLAKE2S_224 = 323, GCRY_MD_BLAKE2S_160 = 324, GCRY_MD_BLAKE2S_128 = 325 }; /* Flags used with the open function. */ enum gcry_md_flags { GCRY_MD_FLAG_SECURE = 1, /* Allocate all buffers in "secure" memory. */ GCRY_MD_FLAG_HMAC = 2, /* Make an HMAC out of this algorithm. */ GCRY_MD_FLAG_BUGEMU1 = 0x0100 }; /* (Forward declaration.) */ struct gcry_md_context; /* This object is used to hold a handle to a message digest object. This structure is private - only to be used by the public gcry_md_* macros. */ typedef struct gcry_md_handle { /* Actual context. */ struct gcry_md_context *ctx; /* Buffer management. */ int bufpos; int bufsize; unsigned char buf[1]; } *gcry_md_hd_t; /* Compatibility types, do not use them. */ #ifndef GCRYPT_NO_DEPRECATED typedef struct gcry_md_handle *GCRY_MD_HD _GCRY_GCC_ATTR_DEPRECATED; typedef struct gcry_md_handle *GcryMDHd _GCRY_GCC_ATTR_DEPRECATED; #endif /* Create a message digest object for algorithm ALGO. FLAGS may be given as an bitwise OR of the gcry_md_flags values. ALGO may be given as 0 if the algorithms to be used are later set using gcry_md_enable. */ gcry_error_t gcry_md_open (gcry_md_hd_t *h, int algo, unsigned int flags); /* Release the message digest object HD. */ void gcry_md_close (gcry_md_hd_t hd); /* Add the message digest algorithm ALGO to the digest object HD. */ gcry_error_t gcry_md_enable (gcry_md_hd_t hd, int algo); /* Create a new digest object as an exact copy of the object HD. */ gcry_error_t gcry_md_copy (gcry_md_hd_t *bhd, gcry_md_hd_t ahd); /* Reset the digest object HD to its initial state. */ void gcry_md_reset (gcry_md_hd_t hd); /* Perform various operations on the digest object HD. */ gcry_error_t gcry_md_ctl (gcry_md_hd_t hd, int cmd, void *buffer, size_t buflen); /* Pass LENGTH bytes of data in BUFFER to the digest object HD so that it can update the digest values. This is the actual hash function. */ void gcry_md_write (gcry_md_hd_t hd, const void *buffer, size_t length); /* Read out the final digest from HD return the digest value for algorithm ALGO. */ unsigned char *gcry_md_read (gcry_md_hd_t hd, int algo); /* Read more output from algorithm ALGO to BUFFER of size LENGTH from * digest object HD. Algorithm needs to be 'expendable-output function'. */ gpg_error_t gcry_md_extract (gcry_md_hd_t hd, int algo, void *buffer, size_t length); /* Convenience function to calculate the hash from the data in BUFFER of size LENGTH using the algorithm ALGO avoiding the creation of a hash object. The hash is returned in the caller provided buffer DIGEST which must be large enough to hold the digest of the given algorithm. */ void gcry_md_hash_buffer (int algo, void *digest, const void *buffer, size_t length); /* Convenience function to hash multiple buffers. */ gpg_error_t gcry_md_hash_buffers (int algo, unsigned int flags, void *digest, const gcry_buffer_t *iov, int iovcnt); /* Retrieve the algorithm used with HD. This does not work reliable if more than one algorithm is enabled in HD. */ int gcry_md_get_algo (gcry_md_hd_t hd); /* Retrieve the length in bytes of the digest yielded by algorithm ALGO. */ unsigned int gcry_md_get_algo_dlen (int algo); /* Return true if the the algorithm ALGO is enabled in the digest object A. */ int gcry_md_is_enabled (gcry_md_hd_t a, int algo); /* Return true if the digest object A is allocated in "secure" memory. */ int gcry_md_is_secure (gcry_md_hd_t a); /* Deprecated: Use gcry_md_is_enabled or gcry_md_is_secure. */ gcry_error_t gcry_md_info (gcry_md_hd_t h, int what, void *buffer, size_t *nbytes) _GCRY_ATTR_INTERNAL; /* Retrieve various information about the algorithm ALGO. */ gcry_error_t gcry_md_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Map the digest algorithm id ALGO to a string representation of the algorithm name. For unknown algorithms this function returns "?". */ const char *gcry_md_algo_name (int algo) _GCRY_GCC_ATTR_PURE; /* Map the algorithm NAME to a digest algorithm Id. Return 0 if the algorithm name is not known. */ int gcry_md_map_name (const char* name) _GCRY_GCC_ATTR_PURE; /* For use with the HMAC feature, the set MAC key to the KEY of KEYLEN bytes. */ gcry_error_t gcry_md_setkey (gcry_md_hd_t hd, const void *key, size_t keylen); /* Start or stop debugging for digest handle HD; i.e. create a file named dbgmd-. while hashing. If SUFFIX is NULL, debugging stops and the file will be closed. */ void gcry_md_debug (gcry_md_hd_t hd, const char *suffix); /* Update the hash(s) of H with the character C. This is a buffered version of the gcry_md_write function. */ #define gcry_md_putc(h,c) \ do { \ gcry_md_hd_t h__ = (h); \ if( (h__)->bufpos == (h__)->bufsize ) \ gcry_md_write( (h__), NULL, 0 ); \ (h__)->buf[(h__)->bufpos++] = (c) & 0xff; \ } while(0) /* Finalize the digest calculation. This is not really needed because gcry_md_read() does this implicitly. */ #define gcry_md_final(a) \ gcry_md_ctl ((a), GCRYCTL_FINALIZE, NULL, 0) /* Return 0 if the algorithm A is available for use. */ #define gcry_md_test_algo(a) \ gcry_md_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /* Return an DER encoded ASN.1 OID for the algorithm A in buffer B. N must point to size_t variable with the available size of buffer B. After return it will receive the actual size of the returned OID. */ #define gcry_md_get_asnoid(a,b,n) \ gcry_md_algo_info((a), GCRYCTL_GET_ASNOID, (b), (n)) /********************************************** * * * Message Authentication Code Functions * * * **********************************************/ /* The data object used to hold a handle to an encryption object. */ struct gcry_mac_handle; typedef struct gcry_mac_handle *gcry_mac_hd_t; /* Algorithm IDs for the hash functions we know about. Not all of them are implemented. */ enum gcry_mac_algos { GCRY_MAC_NONE = 0, GCRY_MAC_HMAC_SHA256 = 101, GCRY_MAC_HMAC_SHA224 = 102, GCRY_MAC_HMAC_SHA512 = 103, GCRY_MAC_HMAC_SHA384 = 104, GCRY_MAC_HMAC_SHA1 = 105, GCRY_MAC_HMAC_MD5 = 106, GCRY_MAC_HMAC_MD4 = 107, GCRY_MAC_HMAC_RMD160 = 108, GCRY_MAC_HMAC_TIGER1 = 109, /* The fixed TIGER variant */ GCRY_MAC_HMAC_WHIRLPOOL = 110, GCRY_MAC_HMAC_GOSTR3411_94 = 111, GCRY_MAC_HMAC_STRIBOG256 = 112, GCRY_MAC_HMAC_STRIBOG512 = 113, GCRY_MAC_HMAC_MD2 = 114, GCRY_MAC_HMAC_SHA3_224 = 115, GCRY_MAC_HMAC_SHA3_256 = 116, GCRY_MAC_HMAC_SHA3_384 = 117, GCRY_MAC_HMAC_SHA3_512 = 118, GCRY_MAC_CMAC_AES = 201, GCRY_MAC_CMAC_3DES = 202, GCRY_MAC_CMAC_CAMELLIA = 203, GCRY_MAC_CMAC_CAST5 = 204, GCRY_MAC_CMAC_BLOWFISH = 205, GCRY_MAC_CMAC_TWOFISH = 206, GCRY_MAC_CMAC_SERPENT = 207, GCRY_MAC_CMAC_SEED = 208, GCRY_MAC_CMAC_RFC2268 = 209, GCRY_MAC_CMAC_IDEA = 210, GCRY_MAC_CMAC_GOST28147 = 211, GCRY_MAC_GMAC_AES = 401, GCRY_MAC_GMAC_CAMELLIA = 402, GCRY_MAC_GMAC_TWOFISH = 403, GCRY_MAC_GMAC_SERPENT = 404, GCRY_MAC_GMAC_SEED = 405, GCRY_MAC_POLY1305 = 501, GCRY_MAC_POLY1305_AES = 502, GCRY_MAC_POLY1305_CAMELLIA = 503, GCRY_MAC_POLY1305_TWOFISH = 504, GCRY_MAC_POLY1305_SERPENT = 505, GCRY_MAC_POLY1305_SEED = 506 }; /* Flags used with the open function. */ enum gcry_mac_flags { GCRY_MAC_FLAG_SECURE = 1 /* Allocate all buffers in "secure" memory. */ }; /* Create a MAC handle for algorithm ALGO. FLAGS may be given as an bitwise OR of the gcry_mac_flags values. CTX maybe NULL or gcry_ctx_t object to be associated with HANDLE. */ gcry_error_t gcry_mac_open (gcry_mac_hd_t *handle, int algo, unsigned int flags, gcry_ctx_t ctx); /* Close the MAC handle H and release all resource. */ void gcry_mac_close (gcry_mac_hd_t h); /* Perform various operations on the MAC object H. */ gcry_error_t gcry_mac_ctl (gcry_mac_hd_t h, int cmd, void *buffer, size_t buflen); /* Retrieve various information about the MAC algorithm ALGO. */ gcry_error_t gcry_mac_algo_info (int algo, int what, void *buffer, size_t *nbytes); /* Set KEY of length KEYLEN bytes for the MAC handle HD. */ gcry_error_t gcry_mac_setkey (gcry_mac_hd_t hd, const void *key, size_t keylen); /* Set initialization vector IV of length IVLEN for the MAC handle HD. */ gcry_error_t gcry_mac_setiv (gcry_mac_hd_t hd, const void *iv, size_t ivlen); /* Pass LENGTH bytes of data in BUFFER to the MAC object HD so that it can update the MAC values. */ gcry_error_t gcry_mac_write (gcry_mac_hd_t hd, const void *buffer, size_t length); /* Read out the final authentication code from the MAC object HD to BUFFER. */ gcry_error_t gcry_mac_read (gcry_mac_hd_t hd, void *buffer, size_t *buflen); /* Verify the final authentication code from the MAC object HD with BUFFER. */ gcry_error_t gcry_mac_verify (gcry_mac_hd_t hd, const void *buffer, size_t buflen); /* Retrieve the algorithm used with MAC. */ int gcry_mac_get_algo (gcry_mac_hd_t hd); /* Retrieve the length in bytes of the MAC yielded by algorithm ALGO. */ unsigned int gcry_mac_get_algo_maclen (int algo); /* Retrieve the default key length in bytes used with algorithm A. */ unsigned int gcry_mac_get_algo_keylen (int algo); /* Map the MAC algorithm whose ID is contained in ALGORITHM to a string representation of the algorithm name. For unknown algorithm IDs this function returns "?". */ const char *gcry_mac_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE; /* Map the algorithm name NAME to an MAC algorithm ID. Return 0 if the algorithm name is not known. */ int gcry_mac_map_name (const char *name) _GCRY_GCC_ATTR_PURE; /* Reset the handle to the state after open/setkey. */ #define gcry_mac_reset(h) gcry_mac_ctl ((h), GCRYCTL_RESET, NULL, 0) /* Return 0 if the algorithm A is available for use. */ #define gcry_mac_test_algo(a) \ gcry_mac_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) /****************************** * * * Key Derivation Functions * * * ******************************/ /* Algorithm IDs for the KDFs. */ enum gcry_kdf_algos { GCRY_KDF_NONE = 0, GCRY_KDF_SIMPLE_S2K = 16, GCRY_KDF_SALTED_S2K = 17, GCRY_KDF_ITERSALTED_S2K = 19, GCRY_KDF_PBKDF1 = 33, GCRY_KDF_PBKDF2 = 34, GCRY_KDF_SCRYPT = 48 }; /* Derive a key from a passphrase. */ gpg_error_t gcry_kdf_derive (const void *passphrase, size_t passphraselen, int algo, int subalgo, const void *salt, size_t saltlen, unsigned long iterations, size_t keysize, void *keybuffer); /************************************ * * * Random Generating Functions * * * ************************************/ /* The type of the random number generator. */ enum gcry_rng_types { GCRY_RNG_TYPE_STANDARD = 1, /* The default CSPRNG generator. */ GCRY_RNG_TYPE_FIPS = 2, /* The FIPS X9.31 AES generator. */ GCRY_RNG_TYPE_SYSTEM = 3 /* The system's native generator. */ }; /* The possible values for the random quality. The rule of thumb is to use STRONG for session keys and VERY_STRONG for key material. WEAK is usually an alias for STRONG and should not be used anymore (except with gcry_mpi_randomize); use gcry_create_nonce instead. */ typedef enum gcry_random_level { GCRY_WEAK_RANDOM = 0, GCRY_STRONG_RANDOM = 1, GCRY_VERY_STRONG_RANDOM = 2 } gcry_random_level_t; /* Fill BUFFER with LENGTH bytes of random, using random numbers of quality LEVEL. */ void gcry_randomize (void *buffer, size_t length, enum gcry_random_level level); /* Add the external random from BUFFER with LENGTH bytes into the pool. QUALITY should either be -1 for unknown or in the range of 0 to 100 */ gcry_error_t gcry_random_add_bytes (const void *buffer, size_t length, int quality); /* If random numbers are used in an application, this macro should be called from time to time so that new stuff gets added to the internal pool of the RNG. */ #define gcry_fast_random_poll() gcry_control (GCRYCTL_FAST_POLL, NULL) /* Return NBYTES of allocated random using a random numbers of quality LEVEL. */ void *gcry_random_bytes (size_t nbytes, enum gcry_random_level level) _GCRY_GCC_ATTR_MALLOC; /* Return NBYTES of allocated random using a random numbers of quality LEVEL. The random numbers are created returned in "secure" memory. */ void *gcry_random_bytes_secure (size_t nbytes, enum gcry_random_level level) _GCRY_GCC_ATTR_MALLOC; /* Set the big integer W to a random value of NBITS using a random generator with quality LEVEL. Note that by using a level of GCRY_WEAK_RANDOM gcry_create_nonce is used internally. */ void gcry_mpi_randomize (gcry_mpi_t w, unsigned int nbits, enum gcry_random_level level); /* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ void gcry_create_nonce (void *buffer, size_t length); /*******************************/ /* */ /* Prime Number Functions */ /* */ /*******************************/ /* Mode values passed to a gcry_prime_check_func_t. */ #define GCRY_PRIME_CHECK_AT_FINISH 0 #define GCRY_PRIME_CHECK_AT_GOT_PRIME 1 #define GCRY_PRIME_CHECK_AT_MAYBE_PRIME 2 /* The function should return 1 if the operation shall continue, 0 to reject the prime candidate. */ typedef int (*gcry_prime_check_func_t) (void *arg, int mode, gcry_mpi_t candidate); /* Flags for gcry_prime_generate(): */ /* Allocate prime numbers and factors in secure memory. */ #define GCRY_PRIME_FLAG_SECRET (1 << 0) /* Make sure that at least one prime factor is of size `FACTOR_BITS'. */ #define GCRY_PRIME_FLAG_SPECIAL_FACTOR (1 << 1) /* Generate a new prime number of PRIME_BITS bits and store it in PRIME. If FACTOR_BITS is non-zero, one of the prime factors of (prime - 1) / 2 must be FACTOR_BITS bits long. If FACTORS is non-zero, allocate a new, NULL-terminated array holding the prime factors and store it in FACTORS. FLAGS might be used to influence the prime number generation process. */ gcry_error_t gcry_prime_generate (gcry_mpi_t *prime, unsigned int prime_bits, unsigned int factor_bits, gcry_mpi_t **factors, gcry_prime_check_func_t cb_func, void *cb_arg, gcry_random_level_t random_level, unsigned int flags); /* Find a generator for PRIME where the factorization of (prime-1) is in the NULL terminated array FACTORS. Return the generator as a newly allocated MPI in R_G. If START_G is not NULL, use this as the start for the search. */ gcry_error_t gcry_prime_group_generator (gcry_mpi_t *r_g, gcry_mpi_t prime, gcry_mpi_t *factors, gcry_mpi_t start_g); /* Convenience function to release the FACTORS array. */ void gcry_prime_release_factors (gcry_mpi_t *factors); /* Check whether the number X is prime. */ gcry_error_t gcry_prime_check (gcry_mpi_t x, unsigned int flags); /************************************ * * * Miscellaneous Stuff * * * ************************************/ /* Release the context object CTX. */ void gcry_ctx_release (gcry_ctx_t ctx); /* Log data using Libgcrypt's own log interface. */ void gcry_log_debug (const char *fmt, ...) _GCRY_GCC_ATTR_PRINTF(1,2); void gcry_log_debughex (const char *text, const void *buffer, size_t length); void gcry_log_debugmpi (const char *text, gcry_mpi_t mpi); void gcry_log_debugpnt (const char *text, gcry_mpi_point_t point, gcry_ctx_t ctx); void gcry_log_debugsxp (const char *text, gcry_sexp_t sexp); char *gcry_get_config (int mode, const char *what); /* Log levels used by the internal logging facility. */ enum gcry_log_levels { GCRY_LOG_CONT = 0, /* (Continue the last log line.) */ GCRY_LOG_INFO = 10, GCRY_LOG_WARN = 20, GCRY_LOG_ERROR = 30, GCRY_LOG_FATAL = 40, GCRY_LOG_BUG = 50, GCRY_LOG_DEBUG = 100 }; /* Type for progress handlers. */ typedef void (*gcry_handler_progress_t) (void *, const char *, int, int, int); /* Type for memory allocation handlers. */ typedef void *(*gcry_handler_alloc_t) (size_t n); /* Type for secure memory check handlers. */ typedef int (*gcry_handler_secure_check_t) (const void *); /* Type for memory reallocation handlers. */ typedef void *(*gcry_handler_realloc_t) (void *p, size_t n); /* Type for memory free handlers. */ typedef void (*gcry_handler_free_t) (void *); /* Type for out-of-memory handlers. */ typedef int (*gcry_handler_no_mem_t) (void *, size_t, unsigned int); /* Type for fatal error handlers. */ typedef void (*gcry_handler_error_t) (void *, int, const char *); /* Type for logging handlers. */ typedef void (*gcry_handler_log_t) (void *, int, const char *, va_list); /* Certain operations can provide progress information. This function is used to register a handler for retrieving these information. */ void gcry_set_progress_handler (gcry_handler_progress_t cb, void *cb_data); /* Register a custom memory allocation functions. */ void gcry_set_allocation_handler ( gcry_handler_alloc_t func_alloc, gcry_handler_alloc_t func_alloc_secure, gcry_handler_secure_check_t func_secure_check, gcry_handler_realloc_t func_realloc, gcry_handler_free_t func_free); /* Register a function used instead of the internal out of memory handler. */ void gcry_set_outofcore_handler (gcry_handler_no_mem_t h, void *opaque); /* Register a function used instead of the internal fatal error handler. */ void gcry_set_fatalerror_handler (gcry_handler_error_t fnc, void *opaque); /* Register a function used instead of the internal logging facility. */ void gcry_set_log_handler (gcry_handler_log_t f, void *opaque); /* Reserved for future use. */ void gcry_set_gettext_handler (const char *(*f)(const char*)); /* Libgcrypt uses its own memory allocation. It is important to use gcry_free () to release memory allocated by libgcrypt. */ void *gcry_malloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_calloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_malloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_calloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_realloc (void *a, size_t n); char *gcry_strdup (const char *string) _GCRY_GCC_ATTR_MALLOC; void *gcry_xmalloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_xcalloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_xmalloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; void *gcry_xcalloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; void *gcry_xrealloc (void *a, size_t n); char *gcry_xstrdup (const char * a) _GCRY_GCC_ATTR_MALLOC; void gcry_free (void *a); /* Return true if A is allocated in "secure" memory. */ int gcry_is_secure (const void *a) _GCRY_GCC_ATTR_PURE; /* Return true if Libgcrypt is in FIPS mode. */ #define gcry_fips_mode_active() !!gcry_control (GCRYCTL_FIPS_MODE_P, 0) #if 0 /* (Keep Emacsens' auto-indent happy.) */ { #endif #ifdef __cplusplus } #endif #endif /* _GCRYPT_H */ /* Local Variables: buffer-read-only: t End: */ linux/atm_he.h000064400000000626151027430560007320 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm_he.h */ #ifndef LINUX_ATM_HE_H #define LINUX_ATM_HE_H #include #define HE_GET_REG _IOW('a', ATMIOC_SARPRV, struct atmif_sioc) #define HE_REGTYPE_PCI 1 #define HE_REGTYPE_RCM 2 #define HE_REGTYPE_TCM 3 #define HE_REGTYPE_MBOX 4 struct he_ioctl_reg { unsigned addr, val; char type; }; #endif /* LINUX_ATM_HE_H */ linux/smc.h000064400000020501151027430560006637 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Shared Memory Communications over RDMA (SMC-R) and RoCE * * Definitions for generic netlink based configuration of an SMC-R PNET table * * Copyright IBM Corp. 2016 * * Author(s): Thomas Richter */ #ifndef _LINUX_SMC_H_ #define _LINUX_SMC_H_ /* Netlink SMC_PNETID attributes */ enum { SMC_PNETID_UNSPEC, SMC_PNETID_NAME, SMC_PNETID_ETHNAME, SMC_PNETID_IBNAME, SMC_PNETID_IBPORT, __SMC_PNETID_MAX, SMC_PNETID_MAX = __SMC_PNETID_MAX - 1 }; enum { /* SMC PNET Table commands */ SMC_PNETID_GET = 1, SMC_PNETID_ADD, SMC_PNETID_DEL, SMC_PNETID_FLUSH }; #define SMCR_GENL_FAMILY_NAME "SMC_PNETID" #define SMCR_GENL_FAMILY_VERSION 1 /* gennetlink interface to access non-socket information from SMC module */ #define SMC_GENL_FAMILY_NAME "SMC_GEN_NETLINK" #define SMC_GENL_FAMILY_VERSION 1 #define SMC_PCI_ID_STR_LEN 16 /* Max length of pci id string */ #define SMC_MAX_HOSTNAME_LEN 32 /* Max length of the hostname */ #define SMC_MAX_UEID 4 /* Max number of user EIDs */ #define SMC_MAX_EID_LEN 32 /* Max length of an EID */ /* SMC_GENL_FAMILY commands */ enum { SMC_NETLINK_GET_SYS_INFO = 1, SMC_NETLINK_GET_LGR_SMCR, SMC_NETLINK_GET_LINK_SMCR, SMC_NETLINK_GET_LGR_SMCD, SMC_NETLINK_GET_DEV_SMCD, SMC_NETLINK_GET_DEV_SMCR, SMC_NETLINK_GET_STATS, SMC_NETLINK_GET_FBACK_STATS, SMC_NETLINK_DUMP_UEID, SMC_NETLINK_ADD_UEID, SMC_NETLINK_REMOVE_UEID, SMC_NETLINK_FLUSH_UEID, SMC_NETLINK_DUMP_SEID, SMC_NETLINK_ENABLE_SEID, SMC_NETLINK_DISABLE_SEID, SMC_NETLINK_DUMP_HS_LIMITATION, SMC_NETLINK_ENABLE_HS_LIMITATION, SMC_NETLINK_DISABLE_HS_LIMITATION, }; /* SMC_GENL_FAMILY top level attributes */ enum { SMC_GEN_UNSPEC, SMC_GEN_SYS_INFO, /* nest */ SMC_GEN_LGR_SMCR, /* nest */ SMC_GEN_LINK_SMCR, /* nest */ SMC_GEN_LGR_SMCD, /* nest */ SMC_GEN_DEV_SMCD, /* nest */ SMC_GEN_DEV_SMCR, /* nest */ SMC_GEN_STATS, /* nest */ SMC_GEN_FBACK_STATS, /* nest */ __SMC_GEN_MAX, SMC_GEN_MAX = __SMC_GEN_MAX - 1 }; /* SMC_GEN_SYS_INFO attributes */ enum { SMC_NLA_SYS_UNSPEC, SMC_NLA_SYS_VER, /* u8 */ SMC_NLA_SYS_REL, /* u8 */ SMC_NLA_SYS_IS_ISM_V2, /* u8 */ SMC_NLA_SYS_LOCAL_HOST, /* string */ SMC_NLA_SYS_SEID, /* string */ SMC_NLA_SYS_IS_SMCR_V2, /* u8 */ __SMC_NLA_SYS_MAX, SMC_NLA_SYS_MAX = __SMC_NLA_SYS_MAX - 1 }; /* SMC_NLA_LGR_D_V2_COMMON and SMC_NLA_LGR_R_V2_COMMON nested attributes */ enum { SMC_NLA_LGR_V2_VER, /* u8 */ SMC_NLA_LGR_V2_REL, /* u8 */ SMC_NLA_LGR_V2_OS, /* u8 */ SMC_NLA_LGR_V2_NEG_EID, /* string */ SMC_NLA_LGR_V2_PEER_HOST, /* string */ __SMC_NLA_LGR_V2_MAX, SMC_NLA_LGR_V2_MAX = __SMC_NLA_LGR_V2_MAX - 1 }; /* SMC_NLA_LGR_R_V2 nested attributes */ enum { SMC_NLA_LGR_R_V2_UNSPEC, SMC_NLA_LGR_R_V2_DIRECT, /* u8 */ __SMC_NLA_LGR_R_V2_MAX, SMC_NLA_LGR_R_V2_MAX = __SMC_NLA_LGR_R_V2_MAX - 1 }; /* SMC_GEN_LGR_SMCR attributes */ enum { SMC_NLA_LGR_R_UNSPEC, SMC_NLA_LGR_R_ID, /* u32 */ SMC_NLA_LGR_R_ROLE, /* u8 */ SMC_NLA_LGR_R_TYPE, /* u8 */ SMC_NLA_LGR_R_PNETID, /* string */ SMC_NLA_LGR_R_VLAN_ID, /* u8 */ SMC_NLA_LGR_R_CONNS_NUM, /* u32 */ SMC_NLA_LGR_R_V2_COMMON, /* nest */ SMC_NLA_LGR_R_V2, /* nest */ SMC_NLA_LGR_R_NET_COOKIE, /* u64 */ SMC_NLA_LGR_R_PAD, /* flag */ SMC_NLA_LGR_R_BUF_TYPE, /* u8 */ __SMC_NLA_LGR_R_MAX, SMC_NLA_LGR_R_MAX = __SMC_NLA_LGR_R_MAX - 1 }; /* SMC_GEN_LINK_SMCR attributes */ enum { SMC_NLA_LINK_UNSPEC, SMC_NLA_LINK_ID, /* u8 */ SMC_NLA_LINK_IB_DEV, /* string */ SMC_NLA_LINK_IB_PORT, /* u8 */ SMC_NLA_LINK_GID, /* string */ SMC_NLA_LINK_PEER_GID, /* string */ SMC_NLA_LINK_CONN_CNT, /* u32 */ SMC_NLA_LINK_NET_DEV, /* u32 */ SMC_NLA_LINK_UID, /* u32 */ SMC_NLA_LINK_PEER_UID, /* u32 */ SMC_NLA_LINK_STATE, /* u32 */ __SMC_NLA_LINK_MAX, SMC_NLA_LINK_MAX = __SMC_NLA_LINK_MAX - 1 }; /* SMC_GEN_LGR_SMCD attributes */ enum { SMC_NLA_LGR_D_UNSPEC, SMC_NLA_LGR_D_ID, /* u32 */ SMC_NLA_LGR_D_GID, /* u64 */ SMC_NLA_LGR_D_PEER_GID, /* u64 */ SMC_NLA_LGR_D_VLAN_ID, /* u8 */ SMC_NLA_LGR_D_CONNS_NUM, /* u32 */ SMC_NLA_LGR_D_PNETID, /* string */ SMC_NLA_LGR_D_CHID, /* u16 */ SMC_NLA_LGR_D_PAD, /* flag */ SMC_NLA_LGR_D_V2_COMMON, /* nest */ __SMC_NLA_LGR_D_MAX, SMC_NLA_LGR_D_MAX = __SMC_NLA_LGR_D_MAX - 1 }; /* SMC_NLA_DEV_PORT nested attributes */ enum { SMC_NLA_DEV_PORT_UNSPEC, SMC_NLA_DEV_PORT_PNET_USR, /* u8 */ SMC_NLA_DEV_PORT_PNETID, /* string */ SMC_NLA_DEV_PORT_NETDEV, /* u32 */ SMC_NLA_DEV_PORT_STATE, /* u8 */ SMC_NLA_DEV_PORT_VALID, /* u8 */ SMC_NLA_DEV_PORT_LNK_CNT, /* u32 */ __SMC_NLA_DEV_PORT_MAX, SMC_NLA_DEV_PORT_MAX = __SMC_NLA_DEV_PORT_MAX - 1 }; /* SMC_GEN_DEV_SMCD and SMC_GEN_DEV_SMCR attributes */ enum { SMC_NLA_DEV_UNSPEC, SMC_NLA_DEV_USE_CNT, /* u32 */ SMC_NLA_DEV_IS_CRIT, /* u8 */ SMC_NLA_DEV_PCI_FID, /* u32 */ SMC_NLA_DEV_PCI_CHID, /* u16 */ SMC_NLA_DEV_PCI_VENDOR, /* u16 */ SMC_NLA_DEV_PCI_DEVICE, /* u16 */ SMC_NLA_DEV_PCI_ID, /* string */ SMC_NLA_DEV_PORT, /* nest */ SMC_NLA_DEV_PORT2, /* nest */ SMC_NLA_DEV_IB_NAME, /* string */ __SMC_NLA_DEV_MAX, SMC_NLA_DEV_MAX = __SMC_NLA_DEV_MAX - 1 }; /* SMC_NLA_STATS_T_TX(RX)_RMB_SIZE nested attributes */ /* SMC_NLA_STATS_TX(RX)PLOAD_SIZE nested attributes */ enum { SMC_NLA_STATS_PLOAD_PAD, SMC_NLA_STATS_PLOAD_8K, /* u64 */ SMC_NLA_STATS_PLOAD_16K, /* u64 */ SMC_NLA_STATS_PLOAD_32K, /* u64 */ SMC_NLA_STATS_PLOAD_64K, /* u64 */ SMC_NLA_STATS_PLOAD_128K, /* u64 */ SMC_NLA_STATS_PLOAD_256K, /* u64 */ SMC_NLA_STATS_PLOAD_512K, /* u64 */ SMC_NLA_STATS_PLOAD_1024K, /* u64 */ SMC_NLA_STATS_PLOAD_G_1024K, /* u64 */ __SMC_NLA_STATS_PLOAD_MAX, SMC_NLA_STATS_PLOAD_MAX = __SMC_NLA_STATS_PLOAD_MAX - 1 }; /* SMC_NLA_STATS_T_TX(RX)_RMB_STATS nested attributes */ enum { SMC_NLA_STATS_RMB_PAD, SMC_NLA_STATS_RMB_SIZE_SM_PEER_CNT, /* u64 */ SMC_NLA_STATS_RMB_SIZE_SM_CNT, /* u64 */ SMC_NLA_STATS_RMB_FULL_PEER_CNT, /* u64 */ SMC_NLA_STATS_RMB_FULL_CNT, /* u64 */ SMC_NLA_STATS_RMB_REUSE_CNT, /* u64 */ SMC_NLA_STATS_RMB_ALLOC_CNT, /* u64 */ SMC_NLA_STATS_RMB_DGRADE_CNT, /* u64 */ __SMC_NLA_STATS_RMB_MAX, SMC_NLA_STATS_RMB_MAX = __SMC_NLA_STATS_RMB_MAX - 1 }; /* SMC_NLA_STATS_SMCD_TECH and _SMCR_TECH nested attributes */ enum { SMC_NLA_STATS_T_PAD, SMC_NLA_STATS_T_TX_RMB_SIZE, /* nest */ SMC_NLA_STATS_T_RX_RMB_SIZE, /* nest */ SMC_NLA_STATS_T_TXPLOAD_SIZE, /* nest */ SMC_NLA_STATS_T_RXPLOAD_SIZE, /* nest */ SMC_NLA_STATS_T_TX_RMB_STATS, /* nest */ SMC_NLA_STATS_T_RX_RMB_STATS, /* nest */ SMC_NLA_STATS_T_CLNT_V1_SUCC, /* u64 */ SMC_NLA_STATS_T_CLNT_V2_SUCC, /* u64 */ SMC_NLA_STATS_T_SRV_V1_SUCC, /* u64 */ SMC_NLA_STATS_T_SRV_V2_SUCC, /* u64 */ SMC_NLA_STATS_T_SENDPAGE_CNT, /* u64 */ SMC_NLA_STATS_T_SPLICE_CNT, /* u64 */ SMC_NLA_STATS_T_CORK_CNT, /* u64 */ SMC_NLA_STATS_T_NDLY_CNT, /* u64 */ SMC_NLA_STATS_T_URG_DATA_CNT, /* u64 */ SMC_NLA_STATS_T_RX_BYTES, /* u64 */ SMC_NLA_STATS_T_TX_BYTES, /* u64 */ SMC_NLA_STATS_T_RX_CNT, /* u64 */ SMC_NLA_STATS_T_TX_CNT, /* u64 */ __SMC_NLA_STATS_T_MAX, SMC_NLA_STATS_T_MAX = __SMC_NLA_STATS_T_MAX - 1 }; /* SMC_GEN_STATS attributes */ enum { SMC_NLA_STATS_PAD, SMC_NLA_STATS_SMCD_TECH, /* nest */ SMC_NLA_STATS_SMCR_TECH, /* nest */ SMC_NLA_STATS_CLNT_HS_ERR_CNT, /* u64 */ SMC_NLA_STATS_SRV_HS_ERR_CNT, /* u64 */ __SMC_NLA_STATS_MAX, SMC_NLA_STATS_MAX = __SMC_NLA_STATS_MAX - 1 }; /* SMC_GEN_FBACK_STATS attributes */ enum { SMC_NLA_FBACK_STATS_PAD, SMC_NLA_FBACK_STATS_TYPE, /* u8 */ SMC_NLA_FBACK_STATS_SRV_CNT, /* u64 */ SMC_NLA_FBACK_STATS_CLNT_CNT, /* u64 */ SMC_NLA_FBACK_STATS_RSN_CODE, /* u32 */ SMC_NLA_FBACK_STATS_RSN_CNT, /* u16 */ __SMC_NLA_FBACK_STATS_MAX, SMC_NLA_FBACK_STATS_MAX = __SMC_NLA_FBACK_STATS_MAX - 1 }; /* SMC_NETLINK_UEID attributes */ enum { SMC_NLA_EID_TABLE_UNSPEC, SMC_NLA_EID_TABLE_ENTRY, /* string */ __SMC_NLA_EID_TABLE_MAX, SMC_NLA_EID_TABLE_MAX = __SMC_NLA_EID_TABLE_MAX - 1 }; /* SMC_NETLINK_SEID attributes */ enum { SMC_NLA_SEID_UNSPEC, SMC_NLA_SEID_ENTRY, /* string */ SMC_NLA_SEID_ENABLED, /* u8 */ __SMC_NLA_SEID_TABLE_MAX, SMC_NLA_SEID_TABLE_MAX = __SMC_NLA_SEID_TABLE_MAX - 1 }; /* SMC_NETLINK_HS_LIMITATION attributes */ enum { SMC_NLA_HS_LIMITATION_UNSPEC, SMC_NLA_HS_LIMITATION_ENABLED, /* u8 */ __SMC_NLA_HS_LIMITATION_MAX, SMC_NLA_HS_LIMITATION_MAX = __SMC_NLA_HS_LIMITATION_MAX - 1 }; /* SMC socket options */ #define SMC_LIMIT_HS 1 /* constraint on smc handshake */ #endif /* _LINUX_SMC_H */ linux/atmmpc.h000064400000010202151027430560007333 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ATMMPC_H_ #define _ATMMPC_H_ #include #include #include #include #define ATMMPC_CTRL _IO('a', ATMIOC_MPOA) #define ATMMPC_DATA _IO('a', ATMIOC_MPOA+1) #define MPC_SOCKET_INGRESS 1 #define MPC_SOCKET_EGRESS 2 struct atmmpc_ioc { int dev_num; __be32 ipaddr; /* the IP address of the shortcut */ int type; /* ingress or egress */ }; typedef struct in_ctrl_info { __u8 Last_NHRP_CIE_code; __u8 Last_Q2931_cause_value; __u8 eg_MPC_ATM_addr[ATM_ESA_LEN]; __be32 tag; __be32 in_dst_ip; /* IP address this ingress MPC sends packets to */ __u16 holding_time; __u32 request_id; } in_ctrl_info; typedef struct eg_ctrl_info { __u8 DLL_header[256]; __u8 DH_length; __be32 cache_id; __be32 tag; __be32 mps_ip; __be32 eg_dst_ip; /* IP address to which ingress MPC sends packets */ __u8 in_MPC_data_ATM_addr[ATM_ESA_LEN]; __u16 holding_time; } eg_ctrl_info; struct mpc_parameters { __u16 mpc_p1; /* Shortcut-Setup Frame Count */ __u16 mpc_p2; /* Shortcut-Setup Frame Time */ __u8 mpc_p3[8]; /* Flow-detection Protocols */ __u16 mpc_p4; /* MPC Initial Retry Time */ __u16 mpc_p5; /* MPC Retry Time Maximum */ __u16 mpc_p6; /* Hold Down Time */ } ; struct k_message { __u16 type; __be32 ip_mask; __u8 MPS_ctrl[ATM_ESA_LEN]; union { in_ctrl_info in_info; eg_ctrl_info eg_info; struct mpc_parameters params; } content; struct atm_qos qos; } __ATM_API_ALIGN; struct llc_snap_hdr { /* RFC 1483 LLC/SNAP encapsulation for routed IP PDUs */ __u8 dsap; /* Destination Service Access Point (0xAA) */ __u8 ssap; /* Source Service Access Point (0xAA) */ __u8 ui; /* Unnumbered Information (0x03) */ __u8 org[3]; /* Organizational identification (0x000000) */ __u8 type[2]; /* Ether type (for IP) (0x0800) */ }; /* TLVs this MPC recognizes */ #define TLV_MPOA_DEVICE_TYPE 0x00a03e2a /* MPOA device types in MPOA Device Type TLV */ #define NON_MPOA 0 #define MPS 1 #define MPC 2 #define MPS_AND_MPC 3 /* MPC parameter defaults */ #define MPC_P1 10 /* Shortcut-Setup Frame Count */ #define MPC_P2 1 /* Shortcut-Setup Frame Time */ #define MPC_P3 0 /* Flow-detection Protocols */ #define MPC_P4 5 /* MPC Initial Retry Time */ #define MPC_P5 40 /* MPC Retry Time Maximum */ #define MPC_P6 160 /* Hold Down Time */ #define HOLDING_TIME_DEFAULT 1200 /* same as MPS-p7 */ /* MPC constants */ #define MPC_C1 2 /* Retry Time Multiplier */ #define MPC_C2 60 /* Initial Keep-Alive Lifetime */ /* Message types - to MPOA daemon */ #define SND_MPOA_RES_RQST 201 #define SET_MPS_CTRL_ADDR 202 #define SND_MPOA_RES_RTRY 203 /* Different type in a retry due to req id */ #define STOP_KEEP_ALIVE_SM 204 #define EGRESS_ENTRY_REMOVED 205 #define SND_EGRESS_PURGE 206 #define DIE 207 /* tell the daemon to exit() */ #define DATA_PLANE_PURGE 208 /* Data plane purge because of egress cache hit miss or dead MPS */ #define OPEN_INGRESS_SVC 209 /* Message types - from MPOA daemon */ #define MPOA_TRIGGER_RCVD 101 #define MPOA_RES_REPLY_RCVD 102 #define INGRESS_PURGE_RCVD 103 #define EGRESS_PURGE_RCVD 104 #define MPS_DEATH 105 #define CACHE_IMPOS_RCVD 106 #define SET_MPC_CTRL_ADDR 107 /* Our MPC's control ATM address */ #define SET_MPS_MAC_ADDR 108 #define CLEAN_UP_AND_EXIT 109 #define SET_MPC_PARAMS 110 /* MPC configuration parameters */ /* Message types - bidirectional */ #define RELOAD 301 /* kill -HUP the daemon for reload */ #endif /* _ATMMPC_H_ */ linux/icmpv6.h000064400000007706151027430560007275 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_ICMPV6_H #define _LINUX_ICMPV6_H #include #include struct icmp6hdr { __u8 icmp6_type; __u8 icmp6_code; __sum16 icmp6_cksum; union { __be32 un_data32[1]; __be16 un_data16[2]; __u8 un_data8[4]; struct icmpv6_echo { __be16 identifier; __be16 sequence; } u_echo; struct icmpv6_nd_advt { #if defined(__LITTLE_ENDIAN_BITFIELD) __u32 reserved:5, override:1, solicited:1, router:1, reserved2:24; #elif defined(__BIG_ENDIAN_BITFIELD) __u32 router:1, solicited:1, override:1, reserved:29; #else #error "Please fix " #endif } u_nd_advt; struct icmpv6_nd_ra { __u8 hop_limit; #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 reserved:3, router_pref:2, home_agent:1, other:1, managed:1; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 managed:1, other:1, home_agent:1, router_pref:2, reserved:3; #else #error "Please fix " #endif __be16 rt_lifetime; } u_nd_ra; } icmp6_dataun; #define icmp6_identifier icmp6_dataun.u_echo.identifier #define icmp6_sequence icmp6_dataun.u_echo.sequence #define icmp6_pointer icmp6_dataun.un_data32[0] #define icmp6_mtu icmp6_dataun.un_data32[0] #define icmp6_unused icmp6_dataun.un_data32[0] #define icmp6_maxdelay icmp6_dataun.un_data16[0] #define icmp6_router icmp6_dataun.u_nd_advt.router #define icmp6_solicited icmp6_dataun.u_nd_advt.solicited #define icmp6_override icmp6_dataun.u_nd_advt.override #define icmp6_ndiscreserved icmp6_dataun.u_nd_advt.reserved #define icmp6_hop_limit icmp6_dataun.u_nd_ra.hop_limit #define icmp6_addrconf_managed icmp6_dataun.u_nd_ra.managed #define icmp6_addrconf_other icmp6_dataun.u_nd_ra.other #define icmp6_rt_lifetime icmp6_dataun.u_nd_ra.rt_lifetime #define icmp6_router_pref icmp6_dataun.u_nd_ra.router_pref }; #define ICMPV6_ROUTER_PREF_LOW 0x3 #define ICMPV6_ROUTER_PREF_MEDIUM 0x0 #define ICMPV6_ROUTER_PREF_HIGH 0x1 #define ICMPV6_ROUTER_PREF_INVALID 0x2 #define ICMPV6_DEST_UNREACH 1 #define ICMPV6_PKT_TOOBIG 2 #define ICMPV6_TIME_EXCEED 3 #define ICMPV6_PARAMPROB 4 #define ICMPV6_INFOMSG_MASK 0x80 #define ICMPV6_ECHO_REQUEST 128 #define ICMPV6_ECHO_REPLY 129 #define ICMPV6_MGM_QUERY 130 #define ICMPV6_MGM_REPORT 131 #define ICMPV6_MGM_REDUCTION 132 #define ICMPV6_NI_QUERY 139 #define ICMPV6_NI_REPLY 140 #define ICMPV6_MLD2_REPORT 143 #define ICMPV6_DHAAD_REQUEST 144 #define ICMPV6_DHAAD_REPLY 145 #define ICMPV6_MOBILE_PREFIX_SOL 146 #define ICMPV6_MOBILE_PREFIX_ADV 147 #define ICMPV6_MRDISC_ADV 151 /* * Codes for Destination Unreachable */ #define ICMPV6_NOROUTE 0 #define ICMPV6_ADM_PROHIBITED 1 #define ICMPV6_NOT_NEIGHBOUR 2 #define ICMPV6_ADDR_UNREACH 3 #define ICMPV6_PORT_UNREACH 4 #define ICMPV6_POLICY_FAIL 5 #define ICMPV6_REJECT_ROUTE 6 /* * Codes for Time Exceeded */ #define ICMPV6_EXC_HOPLIMIT 0 #define ICMPV6_EXC_FRAGTIME 1 /* * Codes for Parameter Problem */ #define ICMPV6_HDR_FIELD 0 #define ICMPV6_UNK_NEXTHDR 1 #define ICMPV6_UNK_OPTION 2 #define ICMPV6_HDR_INCOMP 3 /* * constants for (set|get)sockopt */ #define ICMPV6_FILTER 1 /* * ICMPV6 filter */ #define ICMPV6_FILTER_BLOCK 1 #define ICMPV6_FILTER_PASS 2 #define ICMPV6_FILTER_BLOCKOTHERS 3 #define ICMPV6_FILTER_PASSONLY 4 struct icmp6_filter { __u32 data[8]; }; /* * Definitions for MLDv2 */ #define MLD2_MODE_IS_INCLUDE 1 #define MLD2_MODE_IS_EXCLUDE 2 #define MLD2_CHANGE_TO_INCLUDE 3 #define MLD2_CHANGE_TO_EXCLUDE 4 #define MLD2_ALLOW_NEW_SOURCES 5 #define MLD2_BLOCK_OLD_SOURCES 6 #define MLD2_ALL_MCR_INIT { { { 0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0,0x16 } } } #endif /* _LINUX_ICMPV6_H */ linux/elf-em.h000064400000004213151027430560007224 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_ELF_EM_H #define _LINUX_ELF_EM_H /* These constants define the various ELF target machines */ #define EM_NONE 0 #define EM_M32 1 #define EM_SPARC 2 #define EM_386 3 #define EM_68K 4 #define EM_88K 5 #define EM_486 6 /* Perhaps disused */ #define EM_860 7 #define EM_MIPS 8 /* MIPS R3000 (officially, big-endian only) */ /* Next two are historical and binaries and modules of these types will be rejected by Linux. */ #define EM_MIPS_RS3_LE 10 /* MIPS R3000 little-endian */ #define EM_MIPS_RS4_BE 10 /* MIPS R4000 big-endian */ #define EM_PARISC 15 /* HPPA */ #define EM_SPARC32PLUS 18 /* Sun's "v8plus" */ #define EM_PPC 20 /* PowerPC */ #define EM_PPC64 21 /* PowerPC64 */ #define EM_SPU 23 /* Cell BE SPU */ #define EM_ARM 40 /* ARM 32 bit */ #define EM_SH 42 /* SuperH */ #define EM_SPARCV9 43 /* SPARC v9 64-bit */ #define EM_H8_300 46 /* Renesas H8/300 */ #define EM_IA_64 50 /* HP/Intel IA-64 */ #define EM_X86_64 62 /* AMD x86-64 */ #define EM_S390 22 /* IBM S/390 */ #define EM_CRIS 76 /* Axis Communications 32-bit embedded processor */ #define EM_M32R 88 /* Renesas M32R */ #define EM_MN10300 89 /* Panasonic/MEI MN10300, AM33 */ #define EM_OPENRISC 92 /* OpenRISC 32-bit embedded processor */ #define EM_BLACKFIN 106 /* ADI Blackfin Processor */ #define EM_ALTERA_NIOS2 113 /* Altera Nios II soft-core processor */ #define EM_TI_C6000 140 /* TI C6X DSPs */ #define EM_AARCH64 183 /* ARM 64 bit */ #define EM_TILEPRO 188 /* Tilera TILEPro */ #define EM_MICROBLAZE 189 /* Xilinx MicroBlaze */ #define EM_TILEGX 191 /* Tilera TILE-Gx */ #define EM_BPF 247 /* Linux BPF - in-kernel virtual machine */ #define EM_FRV 0x5441 /* Fujitsu FR-V */ /* * This is an interim value that we will use until the committee comes * up with a final number. */ #define EM_ALPHA 0x9026 /* Bogus old m32r magic number, used by old tools. */ #define EM_CYGNUS_M32R 0x9041 /* This is the old interim value for S/390 architecture */ #define EM_S390_OLD 0xA390 /* Also Panasonic/MEI MN10300, AM33 */ #define EM_CYGNUS_MN10300 0xbeef #endif /* _LINUX_ELF_EM_H */ linux/wanrouter.h000064400000000705151027430560010107 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * wanrouter.h Legacy declarations kept around until X25 is removed */ #ifndef _ROUTER_H #define _ROUTER_H /* 'state' defines */ enum wan_states { WAN_UNCONFIGURED, /* link/channel is not configured */ WAN_DISCONNECTED, /* link/channel is disconnected */ WAN_CONNECTING, /* connection is in progress */ WAN_CONNECTED /* link/channel is operational */ }; #endif /* _ROUTER_H */ linux/gameport.h000064400000001601151027430560007673 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 1999-2002 Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _GAMEPORT_H #define _GAMEPORT_H #define GAMEPORT_MODE_DISABLED 0 #define GAMEPORT_MODE_RAW 1 #define GAMEPORT_MODE_COOKED 2 #define GAMEPORT_ID_VENDOR_ANALOG 0x0001 #define GAMEPORT_ID_VENDOR_MADCATZ 0x0002 #define GAMEPORT_ID_VENDOR_LOGITECH 0x0003 #define GAMEPORT_ID_VENDOR_CREATIVE 0x0004 #define GAMEPORT_ID_VENDOR_GENIUS 0x0005 #define GAMEPORT_ID_VENDOR_INTERACT 0x0006 #define GAMEPORT_ID_VENDOR_MICROSOFT 0x0007 #define GAMEPORT_ID_VENDOR_THRUSTMASTER 0x0008 #define GAMEPORT_ID_VENDOR_GRAVIS 0x0009 #define GAMEPORT_ID_VENDOR_GUILLEMOT 0x000a #endif /* _GAMEPORT_H */ linux/raw.h000064400000000555151027430560006655 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_RAW_H #define __LINUX_RAW_H #include #define RAW_SETBIND _IO( 0xac, 0 ) #define RAW_GETBIND _IO( 0xac, 1 ) struct raw_config_request { int raw_minor; __u64 block_major; __u64 block_minor; }; #define MAX_RAW_MINORS CONFIG_MAX_RAW_DEVS #endif /* __LINUX_RAW_H */ linux/ioctl.h000064400000000243151027430560007170 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_IOCTL_H #define _LINUX_IOCTL_H #include #endif /* _LINUX_IOCTL_H */ linux/virtio_rng.h000064400000000411151027430560010235 0ustar00#ifndef _LINUX_VIRTIO_RNG_H #define _LINUX_VIRTIO_RNG_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. */ #include #include #endif /* _LINUX_VIRTIO_RNG_H */ linux/tee.h000064400000031555151027430560006645 0ustar00/* * Copyright (c) 2015-2016, Linaro Limited * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __TEE_H #define __TEE_H #include #include /* * This file describes the API provided by a TEE driver to user space. * * Each TEE driver defines a TEE specific protocol which is used for the * data passed back and forth using TEE_IOC_CMD. */ /* Helpers to make the ioctl defines */ #define TEE_IOC_MAGIC 0xa4 #define TEE_IOC_BASE 0 /* Flags relating to shared memory */ #define TEE_IOCTL_SHM_MAPPED 0x1 /* memory mapped in normal world */ #define TEE_IOCTL_SHM_DMA_BUF 0x2 /* dma-buf handle on shared memory */ #define TEE_MAX_ARG_SIZE 1024 #define TEE_GEN_CAP_GP (1 << 0)/* GlobalPlatform compliant TEE */ #define TEE_GEN_CAP_PRIVILEGED (1 << 1)/* Privileged device (for supplicant) */ #define TEE_GEN_CAP_REG_MEM (1 << 2)/* Supports registering shared memory */ #define TEE_GEN_CAP_MEMREF_NULL (1 << 3)/* NULL MemRef support */ #define TEE_MEMREF_NULL (__u64)(-1) /* NULL MemRef Buffer */ /* * TEE Implementation ID */ #define TEE_IMPL_ID_OPTEE 1 /* * OP-TEE specific capabilities */ #define TEE_OPTEE_CAP_TZ (1 << 0) /** * struct tee_ioctl_version_data - TEE version * @impl_id: [out] TEE implementation id * @impl_caps: [out] Implementation specific capabilities * @gen_caps: [out] Generic capabilities, defined by TEE_GEN_CAPS_* above * * Identifies the TEE implementation, @impl_id is one of TEE_IMPL_ID_* above. * @impl_caps is implementation specific, for example TEE_OPTEE_CAP_* * is valid when @impl_id == TEE_IMPL_ID_OPTEE. */ struct tee_ioctl_version_data { __u32 impl_id; __u32 impl_caps; __u32 gen_caps; }; /** * TEE_IOC_VERSION - query version of TEE * * Takes a tee_ioctl_version_data struct and returns with the TEE version * data filled in. */ #define TEE_IOC_VERSION _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 0, \ struct tee_ioctl_version_data) /** * struct tee_ioctl_shm_alloc_data - Shared memory allocate argument * @size: [in/out] Size of shared memory to allocate * @flags: [in/out] Flags to/from allocation. * @id: [out] Identifier of the shared memory * * The flags field should currently be zero as input. Updated by the call * with actual flags as defined by TEE_IOCTL_SHM_* above. * This structure is used as argument for TEE_IOC_SHM_ALLOC below. */ struct tee_ioctl_shm_alloc_data { __u64 size; __u32 flags; __s32 id; }; /** * TEE_IOC_SHM_ALLOC - allocate shared memory * * Allocates shared memory between the user space process and secure OS. * * Returns a file descriptor on success or < 0 on failure * * The returned file descriptor is used to map the shared memory into user * space. The shared memory is freed when the descriptor is closed and the * memory is unmapped. */ #define TEE_IOC_SHM_ALLOC _IOWR(TEE_IOC_MAGIC, TEE_IOC_BASE + 1, \ struct tee_ioctl_shm_alloc_data) /** * struct tee_ioctl_buf_data - Variable sized buffer * @buf_ptr: [in] A pointer to a buffer * @buf_len: [in] Length of the buffer above * * Used as argument for TEE_IOC_OPEN_SESSION, TEE_IOC_INVOKE, * TEE_IOC_SUPPL_RECV, and TEE_IOC_SUPPL_SEND below. */ struct tee_ioctl_buf_data { __u64 buf_ptr; __u64 buf_len; }; /* * Attributes for struct tee_ioctl_param, selects field in the union */ #define TEE_IOCTL_PARAM_ATTR_TYPE_NONE 0 /* parameter not used */ /* * These defines value parameters (struct tee_ioctl_param_value) */ #define TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT 1 #define TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT 2 #define TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT 3 /* input and output */ /* * These defines shared memory reference parameters (struct * tee_ioctl_param_memref) */ #define TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT 5 #define TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT 6 #define TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT 7 /* input and output */ /* * Mask for the type part of the attribute, leaves room for more types */ #define TEE_IOCTL_PARAM_ATTR_TYPE_MASK 0xff /* Meta parameter carrying extra information about the message. */ #define TEE_IOCTL_PARAM_ATTR_META 0x100 /* Mask of all known attr bits */ #define TEE_IOCTL_PARAM_ATTR_MASK \ (TEE_IOCTL_PARAM_ATTR_TYPE_MASK | TEE_IOCTL_PARAM_ATTR_META) /* * Matches TEEC_LOGIN_* in GP TEE Client API * Are only defined for GP compliant TEEs */ #define TEE_IOCTL_LOGIN_PUBLIC 0 #define TEE_IOCTL_LOGIN_USER 1 #define TEE_IOCTL_LOGIN_GROUP 2 #define TEE_IOCTL_LOGIN_APPLICATION 4 #define TEE_IOCTL_LOGIN_USER_APPLICATION 5 #define TEE_IOCTL_LOGIN_GROUP_APPLICATION 6 /** * struct tee_ioctl_param - parameter * @attr: attributes * @a: if a memref, offset into the shared memory object, else a value parameter * @b: if a memref, size of the buffer, else a value parameter * @c: if a memref, shared memory identifier, else a value parameter * * @attr & TEE_PARAM_ATTR_TYPE_MASK indicates if memref or value is used in * the union. TEE_PARAM_ATTR_TYPE_VALUE_* indicates value and * TEE_PARAM_ATTR_TYPE_MEMREF_* indicates memref. TEE_PARAM_ATTR_TYPE_NONE * indicates that none of the members are used. * * Shared memory is allocated with TEE_IOC_SHM_ALLOC which returns an * identifier representing the shared memory object. A memref can reference * a part of a shared memory by specifying an offset (@a) and size (@b) of * the object. To supply the entire shared memory object set the offset * (@a) to 0 and size (@b) to the previously returned size of the object. * * A client may need to present a NULL pointer in the argument * passed to a trusted application in the TEE. * This is also a requirement in GlobalPlatform Client API v1.0c * (section 3.2.5 memory references), which can be found at * http://www.globalplatform.org/specificationsdevice.asp * * If a NULL pointer is passed to a TA in the TEE, the (@c) * IOCTL parameters value must be set to TEE_MEMREF_NULL indicating a NULL * memory reference. */ struct tee_ioctl_param { __u64 attr; __u64 a; __u64 b; __u64 c; }; #define TEE_IOCTL_UUID_LEN 16 /** * struct tee_ioctl_open_session_arg - Open session argument * @uuid: [in] UUID of the Trusted Application * @clnt_uuid: [in] UUID of client * @clnt_login: [in] Login class of client, TEE_IOCTL_LOGIN_* above * @cancel_id: [in] Cancellation id, a unique value to identify this request * @session: [out] Session id * @ret: [out] return value * @ret_origin [out] origin of the return value * @num_params [in] number of parameters following this struct */ struct tee_ioctl_open_session_arg { __u8 uuid[TEE_IOCTL_UUID_LEN]; __u8 clnt_uuid[TEE_IOCTL_UUID_LEN]; __u32 clnt_login; __u32 cancel_id; __u32 session; __u32 ret; __u32 ret_origin; __u32 num_params; /* num_params tells the actual number of element in params */ struct tee_ioctl_param params[]; }; /** * TEE_IOC_OPEN_SESSION - opens a session to a Trusted Application * * Takes a struct tee_ioctl_buf_data which contains a struct * tee_ioctl_open_session_arg followed by any array of struct * tee_ioctl_param */ #define TEE_IOC_OPEN_SESSION _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 2, \ struct tee_ioctl_buf_data) /** * struct tee_ioctl_invoke_func_arg - Invokes a function in a Trusted * Application * @func: [in] Trusted Application function, specific to the TA * @session: [in] Session id * @cancel_id: [in] Cancellation id, a unique value to identify this request * @ret: [out] return value * @ret_origin [out] origin of the return value * @num_params [in] number of parameters following this struct */ struct tee_ioctl_invoke_arg { __u32 func; __u32 session; __u32 cancel_id; __u32 ret; __u32 ret_origin; __u32 num_params; /* num_params tells the actual number of element in params */ struct tee_ioctl_param params[]; }; /** * TEE_IOC_INVOKE - Invokes a function in a Trusted Application * * Takes a struct tee_ioctl_buf_data which contains a struct * tee_invoke_func_arg followed by any array of struct tee_param */ #define TEE_IOC_INVOKE _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 3, \ struct tee_ioctl_buf_data) /** * struct tee_ioctl_cancel_arg - Cancels an open session or invoke ioctl * @cancel_id: [in] Cancellation id, a unique value to identify this request * @session: [in] Session id, if the session is opened, else set to 0 */ struct tee_ioctl_cancel_arg { __u32 cancel_id; __u32 session; }; /** * TEE_IOC_CANCEL - Cancels an open session or invoke */ #define TEE_IOC_CANCEL _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 4, \ struct tee_ioctl_cancel_arg) /** * struct tee_ioctl_close_session_arg - Closes an open session * @session: [in] Session id */ struct tee_ioctl_close_session_arg { __u32 session; }; /** * TEE_IOC_CLOSE_SESSION - Closes a session */ #define TEE_IOC_CLOSE_SESSION _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 5, \ struct tee_ioctl_close_session_arg) /** * struct tee_iocl_supp_recv_arg - Receive a request for a supplicant function * @func: [in] supplicant function * @num_params [in/out] number of parameters following this struct * * @num_params is the number of params that tee-supplicant has room to * receive when input, @num_params is the number of actual params * tee-supplicant receives when output. */ struct tee_iocl_supp_recv_arg { __u32 func; __u32 num_params; /* num_params tells the actual number of element in params */ struct tee_ioctl_param params[]; }; /** * TEE_IOC_SUPPL_RECV - Receive a request for a supplicant function * * Takes a struct tee_ioctl_buf_data which contains a struct * tee_iocl_supp_recv_arg followed by any array of struct tee_param */ #define TEE_IOC_SUPPL_RECV _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 6, \ struct tee_ioctl_buf_data) /** * struct tee_iocl_supp_send_arg - Send a response to a received request * @ret: [out] return value * @num_params [in] number of parameters following this struct */ struct tee_iocl_supp_send_arg { __u32 ret; __u32 num_params; /* num_params tells the actual number of element in params */ struct tee_ioctl_param params[]; }; /** * TEE_IOC_SUPPL_SEND - Receive a request for a supplicant function * * Takes a struct tee_ioctl_buf_data which contains a struct * tee_iocl_supp_send_arg followed by any array of struct tee_param */ #define TEE_IOC_SUPPL_SEND _IOR(TEE_IOC_MAGIC, TEE_IOC_BASE + 7, \ struct tee_ioctl_buf_data) /** * struct tee_ioctl_shm_register_data - Shared memory register argument * @addr: [in] Start address of shared memory to register * @length: [in/out] Length of shared memory to register * @flags: [in/out] Flags to/from registration. * @id: [out] Identifier of the shared memory * * The flags field should currently be zero as input. Updated by the call * with actual flags as defined by TEE_IOCTL_SHM_* above. * This structure is used as argument for TEE_IOC_SHM_REGISTER below. */ struct tee_ioctl_shm_register_data { __u64 addr; __u64 length; __u32 flags; __s32 id; }; /** * TEE_IOC_SHM_REGISTER - Register shared memory argument * * Registers shared memory between the user space process and secure OS. * * Returns a file descriptor on success or < 0 on failure * * The shared memory is unregisterred when the descriptor is closed. */ #define TEE_IOC_SHM_REGISTER _IOWR(TEE_IOC_MAGIC, TEE_IOC_BASE + 9, \ struct tee_ioctl_shm_register_data) /* * Five syscalls are used when communicating with the TEE driver. * open(): opens the device associated with the driver * ioctl(): as described above operating on the file descriptor from open() * close(): two cases * - closes the device file descriptor * - closes a file descriptor connected to allocated shared memory * mmap(): maps shared memory into user space using information from struct * tee_ioctl_shm_alloc_data * munmap(): unmaps previously shared memory */ #endif /*__TEE_H*/ linux/pci_regs.h000064400000160743151027430560007665 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * PCI standard defines * Copyright 1994, Drew Eckhardt * Copyright 1997--1999 Martin Mares * * For more information, please consult the following manuals (look at * http://www.pcisig.com/ for how to get them): * * PCI BIOS Specification * PCI Local Bus Specification * PCI to PCI Bridge Specification * PCI System Design Guide * * For HyperTransport information, please consult the following manuals * from http://www.hypertransport.org : * * The HyperTransport I/O Link Specification */ #ifndef LINUX_PCI_REGS_H #define LINUX_PCI_REGS_H /* * Conventional PCI and PCI-X Mode 1 devices have 256 bytes of * configuration space. PCI-X Mode 2 and PCIe devices have 4096 bytes of * configuration space. */ #define PCI_CFG_SPACE_SIZE 256 #define PCI_CFG_SPACE_EXP_SIZE 4096 /* * Under PCI, each device has 256 bytes of configuration address space, * of which the first 64 bytes are standardized as follows: */ #define PCI_STD_HEADER_SIZEOF 64 #define PCI_STD_NUM_BARS 6 #define PCI_VENDOR_ID 0x00 /* 16 bits */ #define PCI_DEVICE_ID 0x02 /* 16 bits */ #define PCI_COMMAND 0x04 /* 16 bits */ #define PCI_COMMAND_IO 0x1 /* Enable response in I/O space */ #define PCI_COMMAND_MEMORY 0x2 /* Enable response in Memory space */ #define PCI_COMMAND_MASTER 0x4 /* Enable bus mastering */ #define PCI_COMMAND_SPECIAL 0x8 /* Enable response to special cycles */ #define PCI_COMMAND_INVALIDATE 0x10 /* Use memory write and invalidate */ #define PCI_COMMAND_VGA_PALETTE 0x20 /* Enable palette snooping */ #define PCI_COMMAND_PARITY 0x40 /* Enable parity checking */ #define PCI_COMMAND_WAIT 0x80 /* Enable address/data stepping */ #define PCI_COMMAND_SERR 0x100 /* Enable SERR */ #define PCI_COMMAND_FAST_BACK 0x200 /* Enable back-to-back writes */ #define PCI_COMMAND_INTX_DISABLE 0x400 /* INTx Emulation Disable */ #define PCI_STATUS 0x06 /* 16 bits */ #define PCI_STATUS_IMM_READY 0x01 /* Immediate Readiness */ #define PCI_STATUS_INTERRUPT 0x08 /* Interrupt status */ #define PCI_STATUS_CAP_LIST 0x10 /* Support Capability List */ #define PCI_STATUS_66MHZ 0x20 /* Support 66 MHz PCI 2.1 bus */ #define PCI_STATUS_UDF 0x40 /* Support User Definable Features [obsolete] */ #define PCI_STATUS_FAST_BACK 0x80 /* Accept fast-back to back */ #define PCI_STATUS_PARITY 0x100 /* Detected parity error */ #define PCI_STATUS_DEVSEL_MASK 0x600 /* DEVSEL timing */ #define PCI_STATUS_DEVSEL_FAST 0x000 #define PCI_STATUS_DEVSEL_MEDIUM 0x200 #define PCI_STATUS_DEVSEL_SLOW 0x400 #define PCI_STATUS_SIG_TARGET_ABORT 0x800 /* Set on target abort */ #define PCI_STATUS_REC_TARGET_ABORT 0x1000 /* Master ack of " */ #define PCI_STATUS_REC_MASTER_ABORT 0x2000 /* Set on master abort */ #define PCI_STATUS_SIG_SYSTEM_ERROR 0x4000 /* Set when we drive SERR */ #define PCI_STATUS_DETECTED_PARITY 0x8000 /* Set on parity error */ #define PCI_CLASS_REVISION 0x08 /* High 24 bits are class, low 8 revision */ #define PCI_REVISION_ID 0x08 /* Revision ID */ #define PCI_CLASS_PROG 0x09 /* Reg. Level Programming Interface */ #define PCI_CLASS_DEVICE 0x0a /* Device class */ #define PCI_CACHE_LINE_SIZE 0x0c /* 8 bits */ #define PCI_LATENCY_TIMER 0x0d /* 8 bits */ #define PCI_HEADER_TYPE 0x0e /* 8 bits */ #define PCI_HEADER_TYPE_MASK 0x7f #define PCI_HEADER_TYPE_NORMAL 0 #define PCI_HEADER_TYPE_BRIDGE 1 #define PCI_HEADER_TYPE_CARDBUS 2 #define PCI_BIST 0x0f /* 8 bits */ #define PCI_BIST_CODE_MASK 0x0f /* Return result */ #define PCI_BIST_START 0x40 /* 1 to start BIST, 2 secs or less */ #define PCI_BIST_CAPABLE 0x80 /* 1 if BIST capable */ /* * Base addresses specify locations in memory or I/O space. * Decoded size can be determined by writing a value of * 0xffffffff to the register, and reading it back. Only * 1 bits are decoded. */ #define PCI_BASE_ADDRESS_0 0x10 /* 32 bits */ #define PCI_BASE_ADDRESS_1 0x14 /* 32 bits [htype 0,1 only] */ #define PCI_BASE_ADDRESS_2 0x18 /* 32 bits [htype 0 only] */ #define PCI_BASE_ADDRESS_3 0x1c /* 32 bits */ #define PCI_BASE_ADDRESS_4 0x20 /* 32 bits */ #define PCI_BASE_ADDRESS_5 0x24 /* 32 bits */ #define PCI_BASE_ADDRESS_SPACE 0x01 /* 0 = memory, 1 = I/O */ #define PCI_BASE_ADDRESS_SPACE_IO 0x01 #define PCI_BASE_ADDRESS_SPACE_MEMORY 0x00 #define PCI_BASE_ADDRESS_MEM_TYPE_MASK 0x06 #define PCI_BASE_ADDRESS_MEM_TYPE_32 0x00 /* 32 bit address */ #define PCI_BASE_ADDRESS_MEM_TYPE_1M 0x02 /* Below 1M [obsolete] */ #define PCI_BASE_ADDRESS_MEM_TYPE_64 0x04 /* 64 bit address */ #define PCI_BASE_ADDRESS_MEM_PREFETCH 0x08 /* prefetchable? */ #define PCI_BASE_ADDRESS_MEM_MASK (~0x0fUL) #define PCI_BASE_ADDRESS_IO_MASK (~0x03UL) /* bit 1 is reserved if address_space = 1 */ /* Header type 0 (normal devices) */ #define PCI_CARDBUS_CIS 0x28 #define PCI_SUBSYSTEM_VENDOR_ID 0x2c #define PCI_SUBSYSTEM_ID 0x2e #define PCI_ROM_ADDRESS 0x30 /* Bits 31..11 are address, 10..1 reserved */ #define PCI_ROM_ADDRESS_ENABLE 0x01 #define PCI_ROM_ADDRESS_MASK (~0x7ffU) #define PCI_CAPABILITY_LIST 0x34 /* Offset of first capability list entry */ /* 0x35-0x3b are reserved */ #define PCI_INTERRUPT_LINE 0x3c /* 8 bits */ #define PCI_INTERRUPT_PIN 0x3d /* 8 bits */ #define PCI_MIN_GNT 0x3e /* 8 bits */ #define PCI_MAX_LAT 0x3f /* 8 bits */ /* Header type 1 (PCI-to-PCI bridges) */ #define PCI_PRIMARY_BUS 0x18 /* Primary bus number */ #define PCI_SECONDARY_BUS 0x19 /* Secondary bus number */ #define PCI_SUBORDINATE_BUS 0x1a /* Highest bus number behind the bridge */ #define PCI_SEC_LATENCY_TIMER 0x1b /* Latency timer for secondary interface */ #define PCI_IO_BASE 0x1c /* I/O range behind the bridge */ #define PCI_IO_LIMIT 0x1d #define PCI_IO_RANGE_TYPE_MASK 0x0fUL /* I/O bridging type */ #define PCI_IO_RANGE_TYPE_16 0x00 #define PCI_IO_RANGE_TYPE_32 0x01 #define PCI_IO_RANGE_MASK (~0x0fUL) /* Standard 4K I/O windows */ #define PCI_IO_1K_RANGE_MASK (~0x03UL) /* Intel 1K I/O windows */ #define PCI_SEC_STATUS 0x1e /* Secondary status register, only bit 14 used */ #define PCI_MEMORY_BASE 0x20 /* Memory range behind */ #define PCI_MEMORY_LIMIT 0x22 #define PCI_MEMORY_RANGE_TYPE_MASK 0x0fUL #define PCI_MEMORY_RANGE_MASK (~0x0fUL) #define PCI_PREF_MEMORY_BASE 0x24 /* Prefetchable memory range behind */ #define PCI_PREF_MEMORY_LIMIT 0x26 #define PCI_PREF_RANGE_TYPE_MASK 0x0fUL #define PCI_PREF_RANGE_TYPE_32 0x00 #define PCI_PREF_RANGE_TYPE_64 0x01 #define PCI_PREF_RANGE_MASK (~0x0fUL) #define PCI_PREF_BASE_UPPER32 0x28 /* Upper half of prefetchable memory range */ #define PCI_PREF_LIMIT_UPPER32 0x2c #define PCI_IO_BASE_UPPER16 0x30 /* Upper half of I/O addresses */ #define PCI_IO_LIMIT_UPPER16 0x32 /* 0x34 same as for htype 0 */ /* 0x35-0x3b is reserved */ #define PCI_ROM_ADDRESS1 0x38 /* Same as PCI_ROM_ADDRESS, but for htype 1 */ /* 0x3c-0x3d are same as for htype 0 */ #define PCI_BRIDGE_CONTROL 0x3e #define PCI_BRIDGE_CTL_PARITY 0x01 /* Enable parity detection on secondary interface */ #define PCI_BRIDGE_CTL_SERR 0x02 /* The same for SERR forwarding */ #define PCI_BRIDGE_CTL_ISA 0x04 /* Enable ISA mode */ #define PCI_BRIDGE_CTL_VGA 0x08 /* Forward VGA addresses */ #define PCI_BRIDGE_CTL_MASTER_ABORT 0x20 /* Report master aborts */ #define PCI_BRIDGE_CTL_BUS_RESET 0x40 /* Secondary bus reset */ #define PCI_BRIDGE_CTL_FAST_BACK 0x80 /* Fast Back2Back enabled on secondary interface */ /* Header type 2 (CardBus bridges) */ #define PCI_CB_CAPABILITY_LIST 0x14 /* 0x15 reserved */ #define PCI_CB_SEC_STATUS 0x16 /* Secondary status */ #define PCI_CB_PRIMARY_BUS 0x18 /* PCI bus number */ #define PCI_CB_CARD_BUS 0x19 /* CardBus bus number */ #define PCI_CB_SUBORDINATE_BUS 0x1a /* Subordinate bus number */ #define PCI_CB_LATENCY_TIMER 0x1b /* CardBus latency timer */ #define PCI_CB_MEMORY_BASE_0 0x1c #define PCI_CB_MEMORY_LIMIT_0 0x20 #define PCI_CB_MEMORY_BASE_1 0x24 #define PCI_CB_MEMORY_LIMIT_1 0x28 #define PCI_CB_IO_BASE_0 0x2c #define PCI_CB_IO_BASE_0_HI 0x2e #define PCI_CB_IO_LIMIT_0 0x30 #define PCI_CB_IO_LIMIT_0_HI 0x32 #define PCI_CB_IO_BASE_1 0x34 #define PCI_CB_IO_BASE_1_HI 0x36 #define PCI_CB_IO_LIMIT_1 0x38 #define PCI_CB_IO_LIMIT_1_HI 0x3a #define PCI_CB_IO_RANGE_MASK (~0x03UL) /* 0x3c-0x3d are same as for htype 0 */ #define PCI_CB_BRIDGE_CONTROL 0x3e #define PCI_CB_BRIDGE_CTL_PARITY 0x01 /* Similar to standard bridge control register */ #define PCI_CB_BRIDGE_CTL_SERR 0x02 #define PCI_CB_BRIDGE_CTL_ISA 0x04 #define PCI_CB_BRIDGE_CTL_VGA 0x08 #define PCI_CB_BRIDGE_CTL_MASTER_ABORT 0x20 #define PCI_CB_BRIDGE_CTL_CB_RESET 0x40 /* CardBus reset */ #define PCI_CB_BRIDGE_CTL_16BIT_INT 0x80 /* Enable interrupt for 16-bit cards */ #define PCI_CB_BRIDGE_CTL_PREFETCH_MEM0 0x100 /* Prefetch enable for both memory regions */ #define PCI_CB_BRIDGE_CTL_PREFETCH_MEM1 0x200 #define PCI_CB_BRIDGE_CTL_POST_WRITES 0x400 #define PCI_CB_SUBSYSTEM_VENDOR_ID 0x40 #define PCI_CB_SUBSYSTEM_ID 0x42 #define PCI_CB_LEGACY_MODE_BASE 0x44 /* 16-bit PC Card legacy mode base address (ExCa) */ /* 0x48-0x7f reserved */ /* Capability lists */ #define PCI_CAP_LIST_ID 0 /* Capability ID */ #define PCI_CAP_ID_PM 0x01 /* Power Management */ #define PCI_CAP_ID_AGP 0x02 /* Accelerated Graphics Port */ #define PCI_CAP_ID_VPD 0x03 /* Vital Product Data */ #define PCI_CAP_ID_SLOTID 0x04 /* Slot Identification */ #define PCI_CAP_ID_MSI 0x05 /* Message Signalled Interrupts */ #define PCI_CAP_ID_CHSWP 0x06 /* CompactPCI HotSwap */ #define PCI_CAP_ID_PCIX 0x07 /* PCI-X */ #define PCI_CAP_ID_HT 0x08 /* HyperTransport */ #define PCI_CAP_ID_VNDR 0x09 /* Vendor-Specific */ #define PCI_CAP_ID_DBG 0x0A /* Debug port */ #define PCI_CAP_ID_CCRC 0x0B /* CompactPCI Central Resource Control */ #define PCI_CAP_ID_SHPC 0x0C /* PCI Standard Hot-Plug Controller */ #define PCI_CAP_ID_SSVID 0x0D /* Bridge subsystem vendor/device ID */ #define PCI_CAP_ID_AGP3 0x0E /* AGP Target PCI-PCI bridge */ #define PCI_CAP_ID_SECDEV 0x0F /* Secure Device */ #define PCI_CAP_ID_EXP 0x10 /* PCI Express */ #define PCI_CAP_ID_MSIX 0x11 /* MSI-X */ #define PCI_CAP_ID_SATA 0x12 /* SATA Data/Index Conf. */ #define PCI_CAP_ID_AF 0x13 /* PCI Advanced Features */ #define PCI_CAP_ID_EA 0x14 /* PCI Enhanced Allocation */ #define PCI_CAP_ID_MAX PCI_CAP_ID_EA #define PCI_CAP_LIST_NEXT 1 /* Next capability in the list */ #define PCI_CAP_FLAGS 2 /* Capability defined flags (16 bits) */ #define PCI_CAP_SIZEOF 4 /* Power Management Registers */ #define PCI_PM_PMC 2 /* PM Capabilities Register */ #define PCI_PM_CAP_VER_MASK 0x0007 /* Version */ #define PCI_PM_CAP_PME_CLOCK 0x0008 /* PME clock required */ #define PCI_PM_CAP_RESERVED 0x0010 /* Reserved field */ #define PCI_PM_CAP_DSI 0x0020 /* Device specific initialization */ #define PCI_PM_CAP_AUX_POWER 0x01C0 /* Auxiliary power support mask */ #define PCI_PM_CAP_D1 0x0200 /* D1 power state support */ #define PCI_PM_CAP_D2 0x0400 /* D2 power state support */ #define PCI_PM_CAP_PME 0x0800 /* PME pin supported */ #define PCI_PM_CAP_PME_MASK 0xF800 /* PME Mask of all supported states */ #define PCI_PM_CAP_PME_D0 0x0800 /* PME# from D0 */ #define PCI_PM_CAP_PME_D1 0x1000 /* PME# from D1 */ #define PCI_PM_CAP_PME_D2 0x2000 /* PME# from D2 */ #define PCI_PM_CAP_PME_D3 0x4000 /* PME# from D3 (hot) */ #define PCI_PM_CAP_PME_D3cold 0x8000 /* PME# from D3 (cold) */ #define PCI_PM_CAP_PME_SHIFT 11 /* Start of the PME Mask in PMC */ #define PCI_PM_CTRL 4 /* PM control and status register */ #define PCI_PM_CTRL_STATE_MASK 0x0003 /* Current power state (D0 to D3) */ #define PCI_PM_CTRL_NO_SOFT_RESET 0x0008 /* No reset for D3hot->D0 */ #define PCI_PM_CTRL_PME_ENABLE 0x0100 /* PME pin enable */ #define PCI_PM_CTRL_DATA_SEL_MASK 0x1e00 /* Data select (??) */ #define PCI_PM_CTRL_DATA_SCALE_MASK 0x6000 /* Data scale (??) */ #define PCI_PM_CTRL_PME_STATUS 0x8000 /* PME pin status */ #define PCI_PM_PPB_EXTENSIONS 6 /* PPB support extensions (??) */ #define PCI_PM_PPB_B2_B3 0x40 /* Stop clock when in D3hot (??) */ #define PCI_PM_BPCC_ENABLE 0x80 /* Bus power/clock control enable (??) */ #define PCI_PM_DATA_REGISTER 7 /* (??) */ #define PCI_PM_SIZEOF 8 /* AGP registers */ #define PCI_AGP_VERSION 2 /* BCD version number */ #define PCI_AGP_RFU 3 /* Rest of capability flags */ #define PCI_AGP_STATUS 4 /* Status register */ #define PCI_AGP_STATUS_RQ_MASK 0xff000000 /* Maximum number of requests - 1 */ #define PCI_AGP_STATUS_SBA 0x0200 /* Sideband addressing supported */ #define PCI_AGP_STATUS_64BIT 0x0020 /* 64-bit addressing supported */ #define PCI_AGP_STATUS_FW 0x0010 /* FW transfers supported */ #define PCI_AGP_STATUS_RATE4 0x0004 /* 4x transfer rate supported */ #define PCI_AGP_STATUS_RATE2 0x0002 /* 2x transfer rate supported */ #define PCI_AGP_STATUS_RATE1 0x0001 /* 1x transfer rate supported */ #define PCI_AGP_COMMAND 8 /* Control register */ #define PCI_AGP_COMMAND_RQ_MASK 0xff000000 /* Master: Maximum number of requests */ #define PCI_AGP_COMMAND_SBA 0x0200 /* Sideband addressing enabled */ #define PCI_AGP_COMMAND_AGP 0x0100 /* Allow processing of AGP transactions */ #define PCI_AGP_COMMAND_64BIT 0x0020 /* Allow processing of 64-bit addresses */ #define PCI_AGP_COMMAND_FW 0x0010 /* Force FW transfers */ #define PCI_AGP_COMMAND_RATE4 0x0004 /* Use 4x rate */ #define PCI_AGP_COMMAND_RATE2 0x0002 /* Use 2x rate */ #define PCI_AGP_COMMAND_RATE1 0x0001 /* Use 1x rate */ #define PCI_AGP_SIZEOF 12 /* Vital Product Data */ #define PCI_VPD_ADDR 2 /* Address to access (15 bits!) */ #define PCI_VPD_ADDR_MASK 0x7fff /* Address mask */ #define PCI_VPD_ADDR_F 0x8000 /* Write 0, 1 indicates completion */ #define PCI_VPD_DATA 4 /* 32-bits of data returned here */ #define PCI_CAP_VPD_SIZEOF 8 /* Slot Identification */ #define PCI_SID_ESR 2 /* Expansion Slot Register */ #define PCI_SID_ESR_NSLOTS 0x1f /* Number of expansion slots available */ #define PCI_SID_ESR_FIC 0x20 /* First In Chassis Flag */ #define PCI_SID_CHASSIS_NR 3 /* Chassis Number */ /* Message Signalled Interrupt registers */ #define PCI_MSI_FLAGS 2 /* Message Control */ #define PCI_MSI_FLAGS_ENABLE 0x0001 /* MSI feature enabled */ #define PCI_MSI_FLAGS_QMASK 0x000e /* Maximum queue size available */ #define PCI_MSI_FLAGS_QSIZE 0x0070 /* Message queue size configured */ #define PCI_MSI_FLAGS_64BIT 0x0080 /* 64-bit addresses allowed */ #define PCI_MSI_FLAGS_MASKBIT 0x0100 /* Per-vector masking capable */ #define PCI_MSI_RFU 3 /* Rest of capability flags */ #define PCI_MSI_ADDRESS_LO 4 /* Lower 32 bits */ #define PCI_MSI_ADDRESS_HI 8 /* Upper 32 bits (if PCI_MSI_FLAGS_64BIT set) */ #define PCI_MSI_DATA_32 8 /* 16 bits of data for 32-bit devices */ #define PCI_MSI_MASK_32 12 /* Mask bits register for 32-bit devices */ #define PCI_MSI_PENDING_32 16 /* Pending intrs for 32-bit devices */ #define PCI_MSI_DATA_64 12 /* 16 bits of data for 64-bit devices */ #define PCI_MSI_MASK_64 16 /* Mask bits register for 64-bit devices */ #define PCI_MSI_PENDING_64 20 /* Pending intrs for 64-bit devices */ /* MSI-X registers (in MSI-X capability) */ #define PCI_MSIX_FLAGS 2 /* Message Control */ #define PCI_MSIX_FLAGS_QSIZE 0x07FF /* Table size */ #define PCI_MSIX_FLAGS_MASKALL 0x4000 /* Mask all vectors for this function */ #define PCI_MSIX_FLAGS_ENABLE 0x8000 /* MSI-X enable */ #define PCI_MSIX_TABLE 4 /* Table offset */ #define PCI_MSIX_TABLE_BIR 0x00000007 /* BAR index */ #define PCI_MSIX_TABLE_OFFSET 0xfffffff8 /* Offset into specified BAR */ #define PCI_MSIX_PBA 8 /* Pending Bit Array offset */ #define PCI_MSIX_PBA_BIR 0x00000007 /* BAR index */ #define PCI_MSIX_PBA_OFFSET 0xfffffff8 /* Offset into specified BAR */ #define PCI_MSIX_FLAGS_BIRMASK PCI_MSIX_PBA_BIR /* deprecated */ #define PCI_CAP_MSIX_SIZEOF 12 /* size of MSIX registers */ /* MSI-X Table entry format (in memory mapped by a BAR) */ #define PCI_MSIX_ENTRY_SIZE 16 #define PCI_MSIX_ENTRY_LOWER_ADDR 0 /* Message Address */ #define PCI_MSIX_ENTRY_UPPER_ADDR 4 /* Message Upper Address */ #define PCI_MSIX_ENTRY_DATA 8 /* Message Data */ #define PCI_MSIX_ENTRY_VECTOR_CTRL 12 /* Vector Control */ #define PCI_MSIX_ENTRY_CTRL_MASKBIT 0x00000001 /* CompactPCI Hotswap Register */ #define PCI_CHSWP_CSR 2 /* Control and Status Register */ #define PCI_CHSWP_DHA 0x01 /* Device Hiding Arm */ #define PCI_CHSWP_EIM 0x02 /* ENUM# Signal Mask */ #define PCI_CHSWP_PIE 0x04 /* Pending Insert or Extract */ #define PCI_CHSWP_LOO 0x08 /* LED On / Off */ #define PCI_CHSWP_PI 0x30 /* Programming Interface */ #define PCI_CHSWP_EXT 0x40 /* ENUM# status - extraction */ #define PCI_CHSWP_INS 0x80 /* ENUM# status - insertion */ /* PCI Advanced Feature registers */ #define PCI_AF_LENGTH 2 #define PCI_AF_CAP 3 #define PCI_AF_CAP_TP 0x01 #define PCI_AF_CAP_FLR 0x02 #define PCI_AF_CTRL 4 #define PCI_AF_CTRL_FLR 0x01 #define PCI_AF_STATUS 5 #define PCI_AF_STATUS_TP 0x01 #define PCI_CAP_AF_SIZEOF 6 /* size of AF registers */ /* PCI Enhanced Allocation registers */ #define PCI_EA_NUM_ENT 2 /* Number of Capability Entries */ #define PCI_EA_NUM_ENT_MASK 0x3f /* Num Entries Mask */ #define PCI_EA_FIRST_ENT 4 /* First EA Entry in List */ #define PCI_EA_FIRST_ENT_BRIDGE 8 /* First EA Entry for Bridges */ #define PCI_EA_ES 0x00000007 /* Entry Size */ #define PCI_EA_BEI 0x000000f0 /* BAR Equivalent Indicator */ /* EA fixed Secondary and Subordinate bus numbers for Bridge */ #define PCI_EA_SEC_BUS_MASK 0xff #define PCI_EA_SUB_BUS_MASK 0xff00 #define PCI_EA_SUB_BUS_SHIFT 8 /* 0-5 map to BARs 0-5 respectively */ #define PCI_EA_BEI_BAR0 0 #define PCI_EA_BEI_BAR5 5 #define PCI_EA_BEI_BRIDGE 6 /* Resource behind bridge */ #define PCI_EA_BEI_ENI 7 /* Equivalent Not Indicated */ #define PCI_EA_BEI_ROM 8 /* Expansion ROM */ /* 9-14 map to VF BARs 0-5 respectively */ #define PCI_EA_BEI_VF_BAR0 9 #define PCI_EA_BEI_VF_BAR5 14 #define PCI_EA_BEI_RESERVED 15 /* Reserved - Treat like ENI */ #define PCI_EA_PP 0x0000ff00 /* Primary Properties */ #define PCI_EA_SP 0x00ff0000 /* Secondary Properties */ #define PCI_EA_P_MEM 0x00 /* Non-Prefetch Memory */ #define PCI_EA_P_MEM_PREFETCH 0x01 /* Prefetchable Memory */ #define PCI_EA_P_IO 0x02 /* I/O Space */ #define PCI_EA_P_VF_MEM_PREFETCH 0x03 /* VF Prefetchable Memory */ #define PCI_EA_P_VF_MEM 0x04 /* VF Non-Prefetch Memory */ #define PCI_EA_P_BRIDGE_MEM 0x05 /* Bridge Non-Prefetch Memory */ #define PCI_EA_P_BRIDGE_MEM_PREFETCH 0x06 /* Bridge Prefetchable Memory */ #define PCI_EA_P_BRIDGE_IO 0x07 /* Bridge I/O Space */ /* 0x08-0xfc reserved */ #define PCI_EA_P_MEM_RESERVED 0xfd /* Reserved Memory */ #define PCI_EA_P_IO_RESERVED 0xfe /* Reserved I/O Space */ #define PCI_EA_P_UNAVAILABLE 0xff /* Entry Unavailable */ #define PCI_EA_WRITABLE 0x40000000 /* Writable: 1 = RW, 0 = HwInit */ #define PCI_EA_ENABLE 0x80000000 /* Enable for this entry */ #define PCI_EA_BASE 4 /* Base Address Offset */ #define PCI_EA_MAX_OFFSET 8 /* MaxOffset (resource length) */ /* bit 0 is reserved */ #define PCI_EA_IS_64 0x00000002 /* 64-bit field flag */ #define PCI_EA_FIELD_MASK 0xfffffffc /* For Base & Max Offset */ /* PCI-X registers (Type 0 (non-bridge) devices) */ #define PCI_X_CMD 2 /* Modes & Features */ #define PCI_X_CMD_DPERR_E 0x0001 /* Data Parity Error Recovery Enable */ #define PCI_X_CMD_ERO 0x0002 /* Enable Relaxed Ordering */ #define PCI_X_CMD_READ_512 0x0000 /* 512 byte maximum read byte count */ #define PCI_X_CMD_READ_1K 0x0004 /* 1Kbyte maximum read byte count */ #define PCI_X_CMD_READ_2K 0x0008 /* 2Kbyte maximum read byte count */ #define PCI_X_CMD_READ_4K 0x000c /* 4Kbyte maximum read byte count */ #define PCI_X_CMD_MAX_READ 0x000c /* Max Memory Read Byte Count */ /* Max # of outstanding split transactions */ #define PCI_X_CMD_SPLIT_1 0x0000 /* Max 1 */ #define PCI_X_CMD_SPLIT_2 0x0010 /* Max 2 */ #define PCI_X_CMD_SPLIT_3 0x0020 /* Max 3 */ #define PCI_X_CMD_SPLIT_4 0x0030 /* Max 4 */ #define PCI_X_CMD_SPLIT_8 0x0040 /* Max 8 */ #define PCI_X_CMD_SPLIT_12 0x0050 /* Max 12 */ #define PCI_X_CMD_SPLIT_16 0x0060 /* Max 16 */ #define PCI_X_CMD_SPLIT_32 0x0070 /* Max 32 */ #define PCI_X_CMD_MAX_SPLIT 0x0070 /* Max Outstanding Split Transactions */ #define PCI_X_CMD_VERSION(x) (((x) >> 12) & 3) /* Version */ #define PCI_X_STATUS 4 /* PCI-X capabilities */ #define PCI_X_STATUS_DEVFN 0x000000ff /* A copy of devfn */ #define PCI_X_STATUS_BUS 0x0000ff00 /* A copy of bus nr */ #define PCI_X_STATUS_64BIT 0x00010000 /* 64-bit device */ #define PCI_X_STATUS_133MHZ 0x00020000 /* 133 MHz capable */ #define PCI_X_STATUS_SPL_DISC 0x00040000 /* Split Completion Discarded */ #define PCI_X_STATUS_UNX_SPL 0x00080000 /* Unexpected Split Completion */ #define PCI_X_STATUS_COMPLEX 0x00100000 /* Device Complexity */ #define PCI_X_STATUS_MAX_READ 0x00600000 /* Designed Max Memory Read Count */ #define PCI_X_STATUS_MAX_SPLIT 0x03800000 /* Designed Max Outstanding Split Transactions */ #define PCI_X_STATUS_MAX_CUM 0x1c000000 /* Designed Max Cumulative Read Size */ #define PCI_X_STATUS_SPL_ERR 0x20000000 /* Rcvd Split Completion Error Msg */ #define PCI_X_STATUS_266MHZ 0x40000000 /* 266 MHz capable */ #define PCI_X_STATUS_533MHZ 0x80000000 /* 533 MHz capable */ #define PCI_X_ECC_CSR 8 /* ECC control and status */ #define PCI_CAP_PCIX_SIZEOF_V0 8 /* size of registers for Version 0 */ #define PCI_CAP_PCIX_SIZEOF_V1 24 /* size for Version 1 */ #define PCI_CAP_PCIX_SIZEOF_V2 PCI_CAP_PCIX_SIZEOF_V1 /* Same for v2 */ /* PCI-X registers (Type 1 (bridge) devices) */ #define PCI_X_BRIDGE_SSTATUS 2 /* Secondary Status */ #define PCI_X_SSTATUS_64BIT 0x0001 /* Secondary AD interface is 64 bits */ #define PCI_X_SSTATUS_133MHZ 0x0002 /* 133 MHz capable */ #define PCI_X_SSTATUS_FREQ 0x03c0 /* Secondary Bus Mode and Frequency */ #define PCI_X_SSTATUS_VERS 0x3000 /* PCI-X Capability Version */ #define PCI_X_SSTATUS_V1 0x1000 /* Mode 2, not Mode 1 */ #define PCI_X_SSTATUS_V2 0x2000 /* Mode 1 or Modes 1 and 2 */ #define PCI_X_SSTATUS_266MHZ 0x4000 /* 266 MHz capable */ #define PCI_X_SSTATUS_533MHZ 0x8000 /* 533 MHz capable */ #define PCI_X_BRIDGE_STATUS 4 /* Bridge Status */ /* PCI Bridge Subsystem ID registers */ #define PCI_SSVID_VENDOR_ID 4 /* PCI Bridge subsystem vendor ID */ #define PCI_SSVID_DEVICE_ID 6 /* PCI Bridge subsystem device ID */ /* PCI Express capability registers */ #define PCI_EXP_FLAGS 2 /* Capabilities register */ #define PCI_EXP_FLAGS_VERS 0x000f /* Capability version */ #define PCI_EXP_FLAGS_TYPE 0x00f0 /* Device/Port type */ #define PCI_EXP_TYPE_ENDPOINT 0x0 /* Express Endpoint */ #define PCI_EXP_TYPE_LEG_END 0x1 /* Legacy Endpoint */ #define PCI_EXP_TYPE_ROOT_PORT 0x4 /* Root Port */ #define PCI_EXP_TYPE_UPSTREAM 0x5 /* Upstream Port */ #define PCI_EXP_TYPE_DOWNSTREAM 0x6 /* Downstream Port */ #define PCI_EXP_TYPE_PCI_BRIDGE 0x7 /* PCIe to PCI/PCI-X Bridge */ #define PCI_EXP_TYPE_PCIE_BRIDGE 0x8 /* PCI/PCI-X to PCIe Bridge */ #define PCI_EXP_TYPE_RC_END 0x9 /* Root Complex Integrated Endpoint */ #define PCI_EXP_TYPE_RC_EC 0xa /* Root Complex Event Collector */ #define PCI_EXP_FLAGS_SLOT 0x0100 /* Slot implemented */ #define PCI_EXP_FLAGS_IRQ 0x3e00 /* Interrupt message number */ #define PCI_EXP_DEVCAP 4 /* Device capabilities */ #define PCI_EXP_DEVCAP_PAYLOAD 0x00000007 /* Max_Payload_Size */ #define PCI_EXP_DEVCAP_PHANTOM 0x00000018 /* Phantom functions */ #define PCI_EXP_DEVCAP_EXT_TAG 0x00000020 /* Extended tags */ #define PCI_EXP_DEVCAP_L0S 0x000001c0 /* L0s Acceptable Latency */ #define PCI_EXP_DEVCAP_L1 0x00000e00 /* L1 Acceptable Latency */ #define PCI_EXP_DEVCAP_ATN_BUT 0x00001000 /* Attention Button Present */ #define PCI_EXP_DEVCAP_ATN_IND 0x00002000 /* Attention Indicator Present */ #define PCI_EXP_DEVCAP_PWR_IND 0x00004000 /* Power Indicator Present */ #define PCI_EXP_DEVCAP_RBER 0x00008000 /* Role-Based Error Reporting */ #define PCI_EXP_DEVCAP_PWR_VAL 0x03fc0000 /* Slot Power Limit Value */ #define PCI_EXP_DEVCAP_PWR_SCL 0x0c000000 /* Slot Power Limit Scale */ #define PCI_EXP_DEVCAP_FLR 0x10000000 /* Function Level Reset */ #define PCI_EXP_DEVCTL 8 /* Device Control */ #define PCI_EXP_DEVCTL_CERE 0x0001 /* Correctable Error Reporting En. */ #define PCI_EXP_DEVCTL_NFERE 0x0002 /* Non-Fatal Error Reporting Enable */ #define PCI_EXP_DEVCTL_FERE 0x0004 /* Fatal Error Reporting Enable */ #define PCI_EXP_DEVCTL_URRE 0x0008 /* Unsupported Request Reporting En. */ #define PCI_EXP_DEVCTL_RELAX_EN 0x0010 /* Enable relaxed ordering */ #define PCI_EXP_DEVCTL_PAYLOAD 0x00e0 /* Max_Payload_Size */ #define PCI_EXP_DEVCTL_EXT_TAG 0x0100 /* Extended Tag Field Enable */ #define PCI_EXP_DEVCTL_PHANTOM 0x0200 /* Phantom Functions Enable */ #define PCI_EXP_DEVCTL_AUX_PME 0x0400 /* Auxiliary Power PM Enable */ #define PCI_EXP_DEVCTL_NOSNOOP_EN 0x0800 /* Enable No Snoop */ #define PCI_EXP_DEVCTL_READRQ 0x7000 /* Max_Read_Request_Size */ #define PCI_EXP_DEVCTL_READRQ_128B 0x0000 /* 128 Bytes */ #define PCI_EXP_DEVCTL_READRQ_256B 0x1000 /* 256 Bytes */ #define PCI_EXP_DEVCTL_READRQ_512B 0x2000 /* 512 Bytes */ #define PCI_EXP_DEVCTL_READRQ_1024B 0x3000 /* 1024 Bytes */ #define PCI_EXP_DEVCTL_READRQ_2048B 0x4000 /* 2048 Bytes */ #define PCI_EXP_DEVCTL_READRQ_4096B 0x5000 /* 4096 Bytes */ #define PCI_EXP_DEVCTL_BCR_FLR 0x8000 /* Bridge Configuration Retry / FLR */ #define PCI_EXP_DEVSTA 10 /* Device Status */ #define PCI_EXP_DEVSTA_CED 0x0001 /* Correctable Error Detected */ #define PCI_EXP_DEVSTA_NFED 0x0002 /* Non-Fatal Error Detected */ #define PCI_EXP_DEVSTA_FED 0x0004 /* Fatal Error Detected */ #define PCI_EXP_DEVSTA_URD 0x0008 /* Unsupported Request Detected */ #define PCI_EXP_DEVSTA_AUXPD 0x0010 /* AUX Power Detected */ #define PCI_EXP_DEVSTA_TRPND 0x0020 /* Transactions Pending */ #define PCI_CAP_EXP_RC_ENDPOINT_SIZEOF_V1 12 /* v1 endpoints without link end here */ #define PCI_EXP_LNKCAP 12 /* Link Capabilities */ #define PCI_EXP_LNKCAP_SLS 0x0000000f /* Supported Link Speeds */ #define PCI_EXP_LNKCAP_SLS_2_5GB 0x00000001 /* LNKCAP2 SLS Vector bit 0 */ #define PCI_EXP_LNKCAP_SLS_5_0GB 0x00000002 /* LNKCAP2 SLS Vector bit 1 */ #define PCI_EXP_LNKCAP_SLS_8_0GB 0x00000003 /* LNKCAP2 SLS Vector bit 2 */ #define PCI_EXP_LNKCAP_SLS_16_0GB 0x00000004 /* LNKCAP2 SLS Vector bit 3 */ #define PCI_EXP_LNKCAP_SLS_32_0GB 0x00000005 /* LNKCAP2 SLS Vector bit 4 */ #define PCI_EXP_LNKCAP_SLS_64_0GB 0x00000006 /* LNKCAP2 SLS Vector bit 5 */ #define PCI_EXP_LNKCAP_MLW 0x000003f0 /* Maximum Link Width */ #define PCI_EXP_LNKCAP_ASPMS 0x00000c00 /* ASPM Support */ #define PCI_EXP_LNKCAP_ASPM_L0S 0x00000400 /* ASPM L0s Support */ #define PCI_EXP_LNKCAP_ASPM_L1 0x00000800 /* ASPM L1 Support */ #define PCI_EXP_LNKCAP_L0SEL 0x00007000 /* L0s Exit Latency */ #define PCI_EXP_LNKCAP_L1EL 0x00038000 /* L1 Exit Latency */ #define PCI_EXP_LNKCAP_CLKPM 0x00040000 /* Clock Power Management */ #define PCI_EXP_LNKCAP_SDERC 0x00080000 /* Surprise Down Error Reporting Capable */ #define PCI_EXP_LNKCAP_DLLLARC 0x00100000 /* Data Link Layer Link Active Reporting Capable */ #define PCI_EXP_LNKCAP_LBNC 0x00200000 /* Link Bandwidth Notification Capability */ #define PCI_EXP_LNKCAP_PN 0xff000000 /* Port Number */ #define PCI_EXP_LNKCTL 16 /* Link Control */ #define PCI_EXP_LNKCTL_ASPMC 0x0003 /* ASPM Control */ #define PCI_EXP_LNKCTL_ASPM_L0S 0x0001 /* L0s Enable */ #define PCI_EXP_LNKCTL_ASPM_L1 0x0002 /* L1 Enable */ #define PCI_EXP_LNKCTL_RCB 0x0008 /* Read Completion Boundary */ #define PCI_EXP_LNKCTL_LD 0x0010 /* Link Disable */ #define PCI_EXP_LNKCTL_RL 0x0020 /* Retrain Link */ #define PCI_EXP_LNKCTL_CCC 0x0040 /* Common Clock Configuration */ #define PCI_EXP_LNKCTL_ES 0x0080 /* Extended Synch */ #define PCI_EXP_LNKCTL_CLKREQ_EN 0x0100 /* Enable clkreq */ #define PCI_EXP_LNKCTL_HAWD 0x0200 /* Hardware Autonomous Width Disable */ #define PCI_EXP_LNKCTL_LBMIE 0x0400 /* Link Bandwidth Management Interrupt Enable */ #define PCI_EXP_LNKCTL_LABIE 0x0800 /* Link Autonomous Bandwidth Interrupt Enable */ #define PCI_EXP_LNKSTA 18 /* Link Status */ #define PCI_EXP_LNKSTA_CLS 0x000f /* Current Link Speed */ #define PCI_EXP_LNKSTA_CLS_2_5GB 0x0001 /* Current Link Speed 2.5GT/s */ #define PCI_EXP_LNKSTA_CLS_5_0GB 0x0002 /* Current Link Speed 5.0GT/s */ #define PCI_EXP_LNKSTA_CLS_8_0GB 0x0003 /* Current Link Speed 8.0GT/s */ #define PCI_EXP_LNKSTA_CLS_16_0GB 0x0004 /* Current Link Speed 16.0GT/s */ #define PCI_EXP_LNKSTA_CLS_32_0GB 0x0005 /* Current Link Speed 32.0GT/s */ #define PCI_EXP_LNKSTA_CLS_64_0GB 0x0006 /* Current Link Speed 64.0GT/s */ #define PCI_EXP_LNKSTA_NLW 0x03f0 /* Negotiated Link Width */ #define PCI_EXP_LNKSTA_NLW_X1 0x0010 /* Current Link Width x1 */ #define PCI_EXP_LNKSTA_NLW_X2 0x0020 /* Current Link Width x2 */ #define PCI_EXP_LNKSTA_NLW_X4 0x0040 /* Current Link Width x4 */ #define PCI_EXP_LNKSTA_NLW_X8 0x0080 /* Current Link Width x8 */ #define PCI_EXP_LNKSTA_NLW_SHIFT 4 /* start of NLW mask in link status */ #define PCI_EXP_LNKSTA_LT 0x0800 /* Link Training */ #define PCI_EXP_LNKSTA_SLC 0x1000 /* Slot Clock Configuration */ #define PCI_EXP_LNKSTA_DLLLA 0x2000 /* Data Link Layer Link Active */ #define PCI_EXP_LNKSTA_LBMS 0x4000 /* Link Bandwidth Management Status */ #define PCI_EXP_LNKSTA_LABS 0x8000 /* Link Autonomous Bandwidth Status */ #define PCI_CAP_EXP_ENDPOINT_SIZEOF_V1 20 /* v1 endpoints with link end here */ #define PCI_EXP_SLTCAP 20 /* Slot Capabilities */ #define PCI_EXP_SLTCAP_ABP 0x00000001 /* Attention Button Present */ #define PCI_EXP_SLTCAP_PCP 0x00000002 /* Power Controller Present */ #define PCI_EXP_SLTCAP_MRLSP 0x00000004 /* MRL Sensor Present */ #define PCI_EXP_SLTCAP_AIP 0x00000008 /* Attention Indicator Present */ #define PCI_EXP_SLTCAP_PIP 0x00000010 /* Power Indicator Present */ #define PCI_EXP_SLTCAP_HPS 0x00000020 /* Hot-Plug Surprise */ #define PCI_EXP_SLTCAP_HPC 0x00000040 /* Hot-Plug Capable */ #define PCI_EXP_SLTCAP_SPLV 0x00007f80 /* Slot Power Limit Value */ #define PCI_EXP_SLTCAP_SPLS 0x00018000 /* Slot Power Limit Scale */ #define PCI_EXP_SLTCAP_EIP 0x00020000 /* Electromechanical Interlock Present */ #define PCI_EXP_SLTCAP_NCCS 0x00040000 /* No Command Completed Support */ #define PCI_EXP_SLTCAP_PSN 0xfff80000 /* Physical Slot Number */ #define PCI_EXP_SLTCTL 24 /* Slot Control */ #define PCI_EXP_SLTCTL_ABPE 0x0001 /* Attention Button Pressed Enable */ #define PCI_EXP_SLTCTL_PFDE 0x0002 /* Power Fault Detected Enable */ #define PCI_EXP_SLTCTL_MRLSCE 0x0004 /* MRL Sensor Changed Enable */ #define PCI_EXP_SLTCTL_PDCE 0x0008 /* Presence Detect Changed Enable */ #define PCI_EXP_SLTCTL_CCIE 0x0010 /* Command Completed Interrupt Enable */ #define PCI_EXP_SLTCTL_HPIE 0x0020 /* Hot-Plug Interrupt Enable */ #define PCI_EXP_SLTCTL_AIC 0x00c0 /* Attention Indicator Control */ #define PCI_EXP_SLTCTL_ATTN_IND_SHIFT 6 /* Attention Indicator shift */ #define PCI_EXP_SLTCTL_ATTN_IND_ON 0x0040 /* Attention Indicator on */ #define PCI_EXP_SLTCTL_ATTN_IND_BLINK 0x0080 /* Attention Indicator blinking */ #define PCI_EXP_SLTCTL_ATTN_IND_OFF 0x00c0 /* Attention Indicator off */ #define PCI_EXP_SLTCTL_PIC 0x0300 /* Power Indicator Control */ #define PCI_EXP_SLTCTL_PWR_IND_ON 0x0100 /* Power Indicator on */ #define PCI_EXP_SLTCTL_PWR_IND_BLINK 0x0200 /* Power Indicator blinking */ #define PCI_EXP_SLTCTL_PWR_IND_OFF 0x0300 /* Power Indicator off */ #define PCI_EXP_SLTCTL_PCC 0x0400 /* Power Controller Control */ #define PCI_EXP_SLTCTL_PWR_ON 0x0000 /* Power On */ #define PCI_EXP_SLTCTL_PWR_OFF 0x0400 /* Power Off */ #define PCI_EXP_SLTCTL_EIC 0x0800 /* Electromechanical Interlock Control */ #define PCI_EXP_SLTCTL_DLLSCE 0x1000 /* Data Link Layer State Changed Enable */ #define PCI_EXP_SLTCTL_IBPD_DISABLE 0x4000 /* In-band PD disable */ #define PCI_EXP_SLTSTA 26 /* Slot Status */ #define PCI_EXP_SLTSTA_ABP 0x0001 /* Attention Button Pressed */ #define PCI_EXP_SLTSTA_PFD 0x0002 /* Power Fault Detected */ #define PCI_EXP_SLTSTA_MRLSC 0x0004 /* MRL Sensor Changed */ #define PCI_EXP_SLTSTA_PDC 0x0008 /* Presence Detect Changed */ #define PCI_EXP_SLTSTA_CC 0x0010 /* Command Completed */ #define PCI_EXP_SLTSTA_MRLSS 0x0020 /* MRL Sensor State */ #define PCI_EXP_SLTSTA_PDS 0x0040 /* Presence Detect State */ #define PCI_EXP_SLTSTA_EIS 0x0080 /* Electromechanical Interlock Status */ #define PCI_EXP_SLTSTA_DLLSC 0x0100 /* Data Link Layer State Changed */ #define PCI_EXP_RTCTL 28 /* Root Control */ #define PCI_EXP_RTCTL_SECEE 0x0001 /* System Error on Correctable Error */ #define PCI_EXP_RTCTL_SENFEE 0x0002 /* System Error on Non-Fatal Error */ #define PCI_EXP_RTCTL_SEFEE 0x0004 /* System Error on Fatal Error */ #define PCI_EXP_RTCTL_PMEIE 0x0008 /* PME Interrupt Enable */ #define PCI_EXP_RTCTL_CRSSVE 0x0010 /* CRS Software Visibility Enable */ #define PCI_EXP_RTCAP 30 /* Root Capabilities */ #define PCI_EXP_RTCAP_CRSVIS 0x0001 /* CRS Software Visibility capability */ #define PCI_EXP_RTSTA 32 /* Root Status */ #define PCI_EXP_RTSTA_PME 0x00010000 /* PME status */ #define PCI_EXP_RTSTA_PENDING 0x00020000 /* PME pending */ /* * The Device Capabilities 2, Device Status 2, Device Control 2, * Link Capabilities 2, Link Status 2, Link Control 2, * Slot Capabilities 2, Slot Status 2, and Slot Control 2 registers * are only present on devices with PCIe Capability version 2. * Use pcie_capability_read_word() and similar interfaces to use them * safely. */ #define PCI_EXP_DEVCAP2 36 /* Device Capabilities 2 */ #define PCI_EXP_DEVCAP2_COMP_TMOUT_DIS 0x00000010 /* Completion Timeout Disable supported */ #define PCI_EXP_DEVCAP2_ARI 0x00000020 /* Alternative Routing-ID */ #define PCI_EXP_DEVCAP2_ATOMIC_ROUTE 0x00000040 /* Atomic Op routing */ #define PCI_EXP_DEVCAP2_ATOMIC_COMP32 0x00000080 /* 32b AtomicOp completion */ #define PCI_EXP_DEVCAP2_ATOMIC_COMP64 0x00000100 /* 64b AtomicOp completion */ #define PCI_EXP_DEVCAP2_ATOMIC_COMP128 0x00000200 /* 128b AtomicOp completion */ #define PCI_EXP_DEVCAP2_LTR 0x00000800 /* Latency tolerance reporting */ #define PCI_EXP_DEVCAP2_OBFF_MASK 0x000c0000 /* OBFF support mechanism */ #define PCI_EXP_DEVCAP2_OBFF_MSG 0x00040000 /* New message signaling */ #define PCI_EXP_DEVCAP2_OBFF_WAKE 0x00080000 /* Re-use WAKE# for OBFF */ #define PCI_EXP_DEVCAP2_EE_PREFIX 0x00200000 /* End-End TLP Prefix */ #define PCI_EXP_DEVCTL2 40 /* Device Control 2 */ #define PCI_EXP_DEVCTL2_COMP_TIMEOUT 0x000f /* Completion Timeout Value */ #define PCI_EXP_DEVCTL2_COMP_TMOUT_DIS 0x0010 /* Completion Timeout Disable */ #define PCI_EXP_DEVCTL2_ARI 0x0020 /* Alternative Routing-ID */ #define PCI_EXP_DEVCTL2_ATOMIC_REQ 0x0040 /* Set Atomic requests */ #define PCI_EXP_DEVCTL2_ATOMIC_EGRESS_BLOCK 0x0080 /* Block atomic egress */ #define PCI_EXP_DEVCTL2_IDO_REQ_EN 0x0100 /* Allow IDO for requests */ #define PCI_EXP_DEVCTL2_IDO_CMP_EN 0x0200 /* Allow IDO for completions */ #define PCI_EXP_DEVCTL2_LTR_EN 0x0400 /* Enable LTR mechanism */ #define PCI_EXP_DEVCTL2_OBFF_MSGA_EN 0x2000 /* Enable OBFF Message type A */ #define PCI_EXP_DEVCTL2_OBFF_MSGB_EN 0x4000 /* Enable OBFF Message type B */ #define PCI_EXP_DEVCTL2_OBFF_WAKE_EN 0x6000 /* OBFF using WAKE# signaling */ #define PCI_EXP_DEVSTA2 42 /* Device Status 2 */ #define PCI_CAP_EXP_RC_ENDPOINT_SIZEOF_V2 44 /* v2 endpoints without link end here */ #define PCI_EXP_LNKCAP2 44 /* Link Capabilities 2 */ #define PCI_EXP_LNKCAP2_SLS_2_5GB 0x00000002 /* Supported Speed 2.5GT/s */ #define PCI_EXP_LNKCAP2_SLS_5_0GB 0x00000004 /* Supported Speed 5GT/s */ #define PCI_EXP_LNKCAP2_SLS_8_0GB 0x00000008 /* Supported Speed 8GT/s */ #define PCI_EXP_LNKCAP2_SLS_16_0GB 0x00000010 /* Supported Speed 16GT/s */ #define PCI_EXP_LNKCAP2_SLS_32_0GB 0x00000020 /* Supported Speed 32GT/s */ #define PCI_EXP_LNKCAP2_SLS_64_0GB 0x00000040 /* Supported Speed 64GT/s */ #define PCI_EXP_LNKCAP2_CROSSLINK 0x00000100 /* Crosslink supported */ #define PCI_EXP_LNKCTL2 48 /* Link Control 2 */ #define PCI_EXP_LNKCTL2_TLS 0x000f #define PCI_EXP_LNKCTL2_TLS_2_5GT 0x0001 /* Supported Speed 2.5GT/s */ #define PCI_EXP_LNKCTL2_TLS_5_0GT 0x0002 /* Supported Speed 5GT/s */ #define PCI_EXP_LNKCTL2_TLS_8_0GT 0x0003 /* Supported Speed 8GT/s */ #define PCI_EXP_LNKCTL2_TLS_16_0GT 0x0004 /* Supported Speed 16GT/s */ #define PCI_EXP_LNKCTL2_TLS_32_0GT 0x0005 /* Supported Speed 32GT/s */ #define PCI_EXP_LNKCTL2_TLS_64_0GT 0x0006 /* Supported Speed 64GT/s */ #define PCI_EXP_LNKCTL2_ENTER_COMP 0x0010 /* Enter Compliance */ #define PCI_EXP_LNKCTL2_TX_MARGIN 0x0380 /* Transmit Margin */ #define PCI_EXP_LNKSTA2 50 /* Link Status 2 */ #define PCI_CAP_EXP_ENDPOINT_SIZEOF_V2 52 /* v2 endpoints with link end here */ #define PCI_EXP_SLTCAP2 52 /* Slot Capabilities 2 */ #define PCI_EXP_SLTCAP2_IBPD 0x00000001 /* In-band PD Disable Supported */ #define PCI_EXP_SLTCTL2 56 /* Slot Control 2 */ #define PCI_EXP_SLTSTA2 58 /* Slot Status 2 */ /* Extended Capabilities (PCI-X 2.0 and Express) */ #define PCI_EXT_CAP_ID(header) (header & 0x0000ffff) #define PCI_EXT_CAP_VER(header) ((header >> 16) & 0xf) #define PCI_EXT_CAP_NEXT(header) ((header >> 20) & 0xffc) #define PCI_EXT_CAP_ID_ERR 0x01 /* Advanced Error Reporting */ #define PCI_EXT_CAP_ID_VC 0x02 /* Virtual Channel Capability */ #define PCI_EXT_CAP_ID_DSN 0x03 /* Device Serial Number */ #define PCI_EXT_CAP_ID_PWR 0x04 /* Power Budgeting */ #define PCI_EXT_CAP_ID_RCLD 0x05 /* Root Complex Link Declaration */ #define PCI_EXT_CAP_ID_RCILC 0x06 /* Root Complex Internal Link Control */ #define PCI_EXT_CAP_ID_RCEC 0x07 /* Root Complex Event Collector */ #define PCI_EXT_CAP_ID_MFVC 0x08 /* Multi-Function VC Capability */ #define PCI_EXT_CAP_ID_VC9 0x09 /* same as _VC */ #define PCI_EXT_CAP_ID_RCRB 0x0A /* Root Complex RB? */ #define PCI_EXT_CAP_ID_VNDR 0x0B /* Vendor-Specific */ #define PCI_EXT_CAP_ID_CAC 0x0C /* Config Access - obsolete */ #define PCI_EXT_CAP_ID_ACS 0x0D /* Access Control Services */ #define PCI_EXT_CAP_ID_ARI 0x0E /* Alternate Routing ID */ #define PCI_EXT_CAP_ID_ATS 0x0F /* Address Translation Services */ #define PCI_EXT_CAP_ID_SRIOV 0x10 /* Single Root I/O Virtualization */ #define PCI_EXT_CAP_ID_MRIOV 0x11 /* Multi Root I/O Virtualization */ #define PCI_EXT_CAP_ID_MCAST 0x12 /* Multicast */ #define PCI_EXT_CAP_ID_PRI 0x13 /* Page Request Interface */ #define PCI_EXT_CAP_ID_AMD_XXX 0x14 /* Reserved for AMD */ #define PCI_EXT_CAP_ID_REBAR 0x15 /* Resizable BAR */ #define PCI_EXT_CAP_ID_DPA 0x16 /* Dynamic Power Allocation */ #define PCI_EXT_CAP_ID_TPH 0x17 /* TPH Requester */ #define PCI_EXT_CAP_ID_LTR 0x18 /* Latency Tolerance Reporting */ #define PCI_EXT_CAP_ID_SECPCI 0x19 /* Secondary PCIe Capability */ #define PCI_EXT_CAP_ID_PMUX 0x1A /* Protocol Multiplexing */ #define PCI_EXT_CAP_ID_PASID 0x1B /* Process Address Space ID */ #define PCI_EXT_CAP_ID_DPC 0x1D /* Downstream Port Containment */ #define PCI_EXT_CAP_ID_L1SS 0x1E /* L1 PM Substates */ #define PCI_EXT_CAP_ID_PTM 0x1F /* Precision Time Measurement */ #define PCI_EXT_CAP_ID_DVSEC 0x23 /* Designated Vendor-Specific */ #define PCI_EXT_CAP_ID_MAX PCI_EXT_CAP_ID_DVSEC #define PCI_EXT_CAP_DSN_SIZEOF 12 #define PCI_EXT_CAP_MCAST_ENDPOINT_SIZEOF 40 /* Advanced Error Reporting */ #define PCI_ERR_UNCOR_STATUS 4 /* Uncorrectable Error Status */ #define PCI_ERR_UNC_UND 0x00000001 /* Undefined */ #define PCI_ERR_UNC_DLP 0x00000010 /* Data Link Protocol */ #define PCI_ERR_UNC_SURPDN 0x00000020 /* Surprise Down */ #define PCI_ERR_UNC_POISON_TLP 0x00001000 /* Poisoned TLP */ #define PCI_ERR_UNC_FCP 0x00002000 /* Flow Control Protocol */ #define PCI_ERR_UNC_COMP_TIME 0x00004000 /* Completion Timeout */ #define PCI_ERR_UNC_COMP_ABORT 0x00008000 /* Completer Abort */ #define PCI_ERR_UNC_UNX_COMP 0x00010000 /* Unexpected Completion */ #define PCI_ERR_UNC_RX_OVER 0x00020000 /* Receiver Overflow */ #define PCI_ERR_UNC_MALF_TLP 0x00040000 /* Malformed TLP */ #define PCI_ERR_UNC_ECRC 0x00080000 /* ECRC Error Status */ #define PCI_ERR_UNC_UNSUP 0x00100000 /* Unsupported Request */ #define PCI_ERR_UNC_ACSV 0x00200000 /* ACS Violation */ #define PCI_ERR_UNC_INTN 0x00400000 /* internal error */ #define PCI_ERR_UNC_MCBTLP 0x00800000 /* MC blocked TLP */ #define PCI_ERR_UNC_ATOMEG 0x01000000 /* Atomic egress blocked */ #define PCI_ERR_UNC_TLPPRE 0x02000000 /* TLP prefix blocked */ #define PCI_ERR_UNCOR_MASK 8 /* Uncorrectable Error Mask */ /* Same bits as above */ #define PCI_ERR_UNCOR_SEVER 12 /* Uncorrectable Error Severity */ /* Same bits as above */ #define PCI_ERR_COR_STATUS 16 /* Correctable Error Status */ #define PCI_ERR_COR_RCVR 0x00000001 /* Receiver Error Status */ #define PCI_ERR_COR_BAD_TLP 0x00000040 /* Bad TLP Status */ #define PCI_ERR_COR_BAD_DLLP 0x00000080 /* Bad DLLP Status */ #define PCI_ERR_COR_REP_ROLL 0x00000100 /* REPLAY_NUM Rollover */ #define PCI_ERR_COR_REP_TIMER 0x00001000 /* Replay Timer Timeout */ #define PCI_ERR_COR_ADV_NFAT 0x00002000 /* Advisory Non-Fatal */ #define PCI_ERR_COR_INTERNAL 0x00004000 /* Corrected Internal */ #define PCI_ERR_COR_LOG_OVER 0x00008000 /* Header Log Overflow */ #define PCI_ERR_COR_MASK 20 /* Correctable Error Mask */ /* Same bits as above */ #define PCI_ERR_CAP 24 /* Advanced Error Capabilities */ #define PCI_ERR_CAP_FEP(x) ((x) & 31) /* First Error Pointer */ #define PCI_ERR_CAP_ECRC_GENC 0x00000020 /* ECRC Generation Capable */ #define PCI_ERR_CAP_ECRC_GENE 0x00000040 /* ECRC Generation Enable */ #define PCI_ERR_CAP_ECRC_CHKC 0x00000080 /* ECRC Check Capable */ #define PCI_ERR_CAP_ECRC_CHKE 0x00000100 /* ECRC Check Enable */ #define PCI_ERR_HEADER_LOG 28 /* Header Log Register (16 bytes) */ #define PCI_ERR_ROOT_COMMAND 44 /* Root Error Command */ #define PCI_ERR_ROOT_CMD_COR_EN 0x00000001 /* Correctable Err Reporting Enable */ #define PCI_ERR_ROOT_CMD_NONFATAL_EN 0x00000002 /* Non-Fatal Err Reporting Enable */ #define PCI_ERR_ROOT_CMD_FATAL_EN 0x00000004 /* Fatal Err Reporting Enable */ #define PCI_ERR_ROOT_STATUS 48 #define PCI_ERR_ROOT_COR_RCV 0x00000001 /* ERR_COR Received */ #define PCI_ERR_ROOT_MULTI_COR_RCV 0x00000002 /* Multiple ERR_COR */ #define PCI_ERR_ROOT_UNCOR_RCV 0x00000004 /* ERR_FATAL/NONFATAL */ #define PCI_ERR_ROOT_MULTI_UNCOR_RCV 0x00000008 /* Multiple FATAL/NONFATAL */ #define PCI_ERR_ROOT_FIRST_FATAL 0x00000010 /* First UNC is Fatal */ #define PCI_ERR_ROOT_NONFATAL_RCV 0x00000020 /* Non-Fatal Received */ #define PCI_ERR_ROOT_FATAL_RCV 0x00000040 /* Fatal Received */ #define PCI_ERR_ROOT_AER_IRQ 0xf8000000 /* Advanced Error Interrupt Message Number */ #define PCI_ERR_ROOT_ERR_SRC 52 /* Error Source Identification */ /* Virtual Channel */ #define PCI_VC_PORT_CAP1 4 #define PCI_VC_CAP1_EVCC 0x00000007 /* extended VC count */ #define PCI_VC_CAP1_LPEVCC 0x00000070 /* low prio extended VC count */ #define PCI_VC_CAP1_ARB_SIZE 0x00000c00 #define PCI_VC_PORT_CAP2 8 #define PCI_VC_CAP2_32_PHASE 0x00000002 #define PCI_VC_CAP2_64_PHASE 0x00000004 #define PCI_VC_CAP2_128_PHASE 0x00000008 #define PCI_VC_CAP2_ARB_OFF 0xff000000 #define PCI_VC_PORT_CTRL 12 #define PCI_VC_PORT_CTRL_LOAD_TABLE 0x00000001 #define PCI_VC_PORT_STATUS 14 #define PCI_VC_PORT_STATUS_TABLE 0x00000001 #define PCI_VC_RES_CAP 16 #define PCI_VC_RES_CAP_32_PHASE 0x00000002 #define PCI_VC_RES_CAP_64_PHASE 0x00000004 #define PCI_VC_RES_CAP_128_PHASE 0x00000008 #define PCI_VC_RES_CAP_128_PHASE_TB 0x00000010 #define PCI_VC_RES_CAP_256_PHASE 0x00000020 #define PCI_VC_RES_CAP_ARB_OFF 0xff000000 #define PCI_VC_RES_CTRL 20 #define PCI_VC_RES_CTRL_LOAD_TABLE 0x00010000 #define PCI_VC_RES_CTRL_ARB_SELECT 0x000e0000 #define PCI_VC_RES_CTRL_ID 0x07000000 #define PCI_VC_RES_CTRL_ENABLE 0x80000000 #define PCI_VC_RES_STATUS 26 #define PCI_VC_RES_STATUS_TABLE 0x00000001 #define PCI_VC_RES_STATUS_NEGO 0x00000002 #define PCI_CAP_VC_BASE_SIZEOF 0x10 #define PCI_CAP_VC_PER_VC_SIZEOF 0x0C /* Power Budgeting */ #define PCI_PWR_DSR 4 /* Data Select Register */ #define PCI_PWR_DATA 8 /* Data Register */ #define PCI_PWR_DATA_BASE(x) ((x) & 0xff) /* Base Power */ #define PCI_PWR_DATA_SCALE(x) (((x) >> 8) & 3) /* Data Scale */ #define PCI_PWR_DATA_PM_SUB(x) (((x) >> 10) & 7) /* PM Sub State */ #define PCI_PWR_DATA_PM_STATE(x) (((x) >> 13) & 3) /* PM State */ #define PCI_PWR_DATA_TYPE(x) (((x) >> 15) & 7) /* Type */ #define PCI_PWR_DATA_RAIL(x) (((x) >> 18) & 7) /* Power Rail */ #define PCI_PWR_CAP 12 /* Capability */ #define PCI_PWR_CAP_BUDGET(x) ((x) & 1) /* Included in system budget */ #define PCI_EXT_CAP_PWR_SIZEOF 16 /* Root Complex Event Collector Endpoint Association */ #define PCI_RCEC_RCIEP_BITMAP 4 /* Associated Bitmap for RCiEPs */ #define PCI_RCEC_BUSN 8 /* RCEC Associated Bus Numbers */ #define PCI_RCEC_BUSN_REG_VER 0x02 /* Least version with BUSN present */ #define PCI_RCEC_BUSN_NEXT(x) (((x) >> 8) & 0xff) #define PCI_RCEC_BUSN_LAST(x) (((x) >> 16) & 0xff) /* Vendor-Specific (VSEC, PCI_EXT_CAP_ID_VNDR) */ #define PCI_VNDR_HEADER 4 /* Vendor-Specific Header */ #define PCI_VNDR_HEADER_ID(x) ((x) & 0xffff) #define PCI_VNDR_HEADER_REV(x) (((x) >> 16) & 0xf) #define PCI_VNDR_HEADER_LEN(x) (((x) >> 20) & 0xfff) /* * HyperTransport sub capability types * * Unfortunately there are both 3 bit and 5 bit capability types defined * in the HT spec, catering for that is a little messy. You probably don't * want to use these directly, just use pci_find_ht_capability() and it * will do the right thing for you. */ #define HT_3BIT_CAP_MASK 0xE0 #define HT_CAPTYPE_SLAVE 0x00 /* Slave/Primary link configuration */ #define HT_CAPTYPE_HOST 0x20 /* Host/Secondary link configuration */ #define HT_5BIT_CAP_MASK 0xF8 #define HT_CAPTYPE_IRQ 0x80 /* IRQ Configuration */ #define HT_CAPTYPE_REMAPPING_40 0xA0 /* 40 bit address remapping */ #define HT_CAPTYPE_REMAPPING_64 0xA2 /* 64 bit address remapping */ #define HT_CAPTYPE_UNITID_CLUMP 0x90 /* Unit ID clumping */ #define HT_CAPTYPE_EXTCONF 0x98 /* Extended Configuration Space Access */ #define HT_CAPTYPE_MSI_MAPPING 0xA8 /* MSI Mapping Capability */ #define HT_MSI_FLAGS 0x02 /* Offset to flags */ #define HT_MSI_FLAGS_ENABLE 0x1 /* Mapping enable */ #define HT_MSI_FLAGS_FIXED 0x2 /* Fixed mapping only */ #define HT_MSI_FIXED_ADDR 0x00000000FEE00000ULL /* Fixed addr */ #define HT_MSI_ADDR_LO 0x04 /* Offset to low addr bits */ #define HT_MSI_ADDR_LO_MASK 0xFFF00000 /* Low address bit mask */ #define HT_MSI_ADDR_HI 0x08 /* Offset to high addr bits */ #define HT_CAPTYPE_DIRECT_ROUTE 0xB0 /* Direct routing configuration */ #define HT_CAPTYPE_VCSET 0xB8 /* Virtual Channel configuration */ #define HT_CAPTYPE_ERROR_RETRY 0xC0 /* Retry on error configuration */ #define HT_CAPTYPE_GEN3 0xD0 /* Generation 3 HyperTransport configuration */ #define HT_CAPTYPE_PM 0xE0 /* HyperTransport power management configuration */ #define HT_CAP_SIZEOF_LONG 28 /* slave & primary */ #define HT_CAP_SIZEOF_SHORT 24 /* host & secondary */ /* Alternative Routing-ID Interpretation */ #define PCI_ARI_CAP 0x04 /* ARI Capability Register */ #define PCI_ARI_CAP_MFVC 0x0001 /* MFVC Function Groups Capability */ #define PCI_ARI_CAP_ACS 0x0002 /* ACS Function Groups Capability */ #define PCI_ARI_CAP_NFN(x) (((x) >> 8) & 0xff) /* Next Function Number */ #define PCI_ARI_CTRL 0x06 /* ARI Control Register */ #define PCI_ARI_CTRL_MFVC 0x0001 /* MFVC Function Groups Enable */ #define PCI_ARI_CTRL_ACS 0x0002 /* ACS Function Groups Enable */ #define PCI_ARI_CTRL_FG(x) (((x) >> 4) & 7) /* Function Group */ #define PCI_EXT_CAP_ARI_SIZEOF 8 /* Address Translation Service */ #define PCI_ATS_CAP 0x04 /* ATS Capability Register */ #define PCI_ATS_CAP_QDEP(x) ((x) & 0x1f) /* Invalidate Queue Depth */ #define PCI_ATS_MAX_QDEP 32 /* Max Invalidate Queue Depth */ #define PCI_ATS_CAP_PAGE_ALIGNED 0x0020 /* Page Aligned Request */ #define PCI_ATS_CTRL 0x06 /* ATS Control Register */ #define PCI_ATS_CTRL_ENABLE 0x8000 /* ATS Enable */ #define PCI_ATS_CTRL_STU(x) ((x) & 0x1f) /* Smallest Translation Unit */ #define PCI_ATS_MIN_STU 12 /* shift of minimum STU block */ #define PCI_EXT_CAP_ATS_SIZEOF 8 /* Page Request Interface */ #define PCI_PRI_CTRL 0x04 /* PRI control register */ #define PCI_PRI_CTRL_ENABLE 0x0001 /* Enable */ #define PCI_PRI_CTRL_RESET 0x0002 /* Reset */ #define PCI_PRI_STATUS 0x06 /* PRI status register */ #define PCI_PRI_STATUS_RF 0x0001 /* Response Failure */ #define PCI_PRI_STATUS_UPRGI 0x0002 /* Unexpected PRG index */ #define PCI_PRI_STATUS_STOPPED 0x0100 /* PRI Stopped */ #define PCI_PRI_STATUS_PASID 0x8000 /* PRG Response PASID Required */ #define PCI_PRI_MAX_REQ 0x08 /* PRI max reqs supported */ #define PCI_PRI_ALLOC_REQ 0x0c /* PRI max reqs allowed */ #define PCI_EXT_CAP_PRI_SIZEOF 16 /* Process Address Space ID */ #define PCI_PASID_CAP 0x04 /* PASID feature register */ #define PCI_PASID_CAP_EXEC 0x02 /* Exec permissions Supported */ #define PCI_PASID_CAP_PRIV 0x04 /* Privilege Mode Supported */ #define PCI_PASID_CTRL 0x06 /* PASID control register */ #define PCI_PASID_CTRL_ENABLE 0x01 /* Enable bit */ #define PCI_PASID_CTRL_EXEC 0x02 /* Exec permissions Enable */ #define PCI_PASID_CTRL_PRIV 0x04 /* Privilege Mode Enable */ #define PCI_EXT_CAP_PASID_SIZEOF 8 /* Single Root I/O Virtualization */ #define PCI_SRIOV_CAP 0x04 /* SR-IOV Capabilities */ #define PCI_SRIOV_CAP_VFM 0x00000001 /* VF Migration Capable */ #define PCI_SRIOV_CAP_INTR(x) ((x) >> 21) /* Interrupt Message Number */ #define PCI_SRIOV_CTRL 0x08 /* SR-IOV Control */ #define PCI_SRIOV_CTRL_VFE 0x0001 /* VF Enable */ #define PCI_SRIOV_CTRL_VFM 0x0002 /* VF Migration Enable */ #define PCI_SRIOV_CTRL_INTR 0x0004 /* VF Migration Interrupt Enable */ #define PCI_SRIOV_CTRL_MSE 0x0008 /* VF Memory Space Enable */ #define PCI_SRIOV_CTRL_ARI 0x0010 /* ARI Capable Hierarchy */ #define PCI_SRIOV_STATUS 0x0a /* SR-IOV Status */ #define PCI_SRIOV_STATUS_VFM 0x0001 /* VF Migration Status */ #define PCI_SRIOV_INITIAL_VF 0x0c /* Initial VFs */ #define PCI_SRIOV_TOTAL_VF 0x0e /* Total VFs */ #define PCI_SRIOV_NUM_VF 0x10 /* Number of VFs */ #define PCI_SRIOV_FUNC_LINK 0x12 /* Function Dependency Link */ #define PCI_SRIOV_VF_OFFSET 0x14 /* First VF Offset */ #define PCI_SRIOV_VF_STRIDE 0x16 /* Following VF Stride */ #define PCI_SRIOV_VF_DID 0x1a /* VF Device ID */ #define PCI_SRIOV_SUP_PGSIZE 0x1c /* Supported Page Sizes */ #define PCI_SRIOV_SYS_PGSIZE 0x20 /* System Page Size */ #define PCI_SRIOV_BAR 0x24 /* VF BAR0 */ #define PCI_SRIOV_NUM_BARS 6 /* Number of VF BARs */ #define PCI_SRIOV_VFM 0x3c /* VF Migration State Array Offset*/ #define PCI_SRIOV_VFM_BIR(x) ((x) & 7) /* State BIR */ #define PCI_SRIOV_VFM_OFFSET(x) ((x) & ~7) /* State Offset */ #define PCI_SRIOV_VFM_UA 0x0 /* Inactive.Unavailable */ #define PCI_SRIOV_VFM_MI 0x1 /* Dormant.MigrateIn */ #define PCI_SRIOV_VFM_MO 0x2 /* Active.MigrateOut */ #define PCI_SRIOV_VFM_AV 0x3 /* Active.Available */ #define PCI_EXT_CAP_SRIOV_SIZEOF 64 #define PCI_LTR_MAX_SNOOP_LAT 0x4 #define PCI_LTR_MAX_NOSNOOP_LAT 0x6 #define PCI_LTR_VALUE_MASK 0x000003ff #define PCI_LTR_SCALE_MASK 0x00001c00 #define PCI_LTR_SCALE_SHIFT 10 #define PCI_EXT_CAP_LTR_SIZEOF 8 /* Access Control Service */ #define PCI_ACS_CAP 0x04 /* ACS Capability Register */ #define PCI_ACS_SV 0x0001 /* Source Validation */ #define PCI_ACS_TB 0x0002 /* Translation Blocking */ #define PCI_ACS_RR 0x0004 /* P2P Request Redirect */ #define PCI_ACS_CR 0x0008 /* P2P Completion Redirect */ #define PCI_ACS_UF 0x0010 /* Upstream Forwarding */ #define PCI_ACS_EC 0x0020 /* P2P Egress Control */ #define PCI_ACS_DT 0x0040 /* Direct Translated P2P */ #define PCI_ACS_EGRESS_BITS 0x05 /* ACS Egress Control Vector Size */ #define PCI_ACS_CTRL 0x06 /* ACS Control Register */ #define PCI_ACS_EGRESS_CTL_V 0x08 /* ACS Egress Control Vector */ #define PCI_VSEC_HDR 4 /* extended cap - vendor-specific */ #define PCI_VSEC_HDR_LEN_SHIFT 20 /* shift for length field */ /* SATA capability */ #define PCI_SATA_REGS 4 /* SATA REGs specifier */ #define PCI_SATA_REGS_MASK 0xF /* location - BAR#/inline */ #define PCI_SATA_REGS_INLINE 0xF /* REGS in config space */ #define PCI_SATA_SIZEOF_SHORT 8 #define PCI_SATA_SIZEOF_LONG 16 /* Resizable BARs */ #define PCI_REBAR_CAP 4 /* capability register */ #define PCI_REBAR_CAP_SIZES 0x00FFFFF0 /* supported BAR sizes */ #define PCI_REBAR_CTRL 8 /* control register */ #define PCI_REBAR_CTRL_BAR_IDX 0x00000007 /* BAR index */ #define PCI_REBAR_CTRL_NBAR_MASK 0x000000E0 /* # of resizable BARs */ #define PCI_REBAR_CTRL_NBAR_SHIFT 5 /* shift for # of BARs */ #define PCI_REBAR_CTRL_BAR_SIZE 0x00001F00 /* BAR size */ #define PCI_REBAR_CTRL_BAR_SHIFT 8 /* shift for BAR size */ /* Dynamic Power Allocation */ #define PCI_DPA_CAP 4 /* capability register */ #define PCI_DPA_CAP_SUBSTATE_MASK 0x1F /* # substates - 1 */ #define PCI_DPA_BASE_SIZEOF 16 /* size with 0 substates */ /* TPH Requester */ #define PCI_TPH_CAP 4 /* capability register */ #define PCI_TPH_CAP_LOC_MASK 0x600 /* location mask */ #define PCI_TPH_LOC_NONE 0x000 /* no location */ #define PCI_TPH_LOC_CAP 0x200 /* in capability */ #define PCI_TPH_LOC_MSIX 0x400 /* in MSI-X */ #define PCI_TPH_CAP_ST_MASK 0x07FF0000 /* st table mask */ #define PCI_TPH_CAP_ST_SHIFT 16 /* st table shift */ #define PCI_TPH_BASE_SIZEOF 12 /* size with no st table */ /* Downstream Port Containment */ #define PCI_EXP_DPC_CAP 4 /* DPC Capability */ #define PCI_EXP_DPC_IRQ 0x001F /* Interrupt Message Number */ #define PCI_EXP_DPC_CAP_RP_EXT 0x0020 /* Root Port Extensions */ #define PCI_EXP_DPC_CAP_POISONED_TLP 0x0040 /* Poisoned TLP Egress Blocking Supported */ #define PCI_EXP_DPC_CAP_SW_TRIGGER 0x0080 /* Software Triggering Supported */ #define PCI_EXP_DPC_RP_PIO_LOG_SIZE 0x0F00 /* RP PIO Log Size */ #define PCI_EXP_DPC_CAP_DL_ACTIVE 0x1000 /* ERR_COR signal on DL_Active supported */ #define PCI_EXP_DPC_CTL 6 /* DPC control */ #define PCI_EXP_DPC_CTL_EN_FATAL 0x0001 /* Enable trigger on ERR_FATAL message */ #define PCI_EXP_DPC_CTL_EN_NONFATAL 0x0002 /* Enable trigger on ERR_NONFATAL message */ #define PCI_EXP_DPC_CTL_INT_EN 0x0008 /* DPC Interrupt Enable */ #define PCI_EXP_DPC_STATUS 8 /* DPC Status */ #define PCI_EXP_DPC_STATUS_TRIGGER 0x0001 /* Trigger Status */ #define PCI_EXP_DPC_STATUS_TRIGGER_RSN 0x0006 /* Trigger Reason */ #define PCI_EXP_DPC_STATUS_INTERRUPT 0x0008 /* Interrupt Status */ #define PCI_EXP_DPC_RP_BUSY 0x0010 /* Root Port Busy */ #define PCI_EXP_DPC_STATUS_TRIGGER_RSN_EXT 0x0060 /* Trig Reason Extension */ #define PCI_EXP_DPC_SOURCE_ID 10 /* DPC Source Identifier */ #define PCI_EXP_DPC_RP_PIO_STATUS 0x0C /* RP PIO Status */ #define PCI_EXP_DPC_RP_PIO_MASK 0x10 /* RP PIO Mask */ #define PCI_EXP_DPC_RP_PIO_SEVERITY 0x14 /* RP PIO Severity */ #define PCI_EXP_DPC_RP_PIO_SYSERROR 0x18 /* RP PIO SysError */ #define PCI_EXP_DPC_RP_PIO_EXCEPTION 0x1C /* RP PIO Exception */ #define PCI_EXP_DPC_RP_PIO_HEADER_LOG 0x20 /* RP PIO Header Log */ #define PCI_EXP_DPC_RP_PIO_IMPSPEC_LOG 0x30 /* RP PIO ImpSpec Log */ #define PCI_EXP_DPC_RP_PIO_TLPPREFIX_LOG 0x34 /* RP PIO TLP Prefix Log */ /* Precision Time Measurement */ #define PCI_PTM_CAP 0x04 /* PTM Capability */ #define PCI_PTM_CAP_REQ 0x00000001 /* Requester capable */ #define PCI_PTM_CAP_ROOT 0x00000004 /* Root capable */ #define PCI_PTM_GRANULARITY_MASK 0x0000FF00 /* Clock granularity */ #define PCI_PTM_CTRL 0x08 /* PTM Control */ #define PCI_PTM_CTRL_ENABLE 0x00000001 /* PTM enable */ #define PCI_PTM_CTRL_ROOT 0x00000002 /* Root select */ /* ASPM L1 PM Substates */ #define PCI_L1SS_CAP 0x04 /* Capabilities Register */ #define PCI_L1SS_CAP_PCIPM_L1_2 0x00000001 /* PCI-PM L1.2 Supported */ #define PCI_L1SS_CAP_PCIPM_L1_1 0x00000002 /* PCI-PM L1.1 Supported */ #define PCI_L1SS_CAP_ASPM_L1_2 0x00000004 /* ASPM L1.2 Supported */ #define PCI_L1SS_CAP_ASPM_L1_1 0x00000008 /* ASPM L1.1 Supported */ #define PCI_L1SS_CAP_L1_PM_SS 0x00000010 /* L1 PM Substates Supported */ #define PCI_L1SS_CAP_CM_RESTORE_TIME 0x0000ff00 /* Port Common_Mode_Restore_Time */ #define PCI_L1SS_CAP_P_PWR_ON_SCALE 0x00030000 /* Port T_POWER_ON scale */ #define PCI_L1SS_CAP_P_PWR_ON_VALUE 0x00f80000 /* Port T_POWER_ON value */ #define PCI_L1SS_CTL1 0x08 /* Control 1 Register */ #define PCI_L1SS_CTL1_PCIPM_L1_2 0x00000001 /* PCI-PM L1.2 Enable */ #define PCI_L1SS_CTL1_PCIPM_L1_1 0x00000002 /* PCI-PM L1.1 Enable */ #define PCI_L1SS_CTL1_ASPM_L1_2 0x00000004 /* ASPM L1.2 Enable */ #define PCI_L1SS_CTL1_ASPM_L1_1 0x00000008 /* ASPM L1.1 Enable */ #define PCI_L1SS_CTL1_L1_2_MASK 0x00000005 #define PCI_L1SS_CTL1_L1SS_MASK 0x0000000f #define PCI_L1SS_CTL1_CM_RESTORE_TIME 0x0000ff00 /* Common_Mode_Restore_Time */ #define PCI_L1SS_CTL1_LTR_L12_TH_VALUE 0x03ff0000 /* LTR_L1.2_THRESHOLD_Value */ #define PCI_L1SS_CTL1_LTR_L12_TH_SCALE 0xe0000000 /* LTR_L1.2_THRESHOLD_Scale */ #define PCI_L1SS_CTL2 0x0c /* Control 2 Register */ /* Designated Vendor-Specific (DVSEC, PCI_EXT_CAP_ID_DVSEC) */ #define PCI_DVSEC_HEADER1 0x4 /* Designated Vendor-Specific Header1 */ #define PCI_DVSEC_HEADER1_VID(x) ((x) & 0xffff) #define PCI_DVSEC_HEADER1_REV(x) (((x) >> 16) & 0xf) #define PCI_DVSEC_HEADER1_LEN(x) (((x) >> 20) & 0xfff) #define PCI_DVSEC_HEADER2 0x8 /* Designated Vendor-Specific Header2 */ #define PCI_DVSEC_HEADER2_ID(x) ((x) & 0xffff) #endif /* LINUX_PCI_REGS_H */ linux/fiemap.h000064400000005327151027430560007327 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * FS_IOC_FIEMAP ioctl infrastructure. * * Some portions copyright (C) 2007 Cluster File Systems, Inc * * Authors: Mark Fasheh * Kalpak Shah * Andreas Dilger */ #ifndef _LINUX_FIEMAP_H #define _LINUX_FIEMAP_H #include struct fiemap_extent { __u64 fe_logical; /* logical offset in bytes for the start of * the extent from the beginning of the file */ __u64 fe_physical; /* physical offset in bytes for the start * of the extent from the beginning of the disk */ __u64 fe_length; /* length in bytes for this extent */ __u64 fe_reserved64[2]; __u32 fe_flags; /* FIEMAP_EXTENT_* flags for this extent */ __u32 fe_reserved[3]; }; struct fiemap { __u64 fm_start; /* logical offset (inclusive) at * which to start mapping (in) */ __u64 fm_length; /* logical length of mapping which * userspace wants (in) */ __u32 fm_flags; /* FIEMAP_FLAG_* flags for request (in/out) */ __u32 fm_mapped_extents;/* number of extents that were mapped (out) */ __u32 fm_extent_count; /* size of fm_extents array (in) */ __u32 fm_reserved; struct fiemap_extent fm_extents[0]; /* array of mapped extents (out) */ }; #define FIEMAP_MAX_OFFSET (~0ULL) #define FIEMAP_FLAG_SYNC 0x00000001 /* sync file data before map */ #define FIEMAP_FLAG_XATTR 0x00000002 /* map extended attribute tree */ #define FIEMAP_FLAG_CACHE 0x00000004 /* request caching of the extents */ #define FIEMAP_FLAGS_COMPAT (FIEMAP_FLAG_SYNC | FIEMAP_FLAG_XATTR) #define FIEMAP_EXTENT_LAST 0x00000001 /* Last extent in file. */ #define FIEMAP_EXTENT_UNKNOWN 0x00000002 /* Data location unknown. */ #define FIEMAP_EXTENT_DELALLOC 0x00000004 /* Location still pending. * Sets EXTENT_UNKNOWN. */ #define FIEMAP_EXTENT_ENCODED 0x00000008 /* Data can not be read * while fs is unmounted */ #define FIEMAP_EXTENT_DATA_ENCRYPTED 0x00000080 /* Data is encrypted by fs. * Sets EXTENT_NO_BYPASS. */ #define FIEMAP_EXTENT_NOT_ALIGNED 0x00000100 /* Extent offsets may not be * block aligned. */ #define FIEMAP_EXTENT_DATA_INLINE 0x00000200 /* Data mixed with metadata. * Sets EXTENT_NOT_ALIGNED.*/ #define FIEMAP_EXTENT_DATA_TAIL 0x00000400 /* Multiple files in block. * Sets EXTENT_NOT_ALIGNED.*/ #define FIEMAP_EXTENT_UNWRITTEN 0x00000800 /* Space allocated, but * no data (i.e. zero). */ #define FIEMAP_EXTENT_MERGED 0x00001000 /* File does not natively * support extents. Result * merged for efficiency. */ #define FIEMAP_EXTENT_SHARED 0x00002000 /* Space shared with other * files. */ #endif /* _LINUX_FIEMAP_H */ linux/cn_proc.h000064400000006600151027430560007504 0ustar00/* SPDX-License-Identifier: LGPL-2.1 WITH Linux-syscall-note */ /* * cn_proc.h - process events connector * * Copyright (C) Matt Helsley, IBM Corp. 2005 * Based on cn_fork.h by Nguyen Anh Quynh and Guillaume Thouvenin * Copyright (C) 2005 Nguyen Anh Quynh * Copyright (C) 2005 Guillaume Thouvenin * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2.1 of the GNU Lesser General Public License * as published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef CN_PROC_H #define CN_PROC_H #include /* * Userspace sends this enum to register with the kernel that it is listening * for events on the connector. */ enum proc_cn_mcast_op { PROC_CN_MCAST_LISTEN = 1, PROC_CN_MCAST_IGNORE = 2 }; /* * From the user's point of view, the process * ID is the thread group ID and thread ID is the internal * kernel "pid". So, fields are assigned as follow: * * In user space - In kernel space * * parent process ID = parent->tgid * parent thread ID = parent->pid * child process ID = child->tgid * child thread ID = child->pid */ struct proc_event { enum what { /* Use successive bits so the enums can be used to record * sets of events as well */ PROC_EVENT_NONE = 0x00000000, PROC_EVENT_FORK = 0x00000001, PROC_EVENT_EXEC = 0x00000002, PROC_EVENT_UID = 0x00000004, PROC_EVENT_GID = 0x00000040, PROC_EVENT_SID = 0x00000080, PROC_EVENT_PTRACE = 0x00000100, PROC_EVENT_COMM = 0x00000200, /* "next" should be 0x00000400 */ /* "last" is the last process event: exit, * while "next to last" is coredumping event */ PROC_EVENT_COREDUMP = 0x40000000, PROC_EVENT_EXIT = 0x80000000 } what; __u32 cpu; __u64 __attribute__((aligned(8))) timestamp_ns; /* Number of nano seconds since system boot */ union { /* must be last field of proc_event struct */ struct { __u32 err; } ack; struct fork_proc_event { __kernel_pid_t parent_pid; __kernel_pid_t parent_tgid; __kernel_pid_t child_pid; __kernel_pid_t child_tgid; } fork; struct exec_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; } exec; struct id_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; union { __u32 ruid; /* task uid */ __u32 rgid; /* task gid */ } r; union { __u32 euid; __u32 egid; } e; } id; struct sid_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; } sid; struct ptrace_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; __kernel_pid_t tracer_pid; __kernel_pid_t tracer_tgid; } ptrace; struct comm_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; char comm[16]; } comm; struct coredump_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; __kernel_pid_t parent_pid; __kernel_pid_t parent_tgid; } coredump; struct exit_proc_event { __kernel_pid_t process_pid; __kernel_pid_t process_tgid; __u32 exit_code, exit_signal; __kernel_pid_t parent_pid; __kernel_pid_t parent_tgid; } exit; } event_data; }; #endif /* CN_PROC_H */ linux/signalfd.h000064400000002321151027430560007644 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/signalfd.h * * Copyright (C) 2007 Davide Libenzi * */ #ifndef _LINUX_SIGNALFD_H #define _LINUX_SIGNALFD_H #include /* For O_CLOEXEC and O_NONBLOCK */ #include /* Flags for signalfd4. */ #define SFD_CLOEXEC O_CLOEXEC #define SFD_NONBLOCK O_NONBLOCK struct signalfd_siginfo { __u32 ssi_signo; __s32 ssi_errno; __s32 ssi_code; __u32 ssi_pid; __u32 ssi_uid; __s32 ssi_fd; __u32 ssi_tid; __u32 ssi_band; __u32 ssi_overrun; __u32 ssi_trapno; __s32 ssi_status; __s32 ssi_int; __u64 ssi_ptr; __u64 ssi_utime; __u64 ssi_stime; __u64 ssi_addr; __u16 ssi_addr_lsb; __u16 __pad2; __s32 ssi_syscall; __u64 ssi_call_addr; __u32 ssi_arch; /* * Pad strcture to 128 bytes. Remember to update the * pad size when you add new members. We use a fixed * size structure to avoid compatibility problems with * future versions, and we leave extra space for additional * members. We use fixed size members because this strcture * comes out of a read(2) and we really don't want to have * a compat on read(2). */ __u8 __pad[28]; }; #endif /* _LINUX_SIGNALFD_H */ linux/smc_diag.h000064400000005250151027430560007627 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _SMC_DIAG_H_ #define _SMC_DIAG_H_ #include #include #include /* Request structure */ struct smc_diag_req { __u8 diag_family; __u8 pad[2]; __u8 diag_ext; /* Query extended information */ struct inet_diag_sockid id; }; /* Base info structure. It contains socket identity (addrs/ports/cookie) based * on the internal clcsock, and more SMC-related socket data */ struct smc_diag_msg { __u8 diag_family; __u8 diag_state; __u8 diag_mode; __u8 diag_shutdown; struct inet_diag_sockid id; __u32 diag_uid; __u64 diag_inode; }; /* Mode of a connection */ enum { SMC_DIAG_MODE_SMCR, SMC_DIAG_MODE_FALLBACK_TCP, SMC_DIAG_MODE_SMCD, }; /* Extensions */ enum { SMC_DIAG_NONE, SMC_DIAG_CONNINFO, SMC_DIAG_LGRINFO, SMC_DIAG_SHUTDOWN, SMC_DIAG_DMBINFO, SMC_DIAG_FALLBACK, __SMC_DIAG_MAX, }; #define SMC_DIAG_MAX (__SMC_DIAG_MAX - 1) /* SMC_DIAG_CONNINFO */ struct smc_diag_cursor { __u16 reserved; __u16 wrap; __u32 count; }; struct smc_diag_conninfo { __u32 token; /* unique connection id */ __u32 sndbuf_size; /* size of send buffer */ __u32 rmbe_size; /* size of RMB element */ __u32 peer_rmbe_size; /* size of peer RMB element */ /* local RMB element cursors */ struct smc_diag_cursor rx_prod; /* received producer cursor */ struct smc_diag_cursor rx_cons; /* received consumer cursor */ /* peer RMB element cursors */ struct smc_diag_cursor tx_prod; /* sent producer cursor */ struct smc_diag_cursor tx_cons; /* sent consumer cursor */ __u8 rx_prod_flags; /* received producer flags */ __u8 rx_conn_state_flags; /* recvd connection flags*/ __u8 tx_prod_flags; /* sent producer flags */ __u8 tx_conn_state_flags; /* sent connection flags*/ /* send buffer cursors */ struct smc_diag_cursor tx_prep; /* prepared to be sent cursor */ struct smc_diag_cursor tx_sent; /* sent cursor */ struct smc_diag_cursor tx_fin; /* confirmed sent cursor */ }; /* SMC_DIAG_LINKINFO */ struct smc_diag_linkinfo { __u8 link_id; /* link identifier */ __u8 ibname[IB_DEVICE_NAME_MAX]; /* name of the RDMA device */ __u8 ibport; /* RDMA device port number */ __u8 gid[40]; /* local GID */ __u8 peer_gid[40]; /* peer GID */ }; struct smc_diag_lgrinfo { struct smc_diag_linkinfo lnk[1]; __u8 role; }; struct smc_diag_fallback { __u32 reason; __u32 peer_diagnosis; }; struct smcd_diag_dmbinfo { /* SMC-D Socket internals */ __u32 linkid; /* Link identifier */ __u64 peer_gid; /* Peer GID */ __u64 my_gid; /* My GID */ __u64 token; /* Token of DMB */ __u64 peer_token; /* Token of remote DMBE */ }; #endif /* _SMC_DIAG_H_ */ linux/seg6_local.h000064400000004014151027430560010074 0ustar00/* * SR-IPv6 implementation * * Author: * David Lebrun * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_SEG6_LOCAL_H #define _LINUX_SEG6_LOCAL_H #include enum { SEG6_LOCAL_UNSPEC, SEG6_LOCAL_ACTION, SEG6_LOCAL_SRH, SEG6_LOCAL_TABLE, SEG6_LOCAL_NH4, SEG6_LOCAL_NH6, SEG6_LOCAL_IIF, SEG6_LOCAL_OIF, SEG6_LOCAL_BPF, __SEG6_LOCAL_MAX, }; #define SEG6_LOCAL_MAX (__SEG6_LOCAL_MAX - 1) enum { SEG6_LOCAL_ACTION_UNSPEC = 0, /* node segment */ SEG6_LOCAL_ACTION_END = 1, /* adjacency segment (IPv6 cross-connect) */ SEG6_LOCAL_ACTION_END_X = 2, /* lookup of next seg NH in table */ SEG6_LOCAL_ACTION_END_T = 3, /* decap and L2 cross-connect */ SEG6_LOCAL_ACTION_END_DX2 = 4, /* decap and IPv6 cross-connect */ SEG6_LOCAL_ACTION_END_DX6 = 5, /* decap and IPv4 cross-connect */ SEG6_LOCAL_ACTION_END_DX4 = 6, /* decap and lookup of DA in v6 table */ SEG6_LOCAL_ACTION_END_DT6 = 7, /* decap and lookup of DA in v4 table */ SEG6_LOCAL_ACTION_END_DT4 = 8, /* binding segment with insertion */ SEG6_LOCAL_ACTION_END_B6 = 9, /* binding segment with encapsulation */ SEG6_LOCAL_ACTION_END_B6_ENCAP = 10, /* binding segment with MPLS encap */ SEG6_LOCAL_ACTION_END_BM = 11, /* lookup last seg in table */ SEG6_LOCAL_ACTION_END_S = 12, /* forward to SR-unaware VNF with static proxy */ SEG6_LOCAL_ACTION_END_AS = 13, /* forward to SR-unaware VNF with masquerading */ SEG6_LOCAL_ACTION_END_AM = 14, /* custom BPF action */ SEG6_LOCAL_ACTION_END_BPF = 15, __SEG6_LOCAL_ACTION_MAX, }; #define SEG6_LOCAL_ACTION_MAX (__SEG6_LOCAL_ACTION_MAX - 1) enum { SEG6_LOCAL_BPF_PROG_UNSPEC, SEG6_LOCAL_BPF_PROG, SEG6_LOCAL_BPF_PROG_NAME, __SEG6_LOCAL_BPF_PROG_MAX, }; #define SEG6_LOCAL_BPF_PROG_MAX (__SEG6_LOCAL_BPF_PROG_MAX - 1) #endif linux/dlm.h000064400000004771151027430560006644 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /****************************************************************************** ******************************************************************************* ** ** Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. ** Copyright (C) 2004-2011 Red Hat, Inc. All rights reserved. ** ** This copyrighted material is made available to anyone wishing to use, ** modify, copy, or redistribute it subject to the terms and conditions ** of the GNU General Public License v.2. ** ******************************************************************************* ******************************************************************************/ #ifndef __DLM_DOT_H__ #define __DLM_DOT_H__ /* * Interface to Distributed Lock Manager (DLM) * routines and structures to use DLM lockspaces */ /* Lock levels and flags are here */ #include #include typedef void dlm_lockspace_t; /* * Lock status block * * Use this structure to specify the contents of the lock value block. For a * conversion request, this structure is used to specify the lock ID of the * lock. DLM writes the status of the lock request and the lock ID assigned * to the request in the lock status block. * * sb_lkid: the returned lock ID. It is set on new (non-conversion) requests. * It is available when dlm_lock returns. * * sb_lvbptr: saves or returns the contents of the lock's LVB according to rules * shown for the DLM_LKF_VALBLK flag. * * sb_flags: DLM_SBF_DEMOTED is returned if in the process of promoting a lock, * it was first demoted to NL to avoid conversion deadlock. * DLM_SBF_VALNOTVALID is returned if the resource's LVB is marked invalid. * * sb_status: the returned status of the lock request set prior to AST * execution. Possible return values: * * 0 if lock request was successful * -EAGAIN if request would block and is flagged DLM_LKF_NOQUEUE * -DLM_EUNLOCK if unlock request was successful * -DLM_ECANCEL if a cancel completed successfully * -EDEADLK if a deadlock was detected * -ETIMEDOUT if the lock request was canceled due to a timeout */ #define DLM_SBF_DEMOTED 0x01 #define DLM_SBF_VALNOTVALID 0x02 #define DLM_SBF_ALTMODE 0x04 struct dlm_lksb { int sb_status; __u32 sb_lkid; char sb_flags; char * sb_lvbptr; }; /* dlm_new_lockspace() flags */ #define DLM_LSFL_TIMEWARN 0x00000002 #define DLM_LSFL_FS 0x00000004 #define DLM_LSFL_NEWEXCL 0x00000008 #endif /* __DLM_DOT_H__ */ linux/input.h000064400000037161151027430560007226 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 1999-2002 Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _INPUT_H #define _INPUT_H #include #include #include #include #include "input-event-codes.h" /* * The event structure itself * Note that __USE_TIME_BITS64 is defined by libc based on * application's request to use 64 bit time_t. */ struct input_event { #if (__BITS_PER_LONG != 32 || !defined(__USE_TIME_BITS64)) && !defined(__KERNEL__) struct timeval time; #define input_event_sec time.tv_sec #define input_event_usec time.tv_usec #else __kernel_ulong_t __sec; #if defined(__sparc__) && defined(__arch64__) unsigned int __usec; unsigned int __pad; #else __kernel_ulong_t __usec; #endif #define input_event_sec __sec #define input_event_usec __usec #endif __u16 type; __u16 code; __s32 value; }; /* * Protocol version. */ #define EV_VERSION 0x010001 /* * IOCTLs (0x00 - 0x7f) */ struct input_id { __u16 bustype; __u16 vendor; __u16 product; __u16 version; }; /** * struct input_absinfo - used by EVIOCGABS/EVIOCSABS ioctls * @value: latest reported value for the axis. * @minimum: specifies minimum value for the axis. * @maximum: specifies maximum value for the axis. * @fuzz: specifies fuzz value that is used to filter noise from * the event stream. * @flat: values that are within this value will be discarded by * joydev interface and reported as 0 instead. * @resolution: specifies resolution for the values reported for * the axis. * * Note that input core does not clamp reported values to the * [minimum, maximum] limits, such task is left to userspace. * * The default resolution for main axes (ABS_X, ABS_Y, ABS_Z) * is reported in units per millimeter (units/mm), resolution * for rotational axes (ABS_RX, ABS_RY, ABS_RZ) is reported * in units per radian. * When INPUT_PROP_ACCELEROMETER is set the resolution changes. * The main axes (ABS_X, ABS_Y, ABS_Z) are then reported in * in units per g (units/g) and in units per degree per second * (units/deg/s) for rotational axes (ABS_RX, ABS_RY, ABS_RZ). */ struct input_absinfo { __s32 value; __s32 minimum; __s32 maximum; __s32 fuzz; __s32 flat; __s32 resolution; }; /** * struct input_keymap_entry - used by EVIOCGKEYCODE/EVIOCSKEYCODE ioctls * @scancode: scancode represented in machine-endian form. * @len: length of the scancode that resides in @scancode buffer. * @index: index in the keymap, may be used instead of scancode * @flags: allows to specify how kernel should handle the request. For * example, setting INPUT_KEYMAP_BY_INDEX flag indicates that kernel * should perform lookup in keymap by @index instead of @scancode * @keycode: key code assigned to this scancode * * The structure is used to retrieve and modify keymap data. Users have * option of performing lookup either by @scancode itself or by @index * in keymap entry. EVIOCGKEYCODE will also return scancode or index * (depending on which element was used to perform lookup). */ struct input_keymap_entry { #define INPUT_KEYMAP_BY_INDEX (1 << 0) __u8 flags; __u8 len; __u16 index; __u32 keycode; __u8 scancode[32]; }; struct input_mask { __u32 type; __u32 codes_size; __u64 codes_ptr; }; #define EVIOCGVERSION _IOR('E', 0x01, int) /* get driver version */ #define EVIOCGID _IOR('E', 0x02, struct input_id) /* get device ID */ #define EVIOCGREP _IOR('E', 0x03, unsigned int[2]) /* get repeat settings */ #define EVIOCSREP _IOW('E', 0x03, unsigned int[2]) /* set repeat settings */ #define EVIOCGKEYCODE _IOR('E', 0x04, unsigned int[2]) /* get keycode */ #define EVIOCGKEYCODE_V2 _IOR('E', 0x04, struct input_keymap_entry) #define EVIOCSKEYCODE _IOW('E', 0x04, unsigned int[2]) /* set keycode */ #define EVIOCSKEYCODE_V2 _IOW('E', 0x04, struct input_keymap_entry) #define EVIOCGNAME(len) _IOC(_IOC_READ, 'E', 0x06, len) /* get device name */ #define EVIOCGPHYS(len) _IOC(_IOC_READ, 'E', 0x07, len) /* get physical location */ #define EVIOCGUNIQ(len) _IOC(_IOC_READ, 'E', 0x08, len) /* get unique identifier */ #define EVIOCGPROP(len) _IOC(_IOC_READ, 'E', 0x09, len) /* get device properties */ /** * EVIOCGMTSLOTS(len) - get MT slot values * @len: size of the data buffer in bytes * * The ioctl buffer argument should be binary equivalent to * * struct input_mt_request_layout { * __u32 code; * __s32 values[num_slots]; * }; * * where num_slots is the (arbitrary) number of MT slots to extract. * * The ioctl size argument (len) is the size of the buffer, which * should satisfy len = (num_slots + 1) * sizeof(__s32). If len is * too small to fit all available slots, the first num_slots are * returned. * * Before the call, code is set to the wanted ABS_MT event type. On * return, values[] is filled with the slot values for the specified * ABS_MT code. * * If the request code is not an ABS_MT value, -EINVAL is returned. */ #define EVIOCGMTSLOTS(len) _IOC(_IOC_READ, 'E', 0x0a, len) #define EVIOCGKEY(len) _IOC(_IOC_READ, 'E', 0x18, len) /* get global key state */ #define EVIOCGLED(len) _IOC(_IOC_READ, 'E', 0x19, len) /* get all LEDs */ #define EVIOCGSND(len) _IOC(_IOC_READ, 'E', 0x1a, len) /* get all sounds status */ #define EVIOCGSW(len) _IOC(_IOC_READ, 'E', 0x1b, len) /* get all switch states */ #define EVIOCGBIT(ev,len) _IOC(_IOC_READ, 'E', 0x20 + (ev), len) /* get event bits */ #define EVIOCGABS(abs) _IOR('E', 0x40 + (abs), struct input_absinfo) /* get abs value/limits */ #define EVIOCSABS(abs) _IOW('E', 0xc0 + (abs), struct input_absinfo) /* set abs value/limits */ #define EVIOCSFF _IOW('E', 0x80, struct ff_effect) /* send a force effect to a force feedback device */ #define EVIOCRMFF _IOW('E', 0x81, int) /* Erase a force effect */ #define EVIOCGEFFECTS _IOR('E', 0x84, int) /* Report number of effects playable at the same time */ #define EVIOCGRAB _IOW('E', 0x90, int) /* Grab/Release device */ #define EVIOCREVOKE _IOW('E', 0x91, int) /* Revoke device access */ /** * EVIOCGMASK - Retrieve current event mask * * This ioctl allows user to retrieve the current event mask for specific * event type. The argument must be of type "struct input_mask" and * specifies the event type to query, the address of the receive buffer and * the size of the receive buffer. * * The event mask is a per-client mask that specifies which events are * forwarded to the client. Each event code is represented by a single bit * in the event mask. If the bit is set, the event is passed to the client * normally. Otherwise, the event is filtered and will never be queued on * the client's receive buffer. * * Event masks do not affect global state of the input device. They only * affect the file descriptor they are applied to. * * The default event mask for a client has all bits set, i.e. all events * are forwarded to the client. If the kernel is queried for an unknown * event type or if the receive buffer is larger than the number of * event codes known to the kernel, the kernel returns all zeroes for those * codes. * * At maximum, codes_size bytes are copied. * * This ioctl may fail with ENODEV in case the file is revoked, EFAULT * if the receive-buffer points to invalid memory, or EINVAL if the kernel * does not implement the ioctl. */ #define EVIOCGMASK _IOR('E', 0x92, struct input_mask) /* Get event-masks */ /** * EVIOCSMASK - Set event mask * * This ioctl is the counterpart to EVIOCGMASK. Instead of receiving the * current event mask, this changes the client's event mask for a specific * type. See EVIOCGMASK for a description of event-masks and the * argument-type. * * This ioctl provides full forward compatibility. If the passed event type * is unknown to the kernel, or if the number of event codes specified in * the mask is bigger than what is known to the kernel, the ioctl is still * accepted and applied. However, any unknown codes are left untouched and * stay cleared. That means, the kernel always filters unknown codes * regardless of what the client requests. If the new mask doesn't cover * all known event-codes, all remaining codes are automatically cleared and * thus filtered. * * This ioctl may fail with ENODEV in case the file is revoked. EFAULT is * returned if the receive-buffer points to invalid memory. EINVAL is returned * if the kernel does not implement the ioctl. */ #define EVIOCSMASK _IOW('E', 0x93, struct input_mask) /* Set event-masks */ #define EVIOCSCLOCKID _IOW('E', 0xa0, int) /* Set clockid to be used for timestamps */ /* * IDs. */ #define ID_BUS 0 #define ID_VENDOR 1 #define ID_PRODUCT 2 #define ID_VERSION 3 #define BUS_PCI 0x01 #define BUS_ISAPNP 0x02 #define BUS_USB 0x03 #define BUS_HIL 0x04 #define BUS_BLUETOOTH 0x05 #define BUS_VIRTUAL 0x06 #define BUS_ISA 0x10 #define BUS_I8042 0x11 #define BUS_XTKBD 0x12 #define BUS_RS232 0x13 #define BUS_GAMEPORT 0x14 #define BUS_PARPORT 0x15 #define BUS_AMIGA 0x16 #define BUS_ADB 0x17 #define BUS_I2C 0x18 #define BUS_HOST 0x19 #define BUS_GSC 0x1A #define BUS_ATARI 0x1B #define BUS_SPI 0x1C #define BUS_RMI 0x1D #define BUS_CEC 0x1E #define BUS_INTEL_ISHTP 0x1F /* * MT_TOOL types */ #define MT_TOOL_FINGER 0x00 #define MT_TOOL_PEN 0x01 #define MT_TOOL_PALM 0x02 #define MT_TOOL_DIAL 0x0a #define MT_TOOL_MAX 0x0f /* * Values describing the status of a force-feedback effect */ #define FF_STATUS_STOPPED 0x00 #define FF_STATUS_PLAYING 0x01 #define FF_STATUS_MAX 0x01 /* * Structures used in ioctls to upload effects to a device * They are pieces of a bigger structure (called ff_effect) */ /* * All duration values are expressed in ms. Values above 32767 ms (0x7fff) * should not be used and have unspecified results. */ /** * struct ff_replay - defines scheduling of the force-feedback effect * @length: duration of the effect * @delay: delay before effect should start playing */ struct ff_replay { __u16 length; __u16 delay; }; /** * struct ff_trigger - defines what triggers the force-feedback effect * @button: number of the button triggering the effect * @interval: controls how soon the effect can be re-triggered */ struct ff_trigger { __u16 button; __u16 interval; }; /** * struct ff_envelope - generic force-feedback effect envelope * @attack_length: duration of the attack (ms) * @attack_level: level at the beginning of the attack * @fade_length: duration of fade (ms) * @fade_level: level at the end of fade * * The @attack_level and @fade_level are absolute values; when applying * envelope force-feedback core will convert to positive/negative * value based on polarity of the default level of the effect. * Valid range for the attack and fade levels is 0x0000 - 0x7fff */ struct ff_envelope { __u16 attack_length; __u16 attack_level; __u16 fade_length; __u16 fade_level; }; /** * struct ff_constant_effect - defines parameters of a constant force-feedback effect * @level: strength of the effect; may be negative * @envelope: envelope data */ struct ff_constant_effect { __s16 level; struct ff_envelope envelope; }; /** * struct ff_ramp_effect - defines parameters of a ramp force-feedback effect * @start_level: beginning strength of the effect; may be negative * @end_level: final strength of the effect; may be negative * @envelope: envelope data */ struct ff_ramp_effect { __s16 start_level; __s16 end_level; struct ff_envelope envelope; }; /** * struct ff_condition_effect - defines a spring or friction force-feedback effect * @right_saturation: maximum level when joystick moved all way to the right * @left_saturation: same for the left side * @right_coeff: controls how fast the force grows when the joystick moves * to the right * @left_coeff: same for the left side * @deadband: size of the dead zone, where no force is produced * @center: position of the dead zone */ struct ff_condition_effect { __u16 right_saturation; __u16 left_saturation; __s16 right_coeff; __s16 left_coeff; __u16 deadband; __s16 center; }; /** * struct ff_periodic_effect - defines parameters of a periodic force-feedback effect * @waveform: kind of the effect (wave) * @period: period of the wave (ms) * @magnitude: peak value * @offset: mean value of the wave (roughly) * @phase: 'horizontal' shift * @envelope: envelope data * @custom_len: number of samples (FF_CUSTOM only) * @custom_data: buffer of samples (FF_CUSTOM only) * * Known waveforms - FF_SQUARE, FF_TRIANGLE, FF_SINE, FF_SAW_UP, * FF_SAW_DOWN, FF_CUSTOM. The exact syntax FF_CUSTOM is undefined * for the time being as no driver supports it yet. * * Note: the data pointed by custom_data is copied by the driver. * You can therefore dispose of the memory after the upload/update. */ struct ff_periodic_effect { __u16 waveform; __u16 period; __s16 magnitude; __s16 offset; __u16 phase; struct ff_envelope envelope; __u32 custom_len; __s16 *custom_data; }; /** * struct ff_rumble_effect - defines parameters of a periodic force-feedback effect * @strong_magnitude: magnitude of the heavy motor * @weak_magnitude: magnitude of the light one * * Some rumble pads have two motors of different weight. Strong_magnitude * represents the magnitude of the vibration generated by the heavy one. */ struct ff_rumble_effect { __u16 strong_magnitude; __u16 weak_magnitude; }; /** * struct ff_effect - defines force feedback effect * @type: type of the effect (FF_CONSTANT, FF_PERIODIC, FF_RAMP, FF_SPRING, * FF_FRICTION, FF_DAMPER, FF_RUMBLE, FF_INERTIA, or FF_CUSTOM) * @id: an unique id assigned to an effect * @direction: direction of the effect * @trigger: trigger conditions (struct ff_trigger) * @replay: scheduling of the effect (struct ff_replay) * @u: effect-specific structure (one of ff_constant_effect, ff_ramp_effect, * ff_periodic_effect, ff_condition_effect, ff_rumble_effect) further * defining effect parameters * * This structure is sent through ioctl from the application to the driver. * To create a new effect application should set its @id to -1; the kernel * will return assigned @id which can later be used to update or delete * this effect. * * Direction of the effect is encoded as follows: * 0 deg -> 0x0000 (down) * 90 deg -> 0x4000 (left) * 180 deg -> 0x8000 (up) * 270 deg -> 0xC000 (right) */ struct ff_effect { __u16 type; __s16 id; __u16 direction; struct ff_trigger trigger; struct ff_replay replay; union { struct ff_constant_effect constant; struct ff_ramp_effect ramp; struct ff_periodic_effect periodic; struct ff_condition_effect condition[2]; /* One for each axis */ struct ff_rumble_effect rumble; } u; }; /* * Force feedback effect types */ #define FF_RUMBLE 0x50 #define FF_PERIODIC 0x51 #define FF_CONSTANT 0x52 #define FF_SPRING 0x53 #define FF_FRICTION 0x54 #define FF_DAMPER 0x55 #define FF_INERTIA 0x56 #define FF_RAMP 0x57 #define FF_EFFECT_MIN FF_RUMBLE #define FF_EFFECT_MAX FF_RAMP /* * Force feedback periodic effect types */ #define FF_SQUARE 0x58 #define FF_TRIANGLE 0x59 #define FF_SINE 0x5a #define FF_SAW_UP 0x5b #define FF_SAW_DOWN 0x5c #define FF_CUSTOM 0x5d #define FF_WAVEFORM_MIN FF_SQUARE #define FF_WAVEFORM_MAX FF_CUSTOM /* * Set ff device properties */ #define FF_GAIN 0x60 #define FF_AUTOCENTER 0x61 /* * ff->playback(effect_id = FF_GAIN) is the first effect_id to * cause a collision with another ff method, in this case ff->set_gain(). * Therefore the greatest safe value for effect_id is FF_GAIN - 1, * and thus the total number of effects should never exceed FF_GAIN. */ #define FF_MAX_EFFECTS FF_GAIN #define FF_MAX 0x7f #define FF_CNT (FF_MAX+1) #endif /* _INPUT_H */ linux/time_types.h000064400000002227151027430560010244 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TIME_TYPES_H #define _LINUX_TIME_TYPES_H #include #ifndef __kernel_timespec struct __kernel_timespec { __kernel_time64_t tv_sec; /* seconds */ long long tv_nsec; /* nanoseconds */ }; #endif #ifndef __kernel_itimerspec struct __kernel_itimerspec { struct __kernel_timespec it_interval; /* timer period */ struct __kernel_timespec it_value; /* timer expiration */ }; #endif /* * legacy timeval structure, only embedded in structures that * traditionally used 'timeval' to pass time intervals (not absolute * times). Do not add new users. If user space fails to compile * here, this is probably because it is not y2038 safe and needs to * be changed to use another interface. */ #ifndef __kernel_old_timeval struct __kernel_old_timeval { __kernel_long_t tv_sec; __kernel_long_t tv_usec; }; #endif struct __kernel_old_timespec { __kernel_time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; struct __kernel_sock_timeval { __s64 tv_sec; __s64 tv_usec; }; #endif /* _LINUX_TIME_TYPES_H */ linux/coresight-stm.h000064400000001242151027430560010646 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_CORESIGHT_STM_H_ #define __UAPI_CORESIGHT_STM_H_ #define STM_FLAG_TIMESTAMPED BIT(3) #define STM_FLAG_GUARANTEED BIT(7) /* * The CoreSight STM supports guaranteed and invariant timing * transactions. Guaranteed transactions are guaranteed to be * traced, this might involve stalling the bus or system to * ensure the transaction is accepted by the STM. While invariant * timing transactions are not guaranteed to be traced, they * will take an invariant amount of time regardless of the * state of the STM. */ enum { STM_OPTION_GUARANTEED = 0, STM_OPTION_INVARIANT, }; #endif linux/ipmi_bmc.h000064400000000720151027430560007635 0ustar00/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright (c) 2015-2018, Intel Corporation. */ #ifndef _LINUX_IPMI_BMC_H #define _LINUX_IPMI_BMC_H #include #define __IPMI_BMC_IOCTL_MAGIC 0xB1 #define IPMI_BMC_IOCTL_SET_SMS_ATN _IO(__IPMI_BMC_IOCTL_MAGIC, 0x00) #define IPMI_BMC_IOCTL_CLEAR_SMS_ATN _IO(__IPMI_BMC_IOCTL_MAGIC, 0x01) #define IPMI_BMC_IOCTL_FORCE_ABORT _IO(__IPMI_BMC_IOCTL_MAGIC, 0x02) #endif /* _LINUX_IPMI_BMC_H */ linux/posix_acl.h000064400000002346151027430560010045 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * Copyright (C) 2002 Andreas Gruenbacher * Copyright (C) 2016 Red Hat, Inc. * * This file is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #ifndef __UAPI_POSIX_ACL_H #define __UAPI_POSIX_ACL_H #define ACL_UNDEFINED_ID (-1) /* a_type field in acl_user_posix_entry_t */ #define ACL_TYPE_ACCESS (0x8000) #define ACL_TYPE_DEFAULT (0x4000) /* e_tag entry in struct posix_acl_entry */ #define ACL_USER_OBJ (0x01) #define ACL_USER (0x02) #define ACL_GROUP_OBJ (0x04) #define ACL_GROUP (0x08) #define ACL_MASK (0x10) #define ACL_OTHER (0x20) /* permissions in the e_perm field */ #define ACL_READ (0x04) #define ACL_WRITE (0x02) #define ACL_EXECUTE (0x01) #endif /* __UAPI_POSIX_ACL_H */ linux/blkzoned.h000064400000014720151027430560007673 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Zoned block devices handling. * * Copyright (C) 2015 Seagate Technology PLC * * Written by: Shaun Tancheff * * Modified by: Damien Le Moal * Copyright (C) 2016 Western Digital * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #ifndef _BLKZONED_H #define _BLKZONED_H #include #include /** * enum blk_zone_type - Types of zones allowed in a zoned device. * * @BLK_ZONE_TYPE_CONVENTIONAL: The zone has no write pointer and can be writen * randomly. Zone reset has no effect on the zone. * @BLK_ZONE_TYPE_SEQWRITE_REQ: The zone must be written sequentially * @BLK_ZONE_TYPE_SEQWRITE_PREF: The zone can be written non-sequentially * * Any other value not defined is reserved and must be considered as invalid. */ enum blk_zone_type { BLK_ZONE_TYPE_CONVENTIONAL = 0x1, BLK_ZONE_TYPE_SEQWRITE_REQ = 0x2, BLK_ZONE_TYPE_SEQWRITE_PREF = 0x3, }; /** * enum blk_zone_cond - Condition [state] of a zone in a zoned device. * * @BLK_ZONE_COND_NOT_WP: The zone has no write pointer, it is conventional. * @BLK_ZONE_COND_EMPTY: The zone is empty. * @BLK_ZONE_COND_IMP_OPEN: The zone is open, but not explicitly opened. * @BLK_ZONE_COND_EXP_OPEN: The zones was explicitly opened by an * OPEN ZONE command. * @BLK_ZONE_COND_CLOSED: The zone was [explicitly] closed after writing. * @BLK_ZONE_COND_FULL: The zone is marked as full, possibly by a zone * FINISH ZONE command. * @BLK_ZONE_COND_READONLY: The zone is read-only. * @BLK_ZONE_COND_OFFLINE: The zone is offline (sectors cannot be read/written). * * The Zone Condition state machine in the ZBC/ZAC standards maps the above * deinitions as: * - ZC1: Empty | BLK_ZONE_EMPTY * - ZC2: Implicit Open | BLK_ZONE_COND_IMP_OPEN * - ZC3: Explicit Open | BLK_ZONE_COND_EXP_OPEN * - ZC4: Closed | BLK_ZONE_CLOSED * - ZC5: Full | BLK_ZONE_FULL * - ZC6: Read Only | BLK_ZONE_READONLY * - ZC7: Offline | BLK_ZONE_OFFLINE * * Conditions 0x5 to 0xC are reserved by the current ZBC/ZAC spec and should * be considered invalid. */ enum blk_zone_cond { BLK_ZONE_COND_NOT_WP = 0x0, BLK_ZONE_COND_EMPTY = 0x1, BLK_ZONE_COND_IMP_OPEN = 0x2, BLK_ZONE_COND_EXP_OPEN = 0x3, BLK_ZONE_COND_CLOSED = 0x4, BLK_ZONE_COND_READONLY = 0xD, BLK_ZONE_COND_FULL = 0xE, BLK_ZONE_COND_OFFLINE = 0xF, }; /** * enum blk_zone_report_flags - Feature flags of reported zone descriptors. * * @BLK_ZONE_REP_CAPACITY: Zone descriptor has capacity field. */ enum blk_zone_report_flags { BLK_ZONE_REP_CAPACITY = (1 << 0), }; /** * struct blk_zone - Zone descriptor for BLKREPORTZONE ioctl. * * @start: Zone start in 512 B sector units * @len: Zone length in 512 B sector units * @wp: Zone write pointer location in 512 B sector units * @type: see enum blk_zone_type for possible values * @cond: see enum blk_zone_cond for possible values * @non_seq: Flag indicating that the zone is using non-sequential resources * (for host-aware zoned block devices only). * @reset: Flag indicating that a zone reset is recommended. * @resv: Padding for 8B alignment. * @capacity: Zone usable capacity in 512 B sector units * @reserved: Padding to 64 B to match the ZBC, ZAC and ZNS defined zone * descriptor size. * * start, len, capacity and wp use the regular 512 B sector unit, regardless * of the device logical block size. The overall structure size is 64 B to * match the ZBC, ZAC and ZNS defined zone descriptor and allow support for * future additional zone information. */ struct blk_zone { __u64 start; /* Zone start sector */ __u64 len; /* Zone length in number of sectors */ __u64 wp; /* Zone write pointer position */ __u8 type; /* Zone type */ __u8 cond; /* Zone condition */ __u8 non_seq; /* Non-sequential write resources active */ __u8 reset; /* Reset write pointer recommended */ #ifdef __GENKSYMS__ __u8 reserved[36]; #else __u8 resv[4]; __u64 capacity; /* Zone capacity in number of sectors */ __u8 reserved[24]; #endif }; /** * struct blk_zone_report - BLKREPORTZONE ioctl request/reply * * @sector: starting sector of report * @nr_zones: IN maximum / OUT actual * @flags: one or more flags as defined by enum blk_zone_report_flags. * @zones: Space to hold @nr_zones @zones entries on reply. * * The array of at most @nr_zones must follow this structure in memory. */ struct blk_zone_report { __u64 sector; __u32 nr_zones; #ifdef __GENKSYMS__ __u8 reserved[4]; #else __u32 flags; #endif struct blk_zone zones[0]; }; /** * struct blk_zone_range - BLKRESETZONE/BLKOPENZONE/ * BLKCLOSEZONE/BLKFINISHZONE ioctl * requests * @sector: Starting sector of the first zone to operate on. * @nr_sectors: Total number of sectors of all zones to operate on. */ struct blk_zone_range { __u64 sector; __u64 nr_sectors; }; /** * Zoned block device ioctl's: * * @BLKREPORTZONE: Get zone information. Takes a zone report as argument. * The zone report will start from the zone containing the * sector specified in the report request structure. * @BLKRESETZONE: Reset the write pointer of the zones in the specified * sector range. The sector range must be zone aligned. * @BLKGETZONESZ: Get the device zone size in number of 512 B sectors. * @BLKGETNRZONES: Get the total number of zones of the device. * @BLKOPENZONE: Open the zones in the specified sector range. * The 512 B sector range must be zone aligned. * @BLKCLOSEZONE: Close the zones in the specified sector range. * The 512 B sector range must be zone aligned. * @BLKFINISHZONE: Mark the zones as full in the specified sector range. * The 512 B sector range must be zone aligned. */ #define BLKREPORTZONE _IOWR(0x12, 130, struct blk_zone_report) #define BLKRESETZONE _IOW(0x12, 131, struct blk_zone_range) #define BLKGETZONESZ _IOR(0x12, 132, __u32) #define BLKGETNRZONES _IOR(0x12, 133, __u32) #define BLKOPENZONE _IOW(0x12, 134, struct blk_zone_range) #define BLKCLOSEZONE _IOW(0x12, 135, struct blk_zone_range) #define BLKFINISHZONE _IOW(0x12, 136, struct blk_zone_range) #endif /* _BLKZONED_H */ linux/coff.h000064400000030274151027430560007002 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* This file is derived from the GAS 2.1.4 assembler control file. The GAS product is under the GNU General Public License, version 2 or later. As such, this file is also under that license. If the file format changes in the COFF object, this file should be subsequently updated to reflect the changes. The actual loader module only uses a few of these structures. The full set is documented here because I received the full set. If you wish more information about COFF, then O'Reilly has a very excellent book. */ #define E_SYMNMLEN 8 /* Number of characters in a symbol name */ #define E_FILNMLEN 14 /* Number of characters in a file name */ #define E_DIMNUM 4 /* Number of array dimensions in auxiliary entry */ /* * These defines are byte order independent. There is no alignment of fields * permitted in the structures. Therefore they are declared as characters * and the values loaded from the character positions. It also makes it * nice to have it "endian" independent. */ /* Load a short int from the following tables with little-endian formats */ #define COFF_SHORT_L(ps) ((short)(((unsigned short)((unsigned char)ps[1])<<8)|\ ((unsigned short)((unsigned char)ps[0])))) /* Load a long int from the following tables with little-endian formats */ #define COFF_LONG_L(ps) (((long)(((unsigned long)((unsigned char)ps[3])<<24) |\ ((unsigned long)((unsigned char)ps[2])<<16) |\ ((unsigned long)((unsigned char)ps[1])<<8) |\ ((unsigned long)((unsigned char)ps[0]))))) /* Load a short int from the following tables with big-endian formats */ #define COFF_SHORT_H(ps) ((short)(((unsigned short)((unsigned char)ps[0])<<8)|\ ((unsigned short)((unsigned char)ps[1])))) /* Load a long int from the following tables with big-endian formats */ #define COFF_LONG_H(ps) (((long)(((unsigned long)((unsigned char)ps[0])<<24) |\ ((unsigned long)((unsigned char)ps[1])<<16) |\ ((unsigned long)((unsigned char)ps[2])<<8) |\ ((unsigned long)((unsigned char)ps[3]))))) /* These may be overridden later by brain dead implementations which generate a big-endian header with little-endian data. In that case, generate a replacement macro which tests a flag and uses either of the two above as appropriate. */ #define COFF_LONG(v) COFF_LONG_L(v) #define COFF_SHORT(v) COFF_SHORT_L(v) /*** coff information for Intel 386/486. */ /********************** FILE HEADER **********************/ struct COFF_filehdr { char f_magic[2]; /* magic number */ char f_nscns[2]; /* number of sections */ char f_timdat[4]; /* time & date stamp */ char f_symptr[4]; /* file pointer to symtab */ char f_nsyms[4]; /* number of symtab entries */ char f_opthdr[2]; /* sizeof(optional hdr) */ char f_flags[2]; /* flags */ }; /* * Bits for f_flags: * * F_RELFLG relocation info stripped from file * F_EXEC file is executable (i.e. no unresolved external * references) * F_LNNO line numbers stripped from file * F_LSYMS local symbols stripped from file * F_MINMAL this is a minimal object file (".m") output of fextract * F_UPDATE this is a fully bound update file, output of ogen * F_SWABD this file has had its bytes swabbed (in names) * F_AR16WR this file has the byte ordering of an AR16WR * (e.g. 11/70) machine * F_AR32WR this file has the byte ordering of an AR32WR machine * (e.g. vax and iNTEL 386) * F_AR32W this file has the byte ordering of an AR32W machine * (e.g. 3b,maxi) * F_PATCH file contains "patch" list in optional header * F_NODF (minimal file only) no decision functions for * replaced functions */ #define COFF_F_RELFLG 0000001 #define COFF_F_EXEC 0000002 #define COFF_F_LNNO 0000004 #define COFF_F_LSYMS 0000010 #define COFF_F_MINMAL 0000020 #define COFF_F_UPDATE 0000040 #define COFF_F_SWABD 0000100 #define COFF_F_AR16WR 0000200 #define COFF_F_AR32WR 0000400 #define COFF_F_AR32W 0001000 #define COFF_F_PATCH 0002000 #define COFF_F_NODF 0002000 #define COFF_I386MAGIC 0x14c /* Linux's system */ #if 0 /* Perhaps, someday, these formats may be used. */ #define COFF_I386PTXMAGIC 0x154 #define COFF_I386AIXMAGIC 0x175 /* IBM's AIX system */ #define COFF_I386BADMAG(x) ((COFF_SHORT((x).f_magic) != COFF_I386MAGIC) \ && COFF_SHORT((x).f_magic) != COFF_I386PTXMAGIC \ && COFF_SHORT((x).f_magic) != COFF_I386AIXMAGIC) #else #define COFF_I386BADMAG(x) (COFF_SHORT((x).f_magic) != COFF_I386MAGIC) #endif #define COFF_FILHDR struct COFF_filehdr #define COFF_FILHSZ sizeof(COFF_FILHDR) /********************** AOUT "OPTIONAL HEADER" **********************/ /* Linux COFF must have this "optional" header. Standard COFF has no entry location for the "entry" point. They normally would start with the first location of the .text section. This is not a good idea for linux. So, the use of this "optional" header is not optional. It is required. Do not be tempted to assume that the size of the optional header is a constant and simply index the next byte by the size of this structure. Use the 'f_opthdr' field in the main coff header for the size of the structure actually written to the file!! */ typedef struct { char magic[2]; /* type of file */ char vstamp[2]; /* version stamp */ char tsize[4]; /* text size in bytes, padded to FW bdry */ char dsize[4]; /* initialized data " " */ char bsize[4]; /* uninitialized data " " */ char entry[4]; /* entry pt. */ char text_start[4]; /* base of text used for this file */ char data_start[4]; /* base of data used for this file */ } COFF_AOUTHDR; #define COFF_AOUTSZ (sizeof(COFF_AOUTHDR)) #define COFF_STMAGIC 0401 #define COFF_OMAGIC 0404 #define COFF_JMAGIC 0407 /* dirty text and data image, can't share */ #define COFF_DMAGIC 0410 /* dirty text segment, data aligned */ #define COFF_ZMAGIC 0413 /* The proper magic number for executables */ #define COFF_SHMAGIC 0443 /* shared library header */ /********************** SECTION HEADER **********************/ struct COFF_scnhdr { char s_name[8]; /* section name */ char s_paddr[4]; /* physical address, aliased s_nlib */ char s_vaddr[4]; /* virtual address */ char s_size[4]; /* section size */ char s_scnptr[4]; /* file ptr to raw data for section */ char s_relptr[4]; /* file ptr to relocation */ char s_lnnoptr[4]; /* file ptr to line numbers */ char s_nreloc[2]; /* number of relocation entries */ char s_nlnno[2]; /* number of line number entries */ char s_flags[4]; /* flags */ }; #define COFF_SCNHDR struct COFF_scnhdr #define COFF_SCNHSZ sizeof(COFF_SCNHDR) /* * names of "special" sections */ #define COFF_TEXT ".text" #define COFF_DATA ".data" #define COFF_BSS ".bss" #define COFF_COMMENT ".comment" #define COFF_LIB ".lib" #define COFF_SECT_TEXT 0 /* Section for instruction code */ #define COFF_SECT_DATA 1 /* Section for initialized globals */ #define COFF_SECT_BSS 2 /* Section for un-initialized globals */ #define COFF_SECT_REQD 3 /* Minimum number of sections for good file */ #define COFF_STYP_REG 0x00 /* regular segment */ #define COFF_STYP_DSECT 0x01 /* dummy segment */ #define COFF_STYP_NOLOAD 0x02 /* no-load segment */ #define COFF_STYP_GROUP 0x04 /* group segment */ #define COFF_STYP_PAD 0x08 /* .pad segment */ #define COFF_STYP_COPY 0x10 /* copy section */ #define COFF_STYP_TEXT 0x20 /* .text segment */ #define COFF_STYP_DATA 0x40 /* .data segment */ #define COFF_STYP_BSS 0x80 /* .bss segment */ #define COFF_STYP_INFO 0x200 /* .comment section */ #define COFF_STYP_OVER 0x400 /* overlay section */ #define COFF_STYP_LIB 0x800 /* library section */ /* * Shared libraries have the following section header in the data field for * each library. */ struct COFF_slib { char sl_entsz[4]; /* Size of this entry */ char sl_pathndx[4]; /* size of the header field */ }; #define COFF_SLIBHD struct COFF_slib #define COFF_SLIBSZ sizeof(COFF_SLIBHD) /********************** LINE NUMBERS **********************/ /* 1 line number entry for every "breakpointable" source line in a section. * Line numbers are grouped on a per function basis; first entry in a function * grouping will have l_lnno = 0 and in place of physical address will be the * symbol table index of the function name. */ struct COFF_lineno { union { char l_symndx[4]; /* function name symbol index, iff l_lnno == 0*/ char l_paddr[4]; /* (physical) address of line number */ } l_addr; char l_lnno[2]; /* line number */ }; #define COFF_LINENO struct COFF_lineno #define COFF_LINESZ 6 /********************** SYMBOLS **********************/ #define COFF_E_SYMNMLEN 8 /* # characters in a short symbol name */ #define COFF_E_FILNMLEN 14 /* # characters in a file name */ #define COFF_E_DIMNUM 4 /* # array dimensions in auxiliary entry */ /* * All symbols and sections have the following definition */ struct COFF_syment { union { char e_name[E_SYMNMLEN]; /* Symbol name (first 8 characters) */ struct { char e_zeroes[4]; /* Leading zeros */ char e_offset[4]; /* Offset if this is a header section */ } e; } e; char e_value[4]; /* Value (address) of the segment */ char e_scnum[2]; /* Section number */ char e_type[2]; /* Type of section */ char e_sclass[1]; /* Loader class */ char e_numaux[1]; /* Number of auxiliary entries which follow */ }; #define COFF_N_BTMASK (0xf) /* Mask for important class bits */ #define COFF_N_TMASK (0x30) /* Mask for important type bits */ #define COFF_N_BTSHFT (4) /* # bits to shift class field */ #define COFF_N_TSHIFT (2) /* # bits to shift type field */ /* * Auxiliary entries because the main table is too limiting. */ union COFF_auxent { /* * Debugger information */ struct { char x_tagndx[4]; /* str, un, or enum tag indx */ union { struct { char x_lnno[2]; /* declaration line number */ char x_size[2]; /* str/union/array size */ } x_lnsz; char x_fsize[4]; /* size of function */ } x_misc; union { struct { /* if ISFCN, tag, or .bb */ char x_lnnoptr[4]; /* ptr to fcn line # */ char x_endndx[4]; /* entry ndx past block end */ } x_fcn; struct { /* if ISARY, up to 4 dimen. */ char x_dimen[E_DIMNUM][2]; } x_ary; } x_fcnary; char x_tvndx[2]; /* tv index */ } x_sym; /* * Source file names (debugger information) */ union { char x_fname[E_FILNMLEN]; struct { char x_zeroes[4]; char x_offset[4]; } x_n; } x_file; /* * Section information */ struct { char x_scnlen[4]; /* section length */ char x_nreloc[2]; /* # relocation entries */ char x_nlinno[2]; /* # line numbers */ } x_scn; /* * Transfer vector (branch table) */ struct { char x_tvfill[4]; /* tv fill value */ char x_tvlen[2]; /* length of .tv */ char x_tvran[2][2]; /* tv range */ } x_tv; /* info about .tv section (in auxent of symbol .tv)) */ }; #define COFF_SYMENT struct COFF_syment #define COFF_SYMESZ 18 #define COFF_AUXENT union COFF_auxent #define COFF_AUXESZ 18 #define COFF_ETEXT "etext" /********************** RELOCATION DIRECTIVES **********************/ struct COFF_reloc { char r_vaddr[4]; /* Virtual address of item */ char r_symndx[4]; /* Symbol index in the symtab */ char r_type[2]; /* Relocation type */ }; #define COFF_RELOC struct COFF_reloc #define COFF_RELSZ 10 #define COFF_DEF_DATA_SECTION_ALIGNMENT 4 #define COFF_DEF_BSS_SECTION_ALIGNMENT 4 #define COFF_DEF_TEXT_SECTION_ALIGNMENT 4 /* For new sections we haven't heard of before */ #define COFF_DEF_SECTION_ALIGNMENT 4 linux/tdx-guest.h000064400000002431151027430560010003 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Userspace interface for TDX guest driver * * Copyright (C) 2022 Intel Corporation */ #ifndef _LINUX_TDX_GUEST_H_ #define _LINUX_TDX_GUEST_H_ #include #include /* Length of the REPORTDATA used in TDG.MR.REPORT TDCALL */ #define TDX_REPORTDATA_LEN 64 /* Length of TDREPORT used in TDG.MR.REPORT TDCALL */ #define TDX_REPORT_LEN 1024 /** * struct tdx_report_req - Request struct for TDX_CMD_GET_REPORT0 IOCTL. * * @reportdata: User buffer with REPORTDATA to be included into TDREPORT. * Typically it can be some nonce provided by attestation * service, so the generated TDREPORT can be uniquely verified. * @tdreport: User buffer to store TDREPORT output from TDCALL[TDG.MR.REPORT]. */ struct tdx_report_req { __u8 reportdata[TDX_REPORTDATA_LEN]; __u8 tdreport[TDX_REPORT_LEN]; }; /* * TDX_CMD_GET_REPORT0 - Get TDREPORT0 (a.k.a. TDREPORT subtype 0) using * TDCALL[TDG.MR.REPORT] * * Return 0 on success, -EIO on TDCALL execution failure, and * standard errno on other general error cases. */ #define TDX_CMD_GET_REPORT0 _IOWR('T', 1, struct tdx_report_req) #endif /* _LINUX_TDX_GUEST_H_ */ linux/dlmconstants.h000064400000011730151027430560010572 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /****************************************************************************** ******************************************************************************* ** ** Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. ** Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved. ** ** This copyrighted material is made available to anyone wishing to use, ** modify, copy, or redistribute it subject to the terms and conditions ** of the GNU General Public License v.2. ** ******************************************************************************* ******************************************************************************/ #ifndef __DLMCONSTANTS_DOT_H__ #define __DLMCONSTANTS_DOT_H__ /* * Constants used by DLM interface. */ #define DLM_LOCKSPACE_LEN 64 #define DLM_RESNAME_MAXLEN 64 /* * Lock Modes */ #define DLM_LOCK_IV (-1) /* invalid */ #define DLM_LOCK_NL 0 /* null */ #define DLM_LOCK_CR 1 /* concurrent read */ #define DLM_LOCK_CW 2 /* concurrent write */ #define DLM_LOCK_PR 3 /* protected read */ #define DLM_LOCK_PW 4 /* protected write */ #define DLM_LOCK_EX 5 /* exclusive */ /* * Flags to dlm_lock * * DLM_LKF_NOQUEUE * * Do not queue the lock request on the wait queue if it cannot be granted * immediately. If the lock cannot be granted because of this flag, DLM will * either return -EAGAIN from the dlm_lock call or will return 0 from * dlm_lock and -EAGAIN in the lock status block when the AST is executed. * * DLM_LKF_CANCEL * * Used to cancel a pending lock request or conversion. A converting lock is * returned to its previously granted mode. * * DLM_LKF_CONVERT * * Indicates a lock conversion request. For conversions the name and namelen * are ignored and the lock ID in the LKSB is used to identify the lock. * * DLM_LKF_VALBLK * * Requests DLM to return the current contents of the lock value block in the * lock status block. When this flag is set in a lock conversion from PW or EX * modes, DLM assigns the value specified in the lock status block to the lock * value block of the lock resource. The LVB is a DLM_LVB_LEN size array * containing application-specific information. * * DLM_LKF_QUECVT * * Force a conversion request to be queued, even if it is compatible with * the granted modes of other locks on the same resource. * * DLM_LKF_IVVALBLK * * Invalidate the lock value block. * * DLM_LKF_CONVDEADLK * * Allows the dlm to resolve conversion deadlocks internally by demoting the * granted mode of a converting lock to NL. The DLM_SBF_DEMOTED flag is * returned for a conversion that's been effected by this. * * DLM_LKF_PERSISTENT * * Only relevant to locks originating in userspace. A persistent lock will not * be removed if the process holding the lock exits. * * DLM_LKF_NODLCKWT * * Do not cancel the lock if it gets into conversion deadlock. * Exclude this lock from being monitored due to DLM_LSFL_TIMEWARN. * * DLM_LKF_NODLCKBLK * * net yet implemented * * DLM_LKF_EXPEDITE * * Used only with new requests for NL mode locks. Tells the lock manager * to grant the lock, ignoring other locks in convert and wait queues. * * DLM_LKF_NOQUEUEBAST * * Send blocking AST's before returning -EAGAIN to the caller. It is only * used along with the NOQUEUE flag. Blocking AST's are not sent for failed * NOQUEUE requests otherwise. * * DLM_LKF_HEADQUE * * Add a lock to the head of the convert or wait queue rather than the tail. * * DLM_LKF_NOORDER * * Disregard the standard grant order rules and grant a lock as soon as it * is compatible with other granted locks. * * DLM_LKF_ORPHAN * * Acquire an orphan lock. * * DLM_LKF_ALTPR * * If the requested mode cannot be granted immediately, try to grant the lock * in PR mode instead. If this alternate mode is granted instead of the * requested mode, DLM_SBF_ALTMODE is returned in the lksb. * * DLM_LKF_ALTCW * * The same as ALTPR, but the alternate mode is CW. * * DLM_LKF_FORCEUNLOCK * * Unlock the lock even if it is converting or waiting or has sublocks. * Only really for use by the userland device.c code. * */ #define DLM_LKF_NOQUEUE 0x00000001 #define DLM_LKF_CANCEL 0x00000002 #define DLM_LKF_CONVERT 0x00000004 #define DLM_LKF_VALBLK 0x00000008 #define DLM_LKF_QUECVT 0x00000010 #define DLM_LKF_IVVALBLK 0x00000020 #define DLM_LKF_CONVDEADLK 0x00000040 #define DLM_LKF_PERSISTENT 0x00000080 #define DLM_LKF_NODLCKWT 0x00000100 #define DLM_LKF_NODLCKBLK 0x00000200 #define DLM_LKF_EXPEDITE 0x00000400 #define DLM_LKF_NOQUEUEBAST 0x00000800 #define DLM_LKF_HEADQUE 0x00001000 #define DLM_LKF_NOORDER 0x00002000 #define DLM_LKF_ORPHAN 0x00004000 #define DLM_LKF_ALTPR 0x00008000 #define DLM_LKF_ALTCW 0x00010000 #define DLM_LKF_FORCEUNLOCK 0x00020000 #define DLM_LKF_TIMEOUT 0x00040000 /* * Some return codes that are not in errno.h */ #define DLM_ECANCEL 0x10001 #define DLM_EUNLOCK 0x10002 #endif /* __DLMCONSTANTS_DOT_H__ */ linux/can/raw.h000064400000005445151027430560007421 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * linux/can/raw.h * * Definitions for raw CAN sockets * * Authors: Oliver Hartkopp * Urs Thuermann * Copyright (c) 2002-2007 Volkswagen Group Electronic Research * 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. Neither the name of Volkswagen nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * The provided data structures and external interfaces from this code * are not restricted to be used by modules with a GPL compatible license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #ifndef _CAN_RAW_H #define _CAN_RAW_H #include #define SOL_CAN_RAW (SOL_CAN_BASE + CAN_RAW) /* for socket options affecting the socket (not the global system) */ enum { CAN_RAW_FILTER = 1, /* set 0 .. n can_filter(s) */ CAN_RAW_ERR_FILTER, /* set filter for error frames */ CAN_RAW_LOOPBACK, /* local loopback (default:on) */ CAN_RAW_RECV_OWN_MSGS, /* receive my own msgs (default:off) */ CAN_RAW_FD_FRAMES, /* allow CAN FD frames (default:off) */ CAN_RAW_JOIN_FILTERS, /* all filters must match to trigger */ }; #endif /* !_UAPI_CAN_RAW_H */ linux/can/gw.h000064400000016416151027430560007245 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * linux/can/gw.h * * Definitions for CAN frame Gateway/Router/Bridge * * Author: Oliver Hartkopp * Copyright (c) 2011 Volkswagen Group Electronic Research * 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. Neither the name of Volkswagen nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * The provided data structures and external interfaces from this code * are not restricted to be used by modules with a GPL compatible license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #ifndef _CAN_GW_H #define _CAN_GW_H #include #include struct rtcanmsg { __u8 can_family; __u8 gwtype; __u16 flags; }; /* CAN gateway types */ enum { CGW_TYPE_UNSPEC, CGW_TYPE_CAN_CAN, /* CAN->CAN routing */ __CGW_TYPE_MAX }; #define CGW_TYPE_MAX (__CGW_TYPE_MAX - 1) /* CAN rtnetlink attribute definitions */ enum { CGW_UNSPEC, CGW_MOD_AND, /* CAN frame modification binary AND */ CGW_MOD_OR, /* CAN frame modification binary OR */ CGW_MOD_XOR, /* CAN frame modification binary XOR */ CGW_MOD_SET, /* CAN frame modification set alternate values */ CGW_CS_XOR, /* set data[] XOR checksum into data[index] */ CGW_CS_CRC8, /* set data[] CRC8 checksum into data[index] */ CGW_HANDLED, /* number of handled CAN frames */ CGW_DROPPED, /* number of dropped CAN frames */ CGW_SRC_IF, /* ifindex of source network interface */ CGW_DST_IF, /* ifindex of destination network interface */ CGW_FILTER, /* specify struct can_filter on source CAN device */ CGW_DELETED, /* number of deleted CAN frames (see max_hops param) */ CGW_LIM_HOPS, /* limit the number of hops of this specific rule */ CGW_MOD_UID, /* user defined identifier for modification updates */ __CGW_MAX }; #define CGW_MAX (__CGW_MAX - 1) #define CGW_FLAGS_CAN_ECHO 0x01 #define CGW_FLAGS_CAN_SRC_TSTAMP 0x02 #define CGW_FLAGS_CAN_IIF_TX_OK 0x04 #define CGW_MOD_FUNCS 4 /* AND OR XOR SET */ /* CAN frame elements that are affected by curr. 3 CAN frame modifications */ #define CGW_MOD_ID 0x01 #define CGW_MOD_DLC 0x02 #define CGW_MOD_DATA 0x04 #define CGW_FRAME_MODS 3 /* ID DLC DATA */ #define MAX_MODFUNCTIONS (CGW_MOD_FUNCS * CGW_FRAME_MODS) struct cgw_frame_mod { struct can_frame cf; __u8 modtype; } __attribute__((packed)); #define CGW_MODATTR_LEN sizeof(struct cgw_frame_mod) struct cgw_csum_xor { __s8 from_idx; __s8 to_idx; __s8 result_idx; __u8 init_xor_val; } __attribute__((packed)); struct cgw_csum_crc8 { __s8 from_idx; __s8 to_idx; __s8 result_idx; __u8 init_crc_val; __u8 final_xor_val; __u8 crctab[256]; __u8 profile; __u8 profile_data[20]; } __attribute__((packed)); /* length of checksum operation parameters. idx = index in CAN frame data[] */ #define CGW_CS_XOR_LEN sizeof(struct cgw_csum_xor) #define CGW_CS_CRC8_LEN sizeof(struct cgw_csum_crc8) /* CRC8 profiles (compute CRC for additional data elements - see below) */ enum { CGW_CRC8PRF_UNSPEC, CGW_CRC8PRF_1U8, /* compute one additional u8 value */ CGW_CRC8PRF_16U8, /* u8 value table indexed by data[1] & 0xF */ CGW_CRC8PRF_SFFID_XOR, /* (can_id & 0xFF) ^ (can_id >> 8 & 0xFF) */ __CGW_CRC8PRF_MAX }; #define CGW_CRC8PRF_MAX (__CGW_CRC8PRF_MAX - 1) /* * CAN rtnetlink attribute contents in detail * * CGW_XXX_IF (length 4 bytes): * Sets an interface index for source/destination network interfaces. * For the CAN->CAN gwtype the indices of _two_ CAN interfaces are mandatory. * * CGW_FILTER (length 8 bytes): * Sets a CAN receive filter for the gateway job specified by the * struct can_filter described in include/linux/can.h * * CGW_MOD_(AND|OR|XOR|SET) (length 17 bytes): * Specifies a modification that's done to a received CAN frame before it is * send out to the destination interface. * * data used as operator * affected CAN frame elements * * CGW_LIM_HOPS (length 1 byte): * Limit the number of hops of this specific rule. Usually the received CAN * frame can be processed as much as 'max_hops' times (which is given at module * load time of the can-gw module). This value is used to reduce the number of * possible hops for this gateway rule to a value smaller then max_hops. * * CGW_MOD_UID (length 4 bytes): * Optional non-zero user defined routing job identifier to alter existing * modification settings at runtime. * * CGW_CS_XOR (length 4 bytes): * Set a simple XOR checksum starting with an initial value into * data[result-idx] using data[start-idx] .. data[end-idx] * * The XOR checksum is calculated like this: * * xor = init_xor_val * * for (i = from_idx .. to_idx) * xor ^= can_frame.data[i] * * can_frame.data[ result_idx ] = xor * * CGW_CS_CRC8 (length 282 bytes): * Set a CRC8 value into data[result-idx] using a given 256 byte CRC8 table, * a given initial value and a defined input data[start-idx] .. data[end-idx]. * Finally the result value is XOR'ed with the final_xor_val. * * The CRC8 checksum is calculated like this: * * crc = init_crc_val * * for (i = from_idx .. to_idx) * crc = crctab[ crc ^ can_frame.data[i] ] * * can_frame.data[ result_idx ] = crc ^ final_xor_val * * The calculated CRC may contain additional source data elements that can be * defined in the handling of 'checksum profiles' e.g. shown in AUTOSAR specs * like http://www.autosar.org/download/R4.0/AUTOSAR_SWS_E2ELibrary.pdf * E.g. the profile_data[] may contain additional u8 values (called DATA_IDs) * that are used depending on counter values inside the CAN frame data[]. * So far only three profiles have been implemented for illustration. * * Remark: In general the attribute data is a linear buffer. * Beware of sending unpacked or aligned structs! */ #endif /* !_UAPI_CAN_GW_H */ linux/can/vxcan.h000064400000000343151027430560007737 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _CAN_VXCAN_H #define _CAN_VXCAN_H enum { VXCAN_INFO_UNSPEC, VXCAN_INFO_PEER, __VXCAN_INFO_MAX #define VXCAN_INFO_MAX (__VXCAN_INFO_MAX - 1) }; #endif linux/can/netlink.h000064400000007625151027430560010276 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/can/netlink.h * * Definitions for the CAN netlink interface * * Copyright (c) 2009 Wolfgang Grandegger * * This program is free software; you can redistribute it and/or modify * it under the terms of the version 2 of the GNU General Public License * as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _CAN_NETLINK_H #define _CAN_NETLINK_H #include /* * CAN bit-timing parameters * * For further information, please read chapter "8 BIT TIMING * REQUIREMENTS" of the "Bosch CAN Specification version 2.0" * at http://www.semiconductors.bosch.de/pdf/can2spec.pdf. */ struct can_bittiming { __u32 bitrate; /* Bit-rate in bits/second */ __u32 sample_point; /* Sample point in one-tenth of a percent */ __u32 tq; /* Time quanta (TQ) in nanoseconds */ __u32 prop_seg; /* Propagation segment in TQs */ __u32 phase_seg1; /* Phase buffer segment 1 in TQs */ __u32 phase_seg2; /* Phase buffer segment 2 in TQs */ __u32 sjw; /* Synchronisation jump width in TQs */ __u32 brp; /* Bit-rate prescaler */ }; /* * CAN harware-dependent bit-timing constant * * Used for calculating and checking bit-timing parameters */ struct can_bittiming_const { char name[16]; /* Name of the CAN controller hardware */ __u32 tseg1_min; /* Time segement 1 = prop_seg + phase_seg1 */ __u32 tseg1_max; __u32 tseg2_min; /* Time segement 2 = phase_seg2 */ __u32 tseg2_max; __u32 sjw_max; /* Synchronisation jump width */ __u32 brp_min; /* Bit-rate prescaler */ __u32 brp_max; __u32 brp_inc; }; /* * CAN clock parameters */ struct can_clock { __u32 freq; /* CAN system clock frequency in Hz */ }; /* * CAN operational and error states */ enum can_state { CAN_STATE_ERROR_ACTIVE = 0, /* RX/TX error count < 96 */ CAN_STATE_ERROR_WARNING, /* RX/TX error count < 128 */ CAN_STATE_ERROR_PASSIVE, /* RX/TX error count < 256 */ CAN_STATE_BUS_OFF, /* RX/TX error count >= 256 */ CAN_STATE_STOPPED, /* Device is stopped */ CAN_STATE_SLEEPING, /* Device is sleeping */ CAN_STATE_MAX }; /* * CAN bus error counters */ struct can_berr_counter { __u16 txerr; __u16 rxerr; }; /* * CAN controller mode */ struct can_ctrlmode { __u32 mask; __u32 flags; }; #define CAN_CTRLMODE_LOOPBACK 0x01 /* Loopback mode */ #define CAN_CTRLMODE_LISTENONLY 0x02 /* Listen-only mode */ #define CAN_CTRLMODE_3_SAMPLES 0x04 /* Triple sampling mode */ #define CAN_CTRLMODE_ONE_SHOT 0x08 /* One-Shot mode */ #define CAN_CTRLMODE_BERR_REPORTING 0x10 /* Bus-error reporting */ #define CAN_CTRLMODE_FD 0x20 /* CAN FD mode */ #define CAN_CTRLMODE_PRESUME_ACK 0x40 /* Ignore missing CAN ACKs */ #define CAN_CTRLMODE_FD_NON_ISO 0x80 /* CAN FD in non-ISO mode */ /* * CAN device statistics */ struct can_device_stats { __u32 bus_error; /* Bus errors */ __u32 error_warning; /* Changes to error warning state */ __u32 error_passive; /* Changes to error passive state */ __u32 bus_off; /* Changes to bus off state */ __u32 arbitration_lost; /* Arbitration lost errors */ __u32 restarts; /* CAN controller re-starts */ }; /* * CAN netlink interface */ enum { IFLA_CAN_UNSPEC, IFLA_CAN_BITTIMING, IFLA_CAN_BITTIMING_CONST, IFLA_CAN_CLOCK, IFLA_CAN_STATE, IFLA_CAN_CTRLMODE, IFLA_CAN_RESTART_MS, IFLA_CAN_RESTART, IFLA_CAN_BERR_COUNTER, IFLA_CAN_DATA_BITTIMING, IFLA_CAN_DATA_BITTIMING_CONST, IFLA_CAN_TERMINATION, IFLA_CAN_TERMINATION_CONST, IFLA_CAN_BITRATE_CONST, IFLA_CAN_DATA_BITRATE_CONST, IFLA_CAN_BITRATE_MAX, __IFLA_CAN_MAX }; #define IFLA_CAN_MAX (__IFLA_CAN_MAX - 1) /* u16 termination range: 1..65535 Ohms */ #define CAN_TERMINATION_DISABLED 0 #endif /* !_UAPI_CAN_NETLINK_H */ linux/can/bcm.h000064400000010017151027430560007360 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * linux/can/bcm.h * * Definitions for CAN Broadcast Manager (BCM) * * Author: Oliver Hartkopp * Copyright (c) 2002-2007 Volkswagen Group Electronic Research * 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. Neither the name of Volkswagen nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * The provided data structures and external interfaces from this code * are not restricted to be used by modules with a GPL compatible license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #ifndef _CAN_BCM_H #define _CAN_BCM_H #include #include struct bcm_timeval { long tv_sec; long tv_usec; }; /** * struct bcm_msg_head - head of messages to/from the broadcast manager * @opcode: opcode, see enum below. * @flags: special flags, see below. * @count: number of frames to send before changing interval. * @ival1: interval for the first @count frames. * @ival2: interval for the following frames. * @can_id: CAN ID of frames to be sent or received. * @nframes: number of frames appended to the message head. * @frames: array of CAN frames. */ struct bcm_msg_head { __u32 opcode; __u32 flags; __u32 count; struct bcm_timeval ival1, ival2; canid_t can_id; __u32 nframes; struct can_frame frames[0]; }; enum { TX_SETUP = 1, /* create (cyclic) transmission task */ TX_DELETE, /* remove (cyclic) transmission task */ TX_READ, /* read properties of (cyclic) transmission task */ TX_SEND, /* send one CAN frame */ RX_SETUP, /* create RX content filter subscription */ RX_DELETE, /* remove RX content filter subscription */ RX_READ, /* read properties of RX content filter subscription */ TX_STATUS, /* reply to TX_READ request */ TX_EXPIRED, /* notification on performed transmissions (count=0) */ RX_STATUS, /* reply to RX_READ request */ RX_TIMEOUT, /* cyclic message is absent */ RX_CHANGED /* updated CAN frame (detected content change) */ }; #define SETTIMER 0x0001 #define STARTTIMER 0x0002 #define TX_COUNTEVT 0x0004 #define TX_ANNOUNCE 0x0008 #define TX_CP_CAN_ID 0x0010 #define RX_FILTER_ID 0x0020 #define RX_CHECK_DLC 0x0040 #define RX_NO_AUTOTIMER 0x0080 #define RX_ANNOUNCE_RESUME 0x0100 #define TX_RESET_MULTI_IDX 0x0200 #define RX_RTR_FRAME 0x0400 #define CAN_FD_FRAME 0x0800 #endif /* !_UAPI_CAN_BCM_H */ linux/can/error.h000064400000014715151027430560007761 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * linux/can/error.h * * Definitions of the CAN error messages to be filtered and passed to the user. * * Author: Oliver Hartkopp * Copyright (c) 2002-2007 Volkswagen Group Electronic Research * 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. Neither the name of Volkswagen nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * The provided data structures and external interfaces from this code * are not restricted to be used by modules with a GPL compatible license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #ifndef _CAN_ERROR_H #define _CAN_ERROR_H #define CAN_ERR_DLC 8 /* dlc for error message frames */ /* error class (mask) in can_id */ #define CAN_ERR_TX_TIMEOUT 0x00000001U /* TX timeout (by netdevice driver) */ #define CAN_ERR_LOSTARB 0x00000002U /* lost arbitration / data[0] */ #define CAN_ERR_CRTL 0x00000004U /* controller problems / data[1] */ #define CAN_ERR_PROT 0x00000008U /* protocol violations / data[2..3] */ #define CAN_ERR_TRX 0x00000010U /* transceiver status / data[4] */ #define CAN_ERR_ACK 0x00000020U /* received no ACK on transmission */ #define CAN_ERR_BUSOFF 0x00000040U /* bus off */ #define CAN_ERR_BUSERROR 0x00000080U /* bus error (may flood!) */ #define CAN_ERR_RESTARTED 0x00000100U /* controller restarted */ /* arbitration lost in bit ... / data[0] */ #define CAN_ERR_LOSTARB_UNSPEC 0x00 /* unspecified */ /* else bit number in bitstream */ /* error status of CAN-controller / data[1] */ #define CAN_ERR_CRTL_UNSPEC 0x00 /* unspecified */ #define CAN_ERR_CRTL_RX_OVERFLOW 0x01 /* RX buffer overflow */ #define CAN_ERR_CRTL_TX_OVERFLOW 0x02 /* TX buffer overflow */ #define CAN_ERR_CRTL_RX_WARNING 0x04 /* reached warning level for RX errors */ #define CAN_ERR_CRTL_TX_WARNING 0x08 /* reached warning level for TX errors */ #define CAN_ERR_CRTL_RX_PASSIVE 0x10 /* reached error passive status RX */ #define CAN_ERR_CRTL_TX_PASSIVE 0x20 /* reached error passive status TX */ /* (at least one error counter exceeds */ /* the protocol-defined level of 127) */ #define CAN_ERR_CRTL_ACTIVE 0x40 /* recovered to error active state */ /* error in CAN protocol (type) / data[2] */ #define CAN_ERR_PROT_UNSPEC 0x00 /* unspecified */ #define CAN_ERR_PROT_BIT 0x01 /* single bit error */ #define CAN_ERR_PROT_FORM 0x02 /* frame format error */ #define CAN_ERR_PROT_STUFF 0x04 /* bit stuffing error */ #define CAN_ERR_PROT_BIT0 0x08 /* unable to send dominant bit */ #define CAN_ERR_PROT_BIT1 0x10 /* unable to send recessive bit */ #define CAN_ERR_PROT_OVERLOAD 0x20 /* bus overload */ #define CAN_ERR_PROT_ACTIVE 0x40 /* active error announcement */ #define CAN_ERR_PROT_TX 0x80 /* error occurred on transmission */ /* error in CAN protocol (location) / data[3] */ #define CAN_ERR_PROT_LOC_UNSPEC 0x00 /* unspecified */ #define CAN_ERR_PROT_LOC_SOF 0x03 /* start of frame */ #define CAN_ERR_PROT_LOC_ID28_21 0x02 /* ID bits 28 - 21 (SFF: 10 - 3) */ #define CAN_ERR_PROT_LOC_ID20_18 0x06 /* ID bits 20 - 18 (SFF: 2 - 0 )*/ #define CAN_ERR_PROT_LOC_SRTR 0x04 /* substitute RTR (SFF: RTR) */ #define CAN_ERR_PROT_LOC_IDE 0x05 /* identifier extension */ #define CAN_ERR_PROT_LOC_ID17_13 0x07 /* ID bits 17-13 */ #define CAN_ERR_PROT_LOC_ID12_05 0x0F /* ID bits 12-5 */ #define CAN_ERR_PROT_LOC_ID04_00 0x0E /* ID bits 4-0 */ #define CAN_ERR_PROT_LOC_RTR 0x0C /* RTR */ #define CAN_ERR_PROT_LOC_RES1 0x0D /* reserved bit 1 */ #define CAN_ERR_PROT_LOC_RES0 0x09 /* reserved bit 0 */ #define CAN_ERR_PROT_LOC_DLC 0x0B /* data length code */ #define CAN_ERR_PROT_LOC_DATA 0x0A /* data section */ #define CAN_ERR_PROT_LOC_CRC_SEQ 0x08 /* CRC sequence */ #define CAN_ERR_PROT_LOC_CRC_DEL 0x18 /* CRC delimiter */ #define CAN_ERR_PROT_LOC_ACK 0x19 /* ACK slot */ #define CAN_ERR_PROT_LOC_ACK_DEL 0x1B /* ACK delimiter */ #define CAN_ERR_PROT_LOC_EOF 0x1A /* end of frame */ #define CAN_ERR_PROT_LOC_INTERM 0x12 /* intermission */ /* error status of CAN-transceiver / data[4] */ /* CANH CANL */ #define CAN_ERR_TRX_UNSPEC 0x00 /* 0000 0000 */ #define CAN_ERR_TRX_CANH_NO_WIRE 0x04 /* 0000 0100 */ #define CAN_ERR_TRX_CANH_SHORT_TO_BAT 0x05 /* 0000 0101 */ #define CAN_ERR_TRX_CANH_SHORT_TO_VCC 0x06 /* 0000 0110 */ #define CAN_ERR_TRX_CANH_SHORT_TO_GND 0x07 /* 0000 0111 */ #define CAN_ERR_TRX_CANL_NO_WIRE 0x40 /* 0100 0000 */ #define CAN_ERR_TRX_CANL_SHORT_TO_BAT 0x50 /* 0101 0000 */ #define CAN_ERR_TRX_CANL_SHORT_TO_VCC 0x60 /* 0110 0000 */ #define CAN_ERR_TRX_CANL_SHORT_TO_GND 0x70 /* 0111 0000 */ #define CAN_ERR_TRX_CANL_SHORT_TO_CANH 0x80 /* 1000 0000 */ /* controller specific additional information / data[5..7] */ #endif /* _CAN_ERROR_H */ linux/mii.h000064400000022430151027430560006636 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/mii.h: definitions for MII-compatible transceivers * Originally drivers/net/sunhme.h. * * Copyright (C) 1996, 1999, 2001 David S. Miller (davem@redhat.com) */ #ifndef __LINUX_MII_H__ #define __LINUX_MII_H__ #include #include /* Generic MII registers. */ #define MII_BMCR 0x00 /* Basic mode control register */ #define MII_BMSR 0x01 /* Basic mode status register */ #define MII_PHYSID1 0x02 /* PHYS ID 1 */ #define MII_PHYSID2 0x03 /* PHYS ID 2 */ #define MII_ADVERTISE 0x04 /* Advertisement control reg */ #define MII_LPA 0x05 /* Link partner ability reg */ #define MII_EXPANSION 0x06 /* Expansion register */ #define MII_CTRL1000 0x09 /* 1000BASE-T control */ #define MII_STAT1000 0x0a /* 1000BASE-T status */ #define MII_MMD_CTRL 0x0d /* MMD Access Control Register */ #define MII_MMD_DATA 0x0e /* MMD Access Data Register */ #define MII_ESTATUS 0x0f /* Extended Status */ #define MII_DCOUNTER 0x12 /* Disconnect counter */ #define MII_FCSCOUNTER 0x13 /* False carrier counter */ #define MII_NWAYTEST 0x14 /* N-way auto-neg test reg */ #define MII_RERRCOUNTER 0x15 /* Receive error counter */ #define MII_SREVISION 0x16 /* Silicon revision */ #define MII_RESV1 0x17 /* Reserved... */ #define MII_LBRERROR 0x18 /* Lpback, rx, bypass error */ #define MII_PHYADDR 0x19 /* PHY address */ #define MII_RESV2 0x1a /* Reserved... */ #define MII_TPISTATUS 0x1b /* TPI status for 10mbps */ #define MII_NCONFIG 0x1c /* Network interface config */ /* Basic mode control register. */ #define BMCR_RESV 0x003f /* Unused... */ #define BMCR_SPEED1000 0x0040 /* MSB of Speed (1000) */ #define BMCR_CTST 0x0080 /* Collision test */ #define BMCR_FULLDPLX 0x0100 /* Full duplex */ #define BMCR_ANRESTART 0x0200 /* Auto negotiation restart */ #define BMCR_ISOLATE 0x0400 /* Isolate data paths from MII */ #define BMCR_PDOWN 0x0800 /* Enable low power state */ #define BMCR_ANENABLE 0x1000 /* Enable auto negotiation */ #define BMCR_SPEED100 0x2000 /* Select 100Mbps */ #define BMCR_LOOPBACK 0x4000 /* TXD loopback bits */ #define BMCR_RESET 0x8000 /* Reset to default state */ #define BMCR_SPEED10 0x0000 /* Select 10Mbps */ /* Basic mode status register. */ #define BMSR_ERCAP 0x0001 /* Ext-reg capability */ #define BMSR_JCD 0x0002 /* Jabber detected */ #define BMSR_LSTATUS 0x0004 /* Link status */ #define BMSR_ANEGCAPABLE 0x0008 /* Able to do auto-negotiation */ #define BMSR_RFAULT 0x0010 /* Remote fault detected */ #define BMSR_ANEGCOMPLETE 0x0020 /* Auto-negotiation complete */ #define BMSR_RESV 0x00c0 /* Unused... */ #define BMSR_ESTATEN 0x0100 /* Extended Status in R15 */ #define BMSR_100HALF2 0x0200 /* Can do 100BASE-T2 HDX */ #define BMSR_100FULL2 0x0400 /* Can do 100BASE-T2 FDX */ #define BMSR_10HALF 0x0800 /* Can do 10mbps, half-duplex */ #define BMSR_10FULL 0x1000 /* Can do 10mbps, full-duplex */ #define BMSR_100HALF 0x2000 /* Can do 100mbps, half-duplex */ #define BMSR_100FULL 0x4000 /* Can do 100mbps, full-duplex */ #define BMSR_100BASE4 0x8000 /* Can do 100mbps, 4k packets */ /* Advertisement control register. */ #define ADVERTISE_SLCT 0x001f /* Selector bits */ #define ADVERTISE_CSMA 0x0001 /* Only selector supported */ #define ADVERTISE_10HALF 0x0020 /* Try for 10mbps half-duplex */ #define ADVERTISE_1000XFULL 0x0020 /* Try for 1000BASE-X full-duplex */ #define ADVERTISE_10FULL 0x0040 /* Try for 10mbps full-duplex */ #define ADVERTISE_1000XHALF 0x0040 /* Try for 1000BASE-X half-duplex */ #define ADVERTISE_100HALF 0x0080 /* Try for 100mbps half-duplex */ #define ADVERTISE_1000XPAUSE 0x0080 /* Try for 1000BASE-X pause */ #define ADVERTISE_100FULL 0x0100 /* Try for 100mbps full-duplex */ #define ADVERTISE_1000XPSE_ASYM 0x0100 /* Try for 1000BASE-X asym pause */ #define ADVERTISE_100BASE4 0x0200 /* Try for 100mbps 4k packets */ #define ADVERTISE_PAUSE_CAP 0x0400 /* Try for pause */ #define ADVERTISE_PAUSE_ASYM 0x0800 /* Try for asymetric pause */ #define ADVERTISE_RESV 0x1000 /* Unused... */ #define ADVERTISE_RFAULT 0x2000 /* Say we can detect faults */ #define ADVERTISE_LPACK 0x4000 /* Ack link partners response */ #define ADVERTISE_NPAGE 0x8000 /* Next page bit */ #define ADVERTISE_FULL (ADVERTISE_100FULL | ADVERTISE_10FULL | \ ADVERTISE_CSMA) #define ADVERTISE_ALL (ADVERTISE_10HALF | ADVERTISE_10FULL | \ ADVERTISE_100HALF | ADVERTISE_100FULL) /* Link partner ability register. */ #define LPA_SLCT 0x001f /* Same as advertise selector */ #define LPA_10HALF 0x0020 /* Can do 10mbps half-duplex */ #define LPA_1000XFULL 0x0020 /* Can do 1000BASE-X full-duplex */ #define LPA_10FULL 0x0040 /* Can do 10mbps full-duplex */ #define LPA_1000XHALF 0x0040 /* Can do 1000BASE-X half-duplex */ #define LPA_100HALF 0x0080 /* Can do 100mbps half-duplex */ #define LPA_1000XPAUSE 0x0080 /* Can do 1000BASE-X pause */ #define LPA_100FULL 0x0100 /* Can do 100mbps full-duplex */ #define LPA_1000XPAUSE_ASYM 0x0100 /* Can do 1000BASE-X pause asym*/ #define LPA_100BASE4 0x0200 /* Can do 100mbps 4k packets */ #define LPA_PAUSE_CAP 0x0400 /* Can pause */ #define LPA_PAUSE_ASYM 0x0800 /* Can pause asymetrically */ #define LPA_RESV 0x1000 /* Unused... */ #define LPA_RFAULT 0x2000 /* Link partner faulted */ #define LPA_LPACK 0x4000 /* Link partner acked us */ #define LPA_NPAGE 0x8000 /* Next page bit */ #define LPA_DUPLEX (LPA_10FULL | LPA_100FULL) #define LPA_100 (LPA_100FULL | LPA_100HALF | LPA_100BASE4) /* Expansion register for auto-negotiation. */ #define EXPANSION_NWAY 0x0001 /* Can do N-way auto-nego */ #define EXPANSION_LCWP 0x0002 /* Got new RX page code word */ #define EXPANSION_ENABLENPAGE 0x0004 /* This enables npage words */ #define EXPANSION_NPCAPABLE 0x0008 /* Link partner supports npage */ #define EXPANSION_MFAULTS 0x0010 /* Multiple faults detected */ #define EXPANSION_RESV 0xffe0 /* Unused... */ #define ESTATUS_1000_XFULL 0x8000 /* Can do 1000BaseX Full */ #define ESTATUS_1000_XHALF 0x4000 /* Can do 1000BaseX Half */ #define ESTATUS_1000_TFULL 0x2000 /* Can do 1000BT Full */ #define ESTATUS_1000_THALF 0x1000 /* Can do 1000BT Half */ /* N-way test register. */ #define NWAYTEST_RESV1 0x00ff /* Unused... */ #define NWAYTEST_LOOPBACK 0x0100 /* Enable loopback for N-way */ #define NWAYTEST_RESV2 0xfe00 /* Unused... */ /* MAC and PHY tx_config_Reg[15:0] for SGMII in-band auto-negotiation.*/ #define ADVERTISE_SGMII 0x0001 /* MAC can do SGMII */ #define LPA_SGMII 0x0001 /* PHY can do SGMII */ #define LPA_SGMII_SPD_MASK 0x0c00 /* SGMII speed mask */ #define LPA_SGMII_FULL_DUPLEX 0x1000 /* SGMII full duplex */ #define LPA_SGMII_DPX_SPD_MASK 0x1C00 /* SGMII duplex and speed bits */ #define LPA_SGMII_10 0x0000 /* 10Mbps */ #define LPA_SGMII_10HALF 0x0000 /* Can do 10mbps half-duplex */ #define LPA_SGMII_10FULL 0x1000 /* Can do 10mbps full-duplex */ #define LPA_SGMII_100 0x0400 /* 100Mbps */ #define LPA_SGMII_100HALF 0x0400 /* Can do 100mbps half-duplex */ #define LPA_SGMII_100FULL 0x1400 /* Can do 100mbps full-duplex */ #define LPA_SGMII_1000 0x0800 /* 1000Mbps */ #define LPA_SGMII_1000HALF 0x0800 /* Can do 1000mbps half-duplex */ #define LPA_SGMII_1000FULL 0x1800 /* Can do 1000mbps full-duplex */ #define LPA_SGMII_LINK 0x8000 /* PHY link with copper-side partner */ /* 1000BASE-T Control register */ #define ADVERTISE_1000FULL 0x0200 /* Advertise 1000BASE-T full duplex */ #define ADVERTISE_1000HALF 0x0100 /* Advertise 1000BASE-T half duplex */ #define CTL1000_PREFER_MASTER 0x0400 /* prefer to operate as master */ #define CTL1000_AS_MASTER 0x0800 #define CTL1000_ENABLE_MASTER 0x1000 /* 1000BASE-T Status register */ #define LPA_1000MSFAIL 0x8000 /* Master/Slave resolution failure */ #define LPA_1000MSRES 0x4000 /* Master/Slave resolution status */ #define LPA_1000LOCALRXOK 0x2000 /* Link partner local receiver status */ #define LPA_1000REMRXOK 0x1000 /* Link partner remote receiver status */ #define LPA_1000FULL 0x0800 /* Link partner 1000BASE-T full duplex */ #define LPA_1000HALF 0x0400 /* Link partner 1000BASE-T half duplex */ /* Flow control flags */ #define FLOW_CTRL_TX 0x01 #define FLOW_CTRL_RX 0x02 /* MMD Access Control register fields */ #define MII_MMD_CTRL_DEVAD_MASK 0x1f /* Mask MMD DEVAD*/ #define MII_MMD_CTRL_ADDR 0x0000 /* Address */ #define MII_MMD_CTRL_NOINCR 0x4000 /* no post increment */ #define MII_MMD_CTRL_INCR_RDWT 0x8000 /* post increment on reads & writes */ #define MII_MMD_CTRL_INCR_ON_WT 0xC000 /* post increment on writes only */ /* This structure is used in all SIOCxMIIxxx ioctl calls */ struct mii_ioctl_data { __u16 phy_id; __u16 reg_num; __u16 val_in; __u16 val_out; }; #endif /* __LINUX_MII_H__ */ linux/serio.h000064400000003765151027430560007213 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 1999-2002 Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _SERIO_H #define _SERIO_H #include #define SPIOCSTYPE _IOW('q', 0x01, unsigned long) /* * bit masks for use in "interrupt" flags (3rd argument) */ #define SERIO_TIMEOUT BIT(0) #define SERIO_PARITY BIT(1) #define SERIO_FRAME BIT(2) #define SERIO_OOB_DATA BIT(3) /* * Serio types */ #define SERIO_XT 0x00 #define SERIO_8042 0x01 #define SERIO_RS232 0x02 #define SERIO_HIL_MLC 0x03 #define SERIO_PS_PSTHRU 0x05 #define SERIO_8042_XL 0x06 /* * Serio protocols */ #define SERIO_UNKNOWN 0x00 #define SERIO_MSC 0x01 #define SERIO_SUN 0x02 #define SERIO_MS 0x03 #define SERIO_MP 0x04 #define SERIO_MZ 0x05 #define SERIO_MZP 0x06 #define SERIO_MZPP 0x07 #define SERIO_VSXXXAA 0x08 #define SERIO_SUNKBD 0x10 #define SERIO_WARRIOR 0x18 #define SERIO_SPACEORB 0x19 #define SERIO_MAGELLAN 0x1a #define SERIO_SPACEBALL 0x1b #define SERIO_GUNZE 0x1c #define SERIO_IFORCE 0x1d #define SERIO_STINGER 0x1e #define SERIO_NEWTON 0x1f #define SERIO_STOWAWAY 0x20 #define SERIO_H3600 0x21 #define SERIO_PS2SER 0x22 #define SERIO_TWIDKBD 0x23 #define SERIO_TWIDJOY 0x24 #define SERIO_HIL 0x25 #define SERIO_SNES232 0x26 #define SERIO_SEMTECH 0x27 #define SERIO_LKKBD 0x28 #define SERIO_ELO 0x29 #define SERIO_MICROTOUCH 0x30 #define SERIO_PENMOUNT 0x31 #define SERIO_TOUCHRIGHT 0x32 #define SERIO_TOUCHWIN 0x33 #define SERIO_TAOSEVM 0x34 #define SERIO_FUJITSU 0x35 #define SERIO_ZHENHUA 0x36 #define SERIO_INEXIO 0x37 #define SERIO_TOUCHIT213 0x38 #define SERIO_W8001 0x39 #define SERIO_DYNAPRO 0x3a #define SERIO_HAMPSHIRE 0x3b #define SERIO_PS2MULT 0x3c #define SERIO_TSC40 0x3d #define SERIO_WACOM_IV 0x3e #define SERIO_EGALAX 0x3f #define SERIO_PULSE8_CEC 0x40 #define SERIO_RAINSHADOW_CEC 0x41 #endif /* _SERIO_H */ linux/isdn_divertif.h000064400000002260151027430560010710 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: isdn_divertif.h,v 1.4.6.1 2001/09/23 22:25:05 kai Exp $ * * Header for the diversion supplementary interface for i4l. * * Author Werner Cornelius (werner@titro.de) * Copyright by Werner Cornelius (werner@titro.de) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef _LINUX_ISDN_DIVERTIF_H #define _LINUX_ISDN_DIVERTIF_H /***********************************************************/ /* magic value is also used to control version information */ /***********************************************************/ #define DIVERT_IF_MAGIC 0x25873401 #define DIVERT_CMD_REG 0x00 /* register command */ #define DIVERT_CMD_REL 0x01 /* release command */ #define DIVERT_NO_ERR 0x00 /* return value no error */ #define DIVERT_CMD_ERR 0x01 /* invalid cmd */ #define DIVERT_VER_ERR 0x02 /* magic/version invalid */ #define DIVERT_REG_ERR 0x03 /* module already registered */ #define DIVERT_REL_ERR 0x04 /* module not registered */ #define DIVERT_REG_NAME isdn_register_divert #endif /* _LINUX_ISDN_DIVERTIF_H */ linux/io_uring.h000064400000014077151027430560007703 0ustar00/* SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT */ /* * Header file for the io_uring interface. * * Copyright (C) 2019 Jens Axboe * Copyright (C) 2019 Christoph Hellwig */ #ifndef LINUX_IO_URING_H #define LINUX_IO_URING_H #include #include /* * IO submission data structure (Submission Queue Entry) */ struct io_uring_sqe { __u8 opcode; /* type of operation for this sqe */ __u8 flags; /* IOSQE_ flags */ __u16 ioprio; /* ioprio for the request */ __s32 fd; /* file descriptor to do IO on */ union { __u64 off; /* offset into file */ __u64 addr2; }; union { __u64 addr; /* pointer to buffer or iovecs */ __u64 splice_off_in; }; __u32 len; /* buffer size or number of iovecs */ union { __kernel_rwf_t rw_flags; __u32 fsync_flags; __u16 poll_events; __u32 sync_range_flags; __u32 msg_flags; __u32 timeout_flags; __u32 accept_flags; __u32 cancel_flags; __u32 open_flags; __u32 statx_flags; __u32 fadvise_advice; __u32 splice_flags; }; __u64 user_data; /* data to be passed back at completion time */ union { struct { /* pack this to avoid bogus arm OABI complaints */ union { /* index into fixed buffers, if used */ __u16 buf_index; /* for grouped buffer selection */ __u16 buf_group; } __attribute__((packed)); /* personality to use, if used */ __u16 personality; __s32 splice_fd_in; }; __u64 __pad2[3]; }; }; enum { IOSQE_FIXED_FILE_BIT, IOSQE_IO_DRAIN_BIT, IOSQE_IO_LINK_BIT, IOSQE_IO_HARDLINK_BIT, IOSQE_ASYNC_BIT, IOSQE_BUFFER_SELECT_BIT, }; /* * sqe->flags */ /* use fixed fileset */ #define IOSQE_FIXED_FILE (1U << IOSQE_FIXED_FILE_BIT) /* issue after inflight IO */ #define IOSQE_IO_DRAIN (1U << IOSQE_IO_DRAIN_BIT) /* links next sqe */ #define IOSQE_IO_LINK (1U << IOSQE_IO_LINK_BIT) /* like LINK, but stronger */ #define IOSQE_IO_HARDLINK (1U << IOSQE_IO_HARDLINK_BIT) /* always go async */ #define IOSQE_ASYNC (1U << IOSQE_ASYNC_BIT) /* select buffer from sqe->buf_group */ #define IOSQE_BUFFER_SELECT (1U << IOSQE_BUFFER_SELECT_BIT) /* * io_uring_setup() flags */ #define IORING_SETUP_IOPOLL (1U << 0) /* io_context is polled */ #define IORING_SETUP_SQPOLL (1U << 1) /* SQ poll thread */ #define IORING_SETUP_SQ_AFF (1U << 2) /* sq_thread_cpu is valid */ #define IORING_SETUP_CQSIZE (1U << 3) /* app defines CQ size */ #define IORING_SETUP_CLAMP (1U << 4) /* clamp SQ/CQ ring sizes */ #define IORING_SETUP_ATTACH_WQ (1U << 5) /* attach to existing wq */ enum { IORING_OP_NOP, IORING_OP_READV, IORING_OP_WRITEV, IORING_OP_FSYNC, IORING_OP_READ_FIXED, IORING_OP_WRITE_FIXED, IORING_OP_POLL_ADD, IORING_OP_POLL_REMOVE, IORING_OP_SYNC_FILE_RANGE, IORING_OP_SENDMSG, IORING_OP_RECVMSG, IORING_OP_TIMEOUT, IORING_OP_TIMEOUT_REMOVE, IORING_OP_ACCEPT, IORING_OP_ASYNC_CANCEL, IORING_OP_LINK_TIMEOUT, IORING_OP_CONNECT, IORING_OP_FALLOCATE, IORING_OP_OPENAT, IORING_OP_CLOSE, IORING_OP_FILES_UPDATE, IORING_OP_STATX, IORING_OP_READ, IORING_OP_WRITE, IORING_OP_FADVISE, IORING_OP_MADVISE, IORING_OP_SEND, IORING_OP_RECV, IORING_OP_OPENAT2, IORING_OP_EPOLL_CTL, IORING_OP_SPLICE, IORING_OP_PROVIDE_BUFFERS, IORING_OP_REMOVE_BUFFERS, /* this goes last, obviously */ IORING_OP_LAST, }; /* * sqe->fsync_flags */ #define IORING_FSYNC_DATASYNC (1U << 0) /* * sqe->timeout_flags */ #define IORING_TIMEOUT_ABS (1U << 0) /* * sqe->splice_flags * extends splice(2) flags */ #define SPLICE_F_FD_IN_FIXED (1U << 31) /* the last bit of __u32 */ /* * IO completion data structure (Completion Queue Entry) */ struct io_uring_cqe { __u64 user_data; /* sqe->data submission passed back */ __s32 res; /* result code for this event */ __u32 flags; }; /* * cqe->flags * * IORING_CQE_F_BUFFER If set, the upper 16 bits are the buffer ID */ #define IORING_CQE_F_BUFFER (1U << 0) enum { IORING_CQE_BUFFER_SHIFT = 16, }; /* * Magic offsets for the application to mmap the data it needs */ #define IORING_OFF_SQ_RING 0ULL #define IORING_OFF_CQ_RING 0x8000000ULL #define IORING_OFF_SQES 0x10000000ULL /* * Filled with the offset for mmap(2) */ struct io_sqring_offsets { __u32 head; __u32 tail; __u32 ring_mask; __u32 ring_entries; __u32 flags; __u32 dropped; __u32 array; __u32 resv1; __u64 resv2; }; /* * sq_ring->flags */ #define IORING_SQ_NEED_WAKEUP (1U << 0) /* needs io_uring_enter wakeup */ struct io_cqring_offsets { __u32 head; __u32 tail; __u32 ring_mask; __u32 ring_entries; __u32 overflow; __u32 cqes; __u64 resv[2]; }; /* * io_uring_enter(2) flags */ #define IORING_ENTER_GETEVENTS (1U << 0) #define IORING_ENTER_SQ_WAKEUP (1U << 1) /* * Passed in for io_uring_setup(2). Copied back with updated info on success */ struct io_uring_params { __u32 sq_entries; __u32 cq_entries; __u32 flags; __u32 sq_thread_cpu; __u32 sq_thread_idle; __u32 features; __u32 wq_fd; __u32 resv[3]; struct io_sqring_offsets sq_off; struct io_cqring_offsets cq_off; }; /* * io_uring_params->features flags */ #define IORING_FEAT_SINGLE_MMAP (1U << 0) #define IORING_FEAT_NODROP (1U << 1) #define IORING_FEAT_SUBMIT_STABLE (1U << 2) #define IORING_FEAT_RW_CUR_POS (1U << 3) #define IORING_FEAT_CUR_PERSONALITY (1U << 4) #define IORING_FEAT_FAST_POLL (1U << 5) /* * io_uring_register(2) opcodes and arguments */ #define IORING_REGISTER_BUFFERS 0 #define IORING_UNREGISTER_BUFFERS 1 #define IORING_REGISTER_FILES 2 #define IORING_UNREGISTER_FILES 3 #define IORING_REGISTER_EVENTFD 4 #define IORING_UNREGISTER_EVENTFD 5 #define IORING_REGISTER_FILES_UPDATE 6 #define IORING_REGISTER_EVENTFD_ASYNC 7 #define IORING_REGISTER_PROBE 8 #define IORING_REGISTER_PERSONALITY 9 #define IORING_UNREGISTER_PERSONALITY 10 struct io_uring_files_update { __u32 offset; __u32 resv; __aligned_u64 /* __s32 * */ fds; }; #define IO_URING_OP_SUPPORTED (1U << 0) struct io_uring_probe_op { __u8 op; __u8 resv; __u16 flags; /* IO_URING_OP_* flags */ __u32 resv2; }; struct io_uring_probe { __u8 last_op; /* last opcode supported */ __u8 ops_len; /* length of ops[] array below */ __u16 resv; __u32 resv2[3]; struct io_uring_probe_op ops[0]; }; #endif linux/utime.h000064400000000327151027430560007204 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_UTIME_H #define _LINUX_UTIME_H #include struct utimbuf { __kernel_time_t actime; __kernel_time_t modtime; }; #endif linux/if_fc.h000064400000003312151027430560007124 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for Fibre Channel. * * Version: @(#)if_fc.h 0.0 11/20/98 * * Author: Fred N. van Kempen, * Donald Becker, * Peter De Schrijver, * Vineet Abraham, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_FC_H #define _LINUX_IF_FC_H #include #define FC_ALEN 6 /* Octets in one ethernet addr */ #define FC_HLEN (sizeof(struct fch_hdr)+sizeof(struct fcllc)) #define FC_ID_LEN 3 /* Octets in a Fibre Channel Address */ /* LLC and SNAP constants */ #define EXTENDED_SAP 0xAA #define UI_CMD 0x03 /* This is NOT the Fibre Channel frame header. The FC frame header is * constructed in the driver as the Tachyon needs certain fields in * certains positions. So, it can't be generalized here.*/ struct fch_hdr { __u8 daddr[FC_ALEN]; /* destination address */ __u8 saddr[FC_ALEN]; /* source address */ }; /* This is a Fibre Channel LLC structure */ struct fcllc { __u8 dsap; /* destination SAP */ __u8 ssap; /* source SAP */ __u8 llc; /* LLC control field */ __u8 protid[3]; /* protocol id */ __be16 ethertype; /* ether type field */ }; #endif /* _LINUX_IF_FC_H */ linux/sev-guest.h000064400000004377151027430560010014 0ustar00/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */ /* * Userspace interface for AMD SEV and SNP guest driver. * * Copyright (C) 2021 Advanced Micro Devices, Inc. * * Author: Brijesh Singh * * SEV API specification is available at: https://developer.amd.com/sev/ */ #ifndef __UAPI_LINUX_SEV_GUEST_H_ #define __UAPI_LINUX_SEV_GUEST_H_ #include struct snp_report_req { /* user data that should be included in the report */ __u8 user_data[64]; /* The vmpl level to be included in the report */ __u32 vmpl; /* Must be zero filled */ __u8 rsvd[28]; }; struct snp_report_resp { /* response data, see SEV-SNP spec for the format */ __u8 data[4000]; }; struct snp_derived_key_req { __u32 root_key_select; __u32 rsvd; __u64 guest_field_select; __u32 vmpl; __u32 guest_svn; __u64 tcb_version; }; struct snp_derived_key_resp { /* response data, see SEV-SNP spec for the format */ __u8 data[64]; }; struct snp_guest_request_ioctl { /* message version number (must be non-zero) */ __u8 msg_version; /* Request and response structure address */ __u64 req_data; __u64 resp_data; /* bits[63:32]: VMM error code, bits[31:0] firmware error code (see psp-sev.h) */ union { __u64 exitinfo2; struct { __u32 fw_error; __u32 vmm_error; }; }; }; struct snp_ext_report_req { struct snp_report_req data; /* where to copy the certificate blob */ __u64 certs_address; /* length of the certificate blob */ __u32 certs_len; }; #define SNP_GUEST_REQ_IOC_TYPE 'S' /* Get SNP attestation report */ #define SNP_GET_REPORT _IOWR(SNP_GUEST_REQ_IOC_TYPE, 0x0, struct snp_guest_request_ioctl) /* Get a derived key from the root */ #define SNP_GET_DERIVED_KEY _IOWR(SNP_GUEST_REQ_IOC_TYPE, 0x1, struct snp_guest_request_ioctl) /* Get SNP extended report as defined in the GHCB specification version 2. */ #define SNP_GET_EXT_REPORT _IOWR(SNP_GUEST_REQ_IOC_TYPE, 0x2, struct snp_guest_request_ioctl) /* Guest message request EXIT_INFO_2 constants */ #define SNP_GUEST_FW_ERR_MASK GENMASK_ULL(31, 0) #define SNP_GUEST_VMM_ERR_SHIFT 32 #define SNP_GUEST_VMM_ERR(x) (((u64)x) << SNP_GUEST_VMM_ERR_SHIFT) #define SNP_GUEST_VMM_ERR_INVALID_LEN 1 #define SNP_GUEST_VMM_ERR_BUSY 2 #endif /* __UAPI_LINUX_SEV_GUEST_H_ */ linux/ipsec.h000064400000001663151027430560007170 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_IPSEC_H #define _LINUX_IPSEC_H /* The definitions, required to talk to KAME racoon IKE. */ #include #define IPSEC_PORT_ANY 0 #define IPSEC_ULPROTO_ANY 255 #define IPSEC_PROTO_ANY 255 enum { IPSEC_MODE_ANY = 0, /* We do not support this for SA */ IPSEC_MODE_TRANSPORT = 1, IPSEC_MODE_TUNNEL = 2, IPSEC_MODE_BEET = 3 }; enum { IPSEC_DIR_ANY = 0, IPSEC_DIR_INBOUND = 1, IPSEC_DIR_OUTBOUND = 2, IPSEC_DIR_FWD = 3, /* It is our own */ IPSEC_DIR_MAX = 4, IPSEC_DIR_INVALID = 5 }; enum { IPSEC_POLICY_DISCARD = 0, IPSEC_POLICY_NONE = 1, IPSEC_POLICY_IPSEC = 2, IPSEC_POLICY_ENTRUST = 3, IPSEC_POLICY_BYPASS = 4 }; enum { IPSEC_LEVEL_DEFAULT = 0, IPSEC_LEVEL_USE = 1, IPSEC_LEVEL_REQUIRE = 2, IPSEC_LEVEL_UNIQUE = 3 }; #define IPSEC_MANUAL_REQID_MAX 0x3fff #define IPSEC_REPLAYWSIZE 32 #endif /* _LINUX_IPSEC_H */ linux/target_core_user.h000064400000011031151027430560011407 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __TARGET_CORE_USER_H #define __TARGET_CORE_USER_H /* This header will be used by application too */ #include #include #define TCMU_VERSION "2.0" /** * DOC: Ring Design * Ring Design * ----------- * * The mmaped area is divided into three parts: * 1) The mailbox (struct tcmu_mailbox, below); * 2) The command ring; * 3) Everything beyond the command ring (data). * * The mailbox tells userspace the offset of the command ring from the * start of the shared memory region, and how big the command ring is. * * The kernel passes SCSI commands to userspace by putting a struct * tcmu_cmd_entry in the ring, updating mailbox->cmd_head, and poking * userspace via UIO's interrupt mechanism. * * tcmu_cmd_entry contains a header. If the header type is PAD, * userspace should skip hdr->length bytes (mod cmdr_size) to find the * next cmd_entry. * * Otherwise, the entry will contain offsets into the mmaped area that * contain the cdb and data buffers -- the latter accessible via the * iov array. iov addresses are also offsets into the shared area. * * When userspace is completed handling the command, set * entry->rsp.scsi_status, fill in rsp.sense_buffer if appropriate, * and also set mailbox->cmd_tail equal to the old cmd_tail plus * hdr->length, mod cmdr_size. If cmd_tail doesn't equal cmd_head, it * should process the next packet the same way, and so on. */ #define TCMU_MAILBOX_VERSION 2 #define ALIGN_SIZE 64 /* Should be enough for most CPUs */ #define TCMU_MAILBOX_FLAG_CAP_OOOC (1 << 0) /* Out-of-order completions */ #define TCMU_MAILBOX_FLAG_CAP_READ_LEN (1 << 1) /* Read data length */ #define TCMU_MAILBOX_FLAG_CAP_TMR (1 << 2) /* TMR notifications */ #define TCMU_MAILBOX_FLAG_CAP_KEEP_BUF (1<<3) /* Keep buf after cmd completion */ struct tcmu_mailbox { __u16 version; __u16 flags; __u32 cmdr_off; __u32 cmdr_size; __u32 cmd_head; /* Updated by user. On its own cacheline */ __u32 cmd_tail __attribute__((__aligned__(ALIGN_SIZE))); } __attribute__((packed)); enum tcmu_opcode { TCMU_OP_PAD = 0, TCMU_OP_CMD, TCMU_OP_TMR, }; /* * Only a few opcodes, and length is 8-byte aligned, so use low bits for opcode. */ struct tcmu_cmd_entry_hdr { __u32 len_op; __u16 cmd_id; __u8 kflags; #define TCMU_UFLAG_UNKNOWN_OP 0x1 #define TCMU_UFLAG_READ_LEN 0x2 #define TCMU_UFLAG_KEEP_BUF 0x4 __u8 uflags; } __attribute__((packed)); #define TCMU_OP_MASK 0x7 static __inline__ enum tcmu_opcode tcmu_hdr_get_op(__u32 len_op) { return len_op & TCMU_OP_MASK; } static __inline__ void tcmu_hdr_set_op(__u32 *len_op, enum tcmu_opcode op) { *len_op &= ~TCMU_OP_MASK; *len_op |= (op & TCMU_OP_MASK); } static __inline__ __u32 tcmu_hdr_get_len(__u32 len_op) { return len_op & ~TCMU_OP_MASK; } static __inline__ void tcmu_hdr_set_len(__u32 *len_op, __u32 len) { *len_op &= TCMU_OP_MASK; *len_op |= len; } /* Currently the same as SCSI_SENSE_BUFFERSIZE */ #define TCMU_SENSE_BUFFERSIZE 96 struct tcmu_cmd_entry { struct tcmu_cmd_entry_hdr hdr; union { struct { __u32 iov_cnt; __u32 iov_bidi_cnt; __u32 iov_dif_cnt; __u64 cdb_off; __u64 __pad1; __u64 __pad2; struct iovec iov[0]; } req; struct { __u8 scsi_status; __u8 __pad1; __u16 __pad2; __u32 read_len; char sense_buffer[TCMU_SENSE_BUFFERSIZE]; } rsp; }; } __attribute__((packed)); struct tcmu_tmr_entry { struct tcmu_cmd_entry_hdr hdr; #define TCMU_TMR_UNKNOWN 0 #define TCMU_TMR_ABORT_TASK 1 #define TCMU_TMR_ABORT_TASK_SET 2 #define TCMU_TMR_CLEAR_ACA 3 #define TCMU_TMR_CLEAR_TASK_SET 4 #define TCMU_TMR_LUN_RESET 5 #define TCMU_TMR_TARGET_WARM_RESET 6 #define TCMU_TMR_TARGET_COLD_RESET 7 /* Pseudo reset due to received PR OUT */ #define TCMU_TMR_LUN_RESET_PRO 128 __u8 tmr_type; __u8 __pad1; __u16 __pad2; __u32 cmd_cnt; __u64 __pad3; __u64 __pad4; __u16 cmd_ids[0]; } __attribute__((packed)); #define TCMU_OP_ALIGN_SIZE sizeof(__u64) enum tcmu_genl_cmd { TCMU_CMD_UNSPEC, TCMU_CMD_ADDED_DEVICE, TCMU_CMD_REMOVED_DEVICE, TCMU_CMD_RECONFIG_DEVICE, TCMU_CMD_ADDED_DEVICE_DONE, TCMU_CMD_REMOVED_DEVICE_DONE, TCMU_CMD_RECONFIG_DEVICE_DONE, TCMU_CMD_SET_FEATURES, __TCMU_CMD_MAX, }; #define TCMU_CMD_MAX (__TCMU_CMD_MAX - 1) enum tcmu_genl_attr { TCMU_ATTR_UNSPEC, TCMU_ATTR_DEVICE, TCMU_ATTR_MINOR, TCMU_ATTR_PAD, TCMU_ATTR_DEV_CFG, TCMU_ATTR_DEV_SIZE, TCMU_ATTR_WRITECACHE, TCMU_ATTR_CMD_STATUS, TCMU_ATTR_DEVICE_ID, TCMU_ATTR_SUPP_KERN_CMD_REPLY, __TCMU_ATTR_MAX, }; #define TCMU_ATTR_MAX (__TCMU_ATTR_MAX - 1) #endif linux/ipx.h000064400000004453151027430560006665 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPX_H_ #define _IPX_H_ #include /* for compatibility with glibc netipx/ipx.h */ #include #include #include #define IPX_NODE_LEN 6 #define IPX_MTU 576 #if __UAPI_DEF_SOCKADDR_IPX struct sockaddr_ipx { __kernel_sa_family_t sipx_family; __be16 sipx_port; __be32 sipx_network; unsigned char sipx_node[IPX_NODE_LEN]; __u8 sipx_type; unsigned char sipx_zero; /* 16 byte fill */ }; #endif /* __UAPI_DEF_SOCKADDR_IPX */ /* * So we can fit the extra info for SIOCSIFADDR into the address nicely */ #define sipx_special sipx_port #define sipx_action sipx_zero #define IPX_DLTITF 0 #define IPX_CRTITF 1 #if __UAPI_DEF_IPX_ROUTE_DEFINITION struct ipx_route_definition { __be32 ipx_network; __be32 ipx_router_network; unsigned char ipx_router_node[IPX_NODE_LEN]; }; #endif /* __UAPI_DEF_IPX_ROUTE_DEFINITION */ #if __UAPI_DEF_IPX_INTERFACE_DEFINITION struct ipx_interface_definition { __be32 ipx_network; unsigned char ipx_device[16]; unsigned char ipx_dlink_type; #define IPX_FRAME_NONE 0 #define IPX_FRAME_SNAP 1 #define IPX_FRAME_8022 2 #define IPX_FRAME_ETHERII 3 #define IPX_FRAME_8023 4 #define IPX_FRAME_TR_8022 5 /* obsolete */ unsigned char ipx_special; #define IPX_SPECIAL_NONE 0 #define IPX_PRIMARY 1 #define IPX_INTERNAL 2 unsigned char ipx_node[IPX_NODE_LEN]; }; #endif /* __UAPI_DEF_IPX_INTERFACE_DEFINITION */ #if __UAPI_DEF_IPX_CONFIG_DATA struct ipx_config_data { unsigned char ipxcfg_auto_select_primary; unsigned char ipxcfg_auto_create_interfaces; }; #endif /* __UAPI_DEF_IPX_CONFIG_DATA */ /* * OLD Route Definition for backward compatibility. */ #if __UAPI_DEF_IPX_ROUTE_DEF struct ipx_route_def { __be32 ipx_network; __be32 ipx_router_network; #define IPX_ROUTE_NO_ROUTER 0 unsigned char ipx_router_node[IPX_NODE_LEN]; unsigned char ipx_device[16]; unsigned short ipx_flags; #define IPX_RT_SNAP 8 #define IPX_RT_8022 4 #define IPX_RT_BLUEBOOK 2 #define IPX_RT_ROUTED 1 }; #endif /* __UAPI_DEF_IPX_ROUTE_DEF */ #define SIOCAIPXITFCRT (SIOCPROTOPRIVATE) #define SIOCAIPXPRISLT (SIOCPROTOPRIVATE + 1) #define SIOCIPXCFGDATA (SIOCPROTOPRIVATE + 2) #define SIOCIPXNCPCONN (SIOCPROTOPRIVATE + 3) #endif /* _IPX_H_ */ linux/psp-sev.h000064400000010752151027430560007461 0ustar00/* * Userspace interface for AMD Secure Encrypted Virtualization (SEV) * platform management commands. * * Copyright (C) 2016-2017 Advanced Micro Devices, Inc. * * Author: Brijesh Singh * * SEV API specification is available at: https://developer.amd.com/sev/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __PSP_SEV_USER_H__ #define __PSP_SEV_USER_H__ #include /** * SEV platform commands */ enum { SEV_FACTORY_RESET = 0, SEV_PLATFORM_STATUS, SEV_PEK_GEN, SEV_PEK_CSR, SEV_PDH_GEN, SEV_PDH_CERT_EXPORT, SEV_PEK_CERT_IMPORT, SEV_GET_ID, /* This command is deprecated, use SEV_GET_ID2 */ SEV_GET_ID2, SEV_MAX, }; /** * SEV Firmware status code */ typedef enum { /* * This error code is not in the SEV spec. Its purpose is to convey that * there was an error that prevented the SEV firmware from being called. * The SEV API error codes are 16 bits, so the -1 value will not overlap * with possible values from the specification. */ SEV_RET_NO_FW_CALL = -1, SEV_RET_SUCCESS = 0, SEV_RET_INVALID_PLATFORM_STATE, SEV_RET_INVALID_GUEST_STATE, SEV_RET_INAVLID_CONFIG, SEV_RET_INVALID_LEN, SEV_RET_ALREADY_OWNED, SEV_RET_INVALID_CERTIFICATE, SEV_RET_POLICY_FAILURE, SEV_RET_INACTIVE, SEV_RET_INVALID_ADDRESS, SEV_RET_BAD_SIGNATURE, SEV_RET_BAD_MEASUREMENT, SEV_RET_ASID_OWNED, SEV_RET_INVALID_ASID, SEV_RET_WBINVD_REQUIRED, SEV_RET_DFFLUSH_REQUIRED, SEV_RET_INVALID_GUEST, SEV_RET_INVALID_COMMAND, SEV_RET_ACTIVE, SEV_RET_HWSEV_RET_PLATFORM, SEV_RET_HWSEV_RET_UNSAFE, SEV_RET_UNSUPPORTED, SEV_RET_INVALID_PARAM, SEV_RET_RESOURCE_LIMIT, SEV_RET_SECURE_DATA_INVALID, SEV_RET_MAX, } sev_ret_code; /** * struct sev_user_data_status - PLATFORM_STATUS command parameters * * @major: major API version * @minor: minor API version * @state: platform state * @flags: platform config flags * @build: firmware build id for API version * @guest_count: number of active guests */ struct sev_user_data_status { __u8 api_major; /* Out */ __u8 api_minor; /* Out */ __u8 state; /* Out */ __u32 flags; /* Out */ __u8 build; /* Out */ __u32 guest_count; /* Out */ } __attribute__((packed)); #define SEV_STATUS_FLAGS_CONFIG_ES 0x0100 /** * struct sev_user_data_pek_csr - PEK_CSR command parameters * * @address: PEK certificate chain * @length: length of certificate */ struct sev_user_data_pek_csr { __u64 address; /* In */ __u32 length; /* In/Out */ } __attribute__((packed)); /** * struct sev_user_data_cert_import - PEK_CERT_IMPORT command parameters * * @pek_address: PEK certificate chain * @pek_len: length of PEK certificate * @oca_address: OCA certificate chain * @oca_len: length of OCA certificate */ struct sev_user_data_pek_cert_import { __u64 pek_cert_address; /* In */ __u32 pek_cert_len; /* In */ __u64 oca_cert_address; /* In */ __u32 oca_cert_len; /* In */ } __attribute__((packed)); /** * struct sev_user_data_pdh_cert_export - PDH_CERT_EXPORT command parameters * * @pdh_address: PDH certificate address * @pdh_len: length of PDH certificate * @cert_chain_address: PDH certificate chain * @cert_chain_len: length of PDH certificate chain */ struct sev_user_data_pdh_cert_export { __u64 pdh_cert_address; /* In */ __u32 pdh_cert_len; /* In/Out */ __u64 cert_chain_address; /* In */ __u32 cert_chain_len; /* In/Out */ } __attribute__((packed)); /** * struct sev_user_data_get_id - GET_ID command parameters (deprecated) * * @socket1: Buffer to pass unique ID of first socket * @socket2: Buffer to pass unique ID of second socket */ struct sev_user_data_get_id { __u8 socket1[64]; /* Out */ __u8 socket2[64]; /* Out */ } __attribute__((packed)); /** * struct sev_user_data_get_id2 - GET_ID command parameters * @address: Buffer to store unique ID * @length: length of the unique ID */ struct sev_user_data_get_id2 { __u64 address; /* In */ __u32 length; /* In/Out */ } __attribute__((packed)); /** * struct sev_issue_cmd - SEV ioctl parameters * * @cmd: SEV commands to execute * @opaque: pointer to the command structure * @error: SEV FW return code on failure */ struct sev_issue_cmd { __u32 cmd; /* In */ __u64 data; /* In */ __u32 error; /* Out */ } __attribute__((packed)); #define SEV_IOC_TYPE 'S' #define SEV_ISSUE_CMD _IOWR(SEV_IOC_TYPE, 0x0, struct sev_issue_cmd) #endif /* __PSP_USER_SEV_H */ linux/btrfs.h000064400000070361151027430560007206 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #ifndef _LINUX_BTRFS_H #define _LINUX_BTRFS_H #include #include #define BTRFS_IOCTL_MAGIC 0x94 #define BTRFS_VOL_NAME_MAX 255 #define BTRFS_LABEL_SIZE 256 /* this should be 4k */ #define BTRFS_PATH_NAME_MAX 4087 struct btrfs_ioctl_vol_args { __s64 fd; char name[BTRFS_PATH_NAME_MAX + 1]; }; #define BTRFS_DEVICE_PATH_NAME_MAX 1024 #define BTRFS_SUBVOL_NAME_MAX 4039 #define BTRFS_SUBVOL_CREATE_ASYNC (1ULL << 0) #define BTRFS_SUBVOL_RDONLY (1ULL << 1) #define BTRFS_SUBVOL_QGROUP_INHERIT (1ULL << 2) #define BTRFS_DEVICE_SPEC_BY_ID (1ULL << 3) #define BTRFS_VOL_ARG_V2_FLAGS_SUPPORTED \ (BTRFS_SUBVOL_CREATE_ASYNC | \ BTRFS_SUBVOL_RDONLY | \ BTRFS_SUBVOL_QGROUP_INHERIT | \ BTRFS_DEVICE_SPEC_BY_ID) #define BTRFS_FSID_SIZE 16 #define BTRFS_UUID_SIZE 16 #define BTRFS_UUID_UNPARSED_SIZE 37 /* * flags definition for qgroup limits * * Used by: * struct btrfs_qgroup_limit.flags * struct btrfs_qgroup_limit_item.flags */ #define BTRFS_QGROUP_LIMIT_MAX_RFER (1ULL << 0) #define BTRFS_QGROUP_LIMIT_MAX_EXCL (1ULL << 1) #define BTRFS_QGROUP_LIMIT_RSV_RFER (1ULL << 2) #define BTRFS_QGROUP_LIMIT_RSV_EXCL (1ULL << 3) #define BTRFS_QGROUP_LIMIT_RFER_CMPR (1ULL << 4) #define BTRFS_QGROUP_LIMIT_EXCL_CMPR (1ULL << 5) struct btrfs_qgroup_limit { __u64 flags; __u64 max_rfer; __u64 max_excl; __u64 rsv_rfer; __u64 rsv_excl; }; /* * flags definition for qgroup inheritance * * Used by: * struct btrfs_qgroup_inherit.flags */ #define BTRFS_QGROUP_INHERIT_SET_LIMITS (1ULL << 0) struct btrfs_qgroup_inherit { __u64 flags; __u64 num_qgroups; __u64 num_ref_copies; __u64 num_excl_copies; struct btrfs_qgroup_limit lim; __u64 qgroups[0]; }; struct btrfs_ioctl_qgroup_limit_args { __u64 qgroupid; struct btrfs_qgroup_limit lim; }; /* * flags for subvolumes * * Used by: * struct btrfs_ioctl_vol_args_v2.flags * * BTRFS_SUBVOL_RDONLY is also provided/consumed by the following ioctls: * - BTRFS_IOC_SUBVOL_GETFLAGS * - BTRFS_IOC_SUBVOL_SETFLAGS */ struct btrfs_ioctl_vol_args_v2 { __s64 fd; __u64 transid; __u64 flags; union { struct { __u64 size; struct btrfs_qgroup_inherit *qgroup_inherit; }; __u64 unused[4]; }; union { char name[BTRFS_SUBVOL_NAME_MAX + 1]; __u64 devid; }; }; /* * structure to report errors and progress to userspace, either as a * result of a finished scrub, a canceled scrub or a progress inquiry */ struct btrfs_scrub_progress { __u64 data_extents_scrubbed; /* # of data extents scrubbed */ __u64 tree_extents_scrubbed; /* # of tree extents scrubbed */ __u64 data_bytes_scrubbed; /* # of data bytes scrubbed */ __u64 tree_bytes_scrubbed; /* # of tree bytes scrubbed */ __u64 read_errors; /* # of read errors encountered (EIO) */ __u64 csum_errors; /* # of failed csum checks */ __u64 verify_errors; /* # of occurences, where the metadata * of a tree block did not match the * expected values, like generation or * logical */ __u64 no_csum; /* # of 4k data block for which no csum * is present, probably the result of * data written with nodatasum */ __u64 csum_discards; /* # of csum for which no data was found * in the extent tree. */ __u64 super_errors; /* # of bad super blocks encountered */ __u64 malloc_errors; /* # of internal kmalloc errors. These * will likely cause an incomplete * scrub */ __u64 uncorrectable_errors; /* # of errors where either no intact * copy was found or the writeback * failed */ __u64 corrected_errors; /* # of errors corrected */ __u64 last_physical; /* last physical address scrubbed. In * case a scrub was aborted, this can * be used to restart the scrub */ __u64 unverified_errors; /* # of occurences where a read for a * full (64k) bio failed, but the re- * check succeeded for each 4k piece. * Intermittent error. */ }; #define BTRFS_SCRUB_READONLY 1 struct btrfs_ioctl_scrub_args { __u64 devid; /* in */ __u64 start; /* in */ __u64 end; /* in */ __u64 flags; /* in */ struct btrfs_scrub_progress progress; /* out */ /* pad to 1k */ __u64 unused[(1024-32-sizeof(struct btrfs_scrub_progress))/8]; }; #define BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS 0 #define BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID 1 struct btrfs_ioctl_dev_replace_start_params { __u64 srcdevid; /* in, if 0, use srcdev_name instead */ __u64 cont_reading_from_srcdev_mode; /* in, see #define * above */ __u8 srcdev_name[BTRFS_DEVICE_PATH_NAME_MAX + 1]; /* in */ __u8 tgtdev_name[BTRFS_DEVICE_PATH_NAME_MAX + 1]; /* in */ }; #define BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED 0 #define BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED 1 #define BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED 2 #define BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED 3 #define BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED 4 struct btrfs_ioctl_dev_replace_status_params { __u64 replace_state; /* out, see #define above */ __u64 progress_1000; /* out, 0 <= x <= 1000 */ __u64 time_started; /* out, seconds since 1-Jan-1970 */ __u64 time_stopped; /* out, seconds since 1-Jan-1970 */ __u64 num_write_errors; /* out */ __u64 num_uncorrectable_read_errors; /* out */ }; #define BTRFS_IOCTL_DEV_REPLACE_CMD_START 0 #define BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS 1 #define BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL 2 #define BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR 0 #define BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED 1 #define BTRFS_IOCTL_DEV_REPLACE_RESULT_ALREADY_STARTED 2 #define BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS 3 struct btrfs_ioctl_dev_replace_args { __u64 cmd; /* in */ __u64 result; /* out */ union { struct btrfs_ioctl_dev_replace_start_params start; struct btrfs_ioctl_dev_replace_status_params status; }; /* in/out */ __u64 spare[64]; }; struct btrfs_ioctl_dev_info_args { __u64 devid; /* in/out */ __u8 uuid[BTRFS_UUID_SIZE]; /* in/out */ __u64 bytes_used; /* out */ __u64 total_bytes; /* out */ __u64 unused[379]; /* pad to 4k */ __u8 path[BTRFS_DEVICE_PATH_NAME_MAX]; /* out */ }; struct btrfs_ioctl_fs_info_args { __u64 max_id; /* out */ __u64 num_devices; /* out */ __u8 fsid[BTRFS_FSID_SIZE]; /* out */ __u32 nodesize; /* out */ __u32 sectorsize; /* out */ __u32 clone_alignment; /* out */ __u32 reserved32; __u64 reserved[122]; /* pad to 1k */ }; /* * feature flags * * Used by: * struct btrfs_ioctl_feature_flags */ #define BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE (1ULL << 0) /* * Older kernels (< 4.9) on big-endian systems produced broken free space tree * bitmaps, and btrfs-progs also used to corrupt the free space tree (versions * < 4.7.3). If this bit is clear, then the free space tree cannot be trusted. * btrfs-progs can also intentionally clear this bit to ask the kernel to * rebuild the free space tree, however this might not work on older kernels * that do not know about this bit. If not sure, clear the cache manually on * first mount when booting older kernel versions. */ #define BTRFS_FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID (1ULL << 1) #define BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF (1ULL << 0) #define BTRFS_FEATURE_INCOMPAT_DEFAULT_SUBVOL (1ULL << 1) #define BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS (1ULL << 2) #define BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO (1ULL << 3) #define BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD (1ULL << 4) /* * older kernels tried to do bigger metadata blocks, but the * code was pretty buggy. Lets not let them try anymore. */ #define BTRFS_FEATURE_INCOMPAT_BIG_METADATA (1ULL << 5) #define BTRFS_FEATURE_INCOMPAT_EXTENDED_IREF (1ULL << 6) #define BTRFS_FEATURE_INCOMPAT_RAID56 (1ULL << 7) #define BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA (1ULL << 8) #define BTRFS_FEATURE_INCOMPAT_NO_HOLES (1ULL << 9) struct btrfs_ioctl_feature_flags { __u64 compat_flags; __u64 compat_ro_flags; __u64 incompat_flags; }; /* balance control ioctl modes */ #define BTRFS_BALANCE_CTL_PAUSE 1 #define BTRFS_BALANCE_CTL_CANCEL 2 /* * this is packed, because it should be exactly the same as its disk * byte order counterpart (struct btrfs_disk_balance_args) */ struct btrfs_balance_args { __u64 profiles; union { __u64 usage; struct { __u32 usage_min; __u32 usage_max; }; }; __u64 devid; __u64 pstart; __u64 pend; __u64 vstart; __u64 vend; __u64 target; __u64 flags; /* * BTRFS_BALANCE_ARGS_LIMIT with value 'limit' * BTRFS_BALANCE_ARGS_LIMIT_RANGE - the extend version can use minimum * and maximum */ union { __u64 limit; /* limit number of processed chunks */ struct { __u32 limit_min; __u32 limit_max; }; }; /* * Process chunks that cross stripes_min..stripes_max devices, * BTRFS_BALANCE_ARGS_STRIPES_RANGE */ __u32 stripes_min; __u32 stripes_max; __u64 unused[6]; } __attribute__ ((__packed__)); /* report balance progress to userspace */ struct btrfs_balance_progress { __u64 expected; /* estimated # of chunks that will be * relocated to fulfill the request */ __u64 considered; /* # of chunks we have considered so far */ __u64 completed; /* # of chunks relocated so far */ }; /* * flags definition for balance * * Restriper's general type filter * * Used by: * btrfs_ioctl_balance_args.flags * btrfs_balance_control.flags (internal) */ #define BTRFS_BALANCE_DATA (1ULL << 0) #define BTRFS_BALANCE_SYSTEM (1ULL << 1) #define BTRFS_BALANCE_METADATA (1ULL << 2) #define BTRFS_BALANCE_TYPE_MASK (BTRFS_BALANCE_DATA | \ BTRFS_BALANCE_SYSTEM | \ BTRFS_BALANCE_METADATA) #define BTRFS_BALANCE_FORCE (1ULL << 3) #define BTRFS_BALANCE_RESUME (1ULL << 4) /* * flags definitions for per-type balance args * * Balance filters * * Used by: * struct btrfs_balance_args */ #define BTRFS_BALANCE_ARGS_PROFILES (1ULL << 0) #define BTRFS_BALANCE_ARGS_USAGE (1ULL << 1) #define BTRFS_BALANCE_ARGS_DEVID (1ULL << 2) #define BTRFS_BALANCE_ARGS_DRANGE (1ULL << 3) #define BTRFS_BALANCE_ARGS_VRANGE (1ULL << 4) #define BTRFS_BALANCE_ARGS_LIMIT (1ULL << 5) #define BTRFS_BALANCE_ARGS_LIMIT_RANGE (1ULL << 6) #define BTRFS_BALANCE_ARGS_STRIPES_RANGE (1ULL << 7) #define BTRFS_BALANCE_ARGS_USAGE_RANGE (1ULL << 10) #define BTRFS_BALANCE_ARGS_MASK \ (BTRFS_BALANCE_ARGS_PROFILES | \ BTRFS_BALANCE_ARGS_USAGE | \ BTRFS_BALANCE_ARGS_DEVID | \ BTRFS_BALANCE_ARGS_DRANGE | \ BTRFS_BALANCE_ARGS_VRANGE | \ BTRFS_BALANCE_ARGS_LIMIT | \ BTRFS_BALANCE_ARGS_LIMIT_RANGE | \ BTRFS_BALANCE_ARGS_STRIPES_RANGE | \ BTRFS_BALANCE_ARGS_USAGE_RANGE) /* * Profile changing flags. When SOFT is set we won't relocate chunk if * it already has the target profile (even though it may be * half-filled). */ #define BTRFS_BALANCE_ARGS_CONVERT (1ULL << 8) #define BTRFS_BALANCE_ARGS_SOFT (1ULL << 9) /* * flags definition for balance state * * Used by: * struct btrfs_ioctl_balance_args.state */ #define BTRFS_BALANCE_STATE_RUNNING (1ULL << 0) #define BTRFS_BALANCE_STATE_PAUSE_REQ (1ULL << 1) #define BTRFS_BALANCE_STATE_CANCEL_REQ (1ULL << 2) struct btrfs_ioctl_balance_args { __u64 flags; /* in/out */ __u64 state; /* out */ struct btrfs_balance_args data; /* in/out */ struct btrfs_balance_args meta; /* in/out */ struct btrfs_balance_args sys; /* in/out */ struct btrfs_balance_progress stat; /* out */ __u64 unused[72]; /* pad to 1k */ }; #define BTRFS_INO_LOOKUP_PATH_MAX 4080 struct btrfs_ioctl_ino_lookup_args { __u64 treeid; __u64 objectid; char name[BTRFS_INO_LOOKUP_PATH_MAX]; }; #define BTRFS_INO_LOOKUP_USER_PATH_MAX (4080 - BTRFS_VOL_NAME_MAX - 1) struct btrfs_ioctl_ino_lookup_user_args { /* in, inode number containing the subvolume of 'subvolid' */ __u64 dirid; /* in */ __u64 treeid; /* out, name of the subvolume of 'treeid' */ char name[BTRFS_VOL_NAME_MAX + 1]; /* * out, constructed path from the directory with which the ioctl is * called to dirid */ char path[BTRFS_INO_LOOKUP_USER_PATH_MAX]; }; /* Search criteria for the btrfs SEARCH ioctl family. */ struct btrfs_ioctl_search_key { /* * The tree we're searching in. 1 is the tree of tree roots, 2 is the * extent tree, etc... * * A special tree_id value of 0 will cause a search in the subvolume * tree that the inode which is passed to the ioctl is part of. */ __u64 tree_id; /* in */ /* * When doing a tree search, we're actually taking a slice from a * linear search space of 136-bit keys. * * A full 136-bit tree key is composed as: * (objectid << 72) + (type << 64) + offset * * The individual min and max values for objectid, type and offset * define the min_key and max_key values for the search range. All * metadata items with a key in the interval [min_key, max_key] will be * returned. * * Additionally, we can filter the items returned on transaction id of * the metadata block they're stored in by specifying a transid range. * Be aware that this transaction id only denotes when the metadata * page that currently contains the item got written the last time as * result of a COW operation. The number does not have any meaning * related to the transaction in which an individual item that is being * returned was created or changed. */ __u64 min_objectid; /* in */ __u64 max_objectid; /* in */ __u64 min_offset; /* in */ __u64 max_offset; /* in */ __u64 min_transid; /* in */ __u64 max_transid; /* in */ __u32 min_type; /* in */ __u32 max_type; /* in */ /* * input: The maximum amount of results desired. * output: The actual amount of items returned, restricted by any of: * - reaching the upper bound of the search range * - reaching the input nr_items amount of items * - completely filling the supplied memory buffer */ __u32 nr_items; /* in/out */ /* align to 64 bits */ __u32 unused; /* some extra for later */ __u64 unused1; __u64 unused2; __u64 unused3; __u64 unused4; }; struct btrfs_ioctl_search_header { __u64 transid; __u64 objectid; __u64 offset; __u32 type; __u32 len; }; #define BTRFS_SEARCH_ARGS_BUFSIZE (4096 - sizeof(struct btrfs_ioctl_search_key)) /* * the buf is an array of search headers where * each header is followed by the actual item * the type field is expanded to 32 bits for alignment */ struct btrfs_ioctl_search_args { struct btrfs_ioctl_search_key key; char buf[BTRFS_SEARCH_ARGS_BUFSIZE]; }; struct btrfs_ioctl_search_args_v2 { struct btrfs_ioctl_search_key key; /* in/out - search parameters */ __u64 buf_size; /* in - size of buffer * out - on EOVERFLOW: needed size * to store item */ __u64 buf[0]; /* out - found items */ }; struct btrfs_ioctl_clone_range_args { __s64 src_fd; __u64 src_offset, src_length; __u64 dest_offset; }; /* * flags definition for the defrag range ioctl * * Used by: * struct btrfs_ioctl_defrag_range_args.flags */ #define BTRFS_DEFRAG_RANGE_COMPRESS 1 #define BTRFS_DEFRAG_RANGE_START_IO 2 struct btrfs_ioctl_defrag_range_args { /* start of the defrag operation */ __u64 start; /* number of bytes to defrag, use (u64)-1 to say all */ __u64 len; /* * flags for the operation, which can include turning * on compression for this one defrag */ __u64 flags; /* * any extent bigger than this will be considered * already defragged. Use 0 to take the kernel default * Use 1 to say every single extent must be rewritten */ __u32 extent_thresh; /* * which compression method to use if turning on compression * for this defrag operation. If unspecified, zlib will * be used */ __u32 compress_type; /* spare for later */ __u32 unused[4]; }; #define BTRFS_SAME_DATA_DIFFERS 1 /* For extent-same ioctl */ struct btrfs_ioctl_same_extent_info { __s64 fd; /* in - destination file */ __u64 logical_offset; /* in - start of extent in destination */ __u64 bytes_deduped; /* out - total # of bytes we were able * to dedupe from this file */ /* status of this dedupe operation: * 0 if dedup succeeds * < 0 for error * == BTRFS_SAME_DATA_DIFFERS if data differs */ __s32 status; /* out - see above description */ __u32 reserved; }; struct btrfs_ioctl_same_args { __u64 logical_offset; /* in - start of extent in source */ __u64 length; /* in - length of extent */ __u16 dest_count; /* in - total elements in info array */ __u16 reserved1; __u32 reserved2; struct btrfs_ioctl_same_extent_info info[0]; }; struct btrfs_ioctl_space_info { __u64 flags; __u64 total_bytes; __u64 used_bytes; }; struct btrfs_ioctl_space_args { __u64 space_slots; __u64 total_spaces; struct btrfs_ioctl_space_info spaces[0]; }; struct btrfs_data_container { __u32 bytes_left; /* out -- bytes not needed to deliver output */ __u32 bytes_missing; /* out -- additional bytes needed for result */ __u32 elem_cnt; /* out */ __u32 elem_missed; /* out */ __u64 val[0]; /* out */ }; struct btrfs_ioctl_ino_path_args { __u64 inum; /* in */ __u64 size; /* in */ __u64 reserved[4]; /* struct btrfs_data_container *fspath; out */ __u64 fspath; /* out */ }; struct btrfs_ioctl_logical_ino_args { __u64 logical; /* in */ __u64 size; /* in */ __u64 reserved[3]; /* must be 0 for now */ __u64 flags; /* in, v2 only */ /* struct btrfs_data_container *inodes; out */ __u64 inodes; }; /* Return every ref to the extent, not just those containing logical block. * Requires logical == extent bytenr. */ #define BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET (1ULL << 0) enum btrfs_dev_stat_values { /* disk I/O failure stats */ BTRFS_DEV_STAT_WRITE_ERRS, /* EIO or EREMOTEIO from lower layers */ BTRFS_DEV_STAT_READ_ERRS, /* EIO or EREMOTEIO from lower layers */ BTRFS_DEV_STAT_FLUSH_ERRS, /* EIO or EREMOTEIO from lower layers */ /* stats for indirect indications for I/O failures */ BTRFS_DEV_STAT_CORRUPTION_ERRS, /* checksum error, bytenr error or * contents is illegal: this is an * indication that the block was damaged * during read or write, or written to * wrong location or read from wrong * location */ BTRFS_DEV_STAT_GENERATION_ERRS, /* an indication that blocks have not * been written */ BTRFS_DEV_STAT_VALUES_MAX }; /* Reset statistics after reading; needs SYS_ADMIN capability */ #define BTRFS_DEV_STATS_RESET (1ULL << 0) struct btrfs_ioctl_get_dev_stats { __u64 devid; /* in */ __u64 nr_items; /* in/out */ __u64 flags; /* in/out */ /* out values: */ __u64 values[BTRFS_DEV_STAT_VALUES_MAX]; __u64 unused[128 - 2 - BTRFS_DEV_STAT_VALUES_MAX]; /* pad to 1k */ }; #define BTRFS_QUOTA_CTL_ENABLE 1 #define BTRFS_QUOTA_CTL_DISABLE 2 #define BTRFS_QUOTA_CTL_RESCAN__NOTUSED 3 struct btrfs_ioctl_quota_ctl_args { __u64 cmd; __u64 status; }; struct btrfs_ioctl_quota_rescan_args { __u64 flags; __u64 progress; __u64 reserved[6]; }; struct btrfs_ioctl_qgroup_assign_args { __u64 assign; __u64 src; __u64 dst; }; struct btrfs_ioctl_qgroup_create_args { __u64 create; __u64 qgroupid; }; struct btrfs_ioctl_timespec { __u64 sec; __u32 nsec; }; struct btrfs_ioctl_received_subvol_args { char uuid[BTRFS_UUID_SIZE]; /* in */ __u64 stransid; /* in */ __u64 rtransid; /* out */ struct btrfs_ioctl_timespec stime; /* in */ struct btrfs_ioctl_timespec rtime; /* out */ __u64 flags; /* in */ __u64 reserved[16]; /* in */ }; /* * Caller doesn't want file data in the send stream, even if the * search of clone sources doesn't find an extent. UPDATE_EXTENT * commands will be sent instead of WRITE commands. */ #define BTRFS_SEND_FLAG_NO_FILE_DATA 0x1 /* * Do not add the leading stream header. Used when multiple snapshots * are sent back to back. */ #define BTRFS_SEND_FLAG_OMIT_STREAM_HEADER 0x2 /* * Omit the command at the end of the stream that indicated the end * of the stream. This option is used when multiple snapshots are * sent back to back. */ #define BTRFS_SEND_FLAG_OMIT_END_CMD 0x4 #define BTRFS_SEND_FLAG_MASK \ (BTRFS_SEND_FLAG_NO_FILE_DATA | \ BTRFS_SEND_FLAG_OMIT_STREAM_HEADER | \ BTRFS_SEND_FLAG_OMIT_END_CMD) struct btrfs_ioctl_send_args { __s64 send_fd; /* in */ __u64 clone_sources_count; /* in */ __u64 *clone_sources; /* in */ __u64 parent_root; /* in */ __u64 flags; /* in */ __u64 reserved[4]; /* in */ }; /* * Information about a fs tree root. * * All items are filled by the ioctl */ struct btrfs_ioctl_get_subvol_info_args { /* Id of this subvolume */ __u64 treeid; /* Name of this subvolume, used to get the real name at mount point */ char name[BTRFS_VOL_NAME_MAX + 1]; /* * Id of the subvolume which contains this subvolume. * Zero for top-level subvolume or a deleted subvolume. */ __u64 parent_id; /* * Inode number of the directory which contains this subvolume. * Zero for top-level subvolume or a deleted subvolume */ __u64 dirid; /* Latest transaction id of this subvolume */ __u64 generation; /* Flags of this subvolume */ __u64 flags; /* UUID of this subvolume */ __u8 uuid[BTRFS_UUID_SIZE]; /* * UUID of the subvolume of which this subvolume is a snapshot. * All zero for a non-snapshot subvolume. */ __u8 parent_uuid[BTRFS_UUID_SIZE]; /* * UUID of the subvolume from which this subvolume was received. * All zero for non-received subvolume. */ __u8 received_uuid[BTRFS_UUID_SIZE]; /* Transaction id indicating when change/create/send/receive happened */ __u64 ctransid; __u64 otransid; __u64 stransid; __u64 rtransid; /* Time corresponding to c/o/s/rtransid */ struct btrfs_ioctl_timespec ctime; struct btrfs_ioctl_timespec otime; struct btrfs_ioctl_timespec stime; struct btrfs_ioctl_timespec rtime; /* Must be zero */ __u64 reserved[8]; }; #define BTRFS_MAX_ROOTREF_BUFFER_NUM 255 struct btrfs_ioctl_get_subvol_rootref_args { /* in/out, minimum id of rootref's treeid to be searched */ __u64 min_treeid; /* out */ struct { __u64 treeid; __u64 dirid; } rootref[BTRFS_MAX_ROOTREF_BUFFER_NUM]; /* out, number of found items */ __u8 num_items; __u8 align[7]; }; /* Error codes as returned by the kernel */ enum btrfs_err_code { BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET = 1, BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET, BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET, BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET, BTRFS_ERROR_DEV_TGT_REPLACE, BTRFS_ERROR_DEV_MISSING_NOT_FOUND, BTRFS_ERROR_DEV_ONLY_WRITABLE, BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS }; #define BTRFS_IOC_SNAP_CREATE _IOW(BTRFS_IOCTL_MAGIC, 1, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_DEFRAG _IOW(BTRFS_IOCTL_MAGIC, 2, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_RESIZE _IOW(BTRFS_IOCTL_MAGIC, 3, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_SCAN_DEV _IOW(BTRFS_IOCTL_MAGIC, 4, \ struct btrfs_ioctl_vol_args) /* trans start and trans end are dangerous, and only for * use by applications that know how to avoid the * resulting deadlocks */ #define BTRFS_IOC_TRANS_START _IO(BTRFS_IOCTL_MAGIC, 6) #define BTRFS_IOC_TRANS_END _IO(BTRFS_IOCTL_MAGIC, 7) #define BTRFS_IOC_SYNC _IO(BTRFS_IOCTL_MAGIC, 8) #define BTRFS_IOC_CLONE _IOW(BTRFS_IOCTL_MAGIC, 9, int) #define BTRFS_IOC_ADD_DEV _IOW(BTRFS_IOCTL_MAGIC, 10, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_RM_DEV _IOW(BTRFS_IOCTL_MAGIC, 11, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_BALANCE _IOW(BTRFS_IOCTL_MAGIC, 12, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_CLONE_RANGE _IOW(BTRFS_IOCTL_MAGIC, 13, \ struct btrfs_ioctl_clone_range_args) #define BTRFS_IOC_SUBVOL_CREATE _IOW(BTRFS_IOCTL_MAGIC, 14, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_SNAP_DESTROY _IOW(BTRFS_IOCTL_MAGIC, 15, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_DEFRAG_RANGE _IOW(BTRFS_IOCTL_MAGIC, 16, \ struct btrfs_ioctl_defrag_range_args) #define BTRFS_IOC_TREE_SEARCH _IOWR(BTRFS_IOCTL_MAGIC, 17, \ struct btrfs_ioctl_search_args) #define BTRFS_IOC_TREE_SEARCH_V2 _IOWR(BTRFS_IOCTL_MAGIC, 17, \ struct btrfs_ioctl_search_args_v2) #define BTRFS_IOC_INO_LOOKUP _IOWR(BTRFS_IOCTL_MAGIC, 18, \ struct btrfs_ioctl_ino_lookup_args) #define BTRFS_IOC_DEFAULT_SUBVOL _IOW(BTRFS_IOCTL_MAGIC, 19, __u64) #define BTRFS_IOC_SPACE_INFO _IOWR(BTRFS_IOCTL_MAGIC, 20, \ struct btrfs_ioctl_space_args) #define BTRFS_IOC_START_SYNC _IOR(BTRFS_IOCTL_MAGIC, 24, __u64) #define BTRFS_IOC_WAIT_SYNC _IOW(BTRFS_IOCTL_MAGIC, 22, __u64) #define BTRFS_IOC_SNAP_CREATE_V2 _IOW(BTRFS_IOCTL_MAGIC, 23, \ struct btrfs_ioctl_vol_args_v2) #define BTRFS_IOC_SUBVOL_CREATE_V2 _IOW(BTRFS_IOCTL_MAGIC, 24, \ struct btrfs_ioctl_vol_args_v2) #define BTRFS_IOC_SUBVOL_GETFLAGS _IOR(BTRFS_IOCTL_MAGIC, 25, __u64) #define BTRFS_IOC_SUBVOL_SETFLAGS _IOW(BTRFS_IOCTL_MAGIC, 26, __u64) #define BTRFS_IOC_SCRUB _IOWR(BTRFS_IOCTL_MAGIC, 27, \ struct btrfs_ioctl_scrub_args) #define BTRFS_IOC_SCRUB_CANCEL _IO(BTRFS_IOCTL_MAGIC, 28) #define BTRFS_IOC_SCRUB_PROGRESS _IOWR(BTRFS_IOCTL_MAGIC, 29, \ struct btrfs_ioctl_scrub_args) #define BTRFS_IOC_DEV_INFO _IOWR(BTRFS_IOCTL_MAGIC, 30, \ struct btrfs_ioctl_dev_info_args) #define BTRFS_IOC_FS_INFO _IOR(BTRFS_IOCTL_MAGIC, 31, \ struct btrfs_ioctl_fs_info_args) #define BTRFS_IOC_BALANCE_V2 _IOWR(BTRFS_IOCTL_MAGIC, 32, \ struct btrfs_ioctl_balance_args) #define BTRFS_IOC_BALANCE_CTL _IOW(BTRFS_IOCTL_MAGIC, 33, int) #define BTRFS_IOC_BALANCE_PROGRESS _IOR(BTRFS_IOCTL_MAGIC, 34, \ struct btrfs_ioctl_balance_args) #define BTRFS_IOC_INO_PATHS _IOWR(BTRFS_IOCTL_MAGIC, 35, \ struct btrfs_ioctl_ino_path_args) #define BTRFS_IOC_LOGICAL_INO _IOWR(BTRFS_IOCTL_MAGIC, 36, \ struct btrfs_ioctl_logical_ino_args) #define BTRFS_IOC_SET_RECEIVED_SUBVOL _IOWR(BTRFS_IOCTL_MAGIC, 37, \ struct btrfs_ioctl_received_subvol_args) #define BTRFS_IOC_SEND _IOW(BTRFS_IOCTL_MAGIC, 38, struct btrfs_ioctl_send_args) #define BTRFS_IOC_DEVICES_READY _IOR(BTRFS_IOCTL_MAGIC, 39, \ struct btrfs_ioctl_vol_args) #define BTRFS_IOC_QUOTA_CTL _IOWR(BTRFS_IOCTL_MAGIC, 40, \ struct btrfs_ioctl_quota_ctl_args) #define BTRFS_IOC_QGROUP_ASSIGN _IOW(BTRFS_IOCTL_MAGIC, 41, \ struct btrfs_ioctl_qgroup_assign_args) #define BTRFS_IOC_QGROUP_CREATE _IOW(BTRFS_IOCTL_MAGIC, 42, \ struct btrfs_ioctl_qgroup_create_args) #define BTRFS_IOC_QGROUP_LIMIT _IOR(BTRFS_IOCTL_MAGIC, 43, \ struct btrfs_ioctl_qgroup_limit_args) #define BTRFS_IOC_QUOTA_RESCAN _IOW(BTRFS_IOCTL_MAGIC, 44, \ struct btrfs_ioctl_quota_rescan_args) #define BTRFS_IOC_QUOTA_RESCAN_STATUS _IOR(BTRFS_IOCTL_MAGIC, 45, \ struct btrfs_ioctl_quota_rescan_args) #define BTRFS_IOC_QUOTA_RESCAN_WAIT _IO(BTRFS_IOCTL_MAGIC, 46) #define BTRFS_IOC_GET_FSLABEL _IOR(BTRFS_IOCTL_MAGIC, 49, \ char[BTRFS_LABEL_SIZE]) #define BTRFS_IOC_SET_FSLABEL _IOW(BTRFS_IOCTL_MAGIC, 50, \ char[BTRFS_LABEL_SIZE]) #define BTRFS_IOC_GET_DEV_STATS _IOWR(BTRFS_IOCTL_MAGIC, 52, \ struct btrfs_ioctl_get_dev_stats) #define BTRFS_IOC_DEV_REPLACE _IOWR(BTRFS_IOCTL_MAGIC, 53, \ struct btrfs_ioctl_dev_replace_args) #define BTRFS_IOC_FILE_EXTENT_SAME _IOWR(BTRFS_IOCTL_MAGIC, 54, \ struct btrfs_ioctl_same_args) #define BTRFS_IOC_GET_FEATURES _IOR(BTRFS_IOCTL_MAGIC, 57, \ struct btrfs_ioctl_feature_flags) #define BTRFS_IOC_SET_FEATURES _IOW(BTRFS_IOCTL_MAGIC, 57, \ struct btrfs_ioctl_feature_flags[2]) #define BTRFS_IOC_GET_SUPPORTED_FEATURES _IOR(BTRFS_IOCTL_MAGIC, 57, \ struct btrfs_ioctl_feature_flags[3]) #define BTRFS_IOC_RM_DEV_V2 _IOW(BTRFS_IOCTL_MAGIC, 58, \ struct btrfs_ioctl_vol_args_v2) #define BTRFS_IOC_LOGICAL_INO_V2 _IOWR(BTRFS_IOCTL_MAGIC, 59, \ struct btrfs_ioctl_logical_ino_args) #define BTRFS_IOC_GET_SUBVOL_INFO _IOR(BTRFS_IOCTL_MAGIC, 60, \ struct btrfs_ioctl_get_subvol_info_args) #define BTRFS_IOC_GET_SUBVOL_ROOTREF _IOWR(BTRFS_IOCTL_MAGIC, 61, \ struct btrfs_ioctl_get_subvol_rootref_args) #define BTRFS_IOC_INO_LOOKUP_USER _IOWR(BTRFS_IOCTL_MAGIC, 62, \ struct btrfs_ioctl_ino_lookup_user_args) #endif /* _LINUX_BTRFS_H */ linux/i2c.h000064400000015734151027430560006546 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* ------------------------------------------------------------------------- */ /* */ /* i2c.h - definitions for the i2c-bus interface */ /* */ /* ------------------------------------------------------------------------- */ /* Copyright (C) 1995-2000 Simon G. Vogl This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* ------------------------------------------------------------------------- */ /* With some changes from Kyösti Mälkki and Frodo Looijaard */ #ifndef _LINUX_I2C_H #define _LINUX_I2C_H #include /** * struct i2c_msg - an I2C transaction segment beginning with START * @addr: Slave address, either seven or ten bits. When this is a ten * bit address, I2C_M_TEN must be set in @flags and the adapter * must support I2C_FUNC_10BIT_ADDR. * @flags: I2C_M_RD is handled by all adapters. No other flags may be * provided unless the adapter exported the relevant I2C_FUNC_* * flags through i2c_check_functionality(). * @len: Number of data bytes in @buf being read from or written to the * I2C slave address. For read transactions where I2C_M_RECV_LEN * is set, the caller guarantees that this buffer can hold up to * 32 bytes in addition to the initial length byte sent by the * slave (plus, if used, the SMBus PEC); and this value will be * incremented by the number of block data bytes received. * @buf: The buffer into which data is read, or from which it's written. * * An i2c_msg is the low level representation of one segment of an I2C * transaction. It is visible to drivers in the @i2c_transfer() procedure, * to userspace from i2c-dev, and to I2C adapter drivers through the * @i2c_adapter.@master_xfer() method. * * Except when I2C "protocol mangling" is used, all I2C adapters implement * the standard rules for I2C transactions. Each transaction begins with a * START. That is followed by the slave address, and a bit encoding read * versus write. Then follow all the data bytes, possibly including a byte * with SMBus PEC. The transfer terminates with a NAK, or when all those * bytes have been transferred and ACKed. If this is the last message in a * group, it is followed by a STOP. Otherwise it is followed by the next * @i2c_msg transaction segment, beginning with a (repeated) START. * * Alternatively, when the adapter supports I2C_FUNC_PROTOCOL_MANGLING then * passing certain @flags may have changed those standard protocol behaviors. * Those flags are only for use with broken/nonconforming slaves, and with * adapters which are known to support the specific mangling options they * need (one or more of IGNORE_NAK, NO_RD_ACK, NOSTART, and REV_DIR_ADDR). */ struct i2c_msg { __u16 addr; /* slave address */ __u16 flags; #define I2C_M_RD 0x0001 /* read data, from slave to master */ /* I2C_M_RD is guaranteed to be 0x0001! */ #define I2C_M_TEN 0x0010 /* this is a ten bit chip address */ #define I2C_M_DMA_SAFE 0x0200 /* the buffer of this message is DMA safe */ /* makes only sense in kernelspace */ /* userspace buffers are copied anyway */ #define I2C_M_RECV_LEN 0x0400 /* length will be first received byte */ #define I2C_M_NO_RD_ACK 0x0800 /* if I2C_FUNC_PROTOCOL_MANGLING */ #define I2C_M_IGNORE_NAK 0x1000 /* if I2C_FUNC_PROTOCOL_MANGLING */ #define I2C_M_REV_DIR_ADDR 0x2000 /* if I2C_FUNC_PROTOCOL_MANGLING */ #define I2C_M_NOSTART 0x4000 /* if I2C_FUNC_NOSTART */ #define I2C_M_STOP 0x8000 /* if I2C_FUNC_PROTOCOL_MANGLING */ __u16 len; /* msg length */ __u8 *buf; /* pointer to msg data */ }; /* To determine what functionality is present */ #define I2C_FUNC_I2C 0x00000001 #define I2C_FUNC_10BIT_ADDR 0x00000002 #define I2C_FUNC_PROTOCOL_MANGLING 0x00000004 /* I2C_M_IGNORE_NAK etc. */ #define I2C_FUNC_SMBUS_PEC 0x00000008 #define I2C_FUNC_NOSTART 0x00000010 /* I2C_M_NOSTART */ #define I2C_FUNC_SLAVE 0x00000020 #define I2C_FUNC_SMBUS_BLOCK_PROC_CALL 0x00008000 /* SMBus 2.0 */ #define I2C_FUNC_SMBUS_QUICK 0x00010000 #define I2C_FUNC_SMBUS_READ_BYTE 0x00020000 #define I2C_FUNC_SMBUS_WRITE_BYTE 0x00040000 #define I2C_FUNC_SMBUS_READ_BYTE_DATA 0x00080000 #define I2C_FUNC_SMBUS_WRITE_BYTE_DATA 0x00100000 #define I2C_FUNC_SMBUS_READ_WORD_DATA 0x00200000 #define I2C_FUNC_SMBUS_WRITE_WORD_DATA 0x00400000 #define I2C_FUNC_SMBUS_PROC_CALL 0x00800000 #define I2C_FUNC_SMBUS_READ_BLOCK_DATA 0x01000000 #define I2C_FUNC_SMBUS_WRITE_BLOCK_DATA 0x02000000 #define I2C_FUNC_SMBUS_READ_I2C_BLOCK 0x04000000 /* I2C-like block xfer */ #define I2C_FUNC_SMBUS_WRITE_I2C_BLOCK 0x08000000 /* w/ 1-byte reg. addr. */ #define I2C_FUNC_SMBUS_HOST_NOTIFY 0x10000000 #define I2C_FUNC_SMBUS_BYTE (I2C_FUNC_SMBUS_READ_BYTE | \ I2C_FUNC_SMBUS_WRITE_BYTE) #define I2C_FUNC_SMBUS_BYTE_DATA (I2C_FUNC_SMBUS_READ_BYTE_DATA | \ I2C_FUNC_SMBUS_WRITE_BYTE_DATA) #define I2C_FUNC_SMBUS_WORD_DATA (I2C_FUNC_SMBUS_READ_WORD_DATA | \ I2C_FUNC_SMBUS_WRITE_WORD_DATA) #define I2C_FUNC_SMBUS_BLOCK_DATA (I2C_FUNC_SMBUS_READ_BLOCK_DATA | \ I2C_FUNC_SMBUS_WRITE_BLOCK_DATA) #define I2C_FUNC_SMBUS_I2C_BLOCK (I2C_FUNC_SMBUS_READ_I2C_BLOCK | \ I2C_FUNC_SMBUS_WRITE_I2C_BLOCK) #define I2C_FUNC_SMBUS_EMUL (I2C_FUNC_SMBUS_QUICK | \ I2C_FUNC_SMBUS_BYTE | \ I2C_FUNC_SMBUS_BYTE_DATA | \ I2C_FUNC_SMBUS_WORD_DATA | \ I2C_FUNC_SMBUS_PROC_CALL | \ I2C_FUNC_SMBUS_WRITE_BLOCK_DATA | \ I2C_FUNC_SMBUS_I2C_BLOCK | \ I2C_FUNC_SMBUS_PEC) /* * Data for SMBus Messages */ #define I2C_SMBUS_BLOCK_MAX 32 /* As specified in SMBus standard */ union i2c_smbus_data { __u8 byte; __u16 word; __u8 block[I2C_SMBUS_BLOCK_MAX + 2]; /* block[0] is used for length */ /* and one more for user-space compatibility */ }; /* i2c_smbus_xfer read or write markers */ #define I2C_SMBUS_READ 1 #define I2C_SMBUS_WRITE 0 /* SMBus transaction types (size parameter in the above functions) Note: these no longer correspond to the (arbitrary) PIIX4 internal codes! */ #define I2C_SMBUS_QUICK 0 #define I2C_SMBUS_BYTE 1 #define I2C_SMBUS_BYTE_DATA 2 #define I2C_SMBUS_WORD_DATA 3 #define I2C_SMBUS_PROC_CALL 4 #define I2C_SMBUS_BLOCK_DATA 5 #define I2C_SMBUS_I2C_BLOCK_BROKEN 6 #define I2C_SMBUS_BLOCK_PROC_CALL 7 /* SMBus 2.0 */ #define I2C_SMBUS_I2C_BLOCK_DATA 8 #endif /* _LINUX_I2C_H */ linux/isdn_ppp.h000064400000003603151027430560007675 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* Linux ISDN subsystem, sync PPP, interface to ipppd * * Copyright 1994-1999 by Fritz Elfert (fritz@isdn4linux.de) * Copyright 1995,96 Thinking Objects Software GmbH Wuerzburg * Copyright 1995,96 by Michael Hipp (Michael.Hipp@student.uni-tuebingen.de) * Copyright 2000-2002 by Kai Germaschewski (kai@germaschewski.name) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef _LINUX_ISDN_PPP_H #define _LINUX_ISDN_PPP_H #define CALLTYPE_INCOMING 0x1 #define CALLTYPE_OUTGOING 0x2 #define CALLTYPE_CALLBACK 0x4 #define IPPP_VERSION "2.2.0" struct pppcallinfo { int calltype; unsigned char local_num[64]; unsigned char remote_num[64]; int charge_units; }; #define PPPIOCGCALLINFO _IOWR('t',128,struct pppcallinfo) #define PPPIOCBUNDLE _IOW('t',129,int) #define PPPIOCGMPFLAGS _IOR('t',130,int) #define PPPIOCSMPFLAGS _IOW('t',131,int) #define PPPIOCSMPMTU _IOW('t',132,int) #define PPPIOCSMPMRU _IOW('t',133,int) #define PPPIOCGCOMPRESSORS _IOR('t',134,unsigned long [8]) #define PPPIOCSCOMPRESSOR _IOW('t',135,int) #define PPPIOCGIFNAME _IOR('t',136, char [IFNAMSIZ] ) #define SC_MP_PROT 0x00000200 #define SC_REJ_MP_PROT 0x00000400 #define SC_OUT_SHORT_SEQ 0x00000800 #define SC_IN_SHORT_SEQ 0x00004000 #define SC_DECOMP_ON 0x01 #define SC_COMP_ON 0x02 #define SC_DECOMP_DISCARD 0x04 #define SC_COMP_DISCARD 0x08 #define SC_LINK_DECOMP_ON 0x10 #define SC_LINK_COMP_ON 0x20 #define SC_LINK_DECOMP_DISCARD 0x40 #define SC_LINK_COMP_DISCARD 0x80 #define ISDN_PPP_COMP_MAX_OPTIONS 16 #define IPPP_COMP_FLAG_XMIT 0x1 #define IPPP_COMP_FLAG_LINK 0x2 struct isdn_ppp_comp_data { int num; unsigned char options[ISDN_PPP_COMP_MAX_OPTIONS]; int optlen; int flags; }; #endif /* _LINUX_ISDN_PPP_H */ linux/ila.h000064400000002336151027430560006630 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* ila.h - ILA Interface */ #ifndef _LINUX_ILA_H #define _LINUX_ILA_H /* NETLINK_GENERIC related info */ #define ILA_GENL_NAME "ila" #define ILA_GENL_VERSION 0x1 enum { ILA_ATTR_UNSPEC, ILA_ATTR_LOCATOR, /* u64 */ ILA_ATTR_IDENTIFIER, /* u64 */ ILA_ATTR_LOCATOR_MATCH, /* u64 */ ILA_ATTR_IFINDEX, /* s32 */ ILA_ATTR_DIR, /* u32 */ ILA_ATTR_PAD, ILA_ATTR_CSUM_MODE, /* u8 */ ILA_ATTR_IDENT_TYPE, /* u8 */ ILA_ATTR_HOOK_TYPE, /* u8 */ __ILA_ATTR_MAX, }; #define ILA_ATTR_MAX (__ILA_ATTR_MAX - 1) enum { ILA_CMD_UNSPEC, ILA_CMD_ADD, ILA_CMD_DEL, ILA_CMD_GET, ILA_CMD_FLUSH, __ILA_CMD_MAX, }; #define ILA_CMD_MAX (__ILA_CMD_MAX - 1) #define ILA_DIR_IN (1 << 0) #define ILA_DIR_OUT (1 << 1) enum { ILA_CSUM_ADJUST_TRANSPORT, ILA_CSUM_NEUTRAL_MAP, ILA_CSUM_NO_ACTION, ILA_CSUM_NEUTRAL_MAP_AUTO, }; enum { ILA_ATYPE_IID = 0, ILA_ATYPE_LUID, ILA_ATYPE_VIRT_V4, ILA_ATYPE_VIRT_UNI_V6, ILA_ATYPE_VIRT_MULTI_V6, ILA_ATYPE_NONLOCAL_ADDR, ILA_ATYPE_RSVD_1, ILA_ATYPE_RSVD_2, ILA_ATYPE_USE_FORMAT = 32, /* Get type from type field in identifier */ }; enum { ILA_HOOK_ROUTE_OUTPUT, ILA_HOOK_ROUTE_INPUT, }; #endif /* _LINUX_ILA_H */ linux/random.h000064400000002532151027430560007341 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/random.h * * Include file for the random number generator. */ #ifndef _LINUX_RANDOM_H #define _LINUX_RANDOM_H #include #include #include /* ioctl()'s for the random number generator */ /* Get the entropy count. */ #define RNDGETENTCNT _IOR( 'R', 0x00, int ) /* Add to (or subtract from) the entropy count. (Superuser only.) */ #define RNDADDTOENTCNT _IOW( 'R', 0x01, int ) /* Get the contents of the entropy pool. (Superuser only.) */ #define RNDGETPOOL _IOR( 'R', 0x02, int [2] ) /* * Write bytes into the entropy pool and add to the entropy count. * (Superuser only.) */ #define RNDADDENTROPY _IOW( 'R', 0x03, int [2] ) /* Clear entropy count to 0. (Superuser only.) */ #define RNDZAPENTCNT _IO( 'R', 0x04 ) /* Clear the entropy pool and associated counters. (Superuser only.) */ #define RNDCLEARPOOL _IO( 'R', 0x06 ) /* Reseed CRNG. (Superuser only.) */ #define RNDRESEEDCRNG _IO( 'R', 0x07 ) struct rand_pool_info { int entropy_count; int buf_size; __u32 buf[0]; }; /* * Flags for getrandom(2) * * GRND_NONBLOCK Don't block and return EAGAIN instead * GRND_RANDOM Use the /dev/random pool instead of /dev/urandom */ #define GRND_NONBLOCK 0x0001 #define GRND_RANDOM 0x0002 #endif /* _LINUX_RANDOM_H */ linux/kdev_t.h000064400000000577151027430560007344 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_KDEV_T_H #define _LINUX_KDEV_T_H /* Some programs want their definitions of MAJOR and MINOR and MKDEV from the kernel sources. These must be the externally visible ones. */ #define MAJOR(dev) ((dev)>>8) #define MINOR(dev) ((dev) & 0xff) #define MKDEV(ma,mi) ((ma)<<8 | (mi)) #endif /* _LINUX_KDEV_T_H */ linux/nfs3.h000064400000004625151027430560006737 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * NFSv3 protocol definitions */ #ifndef _LINUX_NFS3_H #define _LINUX_NFS3_H #define NFS3_PORT 2049 #define NFS3_MAXDATA 32768 #define NFS3_MAXPATHLEN PATH_MAX #define NFS3_MAXNAMLEN NAME_MAX #define NFS3_MAXGROUPS 16 #define NFS3_FHSIZE 64 #define NFS3_COOKIESIZE 4 #define NFS3_CREATEVERFSIZE 8 #define NFS3_COOKIEVERFSIZE 8 #define NFS3_WRITEVERFSIZE 8 #define NFS3_FIFO_DEV (-1) #define NFS3MODE_FMT 0170000 #define NFS3MODE_DIR 0040000 #define NFS3MODE_CHR 0020000 #define NFS3MODE_BLK 0060000 #define NFS3MODE_REG 0100000 #define NFS3MODE_LNK 0120000 #define NFS3MODE_SOCK 0140000 #define NFS3MODE_FIFO 0010000 /* Flags for access() call */ #define NFS3_ACCESS_READ 0x0001 #define NFS3_ACCESS_LOOKUP 0x0002 #define NFS3_ACCESS_MODIFY 0x0004 #define NFS3_ACCESS_EXTEND 0x0008 #define NFS3_ACCESS_DELETE 0x0010 #define NFS3_ACCESS_EXECUTE 0x0020 #define NFS3_ACCESS_FULL 0x003f /* Flags for create mode */ enum nfs3_createmode { NFS3_CREATE_UNCHECKED = 0, NFS3_CREATE_GUARDED = 1, NFS3_CREATE_EXCLUSIVE = 2 }; /* NFSv3 file system properties */ #define NFS3_FSF_LINK 0x0001 #define NFS3_FSF_SYMLINK 0x0002 #define NFS3_FSF_HOMOGENEOUS 0x0008 #define NFS3_FSF_CANSETTIME 0x0010 /* Some shorthands. See fs/nfsd/nfs3proc.c */ #define NFS3_FSF_DEFAULT 0x001B #define NFS3_FSF_BILLYBOY 0x0018 #define NFS3_FSF_READONLY 0x0008 enum nfs3_ftype { NF3NON = 0, NF3REG = 1, NF3DIR = 2, NF3BLK = 3, NF3CHR = 4, NF3LNK = 5, NF3SOCK = 6, NF3FIFO = 7, /* changed from NFSv2 (was 8) */ NF3BAD = 8 }; enum nfs3_time_how { DONT_CHANGE = 0, SET_TO_SERVER_TIME = 1, SET_TO_CLIENT_TIME = 2, }; struct nfs3_fh { unsigned short size; unsigned char data[NFS3_FHSIZE]; }; #define NFS3_VERSION 3 #define NFS3PROC_NULL 0 #define NFS3PROC_GETATTR 1 #define NFS3PROC_SETATTR 2 #define NFS3PROC_LOOKUP 3 #define NFS3PROC_ACCESS 4 #define NFS3PROC_READLINK 5 #define NFS3PROC_READ 6 #define NFS3PROC_WRITE 7 #define NFS3PROC_CREATE 8 #define NFS3PROC_MKDIR 9 #define NFS3PROC_SYMLINK 10 #define NFS3PROC_MKNOD 11 #define NFS3PROC_REMOVE 12 #define NFS3PROC_RMDIR 13 #define NFS3PROC_RENAME 14 #define NFS3PROC_LINK 15 #define NFS3PROC_READDIR 16 #define NFS3PROC_READDIRPLUS 17 #define NFS3PROC_FSSTAT 18 #define NFS3PROC_FSINFO 19 #define NFS3PROC_PATHCONF 20 #define NFS3PROC_COMMIT 21 #define NFS_MNT3_VERSION 3 #endif /* _LINUX_NFS3_H */ linux/ptp_clock.h000064400000016440151027430560010042 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * PTP 1588 clock support - user space interface * * Copyright (C) 2010 OMICRON electronics GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _PTP_CLOCK_H_ #define _PTP_CLOCK_H_ #include #include /* * Bits of the ptp_extts_request.flags field: */ #define PTP_ENABLE_FEATURE (1<<0) #define PTP_RISING_EDGE (1<<1) #define PTP_FALLING_EDGE (1<<2) #define PTP_STRICT_FLAGS (1<<3) #define PTP_EXTTS_EDGES (PTP_RISING_EDGE | PTP_FALLING_EDGE) /* * flag fields valid for the new PTP_EXTTS_REQUEST2 ioctl. */ #define PTP_EXTTS_VALID_FLAGS (PTP_ENABLE_FEATURE | \ PTP_RISING_EDGE | \ PTP_FALLING_EDGE | \ PTP_STRICT_FLAGS) /* * flag fields valid for the original PTP_EXTTS_REQUEST ioctl. * DO NOT ADD NEW FLAGS HERE. */ #define PTP_EXTTS_V1_VALID_FLAGS (PTP_ENABLE_FEATURE | \ PTP_RISING_EDGE | \ PTP_FALLING_EDGE) /* * Bits of the ptp_perout_request.flags field: */ #define PTP_PEROUT_ONE_SHOT (1<<0) #define PTP_PEROUT_DUTY_CYCLE (1<<1) #define PTP_PEROUT_PHASE (1<<2) /* * flag fields valid for the new PTP_PEROUT_REQUEST2 ioctl. */ #define PTP_PEROUT_VALID_FLAGS (PTP_PEROUT_ONE_SHOT | \ PTP_PEROUT_DUTY_CYCLE | \ PTP_PEROUT_PHASE) /* * No flags are valid for the original PTP_PEROUT_REQUEST ioctl */ #define PTP_PEROUT_V1_VALID_FLAGS (0) /* * struct ptp_clock_time - represents a time value * * The sign of the seconds field applies to the whole value. The * nanoseconds field is always unsigned. The reserved field is * included for sub-nanosecond resolution, should the demand for * this ever appear. * */ struct ptp_clock_time { __s64 sec; /* seconds */ __u32 nsec; /* nanoseconds */ __u32 reserved; }; struct ptp_clock_caps { int max_adj; /* Maximum frequency adjustment in parts per billon. */ int n_alarm; /* Number of programmable alarms. */ int n_ext_ts; /* Number of external time stamp channels. */ int n_per_out; /* Number of programmable periodic signals. */ int pps; /* Whether the clock supports a PPS callback. */ int n_pins; /* Number of input/output pins. */ /* Whether the clock supports precise system-device cross timestamps */ int cross_timestamping; /* Whether the clock supports adjust phase */ int adjust_phase; int rsv[12]; /* Reserved for future use. */ }; struct ptp_extts_request { unsigned int index; /* Which channel to configure. */ unsigned int flags; /* Bit field for PTP_xxx flags. */ unsigned int rsv[2]; /* Reserved for future use. */ }; struct ptp_perout_request { union { /* * Absolute start time. * Valid only if (flags & PTP_PEROUT_PHASE) is unset. */ struct ptp_clock_time start; /* * Phase offset. The signal should start toggling at an * unspecified integer multiple of the period, plus this value. * The start time should be "as soon as possible". * Valid only if (flags & PTP_PEROUT_PHASE) is set. */ struct ptp_clock_time phase; }; struct ptp_clock_time period; /* Desired period, zero means disable. */ unsigned int index; /* Which channel to configure. */ unsigned int flags; union { /* * The "on" time of the signal. * Must be lower than the period. * Valid only if (flags & PTP_PEROUT_DUTY_CYCLE) is set. */ struct ptp_clock_time on; /* Reserved for future use. */ unsigned int rsv[4]; }; }; #define PTP_MAX_SAMPLES 25 /* Maximum allowed offset measurement samples. */ struct ptp_sys_offset { unsigned int n_samples; /* Desired number of measurements. */ unsigned int rsv[3]; /* Reserved for future use. */ /* * Array of interleaved system/phc time stamps. The kernel * will provide 2*n_samples + 1 time stamps, with the last * one as a system time stamp. */ struct ptp_clock_time ts[2 * PTP_MAX_SAMPLES + 1]; }; struct ptp_sys_offset_extended { unsigned int n_samples; /* Desired number of measurements. */ unsigned int rsv[3]; /* Reserved for future use. */ /* * Array of [system, phc, system] time stamps. The kernel will provide * 3*n_samples time stamps. */ struct ptp_clock_time ts[PTP_MAX_SAMPLES][3]; }; struct ptp_sys_offset_precise { struct ptp_clock_time device; struct ptp_clock_time sys_realtime; struct ptp_clock_time sys_monoraw; unsigned int rsv[4]; /* Reserved for future use. */ }; enum ptp_pin_function { PTP_PF_NONE, PTP_PF_EXTTS, PTP_PF_PEROUT, PTP_PF_PHYSYNC, }; struct ptp_pin_desc { /* * Hardware specific human readable pin name. This field is * set by the kernel during the PTP_PIN_GETFUNC ioctl and is * ignored for the PTP_PIN_SETFUNC ioctl. */ char name[64]; /* * Pin index in the range of zero to ptp_clock_caps.n_pins - 1. */ unsigned int index; /* * Which of the PTP_PF_xxx functions to use on this pin. */ unsigned int func; /* * The specific channel to use for this function. * This corresponds to the 'index' field of the * PTP_EXTTS_REQUEST and PTP_PEROUT_REQUEST ioctls. */ unsigned int chan; /* * Reserved for future use. */ unsigned int rsv[5]; }; #define PTP_CLK_MAGIC '=' #define PTP_CLOCK_GETCAPS _IOR(PTP_CLK_MAGIC, 1, struct ptp_clock_caps) #define PTP_EXTTS_REQUEST _IOW(PTP_CLK_MAGIC, 2, struct ptp_extts_request) #define PTP_PEROUT_REQUEST _IOW(PTP_CLK_MAGIC, 3, struct ptp_perout_request) #define PTP_ENABLE_PPS _IOW(PTP_CLK_MAGIC, 4, int) #define PTP_SYS_OFFSET _IOW(PTP_CLK_MAGIC, 5, struct ptp_sys_offset) #define PTP_PIN_GETFUNC _IOWR(PTP_CLK_MAGIC, 6, struct ptp_pin_desc) #define PTP_PIN_SETFUNC _IOW(PTP_CLK_MAGIC, 7, struct ptp_pin_desc) #define PTP_SYS_OFFSET_PRECISE \ _IOWR(PTP_CLK_MAGIC, 8, struct ptp_sys_offset_precise) #define PTP_SYS_OFFSET_EXTENDED \ _IOWR(PTP_CLK_MAGIC, 9, struct ptp_sys_offset_extended) #define PTP_CLOCK_GETCAPS2 _IOR(PTP_CLK_MAGIC, 10, struct ptp_clock_caps) #define PTP_EXTTS_REQUEST2 _IOW(PTP_CLK_MAGIC, 11, struct ptp_extts_request) #define PTP_PEROUT_REQUEST2 _IOW(PTP_CLK_MAGIC, 12, struct ptp_perout_request) #define PTP_ENABLE_PPS2 _IOW(PTP_CLK_MAGIC, 13, int) #define PTP_SYS_OFFSET2 _IOW(PTP_CLK_MAGIC, 14, struct ptp_sys_offset) #define PTP_PIN_GETFUNC2 _IOWR(PTP_CLK_MAGIC, 15, struct ptp_pin_desc) #define PTP_PIN_SETFUNC2 _IOW(PTP_CLK_MAGIC, 16, struct ptp_pin_desc) #define PTP_SYS_OFFSET_PRECISE2 \ _IOWR(PTP_CLK_MAGIC, 17, struct ptp_sys_offset_precise) #define PTP_SYS_OFFSET_EXTENDED2 \ _IOWR(PTP_CLK_MAGIC, 18, struct ptp_sys_offset_extended) struct ptp_extts_event { struct ptp_clock_time t; /* Time event occured. */ unsigned int index; /* Which channel produced the event. */ unsigned int flags; /* Reserved for future use. */ unsigned int rsv[2]; /* Reserved for future use. */ }; #endif linux/n_r3964.h000064400000004552151027430560007171 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* r3964 linediscipline for linux * * ----------------------------------------------------------- * Copyright by * Philips Automation Projects * Kassel (Germany) * ----------------------------------------------------------- * This software may be used and distributed according to the terms of * the GNU General Public License, incorporated herein by reference. * * Author: * L. Haag * * $Log: r3964.h,v $ * Revision 1.4 2005/12/21 19:54:24 Kurt Huwig * Fixed HZ usage on 2.6 kernels * Removed unnecessary include * * Revision 1.3 2001/03/18 13:02:24 dwmw2 * Fix timer usage, use spinlocks properly. * * Revision 1.2 2001/03/18 12:53:15 dwmw2 * Merge changes in 2.4.2 * * Revision 1.1.1.1 1998/10/13 16:43:14 dwmw2 * This'll screw the version control * * Revision 1.6 1998/09/30 00:40:38 dwmw2 * Updated to use kernel's N_R3964 if available * * Revision 1.4 1998/04/02 20:29:44 lhaag * select, blocking, ... * * Revision 1.3 1998/02/12 18:58:43 root * fixed some memory leaks * calculation of checksum characters * * Revision 1.2 1998/02/07 13:03:17 root * ioctl read_telegram * * Revision 1.1 1998/02/06 19:19:43 root * Initial revision * * */ #ifndef __LINUX_N_R3964_H__ #define __LINUX_N_R3964_H__ /* line disciplines for r3964 protocol */ /* * Ioctl-commands */ #define R3964_ENABLE_SIGNALS 0x5301 #define R3964_SETPRIORITY 0x5302 #define R3964_USE_BCC 0x5303 #define R3964_READ_TELEGRAM 0x5304 /* Options for R3964_SETPRIORITY */ #define R3964_MASTER 0 #define R3964_SLAVE 1 /* Options for R3964_ENABLE_SIGNALS */ #define R3964_SIG_ACK 0x0001 #define R3964_SIG_DATA 0x0002 #define R3964_SIG_ALL 0x000f #define R3964_SIG_NONE 0x0000 #define R3964_USE_SIGIO 0x1000 /* * r3964 operation states: */ /* types for msg_id: */ enum {R3964_MSG_ACK=1, R3964_MSG_DATA }; #define R3964_MAX_MSG_COUNT 32 /* error codes for client messages */ #define R3964_OK 0 /* no error. */ #define R3964_TX_FAIL -1 /* transmission error, block NOT sent */ #define R3964_OVERFLOW -2 /* msg queue overflow */ /* the client gets this struct when calling read(fd,...): */ struct r3964_client_message { int msg_id; int arg; int error_code; }; #define R3964_MTU 256 #endif /* __LINUX_N_R3964_H__ */ linux/can.h000064400000017311151027430560006623 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * linux/can.h * * Definitions for CAN network layer (socket addr / CAN frame / CAN filter) * * Authors: Oliver Hartkopp * Urs Thuermann * Copyright (c) 2002-2007 Volkswagen Group Electronic Research * 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. Neither the name of Volkswagen nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * Alternatively, provided that this notice is retained in full, this * software may be distributed under the terms of the GNU General * Public License ("GPL") version 2, in which case the provisions of the * GPL apply INSTEAD OF those given above. * * The provided data structures and external interfaces from this code * are not restricted to be used by modules with a GPL compatible license. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #ifndef _CAN_H #define _CAN_H #include #include /* controller area network (CAN) kernel definitions */ /* special address description flags for the CAN_ID */ #define CAN_EFF_FLAG 0x80000000U /* EFF/SFF is set in the MSB */ #define CAN_RTR_FLAG 0x40000000U /* remote transmission request */ #define CAN_ERR_FLAG 0x20000000U /* error message frame */ /* valid bits in CAN ID for frame formats */ #define CAN_SFF_MASK 0x000007FFU /* standard frame format (SFF) */ #define CAN_EFF_MASK 0x1FFFFFFFU /* extended frame format (EFF) */ #define CAN_ERR_MASK 0x1FFFFFFFU /* omit EFF, RTR, ERR flags */ /* * Controller Area Network Identifier structure * * bit 0-28 : CAN identifier (11/29 bit) * bit 29 : error message frame flag (0 = data frame, 1 = error message) * bit 30 : remote transmission request flag (1 = rtr frame) * bit 31 : frame format flag (0 = standard 11 bit, 1 = extended 29 bit) */ typedef __u32 canid_t; #define CAN_SFF_ID_BITS 11 #define CAN_EFF_ID_BITS 29 /* * Controller Area Network Error Message Frame Mask structure * * bit 0-28 : error class mask (see include/linux/can/error.h) * bit 29-31 : set to zero */ typedef __u32 can_err_mask_t; /* CAN payload length and DLC definitions according to ISO 11898-1 */ #define CAN_MAX_DLC 8 #define CAN_MAX_DLEN 8 /* CAN FD payload length and DLC definitions according to ISO 11898-7 */ #define CANFD_MAX_DLC 15 #define CANFD_MAX_DLEN 64 /** * struct can_frame - basic CAN frame structure * @can_id: CAN ID of the frame and CAN_*_FLAG flags, see canid_t definition * @can_dlc: frame payload length in byte (0 .. 8) aka data length code * N.B. the DLC field from ISO 11898-1 Chapter 8.4.2.3 has a 1:1 * mapping of the 'data length code' to the real payload length * @__pad: padding * @__res0: reserved / padding * @__res1: reserved / padding * @data: CAN frame payload (up to 8 byte) */ struct can_frame { canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ __u8 can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */ __u8 __pad; /* padding */ __u8 __res0; /* reserved / padding */ __u8 __res1; /* reserved / padding */ __u8 data[CAN_MAX_DLEN] __attribute__((aligned(8))); }; /* * defined bits for canfd_frame.flags * * The use of struct canfd_frame implies the Extended Data Length (EDL) bit to * be set in the CAN frame bitstream on the wire. The EDL bit switch turns * the CAN controllers bitstream processor into the CAN FD mode which creates * two new options within the CAN FD frame specification: * * Bit Rate Switch - to indicate a second bitrate is/was used for the payload * Error State Indicator - represents the error state of the transmitting node * * As the CANFD_ESI bit is internally generated by the transmitting CAN * controller only the CANFD_BRS bit is relevant for real CAN controllers when * building a CAN FD frame for transmission. Setting the CANFD_ESI bit can make * sense for virtual CAN interfaces to test applications with echoed frames. */ #define CANFD_BRS 0x01 /* bit rate switch (second bitrate for payload data) */ #define CANFD_ESI 0x02 /* error state indicator of the transmitting node */ /** * struct canfd_frame - CAN flexible data rate frame structure * @can_id: CAN ID of the frame and CAN_*_FLAG flags, see canid_t definition * @len: frame payload length in byte (0 .. CANFD_MAX_DLEN) * @flags: additional flags for CAN FD * @__res0: reserved / padding * @__res1: reserved / padding * @data: CAN FD frame payload (up to CANFD_MAX_DLEN byte) */ struct canfd_frame { canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ __u8 len; /* frame payload length in byte */ __u8 flags; /* additional flags for CAN FD */ __u8 __res0; /* reserved / padding */ __u8 __res1; /* reserved / padding */ __u8 data[CANFD_MAX_DLEN] __attribute__((aligned(8))); }; #define CAN_MTU (sizeof(struct can_frame)) #define CANFD_MTU (sizeof(struct canfd_frame)) /* particular protocols of the protocol family PF_CAN */ #define CAN_RAW 1 /* RAW sockets */ #define CAN_BCM 2 /* Broadcast Manager */ #define CAN_TP16 3 /* VAG Transport Protocol v1.6 */ #define CAN_TP20 4 /* VAG Transport Protocol v2.0 */ #define CAN_MCNET 5 /* Bosch MCNet */ #define CAN_ISOTP 6 /* ISO 15765-2 Transport Protocol */ #define CAN_NPROTO 7 #define SOL_CAN_BASE 100 /** * struct sockaddr_can - the sockaddr structure for CAN sockets * @can_family: address family number AF_CAN. * @can_ifindex: CAN network interface index. * @can_addr: protocol specific address information */ struct sockaddr_can { __kernel_sa_family_t can_family; int can_ifindex; union { /* transport protocol class address information (e.g. ISOTP) */ struct { canid_t rx_id, tx_id; } tp; /* reserved for future CAN protocols address information */ } can_addr; }; /** * struct can_filter - CAN ID based filter in can_register(). * @can_id: relevant bits of CAN ID which are not masked out. * @can_mask: CAN mask (see description) * * Description: * A filter matches, when * * & mask == can_id & mask * * The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can * filter for error message frames (CAN_ERR_FLAG bit set in mask). */ struct can_filter { canid_t can_id; canid_t can_mask; }; #define CAN_INV_FILTER 0x20000000U /* to be set in can_filter.can_id */ #define CAN_RAW_FILTER_MAX 512 /* maximum number of can_filter set via setsockopt() */ #endif /* !_UAPI_CAN_H */ linux/rtnetlink.h000064400000047351151027430560010103 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_RTNETLINK_H #define __LINUX_RTNETLINK_H #include #include #include #include #include /* rtnetlink families. Values up to 127 are reserved for real address * families, values above 128 may be used arbitrarily. */ #define RTNL_FAMILY_IPMR 128 #define RTNL_FAMILY_IP6MR 129 #define RTNL_FAMILY_MAX 129 /**** * Routing/neighbour discovery messages. ****/ /* Types of messages */ enum { RTM_BASE = 16, #define RTM_BASE RTM_BASE RTM_NEWLINK = 16, #define RTM_NEWLINK RTM_NEWLINK RTM_DELLINK, #define RTM_DELLINK RTM_DELLINK RTM_GETLINK, #define RTM_GETLINK RTM_GETLINK RTM_SETLINK, #define RTM_SETLINK RTM_SETLINK RTM_NEWADDR = 20, #define RTM_NEWADDR RTM_NEWADDR RTM_DELADDR, #define RTM_DELADDR RTM_DELADDR RTM_GETADDR, #define RTM_GETADDR RTM_GETADDR RTM_NEWROUTE = 24, #define RTM_NEWROUTE RTM_NEWROUTE RTM_DELROUTE, #define RTM_DELROUTE RTM_DELROUTE RTM_GETROUTE, #define RTM_GETROUTE RTM_GETROUTE RTM_NEWNEIGH = 28, #define RTM_NEWNEIGH RTM_NEWNEIGH RTM_DELNEIGH, #define RTM_DELNEIGH RTM_DELNEIGH RTM_GETNEIGH, #define RTM_GETNEIGH RTM_GETNEIGH RTM_NEWRULE = 32, #define RTM_NEWRULE RTM_NEWRULE RTM_DELRULE, #define RTM_DELRULE RTM_DELRULE RTM_GETRULE, #define RTM_GETRULE RTM_GETRULE RTM_NEWQDISC = 36, #define RTM_NEWQDISC RTM_NEWQDISC RTM_DELQDISC, #define RTM_DELQDISC RTM_DELQDISC RTM_GETQDISC, #define RTM_GETQDISC RTM_GETQDISC RTM_NEWTCLASS = 40, #define RTM_NEWTCLASS RTM_NEWTCLASS RTM_DELTCLASS, #define RTM_DELTCLASS RTM_DELTCLASS RTM_GETTCLASS, #define RTM_GETTCLASS RTM_GETTCLASS RTM_NEWTFILTER = 44, #define RTM_NEWTFILTER RTM_NEWTFILTER RTM_DELTFILTER, #define RTM_DELTFILTER RTM_DELTFILTER RTM_GETTFILTER, #define RTM_GETTFILTER RTM_GETTFILTER RTM_NEWACTION = 48, #define RTM_NEWACTION RTM_NEWACTION RTM_DELACTION, #define RTM_DELACTION RTM_DELACTION RTM_GETACTION, #define RTM_GETACTION RTM_GETACTION RTM_NEWPREFIX = 52, #define RTM_NEWPREFIX RTM_NEWPREFIX RTM_GETMULTICAST = 58, #define RTM_GETMULTICAST RTM_GETMULTICAST RTM_GETANYCAST = 62, #define RTM_GETANYCAST RTM_GETANYCAST RTM_NEWNEIGHTBL = 64, #define RTM_NEWNEIGHTBL RTM_NEWNEIGHTBL RTM_GETNEIGHTBL = 66, #define RTM_GETNEIGHTBL RTM_GETNEIGHTBL RTM_SETNEIGHTBL, #define RTM_SETNEIGHTBL RTM_SETNEIGHTBL RTM_NEWNDUSEROPT = 68, #define RTM_NEWNDUSEROPT RTM_NEWNDUSEROPT RTM_NEWADDRLABEL = 72, #define RTM_NEWADDRLABEL RTM_NEWADDRLABEL RTM_DELADDRLABEL, #define RTM_DELADDRLABEL RTM_DELADDRLABEL RTM_GETADDRLABEL, #define RTM_GETADDRLABEL RTM_GETADDRLABEL RTM_GETDCB = 78, #define RTM_GETDCB RTM_GETDCB RTM_SETDCB, #define RTM_SETDCB RTM_SETDCB RTM_NEWNETCONF = 80, #define RTM_NEWNETCONF RTM_NEWNETCONF RTM_DELNETCONF, #define RTM_DELNETCONF RTM_DELNETCONF RTM_GETNETCONF = 82, #define RTM_GETNETCONF RTM_GETNETCONF RTM_NEWMDB = 84, #define RTM_NEWMDB RTM_NEWMDB RTM_DELMDB = 85, #define RTM_DELMDB RTM_DELMDB RTM_GETMDB = 86, #define RTM_GETMDB RTM_GETMDB RTM_NEWNSID = 88, #define RTM_NEWNSID RTM_NEWNSID RTM_DELNSID = 89, #define RTM_DELNSID RTM_DELNSID RTM_GETNSID = 90, #define RTM_GETNSID RTM_GETNSID RTM_NEWSTATS = 92, #define RTM_NEWSTATS RTM_NEWSTATS RTM_GETSTATS = 94, #define RTM_GETSTATS RTM_GETSTATS RTM_NEWCACHEREPORT = 96, #define RTM_NEWCACHEREPORT RTM_NEWCACHEREPORT RTM_NEWCHAIN = 100, #define RTM_NEWCHAIN RTM_NEWCHAIN RTM_DELCHAIN, #define RTM_DELCHAIN RTM_DELCHAIN RTM_GETCHAIN, #define RTM_GETCHAIN RTM_GETCHAIN RTM_NEWNEXTHOP = 104, #define RTM_NEWNEXTHOP RTM_NEWNEXTHOP RTM_DELNEXTHOP, #define RTM_DELNEXTHOP RTM_DELNEXTHOP RTM_GETNEXTHOP, #define RTM_GETNEXTHOP RTM_GETNEXTHOP RTM_NEWLINKPROP = 108, #define RTM_NEWLINKPROP RTM_NEWLINKPROP RTM_DELLINKPROP, #define RTM_DELLINKPROP RTM_DELLINKPROP RTM_GETLINKPROP, #define RTM_GETLINKPROP RTM_GETLINKPROP RTM_NEWVLAN = 112, #define RTM_NEWNVLAN RTM_NEWVLAN RTM_DELVLAN, #define RTM_DELVLAN RTM_DELVLAN RTM_GETVLAN, #define RTM_GETVLAN RTM_GETVLAN __RTM_MAX, #define RTM_MAX (((__RTM_MAX + 3) & ~3) - 1) }; #define RTM_NR_MSGTYPES (RTM_MAX + 1 - RTM_BASE) #define RTM_NR_FAMILIES (RTM_NR_MSGTYPES >> 2) #define RTM_FAM(cmd) (((cmd) - RTM_BASE) >> 2) /* Generic structure for encapsulation of optional route information. It is reminiscent of sockaddr, but with sa_family replaced with attribute type. */ struct rtattr { unsigned short rta_len; unsigned short rta_type; }; /* Macros to handle rtattributes */ #define RTA_ALIGNTO 4U #define RTA_ALIGN(len) ( ((len)+RTA_ALIGNTO-1) & ~(RTA_ALIGNTO-1) ) #define RTA_OK(rta,len) ((len) >= (int)sizeof(struct rtattr) && \ (rta)->rta_len >= sizeof(struct rtattr) && \ (rta)->rta_len <= (len)) #define RTA_NEXT(rta,attrlen) ((attrlen) -= RTA_ALIGN((rta)->rta_len), \ (struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len))) #define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len)) #define RTA_SPACE(len) RTA_ALIGN(RTA_LENGTH(len)) #define RTA_DATA(rta) ((void*)(((char*)(rta)) + RTA_LENGTH(0))) #define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0)) /****************************************************************************** * Definitions used in routing table administration. ****/ struct rtmsg { unsigned char rtm_family; unsigned char rtm_dst_len; unsigned char rtm_src_len; unsigned char rtm_tos; unsigned char rtm_table; /* Routing table id */ unsigned char rtm_protocol; /* Routing protocol; see below */ unsigned char rtm_scope; /* See below */ unsigned char rtm_type; /* See below */ unsigned rtm_flags; }; /* rtm_type */ enum { RTN_UNSPEC, RTN_UNICAST, /* Gateway or direct route */ RTN_LOCAL, /* Accept locally */ RTN_BROADCAST, /* Accept locally as broadcast, send as broadcast */ RTN_ANYCAST, /* Accept locally as broadcast, but send as unicast */ RTN_MULTICAST, /* Multicast route */ RTN_BLACKHOLE, /* Drop */ RTN_UNREACHABLE, /* Destination is unreachable */ RTN_PROHIBIT, /* Administratively prohibited */ RTN_THROW, /* Not in this table */ RTN_NAT, /* Translate this address */ RTN_XRESOLVE, /* Use external resolver */ __RTN_MAX }; #define RTN_MAX (__RTN_MAX - 1) /* rtm_protocol */ #define RTPROT_UNSPEC 0 #define RTPROT_REDIRECT 1 /* Route installed by ICMP redirects; not used by current IPv4 */ #define RTPROT_KERNEL 2 /* Route installed by kernel */ #define RTPROT_BOOT 3 /* Route installed during boot */ #define RTPROT_STATIC 4 /* Route installed by administrator */ /* Values of protocol >= RTPROT_STATIC are not interpreted by kernel; they are just passed from user and back as is. It will be used by hypothetical multiple routing daemons. Note that protocol values should be standardized in order to avoid conflicts. */ #define RTPROT_GATED 8 /* Apparently, GateD */ #define RTPROT_RA 9 /* RDISC/ND router advertisements */ #define RTPROT_MRT 10 /* Merit MRT */ #define RTPROT_ZEBRA 11 /* Zebra */ #define RTPROT_BIRD 12 /* BIRD */ #define RTPROT_DNROUTED 13 /* DECnet routing daemon */ #define RTPROT_XORP 14 /* XORP */ #define RTPROT_NTK 15 /* Netsukuku */ #define RTPROT_DHCP 16 /* DHCP client */ #define RTPROT_MROUTED 17 /* Multicast daemon */ #define RTPROT_BABEL 42 /* Babel daemon */ #define RTPROT_BGP 186 /* BGP Routes */ #define RTPROT_ISIS 187 /* ISIS Routes */ #define RTPROT_OSPF 188 /* OSPF Routes */ #define RTPROT_RIP 189 /* RIP Routes */ #define RTPROT_EIGRP 192 /* EIGRP Routes */ /* rtm_scope Really it is not scope, but sort of distance to the destination. NOWHERE are reserved for not existing destinations, HOST is our local addresses, LINK are destinations, located on directly attached link and UNIVERSE is everywhere in the Universe. Intermediate values are also possible f.e. interior routes could be assigned a value between UNIVERSE and LINK. */ enum rt_scope_t { RT_SCOPE_UNIVERSE=0, /* User defined values */ RT_SCOPE_SITE=200, RT_SCOPE_LINK=253, RT_SCOPE_HOST=254, RT_SCOPE_NOWHERE=255 }; /* rtm_flags */ #define RTM_F_NOTIFY 0x100 /* Notify user of route change */ #define RTM_F_CLONED 0x200 /* This route is cloned */ #define RTM_F_EQUALIZE 0x400 /* Multipath equalizer: NI */ #define RTM_F_PREFIX 0x800 /* Prefix addresses */ #define RTM_F_LOOKUP_TABLE 0x1000 /* set rtm_table to FIB lookup result */ #define RTM_F_FIB_MATCH 0x2000 /* return full fib lookup match */ #define RTM_F_OFFLOAD 0x4000 /* route is offloaded */ #define RTM_F_TRAP 0x8000 /* route is trapping packets */ /* Reserved table identifiers */ enum rt_class_t { RT_TABLE_UNSPEC=0, /* User defined values */ RT_TABLE_COMPAT=252, RT_TABLE_DEFAULT=253, RT_TABLE_MAIN=254, RT_TABLE_LOCAL=255, RT_TABLE_MAX=0xFFFFFFFF }; /* Routing message attributes */ enum rtattr_type_t { RTA_UNSPEC, RTA_DST, RTA_SRC, RTA_IIF, RTA_OIF, RTA_GATEWAY, RTA_PRIORITY, RTA_PREFSRC, RTA_METRICS, RTA_MULTIPATH, RTA_PROTOINFO, /* no longer used */ RTA_FLOW, RTA_CACHEINFO, RTA_SESSION, /* no longer used */ RTA_MP_ALGO, /* no longer used */ RTA_TABLE, RTA_MARK, RTA_MFC_STATS, RTA_VIA, RTA_NEWDST, RTA_PREF, RTA_ENCAP_TYPE, RTA_ENCAP, RTA_EXPIRES, RTA_PAD, RTA_UID, RTA_TTL_PROPAGATE, RTA_IP_PROTO, RTA_SPORT, RTA_DPORT, RTA_NH_ID, __RTA_MAX }; #define RTA_MAX (__RTA_MAX - 1) #define RTM_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct rtmsg)))) #define RTM_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct rtmsg)) /* RTM_MULTIPATH --- array of struct rtnexthop. * * "struct rtnexthop" describes all necessary nexthop information, * i.e. parameters of path to a destination via this nexthop. * * At the moment it is impossible to set different prefsrc, mtu, window * and rtt for different paths from multipath. */ struct rtnexthop { unsigned short rtnh_len; unsigned char rtnh_flags; unsigned char rtnh_hops; int rtnh_ifindex; }; /* rtnh_flags */ #define RTNH_F_DEAD 1 /* Nexthop is dead (used by multipath) */ #define RTNH_F_PERVASIVE 2 /* Do recursive gateway lookup */ #define RTNH_F_ONLINK 4 /* Gateway is forced on link */ #define RTNH_F_OFFLOAD 8 /* offloaded route */ #define RTNH_F_LINKDOWN 16 /* carrier-down on nexthop */ #define RTNH_F_UNRESOLVED 32 /* The entry is unresolved (ipmr) */ #define RTNH_COMPARE_MASK (RTNH_F_DEAD | RTNH_F_LINKDOWN | RTNH_F_OFFLOAD) /* Macros to handle hexthops */ #define RTNH_ALIGNTO 4 #define RTNH_ALIGN(len) ( ((len)+RTNH_ALIGNTO-1) & ~(RTNH_ALIGNTO-1) ) #define RTNH_OK(rtnh,len) ((rtnh)->rtnh_len >= sizeof(struct rtnexthop) && \ ((int)(rtnh)->rtnh_len) <= (len)) #define RTNH_NEXT(rtnh) ((struct rtnexthop*)(((char*)(rtnh)) + RTNH_ALIGN((rtnh)->rtnh_len))) #define RTNH_LENGTH(len) (RTNH_ALIGN(sizeof(struct rtnexthop)) + (len)) #define RTNH_SPACE(len) RTNH_ALIGN(RTNH_LENGTH(len)) #define RTNH_DATA(rtnh) ((struct rtattr*)(((char*)(rtnh)) + RTNH_LENGTH(0))) /* RTA_VIA */ struct rtvia { __kernel_sa_family_t rtvia_family; __u8 rtvia_addr[0]; }; /* RTM_CACHEINFO */ struct rta_cacheinfo { __u32 rta_clntref; __u32 rta_lastuse; __s32 rta_expires; __u32 rta_error; __u32 rta_used; #define RTNETLINK_HAVE_PEERINFO 1 __u32 rta_id; __u32 rta_ts; __u32 rta_tsage; }; /* RTM_METRICS --- array of struct rtattr with types of RTAX_* */ enum { RTAX_UNSPEC, #define RTAX_UNSPEC RTAX_UNSPEC RTAX_LOCK, #define RTAX_LOCK RTAX_LOCK RTAX_MTU, #define RTAX_MTU RTAX_MTU RTAX_WINDOW, #define RTAX_WINDOW RTAX_WINDOW RTAX_RTT, #define RTAX_RTT RTAX_RTT RTAX_RTTVAR, #define RTAX_RTTVAR RTAX_RTTVAR RTAX_SSTHRESH, #define RTAX_SSTHRESH RTAX_SSTHRESH RTAX_CWND, #define RTAX_CWND RTAX_CWND RTAX_ADVMSS, #define RTAX_ADVMSS RTAX_ADVMSS RTAX_REORDERING, #define RTAX_REORDERING RTAX_REORDERING RTAX_HOPLIMIT, #define RTAX_HOPLIMIT RTAX_HOPLIMIT RTAX_INITCWND, #define RTAX_INITCWND RTAX_INITCWND RTAX_FEATURES, #define RTAX_FEATURES RTAX_FEATURES RTAX_RTO_MIN, #define RTAX_RTO_MIN RTAX_RTO_MIN RTAX_INITRWND, #define RTAX_INITRWND RTAX_INITRWND RTAX_QUICKACK, #define RTAX_QUICKACK RTAX_QUICKACK RTAX_CC_ALGO, #define RTAX_CC_ALGO RTAX_CC_ALGO RTAX_FASTOPEN_NO_COOKIE, #define RTAX_FASTOPEN_NO_COOKIE RTAX_FASTOPEN_NO_COOKIE __RTAX_MAX }; #define RTAX_MAX (__RTAX_MAX - 1) #define RTAX_FEATURE_ECN (1 << 0) #define RTAX_FEATURE_SACK (1 << 1) #define RTAX_FEATURE_TIMESTAMP (1 << 2) #define RTAX_FEATURE_ALLFRAG (1 << 3) #define RTAX_FEATURE_MASK (RTAX_FEATURE_ECN | RTAX_FEATURE_SACK | \ RTAX_FEATURE_TIMESTAMP | RTAX_FEATURE_ALLFRAG) struct rta_session { __u8 proto; __u8 pad1; __u16 pad2; union { struct { __u16 sport; __u16 dport; } ports; struct { __u8 type; __u8 code; __u16 ident; } icmpt; __u32 spi; } u; }; struct rta_mfc_stats { __u64 mfcs_packets; __u64 mfcs_bytes; __u64 mfcs_wrong_if; }; /**** * General form of address family dependent message. ****/ struct rtgenmsg { unsigned char rtgen_family; }; /***************************************************************** * Link layer specific messages. ****/ /* struct ifinfomsg * passes link level specific information, not dependent * on network protocol. */ struct ifinfomsg { unsigned char ifi_family; unsigned char __ifi_pad; unsigned short ifi_type; /* ARPHRD_* */ int ifi_index; /* Link index */ unsigned ifi_flags; /* IFF_* flags */ unsigned ifi_change; /* IFF_* change mask */ }; /******************************************************************** * prefix information ****/ struct prefixmsg { unsigned char prefix_family; unsigned char prefix_pad1; unsigned short prefix_pad2; int prefix_ifindex; unsigned char prefix_type; unsigned char prefix_len; unsigned char prefix_flags; unsigned char prefix_pad3; }; enum { PREFIX_UNSPEC, PREFIX_ADDRESS, PREFIX_CACHEINFO, __PREFIX_MAX }; #define PREFIX_MAX (__PREFIX_MAX - 1) struct prefix_cacheinfo { __u32 preferred_time; __u32 valid_time; }; /***************************************************************** * Traffic control messages. ****/ struct tcmsg { unsigned char tcm_family; unsigned char tcm__pad1; unsigned short tcm__pad2; int tcm_ifindex; __u32 tcm_handle; __u32 tcm_parent; /* tcm_block_index is used instead of tcm_parent * in case tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK */ #define tcm_block_index tcm_parent __u32 tcm_info; }; /* For manipulation of filters in shared block, tcm_ifindex is set to * TCM_IFINDEX_MAGIC_BLOCK, and tcm_parent is aliased to tcm_block_index * which is the block index. */ #define TCM_IFINDEX_MAGIC_BLOCK (0xFFFFFFFFU) enum { TCA_UNSPEC, TCA_KIND, TCA_OPTIONS, TCA_STATS, TCA_XSTATS, TCA_RATE, TCA_FCNT, TCA_STATS2, TCA_STAB, TCA_PAD, TCA_DUMP_INVISIBLE, TCA_CHAIN, TCA_HW_OFFLOAD, TCA_INGRESS_BLOCK, TCA_EGRESS_BLOCK, TCA_DUMP_FLAGS, TCA_EXT_WARN_MSG, __TCA_MAX }; #define TCA_MAX (__TCA_MAX - 1) #define TCA_DUMP_FLAGS_TERSE (1 << 0) /* Means that in dump user gets only basic * data necessary to identify the objects * (handle, cookie, etc.) and stats. */ #define TCA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcmsg)))) #define TCA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcmsg)) /******************************************************************** * Neighbor Discovery userland options ****/ struct nduseroptmsg { unsigned char nduseropt_family; unsigned char nduseropt_pad1; unsigned short nduseropt_opts_len; /* Total length of options */ int nduseropt_ifindex; __u8 nduseropt_icmp_type; __u8 nduseropt_icmp_code; unsigned short nduseropt_pad2; unsigned int nduseropt_pad3; /* Followed by one or more ND options */ }; enum { NDUSEROPT_UNSPEC, NDUSEROPT_SRCADDR, __NDUSEROPT_MAX }; #define NDUSEROPT_MAX (__NDUSEROPT_MAX - 1) /* RTnetlink multicast groups - backwards compatibility for userspace */ #define RTMGRP_LINK 1 #define RTMGRP_NOTIFY 2 #define RTMGRP_NEIGH 4 #define RTMGRP_TC 8 #define RTMGRP_IPV4_IFADDR 0x10 #define RTMGRP_IPV4_MROUTE 0x20 #define RTMGRP_IPV4_ROUTE 0x40 #define RTMGRP_IPV4_RULE 0x80 #define RTMGRP_IPV6_IFADDR 0x100 #define RTMGRP_IPV6_MROUTE 0x200 #define RTMGRP_IPV6_ROUTE 0x400 #define RTMGRP_IPV6_IFINFO 0x800 #define RTMGRP_DECnet_IFADDR 0x1000 #define RTMGRP_DECnet_ROUTE 0x4000 #define RTMGRP_IPV6_PREFIX 0x20000 /* RTnetlink multicast groups */ enum rtnetlink_groups { RTNLGRP_NONE, #define RTNLGRP_NONE RTNLGRP_NONE RTNLGRP_LINK, #define RTNLGRP_LINK RTNLGRP_LINK RTNLGRP_NOTIFY, #define RTNLGRP_NOTIFY RTNLGRP_NOTIFY RTNLGRP_NEIGH, #define RTNLGRP_NEIGH RTNLGRP_NEIGH RTNLGRP_TC, #define RTNLGRP_TC RTNLGRP_TC RTNLGRP_IPV4_IFADDR, #define RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_MROUTE, #define RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_ROUTE, #define RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_RULE, #define RTNLGRP_IPV4_RULE RTNLGRP_IPV4_RULE RTNLGRP_IPV6_IFADDR, #define RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_MROUTE, #define RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_ROUTE, #define RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_IFINFO, #define RTNLGRP_IPV6_IFINFO RTNLGRP_IPV6_IFINFO RTNLGRP_DECnet_IFADDR, #define RTNLGRP_DECnet_IFADDR RTNLGRP_DECnet_IFADDR RTNLGRP_NOP2, RTNLGRP_DECnet_ROUTE, #define RTNLGRP_DECnet_ROUTE RTNLGRP_DECnet_ROUTE RTNLGRP_DECnet_RULE, #define RTNLGRP_DECnet_RULE RTNLGRP_DECnet_RULE RTNLGRP_NOP4, RTNLGRP_IPV6_PREFIX, #define RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_RULE, #define RTNLGRP_IPV6_RULE RTNLGRP_IPV6_RULE RTNLGRP_ND_USEROPT, #define RTNLGRP_ND_USEROPT RTNLGRP_ND_USEROPT RTNLGRP_PHONET_IFADDR, #define RTNLGRP_PHONET_IFADDR RTNLGRP_PHONET_IFADDR RTNLGRP_PHONET_ROUTE, #define RTNLGRP_PHONET_ROUTE RTNLGRP_PHONET_ROUTE RTNLGRP_DCB, #define RTNLGRP_DCB RTNLGRP_DCB RTNLGRP_IPV4_NETCONF, #define RTNLGRP_IPV4_NETCONF RTNLGRP_IPV4_NETCONF RTNLGRP_IPV6_NETCONF, #define RTNLGRP_IPV6_NETCONF RTNLGRP_IPV6_NETCONF RTNLGRP_MDB, #define RTNLGRP_MDB RTNLGRP_MDB RTNLGRP_MPLS_ROUTE, #define RTNLGRP_MPLS_ROUTE RTNLGRP_MPLS_ROUTE RTNLGRP_NSID, #define RTNLGRP_NSID RTNLGRP_NSID RTNLGRP_MPLS_NETCONF, #define RTNLGRP_MPLS_NETCONF RTNLGRP_MPLS_NETCONF RTNLGRP_IPV4_MROUTE_R, #define RTNLGRP_IPV4_MROUTE_R RTNLGRP_IPV4_MROUTE_R RTNLGRP_IPV6_MROUTE_R, #define RTNLGRP_IPV6_MROUTE_R RTNLGRP_IPV6_MROUTE_R RTNLGRP_NEXTHOP, #define RTNLGRP_NEXTHOP RTNLGRP_NEXTHOP RTNLGRP_BRVLAN, #define RTNLGRP_BRVLAN RTNLGRP_BRVLAN __RTNLGRP_MAX }; #define RTNLGRP_MAX (__RTNLGRP_MAX - 1) /* TC action piece */ struct tcamsg { unsigned char tca_family; unsigned char tca__pad1; unsigned short tca__pad2; }; enum { TCA_ROOT_UNSPEC, TCA_ROOT_TAB, #define TCA_ACT_TAB TCA_ROOT_TAB #define TCAA_MAX TCA_ROOT_TAB TCA_ROOT_FLAGS, TCA_ROOT_COUNT, TCA_ROOT_TIME_DELTA, /* in msecs */ TCA_ROOT_EXT_WARN_MSG, __TCA_ROOT_MAX, #define TCA_ROOT_MAX (__TCA_ROOT_MAX - 1) }; #define TA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcamsg)))) #define TA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcamsg)) /* tcamsg flags stored in attribute TCA_ROOT_FLAGS * * TCA_ACT_FLAG_LARGE_DUMP_ON user->kernel to request for larger than * TCA_ACT_MAX_PRIO actions in a dump. All dump responses will contain the * number of actions being dumped stored in for user app's consumption in * TCA_ROOT_COUNT * * TCA_ACT_FLAG_TERSE_DUMP user->kernel to request terse (brief) dump that only * includes essential action info (kind, index, etc.) * */ #define TCA_FLAG_LARGE_DUMP_ON (1 << 0) #define TCA_ACT_FLAG_LARGE_DUMP_ON TCA_FLAG_LARGE_DUMP_ON #define TCA_ACT_FLAG_TERSE_DUMP (1 << 1) /* New extended info filters for IFLA_EXT_MASK */ #define RTEXT_FILTER_VF (1 << 0) #define RTEXT_FILTER_BRVLAN (1 << 1) #define RTEXT_FILTER_BRVLAN_COMPRESSED (1 << 2) #define RTEXT_FILTER_SKIP_STATS (1 << 3) #define RTEXT_FILTER_MRP (1 << 4) #define RTEXT_FILTER_CFM_CONFIG (1 << 5) #define RTEXT_FILTER_CFM_STATUS (1 << 6) #define RTEXT_FILTER_MST (1 << 7) /* End of information exported to user level */ #endif /* __LINUX_RTNETLINK_H */ linux/virtio_vsock.h000064400000006016151027430560010603 0ustar00/* * This header, excluding the #ifdef __KERNEL__ part, is BSD licensed so * anyone can use the definitions to implement compatible drivers/servers: * * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Copyright (C) Red Hat, Inc., 2013-2015 * Copyright (C) Asias He , 2013 * Copyright (C) Stefan Hajnoczi , 2015 */ #ifndef _LINUX_VIRTIO_VSOCK_H #define _LINUX_VIRTIO_VSOCK_H #include #include #include struct virtio_vsock_config { __le64 guest_cid; } __attribute__((packed)); enum virtio_vsock_event_id { VIRTIO_VSOCK_EVENT_TRANSPORT_RESET = 0, }; struct virtio_vsock_event { __le32 id; } __attribute__((packed)); struct virtio_vsock_hdr { __le64 src_cid; __le64 dst_cid; __le32 src_port; __le32 dst_port; __le32 len; __le16 type; /* enum virtio_vsock_type */ __le16 op; /* enum virtio_vsock_op */ __le32 flags; __le32 buf_alloc; __le32 fwd_cnt; } __attribute__((packed)); enum virtio_vsock_type { VIRTIO_VSOCK_TYPE_STREAM = 1, }; enum virtio_vsock_op { VIRTIO_VSOCK_OP_INVALID = 0, /* Connect operations */ VIRTIO_VSOCK_OP_REQUEST = 1, VIRTIO_VSOCK_OP_RESPONSE = 2, VIRTIO_VSOCK_OP_RST = 3, VIRTIO_VSOCK_OP_SHUTDOWN = 4, /* To send payload */ VIRTIO_VSOCK_OP_RW = 5, /* Tell the peer our credit info */ VIRTIO_VSOCK_OP_CREDIT_UPDATE = 6, /* Request the peer to send the credit info to us */ VIRTIO_VSOCK_OP_CREDIT_REQUEST = 7, }; /* VIRTIO_VSOCK_OP_SHUTDOWN flags values */ enum virtio_vsock_shutdown { VIRTIO_VSOCK_SHUTDOWN_RCV = 1, VIRTIO_VSOCK_SHUTDOWN_SEND = 2, }; #endif /* _LINUX_VIRTIO_VSOCK_H */ linux/acct.h000064400000007225151027430560006777 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * BSD Process Accounting for Linux - Definitions * * Author: Marco van Wieringen (mvw@planets.elm.net) * * This header file contains the definitions needed to implement * BSD-style process accounting. The kernel accounting code and all * user-level programs that try to do something useful with the * process accounting log must include this file. * * Copyright (C) 1995 - 1997 Marco van Wieringen - ELM Consultancy B.V. * */ #ifndef _LINUX_ACCT_H #define _LINUX_ACCT_H #include #include #include /* * comp_t is a 16-bit "floating" point number with a 3-bit base 8 * exponent and a 13-bit fraction. * comp2_t is 24-bit with 5-bit base 2 exponent and 20 bit fraction * (leading 1 not stored). * See linux/kernel/acct.c for the specific encoding systems used. */ typedef __u16 comp_t; typedef __u32 comp2_t; /* * accounting file record * * This structure contains all of the information written out to the * process accounting file whenever a process exits. */ #define ACCT_COMM 16 struct acct { char ac_flag; /* Flags */ char ac_version; /* Always set to ACCT_VERSION */ /* for binary compatibility back until 2.0 */ __u16 ac_uid16; /* LSB of Real User ID */ __u16 ac_gid16; /* LSB of Real Group ID */ __u16 ac_tty; /* Control Terminal */ __u32 ac_btime; /* Process Creation Time */ comp_t ac_utime; /* User Time */ comp_t ac_stime; /* System Time */ comp_t ac_etime; /* Elapsed Time */ comp_t ac_mem; /* Average Memory Usage */ comp_t ac_io; /* Chars Transferred */ comp_t ac_rw; /* Blocks Read or Written */ comp_t ac_minflt; /* Minor Pagefaults */ comp_t ac_majflt; /* Major Pagefaults */ comp_t ac_swaps; /* Number of Swaps */ /* m68k had no padding here. */ __u16 ac_ahz; /* AHZ */ __u32 ac_exitcode; /* Exitcode */ char ac_comm[ACCT_COMM + 1]; /* Command Name */ __u8 ac_etime_hi; /* Elapsed Time MSB */ __u16 ac_etime_lo; /* Elapsed Time LSB */ __u32 ac_uid; /* Real User ID */ __u32 ac_gid; /* Real Group ID */ }; struct acct_v3 { char ac_flag; /* Flags */ char ac_version; /* Always set to ACCT_VERSION */ __u16 ac_tty; /* Control Terminal */ __u32 ac_exitcode; /* Exitcode */ __u32 ac_uid; /* Real User ID */ __u32 ac_gid; /* Real Group ID */ __u32 ac_pid; /* Process ID */ __u32 ac_ppid; /* Parent Process ID */ __u32 ac_btime; /* Process Creation Time */ float ac_etime; /* Elapsed Time */ comp_t ac_utime; /* User Time */ comp_t ac_stime; /* System Time */ comp_t ac_mem; /* Average Memory Usage */ comp_t ac_io; /* Chars Transferred */ comp_t ac_rw; /* Blocks Read or Written */ comp_t ac_minflt; /* Minor Pagefaults */ comp_t ac_majflt; /* Major Pagefaults */ comp_t ac_swaps; /* Number of Swaps */ char ac_comm[ACCT_COMM]; /* Command Name */ }; /* * accounting flags */ /* bit set when the process ... */ #define AFORK 0x01 /* ... executed fork, but did not exec */ #define ASU 0x02 /* ... used super-user privileges */ #define ACOMPAT 0x04 /* ... used compatibility mode (VAX only not used) */ #define ACORE 0x08 /* ... dumped core */ #define AXSIG 0x10 /* ... was killed by a signal */ #if defined(__BYTE_ORDER) ? __BYTE_ORDER == __BIG_ENDIAN : defined(__BIG_ENDIAN) #define ACCT_BYTEORDER 0x80 /* accounting file is big endian */ #elif defined(__BYTE_ORDER) ? __BYTE_ORDER == __LITTLE_ENDIAN : defined(__LITTLE_ENDIAN) #define ACCT_BYTEORDER 0x00 /* accounting file is little endian */ #else #error unspecified endianness #endif #define ACCT_VERSION 2 #define AHZ (HZ) #endif /* _LINUX_ACCT_H */ linux/sock_diag.h000064400000002425151027430560010005 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __SOCK_DIAG_H__ #define __SOCK_DIAG_H__ #include #define SOCK_DIAG_BY_FAMILY 20 #define SOCK_DESTROY 21 struct sock_diag_req { __u8 sdiag_family; __u8 sdiag_protocol; }; enum { SK_MEMINFO_RMEM_ALLOC, SK_MEMINFO_RCVBUF, SK_MEMINFO_WMEM_ALLOC, SK_MEMINFO_SNDBUF, SK_MEMINFO_FWD_ALLOC, SK_MEMINFO_WMEM_QUEUED, SK_MEMINFO_OPTMEM, SK_MEMINFO_BACKLOG, SK_MEMINFO_DROPS, SK_MEMINFO_VARS, }; enum sknetlink_groups { SKNLGRP_NONE, SKNLGRP_INET_TCP_DESTROY, SKNLGRP_INET_UDP_DESTROY, SKNLGRP_INET6_TCP_DESTROY, SKNLGRP_INET6_UDP_DESTROY, __SKNLGRP_MAX, }; #define SKNLGRP_MAX (__SKNLGRP_MAX - 1) enum { SK_DIAG_BPF_STORAGE_REQ_NONE, SK_DIAG_BPF_STORAGE_REQ_MAP_FD, __SK_DIAG_BPF_STORAGE_REQ_MAX, }; #define SK_DIAG_BPF_STORAGE_REQ_MAX (__SK_DIAG_BPF_STORAGE_REQ_MAX - 1) enum { SK_DIAG_BPF_STORAGE_REP_NONE, SK_DIAG_BPF_STORAGE, __SK_DIAG_BPF_STORAGE_REP_MAX, }; #define SK_DIAB_BPF_STORAGE_REP_MAX (__SK_DIAG_BPF_STORAGE_REP_MAX - 1) enum { SK_DIAG_BPF_STORAGE_NONE, SK_DIAG_BPF_STORAGE_PAD, SK_DIAG_BPF_STORAGE_MAP_ID, SK_DIAG_BPF_STORAGE_MAP_VALUE, __SK_DIAG_BPF_STORAGE_MAX, }; #define SK_DIAG_BPF_STORAGE_MAX (__SK_DIAG_BPF_STORAGE_MAX - 1) #endif /* __SOCK_DIAG_H__ */ linux/reiserfs_fs.h000064400000001407151027430560010373 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright 1996, 1997, 1998 Hans Reiser, see reiserfs/README for licensing and copyright details */ #ifndef _LINUX_REISER_FS_H #define _LINUX_REISER_FS_H #include #include /* * include/linux/reiser_fs.h * * Reiser File System constants and structures * */ /* ioctl's command */ #define REISERFS_IOC_UNPACK _IOW(0xCD,1,long) /* define following flags to be the same as in ext2, so that chattr(1), lsattr(1) will work with us. */ #define REISERFS_IOC_GETFLAGS FS_IOC_GETFLAGS #define REISERFS_IOC_SETFLAGS FS_IOC_SETFLAGS #define REISERFS_IOC_GETVERSION FS_IOC_GETVERSION #define REISERFS_IOC_SETVERSION FS_IOC_SETVERSION #endif /* _LINUX_REISER_FS_H */ linux/switchtec_ioctl.h000064400000012216151027430560011250 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Microsemi Switchtec PCIe Driver * Copyright (c) 2017, Microsemi Corporation * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * */ #ifndef _LINUX_SWITCHTEC_IOCTL_H #define _LINUX_SWITCHTEC_IOCTL_H #include #define SWITCHTEC_IOCTL_PART_CFG0 0 #define SWITCHTEC_IOCTL_PART_CFG1 1 #define SWITCHTEC_IOCTL_PART_IMG0 2 #define SWITCHTEC_IOCTL_PART_IMG1 3 #define SWITCHTEC_IOCTL_PART_NVLOG 4 #define SWITCHTEC_IOCTL_PART_VENDOR0 5 #define SWITCHTEC_IOCTL_PART_VENDOR1 6 #define SWITCHTEC_IOCTL_PART_VENDOR2 7 #define SWITCHTEC_IOCTL_PART_VENDOR3 8 #define SWITCHTEC_IOCTL_PART_VENDOR4 9 #define SWITCHTEC_IOCTL_PART_VENDOR5 10 #define SWITCHTEC_IOCTL_PART_VENDOR6 11 #define SWITCHTEC_IOCTL_PART_VENDOR7 12 #define SWITCHTEC_IOCTL_PART_BL2_0 13 #define SWITCHTEC_IOCTL_PART_BL2_1 14 #define SWITCHTEC_IOCTL_PART_MAP_0 15 #define SWITCHTEC_IOCTL_PART_MAP_1 16 #define SWITCHTEC_IOCTL_PART_KEY_0 17 #define SWITCHTEC_IOCTL_PART_KEY_1 18 #define SWITCHTEC_NUM_PARTITIONS_GEN3 13 #define SWITCHTEC_NUM_PARTITIONS_GEN4 19 /* obsolete: for compatibility with old userspace software */ #define SWITCHTEC_IOCTL_NUM_PARTITIONS SWITCHTEC_NUM_PARTITIONS_GEN3 struct switchtec_ioctl_flash_info { __u64 flash_length; __u32 num_partitions; __u32 padding; }; #define SWITCHTEC_IOCTL_PART_ACTIVE 1 #define SWITCHTEC_IOCTL_PART_RUNNING 2 struct switchtec_ioctl_flash_part_info { __u32 flash_partition; __u32 address; __u32 length; __u32 active; }; struct switchtec_ioctl_event_summary_legacy { __u64 global; __u64 part_bitmap; __u32 local_part; __u32 padding; __u32 part[48]; __u32 pff[48]; }; struct switchtec_ioctl_event_summary { __u64 global; __u64 part_bitmap; __u32 local_part; __u32 padding; __u32 part[48]; __u32 pff[255]; }; #define SWITCHTEC_IOCTL_EVENT_STACK_ERROR 0 #define SWITCHTEC_IOCTL_EVENT_PPU_ERROR 1 #define SWITCHTEC_IOCTL_EVENT_ISP_ERROR 2 #define SWITCHTEC_IOCTL_EVENT_SYS_RESET 3 #define SWITCHTEC_IOCTL_EVENT_FW_EXC 4 #define SWITCHTEC_IOCTL_EVENT_FW_NMI 5 #define SWITCHTEC_IOCTL_EVENT_FW_NON_FATAL 6 #define SWITCHTEC_IOCTL_EVENT_FW_FATAL 7 #define SWITCHTEC_IOCTL_EVENT_TWI_MRPC_COMP 8 #define SWITCHTEC_IOCTL_EVENT_TWI_MRPC_COMP_ASYNC 9 #define SWITCHTEC_IOCTL_EVENT_CLI_MRPC_COMP 10 #define SWITCHTEC_IOCTL_EVENT_CLI_MRPC_COMP_ASYNC 11 #define SWITCHTEC_IOCTL_EVENT_GPIO_INT 12 #define SWITCHTEC_IOCTL_EVENT_PART_RESET 13 #define SWITCHTEC_IOCTL_EVENT_MRPC_COMP 14 #define SWITCHTEC_IOCTL_EVENT_MRPC_COMP_ASYNC 15 #define SWITCHTEC_IOCTL_EVENT_DYN_PART_BIND_COMP 16 #define SWITCHTEC_IOCTL_EVENT_AER_IN_P2P 17 #define SWITCHTEC_IOCTL_EVENT_AER_IN_VEP 18 #define SWITCHTEC_IOCTL_EVENT_DPC 19 #define SWITCHTEC_IOCTL_EVENT_CTS 20 #define SWITCHTEC_IOCTL_EVENT_HOTPLUG 21 #define SWITCHTEC_IOCTL_EVENT_IER 22 #define SWITCHTEC_IOCTL_EVENT_THRESH 23 #define SWITCHTEC_IOCTL_EVENT_POWER_MGMT 24 #define SWITCHTEC_IOCTL_EVENT_TLP_THROTTLING 25 #define SWITCHTEC_IOCTL_EVENT_FORCE_SPEED 26 #define SWITCHTEC_IOCTL_EVENT_CREDIT_TIMEOUT 27 #define SWITCHTEC_IOCTL_EVENT_LINK_STATE 28 #define SWITCHTEC_IOCTL_EVENT_GFMS 29 #define SWITCHTEC_IOCTL_EVENT_INTERCOMM_REQ_NOTIFY 30 #define SWITCHTEC_IOCTL_EVENT_UEC 31 #define SWITCHTEC_IOCTL_MAX_EVENTS 32 #define SWITCHTEC_IOCTL_EVENT_LOCAL_PART_IDX -1 #define SWITCHTEC_IOCTL_EVENT_IDX_ALL -2 #define SWITCHTEC_IOCTL_EVENT_FLAG_CLEAR (1 << 0) #define SWITCHTEC_IOCTL_EVENT_FLAG_EN_POLL (1 << 1) #define SWITCHTEC_IOCTL_EVENT_FLAG_EN_LOG (1 << 2) #define SWITCHTEC_IOCTL_EVENT_FLAG_EN_CLI (1 << 3) #define SWITCHTEC_IOCTL_EVENT_FLAG_EN_FATAL (1 << 4) #define SWITCHTEC_IOCTL_EVENT_FLAG_DIS_POLL (1 << 5) #define SWITCHTEC_IOCTL_EVENT_FLAG_DIS_LOG (1 << 6) #define SWITCHTEC_IOCTL_EVENT_FLAG_DIS_CLI (1 << 7) #define SWITCHTEC_IOCTL_EVENT_FLAG_DIS_FATAL (1 << 8) #define SWITCHTEC_IOCTL_EVENT_FLAG_UNUSED (~0x1ff) struct switchtec_ioctl_event_ctl { __u32 event_id; __s32 index; __u32 flags; __u32 occurred; __u32 count; __u32 data[5]; }; #define SWITCHTEC_IOCTL_PFF_VEP 100 struct switchtec_ioctl_pff_port { __u32 pff; __u32 partition; __u32 port; }; #define SWITCHTEC_IOCTL_FLASH_INFO \ _IOR('W', 0x40, struct switchtec_ioctl_flash_info) #define SWITCHTEC_IOCTL_FLASH_PART_INFO \ _IOWR('W', 0x41, struct switchtec_ioctl_flash_part_info) #define SWITCHTEC_IOCTL_EVENT_SUMMARY \ _IOR('W', 0x42, struct switchtec_ioctl_event_summary) #define SWITCHTEC_IOCTL_EVENT_SUMMARY_LEGACY \ _IOR('W', 0x42, struct switchtec_ioctl_event_summary_legacy) #define SWITCHTEC_IOCTL_EVENT_CTL \ _IOWR('W', 0x43, struct switchtec_ioctl_event_ctl) #define SWITCHTEC_IOCTL_PFF_TO_PORT \ _IOWR('W', 0x44, struct switchtec_ioctl_pff_port) #define SWITCHTEC_IOCTL_PORT_TO_PFF \ _IOWR('W', 0x45, struct switchtec_ioctl_pff_port) #endif linux/usbip.h000064400000001200151027430560007172 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * usbip.h * * USBIP uapi defines and function prototypes etc. */ #ifndef _LINUX_USBIP_H #define _LINUX_USBIP_H /* usbip device status - exported in usbip device sysfs status */ enum usbip_device_status { /* sdev is available. */ SDEV_ST_AVAILABLE = 0x01, /* sdev is now used. */ SDEV_ST_USED, /* sdev is unusable because of a fatal error. */ SDEV_ST_ERROR, /* vdev does not connect a remote device. */ VDEV_ST_NULL, /* vdev is used, but the USB address is not assigned yet */ VDEV_ST_NOTASSIGNED, VDEV_ST_USED, VDEV_ST_ERROR }; #endif /* _LINUX_USBIP_H */ linux/ptrace.h000064400000007132151027430560007340 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_PTRACE_H #define _LINUX_PTRACE_H /* ptrace.h */ /* structs and defines to help the user use the ptrace system call. */ /* has the defines to get at the registers. */ #include #define PTRACE_TRACEME 0 #define PTRACE_PEEKTEXT 1 #define PTRACE_PEEKDATA 2 #define PTRACE_PEEKUSR 3 #define PTRACE_POKETEXT 4 #define PTRACE_POKEDATA 5 #define PTRACE_POKEUSR 6 #define PTRACE_CONT 7 #define PTRACE_KILL 8 #define PTRACE_SINGLESTEP 9 #define PTRACE_ATTACH 16 #define PTRACE_DETACH 17 #define PTRACE_SYSCALL 24 /* 0x4200-0x4300 are reserved for architecture-independent additions. */ #define PTRACE_SETOPTIONS 0x4200 #define PTRACE_GETEVENTMSG 0x4201 #define PTRACE_GETSIGINFO 0x4202 #define PTRACE_SETSIGINFO 0x4203 /* * Generic ptrace interface that exports the architecture specific regsets * using the corresponding NT_* types (which are also used in the core dump). * Please note that the NT_PRSTATUS note type in a core dump contains a full * 'struct elf_prstatus'. But the user_regset for NT_PRSTATUS contains just the * elf_gregset_t that is the pr_reg field of 'struct elf_prstatus'. For all the * other user_regset flavors, the user_regset layout and the ELF core dump note * payload are exactly the same layout. * * This interface usage is as follows: * struct iovec iov = { buf, len}; * * ret = ptrace(PTRACE_GETREGSET/PTRACE_SETREGSET, pid, NT_XXX_TYPE, &iov); * * On the successful completion, iov.len will be updated by the kernel, * specifying how much the kernel has written/read to/from the user's iov.buf. */ #define PTRACE_GETREGSET 0x4204 #define PTRACE_SETREGSET 0x4205 #define PTRACE_SEIZE 0x4206 #define PTRACE_INTERRUPT 0x4207 #define PTRACE_LISTEN 0x4208 #define PTRACE_PEEKSIGINFO 0x4209 struct ptrace_peeksiginfo_args { __u64 off; /* from which siginfo to start */ __u32 flags; __s32 nr; /* how may siginfos to take */ }; #define PTRACE_GETSIGMASK 0x420a #define PTRACE_SETSIGMASK 0x420b #define PTRACE_SECCOMP_GET_FILTER 0x420c #define PTRACE_SECCOMP_GET_METADATA 0x420d struct seccomp_metadata { __u64 filter_off; /* Input: which filter */ __u64 flags; /* Output: filter's flags */ }; #define PTRACE_GET_RSEQ_CONFIGURATION 0x420f struct ptrace_rseq_configuration { __u64 rseq_abi_pointer; __u32 rseq_abi_size; __u32 signature; __u32 flags; __u32 pad; }; /* Read signals from a shared (process wide) queue */ #define PTRACE_PEEKSIGINFO_SHARED (1 << 0) /* Wait extended result codes for the above trace options. */ #define PTRACE_EVENT_FORK 1 #define PTRACE_EVENT_VFORK 2 #define PTRACE_EVENT_CLONE 3 #define PTRACE_EVENT_EXEC 4 #define PTRACE_EVENT_VFORK_DONE 5 #define PTRACE_EVENT_EXIT 6 #define PTRACE_EVENT_SECCOMP 7 /* Extended result codes which enabled by means other than options. */ #define PTRACE_EVENT_STOP 128 /* Options set using PTRACE_SETOPTIONS or using PTRACE_SEIZE @data param */ #define PTRACE_O_TRACESYSGOOD 1 #define PTRACE_O_TRACEFORK (1 << PTRACE_EVENT_FORK) #define PTRACE_O_TRACEVFORK (1 << PTRACE_EVENT_VFORK) #define PTRACE_O_TRACECLONE (1 << PTRACE_EVENT_CLONE) #define PTRACE_O_TRACEEXEC (1 << PTRACE_EVENT_EXEC) #define PTRACE_O_TRACEVFORKDONE (1 << PTRACE_EVENT_VFORK_DONE) #define PTRACE_O_TRACEEXIT (1 << PTRACE_EVENT_EXIT) #define PTRACE_O_TRACESECCOMP (1 << PTRACE_EVENT_SECCOMP) /* eventless options */ #define PTRACE_O_EXITKILL (1 << 20) #define PTRACE_O_SUSPEND_SECCOMP (1 << 21) #define PTRACE_O_MASK (\ 0x000000ff | PTRACE_O_EXITKILL | PTRACE_O_SUSPEND_SECCOMP) #include #endif /* _LINUX_PTRACE_H */ linux/virtio_pci.h000064400000016356151027430560010241 0ustar00/* * Virtio PCI driver * * This module allows virtio devices to be used over a virtual PCI device. * This can be used with QEMU based VMMs like KVM or Xen. * * Copyright IBM Corp. 2007 * * Authors: * Anthony Liguori * * This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _LINUX_VIRTIO_PCI_H #define _LINUX_VIRTIO_PCI_H #include #ifndef VIRTIO_PCI_NO_LEGACY /* A 32-bit r/o bitmask of the features supported by the host */ #define VIRTIO_PCI_HOST_FEATURES 0 /* A 32-bit r/w bitmask of features activated by the guest */ #define VIRTIO_PCI_GUEST_FEATURES 4 /* A 32-bit r/w PFN for the currently selected queue */ #define VIRTIO_PCI_QUEUE_PFN 8 /* A 16-bit r/o queue size for the currently selected queue */ #define VIRTIO_PCI_QUEUE_NUM 12 /* A 16-bit r/w queue selector */ #define VIRTIO_PCI_QUEUE_SEL 14 /* A 16-bit r/w queue notifier */ #define VIRTIO_PCI_QUEUE_NOTIFY 16 /* An 8-bit device status register. */ #define VIRTIO_PCI_STATUS 18 /* An 8-bit r/o interrupt status register. Reading the value will return the * current contents of the ISR and will also clear it. This is effectively * a read-and-acknowledge. */ #define VIRTIO_PCI_ISR 19 /* MSI-X registers: only enabled if MSI-X is enabled. */ /* A 16-bit vector for configuration changes. */ #define VIRTIO_MSI_CONFIG_VECTOR 20 /* A 16-bit vector for selected queue notifications. */ #define VIRTIO_MSI_QUEUE_VECTOR 22 /* The remaining space is defined by each driver as the per-driver * configuration space */ #define VIRTIO_PCI_CONFIG_OFF(msix_enabled) ((msix_enabled) ? 24 : 20) /* Deprecated: please use VIRTIO_PCI_CONFIG_OFF instead */ #define VIRTIO_PCI_CONFIG(dev) VIRTIO_PCI_CONFIG_OFF((dev)->msix_enabled) /* Virtio ABI version, this must match exactly */ #define VIRTIO_PCI_ABI_VERSION 0 /* How many bits to shift physical queue address written to QUEUE_PFN. * 12 is historical, and due to x86 page size. */ #define VIRTIO_PCI_QUEUE_ADDR_SHIFT 12 /* The alignment to use between consumer and producer parts of vring. * x86 pagesize again. */ #define VIRTIO_PCI_VRING_ALIGN 4096 #endif /* VIRTIO_PCI_NO_LEGACY */ /* The bit of the ISR which indicates a device configuration change. */ #define VIRTIO_PCI_ISR_CONFIG 0x2 /* Vector value used to disable MSI for queue */ #define VIRTIO_MSI_NO_VECTOR 0xffff #ifndef VIRTIO_PCI_NO_MODERN /* IDs for different capabilities. Must all exist. */ /* Common configuration */ #define VIRTIO_PCI_CAP_COMMON_CFG 1 /* Notifications */ #define VIRTIO_PCI_CAP_NOTIFY_CFG 2 /* ISR access */ #define VIRTIO_PCI_CAP_ISR_CFG 3 /* Device specific configuration */ #define VIRTIO_PCI_CAP_DEVICE_CFG 4 /* PCI configuration access */ #define VIRTIO_PCI_CAP_PCI_CFG 5 /* Additional shared memory capability */ #define VIRTIO_PCI_CAP_SHARED_MEMORY_CFG 8 /* This is the PCI capability header: */ struct virtio_pci_cap { __u8 cap_vndr; /* Generic PCI field: PCI_CAP_ID_VNDR */ __u8 cap_next; /* Generic PCI field: next ptr. */ __u8 cap_len; /* Generic PCI field: capability length */ __u8 cfg_type; /* Identifies the structure. */ __u8 bar; /* Where to find it. */ __u8 id; /* Multiple capabilities of the same type */ __u8 padding[2]; /* Pad to full dword. */ __le32 offset; /* Offset within bar. */ __le32 length; /* Length of the structure, in bytes. */ }; struct virtio_pci_cap64 { struct virtio_pci_cap cap; __le32 offset_hi; /* Most sig 32 bits of offset */ __le32 length_hi; /* Most sig 32 bits of length */ }; struct virtio_pci_notify_cap { struct virtio_pci_cap cap; __le32 notify_off_multiplier; /* Multiplier for queue_notify_off. */ }; /* Fields in VIRTIO_PCI_CAP_COMMON_CFG: */ struct virtio_pci_common_cfg { /* About the whole device. */ __le32 device_feature_select; /* read-write */ __le32 device_feature; /* read-only */ __le32 guest_feature_select; /* read-write */ __le32 guest_feature; /* read-write */ __le16 msix_config; /* read-write */ __le16 num_queues; /* read-only */ __u8 device_status; /* read-write */ __u8 config_generation; /* read-only */ /* About a specific virtqueue. */ __le16 queue_select; /* read-write */ __le16 queue_size; /* read-write, power of 2. */ __le16 queue_msix_vector; /* read-write */ __le16 queue_enable; /* read-write */ __le16 queue_notify_off; /* read-only */ __le32 queue_desc_lo; /* read-write */ __le32 queue_desc_hi; /* read-write */ __le32 queue_avail_lo; /* read-write */ __le32 queue_avail_hi; /* read-write */ __le32 queue_used_lo; /* read-write */ __le32 queue_used_hi; /* read-write */ }; /* Fields in VIRTIO_PCI_CAP_PCI_CFG: */ struct virtio_pci_cfg_cap { struct virtio_pci_cap cap; __u8 pci_cfg_data[4]; /* Data for BAR access. */ }; /* Macro versions of offsets for the Old Timers! */ #define VIRTIO_PCI_CAP_VNDR 0 #define VIRTIO_PCI_CAP_NEXT 1 #define VIRTIO_PCI_CAP_LEN 2 #define VIRTIO_PCI_CAP_CFG_TYPE 3 #define VIRTIO_PCI_CAP_BAR 4 #define VIRTIO_PCI_CAP_OFFSET 8 #define VIRTIO_PCI_CAP_LENGTH 12 #define VIRTIO_PCI_NOTIFY_CAP_MULT 16 #define VIRTIO_PCI_COMMON_DFSELECT 0 #define VIRTIO_PCI_COMMON_DF 4 #define VIRTIO_PCI_COMMON_GFSELECT 8 #define VIRTIO_PCI_COMMON_GF 12 #define VIRTIO_PCI_COMMON_MSIX 16 #define VIRTIO_PCI_COMMON_NUMQ 18 #define VIRTIO_PCI_COMMON_STATUS 20 #define VIRTIO_PCI_COMMON_CFGGENERATION 21 #define VIRTIO_PCI_COMMON_Q_SELECT 22 #define VIRTIO_PCI_COMMON_Q_SIZE 24 #define VIRTIO_PCI_COMMON_Q_MSIX 26 #define VIRTIO_PCI_COMMON_Q_ENABLE 28 #define VIRTIO_PCI_COMMON_Q_NOFF 30 #define VIRTIO_PCI_COMMON_Q_DESCLO 32 #define VIRTIO_PCI_COMMON_Q_DESCHI 36 #define VIRTIO_PCI_COMMON_Q_AVAILLO 40 #define VIRTIO_PCI_COMMON_Q_AVAILHI 44 #define VIRTIO_PCI_COMMON_Q_USEDLO 48 #define VIRTIO_PCI_COMMON_Q_USEDHI 52 #endif /* VIRTIO_PCI_NO_MODERN */ #endif linux/zorro_ids.h000064400000072413151027430560010100 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Zorro board IDs * * Please keep sorted. */ #define ZORRO_MANUF_PACIFIC_PERIPHERALS 0x00D3 #define ZORRO_PROD_PACIFIC_PERIPHERALS_SE_2000_A500 ZORRO_ID(PACIFIC_PERIPHERALS, 0x00, 0) #define ZORRO_PROD_PACIFIC_PERIPHERALS_SCSI ZORRO_ID(PACIFIC_PERIPHERALS, 0x0A, 0) #define ZORRO_MANUF_MACROSYSTEMS_USA_2 0x0100 #define ZORRO_PROD_MACROSYSTEMS_WARP_ENGINE ZORRO_ID(MACROSYSTEMS_USA_2, 0x13, 0) #define ZORRO_MANUF_KUPKE_1 0x00DD #define ZORRO_PROD_KUPKE_GOLEM_RAM_BOX_2MB ZORRO_ID(KUPKE_1, 0x00, 0) #define ZORRO_MANUF_MEMPHIS 0x0100 #define ZORRO_PROD_MEMPHIS_STORMBRINGER ZORRO_ID(MEMPHIS, 0x00, 0) #define ZORRO_MANUF_3_STATE 0x0200 #define ZORRO_PROD_3_STATE_MEGAMIX_2000 ZORRO_ID(3_STATE, 0x02, 0) #define ZORRO_MANUF_COMMODORE_BRAUNSCHWEIG 0x0201 #define ZORRO_PROD_CBM_A2088_A2286 ZORRO_ID(COMMODORE_BRAUNSCHWEIG, 0x01, 0) #define ZORRO_PROD_CBM_A2286 ZORRO_ID(COMMODORE_BRAUNSCHWEIG, 0x02, 0) #define ZORRO_PROD_CBM_A4091_1 ZORRO_ID(COMMODORE_BRAUNSCHWEIG, 0x54, 0) #define ZORRO_PROD_CBM_A2386SX_1 ZORRO_ID(COMMODORE_BRAUNSCHWEIG, 0x67, 0) #define ZORRO_MANUF_COMMODORE_WEST_CHESTER_1 0x0202 #define ZORRO_PROD_CBM_A2090A ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x01, 0) #define ZORRO_PROD_CBM_A590_A2091_1 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x02, 0) #define ZORRO_PROD_CBM_A590_A2091_2 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x03, 0) #define ZORRO_PROD_CBM_A2090B ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x04, 0) #define ZORRO_PROD_CBM_A2060 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x09, 0) #define ZORRO_PROD_CBM_A590_A2052_A2058_A2091 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x0A, 0) #define ZORRO_PROD_CBM_A560_RAM ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x20, 0) #define ZORRO_PROD_CBM_A2232_PROTOTYPE ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x45, 0) #define ZORRO_PROD_CBM_A2232 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x46, 0) #define ZORRO_PROD_CBM_A2620 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x50, 0) #define ZORRO_PROD_CBM_A2630 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x51, 0) #define ZORRO_PROD_CBM_A4091_2 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x54, 0) #define ZORRO_PROD_CBM_A2065_1 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x5A, 0) #define ZORRO_PROD_CBM_ROMULATOR ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x60, 0) #define ZORRO_PROD_CBM_A3000_TEST_FIXTURE ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x61, 0) #define ZORRO_PROD_CBM_A2386SX_2 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x67, 0) #define ZORRO_PROD_CBM_A2065_2 ZORRO_ID(COMMODORE_WEST_CHESTER_1, 0x70, 0) #define ZORRO_MANUF_COMMODORE_WEST_CHESTER_2 0x0203 #define ZORRO_PROD_CBM_A2090A_CM ZORRO_ID(COMMODORE_WEST_CHESTER_2, 0x03, 0) #define ZORRO_MANUF_PROGRESSIVE_PERIPHERALS_AND_SYSTEMS_2 0x02F4 #define ZORRO_PROD_PPS_EXP8000 ZORRO_ID(PROGRESSIVE_PERIPHERALS_AND_SYSTEMS_2, 0x02, 0) #define ZORRO_MANUF_KOLFF_COMPUTER_SUPPLIES 0x02FF #define ZORRO_PROD_KCS_POWER_PC_BOARD ZORRO_ID(KOLFF_COMPUTER_SUPPLIES, 0x00, 0) #define ZORRO_MANUF_CARDCO_1 0x03EC #define ZORRO_PROD_CARDCO_KRONOS_2000_1 ZORRO_ID(CARDCO_1, 0x04, 0) #define ZORRO_PROD_CARDCO_A1000_1 ZORRO_ID(CARDCO_1, 0x0C, 0) #define ZORRO_PROD_CARDCO_ESCORT ZORRO_ID(CARDCO_1, 0x0E, 0) #define ZORRO_PROD_CARDCO_A2410 ZORRO_ID(CARDCO_1, 0xF5, 0) #define ZORRO_MANUF_A_SQUARED 0x03ED #define ZORRO_PROD_A_SQUARED_LIVE_2000 ZORRO_ID(A_SQUARED, 0x01, 0) #define ZORRO_MANUF_COMSPEC_COMMUNICATIONS 0x03EE #define ZORRO_PROD_COMSPEC_COMMUNICATIONS_AX2000 ZORRO_ID(COMSPEC_COMMUNICATIONS, 0x01, 0) #define ZORRO_MANUF_ANAKIN_RESEARCH 0x03F1 #define ZORRO_PROD_ANAKIN_RESEARCH_EASYL ZORRO_ID(ANAKIN_RESEARCH, 0x01, 0) #define ZORRO_MANUF_MICROBOTICS 0x03F2 #define ZORRO_PROD_MICROBOTICS_STARBOARD_II ZORRO_ID(MICROBOTICS, 0x00, 0) #define ZORRO_PROD_MICROBOTICS_STARDRIVE ZORRO_ID(MICROBOTICS, 0x02, 0) #define ZORRO_PROD_MICROBOTICS_8_UP_A ZORRO_ID(MICROBOTICS, 0x03, 0) #define ZORRO_PROD_MICROBOTICS_8_UP_Z ZORRO_ID(MICROBOTICS, 0x04, 0) #define ZORRO_PROD_MICROBOTICS_DELTA_RAM ZORRO_ID(MICROBOTICS, 0x20, 0) #define ZORRO_PROD_MICROBOTICS_8_STAR_RAM ZORRO_ID(MICROBOTICS, 0x40, 0) #define ZORRO_PROD_MICROBOTICS_8_STAR ZORRO_ID(MICROBOTICS, 0x41, 0) #define ZORRO_PROD_MICROBOTICS_VXL_RAM_32 ZORRO_ID(MICROBOTICS, 0x44, 0) #define ZORRO_PROD_MICROBOTICS_VXL_68030 ZORRO_ID(MICROBOTICS, 0x45, 0) #define ZORRO_PROD_MICROBOTICS_DELTA ZORRO_ID(MICROBOTICS, 0x60, 0) #define ZORRO_PROD_MICROBOTICS_MBX_1200_1200Z_RAM ZORRO_ID(MICROBOTICS, 0x81, 0) #define ZORRO_PROD_MICROBOTICS_HARDFRAME_2000_1 ZORRO_ID(MICROBOTICS, 0x96, 0) #define ZORRO_PROD_MICROBOTICS_HARDFRAME_2000_2 ZORRO_ID(MICROBOTICS, 0x9E, 0) #define ZORRO_PROD_MICROBOTICS_MBX_1200_1200Z ZORRO_ID(MICROBOTICS, 0xC1, 0) #define ZORRO_MANUF_ACCESS_ASSOCIATES_ALEGRA 0x03F4 #define ZORRO_MANUF_EXPANSION_TECHNOLOGIES 0x03F6 #define ZORRO_MANUF_ASDG 0x03FF #define ZORRO_PROD_ASDG_MEMORY_1 ZORRO_ID(ASDG, 0x01, 0) #define ZORRO_PROD_ASDG_MEMORY_2 ZORRO_ID(ASDG, 0x02, 0) #define ZORRO_PROD_ASDG_EB920_LAN_ROVER ZORRO_ID(ASDG, 0xFE, 0) #define ZORRO_PROD_ASDG_GPIB_DUALIEEE488_TWIN_X ZORRO_ID(ASDG, 0xFF, 0) #define ZORRO_MANUF_IMTRONICS_1 0x0404 #define ZORRO_PROD_IMTRONICS_HURRICANE_2800_1 ZORRO_ID(IMTRONICS_1, 0x39, 0) #define ZORRO_PROD_IMTRONICS_HURRICANE_2800_2 ZORRO_ID(IMTRONICS_1, 0x57, 0) #define ZORRO_MANUF_CBM_UNIVERSITY_OF_LOWELL 0x0406 #define ZORRO_PROD_CBM_A2410 ZORRO_ID(CBM_UNIVERSITY_OF_LOWELL, 0x00, 0) #define ZORRO_MANUF_AMERISTAR 0x041D #define ZORRO_PROD_AMERISTAR_A2065 ZORRO_ID(AMERISTAR, 0x01, 0) #define ZORRO_PROD_AMERISTAR_A560 ZORRO_ID(AMERISTAR, 0x09, 0) #define ZORRO_PROD_AMERISTAR_A4066 ZORRO_ID(AMERISTAR, 0x0A, 0) #define ZORRO_MANUF_SUPRA 0x0420 #define ZORRO_PROD_SUPRA_SUPRADRIVE_4x4 ZORRO_ID(SUPRA, 0x01, 0) #define ZORRO_PROD_SUPRA_1000_RAM ZORRO_ID(SUPRA, 0x02, 0) #define ZORRO_PROD_SUPRA_2000_DMA ZORRO_ID(SUPRA, 0x03, 0) #define ZORRO_PROD_SUPRA_500 ZORRO_ID(SUPRA, 0x05, 0) #define ZORRO_PROD_SUPRA_500_SCSI ZORRO_ID(SUPRA, 0x08, 0) #define ZORRO_PROD_SUPRA_500XP_2000_RAM ZORRO_ID(SUPRA, 0x09, 0) #define ZORRO_PROD_SUPRA_500RX_2000_RAM ZORRO_ID(SUPRA, 0x0A, 0) #define ZORRO_PROD_SUPRA_2400ZI ZORRO_ID(SUPRA, 0x0B, 0) #define ZORRO_PROD_SUPRA_500XP_SUPRADRIVE_WORDSYNC ZORRO_ID(SUPRA, 0x0C, 0) #define ZORRO_PROD_SUPRA_SUPRADRIVE_WORDSYNC_II ZORRO_ID(SUPRA, 0x0D, 0) #define ZORRO_PROD_SUPRA_2400ZIPLUS ZORRO_ID(SUPRA, 0x10, 0) #define ZORRO_MANUF_COMPUTER_SYSTEMS_ASSOCIATES 0x0422 #define ZORRO_PROD_CSA_MAGNUM ZORRO_ID(COMPUTER_SYSTEMS_ASSOCIATES, 0x11, 0) #define ZORRO_PROD_CSA_12_GAUGE ZORRO_ID(COMPUTER_SYSTEMS_ASSOCIATES, 0x15, 0) #define ZORRO_MANUF_MARC_MICHAEL_GROTH 0x0439 #define ZORRO_MANUF_M_TECH 0x0502 #define ZORRO_PROD_MTEC_AT500_1 ZORRO_ID(M_TECH, 0x03, 0) #define ZORRO_MANUF_GREAT_VALLEY_PRODUCTS_1 0x06E1 #define ZORRO_PROD_GVP_IMPACT_SERIES_I ZORRO_ID(GREAT_VALLEY_PRODUCTS_1, 0x08, 0) #define ZORRO_MANUF_BYTEBOX 0x07DA #define ZORRO_PROD_BYTEBOX_A500 ZORRO_ID(BYTEBOX, 0x00, 0) #define ZORRO_MANUF_DKB_POWER_COMPUTING 0x07DC #define ZORRO_PROD_DKB_POWER_COMPUTING_SECUREKEY ZORRO_ID(DKB_POWER_COMPUTING, 0x09, 0) #define ZORRO_PROD_DKB_POWER_COMPUTING_DKM_3128 ZORRO_ID(DKB_POWER_COMPUTING, 0x0E, 0) #define ZORRO_PROD_DKB_POWER_COMPUTING_RAPID_FIRE ZORRO_ID(DKB_POWER_COMPUTING, 0x0F, 0) #define ZORRO_PROD_DKB_POWER_COMPUTING_DKM_1202 ZORRO_ID(DKB_POWER_COMPUTING, 0x10, 0) #define ZORRO_PROD_DKB_POWER_COMPUTING_COBRA_VIPER_II_68EC030 ZORRO_ID(DKB_POWER_COMPUTING, 0x12, 0) #define ZORRO_PROD_DKB_POWER_COMPUTING_WILDFIRE_060_1 ZORRO_ID(DKB_POWER_COMPUTING, 0x17, 0) #define ZORRO_PROD_DKB_POWER_COMPUTING_WILDFIRE_060_2 ZORRO_ID(DKB_POWER_COMPUTING, 0xFF, 0) #define ZORRO_MANUF_GREAT_VALLEY_PRODUCTS_2 0x07E1 #define ZORRO_PROD_GVP_IMPACT_SERIES_I_4K ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x01, 0) #define ZORRO_PROD_GVP_IMPACT_SERIES_I_16K_2 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x02, 0) #define ZORRO_PROD_GVP_IMPACT_SERIES_I_16K_3 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x03, 0) #define ZORRO_PROD_GVP_IMPACT_3001_IDE_1 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x08, 0) #define ZORRO_PROD_GVP_IMPACT_3001_RAM ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x09, 0) #define ZORRO_PROD_GVP_IMPACT_SERIES_II_RAM_1 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0A, 0) #define ZORRO_PROD_GVP_EPC_BASE ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0) #define ZORRO_PROD_GVP_GFORCE_040_1 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x20) #define ZORRO_PROD_GVP_GFORCE_040_SCSI_1 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x30) #define ZORRO_PROD_GVP_A1291 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x40) #define ZORRO_PROD_GVP_COMBO_030_R4 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x60) #define ZORRO_PROD_GVP_COMBO_030_R4_SCSI ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x70) #define ZORRO_PROD_GVP_PHONEPAK ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x78) #define ZORRO_PROD_GVP_IO_EXTENDER ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0x98) #define ZORRO_PROD_GVP_GFORCE_030 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xa0) #define ZORRO_PROD_GVP_GFORCE_030_SCSI ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xb0) #define ZORRO_PROD_GVP_A530 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xc0) #define ZORRO_PROD_GVP_A530_SCSI ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xd0) #define ZORRO_PROD_GVP_COMBO_030_R3 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xe0) #define ZORRO_PROD_GVP_COMBO_030_R3_SCSI ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xf0) #define ZORRO_PROD_GVP_SERIES_II ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0B, 0xf8) #define ZORRO_PROD_GVP_IMPACT_3001_IDE_2 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0D, 0) /*#define ZORRO_PROD_GVP_A2000_030 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0D, 0)*/ /*#define ZORRO_PROD_GVP_GFORCE_040_SCSI_2 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x0D, 0)*/ #define ZORRO_PROD_GVP_GFORCE_040_060 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x16, 0) #define ZORRO_PROD_GVP_IMPACT_VISION_24 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0x20, 0) #define ZORRO_PROD_GVP_GFORCE_040_2 ZORRO_ID(GREAT_VALLEY_PRODUCTS_2, 0xFF, 0) #define ZORRO_MANUF_CALIFORNIA_ACCESS_SYNERGY 0x07E5 #define ZORRO_PROD_CALIFORNIA_ACCESS_SYNERGY_MALIBU ZORRO_ID(CALIFORNIA_ACCESS_SYNERGY, 0x01, 0) #define ZORRO_MANUF_XETEC 0x07E6 #define ZORRO_PROD_XETEC_FASTCARD ZORRO_ID(XETEC, 0x01, 0) #define ZORRO_PROD_XETEC_FASTCARD_RAM ZORRO_ID(XETEC, 0x02, 0) #define ZORRO_PROD_XETEC_FASTCARD_PLUS ZORRO_ID(XETEC, 0x03, 0) #define ZORRO_MANUF_PROGRESSIVE_PERIPHERALS_AND_SYSTEMS 0x07EA #define ZORRO_PROD_PPS_MERCURY ZORRO_ID(PROGRESSIVE_PERIPHERALS_AND_SYSTEMS, 0x00, 0) #define ZORRO_PROD_PPS_A3000_68040 ZORRO_ID(PROGRESSIVE_PERIPHERALS_AND_SYSTEMS, 0x01, 0) #define ZORRO_PROD_PPS_A2000_68040 ZORRO_ID(PROGRESSIVE_PERIPHERALS_AND_SYSTEMS, 0x69, 0) #define ZORRO_PROD_PPS_ZEUS ZORRO_ID(PROGRESSIVE_PERIPHERALS_AND_SYSTEMS, 0x96, 0) #define ZORRO_PROD_PPS_A500_68040 ZORRO_ID(PROGRESSIVE_PERIPHERALS_AND_SYSTEMS, 0xBB, 0) #define ZORRO_MANUF_XEBEC 0x07EC #define ZORRO_MANUF_SPIRIT_TECHNOLOGY 0x07F2 #define ZORRO_PROD_SPIRIT_TECHNOLOGY_INSIDER_IN1000 ZORRO_ID(SPIRIT_TECHNOLOGY, 0x01, 0) #define ZORRO_PROD_SPIRIT_TECHNOLOGY_INSIDER_IN500 ZORRO_ID(SPIRIT_TECHNOLOGY, 0x02, 0) #define ZORRO_PROD_SPIRIT_TECHNOLOGY_SIN500 ZORRO_ID(SPIRIT_TECHNOLOGY, 0x03, 0) #define ZORRO_PROD_SPIRIT_TECHNOLOGY_HDA_506 ZORRO_ID(SPIRIT_TECHNOLOGY, 0x04, 0) #define ZORRO_PROD_SPIRIT_TECHNOLOGY_AX_S ZORRO_ID(SPIRIT_TECHNOLOGY, 0x05, 0) #define ZORRO_PROD_SPIRIT_TECHNOLOGY_OCTABYTE ZORRO_ID(SPIRIT_TECHNOLOGY, 0x06, 0) #define ZORRO_PROD_SPIRIT_TECHNOLOGY_INMATE ZORRO_ID(SPIRIT_TECHNOLOGY, 0x08, 0) #define ZORRO_MANUF_SPIRIT_TECHNOLOGY_2 0x07F3 #define ZORRO_MANUF_BSC_ALFADATA_1 0x07FE #define ZORRO_PROD_BSC_ALF_3_1 ZORRO_ID(BSC_ALFADATA_1, 0x03, 0) #define ZORRO_MANUF_BSC_ALFADATA_2 0x0801 #define ZORRO_PROD_BSC_ALF_2_1 ZORRO_ID(BSC_ALFADATA_2, 0x01, 0) #define ZORRO_PROD_BSC_ALF_2_2 ZORRO_ID(BSC_ALFADATA_2, 0x02, 0) #define ZORRO_PROD_BSC_ALF_3_2 ZORRO_ID(BSC_ALFADATA_2, 0x03, 0) #define ZORRO_MANUF_CARDCO_2 0x0802 #define ZORRO_PROD_CARDCO_KRONOS_2000_2 ZORRO_ID(CARDCO_2, 0x04, 0) #define ZORRO_PROD_CARDCO_A1000_2 ZORRO_ID(CARDCO_2, 0x0C, 0) #define ZORRO_MANUF_JOCHHEIM 0x0804 #define ZORRO_PROD_JOCHHEIM_RAM ZORRO_ID(JOCHHEIM, 0x01, 0) #define ZORRO_MANUF_CHECKPOINT_TECHNOLOGIES 0x0807 #define ZORRO_PROD_CHECKPOINT_TECHNOLOGIES_SERIAL_SOLUTION ZORRO_ID(CHECKPOINT_TECHNOLOGIES, 0x00, 0) #define ZORRO_MANUF_EDOTRONIK 0x0810 #define ZORRO_PROD_EDOTRONIK_IEEE_488 ZORRO_ID(EDOTRONIK, 0x01, 0) #define ZORRO_PROD_EDOTRONIK_8032 ZORRO_ID(EDOTRONIK, 0x02, 0) #define ZORRO_PROD_EDOTRONIK_MULTISERIAL ZORRO_ID(EDOTRONIK, 0x03, 0) #define ZORRO_PROD_EDOTRONIK_VIDEODIGITIZER ZORRO_ID(EDOTRONIK, 0x04, 0) #define ZORRO_PROD_EDOTRONIK_PARALLEL_IO ZORRO_ID(EDOTRONIK, 0x05, 0) #define ZORRO_PROD_EDOTRONIK_PIC_PROTOYPING ZORRO_ID(EDOTRONIK, 0x06, 0) #define ZORRO_PROD_EDOTRONIK_ADC ZORRO_ID(EDOTRONIK, 0x07, 0) #define ZORRO_PROD_EDOTRONIK_VME ZORRO_ID(EDOTRONIK, 0x08, 0) #define ZORRO_PROD_EDOTRONIK_DSP96000 ZORRO_ID(EDOTRONIK, 0x09, 0) #define ZORRO_MANUF_NES_INC 0x0813 #define ZORRO_PROD_NES_INC_RAM ZORRO_ID(NES_INC, 0x00, 0) #define ZORRO_MANUF_ICD 0x0817 #define ZORRO_PROD_ICD_ADVANTAGE_2000_SCSI ZORRO_ID(ICD, 0x01, 0) #define ZORRO_PROD_ICD_ADVANTAGE_IDE ZORRO_ID(ICD, 0x03, 0) #define ZORRO_PROD_ICD_ADVANTAGE_2080_RAM ZORRO_ID(ICD, 0x04, 0) #define ZORRO_MANUF_KUPKE_2 0x0819 #define ZORRO_PROD_KUPKE_OMTI ZORRO_ID(KUPKE_2, 0x01, 0) #define ZORRO_PROD_KUPKE_SCSI_II ZORRO_ID(KUPKE_2, 0x02, 0) #define ZORRO_PROD_KUPKE_GOLEM_BOX ZORRO_ID(KUPKE_2, 0x03, 0) #define ZORRO_PROD_KUPKE_030_882 ZORRO_ID(KUPKE_2, 0x04, 0) #define ZORRO_PROD_KUPKE_SCSI_AT ZORRO_ID(KUPKE_2, 0x05, 0) #define ZORRO_MANUF_GREAT_VALLEY_PRODUCTS_3 0x081D #define ZORRO_PROD_GVP_A2000_RAM8 ZORRO_ID(GREAT_VALLEY_PRODUCTS_3, 0x09, 0) #define ZORRO_PROD_GVP_IMPACT_SERIES_II_RAM_2 ZORRO_ID(GREAT_VALLEY_PRODUCTS_3, 0x0A, 0) #define ZORRO_MANUF_INTERWORKS_NETWORK 0x081E #define ZORRO_MANUF_HARDITAL_SYNTHESIS 0x0820 #define ZORRO_PROD_HARDITAL_SYNTHESIS_TQM_68030_68882 ZORRO_ID(HARDITAL_SYNTHESIS, 0x14, 0) #define ZORRO_MANUF_APPLIED_ENGINEERING 0x0828 #define ZORRO_PROD_APPLIED_ENGINEERING_DL2000 ZORRO_ID(APPLIED_ENGINEERING, 0x10, 0) #define ZORRO_PROD_APPLIED_ENGINEERING_RAM_WORKS ZORRO_ID(APPLIED_ENGINEERING, 0xE0, 0) #define ZORRO_MANUF_BSC_ALFADATA_3 0x082C #define ZORRO_PROD_BSC_OKTAGON_2008 ZORRO_ID(BSC_ALFADATA_3, 0x05, 0) #define ZORRO_PROD_BSC_TANDEM_AT_2008_508 ZORRO_ID(BSC_ALFADATA_3, 0x06, 0) #define ZORRO_PROD_BSC_ALFA_RAM_1200 ZORRO_ID(BSC_ALFADATA_3, 0x07, 0) #define ZORRO_PROD_BSC_OKTAGON_2008_RAM ZORRO_ID(BSC_ALFADATA_3, 0x08, 0) #define ZORRO_PROD_BSC_MULTIFACE_I ZORRO_ID(BSC_ALFADATA_3, 0x10, 0) #define ZORRO_PROD_BSC_MULTIFACE_II ZORRO_ID(BSC_ALFADATA_3, 0x11, 0) #define ZORRO_PROD_BSC_MULTIFACE_III ZORRO_ID(BSC_ALFADATA_3, 0x12, 0) #define ZORRO_PROD_BSC_FRAMEMASTER_II ZORRO_ID(BSC_ALFADATA_3, 0x20, 0) #define ZORRO_PROD_BSC_GRAFFITI_RAM ZORRO_ID(BSC_ALFADATA_3, 0x21, 0) #define ZORRO_PROD_BSC_GRAFFITI_REG ZORRO_ID(BSC_ALFADATA_3, 0x22, 0) #define ZORRO_PROD_BSC_ISDN_MASTERCARD ZORRO_ID(BSC_ALFADATA_3, 0x40, 0) #define ZORRO_PROD_BSC_ISDN_MASTERCARD_II ZORRO_ID(BSC_ALFADATA_3, 0x41, 0) #define ZORRO_MANUF_PHOENIX 0x0835 #define ZORRO_PROD_PHOENIX_ST506 ZORRO_ID(PHOENIX, 0x21, 0) #define ZORRO_PROD_PHOENIX_SCSI ZORRO_ID(PHOENIX, 0x22, 0) #define ZORRO_PROD_PHOENIX_RAM ZORRO_ID(PHOENIX, 0xBE, 0) #define ZORRO_MANUF_ADVANCED_STORAGE_SYSTEMS 0x0836 #define ZORRO_PROD_ADVANCED_STORAGE_SYSTEMS_NEXUS ZORRO_ID(ADVANCED_STORAGE_SYSTEMS, 0x01, 0) #define ZORRO_PROD_ADVANCED_STORAGE_SYSTEMS_NEXUS_RAM ZORRO_ID(ADVANCED_STORAGE_SYSTEMS, 0x08, 0) #define ZORRO_MANUF_IMPULSE 0x0838 #define ZORRO_PROD_IMPULSE_FIRECRACKER_24 ZORRO_ID(IMPULSE, 0x00, 0) #define ZORRO_MANUF_IVS 0x0840 #define ZORRO_PROD_IVS_GRANDSLAM_PIC_2 ZORRO_ID(IVS, 0x02, 0) #define ZORRO_PROD_IVS_GRANDSLAM_PIC_1 ZORRO_ID(IVS, 0x04, 0) #define ZORRO_PROD_IVS_OVERDRIVE ZORRO_ID(IVS, 0x10, 0) #define ZORRO_PROD_IVS_TRUMPCARD_CLASSIC ZORRO_ID(IVS, 0x30, 0) #define ZORRO_PROD_IVS_TRUMPCARD_PRO_GRANDSLAM ZORRO_ID(IVS, 0x34, 0) #define ZORRO_PROD_IVS_META_4 ZORRO_ID(IVS, 0x40, 0) #define ZORRO_PROD_IVS_WAVETOOLS ZORRO_ID(IVS, 0xBF, 0) #define ZORRO_PROD_IVS_VECTOR_1 ZORRO_ID(IVS, 0xF3, 0) #define ZORRO_PROD_IVS_VECTOR_2 ZORRO_ID(IVS, 0xF4, 0) #define ZORRO_MANUF_VECTOR_1 0x0841 #define ZORRO_PROD_VECTOR_CONNECTION_1 ZORRO_ID(VECTOR_1, 0xE3, 0) #define ZORRO_MANUF_XPERT_PRODEV 0x0845 #define ZORRO_PROD_XPERT_PRODEV_VISIONA_RAM ZORRO_ID(XPERT_PRODEV, 0x01, 0) #define ZORRO_PROD_XPERT_PRODEV_VISIONA_REG ZORRO_ID(XPERT_PRODEV, 0x02, 0) #define ZORRO_PROD_XPERT_PRODEV_MERLIN_RAM ZORRO_ID(XPERT_PRODEV, 0x03, 0) #define ZORRO_PROD_XPERT_PRODEV_MERLIN_REG_1 ZORRO_ID(XPERT_PRODEV, 0x04, 0) #define ZORRO_PROD_XPERT_PRODEV_MERLIN_REG_2 ZORRO_ID(XPERT_PRODEV, 0xC9, 0) #define ZORRO_MANUF_HYDRA_SYSTEMS 0x0849 #define ZORRO_PROD_HYDRA_SYSTEMS_AMIGANET ZORRO_ID(HYDRA_SYSTEMS, 0x01, 0) #define ZORRO_MANUF_SUNRIZE_INDUSTRIES 0x084F #define ZORRO_PROD_SUNRIZE_INDUSTRIES_AD1012 ZORRO_ID(SUNRIZE_INDUSTRIES, 0x01, 0) #define ZORRO_PROD_SUNRIZE_INDUSTRIES_AD516 ZORRO_ID(SUNRIZE_INDUSTRIES, 0x02, 0) #define ZORRO_PROD_SUNRIZE_INDUSTRIES_DD512 ZORRO_ID(SUNRIZE_INDUSTRIES, 0x03, 0) #define ZORRO_MANUF_TRICERATOPS 0x0850 #define ZORRO_PROD_TRICERATOPS_MULTI_IO ZORRO_ID(TRICERATOPS, 0x01, 0) #define ZORRO_MANUF_APPLIED_MAGIC 0x0851 #define ZORRO_PROD_APPLIED_MAGIC_DMI_RESOLVER ZORRO_ID(APPLIED_MAGIC, 0x01, 0) #define ZORRO_PROD_APPLIED_MAGIC_DIGITAL_BROADCASTER ZORRO_ID(APPLIED_MAGIC, 0x06, 0) #define ZORRO_MANUF_GFX_BASE 0x085E #define ZORRO_PROD_GFX_BASE_GDA_1_VRAM ZORRO_ID(GFX_BASE, 0x00, 0) #define ZORRO_PROD_GFX_BASE_GDA_1 ZORRO_ID(GFX_BASE, 0x01, 0) #define ZORRO_MANUF_ROCTEC 0x0860 #define ZORRO_PROD_ROCTEC_RH_800C ZORRO_ID(ROCTEC, 0x01, 0) #define ZORRO_PROD_ROCTEC_RH_800C_RAM ZORRO_ID(ROCTEC, 0x01, 0) #define ZORRO_MANUF_KATO 0x0861 #define ZORRO_PROD_KATO_MELODY ZORRO_ID(KATO, 0x80, 0) /* ID clash!! */ #define ZORRO_MANUF_HELFRICH_1 0x0861 #define ZORRO_PROD_HELFRICH_RAINBOW_II ZORRO_ID(HELFRICH_1, 0x20, 0) #define ZORRO_PROD_HELFRICH_RAINBOW_III ZORRO_ID(HELFRICH_1, 0x21, 0) #define ZORRO_MANUF_ATLANTIS 0x0862 #define ZORRO_MANUF_PROTAR 0x0864 #define ZORRO_MANUF_ACS 0x0865 #define ZORRO_MANUF_SOFTWARE_RESULTS_ENTERPRISES 0x0866 #define ZORRO_PROD_SOFTWARE_RESULTS_ENTERPRISES_GOLDEN_GATE_2_BUS_PLUS ZORRO_ID(SOFTWARE_RESULTS_ENTERPRISES, 0x01, 0) #define ZORRO_MANUF_MASOBOSHI 0x086D #define ZORRO_PROD_MASOBOSHI_MASTER_CARD_SC201 ZORRO_ID(MASOBOSHI, 0x03, 0) #define ZORRO_PROD_MASOBOSHI_MASTER_CARD_MC702 ZORRO_ID(MASOBOSHI, 0x04, 0) #define ZORRO_PROD_MASOBOSHI_MVD_819 ZORRO_ID(MASOBOSHI, 0x07, 0) #define ZORRO_MANUF_MAINHATTAN_DATA 0x086F #define ZORRO_PROD_MAINHATTAN_DATA_IDE ZORRO_ID(MAINHATTAN_DATA, 0x01, 0) #define ZORRO_MANUF_VILLAGE_TRONIC 0x0877 #define ZORRO_PROD_VILLAGE_TRONIC_DOMINO_RAM ZORRO_ID(VILLAGE_TRONIC, 0x01, 0) #define ZORRO_PROD_VILLAGE_TRONIC_DOMINO_REG ZORRO_ID(VILLAGE_TRONIC, 0x02, 0) #define ZORRO_PROD_VILLAGE_TRONIC_DOMINO_16M_PROTOTYPE ZORRO_ID(VILLAGE_TRONIC, 0x03, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_II_II_PLUS_RAM ZORRO_ID(VILLAGE_TRONIC, 0x0B, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_II_II_PLUS_REG ZORRO_ID(VILLAGE_TRONIC, 0x0C, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_II_II_PLUS_SEGMENTED_MODE ZORRO_ID(VILLAGE_TRONIC, 0x0D, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_IV_Z2_RAM1 ZORRO_ID(VILLAGE_TRONIC, 0x15, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_IV_Z2_RAM2 ZORRO_ID(VILLAGE_TRONIC, 0x16, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_IV_Z2_REG ZORRO_ID(VILLAGE_TRONIC, 0x17, 0) #define ZORRO_PROD_VILLAGE_TRONIC_PICASSO_IV_Z3 ZORRO_ID(VILLAGE_TRONIC, 0x18, 0) #define ZORRO_PROD_VILLAGE_TRONIC_ARIADNE ZORRO_ID(VILLAGE_TRONIC, 0xC9, 0) #define ZORRO_PROD_VILLAGE_TRONIC_ARIADNE2 ZORRO_ID(VILLAGE_TRONIC, 0xCA, 0) #define ZORRO_MANUF_UTILITIES_UNLIMITED 0x087B #define ZORRO_PROD_UTILITIES_UNLIMITED_EMPLANT_DELUXE ZORRO_ID(UTILITIES_UNLIMITED, 0x15, 0) #define ZORRO_PROD_UTILITIES_UNLIMITED_EMPLANT_DELUXE2 ZORRO_ID(UTILITIES_UNLIMITED, 0x20, 0) #define ZORRO_MANUF_AMITRIX 0x0880 #define ZORRO_PROD_AMITRIX_MULTI_IO ZORRO_ID(AMITRIX, 0x01, 0) #define ZORRO_PROD_AMITRIX_CD_RAM ZORRO_ID(AMITRIX, 0x02, 0) #define ZORRO_MANUF_ARMAX 0x0885 #define ZORRO_PROD_ARMAX_OMNIBUS ZORRO_ID(ARMAX, 0x00, 0) #define ZORRO_MANUF_ZEUS 0x088D #define ZORRO_PROD_ZEUS_SPIDER ZORRO_ID(ZEUS, 0x04, 0) #define ZORRO_MANUF_NEWTEK 0x088F #define ZORRO_PROD_NEWTEK_VIDEOTOASTER ZORRO_ID(NEWTEK, 0x00, 0) #define ZORRO_MANUF_M_TECH_GERMANY 0x0890 #define ZORRO_PROD_MTEC_AT500_2 ZORRO_ID(M_TECH_GERMANY, 0x01, 0) #define ZORRO_PROD_MTEC_68030 ZORRO_ID(M_TECH_GERMANY, 0x03, 0) #define ZORRO_PROD_MTEC_68020I ZORRO_ID(M_TECH_GERMANY, 0x06, 0) #define ZORRO_PROD_MTEC_A1200_T68030_RTC ZORRO_ID(M_TECH_GERMANY, 0x20, 0) #define ZORRO_PROD_MTEC_VIPER_MK_V_E_MATRIX_530 ZORRO_ID(M_TECH_GERMANY, 0x21, 0) #define ZORRO_PROD_MTEC_8_MB_RAM ZORRO_ID(M_TECH_GERMANY, 0x22, 0) #define ZORRO_PROD_MTEC_VIPER_MK_V_E_MATRIX_530_SCSI_IDE ZORRO_ID(M_TECH_GERMANY, 0x24, 0) #define ZORRO_MANUF_GREAT_VALLEY_PRODUCTS_4 0x0891 #define ZORRO_PROD_GVP_EGS_28_24_SPECTRUM_RAM ZORRO_ID(GREAT_VALLEY_PRODUCTS_4, 0x01, 0) #define ZORRO_PROD_GVP_EGS_28_24_SPECTRUM_REG ZORRO_ID(GREAT_VALLEY_PRODUCTS_4, 0x02, 0) #define ZORRO_MANUF_APOLLO_1 0x0892 #define ZORRO_PROD_APOLLO_A1200 ZORRO_ID(APOLLO_1, 0x01, 0) #define ZORRO_MANUF_HELFRICH_2 0x0893 #define ZORRO_PROD_HELFRICH_PICCOLO_RAM ZORRO_ID(HELFRICH_2, 0x05, 0) #define ZORRO_PROD_HELFRICH_PICCOLO_REG ZORRO_ID(HELFRICH_2, 0x06, 0) #define ZORRO_PROD_HELFRICH_PEGGY_PLUS_MPEG ZORRO_ID(HELFRICH_2, 0x07, 0) #define ZORRO_PROD_HELFRICH_VIDEOCRUNCHER ZORRO_ID(HELFRICH_2, 0x08, 0) #define ZORRO_PROD_HELFRICH_SD64_RAM ZORRO_ID(HELFRICH_2, 0x0A, 0) #define ZORRO_PROD_HELFRICH_SD64_REG ZORRO_ID(HELFRICH_2, 0x0B, 0) #define ZORRO_MANUF_MACROSYSTEMS_USA 0x089B #define ZORRO_PROD_MACROSYSTEMS_WARP_ENGINE_40xx ZORRO_ID(MACROSYSTEMS_USA, 0x13, 0) #define ZORRO_MANUF_ELBOX_COMPUTER 0x089E #define ZORRO_PROD_ELBOX_COMPUTER_1200_4 ZORRO_ID(ELBOX_COMPUTER, 0x06, 0) #define ZORRO_MANUF_HARMS_PROFESSIONAL 0x0A00 #define ZORRO_PROD_HARMS_PROFESSIONAL_030_PLUS ZORRO_ID(HARMS_PROFESSIONAL, 0x10, 0) #define ZORRO_PROD_HARMS_PROFESSIONAL_3500 ZORRO_ID(HARMS_PROFESSIONAL, 0xD0, 0) #define ZORRO_MANUF_MICRONIK 0x0A50 #define ZORRO_PROD_MICRONIK_RCA_120 ZORRO_ID(MICRONIK, 0x0A, 0) #define ZORRO_MANUF_MICRONIK2 0x0F0F #define ZORRO_PROD_MICRONIK2_Z3I ZORRO_ID(MICRONIK2, 0x01, 0) #define ZORRO_MANUF_MEGAMICRO 0x1000 #define ZORRO_PROD_MEGAMICRO_SCRAM_500 ZORRO_ID(MEGAMICRO, 0x03, 0) #define ZORRO_PROD_MEGAMICRO_SCRAM_500_RAM ZORRO_ID(MEGAMICRO, 0x04, 0) #define ZORRO_MANUF_IMTRONICS_2 0x1028 #define ZORRO_PROD_IMTRONICS_HURRICANE_2800_3 ZORRO_ID(IMTRONICS_2, 0x39, 0) #define ZORRO_PROD_IMTRONICS_HURRICANE_2800_4 ZORRO_ID(IMTRONICS_2, 0x57, 0) /* unofficial ID */ #define ZORRO_MANUF_INDIVIDUAL_COMPUTERS 0x1212 #define ZORRO_PROD_INDIVIDUAL_COMPUTERS_BUDDHA ZORRO_ID(INDIVIDUAL_COMPUTERS, 0x00, 0) #define ZORRO_PROD_INDIVIDUAL_COMPUTERS_X_SURF ZORRO_ID(INDIVIDUAL_COMPUTERS, 0x17, 0) #define ZORRO_PROD_INDIVIDUAL_COMPUTERS_CATWEASEL ZORRO_ID(INDIVIDUAL_COMPUTERS, 0x2A, 0) #define ZORRO_MANUF_KUPKE_3 0x1248 #define ZORRO_PROD_KUPKE_GOLEM_HD_3000 ZORRO_ID(KUPKE_3, 0x01, 0) #define ZORRO_MANUF_ITH 0x1388 #define ZORRO_PROD_ITH_ISDN_MASTER_II ZORRO_ID(ITH, 0x01, 0) #define ZORRO_MANUF_VMC 0x1389 #define ZORRO_PROD_VMC_ISDN_BLASTER_Z2 ZORRO_ID(VMC, 0x01, 0) #define ZORRO_PROD_VMC_HYPERCOM_4 ZORRO_ID(VMC, 0x02, 0) #define ZORRO_MANUF_INFORMATION 0x157C #define ZORRO_PROD_INFORMATION_ISDN_ENGINE_I ZORRO_ID(INFORMATION, 0x64, 0) #define ZORRO_MANUF_VORTEX 0x2017 #define ZORRO_PROD_VORTEX_GOLDEN_GATE_80386SX ZORRO_ID(VORTEX, 0x07, 0) #define ZORRO_PROD_VORTEX_GOLDEN_GATE_RAM ZORRO_ID(VORTEX, 0x08, 0) #define ZORRO_PROD_VORTEX_GOLDEN_GATE_80486 ZORRO_ID(VORTEX, 0x09, 0) #define ZORRO_MANUF_EXPANSION_SYSTEMS 0x2062 #define ZORRO_PROD_EXPANSION_SYSTEMS_DATAFLYER_4000SX ZORRO_ID(EXPANSION_SYSTEMS, 0x01, 0) #define ZORRO_PROD_EXPANSION_SYSTEMS_DATAFLYER_4000SX_RAM ZORRO_ID(EXPANSION_SYSTEMS, 0x02, 0) #define ZORRO_MANUF_READYSOFT 0x2100 #define ZORRO_PROD_READYSOFT_AMAX_II_IV ZORRO_ID(READYSOFT, 0x01, 0) #define ZORRO_MANUF_PHASE5 0x2140 #define ZORRO_PROD_PHASE5_BLIZZARD_RAM ZORRO_ID(PHASE5, 0x01, 0) #define ZORRO_PROD_PHASE5_BLIZZARD ZORRO_ID(PHASE5, 0x02, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_1220_IV ZORRO_ID(PHASE5, 0x06, 0) #define ZORRO_PROD_PHASE5_FASTLANE_Z3_RAM ZORRO_ID(PHASE5, 0x0A, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_1230_II_FASTLANE_Z3_CYBERSCSI_CYBERSTORM060 ZORRO_ID(PHASE5, 0x0B, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_1220_CYBERSTORM ZORRO_ID(PHASE5, 0x0C, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_1230 ZORRO_ID(PHASE5, 0x0D, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_1230_IV_1260 ZORRO_ID(PHASE5, 0x11, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_2060 ZORRO_ID(PHASE5, 0x18, 0) #define ZORRO_PROD_PHASE5_CYBERSTORM_MK_II ZORRO_ID(PHASE5, 0x19, 0) #define ZORRO_PROD_PHASE5_CYBERVISION64 ZORRO_ID(PHASE5, 0x22, 0) #define ZORRO_PROD_PHASE5_CYBERVISION64_3D_PROTOTYPE ZORRO_ID(PHASE5, 0x32, 0) #define ZORRO_PROD_PHASE5_CYBERVISION64_3D ZORRO_ID(PHASE5, 0x43, 0) #define ZORRO_PROD_PHASE5_CYBERSTORM_MK_III ZORRO_ID(PHASE5, 0x64, 0) #define ZORRO_PROD_PHASE5_BLIZZARD_603E_PLUS ZORRO_ID(PHASE5, 0x6e, 0) #define ZORRO_MANUF_DPS 0x2169 #define ZORRO_PROD_DPS_PERSONAL_ANIMATION_RECORDER ZORRO_ID(DPS, 0x01, 0) #define ZORRO_MANUF_APOLLO_2 0x2200 #define ZORRO_PROD_APOLLO_A620_68020_1 ZORRO_ID(APOLLO_2, 0x00, 0) #define ZORRO_PROD_APOLLO_A620_68020_2 ZORRO_ID(APOLLO_2, 0x01, 0) #define ZORRO_MANUF_APOLLO_3 0x2222 #define ZORRO_PROD_APOLLO_AT_APOLLO ZORRO_ID(APOLLO_3, 0x22, 0) #define ZORRO_PROD_APOLLO_1230_1240_1260_2030_4040_4060 ZORRO_ID(APOLLO_3, 0x23, 0) #define ZORRO_MANUF_PETSOFF_LP 0x38A5 #define ZORRO_PROD_PETSOFF_LP_DELFINA ZORRO_ID(PETSOFF_LP, 0x00, 0) #define ZORRO_PROD_PETSOFF_LP_DELFINA_LITE ZORRO_ID(PETSOFF_LP, 0x01, 0) #define ZORRO_MANUF_UWE_GERLACH 0x3FF7 #define ZORRO_PROD_UWE_GERLACH_RAM_ROM ZORRO_ID(UWE_GERLACH, 0xd4, 0) #define ZORRO_MANUF_ACT 0x4231 #define ZORRO_PROD_ACT_PRELUDE ZORRO_ID(ACT, 0x01, 0) #define ZORRO_MANUF_MACROSYSTEMS_GERMANY 0x4754 #define ZORRO_PROD_MACROSYSTEMS_MAESTRO ZORRO_ID(MACROSYSTEMS_GERMANY, 0x03, 0) #define ZORRO_PROD_MACROSYSTEMS_VLAB ZORRO_ID(MACROSYSTEMS_GERMANY, 0x04, 0) #define ZORRO_PROD_MACROSYSTEMS_MAESTRO_PRO ZORRO_ID(MACROSYSTEMS_GERMANY, 0x05, 0) #define ZORRO_PROD_MACROSYSTEMS_RETINA ZORRO_ID(MACROSYSTEMS_GERMANY, 0x06, 0) #define ZORRO_PROD_MACROSYSTEMS_MULTI_EVOLUTION ZORRO_ID(MACROSYSTEMS_GERMANY, 0x08, 0) #define ZORRO_PROD_MACROSYSTEMS_TOCCATA ZORRO_ID(MACROSYSTEMS_GERMANY, 0x0C, 0) #define ZORRO_PROD_MACROSYSTEMS_RETINA_Z3 ZORRO_ID(MACROSYSTEMS_GERMANY, 0x10, 0) #define ZORRO_PROD_MACROSYSTEMS_VLAB_MOTION ZORRO_ID(MACROSYSTEMS_GERMANY, 0x12, 0) #define ZORRO_PROD_MACROSYSTEMS_ALTAIS ZORRO_ID(MACROSYSTEMS_GERMANY, 0x13, 0) #define ZORRO_PROD_MACROSYSTEMS_FALCON_040 ZORRO_ID(MACROSYSTEMS_GERMANY, 0xFD, 0) #define ZORRO_MANUF_COMBITEC 0x6766 #define ZORRO_MANUF_SKI_PERIPHERALS 0x8000 #define ZORRO_PROD_SKI_PERIPHERALS_MAST_FIREBALL ZORRO_ID(SKI_PERIPHERALS, 0x08, 0) #define ZORRO_PROD_SKI_PERIPHERALS_SCSI_DUAL_SERIAL ZORRO_ID(SKI_PERIPHERALS, 0x80, 0) #define ZORRO_MANUF_REIS_WARE_2 0xA9AD #define ZORRO_PROD_REIS_WARE_SCAN_KING ZORRO_ID(REIS_WARE_2, 0x11, 0) #define ZORRO_MANUF_CAMERON 0xAA01 #define ZORRO_PROD_CAMERON_PERSONAL_A4 ZORRO_ID(CAMERON, 0x10, 0) #define ZORRO_MANUF_REIS_WARE 0xAA11 #define ZORRO_PROD_REIS_WARE_HANDYSCANNER ZORRO_ID(REIS_WARE, 0x11, 0) #define ZORRO_MANUF_PHOENIX_2 0xB5A8 #define ZORRO_PROD_PHOENIX_ST506_2 ZORRO_ID(PHOENIX_2, 0x21, 0) #define ZORRO_PROD_PHOENIX_SCSI_2 ZORRO_ID(PHOENIX_2, 0x22, 0) #define ZORRO_PROD_PHOENIX_RAM_2 ZORRO_ID(PHOENIX_2, 0xBE, 0) #define ZORRO_MANUF_COMBITEC_2 0xC008 #define ZORRO_PROD_COMBITEC_HD ZORRO_ID(COMBITEC_2, 0x2A, 0) #define ZORRO_PROD_COMBITEC_SRAM ZORRO_ID(COMBITEC_2, 0x2B, 0) /* * Test and illegal Manufacturer IDs. */ #define ZORRO_MANUF_HACKER 0x07DB #define ZORRO_PROD_GENERAL_PROTOTYPE ZORRO_ID(HACKER, 0x00, 0) #define ZORRO_PROD_HACKER_SCSI ZORRO_ID(HACKER, 0x01, 0) #define ZORRO_PROD_RESOURCE_MANAGEMENT_FORCE_QUICKNET_QN2000 ZORRO_ID(HACKER, 0x02, 0) #define ZORRO_PROD_VECTOR_CONNECTION_2 ZORRO_ID(HACKER, 0xE0, 0) #define ZORRO_PROD_VECTOR_CONNECTION_3 ZORRO_ID(HACKER, 0xE1, 0) #define ZORRO_PROD_VECTOR_CONNECTION_4 ZORRO_ID(HACKER, 0xE2, 0) #define ZORRO_PROD_VECTOR_CONNECTION_5 ZORRO_ID(HACKER, 0xE3, 0) linux/uinput.h000064400000022055151027430560007407 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * User level driver support for input subsystem * * Heavily based on evdev.c by Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Aristeu Sergio Rozanski Filho * * Changes/Revisions: * 0.5 08/13/2015 (David Herrmann & * Benjamin Tissoires ) * - add UI_DEV_SETUP ioctl * - add UI_ABS_SETUP ioctl * - add UI_GET_VERSION ioctl * 0.4 01/09/2014 (Benjamin Tissoires ) * - add UI_GET_SYSNAME ioctl * 0.3 24/05/2006 (Anssi Hannula ) * - update ff support for the changes in kernel interface * - add UINPUT_VERSION * 0.2 16/10/2004 (Micah Dowty ) * - added force feedback support * - added UI_SET_PHYS * 0.1 20/06/2002 * - first public version */ #ifndef __UINPUT_H_ #define __UINPUT_H_ #include #include #define UINPUT_VERSION 5 #define UINPUT_MAX_NAME_SIZE 80 struct uinput_ff_upload { __u32 request_id; __s32 retval; struct ff_effect effect; struct ff_effect old; }; struct uinput_ff_erase { __u32 request_id; __s32 retval; __u32 effect_id; }; /* ioctl */ #define UINPUT_IOCTL_BASE 'U' #define UI_DEV_CREATE _IO(UINPUT_IOCTL_BASE, 1) #define UI_DEV_DESTROY _IO(UINPUT_IOCTL_BASE, 2) struct uinput_setup { struct input_id id; char name[UINPUT_MAX_NAME_SIZE]; __u32 ff_effects_max; }; /** * UI_DEV_SETUP - Set device parameters for setup * * This ioctl sets parameters for the input device to be created. It * supersedes the old "struct uinput_user_dev" method, which wrote this data * via write(). To actually set the absolute axes UI_ABS_SETUP should be * used. * * The ioctl takes a "struct uinput_setup" object as argument. The fields of * this object are as follows: * id: See the description of "struct input_id". This field is * copied unchanged into the new device. * name: This is used unchanged as name for the new device. * ff_effects_max: This limits the maximum numbers of force-feedback effects. * See below for a description of FF with uinput. * * This ioctl can be called multiple times and will overwrite previous values. * If this ioctl fails with -EINVAL, it is recommended to use the old * "uinput_user_dev" method via write() as a fallback, in case you run on an * old kernel that does not support this ioctl. * * This ioctl may fail with -EINVAL if it is not supported or if you passed * incorrect values, -ENOMEM if the kernel runs out of memory or -EFAULT if the * passed uinput_setup object cannot be read/written. * If this call fails, partial data may have already been applied to the * internal device. */ #define UI_DEV_SETUP _IOW(UINPUT_IOCTL_BASE, 3, struct uinput_setup) struct uinput_abs_setup { __u16 code; /* axis code */ /* __u16 filler; */ struct input_absinfo absinfo; }; /** * UI_ABS_SETUP - Set absolute axis information for the device to setup * * This ioctl sets one absolute axis information for the input device to be * created. It supersedes the old "struct uinput_user_dev" method, which wrote * part of this data and the content of UI_DEV_SETUP via write(). * * The ioctl takes a "struct uinput_abs_setup" object as argument. The fields * of this object are as follows: * code: The corresponding input code associated with this axis * (ABS_X, ABS_Y, etc...) * absinfo: See "struct input_absinfo" for a description of this field. * This field is copied unchanged into the kernel for the * specified axis. If the axis is not enabled via * UI_SET_ABSBIT, this ioctl will enable it. * * This ioctl can be called multiple times and will overwrite previous values. * If this ioctl fails with -EINVAL, it is recommended to use the old * "uinput_user_dev" method via write() as a fallback, in case you run on an * old kernel that does not support this ioctl. * * This ioctl may fail with -EINVAL if it is not supported or if you passed * incorrect values, -ENOMEM if the kernel runs out of memory or -EFAULT if the * passed uinput_setup object cannot be read/written. * If this call fails, partial data may have already been applied to the * internal device. */ #define UI_ABS_SETUP _IOW(UINPUT_IOCTL_BASE, 4, struct uinput_abs_setup) #define UI_SET_EVBIT _IOW(UINPUT_IOCTL_BASE, 100, int) #define UI_SET_KEYBIT _IOW(UINPUT_IOCTL_BASE, 101, int) #define UI_SET_RELBIT _IOW(UINPUT_IOCTL_BASE, 102, int) #define UI_SET_ABSBIT _IOW(UINPUT_IOCTL_BASE, 103, int) #define UI_SET_MSCBIT _IOW(UINPUT_IOCTL_BASE, 104, int) #define UI_SET_LEDBIT _IOW(UINPUT_IOCTL_BASE, 105, int) #define UI_SET_SNDBIT _IOW(UINPUT_IOCTL_BASE, 106, int) #define UI_SET_FFBIT _IOW(UINPUT_IOCTL_BASE, 107, int) #define UI_SET_PHYS _IOW(UINPUT_IOCTL_BASE, 108, char*) #define UI_SET_SWBIT _IOW(UINPUT_IOCTL_BASE, 109, int) #define UI_SET_PROPBIT _IOW(UINPUT_IOCTL_BASE, 110, int) #define UI_BEGIN_FF_UPLOAD _IOWR(UINPUT_IOCTL_BASE, 200, struct uinput_ff_upload) #define UI_END_FF_UPLOAD _IOW(UINPUT_IOCTL_BASE, 201, struct uinput_ff_upload) #define UI_BEGIN_FF_ERASE _IOWR(UINPUT_IOCTL_BASE, 202, struct uinput_ff_erase) #define UI_END_FF_ERASE _IOW(UINPUT_IOCTL_BASE, 203, struct uinput_ff_erase) /** * UI_GET_SYSNAME - get the sysfs name of the created uinput device * * @return the sysfs name of the created virtual input device. * The complete sysfs path is then /sys/devices/virtual/input/--NAME-- * Usually, it is in the form "inputN" */ #define UI_GET_SYSNAME(len) _IOC(_IOC_READ, UINPUT_IOCTL_BASE, 44, len) /** * UI_GET_VERSION - Return version of uinput protocol * * This writes uinput protocol version implemented by the kernel into * the integer pointed to by the ioctl argument. The protocol version * is hard-coded in the kernel and is independent of the uinput device. */ #define UI_GET_VERSION _IOR(UINPUT_IOCTL_BASE, 45, unsigned int) /* * To write a force-feedback-capable driver, the upload_effect * and erase_effect callbacks in input_dev must be implemented. * The uinput driver will generate a fake input event when one of * these callbacks are invoked. The userspace code then uses * ioctls to retrieve additional parameters and send the return code. * The callback blocks until this return code is sent. * * The described callback mechanism is only used if ff_effects_max * is set. * * To implement upload_effect(): * 1. Wait for an event with type == EV_UINPUT and code == UI_FF_UPLOAD. * A request ID will be given in 'value'. * 2. Allocate a uinput_ff_upload struct, fill in request_id with * the 'value' from the EV_UINPUT event. * 3. Issue a UI_BEGIN_FF_UPLOAD ioctl, giving it the * uinput_ff_upload struct. It will be filled in with the * ff_effects passed to upload_effect(). * 4. Perform the effect upload, and place a return code back into the uinput_ff_upload struct. * 5. Issue a UI_END_FF_UPLOAD ioctl, also giving it the * uinput_ff_upload_effect struct. This will complete execution * of our upload_effect() handler. * * To implement erase_effect(): * 1. Wait for an event with type == EV_UINPUT and code == UI_FF_ERASE. * A request ID will be given in 'value'. * 2. Allocate a uinput_ff_erase struct, fill in request_id with * the 'value' from the EV_UINPUT event. * 3. Issue a UI_BEGIN_FF_ERASE ioctl, giving it the * uinput_ff_erase struct. It will be filled in with the * effect ID passed to erase_effect(). * 4. Perform the effect erasure, and place a return code back * into the uinput_ff_erase struct. * 5. Issue a UI_END_FF_ERASE ioctl, also giving it the * uinput_ff_erase_effect struct. This will complete execution * of our erase_effect() handler. */ /* * This is the new event type, used only by uinput. * 'code' is UI_FF_UPLOAD or UI_FF_ERASE, and 'value' * is the unique request ID. This number was picked * arbitrarily, above EV_MAX (since the input system * never sees it) but in the range of a 16-bit int. */ #define EV_UINPUT 0x0101 #define UI_FF_UPLOAD 1 #define UI_FF_ERASE 2 struct uinput_user_dev { char name[UINPUT_MAX_NAME_SIZE]; struct input_id id; __u32 ff_effects_max; __s32 absmax[ABS_CNT]; __s32 absmin[ABS_CNT]; __s32 absfuzz[ABS_CNT]; __s32 absflat[ABS_CNT]; }; #endif /* __UINPUT_H_ */ linux/qemu_fw_cfg.h000064400000004645151027430560010352 0ustar00/* SPDX-License-Identifier: BSD-3-Clause */ #ifndef _LINUX_FW_CFG_H #define _LINUX_FW_CFG_H #include #define FW_CFG_ACPI_DEVICE_ID "QEMU0002" /* selector key values for "well-known" fw_cfg entries */ #define FW_CFG_SIGNATURE 0x00 #define FW_CFG_ID 0x01 #define FW_CFG_UUID 0x02 #define FW_CFG_RAM_SIZE 0x03 #define FW_CFG_NOGRAPHIC 0x04 #define FW_CFG_NB_CPUS 0x05 #define FW_CFG_MACHINE_ID 0x06 #define FW_CFG_KERNEL_ADDR 0x07 #define FW_CFG_KERNEL_SIZE 0x08 #define FW_CFG_KERNEL_CMDLINE 0x09 #define FW_CFG_INITRD_ADDR 0x0a #define FW_CFG_INITRD_SIZE 0x0b #define FW_CFG_BOOT_DEVICE 0x0c #define FW_CFG_NUMA 0x0d #define FW_CFG_BOOT_MENU 0x0e #define FW_CFG_MAX_CPUS 0x0f #define FW_CFG_KERNEL_ENTRY 0x10 #define FW_CFG_KERNEL_DATA 0x11 #define FW_CFG_INITRD_DATA 0x12 #define FW_CFG_CMDLINE_ADDR 0x13 #define FW_CFG_CMDLINE_SIZE 0x14 #define FW_CFG_CMDLINE_DATA 0x15 #define FW_CFG_SETUP_ADDR 0x16 #define FW_CFG_SETUP_SIZE 0x17 #define FW_CFG_SETUP_DATA 0x18 #define FW_CFG_FILE_DIR 0x19 #define FW_CFG_FILE_FIRST 0x20 #define FW_CFG_FILE_SLOTS_MIN 0x10 #define FW_CFG_WRITE_CHANNEL 0x4000 #define FW_CFG_ARCH_LOCAL 0x8000 #define FW_CFG_ENTRY_MASK (~(FW_CFG_WRITE_CHANNEL | FW_CFG_ARCH_LOCAL)) #define FW_CFG_INVALID 0xffff /* width in bytes of fw_cfg control register */ #define FW_CFG_CTL_SIZE 0x02 /* fw_cfg "file name" is up to 56 characters (including terminating nul) */ #define FW_CFG_MAX_FILE_PATH 56 /* size in bytes of fw_cfg signature */ #define FW_CFG_SIG_SIZE 4 /* FW_CFG_ID bits */ #define FW_CFG_VERSION 0x01 #define FW_CFG_VERSION_DMA 0x02 /* fw_cfg file directory entry type */ struct fw_cfg_file { __be32 size; __be16 select; __u16 reserved; char name[FW_CFG_MAX_FILE_PATH]; }; /* FW_CFG_DMA_CONTROL bits */ #define FW_CFG_DMA_CTL_ERROR 0x01 #define FW_CFG_DMA_CTL_READ 0x02 #define FW_CFG_DMA_CTL_SKIP 0x04 #define FW_CFG_DMA_CTL_SELECT 0x08 #define FW_CFG_DMA_CTL_WRITE 0x10 #define FW_CFG_DMA_SIGNATURE 0x51454d5520434647ULL /* "QEMU CFG" */ /* Control as first field allows for different structures selected by this * field, which might be useful in the future */ struct fw_cfg_dma_access { __be32 control; __be32 length; __be64 address; }; #define FW_CFG_VMCOREINFO_FILENAME "etc/vmcoreinfo" #define FW_CFG_VMCOREINFO_FORMAT_NONE 0x0 #define FW_CFG_VMCOREINFO_FORMAT_ELF 0x1 struct fw_cfg_vmcoreinfo { __le16 host_format; __le16 guest_format; __le32 size; __le64 paddr; }; #endif linux/mempolicy.h000064400000004267151027430560010066 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * NUMA memory policies for Linux. * Copyright 2003,2004 Andi Kleen SuSE Labs */ #ifndef _LINUX_MEMPOLICY_H #define _LINUX_MEMPOLICY_H #include /* * Both the MPOL_* mempolicy mode and the MPOL_F_* optional mode flags are * passed by the user to either set_mempolicy() or mbind() in an 'int' actual. * The MPOL_MODE_FLAGS macro determines the legal set of optional mode flags. */ /* Policies */ enum { MPOL_DEFAULT, MPOL_PREFERRED, MPOL_BIND, MPOL_INTERLEAVE, MPOL_LOCAL, MPOL_PREFERRED_MANY, MPOL_MAX, /* always last member of enum */ }; /* Flags for set_mempolicy */ #define MPOL_F_STATIC_NODES (1 << 15) #define MPOL_F_RELATIVE_NODES (1 << 14) #define MPOL_F_NUMA_BALANCING (1 << 13) /* Optimize with NUMA balancing if possible */ /* * MPOL_MODE_FLAGS is the union of all possible optional mode flags passed to * either set_mempolicy() or mbind(). */ #define MPOL_MODE_FLAGS \ (MPOL_F_STATIC_NODES | MPOL_F_RELATIVE_NODES | MPOL_F_NUMA_BALANCING) /* Flags for get_mempolicy */ #define MPOL_F_NODE (1<<0) /* return next IL mode instead of node mask */ #define MPOL_F_ADDR (1<<1) /* look up vma using address */ #define MPOL_F_MEMS_ALLOWED (1<<2) /* return allowed memories */ /* Flags for mbind */ #define MPOL_MF_STRICT (1<<0) /* Verify existing pages in the mapping */ #define MPOL_MF_MOVE (1<<1) /* Move pages owned by this process to conform to policy */ #define MPOL_MF_MOVE_ALL (1<<2) /* Move every page to conform to policy */ #define MPOL_MF_LAZY (1<<3) /* Modifies '_MOVE: lazy migrate on fault */ #define MPOL_MF_INTERNAL (1<<4) /* Internal flags start here */ #define MPOL_MF_VALID (MPOL_MF_STRICT | \ MPOL_MF_MOVE | \ MPOL_MF_MOVE_ALL) /* * Internal flags that share the struct mempolicy flags word with * "mode flags". These flags are allocated from bit 0 up, as they * are never OR'ed into the mode in mempolicy API arguments. */ #define MPOL_F_SHARED (1 << 0) /* identify shared policies */ #define MPOL_F_MOF (1 << 3) /* this policy wants migrate on fault */ #define MPOL_F_MORON (1 << 4) /* Migrate On protnone Reference On Node */ #endif /* _LINUX_MEMPOLICY_H */ linux/lightnvm.h000064400000011662151027430560007715 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2015 CNEX Labs. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, * USA. */ #ifndef _LINUX_LIGHTNVM_H #define _LINUX_LIGHTNVM_H #include #include #define DISK_NAME_LEN 32 #include #include #define NVM_TTYPE_NAME_MAX 48 #define NVM_TTYPE_MAX 63 #define NVM_MMTYPE_LEN 8 #define NVM_CTRL_FILE "/dev/lightnvm/control" struct nvm_ioctl_info_tgt { __u32 version[3]; __u32 reserved; char tgtname[NVM_TTYPE_NAME_MAX]; }; struct nvm_ioctl_info { __u32 version[3]; /* in/out - major, minor, patch */ __u16 tgtsize; /* number of targets */ __u16 reserved16; /* pad to 4K page */ __u32 reserved[12]; struct nvm_ioctl_info_tgt tgts[NVM_TTYPE_MAX]; }; enum { NVM_DEVICE_ACTIVE = 1 << 0, }; struct nvm_ioctl_device_info { char devname[DISK_NAME_LEN]; char bmname[NVM_TTYPE_NAME_MAX]; __u32 bmversion[3]; __u32 flags; __u32 reserved[8]; }; struct nvm_ioctl_get_devices { __u32 nr_devices; __u32 reserved[31]; struct nvm_ioctl_device_info info[31]; }; struct nvm_ioctl_create_simple { __u32 lun_begin; __u32 lun_end; }; struct nvm_ioctl_create_extended { __u16 lun_begin; __u16 lun_end; __u16 op; __u16 rsv; }; enum { NVM_CONFIG_TYPE_SIMPLE = 0, NVM_CONFIG_TYPE_EXTENDED = 1, }; struct nvm_ioctl_create_conf { __u32 type; union { struct nvm_ioctl_create_simple s; struct nvm_ioctl_create_extended e; }; }; enum { NVM_TARGET_FACTORY = 1 << 0, /* Init target in factory mode */ }; struct nvm_ioctl_create { char dev[DISK_NAME_LEN]; /* open-channel SSD device */ char tgttype[NVM_TTYPE_NAME_MAX]; /* target type name */ char tgtname[DISK_NAME_LEN]; /* dev to expose target as */ __u32 flags; struct nvm_ioctl_create_conf conf; }; struct nvm_ioctl_remove { char tgtname[DISK_NAME_LEN]; __u32 flags; }; struct nvm_ioctl_dev_init { char dev[DISK_NAME_LEN]; /* open-channel SSD device */ char mmtype[NVM_MMTYPE_LEN]; /* register to media manager */ __u32 flags; }; enum { NVM_FACTORY_ERASE_ONLY_USER = 1 << 0, /* erase only blocks used as * host blks or grown blks */ NVM_FACTORY_RESET_HOST_BLKS = 1 << 1, /* remove host blk marks */ NVM_FACTORY_RESET_GRWN_BBLKS = 1 << 2, /* remove grown blk marks */ NVM_FACTORY_NR_BITS = 1 << 3, /* stops here */ }; struct nvm_ioctl_dev_factory { char dev[DISK_NAME_LEN]; __u32 flags; }; struct nvm_user_vio { __u8 opcode; __u8 flags; __u16 control; __u16 nppas; __u16 rsvd; __u64 metadata; __u64 addr; __u64 ppa_list; __u32 metadata_len; __u32 data_len; __u64 status; __u32 result; __u32 rsvd3[3]; }; struct nvm_passthru_vio { __u8 opcode; __u8 flags; __u8 rsvd[2]; __u32 nsid; __u32 cdw2; __u32 cdw3; __u64 metadata; __u64 addr; __u32 metadata_len; __u32 data_len; __u64 ppa_list; __u16 nppas; __u16 control; __u32 cdw13; __u32 cdw14; __u32 cdw15; __u64 status; __u32 result; __u32 timeout_ms; }; /* The ioctl type, 'L', 0x20 - 0x2F documented in ioctl-number.txt */ enum { /* top level cmds */ NVM_INFO_CMD = 0x20, NVM_GET_DEVICES_CMD, /* device level cmds */ NVM_DEV_CREATE_CMD, NVM_DEV_REMOVE_CMD, /* Init a device to support LightNVM media managers */ NVM_DEV_INIT_CMD, /* Factory reset device */ NVM_DEV_FACTORY_CMD, /* Vector user I/O */ NVM_DEV_VIO_ADMIN_CMD = 0x41, NVM_DEV_VIO_CMD = 0x42, NVM_DEV_VIO_USER_CMD = 0x43, }; #define NVM_IOCTL 'L' /* 0x4c */ #define NVM_INFO _IOWR(NVM_IOCTL, NVM_INFO_CMD, \ struct nvm_ioctl_info) #define NVM_GET_DEVICES _IOR(NVM_IOCTL, NVM_GET_DEVICES_CMD, \ struct nvm_ioctl_get_devices) #define NVM_DEV_CREATE _IOW(NVM_IOCTL, NVM_DEV_CREATE_CMD, \ struct nvm_ioctl_create) #define NVM_DEV_REMOVE _IOW(NVM_IOCTL, NVM_DEV_REMOVE_CMD, \ struct nvm_ioctl_remove) #define NVM_DEV_INIT _IOW(NVM_IOCTL, NVM_DEV_INIT_CMD, \ struct nvm_ioctl_dev_init) #define NVM_DEV_FACTORY _IOW(NVM_IOCTL, NVM_DEV_FACTORY_CMD, \ struct nvm_ioctl_dev_factory) #define NVME_NVM_IOCTL_IO_VIO _IOWR(NVM_IOCTL, NVM_DEV_VIO_USER_CMD, \ struct nvm_passthru_vio) #define NVME_NVM_IOCTL_ADMIN_VIO _IOWR(NVM_IOCTL, NVM_DEV_VIO_ADMIN_CMD,\ struct nvm_passthru_vio) #define NVME_NVM_IOCTL_SUBMIT_VIO _IOWR(NVM_IOCTL, NVM_DEV_VIO_CMD,\ struct nvm_user_vio) #define NVM_VERSION_MAJOR 1 #define NVM_VERSION_MINOR 0 #define NVM_VERSION_PATCHLEVEL 0 #endif linux/watchdog.h000064400000004437151027430560007667 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Generic watchdog defines. Derived from.. * * Berkshire PC Watchdog Defines * by Ken Hollis * */ #ifndef _LINUX_WATCHDOG_H #define _LINUX_WATCHDOG_H #include #include #define WATCHDOG_IOCTL_BASE 'W' struct watchdog_info { __u32 options; /* Options the card/driver supports */ __u32 firmware_version; /* Firmware version of the card */ __u8 identity[32]; /* Identity of the board */ }; #define WDIOC_GETSUPPORT _IOR(WATCHDOG_IOCTL_BASE, 0, struct watchdog_info) #define WDIOC_GETSTATUS _IOR(WATCHDOG_IOCTL_BASE, 1, int) #define WDIOC_GETBOOTSTATUS _IOR(WATCHDOG_IOCTL_BASE, 2, int) #define WDIOC_GETTEMP _IOR(WATCHDOG_IOCTL_BASE, 3, int) #define WDIOC_SETOPTIONS _IOR(WATCHDOG_IOCTL_BASE, 4, int) #define WDIOC_KEEPALIVE _IOR(WATCHDOG_IOCTL_BASE, 5, int) #define WDIOC_SETTIMEOUT _IOWR(WATCHDOG_IOCTL_BASE, 6, int) #define WDIOC_GETTIMEOUT _IOR(WATCHDOG_IOCTL_BASE, 7, int) #define WDIOC_SETPRETIMEOUT _IOWR(WATCHDOG_IOCTL_BASE, 8, int) #define WDIOC_GETPRETIMEOUT _IOR(WATCHDOG_IOCTL_BASE, 9, int) #define WDIOC_GETTIMELEFT _IOR(WATCHDOG_IOCTL_BASE, 10, int) #define WDIOF_UNKNOWN -1 /* Unknown flag error */ #define WDIOS_UNKNOWN -1 /* Unknown status error */ #define WDIOF_OVERHEAT 0x0001 /* Reset due to CPU overheat */ #define WDIOF_FANFAULT 0x0002 /* Fan failed */ #define WDIOF_EXTERN1 0x0004 /* External relay 1 */ #define WDIOF_EXTERN2 0x0008 /* External relay 2 */ #define WDIOF_POWERUNDER 0x0010 /* Power bad/power fault */ #define WDIOF_CARDRESET 0x0020 /* Card previously reset the CPU */ #define WDIOF_POWEROVER 0x0040 /* Power over voltage */ #define WDIOF_SETTIMEOUT 0x0080 /* Set timeout (in seconds) */ #define WDIOF_MAGICCLOSE 0x0100 /* Supports magic close char */ #define WDIOF_PRETIMEOUT 0x0200 /* Pretimeout (in seconds), get/set */ #define WDIOF_ALARMONLY 0x0400 /* Watchdog triggers a management or other external alarm not a reboot */ #define WDIOF_KEEPALIVEPING 0x8000 /* Keep alive ping reply */ #define WDIOS_DISABLECARD 0x0001 /* Turn off the watchdog timer */ #define WDIOS_ENABLECARD 0x0002 /* Turn on the watchdog timer */ #define WDIOS_TEMPPANIC 0x0004 /* Kernel panic on temperature trip */ #endif /* _LINUX_WATCHDOG_H */ linux/quota.h000064400000014223151027430560007212 0ustar00/* * Copyright (c) 1982, 1986 Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Robert Elz at The University of Melbourne. * * 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. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _LINUX_QUOTA_ #define _LINUX_QUOTA_ #include #define __DQUOT_VERSION__ "dquot_6.6.0" #define MAXQUOTAS 3 #define USRQUOTA 0 /* element used for user quotas */ #define GRPQUOTA 1 /* element used for group quotas */ #define PRJQUOTA 2 /* element used for project quotas */ /* * Definitions for the default names of the quotas files. */ #define INITQFNAMES { \ "user", /* USRQUOTA */ \ "group", /* GRPQUOTA */ \ "project", /* PRJQUOTA */ \ "undefined", \ }; /* * Command definitions for the 'quotactl' system call. * The commands are broken into a main command defined below * and a subcommand that is used to convey the type of * quota that is being manipulated (see above). */ #define SUBCMDMASK 0x00ff #define SUBCMDSHIFT 8 #define QCMD(cmd, type) (((cmd) << SUBCMDSHIFT) | ((type) & SUBCMDMASK)) #define Q_SYNC 0x800001 /* sync disk copy of a filesystems quotas */ #define Q_QUOTAON 0x800002 /* turn quotas on */ #define Q_QUOTAOFF 0x800003 /* turn quotas off */ #define Q_GETFMT 0x800004 /* get quota format used on given filesystem */ #define Q_GETINFO 0x800005 /* get information about quota files */ #define Q_SETINFO 0x800006 /* set information about quota files */ #define Q_GETQUOTA 0x800007 /* get user quota structure */ #define Q_SETQUOTA 0x800008 /* set user quota structure */ #define Q_GETNEXTQUOTA 0x800009 /* get disk limits and usage >= ID */ /* Quota format type IDs */ #define QFMT_VFS_OLD 1 #define QFMT_VFS_V0 2 #define QFMT_OCFS2 3 #define QFMT_VFS_V1 4 /* Size of block in which space limits are passed through the quota * interface */ #define QIF_DQBLKSIZE_BITS 10 #define QIF_DQBLKSIZE (1 << QIF_DQBLKSIZE_BITS) /* * Quota structure used for communication with userspace via quotactl * Following flags are used to specify which fields are valid */ enum { QIF_BLIMITS_B = 0, QIF_SPACE_B, QIF_ILIMITS_B, QIF_INODES_B, QIF_BTIME_B, QIF_ITIME_B, }; #define QIF_BLIMITS (1 << QIF_BLIMITS_B) #define QIF_SPACE (1 << QIF_SPACE_B) #define QIF_ILIMITS (1 << QIF_ILIMITS_B) #define QIF_INODES (1 << QIF_INODES_B) #define QIF_BTIME (1 << QIF_BTIME_B) #define QIF_ITIME (1 << QIF_ITIME_B) #define QIF_LIMITS (QIF_BLIMITS | QIF_ILIMITS) #define QIF_USAGE (QIF_SPACE | QIF_INODES) #define QIF_TIMES (QIF_BTIME | QIF_ITIME) #define QIF_ALL (QIF_LIMITS | QIF_USAGE | QIF_TIMES) struct if_dqblk { __u64 dqb_bhardlimit; __u64 dqb_bsoftlimit; __u64 dqb_curspace; __u64 dqb_ihardlimit; __u64 dqb_isoftlimit; __u64 dqb_curinodes; __u64 dqb_btime; __u64 dqb_itime; __u32 dqb_valid; }; struct if_nextdqblk { __u64 dqb_bhardlimit; __u64 dqb_bsoftlimit; __u64 dqb_curspace; __u64 dqb_ihardlimit; __u64 dqb_isoftlimit; __u64 dqb_curinodes; __u64 dqb_btime; __u64 dqb_itime; __u32 dqb_valid; __u32 dqb_id; }; /* * Structure used for setting quota information about file via quotactl * Following flags are used to specify which fields are valid */ #define IIF_BGRACE 1 #define IIF_IGRACE 2 #define IIF_FLAGS 4 #define IIF_ALL (IIF_BGRACE | IIF_IGRACE | IIF_FLAGS) enum { DQF_ROOT_SQUASH_B = 0, DQF_SYS_FILE_B = 16, /* Kernel internal flags invisible to userspace */ DQF_PRIVATE }; /* Root squash enabled (for v1 quota format) */ #define DQF_ROOT_SQUASH (1 << DQF_ROOT_SQUASH_B) /* Quota stored in a system file */ #define DQF_SYS_FILE (1 << DQF_SYS_FILE_B) struct if_dqinfo { __u64 dqi_bgrace; __u64 dqi_igrace; __u32 dqi_flags; /* DFQ_* */ __u32 dqi_valid; }; /* * Definitions for quota netlink interface */ #define QUOTA_NL_NOWARN 0 #define QUOTA_NL_IHARDWARN 1 /* Inode hardlimit reached */ #define QUOTA_NL_ISOFTLONGWARN 2 /* Inode grace time expired */ #define QUOTA_NL_ISOFTWARN 3 /* Inode softlimit reached */ #define QUOTA_NL_BHARDWARN 4 /* Block hardlimit reached */ #define QUOTA_NL_BSOFTLONGWARN 5 /* Block grace time expired */ #define QUOTA_NL_BSOFTWARN 6 /* Block softlimit reached */ #define QUOTA_NL_IHARDBELOW 7 /* Usage got below inode hardlimit */ #define QUOTA_NL_ISOFTBELOW 8 /* Usage got below inode softlimit */ #define QUOTA_NL_BHARDBELOW 9 /* Usage got below block hardlimit */ #define QUOTA_NL_BSOFTBELOW 10 /* Usage got below block softlimit */ enum { QUOTA_NL_C_UNSPEC, QUOTA_NL_C_WARNING, __QUOTA_NL_C_MAX, }; #define QUOTA_NL_C_MAX (__QUOTA_NL_C_MAX - 1) enum { QUOTA_NL_A_UNSPEC, QUOTA_NL_A_QTYPE, QUOTA_NL_A_EXCESS_ID, QUOTA_NL_A_WARNING, QUOTA_NL_A_DEV_MAJOR, QUOTA_NL_A_DEV_MINOR, QUOTA_NL_A_CAUSED_ID, QUOTA_NL_A_PAD, __QUOTA_NL_A_MAX, }; #define QUOTA_NL_A_MAX (__QUOTA_NL_A_MAX - 1) #endif /* _LINUX_QUOTA_ */ linux/selinux_netlink.h000064400000002253151027430560011274 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Netlink event notifications for SELinux. * * Author: James Morris * * Copyright (C) 2004 Red Hat, Inc., James Morris * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. */ #ifndef _LINUX_SELINUX_NETLINK_H #define _LINUX_SELINUX_NETLINK_H #include /* Message types. */ #define SELNL_MSG_BASE 0x10 enum { SELNL_MSG_SETENFORCE = SELNL_MSG_BASE, SELNL_MSG_POLICYLOAD, SELNL_MSG_MAX }; /* Multicast groups - backwards compatiblility for userspace */ #define SELNL_GRP_NONE 0x00000000 #define SELNL_GRP_AVC 0x00000001 /* AVC notifications */ #define SELNL_GRP_ALL 0xffffffff enum selinux_nlgroups { SELNLGRP_NONE, #define SELNLGRP_NONE SELNLGRP_NONE SELNLGRP_AVC, #define SELNLGRP_AVC SELNLGRP_AVC __SELNLGRP_MAX }; #define SELNLGRP_MAX (__SELNLGRP_MAX - 1) /* Message structures */ struct selnl_msg_setenforce { __s32 val; }; struct selnl_msg_policyload { __u32 seqno; }; #endif /* _LINUX_SELINUX_NETLINK_H */ linux/openvswitch.h000064400000116370151027430560010440 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 2007-2017 Nicira, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA */ #ifndef __LINUX_OPENVSWITCH_H #define __LINUX_OPENVSWITCH_H 1 #include #include /** * struct ovs_header - header for OVS Generic Netlink messages. * @dp_ifindex: ifindex of local port for datapath (0 to make a request not * specific to a datapath). * * Attributes following the header are specific to a particular OVS Generic * Netlink family, but all of the OVS families use this header. */ struct ovs_header { int dp_ifindex; }; /* Datapaths. */ #define OVS_DATAPATH_FAMILY "ovs_datapath" #define OVS_DATAPATH_MCGROUP "ovs_datapath" /* V2: * - API users are expected to provide OVS_DP_ATTR_USER_FEATURES * when creating the datapath. */ #define OVS_DATAPATH_VERSION 2 /* First OVS datapath version to support features */ #define OVS_DP_VER_FEATURES 2 enum ovs_datapath_cmd { OVS_DP_CMD_UNSPEC, OVS_DP_CMD_NEW, OVS_DP_CMD_DEL, OVS_DP_CMD_GET, OVS_DP_CMD_SET }; /** * enum ovs_datapath_attr - attributes for %OVS_DP_* commands. * @OVS_DP_ATTR_NAME: Name of the network device that serves as the "local * port". This is the name of the network device whose dp_ifindex is given in * the &struct ovs_header. Always present in notifications. Required in * %OVS_DP_NEW requests. May be used as an alternative to specifying * dp_ifindex in other requests (with a dp_ifindex of 0). * @OVS_DP_ATTR_UPCALL_PID: The Netlink socket in userspace that is initially * set on the datapath port (for OVS_ACTION_ATTR_MISS). Only valid on * %OVS_DP_CMD_NEW requests. A value of zero indicates that upcalls should * not be sent. * @OVS_DP_ATTR_PER_CPU_PIDS: Per-cpu array of PIDs for upcalls when * OVS_DP_F_DISPATCH_UPCALL_PER_CPU feature is set. * @OVS_DP_ATTR_STATS: Statistics about packets that have passed through the * datapath. Always present in notifications. * @OVS_DP_ATTR_MEGAFLOW_STATS: Statistics about mega flow masks usage for the * datapath. Always present in notifications. * @OVS_DP_ATTR_IFINDEX: Interface index for a new datapath netdev. Only * valid for %OVS_DP_CMD_NEW requests. * * These attributes follow the &struct ovs_header within the Generic Netlink * payload for %OVS_DP_* commands. */ enum ovs_datapath_attr { OVS_DP_ATTR_UNSPEC, OVS_DP_ATTR_NAME, /* name of dp_ifindex netdev */ OVS_DP_ATTR_UPCALL_PID, /* Netlink PID to receive upcalls */ OVS_DP_ATTR_STATS, /* struct ovs_dp_stats */ OVS_DP_ATTR_MEGAFLOW_STATS, /* struct ovs_dp_megaflow_stats */ OVS_DP_ATTR_USER_FEATURES, /* OVS_DP_F_* */ OVS_DP_ATTR_PAD, OVS_DP_ATTR_MASKS_CACHE_SIZE, OVS_DP_ATTR_PER_CPU_PIDS, /* Netlink PIDS to receive upcalls in * per-cpu dispatch mode */ OVS_DP_ATTR_IFINDEX, __OVS_DP_ATTR_MAX }; #define OVS_DP_ATTR_MAX (__OVS_DP_ATTR_MAX - 1) struct ovs_dp_stats { __u64 n_hit; /* Number of flow table matches. */ __u64 n_missed; /* Number of flow table misses. */ __u64 n_lost; /* Number of misses not sent to userspace. */ __u64 n_flows; /* Number of flows present */ }; struct ovs_dp_megaflow_stats { __u64 n_mask_hit; /* Number of masks used for flow lookups. */ __u32 n_masks; /* Number of masks for the datapath. */ __u32 pad0; /* Pad for future expension. */ __u64 n_cache_hit; /* Number of cache matches for flow lookups. */ __u64 pad1; /* Pad for future expension. */ }; struct ovs_vport_stats { __u64 rx_packets; /* total packets received */ __u64 tx_packets; /* total packets transmitted */ __u64 rx_bytes; /* total bytes received */ __u64 tx_bytes; /* total bytes transmitted */ __u64 rx_errors; /* bad packets received */ __u64 tx_errors; /* packet transmit problems */ __u64 rx_dropped; /* no space in linux buffers */ __u64 tx_dropped; /* no space available in linux */ }; /* Allow last Netlink attribute to be unaligned */ #define OVS_DP_F_UNALIGNED (1 << 0) /* Allow datapath to associate multiple Netlink PIDs to each vport */ #define OVS_DP_F_VPORT_PIDS (1 << 1) /* Allow tc offload recirc sharing */ #define OVS_DP_F_TC_RECIRC_SHARING (1 << 2) /* Allow per-cpu dispatch of upcalls */ #define OVS_DP_F_DISPATCH_UPCALL_PER_CPU (1 << 3) /* Fixed logical ports. */ #define OVSP_LOCAL ((__u32)0) /* Packet transfer. */ #define OVS_PACKET_FAMILY "ovs_packet" #define OVS_PACKET_VERSION 0x1 enum ovs_packet_cmd { OVS_PACKET_CMD_UNSPEC, /* Kernel-to-user notifications. */ OVS_PACKET_CMD_MISS, /* Flow table miss. */ OVS_PACKET_CMD_ACTION, /* OVS_ACTION_ATTR_USERSPACE action. */ /* Userspace commands. */ OVS_PACKET_CMD_EXECUTE /* Apply actions to a packet. */ }; /** * enum ovs_packet_attr - attributes for %OVS_PACKET_* commands. * @OVS_PACKET_ATTR_PACKET: Present for all notifications. Contains the entire * packet as received, from the start of the Ethernet header onward. For * %OVS_PACKET_CMD_ACTION, %OVS_PACKET_ATTR_PACKET reflects changes made by * actions preceding %OVS_ACTION_ATTR_USERSPACE, but %OVS_PACKET_ATTR_KEY is * the flow key extracted from the packet as originally received. * @OVS_PACKET_ATTR_KEY: Present for all notifications. Contains the flow key * extracted from the packet as nested %OVS_KEY_ATTR_* attributes. This allows * userspace to adapt its flow setup strategy by comparing its notion of the * flow key against the kernel's. * @OVS_PACKET_ATTR_ACTIONS: Contains actions for the packet. Used * for %OVS_PACKET_CMD_EXECUTE. It has nested %OVS_ACTION_ATTR_* attributes. * Also used in upcall when %OVS_ACTION_ATTR_USERSPACE has optional * %OVS_USERSPACE_ATTR_ACTIONS attribute. * @OVS_PACKET_ATTR_USERDATA: Present for an %OVS_PACKET_CMD_ACTION * notification if the %OVS_ACTION_ATTR_USERSPACE action specified an * %OVS_USERSPACE_ATTR_USERDATA attribute, with the same length and content * specified there. * @OVS_PACKET_ATTR_EGRESS_TUN_KEY: Present for an %OVS_PACKET_CMD_ACTION * notification if the %OVS_ACTION_ATTR_USERSPACE action specified an * %OVS_USERSPACE_ATTR_EGRESS_TUN_PORT attribute, which is sent only if the * output port is actually a tunnel port. Contains the output tunnel key * extracted from the packet as nested %OVS_TUNNEL_KEY_ATTR_* attributes. * @OVS_PACKET_ATTR_MRU: Present for an %OVS_PACKET_CMD_ACTION and * @OVS_PACKET_ATTR_LEN: Packet size before truncation. * %OVS_PACKET_ATTR_USERSPACE action specify the Maximum received fragment * size. * @OVS_PACKET_ATTR_HASH: Packet hash info (e.g. hash, sw_hash and l4_hash in skb). * * These attributes follow the &struct ovs_header within the Generic Netlink * payload for %OVS_PACKET_* commands. */ enum ovs_packet_attr { OVS_PACKET_ATTR_UNSPEC, OVS_PACKET_ATTR_PACKET, /* Packet data. */ OVS_PACKET_ATTR_KEY, /* Nested OVS_KEY_ATTR_* attributes. */ OVS_PACKET_ATTR_ACTIONS, /* Nested OVS_ACTION_ATTR_* attributes. */ OVS_PACKET_ATTR_USERDATA, /* OVS_ACTION_ATTR_USERSPACE arg. */ OVS_PACKET_ATTR_EGRESS_TUN_KEY, /* Nested OVS_TUNNEL_KEY_ATTR_* attributes. */ OVS_PACKET_ATTR_UNUSED1, OVS_PACKET_ATTR_UNUSED2, OVS_PACKET_ATTR_PROBE, /* Packet operation is a feature probe, error logging should be suppressed. */ OVS_PACKET_ATTR_MRU, /* Maximum received IP fragment size. */ OVS_PACKET_ATTR_LEN, /* Packet size before truncation. */ OVS_PACKET_ATTR_HASH, /* Packet hash. */ __OVS_PACKET_ATTR_MAX }; #define OVS_PACKET_ATTR_MAX (__OVS_PACKET_ATTR_MAX - 1) /* Virtual ports. */ #define OVS_VPORT_FAMILY "ovs_vport" #define OVS_VPORT_MCGROUP "ovs_vport" #define OVS_VPORT_VERSION 0x1 enum ovs_vport_cmd { OVS_VPORT_CMD_UNSPEC, OVS_VPORT_CMD_NEW, OVS_VPORT_CMD_DEL, OVS_VPORT_CMD_GET, OVS_VPORT_CMD_SET }; enum ovs_vport_type { OVS_VPORT_TYPE_UNSPEC, OVS_VPORT_TYPE_NETDEV, /* network device */ OVS_VPORT_TYPE_INTERNAL, /* network device implemented by datapath */ OVS_VPORT_TYPE_GRE, /* GRE tunnel. */ OVS_VPORT_TYPE_VXLAN, /* VXLAN tunnel. */ OVS_VPORT_TYPE_GENEVE, /* Geneve tunnel. */ __OVS_VPORT_TYPE_MAX }; #define OVS_VPORT_TYPE_MAX (__OVS_VPORT_TYPE_MAX - 1) /** * enum ovs_vport_attr - attributes for %OVS_VPORT_* commands. * @OVS_VPORT_ATTR_PORT_NO: 32-bit port number within datapath. * @OVS_VPORT_ATTR_TYPE: 32-bit %OVS_VPORT_TYPE_* constant describing the type * of vport. * @OVS_VPORT_ATTR_NAME: Name of vport. For a vport based on a network device * this is the name of the network device. Maximum length %IFNAMSIZ-1 bytes * plus a null terminator. * @OVS_VPORT_ATTR_OPTIONS: Vport-specific configuration information. * @OVS_VPORT_ATTR_UPCALL_PID: The array of Netlink socket pids in userspace * among which OVS_PACKET_CMD_MISS upcalls will be distributed for packets * received on this port. If this is a single-element array of value 0, * upcalls should not be sent. * @OVS_VPORT_ATTR_STATS: A &struct ovs_vport_stats giving statistics for * packets sent or received through the vport. * * These attributes follow the &struct ovs_header within the Generic Netlink * payload for %OVS_VPORT_* commands. * * For %OVS_VPORT_CMD_NEW requests, the %OVS_VPORT_ATTR_TYPE and * %OVS_VPORT_ATTR_NAME attributes are required. %OVS_VPORT_ATTR_PORT_NO is * optional; if not specified a free port number is automatically selected. * Whether %OVS_VPORT_ATTR_OPTIONS is required or optional depends on the type * of vport. * * For other requests, if %OVS_VPORT_ATTR_NAME is specified then it is used to * look up the vport to operate on; otherwise dp_idx from the &struct * ovs_header plus %OVS_VPORT_ATTR_PORT_NO determine the vport. */ enum ovs_vport_attr { OVS_VPORT_ATTR_UNSPEC, OVS_VPORT_ATTR_PORT_NO, /* u32 port number within datapath */ OVS_VPORT_ATTR_TYPE, /* u32 OVS_VPORT_TYPE_* constant. */ OVS_VPORT_ATTR_NAME, /* string name, up to IFNAMSIZ bytes long */ OVS_VPORT_ATTR_OPTIONS, /* nested attributes, varies by vport type */ OVS_VPORT_ATTR_UPCALL_PID, /* array of u32 Netlink socket PIDs for */ /* receiving upcalls */ OVS_VPORT_ATTR_STATS, /* struct ovs_vport_stats */ OVS_VPORT_ATTR_PAD, OVS_VPORT_ATTR_IFINDEX, OVS_VPORT_ATTR_NETNSID, OVS_VPORT_ATTR_UPCALL_STATS, __OVS_VPORT_ATTR_MAX }; #define OVS_VPORT_ATTR_MAX (__OVS_VPORT_ATTR_MAX - 1) /** * enum ovs_vport_upcall_attr - attributes for %OVS_VPORT_UPCALL* commands * @OVS_VPORT_UPCALL_SUCCESS: 64-bit upcall success packets. * @OVS_VPORT_UPCALL_FAIL: 64-bit upcall fail packets. */ enum ovs_vport_upcall_attr { OVS_VPORT_UPCALL_ATTR_SUCCESS, OVS_VPORT_UPCALL_ATTR_FAIL, __OVS_VPORT_UPCALL_ATTR_MAX }; #define OVS_VPORT_UPCALL_ATTR_MAX (__OVS_VPORT_UPCALL_ATTR_MAX - 1) enum { OVS_VXLAN_EXT_UNSPEC, OVS_VXLAN_EXT_GBP, /* Flag or __u32 */ __OVS_VXLAN_EXT_MAX, }; #define OVS_VXLAN_EXT_MAX (__OVS_VXLAN_EXT_MAX - 1) /* OVS_VPORT_ATTR_OPTIONS attributes for tunnels. */ enum { OVS_TUNNEL_ATTR_UNSPEC, OVS_TUNNEL_ATTR_DST_PORT, /* 16-bit UDP port, used by L4 tunnels. */ OVS_TUNNEL_ATTR_EXTENSION, __OVS_TUNNEL_ATTR_MAX }; #define OVS_TUNNEL_ATTR_MAX (__OVS_TUNNEL_ATTR_MAX - 1) /* Flows. */ #define OVS_FLOW_FAMILY "ovs_flow" #define OVS_FLOW_MCGROUP "ovs_flow" #define OVS_FLOW_VERSION 0x1 enum ovs_flow_cmd { OVS_FLOW_CMD_UNSPEC, OVS_FLOW_CMD_NEW, OVS_FLOW_CMD_DEL, OVS_FLOW_CMD_GET, OVS_FLOW_CMD_SET }; struct ovs_flow_stats { __u64 n_packets; /* Number of matched packets. */ __u64 n_bytes; /* Number of matched bytes. */ }; enum ovs_key_attr { OVS_KEY_ATTR_UNSPEC, OVS_KEY_ATTR_ENCAP, /* Nested set of encapsulated attributes. */ OVS_KEY_ATTR_PRIORITY, /* u32 skb->priority */ OVS_KEY_ATTR_IN_PORT, /* u32 OVS dp port number */ OVS_KEY_ATTR_ETHERNET, /* struct ovs_key_ethernet */ OVS_KEY_ATTR_VLAN, /* be16 VLAN TCI */ OVS_KEY_ATTR_ETHERTYPE, /* be16 Ethernet type */ OVS_KEY_ATTR_IPV4, /* struct ovs_key_ipv4 */ OVS_KEY_ATTR_IPV6, /* struct ovs_key_ipv6 */ OVS_KEY_ATTR_TCP, /* struct ovs_key_tcp */ OVS_KEY_ATTR_UDP, /* struct ovs_key_udp */ OVS_KEY_ATTR_ICMP, /* struct ovs_key_icmp */ OVS_KEY_ATTR_ICMPV6, /* struct ovs_key_icmpv6 */ OVS_KEY_ATTR_ARP, /* struct ovs_key_arp */ OVS_KEY_ATTR_ND, /* struct ovs_key_nd */ OVS_KEY_ATTR_SKB_MARK, /* u32 skb mark */ OVS_KEY_ATTR_TUNNEL, /* Nested set of ovs_tunnel attributes */ OVS_KEY_ATTR_SCTP, /* struct ovs_key_sctp */ OVS_KEY_ATTR_TCP_FLAGS, /* be16 TCP flags. */ OVS_KEY_ATTR_DP_HASH, /* u32 hash value. Value 0 indicates the hash is not computed by the datapath. */ OVS_KEY_ATTR_RECIRC_ID, /* u32 recirc id */ OVS_KEY_ATTR_MPLS, /* array of struct ovs_key_mpls. * The implementation may restrict * the accepted length of the array. */ OVS_KEY_ATTR_CT_STATE, /* u32 bitmask of OVS_CS_F_* */ OVS_KEY_ATTR_CT_ZONE, /* u16 connection tracking zone. */ OVS_KEY_ATTR_CT_MARK, /* u32 connection tracking mark */ OVS_KEY_ATTR_CT_LABELS, /* 16-octet connection tracking label */ OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4, /* struct ovs_key_ct_tuple_ipv4 */ OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV6, /* struct ovs_key_ct_tuple_ipv6 */ OVS_KEY_ATTR_NSH, /* Nested set of ovs_nsh_key_* */ __OVS_KEY_ATTR_MAX }; #define OVS_KEY_ATTR_MAX (__OVS_KEY_ATTR_MAX - 1) enum ovs_tunnel_key_attr { /* OVS_TUNNEL_KEY_ATTR_NONE, standard nl API requires this attribute! */ OVS_TUNNEL_KEY_ATTR_ID, /* be64 Tunnel ID */ OVS_TUNNEL_KEY_ATTR_IPV4_SRC, /* be32 src IP address. */ OVS_TUNNEL_KEY_ATTR_IPV4_DST, /* be32 dst IP address. */ OVS_TUNNEL_KEY_ATTR_TOS, /* u8 Tunnel IP ToS. */ OVS_TUNNEL_KEY_ATTR_TTL, /* u8 Tunnel IP TTL. */ OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT, /* No argument, set DF. */ OVS_TUNNEL_KEY_ATTR_CSUM, /* No argument. CSUM packet. */ OVS_TUNNEL_KEY_ATTR_OAM, /* No argument. OAM frame. */ OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS, /* Array of Geneve options. */ OVS_TUNNEL_KEY_ATTR_TP_SRC, /* be16 src Transport Port. */ OVS_TUNNEL_KEY_ATTR_TP_DST, /* be16 dst Transport Port. */ OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS, /* Nested OVS_VXLAN_EXT_* */ OVS_TUNNEL_KEY_ATTR_IPV6_SRC, /* struct in6_addr src IPv6 address. */ OVS_TUNNEL_KEY_ATTR_IPV6_DST, /* struct in6_addr dst IPv6 address. */ OVS_TUNNEL_KEY_ATTR_PAD, OVS_TUNNEL_KEY_ATTR_ERSPAN_OPTS, /* struct erspan_metadata */ OVS_TUNNEL_KEY_ATTR_IPV4_INFO_BRIDGE, /* No argument. IPV4_INFO_BRIDGE mode.*/ __OVS_TUNNEL_KEY_ATTR_MAX }; #define OVS_TUNNEL_KEY_ATTR_MAX (__OVS_TUNNEL_KEY_ATTR_MAX - 1) /** * enum ovs_frag_type - IPv4 and IPv6 fragment type * @OVS_FRAG_TYPE_NONE: Packet is not a fragment. * @OVS_FRAG_TYPE_FIRST: Packet is a fragment with offset 0. * @OVS_FRAG_TYPE_LATER: Packet is a fragment with nonzero offset. * * Used as the @ipv4_frag in &struct ovs_key_ipv4 and as @ipv6_frag &struct * ovs_key_ipv6. */ enum ovs_frag_type { OVS_FRAG_TYPE_NONE, OVS_FRAG_TYPE_FIRST, OVS_FRAG_TYPE_LATER, __OVS_FRAG_TYPE_MAX }; #define OVS_FRAG_TYPE_MAX (__OVS_FRAG_TYPE_MAX - 1) struct ovs_key_ethernet { __u8 eth_src[ETH_ALEN]; __u8 eth_dst[ETH_ALEN]; }; struct ovs_key_mpls { __be32 mpls_lse; }; struct ovs_key_ipv4 { __be32 ipv4_src; __be32 ipv4_dst; __u8 ipv4_proto; __u8 ipv4_tos; __u8 ipv4_ttl; __u8 ipv4_frag; /* One of OVS_FRAG_TYPE_*. */ }; struct ovs_key_ipv6 { __be32 ipv6_src[4]; __be32 ipv6_dst[4]; __be32 ipv6_label; /* 20-bits in least-significant bits. */ __u8 ipv6_proto; __u8 ipv6_tclass; __u8 ipv6_hlimit; __u8 ipv6_frag; /* One of OVS_FRAG_TYPE_*. */ }; struct ovs_key_tcp { __be16 tcp_src; __be16 tcp_dst; }; struct ovs_key_udp { __be16 udp_src; __be16 udp_dst; }; struct ovs_key_sctp { __be16 sctp_src; __be16 sctp_dst; }; struct ovs_key_icmp { __u8 icmp_type; __u8 icmp_code; }; struct ovs_key_icmpv6 { __u8 icmpv6_type; __u8 icmpv6_code; }; struct ovs_key_arp { __be32 arp_sip; __be32 arp_tip; __be16 arp_op; __u8 arp_sha[ETH_ALEN]; __u8 arp_tha[ETH_ALEN]; }; struct ovs_key_nd { __be32 nd_target[4]; __u8 nd_sll[ETH_ALEN]; __u8 nd_tll[ETH_ALEN]; }; #define OVS_CT_LABELS_LEN_32 4 #define OVS_CT_LABELS_LEN (OVS_CT_LABELS_LEN_32 * sizeof(__u32)) struct ovs_key_ct_labels { union { __u8 ct_labels[OVS_CT_LABELS_LEN]; __u32 ct_labels_32[OVS_CT_LABELS_LEN_32]; }; }; /* OVS_KEY_ATTR_CT_STATE flags */ #define OVS_CS_F_NEW 0x01 /* Beginning of a new connection. */ #define OVS_CS_F_ESTABLISHED 0x02 /* Part of an existing connection. */ #define OVS_CS_F_RELATED 0x04 /* Related to an established * connection. */ #define OVS_CS_F_REPLY_DIR 0x08 /* Flow is in the reply direction. */ #define OVS_CS_F_INVALID 0x10 /* Could not track connection. */ #define OVS_CS_F_TRACKED 0x20 /* Conntrack has occurred. */ #define OVS_CS_F_SRC_NAT 0x40 /* Packet's source address/port was * mangled by NAT. */ #define OVS_CS_F_DST_NAT 0x80 /* Packet's destination address/port * was mangled by NAT. */ #define OVS_CS_F_NAT_MASK (OVS_CS_F_SRC_NAT | OVS_CS_F_DST_NAT) struct ovs_key_ct_tuple_ipv4 { __be32 ipv4_src; __be32 ipv4_dst; __be16 src_port; __be16 dst_port; __u8 ipv4_proto; }; struct ovs_key_ct_tuple_ipv6 { __be32 ipv6_src[4]; __be32 ipv6_dst[4]; __be16 src_port; __be16 dst_port; __u8 ipv6_proto; }; enum ovs_nsh_key_attr { OVS_NSH_KEY_ATTR_UNSPEC, OVS_NSH_KEY_ATTR_BASE, /* struct ovs_nsh_key_base. */ OVS_NSH_KEY_ATTR_MD1, /* struct ovs_nsh_key_md1. */ OVS_NSH_KEY_ATTR_MD2, /* variable-length octets for MD type 2. */ __OVS_NSH_KEY_ATTR_MAX }; #define OVS_NSH_KEY_ATTR_MAX (__OVS_NSH_KEY_ATTR_MAX - 1) struct ovs_nsh_key_base { __u8 flags; __u8 ttl; __u8 mdtype; __u8 np; __be32 path_hdr; }; #define NSH_MD1_CONTEXT_SIZE 4 struct ovs_nsh_key_md1 { __be32 context[NSH_MD1_CONTEXT_SIZE]; }; /** * enum ovs_flow_attr - attributes for %OVS_FLOW_* commands. * @OVS_FLOW_ATTR_KEY: Nested %OVS_KEY_ATTR_* attributes specifying the flow * key. Always present in notifications. Required for all requests (except * dumps). * @OVS_FLOW_ATTR_ACTIONS: Nested %OVS_ACTION_ATTR_* attributes specifying * the actions to take for packets that match the key. Always present in * notifications. Required for %OVS_FLOW_CMD_NEW requests, optional for * %OVS_FLOW_CMD_SET requests. An %OVS_FLOW_CMD_SET without * %OVS_FLOW_ATTR_ACTIONS will not modify the actions. To clear the actions, * an %OVS_FLOW_ATTR_ACTIONS without any nested attributes must be given. * @OVS_FLOW_ATTR_STATS: &struct ovs_flow_stats giving statistics for this * flow. Present in notifications if the stats would be nonzero. Ignored in * requests. * @OVS_FLOW_ATTR_TCP_FLAGS: An 8-bit value giving the OR'd value of all of the * TCP flags seen on packets in this flow. Only present in notifications for * TCP flows, and only if it would be nonzero. Ignored in requests. * @OVS_FLOW_ATTR_USED: A 64-bit integer giving the time, in milliseconds on * the system monotonic clock, at which a packet was last processed for this * flow. Only present in notifications if a packet has been processed for this * flow. Ignored in requests. * @OVS_FLOW_ATTR_CLEAR: If present in a %OVS_FLOW_CMD_SET request, clears the * last-used time, accumulated TCP flags, and statistics for this flow. * Otherwise ignored in requests. Never present in notifications. * @OVS_FLOW_ATTR_MASK: Nested %OVS_KEY_ATTR_* attributes specifying the * mask bits for wildcarded flow match. Mask bit value '1' specifies exact * match with corresponding flow key bit, while mask bit value '0' specifies * a wildcarded match. Omitting attribute is treated as wildcarding all * corresponding fields. Optional for all requests. If not present, * all flow key bits are exact match bits. * @OVS_FLOW_ATTR_UFID: A value between 1-16 octets specifying a unique * identifier for the flow. Causes the flow to be indexed by this value rather * than the value of the %OVS_FLOW_ATTR_KEY attribute. Optional for all * requests. Present in notifications if the flow was created with this * attribute. * @OVS_FLOW_ATTR_UFID_FLAGS: A 32-bit value of OR'd %OVS_UFID_F_* * flags that provide alternative semantics for flow installation and * retrieval. Optional for all requests. * * These attributes follow the &struct ovs_header within the Generic Netlink * payload for %OVS_FLOW_* commands. */ enum ovs_flow_attr { OVS_FLOW_ATTR_UNSPEC, OVS_FLOW_ATTR_KEY, /* Sequence of OVS_KEY_ATTR_* attributes. */ OVS_FLOW_ATTR_ACTIONS, /* Nested OVS_ACTION_ATTR_* attributes. */ OVS_FLOW_ATTR_STATS, /* struct ovs_flow_stats. */ OVS_FLOW_ATTR_TCP_FLAGS, /* 8-bit OR'd TCP flags. */ OVS_FLOW_ATTR_USED, /* u64 msecs last used in monotonic time. */ OVS_FLOW_ATTR_CLEAR, /* Flag to clear stats, tcp_flags, used. */ OVS_FLOW_ATTR_MASK, /* Sequence of OVS_KEY_ATTR_* attributes. */ OVS_FLOW_ATTR_PROBE, /* Flow operation is a feature probe, error * logging should be suppressed. */ OVS_FLOW_ATTR_UFID, /* Variable length unique flow identifier. */ OVS_FLOW_ATTR_UFID_FLAGS,/* u32 of OVS_UFID_F_*. */ OVS_FLOW_ATTR_PAD, __OVS_FLOW_ATTR_MAX }; #define OVS_FLOW_ATTR_MAX (__OVS_FLOW_ATTR_MAX - 1) /** * Omit attributes for notifications. * * If a datapath request contains an %OVS_UFID_F_OMIT_* flag, then the datapath * may omit the corresponding %OVS_FLOW_ATTR_* from the response. */ #define OVS_UFID_F_OMIT_KEY (1 << 0) #define OVS_UFID_F_OMIT_MASK (1 << 1) #define OVS_UFID_F_OMIT_ACTIONS (1 << 2) /** * enum ovs_sample_attr - Attributes for %OVS_ACTION_ATTR_SAMPLE action. * @OVS_SAMPLE_ATTR_PROBABILITY: 32-bit fraction of packets to sample with * @OVS_ACTION_ATTR_SAMPLE. A value of 0 samples no packets, a value of * %UINT32_MAX samples all packets and intermediate values sample intermediate * fractions of packets. * @OVS_SAMPLE_ATTR_ACTIONS: Set of actions to execute in sampling event. * Actions are passed as nested attributes. * * Executes the specified actions with the given probability on a per-packet * basis. */ enum ovs_sample_attr { OVS_SAMPLE_ATTR_UNSPEC, OVS_SAMPLE_ATTR_PROBABILITY, /* u32 number */ OVS_SAMPLE_ATTR_ACTIONS, /* Nested OVS_ACTION_ATTR_* attributes. */ __OVS_SAMPLE_ATTR_MAX, }; #define OVS_SAMPLE_ATTR_MAX (__OVS_SAMPLE_ATTR_MAX - 1) /** * enum ovs_userspace_attr - Attributes for %OVS_ACTION_ATTR_USERSPACE action. * @OVS_USERSPACE_ATTR_PID: u32 Netlink PID to which the %OVS_PACKET_CMD_ACTION * message should be sent. Required. * @OVS_USERSPACE_ATTR_USERDATA: If present, its variable-length argument is * copied to the %OVS_PACKET_CMD_ACTION message as %OVS_PACKET_ATTR_USERDATA. * @OVS_USERSPACE_ATTR_EGRESS_TUN_PORT: If present, u32 output port to get * tunnel info. * @OVS_USERSPACE_ATTR_ACTIONS: If present, send actions with upcall. */ enum ovs_userspace_attr { OVS_USERSPACE_ATTR_UNSPEC, OVS_USERSPACE_ATTR_PID, /* u32 Netlink PID to receive upcalls. */ OVS_USERSPACE_ATTR_USERDATA, /* Optional user-specified cookie. */ OVS_USERSPACE_ATTR_EGRESS_TUN_PORT, /* Optional, u32 output port * to get tunnel info. */ OVS_USERSPACE_ATTR_ACTIONS, /* Optional flag to get actions. */ __OVS_USERSPACE_ATTR_MAX }; #define OVS_USERSPACE_ATTR_MAX (__OVS_USERSPACE_ATTR_MAX - 1) struct ovs_action_trunc { __u32 max_len; /* Max packet size in bytes. */ }; /** * struct ovs_action_push_mpls - %OVS_ACTION_ATTR_PUSH_MPLS action argument. * @mpls_lse: MPLS label stack entry to push. * @mpls_ethertype: Ethertype to set in the encapsulating ethernet frame. * * The only values @mpls_ethertype should ever be given are %ETH_P_MPLS_UC and * %ETH_P_MPLS_MC, indicating MPLS unicast or multicast. Other are rejected. */ struct ovs_action_push_mpls { __be32 mpls_lse; __be16 mpls_ethertype; /* Either %ETH_P_MPLS_UC or %ETH_P_MPLS_MC */ }; /** * struct ovs_action_add_mpls - %OVS_ACTION_ATTR_ADD_MPLS action * argument. * @mpls_lse: MPLS label stack entry to push. * @mpls_ethertype: Ethertype to set in the encapsulating ethernet frame. * @tun_flags: MPLS tunnel attributes. * * The only values @mpls_ethertype should ever be given are %ETH_P_MPLS_UC and * %ETH_P_MPLS_MC, indicating MPLS unicast or multicast. Other are rejected. */ struct ovs_action_add_mpls { __be32 mpls_lse; __be16 mpls_ethertype; /* Either %ETH_P_MPLS_UC or %ETH_P_MPLS_MC */ __u16 tun_flags; }; #define OVS_MPLS_L3_TUNNEL_FLAG_MASK (1 << 0) /* Flag to specify the place of * insertion of MPLS header. * When false, the MPLS header * will be inserted at the start * of the packet. * When true, the MPLS header * will be inserted at the start * of the l3 header. */ /** * struct ovs_action_push_vlan - %OVS_ACTION_ATTR_PUSH_VLAN action argument. * @vlan_tpid: Tag protocol identifier (TPID) to push. * @vlan_tci: Tag control identifier (TCI) to push. The CFI bit must be set * (but it will not be set in the 802.1Q header that is pushed). * * The @vlan_tpid value is typically %ETH_P_8021Q or %ETH_P_8021AD. * The only acceptable TPID values are those that the kernel module also parses * as 802.1Q or 802.1AD headers, to prevent %OVS_ACTION_ATTR_PUSH_VLAN followed * by %OVS_ACTION_ATTR_POP_VLAN from having surprising results. */ struct ovs_action_push_vlan { __be16 vlan_tpid; /* 802.1Q or 802.1ad TPID. */ __be16 vlan_tci; /* 802.1Q TCI (VLAN ID and priority). */ }; /* Data path hash algorithm for computing Datapath hash. * * The algorithm type only specifies the fields in a flow * will be used as part of the hash. Each datapath is free * to use its own hash algorithm. The hash value will be * opaque to the user space daemon. */ enum ovs_hash_alg { OVS_HASH_ALG_L4, OVS_HASH_ALG_SYM_L4, }; /* * struct ovs_action_hash - %OVS_ACTION_ATTR_HASH action argument. * @hash_alg: Algorithm used to compute hash prior to recirculation. * @hash_basis: basis used for computing hash. */ struct ovs_action_hash { __u32 hash_alg; /* One of ovs_hash_alg. */ __u32 hash_basis; }; /** * enum ovs_ct_attr - Attributes for %OVS_ACTION_ATTR_CT action. * @OVS_CT_ATTR_COMMIT: If present, commits the connection to the conntrack * table. This allows future packets for the same connection to be identified * as 'established' or 'related'. The flow key for the current packet will * retain the pre-commit connection state. * @OVS_CT_ATTR_ZONE: u16 connection tracking zone. * @OVS_CT_ATTR_MARK: u32 value followed by u32 mask. For each bit set in the * mask, the corresponding bit in the value is copied to the connection * tracking mark field in the connection. * @OVS_CT_ATTR_LABELS: %OVS_CT_LABELS_LEN value followed by %OVS_CT_LABELS_LEN * mask. For each bit set in the mask, the corresponding bit in the value is * copied to the connection tracking label field in the connection. * @OVS_CT_ATTR_HELPER: variable length string defining conntrack ALG. * @OVS_CT_ATTR_NAT: Nested OVS_NAT_ATTR_* for performing L3 network address * translation (NAT) on the packet. * @OVS_CT_ATTR_FORCE_COMMIT: Like %OVS_CT_ATTR_COMMIT, but instead of doing * nothing if the connection is already committed will check that the current * packet is in conntrack entry's original direction. If directionality does * not match, will delete the existing conntrack entry and commit a new one. * @OVS_CT_ATTR_EVENTMASK: Mask of bits indicating which conntrack event types * (enum ip_conntrack_events IPCT_*) should be reported. For any bit set to * zero, the corresponding event type is not generated. Default behavior * depends on system configuration, but typically all event types are * generated, hence listening on NFNLGRP_CONNTRACK_UPDATE events may get a lot * of events. Explicitly passing this attribute allows limiting the updates * received to the events of interest. The bit 1 << IPCT_NEW, 1 << * IPCT_RELATED, and 1 << IPCT_DESTROY must be set to ones for those events to * be received on NFNLGRP_CONNTRACK_NEW and NFNLGRP_CONNTRACK_DESTROY groups, * respectively. Remaining bits control the changes for which an event is * delivered on the NFNLGRP_CONNTRACK_UPDATE group. * @OVS_CT_ATTR_TIMEOUT: Variable length string defining conntrack timeout. */ enum ovs_ct_attr { OVS_CT_ATTR_UNSPEC, OVS_CT_ATTR_COMMIT, /* No argument, commits connection. */ OVS_CT_ATTR_ZONE, /* u16 zone id. */ OVS_CT_ATTR_MARK, /* mark to associate with this connection. */ OVS_CT_ATTR_LABELS, /* labels to associate with this connection. */ OVS_CT_ATTR_HELPER, /* netlink helper to assist detection of related connections. */ OVS_CT_ATTR_NAT, /* Nested OVS_NAT_ATTR_* */ OVS_CT_ATTR_FORCE_COMMIT, /* No argument */ OVS_CT_ATTR_EVENTMASK, /* u32 mask of IPCT_* events. */ OVS_CT_ATTR_TIMEOUT, /* Associate timeout with this connection for * fine-grain timeout tuning. */ __OVS_CT_ATTR_MAX }; #define OVS_CT_ATTR_MAX (__OVS_CT_ATTR_MAX - 1) /** * enum ovs_nat_attr - Attributes for %OVS_CT_ATTR_NAT. * * @OVS_NAT_ATTR_SRC: Flag for Source NAT (mangle source address/port). * @OVS_NAT_ATTR_DST: Flag for Destination NAT (mangle destination * address/port). Only one of (@OVS_NAT_ATTR_SRC, @OVS_NAT_ATTR_DST) may be * specified. Effective only for packets for ct_state NEW connections. * Packets of committed connections are mangled by the NAT action according to * the committed NAT type regardless of the flags specified. As a corollary, a * NAT action without a NAT type flag will only mangle packets of committed * connections. The following NAT attributes only apply for NEW * (non-committed) connections, and they may be included only when the CT * action has the @OVS_CT_ATTR_COMMIT flag and either @OVS_NAT_ATTR_SRC or * @OVS_NAT_ATTR_DST is also included. * @OVS_NAT_ATTR_IP_MIN: struct in_addr or struct in6_addr * @OVS_NAT_ATTR_IP_MAX: struct in_addr or struct in6_addr * @OVS_NAT_ATTR_PROTO_MIN: u16 L4 protocol specific lower boundary (port) * @OVS_NAT_ATTR_PROTO_MAX: u16 L4 protocol specific upper boundary (port) * @OVS_NAT_ATTR_PERSISTENT: Flag for persistent IP mapping across reboots * @OVS_NAT_ATTR_PROTO_HASH: Flag for pseudo random L4 port mapping (MD5) * @OVS_NAT_ATTR_PROTO_RANDOM: Flag for fully randomized L4 port mapping */ enum ovs_nat_attr { OVS_NAT_ATTR_UNSPEC, OVS_NAT_ATTR_SRC, OVS_NAT_ATTR_DST, OVS_NAT_ATTR_IP_MIN, OVS_NAT_ATTR_IP_MAX, OVS_NAT_ATTR_PROTO_MIN, OVS_NAT_ATTR_PROTO_MAX, OVS_NAT_ATTR_PERSISTENT, OVS_NAT_ATTR_PROTO_HASH, OVS_NAT_ATTR_PROTO_RANDOM, __OVS_NAT_ATTR_MAX, }; #define OVS_NAT_ATTR_MAX (__OVS_NAT_ATTR_MAX - 1) /* * struct ovs_action_push_eth - %OVS_ACTION_ATTR_PUSH_ETH action argument. * @addresses: Source and destination MAC addresses. * @eth_type: Ethernet type */ struct ovs_action_push_eth { struct ovs_key_ethernet addresses; }; /* * enum ovs_check_pkt_len_attr - Attributes for %OVS_ACTION_ATTR_CHECK_PKT_LEN. * * @OVS_CHECK_PKT_LEN_ATTR_PKT_LEN: u16 Packet length to check for. * @OVS_CHECK_PKT_LEN_ATTR_ACTIONS_IF_GREATER: Nested OVS_ACTION_ATTR_* * actions to apply if the packer length is greater than the specified * length in the attr - OVS_CHECK_PKT_LEN_ATTR_PKT_LEN. * @OVS_CHECK_PKT_LEN_ATTR_ACTIONS_IF_LESS_EQUAL - Nested OVS_ACTION_ATTR_* * actions to apply if the packer length is lesser or equal to the specified * length in the attr - OVS_CHECK_PKT_LEN_ATTR_PKT_LEN. */ enum ovs_check_pkt_len_attr { OVS_CHECK_PKT_LEN_ATTR_UNSPEC, OVS_CHECK_PKT_LEN_ATTR_PKT_LEN, OVS_CHECK_PKT_LEN_ATTR_ACTIONS_IF_GREATER, OVS_CHECK_PKT_LEN_ATTR_ACTIONS_IF_LESS_EQUAL, __OVS_CHECK_PKT_LEN_ATTR_MAX, }; #define OVS_CHECK_PKT_LEN_ATTR_MAX (__OVS_CHECK_PKT_LEN_ATTR_MAX - 1) /** * enum ovs_action_attr - Action types. * * @OVS_ACTION_ATTR_OUTPUT: Output packet to port. * @OVS_ACTION_ATTR_TRUNC: Output packet to port with truncated packet size. * @OVS_ACTION_ATTR_USERSPACE: Send packet to userspace according to nested * %OVS_USERSPACE_ATTR_* attributes. * @OVS_ACTION_ATTR_SET: Replaces the contents of an existing header. The * single nested %OVS_KEY_ATTR_* attribute specifies a header to modify and its * value. * @OVS_ACTION_ATTR_SET_MASKED: Replaces the contents of an existing header. A * nested %OVS_KEY_ATTR_* attribute specifies a header to modify, its value, * and a mask. For every bit set in the mask, the corresponding bit value * is copied from the value to the packet header field, rest of the bits are * left unchanged. The non-masked value bits must be passed in as zeroes. * Masking is not supported for the %OVS_KEY_ATTR_TUNNEL attribute. * @OVS_ACTION_ATTR_PUSH_VLAN: Push a new outermost 802.1Q or 802.1ad header * onto the packet. * @OVS_ACTION_ATTR_POP_VLAN: Pop the outermost 802.1Q or 802.1ad header * from the packet. * @OVS_ACTION_ATTR_SAMPLE: Probabilitically executes actions, as specified in * the nested %OVS_SAMPLE_ATTR_* attributes. * @OVS_ACTION_ATTR_PUSH_MPLS: Push a new MPLS label stack entry onto the * top of the packets MPLS label stack. Set the ethertype of the * encapsulating frame to either %ETH_P_MPLS_UC or %ETH_P_MPLS_MC to * indicate the new packet contents. * @OVS_ACTION_ATTR_POP_MPLS: Pop an MPLS label stack entry off of the * packet's MPLS label stack. Set the encapsulating frame's ethertype to * indicate the new packet contents. This could potentially still be * %ETH_P_MPLS if the resulting MPLS label stack is not empty. If there * is no MPLS label stack, as determined by ethertype, no action is taken. * @OVS_ACTION_ATTR_CT: Track the connection. Populate the conntrack-related * entries in the flow key. * @OVS_ACTION_ATTR_PUSH_ETH: Push a new outermost Ethernet header onto the * packet. * @OVS_ACTION_ATTR_POP_ETH: Pop the outermost Ethernet header off the * packet. * @OVS_ACTION_ATTR_CT_CLEAR: Clear conntrack state from the packet. * @OVS_ACTION_ATTR_PUSH_NSH: push NSH header to the packet. * @OVS_ACTION_ATTR_POP_NSH: pop the outermost NSH header off the packet. * @OVS_ACTION_ATTR_METER: Run packet through a meter, which may drop the * packet, or modify the packet (e.g., change the DSCP field). * @OVS_ACTION_ATTR_CLONE: make a copy of the packet and execute a list of * actions without affecting the original packet and key. * @OVS_ACTION_ATTR_CHECK_PKT_LEN: Check the packet length and execute a set * of actions if greater than the specified packet length, else execute * another set of actions. * @OVS_ACTION_ATTR_ADD_MPLS: Push a new MPLS label stack entry at the * start of the packet or at the start of the l3 header depending on the value * of l3 tunnel flag in the tun_flags field of OVS_ACTION_ATTR_ADD_MPLS * argument. * * Only a single header can be set with a single %OVS_ACTION_ATTR_SET. Not all * fields within a header are modifiable, e.g. the IPv4 protocol and fragment * type may not be changed. * * @OVS_ACTION_ATTR_SET_TO_MASKED: Kernel internal masked set action translated * from the @OVS_ACTION_ATTR_SET. */ enum ovs_action_attr { OVS_ACTION_ATTR_UNSPEC, OVS_ACTION_ATTR_OUTPUT, /* u32 port number. */ OVS_ACTION_ATTR_USERSPACE, /* Nested OVS_USERSPACE_ATTR_*. */ OVS_ACTION_ATTR_SET, /* One nested OVS_KEY_ATTR_*. */ OVS_ACTION_ATTR_PUSH_VLAN, /* struct ovs_action_push_vlan. */ OVS_ACTION_ATTR_POP_VLAN, /* No argument. */ OVS_ACTION_ATTR_SAMPLE, /* Nested OVS_SAMPLE_ATTR_*. */ OVS_ACTION_ATTR_RECIRC, /* u32 recirc_id. */ OVS_ACTION_ATTR_HASH, /* struct ovs_action_hash. */ OVS_ACTION_ATTR_PUSH_MPLS, /* struct ovs_action_push_mpls. */ OVS_ACTION_ATTR_POP_MPLS, /* __be16 ethertype. */ OVS_ACTION_ATTR_SET_MASKED, /* One nested OVS_KEY_ATTR_* including * data immediately followed by a mask. * The data must be zero for the unmasked * bits. */ OVS_ACTION_ATTR_CT, /* Nested OVS_CT_ATTR_* . */ OVS_ACTION_ATTR_TRUNC, /* u32 struct ovs_action_trunc. */ OVS_ACTION_ATTR_PUSH_ETH, /* struct ovs_action_push_eth. */ OVS_ACTION_ATTR_POP_ETH, /* No argument. */ OVS_ACTION_ATTR_CT_CLEAR, /* No argument. */ OVS_ACTION_ATTR_PUSH_NSH, /* Nested OVS_NSH_KEY_ATTR_*. */ OVS_ACTION_ATTR_POP_NSH, /* No argument. */ OVS_ACTION_ATTR_METER, /* u32 meter ID. */ OVS_ACTION_ATTR_CLONE, /* Nested OVS_CLONE_ATTR_*. */ OVS_ACTION_ATTR_CHECK_PKT_LEN, /* Nested OVS_CHECK_PKT_LEN_ATTR_*. */ OVS_ACTION_ATTR_ADD_MPLS, /* struct ovs_action_add_mpls. */ OVS_ACTION_ATTR_DEC_TTL, /* Nested OVS_DEC_TTL_ATTR_*. */ __OVS_ACTION_ATTR_MAX, /* Nothing past this will be accepted * from userspace. */ }; #define OVS_ACTION_ATTR_MAX (__OVS_ACTION_ATTR_MAX - 1) /* Meters. */ #define OVS_METER_FAMILY "ovs_meter" #define OVS_METER_MCGROUP "ovs_meter" #define OVS_METER_VERSION 0x1 enum ovs_meter_cmd { OVS_METER_CMD_UNSPEC, OVS_METER_CMD_FEATURES, /* Get features supported by the datapath. */ OVS_METER_CMD_SET, /* Add or modify a meter. */ OVS_METER_CMD_DEL, /* Delete a meter. */ OVS_METER_CMD_GET /* Get meter stats. */ }; enum ovs_meter_attr { OVS_METER_ATTR_UNSPEC, OVS_METER_ATTR_ID, /* u32 meter ID within datapath. */ OVS_METER_ATTR_KBPS, /* No argument. If set, units in kilobits * per second. Otherwise, units in * packets per second. */ OVS_METER_ATTR_STATS, /* struct ovs_flow_stats for the meter. */ OVS_METER_ATTR_BANDS, /* Nested attributes for meter bands. */ OVS_METER_ATTR_USED, /* u64 msecs last used in monotonic time. */ OVS_METER_ATTR_CLEAR, /* Flag to clear stats, used. */ OVS_METER_ATTR_MAX_METERS, /* u32 number of meters supported. */ OVS_METER_ATTR_MAX_BANDS, /* u32 max number of bands per meter. */ OVS_METER_ATTR_PAD, __OVS_METER_ATTR_MAX }; #define OVS_METER_ATTR_MAX (__OVS_METER_ATTR_MAX - 1) enum ovs_band_attr { OVS_BAND_ATTR_UNSPEC, OVS_BAND_ATTR_TYPE, /* u32 OVS_METER_BAND_TYPE_* constant. */ OVS_BAND_ATTR_RATE, /* u32 band rate in meter units (see above). */ OVS_BAND_ATTR_BURST, /* u32 burst size in meter units. */ OVS_BAND_ATTR_STATS, /* struct ovs_flow_stats for the band. */ __OVS_BAND_ATTR_MAX }; #define OVS_BAND_ATTR_MAX (__OVS_BAND_ATTR_MAX - 1) enum ovs_meter_band_type { OVS_METER_BAND_TYPE_UNSPEC, OVS_METER_BAND_TYPE_DROP, /* Drop exceeding packets. */ __OVS_METER_BAND_TYPE_MAX }; #define OVS_METER_BAND_TYPE_MAX (__OVS_METER_BAND_TYPE_MAX - 1) /* Conntrack limit */ #define OVS_CT_LIMIT_FAMILY "ovs_ct_limit" #define OVS_CT_LIMIT_MCGROUP "ovs_ct_limit" #define OVS_CT_LIMIT_VERSION 0x1 enum ovs_ct_limit_cmd { OVS_CT_LIMIT_CMD_UNSPEC, OVS_CT_LIMIT_CMD_SET, /* Add or modify ct limit. */ OVS_CT_LIMIT_CMD_DEL, /* Delete ct limit. */ OVS_CT_LIMIT_CMD_GET /* Get ct limit. */ }; enum ovs_ct_limit_attr { OVS_CT_LIMIT_ATTR_UNSPEC, OVS_CT_LIMIT_ATTR_ZONE_LIMIT, /* Nested struct ovs_zone_limit. */ __OVS_CT_LIMIT_ATTR_MAX }; #define OVS_CT_LIMIT_ATTR_MAX (__OVS_CT_LIMIT_ATTR_MAX - 1) #define OVS_ZONE_LIMIT_DEFAULT_ZONE -1 struct ovs_zone_limit { int zone_id; __u32 limit; __u32 count; }; enum ovs_dec_ttl_attr { OVS_DEC_TTL_ATTR_UNSPEC, OVS_DEC_TTL_ATTR_ACTION, /* Nested struct nlattr */ __OVS_DEC_TTL_ATTR_MAX }; #define OVS_DEC_TTL_ATTR_MAX (__OVS_DEC_TTL_ATTR_MAX - 1) #endif /* _LINUX_OPENVSWITCH_H */ linux/blkpg.h000064400000001610151027430560007154 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BLKPG_H #define __LINUX_BLKPG_H #include #define BLKPG _IO(0x12,105) /* The argument structure */ struct blkpg_ioctl_arg { int op; int flags; int datalen; void *data; }; /* The subfunctions (for the op field) */ #define BLKPG_ADD_PARTITION 1 #define BLKPG_DEL_PARTITION 2 #define BLKPG_RESIZE_PARTITION 3 /* Sizes of name fields. Unused at present. */ #define BLKPG_DEVNAMELTH 64 #define BLKPG_VOLNAMELTH 64 /* The data structure for ADD_PARTITION and DEL_PARTITION */ struct blkpg_partition { long long start; /* starting offset in bytes */ long long length; /* length in bytes */ int pno; /* partition number */ char devname[BLKPG_DEVNAMELTH]; /* unused / ignored */ char volname[BLKPG_VOLNAMELTH]; /* unused / ignore */ }; #endif /* __LINUX_BLKPG_H */ linux/if_fddi.h000064400000007244151027430560007452 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the ANSI FDDI interface. * * Version: @(#)if_fddi.h 1.0.2 Sep 29 2004 * * Author: Lawrence V. Stefani, * * if_fddi.h is based on previous if_ether.h and if_tr.h work by * Fred N. van Kempen, * Donald Becker, * Alan Cox, * Steve Whitehouse, * Peter De Schrijver, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_FDDI_H #define _LINUX_IF_FDDI_H #include /* * Define max and min legal sizes. The frame sizes do not include * 4 byte FCS/CRC (frame check sequence). */ #define FDDI_K_ALEN 6 /* Octets in one FDDI address */ #define FDDI_K_8022_HLEN 16 /* Total octets in 802.2 header */ #define FDDI_K_SNAP_HLEN 21 /* Total octets in 802.2 SNAP header */ #define FDDI_K_8022_ZLEN 16 /* Min octets in 802.2 frame sans FCS */ #define FDDI_K_SNAP_ZLEN 21 /* Min octets in 802.2 SNAP frame sans FCS */ #define FDDI_K_8022_DLEN 4475 /* Max octets in 802.2 payload */ #define FDDI_K_SNAP_DLEN 4470 /* Max octets in 802.2 SNAP payload */ #define FDDI_K_LLC_ZLEN 13 /* Min octets in LLC frame sans FCS */ #define FDDI_K_LLC_LEN 4491 /* Max octets in LLC frame sans FCS */ #define FDDI_K_OUI_LEN 3 /* Octets in OUI in 802.2 SNAP header */ /* Define FDDI Frame Control (FC) Byte values */ #define FDDI_FC_K_VOID 0x00 #define FDDI_FC_K_NON_RESTRICTED_TOKEN 0x80 #define FDDI_FC_K_RESTRICTED_TOKEN 0xC0 #define FDDI_FC_K_SMT_MIN 0x41 #define FDDI_FC_K_SMT_MAX 0x4F #define FDDI_FC_K_MAC_MIN 0xC1 #define FDDI_FC_K_MAC_MAX 0xCF #define FDDI_FC_K_ASYNC_LLC_MIN 0x50 #define FDDI_FC_K_ASYNC_LLC_DEF 0x54 #define FDDI_FC_K_ASYNC_LLC_MAX 0x5F #define FDDI_FC_K_SYNC_LLC_MIN 0xD0 #define FDDI_FC_K_SYNC_LLC_MAX 0xD7 #define FDDI_FC_K_IMPLEMENTOR_MIN 0x60 #define FDDI_FC_K_IMPLEMENTOR_MAX 0x6F #define FDDI_FC_K_RESERVED_MIN 0x70 #define FDDI_FC_K_RESERVED_MAX 0x7F /* Define LLC and SNAP constants */ #define FDDI_EXTENDED_SAP 0xAA #define FDDI_UI_CMD 0x03 /* Define 802.2 Type 1 header */ struct fddi_8022_1_hdr { __u8 dsap; /* destination service access point */ __u8 ssap; /* source service access point */ __u8 ctrl; /* control byte #1 */ } __attribute__((packed)); /* Define 802.2 Type 2 header */ struct fddi_8022_2_hdr { __u8 dsap; /* destination service access point */ __u8 ssap; /* source service access point */ __u8 ctrl_1; /* control byte #1 */ __u8 ctrl_2; /* control byte #2 */ } __attribute__((packed)); /* Define 802.2 SNAP header */ struct fddi_snap_hdr { __u8 dsap; /* always 0xAA */ __u8 ssap; /* always 0xAA */ __u8 ctrl; /* always 0x03 */ __u8 oui[FDDI_K_OUI_LEN]; /* organizational universal id */ __be16 ethertype; /* packet type ID field */ } __attribute__((packed)); /* Define FDDI LLC frame header */ struct fddihdr { __u8 fc; /* frame control */ __u8 daddr[FDDI_K_ALEN]; /* destination address */ __u8 saddr[FDDI_K_ALEN]; /* source address */ union { struct fddi_8022_1_hdr llc_8022_1; struct fddi_8022_2_hdr llc_8022_2; struct fddi_snap_hdr llc_snap; } hdr; } __attribute__((packed)); #endif /* _LINUX_IF_FDDI_H */ linux/fib_rules.h000064400000003764151027430560010043 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_FIB_RULES_H #define __LINUX_FIB_RULES_H #include #include /* rule is permanent, and cannot be deleted */ #define FIB_RULE_PERMANENT 0x00000001 #define FIB_RULE_INVERT 0x00000002 #define FIB_RULE_UNRESOLVED 0x00000004 #define FIB_RULE_IIF_DETACHED 0x00000008 #define FIB_RULE_DEV_DETACHED FIB_RULE_IIF_DETACHED #define FIB_RULE_OIF_DETACHED 0x00000010 /* try to find source address in routing lookups */ #define FIB_RULE_FIND_SADDR 0x00010000 struct fib_rule_hdr { __u8 family; __u8 dst_len; __u8 src_len; __u8 tos; __u8 table; __u8 res1; /* reserved */ __u8 res2; /* reserved */ __u8 action; __u32 flags; }; struct fib_rule_uid_range { __u32 start; __u32 end; }; struct fib_rule_port_range { __u16 start; __u16 end; }; enum { FRA_UNSPEC, FRA_DST, /* destination address */ FRA_SRC, /* source address */ FRA_IIFNAME, /* interface name */ #define FRA_IFNAME FRA_IIFNAME FRA_GOTO, /* target to jump to (FR_ACT_GOTO) */ FRA_UNUSED2, FRA_PRIORITY, /* priority/preference */ FRA_UNUSED3, FRA_UNUSED4, FRA_UNUSED5, FRA_FWMARK, /* mark */ FRA_FLOW, /* flow/class id */ FRA_TUN_ID, FRA_SUPPRESS_IFGROUP, FRA_SUPPRESS_PREFIXLEN, FRA_TABLE, /* Extended table id */ FRA_FWMASK, /* mask for netfilter mark */ FRA_OIFNAME, FRA_PAD, FRA_L3MDEV, /* iif or oif is l3mdev goto its table */ FRA_UID_RANGE, /* UID range */ FRA_PROTOCOL, /* Originator of the rule */ FRA_IP_PROTO, /* ip proto */ FRA_SPORT_RANGE, /* sport */ FRA_DPORT_RANGE, /* dport */ __FRA_MAX }; #define FRA_MAX (__FRA_MAX - 1) enum { FR_ACT_UNSPEC, FR_ACT_TO_TBL, /* Pass to fixed table */ FR_ACT_GOTO, /* Jump to another rule */ FR_ACT_NOP, /* No operation */ FR_ACT_RES3, FR_ACT_RES4, FR_ACT_BLACKHOLE, /* Drop without notification */ FR_ACT_UNREACHABLE, /* Drop with ENETUNREACH */ FR_ACT_PROHIBIT, /* Drop with EACCES */ __FR_ACT_MAX, }; #define FR_ACT_MAX (__FR_ACT_MAX - 1) #endif linux/if_phonet.h000064400000000650151027430560010033 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * File: if_phonet.h * * Phonet interface kernel definitions * * Copyright (C) 2008 Nokia Corporation. All rights reserved. */ #ifndef LINUX_IF_PHONET_H #define LINUX_IF_PHONET_H #define PHONET_MIN_MTU 6 /* pn_length = 0 */ #define PHONET_MAX_MTU 65541 /* pn_length = 0xffff */ #define PHONET_DEV_MTU PHONET_MAX_MTU #endif /* LINUX_IF_PHONET_H */ linux/hdlc.h000064400000001175151027430560006775 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Generic HDLC support routines for Linux * * Copyright (C) 1999-2005 Krzysztof Halasa * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. */ #ifndef __HDLC_H #define __HDLC_H #define HDLC_MAX_MTU 1500 /* Ethernet 1500 bytes */ #if 0 #define HDLC_MAX_MRU (HDLC_MAX_MTU + 10 + 14 + 4) /* for ETH+VLAN over FR */ #else #define HDLC_MAX_MRU 1600 /* as required for FR network */ #endif #endif /* __HDLC_H */ linux/sync_file.h000064400000005503151027430560010035 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * Copyright (C) 2012 Google, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef _LINUX_SYNC_H #define _LINUX_SYNC_H #include #include /** * struct sync_merge_data - data passed to merge ioctl * @name: name of new fence * @fd2: file descriptor of second fence * @fence: returns the fd of the new fence to userspace * @flags: merge_data flags * @pad: padding for 64-bit alignment, should always be zero */ struct sync_merge_data { char name[32]; __s32 fd2; __s32 fence; __u32 flags; __u32 pad; }; /** * struct sync_fence_info - detailed fence information * @obj_name: name of parent sync_timeline * @driver_name: name of driver implementing the parent * @status: status of the fence 0:active 1:signaled <0:error * @flags: fence_info flags * @timestamp_ns: timestamp of status change in nanoseconds */ struct sync_fence_info { char obj_name[32]; char driver_name[32]; __s32 status; __u32 flags; __u64 timestamp_ns; }; /** * struct sync_file_info - data returned from fence info ioctl * @name: name of fence * @status: status of fence. 1: signaled 0:active <0:error * @flags: sync_file_info flags * @num_fences number of fences in the sync_file * @pad: padding for 64-bit alignment, should always be zero * @sync_fence_info: pointer to array of structs sync_fence_info with all * fences in the sync_file */ struct sync_file_info { char name[32]; __s32 status; __u32 flags; __u32 num_fences; __u32 pad; __u64 sync_fence_info; }; #define SYNC_IOC_MAGIC '>' /** * Opcodes 0, 1 and 2 were burned during a API change to avoid users of the * old API to get weird errors when trying to handling sync_files. The API * change happened during the de-stage of the Sync Framework when there was * no upstream users available. */ /** * DOC: SYNC_IOC_MERGE - merge two fences * * Takes a struct sync_merge_data. Creates a new fence containing copies of * the sync_pts in both the calling fd and sync_merge_data.fd2. Returns the * new fence's fd in sync_merge_data.fence */ #define SYNC_IOC_MERGE _IOWR(SYNC_IOC_MAGIC, 3, struct sync_merge_data) /** * DOC: SYNC_IOC_FILE_INFO - get detailed information on a sync_file * * Takes a struct sync_file_info. If num_fences is 0, the field is updated * with the actual number of fences. If num_fences is > 0, the system will * use the pointer provided on sync_fence_info to return up to num_fences of * struct sync_fence_info, with detailed fence information. */ #define SYNC_IOC_FILE_INFO _IOWR(SYNC_IOC_MAGIC, 4, struct sync_file_info) #endif /* _LINUX_SYNC_H */ linux/virtio_ids.h000064400000006305151027430560010236 0ustar00#ifndef _LINUX_VIRTIO_IDS_H #define _LINUX_VIRTIO_IDS_H /* * Virtio IDs * * This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #define VIRTIO_ID_NET 1 /* virtio net */ #define VIRTIO_ID_BLOCK 2 /* virtio block */ #define VIRTIO_ID_CONSOLE 3 /* virtio console */ #define VIRTIO_ID_RNG 4 /* virtio rng */ #define VIRTIO_ID_BALLOON 5 /* virtio balloon */ #define VIRTIO_ID_RPMSG 7 /* virtio remote processor messaging */ #define VIRTIO_ID_SCSI 8 /* virtio scsi */ #define VIRTIO_ID_9P 9 /* 9p virtio console */ #define VIRTIO_ID_RPROC_SERIAL 11 /* virtio remoteproc serial link */ #define VIRTIO_ID_CAIF 12 /* Virtio caif */ #define VIRTIO_ID_GPU 16 /* virtio GPU */ #define VIRTIO_ID_INPUT 18 /* virtio input */ #define VIRTIO_ID_VSOCK 19 /* virtio vsock transport */ #define VIRTIO_ID_CRYPTO 20 /* virtio crypto */ #define VIRTIO_ID_IOMMU 23 /* virtio IOMMU */ #define VIRTIO_ID_MEM 24 /* virtio mem */ #define VIRTIO_ID_SOUND 25 /* virtio sound */ #define VIRTIO_ID_FS 26 /* virtio filesystem */ #define VIRTIO_ID_MAC80211_HWSIM 29 /* virtio mac80211-hwsim */ #define VIRTIO_ID_BT 40 /* virtio bluetooth */ /* * Virtio Transitional IDs */ #define VIRTIO_TRANS_ID_NET 1000 /* transitional virtio net */ #define VIRTIO_TRANS_ID_BLOCK 1001 /* transitional virtio block */ #define VIRTIO_TRANS_ID_BALLOON 1002 /* transitional virtio balloon */ #define VIRTIO_TRANS_ID_CONSOLE 1003 /* transitional virtio console */ #define VIRTIO_TRANS_ID_SCSI 1004 /* transitional virtio SCSI */ #define VIRTIO_TRANS_ID_RNG 1005 /* transitional virtio rng */ #define VIRTIO_TRANS_ID_9P 1009 /* transitional virtio 9p console */ #endif /* _LINUX_VIRTIO_IDS_H */ linux/hdreg.h000064400000054257151027430560007165 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_HDREG_H #define _LINUX_HDREG_H #include /* * Command Header sizes for IOCTL commands */ #define HDIO_DRIVE_CMD_HDR_SIZE (4 * sizeof(__u8)) #define HDIO_DRIVE_HOB_HDR_SIZE (8 * sizeof(__u8)) #define HDIO_DRIVE_TASK_HDR_SIZE (8 * sizeof(__u8)) #define IDE_DRIVE_TASK_NO_DATA 0 #define IDE_DRIVE_TASK_INVALID -1 #define IDE_DRIVE_TASK_SET_XFER 1 #define IDE_DRIVE_TASK_IN 2 #define IDE_DRIVE_TASK_OUT 3 #define IDE_DRIVE_TASK_RAW_WRITE 4 /* * Define standard taskfile in/out register */ #define IDE_TASKFILE_STD_IN_FLAGS 0xFE #define IDE_HOB_STD_IN_FLAGS 0x3C #define IDE_TASKFILE_STD_OUT_FLAGS 0xFE #define IDE_HOB_STD_OUT_FLAGS 0x3C typedef unsigned char task_ioreg_t; typedef unsigned long sata_ioreg_t; typedef union ide_reg_valid_s { unsigned all : 16; struct { unsigned data : 1; unsigned error_feature : 1; unsigned sector : 1; unsigned nsector : 1; unsigned lcyl : 1; unsigned hcyl : 1; unsigned select : 1; unsigned status_command : 1; unsigned data_hob : 1; unsigned error_feature_hob : 1; unsigned sector_hob : 1; unsigned nsector_hob : 1; unsigned lcyl_hob : 1; unsigned hcyl_hob : 1; unsigned select_hob : 1; unsigned control_hob : 1; } b; } ide_reg_valid_t; typedef struct ide_task_request_s { __u8 io_ports[8]; __u8 hob_ports[8]; /* bytes 6 and 7 are unused */ ide_reg_valid_t out_flags; ide_reg_valid_t in_flags; int data_phase; int req_cmd; unsigned long out_size; unsigned long in_size; } ide_task_request_t; typedef struct ide_ioctl_request_s { ide_task_request_t *task_request; unsigned char *out_buffer; unsigned char *in_buffer; } ide_ioctl_request_t; struct hd_drive_cmd_hdr { __u8 command; __u8 sector_number; __u8 feature; __u8 sector_count; }; typedef struct hd_drive_task_hdr { __u8 data; __u8 feature; __u8 sector_count; __u8 sector_number; __u8 low_cylinder; __u8 high_cylinder; __u8 device_head; __u8 command; } task_struct_t; typedef struct hd_drive_hob_hdr { __u8 data; __u8 feature; __u8 sector_count; __u8 sector_number; __u8 low_cylinder; __u8 high_cylinder; __u8 device_head; __u8 control; } hob_struct_t; #define TASKFILE_NO_DATA 0x0000 #define TASKFILE_IN 0x0001 #define TASKFILE_MULTI_IN 0x0002 #define TASKFILE_OUT 0x0004 #define TASKFILE_MULTI_OUT 0x0008 #define TASKFILE_IN_OUT 0x0010 #define TASKFILE_IN_DMA 0x0020 #define TASKFILE_OUT_DMA 0x0040 #define TASKFILE_IN_DMAQ 0x0080 #define TASKFILE_OUT_DMAQ 0x0100 #define TASKFILE_P_IN 0x0200 #define TASKFILE_P_OUT 0x0400 #define TASKFILE_P_IN_DMA 0x0800 #define TASKFILE_P_OUT_DMA 0x1000 #define TASKFILE_P_IN_DMAQ 0x2000 #define TASKFILE_P_OUT_DMAQ 0x4000 #define TASKFILE_48 0x8000 #define TASKFILE_INVALID 0x7fff /* ATA/ATAPI Commands pre T13 Spec */ #define WIN_NOP 0x00 /* * 0x01->0x02 Reserved */ #define CFA_REQ_EXT_ERROR_CODE 0x03 /* CFA Request Extended Error Code */ /* * 0x04->0x07 Reserved */ #define WIN_SRST 0x08 /* ATAPI soft reset command */ #define WIN_DEVICE_RESET 0x08 /* * 0x09->0x0F Reserved */ #define WIN_RECAL 0x10 #define WIN_RESTORE WIN_RECAL /* * 0x10->0x1F Reserved */ #define WIN_READ 0x20 /* 28-Bit */ #define WIN_READ_ONCE 0x21 /* 28-Bit without retries */ #define WIN_READ_LONG 0x22 /* 28-Bit */ #define WIN_READ_LONG_ONCE 0x23 /* 28-Bit without retries */ #define WIN_READ_EXT 0x24 /* 48-Bit */ #define WIN_READDMA_EXT 0x25 /* 48-Bit */ #define WIN_READDMA_QUEUED_EXT 0x26 /* 48-Bit */ #define WIN_READ_NATIVE_MAX_EXT 0x27 /* 48-Bit */ /* * 0x28 */ #define WIN_MULTREAD_EXT 0x29 /* 48-Bit */ /* * 0x2A->0x2F Reserved */ #define WIN_WRITE 0x30 /* 28-Bit */ #define WIN_WRITE_ONCE 0x31 /* 28-Bit without retries */ #define WIN_WRITE_LONG 0x32 /* 28-Bit */ #define WIN_WRITE_LONG_ONCE 0x33 /* 28-Bit without retries */ #define WIN_WRITE_EXT 0x34 /* 48-Bit */ #define WIN_WRITEDMA_EXT 0x35 /* 48-Bit */ #define WIN_WRITEDMA_QUEUED_EXT 0x36 /* 48-Bit */ #define WIN_SET_MAX_EXT 0x37 /* 48-Bit */ #define CFA_WRITE_SECT_WO_ERASE 0x38 /* CFA Write Sectors without erase */ #define WIN_MULTWRITE_EXT 0x39 /* 48-Bit */ /* * 0x3A->0x3B Reserved */ #define WIN_WRITE_VERIFY 0x3C /* 28-Bit */ /* * 0x3D->0x3F Reserved */ #define WIN_VERIFY 0x40 /* 28-Bit - Read Verify Sectors */ #define WIN_VERIFY_ONCE 0x41 /* 28-Bit - without retries */ #define WIN_VERIFY_EXT 0x42 /* 48-Bit */ /* * 0x43->0x4F Reserved */ #define WIN_FORMAT 0x50 /* * 0x51->0x5F Reserved */ #define WIN_INIT 0x60 /* * 0x61->0x5F Reserved */ #define WIN_SEEK 0x70 /* 0x70-0x7F Reserved */ #define CFA_TRANSLATE_SECTOR 0x87 /* CFA Translate Sector */ #define WIN_DIAGNOSE 0x90 #define WIN_SPECIFY 0x91 /* set drive geometry translation */ #define WIN_DOWNLOAD_MICROCODE 0x92 #define WIN_STANDBYNOW2 0x94 #define WIN_STANDBY2 0x96 #define WIN_SETIDLE2 0x97 #define WIN_CHECKPOWERMODE2 0x98 #define WIN_SLEEPNOW2 0x99 /* * 0x9A VENDOR */ #define WIN_PACKETCMD 0xA0 /* Send a packet command. */ #define WIN_PIDENTIFY 0xA1 /* identify ATAPI device */ #define WIN_QUEUED_SERVICE 0xA2 #define WIN_SMART 0xB0 /* self-monitoring and reporting */ #define CFA_ERASE_SECTORS 0xC0 #define WIN_MULTREAD 0xC4 /* read sectors using multiple mode*/ #define WIN_MULTWRITE 0xC5 /* write sectors using multiple mode */ #define WIN_SETMULT 0xC6 /* enable/disable multiple mode */ #define WIN_READDMA_QUEUED 0xC7 /* read sectors using Queued DMA transfers */ #define WIN_READDMA 0xC8 /* read sectors using DMA transfers */ #define WIN_READDMA_ONCE 0xC9 /* 28-Bit - without retries */ #define WIN_WRITEDMA 0xCA /* write sectors using DMA transfers */ #define WIN_WRITEDMA_ONCE 0xCB /* 28-Bit - without retries */ #define WIN_WRITEDMA_QUEUED 0xCC /* write sectors using Queued DMA transfers */ #define CFA_WRITE_MULTI_WO_ERASE 0xCD /* CFA Write multiple without erase */ #define WIN_GETMEDIASTATUS 0xDA #define WIN_ACKMEDIACHANGE 0xDB /* ATA-1, ATA-2 vendor */ #define WIN_POSTBOOT 0xDC #define WIN_PREBOOT 0xDD #define WIN_DOORLOCK 0xDE /* lock door on removable drives */ #define WIN_DOORUNLOCK 0xDF /* unlock door on removable drives */ #define WIN_STANDBYNOW1 0xE0 #define WIN_IDLEIMMEDIATE 0xE1 /* force drive to become "ready" */ #define WIN_STANDBY 0xE2 /* Set device in Standby Mode */ #define WIN_SETIDLE1 0xE3 #define WIN_READ_BUFFER 0xE4 /* force read only 1 sector */ #define WIN_CHECKPOWERMODE1 0xE5 #define WIN_SLEEPNOW1 0xE6 #define WIN_FLUSH_CACHE 0xE7 #define WIN_WRITE_BUFFER 0xE8 /* force write only 1 sector */ #define WIN_WRITE_SAME 0xE9 /* read ata-2 to use */ /* SET_FEATURES 0x22 or 0xDD */ #define WIN_FLUSH_CACHE_EXT 0xEA /* 48-Bit */ #define WIN_IDENTIFY 0xEC /* ask drive to identify itself */ #define WIN_MEDIAEJECT 0xED #define WIN_IDENTIFY_DMA 0xEE /* same as WIN_IDENTIFY, but DMA */ #define WIN_SETFEATURES 0xEF /* set special drive features */ #define EXABYTE_ENABLE_NEST 0xF0 #define WIN_SECURITY_SET_PASS 0xF1 #define WIN_SECURITY_UNLOCK 0xF2 #define WIN_SECURITY_ERASE_PREPARE 0xF3 #define WIN_SECURITY_ERASE_UNIT 0xF4 #define WIN_SECURITY_FREEZE_LOCK 0xF5 #define WIN_SECURITY_DISABLE 0xF6 #define WIN_READ_NATIVE_MAX 0xF8 /* return the native maximum address */ #define WIN_SET_MAX 0xF9 #define DISABLE_SEAGATE 0xFB /* WIN_SMART sub-commands */ #define SMART_READ_VALUES 0xD0 #define SMART_READ_THRESHOLDS 0xD1 #define SMART_AUTOSAVE 0xD2 #define SMART_SAVE 0xD3 #define SMART_IMMEDIATE_OFFLINE 0xD4 #define SMART_READ_LOG_SECTOR 0xD5 #define SMART_WRITE_LOG_SECTOR 0xD6 #define SMART_WRITE_THRESHOLDS 0xD7 #define SMART_ENABLE 0xD8 #define SMART_DISABLE 0xD9 #define SMART_STATUS 0xDA #define SMART_AUTO_OFFLINE 0xDB /* Password used in TF4 & TF5 executing SMART commands */ #define SMART_LCYL_PASS 0x4F #define SMART_HCYL_PASS 0xC2 /* WIN_SETFEATURES sub-commands */ #define SETFEATURES_EN_8BIT 0x01 /* Enable 8-Bit Transfers */ #define SETFEATURES_EN_WCACHE 0x02 /* Enable write cache */ #define SETFEATURES_DIS_DEFECT 0x04 /* Disable Defect Management */ #define SETFEATURES_EN_APM 0x05 /* Enable advanced power management */ #define SETFEATURES_EN_SAME_R 0x22 /* for a region ATA-1 */ #define SETFEATURES_DIS_MSN 0x31 /* Disable Media Status Notification */ #define SETFEATURES_DIS_RETRY 0x33 /* Disable Retry */ #define SETFEATURES_EN_AAM 0x42 /* Enable Automatic Acoustic Management */ #define SETFEATURES_RW_LONG 0x44 /* Set Length of VS bytes */ #define SETFEATURES_SET_CACHE 0x54 /* Set Cache segments to SC Reg. Val */ #define SETFEATURES_DIS_RLA 0x55 /* Disable read look-ahead feature */ #define SETFEATURES_EN_RI 0x5D /* Enable release interrupt */ #define SETFEATURES_EN_SI 0x5E /* Enable SERVICE interrupt */ #define SETFEATURES_DIS_RPOD 0x66 /* Disable reverting to power on defaults */ #define SETFEATURES_DIS_ECC 0x77 /* Disable ECC byte count */ #define SETFEATURES_DIS_8BIT 0x81 /* Disable 8-Bit Transfers */ #define SETFEATURES_DIS_WCACHE 0x82 /* Disable write cache */ #define SETFEATURES_EN_DEFECT 0x84 /* Enable Defect Management */ #define SETFEATURES_DIS_APM 0x85 /* Disable advanced power management */ #define SETFEATURES_EN_ECC 0x88 /* Enable ECC byte count */ #define SETFEATURES_EN_MSN 0x95 /* Enable Media Status Notification */ #define SETFEATURES_EN_RETRY 0x99 /* Enable Retry */ #define SETFEATURES_EN_RLA 0xAA /* Enable read look-ahead feature */ #define SETFEATURES_PREFETCH 0xAB /* Sets drive prefetch value */ #define SETFEATURES_EN_REST 0xAC /* ATA-1 */ #define SETFEATURES_4B_RW_LONG 0xBB /* Set Length of 4 bytes */ #define SETFEATURES_DIS_AAM 0xC2 /* Disable Automatic Acoustic Management */ #define SETFEATURES_EN_RPOD 0xCC /* Enable reverting to power on defaults */ #define SETFEATURES_DIS_RI 0xDD /* Disable release interrupt ATAPI */ #define SETFEATURES_EN_SAME_M 0xDD /* for a entire device ATA-1 */ #define SETFEATURES_DIS_SI 0xDE /* Disable SERVICE interrupt ATAPI */ /* WIN_SECURITY sub-commands */ #define SECURITY_SET_PASSWORD 0xBA #define SECURITY_UNLOCK 0xBB #define SECURITY_ERASE_PREPARE 0xBC #define SECURITY_ERASE_UNIT 0xBD #define SECURITY_FREEZE_LOCK 0xBE #define SECURITY_DISABLE_PASSWORD 0xBF struct hd_geometry { unsigned char heads; unsigned char sectors; unsigned short cylinders; unsigned long start; }; /* hd/ide ctl's that pass (arg) ptrs to user space are numbered 0x030n/0x031n */ #define HDIO_GETGEO 0x0301 /* get device geometry */ #define HDIO_GET_UNMASKINTR 0x0302 /* get current unmask setting */ #define HDIO_GET_MULTCOUNT 0x0304 /* get current IDE blockmode setting */ #define HDIO_GET_QDMA 0x0305 /* get use-qdma flag */ #define HDIO_SET_XFER 0x0306 /* set transfer rate via proc */ #define HDIO_OBSOLETE_IDENTITY 0x0307 /* OBSOLETE, DO NOT USE: returns 142 bytes */ #define HDIO_GET_KEEPSETTINGS 0x0308 /* get keep-settings-on-reset flag */ #define HDIO_GET_32BIT 0x0309 /* get current io_32bit setting */ #define HDIO_GET_NOWERR 0x030a /* get ignore-write-error flag */ #define HDIO_GET_DMA 0x030b /* get use-dma flag */ #define HDIO_GET_NICE 0x030c /* get nice flags */ #define HDIO_GET_IDENTITY 0x030d /* get IDE identification info */ #define HDIO_GET_WCACHE 0x030e /* get write cache mode on|off */ #define HDIO_GET_ACOUSTIC 0x030f /* get acoustic value */ #define HDIO_GET_ADDRESS 0x0310 /* */ #define HDIO_GET_BUSSTATE 0x031a /* get the bus state of the hwif */ #define HDIO_TRISTATE_HWIF 0x031b /* execute a channel tristate */ #define HDIO_DRIVE_RESET 0x031c /* execute a device reset */ #define HDIO_DRIVE_TASKFILE 0x031d /* execute raw taskfile */ #define HDIO_DRIVE_TASK 0x031e /* execute task and special drive command */ #define HDIO_DRIVE_CMD 0x031f /* execute a special drive command */ #define HDIO_DRIVE_CMD_AEB HDIO_DRIVE_TASK /* hd/ide ctl's that pass (arg) non-ptr values are numbered 0x032n/0x033n */ #define HDIO_SET_MULTCOUNT 0x0321 /* change IDE blockmode */ #define HDIO_SET_UNMASKINTR 0x0322 /* permit other irqs during I/O */ #define HDIO_SET_KEEPSETTINGS 0x0323 /* keep ioctl settings on reset */ #define HDIO_SET_32BIT 0x0324 /* change io_32bit flags */ #define HDIO_SET_NOWERR 0x0325 /* change ignore-write-error flag */ #define HDIO_SET_DMA 0x0326 /* change use-dma flag */ #define HDIO_SET_PIO_MODE 0x0327 /* reconfig interface to new speed */ #define HDIO_SCAN_HWIF 0x0328 /* register and (re)scan interface */ #define HDIO_UNREGISTER_HWIF 0x032a /* unregister interface */ #define HDIO_SET_NICE 0x0329 /* set nice flags */ #define HDIO_SET_WCACHE 0x032b /* change write cache enable-disable */ #define HDIO_SET_ACOUSTIC 0x032c /* change acoustic behavior */ #define HDIO_SET_BUSSTATE 0x032d /* set the bus state of the hwif */ #define HDIO_SET_QDMA 0x032e /* change use-qdma flag */ #define HDIO_SET_ADDRESS 0x032f /* change lba addressing modes */ /* bus states */ enum { BUSSTATE_OFF = 0, BUSSTATE_ON, BUSSTATE_TRISTATE }; /* hd/ide ctl's that pass (arg) ptrs to user space are numbered 0x033n/0x033n */ /* 0x330 is reserved - used to be HDIO_GETGEO_BIG */ /* 0x331 is reserved - used to be HDIO_GETGEO_BIG_RAW */ /* 0x338 is reserved - used to be HDIO_SET_IDE_SCSI */ /* 0x339 is reserved - used to be HDIO_SET_SCSI_IDE */ #define __NEW_HD_DRIVE_ID /* * Structure returned by HDIO_GET_IDENTITY, as per ANSI NCITS ATA6 rev.1b spec. * * If you change something here, please remember to update fix_driveid() in * ide/probe.c. */ struct hd_driveid { unsigned short config; /* lots of obsolete bit flags */ unsigned short cyls; /* Obsolete, "physical" cyls */ unsigned short reserved2; /* reserved (word 2) */ unsigned short heads; /* Obsolete, "physical" heads */ unsigned short track_bytes; /* unformatted bytes per track */ unsigned short sector_bytes; /* unformatted bytes per sector */ unsigned short sectors; /* Obsolete, "physical" sectors per track */ unsigned short vendor0; /* vendor unique */ unsigned short vendor1; /* vendor unique */ unsigned short vendor2; /* Retired vendor unique */ unsigned char serial_no[20]; /* 0 = not_specified */ unsigned short buf_type; /* Retired */ unsigned short buf_size; /* Retired, 512 byte increments * 0 = not_specified */ unsigned short ecc_bytes; /* for r/w long cmds; 0 = not_specified */ unsigned char fw_rev[8]; /* 0 = not_specified */ unsigned char model[40]; /* 0 = not_specified */ unsigned char max_multsect; /* 0=not_implemented */ unsigned char vendor3; /* vendor unique */ unsigned short dword_io; /* 0=not_implemented; 1=implemented */ unsigned char vendor4; /* vendor unique */ unsigned char capability; /* (upper byte of word 49) * 3: IORDYsup * 2: IORDYsw * 1: LBA * 0: DMA */ unsigned short reserved50; /* reserved (word 50) */ unsigned char vendor5; /* Obsolete, vendor unique */ unsigned char tPIO; /* Obsolete, 0=slow, 1=medium, 2=fast */ unsigned char vendor6; /* Obsolete, vendor unique */ unsigned char tDMA; /* Obsolete, 0=slow, 1=medium, 2=fast */ unsigned short field_valid; /* (word 53) * 2: ultra_ok word 88 * 1: eide_ok words 64-70 * 0: cur_ok words 54-58 */ unsigned short cur_cyls; /* Obsolete, logical cylinders */ unsigned short cur_heads; /* Obsolete, l heads */ unsigned short cur_sectors; /* Obsolete, l sectors per track */ unsigned short cur_capacity0; /* Obsolete, l total sectors on drive */ unsigned short cur_capacity1; /* Obsolete, (2 words, misaligned int) */ unsigned char multsect; /* current multiple sector count */ unsigned char multsect_valid; /* when (bit0==1) multsect is ok */ unsigned int lba_capacity; /* Obsolete, total number of sectors */ unsigned short dma_1word; /* Obsolete, single-word dma info */ unsigned short dma_mword; /* multiple-word dma info */ unsigned short eide_pio_modes; /* bits 0:mode3 1:mode4 */ unsigned short eide_dma_min; /* min mword dma cycle time (ns) */ unsigned short eide_dma_time; /* recommended mword dma cycle time (ns) */ unsigned short eide_pio; /* min cycle time (ns), no IORDY */ unsigned short eide_pio_iordy; /* min cycle time (ns), with IORDY */ unsigned short words69_70[2]; /* reserved words 69-70 * future command overlap and queuing */ unsigned short words71_74[4]; /* reserved words 71-74 * for IDENTIFY PACKET DEVICE command */ unsigned short queue_depth; /* (word 75) * 15:5 reserved * 4:0 Maximum queue depth -1 */ unsigned short words76_79[4]; /* reserved words 76-79 */ unsigned short major_rev_num; /* (word 80) */ unsigned short minor_rev_num; /* (word 81) */ unsigned short command_set_1; /* (word 82) supported * 15: Obsolete * 14: NOP command * 13: READ_BUFFER * 12: WRITE_BUFFER * 11: Obsolete * 10: Host Protected Area * 9: DEVICE Reset * 8: SERVICE Interrupt * 7: Release Interrupt * 6: look-ahead * 5: write cache * 4: PACKET Command * 3: Power Management Feature Set * 2: Removable Feature Set * 1: Security Feature Set * 0: SMART Feature Set */ unsigned short command_set_2; /* (word 83) * 15: Shall be ZERO * 14: Shall be ONE * 13: FLUSH CACHE EXT * 12: FLUSH CACHE * 11: Device Configuration Overlay * 10: 48-bit Address Feature Set * 9: Automatic Acoustic Management * 8: SET MAX security * 7: reserved 1407DT PARTIES * 6: SetF sub-command Power-Up * 5: Power-Up in Standby Feature Set * 4: Removable Media Notification * 3: APM Feature Set * 2: CFA Feature Set * 1: READ/WRITE DMA QUEUED * 0: Download MicroCode */ unsigned short cfsse; /* (word 84) * cmd set-feature supported extensions * 15: Shall be ZERO * 14: Shall be ONE * 13:6 reserved * 5: General Purpose Logging * 4: Streaming Feature Set * 3: Media Card Pass Through * 2: Media Serial Number Valid * 1: SMART selt-test supported * 0: SMART error logging */ unsigned short cfs_enable_1; /* (word 85) * command set-feature enabled * 15: Obsolete * 14: NOP command * 13: READ_BUFFER * 12: WRITE_BUFFER * 11: Obsolete * 10: Host Protected Area * 9: DEVICE Reset * 8: SERVICE Interrupt * 7: Release Interrupt * 6: look-ahead * 5: write cache * 4: PACKET Command * 3: Power Management Feature Set * 2: Removable Feature Set * 1: Security Feature Set * 0: SMART Feature Set */ unsigned short cfs_enable_2; /* (word 86) * command set-feature enabled * 15: Shall be ZERO * 14: Shall be ONE * 13: FLUSH CACHE EXT * 12: FLUSH CACHE * 11: Device Configuration Overlay * 10: 48-bit Address Feature Set * 9: Automatic Acoustic Management * 8: SET MAX security * 7: reserved 1407DT PARTIES * 6: SetF sub-command Power-Up * 5: Power-Up in Standby Feature Set * 4: Removable Media Notification * 3: APM Feature Set * 2: CFA Feature Set * 1: READ/WRITE DMA QUEUED * 0: Download MicroCode */ unsigned short csf_default; /* (word 87) * command set-feature default * 15: Shall be ZERO * 14: Shall be ONE * 13:6 reserved * 5: General Purpose Logging enabled * 4: Valid CONFIGURE STREAM executed * 3: Media Card Pass Through enabled * 2: Media Serial Number Valid * 1: SMART selt-test supported * 0: SMART error logging */ unsigned short dma_ultra; /* (word 88) */ unsigned short trseuc; /* time required for security erase */ unsigned short trsEuc; /* time required for enhanced erase */ unsigned short CurAPMvalues; /* current APM values */ unsigned short mprc; /* master password revision code */ unsigned short hw_config; /* hardware config (word 93) * 15: Shall be ZERO * 14: Shall be ONE * 13: * 12: * 11: * 10: * 9: * 8: * 7: * 6: * 5: * 4: * 3: * 2: * 1: * 0: Shall be ONE */ unsigned short acoustic; /* (word 94) * 15:8 Vendor's recommended value * 7:0 current value */ unsigned short msrqs; /* min stream request size */ unsigned short sxfert; /* stream transfer time */ unsigned short sal; /* stream access latency */ unsigned int spg; /* stream performance granularity */ unsigned long long lba_capacity_2;/* 48-bit total number of sectors */ unsigned short words104_125[22];/* reserved words 104-125 */ unsigned short last_lun; /* (word 126) */ unsigned short word127; /* (word 127) Feature Set * Removable Media Notification * 15:2 reserved * 1:0 00 = not supported * 01 = supported * 10 = reserved * 11 = reserved */ unsigned short dlf; /* (word 128) * device lock function * 15:9 reserved * 8 security level 1:max 0:high * 7:6 reserved * 5 enhanced erase * 4 expire * 3 frozen * 2 locked * 1 en/disabled * 0 capability */ unsigned short csfo; /* (word 129) * current set features options * 15:4 reserved * 3: auto reassign * 2: reverting * 1: read-look-ahead * 0: write cache */ unsigned short words130_155[26];/* reserved vendor words 130-155 */ unsigned short word156; /* reserved vendor word 156 */ unsigned short words157_159[3];/* reserved vendor words 157-159 */ unsigned short cfa_power; /* (word 160) CFA Power Mode * 15 word 160 supported * 14 reserved * 13 * 12 * 11:0 */ unsigned short words161_175[15];/* Reserved for CFA */ unsigned short words176_205[30];/* Current Media Serial Number */ unsigned short words206_254[49];/* reserved words 206-254 */ unsigned short integrity_word; /* (word 255) * 15:8 Checksum * 7:0 Signature */ }; /* * IDE "nice" flags. These are used on a per drive basis to determine * when to be nice and give more bandwidth to the other devices which * share the same IDE bus. */ #define IDE_NICE_DSC_OVERLAP (0) /* per the DSC overlap protocol */ #define IDE_NICE_ATAPI_OVERLAP (1) /* not supported yet */ #define IDE_NICE_1 (3) /* when probably won't affect us much */ #define IDE_NICE_0 (2) /* when sure that it won't affect us */ #define IDE_NICE_2 (4) /* when we know it's on our expense */ #endif /* _LINUX_HDREG_H */ linux/netfilter/xt_comment.h000064400000000346151027430560012233 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_COMMENT_H #define _XT_COMMENT_H #define XT_MAX_COMMENT_LEN 256 struct xt_comment_info { char comment[XT_MAX_COMMENT_LEN]; }; #endif /* XT_COMMENT_H */ linux/netfilter/xt_hashlimit.h000064400000006270151027430560012555 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_HASHLIMIT_H #define _XT_HASHLIMIT_H #include #include #include /* timings are in milliseconds. */ #define XT_HASHLIMIT_SCALE 10000 #define XT_HASHLIMIT_SCALE_v2 1000000llu /* 1/10,000 sec period => max of 10,000/sec. Min rate is then 429490 * seconds, or one packet every 59 hours. */ /* packet length accounting is done in 16-byte steps */ #define XT_HASHLIMIT_BYTE_SHIFT 4 /* details of this structure hidden by the implementation */ struct xt_hashlimit_htable; enum { XT_HASHLIMIT_HASH_DIP = 1 << 0, XT_HASHLIMIT_HASH_DPT = 1 << 1, XT_HASHLIMIT_HASH_SIP = 1 << 2, XT_HASHLIMIT_HASH_SPT = 1 << 3, XT_HASHLIMIT_INVERT = 1 << 4, XT_HASHLIMIT_BYTES = 1 << 5, XT_HASHLIMIT_RATE_MATCH = 1 << 6, }; struct hashlimit_cfg { __u32 mode; /* bitmask of XT_HASHLIMIT_HASH_* */ __u32 avg; /* Average secs between packets * scale */ __u32 burst; /* Period multiplier for upper limit. */ /* user specified */ __u32 size; /* how many buckets */ __u32 max; /* max number of entries */ __u32 gc_interval; /* gc interval */ __u32 expire; /* when do entries expire? */ }; struct xt_hashlimit_info { char name [IFNAMSIZ]; /* name */ struct hashlimit_cfg cfg; /* Used internally by the kernel */ struct xt_hashlimit_htable *hinfo; union { void *ptr; struct xt_hashlimit_info *master; } u; }; struct hashlimit_cfg1 { __u32 mode; /* bitmask of XT_HASHLIMIT_HASH_* */ __u32 avg; /* Average secs between packets * scale */ __u32 burst; /* Period multiplier for upper limit. */ /* user specified */ __u32 size; /* how many buckets */ __u32 max; /* max number of entries */ __u32 gc_interval; /* gc interval */ __u32 expire; /* when do entries expire? */ __u8 srcmask, dstmask; }; struct hashlimit_cfg2 { __u64 avg; /* Average secs between packets * scale */ __u64 burst; /* Period multiplier for upper limit. */ __u32 mode; /* bitmask of XT_HASHLIMIT_HASH_* */ /* user specified */ __u32 size; /* how many buckets */ __u32 max; /* max number of entries */ __u32 gc_interval; /* gc interval */ __u32 expire; /* when do entries expire? */ __u8 srcmask, dstmask; }; struct hashlimit_cfg3 { __u64 avg; /* Average secs between packets * scale */ __u64 burst; /* Period multiplier for upper limit. */ __u32 mode; /* bitmask of XT_HASHLIMIT_HASH_* */ /* user specified */ __u32 size; /* how many buckets */ __u32 max; /* max number of entries */ __u32 gc_interval; /* gc interval */ __u32 expire; /* when do entries expire? */ __u32 interval; __u8 srcmask, dstmask; }; struct xt_hashlimit_mtinfo1 { char name[IFNAMSIZ]; struct hashlimit_cfg1 cfg; /* Used internally by the kernel */ struct xt_hashlimit_htable *hinfo __attribute__((aligned(8))); }; struct xt_hashlimit_mtinfo2 { char name[NAME_MAX]; struct hashlimit_cfg2 cfg; /* Used internally by the kernel */ struct xt_hashlimit_htable *hinfo __attribute__((aligned(8))); }; struct xt_hashlimit_mtinfo3 { char name[NAME_MAX]; struct hashlimit_cfg3 cfg; /* Used internally by the kernel */ struct xt_hashlimit_htable *hinfo __attribute__((aligned(8))); }; #endif /* _XT_HASHLIMIT_H */ linux/netfilter/ipset/ip_set_bitmap.h000064400000000654151027430560014023 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __IP_SET_BITMAP_H #define __IP_SET_BITMAP_H #include /* Bitmap type specific error codes */ enum { /* The element is out of the range of the set */ IPSET_ERR_BITMAP_RANGE = IPSET_ERR_TYPE_SPECIFIC, /* The range exceeds the size limit of the set type */ IPSET_ERR_BITMAP_RANGE_SIZE, }; #endif /* __IP_SET_BITMAP_H */ linux/netfilter/ipset/ip_set_list.h000064400000001141151027430560013512 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __IP_SET_LIST_H #define __IP_SET_LIST_H #include /* List type specific error codes */ enum { /* Set name to be added/deleted/tested does not exist. */ IPSET_ERR_NAME = IPSET_ERR_TYPE_SPECIFIC, /* list:set type is not permitted to add */ IPSET_ERR_LOOP, /* Missing reference set */ IPSET_ERR_BEFORE, /* Reference set does not exist */ IPSET_ERR_NAMEREF, /* Set is full */ IPSET_ERR_LIST_FULL, /* Reference set is not added to the set */ IPSET_ERR_REF_EXIST, }; #endif /* __IP_SET_LIST_H */ linux/netfilter/ipset/ip_set.h000064400000021630151027430560012464 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (C) 2000-2002 Joakim Axelsson * Patrick Schaaf * Martin Josefsson * Copyright (C) 2003-2011 Jozsef Kadlecsik * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _IP_SET_H #define _IP_SET_H #include /* The protocol versions */ #define IPSET_PROTOCOL 7 #define IPSET_PROTOCOL_MIN 6 /* The max length of strings including NUL: set and type identifiers */ #define IPSET_MAXNAMELEN 32 /* The maximum permissible comment length we will accept over netlink */ #define IPSET_MAX_COMMENT_SIZE 255 /* Message types and commands */ enum ipset_cmd { IPSET_CMD_NONE, IPSET_CMD_PROTOCOL, /* 1: Return protocol version */ IPSET_CMD_CREATE, /* 2: Create a new (empty) set */ IPSET_CMD_DESTROY, /* 3: Destroy a (empty) set */ IPSET_CMD_FLUSH, /* 4: Remove all elements from a set */ IPSET_CMD_RENAME, /* 5: Rename a set */ IPSET_CMD_SWAP, /* 6: Swap two sets */ IPSET_CMD_LIST, /* 7: List sets */ IPSET_CMD_SAVE, /* 8: Save sets */ IPSET_CMD_ADD, /* 9: Add an element to a set */ IPSET_CMD_DEL, /* 10: Delete an element from a set */ IPSET_CMD_TEST, /* 11: Test an element in a set */ IPSET_CMD_HEADER, /* 12: Get set header data only */ IPSET_CMD_TYPE, /* 13: Get set type */ IPSET_CMD_GET_BYNAME, /* 14: Get set index by name */ IPSET_CMD_GET_BYINDEX, /* 15: Get set name by index */ IPSET_MSG_MAX, /* Netlink message commands */ /* Commands in userspace: */ IPSET_CMD_RESTORE = IPSET_MSG_MAX, /* 16: Enter restore mode */ IPSET_CMD_HELP, /* 17: Get help */ IPSET_CMD_VERSION, /* 18: Get program version */ IPSET_CMD_QUIT, /* 19: Quit from interactive mode */ IPSET_CMD_MAX, IPSET_CMD_COMMIT = IPSET_CMD_MAX, /* 20: Commit buffered commands */ }; /* Attributes at command level */ enum { IPSET_ATTR_UNSPEC, IPSET_ATTR_PROTOCOL, /* 1: Protocol version */ IPSET_ATTR_SETNAME, /* 2: Name of the set */ IPSET_ATTR_TYPENAME, /* 3: Typename */ IPSET_ATTR_SETNAME2 = IPSET_ATTR_TYPENAME, /* Setname at rename/swap */ IPSET_ATTR_REVISION, /* 4: Settype revision */ IPSET_ATTR_FAMILY, /* 5: Settype family */ IPSET_ATTR_FLAGS, /* 6: Flags at command level */ IPSET_ATTR_DATA, /* 7: Nested attributes */ IPSET_ATTR_ADT, /* 8: Multiple data containers */ IPSET_ATTR_LINENO, /* 9: Restore lineno */ IPSET_ATTR_PROTOCOL_MIN, /* 10: Minimal supported version number */ IPSET_ATTR_REVISION_MIN = IPSET_ATTR_PROTOCOL_MIN, /* type rev min */ IPSET_ATTR_INDEX, /* 11: Kernel index of set */ __IPSET_ATTR_CMD_MAX, }; #define IPSET_ATTR_CMD_MAX (__IPSET_ATTR_CMD_MAX - 1) /* CADT specific attributes */ enum { IPSET_ATTR_IP = IPSET_ATTR_UNSPEC + 1, IPSET_ATTR_IP_FROM = IPSET_ATTR_IP, IPSET_ATTR_IP_TO, /* 2 */ IPSET_ATTR_CIDR, /* 3 */ IPSET_ATTR_PORT, /* 4 */ IPSET_ATTR_PORT_FROM = IPSET_ATTR_PORT, IPSET_ATTR_PORT_TO, /* 5 */ IPSET_ATTR_TIMEOUT, /* 6 */ IPSET_ATTR_PROTO, /* 7 */ IPSET_ATTR_CADT_FLAGS, /* 8 */ IPSET_ATTR_CADT_LINENO = IPSET_ATTR_LINENO, /* 9 */ IPSET_ATTR_MARK, /* 10 */ IPSET_ATTR_MARKMASK, /* 11 */ /* Reserve empty slots */ IPSET_ATTR_CADT_MAX = 16, /* Create-only specific attributes */ IPSET_ATTR_GC, IPSET_ATTR_HASHSIZE, IPSET_ATTR_MAXELEM, IPSET_ATTR_NETMASK, IPSET_ATTR_PROBES, IPSET_ATTR_RESIZE, IPSET_ATTR_SIZE, /* Kernel-only */ IPSET_ATTR_ELEMENTS, IPSET_ATTR_REFERENCES, IPSET_ATTR_MEMSIZE, __IPSET_ATTR_CREATE_MAX, }; #define IPSET_ATTR_CREATE_MAX (__IPSET_ATTR_CREATE_MAX - 1) /* ADT specific attributes */ enum { IPSET_ATTR_ETHER = IPSET_ATTR_CADT_MAX + 1, IPSET_ATTR_NAME, IPSET_ATTR_NAMEREF, IPSET_ATTR_IP2, IPSET_ATTR_CIDR2, IPSET_ATTR_IP2_TO, IPSET_ATTR_IFACE, IPSET_ATTR_BYTES, IPSET_ATTR_PACKETS, IPSET_ATTR_COMMENT, IPSET_ATTR_SKBMARK, IPSET_ATTR_SKBPRIO, IPSET_ATTR_SKBQUEUE, IPSET_ATTR_PAD, __IPSET_ATTR_ADT_MAX, }; #define IPSET_ATTR_ADT_MAX (__IPSET_ATTR_ADT_MAX - 1) /* IP specific attributes */ enum { IPSET_ATTR_IPADDR_IPV4 = IPSET_ATTR_UNSPEC + 1, IPSET_ATTR_IPADDR_IPV6, __IPSET_ATTR_IPADDR_MAX, }; #define IPSET_ATTR_IPADDR_MAX (__IPSET_ATTR_IPADDR_MAX - 1) /* Error codes */ enum ipset_errno { IPSET_ERR_PRIVATE = 4096, IPSET_ERR_PROTOCOL, IPSET_ERR_FIND_TYPE, IPSET_ERR_MAX_SETS, IPSET_ERR_BUSY, IPSET_ERR_EXIST_SETNAME2, IPSET_ERR_TYPE_MISMATCH, IPSET_ERR_EXIST, IPSET_ERR_INVALID_CIDR, IPSET_ERR_INVALID_NETMASK, IPSET_ERR_INVALID_FAMILY, IPSET_ERR_TIMEOUT, IPSET_ERR_REFERENCED, IPSET_ERR_IPADDR_IPV4, IPSET_ERR_IPADDR_IPV6, IPSET_ERR_COUNTER, IPSET_ERR_COMMENT, IPSET_ERR_INVALID_MARKMASK, IPSET_ERR_SKBINFO, /* Type specific error codes */ IPSET_ERR_TYPE_SPECIFIC = 4352, }; /* Flags at command level or match/target flags, lower half of cmdattrs*/ enum ipset_cmd_flags { IPSET_FLAG_BIT_EXIST = 0, IPSET_FLAG_EXIST = (1 << IPSET_FLAG_BIT_EXIST), IPSET_FLAG_BIT_LIST_SETNAME = 1, IPSET_FLAG_LIST_SETNAME = (1 << IPSET_FLAG_BIT_LIST_SETNAME), IPSET_FLAG_BIT_LIST_HEADER = 2, IPSET_FLAG_LIST_HEADER = (1 << IPSET_FLAG_BIT_LIST_HEADER), IPSET_FLAG_BIT_SKIP_COUNTER_UPDATE = 3, IPSET_FLAG_SKIP_COUNTER_UPDATE = (1 << IPSET_FLAG_BIT_SKIP_COUNTER_UPDATE), IPSET_FLAG_BIT_SKIP_SUBCOUNTER_UPDATE = 4, IPSET_FLAG_SKIP_SUBCOUNTER_UPDATE = (1 << IPSET_FLAG_BIT_SKIP_SUBCOUNTER_UPDATE), IPSET_FLAG_BIT_MATCH_COUNTERS = 5, IPSET_FLAG_MATCH_COUNTERS = (1 << IPSET_FLAG_BIT_MATCH_COUNTERS), IPSET_FLAG_BIT_RETURN_NOMATCH = 7, IPSET_FLAG_RETURN_NOMATCH = (1 << IPSET_FLAG_BIT_RETURN_NOMATCH), IPSET_FLAG_BIT_MAP_SKBMARK = 8, IPSET_FLAG_MAP_SKBMARK = (1 << IPSET_FLAG_BIT_MAP_SKBMARK), IPSET_FLAG_BIT_MAP_SKBPRIO = 9, IPSET_FLAG_MAP_SKBPRIO = (1 << IPSET_FLAG_BIT_MAP_SKBPRIO), IPSET_FLAG_BIT_MAP_SKBQUEUE = 10, IPSET_FLAG_MAP_SKBQUEUE = (1 << IPSET_FLAG_BIT_MAP_SKBQUEUE), IPSET_FLAG_CMD_MAX = 15, }; /* Flags at CADT attribute level, upper half of cmdattrs */ enum ipset_cadt_flags { IPSET_FLAG_BIT_BEFORE = 0, IPSET_FLAG_BEFORE = (1 << IPSET_FLAG_BIT_BEFORE), IPSET_FLAG_BIT_PHYSDEV = 1, IPSET_FLAG_PHYSDEV = (1 << IPSET_FLAG_BIT_PHYSDEV), IPSET_FLAG_BIT_NOMATCH = 2, IPSET_FLAG_NOMATCH = (1 << IPSET_FLAG_BIT_NOMATCH), IPSET_FLAG_BIT_WITH_COUNTERS = 3, IPSET_FLAG_WITH_COUNTERS = (1 << IPSET_FLAG_BIT_WITH_COUNTERS), IPSET_FLAG_BIT_WITH_COMMENT = 4, IPSET_FLAG_WITH_COMMENT = (1 << IPSET_FLAG_BIT_WITH_COMMENT), IPSET_FLAG_BIT_WITH_FORCEADD = 5, IPSET_FLAG_WITH_FORCEADD = (1 << IPSET_FLAG_BIT_WITH_FORCEADD), IPSET_FLAG_BIT_WITH_SKBINFO = 6, IPSET_FLAG_WITH_SKBINFO = (1 << IPSET_FLAG_BIT_WITH_SKBINFO), IPSET_FLAG_CADT_MAX = 15, }; /* The flag bits which correspond to the non-extension create flags */ enum ipset_create_flags { IPSET_CREATE_FLAG_BIT_FORCEADD = 0, IPSET_CREATE_FLAG_FORCEADD = (1 << IPSET_CREATE_FLAG_BIT_FORCEADD), IPSET_CREATE_FLAG_BIT_MAX = 7, }; /* Commands with settype-specific attributes */ enum ipset_adt { IPSET_ADD, IPSET_DEL, IPSET_TEST, IPSET_ADT_MAX, IPSET_CREATE = IPSET_ADT_MAX, IPSET_CADT_MAX, }; /* Sets are identified by an index in kernel space. Tweak with ip_set_id_t * and IPSET_INVALID_ID if you want to increase the max number of sets. * Also, IPSET_ATTR_INDEX must be changed. */ typedef __u16 ip_set_id_t; #define IPSET_INVALID_ID 65535 enum ip_set_dim { IPSET_DIM_ZERO = 0, IPSET_DIM_ONE, IPSET_DIM_TWO, IPSET_DIM_THREE, /* Max dimension in elements. * If changed, new revision of iptables match/target is required. */ IPSET_DIM_MAX = 6, /* Backward compatibility: set match revision 2 */ IPSET_BIT_RETURN_NOMATCH = 7, }; /* Option flags for kernel operations */ enum ip_set_kopt { IPSET_INV_MATCH = (1 << IPSET_DIM_ZERO), IPSET_DIM_ONE_SRC = (1 << IPSET_DIM_ONE), IPSET_DIM_TWO_SRC = (1 << IPSET_DIM_TWO), IPSET_DIM_THREE_SRC = (1 << IPSET_DIM_THREE), IPSET_RETURN_NOMATCH = (1 << IPSET_BIT_RETURN_NOMATCH), }; enum { IPSET_COUNTER_NONE = 0, IPSET_COUNTER_EQ, IPSET_COUNTER_NE, IPSET_COUNTER_LT, IPSET_COUNTER_GT, }; /* Backward compatibility for set match v3 */ struct ip_set_counter_match0 { __u8 op; __u64 value; }; struct ip_set_counter_match { __aligned_u64 value; __u8 op; }; /* Interface to iptables/ip6tables */ #define SO_IP_SET 83 union ip_set_name_index { char name[IPSET_MAXNAMELEN]; ip_set_id_t index; }; #define IP_SET_OP_GET_BYNAME 0x00000006 /* Get set index by name */ struct ip_set_req_get_set { unsigned int op; unsigned int version; union ip_set_name_index set; }; #define IP_SET_OP_GET_BYINDEX 0x00000007 /* Get set name by index */ /* Uses ip_set_req_get_set */ #define IP_SET_OP_GET_FNAME 0x00000008 /* Get set index and family */ struct ip_set_req_get_set_family { unsigned int op; unsigned int version; unsigned int family; union ip_set_name_index set; }; #define IP_SET_OP_VERSION 0x00000100 /* Ask kernel version */ struct ip_set_req_version { unsigned int op; unsigned int version; }; #endif /* _IP_SET_H */ linux/netfilter/ipset/ip_set_hash.h000064400000001102151027430560013457 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __IP_SET_HASH_H #define __IP_SET_HASH_H #include /* Hash type specific error codes */ enum { /* Hash is full */ IPSET_ERR_HASH_FULL = IPSET_ERR_TYPE_SPECIFIC, /* Null-valued element */ IPSET_ERR_HASH_ELEM, /* Invalid protocol */ IPSET_ERR_INVALID_PROTO, /* Protocol missing but must be specified */ IPSET_ERR_MISSING_PROTO, /* Range not supported */ IPSET_ERR_HASH_RANGE_UNSUPPORTED, /* Invalid range */ IPSET_ERR_HASH_RANGE, }; #endif /* __IP_SET_HASH_H */ linux/netfilter/xt_pkttype.h000064400000000274151027430560012271 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_PKTTYPE_H #define _XT_PKTTYPE_H struct xt_pkttype_info { int pkttype; int invert; }; #endif /*_XT_PKTTYPE_H*/ linux/netfilter/nf_tables_compat.h000064400000001333151027430560013353 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFT_COMPAT_NFNETLINK_H_ #define _NFT_COMPAT_NFNETLINK_H_ enum nft_target_attributes { NFTA_TARGET_UNSPEC, NFTA_TARGET_NAME, NFTA_TARGET_REV, NFTA_TARGET_INFO, __NFTA_TARGET_MAX }; #define NFTA_TARGET_MAX (__NFTA_TARGET_MAX - 1) enum nft_match_attributes { NFTA_MATCH_UNSPEC, NFTA_MATCH_NAME, NFTA_MATCH_REV, NFTA_MATCH_INFO, __NFTA_MATCH_MAX }; #define NFTA_MATCH_MAX (__NFTA_MATCH_MAX - 1) #define NFT_COMPAT_NAME_MAX 32 enum { NFNL_MSG_COMPAT_GET, NFNL_MSG_COMPAT_MAX }; enum { NFTA_COMPAT_UNSPEC = 0, NFTA_COMPAT_NAME, NFTA_COMPAT_REV, NFTA_COMPAT_TYPE, __NFTA_COMPAT_MAX, }; #define NFTA_COMPAT_MAX (__NFTA_COMPAT_MAX - 1) #endif linux/netfilter/xt_tcpudp.h000064400000002342151027430560012066 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TCPUDP_H #define _XT_TCPUDP_H #include /* TCP matching stuff */ struct xt_tcp { __u16 spts[2]; /* Source port range. */ __u16 dpts[2]; /* Destination port range. */ __u8 option; /* TCP Option iff non-zero*/ __u8 flg_mask; /* TCP flags mask byte */ __u8 flg_cmp; /* TCP flags compare byte */ __u8 invflags; /* Inverse flags */ }; /* Values for "inv" field in struct ipt_tcp. */ #define XT_TCP_INV_SRCPT 0x01 /* Invert the sense of source ports. */ #define XT_TCP_INV_DSTPT 0x02 /* Invert the sense of dest ports. */ #define XT_TCP_INV_FLAGS 0x04 /* Invert the sense of TCP flags. */ #define XT_TCP_INV_OPTION 0x08 /* Invert the sense of option test. */ #define XT_TCP_INV_MASK 0x0F /* All possible flags. */ /* UDP matching stuff */ struct xt_udp { __u16 spts[2]; /* Source port range. */ __u16 dpts[2]; /* Destination port range. */ __u8 invflags; /* Inverse flags */ }; /* Values for "invflags" field in struct ipt_udp. */ #define XT_UDP_INV_SRCPT 0x01 /* Invert the sense of source ports. */ #define XT_UDP_INV_DSTPT 0x02 /* Invert the sense of dest ports. */ #define XT_UDP_INV_MASK 0x03 /* All possible flags. */ #endif linux/netfilter/xt_tcpmss.h000064400000000375151027430560012104 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TCPMSS_MATCH_H #define _XT_TCPMSS_MATCH_H #include struct xt_tcpmss_match_info { __u16 mss_min, mss_max; __u8 invert; }; #endif /*_XT_TCPMSS_MATCH_H*/ linux/netfilter/xt_mark.h000064400000000404151027430560011516 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_MARK_H #define _XT_MARK_H #include struct xt_mark_tginfo2 { __u32 mark, mask; }; struct xt_mark_mtinfo1 { __u32 mark, mask; __u8 invert; }; #endif /*_XT_MARK_H*/ linux/netfilter/xt_limit.h000064400000001241151027430560011702 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_RATE_H #define _XT_RATE_H #include /* timings are in milliseconds. */ #define XT_LIMIT_SCALE 10000 struct xt_limit_priv; /* 1/10,000 sec period => max of 10,000/sec. Min rate is then 429490 seconds, or one every 59 hours. */ struct xt_rateinfo { __u32 avg; /* Average secs between packets * scale */ __u32 burst; /* Period multiplier for upper limit. */ /* Used internally by the kernel */ unsigned long prev; /* moved to xt_limit_priv */ __u32 credit; /* moved to xt_limit_priv */ __u32 credit_cap, cost; struct xt_limit_priv *master; }; #endif /*_XT_RATE_H*/ linux/netfilter/xt_TCPOPTSTRIP.h000064400000000627151027430560012426 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TCPOPTSTRIP_H #define _XT_TCPOPTSTRIP_H #include #define tcpoptstrip_set_bit(bmap, idx) \ (bmap[(idx) >> 5] |= 1U << (idx & 31)) #define tcpoptstrip_test_bit(bmap, idx) \ (((1U << (idx & 31)) & bmap[(idx) >> 5]) != 0) struct xt_tcpoptstrip_target_info { __u32 strip_bmap[8]; }; #endif /* _XT_TCPOPTSTRIP_H */ linux/netfilter/nf_conntrack_tcp.h000064400000002607151027430560013373 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NF_CONNTRACK_TCP_H #define _NF_CONNTRACK_TCP_H /* TCP tracking. */ #include /* This is exposed to userspace (ctnetlink) */ enum tcp_conntrack { TCP_CONNTRACK_NONE, TCP_CONNTRACK_SYN_SENT, TCP_CONNTRACK_SYN_RECV, TCP_CONNTRACK_ESTABLISHED, TCP_CONNTRACK_FIN_WAIT, TCP_CONNTRACK_CLOSE_WAIT, TCP_CONNTRACK_LAST_ACK, TCP_CONNTRACK_TIME_WAIT, TCP_CONNTRACK_CLOSE, TCP_CONNTRACK_LISTEN, /* obsolete */ #define TCP_CONNTRACK_SYN_SENT2 TCP_CONNTRACK_LISTEN TCP_CONNTRACK_MAX, TCP_CONNTRACK_IGNORE, TCP_CONNTRACK_RETRANS, TCP_CONNTRACK_UNACK, TCP_CONNTRACK_TIMEOUT_MAX }; /* Window scaling is advertised by the sender */ #define IP_CT_TCP_FLAG_WINDOW_SCALE 0x01 /* SACK is permitted by the sender */ #define IP_CT_TCP_FLAG_SACK_PERM 0x02 /* This sender sent FIN first */ #define IP_CT_TCP_FLAG_CLOSE_INIT 0x04 /* Be liberal in window checking */ #define IP_CT_TCP_FLAG_BE_LIBERAL 0x08 /* Has unacknowledged data */ #define IP_CT_TCP_FLAG_DATA_UNACKNOWLEDGED 0x10 /* The field td_maxack has been set */ #define IP_CT_TCP_FLAG_MAXACK_SET 0x20 /* Marks possibility for expected RFC5961 challenge ACK */ #define IP_CT_EXP_CHALLENGE_ACK 0x40 /* Simultaneous open initialized */ #define IP_CT_TCP_SIMULTANEOUS_OPEN 0x80 struct nf_ct_tcp_flags { __u8 flags; __u8 mask; }; #endif /* _NF_CONNTRACK_TCP_H */ linux/netfilter/xt_CHECKSUM.h000064400000001063151027430560011770 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Header file for iptables ipt_CHECKSUM target * * (C) 2002 by Harald Welte * (C) 2010 Red Hat Inc * Author: Michael S. Tsirkin * * This software is distributed under GNU GPL v2, 1991 */ #ifndef _XT_CHECKSUM_TARGET_H #define _XT_CHECKSUM_TARGET_H #include #define XT_CHECKSUM_OP_FILL 0x01 /* fill in checksum in IP header */ struct xt_CHECKSUM_info { __u8 operation; /* bitset of operations */ }; #endif /* _XT_CHECKSUM_TARGET_H */ linux/netfilter/xt_TCPMSS.h000064400000000353151027430560011600 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TCPMSS_H #define _XT_TCPMSS_H #include struct xt_tcpmss_info { __u16 mss; }; #define XT_TCPMSS_CLAMP_PMTU 0xffff #endif /* _XT_TCPMSS_H */ linux/netfilter/xt_time.h000064400000001332151027430560011523 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TIME_H #define _XT_TIME_H 1 #include struct xt_time_info { __u32 date_start; __u32 date_stop; __u32 daytime_start; __u32 daytime_stop; __u32 monthdays_match; __u8 weekdays_match; __u8 flags; }; enum { /* Match against local time (instead of UTC) */ XT_TIME_LOCAL_TZ = 1 << 0, /* treat timestart > timestop (e.g. 23:00-01:00) as single period */ XT_TIME_CONTIGUOUS = 1 << 1, /* Shortcuts */ XT_TIME_ALL_MONTHDAYS = 0xFFFFFFFE, XT_TIME_ALL_WEEKDAYS = 0xFE, XT_TIME_MIN_DAYTIME = 0, XT_TIME_MAX_DAYTIME = 24 * 60 * 60 - 1, }; #define XT_TIME_ALL_FLAGS (XT_TIME_LOCAL_TZ|XT_TIME_CONTIGUOUS) #endif /* _XT_TIME_H */ linux/netfilter/nf_nat.h000064400000002762151027430560011327 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NETFILTER_NF_NAT_H #define _NETFILTER_NF_NAT_H #include #include #define NF_NAT_RANGE_MAP_IPS (1 << 0) #define NF_NAT_RANGE_PROTO_SPECIFIED (1 << 1) #define NF_NAT_RANGE_PROTO_RANDOM (1 << 2) #define NF_NAT_RANGE_PERSISTENT (1 << 3) #define NF_NAT_RANGE_PROTO_RANDOM_FULLY (1 << 4) #define NF_NAT_RANGE_PROTO_OFFSET (1 << 5) #define NF_NAT_RANGE_PROTO_RANDOM_ALL \ (NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PROTO_RANDOM_FULLY) #define NF_NAT_RANGE_MASK \ (NF_NAT_RANGE_MAP_IPS | NF_NAT_RANGE_PROTO_SPECIFIED | \ NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PERSISTENT | \ NF_NAT_RANGE_PROTO_RANDOM_FULLY | NF_NAT_RANGE_PROTO_OFFSET) struct nf_nat_ipv4_range { unsigned int flags; __be32 min_ip; __be32 max_ip; union nf_conntrack_man_proto min; union nf_conntrack_man_proto max; }; struct nf_nat_ipv4_multi_range_compat { unsigned int rangesize; struct nf_nat_ipv4_range range[1]; }; struct nf_nat_range { unsigned int flags; union nf_inet_addr min_addr; union nf_inet_addr max_addr; union nf_conntrack_man_proto min_proto; union nf_conntrack_man_proto max_proto; }; struct nf_nat_range2 { unsigned int flags; union nf_inet_addr min_addr; union nf_inet_addr max_addr; union nf_conntrack_man_proto min_proto; union nf_conntrack_man_proto max_proto; union nf_conntrack_man_proto base_proto; }; #endif /* _NETFILTER_NF_NAT_H */ linux/netfilter/xt_connmark.h000064400000001604151027430560012377 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _XT_CONNMARK_H #define _XT_CONNMARK_H #include /* Copyright (C) 2002,2004 MARA Systems AB * by Henrik Nordstrom * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ enum { XT_CONNMARK_SET = 0, XT_CONNMARK_SAVE, XT_CONNMARK_RESTORE }; enum { D_SHIFT_LEFT = 0, D_SHIFT_RIGHT, }; struct xt_connmark_tginfo1 { __u32 ctmark, ctmask, nfmask; __u8 mode; }; struct xt_connmark_tginfo2 { __u32 ctmark, ctmask, nfmask; __u8 shift_dir, shift_bits, mode; }; struct xt_connmark_mtinfo1 { __u32 mark, mask; __u8 invert; }; #endif /*_XT_CONNMARK_H*/ linux/netfilter/xt_owner.h000064400000000644151027430560011724 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_OWNER_MATCH_H #define _XT_OWNER_MATCH_H #include enum { XT_OWNER_UID = 1 << 0, XT_OWNER_GID = 1 << 1, XT_OWNER_SOCKET = 1 << 2, XT_OWNER_SUPPL_GROUPS = 1 << 3, }; struct xt_owner_match_info { __u32 uid_min, uid_max; __u32 gid_min, gid_max; __u8 match, invert; }; #endif /* _XT_OWNER_MATCH_H */ linux/netfilter/xt_CONNMARK.h000064400000000307151027430560011776 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CONNMARK_H_target #define _XT_CONNMARK_H_target #include #endif /*_XT_CONNMARK_H_target*/ linux/netfilter/xt_CONNSECMARK.h000064400000000455151027430560012335 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CONNSECMARK_H_target #define _XT_CONNSECMARK_H_target #include enum { CONNSECMARK_SAVE = 1, CONNSECMARK_RESTORE, }; struct xt_connsecmark_target_info { __u8 mode; }; #endif /*_XT_CONNSECMARK_H_target */ linux/netfilter/xt_multiport.h000064400000001321151027430560012622 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_MULTIPORT_H #define _XT_MULTIPORT_H #include enum xt_multiport_flags { XT_MULTIPORT_SOURCE, XT_MULTIPORT_DESTINATION, XT_MULTIPORT_EITHER }; #define XT_MULTI_PORTS 15 /* Must fit inside union xt_matchinfo: 16 bytes */ struct xt_multiport { __u8 flags; /* Type of comparison */ __u8 count; /* Number of ports */ __u16 ports[XT_MULTI_PORTS]; /* Ports */ }; struct xt_multiport_v1 { __u8 flags; /* Type of comparison */ __u8 count; /* Number of ports */ __u16 ports[XT_MULTI_PORTS]; /* Ports */ __u8 pflags[XT_MULTI_PORTS]; /* Port flags */ __u8 invert; /* Invert flag */ }; #endif /*_XT_MULTIPORT_H*/ linux/netfilter/nfnetlink.h000064400000004574151027430560012055 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFNETLINK_H #define _NFNETLINK_H #include #include enum nfnetlink_groups { NFNLGRP_NONE, #define NFNLGRP_NONE NFNLGRP_NONE NFNLGRP_CONNTRACK_NEW, #define NFNLGRP_CONNTRACK_NEW NFNLGRP_CONNTRACK_NEW NFNLGRP_CONNTRACK_UPDATE, #define NFNLGRP_CONNTRACK_UPDATE NFNLGRP_CONNTRACK_UPDATE NFNLGRP_CONNTRACK_DESTROY, #define NFNLGRP_CONNTRACK_DESTROY NFNLGRP_CONNTRACK_DESTROY NFNLGRP_CONNTRACK_EXP_NEW, #define NFNLGRP_CONNTRACK_EXP_NEW NFNLGRP_CONNTRACK_EXP_NEW NFNLGRP_CONNTRACK_EXP_UPDATE, #define NFNLGRP_CONNTRACK_EXP_UPDATE NFNLGRP_CONNTRACK_EXP_UPDATE NFNLGRP_CONNTRACK_EXP_DESTROY, #define NFNLGRP_CONNTRACK_EXP_DESTROY NFNLGRP_CONNTRACK_EXP_DESTROY NFNLGRP_NFTABLES, #define NFNLGRP_NFTABLES NFNLGRP_NFTABLES NFNLGRP_ACCT_QUOTA, #define NFNLGRP_ACCT_QUOTA NFNLGRP_ACCT_QUOTA NFNLGRP_NFTRACE, #define NFNLGRP_NFTRACE NFNLGRP_NFTRACE __NFNLGRP_MAX, }; #define NFNLGRP_MAX (__NFNLGRP_MAX - 1) /* General form of address family dependent message. */ struct nfgenmsg { __u8 nfgen_family; /* AF_xxx */ __u8 version; /* nfnetlink version */ __be16 res_id; /* resource id */ }; #define NFNETLINK_V0 0 /* netfilter netlink message types are split in two pieces: * 8 bit subsystem, 8bit operation. */ #define NFNL_SUBSYS_ID(x) ((x & 0xff00) >> 8) #define NFNL_MSG_TYPE(x) (x & 0x00ff) /* No enum here, otherwise __stringify() trick of MODULE_ALIAS_NFNL_SUBSYS() * won't work anymore */ #define NFNL_SUBSYS_NONE 0 #define NFNL_SUBSYS_CTNETLINK 1 #define NFNL_SUBSYS_CTNETLINK_EXP 2 #define NFNL_SUBSYS_QUEUE 3 #define NFNL_SUBSYS_ULOG 4 #define NFNL_SUBSYS_OSF 5 #define NFNL_SUBSYS_IPSET 6 #define NFNL_SUBSYS_ACCT 7 #define NFNL_SUBSYS_CTNETLINK_TIMEOUT 8 #define NFNL_SUBSYS_CTHELPER 9 #define NFNL_SUBSYS_NFTABLES 10 #define NFNL_SUBSYS_NFT_COMPAT 11 #define NFNL_SUBSYS_COUNT 12 /* Reserved control nfnetlink messages */ #define NFNL_MSG_BATCH_BEGIN NLMSG_MIN_TYPE #define NFNL_MSG_BATCH_END NLMSG_MIN_TYPE+1 /** * enum nfnl_batch_attributes - nfnetlink batch netlink attributes * * @NFNL_BATCH_GENID: generation ID for this changeset (NLA_U32) */ enum nfnl_batch_attributes { NFNL_BATCH_UNSPEC, NFNL_BATCH_GENID, __NFNL_BATCH_MAX }; #define NFNL_BATCH_MAX (__NFNL_BATCH_MAX - 1) #endif /* _NFNETLINK_H */ linux/netfilter/nf_conntrack_sctp.h000064400000001100151027430560013541 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NF_CONNTRACK_SCTP_H #define _NF_CONNTRACK_SCTP_H /* SCTP tracking. */ #include enum sctp_conntrack { SCTP_CONNTRACK_NONE, SCTP_CONNTRACK_CLOSED, SCTP_CONNTRACK_COOKIE_WAIT, SCTP_CONNTRACK_COOKIE_ECHOED, SCTP_CONNTRACK_ESTABLISHED, SCTP_CONNTRACK_SHUTDOWN_SENT, SCTP_CONNTRACK_SHUTDOWN_RECD, SCTP_CONNTRACK_SHUTDOWN_ACK_SENT, SCTP_CONNTRACK_HEARTBEAT_SENT, SCTP_CONNTRACK_HEARTBEAT_ACKED, SCTP_CONNTRACK_MAX }; #endif /* _NF_CONNTRACK_SCTP_H */ linux/netfilter/nfnetlink_acct.h000064400000001604151027430560013036 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFNL_ACCT_H_ #define _NFNL_ACCT_H_ #ifndef NFACCT_NAME_MAX #define NFACCT_NAME_MAX 32 #endif enum nfnl_acct_msg_types { NFNL_MSG_ACCT_NEW, NFNL_MSG_ACCT_GET, NFNL_MSG_ACCT_GET_CTRZERO, NFNL_MSG_ACCT_DEL, NFNL_MSG_ACCT_OVERQUOTA, NFNL_MSG_ACCT_MAX }; enum nfnl_acct_flags { NFACCT_F_QUOTA_PKTS = (1 << 0), NFACCT_F_QUOTA_BYTES = (1 << 1), NFACCT_F_OVERQUOTA = (1 << 2), /* can't be set from userspace */ }; enum nfnl_acct_type { NFACCT_UNSPEC, NFACCT_NAME, NFACCT_PKTS, NFACCT_BYTES, NFACCT_USE, NFACCT_FLAGS, NFACCT_QUOTA, NFACCT_FILTER, NFACCT_PAD, __NFACCT_MAX }; #define NFACCT_MAX (__NFACCT_MAX - 1) enum nfnl_attr_filter_type { NFACCT_FILTER_UNSPEC, NFACCT_FILTER_MASK, NFACCT_FILTER_VALUE, __NFACCT_FILTER_MAX }; #define NFACCT_FILTER_MAX (__NFACCT_FILTER_MAX - 1) #endif /* _NFNL_ACCT_H_ */ linux/netfilter/xt_TEE.h000064400000000515151027430560011204 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TEE_TARGET_H #define _XT_TEE_TARGET_H #include struct xt_tee_tginfo { union nf_inet_addr gw; char oif[16]; /* used internally by the kernel */ struct xt_tee_priv *priv __attribute__((aligned(8))); }; #endif /* _XT_TEE_TARGET_H */ linux/netfilter/xt_set.h000064400000003443151027430560011365 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_SET_H #define _XT_SET_H #include #include /* Revision 0 interface: backward compatible with netfilter/iptables */ /* * Option flags for kernel operations (xt_set_info_v0) */ #define IPSET_SRC 0x01 /* Source match/add */ #define IPSET_DST 0x02 /* Destination match/add */ #define IPSET_MATCH_INV 0x04 /* Inverse matching */ struct xt_set_info_v0 { ip_set_id_t index; union { __u32 flags[IPSET_DIM_MAX + 1]; struct { __u32 __flags[IPSET_DIM_MAX]; __u8 dim; __u8 flags; } compat; } u; }; /* match and target infos */ struct xt_set_info_match_v0 { struct xt_set_info_v0 match_set; }; struct xt_set_info_target_v0 { struct xt_set_info_v0 add_set; struct xt_set_info_v0 del_set; }; /* Revision 1 match and target */ struct xt_set_info { ip_set_id_t index; __u8 dim; __u8 flags; }; /* match and target infos */ struct xt_set_info_match_v1 { struct xt_set_info match_set; }; struct xt_set_info_target_v1 { struct xt_set_info add_set; struct xt_set_info del_set; }; /* Revision 2 target */ struct xt_set_info_target_v2 { struct xt_set_info add_set; struct xt_set_info del_set; __u32 flags; __u32 timeout; }; /* Revision 3 match */ struct xt_set_info_match_v3 { struct xt_set_info match_set; struct ip_set_counter_match0 packets; struct ip_set_counter_match0 bytes; __u32 flags; }; /* Revision 3 target */ struct xt_set_info_target_v3 { struct xt_set_info add_set; struct xt_set_info del_set; struct xt_set_info map_set; __u32 flags; __u32 timeout; }; /* Revision 4 match */ struct xt_set_info_match_v4 { struct xt_set_info match_set; struct ip_set_counter_match packets; struct ip_set_counter_match bytes; __u32 flags; }; #endif /*_XT_SET_H*/ linux/netfilter/xt_statistic.h000064400000001314151027430560012574 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_STATISTIC_H #define _XT_STATISTIC_H #include enum xt_statistic_mode { XT_STATISTIC_MODE_RANDOM, XT_STATISTIC_MODE_NTH, __XT_STATISTIC_MODE_MAX }; #define XT_STATISTIC_MODE_MAX (__XT_STATISTIC_MODE_MAX - 1) enum xt_statistic_flags { XT_STATISTIC_INVERT = 0x1, }; #define XT_STATISTIC_MASK 0x1 struct xt_statistic_priv; struct xt_statistic_info { __u16 mode; __u16 flags; union { struct { __u32 probability; } random; struct { __u32 every; __u32 packet; __u32 count; /* unused */ } nth; } u; struct xt_statistic_priv *master __attribute__((aligned(8))); }; #endif /* _XT_STATISTIC_H */ linux/netfilter/xt_osf.h000064400000003451151027430560011360 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2003+ Evgeniy Polyakov * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef _XT_OSF_H #define _XT_OSF_H #include #include #include #include #define XT_OSF_GENRE NF_OSF_GENRE #define XT_OSF_INVERT NF_OSF_INVERT #define XT_OSF_TTL NF_OSF_TTL #define XT_OSF_LOG NF_OSF_LOG #define XT_OSF_LOGLEVEL_ALL NF_OSF_LOGLEVEL_ALL #define XT_OSF_LOGLEVEL_FIRST NF_OSF_LOGLEVEL_FIRST #define XT_OSF_LOGLEVEL_ALL_KNOWN NF_OSF_LOGLEVEL_ALL_KNOWN #define XT_OSF_TTL_TRUE NF_OSF_TTL_TRUE #define XT_OSF_TTL_NOCHECK NF_OSF_TTL_NOCHECK #define XT_OSF_TTL_LESS 1 /* Check if ip TTL is less than fingerprint one */ #define xt_osf_wc nf_osf_wc #define xt_osf_opt nf_osf_opt #define xt_osf_info nf_osf_info #define xt_osf_user_finger nf_osf_user_finger #define xt_osf_finger nf_osf_finger #define xt_osf_nlmsg nf_osf_nlmsg /* * Add/remove fingerprint from the kernel. */ enum xt_osf_msg_types { OSF_MSG_ADD, OSF_MSG_REMOVE, OSF_MSG_MAX, }; enum xt_osf_attr_type { OSF_ATTR_UNSPEC, OSF_ATTR_FINGER, OSF_ATTR_MAX, }; #endif /* _XT_OSF_H */ linux/netfilter/xt_nfacct.h000064400000000455151027430560012030 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_NFACCT_MATCH_H #define _XT_NFACCT_MATCH_H #include struct nf_acct; struct xt_nfacct_match_info { char name[NFACCT_NAME_MAX]; struct nf_acct *nfacct; }; #endif /* _XT_NFACCT_MATCH_H */ linux/netfilter/nf_conntrack_ftp.h000064400000000666151027430560013401 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NF_CONNTRACK_FTP_H #define _NF_CONNTRACK_FTP_H /* FTP tracking. */ /* This enum is exposed to userspace */ enum nf_ct_ftp_type { /* PORT command from client */ NF_CT_FTP_PORT, /* PASV response from server */ NF_CT_FTP_PASV, /* EPRT command from client */ NF_CT_FTP_EPRT, /* EPSV response from server */ NF_CT_FTP_EPSV, }; #endif /* _NF_CONNTRACK_FTP_H */ linux/netfilter/xt_connlabel.h000064400000000550151027430560012523 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CONNLABEL_H #define _XT_CONNLABEL_H #include #define XT_CONNLABEL_MAXBIT 127 enum xt_connlabel_mtopts { XT_CONNLABEL_OP_INVERT = 1 << 0, XT_CONNLABEL_OP_SET = 1 << 1, }; struct xt_connlabel_mtinfo { __u16 bit; __u16 options; }; #endif /* _XT_CONNLABEL_H */ linux/netfilter/xt_cluster.h000064400000000566151027430560012256 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CLUSTER_MATCH_H #define _XT_CLUSTER_MATCH_H #include enum xt_cluster_flags { XT_CLUSTER_F_INV = (1 << 0) }; struct xt_cluster_match_info { __u32 total_nodes; __u32 node_mask; __u32 hash_seed; __u32 flags; }; #define XT_CLUSTER_NODES_MAX 32 #endif /* _XT_CLUSTER_MATCH_H */ linux/netfilter/xt_LOG.h000064400000001202151027430560011202 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_LOG_H #define _XT_LOG_H /* make sure not to change this without changing nf_log.h:NF_LOG_* (!) */ #define XT_LOG_TCPSEQ 0x01 /* Log TCP sequence numbers */ #define XT_LOG_TCPOPT 0x02 /* Log TCP options */ #define XT_LOG_IPOPT 0x04 /* Log IP options */ #define XT_LOG_UID 0x08 /* Log UID owning local socket */ #define XT_LOG_NFLOG 0x10 /* Unsupported, don't reuse */ #define XT_LOG_MACDECODE 0x20 /* Decode MAC header */ #define XT_LOG_MASK 0x2f struct xt_log_info { unsigned char level; unsigned char logflags; char prefix[30]; }; #endif /* _XT_LOG_H */ linux/netfilter/xt_length.h000064400000000335151027430560012050 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_LENGTH_H #define _XT_LENGTH_H #include struct xt_length_info { __u16 min, max; __u8 invert; }; #endif /*_XT_LENGTH_H*/ linux/netfilter/xt_DSCP.h000064400000001271151027430560011320 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* x_tables module for setting the IPv4/IPv6 DSCP field * * (C) 2002 Harald Welte * based on ipt_FTOS.c (C) 2000 by Matthew G. Marsh * This software is distributed under GNU GPL v2, 1991 * * See RFC2474 for a description of the DSCP field within the IP Header. * * xt_DSCP.h,v 1.7 2002/03/14 12:03:13 laforge Exp */ #ifndef _XT_DSCP_TARGET_H #define _XT_DSCP_TARGET_H #include #include /* target info */ struct xt_DSCP_info { __u8 dscp; }; struct xt_tos_target_info { __u8 tos_value; __u8 tos_mask; }; #endif /* _XT_DSCP_TARGET_H */ linux/netfilter/xt_sctp.h000064400000004426151027430560011545 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_SCTP_H_ #define _XT_SCTP_H_ #include #define XT_SCTP_SRC_PORTS 0x01 #define XT_SCTP_DEST_PORTS 0x02 #define XT_SCTP_CHUNK_TYPES 0x04 #define XT_SCTP_VALID_FLAGS 0x07 struct xt_sctp_flag_info { __u8 chunktype; __u8 flag; __u8 flag_mask; }; #define XT_NUM_SCTP_FLAGS 4 struct xt_sctp_info { __u16 dpts[2]; /* Min, Max */ __u16 spts[2]; /* Min, Max */ __u32 chunkmap[256 / sizeof (__u32)]; /* Bit mask of chunks to be matched according to RFC 2960 */ #define SCTP_CHUNK_MATCH_ANY 0x01 /* Match if any of the chunk types are present */ #define SCTP_CHUNK_MATCH_ALL 0x02 /* Match if all of the chunk types are present */ #define SCTP_CHUNK_MATCH_ONLY 0x04 /* Match if these are the only chunk types present */ __u32 chunk_match_type; struct xt_sctp_flag_info flag_info[XT_NUM_SCTP_FLAGS]; int flag_count; __u32 flags; __u32 invflags; }; #define bytes(type) (sizeof(type) * 8) #define SCTP_CHUNKMAP_SET(chunkmap, type) \ do { \ (chunkmap)[type / bytes(__u32)] |= \ 1 << (type % bytes(__u32)); \ } while (0) #define SCTP_CHUNKMAP_CLEAR(chunkmap, type) \ do { \ (chunkmap)[type / bytes(__u32)] &= \ ~(1 << (type % bytes(__u32))); \ } while (0) #define SCTP_CHUNKMAP_IS_SET(chunkmap, type) \ ({ \ ((chunkmap)[type / bytes (__u32)] & \ (1 << (type % bytes (__u32)))) ? 1: 0; \ }) #define SCTP_CHUNKMAP_RESET(chunkmap) \ memset((chunkmap), 0, sizeof(chunkmap)) #define SCTP_CHUNKMAP_SET_ALL(chunkmap) \ memset((chunkmap), ~0U, sizeof(chunkmap)) #define SCTP_CHUNKMAP_COPY(destmap, srcmap) \ memcpy((destmap), (srcmap), sizeof(srcmap)) #define SCTP_CHUNKMAP_IS_CLEAR(chunkmap) \ __sctp_chunkmap_is_clear((chunkmap), ARRAY_SIZE(chunkmap)) static __inline__ _Bool __sctp_chunkmap_is_clear(const __u32 *chunkmap, unsigned int n) { unsigned int i; for (i = 0; i < n; ++i) if (chunkmap[i]) return 0; return 1; } #define SCTP_CHUNKMAP_IS_ALL_SET(chunkmap) \ __sctp_chunkmap_is_all_set((chunkmap), ARRAY_SIZE(chunkmap)) static __inline__ _Bool __sctp_chunkmap_is_all_set(const __u32 *chunkmap, unsigned int n) { unsigned int i; for (i = 0; i < n; ++i) if (chunkmap[i] != ~0U) return 0; return 1; } #endif /* _XT_SCTP_H_ */ linux/netfilter/xt_bpf.h000064400000001647151027430560011345 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_BPF_H #define _XT_BPF_H #include #include #include #define XT_BPF_MAX_NUM_INSTR 64 #define XT_BPF_PATH_MAX (XT_BPF_MAX_NUM_INSTR * sizeof(struct sock_filter)) struct bpf_prog; struct xt_bpf_info { __u16 bpf_program_num_elem; struct sock_filter bpf_program[XT_BPF_MAX_NUM_INSTR]; /* only used in the kernel */ struct bpf_prog *filter __attribute__((aligned(8))); }; enum xt_bpf_modes { XT_BPF_MODE_BYTECODE, XT_BPF_MODE_FD_PINNED, XT_BPF_MODE_FD_ELF, }; #define XT_BPF_MODE_PATH_PINNED XT_BPF_MODE_FD_PINNED struct xt_bpf_info_v1 { __u16 mode; __u16 bpf_program_num_elem; __s32 fd; union { struct sock_filter bpf_program[XT_BPF_MAX_NUM_INSTR]; char path[XT_BPF_PATH_MAX]; }; /* only used in the kernel */ struct bpf_prog *filter __attribute__((aligned(8))); }; #endif /*_XT_BPF_H */ linux/netfilter/xt_AUDIT.h000064400000001316151027430560011435 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Header file for iptables xt_AUDIT target * * (C) 2010-2011 Thomas Graf * (C) 2010-2011 Red Hat, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _XT_AUDIT_TARGET_H #define _XT_AUDIT_TARGET_H #include enum { XT_AUDIT_TYPE_ACCEPT = 0, XT_AUDIT_TYPE_DROP, XT_AUDIT_TYPE_REJECT, __XT_AUDIT_TYPE_MAX, }; #define XT_AUDIT_TYPE_MAX (__XT_AUDIT_TYPE_MAX - 1) struct xt_audit_info { __u8 type; /* XT_AUDIT_TYPE_* */ }; #endif /* _XT_AUDIT_TARGET_H */ linux/netfilter/xt_ecn.h000064400000001340151027430560011331 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* iptables module for matching the ECN header in IPv4 and TCP header * * (C) 2002 Harald Welte * * This software is distributed under GNU GPL v2, 1991 * * ipt_ecn.h,v 1.4 2002/08/05 19:39:00 laforge Exp */ #ifndef _XT_ECN_H #define _XT_ECN_H #include #include #define XT_ECN_IP_MASK (~XT_DSCP_MASK) #define XT_ECN_OP_MATCH_IP 0x01 #define XT_ECN_OP_MATCH_ECE 0x10 #define XT_ECN_OP_MATCH_CWR 0x20 #define XT_ECN_OP_MATCH_MASK 0xce /* match info */ struct xt_ecn_info { __u8 operation; __u8 invert; __u8 ip_ect; union { struct { __u8 ect; } tcp; } proto; }; #endif /* _XT_ECN_H */ linux/netfilter/xt_l2tp.h000064400000001343151027430560011450 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NETFILTER_XT_L2TP_H #define _LINUX_NETFILTER_XT_L2TP_H #include enum xt_l2tp_type { XT_L2TP_TYPE_CONTROL, XT_L2TP_TYPE_DATA, }; /* L2TP matching stuff */ struct xt_l2tp_info { __u32 tid; /* tunnel id */ __u32 sid; /* session id */ __u8 version; /* L2TP protocol version */ __u8 type; /* L2TP packet type */ __u8 flags; /* which fields to match */ }; enum { XT_L2TP_TID = (1 << 0), /* match L2TP tunnel id */ XT_L2TP_SID = (1 << 1), /* match L2TP session id */ XT_L2TP_VERSION = (1 << 2), /* match L2TP protocol version */ XT_L2TP_TYPE = (1 << 3), /* match L2TP packet type */ }; #endif /* _LINUX_NETFILTER_XT_L2TP_H */ linux/netfilter/xt_LED.h000064400000000726151027430560011177 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_LED_H #define _XT_LED_H #include struct xt_led_info { char id[27]; /* Unique ID for this trigger in the LED class */ __u8 always_blink; /* Blink even if the LED is already on */ __u32 delay; /* Delay until LED is switched off after trigger */ /* Kernel data used in the module */ void *internal_data __attribute__((aligned(8))); }; #endif /* _XT_LED_H */ linux/netfilter/x_tables.h000064400000010563151027430560011661 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _X_TABLES_H #define _X_TABLES_H #include #include #define XT_FUNCTION_MAXNAMELEN 30 #define XT_EXTENSION_MAXNAMELEN 29 #define XT_TABLE_MAXNAMELEN 32 struct xt_entry_match { union { struct { __u16 match_size; /* Used by userspace */ char name[XT_EXTENSION_MAXNAMELEN]; __u8 revision; } user; struct { __u16 match_size; /* Used inside the kernel */ struct xt_match *match; } kernel; /* Total length */ __u16 match_size; } u; unsigned char data[0]; }; struct xt_entry_target { union { struct { __u16 target_size; /* Used by userspace */ char name[XT_EXTENSION_MAXNAMELEN]; __u8 revision; } user; struct { __u16 target_size; /* Used inside the kernel */ struct xt_target *target; } kernel; /* Total length */ __u16 target_size; } u; unsigned char data[0]; }; #define XT_TARGET_INIT(__name, __size) \ { \ .target.u.user = { \ .target_size = XT_ALIGN(__size), \ .name = __name, \ }, \ } struct xt_standard_target { struct xt_entry_target target; int verdict; }; struct xt_error_target { struct xt_entry_target target; char errorname[XT_FUNCTION_MAXNAMELEN]; }; /* The argument to IPT_SO_GET_REVISION_*. Returns highest revision * kernel supports, if >= revision. */ struct xt_get_revision { char name[XT_EXTENSION_MAXNAMELEN]; __u8 revision; }; /* CONTINUE verdict for targets */ #define XT_CONTINUE 0xFFFFFFFF /* For standard target */ #define XT_RETURN (-NF_REPEAT - 1) /* this is a dummy structure to find out the alignment requirement for a struct * containing all the fundamental data types that are used in ipt_entry, * ip6t_entry and arpt_entry. This sucks, and it is a hack. It will be my * personal pleasure to remove it -HW */ struct _xt_align { __u8 u8; __u16 u16; __u32 u32; __u64 u64; }; #define XT_ALIGN(s) __ALIGN_KERNEL((s), __alignof__(struct _xt_align)) /* Standard return verdict, or do jump. */ #define XT_STANDARD_TARGET "" /* Error verdict. */ #define XT_ERROR_TARGET "ERROR" #define SET_COUNTER(c,b,p) do { (c).bcnt = (b); (c).pcnt = (p); } while(0) #define ADD_COUNTER(c,b,p) do { (c).bcnt += (b); (c).pcnt += (p); } while(0) struct xt_counters { __u64 pcnt, bcnt; /* Packet and byte counters */ }; /* The argument to IPT_SO_ADD_COUNTERS. */ struct xt_counters_info { /* Which table. */ char name[XT_TABLE_MAXNAMELEN]; unsigned int num_counters; /* The counters (actually `number' of these). */ struct xt_counters counters[0]; }; #define XT_INV_PROTO 0x40 /* Invert the sense of PROTO. */ /* fn returns 0 to continue iteration */ #define XT_MATCH_ITERATE(type, e, fn, args...) \ ({ \ unsigned int __i; \ int __ret = 0; \ struct xt_entry_match *__m; \ \ for (__i = sizeof(type); \ __i < (e)->target_offset; \ __i += __m->u.match_size) { \ __m = (void *)e + __i; \ \ __ret = fn(__m , ## args); \ if (__ret != 0) \ break; \ } \ __ret; \ }) /* fn returns 0 to continue iteration */ #define XT_ENTRY_ITERATE_CONTINUE(type, entries, size, n, fn, args...) \ ({ \ unsigned int __i, __n; \ int __ret = 0; \ type *__entry; \ \ for (__i = 0, __n = 0; __i < (size); \ __i += __entry->next_offset, __n++) { \ __entry = (void *)(entries) + __i; \ if (__n < n) \ continue; \ \ __ret = fn(__entry , ## args); \ if (__ret != 0) \ break; \ } \ __ret; \ }) /* fn returns 0 to continue iteration */ #define XT_ENTRY_ITERATE(type, entries, size, fn, args...) \ XT_ENTRY_ITERATE_CONTINUE(type, entries, size, 0, fn, args) /* pos is normally a struct ipt_entry/ip6t_entry/etc. */ #define xt_entry_foreach(pos, ehead, esize) \ for ((pos) = (typeof(pos))(ehead); \ (pos) < (typeof(pos))((char *)(ehead) + (esize)); \ (pos) = (typeof(pos))((char *)(pos) + (pos)->next_offset)) /* can only be xt_entry_match, so no use of typeof here */ #define xt_ematch_foreach(pos, entry) \ for ((pos) = (struct xt_entry_match *)entry->elems; \ (pos) < (struct xt_entry_match *)((char *)(entry) + \ (entry)->target_offset); \ (pos) = (struct xt_entry_match *)((char *)(pos) + \ (pos)->u.match_size)) #endif /* _X_TABLES_H */ linux/netfilter/xt_addrtype.h000064400000002074151027430560012405 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_ADDRTYPE_H #define _XT_ADDRTYPE_H #include enum { XT_ADDRTYPE_INVERT_SOURCE = 0x0001, XT_ADDRTYPE_INVERT_DEST = 0x0002, XT_ADDRTYPE_LIMIT_IFACE_IN = 0x0004, XT_ADDRTYPE_LIMIT_IFACE_OUT = 0x0008, }; /* rtn_type enum values from rtnetlink.h, but shifted */ enum { XT_ADDRTYPE_UNSPEC = 1 << 0, XT_ADDRTYPE_UNICAST = 1 << 1, /* 1 << RTN_UNICAST */ XT_ADDRTYPE_LOCAL = 1 << 2, /* 1 << RTN_LOCAL, etc */ XT_ADDRTYPE_BROADCAST = 1 << 3, XT_ADDRTYPE_ANYCAST = 1 << 4, XT_ADDRTYPE_MULTICAST = 1 << 5, XT_ADDRTYPE_BLACKHOLE = 1 << 6, XT_ADDRTYPE_UNREACHABLE = 1 << 7, XT_ADDRTYPE_PROHIBIT = 1 << 8, XT_ADDRTYPE_THROW = 1 << 9, XT_ADDRTYPE_NAT = 1 << 10, XT_ADDRTYPE_XRESOLVE = 1 << 11, }; struct xt_addrtype_info_v1 { __u16 source; /* source-type mask */ __u16 dest; /* dest-type mask */ __u32 flags; }; /* revision 0 */ struct xt_addrtype_info { __u16 source; /* source-type mask */ __u16 dest; /* dest-type mask */ __u32 invert_source; __u32 invert_dest; }; #endif linux/netfilter/nfnetlink_cthelper.h000064400000002262151027430560013733 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFNL_CTHELPER_H_ #define _NFNL_CTHELPER_H_ #define NFCT_HELPER_STATUS_DISABLED 0 #define NFCT_HELPER_STATUS_ENABLED 1 enum nfnl_acct_msg_types { NFNL_MSG_CTHELPER_NEW, NFNL_MSG_CTHELPER_GET, NFNL_MSG_CTHELPER_DEL, NFNL_MSG_CTHELPER_MAX }; enum nfnl_cthelper_type { NFCTH_UNSPEC, NFCTH_NAME, NFCTH_TUPLE, NFCTH_QUEUE_NUM, NFCTH_POLICY, NFCTH_PRIV_DATA_LEN, NFCTH_STATUS, __NFCTH_MAX }; #define NFCTH_MAX (__NFCTH_MAX - 1) enum nfnl_cthelper_policy_type { NFCTH_POLICY_SET_UNSPEC, NFCTH_POLICY_SET_NUM, NFCTH_POLICY_SET, NFCTH_POLICY_SET1 = NFCTH_POLICY_SET, NFCTH_POLICY_SET2, NFCTH_POLICY_SET3, NFCTH_POLICY_SET4, __NFCTH_POLICY_SET_MAX }; #define NFCTH_POLICY_SET_MAX (__NFCTH_POLICY_SET_MAX - 1) enum nfnl_cthelper_pol_type { NFCTH_POLICY_UNSPEC, NFCTH_POLICY_NAME, NFCTH_POLICY_EXPECT_MAX, NFCTH_POLICY_EXPECT_TIMEOUT, __NFCTH_POLICY_MAX }; #define NFCTH_POLICY_MAX (__NFCTH_POLICY_MAX - 1) enum nfnl_cthelper_tuple_type { NFCTH_TUPLE_UNSPEC, NFCTH_TUPLE_L3PROTONUM, NFCTH_TUPLE_L4PROTONUM, __NFCTH_TUPLE_MAX, }; #define NFCTH_TUPLE_MAX (__NFCTH_TUPLE_MAX - 1) #endif /* _NFNL_CTHELPER_H */ linux/netfilter/xt_MARK.h000064400000000270151027430560011317 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_MARK_H_target #define _XT_MARK_H_target #include #endif /*_XT_MARK_H_target */ linux/netfilter/xt_helper.h000064400000000274151027430560012050 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_HELPER_H #define _XT_HELPER_H struct xt_helper_info { int invert; char name[30]; }; #endif /* _XT_HELPER_H */ linux/netfilter/xt_socket.h000064400000001200151027430560012047 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_SOCKET_H #define _XT_SOCKET_H #include enum { XT_SOCKET_TRANSPARENT = 1 << 0, XT_SOCKET_NOWILDCARD = 1 << 1, XT_SOCKET_RESTORESKMARK = 1 << 2, }; struct xt_socket_mtinfo1 { __u8 flags; }; #define XT_SOCKET_FLAGS_V1 XT_SOCKET_TRANSPARENT struct xt_socket_mtinfo2 { __u8 flags; }; #define XT_SOCKET_FLAGS_V2 (XT_SOCKET_TRANSPARENT | XT_SOCKET_NOWILDCARD) struct xt_socket_mtinfo3 { __u8 flags; }; #define XT_SOCKET_FLAGS_V3 (XT_SOCKET_TRANSPARENT \ | XT_SOCKET_NOWILDCARD \ | XT_SOCKET_RESTORESKMARK) #endif /* _XT_SOCKET_H */ linux/netfilter/xt_string.h000064400000001230151027430560012070 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_STRING_H #define _XT_STRING_H #include #define XT_STRING_MAX_PATTERN_SIZE 128 #define XT_STRING_MAX_ALGO_NAME_SIZE 16 enum { XT_STRING_FLAG_INVERT = 0x01, XT_STRING_FLAG_IGNORECASE = 0x02 }; struct xt_string_info { __u16 from_offset; __u16 to_offset; char algo[XT_STRING_MAX_ALGO_NAME_SIZE]; char pattern[XT_STRING_MAX_PATTERN_SIZE]; __u8 patlen; union { struct { __u8 invert; } v0; struct { __u8 flags; } v1; } u; /* Used internally by the kernel */ struct ts_config __attribute__((aligned(8))) *config; }; #endif /*_XT_STRING_H*/ linux/netfilter/nfnetlink_conntrack.h000064400000014020151027430560014102 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPCONNTRACK_NETLINK_H #define _IPCONNTRACK_NETLINK_H #include enum cntl_msg_types { IPCTNL_MSG_CT_NEW, IPCTNL_MSG_CT_GET, IPCTNL_MSG_CT_DELETE, IPCTNL_MSG_CT_GET_CTRZERO, IPCTNL_MSG_CT_GET_STATS_CPU, IPCTNL_MSG_CT_GET_STATS, IPCTNL_MSG_CT_GET_DYING, IPCTNL_MSG_CT_GET_UNCONFIRMED, IPCTNL_MSG_MAX }; enum ctnl_exp_msg_types { IPCTNL_MSG_EXP_NEW, IPCTNL_MSG_EXP_GET, IPCTNL_MSG_EXP_DELETE, IPCTNL_MSG_EXP_GET_STATS_CPU, IPCTNL_MSG_EXP_MAX }; enum ctattr_type { CTA_UNSPEC, CTA_TUPLE_ORIG, CTA_TUPLE_REPLY, CTA_STATUS, CTA_PROTOINFO, CTA_HELP, CTA_NAT_SRC, #define CTA_NAT CTA_NAT_SRC /* backwards compatibility */ CTA_TIMEOUT, CTA_MARK, CTA_COUNTERS_ORIG, CTA_COUNTERS_REPLY, CTA_USE, CTA_ID, CTA_NAT_DST, CTA_TUPLE_MASTER, CTA_SEQ_ADJ_ORIG, CTA_NAT_SEQ_ADJ_ORIG = CTA_SEQ_ADJ_ORIG, CTA_SEQ_ADJ_REPLY, CTA_NAT_SEQ_ADJ_REPLY = CTA_SEQ_ADJ_REPLY, CTA_SECMARK, /* obsolete */ CTA_ZONE, CTA_SECCTX, CTA_TIMESTAMP, CTA_MARK_MASK, CTA_LABELS, CTA_LABELS_MASK, CTA_SYNPROXY, CTA_FILTER, CTA_STATUS_MASK, __CTA_MAX }; #define CTA_MAX (__CTA_MAX - 1) enum ctattr_tuple { CTA_TUPLE_UNSPEC, CTA_TUPLE_IP, CTA_TUPLE_PROTO, CTA_TUPLE_ZONE, __CTA_TUPLE_MAX }; #define CTA_TUPLE_MAX (__CTA_TUPLE_MAX - 1) enum ctattr_ip { CTA_IP_UNSPEC, CTA_IP_V4_SRC, CTA_IP_V4_DST, CTA_IP_V6_SRC, CTA_IP_V6_DST, __CTA_IP_MAX }; #define CTA_IP_MAX (__CTA_IP_MAX - 1) enum ctattr_l4proto { CTA_PROTO_UNSPEC, CTA_PROTO_NUM, CTA_PROTO_SRC_PORT, CTA_PROTO_DST_PORT, CTA_PROTO_ICMP_ID, CTA_PROTO_ICMP_TYPE, CTA_PROTO_ICMP_CODE, CTA_PROTO_ICMPV6_ID, CTA_PROTO_ICMPV6_TYPE, CTA_PROTO_ICMPV6_CODE, __CTA_PROTO_MAX }; #define CTA_PROTO_MAX (__CTA_PROTO_MAX - 1) enum ctattr_protoinfo { CTA_PROTOINFO_UNSPEC, CTA_PROTOINFO_TCP, CTA_PROTOINFO_DCCP, CTA_PROTOINFO_SCTP, __CTA_PROTOINFO_MAX }; #define CTA_PROTOINFO_MAX (__CTA_PROTOINFO_MAX - 1) enum ctattr_protoinfo_tcp { CTA_PROTOINFO_TCP_UNSPEC, CTA_PROTOINFO_TCP_STATE, CTA_PROTOINFO_TCP_WSCALE_ORIGINAL, CTA_PROTOINFO_TCP_WSCALE_REPLY, CTA_PROTOINFO_TCP_FLAGS_ORIGINAL, CTA_PROTOINFO_TCP_FLAGS_REPLY, __CTA_PROTOINFO_TCP_MAX }; #define CTA_PROTOINFO_TCP_MAX (__CTA_PROTOINFO_TCP_MAX - 1) enum ctattr_protoinfo_dccp { CTA_PROTOINFO_DCCP_UNSPEC, CTA_PROTOINFO_DCCP_STATE, CTA_PROTOINFO_DCCP_ROLE, CTA_PROTOINFO_DCCP_HANDSHAKE_SEQ, CTA_PROTOINFO_DCCP_PAD, __CTA_PROTOINFO_DCCP_MAX, }; #define CTA_PROTOINFO_DCCP_MAX (__CTA_PROTOINFO_DCCP_MAX - 1) enum ctattr_protoinfo_sctp { CTA_PROTOINFO_SCTP_UNSPEC, CTA_PROTOINFO_SCTP_STATE, CTA_PROTOINFO_SCTP_VTAG_ORIGINAL, CTA_PROTOINFO_SCTP_VTAG_REPLY, __CTA_PROTOINFO_SCTP_MAX }; #define CTA_PROTOINFO_SCTP_MAX (__CTA_PROTOINFO_SCTP_MAX - 1) enum ctattr_counters { CTA_COUNTERS_UNSPEC, CTA_COUNTERS_PACKETS, /* 64bit counters */ CTA_COUNTERS_BYTES, /* 64bit counters */ CTA_COUNTERS32_PACKETS, /* old 32bit counters, unused */ CTA_COUNTERS32_BYTES, /* old 32bit counters, unused */ CTA_COUNTERS_PAD, __CTA_COUNTERS_MAX }; #define CTA_COUNTERS_MAX (__CTA_COUNTERS_MAX - 1) enum ctattr_tstamp { CTA_TIMESTAMP_UNSPEC, CTA_TIMESTAMP_START, CTA_TIMESTAMP_STOP, CTA_TIMESTAMP_PAD, __CTA_TIMESTAMP_MAX }; #define CTA_TIMESTAMP_MAX (__CTA_TIMESTAMP_MAX - 1) enum ctattr_nat { CTA_NAT_UNSPEC, CTA_NAT_V4_MINIP, #define CTA_NAT_MINIP CTA_NAT_V4_MINIP CTA_NAT_V4_MAXIP, #define CTA_NAT_MAXIP CTA_NAT_V4_MAXIP CTA_NAT_PROTO, CTA_NAT_V6_MINIP, CTA_NAT_V6_MAXIP, __CTA_NAT_MAX }; #define CTA_NAT_MAX (__CTA_NAT_MAX - 1) enum ctattr_protonat { CTA_PROTONAT_UNSPEC, CTA_PROTONAT_PORT_MIN, CTA_PROTONAT_PORT_MAX, __CTA_PROTONAT_MAX }; #define CTA_PROTONAT_MAX (__CTA_PROTONAT_MAX - 1) enum ctattr_seqadj { CTA_SEQADJ_UNSPEC, CTA_SEQADJ_CORRECTION_POS, CTA_SEQADJ_OFFSET_BEFORE, CTA_SEQADJ_OFFSET_AFTER, __CTA_SEQADJ_MAX }; #define CTA_SEQADJ_MAX (__CTA_SEQADJ_MAX - 1) enum ctattr_natseq { CTA_NAT_SEQ_UNSPEC, CTA_NAT_SEQ_CORRECTION_POS, CTA_NAT_SEQ_OFFSET_BEFORE, CTA_NAT_SEQ_OFFSET_AFTER, __CTA_NAT_SEQ_MAX }; #define CTA_NAT_SEQ_MAX (__CTA_NAT_SEQ_MAX - 1) enum ctattr_synproxy { CTA_SYNPROXY_UNSPEC, CTA_SYNPROXY_ISN, CTA_SYNPROXY_ITS, CTA_SYNPROXY_TSOFF, __CTA_SYNPROXY_MAX, }; #define CTA_SYNPROXY_MAX (__CTA_SYNPROXY_MAX - 1) enum ctattr_expect { CTA_EXPECT_UNSPEC, CTA_EXPECT_MASTER, CTA_EXPECT_TUPLE, CTA_EXPECT_MASK, CTA_EXPECT_TIMEOUT, CTA_EXPECT_ID, CTA_EXPECT_HELP_NAME, CTA_EXPECT_ZONE, CTA_EXPECT_FLAGS, CTA_EXPECT_CLASS, CTA_EXPECT_NAT, CTA_EXPECT_FN, __CTA_EXPECT_MAX }; #define CTA_EXPECT_MAX (__CTA_EXPECT_MAX - 1) enum ctattr_expect_nat { CTA_EXPECT_NAT_UNSPEC, CTA_EXPECT_NAT_DIR, CTA_EXPECT_NAT_TUPLE, __CTA_EXPECT_NAT_MAX }; #define CTA_EXPECT_NAT_MAX (__CTA_EXPECT_NAT_MAX - 1) enum ctattr_help { CTA_HELP_UNSPEC, CTA_HELP_NAME, CTA_HELP_INFO, __CTA_HELP_MAX }; #define CTA_HELP_MAX (__CTA_HELP_MAX - 1) enum ctattr_secctx { CTA_SECCTX_UNSPEC, CTA_SECCTX_NAME, __CTA_SECCTX_MAX }; #define CTA_SECCTX_MAX (__CTA_SECCTX_MAX - 1) enum ctattr_stats_cpu { CTA_STATS_UNSPEC, CTA_STATS_SEARCHED, /* no longer used */ CTA_STATS_FOUND, CTA_STATS_NEW, /* no longer used */ CTA_STATS_INVALID, CTA_STATS_IGNORE, /* no longer used */ CTA_STATS_DELETE, /* no longer used */ CTA_STATS_DELETE_LIST, /* no longer used */ CTA_STATS_INSERT, CTA_STATS_INSERT_FAILED, CTA_STATS_DROP, CTA_STATS_EARLY_DROP, CTA_STATS_ERROR, CTA_STATS_SEARCH_RESTART, CTA_STATS_CLASH_RESOLVE, __CTA_STATS_MAX, }; #define CTA_STATS_MAX (__CTA_STATS_MAX - 1) enum ctattr_stats_global { CTA_STATS_GLOBAL_UNSPEC, CTA_STATS_GLOBAL_ENTRIES, CTA_STATS_GLOBAL_MAX_ENTRIES, __CTA_STATS_GLOBAL_MAX, }; #define CTA_STATS_GLOBAL_MAX (__CTA_STATS_GLOBAL_MAX - 1) enum ctattr_expect_stats { CTA_STATS_EXP_UNSPEC, CTA_STATS_EXP_NEW, CTA_STATS_EXP_CREATE, CTA_STATS_EXP_DELETE, __CTA_STATS_EXP_MAX, }; #define CTA_STATS_EXP_MAX (__CTA_STATS_EXP_MAX - 1) enum ctattr_filter { CTA_FILTER_UNSPEC, CTA_FILTER_ORIG_FLAGS, CTA_FILTER_REPLY_FLAGS, __CTA_FILTER_MAX }; #define CTA_FILTER_MAX (__CTA_FILTER_MAX - 1) #endif /* _IPCONNTRACK_NETLINK_H */ linux/netfilter/xt_rpfilter.h000064400000000500151027430560012410 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_RPATH_H #define _XT_RPATH_H #include enum { XT_RPFILTER_LOOSE = 1 << 0, XT_RPFILTER_VALID_MARK = 1 << 1, XT_RPFILTER_ACCEPT_LOCAL = 1 << 2, XT_RPFILTER_INVERT = 1 << 3, }; struct xt_rpfilter_info { __u8 flags; }; #endif linux/netfilter/xt_u32.h000064400000001360151027430560011177 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_U32_H #define _XT_U32_H 1 #include enum xt_u32_ops { XT_U32_AND, XT_U32_LEFTSH, XT_U32_RIGHTSH, XT_U32_AT, }; struct xt_u32_location_element { __u32 number; __u8 nextop; }; struct xt_u32_value_element { __u32 min; __u32 max; }; /* * Any way to allow for an arbitrary number of elements? * For now, I settle with a limit of 10 each. */ #define XT_U32_MAXSIZE 10 struct xt_u32_test { struct xt_u32_location_element location[XT_U32_MAXSIZE+1]; struct xt_u32_value_element value[XT_U32_MAXSIZE+1]; __u8 nnums; __u8 nvalues; }; struct xt_u32 { struct xt_u32_test tests[XT_U32_MAXSIZE+1]; __u8 ntests; __u8 invert; }; #endif /* _XT_U32_H */ linux/netfilter/xt_devgroup.h000064400000000655151027430560012427 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_DEVGROUP_H #define _XT_DEVGROUP_H #include enum xt_devgroup_flags { XT_DEVGROUP_MATCH_SRC = 0x1, XT_DEVGROUP_INVERT_SRC = 0x2, XT_DEVGROUP_MATCH_DST = 0x4, XT_DEVGROUP_INVERT_DST = 0x8, }; struct xt_devgroup_info { __u32 flags; __u32 src_group; __u32 src_mask; __u32 dst_group; __u32 dst_mask; }; #endif /* _XT_DEVGROUP_H */ linux/netfilter/xt_conntrack.h000064400000004775151027430560012565 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* Header file for kernel module to match connection tracking information. * GPL (C) 2001 Marc Boucher (marc@mbsi.ca). */ #ifndef _XT_CONNTRACK_H #define _XT_CONNTRACK_H #include #include #include #define XT_CONNTRACK_STATE_BIT(ctinfo) (1 << ((ctinfo)%IP_CT_IS_REPLY+1)) #define XT_CONNTRACK_STATE_INVALID (1 << 0) #define XT_CONNTRACK_STATE_SNAT (1 << (IP_CT_NUMBER + 1)) #define XT_CONNTRACK_STATE_DNAT (1 << (IP_CT_NUMBER + 2)) #define XT_CONNTRACK_STATE_UNTRACKED (1 << (IP_CT_NUMBER + 3)) /* flags, invflags: */ enum { XT_CONNTRACK_STATE = 1 << 0, XT_CONNTRACK_PROTO = 1 << 1, XT_CONNTRACK_ORIGSRC = 1 << 2, XT_CONNTRACK_ORIGDST = 1 << 3, XT_CONNTRACK_REPLSRC = 1 << 4, XT_CONNTRACK_REPLDST = 1 << 5, XT_CONNTRACK_STATUS = 1 << 6, XT_CONNTRACK_EXPIRES = 1 << 7, XT_CONNTRACK_ORIGSRC_PORT = 1 << 8, XT_CONNTRACK_ORIGDST_PORT = 1 << 9, XT_CONNTRACK_REPLSRC_PORT = 1 << 10, XT_CONNTRACK_REPLDST_PORT = 1 << 11, XT_CONNTRACK_DIRECTION = 1 << 12, XT_CONNTRACK_STATE_ALIAS = 1 << 13, }; struct xt_conntrack_mtinfo1 { union nf_inet_addr origsrc_addr, origsrc_mask; union nf_inet_addr origdst_addr, origdst_mask; union nf_inet_addr replsrc_addr, replsrc_mask; union nf_inet_addr repldst_addr, repldst_mask; __u32 expires_min, expires_max; __u16 l4proto; __be16 origsrc_port, origdst_port; __be16 replsrc_port, repldst_port; __u16 match_flags, invert_flags; __u8 state_mask, status_mask; }; struct xt_conntrack_mtinfo2 { union nf_inet_addr origsrc_addr, origsrc_mask; union nf_inet_addr origdst_addr, origdst_mask; union nf_inet_addr replsrc_addr, replsrc_mask; union nf_inet_addr repldst_addr, repldst_mask; __u32 expires_min, expires_max; __u16 l4proto; __be16 origsrc_port, origdst_port; __be16 replsrc_port, repldst_port; __u16 match_flags, invert_flags; __u16 state_mask, status_mask; }; struct xt_conntrack_mtinfo3 { union nf_inet_addr origsrc_addr, origsrc_mask; union nf_inet_addr origdst_addr, origdst_mask; union nf_inet_addr replsrc_addr, replsrc_mask; union nf_inet_addr repldst_addr, repldst_mask; __u32 expires_min, expires_max; __u16 l4proto; __u16 origsrc_port, origdst_port; __u16 replsrc_port, repldst_port; __u16 match_flags, invert_flags; __u16 state_mask, status_mask; __u16 origsrc_port_high, origdst_port_high; __u16 replsrc_port_high, repldst_port_high; }; #endif /*_XT_CONNTRACK_H*/ linux/netfilter/xt_SYNPROXY.h000064400000000643151027430560012104 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_SYNPROXY_H #define _XT_SYNPROXY_H #include #define XT_SYNPROXY_OPT_MSS 0x01 #define XT_SYNPROXY_OPT_WSCALE 0x02 #define XT_SYNPROXY_OPT_SACK_PERM 0x04 #define XT_SYNPROXY_OPT_TIMESTAMP 0x08 #define XT_SYNPROXY_OPT_ECN 0x10 struct xt_synproxy_info { __u8 options; __u8 wscale; __u16 mss; }; #endif /* _XT_SYNPROXY_H */ linux/netfilter/xt_policy.h000064400000001776151027430560012100 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_POLICY_H #define _XT_POLICY_H #include #include #include #define XT_POLICY_MAX_ELEM 4 enum xt_policy_flags { XT_POLICY_MATCH_IN = 0x1, XT_POLICY_MATCH_OUT = 0x2, XT_POLICY_MATCH_NONE = 0x4, XT_POLICY_MATCH_STRICT = 0x8, }; enum xt_policy_modes { XT_POLICY_MODE_TRANSPORT, XT_POLICY_MODE_TUNNEL }; struct xt_policy_spec { __u8 saddr:1, daddr:1, proto:1, mode:1, spi:1, reqid:1; }; union xt_policy_addr { struct in_addr a4; struct in6_addr a6; }; struct xt_policy_elem { union { struct { union xt_policy_addr saddr; union xt_policy_addr smask; union xt_policy_addr daddr; union xt_policy_addr dmask; }; }; __be32 spi; __u32 reqid; __u8 proto; __u8 mode; struct xt_policy_spec match; struct xt_policy_spec invert; }; struct xt_policy_info { struct xt_policy_elem pol[XT_POLICY_MAX_ELEM]; __u16 flags; __u16 len; }; #endif /* _XT_POLICY_H */ linux/netfilter/nfnetlink_queue.h000064400000006653151027430560013261 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFNETLINK_QUEUE_H #define _NFNETLINK_QUEUE_H #include #include enum nfqnl_msg_types { NFQNL_MSG_PACKET, /* packet from kernel to userspace */ NFQNL_MSG_VERDICT, /* verdict from userspace to kernel */ NFQNL_MSG_CONFIG, /* connect to a particular queue */ NFQNL_MSG_VERDICT_BATCH, /* batchv from userspace to kernel */ NFQNL_MSG_MAX }; struct nfqnl_msg_packet_hdr { __be32 packet_id; /* unique ID of packet in queue */ __be16 hw_protocol; /* hw protocol (network order) */ __u8 hook; /* netfilter hook */ } __attribute__ ((packed)); struct nfqnl_msg_packet_hw { __be16 hw_addrlen; __u16 _pad; __u8 hw_addr[8]; }; struct nfqnl_msg_packet_timestamp { __aligned_be64 sec; __aligned_be64 usec; }; enum nfqnl_vlan_attr { NFQA_VLAN_UNSPEC, NFQA_VLAN_PROTO, /* __be16 skb vlan_proto */ NFQA_VLAN_TCI, /* __be16 skb htons(vlan_tci) */ __NFQA_VLAN_MAX, }; #define NFQA_VLAN_MAX (__NFQA_VLAN_MAX - 1) enum nfqnl_attr_type { NFQA_UNSPEC, NFQA_PACKET_HDR, NFQA_VERDICT_HDR, /* nfqnl_msg_verdict_hrd */ NFQA_MARK, /* __u32 nfmark */ NFQA_TIMESTAMP, /* nfqnl_msg_packet_timestamp */ NFQA_IFINDEX_INDEV, /* __u32 ifindex */ NFQA_IFINDEX_OUTDEV, /* __u32 ifindex */ NFQA_IFINDEX_PHYSINDEV, /* __u32 ifindex */ NFQA_IFINDEX_PHYSOUTDEV, /* __u32 ifindex */ NFQA_HWADDR, /* nfqnl_msg_packet_hw */ NFQA_PAYLOAD, /* opaque data payload */ NFQA_CT, /* nf_conntrack_netlink.h */ NFQA_CT_INFO, /* enum ip_conntrack_info */ NFQA_CAP_LEN, /* __u32 length of captured packet */ NFQA_SKB_INFO, /* __u32 skb meta information */ NFQA_EXP, /* nf_conntrack_netlink.h */ NFQA_UID, /* __u32 sk uid */ NFQA_GID, /* __u32 sk gid */ NFQA_SECCTX, /* security context string */ NFQA_VLAN, /* nested attribute: packet vlan info */ NFQA_L2HDR, /* full L2 header */ __NFQA_MAX }; #define NFQA_MAX (__NFQA_MAX - 1) struct nfqnl_msg_verdict_hdr { __be32 verdict; __be32 id; }; enum nfqnl_msg_config_cmds { NFQNL_CFG_CMD_NONE, NFQNL_CFG_CMD_BIND, NFQNL_CFG_CMD_UNBIND, NFQNL_CFG_CMD_PF_BIND, NFQNL_CFG_CMD_PF_UNBIND, }; struct nfqnl_msg_config_cmd { __u8 command; /* nfqnl_msg_config_cmds */ __u8 _pad; __be16 pf; /* AF_xxx for PF_[UN]BIND */ }; enum nfqnl_config_mode { NFQNL_COPY_NONE, NFQNL_COPY_META, NFQNL_COPY_PACKET, }; struct nfqnl_msg_config_params { __be32 copy_range; __u8 copy_mode; /* enum nfqnl_config_mode */ } __attribute__ ((packed)); enum nfqnl_attr_config { NFQA_CFG_UNSPEC, NFQA_CFG_CMD, /* nfqnl_msg_config_cmd */ NFQA_CFG_PARAMS, /* nfqnl_msg_config_params */ NFQA_CFG_QUEUE_MAXLEN, /* __u32 */ NFQA_CFG_MASK, /* identify which flags to change */ NFQA_CFG_FLAGS, /* value of these flags (__u32) */ __NFQA_CFG_MAX }; #define NFQA_CFG_MAX (__NFQA_CFG_MAX-1) /* Flags for NFQA_CFG_FLAGS */ #define NFQA_CFG_F_FAIL_OPEN (1 << 0) #define NFQA_CFG_F_CONNTRACK (1 << 1) #define NFQA_CFG_F_GSO (1 << 2) #define NFQA_CFG_F_UID_GID (1 << 3) #define NFQA_CFG_F_SECCTX (1 << 4) #define NFQA_CFG_F_MAX (1 << 5) /* flags for NFQA_SKB_INFO */ /* packet appears to have wrong checksums, but they are ok */ #define NFQA_SKB_CSUMNOTREADY (1 << 0) /* packet is GSO (i.e., exceeds device mtu) */ #define NFQA_SKB_GSO (1 << 1) /* csum not validated (incoming device doesn't support hw checksum, etc.) */ #define NFQA_SKB_CSUM_NOTVERIFIED (1 << 2) #endif /* _NFNETLINK_QUEUE_H */ linux/netfilter/nf_conntrack_common.h000064400000010754151027430560014077 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NF_CONNTRACK_COMMON_H #define _NF_CONNTRACK_COMMON_H /* Connection state tracking for netfilter. This is separated from, but required by, the NAT layer; it can also be used by an iptables extension. */ enum ip_conntrack_info { /* Part of an established connection (either direction). */ IP_CT_ESTABLISHED, /* Like NEW, but related to an existing connection, or ICMP error (in either direction). */ IP_CT_RELATED, /* Started a new connection to track (only IP_CT_DIR_ORIGINAL); may be a retransmission. */ IP_CT_NEW, /* >= this indicates reply direction */ IP_CT_IS_REPLY, IP_CT_ESTABLISHED_REPLY = IP_CT_ESTABLISHED + IP_CT_IS_REPLY, IP_CT_RELATED_REPLY = IP_CT_RELATED + IP_CT_IS_REPLY, /* No NEW in reply direction. */ /* Number of distinct IP_CT types. */ IP_CT_NUMBER, /* only for userspace compatibility */ IP_CT_NEW_REPLY = IP_CT_NUMBER, }; #define NF_CT_STATE_INVALID_BIT (1 << 0) #define NF_CT_STATE_BIT(ctinfo) (1 << ((ctinfo) % IP_CT_IS_REPLY + 1)) #define NF_CT_STATE_UNTRACKED_BIT (1 << 6) /* Bitset representing status of connection. */ enum ip_conntrack_status { /* It's an expected connection: bit 0 set. This bit never changed */ IPS_EXPECTED_BIT = 0, IPS_EXPECTED = (1 << IPS_EXPECTED_BIT), /* We've seen packets both ways: bit 1 set. Can be set, not unset. */ IPS_SEEN_REPLY_BIT = 1, IPS_SEEN_REPLY = (1 << IPS_SEEN_REPLY_BIT), /* Conntrack should never be early-expired. */ IPS_ASSURED_BIT = 2, IPS_ASSURED = (1 << IPS_ASSURED_BIT), /* Connection is confirmed: originating packet has left box */ IPS_CONFIRMED_BIT = 3, IPS_CONFIRMED = (1 << IPS_CONFIRMED_BIT), /* Connection needs src nat in orig dir. This bit never changed. */ IPS_SRC_NAT_BIT = 4, IPS_SRC_NAT = (1 << IPS_SRC_NAT_BIT), /* Connection needs dst nat in orig dir. This bit never changed. */ IPS_DST_NAT_BIT = 5, IPS_DST_NAT = (1 << IPS_DST_NAT_BIT), /* Both together. */ IPS_NAT_MASK = (IPS_DST_NAT | IPS_SRC_NAT), /* Connection needs TCP sequence adjusted. */ IPS_SEQ_ADJUST_BIT = 6, IPS_SEQ_ADJUST = (1 << IPS_SEQ_ADJUST_BIT), /* NAT initialization bits. */ IPS_SRC_NAT_DONE_BIT = 7, IPS_SRC_NAT_DONE = (1 << IPS_SRC_NAT_DONE_BIT), IPS_DST_NAT_DONE_BIT = 8, IPS_DST_NAT_DONE = (1 << IPS_DST_NAT_DONE_BIT), /* Both together */ IPS_NAT_DONE_MASK = (IPS_DST_NAT_DONE | IPS_SRC_NAT_DONE), /* Connection is dying (removed from lists), can not be unset. */ IPS_DYING_BIT = 9, IPS_DYING = (1 << IPS_DYING_BIT), /* Connection has fixed timeout. */ IPS_FIXED_TIMEOUT_BIT = 10, IPS_FIXED_TIMEOUT = (1 << IPS_FIXED_TIMEOUT_BIT), /* Conntrack is a template */ IPS_TEMPLATE_BIT = 11, IPS_TEMPLATE = (1 << IPS_TEMPLATE_BIT), /* Conntrack is a fake untracked entry. Obsolete and not used anymore */ IPS_UNTRACKED_BIT = 12, IPS_UNTRACKED = (1 << IPS_UNTRACKED_BIT), /* Conntrack got a helper explicitly attached (ruleset, ctnetlink). */ IPS_HELPER_BIT = 13, IPS_HELPER = (1 << IPS_HELPER_BIT), /* Conntrack has been offloaded to flow table. */ IPS_OFFLOAD_BIT = 14, IPS_OFFLOAD = (1 << IPS_OFFLOAD_BIT), /* Conntrack has been offloaded to hardware. */ IPS_HW_OFFLOAD_BIT = 15, IPS_HW_OFFLOAD = (1 << IPS_HW_OFFLOAD_BIT), /* Be careful here, modifying these bits can make things messy, * so don't let users modify them directly. */ IPS_UNCHANGEABLE_MASK = (IPS_NAT_DONE_MASK | IPS_NAT_MASK | IPS_EXPECTED | IPS_CONFIRMED | IPS_DYING | IPS_SEQ_ADJUST | IPS_TEMPLATE | IPS_UNTRACKED | IPS_OFFLOAD | IPS_HW_OFFLOAD), __IPS_MAX_BIT = 16, }; /* Connection tracking event types */ enum ip_conntrack_events { IPCT_NEW, /* new conntrack */ IPCT_RELATED, /* related conntrack */ IPCT_DESTROY, /* destroyed conntrack */ IPCT_REPLY, /* connection has seen two-way traffic */ IPCT_ASSURED, /* connection status has changed to assured */ IPCT_PROTOINFO, /* protocol information has changed */ IPCT_HELPER, /* new helper has been set */ IPCT_MARK, /* new mark has been set */ IPCT_SEQADJ, /* sequence adjustment has changed */ IPCT_NATSEQADJ = IPCT_SEQADJ, IPCT_SECMARK, /* new security mark has been set */ IPCT_LABEL, /* new connlabel has been set */ IPCT_SYNPROXY, /* synproxy has been set */ }; enum ip_conntrack_expect_events { IPEXP_NEW, /* new expectation */ IPEXP_DESTROY, /* destroyed expectation */ }; /* expectation flags */ #define NF_CT_EXPECT_PERMANENT 0x1 #define NF_CT_EXPECT_INACTIVE 0x2 #define NF_CT_EXPECT_USERSPACE 0x4 #endif /* _NF_CONNTRACK_COMMON_H */ linux/netfilter/nfnetlink_log.h000064400000005357151027430560012716 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFNETLINK_LOG_H #define _NFNETLINK_LOG_H /* This file describes the netlink messages (i.e. 'protocol packets'), * and not any kind of function definitions. It is shared between kernel and * userspace. Don't put kernel specific stuff in here */ #include #include enum nfulnl_msg_types { NFULNL_MSG_PACKET, /* packet from kernel to userspace */ NFULNL_MSG_CONFIG, /* connect to a particular queue */ NFULNL_MSG_MAX }; struct nfulnl_msg_packet_hdr { __be16 hw_protocol; /* hw protocol (network order) */ __u8 hook; /* netfilter hook */ __u8 _pad; }; struct nfulnl_msg_packet_hw { __be16 hw_addrlen; __u16 _pad; __u8 hw_addr[8]; }; struct nfulnl_msg_packet_timestamp { __aligned_be64 sec; __aligned_be64 usec; }; enum nfulnl_attr_type { NFULA_UNSPEC, NFULA_PACKET_HDR, NFULA_MARK, /* __u32 nfmark */ NFULA_TIMESTAMP, /* nfulnl_msg_packet_timestamp */ NFULA_IFINDEX_INDEV, /* __u32 ifindex */ NFULA_IFINDEX_OUTDEV, /* __u32 ifindex */ NFULA_IFINDEX_PHYSINDEV, /* __u32 ifindex */ NFULA_IFINDEX_PHYSOUTDEV, /* __u32 ifindex */ NFULA_HWADDR, /* nfulnl_msg_packet_hw */ NFULA_PAYLOAD, /* opaque data payload */ NFULA_PREFIX, /* string prefix */ NFULA_UID, /* user id of socket */ NFULA_SEQ, /* instance-local sequence number */ NFULA_SEQ_GLOBAL, /* global sequence number */ NFULA_GID, /* group id of socket */ NFULA_HWTYPE, /* hardware type */ NFULA_HWHEADER, /* hardware header */ NFULA_HWLEN, /* hardware header length */ NFULA_CT, /* nf_conntrack_netlink.h */ NFULA_CT_INFO, /* enum ip_conntrack_info */ __NFULA_MAX }; #define NFULA_MAX (__NFULA_MAX - 1) enum nfulnl_msg_config_cmds { NFULNL_CFG_CMD_NONE, NFULNL_CFG_CMD_BIND, NFULNL_CFG_CMD_UNBIND, NFULNL_CFG_CMD_PF_BIND, NFULNL_CFG_CMD_PF_UNBIND, }; struct nfulnl_msg_config_cmd { __u8 command; /* nfulnl_msg_config_cmds */ } __attribute__ ((packed)); struct nfulnl_msg_config_mode { __be32 copy_range; __u8 copy_mode; __u8 _pad; } __attribute__ ((packed)); enum nfulnl_attr_config { NFULA_CFG_UNSPEC, NFULA_CFG_CMD, /* nfulnl_msg_config_cmd */ NFULA_CFG_MODE, /* nfulnl_msg_config_mode */ NFULA_CFG_NLBUFSIZ, /* __u32 buffer size */ NFULA_CFG_TIMEOUT, /* __u32 in 1/100 s */ NFULA_CFG_QTHRESH, /* __u32 */ NFULA_CFG_FLAGS, /* __u16 */ __NFULA_CFG_MAX }; #define NFULA_CFG_MAX (__NFULA_CFG_MAX -1) #define NFULNL_COPY_NONE 0x00 #define NFULNL_COPY_META 0x01 #define NFULNL_COPY_PACKET 0x02 /* 0xff is reserved, don't use it for new copy modes. */ #define NFULNL_CFG_F_SEQ 0x0001 #define NFULNL_CFG_F_SEQ_GLOBAL 0x0002 #define NFULNL_CFG_F_CONNTRACK 0x0004 #endif /* _NFNETLINK_LOG_H */ linux/netfilter/xt_cpu.h000064400000000307151027430560011355 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CPU_H #define _XT_CPU_H #include struct xt_cpu_info { __u32 cpu; __u32 invert; }; #endif /*_XT_CPU_H*/ linux/netfilter/xt_TPROXY.h000064400000001077151027430560011640 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_TPROXY_H #define _XT_TPROXY_H #include #include /* TPROXY target is capable of marking the packet to perform * redirection. We can get rid of that whenever we get support for * mutliple targets in the same rule. */ struct xt_tproxy_target_info { __u32 mark_mask; __u32 mark_value; __be32 laddr; __be16 lport; }; struct xt_tproxy_target_info_v1 { __u32 mark_mask; __u32 mark_value; union nf_inet_addr laddr; __be16 lport; }; #endif /* _XT_TPROXY_H */ linux/netfilter/xt_IDLETIMER.h000064400000002561151027430560012110 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/include/linux/netfilter/xt_IDLETIMER.h * * Header file for Xtables timer target module. * * Copyright (C) 2004, 2010 Nokia Corporation * Written by Timo Teras * * Converted to x_tables and forward-ported to 2.6.34 * by Luciano Coelho * * Contact: Luciano Coelho * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef _XT_IDLETIMER_H #define _XT_IDLETIMER_H #include #define MAX_IDLETIMER_LABEL_SIZE 28 struct idletimer_tg_info { __u32 timeout; char label[MAX_IDLETIMER_LABEL_SIZE]; /* for kernel module internal use only */ struct idletimer_tg *timer __attribute__((aligned(8))); }; #endif linux/netfilter/xt_dscp.h000064400000001275151027430560011524 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* x_tables module for matching the IPv4/IPv6 DSCP field * * (C) 2002 Harald Welte * This software is distributed under GNU GPL v2, 1991 * * See RFC2474 for a description of the DSCP field within the IP Header. * * xt_dscp.h,v 1.3 2002/08/05 19:00:21 laforge Exp */ #ifndef _XT_DSCP_H #define _XT_DSCP_H #include #define XT_DSCP_MASK 0xfc /* 11111100 */ #define XT_DSCP_SHIFT 2 #define XT_DSCP_MAX 0x3f /* 00111111 */ /* match info */ struct xt_dscp_info { __u8 dscp; __u8 invert; }; struct xt_tos_match_info { __u8 tos_mask; __u8 tos_value; __u8 invert; }; #endif /* _XT_DSCP_H */ linux/netfilter/nf_osf.h000064400000003634151027430560011333 0ustar00#ifndef _NF_OSF_H #define _NF_OSF_H #include #define MAXGENRELEN 32 #define NF_OSF_GENRE (1 << 0) #define NF_OSF_TTL (1 << 1) #define NF_OSF_LOG (1 << 2) #define NF_OSF_INVERT (1 << 3) #define NF_OSF_LOGLEVEL_ALL 0 /* log all matched fingerprints */ #define NF_OSF_LOGLEVEL_FIRST 1 /* log only the first matced fingerprint */ #define NF_OSF_LOGLEVEL_ALL_KNOWN 2 /* do not log unknown packets */ #define NF_OSF_TTL_TRUE 0 /* True ip and fingerprint TTL comparison */ /* Do not compare ip and fingerprint TTL at all */ #define NF_OSF_TTL_NOCHECK 2 /* Wildcard MSS (kind of). * It is used to implement a state machine for the different wildcard values * of the MSS and window sizes. */ struct nf_osf_wc { __u32 wc; __u32 val; }; /* This struct represents IANA options * http://www.iana.org/assignments/tcp-parameters */ struct nf_osf_opt { __u16 kind, length; struct nf_osf_wc wc; }; struct nf_osf_info { char genre[MAXGENRELEN]; __u32 len; __u32 flags; __u32 loglevel; __u32 ttl; }; struct nf_osf_user_finger { struct nf_osf_wc wss; __u8 ttl, df; __u16 ss, mss; __u16 opt_num; char genre[MAXGENRELEN]; char version[MAXGENRELEN]; char subtype[MAXGENRELEN]; /* MAX_IPOPTLEN is maximum if all options are NOPs or EOLs */ struct nf_osf_opt opt[MAX_IPOPTLEN]; }; struct nf_osf_nlmsg { struct nf_osf_user_finger f; struct iphdr ip; struct tcphdr tcp; }; /* Defines for IANA option kinds */ enum iana_options { OSFOPT_EOL = 0, /* End of options */ OSFOPT_NOP, /* NOP */ OSFOPT_MSS, /* Maximum segment size */ OSFOPT_WSO, /* Window scale option */ OSFOPT_SACKP, /* SACK permitted */ OSFOPT_SACK, /* SACK */ OSFOPT_ECHO, OSFOPT_ECHOREPLY, OSFOPT_TS, /* Timestamp option */ OSFOPT_POCP, /* Partial Order Connection Permitted */ OSFOPT_POSP, /* Partial Order Service Profile */ /* Others are not used in the current OSF */ OSFOPT_EMPTY = 255, }; #endif /* _NF_OSF_H */ linux/netfilter/xt_ipcomp.h000064400000000745151027430560012063 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_IPCOMP_H #define _XT_IPCOMP_H #include struct xt_ipcomp { __u32 spis[2]; /* Security Parameter Index */ __u8 invflags; /* Inverse flags */ __u8 hdrres; /* Test of the Reserved Filed */ }; /* Values for "invflags" field in struct xt_ipcomp. */ #define XT_IPCOMP_INV_SPI 0x01 /* Invert the sense of spi. */ #define XT_IPCOMP_INV_MASK 0x01 /* All possible flags. */ #endif /*_XT_IPCOMP_H*/ linux/netfilter/xt_physdev.h000064400000001051151027430560012245 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_PHYSDEV_H #define _XT_PHYSDEV_H #include #include #define XT_PHYSDEV_OP_IN 0x01 #define XT_PHYSDEV_OP_OUT 0x02 #define XT_PHYSDEV_OP_BRIDGED 0x04 #define XT_PHYSDEV_OP_ISIN 0x08 #define XT_PHYSDEV_OP_ISOUT 0x10 #define XT_PHYSDEV_OP_MASK (0x20 - 1) struct xt_physdev_info { char physindev[IFNAMSIZ]; char in_mask[IFNAMSIZ]; char physoutdev[IFNAMSIZ]; char out_mask[IFNAMSIZ]; __u8 invert; __u8 bitmask; }; #endif /* _XT_PHYSDEV_H */ linux/netfilter/xt_SECMARK.h000064400000001210151027430560011645 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_SECMARK_H_target #define _XT_SECMARK_H_target #include /* * This is intended for use by various security subsystems (but not * at the same time). * * 'mode' refers to the specific security subsystem which the * packets are being marked for. */ #define SECMARK_MODE_SEL 0x01 /* SELinux */ #define SECMARK_SECCTX_MAX 256 struct xt_secmark_target_info { __u8 mode; __u32 secid; char secctx[SECMARK_SECCTX_MAX]; }; struct xt_secmark_target_info_v1 { __u8 mode; char secctx[SECMARK_SECCTX_MAX]; __u32 secid; }; #endif /*_XT_SECMARK_H_target */ linux/netfilter/xt_mac.h000064400000000343151027430560011326 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_MAC_H #define _XT_MAC_H #include struct xt_mac_info { unsigned char srcaddr[ETH_ALEN]; int invert; }; #endif /*_XT_MAC_H*/ linux/netfilter/xt_CLASSIFY.h000064400000000331151027430560012000 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CLASSIFY_H #define _XT_CLASSIFY_H #include struct xt_classify_target_info { __u32 priority; }; #endif /*_XT_CLASSIFY_H */ linux/netfilter/xt_rateest.h000064400000001533151027430560012237 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_RATEEST_MATCH_H #define _XT_RATEEST_MATCH_H #include #include enum xt_rateest_match_flags { XT_RATEEST_MATCH_INVERT = 1<<0, XT_RATEEST_MATCH_ABS = 1<<1, XT_RATEEST_MATCH_REL = 1<<2, XT_RATEEST_MATCH_DELTA = 1<<3, XT_RATEEST_MATCH_BPS = 1<<4, XT_RATEEST_MATCH_PPS = 1<<5, }; enum xt_rateest_match_mode { XT_RATEEST_MATCH_NONE, XT_RATEEST_MATCH_EQ, XT_RATEEST_MATCH_LT, XT_RATEEST_MATCH_GT, }; struct xt_rateest_match_info { char name1[IFNAMSIZ]; char name2[IFNAMSIZ]; __u16 flags; __u16 mode; __u32 bps1; __u32 pps1; __u32 bps2; __u32 pps2; /* Used internally by the kernel */ struct xt_rateest *est1 __attribute__((aligned(8))); struct xt_rateest *est2 __attribute__((aligned(8))); }; #endif /* _XT_RATEEST_MATCH_H */ linux/netfilter/xt_CT.h000064400000001525151027430560011077 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CT_H #define _XT_CT_H #include enum { XT_CT_NOTRACK = 1 << 0, XT_CT_NOTRACK_ALIAS = 1 << 1, XT_CT_ZONE_DIR_ORIG = 1 << 2, XT_CT_ZONE_DIR_REPL = 1 << 3, XT_CT_ZONE_MARK = 1 << 4, XT_CT_MASK = XT_CT_NOTRACK | XT_CT_NOTRACK_ALIAS | XT_CT_ZONE_DIR_ORIG | XT_CT_ZONE_DIR_REPL | XT_CT_ZONE_MARK, }; struct xt_ct_target_info { __u16 flags; __u16 zone; __u32 ct_events; __u32 exp_events; char helper[16]; /* Used internally by the kernel */ struct nf_conn *ct __attribute__((aligned(8))); }; struct xt_ct_target_info_v1 { __u16 flags; __u16 zone; __u32 ct_events; __u32 exp_events; char helper[16]; char timeout[32]; /* Used internally by the kernel */ struct nf_conn *ct __attribute__((aligned(8))); }; #endif /* _XT_CT_H */ linux/netfilter/xt_quota.h000064400000000620151027430560011715 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_QUOTA_H #define _XT_QUOTA_H #include enum xt_quota_flags { XT_QUOTA_INVERT = 0x1, }; #define XT_QUOTA_MASK 0x1 struct xt_quota_priv; struct xt_quota_info { __u32 flags; __u32 pad; __aligned_u64 quota; /* Used internally by the kernel */ struct xt_quota_priv *master; }; #endif /* _XT_QUOTA_H */ linux/netfilter/xt_esp.h000064400000000642151027430560011357 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_ESP_H #define _XT_ESP_H #include struct xt_esp { __u32 spis[2]; /* Security Parameter Index */ __u8 invflags; /* Inverse flags */ }; /* Values for "invflags" field in struct xt_esp. */ #define XT_ESP_INV_SPI 0x01 /* Invert the sense of spi. */ #define XT_ESP_INV_MASK 0x01 /* All possible flags. */ #endif /*_XT_ESP_H*/ linux/netfilter/nfnetlink_compat.h000064400000004614151027430560013413 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NFNETLINK_COMPAT_H #define _NFNETLINK_COMPAT_H #include /* Old nfnetlink macros for userspace */ /* nfnetlink groups: Up to 32 maximum */ #define NF_NETLINK_CONNTRACK_NEW 0x00000001 #define NF_NETLINK_CONNTRACK_UPDATE 0x00000002 #define NF_NETLINK_CONNTRACK_DESTROY 0x00000004 #define NF_NETLINK_CONNTRACK_EXP_NEW 0x00000008 #define NF_NETLINK_CONNTRACK_EXP_UPDATE 0x00000010 #define NF_NETLINK_CONNTRACK_EXP_DESTROY 0x00000020 /* Generic structure for encapsulation optional netfilter information. * It is reminiscent of sockaddr, but with sa_family replaced * with attribute type. * ! This should someday be put somewhere generic as now rtnetlink and * ! nfnetlink use the same attributes methods. - J. Schulist. */ struct nfattr { __u16 nfa_len; __u16 nfa_type; /* we use 15 bits for the type, and the highest * bit to indicate whether the payload is nested */ }; /* FIXME: Apart from NFNL_NFA_NESTED shamelessly copy and pasted from * rtnetlink.h, it's time to put this in a generic file */ #define NFNL_NFA_NEST 0x8000 #define NFA_TYPE(attr) ((attr)->nfa_type & 0x7fff) #define NFA_ALIGNTO 4 #define NFA_ALIGN(len) (((len) + NFA_ALIGNTO - 1) & ~(NFA_ALIGNTO - 1)) #define NFA_OK(nfa,len) ((len) > 0 && (nfa)->nfa_len >= sizeof(struct nfattr) \ && (nfa)->nfa_len <= (len)) #define NFA_NEXT(nfa,attrlen) ((attrlen) -= NFA_ALIGN((nfa)->nfa_len), \ (struct nfattr *)(((char *)(nfa)) + NFA_ALIGN((nfa)->nfa_len))) #define NFA_LENGTH(len) (NFA_ALIGN(sizeof(struct nfattr)) + (len)) #define NFA_SPACE(len) NFA_ALIGN(NFA_LENGTH(len)) #define NFA_DATA(nfa) ((void *)(((char *)(nfa)) + NFA_LENGTH(0))) #define NFA_PAYLOAD(nfa) ((int)((nfa)->nfa_len) - NFA_LENGTH(0)) #define NFA_NEST(skb, type) \ ({ struct nfattr *__start = (struct nfattr *)skb_tail_pointer(skb); \ NFA_PUT(skb, (NFNL_NFA_NEST | type), 0, NULL); \ __start; }) #define NFA_NEST_END(skb, start) \ ({ (start)->nfa_len = skb_tail_pointer(skb) - (unsigned char *)(start); \ (skb)->len; }) #define NFA_NEST_CANCEL(skb, start) \ ({ if (start) \ skb_trim(skb, (unsigned char *) (start) - (skb)->data); \ -1; }) #define NFM_NFA(n) ((struct nfattr *)(((char *)(n)) \ + NLMSG_ALIGN(sizeof(struct nfgenmsg)))) #define NFM_PAYLOAD(n) NLMSG_PAYLOAD(n, sizeof(struct nfgenmsg)) #endif /* _NFNETLINK_COMPAT_H */ linux/netfilter/xt_dccp.h000064400000000743151027430560011503 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_DCCP_H_ #define _XT_DCCP_H_ #include #define XT_DCCP_SRC_PORTS 0x01 #define XT_DCCP_DEST_PORTS 0x02 #define XT_DCCP_TYPE 0x04 #define XT_DCCP_OPTION 0x08 #define XT_DCCP_VALID_FLAGS 0x0f struct xt_dccp_info { __u16 dpts[2]; /* Min, Max */ __u16 spts[2]; /* Min, Max */ __u16 flags; __u16 invflags; __u16 typemask; __u8 option; }; #endif /* _XT_DCCP_H_ */ linux/netfilter/xt_RATEEST.h000064400000000606151027430560011677 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_RATEEST_TARGET_H #define _XT_RATEEST_TARGET_H #include #include struct xt_rateest_target_info { char name[IFNAMSIZ]; __s8 interval; __u8 ewma_log; /* Used internally by the kernel */ struct xt_rateest *est __attribute__((aligned(8))); }; #endif /* _XT_RATEEST_TARGET_H */ linux/netfilter/xt_cgroup.h000064400000000717151027430560012072 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CGROUP_H #define _XT_CGROUP_H #include #include struct xt_cgroup_info_v0 { __u32 id; __u32 invert; }; struct xt_cgroup_info_v1 { __u8 has_path; __u8 has_classid; __u8 invert_path; __u8 invert_classid; char path[PATH_MAX]; __u32 classid; /* kernel internal data */ void *priv __attribute__((aligned(8))); }; #endif /* _XT_CGROUP_H */ linux/netfilter/xt_connbytes.h000064400000001101151027430560012563 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CONNBYTES_H #define _XT_CONNBYTES_H #include enum xt_connbytes_what { XT_CONNBYTES_PKTS, XT_CONNBYTES_BYTES, XT_CONNBYTES_AVGPKT, }; enum xt_connbytes_direction { XT_CONNBYTES_DIR_ORIGINAL, XT_CONNBYTES_DIR_REPLY, XT_CONNBYTES_DIR_BOTH, }; struct xt_connbytes_info { struct { __aligned_u64 from; /* count to be matched */ __aligned_u64 to; /* count to be matched */ } count; __u8 what; /* ipt_connbytes_what */ __u8 direction; /* ipt_connbytes_direction */ }; #endif linux/netfilter/xt_HMARK.h000064400000001645151027430560011436 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef XT_HMARK_H_ #define XT_HMARK_H_ #include #include enum { XT_HMARK_SADDR_MASK, XT_HMARK_DADDR_MASK, XT_HMARK_SPI, XT_HMARK_SPI_MASK, XT_HMARK_SPORT, XT_HMARK_DPORT, XT_HMARK_SPORT_MASK, XT_HMARK_DPORT_MASK, XT_HMARK_PROTO_MASK, XT_HMARK_RND, XT_HMARK_MODULUS, XT_HMARK_OFFSET, XT_HMARK_CT, XT_HMARK_METHOD_L3, XT_HMARK_METHOD_L3_4, }; #define XT_HMARK_FLAG(flag) (1 << flag) union hmark_ports { struct { __u16 src; __u16 dst; } p16; struct { __be16 src; __be16 dst; } b16; __u32 v32; __be32 b32; }; struct xt_hmark_info { union nf_inet_addr src_mask; union nf_inet_addr dst_mask; union hmark_ports port_mask; union hmark_ports port_set; __u32 flags; __u16 proto_mask; __u32 hashrnd; __u32 hmodulus; __u32 hoffset; /* Mark offset to start from */ }; #endif /* XT_HMARK_H_ */ linux/netfilter/xt_ipvs.h000064400000001250151027430560011545 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_IPVS_H #define _XT_IPVS_H #include #include enum { XT_IPVS_IPVS_PROPERTY = 1 << 0, /* all other options imply this one */ XT_IPVS_PROTO = 1 << 1, XT_IPVS_VADDR = 1 << 2, XT_IPVS_VPORT = 1 << 3, XT_IPVS_DIR = 1 << 4, XT_IPVS_METHOD = 1 << 5, XT_IPVS_VPORTCTL = 1 << 6, XT_IPVS_MASK = (1 << 7) - 1, XT_IPVS_ONCE_MASK = XT_IPVS_MASK & ~XT_IPVS_IPVS_PROPERTY }; struct xt_ipvs_mtinfo { union nf_inet_addr vaddr, vmask; __be16 vport; __u8 l4proto; __u8 fwd_method; __be16 vportctl; __u8 invert; __u8 bitmask; }; #endif /* _XT_IPVS_H */ linux/netfilter/xt_connlimit.h000064400000001077151027430560012567 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_CONNLIMIT_H #define _XT_CONNLIMIT_H #include #include struct xt_connlimit_data; enum { XT_CONNLIMIT_INVERT = 1 << 0, XT_CONNLIMIT_DADDR = 1 << 1, }; struct xt_connlimit_info { union { union nf_inet_addr mask; union { __be32 v4_mask; __be32 v6_mask[4]; }; }; unsigned int limit; /* revision 1 */ __u32 flags; /* Used internally by the kernel */ struct nf_conncount_data *data __attribute__((aligned(8))); }; #endif /* _XT_CONNLIMIT_H */ linux/netfilter/nfnetlink_cttimeout.h000064400000005562151027430560014150 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _CTTIMEOUT_NETLINK_H #define _CTTIMEOUT_NETLINK_H #include enum ctnl_timeout_msg_types { IPCTNL_MSG_TIMEOUT_NEW, IPCTNL_MSG_TIMEOUT_GET, IPCTNL_MSG_TIMEOUT_DELETE, IPCTNL_MSG_TIMEOUT_DEFAULT_SET, IPCTNL_MSG_TIMEOUT_DEFAULT_GET, IPCTNL_MSG_TIMEOUT_MAX }; enum ctattr_timeout { CTA_TIMEOUT_UNSPEC, CTA_TIMEOUT_NAME, CTA_TIMEOUT_L3PROTO, CTA_TIMEOUT_L4PROTO, CTA_TIMEOUT_DATA, CTA_TIMEOUT_USE, __CTA_TIMEOUT_MAX }; #define CTA_TIMEOUT_MAX (__CTA_TIMEOUT_MAX - 1) enum ctattr_timeout_generic { CTA_TIMEOUT_GENERIC_UNSPEC, CTA_TIMEOUT_GENERIC_TIMEOUT, __CTA_TIMEOUT_GENERIC_MAX }; #define CTA_TIMEOUT_GENERIC_MAX (__CTA_TIMEOUT_GENERIC_MAX - 1) enum ctattr_timeout_tcp { CTA_TIMEOUT_TCP_UNSPEC, CTA_TIMEOUT_TCP_SYN_SENT, CTA_TIMEOUT_TCP_SYN_RECV, CTA_TIMEOUT_TCP_ESTABLISHED, CTA_TIMEOUT_TCP_FIN_WAIT, CTA_TIMEOUT_TCP_CLOSE_WAIT, CTA_TIMEOUT_TCP_LAST_ACK, CTA_TIMEOUT_TCP_TIME_WAIT, CTA_TIMEOUT_TCP_CLOSE, CTA_TIMEOUT_TCP_SYN_SENT2, CTA_TIMEOUT_TCP_RETRANS, CTA_TIMEOUT_TCP_UNACK, __CTA_TIMEOUT_TCP_MAX }; #define CTA_TIMEOUT_TCP_MAX (__CTA_TIMEOUT_TCP_MAX - 1) enum ctattr_timeout_udp { CTA_TIMEOUT_UDP_UNSPEC, CTA_TIMEOUT_UDP_UNREPLIED, CTA_TIMEOUT_UDP_REPLIED, __CTA_TIMEOUT_UDP_MAX }; #define CTA_TIMEOUT_UDP_MAX (__CTA_TIMEOUT_UDP_MAX - 1) enum ctattr_timeout_udplite { CTA_TIMEOUT_UDPLITE_UNSPEC, CTA_TIMEOUT_UDPLITE_UNREPLIED, CTA_TIMEOUT_UDPLITE_REPLIED, __CTA_TIMEOUT_UDPLITE_MAX }; #define CTA_TIMEOUT_UDPLITE_MAX (__CTA_TIMEOUT_UDPLITE_MAX - 1) enum ctattr_timeout_icmp { CTA_TIMEOUT_ICMP_UNSPEC, CTA_TIMEOUT_ICMP_TIMEOUT, __CTA_TIMEOUT_ICMP_MAX }; #define CTA_TIMEOUT_ICMP_MAX (__CTA_TIMEOUT_ICMP_MAX - 1) enum ctattr_timeout_dccp { CTA_TIMEOUT_DCCP_UNSPEC, CTA_TIMEOUT_DCCP_REQUEST, CTA_TIMEOUT_DCCP_RESPOND, CTA_TIMEOUT_DCCP_PARTOPEN, CTA_TIMEOUT_DCCP_OPEN, CTA_TIMEOUT_DCCP_CLOSEREQ, CTA_TIMEOUT_DCCP_CLOSING, CTA_TIMEOUT_DCCP_TIMEWAIT, __CTA_TIMEOUT_DCCP_MAX }; #define CTA_TIMEOUT_DCCP_MAX (__CTA_TIMEOUT_DCCP_MAX - 1) enum ctattr_timeout_sctp { CTA_TIMEOUT_SCTP_UNSPEC, CTA_TIMEOUT_SCTP_CLOSED, CTA_TIMEOUT_SCTP_COOKIE_WAIT, CTA_TIMEOUT_SCTP_COOKIE_ECHOED, CTA_TIMEOUT_SCTP_ESTABLISHED, CTA_TIMEOUT_SCTP_SHUTDOWN_SENT, CTA_TIMEOUT_SCTP_SHUTDOWN_RECD, CTA_TIMEOUT_SCTP_SHUTDOWN_ACK_SENT, CTA_TIMEOUT_SCTP_HEARTBEAT_SENT, CTA_TIMEOUT_SCTP_HEARTBEAT_ACKED, __CTA_TIMEOUT_SCTP_MAX }; #define CTA_TIMEOUT_SCTP_MAX (__CTA_TIMEOUT_SCTP_MAX - 1) enum ctattr_timeout_icmpv6 { CTA_TIMEOUT_ICMPV6_UNSPEC, CTA_TIMEOUT_ICMPV6_TIMEOUT, __CTA_TIMEOUT_ICMPV6_MAX }; #define CTA_TIMEOUT_ICMPV6_MAX (__CTA_TIMEOUT_ICMPV6_MAX - 1) enum ctattr_timeout_gre { CTA_TIMEOUT_GRE_UNSPEC, CTA_TIMEOUT_GRE_UNREPLIED, CTA_TIMEOUT_GRE_REPLIED, __CTA_TIMEOUT_GRE_MAX }; #define CTA_TIMEOUT_GRE_MAX (__CTA_TIMEOUT_GRE_MAX - 1) #define CTNL_TIMEOUT_NAME_MAX 32 #endif linux/netfilter/xt_realm.h000064400000000334151027430560011666 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_REALM_H #define _XT_REALM_H #include struct xt_realm_info { __u32 id; __u32 mask; __u8 invert; }; #endif /* _XT_REALM_H */ linux/netfilter/xt_recent.h000064400000002042151027430560012044 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NETFILTER_XT_RECENT_H #define _LINUX_NETFILTER_XT_RECENT_H 1 #include #include enum { XT_RECENT_CHECK = 1 << 0, XT_RECENT_SET = 1 << 1, XT_RECENT_UPDATE = 1 << 2, XT_RECENT_REMOVE = 1 << 3, XT_RECENT_TTL = 1 << 4, XT_RECENT_REAP = 1 << 5, XT_RECENT_SOURCE = 0, XT_RECENT_DEST = 1, XT_RECENT_NAME_LEN = 200, }; /* Only allowed with --rcheck and --update */ #define XT_RECENT_MODIFIERS (XT_RECENT_TTL|XT_RECENT_REAP) #define XT_RECENT_VALID_FLAGS (XT_RECENT_CHECK|XT_RECENT_SET|XT_RECENT_UPDATE|\ XT_RECENT_REMOVE|XT_RECENT_TTL|XT_RECENT_REAP) struct xt_recent_mtinfo { __u32 seconds; __u32 hit_count; __u8 check_set; __u8 invert; char name[XT_RECENT_NAME_LEN]; __u8 side; }; struct xt_recent_mtinfo_v1 { __u32 seconds; __u32 hit_count; __u8 check_set; __u8 invert; char name[XT_RECENT_NAME_LEN]; __u8 side; union nf_inet_addr mask; }; #endif /* _LINUX_NETFILTER_XT_RECENT_H */ linux/netfilter/xt_NFQUEUE.h000064400000001413151027430560011675 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* iptables module for using NFQUEUE mechanism * * (C) 2005 Harald Welte * * This software is distributed under GNU GPL v2, 1991 * */ #ifndef _XT_NFQ_TARGET_H #define _XT_NFQ_TARGET_H #include /* target info */ struct xt_NFQ_info { __u16 queuenum; }; struct xt_NFQ_info_v1 { __u16 queuenum; __u16 queues_total; }; struct xt_NFQ_info_v2 { __u16 queuenum; __u16 queues_total; __u16 bypass; }; struct xt_NFQ_info_v3 { __u16 queuenum; __u16 queues_total; __u16 flags; #define NFQ_FLAG_BYPASS 0x01 /* for compatibility with v2 */ #define NFQ_FLAG_CPU_FANOUT 0x02 /* use current CPU (no hashing) */ #define NFQ_FLAG_MASK 0x03 }; #endif /* _XT_NFQ_TARGET_H */ linux/netfilter/xt_NFLOG.h000064400000001054151027430560011433 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_NFLOG_TARGET #define _XT_NFLOG_TARGET #include #define XT_NFLOG_DEFAULT_GROUP 0x1 #define XT_NFLOG_DEFAULT_THRESHOLD 0 #define XT_NFLOG_MASK 0x1 /* This flag indicates that 'len' field in xt_nflog_info is set*/ #define XT_NFLOG_F_COPY_LEN 0x1 struct xt_nflog_info { /* 'len' will be used iff you set XT_NFLOG_F_COPY_LEN in flags */ __u32 len; __u16 group; __u16 threshold; __u16 flags; __u16 pad; char prefix[64]; }; #endif /* _XT_NFLOG_TARGET */ linux/netfilter/nf_log.h000064400000001032151027430560011313 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NETFILTER_NF_LOG_H #define _NETFILTER_NF_LOG_H #define NF_LOG_TCPSEQ 0x01 /* Log TCP sequence numbers */ #define NF_LOG_TCPOPT 0x02 /* Log TCP options */ #define NF_LOG_IPOPT 0x04 /* Log IP options */ #define NF_LOG_UID 0x08 /* Log UID owning local socket */ #define NF_LOG_NFLOG 0x10 /* Unsupported, don't reuse */ #define NF_LOG_MACDECODE 0x20 /* Decode MAC header */ #define NF_LOG_MASK 0x2f #define NF_LOG_PREFIXLEN 128 #endif /* _NETFILTER_NF_LOG_H */ linux/netfilter/nf_tables.h000064400000140371151027430560012016 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NF_TABLES_H #define _LINUX_NF_TABLES_H #define NFT_NAME_MAXLEN 256 #define NFT_TABLE_MAXNAMELEN NFT_NAME_MAXLEN #define NFT_CHAIN_MAXNAMELEN NFT_NAME_MAXLEN #define NFT_SET_MAXNAMELEN NFT_NAME_MAXLEN #define NFT_OBJ_MAXNAMELEN NFT_NAME_MAXLEN #define NFT_USERDATA_MAXLEN 256 /** * enum nft_registers - nf_tables registers * * nf_tables used to have five registers: a verdict register and four data * registers of size 16. The data registers have been changed to 16 registers * of size 4. For compatibility reasons, the NFT_REG_[1-4] registers still * map to areas of size 16, the 4 byte registers are addressed using * NFT_REG32_00 - NFT_REG32_15. */ enum nft_registers { NFT_REG_VERDICT, NFT_REG_1, NFT_REG_2, NFT_REG_3, NFT_REG_4, __NFT_REG_MAX, NFT_REG32_00 = 8, NFT_REG32_01, NFT_REG32_02, NFT_REG32_03, NFT_REG32_04, NFT_REG32_05, NFT_REG32_06, NFT_REG32_07, NFT_REG32_08, NFT_REG32_09, NFT_REG32_10, NFT_REG32_11, NFT_REG32_12, NFT_REG32_13, NFT_REG32_14, NFT_REG32_15, }; #define NFT_REG_MAX (__NFT_REG_MAX - 1) #define NFT_REG_SIZE 16 #define NFT_REG32_SIZE 4 #define NFT_REG32_COUNT (NFT_REG32_15 - NFT_REG32_00 + 1) /** * enum nft_verdicts - nf_tables internal verdicts * * @NFT_CONTINUE: continue evaluation of the current rule * @NFT_BREAK: terminate evaluation of the current rule * @NFT_JUMP: push the current chain on the jump stack and jump to a chain * @NFT_GOTO: jump to a chain without pushing the current chain on the jump stack * @NFT_RETURN: return to the topmost chain on the jump stack * * The nf_tables verdicts share their numeric space with the netfilter verdicts. */ enum nft_verdicts { NFT_CONTINUE = -1, NFT_BREAK = -2, NFT_JUMP = -3, NFT_GOTO = -4, NFT_RETURN = -5, }; /** * enum nf_tables_msg_types - nf_tables netlink message types * * @NFT_MSG_NEWTABLE: create a new table (enum nft_table_attributes) * @NFT_MSG_GETTABLE: get a table (enum nft_table_attributes) * @NFT_MSG_DELTABLE: delete a table (enum nft_table_attributes) * @NFT_MSG_NEWCHAIN: create a new chain (enum nft_chain_attributes) * @NFT_MSG_GETCHAIN: get a chain (enum nft_chain_attributes) * @NFT_MSG_DELCHAIN: delete a chain (enum nft_chain_attributes) * @NFT_MSG_NEWRULE: create a new rule (enum nft_rule_attributes) * @NFT_MSG_GETRULE: get a rule (enum nft_rule_attributes) * @NFT_MSG_DELRULE: delete a rule (enum nft_rule_attributes) * @NFT_MSG_NEWSET: create a new set (enum nft_set_attributes) * @NFT_MSG_GETSET: get a set (enum nft_set_attributes) * @NFT_MSG_DELSET: delete a set (enum nft_set_attributes) * @NFT_MSG_NEWSETELEM: create a new set element (enum nft_set_elem_attributes) * @NFT_MSG_GETSETELEM: get a set element (enum nft_set_elem_attributes) * @NFT_MSG_DELSETELEM: delete a set element (enum nft_set_elem_attributes) * @NFT_MSG_NEWGEN: announce a new generation, only for events (enum nft_gen_attributes) * @NFT_MSG_GETGEN: get the rule-set generation (enum nft_gen_attributes) * @NFT_MSG_TRACE: trace event (enum nft_trace_attributes) * @NFT_MSG_NEWOBJ: create a stateful object (enum nft_obj_attributes) * @NFT_MSG_GETOBJ: get a stateful object (enum nft_obj_attributes) * @NFT_MSG_DELOBJ: delete a stateful object (enum nft_obj_attributes) * @NFT_MSG_GETOBJ_RESET: get and reset a stateful object (enum nft_obj_attributes) * @NFT_MSG_NEWFLOWTABLE: add new flow table (enum nft_flowtable_attributes) * @NFT_MSG_GETFLOWTABLE: get flow table (enum nft_flowtable_attributes) * @NFT_MSG_DELFLOWTABLE: delete flow table (enum nft_flowtable_attributes) */ enum nf_tables_msg_types { NFT_MSG_NEWTABLE, NFT_MSG_GETTABLE, NFT_MSG_DELTABLE, NFT_MSG_NEWCHAIN, NFT_MSG_GETCHAIN, NFT_MSG_DELCHAIN, NFT_MSG_NEWRULE, NFT_MSG_GETRULE, NFT_MSG_DELRULE, NFT_MSG_NEWSET, NFT_MSG_GETSET, NFT_MSG_DELSET, NFT_MSG_NEWSETELEM, NFT_MSG_GETSETELEM, NFT_MSG_DELSETELEM, NFT_MSG_NEWGEN, NFT_MSG_GETGEN, NFT_MSG_TRACE, NFT_MSG_NEWOBJ, NFT_MSG_GETOBJ, NFT_MSG_DELOBJ, NFT_MSG_GETOBJ_RESET, NFT_MSG_NEWFLOWTABLE, NFT_MSG_GETFLOWTABLE, NFT_MSG_DELFLOWTABLE, NFT_MSG_MAX, }; /** * enum nft_list_attributes - nf_tables generic list netlink attributes * * @NFTA_LIST_ELEM: list element (NLA_NESTED) */ enum nft_list_attributes { NFTA_LIST_UNPEC, NFTA_LIST_ELEM, __NFTA_LIST_MAX }; #define NFTA_LIST_MAX (__NFTA_LIST_MAX - 1) /** * enum nft_hook_attributes - nf_tables netfilter hook netlink attributes * * @NFTA_HOOK_HOOKNUM: netfilter hook number (NLA_U32) * @NFTA_HOOK_PRIORITY: netfilter hook priority (NLA_U32) * @NFTA_HOOK_DEV: netdevice name (NLA_STRING) * @NFTA_HOOK_DEVS: list of netdevices (NLA_NESTED) */ enum nft_hook_attributes { NFTA_HOOK_UNSPEC, NFTA_HOOK_HOOKNUM, NFTA_HOOK_PRIORITY, NFTA_HOOK_DEV, NFTA_HOOK_DEVS, __NFTA_HOOK_MAX }; #define NFTA_HOOK_MAX (__NFTA_HOOK_MAX - 1) /** * enum nft_table_flags - nf_tables table flags * * @NFT_TABLE_F_DORMANT: this table is not active */ enum nft_table_flags { NFT_TABLE_F_DORMANT = 0x1, }; #define NFT_TABLE_F_MASK (NFT_TABLE_F_DORMANT) /** * enum nft_table_attributes - nf_tables table netlink attributes * * @NFTA_TABLE_NAME: name of the table (NLA_STRING) * @NFTA_TABLE_FLAGS: bitmask of enum nft_table_flags (NLA_U32) * @NFTA_TABLE_USE: number of chains in this table (NLA_U32) */ enum nft_table_attributes { NFTA_TABLE_UNSPEC, NFTA_TABLE_NAME, NFTA_TABLE_FLAGS, NFTA_TABLE_USE, NFTA_TABLE_HANDLE, NFTA_TABLE_PAD, __NFTA_TABLE_MAX }; #define NFTA_TABLE_MAX (__NFTA_TABLE_MAX - 1) /** * enum nft_chain_attributes - nf_tables chain netlink attributes * * @NFTA_CHAIN_TABLE: name of the table containing the chain (NLA_STRING) * @NFTA_CHAIN_HANDLE: numeric handle of the chain (NLA_U64) * @NFTA_CHAIN_NAME: name of the chain (NLA_STRING) * @NFTA_CHAIN_HOOK: hook specification for basechains (NLA_NESTED: nft_hook_attributes) * @NFTA_CHAIN_POLICY: numeric policy of the chain (NLA_U32) * @NFTA_CHAIN_USE: number of references to this chain (NLA_U32) * @NFTA_CHAIN_TYPE: type name of the string (NLA_NUL_STRING) * @NFTA_CHAIN_COUNTERS: counter specification of the chain (NLA_NESTED: nft_counter_attributes) * @NFTA_CHAIN_FLAGS: chain flags */ enum nft_chain_attributes { NFTA_CHAIN_UNSPEC, NFTA_CHAIN_TABLE, NFTA_CHAIN_HANDLE, NFTA_CHAIN_NAME, NFTA_CHAIN_HOOK, NFTA_CHAIN_POLICY, NFTA_CHAIN_USE, NFTA_CHAIN_TYPE, NFTA_CHAIN_COUNTERS, NFTA_CHAIN_PAD, NFTA_CHAIN_FLAGS, __NFTA_CHAIN_MAX }; #define NFTA_CHAIN_MAX (__NFTA_CHAIN_MAX - 1) /** * enum nft_rule_attributes - nf_tables rule netlink attributes * * @NFTA_RULE_TABLE: name of the table containing the rule (NLA_STRING) * @NFTA_RULE_CHAIN: name of the chain containing the rule (NLA_STRING) * @NFTA_RULE_HANDLE: numeric handle of the rule (NLA_U64) * @NFTA_RULE_EXPRESSIONS: list of expressions (NLA_NESTED: nft_expr_attributes) * @NFTA_RULE_COMPAT: compatibility specifications of the rule (NLA_NESTED: nft_rule_compat_attributes) * @NFTA_RULE_POSITION: numeric handle of the previous rule (NLA_U64) * @NFTA_RULE_USERDATA: user data (NLA_BINARY, NFT_USERDATA_MAXLEN) * @NFTA_RULE_ID: uniquely identifies a rule in a transaction (NLA_U32) * @NFTA_RULE_POSITION_ID: transaction unique identifier of the previous rule (NLA_U32) */ enum nft_rule_attributes { NFTA_RULE_UNSPEC, NFTA_RULE_TABLE, NFTA_RULE_CHAIN, NFTA_RULE_HANDLE, NFTA_RULE_EXPRESSIONS, NFTA_RULE_COMPAT, NFTA_RULE_POSITION, NFTA_RULE_USERDATA, NFTA_RULE_PAD, NFTA_RULE_ID, NFTA_RULE_POSITION_ID, __NFTA_RULE_MAX }; #define NFTA_RULE_MAX (__NFTA_RULE_MAX - 1) /** * enum nft_rule_compat_flags - nf_tables rule compat flags * * @NFT_RULE_COMPAT_F_INV: invert the check result */ enum nft_rule_compat_flags { NFT_RULE_COMPAT_F_INV = (1 << 1), NFT_RULE_COMPAT_F_MASK = NFT_RULE_COMPAT_F_INV, }; /** * enum nft_rule_compat_attributes - nf_tables rule compat attributes * * @NFTA_RULE_COMPAT_PROTO: numeric value of handled protocol (NLA_U32) * @NFTA_RULE_COMPAT_FLAGS: bitmask of enum nft_rule_compat_flags (NLA_U32) */ enum nft_rule_compat_attributes { NFTA_RULE_COMPAT_UNSPEC, NFTA_RULE_COMPAT_PROTO, NFTA_RULE_COMPAT_FLAGS, __NFTA_RULE_COMPAT_MAX }; #define NFTA_RULE_COMPAT_MAX (__NFTA_RULE_COMPAT_MAX - 1) /** * enum nft_set_flags - nf_tables set flags * * @NFT_SET_ANONYMOUS: name allocation, automatic cleanup on unlink * @NFT_SET_CONSTANT: set contents may not change while bound * @NFT_SET_INTERVAL: set contains intervals * @NFT_SET_MAP: set is used as a dictionary * @NFT_SET_TIMEOUT: set uses timeouts * @NFT_SET_EVAL: set can be updated from the evaluation path * @NFT_SET_OBJECT: set contains stateful objects * @NFT_SET_CONCAT: set contains a concatenation * @NFT_SET_EXPR: set contains expressions */ enum nft_set_flags { NFT_SET_ANONYMOUS = 0x1, NFT_SET_CONSTANT = 0x2, NFT_SET_INTERVAL = 0x4, NFT_SET_MAP = 0x8, NFT_SET_TIMEOUT = 0x10, NFT_SET_EVAL = 0x20, NFT_SET_OBJECT = 0x40, NFT_SET_CONCAT = 0x80, NFT_SET_EXPR = 0x100, }; /** * enum nft_set_policies - set selection policy * * @NFT_SET_POL_PERFORMANCE: prefer high performance over low memory use * @NFT_SET_POL_MEMORY: prefer low memory use over high performance */ enum nft_set_policies { NFT_SET_POL_PERFORMANCE, NFT_SET_POL_MEMORY, }; /** * enum nft_set_desc_attributes - set element description * * @NFTA_SET_DESC_SIZE: number of elements in set (NLA_U32) * @NFTA_SET_DESC_CONCAT: description of field concatenation (NLA_NESTED) */ enum nft_set_desc_attributes { NFTA_SET_DESC_UNSPEC, NFTA_SET_DESC_SIZE, NFTA_SET_DESC_CONCAT, __NFTA_SET_DESC_MAX }; #define NFTA_SET_DESC_MAX (__NFTA_SET_DESC_MAX - 1) /** * enum nft_set_field_attributes - attributes of concatenated fields * * @NFTA_SET_FIELD_LEN: length of single field, in bits (NLA_U32) */ enum nft_set_field_attributes { NFTA_SET_FIELD_UNSPEC, NFTA_SET_FIELD_LEN, __NFTA_SET_FIELD_MAX }; #define NFTA_SET_FIELD_MAX (__NFTA_SET_FIELD_MAX - 1) /** * enum nft_set_attributes - nf_tables set netlink attributes * * @NFTA_SET_TABLE: table name (NLA_STRING) * @NFTA_SET_NAME: set name (NLA_STRING) * @NFTA_SET_FLAGS: bitmask of enum nft_set_flags (NLA_U32) * @NFTA_SET_KEY_TYPE: key data type, informational purpose only (NLA_U32) * @NFTA_SET_KEY_LEN: key data length (NLA_U32) * @NFTA_SET_DATA_TYPE: mapping data type (NLA_U32) * @NFTA_SET_DATA_LEN: mapping data length (NLA_U32) * @NFTA_SET_POLICY: selection policy (NLA_U32) * @NFTA_SET_DESC: set description (NLA_NESTED) * @NFTA_SET_ID: uniquely identifies a set in a transaction (NLA_U32) * @NFTA_SET_TIMEOUT: default timeout value (NLA_U64) * @NFTA_SET_GC_INTERVAL: garbage collection interval (NLA_U32) * @NFTA_SET_USERDATA: user data (NLA_BINARY) * @NFTA_SET_OBJ_TYPE: stateful object type (NLA_U32: NFT_OBJECT_*) * @NFTA_SET_HANDLE: set handle (NLA_U64) * @NFTA_SET_EXPR: set expression (NLA_NESTED: nft_expr_attributes) * @NFTA_SET_EXPRESSIONS: list of expressions (NLA_NESTED: nft_list_attributes) */ enum nft_set_attributes { NFTA_SET_UNSPEC, NFTA_SET_TABLE, NFTA_SET_NAME, NFTA_SET_FLAGS, NFTA_SET_KEY_TYPE, NFTA_SET_KEY_LEN, NFTA_SET_DATA_TYPE, NFTA_SET_DATA_LEN, NFTA_SET_POLICY, NFTA_SET_DESC, NFTA_SET_ID, NFTA_SET_TIMEOUT, NFTA_SET_GC_INTERVAL, NFTA_SET_USERDATA, NFTA_SET_PAD, NFTA_SET_OBJ_TYPE, NFTA_SET_HANDLE, NFTA_SET_EXPR, NFTA_SET_EXPRESSIONS, __NFTA_SET_MAX }; #define NFTA_SET_MAX (__NFTA_SET_MAX - 1) /** * enum nft_set_elem_flags - nf_tables set element flags * * @NFT_SET_ELEM_INTERVAL_END: element ends the previous interval */ enum nft_set_elem_flags { NFT_SET_ELEM_INTERVAL_END = 0x1, }; /** * enum nft_set_elem_attributes - nf_tables set element netlink attributes * * @NFTA_SET_ELEM_KEY: key value (NLA_NESTED: nft_data) * @NFTA_SET_ELEM_DATA: data value of mapping (NLA_NESTED: nft_data_attributes) * @NFTA_SET_ELEM_FLAGS: bitmask of nft_set_elem_flags (NLA_U32) * @NFTA_SET_ELEM_TIMEOUT: timeout value (NLA_U64) * @NFTA_SET_ELEM_EXPIRATION: expiration time (NLA_U64) * @NFTA_SET_ELEM_USERDATA: user data (NLA_BINARY) * @NFTA_SET_ELEM_EXPR: expression (NLA_NESTED: nft_expr_attributes) * @NFTA_SET_ELEM_OBJREF: stateful object reference (NLA_STRING) * @NFTA_SET_ELEM_KEY_END: closing key value (NLA_NESTED: nft_data) * @NFTA_SET_ELEM_EXPRESSIONS: list of expressions (NLA_NESTED: nft_list_attributes) */ enum nft_set_elem_attributes { NFTA_SET_ELEM_UNSPEC, NFTA_SET_ELEM_KEY, NFTA_SET_ELEM_DATA, NFTA_SET_ELEM_FLAGS, NFTA_SET_ELEM_TIMEOUT, NFTA_SET_ELEM_EXPIRATION, NFTA_SET_ELEM_USERDATA, NFTA_SET_ELEM_EXPR, NFTA_SET_ELEM_PAD, NFTA_SET_ELEM_OBJREF, NFTA_SET_ELEM_KEY_END, NFTA_SET_ELEM_EXPRESSIONS, __NFTA_SET_ELEM_MAX }; #define NFTA_SET_ELEM_MAX (__NFTA_SET_ELEM_MAX - 1) /** * enum nft_set_elem_list_attributes - nf_tables set element list netlink attributes * * @NFTA_SET_ELEM_LIST_TABLE: table of the set to be changed (NLA_STRING) * @NFTA_SET_ELEM_LIST_SET: name of the set to be changed (NLA_STRING) * @NFTA_SET_ELEM_LIST_ELEMENTS: list of set elements (NLA_NESTED: nft_set_elem_attributes) * @NFTA_SET_ELEM_LIST_SET_ID: uniquely identifies a set in a transaction (NLA_U32) */ enum nft_set_elem_list_attributes { NFTA_SET_ELEM_LIST_UNSPEC, NFTA_SET_ELEM_LIST_TABLE, NFTA_SET_ELEM_LIST_SET, NFTA_SET_ELEM_LIST_ELEMENTS, NFTA_SET_ELEM_LIST_SET_ID, __NFTA_SET_ELEM_LIST_MAX }; #define NFTA_SET_ELEM_LIST_MAX (__NFTA_SET_ELEM_LIST_MAX - 1) /** * enum nft_data_types - nf_tables data types * * @NFT_DATA_VALUE: generic data * @NFT_DATA_VERDICT: netfilter verdict * * The type of data is usually determined by the kernel directly and is not * explicitly specified by userspace. The only difference are sets, where * userspace specifies the key and mapping data types. * * The values 0xffffff00-0xffffffff are reserved for internally used types. * The remaining range can be freely used by userspace to encode types, all * values are equivalent to NFT_DATA_VALUE. */ enum nft_data_types { NFT_DATA_VALUE, NFT_DATA_VERDICT = 0xffffff00U, }; #define NFT_DATA_RESERVED_MASK 0xffffff00U /** * enum nft_data_attributes - nf_tables data netlink attributes * * @NFTA_DATA_VALUE: generic data (NLA_BINARY) * @NFTA_DATA_VERDICT: nf_tables verdict (NLA_NESTED: nft_verdict_attributes) */ enum nft_data_attributes { NFTA_DATA_UNSPEC, NFTA_DATA_VALUE, NFTA_DATA_VERDICT, __NFTA_DATA_MAX }; #define NFTA_DATA_MAX (__NFTA_DATA_MAX - 1) /* Maximum length of a value */ #define NFT_DATA_VALUE_MAXLEN 64 /** * enum nft_verdict_attributes - nf_tables verdict netlink attributes * * @NFTA_VERDICT_CODE: nf_tables verdict (NLA_U32: enum nft_verdicts) * @NFTA_VERDICT_CHAIN: jump target chain name (NLA_STRING) */ enum nft_verdict_attributes { NFTA_VERDICT_UNSPEC, NFTA_VERDICT_CODE, NFTA_VERDICT_CHAIN, __NFTA_VERDICT_MAX }; #define NFTA_VERDICT_MAX (__NFTA_VERDICT_MAX - 1) /** * enum nft_expr_attributes - nf_tables expression netlink attributes * * @NFTA_EXPR_NAME: name of the expression type (NLA_STRING) * @NFTA_EXPR_DATA: type specific data (NLA_NESTED) */ enum nft_expr_attributes { NFTA_EXPR_UNSPEC, NFTA_EXPR_NAME, NFTA_EXPR_DATA, __NFTA_EXPR_MAX }; #define NFTA_EXPR_MAX (__NFTA_EXPR_MAX - 1) /** * enum nft_immediate_attributes - nf_tables immediate expression netlink attributes * * @NFTA_IMMEDIATE_DREG: destination register to load data into (NLA_U32) * @NFTA_IMMEDIATE_DATA: data to load (NLA_NESTED: nft_data_attributes) */ enum nft_immediate_attributes { NFTA_IMMEDIATE_UNSPEC, NFTA_IMMEDIATE_DREG, NFTA_IMMEDIATE_DATA, __NFTA_IMMEDIATE_MAX }; #define NFTA_IMMEDIATE_MAX (__NFTA_IMMEDIATE_MAX - 1) /** * enum nft_bitwise_attributes - nf_tables bitwise expression netlink attributes * * @NFTA_BITWISE_SREG: source register (NLA_U32: nft_registers) * @NFTA_BITWISE_DREG: destination register (NLA_U32: nft_registers) * @NFTA_BITWISE_LEN: length of operands (NLA_U32) * @NFTA_BITWISE_MASK: mask value (NLA_NESTED: nft_data_attributes) * @NFTA_BITWISE_XOR: xor value (NLA_NESTED: nft_data_attributes) * * The bitwise expression performs the following operation: * * dreg = (sreg & mask) ^ xor * * which allow to express all bitwise operations: * * mask xor * NOT: 1 1 * OR: 0 x * XOR: 1 x * AND: x 0 */ enum nft_bitwise_attributes { NFTA_BITWISE_UNSPEC, NFTA_BITWISE_SREG, NFTA_BITWISE_DREG, NFTA_BITWISE_LEN, NFTA_BITWISE_MASK, NFTA_BITWISE_XOR, __NFTA_BITWISE_MAX }; #define NFTA_BITWISE_MAX (__NFTA_BITWISE_MAX - 1) /** * enum nft_byteorder_ops - nf_tables byteorder operators * * @NFT_BYTEORDER_NTOH: network to host operator * @NFT_BYTEORDER_HTON: host to network operator */ enum nft_byteorder_ops { NFT_BYTEORDER_NTOH, NFT_BYTEORDER_HTON, }; /** * enum nft_byteorder_attributes - nf_tables byteorder expression netlink attributes * * @NFTA_BYTEORDER_SREG: source register (NLA_U32: nft_registers) * @NFTA_BYTEORDER_DREG: destination register (NLA_U32: nft_registers) * @NFTA_BYTEORDER_OP: operator (NLA_U32: enum nft_byteorder_ops) * @NFTA_BYTEORDER_LEN: length of the data (NLA_U32) * @NFTA_BYTEORDER_SIZE: data size in bytes (NLA_U32: 2 or 4) */ enum nft_byteorder_attributes { NFTA_BYTEORDER_UNSPEC, NFTA_BYTEORDER_SREG, NFTA_BYTEORDER_DREG, NFTA_BYTEORDER_OP, NFTA_BYTEORDER_LEN, NFTA_BYTEORDER_SIZE, __NFTA_BYTEORDER_MAX }; #define NFTA_BYTEORDER_MAX (__NFTA_BYTEORDER_MAX - 1) /** * enum nft_cmp_ops - nf_tables relational operator * * @NFT_CMP_EQ: equal * @NFT_CMP_NEQ: not equal * @NFT_CMP_LT: less than * @NFT_CMP_LTE: less than or equal to * @NFT_CMP_GT: greater than * @NFT_CMP_GTE: greater than or equal to */ enum nft_cmp_ops { NFT_CMP_EQ, NFT_CMP_NEQ, NFT_CMP_LT, NFT_CMP_LTE, NFT_CMP_GT, NFT_CMP_GTE, }; /** * enum nft_cmp_attributes - nf_tables cmp expression netlink attributes * * @NFTA_CMP_SREG: source register of data to compare (NLA_U32: nft_registers) * @NFTA_CMP_OP: cmp operation (NLA_U32: nft_cmp_ops) * @NFTA_CMP_DATA: data to compare against (NLA_NESTED: nft_data_attributes) */ enum nft_cmp_attributes { NFTA_CMP_UNSPEC, NFTA_CMP_SREG, NFTA_CMP_OP, NFTA_CMP_DATA, __NFTA_CMP_MAX }; #define NFTA_CMP_MAX (__NFTA_CMP_MAX - 1) /** * enum nft_range_ops - nf_tables range operator * * @NFT_RANGE_EQ: equal * @NFT_RANGE_NEQ: not equal */ enum nft_range_ops { NFT_RANGE_EQ, NFT_RANGE_NEQ, }; /** * enum nft_range_attributes - nf_tables range expression netlink attributes * * @NFTA_RANGE_SREG: source register of data to compare (NLA_U32: nft_registers) * @NFTA_RANGE_OP: cmp operation (NLA_U32: nft_cmp_ops) * @NFTA_RANGE_FROM_DATA: data range from (NLA_NESTED: nft_data_attributes) * @NFTA_RANGE_TO_DATA: data range to (NLA_NESTED: nft_data_attributes) */ enum nft_range_attributes { NFTA_RANGE_UNSPEC, NFTA_RANGE_SREG, NFTA_RANGE_OP, NFTA_RANGE_FROM_DATA, NFTA_RANGE_TO_DATA, __NFTA_RANGE_MAX }; #define NFTA_RANGE_MAX (__NFTA_RANGE_MAX - 1) enum nft_lookup_flags { NFT_LOOKUP_F_INV = (1 << 0), }; /** * enum nft_lookup_attributes - nf_tables set lookup expression netlink attributes * * @NFTA_LOOKUP_SET: name of the set where to look for (NLA_STRING) * @NFTA_LOOKUP_SREG: source register of the data to look for (NLA_U32: nft_registers) * @NFTA_LOOKUP_DREG: destination register (NLA_U32: nft_registers) * @NFTA_LOOKUP_SET_ID: uniquely identifies a set in a transaction (NLA_U32) * @NFTA_LOOKUP_FLAGS: flags (NLA_U32: enum nft_lookup_flags) */ enum nft_lookup_attributes { NFTA_LOOKUP_UNSPEC, NFTA_LOOKUP_SET, NFTA_LOOKUP_SREG, NFTA_LOOKUP_DREG, NFTA_LOOKUP_SET_ID, NFTA_LOOKUP_FLAGS, __NFTA_LOOKUP_MAX }; #define NFTA_LOOKUP_MAX (__NFTA_LOOKUP_MAX - 1) enum nft_dynset_ops { NFT_DYNSET_OP_ADD, NFT_DYNSET_OP_UPDATE, }; enum nft_dynset_flags { NFT_DYNSET_F_INV = (1 << 0), NFT_DYNSET_F_EXPR = (1 << 1), }; /** * enum nft_dynset_attributes - dynset expression attributes * * @NFTA_DYNSET_SET_NAME: name of set the to add data to (NLA_STRING) * @NFTA_DYNSET_SET_ID: uniquely identifier of the set in the transaction (NLA_U32) * @NFTA_DYNSET_OP: operation (NLA_U32) * @NFTA_DYNSET_SREG_KEY: source register of the key (NLA_U32) * @NFTA_DYNSET_SREG_DATA: source register of the data (NLA_U32) * @NFTA_DYNSET_TIMEOUT: timeout value for the new element (NLA_U64) * @NFTA_DYNSET_EXPR: expression (NLA_NESTED: nft_expr_attributes) * @NFTA_DYNSET_FLAGS: flags (NLA_U32) * @NFTA_DYNSET_EXPRESSIONS: list of expressions (NLA_NESTED: nft_list_attributes) */ enum nft_dynset_attributes { NFTA_DYNSET_UNSPEC, NFTA_DYNSET_SET_NAME, NFTA_DYNSET_SET_ID, NFTA_DYNSET_OP, NFTA_DYNSET_SREG_KEY, NFTA_DYNSET_SREG_DATA, NFTA_DYNSET_TIMEOUT, NFTA_DYNSET_EXPR, NFTA_DYNSET_PAD, NFTA_DYNSET_FLAGS, NFTA_DYNSET_EXPRESSIONS, __NFTA_DYNSET_MAX, }; #define NFTA_DYNSET_MAX (__NFTA_DYNSET_MAX - 1) /** * enum nft_payload_bases - nf_tables payload expression offset bases * * @NFT_PAYLOAD_LL_HEADER: link layer header * @NFT_PAYLOAD_NETWORK_HEADER: network header * @NFT_PAYLOAD_TRANSPORT_HEADER: transport header */ enum nft_payload_bases { NFT_PAYLOAD_LL_HEADER, NFT_PAYLOAD_NETWORK_HEADER, NFT_PAYLOAD_TRANSPORT_HEADER, }; /** * enum nft_payload_csum_types - nf_tables payload expression checksum types * * @NFT_PAYLOAD_CSUM_NONE: no checksumming * @NFT_PAYLOAD_CSUM_INET: internet checksum (RFC 791) * @NFT_PAYLOAD_CSUM_SCTP: CRC-32c, for use in SCTP header (RFC 3309) */ enum nft_payload_csum_types { NFT_PAYLOAD_CSUM_NONE, NFT_PAYLOAD_CSUM_INET, NFT_PAYLOAD_CSUM_SCTP, }; enum nft_payload_csum_flags { NFT_PAYLOAD_L4CSUM_PSEUDOHDR = (1 << 0), }; /** * enum nft_payload_attributes - nf_tables payload expression netlink attributes * * @NFTA_PAYLOAD_DREG: destination register to load data into (NLA_U32: nft_registers) * @NFTA_PAYLOAD_BASE: payload base (NLA_U32: nft_payload_bases) * @NFTA_PAYLOAD_OFFSET: payload offset relative to base (NLA_U32) * @NFTA_PAYLOAD_LEN: payload length (NLA_U32) * @NFTA_PAYLOAD_SREG: source register to load data from (NLA_U32: nft_registers) * @NFTA_PAYLOAD_CSUM_TYPE: checksum type (NLA_U32) * @NFTA_PAYLOAD_CSUM_OFFSET: checksum offset relative to base (NLA_U32) * @NFTA_PAYLOAD_CSUM_FLAGS: checksum flags (NLA_U32) */ enum nft_payload_attributes { NFTA_PAYLOAD_UNSPEC, NFTA_PAYLOAD_DREG, NFTA_PAYLOAD_BASE, NFTA_PAYLOAD_OFFSET, NFTA_PAYLOAD_LEN, NFTA_PAYLOAD_SREG, NFTA_PAYLOAD_CSUM_TYPE, NFTA_PAYLOAD_CSUM_OFFSET, NFTA_PAYLOAD_CSUM_FLAGS, __NFTA_PAYLOAD_MAX }; #define NFTA_PAYLOAD_MAX (__NFTA_PAYLOAD_MAX - 1) enum nft_exthdr_flags { NFT_EXTHDR_F_PRESENT = (1 << 0), }; /** * enum nft_exthdr_op - nf_tables match options * * @NFT_EXTHDR_OP_IPV6: match against ipv6 extension headers * @NFT_EXTHDR_OP_TCP: match against tcp options * @NFT_EXTHDR_OP_IPV4: match against ipv4 options * @NFT_EXTHDR_OP_SCTP: match against sctp chunks */ enum nft_exthdr_op { NFT_EXTHDR_OP_IPV6, NFT_EXTHDR_OP_TCPOPT, NFT_EXTHDR_OP_IPV4, NFT_EXTHDR_OP_SCTP, __NFT_EXTHDR_OP_MAX }; #define NFT_EXTHDR_OP_MAX (__NFT_EXTHDR_OP_MAX - 1) /** * enum nft_exthdr_attributes - nf_tables extension header expression netlink attributes * * @NFTA_EXTHDR_DREG: destination register (NLA_U32: nft_registers) * @NFTA_EXTHDR_TYPE: extension header type (NLA_U8) * @NFTA_EXTHDR_OFFSET: extension header offset (NLA_U32) * @NFTA_EXTHDR_LEN: extension header length (NLA_U32) * @NFTA_EXTHDR_FLAGS: extension header flags (NLA_U32) * @NFTA_EXTHDR_OP: option match type (NLA_U32) * @NFTA_EXTHDR_SREG: option match type (NLA_U32) */ enum nft_exthdr_attributes { NFTA_EXTHDR_UNSPEC, NFTA_EXTHDR_DREG, NFTA_EXTHDR_TYPE, NFTA_EXTHDR_OFFSET, NFTA_EXTHDR_LEN, NFTA_EXTHDR_FLAGS, NFTA_EXTHDR_OP, NFTA_EXTHDR_SREG, __NFTA_EXTHDR_MAX }; #define NFTA_EXTHDR_MAX (__NFTA_EXTHDR_MAX - 1) /** * enum nft_meta_keys - nf_tables meta expression keys * * @NFT_META_LEN: packet length (skb->len) * @NFT_META_PROTOCOL: packet ethertype protocol (skb->protocol), invalid in OUTPUT * @NFT_META_PRIORITY: packet priority (skb->priority) * @NFT_META_MARK: packet mark (skb->mark) * @NFT_META_IIF: packet input interface index (dev->ifindex) * @NFT_META_OIF: packet output interface index (dev->ifindex) * @NFT_META_IIFNAME: packet input interface name (dev->name) * @NFT_META_OIFNAME: packet output interface name (dev->name) * @NFT_META_IIFTYPE: packet input interface type (dev->type) * @NFT_META_OIFTYPE: packet output interface type (dev->type) * @NFT_META_SKUID: originating socket UID (fsuid) * @NFT_META_SKGID: originating socket GID (fsgid) * @NFT_META_NFTRACE: packet nftrace bit * @NFT_META_RTCLASSID: realm value of packet's route (skb->dst->tclassid) * @NFT_META_SECMARK: packet secmark (skb->secmark) * @NFT_META_NFPROTO: netfilter protocol * @NFT_META_L4PROTO: layer 4 protocol number * @NFT_META_BRI_IIFNAME: packet input bridge interface name * @NFT_META_BRI_OIFNAME: packet output bridge interface name * @NFT_META_PKTTYPE: packet type (skb->pkt_type), special handling for loopback * @NFT_META_CPU: cpu id through smp_processor_id() * @NFT_META_IIFGROUP: packet input interface group * @NFT_META_OIFGROUP: packet output interface group * @NFT_META_CGROUP: socket control group (skb->sk->sk_classid) * @NFT_META_PRANDOM: a 32bit pseudo-random number * @NFT_META_SECPATH: boolean, secpath_exists (!!skb->sp) * @NFT_META_IIFKIND: packet input interface kind name (dev->rtnl_link_ops->kind) * @NFT_META_OIFKIND: packet output interface kind name (dev->rtnl_link_ops->kind) */ enum nft_meta_keys { NFT_META_LEN, NFT_META_PROTOCOL, NFT_META_PRIORITY, NFT_META_MARK, NFT_META_IIF, NFT_META_OIF, NFT_META_IIFNAME, NFT_META_OIFNAME, NFT_META_IIFTYPE, NFT_META_OIFTYPE, NFT_META_SKUID, NFT_META_SKGID, NFT_META_NFTRACE, NFT_META_RTCLASSID, NFT_META_SECMARK, NFT_META_NFPROTO, NFT_META_L4PROTO, NFT_META_BRI_IIFNAME, NFT_META_BRI_OIFNAME, NFT_META_PKTTYPE, NFT_META_CPU, NFT_META_IIFGROUP, NFT_META_OIFGROUP, NFT_META_CGROUP, NFT_META_PRANDOM, NFT_META_SECPATH, NFT_META_IIFKIND, NFT_META_OIFKIND, }; /** * enum nft_rt_keys - nf_tables routing expression keys * * @NFT_RT_CLASSID: realm value of packet's route (skb->dst->tclassid) * @NFT_RT_NEXTHOP4: routing nexthop for IPv4 * @NFT_RT_NEXTHOP6: routing nexthop for IPv6 * @NFT_RT_TCPMSS: fetch current path tcp mss * @NFT_RT_XFRM: boolean, skb->dst->xfrm != NULL */ enum nft_rt_keys { NFT_RT_CLASSID, NFT_RT_NEXTHOP4, NFT_RT_NEXTHOP6, NFT_RT_TCPMSS, NFT_RT_XFRM, __NFT_RT_MAX }; #define NFT_RT_MAX (__NFT_RT_MAX - 1) /** * enum nft_hash_types - nf_tables hash expression types * * @NFT_HASH_JENKINS: Jenkins Hash * @NFT_HASH_SYM: Symmetric Hash */ enum nft_hash_types { NFT_HASH_JENKINS, NFT_HASH_SYM, }; /** * enum nft_hash_attributes - nf_tables hash expression netlink attributes * * @NFTA_HASH_SREG: source register (NLA_U32) * @NFTA_HASH_DREG: destination register (NLA_U32) * @NFTA_HASH_LEN: source data length (NLA_U32) * @NFTA_HASH_MODULUS: modulus value (NLA_U32) * @NFTA_HASH_SEED: seed value (NLA_U32) * @NFTA_HASH_OFFSET: add this offset value to hash result (NLA_U32) * @NFTA_HASH_TYPE: hash operation (NLA_U32: nft_hash_types) * @NFTA_HASH_SET_NAME: name of the map to lookup (NLA_STRING) * @NFTA_HASH_SET_ID: id of the map (NLA_U32) */ enum nft_hash_attributes { NFTA_HASH_UNSPEC, NFTA_HASH_SREG, NFTA_HASH_DREG, NFTA_HASH_LEN, NFTA_HASH_MODULUS, NFTA_HASH_SEED, NFTA_HASH_OFFSET, NFTA_HASH_TYPE, NFTA_HASH_SET_NAME, /* deprecated */ NFTA_HASH_SET_ID, /* deprecated */ __NFTA_HASH_MAX, }; #define NFTA_HASH_MAX (__NFTA_HASH_MAX - 1) /** * enum nft_meta_attributes - nf_tables meta expression netlink attributes * * @NFTA_META_DREG: destination register (NLA_U32) * @NFTA_META_KEY: meta data item to load (NLA_U32: nft_meta_keys) * @NFTA_META_SREG: source register (NLA_U32) */ enum nft_meta_attributes { NFTA_META_UNSPEC, NFTA_META_DREG, NFTA_META_KEY, NFTA_META_SREG, __NFTA_META_MAX }; #define NFTA_META_MAX (__NFTA_META_MAX - 1) /** * enum nft_rt_attributes - nf_tables routing expression netlink attributes * * @NFTA_RT_DREG: destination register (NLA_U32) * @NFTA_RT_KEY: routing data item to load (NLA_U32: nft_rt_keys) */ enum nft_rt_attributes { NFTA_RT_UNSPEC, NFTA_RT_DREG, NFTA_RT_KEY, __NFTA_RT_MAX }; #define NFTA_RT_MAX (__NFTA_RT_MAX - 1) /** * enum nft_socket_attributes - nf_tables socket expression netlink attributes * * @NFTA_SOCKET_KEY: socket key to match * @NFTA_SOCKET_DREG: destination register */ enum nft_socket_attributes { NFTA_SOCKET_UNSPEC, NFTA_SOCKET_KEY, NFTA_SOCKET_DREG, __NFTA_SOCKET_MAX }; #define NFTA_SOCKET_MAX (__NFTA_SOCKET_MAX - 1) /* * enum nft_socket_keys - nf_tables socket expression keys * * @NFT_SOCKET_TRANSPARENT: Value of the IP(V6)_TRANSPARENT socket option_ */ enum nft_socket_keys { NFT_SOCKET_TRANSPARENT, __NFT_SOCKET_MAX }; #define NFT_SOCKET_MAX (__NFT_SOCKET_MAX - 1) /** * enum nft_ct_keys - nf_tables ct expression keys * * @NFT_CT_STATE: conntrack state (bitmask of enum ip_conntrack_info) * @NFT_CT_DIRECTION: conntrack direction (enum ip_conntrack_dir) * @NFT_CT_STATUS: conntrack status (bitmask of enum ip_conntrack_status) * @NFT_CT_MARK: conntrack mark value * @NFT_CT_SECMARK: conntrack secmark value * @NFT_CT_EXPIRATION: relative conntrack expiration time in ms * @NFT_CT_HELPER: connection tracking helper assigned to conntrack * @NFT_CT_L3PROTOCOL: conntrack layer 3 protocol * @NFT_CT_SRC: conntrack layer 3 protocol source (IPv4/IPv6 address, deprecated) * @NFT_CT_DST: conntrack layer 3 protocol destination (IPv4/IPv6 address, deprecated) * @NFT_CT_PROTOCOL: conntrack layer 4 protocol * @NFT_CT_PROTO_SRC: conntrack layer 4 protocol source * @NFT_CT_PROTO_DST: conntrack layer 4 protocol destination * @NFT_CT_LABELS: conntrack labels * @NFT_CT_PKTS: conntrack packets * @NFT_CT_BYTES: conntrack bytes * @NFT_CT_AVGPKT: conntrack average bytes per packet * @NFT_CT_ZONE: conntrack zone * @NFT_CT_EVENTMASK: ctnetlink events to be generated for this conntrack * @NFT_CT_SRC_IP: conntrack layer 3 protocol source (IPv4 address) * @NFT_CT_DST_IP: conntrack layer 3 protocol destination (IPv4 address) * @NFT_CT_SRC_IP6: conntrack layer 3 protocol source (IPv6 address) * @NFT_CT_DST_IP6: conntrack layer 3 protocol destination (IPv6 address) */ enum nft_ct_keys { NFT_CT_STATE, NFT_CT_DIRECTION, NFT_CT_STATUS, NFT_CT_MARK, NFT_CT_SECMARK, NFT_CT_EXPIRATION, NFT_CT_HELPER, NFT_CT_L3PROTOCOL, NFT_CT_SRC, NFT_CT_DST, NFT_CT_PROTOCOL, NFT_CT_PROTO_SRC, NFT_CT_PROTO_DST, NFT_CT_LABELS, NFT_CT_PKTS, NFT_CT_BYTES, NFT_CT_AVGPKT, NFT_CT_ZONE, NFT_CT_EVENTMASK, NFT_CT_SRC_IP, NFT_CT_DST_IP, NFT_CT_SRC_IP6, NFT_CT_DST_IP6, __NFT_CT_MAX }; #define NFT_CT_MAX (__NFT_CT_MAX - 1) /** * enum nft_ct_attributes - nf_tables ct expression netlink attributes * * @NFTA_CT_DREG: destination register (NLA_U32) * @NFTA_CT_KEY: conntrack data item to load (NLA_U32: nft_ct_keys) * @NFTA_CT_DIRECTION: direction in case of directional keys (NLA_U8) * @NFTA_CT_SREG: source register (NLA_U32) */ enum nft_ct_attributes { NFTA_CT_UNSPEC, NFTA_CT_DREG, NFTA_CT_KEY, NFTA_CT_DIRECTION, NFTA_CT_SREG, __NFTA_CT_MAX }; #define NFTA_CT_MAX (__NFTA_CT_MAX - 1) /** * enum nft_flow_attributes - ct offload expression attributes * @NFTA_FLOW_TABLE_NAME: flow table name (NLA_STRING) */ enum nft_offload_attributes { NFTA_FLOW_UNSPEC, NFTA_FLOW_TABLE_NAME, __NFTA_FLOW_MAX, }; #define NFTA_FLOW_MAX (__NFTA_FLOW_MAX - 1) enum nft_limit_type { NFT_LIMIT_PKTS, NFT_LIMIT_PKT_BYTES }; enum nft_limit_flags { NFT_LIMIT_F_INV = (1 << 0), }; /** * enum nft_limit_attributes - nf_tables limit expression netlink attributes * * @NFTA_LIMIT_RATE: refill rate (NLA_U64) * @NFTA_LIMIT_UNIT: refill unit (NLA_U64) * @NFTA_LIMIT_BURST: burst (NLA_U32) * @NFTA_LIMIT_TYPE: type of limit (NLA_U32: enum nft_limit_type) * @NFTA_LIMIT_FLAGS: flags (NLA_U32: enum nft_limit_flags) */ enum nft_limit_attributes { NFTA_LIMIT_UNSPEC, NFTA_LIMIT_RATE, NFTA_LIMIT_UNIT, NFTA_LIMIT_BURST, NFTA_LIMIT_TYPE, NFTA_LIMIT_FLAGS, NFTA_LIMIT_PAD, __NFTA_LIMIT_MAX }; #define NFTA_LIMIT_MAX (__NFTA_LIMIT_MAX - 1) enum nft_connlimit_flags { NFT_CONNLIMIT_F_INV = (1 << 0), }; /** * enum nft_connlimit_attributes - nf_tables connlimit expression netlink attributes * * @NFTA_CONNLIMIT_COUNT: number of connections (NLA_U32) * @NFTA_CONNLIMIT_FLAGS: flags (NLA_U32: enum nft_connlimit_flags) */ enum nft_connlimit_attributes { NFTA_CONNLIMIT_UNSPEC, NFTA_CONNLIMIT_COUNT, NFTA_CONNLIMIT_FLAGS, __NFTA_CONNLIMIT_MAX }; #define NFTA_CONNLIMIT_MAX (__NFTA_CONNLIMIT_MAX - 1) /** * enum nft_counter_attributes - nf_tables counter expression netlink attributes * * @NFTA_COUNTER_BYTES: number of bytes (NLA_U64) * @NFTA_COUNTER_PACKETS: number of packets (NLA_U64) */ enum nft_counter_attributes { NFTA_COUNTER_UNSPEC, NFTA_COUNTER_BYTES, NFTA_COUNTER_PACKETS, NFTA_COUNTER_PAD, __NFTA_COUNTER_MAX }; #define NFTA_COUNTER_MAX (__NFTA_COUNTER_MAX - 1) /** * enum nft_log_attributes - nf_tables log expression netlink attributes * * @NFTA_LOG_GROUP: netlink group to send messages to (NLA_U32) * @NFTA_LOG_PREFIX: prefix to prepend to log messages (NLA_STRING) * @NFTA_LOG_SNAPLEN: length of payload to include in netlink message (NLA_U32) * @NFTA_LOG_QTHRESHOLD: queue threshold (NLA_U32) * @NFTA_LOG_LEVEL: log level (NLA_U32) * @NFTA_LOG_FLAGS: logging flags (NLA_U32) */ enum nft_log_attributes { NFTA_LOG_UNSPEC, NFTA_LOG_GROUP, NFTA_LOG_PREFIX, NFTA_LOG_SNAPLEN, NFTA_LOG_QTHRESHOLD, NFTA_LOG_LEVEL, NFTA_LOG_FLAGS, __NFTA_LOG_MAX }; #define NFTA_LOG_MAX (__NFTA_LOG_MAX - 1) /** * enum nft_log_level - nf_tables log levels * * @NFT_LOGLEVEL_EMERG: system is unusable * @NFT_LOGLEVEL_ALERT: action must be taken immediately * @NFT_LOGLEVEL_CRIT: critical conditions * @NFT_LOGLEVEL_ERR: error conditions * @NFT_LOGLEVEL_WARNING: warning conditions * @NFT_LOGLEVEL_NOTICE: normal but significant condition * @NFT_LOGLEVEL_INFO: informational * @NFT_LOGLEVEL_DEBUG: debug-level messages * @NFT_LOGLEVEL_AUDIT: enabling audit logging */ enum nft_log_level { NFT_LOGLEVEL_EMERG, NFT_LOGLEVEL_ALERT, NFT_LOGLEVEL_CRIT, NFT_LOGLEVEL_ERR, NFT_LOGLEVEL_WARNING, NFT_LOGLEVEL_NOTICE, NFT_LOGLEVEL_INFO, NFT_LOGLEVEL_DEBUG, NFT_LOGLEVEL_AUDIT, __NFT_LOGLEVEL_MAX }; #define NFT_LOGLEVEL_MAX (__NFT_LOGLEVEL_MAX - 1) /** * enum nft_queue_attributes - nf_tables queue expression netlink attributes * * @NFTA_QUEUE_NUM: netlink queue to send messages to (NLA_U16) * @NFTA_QUEUE_TOTAL: number of queues to load balance packets on (NLA_U16) * @NFTA_QUEUE_FLAGS: various flags (NLA_U16) * @NFTA_QUEUE_SREG_QNUM: source register of queue number (NLA_U32: nft_registers) */ enum nft_queue_attributes { NFTA_QUEUE_UNSPEC, NFTA_QUEUE_NUM, NFTA_QUEUE_TOTAL, NFTA_QUEUE_FLAGS, NFTA_QUEUE_SREG_QNUM, __NFTA_QUEUE_MAX }; #define NFTA_QUEUE_MAX (__NFTA_QUEUE_MAX - 1) #define NFT_QUEUE_FLAG_BYPASS 0x01 /* for compatibility with v2 */ #define NFT_QUEUE_FLAG_CPU_FANOUT 0x02 /* use current CPU (no hashing) */ #define NFT_QUEUE_FLAG_MASK 0x03 enum nft_quota_flags { NFT_QUOTA_F_INV = (1 << 0), NFT_QUOTA_F_DEPLETED = (1 << 1), }; /** * enum nft_quota_attributes - nf_tables quota expression netlink attributes * * @NFTA_QUOTA_BYTES: quota in bytes (NLA_U16) * @NFTA_QUOTA_FLAGS: flags (NLA_U32) * @NFTA_QUOTA_CONSUMED: quota already consumed in bytes (NLA_U64) */ enum nft_quota_attributes { NFTA_QUOTA_UNSPEC, NFTA_QUOTA_BYTES, NFTA_QUOTA_FLAGS, NFTA_QUOTA_PAD, NFTA_QUOTA_CONSUMED, __NFTA_QUOTA_MAX }; #define NFTA_QUOTA_MAX (__NFTA_QUOTA_MAX - 1) /** * enum nft_secmark_attributes - nf_tables secmark object netlink attributes * * @NFTA_SECMARK_CTX: security context (NLA_STRING) */ enum nft_secmark_attributes { NFTA_SECMARK_UNSPEC, NFTA_SECMARK_CTX, __NFTA_SECMARK_MAX, }; #define NFTA_SECMARK_MAX (__NFTA_SECMARK_MAX - 1) /* Max security context length */ #define NFT_SECMARK_CTX_MAXLEN 256 /** * enum nft_reject_types - nf_tables reject expression reject types * * @NFT_REJECT_ICMP_UNREACH: reject using ICMP unreachable * @NFT_REJECT_TCP_RST: reject using TCP RST * @NFT_REJECT_ICMPX_UNREACH: abstracted ICMP unreachable for bridge and inet */ enum nft_reject_types { NFT_REJECT_ICMP_UNREACH, NFT_REJECT_TCP_RST, NFT_REJECT_ICMPX_UNREACH, }; /** * enum nft_reject_code - Generic reject codes for IPv4/IPv6 * * @NFT_REJECT_ICMPX_NO_ROUTE: no route to host / network unreachable * @NFT_REJECT_ICMPX_PORT_UNREACH: port unreachable * @NFT_REJECT_ICMPX_HOST_UNREACH: host unreachable * @NFT_REJECT_ICMPX_ADMIN_PROHIBITED: administratively prohibited * * These codes are mapped to real ICMP and ICMPv6 codes. */ enum nft_reject_inet_code { NFT_REJECT_ICMPX_NO_ROUTE = 0, NFT_REJECT_ICMPX_PORT_UNREACH, NFT_REJECT_ICMPX_HOST_UNREACH, NFT_REJECT_ICMPX_ADMIN_PROHIBITED, __NFT_REJECT_ICMPX_MAX }; #define NFT_REJECT_ICMPX_MAX (__NFT_REJECT_ICMPX_MAX - 1) /** * enum nft_reject_attributes - nf_tables reject expression netlink attributes * * @NFTA_REJECT_TYPE: packet type to use (NLA_U32: nft_reject_types) * @NFTA_REJECT_ICMP_CODE: ICMP code to use (NLA_U8) */ enum nft_reject_attributes { NFTA_REJECT_UNSPEC, NFTA_REJECT_TYPE, NFTA_REJECT_ICMP_CODE, __NFTA_REJECT_MAX }; #define NFTA_REJECT_MAX (__NFTA_REJECT_MAX - 1) /** * enum nft_nat_types - nf_tables nat expression NAT types * * @NFT_NAT_SNAT: source NAT * @NFT_NAT_DNAT: destination NAT */ enum nft_nat_types { NFT_NAT_SNAT, NFT_NAT_DNAT, }; /** * enum nft_nat_attributes - nf_tables nat expression netlink attributes * * @NFTA_NAT_TYPE: NAT type (NLA_U32: nft_nat_types) * @NFTA_NAT_FAMILY: NAT family (NLA_U32) * @NFTA_NAT_REG_ADDR_MIN: source register of address range start (NLA_U32: nft_registers) * @NFTA_NAT_REG_ADDR_MAX: source register of address range end (NLA_U32: nft_registers) * @NFTA_NAT_REG_PROTO_MIN: source register of proto range start (NLA_U32: nft_registers) * @NFTA_NAT_REG_PROTO_MAX: source register of proto range end (NLA_U32: nft_registers) * @NFTA_NAT_FLAGS: NAT flags (see NF_NAT_RANGE_* in linux/netfilter/nf_nat.h) (NLA_U32) */ enum nft_nat_attributes { NFTA_NAT_UNSPEC, NFTA_NAT_TYPE, NFTA_NAT_FAMILY, NFTA_NAT_REG_ADDR_MIN, NFTA_NAT_REG_ADDR_MAX, NFTA_NAT_REG_PROTO_MIN, NFTA_NAT_REG_PROTO_MAX, NFTA_NAT_FLAGS, __NFTA_NAT_MAX }; #define NFTA_NAT_MAX (__NFTA_NAT_MAX - 1) /** * enum nft_tproxy_attributes - nf_tables tproxy expression netlink attributes * * NFTA_TPROXY_FAMILY: Target address family (NLA_U32: nft_registers) * NFTA_TPROXY_REG_ADDR: Target address register (NLA_U32: nft_registers) * NFTA_TPROXY_REG_PORT: Target port register (NLA_U32: nft_registers) */ enum nft_tproxy_attributes { NFTA_TPROXY_UNSPEC, NFTA_TPROXY_FAMILY, NFTA_TPROXY_REG_ADDR, NFTA_TPROXY_REG_PORT, __NFTA_TPROXY_MAX }; #define NFTA_TPROXY_MAX (__NFTA_TPROXY_MAX - 1) /** * enum nft_masq_attributes - nf_tables masquerade expression attributes * * @NFTA_MASQ_FLAGS: NAT flags (see NF_NAT_RANGE_* in linux/netfilter/nf_nat.h) (NLA_U32) * @NFTA_MASQ_REG_PROTO_MIN: source register of proto range start (NLA_U32: nft_registers) * @NFTA_MASQ_REG_PROTO_MAX: source register of proto range end (NLA_U32: nft_registers) */ enum nft_masq_attributes { NFTA_MASQ_UNSPEC, NFTA_MASQ_FLAGS, NFTA_MASQ_REG_PROTO_MIN, NFTA_MASQ_REG_PROTO_MAX, __NFTA_MASQ_MAX }; #define NFTA_MASQ_MAX (__NFTA_MASQ_MAX - 1) /** * enum nft_redir_attributes - nf_tables redirect expression netlink attributes * * @NFTA_REDIR_REG_PROTO_MIN: source register of proto range start (NLA_U32: nft_registers) * @NFTA_REDIR_REG_PROTO_MAX: source register of proto range end (NLA_U32: nft_registers) * @NFTA_REDIR_FLAGS: NAT flags (see NF_NAT_RANGE_* in linux/netfilter/nf_nat.h) (NLA_U32) */ enum nft_redir_attributes { NFTA_REDIR_UNSPEC, NFTA_REDIR_REG_PROTO_MIN, NFTA_REDIR_REG_PROTO_MAX, NFTA_REDIR_FLAGS, __NFTA_REDIR_MAX }; #define NFTA_REDIR_MAX (__NFTA_REDIR_MAX - 1) /** * enum nft_dup_attributes - nf_tables dup expression netlink attributes * * @NFTA_DUP_SREG_ADDR: source register of address (NLA_U32: nft_registers) * @NFTA_DUP_SREG_DEV: source register of output interface (NLA_U32: nft_register) */ enum nft_dup_attributes { NFTA_DUP_UNSPEC, NFTA_DUP_SREG_ADDR, NFTA_DUP_SREG_DEV, __NFTA_DUP_MAX }; #define NFTA_DUP_MAX (__NFTA_DUP_MAX - 1) /** * enum nft_fwd_attributes - nf_tables fwd expression netlink attributes * * @NFTA_FWD_SREG_DEV: source register of output interface (NLA_U32: nft_register) * @NFTA_FWD_SREG_ADDR: source register of destination address (NLA_U32: nft_register) * @NFTA_FWD_NFPROTO: layer 3 family of source register address (NLA_U32: enum nfproto) */ enum nft_fwd_attributes { NFTA_FWD_UNSPEC, NFTA_FWD_SREG_DEV, NFTA_FWD_SREG_ADDR, NFTA_FWD_NFPROTO, __NFTA_FWD_MAX }; #define NFTA_FWD_MAX (__NFTA_FWD_MAX - 1) /** * enum nft_objref_attributes - nf_tables stateful object expression netlink attributes * * @NFTA_OBJREF_IMM_TYPE: object type for immediate reference (NLA_U32: nft_register) * @NFTA_OBJREF_IMM_NAME: object name for immediate reference (NLA_STRING) * @NFTA_OBJREF_SET_SREG: source register of the data to look for (NLA_U32: nft_registers) * @NFTA_OBJREF_SET_NAME: name of the set where to look for (NLA_STRING) * @NFTA_OBJREF_SET_ID: id of the set where to look for in this transaction (NLA_U32) */ enum nft_objref_attributes { NFTA_OBJREF_UNSPEC, NFTA_OBJREF_IMM_TYPE, NFTA_OBJREF_IMM_NAME, NFTA_OBJREF_SET_SREG, NFTA_OBJREF_SET_NAME, NFTA_OBJREF_SET_ID, __NFTA_OBJREF_MAX }; #define NFTA_OBJREF_MAX (__NFTA_OBJREF_MAX - 1) /** * enum nft_gen_attributes - nf_tables ruleset generation attributes * * @NFTA_GEN_ID: Ruleset generation ID (NLA_U32) */ enum nft_gen_attributes { NFTA_GEN_UNSPEC, NFTA_GEN_ID, NFTA_GEN_PROC_PID, NFTA_GEN_PROC_NAME, __NFTA_GEN_MAX }; #define NFTA_GEN_MAX (__NFTA_GEN_MAX - 1) /* * enum nft_fib_attributes - nf_tables fib expression netlink attributes * * @NFTA_FIB_DREG: destination register (NLA_U32) * @NFTA_FIB_RESULT: desired result (NLA_U32) * @NFTA_FIB_FLAGS: flowi fields to initialize when querying the FIB (NLA_U32) * * The FIB expression performs a route lookup according * to the packet data. */ enum nft_fib_attributes { NFTA_FIB_UNSPEC, NFTA_FIB_DREG, NFTA_FIB_RESULT, NFTA_FIB_FLAGS, __NFTA_FIB_MAX }; #define NFTA_FIB_MAX (__NFTA_FIB_MAX - 1) enum nft_fib_result { NFT_FIB_RESULT_UNSPEC, NFT_FIB_RESULT_OIF, NFT_FIB_RESULT_OIFNAME, NFT_FIB_RESULT_ADDRTYPE, __NFT_FIB_RESULT_MAX }; #define NFT_FIB_RESULT_MAX (__NFT_FIB_RESULT_MAX - 1) enum nft_fib_flags { NFTA_FIB_F_SADDR = 1 << 0, /* look up src */ NFTA_FIB_F_DADDR = 1 << 1, /* look up dst */ NFTA_FIB_F_MARK = 1 << 2, /* use skb->mark */ NFTA_FIB_F_IIF = 1 << 3, /* restrict to iif */ NFTA_FIB_F_OIF = 1 << 4, /* restrict to oif */ NFTA_FIB_F_PRESENT = 1 << 5, /* check existence only */ }; enum nft_ct_helper_attributes { NFTA_CT_HELPER_UNSPEC, NFTA_CT_HELPER_NAME, NFTA_CT_HELPER_L3PROTO, NFTA_CT_HELPER_L4PROTO, __NFTA_CT_HELPER_MAX, }; #define NFTA_CT_HELPER_MAX (__NFTA_CT_HELPER_MAX - 1) #define NFT_OBJECT_UNSPEC 0 #define NFT_OBJECT_COUNTER 1 #define NFT_OBJECT_QUOTA 2 #define NFT_OBJECT_CT_HELPER 3 #define NFT_OBJECT_LIMIT 4 #define NFT_OBJECT_CONNLIMIT 5 #define NFT_OBJECT_TUNNEL 6 #define NFT_OBJECT_CT_TIMEOUT 7 #define NFT_OBJECT_SECMARK 8 #define __NFT_OBJECT_MAX 9 #define NFT_OBJECT_MAX (__NFT_OBJECT_MAX - 1) /** * enum nft_object_attributes - nf_tables stateful object netlink attributes * * @NFTA_OBJ_TABLE: name of the table containing the expression (NLA_STRING) * @NFTA_OBJ_NAME: name of this expression type (NLA_STRING) * @NFTA_OBJ_TYPE: stateful object type (NLA_U32) * @NFTA_OBJ_DATA: stateful object data (NLA_NESTED) * @NFTA_OBJ_USE: number of references to this expression (NLA_U32) * @NFTA_OBJ_HANDLE: object handle (NLA_U64) */ enum nft_object_attributes { NFTA_OBJ_UNSPEC, NFTA_OBJ_TABLE, NFTA_OBJ_NAME, NFTA_OBJ_TYPE, NFTA_OBJ_DATA, NFTA_OBJ_USE, NFTA_OBJ_HANDLE, NFTA_OBJ_PAD, __NFTA_OBJ_MAX }; #define NFTA_OBJ_MAX (__NFTA_OBJ_MAX - 1) /** * enum nft_flowtable_flags - nf_tables flowtable flags * * @NFT_FLOWTABLE_HW_OFFLOAD: flowtable hardware offload is enabled * @NFT_FLOWTABLE_COUNTER: enable flow counters */ enum nft_flowtable_flags { NFT_FLOWTABLE_HW_OFFLOAD = 0x1, NFT_FLOWTABLE_COUNTER = 0x2, NFT_FLOWTABLE_MASK = (NFT_FLOWTABLE_HW_OFFLOAD | NFT_FLOWTABLE_COUNTER) }; /** * enum nft_flowtable_attributes - nf_tables flow table netlink attributes * * @NFTA_FLOWTABLE_TABLE: name of the table containing the expression (NLA_STRING) * @NFTA_FLOWTABLE_NAME: name of this flow table (NLA_STRING) * @NFTA_FLOWTABLE_HOOK: netfilter hook configuration(NLA_U32) * @NFTA_FLOWTABLE_USE: number of references to this flow table (NLA_U32) * @NFTA_FLOWTABLE_HANDLE: object handle (NLA_U64) * @NFTA_FLOWTABLE_FLAGS: flags (NLA_U32) */ enum nft_flowtable_attributes { NFTA_FLOWTABLE_UNSPEC, NFTA_FLOWTABLE_TABLE, NFTA_FLOWTABLE_NAME, NFTA_FLOWTABLE_HOOK, NFTA_FLOWTABLE_USE, NFTA_FLOWTABLE_HANDLE, NFTA_FLOWTABLE_PAD, NFTA_FLOWTABLE_FLAGS, __NFTA_FLOWTABLE_MAX }; #define NFTA_FLOWTABLE_MAX (__NFTA_FLOWTABLE_MAX - 1) /** * enum nft_flowtable_hook_attributes - nf_tables flow table hook netlink attributes * * @NFTA_FLOWTABLE_HOOK_NUM: netfilter hook number (NLA_U32) * @NFTA_FLOWTABLE_HOOK_PRIORITY: netfilter hook priority (NLA_U32) * @NFTA_FLOWTABLE_HOOK_DEVS: input devices this flow table is bound to (NLA_NESTED) */ enum nft_flowtable_hook_attributes { NFTA_FLOWTABLE_HOOK_UNSPEC, NFTA_FLOWTABLE_HOOK_NUM, NFTA_FLOWTABLE_HOOK_PRIORITY, NFTA_FLOWTABLE_HOOK_DEVS, __NFTA_FLOWTABLE_HOOK_MAX }; #define NFTA_FLOWTABLE_HOOK_MAX (__NFTA_FLOWTABLE_HOOK_MAX - 1) /** * enum nft_device_attributes - nf_tables device netlink attributes * * @NFTA_DEVICE_NAME: name of this device (NLA_STRING) */ enum nft_devices_attributes { NFTA_DEVICE_UNSPEC, NFTA_DEVICE_NAME, __NFTA_DEVICE_MAX }; #define NFTA_DEVICE_MAX (__NFTA_DEVICE_MAX - 1) /* * enum nft_xfrm_attributes - nf_tables xfrm expr netlink attributes * * @NFTA_XFRM_DREG: destination register (NLA_U32) * @NFTA_XFRM_KEY: enum nft_xfrm_keys (NLA_U32) * @NFTA_XFRM_DIR: direction (NLA_U8) * @NFTA_XFRM_SPNUM: index in secpath array (NLA_U32) */ enum nft_xfrm_attributes { NFTA_XFRM_UNSPEC, NFTA_XFRM_DREG, NFTA_XFRM_KEY, NFTA_XFRM_DIR, NFTA_XFRM_SPNUM, __NFTA_XFRM_MAX }; #define NFTA_XFRM_MAX (__NFTA_XFRM_MAX - 1) enum nft_xfrm_keys { NFT_XFRM_KEY_UNSPEC, NFT_XFRM_KEY_DADDR_IP4, NFT_XFRM_KEY_DADDR_IP6, NFT_XFRM_KEY_SADDR_IP4, NFT_XFRM_KEY_SADDR_IP6, NFT_XFRM_KEY_REQID, NFT_XFRM_KEY_SPI, __NFT_XFRM_KEY_MAX, }; #define NFT_XFRM_KEY_MAX (__NFT_XFRM_KEY_MAX - 1) /** * enum nft_trace_attributes - nf_tables trace netlink attributes * * @NFTA_TRACE_TABLE: name of the table (NLA_STRING) * @NFTA_TRACE_CHAIN: name of the chain (NLA_STRING) * @NFTA_TRACE_RULE_HANDLE: numeric handle of the rule (NLA_U64) * @NFTA_TRACE_TYPE: type of the event (NLA_U32: nft_trace_types) * @NFTA_TRACE_VERDICT: verdict returned by hook (NLA_NESTED: nft_verdicts) * @NFTA_TRACE_ID: pseudo-id, same for each skb traced (NLA_U32) * @NFTA_TRACE_LL_HEADER: linklayer header (NLA_BINARY) * @NFTA_TRACE_NETWORK_HEADER: network header (NLA_BINARY) * @NFTA_TRACE_TRANSPORT_HEADER: transport header (NLA_BINARY) * @NFTA_TRACE_IIF: indev ifindex (NLA_U32) * @NFTA_TRACE_IIFTYPE: netdev->type of indev (NLA_U16) * @NFTA_TRACE_OIF: outdev ifindex (NLA_U32) * @NFTA_TRACE_OIFTYPE: netdev->type of outdev (NLA_U16) * @NFTA_TRACE_MARK: nfmark (NLA_U32) * @NFTA_TRACE_NFPROTO: nf protocol processed (NLA_U32) * @NFTA_TRACE_POLICY: policy that decided fate of packet (NLA_U32) */ enum nft_trace_attributes { NFTA_TRACE_UNSPEC, NFTA_TRACE_TABLE, NFTA_TRACE_CHAIN, NFTA_TRACE_RULE_HANDLE, NFTA_TRACE_TYPE, NFTA_TRACE_VERDICT, NFTA_TRACE_ID, NFTA_TRACE_LL_HEADER, NFTA_TRACE_NETWORK_HEADER, NFTA_TRACE_TRANSPORT_HEADER, NFTA_TRACE_IIF, NFTA_TRACE_IIFTYPE, NFTA_TRACE_OIF, NFTA_TRACE_OIFTYPE, NFTA_TRACE_MARK, NFTA_TRACE_NFPROTO, NFTA_TRACE_POLICY, NFTA_TRACE_PAD, __NFTA_TRACE_MAX }; #define NFTA_TRACE_MAX (__NFTA_TRACE_MAX - 1) enum nft_trace_types { NFT_TRACETYPE_UNSPEC, NFT_TRACETYPE_POLICY, NFT_TRACETYPE_RETURN, NFT_TRACETYPE_RULE, __NFT_TRACETYPE_MAX }; #define NFT_TRACETYPE_MAX (__NFT_TRACETYPE_MAX - 1) /** * enum nft_ng_attributes - nf_tables number generator expression netlink attributes * * @NFTA_NG_DREG: destination register (NLA_U32) * @NFTA_NG_MODULUS: maximum counter value (NLA_U32) * @NFTA_NG_TYPE: operation type (NLA_U32) * @NFTA_NG_OFFSET: offset to be added to the counter (NLA_U32) * @NFTA_NG_SET_NAME: name of the map to lookup (NLA_STRING) * @NFTA_NG_SET_ID: id of the map (NLA_U32) */ enum nft_ng_attributes { NFTA_NG_UNSPEC, NFTA_NG_DREG, NFTA_NG_MODULUS, NFTA_NG_TYPE, NFTA_NG_OFFSET, NFTA_NG_SET_NAME, /* deprecated */ NFTA_NG_SET_ID, /* deprecated */ __NFTA_NG_MAX }; #define NFTA_NG_MAX (__NFTA_NG_MAX - 1) enum nft_ng_types { NFT_NG_INCREMENTAL, NFT_NG_RANDOM, __NFT_NG_MAX }; #define NFT_NG_MAX (__NFT_NG_MAX - 1) #endif /* _LINUX_NF_TABLES_H */ linux/netfilter/xt_iprange.h000064400000001105151027430560012210 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NETFILTER_XT_IPRANGE_H #define _LINUX_NETFILTER_XT_IPRANGE_H 1 #include #include enum { IPRANGE_SRC = 1 << 0, /* match source IP address */ IPRANGE_DST = 1 << 1, /* match destination IP address */ IPRANGE_SRC_INV = 1 << 4, /* negate the condition */ IPRANGE_DST_INV = 1 << 5, /* -"- */ }; struct xt_iprange_mtinfo { union nf_inet_addr src_min, src_max; union nf_inet_addr dst_min, dst_max; __u8 flags; }; #endif /* _LINUX_NETFILTER_XT_IPRANGE_H */ linux/netfilter/nf_conntrack_tuple_common.h000064400000001600151027430560015276 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _NF_CONNTRACK_TUPLE_COMMON_H #define _NF_CONNTRACK_TUPLE_COMMON_H #include #include #include /* IP_CT_IS_REPLY */ enum ip_conntrack_dir { IP_CT_DIR_ORIGINAL, IP_CT_DIR_REPLY, IP_CT_DIR_MAX }; /* The protocol-specific manipulable parts of the tuple: always in * network order */ union nf_conntrack_man_proto { /* Add other protocols here. */ __be16 all; struct { __be16 port; } tcp; struct { __be16 port; } udp; struct { __be16 id; } icmp; struct { __be16 port; } dccp; struct { __be16 port; } sctp; struct { __be16 key; /* GRE key is 32bit, PPtP only uses 16bit */ } gre; }; #define CTINFO2DIR(ctinfo) ((ctinfo) >= IP_CT_IS_REPLY ? IP_CT_DIR_REPLY : IP_CT_DIR_ORIGINAL) #endif /* _NF_CONNTRACK_TUPLE_COMMON_H */ linux/netfilter/xt_state.h000064400000000513151027430560011705 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_STATE_H #define _XT_STATE_H #define XT_STATE_BIT(ctinfo) (1 << ((ctinfo)%IP_CT_IS_REPLY+1)) #define XT_STATE_INVALID (1 << 0) #define XT_STATE_UNTRACKED (1 << (IP_CT_NUMBER + 1)) struct xt_state_info { unsigned int statemask; }; #endif /*_XT_STATE_H*/ linux/stddef.h000064400000002774151027430560007342 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_STDDEF_H #define _LINUX_STDDEF_H #ifndef __always_inline #define __always_inline __inline__ #endif /** * __struct_group() - Create a mirrored named and anonyomous struct * * @TAG: The tag name for the named sub-struct (usually empty) * @NAME: The identifier name of the mirrored sub-struct * @ATTRS: Any struct attributes (usually empty) * @MEMBERS: The member declarations for the mirrored structs * * Used to create an anonymous union of two structs with identical layout * and size: one anonymous and one named. The former's members can be used * normally without sub-struct naming, and the latter can be used to * reason about the start, end, and size of the group of struct members. * The named struct can also be explicitly tagged for layer reuse, as well * as both having struct attributes appended. */ #define __struct_group(TAG, NAME, ATTRS, MEMBERS...) \ union { \ struct { MEMBERS } ATTRS; \ struct TAG { MEMBERS } ATTRS NAME; \ } #endif /* * __DECLARE_FLEX_ARRAY() - Declare a flexible array usable in a union * * @TYPE: The type of each flexible array element * @NAME: The name of the flexible array member * * In order to have a flexible array member in a union or alone in a * struct, it needs to be wrapped in an anonymous struct with at least 1 * named member, but that member can be empty. */ #define __DECLARE_FLEX_ARRAY(TYPE, NAME) \ struct { \ struct { } __empty_ ## NAME; \ TYPE NAME[]; \ } linux/vhost_types.h000064400000007635151027430560010461 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_VHOST_TYPES_H #define _LINUX_VHOST_TYPES_H /* Userspace interface for in-kernel virtio accelerators. */ /* vhost is used to reduce the number of system calls involved in virtio. * * Existing virtio net code is used in the guest without modification. * * This header includes interface used by userspace hypervisor for * device configuration. */ #include #include #include struct vhost_vring_state { unsigned int index; unsigned int num; }; struct vhost_vring_file { unsigned int index; int fd; /* Pass -1 to unbind from file. */ }; struct vhost_vring_addr { unsigned int index; /* Option flags. */ unsigned int flags; /* Flag values: */ /* Whether log address is valid. If set enables logging. */ #define VHOST_VRING_F_LOG 0 /* Start of array of descriptors (virtually contiguous) */ __u64 desc_user_addr; /* Used structure address. Must be 32 bit aligned */ __u64 used_user_addr; /* Available structure address. Must be 16 bit aligned */ __u64 avail_user_addr; /* Logging support. */ /* Log writes to used structure, at offset calculated from specified * address. Address must be 32 bit aligned. */ __u64 log_guest_addr; }; /* no alignment requirement */ struct vhost_iotlb_msg { __u64 iova; __u64 size; __u64 uaddr; #define VHOST_ACCESS_RO 0x1 #define VHOST_ACCESS_WO 0x2 #define VHOST_ACCESS_RW 0x3 __u8 perm; #define VHOST_IOTLB_MISS 1 #define VHOST_IOTLB_UPDATE 2 #define VHOST_IOTLB_INVALIDATE 3 #define VHOST_IOTLB_ACCESS_FAIL 4 /* * VHOST_IOTLB_BATCH_BEGIN and VHOST_IOTLB_BATCH_END allow modifying * multiple mappings in one go: beginning with * VHOST_IOTLB_BATCH_BEGIN, followed by any number of * VHOST_IOTLB_UPDATE messages, and ending with VHOST_IOTLB_BATCH_END. * When one of these two values is used as the message type, the rest * of the fields in the message are ignored. There's no guarantee that * these changes take place automatically in the device. */ #define VHOST_IOTLB_BATCH_BEGIN 5 #define VHOST_IOTLB_BATCH_END 6 __u8 type; }; #define VHOST_IOTLB_MSG 0x1 #define VHOST_IOTLB_MSG_V2 0x2 struct vhost_msg { int type; union { struct vhost_iotlb_msg iotlb; __u8 padding[64]; }; }; struct vhost_msg_v2 { __u32 type; __u32 reserved; union { struct vhost_iotlb_msg iotlb; __u8 padding[64]; }; }; struct vhost_memory_region { __u64 guest_phys_addr; __u64 memory_size; /* bytes */ __u64 userspace_addr; __u64 flags_padding; /* No flags are currently specified. */ }; /* All region addresses and sizes must be 4K aligned. */ #define VHOST_PAGE_SIZE 0x1000 struct vhost_memory { __u32 nregions; __u32 padding; struct vhost_memory_region regions[0]; }; /* VHOST_SCSI specific definitions */ /* * Used by QEMU userspace to ensure a consistent vhost-scsi ABI. * * ABI Rev 0: July 2012 version starting point for v3.6-rc merge candidate + * RFC-v2 vhost-scsi userspace. Add GET_ABI_VERSION ioctl usage * ABI Rev 1: January 2013. Ignore vhost_tpgt field in struct vhost_scsi_target. * All the targets under vhost_wwpn can be seen and used by guset. */ #define VHOST_SCSI_ABI_VERSION 1 struct vhost_scsi_target { int abi_version; char vhost_wwpn[224]; /* TRANSPORT_IQN_LEN */ unsigned short vhost_tpgt; unsigned short reserved; }; /* VHOST_VDPA specific definitions */ struct vhost_vdpa_config { __u32 off; __u32 len; __u8 buf[0]; }; /* vhost vdpa IOVA range * @first: First address that can be mapped by vhost-vDPA * @last: Last address that can be mapped by vhost-vDPA */ struct vhost_vdpa_iova_range { __u64 first; __u64 last; }; /* Feature bits */ /* Log all write descriptors. Can be changed while device is active. */ #define VHOST_F_LOG_ALL 26 /* vhost-net should add virtio_net_hdr for RX, and strip for TX packets. */ #define VHOST_NET_F_VIRTIO_NET_HDR 27 #endif linux/erspan.h000064400000002043151027430560007346 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ERSPAN Tunnel Metadata * * Copyright (c) 2018 VMware * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * Userspace API for metadata mode ERSPAN tunnel */ #ifndef _ERSPAN_H #define _ERSPAN_H #include /* For __beXX in userspace */ #include /* ERSPAN version 2 metadata header */ struct erspan_md2 { __be32 timestamp; __be16 sgt; /* security group tag */ #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 hwid_upper:2, ft:5, p:1; __u8 o:1, gra:2, dir:1, hwid:4; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 p:1, ft:5, hwid_upper:2; __u8 hwid:4, dir:1, gra:2, o:1; #else #error "Please fix " #endif }; struct erspan_metadata { int version; union { __be32 index; /* Version 1 (type II)*/ struct erspan_md2 md2; /* Version 2 (type III) */ } u; }; #endif /* _ERSPAN_H */ linux/stat.h000064400000014320151027430560007032 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_STAT_H #define _LINUX_STAT_H #include #if defined(__KERNEL__) || !defined(__GLIBC__) || (__GLIBC__ < 2) #define S_IFMT 00170000 #define S_IFSOCK 0140000 #define S_IFLNK 0120000 #define S_IFREG 0100000 #define S_IFBLK 0060000 #define S_IFDIR 0040000 #define S_IFCHR 0020000 #define S_IFIFO 0010000 #define S_ISUID 0004000 #define S_ISGID 0002000 #define S_ISVTX 0001000 #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) #define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) #define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) #define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) #define S_IRWXU 00700 #define S_IRUSR 00400 #define S_IWUSR 00200 #define S_IXUSR 00100 #define S_IRWXG 00070 #define S_IRGRP 00040 #define S_IWGRP 00020 #define S_IXGRP 00010 #define S_IRWXO 00007 #define S_IROTH 00004 #define S_IWOTH 00002 #define S_IXOTH 00001 #endif /* * Timestamp structure for the timestamps in struct statx. * * tv_sec holds the number of seconds before (negative) or after (positive) * 00:00:00 1st January 1970 UTC. * * tv_nsec holds a number of nanoseconds (0..999,999,999) after the tv_sec time. * * __reserved is held in case we need a yet finer resolution. */ struct statx_timestamp { __s64 tv_sec; __u32 tv_nsec; __s32 __reserved; }; /* * Structures for the extended file attribute retrieval system call * (statx()). * * The caller passes a mask of what they're specifically interested in as a * parameter to statx(). What statx() actually got will be indicated in * st_mask upon return. * * For each bit in the mask argument: * * - if the datum is not supported: * * - the bit will be cleared, and * * - the datum will be set to an appropriate fabricated value if one is * available (eg. CIFS can take a default uid and gid), otherwise * * - the field will be cleared; * * - otherwise, if explicitly requested: * * - the datum will be synchronised to the server if AT_STATX_FORCE_SYNC is * set or if the datum is considered out of date, and * * - the field will be filled in and the bit will be set; * * - otherwise, if not requested, but available in approximate form without any * effort, it will be filled in anyway, and the bit will be set upon return * (it might not be up to date, however, and no attempt will be made to * synchronise the internal state first); * * - otherwise the field and the bit will be cleared before returning. * * Items in STATX_BASIC_STATS may be marked unavailable on return, but they * will have values installed for compatibility purposes so that stat() and * co. can be emulated in userspace. */ struct statx { /* 0x00 */ __u32 stx_mask; /* What results were written [uncond] */ __u32 stx_blksize; /* Preferred general I/O size [uncond] */ __u64 stx_attributes; /* Flags conveying information about the file [uncond] */ /* 0x10 */ __u32 stx_nlink; /* Number of hard links */ __u32 stx_uid; /* User ID of owner */ __u32 stx_gid; /* Group ID of owner */ __u16 stx_mode; /* File mode */ __u16 __spare0[1]; /* 0x20 */ __u64 stx_ino; /* Inode number */ __u64 stx_size; /* File size */ __u64 stx_blocks; /* Number of 512-byte blocks allocated */ __u64 stx_attributes_mask; /* Mask to show what's supported in stx_attributes */ /* 0x40 */ struct statx_timestamp stx_atime; /* Last access time */ struct statx_timestamp stx_btime; /* File creation time */ struct statx_timestamp stx_ctime; /* Last attribute change time */ struct statx_timestamp stx_mtime; /* Last data modification time */ /* 0x80 */ __u32 stx_rdev_major; /* Device ID of special file [if bdev/cdev] */ __u32 stx_rdev_minor; __u32 stx_dev_major; /* ID of device containing file [uncond] */ __u32 stx_dev_minor; /* 0x90 */ __u64 __spare2[14]; /* Spare space for future expansion */ /* 0x100 */ }; /* * Flags to be stx_mask * * Query request/result mask for statx() and struct statx::stx_mask. * * These bits should be set in the mask argument of statx() to request * particular items when calling statx(). */ #define STATX_TYPE 0x00000001U /* Want/got stx_mode & S_IFMT */ #define STATX_MODE 0x00000002U /* Want/got stx_mode & ~S_IFMT */ #define STATX_NLINK 0x00000004U /* Want/got stx_nlink */ #define STATX_UID 0x00000008U /* Want/got stx_uid */ #define STATX_GID 0x00000010U /* Want/got stx_gid */ #define STATX_ATIME 0x00000020U /* Want/got stx_atime */ #define STATX_MTIME 0x00000040U /* Want/got stx_mtime */ #define STATX_CTIME 0x00000080U /* Want/got stx_ctime */ #define STATX_INO 0x00000100U /* Want/got stx_ino */ #define STATX_SIZE 0x00000200U /* Want/got stx_size */ #define STATX_BLOCKS 0x00000400U /* Want/got stx_blocks */ #define STATX_BASIC_STATS 0x000007ffU /* The stuff in the normal stat struct */ #define STATX_BTIME 0x00000800U /* Want/got stx_btime */ #define STATX_ALL 0x00000fffU /* All currently supported flags */ #define STATX__RESERVED 0x80000000U /* Reserved for future struct statx expansion */ /* * Attributes to be found in stx_attributes and masked in stx_attributes_mask. * * These give information about the features or the state of a file that might * be of use to ordinary userspace programs such as GUIs or ls rather than * specialised tools. * * Note that the flags marked [I] correspond to the FS_IOC_SETFLAGS flags * semantically. Where possible, the numerical value is picked to correspond * also. Note that the DAX attribute indicates that the file is in the CPU * direct access state. It does not correspond to the per-inode flag that * some filesystems support. * */ #define STATX_ATTR_COMPRESSED 0x00000004 /* [I] File is compressed by the fs */ #define STATX_ATTR_IMMUTABLE 0x00000010 /* [I] File is marked immutable */ #define STATX_ATTR_APPEND 0x00000020 /* [I] File is append-only */ #define STATX_ATTR_NODUMP 0x00000040 /* [I] File is not to be dumped */ #define STATX_ATTR_ENCRYPTED 0x00000800 /* [I] File requires key to decrypt in fs */ #define STATX_ATTR_AUTOMOUNT 0x00001000 /* Dir: Automount trigger */ #define STATX_ATTR_DAX 0x00200000 /* File is currently in DAX state */ #endif /* _LINUX_STAT_H */ linux/tipc_config.h000064400000034564151027430560010357 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * include/uapi/linux/tipc_config.h: Header for TIPC configuration interface * * Copyright (c) 2003-2006, Ericsson AB * Copyright (c) 2005-2007, 2010-2011, Wind River Systems * 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. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _LINUX_TIPC_CONFIG_H_ #define _LINUX_TIPC_CONFIG_H_ #include #include #include #include #include /* for ntohs etc. */ /* * Configuration * * All configuration management messaging involves sending a request message * to the TIPC configuration service on a node, which sends a reply message * back. (In the future multi-message replies may be supported.) * * Both request and reply messages consist of a transport header and payload. * The transport header contains info about the desired operation; * the payload consists of zero or more type/length/value (TLV) items * which specify parameters or results for the operation. * * For many operations, the request and reply messages have a fixed number * of TLVs (usually zero or one); however, some reply messages may return * a variable number of TLVs. A failed request is denoted by the presence * of an "error string" TLV in the reply message instead of the TLV(s) the * reply should contain if the request succeeds. */ /* * Public commands: * May be issued by any process. * Accepted by own node, or by remote node only if remote management enabled. */ #define TIPC_CMD_NOOP 0x0000 /* tx none, rx none */ #define TIPC_CMD_GET_NODES 0x0001 /* tx net_addr, rx node_info(s) */ #define TIPC_CMD_GET_MEDIA_NAMES 0x0002 /* tx none, rx media_name(s) */ #define TIPC_CMD_GET_BEARER_NAMES 0x0003 /* tx none, rx bearer_name(s) */ #define TIPC_CMD_GET_LINKS 0x0004 /* tx net_addr, rx link_info(s) */ #define TIPC_CMD_SHOW_NAME_TABLE 0x0005 /* tx name_tbl_query, rx ultra_string */ #define TIPC_CMD_SHOW_PORTS 0x0006 /* tx none, rx ultra_string */ #define TIPC_CMD_SHOW_LINK_STATS 0x000B /* tx link_name, rx ultra_string */ #define TIPC_CMD_SHOW_STATS 0x000F /* tx unsigned, rx ultra_string */ /* * Protected commands: * May only be issued by "network administration capable" process. * Accepted by own node, or by remote node only if remote management enabled * and this node is zone manager. */ #define TIPC_CMD_GET_REMOTE_MNG 0x4003 /* tx none, rx unsigned */ #define TIPC_CMD_GET_MAX_PORTS 0x4004 /* tx none, rx unsigned */ #define TIPC_CMD_GET_MAX_PUBL 0x4005 /* obsoleted */ #define TIPC_CMD_GET_MAX_SUBSCR 0x4006 /* obsoleted */ #define TIPC_CMD_GET_MAX_ZONES 0x4007 /* obsoleted */ #define TIPC_CMD_GET_MAX_CLUSTERS 0x4008 /* obsoleted */ #define TIPC_CMD_GET_MAX_NODES 0x4009 /* obsoleted */ #define TIPC_CMD_GET_MAX_SLAVES 0x400A /* obsoleted */ #define TIPC_CMD_GET_NETID 0x400B /* tx none, rx unsigned */ #define TIPC_CMD_ENABLE_BEARER 0x4101 /* tx bearer_config, rx none */ #define TIPC_CMD_DISABLE_BEARER 0x4102 /* tx bearer_name, rx none */ #define TIPC_CMD_SET_LINK_TOL 0x4107 /* tx link_config, rx none */ #define TIPC_CMD_SET_LINK_PRI 0x4108 /* tx link_config, rx none */ #define TIPC_CMD_SET_LINK_WINDOW 0x4109 /* tx link_config, rx none */ #define TIPC_CMD_SET_LOG_SIZE 0x410A /* obsoleted */ #define TIPC_CMD_DUMP_LOG 0x410B /* obsoleted */ #define TIPC_CMD_RESET_LINK_STATS 0x410C /* tx link_name, rx none */ /* * Private commands: * May only be issued by "network administration capable" process. * Accepted by own node only; cannot be used on a remote node. */ #define TIPC_CMD_SET_NODE_ADDR 0x8001 /* tx net_addr, rx none */ #define TIPC_CMD_SET_REMOTE_MNG 0x8003 /* tx unsigned, rx none */ #define TIPC_CMD_SET_MAX_PORTS 0x8004 /* tx unsigned, rx none */ #define TIPC_CMD_SET_MAX_PUBL 0x8005 /* obsoleted */ #define TIPC_CMD_SET_MAX_SUBSCR 0x8006 /* obsoleted */ #define TIPC_CMD_SET_MAX_ZONES 0x8007 /* obsoleted */ #define TIPC_CMD_SET_MAX_CLUSTERS 0x8008 /* obsoleted */ #define TIPC_CMD_SET_MAX_NODES 0x8009 /* obsoleted */ #define TIPC_CMD_SET_MAX_SLAVES 0x800A /* obsoleted */ #define TIPC_CMD_SET_NETID 0x800B /* tx unsigned, rx none */ /* * Reserved commands: * May not be issued by any process. * Used internally by TIPC. */ #define TIPC_CMD_NOT_NET_ADMIN 0xC001 /* tx none, rx none */ /* * TLV types defined for TIPC */ #define TIPC_TLV_NONE 0 /* no TLV present */ #define TIPC_TLV_VOID 1 /* empty TLV (0 data bytes)*/ #define TIPC_TLV_UNSIGNED 2 /* 32-bit integer */ #define TIPC_TLV_STRING 3 /* char[128] (max) */ #define TIPC_TLV_LARGE_STRING 4 /* char[2048] (max) */ #define TIPC_TLV_ULTRA_STRING 5 /* char[32768] (max) */ #define TIPC_TLV_ERROR_STRING 16 /* char[128] containing "error code" */ #define TIPC_TLV_NET_ADDR 17 /* 32-bit integer denoting */ #define TIPC_TLV_MEDIA_NAME 18 /* char[TIPC_MAX_MEDIA_NAME] */ #define TIPC_TLV_BEARER_NAME 19 /* char[TIPC_MAX_BEARER_NAME] */ #define TIPC_TLV_LINK_NAME 20 /* char[TIPC_MAX_LINK_NAME] */ #define TIPC_TLV_NODE_INFO 21 /* struct tipc_node_info */ #define TIPC_TLV_LINK_INFO 22 /* struct tipc_link_info */ #define TIPC_TLV_BEARER_CONFIG 23 /* struct tipc_bearer_config */ #define TIPC_TLV_LINK_CONFIG 24 /* struct tipc_link_config */ #define TIPC_TLV_NAME_TBL_QUERY 25 /* struct tipc_name_table_query */ #define TIPC_TLV_PORT_REF 26 /* 32-bit port reference */ /* * Link priority limits (min, default, max, media default) */ #define TIPC_MIN_LINK_PRI 0 #define TIPC_DEF_LINK_PRI 10 #define TIPC_MAX_LINK_PRI 31 #define TIPC_MEDIA_LINK_PRI (TIPC_MAX_LINK_PRI + 1) /* * Link tolerance limits (min, default, max), in ms */ #define TIPC_MIN_LINK_TOL 50 #define TIPC_DEF_LINK_TOL 1500 #define TIPC_MAX_LINK_TOL 30000 #if (TIPC_MIN_LINK_TOL < 16) #error "TIPC_MIN_LINK_TOL is too small (abort limit may be NaN)" #endif /* * Link window limits (min, default, max), in packets */ #define TIPC_MIN_LINK_WIN 16 #define TIPC_DEF_LINK_WIN 50 #define TIPC_MAX_LINK_WIN 8191 /* * Default MTU for UDP media */ #define TIPC_DEF_LINK_UDP_MTU 14000 struct tipc_node_info { __be32 addr; /* network address of node */ __be32 up; /* 0=down, 1= up */ }; struct tipc_link_info { __be32 dest; /* network address of peer node */ __be32 up; /* 0=down, 1=up */ char str[TIPC_MAX_LINK_NAME]; /* link name */ }; struct tipc_bearer_config { __be32 priority; /* Range [1,31]. Override per link */ __be32 disc_domain; /* describing desired nodes */ char name[TIPC_MAX_BEARER_NAME]; }; struct tipc_link_config { __be32 value; char name[TIPC_MAX_LINK_NAME]; }; #define TIPC_NTQ_ALLTYPES 0x80000000 struct tipc_name_table_query { __be32 depth; /* 1:type, 2:+name info, 3:+port info, 4+:+debug info */ __be32 type; /* {t,l,u} info ignored if high bit of "depth" is set */ __be32 lowbound; /* (i.e. displays all entries of name table) */ __be32 upbound; }; /* * The error string TLV is a null-terminated string describing the cause * of the request failure. To simplify error processing (and to save space) * the first character of the string can be a special error code character * (lying by the range 0x80 to 0xFF) which represents a pre-defined reason. */ #define TIPC_CFG_TLV_ERROR "\x80" /* request contains incorrect TLV(s) */ #define TIPC_CFG_NOT_NET_ADMIN "\x81" /* must be network administrator */ #define TIPC_CFG_NOT_ZONE_MSTR "\x82" /* must be zone master */ #define TIPC_CFG_NO_REMOTE "\x83" /* remote management not enabled */ #define TIPC_CFG_NOT_SUPPORTED "\x84" /* request is not supported by TIPC */ #define TIPC_CFG_INVALID_VALUE "\x85" /* request has invalid argument value */ /* * A TLV consists of a descriptor, followed by the TLV value. * TLV descriptor fields are stored in network byte order; * TLV values must also be stored in network byte order (where applicable). * TLV descriptors must be aligned to addresses which are multiple of 4, * so up to 3 bytes of padding may exist at the end of the TLV value area. * There must not be any padding between the TLV descriptor and its value. */ struct tlv_desc { __be16 tlv_len; /* TLV length (descriptor + value) */ __be16 tlv_type; /* TLV identifier */ }; #define TLV_ALIGNTO 4 #define TLV_ALIGN(datalen) (((datalen)+(TLV_ALIGNTO-1)) & ~(TLV_ALIGNTO-1)) #define TLV_LENGTH(datalen) (sizeof(struct tlv_desc) + (datalen)) #define TLV_SPACE(datalen) (TLV_ALIGN(TLV_LENGTH(datalen))) #define TLV_DATA(tlv) ((void *)((char *)(tlv) + TLV_LENGTH(0))) static __inline__ int TLV_OK(const void *tlv, __u16 space) { /* * Would also like to check that "tlv" is a multiple of 4, * but don't know how to do this in a portable way. * - Tried doing (!(tlv & (TLV_ALIGNTO-1))), but GCC compiler * won't allow binary "&" with a pointer. * - Tried casting "tlv" to integer type, but causes warning about size * mismatch when pointer is bigger than chosen type (int, long, ...). */ return (space >= TLV_SPACE(0)) && (ntohs(((struct tlv_desc *)tlv)->tlv_len) <= space); } static __inline__ int TLV_CHECK(const void *tlv, __u16 space, __u16 exp_type) { return TLV_OK(tlv, space) && (ntohs(((struct tlv_desc *)tlv)->tlv_type) == exp_type); } static __inline__ int TLV_GET_LEN(struct tlv_desc *tlv) { return ntohs(tlv->tlv_len); } static __inline__ void TLV_SET_LEN(struct tlv_desc *tlv, __u16 len) { tlv->tlv_len = htons(len); } static __inline__ int TLV_CHECK_TYPE(struct tlv_desc *tlv, __u16 type) { return (ntohs(tlv->tlv_type) == type); } static __inline__ void TLV_SET_TYPE(struct tlv_desc *tlv, __u16 type) { tlv->tlv_type = htons(type); } static __inline__ int TLV_SET(void *tlv, __u16 type, void *data, __u16 len) { struct tlv_desc *tlv_ptr; int tlv_len; tlv_len = TLV_LENGTH(len); tlv_ptr = (struct tlv_desc *)tlv; tlv_ptr->tlv_type = htons(type); tlv_ptr->tlv_len = htons(tlv_len); if (len && data) memcpy(TLV_DATA(tlv_ptr), data, tlv_len); return TLV_SPACE(len); } /* * A TLV list descriptor simplifies processing of messages * containing multiple TLVs. */ struct tlv_list_desc { struct tlv_desc *tlv_ptr; /* ptr to current TLV */ __u32 tlv_space; /* # bytes from curr TLV to list end */ }; static __inline__ void TLV_LIST_INIT(struct tlv_list_desc *list, void *data, __u32 space) { list->tlv_ptr = (struct tlv_desc *)data; list->tlv_space = space; } static __inline__ int TLV_LIST_EMPTY(struct tlv_list_desc *list) { return (list->tlv_space == 0); } static __inline__ int TLV_LIST_CHECK(struct tlv_list_desc *list, __u16 exp_type) { return TLV_CHECK(list->tlv_ptr, list->tlv_space, exp_type); } static __inline__ void *TLV_LIST_DATA(struct tlv_list_desc *list) { return TLV_DATA(list->tlv_ptr); } static __inline__ void TLV_LIST_STEP(struct tlv_list_desc *list) { __u16 tlv_space = TLV_ALIGN(ntohs(list->tlv_ptr->tlv_len)); list->tlv_ptr = (struct tlv_desc *)((char *)list->tlv_ptr + tlv_space); list->tlv_space -= tlv_space; } /* * Configuration messages exchanged via NETLINK_GENERIC use the following * family id, name, version and command. */ #define TIPC_GENL_NAME "TIPC" #define TIPC_GENL_VERSION 0x1 #define TIPC_GENL_CMD 0x1 /* * TIPC specific header used in NETLINK_GENERIC requests. */ struct tipc_genlmsghdr { __u32 dest; /* Destination address */ __u16 cmd; /* Command */ __u16 reserved; /* Unused */ }; #define TIPC_GENL_HDRLEN NLMSG_ALIGN(sizeof(struct tipc_genlmsghdr)) /* * Configuration messages exchanged via TIPC sockets use the TIPC configuration * message header, which is defined below. This structure is analogous * to the Netlink message header, but fields are stored in network byte order * and no padding is permitted between the header and the message data * that follows. */ struct tipc_cfg_msg_hdr { __be32 tcm_len; /* Message length (including header) */ __be16 tcm_type; /* Command type */ __be16 tcm_flags; /* Additional flags */ char tcm_reserved[8]; /* Unused */ }; #define TCM_F_REQUEST 0x1 /* Flag: Request message */ #define TCM_F_MORE 0x2 /* Flag: Message to be continued */ #define TCM_ALIGN(datalen) (((datalen)+3) & ~3) #define TCM_LENGTH(datalen) (sizeof(struct tipc_cfg_msg_hdr) + datalen) #define TCM_SPACE(datalen) (TCM_ALIGN(TCM_LENGTH(datalen))) #define TCM_DATA(tcm_hdr) ((void *)((char *)(tcm_hdr) + TCM_LENGTH(0))) static __inline__ int TCM_SET(void *msg, __u16 cmd, __u16 flags, void *data, __u16 data_len) { struct tipc_cfg_msg_hdr *tcm_hdr; int msg_len; msg_len = TCM_LENGTH(data_len); tcm_hdr = (struct tipc_cfg_msg_hdr *)msg; tcm_hdr->tcm_len = htonl(msg_len); tcm_hdr->tcm_type = htons(cmd); tcm_hdr->tcm_flags = htons(flags); if (data_len && data) memcpy(TCM_DATA(msg), data, data_len); return TCM_SPACE(data_len); } #endif linux/pkt_cls.h000064400000044117151027430560007525 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_PKT_CLS_H #define __LINUX_PKT_CLS_H #include #include #define TC_COOKIE_MAX_SIZE 16 /* Action attributes */ enum { TCA_ACT_UNSPEC, TCA_ACT_KIND, TCA_ACT_OPTIONS, TCA_ACT_INDEX, TCA_ACT_STATS, TCA_ACT_PAD, TCA_ACT_COOKIE, TCA_ACT_FLAGS, TCA_ACT_HW_STATS, TCA_ACT_USED_HW_STATS, TCA_ACT_IN_HW_COUNT, __TCA_ACT_MAX }; /* See other TCA_ACT_FLAGS_ * flags in include/net/act_api.h. */ #define TCA_ACT_FLAGS_NO_PERCPU_STATS (1 << 0) /* Don't use percpu allocator for * actions stats. */ #define TCA_ACT_FLAGS_SKIP_HW (1 << 1) /* don't offload action to HW */ #define TCA_ACT_FLAGS_SKIP_SW (1 << 2) /* don't use action in SW */ /* tca HW stats type * When user does not pass the attribute, he does not care. * It is the same as if he would pass the attribute with * all supported bits set. * In case no bits are set, user is not interested in getting any HW statistics. */ #define TCA_ACT_HW_STATS_IMMEDIATE (1 << 0) /* Means that in dump, user * gets the current HW stats * state from the device * queried at the dump time. */ #define TCA_ACT_HW_STATS_DELAYED (1 << 1) /* Means that in dump, user gets * HW stats that might be out of date * for some time, maybe couple of * seconds. This is the case when * driver polls stats updates * periodically or when it gets async * stats update from the device. */ #define TCA_ACT_MAX __TCA_ACT_MAX #define TCA_OLD_COMPAT (TCA_ACT_MAX+1) #define TCA_ACT_MAX_PRIO 32 #define TCA_ACT_BIND 1 #define TCA_ACT_NOBIND 0 #define TCA_ACT_UNBIND 1 #define TCA_ACT_NOUNBIND 0 #define TCA_ACT_REPLACE 1 #define TCA_ACT_NOREPLACE 0 #define TC_ACT_UNSPEC (-1) #define TC_ACT_OK 0 #define TC_ACT_RECLASSIFY 1 #define TC_ACT_SHOT 2 #define TC_ACT_PIPE 3 #define TC_ACT_STOLEN 4 #define TC_ACT_QUEUED 5 #define TC_ACT_REPEAT 6 #define TC_ACT_REDIRECT 7 #define TC_ACT_TRAP 8 /* For hw path, this means "trap to cpu" * and don't further process the frame * in hardware. For sw path, this is * equivalent of TC_ACT_STOLEN - drop * the skb and act like everything * is alright. */ #define TC_ACT_VALUE_MAX TC_ACT_TRAP /* There is a special kind of actions called "extended actions", * which need a value parameter. These have a local opcode located in * the highest nibble, starting from 1. The rest of the bits * are used to carry the value. These two parts together make * a combined opcode. */ #define __TC_ACT_EXT_SHIFT 28 #define __TC_ACT_EXT(local) ((local) << __TC_ACT_EXT_SHIFT) #define TC_ACT_EXT_VAL_MASK ((1 << __TC_ACT_EXT_SHIFT) - 1) #define TC_ACT_EXT_OPCODE(combined) ((combined) & (~TC_ACT_EXT_VAL_MASK)) #define TC_ACT_EXT_CMP(combined, opcode) (TC_ACT_EXT_OPCODE(combined) == opcode) #define TC_ACT_JUMP __TC_ACT_EXT(1) #define TC_ACT_GOTO_CHAIN __TC_ACT_EXT(2) #define TC_ACT_EXT_OPCODE_MAX TC_ACT_GOTO_CHAIN /* These macros are put here for binary compatibility with userspace apps that * make use of them. For kernel code and new userspace apps, use the TCA_ID_* * versions. */ #define TCA_ACT_GACT 5 #define TCA_ACT_IPT 6 #define TCA_ACT_PEDIT 7 #define TCA_ACT_MIRRED 8 #define TCA_ACT_NAT 9 #define TCA_ACT_XT 10 #define TCA_ACT_SKBEDIT 11 #define TCA_ACT_VLAN 12 #define TCA_ACT_BPF 13 #define TCA_ACT_CONNMARK 14 #define TCA_ACT_SKBMOD 15 #define TCA_ACT_CSUM 16 #define TCA_ACT_TUNNEL_KEY 17 #define TCA_ACT_SIMP 22 #define TCA_ACT_IFE 25 #define TCA_ACT_SAMPLE 26 /* Action type identifiers*/ enum tca_id { TCA_ID_UNSPEC = 0, TCA_ID_POLICE = 1, TCA_ID_GACT = TCA_ACT_GACT, TCA_ID_IPT = TCA_ACT_IPT, TCA_ID_PEDIT = TCA_ACT_PEDIT, TCA_ID_MIRRED = TCA_ACT_MIRRED, TCA_ID_NAT = TCA_ACT_NAT, TCA_ID_XT = TCA_ACT_XT, TCA_ID_SKBEDIT = TCA_ACT_SKBEDIT, TCA_ID_VLAN = TCA_ACT_VLAN, TCA_ID_BPF = TCA_ACT_BPF, TCA_ID_CONNMARK = TCA_ACT_CONNMARK, TCA_ID_SKBMOD = TCA_ACT_SKBMOD, TCA_ID_CSUM = TCA_ACT_CSUM, TCA_ID_TUNNEL_KEY = TCA_ACT_TUNNEL_KEY, TCA_ID_SIMP = TCA_ACT_SIMP, TCA_ID_IFE = TCA_ACT_IFE, TCA_ID_SAMPLE = TCA_ACT_SAMPLE, TCA_ID_CTINFO, TCA_ID_MPLS, TCA_ID_CT, TCA_ID_GATE, /* other actions go here */ __TCA_ID_MAX = 255 }; #define TCA_ID_MAX __TCA_ID_MAX struct tc_police { __u32 index; int action; #define TC_POLICE_UNSPEC TC_ACT_UNSPEC #define TC_POLICE_OK TC_ACT_OK #define TC_POLICE_RECLASSIFY TC_ACT_RECLASSIFY #define TC_POLICE_SHOT TC_ACT_SHOT #define TC_POLICE_PIPE TC_ACT_PIPE __u32 limit; __u32 burst; __u32 mtu; struct tc_ratespec rate; struct tc_ratespec peakrate; int refcnt; int bindcnt; __u32 capab; }; struct tcf_t { __u64 install; __u64 lastuse; __u64 expires; __u64 firstuse; }; struct tc_cnt { int refcnt; int bindcnt; }; #define tc_gen \ __u32 index; \ __u32 capab; \ int action; \ int refcnt; \ int bindcnt enum { TCA_POLICE_UNSPEC, TCA_POLICE_TBF, TCA_POLICE_RATE, TCA_POLICE_PEAKRATE, TCA_POLICE_AVRATE, TCA_POLICE_RESULT, TCA_POLICE_TM, TCA_POLICE_PAD, TCA_POLICE_RATE64, TCA_POLICE_PEAKRATE64, TCA_POLICE_PKTRATE64, TCA_POLICE_PKTBURST64, __TCA_POLICE_MAX #define TCA_POLICE_RESULT TCA_POLICE_RESULT }; #define TCA_POLICE_MAX (__TCA_POLICE_MAX - 1) /* tca flags definitions */ #define TCA_CLS_FLAGS_SKIP_HW (1 << 0) /* don't offload filter to HW */ #define TCA_CLS_FLAGS_SKIP_SW (1 << 1) /* don't use filter in SW */ #define TCA_CLS_FLAGS_IN_HW (1 << 2) /* filter is offloaded to HW */ #define TCA_CLS_FLAGS_NOT_IN_HW (1 << 3) /* filter isn't offloaded to HW */ #define TCA_CLS_FLAGS_VERBOSE (1 << 4) /* verbose logging */ /* U32 filters */ #define TC_U32_HTID(h) ((h)&0xFFF00000) #define TC_U32_USERHTID(h) (TC_U32_HTID(h)>>20) #define TC_U32_HASH(h) (((h)>>12)&0xFF) #define TC_U32_NODE(h) ((h)&0xFFF) #define TC_U32_KEY(h) ((h)&0xFFFFF) #define TC_U32_UNSPEC 0 #define TC_U32_ROOT (0xFFF00000) enum { TCA_U32_UNSPEC, TCA_U32_CLASSID, TCA_U32_HASH, TCA_U32_LINK, TCA_U32_DIVISOR, TCA_U32_SEL, TCA_U32_POLICE, TCA_U32_ACT, TCA_U32_INDEV, TCA_U32_PCNT, TCA_U32_MARK, TCA_U32_FLAGS, TCA_U32_PAD, __TCA_U32_MAX }; #define TCA_U32_MAX (__TCA_U32_MAX - 1) struct tc_u32_key { __be32 mask; __be32 val; int off; int offmask; }; struct tc_u32_sel { unsigned char flags; unsigned char offshift; unsigned char nkeys; __be16 offmask; __u16 off; short offoff; short hoff; __be32 hmask; struct tc_u32_key keys[0]; }; struct tc_u32_mark { __u32 val; __u32 mask; __u32 success; }; struct tc_u32_pcnt { __u64 rcnt; __u64 rhit; __u64 kcnts[0]; }; /* Flags */ #define TC_U32_TERMINAL 1 #define TC_U32_OFFSET 2 #define TC_U32_VAROFFSET 4 #define TC_U32_EAT 8 #define TC_U32_MAXDEPTH 8 /* RSVP filter */ enum { TCA_RSVP_UNSPEC, TCA_RSVP_CLASSID, TCA_RSVP_DST, TCA_RSVP_SRC, TCA_RSVP_PINFO, TCA_RSVP_POLICE, TCA_RSVP_ACT, __TCA_RSVP_MAX }; #define TCA_RSVP_MAX (__TCA_RSVP_MAX - 1 ) struct tc_rsvp_gpi { __u32 key; __u32 mask; int offset; }; struct tc_rsvp_pinfo { struct tc_rsvp_gpi dpi; struct tc_rsvp_gpi spi; __u8 protocol; __u8 tunnelid; __u8 tunnelhdr; __u8 pad; }; /* ROUTE filter */ enum { TCA_ROUTE4_UNSPEC, TCA_ROUTE4_CLASSID, TCA_ROUTE4_TO, TCA_ROUTE4_FROM, TCA_ROUTE4_IIF, TCA_ROUTE4_POLICE, TCA_ROUTE4_ACT, __TCA_ROUTE4_MAX }; #define TCA_ROUTE4_MAX (__TCA_ROUTE4_MAX - 1) /* FW filter */ enum { TCA_FW_UNSPEC, TCA_FW_CLASSID, TCA_FW_POLICE, TCA_FW_INDEV, TCA_FW_ACT, /* used by CONFIG_NET_CLS_ACT */ TCA_FW_MASK, __TCA_FW_MAX }; #define TCA_FW_MAX (__TCA_FW_MAX - 1) /* TC index filter */ enum { TCA_TCINDEX_UNSPEC, TCA_TCINDEX_HASH, TCA_TCINDEX_MASK, TCA_TCINDEX_SHIFT, TCA_TCINDEX_FALL_THROUGH, TCA_TCINDEX_CLASSID, TCA_TCINDEX_POLICE, TCA_TCINDEX_ACT, __TCA_TCINDEX_MAX }; #define TCA_TCINDEX_MAX (__TCA_TCINDEX_MAX - 1) /* Flow filter */ enum { FLOW_KEY_SRC, FLOW_KEY_DST, FLOW_KEY_PROTO, FLOW_KEY_PROTO_SRC, FLOW_KEY_PROTO_DST, FLOW_KEY_IIF, FLOW_KEY_PRIORITY, FLOW_KEY_MARK, FLOW_KEY_NFCT, FLOW_KEY_NFCT_SRC, FLOW_KEY_NFCT_DST, FLOW_KEY_NFCT_PROTO_SRC, FLOW_KEY_NFCT_PROTO_DST, FLOW_KEY_RTCLASSID, FLOW_KEY_SKUID, FLOW_KEY_SKGID, FLOW_KEY_VLAN_TAG, FLOW_KEY_RXHASH, __FLOW_KEY_MAX, }; #define FLOW_KEY_MAX (__FLOW_KEY_MAX - 1) enum { FLOW_MODE_MAP, FLOW_MODE_HASH, }; enum { TCA_FLOW_UNSPEC, TCA_FLOW_KEYS, TCA_FLOW_MODE, TCA_FLOW_BASECLASS, TCA_FLOW_RSHIFT, TCA_FLOW_ADDEND, TCA_FLOW_MASK, TCA_FLOW_XOR, TCA_FLOW_DIVISOR, TCA_FLOW_ACT, TCA_FLOW_POLICE, TCA_FLOW_EMATCHES, TCA_FLOW_PERTURB, __TCA_FLOW_MAX }; #define TCA_FLOW_MAX (__TCA_FLOW_MAX - 1) /* Basic filter */ struct tc_basic_pcnt { __u64 rcnt; __u64 rhit; }; enum { TCA_BASIC_UNSPEC, TCA_BASIC_CLASSID, TCA_BASIC_EMATCHES, TCA_BASIC_ACT, TCA_BASIC_POLICE, TCA_BASIC_PCNT, TCA_BASIC_PAD, __TCA_BASIC_MAX }; #define TCA_BASIC_MAX (__TCA_BASIC_MAX - 1) /* Cgroup classifier */ enum { TCA_CGROUP_UNSPEC, TCA_CGROUP_ACT, TCA_CGROUP_POLICE, TCA_CGROUP_EMATCHES, __TCA_CGROUP_MAX, }; #define TCA_CGROUP_MAX (__TCA_CGROUP_MAX - 1) /* BPF classifier */ #define TCA_BPF_FLAG_ACT_DIRECT (1 << 0) enum { TCA_BPF_UNSPEC, TCA_BPF_ACT, TCA_BPF_POLICE, TCA_BPF_CLASSID, TCA_BPF_OPS_LEN, TCA_BPF_OPS, TCA_BPF_FD, TCA_BPF_NAME, TCA_BPF_FLAGS, TCA_BPF_FLAGS_GEN, TCA_BPF_TAG, TCA_BPF_ID, __TCA_BPF_MAX, }; #define TCA_BPF_MAX (__TCA_BPF_MAX - 1) /* Flower classifier */ enum { TCA_FLOWER_UNSPEC, TCA_FLOWER_CLASSID, TCA_FLOWER_INDEV, TCA_FLOWER_ACT, TCA_FLOWER_KEY_ETH_DST, /* ETH_ALEN */ TCA_FLOWER_KEY_ETH_DST_MASK, /* ETH_ALEN */ TCA_FLOWER_KEY_ETH_SRC, /* ETH_ALEN */ TCA_FLOWER_KEY_ETH_SRC_MASK, /* ETH_ALEN */ TCA_FLOWER_KEY_ETH_TYPE, /* be16 */ TCA_FLOWER_KEY_IP_PROTO, /* u8 */ TCA_FLOWER_KEY_IPV4_SRC, /* be32 */ TCA_FLOWER_KEY_IPV4_SRC_MASK, /* be32 */ TCA_FLOWER_KEY_IPV4_DST, /* be32 */ TCA_FLOWER_KEY_IPV4_DST_MASK, /* be32 */ TCA_FLOWER_KEY_IPV6_SRC, /* struct in6_addr */ TCA_FLOWER_KEY_IPV6_SRC_MASK, /* struct in6_addr */ TCA_FLOWER_KEY_IPV6_DST, /* struct in6_addr */ TCA_FLOWER_KEY_IPV6_DST_MASK, /* struct in6_addr */ TCA_FLOWER_KEY_TCP_SRC, /* be16 */ TCA_FLOWER_KEY_TCP_DST, /* be16 */ TCA_FLOWER_KEY_UDP_SRC, /* be16 */ TCA_FLOWER_KEY_UDP_DST, /* be16 */ TCA_FLOWER_FLAGS, TCA_FLOWER_KEY_VLAN_ID, /* be16 */ TCA_FLOWER_KEY_VLAN_PRIO, /* u8 */ TCA_FLOWER_KEY_VLAN_ETH_TYPE, /* be16 */ TCA_FLOWER_KEY_ENC_KEY_ID, /* be32 */ TCA_FLOWER_KEY_ENC_IPV4_SRC, /* be32 */ TCA_FLOWER_KEY_ENC_IPV4_SRC_MASK,/* be32 */ TCA_FLOWER_KEY_ENC_IPV4_DST, /* be32 */ TCA_FLOWER_KEY_ENC_IPV4_DST_MASK,/* be32 */ TCA_FLOWER_KEY_ENC_IPV6_SRC, /* struct in6_addr */ TCA_FLOWER_KEY_ENC_IPV6_SRC_MASK,/* struct in6_addr */ TCA_FLOWER_KEY_ENC_IPV6_DST, /* struct in6_addr */ TCA_FLOWER_KEY_ENC_IPV6_DST_MASK,/* struct in6_addr */ TCA_FLOWER_KEY_TCP_SRC_MASK, /* be16 */ TCA_FLOWER_KEY_TCP_DST_MASK, /* be16 */ TCA_FLOWER_KEY_UDP_SRC_MASK, /* be16 */ TCA_FLOWER_KEY_UDP_DST_MASK, /* be16 */ TCA_FLOWER_KEY_SCTP_SRC_MASK, /* be16 */ TCA_FLOWER_KEY_SCTP_DST_MASK, /* be16 */ TCA_FLOWER_KEY_SCTP_SRC, /* be16 */ TCA_FLOWER_KEY_SCTP_DST, /* be16 */ TCA_FLOWER_KEY_ENC_UDP_SRC_PORT, /* be16 */ TCA_FLOWER_KEY_ENC_UDP_SRC_PORT_MASK, /* be16 */ TCA_FLOWER_KEY_ENC_UDP_DST_PORT, /* be16 */ TCA_FLOWER_KEY_ENC_UDP_DST_PORT_MASK, /* be16 */ TCA_FLOWER_KEY_FLAGS, /* be32 */ TCA_FLOWER_KEY_FLAGS_MASK, /* be32 */ TCA_FLOWER_KEY_ICMPV4_CODE, /* u8 */ TCA_FLOWER_KEY_ICMPV4_CODE_MASK,/* u8 */ TCA_FLOWER_KEY_ICMPV4_TYPE, /* u8 */ TCA_FLOWER_KEY_ICMPV4_TYPE_MASK,/* u8 */ TCA_FLOWER_KEY_ICMPV6_CODE, /* u8 */ TCA_FLOWER_KEY_ICMPV6_CODE_MASK,/* u8 */ TCA_FLOWER_KEY_ICMPV6_TYPE, /* u8 */ TCA_FLOWER_KEY_ICMPV6_TYPE_MASK,/* u8 */ TCA_FLOWER_KEY_ARP_SIP, /* be32 */ TCA_FLOWER_KEY_ARP_SIP_MASK, /* be32 */ TCA_FLOWER_KEY_ARP_TIP, /* be32 */ TCA_FLOWER_KEY_ARP_TIP_MASK, /* be32 */ TCA_FLOWER_KEY_ARP_OP, /* u8 */ TCA_FLOWER_KEY_ARP_OP_MASK, /* u8 */ TCA_FLOWER_KEY_ARP_SHA, /* ETH_ALEN */ TCA_FLOWER_KEY_ARP_SHA_MASK, /* ETH_ALEN */ TCA_FLOWER_KEY_ARP_THA, /* ETH_ALEN */ TCA_FLOWER_KEY_ARP_THA_MASK, /* ETH_ALEN */ TCA_FLOWER_KEY_MPLS_TTL, /* u8 - 8 bits */ TCA_FLOWER_KEY_MPLS_BOS, /* u8 - 1 bit */ TCA_FLOWER_KEY_MPLS_TC, /* u8 - 3 bits */ TCA_FLOWER_KEY_MPLS_LABEL, /* be32 - 20 bits */ TCA_FLOWER_KEY_TCP_FLAGS, /* be16 */ TCA_FLOWER_KEY_TCP_FLAGS_MASK, /* be16 */ TCA_FLOWER_KEY_IP_TOS, /* u8 */ TCA_FLOWER_KEY_IP_TOS_MASK, /* u8 */ TCA_FLOWER_KEY_IP_TTL, /* u8 */ TCA_FLOWER_KEY_IP_TTL_MASK, /* u8 */ TCA_FLOWER_KEY_CVLAN_ID, /* be16 */ TCA_FLOWER_KEY_CVLAN_PRIO, /* u8 */ TCA_FLOWER_KEY_CVLAN_ETH_TYPE, /* be16 */ TCA_FLOWER_KEY_ENC_IP_TOS, /* u8 */ TCA_FLOWER_KEY_ENC_IP_TOS_MASK, /* u8 */ TCA_FLOWER_KEY_ENC_IP_TTL, /* u8 */ TCA_FLOWER_KEY_ENC_IP_TTL_MASK, /* u8 */ TCA_FLOWER_KEY_ENC_OPTS, TCA_FLOWER_KEY_ENC_OPTS_MASK, TCA_FLOWER_IN_HW_COUNT, TCA_FLOWER_KEY_PORT_SRC_MIN, /* be16 */ TCA_FLOWER_KEY_PORT_SRC_MAX, /* be16 */ TCA_FLOWER_KEY_PORT_DST_MIN, /* be16 */ TCA_FLOWER_KEY_PORT_DST_MAX, /* be16 */ TCA_FLOWER_KEY_CT_STATE, /* u16 */ TCA_FLOWER_KEY_CT_STATE_MASK, /* u16 */ TCA_FLOWER_KEY_CT_ZONE, /* u16 */ TCA_FLOWER_KEY_CT_ZONE_MASK, /* u16 */ TCA_FLOWER_KEY_CT_MARK, /* u32 */ TCA_FLOWER_KEY_CT_MARK_MASK, /* u32 */ TCA_FLOWER_KEY_CT_LABELS, /* u128 */ TCA_FLOWER_KEY_CT_LABELS_MASK, /* u128 */ TCA_FLOWER_KEY_MPLS_OPTS, TCA_FLOWER_KEY_HASH, /* u32 */ TCA_FLOWER_KEY_HASH_MASK, /* u32 */ TCA_FLOWER_KEY_NUM_OF_VLANS, /* u8 */ TCA_FLOWER_KEY_PPPOE_SID, /* be16 */ TCA_FLOWER_KEY_PPP_PROTO, /* be16 */ TCA_FLOWER_KEY_L2TPV3_SID, /* be32 */ __TCA_FLOWER_MAX, }; #define TCA_FLOWER_MAX (__TCA_FLOWER_MAX - 1) enum { TCA_FLOWER_KEY_CT_FLAGS_NEW = 1 << 0, /* Beginning of a new connection. */ TCA_FLOWER_KEY_CT_FLAGS_ESTABLISHED = 1 << 1, /* Part of an existing connection. */ TCA_FLOWER_KEY_CT_FLAGS_RELATED = 1 << 2, /* Related to an established connection. */ TCA_FLOWER_KEY_CT_FLAGS_TRACKED = 1 << 3, /* Conntrack has occurred. */ TCA_FLOWER_KEY_CT_FLAGS_INVALID = 1 << 4, /* Conntrack is invalid. */ TCA_FLOWER_KEY_CT_FLAGS_REPLY = 1 << 5, /* Packet is in the reply direction. */ __TCA_FLOWER_KEY_CT_FLAGS_MAX, }; enum { TCA_FLOWER_KEY_ENC_OPTS_UNSPEC, TCA_FLOWER_KEY_ENC_OPTS_GENEVE, /* Nested * TCA_FLOWER_KEY_ENC_OPT_GENEVE_ * attributes */ TCA_FLOWER_KEY_ENC_OPTS_VXLAN, /* Nested * TCA_FLOWER_KEY_ENC_OPT_VXLAN_ * attributes */ TCA_FLOWER_KEY_ENC_OPTS_ERSPAN, /* Nested * TCA_FLOWER_KEY_ENC_OPT_ERSPAN_ * attributes */ __TCA_FLOWER_KEY_ENC_OPTS_MAX, }; #define TCA_FLOWER_KEY_ENC_OPTS_MAX (__TCA_FLOWER_KEY_ENC_OPTS_MAX - 1) enum { TCA_FLOWER_KEY_ENC_OPT_GENEVE_UNSPEC, TCA_FLOWER_KEY_ENC_OPT_GENEVE_CLASS, /* u16 */ TCA_FLOWER_KEY_ENC_OPT_GENEVE_TYPE, /* u8 */ TCA_FLOWER_KEY_ENC_OPT_GENEVE_DATA, /* 4 to 128 bytes */ __TCA_FLOWER_KEY_ENC_OPT_GENEVE_MAX, }; #define TCA_FLOWER_KEY_ENC_OPT_GENEVE_MAX \ (__TCA_FLOWER_KEY_ENC_OPT_GENEVE_MAX - 1) enum { TCA_FLOWER_KEY_ENC_OPT_VXLAN_UNSPEC, TCA_FLOWER_KEY_ENC_OPT_VXLAN_GBP, /* u32 */ __TCA_FLOWER_KEY_ENC_OPT_VXLAN_MAX, }; #define TCA_FLOWER_KEY_ENC_OPT_VXLAN_MAX \ (__TCA_FLOWER_KEY_ENC_OPT_VXLAN_MAX - 1) enum { TCA_FLOWER_KEY_ENC_OPT_ERSPAN_UNSPEC, TCA_FLOWER_KEY_ENC_OPT_ERSPAN_VER, /* u8 */ TCA_FLOWER_KEY_ENC_OPT_ERSPAN_INDEX, /* be32 */ TCA_FLOWER_KEY_ENC_OPT_ERSPAN_DIR, /* u8 */ TCA_FLOWER_KEY_ENC_OPT_ERSPAN_HWID, /* u8 */ __TCA_FLOWER_KEY_ENC_OPT_ERSPAN_MAX, }; #define TCA_FLOWER_KEY_ENC_OPT_ERSPAN_MAX \ (__TCA_FLOWER_KEY_ENC_OPT_ERSPAN_MAX - 1) enum { TCA_FLOWER_KEY_MPLS_OPTS_UNSPEC, TCA_FLOWER_KEY_MPLS_OPTS_LSE, __TCA_FLOWER_KEY_MPLS_OPTS_MAX, }; #define TCA_FLOWER_KEY_MPLS_OPTS_MAX (__TCA_FLOWER_KEY_MPLS_OPTS_MAX - 1) enum { TCA_FLOWER_KEY_MPLS_OPT_LSE_UNSPEC, TCA_FLOWER_KEY_MPLS_OPT_LSE_DEPTH, TCA_FLOWER_KEY_MPLS_OPT_LSE_TTL, TCA_FLOWER_KEY_MPLS_OPT_LSE_BOS, TCA_FLOWER_KEY_MPLS_OPT_LSE_TC, TCA_FLOWER_KEY_MPLS_OPT_LSE_LABEL, __TCA_FLOWER_KEY_MPLS_OPT_LSE_MAX, }; #define TCA_FLOWER_KEY_MPLS_OPT_LSE_MAX \ (__TCA_FLOWER_KEY_MPLS_OPT_LSE_MAX - 1) enum { TCA_FLOWER_KEY_FLAGS_IS_FRAGMENT = (1 << 0), TCA_FLOWER_KEY_FLAGS_FRAG_IS_FIRST = (1 << 1), }; #define TCA_FLOWER_MASK_FLAGS_RANGE (1 << 0) /* Range-based match */ /* Match-all classifier */ struct tc_matchall_pcnt { __u64 rhit; }; enum { TCA_MATCHALL_UNSPEC, TCA_MATCHALL_CLASSID, TCA_MATCHALL_ACT, TCA_MATCHALL_FLAGS, TCA_MATCHALL_PCNT, TCA_MATCHALL_PAD, __TCA_MATCHALL_MAX, }; #define TCA_MATCHALL_MAX (__TCA_MATCHALL_MAX - 1) /* Extended Matches */ struct tcf_ematch_tree_hdr { __u16 nmatches; __u16 progid; }; enum { TCA_EMATCH_TREE_UNSPEC, TCA_EMATCH_TREE_HDR, TCA_EMATCH_TREE_LIST, __TCA_EMATCH_TREE_MAX }; #define TCA_EMATCH_TREE_MAX (__TCA_EMATCH_TREE_MAX - 1) struct tcf_ematch_hdr { __u16 matchid; __u16 kind; __u16 flags; __u16 pad; /* currently unused */ }; /* 0 1 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 * +-----------------------+-+-+---+ * | Unused |S|I| R | * +-----------------------+-+-+---+ * * R(2) ::= relation to next ematch * where: 0 0 END (last ematch) * 0 1 AND * 1 0 OR * 1 1 Unused (invalid) * I(1) ::= invert result * S(1) ::= simple payload */ #define TCF_EM_REL_END 0 #define TCF_EM_REL_AND (1<<0) #define TCF_EM_REL_OR (1<<1) #define TCF_EM_INVERT (1<<2) #define TCF_EM_SIMPLE (1<<3) #define TCF_EM_REL_MASK 3 #define TCF_EM_REL_VALID(v) (((v) & TCF_EM_REL_MASK) != TCF_EM_REL_MASK) enum { TCF_LAYER_LINK, TCF_LAYER_NETWORK, TCF_LAYER_TRANSPORT, __TCF_LAYER_MAX }; #define TCF_LAYER_MAX (__TCF_LAYER_MAX - 1) /* Ematch type assignments * 1..32767 Reserved for ematches inside kernel tree * 32768..65535 Free to use, not reliable */ #define TCF_EM_CONTAINER 0 #define TCF_EM_CMP 1 #define TCF_EM_NBYTE 2 #define TCF_EM_U32 3 #define TCF_EM_META 4 #define TCF_EM_TEXT 5 #define TCF_EM_VLAN 6 #define TCF_EM_CANID 7 #define TCF_EM_IPSET 8 #define TCF_EM_IPT 9 #define TCF_EM_MAX 9 enum { TCF_EM_PROG_TC }; enum { TCF_EM_OPND_EQ, TCF_EM_OPND_GT, TCF_EM_OPND_LT }; #endif linux/edd.h000064400000012744151027430560006623 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/include/linux/edd.h * Copyright (C) 2002, 2003, 2004 Dell Inc. * by Matt Domsch * * structures and definitions for the int 13h, ax={41,48}h * BIOS Enhanced Disk Drive Services * This is based on the T13 group document D1572 Revision 0 (August 14 2002) * available at http://www.t13.org/docs2002/d1572r0.pdf. It is * very similar to D1484 Revision 3 http://www.t13.org/docs2002/d1484r3.pdf * * In a nutshell, arch/{i386,x86_64}/boot/setup.S populates a scratch * table in the boot_params that contains a list of BIOS-enumerated * boot devices. * In arch/{i386,x86_64}/kernel/setup.c, this information is * transferred into the edd structure, and in drivers/firmware/edd.c, that * information is used to identify BIOS boot disk. The code in setup.S * is very sensitive to the size of these structures. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License v2.0 as published by * the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef _LINUX_EDD_H #define _LINUX_EDD_H #include #define EDDNR 0x1e9 /* addr of number of edd_info structs at EDDBUF in boot_params - treat this as 1 byte */ #define EDDBUF 0xd00 /* addr of edd_info structs in boot_params */ #define EDDMAXNR 6 /* number of edd_info structs starting at EDDBUF */ #define EDDEXTSIZE 8 /* change these if you muck with the structures */ #define EDDPARMSIZE 74 #define CHECKEXTENSIONSPRESENT 0x41 #define GETDEVICEPARAMETERS 0x48 #define LEGACYGETDEVICEPARAMETERS 0x08 #define EDDMAGIC1 0x55AA #define EDDMAGIC2 0xAA55 #define READ_SECTORS 0x02 /* int13 AH=0x02 is READ_SECTORS command */ #define EDD_MBR_SIG_OFFSET 0x1B8 /* offset of signature in the MBR */ #define EDD_MBR_SIG_BUF 0x290 /* addr in boot params */ #define EDD_MBR_SIG_MAX 16 /* max number of signatures to store */ #define EDD_MBR_SIG_NR_BUF 0x1ea /* addr of number of MBR signtaures at EDD_MBR_SIG_BUF in boot_params - treat this as 1 byte */ #ifndef __ASSEMBLY__ #define EDD_EXT_FIXED_DISK_ACCESS (1 << 0) #define EDD_EXT_DEVICE_LOCKING_AND_EJECTING (1 << 1) #define EDD_EXT_ENHANCED_DISK_DRIVE_SUPPORT (1 << 2) #define EDD_EXT_64BIT_EXTENSIONS (1 << 3) #define EDD_INFO_DMA_BOUNDARY_ERROR_TRANSPARENT (1 << 0) #define EDD_INFO_GEOMETRY_VALID (1 << 1) #define EDD_INFO_REMOVABLE (1 << 2) #define EDD_INFO_WRITE_VERIFY (1 << 3) #define EDD_INFO_MEDIA_CHANGE_NOTIFICATION (1 << 4) #define EDD_INFO_LOCKABLE (1 << 5) #define EDD_INFO_NO_MEDIA_PRESENT (1 << 6) #define EDD_INFO_USE_INT13_FN50 (1 << 7) struct edd_device_params { __u16 length; __u16 info_flags; __u32 num_default_cylinders; __u32 num_default_heads; __u32 sectors_per_track; __u64 number_of_sectors; __u16 bytes_per_sector; __u32 dpte_ptr; /* 0xFFFFFFFF for our purposes */ __u16 key; /* = 0xBEDD */ __u8 device_path_info_length; /* = 44 */ __u8 reserved2; __u16 reserved3; __u8 host_bus_type[4]; __u8 interface_type[8]; union { struct { __u16 base_address; __u16 reserved1; __u32 reserved2; } __attribute__ ((packed)) isa; struct { __u8 bus; __u8 slot; __u8 function; __u8 channel; __u32 reserved; } __attribute__ ((packed)) pci; /* pcix is same as pci */ struct { __u64 reserved; } __attribute__ ((packed)) ibnd; struct { __u64 reserved; } __attribute__ ((packed)) xprs; struct { __u64 reserved; } __attribute__ ((packed)) htpt; struct { __u64 reserved; } __attribute__ ((packed)) unknown; } interface_path; union { struct { __u8 device; __u8 reserved1; __u16 reserved2; __u32 reserved3; __u64 reserved4; } __attribute__ ((packed)) ata; struct { __u8 device; __u8 lun; __u8 reserved1; __u8 reserved2; __u32 reserved3; __u64 reserved4; } __attribute__ ((packed)) atapi; struct { __u16 id; __u64 lun; __u16 reserved1; __u32 reserved2; } __attribute__ ((packed)) scsi; struct { __u64 serial_number; __u64 reserved; } __attribute__ ((packed)) usb; struct { __u64 eui; __u64 reserved; } __attribute__ ((packed)) i1394; struct { __u64 wwid; __u64 lun; } __attribute__ ((packed)) fibre; struct { __u64 identity_tag; __u64 reserved; } __attribute__ ((packed)) i2o; struct { __u32 array_number; __u32 reserved1; __u64 reserved2; } __attribute__ ((packed)) raid; struct { __u8 device; __u8 reserved1; __u16 reserved2; __u32 reserved3; __u64 reserved4; } __attribute__ ((packed)) sata; struct { __u64 reserved1; __u64 reserved2; } __attribute__ ((packed)) unknown; } device_path; __u8 reserved4; __u8 checksum; } __attribute__ ((packed)); struct edd_info { __u8 device; __u8 version; __u16 interface_support; __u16 legacy_max_cylinder; __u8 legacy_max_head; __u8 legacy_sectors_per_track; struct edd_device_params params; } __attribute__ ((packed)); struct edd { unsigned int mbr_signature[EDD_MBR_SIG_MAX]; struct edd_info edd_info[EDDMAXNR]; unsigned char mbr_signature_nr; unsigned char edd_info_nr; }; #endif /*!__ASSEMBLY__ */ #endif /* _LINUX_EDD_H */ linux/icmp.h000064400000005637151027430560007022 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the ICMP protocol. * * Version: @(#)icmp.h 1.0.3 04/28/93 * * Author: Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_ICMP_H #define _LINUX_ICMP_H #include #define ICMP_ECHOREPLY 0 /* Echo Reply */ #define ICMP_DEST_UNREACH 3 /* Destination Unreachable */ #define ICMP_SOURCE_QUENCH 4 /* Source Quench */ #define ICMP_REDIRECT 5 /* Redirect (change route) */ #define ICMP_ECHO 8 /* Echo Request */ #define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */ #define ICMP_PARAMETERPROB 12 /* Parameter Problem */ #define ICMP_TIMESTAMP 13 /* Timestamp Request */ #define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */ #define ICMP_INFO_REQUEST 15 /* Information Request */ #define ICMP_INFO_REPLY 16 /* Information Reply */ #define ICMP_ADDRESS 17 /* Address Mask Request */ #define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */ #define NR_ICMP_TYPES 18 /* Codes for UNREACH. */ #define ICMP_NET_UNREACH 0 /* Network Unreachable */ #define ICMP_HOST_UNREACH 1 /* Host Unreachable */ #define ICMP_PROT_UNREACH 2 /* Protocol Unreachable */ #define ICMP_PORT_UNREACH 3 /* Port Unreachable */ #define ICMP_FRAG_NEEDED 4 /* Fragmentation Needed/DF set */ #define ICMP_SR_FAILED 5 /* Source Route failed */ #define ICMP_NET_UNKNOWN 6 #define ICMP_HOST_UNKNOWN 7 #define ICMP_HOST_ISOLATED 8 #define ICMP_NET_ANO 9 #define ICMP_HOST_ANO 10 #define ICMP_NET_UNR_TOS 11 #define ICMP_HOST_UNR_TOS 12 #define ICMP_PKT_FILTERED 13 /* Packet filtered */ #define ICMP_PREC_VIOLATION 14 /* Precedence violation */ #define ICMP_PREC_CUTOFF 15 /* Precedence cut off */ #define NR_ICMP_UNREACH 15 /* instead of hardcoding immediate value */ /* Codes for REDIRECT. */ #define ICMP_REDIR_NET 0 /* Redirect Net */ #define ICMP_REDIR_HOST 1 /* Redirect Host */ #define ICMP_REDIR_NETTOS 2 /* Redirect Net for TOS */ #define ICMP_REDIR_HOSTTOS 3 /* Redirect Host for TOS */ /* Codes for TIME_EXCEEDED. */ #define ICMP_EXC_TTL 0 /* TTL count exceeded */ #define ICMP_EXC_FRAGTIME 1 /* Fragment Reass time exceeded */ struct icmphdr { __u8 type; __u8 code; __sum16 checksum; union { struct { __be16 id; __be16 sequence; } echo; __be32 gateway; struct { __be16 __unused; __be16 mtu; } frag; __u8 reserved[4]; } un; }; /* * constants for (set|get)sockopt */ #define ICMP_FILTER 1 struct icmp_filter { __u32 data; }; #endif /* _LINUX_ICMP_H */ linux/if_pppol2tp.h000064400000006334151027430560010323 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /*************************************************************************** * Linux PPP over L2TP (PPPoL2TP) Socket Implementation (RFC 2661) * * This file supplies definitions required by the PPP over L2TP driver * (l2tp_ppp.c). All version information wrt this file is located in l2tp_ppp.c * * License: * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #ifndef __LINUX_IF_PPPOL2TP_H #define __LINUX_IF_PPPOL2TP_H #include #include #include #include /* Structure used to connect() the socket to a particular tunnel UDP * socket over IPv4. */ struct pppol2tp_addr { __kernel_pid_t pid; /* pid that owns the fd. * 0 => current */ int fd; /* FD of UDP socket to use */ struct sockaddr_in addr; /* IP address and port to send to */ __u16 s_tunnel, s_session; /* For matching incoming packets */ __u16 d_tunnel, d_session; /* For sending outgoing packets */ }; /* Structure used to connect() the socket to a particular tunnel UDP * socket over IPv6. */ struct pppol2tpin6_addr { __kernel_pid_t pid; /* pid that owns the fd. * 0 => current */ int fd; /* FD of UDP socket to use */ __u16 s_tunnel, s_session; /* For matching incoming packets */ __u16 d_tunnel, d_session; /* For sending outgoing packets */ struct sockaddr_in6 addr; /* IP address and port to send to */ }; /* The L2TPv3 protocol changes tunnel and session ids from 16 to 32 * bits. So we need a different sockaddr structure. */ struct pppol2tpv3_addr { __kernel_pid_t pid; /* pid that owns the fd. * 0 => current */ int fd; /* FD of UDP or IP socket to use */ struct sockaddr_in addr; /* IP address and port to send to */ __u32 s_tunnel, s_session; /* For matching incoming packets */ __u32 d_tunnel, d_session; /* For sending outgoing packets */ }; struct pppol2tpv3in6_addr { __kernel_pid_t pid; /* pid that owns the fd. * 0 => current */ int fd; /* FD of UDP or IP socket to use */ __u32 s_tunnel, s_session; /* For matching incoming packets */ __u32 d_tunnel, d_session; /* For sending outgoing packets */ struct sockaddr_in6 addr; /* IP address and port to send to */ }; /* Socket options: * DEBUG - bitmask of debug message categories * SENDSEQ - 0 => don't send packets with sequence numbers * 1 => send packets with sequence numbers * RECVSEQ - 0 => receive packet sequence numbers are optional * 1 => drop receive packets without sequence numbers * LNSMODE - 0 => act as LAC. * 1 => act as LNS. * REORDERTO - reorder timeout (in millisecs). If 0, don't try to reorder. */ enum { PPPOL2TP_SO_DEBUG = 1, PPPOL2TP_SO_RECVSEQ = 2, PPPOL2TP_SO_SENDSEQ = 3, PPPOL2TP_SO_LNSMODE = 4, PPPOL2TP_SO_REORDERTO = 5, }; /* Debug message categories for the DEBUG socket option (deprecated) */ enum { PPPOL2TP_MSG_DEBUG = L2TP_MSG_DEBUG, PPPOL2TP_MSG_CONTROL = L2TP_MSG_CONTROL, PPPOL2TP_MSG_SEQ = L2TP_MSG_SEQ, PPPOL2TP_MSG_DATA = L2TP_MSG_DATA, }; #endif /* __LINUX_IF_PPPOL2TP_H */ linux/apm_bios.h000064400000007143151027430560007655 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Include file for the interface to an APM BIOS * Copyright 1994-2001 Stephen Rothwell (sfr@canb.auug.org.au) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #ifndef _LINUX_APM_H #define _LINUX_APM_H #include typedef unsigned short apm_event_t; typedef unsigned short apm_eventinfo_t; struct apm_bios_info { __u16 version; __u16 cseg; __u32 offset; __u16 cseg_16; __u16 dseg; __u16 flags; __u16 cseg_len; __u16 cseg_16_len; __u16 dseg_len; }; /* * Power states */ #define APM_STATE_READY 0x0000 #define APM_STATE_STANDBY 0x0001 #define APM_STATE_SUSPEND 0x0002 #define APM_STATE_OFF 0x0003 #define APM_STATE_BUSY 0x0004 #define APM_STATE_REJECT 0x0005 #define APM_STATE_OEM_SYS 0x0020 #define APM_STATE_OEM_DEV 0x0040 #define APM_STATE_DISABLE 0x0000 #define APM_STATE_ENABLE 0x0001 #define APM_STATE_DISENGAGE 0x0000 #define APM_STATE_ENGAGE 0x0001 /* * Events (results of Get PM Event) */ #define APM_SYS_STANDBY 0x0001 #define APM_SYS_SUSPEND 0x0002 #define APM_NORMAL_RESUME 0x0003 #define APM_CRITICAL_RESUME 0x0004 #define APM_LOW_BATTERY 0x0005 #define APM_POWER_STATUS_CHANGE 0x0006 #define APM_UPDATE_TIME 0x0007 #define APM_CRITICAL_SUSPEND 0x0008 #define APM_USER_STANDBY 0x0009 #define APM_USER_SUSPEND 0x000a #define APM_STANDBY_RESUME 0x000b #define APM_CAPABILITY_CHANGE 0x000c #define APM_USER_HIBERNATION 0x000d #define APM_HIBERNATION_RESUME 0x000e /* * Error codes */ #define APM_SUCCESS 0x00 #define APM_DISABLED 0x01 #define APM_CONNECTED 0x02 #define APM_NOT_CONNECTED 0x03 #define APM_16_CONNECTED 0x05 #define APM_16_UNSUPPORTED 0x06 #define APM_32_CONNECTED 0x07 #define APM_32_UNSUPPORTED 0x08 #define APM_BAD_DEVICE 0x09 #define APM_BAD_PARAM 0x0a #define APM_NOT_ENGAGED 0x0b #define APM_BAD_FUNCTION 0x0c #define APM_RESUME_DISABLED 0x0d #define APM_NO_ERROR 0x53 #define APM_BAD_STATE 0x60 #define APM_NO_EVENTS 0x80 #define APM_NOT_PRESENT 0x86 /* * APM Device IDs */ #define APM_DEVICE_BIOS 0x0000 #define APM_DEVICE_ALL 0x0001 #define APM_DEVICE_DISPLAY 0x0100 #define APM_DEVICE_STORAGE 0x0200 #define APM_DEVICE_PARALLEL 0x0300 #define APM_DEVICE_SERIAL 0x0400 #define APM_DEVICE_NETWORK 0x0500 #define APM_DEVICE_PCMCIA 0x0600 #define APM_DEVICE_BATTERY 0x8000 #define APM_DEVICE_OEM 0xe000 #define APM_DEVICE_OLD_ALL 0xffff #define APM_DEVICE_CLASS 0x00ff #define APM_DEVICE_MASK 0xff00 /* * Battery status */ #define APM_MAX_BATTERIES 2 /* * APM defined capability bit flags */ #define APM_CAP_GLOBAL_STANDBY 0x0001 #define APM_CAP_GLOBAL_SUSPEND 0x0002 #define APM_CAP_RESUME_STANDBY_TIMER 0x0004 /* Timer resume from standby */ #define APM_CAP_RESUME_SUSPEND_TIMER 0x0008 /* Timer resume from suspend */ #define APM_CAP_RESUME_STANDBY_RING 0x0010 /* Resume on Ring fr standby */ #define APM_CAP_RESUME_SUSPEND_RING 0x0020 /* Resume on Ring fr suspend */ #define APM_CAP_RESUME_STANDBY_PCMCIA 0x0040 /* Resume on PCMCIA Ring */ #define APM_CAP_RESUME_SUSPEND_PCMCIA 0x0080 /* Resume on PCMCIA Ring */ /* * ioctl operations */ #include #define APM_IOC_STANDBY _IO('A', 1) #define APM_IOC_SUSPEND _IO('A', 2) #endif /* _LINUX_APM_H */ linux/pfkeyv2.h000064400000024511151027430560007450 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* PF_KEY user interface, this is defined by rfc2367 so * do not make arbitrary modifications or else this header * file will not be compliant. */ #ifndef _LINUX_PFKEY2_H #define _LINUX_PFKEY2_H #include #define PF_KEY_V2 2 #define PFKEYV2_REVISION 199806L struct sadb_msg { __u8 sadb_msg_version; __u8 sadb_msg_type; __u8 sadb_msg_errno; __u8 sadb_msg_satype; __u16 sadb_msg_len; __u16 sadb_msg_reserved; __u32 sadb_msg_seq; __u32 sadb_msg_pid; } __attribute__((packed)); /* sizeof(struct sadb_msg) == 16 */ struct sadb_ext { __u16 sadb_ext_len; __u16 sadb_ext_type; } __attribute__((packed)); /* sizeof(struct sadb_ext) == 4 */ struct sadb_sa { __u16 sadb_sa_len; __u16 sadb_sa_exttype; __be32 sadb_sa_spi; __u8 sadb_sa_replay; __u8 sadb_sa_state; __u8 sadb_sa_auth; __u8 sadb_sa_encrypt; __u32 sadb_sa_flags; } __attribute__((packed)); /* sizeof(struct sadb_sa) == 16 */ struct sadb_lifetime { __u16 sadb_lifetime_len; __u16 sadb_lifetime_exttype; __u32 sadb_lifetime_allocations; __u64 sadb_lifetime_bytes; __u64 sadb_lifetime_addtime; __u64 sadb_lifetime_usetime; } __attribute__((packed)); /* sizeof(struct sadb_lifetime) == 32 */ struct sadb_address { __u16 sadb_address_len; __u16 sadb_address_exttype; __u8 sadb_address_proto; __u8 sadb_address_prefixlen; __u16 sadb_address_reserved; } __attribute__((packed)); /* sizeof(struct sadb_address) == 8 */ struct sadb_key { __u16 sadb_key_len; __u16 sadb_key_exttype; __u16 sadb_key_bits; __u16 sadb_key_reserved; } __attribute__((packed)); /* sizeof(struct sadb_key) == 8 */ struct sadb_ident { __u16 sadb_ident_len; __u16 sadb_ident_exttype; __u16 sadb_ident_type; __u16 sadb_ident_reserved; __u64 sadb_ident_id; } __attribute__((packed)); /* sizeof(struct sadb_ident) == 16 */ struct sadb_sens { __u16 sadb_sens_len; __u16 sadb_sens_exttype; __u32 sadb_sens_dpd; __u8 sadb_sens_sens_level; __u8 sadb_sens_sens_len; __u8 sadb_sens_integ_level; __u8 sadb_sens_integ_len; __u32 sadb_sens_reserved; } __attribute__((packed)); /* sizeof(struct sadb_sens) == 16 */ /* followed by: __u64 sadb_sens_bitmap[sens_len]; __u64 sadb_integ_bitmap[integ_len]; */ struct sadb_prop { __u16 sadb_prop_len; __u16 sadb_prop_exttype; __u8 sadb_prop_replay; __u8 sadb_prop_reserved[3]; } __attribute__((packed)); /* sizeof(struct sadb_prop) == 8 */ /* followed by: struct sadb_comb sadb_combs[(sadb_prop_len + sizeof(__u64) - sizeof(struct sadb_prop)) / sizeof(struct sadb_comb)]; */ struct sadb_comb { __u8 sadb_comb_auth; __u8 sadb_comb_encrypt; __u16 sadb_comb_flags; __u16 sadb_comb_auth_minbits; __u16 sadb_comb_auth_maxbits; __u16 sadb_comb_encrypt_minbits; __u16 sadb_comb_encrypt_maxbits; __u32 sadb_comb_reserved; __u32 sadb_comb_soft_allocations; __u32 sadb_comb_hard_allocations; __u64 sadb_comb_soft_bytes; __u64 sadb_comb_hard_bytes; __u64 sadb_comb_soft_addtime; __u64 sadb_comb_hard_addtime; __u64 sadb_comb_soft_usetime; __u64 sadb_comb_hard_usetime; } __attribute__((packed)); /* sizeof(struct sadb_comb) == 72 */ struct sadb_supported { __u16 sadb_supported_len; __u16 sadb_supported_exttype; __u32 sadb_supported_reserved; } __attribute__((packed)); /* sizeof(struct sadb_supported) == 8 */ /* followed by: struct sadb_alg sadb_algs[(sadb_supported_len + sizeof(__u64) - sizeof(struct sadb_supported)) / sizeof(struct sadb_alg)]; */ struct sadb_alg { __u8 sadb_alg_id; __u8 sadb_alg_ivlen; __u16 sadb_alg_minbits; __u16 sadb_alg_maxbits; __u16 sadb_alg_reserved; } __attribute__((packed)); /* sizeof(struct sadb_alg) == 8 */ struct sadb_spirange { __u16 sadb_spirange_len; __u16 sadb_spirange_exttype; __u32 sadb_spirange_min; __u32 sadb_spirange_max; __u32 sadb_spirange_reserved; } __attribute__((packed)); /* sizeof(struct sadb_spirange) == 16 */ struct sadb_x_kmprivate { __u16 sadb_x_kmprivate_len; __u16 sadb_x_kmprivate_exttype; __u32 sadb_x_kmprivate_reserved; } __attribute__((packed)); /* sizeof(struct sadb_x_kmprivate) == 8 */ struct sadb_x_sa2 { __u16 sadb_x_sa2_len; __u16 sadb_x_sa2_exttype; __u8 sadb_x_sa2_mode; __u8 sadb_x_sa2_reserved1; __u16 sadb_x_sa2_reserved2; __u32 sadb_x_sa2_sequence; __u32 sadb_x_sa2_reqid; } __attribute__((packed)); /* sizeof(struct sadb_x_sa2) == 16 */ struct sadb_x_policy { __u16 sadb_x_policy_len; __u16 sadb_x_policy_exttype; __u16 sadb_x_policy_type; __u8 sadb_x_policy_dir; __u8 sadb_x_policy_reserved; __u32 sadb_x_policy_id; __u32 sadb_x_policy_priority; } __attribute__((packed)); /* sizeof(struct sadb_x_policy) == 16 */ struct sadb_x_ipsecrequest { __u16 sadb_x_ipsecrequest_len; __u16 sadb_x_ipsecrequest_proto; __u8 sadb_x_ipsecrequest_mode; __u8 sadb_x_ipsecrequest_level; __u16 sadb_x_ipsecrequest_reserved1; __u32 sadb_x_ipsecrequest_reqid; __u32 sadb_x_ipsecrequest_reserved2; } __attribute__((packed)); /* sizeof(struct sadb_x_ipsecrequest) == 16 */ /* This defines the TYPE of Nat Traversal in use. Currently only one * type of NAT-T is supported, draft-ietf-ipsec-udp-encaps-06 */ struct sadb_x_nat_t_type { __u16 sadb_x_nat_t_type_len; __u16 sadb_x_nat_t_type_exttype; __u8 sadb_x_nat_t_type_type; __u8 sadb_x_nat_t_type_reserved[3]; } __attribute__((packed)); /* sizeof(struct sadb_x_nat_t_type) == 8 */ /* Pass a NAT Traversal port (Source or Dest port) */ struct sadb_x_nat_t_port { __u16 sadb_x_nat_t_port_len; __u16 sadb_x_nat_t_port_exttype; __be16 sadb_x_nat_t_port_port; __u16 sadb_x_nat_t_port_reserved; } __attribute__((packed)); /* sizeof(struct sadb_x_nat_t_port) == 8 */ /* Generic LSM security context */ struct sadb_x_sec_ctx { __u16 sadb_x_sec_len; __u16 sadb_x_sec_exttype; __u8 sadb_x_ctx_alg; /* LSMs: e.g., selinux == 1 */ __u8 sadb_x_ctx_doi; __u16 sadb_x_ctx_len; } __attribute__((packed)); /* sizeof(struct sadb_sec_ctx) = 8 */ /* Used by MIGRATE to pass addresses IKE will use to perform * negotiation with the peer */ struct sadb_x_kmaddress { __u16 sadb_x_kmaddress_len; __u16 sadb_x_kmaddress_exttype; __u32 sadb_x_kmaddress_reserved; } __attribute__((packed)); /* sizeof(struct sadb_x_kmaddress) == 8 */ /* To specify the SA dump filter */ struct sadb_x_filter { __u16 sadb_x_filter_len; __u16 sadb_x_filter_exttype; __u32 sadb_x_filter_saddr[4]; __u32 sadb_x_filter_daddr[4]; __u16 sadb_x_filter_family; __u8 sadb_x_filter_splen; __u8 sadb_x_filter_dplen; } __attribute__((packed)); /* sizeof(struct sadb_x_filter) == 40 */ /* Message types */ #define SADB_RESERVED 0 #define SADB_GETSPI 1 #define SADB_UPDATE 2 #define SADB_ADD 3 #define SADB_DELETE 4 #define SADB_GET 5 #define SADB_ACQUIRE 6 #define SADB_REGISTER 7 #define SADB_EXPIRE 8 #define SADB_FLUSH 9 #define SADB_DUMP 10 #define SADB_X_PROMISC 11 #define SADB_X_PCHANGE 12 #define SADB_X_SPDUPDATE 13 #define SADB_X_SPDADD 14 #define SADB_X_SPDDELETE 15 #define SADB_X_SPDGET 16 #define SADB_X_SPDACQUIRE 17 #define SADB_X_SPDDUMP 18 #define SADB_X_SPDFLUSH 19 #define SADB_X_SPDSETIDX 20 #define SADB_X_SPDEXPIRE 21 #define SADB_X_SPDDELETE2 22 #define SADB_X_NAT_T_NEW_MAPPING 23 #define SADB_X_MIGRATE 24 #define SADB_MAX 24 /* Security Association flags */ #define SADB_SAFLAGS_PFS 1 #define SADB_SAFLAGS_NOPMTUDISC 0x20000000 #define SADB_SAFLAGS_DECAP_DSCP 0x40000000 #define SADB_SAFLAGS_NOECN 0x80000000 /* Security Association states */ #define SADB_SASTATE_LARVAL 0 #define SADB_SASTATE_MATURE 1 #define SADB_SASTATE_DYING 2 #define SADB_SASTATE_DEAD 3 #define SADB_SASTATE_MAX 3 /* Security Association types */ #define SADB_SATYPE_UNSPEC 0 #define SADB_SATYPE_AH 2 #define SADB_SATYPE_ESP 3 #define SADB_SATYPE_RSVP 5 #define SADB_SATYPE_OSPFV2 6 #define SADB_SATYPE_RIPV2 7 #define SADB_SATYPE_MIP 8 #define SADB_X_SATYPE_IPCOMP 9 #define SADB_SATYPE_MAX 9 /* Authentication algorithms */ #define SADB_AALG_NONE 0 #define SADB_AALG_MD5HMAC 2 #define SADB_AALG_SHA1HMAC 3 #define SADB_X_AALG_SHA2_256HMAC 5 #define SADB_X_AALG_SHA2_384HMAC 6 #define SADB_X_AALG_SHA2_512HMAC 7 #define SADB_X_AALG_RIPEMD160HMAC 8 #define SADB_X_AALG_AES_XCBC_MAC 9 #define SADB_X_AALG_NULL 251 /* kame */ #define SADB_AALG_MAX 251 /* Encryption algorithms */ #define SADB_EALG_NONE 0 #define SADB_EALG_DESCBC 2 #define SADB_EALG_3DESCBC 3 #define SADB_X_EALG_CASTCBC 6 #define SADB_X_EALG_BLOWFISHCBC 7 #define SADB_EALG_NULL 11 #define SADB_X_EALG_AESCBC 12 #define SADB_X_EALG_AESCTR 13 #define SADB_X_EALG_AES_CCM_ICV8 14 #define SADB_X_EALG_AES_CCM_ICV12 15 #define SADB_X_EALG_AES_CCM_ICV16 16 #define SADB_X_EALG_AES_GCM_ICV8 18 #define SADB_X_EALG_AES_GCM_ICV12 19 #define SADB_X_EALG_AES_GCM_ICV16 20 #define SADB_X_EALG_CAMELLIACBC 22 #define SADB_X_EALG_NULL_AES_GMAC 23 #define SADB_EALG_MAX 253 /* last EALG */ /* private allocations should use 249-255 (RFC2407) */ #define SADB_X_EALG_SERPENTCBC 252 /* draft-ietf-ipsec-ciph-aes-cbc-00 */ #define SADB_X_EALG_TWOFISHCBC 253 /* draft-ietf-ipsec-ciph-aes-cbc-00 */ /* Compression algorithms */ #define SADB_X_CALG_NONE 0 #define SADB_X_CALG_OUI 1 #define SADB_X_CALG_DEFLATE 2 #define SADB_X_CALG_LZS 3 #define SADB_X_CALG_LZJH 4 #define SADB_X_CALG_MAX 4 /* Extension Header values */ #define SADB_EXT_RESERVED 0 #define SADB_EXT_SA 1 #define SADB_EXT_LIFETIME_CURRENT 2 #define SADB_EXT_LIFETIME_HARD 3 #define SADB_EXT_LIFETIME_SOFT 4 #define SADB_EXT_ADDRESS_SRC 5 #define SADB_EXT_ADDRESS_DST 6 #define SADB_EXT_ADDRESS_PROXY 7 #define SADB_EXT_KEY_AUTH 8 #define SADB_EXT_KEY_ENCRYPT 9 #define SADB_EXT_IDENTITY_SRC 10 #define SADB_EXT_IDENTITY_DST 11 #define SADB_EXT_SENSITIVITY 12 #define SADB_EXT_PROPOSAL 13 #define SADB_EXT_SUPPORTED_AUTH 14 #define SADB_EXT_SUPPORTED_ENCRYPT 15 #define SADB_EXT_SPIRANGE 16 #define SADB_X_EXT_KMPRIVATE 17 #define SADB_X_EXT_POLICY 18 #define SADB_X_EXT_SA2 19 /* The next four entries are for setting up NAT Traversal */ #define SADB_X_EXT_NAT_T_TYPE 20 #define SADB_X_EXT_NAT_T_SPORT 21 #define SADB_X_EXT_NAT_T_DPORT 22 #define SADB_X_EXT_NAT_T_OA 23 #define SADB_X_EXT_SEC_CTX 24 /* Used with MIGRATE to pass @ to IKE for negotiation */ #define SADB_X_EXT_KMADDRESS 25 #define SADB_X_EXT_FILTER 26 #define SADB_EXT_MAX 26 /* Identity Extension values */ #define SADB_IDENTTYPE_RESERVED 0 #define SADB_IDENTTYPE_PREFIX 1 #define SADB_IDENTTYPE_FQDN 2 #define SADB_IDENTTYPE_USERFQDN 3 #define SADB_IDENTTYPE_MAX 3 #endif /* !(_LINUX_PFKEY2_H) */ linux/joystick.h000064400000006552151027430560007726 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (C) 1996-2000 Vojtech Pavlik * * Sponsored by SuSE */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _LINUX_JOYSTICK_H #define _LINUX_JOYSTICK_H #include #include /* * Version */ #define JS_VERSION 0x020100 /* * Types and constants for reading from /dev/js */ #define JS_EVENT_BUTTON 0x01 /* button pressed/released */ #define JS_EVENT_AXIS 0x02 /* joystick moved */ #define JS_EVENT_INIT 0x80 /* initial state of device */ struct js_event { __u32 time; /* event timestamp in milliseconds */ __s16 value; /* value */ __u8 type; /* event type */ __u8 number; /* axis/button number */ }; /* * IOCTL commands for joystick driver */ #define JSIOCGVERSION _IOR('j', 0x01, __u32) /* get driver version */ #define JSIOCGAXES _IOR('j', 0x11, __u8) /* get number of axes */ #define JSIOCGBUTTONS _IOR('j', 0x12, __u8) /* get number of buttons */ #define JSIOCGNAME(len) _IOC(_IOC_READ, 'j', 0x13, len) /* get identifier string */ #define JSIOCSCORR _IOW('j', 0x21, struct js_corr) /* set correction values */ #define JSIOCGCORR _IOR('j', 0x22, struct js_corr) /* get correction values */ #define JSIOCSAXMAP _IOW('j', 0x31, __u8[ABS_CNT]) /* set axis mapping */ #define JSIOCGAXMAP _IOR('j', 0x32, __u8[ABS_CNT]) /* get axis mapping */ #define JSIOCSBTNMAP _IOW('j', 0x33, __u16[KEY_MAX - BTN_MISC + 1]) /* set button mapping */ #define JSIOCGBTNMAP _IOR('j', 0x34, __u16[KEY_MAX - BTN_MISC + 1]) /* get button mapping */ /* * Types and constants for get/set correction */ #define JS_CORR_NONE 0x00 /* returns raw values */ #define JS_CORR_BROKEN 0x01 /* broken line */ struct js_corr { __s32 coef[8]; __s16 prec; __u16 type; }; /* * v0.x compatibility definitions */ #define JS_RETURN sizeof(struct JS_DATA_TYPE) #define JS_TRUE 1 #define JS_FALSE 0 #define JS_X_0 0x01 #define JS_Y_0 0x02 #define JS_X_1 0x04 #define JS_Y_1 0x08 #define JS_MAX 2 #define JS_DEF_TIMEOUT 0x1300 #define JS_DEF_CORR 0 #define JS_DEF_TIMELIMIT 10L #define JS_SET_CAL 1 #define JS_GET_CAL 2 #define JS_SET_TIMEOUT 3 #define JS_GET_TIMEOUT 4 #define JS_SET_TIMELIMIT 5 #define JS_GET_TIMELIMIT 6 #define JS_GET_ALL 7 #define JS_SET_ALL 8 struct JS_DATA_TYPE { __s32 buttons; __s32 x; __s32 y; }; struct JS_DATA_SAVE_TYPE_32 { __s32 JS_TIMEOUT; __s32 BUSY; __s32 JS_EXPIRETIME; __s32 JS_TIMELIMIT; struct JS_DATA_TYPE JS_SAVE; struct JS_DATA_TYPE JS_CORR; }; struct JS_DATA_SAVE_TYPE_64 { __s32 JS_TIMEOUT; __s32 BUSY; __s64 JS_EXPIRETIME; __s64 JS_TIMELIMIT; struct JS_DATA_TYPE JS_SAVE; struct JS_DATA_TYPE JS_CORR; }; #endif /* _LINUX_JOYSTICK_H */ linux/virtio_scsi.h000064400000013623151027430560010421 0ustar00/* * This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. * * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _LINUX_VIRTIO_SCSI_H #define _LINUX_VIRTIO_SCSI_H #include /* Default values of the CDB and sense data size configuration fields */ #define VIRTIO_SCSI_CDB_DEFAULT_SIZE 32 #define VIRTIO_SCSI_SENSE_DEFAULT_SIZE 96 #ifndef VIRTIO_SCSI_CDB_SIZE #define VIRTIO_SCSI_CDB_SIZE VIRTIO_SCSI_CDB_DEFAULT_SIZE #endif #ifndef VIRTIO_SCSI_SENSE_SIZE #define VIRTIO_SCSI_SENSE_SIZE VIRTIO_SCSI_SENSE_DEFAULT_SIZE #endif /* SCSI command request, followed by data-out */ struct virtio_scsi_cmd_req { __u8 lun[8]; /* Logical Unit Number */ __virtio64 tag; /* Command identifier */ __u8 task_attr; /* Task attribute */ __u8 prio; /* SAM command priority field */ __u8 crn; __u8 cdb[VIRTIO_SCSI_CDB_SIZE]; } __attribute__((packed)); /* SCSI command request, followed by protection information */ struct virtio_scsi_cmd_req_pi { __u8 lun[8]; /* Logical Unit Number */ __virtio64 tag; /* Command identifier */ __u8 task_attr; /* Task attribute */ __u8 prio; /* SAM command priority field */ __u8 crn; __virtio32 pi_bytesout; /* DataOUT PI Number of bytes */ __virtio32 pi_bytesin; /* DataIN PI Number of bytes */ __u8 cdb[VIRTIO_SCSI_CDB_SIZE]; } __attribute__((packed)); /* Response, followed by sense data and data-in */ struct virtio_scsi_cmd_resp { __virtio32 sense_len; /* Sense data length */ __virtio32 resid; /* Residual bytes in data buffer */ __virtio16 status_qualifier; /* Status qualifier */ __u8 status; /* Command completion status */ __u8 response; /* Response values */ __u8 sense[VIRTIO_SCSI_SENSE_SIZE]; } __attribute__((packed)); /* Task Management Request */ struct virtio_scsi_ctrl_tmf_req { __virtio32 type; __virtio32 subtype; __u8 lun[8]; __virtio64 tag; } __attribute__((packed)); struct virtio_scsi_ctrl_tmf_resp { __u8 response; } __attribute__((packed)); /* Asynchronous notification query/subscription */ struct virtio_scsi_ctrl_an_req { __virtio32 type; __u8 lun[8]; __virtio32 event_requested; } __attribute__((packed)); struct virtio_scsi_ctrl_an_resp { __virtio32 event_actual; __u8 response; } __attribute__((packed)); struct virtio_scsi_event { __virtio32 event; __u8 lun[8]; __virtio32 reason; } __attribute__((packed)); struct virtio_scsi_config { __u32 num_queues; __u32 seg_max; __u32 max_sectors; __u32 cmd_per_lun; __u32 event_info_size; __u32 sense_size; __u32 cdb_size; __u16 max_channel; __u16 max_target; __u32 max_lun; } __attribute__((packed)); /* Feature Bits */ #define VIRTIO_SCSI_F_INOUT 0 #define VIRTIO_SCSI_F_HOTPLUG 1 #define VIRTIO_SCSI_F_CHANGE 2 #define VIRTIO_SCSI_F_T10_PI 3 /* Response codes */ #define VIRTIO_SCSI_S_OK 0 #define VIRTIO_SCSI_S_OVERRUN 1 #define VIRTIO_SCSI_S_ABORTED 2 #define VIRTIO_SCSI_S_BAD_TARGET 3 #define VIRTIO_SCSI_S_RESET 4 #define VIRTIO_SCSI_S_BUSY 5 #define VIRTIO_SCSI_S_TRANSPORT_FAILURE 6 #define VIRTIO_SCSI_S_TARGET_FAILURE 7 #define VIRTIO_SCSI_S_NEXUS_FAILURE 8 #define VIRTIO_SCSI_S_FAILURE 9 #define VIRTIO_SCSI_S_FUNCTION_SUCCEEDED 10 #define VIRTIO_SCSI_S_FUNCTION_REJECTED 11 #define VIRTIO_SCSI_S_INCORRECT_LUN 12 /* Controlq type codes. */ #define VIRTIO_SCSI_T_TMF 0 #define VIRTIO_SCSI_T_AN_QUERY 1 #define VIRTIO_SCSI_T_AN_SUBSCRIBE 2 /* Valid TMF subtypes. */ #define VIRTIO_SCSI_T_TMF_ABORT_TASK 0 #define VIRTIO_SCSI_T_TMF_ABORT_TASK_SET 1 #define VIRTIO_SCSI_T_TMF_CLEAR_ACA 2 #define VIRTIO_SCSI_T_TMF_CLEAR_TASK_SET 3 #define VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET 4 #define VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET 5 #define VIRTIO_SCSI_T_TMF_QUERY_TASK 6 #define VIRTIO_SCSI_T_TMF_QUERY_TASK_SET 7 /* Events. */ #define VIRTIO_SCSI_T_EVENTS_MISSED 0x80000000 #define VIRTIO_SCSI_T_NO_EVENT 0 #define VIRTIO_SCSI_T_TRANSPORT_RESET 1 #define VIRTIO_SCSI_T_ASYNC_NOTIFY 2 #define VIRTIO_SCSI_T_PARAM_CHANGE 3 /* Reasons of transport reset event */ #define VIRTIO_SCSI_EVT_RESET_HARD 0 #define VIRTIO_SCSI_EVT_RESET_RESCAN 1 #define VIRTIO_SCSI_EVT_RESET_REMOVED 2 #define VIRTIO_SCSI_S_SIMPLE 0 #define VIRTIO_SCSI_S_ORDERED 1 #define VIRTIO_SCSI_S_HEAD 2 #define VIRTIO_SCSI_S_ACA 3 #endif /* _LINUX_VIRTIO_SCSI_H */ linux/ipmi_ssif_bmc.h000064400000000671151027430560010666 0ustar00/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note*/ /* * Copyright (c) 2022, Ampere Computing LLC. */ #ifndef _LINUX_IPMI_SSIF_BMC_H #define _LINUX_IPMI_SSIF_BMC_H #include /* Max length of ipmi ssif message included netfn and cmd field */ #define IPMI_SSIF_PAYLOAD_MAX 254 struct ipmi_ssif_msg { unsigned int len; __u8 payload[IPMI_SSIF_PAYLOAD_MAX]; }; #endif /* _LINUX_IPMI_SSIF_BMC_H */ linux/virtio_blk.h000064400000015215151027430560010227 0ustar00#ifndef _LINUX_VIRTIO_BLK_H #define _LINUX_VIRTIO_BLK_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include /* Feature bits */ #define VIRTIO_BLK_F_SIZE_MAX 1 /* Indicates maximum segment size */ #define VIRTIO_BLK_F_SEG_MAX 2 /* Indicates maximum # of segments */ #define VIRTIO_BLK_F_GEOMETRY 4 /* Legacy geometry available */ #define VIRTIO_BLK_F_RO 5 /* Disk is read-only */ #define VIRTIO_BLK_F_BLK_SIZE 6 /* Block size of disk is available*/ #define VIRTIO_BLK_F_TOPOLOGY 10 /* Topology information is available */ #define VIRTIO_BLK_F_MQ 12 /* support more than one vq */ #define VIRTIO_BLK_F_DISCARD 13 /* DISCARD is supported */ #define VIRTIO_BLK_F_WRITE_ZEROES 14 /* WRITE ZEROES is supported */ /* Legacy feature bits */ #ifndef VIRTIO_BLK_NO_LEGACY #define VIRTIO_BLK_F_BARRIER 0 /* Does host support barriers? */ #define VIRTIO_BLK_F_SCSI 7 /* Supports scsi command passthru */ #define VIRTIO_BLK_F_FLUSH 9 /* Flush command supported */ #define VIRTIO_BLK_F_CONFIG_WCE 11 /* Writeback mode available in config */ /* Old (deprecated) name for VIRTIO_BLK_F_FLUSH. */ #define VIRTIO_BLK_F_WCE VIRTIO_BLK_F_FLUSH #endif /* !VIRTIO_BLK_NO_LEGACY */ #define VIRTIO_BLK_ID_BYTES 20 /* ID string length */ struct virtio_blk_config { /* The capacity (in 512-byte sectors). */ __u64 capacity; /* The maximum segment size (if VIRTIO_BLK_F_SIZE_MAX) */ __u32 size_max; /* The maximum number of segments (if VIRTIO_BLK_F_SEG_MAX) */ __u32 seg_max; /* geometry of the device (if VIRTIO_BLK_F_GEOMETRY) */ struct virtio_blk_geometry { __u16 cylinders; __u8 heads; __u8 sectors; } geometry; /* block size of device (if VIRTIO_BLK_F_BLK_SIZE) */ __u32 blk_size; /* the next 4 entries are guarded by VIRTIO_BLK_F_TOPOLOGY */ /* exponent for physical block per logical block. */ __u8 physical_block_exp; /* alignment offset in logical blocks. */ __u8 alignment_offset; /* minimum I/O size without performance penalty in logical blocks. */ __u16 min_io_size; /* optimal sustained I/O size in logical blocks. */ __u32 opt_io_size; /* writeback mode (if VIRTIO_BLK_F_CONFIG_WCE) */ __u8 wce; __u8 unused; /* number of vqs, only available when VIRTIO_BLK_F_MQ is set */ __u16 num_queues; /* the next 3 entries are guarded by VIRTIO_BLK_F_DISCARD */ /* * The maximum discard sectors (in 512-byte sectors) for * one segment. */ __u32 max_discard_sectors; /* * The maximum number of discard segments in a * discard command. */ __u32 max_discard_seg; /* Discard commands must be aligned to this number of sectors. */ __u32 discard_sector_alignment; /* the next 3 entries are guarded by VIRTIO_BLK_F_WRITE_ZEROES */ /* * The maximum number of write zeroes sectors (in 512-byte sectors) in * one segment. */ __u32 max_write_zeroes_sectors; /* * The maximum number of segments in a write zeroes * command. */ __u32 max_write_zeroes_seg; /* * Set if a VIRTIO_BLK_T_WRITE_ZEROES request may result in the * deallocation of one or more of the sectors. */ __u8 write_zeroes_may_unmap; __u8 unused1[3]; } __attribute__((packed)); /* * Command types * * Usage is a bit tricky as some bits are used as flags and some are not. * * Rules: * VIRTIO_BLK_T_OUT may be combined with VIRTIO_BLK_T_SCSI_CMD or * VIRTIO_BLK_T_BARRIER. VIRTIO_BLK_T_FLUSH is a command of its own * and may not be combined with any of the other flags. */ /* These two define direction. */ #define VIRTIO_BLK_T_IN 0 #define VIRTIO_BLK_T_OUT 1 #ifndef VIRTIO_BLK_NO_LEGACY /* This bit says it's a scsi command, not an actual read or write. */ #define VIRTIO_BLK_T_SCSI_CMD 2 #endif /* VIRTIO_BLK_NO_LEGACY */ /* Cache flush command */ #define VIRTIO_BLK_T_FLUSH 4 /* Get device ID command */ #define VIRTIO_BLK_T_GET_ID 8 /* Discard command */ #define VIRTIO_BLK_T_DISCARD 11 /* Write zeroes command */ #define VIRTIO_BLK_T_WRITE_ZEROES 13 #ifndef VIRTIO_BLK_NO_LEGACY /* Barrier before this op. */ #define VIRTIO_BLK_T_BARRIER 0x80000000 #endif /* !VIRTIO_BLK_NO_LEGACY */ /* * This comes first in the read scatter-gather list. * For legacy virtio, if VIRTIO_F_ANY_LAYOUT is not negotiated, * this is the first element of the read scatter-gather list. */ struct virtio_blk_outhdr { /* VIRTIO_BLK_T* */ __virtio32 type; /* io priority. */ __virtio32 ioprio; /* Sector (ie. 512 byte offset) */ __virtio64 sector; }; /* Unmap this range (only valid for write zeroes command) */ #define VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP 0x00000001 /* Discard/write zeroes range for each request. */ struct virtio_blk_discard_write_zeroes { /* discard/write zeroes start sector */ __le64 sector; /* number of discard/write zeroes sectors */ __le32 num_sectors; /* flags for this range */ __le32 flags; }; #ifndef VIRTIO_BLK_NO_LEGACY struct virtio_scsi_inhdr { __virtio32 errors; __virtio32 data_len; __virtio32 sense_len; __virtio32 residual; }; #endif /* !VIRTIO_BLK_NO_LEGACY */ /* And this is the final byte of the write scatter-gather list. */ #define VIRTIO_BLK_S_OK 0 #define VIRTIO_BLK_S_IOERR 1 #define VIRTIO_BLK_S_UNSUPP 2 #endif /* _LINUX_VIRTIO_BLK_H */ linux/chio.h000064400000012340151027430560007001 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ioctl interface for the scsi media changer driver */ /* changer element types */ #define CHET_MT 0 /* media transport element (robot) */ #define CHET_ST 1 /* storage element (media slots) */ #define CHET_IE 2 /* import/export element */ #define CHET_DT 3 /* data transfer element (tape/cdrom/whatever) */ #define CHET_V1 4 /* vendor specific #1 */ #define CHET_V2 5 /* vendor specific #2 */ #define CHET_V3 6 /* vendor specific #3 */ #define CHET_V4 7 /* vendor specific #4 */ /* * CHIOGPARAMS * query changer properties * * CHIOVGPARAMS * query vendor-specific element types * * accessing elements works by specifing type and unit of the element. * for example, storage elements are addressed with type = CHET_ST and * unit = 0 .. cp_nslots-1 * */ struct changer_params { int cp_curpicker; /* current transport element */ int cp_npickers; /* number of transport elements (CHET_MT) */ int cp_nslots; /* number of storage elements (CHET_ST) */ int cp_nportals; /* number of import/export elements (CHET_IE) */ int cp_ndrives; /* number of data transfer elements (CHET_DT) */ }; struct changer_vendor_params { int cvp_n1; /* number of vendor specific elems (CHET_V1) */ char cvp_label1[16]; int cvp_n2; /* number of vendor specific elems (CHET_V2) */ char cvp_label2[16]; int cvp_n3; /* number of vendor specific elems (CHET_V3) */ char cvp_label3[16]; int cvp_n4; /* number of vendor specific elems (CHET_V4) */ char cvp_label4[16]; int reserved[8]; }; /* * CHIOMOVE * move a medium from one element to another */ struct changer_move { int cm_fromtype; /* type/unit of source element */ int cm_fromunit; int cm_totype; /* type/unit of destination element */ int cm_tounit; int cm_flags; }; #define CM_INVERT 1 /* flag: rotate media (for double-sided like MOD) */ /* * CHIOEXCHANGE * move one medium from element #1 to element #2, * and another one from element #2 to element #3. * element #1 and #3 are allowed to be identical. */ struct changer_exchange { int ce_srctype; /* type/unit of element #1 */ int ce_srcunit; int ce_fdsttype; /* type/unit of element #2 */ int ce_fdstunit; int ce_sdsttype; /* type/unit of element #3 */ int ce_sdstunit; int ce_flags; }; #define CE_INVERT1 1 #define CE_INVERT2 2 /* * CHIOPOSITION * move the transport element (robot arm) to a specific element. */ struct changer_position { int cp_type; int cp_unit; int cp_flags; }; #define CP_INVERT 1 /* * CHIOGSTATUS * get element status for all elements of a specific type */ struct changer_element_status { int ces_type; unsigned char *ces_data; }; #define CESTATUS_FULL 0x01 /* full */ #define CESTATUS_IMPEXP 0x02 /* media was imported (inserted by sysop) */ #define CESTATUS_EXCEPT 0x04 /* error condition */ #define CESTATUS_ACCESS 0x08 /* access allowed */ #define CESTATUS_EXENAB 0x10 /* element can export media */ #define CESTATUS_INENAB 0x20 /* element can import media */ /* * CHIOGELEM * get more detailed status information for a single element */ struct changer_get_element { int cge_type; /* type/unit */ int cge_unit; int cge_status; /* status */ int cge_errno; /* errno */ int cge_srctype; /* source element of the last move/exchange */ int cge_srcunit; int cge_id; /* scsi id (for data transfer elements) */ int cge_lun; /* scsi lun (for data transfer elements) */ char cge_pvoltag[36]; /* primary volume tag */ char cge_avoltag[36]; /* alternate volume tag */ int cge_flags; }; /* flags */ #define CGE_ERRNO 0x01 /* errno available */ #define CGE_INVERT 0x02 /* media inverted */ #define CGE_SRC 0x04 /* media src available */ #define CGE_IDLUN 0x08 /* ID+LUN available */ #define CGE_PVOLTAG 0x10 /* primary volume tag available */ #define CGE_AVOLTAG 0x20 /* alternate volume tag available */ /* * CHIOSVOLTAG * set volume tag */ struct changer_set_voltag { int csv_type; /* type/unit */ int csv_unit; char csv_voltag[36]; /* volume tag */ int csv_flags; }; #define CSV_PVOLTAG 0x01 /* primary volume tag */ #define CSV_AVOLTAG 0x02 /* alternate volume tag */ #define CSV_CLEARTAG 0x04 /* clear volume tag */ /* ioctls */ #define CHIOMOVE _IOW('c', 1,struct changer_move) #define CHIOEXCHANGE _IOW('c', 2,struct changer_exchange) #define CHIOPOSITION _IOW('c', 3,struct changer_position) #define CHIOGPICKER _IOR('c', 4,int) /* not impl. */ #define CHIOSPICKER _IOW('c', 5,int) /* not impl. */ #define CHIOGPARAMS _IOR('c', 6,struct changer_params) #define CHIOGSTATUS _IOW('c', 8,struct changer_element_status) #define CHIOGELEM _IOW('c',16,struct changer_get_element) #define CHIOINITELEM _IO('c',17) #define CHIOSVOLTAG _IOW('c',18,struct changer_set_voltag) #define CHIOGVPARAMS _IOR('c',19,struct changer_vendor_params) /* ---------------------------------------------------------------------- */ /* * Local variables: * c-basic-offset: 8 * End: */ linux/if_ether.h000064400000020070151027430560007643 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the Ethernet IEEE 802.3 interface. * * Version: @(#)if_ether.h 1.0.1a 02/08/94 * * Author: Fred N. van Kempen, * Donald Becker, * Alan Cox, * Steve Whitehouse, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_ETHER_H #define _LINUX_IF_ETHER_H #include /* * IEEE 802.3 Ethernet magic constants. The frame sizes omit the preamble * and FCS/CRC (frame check sequence). */ #define ETH_ALEN 6 /* Octets in one ethernet addr */ #define ETH_TLEN 2 /* Octets in ethernet type field */ #define ETH_HLEN 14 /* Total octets in header. */ #define ETH_ZLEN 60 /* Min. octets in frame sans FCS */ #define ETH_DATA_LEN 1500 /* Max. octets in payload */ #define ETH_FRAME_LEN 1514 /* Max. octets in frame sans FCS */ #define ETH_FCS_LEN 4 /* Octets in the FCS */ #define ETH_MIN_MTU 68 /* Min IPv4 MTU per RFC791 */ #define ETH_MAX_MTU 0xFFFFU /* 65535, same as IP_MAX_MTU */ /* * These are the defined Ethernet Protocol ID's. */ #define ETH_P_LOOP 0x0060 /* Ethernet Loopback packet */ #define ETH_P_PUP 0x0200 /* Xerox PUP packet */ #define ETH_P_PUPAT 0x0201 /* Xerox PUP Addr Trans packet */ #define ETH_P_TSN 0x22F0 /* TSN (IEEE 1722) packet */ #define ETH_P_ERSPAN2 0x22EB /* ERSPAN version 2 (type III) */ #define ETH_P_IP 0x0800 /* Internet Protocol packet */ #define ETH_P_X25 0x0805 /* CCITT X.25 */ #define ETH_P_ARP 0x0806 /* Address Resolution packet */ #define ETH_P_BPQ 0x08FF /* G8BPQ AX.25 Ethernet Packet [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_IEEEPUP 0x0a00 /* Xerox IEEE802.3 PUP packet */ #define ETH_P_IEEEPUPAT 0x0a01 /* Xerox IEEE802.3 PUP Addr Trans packet */ #define ETH_P_BATMAN 0x4305 /* B.A.T.M.A.N.-Advanced packet [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_DEC 0x6000 /* DEC Assigned proto */ #define ETH_P_DNA_DL 0x6001 /* DEC DNA Dump/Load */ #define ETH_P_DNA_RC 0x6002 /* DEC DNA Remote Console */ #define ETH_P_DNA_RT 0x6003 /* DEC DNA Routing */ #define ETH_P_LAT 0x6004 /* DEC LAT */ #define ETH_P_DIAG 0x6005 /* DEC Diagnostics */ #define ETH_P_CUST 0x6006 /* DEC Customer use */ #define ETH_P_SCA 0x6007 /* DEC Systems Comms Arch */ #define ETH_P_TEB 0x6558 /* Trans Ether Bridging */ #define ETH_P_RARP 0x8035 /* Reverse Addr Res packet */ #define ETH_P_ATALK 0x809B /* Appletalk DDP */ #define ETH_P_AARP 0x80F3 /* Appletalk AARP */ #define ETH_P_8021Q 0x8100 /* 802.1Q VLAN Extended Header */ #define ETH_P_ERSPAN 0x88BE /* ERSPAN type II */ #define ETH_P_IPX 0x8137 /* IPX over DIX */ #define ETH_P_IPV6 0x86DD /* IPv6 over bluebook */ #define ETH_P_PAUSE 0x8808 /* IEEE Pause frames. See 802.3 31B */ #define ETH_P_SLOW 0x8809 /* Slow Protocol. See 802.3ad 43B */ #define ETH_P_WCCP 0x883E /* Web-cache coordination protocol * defined in draft-wilson-wrec-wccp-v2-00.txt */ #define ETH_P_MPLS_UC 0x8847 /* MPLS Unicast traffic */ #define ETH_P_MPLS_MC 0x8848 /* MPLS Multicast traffic */ #define ETH_P_ATMMPOA 0x884c /* MultiProtocol Over ATM */ #define ETH_P_PPP_DISC 0x8863 /* PPPoE discovery messages */ #define ETH_P_PPP_SES 0x8864 /* PPPoE session messages */ #define ETH_P_LINK_CTL 0x886c /* HPNA, wlan link local tunnel */ #define ETH_P_ATMFATE 0x8884 /* Frame-based ATM Transport * over Ethernet */ #define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */ #define ETH_P_AOE 0x88A2 /* ATA over Ethernet */ #define ETH_P_8021AD 0x88A8 /* 802.1ad Service VLAN */ #define ETH_P_802_EX1 0x88B5 /* 802.1 Local Experimental 1. */ #define ETH_P_PREAUTH 0x88C7 /* 802.11 Preauthentication */ #define ETH_P_TIPC 0x88CA /* TIPC */ #define ETH_P_LLDP 0x88CC /* Link Layer Discovery Protocol */ #define ETH_P_MRP 0x88E3 /* Media Redundancy Protocol */ #define ETH_P_MACSEC 0x88E5 /* 802.1ae MACsec */ #define ETH_P_8021AH 0x88E7 /* 802.1ah Backbone Service Tag */ #define ETH_P_MVRP 0x88F5 /* 802.1Q MVRP */ #define ETH_P_1588 0x88F7 /* IEEE 1588 Timesync */ #define ETH_P_NCSI 0x88F8 /* NCSI protocol */ #define ETH_P_PRP 0x88FB /* IEC 62439-3 PRP/HSRv0 */ #define ETH_P_CFM 0x8902 /* Connectivity Fault Management */ #define ETH_P_FCOE 0x8906 /* Fibre Channel over Ethernet */ #define ETH_P_IBOE 0x8915 /* Infiniband over Ethernet */ #define ETH_P_TDLS 0x890D /* TDLS */ #define ETH_P_FIP 0x8914 /* FCoE Initialization Protocol */ #define ETH_P_80221 0x8917 /* IEEE 802.21 Media Independent Handover Protocol */ #define ETH_P_HSR 0x892F /* IEC 62439-3 HSRv1 */ #define ETH_P_NSH 0x894F /* Network Service Header */ #define ETH_P_LOOPBACK 0x9000 /* Ethernet loopback packet, per IEEE 802.3 */ #define ETH_P_QINQ1 0x9100 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_QINQ2 0x9200 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_QINQ3 0x9300 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_EDSA 0xDADA /* Ethertype DSA [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_IFE 0xED3E /* ForCES inter-FE LFB type */ #define ETH_P_AF_IUCV 0xFBFB /* IBM af_iucv [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_802_3_MIN 0x0600 /* If the value in the ethernet type is less than this value * then the frame is Ethernet II. Else it is 802.3 */ /* * Non DIX types. Won't clash for 1500 types. */ #define ETH_P_802_3 0x0001 /* Dummy type for 802.3 frames */ #define ETH_P_AX25 0x0002 /* Dummy protocol id for AX.25 */ #define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */ #define ETH_P_802_2 0x0004 /* 802.2 frames */ #define ETH_P_SNAP 0x0005 /* Internal only */ #define ETH_P_DDCMP 0x0006 /* DEC DDCMP: Internal only */ #define ETH_P_WAN_PPP 0x0007 /* Dummy type for WAN PPP frames*/ #define ETH_P_PPP_MP 0x0008 /* Dummy type for PPP MP frames */ #define ETH_P_LOCALTALK 0x0009 /* Localtalk pseudo type */ #define ETH_P_CAN 0x000C /* CAN: Controller Area Network */ #define ETH_P_CANFD 0x000D /* CANFD: CAN flexible data rate*/ #define ETH_P_PPPTALK 0x0010 /* Dummy type for Atalk over PPP*/ #define ETH_P_TR_802_2 0x0011 /* 802.2 frames */ #define ETH_P_MOBITEX 0x0015 /* Mobitex (kaz@cafe.net) */ #define ETH_P_CONTROL 0x0016 /* Card specific control frames */ #define ETH_P_IRDA 0x0017 /* Linux-IrDA */ #define ETH_P_ECONET 0x0018 /* Acorn Econet */ #define ETH_P_HDLC 0x0019 /* HDLC frames */ #define ETH_P_ARCNET 0x001A /* 1A for ArcNet :-) */ #define ETH_P_DSA 0x001B /* Distributed Switch Arch. */ #define ETH_P_TRAILER 0x001C /* Trailer switch tagging */ #define ETH_P_PHONET 0x00F5 /* Nokia Phonet frames */ #define ETH_P_IEEE802154 0x00F6 /* IEEE802.15.4 frame */ #define ETH_P_CAIF 0x00F7 /* ST-Ericsson CAIF protocol */ #define ETH_P_XDSA 0x00F8 /* Multiplexed DSA protocol */ #define ETH_P_MAP 0x00F9 /* Qualcomm multiplexing and * aggregation protocol */ /* * This is an Ethernet frame header. */ /* allow libcs like musl to deactivate this, glibc does not implement this. */ #ifndef __UAPI_DEF_ETHHDR #define __UAPI_DEF_ETHHDR 1 #endif #if __UAPI_DEF_ETHHDR struct ethhdr { unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ unsigned char h_source[ETH_ALEN]; /* source ether addr */ __be16 h_proto; /* packet type ID field */ } __attribute__((packed)); #endif #endif /* _LINUX_IF_ETHER_H */ linux/bpf.h000064400000676464151027430560006655 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. */ #ifndef __LINUX_BPF_H__ #define __LINUX_BPF_H__ #include #include /* Extended instruction set based on top of classic BPF */ /* instruction classes */ #define BPF_JMP32 0x06 /* jmp mode in word width */ #define BPF_ALU64 0x07 /* alu mode in double word width */ /* ld/ldx fields */ #define BPF_DW 0x18 /* double word (64-bit) */ #define BPF_ATOMIC 0xc0 /* atomic memory ops - op type in immediate */ #define BPF_XADD 0xc0 /* exclusive add - legacy name */ /* alu/jmp fields */ #define BPF_MOV 0xb0 /* mov reg to reg */ #define BPF_ARSH 0xc0 /* sign extending arithmetic shift right */ /* change endianness of a register */ #define BPF_END 0xd0 /* flags for endianness conversion: */ #define BPF_TO_LE 0x00 /* convert to little-endian */ #define BPF_TO_BE 0x08 /* convert to big-endian */ #define BPF_FROM_LE BPF_TO_LE #define BPF_FROM_BE BPF_TO_BE /* jmp encodings */ #define BPF_JNE 0x50 /* jump != */ #define BPF_JLT 0xa0 /* LT is unsigned, '<' */ #define BPF_JLE 0xb0 /* LE is unsigned, '<=' */ #define BPF_JSGT 0x60 /* SGT is signed '>', GT in x86 */ #define BPF_JSGE 0x70 /* SGE is signed '>=', GE in x86 */ #define BPF_JSLT 0xc0 /* SLT is signed, '<' */ #define BPF_JSLE 0xd0 /* SLE is signed, '<=' */ #define BPF_CALL 0x80 /* function call */ #define BPF_EXIT 0x90 /* function return */ /* atomic op type fields (stored in immediate) */ #define BPF_FETCH 0x01 /* not an opcode on its own, used to build others */ #define BPF_XCHG (0xe0 | BPF_FETCH) /* atomic exchange */ #define BPF_CMPXCHG (0xf0 | BPF_FETCH) /* atomic compare-and-write */ /* Register numbers */ enum { BPF_REG_0 = 0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5, BPF_REG_6, BPF_REG_7, BPF_REG_8, BPF_REG_9, BPF_REG_10, __MAX_BPF_REG, }; /* BPF has 10 general purpose 64-bit registers and stack frame. */ #define MAX_BPF_REG __MAX_BPF_REG struct bpf_insn { __u8 code; /* opcode */ __u8 dst_reg:4; /* dest register */ __u8 src_reg:4; /* source register */ __s16 off; /* signed offset */ __s32 imm; /* signed immediate constant */ }; /* Key of an a BPF_MAP_TYPE_LPM_TRIE entry */ struct bpf_lpm_trie_key { __u32 prefixlen; /* up to 32 for AF_INET, 128 for AF_INET6 */ __u8 data[0]; /* Arbitrary size */ }; struct bpf_cgroup_storage_key { __u64 cgroup_inode_id; /* cgroup inode id */ __u32 attach_type; /* program attach type */ }; union bpf_iter_link_info { struct { __u32 map_fd; } map; }; /* BPF syscall commands, see bpf(2) man-page for more details. */ /** * DOC: eBPF Syscall Preamble * * The operation to be performed by the **bpf**\ () system call is determined * by the *cmd* argument. Each operation takes an accompanying argument, * provided via *attr*, which is a pointer to a union of type *bpf_attr* (see * below). The size argument is the size of the union pointed to by *attr*. */ /** * DOC: eBPF Syscall Commands * * BPF_MAP_CREATE * Description * Create a map and return a file descriptor that refers to the * map. The close-on-exec file descriptor flag (see **fcntl**\ (2)) * is automatically enabled for the new file descriptor. * * Applying **close**\ (2) to the file descriptor returned by * **BPF_MAP_CREATE** will delete the map (but see NOTES). * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_MAP_LOOKUP_ELEM * Description * Look up an element with a given *key* in the map referred to * by the file descriptor *map_fd*. * * The *flags* argument may be specified as one of the * following: * * **BPF_F_LOCK** * Look up the value of a spin-locked map without * returning the lock. This must be specified if the * elements contain a spinlock. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_MAP_UPDATE_ELEM * Description * Create or update an element (key/value pair) in a specified map. * * The *flags* argument should be specified as one of the * following: * * **BPF_ANY** * Create a new element or update an existing element. * **BPF_NOEXIST** * Create a new element only if it did not exist. * **BPF_EXIST** * Update an existing element. * **BPF_F_LOCK** * Update a spin_lock-ed map element. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * May set *errno* to **EINVAL**, **EPERM**, **ENOMEM**, * **E2BIG**, **EEXIST**, or **ENOENT**. * * **E2BIG** * The number of elements in the map reached the * *max_entries* limit specified at map creation time. * **EEXIST** * If *flags* specifies **BPF_NOEXIST** and the element * with *key* already exists in the map. * **ENOENT** * If *flags* specifies **BPF_EXIST** and the element with * *key* does not exist in the map. * * BPF_MAP_DELETE_ELEM * Description * Look up and delete an element by key in a specified map. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_MAP_GET_NEXT_KEY * Description * Look up an element by key in a specified map and return the key * of the next element. Can be used to iterate over all elements * in the map. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * The following cases can be used to iterate over all elements of * the map: * * * If *key* is not found, the operation returns zero and sets * the *next_key* pointer to the key of the first element. * * If *key* is found, the operation returns zero and sets the * *next_key* pointer to the key of the next element. * * If *key* is the last element, returns -1 and *errno* is set * to **ENOENT**. * * May set *errno* to **ENOMEM**, **EFAULT**, **EPERM**, or * **EINVAL** on error. * * BPF_PROG_LOAD * Description * Verify and load an eBPF program, returning a new file * descriptor associated with the program. * * Applying **close**\ (2) to the file descriptor returned by * **BPF_PROG_LOAD** will unload the eBPF program (but see NOTES). * * The close-on-exec file descriptor flag (see **fcntl**\ (2)) is * automatically enabled for the new file descriptor. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_OBJ_PIN * Description * Pin an eBPF program or map referred by the specified *bpf_fd* * to the provided *pathname* on the filesystem. * * The *pathname* argument must not contain a dot ("."). * * On success, *pathname* retains a reference to the eBPF object, * preventing deallocation of the object when the original * *bpf_fd* is closed. This allow the eBPF object to live beyond * **close**\ (\ *bpf_fd*\ ), and hence the lifetime of the parent * process. * * Applying **unlink**\ (2) or similar calls to the *pathname* * unpins the object from the filesystem, removing the reference. * If no other file descriptors or filesystem nodes refer to the * same object, it will be deallocated (see NOTES). * * The filesystem type for the parent directory of *pathname* must * be **BPF_FS_MAGIC**. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_OBJ_GET * Description * Open a file descriptor for the eBPF object pinned to the * specified *pathname*. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_PROG_ATTACH * Description * Attach an eBPF program to a *target_fd* at the specified * *attach_type* hook. * * The *attach_type* specifies the eBPF attachment point to * attach the program to, and must be one of *bpf_attach_type* * (see below). * * The *attach_bpf_fd* must be a valid file descriptor for a * loaded eBPF program of a cgroup, flow dissector, LIRC, sockmap * or sock_ops type corresponding to the specified *attach_type*. * * The *target_fd* must be a valid file descriptor for a kernel * object which depends on the attach type of *attach_bpf_fd*: * * **BPF_PROG_TYPE_CGROUP_DEVICE**, * **BPF_PROG_TYPE_CGROUP_SKB**, * **BPF_PROG_TYPE_CGROUP_SOCK**, * **BPF_PROG_TYPE_CGROUP_SOCK_ADDR**, * **BPF_PROG_TYPE_CGROUP_SOCKOPT**, * **BPF_PROG_TYPE_CGROUP_SYSCTL**, * **BPF_PROG_TYPE_SOCK_OPS** * * Control Group v2 hierarchy with the eBPF controller * enabled. Requires the kernel to be compiled with * **CONFIG_CGROUP_BPF**. * * **BPF_PROG_TYPE_FLOW_DISSECTOR** * * Network namespace (eg /proc/self/ns/net). * * **BPF_PROG_TYPE_LIRC_MODE2** * * LIRC device path (eg /dev/lircN). Requires the kernel * to be compiled with **CONFIG_BPF_LIRC_MODE2**. * * **BPF_PROG_TYPE_SK_SKB**, * **BPF_PROG_TYPE_SK_MSG** * * eBPF map of socket type (eg **BPF_MAP_TYPE_SOCKHASH**). * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_PROG_DETACH * Description * Detach the eBPF program associated with the *target_fd* at the * hook specified by *attach_type*. The program must have been * previously attached using **BPF_PROG_ATTACH**. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_PROG_TEST_RUN * Description * Run the eBPF program associated with the *prog_fd* a *repeat* * number of times against a provided program context *ctx_in* and * data *data_in*, and return the modified program context * *ctx_out*, *data_out* (for example, packet data), result of the * execution *retval*, and *duration* of the test run. * * The sizes of the buffers provided as input and output * parameters *ctx_in*, *ctx_out*, *data_in*, and *data_out* must * be provided in the corresponding variables *ctx_size_in*, * *ctx_size_out*, *data_size_in*, and/or *data_size_out*. If any * of these parameters are not provided (ie set to NULL), the * corresponding size field must be zero. * * Some program types have particular requirements: * * **BPF_PROG_TYPE_SK_LOOKUP** * *data_in* and *data_out* must be NULL. * * **BPF_PROG_TYPE_XDP** * *ctx_in* and *ctx_out* must be NULL. * * **BPF_PROG_TYPE_RAW_TRACEPOINT**, * **BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE** * * *ctx_out*, *data_in* and *data_out* must be NULL. * *repeat* must be zero. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * **ENOSPC** * Either *data_size_out* or *ctx_size_out* is too small. * **ENOTSUPP** * This command is not supported by the program type of * the program referred to by *prog_fd*. * * BPF_PROG_GET_NEXT_ID * Description * Fetch the next eBPF program currently loaded into the kernel. * * Looks for the eBPF program with an id greater than *start_id* * and updates *next_id* on success. If no other eBPF programs * remain with ids higher than *start_id*, returns -1 and sets * *errno* to **ENOENT**. * * Return * Returns zero on success. On error, or when no id remains, -1 * is returned and *errno* is set appropriately. * * BPF_MAP_GET_NEXT_ID * Description * Fetch the next eBPF map currently loaded into the kernel. * * Looks for the eBPF map with an id greater than *start_id* * and updates *next_id* on success. If no other eBPF maps * remain with ids higher than *start_id*, returns -1 and sets * *errno* to **ENOENT**. * * Return * Returns zero on success. On error, or when no id remains, -1 * is returned and *errno* is set appropriately. * * BPF_PROG_GET_FD_BY_ID * Description * Open a file descriptor for the eBPF program corresponding to * *prog_id*. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_MAP_GET_FD_BY_ID * Description * Open a file descriptor for the eBPF map corresponding to * *map_id*. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_OBJ_GET_INFO_BY_FD * Description * Obtain information about the eBPF object corresponding to * *bpf_fd*. * * Populates up to *info_len* bytes of *info*, which will be in * one of the following formats depending on the eBPF object type * of *bpf_fd*: * * * **struct bpf_prog_info** * * **struct bpf_map_info** * * **struct bpf_btf_info** * * **struct bpf_link_info** * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_PROG_QUERY * Description * Obtain information about eBPF programs associated with the * specified *attach_type* hook. * * The *target_fd* must be a valid file descriptor for a kernel * object which depends on the attach type of *attach_bpf_fd*: * * **BPF_PROG_TYPE_CGROUP_DEVICE**, * **BPF_PROG_TYPE_CGROUP_SKB**, * **BPF_PROG_TYPE_CGROUP_SOCK**, * **BPF_PROG_TYPE_CGROUP_SOCK_ADDR**, * **BPF_PROG_TYPE_CGROUP_SOCKOPT**, * **BPF_PROG_TYPE_CGROUP_SYSCTL**, * **BPF_PROG_TYPE_SOCK_OPS** * * Control Group v2 hierarchy with the eBPF controller * enabled. Requires the kernel to be compiled with * **CONFIG_CGROUP_BPF**. * * **BPF_PROG_TYPE_FLOW_DISSECTOR** * * Network namespace (eg /proc/self/ns/net). * * **BPF_PROG_TYPE_LIRC_MODE2** * * LIRC device path (eg /dev/lircN). Requires the kernel * to be compiled with **CONFIG_BPF_LIRC_MODE2**. * * **BPF_PROG_QUERY** always fetches the number of programs * attached and the *attach_flags* which were used to attach those * programs. Additionally, if *prog_ids* is nonzero and the number * of attached programs is less than *prog_cnt*, populates * *prog_ids* with the eBPF program ids of the programs attached * at *target_fd*. * * The following flags may alter the result: * * **BPF_F_QUERY_EFFECTIVE** * Only return information regarding programs which are * currently effective at the specified *target_fd*. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_RAW_TRACEPOINT_OPEN * Description * Attach an eBPF program to a tracepoint *name* to access kernel * internal arguments of the tracepoint in their raw form. * * The *prog_fd* must be a valid file descriptor associated with * a loaded eBPF program of type **BPF_PROG_TYPE_RAW_TRACEPOINT**. * * No ABI guarantees are made about the content of tracepoint * arguments exposed to the corresponding eBPF program. * * Applying **close**\ (2) to the file descriptor returned by * **BPF_RAW_TRACEPOINT_OPEN** will delete the map (but see NOTES). * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_BTF_LOAD * Description * Verify and load BPF Type Format (BTF) metadata into the kernel, * returning a new file descriptor associated with the metadata. * BTF is described in more detail at * https://www.kernel.org/doc/html/latest/bpf/btf.html. * * The *btf* parameter must point to valid memory providing * *btf_size* bytes of BTF binary metadata. * * The returned file descriptor can be passed to other **bpf**\ () * subcommands such as **BPF_PROG_LOAD** or **BPF_MAP_CREATE** to * associate the BTF with those objects. * * Similar to **BPF_PROG_LOAD**, **BPF_BTF_LOAD** has optional * parameters to specify a *btf_log_buf*, *btf_log_size* and * *btf_log_level* which allow the kernel to return freeform log * output regarding the BTF verification process. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_BTF_GET_FD_BY_ID * Description * Open a file descriptor for the BPF Type Format (BTF) * corresponding to *btf_id*. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_TASK_FD_QUERY * Description * Obtain information about eBPF programs associated with the * target process identified by *pid* and *fd*. * * If the *pid* and *fd* are associated with a tracepoint, kprobe * or uprobe perf event, then the *prog_id* and *fd_type* will * be populated with the eBPF program id and file descriptor type * of type **bpf_task_fd_type**. If associated with a kprobe or * uprobe, the *probe_offset* and *probe_addr* will also be * populated. Optionally, if *buf* is provided, then up to * *buf_len* bytes of *buf* will be populated with the name of * the tracepoint, kprobe or uprobe. * * The resulting *prog_id* may be introspected in deeper detail * using **BPF_PROG_GET_FD_BY_ID** and **BPF_OBJ_GET_INFO_BY_FD**. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_MAP_LOOKUP_AND_DELETE_ELEM * Description * Look up an element with the given *key* in the map referred to * by the file descriptor *fd*, and if found, delete the element. * * For **BPF_MAP_TYPE_QUEUE** and **BPF_MAP_TYPE_STACK** map * types, the *flags* argument needs to be set to 0, but for other * map types, it may be specified as: * * **BPF_F_LOCK** * Look up and delete the value of a spin-locked map * without returning the lock. This must be specified if * the elements contain a spinlock. * * The **BPF_MAP_TYPE_QUEUE** and **BPF_MAP_TYPE_STACK** map types * implement this command as a "pop" operation, deleting the top * element rather than one corresponding to *key*. * The *key* and *key_len* parameters should be zeroed when * issuing this operation for these map types. * * This command is only valid for the following map types: * * **BPF_MAP_TYPE_QUEUE** * * **BPF_MAP_TYPE_STACK** * * **BPF_MAP_TYPE_HASH** * * **BPF_MAP_TYPE_PERCPU_HASH** * * **BPF_MAP_TYPE_LRU_HASH** * * **BPF_MAP_TYPE_LRU_PERCPU_HASH** * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_MAP_FREEZE * Description * Freeze the permissions of the specified map. * * Write permissions may be frozen by passing zero *flags*. * Upon success, no future syscall invocations may alter the * map state of *map_fd*. Write operations from eBPF programs * are still possible for a frozen map. * * Not supported for maps of type **BPF_MAP_TYPE_STRUCT_OPS**. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_BTF_GET_NEXT_ID * Description * Fetch the next BPF Type Format (BTF) object currently loaded * into the kernel. * * Looks for the BTF object with an id greater than *start_id* * and updates *next_id* on success. If no other BTF objects * remain with ids higher than *start_id*, returns -1 and sets * *errno* to **ENOENT**. * * Return * Returns zero on success. On error, or when no id remains, -1 * is returned and *errno* is set appropriately. * * BPF_MAP_LOOKUP_BATCH * Description * Iterate and fetch multiple elements in a map. * * Two opaque values are used to manage batch operations, * *in_batch* and *out_batch*. Initially, *in_batch* must be set * to NULL to begin the batched operation. After each subsequent * **BPF_MAP_LOOKUP_BATCH**, the caller should pass the resultant * *out_batch* as the *in_batch* for the next operation to * continue iteration from the current point. * * The *keys* and *values* are output parameters which must point * to memory large enough to hold *count* items based on the key * and value size of the map *map_fd*. The *keys* buffer must be * of *key_size* * *count*. The *values* buffer must be of * *value_size* * *count*. * * The *elem_flags* argument may be specified as one of the * following: * * **BPF_F_LOCK** * Look up the value of a spin-locked map without * returning the lock. This must be specified if the * elements contain a spinlock. * * On success, *count* elements from the map are copied into the * user buffer, with the keys copied into *keys* and the values * copied into the corresponding indices in *values*. * * If an error is returned and *errno* is not **EFAULT**, *count* * is set to the number of successfully processed elements. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * May set *errno* to **ENOSPC** to indicate that *keys* or * *values* is too small to dump an entire bucket during * iteration of a hash-based map type. * * BPF_MAP_LOOKUP_AND_DELETE_BATCH * Description * Iterate and delete all elements in a map. * * This operation has the same behavior as * **BPF_MAP_LOOKUP_BATCH** with two exceptions: * * * Every element that is successfully returned is also deleted * from the map. This is at least *count* elements. Note that * *count* is both an input and an output parameter. * * Upon returning with *errno* set to **EFAULT**, up to * *count* elements may be deleted without returning the keys * and values of the deleted elements. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_MAP_UPDATE_BATCH * Description * Update multiple elements in a map by *key*. * * The *keys* and *values* are input parameters which must point * to memory large enough to hold *count* items based on the key * and value size of the map *map_fd*. The *keys* buffer must be * of *key_size* * *count*. The *values* buffer must be of * *value_size* * *count*. * * Each element specified in *keys* is sequentially updated to the * value in the corresponding index in *values*. The *in_batch* * and *out_batch* parameters are ignored and should be zeroed. * * The *elem_flags* argument should be specified as one of the * following: * * **BPF_ANY** * Create new elements or update a existing elements. * **BPF_NOEXIST** * Create new elements only if they do not exist. * **BPF_EXIST** * Update existing elements. * **BPF_F_LOCK** * Update spin_lock-ed map elements. This must be * specified if the map value contains a spinlock. * * On success, *count* elements from the map are updated. * * If an error is returned and *errno* is not **EFAULT**, *count* * is set to the number of successfully processed elements. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * May set *errno* to **EINVAL**, **EPERM**, **ENOMEM**, or * **E2BIG**. **E2BIG** indicates that the number of elements in * the map reached the *max_entries* limit specified at map * creation time. * * May set *errno* to one of the following error codes under * specific circumstances: * * **EEXIST** * If *flags* specifies **BPF_NOEXIST** and the element * with *key* already exists in the map. * **ENOENT** * If *flags* specifies **BPF_EXIST** and the element with * *key* does not exist in the map. * * BPF_MAP_DELETE_BATCH * Description * Delete multiple elements in a map by *key*. * * The *keys* parameter is an input parameter which must point * to memory large enough to hold *count* items based on the key * size of the map *map_fd*, that is, *key_size* * *count*. * * Each element specified in *keys* is sequentially deleted. The * *in_batch*, *out_batch*, and *values* parameters are ignored * and should be zeroed. * * The *elem_flags* argument may be specified as one of the * following: * * **BPF_F_LOCK** * Look up the value of a spin-locked map without * returning the lock. This must be specified if the * elements contain a spinlock. * * On success, *count* elements from the map are updated. * * If an error is returned and *errno* is not **EFAULT**, *count* * is set to the number of successfully processed elements. If * *errno* is **EFAULT**, up to *count* elements may be been * deleted. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_LINK_CREATE * Description * Attach an eBPF program to a *target_fd* at the specified * *attach_type* hook and return a file descriptor handle for * managing the link. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_LINK_UPDATE * Description * Update the eBPF program in the specified *link_fd* to * *new_prog_fd*. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_LINK_GET_FD_BY_ID * Description * Open a file descriptor for the eBPF Link corresponding to * *link_id*. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_LINK_GET_NEXT_ID * Description * Fetch the next eBPF link currently loaded into the kernel. * * Looks for the eBPF link with an id greater than *start_id* * and updates *next_id* on success. If no other eBPF links * remain with ids higher than *start_id*, returns -1 and sets * *errno* to **ENOENT**. * * Return * Returns zero on success. On error, or when no id remains, -1 * is returned and *errno* is set appropriately. * * BPF_ENABLE_STATS * Description * Enable eBPF runtime statistics gathering. * * Runtime statistics gathering for the eBPF runtime is disabled * by default to minimize the corresponding performance overhead. * This command enables statistics globally. * * Multiple programs may independently enable statistics. * After gathering the desired statistics, eBPF runtime statistics * may be disabled again by calling **close**\ (2) for the file * descriptor returned by this function. Statistics will only be * disabled system-wide when all outstanding file descriptors * returned by prior calls for this subcommand are closed. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_ITER_CREATE * Description * Create an iterator on top of the specified *link_fd* (as * previously created using **BPF_LINK_CREATE**) and return a * file descriptor that can be used to trigger the iteration. * * If the resulting file descriptor is pinned to the filesystem * using **BPF_OBJ_PIN**, then subsequent **read**\ (2) syscalls * for that path will trigger the iterator to read kernel state * using the eBPF program attached to *link_fd*. * * Return * A new file descriptor (a nonnegative integer), or -1 if an * error occurred (in which case, *errno* is set appropriately). * * BPF_LINK_DETACH * Description * Forcefully detach the specified *link_fd* from its * corresponding attachment point. * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * BPF_PROG_BIND_MAP * Description * Bind a map to the lifetime of an eBPF program. * * The map identified by *map_fd* is bound to the program * identified by *prog_fd* and only released when *prog_fd* is * released. This may be used in cases where metadata should be * associated with a program which otherwise does not contain any * references to the map (for example, embedded in the eBPF * program instructions). * * Return * Returns zero on success. On error, -1 is returned and *errno* * is set appropriately. * * NOTES * eBPF objects (maps and programs) can be shared between processes. * * * After **fork**\ (2), the child inherits file descriptors * referring to the same eBPF objects. * * File descriptors referring to eBPF objects can be transferred over * **unix**\ (7) domain sockets. * * File descriptors referring to eBPF objects can be duplicated in the * usual way, using **dup**\ (2) and similar calls. * * File descriptors referring to eBPF objects can be pinned to the * filesystem using the **BPF_OBJ_PIN** command of **bpf**\ (2). * * An eBPF object is deallocated only after all file descriptors referring * to the object have been closed and no references remain pinned to the * filesystem or attached (for example, bound to a program or device). */ enum bpf_cmd { BPF_MAP_CREATE, BPF_MAP_LOOKUP_ELEM, BPF_MAP_UPDATE_ELEM, BPF_MAP_DELETE_ELEM, BPF_MAP_GET_NEXT_KEY, BPF_PROG_LOAD, BPF_OBJ_PIN, BPF_OBJ_GET, BPF_PROG_ATTACH, BPF_PROG_DETACH, BPF_PROG_TEST_RUN, BPF_PROG_RUN = BPF_PROG_TEST_RUN, BPF_PROG_GET_NEXT_ID, BPF_MAP_GET_NEXT_ID, BPF_PROG_GET_FD_BY_ID, BPF_MAP_GET_FD_BY_ID, BPF_OBJ_GET_INFO_BY_FD, BPF_PROG_QUERY, BPF_RAW_TRACEPOINT_OPEN, BPF_BTF_LOAD, BPF_BTF_GET_FD_BY_ID, BPF_TASK_FD_QUERY, BPF_MAP_LOOKUP_AND_DELETE_ELEM, BPF_MAP_FREEZE, BPF_BTF_GET_NEXT_ID, BPF_MAP_LOOKUP_BATCH, BPF_MAP_LOOKUP_AND_DELETE_BATCH, BPF_MAP_UPDATE_BATCH, BPF_MAP_DELETE_BATCH, BPF_LINK_CREATE, BPF_LINK_UPDATE, BPF_LINK_GET_FD_BY_ID, BPF_LINK_GET_NEXT_ID, BPF_ENABLE_STATS, BPF_ITER_CREATE, BPF_LINK_DETACH, BPF_PROG_BIND_MAP, }; enum bpf_map_type { BPF_MAP_TYPE_UNSPEC, BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_PROG_ARRAY, BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_PERCPU_HASH, BPF_MAP_TYPE_PERCPU_ARRAY, BPF_MAP_TYPE_STACK_TRACE, BPF_MAP_TYPE_CGROUP_ARRAY, BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, BPF_MAP_TYPE_LPM_TRIE, BPF_MAP_TYPE_ARRAY_OF_MAPS, BPF_MAP_TYPE_HASH_OF_MAPS, BPF_MAP_TYPE_DEVMAP, BPF_MAP_TYPE_SOCKMAP, BPF_MAP_TYPE_CPUMAP, BPF_MAP_TYPE_XSKMAP, BPF_MAP_TYPE_SOCKHASH, #ifndef __GENKSYMS__ BPF_MAP_TYPE_CGROUP_STORAGE, BPF_MAP_TYPE_REUSEPORT_SOCKARRAY, BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE, BPF_MAP_TYPE_QUEUE, BPF_MAP_TYPE_STACK, BPF_MAP_TYPE_SK_STORAGE, BPF_MAP_TYPE_DEVMAP_HASH, BPF_MAP_TYPE_STRUCT_OPS, BPF_MAP_TYPE_RINGBUF, BPF_MAP_TYPE_INODE_STORAGE, BPF_MAP_TYPE_TASK_STORAGE, #endif /* __GENKSYMS__ */ }; /* Note that tracing related programs such as * BPF_PROG_TYPE_{KPROBE,TRACEPOINT,PERF_EVENT,RAW_TRACEPOINT} * are not subject to a stable API since kernel internal data * structures can change from release to release and may * therefore break existing tracing BPF programs. Tracing BPF * programs correspond to /a/ specific kernel which is to be * analyzed, and not /a/ specific kernel /and/ all future ones. */ enum bpf_prog_type { BPF_PROG_TYPE_UNSPEC, BPF_PROG_TYPE_SOCKET_FILTER, BPF_PROG_TYPE_KPROBE, BPF_PROG_TYPE_SCHED_CLS, BPF_PROG_TYPE_SCHED_ACT, BPF_PROG_TYPE_TRACEPOINT, BPF_PROG_TYPE_XDP, BPF_PROG_TYPE_PERF_EVENT, BPF_PROG_TYPE_CGROUP_SKB, BPF_PROG_TYPE_CGROUP_SOCK, BPF_PROG_TYPE_LWT_IN, BPF_PROG_TYPE_LWT_OUT, BPF_PROG_TYPE_LWT_XMIT, BPF_PROG_TYPE_SOCK_OPS, BPF_PROG_TYPE_SK_SKB, BPF_PROG_TYPE_CGROUP_DEVICE, BPF_PROG_TYPE_SK_MSG, BPF_PROG_TYPE_RAW_TRACEPOINT, BPF_PROG_TYPE_CGROUP_SOCK_ADDR, BPF_PROG_TYPE_LWT_SEG6LOCAL, BPF_PROG_TYPE_LIRC_MODE2, #ifndef __GENKSYMS__ BPF_PROG_TYPE_SK_REUSEPORT, BPF_PROG_TYPE_FLOW_DISSECTOR, BPF_PROG_TYPE_CGROUP_SYSCTL, BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, BPF_PROG_TYPE_CGROUP_SOCKOPT, BPF_PROG_TYPE_TRACING, BPF_PROG_TYPE_STRUCT_OPS, BPF_PROG_TYPE_EXT, BPF_PROG_TYPE_LSM, BPF_PROG_TYPE_SK_LOOKUP, BPF_PROG_TYPE_SYSCALL, /* a program that can execute syscalls */ #endif /* __GENKSYMS__ */ }; enum bpf_attach_type { BPF_CGROUP_INET_INGRESS, BPF_CGROUP_INET_EGRESS, BPF_CGROUP_INET_SOCK_CREATE, BPF_CGROUP_SOCK_OPS, BPF_SK_SKB_STREAM_PARSER, BPF_SK_SKB_STREAM_VERDICT, BPF_CGROUP_DEVICE, BPF_SK_MSG_VERDICT, BPF_CGROUP_INET4_BIND, BPF_CGROUP_INET6_BIND, BPF_CGROUP_INET4_CONNECT, BPF_CGROUP_INET6_CONNECT, BPF_CGROUP_INET4_POST_BIND, BPF_CGROUP_INET6_POST_BIND, BPF_CGROUP_UDP4_SENDMSG, BPF_CGROUP_UDP6_SENDMSG, BPF_LIRC_MODE2, #ifndef __GENKSYMS__ BPF_FLOW_DISSECTOR, BPF_CGROUP_SYSCTL, BPF_CGROUP_UDP4_RECVMSG, BPF_CGROUP_UDP6_RECVMSG, BPF_CGROUP_GETSOCKOPT, BPF_CGROUP_SETSOCKOPT, BPF_TRACE_RAW_TP, BPF_TRACE_FENTRY, BPF_TRACE_FEXIT, BPF_MODIFY_RETURN, BPF_LSM_MAC, BPF_TRACE_ITER, BPF_CGROUP_INET4_GETPEERNAME, BPF_CGROUP_INET6_GETPEERNAME, BPF_CGROUP_INET4_GETSOCKNAME, BPF_CGROUP_INET6_GETSOCKNAME, BPF_XDP_DEVMAP, BPF_CGROUP_INET_SOCK_RELEASE, BPF_XDP_CPUMAP, BPF_SK_LOOKUP, BPF_XDP, BPF_SK_SKB_VERDICT, #endif /* __GENKSYMS__ */ __MAX_BPF_ATTACH_TYPE }; #define MAX_BPF_ATTACH_TYPE __MAX_BPF_ATTACH_TYPE enum bpf_link_type { BPF_LINK_TYPE_UNSPEC = 0, BPF_LINK_TYPE_RAW_TRACEPOINT = 1, BPF_LINK_TYPE_TRACING = 2, BPF_LINK_TYPE_CGROUP = 3, BPF_LINK_TYPE_ITER = 4, BPF_LINK_TYPE_NETNS = 5, BPF_LINK_TYPE_XDP = 6, MAX_BPF_LINK_TYPE, }; /* cgroup-bpf attach flags used in BPF_PROG_ATTACH command * * NONE(default): No further bpf programs allowed in the subtree. * * BPF_F_ALLOW_OVERRIDE: If a sub-cgroup installs some bpf program, * the program in this cgroup yields to sub-cgroup program. * * BPF_F_ALLOW_MULTI: If a sub-cgroup installs some bpf program, * that cgroup program gets run in addition to the program in this cgroup. * * Only one program is allowed to be attached to a cgroup with * NONE or BPF_F_ALLOW_OVERRIDE flag. * Attaching another program on top of NONE or BPF_F_ALLOW_OVERRIDE will * release old program and attach the new one. Attach flags has to match. * * Multiple programs are allowed to be attached to a cgroup with * BPF_F_ALLOW_MULTI flag. They are executed in FIFO order * (those that were attached first, run first) * The programs of sub-cgroup are executed first, then programs of * this cgroup and then programs of parent cgroup. * When children program makes decision (like picking TCP CA or sock bind) * parent program has a chance to override it. * * With BPF_F_ALLOW_MULTI a new program is added to the end of the list of * programs for a cgroup. Though it's possible to replace an old program at * any position by also specifying BPF_F_REPLACE flag and position itself in * replace_bpf_fd attribute. Old program at this position will be released. * * A cgroup with MULTI or OVERRIDE flag allows any attach flags in sub-cgroups. * A cgroup with NONE doesn't allow any programs in sub-cgroups. * Ex1: * cgrp1 (MULTI progs A, B) -> * cgrp2 (OVERRIDE prog C) -> * cgrp3 (MULTI prog D) -> * cgrp4 (OVERRIDE prog E) -> * cgrp5 (NONE prog F) * the event in cgrp5 triggers execution of F,D,A,B in that order. * if prog F is detached, the execution is E,D,A,B * if prog F and D are detached, the execution is E,A,B * if prog F, E and D are detached, the execution is C,A,B * * All eligible programs are executed regardless of return code from * earlier programs. */ #define BPF_F_ALLOW_OVERRIDE (1U << 0) #define BPF_F_ALLOW_MULTI (1U << 1) #define BPF_F_REPLACE (1U << 2) /* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the * verifier will perform strict alignment checking as if the kernel * has been built with CONFIG_EFFICIENT_UNALIGNED_ACCESS not set, * and NET_IP_ALIGN defined to 2. */ #define BPF_F_STRICT_ALIGNMENT (1U << 0) /* If BPF_F_ANY_ALIGNMENT is used in BPF_PROF_LOAD command, the * verifier will allow any alignment whatsoever. On platforms * with strict alignment requirements for loads ands stores (such * as sparc and mips) the verifier validates that all loads and * stores provably follow this requirement. This flag turns that * checking and enforcement off. * * It is mostly used for testing when we want to validate the * context and memory access aspects of the verifier, but because * of an unaligned access the alignment check would trigger before * the one we are interested in. */ #define BPF_F_ANY_ALIGNMENT (1U << 1) /* BPF_F_TEST_RND_HI32 is used in BPF_PROG_LOAD command for testing purpose. * Verifier does sub-register def/use analysis and identifies instructions whose * def only matters for low 32-bit, high 32-bit is never referenced later * through implicit zero extension. Therefore verifier notifies JIT back-ends * that it is safe to ignore clearing high 32-bit for these instructions. This * saves some back-ends a lot of code-gen. However such optimization is not * necessary on some arches, for example x86_64, arm64 etc, whose JIT back-ends * hence hasn't used verifier's analysis result. But, we really want to have a * way to be able to verify the correctness of the described optimization on * x86_64 on which testsuites are frequently exercised. * * So, this flag is introduced. Once it is set, verifier will randomize high * 32-bit for those instructions who has been identified as safe to ignore them. * Then, if verifier is not doing correct analysis, such randomization will * regress tests to expose bugs. */ #define BPF_F_TEST_RND_HI32 (1U << 2) /* The verifier internal test flag. Behavior is undefined */ #define BPF_F_TEST_STATE_FREQ (1U << 3) /* If BPF_F_SLEEPABLE is used in BPF_PROG_LOAD command, the verifier will * restrict map and helper usage for such programs. Sleepable BPF programs can * only be attached to hooks where kernel execution context allows sleeping. * Such programs are allowed to use helpers that may sleep like * bpf_copy_from_user(). */ #define BPF_F_SLEEPABLE (1U << 4) /* When BPF ldimm64's insn[0].src_reg != 0 then this can have * the following extensions: * * insn[0].src_reg: BPF_PSEUDO_MAP_[FD|IDX] * insn[0].imm: map fd or fd_idx * insn[1].imm: 0 * insn[0].off: 0 * insn[1].off: 0 * ldimm64 rewrite: address of map * verifier type: CONST_PTR_TO_MAP */ #define BPF_PSEUDO_MAP_FD 1 #define BPF_PSEUDO_MAP_IDX 5 /* insn[0].src_reg: BPF_PSEUDO_MAP_[IDX_]VALUE * insn[0].imm: map fd or fd_idx * insn[1].imm: offset into value * insn[0].off: 0 * insn[1].off: 0 * ldimm64 rewrite: address of map[0]+offset * verifier type: PTR_TO_MAP_VALUE */ #define BPF_PSEUDO_MAP_VALUE 2 #define BPF_PSEUDO_MAP_IDX_VALUE 6 /* insn[0].src_reg: BPF_PSEUDO_BTF_ID * insn[0].imm: kernel btd id of VAR * insn[1].imm: 0 * insn[0].off: 0 * insn[1].off: 0 * ldimm64 rewrite: address of the kernel variable * verifier type: PTR_TO_BTF_ID or PTR_TO_MEM, depending on whether the var * is struct/union. */ #define BPF_PSEUDO_BTF_ID 3 /* insn[0].src_reg: BPF_PSEUDO_FUNC * insn[0].imm: insn offset to the func * insn[1].imm: 0 * insn[0].off: 0 * insn[1].off: 0 * ldimm64 rewrite: address of the function * verifier type: PTR_TO_FUNC. */ #define BPF_PSEUDO_FUNC 4 /* when bpf_call->src_reg == BPF_PSEUDO_CALL, bpf_call->imm == pc-relative * offset to another bpf function */ #define BPF_PSEUDO_CALL 1 /* when bpf_call->src_reg == BPF_PSEUDO_KFUNC_CALL, * bpf_call->imm == btf_id of a BTF_KIND_FUNC in the running kernel */ #define BPF_PSEUDO_KFUNC_CALL 2 /* flags for BPF_MAP_UPDATE_ELEM command */ enum { BPF_ANY = 0, /* create new element or update existing */ BPF_NOEXIST = 1, /* create new element if it didn't exist */ BPF_EXIST = 2, /* update existing element */ BPF_F_LOCK = 4, /* spin_lock-ed map_lookup/map_update */ }; /* flags for BPF_MAP_CREATE command */ enum { BPF_F_NO_PREALLOC = (1U << 0), /* Instead of having one common LRU list in the * BPF_MAP_TYPE_LRU_[PERCPU_]HASH map, use a percpu LRU list * which can scale and perform better. * Note, the LRU nodes (including free nodes) cannot be moved * across different LRU lists. */ BPF_F_NO_COMMON_LRU = (1U << 1), /* Specify numa node during map creation */ BPF_F_NUMA_NODE = (1U << 2), /* Flags for accessing BPF object from syscall side. */ BPF_F_RDONLY = (1U << 3), BPF_F_WRONLY = (1U << 4), /* Flag for stack_map, store build_id+offset instead of pointer */ BPF_F_STACK_BUILD_ID = (1U << 5), /* Zero-initialize hash function seed. This should only be used for testing. */ BPF_F_ZERO_SEED = (1U << 6), /* Flags for accessing BPF object from program side. */ BPF_F_RDONLY_PROG = (1U << 7), BPF_F_WRONLY_PROG = (1U << 8), /* Clone map from listener for newly accepted socket */ BPF_F_CLONE = (1U << 9), /* Enable memory-mapping BPF map */ BPF_F_MMAPABLE = (1U << 10), /* Share perf_event among processes */ BPF_F_PRESERVE_ELEMS = (1U << 11), /* Create a map that is suitable to be an inner map with dynamic max entries */ BPF_F_INNER_MAP = (1U << 12), }; /* Flags for BPF_PROG_QUERY. */ /* Query effective (directly attached + inherited from ancestor cgroups) * programs that will be executed for events within a cgroup. * attach_flags with this flag are returned only for directly attached programs. */ #define BPF_F_QUERY_EFFECTIVE (1U << 0) /* Flags for BPF_PROG_TEST_RUN */ /* If set, run the test on the cpu specified by bpf_attr.test.cpu */ #define BPF_F_TEST_RUN_ON_CPU (1U << 0) /* type for BPF_ENABLE_STATS */ enum bpf_stats_type { /* enabled run_time_ns and run_cnt */ BPF_STATS_RUN_TIME = 0, }; enum bpf_stack_build_id_status { /* user space need an empty entry to identify end of a trace */ BPF_STACK_BUILD_ID_EMPTY = 0, /* with valid build_id and offset */ BPF_STACK_BUILD_ID_VALID = 1, /* couldn't get build_id, fallback to ip */ BPF_STACK_BUILD_ID_IP = 2, }; #define BPF_BUILD_ID_SIZE 20 struct bpf_stack_build_id { __s32 status; unsigned char build_id[BPF_BUILD_ID_SIZE]; union { __u64 offset; __u64 ip; }; }; #define BPF_OBJ_NAME_LEN 16U union bpf_attr { struct { /* anonymous struct used by BPF_MAP_CREATE command */ __u32 map_type; /* one of enum bpf_map_type */ __u32 key_size; /* size of key in bytes */ __u32 value_size; /* size of value in bytes */ __u32 max_entries; /* max number of entries in a map */ __u32 map_flags; /* BPF_MAP_CREATE related * flags defined above. */ __u32 inner_map_fd; /* fd pointing to the inner map */ __u32 numa_node; /* numa node (effective only if * BPF_F_NUMA_NODE is set). */ char map_name[BPF_OBJ_NAME_LEN]; __u32 map_ifindex; /* ifindex of netdev to create on */ __u32 btf_fd; /* fd pointing to a BTF type data */ __u32 btf_key_type_id; /* BTF type_id of the key */ __u32 btf_value_type_id; /* BTF type_id of the value */ #ifndef __GENKSYMS__ __u32 btf_vmlinux_value_type_id;/* BTF type_id of a kernel- * struct stored as the * map value */ #endif /* __GENKSYMS__ */ }; struct { /* anonymous struct used by BPF_MAP_*_ELEM commands */ __u32 map_fd; __aligned_u64 key; union { __aligned_u64 value; __aligned_u64 next_key; }; __u64 flags; }; #ifndef __GENKSYMS__ struct { /* struct used by BPF_MAP_*_BATCH commands */ __aligned_u64 in_batch; /* start batch, * NULL to start from beginning */ __aligned_u64 out_batch; /* output: next start batch */ __aligned_u64 keys; __aligned_u64 values; __u32 count; /* input/output: * input: # of key/value * elements * output: # of filled elements */ __u32 map_fd; __u64 elem_flags; __u64 flags; } batch; #endif /* __GENKSYMS__ */ struct { /* anonymous struct used by BPF_PROG_LOAD command */ __u32 prog_type; /* one of enum bpf_prog_type */ __u32 insn_cnt; __aligned_u64 insns; __aligned_u64 license; __u32 log_level; /* verbosity level of verifier */ __u32 log_size; /* size of user buffer */ __aligned_u64 log_buf; /* user supplied buffer */ __u32 kern_version; /* not used */ __u32 prog_flags; char prog_name[BPF_OBJ_NAME_LEN]; __u32 prog_ifindex; /* ifindex of netdev to prep for */ /* For some prog types expected attach type must be known at * load time to verify attach type specific parts of prog * (context accesses, allowed helpers, etc). */ __u32 expected_attach_type; #ifndef __GENKSYMS__ __u32 prog_btf_fd; /* fd pointing to BTF type data */ __u32 func_info_rec_size; /* userspace bpf_func_info size */ __aligned_u64 func_info; /* func info */ __u32 func_info_cnt; /* number of bpf_func_info records */ __u32 line_info_rec_size; /* userspace bpf_line_info size */ __aligned_u64 line_info; /* line info */ __u32 line_info_cnt; /* number of bpf_line_info records */ __u32 attach_btf_id; /* in-kernel BTF type id to attach to */ union { /* valid prog_fd to attach to bpf prog */ __u32 attach_prog_fd; /* or valid module BTF object fd or 0 to attach to vmlinux */ __u32 attach_btf_obj_fd; }; __u32 :32; /* pad */ __aligned_u64 fd_array; /* array of FDs */ #endif /* __GENKSYMS__ */ }; struct { /* anonymous struct used by BPF_OBJ_* commands */ __aligned_u64 pathname; __u32 bpf_fd; __u32 file_flags; }; struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */ __u32 target_fd; /* container object to attach to */ __u32 attach_bpf_fd; /* eBPF program to attach */ __u32 attach_type; __u32 attach_flags; #ifndef __GENKSYMS__ __u32 replace_bpf_fd; /* previously attached eBPF * program to replace if * BPF_F_REPLACE is used */ #endif /* __GENKSYMS__ */ }; struct { /* anonymous struct used by BPF_PROG_TEST_RUN command */ __u32 prog_fd; __u32 retval; __u32 data_size_in; /* input: len of data_in */ __u32 data_size_out; /* input/output: len of data_out * returns ENOSPC if data_out * is too small. */ __aligned_u64 data_in; __aligned_u64 data_out; __u32 repeat; __u32 duration; #ifndef __GENKSYMS__ __u32 ctx_size_in; /* input: len of ctx_in */ __u32 ctx_size_out; /* input/output: len of ctx_out * returns ENOSPC if ctx_out * is too small. */ __aligned_u64 ctx_in; __aligned_u64 ctx_out; __u32 flags; __u32 cpu; #endif /* __GENKSYMS__ */ } test; struct { /* anonymous struct used by BPF_*_GET_*_ID */ union { __u32 start_id; __u32 prog_id; __u32 map_id; __u32 btf_id; #ifndef __GENKSYMS__ __u32 link_id; #endif /* __GENKSYMS__ */ }; __u32 next_id; __u32 open_flags; }; struct { /* anonymous struct used by BPF_OBJ_GET_INFO_BY_FD */ __u32 bpf_fd; __u32 info_len; __aligned_u64 info; } info; struct { /* anonymous struct used by BPF_PROG_QUERY command */ __u32 target_fd; /* container object to query */ __u32 attach_type; __u32 query_flags; __u32 attach_flags; __aligned_u64 prog_ids; __u32 prog_cnt; } query; struct { /* anonymous struct used by BPF_RAW_TRACEPOINT_OPEN command */ __u64 name; __u32 prog_fd; } raw_tracepoint; struct { /* anonymous struct for BPF_BTF_LOAD */ __aligned_u64 btf; __aligned_u64 btf_log_buf; __u32 btf_size; __u32 btf_log_size; __u32 btf_log_level; }; struct { __u32 pid; /* input: pid */ __u32 fd; /* input: fd */ __u32 flags; /* input: flags */ __u32 buf_len; /* input/output: buf len */ __aligned_u64 buf; /* input/output: * tp_name for tracepoint * symbol for kprobe * filename for uprobe */ __u32 prog_id; /* output: prod_id */ __u32 fd_type; /* output: BPF_FD_TYPE_* */ __u64 probe_offset; /* output: probe_offset */ __u64 probe_addr; /* output: probe_addr */ } task_fd_query; #ifndef __GENKSYMS__ struct { /* struct used by BPF_LINK_CREATE command */ __u32 prog_fd; /* eBPF program to attach */ union { __u32 target_fd; /* object to attach to */ __u32 target_ifindex; /* target ifindex */ }; __u32 attach_type; /* attach type */ __u32 flags; /* extra flags */ union { __u32 target_btf_id; /* btf_id of target to attach to */ struct { __aligned_u64 iter_info; /* extra bpf_iter_link_info */ __u32 iter_info_len; /* iter_info length */ }; }; } link_create; struct { /* struct used by BPF_LINK_UPDATE command */ __u32 link_fd; /* link fd */ /* new program fd to update link with */ __u32 new_prog_fd; __u32 flags; /* extra flags */ /* expected link's program fd; is specified only if * BPF_F_REPLACE flag is set in flags */ __u32 old_prog_fd; } link_update; struct { __u32 link_fd; } link_detach; struct { /* struct used by BPF_ENABLE_STATS command */ __u32 type; } enable_stats; struct { /* struct used by BPF_ITER_CREATE command */ __u32 link_fd; __u32 flags; } iter_create; struct { /* struct used by BPF_PROG_BIND_MAP command */ __u32 prog_fd; __u32 map_fd; __u32 flags; /* extra flags */ } prog_bind_map; #endif /* __GENKSYMS__ */ } __attribute__((aligned(8))); /* The description below is an attempt at providing documentation to eBPF * developers about the multiple available eBPF helper functions. It can be * parsed and used to produce a manual page. The workflow is the following, * and requires the rst2man utility: * * $ ./scripts/bpf_doc.py \ * --filename include/uapi/linux/bpf.h > /tmp/bpf-helpers.rst * $ rst2man /tmp/bpf-helpers.rst > /tmp/bpf-helpers.7 * $ man /tmp/bpf-helpers.7 * * Note that in order to produce this external documentation, some RST * formatting is used in the descriptions to get "bold" and "italics" in * manual pages. Also note that the few trailing white spaces are * intentional, removing them would break paragraphs for rst2man. * * Start of BPF helper function descriptions: * * void *bpf_map_lookup_elem(struct bpf_map *map, const void *key) * Description * Perform a lookup in *map* for an entry associated to *key*. * Return * Map value associated to *key*, or **NULL** if no entry was * found. * * long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags) * Description * Add or update the value of the entry associated to *key* in * *map* with *value*. *flags* is one of: * * **BPF_NOEXIST** * The entry for *key* must not exist in the map. * **BPF_EXIST** * The entry for *key* must already exist in the map. * **BPF_ANY** * No condition on the existence of the entry for *key*. * * Flag value **BPF_NOEXIST** cannot be used for maps of types * **BPF_MAP_TYPE_ARRAY** or **BPF_MAP_TYPE_PERCPU_ARRAY** (all * elements always exist), the helper would return an error. * Return * 0 on success, or a negative error in case of failure. * * long bpf_map_delete_elem(struct bpf_map *map, const void *key) * Description * Delete entry with *key* from *map*. * Return * 0 on success, or a negative error in case of failure. * * long bpf_probe_read(void *dst, u32 size, const void *unsafe_ptr) * Description * For tracing programs, safely attempt to read *size* bytes from * kernel space address *unsafe_ptr* and store the data in *dst*. * * Generally, use **bpf_probe_read_user**\ () or * **bpf_probe_read_kernel**\ () instead. * Return * 0 on success, or a negative error in case of failure. * * u64 bpf_ktime_get_ns(void) * Description * Return the time elapsed since system boot, in nanoseconds. * Does not include time the system was suspended. * See: **clock_gettime**\ (**CLOCK_MONOTONIC**) * Return * Current *ktime*. * * long bpf_trace_printk(const char *fmt, u32 fmt_size, ...) * Description * This helper is a "printk()-like" facility for debugging. It * prints a message defined by format *fmt* (of size *fmt_size*) * to file *\/sys/kernel/debug/tracing/trace* from DebugFS, if * available. It can take up to three additional **u64** * arguments (as an eBPF helpers, the total number of arguments is * limited to five). * * Each time the helper is called, it appends a line to the trace. * Lines are discarded while *\/sys/kernel/debug/tracing/trace* is * open, use *\/sys/kernel/debug/tracing/trace_pipe* to avoid this. * The format of the trace is customizable, and the exact output * one will get depends on the options set in * *\/sys/kernel/debug/tracing/trace_options* (see also the * *README* file under the same directory). However, it usually * defaults to something like: * * :: * * telnet-470 [001] .N.. 419421.045894: 0x00000001: * * In the above: * * * ``telnet`` is the name of the current task. * * ``470`` is the PID of the current task. * * ``001`` is the CPU number on which the task is * running. * * In ``.N..``, each character refers to a set of * options (whether irqs are enabled, scheduling * options, whether hard/softirqs are running, level of * preempt_disabled respectively). **N** means that * **TIF_NEED_RESCHED** and **PREEMPT_NEED_RESCHED** * are set. * * ``419421.045894`` is a timestamp. * * ``0x00000001`` is a fake value used by BPF for the * instruction pointer register. * * ```` is the message formatted with * *fmt*. * * The conversion specifiers supported by *fmt* are similar, but * more limited than for printk(). They are **%d**, **%i**, * **%u**, **%x**, **%ld**, **%li**, **%lu**, **%lx**, **%lld**, * **%lli**, **%llu**, **%llx**, **%p**, **%s**. No modifier (size * of field, padding with zeroes, etc.) is available, and the * helper will return **-EINVAL** (but print nothing) if it * encounters an unknown specifier. * * Also, note that **bpf_trace_printk**\ () is slow, and should * only be used for debugging purposes. For this reason, a notice * block (spanning several lines) is printed to kernel logs and * states that the helper should not be used "for production use" * the first time this helper is used (or more precisely, when * **trace_printk**\ () buffers are allocated). For passing values * to user space, perf events should be preferred. * Return * The number of bytes written to the buffer, or a negative error * in case of failure. * * u32 bpf_get_prandom_u32(void) * Description * Get a pseudo-random number. * * From a security point of view, this helper uses its own * pseudo-random internal state, and cannot be used to infer the * seed of other random functions in the kernel. However, it is * essential to note that the generator used by the helper is not * cryptographically secure. * Return * A random 32-bit unsigned value. * * u32 bpf_get_smp_processor_id(void) * Description * Get the SMP (symmetric multiprocessing) processor id. Note that * all programs run with preemption disabled, which means that the * SMP processor id is stable during all the execution of the * program. * Return * The SMP id of the processor running the program. * * long bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len, u64 flags) * Description * Store *len* bytes from address *from* into the packet * associated to *skb*, at *offset*. *flags* are a combination of * **BPF_F_RECOMPUTE_CSUM** (automatically recompute the * checksum for the packet after storing the bytes) and * **BPF_F_INVALIDATE_HASH** (set *skb*\ **->hash**, *skb*\ * **->swhash** and *skb*\ **->l4hash** to 0). * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_l3_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 size) * Description * Recompute the layer 3 (e.g. IP) checksum for the packet * associated to *skb*. Computation is incremental, so the helper * must know the former value of the header field that was * modified (*from*), the new value of this field (*to*), and the * number of bytes (2 or 4) for this field, stored in *size*. * Alternatively, it is possible to store the difference between * the previous and the new values of the header field in *to*, by * setting *from* and *size* to 0. For both methods, *offset* * indicates the location of the IP checksum within the packet. * * This helper works in combination with **bpf_csum_diff**\ (), * which does not update the checksum in-place, but offers more * flexibility and can handle sizes larger than 2 or 4 for the * checksum to update. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_l4_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 flags) * Description * Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the * packet associated to *skb*. Computation is incremental, so the * helper must know the former value of the header field that was * modified (*from*), the new value of this field (*to*), and the * number of bytes (2 or 4) for this field, stored on the lowest * four bits of *flags*. Alternatively, it is possible to store * the difference between the previous and the new values of the * header field in *to*, by setting *from* and the four lowest * bits of *flags* to 0. For both methods, *offset* indicates the * location of the IP checksum within the packet. In addition to * the size of the field, *flags* can be added (bitwise OR) actual * flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left * untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and * for updates resulting in a null checksum the value is set to * **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates * the checksum is to be computed against a pseudo-header. * * This helper works in combination with **bpf_csum_diff**\ (), * which does not update the checksum in-place, but offers more * flexibility and can handle sizes larger than 2 or 4 for the * checksum to update. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_tail_call(void *ctx, struct bpf_map *prog_array_map, u32 index) * Description * This special helper is used to trigger a "tail call", or in * other words, to jump into another eBPF program. The same stack * frame is used (but values on stack and in registers for the * caller are not accessible to the callee). This mechanism allows * for program chaining, either for raising the maximum number of * available eBPF instructions, or to execute given programs in * conditional blocks. For security reasons, there is an upper * limit to the number of successive tail calls that can be * performed. * * Upon call of this helper, the program attempts to jump into a * program referenced at index *index* in *prog_array_map*, a * special map of type **BPF_MAP_TYPE_PROG_ARRAY**, and passes * *ctx*, a pointer to the context. * * If the call succeeds, the kernel immediately runs the first * instruction of the new program. This is not a function call, * and it never returns to the previous program. If the call * fails, then the helper has no effect, and the caller continues * to run its subsequent instructions. A call can fail if the * destination program for the jump does not exist (i.e. *index* * is superior to the number of entries in *prog_array_map*), or * if the maximum number of tail calls has been reached for this * chain of programs. This limit is defined in the kernel by the * macro **MAX_TAIL_CALL_CNT** (not accessible to user space), * which is currently set to 32. * Return * 0 on success, or a negative error in case of failure. * * long bpf_clone_redirect(struct sk_buff *skb, u32 ifindex, u64 flags) * Description * Clone and redirect the packet associated to *skb* to another * net device of index *ifindex*. Both ingress and egress * interfaces can be used for redirection. The **BPF_F_INGRESS** * value in *flags* is used to make the distinction (ingress path * is selected if the flag is present, egress path otherwise). * This is the only flag supported for now. * * In comparison with **bpf_redirect**\ () helper, * **bpf_clone_redirect**\ () has the associated cost of * duplicating the packet buffer, but this can be executed out of * the eBPF program. Conversely, **bpf_redirect**\ () is more * efficient, but it is handled through an action code where the * redirection happens only after the eBPF program has returned. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. Positive * error indicates a potential drop or congestion in the target * device. The particular positive error codes are not defined. * * u64 bpf_get_current_pid_tgid(void) * Return * A 64-bit integer containing the current tgid and pid, and * created as such: * *current_task*\ **->tgid << 32 \|** * *current_task*\ **->pid**. * * u64 bpf_get_current_uid_gid(void) * Return * A 64-bit integer containing the current GID and UID, and * created as such: *current_gid* **<< 32 \|** *current_uid*. * * long bpf_get_current_comm(void *buf, u32 size_of_buf) * Description * Copy the **comm** attribute of the current task into *buf* of * *size_of_buf*. The **comm** attribute contains the name of * the executable (excluding the path) for the current task. The * *size_of_buf* must be strictly positive. On success, the * helper makes sure that the *buf* is NUL-terminated. On failure, * it is filled with zeroes. * Return * 0 on success, or a negative error in case of failure. * * u32 bpf_get_cgroup_classid(struct sk_buff *skb) * Description * Retrieve the classid for the current task, i.e. for the net_cls * cgroup to which *skb* belongs. * * This helper can be used on TC egress path, but not on ingress. * * The net_cls cgroup provides an interface to tag network packets * based on a user-provided identifier for all traffic coming from * the tasks belonging to the related cgroup. See also the related * kernel documentation, available from the Linux sources in file * *Documentation/cgroup-v1/net_cls.txt*. * * The Linux kernel has two versions for cgroups: there are * cgroups v1 and cgroups v2. Both are available to users, who can * use a mixture of them, but note that the net_cls cgroup is for * cgroup v1 only. This makes it incompatible with BPF programs * run on cgroups, which is a cgroup-v2-only feature (a socket can * only hold data for one version of cgroups at a time). * * This helper is only available is the kernel was compiled with * the **CONFIG_CGROUP_NET_CLASSID** configuration option set to * "**y**" or to "**m**". * Return * The classid, or 0 for the default unconfigured classid. * * long bpf_skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci) * Description * Push a *vlan_tci* (VLAN tag control information) of protocol * *vlan_proto* to the packet associated to *skb*, then update * the checksum. Note that if *vlan_proto* is different from * **ETH_P_8021Q** and **ETH_P_8021AD**, it is considered to * be **ETH_P_8021Q**. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_vlan_pop(struct sk_buff *skb) * Description * Pop a VLAN header from the packet associated to *skb*. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_get_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) * Description * Get tunnel metadata. This helper takes a pointer *key* to an * empty **struct bpf_tunnel_key** of **size**, that will be * filled with tunnel metadata for the packet associated to *skb*. * The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which * indicates that the tunnel is based on IPv6 protocol instead of * IPv4. * * The **struct bpf_tunnel_key** is an object that generalizes the * principal parameters used by various tunneling protocols into a * single struct. This way, it can be used to easily make a * decision based on the contents of the encapsulation header, * "summarized" in this struct. In particular, it holds the IP * address of the remote end (IPv4 or IPv6, depending on the case) * in *key*\ **->remote_ipv4** or *key*\ **->remote_ipv6**. Also, * this struct exposes the *key*\ **->tunnel_id**, which is * generally mapped to a VNI (Virtual Network Identifier), making * it programmable together with the **bpf_skb_set_tunnel_key**\ * () helper. * * Let's imagine that the following code is part of a program * attached to the TC ingress interface, on one end of a GRE * tunnel, and is supposed to filter out all messages coming from * remote ends with IPv4 address other than 10.0.0.1: * * :: * * int ret; * struct bpf_tunnel_key key = {}; * * ret = bpf_skb_get_tunnel_key(skb, &key, sizeof(key), 0); * if (ret < 0) * return TC_ACT_SHOT; // drop packet * * if (key.remote_ipv4 != 0x0a000001) * return TC_ACT_SHOT; // drop packet * * return TC_ACT_OK; // accept packet * * This interface can also be used with all encapsulation devices * that can operate in "collect metadata" mode: instead of having * one network device per specific configuration, the "collect * metadata" mode only requires a single device where the * configuration can be extracted from this helper. * * This can be used together with various tunnels such as VXLan, * Geneve, GRE or IP in IP (IPIP). * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_set_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) * Description * Populate tunnel metadata for packet associated to *skb.* The * tunnel metadata is set to the contents of *key*, of *size*. The * *flags* can be set to a combination of the following values: * * **BPF_F_TUNINFO_IPV6** * Indicate that the tunnel is based on IPv6 protocol * instead of IPv4. * **BPF_F_ZERO_CSUM_TX** * For IPv4 packets, add a flag to tunnel metadata * indicating that checksum computation should be skipped * and checksum set to zeroes. * **BPF_F_DONT_FRAGMENT** * Add a flag to tunnel metadata indicating that the * packet should not be fragmented. * **BPF_F_SEQ_NUMBER** * Add a flag to tunnel metadata indicating that a * sequence number should be added to tunnel header before * sending the packet. This flag was added for GRE * encapsulation, but might be used with other protocols * as well in the future. * * Here is a typical usage on the transmit path: * * :: * * struct bpf_tunnel_key key; * populate key ... * bpf_skb_set_tunnel_key(skb, &key, sizeof(key), 0); * bpf_clone_redirect(skb, vxlan_dev_ifindex, 0); * * See also the description of the **bpf_skb_get_tunnel_key**\ () * helper for additional information. * Return * 0 on success, or a negative error in case of failure. * * u64 bpf_perf_event_read(struct bpf_map *map, u64 flags) * Description * Read the value of a perf event counter. This helper relies on a * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of * the perf event counter is selected when *map* is updated with * perf event file descriptors. The *map* is an array whose size * is the number of available CPUs, and each cell contains a value * relative to one CPU. The value to retrieve is indicated by * *flags*, that contains the index of the CPU to look up, masked * with **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to * **BPF_F_CURRENT_CPU** to indicate that the value for the * current CPU should be retrieved. * * Note that before Linux 4.13, only hardware perf event can be * retrieved. * * Also, be aware that the newer helper * **bpf_perf_event_read_value**\ () is recommended over * **bpf_perf_event_read**\ () in general. The latter has some ABI * quirks where error and counter value are used as a return code * (which is wrong to do since ranges may overlap). This issue is * fixed with **bpf_perf_event_read_value**\ (), which at the same * time provides more features over the **bpf_perf_event_read**\ * () interface. Please refer to the description of * **bpf_perf_event_read_value**\ () for details. * Return * The value of the perf event counter read from the map, or a * negative error code in case of failure. * * long bpf_redirect(u32 ifindex, u64 flags) * Description * Redirect the packet to another net device of index *ifindex*. * This helper is somewhat similar to **bpf_clone_redirect**\ * (), except that the packet is not cloned, which provides * increased performance. * * Except for XDP, both ingress and egress interfaces can be used * for redirection. The **BPF_F_INGRESS** value in *flags* is used * to make the distinction (ingress path is selected if the flag * is present, egress path otherwise). Currently, XDP only * supports redirection to the egress interface, and accepts no * flag at all. * * The same effect can also be attained with the more generic * **bpf_redirect_map**\ (), which uses a BPF map to store the * redirect target instead of providing it directly to the helper. * Return * For XDP, the helper returns **XDP_REDIRECT** on success or * **XDP_ABORTED** on error. For other program types, the values * are **TC_ACT_REDIRECT** on success or **TC_ACT_SHOT** on * error. * * u32 bpf_get_route_realm(struct sk_buff *skb) * Description * Retrieve the realm or the route, that is to say the * **tclassid** field of the destination for the *skb*. The * identifier retrieved is a user-provided tag, similar to the * one used with the net_cls cgroup (see description for * **bpf_get_cgroup_classid**\ () helper), but here this tag is * held by a route (a destination entry), not by a task. * * Retrieving this identifier works with the clsact TC egress hook * (see also **tc-bpf(8)**), or alternatively on conventional * classful egress qdiscs, but not on TC ingress path. In case of * clsact TC egress hook, this has the advantage that, internally, * the destination entry has not been dropped yet in the transmit * path. Therefore, the destination entry does not need to be * artificially held via **netif_keep_dst**\ () for a classful * qdisc until the *skb* is freed. * * This helper is available only if the kernel was compiled with * **CONFIG_IP_ROUTE_CLASSID** configuration option. * Return * The realm of the route for the packet associated to *skb*, or 0 * if none was found. * * long bpf_perf_event_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) * Description * Write raw *data* blob into a special BPF perf event held by * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf * event must have the following attributes: **PERF_SAMPLE_RAW** * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. * * The *flags* are used to indicate the index in *map* for which * the value must be put, masked with **BPF_F_INDEX_MASK**. * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** * to indicate that the index of the current CPU core should be * used. * * The value to write, of *size*, is passed through eBPF stack and * pointed by *data*. * * The context of the program *ctx* needs also be passed to the * helper. * * On user space, a program willing to read the values needs to * call **perf_event_open**\ () on the perf event (either for * one or for all CPUs) and to store the file descriptor into the * *map*. This must be done before the eBPF program can send data * into it. An example is available in file * *samples/bpf/trace_output_user.c* in the Linux kernel source * tree (the eBPF program counterpart is in * *samples/bpf/trace_output_kern.c*). * * **bpf_perf_event_output**\ () achieves better performance * than **bpf_trace_printk**\ () for sharing data with user * space, and is much better suitable for streaming data from eBPF * programs. * * Note that this helper is not restricted to tracing use cases * and can be used with programs attached to TC or XDP as well, * where it allows for passing data to user space listeners. Data * can be: * * * Only custom structs, * * Only the packet payload, or * * A combination of both. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_load_bytes(const void *skb, u32 offset, void *to, u32 len) * Description * This helper was provided as an easy way to load data from a * packet. It can be used to load *len* bytes from *offset* from * the packet associated to *skb*, into the buffer pointed by * *to*. * * Since Linux 4.7, usage of this helper has mostly been replaced * by "direct packet access", enabling packet data to be * manipulated with *skb*\ **->data** and *skb*\ **->data_end** * pointing respectively to the first byte of packet data and to * the byte after the last byte of packet data. However, it * remains useful if one wishes to read large quantities of data * at once from a packet into the eBPF stack. * Return * 0 on success, or a negative error in case of failure. * * long bpf_get_stackid(void *ctx, struct bpf_map *map, u64 flags) * Description * Walk a user or a kernel stack and return its id. To achieve * this, the helper needs *ctx*, which is a pointer to the context * on which the tracing program is executed, and a pointer to a * *map* of type **BPF_MAP_TYPE_STACK_TRACE**. * * The last argument, *flags*, holds the number of stack frames to * skip (from 0 to 255), masked with * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set * a combination of the following flags: * * **BPF_F_USER_STACK** * Collect a user space stack instead of a kernel stack. * **BPF_F_FAST_STACK_CMP** * Compare stacks by hash only. * **BPF_F_REUSE_STACKID** * If two different stacks hash into the same *stackid*, * discard the old one. * * The stack id retrieved is a 32 bit long integer handle which * can be further combined with other data (including other stack * ids) and used as a key into maps. This can be useful for * generating a variety of graphs (such as flame graphs or off-cpu * graphs). * * For walking a stack, this helper is an improvement over * **bpf_probe_read**\ (), which can be used with unrolled loops * but is not efficient and consumes a lot of eBPF instructions. * Instead, **bpf_get_stackid**\ () can collect up to * **PERF_MAX_STACK_DEPTH** both kernel and user frames. Note that * this limit can be controlled with the **sysctl** program, and * that it should be manually increased in order to profile long * user stacks (such as stacks for Java programs). To do so, use: * * :: * * # sysctl kernel.perf_event_max_stack= * Return * The positive or null stack id on success, or a negative error * in case of failure. * * s64 bpf_csum_diff(__be32 *from, u32 from_size, __be32 *to, u32 to_size, __wsum seed) * Description * Compute a checksum difference, from the raw buffer pointed by * *from*, of length *from_size* (that must be a multiple of 4), * towards the raw buffer pointed by *to*, of size *to_size* * (same remark). An optional *seed* can be added to the value * (this can be cascaded, the seed may come from a previous call * to the helper). * * This is flexible enough to be used in several ways: * * * With *from_size* == 0, *to_size* > 0 and *seed* set to * checksum, it can be used when pushing new data. * * With *from_size* > 0, *to_size* == 0 and *seed* set to * checksum, it can be used when removing data from a packet. * * With *from_size* > 0, *to_size* > 0 and *seed* set to 0, it * can be used to compute a diff. Note that *from_size* and * *to_size* do not need to be equal. * * This helper can be used in combination with * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ (), to * which one can feed in the difference computed with * **bpf_csum_diff**\ (). * Return * The checksum result, or a negative error code in case of * failure. * * long bpf_skb_get_tunnel_opt(struct sk_buff *skb, void *opt, u32 size) * Description * Retrieve tunnel options metadata for the packet associated to * *skb*, and store the raw tunnel option data to the buffer *opt* * of *size*. * * This helper can be used with encapsulation devices that can * operate in "collect metadata" mode (please refer to the related * note in the description of **bpf_skb_get_tunnel_key**\ () for * more details). A particular example where this can be used is * in combination with the Geneve encapsulation protocol, where it * allows for pushing (with **bpf_skb_get_tunnel_opt**\ () helper) * and retrieving arbitrary TLVs (Type-Length-Value headers) from * the eBPF program. This allows for full customization of these * headers. * Return * The size of the option data retrieved. * * long bpf_skb_set_tunnel_opt(struct sk_buff *skb, void *opt, u32 size) * Description * Set tunnel options metadata for the packet associated to *skb* * to the option data contained in the raw buffer *opt* of *size*. * * See also the description of the **bpf_skb_get_tunnel_opt**\ () * helper for additional information. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_change_proto(struct sk_buff *skb, __be16 proto, u64 flags) * Description * Change the protocol of the *skb* to *proto*. Currently * supported are transition from IPv4 to IPv6, and from IPv6 to * IPv4. The helper takes care of the groundwork for the * transition, including resizing the socket buffer. The eBPF * program is expected to fill the new headers, if any, via * **skb_store_bytes**\ () and to recompute the checksums with * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ * (). The main case for this helper is to perform NAT64 * operations out of an eBPF program. * * Internally, the GSO type is marked as dodgy so that headers are * checked and segments are recalculated by the GSO/GRO engine. * The size for GSO target is adapted as well. * * All values for *flags* are reserved for future usage, and must * be left at zero. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_change_type(struct sk_buff *skb, u32 type) * Description * Change the packet type for the packet associated to *skb*. This * comes down to setting *skb*\ **->pkt_type** to *type*, except * the eBPF program does not have a write access to *skb*\ * **->pkt_type** beside this helper. Using a helper here allows * for graceful handling of errors. * * The major use case is to change incoming *skb*s to * **PACKET_HOST** in a programmatic way instead of having to * recirculate via **redirect**\ (..., **BPF_F_INGRESS**), for * example. * * Note that *type* only allows certain values. At this time, they * are: * * **PACKET_HOST** * Packet is for us. * **PACKET_BROADCAST** * Send packet to all. * **PACKET_MULTICAST** * Send packet to group. * **PACKET_OTHERHOST** * Send packet to someone else. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_under_cgroup(struct sk_buff *skb, struct bpf_map *map, u32 index) * Description * Check whether *skb* is a descendant of the cgroup2 held by * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. * Return * The return value depends on the result of the test, and can be: * * * 0, if the *skb* failed the cgroup2 descendant test. * * 1, if the *skb* succeeded the cgroup2 descendant test. * * A negative error code, if an error occurred. * * u32 bpf_get_hash_recalc(struct sk_buff *skb) * Description * Retrieve the hash of the packet, *skb*\ **->hash**. If it is * not set, in particular if the hash was cleared due to mangling, * recompute this hash. Later accesses to the hash can be done * directly with *skb*\ **->hash**. * * Calling **bpf_set_hash_invalid**\ (), changing a packet * prototype with **bpf_skb_change_proto**\ (), or calling * **bpf_skb_store_bytes**\ () with the * **BPF_F_INVALIDATE_HASH** are actions susceptible to clear * the hash and to trigger a new computation for the next call to * **bpf_get_hash_recalc**\ (). * Return * The 32-bit hash. * * u64 bpf_get_current_task(void) * Return * A pointer to the current task struct. * * long bpf_probe_write_user(void *dst, const void *src, u32 len) * Description * Attempt in a safe way to write *len* bytes from the buffer * *src* to *dst* in memory. It only works for threads that are in * user context, and *dst* must be a valid user space address. * * This helper should not be used to implement any kind of * security mechanism because of TOC-TOU attacks, but rather to * debug, divert, and manipulate execution of semi-cooperative * processes. * * Keep in mind that this feature is meant for experiments, and it * has a risk of crashing the system and running programs. * Therefore, when an eBPF program using this helper is attached, * a warning including PID and process name is printed to kernel * logs. * Return * 0 on success, or a negative error in case of failure. * * long bpf_current_task_under_cgroup(struct bpf_map *map, u32 index) * Description * Check whether the probe is being run is the context of a given * subset of the cgroup2 hierarchy. The cgroup2 to test is held by * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. * Return * The return value depends on the result of the test, and can be: * * * 0, if current task belongs to the cgroup2. * * 1, if current task does not belong to the cgroup2. * * A negative error code, if an error occurred. * * long bpf_skb_change_tail(struct sk_buff *skb, u32 len, u64 flags) * Description * Resize (trim or grow) the packet associated to *skb* to the * new *len*. The *flags* are reserved for future usage, and must * be left at zero. * * The basic idea is that the helper performs the needed work to * change the size of the packet, then the eBPF program rewrites * the rest via helpers like **bpf_skb_store_bytes**\ (), * **bpf_l3_csum_replace**\ (), **bpf_l3_csum_replace**\ () * and others. This helper is a slow path utility intended for * replies with control messages. And because it is targeted for * slow path, the helper itself can afford to be slow: it * implicitly linearizes, unclones and drops offloads from the * *skb*. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_pull_data(struct sk_buff *skb, u32 len) * Description * Pull in non-linear data in case the *skb* is non-linear and not * all of *len* are part of the linear section. Make *len* bytes * from *skb* readable and writable. If a zero value is passed for * *len*, then the whole length of the *skb* is pulled. * * This helper is only needed for reading and writing with direct * packet access. * * For direct packet access, testing that offsets to access * are within packet boundaries (test on *skb*\ **->data_end**) is * susceptible to fail if offsets are invalid, or if the requested * data is in non-linear parts of the *skb*. On failure the * program can just bail out, or in the case of a non-linear * buffer, use a helper to make the data available. The * **bpf_skb_load_bytes**\ () helper is a first solution to access * the data. Another one consists in using **bpf_skb_pull_data** * to pull in once the non-linear parts, then retesting and * eventually access the data. * * At the same time, this also makes sure the *skb* is uncloned, * which is a necessary condition for direct write. As this needs * to be an invariant for the write part only, the verifier * detects writes and adds a prologue that is calling * **bpf_skb_pull_data()** to effectively unclone the *skb* from * the very beginning in case it is indeed cloned. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * s64 bpf_csum_update(struct sk_buff *skb, __wsum csum) * Description * Add the checksum *csum* into *skb*\ **->csum** in case the * driver has supplied a checksum for the entire packet into that * field. Return an error otherwise. This helper is intended to be * used in combination with **bpf_csum_diff**\ (), in particular * when the checksum needs to be updated after data has been * written into the packet through direct packet access. * Return * The checksum on success, or a negative error code in case of * failure. * * void bpf_set_hash_invalid(struct sk_buff *skb) * Description * Invalidate the current *skb*\ **->hash**. It can be used after * mangling on headers through direct packet access, in order to * indicate that the hash is outdated and to trigger a * recalculation the next time the kernel tries to access this * hash or when the **bpf_get_hash_recalc**\ () helper is called. * * long bpf_get_numa_node_id(void) * Description * Return the id of the current NUMA node. The primary use case * for this helper is the selection of sockets for the local NUMA * node, when the program is attached to sockets using the * **SO_ATTACH_REUSEPORT_EBPF** option (see also **socket(7)**), * but the helper is also available to other eBPF program types, * similarly to **bpf_get_smp_processor_id**\ (). * Return * The id of current NUMA node. * * long bpf_skb_change_head(struct sk_buff *skb, u32 len, u64 flags) * Description * Grows headroom of packet associated to *skb* and adjusts the * offset of the MAC header accordingly, adding *len* bytes of * space. It automatically extends and reallocates memory as * required. * * This helper can be used on a layer 3 *skb* to push a MAC header * for redirection into a layer 2 device. * * All values for *flags* are reserved for future usage, and must * be left at zero. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_xdp_adjust_head(struct xdp_buff *xdp_md, int delta) * Description * Adjust (move) *xdp_md*\ **->data** by *delta* bytes. Note that * it is possible to use a negative value for *delta*. This helper * can be used to prepare the packet for pushing or popping * headers. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_probe_read_str(void *dst, u32 size, const void *unsafe_ptr) * Description * Copy a NUL terminated string from an unsafe kernel address * *unsafe_ptr* to *dst*. See **bpf_probe_read_kernel_str**\ () for * more details. * * Generally, use **bpf_probe_read_user_str**\ () or * **bpf_probe_read_kernel_str**\ () instead. * Return * On success, the strictly positive length of the string, * including the trailing NUL character. On error, a negative * value. * * u64 bpf_get_socket_cookie(struct sk_buff *skb) * Description * If the **struct sk_buff** pointed by *skb* has a known socket, * retrieve the cookie (generated by the kernel) of this socket. * If no cookie has been set yet, generate a new cookie. Once * generated, the socket cookie remains stable for the life of the * socket. This helper can be useful for monitoring per socket * networking traffic statistics as it provides a global socket * identifier that can be assumed unique. * Return * A 8-byte long unique number on success, or 0 if the socket * field is missing inside *skb*. * * u64 bpf_get_socket_cookie(struct bpf_sock_addr *ctx) * Description * Equivalent to bpf_get_socket_cookie() helper that accepts * *skb*, but gets socket from **struct bpf_sock_addr** context. * Return * A 8-byte long unique number. * * u64 bpf_get_socket_cookie(struct bpf_sock_ops *ctx) * Description * Equivalent to **bpf_get_socket_cookie**\ () helper that accepts * *skb*, but gets socket from **struct bpf_sock_ops** context. * Return * A 8-byte long unique number. * * u64 bpf_get_socket_cookie(struct sock *sk) * Description * Equivalent to **bpf_get_socket_cookie**\ () helper that accepts * *sk*, but gets socket from a BTF **struct sock**. This helper * also works for sleepable programs. * Return * A 8-byte long unique number or 0 if *sk* is NULL. * * u32 bpf_get_socket_uid(struct sk_buff *skb) * Return * The owner UID of the socket associated to *skb*. If the socket * is **NULL**, or if it is not a full socket (i.e. if it is a * time-wait or a request socket instead), **overflowuid** value * is returned (note that **overflowuid** might also be the actual * UID value for the socket). * * long bpf_set_hash(struct sk_buff *skb, u32 hash) * Description * Set the full hash for *skb* (set the field *skb*\ **->hash**) * to value *hash*. * Return * 0 * * long bpf_setsockopt(void *bpf_socket, int level, int optname, void *optval, int optlen) * Description * Emulate a call to **setsockopt()** on the socket associated to * *bpf_socket*, which must be a full socket. The *level* at * which the option resides and the name *optname* of the option * must be specified, see **setsockopt(2)** for more information. * The option value of length *optlen* is pointed by *optval*. * * *bpf_socket* should be one of the following: * * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** * and **BPF_CGROUP_INET6_CONNECT**. * * This helper actually implements a subset of **setsockopt()**. * It supports the following *level*\ s: * * * **SOL_SOCKET**, which supports the following *optname*\ s: * **SO_RCVBUF**, **SO_SNDBUF**, **SO_MAX_PACING_RATE**, * **SO_PRIORITY**, **SO_RCVLOWAT**, **SO_MARK**, * **SO_BINDTODEVICE**, **SO_KEEPALIVE**. * * **IPPROTO_TCP**, which supports the following *optname*\ s: * **TCP_CONGESTION**, **TCP_BPF_IW**, * **TCP_BPF_SNDCWND_CLAMP**, **TCP_SAVE_SYN**, * **TCP_KEEPIDLE**, **TCP_KEEPINTVL**, **TCP_KEEPCNT**, * **TCP_SYNCNT**, **TCP_USER_TIMEOUT**, **TCP_NOTSENT_LOWAT**. * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_adjust_room(struct sk_buff *skb, s32 len_diff, u32 mode, u64 flags) * Description * Grow or shrink the room for data in the packet associated to * *skb* by *len_diff*, and according to the selected *mode*. * * By default, the helper will reset any offloaded checksum * indicator of the skb to CHECKSUM_NONE. This can be avoided * by the following flag: * * * **BPF_F_ADJ_ROOM_NO_CSUM_RESET**: Do not reset offloaded * checksum data of the skb to CHECKSUM_NONE. * * There are two supported modes at this time: * * * **BPF_ADJ_ROOM_MAC**: Adjust room at the mac layer * (room space is added or removed below the layer 2 header). * * * **BPF_ADJ_ROOM_NET**: Adjust room at the network layer * (room space is added or removed below the layer 3 header). * * The following flags are supported at this time: * * * **BPF_F_ADJ_ROOM_FIXED_GSO**: Do not adjust gso_size. * Adjusting mss in this way is not allowed for datagrams. * * * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV4**, * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV6**: * Any new space is reserved to hold a tunnel header. * Configure skb offsets and other fields accordingly. * * * **BPF_F_ADJ_ROOM_ENCAP_L4_GRE**, * **BPF_F_ADJ_ROOM_ENCAP_L4_UDP**: * Use with ENCAP_L3 flags to further specify the tunnel type. * * * **BPF_F_ADJ_ROOM_ENCAP_L2**\ (*len*): * Use with ENCAP_L3/L4 flags to further specify the tunnel * type; *len* is the length of the inner MAC header. * * * **BPF_F_ADJ_ROOM_ENCAP_L2_ETH**: * Use with BPF_F_ADJ_ROOM_ENCAP_L2 flag to further specify the * L2 type as Ethernet. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags) * Description * Redirect the packet to the endpoint referenced by *map* at * index *key*. Depending on its type, this *map* can contain * references to net devices (for forwarding packets through other * ports), or to CPUs (for redirecting XDP frames to another CPU; * but this is only implemented for native XDP (with driver * support) as of this writing). * * The lower two bits of *flags* are used as the return code if * the map lookup fails. This is so that the return value can be * one of the XDP program return codes up to **XDP_TX**, as chosen * by the caller. The higher bits of *flags* can be set to * BPF_F_BROADCAST or BPF_F_EXCLUDE_INGRESS as defined below. * * With BPF_F_BROADCAST the packet will be broadcasted to all the * interfaces in the map, with BPF_F_EXCLUDE_INGRESS the ingress * interface will be excluded when do broadcasting. * * See also **bpf_redirect**\ (), which only supports redirecting * to an ifindex, but doesn't require a map to do so. * Return * **XDP_REDIRECT** on success, or the value of the two lower bits * of the *flags* argument on error. * * long bpf_sk_redirect_map(struct sk_buff *skb, struct bpf_map *map, u32 key, u64 flags) * Description * Redirect the packet to the socket referenced by *map* (of type * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and * egress interfaces can be used for redirection. The * **BPF_F_INGRESS** value in *flags* is used to make the * distinction (ingress path is selected if the flag is present, * egress path otherwise). This is the only flag supported for now. * Return * **SK_PASS** on success, or **SK_DROP** on error. * * long bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) * Description * Add an entry to, or update a *map* referencing sockets. The * *skops* is used as a new value for the entry associated to * *key*. *flags* is one of: * * **BPF_NOEXIST** * The entry for *key* must not exist in the map. * **BPF_EXIST** * The entry for *key* must already exist in the map. * **BPF_ANY** * No condition on the existence of the entry for *key*. * * If the *map* has eBPF programs (parser and verdict), those will * be inherited by the socket being added. If the socket is * already attached to eBPF programs, this results in an error. * Return * 0 on success, or a negative error in case of failure. * * long bpf_xdp_adjust_meta(struct xdp_buff *xdp_md, int delta) * Description * Adjust the address pointed by *xdp_md*\ **->data_meta** by * *delta* (which can be positive or negative). Note that this * operation modifies the address stored in *xdp_md*\ **->data**, * so the latter must be loaded only after the helper has been * called. * * The use of *xdp_md*\ **->data_meta** is optional and programs * are not required to use it. The rationale is that when the * packet is processed with XDP (e.g. as DoS filter), it is * possible to push further meta data along with it before passing * to the stack, and to give the guarantee that an ingress eBPF * program attached as a TC classifier on the same device can pick * this up for further post-processing. Since TC works with socket * buffers, it remains possible to set from XDP the **mark** or * **priority** pointers, or other pointers for the socket buffer. * Having this scratch space generic and programmable allows for * more flexibility as the user is free to store whatever meta * data they need. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_perf_event_read_value(struct bpf_map *map, u64 flags, struct bpf_perf_event_value *buf, u32 buf_size) * Description * Read the value of a perf event counter, and store it into *buf* * of size *buf_size*. This helper relies on a *map* of type * **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of the perf event * counter is selected when *map* is updated with perf event file * descriptors. The *map* is an array whose size is the number of * available CPUs, and each cell contains a value relative to one * CPU. The value to retrieve is indicated by *flags*, that * contains the index of the CPU to look up, masked with * **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to * **BPF_F_CURRENT_CPU** to indicate that the value for the * current CPU should be retrieved. * * This helper behaves in a way close to * **bpf_perf_event_read**\ () helper, save that instead of * just returning the value observed, it fills the *buf* * structure. This allows for additional data to be retrieved: in * particular, the enabled and running times (in *buf*\ * **->enabled** and *buf*\ **->running**, respectively) are * copied. In general, **bpf_perf_event_read_value**\ () is * recommended over **bpf_perf_event_read**\ (), which has some * ABI issues and provides fewer functionalities. * * These values are interesting, because hardware PMU (Performance * Monitoring Unit) counters are limited resources. When there are * more PMU based perf events opened than available counters, * kernel will multiplex these events so each event gets certain * percentage (but not all) of the PMU time. In case that * multiplexing happens, the number of samples or counter value * will not reflect the case compared to when no multiplexing * occurs. This makes comparison between different runs difficult. * Typically, the counter value should be normalized before * comparing to other experiments. The usual normalization is done * as follows. * * :: * * normalized_counter = counter * t_enabled / t_running * * Where t_enabled is the time enabled for event and t_running is * the time running for event since last normalization. The * enabled and running times are accumulated since the perf event * open. To achieve scaling factor between two invocations of an * eBPF program, users can use CPU id as the key (which is * typical for perf array usage model) to remember the previous * value and do the calculation inside the eBPF program. * Return * 0 on success, or a negative error in case of failure. * * long bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct bpf_perf_event_value *buf, u32 buf_size) * Description * For en eBPF program attached to a perf event, retrieve the * value of the event counter associated to *ctx* and store it in * the structure pointed by *buf* and of size *buf_size*. Enabled * and running times are also stored in the structure (see * description of helper **bpf_perf_event_read_value**\ () for * more details). * Return * 0 on success, or a negative error in case of failure. * * long bpf_getsockopt(void *bpf_socket, int level, int optname, void *optval, int optlen) * Description * Emulate a call to **getsockopt()** on the socket associated to * *bpf_socket*, which must be a full socket. The *level* at * which the option resides and the name *optname* of the option * must be specified, see **getsockopt(2)** for more information. * The retrieved value is stored in the structure pointed by * *opval* and of length *optlen*. * * *bpf_socket* should be one of the following: * * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** * and **BPF_CGROUP_INET6_CONNECT**. * * This helper actually implements a subset of **getsockopt()**. * It supports the following *level*\ s: * * * **IPPROTO_TCP**, which supports *optname* * **TCP_CONGESTION**. * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. * Return * 0 on success, or a negative error in case of failure. * * long bpf_override_return(struct pt_regs *regs, u64 rc) * Description * Used for error injection, this helper uses kprobes to override * the return value of the probed function, and to set it to *rc*. * The first argument is the context *regs* on which the kprobe * works. * * This helper works by setting the PC (program counter) * to an override function which is run in place of the original * probed function. This means the probed function is not run at * all. The replacement function just returns with the required * value. * * This helper has security implications, and thus is subject to * restrictions. It is only available if the kernel was compiled * with the **CONFIG_BPF_KPROBE_OVERRIDE** configuration * option, and in this case it only works on functions tagged with * **ALLOW_ERROR_INJECTION** in the kernel code. * * Also, the helper is only available for the architectures having * the CONFIG_FUNCTION_ERROR_INJECTION option. As of this writing, * x86 architecture is the only one to support this feature. * Return * 0 * * long bpf_sock_ops_cb_flags_set(struct bpf_sock_ops *bpf_sock, int argval) * Description * Attempt to set the value of the **bpf_sock_ops_cb_flags** field * for the full TCP socket associated to *bpf_sock_ops* to * *argval*. * * The primary use of this field is to determine if there should * be calls to eBPF programs of type * **BPF_PROG_TYPE_SOCK_OPS** at various points in the TCP * code. A program of the same type can change its value, per * connection and as necessary, when the connection is * established. This field is directly accessible for reading, but * this helper must be used for updates in order to return an * error if an eBPF program tries to set a callback that is not * supported in the current kernel. * * *argval* is a flag array which can combine these flags: * * * **BPF_SOCK_OPS_RTO_CB_FLAG** (retransmission time out) * * **BPF_SOCK_OPS_RETRANS_CB_FLAG** (retransmission) * * **BPF_SOCK_OPS_STATE_CB_FLAG** (TCP state change) * * **BPF_SOCK_OPS_RTT_CB_FLAG** (every RTT) * * Therefore, this function can be used to clear a callback flag by * setting the appropriate bit to zero. e.g. to disable the RTO * callback: * * **bpf_sock_ops_cb_flags_set(bpf_sock,** * **bpf_sock->bpf_sock_ops_cb_flags & ~BPF_SOCK_OPS_RTO_CB_FLAG)** * * Here are some examples of where one could call such eBPF * program: * * * When RTO fires. * * When a packet is retransmitted. * * When the connection terminates. * * When a packet is sent. * * When a packet is received. * Return * Code **-EINVAL** if the socket is not a full TCP socket; * otherwise, a positive number containing the bits that could not * be set is returned (which comes down to 0 if all bits were set * as required). * * long bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, u32 key, u64 flags) * Description * This helper is used in programs implementing policies at the * socket level. If the message *msg* is allowed to pass (i.e. if * the verdict eBPF program returns **SK_PASS**), redirect it to * the socket referenced by *map* (of type * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and * egress interfaces can be used for redirection. The * **BPF_F_INGRESS** value in *flags* is used to make the * distinction (ingress path is selected if the flag is present, * egress path otherwise). This is the only flag supported for now. * Return * **SK_PASS** on success, or **SK_DROP** on error. * * long bpf_msg_apply_bytes(struct sk_msg_buff *msg, u32 bytes) * Description * For socket policies, apply the verdict of the eBPF program to * the next *bytes* (number of bytes) of message *msg*. * * For example, this helper can be used in the following cases: * * * A single **sendmsg**\ () or **sendfile**\ () system call * contains multiple logical messages that the eBPF program is * supposed to read and for which it should apply a verdict. * * An eBPF program only cares to read the first *bytes* of a * *msg*. If the message has a large payload, then setting up * and calling the eBPF program repeatedly for all bytes, even * though the verdict is already known, would create unnecessary * overhead. * * When called from within an eBPF program, the helper sets a * counter internal to the BPF infrastructure, that is used to * apply the last verdict to the next *bytes*. If *bytes* is * smaller than the current data being processed from a * **sendmsg**\ () or **sendfile**\ () system call, the first * *bytes* will be sent and the eBPF program will be re-run with * the pointer for start of data pointing to byte number *bytes* * **+ 1**. If *bytes* is larger than the current data being * processed, then the eBPF verdict will be applied to multiple * **sendmsg**\ () or **sendfile**\ () calls until *bytes* are * consumed. * * Note that if a socket closes with the internal counter holding * a non-zero value, this is not a problem because data is not * being buffered for *bytes* and is sent as it is received. * Return * 0 * * long bpf_msg_cork_bytes(struct sk_msg_buff *msg, u32 bytes) * Description * For socket policies, prevent the execution of the verdict eBPF * program for message *msg* until *bytes* (byte number) have been * accumulated. * * This can be used when one needs a specific number of bytes * before a verdict can be assigned, even if the data spans * multiple **sendmsg**\ () or **sendfile**\ () calls. The extreme * case would be a user calling **sendmsg**\ () repeatedly with * 1-byte long message segments. Obviously, this is bad for * performance, but it is still valid. If the eBPF program needs * *bytes* bytes to validate a header, this helper can be used to * prevent the eBPF program to be called again until *bytes* have * been accumulated. * Return * 0 * * long bpf_msg_pull_data(struct sk_msg_buff *msg, u32 start, u32 end, u64 flags) * Description * For socket policies, pull in non-linear data from user space * for *msg* and set pointers *msg*\ **->data** and *msg*\ * **->data_end** to *start* and *end* bytes offsets into *msg*, * respectively. * * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a * *msg* it can only parse data that the (**data**, **data_end**) * pointers have already consumed. For **sendmsg**\ () hooks this * is likely the first scatterlist element. But for calls relying * on the **sendpage** handler (e.g. **sendfile**\ ()) this will * be the range (**0**, **0**) because the data is shared with * user space and by default the objective is to avoid allowing * user space to modify data while (or after) eBPF verdict is * being decided. This helper can be used to pull in data and to * set the start and end pointer to given values. Data will be * copied if necessary (i.e. if data was not linear and if start * and end pointers do not point to the same chunk). * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * * All values for *flags* are reserved for future usage, and must * be left at zero. * Return * 0 on success, or a negative error in case of failure. * * long bpf_bind(struct bpf_sock_addr *ctx, struct sockaddr *addr, int addr_len) * Description * Bind the socket associated to *ctx* to the address pointed by * *addr*, of length *addr_len*. This allows for making outgoing * connection from the desired IP address, which can be useful for * example when all processes inside a cgroup should use one * single IP address on a host that has multiple IP configured. * * This helper works for IPv4 and IPv6, TCP and UDP sockets. The * domain (*addr*\ **->sa_family**) must be **AF_INET** (or * **AF_INET6**). It's advised to pass zero port (**sin_port** * or **sin6_port**) which triggers IP_BIND_ADDRESS_NO_PORT-like * behavior and lets the kernel efficiently pick up an unused * port as long as 4-tuple is unique. Passing non-zero port might * lead to degraded performance. * Return * 0 on success, or a negative error in case of failure. * * long bpf_xdp_adjust_tail(struct xdp_buff *xdp_md, int delta) * Description * Adjust (move) *xdp_md*\ **->data_end** by *delta* bytes. It is * possible to both shrink and grow the packet tail. * Shrink done via *delta* being a negative integer. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_skb_get_xfrm_state(struct sk_buff *skb, u32 index, struct bpf_xfrm_state *xfrm_state, u32 size, u64 flags) * Description * Retrieve the XFRM state (IP transform framework, see also * **ip-xfrm(8)**) at *index* in XFRM "security path" for *skb*. * * The retrieved value is stored in the **struct bpf_xfrm_state** * pointed by *xfrm_state* and of length *size*. * * All values for *flags* are reserved for future usage, and must * be left at zero. * * This helper is available only if the kernel was compiled with * **CONFIG_XFRM** configuration option. * Return * 0 on success, or a negative error in case of failure. * * long bpf_get_stack(void *ctx, void *buf, u32 size, u64 flags) * Description * Return a user or a kernel stack in bpf program provided buffer. * To achieve this, the helper needs *ctx*, which is a pointer * to the context on which the tracing program is executed. * To store the stacktrace, the bpf program provides *buf* with * a nonnegative *size*. * * The last argument, *flags*, holds the number of stack frames to * skip (from 0 to 255), masked with * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set * the following flags: * * **BPF_F_USER_STACK** * Collect a user space stack instead of a kernel stack. * **BPF_F_USER_BUILD_ID** * Collect buildid+offset instead of ips for user stack, * only valid if **BPF_F_USER_STACK** is also specified. * * **bpf_get_stack**\ () can collect up to * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject * to sufficient large buffer size. Note that * this limit can be controlled with the **sysctl** program, and * that it should be manually increased in order to profile long * user stacks (such as stacks for Java programs). To do so, use: * * :: * * # sysctl kernel.perf_event_max_stack= * Return * A non-negative value equal to or less than *size* on success, * or a negative error in case of failure. * * long bpf_skb_load_bytes_relative(const void *skb, u32 offset, void *to, u32 len, u32 start_header) * Description * This helper is similar to **bpf_skb_load_bytes**\ () in that * it provides an easy way to load *len* bytes from *offset* * from the packet associated to *skb*, into the buffer pointed * by *to*. The difference to **bpf_skb_load_bytes**\ () is that * a fifth argument *start_header* exists in order to select a * base offset to start from. *start_header* can be one of: * * **BPF_HDR_START_MAC** * Base offset to load data from is *skb*'s mac header. * **BPF_HDR_START_NET** * Base offset to load data from is *skb*'s network header. * * In general, "direct packet access" is the preferred method to * access packet data, however, this helper is in particular useful * in socket filters where *skb*\ **->data** does not always point * to the start of the mac header and where "direct packet access" * is not available. * Return * 0 on success, or a negative error in case of failure. * * long bpf_fib_lookup(void *ctx, struct bpf_fib_lookup *params, int plen, u32 flags) * Description * Do FIB lookup in kernel tables using parameters in *params*. * If lookup is successful and result shows packet is to be * forwarded, the neighbor tables are searched for the nexthop. * If successful (ie., FIB lookup shows forwarding and nexthop * is resolved), the nexthop address is returned in ipv4_dst * or ipv6_dst based on family, smac is set to mac address of * egress device, dmac is set to nexthop mac address, rt_metric * is set to metric from route (IPv4/IPv6 only), and ifindex * is set to the device index of the nexthop from the FIB lookup. * * *plen* argument is the size of the passed in struct. * *flags* argument can be a combination of one or more of the * following values: * * **BPF_FIB_LOOKUP_DIRECT** * Do a direct table lookup vs full lookup using FIB * rules. * **BPF_FIB_LOOKUP_OUTPUT** * Perform lookup from an egress perspective (default is * ingress). * * *ctx* is either **struct xdp_md** for XDP programs or * **struct sk_buff** tc cls_act programs. * Return * * < 0 if any input argument is invalid * * 0 on success (packet is forwarded, nexthop neighbor exists) * * > 0 one of **BPF_FIB_LKUP_RET_** codes explaining why the * packet is not forwarded or needs assist from full stack * * If lookup fails with BPF_FIB_LKUP_RET_FRAG_NEEDED, then the MTU * was exceeded and output params->mtu_result contains the MTU. * * long bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) * Description * Add an entry to, or update a sockhash *map* referencing sockets. * The *skops* is used as a new value for the entry associated to * *key*. *flags* is one of: * * **BPF_NOEXIST** * The entry for *key* must not exist in the map. * **BPF_EXIST** * The entry for *key* must already exist in the map. * **BPF_ANY** * No condition on the existence of the entry for *key*. * * If the *map* has eBPF programs (parser and verdict), those will * be inherited by the socket being added. If the socket is * already attached to eBPF programs, this results in an error. * Return * 0 on success, or a negative error in case of failure. * * long bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, u64 flags) * Description * This helper is used in programs implementing policies at the * socket level. If the message *msg* is allowed to pass (i.e. if * the verdict eBPF program returns **SK_PASS**), redirect it to * the socket referenced by *map* (of type * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and * egress interfaces can be used for redirection. The * **BPF_F_INGRESS** value in *flags* is used to make the * distinction (ingress path is selected if the flag is present, * egress path otherwise). This is the only flag supported for now. * Return * **SK_PASS** on success, or **SK_DROP** on error. * * long bpf_sk_redirect_hash(struct sk_buff *skb, struct bpf_map *map, void *key, u64 flags) * Description * This helper is used in programs implementing policies at the * skb socket level. If the sk_buff *skb* is allowed to pass (i.e. * if the verdict eBPF program returns **SK_PASS**), redirect it * to the socket referenced by *map* (of type * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and * egress interfaces can be used for redirection. The * **BPF_F_INGRESS** value in *flags* is used to make the * distinction (ingress path is selected if the flag is present, * egress otherwise). This is the only flag supported for now. * Return * **SK_PASS** on success, or **SK_DROP** on error. * * long bpf_lwt_push_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len) * Description * Encapsulate the packet associated to *skb* within a Layer 3 * protocol header. This header is provided in the buffer at * address *hdr*, with *len* its size in bytes. *type* indicates * the protocol of the header and can be one of: * * **BPF_LWT_ENCAP_SEG6** * IPv6 encapsulation with Segment Routing Header * (**struct ipv6_sr_hdr**). *hdr* only contains the SRH, * the IPv6 header is computed by the kernel. * **BPF_LWT_ENCAP_SEG6_INLINE** * Only works if *skb* contains an IPv6 packet. Insert a * Segment Routing Header (**struct ipv6_sr_hdr**) inside * the IPv6 header. * **BPF_LWT_ENCAP_IP** * IP encapsulation (GRE/GUE/IPIP/etc). The outer header * must be IPv4 or IPv6, followed by zero or more * additional headers, up to **LWT_BPF_MAX_HEADROOM** * total bytes in all prepended headers. Please note that * if **skb_is_gso**\ (*skb*) is true, no more than two * headers can be prepended, and the inner header, if * present, should be either GRE or UDP/GUE. * * **BPF_LWT_ENCAP_SEG6**\ \* types can be called by BPF programs * of type **BPF_PROG_TYPE_LWT_IN**; **BPF_LWT_ENCAP_IP** type can * be called by bpf programs of types **BPF_PROG_TYPE_LWT_IN** and * **BPF_PROG_TYPE_LWT_XMIT**. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_lwt_seg6_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len) * Description * Store *len* bytes from address *from* into the packet * associated to *skb*, at *offset*. Only the flags, tag and TLVs * inside the outermost IPv6 Segment Routing Header can be * modified through this helper. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_lwt_seg6_adjust_srh(struct sk_buff *skb, u32 offset, s32 delta) * Description * Adjust the size allocated to TLVs in the outermost IPv6 * Segment Routing Header contained in the packet associated to * *skb*, at position *offset* by *delta* bytes. Only offsets * after the segments are accepted. *delta* can be as well * positive (growing) as negative (shrinking). * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_lwt_seg6_action(struct sk_buff *skb, u32 action, void *param, u32 param_len) * Description * Apply an IPv6 Segment Routing action of type *action* to the * packet associated to *skb*. Each action takes a parameter * contained at address *param*, and of length *param_len* bytes. * *action* can be one of: * * **SEG6_LOCAL_ACTION_END_X** * End.X action: Endpoint with Layer-3 cross-connect. * Type of *param*: **struct in6_addr**. * **SEG6_LOCAL_ACTION_END_T** * End.T action: Endpoint with specific IPv6 table lookup. * Type of *param*: **int**. * **SEG6_LOCAL_ACTION_END_B6** * End.B6 action: Endpoint bound to an SRv6 policy. * Type of *param*: **struct ipv6_sr_hdr**. * **SEG6_LOCAL_ACTION_END_B6_ENCAP** * End.B6.Encap action: Endpoint bound to an SRv6 * encapsulation policy. * Type of *param*: **struct ipv6_sr_hdr**. * * A call to this helper is susceptible to change the underlying * packet buffer. Therefore, at load time, all checks on pointers * previously done by the verifier are invalidated and must be * performed again, if the helper is used in combination with * direct packet access. * Return * 0 on success, or a negative error in case of failure. * * long bpf_rc_repeat(void *ctx) * Description * This helper is used in programs implementing IR decoding, to * report a successfully decoded repeat key message. This delays * the generation of a key up event for previously generated * key down event. * * Some IR protocols like NEC have a special IR message for * repeating last button, for when a button is held down. * * The *ctx* should point to the lirc sample as passed into * the program. * * This helper is only available is the kernel was compiled with * the **CONFIG_BPF_LIRC_MODE2** configuration option set to * "**y**". * Return * 0 * * long bpf_rc_keydown(void *ctx, u32 protocol, u64 scancode, u32 toggle) * Description * This helper is used in programs implementing IR decoding, to * report a successfully decoded key press with *scancode*, * *toggle* value in the given *protocol*. The scancode will be * translated to a keycode using the rc keymap, and reported as * an input key down event. After a period a key up event is * generated. This period can be extended by calling either * **bpf_rc_keydown**\ () again with the same values, or calling * **bpf_rc_repeat**\ (). * * Some protocols include a toggle bit, in case the button was * released and pressed again between consecutive scancodes. * * The *ctx* should point to the lirc sample as passed into * the program. * * The *protocol* is the decoded protocol number (see * **enum rc_proto** for some predefined values). * * This helper is only available is the kernel was compiled with * the **CONFIG_BPF_LIRC_MODE2** configuration option set to * "**y**". * Return * 0 * * u64 bpf_skb_cgroup_id(struct sk_buff *skb) * Description * Return the cgroup v2 id of the socket associated with the *skb*. * This is roughly similar to the **bpf_get_cgroup_classid**\ () * helper for cgroup v1 by providing a tag resp. identifier that * can be matched on or used for map lookups e.g. to implement * policy. The cgroup v2 id of a given path in the hierarchy is * exposed in user space through the f_handle API in order to get * to the same 64-bit id. * * This helper can be used on TC egress path, but not on ingress, * and is available only if the kernel was compiled with the * **CONFIG_SOCK_CGROUP_DATA** configuration option. * Return * The id is returned or 0 in case the id could not be retrieved. * * u64 bpf_get_current_cgroup_id(void) * Return * A 64-bit integer containing the current cgroup id based * on the cgroup within which the current task is running. * * void *bpf_get_local_storage(void *map, u64 flags) * Description * Get the pointer to the local storage area. * The type and the size of the local storage is defined * by the *map* argument. * The *flags* meaning is specific for each map type, * and has to be 0 for cgroup local storage. * * Depending on the BPF program type, a local storage area * can be shared between multiple instances of the BPF program, * running simultaneously. * * A user should care about the synchronization by himself. * For example, by using the **BPF_ATOMIC** instructions to alter * the shared data. * Return * A pointer to the local storage area. * * long bpf_sk_select_reuseport(struct sk_reuseport_md *reuse, struct bpf_map *map, void *key, u64 flags) * Description * Select a **SO_REUSEPORT** socket from a * **BPF_MAP_TYPE_REUSEPORT_ARRAY** *map*. * It checks the selected socket is matching the incoming * request in the socket buffer. * Return * 0 on success, or a negative error in case of failure. * * u64 bpf_skb_ancestor_cgroup_id(struct sk_buff *skb, int ancestor_level) * Description * Return id of cgroup v2 that is ancestor of cgroup associated * with the *skb* at the *ancestor_level*. The root cgroup is at * *ancestor_level* zero and each step down the hierarchy * increments the level. If *ancestor_level* == level of cgroup * associated with *skb*, then return value will be same as that * of **bpf_skb_cgroup_id**\ (). * * The helper is useful to implement policies based on cgroups * that are upper in hierarchy than immediate cgroup associated * with *skb*. * * The format of returned id and helper limitations are same as in * **bpf_skb_cgroup_id**\ (). * Return * The id is returned or 0 in case the id could not be retrieved. * * struct bpf_sock *bpf_sk_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) * Description * Look for TCP socket matching *tuple*, optionally in a child * network namespace *netns*. The return value must be checked, * and if non-**NULL**, released via **bpf_sk_release**\ (). * * The *ctx* should point to the context of the program, such as * the skb or socket (depending on the hook in use). This is used * to determine the base network namespace for the lookup. * * *tuple_size* must be one of: * * **sizeof**\ (*tuple*\ **->ipv4**) * Look for an IPv4 socket. * **sizeof**\ (*tuple*\ **->ipv6**) * Look for an IPv6 socket. * * If the *netns* is a negative signed 32-bit integer, then the * socket lookup table in the netns associated with the *ctx* * will be used. For the TC hooks, this is the netns of the device * in the skb. For socket hooks, this is the netns of the socket. * If *netns* is any other signed 32-bit value greater than or * equal to zero then it specifies the ID of the netns relative to * the netns associated with the *ctx*. *netns* values beyond the * range of 32-bit integers are reserved for future use. * * All values for *flags* are reserved for future usage, and must * be left at zero. * * This helper is available only if the kernel was compiled with * **CONFIG_NET** configuration option. * Return * Pointer to **struct bpf_sock**, or **NULL** in case of failure. * For sockets with reuseport option, the **struct bpf_sock** * result is from *reuse*\ **->socks**\ [] using the hash of the * tuple. * * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) * Description * Look for UDP socket matching *tuple*, optionally in a child * network namespace *netns*. The return value must be checked, * and if non-**NULL**, released via **bpf_sk_release**\ (). * * The *ctx* should point to the context of the program, such as * the skb or socket (depending on the hook in use). This is used * to determine the base network namespace for the lookup. * * *tuple_size* must be one of: * * **sizeof**\ (*tuple*\ **->ipv4**) * Look for an IPv4 socket. * **sizeof**\ (*tuple*\ **->ipv6**) * Look for an IPv6 socket. * * If the *netns* is a negative signed 32-bit integer, then the * socket lookup table in the netns associated with the *ctx* * will be used. For the TC hooks, this is the netns of the device * in the skb. For socket hooks, this is the netns of the socket. * If *netns* is any other signed 32-bit value greater than or * equal to zero then it specifies the ID of the netns relative to * the netns associated with the *ctx*. *netns* values beyond the * range of 32-bit integers are reserved for future use. * * All values for *flags* are reserved for future usage, and must * be left at zero. * * This helper is available only if the kernel was compiled with * **CONFIG_NET** configuration option. * Return * Pointer to **struct bpf_sock**, or **NULL** in case of failure. * For sockets with reuseport option, the **struct bpf_sock** * result is from *reuse*\ **->socks**\ [] using the hash of the * tuple. * * long bpf_sk_release(void *sock) * Description * Release the reference held by *sock*. *sock* must be a * non-**NULL** pointer that was returned from * **bpf_sk_lookup_xxx**\ (). * Return * 0 on success, or a negative error in case of failure. * * long bpf_map_push_elem(struct bpf_map *map, const void *value, u64 flags) * Description * Push an element *value* in *map*. *flags* is one of: * * **BPF_EXIST** * If the queue/stack is full, the oldest element is * removed to make room for this. * Return * 0 on success, or a negative error in case of failure. * * long bpf_map_pop_elem(struct bpf_map *map, void *value) * Description * Pop an element from *map*. * Return * 0 on success, or a negative error in case of failure. * * long bpf_map_peek_elem(struct bpf_map *map, void *value) * Description * Get an element from *map* without removing it. * Return * 0 on success, or a negative error in case of failure. * * long bpf_msg_push_data(struct sk_msg_buff *msg, u32 start, u32 len, u64 flags) * Description * For socket policies, insert *len* bytes into *msg* at offset * *start*. * * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a * *msg* it may want to insert metadata or options into the *msg*. * This can later be read and used by any of the lower layer BPF * hooks. * * This helper may fail if under memory pressure (a malloc * fails) in these cases BPF programs will get an appropriate * error and BPF programs will need to handle them. * Return * 0 on success, or a negative error in case of failure. * * long bpf_msg_pop_data(struct sk_msg_buff *msg, u32 start, u32 len, u64 flags) * Description * Will remove *len* bytes from a *msg* starting at byte *start*. * This may result in **ENOMEM** errors under certain situations if * an allocation and copy are required due to a full ring buffer. * However, the helper will try to avoid doing the allocation * if possible. Other errors can occur if input parameters are * invalid either due to *start* byte not being valid part of *msg* * payload and/or *pop* value being to large. * Return * 0 on success, or a negative error in case of failure. * * long bpf_rc_pointer_rel(void *ctx, s32 rel_x, s32 rel_y) * Description * This helper is used in programs implementing IR decoding, to * report a successfully decoded pointer movement. * * The *ctx* should point to the lirc sample as passed into * the program. * * This helper is only available is the kernel was compiled with * the **CONFIG_BPF_LIRC_MODE2** configuration option set to * "**y**". * Return * 0 * * long bpf_spin_lock(struct bpf_spin_lock *lock) * Description * Acquire a spinlock represented by the pointer *lock*, which is * stored as part of a value of a map. Taking the lock allows to * safely update the rest of the fields in that value. The * spinlock can (and must) later be released with a call to * **bpf_spin_unlock**\ (\ *lock*\ ). * * Spinlocks in BPF programs come with a number of restrictions * and constraints: * * * **bpf_spin_lock** objects are only allowed inside maps of * types **BPF_MAP_TYPE_HASH** and **BPF_MAP_TYPE_ARRAY** (this * list could be extended in the future). * * BTF description of the map is mandatory. * * The BPF program can take ONE lock at a time, since taking two * or more could cause dead locks. * * Only one **struct bpf_spin_lock** is allowed per map element. * * When the lock is taken, calls (either BPF to BPF or helpers) * are not allowed. * * The **BPF_LD_ABS** and **BPF_LD_IND** instructions are not * allowed inside a spinlock-ed region. * * The BPF program MUST call **bpf_spin_unlock**\ () to release * the lock, on all execution paths, before it returns. * * The BPF program can access **struct bpf_spin_lock** only via * the **bpf_spin_lock**\ () and **bpf_spin_unlock**\ () * helpers. Loading or storing data into the **struct * bpf_spin_lock** *lock*\ **;** field of a map is not allowed. * * To use the **bpf_spin_lock**\ () helper, the BTF description * of the map value must be a struct and have **struct * bpf_spin_lock** *anyname*\ **;** field at the top level. * Nested lock inside another struct is not allowed. * * The **struct bpf_spin_lock** *lock* field in a map value must * be aligned on a multiple of 4 bytes in that value. * * Syscall with command **BPF_MAP_LOOKUP_ELEM** does not copy * the **bpf_spin_lock** field to user space. * * Syscall with command **BPF_MAP_UPDATE_ELEM**, or update from * a BPF program, do not update the **bpf_spin_lock** field. * * **bpf_spin_lock** cannot be on the stack or inside a * networking packet (it can only be inside of a map values). * * **bpf_spin_lock** is available to root only. * * Tracing programs and socket filter programs cannot use * **bpf_spin_lock**\ () due to insufficient preemption checks * (but this may change in the future). * * **bpf_spin_lock** is not allowed in inner maps of map-in-map. * Return * 0 * * long bpf_spin_unlock(struct bpf_spin_lock *lock) * Description * Release the *lock* previously locked by a call to * **bpf_spin_lock**\ (\ *lock*\ ). * Return * 0 * * struct bpf_sock *bpf_sk_fullsock(struct bpf_sock *sk) * Description * This helper gets a **struct bpf_sock** pointer such * that all the fields in this **bpf_sock** can be accessed. * Return * A **struct bpf_sock** pointer on success, or **NULL** in * case of failure. * * struct bpf_tcp_sock *bpf_tcp_sock(struct bpf_sock *sk) * Description * This helper gets a **struct bpf_tcp_sock** pointer from a * **struct bpf_sock** pointer. * Return * A **struct bpf_tcp_sock** pointer on success, or **NULL** in * case of failure. * * long bpf_skb_ecn_set_ce(struct sk_buff *skb) * Description * Set ECN (Explicit Congestion Notification) field of IP header * to **CE** (Congestion Encountered) if current value is **ECT** * (ECN Capable Transport). Otherwise, do nothing. Works with IPv6 * and IPv4. * Return * 1 if the **CE** flag is set (either by the current helper call * or because it was already present), 0 if it is not set. * * struct bpf_sock *bpf_get_listener_sock(struct bpf_sock *sk) * Description * Return a **struct bpf_sock** pointer in **TCP_LISTEN** state. * **bpf_sk_release**\ () is unnecessary and not allowed. * Return * A **struct bpf_sock** pointer on success, or **NULL** in * case of failure. * * struct bpf_sock *bpf_skc_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) * Description * Look for TCP socket matching *tuple*, optionally in a child * network namespace *netns*. The return value must be checked, * and if non-**NULL**, released via **bpf_sk_release**\ (). * * This function is identical to **bpf_sk_lookup_tcp**\ (), except * that it also returns timewait or request sockets. Use * **bpf_sk_fullsock**\ () or **bpf_tcp_sock**\ () to access the * full structure. * * This helper is available only if the kernel was compiled with * **CONFIG_NET** configuration option. * Return * Pointer to **struct bpf_sock**, or **NULL** in case of failure. * For sockets with reuseport option, the **struct bpf_sock** * result is from *reuse*\ **->socks**\ [] using the hash of the * tuple. * * long bpf_tcp_check_syncookie(void *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len) * Description * Check whether *iph* and *th* contain a valid SYN cookie ACK for * the listening socket in *sk*. * * *iph* points to the start of the IPv4 or IPv6 header, while * *iph_len* contains **sizeof**\ (**struct iphdr**) or * **sizeof**\ (**struct ip6hdr**). * * *th* points to the start of the TCP header, while *th_len* * contains **sizeof**\ (**struct tcphdr**). * Return * 0 if *iph* and *th* are a valid SYN cookie ACK, or a negative * error otherwise. * * long bpf_sysctl_get_name(struct bpf_sysctl *ctx, char *buf, size_t buf_len, u64 flags) * Description * Get name of sysctl in /proc/sys/ and copy it into provided by * program buffer *buf* of size *buf_len*. * * The buffer is always NUL terminated, unless it's zero-sized. * * If *flags* is zero, full name (e.g. "net/ipv4/tcp_mem") is * copied. Use **BPF_F_SYSCTL_BASE_NAME** flag to copy base name * only (e.g. "tcp_mem"). * Return * Number of character copied (not including the trailing NUL). * * **-E2BIG** if the buffer wasn't big enough (*buf* will contain * truncated name in this case). * * long bpf_sysctl_get_current_value(struct bpf_sysctl *ctx, char *buf, size_t buf_len) * Description * Get current value of sysctl as it is presented in /proc/sys * (incl. newline, etc), and copy it as a string into provided * by program buffer *buf* of size *buf_len*. * * The whole value is copied, no matter what file position user * space issued e.g. sys_read at. * * The buffer is always NUL terminated, unless it's zero-sized. * Return * Number of character copied (not including the trailing NUL). * * **-E2BIG** if the buffer wasn't big enough (*buf* will contain * truncated name in this case). * * **-EINVAL** if current value was unavailable, e.g. because * sysctl is uninitialized and read returns -EIO for it. * * long bpf_sysctl_get_new_value(struct bpf_sysctl *ctx, char *buf, size_t buf_len) * Description * Get new value being written by user space to sysctl (before * the actual write happens) and copy it as a string into * provided by program buffer *buf* of size *buf_len*. * * User space may write new value at file position > 0. * * The buffer is always NUL terminated, unless it's zero-sized. * Return * Number of character copied (not including the trailing NUL). * * **-E2BIG** if the buffer wasn't big enough (*buf* will contain * truncated name in this case). * * **-EINVAL** if sysctl is being read. * * long bpf_sysctl_set_new_value(struct bpf_sysctl *ctx, const char *buf, size_t buf_len) * Description * Override new value being written by user space to sysctl with * value provided by program in buffer *buf* of size *buf_len*. * * *buf* should contain a string in same form as provided by user * space on sysctl write. * * User space may write new value at file position > 0. To override * the whole sysctl value file position should be set to zero. * Return * 0 on success. * * **-E2BIG** if the *buf_len* is too big. * * **-EINVAL** if sysctl is being read. * * long bpf_strtol(const char *buf, size_t buf_len, u64 flags, long *res) * Description * Convert the initial part of the string from buffer *buf* of * size *buf_len* to a long integer according to the given base * and save the result in *res*. * * The string may begin with an arbitrary amount of white space * (as determined by **isspace**\ (3)) followed by a single * optional '**-**' sign. * * Five least significant bits of *flags* encode base, other bits * are currently unused. * * Base must be either 8, 10, 16 or 0 to detect it automatically * similar to user space **strtol**\ (3). * Return * Number of characters consumed on success. Must be positive but * no more than *buf_len*. * * **-EINVAL** if no valid digits were found or unsupported base * was provided. * * **-ERANGE** if resulting value was out of range. * * long bpf_strtoul(const char *buf, size_t buf_len, u64 flags, unsigned long *res) * Description * Convert the initial part of the string from buffer *buf* of * size *buf_len* to an unsigned long integer according to the * given base and save the result in *res*. * * The string may begin with an arbitrary amount of white space * (as determined by **isspace**\ (3)). * * Five least significant bits of *flags* encode base, other bits * are currently unused. * * Base must be either 8, 10, 16 or 0 to detect it automatically * similar to user space **strtoul**\ (3). * Return * Number of characters consumed on success. Must be positive but * no more than *buf_len*. * * **-EINVAL** if no valid digits were found or unsupported base * was provided. * * **-ERANGE** if resulting value was out of range. * * void *bpf_sk_storage_get(struct bpf_map *map, void *sk, void *value, u64 flags) * Description * Get a bpf-local-storage from a *sk*. * * Logically, it could be thought of getting the value from * a *map* with *sk* as the **key**. From this * perspective, the usage is not much different from * **bpf_map_lookup_elem**\ (*map*, **&**\ *sk*) except this * helper enforces the key must be a full socket and the map must * be a **BPF_MAP_TYPE_SK_STORAGE** also. * * Underneath, the value is stored locally at *sk* instead of * the *map*. The *map* is used as the bpf-local-storage * "type". The bpf-local-storage "type" (i.e. the *map*) is * searched against all bpf-local-storages residing at *sk*. * * *sk* is a kernel **struct sock** pointer for LSM program. * *sk* is a **struct bpf_sock** pointer for other program types. * * An optional *flags* (**BPF_SK_STORAGE_GET_F_CREATE**) can be * used such that a new bpf-local-storage will be * created if one does not exist. *value* can be used * together with **BPF_SK_STORAGE_GET_F_CREATE** to specify * the initial value of a bpf-local-storage. If *value* is * **NULL**, the new bpf-local-storage will be zero initialized. * Return * A bpf-local-storage pointer is returned on success. * * **NULL** if not found or there was an error in adding * a new bpf-local-storage. * * long bpf_sk_storage_delete(struct bpf_map *map, void *sk) * Description * Delete a bpf-local-storage from a *sk*. * Return * 0 on success. * * **-ENOENT** if the bpf-local-storage cannot be found. * **-EINVAL** if sk is not a fullsock (e.g. a request_sock). * * long bpf_send_signal(u32 sig) * Description * Send signal *sig* to the process of the current task. * The signal may be delivered to any of this process's threads. * Return * 0 on success or successfully queued. * * **-EBUSY** if work queue under nmi is full. * * **-EINVAL** if *sig* is invalid. * * **-EPERM** if no permission to send the *sig*. * * **-EAGAIN** if bpf program can try again. * * s64 bpf_tcp_gen_syncookie(void *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len) * Description * Try to issue a SYN cookie for the packet with corresponding * IP/TCP headers, *iph* and *th*, on the listening socket in *sk*. * * *iph* points to the start of the IPv4 or IPv6 header, while * *iph_len* contains **sizeof**\ (**struct iphdr**) or * **sizeof**\ (**struct ip6hdr**). * * *th* points to the start of the TCP header, while *th_len* * contains the length of the TCP header. * Return * On success, lower 32 bits hold the generated SYN cookie in * followed by 16 bits which hold the MSS value for that cookie, * and the top 16 bits are unused. * * On failure, the returned value is one of the following: * * **-EINVAL** SYN cookie cannot be issued due to error * * **-ENOENT** SYN cookie should not be issued (no SYN flood) * * **-EOPNOTSUPP** kernel configuration does not enable SYN cookies * * **-EPROTONOSUPPORT** IP packet version is not 4 or 6 * * long bpf_skb_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) * Description * Write raw *data* blob into a special BPF perf event held by * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf * event must have the following attributes: **PERF_SAMPLE_RAW** * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. * * The *flags* are used to indicate the index in *map* for which * the value must be put, masked with **BPF_F_INDEX_MASK**. * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** * to indicate that the index of the current CPU core should be * used. * * The value to write, of *size*, is passed through eBPF stack and * pointed by *data*. * * *ctx* is a pointer to in-kernel struct sk_buff. * * This helper is similar to **bpf_perf_event_output**\ () but * restricted to raw_tracepoint bpf programs. * Return * 0 on success, or a negative error in case of failure. * * long bpf_probe_read_user(void *dst, u32 size, const void *unsafe_ptr) * Description * Safely attempt to read *size* bytes from user space address * *unsafe_ptr* and store the data in *dst*. * Return * 0 on success, or a negative error in case of failure. * * long bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr) * Description * Safely attempt to read *size* bytes from kernel space address * *unsafe_ptr* and store the data in *dst*. * Return * 0 on success, or a negative error in case of failure. * * long bpf_probe_read_user_str(void *dst, u32 size, const void *unsafe_ptr) * Description * Copy a NUL terminated string from an unsafe user address * *unsafe_ptr* to *dst*. The *size* should include the * terminating NUL byte. In case the string length is smaller than * *size*, the target is not padded with further NUL bytes. If the * string length is larger than *size*, just *size*-1 bytes are * copied and the last byte is set to NUL. * * On success, returns the number of bytes that were written, * including the terminal NUL. This makes this helper useful in * tracing programs for reading strings, and more importantly to * get its length at runtime. See the following snippet: * * :: * * SEC("kprobe/sys_open") * void bpf_sys_open(struct pt_regs *ctx) * { * char buf[PATHLEN]; // PATHLEN is defined to 256 * int res = bpf_probe_read_user_str(buf, sizeof(buf), * ctx->di); * * // Consume buf, for example push it to * // userspace via bpf_perf_event_output(); we * // can use res (the string length) as event * // size, after checking its boundaries. * } * * In comparison, using **bpf_probe_read_user**\ () helper here * instead to read the string would require to estimate the length * at compile time, and would often result in copying more memory * than necessary. * * Another useful use case is when parsing individual process * arguments or individual environment variables navigating * *current*\ **->mm->arg_start** and *current*\ * **->mm->env_start**: using this helper and the return value, * one can quickly iterate at the right offset of the memory area. * Return * On success, the strictly positive length of the output string, * including the trailing NUL character. On error, a negative * value. * * long bpf_probe_read_kernel_str(void *dst, u32 size, const void *unsafe_ptr) * Description * Copy a NUL terminated string from an unsafe kernel address *unsafe_ptr* * to *dst*. Same semantics as with **bpf_probe_read_user_str**\ () apply. * Return * On success, the strictly positive length of the string, including * the trailing NUL character. On error, a negative value. * * long bpf_tcp_send_ack(void *tp, u32 rcv_nxt) * Description * Send out a tcp-ack. *tp* is the in-kernel struct **tcp_sock**. * *rcv_nxt* is the ack_seq to be sent out. * Return * 0 on success, or a negative error in case of failure. * * long bpf_send_signal_thread(u32 sig) * Description * Send signal *sig* to the thread corresponding to the current task. * Return * 0 on success or successfully queued. * * **-EBUSY** if work queue under nmi is full. * * **-EINVAL** if *sig* is invalid. * * **-EPERM** if no permission to send the *sig*. * * **-EAGAIN** if bpf program can try again. * * u64 bpf_jiffies64(void) * Description * Obtain the 64bit jiffies * Return * The 64 bit jiffies * * long bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags) * Description * For an eBPF program attached to a perf event, retrieve the * branch records (**struct perf_branch_entry**) associated to *ctx* * and store it in the buffer pointed by *buf* up to size * *size* bytes. * Return * On success, number of bytes written to *buf*. On error, a * negative value. * * The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to * instead return the number of bytes required to store all the * branch entries. If this flag is set, *buf* may be NULL. * * **-EINVAL** if arguments invalid or **size** not a multiple * of **sizeof**\ (**struct perf_branch_entry**\ ). * * **-ENOENT** if architecture does not support branch records. * * long bpf_get_ns_current_pid_tgid(u64 dev, u64 ino, struct bpf_pidns_info *nsdata, u32 size) * Description * Returns 0 on success, values for *pid* and *tgid* as seen from the current * *namespace* will be returned in *nsdata*. * Return * 0 on success, or one of the following in case of failure: * * **-EINVAL** if dev and inum supplied don't match dev_t and inode number * with nsfs of current task, or if dev conversion to dev_t lost high bits. * * **-ENOENT** if pidns does not exists for the current task. * * long bpf_xdp_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) * Description * Write raw *data* blob into a special BPF perf event held by * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf * event must have the following attributes: **PERF_SAMPLE_RAW** * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. * * The *flags* are used to indicate the index in *map* for which * the value must be put, masked with **BPF_F_INDEX_MASK**. * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** * to indicate that the index of the current CPU core should be * used. * * The value to write, of *size*, is passed through eBPF stack and * pointed by *data*. * * *ctx* is a pointer to in-kernel struct xdp_buff. * * This helper is similar to **bpf_perf_eventoutput**\ () but * restricted to raw_tracepoint bpf programs. * Return * 0 on success, or a negative error in case of failure. * * u64 bpf_get_netns_cookie(void *ctx) * Description * Retrieve the cookie (generated by the kernel) of the network * namespace the input *ctx* is associated with. The network * namespace cookie remains stable for its lifetime and provides * a global identifier that can be assumed unique. If *ctx* is * NULL, then the helper returns the cookie for the initial * network namespace. The cookie itself is very similar to that * of **bpf_get_socket_cookie**\ () helper, but for network * namespaces instead of sockets. * Return * A 8-byte long opaque number. * * u64 bpf_get_current_ancestor_cgroup_id(int ancestor_level) * Description * Return id of cgroup v2 that is ancestor of the cgroup associated * with the current task at the *ancestor_level*. The root cgroup * is at *ancestor_level* zero and each step down the hierarchy * increments the level. If *ancestor_level* == level of cgroup * associated with the current task, then return value will be the * same as that of **bpf_get_current_cgroup_id**\ (). * * The helper is useful to implement policies based on cgroups * that are upper in hierarchy than immediate cgroup associated * with the current task. * * The format of returned id and helper limitations are same as in * **bpf_get_current_cgroup_id**\ (). * Return * The id is returned or 0 in case the id could not be retrieved. * * long bpf_sk_assign(struct sk_buff *skb, void *sk, u64 flags) * Description * Helper is overloaded depending on BPF program type. This * description applies to **BPF_PROG_TYPE_SCHED_CLS** and * **BPF_PROG_TYPE_SCHED_ACT** programs. * * Assign the *sk* to the *skb*. When combined with appropriate * routing configuration to receive the packet towards the socket, * will cause *skb* to be delivered to the specified socket. * Subsequent redirection of *skb* via **bpf_redirect**\ (), * **bpf_clone_redirect**\ () or other methods outside of BPF may * interfere with successful delivery to the socket. * * This operation is only valid from TC ingress path. * * The *flags* argument must be zero. * Return * 0 on success, or a negative error in case of failure: * * **-EINVAL** if specified *flags* are not supported. * * **-ENOENT** if the socket is unavailable for assignment. * * **-ENETUNREACH** if the socket is unreachable (wrong netns). * * **-EOPNOTSUPP** if the operation is not supported, for example * a call from outside of TC ingress. * * **-ESOCKTNOSUPPORT** if the socket type is not supported * (reuseport). * * long bpf_sk_assign(struct bpf_sk_lookup *ctx, struct bpf_sock *sk, u64 flags) * Description * Helper is overloaded depending on BPF program type. This * description applies to **BPF_PROG_TYPE_SK_LOOKUP** programs. * * Select the *sk* as a result of a socket lookup. * * For the operation to succeed passed socket must be compatible * with the packet description provided by the *ctx* object. * * L4 protocol (**IPPROTO_TCP** or **IPPROTO_UDP**) must * be an exact match. While IP family (**AF_INET** or * **AF_INET6**) must be compatible, that is IPv6 sockets * that are not v6-only can be selected for IPv4 packets. * * Only TCP listeners and UDP unconnected sockets can be * selected. *sk* can also be NULL to reset any previous * selection. * * *flags* argument can combination of following values: * * * **BPF_SK_LOOKUP_F_REPLACE** to override the previous * socket selection, potentially done by a BPF program * that ran before us. * * * **BPF_SK_LOOKUP_F_NO_REUSEPORT** to skip * load-balancing within reuseport group for the socket * being selected. * * On success *ctx->sk* will point to the selected socket. * * Return * 0 on success, or a negative errno in case of failure. * * * **-EAFNOSUPPORT** if socket family (*sk->family*) is * not compatible with packet family (*ctx->family*). * * * **-EEXIST** if socket has been already selected, * potentially by another program, and * **BPF_SK_LOOKUP_F_REPLACE** flag was not specified. * * * **-EINVAL** if unsupported flags were specified. * * * **-EPROTOTYPE** if socket L4 protocol * (*sk->protocol*) doesn't match packet protocol * (*ctx->protocol*). * * * **-ESOCKTNOSUPPORT** if socket is not in allowed * state (TCP listening or UDP unconnected). * * u64 bpf_ktime_get_boot_ns(void) * Description * Return the time elapsed since system boot, in nanoseconds. * Does include the time the system was suspended. * See: **clock_gettime**\ (**CLOCK_BOOTTIME**) * Return * Current *ktime*. * * long bpf_seq_printf(struct seq_file *m, const char *fmt, u32 fmt_size, const void *data, u32 data_len) * Description * **bpf_seq_printf**\ () uses seq_file **seq_printf**\ () to print * out the format string. * The *m* represents the seq_file. The *fmt* and *fmt_size* are for * the format string itself. The *data* and *data_len* are format string * arguments. The *data* are a **u64** array and corresponding format string * values are stored in the array. For strings and pointers where pointees * are accessed, only the pointer values are stored in the *data* array. * The *data_len* is the size of *data* in bytes. * * Formats **%s**, **%p{i,I}{4,6}** requires to read kernel memory. * Reading kernel memory may fail due to either invalid address or * valid address but requiring a major memory fault. If reading kernel memory * fails, the string for **%s** will be an empty string, and the ip * address for **%p{i,I}{4,6}** will be 0. Not returning error to * bpf program is consistent with what **bpf_trace_printk**\ () does for now. * Return * 0 on success, or a negative error in case of failure: * * **-EBUSY** if per-CPU memory copy buffer is busy, can try again * by returning 1 from bpf program. * * **-EINVAL** if arguments are invalid, or if *fmt* is invalid/unsupported. * * **-E2BIG** if *fmt* contains too many format specifiers. * * **-EOVERFLOW** if an overflow happened: The same object will be tried again. * * long bpf_seq_write(struct seq_file *m, const void *data, u32 len) * Description * **bpf_seq_write**\ () uses seq_file **seq_write**\ () to write the data. * The *m* represents the seq_file. The *data* and *len* represent the * data to write in bytes. * Return * 0 on success, or a negative error in case of failure: * * **-EOVERFLOW** if an overflow happened: The same object will be tried again. * * u64 bpf_sk_cgroup_id(void *sk) * Description * Return the cgroup v2 id of the socket *sk*. * * *sk* must be a non-**NULL** pointer to a socket, e.g. one * returned from **bpf_sk_lookup_xxx**\ (), * **bpf_sk_fullsock**\ (), etc. The format of returned id is * same as in **bpf_skb_cgroup_id**\ (). * * This helper is available only if the kernel was compiled with * the **CONFIG_SOCK_CGROUP_DATA** configuration option. * Return * The id is returned or 0 in case the id could not be retrieved. * * u64 bpf_sk_ancestor_cgroup_id(void *sk, int ancestor_level) * Description * Return id of cgroup v2 that is ancestor of cgroup associated * with the *sk* at the *ancestor_level*. The root cgroup is at * *ancestor_level* zero and each step down the hierarchy * increments the level. If *ancestor_level* == level of cgroup * associated with *sk*, then return value will be same as that * of **bpf_sk_cgroup_id**\ (). * * The helper is useful to implement policies based on cgroups * that are upper in hierarchy than immediate cgroup associated * with *sk*. * * The format of returned id and helper limitations are same as in * **bpf_sk_cgroup_id**\ (). * Return * The id is returned or 0 in case the id could not be retrieved. * * long bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags) * Description * Copy *size* bytes from *data* into a ring buffer *ringbuf*. * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification * of new data availability is sent. * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification * of new data availability is sent unconditionally. * If **0** is specified in *flags*, an adaptive notification * of new data availability is sent. * * An adaptive notification is a notification sent whenever the user-space * process has caught up and consumed all available payloads. In case the user-space * process is still processing a previous payload, then no notification is needed * as it will process the newly added payload automatically. * Return * 0 on success, or a negative error in case of failure. * * void *bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags) * Description * Reserve *size* bytes of payload in a ring buffer *ringbuf*. * *flags* must be 0. * Return * Valid pointer with *size* bytes of memory available; NULL, * otherwise. * * void bpf_ringbuf_submit(void *data, u64 flags) * Description * Submit reserved ring buffer sample, pointed to by *data*. * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification * of new data availability is sent. * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification * of new data availability is sent unconditionally. * If **0** is specified in *flags*, an adaptive notification * of new data availability is sent. * * See 'bpf_ringbuf_output()' for the definition of adaptive notification. * Return * Nothing. Always succeeds. * * void bpf_ringbuf_discard(void *data, u64 flags) * Description * Discard reserved ring buffer sample, pointed to by *data*. * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification * of new data availability is sent. * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification * of new data availability is sent unconditionally. * If **0** is specified in *flags*, an adaptive notification * of new data availability is sent. * * See 'bpf_ringbuf_output()' for the definition of adaptive notification. * Return * Nothing. Always succeeds. * * u64 bpf_ringbuf_query(void *ringbuf, u64 flags) * Description * Query various characteristics of provided ring buffer. What * exactly is queries is determined by *flags*: * * * **BPF_RB_AVAIL_DATA**: Amount of data not yet consumed. * * **BPF_RB_RING_SIZE**: The size of ring buffer. * * **BPF_RB_CONS_POS**: Consumer position (can wrap around). * * **BPF_RB_PROD_POS**: Producer(s) position (can wrap around). * * Data returned is just a momentary snapshot of actual values * and could be inaccurate, so this facility should be used to * power heuristics and for reporting, not to make 100% correct * calculation. * Return * Requested value, or 0, if *flags* are not recognized. * * long bpf_csum_level(struct sk_buff *skb, u64 level) * Description * Change the skbs checksum level by one layer up or down, or * reset it entirely to none in order to have the stack perform * checksum validation. The level is applicable to the following * protocols: TCP, UDP, GRE, SCTP, FCOE. For example, a decap of * | ETH | IP | UDP | GUE | IP | TCP | into | ETH | IP | TCP | * through **bpf_skb_adjust_room**\ () helper with passing in * **BPF_F_ADJ_ROOM_NO_CSUM_RESET** flag would require one call * to **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_DEC** since * the UDP header is removed. Similarly, an encap of the latter * into the former could be accompanied by a helper call to * **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_INC** if the * skb is still intended to be processed in higher layers of the * stack instead of just egressing at tc. * * There are three supported level settings at this time: * * * **BPF_CSUM_LEVEL_INC**: Increases skb->csum_level for skbs * with CHECKSUM_UNNECESSARY. * * **BPF_CSUM_LEVEL_DEC**: Decreases skb->csum_level for skbs * with CHECKSUM_UNNECESSARY. * * **BPF_CSUM_LEVEL_RESET**: Resets skb->csum_level to 0 and * sets CHECKSUM_NONE to force checksum validation by the stack. * * **BPF_CSUM_LEVEL_QUERY**: No-op, returns the current * skb->csum_level. * Return * 0 on success, or a negative error in case of failure. In the * case of **BPF_CSUM_LEVEL_QUERY**, the current skb->csum_level * is returned or the error code -EACCES in case the skb is not * subject to CHECKSUM_UNNECESSARY. * * struct tcp6_sock *bpf_skc_to_tcp6_sock(void *sk) * Description * Dynamically cast a *sk* pointer to a *tcp6_sock* pointer. * Return * *sk* if casting is valid, or **NULL** otherwise. * * struct tcp_sock *bpf_skc_to_tcp_sock(void *sk) * Description * Dynamically cast a *sk* pointer to a *tcp_sock* pointer. * Return * *sk* if casting is valid, or **NULL** otherwise. * * struct tcp_timewait_sock *bpf_skc_to_tcp_timewait_sock(void *sk) * Description * Dynamically cast a *sk* pointer to a *tcp_timewait_sock* pointer. * Return * *sk* if casting is valid, or **NULL** otherwise. * * struct tcp_request_sock *bpf_skc_to_tcp_request_sock(void *sk) * Description * Dynamically cast a *sk* pointer to a *tcp_request_sock* pointer. * Return * *sk* if casting is valid, or **NULL** otherwise. * * struct udp6_sock *bpf_skc_to_udp6_sock(void *sk) * Description * Dynamically cast a *sk* pointer to a *udp6_sock* pointer. * Return * *sk* if casting is valid, or **NULL** otherwise. * * long bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, u64 flags) * Description * Return a user or a kernel stack in bpf program provided buffer. * To achieve this, the helper needs *task*, which is a valid * pointer to **struct task_struct**. To store the stacktrace, the * bpf program provides *buf* with a nonnegative *size*. * * The last argument, *flags*, holds the number of stack frames to * skip (from 0 to 255), masked with * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set * the following flags: * * **BPF_F_USER_STACK** * Collect a user space stack instead of a kernel stack. * **BPF_F_USER_BUILD_ID** * Collect buildid+offset instead of ips for user stack, * only valid if **BPF_F_USER_STACK** is also specified. * * **bpf_get_task_stack**\ () can collect up to * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject * to sufficient large buffer size. Note that * this limit can be controlled with the **sysctl** program, and * that it should be manually increased in order to profile long * user stacks (such as stacks for Java programs). To do so, use: * * :: * * # sysctl kernel.perf_event_max_stack= * Return * A non-negative value equal to or less than *size* on success, * or a negative error in case of failure. * * long bpf_load_hdr_opt(struct bpf_sock_ops *skops, void *searchby_res, u32 len, u64 flags) * Description * Load header option. Support reading a particular TCP header * option for bpf program (**BPF_PROG_TYPE_SOCK_OPS**). * * If *flags* is 0, it will search the option from the * *skops*\ **->skb_data**. The comment in **struct bpf_sock_ops** * has details on what skb_data contains under different * *skops*\ **->op**. * * The first byte of the *searchby_res* specifies the * kind that it wants to search. * * If the searching kind is an experimental kind * (i.e. 253 or 254 according to RFC6994). It also * needs to specify the "magic" which is either * 2 bytes or 4 bytes. It then also needs to * specify the size of the magic by using * the 2nd byte which is "kind-length" of a TCP * header option and the "kind-length" also * includes the first 2 bytes "kind" and "kind-length" * itself as a normal TCP header option also does. * * For example, to search experimental kind 254 with * 2 byte magic 0xeB9F, the searchby_res should be * [ 254, 4, 0xeB, 0x9F, 0, 0, .... 0 ]. * * To search for the standard window scale option (3), * the *searchby_res* should be [ 3, 0, 0, .... 0 ]. * Note, kind-length must be 0 for regular option. * * Searching for No-Op (0) and End-of-Option-List (1) are * not supported. * * *len* must be at least 2 bytes which is the minimal size * of a header option. * * Supported flags: * * * **BPF_LOAD_HDR_OPT_TCP_SYN** to search from the * saved_syn packet or the just-received syn packet. * * Return * > 0 when found, the header option is copied to *searchby_res*. * The return value is the total length copied. On failure, a * negative error code is returned: * * **-EINVAL** if a parameter is invalid. * * **-ENOMSG** if the option is not found. * * **-ENOENT** if no syn packet is available when * **BPF_LOAD_HDR_OPT_TCP_SYN** is used. * * **-ENOSPC** if there is not enough space. Only *len* number of * bytes are copied. * * **-EFAULT** on failure to parse the header options in the * packet. * * **-EPERM** if the helper cannot be used under the current * *skops*\ **->op**. * * long bpf_store_hdr_opt(struct bpf_sock_ops *skops, const void *from, u32 len, u64 flags) * Description * Store header option. The data will be copied * from buffer *from* with length *len* to the TCP header. * * The buffer *from* should have the whole option that * includes the kind, kind-length, and the actual * option data. The *len* must be at least kind-length * long. The kind-length does not have to be 4 byte * aligned. The kernel will take care of the padding * and setting the 4 bytes aligned value to th->doff. * * This helper will check for duplicated option * by searching the same option in the outgoing skb. * * This helper can only be called during * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. * * Return * 0 on success, or negative error in case of failure: * * **-EINVAL** If param is invalid. * * **-ENOSPC** if there is not enough space in the header. * Nothing has been written * * **-EEXIST** if the option already exists. * * **-EFAULT** on failrue to parse the existing header options. * * **-EPERM** if the helper cannot be used under the current * *skops*\ **->op**. * * long bpf_reserve_hdr_opt(struct bpf_sock_ops *skops, u32 len, u64 flags) * Description * Reserve *len* bytes for the bpf header option. The * space will be used by **bpf_store_hdr_opt**\ () later in * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. * * If **bpf_reserve_hdr_opt**\ () is called multiple times, * the total number of bytes will be reserved. * * This helper can only be called during * **BPF_SOCK_OPS_HDR_OPT_LEN_CB**. * * Return * 0 on success, or negative error in case of failure: * * **-EINVAL** if a parameter is invalid. * * **-ENOSPC** if there is not enough space in the header. * * **-EPERM** if the helper cannot be used under the current * *skops*\ **->op**. * * void *bpf_inode_storage_get(struct bpf_map *map, void *inode, void *value, u64 flags) * Description * Get a bpf_local_storage from an *inode*. * * Logically, it could be thought of as getting the value from * a *map* with *inode* as the **key**. From this * perspective, the usage is not much different from * **bpf_map_lookup_elem**\ (*map*, **&**\ *inode*) except this * helper enforces the key must be an inode and the map must also * be a **BPF_MAP_TYPE_INODE_STORAGE**. * * Underneath, the value is stored locally at *inode* instead of * the *map*. The *map* is used as the bpf-local-storage * "type". The bpf-local-storage "type" (i.e. the *map*) is * searched against all bpf_local_storage residing at *inode*. * * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be * used such that a new bpf_local_storage will be * created if one does not exist. *value* can be used * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify * the initial value of a bpf_local_storage. If *value* is * **NULL**, the new bpf_local_storage will be zero initialized. * Return * A bpf_local_storage pointer is returned on success. * * **NULL** if not found or there was an error in adding * a new bpf_local_storage. * * int bpf_inode_storage_delete(struct bpf_map *map, void *inode) * Description * Delete a bpf_local_storage from an *inode*. * Return * 0 on success. * * **-ENOENT** if the bpf_local_storage cannot be found. * * long bpf_d_path(struct path *path, char *buf, u32 sz) * Description * Return full path for given **struct path** object, which * needs to be the kernel BTF *path* object. The path is * returned in the provided buffer *buf* of size *sz* and * is zero terminated. * * Return * On success, the strictly positive length of the string, * including the trailing NUL character. On error, a negative * value. * * long bpf_copy_from_user(void *dst, u32 size, const void *user_ptr) * Description * Read *size* bytes from user space address *user_ptr* and store * the data in *dst*. This is a wrapper of **copy_from_user**\ (). * Return * 0 on success, or a negative error in case of failure. * * long bpf_snprintf_btf(char *str, u32 str_size, struct btf_ptr *ptr, u32 btf_ptr_size, u64 flags) * Description * Use BTF to store a string representation of *ptr*->ptr in *str*, * using *ptr*->type_id. This value should specify the type * that *ptr*->ptr points to. LLVM __builtin_btf_type_id(type, 1) * can be used to look up vmlinux BTF type ids. Traversing the * data structure using BTF, the type information and values are * stored in the first *str_size* - 1 bytes of *str*. Safe copy of * the pointer data is carried out to avoid kernel crashes during * operation. Smaller types can use string space on the stack; * larger programs can use map data to store the string * representation. * * The string can be subsequently shared with userspace via * bpf_perf_event_output() or ring buffer interfaces. * bpf_trace_printk() is to be avoided as it places too small * a limit on string size to be useful. * * *flags* is a combination of * * **BTF_F_COMPACT** * no formatting around type information * **BTF_F_NONAME** * no struct/union member names/types * **BTF_F_PTR_RAW** * show raw (unobfuscated) pointer values; * equivalent to printk specifier %px. * **BTF_F_ZERO** * show zero-valued struct/union members; they * are not displayed by default * * Return * The number of bytes that were written (or would have been * written if output had to be truncated due to string size), * or a negative error in cases of failure. * * long bpf_seq_printf_btf(struct seq_file *m, struct btf_ptr *ptr, u32 ptr_size, u64 flags) * Description * Use BTF to write to seq_write a string representation of * *ptr*->ptr, using *ptr*->type_id as per bpf_snprintf_btf(). * *flags* are identical to those used for bpf_snprintf_btf. * Return * 0 on success or a negative error in case of failure. * * u64 bpf_skb_cgroup_classid(struct sk_buff *skb) * Description * See **bpf_get_cgroup_classid**\ () for the main description. * This helper differs from **bpf_get_cgroup_classid**\ () in that * the cgroup v1 net_cls class is retrieved only from the *skb*'s * associated socket instead of the current process. * Return * The id is returned or 0 in case the id could not be retrieved. * * long bpf_redirect_neigh(u32 ifindex, struct bpf_redir_neigh *params, int plen, u64 flags) * Description * Redirect the packet to another net device of index *ifindex* * and fill in L2 addresses from neighboring subsystem. This helper * is somewhat similar to **bpf_redirect**\ (), except that it * populates L2 addresses as well, meaning, internally, the helper * relies on the neighbor lookup for the L2 address of the nexthop. * * The helper will perform a FIB lookup based on the skb's * networking header to get the address of the next hop, unless * this is supplied by the caller in the *params* argument. The * *plen* argument indicates the len of *params* and should be set * to 0 if *params* is NULL. * * The *flags* argument is reserved and must be 0. The helper is * currently only supported for tc BPF program types, and enabled * for IPv4 and IPv6 protocols. * Return * The helper returns **TC_ACT_REDIRECT** on success or * **TC_ACT_SHOT** on error. * * void *bpf_per_cpu_ptr(const void *percpu_ptr, u32 cpu) * Description * Take a pointer to a percpu ksym, *percpu_ptr*, and return a * pointer to the percpu kernel variable on *cpu*. A ksym is an * extern variable decorated with '__ksym'. For ksym, there is a * global var (either static or global) defined of the same name * in the kernel. The ksym is percpu if the global var is percpu. * The returned pointer points to the global percpu var on *cpu*. * * bpf_per_cpu_ptr() has the same semantic as per_cpu_ptr() in the * kernel, except that bpf_per_cpu_ptr() may return NULL. This * happens if *cpu* is larger than nr_cpu_ids. The caller of * bpf_per_cpu_ptr() must check the returned value. * Return * A pointer pointing to the kernel percpu variable on *cpu*, or * NULL, if *cpu* is invalid. * * void *bpf_this_cpu_ptr(const void *percpu_ptr) * Description * Take a pointer to a percpu ksym, *percpu_ptr*, and return a * pointer to the percpu kernel variable on this cpu. See the * description of 'ksym' in **bpf_per_cpu_ptr**\ (). * * bpf_this_cpu_ptr() has the same semantic as this_cpu_ptr() in * the kernel. Different from **bpf_per_cpu_ptr**\ (), it would * never return NULL. * Return * A pointer pointing to the kernel percpu variable on this cpu. * * long bpf_redirect_peer(u32 ifindex, u64 flags) * Description * Redirect the packet to another net device of index *ifindex*. * This helper is somewhat similar to **bpf_redirect**\ (), except * that the redirection happens to the *ifindex*' peer device and * the netns switch takes place from ingress to ingress without * going through the CPU's backlog queue. * * The *flags* argument is reserved and must be 0. The helper is * currently only supported for tc BPF program types at the ingress * hook and for veth device types. The peer device must reside in a * different network namespace. * Return * The helper returns **TC_ACT_REDIRECT** on success or * **TC_ACT_SHOT** on error. * * void *bpf_task_storage_get(struct bpf_map *map, struct task_struct *task, void *value, u64 flags) * Description * Get a bpf_local_storage from the *task*. * * Logically, it could be thought of as getting the value from * a *map* with *task* as the **key**. From this * perspective, the usage is not much different from * **bpf_map_lookup_elem**\ (*map*, **&**\ *task*) except this * helper enforces the key must be an task_struct and the map must also * be a **BPF_MAP_TYPE_TASK_STORAGE**. * * Underneath, the value is stored locally at *task* instead of * the *map*. The *map* is used as the bpf-local-storage * "type". The bpf-local-storage "type" (i.e. the *map*) is * searched against all bpf_local_storage residing at *task*. * * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be * used such that a new bpf_local_storage will be * created if one does not exist. *value* can be used * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify * the initial value of a bpf_local_storage. If *value* is * **NULL**, the new bpf_local_storage will be zero initialized. * Return * A bpf_local_storage pointer is returned on success. * * **NULL** if not found or there was an error in adding * a new bpf_local_storage. * * long bpf_task_storage_delete(struct bpf_map *map, struct task_struct *task) * Description * Delete a bpf_local_storage from a *task*. * Return * 0 on success. * * **-ENOENT** if the bpf_local_storage cannot be found. * * struct task_struct *bpf_get_current_task_btf(void) * Description * Return a BTF pointer to the "current" task. * This pointer can also be used in helpers that accept an * *ARG_PTR_TO_BTF_ID* of type *task_struct*. * Return * Pointer to the current task. * * long bpf_bprm_opts_set(struct linux_binprm *bprm, u64 flags) * Description * Set or clear certain options on *bprm*: * * **BPF_F_BPRM_SECUREEXEC** Set the secureexec bit * which sets the **AT_SECURE** auxv for glibc. The bit * is cleared if the flag is not specified. * Return * **-EINVAL** if invalid *flags* are passed, zero otherwise. * * u64 bpf_ktime_get_coarse_ns(void) * Description * Return a coarse-grained version of the time elapsed since * system boot, in nanoseconds. Does not include time the system * was suspended. * * See: **clock_gettime**\ (**CLOCK_MONOTONIC_COARSE**) * Return * Current *ktime*. * * long bpf_ima_inode_hash(struct inode *inode, void *dst, u32 size) * Description * Returns the stored IMA hash of the *inode* (if it's avaialable). * If the hash is larger than *size*, then only *size* * bytes will be copied to *dst* * Return * The **hash_algo** is returned on success, * **-EOPNOTSUP** if IMA is disabled or **-EINVAL** if * invalid arguments are passed. * * struct socket *bpf_sock_from_file(struct file *file) * Description * If the given file represents a socket, returns the associated * socket. * Return * A pointer to a struct socket on success or NULL if the file is * not a socket. * * long bpf_check_mtu(void *ctx, u32 ifindex, u32 *mtu_len, s32 len_diff, u64 flags) * Description * Check packet size against exceeding MTU of net device (based * on *ifindex*). This helper will likely be used in combination * with helpers that adjust/change the packet size. * * The argument *len_diff* can be used for querying with a planned * size change. This allows to check MTU prior to changing packet * ctx. Providing an *len_diff* adjustment that is larger than the * actual packet size (resulting in negative packet size) will in * principle not exceed the MTU, why it is not considered a * failure. Other BPF-helpers are needed for performing the * planned size change, why the responsability for catch a negative * packet size belong in those helpers. * * Specifying *ifindex* zero means the MTU check is performed * against the current net device. This is practical if this isn't * used prior to redirect. * * On input *mtu_len* must be a valid pointer, else verifier will * reject BPF program. If the value *mtu_len* is initialized to * zero then the ctx packet size is use. When value *mtu_len* is * provided as input this specify the L3 length that the MTU check * is done against. Remember XDP and TC length operate at L2, but * this value is L3 as this correlate to MTU and IP-header tot_len * values which are L3 (similar behavior as bpf_fib_lookup). * * The Linux kernel route table can configure MTUs on a more * specific per route level, which is not provided by this helper. * For route level MTU checks use the **bpf_fib_lookup**\ () * helper. * * *ctx* is either **struct xdp_md** for XDP programs or * **struct sk_buff** for tc cls_act programs. * * The *flags* argument can be a combination of one or more of the * following values: * * **BPF_MTU_CHK_SEGS** * This flag will only works for *ctx* **struct sk_buff**. * If packet context contains extra packet segment buffers * (often knows as GSO skb), then MTU check is harder to * check at this point, because in transmit path it is * possible for the skb packet to get re-segmented * (depending on net device features). This could still be * a MTU violation, so this flag enables performing MTU * check against segments, with a different violation * return code to tell it apart. Check cannot use len_diff. * * On return *mtu_len* pointer contains the MTU value of the net * device. Remember the net device configured MTU is the L3 size, * which is returned here and XDP and TC length operate at L2. * Helper take this into account for you, but remember when using * MTU value in your BPF-code. * * Return * * 0 on success, and populate MTU value in *mtu_len* pointer. * * * < 0 if any input argument is invalid (*mtu_len* not updated) * * MTU violations return positive values, but also populate MTU * value in *mtu_len* pointer, as this can be needed for * implementing PMTU handing: * * * **BPF_MTU_CHK_RET_FRAG_NEEDED** * * **BPF_MTU_CHK_RET_SEGS_TOOBIG** * * long bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, void *callback_ctx, u64 flags) * Description * For each element in **map**, call **callback_fn** function with * **map**, **callback_ctx** and other map-specific parameters. * The **callback_fn** should be a static function and * the **callback_ctx** should be a pointer to the stack. * The **flags** is used to control certain aspects of the helper. * Currently, the **flags** must be 0. * * The following are a list of supported map types and their * respective expected callback signatures: * * BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_PERCPU_HASH, * BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, * BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_PERCPU_ARRAY * * long (\*callback_fn)(struct bpf_map \*map, const void \*key, void \*value, void \*ctx); * * For per_cpu maps, the map_value is the value on the cpu where the * bpf_prog is running. * * If **callback_fn** return 0, the helper will continue to the next * element. If return value is 1, the helper will skip the rest of * elements and return. Other return values are not used now. * * Return * The number of traversed map elements for success, **-EINVAL** for * invalid **flags**. * * long bpf_snprintf(char *str, u32 str_size, const char *fmt, u64 *data, u32 data_len) * Description * Outputs a string into the **str** buffer of size **str_size** * based on a format string stored in a read-only map pointed by * **fmt**. * * Each format specifier in **fmt** corresponds to one u64 element * in the **data** array. For strings and pointers where pointees * are accessed, only the pointer values are stored in the *data* * array. The *data_len* is the size of *data* in bytes. * * Formats **%s** and **%p{i,I}{4,6}** require to read kernel * memory. Reading kernel memory may fail due to either invalid * address or valid address but requiring a major memory fault. If * reading kernel memory fails, the string for **%s** will be an * empty string, and the ip address for **%p{i,I}{4,6}** will be 0. * Not returning error to bpf program is consistent with what * **bpf_trace_printk**\ () does for now. * * Return * The strictly positive length of the formatted string, including * the trailing zero character. If the return value is greater than * **str_size**, **str** contains a truncated string, guaranteed to * be zero-terminated except when **str_size** is 0. * * Or **-EBUSY** if the per-CPU memory copy buffer is busy. * * long bpf_sys_bpf(u32 cmd, void *attr, u32 attr_size) * Description * Execute bpf syscall with given arguments. * Return * A syscall result. * * long bpf_btf_find_by_name_kind(char *name, int name_sz, u32 kind, int flags) * Description * Find BTF type with given name and kind in vmlinux BTF or in module's BTFs. * Return * Returns btf_id and btf_obj_fd in lower and upper 32 bits. * * long bpf_sys_close(u32 fd) * Description * Execute close syscall for given FD. * Return * A syscall result. */ #define __BPF_FUNC_MAPPER(FN) \ FN(unspec), \ FN(map_lookup_elem), \ FN(map_update_elem), \ FN(map_delete_elem), \ FN(probe_read), \ FN(ktime_get_ns), \ FN(trace_printk), \ FN(get_prandom_u32), \ FN(get_smp_processor_id), \ FN(skb_store_bytes), \ FN(l3_csum_replace), \ FN(l4_csum_replace), \ FN(tail_call), \ FN(clone_redirect), \ FN(get_current_pid_tgid), \ FN(get_current_uid_gid), \ FN(get_current_comm), \ FN(get_cgroup_classid), \ FN(skb_vlan_push), \ FN(skb_vlan_pop), \ FN(skb_get_tunnel_key), \ FN(skb_set_tunnel_key), \ FN(perf_event_read), \ FN(redirect), \ FN(get_route_realm), \ FN(perf_event_output), \ FN(skb_load_bytes), \ FN(get_stackid), \ FN(csum_diff), \ FN(skb_get_tunnel_opt), \ FN(skb_set_tunnel_opt), \ FN(skb_change_proto), \ FN(skb_change_type), \ FN(skb_under_cgroup), \ FN(get_hash_recalc), \ FN(get_current_task), \ FN(probe_write_user), \ FN(current_task_under_cgroup), \ FN(skb_change_tail), \ FN(skb_pull_data), \ FN(csum_update), \ FN(set_hash_invalid), \ FN(get_numa_node_id), \ FN(skb_change_head), \ FN(xdp_adjust_head), \ FN(probe_read_str), \ FN(get_socket_cookie), \ FN(get_socket_uid), \ FN(set_hash), \ FN(setsockopt), \ FN(skb_adjust_room), \ FN(redirect_map), \ FN(sk_redirect_map), \ FN(sock_map_update), \ FN(xdp_adjust_meta), \ FN(perf_event_read_value), \ FN(perf_prog_read_value), \ FN(getsockopt), \ FN(override_return), \ FN(sock_ops_cb_flags_set), \ FN(msg_redirect_map), \ FN(msg_apply_bytes), \ FN(msg_cork_bytes), \ FN(msg_pull_data), \ FN(bind), \ FN(xdp_adjust_tail), \ FN(skb_get_xfrm_state), \ FN(get_stack), \ FN(skb_load_bytes_relative), \ FN(fib_lookup), \ FN(sock_hash_update), \ FN(msg_redirect_hash), \ FN(sk_redirect_hash), \ FN(lwt_push_encap), \ FN(lwt_seg6_store_bytes), \ FN(lwt_seg6_adjust_srh), \ FN(lwt_seg6_action), \ FN(rc_repeat), \ FN(rc_keydown), \ FN(skb_cgroup_id), \ FN(get_current_cgroup_id), \ FN(get_local_storage), \ FN(sk_select_reuseport), \ FN(skb_ancestor_cgroup_id), \ FN(sk_lookup_tcp), \ FN(sk_lookup_udp), \ FN(sk_release), \ FN(map_push_elem), \ FN(map_pop_elem), \ FN(map_peek_elem), \ FN(msg_push_data), \ FN(msg_pop_data), \ FN(rc_pointer_rel), \ FN(spin_lock), \ FN(spin_unlock), \ FN(sk_fullsock), \ FN(tcp_sock), \ FN(skb_ecn_set_ce), \ FN(get_listener_sock), \ FN(skc_lookup_tcp), \ FN(tcp_check_syncookie), \ FN(sysctl_get_name), \ FN(sysctl_get_current_value), \ FN(sysctl_get_new_value), \ FN(sysctl_set_new_value), \ FN(strtol), \ FN(strtoul), \ FN(sk_storage_get), \ FN(sk_storage_delete), \ FN(send_signal), \ FN(tcp_gen_syncookie), \ FN(skb_output), \ FN(probe_read_user), \ FN(probe_read_kernel), \ FN(probe_read_user_str), \ FN(probe_read_kernel_str), \ FN(tcp_send_ack), \ FN(send_signal_thread), \ FN(jiffies64), \ FN(read_branch_records), \ FN(get_ns_current_pid_tgid), \ FN(xdp_output), \ FN(get_netns_cookie), \ FN(get_current_ancestor_cgroup_id), \ FN(sk_assign), \ FN(ktime_get_boot_ns), \ FN(seq_printf), \ FN(seq_write), \ FN(sk_cgroup_id), \ FN(sk_ancestor_cgroup_id), \ FN(ringbuf_output), \ FN(ringbuf_reserve), \ FN(ringbuf_submit), \ FN(ringbuf_discard), \ FN(ringbuf_query), \ FN(csum_level), \ FN(skc_to_tcp6_sock), \ FN(skc_to_tcp_sock), \ FN(skc_to_tcp_timewait_sock), \ FN(skc_to_tcp_request_sock), \ FN(skc_to_udp6_sock), \ FN(get_task_stack), \ FN(load_hdr_opt), \ FN(store_hdr_opt), \ FN(reserve_hdr_opt), \ FN(inode_storage_get), \ FN(inode_storage_delete), \ FN(d_path), \ FN(copy_from_user), \ FN(snprintf_btf), \ FN(seq_printf_btf), \ FN(skb_cgroup_classid), \ FN(redirect_neigh), \ FN(per_cpu_ptr), \ FN(this_cpu_ptr), \ FN(redirect_peer), \ FN(task_storage_get), \ FN(task_storage_delete), \ FN(get_current_task_btf), \ FN(bprm_opts_set), \ FN(ktime_get_coarse_ns), \ FN(ima_inode_hash), \ FN(sock_from_file), \ FN(check_mtu), \ FN(for_each_map_elem), \ FN(snprintf), \ FN(sys_bpf), \ FN(btf_find_by_name_kind), \ FN(sys_close), \ /* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper * function eBPF program intends to call */ #define __BPF_ENUM_FN(x) BPF_FUNC_ ## x enum bpf_func_id { __BPF_FUNC_MAPPER(__BPF_ENUM_FN) __BPF_FUNC_MAX_ID, }; #undef __BPF_ENUM_FN /* All flags used by eBPF helper functions, placed here. */ /* BPF_FUNC_skb_store_bytes flags. */ enum { BPF_F_RECOMPUTE_CSUM = (1ULL << 0), BPF_F_INVALIDATE_HASH = (1ULL << 1), }; /* BPF_FUNC_l3_csum_replace and BPF_FUNC_l4_csum_replace flags. * First 4 bits are for passing the header field size. */ enum { BPF_F_HDR_FIELD_MASK = 0xfULL, }; /* BPF_FUNC_l4_csum_replace flags. */ enum { BPF_F_PSEUDO_HDR = (1ULL << 4), BPF_F_MARK_MANGLED_0 = (1ULL << 5), BPF_F_MARK_ENFORCE = (1ULL << 6), }; /* BPF_FUNC_clone_redirect and BPF_FUNC_redirect flags. */ enum { BPF_F_INGRESS = (1ULL << 0), }; /* BPF_FUNC_skb_set_tunnel_key and BPF_FUNC_skb_get_tunnel_key flags. */ enum { BPF_F_TUNINFO_IPV6 = (1ULL << 0), }; /* flags for both BPF_FUNC_get_stackid and BPF_FUNC_get_stack. */ enum { BPF_F_SKIP_FIELD_MASK = 0xffULL, BPF_F_USER_STACK = (1ULL << 8), /* flags used by BPF_FUNC_get_stackid only. */ BPF_F_FAST_STACK_CMP = (1ULL << 9), BPF_F_REUSE_STACKID = (1ULL << 10), /* flags used by BPF_FUNC_get_stack only. */ BPF_F_USER_BUILD_ID = (1ULL << 11), }; /* BPF_FUNC_skb_set_tunnel_key flags. */ enum { BPF_F_ZERO_CSUM_TX = (1ULL << 1), BPF_F_DONT_FRAGMENT = (1ULL << 2), BPF_F_SEQ_NUMBER = (1ULL << 3), }; /* BPF_FUNC_perf_event_output, BPF_FUNC_perf_event_read and * BPF_FUNC_perf_event_read_value flags. */ enum { BPF_F_INDEX_MASK = 0xffffffffULL, BPF_F_CURRENT_CPU = BPF_F_INDEX_MASK, /* BPF_FUNC_perf_event_output for sk_buff input context. */ BPF_F_CTXLEN_MASK = (0xfffffULL << 32), }; /* Current network namespace */ enum { BPF_F_CURRENT_NETNS = (-1L), }; /* BPF_FUNC_csum_level level values. */ enum { BPF_CSUM_LEVEL_QUERY, BPF_CSUM_LEVEL_INC, BPF_CSUM_LEVEL_DEC, BPF_CSUM_LEVEL_RESET, }; /* BPF_FUNC_skb_adjust_room flags. */ enum { BPF_F_ADJ_ROOM_FIXED_GSO = (1ULL << 0), BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 = (1ULL << 1), BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 = (1ULL << 2), BPF_F_ADJ_ROOM_ENCAP_L4_GRE = (1ULL << 3), BPF_F_ADJ_ROOM_ENCAP_L4_UDP = (1ULL << 4), BPF_F_ADJ_ROOM_NO_CSUM_RESET = (1ULL << 5), BPF_F_ADJ_ROOM_ENCAP_L2_ETH = (1ULL << 6), }; enum { BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff, BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 56, }; #define BPF_F_ADJ_ROOM_ENCAP_L2(len) (((__u64)len & \ BPF_ADJ_ROOM_ENCAP_L2_MASK) \ << BPF_ADJ_ROOM_ENCAP_L2_SHIFT) /* BPF_FUNC_sysctl_get_name flags. */ enum { BPF_F_SYSCTL_BASE_NAME = (1ULL << 0), }; /* BPF_FUNC__storage_get flags */ enum { BPF_LOCAL_STORAGE_GET_F_CREATE = (1ULL << 0), /* BPF_SK_STORAGE_GET_F_CREATE is only kept for backward compatibility * and BPF_LOCAL_STORAGE_GET_F_CREATE must be used instead. */ BPF_SK_STORAGE_GET_F_CREATE = BPF_LOCAL_STORAGE_GET_F_CREATE, }; /* BPF_FUNC_read_branch_records flags. */ enum { BPF_F_GET_BRANCH_RECORDS_SIZE = (1ULL << 0), }; /* BPF_FUNC_bpf_ringbuf_commit, BPF_FUNC_bpf_ringbuf_discard, and * BPF_FUNC_bpf_ringbuf_output flags. */ enum { BPF_RB_NO_WAKEUP = (1ULL << 0), BPF_RB_FORCE_WAKEUP = (1ULL << 1), }; /* BPF_FUNC_bpf_ringbuf_query flags */ enum { BPF_RB_AVAIL_DATA = 0, BPF_RB_RING_SIZE = 1, BPF_RB_CONS_POS = 2, BPF_RB_PROD_POS = 3, }; /* BPF ring buffer constants */ enum { BPF_RINGBUF_BUSY_BIT = (1U << 31), BPF_RINGBUF_DISCARD_BIT = (1U << 30), BPF_RINGBUF_HDR_SZ = 8, }; /* BPF_FUNC_sk_assign flags in bpf_sk_lookup context. */ enum { BPF_SK_LOOKUP_F_REPLACE = (1ULL << 0), BPF_SK_LOOKUP_F_NO_REUSEPORT = (1ULL << 1), }; /* Mode for BPF_FUNC_skb_adjust_room helper. */ enum bpf_adj_room_mode { BPF_ADJ_ROOM_NET, BPF_ADJ_ROOM_MAC, }; /* Mode for BPF_FUNC_skb_load_bytes_relative helper. */ enum bpf_hdr_start_off { BPF_HDR_START_MAC, BPF_HDR_START_NET, }; /* Encapsulation type for BPF_FUNC_lwt_push_encap helper. */ enum bpf_lwt_encap_mode { BPF_LWT_ENCAP_SEG6, BPF_LWT_ENCAP_SEG6_INLINE, BPF_LWT_ENCAP_IP, }; /* Flags for bpf_bprm_opts_set helper */ enum { BPF_F_BPRM_SECUREEXEC = (1ULL << 0), }; /* Flags for bpf_redirect_map helper */ enum { BPF_F_BROADCAST = (1ULL << 3), BPF_F_EXCLUDE_INGRESS = (1ULL << 4), }; #define __bpf_md_ptr(type, name) \ union { \ type name; \ __u64 :64; \ } __attribute__((aligned(8))) /* user accessible mirror of in-kernel sk_buff. * new fields can only be added to the end of this structure */ struct __sk_buff { __u32 len; __u32 pkt_type; __u32 mark; __u32 queue_mapping; __u32 protocol; __u32 vlan_present; __u32 vlan_tci; __u32 vlan_proto; __u32 priority; __u32 ingress_ifindex; __u32 ifindex; __u32 tc_index; __u32 cb[5]; __u32 hash; __u32 tc_classid; __u32 data; __u32 data_end; __u32 napi_id; /* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */ __u32 family; __u32 remote_ip4; /* Stored in network byte order */ __u32 local_ip4; /* Stored in network byte order */ __u32 remote_ip6[4]; /* Stored in network byte order */ __u32 local_ip6[4]; /* Stored in network byte order */ __u32 remote_port; /* Stored in network byte order */ __u32 local_port; /* stored in host byte order */ /* ... here. */ __u32 data_meta; __bpf_md_ptr(struct bpf_flow_keys *, flow_keys); __u64 tstamp; __u32 wire_len; __u32 gso_segs; __bpf_md_ptr(struct bpf_sock *, sk); __u32 gso_size; }; struct bpf_tunnel_key { __u32 tunnel_id; union { __u32 remote_ipv4; __u32 remote_ipv6[4]; }; __u8 tunnel_tos; __u8 tunnel_ttl; __u16 tunnel_ext; /* Padding, future use. */ __u32 tunnel_label; }; /* user accessible mirror of in-kernel xfrm_state. * new fields can only be added to the end of this structure */ struct bpf_xfrm_state { __u32 reqid; __u32 spi; /* Stored in network byte order */ __u16 family; __u16 ext; /* Padding, future use. */ union { __u32 remote_ipv4; /* Stored in network byte order */ __u32 remote_ipv6[4]; /* Stored in network byte order */ }; }; /* Generic BPF return codes which all BPF program types may support. * The values are binary compatible with their TC_ACT_* counter-part to * provide backwards compatibility with existing SCHED_CLS and SCHED_ACT * programs. * * XDP is handled seprately, see XDP_*. */ enum bpf_ret_code { BPF_OK = 0, /* 1 reserved */ BPF_DROP = 2, /* 3-6 reserved */ BPF_REDIRECT = 7, /* >127 are reserved for prog type specific return codes. * * BPF_LWT_REROUTE: used by BPF_PROG_TYPE_LWT_IN and * BPF_PROG_TYPE_LWT_XMIT to indicate that skb had been * changed and should be routed based on its new L3 header. * (This is an L3 redirect, as opposed to L2 redirect * represented by BPF_REDIRECT above). */ BPF_LWT_REROUTE = 128, }; struct bpf_sock { __u32 bound_dev_if; __u32 family; __u32 type; __u32 protocol; __u32 mark; __u32 priority; /* IP address also allows 1 and 2 bytes access */ __u32 src_ip4; __u32 src_ip6[4]; __u32 src_port; /* host byte order */ __u32 dst_port; /* network byte order */ __u32 dst_ip4; __u32 dst_ip6[4]; __u32 state; __s32 rx_queue_mapping; }; struct bpf_tcp_sock { __u32 snd_cwnd; /* Sending congestion window */ __u32 srtt_us; /* smoothed round trip time << 3 in usecs */ __u32 rtt_min; __u32 snd_ssthresh; /* Slow start size threshold */ __u32 rcv_nxt; /* What we want to receive next */ __u32 snd_nxt; /* Next sequence we send */ __u32 snd_una; /* First byte we want an ack for */ __u32 mss_cache; /* Cached effective mss, not including SACKS */ __u32 ecn_flags; /* ECN status bits. */ __u32 rate_delivered; /* saved rate sample: packets delivered */ __u32 rate_interval_us; /* saved rate sample: time elapsed */ __u32 packets_out; /* Packets which are "in flight" */ __u32 retrans_out; /* Retransmitted packets out */ __u32 total_retrans; /* Total retransmits for entire connection */ __u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn * total number of segments in. */ __u32 data_segs_in; /* RFC4898 tcpEStatsPerfDataSegsIn * total number of data segments in. */ __u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut * The total number of segments sent. */ __u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut * total number of data segments sent. */ __u32 lost_out; /* Lost packets */ __u32 sacked_out; /* SACK'd packets */ __u64 bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived * sum(delta(rcv_nxt)), or how many bytes * were acked. */ __u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked * sum(delta(snd_una)), or how many bytes * were acked. */ __u32 dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups * total number of DSACK blocks received */ __u32 delivered; /* Total data packets delivered incl. rexmits */ __u32 delivered_ce; /* Like the above but only ECE marked packets */ __u32 icsk_retransmits; /* Number of unrecovered [RTO] timeouts */ }; struct bpf_sock_tuple { union { struct { __be32 saddr; __be32 daddr; __be16 sport; __be16 dport; } ipv4; struct { __be32 saddr[4]; __be32 daddr[4]; __be16 sport; __be16 dport; } ipv6; }; }; struct bpf_xdp_sock { __u32 queue_id; }; #define XDP_PACKET_HEADROOM 256 /* User return codes for XDP prog type. * A valid XDP program must return one of these defined values. All other * return codes are reserved for future use. Unknown return codes will * result in packet drops and a warning via bpf_warn_invalid_xdp_action(). */ enum xdp_action { XDP_ABORTED = 0, XDP_DROP, XDP_PASS, XDP_TX, XDP_REDIRECT, }; /* user accessible metadata for XDP packet hook * new fields must be added to the end of this structure */ struct xdp_md { __u32 data; __u32 data_end; __u32 data_meta; /* Below access go through struct xdp_rxq_info */ __u32 ingress_ifindex; /* rxq->dev->ifindex */ __u32 rx_queue_index; /* rxq->queue_index */ __u32 egress_ifindex; /* txq->dev->ifindex */ }; /* DEVMAP map-value layout * * The struct data-layout of map-value is a configuration interface. * New members can only be added to the end of this structure. */ struct bpf_devmap_val { __u32 ifindex; /* device index */ union { int fd; /* prog fd on map write */ __u32 id; /* prog id on map read */ } bpf_prog; }; /* CPUMAP map-value layout * * The struct data-layout of map-value is a configuration interface. * New members can only be added to the end of this structure. */ struct bpf_cpumap_val { __u32 qsize; /* queue size to remote target CPU */ union { int fd; /* prog fd on map write */ __u32 id; /* prog id on map read */ } bpf_prog; }; enum sk_action { SK_DROP = 0, SK_PASS, }; /* user accessible metadata for SK_MSG packet hook, new fields must * be added to the end of this structure */ struct sk_msg_md { __bpf_md_ptr(void *, data); __bpf_md_ptr(void *, data_end); __u32 family; __u32 remote_ip4; /* Stored in network byte order */ __u32 local_ip4; /* Stored in network byte order */ __u32 remote_ip6[4]; /* Stored in network byte order */ __u32 local_ip6[4]; /* Stored in network byte order */ __u32 remote_port; /* Stored in network byte order */ __u32 local_port; /* stored in host byte order */ __u32 size; /* Total size of sk_msg */ __bpf_md_ptr(struct bpf_sock *, sk); /* current socket */ }; struct sk_reuseport_md { /* * Start of directly accessible data. It begins from * the tcp/udp header. */ __bpf_md_ptr(void *, data); /* End of directly accessible data */ __bpf_md_ptr(void *, data_end); /* * Total length of packet (starting from the tcp/udp header). * Note that the directly accessible bytes (data_end - data) * could be less than this "len". Those bytes could be * indirectly read by a helper "bpf_skb_load_bytes()". */ __u32 len; /* * Eth protocol in the mac header (network byte order). e.g. * ETH_P_IP(0x0800) and ETH_P_IPV6(0x86DD) */ __u32 eth_protocol; __u32 ip_protocol; /* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */ __u32 bind_inany; /* Is sock bound to an INANY address? */ __u32 hash; /* A hash of the packet 4 tuples */ __bpf_md_ptr(struct bpf_sock *, sk); }; #define BPF_TAG_SIZE 8 struct bpf_prog_info { __u32 type; __u32 id; __u8 tag[BPF_TAG_SIZE]; __u32 jited_prog_len; __u32 xlated_prog_len; __aligned_u64 jited_prog_insns; __aligned_u64 xlated_prog_insns; __u64 load_time; /* ns since boottime */ __u32 created_by_uid; __u32 nr_map_ids; __aligned_u64 map_ids; char name[BPF_OBJ_NAME_LEN]; __u32 ifindex; __u32 gpl_compatible:1; __u32 :31; /* alignment pad */ __u64 netns_dev; __u64 netns_ino; __u32 nr_jited_ksyms; __u32 nr_jited_func_lens; __aligned_u64 jited_ksyms; __aligned_u64 jited_func_lens; __u32 btf_id; __u32 func_info_rec_size; __aligned_u64 func_info; __u32 nr_func_info; __u32 nr_line_info; __aligned_u64 line_info; __aligned_u64 jited_line_info; __u32 nr_jited_line_info; __u32 line_info_rec_size; __u32 jited_line_info_rec_size; __u32 nr_prog_tags; __aligned_u64 prog_tags; __u64 run_time_ns; __u64 run_cnt; __u64 recursion_misses; } __attribute__((aligned(8))); struct bpf_map_info { __u32 type; __u32 id; __u32 key_size; __u32 value_size; __u32 max_entries; __u32 map_flags; char name[BPF_OBJ_NAME_LEN]; __u32 ifindex; __u32 btf_vmlinux_value_type_id; __u64 netns_dev; __u64 netns_ino; __u32 btf_id; __u32 btf_key_type_id; __u32 btf_value_type_id; } __attribute__((aligned(8))); struct bpf_btf_info { __aligned_u64 btf; __u32 btf_size; __u32 id; __aligned_u64 name; __u32 name_len; __u32 kernel_btf; } __attribute__((aligned(8))); struct bpf_link_info { __u32 type; __u32 id; __u32 prog_id; union { struct { __aligned_u64 tp_name; /* in/out: tp_name buffer ptr */ __u32 tp_name_len; /* in/out: tp_name buffer len */ } raw_tracepoint; struct { __u32 attach_type; __u32 target_obj_id; /* prog_id for PROG_EXT, otherwise btf object id */ __u32 target_btf_id; /* BTF type id inside the object */ } tracing; struct { __u64 cgroup_id; __u32 attach_type; } cgroup; struct { __aligned_u64 target_name; /* in/out: target_name buffer ptr */ __u32 target_name_len; /* in/out: target_name buffer len */ union { struct { __u32 map_id; } map; }; } iter; struct { __u32 netns_ino; __u32 attach_type; } netns; struct { __u32 ifindex; } xdp; }; } __attribute__((aligned(8))); /* User bpf_sock_addr struct to access socket fields and sockaddr struct passed * by user and intended to be used by socket (e.g. to bind to, depends on * attach type). */ struct bpf_sock_addr { __u32 user_family; /* Allows 4-byte read, but no write. */ __u32 user_ip4; /* Allows 1,2,4-byte read and 4-byte write. * Stored in network byte order. */ __u32 user_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. * Stored in network byte order. */ __u32 user_port; /* Allows 1,2,4-byte read and 4-byte write. * Stored in network byte order */ __u32 family; /* Allows 4-byte read, but no write */ __u32 type; /* Allows 4-byte read, but no write */ __u32 protocol; /* Allows 4-byte read, but no write */ __u32 msg_src_ip4; /* Allows 1,2,4-byte read and 4-byte write. * Stored in network byte order. */ __u32 msg_src_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. * Stored in network byte order. */ __bpf_md_ptr(struct bpf_sock *, sk); }; /* User bpf_sock_ops struct to access socket values and specify request ops * and their replies. * Some of this fields are in network (bigendian) byte order and may need * to be converted before use (bpf_ntohl() defined in samples/bpf/bpf_endian.h). * New fields can only be added at the end of this structure */ struct bpf_sock_ops { __u32 op; union { __u32 args[4]; /* Optionally passed to bpf program */ __u32 reply; /* Returned by bpf program */ __u32 replylong[4]; /* Optionally returned by bpf prog */ }; __u32 family; __u32 remote_ip4; /* Stored in network byte order */ __u32 local_ip4; /* Stored in network byte order */ __u32 remote_ip6[4]; /* Stored in network byte order */ __u32 local_ip6[4]; /* Stored in network byte order */ __u32 remote_port; /* Stored in network byte order */ __u32 local_port; /* stored in host byte order */ __u32 is_fullsock; /* Some TCP fields are only valid if * there is a full socket. If not, the * fields read as zero. */ __u32 snd_cwnd; __u32 srtt_us; /* Averaged RTT << 3 in usecs */ __u32 bpf_sock_ops_cb_flags; /* flags defined in uapi/linux/tcp.h */ __u32 state; __u32 rtt_min; __u32 snd_ssthresh; __u32 rcv_nxt; __u32 snd_nxt; __u32 snd_una; __u32 mss_cache; __u32 ecn_flags; __u32 rate_delivered; __u32 rate_interval_us; __u32 packets_out; __u32 retrans_out; __u32 total_retrans; __u32 segs_in; __u32 data_segs_in; __u32 segs_out; __u32 data_segs_out; __u32 lost_out; __u32 sacked_out; __u32 sk_txhash; __u64 bytes_received; __u64 bytes_acked; __bpf_md_ptr(struct bpf_sock *, sk); /* [skb_data, skb_data_end) covers the whole TCP header. * * BPF_SOCK_OPS_PARSE_HDR_OPT_CB: The packet received * BPF_SOCK_OPS_HDR_OPT_LEN_CB: Not useful because the * header has not been written. * BPF_SOCK_OPS_WRITE_HDR_OPT_CB: The header and options have * been written so far. * BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB: The SYNACK that concludes * the 3WHS. * BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: The ACK that concludes * the 3WHS. * * bpf_load_hdr_opt() can also be used to read a particular option. */ __bpf_md_ptr(void *, skb_data); __bpf_md_ptr(void *, skb_data_end); __u32 skb_len; /* The total length of a packet. * It includes the header, options, * and payload. */ __u32 skb_tcp_flags; /* tcp_flags of the header. It provides * an easy way to check for tcp_flags * without parsing skb_data. * * In particular, the skb_tcp_flags * will still be available in * BPF_SOCK_OPS_HDR_OPT_LEN even though * the outgoing header has not * been written yet. */ }; /* Definitions for bpf_sock_ops_cb_flags */ enum { BPF_SOCK_OPS_RTO_CB_FLAG = (1<<0), BPF_SOCK_OPS_RETRANS_CB_FLAG = (1<<1), BPF_SOCK_OPS_STATE_CB_FLAG = (1<<2), BPF_SOCK_OPS_RTT_CB_FLAG = (1<<3), /* Call bpf for all received TCP headers. The bpf prog will be * called under sock_ops->op == BPF_SOCK_OPS_PARSE_HDR_OPT_CB * * Please refer to the comment in BPF_SOCK_OPS_PARSE_HDR_OPT_CB * for the header option related helpers that will be useful * to the bpf programs. * * It could be used at the client/active side (i.e. connect() side) * when the server told it that the server was in syncookie * mode and required the active side to resend the bpf-written * options. The active side can keep writing the bpf-options until * it received a valid packet from the server side to confirm * the earlier packet (and options) has been received. The later * example patch is using it like this at the active side when the * server is in syncookie mode. * * The bpf prog will usually turn this off in the common cases. */ BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG = (1<<4), /* Call bpf when kernel has received a header option that * the kernel cannot handle. The bpf prog will be called under * sock_ops->op == BPF_SOCK_OPS_PARSE_HDR_OPT_CB. * * Please refer to the comment in BPF_SOCK_OPS_PARSE_HDR_OPT_CB * for the header option related helpers that will be useful * to the bpf programs. */ BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG = (1<<5), /* Call bpf when the kernel is writing header options for the * outgoing packet. The bpf prog will first be called * to reserve space in a skb under * sock_ops->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB. Then * the bpf prog will be called to write the header option(s) * under sock_ops->op == BPF_SOCK_OPS_WRITE_HDR_OPT_CB. * * Please refer to the comment in BPF_SOCK_OPS_HDR_OPT_LEN_CB * and BPF_SOCK_OPS_WRITE_HDR_OPT_CB for the header option * related helpers that will be useful to the bpf programs. * * The kernel gets its chance to reserve space and write * options first before the BPF program does. */ BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG = (1<<6), /* Mask of all currently supported cb flags */ BPF_SOCK_OPS_ALL_CB_FLAGS = 0x7F, }; /* List of known BPF sock_ops operators. * New entries can only be added at the end */ enum { BPF_SOCK_OPS_VOID, BPF_SOCK_OPS_TIMEOUT_INIT, /* Should return SYN-RTO value to use or * -1 if default value should be used */ BPF_SOCK_OPS_RWND_INIT, /* Should return initial advertized * window (in packets) or -1 if default * value should be used */ BPF_SOCK_OPS_TCP_CONNECT_CB, /* Calls BPF program right before an * active connection is initialized */ BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, /* Calls BPF program when an * active connection is * established */ BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, /* Calls BPF program when a * passive connection is * established */ BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control * needs ECN */ BPF_SOCK_OPS_BASE_RTT, /* Get base RTT. The correct value is * based on the path and may be * dependent on the congestion control * algorithm. In general it indicates * a congestion threshold. RTTs above * this indicate congestion */ BPF_SOCK_OPS_RTO_CB, /* Called when an RTO has triggered. * Arg1: value of icsk_retransmits * Arg2: value of icsk_rto * Arg3: whether RTO has expired */ BPF_SOCK_OPS_RETRANS_CB, /* Called when skb is retransmitted. * Arg1: sequence number of 1st byte * Arg2: # segments * Arg3: return value of * tcp_transmit_skb (0 => success) */ BPF_SOCK_OPS_STATE_CB, /* Called when TCP changes state. * Arg1: old_state * Arg2: new_state */ BPF_SOCK_OPS_TCP_LISTEN_CB, /* Called on listen(2), right after * socket transition to LISTEN state. */ BPF_SOCK_OPS_RTT_CB, /* Called on every RTT. */ BPF_SOCK_OPS_PARSE_HDR_OPT_CB, /* Parse the header option. * It will be called to handle * the packets received at * an already established * connection. * * sock_ops->skb_data: * Referring to the received skb. * It covers the TCP header only. * * bpf_load_hdr_opt() can also * be used to search for a * particular option. */ BPF_SOCK_OPS_HDR_OPT_LEN_CB, /* Reserve space for writing the * header option later in * BPF_SOCK_OPS_WRITE_HDR_OPT_CB. * Arg1: bool want_cookie. (in * writing SYNACK only) * * sock_ops->skb_data: * Not available because no header has * been written yet. * * sock_ops->skb_tcp_flags: * The tcp_flags of the * outgoing skb. (e.g. SYN, ACK, FIN). * * bpf_reserve_hdr_opt() should * be used to reserve space. */ BPF_SOCK_OPS_WRITE_HDR_OPT_CB, /* Write the header options * Arg1: bool want_cookie. (in * writing SYNACK only) * * sock_ops->skb_data: * Referring to the outgoing skb. * It covers the TCP header * that has already been written * by the kernel and the * earlier bpf-progs. * * sock_ops->skb_tcp_flags: * The tcp_flags of the outgoing * skb. (e.g. SYN, ACK, FIN). * * bpf_store_hdr_opt() should * be used to write the * option. * * bpf_load_hdr_opt() can also * be used to search for a * particular option that * has already been written * by the kernel or the * earlier bpf-progs. */ }; /* List of TCP states. There is a build check in net/ipv4/tcp.c to detect * changes between the TCP and BPF versions. Ideally this should never happen. * If it does, we need to add code to convert them before calling * the BPF sock_ops function. */ enum { BPF_TCP_ESTABLISHED = 1, BPF_TCP_SYN_SENT, BPF_TCP_SYN_RECV, BPF_TCP_FIN_WAIT1, BPF_TCP_FIN_WAIT2, BPF_TCP_TIME_WAIT, BPF_TCP_CLOSE, BPF_TCP_CLOSE_WAIT, BPF_TCP_LAST_ACK, BPF_TCP_LISTEN, BPF_TCP_CLOSING, /* Now a valid state */ BPF_TCP_NEW_SYN_RECV, BPF_TCP_BOUND_INACTIVE, BPF_TCP_MAX_STATES /* Leave at the end! */ }; enum { TCP_BPF_IW = 1001, /* Set TCP initial congestion window */ TCP_BPF_SNDCWND_CLAMP = 1002, /* Set sndcwnd_clamp */ TCP_BPF_DELACK_MAX = 1003, /* Max delay ack in usecs */ TCP_BPF_RTO_MIN = 1004, /* Min delay ack in usecs */ /* Copy the SYN pkt to optval * * BPF_PROG_TYPE_SOCK_OPS only. It is similar to the * bpf_getsockopt(TCP_SAVED_SYN) but it does not limit * to only getting from the saved_syn. It can either get the * syn packet from: * * 1. the just-received SYN packet (only available when writing the * SYNACK). It will be useful when it is not necessary to * save the SYN packet for latter use. It is also the only way * to get the SYN during syncookie mode because the syn * packet cannot be saved during syncookie. * * OR * * 2. the earlier saved syn which was done by * bpf_setsockopt(TCP_SAVE_SYN). * * The bpf_getsockopt(TCP_BPF_SYN*) option will hide where the * SYN packet is obtained. * * If the bpf-prog does not need the IP[46] header, the * bpf-prog can avoid parsing the IP header by using * TCP_BPF_SYN. Otherwise, the bpf-prog can get both * IP[46] and TCP header by using TCP_BPF_SYN_IP. * * >0: Total number of bytes copied * -ENOSPC: Not enough space in optval. Only optlen number of * bytes is copied. * -ENOENT: The SYN skb is not available now and the earlier SYN pkt * is not saved by setsockopt(TCP_SAVE_SYN). */ TCP_BPF_SYN = 1005, /* Copy the TCP header */ TCP_BPF_SYN_IP = 1006, /* Copy the IP[46] and TCP header */ TCP_BPF_SYN_MAC = 1007, /* Copy the MAC, IP[46], and TCP header */ }; enum { BPF_LOAD_HDR_OPT_TCP_SYN = (1ULL << 0), }; /* args[0] value during BPF_SOCK_OPS_HDR_OPT_LEN_CB and * BPF_SOCK_OPS_WRITE_HDR_OPT_CB. */ enum { BPF_WRITE_HDR_TCP_CURRENT_MSS = 1, /* Kernel is finding the * total option spaces * required for an established * sk in order to calculate the * MSS. No skb is actually * sent. */ BPF_WRITE_HDR_TCP_SYNACK_COOKIE = 2, /* Kernel is in syncookie mode * when sending a SYN. */ }; struct bpf_perf_event_value { __u64 counter; __u64 enabled; __u64 running; }; enum { BPF_DEVCG_ACC_MKNOD = (1ULL << 0), BPF_DEVCG_ACC_READ = (1ULL << 1), BPF_DEVCG_ACC_WRITE = (1ULL << 2), }; enum { BPF_DEVCG_DEV_BLOCK = (1ULL << 0), BPF_DEVCG_DEV_CHAR = (1ULL << 1), }; struct bpf_cgroup_dev_ctx { /* access_type encoded as (BPF_DEVCG_ACC_* << 16) | BPF_DEVCG_DEV_* */ __u32 access_type; __u32 major; __u32 minor; }; struct bpf_raw_tracepoint_args { __u64 args[0]; }; /* DIRECT: Skip the FIB rules and go to FIB table associated with device * OUTPUT: Do lookup from egress perspective; default is ingress */ enum { BPF_FIB_LOOKUP_DIRECT = (1U << 0), BPF_FIB_LOOKUP_OUTPUT = (1U << 1), }; enum { BPF_FIB_LKUP_RET_SUCCESS, /* lookup successful */ BPF_FIB_LKUP_RET_BLACKHOLE, /* dest is blackholed; can be dropped */ BPF_FIB_LKUP_RET_UNREACHABLE, /* dest is unreachable; can be dropped */ BPF_FIB_LKUP_RET_PROHIBIT, /* dest not allowed; can be dropped */ BPF_FIB_LKUP_RET_NOT_FWDED, /* packet is not forwarded */ BPF_FIB_LKUP_RET_FWD_DISABLED, /* fwding is not enabled on ingress */ BPF_FIB_LKUP_RET_UNSUPP_LWT, /* fwd requires encapsulation */ BPF_FIB_LKUP_RET_NO_NEIGH, /* no neighbor entry for nh */ BPF_FIB_LKUP_RET_FRAG_NEEDED, /* fragmentation required to fwd */ }; struct bpf_fib_lookup { /* input: network family for lookup (AF_INET, AF_INET6) * output: network family of egress nexthop */ __u8 family; /* set if lookup is to consider L4 data - e.g., FIB rules */ __u8 l4_protocol; __be16 sport; __be16 dport; union { /* used for MTU check */ /* input to lookup */ __u16 tot_len; /* L3 length from network hdr (iph->tot_len) */ /* output: MTU value */ __u16 mtu_result; }; /* input: L3 device index for lookup * output: device index from FIB lookup */ __u32 ifindex; union { /* inputs to lookup */ __u8 tos; /* AF_INET */ __be32 flowinfo; /* AF_INET6, flow_label + priority */ /* output: metric of fib result (IPv4/IPv6 only) */ __u32 rt_metric; }; union { __be32 ipv4_src; __u32 ipv6_src[4]; /* in6_addr; network order */ }; /* input to bpf_fib_lookup, ipv{4,6}_dst is destination address in * network header. output: bpf_fib_lookup sets to gateway address * if FIB lookup returns gateway route */ union { __be32 ipv4_dst; __u32 ipv6_dst[4]; /* in6_addr; network order */ }; /* output */ __be16 h_vlan_proto; __be16 h_vlan_TCI; __u8 smac[6]; /* ETH_ALEN */ __u8 dmac[6]; /* ETH_ALEN */ }; struct bpf_redir_neigh { /* network family for lookup (AF_INET, AF_INET6) */ __u32 nh_family; /* network address of nexthop; skips fib lookup to find gateway */ union { __be32 ipv4_nh; __u32 ipv6_nh[4]; /* in6_addr; network order */ }; }; /* bpf_check_mtu flags*/ enum bpf_check_mtu_flags { BPF_MTU_CHK_SEGS = (1U << 0), }; enum bpf_check_mtu_ret { BPF_MTU_CHK_RET_SUCCESS, /* check and lookup successful */ BPF_MTU_CHK_RET_FRAG_NEEDED, /* fragmentation required to fwd */ BPF_MTU_CHK_RET_SEGS_TOOBIG, /* GSO re-segmentation needed to fwd */ }; enum bpf_task_fd_type { BPF_FD_TYPE_RAW_TRACEPOINT, /* tp name */ BPF_FD_TYPE_TRACEPOINT, /* tp name */ BPF_FD_TYPE_KPROBE, /* (symbol + offset) or addr */ BPF_FD_TYPE_KRETPROBE, /* (symbol + offset) or addr */ BPF_FD_TYPE_UPROBE, /* filename + offset */ BPF_FD_TYPE_URETPROBE, /* filename + offset */ }; enum { BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG = (1U << 0), BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL = (1U << 1), BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP = (1U << 2), }; struct bpf_flow_keys { __u16 nhoff; __u16 thoff; __u16 addr_proto; /* ETH_P_* of valid addrs */ __u8 is_frag; __u8 is_first_frag; __u8 is_encap; __u8 ip_proto; __be16 n_proto; __be16 sport; __be16 dport; union { struct { __be32 ipv4_src; __be32 ipv4_dst; }; struct { __u32 ipv6_src[4]; /* in6_addr; network order */ __u32 ipv6_dst[4]; /* in6_addr; network order */ }; }; __u32 flags; __be32 flow_label; }; struct bpf_func_info { __u32 insn_off; __u32 type_id; }; #define BPF_LINE_INFO_LINE_NUM(line_col) ((line_col) >> 10) #define BPF_LINE_INFO_LINE_COL(line_col) ((line_col) & 0x3ff) struct bpf_line_info { __u32 insn_off; __u32 file_name_off; __u32 line_off; __u32 line_col; }; struct bpf_spin_lock { __u32 val; }; struct bpf_sysctl { __u32 write; /* Sysctl is being read (= 0) or written (= 1). * Allows 1,2,4-byte read, but no write. */ __u32 file_pos; /* Sysctl file position to read from, write to. * Allows 1,2,4-byte read an 4-byte write. */ }; struct bpf_sockopt { __bpf_md_ptr(struct bpf_sock *, sk); __bpf_md_ptr(void *, optval); __bpf_md_ptr(void *, optval_end); __s32 level; __s32 optname; __s32 optlen; __s32 retval; }; struct bpf_pidns_info { __u32 pid; __u32 tgid; }; /* User accessible data for SK_LOOKUP programs. Add new fields at the end. */ struct bpf_sk_lookup { union { __bpf_md_ptr(struct bpf_sock *, sk); /* Selected socket */ __u64 cookie; /* Non-zero if socket was selected in PROG_TEST_RUN */ }; __u32 family; /* Protocol family (AF_INET, AF_INET6) */ __u32 protocol; /* IP protocol (IPPROTO_TCP, IPPROTO_UDP) */ __u32 remote_ip4; /* Network byte order */ __u32 remote_ip6[4]; /* Network byte order */ __u32 remote_port; /* Network byte order */ __u32 local_ip4; /* Network byte order */ __u32 local_ip6[4]; /* Network byte order */ __u32 local_port; /* Host byte order */ }; /* * struct btf_ptr is used for typed pointer representation; the * type id is used to render the pointer data as the appropriate type * via the bpf_snprintf_btf() helper described above. A flags field - * potentially to specify additional details about the BTF pointer * (rather than its mode of display) - is included for future use. * Display flags - BTF_F_* - are passed to bpf_snprintf_btf separately. */ struct btf_ptr { void *ptr; __u32 type_id; __u32 flags; /* BTF ptr flags; unused at present. */ }; /* * Flags to control bpf_snprintf_btf() behaviour. * - BTF_F_COMPACT: no formatting around type information * - BTF_F_NONAME: no struct/union member names/types * - BTF_F_PTR_RAW: show raw (unobfuscated) pointer values; * equivalent to %px. * - BTF_F_ZERO: show zero-valued struct/union members; they * are not displayed by default */ enum { BTF_F_COMPACT = (1ULL << 0), BTF_F_NONAME = (1ULL << 1), BTF_F_PTR_RAW = (1ULL << 2), BTF_F_ZERO = (1ULL << 3), }; #endif /* __LINUX_BPF_H__ */ linux/wimax.h000064400000020263151027430560007207 0ustar00/* * Linux WiMax * API for user space * * * Copyright (C) 2007-2008 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Intel Corporation * Inaky Perez-Gonzalez * - Initial implementation * * * This file declares the user/kernel protocol that is spoken over * Generic Netlink, as well as any type declaration that is to be used * by kernel and user space. * * It is intended for user space to clone it verbatim to use it as a * primary reference for definitions. * * Stuff intended for kernel usage as well as full protocol and stack * documentation is rooted in include/net/wimax.h. */ #ifndef __LINUX__WIMAX_H__ #define __LINUX__WIMAX_H__ #include enum { /** * Version of the interface (unsigned decimal, MMm, max 25.5) * M - Major: change if removing or modifying an existing call. * m - minor: change when adding a new call */ WIMAX_GNL_VERSION = 01, /* Generic NetLink attributes */ WIMAX_GNL_ATTR_INVALID = 0x00, WIMAX_GNL_ATTR_MAX = 10, }; /* * Generic NetLink operations * * Most of these map to an API call; _OP_ stands for operation, _RP_ * for reply and _RE_ for report (aka: signal). */ enum { WIMAX_GNL_OP_MSG_FROM_USER, /* User to kernel message */ WIMAX_GNL_OP_MSG_TO_USER, /* Kernel to user message */ WIMAX_GNL_OP_RFKILL, /* Run wimax_rfkill() */ WIMAX_GNL_OP_RESET, /* Run wimax_rfkill() */ WIMAX_GNL_RE_STATE_CHANGE, /* Report: status change */ WIMAX_GNL_OP_STATE_GET, /* Request for current state */ }; /* Message from user / to user */ enum { WIMAX_GNL_MSG_IFIDX = 1, WIMAX_GNL_MSG_PIPE_NAME, WIMAX_GNL_MSG_DATA, }; /* * wimax_rfkill() * * The state of the radio (ON/OFF) is mapped to the rfkill subsystem's * switch state (DISABLED/ENABLED). */ enum wimax_rf_state { WIMAX_RF_OFF = 0, /* Radio is off, rfkill on/enabled */ WIMAX_RF_ON = 1, /* Radio is on, rfkill off/disabled */ WIMAX_RF_QUERY = 2, }; /* Attributes */ enum { WIMAX_GNL_RFKILL_IFIDX = 1, WIMAX_GNL_RFKILL_STATE, }; /* Attributes for wimax_reset() */ enum { WIMAX_GNL_RESET_IFIDX = 1, }; /* Attributes for wimax_state_get() */ enum { WIMAX_GNL_STGET_IFIDX = 1, }; /* * Attributes for the Report State Change * * For now we just have the old and new states; new attributes might * be added later on. */ enum { WIMAX_GNL_STCH_IFIDX = 1, WIMAX_GNL_STCH_STATE_OLD, WIMAX_GNL_STCH_STATE_NEW, }; /** * enum wimax_st - The different states of a WiMAX device * @__WIMAX_ST_NULL: The device structure has been allocated and zeroed, * but still wimax_dev_add() hasn't been called. There is no state. * * @WIMAX_ST_DOWN: The device has been registered with the WiMAX and * networking stacks, but it is not initialized (normally that is * done with 'ifconfig DEV up' [or equivalent], which can upload * firmware and enable communications with the device). * In this state, the device is powered down and using as less * power as possible. * This state is the default after a call to wimax_dev_add(). It * is ok to have drivers move directly to %WIMAX_ST_UNINITIALIZED * or %WIMAX_ST_RADIO_OFF in _probe() after the call to * wimax_dev_add(). * It is recommended that the driver leaves this state when * calling 'ifconfig DEV up' and enters it back on 'ifconfig DEV * down'. * * @__WIMAX_ST_QUIESCING: The device is being torn down, so no API * operations are allowed to proceed except the ones needed to * complete the device clean up process. * * @WIMAX_ST_UNINITIALIZED: [optional] Communication with the device * is setup, but the device still requires some configuration * before being operational. * Some WiMAX API calls might work. * * @WIMAX_ST_RADIO_OFF: The device is fully up; radio is off (wether * by hardware or software switches). * It is recommended to always leave the device in this state * after initialization. * * @WIMAX_ST_READY: The device is fully up and radio is on. * * @WIMAX_ST_SCANNING: [optional] The device has been instructed to * scan. In this state, the device cannot be actively connected to * a network. * * @WIMAX_ST_CONNECTING: The device is connecting to a network. This * state exists because in some devices, the connect process can * include a number of negotiations between user space, kernel * space and the device. User space needs to know what the device * is doing. If the connect sequence in a device is atomic and * fast, the device can transition directly to CONNECTED * * @WIMAX_ST_CONNECTED: The device is connected to a network. * * @__WIMAX_ST_INVALID: This is an invalid state used to mark the * maximum numeric value of states. * * Description: * * Transitions from one state to another one are atomic and can only * be caused in kernel space with wimax_state_change(). To read the * state, use wimax_state_get(). * * States starting with __ are internal and shall not be used or * referred to by drivers or userspace. They look ugly, but that's the * point -- if any use is made non-internal to the stack, it is easier * to catch on review. * * All API operations [with well defined exceptions] will take the * device mutex before starting and then check the state. If the state * is %__WIMAX_ST_NULL, %WIMAX_ST_DOWN, %WIMAX_ST_UNINITIALIZED or * %__WIMAX_ST_QUIESCING, it will drop the lock and quit with * -%EINVAL, -%ENOMEDIUM, -%ENOTCONN or -%ESHUTDOWN. * * The order of the definitions is important, so we can do numerical * comparisons (eg: < %WIMAX_ST_RADIO_OFF means the device is not ready * to operate). */ /* * The allowed state transitions are described in the table below * (states in rows can go to states in columns where there is an X): * * UNINI RADIO READY SCAN CONNEC CONNEC * NULL DOWN QUIESCING TIALIZED OFF NING TING TED * NULL - x * DOWN - x x x * QUIESCING x - * UNINITIALIZED x - x * RADIO_OFF x - x * READY x x - x x x * SCANNING x x x - x x * CONNECTING x x x x - x * CONNECTED x x x - * * This table not available in kernel-doc because the formatting messes it up. */ enum wimax_st { __WIMAX_ST_NULL = 0, WIMAX_ST_DOWN, __WIMAX_ST_QUIESCING, WIMAX_ST_UNINITIALIZED, WIMAX_ST_RADIO_OFF, WIMAX_ST_READY, WIMAX_ST_SCANNING, WIMAX_ST_CONNECTING, WIMAX_ST_CONNECTED, __WIMAX_ST_INVALID /* Always keep last */ }; #endif /* #ifndef __LINUX__WIMAX_H__ */ linux/reiserfs_xattr.h000064400000001025151027430560011121 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* File: linux/reiserfs_xattr.h */ #ifndef _LINUX_REISERFS_XATTR_H #define _LINUX_REISERFS_XATTR_H #include /* Magic value in header */ #define REISERFS_XATTR_MAGIC 0x52465841 /* "RFXA" */ struct reiserfs_xattr_header { __le32 h_magic; /* magic number for identification */ __le32 h_hash; /* hash of the value */ }; struct reiserfs_security_handle { const char *name; void *value; size_t length; }; #endif /* _LINUX_REISERFS_XATTR_H */ linux/netfilter_bridge/ebt_mark_t.h000064400000001477151027430560013507 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_MARK_T_H #define __LINUX_BRIDGE_EBT_MARK_T_H /* The target member is reused for adding new actions, the * value of the real target is -1 to -NUM_STANDARD_TARGETS. * For backward compatibility, the 4 lsb (2 would be enough, * but let's play it safe) are kept to designate this target. * The remaining bits designate the action. By making the set * action 0xfffffff0, the result will look ok for older * versions. [September 2006] */ #define MARK_SET_VALUE (0xfffffff0) #define MARK_OR_VALUE (0xffffffe0) #define MARK_AND_VALUE (0xffffffd0) #define MARK_XOR_VALUE (0xffffffc0) struct ebt_mark_t_info { unsigned long mark; /* EBT_ACCEPT, EBT_DROP, EBT_CONTINUE or EBT_RETURN */ int target; }; #define EBT_MARK_TARGET "mark" #endif linux/netfilter_bridge/ebt_ip.h000064400000002106151027430560012630 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ebt_ip * * Authors: * Bart De Schuymer * * April, 2002 * * Changes: * added ip-sport and ip-dport * Innominate Security Technologies AG * September, 2002 */ #ifndef __LINUX_BRIDGE_EBT_IP_H #define __LINUX_BRIDGE_EBT_IP_H #include #define EBT_IP_SOURCE 0x01 #define EBT_IP_DEST 0x02 #define EBT_IP_TOS 0x04 #define EBT_IP_PROTO 0x08 #define EBT_IP_SPORT 0x10 #define EBT_IP_DPORT 0x20 #define EBT_IP_ICMP 0x40 #define EBT_IP_IGMP 0x80 #define EBT_IP_MASK (EBT_IP_SOURCE | EBT_IP_DEST | EBT_IP_TOS | EBT_IP_PROTO |\ EBT_IP_SPORT | EBT_IP_DPORT | EBT_IP_ICMP | EBT_IP_IGMP) #define EBT_IP_MATCH "ip" /* the same values are used for the invflags */ struct ebt_ip_info { __be32 saddr; __be32 daddr; __be32 smsk; __be32 dmsk; __u8 tos; __u8 protocol; __u8 bitmask; __u8 invflags; union { __u16 sport[2]; __u8 icmp_type[2]; __u8 igmp_type[2]; }; union { __u16 dport[2]; __u8 icmp_code[2]; }; }; #endif linux/netfilter_bridge/ebt_pkttype.h000064400000000413151027430560013717 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_PKTTYPE_H #define __LINUX_BRIDGE_EBT_PKTTYPE_H #include struct ebt_pkttype_info { __u8 pkt_type; __u8 invert; }; #define EBT_PKTTYPE_MATCH "pkttype" #endif linux/netfilter_bridge/ebt_mark_m.h000064400000000604151027430560013467 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_MARK_M_H #define __LINUX_BRIDGE_EBT_MARK_M_H #include #define EBT_MARK_AND 0x01 #define EBT_MARK_OR 0x02 #define EBT_MARK_MASK (EBT_MARK_AND | EBT_MARK_OR) struct ebt_mark_m_info { unsigned long mark, mask; __u8 invert; __u8 bitmask; }; #define EBT_MARK_MATCH "mark_m" #endif linux/netfilter_bridge/ebtables.h000064400000022145151027430560013154 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ebtables * * Authors: * Bart De Schuymer * * ebtables.c,v 2.0, April, 2002 * * This code is strongly inspired by the iptables code which is * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling */ #ifndef __LINUX_BRIDGE_EFF_H #define __LINUX_BRIDGE_EFF_H #include #include #include #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN EBT_TABLE_MAXNAMELEN #define EBT_FUNCTION_MAXNAMELEN EBT_TABLE_MAXNAMELEN #define EBT_EXTENSION_MAXNAMELEN 31 /* verdicts >0 are "branches" */ #define EBT_ACCEPT -1 #define EBT_DROP -2 #define EBT_CONTINUE -3 #define EBT_RETURN -4 #define NUM_STANDARD_TARGETS 4 /* ebtables target modules store the verdict inside an int. We can * reclaim a part of this int for backwards compatible extensions. * The 4 lsb are more than enough to store the verdict. */ #define EBT_VERDICT_BITS 0x0000000F struct xt_match; struct xt_target; struct ebt_counter { __u64 pcnt; __u64 bcnt; }; struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; /* nr of rules in the table */ unsigned int nentries; /* total size of the entries */ unsigned int entries_size; /* start of the chains */ struct ebt_entries *hook_entry[NF_BR_NUMHOOKS]; /* nr of counters userspace expects back */ unsigned int num_counters; /* where the kernel will put the old counters */ struct ebt_counter *counters; char *entries; }; struct ebt_replace_kernel { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; /* nr of rules in the table */ unsigned int nentries; /* total size of the entries */ unsigned int entries_size; /* start of the chains */ struct ebt_entries *hook_entry[NF_BR_NUMHOOKS]; /* nr of counters userspace expects back */ unsigned int num_counters; /* where the kernel will put the old counters */ struct ebt_counter *counters; char *entries; }; struct ebt_entries { /* this field is always set to zero * See EBT_ENTRY_OR_ENTRIES. * Must be same size as ebt_entry.bitmask */ unsigned int distinguisher; /* the chain name */ char name[EBT_CHAIN_MAXNAMELEN]; /* counter offset for this chain */ unsigned int counter_offset; /* one standard (accept, drop, return) per hook */ int policy; /* nr. of entries */ unsigned int nentries; /* entry list */ char data[0] __attribute__ ((aligned (__alignof__(struct ebt_replace)))); }; /* used for the bitmask of struct ebt_entry */ /* This is a hack to make a difference between an ebt_entry struct and an * ebt_entries struct when traversing the entries from start to end. * Using this simplifies the code a lot, while still being able to use * ebt_entries. * Contrary, iptables doesn't use something like ebt_entries and therefore uses * different techniques for naming the policy and such. So, iptables doesn't * need a hack like this. */ #define EBT_ENTRY_OR_ENTRIES 0x01 /* these are the normal masks */ #define EBT_NOPROTO 0x02 #define EBT_802_3 0x04 #define EBT_SOURCEMAC 0x08 #define EBT_DESTMAC 0x10 #define EBT_F_MASK (EBT_NOPROTO | EBT_802_3 | EBT_SOURCEMAC | EBT_DESTMAC \ | EBT_ENTRY_OR_ENTRIES) #define EBT_IPROTO 0x01 #define EBT_IIN 0x02 #define EBT_IOUT 0x04 #define EBT_ISOURCE 0x8 #define EBT_IDEST 0x10 #define EBT_ILOGICALIN 0x20 #define EBT_ILOGICALOUT 0x40 #define EBT_INV_MASK (EBT_IPROTO | EBT_IIN | EBT_IOUT | EBT_ILOGICALIN \ | EBT_ILOGICALOUT | EBT_ISOURCE | EBT_IDEST) struct ebt_entry_match { union { struct { char name[EBT_EXTENSION_MAXNAMELEN]; uint8_t revision; }; struct xt_match *match; } u; /* size of data */ unsigned int match_size; unsigned char data[0] __attribute__ ((aligned (__alignof__(struct ebt_replace)))); }; struct ebt_entry_watcher { union { struct { char name[EBT_EXTENSION_MAXNAMELEN]; uint8_t revision; }; struct xt_target *watcher; } u; /* size of data */ unsigned int watcher_size; unsigned char data[0] __attribute__ ((aligned (__alignof__(struct ebt_replace)))); }; struct ebt_entry_target { union { struct { char name[EBT_EXTENSION_MAXNAMELEN]; uint8_t revision; }; struct xt_target *target; } u; /* size of data */ unsigned int target_size; unsigned char data[0] __attribute__ ((aligned (__alignof__(struct ebt_replace)))); }; #define EBT_STANDARD_TARGET "standard" struct ebt_standard_target { struct ebt_entry_target target; int verdict; }; /* one entry */ struct ebt_entry { /* this needs to be the first field */ unsigned int bitmask; unsigned int invflags; __be16 ethproto; /* the physical in-dev */ char in[IFNAMSIZ]; /* the logical in-dev */ char logical_in[IFNAMSIZ]; /* the physical out-dev */ char out[IFNAMSIZ]; /* the logical out-dev */ char logical_out[IFNAMSIZ]; unsigned char sourcemac[ETH_ALEN]; unsigned char sourcemsk[ETH_ALEN]; unsigned char destmac[ETH_ALEN]; unsigned char destmsk[ETH_ALEN]; /* sizeof ebt_entry + matches */ unsigned int watchers_offset; /* sizeof ebt_entry + matches + watchers */ unsigned int target_offset; /* sizeof ebt_entry + matches + watchers + target */ unsigned int next_offset; unsigned char elems[0] __attribute__ ((aligned (__alignof__(struct ebt_replace)))); }; static __inline__ struct ebt_entry_target * ebt_get_target(struct ebt_entry *e) { return (void *)e + e->target_offset; } /* {g,s}etsockopt numbers */ #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_SET_COUNTERS (EBT_SO_SET_ENTRIES+1) #define EBT_SO_SET_MAX (EBT_SO_SET_COUNTERS+1) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO+1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES+1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO+1) #define EBT_SO_GET_MAX (EBT_SO_GET_INIT_ENTRIES+1) /* blatently stolen from ip_tables.h * fn returns 0 to continue iteration */ #define EBT_MATCH_ITERATE(e, fn, args...) \ ({ \ unsigned int __i; \ int __ret = 0; \ struct ebt_entry_match *__match; \ \ for (__i = sizeof(struct ebt_entry); \ __i < (e)->watchers_offset; \ __i += __match->match_size + \ sizeof(struct ebt_entry_match)) { \ __match = (void *)(e) + __i; \ \ __ret = fn(__match , ## args); \ if (__ret != 0) \ break; \ } \ if (__ret == 0) { \ if (__i != (e)->watchers_offset) \ __ret = -EINVAL; \ } \ __ret; \ }) #define EBT_WATCHER_ITERATE(e, fn, args...) \ ({ \ unsigned int __i; \ int __ret = 0; \ struct ebt_entry_watcher *__watcher; \ \ for (__i = e->watchers_offset; \ __i < (e)->target_offset; \ __i += __watcher->watcher_size + \ sizeof(struct ebt_entry_watcher)) { \ __watcher = (void *)(e) + __i; \ \ __ret = fn(__watcher , ## args); \ if (__ret != 0) \ break; \ } \ if (__ret == 0) { \ if (__i != (e)->target_offset) \ __ret = -EINVAL; \ } \ __ret; \ }) #define EBT_ENTRY_ITERATE(entries, size, fn, args...) \ ({ \ unsigned int __i; \ int __ret = 0; \ struct ebt_entry *__entry; \ \ for (__i = 0; __i < (size);) { \ __entry = (void *)(entries) + __i; \ __ret = fn(__entry , ## args); \ if (__ret != 0) \ break; \ if (__entry->bitmask != 0) \ __i += __entry->next_offset; \ else \ __i += sizeof(struct ebt_entries); \ } \ if (__ret == 0) { \ if (__i != (size)) \ __ret = -EINVAL; \ } \ __ret; \ }) #endif /* __LINUX_BRIDGE_EFF_H */ linux/netfilter_bridge/ebt_nat.h000064400000000603151027430560013002 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_NAT_H #define __LINUX_BRIDGE_EBT_NAT_H #include #define NAT_ARP_BIT (0x00000010) struct ebt_nat_info { unsigned char mac[ETH_ALEN]; /* EBT_ACCEPT, EBT_DROP, EBT_CONTINUE or EBT_RETURN */ int target; }; #define EBT_SNAT_TARGET "snat" #define EBT_DNAT_TARGET "dnat" #endif linux/netfilter_bridge/ebt_802_3.h000064400000002372151027430560012760 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_802_3_H #define __LINUX_BRIDGE_EBT_802_3_H #include #include #define EBT_802_3_SAP 0x01 #define EBT_802_3_TYPE 0x02 #define EBT_802_3_MATCH "802_3" /* * If frame has DSAP/SSAP value 0xaa you must check the SNAP type * to discover what kind of packet we're carrying. */ #define CHECK_TYPE 0xaa /* * Control field may be one or two bytes. If the first byte has * the value 0x03 then the entire length is one byte, otherwise it is two. * One byte controls are used in Unnumbered Information frames. * Two byte controls are used in Numbered Information frames. */ #define IS_UI 0x03 #define EBT_802_3_MASK (EBT_802_3_SAP | EBT_802_3_TYPE | EBT_802_3) /* ui has one byte ctrl, ni has two */ struct hdr_ui { __u8 dsap; __u8 ssap; __u8 ctrl; __u8 orig[3]; __be16 type; }; struct hdr_ni { __u8 dsap; __u8 ssap; __be16 ctrl; __u8 orig[3]; __be16 type; }; struct ebt_802_3_hdr { __u8 daddr[ETH_ALEN]; __u8 saddr[ETH_ALEN]; __be16 len; union { struct hdr_ui ui; struct hdr_ni ni; } llc; }; struct ebt_802_3_info { __u8 sap; __be16 type; __u8 bitmask; __u8 invflags; }; #endif /* __LINUX_BRIDGE_EBT_802_3_H */ linux/netfilter_bridge/ebt_limit.h000064400000001150151027430560013334 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_LIMIT_H #define __LINUX_BRIDGE_EBT_LIMIT_H #include #define EBT_LIMIT_MATCH "limit" /* timings are in milliseconds. */ #define EBT_LIMIT_SCALE 10000 /* 1/10,000 sec period => max of 10,000/sec. Min rate is then 429490 seconds, or one every 59 hours. */ struct ebt_limit_info { __u32 avg; /* Average secs between packets * scale */ __u32 burst; /* Period multiplier for upper limit. */ /* Used internally by the kernel */ unsigned long prev; __u32 credit; __u32 credit_cap, cost; }; #endif linux/netfilter_bridge/ebt_vlan.h000064400000001317151027430560013163 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_VLAN_H #define __LINUX_BRIDGE_EBT_VLAN_H #include #define EBT_VLAN_ID 0x01 #define EBT_VLAN_PRIO 0x02 #define EBT_VLAN_ENCAP 0x04 #define EBT_VLAN_MASK (EBT_VLAN_ID | EBT_VLAN_PRIO | EBT_VLAN_ENCAP) #define EBT_VLAN_MATCH "vlan" struct ebt_vlan_info { __u16 id; /* VLAN ID {1-4095} */ __u8 prio; /* VLAN User Priority {0-7} */ __be16 encap; /* VLAN Encapsulated frame code {0-65535} */ __u8 bitmask; /* Args bitmask bit 1=1 - ID arg, bit 2=1 User-Priority arg, bit 3=1 encap*/ __u8 invflags; /* Inverse bitmask bit 1=1 - inversed ID arg, bit 2=1 - inversed Pirority arg */ }; #endif linux/netfilter_bridge/ebt_arpreply.h000064400000000441151027430560014056 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_ARPREPLY_H #define __LINUX_BRIDGE_EBT_ARPREPLY_H #include struct ebt_arpreply_info { unsigned char mac[ETH_ALEN]; int target; }; #define EBT_ARPREPLY_TARGET "arpreply" #endif linux/netfilter_bridge/ebt_nflog.h000064400000000776151027430560013340 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_NFLOG_H #define __LINUX_BRIDGE_EBT_NFLOG_H #include #define EBT_NFLOG_MASK 0x0 #define EBT_NFLOG_PREFIX_SIZE 64 #define EBT_NFLOG_WATCHER "nflog" #define EBT_NFLOG_DEFAULT_GROUP 0x1 #define EBT_NFLOG_DEFAULT_THRESHOLD 1 struct ebt_nflog_info { __u32 len; __u16 group; __u16 threshold; __u16 flags; __u16 pad; char prefix[EBT_NFLOG_PREFIX_SIZE]; }; #endif /* __LINUX_BRIDGE_EBT_NFLOG_H */ linux/netfilter_bridge/ebt_stp.h000064400000002126151027430560013030 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_STP_H #define __LINUX_BRIDGE_EBT_STP_H #include #define EBT_STP_TYPE 0x0001 #define EBT_STP_FLAGS 0x0002 #define EBT_STP_ROOTPRIO 0x0004 #define EBT_STP_ROOTADDR 0x0008 #define EBT_STP_ROOTCOST 0x0010 #define EBT_STP_SENDERPRIO 0x0020 #define EBT_STP_SENDERADDR 0x0040 #define EBT_STP_PORT 0x0080 #define EBT_STP_MSGAGE 0x0100 #define EBT_STP_MAXAGE 0x0200 #define EBT_STP_HELLOTIME 0x0400 #define EBT_STP_FWDD 0x0800 #define EBT_STP_MASK 0x0fff #define EBT_STP_CONFIG_MASK 0x0ffe #define EBT_STP_MATCH "stp" struct ebt_stp_config_info { __u8 flags; __u16 root_priol, root_priou; char root_addr[6], root_addrmsk[6]; __u32 root_costl, root_costu; __u16 sender_priol, sender_priou; char sender_addr[6], sender_addrmsk[6]; __u16 portl, portu; __u16 msg_agel, msg_ageu; __u16 max_agel, max_ageu; __u16 hello_timel, hello_timeu; __u16 forward_delayl, forward_delayu; }; struct ebt_stp_info { __u8 type; struct ebt_stp_config_info config; __u16 bitmask; __u16 invflags; }; #endif linux/netfilter_bridge/ebt_redirect.h000064400000000436151027430560014025 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_REDIRECT_H #define __LINUX_BRIDGE_EBT_REDIRECT_H struct ebt_redirect_info { /* EBT_ACCEPT, EBT_DROP, EBT_CONTINUE or EBT_RETURN */ int target; }; #define EBT_REDIRECT_TARGET "redirect" #endif linux/netfilter_bridge/ebt_among.h000064400000003773151027430560013334 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_AMONG_H #define __LINUX_BRIDGE_EBT_AMONG_H #include #define EBT_AMONG_DST 0x01 #define EBT_AMONG_SRC 0x02 /* Grzegorz Borowiak 2003 * * Write-once-read-many hash table, used for checking if a given * MAC address belongs to a set or not and possibly for checking * if it is related with a given IPv4 address. * * The hash value of an address is its last byte. * * In real-world ethernet addresses, values of the last byte are * evenly distributed and there is no need to consider other bytes. * It would only slow the routines down. * * For MAC address comparison speedup reasons, we introduce a trick. * MAC address is mapped onto an array of two 32-bit integers. * This pair of integers is compared with MAC addresses in the * hash table, which are stored also in form of pairs of integers * (in `cmp' array). This is quick as it requires only two elementary * number comparisons in worst case. Further, we take advantage of * fact that entropy of 3 last bytes of address is larger than entropy * of 3 first bytes. So first we compare 4 last bytes of addresses and * if they are the same we compare 2 first. * * Yes, it is a memory overhead, but in 2003 AD, who cares? */ struct ebt_mac_wormhash_tuple { __u32 cmp[2]; __be32 ip; }; struct ebt_mac_wormhash { int table[257]; int poolsize; struct ebt_mac_wormhash_tuple pool[0]; }; #define ebt_mac_wormhash_size(x) ((x) ? sizeof(struct ebt_mac_wormhash) \ + (x)->poolsize * sizeof(struct ebt_mac_wormhash_tuple) : 0) struct ebt_among_info { int wh_dst_ofs; int wh_src_ofs; int bitmask; }; #define EBT_AMONG_DST_NEG 0x1 #define EBT_AMONG_SRC_NEG 0x2 #define ebt_among_wh_dst(x) ((x)->wh_dst_ofs ? \ (struct ebt_mac_wormhash*)((char*)(x) + (x)->wh_dst_ofs) : NULL) #define ebt_among_wh_src(x) ((x)->wh_src_ofs ? \ (struct ebt_mac_wormhash*)((char*)(x) + (x)->wh_src_ofs) : NULL) #define EBT_AMONG_MATCH "among" #endif linux/netfilter_bridge/ebt_ip6.h000064400000002040151027430560012713 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ebt_ip6 * * Authors: * Kuo-Lang Tseng * Manohar Castelino * * Jan 11, 2008 * */ #ifndef __LINUX_BRIDGE_EBT_IP6_H #define __LINUX_BRIDGE_EBT_IP6_H #include #include #define EBT_IP6_SOURCE 0x01 #define EBT_IP6_DEST 0x02 #define EBT_IP6_TCLASS 0x04 #define EBT_IP6_PROTO 0x08 #define EBT_IP6_SPORT 0x10 #define EBT_IP6_DPORT 0x20 #define EBT_IP6_ICMP6 0x40 #define EBT_IP6_MASK (EBT_IP6_SOURCE | EBT_IP6_DEST | EBT_IP6_TCLASS |\ EBT_IP6_PROTO | EBT_IP6_SPORT | EBT_IP6_DPORT | \ EBT_IP6_ICMP6) #define EBT_IP6_MATCH "ip6" /* the same values are used for the invflags */ struct ebt_ip6_info { struct in6_addr saddr; struct in6_addr daddr; struct in6_addr smsk; struct in6_addr dmsk; __u8 tclass; __u8 protocol; __u8 bitmask; __u8 invflags; union { __u16 sport[2]; __u8 icmpv6_type[2]; }; union { __u16 dport[2]; __u8 icmpv6_code[2]; }; }; #endif linux/netfilter_bridge/ebt_arp.h000064400000001604151027430560013004 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_ARP_H #define __LINUX_BRIDGE_EBT_ARP_H #include #include #define EBT_ARP_OPCODE 0x01 #define EBT_ARP_HTYPE 0x02 #define EBT_ARP_PTYPE 0x04 #define EBT_ARP_SRC_IP 0x08 #define EBT_ARP_DST_IP 0x10 #define EBT_ARP_SRC_MAC 0x20 #define EBT_ARP_DST_MAC 0x40 #define EBT_ARP_GRAT 0x80 #define EBT_ARP_MASK (EBT_ARP_OPCODE | EBT_ARP_HTYPE | EBT_ARP_PTYPE | \ EBT_ARP_SRC_IP | EBT_ARP_DST_IP | EBT_ARP_SRC_MAC | EBT_ARP_DST_MAC | \ EBT_ARP_GRAT) #define EBT_ARP_MATCH "arp" struct ebt_arp_info { __be16 htype; __be16 ptype; __be16 opcode; __be32 saddr; __be32 smsk; __be32 daddr; __be32 dmsk; unsigned char smaddr[ETH_ALEN]; unsigned char smmsk[ETH_ALEN]; unsigned char dmaddr[ETH_ALEN]; unsigned char dmmsk[ETH_ALEN]; __u8 bitmask; __u8 invflags; }; #endif linux/netfilter_bridge/ebt_log.h000064400000001032151027430560012776 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_EBT_LOG_H #define __LINUX_BRIDGE_EBT_LOG_H #include #define EBT_LOG_IP 0x01 /* if the frame is made by ip, log the ip information */ #define EBT_LOG_ARP 0x02 #define EBT_LOG_NFLOG 0x04 #define EBT_LOG_IP6 0x08 #define EBT_LOG_MASK (EBT_LOG_IP | EBT_LOG_ARP | EBT_LOG_IP6) #define EBT_LOG_PREFIX_SIZE 30 #define EBT_LOG_WATCHER "log" struct ebt_log_info { __u8 loglevel; __u8 prefix[EBT_LOG_PREFIX_SIZE]; __u32 bitmask; }; #endif linux/dm-ioctl.h000064400000026210151027430560007570 0ustar00/* SPDX-License-Identifier: LGPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (C) 2001 - 2003 Sistina Software (UK) Limited. * Copyright (C) 2004 - 2009 Red Hat, Inc. All rights reserved. * * This file is released under the LGPL. */ #ifndef _LINUX_DM_IOCTL_V4_H #define _LINUX_DM_IOCTL_V4_H #include #define DM_DIR "mapper" /* Slashes not supported */ #define DM_CONTROL_NODE "control" #define DM_MAX_TYPE_NAME 16 #define DM_NAME_LEN 128 #define DM_UUID_LEN 129 /* * A traditional ioctl interface for the device mapper. * * Each device can have two tables associated with it, an * 'active' table which is the one currently used by io passing * through the device, and an 'inactive' one which is a table * that is being prepared as a replacement for the 'active' one. * * DM_VERSION: * Just get the version information for the ioctl interface. * * DM_REMOVE_ALL: * Remove all dm devices, destroy all tables. Only really used * for debug. * * DM_LIST_DEVICES: * Get a list of all the dm device names. * * DM_DEV_CREATE: * Create a new device, neither the 'active' or 'inactive' table * slots will be filled. The device will be in suspended state * after creation, however any io to the device will get errored * since it will be out-of-bounds. * * DM_DEV_REMOVE: * Remove a device, destroy any tables. * * DM_DEV_RENAME: * Rename a device or set its uuid if none was previously supplied. * * DM_SUSPEND: * This performs both suspend and resume, depending which flag is * passed in. * Suspend: This command will not return until all pending io to * the device has completed. Further io will be deferred until * the device is resumed. * Resume: It is no longer an error to issue this command on an * unsuspended device. If a table is present in the 'inactive' * slot, it will be moved to the active slot, then the old table * from the active slot will be _destroyed_. Finally the device * is resumed. * * DM_DEV_STATUS: * Retrieves the status for the table in the 'active' slot. * * DM_DEV_WAIT: * Wait for a significant event to occur to the device. This * could either be caused by an event triggered by one of the * targets of the table in the 'active' slot, or a table change. * * DM_TABLE_LOAD: * Load a table into the 'inactive' slot for the device. The * device does _not_ need to be suspended prior to this command. * * DM_TABLE_CLEAR: * Destroy any table in the 'inactive' slot (ie. abort). * * DM_TABLE_DEPS: * Return a set of device dependencies for the 'active' table. * * DM_TABLE_STATUS: * Return the targets status for the 'active' table. * * DM_TARGET_MSG: * Pass a message string to the target at a specific offset of a device. * * DM_DEV_SET_GEOMETRY: * Set the geometry of a device by passing in a string in this format: * * "cylinders heads sectors_per_track start_sector" * * Beware that CHS geometry is nearly obsolete and only provided * for compatibility with dm devices that can be booted by a PC * BIOS. See struct hd_geometry for range limits. Also note that * the geometry is erased if the device size changes. */ /* * All ioctl arguments consist of a single chunk of memory, with * this structure at the start. If a uuid is specified any * lookup (eg. for a DM_INFO) will be done on that, *not* the * name. */ struct dm_ioctl { /* * The version number is made up of three parts: * major - no backward or forward compatibility, * minor - only backwards compatible, * patch - both backwards and forwards compatible. * * All clients of the ioctl interface should fill in the * version number of the interface that they were * compiled with. * * All recognised ioctl commands (ie. those that don't * return -ENOTTY) fill out this field, even if the * command failed. */ __u32 version[3]; /* in/out */ __u32 data_size; /* total size of data passed in * including this struct */ __u32 data_start; /* offset to start of data * relative to start of this struct */ __u32 target_count; /* in/out */ __s32 open_count; /* out */ __u32 flags; /* in/out */ /* * event_nr holds either the event number (input and output) or the * udev cookie value (input only). * The DM_DEV_WAIT ioctl takes an event number as input. * The DM_SUSPEND, DM_DEV_REMOVE and DM_DEV_RENAME ioctls * use the field as a cookie to return in the DM_COOKIE * variable with the uevents they issue. * For output, the ioctls return the event number, not the cookie. */ __u32 event_nr; /* in/out */ __u32 padding; __u64 dev; /* in/out */ char name[DM_NAME_LEN]; /* device name */ char uuid[DM_UUID_LEN]; /* unique identifier for * the block device */ char data[7]; /* padding or data */ }; /* * Used to specify tables. These structures appear after the * dm_ioctl. */ struct dm_target_spec { __u64 sector_start; __u64 length; __s32 status; /* used when reading from kernel only */ /* * Location of the next dm_target_spec. * - When specifying targets on a DM_TABLE_LOAD command, this value is * the number of bytes from the start of the "current" dm_target_spec * to the start of the "next" dm_target_spec. * - When retrieving targets on a DM_TABLE_STATUS command, this value * is the number of bytes from the start of the first dm_target_spec * (that follows the dm_ioctl struct) to the start of the "next" * dm_target_spec. */ __u32 next; char target_type[DM_MAX_TYPE_NAME]; /* * Parameter string starts immediately after this object. * Be careful to add padding after string to ensure correct * alignment of subsequent dm_target_spec. */ }; /* * Used to retrieve the target dependencies. */ struct dm_target_deps { __u32 count; /* Array size */ __u32 padding; /* unused */ __u64 dev[0]; /* out */ }; /* * Used to get a list of all dm devices. */ struct dm_name_list { __u64 dev; __u32 next; /* offset to the next record from the _start_ of this */ char name[0]; /* * The following members can be accessed by taking a pointer that * points immediately after the terminating zero character in "name" * and aligning this pointer to next 8-byte boundary. * Uuid is present if the flag DM_NAME_LIST_FLAG_HAS_UUID is set. * * __u32 event_nr; * __u32 flags; * char uuid[0]; */ }; #define DM_NAME_LIST_FLAG_HAS_UUID 1 #define DM_NAME_LIST_FLAG_DOESNT_HAVE_UUID 2 /* * Used to retrieve the target versions */ struct dm_target_versions { __u32 next; __u32 version[3]; char name[0]; }; /* * Used to pass message to a target */ struct dm_target_msg { __u64 sector; /* Device sector */ char message[0]; }; /* * If you change this make sure you make the corresponding change * to dm-ioctl.c:lookup_ioctl() */ enum { /* Top level cmds */ DM_VERSION_CMD = 0, DM_REMOVE_ALL_CMD, DM_LIST_DEVICES_CMD, /* device level cmds */ DM_DEV_CREATE_CMD, DM_DEV_REMOVE_CMD, DM_DEV_RENAME_CMD, DM_DEV_SUSPEND_CMD, DM_DEV_STATUS_CMD, DM_DEV_WAIT_CMD, /* Table level cmds */ DM_TABLE_LOAD_CMD, DM_TABLE_CLEAR_CMD, DM_TABLE_DEPS_CMD, DM_TABLE_STATUS_CMD, /* Added later */ DM_LIST_VERSIONS_CMD, DM_TARGET_MSG_CMD, DM_DEV_SET_GEOMETRY_CMD, DM_DEV_ARM_POLL_CMD, DM_GET_TARGET_VERSION_CMD, }; #define DM_IOCTL 0xfd #define DM_VERSION _IOWR(DM_IOCTL, DM_VERSION_CMD, struct dm_ioctl) #define DM_REMOVE_ALL _IOWR(DM_IOCTL, DM_REMOVE_ALL_CMD, struct dm_ioctl) #define DM_LIST_DEVICES _IOWR(DM_IOCTL, DM_LIST_DEVICES_CMD, struct dm_ioctl) #define DM_DEV_CREATE _IOWR(DM_IOCTL, DM_DEV_CREATE_CMD, struct dm_ioctl) #define DM_DEV_REMOVE _IOWR(DM_IOCTL, DM_DEV_REMOVE_CMD, struct dm_ioctl) #define DM_DEV_RENAME _IOWR(DM_IOCTL, DM_DEV_RENAME_CMD, struct dm_ioctl) #define DM_DEV_SUSPEND _IOWR(DM_IOCTL, DM_DEV_SUSPEND_CMD, struct dm_ioctl) #define DM_DEV_STATUS _IOWR(DM_IOCTL, DM_DEV_STATUS_CMD, struct dm_ioctl) #define DM_DEV_WAIT _IOWR(DM_IOCTL, DM_DEV_WAIT_CMD, struct dm_ioctl) #define DM_DEV_ARM_POLL _IOWR(DM_IOCTL, DM_DEV_ARM_POLL_CMD, struct dm_ioctl) #define DM_TABLE_LOAD _IOWR(DM_IOCTL, DM_TABLE_LOAD_CMD, struct dm_ioctl) #define DM_TABLE_CLEAR _IOWR(DM_IOCTL, DM_TABLE_CLEAR_CMD, struct dm_ioctl) #define DM_TABLE_DEPS _IOWR(DM_IOCTL, DM_TABLE_DEPS_CMD, struct dm_ioctl) #define DM_TABLE_STATUS _IOWR(DM_IOCTL, DM_TABLE_STATUS_CMD, struct dm_ioctl) #define DM_LIST_VERSIONS _IOWR(DM_IOCTL, DM_LIST_VERSIONS_CMD, struct dm_ioctl) #define DM_GET_TARGET_VERSION _IOWR(DM_IOCTL, DM_GET_TARGET_VERSION_CMD, struct dm_ioctl) #define DM_TARGET_MSG _IOWR(DM_IOCTL, DM_TARGET_MSG_CMD, struct dm_ioctl) #define DM_DEV_SET_GEOMETRY _IOWR(DM_IOCTL, DM_DEV_SET_GEOMETRY_CMD, struct dm_ioctl) #define DM_VERSION_MAJOR 4 #define DM_VERSION_MINOR 46 #define DM_VERSION_PATCHLEVEL 0 #define DM_VERSION_EXTRA "-ioctl (2022-02-22)" /* Status bits */ #define DM_READONLY_FLAG (1 << 0) /* In/Out */ #define DM_SUSPEND_FLAG (1 << 1) /* In/Out */ #define DM_PERSISTENT_DEV_FLAG (1 << 3) /* In */ /* * Flag passed into ioctl STATUS command to get table information * rather than current status. */ #define DM_STATUS_TABLE_FLAG (1 << 4) /* In */ /* * Flags that indicate whether a table is present in either of * the two table slots that a device has. */ #define DM_ACTIVE_PRESENT_FLAG (1 << 5) /* Out */ #define DM_INACTIVE_PRESENT_FLAG (1 << 6) /* Out */ /* * Indicates that the buffer passed in wasn't big enough for the * results. */ #define DM_BUFFER_FULL_FLAG (1 << 8) /* Out */ /* * This flag is now ignored. */ #define DM_SKIP_BDGET_FLAG (1 << 9) /* In */ /* * Set this to avoid attempting to freeze any filesystem when suspending. */ #define DM_SKIP_LOCKFS_FLAG (1 << 10) /* In */ /* * Set this to suspend without flushing queued ios. * Also disables flushing uncommitted changes in the thin target before * generating statistics for DM_TABLE_STATUS and DM_DEV_WAIT. */ #define DM_NOFLUSH_FLAG (1 << 11) /* In */ /* * If set, any table information returned will relate to the inactive * table instead of the live one. Always check DM_INACTIVE_PRESENT_FLAG * is set before using the data returned. */ #define DM_QUERY_INACTIVE_TABLE_FLAG (1 << 12) /* In */ /* * If set, a uevent was generated for which the caller may need to wait. */ #define DM_UEVENT_GENERATED_FLAG (1 << 13) /* Out */ /* * If set, rename changes the uuid not the name. Only permitted * if no uuid was previously supplied: an existing uuid cannot be changed. */ #define DM_UUID_FLAG (1 << 14) /* In */ /* * If set, all buffers are wiped after use. Use when sending * or requesting sensitive data such as an encryption key. */ #define DM_SECURE_DATA_FLAG (1 << 15) /* In */ /* * If set, a message generated output data. */ #define DM_DATA_OUT_FLAG (1 << 16) /* Out */ /* * If set with DM_DEV_REMOVE or DM_REMOVE_ALL this indicates that if * the device cannot be removed immediately because it is still in use * it should instead be scheduled for removal when it gets closed. * * On return from DM_DEV_REMOVE, DM_DEV_STATUS or other ioctls, this * flag indicates that the device is scheduled to be removed when it * gets closed. */ #define DM_DEFERRED_REMOVE (1 << 17) /* In/Out */ /* * If set, the device is suspended internally. */ #define DM_INTERNAL_SUSPEND_FLAG (1 << 18) /* Out */ #endif /* _LINUX_DM_IOCTL_H */ linux/adfs_fs.h000064400000001650151027430560007466 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ADFS_FS_H #define _ADFS_FS_H #include #include /* * Disc Record at disc address 0xc00 */ struct adfs_discrecord { __u8 log2secsize; __u8 secspertrack; __u8 heads; __u8 density; __u8 idlen; __u8 log2bpmb; __u8 skew; __u8 bootoption; __u8 lowsector; __u8 nzones; __le16 zone_spare; __le32 root; __le32 disc_size; __le16 disc_id; __u8 disc_name[10]; __le32 disc_type; __le32 disc_size_high; __u8 log2sharesize:4; __u8 unused40:4; __u8 big_flag:1; __u8 unused41:1; __u8 nzones_high; __le32 format_version; __le32 root_size; __u8 unused52[60 - 52]; }; #define ADFS_DISCRECORD (0xc00) #define ADFS_DR_OFFSET (0x1c0) #define ADFS_DR_SIZE 60 #define ADFS_DR_SIZE_BITS (ADFS_DR_SIZE << 3) #endif /* _ADFS_FS_H */ linux/firewire-constants.h000064400000006237151027430560011715 0ustar00/* * IEEE 1394 constants. * * Copyright (C) 2005-2007 Kristian Hoegsberg * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef _LINUX_FIREWIRE_CONSTANTS_H #define _LINUX_FIREWIRE_CONSTANTS_H #define TCODE_WRITE_QUADLET_REQUEST 0x0 #define TCODE_WRITE_BLOCK_REQUEST 0x1 #define TCODE_WRITE_RESPONSE 0x2 #define TCODE_READ_QUADLET_REQUEST 0x4 #define TCODE_READ_BLOCK_REQUEST 0x5 #define TCODE_READ_QUADLET_RESPONSE 0x6 #define TCODE_READ_BLOCK_RESPONSE 0x7 #define TCODE_CYCLE_START 0x8 #define TCODE_LOCK_REQUEST 0x9 #define TCODE_STREAM_DATA 0xa #define TCODE_LOCK_RESPONSE 0xb #define EXTCODE_MASK_SWAP 0x1 #define EXTCODE_COMPARE_SWAP 0x2 #define EXTCODE_FETCH_ADD 0x3 #define EXTCODE_LITTLE_ADD 0x4 #define EXTCODE_BOUNDED_ADD 0x5 #define EXTCODE_WRAP_ADD 0x6 #define EXTCODE_VENDOR_DEPENDENT 0x7 /* Linux firewire-core (Juju) specific tcodes */ #define TCODE_LOCK_MASK_SWAP (0x10 | EXTCODE_MASK_SWAP) #define TCODE_LOCK_COMPARE_SWAP (0x10 | EXTCODE_COMPARE_SWAP) #define TCODE_LOCK_FETCH_ADD (0x10 | EXTCODE_FETCH_ADD) #define TCODE_LOCK_LITTLE_ADD (0x10 | EXTCODE_LITTLE_ADD) #define TCODE_LOCK_BOUNDED_ADD (0x10 | EXTCODE_BOUNDED_ADD) #define TCODE_LOCK_WRAP_ADD (0x10 | EXTCODE_WRAP_ADD) #define TCODE_LOCK_VENDOR_DEPENDENT (0x10 | EXTCODE_VENDOR_DEPENDENT) #define RCODE_COMPLETE 0x0 #define RCODE_CONFLICT_ERROR 0x4 #define RCODE_DATA_ERROR 0x5 #define RCODE_TYPE_ERROR 0x6 #define RCODE_ADDRESS_ERROR 0x7 /* Linux firewire-core (Juju) specific rcodes */ #define RCODE_SEND_ERROR 0x10 #define RCODE_CANCELLED 0x11 #define RCODE_BUSY 0x12 #define RCODE_GENERATION 0x13 #define RCODE_NO_ACK 0x14 #define SCODE_100 0x0 #define SCODE_200 0x1 #define SCODE_400 0x2 #define SCODE_800 0x3 #define SCODE_1600 0x4 #define SCODE_3200 0x5 #define SCODE_BETA 0x3 #define ACK_COMPLETE 0x1 #define ACK_PENDING 0x2 #define ACK_BUSY_X 0x4 #define ACK_BUSY_A 0x5 #define ACK_BUSY_B 0x6 #define ACK_DATA_ERROR 0xd #define ACK_TYPE_ERROR 0xe #define RETRY_1 0x00 #define RETRY_X 0x01 #define RETRY_A 0x02 #define RETRY_B 0x03 #endif /* _LINUX_FIREWIRE_CONSTANTS_H */ linux/wait.h000064400000001252151027430560007023 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_WAIT_H #define _LINUX_WAIT_H #define WNOHANG 0x00000001 #define WUNTRACED 0x00000002 #define WSTOPPED WUNTRACED #define WEXITED 0x00000004 #define WCONTINUED 0x00000008 #define WNOWAIT 0x01000000 /* Don't reap, just poll status. */ #define __WNOTHREAD 0x20000000 /* Don't wait on children of other threads in this group */ #define __WALL 0x40000000 /* Wait on all children, regardless of type */ #define __WCLONE 0x80000000 /* Wait only on non-SIGCHLD children */ /* First argument to waitid: */ #define P_ALL 0 #define P_PID 1 #define P_PGID 2 #define P_PIDFD 3 #endif /* _LINUX_WAIT_H */ linux/virtio_ring.h000064400000016511151027430560010416 0ustar00#ifndef _LINUX_VIRTIO_RING_H #define _LINUX_VIRTIO_RING_H /* An interface for efficient virtio implementation, currently for use by KVM, * but hopefully others soon. Do NOT change this since it will * break existing servers and clients. * * This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Copyright Rusty Russell IBM Corporation 2007. */ #include #include #include /* This marks a buffer as continuing via the next field. */ #define VRING_DESC_F_NEXT 1 /* This marks a buffer as write-only (otherwise read-only). */ #define VRING_DESC_F_WRITE 2 /* This means the buffer contains a list of buffer descriptors. */ #define VRING_DESC_F_INDIRECT 4 /* * Mark a descriptor as available or used in packed ring. * Notice: they are defined as shifts instead of shifted values. */ #define VRING_PACKED_DESC_F_AVAIL 7 #define VRING_PACKED_DESC_F_USED 15 /* The Host uses this in used->flags to advise the Guest: don't kick me when * you add a buffer. It's unreliable, so it's simply an optimization. Guest * will still kick if it's out of buffers. */ #define VRING_USED_F_NO_NOTIFY 1 /* The Guest uses this in avail->flags to advise the Host: don't interrupt me * when you consume a buffer. It's unreliable, so it's simply an * optimization. */ #define VRING_AVAIL_F_NO_INTERRUPT 1 /* Enable events in packed ring. */ #define VRING_PACKED_EVENT_FLAG_ENABLE 0x0 /* Disable events in packed ring. */ #define VRING_PACKED_EVENT_FLAG_DISABLE 0x1 /* * Enable events for a specific descriptor in packed ring. * (as specified by Descriptor Ring Change Event Offset/Wrap Counter). * Only valid if VIRTIO_RING_F_EVENT_IDX has been negotiated. */ #define VRING_PACKED_EVENT_FLAG_DESC 0x2 /* * Wrap counter bit shift in event suppression structure * of packed ring. */ #define VRING_PACKED_EVENT_F_WRAP_CTR 15 /* We support indirect buffer descriptors */ #define VIRTIO_RING_F_INDIRECT_DESC 28 /* The Guest publishes the used index for which it expects an interrupt * at the end of the avail ring. Host should ignore the avail->flags field. */ /* The Host publishes the avail index for which it expects a kick * at the end of the used ring. Guest should ignore the used->flags field. */ #define VIRTIO_RING_F_EVENT_IDX 29 /* Virtio ring descriptors: 16 bytes. These can chain together via "next". */ struct vring_desc { /* Address (guest-physical). */ __virtio64 addr; /* Length. */ __virtio32 len; /* The flags as indicated above. */ __virtio16 flags; /* We chain unused descriptors via this, too */ __virtio16 next; }; struct vring_avail { __virtio16 flags; __virtio16 idx; __virtio16 ring[]; }; /* u32 is used here for ids for padding reasons. */ struct vring_used_elem { /* Index of start of used descriptor chain. */ __virtio32 id; /* Total length of the descriptor chain which was used (written to) */ __virtio32 len; }; struct vring_used { __virtio16 flags; __virtio16 idx; struct vring_used_elem ring[]; }; struct vring { unsigned int num; struct vring_desc *desc; struct vring_avail *avail; struct vring_used *used; }; /* Alignment requirements for vring elements. * When using pre-virtio 1.0 layout, these fall out naturally. */ #define VRING_AVAIL_ALIGN_SIZE 2 #define VRING_USED_ALIGN_SIZE 4 #define VRING_DESC_ALIGN_SIZE 16 #ifndef VIRTIO_RING_NO_LEGACY /* The standard layout for the ring is a continuous chunk of memory which looks * like this. We assume num is a power of 2. * * struct vring * { * // The actual descriptors (16 bytes each) * struct vring_desc desc[num]; * * // A ring of available descriptor heads with free-running index. * __virtio16 avail_flags; * __virtio16 avail_idx; * __virtio16 available[num]; * __virtio16 used_event_idx; * * // Padding to the next align boundary. * char pad[]; * * // A ring of used descriptor heads with free-running index. * __virtio16 used_flags; * __virtio16 used_idx; * struct vring_used_elem used[num]; * __virtio16 avail_event_idx; * }; */ /* We publish the used event index at the end of the available ring, and vice * versa. They are at the end for backwards compatibility. */ #define vring_used_event(vr) ((vr)->avail->ring[(vr)->num]) #define vring_avail_event(vr) (*(__virtio16 *)&(vr)->used->ring[(vr)->num]) static __inline__ void vring_init(struct vring *vr, unsigned int num, void *p, unsigned long align) { vr->num = num; vr->desc = p; vr->avail = p + num*sizeof(struct vring_desc); vr->used = (void *)(((uintptr_t)&vr->avail->ring[num] + sizeof(__virtio16) + align-1) & ~(align - 1)); } static __inline__ unsigned vring_size(unsigned int num, unsigned long align) { return ((sizeof(struct vring_desc) * num + sizeof(__virtio16) * (3 + num) + align - 1) & ~(align - 1)) + sizeof(__virtio16) * 3 + sizeof(struct vring_used_elem) * num; } #endif /* VIRTIO_RING_NO_LEGACY */ /* The following is used with USED_EVENT_IDX and AVAIL_EVENT_IDX */ /* Assuming a given event_idx value from the other side, if * we have just incremented index from old to new_idx, * should we trigger an event? */ static __inline__ int vring_need_event(__u16 event_idx, __u16 new_idx, __u16 old) { /* Note: Xen has similar logic for notification hold-off * in include/xen/interface/io/ring.h with req_event and req_prod * corresponding to event_idx + 1 and new_idx respectively. * Note also that req_event and req_prod in Xen start at 1, * event indexes in virtio start at 0. */ return (__u16)(new_idx - event_idx - 1) < (__u16)(new_idx - old); } struct vring_packed_desc_event { /* Descriptor Ring Change Event Offset/Wrap Counter. */ __le16 off_wrap; /* Descriptor Ring Change Event Flags. */ __le16 flags; }; struct vring_packed_desc { /* Buffer Address. */ __le64 addr; /* Buffer Length. */ __le32 len; /* Buffer ID. */ __le16 id; /* The flags depending on descriptor type. */ __le16 flags; }; #endif /* _LINUX_VIRTIO_RING_H */ linux/dqblk_xfs.h000064400000022035151027430560010036 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * Copyright (c) 1995-2001,2004 Silicon Graphics, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesset General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _LINUX_DQBLK_XFS_H #define _LINUX_DQBLK_XFS_H #include /* * Disk quota - quotactl(2) commands for the XFS Quota Manager (XQM). */ #define XQM_CMD(x) (('X'<<8)+(x)) /* note: forms first QCMD argument */ #define XQM_COMMAND(x) (((x) & (0xff<<8)) == ('X'<<8)) /* test if for XFS */ #define XQM_USRQUOTA 0 /* system call user quota type */ #define XQM_GRPQUOTA 1 /* system call group quota type */ #define XQM_PRJQUOTA 2 /* system call project quota type */ #define XQM_MAXQUOTAS 3 #define Q_XQUOTAON XQM_CMD(1) /* enable accounting/enforcement */ #define Q_XQUOTAOFF XQM_CMD(2) /* disable accounting/enforcement */ #define Q_XGETQUOTA XQM_CMD(3) /* get disk limits and usage */ #define Q_XSETQLIM XQM_CMD(4) /* set disk limits */ #define Q_XGETQSTAT XQM_CMD(5) /* get quota subsystem status */ #define Q_XQUOTARM XQM_CMD(6) /* free disk space used by dquots */ #define Q_XQUOTASYNC XQM_CMD(7) /* delalloc flush, updates dquots */ #define Q_XGETQSTATV XQM_CMD(8) /* newer version of get quota */ #define Q_XGETNEXTQUOTA XQM_CMD(9) /* get disk limits and usage >= ID */ /* * fs_disk_quota structure: * * This contains the current quota information regarding a user/proj/group. * It is 64-bit aligned, and all the blk units are in BBs (Basic Blocks) of * 512 bytes. */ #define FS_DQUOT_VERSION 1 /* fs_disk_quota.d_version */ typedef struct fs_disk_quota { __s8 d_version; /* version of this structure */ __s8 d_flags; /* FS_{USER,PROJ,GROUP}_QUOTA */ __u16 d_fieldmask; /* field specifier */ __u32 d_id; /* user, project, or group ID */ __u64 d_blk_hardlimit;/* absolute limit on disk blks */ __u64 d_blk_softlimit;/* preferred limit on disk blks */ __u64 d_ino_hardlimit;/* maximum # allocated inodes */ __u64 d_ino_softlimit;/* preferred inode limit */ __u64 d_bcount; /* # disk blocks owned by the user */ __u64 d_icount; /* # inodes owned by the user */ __s32 d_itimer; /* zero if within inode limits */ /* if not, we refuse service */ __s32 d_btimer; /* similar to above; for disk blocks */ __u16 d_iwarns; /* # warnings issued wrt num inodes */ __u16 d_bwarns; /* # warnings issued wrt disk blocks */ __s8 d_itimer_hi; /* upper 8 bits of timer values */ __s8 d_btimer_hi; __s8 d_rtbtimer_hi; __s8 d_padding2; /* padding2 - for future use */ __u64 d_rtb_hardlimit;/* absolute limit on realtime blks */ __u64 d_rtb_softlimit;/* preferred limit on RT disk blks */ __u64 d_rtbcount; /* # realtime blocks owned */ __s32 d_rtbtimer; /* similar to above; for RT disk blks */ __u16 d_rtbwarns; /* # warnings issued wrt RT disk blks */ __s16 d_padding3; /* padding3 - for future use */ char d_padding4[8]; /* yet more padding */ } fs_disk_quota_t; /* * These fields are sent to Q_XSETQLIM to specify fields that need to change. */ #define FS_DQ_ISOFT (1<<0) #define FS_DQ_IHARD (1<<1) #define FS_DQ_BSOFT (1<<2) #define FS_DQ_BHARD (1<<3) #define FS_DQ_RTBSOFT (1<<4) #define FS_DQ_RTBHARD (1<<5) #define FS_DQ_LIMIT_MASK (FS_DQ_ISOFT | FS_DQ_IHARD | FS_DQ_BSOFT | \ FS_DQ_BHARD | FS_DQ_RTBSOFT | FS_DQ_RTBHARD) /* * These timers can only be set in super user's dquot. For others, timers are * automatically started and stopped. Superusers timer values set the limits * for the rest. In case these values are zero, the DQ_{F,B}TIMELIMIT values * defined below are used. * These values also apply only to the d_fieldmask field for Q_XSETQLIM. */ #define FS_DQ_BTIMER (1<<6) #define FS_DQ_ITIMER (1<<7) #define FS_DQ_RTBTIMER (1<<8) #define FS_DQ_TIMER_MASK (FS_DQ_BTIMER | FS_DQ_ITIMER | FS_DQ_RTBTIMER) /* * Warning counts are set in both super user's dquot and others. For others, * warnings are set/cleared by the administrators (or automatically by going * below the soft limit). Superusers warning values set the warning limits * for the rest. In case these values are zero, the DQ_{F,B}WARNLIMIT values * defined below are used. * These values also apply only to the d_fieldmask field for Q_XSETQLIM. */ #define FS_DQ_BWARNS (1<<9) #define FS_DQ_IWARNS (1<<10) #define FS_DQ_RTBWARNS (1<<11) #define FS_DQ_WARNS_MASK (FS_DQ_BWARNS | FS_DQ_IWARNS | FS_DQ_RTBWARNS) /* * Accounting values. These can only be set for filesystem with * non-transactional quotas that require quotacheck(8) in userspace. */ #define FS_DQ_BCOUNT (1<<12) #define FS_DQ_ICOUNT (1<<13) #define FS_DQ_RTBCOUNT (1<<14) #define FS_DQ_ACCT_MASK (FS_DQ_BCOUNT | FS_DQ_ICOUNT | FS_DQ_RTBCOUNT) /* * Quota expiration timestamps are 40-bit signed integers, with the upper 8 * bits encoded in the _hi fields. */ #define FS_DQ_BIGTIME (1<<15) /* * Various flags related to quotactl(2). */ #define FS_QUOTA_UDQ_ACCT (1<<0) /* user quota accounting */ #define FS_QUOTA_UDQ_ENFD (1<<1) /* user quota limits enforcement */ #define FS_QUOTA_GDQ_ACCT (1<<2) /* group quota accounting */ #define FS_QUOTA_GDQ_ENFD (1<<3) /* group quota limits enforcement */ #define FS_QUOTA_PDQ_ACCT (1<<4) /* project quota accounting */ #define FS_QUOTA_PDQ_ENFD (1<<5) /* project quota limits enforcement */ #define FS_USER_QUOTA (1<<0) /* user quota type */ #define FS_PROJ_QUOTA (1<<1) /* project quota type */ #define FS_GROUP_QUOTA (1<<2) /* group quota type */ /* * fs_quota_stat is the struct returned in Q_XGETQSTAT for a given file system. * Provides a centralized way to get meta information about the quota subsystem. * eg. space taken up for user and group quotas, number of dquots currently * incore. */ #define FS_QSTAT_VERSION 1 /* fs_quota_stat.qs_version */ /* * Some basic information about 'quota files'. */ typedef struct fs_qfilestat { __u64 qfs_ino; /* inode number */ __u64 qfs_nblks; /* number of BBs 512-byte-blks */ __u32 qfs_nextents; /* number of extents */ } fs_qfilestat_t; typedef struct fs_quota_stat { __s8 qs_version; /* version number for future changes */ __u16 qs_flags; /* FS_QUOTA_{U,P,G}DQ_{ACCT,ENFD} */ __s8 qs_pad; /* unused */ fs_qfilestat_t qs_uquota; /* user quota storage information */ fs_qfilestat_t qs_gquota; /* group quota storage information */ __u32 qs_incoredqs; /* number of dquots incore */ __s32 qs_btimelimit; /* limit for blks timer */ __s32 qs_itimelimit; /* limit for inodes timer */ __s32 qs_rtbtimelimit;/* limit for rt blks timer */ __u16 qs_bwarnlimit; /* limit for num warnings */ __u16 qs_iwarnlimit; /* limit for num warnings */ } fs_quota_stat_t; /* * fs_quota_statv is used by Q_XGETQSTATV for a given file system. It provides * a centralized way to get meta information about the quota subsystem. eg. * space taken up for user, group, and project quotas, number of dquots * currently incore. * * This version has proper versioning support with appropriate padding for * future expansions, and ability to expand for future without creating any * backward compatibility issues. * * Q_XGETQSTATV uses the passed in value of the requested version via * fs_quota_statv.qs_version to determine the return data layout of * fs_quota_statv. The kernel will fill the data fields relevant to that * version. * * If kernel does not support user space caller specified version, EINVAL will * be returned. User space caller can then reduce the version number and retry * the same command. */ #define FS_QSTATV_VERSION1 1 /* fs_quota_statv.qs_version */ /* * Some basic information about 'quota files' for Q_XGETQSTATV command */ struct fs_qfilestatv { __u64 qfs_ino; /* inode number */ __u64 qfs_nblks; /* number of BBs 512-byte-blks */ __u32 qfs_nextents; /* number of extents */ __u32 qfs_pad; /* pad for 8-byte alignment */ }; struct fs_quota_statv { __s8 qs_version; /* version for future changes */ __u8 qs_pad1; /* pad for 16bit alignment */ __u16 qs_flags; /* FS_QUOTA_.* flags */ __u32 qs_incoredqs; /* number of dquots incore */ struct fs_qfilestatv qs_uquota; /* user quota information */ struct fs_qfilestatv qs_gquota; /* group quota information */ struct fs_qfilestatv qs_pquota; /* project quota information */ __s32 qs_btimelimit; /* limit for blks timer */ __s32 qs_itimelimit; /* limit for inodes timer */ __s32 qs_rtbtimelimit;/* limit for rt blks timer */ __u16 qs_bwarnlimit; /* limit for num warnings */ __u16 qs_iwarnlimit; /* limit for num warnings */ __u64 qs_pad2[8]; /* for future proofing */ }; #endif /* _LINUX_DQBLK_XFS_H */ linux/pkt_sched.h000064400000073130151027430560010027 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_PKT_SCHED_H #define __LINUX_PKT_SCHED_H #include #include /* Logical priority bands not depending on specific packet scheduler. Every scheduler will map them to real traffic classes, if it has no more precise mechanism to classify packets. These numbers have no special meaning, though their coincidence with obsolete IPv6 values is not occasional :-). New IPv6 drafts preferred full anarchy inspired by diffserv group. Note: TC_PRIO_BESTEFFORT does not mean that it is the most unhappy class, actually, as rule it will be handled with more care than filler or even bulk. */ #define TC_PRIO_BESTEFFORT 0 #define TC_PRIO_FILLER 1 #define TC_PRIO_BULK 2 #define TC_PRIO_INTERACTIVE_BULK 4 #define TC_PRIO_INTERACTIVE 6 #define TC_PRIO_CONTROL 7 #define TC_PRIO_MAX 15 /* Generic queue statistics, available for all the elements. Particular schedulers may have also their private records. */ struct tc_stats { __u64 bytes; /* Number of enqueued bytes */ __u32 packets; /* Number of enqueued packets */ __u32 drops; /* Packets dropped because of lack of resources */ __u32 overlimits; /* Number of throttle events when this * flow goes out of allocated bandwidth */ __u32 bps; /* Current flow byte rate */ __u32 pps; /* Current flow packet rate */ __u32 qlen; __u32 backlog; }; struct tc_estimator { signed char interval; unsigned char ewma_log; }; /* "Handles" --------- All the traffic control objects have 32bit identifiers, or "handles". They can be considered as opaque numbers from user API viewpoint, but actually they always consist of two fields: major and minor numbers, which are interpreted by kernel specially, that may be used by applications, though not recommended. F.e. qdisc handles always have minor number equal to zero, classes (or flows) have major equal to parent qdisc major, and minor uniquely identifying class inside qdisc. Macros to manipulate handles: */ #define TC_H_MAJ_MASK (0xFFFF0000U) #define TC_H_MIN_MASK (0x0000FFFFU) #define TC_H_MAJ(h) ((h)&TC_H_MAJ_MASK) #define TC_H_MIN(h) ((h)&TC_H_MIN_MASK) #define TC_H_MAKE(maj,min) (((maj)&TC_H_MAJ_MASK)|((min)&TC_H_MIN_MASK)) #define TC_H_UNSPEC (0U) #define TC_H_ROOT (0xFFFFFFFFU) #define TC_H_INGRESS (0xFFFFFFF1U) #define TC_H_CLSACT TC_H_INGRESS #define TC_H_MIN_PRIORITY 0xFFE0U #define TC_H_MIN_INGRESS 0xFFF2U #define TC_H_MIN_EGRESS 0xFFF3U /* Need to corrospond to iproute2 tc/tc_core.h "enum link_layer" */ enum tc_link_layer { TC_LINKLAYER_UNAWARE, /* Indicate unaware old iproute2 util */ TC_LINKLAYER_ETHERNET, TC_LINKLAYER_ATM, }; #define TC_LINKLAYER_MASK 0x0F /* limit use to lower 4 bits */ struct tc_ratespec { unsigned char cell_log; __u8 linklayer; /* lower 4 bits */ unsigned short overhead; short cell_align; unsigned short mpu; __u32 rate; }; #define TC_RTAB_SIZE 1024 struct tc_sizespec { unsigned char cell_log; unsigned char size_log; short cell_align; int overhead; unsigned int linklayer; unsigned int mpu; unsigned int mtu; unsigned int tsize; }; enum { TCA_STAB_UNSPEC, TCA_STAB_BASE, TCA_STAB_DATA, __TCA_STAB_MAX }; #define TCA_STAB_MAX (__TCA_STAB_MAX - 1) /* FIFO section */ struct tc_fifo_qopt { __u32 limit; /* Queue length: bytes for bfifo, packets for pfifo */ }; /* SKBPRIO section */ /* * Priorities go from zero to (SKBPRIO_MAX_PRIORITY - 1). * SKBPRIO_MAX_PRIORITY should be at least 64 in order for skbprio to be able * to map one to one the DS field of IPV4 and IPV6 headers. * Memory allocation grows linearly with SKBPRIO_MAX_PRIORITY. */ #define SKBPRIO_MAX_PRIORITY 64 struct tc_skbprio_qopt { __u32 limit; /* Queue length in packets. */ }; /* PRIO section */ #define TCQ_PRIO_BANDS 16 #define TCQ_MIN_PRIO_BANDS 2 struct tc_prio_qopt { int bands; /* Number of bands */ __u8 priomap[TC_PRIO_MAX+1]; /* Map: logical priority -> PRIO band */ }; /* MULTIQ section */ struct tc_multiq_qopt { __u16 bands; /* Number of bands */ __u16 max_bands; /* Maximum number of queues */ }; /* PLUG section */ #define TCQ_PLUG_BUFFER 0 #define TCQ_PLUG_RELEASE_ONE 1 #define TCQ_PLUG_RELEASE_INDEFINITE 2 #define TCQ_PLUG_LIMIT 3 struct tc_plug_qopt { /* TCQ_PLUG_BUFFER: Inset a plug into the queue and * buffer any incoming packets * TCQ_PLUG_RELEASE_ONE: Dequeue packets from queue head * to beginning of the next plug. * TCQ_PLUG_RELEASE_INDEFINITE: Dequeue all packets from queue. * Stop buffering packets until the next TCQ_PLUG_BUFFER * command is received (just act as a pass-thru queue). * TCQ_PLUG_LIMIT: Increase/decrease queue size */ int action; __u32 limit; }; /* TBF section */ struct tc_tbf_qopt { struct tc_ratespec rate; struct tc_ratespec peakrate; __u32 limit; __u32 buffer; __u32 mtu; }; enum { TCA_TBF_UNSPEC, TCA_TBF_PARMS, TCA_TBF_RTAB, TCA_TBF_PTAB, TCA_TBF_RATE64, TCA_TBF_PRATE64, TCA_TBF_BURST, TCA_TBF_PBURST, TCA_TBF_PAD, __TCA_TBF_MAX, }; #define TCA_TBF_MAX (__TCA_TBF_MAX - 1) /* TEQL section */ /* TEQL does not require any parameters */ /* SFQ section */ struct tc_sfq_qopt { unsigned quantum; /* Bytes per round allocated to flow */ int perturb_period; /* Period of hash perturbation */ __u32 limit; /* Maximal packets in queue */ unsigned divisor; /* Hash divisor */ unsigned flows; /* Maximal number of flows */ }; struct tc_sfqred_stats { __u32 prob_drop; /* Early drops, below max threshold */ __u32 forced_drop; /* Early drops, after max threshold */ __u32 prob_mark; /* Marked packets, below max threshold */ __u32 forced_mark; /* Marked packets, after max threshold */ __u32 prob_mark_head; /* Marked packets, below max threshold */ __u32 forced_mark_head;/* Marked packets, after max threshold */ }; struct tc_sfq_qopt_v1 { struct tc_sfq_qopt v0; unsigned int depth; /* max number of packets per flow */ unsigned int headdrop; /* SFQRED parameters */ __u32 limit; /* HARD maximal flow queue length (bytes) */ __u32 qth_min; /* Min average length threshold (bytes) */ __u32 qth_max; /* Max average length threshold (bytes) */ unsigned char Wlog; /* log(W) */ unsigned char Plog; /* log(P_max/(qth_max-qth_min)) */ unsigned char Scell_log; /* cell size for idle damping */ unsigned char flags; __u32 max_P; /* probability, high resolution */ /* SFQRED stats */ struct tc_sfqred_stats stats; }; struct tc_sfq_xstats { __s32 allot; }; /* RED section */ enum { TCA_RED_UNSPEC, TCA_RED_PARMS, TCA_RED_STAB, TCA_RED_MAX_P, TCA_RED_FLAGS, /* bitfield32 */ TCA_RED_EARLY_DROP_BLOCK, /* u32 */ TCA_RED_MARK_BLOCK, /* u32 */ __TCA_RED_MAX, }; #define TCA_RED_MAX (__TCA_RED_MAX - 1) struct tc_red_qopt { __u32 limit; /* HARD maximal queue length (bytes) */ __u32 qth_min; /* Min average length threshold (bytes) */ __u32 qth_max; /* Max average length threshold (bytes) */ unsigned char Wlog; /* log(W) */ unsigned char Plog; /* log(P_max/(qth_max-qth_min)) */ unsigned char Scell_log; /* cell size for idle damping */ /* This field can be used for flags that a RED-like qdisc has * historically supported. E.g. when configuring RED, it can be used for * ECN, HARDDROP and ADAPTATIVE. For SFQ it can be used for ECN, * HARDDROP. Etc. Because this field has not been validated, and is * copied back on dump, any bits besides those to which a given qdisc * has assigned a historical meaning need to be considered for free use * by userspace tools. * * Any further flags need to be passed differently, e.g. through an * attribute (such as TCA_RED_FLAGS above). Such attribute should allow * passing both recent and historic flags in one value. */ unsigned char flags; #define TC_RED_ECN 1 #define TC_RED_HARDDROP 2 #define TC_RED_ADAPTATIVE 4 #define TC_RED_NODROP 8 }; #define TC_RED_HISTORIC_FLAGS (TC_RED_ECN | TC_RED_HARDDROP | TC_RED_ADAPTATIVE) struct tc_red_xstats { __u32 early; /* Early drops */ __u32 pdrop; /* Drops due to queue limits */ __u32 other; /* Drops due to drop() calls */ __u32 marked; /* Marked packets */ }; /* GRED section */ #define MAX_DPs 16 enum { TCA_GRED_UNSPEC, TCA_GRED_PARMS, TCA_GRED_STAB, TCA_GRED_DPS, TCA_GRED_MAX_P, TCA_GRED_LIMIT, TCA_GRED_VQ_LIST, /* nested TCA_GRED_VQ_ENTRY */ __TCA_GRED_MAX, }; #define TCA_GRED_MAX (__TCA_GRED_MAX - 1) enum { TCA_GRED_VQ_ENTRY_UNSPEC, TCA_GRED_VQ_ENTRY, /* nested TCA_GRED_VQ_* */ __TCA_GRED_VQ_ENTRY_MAX, }; #define TCA_GRED_VQ_ENTRY_MAX (__TCA_GRED_VQ_ENTRY_MAX - 1) enum { TCA_GRED_VQ_UNSPEC, TCA_GRED_VQ_PAD, TCA_GRED_VQ_DP, /* u32 */ TCA_GRED_VQ_STAT_BYTES, /* u64 */ TCA_GRED_VQ_STAT_PACKETS, /* u32 */ TCA_GRED_VQ_STAT_BACKLOG, /* u32 */ TCA_GRED_VQ_STAT_PROB_DROP, /* u32 */ TCA_GRED_VQ_STAT_PROB_MARK, /* u32 */ TCA_GRED_VQ_STAT_FORCED_DROP, /* u32 */ TCA_GRED_VQ_STAT_FORCED_MARK, /* u32 */ TCA_GRED_VQ_STAT_PDROP, /* u32 */ TCA_GRED_VQ_STAT_OTHER, /* u32 */ TCA_GRED_VQ_FLAGS, /* u32 */ __TCA_GRED_VQ_MAX }; #define TCA_GRED_VQ_MAX (__TCA_GRED_VQ_MAX - 1) struct tc_gred_qopt { __u32 limit; /* HARD maximal queue length (bytes) */ __u32 qth_min; /* Min average length threshold (bytes) */ __u32 qth_max; /* Max average length threshold (bytes) */ __u32 DP; /* up to 2^32 DPs */ __u32 backlog; __u32 qave; __u32 forced; __u32 early; __u32 other; __u32 pdrop; __u8 Wlog; /* log(W) */ __u8 Plog; /* log(P_max/(qth_max-qth_min)) */ __u8 Scell_log; /* cell size for idle damping */ __u8 prio; /* prio of this VQ */ __u32 packets; __u32 bytesin; }; /* gred setup */ struct tc_gred_sopt { __u32 DPs; __u32 def_DP; __u8 grio; __u8 flags; __u16 pad1; }; /* CHOKe section */ enum { TCA_CHOKE_UNSPEC, TCA_CHOKE_PARMS, TCA_CHOKE_STAB, TCA_CHOKE_MAX_P, __TCA_CHOKE_MAX, }; #define TCA_CHOKE_MAX (__TCA_CHOKE_MAX - 1) struct tc_choke_qopt { __u32 limit; /* Hard queue length (packets) */ __u32 qth_min; /* Min average threshold (packets) */ __u32 qth_max; /* Max average threshold (packets) */ unsigned char Wlog; /* log(W) */ unsigned char Plog; /* log(P_max/(qth_max-qth_min)) */ unsigned char Scell_log; /* cell size for idle damping */ unsigned char flags; /* see RED flags */ }; struct tc_choke_xstats { __u32 early; /* Early drops */ __u32 pdrop; /* Drops due to queue limits */ __u32 other; /* Drops due to drop() calls */ __u32 marked; /* Marked packets */ __u32 matched; /* Drops due to flow match */ }; /* HTB section */ #define TC_HTB_NUMPRIO 8 #define TC_HTB_MAXDEPTH 8 #define TC_HTB_PROTOVER 3 /* the same as HTB and TC's major */ struct tc_htb_opt { struct tc_ratespec rate; struct tc_ratespec ceil; __u32 buffer; __u32 cbuffer; __u32 quantum; __u32 level; /* out only */ __u32 prio; }; struct tc_htb_glob { __u32 version; /* to match HTB/TC */ __u32 rate2quantum; /* bps->quantum divisor */ __u32 defcls; /* default class number */ __u32 debug; /* debug flags */ /* stats */ __u32 direct_pkts; /* count of non shaped packets */ }; enum { TCA_HTB_UNSPEC, TCA_HTB_PARMS, TCA_HTB_INIT, TCA_HTB_CTAB, TCA_HTB_RTAB, TCA_HTB_DIRECT_QLEN, TCA_HTB_RATE64, TCA_HTB_CEIL64, TCA_HTB_PAD, TCA_HTB_OFFLOAD, __TCA_HTB_MAX, }; #define TCA_HTB_MAX (__TCA_HTB_MAX - 1) struct tc_htb_xstats { __u32 lends; __u32 borrows; __u32 giants; /* unused since 'Make HTB scheduler work with TSO.' */ __s32 tokens; __s32 ctokens; }; /* HFSC section */ struct tc_hfsc_qopt { __u16 defcls; /* default class */ }; struct tc_service_curve { __u32 m1; /* slope of the first segment in bps */ __u32 d; /* x-projection of the first segment in us */ __u32 m2; /* slope of the second segment in bps */ }; struct tc_hfsc_stats { __u64 work; /* total work done */ __u64 rtwork; /* work done by real-time criteria */ __u32 period; /* current period */ __u32 level; /* class level in hierarchy */ }; enum { TCA_HFSC_UNSPEC, TCA_HFSC_RSC, TCA_HFSC_FSC, TCA_HFSC_USC, __TCA_HFSC_MAX, }; #define TCA_HFSC_MAX (__TCA_HFSC_MAX - 1) /* CBQ section */ #define TC_CBQ_MAXPRIO 8 #define TC_CBQ_MAXLEVEL 8 #define TC_CBQ_DEF_EWMA 5 struct tc_cbq_lssopt { unsigned char change; unsigned char flags; #define TCF_CBQ_LSS_BOUNDED 1 #define TCF_CBQ_LSS_ISOLATED 2 unsigned char ewma_log; unsigned char level; #define TCF_CBQ_LSS_FLAGS 1 #define TCF_CBQ_LSS_EWMA 2 #define TCF_CBQ_LSS_MAXIDLE 4 #define TCF_CBQ_LSS_MINIDLE 8 #define TCF_CBQ_LSS_OFFTIME 0x10 #define TCF_CBQ_LSS_AVPKT 0x20 __u32 maxidle; __u32 minidle; __u32 offtime; __u32 avpkt; }; struct tc_cbq_wrropt { unsigned char flags; unsigned char priority; unsigned char cpriority; unsigned char __reserved; __u32 allot; __u32 weight; }; struct tc_cbq_ovl { unsigned char strategy; #define TC_CBQ_OVL_CLASSIC 0 #define TC_CBQ_OVL_DELAY 1 #define TC_CBQ_OVL_LOWPRIO 2 #define TC_CBQ_OVL_DROP 3 #define TC_CBQ_OVL_RCLASSIC 4 unsigned char priority2; __u16 pad; __u32 penalty; }; struct tc_cbq_police { unsigned char police; unsigned char __res1; unsigned short __res2; }; struct tc_cbq_fopt { __u32 split; __u32 defmap; __u32 defchange; }; struct tc_cbq_xstats { __u32 borrows; __u32 overactions; __s32 avgidle; __s32 undertime; }; enum { TCA_CBQ_UNSPEC, TCA_CBQ_LSSOPT, TCA_CBQ_WRROPT, TCA_CBQ_FOPT, TCA_CBQ_OVL_STRATEGY, TCA_CBQ_RATE, TCA_CBQ_RTAB, TCA_CBQ_POLICE, __TCA_CBQ_MAX, }; #define TCA_CBQ_MAX (__TCA_CBQ_MAX - 1) /* dsmark section */ enum { TCA_DSMARK_UNSPEC, TCA_DSMARK_INDICES, TCA_DSMARK_DEFAULT_INDEX, TCA_DSMARK_SET_TC_INDEX, TCA_DSMARK_MASK, TCA_DSMARK_VALUE, __TCA_DSMARK_MAX, }; #define TCA_DSMARK_MAX (__TCA_DSMARK_MAX - 1) /* ATM section */ enum { TCA_ATM_UNSPEC, TCA_ATM_FD, /* file/socket descriptor */ TCA_ATM_PTR, /* pointer to descriptor - later */ TCA_ATM_HDR, /* LL header */ TCA_ATM_EXCESS, /* excess traffic class (0 for CLP) */ TCA_ATM_ADDR, /* PVC address (for output only) */ TCA_ATM_STATE, /* VC state (ATM_VS_*; for output only) */ __TCA_ATM_MAX, }; #define TCA_ATM_MAX (__TCA_ATM_MAX - 1) /* Network emulator */ enum { TCA_NETEM_UNSPEC, TCA_NETEM_CORR, TCA_NETEM_DELAY_DIST, TCA_NETEM_REORDER, TCA_NETEM_CORRUPT, TCA_NETEM_LOSS, TCA_NETEM_RATE, TCA_NETEM_ECN, TCA_NETEM_RATE64, TCA_NETEM_PAD, TCA_NETEM_LATENCY64, TCA_NETEM_JITTER64, TCA_NETEM_SLOT, TCA_NETEM_SLOT_DIST, __TCA_NETEM_MAX, }; #define TCA_NETEM_MAX (__TCA_NETEM_MAX - 1) struct tc_netem_qopt { __u32 latency; /* added delay (us) */ __u32 limit; /* fifo limit (packets) */ __u32 loss; /* random packet loss (0=none ~0=100%) */ __u32 gap; /* re-ordering gap (0 for none) */ __u32 duplicate; /* random packet dup (0=none ~0=100%) */ __u32 jitter; /* random jitter in latency (us) */ }; struct tc_netem_corr { __u32 delay_corr; /* delay correlation */ __u32 loss_corr; /* packet loss correlation */ __u32 dup_corr; /* duplicate correlation */ }; struct tc_netem_reorder { __u32 probability; __u32 correlation; }; struct tc_netem_corrupt { __u32 probability; __u32 correlation; }; struct tc_netem_rate { __u32 rate; /* byte/s */ __s32 packet_overhead; __u32 cell_size; __s32 cell_overhead; }; struct tc_netem_slot { __s64 min_delay; /* nsec */ __s64 max_delay; __s32 max_packets; __s32 max_bytes; __s64 dist_delay; /* nsec */ __s64 dist_jitter; /* nsec */ }; enum { NETEM_LOSS_UNSPEC, NETEM_LOSS_GI, /* General Intuitive - 4 state model */ NETEM_LOSS_GE, /* Gilbert Elliot models */ __NETEM_LOSS_MAX }; #define NETEM_LOSS_MAX (__NETEM_LOSS_MAX - 1) /* State transition probabilities for 4 state model */ struct tc_netem_gimodel { __u32 p13; __u32 p31; __u32 p32; __u32 p14; __u32 p23; }; /* Gilbert-Elliot models */ struct tc_netem_gemodel { __u32 p; __u32 r; __u32 h; __u32 k1; }; #define NETEM_DIST_SCALE 8192 #define NETEM_DIST_MAX 16384 /* DRR */ enum { TCA_DRR_UNSPEC, TCA_DRR_QUANTUM, __TCA_DRR_MAX }; #define TCA_DRR_MAX (__TCA_DRR_MAX - 1) struct tc_drr_stats { __u32 deficit; }; /* MQPRIO */ #define TC_QOPT_BITMASK 15 #define TC_QOPT_MAX_QUEUE 16 enum { TC_MQPRIO_HW_OFFLOAD_NONE, /* no offload requested */ TC_MQPRIO_HW_OFFLOAD_TCS, /* offload TCs, no queue counts */ __TC_MQPRIO_HW_OFFLOAD_MAX }; #define TC_MQPRIO_HW_OFFLOAD_MAX (__TC_MQPRIO_HW_OFFLOAD_MAX - 1) enum { TC_MQPRIO_MODE_DCB, TC_MQPRIO_MODE_CHANNEL, __TC_MQPRIO_MODE_MAX }; #define __TC_MQPRIO_MODE_MAX (__TC_MQPRIO_MODE_MAX - 1) enum { TC_MQPRIO_SHAPER_DCB, TC_MQPRIO_SHAPER_BW_RATE, /* Add new shapers below */ __TC_MQPRIO_SHAPER_MAX }; #define __TC_MQPRIO_SHAPER_MAX (__TC_MQPRIO_SHAPER_MAX - 1) struct tc_mqprio_qopt { __u8 num_tc; __u8 prio_tc_map[TC_QOPT_BITMASK + 1]; __u8 hw; __u16 count[TC_QOPT_MAX_QUEUE]; __u16 offset[TC_QOPT_MAX_QUEUE]; }; #define TC_MQPRIO_F_MODE 0x1 #define TC_MQPRIO_F_SHAPER 0x2 #define TC_MQPRIO_F_MIN_RATE 0x4 #define TC_MQPRIO_F_MAX_RATE 0x8 enum { TCA_MQPRIO_UNSPEC, TCA_MQPRIO_MODE, TCA_MQPRIO_SHAPER, TCA_MQPRIO_MIN_RATE64, TCA_MQPRIO_MAX_RATE64, __TCA_MQPRIO_MAX, }; #define TCA_MQPRIO_MAX (__TCA_MQPRIO_MAX - 1) /* SFB */ enum { TCA_SFB_UNSPEC, TCA_SFB_PARMS, __TCA_SFB_MAX, }; #define TCA_SFB_MAX (__TCA_SFB_MAX - 1) /* * Note: increment, decrement are Q0.16 fixed-point values. */ struct tc_sfb_qopt { __u32 rehash_interval; /* delay between hash move, in ms */ __u32 warmup_time; /* double buffering warmup time in ms (warmup_time < rehash_interval) */ __u32 max; /* max len of qlen_min */ __u32 bin_size; /* maximum queue length per bin */ __u32 increment; /* probability increment, (d1 in Blue) */ __u32 decrement; /* probability decrement, (d2 in Blue) */ __u32 limit; /* max SFB queue length */ __u32 penalty_rate; /* inelastic flows are rate limited to 'rate' pps */ __u32 penalty_burst; }; struct tc_sfb_xstats { __u32 earlydrop; __u32 penaltydrop; __u32 bucketdrop; __u32 queuedrop; __u32 childdrop; /* drops in child qdisc */ __u32 marked; __u32 maxqlen; __u32 maxprob; __u32 avgprob; }; #define SFB_MAX_PROB 0xFFFF /* QFQ */ enum { TCA_QFQ_UNSPEC, TCA_QFQ_WEIGHT, TCA_QFQ_LMAX, __TCA_QFQ_MAX }; #define TCA_QFQ_MAX (__TCA_QFQ_MAX - 1) struct tc_qfq_stats { __u32 weight; __u32 lmax; }; /* CODEL */ enum { TCA_CODEL_UNSPEC, TCA_CODEL_TARGET, TCA_CODEL_LIMIT, TCA_CODEL_INTERVAL, TCA_CODEL_ECN, TCA_CODEL_CE_THRESHOLD, __TCA_CODEL_MAX }; #define TCA_CODEL_MAX (__TCA_CODEL_MAX - 1) struct tc_codel_xstats { __u32 maxpacket; /* largest packet we've seen so far */ __u32 count; /* how many drops we've done since the last time we * entered dropping state */ __u32 lastcount; /* count at entry to dropping state */ __u32 ldelay; /* in-queue delay seen by most recently dequeued packet */ __s32 drop_next; /* time to drop next packet */ __u32 drop_overlimit; /* number of time max qdisc packet limit was hit */ __u32 ecn_mark; /* number of packets we ECN marked instead of dropped */ __u32 dropping; /* are we in dropping state ? */ __u32 ce_mark; /* number of CE marked packets because of ce_threshold */ }; /* FQ_CODEL */ #define FQ_CODEL_QUANTUM_MAX (1 << 20) enum { TCA_FQ_CODEL_UNSPEC, TCA_FQ_CODEL_TARGET, TCA_FQ_CODEL_LIMIT, TCA_FQ_CODEL_INTERVAL, TCA_FQ_CODEL_ECN, TCA_FQ_CODEL_FLOWS, TCA_FQ_CODEL_QUANTUM, TCA_FQ_CODEL_CE_THRESHOLD, TCA_FQ_CODEL_DROP_BATCH_SIZE, TCA_FQ_CODEL_MEMORY_LIMIT, TCA_FQ_CODEL_CE_THRESHOLD_SELECTOR, TCA_FQ_CODEL_CE_THRESHOLD_MASK, __TCA_FQ_CODEL_MAX }; #define TCA_FQ_CODEL_MAX (__TCA_FQ_CODEL_MAX - 1) enum { TCA_FQ_CODEL_XSTATS_QDISC, TCA_FQ_CODEL_XSTATS_CLASS, }; struct tc_fq_codel_qd_stats { __u32 maxpacket; /* largest packet we've seen so far */ __u32 drop_overlimit; /* number of time max qdisc * packet limit was hit */ __u32 ecn_mark; /* number of packets we ECN marked * instead of being dropped */ __u32 new_flow_count; /* number of time packets * created a 'new flow' */ __u32 new_flows_len; /* count of flows in new list */ __u32 old_flows_len; /* count of flows in old list */ __u32 ce_mark; /* packets above ce_threshold */ __u32 memory_usage; /* in bytes */ __u32 drop_overmemory; }; struct tc_fq_codel_cl_stats { __s32 deficit; __u32 ldelay; /* in-queue delay seen by most recently * dequeued packet */ __u32 count; __u32 lastcount; __u32 dropping; __s32 drop_next; }; struct tc_fq_codel_xstats { __u32 type; union { struct tc_fq_codel_qd_stats qdisc_stats; struct tc_fq_codel_cl_stats class_stats; }; }; /* FQ */ enum { TCA_FQ_UNSPEC, TCA_FQ_PLIMIT, /* limit of total number of packets in queue */ TCA_FQ_FLOW_PLIMIT, /* limit of packets per flow */ TCA_FQ_QUANTUM, /* RR quantum */ TCA_FQ_INITIAL_QUANTUM, /* RR quantum for new flow */ TCA_FQ_RATE_ENABLE, /* enable/disable rate limiting */ TCA_FQ_FLOW_DEFAULT_RATE,/* obsolete, do not use */ TCA_FQ_FLOW_MAX_RATE, /* per flow max rate */ TCA_FQ_BUCKETS_LOG, /* log2(number of buckets) */ TCA_FQ_FLOW_REFILL_DELAY, /* flow credit refill delay in usec */ TCA_FQ_ORPHAN_MASK, /* mask applied to orphaned skb hashes */ TCA_FQ_LOW_RATE_THRESHOLD, /* per packet delay under this rate */ TCA_FQ_CE_THRESHOLD, /* DCTCP-like CE-marking threshold */ TCA_FQ_TIMER_SLACK, /* timer slack */ __TCA_FQ_MAX }; #define TCA_FQ_MAX (__TCA_FQ_MAX - 1) struct tc_fq_qd_stats { __u64 gc_flows; __u64 highprio_packets; __u64 tcp_retrans; __u64 throttled; __u64 flows_plimit; __u64 pkts_too_long; __u64 allocation_errors; __s64 time_next_delayed_flow; __u32 flows; __u32 inactive_flows; __u32 throttled_flows; __u32 unthrottle_latency_ns; __u64 ce_mark; /* packets above ce_threshold */ }; /* Heavy-Hitter Filter */ enum { TCA_HHF_UNSPEC, TCA_HHF_BACKLOG_LIMIT, TCA_HHF_QUANTUM, TCA_HHF_HH_FLOWS_LIMIT, TCA_HHF_RESET_TIMEOUT, TCA_HHF_ADMIT_BYTES, TCA_HHF_EVICT_TIMEOUT, TCA_HHF_NON_HH_WEIGHT, __TCA_HHF_MAX }; #define TCA_HHF_MAX (__TCA_HHF_MAX - 1) struct tc_hhf_xstats { __u32 drop_overlimit; /* number of times max qdisc packet limit * was hit */ __u32 hh_overlimit; /* number of times max heavy-hitters was hit */ __u32 hh_tot_count; /* number of captured heavy-hitters so far */ __u32 hh_cur_count; /* number of current heavy-hitters */ }; /* PIE */ enum { TCA_PIE_UNSPEC, TCA_PIE_TARGET, TCA_PIE_LIMIT, TCA_PIE_TUPDATE, TCA_PIE_ALPHA, TCA_PIE_BETA, TCA_PIE_ECN, TCA_PIE_BYTEMODE, TCA_PIE_DQ_RATE_ESTIMATOR, __TCA_PIE_MAX }; #define TCA_PIE_MAX (__TCA_PIE_MAX - 1) struct tc_pie_xstats { __u64 prob; /* current probability */ __u32 delay; /* current delay in ms */ __u32 avg_dq_rate; /* current average dq_rate in * bits/pie_time */ __u32 dq_rate_estimating; /* is avg_dq_rate being calculated? */ __u32 packets_in; /* total number of packets enqueued */ __u32 dropped; /* packets dropped due to pie_action */ __u32 overlimit; /* dropped due to lack of space * in queue */ __u32 maxq; /* maximum queue size */ __u32 ecn_mark; /* packets marked with ecn*/ }; /* FQ PIE */ enum { TCA_FQ_PIE_UNSPEC, TCA_FQ_PIE_LIMIT, TCA_FQ_PIE_FLOWS, TCA_FQ_PIE_TARGET, TCA_FQ_PIE_TUPDATE, TCA_FQ_PIE_ALPHA, TCA_FQ_PIE_BETA, TCA_FQ_PIE_QUANTUM, TCA_FQ_PIE_MEMORY_LIMIT, TCA_FQ_PIE_ECN_PROB, TCA_FQ_PIE_ECN, TCA_FQ_PIE_BYTEMODE, TCA_FQ_PIE_DQ_RATE_ESTIMATOR, __TCA_FQ_PIE_MAX }; #define TCA_FQ_PIE_MAX (__TCA_FQ_PIE_MAX - 1) struct tc_fq_pie_xstats { __u32 packets_in; /* total number of packets enqueued */ __u32 dropped; /* packets dropped due to fq_pie_action */ __u32 overlimit; /* dropped due to lack of space in queue */ __u32 overmemory; /* dropped due to lack of memory in queue */ __u32 ecn_mark; /* packets marked with ecn */ __u32 new_flow_count; /* count of new flows created by packets */ __u32 new_flows_len; /* count of flows in new list */ __u32 old_flows_len; /* count of flows in old list */ __u32 memory_usage; /* total memory across all queues */ }; /* CBS */ struct tc_cbs_qopt { __u8 offload; __u8 _pad[3]; __s32 hicredit; __s32 locredit; __s32 idleslope; __s32 sendslope; }; enum { TCA_CBS_UNSPEC, TCA_CBS_PARMS, __TCA_CBS_MAX, }; #define TCA_CBS_MAX (__TCA_CBS_MAX - 1) /* ETF */ struct tc_etf_qopt { __s32 delta; __s32 clockid; __u32 flags; #define TC_ETF_DEADLINE_MODE_ON _BITUL(0) #define TC_ETF_OFFLOAD_ON _BITUL(1) #define TC_ETF_SKIP_SOCK_CHECK _BITUL(2) }; enum { TCA_ETF_UNSPEC, TCA_ETF_PARMS, __TCA_ETF_MAX, }; #define TCA_ETF_MAX (__TCA_ETF_MAX - 1) /* CAKE */ enum { TCA_CAKE_UNSPEC, TCA_CAKE_PAD, TCA_CAKE_BASE_RATE64, TCA_CAKE_DIFFSERV_MODE, TCA_CAKE_ATM, TCA_CAKE_FLOW_MODE, TCA_CAKE_OVERHEAD, TCA_CAKE_RTT, TCA_CAKE_TARGET, TCA_CAKE_AUTORATE, TCA_CAKE_MEMORY, TCA_CAKE_NAT, TCA_CAKE_RAW, TCA_CAKE_WASH, TCA_CAKE_MPU, TCA_CAKE_INGRESS, TCA_CAKE_ACK_FILTER, TCA_CAKE_SPLIT_GSO, TCA_CAKE_FWMARK, __TCA_CAKE_MAX }; #define TCA_CAKE_MAX (__TCA_CAKE_MAX - 1) enum { __TCA_CAKE_STATS_INVALID, TCA_CAKE_STATS_PAD, TCA_CAKE_STATS_CAPACITY_ESTIMATE64, TCA_CAKE_STATS_MEMORY_LIMIT, TCA_CAKE_STATS_MEMORY_USED, TCA_CAKE_STATS_AVG_NETOFF, TCA_CAKE_STATS_MIN_NETLEN, TCA_CAKE_STATS_MAX_NETLEN, TCA_CAKE_STATS_MIN_ADJLEN, TCA_CAKE_STATS_MAX_ADJLEN, TCA_CAKE_STATS_TIN_STATS, TCA_CAKE_STATS_DEFICIT, TCA_CAKE_STATS_COBALT_COUNT, TCA_CAKE_STATS_DROPPING, TCA_CAKE_STATS_DROP_NEXT_US, TCA_CAKE_STATS_P_DROP, TCA_CAKE_STATS_BLUE_TIMER_US, __TCA_CAKE_STATS_MAX }; #define TCA_CAKE_STATS_MAX (__TCA_CAKE_STATS_MAX - 1) enum { __TCA_CAKE_TIN_STATS_INVALID, TCA_CAKE_TIN_STATS_PAD, TCA_CAKE_TIN_STATS_SENT_PACKETS, TCA_CAKE_TIN_STATS_SENT_BYTES64, TCA_CAKE_TIN_STATS_DROPPED_PACKETS, TCA_CAKE_TIN_STATS_DROPPED_BYTES64, TCA_CAKE_TIN_STATS_ACKS_DROPPED_PACKETS, TCA_CAKE_TIN_STATS_ACKS_DROPPED_BYTES64, TCA_CAKE_TIN_STATS_ECN_MARKED_PACKETS, TCA_CAKE_TIN_STATS_ECN_MARKED_BYTES64, TCA_CAKE_TIN_STATS_BACKLOG_PACKETS, TCA_CAKE_TIN_STATS_BACKLOG_BYTES, TCA_CAKE_TIN_STATS_THRESHOLD_RATE64, TCA_CAKE_TIN_STATS_TARGET_US, TCA_CAKE_TIN_STATS_INTERVAL_US, TCA_CAKE_TIN_STATS_WAY_INDIRECT_HITS, TCA_CAKE_TIN_STATS_WAY_MISSES, TCA_CAKE_TIN_STATS_WAY_COLLISIONS, TCA_CAKE_TIN_STATS_PEAK_DELAY_US, TCA_CAKE_TIN_STATS_AVG_DELAY_US, TCA_CAKE_TIN_STATS_BASE_DELAY_US, TCA_CAKE_TIN_STATS_SPARSE_FLOWS, TCA_CAKE_TIN_STATS_BULK_FLOWS, TCA_CAKE_TIN_STATS_UNRESPONSIVE_FLOWS, TCA_CAKE_TIN_STATS_MAX_SKBLEN, TCA_CAKE_TIN_STATS_FLOW_QUANTUM, __TCA_CAKE_TIN_STATS_MAX }; #define TCA_CAKE_TIN_STATS_MAX (__TCA_CAKE_TIN_STATS_MAX - 1) #define TC_CAKE_MAX_TINS (8) enum { CAKE_FLOW_NONE = 0, CAKE_FLOW_SRC_IP, CAKE_FLOW_DST_IP, CAKE_FLOW_HOSTS, /* = CAKE_FLOW_SRC_IP | CAKE_FLOW_DST_IP */ CAKE_FLOW_FLOWS, CAKE_FLOW_DUAL_SRC, /* = CAKE_FLOW_SRC_IP | CAKE_FLOW_FLOWS */ CAKE_FLOW_DUAL_DST, /* = CAKE_FLOW_DST_IP | CAKE_FLOW_FLOWS */ CAKE_FLOW_TRIPLE, /* = CAKE_FLOW_HOSTS | CAKE_FLOW_FLOWS */ CAKE_FLOW_MAX, }; enum { CAKE_DIFFSERV_DIFFSERV3 = 0, CAKE_DIFFSERV_DIFFSERV4, CAKE_DIFFSERV_DIFFSERV8, CAKE_DIFFSERV_BESTEFFORT, CAKE_DIFFSERV_PRECEDENCE, CAKE_DIFFSERV_MAX }; enum { CAKE_ACK_NONE = 0, CAKE_ACK_FILTER, CAKE_ACK_AGGRESSIVE, CAKE_ACK_MAX }; enum { CAKE_ATM_NONE = 0, CAKE_ATM_ATM, CAKE_ATM_PTM, CAKE_ATM_MAX }; /* TAPRIO */ enum { TC_TAPRIO_CMD_SET_GATES = 0x00, TC_TAPRIO_CMD_SET_AND_HOLD = 0x01, TC_TAPRIO_CMD_SET_AND_RELEASE = 0x02, }; enum { TCA_TAPRIO_SCHED_ENTRY_UNSPEC, TCA_TAPRIO_SCHED_ENTRY_INDEX, /* u32 */ TCA_TAPRIO_SCHED_ENTRY_CMD, /* u8 */ TCA_TAPRIO_SCHED_ENTRY_GATE_MASK, /* u32 */ TCA_TAPRIO_SCHED_ENTRY_INTERVAL, /* u32 */ __TCA_TAPRIO_SCHED_ENTRY_MAX, }; #define TCA_TAPRIO_SCHED_ENTRY_MAX (__TCA_TAPRIO_SCHED_ENTRY_MAX - 1) /* The format for schedule entry list is: * [TCA_TAPRIO_SCHED_ENTRY_LIST] * [TCA_TAPRIO_SCHED_ENTRY] * [TCA_TAPRIO_SCHED_ENTRY_CMD] * [TCA_TAPRIO_SCHED_ENTRY_GATES] * [TCA_TAPRIO_SCHED_ENTRY_INTERVAL] */ enum { TCA_TAPRIO_SCHED_UNSPEC, TCA_TAPRIO_SCHED_ENTRY, __TCA_TAPRIO_SCHED_MAX, }; #define TCA_TAPRIO_SCHED_MAX (__TCA_TAPRIO_SCHED_MAX - 1) /* The format for the admin sched (dump only): * [TCA_TAPRIO_SCHED_ADMIN_SCHED] * [TCA_TAPRIO_ATTR_SCHED_BASE_TIME] * [TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST] * [TCA_TAPRIO_ATTR_SCHED_ENTRY] * [TCA_TAPRIO_ATTR_SCHED_ENTRY_CMD] * [TCA_TAPRIO_ATTR_SCHED_ENTRY_GATES] * [TCA_TAPRIO_ATTR_SCHED_ENTRY_INTERVAL] */ #define TCA_TAPRIO_ATTR_FLAG_TXTIME_ASSIST _BITUL(0) #define TCA_TAPRIO_ATTR_FLAG_FULL_OFFLOAD _BITUL(1) enum { TCA_TAPRIO_TC_ENTRY_UNSPEC, TCA_TAPRIO_TC_ENTRY_INDEX, /* u32 */ TCA_TAPRIO_TC_ENTRY_MAX_SDU, /* u32 */ /* add new constants above here */ __TCA_TAPRIO_TC_ENTRY_CNT, TCA_TAPRIO_TC_ENTRY_MAX = (__TCA_TAPRIO_TC_ENTRY_CNT - 1) }; enum { TCA_TAPRIO_ATTR_UNSPEC, TCA_TAPRIO_ATTR_PRIOMAP, /* struct tc_mqprio_qopt */ TCA_TAPRIO_ATTR_SCHED_ENTRY_LIST, /* nested of entry */ TCA_TAPRIO_ATTR_SCHED_BASE_TIME, /* s64 */ TCA_TAPRIO_ATTR_SCHED_SINGLE_ENTRY, /* single entry */ TCA_TAPRIO_ATTR_SCHED_CLOCKID, /* s32 */ TCA_TAPRIO_PAD, TCA_TAPRIO_ATTR_ADMIN_SCHED, /* The admin sched, only used in dump */ TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME, /* s64 */ TCA_TAPRIO_ATTR_SCHED_CYCLE_TIME_EXTENSION, /* s64 */ TCA_TAPRIO_ATTR_FLAGS, /* u32 */ TCA_TAPRIO_ATTR_TXTIME_DELAY, /* u32 */ TCA_TAPRIO_ATTR_TC_ENTRY, /* nest */ __TCA_TAPRIO_ATTR_MAX, }; #define TCA_TAPRIO_ATTR_MAX (__TCA_TAPRIO_ATTR_MAX - 1) /* ETS */ #define TCQ_ETS_MAX_BANDS 16 enum { TCA_ETS_UNSPEC, TCA_ETS_NBANDS, /* u8 */ TCA_ETS_NSTRICT, /* u8 */ TCA_ETS_QUANTA, /* nested TCA_ETS_QUANTA_BAND */ TCA_ETS_QUANTA_BAND, /* u32 */ TCA_ETS_PRIOMAP, /* nested TCA_ETS_PRIOMAP_BAND */ TCA_ETS_PRIOMAP_BAND, /* u8 */ __TCA_ETS_MAX, }; #define TCA_ETS_MAX (__TCA_ETS_MAX - 1) #endif linux/raid/md_p.h000064400000037441151027430560007726 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* md_p.h : physical layout of Linux RAID devices Copyright (C) 1996-98 Ingo Molnar, Gadi Oxman This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. You should have received a copy of the GNU General Public License (for example /usr/src/linux/COPYING); if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _MD_P_H #define _MD_P_H #include #include /* * RAID superblock. * * The RAID superblock maintains some statistics on each RAID configuration. * Each real device in the RAID set contains it near the end of the device. * Some of the ideas are copied from the ext2fs implementation. * * We currently use 4096 bytes as follows: * * word offset function * * 0 - 31 Constant generic RAID device information. * 32 - 63 Generic state information. * 64 - 127 Personality specific information. * 128 - 511 12 32-words descriptors of the disks in the raid set. * 512 - 911 Reserved. * 912 - 1023 Disk specific descriptor. */ /* * If x is the real device size in bytes, we return an apparent size of: * * y = (x & ~(MD_RESERVED_BYTES - 1)) - MD_RESERVED_BYTES * * and place the 4kB superblock at offset y. */ #define MD_RESERVED_BYTES (64 * 1024) #define MD_RESERVED_SECTORS (MD_RESERVED_BYTES / 512) #define MD_NEW_SIZE_SECTORS(x) ((x & ~(MD_RESERVED_SECTORS - 1)) - MD_RESERVED_SECTORS) #define MD_SB_BYTES 4096 #define MD_SB_WORDS (MD_SB_BYTES / 4) #define MD_SB_SECTORS (MD_SB_BYTES / 512) /* * The following are counted in 32-bit words */ #define MD_SB_GENERIC_OFFSET 0 #define MD_SB_PERSONALITY_OFFSET 64 #define MD_SB_DISKS_OFFSET 128 #define MD_SB_DESCRIPTOR_OFFSET 992 #define MD_SB_GENERIC_CONSTANT_WORDS 32 #define MD_SB_GENERIC_STATE_WORDS 32 #define MD_SB_GENERIC_WORDS (MD_SB_GENERIC_CONSTANT_WORDS + MD_SB_GENERIC_STATE_WORDS) #define MD_SB_PERSONALITY_WORDS 64 #define MD_SB_DESCRIPTOR_WORDS 32 #define MD_SB_DISKS 27 #define MD_SB_DISKS_WORDS (MD_SB_DISKS*MD_SB_DESCRIPTOR_WORDS) #define MD_SB_RESERVED_WORDS (1024 - MD_SB_GENERIC_WORDS - MD_SB_PERSONALITY_WORDS - MD_SB_DISKS_WORDS - MD_SB_DESCRIPTOR_WORDS) #define MD_SB_EQUAL_WORDS (MD_SB_GENERIC_WORDS + MD_SB_PERSONALITY_WORDS + MD_SB_DISKS_WORDS) /* * Device "operational" state bits */ #define MD_DISK_FAULTY 0 /* disk is faulty / operational */ #define MD_DISK_ACTIVE 1 /* disk is running or spare disk */ #define MD_DISK_SYNC 2 /* disk is in sync with the raid set */ #define MD_DISK_REMOVED 3 /* disk is in sync with the raid set */ #define MD_DISK_CLUSTER_ADD 4 /* Initiate a disk add across the cluster * For clustered enviroments only. */ #define MD_DISK_CANDIDATE 5 /* disk is added as spare (local) until confirmed * For clustered enviroments only. */ #define MD_DISK_FAILFAST 10 /* Send REQ_FAILFAST if there are multiple * devices available - and don't try to * correct read errors. */ #define MD_DISK_WRITEMOSTLY 9 /* disk is "write-mostly" is RAID1 config. * read requests will only be sent here in * dire need */ #define MD_DISK_JOURNAL 18 /* disk is used as the write journal in RAID-5/6 */ #define MD_DISK_ROLE_SPARE 0xffff #define MD_DISK_ROLE_FAULTY 0xfffe #define MD_DISK_ROLE_JOURNAL 0xfffd #define MD_DISK_ROLE_MAX 0xff00 /* max value of regular disk role */ typedef struct mdp_device_descriptor_s { __u32 number; /* 0 Device number in the entire set */ __u32 major; /* 1 Device major number */ __u32 minor; /* 2 Device minor number */ __u32 raid_disk; /* 3 The role of the device in the raid set */ __u32 state; /* 4 Operational state */ __u32 reserved[MD_SB_DESCRIPTOR_WORDS - 5]; } mdp_disk_t; #define MD_SB_MAGIC 0xa92b4efc /* * Superblock state bits */ #define MD_SB_CLEAN 0 #define MD_SB_ERRORS 1 #define MD_SB_CLUSTERED 5 /* MD is clustered */ #define MD_SB_BITMAP_PRESENT 8 /* bitmap may be present nearby */ /* * Notes: * - if an array is being reshaped (restriped) in order to change the * the number of active devices in the array, 'raid_disks' will be * the larger of the old and new numbers. 'delta_disks' will * be the "new - old". So if +ve, raid_disks is the new value, and * "raid_disks-delta_disks" is the old. If -ve, raid_disks is the * old value and "raid_disks+delta_disks" is the new (smaller) value. */ typedef struct mdp_superblock_s { /* * Constant generic information */ __u32 md_magic; /* 0 MD identifier */ __u32 major_version; /* 1 major version to which the set conforms */ __u32 minor_version; /* 2 minor version ... */ __u32 patch_version; /* 3 patchlevel version ... */ __u32 gvalid_words; /* 4 Number of used words in this section */ __u32 set_uuid0; /* 5 Raid set identifier */ __u32 ctime; /* 6 Creation time */ __u32 level; /* 7 Raid personality */ __u32 size; /* 8 Apparent size of each individual disk */ __u32 nr_disks; /* 9 total disks in the raid set */ __u32 raid_disks; /* 10 disks in a fully functional raid set */ __u32 md_minor; /* 11 preferred MD minor device number */ __u32 not_persistent; /* 12 does it have a persistent superblock */ __u32 set_uuid1; /* 13 Raid set identifier #2 */ __u32 set_uuid2; /* 14 Raid set identifier #3 */ __u32 set_uuid3; /* 15 Raid set identifier #4 */ __u32 gstate_creserved[MD_SB_GENERIC_CONSTANT_WORDS - 16]; /* * Generic state information */ __u32 utime; /* 0 Superblock update time */ __u32 state; /* 1 State bits (clean, ...) */ __u32 active_disks; /* 2 Number of currently active disks */ __u32 working_disks; /* 3 Number of working disks */ __u32 failed_disks; /* 4 Number of failed disks */ __u32 spare_disks; /* 5 Number of spare disks */ __u32 sb_csum; /* 6 checksum of the whole superblock */ #if defined(__BYTE_ORDER) ? __BYTE_ORDER == __BIG_ENDIAN : defined(__BIG_ENDIAN) __u32 events_hi; /* 7 high-order of superblock update count */ __u32 events_lo; /* 8 low-order of superblock update count */ __u32 cp_events_hi; /* 9 high-order of checkpoint update count */ __u32 cp_events_lo; /* 10 low-order of checkpoint update count */ #elif defined(__BYTE_ORDER) ? __BYTE_ORDER == __LITTLE_ENDIAN : defined(__LITTLE_ENDIAN) __u32 events_lo; /* 7 low-order of superblock update count */ __u32 events_hi; /* 8 high-order of superblock update count */ __u32 cp_events_lo; /* 9 low-order of checkpoint update count */ __u32 cp_events_hi; /* 10 high-order of checkpoint update count */ #else #error unspecified endianness #endif __u32 recovery_cp; /* 11 recovery checkpoint sector count */ /* There are only valid for minor_version > 90 */ __u64 reshape_position; /* 12,13 next address in array-space for reshape */ __u32 new_level; /* 14 new level we are reshaping to */ __u32 delta_disks; /* 15 change in number of raid_disks */ __u32 new_layout; /* 16 new layout */ __u32 new_chunk; /* 17 new chunk size (bytes) */ __u32 gstate_sreserved[MD_SB_GENERIC_STATE_WORDS - 18]; /* * Personality information */ __u32 layout; /* 0 the array's physical layout */ __u32 chunk_size; /* 1 chunk size in bytes */ __u32 root_pv; /* 2 LV root PV */ __u32 root_block; /* 3 LV root block */ __u32 pstate_reserved[MD_SB_PERSONALITY_WORDS - 4]; /* * Disks information */ mdp_disk_t disks[MD_SB_DISKS]; /* * Reserved */ __u32 reserved[MD_SB_RESERVED_WORDS]; /* * Active descriptor */ mdp_disk_t this_disk; } mdp_super_t; static __inline__ __u64 md_event(mdp_super_t *sb) { __u64 ev = sb->events_hi; return (ev<<32)| sb->events_lo; } #define MD_SUPERBLOCK_1_TIME_SEC_MASK ((1ULL<<40) - 1) /* * The version-1 superblock : * All numeric fields are little-endian. * * total size: 256 bytes plus 2 per device. * 1K allows 384 devices. */ struct mdp_superblock_1 { /* constant array information - 128 bytes */ __le32 magic; /* MD_SB_MAGIC: 0xa92b4efc - little endian */ __le32 major_version; /* 1 */ __le32 feature_map; /* bit 0 set if 'bitmap_offset' is meaningful */ __le32 pad0; /* always set to 0 when writing */ __u8 set_uuid[16]; /* user-space generated. */ char set_name[32]; /* set and interpreted by user-space */ __le64 ctime; /* lo 40 bits are seconds, top 24 are microseconds or 0*/ __le32 level; /* -4 (multipath), -1 (linear), 0,1,4,5 */ __le32 layout; /* only for raid5 and raid10 currently */ __le64 size; /* used size of component devices, in 512byte sectors */ __le32 chunksize; /* in 512byte sectors */ __le32 raid_disks; union { __le32 bitmap_offset; /* sectors after start of superblock that bitmap starts * NOTE: signed, so bitmap can be before superblock * only meaningful of feature_map[0] is set. */ /* only meaningful when feature_map[MD_FEATURE_PPL] is set */ struct { __le16 offset; /* sectors from start of superblock that ppl starts (signed) */ __le16 size; /* ppl size in sectors */ } ppl; }; /* These are only valid with feature bit '4' */ __le32 new_level; /* new level we are reshaping to */ __le64 reshape_position; /* next address in array-space for reshape */ __le32 delta_disks; /* change in number of raid_disks */ __le32 new_layout; /* new layout */ __le32 new_chunk; /* new chunk size (512byte sectors) */ __le32 new_offset; /* signed number to add to data_offset in new * layout. 0 == no-change. This can be * different on each device in the array. */ /* constant this-device information - 64 bytes */ __le64 data_offset; /* sector start of data, often 0 */ __le64 data_size; /* sectors in this device that can be used for data */ __le64 super_offset; /* sector start of this superblock */ union { __le64 recovery_offset;/* sectors before this offset (from data_offset) have been recovered */ __le64 journal_tail;/* journal tail of journal device (from data_offset) */ }; __le32 dev_number; /* permanent identifier of this device - not role in raid */ __le32 cnt_corrected_read; /* number of read errors that were corrected by re-writing */ __u8 device_uuid[16]; /* user-space setable, ignored by kernel */ __u8 devflags; /* per-device flags. Only two defined...*/ #define WriteMostly1 1 /* mask for writemostly flag in above */ #define FailFast1 2 /* Should avoid retries and fixups and just fail */ /* Bad block log. If there are any bad blocks the feature flag is set. * If offset and size are non-zero, that space is reserved and available */ __u8 bblog_shift; /* shift from sectors to block size */ __le16 bblog_size; /* number of sectors reserved for list */ __le32 bblog_offset; /* sector offset from superblock to bblog, * signed - not unsigned */ /* array state information - 64 bytes */ __le64 utime; /* 40 bits second, 24 bits microseconds */ __le64 events; /* incremented when superblock updated */ __le64 resync_offset; /* data before this offset (from data_offset) known to be in sync */ __le32 sb_csum; /* checksum up to devs[max_dev] */ __le32 max_dev; /* size of devs[] array to consider */ __u8 pad3[64-32]; /* set to 0 when writing */ /* device state information. Indexed by dev_number. * 2 bytes per device * Note there are no per-device state flags. State information is rolled * into the 'roles' value. If a device is spare or faulty, then it doesn't * have a meaningful role. */ __le16 dev_roles[0]; /* role in array, or 0xffff for a spare, or 0xfffe for faulty */ }; /* feature_map bits */ #define MD_FEATURE_BITMAP_OFFSET 1 #define MD_FEATURE_RECOVERY_OFFSET 2 /* recovery_offset is present and * must be honoured */ #define MD_FEATURE_RESHAPE_ACTIVE 4 #define MD_FEATURE_BAD_BLOCKS 8 /* badblock list is not empty */ #define MD_FEATURE_REPLACEMENT 16 /* This device is replacing an * active device with same 'role'. * 'recovery_offset' is also set. */ #define MD_FEATURE_RESHAPE_BACKWARDS 32 /* Reshape doesn't change number * of devices, but is going * backwards anyway. */ #define MD_FEATURE_NEW_OFFSET 64 /* new_offset must be honoured */ #define MD_FEATURE_RECOVERY_BITMAP 128 /* recovery that is happening * is guided by bitmap. */ #define MD_FEATURE_CLUSTERED 256 /* clustered MD */ #define MD_FEATURE_JOURNAL 512 /* support write cache */ #define MD_FEATURE_PPL 1024 /* support PPL */ #define MD_FEATURE_MULTIPLE_PPLS 2048 /* support for multiple PPLs */ #define MD_FEATURE_RAID0_LAYOUT 4096 /* layout is meaningful for RAID0 */ #define MD_FEATURE_ALL (MD_FEATURE_BITMAP_OFFSET \ |MD_FEATURE_RECOVERY_OFFSET \ |MD_FEATURE_RESHAPE_ACTIVE \ |MD_FEATURE_BAD_BLOCKS \ |MD_FEATURE_REPLACEMENT \ |MD_FEATURE_RESHAPE_BACKWARDS \ |MD_FEATURE_NEW_OFFSET \ |MD_FEATURE_RECOVERY_BITMAP \ |MD_FEATURE_CLUSTERED \ |MD_FEATURE_JOURNAL \ |MD_FEATURE_PPL \ |MD_FEATURE_MULTIPLE_PPLS \ |MD_FEATURE_RAID0_LAYOUT \ ) struct r5l_payload_header { __le16 type; __le16 flags; } __attribute__ ((__packed__)); enum r5l_payload_type { R5LOG_PAYLOAD_DATA = 0, R5LOG_PAYLOAD_PARITY = 1, R5LOG_PAYLOAD_FLUSH = 2, }; struct r5l_payload_data_parity { struct r5l_payload_header header; __le32 size; /* sector. data/parity size. each 4k * has a checksum */ __le64 location; /* sector. For data, it's raid sector. For * parity, it's stripe sector */ __le32 checksum[]; } __attribute__ ((__packed__)); enum r5l_payload_data_parity_flag { R5LOG_PAYLOAD_FLAG_DISCARD = 1, /* payload is discard */ /* * RESHAPED/RESHAPING is only set when there is reshape activity. Note, * both data/parity of a stripe should have the same flag set * * RESHAPED: reshape is running, and this stripe finished reshape * RESHAPING: reshape is running, and this stripe isn't reshaped */ R5LOG_PAYLOAD_FLAG_RESHAPED = 2, R5LOG_PAYLOAD_FLAG_RESHAPING = 3, }; struct r5l_payload_flush { struct r5l_payload_header header; __le32 size; /* flush_stripes size, bytes */ __le64 flush_stripes[]; } __attribute__ ((__packed__)); enum r5l_payload_flush_flag { R5LOG_PAYLOAD_FLAG_FLUSH_STRIPE = 1, /* data represents whole stripe */ }; struct r5l_meta_block { __le32 magic; __le32 checksum; __u8 version; __u8 __zero_pading_1; __le16 __zero_pading_2; __le32 meta_size; /* whole size of the block */ __le64 seq; __le64 position; /* sector, start from rdev->data_offset, current position */ struct r5l_payload_header payloads[]; } __attribute__ ((__packed__)); #define R5LOG_VERSION 0x1 #define R5LOG_MAGIC 0x6433c509 struct ppl_header_entry { __le64 data_sector; /* raid sector of the new data */ __le32 pp_size; /* length of partial parity */ __le32 data_size; /* length of data */ __le32 parity_disk; /* member disk containing parity */ __le32 checksum; /* checksum of partial parity data for this * entry (~crc32c) */ } __attribute__ ((__packed__)); #define PPL_HEADER_SIZE 4096 #define PPL_HDR_RESERVED 512 #define PPL_HDR_ENTRY_SPACE \ (PPL_HEADER_SIZE - PPL_HDR_RESERVED - 4 * sizeof(__le32) - sizeof(__le64)) #define PPL_HDR_MAX_ENTRIES \ (PPL_HDR_ENTRY_SPACE / sizeof(struct ppl_header_entry)) struct ppl_header { __u8 reserved[PPL_HDR_RESERVED];/* reserved space, fill with 0xff */ __le32 signature; /* signature (family number of volume) */ __le32 padding; /* zero pad */ __le64 generation; /* generation number of the header */ __le32 entries_count; /* number of entries in entry array */ __le32 checksum; /* checksum of the header (~crc32c) */ struct ppl_header_entry entries[PPL_HDR_MAX_ENTRIES]; } __attribute__ ((__packed__)); #endif linux/raid/md_u.h000064400000010604151027430560007723 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* md_u.h : user <=> kernel API between Linux raidtools and RAID drivers Copyright (C) 1998 Ingo Molnar This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. You should have received a copy of the GNU General Public License (for example /usr/src/linux/COPYING); if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _MD_U_H #define _MD_U_H /* * Different major versions are not compatible. * Different minor versions are only downward compatible. * Different patchlevel versions are downward and upward compatible. */ #define MD_MAJOR_VERSION 0 #define MD_MINOR_VERSION 90 /* * MD_PATCHLEVEL_VERSION indicates kernel functionality. * >=1 means different superblock formats are selectable using SET_ARRAY_INFO * and major_version/minor_version accordingly * >=2 means that Internal bitmaps are supported by setting MD_SB_BITMAP_PRESENT * in the super status byte * >=3 means that bitmap superblock version 4 is supported, which uses * little-ending representation rather than host-endian */ #define MD_PATCHLEVEL_VERSION 3 /* ioctls */ /* status */ #define RAID_VERSION _IOR (MD_MAJOR, 0x10, mdu_version_t) #define GET_ARRAY_INFO _IOR (MD_MAJOR, 0x11, mdu_array_info_t) #define GET_DISK_INFO _IOR (MD_MAJOR, 0x12, mdu_disk_info_t) #define RAID_AUTORUN _IO (MD_MAJOR, 0x14) #define GET_BITMAP_FILE _IOR (MD_MAJOR, 0x15, mdu_bitmap_file_t) /* configuration */ #define CLEAR_ARRAY _IO (MD_MAJOR, 0x20) #define ADD_NEW_DISK _IOW (MD_MAJOR, 0x21, mdu_disk_info_t) #define HOT_REMOVE_DISK _IO (MD_MAJOR, 0x22) #define SET_ARRAY_INFO _IOW (MD_MAJOR, 0x23, mdu_array_info_t) #define SET_DISK_INFO _IO (MD_MAJOR, 0x24) #define WRITE_RAID_INFO _IO (MD_MAJOR, 0x25) #define UNPROTECT_ARRAY _IO (MD_MAJOR, 0x26) #define PROTECT_ARRAY _IO (MD_MAJOR, 0x27) #define HOT_ADD_DISK _IO (MD_MAJOR, 0x28) #define SET_DISK_FAULTY _IO (MD_MAJOR, 0x29) #define HOT_GENERATE_ERROR _IO (MD_MAJOR, 0x2a) #define SET_BITMAP_FILE _IOW (MD_MAJOR, 0x2b, int) /* usage */ #define RUN_ARRAY _IOW (MD_MAJOR, 0x30, mdu_param_t) /* 0x31 was START_ARRAY */ #define STOP_ARRAY _IO (MD_MAJOR, 0x32) #define STOP_ARRAY_RO _IO (MD_MAJOR, 0x33) #define RESTART_ARRAY_RW _IO (MD_MAJOR, 0x34) #define CLUSTERED_DISK_NACK _IO (MD_MAJOR, 0x35) /* 63 partitions with the alternate major number (mdp) */ #define MdpMinorShift 6 typedef struct mdu_version_s { int major; int minor; int patchlevel; } mdu_version_t; typedef struct mdu_array_info_s { /* * Generic constant information */ int major_version; int minor_version; int patch_version; unsigned int ctime; int level; int size; int nr_disks; int raid_disks; int md_minor; int not_persistent; /* * Generic state information */ unsigned int utime; /* 0 Superblock update time */ int state; /* 1 State bits (clean, ...) */ int active_disks; /* 2 Number of currently active disks */ int working_disks; /* 3 Number of working disks */ int failed_disks; /* 4 Number of failed disks */ int spare_disks; /* 5 Number of spare disks */ /* * Personality information */ int layout; /* 0 the array's physical layout */ int chunk_size; /* 1 chunk size in bytes */ } mdu_array_info_t; /* non-obvious values for 'level' */ #define LEVEL_MULTIPATH (-4) #define LEVEL_LINEAR (-1) #define LEVEL_FAULTY (-5) /* we need a value for 'no level specified' and 0 * means 'raid0', so we need something else. This is * for internal use only */ #define LEVEL_NONE (-1000000) typedef struct mdu_disk_info_s { /* * configuration/status of one particular disk */ int number; int major; int minor; int raid_disk; int state; } mdu_disk_info_t; typedef struct mdu_start_info_s { /* * configuration/status of one particular disk */ int major; int minor; int raid_disk; int state; } mdu_start_info_t; typedef struct mdu_bitmap_file_s { char pathname[4096]; } mdu_bitmap_file_t; typedef struct mdu_param_s { int personality; /* 1,2,3,4 */ int chunk_size; /* in bytes */ int max_fault; /* unused for now */ } mdu_param_t; #endif /* _MD_U_H */ linux/atmapi.h000064400000001670151027430560007336 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmapi.h - ATM API user space/kernel compatibility */ /* Written 1999,2000 by Werner Almesberger, EPFL ICA */ #ifndef _LINUX_ATMAPI_H #define _LINUX_ATMAPI_H #if defined(__sparc__) || defined(__ia64__) /* such alignment is not required on 32 bit sparcs, but we can't figure that we are on a sparc64 while compiling user-space programs. */ #define __ATM_API_ALIGN __attribute__((aligned(8))) #else #define __ATM_API_ALIGN #endif /* * Opaque type for kernel pointers. Note that _ is never accessed. We need * the struct in order hide the array, so that we can make simple assignments * instead of being forced to use memcpy. It also improves error reporting for * code that still assumes that we're passing unsigned longs. * * Convention: NULL pointers are passed as a field of all zeroes. */ typedef struct { unsigned char _[8]; } __ATM_API_ALIGN atm_kptr_t; #endif linux/tcp.h000064400000023300151027430560006643 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the TCP protocol. * * Version: @(#)tcp.h 1.0.2 04/28/93 * * Author: Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_TCP_H #define _LINUX_TCP_H #include #include #include struct tcphdr { __be16 source; __be16 dest; __be32 seq; __be32 ack_seq; #if defined(__LITTLE_ENDIAN_BITFIELD) __u16 res1:4, doff:4, fin:1, syn:1, rst:1, psh:1, ack:1, urg:1, ece:1, cwr:1; #elif defined(__BIG_ENDIAN_BITFIELD) __u16 doff:4, res1:4, cwr:1, ece:1, urg:1, ack:1, psh:1, rst:1, syn:1, fin:1; #else #error "Adjust your defines" #endif __be16 window; __sum16 check; __be16 urg_ptr; }; /* * The union cast uses a gcc extension to avoid aliasing problems * (union is compatible to any of its members) * This means this part of the code is -fstrict-aliasing safe now. */ union tcp_word_hdr { struct tcphdr hdr; __be32 words[5]; }; #define tcp_flag_word(tp) ( ((union tcp_word_hdr *)(tp))->words [3]) enum { TCP_FLAG_CWR = __constant_cpu_to_be32(0x00800000), TCP_FLAG_ECE = __constant_cpu_to_be32(0x00400000), TCP_FLAG_URG = __constant_cpu_to_be32(0x00200000), TCP_FLAG_ACK = __constant_cpu_to_be32(0x00100000), TCP_FLAG_PSH = __constant_cpu_to_be32(0x00080000), TCP_FLAG_RST = __constant_cpu_to_be32(0x00040000), TCP_FLAG_SYN = __constant_cpu_to_be32(0x00020000), TCP_FLAG_FIN = __constant_cpu_to_be32(0x00010000), TCP_RESERVED_BITS = __constant_cpu_to_be32(0x0F000000), TCP_DATA_OFFSET = __constant_cpu_to_be32(0xF0000000) }; /* * TCP general constants */ #define TCP_MSS_DEFAULT 536U /* IPv4 (RFC1122, RFC2581) */ #define TCP_MSS_DESIRED 1220U /* IPv6 (tunneled), EDNS0 (RFC3226) */ /* TCP socket options */ #define TCP_NODELAY 1 /* Turn off Nagle's algorithm. */ #define TCP_MAXSEG 2 /* Limit MSS */ #define TCP_CORK 3 /* Never send partially complete segments */ #define TCP_KEEPIDLE 4 /* Start keeplives after this period */ #define TCP_KEEPINTVL 5 /* Interval between keepalives */ #define TCP_KEEPCNT 6 /* Number of keepalives before death */ #define TCP_SYNCNT 7 /* Number of SYN retransmits */ #define TCP_LINGER2 8 /* Life time of orphaned FIN-WAIT-2 state */ #define TCP_DEFER_ACCEPT 9 /* Wake up listener only when data arrive */ #define TCP_WINDOW_CLAMP 10 /* Bound advertised window */ #define TCP_INFO 11 /* Information about this connection. */ #define TCP_QUICKACK 12 /* Block/reenable quick acks */ #define TCP_CONGESTION 13 /* Congestion control algorithm */ #define TCP_MD5SIG 14 /* TCP MD5 Signature (RFC2385) */ #define TCP_THIN_LINEAR_TIMEOUTS 16 /* Use linear timeouts for thin streams*/ #define TCP_THIN_DUPACK 17 /* Fast retrans. after 1 dupack */ #define TCP_USER_TIMEOUT 18 /* How long for loss retry before timeout */ #define TCP_REPAIR 19 /* TCP sock is under repair right now */ #define TCP_REPAIR_QUEUE 20 #define TCP_QUEUE_SEQ 21 #define TCP_REPAIR_OPTIONS 22 #define TCP_FASTOPEN 23 /* Enable FastOpen on listeners */ #define TCP_TIMESTAMP 24 #define TCP_NOTSENT_LOWAT 25 /* limit number of unsent bytes in write queue */ #define TCP_CC_INFO 26 /* Get Congestion Control (optional) info */ #define TCP_SAVE_SYN 27 /* Record SYN headers for new connections */ #define TCP_SAVED_SYN 28 /* Get SYN headers recorded for connection */ #define TCP_REPAIR_WINDOW 29 /* Get/set window parameters */ #define TCP_FASTOPEN_CONNECT 30 /* Attempt FastOpen with connect */ #define TCP_ULP 31 /* Attach a ULP to a TCP connection */ #define TCP_MD5SIG_EXT 32 /* TCP MD5 Signature with extensions */ #define TCP_FASTOPEN_KEY 33 /* Set the key for Fast Open (cookie) */ #define TCP_FASTOPEN_NO_COOKIE 34 /* Enable TFO without a TFO cookie */ #define TCP_ZEROCOPY_RECEIVE 35 #define TCP_INQ 36 /* Notify bytes available to read as a cmsg on read */ #define TCP_CM_INQ TCP_INQ #define TCP_REPAIR_ON 1 #define TCP_REPAIR_OFF 0 #define TCP_REPAIR_OFF_NO_WP -1 /* Turn off without window probes */ struct tcp_repair_opt { __u32 opt_code; __u32 opt_val; }; struct tcp_repair_window { __u32 snd_wl1; __u32 snd_wnd; __u32 max_window; __u32 rcv_wnd; __u32 rcv_wup; }; enum { TCP_NO_QUEUE, TCP_RECV_QUEUE, TCP_SEND_QUEUE, TCP_QUEUES_NR, }; /* for TCP_INFO socket option */ #define TCPI_OPT_TIMESTAMPS 1 #define TCPI_OPT_SACK 2 #define TCPI_OPT_WSCALE 4 #define TCPI_OPT_ECN 8 /* ECN was negociated at TCP session init */ #define TCPI_OPT_ECN_SEEN 16 /* we received at least one packet with ECT */ #define TCPI_OPT_SYN_DATA 32 /* SYN-ACK acked data in SYN sent or rcvd */ enum tcp_ca_state { TCP_CA_Open = 0, #define TCPF_CA_Open (1<= 10 */ #define KCAPI_CMD_TRACE 10 #define KCAPI_CMD_ADDCARD 11 /* OBSOLETE */ /* * flag > 2 => trace also data * flag & 1 => show trace */ #define KCAPI_TRACE_OFF 0 #define KCAPI_TRACE_SHORT_NO_DATA 1 #define KCAPI_TRACE_FULL_NO_DATA 2 #define KCAPI_TRACE_SHORT 3 #define KCAPI_TRACE_FULL 4 #endif /* __KERNELCAPI_H__ */ linux/if_arcnet.h000064400000007205151027430560010015 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the ARCnet interface. * * Authors: David Woodhouse and Avery Pennarun * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_ARCNET_H #define _LINUX_IF_ARCNET_H #include #include /* * These are the defined ARCnet Protocol ID's. */ /* CAP mode */ /* No macro but uses 1-8 */ /* RFC1201 Protocol ID's */ #define ARC_P_IP 212 /* 0xD4 */ #define ARC_P_IPV6 196 /* 0xC4: RFC2497 */ #define ARC_P_ARP 213 /* 0xD5 */ #define ARC_P_RARP 214 /* 0xD6 */ #define ARC_P_IPX 250 /* 0xFA */ #define ARC_P_NOVELL_EC 236 /* 0xEC */ /* Old RFC1051 Protocol ID's */ #define ARC_P_IP_RFC1051 240 /* 0xF0 */ #define ARC_P_ARP_RFC1051 241 /* 0xF1 */ /* MS LanMan/WfWg "NDIS" encapsulation */ #define ARC_P_ETHER 232 /* 0xE8 */ /* Unsupported/indirectly supported protocols */ #define ARC_P_DATAPOINT_BOOT 0 /* very old Datapoint equipment */ #define ARC_P_DATAPOINT_MOUNT 1 #define ARC_P_POWERLAN_BEACON 8 /* Probably ATA-Netbios related */ #define ARC_P_POWERLAN_BEACON2 243 /* 0xF3 */ #define ARC_P_LANSOFT 251 /* 0xFB - what is this? */ #define ARC_P_ATALK 0xDD /* Hardware address length */ #define ARCNET_ALEN 1 /* * The RFC1201-specific components of an arcnet packet header. */ struct arc_rfc1201 { __u8 proto; /* protocol ID field - varies */ __u8 split_flag; /* for use with split packets */ __be16 sequence; /* sequence number */ __u8 payload[0]; /* space remaining in packet (504 bytes)*/ }; #define RFC1201_HDR_SIZE 4 /* * The RFC1051-specific components. */ struct arc_rfc1051 { __u8 proto; /* ARC_P_RFC1051_ARP/RFC1051_IP */ __u8 payload[0]; /* 507 bytes */ }; #define RFC1051_HDR_SIZE 1 /* * The ethernet-encap-specific components. We have a real ethernet header * and some data. */ struct arc_eth_encap { __u8 proto; /* Always ARC_P_ETHER */ struct ethhdr eth; /* standard ethernet header (yuck!) */ __u8 payload[0]; /* 493 bytes */ }; #define ETH_ENCAP_HDR_SIZE 14 struct arc_cap { __u8 proto; __u8 cookie[sizeof(int)]; /* Actually NOT sent over the network */ union { __u8 ack; __u8 raw[0]; /* 507 bytes */ } mes; }; /* * The data needed by the actual arcnet hardware. * * Now, in the real arcnet hardware, the third and fourth bytes are the * 'offset' specification instead of the length, and the soft data is at * the _end_ of the 512-byte buffer. We hide this complexity inside the * driver. */ struct arc_hardware { __u8 source; /* source ARCnet - filled in automagically */ __u8 dest; /* destination ARCnet - 0 for broadcast */ __u8 offset[2]; /* offset bytes (some weird semantics) */ }; #define ARC_HDR_SIZE 4 /* * This is an ARCnet frame header, as seen by the kernel (and userspace, * when you do a raw packet capture). */ struct archdr { /* hardware requirements */ struct arc_hardware hard; /* arcnet encapsulation-specific bits */ union { struct arc_rfc1201 rfc1201; struct arc_rfc1051 rfc1051; struct arc_eth_encap eth_encap; struct arc_cap cap; __u8 raw[0]; /* 508 bytes */ } soft; }; #endif /* _LINUX_IF_ARCNET_H */ linux/socket.h000064400000001605151027430560007351 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SOCKET_H #define _LINUX_SOCKET_H /* * Desired design of maximum size and alignment (see RFC2553) */ #define _K_SS_MAXSIZE 128 /* Implementation specific max size */ #define _K_SS_ALIGNSIZE (__alignof__ (struct sockaddr *)) /* Implementation specific desired alignment */ typedef unsigned short __kernel_sa_family_t; struct __kernel_sockaddr_storage { __kernel_sa_family_t ss_family; /* address family */ /* Following field(s) are implementation specific */ char __data[_K_SS_MAXSIZE - sizeof(unsigned short)]; /* space to achieve desired size, */ /* _SS_MAXSIZE value minus size of ss_family */ } __attribute__ ((aligned(_K_SS_ALIGNSIZE))); /* force desired alignment */ #define SOCK_TXREHASH_DEFAULT 255 #define SOCK_TXREHASH_DISABLED 0 #define SOCK_TXREHASH_ENABLED 1 #endif /* _LINUX_SOCKET_H */ linux/blktrace_api.h000064400000011135151027430560010500 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef BLKTRACE_H #define BLKTRACE_H #include /* * Trace categories */ enum blktrace_cat { BLK_TC_READ = 1 << 0, /* reads */ BLK_TC_WRITE = 1 << 1, /* writes */ BLK_TC_FLUSH = 1 << 2, /* flush */ BLK_TC_SYNC = 1 << 3, /* sync IO */ BLK_TC_SYNCIO = BLK_TC_SYNC, BLK_TC_QUEUE = 1 << 4, /* queueing/merging */ BLK_TC_REQUEUE = 1 << 5, /* requeueing */ BLK_TC_ISSUE = 1 << 6, /* issue */ BLK_TC_COMPLETE = 1 << 7, /* completions */ BLK_TC_FS = 1 << 8, /* fs requests */ BLK_TC_PC = 1 << 9, /* pc requests */ BLK_TC_NOTIFY = 1 << 10, /* special message */ BLK_TC_AHEAD = 1 << 11, /* readahead */ BLK_TC_META = 1 << 12, /* metadata */ BLK_TC_DISCARD = 1 << 13, /* discard requests */ BLK_TC_DRV_DATA = 1 << 14, /* binary per-driver data */ BLK_TC_FUA = 1 << 15, /* fua requests */ BLK_TC_END = 1 << 15, /* we've run out of bits! */ }; #define BLK_TC_SHIFT (16) #define BLK_TC_ACT(act) ((act) << BLK_TC_SHIFT) /* * Basic trace actions */ enum blktrace_act { __BLK_TA_QUEUE = 1, /* queued */ __BLK_TA_BACKMERGE, /* back merged to existing rq */ __BLK_TA_FRONTMERGE, /* front merge to existing rq */ __BLK_TA_GETRQ, /* allocated new request */ __BLK_TA_SLEEPRQ, /* sleeping on rq allocation */ __BLK_TA_REQUEUE, /* request requeued */ __BLK_TA_ISSUE, /* sent to driver */ __BLK_TA_COMPLETE, /* completed by driver */ __BLK_TA_PLUG, /* queue was plugged */ __BLK_TA_UNPLUG_IO, /* queue was unplugged by io */ __BLK_TA_UNPLUG_TIMER, /* queue was unplugged by timer */ __BLK_TA_INSERT, /* insert request */ __BLK_TA_SPLIT, /* bio was split */ __BLK_TA_BOUNCE, /* bio was bounced */ __BLK_TA_REMAP, /* bio was remapped */ __BLK_TA_ABORT, /* request aborted */ __BLK_TA_DRV_DATA, /* driver-specific binary data */ __BLK_TA_CGROUP = 1 << 8, /* from a cgroup*/ }; /* * Notify events. */ enum blktrace_notify { __BLK_TN_PROCESS = 0, /* establish pid/name mapping */ __BLK_TN_TIMESTAMP, /* include system clock */ __BLK_TN_MESSAGE, /* Character string message */ __BLK_TN_CGROUP = __BLK_TA_CGROUP, /* from a cgroup */ }; /* * Trace actions in full. Additionally, read or write is masked */ #define BLK_TA_QUEUE (__BLK_TA_QUEUE | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_BACKMERGE (__BLK_TA_BACKMERGE | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_FRONTMERGE (__BLK_TA_FRONTMERGE | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_GETRQ (__BLK_TA_GETRQ | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_SLEEPRQ (__BLK_TA_SLEEPRQ | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_REQUEUE (__BLK_TA_REQUEUE | BLK_TC_ACT(BLK_TC_REQUEUE)) #define BLK_TA_ISSUE (__BLK_TA_ISSUE | BLK_TC_ACT(BLK_TC_ISSUE)) #define BLK_TA_COMPLETE (__BLK_TA_COMPLETE| BLK_TC_ACT(BLK_TC_COMPLETE)) #define BLK_TA_PLUG (__BLK_TA_PLUG | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_UNPLUG_IO (__BLK_TA_UNPLUG_IO | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_UNPLUG_TIMER (__BLK_TA_UNPLUG_TIMER | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_INSERT (__BLK_TA_INSERT | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_SPLIT (__BLK_TA_SPLIT) #define BLK_TA_BOUNCE (__BLK_TA_BOUNCE) #define BLK_TA_REMAP (__BLK_TA_REMAP | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_ABORT (__BLK_TA_ABORT | BLK_TC_ACT(BLK_TC_QUEUE)) #define BLK_TA_DRV_DATA (__BLK_TA_DRV_DATA | BLK_TC_ACT(BLK_TC_DRV_DATA)) #define BLK_TN_PROCESS (__BLK_TN_PROCESS | BLK_TC_ACT(BLK_TC_NOTIFY)) #define BLK_TN_TIMESTAMP (__BLK_TN_TIMESTAMP | BLK_TC_ACT(BLK_TC_NOTIFY)) #define BLK_TN_MESSAGE (__BLK_TN_MESSAGE | BLK_TC_ACT(BLK_TC_NOTIFY)) #define BLK_IO_TRACE_MAGIC 0x65617400 #define BLK_IO_TRACE_VERSION 0x07 /* * The trace itself */ struct blk_io_trace { __u32 magic; /* MAGIC << 8 | version */ __u32 sequence; /* event number */ __u64 time; /* in nanoseconds */ __u64 sector; /* disk offset */ __u32 bytes; /* transfer length */ __u32 action; /* what happened */ __u32 pid; /* who did it */ __u32 device; /* device number */ __u32 cpu; /* on what cpu did it happen */ __u16 error; /* completion error */ __u16 pdu_len; /* length of data after this trace */ /* cgroup id will be stored here if exists */ }; /* * The remap event */ struct blk_io_trace_remap { __be32 device_from; __be32 device_to; __be64 sector_from; }; enum { Blktrace_setup = 1, Blktrace_running, Blktrace_stopped, }; #define BLKTRACE_BDEV_SIZE 32 /* * User setup structure passed with BLKTRACESETUP */ struct blk_user_trace_setup { char name[BLKTRACE_BDEV_SIZE]; /* output */ __u16 act_mask; /* input */ __u32 buf_size; /* input */ __u32 buf_nr; /* input */ __u64 start_lba; __u64 end_lba; __u32 pid; }; #endif /* BLKTRACE_H */ linux/virtio_config.h000064400000007645151027430560010734 0ustar00#ifndef _LINUX_VIRTIO_CONFIG_H #define _LINUX_VIRTIO_CONFIG_H /* This header, excluding the #ifdef __KERNEL__ part, is BSD licensed so * anyone can use the definitions to implement compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* Virtio devices use a standardized configuration space to define their * features and pass configuration information, but each implementation can * store and access that space differently. */ #include /* Status byte for guest to report progress, and synchronize features. */ /* We have seen device and processed generic fields (VIRTIO_CONFIG_F_VIRTIO) */ #define VIRTIO_CONFIG_S_ACKNOWLEDGE 1 /* We have found a driver for the device. */ #define VIRTIO_CONFIG_S_DRIVER 2 /* Driver has used its parts of the config, and is happy */ #define VIRTIO_CONFIG_S_DRIVER_OK 4 /* Driver has finished configuring features */ #define VIRTIO_CONFIG_S_FEATURES_OK 8 /* Device entered invalid state, driver must reset it */ #define VIRTIO_CONFIG_S_NEEDS_RESET 0x40 /* We've given up on this device. */ #define VIRTIO_CONFIG_S_FAILED 0x80 /* * Virtio feature bits VIRTIO_TRANSPORT_F_START through * VIRTIO_TRANSPORT_F_END are reserved for the transport * being used (e.g. virtio_ring, virtio_pci etc.), the * rest are per-device feature bits. */ #define VIRTIO_TRANSPORT_F_START 28 #define VIRTIO_TRANSPORT_F_END 38 #ifndef VIRTIO_CONFIG_NO_LEGACY /* Do we get callbacks when the ring is completely used, even if we've * suppressed them? */ #define VIRTIO_F_NOTIFY_ON_EMPTY 24 /* Can the device handle any descriptor layout? */ #define VIRTIO_F_ANY_LAYOUT 27 #endif /* VIRTIO_CONFIG_NO_LEGACY */ /* v1.0 compliant. */ #define VIRTIO_F_VERSION_1 32 /* * If clear - device has the platform DMA (e.g. IOMMU) bypass quirk feature. * If set - use platform DMA tools to access the memory. * * Note the reverse polarity (compared to most other features), * this is for compatibility with legacy systems. */ #define VIRTIO_F_ACCESS_PLATFORM 33 /* Legacy name for VIRTIO_F_ACCESS_PLATFORM (for compatibility with old userspace) */ #define VIRTIO_F_IOMMU_PLATFORM VIRTIO_F_ACCESS_PLATFORM /* This feature indicates support for the packed virtqueue layout. */ #define VIRTIO_F_RING_PACKED 34 /* * This feature indicates that memory accesses by the driver and the * device are ordered in a way described by the platform. */ #define VIRTIO_F_ORDER_PLATFORM 36 /* * Does the device support Single Root I/O Virtualization? */ #define VIRTIO_F_SR_IOV 37 #endif /* _LINUX_VIRTIO_CONFIG_H */ linux/scif_ioctl.h000064400000014356151027430560010206 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Intel MIC Platform Software Stack (MPSS) * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2014 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * BSD LICENSE * * Copyright(c) 2014 Intel Corporation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Intel SCIF driver. * */ /* * ----------------------------------------- * SCIF IOCTL interface information * ----------------------------------------- */ #ifndef SCIF_IOCTL_H #define SCIF_IOCTL_H #include /** * struct scif_port_id - SCIF port information * @node: node on which port resides * @port: local port number */ struct scif_port_id { __u16 node; __u16 port; }; /** * struct scifioctl_connect - used for SCIF_CONNECT IOCTL * @self: used to read back the assigned port_id * @peer: destination node and port to connect to */ struct scifioctl_connect { struct scif_port_id self; struct scif_port_id peer; }; /** * struct scifioctl_accept - used for SCIF_ACCEPTREQ IOCTL * @flags: flags * @peer: global id of peer endpoint * @endpt: new connected endpoint descriptor */ struct scifioctl_accept { __s32 flags; struct scif_port_id peer; __u64 endpt; }; /** * struct scifioctl_msg - used for SCIF_SEND/SCIF_RECV IOCTL * @msg: message buffer address * @len: message length * @flags: flags * @out_len: number of bytes sent/received */ struct scifioctl_msg { __u64 msg; __s32 len; __s32 flags; __s32 out_len; }; /** * struct scifioctl_reg - used for SCIF_REG IOCTL * @addr: starting virtual address * @len: length of range * @offset: offset of window * @prot: read/write protection * @flags: flags * @out_offset: offset returned */ struct scifioctl_reg { __u64 addr; __u64 len; __s64 offset; __s32 prot; __s32 flags; __s64 out_offset; }; /** * struct scifioctl_unreg - used for SCIF_UNREG IOCTL * @offset: start of range to unregister * @len: length of range to unregister */ struct scifioctl_unreg { __s64 offset; __u64 len; }; /** * struct scifioctl_copy - used for SCIF DMA copy IOCTLs * * @loffset: offset in local registered address space to/from * which to copy * @len: length of range to copy * @roffset: offset in remote registered address space to/from * which to copy * @addr: user virtual address to/from which to copy * @flags: flags * * This structure is used for SCIF_READFROM, SCIF_WRITETO, SCIF_VREADFROM * and SCIF_VREADFROM IOCTL's. */ struct scifioctl_copy { __s64 loffset; __u64 len; __s64 roffset; __u64 addr; __s32 flags; }; /** * struct scifioctl_fence_mark - used for SCIF_FENCE_MARK IOCTL * @flags: flags * @mark: fence handle which is a pointer to a __s32 */ struct scifioctl_fence_mark { __s32 flags; __u64 mark; }; /** * struct scifioctl_fence_signal - used for SCIF_FENCE_SIGNAL IOCTL * @loff: local offset * @lval: value to write to loffset * @roff: remote offset * @rval: value to write to roffset * @flags: flags */ struct scifioctl_fence_signal { __s64 loff; __u64 lval; __s64 roff; __u64 rval; __s32 flags; }; /** * struct scifioctl_node_ids - used for SCIF_GET_NODEIDS IOCTL * @nodes: pointer to an array of node_ids * @self: ID of the current node * @len: length of array */ struct scifioctl_node_ids { __u64 nodes; __u64 self; __s32 len; }; #define SCIF_BIND _IOWR('s', 1, __u64) #define SCIF_LISTEN _IOW('s', 2, __s32) #define SCIF_CONNECT _IOWR('s', 3, struct scifioctl_connect) #define SCIF_ACCEPTREQ _IOWR('s', 4, struct scifioctl_accept) #define SCIF_ACCEPTREG _IOWR('s', 5, __u64) #define SCIF_SEND _IOWR('s', 6, struct scifioctl_msg) #define SCIF_RECV _IOWR('s', 7, struct scifioctl_msg) #define SCIF_REG _IOWR('s', 8, struct scifioctl_reg) #define SCIF_UNREG _IOWR('s', 9, struct scifioctl_unreg) #define SCIF_READFROM _IOWR('s', 10, struct scifioctl_copy) #define SCIF_WRITETO _IOWR('s', 11, struct scifioctl_copy) #define SCIF_VREADFROM _IOWR('s', 12, struct scifioctl_copy) #define SCIF_VWRITETO _IOWR('s', 13, struct scifioctl_copy) #define SCIF_GET_NODEIDS _IOWR('s', 14, struct scifioctl_node_ids) #define SCIF_FENCE_MARK _IOWR('s', 15, struct scifioctl_fence_mark) #define SCIF_FENCE_WAIT _IOWR('s', 16, __s32) #define SCIF_FENCE_SIGNAL _IOWR('s', 17, struct scifioctl_fence_signal) #endif /* SCIF_IOCTL_H */ linux/keyctl.h000064400000006654151027430560007365 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* keyctl.h: keyctl command IDs * * Copyright (C) 2004, 2008 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_KEYCTL_H #define _LINUX_KEYCTL_H #include /* special process keyring shortcut IDs */ #define KEY_SPEC_THREAD_KEYRING -1 /* - key ID for thread-specific keyring */ #define KEY_SPEC_PROCESS_KEYRING -2 /* - key ID for process-specific keyring */ #define KEY_SPEC_SESSION_KEYRING -3 /* - key ID for session-specific keyring */ #define KEY_SPEC_USER_KEYRING -4 /* - key ID for UID-specific keyring */ #define KEY_SPEC_USER_SESSION_KEYRING -5 /* - key ID for UID-session keyring */ #define KEY_SPEC_GROUP_KEYRING -6 /* - key ID for GID-specific keyring */ #define KEY_SPEC_REQKEY_AUTH_KEY -7 /* - key ID for assumed request_key auth key */ #define KEY_SPEC_REQUESTOR_KEYRING -8 /* - key ID for request_key() dest keyring */ /* request-key default keyrings */ #define KEY_REQKEY_DEFL_NO_CHANGE -1 #define KEY_REQKEY_DEFL_DEFAULT 0 #define KEY_REQKEY_DEFL_THREAD_KEYRING 1 #define KEY_REQKEY_DEFL_PROCESS_KEYRING 2 #define KEY_REQKEY_DEFL_SESSION_KEYRING 3 #define KEY_REQKEY_DEFL_USER_KEYRING 4 #define KEY_REQKEY_DEFL_USER_SESSION_KEYRING 5 #define KEY_REQKEY_DEFL_GROUP_KEYRING 6 #define KEY_REQKEY_DEFL_REQUESTOR_KEYRING 7 /* keyctl commands */ #define KEYCTL_GET_KEYRING_ID 0 /* ask for a keyring's ID */ #define KEYCTL_JOIN_SESSION_KEYRING 1 /* join or start named session keyring */ #define KEYCTL_UPDATE 2 /* update a key */ #define KEYCTL_REVOKE 3 /* revoke a key */ #define KEYCTL_CHOWN 4 /* set ownership of a key */ #define KEYCTL_SETPERM 5 /* set perms on a key */ #define KEYCTL_DESCRIBE 6 /* describe a key */ #define KEYCTL_CLEAR 7 /* clear contents of a keyring */ #define KEYCTL_LINK 8 /* link a key into a keyring */ #define KEYCTL_UNLINK 9 /* unlink a key from a keyring */ #define KEYCTL_SEARCH 10 /* search for a key in a keyring */ #define KEYCTL_READ 11 /* read a key or keyring's contents */ #define KEYCTL_INSTANTIATE 12 /* instantiate a partially constructed key */ #define KEYCTL_NEGATE 13 /* negate a partially constructed key */ #define KEYCTL_SET_REQKEY_KEYRING 14 /* set default request-key keyring */ #define KEYCTL_SET_TIMEOUT 15 /* set key timeout */ #define KEYCTL_ASSUME_AUTHORITY 16 /* assume request_key() authorisation */ #define KEYCTL_GET_SECURITY 17 /* get key security label */ #define KEYCTL_SESSION_TO_PARENT 18 /* apply session keyring to parent process */ #define KEYCTL_REJECT 19 /* reject a partially constructed key */ #define KEYCTL_INSTANTIATE_IOV 20 /* instantiate a partially constructed key */ #define KEYCTL_INVALIDATE 21 /* invalidate a key */ #define KEYCTL_GET_PERSISTENT 22 /* get a user's persistent keyring */ #define KEYCTL_DH_COMPUTE 23 /* Compute Diffie-Hellman values */ #define KEYCTL_RESTRICT_KEYRING 29 /* Restrict keys allowed to link to a keyring */ /* keyctl structures */ struct keyctl_dh_params { __s32 private; __s32 prime; __s32 base; }; struct keyctl_kdf_params { char *hashname; char *otherinfo; __u32 otherinfolen; __u32 __spare[8]; }; #endif /* _LINUX_KEYCTL_H */ linux/vboxguest.h000064400000021031151027430560010102 0ustar00/* SPDX-License-Identifier: (GPL-2.0 OR CDDL-1.0) */ /* * VBoxGuest - VirtualBox Guest Additions Driver Interface. * * Copyright (C) 2006-2016 Oracle Corporation */ #ifndef __UAPI_VBOXGUEST_H__ #define __UAPI_VBOXGUEST_H__ #include #include #include #include /* Version of vbg_ioctl_hdr structure. */ #define VBG_IOCTL_HDR_VERSION 0x10001 /* Default request type. Use this for non-VMMDev requests. */ #define VBG_IOCTL_HDR_TYPE_DEFAULT 0 /** * Common ioctl header. * * This is a mirror of vmmdev_request_header to prevent duplicating data and * needing to verify things multiple times. */ struct vbg_ioctl_hdr { /** IN: The request input size, and output size if size_out is zero. */ __u32 size_in; /** IN: Structure version (VBG_IOCTL_HDR_VERSION) */ __u32 version; /** IN: The VMMDev request type or VBG_IOCTL_HDR_TYPE_DEFAULT. */ __u32 type; /** * OUT: The VBox status code of the operation, out direction only. * This is a VINF_ or VERR_ value as defined in vbox_err.h. */ __s32 rc; /** IN: Output size. Set to zero to use size_in as output size. */ __u32 size_out; /** Reserved, MBZ. */ __u32 reserved; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_hdr, 24); /* * The VBoxGuest I/O control version. * * As usual, the high word contains the major version and changes to it * signifies incompatible changes. * * The lower word is the minor version number, it is increased when new * functions are added or existing changed in a backwards compatible manner. */ #define VBG_IOC_VERSION 0x00010000u /** * VBG_IOCTL_DRIVER_VERSION_INFO data structure * * Note VBG_IOCTL_DRIVER_VERSION_INFO may switch the session to a backwards * compatible interface version if uClientVersion indicates older client code. */ struct vbg_ioctl_driver_version_info { /** The header. */ struct vbg_ioctl_hdr hdr; union { struct { /** Requested interface version (VBG_IOC_VERSION). */ __u32 req_version; /** * Minimum interface version number (typically the * major version part of VBG_IOC_VERSION). */ __u32 min_version; /** Reserved, MBZ. */ __u32 reserved1; /** Reserved, MBZ. */ __u32 reserved2; } in; struct { /** Version for this session (typ. VBG_IOC_VERSION). */ __u32 session_version; /** Version of the IDC interface (VBG_IOC_VERSION). */ __u32 driver_version; /** The SVN revision of the driver, or 0. */ __u32 driver_revision; /** Reserved \#1 (zero until defined). */ __u32 reserved1; /** Reserved \#2 (zero until defined). */ __u32 reserved2; } out; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_driver_version_info, 24 + 20); #define VBG_IOCTL_DRIVER_VERSION_INFO \ _IOWR('V', 0, struct vbg_ioctl_driver_version_info) /* IOCTL to perform a VMM Device request less than 1KB in size. */ #define VBG_IOCTL_VMMDEV_REQUEST(s) _IOC(_IOC_READ | _IOC_WRITE, 'V', 2, s) /* IOCTL to perform a VMM Device request larger then 1KB. */ #define VBG_IOCTL_VMMDEV_REQUEST_BIG _IOC(_IOC_READ | _IOC_WRITE, 'V', 3, 0) /** VBG_IOCTL_HGCM_CONNECT data structure. */ struct vbg_ioctl_hgcm_connect { struct vbg_ioctl_hdr hdr; union { struct { struct vmmdev_hgcm_service_location loc; } in; struct { __u32 client_id; } out; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_hgcm_connect, 24 + 132); #define VBG_IOCTL_HGCM_CONNECT \ _IOWR('V', 4, struct vbg_ioctl_hgcm_connect) /** VBG_IOCTL_HGCM_DISCONNECT data structure. */ struct vbg_ioctl_hgcm_disconnect { struct vbg_ioctl_hdr hdr; union { struct { __u32 client_id; } in; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_hgcm_disconnect, 24 + 4); #define VBG_IOCTL_HGCM_DISCONNECT \ _IOWR('V', 5, struct vbg_ioctl_hgcm_disconnect) /** VBG_IOCTL_HGCM_CALL data structure. */ struct vbg_ioctl_hgcm_call { /** The header. */ struct vbg_ioctl_hdr hdr; /** Input: The id of the caller. */ __u32 client_id; /** Input: Function number. */ __u32 function; /** * Input: How long to wait (milliseconds) for completion before * cancelling the call. Set to -1 to wait indefinitely. */ __u32 timeout_ms; /** Interruptable flag, ignored for userspace calls. */ __u8 interruptible; /** Explicit padding, MBZ. */ __u8 reserved; /** * Input: How many parameters following this structure. * * The parameters are either HGCMFunctionParameter64 or 32, * depending on whether we're receiving a 64-bit or 32-bit request. * * The current maximum is 61 parameters (given a 1KB max request size, * and a 64-bit parameter size of 16 bytes). */ __u16 parm_count; /* * Parameters follow in form: * struct hgcm_function_parameter<32|64> parms[parm_count] */ }; VMMDEV_ASSERT_SIZE(vbg_ioctl_hgcm_call, 24 + 16); #define VBG_IOCTL_HGCM_CALL_32(s) _IOC(_IOC_READ | _IOC_WRITE, 'V', 6, s) #define VBG_IOCTL_HGCM_CALL_64(s) _IOC(_IOC_READ | _IOC_WRITE, 'V', 7, s) #if __BITS_PER_LONG == 64 #define VBG_IOCTL_HGCM_CALL(s) VBG_IOCTL_HGCM_CALL_64(s) #else #define VBG_IOCTL_HGCM_CALL(s) VBG_IOCTL_HGCM_CALL_32(s) #endif /** VBG_IOCTL_LOG data structure. */ struct vbg_ioctl_log { /** The header. */ struct vbg_ioctl_hdr hdr; union { struct { /** * The log message, this may be zero terminated. If it * is not zero terminated then the length is determined * from the input size. */ char msg[1]; } in; } u; }; #define VBG_IOCTL_LOG(s) _IOC(_IOC_READ | _IOC_WRITE, 'V', 9, s) /** VBG_IOCTL_WAIT_FOR_EVENTS data structure. */ struct vbg_ioctl_wait_for_events { /** The header. */ struct vbg_ioctl_hdr hdr; union { struct { /** Timeout in milliseconds. */ __u32 timeout_ms; /** Events to wait for. */ __u32 events; } in; struct { /** Events that occurred. */ __u32 events; } out; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_wait_for_events, 24 + 8); #define VBG_IOCTL_WAIT_FOR_EVENTS \ _IOWR('V', 10, struct vbg_ioctl_wait_for_events) /* * IOCTL to VBoxGuest to interrupt (cancel) any pending * VBG_IOCTL_WAIT_FOR_EVENTS and return. * * Handled inside the vboxguest driver and not seen by the host at all. * After calling this, VBG_IOCTL_WAIT_FOR_EVENTS should no longer be called in * the same session. Any VBOXGUEST_IOCTL_WAITEVENT calls in the same session * done after calling this will directly exit with -EINTR. */ #define VBG_IOCTL_INTERRUPT_ALL_WAIT_FOR_EVENTS \ _IOWR('V', 11, struct vbg_ioctl_hdr) /** VBG_IOCTL_CHANGE_FILTER_MASK data structure. */ struct vbg_ioctl_change_filter { /** The header. */ struct vbg_ioctl_hdr hdr; union { struct { /** Flags to set. */ __u32 or_mask; /** Flags to remove. */ __u32 not_mask; } in; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_change_filter, 24 + 8); /* IOCTL to VBoxGuest to control the event filter mask. */ #define VBG_IOCTL_CHANGE_FILTER_MASK \ _IOWR('V', 12, struct vbg_ioctl_change_filter) /** VBG_IOCTL_CHANGE_GUEST_CAPABILITIES data structure. */ struct vbg_ioctl_set_guest_caps { /** The header. */ struct vbg_ioctl_hdr hdr; union { struct { /** Capabilities to set (VMMDEV_GUEST_SUPPORTS_XXX). */ __u32 or_mask; /** Capabilities to drop (VMMDEV_GUEST_SUPPORTS_XXX). */ __u32 not_mask; } in; struct { /** Capabilities held by the session after the call. */ __u32 session_caps; /** Capabilities for all the sessions after the call. */ __u32 global_caps; } out; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_set_guest_caps, 24 + 8); #define VBG_IOCTL_CHANGE_GUEST_CAPABILITIES \ _IOWR('V', 14, struct vbg_ioctl_set_guest_caps) /** VBG_IOCTL_CHECK_BALLOON data structure. */ struct vbg_ioctl_check_balloon { /** The header. */ struct vbg_ioctl_hdr hdr; union { struct { /** The size of the balloon in chunks of 1MB. */ __u32 balloon_chunks; /** * false = handled in R0, no further action required. * true = allocate balloon memory in R3. */ __u8 handle_in_r3; /** Explicit padding, MBZ. */ __u8 padding[3]; } out; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_check_balloon, 24 + 8); /* * IOCTL to check memory ballooning. * * The guest kernel module will ask the host for the current size of the * balloon and adjust the size. Or it will set handle_in_r3 = true and R3 is * responsible for allocating memory and calling VBG_IOCTL_CHANGE_BALLOON. */ #define VBG_IOCTL_CHECK_BALLOON \ _IOWR('V', 17, struct vbg_ioctl_check_balloon) /** VBG_IOCTL_WRITE_CORE_DUMP data structure. */ struct vbg_ioctl_write_coredump { struct vbg_ioctl_hdr hdr; union { struct { __u32 flags; /** Flags (reserved, MBZ). */ } in; } u; }; VMMDEV_ASSERT_SIZE(vbg_ioctl_write_coredump, 24 + 4); #define VBG_IOCTL_WRITE_CORE_DUMP \ _IOWR('V', 19, struct vbg_ioctl_write_coredump) #endif linux/ivtvfb.h000064400000002267151027430560007366 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* On Screen Display cx23415 Framebuffer driver Copyright (C) 2006, 2007 Ian Armstrong This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LINUX_IVTVFB_H__ #define __LINUX_IVTVFB_H__ #include /* Framebuffer external API */ struct ivtvfb_dma_frame { void *source; unsigned long dest_offset; int count; }; #define IVTVFB_IOC_DMA_FRAME _IOW('V', BASE_VIDIOC_PRIVATE+0, struct ivtvfb_dma_frame) #endif linux/nfc.h000064400000025711151027430560006633 0ustar00/* * Copyright (C) 2011 Instituto Nokia de Tecnologia * * Authors: * Lauro Ramos Venancio * Aloisio Almeida Jr * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __LINUX_NFC_H #define __LINUX_NFC_H #include #include #define NFC_GENL_NAME "nfc" #define NFC_GENL_VERSION 1 #define NFC_GENL_MCAST_EVENT_NAME "events" /** * enum nfc_commands - supported nfc commands * * @NFC_CMD_UNSPEC: unspecified command * * @NFC_CMD_GET_DEVICE: request information about a device (requires * %NFC_ATTR_DEVICE_INDEX) or dump request to get a list of all nfc devices * @NFC_CMD_DEV_UP: turn on the nfc device * (requires %NFC_ATTR_DEVICE_INDEX) * @NFC_CMD_DEV_DOWN: turn off the nfc device * (requires %NFC_ATTR_DEVICE_INDEX) * @NFC_CMD_START_POLL: start polling for targets using the given protocols * (requires %NFC_ATTR_DEVICE_INDEX and %NFC_ATTR_PROTOCOLS) * @NFC_CMD_STOP_POLL: stop polling for targets (requires * %NFC_ATTR_DEVICE_INDEX) * @NFC_CMD_GET_TARGET: dump all targets found by the previous poll (requires * %NFC_ATTR_DEVICE_INDEX) * @NFC_EVENT_TARGETS_FOUND: event emitted when a new target is found * (it sends %NFC_ATTR_DEVICE_INDEX) * @NFC_EVENT_DEVICE_ADDED: event emitted when a new device is registred * (it sends %NFC_ATTR_DEVICE_NAME, %NFC_ATTR_DEVICE_INDEX and * %NFC_ATTR_PROTOCOLS) * @NFC_EVENT_DEVICE_REMOVED: event emitted when a device is removed * (it sends %NFC_ATTR_DEVICE_INDEX) * @NFC_EVENT_TM_ACTIVATED: event emitted when the adapter is activated in * target mode. * @NFC_EVENT_DEVICE_DEACTIVATED: event emitted when the adapter is deactivated * from target mode. * @NFC_CMD_LLC_GET_PARAMS: request LTO, RW, and MIUX parameters for a device * @NFC_CMD_LLC_SET_PARAMS: set one or more of LTO, RW, and MIUX parameters for * a device. LTO must be set before the link is up otherwise -EINPROGRESS * is returned. RW and MIUX can be set at anytime and will be passed in * subsequent CONNECT and CC messages. * If one of the passed parameters is wrong none is set and -EINVAL is * returned. * @NFC_CMD_ENABLE_SE: Enable the physical link to a specific secure element. * Once enabled a secure element will handle card emulation mode, i.e. * starting a poll from a device which has a secure element enabled means * we want to do SE based card emulation. * @NFC_CMD_DISABLE_SE: Disable the physical link to a specific secure element. * @NFC_CMD_FW_DOWNLOAD: Request to Load/flash firmware, or event to inform * that some firmware was loaded * @NFC_EVENT_SE_ADDED: Event emitted when a new secure element is discovered. * This typically will be sent whenever a new NFC controller with either * an embedded SE or an UICC one connected to it through SWP. * @NFC_EVENT_SE_REMOVED: Event emitted when a secure element is removed from * the system, as a consequence of e.g. an NFC controller being unplugged. * @NFC_EVENT_SE_CONNECTIVITY: This event is emitted whenever a secure element * is requesting connectivity access. For example a UICC SE may need to * talk with a sleeping modem and will notify this need by sending this * event. It is then up to userspace to decide if it will wake the modem * up or not. * @NFC_EVENT_SE_TRANSACTION: This event is sent when an application running on * a specific SE notifies us about the end of a transaction. The parameter * for this event is the application ID (AID). * @NFC_CMD_GET_SE: Dump all discovered secure elements from an NFC controller. * @NFC_CMD_SE_IO: Send/Receive APDUs to/from the selected secure element. * @NFC_CMD_ACTIVATE_TARGET: Request NFC controller to reactivate target. * @NFC_CMD_VENDOR: Vendor specific command, to be implemented directly * from the driver in order to support hardware specific operations. * @NFC_CMD_DEACTIVATE_TARGET: Request NFC controller to deactivate target. */ enum nfc_commands { NFC_CMD_UNSPEC, NFC_CMD_GET_DEVICE, NFC_CMD_DEV_UP, NFC_CMD_DEV_DOWN, NFC_CMD_DEP_LINK_UP, NFC_CMD_DEP_LINK_DOWN, NFC_CMD_START_POLL, NFC_CMD_STOP_POLL, NFC_CMD_GET_TARGET, NFC_EVENT_TARGETS_FOUND, NFC_EVENT_DEVICE_ADDED, NFC_EVENT_DEVICE_REMOVED, NFC_EVENT_TARGET_LOST, NFC_EVENT_TM_ACTIVATED, NFC_EVENT_TM_DEACTIVATED, NFC_CMD_LLC_GET_PARAMS, NFC_CMD_LLC_SET_PARAMS, NFC_CMD_ENABLE_SE, NFC_CMD_DISABLE_SE, NFC_CMD_LLC_SDREQ, NFC_EVENT_LLC_SDRES, NFC_CMD_FW_DOWNLOAD, NFC_EVENT_SE_ADDED, NFC_EVENT_SE_REMOVED, NFC_EVENT_SE_CONNECTIVITY, NFC_EVENT_SE_TRANSACTION, NFC_CMD_GET_SE, NFC_CMD_SE_IO, NFC_CMD_ACTIVATE_TARGET, NFC_CMD_VENDOR, NFC_CMD_DEACTIVATE_TARGET, /* private: internal use only */ __NFC_CMD_AFTER_LAST }; #define NFC_CMD_MAX (__NFC_CMD_AFTER_LAST - 1) /** * enum nfc_attrs - supported nfc attributes * * @NFC_ATTR_UNSPEC: unspecified attribute * * @NFC_ATTR_DEVICE_INDEX: index of nfc device * @NFC_ATTR_DEVICE_NAME: device name, max 8 chars * @NFC_ATTR_PROTOCOLS: nfc protocols - bitwise or-ed combination from * NFC_PROTO_*_MASK constants * @NFC_ATTR_TARGET_INDEX: index of the nfc target * @NFC_ATTR_TARGET_SENS_RES: NFC-A targets extra information such as NFCID * @NFC_ATTR_TARGET_SEL_RES: NFC-A targets extra information (useful if the * target is not NFC-Forum compliant) * @NFC_ATTR_TARGET_NFCID1: NFC-A targets identifier, max 10 bytes * @NFC_ATTR_TARGET_SENSB_RES: NFC-B targets extra information, max 12 bytes * @NFC_ATTR_TARGET_SENSF_RES: NFC-F targets extra information, max 18 bytes * @NFC_ATTR_COMM_MODE: Passive or active mode * @NFC_ATTR_RF_MODE: Initiator or target * @NFC_ATTR_IM_PROTOCOLS: Initiator mode protocols to poll for * @NFC_ATTR_TM_PROTOCOLS: Target mode protocols to listen for * @NFC_ATTR_LLC_PARAM_LTO: Link TimeOut parameter * @NFC_ATTR_LLC_PARAM_RW: Receive Window size parameter * @NFC_ATTR_LLC_PARAM_MIUX: MIU eXtension parameter * @NFC_ATTR_SE: Available Secure Elements * @NFC_ATTR_FIRMWARE_NAME: Free format firmware version * @NFC_ATTR_SE_INDEX: Secure element index * @NFC_ATTR_SE_TYPE: Secure element type (UICC or EMBEDDED) * @NFC_ATTR_FIRMWARE_DOWNLOAD_STATUS: Firmware download operation status * @NFC_ATTR_APDU: Secure element APDU * @NFC_ATTR_TARGET_ISO15693_DSFID: ISO 15693 Data Storage Format Identifier * @NFC_ATTR_TARGET_ISO15693_UID: ISO 15693 Unique Identifier * @NFC_ATTR_SE_PARAMS: Parameters data from an evt_transaction * @NFC_ATTR_VENDOR_ID: NFC manufacturer unique ID, typically an OUI * @NFC_ATTR_VENDOR_SUBCMD: Vendor specific sub command * @NFC_ATTR_VENDOR_DATA: Vendor specific data, to be optionally passed * to a vendor specific command implementation */ enum nfc_attrs { NFC_ATTR_UNSPEC, NFC_ATTR_DEVICE_INDEX, NFC_ATTR_DEVICE_NAME, NFC_ATTR_PROTOCOLS, NFC_ATTR_TARGET_INDEX, NFC_ATTR_TARGET_SENS_RES, NFC_ATTR_TARGET_SEL_RES, NFC_ATTR_TARGET_NFCID1, NFC_ATTR_TARGET_SENSB_RES, NFC_ATTR_TARGET_SENSF_RES, NFC_ATTR_COMM_MODE, NFC_ATTR_RF_MODE, NFC_ATTR_DEVICE_POWERED, NFC_ATTR_IM_PROTOCOLS, NFC_ATTR_TM_PROTOCOLS, NFC_ATTR_LLC_PARAM_LTO, NFC_ATTR_LLC_PARAM_RW, NFC_ATTR_LLC_PARAM_MIUX, NFC_ATTR_SE, NFC_ATTR_LLC_SDP, NFC_ATTR_FIRMWARE_NAME, NFC_ATTR_SE_INDEX, NFC_ATTR_SE_TYPE, NFC_ATTR_SE_AID, NFC_ATTR_FIRMWARE_DOWNLOAD_STATUS, NFC_ATTR_SE_APDU, NFC_ATTR_TARGET_ISO15693_DSFID, NFC_ATTR_TARGET_ISO15693_UID, NFC_ATTR_SE_PARAMS, NFC_ATTR_VENDOR_ID, NFC_ATTR_VENDOR_SUBCMD, NFC_ATTR_VENDOR_DATA, /* private: internal use only */ __NFC_ATTR_AFTER_LAST }; #define NFC_ATTR_MAX (__NFC_ATTR_AFTER_LAST - 1) enum nfc_sdp_attr { NFC_SDP_ATTR_UNSPEC, NFC_SDP_ATTR_URI, NFC_SDP_ATTR_SAP, /* private: internal use only */ __NFC_SDP_ATTR_AFTER_LAST }; #define NFC_SDP_ATTR_MAX (__NFC_SDP_ATTR_AFTER_LAST - 1) #define NFC_DEVICE_NAME_MAXSIZE 8 #define NFC_NFCID1_MAXSIZE 10 #define NFC_NFCID2_MAXSIZE 8 #define NFC_NFCID3_MAXSIZE 10 #define NFC_SENSB_RES_MAXSIZE 12 #define NFC_SENSF_RES_MAXSIZE 18 #define NFC_ATR_REQ_MAXSIZE 64 #define NFC_ATR_RES_MAXSIZE 64 #define NFC_ATR_REQ_GB_MAXSIZE 48 #define NFC_ATR_RES_GB_MAXSIZE 47 #define NFC_GB_MAXSIZE 48 #define NFC_FIRMWARE_NAME_MAXSIZE 32 #define NFC_ISO15693_UID_MAXSIZE 8 /* NFC protocols */ #define NFC_PROTO_JEWEL 1 #define NFC_PROTO_MIFARE 2 #define NFC_PROTO_FELICA 3 #define NFC_PROTO_ISO14443 4 #define NFC_PROTO_NFC_DEP 5 #define NFC_PROTO_ISO14443_B 6 #define NFC_PROTO_ISO15693 7 #define NFC_PROTO_MAX 8 /* NFC communication modes */ #define NFC_COMM_ACTIVE 0 #define NFC_COMM_PASSIVE 1 /* NFC RF modes */ #define NFC_RF_INITIATOR 0 #define NFC_RF_TARGET 1 #define NFC_RF_NONE 2 /* NFC protocols masks used in bitsets */ #define NFC_PROTO_JEWEL_MASK (1 << NFC_PROTO_JEWEL) #define NFC_PROTO_MIFARE_MASK (1 << NFC_PROTO_MIFARE) #define NFC_PROTO_FELICA_MASK (1 << NFC_PROTO_FELICA) #define NFC_PROTO_ISO14443_MASK (1 << NFC_PROTO_ISO14443) #define NFC_PROTO_NFC_DEP_MASK (1 << NFC_PROTO_NFC_DEP) #define NFC_PROTO_ISO14443_B_MASK (1 << NFC_PROTO_ISO14443_B) #define NFC_PROTO_ISO15693_MASK (1 << NFC_PROTO_ISO15693) /* NFC Secure Elements */ #define NFC_SE_UICC 0x1 #define NFC_SE_EMBEDDED 0x2 #define NFC_SE_DISABLED 0x0 #define NFC_SE_ENABLED 0x1 struct sockaddr_nfc { sa_family_t sa_family; __u32 dev_idx; __u32 target_idx; __u32 nfc_protocol; }; #define NFC_LLCP_MAX_SERVICE_NAME 63 struct sockaddr_nfc_llcp { sa_family_t sa_family; __u32 dev_idx; __u32 target_idx; __u32 nfc_protocol; __u8 dsap; /* Destination SAP, if known */ __u8 ssap; /* Source SAP to be bound to */ char service_name[NFC_LLCP_MAX_SERVICE_NAME]; /* Service name URI */; size_t service_name_len; }; /* NFC socket protocols */ #define NFC_SOCKPROTO_RAW 0 #define NFC_SOCKPROTO_LLCP 1 #define NFC_SOCKPROTO_MAX 2 #define NFC_HEADER_SIZE 1 /** * Pseudo-header info for raw socket packets * First byte is the adapter index * Second byte contains flags * - 0x01 - Direction (0=RX, 1=TX) * - 0x02-0x04 - Payload type (000=LLCP, 001=NCI, 010=HCI, 011=Digital, * 100=Proprietary) * - 0x05-0x80 - Reserved **/ #define NFC_RAW_HEADER_SIZE 2 #define NFC_DIRECTION_RX 0x00 #define NFC_DIRECTION_TX 0x01 #define RAW_PAYLOAD_LLCP 0 #define RAW_PAYLOAD_NCI 1 #define RAW_PAYLOAD_HCI 2 #define RAW_PAYLOAD_DIGITAL 3 #define RAW_PAYLOAD_PROPRIETARY 4 /* socket option names */ #define NFC_LLCP_RW 0 #define NFC_LLCP_MIUX 1 #define NFC_LLCP_REMOTE_MIU 2 #define NFC_LLCP_REMOTE_LTO 3 #define NFC_LLCP_REMOTE_RW 4 #endif /*__LINUX_NFC_H */ linux/batman_adv.h000064400000027311151027430560010157 0ustar00/* SPDX-License-Identifier: MIT */ /* Copyright (C) 2016-2018 B.A.T.M.A.N. contributors: * * Matthias Schiffer * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef _LINUX_BATMAN_ADV_H_ #define _LINUX_BATMAN_ADV_H_ #define BATADV_NL_NAME "batadv" #define BATADV_NL_MCAST_GROUP_TPMETER "tpmeter" /** * enum batadv_tt_client_flags - TT client specific flags * * Bits from 0 to 7 are called _remote flags_ because they are sent on the wire. * Bits from 8 to 15 are called _local flags_ because they are used for local * computations only. * * Bits from 4 to 7 - a subset of remote flags - are ensured to be in sync with * the other nodes in the network. To achieve this goal these flags are included * in the TT CRC computation. */ enum batadv_tt_client_flags { /** * @BATADV_TT_CLIENT_DEL: the client has to be deleted from the table */ BATADV_TT_CLIENT_DEL = (1 << 0), /** * @BATADV_TT_CLIENT_ROAM: the client roamed to/from another node and * the new update telling its new real location has not been * received/sent yet */ BATADV_TT_CLIENT_ROAM = (1 << 1), /** * @BATADV_TT_CLIENT_WIFI: this client is connected through a wifi * interface. This information is used by the "AP Isolation" feature */ BATADV_TT_CLIENT_WIFI = (1 << 4), /** * @BATADV_TT_CLIENT_ISOLA: this client is considered "isolated". This * information is used by the Extended Isolation feature */ BATADV_TT_CLIENT_ISOLA = (1 << 5), /** * @BATADV_TT_CLIENT_NOPURGE: this client should never be removed from * the table */ BATADV_TT_CLIENT_NOPURGE = (1 << 8), /** * @BATADV_TT_CLIENT_NEW: this client has been added to the local table * but has not been announced yet */ BATADV_TT_CLIENT_NEW = (1 << 9), /** * @BATADV_TT_CLIENT_PENDING: this client is marked for removal but it * is kept in the table for one more originator interval for consistency * purposes */ BATADV_TT_CLIENT_PENDING = (1 << 10), /** * @BATADV_TT_CLIENT_TEMP: this global client has been detected to be * part of the network but no nnode has already announced it */ BATADV_TT_CLIENT_TEMP = (1 << 11), }; /** * enum batadv_mcast_flags_priv - Private, own multicast flags * * These are internal, multicast related flags. Currently they describe certain * multicast related attributes of the segment this originator bridges into the * mesh. * * Those attributes are used to determine the public multicast flags this * originator is going to announce via TT. * * For netlink, if BATADV_MCAST_FLAGS_BRIDGED is unset then all querier * related flags are undefined. */ enum batadv_mcast_flags_priv { /** * @BATADV_MCAST_FLAGS_BRIDGED: There is a bridge on top of the mesh * interface. */ BATADV_MCAST_FLAGS_BRIDGED = (1 << 0), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV4_EXISTS: Whether an IGMP querier * exists in the mesh */ BATADV_MCAST_FLAGS_QUERIER_IPV4_EXISTS = (1 << 1), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV6_EXISTS: Whether an MLD querier * exists in the mesh */ BATADV_MCAST_FLAGS_QUERIER_IPV6_EXISTS = (1 << 2), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV4_SHADOWING: If an IGMP querier * exists, whether it is potentially shadowing multicast listeners * (i.e. querier is behind our own bridge segment) */ BATADV_MCAST_FLAGS_QUERIER_IPV4_SHADOWING = (1 << 3), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV6_SHADOWING: If an MLD querier * exists, whether it is potentially shadowing multicast listeners * (i.e. querier is behind our own bridge segment) */ BATADV_MCAST_FLAGS_QUERIER_IPV6_SHADOWING = (1 << 4), }; /** * enum batadv_nl_attrs - batman-adv netlink attributes */ enum batadv_nl_attrs { /** * @BATADV_ATTR_UNSPEC: unspecified attribute to catch errors */ BATADV_ATTR_UNSPEC, /** * @BATADV_ATTR_VERSION: batman-adv version string */ BATADV_ATTR_VERSION, /** * @BATADV_ATTR_ALGO_NAME: name of routing algorithm */ BATADV_ATTR_ALGO_NAME, /** * @BATADV_ATTR_MESH_IFINDEX: index of the batman-adv interface */ BATADV_ATTR_MESH_IFINDEX, /** * @BATADV_ATTR_MESH_IFNAME: name of the batman-adv interface */ BATADV_ATTR_MESH_IFNAME, /** * @BATADV_ATTR_MESH_ADDRESS: mac address of the batman-adv interface */ BATADV_ATTR_MESH_ADDRESS, /** * @BATADV_ATTR_HARD_IFINDEX: index of the non-batman-adv interface */ BATADV_ATTR_HARD_IFINDEX, /** * @BATADV_ATTR_HARD_IFNAME: name of the non-batman-adv interface */ BATADV_ATTR_HARD_IFNAME, /** * @BATADV_ATTR_HARD_ADDRESS: mac address of the non-batman-adv * interface */ BATADV_ATTR_HARD_ADDRESS, /** * @BATADV_ATTR_ORIG_ADDRESS: originator mac address */ BATADV_ATTR_ORIG_ADDRESS, /** * @BATADV_ATTR_TPMETER_RESULT: result of run (see * batadv_tp_meter_status) */ BATADV_ATTR_TPMETER_RESULT, /** * @BATADV_ATTR_TPMETER_TEST_TIME: time (msec) the run took */ BATADV_ATTR_TPMETER_TEST_TIME, /** * @BATADV_ATTR_TPMETER_BYTES: amount of acked bytes during run */ BATADV_ATTR_TPMETER_BYTES, /** * @BATADV_ATTR_TPMETER_COOKIE: session cookie to match tp_meter session */ BATADV_ATTR_TPMETER_COOKIE, /** * @BATADV_ATTR_PAD: attribute used for padding for 64-bit alignment */ BATADV_ATTR_PAD, /** * @BATADV_ATTR_ACTIVE: Flag indicating if the hard interface is active */ BATADV_ATTR_ACTIVE, /** * @BATADV_ATTR_TT_ADDRESS: Client MAC address */ BATADV_ATTR_TT_ADDRESS, /** * @BATADV_ATTR_TT_TTVN: Translation table version */ BATADV_ATTR_TT_TTVN, /** * @BATADV_ATTR_TT_LAST_TTVN: Previous translation table version */ BATADV_ATTR_TT_LAST_TTVN, /** * @BATADV_ATTR_TT_CRC32: CRC32 over translation table */ BATADV_ATTR_TT_CRC32, /** * @BATADV_ATTR_TT_VID: VLAN ID */ BATADV_ATTR_TT_VID, /** * @BATADV_ATTR_TT_FLAGS: Translation table client flags */ BATADV_ATTR_TT_FLAGS, /** * @BATADV_ATTR_FLAG_BEST: Flags indicating entry is the best */ BATADV_ATTR_FLAG_BEST, /** * @BATADV_ATTR_LAST_SEEN_MSECS: Time in milliseconds since last seen */ BATADV_ATTR_LAST_SEEN_MSECS, /** * @BATADV_ATTR_NEIGH_ADDRESS: Neighbour MAC address */ BATADV_ATTR_NEIGH_ADDRESS, /** * @BATADV_ATTR_TQ: TQ to neighbour */ BATADV_ATTR_TQ, /** * @BATADV_ATTR_THROUGHPUT: Estimated throughput to Neighbour */ BATADV_ATTR_THROUGHPUT, /** * @BATADV_ATTR_BANDWIDTH_UP: Reported uplink bandwidth */ BATADV_ATTR_BANDWIDTH_UP, /** * @BATADV_ATTR_BANDWIDTH_DOWN: Reported downlink bandwidth */ BATADV_ATTR_BANDWIDTH_DOWN, /** * @BATADV_ATTR_ROUTER: Gateway router MAC address */ BATADV_ATTR_ROUTER, /** * @BATADV_ATTR_BLA_OWN: Flag indicating own originator */ BATADV_ATTR_BLA_OWN, /** * @BATADV_ATTR_BLA_ADDRESS: Bridge loop avoidance claim MAC address */ BATADV_ATTR_BLA_ADDRESS, /** * @BATADV_ATTR_BLA_VID: BLA VLAN ID */ BATADV_ATTR_BLA_VID, /** * @BATADV_ATTR_BLA_BACKBONE: BLA gateway originator MAC address */ BATADV_ATTR_BLA_BACKBONE, /** * @BATADV_ATTR_BLA_CRC: BLA CRC */ BATADV_ATTR_BLA_CRC, /** * @BATADV_ATTR_DAT_CACHE_IP4ADDRESS: Client IPv4 address */ BATADV_ATTR_DAT_CACHE_IP4ADDRESS, /** * @BATADV_ATTR_DAT_CACHE_HWADDRESS: Client MAC address */ BATADV_ATTR_DAT_CACHE_HWADDRESS, /** * @BATADV_ATTR_DAT_CACHE_VID: VLAN ID */ BATADV_ATTR_DAT_CACHE_VID, /** * @BATADV_ATTR_MCAST_FLAGS: Per originator multicast flags */ BATADV_ATTR_MCAST_FLAGS, /** * @BATADV_ATTR_MCAST_FLAGS_PRIV: Private, own multicast flags */ BATADV_ATTR_MCAST_FLAGS_PRIV, /* add attributes above here, update the policy in netlink.c */ /** * @__BATADV_ATTR_AFTER_LAST: internal use */ __BATADV_ATTR_AFTER_LAST, /** * @NUM_BATADV_ATTR: total number of batadv_nl_attrs available */ NUM_BATADV_ATTR = __BATADV_ATTR_AFTER_LAST, /** * @BATADV_ATTR_MAX: highest attribute number currently defined */ BATADV_ATTR_MAX = __BATADV_ATTR_AFTER_LAST - 1 }; /** * enum batadv_nl_commands - supported batman-adv netlink commands */ enum batadv_nl_commands { /** * @BATADV_CMD_UNSPEC: unspecified command to catch errors */ BATADV_CMD_UNSPEC, /** * @BATADV_CMD_GET_MESH_INFO: Query basic information about batman-adv * device */ BATADV_CMD_GET_MESH_INFO, /** * @BATADV_CMD_TP_METER: Start a tp meter session */ BATADV_CMD_TP_METER, /** * @BATADV_CMD_TP_METER_CANCEL: Cancel a tp meter session */ BATADV_CMD_TP_METER_CANCEL, /** * @BATADV_CMD_GET_ROUTING_ALGOS: Query the list of routing algorithms. */ BATADV_CMD_GET_ROUTING_ALGOS, /** * @BATADV_CMD_GET_HARDIFS: Query list of hard interfaces */ BATADV_CMD_GET_HARDIFS, /** * @BATADV_CMD_GET_TRANSTABLE_LOCAL: Query list of local translations */ BATADV_CMD_GET_TRANSTABLE_LOCAL, /** * @BATADV_CMD_GET_TRANSTABLE_GLOBAL: Query list of global translations */ BATADV_CMD_GET_TRANSTABLE_GLOBAL, /** * @BATADV_CMD_GET_ORIGINATORS: Query list of originators */ BATADV_CMD_GET_ORIGINATORS, /** * @BATADV_CMD_GET_NEIGHBORS: Query list of neighbours */ BATADV_CMD_GET_NEIGHBORS, /** * @BATADV_CMD_GET_GATEWAYS: Query list of gateways */ BATADV_CMD_GET_GATEWAYS, /** * @BATADV_CMD_GET_BLA_CLAIM: Query list of bridge loop avoidance claims */ BATADV_CMD_GET_BLA_CLAIM, /** * @BATADV_CMD_GET_BLA_BACKBONE: Query list of bridge loop avoidance * backbones */ BATADV_CMD_GET_BLA_BACKBONE, /** * @BATADV_CMD_GET_DAT_CACHE: Query list of DAT cache entries */ BATADV_CMD_GET_DAT_CACHE, /** * @BATADV_CMD_GET_MCAST_FLAGS: Query list of multicast flags */ BATADV_CMD_GET_MCAST_FLAGS, /* add new commands above here */ /** * @__BATADV_CMD_AFTER_LAST: internal use */ __BATADV_CMD_AFTER_LAST, /** * @BATADV_CMD_MAX: highest used command number */ BATADV_CMD_MAX = __BATADV_CMD_AFTER_LAST - 1 }; /** * enum batadv_tp_meter_reason - reason of a tp meter test run stop */ enum batadv_tp_meter_reason { /** * @BATADV_TP_REASON_COMPLETE: sender finished tp run */ BATADV_TP_REASON_COMPLETE = 3, /** * @BATADV_TP_REASON_CANCEL: sender was stopped during run */ BATADV_TP_REASON_CANCEL = 4, /* error status >= 128 */ /** * @BATADV_TP_REASON_DST_UNREACHABLE: receiver could not be reached or * didn't answer */ BATADV_TP_REASON_DST_UNREACHABLE = 128, /** * @BATADV_TP_REASON_RESEND_LIMIT: (unused) sender retry reached limit */ BATADV_TP_REASON_RESEND_LIMIT = 129, /** * @BATADV_TP_REASON_ALREADY_ONGOING: test to or from the same node * already ongoing */ BATADV_TP_REASON_ALREADY_ONGOING = 130, /** * @BATADV_TP_REASON_MEMORY_ERROR: test was stopped due to low memory */ BATADV_TP_REASON_MEMORY_ERROR = 131, /** * @BATADV_TP_REASON_CANT_SEND: failed to send via outgoing interface */ BATADV_TP_REASON_CANT_SEND = 132, /** * @BATADV_TP_REASON_TOO_MANY: too many ongoing sessions */ BATADV_TP_REASON_TOO_MANY = 133, }; #endif /* _LINUX_BATMAN_ADV_H_ */ linux/coda_psdev.h000064400000001417151027430560010171 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __CODA_PSDEV_H #define __CODA_PSDEV_H #include #define CODA_PSDEV_MAJOR 67 #define MAX_CODADEVS 5 /* how many do we allow */ /* messages between coda filesystem in kernel and Venus */ struct upc_req { struct list_head uc_chain; caddr_t uc_data; u_short uc_flags; u_short uc_inSize; /* Size is at most 5000 bytes */ u_short uc_outSize; u_short uc_opcode; /* copied from data to save lookup */ int uc_unique; wait_queue_head_t uc_sleep; /* process' wait queue */ }; #define CODA_REQ_ASYNC 0x1 #define CODA_REQ_READ 0x2 #define CODA_REQ_WRITE 0x4 #define CODA_REQ_ABORT 0x8 #endif /* __CODA_PSDEV_H */ linux/fou.h000064400000001266151027430560006655 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* fou.h - FOU Interface */ #ifndef _LINUX_FOU_H #define _LINUX_FOU_H /* NETLINK_GENERIC related info */ #define FOU_GENL_NAME "fou" #define FOU_GENL_VERSION 0x1 enum { FOU_ATTR_UNSPEC, FOU_ATTR_PORT, /* u16 */ FOU_ATTR_AF, /* u8 */ FOU_ATTR_IPPROTO, /* u8 */ FOU_ATTR_TYPE, /* u8 */ FOU_ATTR_REMCSUM_NOPARTIAL, /* flag */ __FOU_ATTR_MAX, }; #define FOU_ATTR_MAX (__FOU_ATTR_MAX - 1) enum { FOU_CMD_UNSPEC, FOU_CMD_ADD, FOU_CMD_DEL, FOU_CMD_GET, __FOU_CMD_MAX, }; enum { FOU_ENCAP_UNSPEC, FOU_ENCAP_DIRECT, FOU_ENCAP_GUE, }; #define FOU_CMD_MAX (__FOU_CMD_MAX - 1) #endif /* _LINUX_FOU_H */ linux/ppp_defs.h000064400000011763151027430560007667 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ppp_defs.h - PPP definitions. * * Copyright 1994-2000 Paul Mackerras. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #include #ifndef _PPP_DEFS_H_ #define _PPP_DEFS_H_ /* * The basic PPP frame. */ #define PPP_HDRLEN 4 /* octets for standard ppp header */ #define PPP_FCSLEN 2 /* octets for FCS */ #define PPP_MRU 1500 /* default MRU = max length of info field */ #define PPP_ADDRESS(p) (((__u8 *)(p))[0]) #define PPP_CONTROL(p) (((__u8 *)(p))[1]) #define PPP_PROTOCOL(p) ((((__u8 *)(p))[2] << 8) + ((__u8 *)(p))[3]) /* * Significant octet values. */ #define PPP_ALLSTATIONS 0xff /* All-Stations broadcast address */ #define PPP_UI 0x03 /* Unnumbered Information */ #define PPP_FLAG 0x7e /* Flag Sequence */ #define PPP_ESCAPE 0x7d /* Asynchronous Control Escape */ #define PPP_TRANS 0x20 /* Asynchronous transparency modifier */ /* * Protocol field values. */ #define PPP_IP 0x21 /* Internet Protocol */ #define PPP_AT 0x29 /* AppleTalk Protocol */ #define PPP_IPX 0x2b /* IPX protocol */ #define PPP_VJC_COMP 0x2d /* VJ compressed TCP */ #define PPP_VJC_UNCOMP 0x2f /* VJ uncompressed TCP */ #define PPP_MP 0x3d /* Multilink protocol */ #define PPP_IPV6 0x57 /* Internet Protocol Version 6 */ #define PPP_COMPFRAG 0xfb /* fragment compressed below bundle */ #define PPP_COMP 0xfd /* compressed packet */ #define PPP_MPLS_UC 0x0281 /* Multi Protocol Label Switching - Unicast */ #define PPP_MPLS_MC 0x0283 /* Multi Protocol Label Switching - Multicast */ #define PPP_IPCP 0x8021 /* IP Control Protocol */ #define PPP_ATCP 0x8029 /* AppleTalk Control Protocol */ #define PPP_IPXCP 0x802b /* IPX Control Protocol */ #define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ #define PPP_CCPFRAG 0x80fb /* CCP at link level (below MP bundle) */ #define PPP_CCP 0x80fd /* Compression Control Protocol */ #define PPP_MPLSCP 0x80fd /* MPLS Control Protocol */ #define PPP_LCP 0xc021 /* Link Control Protocol */ #define PPP_PAP 0xc023 /* Password Authentication Protocol */ #define PPP_LQR 0xc025 /* Link Quality Report protocol */ #define PPP_CHAP 0xc223 /* Cryptographic Handshake Auth. Protocol */ #define PPP_CBCP 0xc029 /* Callback Control Protocol */ /* * Values for FCS calculations. */ #define PPP_INITFCS 0xffff /* Initial FCS value */ #define PPP_GOODFCS 0xf0b8 /* Good final FCS value */ /* * Extended asyncmap - allows any character to be escaped. */ typedef __u32 ext_accm[8]; /* * What to do with network protocol (NP) packets. */ enum NPmode { NPMODE_PASS, /* pass the packet through */ NPMODE_DROP, /* silently drop the packet */ NPMODE_ERROR, /* return an error */ NPMODE_QUEUE /* save it up for later. */ }; /* * Statistics for LQRP and pppstats */ struct pppstat { __u32 ppp_discards; /* # frames discarded */ __u32 ppp_ibytes; /* bytes received */ __u32 ppp_ioctects; /* bytes received not in error */ __u32 ppp_ipackets; /* packets received */ __u32 ppp_ierrors; /* receive errors */ __u32 ppp_ilqrs; /* # LQR frames received */ __u32 ppp_obytes; /* raw bytes sent */ __u32 ppp_ooctects; /* frame bytes sent */ __u32 ppp_opackets; /* packets sent */ __u32 ppp_oerrors; /* transmit errors */ __u32 ppp_olqrs; /* # LQR frames sent */ }; struct vjstat { __u32 vjs_packets; /* outbound packets */ __u32 vjs_compressed; /* outbound compressed packets */ __u32 vjs_searches; /* searches for connection state */ __u32 vjs_misses; /* times couldn't find conn. state */ __u32 vjs_uncompressedin; /* inbound uncompressed packets */ __u32 vjs_compressedin; /* inbound compressed packets */ __u32 vjs_errorin; /* inbound unknown type packets */ __u32 vjs_tossed; /* inbound packets tossed because of error */ }; struct compstat { __u32 unc_bytes; /* total uncompressed bytes */ __u32 unc_packets; /* total uncompressed packets */ __u32 comp_bytes; /* compressed bytes */ __u32 comp_packets; /* compressed packets */ __u32 inc_bytes; /* incompressible bytes */ __u32 inc_packets; /* incompressible packets */ /* the compression ratio is defined as in_count / bytes_out */ __u32 in_count; /* Bytes received */ __u32 bytes_out; /* Bytes transmitted */ double ratio; /* not computed in kernel. */ }; struct ppp_stats { struct pppstat p; /* basic PPP statistics */ struct vjstat vj; /* VJ header compression statistics */ }; struct ppp_comp_stats { struct compstat c; /* packet compression statistics */ struct compstat d; /* packet decompression statistics */ }; /* * The following structure records the time in seconds since * the last NP packet was sent or received. */ struct ppp_idle { __kernel_time_t xmit_idle; /* time since last NP packet sent */ __kernel_time_t recv_idle; /* time since last NP packet received */ }; #endif /* _PPP_DEFS_H_ */ linux/qrtr.h000064400000001575151027430560007057 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_QRTR_H #define _LINUX_QRTR_H #include #include #define QRTR_NODE_BCAST 0xffffffffu #define QRTR_PORT_CTRL 0xfffffffeu struct sockaddr_qrtr { __kernel_sa_family_t sq_family; __u32 sq_node; __u32 sq_port; }; enum qrtr_pkt_type { QRTR_TYPE_DATA = 1, QRTR_TYPE_HELLO = 2, QRTR_TYPE_BYE = 3, QRTR_TYPE_NEW_SERVER = 4, QRTR_TYPE_DEL_SERVER = 5, QRTR_TYPE_DEL_CLIENT = 6, QRTR_TYPE_RESUME_TX = 7, QRTR_TYPE_EXIT = 8, QRTR_TYPE_PING = 9, QRTR_TYPE_NEW_LOOKUP = 10, QRTR_TYPE_DEL_LOOKUP = 11, }; struct qrtr_ctrl_pkt { __le32 cmd; union { struct { __le32 service; __le32 instance; __le32 node; __le32 port; } server; struct { __le32 node; __le32 port; } client; }; } __attribute__((packed)); #endif /* _LINUX_QRTR_H */ linux/nvme_ioctl.h000064400000004100151027430560010211 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Definitions for the NVM Express ioctl interface * Copyright (c) 2011-2014, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #ifndef _LINUX_NVME_IOCTL_H #define _LINUX_NVME_IOCTL_H #include struct nvme_user_io { __u8 opcode; __u8 flags; __u16 control; __u16 nblocks; __u16 rsvd; __u64 metadata; __u64 addr; __u64 slba; __u32 dsmgmt; __u32 reftag; __u16 apptag; __u16 appmask; }; struct nvme_passthru_cmd { __u8 opcode; __u8 flags; __u16 rsvd1; __u32 nsid; __u32 cdw2; __u32 cdw3; __u64 metadata; __u64 addr; __u32 metadata_len; __u32 data_len; __u32 cdw10; __u32 cdw11; __u32 cdw12; __u32 cdw13; __u32 cdw14; __u32 cdw15; __u32 timeout_ms; __u32 result; }; struct nvme_passthru_cmd64 { __u8 opcode; __u8 flags; __u16 rsvd1; __u32 nsid; __u32 cdw2; __u32 cdw3; __u64 metadata; __u64 addr; __u32 metadata_len; __u32 data_len; __u32 cdw10; __u32 cdw11; __u32 cdw12; __u32 cdw13; __u32 cdw14; __u32 cdw15; __u32 timeout_ms; __u32 rsvd2; __u64 result; }; #define nvme_admin_cmd nvme_passthru_cmd #define NVME_IOCTL_ID _IO('N', 0x40) #define NVME_IOCTL_ADMIN_CMD _IOWR('N', 0x41, struct nvme_admin_cmd) #define NVME_IOCTL_SUBMIT_IO _IOW('N', 0x42, struct nvme_user_io) #define NVME_IOCTL_IO_CMD _IOWR('N', 0x43, struct nvme_passthru_cmd) #define NVME_IOCTL_RESET _IO('N', 0x44) #define NVME_IOCTL_SUBSYS_RESET _IO('N', 0x45) #define NVME_IOCTL_RESCAN _IO('N', 0x46) #define NVME_IOCTL_ADMIN64_CMD _IOWR('N', 0x47, struct nvme_passthru_cmd64) #define NVME_IOCTL_IO64_CMD _IOWR('N', 0x48, struct nvme_passthru_cmd64) #endif /* _LINUX_NVME_IOCTL_H */ linux/if.h000064400000025225151027430560006463 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the INET interface module. * * Version: @(#)if.h 1.0.2 04/18/93 * * Authors: Original taken from Berkeley UNIX 4.3, (c) UCB 1982-1988 * Ross Biro * Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_H #define _LINUX_IF_H #include /* for compatibility with glibc */ #include /* for "__kernel_caddr_t" et al */ #include /* for "struct sockaddr" et al */ /* for "__user" et al */ #include /* for struct sockaddr. */ #if __UAPI_DEF_IF_IFNAMSIZ #define IFNAMSIZ 16 #endif /* __UAPI_DEF_IF_IFNAMSIZ */ #define IFALIASZ 256 #define ALTIFNAMSIZ 128 #include /* For glibc compatibility. An empty enum does not compile. */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO != 0 || \ __UAPI_DEF_IF_NET_DEVICE_FLAGS != 0 /** * enum net_device_flags - &struct net_device flags * * These are the &struct net_device flags, they can be set by drivers, the * kernel and some can be triggered by userspace. Userspace can query and * set these flags using userspace utilities but there is also a sysfs * entry available for all dev flags which can be queried and set. These flags * are shared for all types of net_devices. The sysfs entries are available * via /sys/class/net//flags. Flags which can be toggled through sysfs * are annotated below, note that only a few flags can be toggled and some * other flags are always preserved from the original net_device flags * even if you try to set them via sysfs. Flags which are always preserved * are kept under the flag grouping @IFF_VOLATILE. Flags which are __volatile__ * are annotated below as such. * * You should have a pretty good reason to be extending these flags. * * @IFF_UP: interface is up. Can be toggled through sysfs. * @IFF_BROADCAST: broadcast address valid. Volatile. * @IFF_DEBUG: turn on debugging. Can be toggled through sysfs. * @IFF_LOOPBACK: is a loopback net. Volatile. * @IFF_POINTOPOINT: interface is has p-p link. Volatile. * @IFF_NOTRAILERS: avoid use of trailers. Can be toggled through sysfs. * Volatile. * @IFF_RUNNING: interface RFC2863 OPER_UP. Volatile. * @IFF_NOARP: no ARP protocol. Can be toggled through sysfs. Volatile. * @IFF_PROMISC: receive all packets. Can be toggled through sysfs. * @IFF_ALLMULTI: receive all multicast packets. Can be toggled through * sysfs. * @IFF_MASTER: master of a load balancer. Volatile. * @IFF_SLAVE: slave of a load balancer. Volatile. * @IFF_MULTICAST: Supports multicast. Can be toggled through sysfs. * @IFF_PORTSEL: can set media type. Can be toggled through sysfs. * @IFF_AUTOMEDIA: auto media select active. Can be toggled through sysfs. * @IFF_DYNAMIC: dialup device with changing addresses. Can be toggled * through sysfs. * @IFF_LOWER_UP: driver signals L1 up. Volatile. * @IFF_DORMANT: driver signals dormant. Volatile. * @IFF_ECHO: echo sent packets. Volatile. */ enum net_device_flags { /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS IFF_UP = 1<<0, /* sysfs */ IFF_BROADCAST = 1<<1, /* __volatile__ */ IFF_DEBUG = 1<<2, /* sysfs */ IFF_LOOPBACK = 1<<3, /* __volatile__ */ IFF_POINTOPOINT = 1<<4, /* __volatile__ */ IFF_NOTRAILERS = 1<<5, /* sysfs */ IFF_RUNNING = 1<<6, /* __volatile__ */ IFF_NOARP = 1<<7, /* sysfs */ IFF_PROMISC = 1<<8, /* sysfs */ IFF_ALLMULTI = 1<<9, /* sysfs */ IFF_MASTER = 1<<10, /* __volatile__ */ IFF_SLAVE = 1<<11, /* __volatile__ */ IFF_MULTICAST = 1<<12, /* sysfs */ IFF_PORTSEL = 1<<13, /* sysfs */ IFF_AUTOMEDIA = 1<<14, /* sysfs */ IFF_DYNAMIC = 1<<15, /* sysfs */ #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO IFF_LOWER_UP = 1<<16, /* __volatile__ */ IFF_DORMANT = 1<<17, /* __volatile__ */ IFF_ECHO = 1<<18, /* __volatile__ */ #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO */ }; #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO != 0 || __UAPI_DEF_IF_NET_DEVICE_FLAGS != 0 */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS #define IFF_UP IFF_UP #define IFF_BROADCAST IFF_BROADCAST #define IFF_DEBUG IFF_DEBUG #define IFF_LOOPBACK IFF_LOOPBACK #define IFF_POINTOPOINT IFF_POINTOPOINT #define IFF_NOTRAILERS IFF_NOTRAILERS #define IFF_RUNNING IFF_RUNNING #define IFF_NOARP IFF_NOARP #define IFF_PROMISC IFF_PROMISC #define IFF_ALLMULTI IFF_ALLMULTI #define IFF_MASTER IFF_MASTER #define IFF_SLAVE IFF_SLAVE #define IFF_MULTICAST IFF_MULTICAST #define IFF_PORTSEL IFF_PORTSEL #define IFF_AUTOMEDIA IFF_AUTOMEDIA #define IFF_DYNAMIC IFF_DYNAMIC #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO #define IFF_LOWER_UP IFF_LOWER_UP #define IFF_DORMANT IFF_DORMANT #define IFF_ECHO IFF_ECHO #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO */ #define IFF_VOLATILE (IFF_LOOPBACK|IFF_POINTOPOINT|IFF_BROADCAST|IFF_ECHO|\ IFF_MASTER|IFF_SLAVE|IFF_RUNNING|IFF_LOWER_UP|IFF_DORMANT) #define IF_GET_IFACE 0x0001 /* for querying only */ #define IF_GET_PROTO 0x0002 /* For definitions see hdlc.h */ #define IF_IFACE_V35 0x1000 /* V.35 serial interface */ #define IF_IFACE_V24 0x1001 /* V.24 serial interface */ #define IF_IFACE_X21 0x1002 /* X.21 serial interface */ #define IF_IFACE_T1 0x1003 /* T1 telco serial interface */ #define IF_IFACE_E1 0x1004 /* E1 telco serial interface */ #define IF_IFACE_SYNC_SERIAL 0x1005 /* can't be set by software */ #define IF_IFACE_X21D 0x1006 /* X.21 Dual Clocking (FarSite) */ /* For definitions see hdlc.h */ #define IF_PROTO_HDLC 0x2000 /* raw HDLC protocol */ #define IF_PROTO_PPP 0x2001 /* PPP protocol */ #define IF_PROTO_CISCO 0x2002 /* Cisco HDLC protocol */ #define IF_PROTO_FR 0x2003 /* Frame Relay protocol */ #define IF_PROTO_FR_ADD_PVC 0x2004 /* Create FR PVC */ #define IF_PROTO_FR_DEL_PVC 0x2005 /* Delete FR PVC */ #define IF_PROTO_X25 0x2006 /* X.25 */ #define IF_PROTO_HDLC_ETH 0x2007 /* raw HDLC, Ethernet emulation */ #define IF_PROTO_FR_ADD_ETH_PVC 0x2008 /* Create FR Ethernet-bridged PVC */ #define IF_PROTO_FR_DEL_ETH_PVC 0x2009 /* Delete FR Ethernet-bridged PVC */ #define IF_PROTO_FR_PVC 0x200A /* for reading PVC status */ #define IF_PROTO_FR_ETH_PVC 0x200B #define IF_PROTO_RAW 0x200C /* RAW Socket */ /* RFC 2863 operational status */ enum { IF_OPER_UNKNOWN, IF_OPER_NOTPRESENT, IF_OPER_DOWN, IF_OPER_LOWERLAYERDOWN, IF_OPER_TESTING, IF_OPER_DORMANT, IF_OPER_UP, }; /* link modes */ enum { IF_LINK_MODE_DEFAULT, IF_LINK_MODE_DORMANT, /* limit upward transition to dormant */ IF_LINK_MODE_TESTING, /* limit upward transition to testing */ }; /* * Device mapping structure. I'd just gone off and designed a * beautiful scheme using only loadable modules with arguments * for driver options and along come the PCMCIA people 8) * * Ah well. The get() side of this is good for WDSETUP, and it'll * be handy for debugging things. The set side is fine for now and * being very small might be worth keeping for clean configuration. */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_IFMAP struct ifmap { unsigned long mem_start; unsigned long mem_end; unsigned short base_addr; unsigned char irq; unsigned char dma; unsigned char port; /* 3 bytes spare */ }; #endif /* __UAPI_DEF_IF_IFMAP */ struct if_settings { unsigned int type; /* Type of physical device or protocol */ unsigned int size; /* Size of the data allocated by the caller */ union { /* {atm/eth/dsl}_settings anyone ? */ raw_hdlc_proto *raw_hdlc; cisco_proto *cisco; fr_proto *fr; fr_proto_pvc *fr_pvc; fr_proto_pvc_info *fr_pvc_info; /* interface settings */ sync_serial_settings *sync; te1_settings *te1; } ifs_ifsu; }; /* * Interface request structure used for socket * ioctl's. All interface ioctl's must have parameter * definitions which begin with ifr_name. The * remainder may be interface specific. */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_IFREQ struct ifreq { #define IFHWADDRLEN 6 union { char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */ } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; int ifru_ivalue; int ifru_mtu; struct ifmap ifru_map; char ifru_slave[IFNAMSIZ]; /* Just fits the size */ char ifru_newname[IFNAMSIZ]; void * ifru_data; struct if_settings ifru_settings; } ifr_ifru; }; #endif /* __UAPI_DEF_IF_IFREQ */ #define ifr_name ifr_ifrn.ifrn_name /* interface name */ #define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */ #define ifr_addr ifr_ifru.ifru_addr /* address */ #define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-p lnk */ #define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */ #define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */ #define ifr_flags ifr_ifru.ifru_flags /* flags */ #define ifr_metric ifr_ifru.ifru_ivalue /* metric */ #define ifr_mtu ifr_ifru.ifru_mtu /* mtu */ #define ifr_map ifr_ifru.ifru_map /* device map */ #define ifr_slave ifr_ifru.ifru_slave /* slave device */ #define ifr_data ifr_ifru.ifru_data /* for use by interface */ #define ifr_ifindex ifr_ifru.ifru_ivalue /* interface index */ #define ifr_bandwidth ifr_ifru.ifru_ivalue /* link bandwidth */ #define ifr_qlen ifr_ifru.ifru_ivalue /* Queue length */ #define ifr_newname ifr_ifru.ifru_newname /* New name */ #define ifr_settings ifr_ifru.ifru_settings /* Device/proto settings*/ /* * Structure used in SIOCGIFCONF request. * Used to retrieve interface configuration * for machine (useful for programs which * must know all networks accessible). */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_IFCONF struct ifconf { int ifc_len; /* size of buffer */ union { char *ifcu_buf; struct ifreq *ifcu_req; } ifc_ifcu; }; #endif /* __UAPI_DEF_IF_IFCONF */ #define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */ #define ifc_req ifc_ifcu.ifcu_req /* array of structures */ #endif /* _LINUX_IF_H */ linux/perf_event.h000064400000117204151027430560010221 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Performance events: * * Copyright (C) 2008-2009, Thomas Gleixner * Copyright (C) 2008-2011, Red Hat, Inc., Ingo Molnar * Copyright (C) 2008-2011, Red Hat, Inc., Peter Zijlstra * * Data type definitions, declarations, prototypes. * * Started by: Thomas Gleixner and Ingo Molnar * * For licencing details see kernel-base/COPYING */ #ifndef _LINUX_PERF_EVENT_H #define _LINUX_PERF_EVENT_H #include #include #include /* * User-space ABI bits: */ /* * attr.type */ enum perf_type_id { PERF_TYPE_HARDWARE = 0, PERF_TYPE_SOFTWARE = 1, PERF_TYPE_TRACEPOINT = 2, PERF_TYPE_HW_CACHE = 3, PERF_TYPE_RAW = 4, PERF_TYPE_BREAKPOINT = 5, PERF_TYPE_MAX, /* non-ABI */ }; /* * attr.config layout for type PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE * PERF_TYPE_HARDWARE: 0xEEEEEEEE000000AA * AA: hardware event ID * EEEEEEEE: PMU type ID * PERF_TYPE_HW_CACHE: 0xEEEEEEEE00DDCCBB * BB: hardware cache ID * CC: hardware cache op ID * DD: hardware cache op result ID * EEEEEEEE: PMU type ID * If the PMU type ID is 0, the PERF_TYPE_RAW will be applied. */ #define PERF_PMU_TYPE_SHIFT 32 #define PERF_HW_EVENT_MASK 0xffffffff /* * Generalized performance event event_id types, used by the * attr.event_id parameter of the sys_perf_event_open() * syscall: */ enum perf_hw_id { /* * Common hardware events, generalized by the kernel: */ PERF_COUNT_HW_CPU_CYCLES = 0, PERF_COUNT_HW_INSTRUCTIONS = 1, PERF_COUNT_HW_CACHE_REFERENCES = 2, PERF_COUNT_HW_CACHE_MISSES = 3, PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4, PERF_COUNT_HW_BRANCH_MISSES = 5, PERF_COUNT_HW_BUS_CYCLES = 6, PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7, PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8, PERF_COUNT_HW_REF_CPU_CYCLES = 9, PERF_COUNT_HW_MAX, /* non-ABI */ }; /* * Generalized hardware cache events: * * { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x * { read, write, prefetch } x * { accesses, misses } */ enum perf_hw_cache_id { PERF_COUNT_HW_CACHE_L1D = 0, PERF_COUNT_HW_CACHE_L1I = 1, PERF_COUNT_HW_CACHE_LL = 2, PERF_COUNT_HW_CACHE_DTLB = 3, PERF_COUNT_HW_CACHE_ITLB = 4, PERF_COUNT_HW_CACHE_BPU = 5, PERF_COUNT_HW_CACHE_NODE = 6, PERF_COUNT_HW_CACHE_MAX, /* non-ABI */ }; enum perf_hw_cache_op_id { PERF_COUNT_HW_CACHE_OP_READ = 0, PERF_COUNT_HW_CACHE_OP_WRITE = 1, PERF_COUNT_HW_CACHE_OP_PREFETCH = 2, PERF_COUNT_HW_CACHE_OP_MAX, /* non-ABI */ }; enum perf_hw_cache_op_result_id { PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0, PERF_COUNT_HW_CACHE_RESULT_MISS = 1, PERF_COUNT_HW_CACHE_RESULT_MAX, /* non-ABI */ }; /* * Special "software" events provided by the kernel, even if the hardware * does not support performance events. These events measure various * physical and sw events of the kernel (and allow the profiling of them as * well): */ enum perf_sw_ids { PERF_COUNT_SW_CPU_CLOCK = 0, PERF_COUNT_SW_TASK_CLOCK = 1, PERF_COUNT_SW_PAGE_FAULTS = 2, PERF_COUNT_SW_CONTEXT_SWITCHES = 3, PERF_COUNT_SW_CPU_MIGRATIONS = 4, PERF_COUNT_SW_PAGE_FAULTS_MIN = 5, PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6, PERF_COUNT_SW_ALIGNMENT_FAULTS = 7, PERF_COUNT_SW_EMULATION_FAULTS = 8, PERF_COUNT_SW_DUMMY = 9, PERF_COUNT_SW_BPF_OUTPUT = 10, PERF_COUNT_SW_CGROUP_SWITCHES = 11, PERF_COUNT_SW_MAX, /* non-ABI */ }; /* * Bits that can be set in attr.sample_type to request information * in the overflow packets. */ enum perf_event_sample_format { PERF_SAMPLE_IP = 1U << 0, PERF_SAMPLE_TID = 1U << 1, PERF_SAMPLE_TIME = 1U << 2, PERF_SAMPLE_ADDR = 1U << 3, PERF_SAMPLE_READ = 1U << 4, PERF_SAMPLE_CALLCHAIN = 1U << 5, PERF_SAMPLE_ID = 1U << 6, PERF_SAMPLE_CPU = 1U << 7, PERF_SAMPLE_PERIOD = 1U << 8, PERF_SAMPLE_STREAM_ID = 1U << 9, PERF_SAMPLE_RAW = 1U << 10, PERF_SAMPLE_BRANCH_STACK = 1U << 11, PERF_SAMPLE_REGS_USER = 1U << 12, PERF_SAMPLE_STACK_USER = 1U << 13, PERF_SAMPLE_WEIGHT = 1U << 14, PERF_SAMPLE_DATA_SRC = 1U << 15, PERF_SAMPLE_IDENTIFIER = 1U << 16, PERF_SAMPLE_TRANSACTION = 1U << 17, PERF_SAMPLE_REGS_INTR = 1U << 18, PERF_SAMPLE_PHYS_ADDR = 1U << 19, PERF_SAMPLE_AUX = 1U << 20, PERF_SAMPLE_CGROUP = 1U << 21, #ifndef __GENKSYMS__ PERF_SAMPLE_DATA_PAGE_SIZE = 1U << 22, PERF_SAMPLE_CODE_PAGE_SIZE = 1U << 23, PERF_SAMPLE_WEIGHT_STRUCT = 1U << 24, PERF_SAMPLE_MAX = 1U << 25, /* non-ABI */ #else PERF_SAMPLE_MAX = 1U << 22, /* non-ABI */ #endif /* __GENKSYMS__ */ __PERF_SAMPLE_CALLCHAIN_EARLY = 1ULL << 63, /* non-ABI; internal use */ }; #define PERF_SAMPLE_WEIGHT_TYPE (PERF_SAMPLE_WEIGHT | PERF_SAMPLE_WEIGHT_STRUCT) /* * values to program into branch_sample_type when PERF_SAMPLE_BRANCH is set * * If the user does not pass priv level information via branch_sample_type, * the kernel uses the event's priv level. Branch and event priv levels do * not have to match. Branch priv level is checked for permissions. * * The branch types can be combined, however BRANCH_ANY covers all types * of branches and therefore it supersedes all the other types. */ enum perf_branch_sample_type_shift { PERF_SAMPLE_BRANCH_USER_SHIFT = 0, /* user branches */ PERF_SAMPLE_BRANCH_KERNEL_SHIFT = 1, /* kernel branches */ PERF_SAMPLE_BRANCH_HV_SHIFT = 2, /* hypervisor branches */ PERF_SAMPLE_BRANCH_ANY_SHIFT = 3, /* any branch types */ PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT = 4, /* any call branch */ PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT = 5, /* any return branch */ PERF_SAMPLE_BRANCH_IND_CALL_SHIFT = 6, /* indirect calls */ PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT = 7, /* transaction aborts */ PERF_SAMPLE_BRANCH_IN_TX_SHIFT = 8, /* in transaction */ PERF_SAMPLE_BRANCH_NO_TX_SHIFT = 9, /* not in transaction */ PERF_SAMPLE_BRANCH_COND_SHIFT = 10, /* conditional branches */ PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT = 11, /* call/ret stack */ PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT = 12, /* indirect jumps */ PERF_SAMPLE_BRANCH_CALL_SHIFT = 13, /* direct call */ PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT = 14, /* no flags */ PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT = 15, /* no cycles */ PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT = 16, /* save branch type */ PERF_SAMPLE_BRANCH_HW_INDEX_SHIFT = 17, /* save low level index of raw branch records */ PERF_SAMPLE_BRANCH_MAX_SHIFT /* non-ABI */ }; enum perf_branch_sample_type { PERF_SAMPLE_BRANCH_USER = 1U << PERF_SAMPLE_BRANCH_USER_SHIFT, PERF_SAMPLE_BRANCH_KERNEL = 1U << PERF_SAMPLE_BRANCH_KERNEL_SHIFT, PERF_SAMPLE_BRANCH_HV = 1U << PERF_SAMPLE_BRANCH_HV_SHIFT, PERF_SAMPLE_BRANCH_ANY = 1U << PERF_SAMPLE_BRANCH_ANY_SHIFT, PERF_SAMPLE_BRANCH_ANY_CALL = 1U << PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT, PERF_SAMPLE_BRANCH_ANY_RETURN = 1U << PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT, PERF_SAMPLE_BRANCH_IND_CALL = 1U << PERF_SAMPLE_BRANCH_IND_CALL_SHIFT, PERF_SAMPLE_BRANCH_ABORT_TX = 1U << PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT, PERF_SAMPLE_BRANCH_IN_TX = 1U << PERF_SAMPLE_BRANCH_IN_TX_SHIFT, PERF_SAMPLE_BRANCH_NO_TX = 1U << PERF_SAMPLE_BRANCH_NO_TX_SHIFT, PERF_SAMPLE_BRANCH_COND = 1U << PERF_SAMPLE_BRANCH_COND_SHIFT, PERF_SAMPLE_BRANCH_CALL_STACK = 1U << PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT, PERF_SAMPLE_BRANCH_IND_JUMP = 1U << PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT, PERF_SAMPLE_BRANCH_CALL = 1U << PERF_SAMPLE_BRANCH_CALL_SHIFT, PERF_SAMPLE_BRANCH_NO_FLAGS = 1U << PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT, PERF_SAMPLE_BRANCH_NO_CYCLES = 1U << PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT, PERF_SAMPLE_BRANCH_TYPE_SAVE = 1U << PERF_SAMPLE_BRANCH_TYPE_SAVE_SHIFT, PERF_SAMPLE_BRANCH_HW_INDEX = 1U << PERF_SAMPLE_BRANCH_HW_INDEX_SHIFT, PERF_SAMPLE_BRANCH_MAX = 1U << PERF_SAMPLE_BRANCH_MAX_SHIFT, }; /* * Common flow change classification */ enum { PERF_BR_UNKNOWN = 0, /* unknown */ PERF_BR_COND = 1, /* conditional */ PERF_BR_UNCOND = 2, /* unconditional */ PERF_BR_IND = 3, /* indirect */ PERF_BR_CALL = 4, /* function call */ PERF_BR_IND_CALL = 5, /* indirect function call */ PERF_BR_RET = 6, /* function return */ PERF_BR_SYSCALL = 7, /* syscall */ PERF_BR_SYSRET = 8, /* syscall return */ PERF_BR_COND_CALL = 9, /* conditional function call */ PERF_BR_COND_RET = 10, /* conditional function return */ PERF_BR_ERET = 11, /* exception return */ PERF_BR_IRQ = 12, /* irq */ PERF_BR_MAX, }; /* * Common branch speculation outcome classification */ enum { PERF_BR_SPEC_NA = 0, /* Not available */ PERF_BR_SPEC_WRONG_PATH = 1, /* Speculative but on wrong path */ PERF_BR_NON_SPEC_CORRECT_PATH = 2, /* Non-speculative but on correct path */ PERF_BR_SPEC_CORRECT_PATH = 3, /* Speculative and on correct path */ PERF_BR_SPEC_MAX, }; #define PERF_SAMPLE_BRANCH_PLM_ALL \ (PERF_SAMPLE_BRANCH_USER|\ PERF_SAMPLE_BRANCH_KERNEL|\ PERF_SAMPLE_BRANCH_HV) /* * Values to determine ABI of the registers dump. */ enum perf_sample_regs_abi { PERF_SAMPLE_REGS_ABI_NONE = 0, PERF_SAMPLE_REGS_ABI_32 = 1, PERF_SAMPLE_REGS_ABI_64 = 2, }; /* * Values for the memory transaction event qualifier, mostly for * abort events. Multiple bits can be set. */ enum { PERF_TXN_ELISION = (1 << 0), /* From elision */ PERF_TXN_TRANSACTION = (1 << 1), /* From transaction */ PERF_TXN_SYNC = (1 << 2), /* Instruction is related */ PERF_TXN_ASYNC = (1 << 3), /* Instruction not related */ PERF_TXN_RETRY = (1 << 4), /* Retry possible */ PERF_TXN_CONFLICT = (1 << 5), /* Conflict abort */ PERF_TXN_CAPACITY_WRITE = (1 << 6), /* Capacity write abort */ PERF_TXN_CAPACITY_READ = (1 << 7), /* Capacity read abort */ PERF_TXN_MAX = (1 << 8), /* non-ABI */ /* bits 32..63 are reserved for the abort code */ PERF_TXN_ABORT_MASK = (0xffffffffULL << 32), PERF_TXN_ABORT_SHIFT = 32, }; /* * The format of the data returned by read() on a perf event fd, * as specified by attr.read_format: * * struct read_format { * { u64 value; * { u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED * { u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING * { u64 id; } && PERF_FORMAT_ID * } && !PERF_FORMAT_GROUP * * { u64 nr; * { u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED * { u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING * { u64 value; * { u64 id; } && PERF_FORMAT_ID * } cntr[nr]; * } && PERF_FORMAT_GROUP * }; */ enum perf_event_read_format { PERF_FORMAT_TOTAL_TIME_ENABLED = 1U << 0, PERF_FORMAT_TOTAL_TIME_RUNNING = 1U << 1, PERF_FORMAT_ID = 1U << 2, PERF_FORMAT_GROUP = 1U << 3, PERF_FORMAT_MAX = 1U << 4, /* non-ABI */ }; #define PERF_ATTR_SIZE_VER0 64 /* sizeof first published struct */ #define PERF_ATTR_SIZE_VER1 72 /* add: config2 */ #define PERF_ATTR_SIZE_VER2 80 /* add: branch_sample_type */ #define PERF_ATTR_SIZE_VER3 96 /* add: sample_regs_user */ /* add: sample_stack_user */ #define PERF_ATTR_SIZE_VER4 104 /* add: sample_regs_intr */ #define PERF_ATTR_SIZE_VER5 112 /* add: aux_watermark */ #define PERF_ATTR_SIZE_VER6 120 /* add: aux_sample_size */ /* * Hardware event_id to monitor via a performance monitoring event: * * @sample_max_stack: Max number of frame pointers in a callchain, * should be < /proc/sys/kernel/perf_event_max_stack */ struct perf_event_attr { /* * Major type: hardware/software/tracepoint/etc. */ __u32 type; /* * Size of the attr structure, for fwd/bwd compat. */ __u32 size; /* * Type specific configuration information. */ __u64 config; union { __u64 sample_period; __u64 sample_freq; }; __u64 sample_type; __u64 read_format; __u64 disabled : 1, /* off by default */ inherit : 1, /* children inherit it */ pinned : 1, /* must always be on PMU */ exclusive : 1, /* only group on PMU */ exclude_user : 1, /* don't count user */ exclude_kernel : 1, /* ditto kernel */ exclude_hv : 1, /* ditto hypervisor */ exclude_idle : 1, /* don't count when idle */ mmap : 1, /* include mmap data */ comm : 1, /* include comm data */ freq : 1, /* use freq, not period */ inherit_stat : 1, /* per task counts */ enable_on_exec : 1, /* next exec enables */ task : 1, /* trace fork/exit */ watermark : 1, /* wakeup_watermark */ /* * precise_ip: * * 0 - SAMPLE_IP can have arbitrary skid * 1 - SAMPLE_IP must have constant skid * 2 - SAMPLE_IP requested to have 0 skid * 3 - SAMPLE_IP must have 0 skid * * See also PERF_RECORD_MISC_EXACT_IP */ precise_ip : 2, /* skid constraint */ mmap_data : 1, /* non-exec mmap data */ sample_id_all : 1, /* sample_type all events */ exclude_host : 1, /* don't count in host */ exclude_guest : 1, /* don't count in guest */ exclude_callchain_kernel : 1, /* exclude kernel callchains */ exclude_callchain_user : 1, /* exclude user callchains */ mmap2 : 1, /* include mmap with inode data */ comm_exec : 1, /* flag comm events that are due to an exec */ use_clockid : 1, /* use @clockid for time fields */ context_switch : 1, /* context switch data */ write_backward : 1, /* Write ring buffer from end to beginning */ namespaces : 1, /* include namespaces data */ #ifndef __GENKSYMS__ ksymbol : 1, /* include ksymbol events */ bpf_event : 1, /* include bpf events */ aux_output : 1, /* generate AUX records instead of events */ cgroup : 1, /* include cgroup events */ text_poke : 1, /* include text poke events */ build_id : 1, /* use build id in mmap2 events */ inherit_thread : 1, /* children only inherit if cloned with CLONE_THREAD */ remove_on_exec : 1, /* event is removed from task on exec */ __reserved_1 : 27; #else __reserved_1 : 35; #endif /* __GENKSYMS__ */ union { __u32 wakeup_events; /* wakeup every n events */ __u32 wakeup_watermark; /* bytes before wakeup */ }; __u32 bp_type; union { __u64 bp_addr; __u64 kprobe_func; /* for perf_kprobe */ __u64 uprobe_path; /* for perf_uprobe */ __u64 config1; /* extension of config */ }; union { __u64 bp_len; __u64 kprobe_addr; /* when kprobe_func == NULL */ __u64 probe_offset; /* for perf_[k,u]probe */ __u64 config2; /* extension of config1 */ }; __u64 branch_sample_type; /* enum perf_branch_sample_type */ /* * Defines set of user regs to dump on samples. * See asm/perf_regs.h for details. */ __u64 sample_regs_user; /* * Defines size of the user stack to dump on samples. */ __u32 sample_stack_user; __s32 clockid; /* * Defines set of regs to dump for each sample * state captured on: * - precise = 0: PMU interrupt * - precise > 0: sampled instruction * * See asm/perf_regs.h for details. */ __u64 sample_regs_intr; /* * Wakeup watermark for AUX area */ __u32 aux_watermark; __u16 sample_max_stack; __u16 __reserved_2; #ifndef __GENKSYMS__ __u32 aux_sample_size; __u32 __reserved_3; #endif /* __GENKSYMS__ */ }; /* * Structure used by below PERF_EVENT_IOC_QUERY_BPF command * to query bpf programs attached to the same perf tracepoint * as the given perf event. */ struct perf_event_query_bpf { /* * The below ids array length */ __u32 ids_len; /* * Set by the kernel to indicate the number of * available programs */ __u32 prog_cnt; /* * User provided buffer to store program ids */ __u32 ids[0]; }; /* * Ioctls that can be done on a perf event fd: */ #define PERF_EVENT_IOC_ENABLE _IO ('$', 0) #define PERF_EVENT_IOC_DISABLE _IO ('$', 1) #define PERF_EVENT_IOC_REFRESH _IO ('$', 2) #define PERF_EVENT_IOC_RESET _IO ('$', 3) #define PERF_EVENT_IOC_PERIOD _IOW('$', 4, __u64) #define PERF_EVENT_IOC_SET_OUTPUT _IO ('$', 5) #define PERF_EVENT_IOC_SET_FILTER _IOW('$', 6, char *) #define PERF_EVENT_IOC_ID _IOR('$', 7, __u64 *) #define PERF_EVENT_IOC_SET_BPF _IOW('$', 8, __u32) #define PERF_EVENT_IOC_PAUSE_OUTPUT _IOW('$', 9, __u32) #define PERF_EVENT_IOC_QUERY_BPF _IOWR('$', 10, struct perf_event_query_bpf *) #define PERF_EVENT_IOC_MODIFY_ATTRIBUTES _IOW('$', 11, struct perf_event_attr *) enum perf_event_ioc_flags { PERF_IOC_FLAG_GROUP = 1U << 0, }; /* * Structure of the page that can be mapped via mmap */ struct perf_event_mmap_page { __u32 version; /* version number of this structure */ __u32 compat_version; /* lowest version this is compat with */ /* * Bits needed to read the hw events in user-space. * * u32 seq, time_mult, time_shift, index, width; * u64 count, enabled, running; * u64 cyc, time_offset; * s64 pmc = 0; * * do { * seq = pc->lock; * barrier() * * enabled = pc->time_enabled; * running = pc->time_running; * * if (pc->cap_usr_time && enabled != running) { * cyc = rdtsc(); * time_offset = pc->time_offset; * time_mult = pc->time_mult; * time_shift = pc->time_shift; * } * * index = pc->index; * count = pc->offset; * if (pc->cap_user_rdpmc && index) { * width = pc->pmc_width; * pmc = rdpmc(index - 1); * } * * barrier(); * } while (pc->lock != seq); * * NOTE: for obvious reason this only works on self-monitoring * processes. */ __u32 lock; /* seqlock for synchronization */ __u32 index; /* hardware event identifier */ __s64 offset; /* add to hardware event value */ __u64 time_enabled; /* time event active */ __u64 time_running; /* time event on cpu */ union { __u64 capabilities; struct { __u64 cap_bit0 : 1, /* Always 0, deprecated, see commit 860f085b74e9 */ cap_bit0_is_deprecated : 1, /* Always 1, signals that bit 0 is zero */ cap_user_rdpmc : 1, /* The RDPMC instruction can be used to read counts */ cap_user_time : 1, /* The time_{shift,mult,offset} fields are used */ cap_user_time_zero : 1, /* The time_zero field is used */ cap_user_time_short : 1, /* the time_{cycle,mask} fields are used */ cap_____res : 58; }; }; /* * If cap_user_rdpmc this field provides the bit-width of the value * read using the rdpmc() or equivalent instruction. This can be used * to sign extend the result like: * * pmc <<= 64 - width; * pmc >>= 64 - width; // signed shift right * count += pmc; */ __u16 pmc_width; /* * If cap_usr_time the below fields can be used to compute the time * delta since time_enabled (in ns) using rdtsc or similar. * * u64 quot, rem; * u64 delta; * * quot = (cyc >> time_shift); * rem = cyc & (((u64)1 << time_shift) - 1); * delta = time_offset + quot * time_mult + * ((rem * time_mult) >> time_shift); * * Where time_offset,time_mult,time_shift and cyc are read in the * seqcount loop described above. This delta can then be added to * enabled and possible running (if index), improving the scaling: * * enabled += delta; * if (index) * running += delta; * * quot = count / running; * rem = count % running; * count = quot * enabled + (rem * enabled) / running; */ __u16 time_shift; __u32 time_mult; __u64 time_offset; /* * If cap_usr_time_zero, the hardware clock (e.g. TSC) can be calculated * from sample timestamps. * * time = timestamp - time_zero; * quot = time / time_mult; * rem = time % time_mult; * cyc = (quot << time_shift) + (rem << time_shift) / time_mult; * * And vice versa: * * quot = cyc >> time_shift; * rem = cyc & (((u64)1 << time_shift) - 1); * timestamp = time_zero + quot * time_mult + * ((rem * time_mult) >> time_shift); */ __u64 time_zero; __u32 size; /* Header size up to __reserved[] fields. */ __u32 __reserved_1; /* * If cap_usr_time_short, the hardware clock is less than 64bit wide * and we must compute the 'cyc' value, as used by cap_usr_time, as: * * cyc = time_cycles + ((cyc - time_cycles) & time_mask) * * NOTE: this form is explicitly chosen such that cap_usr_time_short * is a correction on top of cap_usr_time, and code that doesn't * know about cap_usr_time_short still works under the assumption * the counter doesn't wrap. */ __u64 time_cycles; __u64 time_mask; /* * Hole for extension of the self monitor capabilities */ __u8 __reserved[116*8]; /* align to 1k. */ /* * Control data for the mmap() data buffer. * * User-space reading the @data_head value should issue an smp_rmb(), * after reading this value. * * When the mapping is PROT_WRITE the @data_tail value should be * written by userspace to reflect the last read data, after issueing * an smp_mb() to separate the data read from the ->data_tail store. * In this case the kernel will not over-write unread data. * * See perf_output_put_handle() for the data ordering. * * data_{offset,size} indicate the location and size of the perf record * buffer within the mmapped area. */ __u64 data_head; /* head in the data section */ __u64 data_tail; /* user-space written tail */ __u64 data_offset; /* where the buffer starts */ __u64 data_size; /* data buffer size */ /* * AUX area is defined by aux_{offset,size} fields that should be set * by the userspace, so that * * aux_offset >= data_offset + data_size * * prior to mmap()ing it. Size of the mmap()ed area should be aux_size. * * Ring buffer pointers aux_{head,tail} have the same semantics as * data_{head,tail} and same ordering rules apply. */ __u64 aux_head; __u64 aux_tail; __u64 aux_offset; __u64 aux_size; }; /* * The current state of perf_event_header::misc bits usage: * ('|' used bit, '-' unused bit) * * 012 CDEF * |||---------|||| * * Where: * 0-2 CPUMODE_MASK * * C PROC_MAP_PARSE_TIMEOUT * D MMAP_DATA / COMM_EXEC / FORK_EXEC / SWITCH_OUT * E MMAP_BUILD_ID / EXACT_IP / SCHED_OUT_PREEMPT * F (reserved) */ #define PERF_RECORD_MISC_CPUMODE_MASK (7 << 0) #define PERF_RECORD_MISC_CPUMODE_UNKNOWN (0 << 0) #define PERF_RECORD_MISC_KERNEL (1 << 0) #define PERF_RECORD_MISC_USER (2 << 0) #define PERF_RECORD_MISC_HYPERVISOR (3 << 0) #define PERF_RECORD_MISC_GUEST_KERNEL (4 << 0) #define PERF_RECORD_MISC_GUEST_USER (5 << 0) /* * Indicates that /proc/PID/maps parsing are truncated by time out. */ #define PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT (1 << 12) /* * Following PERF_RECORD_MISC_* are used on different * events, so can reuse the same bit position: * * PERF_RECORD_MISC_MMAP_DATA - PERF_RECORD_MMAP* events * PERF_RECORD_MISC_COMM_EXEC - PERF_RECORD_COMM event * PERF_RECORD_MISC_FORK_EXEC - PERF_RECORD_FORK event (perf internal) * PERF_RECORD_MISC_SWITCH_OUT - PERF_RECORD_SWITCH* events */ #define PERF_RECORD_MISC_MMAP_DATA (1 << 13) #define PERF_RECORD_MISC_COMM_EXEC (1 << 13) #define PERF_RECORD_MISC_FORK_EXEC (1 << 13) #define PERF_RECORD_MISC_SWITCH_OUT (1 << 13) /* * These PERF_RECORD_MISC_* flags below are safely reused * for the following events: * * PERF_RECORD_MISC_EXACT_IP - PERF_RECORD_SAMPLE of precise events * PERF_RECORD_MISC_SWITCH_OUT_PREEMPT - PERF_RECORD_SWITCH* events * PERF_RECORD_MISC_MMAP_BUILD_ID - PERF_RECORD_MMAP2 event * * * PERF_RECORD_MISC_EXACT_IP: * Indicates that the content of PERF_SAMPLE_IP points to * the actual instruction that triggered the event. See also * perf_event_attr::precise_ip. * * PERF_RECORD_MISC_SWITCH_OUT_PREEMPT: * Indicates that thread was preempted in TASK_RUNNING state. * * PERF_RECORD_MISC_MMAP_BUILD_ID: * Indicates that mmap2 event carries build id data. */ #define PERF_RECORD_MISC_EXACT_IP (1 << 14) #define PERF_RECORD_MISC_SWITCH_OUT_PREEMPT (1 << 14) #define PERF_RECORD_MISC_MMAP_BUILD_ID (1 << 14) /* * Reserve the last bit to indicate some extended misc field */ #define PERF_RECORD_MISC_EXT_RESERVED (1 << 15) struct perf_event_header { __u32 type; __u16 misc; __u16 size; }; struct perf_ns_link_info { __u64 dev; __u64 ino; }; enum { NET_NS_INDEX = 0, UTS_NS_INDEX = 1, IPC_NS_INDEX = 2, PID_NS_INDEX = 3, USER_NS_INDEX = 4, MNT_NS_INDEX = 5, CGROUP_NS_INDEX = 6, NR_NAMESPACES, /* number of available namespaces */ }; enum perf_event_type { /* * If perf_event_attr.sample_id_all is set then all event types will * have the sample_type selected fields related to where/when * (identity) an event took place (TID, TIME, ID, STREAM_ID, CPU, * IDENTIFIER) described in PERF_RECORD_SAMPLE below, it will be stashed * just after the perf_event_header and the fields already present for * the existing fields, i.e. at the end of the payload. That way a newer * perf.data file will be supported by older perf tools, with these new * optional fields being ignored. * * struct sample_id { * { u32 pid, tid; } && PERF_SAMPLE_TID * { u64 time; } && PERF_SAMPLE_TIME * { u64 id; } && PERF_SAMPLE_ID * { u64 stream_id;} && PERF_SAMPLE_STREAM_ID * { u32 cpu, res; } && PERF_SAMPLE_CPU * { u64 id; } && PERF_SAMPLE_IDENTIFIER * } && perf_event_attr::sample_id_all * * Note that PERF_SAMPLE_IDENTIFIER duplicates PERF_SAMPLE_ID. The * advantage of PERF_SAMPLE_IDENTIFIER is that its position is fixed * relative to header.size. */ /* * The MMAP events record the PROT_EXEC mappings so that we can * correlate userspace IPs to code. They have the following structure: * * struct { * struct perf_event_header header; * * u32 pid, tid; * u64 addr; * u64 len; * u64 pgoff; * char filename[]; * struct sample_id sample_id; * }; */ PERF_RECORD_MMAP = 1, /* * struct { * struct perf_event_header header; * u64 id; * u64 lost; * struct sample_id sample_id; * }; */ PERF_RECORD_LOST = 2, /* * struct { * struct perf_event_header header; * * u32 pid, tid; * char comm[]; * struct sample_id sample_id; * }; */ PERF_RECORD_COMM = 3, /* * struct { * struct perf_event_header header; * u32 pid, ppid; * u32 tid, ptid; * u64 time; * struct sample_id sample_id; * }; */ PERF_RECORD_EXIT = 4, /* * struct { * struct perf_event_header header; * u64 time; * u64 id; * u64 stream_id; * struct sample_id sample_id; * }; */ PERF_RECORD_THROTTLE = 5, PERF_RECORD_UNTHROTTLE = 6, /* * struct { * struct perf_event_header header; * u32 pid, ppid; * u32 tid, ptid; * u64 time; * struct sample_id sample_id; * }; */ PERF_RECORD_FORK = 7, /* * struct { * struct perf_event_header header; * u32 pid, tid; * * struct read_format values; * struct sample_id sample_id; * }; */ PERF_RECORD_READ = 8, /* * struct { * struct perf_event_header header; * * # * # Note that PERF_SAMPLE_IDENTIFIER duplicates PERF_SAMPLE_ID. * # The advantage of PERF_SAMPLE_IDENTIFIER is that its position * # is fixed relative to header. * # * * { u64 id; } && PERF_SAMPLE_IDENTIFIER * { u64 ip; } && PERF_SAMPLE_IP * { u32 pid, tid; } && PERF_SAMPLE_TID * { u64 time; } && PERF_SAMPLE_TIME * { u64 addr; } && PERF_SAMPLE_ADDR * { u64 id; } && PERF_SAMPLE_ID * { u64 stream_id;} && PERF_SAMPLE_STREAM_ID * { u32 cpu, res; } && PERF_SAMPLE_CPU * { u64 period; } && PERF_SAMPLE_PERIOD * * { struct read_format values; } && PERF_SAMPLE_READ * * { u64 nr, * u64 ips[nr]; } && PERF_SAMPLE_CALLCHAIN * * # * # The RAW record below is opaque data wrt the ABI * # * # That is, the ABI doesn't make any promises wrt to * # the stability of its content, it may vary depending * # on event, hardware, kernel version and phase of * # the moon. * # * # In other words, PERF_SAMPLE_RAW contents are not an ABI. * # * * { u32 size; * char data[size];}&& PERF_SAMPLE_RAW * * { u64 nr; * { u64 hw_idx; } && PERF_SAMPLE_BRANCH_HW_INDEX * { u64 from, to, flags } lbr[nr]; * } && PERF_SAMPLE_BRANCH_STACK * * { u64 abi; # enum perf_sample_regs_abi * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_USER * * { u64 size; * char data[size]; * u64 dyn_size; } && PERF_SAMPLE_STACK_USER * * { union perf_sample_weight * { * u64 full; && PERF_SAMPLE_WEIGHT * #if defined(__LITTLE_ENDIAN_BITFIELD) * struct { * u32 var1_dw; * u16 var2_w; * u16 var3_w; * } && PERF_SAMPLE_WEIGHT_STRUCT * #elif defined(__BIG_ENDIAN_BITFIELD) * struct { * u16 var3_w; * u16 var2_w; * u32 var1_dw; * } && PERF_SAMPLE_WEIGHT_STRUCT * #endif * } * } * { u64 data_src; } && PERF_SAMPLE_DATA_SRC * { u64 transaction; } && PERF_SAMPLE_TRANSACTION * { u64 abi; # enum perf_sample_regs_abi * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_INTR * { u64 phys_addr;} && PERF_SAMPLE_PHYS_ADDR * { u64 size; * char data[size]; } && PERF_SAMPLE_AUX * { u64 data_page_size;} && PERF_SAMPLE_DATA_PAGE_SIZE * { u64 code_page_size;} && PERF_SAMPLE_CODE_PAGE_SIZE * }; */ PERF_RECORD_SAMPLE = 9, /* * The MMAP2 records are an augmented version of MMAP, they add * maj, min, ino numbers to be used to uniquely identify each mapping * * struct { * struct perf_event_header header; * * u32 pid, tid; * u64 addr; * u64 len; * u64 pgoff; * union { * struct { * u32 maj; * u32 min; * u64 ino; * u64 ino_generation; * }; * struct { * u8 build_id_size; * u8 __reserved_1; * u16 __reserved_2; * u8 build_id[20]; * }; * }; * u32 prot, flags; * char filename[]; * struct sample_id sample_id; * }; */ PERF_RECORD_MMAP2 = 10, /* * Records that new data landed in the AUX buffer part. * * struct { * struct perf_event_header header; * * u64 aux_offset; * u64 aux_size; * u64 flags; * struct sample_id sample_id; * }; */ PERF_RECORD_AUX = 11, /* * Indicates that instruction trace has started * * struct { * struct perf_event_header header; * u32 pid; * u32 tid; * struct sample_id sample_id; * }; */ PERF_RECORD_ITRACE_START = 12, /* * Records the dropped/lost sample number. * * struct { * struct perf_event_header header; * * u64 lost; * struct sample_id sample_id; * }; */ PERF_RECORD_LOST_SAMPLES = 13, /* * Records a context switch in or out (flagged by * PERF_RECORD_MISC_SWITCH_OUT). See also * PERF_RECORD_SWITCH_CPU_WIDE. * * struct { * struct perf_event_header header; * struct sample_id sample_id; * }; */ PERF_RECORD_SWITCH = 14, /* * CPU-wide version of PERF_RECORD_SWITCH with next_prev_pid and * next_prev_tid that are the next (switching out) or previous * (switching in) pid/tid. * * struct { * struct perf_event_header header; * u32 next_prev_pid; * u32 next_prev_tid; * struct sample_id sample_id; * }; */ PERF_RECORD_SWITCH_CPU_WIDE = 15, /* * struct { * struct perf_event_header header; * u32 pid; * u32 tid; * u64 nr_namespaces; * { u64 dev, inode; } [nr_namespaces]; * struct sample_id sample_id; * }; */ PERF_RECORD_NAMESPACES = 16, #ifndef __GENKSYMS__ /* * Record ksymbol register/unregister events: * * struct { * struct perf_event_header header; * u64 addr; * u32 len; * u16 ksym_type; * u16 flags; * char name[]; * struct sample_id sample_id; * }; */ PERF_RECORD_KSYMBOL = 17, /* * Record bpf events: * enum perf_bpf_event_type { * PERF_BPF_EVENT_UNKNOWN = 0, * PERF_BPF_EVENT_PROG_LOAD = 1, * PERF_BPF_EVENT_PROG_UNLOAD = 2, * }; * * struct { * struct perf_event_header header; * u16 type; * u16 flags; * u32 id; * u8 tag[BPF_TAG_SIZE]; * struct sample_id sample_id; * }; */ PERF_RECORD_BPF_EVENT = 18, /* * struct { * struct perf_event_header header; * u64 id; * char path[]; * struct sample_id sample_id; * }; */ PERF_RECORD_CGROUP = 19, /* * Records changes to kernel text i.e. self-modified code. 'old_len' is * the number of old bytes, 'new_len' is the number of new bytes. Either * 'old_len' or 'new_len' may be zero to indicate, for example, the * addition or removal of a trampoline. 'bytes' contains the old bytes * followed immediately by the new bytes. * * struct { * struct perf_event_header header; * u64 addr; * u16 old_len; * u16 new_len; * u8 bytes[]; * struct sample_id sample_id; * }; */ PERF_RECORD_TEXT_POKE = 20, #endif /* __GENKSYMS__ */ PERF_RECORD_MAX, /* non-ABI */ }; enum perf_record_ksymbol_type { PERF_RECORD_KSYMBOL_TYPE_UNKNOWN = 0, PERF_RECORD_KSYMBOL_TYPE_BPF = 1, PERF_RECORD_KSYMBOL_TYPE_MAX /* non-ABI */ }; #define PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER (1 << 0) enum perf_bpf_event_type { PERF_BPF_EVENT_UNKNOWN = 0, PERF_BPF_EVENT_PROG_LOAD = 1, PERF_BPF_EVENT_PROG_UNLOAD = 2, PERF_BPF_EVENT_MAX, /* non-ABI */ }; #define PERF_MAX_STACK_DEPTH 127 #define PERF_MAX_CONTEXTS_PER_STACK 8 enum perf_callchain_context { PERF_CONTEXT_HV = (__u64)-32, PERF_CONTEXT_KERNEL = (__u64)-128, PERF_CONTEXT_USER = (__u64)-512, PERF_CONTEXT_GUEST = (__u64)-2048, PERF_CONTEXT_GUEST_KERNEL = (__u64)-2176, PERF_CONTEXT_GUEST_USER = (__u64)-2560, PERF_CONTEXT_MAX = (__u64)-4095, }; /** * PERF_RECORD_AUX::flags bits */ #define PERF_AUX_FLAG_TRUNCATED 0x01 /* record was truncated to fit */ #define PERF_AUX_FLAG_OVERWRITE 0x02 /* snapshot from overwrite mode */ #define PERF_AUX_FLAG_PARTIAL 0x04 /* record contains gaps */ #define PERF_AUX_FLAG_COLLISION 0x08 /* sample collided with another */ #define PERF_FLAG_FD_NO_GROUP (1UL << 0) #define PERF_FLAG_FD_OUTPUT (1UL << 1) #define PERF_FLAG_PID_CGROUP (1UL << 2) /* pid=cgroup id, per-cpu mode only */ #define PERF_FLAG_FD_CLOEXEC (1UL << 3) /* O_CLOEXEC */ #if defined(__LITTLE_ENDIAN_BITFIELD) union perf_mem_data_src { __u64 val; struct { __u64 mem_op:5, /* type of opcode */ mem_lvl:14, /* memory hierarchy level */ mem_snoop:5, /* snoop mode */ mem_lock:2, /* lock instr */ mem_dtlb:7, /* tlb access */ mem_lvl_num:4, /* memory hierarchy level number */ mem_remote:1, /* remote */ mem_snoopx:2, /* snoop mode, ext */ #ifndef __GENKSYMS__ mem_blk:3, /* access blocked */ mem_hops:3, /* hop level */ mem_rsvd:18; #else mem_rsvd:24; #endif /* __GENKSYMS__ */ }; }; #elif defined(__BIG_ENDIAN_BITFIELD) union perf_mem_data_src { __u64 val; struct { #ifndef __GENKSYMS__ __u64 mem_rsvd:18, mem_hops:3, /* hop level */ mem_blk:3, /* access blocked */ #else __u64 mem_rsvd:24, #endif /* __GENKSYMS__ */ mem_snoopx:2, /* snoop mode, ext */ mem_remote:1, /* remote */ mem_lvl_num:4, /* memory hierarchy level number */ mem_dtlb:7, /* tlb access */ mem_lock:2, /* lock instr */ mem_snoop:5, /* snoop mode */ mem_lvl:14, /* memory hierarchy level */ mem_op:5; /* type of opcode */ }; }; #else #error "Unknown endianness" #endif /* type of opcode (load/store/prefetch,code) */ #define PERF_MEM_OP_NA 0x01 /* not available */ #define PERF_MEM_OP_LOAD 0x02 /* load instruction */ #define PERF_MEM_OP_STORE 0x04 /* store instruction */ #define PERF_MEM_OP_PFETCH 0x08 /* prefetch */ #define PERF_MEM_OP_EXEC 0x10 /* code (execution) */ #define PERF_MEM_OP_SHIFT 0 /* * PERF_MEM_LVL_* namespace being depricated to some extent in the * favour of newer composite PERF_MEM_{LVLNUM_,REMOTE_,SNOOPX_} fields. * Supporting this namespace inorder to not break defined ABIs. * * memory hierarchy (memory level, hit or miss) */ #define PERF_MEM_LVL_NA 0x01 /* not available */ #define PERF_MEM_LVL_HIT 0x02 /* hit level */ #define PERF_MEM_LVL_MISS 0x04 /* miss level */ #define PERF_MEM_LVL_L1 0x08 /* L1 */ #define PERF_MEM_LVL_LFB 0x10 /* Line Fill Buffer */ #define PERF_MEM_LVL_L2 0x20 /* L2 */ #define PERF_MEM_LVL_L3 0x40 /* L3 */ #define PERF_MEM_LVL_LOC_RAM 0x80 /* Local DRAM */ #define PERF_MEM_LVL_REM_RAM1 0x100 /* Remote DRAM (1 hop) */ #define PERF_MEM_LVL_REM_RAM2 0x200 /* Remote DRAM (2 hops) */ #define PERF_MEM_LVL_REM_CCE1 0x400 /* Remote Cache (1 hop) */ #define PERF_MEM_LVL_REM_CCE2 0x800 /* Remote Cache (2 hops) */ #define PERF_MEM_LVL_IO 0x1000 /* I/O memory */ #define PERF_MEM_LVL_UNC 0x2000 /* Uncached memory */ #define PERF_MEM_LVL_SHIFT 5 #define PERF_MEM_REMOTE_REMOTE 0x01 /* Remote */ #define PERF_MEM_REMOTE_SHIFT 37 #define PERF_MEM_LVLNUM_L1 0x01 /* L1 */ #define PERF_MEM_LVLNUM_L2 0x02 /* L2 */ #define PERF_MEM_LVLNUM_L3 0x03 /* L3 */ #define PERF_MEM_LVLNUM_L4 0x04 /* L4 */ /* 5-0x8 available */ #define PERF_MEM_LVLNUM_CXL 0x09 /* CXL */ #define PERF_MEM_LVLNUM_IO 0x0a /* I/O */ #define PERF_MEM_LVLNUM_ANY_CACHE 0x0b /* Any cache */ #define PERF_MEM_LVLNUM_LFB 0x0c /* LFB */ #define PERF_MEM_LVLNUM_RAM 0x0d /* RAM */ #define PERF_MEM_LVLNUM_PMEM 0x0e /* PMEM */ #define PERF_MEM_LVLNUM_NA 0x0f /* N/A */ #define PERF_MEM_LVLNUM_SHIFT 33 /* snoop mode */ #define PERF_MEM_SNOOP_NA 0x01 /* not available */ #define PERF_MEM_SNOOP_NONE 0x02 /* no snoop */ #define PERF_MEM_SNOOP_HIT 0x04 /* snoop hit */ #define PERF_MEM_SNOOP_MISS 0x08 /* snoop miss */ #define PERF_MEM_SNOOP_HITM 0x10 /* snoop hit modified */ #define PERF_MEM_SNOOP_SHIFT 19 #define PERF_MEM_SNOOPX_FWD 0x01 /* forward */ #define PERF_MEM_SNOOPX_PEER 0x02 /* xfer from peer */ #define PERF_MEM_SNOOPX_SHIFT 38 /* locked instruction */ #define PERF_MEM_LOCK_NA 0x01 /* not available */ #define PERF_MEM_LOCK_LOCKED 0x02 /* locked transaction */ #define PERF_MEM_LOCK_SHIFT 24 /* TLB access */ #define PERF_MEM_TLB_NA 0x01 /* not available */ #define PERF_MEM_TLB_HIT 0x02 /* hit level */ #define PERF_MEM_TLB_MISS 0x04 /* miss level */ #define PERF_MEM_TLB_L1 0x08 /* L1 */ #define PERF_MEM_TLB_L2 0x10 /* L2 */ #define PERF_MEM_TLB_WK 0x20 /* Hardware Walker*/ #define PERF_MEM_TLB_OS 0x40 /* OS fault handler */ #define PERF_MEM_TLB_SHIFT 26 /* Access blocked */ #define PERF_MEM_BLK_NA 0x01 /* not available */ #define PERF_MEM_BLK_DATA 0x02 /* data could not be forwarded */ #define PERF_MEM_BLK_ADDR 0x04 /* address conflict */ #define PERF_MEM_BLK_SHIFT 40 /* hop level */ #define PERF_MEM_HOPS_0 0x01 /* remote core, same node */ #define PERF_MEM_HOPS_1 0x02 /* remote node, same socket */ #define PERF_MEM_HOPS_2 0x03 /* remote socket, same board */ #define PERF_MEM_HOPS_3 0x04 /* remote board */ /* 5-7 available */ #define PERF_MEM_HOPS_SHIFT 43 #define PERF_MEM_S(a, s) \ (((__u64)PERF_MEM_##a##_##s) << PERF_MEM_##a##_SHIFT) /* * single taken branch record layout: * * from: source instruction (may not always be a branch insn) * to: branch target * mispred: branch target was mispredicted * predicted: branch target was predicted * * support for mispred, predicted is optional. In case it * is not supported mispred = predicted = 0. * * in_tx: running in a hardware transaction * abort: aborting a hardware transaction * cycles: cycles from last branch (or 0 if not supported) * type: branch type * spec: branch speculation info (or 0 if not supported) */ struct perf_branch_entry { __u64 from; __u64 to; __u64 mispred:1, /* target mispredicted */ predicted:1,/* target predicted */ in_tx:1, /* in transaction */ abort:1, /* transaction abort */ cycles:16, /* cycle count to last branch */ type:4, /* branch type */ #ifndef __GENKSYMS__ spec:2, /* branch speculation info */ reserved:38; #else reserved:40; #endif /* __GENKSYMS__ */ }; #ifndef __GENKSYMS__ union perf_sample_weight { __u64 full; #if defined(__LITTLE_ENDIAN_BITFIELD) struct { __u32 var1_dw; __u16 var2_w; __u16 var3_w; }; #elif defined(__BIG_ENDIAN_BITFIELD) struct { __u16 var3_w; __u16 var2_w; __u32 var1_dw; }; #else #error "Unknown endianness" #endif }; #endif /* __GENKSYMS__ */ #endif /* _LINUX_PERF_EVENT_H */ linux/videodev2.h000064400000261165151027430560007761 0ustar00/* SPDX-License-Identifier: ((GPL-2.0+ WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Video for Linux Two header file * * Copyright (C) 1999-2012 the contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Alternatively you can redistribute this file under the terms of the * BSD license as stated below: * * 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 names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Header file for v4l or V4L2 drivers and applications * with public API. * All kernel-specific stuff were moved to media/v4l2-dev.h, so * no #if __KERNEL tests are allowed here * * See https://linuxtv.org for more info * * Author: Bill Dirks * Justin Schoeman * Hans Verkuil * et al. */ #ifndef __LINUX_VIDEODEV2_H #define __LINUX_VIDEODEV2_H #include #include #include #include #include /* * Common stuff for both V4L1 and V4L2 * Moved from videodev.h */ #define VIDEO_MAX_FRAME 32 #define VIDEO_MAX_PLANES 8 /* * M I S C E L L A N E O U S */ /* Four-character-code (FOURCC) */ #define v4l2_fourcc(a, b, c, d)\ ((__u32)(a) | ((__u32)(b) << 8) | ((__u32)(c) << 16) | ((__u32)(d) << 24)) #define v4l2_fourcc_be(a, b, c, d) (v4l2_fourcc(a, b, c, d) | (1U << 31)) /* * E N U M S */ enum v4l2_field { V4L2_FIELD_ANY = 0, /* driver can choose from none, top, bottom, interlaced depending on whatever it thinks is approximate ... */ V4L2_FIELD_NONE = 1, /* this device has no fields ... */ V4L2_FIELD_TOP = 2, /* top field only */ V4L2_FIELD_BOTTOM = 3, /* bottom field only */ V4L2_FIELD_INTERLACED = 4, /* both fields interlaced */ V4L2_FIELD_SEQ_TB = 5, /* both fields sequential into one buffer, top-bottom order */ V4L2_FIELD_SEQ_BT = 6, /* same as above + bottom-top order */ V4L2_FIELD_ALTERNATE = 7, /* both fields alternating into separate buffers */ V4L2_FIELD_INTERLACED_TB = 8, /* both fields interlaced, top field first and the top field is transmitted first */ V4L2_FIELD_INTERLACED_BT = 9, /* both fields interlaced, top field first and the bottom field is transmitted first */ }; #define V4L2_FIELD_HAS_TOP(field) \ ((field) == V4L2_FIELD_TOP ||\ (field) == V4L2_FIELD_INTERLACED ||\ (field) == V4L2_FIELD_INTERLACED_TB ||\ (field) == V4L2_FIELD_INTERLACED_BT ||\ (field) == V4L2_FIELD_SEQ_TB ||\ (field) == V4L2_FIELD_SEQ_BT) #define V4L2_FIELD_HAS_BOTTOM(field) \ ((field) == V4L2_FIELD_BOTTOM ||\ (field) == V4L2_FIELD_INTERLACED ||\ (field) == V4L2_FIELD_INTERLACED_TB ||\ (field) == V4L2_FIELD_INTERLACED_BT ||\ (field) == V4L2_FIELD_SEQ_TB ||\ (field) == V4L2_FIELD_SEQ_BT) #define V4L2_FIELD_HAS_BOTH(field) \ ((field) == V4L2_FIELD_INTERLACED ||\ (field) == V4L2_FIELD_INTERLACED_TB ||\ (field) == V4L2_FIELD_INTERLACED_BT ||\ (field) == V4L2_FIELD_SEQ_TB ||\ (field) == V4L2_FIELD_SEQ_BT) #define V4L2_FIELD_HAS_T_OR_B(field) \ ((field) == V4L2_FIELD_BOTTOM ||\ (field) == V4L2_FIELD_TOP ||\ (field) == V4L2_FIELD_ALTERNATE) #define V4L2_FIELD_IS_INTERLACED(field) \ ((field) == V4L2_FIELD_INTERLACED ||\ (field) == V4L2_FIELD_INTERLACED_TB ||\ (field) == V4L2_FIELD_INTERLACED_BT) #define V4L2_FIELD_IS_SEQUENTIAL(field) \ ((field) == V4L2_FIELD_SEQ_TB ||\ (field) == V4L2_FIELD_SEQ_BT) enum v4l2_buf_type { V4L2_BUF_TYPE_VIDEO_CAPTURE = 1, V4L2_BUF_TYPE_VIDEO_OUTPUT = 2, V4L2_BUF_TYPE_VIDEO_OVERLAY = 3, V4L2_BUF_TYPE_VBI_CAPTURE = 4, V4L2_BUF_TYPE_VBI_OUTPUT = 5, V4L2_BUF_TYPE_SLICED_VBI_CAPTURE = 6, V4L2_BUF_TYPE_SLICED_VBI_OUTPUT = 7, V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY = 8, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE = 9, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE = 10, V4L2_BUF_TYPE_SDR_CAPTURE = 11, V4L2_BUF_TYPE_SDR_OUTPUT = 12, V4L2_BUF_TYPE_META_CAPTURE = 13, V4L2_BUF_TYPE_META_OUTPUT = 14, /* Deprecated, do not use */ V4L2_BUF_TYPE_PRIVATE = 0x80, }; #define V4L2_TYPE_IS_MULTIPLANAR(type) \ ((type) == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE \ || (type) == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) #define V4L2_TYPE_IS_OUTPUT(type) \ ((type) == V4L2_BUF_TYPE_VIDEO_OUTPUT \ || (type) == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE \ || (type) == V4L2_BUF_TYPE_VIDEO_OVERLAY \ || (type) == V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY \ || (type) == V4L2_BUF_TYPE_VBI_OUTPUT \ || (type) == V4L2_BUF_TYPE_SLICED_VBI_OUTPUT \ || (type) == V4L2_BUF_TYPE_SDR_OUTPUT \ || (type) == V4L2_BUF_TYPE_META_OUTPUT) enum v4l2_tuner_type { V4L2_TUNER_RADIO = 1, V4L2_TUNER_ANALOG_TV = 2, V4L2_TUNER_DIGITAL_TV = 3, V4L2_TUNER_SDR = 4, V4L2_TUNER_RF = 5, }; /* Deprecated, do not use */ #define V4L2_TUNER_ADC V4L2_TUNER_SDR enum v4l2_memory { V4L2_MEMORY_MMAP = 1, V4L2_MEMORY_USERPTR = 2, V4L2_MEMORY_OVERLAY = 3, V4L2_MEMORY_DMABUF = 4, }; /* see also http://vektor.theorem.ca/graphics/ycbcr/ */ enum v4l2_colorspace { /* * Default colorspace, i.e. let the driver figure it out. * Can only be used with video capture. */ V4L2_COLORSPACE_DEFAULT = 0, /* SMPTE 170M: used for broadcast NTSC/PAL SDTV */ V4L2_COLORSPACE_SMPTE170M = 1, /* Obsolete pre-1998 SMPTE 240M HDTV standard, superseded by Rec 709 */ V4L2_COLORSPACE_SMPTE240M = 2, /* Rec.709: used for HDTV */ V4L2_COLORSPACE_REC709 = 3, /* * Deprecated, do not use. No driver will ever return this. This was * based on a misunderstanding of the bt878 datasheet. */ V4L2_COLORSPACE_BT878 = 4, /* * NTSC 1953 colorspace. This only makes sense when dealing with * really, really old NTSC recordings. Superseded by SMPTE 170M. */ V4L2_COLORSPACE_470_SYSTEM_M = 5, /* * EBU Tech 3213 PAL/SECAM colorspace. This only makes sense when * dealing with really old PAL/SECAM recordings. Superseded by * SMPTE 170M. */ V4L2_COLORSPACE_470_SYSTEM_BG = 6, /* * Effectively shorthand for V4L2_COLORSPACE_SRGB, V4L2_YCBCR_ENC_601 * and V4L2_QUANTIZATION_FULL_RANGE. To be used for (Motion-)JPEG. */ V4L2_COLORSPACE_JPEG = 7, /* For RGB colorspaces such as produces by most webcams. */ V4L2_COLORSPACE_SRGB = 8, /* opRGB colorspace */ V4L2_COLORSPACE_OPRGB = 9, /* BT.2020 colorspace, used for UHDTV. */ V4L2_COLORSPACE_BT2020 = 10, /* Raw colorspace: for RAW unprocessed images */ V4L2_COLORSPACE_RAW = 11, /* DCI-P3 colorspace, used by cinema projectors */ V4L2_COLORSPACE_DCI_P3 = 12, }; /* * Determine how COLORSPACE_DEFAULT should map to a proper colorspace. * This depends on whether this is a SDTV image (use SMPTE 170M), an * HDTV image (use Rec. 709), or something else (use sRGB). */ #define V4L2_MAP_COLORSPACE_DEFAULT(is_sdtv, is_hdtv) \ ((is_sdtv) ? V4L2_COLORSPACE_SMPTE170M : \ ((is_hdtv) ? V4L2_COLORSPACE_REC709 : V4L2_COLORSPACE_SRGB)) enum v4l2_xfer_func { /* * Mapping of V4L2_XFER_FUNC_DEFAULT to actual transfer functions * for the various colorspaces: * * V4L2_COLORSPACE_SMPTE170M, V4L2_COLORSPACE_470_SYSTEM_M, * V4L2_COLORSPACE_470_SYSTEM_BG, V4L2_COLORSPACE_REC709 and * V4L2_COLORSPACE_BT2020: V4L2_XFER_FUNC_709 * * V4L2_COLORSPACE_SRGB, V4L2_COLORSPACE_JPEG: V4L2_XFER_FUNC_SRGB * * V4L2_COLORSPACE_OPRGB: V4L2_XFER_FUNC_OPRGB * * V4L2_COLORSPACE_SMPTE240M: V4L2_XFER_FUNC_SMPTE240M * * V4L2_COLORSPACE_RAW: V4L2_XFER_FUNC_NONE * * V4L2_COLORSPACE_DCI_P3: V4L2_XFER_FUNC_DCI_P3 */ V4L2_XFER_FUNC_DEFAULT = 0, V4L2_XFER_FUNC_709 = 1, V4L2_XFER_FUNC_SRGB = 2, V4L2_XFER_FUNC_OPRGB = 3, V4L2_XFER_FUNC_SMPTE240M = 4, V4L2_XFER_FUNC_NONE = 5, V4L2_XFER_FUNC_DCI_P3 = 6, V4L2_XFER_FUNC_SMPTE2084 = 7, }; /* * Determine how XFER_FUNC_DEFAULT should map to a proper transfer function. * This depends on the colorspace. */ #define V4L2_MAP_XFER_FUNC_DEFAULT(colsp) \ ((colsp) == V4L2_COLORSPACE_OPRGB ? V4L2_XFER_FUNC_OPRGB : \ ((colsp) == V4L2_COLORSPACE_SMPTE240M ? V4L2_XFER_FUNC_SMPTE240M : \ ((colsp) == V4L2_COLORSPACE_DCI_P3 ? V4L2_XFER_FUNC_DCI_P3 : \ ((colsp) == V4L2_COLORSPACE_RAW ? V4L2_XFER_FUNC_NONE : \ ((colsp) == V4L2_COLORSPACE_SRGB || (colsp) == V4L2_COLORSPACE_JPEG ? \ V4L2_XFER_FUNC_SRGB : V4L2_XFER_FUNC_709))))) enum v4l2_ycbcr_encoding { /* * Mapping of V4L2_YCBCR_ENC_DEFAULT to actual encodings for the * various colorspaces: * * V4L2_COLORSPACE_SMPTE170M, V4L2_COLORSPACE_470_SYSTEM_M, * V4L2_COLORSPACE_470_SYSTEM_BG, V4L2_COLORSPACE_SRGB, * V4L2_COLORSPACE_OPRGB and V4L2_COLORSPACE_JPEG: V4L2_YCBCR_ENC_601 * * V4L2_COLORSPACE_REC709 and V4L2_COLORSPACE_DCI_P3: V4L2_YCBCR_ENC_709 * * V4L2_COLORSPACE_BT2020: V4L2_YCBCR_ENC_BT2020 * * V4L2_COLORSPACE_SMPTE240M: V4L2_YCBCR_ENC_SMPTE240M */ V4L2_YCBCR_ENC_DEFAULT = 0, /* ITU-R 601 -- SDTV */ V4L2_YCBCR_ENC_601 = 1, /* Rec. 709 -- HDTV */ V4L2_YCBCR_ENC_709 = 2, /* ITU-R 601/EN 61966-2-4 Extended Gamut -- SDTV */ V4L2_YCBCR_ENC_XV601 = 3, /* Rec. 709/EN 61966-2-4 Extended Gamut -- HDTV */ V4L2_YCBCR_ENC_XV709 = 4, /* * sYCC (Y'CbCr encoding of sRGB), identical to ENC_601. It was added * originally due to a misunderstanding of the sYCC standard. It should * not be used, instead use V4L2_YCBCR_ENC_601. */ V4L2_YCBCR_ENC_SYCC = 5, /* BT.2020 Non-constant Luminance Y'CbCr */ V4L2_YCBCR_ENC_BT2020 = 6, /* BT.2020 Constant Luminance Y'CbcCrc */ V4L2_YCBCR_ENC_BT2020_CONST_LUM = 7, /* SMPTE 240M -- Obsolete HDTV */ V4L2_YCBCR_ENC_SMPTE240M = 8, }; /* * enum v4l2_hsv_encoding values should not collide with the ones from * enum v4l2_ycbcr_encoding. */ enum v4l2_hsv_encoding { /* Hue mapped to 0 - 179 */ V4L2_HSV_ENC_180 = 128, /* Hue mapped to 0-255 */ V4L2_HSV_ENC_256 = 129, }; /* * Determine how YCBCR_ENC_DEFAULT should map to a proper Y'CbCr encoding. * This depends on the colorspace. */ #define V4L2_MAP_YCBCR_ENC_DEFAULT(colsp) \ (((colsp) == V4L2_COLORSPACE_REC709 || \ (colsp) == V4L2_COLORSPACE_DCI_P3) ? V4L2_YCBCR_ENC_709 : \ ((colsp) == V4L2_COLORSPACE_BT2020 ? V4L2_YCBCR_ENC_BT2020 : \ ((colsp) == V4L2_COLORSPACE_SMPTE240M ? V4L2_YCBCR_ENC_SMPTE240M : \ V4L2_YCBCR_ENC_601))) enum v4l2_quantization { /* * The default for R'G'B' quantization is always full range, except * for the BT2020 colorspace. For Y'CbCr the quantization is always * limited range, except for COLORSPACE_JPEG: this is full range. */ V4L2_QUANTIZATION_DEFAULT = 0, V4L2_QUANTIZATION_FULL_RANGE = 1, V4L2_QUANTIZATION_LIM_RANGE = 2, }; /* * Determine how QUANTIZATION_DEFAULT should map to a proper quantization. * This depends on whether the image is RGB or not, the colorspace and the * Y'CbCr encoding. */ #define V4L2_MAP_QUANTIZATION_DEFAULT(is_rgb_or_hsv, colsp, ycbcr_enc) \ (((is_rgb_or_hsv) && (colsp) == V4L2_COLORSPACE_BT2020) ? \ V4L2_QUANTIZATION_LIM_RANGE : \ (((is_rgb_or_hsv) || (colsp) == V4L2_COLORSPACE_JPEG) ? \ V4L2_QUANTIZATION_FULL_RANGE : V4L2_QUANTIZATION_LIM_RANGE)) /* * Deprecated names for opRGB colorspace (IEC 61966-2-5) * * WARNING: Please don't use these deprecated defines in your code, as * there is a chance we have to remove them in the future. */ #define V4L2_COLORSPACE_ADOBERGB V4L2_COLORSPACE_OPRGB #define V4L2_XFER_FUNC_ADOBERGB V4L2_XFER_FUNC_OPRGB enum v4l2_priority { V4L2_PRIORITY_UNSET = 0, /* not initialized */ V4L2_PRIORITY_BACKGROUND = 1, V4L2_PRIORITY_INTERACTIVE = 2, V4L2_PRIORITY_RECORD = 3, V4L2_PRIORITY_DEFAULT = V4L2_PRIORITY_INTERACTIVE, }; struct v4l2_rect { __s32 left; __s32 top; __u32 width; __u32 height; }; struct v4l2_fract { __u32 numerator; __u32 denominator; }; /** * struct v4l2_capability - Describes V4L2 device caps returned by VIDIOC_QUERYCAP * * @driver: name of the driver module (e.g. "bttv") * @card: name of the card (e.g. "Hauppauge WinTV") * @bus_info: name of the bus (e.g. "PCI:" + pci_name(pci_dev) ) * @version: KERNEL_VERSION * @capabilities: capabilities of the physical device as a whole * @device_caps: capabilities accessed via this particular device (node) * @reserved: reserved fields for future extensions */ struct v4l2_capability { __u8 driver[16]; __u8 card[32]; __u8 bus_info[32]; __u32 version; __u32 capabilities; __u32 device_caps; __u32 reserved[3]; }; /* Values for 'capabilities' field */ #define V4L2_CAP_VIDEO_CAPTURE 0x00000001 /* Is a video capture device */ #define V4L2_CAP_VIDEO_OUTPUT 0x00000002 /* Is a video output device */ #define V4L2_CAP_VIDEO_OVERLAY 0x00000004 /* Can do video overlay */ #define V4L2_CAP_VBI_CAPTURE 0x00000010 /* Is a raw VBI capture device */ #define V4L2_CAP_VBI_OUTPUT 0x00000020 /* Is a raw VBI output device */ #define V4L2_CAP_SLICED_VBI_CAPTURE 0x00000040 /* Is a sliced VBI capture device */ #define V4L2_CAP_SLICED_VBI_OUTPUT 0x00000080 /* Is a sliced VBI output device */ #define V4L2_CAP_RDS_CAPTURE 0x00000100 /* RDS data capture */ #define V4L2_CAP_VIDEO_OUTPUT_OVERLAY 0x00000200 /* Can do video output overlay */ #define V4L2_CAP_HW_FREQ_SEEK 0x00000400 /* Can do hardware frequency seek */ #define V4L2_CAP_RDS_OUTPUT 0x00000800 /* Is an RDS encoder */ /* Is a video capture device that supports multiplanar formats */ #define V4L2_CAP_VIDEO_CAPTURE_MPLANE 0x00001000 /* Is a video output device that supports multiplanar formats */ #define V4L2_CAP_VIDEO_OUTPUT_MPLANE 0x00002000 /* Is a video mem-to-mem device that supports multiplanar formats */ #define V4L2_CAP_VIDEO_M2M_MPLANE 0x00004000 /* Is a video mem-to-mem device */ #define V4L2_CAP_VIDEO_M2M 0x00008000 #define V4L2_CAP_TUNER 0x00010000 /* has a tuner */ #define V4L2_CAP_AUDIO 0x00020000 /* has audio support */ #define V4L2_CAP_RADIO 0x00040000 /* is a radio device */ #define V4L2_CAP_MODULATOR 0x00080000 /* has a modulator */ #define V4L2_CAP_SDR_CAPTURE 0x00100000 /* Is a SDR capture device */ #define V4L2_CAP_EXT_PIX_FORMAT 0x00200000 /* Supports the extended pixel format */ #define V4L2_CAP_SDR_OUTPUT 0x00400000 /* Is a SDR output device */ #define V4L2_CAP_META_CAPTURE 0x00800000 /* Is a metadata capture device */ #define V4L2_CAP_READWRITE 0x01000000 /* read/write systemcalls */ #define V4L2_CAP_ASYNCIO 0x02000000 /* async I/O */ #define V4L2_CAP_STREAMING 0x04000000 /* streaming I/O ioctls */ #define V4L2_CAP_META_OUTPUT 0x08000000 /* Is a metadata output device */ #define V4L2_CAP_TOUCH 0x10000000 /* Is a touch device */ #define V4L2_CAP_DEVICE_CAPS 0x80000000 /* sets device capabilities field */ /* * V I D E O I M A G E F O R M A T */ struct v4l2_pix_format { __u32 width; __u32 height; __u32 pixelformat; __u32 field; /* enum v4l2_field */ __u32 bytesperline; /* for padding, zero if unused */ __u32 sizeimage; __u32 colorspace; /* enum v4l2_colorspace */ __u32 priv; /* private data, depends on pixelformat */ __u32 flags; /* format flags (V4L2_PIX_FMT_FLAG_*) */ union { /* enum v4l2_ycbcr_encoding */ __u32 ycbcr_enc; /* enum v4l2_hsv_encoding */ __u32 hsv_enc; }; __u32 quantization; /* enum v4l2_quantization */ __u32 xfer_func; /* enum v4l2_xfer_func */ }; /* Pixel format FOURCC depth Description */ /* RGB formats */ #define V4L2_PIX_FMT_RGB332 v4l2_fourcc('R', 'G', 'B', '1') /* 8 RGB-3-3-2 */ #define V4L2_PIX_FMT_RGB444 v4l2_fourcc('R', '4', '4', '4') /* 16 xxxxrrrr ggggbbbb */ #define V4L2_PIX_FMT_ARGB444 v4l2_fourcc('A', 'R', '1', '2') /* 16 aaaarrrr ggggbbbb */ #define V4L2_PIX_FMT_XRGB444 v4l2_fourcc('X', 'R', '1', '2') /* 16 xxxxrrrr ggggbbbb */ #define V4L2_PIX_FMT_RGBA444 v4l2_fourcc('R', 'A', '1', '2') /* 16 rrrrgggg bbbbaaaa */ #define V4L2_PIX_FMT_RGBX444 v4l2_fourcc('R', 'X', '1', '2') /* 16 rrrrgggg bbbbxxxx */ #define V4L2_PIX_FMT_ABGR444 v4l2_fourcc('A', 'B', '1', '2') /* 16 aaaabbbb ggggrrrr */ #define V4L2_PIX_FMT_XBGR444 v4l2_fourcc('X', 'B', '1', '2') /* 16 xxxxbbbb ggggrrrr */ /* * Originally this had 'BA12' as fourcc, but this clashed with the older * V4L2_PIX_FMT_SGRBG12 which inexplicably used that same fourcc. * So use 'GA12' instead for V4L2_PIX_FMT_BGRA444. */ #define V4L2_PIX_FMT_BGRA444 v4l2_fourcc('G', 'A', '1', '2') /* 16 bbbbgggg rrrraaaa */ #define V4L2_PIX_FMT_BGRX444 v4l2_fourcc('B', 'X', '1', '2') /* 16 bbbbgggg rrrrxxxx */ #define V4L2_PIX_FMT_RGB555 v4l2_fourcc('R', 'G', 'B', 'O') /* 16 RGB-5-5-5 */ #define V4L2_PIX_FMT_ARGB555 v4l2_fourcc('A', 'R', '1', '5') /* 16 ARGB-1-5-5-5 */ #define V4L2_PIX_FMT_XRGB555 v4l2_fourcc('X', 'R', '1', '5') /* 16 XRGB-1-5-5-5 */ #define V4L2_PIX_FMT_RGBA555 v4l2_fourcc('R', 'A', '1', '5') /* 16 RGBA-5-5-5-1 */ #define V4L2_PIX_FMT_RGBX555 v4l2_fourcc('R', 'X', '1', '5') /* 16 RGBX-5-5-5-1 */ #define V4L2_PIX_FMT_ABGR555 v4l2_fourcc('A', 'B', '1', '5') /* 16 ABGR-1-5-5-5 */ #define V4L2_PIX_FMT_XBGR555 v4l2_fourcc('X', 'B', '1', '5') /* 16 XBGR-1-5-5-5 */ #define V4L2_PIX_FMT_BGRA555 v4l2_fourcc('B', 'A', '1', '5') /* 16 BGRA-5-5-5-1 */ #define V4L2_PIX_FMT_BGRX555 v4l2_fourcc('B', 'X', '1', '5') /* 16 BGRX-5-5-5-1 */ #define V4L2_PIX_FMT_RGB565 v4l2_fourcc('R', 'G', 'B', 'P') /* 16 RGB-5-6-5 */ #define V4L2_PIX_FMT_RGB555X v4l2_fourcc('R', 'G', 'B', 'Q') /* 16 RGB-5-5-5 BE */ #define V4L2_PIX_FMT_ARGB555X v4l2_fourcc_be('A', 'R', '1', '5') /* 16 ARGB-5-5-5 BE */ #define V4L2_PIX_FMT_XRGB555X v4l2_fourcc_be('X', 'R', '1', '5') /* 16 XRGB-5-5-5 BE */ #define V4L2_PIX_FMT_RGB565X v4l2_fourcc('R', 'G', 'B', 'R') /* 16 RGB-5-6-5 BE */ #define V4L2_PIX_FMT_BGR666 v4l2_fourcc('B', 'G', 'R', 'H') /* 18 BGR-6-6-6 */ #define V4L2_PIX_FMT_BGR24 v4l2_fourcc('B', 'G', 'R', '3') /* 24 BGR-8-8-8 */ #define V4L2_PIX_FMT_RGB24 v4l2_fourcc('R', 'G', 'B', '3') /* 24 RGB-8-8-8 */ #define V4L2_PIX_FMT_BGR32 v4l2_fourcc('B', 'G', 'R', '4') /* 32 BGR-8-8-8-8 */ #define V4L2_PIX_FMT_ABGR32 v4l2_fourcc('A', 'R', '2', '4') /* 32 BGRA-8-8-8-8 */ #define V4L2_PIX_FMT_XBGR32 v4l2_fourcc('X', 'R', '2', '4') /* 32 BGRX-8-8-8-8 */ #define V4L2_PIX_FMT_BGRA32 v4l2_fourcc('R', 'A', '2', '4') /* 32 ABGR-8-8-8-8 */ #define V4L2_PIX_FMT_BGRX32 v4l2_fourcc('R', 'X', '2', '4') /* 32 XBGR-8-8-8-8 */ #define V4L2_PIX_FMT_RGB32 v4l2_fourcc('R', 'G', 'B', '4') /* 32 RGB-8-8-8-8 */ #define V4L2_PIX_FMT_RGBA32 v4l2_fourcc('A', 'B', '2', '4') /* 32 RGBA-8-8-8-8 */ #define V4L2_PIX_FMT_RGBX32 v4l2_fourcc('X', 'B', '2', '4') /* 32 RGBX-8-8-8-8 */ #define V4L2_PIX_FMT_ARGB32 v4l2_fourcc('B', 'A', '2', '4') /* 32 ARGB-8-8-8-8 */ #define V4L2_PIX_FMT_XRGB32 v4l2_fourcc('B', 'X', '2', '4') /* 32 XRGB-8-8-8-8 */ /* Grey formats */ #define V4L2_PIX_FMT_GREY v4l2_fourcc('G', 'R', 'E', 'Y') /* 8 Greyscale */ #define V4L2_PIX_FMT_Y4 v4l2_fourcc('Y', '0', '4', ' ') /* 4 Greyscale */ #define V4L2_PIX_FMT_Y6 v4l2_fourcc('Y', '0', '6', ' ') /* 6 Greyscale */ #define V4L2_PIX_FMT_Y10 v4l2_fourcc('Y', '1', '0', ' ') /* 10 Greyscale */ #define V4L2_PIX_FMT_Y12 v4l2_fourcc('Y', '1', '2', ' ') /* 12 Greyscale */ #define V4L2_PIX_FMT_Y16 v4l2_fourcc('Y', '1', '6', ' ') /* 16 Greyscale */ #define V4L2_PIX_FMT_Y16_BE v4l2_fourcc_be('Y', '1', '6', ' ') /* 16 Greyscale BE */ /* Grey bit-packed formats */ #define V4L2_PIX_FMT_Y10BPACK v4l2_fourcc('Y', '1', '0', 'B') /* 10 Greyscale bit-packed */ #define V4L2_PIX_FMT_Y10P v4l2_fourcc('Y', '1', '0', 'P') /* 10 Greyscale, MIPI RAW10 packed */ /* Palette formats */ #define V4L2_PIX_FMT_PAL8 v4l2_fourcc('P', 'A', 'L', '8') /* 8 8-bit palette */ /* Chrominance formats */ #define V4L2_PIX_FMT_UV8 v4l2_fourcc('U', 'V', '8', ' ') /* 8 UV 4:4 */ /* Luminance+Chrominance formats */ #define V4L2_PIX_FMT_YUYV v4l2_fourcc('Y', 'U', 'Y', 'V') /* 16 YUV 4:2:2 */ #define V4L2_PIX_FMT_YYUV v4l2_fourcc('Y', 'Y', 'U', 'V') /* 16 YUV 4:2:2 */ #define V4L2_PIX_FMT_YVYU v4l2_fourcc('Y', 'V', 'Y', 'U') /* 16 YVU 4:2:2 */ #define V4L2_PIX_FMT_UYVY v4l2_fourcc('U', 'Y', 'V', 'Y') /* 16 YUV 4:2:2 */ #define V4L2_PIX_FMT_VYUY v4l2_fourcc('V', 'Y', 'U', 'Y') /* 16 YUV 4:2:2 */ #define V4L2_PIX_FMT_Y41P v4l2_fourcc('Y', '4', '1', 'P') /* 12 YUV 4:1:1 */ #define V4L2_PIX_FMT_YUV444 v4l2_fourcc('Y', '4', '4', '4') /* 16 xxxxyyyy uuuuvvvv */ #define V4L2_PIX_FMT_YUV555 v4l2_fourcc('Y', 'U', 'V', 'O') /* 16 YUV-5-5-5 */ #define V4L2_PIX_FMT_YUV565 v4l2_fourcc('Y', 'U', 'V', 'P') /* 16 YUV-5-6-5 */ #define V4L2_PIX_FMT_YUV32 v4l2_fourcc('Y', 'U', 'V', '4') /* 32 YUV-8-8-8-8 */ #define V4L2_PIX_FMT_AYUV32 v4l2_fourcc('A', 'Y', 'U', 'V') /* 32 AYUV-8-8-8-8 */ #define V4L2_PIX_FMT_XYUV32 v4l2_fourcc('X', 'Y', 'U', 'V') /* 32 XYUV-8-8-8-8 */ #define V4L2_PIX_FMT_VUYA32 v4l2_fourcc('V', 'U', 'Y', 'A') /* 32 VUYA-8-8-8-8 */ #define V4L2_PIX_FMT_VUYX32 v4l2_fourcc('V', 'U', 'Y', 'X') /* 32 VUYX-8-8-8-8 */ #define V4L2_PIX_FMT_HI240 v4l2_fourcc('H', 'I', '2', '4') /* 8 8-bit color */ #define V4L2_PIX_FMT_HM12 v4l2_fourcc('H', 'M', '1', '2') /* 8 YUV 4:2:0 16x16 macroblocks */ #define V4L2_PIX_FMT_M420 v4l2_fourcc('M', '4', '2', '0') /* 12 YUV 4:2:0 2 lines y, 1 line uv interleaved */ /* two planes -- one Y, one Cr + Cb interleaved */ #define V4L2_PIX_FMT_NV12 v4l2_fourcc('N', 'V', '1', '2') /* 12 Y/CbCr 4:2:0 */ #define V4L2_PIX_FMT_NV21 v4l2_fourcc('N', 'V', '2', '1') /* 12 Y/CrCb 4:2:0 */ #define V4L2_PIX_FMT_NV16 v4l2_fourcc('N', 'V', '1', '6') /* 16 Y/CbCr 4:2:2 */ #define V4L2_PIX_FMT_NV61 v4l2_fourcc('N', 'V', '6', '1') /* 16 Y/CrCb 4:2:2 */ #define V4L2_PIX_FMT_NV24 v4l2_fourcc('N', 'V', '2', '4') /* 24 Y/CbCr 4:4:4 */ #define V4L2_PIX_FMT_NV42 v4l2_fourcc('N', 'V', '4', '2') /* 24 Y/CrCb 4:4:4 */ /* two non contiguous planes - one Y, one Cr + Cb interleaved */ #define V4L2_PIX_FMT_NV12M v4l2_fourcc('N', 'M', '1', '2') /* 12 Y/CbCr 4:2:0 */ #define V4L2_PIX_FMT_NV21M v4l2_fourcc('N', 'M', '2', '1') /* 21 Y/CrCb 4:2:0 */ #define V4L2_PIX_FMT_NV16M v4l2_fourcc('N', 'M', '1', '6') /* 16 Y/CbCr 4:2:2 */ #define V4L2_PIX_FMT_NV61M v4l2_fourcc('N', 'M', '6', '1') /* 16 Y/CrCb 4:2:2 */ #define V4L2_PIX_FMT_NV12MT v4l2_fourcc('T', 'M', '1', '2') /* 12 Y/CbCr 4:2:0 64x32 macroblocks */ #define V4L2_PIX_FMT_NV12MT_16X16 v4l2_fourcc('V', 'M', '1', '2') /* 12 Y/CbCr 4:2:0 16x16 macroblocks */ /* three planes - Y Cb, Cr */ #define V4L2_PIX_FMT_YUV410 v4l2_fourcc('Y', 'U', 'V', '9') /* 9 YUV 4:1:0 */ #define V4L2_PIX_FMT_YVU410 v4l2_fourcc('Y', 'V', 'U', '9') /* 9 YVU 4:1:0 */ #define V4L2_PIX_FMT_YUV411P v4l2_fourcc('4', '1', '1', 'P') /* 12 YVU411 planar */ #define V4L2_PIX_FMT_YUV420 v4l2_fourcc('Y', 'U', '1', '2') /* 12 YUV 4:2:0 */ #define V4L2_PIX_FMT_YVU420 v4l2_fourcc('Y', 'V', '1', '2') /* 12 YVU 4:2:0 */ #define V4L2_PIX_FMT_YUV422P v4l2_fourcc('4', '2', '2', 'P') /* 16 YVU422 planar */ /* three non contiguous planes - Y, Cb, Cr */ #define V4L2_PIX_FMT_YUV420M v4l2_fourcc('Y', 'M', '1', '2') /* 12 YUV420 planar */ #define V4L2_PIX_FMT_YVU420M v4l2_fourcc('Y', 'M', '2', '1') /* 12 YVU420 planar */ #define V4L2_PIX_FMT_YUV422M v4l2_fourcc('Y', 'M', '1', '6') /* 16 YUV422 planar */ #define V4L2_PIX_FMT_YVU422M v4l2_fourcc('Y', 'M', '6', '1') /* 16 YVU422 planar */ #define V4L2_PIX_FMT_YUV444M v4l2_fourcc('Y', 'M', '2', '4') /* 24 YUV444 planar */ #define V4L2_PIX_FMT_YVU444M v4l2_fourcc('Y', 'M', '4', '2') /* 24 YVU444 planar */ /* Bayer formats - see http://www.siliconimaging.com/RGB%20Bayer.htm */ #define V4L2_PIX_FMT_SBGGR8 v4l2_fourcc('B', 'A', '8', '1') /* 8 BGBG.. GRGR.. */ #define V4L2_PIX_FMT_SGBRG8 v4l2_fourcc('G', 'B', 'R', 'G') /* 8 GBGB.. RGRG.. */ #define V4L2_PIX_FMT_SGRBG8 v4l2_fourcc('G', 'R', 'B', 'G') /* 8 GRGR.. BGBG.. */ #define V4L2_PIX_FMT_SRGGB8 v4l2_fourcc('R', 'G', 'G', 'B') /* 8 RGRG.. GBGB.. */ #define V4L2_PIX_FMT_SBGGR10 v4l2_fourcc('B', 'G', '1', '0') /* 10 BGBG.. GRGR.. */ #define V4L2_PIX_FMT_SGBRG10 v4l2_fourcc('G', 'B', '1', '0') /* 10 GBGB.. RGRG.. */ #define V4L2_PIX_FMT_SGRBG10 v4l2_fourcc('B', 'A', '1', '0') /* 10 GRGR.. BGBG.. */ #define V4L2_PIX_FMT_SRGGB10 v4l2_fourcc('R', 'G', '1', '0') /* 10 RGRG.. GBGB.. */ /* 10bit raw bayer packed, 5 bytes for every 4 pixels */ #define V4L2_PIX_FMT_SBGGR10P v4l2_fourcc('p', 'B', 'A', 'A') #define V4L2_PIX_FMT_SGBRG10P v4l2_fourcc('p', 'G', 'A', 'A') #define V4L2_PIX_FMT_SGRBG10P v4l2_fourcc('p', 'g', 'A', 'A') #define V4L2_PIX_FMT_SRGGB10P v4l2_fourcc('p', 'R', 'A', 'A') /* 10bit raw bayer a-law compressed to 8 bits */ #define V4L2_PIX_FMT_SBGGR10ALAW8 v4l2_fourcc('a', 'B', 'A', '8') #define V4L2_PIX_FMT_SGBRG10ALAW8 v4l2_fourcc('a', 'G', 'A', '8') #define V4L2_PIX_FMT_SGRBG10ALAW8 v4l2_fourcc('a', 'g', 'A', '8') #define V4L2_PIX_FMT_SRGGB10ALAW8 v4l2_fourcc('a', 'R', 'A', '8') /* 10bit raw bayer DPCM compressed to 8 bits */ #define V4L2_PIX_FMT_SBGGR10DPCM8 v4l2_fourcc('b', 'B', 'A', '8') #define V4L2_PIX_FMT_SGBRG10DPCM8 v4l2_fourcc('b', 'G', 'A', '8') #define V4L2_PIX_FMT_SGRBG10DPCM8 v4l2_fourcc('B', 'D', '1', '0') #define V4L2_PIX_FMT_SRGGB10DPCM8 v4l2_fourcc('b', 'R', 'A', '8') #define V4L2_PIX_FMT_SBGGR12 v4l2_fourcc('B', 'G', '1', '2') /* 12 BGBG.. GRGR.. */ #define V4L2_PIX_FMT_SGBRG12 v4l2_fourcc('G', 'B', '1', '2') /* 12 GBGB.. RGRG.. */ #define V4L2_PIX_FMT_SGRBG12 v4l2_fourcc('B', 'A', '1', '2') /* 12 GRGR.. BGBG.. */ #define V4L2_PIX_FMT_SRGGB12 v4l2_fourcc('R', 'G', '1', '2') /* 12 RGRG.. GBGB.. */ /* 12bit raw bayer packed, 6 bytes for every 4 pixels */ #define V4L2_PIX_FMT_SBGGR12P v4l2_fourcc('p', 'B', 'C', 'C') #define V4L2_PIX_FMT_SGBRG12P v4l2_fourcc('p', 'G', 'C', 'C') #define V4L2_PIX_FMT_SGRBG12P v4l2_fourcc('p', 'g', 'C', 'C') #define V4L2_PIX_FMT_SRGGB12P v4l2_fourcc('p', 'R', 'C', 'C') /* 14bit raw bayer packed, 7 bytes for every 4 pixels */ #define V4L2_PIX_FMT_SBGGR14P v4l2_fourcc('p', 'B', 'E', 'E') #define V4L2_PIX_FMT_SGBRG14P v4l2_fourcc('p', 'G', 'E', 'E') #define V4L2_PIX_FMT_SGRBG14P v4l2_fourcc('p', 'g', 'E', 'E') #define V4L2_PIX_FMT_SRGGB14P v4l2_fourcc('p', 'R', 'E', 'E') #define V4L2_PIX_FMT_SBGGR16 v4l2_fourcc('B', 'Y', 'R', '2') /* 16 BGBG.. GRGR.. */ #define V4L2_PIX_FMT_SGBRG16 v4l2_fourcc('G', 'B', '1', '6') /* 16 GBGB.. RGRG.. */ #define V4L2_PIX_FMT_SGRBG16 v4l2_fourcc('G', 'R', '1', '6') /* 16 GRGR.. BGBG.. */ #define V4L2_PIX_FMT_SRGGB16 v4l2_fourcc('R', 'G', '1', '6') /* 16 RGRG.. GBGB.. */ /* HSV formats */ #define V4L2_PIX_FMT_HSV24 v4l2_fourcc('H', 'S', 'V', '3') #define V4L2_PIX_FMT_HSV32 v4l2_fourcc('H', 'S', 'V', '4') /* compressed formats */ #define V4L2_PIX_FMT_MJPEG v4l2_fourcc('M', 'J', 'P', 'G') /* Motion-JPEG */ #define V4L2_PIX_FMT_JPEG v4l2_fourcc('J', 'P', 'E', 'G') /* JFIF JPEG */ #define V4L2_PIX_FMT_DV v4l2_fourcc('d', 'v', 's', 'd') /* 1394 */ #define V4L2_PIX_FMT_MPEG v4l2_fourcc('M', 'P', 'E', 'G') /* MPEG-1/2/4 Multiplexed */ #define V4L2_PIX_FMT_H264 v4l2_fourcc('H', '2', '6', '4') /* H264 with start codes */ #define V4L2_PIX_FMT_H264_NO_SC v4l2_fourcc('A', 'V', 'C', '1') /* H264 without start codes */ #define V4L2_PIX_FMT_H264_MVC v4l2_fourcc('M', '2', '6', '4') /* H264 MVC */ #define V4L2_PIX_FMT_H263 v4l2_fourcc('H', '2', '6', '3') /* H263 */ #define V4L2_PIX_FMT_MPEG1 v4l2_fourcc('M', 'P', 'G', '1') /* MPEG-1 ES */ #define V4L2_PIX_FMT_MPEG2 v4l2_fourcc('M', 'P', 'G', '2') /* MPEG-2 ES */ #define V4L2_PIX_FMT_MPEG2_SLICE v4l2_fourcc('M', 'G', '2', 'S') /* MPEG-2 parsed slice data */ #define V4L2_PIX_FMT_MPEG4 v4l2_fourcc('M', 'P', 'G', '4') /* MPEG-4 part 2 ES */ #define V4L2_PIX_FMT_XVID v4l2_fourcc('X', 'V', 'I', 'D') /* Xvid */ #define V4L2_PIX_FMT_VC1_ANNEX_G v4l2_fourcc('V', 'C', '1', 'G') /* SMPTE 421M Annex G compliant stream */ #define V4L2_PIX_FMT_VC1_ANNEX_L v4l2_fourcc('V', 'C', '1', 'L') /* SMPTE 421M Annex L compliant stream */ #define V4L2_PIX_FMT_VP8 v4l2_fourcc('V', 'P', '8', '0') /* VP8 */ #define V4L2_PIX_FMT_VP9 v4l2_fourcc('V', 'P', '9', '0') /* VP9 */ #define V4L2_PIX_FMT_HEVC v4l2_fourcc('H', 'E', 'V', 'C') /* HEVC aka H.265 */ #define V4L2_PIX_FMT_FWHT v4l2_fourcc('F', 'W', 'H', 'T') /* Fast Walsh Hadamard Transform (vicodec) */ /* Vendor-specific formats */ #define V4L2_PIX_FMT_CPIA1 v4l2_fourcc('C', 'P', 'I', 'A') /* cpia1 YUV */ #define V4L2_PIX_FMT_WNVA v4l2_fourcc('W', 'N', 'V', 'A') /* Winnov hw compress */ #define V4L2_PIX_FMT_SN9C10X v4l2_fourcc('S', '9', '1', '0') /* SN9C10x compression */ #define V4L2_PIX_FMT_SN9C20X_I420 v4l2_fourcc('S', '9', '2', '0') /* SN9C20x YUV 4:2:0 */ #define V4L2_PIX_FMT_PWC1 v4l2_fourcc('P', 'W', 'C', '1') /* pwc older webcam */ #define V4L2_PIX_FMT_PWC2 v4l2_fourcc('P', 'W', 'C', '2') /* pwc newer webcam */ #define V4L2_PIX_FMT_ET61X251 v4l2_fourcc('E', '6', '2', '5') /* ET61X251 compression */ #define V4L2_PIX_FMT_SPCA501 v4l2_fourcc('S', '5', '0', '1') /* YUYV per line */ #define V4L2_PIX_FMT_SPCA505 v4l2_fourcc('S', '5', '0', '5') /* YYUV per line */ #define V4L2_PIX_FMT_SPCA508 v4l2_fourcc('S', '5', '0', '8') /* YUVY per line */ #define V4L2_PIX_FMT_SPCA561 v4l2_fourcc('S', '5', '6', '1') /* compressed GBRG bayer */ #define V4L2_PIX_FMT_PAC207 v4l2_fourcc('P', '2', '0', '7') /* compressed BGGR bayer */ #define V4L2_PIX_FMT_MR97310A v4l2_fourcc('M', '3', '1', '0') /* compressed BGGR bayer */ #define V4L2_PIX_FMT_JL2005BCD v4l2_fourcc('J', 'L', '2', '0') /* compressed RGGB bayer */ #define V4L2_PIX_FMT_SN9C2028 v4l2_fourcc('S', 'O', 'N', 'X') /* compressed GBRG bayer */ #define V4L2_PIX_FMT_SQ905C v4l2_fourcc('9', '0', '5', 'C') /* compressed RGGB bayer */ #define V4L2_PIX_FMT_PJPG v4l2_fourcc('P', 'J', 'P', 'G') /* Pixart 73xx JPEG */ #define V4L2_PIX_FMT_OV511 v4l2_fourcc('O', '5', '1', '1') /* ov511 JPEG */ #define V4L2_PIX_FMT_OV518 v4l2_fourcc('O', '5', '1', '8') /* ov518 JPEG */ #define V4L2_PIX_FMT_STV0680 v4l2_fourcc('S', '6', '8', '0') /* stv0680 bayer */ #define V4L2_PIX_FMT_TM6000 v4l2_fourcc('T', 'M', '6', '0') /* tm5600/tm60x0 */ #define V4L2_PIX_FMT_CIT_YYVYUY v4l2_fourcc('C', 'I', 'T', 'V') /* one line of Y then 1 line of VYUY */ #define V4L2_PIX_FMT_KONICA420 v4l2_fourcc('K', 'O', 'N', 'I') /* YUV420 planar in blocks of 256 pixels */ #define V4L2_PIX_FMT_JPGL v4l2_fourcc('J', 'P', 'G', 'L') /* JPEG-Lite */ #define V4L2_PIX_FMT_SE401 v4l2_fourcc('S', '4', '0', '1') /* se401 janggu compressed rgb */ #define V4L2_PIX_FMT_S5C_UYVY_JPG v4l2_fourcc('S', '5', 'C', 'I') /* S5C73M3 interleaved UYVY/JPEG */ #define V4L2_PIX_FMT_Y8I v4l2_fourcc('Y', '8', 'I', ' ') /* Greyscale 8-bit L/R interleaved */ #define V4L2_PIX_FMT_Y12I v4l2_fourcc('Y', '1', '2', 'I') /* Greyscale 12-bit L/R interleaved */ #define V4L2_PIX_FMT_Z16 v4l2_fourcc('Z', '1', '6', ' ') /* Depth data 16-bit */ #define V4L2_PIX_FMT_MT21C v4l2_fourcc('M', 'T', '2', '1') /* Mediatek compressed block mode */ #define V4L2_PIX_FMT_INZI v4l2_fourcc('I', 'N', 'Z', 'I') /* Intel Planar Greyscale 10-bit and Depth 16-bit */ #define V4L2_PIX_FMT_SUNXI_TILED_NV12 v4l2_fourcc('S', 'T', '1', '2') /* Sunxi Tiled NV12 Format */ #define V4L2_PIX_FMT_CNF4 v4l2_fourcc('C', 'N', 'F', '4') /* Intel 4-bit packed depth confidence information */ /* 10bit raw bayer packed, 32 bytes for every 25 pixels, last LSB 6 bits unused */ #define V4L2_PIX_FMT_IPU3_SBGGR10 v4l2_fourcc('i', 'p', '3', 'b') /* IPU3 packed 10-bit BGGR bayer */ #define V4L2_PIX_FMT_IPU3_SGBRG10 v4l2_fourcc('i', 'p', '3', 'g') /* IPU3 packed 10-bit GBRG bayer */ #define V4L2_PIX_FMT_IPU3_SGRBG10 v4l2_fourcc('i', 'p', '3', 'G') /* IPU3 packed 10-bit GRBG bayer */ #define V4L2_PIX_FMT_IPU3_SRGGB10 v4l2_fourcc('i', 'p', '3', 'r') /* IPU3 packed 10-bit RGGB bayer */ /* SDR formats - used only for Software Defined Radio devices */ #define V4L2_SDR_FMT_CU8 v4l2_fourcc('C', 'U', '0', '8') /* IQ u8 */ #define V4L2_SDR_FMT_CU16LE v4l2_fourcc('C', 'U', '1', '6') /* IQ u16le */ #define V4L2_SDR_FMT_CS8 v4l2_fourcc('C', 'S', '0', '8') /* complex s8 */ #define V4L2_SDR_FMT_CS14LE v4l2_fourcc('C', 'S', '1', '4') /* complex s14le */ #define V4L2_SDR_FMT_RU12LE v4l2_fourcc('R', 'U', '1', '2') /* real u12le */ #define V4L2_SDR_FMT_PCU16BE v4l2_fourcc('P', 'C', '1', '6') /* planar complex u16be */ #define V4L2_SDR_FMT_PCU18BE v4l2_fourcc('P', 'C', '1', '8') /* planar complex u18be */ #define V4L2_SDR_FMT_PCU20BE v4l2_fourcc('P', 'C', '2', '0') /* planar complex u20be */ /* Touch formats - used for Touch devices */ #define V4L2_TCH_FMT_DELTA_TD16 v4l2_fourcc('T', 'D', '1', '6') /* 16-bit signed deltas */ #define V4L2_TCH_FMT_DELTA_TD08 v4l2_fourcc('T', 'D', '0', '8') /* 8-bit signed deltas */ #define V4L2_TCH_FMT_TU16 v4l2_fourcc('T', 'U', '1', '6') /* 16-bit unsigned touch data */ #define V4L2_TCH_FMT_TU08 v4l2_fourcc('T', 'U', '0', '8') /* 8-bit unsigned touch data */ /* Meta-data formats */ #define V4L2_META_FMT_VSP1_HGO v4l2_fourcc('V', 'S', 'P', 'H') /* R-Car VSP1 1-D Histogram */ #define V4L2_META_FMT_VSP1_HGT v4l2_fourcc('V', 'S', 'P', 'T') /* R-Car VSP1 2-D Histogram */ #define V4L2_META_FMT_UVC v4l2_fourcc('U', 'V', 'C', 'H') /* UVC Payload Header metadata */ #define V4L2_META_FMT_D4XX v4l2_fourcc('D', '4', 'X', 'X') /* D4XX Payload Header metadata */ /* priv field value to indicates that subsequent fields are valid. */ #define V4L2_PIX_FMT_PRIV_MAGIC 0xfeedcafe /* Flags */ #define V4L2_PIX_FMT_FLAG_PREMUL_ALPHA 0x00000001 /* * F O R M A T E N U M E R A T I O N */ struct v4l2_fmtdesc { __u32 index; /* Format number */ __u32 type; /* enum v4l2_buf_type */ __u32 flags; __u8 description[32]; /* Description string */ __u32 pixelformat; /* Format fourcc */ __u32 reserved[4]; }; #define V4L2_FMT_FLAG_COMPRESSED 0x0001 #define V4L2_FMT_FLAG_EMULATED 0x0002 /* Frame Size and frame rate enumeration */ /* * F R A M E S I Z E E N U M E R A T I O N */ enum v4l2_frmsizetypes { V4L2_FRMSIZE_TYPE_DISCRETE = 1, V4L2_FRMSIZE_TYPE_CONTINUOUS = 2, V4L2_FRMSIZE_TYPE_STEPWISE = 3, }; struct v4l2_frmsize_discrete { __u32 width; /* Frame width [pixel] */ __u32 height; /* Frame height [pixel] */ }; struct v4l2_frmsize_stepwise { __u32 min_width; /* Minimum frame width [pixel] */ __u32 max_width; /* Maximum frame width [pixel] */ __u32 step_width; /* Frame width step size [pixel] */ __u32 min_height; /* Minimum frame height [pixel] */ __u32 max_height; /* Maximum frame height [pixel] */ __u32 step_height; /* Frame height step size [pixel] */ }; struct v4l2_frmsizeenum { __u32 index; /* Frame size number */ __u32 pixel_format; /* Pixel format */ __u32 type; /* Frame size type the device supports. */ union { /* Frame size */ struct v4l2_frmsize_discrete discrete; struct v4l2_frmsize_stepwise stepwise; }; __u32 reserved[2]; /* Reserved space for future use */ }; /* * F R A M E R A T E E N U M E R A T I O N */ enum v4l2_frmivaltypes { V4L2_FRMIVAL_TYPE_DISCRETE = 1, V4L2_FRMIVAL_TYPE_CONTINUOUS = 2, V4L2_FRMIVAL_TYPE_STEPWISE = 3, }; struct v4l2_frmival_stepwise { struct v4l2_fract min; /* Minimum frame interval [s] */ struct v4l2_fract max; /* Maximum frame interval [s] */ struct v4l2_fract step; /* Frame interval step size [s] */ }; struct v4l2_frmivalenum { __u32 index; /* Frame format index */ __u32 pixel_format; /* Pixel format */ __u32 width; /* Frame width */ __u32 height; /* Frame height */ __u32 type; /* Frame interval type the device supports. */ union { /* Frame interval */ struct v4l2_fract discrete; struct v4l2_frmival_stepwise stepwise; }; __u32 reserved[2]; /* Reserved space for future use */ }; /* * T I M E C O D E */ struct v4l2_timecode { __u32 type; __u32 flags; __u8 frames; __u8 seconds; __u8 minutes; __u8 hours; __u8 userbits[4]; }; /* Type */ #define V4L2_TC_TYPE_24FPS 1 #define V4L2_TC_TYPE_25FPS 2 #define V4L2_TC_TYPE_30FPS 3 #define V4L2_TC_TYPE_50FPS 4 #define V4L2_TC_TYPE_60FPS 5 /* Flags */ #define V4L2_TC_FLAG_DROPFRAME 0x0001 /* "drop-frame" mode */ #define V4L2_TC_FLAG_COLORFRAME 0x0002 #define V4L2_TC_USERBITS_field 0x000C #define V4L2_TC_USERBITS_USERDEFINED 0x0000 #define V4L2_TC_USERBITS_8BITCHARS 0x0008 /* The above is based on SMPTE timecodes */ struct v4l2_jpegcompression { int quality; int APPn; /* Number of APP segment to be written, * must be 0..15 */ int APP_len; /* Length of data in JPEG APPn segment */ char APP_data[60]; /* Data in the JPEG APPn segment. */ int COM_len; /* Length of data in JPEG COM segment */ char COM_data[60]; /* Data in JPEG COM segment */ __u32 jpeg_markers; /* Which markers should go into the JPEG * output. Unless you exactly know what * you do, leave them untouched. * Including less markers will make the * resulting code smaller, but there will * be fewer applications which can read it. * The presence of the APP and COM marker * is influenced by APP_len and COM_len * ONLY, not by this property! */ #define V4L2_JPEG_MARKER_DHT (1<<3) /* Define Huffman Tables */ #define V4L2_JPEG_MARKER_DQT (1<<4) /* Define Quantization Tables */ #define V4L2_JPEG_MARKER_DRI (1<<5) /* Define Restart Interval */ #define V4L2_JPEG_MARKER_COM (1<<6) /* Comment segment */ #define V4L2_JPEG_MARKER_APP (1<<7) /* App segment, driver will * always use APP0 */ }; /* * M E M O R Y - M A P P I N G B U F F E R S */ struct v4l2_requestbuffers { __u32 count; __u32 type; /* enum v4l2_buf_type */ __u32 memory; /* enum v4l2_memory */ __u32 capabilities; __u32 reserved[1]; }; /* capabilities for struct v4l2_requestbuffers and v4l2_create_buffers */ #define V4L2_BUF_CAP_SUPPORTS_MMAP (1 << 0) #define V4L2_BUF_CAP_SUPPORTS_USERPTR (1 << 1) #define V4L2_BUF_CAP_SUPPORTS_DMABUF (1 << 2) #define V4L2_BUF_CAP_SUPPORTS_REQUESTS (1 << 3) /** * struct v4l2_plane - plane info for multi-planar buffers * @bytesused: number of bytes occupied by data in the plane (payload) * @length: size of this plane (NOT the payload) in bytes * @mem_offset: when memory in the associated struct v4l2_buffer is * V4L2_MEMORY_MMAP, equals the offset from the start of * the device memory for this plane (or is a "cookie" that * should be passed to mmap() called on the video node) * @userptr: when memory is V4L2_MEMORY_USERPTR, a userspace pointer * pointing to this plane * @fd: when memory is V4L2_MEMORY_DMABUF, a userspace file * descriptor associated with this plane * @data_offset: offset in the plane to the start of data; usually 0, * unless there is a header in front of the data * * Multi-planar buffers consist of one or more planes, e.g. an YCbCr buffer * with two planes can have one plane for Y, and another for interleaved CbCr * components. Each plane can reside in a separate memory buffer, or even in * a completely separate memory node (e.g. in embedded devices). */ struct v4l2_plane { __u32 bytesused; __u32 length; union { __u32 mem_offset; unsigned long userptr; __s32 fd; } m; __u32 data_offset; __u32 reserved[11]; }; /** * struct v4l2_buffer - video buffer info * @index: id number of the buffer * @type: enum v4l2_buf_type; buffer type (type == *_MPLANE for * multiplanar buffers); * @bytesused: number of bytes occupied by data in the buffer (payload); * unused (set to 0) for multiplanar buffers * @flags: buffer informational flags * @field: enum v4l2_field; field order of the image in the buffer * @timestamp: frame timestamp * @timecode: frame timecode * @sequence: sequence count of this frame * @memory: enum v4l2_memory; the method, in which the actual video data is * passed * @offset: for non-multiplanar buffers with memory == V4L2_MEMORY_MMAP; * offset from the start of the device memory for this plane, * (or a "cookie" that should be passed to mmap() as offset) * @userptr: for non-multiplanar buffers with memory == V4L2_MEMORY_USERPTR; * a userspace pointer pointing to this buffer * @fd: for non-multiplanar buffers with memory == V4L2_MEMORY_DMABUF; * a userspace file descriptor associated with this buffer * @planes: for multiplanar buffers; userspace pointer to the array of plane * info structs for this buffer * @length: size in bytes of the buffer (NOT its payload) for single-plane * buffers (when type != *_MPLANE); number of elements in the * planes array for multi-plane buffers * * Contains data exchanged by application and driver using one of the Streaming * I/O methods. */ struct v4l2_buffer { __u32 index; __u32 type; __u32 bytesused; __u32 flags; __u32 field; struct timeval timestamp; struct v4l2_timecode timecode; __u32 sequence; /* memory location */ __u32 memory; union { __u32 offset; unsigned long userptr; struct v4l2_plane *planes; __s32 fd; } m; __u32 length; __u32 reserved2; __u32 reserved; }; /* Flags for 'flags' field */ /* Buffer is mapped (flag) */ #define V4L2_BUF_FLAG_MAPPED 0x00000001 /* Buffer is queued for processing */ #define V4L2_BUF_FLAG_QUEUED 0x00000002 /* Buffer is ready */ #define V4L2_BUF_FLAG_DONE 0x00000004 /* Image is a keyframe (I-frame) */ #define V4L2_BUF_FLAG_KEYFRAME 0x00000008 /* Image is a P-frame */ #define V4L2_BUF_FLAG_PFRAME 0x00000010 /* Image is a B-frame */ #define V4L2_BUF_FLAG_BFRAME 0x00000020 /* Buffer is ready, but the data contained within is corrupted. */ #define V4L2_BUF_FLAG_ERROR 0x00000040 /* timecode field is valid */ #define V4L2_BUF_FLAG_TIMECODE 0x00000100 /* Buffer is prepared for queuing */ #define V4L2_BUF_FLAG_PREPARED 0x00000400 /* Cache handling flags */ #define V4L2_BUF_FLAG_NO_CACHE_INVALIDATE 0x00000800 #define V4L2_BUF_FLAG_NO_CACHE_CLEAN 0x00001000 /* Timestamp type */ #define V4L2_BUF_FLAG_TIMESTAMP_MASK 0x0000e000 #define V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN 0x00000000 #define V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC 0x00002000 #define V4L2_BUF_FLAG_TIMESTAMP_COPY 0x00004000 /* Timestamp sources. */ #define V4L2_BUF_FLAG_TSTAMP_SRC_MASK 0x00070000 #define V4L2_BUF_FLAG_TSTAMP_SRC_EOF 0x00000000 #define V4L2_BUF_FLAG_TSTAMP_SRC_SOE 0x00010000 /* mem2mem encoder/decoder */ #define V4L2_BUF_FLAG_LAST 0x00100000 /** * struct v4l2_exportbuffer - export of video buffer as DMABUF file descriptor * * @index: id number of the buffer * @type: enum v4l2_buf_type; buffer type (type == *_MPLANE for * multiplanar buffers); * @plane: index of the plane to be exported, 0 for single plane queues * @flags: flags for newly created file, currently only O_CLOEXEC is * supported, refer to manual of open syscall for more details * @fd: file descriptor associated with DMABUF (set by driver) * * Contains data used for exporting a video buffer as DMABUF file descriptor. * The buffer is identified by a 'cookie' returned by VIDIOC_QUERYBUF * (identical to the cookie used to mmap() the buffer to userspace). All * reserved fields must be set to zero. The field reserved0 is expected to * become a structure 'type' allowing an alternative layout of the structure * content. Therefore this field should not be used for any other extensions. */ struct v4l2_exportbuffer { __u32 type; /* enum v4l2_buf_type */ __u32 index; __u32 plane; __u32 flags; __s32 fd; __u32 reserved[11]; }; /* * O V E R L A Y P R E V I E W */ struct v4l2_framebuffer { __u32 capability; __u32 flags; /* FIXME: in theory we should pass something like PCI device + memory * region + offset instead of some physical address */ void *base; struct { __u32 width; __u32 height; __u32 pixelformat; __u32 field; /* enum v4l2_field */ __u32 bytesperline; /* for padding, zero if unused */ __u32 sizeimage; __u32 colorspace; /* enum v4l2_colorspace */ __u32 priv; /* reserved field, set to 0 */ } fmt; }; /* Flags for the 'capability' field. Read only */ #define V4L2_FBUF_CAP_EXTERNOVERLAY 0x0001 #define V4L2_FBUF_CAP_CHROMAKEY 0x0002 #define V4L2_FBUF_CAP_LIST_CLIPPING 0x0004 #define V4L2_FBUF_CAP_BITMAP_CLIPPING 0x0008 #define V4L2_FBUF_CAP_LOCAL_ALPHA 0x0010 #define V4L2_FBUF_CAP_GLOBAL_ALPHA 0x0020 #define V4L2_FBUF_CAP_LOCAL_INV_ALPHA 0x0040 #define V4L2_FBUF_CAP_SRC_CHROMAKEY 0x0080 /* Flags for the 'flags' field. */ #define V4L2_FBUF_FLAG_PRIMARY 0x0001 #define V4L2_FBUF_FLAG_OVERLAY 0x0002 #define V4L2_FBUF_FLAG_CHROMAKEY 0x0004 #define V4L2_FBUF_FLAG_LOCAL_ALPHA 0x0008 #define V4L2_FBUF_FLAG_GLOBAL_ALPHA 0x0010 #define V4L2_FBUF_FLAG_LOCAL_INV_ALPHA 0x0020 #define V4L2_FBUF_FLAG_SRC_CHROMAKEY 0x0040 struct v4l2_clip { struct v4l2_rect c; struct v4l2_clip *next; }; struct v4l2_window { struct v4l2_rect w; __u32 field; /* enum v4l2_field */ __u32 chromakey; struct v4l2_clip *clips; __u32 clipcount; void *bitmap; __u8 global_alpha; }; /* * C A P T U R E P A R A M E T E R S */ struct v4l2_captureparm { __u32 capability; /* Supported modes */ __u32 capturemode; /* Current mode */ struct v4l2_fract timeperframe; /* Time per frame in seconds */ __u32 extendedmode; /* Driver-specific extensions */ __u32 readbuffers; /* # of buffers for read */ __u32 reserved[4]; }; /* Flags for 'capability' and 'capturemode' fields */ #define V4L2_MODE_HIGHQUALITY 0x0001 /* High quality imaging mode */ #define V4L2_CAP_TIMEPERFRAME 0x1000 /* timeperframe field is supported */ struct v4l2_outputparm { __u32 capability; /* Supported modes */ __u32 outputmode; /* Current mode */ struct v4l2_fract timeperframe; /* Time per frame in seconds */ __u32 extendedmode; /* Driver-specific extensions */ __u32 writebuffers; /* # of buffers for write */ __u32 reserved[4]; }; /* * I N P U T I M A G E C R O P P I N G */ struct v4l2_cropcap { __u32 type; /* enum v4l2_buf_type */ struct v4l2_rect bounds; struct v4l2_rect defrect; struct v4l2_fract pixelaspect; }; struct v4l2_crop { __u32 type; /* enum v4l2_buf_type */ struct v4l2_rect c; }; /** * struct v4l2_selection - selection info * @type: buffer type (do not use *_MPLANE types) * @target: Selection target, used to choose one of possible rectangles; * defined in v4l2-common.h; V4L2_SEL_TGT_* . * @flags: constraints flags, defined in v4l2-common.h; V4L2_SEL_FLAG_*. * @r: coordinates of selection window * @reserved: for future use, rounds structure size to 64 bytes, set to zero * * Hardware may use multiple helper windows to process a video stream. * The structure is used to exchange this selection areas between * an application and a driver. */ struct v4l2_selection { __u32 type; __u32 target; __u32 flags; struct v4l2_rect r; __u32 reserved[9]; }; /* * A N A L O G V I D E O S T A N D A R D */ typedef __u64 v4l2_std_id; /* one bit for each */ #define V4L2_STD_PAL_B ((v4l2_std_id)0x00000001) #define V4L2_STD_PAL_B1 ((v4l2_std_id)0x00000002) #define V4L2_STD_PAL_G ((v4l2_std_id)0x00000004) #define V4L2_STD_PAL_H ((v4l2_std_id)0x00000008) #define V4L2_STD_PAL_I ((v4l2_std_id)0x00000010) #define V4L2_STD_PAL_D ((v4l2_std_id)0x00000020) #define V4L2_STD_PAL_D1 ((v4l2_std_id)0x00000040) #define V4L2_STD_PAL_K ((v4l2_std_id)0x00000080) #define V4L2_STD_PAL_M ((v4l2_std_id)0x00000100) #define V4L2_STD_PAL_N ((v4l2_std_id)0x00000200) #define V4L2_STD_PAL_Nc ((v4l2_std_id)0x00000400) #define V4L2_STD_PAL_60 ((v4l2_std_id)0x00000800) #define V4L2_STD_NTSC_M ((v4l2_std_id)0x00001000) /* BTSC */ #define V4L2_STD_NTSC_M_JP ((v4l2_std_id)0x00002000) /* EIA-J */ #define V4L2_STD_NTSC_443 ((v4l2_std_id)0x00004000) #define V4L2_STD_NTSC_M_KR ((v4l2_std_id)0x00008000) /* FM A2 */ #define V4L2_STD_SECAM_B ((v4l2_std_id)0x00010000) #define V4L2_STD_SECAM_D ((v4l2_std_id)0x00020000) #define V4L2_STD_SECAM_G ((v4l2_std_id)0x00040000) #define V4L2_STD_SECAM_H ((v4l2_std_id)0x00080000) #define V4L2_STD_SECAM_K ((v4l2_std_id)0x00100000) #define V4L2_STD_SECAM_K1 ((v4l2_std_id)0x00200000) #define V4L2_STD_SECAM_L ((v4l2_std_id)0x00400000) #define V4L2_STD_SECAM_LC ((v4l2_std_id)0x00800000) /* ATSC/HDTV */ #define V4L2_STD_ATSC_8_VSB ((v4l2_std_id)0x01000000) #define V4L2_STD_ATSC_16_VSB ((v4l2_std_id)0x02000000) /* FIXME: Although std_id is 64 bits, there is an issue on PPC32 architecture that makes switch(__u64) to break. So, there's a hack on v4l2-common.c rounding this value to 32 bits. As, currently, the max value is for V4L2_STD_ATSC_16_VSB (30 bits wide), it should work fine. However, if needed to add more than two standards, v4l2-common.c should be fixed. */ /* * Some macros to merge video standards in order to make live easier for the * drivers and V4L2 applications */ /* * "Common" NTSC/M - It should be noticed that V4L2_STD_NTSC_443 is * Missing here. */ #define V4L2_STD_NTSC (V4L2_STD_NTSC_M |\ V4L2_STD_NTSC_M_JP |\ V4L2_STD_NTSC_M_KR) /* Secam macros */ #define V4L2_STD_SECAM_DK (V4L2_STD_SECAM_D |\ V4L2_STD_SECAM_K |\ V4L2_STD_SECAM_K1) /* All Secam Standards */ #define V4L2_STD_SECAM (V4L2_STD_SECAM_B |\ V4L2_STD_SECAM_G |\ V4L2_STD_SECAM_H |\ V4L2_STD_SECAM_DK |\ V4L2_STD_SECAM_L |\ V4L2_STD_SECAM_LC) /* PAL macros */ #define V4L2_STD_PAL_BG (V4L2_STD_PAL_B |\ V4L2_STD_PAL_B1 |\ V4L2_STD_PAL_G) #define V4L2_STD_PAL_DK (V4L2_STD_PAL_D |\ V4L2_STD_PAL_D1 |\ V4L2_STD_PAL_K) /* * "Common" PAL - This macro is there to be compatible with the old * V4L1 concept of "PAL": /BGDKHI. * Several PAL standards are missing here: /M, /N and /Nc */ #define V4L2_STD_PAL (V4L2_STD_PAL_BG |\ V4L2_STD_PAL_DK |\ V4L2_STD_PAL_H |\ V4L2_STD_PAL_I) /* Chroma "agnostic" standards */ #define V4L2_STD_B (V4L2_STD_PAL_B |\ V4L2_STD_PAL_B1 |\ V4L2_STD_SECAM_B) #define V4L2_STD_G (V4L2_STD_PAL_G |\ V4L2_STD_SECAM_G) #define V4L2_STD_H (V4L2_STD_PAL_H |\ V4L2_STD_SECAM_H) #define V4L2_STD_L (V4L2_STD_SECAM_L |\ V4L2_STD_SECAM_LC) #define V4L2_STD_GH (V4L2_STD_G |\ V4L2_STD_H) #define V4L2_STD_DK (V4L2_STD_PAL_DK |\ V4L2_STD_SECAM_DK) #define V4L2_STD_BG (V4L2_STD_B |\ V4L2_STD_G) #define V4L2_STD_MN (V4L2_STD_PAL_M |\ V4L2_STD_PAL_N |\ V4L2_STD_PAL_Nc |\ V4L2_STD_NTSC) /* Standards where MTS/BTSC stereo could be found */ #define V4L2_STD_MTS (V4L2_STD_NTSC_M |\ V4L2_STD_PAL_M |\ V4L2_STD_PAL_N |\ V4L2_STD_PAL_Nc) /* Standards for Countries with 60Hz Line frequency */ #define V4L2_STD_525_60 (V4L2_STD_PAL_M |\ V4L2_STD_PAL_60 |\ V4L2_STD_NTSC |\ V4L2_STD_NTSC_443) /* Standards for Countries with 50Hz Line frequency */ #define V4L2_STD_625_50 (V4L2_STD_PAL |\ V4L2_STD_PAL_N |\ V4L2_STD_PAL_Nc |\ V4L2_STD_SECAM) #define V4L2_STD_ATSC (V4L2_STD_ATSC_8_VSB |\ V4L2_STD_ATSC_16_VSB) /* Macros with none and all analog standards */ #define V4L2_STD_UNKNOWN 0 #define V4L2_STD_ALL (V4L2_STD_525_60 |\ V4L2_STD_625_50) struct v4l2_standard { __u32 index; v4l2_std_id id; __u8 name[24]; struct v4l2_fract frameperiod; /* Frames, not fields */ __u32 framelines; __u32 reserved[4]; }; /* * D V B T T I M I N G S */ /** struct v4l2_bt_timings - BT.656/BT.1120 timing data * @width: total width of the active video in pixels * @height: total height of the active video in lines * @interlaced: Interlaced or progressive * @polarities: Positive or negative polarities * @pixelclock: Pixel clock in HZ. Ex. 74.25MHz->74250000 * @hfrontporch:Horizontal front porch in pixels * @hsync: Horizontal Sync length in pixels * @hbackporch: Horizontal back porch in pixels * @vfrontporch:Vertical front porch in lines * @vsync: Vertical Sync length in lines * @vbackporch: Vertical back porch in lines * @il_vfrontporch:Vertical front porch for the even field * (aka field 2) of interlaced field formats * @il_vsync: Vertical Sync length for the even field * (aka field 2) of interlaced field formats * @il_vbackporch:Vertical back porch for the even field * (aka field 2) of interlaced field formats * @standards: Standards the timing belongs to * @flags: Flags * @picture_aspect: The picture aspect ratio (hor/vert). * @cea861_vic: VIC code as per the CEA-861 standard. * @hdmi_vic: VIC code as per the HDMI standard. * @reserved: Reserved fields, must be zeroed. * * A note regarding vertical interlaced timings: height refers to the total * height of the active video frame (= two fields). The blanking timings refer * to the blanking of each field. So the height of the total frame is * calculated as follows: * * tot_height = height + vfrontporch + vsync + vbackporch + * il_vfrontporch + il_vsync + il_vbackporch * * The active height of each field is height / 2. */ struct v4l2_bt_timings { __u32 width; __u32 height; __u32 interlaced; __u32 polarities; __u64 pixelclock; __u32 hfrontporch; __u32 hsync; __u32 hbackporch; __u32 vfrontporch; __u32 vsync; __u32 vbackporch; __u32 il_vfrontporch; __u32 il_vsync; __u32 il_vbackporch; __u32 standards; __u32 flags; struct v4l2_fract picture_aspect; __u8 cea861_vic; __u8 hdmi_vic; __u8 reserved[46]; } __attribute__ ((packed)); /* Interlaced or progressive format */ #define V4L2_DV_PROGRESSIVE 0 #define V4L2_DV_INTERLACED 1 /* Polarities. If bit is not set, it is assumed to be negative polarity */ #define V4L2_DV_VSYNC_POS_POL 0x00000001 #define V4L2_DV_HSYNC_POS_POL 0x00000002 /* Timings standards */ #define V4L2_DV_BT_STD_CEA861 (1 << 0) /* CEA-861 Digital TV Profile */ #define V4L2_DV_BT_STD_DMT (1 << 1) /* VESA Discrete Monitor Timings */ #define V4L2_DV_BT_STD_CVT (1 << 2) /* VESA Coordinated Video Timings */ #define V4L2_DV_BT_STD_GTF (1 << 3) /* VESA Generalized Timings Formula */ #define V4L2_DV_BT_STD_SDI (1 << 4) /* SDI Timings */ /* Flags */ /* * CVT/GTF specific: timing uses reduced blanking (CVT) or the 'Secondary * GTF' curve (GTF). In both cases the horizontal and/or vertical blanking * intervals are reduced, allowing a higher resolution over the same * bandwidth. This is a read-only flag. */ #define V4L2_DV_FL_REDUCED_BLANKING (1 << 0) /* * CEA-861 specific: set for CEA-861 formats with a framerate of a multiple * of six. These formats can be optionally played at 1 / 1.001 speed. * This is a read-only flag. */ #define V4L2_DV_FL_CAN_REDUCE_FPS (1 << 1) /* * CEA-861 specific: only valid for video transmitters, the flag is cleared * by receivers. * If the framerate of the format is a multiple of six, then the pixelclock * used to set up the transmitter is divided by 1.001 to make it compatible * with 60 Hz based standards such as NTSC and PAL-M that use a framerate of * 29.97 Hz. Otherwise this flag is cleared. If the transmitter can't generate * such frequencies, then the flag will also be cleared. */ #define V4L2_DV_FL_REDUCED_FPS (1 << 2) /* * Specific to interlaced formats: if set, then field 1 is really one half-line * longer and field 2 is really one half-line shorter, so each field has * exactly the same number of half-lines. Whether half-lines can be detected * or used depends on the hardware. */ #define V4L2_DV_FL_HALF_LINE (1 << 3) /* * If set, then this is a Consumer Electronics (CE) video format. Such formats * differ from other formats (commonly called IT formats) in that if RGB * encoding is used then by default the RGB values use limited range (i.e. * use the range 16-235) as opposed to 0-255. All formats defined in CEA-861 * except for the 640x480 format are CE formats. */ #define V4L2_DV_FL_IS_CE_VIDEO (1 << 4) /* Some formats like SMPTE-125M have an interlaced signal with a odd * total height. For these formats, if this flag is set, the first * field has the extra line. If not, it is the second field. */ #define V4L2_DV_FL_FIRST_FIELD_EXTRA_LINE (1 << 5) /* * If set, then the picture_aspect field is valid. Otherwise assume that the * pixels are square, so the picture aspect ratio is the same as the width to * height ratio. */ #define V4L2_DV_FL_HAS_PICTURE_ASPECT (1 << 6) /* * If set, then the cea861_vic field is valid and contains the Video * Identification Code as per the CEA-861 standard. */ #define V4L2_DV_FL_HAS_CEA861_VIC (1 << 7) /* * If set, then the hdmi_vic field is valid and contains the Video * Identification Code as per the HDMI standard (HDMI Vendor Specific * InfoFrame). */ #define V4L2_DV_FL_HAS_HDMI_VIC (1 << 8) /* * CEA-861 specific: only valid for video receivers. * If set, then HW can detect the difference between regular FPS and * 1000/1001 FPS. Note: This flag is only valid for HDMI VIC codes with * the V4L2_DV_FL_CAN_REDUCE_FPS flag set. */ #define V4L2_DV_FL_CAN_DETECT_REDUCED_FPS (1 << 9) /* A few useful defines to calculate the total blanking and frame sizes */ #define V4L2_DV_BT_BLANKING_WIDTH(bt) \ ((bt)->hfrontporch + (bt)->hsync + (bt)->hbackporch) #define V4L2_DV_BT_FRAME_WIDTH(bt) \ ((bt)->width + V4L2_DV_BT_BLANKING_WIDTH(bt)) #define V4L2_DV_BT_BLANKING_HEIGHT(bt) \ ((bt)->vfrontporch + (bt)->vsync + (bt)->vbackporch + \ (bt)->il_vfrontporch + (bt)->il_vsync + (bt)->il_vbackporch) #define V4L2_DV_BT_FRAME_HEIGHT(bt) \ ((bt)->height + V4L2_DV_BT_BLANKING_HEIGHT(bt)) /** struct v4l2_dv_timings - DV timings * @type: the type of the timings * @bt: BT656/1120 timings */ struct v4l2_dv_timings { __u32 type; union { struct v4l2_bt_timings bt; __u32 reserved[32]; }; } __attribute__ ((packed)); /* Values for the type field */ #define V4L2_DV_BT_656_1120 0 /* BT.656/1120 timing type */ /** struct v4l2_enum_dv_timings - DV timings enumeration * @index: enumeration index * @pad: the pad number for which to enumerate timings (used with * v4l-subdev nodes only) * @reserved: must be zeroed * @timings: the timings for the given index */ struct v4l2_enum_dv_timings { __u32 index; __u32 pad; __u32 reserved[2]; struct v4l2_dv_timings timings; }; /** struct v4l2_bt_timings_cap - BT.656/BT.1120 timing capabilities * @min_width: width in pixels * @max_width: width in pixels * @min_height: height in lines * @max_height: height in lines * @min_pixelclock: Pixel clock in HZ. Ex. 74.25MHz->74250000 * @max_pixelclock: Pixel clock in HZ. Ex. 74.25MHz->74250000 * @standards: Supported standards * @capabilities: Supported capabilities * @reserved: Must be zeroed */ struct v4l2_bt_timings_cap { __u32 min_width; __u32 max_width; __u32 min_height; __u32 max_height; __u64 min_pixelclock; __u64 max_pixelclock; __u32 standards; __u32 capabilities; __u32 reserved[16]; } __attribute__ ((packed)); /* Supports interlaced formats */ #define V4L2_DV_BT_CAP_INTERLACED (1 << 0) /* Supports progressive formats */ #define V4L2_DV_BT_CAP_PROGRESSIVE (1 << 1) /* Supports CVT/GTF reduced blanking */ #define V4L2_DV_BT_CAP_REDUCED_BLANKING (1 << 2) /* Supports custom formats */ #define V4L2_DV_BT_CAP_CUSTOM (1 << 3) /** struct v4l2_dv_timings_cap - DV timings capabilities * @type: the type of the timings (same as in struct v4l2_dv_timings) * @pad: the pad number for which to query capabilities (used with * v4l-subdev nodes only) * @bt: the BT656/1120 timings capabilities */ struct v4l2_dv_timings_cap { __u32 type; __u32 pad; __u32 reserved[2]; union { struct v4l2_bt_timings_cap bt; __u32 raw_data[32]; }; }; /* * V I D E O I N P U T S */ struct v4l2_input { __u32 index; /* Which input */ __u8 name[32]; /* Label */ __u32 type; /* Type of input */ __u32 audioset; /* Associated audios (bitfield) */ __u32 tuner; /* enum v4l2_tuner_type */ v4l2_std_id std; __u32 status; __u32 capabilities; __u32 reserved[3]; }; /* Values for the 'type' field */ #define V4L2_INPUT_TYPE_TUNER 1 #define V4L2_INPUT_TYPE_CAMERA 2 #define V4L2_INPUT_TYPE_TOUCH 3 /* field 'status' - general */ #define V4L2_IN_ST_NO_POWER 0x00000001 /* Attached device is off */ #define V4L2_IN_ST_NO_SIGNAL 0x00000002 #define V4L2_IN_ST_NO_COLOR 0x00000004 /* field 'status' - sensor orientation */ /* If sensor is mounted upside down set both bits */ #define V4L2_IN_ST_HFLIP 0x00000010 /* Frames are flipped horizontally */ #define V4L2_IN_ST_VFLIP 0x00000020 /* Frames are flipped vertically */ /* field 'status' - analog */ #define V4L2_IN_ST_NO_H_LOCK 0x00000100 /* No horizontal sync lock */ #define V4L2_IN_ST_COLOR_KILL 0x00000200 /* Color killer is active */ #define V4L2_IN_ST_NO_V_LOCK 0x00000400 /* No vertical sync lock */ #define V4L2_IN_ST_NO_STD_LOCK 0x00000800 /* No standard format lock */ /* field 'status' - digital */ #define V4L2_IN_ST_NO_SYNC 0x00010000 /* No synchronization lock */ #define V4L2_IN_ST_NO_EQU 0x00020000 /* No equalizer lock */ #define V4L2_IN_ST_NO_CARRIER 0x00040000 /* Carrier recovery failed */ /* field 'status' - VCR and set-top box */ #define V4L2_IN_ST_MACROVISION 0x01000000 /* Macrovision detected */ #define V4L2_IN_ST_NO_ACCESS 0x02000000 /* Conditional access denied */ #define V4L2_IN_ST_VTR 0x04000000 /* VTR time constant */ /* capabilities flags */ #define V4L2_IN_CAP_DV_TIMINGS 0x00000002 /* Supports S_DV_TIMINGS */ #define V4L2_IN_CAP_CUSTOM_TIMINGS V4L2_IN_CAP_DV_TIMINGS /* For compatibility */ #define V4L2_IN_CAP_STD 0x00000004 /* Supports S_STD */ #define V4L2_IN_CAP_NATIVE_SIZE 0x00000008 /* Supports setting native size */ /* * V I D E O O U T P U T S */ struct v4l2_output { __u32 index; /* Which output */ __u8 name[32]; /* Label */ __u32 type; /* Type of output */ __u32 audioset; /* Associated audios (bitfield) */ __u32 modulator; /* Associated modulator */ v4l2_std_id std; __u32 capabilities; __u32 reserved[3]; }; /* Values for the 'type' field */ #define V4L2_OUTPUT_TYPE_MODULATOR 1 #define V4L2_OUTPUT_TYPE_ANALOG 2 #define V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY 3 /* capabilities flags */ #define V4L2_OUT_CAP_DV_TIMINGS 0x00000002 /* Supports S_DV_TIMINGS */ #define V4L2_OUT_CAP_CUSTOM_TIMINGS V4L2_OUT_CAP_DV_TIMINGS /* For compatibility */ #define V4L2_OUT_CAP_STD 0x00000004 /* Supports S_STD */ #define V4L2_OUT_CAP_NATIVE_SIZE 0x00000008 /* Supports setting native size */ /* * C O N T R O L S */ struct v4l2_control { __u32 id; __s32 value; }; struct v4l2_ext_control { __u32 id; __u32 size; __u32 reserved2[1]; union { __s32 value; __s64 value64; char *string; __u8 *p_u8; __u16 *p_u16; __u32 *p_u32; struct v4l2_ctrl_mpeg2_slice_params *p_mpeg2_slice_params; struct v4l2_ctrl_mpeg2_quantization *p_mpeg2_quantization; void *ptr; }; } __attribute__ ((packed)); struct v4l2_ext_controls { union { __u32 ctrl_class; __u32 which; }; __u32 count; __u32 error_idx; __s32 request_fd; __u32 reserved[1]; struct v4l2_ext_control *controls; }; #define V4L2_CTRL_ID_MASK (0x0fffffff) #define V4L2_CTRL_ID2CLASS(id) ((id) & 0x0fff0000UL) #define V4L2_CTRL_ID2WHICH(id) ((id) & 0x0fff0000UL) #define V4L2_CTRL_DRIVER_PRIV(id) (((id) & 0xffff) >= 0x1000) #define V4L2_CTRL_MAX_DIMS (4) #define V4L2_CTRL_WHICH_CUR_VAL 0 #define V4L2_CTRL_WHICH_DEF_VAL 0x0f000000 #define V4L2_CTRL_WHICH_REQUEST_VAL 0x0f010000 enum v4l2_ctrl_type { V4L2_CTRL_TYPE_INTEGER = 1, V4L2_CTRL_TYPE_BOOLEAN = 2, V4L2_CTRL_TYPE_MENU = 3, V4L2_CTRL_TYPE_BUTTON = 4, V4L2_CTRL_TYPE_INTEGER64 = 5, V4L2_CTRL_TYPE_CTRL_CLASS = 6, V4L2_CTRL_TYPE_STRING = 7, V4L2_CTRL_TYPE_BITMASK = 8, V4L2_CTRL_TYPE_INTEGER_MENU = 9, /* Compound types are >= 0x0100 */ V4L2_CTRL_COMPOUND_TYPES = 0x0100, V4L2_CTRL_TYPE_U8 = 0x0100, V4L2_CTRL_TYPE_U16 = 0x0101, V4L2_CTRL_TYPE_U32 = 0x0102, V4L2_CTRL_TYPE_MPEG2_SLICE_PARAMS = 0x0103, V4L2_CTRL_TYPE_MPEG2_QUANTIZATION = 0x0104, }; /* Used in the VIDIOC_QUERYCTRL ioctl for querying controls */ struct v4l2_queryctrl { __u32 id; __u32 type; /* enum v4l2_ctrl_type */ __u8 name[32]; /* Whatever */ __s32 minimum; /* Note signedness */ __s32 maximum; __s32 step; __s32 default_value; __u32 flags; __u32 reserved[2]; }; /* Used in the VIDIOC_QUERY_EXT_CTRL ioctl for querying extended controls */ struct v4l2_query_ext_ctrl { __u32 id; __u32 type; char name[32]; __s64 minimum; __s64 maximum; __u64 step; __s64 default_value; __u32 flags; __u32 elem_size; __u32 elems; __u32 nr_of_dims; __u32 dims[V4L2_CTRL_MAX_DIMS]; __u32 reserved[32]; }; /* Used in the VIDIOC_QUERYMENU ioctl for querying menu items */ struct v4l2_querymenu { __u32 id; __u32 index; union { __u8 name[32]; /* Whatever */ __s64 value; }; __u32 reserved; } __attribute__ ((packed)); /* Control flags */ #define V4L2_CTRL_FLAG_DISABLED 0x0001 #define V4L2_CTRL_FLAG_GRABBED 0x0002 #define V4L2_CTRL_FLAG_READ_ONLY 0x0004 #define V4L2_CTRL_FLAG_UPDATE 0x0008 #define V4L2_CTRL_FLAG_INACTIVE 0x0010 #define V4L2_CTRL_FLAG_SLIDER 0x0020 #define V4L2_CTRL_FLAG_WRITE_ONLY 0x0040 #define V4L2_CTRL_FLAG_VOLATILE 0x0080 #define V4L2_CTRL_FLAG_HAS_PAYLOAD 0x0100 #define V4L2_CTRL_FLAG_EXECUTE_ON_WRITE 0x0200 #define V4L2_CTRL_FLAG_MODIFY_LAYOUT 0x0400 /* Query flags, to be ORed with the control ID */ #define V4L2_CTRL_FLAG_NEXT_CTRL 0x80000000 #define V4L2_CTRL_FLAG_NEXT_COMPOUND 0x40000000 /* User-class control IDs defined by V4L2 */ #define V4L2_CID_MAX_CTRLS 1024 /* IDs reserved for driver specific controls */ #define V4L2_CID_PRIVATE_BASE 0x08000000 /* * T U N I N G */ struct v4l2_tuner { __u32 index; __u8 name[32]; __u32 type; /* enum v4l2_tuner_type */ __u32 capability; __u32 rangelow; __u32 rangehigh; __u32 rxsubchans; __u32 audmode; __s32 signal; __s32 afc; __u32 reserved[4]; }; struct v4l2_modulator { __u32 index; __u8 name[32]; __u32 capability; __u32 rangelow; __u32 rangehigh; __u32 txsubchans; __u32 type; /* enum v4l2_tuner_type */ __u32 reserved[3]; }; /* Flags for the 'capability' field */ #define V4L2_TUNER_CAP_LOW 0x0001 #define V4L2_TUNER_CAP_NORM 0x0002 #define V4L2_TUNER_CAP_HWSEEK_BOUNDED 0x0004 #define V4L2_TUNER_CAP_HWSEEK_WRAP 0x0008 #define V4L2_TUNER_CAP_STEREO 0x0010 #define V4L2_TUNER_CAP_LANG2 0x0020 #define V4L2_TUNER_CAP_SAP 0x0020 #define V4L2_TUNER_CAP_LANG1 0x0040 #define V4L2_TUNER_CAP_RDS 0x0080 #define V4L2_TUNER_CAP_RDS_BLOCK_IO 0x0100 #define V4L2_TUNER_CAP_RDS_CONTROLS 0x0200 #define V4L2_TUNER_CAP_FREQ_BANDS 0x0400 #define V4L2_TUNER_CAP_HWSEEK_PROG_LIM 0x0800 #define V4L2_TUNER_CAP_1HZ 0x1000 /* Flags for the 'rxsubchans' field */ #define V4L2_TUNER_SUB_MONO 0x0001 #define V4L2_TUNER_SUB_STEREO 0x0002 #define V4L2_TUNER_SUB_LANG2 0x0004 #define V4L2_TUNER_SUB_SAP 0x0004 #define V4L2_TUNER_SUB_LANG1 0x0008 #define V4L2_TUNER_SUB_RDS 0x0010 /* Values for the 'audmode' field */ #define V4L2_TUNER_MODE_MONO 0x0000 #define V4L2_TUNER_MODE_STEREO 0x0001 #define V4L2_TUNER_MODE_LANG2 0x0002 #define V4L2_TUNER_MODE_SAP 0x0002 #define V4L2_TUNER_MODE_LANG1 0x0003 #define V4L2_TUNER_MODE_LANG1_LANG2 0x0004 struct v4l2_frequency { __u32 tuner; __u32 type; /* enum v4l2_tuner_type */ __u32 frequency; __u32 reserved[8]; }; #define V4L2_BAND_MODULATION_VSB (1 << 1) #define V4L2_BAND_MODULATION_FM (1 << 2) #define V4L2_BAND_MODULATION_AM (1 << 3) struct v4l2_frequency_band { __u32 tuner; __u32 type; /* enum v4l2_tuner_type */ __u32 index; __u32 capability; __u32 rangelow; __u32 rangehigh; __u32 modulation; __u32 reserved[9]; }; struct v4l2_hw_freq_seek { __u32 tuner; __u32 type; /* enum v4l2_tuner_type */ __u32 seek_upward; __u32 wrap_around; __u32 spacing; __u32 rangelow; __u32 rangehigh; __u32 reserved[5]; }; /* * R D S */ struct v4l2_rds_data { __u8 lsb; __u8 msb; __u8 block; } __attribute__ ((packed)); #define V4L2_RDS_BLOCK_MSK 0x7 #define V4L2_RDS_BLOCK_A 0 #define V4L2_RDS_BLOCK_B 1 #define V4L2_RDS_BLOCK_C 2 #define V4L2_RDS_BLOCK_D 3 #define V4L2_RDS_BLOCK_C_ALT 4 #define V4L2_RDS_BLOCK_INVALID 7 #define V4L2_RDS_BLOCK_CORRECTED 0x40 #define V4L2_RDS_BLOCK_ERROR 0x80 /* * A U D I O */ struct v4l2_audio { __u32 index; __u8 name[32]; __u32 capability; __u32 mode; __u32 reserved[2]; }; /* Flags for the 'capability' field */ #define V4L2_AUDCAP_STEREO 0x00001 #define V4L2_AUDCAP_AVL 0x00002 /* Flags for the 'mode' field */ #define V4L2_AUDMODE_AVL 0x00001 struct v4l2_audioout { __u32 index; __u8 name[32]; __u32 capability; __u32 mode; __u32 reserved[2]; }; /* * M P E G S E R V I C E S */ #if 1 #define V4L2_ENC_IDX_FRAME_I (0) #define V4L2_ENC_IDX_FRAME_P (1) #define V4L2_ENC_IDX_FRAME_B (2) #define V4L2_ENC_IDX_FRAME_MASK (0xf) struct v4l2_enc_idx_entry { __u64 offset; __u64 pts; __u32 length; __u32 flags; __u32 reserved[2]; }; #define V4L2_ENC_IDX_ENTRIES (64) struct v4l2_enc_idx { __u32 entries; __u32 entries_cap; __u32 reserved[4]; struct v4l2_enc_idx_entry entry[V4L2_ENC_IDX_ENTRIES]; }; #define V4L2_ENC_CMD_START (0) #define V4L2_ENC_CMD_STOP (1) #define V4L2_ENC_CMD_PAUSE (2) #define V4L2_ENC_CMD_RESUME (3) /* Flags for V4L2_ENC_CMD_STOP */ #define V4L2_ENC_CMD_STOP_AT_GOP_END (1 << 0) struct v4l2_encoder_cmd { __u32 cmd; __u32 flags; union { struct { __u32 data[8]; } raw; }; }; /* Decoder commands */ #define V4L2_DEC_CMD_START (0) #define V4L2_DEC_CMD_STOP (1) #define V4L2_DEC_CMD_PAUSE (2) #define V4L2_DEC_CMD_RESUME (3) /* Flags for V4L2_DEC_CMD_START */ #define V4L2_DEC_CMD_START_MUTE_AUDIO (1 << 0) /* Flags for V4L2_DEC_CMD_PAUSE */ #define V4L2_DEC_CMD_PAUSE_TO_BLACK (1 << 0) /* Flags for V4L2_DEC_CMD_STOP */ #define V4L2_DEC_CMD_STOP_TO_BLACK (1 << 0) #define V4L2_DEC_CMD_STOP_IMMEDIATELY (1 << 1) /* Play format requirements (returned by the driver): */ /* The decoder has no special format requirements */ #define V4L2_DEC_START_FMT_NONE (0) /* The decoder requires full GOPs */ #define V4L2_DEC_START_FMT_GOP (1) /* The structure must be zeroed before use by the application This ensures it can be extended safely in the future. */ struct v4l2_decoder_cmd { __u32 cmd; __u32 flags; union { struct { __u64 pts; } stop; struct { /* 0 or 1000 specifies normal speed, 1 specifies forward single stepping, -1 specifies backward single stepping, >1: playback at speed/1000 of the normal speed, <-1: reverse playback at (-speed/1000) of the normal speed. */ __s32 speed; __u32 format; } start; struct { __u32 data[16]; } raw; }; }; #endif /* * D A T A S E R V I C E S ( V B I ) * * Data services API by Michael Schimek */ /* Raw VBI */ struct v4l2_vbi_format { __u32 sampling_rate; /* in 1 Hz */ __u32 offset; __u32 samples_per_line; __u32 sample_format; /* V4L2_PIX_FMT_* */ __s32 start[2]; __u32 count[2]; __u32 flags; /* V4L2_VBI_* */ __u32 reserved[2]; /* must be zero */ }; /* VBI flags */ #define V4L2_VBI_UNSYNC (1 << 0) #define V4L2_VBI_INTERLACED (1 << 1) /* ITU-R start lines for each field */ #define V4L2_VBI_ITU_525_F1_START (1) #define V4L2_VBI_ITU_525_F2_START (264) #define V4L2_VBI_ITU_625_F1_START (1) #define V4L2_VBI_ITU_625_F2_START (314) /* Sliced VBI * * This implements is a proposal V4L2 API to allow SLICED VBI * required for some hardware encoders. It should change without * notice in the definitive implementation. */ struct v4l2_sliced_vbi_format { __u16 service_set; /* service_lines[0][...] specifies lines 0-23 (1-23 used) of the first field service_lines[1][...] specifies lines 0-23 (1-23 used) of the second field (equals frame lines 313-336 for 625 line video standards, 263-286 for 525 line standards) */ __u16 service_lines[2][24]; __u32 io_size; __u32 reserved[2]; /* must be zero */ }; /* Teletext World System Teletext (WST), defined on ITU-R BT.653-2 */ #define V4L2_SLICED_TELETEXT_B (0x0001) /* Video Program System, defined on ETS 300 231*/ #define V4L2_SLICED_VPS (0x0400) /* Closed Caption, defined on EIA-608 */ #define V4L2_SLICED_CAPTION_525 (0x1000) /* Wide Screen System, defined on ITU-R BT1119.1 */ #define V4L2_SLICED_WSS_625 (0x4000) #define V4L2_SLICED_VBI_525 (V4L2_SLICED_CAPTION_525) #define V4L2_SLICED_VBI_625 (V4L2_SLICED_TELETEXT_B | V4L2_SLICED_VPS | V4L2_SLICED_WSS_625) struct v4l2_sliced_vbi_cap { __u16 service_set; /* service_lines[0][...] specifies lines 0-23 (1-23 used) of the first field service_lines[1][...] specifies lines 0-23 (1-23 used) of the second field (equals frame lines 313-336 for 625 line video standards, 263-286 for 525 line standards) */ __u16 service_lines[2][24]; __u32 type; /* enum v4l2_buf_type */ __u32 reserved[3]; /* must be 0 */ }; struct v4l2_sliced_vbi_data { __u32 id; __u32 field; /* 0: first field, 1: second field */ __u32 line; /* 1-23 */ __u32 reserved; /* must be 0 */ __u8 data[48]; }; /* * Sliced VBI data inserted into MPEG Streams */ /* * V4L2_MPEG_STREAM_VBI_FMT_IVTV: * * Structure of payload contained in an MPEG 2 Private Stream 1 PES Packet in an * MPEG-2 Program Pack that contains V4L2_MPEG_STREAM_VBI_FMT_IVTV Sliced VBI * data * * Note, the MPEG-2 Program Pack and Private Stream 1 PES packet header * definitions are not included here. See the MPEG-2 specifications for details * on these headers. */ /* Line type IDs */ #define V4L2_MPEG_VBI_IVTV_TELETEXT_B (1) #define V4L2_MPEG_VBI_IVTV_CAPTION_525 (4) #define V4L2_MPEG_VBI_IVTV_WSS_625 (5) #define V4L2_MPEG_VBI_IVTV_VPS (7) struct v4l2_mpeg_vbi_itv0_line { __u8 id; /* One of V4L2_MPEG_VBI_IVTV_* above */ __u8 data[42]; /* Sliced VBI data for the line */ } __attribute__ ((packed)); struct v4l2_mpeg_vbi_itv0 { __le32 linemask[2]; /* Bitmasks of VBI service lines present */ struct v4l2_mpeg_vbi_itv0_line line[35]; } __attribute__ ((packed)); struct v4l2_mpeg_vbi_ITV0 { struct v4l2_mpeg_vbi_itv0_line line[36]; } __attribute__ ((packed)); #define V4L2_MPEG_VBI_IVTV_MAGIC0 "itv0" #define V4L2_MPEG_VBI_IVTV_MAGIC1 "ITV0" struct v4l2_mpeg_vbi_fmt_ivtv { __u8 magic[4]; union { struct v4l2_mpeg_vbi_itv0 itv0; struct v4l2_mpeg_vbi_ITV0 ITV0; }; } __attribute__ ((packed)); /* * A G G R E G A T E S T R U C T U R E S */ /** * struct v4l2_plane_pix_format - additional, per-plane format definition * @sizeimage: maximum size in bytes required for data, for which * this plane will be used * @bytesperline: distance in bytes between the leftmost pixels in two * adjacent lines */ struct v4l2_plane_pix_format { __u32 sizeimage; __u32 bytesperline; __u16 reserved[6]; } __attribute__ ((packed)); /** * struct v4l2_pix_format_mplane - multiplanar format definition * @width: image width in pixels * @height: image height in pixels * @pixelformat: little endian four character code (fourcc) * @field: enum v4l2_field; field order (for interlaced video) * @colorspace: enum v4l2_colorspace; supplemental to pixelformat * @plane_fmt: per-plane information * @num_planes: number of planes for this format * @flags: format flags (V4L2_PIX_FMT_FLAG_*) * @ycbcr_enc: enum v4l2_ycbcr_encoding, Y'CbCr encoding * @quantization: enum v4l2_quantization, colorspace quantization * @xfer_func: enum v4l2_xfer_func, colorspace transfer function */ struct v4l2_pix_format_mplane { __u32 width; __u32 height; __u32 pixelformat; __u32 field; __u32 colorspace; struct v4l2_plane_pix_format plane_fmt[VIDEO_MAX_PLANES]; __u8 num_planes; __u8 flags; union { __u8 ycbcr_enc; __u8 hsv_enc; }; __u8 quantization; __u8 xfer_func; __u8 reserved[7]; } __attribute__ ((packed)); /** * struct v4l2_sdr_format - SDR format definition * @pixelformat: little endian four character code (fourcc) * @buffersize: maximum size in bytes required for data */ struct v4l2_sdr_format { __u32 pixelformat; __u32 buffersize; __u8 reserved[24]; } __attribute__ ((packed)); /** * struct v4l2_meta_format - metadata format definition * @dataformat: little endian four character code (fourcc) * @buffersize: maximum size in bytes required for data */ struct v4l2_meta_format { __u32 dataformat; __u32 buffersize; } __attribute__ ((packed)); /** * struct v4l2_format - stream data format * @type: enum v4l2_buf_type; type of the data stream * @pix: definition of an image format * @pix_mp: definition of a multiplanar image format * @win: definition of an overlaid image * @vbi: raw VBI capture or output parameters * @sliced: sliced VBI capture or output parameters * @raw_data: placeholder for future extensions and custom formats */ struct v4l2_format { __u32 type; union { struct v4l2_pix_format pix; /* V4L2_BUF_TYPE_VIDEO_CAPTURE */ struct v4l2_pix_format_mplane pix_mp; /* V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE */ struct v4l2_window win; /* V4L2_BUF_TYPE_VIDEO_OVERLAY */ struct v4l2_vbi_format vbi; /* V4L2_BUF_TYPE_VBI_CAPTURE */ struct v4l2_sliced_vbi_format sliced; /* V4L2_BUF_TYPE_SLICED_VBI_CAPTURE */ struct v4l2_sdr_format sdr; /* V4L2_BUF_TYPE_SDR_CAPTURE */ struct v4l2_meta_format meta; /* V4L2_BUF_TYPE_META_CAPTURE */ __u8 raw_data[200]; /* user-defined */ } fmt; }; /* Stream type-dependent parameters */ struct v4l2_streamparm { __u32 type; /* enum v4l2_buf_type */ union { struct v4l2_captureparm capture; struct v4l2_outputparm output; __u8 raw_data[200]; /* user-defined */ } parm; }; /* * E V E N T S */ #define V4L2_EVENT_ALL 0 #define V4L2_EVENT_VSYNC 1 #define V4L2_EVENT_EOS 2 #define V4L2_EVENT_CTRL 3 #define V4L2_EVENT_FRAME_SYNC 4 #define V4L2_EVENT_SOURCE_CHANGE 5 #define V4L2_EVENT_MOTION_DET 6 #define V4L2_EVENT_PRIVATE_START 0x08000000 /* Payload for V4L2_EVENT_VSYNC */ struct v4l2_event_vsync { /* Can be V4L2_FIELD_ANY, _NONE, _TOP or _BOTTOM */ __u8 field; } __attribute__ ((packed)); /* Payload for V4L2_EVENT_CTRL */ #define V4L2_EVENT_CTRL_CH_VALUE (1 << 0) #define V4L2_EVENT_CTRL_CH_FLAGS (1 << 1) #define V4L2_EVENT_CTRL_CH_RANGE (1 << 2) struct v4l2_event_ctrl { __u32 changes; __u32 type; union { __s32 value; __s64 value64; }; __u32 flags; __s32 minimum; __s32 maximum; __s32 step; __s32 default_value; }; struct v4l2_event_frame_sync { __u32 frame_sequence; }; #define V4L2_EVENT_SRC_CH_RESOLUTION (1 << 0) struct v4l2_event_src_change { __u32 changes; }; #define V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ (1 << 0) /** * struct v4l2_event_motion_det - motion detection event * @flags: if V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ is set, then the * frame_sequence field is valid. * @frame_sequence: the frame sequence number associated with this event. * @region_mask: which regions detected motion. */ struct v4l2_event_motion_det { __u32 flags; __u32 frame_sequence; __u32 region_mask; }; struct v4l2_event { __u32 type; union { struct v4l2_event_vsync vsync; struct v4l2_event_ctrl ctrl; struct v4l2_event_frame_sync frame_sync; struct v4l2_event_src_change src_change; struct v4l2_event_motion_det motion_det; __u8 data[64]; } u; __u32 pending; __u32 sequence; struct timespec timestamp; __u32 id; __u32 reserved[8]; }; #define V4L2_EVENT_SUB_FL_SEND_INITIAL (1 << 0) #define V4L2_EVENT_SUB_FL_ALLOW_FEEDBACK (1 << 1) struct v4l2_event_subscription { __u32 type; __u32 id; __u32 flags; __u32 reserved[5]; }; /* * A D V A N C E D D E B U G G I N G * * NOTE: EXPERIMENTAL API, NEVER RELY ON THIS IN APPLICATIONS! * FOR DEBUGGING, TESTING AND INTERNAL USE ONLY! */ /* VIDIOC_DBG_G_REGISTER and VIDIOC_DBG_S_REGISTER */ #define V4L2_CHIP_MATCH_BRIDGE 0 /* Match against chip ID on the bridge (0 for the bridge) */ #define V4L2_CHIP_MATCH_SUBDEV 4 /* Match against subdev index */ /* The following four defines are no longer in use */ #define V4L2_CHIP_MATCH_HOST V4L2_CHIP_MATCH_BRIDGE #define V4L2_CHIP_MATCH_I2C_DRIVER 1 /* Match against I2C driver name */ #define V4L2_CHIP_MATCH_I2C_ADDR 2 /* Match against I2C 7-bit address */ #define V4L2_CHIP_MATCH_AC97 3 /* Match against ancillary AC97 chip */ struct v4l2_dbg_match { __u32 type; /* Match type */ union { /* Match this chip, meaning determined by type */ __u32 addr; char name[32]; }; } __attribute__ ((packed)); struct v4l2_dbg_register { struct v4l2_dbg_match match; __u32 size; /* register size in bytes */ __u64 reg; __u64 val; } __attribute__ ((packed)); #define V4L2_CHIP_FL_READABLE (1 << 0) #define V4L2_CHIP_FL_WRITABLE (1 << 1) /* VIDIOC_DBG_G_CHIP_INFO */ struct v4l2_dbg_chip_info { struct v4l2_dbg_match match; char name[32]; __u32 flags; __u32 reserved[32]; } __attribute__ ((packed)); /** * struct v4l2_create_buffers - VIDIOC_CREATE_BUFS argument * @index: on return, index of the first created buffer * @count: entry: number of requested buffers, * return: number of created buffers * @memory: enum v4l2_memory; buffer memory type * @format: frame format, for which buffers are requested * @capabilities: capabilities of this buffer type. * @reserved: future extensions */ struct v4l2_create_buffers { __u32 index; __u32 count; __u32 memory; struct v4l2_format format; __u32 capabilities; __u32 reserved[7]; }; /* * I O C T L C O D E S F O R V I D E O D E V I C E S * */ #define VIDIOC_QUERYCAP _IOR('V', 0, struct v4l2_capability) #define VIDIOC_ENUM_FMT _IOWR('V', 2, struct v4l2_fmtdesc) #define VIDIOC_G_FMT _IOWR('V', 4, struct v4l2_format) #define VIDIOC_S_FMT _IOWR('V', 5, struct v4l2_format) #define VIDIOC_REQBUFS _IOWR('V', 8, struct v4l2_requestbuffers) #define VIDIOC_QUERYBUF _IOWR('V', 9, struct v4l2_buffer) #define VIDIOC_G_FBUF _IOR('V', 10, struct v4l2_framebuffer) #define VIDIOC_S_FBUF _IOW('V', 11, struct v4l2_framebuffer) #define VIDIOC_OVERLAY _IOW('V', 14, int) #define VIDIOC_QBUF _IOWR('V', 15, struct v4l2_buffer) #define VIDIOC_EXPBUF _IOWR('V', 16, struct v4l2_exportbuffer) #define VIDIOC_DQBUF _IOWR('V', 17, struct v4l2_buffer) #define VIDIOC_STREAMON _IOW('V', 18, int) #define VIDIOC_STREAMOFF _IOW('V', 19, int) #define VIDIOC_G_PARM _IOWR('V', 21, struct v4l2_streamparm) #define VIDIOC_S_PARM _IOWR('V', 22, struct v4l2_streamparm) #define VIDIOC_G_STD _IOR('V', 23, v4l2_std_id) #define VIDIOC_S_STD _IOW('V', 24, v4l2_std_id) #define VIDIOC_ENUMSTD _IOWR('V', 25, struct v4l2_standard) #define VIDIOC_ENUMINPUT _IOWR('V', 26, struct v4l2_input) #define VIDIOC_G_CTRL _IOWR('V', 27, struct v4l2_control) #define VIDIOC_S_CTRL _IOWR('V', 28, struct v4l2_control) #define VIDIOC_G_TUNER _IOWR('V', 29, struct v4l2_tuner) #define VIDIOC_S_TUNER _IOW('V', 30, struct v4l2_tuner) #define VIDIOC_G_AUDIO _IOR('V', 33, struct v4l2_audio) #define VIDIOC_S_AUDIO _IOW('V', 34, struct v4l2_audio) #define VIDIOC_QUERYCTRL _IOWR('V', 36, struct v4l2_queryctrl) #define VIDIOC_QUERYMENU _IOWR('V', 37, struct v4l2_querymenu) #define VIDIOC_G_INPUT _IOR('V', 38, int) #define VIDIOC_S_INPUT _IOWR('V', 39, int) #define VIDIOC_G_EDID _IOWR('V', 40, struct v4l2_edid) #define VIDIOC_S_EDID _IOWR('V', 41, struct v4l2_edid) #define VIDIOC_G_OUTPUT _IOR('V', 46, int) #define VIDIOC_S_OUTPUT _IOWR('V', 47, int) #define VIDIOC_ENUMOUTPUT _IOWR('V', 48, struct v4l2_output) #define VIDIOC_G_AUDOUT _IOR('V', 49, struct v4l2_audioout) #define VIDIOC_S_AUDOUT _IOW('V', 50, struct v4l2_audioout) #define VIDIOC_G_MODULATOR _IOWR('V', 54, struct v4l2_modulator) #define VIDIOC_S_MODULATOR _IOW('V', 55, struct v4l2_modulator) #define VIDIOC_G_FREQUENCY _IOWR('V', 56, struct v4l2_frequency) #define VIDIOC_S_FREQUENCY _IOW('V', 57, struct v4l2_frequency) #define VIDIOC_CROPCAP _IOWR('V', 58, struct v4l2_cropcap) #define VIDIOC_G_CROP _IOWR('V', 59, struct v4l2_crop) #define VIDIOC_S_CROP _IOW('V', 60, struct v4l2_crop) #define VIDIOC_G_JPEGCOMP _IOR('V', 61, struct v4l2_jpegcompression) #define VIDIOC_S_JPEGCOMP _IOW('V', 62, struct v4l2_jpegcompression) #define VIDIOC_QUERYSTD _IOR('V', 63, v4l2_std_id) #define VIDIOC_TRY_FMT _IOWR('V', 64, struct v4l2_format) #define VIDIOC_ENUMAUDIO _IOWR('V', 65, struct v4l2_audio) #define VIDIOC_ENUMAUDOUT _IOWR('V', 66, struct v4l2_audioout) #define VIDIOC_G_PRIORITY _IOR('V', 67, __u32) /* enum v4l2_priority */ #define VIDIOC_S_PRIORITY _IOW('V', 68, __u32) /* enum v4l2_priority */ #define VIDIOC_G_SLICED_VBI_CAP _IOWR('V', 69, struct v4l2_sliced_vbi_cap) #define VIDIOC_LOG_STATUS _IO('V', 70) #define VIDIOC_G_EXT_CTRLS _IOWR('V', 71, struct v4l2_ext_controls) #define VIDIOC_S_EXT_CTRLS _IOWR('V', 72, struct v4l2_ext_controls) #define VIDIOC_TRY_EXT_CTRLS _IOWR('V', 73, struct v4l2_ext_controls) #define VIDIOC_ENUM_FRAMESIZES _IOWR('V', 74, struct v4l2_frmsizeenum) #define VIDIOC_ENUM_FRAMEINTERVALS _IOWR('V', 75, struct v4l2_frmivalenum) #define VIDIOC_G_ENC_INDEX _IOR('V', 76, struct v4l2_enc_idx) #define VIDIOC_ENCODER_CMD _IOWR('V', 77, struct v4l2_encoder_cmd) #define VIDIOC_TRY_ENCODER_CMD _IOWR('V', 78, struct v4l2_encoder_cmd) /* * Experimental, meant for debugging, testing and internal use. * Only implemented if CONFIG_VIDEO_ADV_DEBUG is defined. * You must be root to use these ioctls. Never use these in applications! */ #define VIDIOC_DBG_S_REGISTER _IOW('V', 79, struct v4l2_dbg_register) #define VIDIOC_DBG_G_REGISTER _IOWR('V', 80, struct v4l2_dbg_register) #define VIDIOC_S_HW_FREQ_SEEK _IOW('V', 82, struct v4l2_hw_freq_seek) #define VIDIOC_S_DV_TIMINGS _IOWR('V', 87, struct v4l2_dv_timings) #define VIDIOC_G_DV_TIMINGS _IOWR('V', 88, struct v4l2_dv_timings) #define VIDIOC_DQEVENT _IOR('V', 89, struct v4l2_event) #define VIDIOC_SUBSCRIBE_EVENT _IOW('V', 90, struct v4l2_event_subscription) #define VIDIOC_UNSUBSCRIBE_EVENT _IOW('V', 91, struct v4l2_event_subscription) #define VIDIOC_CREATE_BUFS _IOWR('V', 92, struct v4l2_create_buffers) #define VIDIOC_PREPARE_BUF _IOWR('V', 93, struct v4l2_buffer) #define VIDIOC_G_SELECTION _IOWR('V', 94, struct v4l2_selection) #define VIDIOC_S_SELECTION _IOWR('V', 95, struct v4l2_selection) #define VIDIOC_DECODER_CMD _IOWR('V', 96, struct v4l2_decoder_cmd) #define VIDIOC_TRY_DECODER_CMD _IOWR('V', 97, struct v4l2_decoder_cmd) #define VIDIOC_ENUM_DV_TIMINGS _IOWR('V', 98, struct v4l2_enum_dv_timings) #define VIDIOC_QUERY_DV_TIMINGS _IOR('V', 99, struct v4l2_dv_timings) #define VIDIOC_DV_TIMINGS_CAP _IOWR('V', 100, struct v4l2_dv_timings_cap) #define VIDIOC_ENUM_FREQ_BANDS _IOWR('V', 101, struct v4l2_frequency_band) /* * Experimental, meant for debugging, testing and internal use. * Never use this in applications! */ #define VIDIOC_DBG_G_CHIP_INFO _IOWR('V', 102, struct v4l2_dbg_chip_info) #define VIDIOC_QUERY_EXT_CTRL _IOWR('V', 103, struct v4l2_query_ext_ctrl) /* Reminder: when adding new ioctls please add support for them to drivers/media/v4l2-core/v4l2-compat-ioctl32.c as well! */ #define BASE_VIDIOC_PRIVATE 192 /* 192-255 are private */ #endif /* __LINUX_VIDEODEV2_H */ linux/cm4000_cs.h000064400000003416151027430560007453 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _CM4000_H_ #define _CM4000_H_ #include #include #define MAX_ATR 33 #define CM4000_MAX_DEV 4 /* those two structures are passed via ioctl() from/to userspace. They are * used by existing userspace programs, so I kepth the awkward "bIFSD" naming * not to break compilation of userspace apps. -HW */ typedef struct atreq { __s32 atr_len; unsigned char atr[64]; __s32 power_act; unsigned char bIFSD; unsigned char bIFSC; } atreq_t; /* what is particularly stupid in the original driver is the arch-dependent * member sizes. This leads to CONFIG_COMPAT breakage, since 32bit userspace * will lay out the structure members differently than the 64bit kernel. * * I've changed "ptsreq.protocol" from "unsigned long" to "__u32". * On 32bit this will make no difference. With 64bit kernels, it will make * 32bit apps work, too. */ typedef struct ptsreq { __u32 protocol; /*T=0: 2^0, T=1: 2^1*/ unsigned char flags; unsigned char pts1; unsigned char pts2; unsigned char pts3; } ptsreq_t; #define CM_IOC_MAGIC 'c' #define CM_IOC_MAXNR 255 #define CM_IOCGSTATUS _IOR (CM_IOC_MAGIC, 0, unsigned char *) #define CM_IOCGATR _IOWR(CM_IOC_MAGIC, 1, atreq_t *) #define CM_IOCSPTS _IOW (CM_IOC_MAGIC, 2, ptsreq_t *) #define CM_IOCSRDR _IO (CM_IOC_MAGIC, 3) #define CM_IOCARDOFF _IO (CM_IOC_MAGIC, 4) #define CM_IOSDBGLVL _IOW(CM_IOC_MAGIC, 250, int*) /* card and device states */ #define CM_CARD_INSERTED 0x01 #define CM_CARD_POWERED 0x02 #define CM_ATR_PRESENT 0x04 #define CM_ATR_VALID 0x08 #define CM_STATE_VALID 0x0f /* extra info only from CM4000 */ #define CM_NO_READER 0x10 #define CM_BAD_CARD 0x20 #endif /* _CM4000_H_ */ linux/nexthop.h000064400000002776151027430560007560 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NEXTHOP_H #define _LINUX_NEXTHOP_H #include struct nhmsg { unsigned char nh_family; unsigned char nh_scope; /* return only */ unsigned char nh_protocol; /* Routing protocol that installed nh */ unsigned char resvd; unsigned int nh_flags; /* RTNH_F flags */ }; /* entry in a nexthop group */ struct nexthop_grp { __u32 id; /* nexthop id - must exist */ __u8 weight; /* weight of this nexthop */ __u8 resvd1; __u16 resvd2; }; enum { NEXTHOP_GRP_TYPE_MPATH, /* default type if not specified */ __NEXTHOP_GRP_TYPE_MAX, }; #define NEXTHOP_GRP_TYPE_MAX (__NEXTHOP_GRP_TYPE_MAX - 1) enum { NHA_UNSPEC, NHA_ID, /* u32; id for nexthop. id == 0 means auto-assign */ NHA_GROUP, /* array of nexthop_grp */ NHA_GROUP_TYPE, /* u16 one of NEXTHOP_GRP_TYPE */ /* if NHA_GROUP attribute is added, no other attributes can be set */ NHA_BLACKHOLE, /* flag; nexthop used to blackhole packets */ /* if NHA_BLACKHOLE is added, OIF, GATEWAY, ENCAP can not be set */ NHA_OIF, /* u32; nexthop device */ NHA_GATEWAY, /* be32 (IPv4) or in6_addr (IPv6) gw address */ NHA_ENCAP_TYPE, /* u16; lwt encap type */ NHA_ENCAP, /* lwt encap data */ /* NHA_OIF can be appended to dump request to return only * nexthops using given device */ NHA_GROUPS, /* flag; only return nexthop groups in dump */ NHA_MASTER, /* u32; only return nexthops with given master dev */ __NHA_MAX, }; #define NHA_MAX (__NHA_MAX - 1) #endif linux/if_ltalk.h000064400000000322151027430560007641 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_LTALK_H #define __LINUX_LTALK_H #define LTALK_HLEN 1 #define LTALK_MTU 600 #define LTALK_ALEN 1 #endif /* __LINUX_LTALK_H */ linux/virtio_bt.h000064400000001404151027430560010057 0ustar00/* SPDX-License-Identifier: BSD-3-Clause */ #ifndef _LINUX_VIRTIO_BT_H #define _LINUX_VIRTIO_BT_H #include /* Feature bits */ #define VIRTIO_BT_F_VND_HCI 0 /* Indicates vendor command support */ #define VIRTIO_BT_F_MSFT_EXT 1 /* Indicates MSFT vendor support */ #define VIRTIO_BT_F_AOSP_EXT 2 /* Indicates AOSP vendor support */ enum virtio_bt_config_type { VIRTIO_BT_CONFIG_TYPE_PRIMARY = 0, VIRTIO_BT_CONFIG_TYPE_AMP = 1, }; enum virtio_bt_config_vendor { VIRTIO_BT_CONFIG_VENDOR_NONE = 0, VIRTIO_BT_CONFIG_VENDOR_ZEPHYR = 1, VIRTIO_BT_CONFIG_VENDOR_INTEL = 2, VIRTIO_BT_CONFIG_VENDOR_REALTEK = 3, }; struct virtio_bt_config { __u8 type; __u16 vendor; __u16 msft_opcode; } __attribute__((packed)); #endif /* _LINUX_VIRTIO_BT_H */ linux/hysdn_if.h000064400000002546151027430560007671 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: hysdn_if.h,v 1.1.8.3 2001/09/23 22:25:05 kai Exp $ * * Linux driver for HYSDN cards * ioctl definitions shared by hynetmgr and driver. * * Author Werner Cornelius (werner@titro.de) for Hypercope GmbH * Copyright 1999 by Werner Cornelius (werner@titro.de) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ /****************/ /* error values */ /****************/ #define ERR_NONE 0 /* no error occurred */ #define ERR_ALREADY_BOOT 1000 /* we are already booting */ #define EPOF_BAD_MAGIC 1001 /* bad magic in POF header */ #define ERR_BOARD_DPRAM 1002 /* board DPRAM failed */ #define EPOF_INTERNAL 1003 /* internal POF handler error */ #define EPOF_BAD_IMG_SIZE 1004 /* POF boot image size invalid */ #define ERR_BOOTIMG_FAIL 1005 /* 1. stage boot image did not start */ #define ERR_BOOTSEQ_FAIL 1006 /* 2. stage boot seq handshake timeout */ #define ERR_POF_TIMEOUT 1007 /* timeout waiting for card pof ready */ #define ERR_NOT_BOOTED 1008 /* operation only allowed when booted */ #define ERR_CONF_LONG 1009 /* conf line is too long */ #define ERR_INV_CHAN 1010 /* invalid channel number */ #define ERR_ASYNC_TIME 1011 /* timeout sending async data */ linux/cramfs_fs.h000064400000006743151027430560010034 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __CRAMFS_H #define __CRAMFS_H #include #include #define CRAMFS_SIGNATURE "Compressed ROMFS" /* * Width of various bitfields in struct cramfs_inode. * Primarily used to generate warnings in mkcramfs. */ #define CRAMFS_MODE_WIDTH 16 #define CRAMFS_UID_WIDTH 16 #define CRAMFS_SIZE_WIDTH 24 #define CRAMFS_GID_WIDTH 8 #define CRAMFS_NAMELEN_WIDTH 6 #define CRAMFS_OFFSET_WIDTH 26 /* * Since inode.namelen is a unsigned 6-bit number, the maximum cramfs * path length is 63 << 2 = 252. */ #define CRAMFS_MAXPATHLEN (((1 << CRAMFS_NAMELEN_WIDTH) - 1) << 2) /* * Reasonably terse representation of the inode data. */ struct cramfs_inode { __u32 mode:CRAMFS_MODE_WIDTH, uid:CRAMFS_UID_WIDTH; /* SIZE for device files is i_rdev */ __u32 size:CRAMFS_SIZE_WIDTH, gid:CRAMFS_GID_WIDTH; /* NAMELEN is the length of the file name, divided by 4 and rounded up. (cramfs doesn't support hard links.) */ /* OFFSET: For symlinks and non-empty regular files, this contains the offset (divided by 4) of the file data in compressed form (starting with an array of block pointers; see README). For non-empty directories it is the offset (divided by 4) of the inode of the first file in that directory. For anything else, offset is zero. */ __u32 namelen:CRAMFS_NAMELEN_WIDTH, offset:CRAMFS_OFFSET_WIDTH; }; struct cramfs_info { __u32 crc; __u32 edition; __u32 blocks; __u32 files; }; /* * Superblock information at the beginning of the FS. */ struct cramfs_super { __u32 magic; /* 0x28cd3d45 - random number */ __u32 size; /* length in bytes */ __u32 flags; /* feature flags */ __u32 future; /* reserved for future use */ __u8 signature[16]; /* "Compressed ROMFS" */ struct cramfs_info fsid; /* unique filesystem info */ __u8 name[16]; /* user-defined name */ struct cramfs_inode root; /* root inode data */ }; /* * Feature flags * * 0x00000000 - 0x000000ff: features that work for all past kernels * 0x00000100 - 0xffffffff: features that don't work for past kernels */ #define CRAMFS_FLAG_FSID_VERSION_2 0x00000001 /* fsid version #2 */ #define CRAMFS_FLAG_SORTED_DIRS 0x00000002 /* sorted dirs */ #define CRAMFS_FLAG_HOLES 0x00000100 /* support for holes */ #define CRAMFS_FLAG_WRONG_SIGNATURE 0x00000200 /* reserved */ #define CRAMFS_FLAG_SHIFTED_ROOT_OFFSET 0x00000400 /* shifted root fs */ #define CRAMFS_FLAG_EXT_BLOCK_POINTERS 0x00000800 /* block pointer extensions */ /* * Valid values in super.flags. Currently we refuse to mount * if (flags & ~CRAMFS_SUPPORTED_FLAGS). Maybe that should be * changed to test super.future instead. */ #define CRAMFS_SUPPORTED_FLAGS ( 0x000000ff \ | CRAMFS_FLAG_HOLES \ | CRAMFS_FLAG_WRONG_SIGNATURE \ | CRAMFS_FLAG_SHIFTED_ROOT_OFFSET \ | CRAMFS_FLAG_EXT_BLOCK_POINTERS ) /* * Block pointer flags * * The maximum block offset that needs to be represented is roughly: * * (1 << CRAMFS_OFFSET_WIDTH) * 4 + * (1 << CRAMFS_SIZE_WIDTH) / PAGE_SIZE * (4 + PAGE_SIZE) * = 0x11004000 * * That leaves room for 3 flag bits in the block pointer table. */ #define CRAMFS_BLK_FLAG_UNCOMPRESSED (1 << 31) #define CRAMFS_BLK_FLAG_DIRECT_PTR (1 << 30) #define CRAMFS_BLK_FLAGS ( CRAMFS_BLK_FLAG_UNCOMPRESSED \ | CRAMFS_BLK_FLAG_DIRECT_PTR ) /* * Direct blocks are at least 4-byte aligned. * Pointers to direct blocks are shifted down by 2 bits. */ #define CRAMFS_BLK_DIRECT_PTR_SHIFT 2 #endif /* __CRAMFS_H */ linux/kexec.h000064400000003453151027430560007163 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef LINUX_KEXEC_H #define LINUX_KEXEC_H /* kexec system call - It loads the new kernel to boot into. * kexec does not sync, or unmount filesystems so if you need * that to happen you need to do that yourself. */ #include /* kexec flags for different usage scenarios */ #define KEXEC_ON_CRASH 0x00000001 #define KEXEC_PRESERVE_CONTEXT 0x00000002 #define KEXEC_ARCH_MASK 0xffff0000 /* * Kexec file load interface flags. * KEXEC_FILE_UNLOAD : Unload already loaded kexec/kdump image. * KEXEC_FILE_ON_CRASH : Load/unload operation belongs to kdump image. * KEXEC_FILE_NO_INITRAMFS : No initramfs is being loaded. Ignore the initrd * fd field. */ #define KEXEC_FILE_UNLOAD 0x00000001 #define KEXEC_FILE_ON_CRASH 0x00000002 #define KEXEC_FILE_NO_INITRAMFS 0x00000004 /* These values match the ELF architecture values. * Unless there is a good reason that should continue to be the case. */ #define KEXEC_ARCH_DEFAULT ( 0 << 16) #define KEXEC_ARCH_386 ( 3 << 16) #define KEXEC_ARCH_68K ( 4 << 16) #define KEXEC_ARCH_X86_64 (62 << 16) #define KEXEC_ARCH_PPC (20 << 16) #define KEXEC_ARCH_PPC64 (21 << 16) #define KEXEC_ARCH_IA_64 (50 << 16) #define KEXEC_ARCH_ARM (40 << 16) #define KEXEC_ARCH_S390 (22 << 16) #define KEXEC_ARCH_SH (42 << 16) #define KEXEC_ARCH_MIPS_LE (10 << 16) #define KEXEC_ARCH_MIPS ( 8 << 16) #define KEXEC_ARCH_AARCH64 (183 << 16) /* The artificial cap on the number of segments passed to kexec_load. */ #define KEXEC_SEGMENT_MAX 16 /* * This structure is used to hold the arguments that are used when * loading kernel binaries. */ struct kexec_segment { const void *buf; size_t bufsz; const void *mem; size_t memsz; }; #endif /* LINUX_KEXEC_H */ linux/personality.h000064400000004061151027430560010431 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_PERSONALITY_H #define _LINUX_PERSONALITY_H /* * Flags for bug emulation. * * These occupy the top three bytes. */ enum { UNAME26 = 0x0020000, ADDR_NO_RANDOMIZE = 0x0040000, /* disable randomization of VA space */ FDPIC_FUNCPTRS = 0x0080000, /* userspace function ptrs point to descriptors * (signal handling) */ MMAP_PAGE_ZERO = 0x0100000, ADDR_COMPAT_LAYOUT = 0x0200000, READ_IMPLIES_EXEC = 0x0400000, ADDR_LIMIT_32BIT = 0x0800000, SHORT_INODE = 0x1000000, WHOLE_SECONDS = 0x2000000, STICKY_TIMEOUTS = 0x4000000, ADDR_LIMIT_3GB = 0x8000000, }; /* * Security-relevant compatibility flags that must be * cleared upon setuid or setgid exec: */ #define PER_CLEAR_ON_SETID (READ_IMPLIES_EXEC | \ ADDR_NO_RANDOMIZE | \ ADDR_COMPAT_LAYOUT | \ MMAP_PAGE_ZERO) /* * Personality types. * * These go in the low byte. Avoid using the top bit, it will * conflict with error returns. */ enum { PER_LINUX = 0x0000, PER_LINUX_32BIT = 0x0000 | ADDR_LIMIT_32BIT, PER_LINUX_FDPIC = 0x0000 | FDPIC_FUNCPTRS, PER_SVR4 = 0x0001 | STICKY_TIMEOUTS | MMAP_PAGE_ZERO, PER_SVR3 = 0x0002 | STICKY_TIMEOUTS | SHORT_INODE, PER_SCOSVR3 = 0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS | SHORT_INODE, PER_OSR5 = 0x0003 | STICKY_TIMEOUTS | WHOLE_SECONDS, PER_WYSEV386 = 0x0004 | STICKY_TIMEOUTS | SHORT_INODE, PER_ISCR4 = 0x0005 | STICKY_TIMEOUTS, PER_BSD = 0x0006, PER_SUNOS = 0x0006 | STICKY_TIMEOUTS, PER_XENIX = 0x0007 | STICKY_TIMEOUTS | SHORT_INODE, PER_LINUX32 = 0x0008, PER_LINUX32_3GB = 0x0008 | ADDR_LIMIT_3GB, PER_IRIX32 = 0x0009 | STICKY_TIMEOUTS,/* IRIX5 32-bit */ PER_IRIXN32 = 0x000a | STICKY_TIMEOUTS,/* IRIX6 new 32-bit */ PER_IRIX64 = 0x000b | STICKY_TIMEOUTS,/* IRIX6 64-bit */ PER_RISCOS = 0x000c, PER_SOLARIS = 0x000d | STICKY_TIMEOUTS, PER_UW7 = 0x000e | STICKY_TIMEOUTS | MMAP_PAGE_ZERO, PER_OSF4 = 0x000f, /* OSF/1 v4 */ PER_HPUX = 0x0010, PER_MASK = 0x00ff, }; #endif /* _LINUX_PERSONALITY_H */ linux/netfilter_ipv6.h000064400000004215151027430560011021 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* IPv6-specific defines for netfilter. * (C)1998 Rusty Russell -- This code is GPL. * (C)1999 David Jeffery * this header was blatantly ripped from netfilter_ipv4.h * it's amazing what adding a bunch of 6s can do =8^) */ #ifndef __LINUX_IP6_NETFILTER_H #define __LINUX_IP6_NETFILTER_H #include /* only for userspace compatibility */ #include /* for INT_MIN, INT_MAX */ /* IP Cache bits. */ /* Src IP address. */ #define NFC_IP6_SRC 0x0001 /* Dest IP address. */ #define NFC_IP6_DST 0x0002 /* Input device. */ #define NFC_IP6_IF_IN 0x0004 /* Output device. */ #define NFC_IP6_IF_OUT 0x0008 /* TOS. */ #define NFC_IP6_TOS 0x0010 /* Protocol. */ #define NFC_IP6_PROTO 0x0020 /* IP options. */ #define NFC_IP6_OPTIONS 0x0040 /* Frag & flags. */ #define NFC_IP6_FRAG 0x0080 /* Per-protocol information: only matters if proto match. */ /* TCP flags. */ #define NFC_IP6_TCPFLAGS 0x0100 /* Source port. */ #define NFC_IP6_SRC_PT 0x0200 /* Dest port. */ #define NFC_IP6_DST_PT 0x0400 /* Something else about the proto */ #define NFC_IP6_PROTO_UNKNOWN 0x2000 /* IP6 Hooks */ /* After promisc drops, checksum checks. */ #define NF_IP6_PRE_ROUTING 0 /* If the packet is destined for this box. */ #define NF_IP6_LOCAL_IN 1 /* If the packet is destined for another interface. */ #define NF_IP6_FORWARD 2 /* Packets coming from a local process. */ #define NF_IP6_LOCAL_OUT 3 /* Packets about to hit the wire. */ #define NF_IP6_POST_ROUTING 4 #define NF_IP6_NUMHOOKS 5 enum nf_ip6_hook_priorities { NF_IP6_PRI_FIRST = INT_MIN, NF_IP6_PRI_RAW_BEFORE_DEFRAG = -450, NF_IP6_PRI_CONNTRACK_DEFRAG = -400, NF_IP6_PRI_RAW = -300, NF_IP6_PRI_SELINUX_FIRST = -225, NF_IP6_PRI_CONNTRACK = -200, NF_IP6_PRI_MANGLE = -150, NF_IP6_PRI_NAT_DST = -100, NF_IP6_PRI_FILTER = 0, NF_IP6_PRI_SECURITY = 50, NF_IP6_PRI_NAT_SRC = 100, NF_IP6_PRI_SELINUX_LAST = 225, NF_IP6_PRI_CONNTRACK_HELPER = 300, NF_IP6_PRI_LAST = INT_MAX, }; #endif /* __LINUX_IP6_NETFILTER_H */ linux/close_range.h000064400000000571151027430560010343 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_CLOSE_RANGE_H #define _LINUX_CLOSE_RANGE_H /* Unshare the file descriptor table before closing file descriptors. */ #define CLOSE_RANGE_UNSHARE (1U << 1) /* Set the FD_CLOEXEC bit instead of closing the file descriptor. */ #define CLOSE_RANGE_CLOEXEC (1U << 2) #endif /* _LINUX_CLOSE_RANGE_H */ linux/wmi.h000064400000003536151027430560006662 0ustar00/* * User API methods for ACPI-WMI mapping driver * * Copyright (C) 2017 Dell, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _LINUX_WMI_H #define _LINUX_WMI_H #include #include /* WMI bus will filter all WMI vendor driver requests through this IOC */ #define WMI_IOC 'W' /* All ioctl requests through WMI should declare their size followed by * relevant data objects */ struct wmi_ioctl_buffer { __u64 length; __u8 data[]; }; /* This structure may be modified by the firmware when we enter * system management mode through SMM, hence the volatiles */ struct calling_interface_buffer { __u16 cmd_class; __u16 cmd_select; __volatile__ __u32 input[4]; __volatile__ __u32 output[4]; } __attribute__((packed)); struct dell_wmi_extensions { __u32 argattrib; __u32 blength; __u8 data[]; } __attribute__((packed)); struct dell_wmi_smbios_buffer { __u64 length; struct calling_interface_buffer std; struct dell_wmi_extensions ext; } __attribute__((packed)); /* Whitelisted smbios class/select commands */ #define CLASS_TOKEN_READ 0 #define CLASS_TOKEN_WRITE 1 #define SELECT_TOKEN_STD 0 #define SELECT_TOKEN_BAT 1 #define SELECT_TOKEN_AC 2 #define CLASS_FLASH_INTERFACE 7 #define SELECT_FLASH_INTERFACE 3 #define CLASS_ADMIN_PROP 10 #define SELECT_ADMIN_PROP 3 #define CLASS_INFO 17 #define SELECT_RFKILL 11 #define SELECT_APP_REGISTRATION 3 #define SELECT_DOCK 22 /* whitelisted tokens */ #define CAPSULE_EN_TOKEN 0x0461 #define CAPSULE_DIS_TOKEN 0x0462 #define WSMT_EN_TOKEN 0x04EC #define WSMT_DIS_TOKEN 0x04ED /* Dell SMBIOS calling IOCTL command used by dell-smbios-wmi */ #define DELL_WMI_SMBIOS_CMD _IOWR(WMI_IOC, 0, struct dell_wmi_smbios_buffer) #endif linux/mount.h000064400000010702151027430560007221 0ustar00#ifndef _LINUX_MOUNT_H #define _LINUX_MOUNT_H /* * These are the fs-independent mount-flags: up to 32 flags are supported * * Usage of these is restricted within the kernel to core mount(2) code and * callers of sys_mount() only. Filesystems should be using the SB_* * equivalent instead. */ #define MS_RDONLY 1 /* Mount read-only */ #define MS_NOSUID 2 /* Ignore suid and sgid bits */ #define MS_NODEV 4 /* Disallow access to device special files */ #define MS_NOEXEC 8 /* Disallow program execution */ #define MS_SYNCHRONOUS 16 /* Writes are synced at once */ #define MS_REMOUNT 32 /* Alter flags of a mounted FS */ #define MS_MANDLOCK 64 /* Allow mandatory locks on an FS */ #define MS_DIRSYNC 128 /* Directory modifications are synchronous */ #define MS_NOATIME 1024 /* Do not update access times. */ #define MS_NODIRATIME 2048 /* Do not update directory access times */ #define MS_BIND 4096 #define MS_MOVE 8192 #define MS_REC 16384 #define MS_VERBOSE 32768 /* War is peace. Verbosity is silence. MS_VERBOSE is deprecated. */ #define MS_SILENT 32768 #define MS_POSIXACL (1<<16) /* VFS does not apply the umask */ #define MS_UNBINDABLE (1<<17) /* change to unbindable */ #define MS_PRIVATE (1<<18) /* change to private */ #define MS_SLAVE (1<<19) /* change to slave */ #define MS_SHARED (1<<20) /* change to shared */ #define MS_RELATIME (1<<21) /* Update atime relative to mtime/ctime. */ #define MS_KERNMOUNT (1<<22) /* this is a kern_mount call */ #define MS_I_VERSION (1<<23) /* Update inode I_version field */ #define MS_STRICTATIME (1<<24) /* Always perform atime updates */ #define MS_LAZYTIME (1<<25) /* Update the on-disk [acm]times lazily */ /* These sb flags are internal to the kernel */ #define MS_SUBMOUNT (1<<26) #define MS_NOREMOTELOCK (1<<27) #define MS_NOSEC (1<<28) #define MS_BORN (1<<29) #define MS_ACTIVE (1<<30) #define MS_NOUSER (1<<31) /* * Superblock flags that can be altered by MS_REMOUNT */ #define MS_RMT_MASK (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION|\ MS_LAZYTIME) /* * Old magic mount flag and mask */ #define MS_MGC_VAL 0xC0ED0000 #define MS_MGC_MSK 0xffff0000 /* * open_tree() flags. */ #define OPEN_TREE_CLONE 1 /* Clone the target tree and attach the clone */ #define OPEN_TREE_CLOEXEC O_CLOEXEC /* Close the file on execve() */ /* * move_mount() flags. */ #define MOVE_MOUNT_F_SYMLINKS 0x00000001 /* Follow symlinks on from path */ #define MOVE_MOUNT_F_AUTOMOUNTS 0x00000002 /* Follow automounts on from path */ #define MOVE_MOUNT_F_EMPTY_PATH 0x00000004 /* Empty from path permitted */ #define MOVE_MOUNT_T_SYMLINKS 0x00000010 /* Follow symlinks on to path */ #define MOVE_MOUNT_T_AUTOMOUNTS 0x00000020 /* Follow automounts on to path */ #define MOVE_MOUNT_T_EMPTY_PATH 0x00000040 /* Empty to path permitted */ #define MOVE_MOUNT__MASK 0x00000077 /* * fsopen() flags. */ #define FSOPEN_CLOEXEC 0x00000001 /* * fspick() flags. */ #define FSPICK_CLOEXEC 0x00000001 #define FSPICK_SYMLINK_NOFOLLOW 0x00000002 #define FSPICK_NO_AUTOMOUNT 0x00000004 #define FSPICK_EMPTY_PATH 0x00000008 /* * The type of fsconfig() call made. */ enum fsconfig_command { FSCONFIG_SET_FLAG = 0, /* Set parameter, supplying no value */ FSCONFIG_SET_STRING = 1, /* Set parameter, supplying a string value */ FSCONFIG_SET_BINARY = 2, /* Set parameter, supplying a binary blob value */ FSCONFIG_SET_PATH = 3, /* Set parameter, supplying an object by path */ FSCONFIG_SET_PATH_EMPTY = 4, /* Set parameter, supplying an object by (empty) path */ FSCONFIG_SET_FD = 5, /* Set parameter, supplying an object by fd */ FSCONFIG_CMD_CREATE = 6, /* Invoke superblock creation */ FSCONFIG_CMD_RECONFIGURE = 7, /* Invoke superblock reconfiguration */ }; /* * fsmount() flags. */ #define FSMOUNT_CLOEXEC 0x00000001 /* * Mount attributes. */ #define MOUNT_ATTR_RDONLY 0x00000001 /* Mount read-only */ #define MOUNT_ATTR_NOSUID 0x00000002 /* Ignore suid and sgid bits */ #define MOUNT_ATTR_NODEV 0x00000004 /* Disallow access to device special files */ #define MOUNT_ATTR_NOEXEC 0x00000008 /* Disallow program execution */ #define MOUNT_ATTR__ATIME 0x00000070 /* Setting on how atime should be updated */ #define MOUNT_ATTR_RELATIME 0x00000000 /* - Update atime relative to mtime/ctime. */ #define MOUNT_ATTR_NOATIME 0x00000010 /* - Do not update access times. */ #define MOUNT_ATTR_STRICTATIME 0x00000020 /* - Always perform atime updates */ #define MOUNT_ATTR_NODIRATIME 0x00000080 /* Do not update directory access times */ #endif /* _LINUX_MOUNT_H */ linux/nfs_fs.h000064400000003151151027430560007335 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/include/linux/nfs_fs.h * * Copyright (C) 1992 Rick Sladkey * * OS-specific nfs filesystem definitions and declarations */ #ifndef _LINUX_NFS_FS_H #define _LINUX_NFS_FS_H #include /* Default timeout values */ #define NFS_DEF_UDP_TIMEO (11) #define NFS_DEF_UDP_RETRANS (3) #define NFS_DEF_TCP_TIMEO (600) #define NFS_DEF_TCP_RETRANS (2) #define NFS_MAX_UDP_TIMEOUT (60*HZ) #define NFS_MAX_TCP_TIMEOUT (600*HZ) #define NFS_DEF_ACREGMIN (3) #define NFS_DEF_ACREGMAX (60) #define NFS_DEF_ACDIRMIN (30) #define NFS_DEF_ACDIRMAX (60) /* * When flushing a cluster of dirty pages, there can be different * strategies: */ #define FLUSH_SYNC 1 /* file being synced, or contention */ #define FLUSH_STABLE 4 /* commit to stable storage */ #define FLUSH_LOWPRI 8 /* low priority background flush */ #define FLUSH_HIGHPRI 16 /* high priority memory reclaim flush */ #define FLUSH_COND_STABLE 32 /* conditional stable write - only stable * if everything fits in one RPC */ /* * NFS debug flags */ #define NFSDBG_VFS 0x0001 #define NFSDBG_DIRCACHE 0x0002 #define NFSDBG_LOOKUPCACHE 0x0004 #define NFSDBG_PAGECACHE 0x0008 #define NFSDBG_PROC 0x0010 #define NFSDBG_XDR 0x0020 #define NFSDBG_FILE 0x0040 #define NFSDBG_ROOT 0x0080 #define NFSDBG_CALLBACK 0x0100 #define NFSDBG_CLIENT 0x0200 #define NFSDBG_MOUNT 0x0400 #define NFSDBG_FSCACHE 0x0800 #define NFSDBG_PNFS 0x1000 #define NFSDBG_PNFS_LD 0x2000 #define NFSDBG_STATE 0x4000 #define NFSDBG_XATTRCACHE 0x8000 #define NFSDBG_ALL 0xFFFF #endif /* _LINUX_NFS_FS_H */ linux/max2175.h000064400000002013151027430560007157 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * max2175.h * * Maxim Integrated MAX2175 RF to Bits tuner driver - user space header file. * * Copyright (C) 2016 Maxim Integrated Products * Copyright (C) 2017 Renesas Electronics Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __UAPI_MAX2175_H_ #define __UAPI_MAX2175_H_ #include #define V4L2_CID_MAX2175_I2S_ENABLE (V4L2_CID_USER_MAX217X_BASE + 0x01) #define V4L2_CID_MAX2175_HSLS (V4L2_CID_USER_MAX217X_BASE + 0x02) #define V4L2_CID_MAX2175_RX_MODE (V4L2_CID_USER_MAX217X_BASE + 0x03) #endif /* __UAPI_MAX2175_H_ */ linux/jffs2.h000064400000015552151027430560007101 0ustar00/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright © 2001-2007 Red Hat, Inc. * Copyright © 2004-2010 David Woodhouse * * Created by David Woodhouse * * For licensing information, see the file 'LICENCE' in the * jffs2 directory. */ #ifndef __LINUX_JFFS2_H__ #define __LINUX_JFFS2_H__ #include #include /* You must include something which defines the C99 uintXX_t types. We don't do it from here because this file is used in too many different environments. */ /* Values we may expect to find in the 'magic' field */ #define JFFS2_OLD_MAGIC_BITMASK 0x1984 #define JFFS2_MAGIC_BITMASK 0x1985 #define KSAMTIB_CIGAM_2SFFJ 0x8519 /* For detecting wrong-endian fs */ #define JFFS2_EMPTY_BITMASK 0xffff #define JFFS2_DIRTY_BITMASK 0x0000 /* Summary node MAGIC marker */ #define JFFS2_SUM_MAGIC 0x02851885 /* We only allow a single char for length, and 0xFF is empty flash so we don't want it confused with a real length. Hence max 254. */ #define JFFS2_MAX_NAME_LEN 254 /* How small can we sensibly write nodes? */ #define JFFS2_MIN_DATA_LEN 128 #define JFFS2_COMPR_NONE 0x00 #define JFFS2_COMPR_ZERO 0x01 #define JFFS2_COMPR_RTIME 0x02 #define JFFS2_COMPR_RUBINMIPS 0x03 #define JFFS2_COMPR_COPY 0x04 #define JFFS2_COMPR_DYNRUBIN 0x05 #define JFFS2_COMPR_ZLIB 0x06 #define JFFS2_COMPR_LZO 0x07 /* Compatibility flags. */ #define JFFS2_COMPAT_MASK 0xc000 /* What do to if an unknown nodetype is found */ #define JFFS2_NODE_ACCURATE 0x2000 /* INCOMPAT: Fail to mount the filesystem */ #define JFFS2_FEATURE_INCOMPAT 0xc000 /* ROCOMPAT: Mount read-only */ #define JFFS2_FEATURE_ROCOMPAT 0x8000 /* RWCOMPAT_COPY: Mount read/write, and copy the node when it's GC'd */ #define JFFS2_FEATURE_RWCOMPAT_COPY 0x4000 /* RWCOMPAT_DELETE: Mount read/write, and delete the node when it's GC'd */ #define JFFS2_FEATURE_RWCOMPAT_DELETE 0x0000 #define JFFS2_NODETYPE_DIRENT (JFFS2_FEATURE_INCOMPAT | JFFS2_NODE_ACCURATE | 1) #define JFFS2_NODETYPE_INODE (JFFS2_FEATURE_INCOMPAT | JFFS2_NODE_ACCURATE | 2) #define JFFS2_NODETYPE_CLEANMARKER (JFFS2_FEATURE_RWCOMPAT_DELETE | JFFS2_NODE_ACCURATE | 3) #define JFFS2_NODETYPE_PADDING (JFFS2_FEATURE_RWCOMPAT_DELETE | JFFS2_NODE_ACCURATE | 4) #define JFFS2_NODETYPE_SUMMARY (JFFS2_FEATURE_RWCOMPAT_DELETE | JFFS2_NODE_ACCURATE | 6) #define JFFS2_NODETYPE_XATTR (JFFS2_FEATURE_INCOMPAT | JFFS2_NODE_ACCURATE | 8) #define JFFS2_NODETYPE_XREF (JFFS2_FEATURE_INCOMPAT | JFFS2_NODE_ACCURATE | 9) /* XATTR Related */ #define JFFS2_XPREFIX_USER 1 /* for "user." */ #define JFFS2_XPREFIX_SECURITY 2 /* for "security." */ #define JFFS2_XPREFIX_ACL_ACCESS 3 /* for "system.posix_acl_access" */ #define JFFS2_XPREFIX_ACL_DEFAULT 4 /* for "system.posix_acl_default" */ #define JFFS2_XPREFIX_TRUSTED 5 /* for "trusted.*" */ #define JFFS2_ACL_VERSION 0x0001 // Maybe later... //#define JFFS2_NODETYPE_CHECKPOINT (JFFS2_FEATURE_RWCOMPAT_DELETE | JFFS2_NODE_ACCURATE | 3) //#define JFFS2_NODETYPE_OPTIONS (JFFS2_FEATURE_RWCOMPAT_COPY | JFFS2_NODE_ACCURATE | 4) #define JFFS2_INO_FLAG_PREREAD 1 /* Do read_inode() for this one at mount time, don't wait for it to happen later */ #define JFFS2_INO_FLAG_USERCOMPR 2 /* User has requested a specific compression type */ /* These can go once we've made sure we've caught all uses without byteswapping */ typedef struct { __u32 v32; } __attribute__((packed)) jint32_t; typedef struct { __u32 m; } __attribute__((packed)) jmode_t; typedef struct { __u16 v16; } __attribute__((packed)) jint16_t; struct jffs2_unknown_node { /* All start like this */ jint16_t magic; jint16_t nodetype; jint32_t totlen; /* So we can skip over nodes we don't grok */ jint32_t hdr_crc; }; struct jffs2_raw_dirent { jint16_t magic; jint16_t nodetype; /* == JFFS2_NODETYPE_DIRENT */ jint32_t totlen; jint32_t hdr_crc; jint32_t pino; jint32_t version; jint32_t ino; /* == zero for unlink */ jint32_t mctime; __u8 nsize; __u8 type; __u8 unused[2]; jint32_t node_crc; jint32_t name_crc; __u8 name[0]; }; /* The JFFS2 raw inode structure: Used for storage on physical media. */ /* The uid, gid, atime, mtime and ctime members could be longer, but are left like this for space efficiency. If and when people decide they really need them extended, it's simple enough to add support for a new type of raw node. */ struct jffs2_raw_inode { jint16_t magic; /* A constant magic number. */ jint16_t nodetype; /* == JFFS2_NODETYPE_INODE */ jint32_t totlen; /* Total length of this node (inc data, etc.) */ jint32_t hdr_crc; jint32_t ino; /* Inode number. */ jint32_t version; /* Version number. */ jmode_t mode; /* The file's type or mode. */ jint16_t uid; /* The file's owner. */ jint16_t gid; /* The file's group. */ jint32_t isize; /* Total resultant size of this inode (used for truncations) */ jint32_t atime; /* Last access time. */ jint32_t mtime; /* Last modification time. */ jint32_t ctime; /* Change time. */ jint32_t offset; /* Where to begin to write. */ jint32_t csize; /* (Compressed) data size */ jint32_t dsize; /* Size of the node's data. (after decompression) */ __u8 compr; /* Compression algorithm used */ __u8 usercompr; /* Compression algorithm requested by the user */ jint16_t flags; /* See JFFS2_INO_FLAG_* */ jint32_t data_crc; /* CRC for the (compressed) data. */ jint32_t node_crc; /* CRC for the raw inode (excluding data) */ __u8 data[0]; }; struct jffs2_raw_xattr { jint16_t magic; jint16_t nodetype; /* = JFFS2_NODETYPE_XATTR */ jint32_t totlen; jint32_t hdr_crc; jint32_t xid; /* XATTR identifier number */ jint32_t version; __u8 xprefix; __u8 name_len; jint16_t value_len; jint32_t data_crc; jint32_t node_crc; __u8 data[0]; } __attribute__((packed)); struct jffs2_raw_xref { jint16_t magic; jint16_t nodetype; /* = JFFS2_NODETYPE_XREF */ jint32_t totlen; jint32_t hdr_crc; jint32_t ino; /* inode number */ jint32_t xid; /* XATTR identifier number */ jint32_t xseqno; /* xref sequential number */ jint32_t node_crc; } __attribute__((packed)); struct jffs2_raw_summary { jint16_t magic; jint16_t nodetype; /* = JFFS2_NODETYPE_SUMMARY */ jint32_t totlen; jint32_t hdr_crc; jint32_t sum_num; /* number of sum entries*/ jint32_t cln_mkr; /* clean marker size, 0 = no cleanmarker */ jint32_t padded; /* sum of the size of padding nodes */ jint32_t sum_crc; /* summary information crc */ jint32_t node_crc; /* node crc */ jint32_t sum[0]; /* inode summary info */ }; union jffs2_node_union { struct jffs2_raw_inode i; struct jffs2_raw_dirent d; struct jffs2_raw_xattr x; struct jffs2_raw_xref r; struct jffs2_raw_summary s; struct jffs2_unknown_node u; }; /* Data payload for device nodes. */ union jffs2_device_node { jint16_t old_id; jint32_t new_id; }; #endif /* __LINUX_JFFS2_H__ */ linux/isdn/capicmd.h000064400000011166151027430560010421 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: capicmd.h,v 1.2.6.2 2001/09/23 22:24:33 kai Exp $ * * CAPI 2.0 Interface for Linux * * Copyright 1997 by Carsten Paeth * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef __CAPICMD_H__ #define __CAPICMD_H__ #define CAPI_MSG_BASELEN 8 #define CAPI_DATA_B3_REQ_LEN (CAPI_MSG_BASELEN+4+4+2+2+2) #define CAPI_DATA_B3_RESP_LEN (CAPI_MSG_BASELEN+4+2) /*----- CAPI commands -----*/ #define CAPI_ALERT 0x01 #define CAPI_CONNECT 0x02 #define CAPI_CONNECT_ACTIVE 0x03 #define CAPI_CONNECT_B3_ACTIVE 0x83 #define CAPI_CONNECT_B3 0x82 #define CAPI_CONNECT_B3_T90_ACTIVE 0x88 #define CAPI_DATA_B3 0x86 #define CAPI_DISCONNECT_B3 0x84 #define CAPI_DISCONNECT 0x04 #define CAPI_FACILITY 0x80 #define CAPI_INFO 0x08 #define CAPI_LISTEN 0x05 #define CAPI_MANUFACTURER 0xff #define CAPI_RESET_B3 0x87 #define CAPI_SELECT_B_PROTOCOL 0x41 /*----- CAPI subcommands -----*/ #define CAPI_REQ 0x80 #define CAPI_CONF 0x81 #define CAPI_IND 0x82 #define CAPI_RESP 0x83 /*----- CAPI combined commands -----*/ #define CAPICMD(cmd,subcmd) (((cmd)<<8)|(subcmd)) #define CAPI_DISCONNECT_REQ CAPICMD(CAPI_DISCONNECT,CAPI_REQ) #define CAPI_DISCONNECT_CONF CAPICMD(CAPI_DISCONNECT,CAPI_CONF) #define CAPI_DISCONNECT_IND CAPICMD(CAPI_DISCONNECT,CAPI_IND) #define CAPI_DISCONNECT_RESP CAPICMD(CAPI_DISCONNECT,CAPI_RESP) #define CAPI_ALERT_REQ CAPICMD(CAPI_ALERT,CAPI_REQ) #define CAPI_ALERT_CONF CAPICMD(CAPI_ALERT,CAPI_CONF) #define CAPI_CONNECT_REQ CAPICMD(CAPI_CONNECT,CAPI_REQ) #define CAPI_CONNECT_CONF CAPICMD(CAPI_CONNECT,CAPI_CONF) #define CAPI_CONNECT_IND CAPICMD(CAPI_CONNECT,CAPI_IND) #define CAPI_CONNECT_RESP CAPICMD(CAPI_CONNECT,CAPI_RESP) #define CAPI_CONNECT_ACTIVE_REQ CAPICMD(CAPI_CONNECT_ACTIVE,CAPI_REQ) #define CAPI_CONNECT_ACTIVE_CONF CAPICMD(CAPI_CONNECT_ACTIVE,CAPI_CONF) #define CAPI_CONNECT_ACTIVE_IND CAPICMD(CAPI_CONNECT_ACTIVE,CAPI_IND) #define CAPI_CONNECT_ACTIVE_RESP CAPICMD(CAPI_CONNECT_ACTIVE,CAPI_RESP) #define CAPI_SELECT_B_PROTOCOL_REQ CAPICMD(CAPI_SELECT_B_PROTOCOL,CAPI_REQ) #define CAPI_SELECT_B_PROTOCOL_CONF CAPICMD(CAPI_SELECT_B_PROTOCOL,CAPI_CONF) #define CAPI_CONNECT_B3_ACTIVE_REQ CAPICMD(CAPI_CONNECT_B3_ACTIVE,CAPI_REQ) #define CAPI_CONNECT_B3_ACTIVE_CONF CAPICMD(CAPI_CONNECT_B3_ACTIVE,CAPI_CONF) #define CAPI_CONNECT_B3_ACTIVE_IND CAPICMD(CAPI_CONNECT_B3_ACTIVE,CAPI_IND) #define CAPI_CONNECT_B3_ACTIVE_RESP CAPICMD(CAPI_CONNECT_B3_ACTIVE,CAPI_RESP) #define CAPI_CONNECT_B3_REQ CAPICMD(CAPI_CONNECT_B3,CAPI_REQ) #define CAPI_CONNECT_B3_CONF CAPICMD(CAPI_CONNECT_B3,CAPI_CONF) #define CAPI_CONNECT_B3_IND CAPICMD(CAPI_CONNECT_B3,CAPI_IND) #define CAPI_CONNECT_B3_RESP CAPICMD(CAPI_CONNECT_B3,CAPI_RESP) #define CAPI_CONNECT_B3_T90_ACTIVE_IND CAPICMD(CAPI_CONNECT_B3_T90_ACTIVE,CAPI_IND) #define CAPI_CONNECT_B3_T90_ACTIVE_RESP CAPICMD(CAPI_CONNECT_B3_T90_ACTIVE,CAPI_RESP) #define CAPI_DATA_B3_REQ CAPICMD(CAPI_DATA_B3,CAPI_REQ) #define CAPI_DATA_B3_CONF CAPICMD(CAPI_DATA_B3,CAPI_CONF) #define CAPI_DATA_B3_IND CAPICMD(CAPI_DATA_B3,CAPI_IND) #define CAPI_DATA_B3_RESP CAPICMD(CAPI_DATA_B3,CAPI_RESP) #define CAPI_DISCONNECT_B3_REQ CAPICMD(CAPI_DISCONNECT_B3,CAPI_REQ) #define CAPI_DISCONNECT_B3_CONF CAPICMD(CAPI_DISCONNECT_B3,CAPI_CONF) #define CAPI_DISCONNECT_B3_IND CAPICMD(CAPI_DISCONNECT_B3,CAPI_IND) #define CAPI_DISCONNECT_B3_RESP CAPICMD(CAPI_DISCONNECT_B3,CAPI_RESP) #define CAPI_RESET_B3_REQ CAPICMD(CAPI_RESET_B3,CAPI_REQ) #define CAPI_RESET_B3_CONF CAPICMD(CAPI_RESET_B3,CAPI_CONF) #define CAPI_RESET_B3_IND CAPICMD(CAPI_RESET_B3,CAPI_IND) #define CAPI_RESET_B3_RESP CAPICMD(CAPI_RESET_B3,CAPI_RESP) #define CAPI_LISTEN_REQ CAPICMD(CAPI_LISTEN,CAPI_REQ) #define CAPI_LISTEN_CONF CAPICMD(CAPI_LISTEN,CAPI_CONF) #define CAPI_MANUFACTURER_REQ CAPICMD(CAPI_MANUFACTURER,CAPI_REQ) #define CAPI_MANUFACTURER_CONF CAPICMD(CAPI_MANUFACTURER,CAPI_CONF) #define CAPI_MANUFACTURER_IND CAPICMD(CAPI_MANUFACTURER,CAPI_IND) #define CAPI_MANUFACTURER_RESP CAPICMD(CAPI_MANUFACTURER,CAPI_RESP) #define CAPI_FACILITY_REQ CAPICMD(CAPI_FACILITY,CAPI_REQ) #define CAPI_FACILITY_CONF CAPICMD(CAPI_FACILITY,CAPI_CONF) #define CAPI_FACILITY_IND CAPICMD(CAPI_FACILITY,CAPI_IND) #define CAPI_FACILITY_RESP CAPICMD(CAPI_FACILITY,CAPI_RESP) #define CAPI_INFO_REQ CAPICMD(CAPI_INFO,CAPI_REQ) #define CAPI_INFO_CONF CAPICMD(CAPI_INFO,CAPI_CONF) #define CAPI_INFO_IND CAPICMD(CAPI_INFO,CAPI_IND) #define CAPI_INFO_RESP CAPICMD(CAPI_INFO,CAPI_RESP) #endif /* __CAPICMD_H__ */ linux/input-event-codes.h000064400000067676151027430560011456 0ustar00/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */ /* * Input event codes * * *** IMPORTANT *** * This file is not only included from C-code but also from devicetree source * files. As such this file MUST only contain comments and defines. * * Copyright (c) 1999-2002 Vojtech Pavlik * Copyright (c) 2015 Hans de Goede * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _INPUT_EVENT_CODES_H #define _INPUT_EVENT_CODES_H /* * Device properties and quirks */ #define INPUT_PROP_POINTER 0x00 /* needs a pointer */ #define INPUT_PROP_DIRECT 0x01 /* direct input devices */ #define INPUT_PROP_BUTTONPAD 0x02 /* has button(s) under pad */ #define INPUT_PROP_SEMI_MT 0x03 /* touch rectangle only */ #define INPUT_PROP_TOPBUTTONPAD 0x04 /* softbuttons at top of pad */ #define INPUT_PROP_POINTING_STICK 0x05 /* is a pointing stick */ #define INPUT_PROP_ACCELEROMETER 0x06 /* has accelerometer */ #define INPUT_PROP_MAX 0x1f #define INPUT_PROP_CNT (INPUT_PROP_MAX + 1) /* * Event types */ #define EV_SYN 0x00 #define EV_KEY 0x01 #define EV_REL 0x02 #define EV_ABS 0x03 #define EV_MSC 0x04 #define EV_SW 0x05 #define EV_LED 0x11 #define EV_SND 0x12 #define EV_REP 0x14 #define EV_FF 0x15 #define EV_PWR 0x16 #define EV_FF_STATUS 0x17 #define EV_MAX 0x1f #define EV_CNT (EV_MAX+1) /* * Synchronization events. */ #define SYN_REPORT 0 #define SYN_CONFIG 1 #define SYN_MT_REPORT 2 #define SYN_DROPPED 3 #define SYN_MAX 0xf #define SYN_CNT (SYN_MAX+1) /* * Keys and buttons * * Most of the keys/buttons are modeled after USB HUT 1.12 * (see http://www.usb.org/developers/hidpage). * Abbreviations in the comments: * AC - Application Control * AL - Application Launch Button * SC - System Control */ #define KEY_RESERVED 0 #define KEY_ESC 1 #define KEY_1 2 #define KEY_2 3 #define KEY_3 4 #define KEY_4 5 #define KEY_5 6 #define KEY_6 7 #define KEY_7 8 #define KEY_8 9 #define KEY_9 10 #define KEY_0 11 #define KEY_MINUS 12 #define KEY_EQUAL 13 #define KEY_BACKSPACE 14 #define KEY_TAB 15 #define KEY_Q 16 #define KEY_W 17 #define KEY_E 18 #define KEY_R 19 #define KEY_T 20 #define KEY_Y 21 #define KEY_U 22 #define KEY_I 23 #define KEY_O 24 #define KEY_P 25 #define KEY_LEFTBRACE 26 #define KEY_RIGHTBRACE 27 #define KEY_ENTER 28 #define KEY_LEFTCTRL 29 #define KEY_A 30 #define KEY_S 31 #define KEY_D 32 #define KEY_F 33 #define KEY_G 34 #define KEY_H 35 #define KEY_J 36 #define KEY_K 37 #define KEY_L 38 #define KEY_SEMICOLON 39 #define KEY_APOSTROPHE 40 #define KEY_GRAVE 41 #define KEY_LEFTSHIFT 42 #define KEY_BACKSLASH 43 #define KEY_Z 44 #define KEY_X 45 #define KEY_C 46 #define KEY_V 47 #define KEY_B 48 #define KEY_N 49 #define KEY_M 50 #define KEY_COMMA 51 #define KEY_DOT 52 #define KEY_SLASH 53 #define KEY_RIGHTSHIFT 54 #define KEY_KPASTERISK 55 #define KEY_LEFTALT 56 #define KEY_SPACE 57 #define KEY_CAPSLOCK 58 #define KEY_F1 59 #define KEY_F2 60 #define KEY_F3 61 #define KEY_F4 62 #define KEY_F5 63 #define KEY_F6 64 #define KEY_F7 65 #define KEY_F8 66 #define KEY_F9 67 #define KEY_F10 68 #define KEY_NUMLOCK 69 #define KEY_SCROLLLOCK 70 #define KEY_KP7 71 #define KEY_KP8 72 #define KEY_KP9 73 #define KEY_KPMINUS 74 #define KEY_KP4 75 #define KEY_KP5 76 #define KEY_KP6 77 #define KEY_KPPLUS 78 #define KEY_KP1 79 #define KEY_KP2 80 #define KEY_KP3 81 #define KEY_KP0 82 #define KEY_KPDOT 83 #define KEY_ZENKAKUHANKAKU 85 #define KEY_102ND 86 #define KEY_F11 87 #define KEY_F12 88 #define KEY_RO 89 #define KEY_KATAKANA 90 #define KEY_HIRAGANA 91 #define KEY_HENKAN 92 #define KEY_KATAKANAHIRAGANA 93 #define KEY_MUHENKAN 94 #define KEY_KPJPCOMMA 95 #define KEY_KPENTER 96 #define KEY_RIGHTCTRL 97 #define KEY_KPSLASH 98 #define KEY_SYSRQ 99 #define KEY_RIGHTALT 100 #define KEY_LINEFEED 101 #define KEY_HOME 102 #define KEY_UP 103 #define KEY_PAGEUP 104 #define KEY_LEFT 105 #define KEY_RIGHT 106 #define KEY_END 107 #define KEY_DOWN 108 #define KEY_PAGEDOWN 109 #define KEY_INSERT 110 #define KEY_DELETE 111 #define KEY_MACRO 112 #define KEY_MUTE 113 #define KEY_VOLUMEDOWN 114 #define KEY_VOLUMEUP 115 #define KEY_POWER 116 /* SC System Power Down */ #define KEY_KPEQUAL 117 #define KEY_KPPLUSMINUS 118 #define KEY_PAUSE 119 #define KEY_SCALE 120 /* AL Compiz Scale (Expose) */ #define KEY_KPCOMMA 121 #define KEY_HANGEUL 122 #define KEY_HANGUEL KEY_HANGEUL #define KEY_HANJA 123 #define KEY_YEN 124 #define KEY_LEFTMETA 125 #define KEY_RIGHTMETA 126 #define KEY_COMPOSE 127 #define KEY_STOP 128 /* AC Stop */ #define KEY_AGAIN 129 #define KEY_PROPS 130 /* AC Properties */ #define KEY_UNDO 131 /* AC Undo */ #define KEY_FRONT 132 #define KEY_COPY 133 /* AC Copy */ #define KEY_OPEN 134 /* AC Open */ #define KEY_PASTE 135 /* AC Paste */ #define KEY_FIND 136 /* AC Search */ #define KEY_CUT 137 /* AC Cut */ #define KEY_HELP 138 /* AL Integrated Help Center */ #define KEY_MENU 139 /* Menu (show menu) */ #define KEY_CALC 140 /* AL Calculator */ #define KEY_SETUP 141 #define KEY_SLEEP 142 /* SC System Sleep */ #define KEY_WAKEUP 143 /* System Wake Up */ #define KEY_FILE 144 /* AL Local Machine Browser */ #define KEY_SENDFILE 145 #define KEY_DELETEFILE 146 #define KEY_XFER 147 #define KEY_PROG1 148 #define KEY_PROG2 149 #define KEY_WWW 150 /* AL Internet Browser */ #define KEY_MSDOS 151 #define KEY_COFFEE 152 /* AL Terminal Lock/Screensaver */ #define KEY_SCREENLOCK KEY_COFFEE #define KEY_ROTATE_DISPLAY 153 /* Display orientation for e.g. tablets */ #define KEY_DIRECTION KEY_ROTATE_DISPLAY #define KEY_CYCLEWINDOWS 154 #define KEY_MAIL 155 #define KEY_BOOKMARKS 156 /* AC Bookmarks */ #define KEY_COMPUTER 157 #define KEY_BACK 158 /* AC Back */ #define KEY_FORWARD 159 /* AC Forward */ #define KEY_CLOSECD 160 #define KEY_EJECTCD 161 #define KEY_EJECTCLOSECD 162 #define KEY_NEXTSONG 163 #define KEY_PLAYPAUSE 164 #define KEY_PREVIOUSSONG 165 #define KEY_STOPCD 166 #define KEY_RECORD 167 #define KEY_REWIND 168 #define KEY_PHONE 169 /* Media Select Telephone */ #define KEY_ISO 170 #define KEY_CONFIG 171 /* AL Consumer Control Configuration */ #define KEY_HOMEPAGE 172 /* AC Home */ #define KEY_REFRESH 173 /* AC Refresh */ #define KEY_EXIT 174 /* AC Exit */ #define KEY_MOVE 175 #define KEY_EDIT 176 #define KEY_SCROLLUP 177 #define KEY_SCROLLDOWN 178 #define KEY_KPLEFTPAREN 179 #define KEY_KPRIGHTPAREN 180 #define KEY_NEW 181 /* AC New */ #define KEY_REDO 182 /* AC Redo/Repeat */ #define KEY_F13 183 #define KEY_F14 184 #define KEY_F15 185 #define KEY_F16 186 #define KEY_F17 187 #define KEY_F18 188 #define KEY_F19 189 #define KEY_F20 190 #define KEY_F21 191 #define KEY_F22 192 #define KEY_F23 193 #define KEY_F24 194 #define KEY_PLAYCD 200 #define KEY_PAUSECD 201 #define KEY_PROG3 202 #define KEY_PROG4 203 #define KEY_DASHBOARD 204 /* AL Dashboard */ #define KEY_SUSPEND 205 #define KEY_CLOSE 206 /* AC Close */ #define KEY_PLAY 207 #define KEY_FASTFORWARD 208 #define KEY_BASSBOOST 209 #define KEY_PRINT 210 /* AC Print */ #define KEY_HP 211 #define KEY_CAMERA 212 #define KEY_SOUND 213 #define KEY_QUESTION 214 #define KEY_EMAIL 215 #define KEY_CHAT 216 #define KEY_SEARCH 217 #define KEY_CONNECT 218 #define KEY_FINANCE 219 /* AL Checkbook/Finance */ #define KEY_SPORT 220 #define KEY_SHOP 221 #define KEY_ALTERASE 222 #define KEY_CANCEL 223 /* AC Cancel */ #define KEY_BRIGHTNESSDOWN 224 #define KEY_BRIGHTNESSUP 225 #define KEY_MEDIA 226 #define KEY_SWITCHVIDEOMODE 227 /* Cycle between available video outputs (Monitor/LCD/TV-out/etc) */ #define KEY_KBDILLUMTOGGLE 228 #define KEY_KBDILLUMDOWN 229 #define KEY_KBDILLUMUP 230 #define KEY_SEND 231 /* AC Send */ #define KEY_REPLY 232 /* AC Reply */ #define KEY_FORWARDMAIL 233 /* AC Forward Msg */ #define KEY_SAVE 234 /* AC Save */ #define KEY_DOCUMENTS 235 #define KEY_BATTERY 236 #define KEY_BLUETOOTH 237 #define KEY_WLAN 238 #define KEY_UWB 239 #define KEY_UNKNOWN 240 #define KEY_VIDEO_NEXT 241 /* drive next video source */ #define KEY_VIDEO_PREV 242 /* drive previous video source */ #define KEY_BRIGHTNESS_CYCLE 243 /* brightness up, after max is min */ #define KEY_BRIGHTNESS_AUTO 244 /* Set Auto Brightness: manual brightness control is off, rely on ambient */ #define KEY_BRIGHTNESS_ZERO KEY_BRIGHTNESS_AUTO #define KEY_DISPLAY_OFF 245 /* display device to off state */ #define KEY_WWAN 246 /* Wireless WAN (LTE, UMTS, GSM, etc.) */ #define KEY_WIMAX KEY_WWAN #define KEY_RFKILL 247 /* Key that controls all radios */ #define KEY_MICMUTE 248 /* Mute / unmute the microphone */ /* Code 255 is reserved for special needs of AT keyboard driver */ #define BTN_MISC 0x100 #define BTN_0 0x100 #define BTN_1 0x101 #define BTN_2 0x102 #define BTN_3 0x103 #define BTN_4 0x104 #define BTN_5 0x105 #define BTN_6 0x106 #define BTN_7 0x107 #define BTN_8 0x108 #define BTN_9 0x109 #define BTN_MOUSE 0x110 #define BTN_LEFT 0x110 #define BTN_RIGHT 0x111 #define BTN_MIDDLE 0x112 #define BTN_SIDE 0x113 #define BTN_EXTRA 0x114 #define BTN_FORWARD 0x115 #define BTN_BACK 0x116 #define BTN_TASK 0x117 #define BTN_JOYSTICK 0x120 #define BTN_TRIGGER 0x120 #define BTN_THUMB 0x121 #define BTN_THUMB2 0x122 #define BTN_TOP 0x123 #define BTN_TOP2 0x124 #define BTN_PINKIE 0x125 #define BTN_BASE 0x126 #define BTN_BASE2 0x127 #define BTN_BASE3 0x128 #define BTN_BASE4 0x129 #define BTN_BASE5 0x12a #define BTN_BASE6 0x12b #define BTN_DEAD 0x12f #define BTN_GAMEPAD 0x130 #define BTN_SOUTH 0x130 #define BTN_A BTN_SOUTH #define BTN_EAST 0x131 #define BTN_B BTN_EAST #define BTN_C 0x132 #define BTN_NORTH 0x133 #define BTN_X BTN_NORTH #define BTN_WEST 0x134 #define BTN_Y BTN_WEST #define BTN_Z 0x135 #define BTN_TL 0x136 #define BTN_TR 0x137 #define BTN_TL2 0x138 #define BTN_TR2 0x139 #define BTN_SELECT 0x13a #define BTN_START 0x13b #define BTN_MODE 0x13c #define BTN_THUMBL 0x13d #define BTN_THUMBR 0x13e #define BTN_DIGI 0x140 #define BTN_TOOL_PEN 0x140 #define BTN_TOOL_RUBBER 0x141 #define BTN_TOOL_BRUSH 0x142 #define BTN_TOOL_PENCIL 0x143 #define BTN_TOOL_AIRBRUSH 0x144 #define BTN_TOOL_FINGER 0x145 #define BTN_TOOL_MOUSE 0x146 #define BTN_TOOL_LENS 0x147 #define BTN_TOOL_QUINTTAP 0x148 /* Five fingers on trackpad */ #define BTN_STYLUS3 0x149 #define BTN_TOUCH 0x14a #define BTN_STYLUS 0x14b #define BTN_STYLUS2 0x14c #define BTN_TOOL_DOUBLETAP 0x14d #define BTN_TOOL_TRIPLETAP 0x14e #define BTN_TOOL_QUADTAP 0x14f /* Four fingers on trackpad */ #define BTN_WHEEL 0x150 #define BTN_GEAR_DOWN 0x150 #define BTN_GEAR_UP 0x151 #define KEY_OK 0x160 #define KEY_SELECT 0x161 #define KEY_GOTO 0x162 #define KEY_CLEAR 0x163 #define KEY_POWER2 0x164 #define KEY_OPTION 0x165 #define KEY_INFO 0x166 /* AL OEM Features/Tips/Tutorial */ #define KEY_TIME 0x167 #define KEY_VENDOR 0x168 #define KEY_ARCHIVE 0x169 #define KEY_PROGRAM 0x16a /* Media Select Program Guide */ #define KEY_CHANNEL 0x16b #define KEY_FAVORITES 0x16c #define KEY_EPG 0x16d #define KEY_PVR 0x16e /* Media Select Home */ #define KEY_MHP 0x16f #define KEY_LANGUAGE 0x170 #define KEY_TITLE 0x171 #define KEY_SUBTITLE 0x172 #define KEY_ANGLE 0x173 #define KEY_FULL_SCREEN 0x174 /* AC View Toggle */ #define KEY_ZOOM KEY_FULL_SCREEN #define KEY_MODE 0x175 #define KEY_KEYBOARD 0x176 #define KEY_ASPECT_RATIO 0x177 /* HUTRR37: Aspect */ #define KEY_SCREEN KEY_ASPECT_RATIO #define KEY_PC 0x178 /* Media Select Computer */ #define KEY_TV 0x179 /* Media Select TV */ #define KEY_TV2 0x17a /* Media Select Cable */ #define KEY_VCR 0x17b /* Media Select VCR */ #define KEY_VCR2 0x17c /* VCR Plus */ #define KEY_SAT 0x17d /* Media Select Satellite */ #define KEY_SAT2 0x17e #define KEY_CD 0x17f /* Media Select CD */ #define KEY_TAPE 0x180 /* Media Select Tape */ #define KEY_RADIO 0x181 #define KEY_TUNER 0x182 /* Media Select Tuner */ #define KEY_PLAYER 0x183 #define KEY_TEXT 0x184 #define KEY_DVD 0x185 /* Media Select DVD */ #define KEY_AUX 0x186 #define KEY_MP3 0x187 #define KEY_AUDIO 0x188 /* AL Audio Browser */ #define KEY_VIDEO 0x189 /* AL Movie Browser */ #define KEY_DIRECTORY 0x18a #define KEY_LIST 0x18b #define KEY_MEMO 0x18c /* Media Select Messages */ #define KEY_CALENDAR 0x18d #define KEY_RED 0x18e #define KEY_GREEN 0x18f #define KEY_YELLOW 0x190 #define KEY_BLUE 0x191 #define KEY_CHANNELUP 0x192 /* Channel Increment */ #define KEY_CHANNELDOWN 0x193 /* Channel Decrement */ #define KEY_FIRST 0x194 #define KEY_LAST 0x195 /* Recall Last */ #define KEY_AB 0x196 #define KEY_NEXT 0x197 #define KEY_RESTART 0x198 #define KEY_SLOW 0x199 #define KEY_SHUFFLE 0x19a #define KEY_BREAK 0x19b #define KEY_PREVIOUS 0x19c #define KEY_DIGITS 0x19d #define KEY_TEEN 0x19e #define KEY_TWEN 0x19f #define KEY_VIDEOPHONE 0x1a0 /* Media Select Video Phone */ #define KEY_GAMES 0x1a1 /* Media Select Games */ #define KEY_ZOOMIN 0x1a2 /* AC Zoom In */ #define KEY_ZOOMOUT 0x1a3 /* AC Zoom Out */ #define KEY_ZOOMRESET 0x1a4 /* AC Zoom */ #define KEY_WORDPROCESSOR 0x1a5 /* AL Word Processor */ #define KEY_EDITOR 0x1a6 /* AL Text Editor */ #define KEY_SPREADSHEET 0x1a7 /* AL Spreadsheet */ #define KEY_GRAPHICSEDITOR 0x1a8 /* AL Graphics Editor */ #define KEY_PRESENTATION 0x1a9 /* AL Presentation App */ #define KEY_DATABASE 0x1aa /* AL Database App */ #define KEY_NEWS 0x1ab /* AL Newsreader */ #define KEY_VOICEMAIL 0x1ac /* AL Voicemail */ #define KEY_ADDRESSBOOK 0x1ad /* AL Contacts/Address Book */ #define KEY_MESSENGER 0x1ae /* AL Instant Messaging */ #define KEY_DISPLAYTOGGLE 0x1af /* Turn display (LCD) on and off */ #define KEY_BRIGHTNESS_TOGGLE KEY_DISPLAYTOGGLE #define KEY_SPELLCHECK 0x1b0 /* AL Spell Check */ #define KEY_LOGOFF 0x1b1 /* AL Logoff */ #define KEY_DOLLAR 0x1b2 #define KEY_EURO 0x1b3 #define KEY_FRAMEBACK 0x1b4 /* Consumer - transport controls */ #define KEY_FRAMEFORWARD 0x1b5 #define KEY_CONTEXT_MENU 0x1b6 /* GenDesc - system context menu */ #define KEY_MEDIA_REPEAT 0x1b7 /* Consumer - transport control */ #define KEY_10CHANNELSUP 0x1b8 /* 10 channels up (10+) */ #define KEY_10CHANNELSDOWN 0x1b9 /* 10 channels down (10-) */ #define KEY_IMAGES 0x1ba /* AL Image Browser */ #define KEY_NOTIFICATION_CENTER 0x1bc /* Show/hide the notification center */ #define KEY_PICKUP_PHONE 0x1bd /* Answer incoming call */ #define KEY_HANGUP_PHONE 0x1be /* Decline incoming call */ #define KEY_DEL_EOL 0x1c0 #define KEY_DEL_EOS 0x1c1 #define KEY_INS_LINE 0x1c2 #define KEY_DEL_LINE 0x1c3 #define KEY_FN 0x1d0 #define KEY_FN_ESC 0x1d1 #define KEY_FN_F1 0x1d2 #define KEY_FN_F2 0x1d3 #define KEY_FN_F3 0x1d4 #define KEY_FN_F4 0x1d5 #define KEY_FN_F5 0x1d6 #define KEY_FN_F6 0x1d7 #define KEY_FN_F7 0x1d8 #define KEY_FN_F8 0x1d9 #define KEY_FN_F9 0x1da #define KEY_FN_F10 0x1db #define KEY_FN_F11 0x1dc #define KEY_FN_F12 0x1dd #define KEY_FN_1 0x1de #define KEY_FN_2 0x1df #define KEY_FN_D 0x1e0 #define KEY_FN_E 0x1e1 #define KEY_FN_F 0x1e2 #define KEY_FN_S 0x1e3 #define KEY_FN_B 0x1e4 #define KEY_FN_RIGHT_SHIFT 0x1e5 #define KEY_BRL_DOT1 0x1f1 #define KEY_BRL_DOT2 0x1f2 #define KEY_BRL_DOT3 0x1f3 #define KEY_BRL_DOT4 0x1f4 #define KEY_BRL_DOT5 0x1f5 #define KEY_BRL_DOT6 0x1f6 #define KEY_BRL_DOT7 0x1f7 #define KEY_BRL_DOT8 0x1f8 #define KEY_BRL_DOT9 0x1f9 #define KEY_BRL_DOT10 0x1fa #define KEY_NUMERIC_0 0x200 /* used by phones, remote controls, */ #define KEY_NUMERIC_1 0x201 /* and other keypads */ #define KEY_NUMERIC_2 0x202 #define KEY_NUMERIC_3 0x203 #define KEY_NUMERIC_4 0x204 #define KEY_NUMERIC_5 0x205 #define KEY_NUMERIC_6 0x206 #define KEY_NUMERIC_7 0x207 #define KEY_NUMERIC_8 0x208 #define KEY_NUMERIC_9 0x209 #define KEY_NUMERIC_STAR 0x20a #define KEY_NUMERIC_POUND 0x20b #define KEY_NUMERIC_A 0x20c /* Phone key A - HUT Telephony 0xb9 */ #define KEY_NUMERIC_B 0x20d #define KEY_NUMERIC_C 0x20e #define KEY_NUMERIC_D 0x20f #define KEY_CAMERA_FOCUS 0x210 #define KEY_WPS_BUTTON 0x211 /* WiFi Protected Setup key */ #define KEY_TOUCHPAD_TOGGLE 0x212 /* Request switch touchpad on or off */ #define KEY_TOUCHPAD_ON 0x213 #define KEY_TOUCHPAD_OFF 0x214 #define KEY_CAMERA_ZOOMIN 0x215 #define KEY_CAMERA_ZOOMOUT 0x216 #define KEY_CAMERA_UP 0x217 #define KEY_CAMERA_DOWN 0x218 #define KEY_CAMERA_LEFT 0x219 #define KEY_CAMERA_RIGHT 0x21a #define KEY_ATTENDANT_ON 0x21b #define KEY_ATTENDANT_OFF 0x21c #define KEY_ATTENDANT_TOGGLE 0x21d /* Attendant call on or off */ #define KEY_LIGHTS_TOGGLE 0x21e /* Reading light on or off */ #define BTN_DPAD_UP 0x220 #define BTN_DPAD_DOWN 0x221 #define BTN_DPAD_LEFT 0x222 #define BTN_DPAD_RIGHT 0x223 #define KEY_ALS_TOGGLE 0x230 /* Ambient light sensor */ #define KEY_ROTATE_LOCK_TOGGLE 0x231 /* Display rotation lock */ #define KEY_BUTTONCONFIG 0x240 /* AL Button Configuration */ #define KEY_TASKMANAGER 0x241 /* AL Task/Project Manager */ #define KEY_JOURNAL 0x242 /* AL Log/Journal/Timecard */ #define KEY_CONTROLPANEL 0x243 /* AL Control Panel */ #define KEY_APPSELECT 0x244 /* AL Select Task/Application */ #define KEY_SCREENSAVER 0x245 /* AL Screen Saver */ #define KEY_VOICECOMMAND 0x246 /* Listening Voice Command */ #define KEY_ASSISTANT 0x247 /* AL Context-aware desktop assistant */ #define KEY_KBD_LAYOUT_NEXT 0x248 /* AC Next Keyboard Layout Select */ #define KEY_EMOJI_PICKER 0x249 /* Show/hide emoji picker (HUTRR101) */ #define KEY_BRIGHTNESS_MIN 0x250 /* Set Brightness to Minimum */ #define KEY_BRIGHTNESS_MAX 0x251 /* Set Brightness to Maximum */ #define KEY_KBDINPUTASSIST_PREV 0x260 #define KEY_KBDINPUTASSIST_NEXT 0x261 #define KEY_KBDINPUTASSIST_PREVGROUP 0x262 #define KEY_KBDINPUTASSIST_NEXTGROUP 0x263 #define KEY_KBDINPUTASSIST_ACCEPT 0x264 #define KEY_KBDINPUTASSIST_CANCEL 0x265 /* Diagonal movement keys */ #define KEY_RIGHT_UP 0x266 #define KEY_RIGHT_DOWN 0x267 #define KEY_LEFT_UP 0x268 #define KEY_LEFT_DOWN 0x269 #define KEY_ROOT_MENU 0x26a /* Show Device's Root Menu */ /* Show Top Menu of the Media (e.g. DVD) */ #define KEY_MEDIA_TOP_MENU 0x26b #define KEY_NUMERIC_11 0x26c #define KEY_NUMERIC_12 0x26d /* * Toggle Audio Description: refers to an audio service that helps blind and * visually impaired consumers understand the action in a program. Note: in * some countries this is referred to as "Video Description". */ #define KEY_AUDIO_DESC 0x26e #define KEY_3D_MODE 0x26f #define KEY_NEXT_FAVORITE 0x270 #define KEY_STOP_RECORD 0x271 #define KEY_PAUSE_RECORD 0x272 #define KEY_VOD 0x273 /* Video on Demand */ #define KEY_UNMUTE 0x274 #define KEY_FASTREVERSE 0x275 #define KEY_SLOWREVERSE 0x276 /* * Control a data application associated with the currently viewed channel, * e.g. teletext or data broadcast application (MHEG, MHP, HbbTV, etc.) */ #define KEY_DATA 0x277 #define KEY_ONSCREEN_KEYBOARD 0x278 /* Electronic privacy screen control */ #define KEY_PRIVACY_SCREEN_TOGGLE 0x279 /* Select an area of screen to be copied */ #define KEY_SELECTIVE_SCREENSHOT 0x27a /* * Some keyboards have keys which do not have a defined meaning, these keys * are intended to be programmed / bound to macros by the user. For most * keyboards with these macro-keys the key-sequence to inject, or action to * take, is all handled by software on the host side. So from the kernel's * point of view these are just normal keys. * * The KEY_MACRO# codes below are intended for such keys, which may be labeled * e.g. G1-G18, or S1 - S30. The KEY_MACRO# codes MUST NOT be used for keys * where the marking on the key does indicate a defined meaning / purpose. * * The KEY_MACRO# codes MUST also NOT be used as fallback for when no existing * KEY_FOO define matches the marking / purpose. In this case a new KEY_FOO * define MUST be added. */ #define KEY_MACRO1 0x290 #define KEY_MACRO2 0x291 #define KEY_MACRO3 0x292 #define KEY_MACRO4 0x293 #define KEY_MACRO5 0x294 #define KEY_MACRO6 0x295 #define KEY_MACRO7 0x296 #define KEY_MACRO8 0x297 #define KEY_MACRO9 0x298 #define KEY_MACRO10 0x299 #define KEY_MACRO11 0x29a #define KEY_MACRO12 0x29b #define KEY_MACRO13 0x29c #define KEY_MACRO14 0x29d #define KEY_MACRO15 0x29e #define KEY_MACRO16 0x29f #define KEY_MACRO17 0x2a0 #define KEY_MACRO18 0x2a1 #define KEY_MACRO19 0x2a2 #define KEY_MACRO20 0x2a3 #define KEY_MACRO21 0x2a4 #define KEY_MACRO22 0x2a5 #define KEY_MACRO23 0x2a6 #define KEY_MACRO24 0x2a7 #define KEY_MACRO25 0x2a8 #define KEY_MACRO26 0x2a9 #define KEY_MACRO27 0x2aa #define KEY_MACRO28 0x2ab #define KEY_MACRO29 0x2ac #define KEY_MACRO30 0x2ad /* * Some keyboards with the macro-keys described above have some extra keys * for controlling the host-side software responsible for the macro handling: * -A macro recording start/stop key. Note that not all keyboards which emit * KEY_MACRO_RECORD_START will also emit KEY_MACRO_RECORD_STOP if * KEY_MACRO_RECORD_STOP is not advertised, then KEY_MACRO_RECORD_START * should be interpreted as a recording start/stop toggle; * -Keys for switching between different macro (pre)sets, either a key for * cycling through the configured presets or keys to directly select a preset. */ #define KEY_MACRO_RECORD_START 0x2b0 #define KEY_MACRO_RECORD_STOP 0x2b1 #define KEY_MACRO_PRESET_CYCLE 0x2b2 #define KEY_MACRO_PRESET1 0x2b3 #define KEY_MACRO_PRESET2 0x2b4 #define KEY_MACRO_PRESET3 0x2b5 /* * Some keyboards have a buildin LCD panel where the contents are controlled * by the host. Often these have a number of keys directly below the LCD * intended for controlling a menu shown on the LCD. These keys often don't * have any labeling so we just name them KEY_KBD_LCD_MENU# */ #define KEY_KBD_LCD_MENU1 0x2b8 #define KEY_KBD_LCD_MENU2 0x2b9 #define KEY_KBD_LCD_MENU3 0x2ba #define KEY_KBD_LCD_MENU4 0x2bb #define KEY_KBD_LCD_MENU5 0x2bc #define BTN_TRIGGER_HAPPY 0x2c0 #define BTN_TRIGGER_HAPPY1 0x2c0 #define BTN_TRIGGER_HAPPY2 0x2c1 #define BTN_TRIGGER_HAPPY3 0x2c2 #define BTN_TRIGGER_HAPPY4 0x2c3 #define BTN_TRIGGER_HAPPY5 0x2c4 #define BTN_TRIGGER_HAPPY6 0x2c5 #define BTN_TRIGGER_HAPPY7 0x2c6 #define BTN_TRIGGER_HAPPY8 0x2c7 #define BTN_TRIGGER_HAPPY9 0x2c8 #define BTN_TRIGGER_HAPPY10 0x2c9 #define BTN_TRIGGER_HAPPY11 0x2ca #define BTN_TRIGGER_HAPPY12 0x2cb #define BTN_TRIGGER_HAPPY13 0x2cc #define BTN_TRIGGER_HAPPY14 0x2cd #define BTN_TRIGGER_HAPPY15 0x2ce #define BTN_TRIGGER_HAPPY16 0x2cf #define BTN_TRIGGER_HAPPY17 0x2d0 #define BTN_TRIGGER_HAPPY18 0x2d1 #define BTN_TRIGGER_HAPPY19 0x2d2 #define BTN_TRIGGER_HAPPY20 0x2d3 #define BTN_TRIGGER_HAPPY21 0x2d4 #define BTN_TRIGGER_HAPPY22 0x2d5 #define BTN_TRIGGER_HAPPY23 0x2d6 #define BTN_TRIGGER_HAPPY24 0x2d7 #define BTN_TRIGGER_HAPPY25 0x2d8 #define BTN_TRIGGER_HAPPY26 0x2d9 #define BTN_TRIGGER_HAPPY27 0x2da #define BTN_TRIGGER_HAPPY28 0x2db #define BTN_TRIGGER_HAPPY29 0x2dc #define BTN_TRIGGER_HAPPY30 0x2dd #define BTN_TRIGGER_HAPPY31 0x2de #define BTN_TRIGGER_HAPPY32 0x2df #define BTN_TRIGGER_HAPPY33 0x2e0 #define BTN_TRIGGER_HAPPY34 0x2e1 #define BTN_TRIGGER_HAPPY35 0x2e2 #define BTN_TRIGGER_HAPPY36 0x2e3 #define BTN_TRIGGER_HAPPY37 0x2e4 #define BTN_TRIGGER_HAPPY38 0x2e5 #define BTN_TRIGGER_HAPPY39 0x2e6 #define BTN_TRIGGER_HAPPY40 0x2e7 /* We avoid low common keys in module aliases so they don't get huge. */ #define KEY_MIN_INTERESTING KEY_MUTE #define KEY_MAX 0x2ff #define KEY_CNT (KEY_MAX+1) /* * Relative axes */ #define REL_X 0x00 #define REL_Y 0x01 #define REL_Z 0x02 #define REL_RX 0x03 #define REL_RY 0x04 #define REL_RZ 0x05 #define REL_HWHEEL 0x06 #define REL_DIAL 0x07 #define REL_WHEEL 0x08 #define REL_MISC 0x09 /* * 0x0a is reserved and should not be used in input drivers. * It was used by HID as REL_MISC+1 and userspace needs to detect if * the next REL_* event is correct or is just REL_MISC + n. * We define here REL_RESERVED so userspace can rely on it and detect * the situation described above. */ #define REL_RESERVED 0x0a #define REL_WHEEL_HI_RES 0x0b #define REL_HWHEEL_HI_RES 0x0c #define REL_MAX 0x0f #define REL_CNT (REL_MAX+1) /* * Absolute axes */ #define ABS_X 0x00 #define ABS_Y 0x01 #define ABS_Z 0x02 #define ABS_RX 0x03 #define ABS_RY 0x04 #define ABS_RZ 0x05 #define ABS_THROTTLE 0x06 #define ABS_RUDDER 0x07 #define ABS_WHEEL 0x08 #define ABS_GAS 0x09 #define ABS_BRAKE 0x0a #define ABS_HAT0X 0x10 #define ABS_HAT0Y 0x11 #define ABS_HAT1X 0x12 #define ABS_HAT1Y 0x13 #define ABS_HAT2X 0x14 #define ABS_HAT2Y 0x15 #define ABS_HAT3X 0x16 #define ABS_HAT3Y 0x17 #define ABS_PRESSURE 0x18 #define ABS_DISTANCE 0x19 #define ABS_TILT_X 0x1a #define ABS_TILT_Y 0x1b #define ABS_TOOL_WIDTH 0x1c #define ABS_VOLUME 0x20 #define ABS_MISC 0x28 /* * 0x2e is reserved and should not be used in input drivers. * It was used by HID as ABS_MISC+6 and userspace needs to detect if * the next ABS_* event is correct or is just ABS_MISC + n. * We define here ABS_RESERVED so userspace can rely on it and detect * the situation described above. */ #define ABS_RESERVED 0x2e #define ABS_MT_SLOT 0x2f /* MT slot being modified */ #define ABS_MT_TOUCH_MAJOR 0x30 /* Major axis of touching ellipse */ #define ABS_MT_TOUCH_MINOR 0x31 /* Minor axis (omit if circular) */ #define ABS_MT_WIDTH_MAJOR 0x32 /* Major axis of approaching ellipse */ #define ABS_MT_WIDTH_MINOR 0x33 /* Minor axis (omit if circular) */ #define ABS_MT_ORIENTATION 0x34 /* Ellipse orientation */ #define ABS_MT_POSITION_X 0x35 /* Center X touch position */ #define ABS_MT_POSITION_Y 0x36 /* Center Y touch position */ #define ABS_MT_TOOL_TYPE 0x37 /* Type of touching device */ #define ABS_MT_BLOB_ID 0x38 /* Group a set of packets as a blob */ #define ABS_MT_TRACKING_ID 0x39 /* Unique ID of initiated contact */ #define ABS_MT_PRESSURE 0x3a /* Pressure on contact area */ #define ABS_MT_DISTANCE 0x3b /* Contact hover distance */ #define ABS_MT_TOOL_X 0x3c /* Center X tool position */ #define ABS_MT_TOOL_Y 0x3d /* Center Y tool position */ #define ABS_MAX 0x3f #define ABS_CNT (ABS_MAX+1) /* * Switch events */ #define SW_LID 0x00 /* set = lid shut */ #define SW_TABLET_MODE 0x01 /* set = tablet mode */ #define SW_HEADPHONE_INSERT 0x02 /* set = inserted */ #define SW_RFKILL_ALL 0x03 /* rfkill master switch, type "any" set = radio enabled */ #define SW_RADIO SW_RFKILL_ALL /* deprecated */ #define SW_MICROPHONE_INSERT 0x04 /* set = inserted */ #define SW_DOCK 0x05 /* set = plugged into dock */ #define SW_LINEOUT_INSERT 0x06 /* set = inserted */ #define SW_JACK_PHYSICAL_INSERT 0x07 /* set = mechanical switch set */ #define SW_VIDEOOUT_INSERT 0x08 /* set = inserted */ #define SW_CAMERA_LENS_COVER 0x09 /* set = lens covered */ #define SW_KEYPAD_SLIDE 0x0a /* set = keypad slide out */ #define SW_FRONT_PROXIMITY 0x0b /* set = front proximity sensor active */ #define SW_ROTATE_LOCK 0x0c /* set = rotate locked/disabled */ #define SW_LINEIN_INSERT 0x0d /* set = inserted */ #define SW_MUTE_DEVICE 0x0e /* set = device disabled */ #define SW_PEN_INSERTED 0x0f /* set = pen inserted */ #define SW_MACHINE_COVER 0x10 /* set = cover closed */ #define SW_MAX 0x10 #define SW_CNT (SW_MAX+1) /* * Misc events */ #define MSC_SERIAL 0x00 #define MSC_PULSELED 0x01 #define MSC_GESTURE 0x02 #define MSC_RAW 0x03 #define MSC_SCAN 0x04 #define MSC_TIMESTAMP 0x05 #define MSC_MAX 0x07 #define MSC_CNT (MSC_MAX+1) /* * LEDs */ #define LED_NUML 0x00 #define LED_CAPSL 0x01 #define LED_SCROLLL 0x02 #define LED_COMPOSE 0x03 #define LED_KANA 0x04 #define LED_SLEEP 0x05 #define LED_SUSPEND 0x06 #define LED_MUTE 0x07 #define LED_MISC 0x08 #define LED_MAIL 0x09 #define LED_CHARGING 0x0a #define LED_MAX 0x0f #define LED_CNT (LED_MAX+1) /* * Autorepeat values */ #define REP_DELAY 0x00 #define REP_PERIOD 0x01 #define REP_MAX 0x01 #define REP_CNT (REP_MAX+1) /* * Sounds */ #define SND_CLICK 0x00 #define SND_BELL 0x01 #define SND_TONE 0x02 #define SND_MAX 0x07 #define SND_CNT (SND_MAX+1) #endif linux/zorro.h000064400000006340151027430560007235 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/zorro.h -- Amiga AutoConfig (Zorro) Bus Definitions * * Copyright (C) 1995--2003 Geert Uytterhoeven * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. */ #ifndef _LINUX_ZORRO_H #define _LINUX_ZORRO_H #include /* * Each Zorro board has a 32-bit ID of the form * * mmmmmmmmmmmmmmmmppppppppeeeeeeee * * with * * mmmmmmmmmmmmmmmm 16-bit Manufacturer ID (assigned by CBM (sigh)) * pppppppp 8-bit Product ID (assigned by manufacturer) * eeeeeeee 8-bit Extended Product ID (currently only used * for some GVP boards) */ #define ZORRO_MANUF(id) ((id) >> 16) #define ZORRO_PROD(id) (((id) >> 8) & 0xff) #define ZORRO_EPC(id) ((id) & 0xff) #define ZORRO_ID(manuf, prod, epc) \ ((ZORRO_MANUF_##manuf << 16) | ((prod) << 8) | (epc)) typedef __u32 zorro_id; /* Include the ID list */ #include /* * GVP identifies most of its products through the 'extended product code' * (epc). The epc has to be ANDed with the GVP_PRODMASK before the * identification. */ #define GVP_PRODMASK (0xf8) #define GVP_SCSICLKMASK (0x01) enum GVP_flags { GVP_IO = 0x01, GVP_ACCEL = 0x02, GVP_SCSI = 0x04, GVP_24BITDMA = 0x08, GVP_25BITDMA = 0x10, GVP_NOBANK = 0x20, GVP_14MHZ = 0x40, }; struct Node { __be32 ln_Succ; /* Pointer to next (successor) */ __be32 ln_Pred; /* Pointer to previous (predecessor) */ __u8 ln_Type; __s8 ln_Pri; /* Priority, for sorting */ __be32 ln_Name; /* ID string, null terminated */ } __attribute__((packed)); struct ExpansionRom { /* -First 16 bytes of the expansion ROM */ __u8 er_Type; /* Board type, size and flags */ __u8 er_Product; /* Product number, assigned by manufacturer */ __u8 er_Flags; /* Flags */ __u8 er_Reserved03; /* Must be zero ($ff inverted) */ __be16 er_Manufacturer; /* Unique ID, ASSIGNED BY COMMODORE-AMIGA! */ __be32 er_SerialNumber; /* Available for use by manufacturer */ __be16 er_InitDiagVec; /* Offset to optional "DiagArea" structure */ __u8 er_Reserved0c; __u8 er_Reserved0d; __u8 er_Reserved0e; __u8 er_Reserved0f; } __attribute__((packed)); /* er_Type board type bits */ #define ERT_TYPEMASK 0xc0 #define ERT_ZORROII 0xc0 #define ERT_ZORROIII 0x80 /* other bits defined in er_Type */ #define ERTB_MEMLIST 5 /* Link RAM into free memory list */ #define ERTF_MEMLIST (1<<5) struct ConfigDev { struct Node cd_Node; __u8 cd_Flags; /* (read/write) */ __u8 cd_Pad; /* reserved */ struct ExpansionRom cd_Rom; /* copy of board's expansion ROM */ __be32 cd_BoardAddr; /* where in memory the board was placed */ __be32 cd_BoardSize; /* size of board in bytes */ __be16 cd_SlotAddr; /* which slot number (PRIVATE) */ __be16 cd_SlotSize; /* number of slots (PRIVATE) */ __be32 cd_Driver; /* pointer to node of driver */ __be32 cd_NextCD; /* linked list of drivers to config */ __be32 cd_Unused[4]; /* for whatever the driver wants */ } __attribute__((packed)); #define ZORRO_NUM_AUTO 16 #endif /* _LINUX_ZORRO_H */ linux/atm_nicstar.h000064400000002376151027430560010373 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /****************************************************************************** * * atm_nicstar.h * * Driver-specific declarations for use by NICSTAR driver specific utils. * * Author: Rui Prior * * (C) INESC 1998 * ******************************************************************************/ #ifndef LINUX_ATM_NICSTAR_H #define LINUX_ATM_NICSTAR_H /* Note: non-kernel programs including this file must also include * sys/types.h for struct timeval */ #include #include #define NS_GETPSTAT _IOWR('a',ATMIOC_SARPRV+1,struct atmif_sioc) /* get pool statistics */ #define NS_SETBUFLEV _IOW('a',ATMIOC_SARPRV+2,struct atmif_sioc) /* set buffer level markers */ #define NS_ADJBUFLEV _IO('a',ATMIOC_SARPRV+3) /* adjust buffer level */ typedef struct buf_nr { unsigned min; unsigned init; unsigned max; }buf_nr; typedef struct pool_levels { int buftype; int count; /* (At least for now) only used in NS_GETPSTAT */ buf_nr level; } pool_levels; /* type must be one of the following: */ #define NS_BUFTYPE_SMALL 1 #define NS_BUFTYPE_LARGE 2 #define NS_BUFTYPE_HUGE 3 #define NS_BUFTYPE_IOVEC 4 #endif /* LINUX_ATM_NICSTAR_H */ linux/dn.h000064400000011042151027430560006456 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_DN_H #define _LINUX_DN_H #include #include #include /* DECnet Data Structures and Constants */ /* * DNPROTO_NSP can't be the same as SOL_SOCKET, * so increment each by one (compared to ULTRIX) */ #define DNPROTO_NSP 2 /* NSP protocol number */ #define DNPROTO_ROU 3 /* Routing protocol number */ #define DNPROTO_NML 4 /* Net mgt protocol number */ #define DNPROTO_EVL 5 /* Evl protocol number (usr) */ #define DNPROTO_EVR 6 /* Evl protocol number (evl) */ #define DNPROTO_NSPT 7 /* NSP trace protocol number */ #define DN_ADDL 2 #define DN_MAXADDL 2 /* ULTRIX headers have 20 here, but pathworks has 2 */ #define DN_MAXOPTL 16 #define DN_MAXOBJL 16 #define DN_MAXACCL 40 #define DN_MAXALIASL 128 #define DN_MAXNODEL 256 #define DNBUFSIZE 65023 /* * SET/GET Socket options - must match the DSO_ numbers below */ #define SO_CONDATA 1 #define SO_CONACCESS 2 #define SO_PROXYUSR 3 #define SO_LINKINFO 7 #define DSO_CONDATA 1 /* Set/Get connect data */ #define DSO_DISDATA 10 /* Set/Get disconnect data */ #define DSO_CONACCESS 2 /* Set/Get connect access data */ #define DSO_ACCEPTMODE 4 /* Set/Get accept mode */ #define DSO_CONACCEPT 5 /* Accept deferred connection */ #define DSO_CONREJECT 6 /* Reject deferred connection */ #define DSO_LINKINFO 7 /* Set/Get link information */ #define DSO_STREAM 8 /* Set socket type to stream */ #define DSO_SEQPACKET 9 /* Set socket type to sequenced packet */ #define DSO_MAXWINDOW 11 /* Maximum window size allowed */ #define DSO_NODELAY 12 /* Turn off nagle */ #define DSO_CORK 13 /* Wait for more data! */ #define DSO_SERVICES 14 /* NSP Services field */ #define DSO_INFO 15 /* NSP Info field */ #define DSO_MAX 15 /* Maximum option number */ /* LINK States */ #define LL_INACTIVE 0 #define LL_CONNECTING 1 #define LL_RUNNING 2 #define LL_DISCONNECTING 3 #define ACC_IMMED 0 #define ACC_DEFER 1 #define SDF_WILD 1 /* Wild card object */ #define SDF_PROXY 2 /* Addr eligible for proxy */ #define SDF_UICPROXY 4 /* Use uic-based proxy */ /* Structures */ struct dn_naddr { __le16 a_len; __u8 a_addr[DN_MAXADDL]; /* Two bytes little endian */ }; struct sockaddr_dn { __u16 sdn_family; __u8 sdn_flags; __u8 sdn_objnum; __le16 sdn_objnamel; __u8 sdn_objname[DN_MAXOBJL]; struct dn_naddr sdn_add; }; #define sdn_nodeaddrl sdn_add.a_len /* Node address length */ #define sdn_nodeaddr sdn_add.a_addr /* Node address */ /* * DECnet set/get DSO_CONDATA, DSO_DISDATA (optional data) structure */ struct optdata_dn { __le16 opt_status; /* Extended status return */ #define opt_sts opt_status __le16 opt_optl; /* Length of user data */ __u8 opt_data[16]; /* User data */ }; struct accessdata_dn { __u8 acc_accl; __u8 acc_acc[DN_MAXACCL]; __u8 acc_passl; __u8 acc_pass[DN_MAXACCL]; __u8 acc_userl; __u8 acc_user[DN_MAXACCL]; }; /* * DECnet logical link information structure */ struct linkinfo_dn { __u16 idn_segsize; /* Segment size for link */ __u8 idn_linkstate; /* Logical link state */ }; /* * Ethernet address format (for DECnet) */ union etheraddress { __u8 dne_addr[ETH_ALEN]; /* Full ethernet address */ struct { __u8 dne_hiord[4]; /* DECnet HIORD prefix */ __u8 dne_nodeaddr[2]; /* DECnet node address */ } dne_remote; }; /* * DECnet physical socket address format */ struct dn_addr { __le16 dna_family; /* AF_DECnet */ union etheraddress dna_netaddr; /* DECnet ethernet address */ }; #define DECNET_IOCTL_BASE 0x89 /* PROTOPRIVATE range */ #define SIOCSNETADDR _IOW(DECNET_IOCTL_BASE, 0xe0, struct dn_naddr) #define SIOCGNETADDR _IOR(DECNET_IOCTL_BASE, 0xe1, struct dn_naddr) #define OSIOCSNETADDR _IOW(DECNET_IOCTL_BASE, 0xe0, int) #define OSIOCGNETADDR _IOR(DECNET_IOCTL_BASE, 0xe1, int) #endif /* _LINUX_DN_H */ linux/memfd.h000064400000002454151027430560007154 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MEMFD_H #define _LINUX_MEMFD_H #include /* flags for memfd_create(2) (unsigned int) */ #define MFD_CLOEXEC 0x0001U #define MFD_ALLOW_SEALING 0x0002U #define MFD_HUGETLB 0x0004U /* * Huge page size encoding when MFD_HUGETLB is specified, and a huge page * size other than the default is desired. See hugetlb_encode.h. * All known huge page size encodings are provided here. It is the * responsibility of the application to know which sizes are supported on * the running system. See mmap(2) man page for details. */ #define MFD_HUGE_SHIFT HUGETLB_FLAG_ENCODE_SHIFT #define MFD_HUGE_MASK HUGETLB_FLAG_ENCODE_MASK #define MFD_HUGE_64KB HUGETLB_FLAG_ENCODE_64KB #define MFD_HUGE_512KB HUGETLB_FLAG_ENCODE_512KB #define MFD_HUGE_1MB HUGETLB_FLAG_ENCODE_1MB #define MFD_HUGE_2MB HUGETLB_FLAG_ENCODE_2MB #define MFD_HUGE_8MB HUGETLB_FLAG_ENCODE_8MB #define MFD_HUGE_16MB HUGETLB_FLAG_ENCODE_16MB #define MFD_HUGE_32MB HUGETLB_FLAG_ENCODE_32MB #define MFD_HUGE_256MB HUGETLB_FLAG_ENCODE_256MB #define MFD_HUGE_512MB HUGETLB_FLAG_ENCODE_512MB #define MFD_HUGE_1GB HUGETLB_FLAG_ENCODE_1GB #define MFD_HUGE_2GB HUGETLB_FLAG_ENCODE_2GB #define MFD_HUGE_16GB HUGETLB_FLAG_ENCODE_16GB #endif /* _LINUX_MEMFD_H */ linux/isst_if.h000064400000012410151027430560007515 0ustar00/* SPDX-License-Identifier: GPL-2.0 */ /* * Intel Speed Select Interface: OS to hardware Interface * Copyright (c) 2019, Intel Corporation. * All rights reserved. * * Author: Srinivas Pandruvada */ #ifndef __ISST_IF_H #define __ISST_IF_H #include /** * struct isst_if_platform_info - Define platform information * @api_version: Version of the firmware document, which this driver * can communicate * @driver_version: Driver version, which will help user to send right * commands. Even if the firmware is capable, driver may * not be ready * @max_cmds_per_ioctl: Returns the maximum number of commands driver will * accept in a single ioctl * @mbox_supported: Support of mail box interface * @mmio_supported: Support of mmio interface for core-power feature * * Used to return output of IOCTL ISST_IF_GET_PLATFORM_INFO. This * information can be used by the user space, to get the driver, firmware * support and also number of commands to send in a single IOCTL request. */ struct isst_if_platform_info { __u16 api_version; __u16 driver_version; __u16 max_cmds_per_ioctl; __u8 mbox_supported; __u8 mmio_supported; }; /** * struct isst_if_cpu_map - CPU mapping between logical and physical CPU * @logical_cpu: Linux logical CPU number * @physical_cpu: PUNIT CPU number * * Used to convert from Linux logical CPU to PUNIT CPU numbering scheme. * The PUNIT CPU number is different than APIC ID based CPU numbering. */ struct isst_if_cpu_map { __u32 logical_cpu; __u32 physical_cpu; }; /** * struct isst_if_cpu_maps - structure for CPU map IOCTL * @cmd_count: Number of CPU mapping command in cpu_map[] * @cpu_map[]: Holds one or more CPU map data structure * * This structure used with ioctl ISST_IF_GET_PHY_ID to send * one or more CPU mapping commands. Here IOCTL return value indicates * number of commands sent or error number if no commands have been sent. */ struct isst_if_cpu_maps { __u32 cmd_count; struct isst_if_cpu_map cpu_map[1]; }; /** * struct isst_if_io_reg - Read write PUNIT IO register * @read_write: Value 0: Read, 1: Write * @logical_cpu: Logical CPU number to get target PCI device. * @reg: PUNIT register offset * @value: For write operation value to write and for * for read placeholder read value * * Structure to specify read/write data to PUNIT registers. */ struct isst_if_io_reg { __u32 read_write; /* Read:0, Write:1 */ __u32 logical_cpu; __u32 reg; __u32 value; }; /** * struct isst_if_io_regs - structure for IO register commands * @cmd_count: Number of io reg commands in io_reg[] * @io_reg[]: Holds one or more io_reg command structure * * This structure used with ioctl ISST_IF_IO_CMD to send * one or more read/write commands to PUNIT. Here IOCTL return value * indicates number of requests sent or error number if no requests have * been sent. */ struct isst_if_io_regs { __u32 req_count; struct isst_if_io_reg io_reg[1]; }; /** * struct isst_if_mbox_cmd - Structure to define mail box command * @logical_cpu: Logical CPU number to get target PCI device * @parameter: Mailbox parameter value * @req_data: Request data for the mailbox * @resp_data: Response data for mailbox command response * @command: Mailbox command value * @sub_command: Mailbox sub command value * @reserved: Unused, set to 0 * * Structure to specify mailbox command to be sent to PUNIT. */ struct isst_if_mbox_cmd { __u32 logical_cpu; __u32 parameter; __u32 req_data; __u32 resp_data; __u16 command; __u16 sub_command; __u32 reserved; }; /** * struct isst_if_mbox_cmds - structure for mailbox commands * @cmd_count: Number of mailbox commands in mbox_cmd[] * @mbox_cmd[]: Holds one or more mbox commands * * This structure used with ioctl ISST_IF_MBOX_COMMAND to send * one or more mailbox commands to PUNIT. Here IOCTL return value * indicates number of commands sent or error number if no commands have * been sent. */ struct isst_if_mbox_cmds { __u32 cmd_count; struct isst_if_mbox_cmd mbox_cmd[1]; }; /** * struct isst_if_msr_cmd - Structure to define msr command * @read_write: Value 0: Read, 1: Write * @logical_cpu: Logical CPU number * @msr: MSR number * @data: For write operation, data to write, for read * place holder * * Structure to specify MSR command related to PUNIT. */ struct isst_if_msr_cmd { __u32 read_write; /* Read:0, Write:1 */ __u32 logical_cpu; __u64 msr; __u64 data; }; /** * struct isst_if_msr_cmds - structure for msr commands * @cmd_count: Number of mailbox commands in msr_cmd[] * @msr_cmd[]: Holds one or more msr commands * * This structure used with ioctl ISST_IF_MSR_COMMAND to send * one or more MSR commands. IOCTL return value indicates number of * commands sent or error number if no commands have been sent. */ struct isst_if_msr_cmds { __u32 cmd_count; struct isst_if_msr_cmd msr_cmd[1]; }; #define ISST_IF_MAGIC 0xFE #define ISST_IF_GET_PLATFORM_INFO _IOR(ISST_IF_MAGIC, 0, struct isst_if_platform_info *) #define ISST_IF_GET_PHY_ID _IOWR(ISST_IF_MAGIC, 1, struct isst_if_cpu_map *) #define ISST_IF_IO_CMD _IOW(ISST_IF_MAGIC, 2, struct isst_if_io_regs *) #define ISST_IF_MBOX_COMMAND _IOWR(ISST_IF_MAGIC, 3, struct isst_if_mbox_cmds *) #define ISST_IF_MSR_COMMAND _IOWR(ISST_IF_MAGIC, 4, struct isst_if_msr_cmds *) #endif linux/atm_idt77105.h000064400000001673151027430560010113 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm_idt77105.h - Driver-specific declarations of the IDT77105 driver (for * use by driver-specific utilities) */ /* Written 1999 by Greg Banks . Copied from atm_suni.h. */ #ifndef LINUX_ATM_IDT77105_H #define LINUX_ATM_IDT77105_H #include #include #include /* * Structure for IDT77105_GETSTAT and IDT77105_GETSTATZ ioctls. * Pointed to by `arg' in atmif_sioc. */ struct idt77105_stats { __u32 symbol_errors; /* wire symbol errors */ __u32 tx_cells; /* cells transmitted */ __u32 rx_cells; /* cells received */ __u32 rx_hec_errors; /* Header Error Check errors on receive */ }; #define IDT77105_GETSTAT _IOW('a',ATMIOC_PHYPRV+2,struct atmif_sioc) /* get stats */ #define IDT77105_GETSTATZ _IOW('a',ATMIOC_PHYPRV+3,struct atmif_sioc) /* get stats and zero */ #endif linux/kfd_ioctl.h000064400000070216151027430560010023 0ustar00/* * Copyright 2014 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KFD_IOCTL_H_INCLUDED #define KFD_IOCTL_H_INCLUDED #include #include /* * - 1.1 - initial version * - 1.3 - Add SMI events support * - 1.4 - Indicate new SRAM EDC bit in device properties * - 1.5 - Add SVM API * - 1.6 - Query clear flags in SVM get_attr API * - 1.7 - Checkpoint Restore (CRIU) API * - 1.8 - CRIU - Support for SDMA transfers with GTT BOs * - 1.9 - Add available memory ioctl * - 1.10 - Add SMI profiler event log * - 1.11 - Add unified memory for ctx save/restore area */ #define KFD_IOCTL_MAJOR_VERSION 1 #define KFD_IOCTL_MINOR_VERSION 11 struct kfd_ioctl_get_version_args { __u32 major_version; /* from KFD */ __u32 minor_version; /* from KFD */ }; /* For kfd_ioctl_create_queue_args.queue_type. */ #define KFD_IOC_QUEUE_TYPE_COMPUTE 0x0 #define KFD_IOC_QUEUE_TYPE_SDMA 0x1 #define KFD_IOC_QUEUE_TYPE_COMPUTE_AQL 0x2 #define KFD_IOC_QUEUE_TYPE_SDMA_XGMI 0x3 #define KFD_MAX_QUEUE_PERCENTAGE 100 #define KFD_MAX_QUEUE_PRIORITY 15 struct kfd_ioctl_create_queue_args { __u64 ring_base_address; /* to KFD */ __u64 write_pointer_address; /* from KFD */ __u64 read_pointer_address; /* from KFD */ __u64 doorbell_offset; /* from KFD */ __u32 ring_size; /* to KFD */ __u32 gpu_id; /* to KFD */ __u32 queue_type; /* to KFD */ __u32 queue_percentage; /* to KFD */ __u32 queue_priority; /* to KFD */ __u32 queue_id; /* from KFD */ __u64 eop_buffer_address; /* to KFD */ __u64 eop_buffer_size; /* to KFD */ __u64 ctx_save_restore_address; /* to KFD */ __u32 ctx_save_restore_size; /* to KFD */ __u32 ctl_stack_size; /* to KFD */ }; struct kfd_ioctl_destroy_queue_args { __u32 queue_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_update_queue_args { __u64 ring_base_address; /* to KFD */ __u32 queue_id; /* to KFD */ __u32 ring_size; /* to KFD */ __u32 queue_percentage; /* to KFD */ __u32 queue_priority; /* to KFD */ }; struct kfd_ioctl_set_cu_mask_args { __u32 queue_id; /* to KFD */ __u32 num_cu_mask; /* to KFD */ __u64 cu_mask_ptr; /* to KFD */ }; struct kfd_ioctl_get_queue_wave_state_args { __u64 ctl_stack_address; /* to KFD */ __u32 ctl_stack_used_size; /* from KFD */ __u32 save_area_used_size; /* from KFD */ __u32 queue_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_get_available_memory_args { __u64 available; /* from KFD */ __u32 gpu_id; /* to KFD */ __u32 pad; }; /* For kfd_ioctl_set_memory_policy_args.default_policy and alternate_policy */ #define KFD_IOC_CACHE_POLICY_COHERENT 0 #define KFD_IOC_CACHE_POLICY_NONCOHERENT 1 struct kfd_ioctl_set_memory_policy_args { __u64 alternate_aperture_base; /* to KFD */ __u64 alternate_aperture_size; /* to KFD */ __u32 gpu_id; /* to KFD */ __u32 default_policy; /* to KFD */ __u32 alternate_policy; /* to KFD */ __u32 pad; }; /* * All counters are monotonic. They are used for profiling of compute jobs. * The profiling is done by userspace. * * In case of GPU reset, the counter should not be affected. */ struct kfd_ioctl_get_clock_counters_args { __u64 gpu_clock_counter; /* from KFD */ __u64 cpu_clock_counter; /* from KFD */ __u64 system_clock_counter; /* from KFD */ __u64 system_clock_freq; /* from KFD */ __u32 gpu_id; /* to KFD */ __u32 pad; }; struct kfd_process_device_apertures { __u64 lds_base; /* from KFD */ __u64 lds_limit; /* from KFD */ __u64 scratch_base; /* from KFD */ __u64 scratch_limit; /* from KFD */ __u64 gpuvm_base; /* from KFD */ __u64 gpuvm_limit; /* from KFD */ __u32 gpu_id; /* from KFD */ __u32 pad; }; /* * AMDKFD_IOC_GET_PROCESS_APERTURES is deprecated. Use * AMDKFD_IOC_GET_PROCESS_APERTURES_NEW instead, which supports an * unlimited number of GPUs. */ #define NUM_OF_SUPPORTED_GPUS 7 struct kfd_ioctl_get_process_apertures_args { struct kfd_process_device_apertures process_apertures[NUM_OF_SUPPORTED_GPUS];/* from KFD */ /* from KFD, should be in the range [1 - NUM_OF_SUPPORTED_GPUS] */ __u32 num_of_nodes; __u32 pad; }; struct kfd_ioctl_get_process_apertures_new_args { /* User allocated. Pointer to struct kfd_process_device_apertures * filled in by Kernel */ __u64 kfd_process_device_apertures_ptr; /* to KFD - indicates amount of memory present in * kfd_process_device_apertures_ptr * from KFD - Number of entries filled by KFD. */ __u32 num_of_nodes; __u32 pad; }; #define MAX_ALLOWED_NUM_POINTS 100 #define MAX_ALLOWED_AW_BUFF_SIZE 4096 #define MAX_ALLOWED_WAC_BUFF_SIZE 128 struct kfd_ioctl_dbg_register_args { __u32 gpu_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_dbg_unregister_args { __u32 gpu_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_dbg_address_watch_args { __u64 content_ptr; /* a pointer to the actual content */ __u32 gpu_id; /* to KFD */ __u32 buf_size_in_bytes; /*including gpu_id and buf_size */ }; struct kfd_ioctl_dbg_wave_control_args { __u64 content_ptr; /* a pointer to the actual content */ __u32 gpu_id; /* to KFD */ __u32 buf_size_in_bytes; /*including gpu_id and buf_size */ }; #define KFD_INVALID_FD 0xffffffff /* Matching HSA_EVENTTYPE */ #define KFD_IOC_EVENT_SIGNAL 0 #define KFD_IOC_EVENT_NODECHANGE 1 #define KFD_IOC_EVENT_DEVICESTATECHANGE 2 #define KFD_IOC_EVENT_HW_EXCEPTION 3 #define KFD_IOC_EVENT_SYSTEM_EVENT 4 #define KFD_IOC_EVENT_DEBUG_EVENT 5 #define KFD_IOC_EVENT_PROFILE_EVENT 6 #define KFD_IOC_EVENT_QUEUE_EVENT 7 #define KFD_IOC_EVENT_MEMORY 8 #define KFD_IOC_WAIT_RESULT_COMPLETE 0 #define KFD_IOC_WAIT_RESULT_TIMEOUT 1 #define KFD_IOC_WAIT_RESULT_FAIL 2 #define KFD_SIGNAL_EVENT_LIMIT 4096 /* For kfd_event_data.hw_exception_data.reset_type. */ #define KFD_HW_EXCEPTION_WHOLE_GPU_RESET 0 #define KFD_HW_EXCEPTION_PER_ENGINE_RESET 1 /* For kfd_event_data.hw_exception_data.reset_cause. */ #define KFD_HW_EXCEPTION_GPU_HANG 0 #define KFD_HW_EXCEPTION_ECC 1 /* For kfd_hsa_memory_exception_data.ErrorType */ #define KFD_MEM_ERR_NO_RAS 0 #define KFD_MEM_ERR_SRAM_ECC 1 #define KFD_MEM_ERR_POISON_CONSUMED 2 #define KFD_MEM_ERR_GPU_HANG 3 struct kfd_ioctl_create_event_args { __u64 event_page_offset; /* from KFD */ __u32 event_trigger_data; /* from KFD - signal events only */ __u32 event_type; /* to KFD */ __u32 auto_reset; /* to KFD */ __u32 node_id; /* to KFD - only valid for certain event types */ __u32 event_id; /* from KFD */ __u32 event_slot_index; /* from KFD */ }; struct kfd_ioctl_destroy_event_args { __u32 event_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_set_event_args { __u32 event_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_reset_event_args { __u32 event_id; /* to KFD */ __u32 pad; }; struct kfd_memory_exception_failure { __u32 NotPresent; /* Page not present or supervisor privilege */ __u32 ReadOnly; /* Write access to a read-only page */ __u32 NoExecute; /* Execute access to a page marked NX */ __u32 imprecise; /* Can't determine the exact fault address */ }; /* memory exception data */ struct kfd_hsa_memory_exception_data { struct kfd_memory_exception_failure failure; __u64 va; __u32 gpu_id; __u32 ErrorType; /* 0 = no RAS error, * 1 = ECC_SRAM, * 2 = Link_SYNFLOOD (poison), * 3 = GPU hang (not attributable to a specific cause), * other values reserved */ }; /* hw exception data */ struct kfd_hsa_hw_exception_data { __u32 reset_type; __u32 reset_cause; __u32 memory_lost; __u32 gpu_id; }; /* Event data */ struct kfd_event_data { union { struct kfd_hsa_memory_exception_data memory_exception_data; struct kfd_hsa_hw_exception_data hw_exception_data; }; /* From KFD */ __u64 kfd_event_data_ext; /* pointer to an extension structure for future exception types */ __u32 event_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_wait_events_args { __u64 events_ptr; /* pointed to struct kfd_event_data array, to KFD */ __u32 num_events; /* to KFD */ __u32 wait_for_all; /* to KFD */ __u32 timeout; /* to KFD */ __u32 wait_result; /* from KFD */ }; struct kfd_ioctl_set_scratch_backing_va_args { __u64 va_addr; /* to KFD */ __u32 gpu_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_get_tile_config_args { /* to KFD: pointer to tile array */ __u64 tile_config_ptr; /* to KFD: pointer to macro tile array */ __u64 macro_tile_config_ptr; /* to KFD: array size allocated by user mode * from KFD: array size filled by kernel */ __u32 num_tile_configs; /* to KFD: array size allocated by user mode * from KFD: array size filled by kernel */ __u32 num_macro_tile_configs; __u32 gpu_id; /* to KFD */ __u32 gb_addr_config; /* from KFD */ __u32 num_banks; /* from KFD */ __u32 num_ranks; /* from KFD */ /* struct size can be extended later if needed * without breaking ABI compatibility */ }; struct kfd_ioctl_set_trap_handler_args { __u64 tba_addr; /* to KFD */ __u64 tma_addr; /* to KFD */ __u32 gpu_id; /* to KFD */ __u32 pad; }; struct kfd_ioctl_acquire_vm_args { __u32 drm_fd; /* to KFD */ __u32 gpu_id; /* to KFD */ }; /* Allocation flags: memory types */ #define KFD_IOC_ALLOC_MEM_FLAGS_VRAM (1 << 0) #define KFD_IOC_ALLOC_MEM_FLAGS_GTT (1 << 1) #define KFD_IOC_ALLOC_MEM_FLAGS_USERPTR (1 << 2) #define KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL (1 << 3) #define KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP (1 << 4) /* Allocation flags: attributes/access options */ #define KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE (1 << 31) #define KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE (1 << 30) #define KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC (1 << 29) #define KFD_IOC_ALLOC_MEM_FLAGS_NO_SUBSTITUTE (1 << 28) #define KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM (1 << 27) #define KFD_IOC_ALLOC_MEM_FLAGS_COHERENT (1 << 26) #define KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED (1 << 25) /* Allocate memory for later SVM (shared virtual memory) mapping. * * @va_addr: virtual address of the memory to be allocated * all later mappings on all GPUs will use this address * @size: size in bytes * @handle: buffer handle returned to user mode, used to refer to * this allocation for mapping, unmapping and freeing * @mmap_offset: for CPU-mapping the allocation by mmapping a render node * for userptrs this is overloaded to specify the CPU address * @gpu_id: device identifier * @flags: memory type and attributes. See KFD_IOC_ALLOC_MEM_FLAGS above */ struct kfd_ioctl_alloc_memory_of_gpu_args { __u64 va_addr; /* to KFD */ __u64 size; /* to KFD */ __u64 handle; /* from KFD */ __u64 mmap_offset; /* to KFD (userptr), from KFD (mmap offset) */ __u32 gpu_id; /* to KFD */ __u32 flags; }; /* Free memory allocated with kfd_ioctl_alloc_memory_of_gpu * * @handle: memory handle returned by alloc */ struct kfd_ioctl_free_memory_of_gpu_args { __u64 handle; /* to KFD */ }; /* Map memory to one or more GPUs * * @handle: memory handle returned by alloc * @device_ids_array_ptr: array of gpu_ids (__u32 per device) * @n_devices: number of devices in the array * @n_success: number of devices mapped successfully * * @n_success returns information to the caller how many devices from * the start of the array have mapped the buffer successfully. It can * be passed into a subsequent retry call to skip those devices. For * the first call the caller should initialize it to 0. * * If the ioctl completes with return code 0 (success), n_success == * n_devices. */ struct kfd_ioctl_map_memory_to_gpu_args { __u64 handle; /* to KFD */ __u64 device_ids_array_ptr; /* to KFD */ __u32 n_devices; /* to KFD */ __u32 n_success; /* to/from KFD */ }; /* Unmap memory from one or more GPUs * * same arguments as for mapping */ struct kfd_ioctl_unmap_memory_from_gpu_args { __u64 handle; /* to KFD */ __u64 device_ids_array_ptr; /* to KFD */ __u32 n_devices; /* to KFD */ __u32 n_success; /* to/from KFD */ }; /* Allocate GWS for specific queue * * @queue_id: queue's id that GWS is allocated for * @num_gws: how many GWS to allocate * @first_gws: index of the first GWS allocated. * only support contiguous GWS allocation */ struct kfd_ioctl_alloc_queue_gws_args { __u32 queue_id; /* to KFD */ __u32 num_gws; /* to KFD */ __u32 first_gws; /* from KFD */ __u32 pad; }; struct kfd_ioctl_get_dmabuf_info_args { __u64 size; /* from KFD */ __u64 metadata_ptr; /* to KFD */ __u32 metadata_size; /* to KFD (space allocated by user) * from KFD (actual metadata size) */ __u32 gpu_id; /* from KFD */ __u32 flags; /* from KFD (KFD_IOC_ALLOC_MEM_FLAGS) */ __u32 dmabuf_fd; /* to KFD */ }; struct kfd_ioctl_import_dmabuf_args { __u64 va_addr; /* to KFD */ __u64 handle; /* from KFD */ __u32 gpu_id; /* to KFD */ __u32 dmabuf_fd; /* to KFD */ }; /* * KFD SMI(System Management Interface) events */ enum kfd_smi_event { KFD_SMI_EVENT_NONE = 0, /* not used */ KFD_SMI_EVENT_VMFAULT = 1, /* event start counting at 1 */ KFD_SMI_EVENT_THERMAL_THROTTLE = 2, KFD_SMI_EVENT_GPU_PRE_RESET = 3, KFD_SMI_EVENT_GPU_POST_RESET = 4, KFD_SMI_EVENT_MIGRATE_START = 5, KFD_SMI_EVENT_MIGRATE_END = 6, KFD_SMI_EVENT_PAGE_FAULT_START = 7, KFD_SMI_EVENT_PAGE_FAULT_END = 8, KFD_SMI_EVENT_QUEUE_EVICTION = 9, KFD_SMI_EVENT_QUEUE_RESTORE = 10, KFD_SMI_EVENT_UNMAP_FROM_GPU = 11, /* * max event number, as a flag bit to get events from all processes, * this requires super user permission, otherwise will not be able to * receive event from any process. Without this flag to receive events * from same process. */ KFD_SMI_EVENT_ALL_PROCESS = 64 }; enum KFD_MIGRATE_TRIGGERS { KFD_MIGRATE_TRIGGER_PREFETCH, KFD_MIGRATE_TRIGGER_PAGEFAULT_GPU, KFD_MIGRATE_TRIGGER_PAGEFAULT_CPU, KFD_MIGRATE_TRIGGER_TTM_EVICTION }; enum KFD_QUEUE_EVICTION_TRIGGERS { KFD_QUEUE_EVICTION_TRIGGER_SVM, KFD_QUEUE_EVICTION_TRIGGER_USERPTR, KFD_QUEUE_EVICTION_TRIGGER_TTM, KFD_QUEUE_EVICTION_TRIGGER_SUSPEND, KFD_QUEUE_EVICTION_CRIU_CHECKPOINT, KFD_QUEUE_EVICTION_CRIU_RESTORE }; enum KFD_SVM_UNMAP_TRIGGERS { KFD_SVM_UNMAP_TRIGGER_MMU_NOTIFY, KFD_SVM_UNMAP_TRIGGER_MMU_NOTIFY_MIGRATE, KFD_SVM_UNMAP_TRIGGER_UNMAP_FROM_CPU }; #define KFD_SMI_EVENT_MASK_FROM_INDEX(i) (1ULL << ((i) - 1)) #define KFD_SMI_EVENT_MSG_SIZE 96 struct kfd_ioctl_smi_events_args { __u32 gpuid; /* to KFD */ __u32 anon_fd; /* from KFD */ }; /************************************************************************************************** * CRIU IOCTLs (Checkpoint Restore In Userspace) * * When checkpointing a process, the userspace application will perform: * 1. PROCESS_INFO op to determine current process information. This pauses execution and evicts * all the queues. * 2. CHECKPOINT op to checkpoint process contents (BOs, queues, events, svm-ranges) * 3. UNPAUSE op to un-evict all the queues * * When restoring a process, the CRIU userspace application will perform: * * 1. RESTORE op to restore process contents * 2. RESUME op to start the process * * Note: Queues are forced into an evicted state after a successful PROCESS_INFO. User * application needs to perform an UNPAUSE operation after calling PROCESS_INFO. */ enum kfd_criu_op { KFD_CRIU_OP_PROCESS_INFO, KFD_CRIU_OP_CHECKPOINT, KFD_CRIU_OP_UNPAUSE, KFD_CRIU_OP_RESTORE, KFD_CRIU_OP_RESUME, }; /** * kfd_ioctl_criu_args - Arguments perform CRIU operation * @devices: [in/out] User pointer to memory location for devices information. * This is an array of type kfd_criu_device_bucket. * @bos: [in/out] User pointer to memory location for BOs information * This is an array of type kfd_criu_bo_bucket. * @priv_data: [in/out] User pointer to memory location for private data * @priv_data_size: [in/out] Size of priv_data in bytes * @num_devices: [in/out] Number of GPUs used by process. Size of @devices array. * @num_bos [in/out] Number of BOs used by process. Size of @bos array. * @num_objects: [in/out] Number of objects used by process. Objects are opaque to * user application. * @pid: [in/out] PID of the process being checkpointed * @op [in] Type of operation (kfd_criu_op) * * Return: 0 on success, -errno on failure */ struct kfd_ioctl_criu_args { __u64 devices; /* Used during ops: CHECKPOINT, RESTORE */ __u64 bos; /* Used during ops: CHECKPOINT, RESTORE */ __u64 priv_data; /* Used during ops: CHECKPOINT, RESTORE */ __u64 priv_data_size; /* Used during ops: PROCESS_INFO, RESTORE */ __u32 num_devices; /* Used during ops: PROCESS_INFO, RESTORE */ __u32 num_bos; /* Used during ops: PROCESS_INFO, RESTORE */ __u32 num_objects; /* Used during ops: PROCESS_INFO, RESTORE */ __u32 pid; /* Used during ops: PROCESS_INFO, RESUME */ __u32 op; }; struct kfd_criu_device_bucket { __u32 user_gpu_id; __u32 actual_gpu_id; __u32 drm_fd; __u32 pad; }; struct kfd_criu_bo_bucket { __u64 addr; __u64 size; __u64 offset; __u64 restored_offset; /* During restore, updated offset for BO */ __u32 gpu_id; /* This is the user_gpu_id */ __u32 alloc_flags; __u32 dmabuf_fd; __u32 pad; }; /* CRIU IOCTLs - END */ /**************************************************************************************************/ /* Register offset inside the remapped mmio page */ enum kfd_mmio_remap { KFD_MMIO_REMAP_HDP_MEM_FLUSH_CNTL = 0, KFD_MMIO_REMAP_HDP_REG_FLUSH_CNTL = 4, }; /* Guarantee host access to memory */ #define KFD_IOCTL_SVM_FLAG_HOST_ACCESS 0x00000001 /* Fine grained coherency between all devices with access */ #define KFD_IOCTL_SVM_FLAG_COHERENT 0x00000002 /* Use any GPU in same hive as preferred device */ #define KFD_IOCTL_SVM_FLAG_HIVE_LOCAL 0x00000004 /* GPUs only read, allows replication */ #define KFD_IOCTL_SVM_FLAG_GPU_RO 0x00000008 /* Allow execution on GPU */ #define KFD_IOCTL_SVM_FLAG_GPU_EXEC 0x00000010 /* GPUs mostly read, may allow similar optimizations as RO, but writes fault */ #define KFD_IOCTL_SVM_FLAG_GPU_READ_MOSTLY 0x00000020 /* Keep GPU memory mapping always valid as if XNACK is disable */ #define KFD_IOCTL_SVM_FLAG_GPU_ALWAYS_MAPPED 0x00000040 /** * kfd_ioctl_svm_op - SVM ioctl operations * * @KFD_IOCTL_SVM_OP_SET_ATTR: Modify one or more attributes * @KFD_IOCTL_SVM_OP_GET_ATTR: Query one or more attributes */ enum kfd_ioctl_svm_op { KFD_IOCTL_SVM_OP_SET_ATTR, KFD_IOCTL_SVM_OP_GET_ATTR }; /** kfd_ioctl_svm_location - Enum for preferred and prefetch locations * * GPU IDs are used to specify GPUs as preferred and prefetch locations. * Below definitions are used for system memory or for leaving the preferred * location unspecified. */ enum kfd_ioctl_svm_location { KFD_IOCTL_SVM_LOCATION_SYSMEM = 0, KFD_IOCTL_SVM_LOCATION_UNDEFINED = 0xffffffff }; /** * kfd_ioctl_svm_attr_type - SVM attribute types * * @KFD_IOCTL_SVM_ATTR_PREFERRED_LOC: gpuid of the preferred location, 0 for * system memory * @KFD_IOCTL_SVM_ATTR_PREFETCH_LOC: gpuid of the prefetch location, 0 for * system memory. Setting this triggers an * immediate prefetch (migration). * @KFD_IOCTL_SVM_ATTR_ACCESS: * @KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE: * @KFD_IOCTL_SVM_ATTR_NO_ACCESS: specify memory access for the gpuid given * by the attribute value * @KFD_IOCTL_SVM_ATTR_SET_FLAGS: bitmask of flags to set (see * KFD_IOCTL_SVM_FLAG_...) * @KFD_IOCTL_SVM_ATTR_CLR_FLAGS: bitmask of flags to clear * @KFD_IOCTL_SVM_ATTR_GRANULARITY: migration granularity * (log2 num pages) */ enum kfd_ioctl_svm_attr_type { KFD_IOCTL_SVM_ATTR_PREFERRED_LOC, KFD_IOCTL_SVM_ATTR_PREFETCH_LOC, KFD_IOCTL_SVM_ATTR_ACCESS, KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE, KFD_IOCTL_SVM_ATTR_NO_ACCESS, KFD_IOCTL_SVM_ATTR_SET_FLAGS, KFD_IOCTL_SVM_ATTR_CLR_FLAGS, KFD_IOCTL_SVM_ATTR_GRANULARITY }; /** * kfd_ioctl_svm_attribute - Attributes as pairs of type and value * * The meaning of the @value depends on the attribute type. * * @type: attribute type (see enum @kfd_ioctl_svm_attr_type) * @value: attribute value */ struct kfd_ioctl_svm_attribute { __u32 type; __u32 value; }; /** * kfd_ioctl_svm_args - Arguments for SVM ioctl * * @op specifies the operation to perform (see enum * @kfd_ioctl_svm_op). @start_addr and @size are common for all * operations. * * A variable number of attributes can be given in @attrs. * @nattr specifies the number of attributes. New attributes can be * added in the future without breaking the ABI. If unknown attributes * are given, the function returns -EINVAL. * * @KFD_IOCTL_SVM_OP_SET_ATTR sets attributes for a virtual address * range. It may overlap existing virtual address ranges. If it does, * the existing ranges will be split such that the attribute changes * only apply to the specified address range. * * @KFD_IOCTL_SVM_OP_GET_ATTR returns the intersection of attributes * over all memory in the given range and returns the result as the * attribute value. If different pages have different preferred or * prefetch locations, 0xffffffff will be returned for * @KFD_IOCTL_SVM_ATTR_PREFERRED_LOC or * @KFD_IOCTL_SVM_ATTR_PREFETCH_LOC resepctively. For * @KFD_IOCTL_SVM_ATTR_SET_FLAGS, flags of all pages will be * aggregated by bitwise AND. That means, a flag will be set in the * output, if that flag is set for all pages in the range. For * @KFD_IOCTL_SVM_ATTR_CLR_FLAGS, flags of all pages will be * aggregated by bitwise NOR. That means, a flag will be set in the * output, if that flag is clear for all pages in the range. * The minimum migration granularity throughout the range will be * returned for @KFD_IOCTL_SVM_ATTR_GRANULARITY. * * Querying of accessibility attributes works by initializing the * attribute type to @KFD_IOCTL_SVM_ATTR_ACCESS and the value to the * GPUID being queried. Multiple attributes can be given to allow * querying multiple GPUIDs. The ioctl function overwrites the * attribute type to indicate the access for the specified GPU. */ struct kfd_ioctl_svm_args { __u64 start_addr; __u64 size; __u32 op; __u32 nattr; /* Variable length array of attributes */ struct kfd_ioctl_svm_attribute attrs[]; }; /** * kfd_ioctl_set_xnack_mode_args - Arguments for set_xnack_mode * * @xnack_enabled: [in/out] Whether to enable XNACK mode for this process * * @xnack_enabled indicates whether recoverable page faults should be * enabled for the current process. 0 means disabled, positive means * enabled, negative means leave unchanged. If enabled, virtual address * translations on GFXv9 and later AMD GPUs can return XNACK and retry * the access until a valid PTE is available. This is used to implement * device page faults. * * On output, @xnack_enabled returns the (new) current mode (0 or * positive). Therefore, a negative input value can be used to query * the current mode without changing it. * * The XNACK mode fundamentally changes the way SVM managed memory works * in the driver, with subtle effects on application performance and * functionality. * * Enabling XNACK mode requires shader programs to be compiled * differently. Furthermore, not all GPUs support changing the mode * per-process. Therefore changing the mode is only allowed while no * user mode queues exist in the process. This ensure that no shader * code is running that may be compiled for the wrong mode. And GPUs * that cannot change to the requested mode will prevent the XNACK * mode from occurring. All GPUs used by the process must be in the * same XNACK mode. * * GFXv8 or older GPUs do not support 48 bit virtual addresses or SVM. * Therefore those GPUs are not considered for the XNACK mode switch. * * Return: 0 on success, -errno on failure */ struct kfd_ioctl_set_xnack_mode_args { __s32 xnack_enabled; }; #define AMDKFD_IOCTL_BASE 'K' #define AMDKFD_IO(nr) _IO(AMDKFD_IOCTL_BASE, nr) #define AMDKFD_IOR(nr, type) _IOR(AMDKFD_IOCTL_BASE, nr, type) #define AMDKFD_IOW(nr, type) _IOW(AMDKFD_IOCTL_BASE, nr, type) #define AMDKFD_IOWR(nr, type) _IOWR(AMDKFD_IOCTL_BASE, nr, type) #define AMDKFD_IOC_GET_VERSION \ AMDKFD_IOR(0x01, struct kfd_ioctl_get_version_args) #define AMDKFD_IOC_CREATE_QUEUE \ AMDKFD_IOWR(0x02, struct kfd_ioctl_create_queue_args) #define AMDKFD_IOC_DESTROY_QUEUE \ AMDKFD_IOWR(0x03, struct kfd_ioctl_destroy_queue_args) #define AMDKFD_IOC_SET_MEMORY_POLICY \ AMDKFD_IOW(0x04, struct kfd_ioctl_set_memory_policy_args) #define AMDKFD_IOC_GET_CLOCK_COUNTERS \ AMDKFD_IOWR(0x05, struct kfd_ioctl_get_clock_counters_args) #define AMDKFD_IOC_GET_PROCESS_APERTURES \ AMDKFD_IOR(0x06, struct kfd_ioctl_get_process_apertures_args) #define AMDKFD_IOC_UPDATE_QUEUE \ AMDKFD_IOW(0x07, struct kfd_ioctl_update_queue_args) #define AMDKFD_IOC_CREATE_EVENT \ AMDKFD_IOWR(0x08, struct kfd_ioctl_create_event_args) #define AMDKFD_IOC_DESTROY_EVENT \ AMDKFD_IOW(0x09, struct kfd_ioctl_destroy_event_args) #define AMDKFD_IOC_SET_EVENT \ AMDKFD_IOW(0x0A, struct kfd_ioctl_set_event_args) #define AMDKFD_IOC_RESET_EVENT \ AMDKFD_IOW(0x0B, struct kfd_ioctl_reset_event_args) #define AMDKFD_IOC_WAIT_EVENTS \ AMDKFD_IOWR(0x0C, struct kfd_ioctl_wait_events_args) #define AMDKFD_IOC_DBG_REGISTER_DEPRECATED \ AMDKFD_IOW(0x0D, struct kfd_ioctl_dbg_register_args) #define AMDKFD_IOC_DBG_UNREGISTER_DEPRECATED \ AMDKFD_IOW(0x0E, struct kfd_ioctl_dbg_unregister_args) #define AMDKFD_IOC_DBG_ADDRESS_WATCH_DEPRECATED \ AMDKFD_IOW(0x0F, struct kfd_ioctl_dbg_address_watch_args) #define AMDKFD_IOC_DBG_WAVE_CONTROL_DEPRECATED \ AMDKFD_IOW(0x10, struct kfd_ioctl_dbg_wave_control_args) #define AMDKFD_IOC_SET_SCRATCH_BACKING_VA \ AMDKFD_IOWR(0x11, struct kfd_ioctl_set_scratch_backing_va_args) #define AMDKFD_IOC_GET_TILE_CONFIG \ AMDKFD_IOWR(0x12, struct kfd_ioctl_get_tile_config_args) #define AMDKFD_IOC_SET_TRAP_HANDLER \ AMDKFD_IOW(0x13, struct kfd_ioctl_set_trap_handler_args) #define AMDKFD_IOC_GET_PROCESS_APERTURES_NEW \ AMDKFD_IOWR(0x14, \ struct kfd_ioctl_get_process_apertures_new_args) #define AMDKFD_IOC_ACQUIRE_VM \ AMDKFD_IOW(0x15, struct kfd_ioctl_acquire_vm_args) #define AMDKFD_IOC_ALLOC_MEMORY_OF_GPU \ AMDKFD_IOWR(0x16, struct kfd_ioctl_alloc_memory_of_gpu_args) #define AMDKFD_IOC_FREE_MEMORY_OF_GPU \ AMDKFD_IOW(0x17, struct kfd_ioctl_free_memory_of_gpu_args) #define AMDKFD_IOC_MAP_MEMORY_TO_GPU \ AMDKFD_IOWR(0x18, struct kfd_ioctl_map_memory_to_gpu_args) #define AMDKFD_IOC_UNMAP_MEMORY_FROM_GPU \ AMDKFD_IOWR(0x19, struct kfd_ioctl_unmap_memory_from_gpu_args) #define AMDKFD_IOC_SET_CU_MASK \ AMDKFD_IOW(0x1A, struct kfd_ioctl_set_cu_mask_args) #define AMDKFD_IOC_GET_QUEUE_WAVE_STATE \ AMDKFD_IOWR(0x1B, struct kfd_ioctl_get_queue_wave_state_args) #define AMDKFD_IOC_GET_DMABUF_INFO \ AMDKFD_IOWR(0x1C, struct kfd_ioctl_get_dmabuf_info_args) #define AMDKFD_IOC_IMPORT_DMABUF \ AMDKFD_IOWR(0x1D, struct kfd_ioctl_import_dmabuf_args) #define AMDKFD_IOC_ALLOC_QUEUE_GWS \ AMDKFD_IOWR(0x1E, struct kfd_ioctl_alloc_queue_gws_args) #define AMDKFD_IOC_SMI_EVENTS \ AMDKFD_IOWR(0x1F, struct kfd_ioctl_smi_events_args) #define AMDKFD_IOC_SVM AMDKFD_IOWR(0x20, struct kfd_ioctl_svm_args) #define AMDKFD_IOC_SET_XNACK_MODE \ AMDKFD_IOWR(0x21, struct kfd_ioctl_set_xnack_mode_args) #define AMDKFD_IOC_CRIU_OP \ AMDKFD_IOWR(0x22, struct kfd_ioctl_criu_args) #define AMDKFD_IOC_AVAILABLE_MEMORY \ AMDKFD_IOWR(0x23, struct kfd_ioctl_get_available_memory_args) #define AMDKFD_COMMAND_START 0x01 #define AMDKFD_COMMAND_END 0x24 #endif linux/param.h000064400000000215151027430560007155 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_PARAM_H #define _LINUX_PARAM_H #include #endif linux/netfilter_bridge.h000064400000002220151027430560011363 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BRIDGE_NETFILTER_H #define __LINUX_BRIDGE_NETFILTER_H /* bridge-specific defines for netfilter. */ #include #include #include #include #include #include /* for INT_MIN, INT_MAX */ /* Bridge Hooks */ /* After promisc drops, checksum checks. */ #define NF_BR_PRE_ROUTING 0 /* If the packet is destined for this box. */ #define NF_BR_LOCAL_IN 1 /* If the packet is destined for another interface. */ #define NF_BR_FORWARD 2 /* Packets coming from a local process. */ #define NF_BR_LOCAL_OUT 3 /* Packets about to hit the wire. */ #define NF_BR_POST_ROUTING 4 /* Not really a hook, but used for the ebtables broute table */ #define NF_BR_BROUTING 5 #define NF_BR_NUMHOOKS 6 enum nf_br_hook_priorities { NF_BR_PRI_FIRST = INT_MIN, NF_BR_PRI_NAT_DST_BRIDGED = -300, NF_BR_PRI_FILTER_BRIDGED = -200, NF_BR_PRI_BRNF = 0, NF_BR_PRI_NAT_DST_OTHER = 100, NF_BR_PRI_FILTER_OTHER = 200, NF_BR_PRI_NAT_SRC = 300, NF_BR_PRI_LAST = INT_MAX, }; #endif /* __LINUX_BRIDGE_NETFILTER_H */ linux/unistd.h000064400000000334151027430560007365 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_UNISTD_H_ #define _LINUX_UNISTD_H_ /* * Include machine specific syscall numbers */ #include #endif /* _LINUX_UNISTD_H_ */ linux/atmioc.h000064400000003156151027430560007340 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmioc.h - ranges for ATM-related ioctl numbers */ /* Written 1995-1999 by Werner Almesberger, EPFL LRC/ICA */ /* * See http://icawww1.epfl.ch/linux-atm/magic.html for the complete list of * "magic" ioctl numbers. */ #ifndef _LINUX_ATMIOC_H #define _LINUX_ATMIOC_H #include /* everybody including atmioc.h will also need _IO{,R,W,WR} */ #define ATMIOC_PHYCOM 0x00 /* PHY device common ioctls, globally unique */ #define ATMIOC_PHYCOM_END 0x0f #define ATMIOC_PHYTYP 0x10 /* PHY dev type ioctls, unique per PHY type */ #define ATMIOC_PHYTYP_END 0x2f #define ATMIOC_PHYPRV 0x30 /* PHY dev private ioctls, unique per driver */ #define ATMIOC_PHYPRV_END 0x4f #define ATMIOC_SARCOM 0x50 /* SAR device common ioctls, globally unique */ #define ATMIOC_SARCOM_END 0x50 #define ATMIOC_SARPRV 0x60 /* SAR dev private ioctls, unique per driver */ #define ATMIOC_SARPRV_END 0x7f #define ATMIOC_ITF 0x80 /* Interface ioctls, globally unique */ #define ATMIOC_ITF_END 0x8f #define ATMIOC_BACKEND 0x90 /* ATM generic backend ioctls, u. per backend */ #define ATMIOC_BACKEND_END 0xaf /* 0xb0-0xbf: Reserved for future use */ #define ATMIOC_AREQUIPA 0xc0 /* Application requested IP over ATM, glob. u. */ #define ATMIOC_LANE 0xd0 /* LAN Emulation, globally unique */ #define ATMIOC_MPOA 0xd8 /* MPOA, globally unique */ #define ATMIOC_CLIP 0xe0 /* Classical IP over ATM control, globally u. */ #define ATMIOC_CLIP_END 0xef #define ATMIOC_SPECIAL 0xf0 /* Special-purpose controls, globally unique */ #define ATMIOC_SPECIAL_END 0xff #endif linux/rxrpc.h000064400000011730151027430560007217 0ustar00/* Types and definitions for AF_RXRPC. * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #ifndef _LINUX_RXRPC_H #define _LINUX_RXRPC_H #include #include #include /* * RxRPC socket address */ struct sockaddr_rxrpc { __kernel_sa_family_t srx_family; /* address family */ __u16 srx_service; /* service desired */ __u16 transport_type; /* type of transport socket (SOCK_DGRAM) */ __u16 transport_len; /* length of transport address */ union { __kernel_sa_family_t family; /* transport address family */ struct sockaddr_in sin; /* IPv4 transport address */ struct sockaddr_in6 sin6; /* IPv6 transport address */ } transport; }; /* * RxRPC socket options */ #define RXRPC_SECURITY_KEY 1 /* [clnt] set client security key */ #define RXRPC_SECURITY_KEYRING 2 /* [srvr] set ring of server security keys */ #define RXRPC_EXCLUSIVE_CONNECTION 3 /* Deprecated; use RXRPC_EXCLUSIVE_CALL instead */ #define RXRPC_MIN_SECURITY_LEVEL 4 /* minimum security level */ #define RXRPC_UPGRADEABLE_SERVICE 5 /* Upgrade service[0] -> service[1] */ #define RXRPC_SUPPORTED_CMSG 6 /* Get highest supported control message type */ /* * RxRPC control messages * - If neither abort or accept are specified, the message is a data message. * - terminal messages mean that a user call ID tag can be recycled * - s/r/- indicate whether these are applicable to sendmsg() and/or recvmsg() */ enum rxrpc_cmsg_type { RXRPC_USER_CALL_ID = 1, /* sr: user call ID specifier */ RXRPC_ABORT = 2, /* sr: abort request / notification [terminal] */ RXRPC_ACK = 3, /* -r: [Service] RPC op final ACK received [terminal] */ RXRPC_NET_ERROR = 5, /* -r: network error received [terminal] */ RXRPC_BUSY = 6, /* -r: server busy received [terminal] */ RXRPC_LOCAL_ERROR = 7, /* -r: local error generated [terminal] */ RXRPC_NEW_CALL = 8, /* -r: [Service] new incoming call notification */ RXRPC_ACCEPT = 9, /* s-: [Service] accept request */ RXRPC_EXCLUSIVE_CALL = 10, /* s-: Call should be on exclusive connection */ RXRPC_UPGRADE_SERVICE = 11, /* s-: Request service upgrade for client call */ RXRPC_TX_LENGTH = 12, /* s-: Total length of Tx data */ RXRPC_SET_CALL_TIMEOUT = 13, /* s-: Set one or more call timeouts */ RXRPC__SUPPORTED }; /* * RxRPC security levels */ #define RXRPC_SECURITY_PLAIN 0 /* plain secure-checksummed packets only */ #define RXRPC_SECURITY_AUTH 1 /* authenticated packets */ #define RXRPC_SECURITY_ENCRYPT 2 /* encrypted packets */ /* * RxRPC security indices */ #define RXRPC_SECURITY_NONE 0 /* no security protocol */ #define RXRPC_SECURITY_RXKAD 2 /* kaserver or kerberos 4 */ #define RXRPC_SECURITY_RXGK 4 /* gssapi-based */ #define RXRPC_SECURITY_RXK5 5 /* kerberos 5 */ /* * RxRPC-level abort codes */ #define RX_CALL_DEAD -1 /* call/conn has been inactive and is shut down */ #define RX_INVALID_OPERATION -2 /* invalid operation requested / attempted */ #define RX_CALL_TIMEOUT -3 /* call timeout exceeded */ #define RX_EOF -4 /* unexpected end of data on read op */ #define RX_PROTOCOL_ERROR -5 /* low-level protocol error */ #define RX_USER_ABORT -6 /* generic user abort */ #define RX_ADDRINUSE -7 /* UDP port in use */ #define RX_DEBUGI_BADTYPE -8 /* bad debugging packet type */ /* * (un)marshalling abort codes (rxgen) */ #define RXGEN_CC_MARSHAL -450 #define RXGEN_CC_UNMARSHAL -451 #define RXGEN_SS_MARSHAL -452 #define RXGEN_SS_UNMARSHAL -453 #define RXGEN_DECODE -454 #define RXGEN_OPCODE -455 #define RXGEN_SS_XDRFREE -456 #define RXGEN_CC_XDRFREE -457 /* * Rx kerberos security abort codes * - unfortunately we have no generalised security abort codes to say things * like "unsupported security", so we have to use these instead and hope the * other side understands */ #define RXKADINCONSISTENCY 19270400 /* security module structure inconsistent */ #define RXKADPACKETSHORT 19270401 /* packet too short for security challenge */ #define RXKADLEVELFAIL 19270402 /* security level negotiation failed */ #define RXKADTICKETLEN 19270403 /* ticket length too short or too long */ #define RXKADOUTOFSEQUENCE 19270404 /* packet had bad sequence number */ #define RXKADNOAUTH 19270405 /* caller not authorised */ #define RXKADBADKEY 19270406 /* illegal key: bad parity or weak */ #define RXKADBADTICKET 19270407 /* security object was passed a bad ticket */ #define RXKADUNKNOWNKEY 19270408 /* ticket contained unknown key version number */ #define RXKADEXPIRED 19270409 /* authentication expired */ #define RXKADSEALEDINCON 19270410 /* sealed data inconsistent */ #define RXKADDATALEN 19270411 /* user data too long */ #define RXKADILLEGALLEVEL 19270412 /* caller not authorised to use encrypted conns */ #endif /* _LINUX_RXRPC_H */ linux/ax25.h000064400000005410151027430560006636 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * These are the public elements of the Linux kernel AX.25 code. A similar * file netrom.h exists for the NET/ROM protocol. */ #ifndef AX25_KERNEL_H #define AX25_KERNEL_H #include #define AX25_MTU 256 #define AX25_MAX_DIGIS 8 #define AX25_WINDOW 1 #define AX25_T1 2 #define AX25_N2 3 #define AX25_T3 4 #define AX25_T2 5 #define AX25_BACKOFF 6 #define AX25_EXTSEQ 7 #define AX25_PIDINCL 8 #define AX25_IDLE 9 #define AX25_PACLEN 10 #define AX25_IAMDIGI 12 #define AX25_KILL 99 #define SIOCAX25GETUID (SIOCPROTOPRIVATE+0) #define SIOCAX25ADDUID (SIOCPROTOPRIVATE+1) #define SIOCAX25DELUID (SIOCPROTOPRIVATE+2) #define SIOCAX25NOUID (SIOCPROTOPRIVATE+3) #define SIOCAX25OPTRT (SIOCPROTOPRIVATE+7) #define SIOCAX25CTLCON (SIOCPROTOPRIVATE+8) #define SIOCAX25GETINFOOLD (SIOCPROTOPRIVATE+9) #define SIOCAX25ADDFWD (SIOCPROTOPRIVATE+10) #define SIOCAX25DELFWD (SIOCPROTOPRIVATE+11) #define SIOCAX25DEVCTL (SIOCPROTOPRIVATE+12) #define SIOCAX25GETINFO (SIOCPROTOPRIVATE+13) #define AX25_SET_RT_IPMODE 2 #define AX25_NOUID_DEFAULT 0 #define AX25_NOUID_BLOCK 1 typedef struct { char ax25_call[7]; /* 6 call + SSID (shifted ascii!) */ } ax25_address; struct sockaddr_ax25 { __kernel_sa_family_t sax25_family; ax25_address sax25_call; int sax25_ndigis; /* Digipeater ax25_address sets follow */ }; #define sax25_uid sax25_ndigis struct full_sockaddr_ax25 { struct sockaddr_ax25 fsa_ax25; ax25_address fsa_digipeater[AX25_MAX_DIGIS]; }; struct ax25_routes_struct { ax25_address port_addr; ax25_address dest_addr; unsigned char digi_count; ax25_address digi_addr[AX25_MAX_DIGIS]; }; struct ax25_route_opt_struct { ax25_address port_addr; ax25_address dest_addr; int cmd; int arg; }; struct ax25_ctl_struct { ax25_address port_addr; ax25_address source_addr; ax25_address dest_addr; unsigned int cmd; unsigned long arg; unsigned char digi_count; ax25_address digi_addr[AX25_MAX_DIGIS]; }; /* this will go away. Please do not export to user land */ struct ax25_info_struct_deprecated { unsigned int n2, n2count; unsigned int t1, t1timer; unsigned int t2, t2timer; unsigned int t3, t3timer; unsigned int idle, idletimer; unsigned int state; unsigned int rcv_q, snd_q; }; struct ax25_info_struct { unsigned int n2, n2count; unsigned int t1, t1timer; unsigned int t2, t2timer; unsigned int t3, t3timer; unsigned int idle, idletimer; unsigned int state; unsigned int rcv_q, snd_q; unsigned int vs, vr, va, vs_max; unsigned int paclen; unsigned int window; }; struct ax25_fwd_struct { ax25_address port_from; ax25_address port_to; }; #endif linux/bpf_perf_event.h000064400000001021151027430560011035 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. */ #ifndef __LINUX_BPF_PERF_EVENT_H__ #define __LINUX_BPF_PERF_EVENT_H__ #include struct bpf_perf_event_data { bpf_user_pt_regs_t regs; __u64 sample_period; __u64 addr; }; #endif /* __LINUX_BPF_PERF_EVENT_H__ */ linux/securebits.h000064400000005220151027430560010226 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SECUREBITS_H #define _LINUX_SECUREBITS_H /* Each securesetting is implemented using two bits. One bit specifies whether the setting is on or off. The other bit specify whether the setting is locked or not. A setting which is locked cannot be changed from user-level. */ #define issecure_mask(X) (1 << (X)) #define SECUREBITS_DEFAULT 0x00000000 /* When set UID 0 has no special privileges. When unset, we support inheritance of root-permissions and suid-root executable under compatibility mode. We raise the effective and inheritable bitmasks *of the executable file* if the effective uid of the new process is 0. If the real uid is 0, we raise the effective (legacy) bit of the executable file. */ #define SECURE_NOROOT 0 #define SECURE_NOROOT_LOCKED 1 /* make bit-0 immutable */ #define SECBIT_NOROOT (issecure_mask(SECURE_NOROOT)) #define SECBIT_NOROOT_LOCKED (issecure_mask(SECURE_NOROOT_LOCKED)) /* When set, setuid to/from uid 0 does not trigger capability-"fixup". When unset, to provide compatiblility with old programs relying on set*uid to gain/lose privilege, transitions to/from uid 0 cause capabilities to be gained/lost. */ #define SECURE_NO_SETUID_FIXUP 2 #define SECURE_NO_SETUID_FIXUP_LOCKED 3 /* make bit-2 immutable */ #define SECBIT_NO_SETUID_FIXUP (issecure_mask(SECURE_NO_SETUID_FIXUP)) #define SECBIT_NO_SETUID_FIXUP_LOCKED \ (issecure_mask(SECURE_NO_SETUID_FIXUP_LOCKED)) /* When set, a process can retain its capabilities even after transitioning to a non-root user (the set-uid fixup suppressed by bit 2). Bit-4 is cleared when a process calls exec(); setting both bit 4 and 5 will create a barrier through exec that no exec()'d child can use this feature again. */ #define SECURE_KEEP_CAPS 4 #define SECURE_KEEP_CAPS_LOCKED 5 /* make bit-4 immutable */ #define SECBIT_KEEP_CAPS (issecure_mask(SECURE_KEEP_CAPS)) #define SECBIT_KEEP_CAPS_LOCKED (issecure_mask(SECURE_KEEP_CAPS_LOCKED)) /* When set, a process cannot add new capabilities to its ambient set. */ #define SECURE_NO_CAP_AMBIENT_RAISE 6 #define SECURE_NO_CAP_AMBIENT_RAISE_LOCKED 7 /* make bit-6 immutable */ #define SECBIT_NO_CAP_AMBIENT_RAISE (issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE)) #define SECBIT_NO_CAP_AMBIENT_RAISE_LOCKED \ (issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE_LOCKED)) #define SECURE_ALL_BITS (issecure_mask(SECURE_NOROOT) | \ issecure_mask(SECURE_NO_SETUID_FIXUP) | \ issecure_mask(SECURE_KEEP_CAPS) | \ issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE)) #define SECURE_ALL_LOCKS (SECURE_ALL_BITS << 1) #endif /* _LINUX_SECUREBITS_H */ linux/netfilter_arp.h000064400000000675151027430560010725 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ #ifndef __LINUX_ARP_NETFILTER_H #define __LINUX_ARP_NETFILTER_H /* ARP-specific defines for netfilter. * (C)2002 Rusty Russell IBM -- This code is GPL. */ #include /* There is no PF_ARP. */ #define NF_ARP 0 /* ARP Hooks */ #define NF_ARP_IN 0 #define NF_ARP_OUT 1 #define NF_ARP_FORWARD 2 #define NF_ARP_NUMHOOKS 3 #endif /* __LINUX_ARP_NETFILTER_H */ linux/if_bonding.h000064400000012253151027430560010160 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * Bond several ethernet interfaces into a Cisco, running 'Etherchannel'. * * * Portions are (c) Copyright 1995 Simon "Guru Aleph-Null" Janes * NCM: Network and Communications Management, Inc. * * BUT, I'm the one who modified it for ethernet, so: * (c) Copyright 1999, Thomas Davis, tadavis@lbl.gov * * This software may be used and distributed according to the terms * of the GNU Public License, incorporated herein by reference. * * 2003/03/18 - Amir Noam * - Added support for getting slave's speed and duplex via ethtool. * Needed for 802.3ad and other future modes. * * 2003/03/18 - Tsippy Mendelson and * Shmulik Hen * - Enable support of modes that need to use the unique mac address of * each slave. * * 2003/03/18 - Tsippy Mendelson and * Amir Noam * - Moved driver's private data types to bonding.h * * 2003/03/18 - Amir Noam , * Tsippy Mendelson and * Shmulik Hen * - Added support for IEEE 802.3ad Dynamic link aggregation mode. * * 2003/05/01 - Amir Noam * - Added ABI version control to restore compatibility between * new/old ifenslave and new/old bonding. * * 2003/12/01 - Shmulik Hen * - Code cleanup and style changes * * 2005/05/05 - Jason Gabler * - added definitions for various XOR hashing policies */ #ifndef _LINUX_IF_BONDING_H #define _LINUX_IF_BONDING_H #include #include #include /* userland - kernel ABI version (2003/05/08) */ #define BOND_ABI_VERSION 2 /* * We can remove these ioctl definitions in 2.5. People should use the * SIOC*** versions of them instead */ #define BOND_ENSLAVE_OLD (SIOCDEVPRIVATE) #define BOND_RELEASE_OLD (SIOCDEVPRIVATE + 1) #define BOND_SETHWADDR_OLD (SIOCDEVPRIVATE + 2) #define BOND_SLAVE_INFO_QUERY_OLD (SIOCDEVPRIVATE + 11) #define BOND_INFO_QUERY_OLD (SIOCDEVPRIVATE + 12) #define BOND_CHANGE_ACTIVE_OLD (SIOCDEVPRIVATE + 13) #define BOND_CHECK_MII_STATUS (SIOCGMIIPHY) #define BOND_MODE_ROUNDROBIN 0 #define BOND_MODE_ACTIVEBACKUP 1 #define BOND_MODE_XOR 2 #define BOND_MODE_BROADCAST 3 #define BOND_MODE_8023AD 4 #define BOND_MODE_TLB 5 #define BOND_MODE_ALB 6 /* TLB + RLB (receive load balancing) */ /* each slave's link has 4 states */ #define BOND_LINK_UP 0 /* link is up and running */ #define BOND_LINK_FAIL 1 /* link has just gone down */ #define BOND_LINK_DOWN 2 /* link has been down for too long time */ #define BOND_LINK_BACK 3 /* link is going back */ /* each slave has several states */ #define BOND_STATE_ACTIVE 0 /* link is active */ #define BOND_STATE_BACKUP 1 /* link is backup */ #define BOND_DEFAULT_MAX_BONDS 1 /* Default maximum number of devices to support */ #define BOND_DEFAULT_TX_QUEUES 16 /* Default number of tx queues per device */ #define BOND_DEFAULT_RESEND_IGMP 1 /* Default number of IGMP membership reports */ /* hashing types */ #define BOND_XMIT_POLICY_LAYER2 0 /* layer 2 (MAC only), default */ #define BOND_XMIT_POLICY_LAYER34 1 /* layer 3+4 (IP ^ (TCP || UDP)) */ #define BOND_XMIT_POLICY_LAYER23 2 /* layer 2+3 (IP ^ MAC) */ #define BOND_XMIT_POLICY_ENCAP23 3 /* encapsulated layer 2+3 */ #define BOND_XMIT_POLICY_ENCAP34 4 /* encapsulated layer 3+4 */ #define BOND_XMIT_POLICY_VLAN_SRCMAC 5 /* vlan + source MAC */ /* 802.3ad port state definitions (43.4.2.2 in the 802.3ad standard) */ #define LACP_STATE_LACP_ACTIVITY 0x1 #define LACP_STATE_LACP_TIMEOUT 0x2 #define LACP_STATE_AGGREGATION 0x4 #define LACP_STATE_SYNCHRONIZATION 0x8 #define LACP_STATE_COLLECTING 0x10 #define LACP_STATE_DISTRIBUTING 0x20 #define LACP_STATE_DEFAULTED 0x40 #define LACP_STATE_EXPIRED 0x80 typedef struct ifbond { __s32 bond_mode; __s32 num_slaves; __s32 miimon; } ifbond; typedef struct ifslave { __s32 slave_id; /* Used as an IN param to the BOND_SLAVE_INFO_QUERY ioctl */ char slave_name[IFNAMSIZ]; __s8 link; __s8 state; __u32 link_failure_count; } ifslave; struct ad_info { __u16 aggregator_id; __u16 ports; __u16 actor_key; __u16 partner_key; __u8 partner_system[ETH_ALEN]; }; /* Embedded inside LINK_XSTATS_TYPE_BOND */ enum { BOND_XSTATS_UNSPEC, BOND_XSTATS_3AD, __BOND_XSTATS_MAX }; #define BOND_XSTATS_MAX (__BOND_XSTATS_MAX - 1) /* Embedded inside BOND_XSTATS_3AD */ enum { BOND_3AD_STAT_LACPDU_RX, BOND_3AD_STAT_LACPDU_TX, BOND_3AD_STAT_LACPDU_UNKNOWN_RX, BOND_3AD_STAT_LACPDU_ILLEGAL_RX, BOND_3AD_STAT_MARKER_RX, BOND_3AD_STAT_MARKER_TX, BOND_3AD_STAT_MARKER_RESP_RX, BOND_3AD_STAT_MARKER_RESP_TX, BOND_3AD_STAT_MARKER_UNKNOWN_RX, BOND_3AD_STAT_PAD, __BOND_3AD_STAT_MAX }; #define BOND_3AD_STAT_MAX (__BOND_3AD_STAT_MAX - 1) #endif /* _LINUX_IF_BONDING_H */ /* * Local variables: * version-control: t * kept-new-versions: 5 * c-indent-level: 8 * c-basic-offset: 8 * tab-width: 8 * End: */ linux/rtc.h000064400000007651151027430560006660 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Generic RTC interface. * This version contains the part of the user interface to the Real Time Clock * service. It is used with both the legacy mc146818 and also EFI * Struct rtc_time and first 12 ioctl by Paul Gortmaker, 1996 - separated out * from to this file for 2.4 kernels. * * Copyright (C) 1999 Hewlett-Packard Co. * Copyright (C) 1999 Stephane Eranian */ #ifndef _LINUX_RTC_H_ #define _LINUX_RTC_H_ /* * The struct used to pass data via the following ioctl. Similar to the * struct tm in , but it needs to be here so that the kernel * source is self contained, allowing cross-compiles, etc. etc. */ struct rtc_time { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; }; /* * This data structure is inspired by the EFI (v0.92) wakeup * alarm API. */ struct rtc_wkalrm { unsigned char enabled; /* 0 = alarm disabled, 1 = alarm enabled */ unsigned char pending; /* 0 = alarm not pending, 1 = alarm pending */ struct rtc_time time; /* time the alarm is set to */ }; /* * Data structure to control PLL correction some better RTC feature * pll_value is used to get or set current value of correction, * the rest of the struct is used to query HW capabilities. * This is modeled after the RTC used in Q40/Q60 computers but * should be sufficiently flexible for other devices * * +ve pll_value means clock will run faster by * pll_value*pll_posmult/pll_clock * -ve pll_value means clock will run slower by * pll_value*pll_negmult/pll_clock */ struct rtc_pll_info { int pll_ctrl; /* placeholder for fancier control */ int pll_value; /* get/set correction value */ int pll_max; /* max +ve (faster) adjustment value */ int pll_min; /* max -ve (slower) adjustment value */ int pll_posmult; /* factor for +ve correction */ int pll_negmult; /* factor for -ve correction */ long pll_clock; /* base PLL frequency */ }; /* * ioctl calls that are permitted to the /dev/rtc interface, if * any of the RTC drivers are enabled. */ #define RTC_AIE_ON _IO('p', 0x01) /* Alarm int. enable on */ #define RTC_AIE_OFF _IO('p', 0x02) /* ... off */ #define RTC_UIE_ON _IO('p', 0x03) /* Update int. enable on */ #define RTC_UIE_OFF _IO('p', 0x04) /* ... off */ #define RTC_PIE_ON _IO('p', 0x05) /* Periodic int. enable on */ #define RTC_PIE_OFF _IO('p', 0x06) /* ... off */ #define RTC_WIE_ON _IO('p', 0x0f) /* Watchdog int. enable on */ #define RTC_WIE_OFF _IO('p', 0x10) /* ... off */ #define RTC_ALM_SET _IOW('p', 0x07, struct rtc_time) /* Set alarm time */ #define RTC_ALM_READ _IOR('p', 0x08, struct rtc_time) /* Read alarm time */ #define RTC_RD_TIME _IOR('p', 0x09, struct rtc_time) /* Read RTC time */ #define RTC_SET_TIME _IOW('p', 0x0a, struct rtc_time) /* Set RTC time */ #define RTC_IRQP_READ _IOR('p', 0x0b, unsigned long) /* Read IRQ rate */ #define RTC_IRQP_SET _IOW('p', 0x0c, unsigned long) /* Set IRQ rate */ #define RTC_EPOCH_READ _IOR('p', 0x0d, unsigned long) /* Read epoch */ #define RTC_EPOCH_SET _IOW('p', 0x0e, unsigned long) /* Set epoch */ #define RTC_WKALM_SET _IOW('p', 0x0f, struct rtc_wkalrm)/* Set wakeup alarm*/ #define RTC_WKALM_RD _IOR('p', 0x10, struct rtc_wkalrm)/* Get wakeup alarm*/ #define RTC_PLL_GET _IOR('p', 0x11, struct rtc_pll_info) /* Get PLL correction */ #define RTC_PLL_SET _IOW('p', 0x12, struct rtc_pll_info) /* Set PLL correction */ #define RTC_VL_READ _IOR('p', 0x13, int) /* Voltage low detector */ #define RTC_VL_CLR _IO('p', 0x14) /* Clear voltage low information */ /* interrupt flags */ #define RTC_IRQF 0x80 /* Any of the following is active */ #define RTC_PF 0x40 /* Periodic interrupt */ #define RTC_AF 0x20 /* Alarm interrupt */ #define RTC_UF 0x10 /* Update interrupt for 1Hz RTC */ #define RTC_MAX_FREQ 8192 #endif /* _LINUX_RTC_H_ */ linux/dlm_plock.h000064400000001576151027430560010034 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2005-2008 Red Hat, Inc. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License v.2. */ #ifndef __DLM_PLOCK_DOT_H__ #define __DLM_PLOCK_DOT_H__ #include #define DLM_PLOCK_MISC_NAME "dlm_plock" #define DLM_PLOCK_VERSION_MAJOR 1 #define DLM_PLOCK_VERSION_MINOR 2 #define DLM_PLOCK_VERSION_PATCH 0 enum { DLM_PLOCK_OP_LOCK = 1, DLM_PLOCK_OP_UNLOCK, DLM_PLOCK_OP_GET, }; #define DLM_PLOCK_FL_CLOSE 1 struct dlm_plock_info { __u32 version[3]; __u8 optype; __u8 ex; __u8 wait; __u8 flags; __u32 pid; __s32 nodeid; __s32 rv; __u32 fsid; __u64 number; __u64 start; __u64 end; __u64 owner; }; #endif /* __DLM_PLOCK_DOT_H__ */ linux/iio/types.h000064400000003631151027430560010006 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* industrial I/O data types needed both in and out of kernel * * Copyright (c) 2008 Jonathan Cameron * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _IIO_TYPES_H_ #define _IIO_TYPES_H_ enum iio_chan_type { IIO_VOLTAGE, IIO_CURRENT, IIO_POWER, IIO_ACCEL, IIO_ANGL_VEL, IIO_MAGN, IIO_LIGHT, IIO_INTENSITY, IIO_PROXIMITY, IIO_TEMP, IIO_INCLI, IIO_ROT, IIO_ANGL, IIO_TIMESTAMP, IIO_CAPACITANCE, IIO_ALTVOLTAGE, IIO_CCT, IIO_PRESSURE, IIO_HUMIDITYRELATIVE, IIO_ACTIVITY, IIO_STEPS, IIO_ENERGY, IIO_DISTANCE, IIO_VELOCITY, IIO_CONCENTRATION, IIO_RESISTANCE, IIO_PH, IIO_UVINDEX, IIO_ELECTRICALCONDUCTIVITY, IIO_COUNT, IIO_INDEX, IIO_GRAVITY, }; enum iio_modifier { IIO_NO_MOD, IIO_MOD_X, IIO_MOD_Y, IIO_MOD_Z, IIO_MOD_X_AND_Y, IIO_MOD_X_AND_Z, IIO_MOD_Y_AND_Z, IIO_MOD_X_AND_Y_AND_Z, IIO_MOD_X_OR_Y, IIO_MOD_X_OR_Z, IIO_MOD_Y_OR_Z, IIO_MOD_X_OR_Y_OR_Z, IIO_MOD_LIGHT_BOTH, IIO_MOD_LIGHT_IR, IIO_MOD_ROOT_SUM_SQUARED_X_Y, IIO_MOD_SUM_SQUARED_X_Y_Z, IIO_MOD_LIGHT_CLEAR, IIO_MOD_LIGHT_RED, IIO_MOD_LIGHT_GREEN, IIO_MOD_LIGHT_BLUE, IIO_MOD_QUATERNION, IIO_MOD_TEMP_AMBIENT, IIO_MOD_TEMP_OBJECT, IIO_MOD_NORTH_MAGN, IIO_MOD_NORTH_TRUE, IIO_MOD_NORTH_MAGN_TILT_COMP, IIO_MOD_NORTH_TRUE_TILT_COMP, IIO_MOD_RUNNING, IIO_MOD_JOGGING, IIO_MOD_WALKING, IIO_MOD_STILL, IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z, IIO_MOD_I, IIO_MOD_Q, IIO_MOD_CO2, IIO_MOD_VOC, IIO_MOD_LIGHT_UV, }; enum iio_event_type { IIO_EV_TYPE_THRESH, IIO_EV_TYPE_MAG, IIO_EV_TYPE_ROC, IIO_EV_TYPE_THRESH_ADAPTIVE, IIO_EV_TYPE_MAG_ADAPTIVE, IIO_EV_TYPE_CHANGE, }; enum iio_event_direction { IIO_EV_DIR_EITHER, IIO_EV_DIR_RISING, IIO_EV_DIR_FALLING, IIO_EV_DIR_NONE, }; #endif /* _IIO_TYPES_H_ */ linux/iio/events.h000064400000002556151027430560010153 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* The industrial I/O - event passing to userspace * * Copyright (c) 2008-2011 Jonathan Cameron * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _IIO_EVENTS_H_ #define _IIO_EVENTS_H_ #include #include /** * struct iio_event_data - The actual event being pushed to userspace * @id: event identifier * @timestamp: best estimate of time of event occurrence (often from * the interrupt handler) */ struct iio_event_data { __u64 id; __s64 timestamp; }; #define IIO_GET_EVENT_FD_IOCTL _IOR('i', 0x90, int) #define IIO_EVENT_CODE_EXTRACT_TYPE(mask) ((mask >> 56) & 0xFF) #define IIO_EVENT_CODE_EXTRACT_DIR(mask) ((mask >> 48) & 0x7F) #define IIO_EVENT_CODE_EXTRACT_CHAN_TYPE(mask) ((mask >> 32) & 0xFF) /* Event code number extraction depends on which type of event we have. * Perhaps review this function in the future*/ #define IIO_EVENT_CODE_EXTRACT_CHAN(mask) ((__s16)(mask & 0xFFFF)) #define IIO_EVENT_CODE_EXTRACT_CHAN2(mask) ((__s16)(((mask) >> 16) & 0xFFFF)) #define IIO_EVENT_CODE_EXTRACT_MODIFIER(mask) ((mask >> 40) & 0xFF) #define IIO_EVENT_CODE_EXTRACT_DIFF(mask) (((mask) >> 55) & 0x1) #endif /* _IIO_EVENTS_H_ */ linux/kd.h000064400000014155151027430560006463 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_KD_H #define _LINUX_KD_H #include /* 0x4B is 'K', to avoid collision with termios and vt */ #define GIO_FONT 0x4B60 /* gets font in expanded form */ #define PIO_FONT 0x4B61 /* use font in expanded form */ #define GIO_FONTX 0x4B6B /* get font using struct consolefontdesc */ #define PIO_FONTX 0x4B6C /* set font using struct consolefontdesc */ struct consolefontdesc { unsigned short charcount; /* characters in font (256 or 512) */ unsigned short charheight; /* scan lines per character (1-32) */ char *chardata; /* font data in expanded form */ }; #define PIO_FONTRESET 0x4B6D /* reset to default font */ #define GIO_CMAP 0x4B70 /* gets colour palette on VGA+ */ #define PIO_CMAP 0x4B71 /* sets colour palette on VGA+ */ #define KIOCSOUND 0x4B2F /* start sound generation (0 for off) */ #define KDMKTONE 0x4B30 /* generate tone */ #define KDGETLED 0x4B31 /* return current led state */ #define KDSETLED 0x4B32 /* set led state [lights, not flags] */ #define LED_SCR 0x01 /* scroll lock led */ #define LED_NUM 0x02 /* num lock led */ #define LED_CAP 0x04 /* caps lock led */ #define KDGKBTYPE 0x4B33 /* get keyboard type */ #define KB_84 0x01 #define KB_101 0x02 /* this is what we always answer */ #define KB_OTHER 0x03 #define KDADDIO 0x4B34 /* add i/o port as valid */ #define KDDELIO 0x4B35 /* del i/o port as valid */ #define KDENABIO 0x4B36 /* enable i/o to video board */ #define KDDISABIO 0x4B37 /* disable i/o to video board */ #define KDSETMODE 0x4B3A /* set text/graphics mode */ #define KD_TEXT 0x00 #define KD_GRAPHICS 0x01 #define KD_TEXT0 0x02 /* obsolete */ #define KD_TEXT1 0x03 /* obsolete */ #define KDGETMODE 0x4B3B /* get current mode */ #define KDMAPDISP 0x4B3C /* map display into address space */ #define KDUNMAPDISP 0x4B3D /* unmap display from address space */ typedef char scrnmap_t; #define E_TABSZ 256 #define GIO_SCRNMAP 0x4B40 /* get screen mapping from kernel */ #define PIO_SCRNMAP 0x4B41 /* put screen mapping table in kernel */ #define GIO_UNISCRNMAP 0x4B69 /* get full Unicode screen mapping */ #define PIO_UNISCRNMAP 0x4B6A /* set full Unicode screen mapping */ #define GIO_UNIMAP 0x4B66 /* get unicode-to-font mapping from kernel */ struct unipair { unsigned short unicode; unsigned short fontpos; }; struct unimapdesc { unsigned short entry_ct; struct unipair *entries; }; #define PIO_UNIMAP 0x4B67 /* put unicode-to-font mapping in kernel */ #define PIO_UNIMAPCLR 0x4B68 /* clear table, possibly advise hash algorithm */ struct unimapinit { unsigned short advised_hashsize; /* 0 if no opinion */ unsigned short advised_hashstep; /* 0 if no opinion */ unsigned short advised_hashlevel; /* 0 if no opinion */ }; #define UNI_DIRECT_BASE 0xF000 /* start of Direct Font Region */ #define UNI_DIRECT_MASK 0x01FF /* Direct Font Region bitmask */ #define K_RAW 0x00 #define K_XLATE 0x01 #define K_MEDIUMRAW 0x02 #define K_UNICODE 0x03 #define K_OFF 0x04 #define KDGKBMODE 0x4B44 /* gets current keyboard mode */ #define KDSKBMODE 0x4B45 /* sets current keyboard mode */ #define K_METABIT 0x03 #define K_ESCPREFIX 0x04 #define KDGKBMETA 0x4B62 /* gets meta key handling mode */ #define KDSKBMETA 0x4B63 /* sets meta key handling mode */ #define K_SCROLLLOCK 0x01 #define K_NUMLOCK 0x02 #define K_CAPSLOCK 0x04 #define KDGKBLED 0x4B64 /* get led flags (not lights) */ #define KDSKBLED 0x4B65 /* set led flags (not lights) */ struct kbentry { unsigned char kb_table; unsigned char kb_index; unsigned short kb_value; }; #define K_NORMTAB 0x00 #define K_SHIFTTAB 0x01 #define K_ALTTAB 0x02 #define K_ALTSHIFTTAB 0x03 #define KDGKBENT 0x4B46 /* gets one entry in translation table */ #define KDSKBENT 0x4B47 /* sets one entry in translation table */ struct kbsentry { unsigned char kb_func; unsigned char kb_string[512]; }; #define KDGKBSENT 0x4B48 /* gets one function key string entry */ #define KDSKBSENT 0x4B49 /* sets one function key string entry */ struct kbdiacr { unsigned char diacr, base, result; }; struct kbdiacrs { unsigned int kb_cnt; /* number of entries in following array */ struct kbdiacr kbdiacr[256]; /* MAX_DIACR from keyboard.h */ }; #define KDGKBDIACR 0x4B4A /* read kernel accent table */ #define KDSKBDIACR 0x4B4B /* write kernel accent table */ struct kbdiacruc { unsigned int diacr, base, result; }; struct kbdiacrsuc { unsigned int kb_cnt; /* number of entries in following array */ struct kbdiacruc kbdiacruc[256]; /* MAX_DIACR from keyboard.h */ }; #define KDGKBDIACRUC 0x4BFA /* read kernel accent table - UCS */ #define KDSKBDIACRUC 0x4BFB /* write kernel accent table - UCS */ struct kbkeycode { unsigned int scancode, keycode; }; #define KDGETKEYCODE 0x4B4C /* read kernel keycode table entry */ #define KDSETKEYCODE 0x4B4D /* write kernel keycode table entry */ #define KDSIGACCEPT 0x4B4E /* accept kbd generated signals */ struct kbd_repeat { int delay; /* in msec; <= 0: don't change */ int period; /* in msec; <= 0: don't change */ /* earlier this field was misnamed "rate" */ }; #define KDKBDREP 0x4B52 /* set keyboard delay/repeat rate; * actually used values are returned */ #define KDFONTOP 0x4B72 /* font operations */ struct console_font_op { unsigned int op; /* operation code KD_FONT_OP_* */ unsigned int flags; /* KD_FONT_FLAG_* */ unsigned int width, height; /* font size */ unsigned int charcount; unsigned char *data; /* font data with height fixed to 32 */ }; struct console_font { unsigned int width, height; /* font size */ unsigned int charcount; unsigned char *data; /* font data with height fixed to 32 */ }; #define KD_FONT_OP_SET 0 /* Set font */ #define KD_FONT_OP_GET 1 /* Get font */ #define KD_FONT_OP_SET_DEFAULT 2 /* Set font to default, data points to name / NULL */ #define KD_FONT_OP_COPY 3 /* Copy from another console */ #define KD_FONT_FLAG_DONT_RECALC 1 /* Don't recalculate hw charcell size [compat] */ /* note: 0x4B00-0x4B4E all have had a value at some time; don't reuse for the time being */ /* note: 0x4B60-0x4B6D, 0x4B70-0x4B72 used above */ #endif /* _LINUX_KD_H */ linux/usb/midi.h000064400000006552151027430560007602 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * -- USB MIDI definitions. * * Copyright (C) 2006 Thumtronics Pty Ltd. * Developed for Thumtronics by Grey Innovation * Ben Williamson * * This software is distributed under the terms of the GNU General Public * License ("GPL") version 2, as published by the Free Software Foundation. * * This file holds USB constants and structures defined * by the USB Device Class Definition for MIDI Devices. * Comments below reference relevant sections of that document: * * http://www.usb.org/developers/devclass_docs/midi10.pdf */ #ifndef __LINUX_USB_MIDI_H #define __LINUX_USB_MIDI_H #include /* A.1 MS Class-Specific Interface Descriptor Subtypes */ #define USB_MS_HEADER 0x01 #define USB_MS_MIDI_IN_JACK 0x02 #define USB_MS_MIDI_OUT_JACK 0x03 #define USB_MS_ELEMENT 0x04 /* A.2 MS Class-Specific Endpoint Descriptor Subtypes */ #define USB_MS_GENERAL 0x01 /* A.3 MS MIDI IN and OUT Jack Types */ #define USB_MS_EMBEDDED 0x01 #define USB_MS_EXTERNAL 0x02 /* 6.1.2.1 Class-Specific MS Interface Header Descriptor */ struct usb_ms_header_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __le16 bcdMSC; __le16 wTotalLength; } __attribute__ ((packed)); #define USB_DT_MS_HEADER_SIZE 7 /* 6.1.2.2 MIDI IN Jack Descriptor */ struct usb_midi_in_jack_descriptor { __u8 bLength; __u8 bDescriptorType; /* USB_DT_CS_INTERFACE */ __u8 bDescriptorSubtype; /* USB_MS_MIDI_IN_JACK */ __u8 bJackType; /* USB_MS_EMBEDDED/EXTERNAL */ __u8 bJackID; __u8 iJack; } __attribute__ ((packed)); #define USB_DT_MIDI_IN_SIZE 6 struct usb_midi_source_pin { __u8 baSourceID; __u8 baSourcePin; } __attribute__ ((packed)); /* 6.1.2.3 MIDI OUT Jack Descriptor */ struct usb_midi_out_jack_descriptor { __u8 bLength; __u8 bDescriptorType; /* USB_DT_CS_INTERFACE */ __u8 bDescriptorSubtype; /* USB_MS_MIDI_OUT_JACK */ __u8 bJackType; /* USB_MS_EMBEDDED/EXTERNAL */ __u8 bJackID; __u8 bNrInputPins; /* p */ struct usb_midi_source_pin pins[]; /* [p] */ /*__u8 iJack; -- omitted due to variable-sized pins[] */ } __attribute__ ((packed)); #define USB_DT_MIDI_OUT_SIZE(p) (7 + 2 * (p)) /* As above, but more useful for defining your own descriptors: */ #define DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(p) \ struct usb_midi_out_jack_descriptor_##p { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubtype; \ __u8 bJackType; \ __u8 bJackID; \ __u8 bNrInputPins; \ struct usb_midi_source_pin pins[p]; \ __u8 iJack; \ } __attribute__ ((packed)) /* 6.2.2 Class-Specific MS Bulk Data Endpoint Descriptor */ struct usb_ms_endpoint_descriptor { __u8 bLength; /* 4+n */ __u8 bDescriptorType; /* USB_DT_CS_ENDPOINT */ __u8 bDescriptorSubtype; /* USB_MS_GENERAL */ __u8 bNumEmbMIDIJack; /* n */ __u8 baAssocJackID[]; /* [n] */ } __attribute__ ((packed)); #define USB_DT_MS_ENDPOINT_SIZE(n) (4 + (n)) /* As above, but more useful for defining your own descriptors: */ #define DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(n) \ struct usb_ms_endpoint_descriptor_##n { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubtype; \ __u8 bNumEmbMIDIJack; \ __u8 baAssocJackID[n]; \ } __attribute__ ((packed)) #endif /* __LINUX_USB_MIDI_H */ linux/usb/ch11.h000064400000021675151027430560007417 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * This file holds Hub protocol constants and data structures that are * defined in chapter 11 (Hub Specification) of the USB 2.0 specification. * * It is used/shared between the USB core, the HCDs and couple of other USB * drivers. */ #ifndef __LINUX_CH11_H #define __LINUX_CH11_H #include /* __u8 etc */ /* This is arbitrary. * From USB 2.0 spec Table 11-13, offset 7, a hub can * have up to 255 ports. The most yet reported is 10. * * Current Wireless USB host hardware (Intel i1480 for example) allows * up to 22 devices to connect. Upcoming hardware might raise that * limit. Because the arrays need to add a bit for hub status data, we * use 31, so plus one evens out to four bytes. */ #define USB_MAXCHILDREN 31 /* See USB 3.1 spec Table 10-5 */ #define USB_SS_MAXPORTS 15 /* * Hub request types */ #define USB_RT_HUB (USB_TYPE_CLASS | USB_RECIP_DEVICE) #define USB_RT_PORT (USB_TYPE_CLASS | USB_RECIP_OTHER) /* * Port status type for GetPortStatus requests added in USB 3.1 * See USB 3.1 spec Table 10-12 */ #define HUB_PORT_STATUS 0 #define HUB_PORT_PD_STATUS 1 #define HUB_EXT_PORT_STATUS 2 /* * Hub class requests * See USB 2.0 spec Table 11-16 */ #define HUB_CLEAR_TT_BUFFER 8 #define HUB_RESET_TT 9 #define HUB_GET_TT_STATE 10 #define HUB_STOP_TT 11 /* * Hub class additional requests defined by USB 3.0 spec * See USB 3.0 spec Table 10-6 */ #define HUB_SET_DEPTH 12 #define HUB_GET_PORT_ERR_COUNT 13 /* * Hub Class feature numbers * See USB 2.0 spec Table 11-17 */ #define C_HUB_LOCAL_POWER 0 #define C_HUB_OVER_CURRENT 1 /* * Port feature numbers * See USB 2.0 spec Table 11-17 */ #define USB_PORT_FEAT_CONNECTION 0 #define USB_PORT_FEAT_ENABLE 1 #define USB_PORT_FEAT_SUSPEND 2 /* L2 suspend */ #define USB_PORT_FEAT_OVER_CURRENT 3 #define USB_PORT_FEAT_RESET 4 #define USB_PORT_FEAT_L1 5 /* L1 suspend */ #define USB_PORT_FEAT_POWER 8 #define USB_PORT_FEAT_LOWSPEED 9 /* Should never be used */ #define USB_PORT_FEAT_C_CONNECTION 16 #define USB_PORT_FEAT_C_ENABLE 17 #define USB_PORT_FEAT_C_SUSPEND 18 #define USB_PORT_FEAT_C_OVER_CURRENT 19 #define USB_PORT_FEAT_C_RESET 20 #define USB_PORT_FEAT_TEST 21 #define USB_PORT_FEAT_INDICATOR 22 #define USB_PORT_FEAT_C_PORT_L1 23 /* * Port feature selectors added by USB 3.0 spec. * See USB 3.0 spec Table 10-7 */ #define USB_PORT_FEAT_LINK_STATE 5 #define USB_PORT_FEAT_U1_TIMEOUT 23 #define USB_PORT_FEAT_U2_TIMEOUT 24 #define USB_PORT_FEAT_C_PORT_LINK_STATE 25 #define USB_PORT_FEAT_C_PORT_CONFIG_ERROR 26 #define USB_PORT_FEAT_REMOTE_WAKE_MASK 27 #define USB_PORT_FEAT_BH_PORT_RESET 28 #define USB_PORT_FEAT_C_BH_PORT_RESET 29 #define USB_PORT_FEAT_FORCE_LINKPM_ACCEPT 30 #define USB_PORT_LPM_TIMEOUT(p) (((p) & 0xff) << 8) /* USB 3.0 hub remote wake mask bits, see table 10-14 */ #define USB_PORT_FEAT_REMOTE_WAKE_CONNECT (1 << 8) #define USB_PORT_FEAT_REMOTE_WAKE_DISCONNECT (1 << 9) #define USB_PORT_FEAT_REMOTE_WAKE_OVER_CURRENT (1 << 10) /* * Hub Status and Hub Change results * See USB 2.0 spec Table 11-19 and Table 11-20 * USB 3.1 extends the port status request and may return 4 additional bytes. * See USB 3.1 spec section 10.16.2.6 Table 10-12 and 10-15 */ struct usb_port_status { __le16 wPortStatus; __le16 wPortChange; __le32 dwExtPortStatus; } __attribute__ ((packed)); /* * wPortStatus bit field * See USB 2.0 spec Table 11-21 */ #define USB_PORT_STAT_CONNECTION 0x0001 #define USB_PORT_STAT_ENABLE 0x0002 #define USB_PORT_STAT_SUSPEND 0x0004 #define USB_PORT_STAT_OVERCURRENT 0x0008 #define USB_PORT_STAT_RESET 0x0010 #define USB_PORT_STAT_L1 0x0020 /* bits 6 to 7 are reserved */ #define USB_PORT_STAT_POWER 0x0100 #define USB_PORT_STAT_LOW_SPEED 0x0200 #define USB_PORT_STAT_HIGH_SPEED 0x0400 #define USB_PORT_STAT_TEST 0x0800 #define USB_PORT_STAT_INDICATOR 0x1000 /* bits 13 to 15 are reserved */ /* * Additions to wPortStatus bit field from USB 3.0 * See USB 3.0 spec Table 10-10 */ #define USB_PORT_STAT_LINK_STATE 0x01e0 #define USB_SS_PORT_STAT_POWER 0x0200 #define USB_SS_PORT_STAT_SPEED 0x1c00 #define USB_PORT_STAT_SPEED_5GBPS 0x0000 /* Valid only if port is enabled */ /* Bits that are the same from USB 2.0 */ #define USB_SS_PORT_STAT_MASK (USB_PORT_STAT_CONNECTION | \ USB_PORT_STAT_ENABLE | \ USB_PORT_STAT_OVERCURRENT | \ USB_PORT_STAT_RESET) /* * Definitions for PORT_LINK_STATE values * (bits 5-8) in wPortStatus */ #define USB_SS_PORT_LS_U0 0x0000 #define USB_SS_PORT_LS_U1 0x0020 #define USB_SS_PORT_LS_U2 0x0040 #define USB_SS_PORT_LS_U3 0x0060 #define USB_SS_PORT_LS_SS_DISABLED 0x0080 #define USB_SS_PORT_LS_RX_DETECT 0x00a0 #define USB_SS_PORT_LS_SS_INACTIVE 0x00c0 #define USB_SS_PORT_LS_POLLING 0x00e0 #define USB_SS_PORT_LS_RECOVERY 0x0100 #define USB_SS_PORT_LS_HOT_RESET 0x0120 #define USB_SS_PORT_LS_COMP_MOD 0x0140 #define USB_SS_PORT_LS_LOOPBACK 0x0160 /* * wPortChange bit field * See USB 2.0 spec Table 11-22 and USB 2.0 LPM ECN Table-4.10 * Bits 0 to 5 shown, bits 6 to 15 are reserved */ #define USB_PORT_STAT_C_CONNECTION 0x0001 #define USB_PORT_STAT_C_ENABLE 0x0002 #define USB_PORT_STAT_C_SUSPEND 0x0004 #define USB_PORT_STAT_C_OVERCURRENT 0x0008 #define USB_PORT_STAT_C_RESET 0x0010 #define USB_PORT_STAT_C_L1 0x0020 /* * USB 3.0 wPortChange bit fields * See USB 3.0 spec Table 10-11 */ #define USB_PORT_STAT_C_BH_RESET 0x0020 #define USB_PORT_STAT_C_LINK_STATE 0x0040 #define USB_PORT_STAT_C_CONFIG_ERROR 0x0080 /* * USB 3.1 dwExtPortStatus field masks * See USB 3.1 spec 10.16.2.6.3 Table 10-15 */ #define USB_EXT_PORT_STAT_RX_SPEED_ID 0x0000000f #define USB_EXT_PORT_STAT_TX_SPEED_ID 0x000000f0 #define USB_EXT_PORT_STAT_RX_LANES 0x00000f00 #define USB_EXT_PORT_STAT_TX_LANES 0x0000f000 #define USB_EXT_PORT_RX_LANES(p) \ (((p) & USB_EXT_PORT_STAT_RX_LANES) >> 8) #define USB_EXT_PORT_TX_LANES(p) \ (((p) & USB_EXT_PORT_STAT_TX_LANES) >> 12) /* * wHubCharacteristics (masks) * See USB 2.0 spec Table 11-13, offset 3 */ #define HUB_CHAR_LPSM 0x0003 /* Logical Power Switching Mode mask */ #define HUB_CHAR_COMMON_LPSM 0x0000 /* All ports power control at once */ #define HUB_CHAR_INDV_PORT_LPSM 0x0001 /* per-port power control */ #define HUB_CHAR_NO_LPSM 0x0002 /* no power switching */ #define HUB_CHAR_COMPOUND 0x0004 /* hub is part of a compound device */ #define HUB_CHAR_OCPM 0x0018 /* Over-Current Protection Mode mask */ #define HUB_CHAR_COMMON_OCPM 0x0000 /* All ports Over-Current reporting */ #define HUB_CHAR_INDV_PORT_OCPM 0x0008 /* per-port Over-current reporting */ #define HUB_CHAR_NO_OCPM 0x0010 /* No Over-current Protection support */ #define HUB_CHAR_TTTT 0x0060 /* TT Think Time mask */ #define HUB_CHAR_PORTIND 0x0080 /* per-port indicators (LEDs) */ struct usb_hub_status { __le16 wHubStatus; __le16 wHubChange; } __attribute__ ((packed)); /* * Hub Status & Hub Change bit masks * See USB 2.0 spec Table 11-19 and Table 11-20 * Bits 0 and 1 for wHubStatus and wHubChange * Bits 2 to 15 are reserved for both */ #define HUB_STATUS_LOCAL_POWER 0x0001 #define HUB_STATUS_OVERCURRENT 0x0002 #define HUB_CHANGE_LOCAL_POWER 0x0001 #define HUB_CHANGE_OVERCURRENT 0x0002 /* * Hub descriptor * See USB 2.0 spec Table 11-13 */ #define USB_DT_HUB (USB_TYPE_CLASS | 0x09) #define USB_DT_SS_HUB (USB_TYPE_CLASS | 0x0a) #define USB_DT_HUB_NONVAR_SIZE 7 #define USB_DT_SS_HUB_SIZE 12 /* * Hub Device descriptor * USB Hub class device protocols */ #define USB_HUB_PR_FS 0 /* Full speed hub */ #define USB_HUB_PR_HS_NO_TT 0 /* Hi-speed hub without TT */ #define USB_HUB_PR_HS_SINGLE_TT 1 /* Hi-speed hub with single TT */ #define USB_HUB_PR_HS_MULTI_TT 2 /* Hi-speed hub with multiple TT */ #define USB_HUB_PR_SS 3 /* Super speed hub */ struct usb_hub_descriptor { __u8 bDescLength; __u8 bDescriptorType; __u8 bNbrPorts; __le16 wHubCharacteristics; __u8 bPwrOn2PwrGood; __u8 bHubContrCurrent; /* 2.0 and 3.0 hubs differ here */ union { struct { /* add 1 bit for hub status change; round to bytes */ __u8 DeviceRemovable[(USB_MAXCHILDREN + 1 + 7) / 8]; __u8 PortPwrCtrlMask[(USB_MAXCHILDREN + 1 + 7) / 8]; } __attribute__ ((packed)) hs; struct { __u8 bHubHdrDecLat; __le16 wHubDelay; __le16 DeviceRemovable; } __attribute__ ((packed)) ss; } u; } __attribute__ ((packed)); /* port indicator status selectors, tables 11-7 and 11-25 */ #define HUB_LED_AUTO 0 #define HUB_LED_AMBER 1 #define HUB_LED_GREEN 2 #define HUB_LED_OFF 3 enum hub_led_mode { INDICATOR_AUTO = 0, INDICATOR_CYCLE, /* software blinks for attention: software, hardware, reserved */ INDICATOR_GREEN_BLINK, INDICATOR_GREEN_BLINK_OFF, INDICATOR_AMBER_BLINK, INDICATOR_AMBER_BLINK_OFF, INDICATOR_ALT_BLINK, INDICATOR_ALT_BLINK_OFF } __attribute__ ((packed)); /* Transaction Translator Think Times, in bits */ #define HUB_TTTT_8_BITS 0x00 #define HUB_TTTT_16_BITS 0x20 #define HUB_TTTT_24_BITS 0x40 #define HUB_TTTT_32_BITS 0x60 #endif /* __LINUX_CH11_H */ linux/usb/functionfs.h000064400000024202151027430560011026 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_FUNCTIONFS_H__ #define __LINUX_FUNCTIONFS_H__ #include #include #include enum { FUNCTIONFS_DESCRIPTORS_MAGIC = 1, FUNCTIONFS_STRINGS_MAGIC = 2, FUNCTIONFS_DESCRIPTORS_MAGIC_V2 = 3, }; enum functionfs_flags { FUNCTIONFS_HAS_FS_DESC = 1, FUNCTIONFS_HAS_HS_DESC = 2, FUNCTIONFS_HAS_SS_DESC = 4, FUNCTIONFS_HAS_MS_OS_DESC = 8, FUNCTIONFS_VIRTUAL_ADDR = 16, FUNCTIONFS_EVENTFD = 32, FUNCTIONFS_ALL_CTRL_RECIP = 64, FUNCTIONFS_CONFIG0_SETUP = 128, }; /* Descriptor of an non-audio endpoint */ struct usb_endpoint_descriptor_no_audio { __u8 bLength; __u8 bDescriptorType; __u8 bEndpointAddress; __u8 bmAttributes; __le16 wMaxPacketSize; __u8 bInterval; } __attribute__((packed)); struct usb_functionfs_descs_head_v2 { __le32 magic; __le32 length; __le32 flags; /* * __le32 fs_count, hs_count, fs_count; must be included manually in * the structure taking flags into consideration. */ } __attribute__((packed)); /* Legacy format, deprecated as of 3.14. */ struct usb_functionfs_descs_head { __le32 magic; __le32 length; __le32 fs_count; __le32 hs_count; } __attribute__((packed, deprecated)); /* MS OS Descriptor header */ struct usb_os_desc_header { __u8 interface; __le32 dwLength; __le16 bcdVersion; __le16 wIndex; union { struct { __u8 bCount; __u8 Reserved; }; __le16 wCount; }; } __attribute__((packed)); struct usb_ext_compat_desc { __u8 bFirstInterfaceNumber; __u8 Reserved1; __u8 CompatibleID[8]; __u8 SubCompatibleID[8]; __u8 Reserved2[6]; }; struct usb_ext_prop_desc { __le32 dwSize; __le32 dwPropertyDataType; __le16 wPropertyNameLength; } __attribute__((packed)); /* * Descriptors format: * * | off | name | type | description | * |-----+-----------+--------------+--------------------------------------| * | 0 | magic | LE32 | FUNCTIONFS_DESCRIPTORS_MAGIC_V2 | * | 4 | length | LE32 | length of the whole data chunk | * | 8 | flags | LE32 | combination of functionfs_flags | * | | eventfd | LE32 | eventfd file descriptor | * | | fs_count | LE32 | number of full-speed descriptors | * | | hs_count | LE32 | number of high-speed descriptors | * | | ss_count | LE32 | number of super-speed descriptors | * | | os_count | LE32 | number of MS OS descriptors | * | | fs_descrs | Descriptor[] | list of full-speed descriptors | * | | hs_descrs | Descriptor[] | list of high-speed descriptors | * | | ss_descrs | Descriptor[] | list of super-speed descriptors | * | | os_descrs | OSDesc[] | list of MS OS descriptors | * * Depending on which flags are set, various fields may be missing in the * structure. Any flags that are not recognised cause the whole block to be * rejected with -ENOSYS. * * Legacy descriptors format (deprecated as of 3.14): * * | off | name | type | description | * |-----+-----------+--------------+--------------------------------------| * | 0 | magic | LE32 | FUNCTIONFS_DESCRIPTORS_MAGIC | * | 4 | length | LE32 | length of the whole data chunk | * | 8 | fs_count | LE32 | number of full-speed descriptors | * | 12 | hs_count | LE32 | number of high-speed descriptors | * | 16 | fs_descrs | Descriptor[] | list of full-speed descriptors | * | | hs_descrs | Descriptor[] | list of high-speed descriptors | * * All numbers must be in little endian order. * * Descriptor[] is an array of valid USB descriptors which have the following * format: * * | off | name | type | description | * |-----+-----------------+------+--------------------------| * | 0 | bLength | U8 | length of the descriptor | * | 1 | bDescriptorType | U8 | descriptor type | * | 2 | payload | | descriptor's payload | * * OSDesc[] is an array of valid MS OS Feature Descriptors which have one of * the following formats: * * | off | name | type | description | * |-----+-----------------+------+--------------------------| * | 0 | inteface | U8 | related interface number | * | 1 | dwLength | U32 | length of the descriptor | * | 5 | bcdVersion | U16 | currently supported: 1 | * | 7 | wIndex | U16 | currently supported: 4 | * | 9 | bCount | U8 | number of ext. compat. | * | 10 | Reserved | U8 | 0 | * | 11 | ExtCompat[] | | list of ext. compat. d. | * * | off | name | type | description | * |-----+-----------------+------+--------------------------| * | 0 | inteface | U8 | related interface number | * | 1 | dwLength | U32 | length of the descriptor | * | 5 | bcdVersion | U16 | currently supported: 1 | * | 7 | wIndex | U16 | currently supported: 5 | * | 9 | wCount | U16 | number of ext. compat. | * | 11 | ExtProp[] | | list of ext. prop. d. | * * ExtCompat[] is an array of valid Extended Compatiblity descriptors * which have the following format: * * | off | name | type | description | * |-----+-----------------------+------+-------------------------------------| * | 0 | bFirstInterfaceNumber | U8 | index of the interface or of the 1st| * | | | | interface in an IAD group | * | 1 | Reserved | U8 | 1 | * | 2 | CompatibleID | U8[8]| compatible ID string | * | 10 | SubCompatibleID | U8[8]| subcompatible ID string | * | 18 | Reserved | U8[6]| 0 | * * ExtProp[] is an array of valid Extended Properties descriptors * which have the following format: * * | off | name | type | description | * |-----+-----------------------+------+-------------------------------------| * | 0 | dwSize | U32 | length of the descriptor | * | 4 | dwPropertyDataType | U32 | 1..7 | * | 8 | wPropertyNameLength | U16 | bPropertyName length (NL) | * | 10 | bPropertyName |U8[NL]| name of this property | * |10+NL| dwPropertyDataLength | U32 | bPropertyData length (DL) | * |14+NL| bProperty |U8[DL]| payload of this property | */ struct usb_functionfs_strings_head { __le32 magic; __le32 length; __le32 str_count; __le32 lang_count; } __attribute__((packed)); /* * Strings format: * * | off | name | type | description | * |-----+------------+-----------------------+----------------------------| * | 0 | magic | LE32 | FUNCTIONFS_STRINGS_MAGIC | * | 4 | length | LE32 | length of the data chunk | * | 8 | str_count | LE32 | number of strings | * | 12 | lang_count | LE32 | number of languages | * | 16 | stringtab | StringTab[lang_count] | table of strings per lang | * * For each language there is one stringtab entry (ie. there are lang_count * stringtab entires). Each StringTab has following format: * * | off | name | type | description | * |-----+---------+-------------------+------------------------------------| * | 0 | lang | LE16 | language code | * | 2 | strings | String[str_count] | array of strings in given language | * * For each string there is one strings entry (ie. there are str_count * string entries). Each String is a NUL terminated string encoded in * UTF-8. */ /* * Events are delivered on the ep0 file descriptor, when the user mode driver * reads from this file descriptor after writing the descriptors. Don't * stop polling this descriptor. */ enum usb_functionfs_event_type { FUNCTIONFS_BIND, FUNCTIONFS_UNBIND, FUNCTIONFS_ENABLE, FUNCTIONFS_DISABLE, FUNCTIONFS_SETUP, FUNCTIONFS_SUSPEND, FUNCTIONFS_RESUME }; /* NOTE: this structure must stay the same size and layout on * both 32-bit and 64-bit kernels. */ struct usb_functionfs_event { union { /* SETUP: packet; DATA phase i/o precedes next event *(setup.bmRequestType & USB_DIR_IN) flags direction */ struct usb_ctrlrequest setup; } __attribute__((packed)) u; /* enum usb_functionfs_event_type */ __u8 type; __u8 _pad[3]; } __attribute__((packed)); /* Endpoint ioctls */ /* The same as in gadgetfs */ /* IN transfers may be reported to the gadget driver as complete * when the fifo is loaded, before the host reads the data; * OUT transfers may be reported to the host's "client" driver as * complete when they're sitting in the FIFO unread. * THIS returns how many bytes are "unclaimed" in the endpoint fifo * (needed for precise fault handling, when the hardware allows it) */ #define FUNCTIONFS_FIFO_STATUS _IO('g', 1) /* discards any unclaimed data in the fifo. */ #define FUNCTIONFS_FIFO_FLUSH _IO('g', 2) /* resets endpoint halt+toggle; used to implement set_interface. * some hardware (like pxa2xx) can't support this. */ #define FUNCTIONFS_CLEAR_HALT _IO('g', 3) /* Specific for functionfs */ /* * Returns reverse mapping of an interface. Called on EP0. If there * is no such interface returns -EDOM. If function is not active * returns -ENODEV. */ #define FUNCTIONFS_INTERFACE_REVMAP _IO('g', 128) /* * Returns real bEndpointAddress of an endpoint. If endpoint shuts down * during the call, returns -ESHUTDOWN. */ #define FUNCTIONFS_ENDPOINT_REVMAP _IO('g', 129) /* * Returns endpoint descriptor. If endpoint shuts down during the call, * returns -ESHUTDOWN. */ #define FUNCTIONFS_ENDPOINT_DESC _IOR('g', 130, \ struct usb_endpoint_descriptor) #endif /* __LINUX_FUNCTIONFS_H__ */ linux/usb/gadgetfs.h000064400000005402151027430560010435 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Filesystem based user-mode API to USB Gadget controller hardware * * Other than ep0 operations, most things are done by read() and write() * on endpoint files found in one directory. They are configured by * writing descriptors, and then may be used for normal stream style * i/o requests. When ep0 is configured, the device can enumerate; * when it's closed, the device disconnects from usb. Operations on * ep0 require ioctl() operations. * * Configuration and device descriptors get written to /dev/gadget/$CHIP, * which may then be used to read usb_gadgetfs_event structs. The driver * may activate endpoints as it handles SET_CONFIGURATION setup events, * or earlier; writing endpoint descriptors to /dev/gadget/$ENDPOINT * then performing data transfers by reading or writing. */ #ifndef __LINUX_USB_GADGETFS_H #define __LINUX_USB_GADGETFS_H #include #include #include /* * Events are delivered on the ep0 file descriptor, when the user mode driver * reads from this file descriptor after writing the descriptors. Don't * stop polling this descriptor. */ enum usb_gadgetfs_event_type { GADGETFS_NOP = 0, GADGETFS_CONNECT, GADGETFS_DISCONNECT, GADGETFS_SETUP, GADGETFS_SUSPEND, /* and likely more ! */ }; /* NOTE: this structure must stay the same size and layout on * both 32-bit and 64-bit kernels. */ struct usb_gadgetfs_event { union { /* NOP, DISCONNECT, SUSPEND: nothing * ... some hardware can't report disconnection */ /* CONNECT: just the speed */ enum usb_device_speed speed; /* SETUP: packet; DATA phase i/o precedes next event *(setup.bmRequestType & USB_DIR_IN) flags direction * ... includes SET_CONFIGURATION, SET_INTERFACE */ struct usb_ctrlrequest setup; } u; enum usb_gadgetfs_event_type type; }; /* The 'g' code is also used by printer gadget ioctl requests. * Don't add any colliding codes to either driver, and keep * them in unique ranges (size 0x20 for now). */ /* endpoint ioctls */ /* IN transfers may be reported to the gadget driver as complete * when the fifo is loaded, before the host reads the data; * OUT transfers may be reported to the host's "client" driver as * complete when they're sitting in the FIFO unread. * THIS returns how many bytes are "unclaimed" in the endpoint fifo * (needed for precise fault handling, when the hardware allows it) */ #define GADGETFS_FIFO_STATUS _IO('g', 1) /* discards any unclaimed data in the fifo. */ #define GADGETFS_FIFO_FLUSH _IO('g', 2) /* resets endpoint halt+toggle; used to implement set_interface. * some hardware (like pxa2xx) can't support this. */ #define GADGETFS_CLEAR_HALT _IO('g', 3) #endif /* __LINUX_USB_GADGETFS_H */ linux/usb/charger.h000064400000001126151027430560010263 0ustar00/* * This file defines the USB charger type and state that are needed for * USB device APIs. */ #ifndef __LINUX_USB_CHARGER_H #define __LINUX_USB_CHARGER_H /* * USB charger type: * SDP (Standard Downstream Port) * DCP (Dedicated Charging Port) * CDP (Charging Downstream Port) * ACA (Accessory Charger Adapters) */ enum usb_charger_type { UNKNOWN_TYPE = 0, SDP_TYPE = 1, DCP_TYPE = 2, CDP_TYPE = 3, ACA_TYPE = 4, }; /* USB charger state */ enum usb_charger_state { USB_CHARGER_DEFAULT = 0, USB_CHARGER_PRESENT = 1, USB_CHARGER_ABSENT = 2, }; #endif /* __LINUX_USB_CHARGER_H */ linux/usb/cdc.h000064400000032246151027430560007410 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * USB Communications Device Class (CDC) definitions * * CDC says how to talk to lots of different types of network adapters, * notably ethernet adapters and various modems. It's used mostly with * firmware based USB peripherals. */ #ifndef __UAPI_LINUX_USB_CDC_H #define __UAPI_LINUX_USB_CDC_H #include #define USB_CDC_SUBCLASS_ACM 0x02 #define USB_CDC_SUBCLASS_ETHERNET 0x06 #define USB_CDC_SUBCLASS_WHCM 0x08 #define USB_CDC_SUBCLASS_DMM 0x09 #define USB_CDC_SUBCLASS_MDLM 0x0a #define USB_CDC_SUBCLASS_OBEX 0x0b #define USB_CDC_SUBCLASS_EEM 0x0c #define USB_CDC_SUBCLASS_NCM 0x0d #define USB_CDC_SUBCLASS_MBIM 0x0e #define USB_CDC_PROTO_NONE 0 #define USB_CDC_ACM_PROTO_AT_V25TER 1 #define USB_CDC_ACM_PROTO_AT_PCCA101 2 #define USB_CDC_ACM_PROTO_AT_PCCA101_WAKE 3 #define USB_CDC_ACM_PROTO_AT_GSM 4 #define USB_CDC_ACM_PROTO_AT_3G 5 #define USB_CDC_ACM_PROTO_AT_CDMA 6 #define USB_CDC_ACM_PROTO_VENDOR 0xff #define USB_CDC_PROTO_EEM 7 #define USB_CDC_NCM_PROTO_NTB 1 #define USB_CDC_MBIM_PROTO_NTB 2 /*-------------------------------------------------------------------------*/ /* * Class-Specific descriptors ... there are a couple dozen of them */ #define USB_CDC_HEADER_TYPE 0x00 /* header_desc */ #define USB_CDC_CALL_MANAGEMENT_TYPE 0x01 /* call_mgmt_descriptor */ #define USB_CDC_ACM_TYPE 0x02 /* acm_descriptor */ #define USB_CDC_UNION_TYPE 0x06 /* union_desc */ #define USB_CDC_COUNTRY_TYPE 0x07 #define USB_CDC_NETWORK_TERMINAL_TYPE 0x0a /* network_terminal_desc */ #define USB_CDC_ETHERNET_TYPE 0x0f /* ether_desc */ #define USB_CDC_WHCM_TYPE 0x11 #define USB_CDC_MDLM_TYPE 0x12 /* mdlm_desc */ #define USB_CDC_MDLM_DETAIL_TYPE 0x13 /* mdlm_detail_desc */ #define USB_CDC_DMM_TYPE 0x14 #define USB_CDC_OBEX_TYPE 0x15 #define USB_CDC_NCM_TYPE 0x1a #define USB_CDC_MBIM_TYPE 0x1b #define USB_CDC_MBIM_EXTENDED_TYPE 0x1c /* "Header Functional Descriptor" from CDC spec 5.2.3.1 */ struct usb_cdc_header_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdCDC; } __attribute__ ((packed)); /* "Call Management Descriptor" from CDC spec 5.2.3.2 */ struct usb_cdc_call_mgmt_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bmCapabilities; #define USB_CDC_CALL_MGMT_CAP_CALL_MGMT 0x01 #define USB_CDC_CALL_MGMT_CAP_DATA_INTF 0x02 __u8 bDataInterface; } __attribute__ ((packed)); /* "Abstract Control Management Descriptor" from CDC spec 5.2.3.3 */ struct usb_cdc_acm_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bmCapabilities; } __attribute__ ((packed)); /* capabilities from 5.2.3.3 */ #define USB_CDC_COMM_FEATURE 0x01 #define USB_CDC_CAP_LINE 0x02 #define USB_CDC_CAP_BRK 0x04 #define USB_CDC_CAP_NOTIFY 0x08 /* "Union Functional Descriptor" from CDC spec 5.2.3.8 */ struct usb_cdc_union_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bMasterInterface0; __u8 bSlaveInterface0; /* ... and there could be other slave interfaces */ } __attribute__ ((packed)); /* "Country Selection Functional Descriptor" from CDC spec 5.2.3.9 */ struct usb_cdc_country_functional_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 iCountryCodeRelDate; __le16 wCountyCode0; /* ... and there can be a lot of country codes */ } __attribute__ ((packed)); /* "Network Channel Terminal Functional Descriptor" from CDC spec 5.2.3.11 */ struct usb_cdc_network_terminal_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bEntityId; __u8 iName; __u8 bChannelIndex; __u8 bPhysicalInterface; } __attribute__ ((packed)); /* "Ethernet Networking Functional Descriptor" from CDC spec 5.2.3.16 */ struct usb_cdc_ether_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 iMACAddress; __le32 bmEthernetStatistics; __le16 wMaxSegmentSize; __le16 wNumberMCFilters; __u8 bNumberPowerFilters; } __attribute__ ((packed)); /* "Telephone Control Model Functional Descriptor" from CDC WMC spec 6.3..3 */ struct usb_cdc_dmm_desc { __u8 bFunctionLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u16 bcdVersion; __le16 wMaxCommand; } __attribute__ ((packed)); /* "MDLM Functional Descriptor" from CDC WMC spec 6.7.2.3 */ struct usb_cdc_mdlm_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdVersion; __u8 bGUID[16]; } __attribute__ ((packed)); /* "MDLM Detail Functional Descriptor" from CDC WMC spec 6.7.2.4 */ struct usb_cdc_mdlm_detail_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; /* type is associated with mdlm_desc.bGUID */ __u8 bGuidDescriptorType; __u8 bDetailData[0]; } __attribute__ ((packed)); /* "OBEX Control Model Functional Descriptor" */ struct usb_cdc_obex_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdVersion; } __attribute__ ((packed)); /* "NCM Control Model Functional Descriptor" */ struct usb_cdc_ncm_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdNcmVersion; __u8 bmNetworkCapabilities; } __attribute__ ((packed)); /* "MBIM Control Model Functional Descriptor" */ struct usb_cdc_mbim_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdMBIMVersion; __le16 wMaxControlMessage; __u8 bNumberFilters; __u8 bMaxFilterSize; __le16 wMaxSegmentSize; __u8 bmNetworkCapabilities; } __attribute__ ((packed)); /* "MBIM Extended Functional Descriptor" from CDC MBIM spec 1.0 errata-1 */ struct usb_cdc_mbim_extended_desc { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdMBIMExtendedVersion; __u8 bMaxOutstandingCommandMessages; __le16 wMTU; } __attribute__ ((packed)); /*-------------------------------------------------------------------------*/ /* * Class-Specific Control Requests (6.2) * * section 3.6.2.1 table 4 has the ACM profile, for modems. * section 3.8.2 table 10 has the ethernet profile. * * Microsoft's RNDIS stack for Ethernet is a vendor-specific CDC ACM variant, * heavily dependent on the encapsulated (proprietary) command mechanism. */ #define USB_CDC_SEND_ENCAPSULATED_COMMAND 0x00 #define USB_CDC_GET_ENCAPSULATED_RESPONSE 0x01 #define USB_CDC_REQ_SET_LINE_CODING 0x20 #define USB_CDC_REQ_GET_LINE_CODING 0x21 #define USB_CDC_REQ_SET_CONTROL_LINE_STATE 0x22 #define USB_CDC_REQ_SEND_BREAK 0x23 #define USB_CDC_SET_ETHERNET_MULTICAST_FILTERS 0x40 #define USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER 0x41 #define USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER 0x42 #define USB_CDC_SET_ETHERNET_PACKET_FILTER 0x43 #define USB_CDC_GET_ETHERNET_STATISTIC 0x44 #define USB_CDC_GET_NTB_PARAMETERS 0x80 #define USB_CDC_GET_NET_ADDRESS 0x81 #define USB_CDC_SET_NET_ADDRESS 0x82 #define USB_CDC_GET_NTB_FORMAT 0x83 #define USB_CDC_SET_NTB_FORMAT 0x84 #define USB_CDC_GET_NTB_INPUT_SIZE 0x85 #define USB_CDC_SET_NTB_INPUT_SIZE 0x86 #define USB_CDC_GET_MAX_DATAGRAM_SIZE 0x87 #define USB_CDC_SET_MAX_DATAGRAM_SIZE 0x88 #define USB_CDC_GET_CRC_MODE 0x89 #define USB_CDC_SET_CRC_MODE 0x8a /* Line Coding Structure from CDC spec 6.2.13 */ struct usb_cdc_line_coding { __le32 dwDTERate; __u8 bCharFormat; #define USB_CDC_1_STOP_BITS 0 #define USB_CDC_1_5_STOP_BITS 1 #define USB_CDC_2_STOP_BITS 2 __u8 bParityType; #define USB_CDC_NO_PARITY 0 #define USB_CDC_ODD_PARITY 1 #define USB_CDC_EVEN_PARITY 2 #define USB_CDC_MARK_PARITY 3 #define USB_CDC_SPACE_PARITY 4 __u8 bDataBits; } __attribute__ ((packed)); /* Control Signal Bitmap Values from 6.2.14 SetControlLineState */ #define USB_CDC_CTRL_DTR (1 << 0) #define USB_CDC_CTRL_RTS (1 << 1) /* table 62; bits in multicast filter */ #define USB_CDC_PACKET_TYPE_PROMISCUOUS (1 << 0) #define USB_CDC_PACKET_TYPE_ALL_MULTICAST (1 << 1) /* no filter */ #define USB_CDC_PACKET_TYPE_DIRECTED (1 << 2) #define USB_CDC_PACKET_TYPE_BROADCAST (1 << 3) #define USB_CDC_PACKET_TYPE_MULTICAST (1 << 4) /* filtered */ /*-------------------------------------------------------------------------*/ /* * Class-Specific Notifications (6.3) sent by interrupt transfers * * section 3.8.2 table 11 of the CDC spec lists Ethernet notifications * section 3.6.2.1 table 5 specifies ACM notifications, accepted by RNDIS * RNDIS also defines its own bit-incompatible notifications */ #define USB_CDC_NOTIFY_NETWORK_CONNECTION 0x00 #define USB_CDC_NOTIFY_RESPONSE_AVAILABLE 0x01 #define USB_CDC_NOTIFY_SERIAL_STATE 0x20 #define USB_CDC_NOTIFY_SPEED_CHANGE 0x2a struct usb_cdc_notification { __u8 bmRequestType; __u8 bNotificationType; __le16 wValue; __le16 wIndex; __le16 wLength; } __attribute__ ((packed)); /* UART State Bitmap Values from 6.3.5 SerialState */ #define USB_CDC_SERIAL_STATE_DCD (1 << 0) #define USB_CDC_SERIAL_STATE_DSR (1 << 1) #define USB_CDC_SERIAL_STATE_BREAK (1 << 2) #define USB_CDC_SERIAL_STATE_RING_SIGNAL (1 << 3) #define USB_CDC_SERIAL_STATE_FRAMING (1 << 4) #define USB_CDC_SERIAL_STATE_PARITY (1 << 5) #define USB_CDC_SERIAL_STATE_OVERRUN (1 << 6) struct usb_cdc_speed_change { __le32 DLBitRRate; /* contains the downlink bit rate (IN pipe) */ __le32 ULBitRate; /* contains the uplink bit rate (OUT pipe) */ } __attribute__ ((packed)); /*-------------------------------------------------------------------------*/ /* * Class Specific structures and constants * * CDC NCM NTB parameters structure, CDC NCM subclass 6.2.1 * */ struct usb_cdc_ncm_ntb_parameters { __le16 wLength; __le16 bmNtbFormatsSupported; __le32 dwNtbInMaxSize; __le16 wNdpInDivisor; __le16 wNdpInPayloadRemainder; __le16 wNdpInAlignment; __le16 wPadding1; __le32 dwNtbOutMaxSize; __le16 wNdpOutDivisor; __le16 wNdpOutPayloadRemainder; __le16 wNdpOutAlignment; __le16 wNtbOutMaxDatagrams; } __attribute__ ((packed)); /* * CDC NCM transfer headers, CDC NCM subclass 3.2 */ #define USB_CDC_NCM_NTH16_SIGN 0x484D434E /* NCMH */ #define USB_CDC_NCM_NTH32_SIGN 0x686D636E /* ncmh */ struct usb_cdc_ncm_nth16 { __le32 dwSignature; __le16 wHeaderLength; __le16 wSequence; __le16 wBlockLength; __le16 wNdpIndex; } __attribute__ ((packed)); struct usb_cdc_ncm_nth32 { __le32 dwSignature; __le16 wHeaderLength; __le16 wSequence; __le32 dwBlockLength; __le32 dwNdpIndex; } __attribute__ ((packed)); /* * CDC NCM datagram pointers, CDC NCM subclass 3.3 */ #define USB_CDC_NCM_NDP16_CRC_SIGN 0x314D434E /* NCM1 */ #define USB_CDC_NCM_NDP16_NOCRC_SIGN 0x304D434E /* NCM0 */ #define USB_CDC_NCM_NDP32_CRC_SIGN 0x316D636E /* ncm1 */ #define USB_CDC_NCM_NDP32_NOCRC_SIGN 0x306D636E /* ncm0 */ #define USB_CDC_MBIM_NDP16_IPS_SIGN 0x00535049 /* IPS : IPS0 for now */ #define USB_CDC_MBIM_NDP32_IPS_SIGN 0x00737069 /* ips : ips0 for now */ #define USB_CDC_MBIM_NDP16_DSS_SIGN 0x00535344 /* DSS */ #define USB_CDC_MBIM_NDP32_DSS_SIGN 0x00737364 /* dss */ /* 16-bit NCM Datagram Pointer Entry */ struct usb_cdc_ncm_dpe16 { __le16 wDatagramIndex; __le16 wDatagramLength; } __attribute__((__packed__)); /* 16-bit NCM Datagram Pointer Table */ struct usb_cdc_ncm_ndp16 { __le32 dwSignature; __le16 wLength; __le16 wNextNdpIndex; struct usb_cdc_ncm_dpe16 dpe16[0]; } __attribute__ ((packed)); /* 32-bit NCM Datagram Pointer Entry */ struct usb_cdc_ncm_dpe32 { __le32 dwDatagramIndex; __le32 dwDatagramLength; } __attribute__((__packed__)); /* 32-bit NCM Datagram Pointer Table */ struct usb_cdc_ncm_ndp32 { __le32 dwSignature; __le16 wLength; __le16 wReserved6; __le32 dwNextNdpIndex; __le32 dwReserved12; struct usb_cdc_ncm_dpe32 dpe32[0]; } __attribute__ ((packed)); /* CDC NCM subclass 3.2.1 and 3.2.2 */ #define USB_CDC_NCM_NDP16_INDEX_MIN 0x000C #define USB_CDC_NCM_NDP32_INDEX_MIN 0x0010 /* CDC NCM subclass 3.3.3 Datagram Formatting */ #define USB_CDC_NCM_DATAGRAM_FORMAT_CRC 0x30 #define USB_CDC_NCM_DATAGRAM_FORMAT_NOCRC 0X31 /* CDC NCM subclass 4.2 NCM Communications Interface Protocol Code */ #define USB_CDC_NCM_PROTO_CODE_NO_ENCAP_COMMANDS 0x00 #define USB_CDC_NCM_PROTO_CODE_EXTERN_PROTO 0xFE /* CDC NCM subclass 5.2.1 NCM Functional Descriptor, bmNetworkCapabilities */ #define USB_CDC_NCM_NCAP_ETH_FILTER (1 << 0) #define USB_CDC_NCM_NCAP_NET_ADDRESS (1 << 1) #define USB_CDC_NCM_NCAP_ENCAP_COMMAND (1 << 2) #define USB_CDC_NCM_NCAP_MAX_DATAGRAM_SIZE (1 << 3) #define USB_CDC_NCM_NCAP_CRC_MODE (1 << 4) #define USB_CDC_NCM_NCAP_NTB_INPUT_SIZE (1 << 5) /* CDC NCM subclass Table 6-3: NTB Parameter Structure */ #define USB_CDC_NCM_NTB16_SUPPORTED (1 << 0) #define USB_CDC_NCM_NTB32_SUPPORTED (1 << 1) /* CDC NCM subclass Table 6-3: NTB Parameter Structure */ #define USB_CDC_NCM_NDP_ALIGN_MIN_SIZE 0x04 #define USB_CDC_NCM_NTB_MAX_LENGTH 0x1C /* CDC NCM subclass 6.2.5 SetNtbFormat */ #define USB_CDC_NCM_NTB16_FORMAT 0x00 #define USB_CDC_NCM_NTB32_FORMAT 0x01 /* CDC NCM subclass 6.2.7 SetNtbInputSize */ #define USB_CDC_NCM_NTB_MIN_IN_SIZE 2048 #define USB_CDC_NCM_NTB_MIN_OUT_SIZE 2048 /* NTB Input Size Structure */ struct usb_cdc_ncm_ndp_input_size { __le32 dwNtbInMaxSize; __le16 wNtbInMaxDatagrams; __le16 wReserved; } __attribute__ ((packed)); /* CDC NCM subclass 6.2.11 SetCrcMode */ #define USB_CDC_NCM_CRC_NOT_APPENDED 0x00 #define USB_CDC_NCM_CRC_APPENDED 0x01 #endif /* __UAPI_LINUX_USB_CDC_H */ linux/usb/video.h000064400000041617151027430560007767 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * USB Video Class definitions. * * Copyright (C) 2009 Laurent Pinchart * * This file holds USB constants and structures defined by the USB Device * Class Definition for Video Devices. Unless otherwise stated, comments * below reference relevant sections of the USB Video Class 1.1 specification * available at * * http://www.usb.org/developers/devclass_docs/USB_Video_Class_1_1.zip */ #ifndef __LINUX_USB_VIDEO_H #define __LINUX_USB_VIDEO_H #include /* -------------------------------------------------------------------------- * UVC constants */ /* A.2. Video Interface Subclass Codes */ #define UVC_SC_UNDEFINED 0x00 #define UVC_SC_VIDEOCONTROL 0x01 #define UVC_SC_VIDEOSTREAMING 0x02 #define UVC_SC_VIDEO_INTERFACE_COLLECTION 0x03 /* A.3. Video Interface Protocol Codes */ #define UVC_PC_PROTOCOL_UNDEFINED 0x00 #define UVC_PC_PROTOCOL_15 0x01 /* A.5. Video Class-Specific VC Interface Descriptor Subtypes */ #define UVC_VC_DESCRIPTOR_UNDEFINED 0x00 #define UVC_VC_HEADER 0x01 #define UVC_VC_INPUT_TERMINAL 0x02 #define UVC_VC_OUTPUT_TERMINAL 0x03 #define UVC_VC_SELECTOR_UNIT 0x04 #define UVC_VC_PROCESSING_UNIT 0x05 #define UVC_VC_EXTENSION_UNIT 0x06 /* A.6. Video Class-Specific VS Interface Descriptor Subtypes */ #define UVC_VS_UNDEFINED 0x00 #define UVC_VS_INPUT_HEADER 0x01 #define UVC_VS_OUTPUT_HEADER 0x02 #define UVC_VS_STILL_IMAGE_FRAME 0x03 #define UVC_VS_FORMAT_UNCOMPRESSED 0x04 #define UVC_VS_FRAME_UNCOMPRESSED 0x05 #define UVC_VS_FORMAT_MJPEG 0x06 #define UVC_VS_FRAME_MJPEG 0x07 #define UVC_VS_FORMAT_MPEG2TS 0x0a #define UVC_VS_FORMAT_DV 0x0c #define UVC_VS_COLORFORMAT 0x0d #define UVC_VS_FORMAT_FRAME_BASED 0x10 #define UVC_VS_FRAME_FRAME_BASED 0x11 #define UVC_VS_FORMAT_STREAM_BASED 0x12 /* A.7. Video Class-Specific Endpoint Descriptor Subtypes */ #define UVC_EP_UNDEFINED 0x00 #define UVC_EP_GENERAL 0x01 #define UVC_EP_ENDPOINT 0x02 #define UVC_EP_INTERRUPT 0x03 /* A.8. Video Class-Specific Request Codes */ #define UVC_RC_UNDEFINED 0x00 #define UVC_SET_CUR 0x01 #define UVC_GET_CUR 0x81 #define UVC_GET_MIN 0x82 #define UVC_GET_MAX 0x83 #define UVC_GET_RES 0x84 #define UVC_GET_LEN 0x85 #define UVC_GET_INFO 0x86 #define UVC_GET_DEF 0x87 /* A.9.1. VideoControl Interface Control Selectors */ #define UVC_VC_CONTROL_UNDEFINED 0x00 #define UVC_VC_VIDEO_POWER_MODE_CONTROL 0x01 #define UVC_VC_REQUEST_ERROR_CODE_CONTROL 0x02 /* A.9.2. Terminal Control Selectors */ #define UVC_TE_CONTROL_UNDEFINED 0x00 /* A.9.3. Selector Unit Control Selectors */ #define UVC_SU_CONTROL_UNDEFINED 0x00 #define UVC_SU_INPUT_SELECT_CONTROL 0x01 /* A.9.4. Camera Terminal Control Selectors */ #define UVC_CT_CONTROL_UNDEFINED 0x00 #define UVC_CT_SCANNING_MODE_CONTROL 0x01 #define UVC_CT_AE_MODE_CONTROL 0x02 #define UVC_CT_AE_PRIORITY_CONTROL 0x03 #define UVC_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 0x04 #define UVC_CT_EXPOSURE_TIME_RELATIVE_CONTROL 0x05 #define UVC_CT_FOCUS_ABSOLUTE_CONTROL 0x06 #define UVC_CT_FOCUS_RELATIVE_CONTROL 0x07 #define UVC_CT_FOCUS_AUTO_CONTROL 0x08 #define UVC_CT_IRIS_ABSOLUTE_CONTROL 0x09 #define UVC_CT_IRIS_RELATIVE_CONTROL 0x0a #define UVC_CT_ZOOM_ABSOLUTE_CONTROL 0x0b #define UVC_CT_ZOOM_RELATIVE_CONTROL 0x0c #define UVC_CT_PANTILT_ABSOLUTE_CONTROL 0x0d #define UVC_CT_PANTILT_RELATIVE_CONTROL 0x0e #define UVC_CT_ROLL_ABSOLUTE_CONTROL 0x0f #define UVC_CT_ROLL_RELATIVE_CONTROL 0x10 #define UVC_CT_PRIVACY_CONTROL 0x11 /* A.9.5. Processing Unit Control Selectors */ #define UVC_PU_CONTROL_UNDEFINED 0x00 #define UVC_PU_BACKLIGHT_COMPENSATION_CONTROL 0x01 #define UVC_PU_BRIGHTNESS_CONTROL 0x02 #define UVC_PU_CONTRAST_CONTROL 0x03 #define UVC_PU_GAIN_CONTROL 0x04 #define UVC_PU_POWER_LINE_FREQUENCY_CONTROL 0x05 #define UVC_PU_HUE_CONTROL 0x06 #define UVC_PU_SATURATION_CONTROL 0x07 #define UVC_PU_SHARPNESS_CONTROL 0x08 #define UVC_PU_GAMMA_CONTROL 0x09 #define UVC_PU_WHITE_BALANCE_TEMPERATURE_CONTROL 0x0a #define UVC_PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 0x0b #define UVC_PU_WHITE_BALANCE_COMPONENT_CONTROL 0x0c #define UVC_PU_WHITE_BALANCE_COMPONENT_AUTO_CONTROL 0x0d #define UVC_PU_DIGITAL_MULTIPLIER_CONTROL 0x0e #define UVC_PU_DIGITAL_MULTIPLIER_LIMIT_CONTROL 0x0f #define UVC_PU_HUE_AUTO_CONTROL 0x10 #define UVC_PU_ANALOG_VIDEO_STANDARD_CONTROL 0x11 #define UVC_PU_ANALOG_LOCK_STATUS_CONTROL 0x12 /* A.9.7. VideoStreaming Interface Control Selectors */ #define UVC_VS_CONTROL_UNDEFINED 0x00 #define UVC_VS_PROBE_CONTROL 0x01 #define UVC_VS_COMMIT_CONTROL 0x02 #define UVC_VS_STILL_PROBE_CONTROL 0x03 #define UVC_VS_STILL_COMMIT_CONTROL 0x04 #define UVC_VS_STILL_IMAGE_TRIGGER_CONTROL 0x05 #define UVC_VS_STREAM_ERROR_CODE_CONTROL 0x06 #define UVC_VS_GENERATE_KEY_FRAME_CONTROL 0x07 #define UVC_VS_UPDATE_FRAME_SEGMENT_CONTROL 0x08 #define UVC_VS_SYNC_DELAY_CONTROL 0x09 /* B.1. USB Terminal Types */ #define UVC_TT_VENDOR_SPECIFIC 0x0100 #define UVC_TT_STREAMING 0x0101 /* B.2. Input Terminal Types */ #define UVC_ITT_VENDOR_SPECIFIC 0x0200 #define UVC_ITT_CAMERA 0x0201 #define UVC_ITT_MEDIA_TRANSPORT_INPUT 0x0202 /* B.3. Output Terminal Types */ #define UVC_OTT_VENDOR_SPECIFIC 0x0300 #define UVC_OTT_DISPLAY 0x0301 #define UVC_OTT_MEDIA_TRANSPORT_OUTPUT 0x0302 /* B.4. External Terminal Types */ #define UVC_EXTERNAL_VENDOR_SPECIFIC 0x0400 #define UVC_COMPOSITE_CONNECTOR 0x0401 #define UVC_SVIDEO_CONNECTOR 0x0402 #define UVC_COMPONENT_CONNECTOR 0x0403 /* 2.4.2.2. Status Packet Type */ #define UVC_STATUS_TYPE_CONTROL 1 #define UVC_STATUS_TYPE_STREAMING 2 /* 2.4.3.3. Payload Header Information */ #define UVC_STREAM_EOH (1 << 7) #define UVC_STREAM_ERR (1 << 6) #define UVC_STREAM_STI (1 << 5) #define UVC_STREAM_RES (1 << 4) #define UVC_STREAM_SCR (1 << 3) #define UVC_STREAM_PTS (1 << 2) #define UVC_STREAM_EOF (1 << 1) #define UVC_STREAM_FID (1 << 0) /* 4.1.2. Control Capabilities */ #define UVC_CONTROL_CAP_GET (1 << 0) #define UVC_CONTROL_CAP_SET (1 << 1) #define UVC_CONTROL_CAP_DISABLED (1 << 2) #define UVC_CONTROL_CAP_AUTOUPDATE (1 << 3) #define UVC_CONTROL_CAP_ASYNCHRONOUS (1 << 4) /* 3.9.2.6 Color Matching Descriptor Values */ enum uvc_color_primaries_values { UVC_COLOR_PRIMARIES_UNSPECIFIED, UVC_COLOR_PRIMARIES_BT_709_SRGB, UVC_COLOR_PRIMARIES_BT_470_2_M, UVC_COLOR_PRIMARIES_BT_470_2_B_G, UVC_COLOR_PRIMARIES_SMPTE_170M, UVC_COLOR_PRIMARIES_SMPTE_240M, }; enum uvc_transfer_characteristics_values { UVC_TRANSFER_CHARACTERISTICS_UNSPECIFIED, UVC_TRANSFER_CHARACTERISTICS_BT_709, UVC_TRANSFER_CHARACTERISTICS_BT_470_2_M, UVC_TRANSFER_CHARACTERISTICS_BT_470_2_B_G, UVC_TRANSFER_CHARACTERISTICS_SMPTE_170M, UVC_TRANSFER_CHARACTERISTICS_SMPTE_240M, UVC_TRANSFER_CHARACTERISTICS_LINEAR, UVC_TRANSFER_CHARACTERISTICS_SRGB, }; enum uvc_matrix_coefficients { UVC_MATRIX_COEFFICIENTS_UNSPECIFIED, UVC_MATRIX_COEFFICIENTS_BT_709, UVC_MATRIX_COEFFICIENTS_FCC, UVC_MATRIX_COEFFICIENTS_BT_470_2_B_G, UVC_MATRIX_COEFFICIENTS_SMPTE_170M, UVC_MATRIX_COEFFICIENTS_SMPTE_240M, }; /* ------------------------------------------------------------------------ * UVC structures */ /* All UVC descriptors have these 3 fields at the beginning */ struct uvc_descriptor_header { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; } __attribute__((packed)); /* 3.7.2. Video Control Interface Header Descriptor */ struct uvc_header_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 bcdUVC; __le16 wTotalLength; __le32 dwClockFrequency; __u8 bInCollection; __u8 baInterfaceNr[]; } __attribute__((__packed__)); #define UVC_DT_HEADER_SIZE(n) (12+(n)) #define UVC_HEADER_DESCRIPTOR(n) \ uvc_header_descriptor_##n #define DECLARE_UVC_HEADER_DESCRIPTOR(n) \ struct UVC_HEADER_DESCRIPTOR(n) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __le16 bcdUVC; \ __le16 wTotalLength; \ __le32 dwClockFrequency; \ __u8 bInCollection; \ __u8 baInterfaceNr[n]; \ } __attribute__ ((packed)) /* 3.7.2.1. Input Terminal Descriptor */ struct uvc_input_terminal_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bTerminalID; __le16 wTerminalType; __u8 bAssocTerminal; __u8 iTerminal; } __attribute__((__packed__)); #define UVC_DT_INPUT_TERMINAL_SIZE 8 /* 3.7.2.2. Output Terminal Descriptor */ struct uvc_output_terminal_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bTerminalID; __le16 wTerminalType; __u8 bAssocTerminal; __u8 bSourceID; __u8 iTerminal; } __attribute__((__packed__)); #define UVC_DT_OUTPUT_TERMINAL_SIZE 9 /* 3.7.2.3. Camera Terminal Descriptor */ struct uvc_camera_terminal_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bTerminalID; __le16 wTerminalType; __u8 bAssocTerminal; __u8 iTerminal; __le16 wObjectiveFocalLengthMin; __le16 wObjectiveFocalLengthMax; __le16 wOcularFocalLength; __u8 bControlSize; __u8 bmControls[3]; } __attribute__((__packed__)); #define UVC_DT_CAMERA_TERMINAL_SIZE(n) (15+(n)) /* 3.7.2.4. Selector Unit Descriptor */ struct uvc_selector_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bUnitID; __u8 bNrInPins; __u8 baSourceID[0]; __u8 iSelector; } __attribute__((__packed__)); #define UVC_DT_SELECTOR_UNIT_SIZE(n) (6+(n)) #define UVC_SELECTOR_UNIT_DESCRIPTOR(n) \ uvc_selector_unit_descriptor_##n #define DECLARE_UVC_SELECTOR_UNIT_DESCRIPTOR(n) \ struct UVC_SELECTOR_UNIT_DESCRIPTOR(n) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __u8 bUnitID; \ __u8 bNrInPins; \ __u8 baSourceID[n]; \ __u8 iSelector; \ } __attribute__ ((packed)) /* 3.7.2.5. Processing Unit Descriptor */ struct uvc_processing_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bUnitID; __u8 bSourceID; __le16 wMaxMultiplier; __u8 bControlSize; __u8 bmControls[2]; __u8 iProcessing; __u8 bmVideoStandards; } __attribute__((__packed__)); #define UVC_DT_PROCESSING_UNIT_SIZE(n) (10+(n)) /* 3.7.2.6. Extension Unit Descriptor */ struct uvc_extension_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bUnitID; __u8 guidExtensionCode[16]; __u8 bNumControls; __u8 bNrInPins; __u8 baSourceID[0]; __u8 bControlSize; __u8 bmControls[0]; __u8 iExtension; } __attribute__((__packed__)); #define UVC_DT_EXTENSION_UNIT_SIZE(p, n) (24+(p)+(n)) #define UVC_EXTENSION_UNIT_DESCRIPTOR(p, n) \ uvc_extension_unit_descriptor_##p_##n #define DECLARE_UVC_EXTENSION_UNIT_DESCRIPTOR(p, n) \ struct UVC_EXTENSION_UNIT_DESCRIPTOR(p, n) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __u8 bUnitID; \ __u8 guidExtensionCode[16]; \ __u8 bNumControls; \ __u8 bNrInPins; \ __u8 baSourceID[p]; \ __u8 bControlSize; \ __u8 bmControls[n]; \ __u8 iExtension; \ } __attribute__ ((packed)) /* 3.8.2.2. Video Control Interrupt Endpoint Descriptor */ struct uvc_control_endpoint_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __le16 wMaxTransferSize; } __attribute__((__packed__)); #define UVC_DT_CONTROL_ENDPOINT_SIZE 5 /* 3.9.2.1. Input Header Descriptor */ struct uvc_input_header_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bNumFormats; __le16 wTotalLength; __u8 bEndpointAddress; __u8 bmInfo; __u8 bTerminalLink; __u8 bStillCaptureMethod; __u8 bTriggerSupport; __u8 bTriggerUsage; __u8 bControlSize; __u8 bmaControls[]; } __attribute__((__packed__)); #define UVC_DT_INPUT_HEADER_SIZE(n, p) (13+(n*p)) #define UVC_INPUT_HEADER_DESCRIPTOR(n, p) \ uvc_input_header_descriptor_##n_##p #define DECLARE_UVC_INPUT_HEADER_DESCRIPTOR(n, p) \ struct UVC_INPUT_HEADER_DESCRIPTOR(n, p) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __u8 bNumFormats; \ __le16 wTotalLength; \ __u8 bEndpointAddress; \ __u8 bmInfo; \ __u8 bTerminalLink; \ __u8 bStillCaptureMethod; \ __u8 bTriggerSupport; \ __u8 bTriggerUsage; \ __u8 bControlSize; \ __u8 bmaControls[p][n]; \ } __attribute__ ((packed)) /* 3.9.2.2. Output Header Descriptor */ struct uvc_output_header_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bNumFormats; __le16 wTotalLength; __u8 bEndpointAddress; __u8 bTerminalLink; __u8 bControlSize; __u8 bmaControls[]; } __attribute__((__packed__)); #define UVC_DT_OUTPUT_HEADER_SIZE(n, p) (9+(n*p)) #define UVC_OUTPUT_HEADER_DESCRIPTOR(n, p) \ uvc_output_header_descriptor_##n_##p #define DECLARE_UVC_OUTPUT_HEADER_DESCRIPTOR(n, p) \ struct UVC_OUTPUT_HEADER_DESCRIPTOR(n, p) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __u8 bNumFormats; \ __le16 wTotalLength; \ __u8 bEndpointAddress; \ __u8 bTerminalLink; \ __u8 bControlSize; \ __u8 bmaControls[p][n]; \ } __attribute__ ((packed)) /* 3.9.2.6. Color matching descriptor */ struct uvc_color_matching_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bColorPrimaries; __u8 bTransferCharacteristics; __u8 bMatrixCoefficients; } __attribute__((__packed__)); #define UVC_DT_COLOR_MATCHING_SIZE 6 /* 4.3.1.1. Video Probe and Commit Controls */ struct uvc_streaming_control { __u16 bmHint; __u8 bFormatIndex; __u8 bFrameIndex; __u32 dwFrameInterval; __u16 wKeyFrameRate; __u16 wPFrameRate; __u16 wCompQuality; __u16 wCompWindowSize; __u16 wDelay; __u32 dwMaxVideoFrameSize; __u32 dwMaxPayloadTransferSize; __u32 dwClockFrequency; __u8 bmFramingInfo; __u8 bPreferedVersion; __u8 bMinVersion; __u8 bMaxVersion; } __attribute__((__packed__)); /* Uncompressed Payload - 3.1.1. Uncompressed Video Format Descriptor */ struct uvc_format_uncompressed { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bFormatIndex; __u8 bNumFrameDescriptors; __u8 guidFormat[16]; __u8 bBitsPerPixel; __u8 bDefaultFrameIndex; __u8 bAspectRatioX; __u8 bAspectRatioY; __u8 bmInterfaceFlags; __u8 bCopyProtect; } __attribute__((__packed__)); #define UVC_DT_FORMAT_UNCOMPRESSED_SIZE 27 /* Uncompressed Payload - 3.1.2. Uncompressed Video Frame Descriptor */ struct uvc_frame_uncompressed { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bFrameIndex; __u8 bmCapabilities; __le16 wWidth; __le16 wHeight; __le32 dwMinBitRate; __le32 dwMaxBitRate; __le32 dwMaxVideoFrameBufferSize; __le32 dwDefaultFrameInterval; __u8 bFrameIntervalType; __le32 dwFrameInterval[]; } __attribute__((__packed__)); #define UVC_DT_FRAME_UNCOMPRESSED_SIZE(n) (26+4*(n)) #define UVC_FRAME_UNCOMPRESSED(n) \ uvc_frame_uncompressed_##n #define DECLARE_UVC_FRAME_UNCOMPRESSED(n) \ struct UVC_FRAME_UNCOMPRESSED(n) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __u8 bFrameIndex; \ __u8 bmCapabilities; \ __le16 wWidth; \ __le16 wHeight; \ __le32 dwMinBitRate; \ __le32 dwMaxBitRate; \ __le32 dwMaxVideoFrameBufferSize; \ __le32 dwDefaultFrameInterval; \ __u8 bFrameIntervalType; \ __le32 dwFrameInterval[n]; \ } __attribute__ ((packed)) /* MJPEG Payload - 3.1.1. MJPEG Video Format Descriptor */ struct uvc_format_mjpeg { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bFormatIndex; __u8 bNumFrameDescriptors; __u8 bmFlags; __u8 bDefaultFrameIndex; __u8 bAspectRatioX; __u8 bAspectRatioY; __u8 bmInterfaceFlags; __u8 bCopyProtect; } __attribute__((__packed__)); #define UVC_DT_FORMAT_MJPEG_SIZE 11 /* MJPEG Payload - 3.1.2. MJPEG Video Frame Descriptor */ struct uvc_frame_mjpeg { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubType; __u8 bFrameIndex; __u8 bmCapabilities; __le16 wWidth; __le16 wHeight; __le32 dwMinBitRate; __le32 dwMaxBitRate; __le32 dwMaxVideoFrameBufferSize; __le32 dwDefaultFrameInterval; __u8 bFrameIntervalType; __le32 dwFrameInterval[]; } __attribute__((__packed__)); #define UVC_DT_FRAME_MJPEG_SIZE(n) (26+4*(n)) #define UVC_FRAME_MJPEG(n) \ uvc_frame_mjpeg_##n #define DECLARE_UVC_FRAME_MJPEG(n) \ struct UVC_FRAME_MJPEG(n) { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubType; \ __u8 bFrameIndex; \ __u8 bmCapabilities; \ __le16 wWidth; \ __le16 wHeight; \ __le32 dwMinBitRate; \ __le32 dwMaxBitRate; \ __le32 dwMaxVideoFrameBufferSize; \ __le32 dwDefaultFrameInterval; \ __u8 bFrameIntervalType; \ __le32 dwFrameInterval[n]; \ } __attribute__ ((packed)) #endif /* __LINUX_USB_VIDEO_H */ linux/usb/audio.h000064400000046042151027430560007757 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * -- USB Audio definitions. * * Copyright (C) 2006 Thumtronics Pty Ltd. * Developed for Thumtronics by Grey Innovation * Ben Williamson * * This software is distributed under the terms of the GNU General Public * License ("GPL") version 2, as published by the Free Software Foundation. * * This file holds USB constants and structures defined * by the USB Device Class Definition for Audio Devices. * Comments below reference relevant sections of that document: * * http://www.usb.org/developers/devclass_docs/audio10.pdf * * Types and defines in this file are either specific to version 1.0 of * this standard or common for newer versions. */ #ifndef __LINUX_USB_AUDIO_H #define __LINUX_USB_AUDIO_H #include /* bInterfaceProtocol values to denote the version of the standard used */ #define UAC_VERSION_1 0x00 #define UAC_VERSION_2 0x20 #define UAC_VERSION_3 0x30 /* A.2 Audio Interface Subclass Codes */ #define USB_SUBCLASS_AUDIOCONTROL 0x01 #define USB_SUBCLASS_AUDIOSTREAMING 0x02 #define USB_SUBCLASS_MIDISTREAMING 0x03 /* A.5 Audio Class-Specific AC Interface Descriptor Subtypes */ #define UAC_HEADER 0x01 #define UAC_INPUT_TERMINAL 0x02 #define UAC_OUTPUT_TERMINAL 0x03 #define UAC_MIXER_UNIT 0x04 #define UAC_SELECTOR_UNIT 0x05 #define UAC_FEATURE_UNIT 0x06 #define UAC1_PROCESSING_UNIT 0x07 #define UAC1_EXTENSION_UNIT 0x08 /* A.6 Audio Class-Specific AS Interface Descriptor Subtypes */ #define UAC_AS_GENERAL 0x01 #define UAC_FORMAT_TYPE 0x02 #define UAC_FORMAT_SPECIFIC 0x03 /* A.7 Processing Unit Process Types */ #define UAC_PROCESS_UNDEFINED 0x00 #define UAC_PROCESS_UP_DOWNMIX 0x01 #define UAC_PROCESS_DOLBY_PROLOGIC 0x02 #define UAC_PROCESS_STEREO_EXTENDER 0x03 #define UAC_PROCESS_REVERB 0x04 #define UAC_PROCESS_CHORUS 0x05 #define UAC_PROCESS_DYN_RANGE_COMP 0x06 /* A.8 Audio Class-Specific Endpoint Descriptor Subtypes */ #define UAC_EP_GENERAL 0x01 /* A.9 Audio Class-Specific Request Codes */ #define UAC_SET_ 0x00 #define UAC_GET_ 0x80 #define UAC__CUR 0x1 #define UAC__MIN 0x2 #define UAC__MAX 0x3 #define UAC__RES 0x4 #define UAC__MEM 0x5 #define UAC_SET_CUR (UAC_SET_ | UAC__CUR) #define UAC_GET_CUR (UAC_GET_ | UAC__CUR) #define UAC_SET_MIN (UAC_SET_ | UAC__MIN) #define UAC_GET_MIN (UAC_GET_ | UAC__MIN) #define UAC_SET_MAX (UAC_SET_ | UAC__MAX) #define UAC_GET_MAX (UAC_GET_ | UAC__MAX) #define UAC_SET_RES (UAC_SET_ | UAC__RES) #define UAC_GET_RES (UAC_GET_ | UAC__RES) #define UAC_SET_MEM (UAC_SET_ | UAC__MEM) #define UAC_GET_MEM (UAC_GET_ | UAC__MEM) #define UAC_GET_STAT 0xff /* A.10 Control Selector Codes */ /* A.10.1 Terminal Control Selectors */ #define UAC_TERM_COPY_PROTECT 0x01 /* A.10.2 Feature Unit Control Selectors */ #define UAC_FU_MUTE 0x01 #define UAC_FU_VOLUME 0x02 #define UAC_FU_BASS 0x03 #define UAC_FU_MID 0x04 #define UAC_FU_TREBLE 0x05 #define UAC_FU_GRAPHIC_EQUALIZER 0x06 #define UAC_FU_AUTOMATIC_GAIN 0x07 #define UAC_FU_DELAY 0x08 #define UAC_FU_BASS_BOOST 0x09 #define UAC_FU_LOUDNESS 0x0a #define UAC_CONTROL_BIT(CS) (1 << ((CS) - 1)) /* A.10.3.1 Up/Down-mix Processing Unit Controls Selectors */ #define UAC_UD_ENABLE 0x01 #define UAC_UD_MODE_SELECT 0x02 /* A.10.3.2 Dolby Prologic (tm) Processing Unit Controls Selectors */ #define UAC_DP_ENABLE 0x01 #define UAC_DP_MODE_SELECT 0x02 /* A.10.3.3 3D Stereo Extender Processing Unit Control Selectors */ #define UAC_3D_ENABLE 0x01 #define UAC_3D_SPACE 0x02 /* A.10.3.4 Reverberation Processing Unit Control Selectors */ #define UAC_REVERB_ENABLE 0x01 #define UAC_REVERB_LEVEL 0x02 #define UAC_REVERB_TIME 0x03 #define UAC_REVERB_FEEDBACK 0x04 /* A.10.3.5 Chorus Processing Unit Control Selectors */ #define UAC_CHORUS_ENABLE 0x01 #define UAC_CHORUS_LEVEL 0x02 #define UAC_CHORUS_RATE 0x03 #define UAC_CHORUS_DEPTH 0x04 /* A.10.3.6 Dynamic Range Compressor Unit Control Selectors */ #define UAC_DCR_ENABLE 0x01 #define UAC_DCR_RATE 0x02 #define UAC_DCR_MAXAMPL 0x03 #define UAC_DCR_THRESHOLD 0x04 #define UAC_DCR_ATTACK_TIME 0x05 #define UAC_DCR_RELEASE_TIME 0x06 /* A.10.4 Extension Unit Control Selectors */ #define UAC_XU_ENABLE 0x01 /* MIDI - A.1 MS Class-Specific Interface Descriptor Subtypes */ #define UAC_MS_HEADER 0x01 #define UAC_MIDI_IN_JACK 0x02 #define UAC_MIDI_OUT_JACK 0x03 /* MIDI - A.1 MS Class-Specific Endpoint Descriptor Subtypes */ #define UAC_MS_GENERAL 0x01 /* Terminals - 2.1 USB Terminal Types */ #define UAC_TERMINAL_UNDEFINED 0x100 #define UAC_TERMINAL_STREAMING 0x101 #define UAC_TERMINAL_VENDOR_SPEC 0x1FF /* Terminal Control Selectors */ /* 4.3.2 Class-Specific AC Interface Descriptor */ struct uac1_ac_header_descriptor { __u8 bLength; /* 8 + n */ __u8 bDescriptorType; /* USB_DT_CS_INTERFACE */ __u8 bDescriptorSubtype; /* UAC_MS_HEADER */ __le16 bcdADC; /* 0x0100 */ __le16 wTotalLength; /* includes Unit and Terminal desc. */ __u8 bInCollection; /* n */ __u8 baInterfaceNr[]; /* [n] */ } __attribute__ ((packed)); #define UAC_DT_AC_HEADER_SIZE(n) (8 + (n)) /* As above, but more useful for defining your own descriptors: */ #define DECLARE_UAC_AC_HEADER_DESCRIPTOR(n) \ struct uac1_ac_header_descriptor_##n { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubtype; \ __le16 bcdADC; \ __le16 wTotalLength; \ __u8 bInCollection; \ __u8 baInterfaceNr[n]; \ } __attribute__ ((packed)) /* 4.3.2.1 Input Terminal Descriptor */ struct uac_input_terminal_descriptor { __u8 bLength; /* in bytes: 12 */ __u8 bDescriptorType; /* CS_INTERFACE descriptor type */ __u8 bDescriptorSubtype; /* INPUT_TERMINAL descriptor subtype */ __u8 bTerminalID; /* Constant uniquely terminal ID */ __le16 wTerminalType; /* USB Audio Terminal Types */ __u8 bAssocTerminal; /* ID of the Output Terminal associated */ __u8 bNrChannels; /* Number of logical output channels */ __le16 wChannelConfig; __u8 iChannelNames; __u8 iTerminal; } __attribute__ ((packed)); #define UAC_DT_INPUT_TERMINAL_SIZE 12 /* Terminals - 2.2 Input Terminal Types */ #define UAC_INPUT_TERMINAL_UNDEFINED 0x200 #define UAC_INPUT_TERMINAL_MICROPHONE 0x201 #define UAC_INPUT_TERMINAL_DESKTOP_MICROPHONE 0x202 #define UAC_INPUT_TERMINAL_PERSONAL_MICROPHONE 0x203 #define UAC_INPUT_TERMINAL_OMNI_DIR_MICROPHONE 0x204 #define UAC_INPUT_TERMINAL_MICROPHONE_ARRAY 0x205 #define UAC_INPUT_TERMINAL_PROC_MICROPHONE_ARRAY 0x206 /* Terminals - control selectors */ #define UAC_TERMINAL_CS_COPY_PROTECT_CONTROL 0x01 /* 4.3.2.2 Output Terminal Descriptor */ struct uac1_output_terminal_descriptor { __u8 bLength; /* in bytes: 9 */ __u8 bDescriptorType; /* CS_INTERFACE descriptor type */ __u8 bDescriptorSubtype; /* OUTPUT_TERMINAL descriptor subtype */ __u8 bTerminalID; /* Constant uniquely terminal ID */ __le16 wTerminalType; /* USB Audio Terminal Types */ __u8 bAssocTerminal; /* ID of the Input Terminal associated */ __u8 bSourceID; /* ID of the connected Unit or Terminal*/ __u8 iTerminal; } __attribute__ ((packed)); #define UAC_DT_OUTPUT_TERMINAL_SIZE 9 /* Terminals - 2.3 Output Terminal Types */ #define UAC_OUTPUT_TERMINAL_UNDEFINED 0x300 #define UAC_OUTPUT_TERMINAL_SPEAKER 0x301 #define UAC_OUTPUT_TERMINAL_HEADPHONES 0x302 #define UAC_OUTPUT_TERMINAL_HEAD_MOUNTED_DISPLAY_AUDIO 0x303 #define UAC_OUTPUT_TERMINAL_DESKTOP_SPEAKER 0x304 #define UAC_OUTPUT_TERMINAL_ROOM_SPEAKER 0x305 #define UAC_OUTPUT_TERMINAL_COMMUNICATION_SPEAKER 0x306 #define UAC_OUTPUT_TERMINAL_LOW_FREQ_EFFECTS_SPEAKER 0x307 /* Terminals - 2.4 Bi-directional Terminal Types */ #define UAC_BIDIR_TERMINAL_UNDEFINED 0x400 #define UAC_BIDIR_TERMINAL_HANDSET 0x401 #define UAC_BIDIR_TERMINAL_HEADSET 0x402 #define UAC_BIDIR_TERMINAL_SPEAKER_PHONE 0x403 #define UAC_BIDIR_TERMINAL_ECHO_SUPPRESSING 0x404 #define UAC_BIDIR_TERMINAL_ECHO_CANCELING 0x405 /* Set bControlSize = 2 as default setting */ #define UAC_DT_FEATURE_UNIT_SIZE(ch) (7 + ((ch) + 1) * 2) /* As above, but more useful for defining your own descriptors: */ #define DECLARE_UAC_FEATURE_UNIT_DESCRIPTOR(ch) \ struct uac_feature_unit_descriptor_##ch { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubtype; \ __u8 bUnitID; \ __u8 bSourceID; \ __u8 bControlSize; \ __le16 bmaControls[ch + 1]; \ __u8 iFeature; \ } __attribute__ ((packed)) /* 4.3.2.3 Mixer Unit Descriptor */ struct uac_mixer_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bUnitID; __u8 bNrInPins; __u8 baSourceID[]; } __attribute__ ((packed)); static __inline__ __u8 uac_mixer_unit_bNrChannels(struct uac_mixer_unit_descriptor *desc) { return desc->baSourceID[desc->bNrInPins]; } static __inline__ __u32 uac_mixer_unit_wChannelConfig(struct uac_mixer_unit_descriptor *desc, int protocol) { if (protocol == UAC_VERSION_1) return (desc->baSourceID[desc->bNrInPins + 2] << 8) | desc->baSourceID[desc->bNrInPins + 1]; else return (desc->baSourceID[desc->bNrInPins + 4] << 24) | (desc->baSourceID[desc->bNrInPins + 3] << 16) | (desc->baSourceID[desc->bNrInPins + 2] << 8) | (desc->baSourceID[desc->bNrInPins + 1]); } static __inline__ __u8 uac_mixer_unit_iChannelNames(struct uac_mixer_unit_descriptor *desc, int protocol) { return (protocol == UAC_VERSION_1) ? desc->baSourceID[desc->bNrInPins + 3] : desc->baSourceID[desc->bNrInPins + 5]; } static __inline__ __u8 *uac_mixer_unit_bmControls(struct uac_mixer_unit_descriptor *desc, int protocol) { switch (protocol) { case UAC_VERSION_1: return &desc->baSourceID[desc->bNrInPins + 4]; case UAC_VERSION_2: return &desc->baSourceID[desc->bNrInPins + 6]; case UAC_VERSION_3: return &desc->baSourceID[desc->bNrInPins + 2]; default: return NULL; } } static __inline__ __u16 uac3_mixer_unit_wClusterDescrID(struct uac_mixer_unit_descriptor *desc) { return (desc->baSourceID[desc->bNrInPins + 1] << 8) | desc->baSourceID[desc->bNrInPins]; } static __inline__ __u8 uac_mixer_unit_iMixer(struct uac_mixer_unit_descriptor *desc) { __u8 *raw = (__u8 *) desc; return raw[desc->bLength - 1]; } /* 4.3.2.4 Selector Unit Descriptor */ struct uac_selector_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bUintID; __u8 bNrInPins; __u8 baSourceID[]; } __attribute__ ((packed)); static __inline__ __u8 uac_selector_unit_iSelector(struct uac_selector_unit_descriptor *desc) { __u8 *raw = (__u8 *) desc; return raw[desc->bLength - 1]; } /* 4.3.2.5 Feature Unit Descriptor */ struct uac_feature_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bUnitID; __u8 bSourceID; __u8 bControlSize; __u8 bmaControls[0]; /* variable length */ } __attribute__((packed)); static __inline__ __u8 uac_feature_unit_iFeature(struct uac_feature_unit_descriptor *desc) { __u8 *raw = (__u8 *) desc; return raw[desc->bLength - 1]; } /* 4.3.2.6 Processing Unit Descriptors */ struct uac_processing_unit_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bUnitID; __le16 wProcessType; __u8 bNrInPins; __u8 baSourceID[]; } __attribute__ ((packed)); static __inline__ __u8 uac_processing_unit_bNrChannels(struct uac_processing_unit_descriptor *desc) { return desc->baSourceID[desc->bNrInPins]; } static __inline__ __u32 uac_processing_unit_wChannelConfig(struct uac_processing_unit_descriptor *desc, int protocol) { if (protocol == UAC_VERSION_1) return (desc->baSourceID[desc->bNrInPins + 2] << 8) | desc->baSourceID[desc->bNrInPins + 1]; else return (desc->baSourceID[desc->bNrInPins + 4] << 24) | (desc->baSourceID[desc->bNrInPins + 3] << 16) | (desc->baSourceID[desc->bNrInPins + 2] << 8) | (desc->baSourceID[desc->bNrInPins + 1]); } static __inline__ __u8 uac_processing_unit_iChannelNames(struct uac_processing_unit_descriptor *desc, int protocol) { return (protocol == UAC_VERSION_1) ? desc->baSourceID[desc->bNrInPins + 3] : desc->baSourceID[desc->bNrInPins + 5]; } static __inline__ __u8 uac_processing_unit_bControlSize(struct uac_processing_unit_descriptor *desc, int protocol) { switch (protocol) { case UAC_VERSION_1: return desc->baSourceID[desc->bNrInPins + 4]; case UAC_VERSION_2: return 2; /* in UAC2, this value is constant */ case UAC_VERSION_3: return 4; /* in UAC3, this value is constant */ default: return 1; } } static __inline__ __u8 *uac_processing_unit_bmControls(struct uac_processing_unit_descriptor *desc, int protocol) { switch (protocol) { case UAC_VERSION_1: return &desc->baSourceID[desc->bNrInPins + 5]; case UAC_VERSION_2: return &desc->baSourceID[desc->bNrInPins + 6]; case UAC_VERSION_3: return &desc->baSourceID[desc->bNrInPins + 2]; default: return NULL; } } static __inline__ __u8 uac_processing_unit_iProcessing(struct uac_processing_unit_descriptor *desc, int protocol) { __u8 control_size = uac_processing_unit_bControlSize(desc, protocol); switch (protocol) { case UAC_VERSION_1: case UAC_VERSION_2: default: return *(uac_processing_unit_bmControls(desc, protocol) + control_size); case UAC_VERSION_3: return 0; /* UAC3 does not have this field */ } } static __inline__ __u8 *uac_processing_unit_specific(struct uac_processing_unit_descriptor *desc, int protocol) { __u8 control_size = uac_processing_unit_bControlSize(desc, protocol); switch (protocol) { case UAC_VERSION_1: case UAC_VERSION_2: default: return uac_processing_unit_bmControls(desc, protocol) + control_size + 1; case UAC_VERSION_3: return uac_processing_unit_bmControls(desc, protocol) + control_size; } } /* * Extension Unit (XU) has almost compatible layout with Processing Unit, but * on UAC2, it has a different bmControls size (bControlSize); it's 1 byte for * XU while 2 bytes for PU. The last iExtension field is a one-byte index as * well as iProcessing field of PU. */ static __inline__ __u8 uac_extension_unit_bControlSize(struct uac_processing_unit_descriptor *desc, int protocol) { switch (protocol) { case UAC_VERSION_1: return desc->baSourceID[desc->bNrInPins + 4]; case UAC_VERSION_2: return 1; /* in UAC2, this value is constant */ case UAC_VERSION_3: return 4; /* in UAC3, this value is constant */ default: return 1; } } static __inline__ __u8 uac_extension_unit_iExtension(struct uac_processing_unit_descriptor *desc, int protocol) { __u8 control_size = uac_extension_unit_bControlSize(desc, protocol); switch (protocol) { case UAC_VERSION_1: case UAC_VERSION_2: default: return *(uac_processing_unit_bmControls(desc, protocol) + control_size); case UAC_VERSION_3: return 0; /* UAC3 does not have this field */ } } /* 4.5.2 Class-Specific AS Interface Descriptor */ struct uac1_as_header_descriptor { __u8 bLength; /* in bytes: 7 */ __u8 bDescriptorType; /* USB_DT_CS_INTERFACE */ __u8 bDescriptorSubtype; /* AS_GENERAL */ __u8 bTerminalLink; /* Terminal ID of connected Terminal */ __u8 bDelay; /* Delay introduced by the data path */ __le16 wFormatTag; /* The Audio Data Format */ } __attribute__ ((packed)); #define UAC_DT_AS_HEADER_SIZE 7 /* Formats - A.1.1 Audio Data Format Type I Codes */ #define UAC_FORMAT_TYPE_I_UNDEFINED 0x0 #define UAC_FORMAT_TYPE_I_PCM 0x1 #define UAC_FORMAT_TYPE_I_PCM8 0x2 #define UAC_FORMAT_TYPE_I_IEEE_FLOAT 0x3 #define UAC_FORMAT_TYPE_I_ALAW 0x4 #define UAC_FORMAT_TYPE_I_MULAW 0x5 struct uac_format_type_i_continuous_descriptor { __u8 bLength; /* in bytes: 8 + (ns * 3) */ __u8 bDescriptorType; /* USB_DT_CS_INTERFACE */ __u8 bDescriptorSubtype; /* FORMAT_TYPE */ __u8 bFormatType; /* FORMAT_TYPE_1 */ __u8 bNrChannels; /* physical channels in the stream */ __u8 bSubframeSize; /* */ __u8 bBitResolution; __u8 bSamFreqType; __u8 tLowerSamFreq[3]; __u8 tUpperSamFreq[3]; } __attribute__ ((packed)); #define UAC_FORMAT_TYPE_I_CONTINUOUS_DESC_SIZE 14 struct uac_format_type_i_discrete_descriptor { __u8 bLength; /* in bytes: 8 + (ns * 3) */ __u8 bDescriptorType; /* USB_DT_CS_INTERFACE */ __u8 bDescriptorSubtype; /* FORMAT_TYPE */ __u8 bFormatType; /* FORMAT_TYPE_1 */ __u8 bNrChannels; /* physical channels in the stream */ __u8 bSubframeSize; /* */ __u8 bBitResolution; __u8 bSamFreqType; __u8 tSamFreq[][3]; } __attribute__ ((packed)); #define DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(n) \ struct uac_format_type_i_discrete_descriptor_##n { \ __u8 bLength; \ __u8 bDescriptorType; \ __u8 bDescriptorSubtype; \ __u8 bFormatType; \ __u8 bNrChannels; \ __u8 bSubframeSize; \ __u8 bBitResolution; \ __u8 bSamFreqType; \ __u8 tSamFreq[n][3]; \ } __attribute__ ((packed)) #define UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(n) (8 + (n * 3)) struct uac_format_type_i_ext_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bFormatType; __u8 bSubslotSize; __u8 bBitResolution; __u8 bHeaderLength; __u8 bControlSize; __u8 bSideBandProtocol; } __attribute__((packed)); /* Formats - Audio Data Format Type I Codes */ #define UAC_FORMAT_TYPE_II_MPEG 0x1001 #define UAC_FORMAT_TYPE_II_AC3 0x1002 struct uac_format_type_ii_discrete_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bFormatType; __le16 wMaxBitRate; __le16 wSamplesPerFrame; __u8 bSamFreqType; __u8 tSamFreq[][3]; } __attribute__((packed)); struct uac_format_type_ii_ext_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDescriptorSubtype; __u8 bFormatType; __le16 wMaxBitRate; __le16 wSamplesPerFrame; __u8 bHeaderLength; __u8 bSideBandProtocol; } __attribute__((packed)); /* type III */ #define UAC_FORMAT_TYPE_III_IEC1937_AC3 0x2001 #define UAC_FORMAT_TYPE_III_IEC1937_MPEG1_LAYER1 0x2002 #define UAC_FORMAT_TYPE_III_IEC1937_MPEG2_NOEXT 0x2003 #define UAC_FORMAT_TYPE_III_IEC1937_MPEG2_EXT 0x2004 #define UAC_FORMAT_TYPE_III_IEC1937_MPEG2_LAYER1_LS 0x2005 #define UAC_FORMAT_TYPE_III_IEC1937_MPEG2_LAYER23_LS 0x2006 /* Formats - A.2 Format Type Codes */ #define UAC_FORMAT_TYPE_UNDEFINED 0x0 #define UAC_FORMAT_TYPE_I 0x1 #define UAC_FORMAT_TYPE_II 0x2 #define UAC_FORMAT_TYPE_III 0x3 #define UAC_EXT_FORMAT_TYPE_I 0x81 #define UAC_EXT_FORMAT_TYPE_II 0x82 #define UAC_EXT_FORMAT_TYPE_III 0x83 struct uac_iso_endpoint_descriptor { __u8 bLength; /* in bytes: 7 */ __u8 bDescriptorType; /* USB_DT_CS_ENDPOINT */ __u8 bDescriptorSubtype; /* EP_GENERAL */ __u8 bmAttributes; __u8 bLockDelayUnits; __le16 wLockDelay; } __attribute__((packed)); #define UAC_ISO_ENDPOINT_DESC_SIZE 7 #define UAC_EP_CS_ATTR_SAMPLE_RATE 0x01 #define UAC_EP_CS_ATTR_PITCH_CONTROL 0x02 #define UAC_EP_CS_ATTR_FILL_MAX 0x80 /* status word format (3.7.1.1) */ #define UAC1_STATUS_TYPE_ORIG_MASK 0x0f #define UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF 0x0 #define UAC1_STATUS_TYPE_ORIG_AUDIO_STREAM_IF 0x1 #define UAC1_STATUS_TYPE_ORIG_AUDIO_STREAM_EP 0x2 #define UAC1_STATUS_TYPE_IRQ_PENDING (1 << 7) #define UAC1_STATUS_TYPE_MEM_CHANGED (1 << 6) struct uac1_status_word { __u8 bStatusType; __u8 bOriginator; } __attribute__((packed)); #endif /* __LINUX_USB_AUDIO_H */ linux/usb/tmc.h000064400000011366151027430560007442 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2007 Stefan Kopp, Gechingen, Germany * Copyright (C) 2008 Novell, Inc. * Copyright (C) 2008 Greg Kroah-Hartman * Copyright (C) 2015 Dave Penkler * Copyright (C) 2018 IVI Foundation, Inc. * * This file holds USB constants defined by the USB Device Class * and USB488 Subclass Definitions for Test and Measurement devices * published by the USB-IF. * * It also has the ioctl and capability definitions for the * usbtmc kernel driver that userspace needs to know about. */ #ifndef __LINUX_USB_TMC_H #define __LINUX_USB_TMC_H #include /* __u8 etc */ /* USB TMC status values */ #define USBTMC_STATUS_SUCCESS 0x01 #define USBTMC_STATUS_PENDING 0x02 #define USBTMC_STATUS_FAILED 0x80 #define USBTMC_STATUS_TRANSFER_NOT_IN_PROGRESS 0x81 #define USBTMC_STATUS_SPLIT_NOT_IN_PROGRESS 0x82 #define USBTMC_STATUS_SPLIT_IN_PROGRESS 0x83 /* USB TMC requests values */ #define USBTMC_REQUEST_INITIATE_ABORT_BULK_OUT 1 #define USBTMC_REQUEST_CHECK_ABORT_BULK_OUT_STATUS 2 #define USBTMC_REQUEST_INITIATE_ABORT_BULK_IN 3 #define USBTMC_REQUEST_CHECK_ABORT_BULK_IN_STATUS 4 #define USBTMC_REQUEST_INITIATE_CLEAR 5 #define USBTMC_REQUEST_CHECK_CLEAR_STATUS 6 #define USBTMC_REQUEST_GET_CAPABILITIES 7 #define USBTMC_REQUEST_INDICATOR_PULSE 64 #define USBTMC488_REQUEST_READ_STATUS_BYTE 128 #define USBTMC488_REQUEST_REN_CONTROL 160 #define USBTMC488_REQUEST_GOTO_LOCAL 161 #define USBTMC488_REQUEST_LOCAL_LOCKOUT 162 struct usbtmc_request { __u8 bRequestType; __u8 bRequest; __u16 wValue; __u16 wIndex; __u16 wLength; } __attribute__ ((packed)); struct usbtmc_ctrlrequest { struct usbtmc_request req; void *data; /* pointer to user space */ } __attribute__ ((packed)); struct usbtmc_termchar { __u8 term_char; __u8 term_char_enabled; } __attribute__ ((packed)); /* * usbtmc_message->flags: */ #define USBTMC_FLAG_ASYNC 0x0001 #define USBTMC_FLAG_APPEND 0x0002 #define USBTMC_FLAG_IGNORE_TRAILER 0x0004 struct usbtmc_message { __u32 transfer_size; /* size of bytes to transfer */ __u32 transferred; /* size of received/written bytes */ __u32 flags; /* bit 0: 0 = synchronous; 1 = asynchronous */ void *message; /* pointer to header and data in user space */ } __attribute__ ((packed)); /* Request values for USBTMC driver's ioctl entry point */ #define USBTMC_IOC_NR 91 #define USBTMC_IOCTL_INDICATOR_PULSE _IO(USBTMC_IOC_NR, 1) #define USBTMC_IOCTL_CLEAR _IO(USBTMC_IOC_NR, 2) #define USBTMC_IOCTL_ABORT_BULK_OUT _IO(USBTMC_IOC_NR, 3) #define USBTMC_IOCTL_ABORT_BULK_IN _IO(USBTMC_IOC_NR, 4) #define USBTMC_IOCTL_CLEAR_OUT_HALT _IO(USBTMC_IOC_NR, 6) #define USBTMC_IOCTL_CLEAR_IN_HALT _IO(USBTMC_IOC_NR, 7) #define USBTMC_IOCTL_CTRL_REQUEST _IOWR(USBTMC_IOC_NR, 8, struct usbtmc_ctrlrequest) #define USBTMC_IOCTL_GET_TIMEOUT _IOR(USBTMC_IOC_NR, 9, __u32) #define USBTMC_IOCTL_SET_TIMEOUT _IOW(USBTMC_IOC_NR, 10, __u32) #define USBTMC_IOCTL_EOM_ENABLE _IOW(USBTMC_IOC_NR, 11, __u8) #define USBTMC_IOCTL_CONFIG_TERMCHAR _IOW(USBTMC_IOC_NR, 12, struct usbtmc_termchar) #define USBTMC_IOCTL_WRITE _IOWR(USBTMC_IOC_NR, 13, struct usbtmc_message) #define USBTMC_IOCTL_READ _IOWR(USBTMC_IOC_NR, 14, struct usbtmc_message) #define USBTMC_IOCTL_WRITE_RESULT _IOWR(USBTMC_IOC_NR, 15, __u32) #define USBTMC_IOCTL_API_VERSION _IOR(USBTMC_IOC_NR, 16, __u32) #define USBTMC488_IOCTL_GET_CAPS _IOR(USBTMC_IOC_NR, 17, unsigned char) #define USBTMC488_IOCTL_READ_STB _IOR(USBTMC_IOC_NR, 18, unsigned char) #define USBTMC488_IOCTL_REN_CONTROL _IOW(USBTMC_IOC_NR, 19, unsigned char) #define USBTMC488_IOCTL_GOTO_LOCAL _IO(USBTMC_IOC_NR, 20) #define USBTMC488_IOCTL_LOCAL_LOCKOUT _IO(USBTMC_IOC_NR, 21) #define USBTMC488_IOCTL_TRIGGER _IO(USBTMC_IOC_NR, 22) #define USBTMC488_IOCTL_WAIT_SRQ _IOW(USBTMC_IOC_NR, 23, __u32) #define USBTMC_IOCTL_MSG_IN_ATTR _IOR(USBTMC_IOC_NR, 24, __u8) #define USBTMC_IOCTL_AUTO_ABORT _IOW(USBTMC_IOC_NR, 25, __u8) #define USBTMC_IOCTL_GET_STB _IOR(USBTMC_IOC_NR, 26, __u8) #define USBTMC_IOCTL_GET_SRQ_STB _IOR(USBTMC_IOC_NR, 27, __u8) /* Cancel and cleanup asynchronous calls */ #define USBTMC_IOCTL_CANCEL_IO _IO(USBTMC_IOC_NR, 35) #define USBTMC_IOCTL_CLEANUP_IO _IO(USBTMC_IOC_NR, 36) /* Driver encoded usb488 capabilities */ #define USBTMC488_CAPABILITY_TRIGGER 1 #define USBTMC488_CAPABILITY_SIMPLE 2 #define USBTMC488_CAPABILITY_REN_CONTROL 2 #define USBTMC488_CAPABILITY_GOTO_LOCAL 2 #define USBTMC488_CAPABILITY_LOCAL_LOCKOUT 2 #define USBTMC488_CAPABILITY_488_DOT_2 4 #define USBTMC488_CAPABILITY_DT1 16 #define USBTMC488_CAPABILITY_RL1 32 #define USBTMC488_CAPABILITY_SR1 64 #define USBTMC488_CAPABILITY_FULL_SCPI 128 #endif linux/usb/g_uvc.h000064400000002061151027430560007752 0ustar00/* SPDX-License-Identifier: GPL-2.0+ */ /* * g_uvc.h -- USB Video Class Gadget driver API * * Copyright (C) 2009-2010 Laurent Pinchart */ #ifndef __LINUX_USB_G_UVC_H #define __LINUX_USB_G_UVC_H #include #include #include #define UVC_EVENT_FIRST (V4L2_EVENT_PRIVATE_START + 0) #define UVC_EVENT_CONNECT (V4L2_EVENT_PRIVATE_START + 0) #define UVC_EVENT_DISCONNECT (V4L2_EVENT_PRIVATE_START + 1) #define UVC_EVENT_STREAMON (V4L2_EVENT_PRIVATE_START + 2) #define UVC_EVENT_STREAMOFF (V4L2_EVENT_PRIVATE_START + 3) #define UVC_EVENT_SETUP (V4L2_EVENT_PRIVATE_START + 4) #define UVC_EVENT_DATA (V4L2_EVENT_PRIVATE_START + 5) #define UVC_EVENT_LAST (V4L2_EVENT_PRIVATE_START + 5) struct uvc_request_data { __s32 length; __u8 data[60]; }; struct uvc_event { union { enum usb_device_speed speed; struct usb_ctrlrequest req; struct uvc_request_data data; }; }; #define UVCIOC_SEND_RESPONSE _IOW('U', 1, struct uvc_request_data) #endif /* __LINUX_USB_G_UVC_H */ linux/usb/g_printer.h000064400000002551151027430560010644 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * g_printer.h -- Header file for USB Printer gadget driver * * Copyright (C) 2007 Craig W. Nadler * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LINUX_USB_G_PRINTER_H #define __LINUX_USB_G_PRINTER_H #define PRINTER_NOT_ERROR 0x08 #define PRINTER_SELECTED 0x10 #define PRINTER_PAPER_EMPTY 0x20 /* The 'g' code is also used by gadgetfs ioctl requests. * Don't add any colliding codes to either driver, and keep * them in unique ranges (size 0x20 for now). */ #define GADGET_GET_PRINTER_STATUS _IOR('g', 0x21, unsigned char) #define GADGET_SET_PRINTER_STATUS _IOWR('g', 0x22, unsigned char) #endif /* __LINUX_USB_G_PRINTER_H */ linux/usb/cdc-wdm.h000064400000001343151027430560010167 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * USB CDC Device Management userspace API definitions * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #ifndef __LINUX_USB_CDC_WDM_H #define __LINUX_USB_CDC_WDM_H #include /* * This IOCTL is used to retrieve the wMaxCommand for the device, * defining the message limit for both reading and writing. * * For CDC WDM functions this will be the wMaxCommand field of the * Device Management Functional Descriptor. */ #define IOCTL_WDM_MAX_COMMAND _IOR('H', 0xA0, __u16) #endif /* __LINUX_USB_CDC_WDM_H */ linux/usb/ch9.h000064400000115142151027430560007337 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * This file holds USB constants and structures that are needed for * USB device APIs. These are used by the USB device model, which is * defined in chapter 9 of the USB 2.0 specification and in the * Wireless USB 1.0 (spread around). Linux has several APIs in C that * need these: * * - the master/host side Linux-USB kernel driver API; * - the "usbfs" user space API; and * - the Linux "gadget" slave/device/peripheral side driver API. * * USB 2.0 adds an additional "On The Go" (OTG) mode, which lets systems * act either as a USB master/host or as a USB slave/device. That means * the master and slave side APIs benefit from working well together. * * There's also "Wireless USB", using low power short range radios for * peripheral interconnection but otherwise building on the USB framework. * * Note all descriptors are declared '__attribute__((packed))' so that: * * [a] they never get padded, either internally (USB spec writers * probably handled that) or externally; * * [b] so that accessing bigger-than-a-bytes fields will never * generate bus errors on any platform, even when the location of * its descriptor inside a bundle isn't "naturally aligned", and * * [c] for consistency, removing all doubt even when it appears to * someone that the two other points are non-issues for that * particular descriptor type. */ #ifndef __LINUX_USB_CH9_H #define __LINUX_USB_CH9_H #include /* __u8 etc */ #include /* le16_to_cpu */ /*-------------------------------------------------------------------------*/ /* CONTROL REQUEST SUPPORT */ /* * USB directions * * This bit flag is used in endpoint descriptors' bEndpointAddress field. * It's also one of three fields in control requests bRequestType. */ #define USB_DIR_OUT 0 /* to device */ #define USB_DIR_IN 0x80 /* to host */ /* * USB types, the second of three bRequestType fields */ #define USB_TYPE_MASK (0x03 << 5) #define USB_TYPE_STANDARD (0x00 << 5) #define USB_TYPE_CLASS (0x01 << 5) #define USB_TYPE_VENDOR (0x02 << 5) #define USB_TYPE_RESERVED (0x03 << 5) /* * USB recipients, the third of three bRequestType fields */ #define USB_RECIP_MASK 0x1f #define USB_RECIP_DEVICE 0x00 #define USB_RECIP_INTERFACE 0x01 #define USB_RECIP_ENDPOINT 0x02 #define USB_RECIP_OTHER 0x03 /* From Wireless USB 1.0 */ #define USB_RECIP_PORT 0x04 #define USB_RECIP_RPIPE 0x05 /* * Standard requests, for the bRequest field of a SETUP packet. * * These are qualified by the bRequestType field, so that for example * TYPE_CLASS or TYPE_VENDOR specific feature flags could be retrieved * by a GET_STATUS request. */ #define USB_REQ_GET_STATUS 0x00 #define USB_REQ_CLEAR_FEATURE 0x01 #define USB_REQ_SET_FEATURE 0x03 #define USB_REQ_SET_ADDRESS 0x05 #define USB_REQ_GET_DESCRIPTOR 0x06 #define USB_REQ_SET_DESCRIPTOR 0x07 #define USB_REQ_GET_CONFIGURATION 0x08 #define USB_REQ_SET_CONFIGURATION 0x09 #define USB_REQ_GET_INTERFACE 0x0A #define USB_REQ_SET_INTERFACE 0x0B #define USB_REQ_SYNCH_FRAME 0x0C #define USB_REQ_SET_SEL 0x30 #define USB_REQ_SET_ISOCH_DELAY 0x31 #define USB_REQ_SET_ENCRYPTION 0x0D /* Wireless USB */ #define USB_REQ_GET_ENCRYPTION 0x0E #define USB_REQ_RPIPE_ABORT 0x0E #define USB_REQ_SET_HANDSHAKE 0x0F #define USB_REQ_RPIPE_RESET 0x0F #define USB_REQ_GET_HANDSHAKE 0x10 #define USB_REQ_SET_CONNECTION 0x11 #define USB_REQ_SET_SECURITY_DATA 0x12 #define USB_REQ_GET_SECURITY_DATA 0x13 #define USB_REQ_SET_WUSB_DATA 0x14 #define USB_REQ_LOOPBACK_DATA_WRITE 0x15 #define USB_REQ_LOOPBACK_DATA_READ 0x16 #define USB_REQ_SET_INTERFACE_DS 0x17 /* specific requests for USB Power Delivery */ #define USB_REQ_GET_PARTNER_PDO 20 #define USB_REQ_GET_BATTERY_STATUS 21 #define USB_REQ_SET_PDO 22 #define USB_REQ_GET_VDM 23 #define USB_REQ_SEND_VDM 24 /* The Link Power Management (LPM) ECN defines USB_REQ_TEST_AND_SET command, * used by hubs to put ports into a new L1 suspend state, except that it * forgot to define its number ... */ /* * USB feature flags are written using USB_REQ_{CLEAR,SET}_FEATURE, and * are read as a bit array returned by USB_REQ_GET_STATUS. (So there * are at most sixteen features of each type.) Hubs may also support a * new USB_REQ_TEST_AND_SET_FEATURE to put ports into L1 suspend. */ #define USB_DEVICE_SELF_POWERED 0 /* (read only) */ #define USB_DEVICE_REMOTE_WAKEUP 1 /* dev may initiate wakeup */ #define USB_DEVICE_TEST_MODE 2 /* (wired high speed only) */ #define USB_DEVICE_BATTERY 2 /* (wireless) */ #define USB_DEVICE_B_HNP_ENABLE 3 /* (otg) dev may initiate HNP */ #define USB_DEVICE_WUSB_DEVICE 3 /* (wireless)*/ #define USB_DEVICE_A_HNP_SUPPORT 4 /* (otg) RH port supports HNP */ #define USB_DEVICE_A_ALT_HNP_SUPPORT 5 /* (otg) other RH port does */ #define USB_DEVICE_DEBUG_MODE 6 /* (special devices only) */ /* * Test Mode Selectors * See USB 2.0 spec Table 9-7 */ #define TEST_J 1 #define TEST_K 2 #define TEST_SE0_NAK 3 #define TEST_PACKET 4 #define TEST_FORCE_EN 5 /* Status Type */ #define USB_STATUS_TYPE_STANDARD 0 #define USB_STATUS_TYPE_PTM 1 /* * New Feature Selectors as added by USB 3.0 * See USB 3.0 spec Table 9-7 */ #define USB_DEVICE_U1_ENABLE 48 /* dev may initiate U1 transition */ #define USB_DEVICE_U2_ENABLE 49 /* dev may initiate U2 transition */ #define USB_DEVICE_LTM_ENABLE 50 /* dev may send LTM */ #define USB_INTRF_FUNC_SUSPEND 0 /* function suspend */ #define USB_INTR_FUNC_SUSPEND_OPT_MASK 0xFF00 /* * Suspend Options, Table 9-8 USB 3.0 spec */ #define USB_INTRF_FUNC_SUSPEND_LP (1 << (8 + 0)) #define USB_INTRF_FUNC_SUSPEND_RW (1 << (8 + 1)) /* * Interface status, Figure 9-5 USB 3.0 spec */ #define USB_INTRF_STAT_FUNC_RW_CAP 1 #define USB_INTRF_STAT_FUNC_RW 2 #define USB_ENDPOINT_HALT 0 /* IN/OUT will STALL */ /* Bit array elements as returned by the USB_REQ_GET_STATUS request. */ #define USB_DEV_STAT_U1_ENABLED 2 /* transition into U1 state */ #define USB_DEV_STAT_U2_ENABLED 3 /* transition into U2 state */ #define USB_DEV_STAT_LTM_ENABLED 4 /* Latency tolerance messages */ /* * Feature selectors from Table 9-8 USB Power Delivery spec */ #define USB_DEVICE_BATTERY_WAKE_MASK 40 #define USB_DEVICE_OS_IS_PD_AWARE 41 #define USB_DEVICE_POLICY_MODE 42 #define USB_PORT_PR_SWAP 43 #define USB_PORT_GOTO_MIN 44 #define USB_PORT_RETURN_POWER 45 #define USB_PORT_ACCEPT_PD_REQUEST 46 #define USB_PORT_REJECT_PD_REQUEST 47 #define USB_PORT_PORT_PD_RESET 48 #define USB_PORT_C_PORT_PD_CHANGE 49 #define USB_PORT_CABLE_PD_RESET 50 #define USB_DEVICE_CHARGING_POLICY 54 /** * struct usb_ctrlrequest - SETUP data for a USB device control request * @bRequestType: matches the USB bmRequestType field * @bRequest: matches the USB bRequest field * @wValue: matches the USB wValue field (le16 byte order) * @wIndex: matches the USB wIndex field (le16 byte order) * @wLength: matches the USB wLength field (le16 byte order) * * This structure is used to send control requests to a USB device. It matches * the different fields of the USB 2.0 Spec section 9.3, table 9-2. See the * USB spec for a fuller description of the different fields, and what they are * used for. * * Note that the driver for any interface can issue control requests. * For most devices, interfaces don't coordinate with each other, so * such requests may be made at any time. */ struct usb_ctrlrequest { __u8 bRequestType; __u8 bRequest; __le16 wValue; __le16 wIndex; __le16 wLength; } __attribute__ ((packed)); /*-------------------------------------------------------------------------*/ /* * STANDARD DESCRIPTORS ... as returned by GET_DESCRIPTOR, or * (rarely) accepted by SET_DESCRIPTOR. * * Note that all multi-byte values here are encoded in little endian * byte order "on the wire". Within the kernel and when exposed * through the Linux-USB APIs, they are not converted to cpu byte * order; it is the responsibility of the client code to do this. * The single exception is when device and configuration descriptors (but * not other descriptors) are read from character devices * (i.e. /dev/bus/usb/BBB/DDD); * in this case the fields are converted to host endianness by the kernel. */ /* * Descriptor types ... USB 2.0 spec table 9.5 */ #define USB_DT_DEVICE 0x01 #define USB_DT_CONFIG 0x02 #define USB_DT_STRING 0x03 #define USB_DT_INTERFACE 0x04 #define USB_DT_ENDPOINT 0x05 #define USB_DT_DEVICE_QUALIFIER 0x06 #define USB_DT_OTHER_SPEED_CONFIG 0x07 #define USB_DT_INTERFACE_POWER 0x08 /* these are from a minor usb 2.0 revision (ECN) */ #define USB_DT_OTG 0x09 #define USB_DT_DEBUG 0x0a #define USB_DT_INTERFACE_ASSOCIATION 0x0b /* these are from the Wireless USB spec */ #define USB_DT_SECURITY 0x0c #define USB_DT_KEY 0x0d #define USB_DT_ENCRYPTION_TYPE 0x0e #define USB_DT_BOS 0x0f #define USB_DT_DEVICE_CAPABILITY 0x10 #define USB_DT_WIRELESS_ENDPOINT_COMP 0x11 #define USB_DT_WIRE_ADAPTER 0x21 #define USB_DT_RPIPE 0x22 #define USB_DT_CS_RADIO_CONTROL 0x23 /* From the T10 UAS specification */ #define USB_DT_PIPE_USAGE 0x24 /* From the USB 3.0 spec */ #define USB_DT_SS_ENDPOINT_COMP 0x30 /* From the USB 3.1 spec */ #define USB_DT_SSP_ISOC_ENDPOINT_COMP 0x31 /* Conventional codes for class-specific descriptors. The convention is * defined in the USB "Common Class" Spec (3.11). Individual class specs * are authoritative for their usage, not the "common class" writeup. */ #define USB_DT_CS_DEVICE (USB_TYPE_CLASS | USB_DT_DEVICE) #define USB_DT_CS_CONFIG (USB_TYPE_CLASS | USB_DT_CONFIG) #define USB_DT_CS_STRING (USB_TYPE_CLASS | USB_DT_STRING) #define USB_DT_CS_INTERFACE (USB_TYPE_CLASS | USB_DT_INTERFACE) #define USB_DT_CS_ENDPOINT (USB_TYPE_CLASS | USB_DT_ENDPOINT) /* All standard descriptors have these 2 fields at the beginning */ struct usb_descriptor_header { __u8 bLength; __u8 bDescriptorType; } __attribute__ ((packed)); /*-------------------------------------------------------------------------*/ /* USB_DT_DEVICE: Device descriptor */ struct usb_device_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 bcdUSB; __u8 bDeviceClass; __u8 bDeviceSubClass; __u8 bDeviceProtocol; __u8 bMaxPacketSize0; __le16 idVendor; __le16 idProduct; __le16 bcdDevice; __u8 iManufacturer; __u8 iProduct; __u8 iSerialNumber; __u8 bNumConfigurations; } __attribute__ ((packed)); #define USB_DT_DEVICE_SIZE 18 /* * Device and/or Interface Class codes * as found in bDeviceClass or bInterfaceClass * and defined by www.usb.org documents */ #define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */ #define USB_CLASS_AUDIO 1 #define USB_CLASS_COMM 2 #define USB_CLASS_HID 3 #define USB_CLASS_PHYSICAL 5 #define USB_CLASS_STILL_IMAGE 6 #define USB_CLASS_PRINTER 7 #define USB_CLASS_MASS_STORAGE 8 #define USB_CLASS_HUB 9 #define USB_CLASS_CDC_DATA 0x0a #define USB_CLASS_CSCID 0x0b /* chip+ smart card */ #define USB_CLASS_CONTENT_SEC 0x0d /* content security */ #define USB_CLASS_VIDEO 0x0e #define USB_CLASS_WIRELESS_CONTROLLER 0xe0 #define USB_CLASS_PERSONAL_HEALTHCARE 0x0f #define USB_CLASS_AUDIO_VIDEO 0x10 #define USB_CLASS_BILLBOARD 0x11 #define USB_CLASS_USB_TYPE_C_BRIDGE 0x12 #define USB_CLASS_MISC 0xef #define USB_CLASS_APP_SPEC 0xfe #define USB_CLASS_VENDOR_SPEC 0xff #define USB_SUBCLASS_VENDOR_SPEC 0xff /*-------------------------------------------------------------------------*/ /* USB_DT_CONFIG: Configuration descriptor information. * * USB_DT_OTHER_SPEED_CONFIG is the same descriptor, except that the * descriptor type is different. Highspeed-capable devices can look * different depending on what speed they're currently running. Only * devices with a USB_DT_DEVICE_QUALIFIER have any OTHER_SPEED_CONFIG * descriptors. */ struct usb_config_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 wTotalLength; __u8 bNumInterfaces; __u8 bConfigurationValue; __u8 iConfiguration; __u8 bmAttributes; __u8 bMaxPower; } __attribute__ ((packed)); #define USB_DT_CONFIG_SIZE 9 /* from config descriptor bmAttributes */ #define USB_CONFIG_ATT_ONE (1 << 7) /* must be set */ #define USB_CONFIG_ATT_SELFPOWER (1 << 6) /* self powered */ #define USB_CONFIG_ATT_WAKEUP (1 << 5) /* can wakeup */ #define USB_CONFIG_ATT_BATTERY (1 << 4) /* battery powered */ /*-------------------------------------------------------------------------*/ /* USB String descriptors can contain at most 126 characters. */ #define USB_MAX_STRING_LEN 126 /* USB_DT_STRING: String descriptor */ struct usb_string_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 wData[1]; /* UTF-16LE encoded */ } __attribute__ ((packed)); /* note that "string" zero is special, it holds language codes that * the device supports, not Unicode characters. */ /*-------------------------------------------------------------------------*/ /* USB_DT_INTERFACE: Interface descriptor */ struct usb_interface_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bInterfaceNumber; __u8 bAlternateSetting; __u8 bNumEndpoints; __u8 bInterfaceClass; __u8 bInterfaceSubClass; __u8 bInterfaceProtocol; __u8 iInterface; } __attribute__ ((packed)); #define USB_DT_INTERFACE_SIZE 9 /*-------------------------------------------------------------------------*/ /* USB_DT_ENDPOINT: Endpoint descriptor */ struct usb_endpoint_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bEndpointAddress; __u8 bmAttributes; __le16 wMaxPacketSize; __u8 bInterval; /* NOTE: these two are _only_ in audio endpoints. */ /* use USB_DT_ENDPOINT*_SIZE in bLength, not sizeof. */ __u8 bRefresh; __u8 bSynchAddress; } __attribute__ ((packed)); #define USB_DT_ENDPOINT_SIZE 7 #define USB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */ /* * Endpoints */ #define USB_ENDPOINT_NUMBER_MASK 0x0f /* in bEndpointAddress */ #define USB_ENDPOINT_DIR_MASK 0x80 #define USB_ENDPOINT_XFERTYPE_MASK 0x03 /* in bmAttributes */ #define USB_ENDPOINT_XFER_CONTROL 0 #define USB_ENDPOINT_XFER_ISOC 1 #define USB_ENDPOINT_XFER_BULK 2 #define USB_ENDPOINT_XFER_INT 3 #define USB_ENDPOINT_MAX_ADJUSTABLE 0x80 #define USB_ENDPOINT_MAXP_MASK 0x07ff #define USB_EP_MAXP_MULT_SHIFT 11 #define USB_EP_MAXP_MULT_MASK (3 << USB_EP_MAXP_MULT_SHIFT) #define USB_EP_MAXP_MULT(m) \ (((m) & USB_EP_MAXP_MULT_MASK) >> USB_EP_MAXP_MULT_SHIFT) /* The USB 3.0 spec redefines bits 5:4 of bmAttributes as interrupt ep type. */ #define USB_ENDPOINT_INTRTYPE 0x30 #define USB_ENDPOINT_INTR_PERIODIC (0 << 4) #define USB_ENDPOINT_INTR_NOTIFICATION (1 << 4) #define USB_ENDPOINT_SYNCTYPE 0x0c #define USB_ENDPOINT_SYNC_NONE (0 << 2) #define USB_ENDPOINT_SYNC_ASYNC (1 << 2) #define USB_ENDPOINT_SYNC_ADAPTIVE (2 << 2) #define USB_ENDPOINT_SYNC_SYNC (3 << 2) #define USB_ENDPOINT_USAGE_MASK 0x30 #define USB_ENDPOINT_USAGE_DATA 0x00 #define USB_ENDPOINT_USAGE_FEEDBACK 0x10 #define USB_ENDPOINT_USAGE_IMPLICIT_FB 0x20 /* Implicit feedback Data endpoint */ /*-------------------------------------------------------------------------*/ /** * usb_endpoint_num - get the endpoint's number * @epd: endpoint to be checked * * Returns @epd's number: 0 to 15. */ static __inline__ int usb_endpoint_num(const struct usb_endpoint_descriptor *epd) { return epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK; } /** * usb_endpoint_type - get the endpoint's transfer type * @epd: endpoint to be checked * * Returns one of USB_ENDPOINT_XFER_{CONTROL, ISOC, BULK, INT} according * to @epd's transfer type. */ static __inline__ int usb_endpoint_type(const struct usb_endpoint_descriptor *epd) { return epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK; } /** * usb_endpoint_dir_in - check if the endpoint has IN direction * @epd: endpoint to be checked * * Returns true if the endpoint is of type IN, otherwise it returns false. */ static __inline__ int usb_endpoint_dir_in(const struct usb_endpoint_descriptor *epd) { return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN); } /** * usb_endpoint_dir_out - check if the endpoint has OUT direction * @epd: endpoint to be checked * * Returns true if the endpoint is of type OUT, otherwise it returns false. */ static __inline__ int usb_endpoint_dir_out( const struct usb_endpoint_descriptor *epd) { return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT); } /** * usb_endpoint_xfer_bulk - check if the endpoint has bulk transfer type * @epd: endpoint to be checked * * Returns true if the endpoint is of type bulk, otherwise it returns false. */ static __inline__ int usb_endpoint_xfer_bulk( const struct usb_endpoint_descriptor *epd) { return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK); } /** * usb_endpoint_xfer_control - check if the endpoint has control transfer type * @epd: endpoint to be checked * * Returns true if the endpoint is of type control, otherwise it returns false. */ static __inline__ int usb_endpoint_xfer_control( const struct usb_endpoint_descriptor *epd) { return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_CONTROL); } /** * usb_endpoint_xfer_int - check if the endpoint has interrupt transfer type * @epd: endpoint to be checked * * Returns true if the endpoint is of type interrupt, otherwise it returns * false. */ static __inline__ int usb_endpoint_xfer_int( const struct usb_endpoint_descriptor *epd) { return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT); } /** * usb_endpoint_xfer_isoc - check if the endpoint has isochronous transfer type * @epd: endpoint to be checked * * Returns true if the endpoint is of type isochronous, otherwise it returns * false. */ static __inline__ int usb_endpoint_xfer_isoc( const struct usb_endpoint_descriptor *epd) { return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_ISOC); } /** * usb_endpoint_is_bulk_in - check if the endpoint is bulk IN * @epd: endpoint to be checked * * Returns true if the endpoint has bulk transfer type and IN direction, * otherwise it returns false. */ static __inline__ int usb_endpoint_is_bulk_in( const struct usb_endpoint_descriptor *epd) { return usb_endpoint_xfer_bulk(epd) && usb_endpoint_dir_in(epd); } /** * usb_endpoint_is_bulk_out - check if the endpoint is bulk OUT * @epd: endpoint to be checked * * Returns true if the endpoint has bulk transfer type and OUT direction, * otherwise it returns false. */ static __inline__ int usb_endpoint_is_bulk_out( const struct usb_endpoint_descriptor *epd) { return usb_endpoint_xfer_bulk(epd) && usb_endpoint_dir_out(epd); } /** * usb_endpoint_is_int_in - check if the endpoint is interrupt IN * @epd: endpoint to be checked * * Returns true if the endpoint has interrupt transfer type and IN direction, * otherwise it returns false. */ static __inline__ int usb_endpoint_is_int_in( const struct usb_endpoint_descriptor *epd) { return usb_endpoint_xfer_int(epd) && usb_endpoint_dir_in(epd); } /** * usb_endpoint_is_int_out - check if the endpoint is interrupt OUT * @epd: endpoint to be checked * * Returns true if the endpoint has interrupt transfer type and OUT direction, * otherwise it returns false. */ static __inline__ int usb_endpoint_is_int_out( const struct usb_endpoint_descriptor *epd) { return usb_endpoint_xfer_int(epd) && usb_endpoint_dir_out(epd); } /** * usb_endpoint_is_isoc_in - check if the endpoint is isochronous IN * @epd: endpoint to be checked * * Returns true if the endpoint has isochronous transfer type and IN direction, * otherwise it returns false. */ static __inline__ int usb_endpoint_is_isoc_in( const struct usb_endpoint_descriptor *epd) { return usb_endpoint_xfer_isoc(epd) && usb_endpoint_dir_in(epd); } /** * usb_endpoint_is_isoc_out - check if the endpoint is isochronous OUT * @epd: endpoint to be checked * * Returns true if the endpoint has isochronous transfer type and OUT direction, * otherwise it returns false. */ static __inline__ int usb_endpoint_is_isoc_out( const struct usb_endpoint_descriptor *epd) { return usb_endpoint_xfer_isoc(epd) && usb_endpoint_dir_out(epd); } /** * usb_endpoint_maxp - get endpoint's max packet size * @epd: endpoint to be checked * * Returns @epd's max packet bits [10:0] */ static __inline__ int usb_endpoint_maxp(const struct usb_endpoint_descriptor *epd) { return __le16_to_cpu(epd->wMaxPacketSize) & USB_ENDPOINT_MAXP_MASK; } /** * usb_endpoint_maxp_mult - get endpoint's transactional opportunities * @epd: endpoint to be checked * * Return @epd's wMaxPacketSize[12:11] + 1 */ static __inline__ int usb_endpoint_maxp_mult(const struct usb_endpoint_descriptor *epd) { int maxp = __le16_to_cpu(epd->wMaxPacketSize); return USB_EP_MAXP_MULT(maxp) + 1; } static __inline__ int usb_endpoint_interrupt_type( const struct usb_endpoint_descriptor *epd) { return epd->bmAttributes & USB_ENDPOINT_INTRTYPE; } /*-------------------------------------------------------------------------*/ /* USB_DT_SSP_ISOC_ENDPOINT_COMP: SuperSpeedPlus Isochronous Endpoint Companion * descriptor */ struct usb_ssp_isoc_ep_comp_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 wReseved; __le32 dwBytesPerInterval; } __attribute__ ((packed)); #define USB_DT_SSP_ISOC_EP_COMP_SIZE 8 /*-------------------------------------------------------------------------*/ /* USB_DT_SS_ENDPOINT_COMP: SuperSpeed Endpoint Companion descriptor */ struct usb_ss_ep_comp_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bMaxBurst; __u8 bmAttributes; __le16 wBytesPerInterval; } __attribute__ ((packed)); #define USB_DT_SS_EP_COMP_SIZE 6 /* Bits 4:0 of bmAttributes if this is a bulk endpoint */ static __inline__ int usb_ss_max_streams(const struct usb_ss_ep_comp_descriptor *comp) { int max_streams; if (!comp) return 0; max_streams = comp->bmAttributes & 0x1f; if (!max_streams) return 0; max_streams = 1 << max_streams; return max_streams; } /* Bits 1:0 of bmAttributes if this is an isoc endpoint */ #define USB_SS_MULT(p) (1 + ((p) & 0x3)) /* Bit 7 of bmAttributes if a SSP isoc endpoint companion descriptor exists */ #define USB_SS_SSP_ISOC_COMP(p) ((p) & (1 << 7)) /*-------------------------------------------------------------------------*/ /* USB_DT_DEVICE_QUALIFIER: Device Qualifier descriptor */ struct usb_qualifier_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 bcdUSB; __u8 bDeviceClass; __u8 bDeviceSubClass; __u8 bDeviceProtocol; __u8 bMaxPacketSize0; __u8 bNumConfigurations; __u8 bRESERVED; } __attribute__ ((packed)); /*-------------------------------------------------------------------------*/ /* USB_DT_OTG (from OTG 1.0a supplement) */ struct usb_otg_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bmAttributes; /* support for HNP, SRP, etc */ } __attribute__ ((packed)); /* USB_DT_OTG (from OTG 2.0 supplement) */ struct usb_otg20_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bmAttributes; /* support for HNP, SRP and ADP, etc */ __le16 bcdOTG; /* OTG and EH supplement release number * in binary-coded decimal(i.e. 2.0 is 0200H) */ } __attribute__ ((packed)); /* from usb_otg_descriptor.bmAttributes */ #define USB_OTG_SRP (1 << 0) #define USB_OTG_HNP (1 << 1) /* swap host/device roles */ #define USB_OTG_ADP (1 << 2) /* support ADP */ #define OTG_STS_SELECTOR 0xF000 /* OTG status selector */ /*-------------------------------------------------------------------------*/ /* USB_DT_DEBUG: for special highspeed devices, replacing serial console */ struct usb_debug_descriptor { __u8 bLength; __u8 bDescriptorType; /* bulk endpoints with 8 byte maxpacket */ __u8 bDebugInEndpoint; __u8 bDebugOutEndpoint; } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB_DT_INTERFACE_ASSOCIATION: groups interfaces */ struct usb_interface_assoc_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bFirstInterface; __u8 bInterfaceCount; __u8 bFunctionClass; __u8 bFunctionSubClass; __u8 bFunctionProtocol; __u8 iFunction; } __attribute__ ((packed)); #define USB_DT_INTERFACE_ASSOCIATION_SIZE 8 /*-------------------------------------------------------------------------*/ /* USB_DT_SECURITY: group of wireless security descriptors, including * encryption types available for setting up a CC/association. */ struct usb_security_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 wTotalLength; __u8 bNumEncryptionTypes; } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB_DT_KEY: used with {GET,SET}_SECURITY_DATA; only public keys * may be retrieved. */ struct usb_key_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 tTKID[3]; __u8 bReserved; __u8 bKeyData[0]; } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB_DT_ENCRYPTION_TYPE: bundled in DT_SECURITY groups */ struct usb_encryption_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bEncryptionType; #define USB_ENC_TYPE_UNSECURE 0 #define USB_ENC_TYPE_WIRED 1 /* non-wireless mode */ #define USB_ENC_TYPE_CCM_1 2 /* aes128/cbc session */ #define USB_ENC_TYPE_RSA_1 3 /* rsa3072/sha1 auth */ __u8 bEncryptionValue; /* use in SET_ENCRYPTION */ __u8 bAuthKeyIndex; } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB_DT_BOS: group of device-level capabilities */ struct usb_bos_descriptor { __u8 bLength; __u8 bDescriptorType; __le16 wTotalLength; __u8 bNumDeviceCaps; } __attribute__((packed)); #define USB_DT_BOS_SIZE 5 /*-------------------------------------------------------------------------*/ /* USB_DT_DEVICE_CAPABILITY: grouped with BOS */ struct usb_dev_cap_header { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; } __attribute__((packed)); #define USB_CAP_TYPE_WIRELESS_USB 1 struct usb_wireless_cap_descriptor { /* Ultra Wide Band */ __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __u8 bmAttributes; #define USB_WIRELESS_P2P_DRD (1 << 1) #define USB_WIRELESS_BEACON_MASK (3 << 2) #define USB_WIRELESS_BEACON_SELF (1 << 2) #define USB_WIRELESS_BEACON_DIRECTED (2 << 2) #define USB_WIRELESS_BEACON_NONE (3 << 2) __le16 wPHYRates; /* bit rates, Mbps */ #define USB_WIRELESS_PHY_53 (1 << 0) /* always set */ #define USB_WIRELESS_PHY_80 (1 << 1) #define USB_WIRELESS_PHY_107 (1 << 2) /* always set */ #define USB_WIRELESS_PHY_160 (1 << 3) #define USB_WIRELESS_PHY_200 (1 << 4) /* always set */ #define USB_WIRELESS_PHY_320 (1 << 5) #define USB_WIRELESS_PHY_400 (1 << 6) #define USB_WIRELESS_PHY_480 (1 << 7) __u8 bmTFITXPowerInfo; /* TFI power levels */ __u8 bmFFITXPowerInfo; /* FFI power levels */ __le16 bmBandGroup; __u8 bReserved; } __attribute__((packed)); #define USB_DT_USB_WIRELESS_CAP_SIZE 11 /* USB 2.0 Extension descriptor */ #define USB_CAP_TYPE_EXT 2 struct usb_ext_cap_descriptor { /* Link Power Management */ __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __le32 bmAttributes; #define USB_LPM_SUPPORT (1 << 1) /* supports LPM */ #define USB_BESL_SUPPORT (1 << 2) /* supports BESL */ #define USB_BESL_BASELINE_VALID (1 << 3) /* Baseline BESL valid*/ #define USB_BESL_DEEP_VALID (1 << 4) /* Deep BESL valid */ #define USB_SET_BESL_BASELINE(p) (((p) & 0xf) << 8) #define USB_SET_BESL_DEEP(p) (((p) & 0xf) << 12) #define USB_GET_BESL_BASELINE(p) (((p) & (0xf << 8)) >> 8) #define USB_GET_BESL_DEEP(p) (((p) & (0xf << 12)) >> 12) } __attribute__((packed)); #define USB_DT_USB_EXT_CAP_SIZE 7 /* * SuperSpeed USB Capability descriptor: Defines the set of SuperSpeed USB * specific device level capabilities */ #define USB_SS_CAP_TYPE 3 struct usb_ss_cap_descriptor { /* Link Power Management */ __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __u8 bmAttributes; #define USB_LTM_SUPPORT (1 << 1) /* supports LTM */ __le16 wSpeedSupported; #define USB_LOW_SPEED_OPERATION (1) /* Low speed operation */ #define USB_FULL_SPEED_OPERATION (1 << 1) /* Full speed operation */ #define USB_HIGH_SPEED_OPERATION (1 << 2) /* High speed operation */ #define USB_5GBPS_OPERATION (1 << 3) /* Operation at 5Gbps */ __u8 bFunctionalitySupport; __u8 bU1devExitLat; __le16 bU2DevExitLat; } __attribute__((packed)); #define USB_DT_USB_SS_CAP_SIZE 10 /* * Container ID Capability descriptor: Defines the instance unique ID used to * identify the instance across all operating modes */ #define CONTAINER_ID_TYPE 4 struct usb_ss_container_id_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __u8 bReserved; __u8 ContainerID[16]; /* 128-bit number */ } __attribute__((packed)); #define USB_DT_USB_SS_CONTN_ID_SIZE 20 /* * SuperSpeed Plus USB Capability descriptor: Defines the set of * SuperSpeed Plus USB specific device level capabilities */ #define USB_SSP_CAP_TYPE 0xa struct usb_ssp_cap_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __u8 bReserved; __le32 bmAttributes; #define USB_SSP_SUBLINK_SPEED_ATTRIBS (0x1f << 0) /* sublink speed entries */ #define USB_SSP_SUBLINK_SPEED_IDS (0xf << 5) /* speed ID entries */ __le16 wFunctionalitySupport; #define USB_SSP_MIN_SUBLINK_SPEED_ATTRIBUTE_ID (0xf) #define USB_SSP_MIN_RX_LANE_COUNT (0xf << 8) #define USB_SSP_MIN_TX_LANE_COUNT (0xf << 12) __le16 wReserved; __le32 bmSublinkSpeedAttr[1]; /* list of sublink speed attrib entries */ #define USB_SSP_SUBLINK_SPEED_SSID (0xf) /* sublink speed ID */ #define USB_SSP_SUBLINK_SPEED_LSE (0x3 << 4) /* Lanespeed exponent */ #define USB_SSP_SUBLINK_SPEED_LSE_BPS 0 #define USB_SSP_SUBLINK_SPEED_LSE_KBPS 1 #define USB_SSP_SUBLINK_SPEED_LSE_MBPS 2 #define USB_SSP_SUBLINK_SPEED_LSE_GBPS 3 #define USB_SSP_SUBLINK_SPEED_ST (0x3 << 6) /* Sublink type */ #define USB_SSP_SUBLINK_SPEED_ST_SYM_RX 0 #define USB_SSP_SUBLINK_SPEED_ST_ASYM_RX 1 #define USB_SSP_SUBLINK_SPEED_ST_SYM_TX 2 #define USB_SSP_SUBLINK_SPEED_ST_ASYM_TX 3 #define USB_SSP_SUBLINK_SPEED_RSVD (0x3f << 8) /* Reserved */ #define USB_SSP_SUBLINK_SPEED_LP (0x3 << 14) /* Link protocol */ #define USB_SSP_SUBLINK_SPEED_LP_SS 0 #define USB_SSP_SUBLINK_SPEED_LP_SSP 1 #define USB_SSP_SUBLINK_SPEED_LSM (0xff << 16) /* Lanespeed mantissa */ } __attribute__((packed)); /* * USB Power Delivery Capability Descriptor: * Defines capabilities for PD */ /* Defines the various PD Capabilities of this device */ #define USB_PD_POWER_DELIVERY_CAPABILITY 0x06 /* Provides information on each battery supported by the device */ #define USB_PD_BATTERY_INFO_CAPABILITY 0x07 /* The Consumer characteristics of a Port on the device */ #define USB_PD_PD_CONSUMER_PORT_CAPABILITY 0x08 /* The provider characteristics of a Port on the device */ #define USB_PD_PD_PROVIDER_PORT_CAPABILITY 0x09 struct usb_pd_cap_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; /* set to USB_PD_POWER_DELIVERY_CAPABILITY */ __u8 bReserved; __le32 bmAttributes; #define USB_PD_CAP_BATTERY_CHARGING (1 << 1) /* supports Battery Charging specification */ #define USB_PD_CAP_USB_PD (1 << 2) /* supports USB Power Delivery specification */ #define USB_PD_CAP_PROVIDER (1 << 3) /* can provide power */ #define USB_PD_CAP_CONSUMER (1 << 4) /* can consume power */ #define USB_PD_CAP_CHARGING_POLICY (1 << 5) /* supports CHARGING_POLICY feature */ #define USB_PD_CAP_TYPE_C_CURRENT (1 << 6) /* supports power capabilities defined in the USB Type-C Specification */ #define USB_PD_CAP_PWR_AC (1 << 8) #define USB_PD_CAP_PWR_BAT (1 << 9) #define USB_PD_CAP_PWR_USE_V_BUS (1 << 14) __le16 bmProviderPorts; /* Bit zero refers to the UFP of the device */ __le16 bmConsumerPorts; __le16 bcdBCVersion; __le16 bcdPDVersion; __le16 bcdUSBTypeCVersion; } __attribute__((packed)); struct usb_pd_cap_battery_info_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; /* Index of string descriptor shall contain the user friendly name for this battery */ __u8 iBattery; /* Index of string descriptor shall contain the Serial Number String for this battery */ __u8 iSerial; __u8 iManufacturer; __u8 bBatteryId; /* uniquely identifies this battery in status Messages */ __u8 bReserved; /* * Shall contain the Battery Charge value above which this * battery is considered to be fully charged but not necessarily * “topped off.” */ __le32 dwChargedThreshold; /* in mWh */ /* * Shall contain the minimum charge level of this battery such * that above this threshold, a device can be assured of being * able to power up successfully (see Battery Charging 1.2). */ __le32 dwWeakThreshold; /* in mWh */ __le32 dwBatteryDesignCapacity; /* in mWh */ __le32 dwBatteryLastFullchargeCapacity; /* in mWh */ } __attribute__((packed)); struct usb_pd_cap_consumer_port_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __u8 bReserved; __u8 bmCapabilities; /* port will oerate under: */ #define USB_PD_CAP_CONSUMER_BC (1 << 0) /* BC */ #define USB_PD_CAP_CONSUMER_PD (1 << 1) /* PD */ #define USB_PD_CAP_CONSUMER_TYPE_C (1 << 2) /* USB Type-C Current */ __le16 wMinVoltage; /* in 50mV units */ __le16 wMaxVoltage; /* in 50mV units */ __u16 wReserved; __le32 dwMaxOperatingPower; /* in 10 mW - operating at steady state */ __le32 dwMaxPeakPower; /* in 10mW units - operating at peak power */ __le32 dwMaxPeakPowerTime; /* in 100ms units - duration of peak */ #define USB_PD_CAP_CONSUMER_UNKNOWN_PEAK_POWER_TIME 0xffff } __attribute__((packed)); struct usb_pd_cap_provider_port_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; __u8 bReserved1; __u8 bmCapabilities; /* port will oerate under: */ #define USB_PD_CAP_PROVIDER_BC (1 << 0) /* BC */ #define USB_PD_CAP_PROVIDER_PD (1 << 1) /* PD */ #define USB_PD_CAP_PROVIDER_TYPE_C (1 << 2) /* USB Type-C Current */ __u8 bNumOfPDObjects; __u8 bReserved2; __le32 wPowerDataObject[]; } __attribute__((packed)); /* * Precision time measurement capability descriptor: advertised by devices and * hubs that support PTM */ #define USB_PTM_CAP_TYPE 0xb struct usb_ptm_cap_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bDevCapabilityType; } __attribute__((packed)); #define USB_DT_USB_PTM_ID_SIZE 3 /* * The size of the descriptor for the Sublink Speed Attribute Count * (SSAC) specified in bmAttributes[4:0]. SSAC is zero-based */ #define USB_DT_USB_SSP_CAP_SIZE(ssac) (12 + (ssac + 1) * 4) /*-------------------------------------------------------------------------*/ /* USB_DT_WIRELESS_ENDPOINT_COMP: companion descriptor associated with * each endpoint descriptor for a wireless device */ struct usb_wireless_ep_comp_descriptor { __u8 bLength; __u8 bDescriptorType; __u8 bMaxBurst; __u8 bMaxSequence; __le16 wMaxStreamDelay; __le16 wOverTheAirPacketSize; __u8 bOverTheAirInterval; __u8 bmCompAttributes; #define USB_ENDPOINT_SWITCH_MASK 0x03 /* in bmCompAttributes */ #define USB_ENDPOINT_SWITCH_NO 0 #define USB_ENDPOINT_SWITCH_SWITCH 1 #define USB_ENDPOINT_SWITCH_SCALE 2 } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB_REQ_SET_HANDSHAKE is a four-way handshake used between a wireless * host and a device for connection set up, mutual authentication, and * exchanging short lived session keys. The handshake depends on a CC. */ struct usb_handshake { __u8 bMessageNumber; __u8 bStatus; __u8 tTKID[3]; __u8 bReserved; __u8 CDID[16]; __u8 nonce[16]; __u8 MIC[8]; } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB_REQ_SET_CONNECTION modifies or revokes a connection context (CC). * A CC may also be set up using non-wireless secure channels (including * wired USB!), and some devices may support CCs with multiple hosts. */ struct usb_connection_context { __u8 CHID[16]; /* persistent host id */ __u8 CDID[16]; /* device id (unique w/in host context) */ __u8 CK[16]; /* connection key */ } __attribute__((packed)); /*-------------------------------------------------------------------------*/ /* USB 2.0 defines three speeds, here's how Linux identifies them */ enum usb_device_speed { USB_SPEED_UNKNOWN = 0, /* enumerating */ USB_SPEED_LOW, USB_SPEED_FULL, /* usb 1.1 */ USB_SPEED_HIGH, /* usb 2.0 */ USB_SPEED_WIRELESS, /* wireless (usb 2.5) */ USB_SPEED_SUPER, /* usb 3.0 */ USB_SPEED_SUPER_PLUS, /* usb 3.1 */ }; enum usb_device_state { /* NOTATTACHED isn't in the USB spec, and this state acts * the same as ATTACHED ... but it's clearer this way. */ USB_STATE_NOTATTACHED = 0, /* chapter 9 and authentication (wireless) device states */ USB_STATE_ATTACHED, USB_STATE_POWERED, /* wired */ USB_STATE_RECONNECTING, /* auth */ USB_STATE_UNAUTHENTICATED, /* auth */ USB_STATE_DEFAULT, /* limited function */ USB_STATE_ADDRESS, USB_STATE_CONFIGURED, /* most functions */ USB_STATE_SUSPENDED /* NOTE: there are actually four different SUSPENDED * states, returning to POWERED, DEFAULT, ADDRESS, or * CONFIGURED respectively when SOF tokens flow again. * At this level there's no difference between L1 and L2 * suspend states. (L2 being original USB 1.1 suspend.) */ }; enum usb3_link_state { USB3_LPM_U0 = 0, USB3_LPM_U1, USB3_LPM_U2, USB3_LPM_U3 }; /* * A U1 timeout of 0x0 means the parent hub will reject any transitions to U1. * 0xff means the parent hub will accept transitions to U1, but will not * initiate a transition. * * A U1 timeout of 0x1 to 0x7F also causes the hub to initiate a transition to * U1 after that many microseconds. Timeouts of 0x80 to 0xFE are reserved * values. * * A U2 timeout of 0x0 means the parent hub will reject any transitions to U2. * 0xff means the parent hub will accept transitions to U2, but will not * initiate a transition. * * A U2 timeout of 0x1 to 0xFE also causes the hub to initiate a transition to * U2 after N*256 microseconds. Therefore a U2 timeout value of 0x1 means a U2 * idle timer of 256 microseconds, 0x2 means 512 microseconds, 0xFE means * 65.024ms. */ #define USB3_LPM_DISABLED 0x0 #define USB3_LPM_U1_MAX_TIMEOUT 0x7F #define USB3_LPM_U2_MAX_TIMEOUT 0xFE #define USB3_LPM_DEVICE_INITIATED 0xFF struct usb_set_sel_req { __u8 u1_sel; __u8 u1_pel; __le16 u2_sel; __le16 u2_pel; } __attribute__ ((packed)); /* * The Set System Exit Latency control transfer provides one byte each for * U1 SEL and U1 PEL, so the max exit latency is 0xFF. U2 SEL and U2 PEL each * are two bytes long. */ #define USB3_LPM_MAX_U1_SEL_PEL 0xFF #define USB3_LPM_MAX_U2_SEL_PEL 0xFFFF /*-------------------------------------------------------------------------*/ /* * As per USB compliance update, a device that is actively drawing * more than 100mA from USB must report itself as bus-powered in * the GetStatus(DEVICE) call. * http://compliance.usb.org/index.asp?UpdateFile=Electrical&Format=Standard#34 */ #define USB_SELF_POWER_VBUS_MAX_DRAW 100 #endif /* __LINUX_USB_CH9_H */ linux/hpet.h000064400000001347151027430560007024 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __HPET__ #define __HPET__ struct hpet_info { unsigned long hi_ireqfreq; /* Hz */ unsigned long hi_flags; /* information */ unsigned short hi_hpet; unsigned short hi_timer; }; #define HPET_INFO_PERIODIC 0x0010 /* periodic-capable comparator */ #define HPET_IE_ON _IO('h', 0x01) /* interrupt on */ #define HPET_IE_OFF _IO('h', 0x02) /* interrupt off */ #define HPET_INFO _IOR('h', 0x03, struct hpet_info) #define HPET_EPI _IO('h', 0x04) /* enable periodic */ #define HPET_DPI _IO('h', 0x05) /* disable periodic */ #define HPET_IRQFREQ _IOW('h', 0x6, unsigned long) /* IRQFREQ usec */ #define MAX_HPET_TBS 8 /* maximum hpet timer blocks */ #endif /* __HPET__ */ linux/rds.h000064400000022125151027430560006651 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR Linux-OpenIB) */ /* * Copyright (c) 2008 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #ifndef _LINUX_RDS_H #define _LINUX_RDS_H #include #include /* For __kernel_sockaddr_storage. */ #define RDS_IB_ABI_VERSION 0x301 #define SOL_RDS 276 /* * setsockopt/getsockopt for SOL_RDS */ #define RDS_CANCEL_SENT_TO 1 #define RDS_GET_MR 2 #define RDS_FREE_MR 3 /* deprecated: RDS_BARRIER 4 */ #define RDS_RECVERR 5 #define RDS_CONG_MONITOR 6 #define RDS_GET_MR_FOR_DEST 7 #define SO_RDS_TRANSPORT 8 /* Socket option to tap receive path latency * SO_RDS: SO_RDS_MSG_RXPATH_LATENCY * Format used struct rds_rx_trace_so */ #define SO_RDS_MSG_RXPATH_LATENCY 10 /* supported values for SO_RDS_TRANSPORT */ #define RDS_TRANS_IB 0 #define RDS_TRANS_IWARP 1 #define RDS_TRANS_TCP 2 #define RDS_TRANS_COUNT 3 #define RDS_TRANS_NONE (~0) /* * Control message types for SOL_RDS. * * CMSG_RDMA_ARGS (sendmsg) * Request a RDMA transfer to/from the specified * memory ranges. * The cmsg_data is a struct rds_rdma_args. * RDS_CMSG_RDMA_DEST (recvmsg, sendmsg) * Kernel informs application about intended * source/destination of a RDMA transfer * RDS_CMSG_RDMA_MAP (sendmsg) * Application asks kernel to map the given * memory range into a IB MR, and send the * R_Key along in an RDS extension header. * The cmsg_data is a struct rds_get_mr_args, * the same as for the GET_MR setsockopt. * RDS_CMSG_RDMA_STATUS (recvmsg) * Returns the status of a completed RDMA operation. * RDS_CMSG_RXPATH_LATENCY(recvmsg) * Returns rds message latencies in various stages of receive * path in nS. Its set per socket using SO_RDS_MSG_RXPATH_LATENCY * socket option. Legitimate points are defined in * enum rds_message_rxpath_latency. More points can be added in * future. CSMG format is struct rds_cmsg_rx_trace. */ #define RDS_CMSG_RDMA_ARGS 1 #define RDS_CMSG_RDMA_DEST 2 #define RDS_CMSG_RDMA_MAP 3 #define RDS_CMSG_RDMA_STATUS 4 #define RDS_CMSG_CONG_UPDATE 5 #define RDS_CMSG_ATOMIC_FADD 6 #define RDS_CMSG_ATOMIC_CSWP 7 #define RDS_CMSG_MASKED_ATOMIC_FADD 8 #define RDS_CMSG_MASKED_ATOMIC_CSWP 9 #define RDS_CMSG_RXPATH_LATENCY 11 #define RDS_CMSG_ZCOPY_COOKIE 12 #define RDS_CMSG_ZCOPY_COMPLETION 13 #define RDS_INFO_FIRST 10000 #define RDS_INFO_COUNTERS 10000 #define RDS_INFO_CONNECTIONS 10001 /* 10002 aka RDS_INFO_FLOWS is deprecated */ #define RDS_INFO_SEND_MESSAGES 10003 #define RDS_INFO_RETRANS_MESSAGES 10004 #define RDS_INFO_RECV_MESSAGES 10005 #define RDS_INFO_SOCKETS 10006 #define RDS_INFO_TCP_SOCKETS 10007 #define RDS_INFO_IB_CONNECTIONS 10008 #define RDS_INFO_CONNECTION_STATS 10009 #define RDS_INFO_IWARP_CONNECTIONS 10010 #define RDS_INFO_LAST 10010 struct rds_info_counter { __u8 name[32]; __u64 value; } __attribute__((packed)); #define RDS_INFO_CONNECTION_FLAG_SENDING 0x01 #define RDS_INFO_CONNECTION_FLAG_CONNECTING 0x02 #define RDS_INFO_CONNECTION_FLAG_CONNECTED 0x04 #define TRANSNAMSIZ 16 struct rds_info_connection { __u64 next_tx_seq; __u64 next_rx_seq; __be32 laddr; __be32 faddr; __u8 transport[TRANSNAMSIZ]; /* null term ascii */ __u8 flags; } __attribute__((packed)); #define RDS_INFO_MESSAGE_FLAG_ACK 0x01 #define RDS_INFO_MESSAGE_FLAG_FAST_ACK 0x02 struct rds_info_message { __u64 seq; __u32 len; __be32 laddr; __be32 faddr; __be16 lport; __be16 fport; __u8 flags; } __attribute__((packed)); struct rds_info_socket { __u32 sndbuf; __be32 bound_addr; __be32 connected_addr; __be16 bound_port; __be16 connected_port; __u32 rcvbuf; __u64 inum; } __attribute__((packed)); struct rds_info_tcp_socket { __be32 local_addr; __be16 local_port; __be32 peer_addr; __be16 peer_port; __u64 hdr_rem; __u64 data_rem; __u32 last_sent_nxt; __u32 last_expected_una; __u32 last_seen_una; } __attribute__((packed)); #define RDS_IB_GID_LEN 16 struct rds_info_rdma_connection { __be32 src_addr; __be32 dst_addr; __u8 src_gid[RDS_IB_GID_LEN]; __u8 dst_gid[RDS_IB_GID_LEN]; __u32 max_send_wr; __u32 max_recv_wr; __u32 max_send_sge; __u32 rdma_mr_max; __u32 rdma_mr_size; }; /* RDS message Receive Path Latency points */ enum rds_message_rxpath_latency { RDS_MSG_RX_HDR_TO_DGRAM_START = 0, RDS_MSG_RX_DGRAM_REASSEMBLE, RDS_MSG_RX_DGRAM_DELIVERED, RDS_MSG_RX_DGRAM_TRACE_MAX }; struct rds_rx_trace_so { __u8 rx_traces; __u8 rx_trace_pos[RDS_MSG_RX_DGRAM_TRACE_MAX]; }; struct rds_cmsg_rx_trace { __u8 rx_traces; __u8 rx_trace_pos[RDS_MSG_RX_DGRAM_TRACE_MAX]; __u64 rx_trace[RDS_MSG_RX_DGRAM_TRACE_MAX]; }; /* * Congestion monitoring. * Congestion control in RDS happens at the host connection * level by exchanging a bitmap marking congested ports. * By default, a process sleeping in poll() is always woken * up when the congestion map is updated. * With explicit monitoring, an application can have more * fine-grained control. * The application installs a 64bit mask value in the socket, * where each bit corresponds to a group of ports. * When a congestion update arrives, RDS checks the set of * ports that are now uncongested against the list bit mask * installed in the socket, and if they overlap, we queue a * cong_notification on the socket. * * To install the congestion monitor bitmask, use RDS_CONG_MONITOR * with the 64bit mask. * Congestion updates are received via RDS_CMSG_CONG_UPDATE * control messages. * * The correspondence between bits and ports is * 1 << (portnum % 64) */ #define RDS_CONG_MONITOR_SIZE 64 #define RDS_CONG_MONITOR_BIT(port) (((unsigned int) port) % RDS_CONG_MONITOR_SIZE) #define RDS_CONG_MONITOR_MASK(port) (1ULL << RDS_CONG_MONITOR_BIT(port)) /* * RDMA related types */ /* * This encapsulates a remote memory location. * In the current implementation, it contains the R_Key * of the remote memory region, and the offset into it * (so that the application does not have to worry about * alignment). */ typedef __u64 rds_rdma_cookie_t; struct rds_iovec { __u64 addr; __u64 bytes; }; struct rds_get_mr_args { struct rds_iovec vec; __u64 cookie_addr; __u64 flags; }; struct rds_get_mr_for_dest_args { struct __kernel_sockaddr_storage dest_addr; struct rds_iovec vec; __u64 cookie_addr; __u64 flags; }; struct rds_free_mr_args { rds_rdma_cookie_t cookie; __u64 flags; }; struct rds_rdma_args { rds_rdma_cookie_t cookie; struct rds_iovec remote_vec; __u64 local_vec_addr; __u64 nr_local; __u64 flags; __u64 user_token; }; struct rds_atomic_args { rds_rdma_cookie_t cookie; __u64 local_addr; __u64 remote_addr; union { struct { __u64 compare; __u64 swap; } cswp; struct { __u64 add; } fadd; struct { __u64 compare; __u64 swap; __u64 compare_mask; __u64 swap_mask; } m_cswp; struct { __u64 add; __u64 nocarry_mask; } m_fadd; }; __u64 flags; __u64 user_token; }; struct rds_rdma_notify { __u64 user_token; __s32 status; }; #define RDS_RDMA_SUCCESS 0 #define RDS_RDMA_REMOTE_ERROR 1 #define RDS_RDMA_CANCELED 2 #define RDS_RDMA_DROPPED 3 #define RDS_RDMA_OTHER_ERROR 4 #define RDS_MAX_ZCOOKIES 8 struct rds_zcopy_cookies { __u32 num; __u32 cookies[RDS_MAX_ZCOOKIES]; }; /* * Common set of flags for all RDMA related structs */ #define RDS_RDMA_READWRITE 0x0001 #define RDS_RDMA_FENCE 0x0002 /* use FENCE for immediate send */ #define RDS_RDMA_INVALIDATE 0x0004 /* invalidate R_Key after freeing MR */ #define RDS_RDMA_USE_ONCE 0x0008 /* free MR after use */ #define RDS_RDMA_DONTWAIT 0x0010 /* Don't wait in SET_BARRIER */ #define RDS_RDMA_NOTIFY_ME 0x0020 /* Notify when operation completes */ #define RDS_RDMA_SILENT 0x0040 /* Do not interrupt remote */ #endif /* IB_RDS_H */ linux/map_to_7segment.h000064400000016123151027430560011152 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2005 Henk Vergonet * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MAP_TO_7SEGMENT_H #define MAP_TO_7SEGMENT_H /* This file provides translation primitives and tables for the conversion * of (ASCII) characters to a 7-segments notation. * * The 7 segment's wikipedia notation below is used as standard. * See: http://en.wikipedia.org/wiki/Seven_segment_display * * Notation: +-a-+ * f b * +-g-+ * e c * +-d-+ * * Usage: * * Register a map variable, and fill it with a character set: * static SEG7_DEFAULT_MAP(map_seg7); * * * Then use for conversion: * seg7 = map_to_seg7(&map_seg7, some_char); * ... * * In device drivers it is recommended, if required, to make the char map * accessible via the sysfs interface using the following scheme: * * static ssize_t show_map(struct device *dev, char *buf) { * memcpy(buf, &map_seg7, sizeof(map_seg7)); * return sizeof(map_seg7); * } * static ssize_t store_map(struct device *dev, const char *buf, size_t cnt) { * if(cnt != sizeof(map_seg7)) * return -EINVAL; * memcpy(&map_seg7, buf, cnt); * return cnt; * } * static DEVICE_ATTR(map_seg7, PERMS_RW, show_map, store_map); * * History: * 2005-05-31 RFC linux-kernel@vger.kernel.org */ #include #define BIT_SEG7_A 0 #define BIT_SEG7_B 1 #define BIT_SEG7_C 2 #define BIT_SEG7_D 3 #define BIT_SEG7_E 4 #define BIT_SEG7_F 5 #define BIT_SEG7_G 6 #define BIT_SEG7_RESERVED 7 struct seg7_conversion_map { unsigned char table[128]; }; static __inline__ int map_to_seg7(struct seg7_conversion_map *map, int c) { return c >= 0 && c < sizeof(map->table) ? map->table[c] : -EINVAL; } #define SEG7_CONVERSION_MAP(_name, _map) \ struct seg7_conversion_map _name = { .table = { _map } } /* * It is recommended to use a facility that allows user space to redefine * custom character sets for LCD devices. Please use a sysfs interface * as described above. */ #define MAP_TO_SEG7_SYSFS_FILE "map_seg7" /******************************************************************************* * ASCII conversion table ******************************************************************************/ #define _SEG7(l,a,b,c,d,e,f,g) \ ( a<',1,1,0,0,0,0,1), _SEG7('?',1,1,1,0,0,1,0),\ _SEG7('@',1,1,0,1,1,1,1), #define _MAP_65_90_ASCII_SEG7_ALPHA_UPPR \ _SEG7('A',1,1,1,0,1,1,1), _SEG7('B',1,1,1,1,1,1,1), _SEG7('C',1,0,0,1,1,1,0),\ _SEG7('D',1,1,1,1,1,1,0), _SEG7('E',1,0,0,1,1,1,1), _SEG7('F',1,0,0,0,1,1,1),\ _SEG7('G',1,1,1,1,0,1,1), _SEG7('H',0,1,1,0,1,1,1), _SEG7('I',0,1,1,0,0,0,0),\ _SEG7('J',0,1,1,1,0,0,0), _SEG7('K',0,1,1,0,1,1,1), _SEG7('L',0,0,0,1,1,1,0),\ _SEG7('M',1,1,1,0,1,1,0), _SEG7('N',1,1,1,0,1,1,0), _SEG7('O',1,1,1,1,1,1,0),\ _SEG7('P',1,1,0,0,1,1,1), _SEG7('Q',1,1,1,1,1,1,0), _SEG7('R',1,1,1,0,1,1,1),\ _SEG7('S',1,0,1,1,0,1,1), _SEG7('T',0,0,0,1,1,1,1), _SEG7('U',0,1,1,1,1,1,0),\ _SEG7('V',0,1,1,1,1,1,0), _SEG7('W',0,1,1,1,1,1,1), _SEG7('X',0,1,1,0,1,1,1),\ _SEG7('Y',0,1,1,0,0,1,1), _SEG7('Z',1,1,0,1,1,0,1), #define _MAP_91_96_ASCII_SEG7_SYMBOL \ _SEG7('[',1,0,0,1,1,1,0), _SEG7('\\',0,0,1,0,0,1,1),_SEG7(']',1,1,1,1,0,0,0),\ _SEG7('^',1,1,0,0,0,1,0), _SEG7('_',0,0,0,1,0,0,0), _SEG7('`',0,1,0,0,0,0,0), #define _MAP_97_122_ASCII_SEG7_ALPHA_LOWER \ _SEG7('A',1,1,1,0,1,1,1), _SEG7('b',0,0,1,1,1,1,1), _SEG7('c',0,0,0,1,1,0,1),\ _SEG7('d',0,1,1,1,1,0,1), _SEG7('E',1,0,0,1,1,1,1), _SEG7('F',1,0,0,0,1,1,1),\ _SEG7('G',1,1,1,1,0,1,1), _SEG7('h',0,0,1,0,1,1,1), _SEG7('i',0,0,1,0,0,0,0),\ _SEG7('j',0,0,1,1,0,0,0), _SEG7('k',0,0,1,0,1,1,1), _SEG7('L',0,0,0,1,1,1,0),\ _SEG7('M',1,1,1,0,1,1,0), _SEG7('n',0,0,1,0,1,0,1), _SEG7('o',0,0,1,1,1,0,1),\ _SEG7('P',1,1,0,0,1,1,1), _SEG7('q',1,1,1,0,0,1,1), _SEG7('r',0,0,0,0,1,0,1),\ _SEG7('S',1,0,1,1,0,1,1), _SEG7('T',0,0,0,1,1,1,1), _SEG7('u',0,0,1,1,1,0,0),\ _SEG7('v',0,0,1,1,1,0,0), _SEG7('W',0,1,1,1,1,1,1), _SEG7('X',0,1,1,0,1,1,1),\ _SEG7('y',0,1,1,1,0,1,1), _SEG7('Z',1,1,0,1,1,0,1), #define _MAP_123_126_ASCII_SEG7_SYMBOL \ _SEG7('{',1,0,0,1,1,1,0), _SEG7('|',0,0,0,0,1,1,0), _SEG7('}',1,1,1,1,0,0,0),\ _SEG7('~',1,0,0,0,0,0,0), /* Maps */ /* This set tries to map as close as possible to the visible characteristics * of the ASCII symbol, lowercase and uppercase letters may differ in * presentation on the display. */ #define MAP_ASCII7SEG_ALPHANUM \ _MAP_0_32_ASCII_SEG7_NON_PRINTABLE \ _MAP_33_47_ASCII_SEG7_SYMBOL \ _MAP_48_57_ASCII_SEG7_NUMERIC \ _MAP_58_64_ASCII_SEG7_SYMBOL \ _MAP_65_90_ASCII_SEG7_ALPHA_UPPR \ _MAP_91_96_ASCII_SEG7_SYMBOL \ _MAP_97_122_ASCII_SEG7_ALPHA_LOWER \ _MAP_123_126_ASCII_SEG7_SYMBOL /* This set tries to map as close as possible to the symbolic characteristics * of the ASCII character for maximum discrimination. * For now this means all alpha chars are in lower case representations. * (This for example facilitates the use of hex numbers with uppercase input.) */ #define MAP_ASCII7SEG_ALPHANUM_LC \ _MAP_0_32_ASCII_SEG7_NON_PRINTABLE \ _MAP_33_47_ASCII_SEG7_SYMBOL \ _MAP_48_57_ASCII_SEG7_NUMERIC \ _MAP_58_64_ASCII_SEG7_SYMBOL \ _MAP_97_122_ASCII_SEG7_ALPHA_LOWER \ _MAP_91_96_ASCII_SEG7_SYMBOL \ _MAP_97_122_ASCII_SEG7_ALPHA_LOWER \ _MAP_123_126_ASCII_SEG7_SYMBOL #define SEG7_DEFAULT_MAP(_name) \ SEG7_CONVERSION_MAP(_name,MAP_ASCII7SEG_ALPHANUM) #endif /* MAP_TO_7SEGMENT_H */ linux/ipv6_route.h000064400000003564151027430560010171 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Linux INET6 implementation * * Authors: * Pedro Roque * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IPV6_ROUTE_H #define _LINUX_IPV6_ROUTE_H #include #include /* For struct in6_addr. */ #define RTF_DEFAULT 0x00010000 /* default - learned via ND */ #define RTF_ALLONLINK 0x00020000 /* (deprecated and will be removed) fallback, no routers on link */ #define RTF_ADDRCONF 0x00040000 /* addrconf route - RA */ #define RTF_PREFIX_RT 0x00080000 /* A prefix only route - RA */ #define RTF_ANYCAST 0x00100000 /* Anycast */ #define RTF_NONEXTHOP 0x00200000 /* route with no nexthop */ #define RTF_EXPIRES 0x00400000 #define RTF_ROUTEINFO 0x00800000 /* route information - RA */ #define RTF_CACHE 0x01000000 /* read-only: can not be set by user */ #define RTF_FLOW 0x02000000 /* flow significant route */ #define RTF_POLICY 0x04000000 /* policy route */ #define RTF_PREF(pref) ((pref) << 27) #define RTF_PREF_MASK 0x18000000 #define RTF_PCPU 0x40000000 /* read-only: can not be set by user */ #define RTF_LOCAL 0x80000000 struct in6_rtmsg { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; __u32 rtmsg_type; __u16 rtmsg_dst_len; __u16 rtmsg_src_len; __u32 rtmsg_metric; unsigned long rtmsg_info; __u32 rtmsg_flags; int rtmsg_ifindex; }; #define RTMSG_NEWDEVICE 0x11 #define RTMSG_DELDEVICE 0x12 #define RTMSG_NEWROUTE 0x21 #define RTMSG_DELROUTE 0x22 #define IP6_RT_PRIO_USER 1024 #define IP6_RT_PRIO_ADDRCONF 256 #endif /* _LINUX_IPV6_ROUTE_H */ linux/atmsap.h000064400000011552151027430560007350 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmsap.h - ATM Service Access Point addressing definitions */ /* Written 1995-1999 by Werner Almesberger, EPFL LRC/ICA */ #ifndef _LINUX_ATMSAP_H #define _LINUX_ATMSAP_H #include /* * BEGIN_xx and END_xx markers are used for automatic generation of * documentation. Do not change them. */ /* * Layer 2 protocol identifiers */ /* BEGIN_L2 */ #define ATM_L2_NONE 0 /* L2 not specified */ #define ATM_L2_ISO1745 0x01 /* Basic mode ISO 1745 */ #define ATM_L2_Q291 0x02 /* ITU-T Q.291 (Rec. I.441) */ #define ATM_L2_X25_LL 0x06 /* ITU-T X.25, link layer */ #define ATM_L2_X25_ML 0x07 /* ITU-T X.25, multilink */ #define ATM_L2_LAPB 0x08 /* Extended LAPB, half-duplex (Rec. T.71) */ #define ATM_L2_HDLC_ARM 0x09 /* HDLC ARM (ISO/IEC 4335) */ #define ATM_L2_HDLC_NRM 0x0a /* HDLC NRM (ISO/IEC 4335) */ #define ATM_L2_HDLC_ABM 0x0b /* HDLC ABM (ISO/IEC 4335) */ #define ATM_L2_ISO8802 0x0c /* LAN LLC (ISO/IEC 8802/2) */ #define ATM_L2_X75 0x0d /* ITU-T X.75, SLP */ #define ATM_L2_Q922 0x0e /* ITU-T Q.922 */ #define ATM_L2_USER 0x10 /* user-specified */ #define ATM_L2_ISO7776 0x11 /* ISO 7776 DTE-DTE */ /* END_L2 */ /* * Layer 3 protocol identifiers */ /* BEGIN_L3 */ #define ATM_L3_NONE 0 /* L3 not specified */ #define ATM_L3_X25 0x06 /* ITU-T X.25, packet layer */ #define ATM_L3_ISO8208 0x07 /* ISO/IEC 8208 */ #define ATM_L3_X223 0x08 /* ITU-T X.223 | ISO/IEC 8878 */ #define ATM_L3_ISO8473 0x09 /* ITU-T X.233 | ISO/IEC 8473 */ #define ATM_L3_T70 0x0a /* ITU-T T.70 minimum network layer */ #define ATM_L3_TR9577 0x0b /* ISO/IEC TR 9577 */ #define ATM_L3_H310 0x0c /* ITU-T Recommendation H.310 */ #define ATM_L3_H321 0x0d /* ITU-T Recommendation H.321 */ #define ATM_L3_USER 0x10 /* user-specified */ /* END_L3 */ /* * High layer identifiers */ /* BEGIN_HL */ #define ATM_HL_NONE 0 /* HL not specified */ #define ATM_HL_ISO 0x01 /* ISO */ #define ATM_HL_USER 0x02 /* user-specific */ #define ATM_HL_HLP 0x03 /* high layer profile - UNI 3.0 only */ #define ATM_HL_VENDOR 0x04 /* vendor-specific application identifier */ /* END_HL */ /* * ITU-T coded mode of operation */ /* BEGIN_IMD */ #define ATM_IMD_NONE 0 /* mode not specified */ #define ATM_IMD_NORMAL 1 /* normal mode of operation */ #define ATM_IMD_EXTENDED 2 /* extended mode of operation */ /* END_IMD */ /* * H.310 code points */ #define ATM_TT_NONE 0 /* terminal type not specified */ #define ATM_TT_RX 1 /* receive only */ #define ATM_TT_TX 2 /* send only */ #define ATM_TT_RXTX 3 /* receive and send */ #define ATM_MC_NONE 0 /* no multiplexing */ #define ATM_MC_TS 1 /* transport stream (TS) */ #define ATM_MC_TS_FEC 2 /* transport stream with forward error corr. */ #define ATM_MC_PS 3 /* program stream (PS) */ #define ATM_MC_PS_FEC 4 /* program stream with forward error corr. */ #define ATM_MC_H221 5 /* ITU-T Rec. H.221 */ /* * SAP structures */ #define ATM_MAX_HLI 8 /* maximum high-layer information length */ struct atm_blli { unsigned char l2_proto; /* layer 2 protocol */ union { struct { unsigned char mode; /* mode of operation (ATM_IMD_xxx), 0 if */ /* absent */ unsigned char window; /* window size (k), 1-127 (0 to omit) */ } itu; /* ITU-T encoding */ unsigned char user; /* user-specified l2 information */ } l2; unsigned char l3_proto; /* layer 3 protocol */ union { struct { unsigned char mode; /* mode of operation (ATM_IMD_xxx), 0 if */ /* absent */ unsigned char def_size; /* default packet size (log2), 4-12 (0 to */ /* omit) */ unsigned char window;/* packet window size, 1-127 (0 to omit) */ } itu; /* ITU-T encoding */ unsigned char user; /* user specified l3 information */ struct { /* if l3_proto = ATM_L3_H310 */ unsigned char term_type; /* terminal type */ unsigned char fw_mpx_cap; /* forward multiplexing capability */ /* only if term_type != ATM_TT_NONE */ unsigned char bw_mpx_cap; /* backward multiplexing capability */ /* only if term_type != ATM_TT_NONE */ } h310; struct { /* if l3_proto = ATM_L3_TR9577 */ unsigned char ipi; /* initial protocol id */ unsigned char snap[5];/* IEEE 802.1 SNAP identifier */ /* (only if ipi == NLPID_IEEE802_1_SNAP) */ } tr9577; } l3; } __ATM_API_ALIGN; struct atm_bhli { unsigned char hl_type; /* high layer information type */ unsigned char hl_length; /* length (only if hl_type == ATM_HL_USER || */ /* hl_type == ATM_HL_ISO) */ unsigned char hl_info[ATM_MAX_HLI];/* high layer information */ }; #define ATM_MAX_BLLI 3 /* maximum number of BLLI elements */ struct atm_sap { struct atm_bhli bhli; /* local SAP, high-layer information */ struct atm_blli blli[ATM_MAX_BLLI] __ATM_API_ALIGN; /* local SAP, low-layer info */ }; static __inline__ int blli_in_use(struct atm_blli blli) { return blli.l2_proto || blli.l3_proto; } #endif linux/if_link.h000064400000074435151027430560007507 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_IF_LINK_H #define _LINUX_IF_LINK_H #include #include /* This struct should be in sync with struct rtnl_link_stats64 */ struct rtnl_link_stats { __u32 rx_packets; /* total packets received */ __u32 tx_packets; /* total packets transmitted */ __u32 rx_bytes; /* total bytes received */ __u32 tx_bytes; /* total bytes transmitted */ __u32 rx_errors; /* bad packets received */ __u32 tx_errors; /* packet transmit problems */ __u32 rx_dropped; /* no space in linux buffers */ __u32 tx_dropped; /* no space available in linux */ __u32 multicast; /* multicast packets received */ __u32 collisions; /* detailed rx_errors: */ __u32 rx_length_errors; __u32 rx_over_errors; /* receiver ring buff overflow */ __u32 rx_crc_errors; /* recved pkt with crc error */ __u32 rx_frame_errors; /* recv'd frame alignment error */ __u32 rx_fifo_errors; /* recv'r fifo overrun */ __u32 rx_missed_errors; /* receiver missed packet */ /* detailed tx_errors */ __u32 tx_aborted_errors; __u32 tx_carrier_errors; __u32 tx_fifo_errors; __u32 tx_heartbeat_errors; __u32 tx_window_errors; /* for cslip etc */ __u32 rx_compressed; __u32 tx_compressed; __u32 rx_nohandler; /* dropped, no handler found */ }; /** * struct rtnl_link_stats64 - The main device statistics structure. * * @rx_packets: Number of good packets received by the interface. * For hardware interfaces counts all good packets received from the device * by the host, including packets which host had to drop at various stages * of processing (even in the driver). * * @tx_packets: Number of packets successfully transmitted. * For hardware interfaces counts packets which host was able to successfully * hand over to the device, which does not necessarily mean that packets * had been successfully transmitted out of the device, only that device * acknowledged it copied them out of host memory. * * @rx_bytes: Number of good received bytes, corresponding to @rx_packets. * * For IEEE 802.3 devices should count the length of Ethernet Frames * excluding the FCS. * * @tx_bytes: Number of good transmitted bytes, corresponding to @tx_packets. * * For IEEE 802.3 devices should count the length of Ethernet Frames * excluding the FCS. * * @rx_errors: Total number of bad packets received on this network device. * This counter must include events counted by @rx_length_errors, * @rx_crc_errors, @rx_frame_errors and other errors not otherwise * counted. * * @tx_errors: Total number of transmit problems. * This counter must include events counter by @tx_aborted_errors, * @tx_carrier_errors, @tx_fifo_errors, @tx_heartbeat_errors, * @tx_window_errors and other errors not otherwise counted. * * @rx_dropped: Number of packets received but not processed, * e.g. due to lack of resources or unsupported protocol. * For hardware interfaces this counter should not include packets * dropped by the device which are counted separately in * @rx_missed_errors (since procfs folds those two counters together). * * @tx_dropped: Number of packets dropped on their way to transmission, * e.g. due to lack of resources. * * @multicast: Multicast packets received. * For hardware interfaces this statistic is commonly calculated * at the device level (unlike @rx_packets) and therefore may include * packets which did not reach the host. * * For IEEE 802.3 devices this counter may be equivalent to: * * - 30.3.1.1.21 aMulticastFramesReceivedOK * * @collisions: Number of collisions during packet transmissions. * * @rx_length_errors: Number of packets dropped due to invalid length. * Part of aggregate "frame" errors in `/proc/net/dev`. * * For IEEE 802.3 devices this counter should be equivalent to a sum * of the following attributes: * * - 30.3.1.1.23 aInRangeLengthErrors * - 30.3.1.1.24 aOutOfRangeLengthField * - 30.3.1.1.25 aFrameTooLongErrors * * @rx_over_errors: Receiver FIFO overflow event counter. * * Historically the count of overflow events. Such events may be * reported in the receive descriptors or via interrupts, and may * not correspond one-to-one with dropped packets. * * The recommended interpretation for high speed interfaces is - * number of packets dropped because they did not fit into buffers * provided by the host, e.g. packets larger than MTU or next buffer * in the ring was not available for a scatter transfer. * * Part of aggregate "frame" errors in `/proc/net/dev`. * * This statistics was historically used interchangeably with * @rx_fifo_errors. * * This statistic corresponds to hardware events and is not commonly used * on software devices. * * @rx_crc_errors: Number of packets received with a CRC error. * Part of aggregate "frame" errors in `/proc/net/dev`. * * For IEEE 802.3 devices this counter must be equivalent to: * * - 30.3.1.1.6 aFrameCheckSequenceErrors * * @rx_frame_errors: Receiver frame alignment errors. * Part of aggregate "frame" errors in `/proc/net/dev`. * * For IEEE 802.3 devices this counter should be equivalent to: * * - 30.3.1.1.7 aAlignmentErrors * * @rx_fifo_errors: Receiver FIFO error counter. * * Historically the count of overflow events. Those events may be * reported in the receive descriptors or via interrupts, and may * not correspond one-to-one with dropped packets. * * This statistics was used interchangeably with @rx_over_errors. * Not recommended for use in drivers for high speed interfaces. * * This statistic is used on software devices, e.g. to count software * packet queue overflow (can) or sequencing errors (GRE). * * @rx_missed_errors: Count of packets missed by the host. * Folded into the "drop" counter in `/proc/net/dev`. * * Counts number of packets dropped by the device due to lack * of buffer space. This usually indicates that the host interface * is slower than the network interface, or host is not keeping up * with the receive packet rate. * * This statistic corresponds to hardware events and is not used * on software devices. * * @tx_aborted_errors: * Part of aggregate "carrier" errors in `/proc/net/dev`. * For IEEE 802.3 devices capable of half-duplex operation this counter * must be equivalent to: * * - 30.3.1.1.11 aFramesAbortedDueToXSColls * * High speed interfaces may use this counter as a general device * discard counter. * * @tx_carrier_errors: Number of frame transmission errors due to loss * of carrier during transmission. * Part of aggregate "carrier" errors in `/proc/net/dev`. * * For IEEE 802.3 devices this counter must be equivalent to: * * - 30.3.1.1.13 aCarrierSenseErrors * * @tx_fifo_errors: Number of frame transmission errors due to device * FIFO underrun / underflow. This condition occurs when the device * begins transmission of a frame but is unable to deliver the * entire frame to the transmitter in time for transmission. * Part of aggregate "carrier" errors in `/proc/net/dev`. * * @tx_heartbeat_errors: Number of Heartbeat / SQE Test errors for * old half-duplex Ethernet. * Part of aggregate "carrier" errors in `/proc/net/dev`. * * For IEEE 802.3 devices possibly equivalent to: * * - 30.3.2.1.4 aSQETestErrors * * @tx_window_errors: Number of frame transmission errors due * to late collisions (for Ethernet - after the first 64B of transmission). * Part of aggregate "carrier" errors in `/proc/net/dev`. * * For IEEE 802.3 devices this counter must be equivalent to: * * - 30.3.1.1.10 aLateCollisions * * @rx_compressed: Number of correctly received compressed packets. * This counters is only meaningful for interfaces which support * packet compression (e.g. CSLIP, PPP). * * @tx_compressed: Number of transmitted compressed packets. * This counters is only meaningful for interfaces which support * packet compression (e.g. CSLIP, PPP). * * @rx_nohandler: Number of packets received on the interface * but dropped by the networking stack because the device is * not designated to receive packets (e.g. backup link in a bond). */ struct rtnl_link_stats64 { __u64 rx_packets; __u64 tx_packets; __u64 rx_bytes; __u64 tx_bytes; __u64 rx_errors; __u64 tx_errors; __u64 rx_dropped; __u64 tx_dropped; __u64 multicast; __u64 collisions; /* detailed rx_errors: */ __u64 rx_length_errors; __u64 rx_over_errors; __u64 rx_crc_errors; __u64 rx_frame_errors; __u64 rx_fifo_errors; __u64 rx_missed_errors; /* detailed tx_errors */ __u64 tx_aborted_errors; __u64 tx_carrier_errors; __u64 tx_fifo_errors; __u64 tx_heartbeat_errors; __u64 tx_window_errors; /* for cslip etc */ __u64 rx_compressed; __u64 tx_compressed; __u64 rx_nohandler; }; /* The struct should be in sync with struct ifmap */ struct rtnl_link_ifmap { __u64 mem_start; __u64 mem_end; __u64 base_addr; __u16 irq; __u8 dma; __u8 port; }; /* * IFLA_AF_SPEC * Contains nested attributes for address family specific attributes. * Each address family may create a attribute with the address family * number as type and create its own attribute structure in it. * * Example: * [IFLA_AF_SPEC] = { * [AF_INET] = { * [IFLA_INET_CONF] = ..., * }, * [AF_INET6] = { * [IFLA_INET6_FLAGS] = ..., * [IFLA_INET6_CONF] = ..., * } * } */ enum { IFLA_UNSPEC, IFLA_ADDRESS, IFLA_BROADCAST, IFLA_IFNAME, IFLA_MTU, IFLA_LINK, IFLA_QDISC, IFLA_STATS, IFLA_COST, #define IFLA_COST IFLA_COST IFLA_PRIORITY, #define IFLA_PRIORITY IFLA_PRIORITY IFLA_MASTER, #define IFLA_MASTER IFLA_MASTER IFLA_WIRELESS, /* Wireless Extension event - see wireless.h */ #define IFLA_WIRELESS IFLA_WIRELESS IFLA_PROTINFO, /* Protocol specific information for a link */ #define IFLA_PROTINFO IFLA_PROTINFO IFLA_TXQLEN, #define IFLA_TXQLEN IFLA_TXQLEN IFLA_MAP, #define IFLA_MAP IFLA_MAP IFLA_WEIGHT, #define IFLA_WEIGHT IFLA_WEIGHT IFLA_OPERSTATE, IFLA_LINKMODE, IFLA_LINKINFO, #define IFLA_LINKINFO IFLA_LINKINFO IFLA_NET_NS_PID, IFLA_IFALIAS, IFLA_NUM_VF, /* Number of VFs if device is SR-IOV PF */ IFLA_VFINFO_LIST, IFLA_STATS64, IFLA_VF_PORTS, IFLA_PORT_SELF, IFLA_AF_SPEC, IFLA_GROUP, /* Group the device belongs to */ IFLA_NET_NS_FD, IFLA_EXT_MASK, /* Extended info mask, VFs, etc */ IFLA_PROMISCUITY, /* Promiscuity count: > 0 means acts PROMISC */ #define IFLA_PROMISCUITY IFLA_PROMISCUITY IFLA_NUM_TX_QUEUES, IFLA_NUM_RX_QUEUES, IFLA_CARRIER, IFLA_PHYS_PORT_ID, IFLA_CARRIER_CHANGES, IFLA_PHYS_SWITCH_ID, IFLA_LINK_NETNSID, IFLA_PHYS_PORT_NAME, IFLA_PROTO_DOWN, IFLA_GSO_MAX_SEGS, IFLA_GSO_MAX_SIZE, IFLA_PAD, IFLA_XDP, IFLA_EVENT, IFLA_NEW_NETNSID, IFLA_IF_NETNSID, IFLA_TARGET_NETNSID = IFLA_IF_NETNSID, /* new alias */ IFLA_CARRIER_UP_COUNT, IFLA_CARRIER_DOWN_COUNT, IFLA_NEW_IFINDEX, IFLA_MIN_MTU, IFLA_MAX_MTU, IFLA_PROP_LIST, IFLA_ALT_IFNAME, /* Alternative ifname */ IFLA_PERM_ADDRESS, __RH_RESERVED_IFLA_PROTO_DOWN_REASON, /* device (sysfs) name as parent, used instead * of IFLA_LINK where there's no parent netdev */ IFLA_PARENT_DEV_NAME, IFLA_PARENT_DEV_BUS_NAME, __IFLA_MAX }; #define IFLA_MAX (__IFLA_MAX - 1) /* backwards compatibility for userspace */ #define IFLA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ifinfomsg)))) #define IFLA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ifinfomsg)) enum { IFLA_INET_UNSPEC, IFLA_INET_CONF, __IFLA_INET_MAX, }; #define IFLA_INET_MAX (__IFLA_INET_MAX - 1) /* ifi_flags. IFF_* flags. The only change is: IFF_LOOPBACK, IFF_BROADCAST and IFF_POINTOPOINT are more not changeable by user. They describe link media characteristics and set by device driver. Comments: - Combination IFF_BROADCAST|IFF_POINTOPOINT is invalid - If neither of these three flags are set; the interface is NBMA. - IFF_MULTICAST does not mean anything special: multicasts can be used on all not-NBMA links. IFF_MULTICAST means that this media uses special encapsulation for multicast frames. Apparently, all IFF_POINTOPOINT and IFF_BROADCAST devices are able to use multicasts too. */ /* IFLA_LINK. For usual devices it is equal ifi_index. If it is a "virtual interface" (f.e. tunnel), ifi_link can point to real physical interface (f.e. for bandwidth calculations), or maybe 0, what means, that real media is unknown (usual for IPIP tunnels, when route to endpoint is allowed to change) */ /* Subtype attributes for IFLA_PROTINFO */ enum { IFLA_INET6_UNSPEC, IFLA_INET6_FLAGS, /* link flags */ IFLA_INET6_CONF, /* sysctl parameters */ IFLA_INET6_STATS, /* statistics */ IFLA_INET6_MCAST, /* MC things. What of them? */ IFLA_INET6_CACHEINFO, /* time values and max reasm size */ IFLA_INET6_ICMP6STATS, /* statistics (icmpv6) */ IFLA_INET6_TOKEN, /* device token */ IFLA_INET6_ADDR_GEN_MODE, /* implicit address generator mode */ __IFLA_INET6_MAX }; #define IFLA_INET6_MAX (__IFLA_INET6_MAX - 1) enum in6_addr_gen_mode { IN6_ADDR_GEN_MODE_EUI64, IN6_ADDR_GEN_MODE_NONE, IN6_ADDR_GEN_MODE_STABLE_PRIVACY, IN6_ADDR_GEN_MODE_RANDOM, }; /* Bridge section */ enum { IFLA_BR_UNSPEC, IFLA_BR_FORWARD_DELAY, IFLA_BR_HELLO_TIME, IFLA_BR_MAX_AGE, IFLA_BR_AGEING_TIME, IFLA_BR_STP_STATE, IFLA_BR_PRIORITY, IFLA_BR_VLAN_FILTERING, IFLA_BR_VLAN_PROTOCOL, IFLA_BR_GROUP_FWD_MASK, IFLA_BR_ROOT_ID, IFLA_BR_BRIDGE_ID, IFLA_BR_ROOT_PORT, IFLA_BR_ROOT_PATH_COST, IFLA_BR_TOPOLOGY_CHANGE, IFLA_BR_TOPOLOGY_CHANGE_DETECTED, IFLA_BR_HELLO_TIMER, IFLA_BR_TCN_TIMER, IFLA_BR_TOPOLOGY_CHANGE_TIMER, IFLA_BR_GC_TIMER, IFLA_BR_GROUP_ADDR, IFLA_BR_FDB_FLUSH, IFLA_BR_MCAST_ROUTER, IFLA_BR_MCAST_SNOOPING, IFLA_BR_MCAST_QUERY_USE_IFADDR, IFLA_BR_MCAST_QUERIER, IFLA_BR_MCAST_HASH_ELASTICITY, IFLA_BR_MCAST_HASH_MAX, IFLA_BR_MCAST_LAST_MEMBER_CNT, IFLA_BR_MCAST_STARTUP_QUERY_CNT, IFLA_BR_MCAST_LAST_MEMBER_INTVL, IFLA_BR_MCAST_MEMBERSHIP_INTVL, IFLA_BR_MCAST_QUERIER_INTVL, IFLA_BR_MCAST_QUERY_INTVL, IFLA_BR_MCAST_QUERY_RESPONSE_INTVL, IFLA_BR_MCAST_STARTUP_QUERY_INTVL, IFLA_BR_NF_CALL_IPTABLES, IFLA_BR_NF_CALL_IP6TABLES, IFLA_BR_NF_CALL_ARPTABLES, IFLA_BR_VLAN_DEFAULT_PVID, IFLA_BR_PAD, IFLA_BR_VLAN_STATS_ENABLED, IFLA_BR_MCAST_STATS_ENABLED, IFLA_BR_MCAST_IGMP_VERSION, IFLA_BR_MCAST_MLD_VERSION, IFLA_BR_VLAN_STATS_PER_PORT, IFLA_BR_MULTI_BOOLOPT, IFLA_BR_MCAST_QUERIER_STATE, __IFLA_BR_MAX, }; #define IFLA_BR_MAX (__IFLA_BR_MAX - 1) struct ifla_bridge_id { __u8 prio[2]; __u8 addr[6]; /* ETH_ALEN */ }; enum { BRIDGE_MODE_UNSPEC, BRIDGE_MODE_HAIRPIN, }; enum { IFLA_BRPORT_UNSPEC, IFLA_BRPORT_STATE, /* Spanning tree state */ IFLA_BRPORT_PRIORITY, /* " priority */ IFLA_BRPORT_COST, /* " cost */ IFLA_BRPORT_MODE, /* mode (hairpin) */ IFLA_BRPORT_GUARD, /* bpdu guard */ IFLA_BRPORT_PROTECT, /* root port protection */ IFLA_BRPORT_FAST_LEAVE, /* multicast fast leave */ IFLA_BRPORT_LEARNING, /* mac learning */ IFLA_BRPORT_UNICAST_FLOOD, /* flood unicast traffic */ IFLA_BRPORT_PROXYARP, /* proxy ARP */ IFLA_BRPORT_LEARNING_SYNC, /* mac learning sync from device */ IFLA_BRPORT_PROXYARP_WIFI, /* proxy ARP for Wi-Fi */ IFLA_BRPORT_ROOT_ID, /* designated root */ IFLA_BRPORT_BRIDGE_ID, /* designated bridge */ IFLA_BRPORT_DESIGNATED_PORT, IFLA_BRPORT_DESIGNATED_COST, IFLA_BRPORT_ID, IFLA_BRPORT_NO, IFLA_BRPORT_TOPOLOGY_CHANGE_ACK, IFLA_BRPORT_CONFIG_PENDING, IFLA_BRPORT_MESSAGE_AGE_TIMER, IFLA_BRPORT_FORWARD_DELAY_TIMER, IFLA_BRPORT_HOLD_TIMER, IFLA_BRPORT_FLUSH, IFLA_BRPORT_MULTICAST_ROUTER, IFLA_BRPORT_PAD, IFLA_BRPORT_MCAST_FLOOD, IFLA_BRPORT_MCAST_TO_UCAST, IFLA_BRPORT_VLAN_TUNNEL, IFLA_BRPORT_BCAST_FLOOD, IFLA_BRPORT_GROUP_FWD_MASK, IFLA_BRPORT_NEIGH_SUPPRESS, IFLA_BRPORT_ISOLATED, IFLA_BRPORT_BACKUP_PORT, IFLA_BRPORT_MRP_RING_OPEN, IFLA_BRPORT_MRP_IN_OPEN, IFLA_BRPORT_MCAST_EHT_HOSTS_LIMIT, IFLA_BRPORT_MCAST_EHT_HOSTS_CNT, IFLA_BRPORT_LOCKED, __IFLA_BRPORT_MAX }; #define IFLA_BRPORT_MAX (__IFLA_BRPORT_MAX - 1) struct ifla_cacheinfo { __u32 max_reasm_len; __u32 tstamp; /* ipv6InterfaceTable updated timestamp */ __u32 reachable_time; __u32 retrans_time; }; enum { IFLA_INFO_UNSPEC, IFLA_INFO_KIND, IFLA_INFO_DATA, IFLA_INFO_XSTATS, IFLA_INFO_SLAVE_KIND, IFLA_INFO_SLAVE_DATA, __IFLA_INFO_MAX, }; #define IFLA_INFO_MAX (__IFLA_INFO_MAX - 1) /* VLAN section */ enum { IFLA_VLAN_UNSPEC, IFLA_VLAN_ID, IFLA_VLAN_FLAGS, IFLA_VLAN_EGRESS_QOS, IFLA_VLAN_INGRESS_QOS, IFLA_VLAN_PROTOCOL, __IFLA_VLAN_MAX, }; #define IFLA_VLAN_MAX (__IFLA_VLAN_MAX - 1) struct ifla_vlan_flags { __u32 flags; __u32 mask; }; enum { IFLA_VLAN_QOS_UNSPEC, IFLA_VLAN_QOS_MAPPING, __IFLA_VLAN_QOS_MAX }; #define IFLA_VLAN_QOS_MAX (__IFLA_VLAN_QOS_MAX - 1) struct ifla_vlan_qos_mapping { __u32 from; __u32 to; }; /* MACVLAN section */ enum { IFLA_MACVLAN_UNSPEC, IFLA_MACVLAN_MODE, IFLA_MACVLAN_FLAGS, IFLA_MACVLAN_MACADDR_MODE, IFLA_MACVLAN_MACADDR, IFLA_MACVLAN_MACADDR_DATA, IFLA_MACVLAN_MACADDR_COUNT, IFLA_MACVLAN_BC_QUEUE_LEN, IFLA_MACVLAN_BC_QUEUE_LEN_USED, IFLA_MACVLAN_BC_CUTOFF, __IFLA_MACVLAN_MAX, }; #define IFLA_MACVLAN_MAX (__IFLA_MACVLAN_MAX - 1) enum macvlan_mode { MACVLAN_MODE_PRIVATE = 1, /* don't talk to other macvlans */ MACVLAN_MODE_VEPA = 2, /* talk to other ports through ext bridge */ MACVLAN_MODE_BRIDGE = 4, /* talk to bridge ports directly */ MACVLAN_MODE_PASSTHRU = 8,/* take over the underlying device */ MACVLAN_MODE_SOURCE = 16,/* use source MAC address list to assign */ }; enum macvlan_macaddr_mode { MACVLAN_MACADDR_ADD, MACVLAN_MACADDR_DEL, MACVLAN_MACADDR_FLUSH, MACVLAN_MACADDR_SET, }; #define MACVLAN_FLAG_NOPROMISC 1 /* VRF section */ enum { IFLA_VRF_UNSPEC, IFLA_VRF_TABLE, __IFLA_VRF_MAX }; #define IFLA_VRF_MAX (__IFLA_VRF_MAX - 1) enum { IFLA_VRF_PORT_UNSPEC, IFLA_VRF_PORT_TABLE, __IFLA_VRF_PORT_MAX }; #define IFLA_VRF_PORT_MAX (__IFLA_VRF_PORT_MAX - 1) /* MACSEC section */ enum { IFLA_MACSEC_UNSPEC, IFLA_MACSEC_SCI, IFLA_MACSEC_PORT, IFLA_MACSEC_ICV_LEN, IFLA_MACSEC_CIPHER_SUITE, IFLA_MACSEC_WINDOW, IFLA_MACSEC_ENCODING_SA, IFLA_MACSEC_ENCRYPT, IFLA_MACSEC_PROTECT, IFLA_MACSEC_INC_SCI, IFLA_MACSEC_ES, IFLA_MACSEC_SCB, IFLA_MACSEC_REPLAY_PROTECT, IFLA_MACSEC_VALIDATION, IFLA_MACSEC_PAD, __IFLA_MACSEC_MAX, }; #define IFLA_MACSEC_MAX (__IFLA_MACSEC_MAX - 1) /* XFRM section */ enum { IFLA_XFRM_UNSPEC, IFLA_XFRM_LINK, IFLA_XFRM_IF_ID, __IFLA_XFRM_MAX }; #define IFLA_XFRM_MAX (__IFLA_XFRM_MAX - 1) enum macsec_validation_type { MACSEC_VALIDATE_DISABLED = 0, MACSEC_VALIDATE_CHECK = 1, MACSEC_VALIDATE_STRICT = 2, __MACSEC_VALIDATE_END, MACSEC_VALIDATE_MAX = __MACSEC_VALIDATE_END - 1, }; /* IPVLAN section */ enum { IFLA_IPVLAN_UNSPEC, IFLA_IPVLAN_MODE, IFLA_IPVLAN_FLAGS, __IFLA_IPVLAN_MAX }; #define IFLA_IPVLAN_MAX (__IFLA_IPVLAN_MAX - 1) enum ipvlan_mode { IPVLAN_MODE_L2 = 0, IPVLAN_MODE_L3, IPVLAN_MODE_L3S, IPVLAN_MODE_MAX }; #define IPVLAN_F_PRIVATE 0x01 #define IPVLAN_F_VEPA 0x02 /* VXLAN section */ enum { IFLA_VXLAN_UNSPEC, IFLA_VXLAN_ID, IFLA_VXLAN_GROUP, /* group or remote address */ IFLA_VXLAN_LINK, IFLA_VXLAN_LOCAL, IFLA_VXLAN_TTL, IFLA_VXLAN_TOS, IFLA_VXLAN_LEARNING, IFLA_VXLAN_AGEING, IFLA_VXLAN_LIMIT, IFLA_VXLAN_PORT_RANGE, /* source port */ IFLA_VXLAN_PROXY, IFLA_VXLAN_RSC, IFLA_VXLAN_L2MISS, IFLA_VXLAN_L3MISS, IFLA_VXLAN_PORT, /* destination port */ IFLA_VXLAN_GROUP6, IFLA_VXLAN_LOCAL6, IFLA_VXLAN_UDP_CSUM, IFLA_VXLAN_UDP_ZERO_CSUM6_TX, IFLA_VXLAN_UDP_ZERO_CSUM6_RX, IFLA_VXLAN_REMCSUM_TX, IFLA_VXLAN_REMCSUM_RX, IFLA_VXLAN_GBP, IFLA_VXLAN_REMCSUM_NOPARTIAL, IFLA_VXLAN_COLLECT_METADATA, IFLA_VXLAN_LABEL, IFLA_VXLAN_GPE, IFLA_VXLAN_TTL_INHERIT, IFLA_VXLAN_DF, __IFLA_VXLAN_MAX }; #define IFLA_VXLAN_MAX (__IFLA_VXLAN_MAX - 1) struct ifla_vxlan_port_range { __be16 low; __be16 high; }; enum ifla_vxlan_df { VXLAN_DF_UNSET = 0, VXLAN_DF_SET, VXLAN_DF_INHERIT, __VXLAN_DF_END, VXLAN_DF_MAX = __VXLAN_DF_END - 1, }; /* GENEVE section */ enum { IFLA_GENEVE_UNSPEC, IFLA_GENEVE_ID, IFLA_GENEVE_REMOTE, IFLA_GENEVE_TTL, IFLA_GENEVE_TOS, IFLA_GENEVE_PORT, /* destination port */ IFLA_GENEVE_COLLECT_METADATA, IFLA_GENEVE_REMOTE6, IFLA_GENEVE_UDP_CSUM, IFLA_GENEVE_UDP_ZERO_CSUM6_TX, IFLA_GENEVE_UDP_ZERO_CSUM6_RX, IFLA_GENEVE_LABEL, IFLA_GENEVE_TTL_INHERIT, IFLA_GENEVE_DF, __IFLA_GENEVE_MAX }; #define IFLA_GENEVE_MAX (__IFLA_GENEVE_MAX - 1) enum ifla_geneve_df { GENEVE_DF_UNSET = 0, GENEVE_DF_SET, GENEVE_DF_INHERIT, __GENEVE_DF_END, GENEVE_DF_MAX = __GENEVE_DF_END - 1, }; /* Bareudp section */ enum { IFLA_BAREUDP_UNSPEC, IFLA_BAREUDP_PORT, IFLA_BAREUDP_ETHERTYPE, IFLA_BAREUDP_SRCPORT_MIN, IFLA_BAREUDP_MULTIPROTO_MODE, __IFLA_BAREUDP_MAX }; #define IFLA_BAREUDP_MAX (__IFLA_BAREUDP_MAX - 1) /* PPP section */ enum { IFLA_PPP_UNSPEC, IFLA_PPP_DEV_FD, __IFLA_PPP_MAX }; #define IFLA_PPP_MAX (__IFLA_PPP_MAX - 1) /* GTP section */ enum ifla_gtp_role { GTP_ROLE_GGSN = 0, GTP_ROLE_SGSN, }; enum { IFLA_GTP_UNSPEC, IFLA_GTP_FD0, IFLA_GTP_FD1, IFLA_GTP_PDP_HASHSIZE, IFLA_GTP_ROLE, __IFLA_GTP_MAX, }; #define IFLA_GTP_MAX (__IFLA_GTP_MAX - 1) /* Bonding section */ enum { IFLA_BOND_UNSPEC, IFLA_BOND_MODE, IFLA_BOND_ACTIVE_SLAVE, IFLA_BOND_MIIMON, IFLA_BOND_UPDELAY, IFLA_BOND_DOWNDELAY, IFLA_BOND_USE_CARRIER, IFLA_BOND_ARP_INTERVAL, IFLA_BOND_ARP_IP_TARGET, IFLA_BOND_ARP_VALIDATE, IFLA_BOND_ARP_ALL_TARGETS, IFLA_BOND_PRIMARY, IFLA_BOND_PRIMARY_RESELECT, IFLA_BOND_FAIL_OVER_MAC, IFLA_BOND_XMIT_HASH_POLICY, IFLA_BOND_RESEND_IGMP, IFLA_BOND_NUM_PEER_NOTIF, IFLA_BOND_ALL_SLAVES_ACTIVE, IFLA_BOND_MIN_LINKS, IFLA_BOND_LP_INTERVAL, IFLA_BOND_PACKETS_PER_SLAVE, IFLA_BOND_AD_LACP_RATE, IFLA_BOND_AD_SELECT, IFLA_BOND_AD_INFO, IFLA_BOND_AD_ACTOR_SYS_PRIO, IFLA_BOND_AD_USER_PORT_KEY, IFLA_BOND_AD_ACTOR_SYSTEM, IFLA_BOND_TLB_DYNAMIC_LB, IFLA_BOND_PEER_NOTIF_DELAY, IFLA_BOND_AD_LACP_ACTIVE, __IFLA_BOND_MAX, }; #define IFLA_BOND_MAX (__IFLA_BOND_MAX - 1) enum { IFLA_BOND_AD_INFO_UNSPEC, IFLA_BOND_AD_INFO_AGGREGATOR, IFLA_BOND_AD_INFO_NUM_PORTS, IFLA_BOND_AD_INFO_ACTOR_KEY, IFLA_BOND_AD_INFO_PARTNER_KEY, IFLA_BOND_AD_INFO_PARTNER_MAC, __IFLA_BOND_AD_INFO_MAX, }; #define IFLA_BOND_AD_INFO_MAX (__IFLA_BOND_AD_INFO_MAX - 1) enum { IFLA_BOND_SLAVE_UNSPEC, IFLA_BOND_SLAVE_STATE, IFLA_BOND_SLAVE_MII_STATUS, IFLA_BOND_SLAVE_LINK_FAILURE_COUNT, IFLA_BOND_SLAVE_PERM_HWADDR, IFLA_BOND_SLAVE_QUEUE_ID, IFLA_BOND_SLAVE_AD_AGGREGATOR_ID, IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE, IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE, __IFLA_BOND_SLAVE_MAX, }; #define IFLA_BOND_SLAVE_MAX (__IFLA_BOND_SLAVE_MAX - 1) /* SR-IOV virtual function management section */ enum { IFLA_VF_INFO_UNSPEC, IFLA_VF_INFO, __IFLA_VF_INFO_MAX, }; #define IFLA_VF_INFO_MAX (__IFLA_VF_INFO_MAX - 1) enum { IFLA_VF_UNSPEC, IFLA_VF_MAC, /* Hardware queue specific attributes */ IFLA_VF_VLAN, /* VLAN ID and QoS */ IFLA_VF_TX_RATE, /* Max TX Bandwidth Allocation */ IFLA_VF_SPOOFCHK, /* Spoof Checking on/off switch */ IFLA_VF_LINK_STATE, /* link state enable/disable/auto switch */ IFLA_VF_RATE, /* Min and Max TX Bandwidth Allocation */ IFLA_VF_RSS_QUERY_EN, /* RSS Redirection Table and Hash Key query * on/off switch */ IFLA_VF_STATS, /* network device statistics */ IFLA_VF_TRUST, /* Trust VF */ IFLA_VF_IB_NODE_GUID, /* VF Infiniband node GUID */ IFLA_VF_IB_PORT_GUID, /* VF Infiniband port GUID */ IFLA_VF_VLAN_LIST, /* nested list of vlans, option for QinQ */ IFLA_VF_BROADCAST, /* VF broadcast */ __IFLA_VF_MAX, }; #define IFLA_VF_MAX (__IFLA_VF_MAX - 1) struct ifla_vf_mac { __u32 vf; __u8 mac[32]; /* MAX_ADDR_LEN */ }; struct ifla_vf_broadcast { __u8 broadcast[32]; }; struct ifla_vf_vlan { __u32 vf; __u32 vlan; /* 0 - 4095, 0 disables VLAN filter */ __u32 qos; }; enum { IFLA_VF_VLAN_INFO_UNSPEC, IFLA_VF_VLAN_INFO, /* VLAN ID, QoS and VLAN protocol */ __IFLA_VF_VLAN_INFO_MAX, }; #define IFLA_VF_VLAN_INFO_MAX (__IFLA_VF_VLAN_INFO_MAX - 1) #define MAX_VLAN_LIST_LEN 1 struct ifla_vf_vlan_info { __u32 vf; __u32 vlan; /* 0 - 4095, 0 disables VLAN filter */ __u32 qos; __be16 vlan_proto; /* VLAN protocol either 802.1Q or 802.1ad */ }; struct ifla_vf_tx_rate { __u32 vf; __u32 rate; /* Max TX bandwidth in Mbps, 0 disables throttling */ }; struct ifla_vf_rate { __u32 vf; __u32 min_tx_rate; /* Min Bandwidth in Mbps */ __u32 max_tx_rate; /* Max Bandwidth in Mbps */ }; struct ifla_vf_spoofchk { __u32 vf; __u32 setting; }; struct ifla_vf_guid { __u32 vf; __u64 guid; }; enum { IFLA_VF_LINK_STATE_AUTO, /* link state of the uplink */ IFLA_VF_LINK_STATE_ENABLE, /* link always up */ IFLA_VF_LINK_STATE_DISABLE, /* link always down */ __IFLA_VF_LINK_STATE_MAX, }; struct ifla_vf_link_state { __u32 vf; __u32 link_state; }; struct ifla_vf_rss_query_en { __u32 vf; __u32 setting; }; enum { IFLA_VF_STATS_RX_PACKETS, IFLA_VF_STATS_TX_PACKETS, IFLA_VF_STATS_RX_BYTES, IFLA_VF_STATS_TX_BYTES, IFLA_VF_STATS_BROADCAST, IFLA_VF_STATS_MULTICAST, IFLA_VF_STATS_PAD, IFLA_VF_STATS_RX_DROPPED, IFLA_VF_STATS_TX_DROPPED, __IFLA_VF_STATS_MAX, }; #define IFLA_VF_STATS_MAX (__IFLA_VF_STATS_MAX - 1) struct ifla_vf_trust { __u32 vf; __u32 setting; }; /* VF ports management section * * Nested layout of set/get msg is: * * [IFLA_NUM_VF] * [IFLA_VF_PORTS] * [IFLA_VF_PORT] * [IFLA_PORT_*], ... * [IFLA_VF_PORT] * [IFLA_PORT_*], ... * ... * [IFLA_PORT_SELF] * [IFLA_PORT_*], ... */ enum { IFLA_VF_PORT_UNSPEC, IFLA_VF_PORT, /* nest */ __IFLA_VF_PORT_MAX, }; #define IFLA_VF_PORT_MAX (__IFLA_VF_PORT_MAX - 1) enum { IFLA_PORT_UNSPEC, IFLA_PORT_VF, /* __u32 */ IFLA_PORT_PROFILE, /* string */ IFLA_PORT_VSI_TYPE, /* 802.1Qbg (pre-)standard VDP */ IFLA_PORT_INSTANCE_UUID, /* binary UUID */ IFLA_PORT_HOST_UUID, /* binary UUID */ IFLA_PORT_REQUEST, /* __u8 */ IFLA_PORT_RESPONSE, /* __u16, output only */ __IFLA_PORT_MAX, }; #define IFLA_PORT_MAX (__IFLA_PORT_MAX - 1) #define PORT_PROFILE_MAX 40 #define PORT_UUID_MAX 16 #define PORT_SELF_VF -1 enum { PORT_REQUEST_PREASSOCIATE = 0, PORT_REQUEST_PREASSOCIATE_RR, PORT_REQUEST_ASSOCIATE, PORT_REQUEST_DISASSOCIATE, }; enum { PORT_VDP_RESPONSE_SUCCESS = 0, PORT_VDP_RESPONSE_INVALID_FORMAT, PORT_VDP_RESPONSE_INSUFFICIENT_RESOURCES, PORT_VDP_RESPONSE_UNUSED_VTID, PORT_VDP_RESPONSE_VTID_VIOLATION, PORT_VDP_RESPONSE_VTID_VERSION_VIOALTION, PORT_VDP_RESPONSE_OUT_OF_SYNC, /* 0x08-0xFF reserved for future VDP use */ PORT_PROFILE_RESPONSE_SUCCESS = 0x100, PORT_PROFILE_RESPONSE_INPROGRESS, PORT_PROFILE_RESPONSE_INVALID, PORT_PROFILE_RESPONSE_BADSTATE, PORT_PROFILE_RESPONSE_INSUFFICIENT_RESOURCES, PORT_PROFILE_RESPONSE_ERROR, }; struct ifla_port_vsi { __u8 vsi_mgr_id; __u8 vsi_type_id[3]; __u8 vsi_type_version; __u8 pad[3]; }; /* IPoIB section */ enum { IFLA_IPOIB_UNSPEC, IFLA_IPOIB_PKEY, IFLA_IPOIB_MODE, IFLA_IPOIB_UMCAST, __IFLA_IPOIB_MAX }; enum { IPOIB_MODE_DATAGRAM = 0, /* using unreliable datagram QPs */ IPOIB_MODE_CONNECTED = 1, /* using connected QPs */ }; #define IFLA_IPOIB_MAX (__IFLA_IPOIB_MAX - 1) /* HSR section */ enum { IFLA_HSR_UNSPEC, IFLA_HSR_SLAVE1, IFLA_HSR_SLAVE2, IFLA_HSR_MULTICAST_SPEC, /* Last byte of supervision addr */ IFLA_HSR_SUPERVISION_ADDR, /* Supervision frame multicast addr */ IFLA_HSR_SEQ_NR, IFLA_HSR_VERSION, /* HSR version */ __IFLA_HSR_MAX, }; #define IFLA_HSR_MAX (__IFLA_HSR_MAX - 1) /* STATS section */ struct if_stats_msg { __u8 family; __u8 pad1; __u16 pad2; __u32 ifindex; __u32 filter_mask; }; /* A stats attribute can be netdev specific or a global stat. * For netdev stats, lets use the prefix IFLA_STATS_LINK_* */ enum { IFLA_STATS_UNSPEC, /* also used as 64bit pad attribute */ IFLA_STATS_LINK_64, IFLA_STATS_LINK_XSTATS, IFLA_STATS_LINK_XSTATS_SLAVE, IFLA_STATS_LINK_OFFLOAD_XSTATS, IFLA_STATS_AF_SPEC, __IFLA_STATS_MAX, }; #define IFLA_STATS_MAX (__IFLA_STATS_MAX - 1) #define IFLA_STATS_FILTER_BIT(ATTR) (1 << (ATTR - 1)) /* These are embedded into IFLA_STATS_LINK_XSTATS: * [IFLA_STATS_LINK_XSTATS] * -> [LINK_XSTATS_TYPE_xxx] * -> [rtnl link type specific attributes] */ enum { LINK_XSTATS_TYPE_UNSPEC, LINK_XSTATS_TYPE_BRIDGE, LINK_XSTATS_TYPE_BOND, __LINK_XSTATS_TYPE_MAX }; #define LINK_XSTATS_TYPE_MAX (__LINK_XSTATS_TYPE_MAX - 1) /* These are stats embedded into IFLA_STATS_LINK_OFFLOAD_XSTATS */ enum { IFLA_OFFLOAD_XSTATS_UNSPEC, IFLA_OFFLOAD_XSTATS_CPU_HIT, /* struct rtnl_link_stats64 */ __IFLA_OFFLOAD_XSTATS_MAX }; #define IFLA_OFFLOAD_XSTATS_MAX (__IFLA_OFFLOAD_XSTATS_MAX - 1) /* XDP section */ #define XDP_FLAGS_UPDATE_IF_NOEXIST (1U << 0) #define XDP_FLAGS_SKB_MODE (1U << 1) #define XDP_FLAGS_DRV_MODE (1U << 2) #define XDP_FLAGS_HW_MODE (1U << 3) #define XDP_FLAGS_REPLACE (1U << 4) #define XDP_FLAGS_MODES (XDP_FLAGS_SKB_MODE | \ XDP_FLAGS_DRV_MODE | \ XDP_FLAGS_HW_MODE) #define XDP_FLAGS_MASK (XDP_FLAGS_UPDATE_IF_NOEXIST | \ XDP_FLAGS_MODES | XDP_FLAGS_REPLACE) /* These are stored into IFLA_XDP_ATTACHED on dump. */ enum { XDP_ATTACHED_NONE = 0, XDP_ATTACHED_DRV, XDP_ATTACHED_SKB, XDP_ATTACHED_HW, XDP_ATTACHED_MULTI, }; enum { IFLA_XDP_UNSPEC, IFLA_XDP_FD, IFLA_XDP_ATTACHED, IFLA_XDP_FLAGS, IFLA_XDP_PROG_ID, IFLA_XDP_DRV_PROG_ID, IFLA_XDP_SKB_PROG_ID, IFLA_XDP_HW_PROG_ID, IFLA_XDP_EXPECTED_FD, __IFLA_XDP_MAX, }; #define IFLA_XDP_MAX (__IFLA_XDP_MAX - 1) enum { IFLA_EVENT_NONE, IFLA_EVENT_REBOOT, /* internal reset / reboot */ IFLA_EVENT_FEATURES, /* change in offload features */ IFLA_EVENT_BONDING_FAILOVER, /* change in active slave */ IFLA_EVENT_NOTIFY_PEERS, /* re-sent grat. arp/ndisc */ IFLA_EVENT_IGMP_RESEND, /* re-sent IGMP JOIN */ IFLA_EVENT_BONDING_OPTIONS, /* change in bonding options */ }; /* tun section */ enum { IFLA_TUN_UNSPEC, IFLA_TUN_OWNER, IFLA_TUN_GROUP, IFLA_TUN_TYPE, IFLA_TUN_PI, IFLA_TUN_VNET_HDR, IFLA_TUN_PERSIST, IFLA_TUN_MULTI_QUEUE, IFLA_TUN_NUM_QUEUES, IFLA_TUN_NUM_DISABLED_QUEUES, __IFLA_TUN_MAX, }; #define IFLA_TUN_MAX (__IFLA_TUN_MAX - 1) /* rmnet section */ #define RMNET_FLAGS_INGRESS_DEAGGREGATION (1U << 0) #define RMNET_FLAGS_INGRESS_MAP_COMMANDS (1U << 1) #define RMNET_FLAGS_INGRESS_MAP_CKSUMV4 (1U << 2) #define RMNET_FLAGS_EGRESS_MAP_CKSUMV4 (1U << 3) enum { IFLA_RMNET_UNSPEC, IFLA_RMNET_MUX_ID, IFLA_RMNET_FLAGS, __IFLA_RMNET_MAX, }; #define IFLA_RMNET_MAX (__IFLA_RMNET_MAX - 1) struct ifla_rmnet_flags { __u32 flags; __u32 mask; }; #endif /* _LINUX_IF_LINK_H */ linux/in.h000064400000023436151027430560006475 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions of the Internet Protocol. * * Version: @(#)in.h 1.0.1 04/21/93 * * Authors: Original taken from the GNU Project file. * Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IN_H #define _LINUX_IN_H #include #include #include #if __UAPI_DEF_IN_IPPROTO /* Standard well-defined IP protocols. */ enum { IPPROTO_IP = 0, /* Dummy protocol for TCP */ #define IPPROTO_IP IPPROTO_IP IPPROTO_ICMP = 1, /* Internet Control Message Protocol */ #define IPPROTO_ICMP IPPROTO_ICMP IPPROTO_IGMP = 2, /* Internet Group Management Protocol */ #define IPPROTO_IGMP IPPROTO_IGMP IPPROTO_IPIP = 4, /* IPIP tunnels (older KA9Q tunnels use 94) */ #define IPPROTO_IPIP IPPROTO_IPIP IPPROTO_TCP = 6, /* Transmission Control Protocol */ #define IPPROTO_TCP IPPROTO_TCP IPPROTO_EGP = 8, /* Exterior Gateway Protocol */ #define IPPROTO_EGP IPPROTO_EGP IPPROTO_PUP = 12, /* PUP protocol */ #define IPPROTO_PUP IPPROTO_PUP IPPROTO_UDP = 17, /* User Datagram Protocol */ #define IPPROTO_UDP IPPROTO_UDP IPPROTO_IDP = 22, /* XNS IDP protocol */ #define IPPROTO_IDP IPPROTO_IDP IPPROTO_TP = 29, /* SO Transport Protocol Class 4 */ #define IPPROTO_TP IPPROTO_TP IPPROTO_DCCP = 33, /* Datagram Congestion Control Protocol */ #define IPPROTO_DCCP IPPROTO_DCCP IPPROTO_IPV6 = 41, /* IPv6-in-IPv4 tunnelling */ #define IPPROTO_IPV6 IPPROTO_IPV6 IPPROTO_RSVP = 46, /* RSVP Protocol */ #define IPPROTO_RSVP IPPROTO_RSVP IPPROTO_GRE = 47, /* Cisco GRE tunnels (rfc 1701,1702) */ #define IPPROTO_GRE IPPROTO_GRE IPPROTO_ESP = 50, /* Encapsulation Security Payload protocol */ #define IPPROTO_ESP IPPROTO_ESP IPPROTO_AH = 51, /* Authentication Header protocol */ #define IPPROTO_AH IPPROTO_AH IPPROTO_MTP = 92, /* Multicast Transport Protocol */ #define IPPROTO_MTP IPPROTO_MTP IPPROTO_BEETPH = 94, /* IP option pseudo header for BEET */ #define IPPROTO_BEETPH IPPROTO_BEETPH IPPROTO_ENCAP = 98, /* Encapsulation Header */ #define IPPROTO_ENCAP IPPROTO_ENCAP IPPROTO_PIM = 103, /* Protocol Independent Multicast */ #define IPPROTO_PIM IPPROTO_PIM IPPROTO_COMP = 108, /* Compression Header Protocol */ #define IPPROTO_COMP IPPROTO_COMP IPPROTO_L2TP = 115, /* Layer 2 Tunnelling Protocol */ #define IPPROTO_L2TP IPPROTO_L2TP IPPROTO_SCTP = 132, /* Stream Control Transport Protocol */ #define IPPROTO_SCTP IPPROTO_SCTP IPPROTO_UDPLITE = 136, /* UDP-Lite (RFC 3828) */ #define IPPROTO_UDPLITE IPPROTO_UDPLITE IPPROTO_MPLS = 137, /* MPLS in IP (RFC 4023) */ #define IPPROTO_MPLS IPPROTO_MPLS IPPROTO_RAW = 255, /* Raw IP packets */ #define IPPROTO_RAW IPPROTO_RAW IPPROTO_MAX #define IPPROTO_MPTCP 262 }; #endif #if __UAPI_DEF_IN_ADDR /* Internet address. */ struct in_addr { __be32 s_addr; }; #endif #define IP_TOS 1 #define IP_TTL 2 #define IP_HDRINCL 3 #define IP_OPTIONS 4 #define IP_ROUTER_ALERT 5 #define IP_RECVOPTS 6 #define IP_RETOPTS 7 #define IP_PKTINFO 8 #define IP_PKTOPTIONS 9 #define IP_MTU_DISCOVER 10 #define IP_RECVERR 11 #define IP_RECVTTL 12 #define IP_RECVTOS 13 #define IP_MTU 14 #define IP_FREEBIND 15 #define IP_IPSEC_POLICY 16 #define IP_XFRM_POLICY 17 #define IP_PASSSEC 18 #define IP_TRANSPARENT 19 /* BSD compatibility */ #define IP_RECVRETOPTS IP_RETOPTS /* TProxy original addresses */ #define IP_ORIGDSTADDR 20 #define IP_RECVORIGDSTADDR IP_ORIGDSTADDR #define IP_MINTTL 21 #define IP_NODEFRAG 22 #define IP_CHECKSUM 23 #define IP_BIND_ADDRESS_NO_PORT 24 #define IP_RECVFRAGSIZE 25 /* IP_MTU_DISCOVER values */ #define IP_PMTUDISC_DONT 0 /* Never send DF frames */ #define IP_PMTUDISC_WANT 1 /* Use per route hints */ #define IP_PMTUDISC_DO 2 /* Always DF */ #define IP_PMTUDISC_PROBE 3 /* Ignore dst pmtu */ /* Always use interface mtu (ignores dst pmtu) but don't set DF flag. * Also incoming ICMP frag_needed notifications will be ignored on * this socket to prevent accepting spoofed ones. */ #define IP_PMTUDISC_INTERFACE 4 /* weaker version of IP_PMTUDISC_INTERFACE, which allos packets to get * fragmented if they exeed the interface mtu */ #define IP_PMTUDISC_OMIT 5 #define IP_MULTICAST_IF 32 #define IP_MULTICAST_TTL 33 #define IP_MULTICAST_LOOP 34 #define IP_ADD_MEMBERSHIP 35 #define IP_DROP_MEMBERSHIP 36 #define IP_UNBLOCK_SOURCE 37 #define IP_BLOCK_SOURCE 38 #define IP_ADD_SOURCE_MEMBERSHIP 39 #define IP_DROP_SOURCE_MEMBERSHIP 40 #define IP_MSFILTER 41 #define MCAST_JOIN_GROUP 42 #define MCAST_BLOCK_SOURCE 43 #define MCAST_UNBLOCK_SOURCE 44 #define MCAST_LEAVE_GROUP 45 #define MCAST_JOIN_SOURCE_GROUP 46 #define MCAST_LEAVE_SOURCE_GROUP 47 #define MCAST_MSFILTER 48 #define IP_MULTICAST_ALL 49 #define IP_UNICAST_IF 50 #define MCAST_EXCLUDE 0 #define MCAST_INCLUDE 1 /* These need to appear somewhere around here */ #define IP_DEFAULT_MULTICAST_TTL 1 #define IP_DEFAULT_MULTICAST_LOOP 1 /* Request struct for multicast socket ops */ #if __UAPI_DEF_IP_MREQ struct ip_mreq { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_interface; /* local IP address of interface */ }; struct ip_mreqn { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_address; /* local IP address of interface */ int imr_ifindex; /* Interface index */ }; struct ip_mreq_source { __be32 imr_multiaddr; __be32 imr_interface; __be32 imr_sourceaddr; }; struct ip_msfilter { __be32 imsf_multiaddr; __be32 imsf_interface; __u32 imsf_fmode; __u32 imsf_numsrc; __be32 imsf_slist[1]; }; #define IP_MSFILTER_SIZE(numsrc) \ (sizeof(struct ip_msfilter) - sizeof(__u32) \ + (numsrc) * sizeof(__u32)) struct group_req { __u32 gr_interface; /* interface index */ struct __kernel_sockaddr_storage gr_group; /* group address */ }; struct group_source_req { __u32 gsr_interface; /* interface index */ struct __kernel_sockaddr_storage gsr_group; /* group address */ struct __kernel_sockaddr_storage gsr_source; /* source address */ }; struct group_filter { __u32 gf_interface; /* interface index */ struct __kernel_sockaddr_storage gf_group; /* multicast address */ __u32 gf_fmode; /* filter mode */ __u32 gf_numsrc; /* number of sources */ struct __kernel_sockaddr_storage gf_slist[1]; /* interface index */ }; #define GROUP_FILTER_SIZE(numsrc) \ (sizeof(struct group_filter) - sizeof(struct __kernel_sockaddr_storage) \ + (numsrc) * sizeof(struct __kernel_sockaddr_storage)) #endif #if __UAPI_DEF_IN_PKTINFO struct in_pktinfo { int ipi_ifindex; struct in_addr ipi_spec_dst; struct in_addr ipi_addr; }; #endif /* Structure describing an Internet (IP) socket address. */ #if __UAPI_DEF_SOCKADDR_IN #define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */ struct sockaddr_in { __kernel_sa_family_t sin_family; /* Address family */ __be16 sin_port; /* Port number */ struct in_addr sin_addr; /* Internet address */ /* Pad to size of `struct sockaddr'. */ unsigned char __pad[__SOCK_SIZE__ - sizeof(short int) - sizeof(unsigned short int) - sizeof(struct in_addr)]; }; #define sin_zero __pad /* for BSD UNIX comp. -FvK */ #endif #if __UAPI_DEF_IN_CLASS /* * Definitions of the bits in an Internet address integer. * On subnets, host and network parts are found according * to the subnet mask, not these masks. */ #define IN_CLASSA(a) ((((long int) (a)) & 0x80000000) == 0) #define IN_CLASSA_NET 0xff000000 #define IN_CLASSA_NSHIFT 24 #define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) #define IN_CLASSA_MAX 128 #define IN_CLASSB(a) ((((long int) (a)) & 0xc0000000) == 0x80000000) #define IN_CLASSB_NET 0xffff0000 #define IN_CLASSB_NSHIFT 16 #define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) #define IN_CLASSB_MAX 65536 #define IN_CLASSC(a) ((((long int) (a)) & 0xe0000000) == 0xc0000000) #define IN_CLASSC_NET 0xffffff00 #define IN_CLASSC_NSHIFT 8 #define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) #define IN_CLASSD(a) ((((long int) (a)) & 0xf0000000) == 0xe0000000) #define IN_MULTICAST(a) IN_CLASSD(a) #define IN_MULTICAST_NET 0xF0000000 #define IN_EXPERIMENTAL(a) ((((long int) (a)) & 0xf0000000) == 0xf0000000) #define IN_BADCLASS(a) IN_EXPERIMENTAL((a)) /* Address to accept any incoming messages. */ #define INADDR_ANY ((unsigned long int) 0x00000000) /* Address to send to all hosts. */ #define INADDR_BROADCAST ((unsigned long int) 0xffffffff) /* Address indicating an error return. */ #define INADDR_NONE ((unsigned long int) 0xffffffff) /* Dummy address for src of ICMP replies if no real address is set (RFC7600). */ #define INADDR_DUMMY ((unsigned long int) 0xc0000008) /* Network number for local host loopback. */ #define IN_LOOPBACKNET 127 /* Address to loopback in software to local host. */ #define INADDR_LOOPBACK 0x7f000001 /* 127.0.0.1 */ #define IN_LOOPBACK(a) ((((long int) (a)) & 0xff000000) == 0x7f000000) /* Defines for Multicast INADDR */ #define INADDR_UNSPEC_GROUP 0xe0000000U /* 224.0.0.0 */ #define INADDR_ALLHOSTS_GROUP 0xe0000001U /* 224.0.0.1 */ #define INADDR_ALLRTRS_GROUP 0xe0000002U /* 224.0.0.2 */ #define INADDR_ALLSNOOPERS_GROUP 0xe000006aU /* 224.0.0.106 */ #define INADDR_MAX_LOCAL_GROUP 0xe00000ffU /* 224.0.0.255 */ #endif /* contains the htonl type stuff.. */ #include #endif /* _LINUX_IN_H */ linux/if_eql.h000064400000002505151027430560007320 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Equalizer Load-balancer for serial network interfaces. * * (c) Copyright 1995 Simon "Guru Aleph-Null" Janes * NCM: Network and Communications Management, Inc. * * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * The author may be reached as simon@ncm.com, or C/O * NCM * Attn: Simon Janes * 6803 Whittier Ave * McLean VA 22101 * Phone: 1-703-847-0040 ext 103 */ #ifndef _LINUX_IF_EQL_H #define _LINUX_IF_EQL_H #define EQL_DEFAULT_SLAVE_PRIORITY 28800 #define EQL_DEFAULT_MAX_SLAVES 4 #define EQL_DEFAULT_MTU 576 #define EQL_DEFAULT_RESCHED_IVAL HZ #define EQL_ENSLAVE (SIOCDEVPRIVATE) #define EQL_EMANCIPATE (SIOCDEVPRIVATE + 1) #define EQL_GETSLAVECFG (SIOCDEVPRIVATE + 2) #define EQL_SETSLAVECFG (SIOCDEVPRIVATE + 3) #define EQL_GETMASTRCFG (SIOCDEVPRIVATE + 4) #define EQL_SETMASTRCFG (SIOCDEVPRIVATE + 5) typedef struct master_config { char master_name[16]; int max_slaves; int min_slaves; } master_config_t; typedef struct slave_config { char slave_name[16]; long priority; } slave_config_t; typedef struct slaving_request { char slave_name[16]; long priority; } slaving_request_t; #endif /* _LINUX_IF_EQL_H */ linux/nbd.h000064400000005720151027430560006626 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * 1999 Copyright (C) Pavel Machek, pavel@ucw.cz. This code is GPL. * 1999/11/04 Copyright (C) 1999 VMware, Inc. (Regis "HPReg" Duchesne) * Made nbd_end_request() use the io_request_lock * 2001 Copyright (C) Steven Whitehouse * New nbd_end_request() for compatibility with new linux block * layer code. * 2003/06/24 Louis D. Langholtz * Removed unneeded blksize_bits field from nbd_device struct. * Cleanup PARANOIA usage & code. * 2004/02/19 Paul Clements * Removed PARANOIA, plus various cleanup and comments */ #ifndef LINUX_NBD_H #define LINUX_NBD_H #include #define NBD_SET_SOCK _IO( 0xab, 0 ) #define NBD_SET_BLKSIZE _IO( 0xab, 1 ) #define NBD_SET_SIZE _IO( 0xab, 2 ) #define NBD_DO_IT _IO( 0xab, 3 ) #define NBD_CLEAR_SOCK _IO( 0xab, 4 ) #define NBD_CLEAR_QUE _IO( 0xab, 5 ) #define NBD_PRINT_DEBUG _IO( 0xab, 6 ) #define NBD_SET_SIZE_BLOCKS _IO( 0xab, 7 ) #define NBD_DISCONNECT _IO( 0xab, 8 ) #define NBD_SET_TIMEOUT _IO( 0xab, 9 ) #define NBD_SET_FLAGS _IO( 0xab, 10) enum { NBD_CMD_READ = 0, NBD_CMD_WRITE = 1, NBD_CMD_DISC = 2, NBD_CMD_FLUSH = 3, NBD_CMD_TRIM = 4 }; /* values for flags field, these are server interaction specific. */ #define NBD_FLAG_HAS_FLAGS (1 << 0) /* nbd-server supports flags */ #define NBD_FLAG_READ_ONLY (1 << 1) /* device is read-only */ #define NBD_FLAG_SEND_FLUSH (1 << 2) /* can flush writeback cache */ #define NBD_FLAG_SEND_FUA (1 << 3) /* send FUA (forced unit access) */ /* there is a gap here to match userspace */ #define NBD_FLAG_SEND_TRIM (1 << 5) /* send trim/discard */ #define NBD_FLAG_CAN_MULTI_CONN (1 << 8) /* Server supports multiple connections per export. */ /* values for cmd flags in the upper 16 bits of request type */ #define NBD_CMD_FLAG_FUA (1 << 16) /* FUA (forced unit access) op */ /* These are client behavior specific flags. */ #define NBD_CFLAG_DESTROY_ON_DISCONNECT (1 << 0) /* delete the nbd device on disconnect. */ #define NBD_CFLAG_DISCONNECT_ON_CLOSE (1 << 1) /* disconnect the nbd device on * close by last opener. */ /* userspace doesn't need the nbd_device structure */ /* These are sent over the network in the request/reply magic fields */ #define NBD_REQUEST_MAGIC 0x25609513 #define NBD_REPLY_MAGIC 0x67446698 /* Do *not* use magics: 0x12560953 0x96744668. */ /* * This is the packet used for communication between client and * server. All data are in network byte order. */ struct nbd_request { __be32 magic; __be32 type; /* == READ || == WRITE */ char handle[8]; __be64 from; __be32 len; } __attribute__((packed)); /* * This is the reply packet that nbd-server sends back to the client after * it has completed an I/O request (or an error occurs). */ struct nbd_reply { __be32 magic; __be32 error; /* 0 = ok, else error */ char handle[8]; /* handle you got from request */ }; #endif /* LINUX_NBD_H */ linux/xdp_diag.h000064400000002674151027430560007647 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * xdp_diag: interface for query/monitor XDP sockets * Copyright(c) 2019 Intel Corporation. */ #ifndef _LINUX_XDP_DIAG_H #define _LINUX_XDP_DIAG_H #include struct xdp_diag_req { __u8 sdiag_family; __u8 sdiag_protocol; __u16 pad; __u32 xdiag_ino; __u32 xdiag_show; __u32 xdiag_cookie[2]; }; struct xdp_diag_msg { __u8 xdiag_family; __u8 xdiag_type; __u16 pad; __u32 xdiag_ino; __u32 xdiag_cookie[2]; }; #define XDP_SHOW_INFO (1 << 0) /* Basic information */ #define XDP_SHOW_RING_CFG (1 << 1) #define XDP_SHOW_UMEM (1 << 2) #define XDP_SHOW_MEMINFO (1 << 3) #define XDP_SHOW_STATS (1 << 4) enum { XDP_DIAG_NONE, XDP_DIAG_INFO, XDP_DIAG_UID, XDP_DIAG_RX_RING, XDP_DIAG_TX_RING, XDP_DIAG_UMEM, XDP_DIAG_UMEM_FILL_RING, XDP_DIAG_UMEM_COMPLETION_RING, XDP_DIAG_MEMINFO, XDP_DIAG_STATS, __XDP_DIAG_MAX, }; #define XDP_DIAG_MAX (__XDP_DIAG_MAX - 1) struct xdp_diag_info { __u32 ifindex; __u32 queue_id; }; struct xdp_diag_ring { __u32 entries; /*num descs */ }; #define XDP_DU_F_ZEROCOPY (1 << 0) struct xdp_diag_umem { __u64 size; __u32 id; __u32 num_pages; __u32 chunk_size; __u32 headroom; __u32 ifindex; __u32 queue_id; __u32 flags; __u32 refs; }; struct xdp_diag_stats { __u64 n_rx_dropped; __u64 n_rx_invalid; __u64 n_rx_full; __u64 n_fill_ring_empty; __u64 n_tx_invalid; __u64 n_tx_ring_empty; }; #endif /* _LINUX_XDP_DIAG_H */ linux/media.h000064400000026166151027430560007151 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Multimedia device API * * Copyright (C) 2010 Nokia Corporation * * Contacts: Laurent Pinchart * Sakari Ailus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __LINUX_MEDIA_H #define __LINUX_MEDIA_H #include #include #include #include struct media_device_info { char driver[16]; char model[32]; char serial[40]; char bus_info[32]; __u32 media_version; __u32 hw_revision; __u32 driver_version; __u32 reserved[31]; }; /* * Base number ranges for entity functions * * NOTE: Userspace should not rely on these ranges to identify a group * of function types, as newer functions can be added with any name within * the full u32 range. * * Some older functions use the MEDIA_ENT_F_OLD_*_BASE range. Do not * change this, this is for backwards compatibility. When adding new * functions always use MEDIA_ENT_F_BASE. */ #define MEDIA_ENT_F_BASE 0x00000000 #define MEDIA_ENT_F_OLD_BASE 0x00010000 #define MEDIA_ENT_F_OLD_SUBDEV_BASE 0x00020000 /* * Initial value to be used when a new entity is created * Drivers should change it to something useful. */ #define MEDIA_ENT_F_UNKNOWN MEDIA_ENT_F_BASE /* * Subdevs are initialized with MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN in order * to preserve backward compatibility. Drivers must change to the proper * subdev type before registering the entity. */ #define MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN MEDIA_ENT_F_OLD_SUBDEV_BASE /* * DVB entity functions */ #define MEDIA_ENT_F_DTV_DEMOD (MEDIA_ENT_F_BASE + 0x00001) #define MEDIA_ENT_F_TS_DEMUX (MEDIA_ENT_F_BASE + 0x00002) #define MEDIA_ENT_F_DTV_CA (MEDIA_ENT_F_BASE + 0x00003) #define MEDIA_ENT_F_DTV_NET_DECAP (MEDIA_ENT_F_BASE + 0x00004) /* * I/O entity functions */ #define MEDIA_ENT_F_IO_V4L (MEDIA_ENT_F_OLD_BASE + 1) #define MEDIA_ENT_F_IO_DTV (MEDIA_ENT_F_BASE + 0x01001) #define MEDIA_ENT_F_IO_VBI (MEDIA_ENT_F_BASE + 0x01002) #define MEDIA_ENT_F_IO_SWRADIO (MEDIA_ENT_F_BASE + 0x01003) /* * Sensor functions */ #define MEDIA_ENT_F_CAM_SENSOR (MEDIA_ENT_F_OLD_SUBDEV_BASE + 1) #define MEDIA_ENT_F_FLASH (MEDIA_ENT_F_OLD_SUBDEV_BASE + 2) #define MEDIA_ENT_F_LENS (MEDIA_ENT_F_OLD_SUBDEV_BASE + 3) /* * Video decoder functions */ #define MEDIA_ENT_F_ATV_DECODER (MEDIA_ENT_F_OLD_SUBDEV_BASE + 4) #define MEDIA_ENT_F_DTV_DECODER (MEDIA_ENT_F_BASE + 0x6001) /* * Digital TV, analog TV, radio and/or software defined radio tuner functions. * * It is a responsibility of the master/bridge drivers to add connectors * and links for MEDIA_ENT_F_TUNER. Please notice that some old tuners * may require the usage of separate I2C chips to decode analog TV signals, * when the master/bridge chipset doesn't have its own TV standard decoder. * On such cases, the IF-PLL staging is mapped via one or two entities: * MEDIA_ENT_F_IF_VID_DECODER and/or MEDIA_ENT_F_IF_AUD_DECODER. */ #define MEDIA_ENT_F_TUNER (MEDIA_ENT_F_OLD_SUBDEV_BASE + 5) /* * Analog TV IF-PLL decoder functions * * It is a responsibility of the master/bridge drivers to create links * for MEDIA_ENT_F_IF_VID_DECODER and MEDIA_ENT_F_IF_AUD_DECODER. */ #define MEDIA_ENT_F_IF_VID_DECODER (MEDIA_ENT_F_BASE + 0x02001) #define MEDIA_ENT_F_IF_AUD_DECODER (MEDIA_ENT_F_BASE + 0x02002) /* * Audio entity functions */ #define MEDIA_ENT_F_AUDIO_CAPTURE (MEDIA_ENT_F_BASE + 0x03001) #define MEDIA_ENT_F_AUDIO_PLAYBACK (MEDIA_ENT_F_BASE + 0x03002) #define MEDIA_ENT_F_AUDIO_MIXER (MEDIA_ENT_F_BASE + 0x03003) /* * Processing entity functions */ #define MEDIA_ENT_F_PROC_VIDEO_COMPOSER (MEDIA_ENT_F_BASE + 0x4001) #define MEDIA_ENT_F_PROC_VIDEO_PIXEL_FORMATTER (MEDIA_ENT_F_BASE + 0x4002) #define MEDIA_ENT_F_PROC_VIDEO_PIXEL_ENC_CONV (MEDIA_ENT_F_BASE + 0x4003) #define MEDIA_ENT_F_PROC_VIDEO_LUT (MEDIA_ENT_F_BASE + 0x4004) #define MEDIA_ENT_F_PROC_VIDEO_SCALER (MEDIA_ENT_F_BASE + 0x4005) #define MEDIA_ENT_F_PROC_VIDEO_STATISTICS (MEDIA_ENT_F_BASE + 0x4006) /* * Switch and bridge entity functions */ #define MEDIA_ENT_F_VID_MUX (MEDIA_ENT_F_BASE + 0x5001) #define MEDIA_ENT_F_VID_IF_BRIDGE (MEDIA_ENT_F_BASE + 0x5002) /* Entity flags */ #define MEDIA_ENT_FL_DEFAULT (1 << 0) #define MEDIA_ENT_FL_CONNECTOR (1 << 1) /* OR with the entity id value to find the next entity */ #define MEDIA_ENT_ID_FLAG_NEXT (1 << 31) struct media_entity_desc { __u32 id; char name[32]; __u32 type; __u32 revision; __u32 flags; __u32 group_id; __u16 pads; __u16 links; __u32 reserved[4]; union { /* Node specifications */ struct { __u32 major; __u32 minor; } dev; /* * TODO: this shouldn't have been added without * actual drivers that use this. When the first real driver * appears that sets this information, special attention * should be given whether this information is 1) enough, and * 2) can deal with udev rules that rename devices. The struct * dev would not be sufficient for this since that does not * contain the subdevice information. In addition, struct dev * can only refer to a single device, and not to multiple (e.g. * pcm and mixer devices). */ struct { __u32 card; __u32 device; __u32 subdevice; } alsa; /* * DEPRECATED: previous node specifications. Kept just to * avoid breaking compilation. Use media_entity_desc.dev * instead. */ struct { __u32 major; __u32 minor; } v4l; struct { __u32 major; __u32 minor; } fb; int dvb; /* Sub-device specifications */ /* Nothing needed yet */ __u8 raw[184]; }; }; #define MEDIA_PAD_FL_SINK (1 << 0) #define MEDIA_PAD_FL_SOURCE (1 << 1) #define MEDIA_PAD_FL_MUST_CONNECT (1 << 2) struct media_pad_desc { __u32 entity; /* entity ID */ __u16 index; /* pad index */ __u32 flags; /* pad flags */ __u32 reserved[2]; }; #define MEDIA_LNK_FL_ENABLED (1 << 0) #define MEDIA_LNK_FL_IMMUTABLE (1 << 1) #define MEDIA_LNK_FL_DYNAMIC (1 << 2) #define MEDIA_LNK_FL_LINK_TYPE (0xf << 28) # define MEDIA_LNK_FL_DATA_LINK (0 << 28) # define MEDIA_LNK_FL_INTERFACE_LINK (1 << 28) struct media_link_desc { struct media_pad_desc source; struct media_pad_desc sink; __u32 flags; __u32 reserved[2]; }; struct media_links_enum { __u32 entity; /* Should have enough room for pads elements */ struct media_pad_desc *pads; /* Should have enough room for links elements */ struct media_link_desc *links; __u32 reserved[4]; }; /* Interface type ranges */ #define MEDIA_INTF_T_DVB_BASE 0x00000100 #define MEDIA_INTF_T_V4L_BASE 0x00000200 /* Interface types */ #define MEDIA_INTF_T_DVB_FE (MEDIA_INTF_T_DVB_BASE) #define MEDIA_INTF_T_DVB_DEMUX (MEDIA_INTF_T_DVB_BASE + 1) #define MEDIA_INTF_T_DVB_DVR (MEDIA_INTF_T_DVB_BASE + 2) #define MEDIA_INTF_T_DVB_CA (MEDIA_INTF_T_DVB_BASE + 3) #define MEDIA_INTF_T_DVB_NET (MEDIA_INTF_T_DVB_BASE + 4) #define MEDIA_INTF_T_V4L_VIDEO (MEDIA_INTF_T_V4L_BASE) #define MEDIA_INTF_T_V4L_VBI (MEDIA_INTF_T_V4L_BASE + 1) #define MEDIA_INTF_T_V4L_RADIO (MEDIA_INTF_T_V4L_BASE + 2) #define MEDIA_INTF_T_V4L_SUBDEV (MEDIA_INTF_T_V4L_BASE + 3) #define MEDIA_INTF_T_V4L_SWRADIO (MEDIA_INTF_T_V4L_BASE + 4) #define MEDIA_INTF_T_V4L_TOUCH (MEDIA_INTF_T_V4L_BASE + 5) /* * MC next gen API definitions */ struct media_v2_entity { __u32 id; char name[64]; __u32 function; /* Main function of the entity */ __u32 reserved[6]; } __attribute__ ((packed)); /* Should match the specific fields at media_intf_devnode */ struct media_v2_intf_devnode { __u32 major; __u32 minor; } __attribute__ ((packed)); struct media_v2_interface { __u32 id; __u32 intf_type; __u32 flags; __u32 reserved[9]; union { struct media_v2_intf_devnode devnode; __u32 raw[16]; }; } __attribute__ ((packed)); struct media_v2_pad { __u32 id; __u32 entity_id; __u32 flags; __u32 reserved[5]; } __attribute__ ((packed)); struct media_v2_link { __u32 id; __u32 source_id; __u32 sink_id; __u32 flags; __u32 reserved[6]; } __attribute__ ((packed)); struct media_v2_topology { __u64 topology_version; __u32 num_entities; __u32 reserved1; __u64 ptr_entities; __u32 num_interfaces; __u32 reserved2; __u64 ptr_interfaces; __u32 num_pads; __u32 reserved3; __u64 ptr_pads; __u32 num_links; __u32 reserved4; __u64 ptr_links; } __attribute__ ((packed)); /* ioctls */ #define MEDIA_IOC_DEVICE_INFO _IOWR('|', 0x00, struct media_device_info) #define MEDIA_IOC_ENUM_ENTITIES _IOWR('|', 0x01, struct media_entity_desc) #define MEDIA_IOC_ENUM_LINKS _IOWR('|', 0x02, struct media_links_enum) #define MEDIA_IOC_SETUP_LINK _IOWR('|', 0x03, struct media_link_desc) #define MEDIA_IOC_G_TOPOLOGY _IOWR('|', 0x04, struct media_v2_topology) /* * Legacy symbols used to avoid userspace compilation breakages. * Do not use any of this in new applications! * * Those symbols map the entity function into types and should be * used only on legacy programs for legacy hardware. Don't rely * on those for MEDIA_IOC_G_TOPOLOGY. */ #define MEDIA_ENT_TYPE_SHIFT 16 #define MEDIA_ENT_TYPE_MASK 0x00ff0000 #define MEDIA_ENT_SUBTYPE_MASK 0x0000ffff #define MEDIA_ENT_T_DEVNODE_UNKNOWN (MEDIA_ENT_F_OLD_BASE | \ MEDIA_ENT_SUBTYPE_MASK) #define MEDIA_ENT_T_DEVNODE MEDIA_ENT_F_OLD_BASE #define MEDIA_ENT_T_DEVNODE_V4L MEDIA_ENT_F_IO_V4L #define MEDIA_ENT_T_DEVNODE_FB (MEDIA_ENT_F_OLD_BASE + 2) #define MEDIA_ENT_T_DEVNODE_ALSA (MEDIA_ENT_F_OLD_BASE + 3) #define MEDIA_ENT_T_DEVNODE_DVB (MEDIA_ENT_F_OLD_BASE + 4) #define MEDIA_ENT_T_UNKNOWN MEDIA_ENT_F_UNKNOWN #define MEDIA_ENT_T_V4L2_VIDEO MEDIA_ENT_F_IO_V4L #define MEDIA_ENT_T_V4L2_SUBDEV MEDIA_ENT_F_V4L2_SUBDEV_UNKNOWN #define MEDIA_ENT_T_V4L2_SUBDEV_SENSOR MEDIA_ENT_F_CAM_SENSOR #define MEDIA_ENT_T_V4L2_SUBDEV_FLASH MEDIA_ENT_F_FLASH #define MEDIA_ENT_T_V4L2_SUBDEV_LENS MEDIA_ENT_F_LENS #define MEDIA_ENT_T_V4L2_SUBDEV_DECODER MEDIA_ENT_F_ATV_DECODER #define MEDIA_ENT_T_V4L2_SUBDEV_TUNER MEDIA_ENT_F_TUNER /* * There is still no ALSA support in the media controller. These * defines should not have been added and we leave them here only * in case some application tries to use these defines. */ #define MEDIA_INTF_T_ALSA_BASE 0x00000300 #define MEDIA_INTF_T_ALSA_PCM_CAPTURE (MEDIA_INTF_T_ALSA_BASE) #define MEDIA_INTF_T_ALSA_PCM_PLAYBACK (MEDIA_INTF_T_ALSA_BASE + 1) #define MEDIA_INTF_T_ALSA_CONTROL (MEDIA_INTF_T_ALSA_BASE + 2) #define MEDIA_INTF_T_ALSA_COMPRESS (MEDIA_INTF_T_ALSA_BASE + 3) #define MEDIA_INTF_T_ALSA_RAWMIDI (MEDIA_INTF_T_ALSA_BASE + 4) #define MEDIA_INTF_T_ALSA_HWDEP (MEDIA_INTF_T_ALSA_BASE + 5) #define MEDIA_INTF_T_ALSA_SEQUENCER (MEDIA_INTF_T_ALSA_BASE + 6) #define MEDIA_INTF_T_ALSA_TIMER (MEDIA_INTF_T_ALSA_BASE + 7) /* Obsolete symbol for media_version, no longer used in the kernel */ #define MEDIA_API_VERSION KERNEL_VERSION(0, 1, 0) #endif /* __LINUX_MEDIA_H */ linux/radeonfb.h000064400000000550151027430560007637 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_RADEONFB_H__ #define __LINUX_RADEONFB_H__ #include #include #define ATY_RADEON_LCD_ON 0x00000001 #define ATY_RADEON_CRT_ON 0x00000002 #define FBIO_RADEON_GET_MIRROR _IOR('@', 3, size_t) #define FBIO_RADEON_SET_MIRROR _IOW('@', 4, size_t) #endif linux/cfm_bridge.h000064400000002660151027430560010144 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _LINUX_CFM_BRIDGE_H_ #define _LINUX_CFM_BRIDGE_H_ #include #include #define ETHER_HEADER_LENGTH (6+6+4+2) #define CFM_MAID_LENGTH 48 #define CFM_CCM_PDU_LENGTH 75 #define CFM_PORT_STATUS_TLV_LENGTH 4 #define CFM_IF_STATUS_TLV_LENGTH 4 #define CFM_IF_STATUS_TLV_TYPE 4 #define CFM_PORT_STATUS_TLV_TYPE 2 #define CFM_ENDE_TLV_TYPE 0 #define CFM_CCM_MAX_FRAME_LENGTH (ETHER_HEADER_LENGTH+\ CFM_CCM_PDU_LENGTH+\ CFM_PORT_STATUS_TLV_LENGTH+\ CFM_IF_STATUS_TLV_LENGTH) #define CFM_FRAME_PRIO 7 #define CFM_CCM_TLV_OFFSET 70 #define CFM_CCM_PDU_MAID_OFFSET 10 #define CFM_CCM_PDU_MEPID_OFFSET 8 #define CFM_CCM_PDU_SEQNR_OFFSET 4 #define CFM_CCM_PDU_TLV_OFFSET 74 #define CFM_CCM_ITU_RESERVED_SIZE 16 struct br_cfm_common_hdr { __u8 mdlevel_version; __u8 opcode; __u8 flags; __u8 tlv_offset; }; enum br_cfm_opcodes { BR_CFM_OPCODE_CCM = 0x1, }; /* MEP domain */ enum br_cfm_domain { BR_CFM_PORT, BR_CFM_VLAN, }; /* MEP direction */ enum br_cfm_mep_direction { BR_CFM_MEP_DIRECTION_DOWN, BR_CFM_MEP_DIRECTION_UP, }; /* CCM interval supported. */ enum br_cfm_ccm_interval { BR_CFM_CCM_INTERVAL_NONE, BR_CFM_CCM_INTERVAL_3_3_MS, BR_CFM_CCM_INTERVAL_10_MS, BR_CFM_CCM_INTERVAL_100_MS, BR_CFM_CCM_INTERVAL_1_SEC, BR_CFM_CCM_INTERVAL_10_SEC, BR_CFM_CCM_INTERVAL_1_MIN, BR_CFM_CCM_INTERVAL_10_MIN, }; #endif linux/types.h000064400000002704151027430560007226 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TYPES_H #define _LINUX_TYPES_H #include #ifndef __ASSEMBLY__ #include /* * Below are truly Linux-specific types that should never collide with * any application/library that wants linux/types.h. */ #ifdef __CHECKER__ #define __bitwise__ __attribute__((bitwise)) #else #define __bitwise__ #endif #define __bitwise __bitwise__ typedef __u16 __bitwise __le16; typedef __u16 __bitwise __be16; typedef __u32 __bitwise __le32; typedef __u32 __bitwise __be32; typedef __u64 __bitwise __le64; typedef __u64 __bitwise __be64; typedef __u16 __bitwise __sum16; typedef __u32 __bitwise __wsum; /* * aligned_u64 should be used in defining kernel<->userspace ABIs to avoid * common 32/64-bit compat problems. * 64-bit values align to 4-byte boundaries on x86_32 (and possibly other * architectures) and to 8-byte boundaries on 64-bit architectures. The new * aligned_64 type enforces 8-byte alignment so that structs containing * aligned_64 values have the same alignment on 32-bit and 64-bit architectures. * No conversions are necessary between 32-bit user-space and a 64-bit kernel. */ #define __aligned_u64 __u64 __attribute__((aligned(8))) #define __aligned_be64 __be64 __attribute__((aligned(8))) #define __aligned_le64 __le64 __attribute__((aligned(8))) typedef unsigned __bitwise __poll_t; #endif /* __ASSEMBLY__ */ #endif /* _LINUX_TYPES_H */ linux/kcm.h000064400000001466151027430560006640 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Kernel Connection Multiplexor * * Copyright (c) 2016 Tom Herbert * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * User API to clone KCM sockets and attach transport socket to a KCM * multiplexor. */ #ifndef KCM_KERNEL_H #define KCM_KERNEL_H struct kcm_attach { int fd; int bpf_fd; }; struct kcm_unattach { int fd; }; struct kcm_clone { int fd; }; #define SIOCKCMATTACH (SIOCPROTOPRIVATE + 0) #define SIOCKCMUNATTACH (SIOCPROTOPRIVATE + 1) #define SIOCKCMCLONE (SIOCPROTOPRIVATE + 2) #define KCMPROTO_CONNECTED 0 /* Socket options */ #define KCM_RECV_DISABLE 1 #endif linux/rseq.h000064400000011450151027430560007032 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _LINUX_RSEQ_H #define _LINUX_RSEQ_H /* * linux/rseq.h * * Restartable sequences system call API * * Copyright (c) 2015-2018 Mathieu Desnoyers */ #include #include enum rseq_cpu_id_state { RSEQ_CPU_ID_UNINITIALIZED = -1, RSEQ_CPU_ID_REGISTRATION_FAILED = -2, }; enum rseq_flags { RSEQ_FLAG_UNREGISTER = (1 << 0), }; enum rseq_cs_flags_bit { RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT = 0, RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT = 1, RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT = 2, }; enum rseq_cs_flags { RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT), RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT), RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT), }; /* * struct rseq_cs is aligned on 4 * 8 bytes to ensure it is always * contained within a single cache-line. It is usually declared as * link-time constant data. */ struct rseq_cs { /* Version of this structure. */ __u32 version; /* enum rseq_cs_flags */ __u32 flags; __u64 start_ip; /* Offset from start_ip. */ __u64 post_commit_offset; __u64 abort_ip; } __attribute__((aligned(4 * sizeof(__u64)))); /* * struct rseq is aligned on 4 * 8 bytes to ensure it is always * contained within a single cache-line. * * A single struct rseq per thread is allowed. */ struct rseq { /* * Restartable sequences cpu_id_start field. Updated by the * kernel. Read by user-space with single-copy atomicity * semantics. This field should only be read by the thread which * registered this data structure. Aligned on 32-bit. Always * contains a value in the range of possible CPUs, although the * value may not be the actual current CPU (e.g. if rseq is not * initialized). This CPU number value should always be compared * against the value of the cpu_id field before performing a rseq * commit or returning a value read from a data structure indexed * using the cpu_id_start value. */ __u32 cpu_id_start; /* * Restartable sequences cpu_id field. Updated by the kernel. * Read by user-space with single-copy atomicity semantics. This * field should only be read by the thread which registered this * data structure. Aligned on 32-bit. Values * RSEQ_CPU_ID_UNINITIALIZED and RSEQ_CPU_ID_REGISTRATION_FAILED * have a special semantic: the former means "rseq uninitialized", * and latter means "rseq initialization failed". This value is * meant to be read within rseq critical sections and compared * with the cpu_id_start value previously read, before performing * the commit instruction, or read and compared with the * cpu_id_start value before returning a value loaded from a data * structure indexed using the cpu_id_start value. */ __u32 cpu_id; /* * Restartable sequences rseq_cs field. * * Contains NULL when no critical section is active for the current * thread, or holds a pointer to the currently active struct rseq_cs. * * Updated by user-space, which sets the address of the currently * active rseq_cs at the beginning of assembly instruction sequence * block, and set to NULL by the kernel when it restarts an assembly * instruction sequence block, as well as when the kernel detects that * it is preempting or delivering a signal outside of the range * targeted by the rseq_cs. Also needs to be set to NULL by user-space * before reclaiming memory that contains the targeted struct rseq_cs. * * Read and set by the kernel. Set by user-space with single-copy * atomicity semantics. This field should only be updated by the * thread which registered this data structure. Aligned on 64-bit. */ union { __u64 ptr64; #ifdef __LP64__ __u64 ptr; #else struct { #if (defined(__BYTE_ORDER) && (__BYTE_ORDER == __BIG_ENDIAN)) || defined(__BIG_ENDIAN) __u32 padding; /* Initialized to zero. */ __u32 ptr32; #else /* LITTLE */ __u32 ptr32; __u32 padding; /* Initialized to zero. */ #endif /* ENDIAN */ } ptr; #endif } rseq_cs; /* * Restartable sequences flags field. * * This field should only be updated by the thread which * registered this data structure. Read by the kernel. * Mainly used for single-stepping through rseq critical sections * with debuggers. * * - RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT * Inhibit instruction sequence block restart on preemption * for this thread. * - RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL * Inhibit instruction sequence block restart on signal * delivery for this thread. * - RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE * Inhibit instruction sequence block restart on migration for * this thread. */ __u32 flags; } __attribute__((aligned(4 * sizeof(__u64)))); #endif /* _LINUX_RSEQ_H */ linux/taskstats.h000064400000016014151027430560010102 0ustar00/* SPDX-License-Identifier: LGPL-2.1 WITH Linux-syscall-note */ /* taskstats.h - exporting per-task statistics * * Copyright (C) Shailabh Nagar, IBM Corp. 2006 * (C) Balbir Singh, IBM Corp. 2006 * (C) Jay Lan, SGI, 2006 * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2.1 of the GNU Lesser General Public License * as published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef _LINUX_TASKSTATS_H #define _LINUX_TASKSTATS_H #include /* Format for per-task data returned to userland when * - a task exits * - listener requests stats for a task * * The struct is versioned. Newer versions should only add fields to * the bottom of the struct to maintain backward compatibility. * * * To add new fields * a) bump up TASKSTATS_VERSION * b) add comment indicating new version number at end of struct * c) add new fields after version comment; maintain 64-bit alignment */ #define TASKSTATS_VERSION 9 #define TS_COMM_LEN 32 /* should be >= TASK_COMM_LEN * in linux/sched.h */ struct taskstats { /* The version number of this struct. This field is always set to * TAKSTATS_VERSION, which is defined in . * Each time the struct is changed, the value should be incremented. */ __u16 version; __u32 ac_exitcode; /* Exit status */ /* The accounting flags of a task as defined in * Defined values are AFORK, ASU, ACOMPAT, ACORE, and AXSIG. */ __u8 ac_flag; /* Record flags */ __u8 ac_nice; /* task_nice */ /* Delay accounting fields start * * All values, until comment "Delay accounting fields end" are * available only if delay accounting is enabled, even though the last * few fields are not delays * * xxx_count is the number of delay values recorded * xxx_delay_total is the corresponding cumulative delay in nanoseconds * * xxx_delay_total wraps around to zero on overflow * xxx_count incremented regardless of overflow */ /* Delay waiting for cpu, while runnable * count, delay_total NOT updated atomically */ __u64 cpu_count __attribute__((aligned(8))); __u64 cpu_delay_total; /* Following four fields atomically updated using task->delays->lock */ /* Delay waiting for synchronous block I/O to complete * does not account for delays in I/O submission */ __u64 blkio_count; __u64 blkio_delay_total; /* Delay waiting for page fault I/O (swap in only) */ __u64 swapin_count; __u64 swapin_delay_total; /* cpu "wall-clock" running time * On some architectures, value will adjust for cpu time stolen * from the kernel in involuntary waits due to virtualization. * Value is cumulative, in nanoseconds, without a corresponding count * and wraps around to zero silently on overflow */ __u64 cpu_run_real_total; /* cpu "virtual" running time * Uses time intervals seen by the kernel i.e. no adjustment * for kernel's involuntary waits due to virtualization. * Value is cumulative, in nanoseconds, without a corresponding count * and wraps around to zero silently on overflow */ __u64 cpu_run_virtual_total; /* Delay accounting fields end */ /* version 1 ends here */ /* Basic Accounting Fields start */ char ac_comm[TS_COMM_LEN]; /* Command name */ __u8 ac_sched __attribute__((aligned(8))); /* Scheduling discipline */ __u8 ac_pad[3]; __u32 ac_uid __attribute__((aligned(8))); /* User ID */ __u32 ac_gid; /* Group ID */ __u32 ac_pid; /* Process ID */ __u32 ac_ppid; /* Parent process ID */ __u32 ac_btime; /* Begin time [sec since 1970] */ __u64 ac_etime __attribute__((aligned(8))); /* Elapsed time [usec] */ __u64 ac_utime; /* User CPU time [usec] */ __u64 ac_stime; /* SYstem CPU time [usec] */ __u64 ac_minflt; /* Minor Page Fault Count */ __u64 ac_majflt; /* Major Page Fault Count */ /* Basic Accounting Fields end */ /* Extended accounting fields start */ /* Accumulated RSS usage in duration of a task, in MBytes-usecs. * The current rss usage is added to this counter every time * a tick is charged to a task's system time. So, at the end we * will have memory usage multiplied by system time. Thus an * average usage per system time unit can be calculated. */ __u64 coremem; /* accumulated RSS usage in MB-usec */ /* Accumulated virtual memory usage in duration of a task. * Same as acct_rss_mem1 above except that we keep track of VM usage. */ __u64 virtmem; /* accumulated VM usage in MB-usec */ /* High watermark of RSS and virtual memory usage in duration of * a task, in KBytes. */ __u64 hiwater_rss; /* High-watermark of RSS usage, in KB */ __u64 hiwater_vm; /* High-water VM usage, in KB */ /* The following four fields are I/O statistics of a task. */ __u64 read_char; /* bytes read */ __u64 write_char; /* bytes written */ __u64 read_syscalls; /* read syscalls */ __u64 write_syscalls; /* write syscalls */ /* Extended accounting fields end */ #define TASKSTATS_HAS_IO_ACCOUNTING /* Per-task storage I/O accounting starts */ __u64 read_bytes; /* bytes of read I/O */ __u64 write_bytes; /* bytes of write I/O */ __u64 cancelled_write_bytes; /* bytes of cancelled write I/O */ __u64 nvcsw; /* voluntary_ctxt_switches */ __u64 nivcsw; /* nonvoluntary_ctxt_switches */ /* time accounting for SMT machines */ __u64 ac_utimescaled; /* utime scaled on frequency etc */ __u64 ac_stimescaled; /* stime scaled on frequency etc */ __u64 cpu_scaled_run_real_total; /* scaled cpu_run_real_total */ /* Delay waiting for memory reclaim */ __u64 freepages_count; __u64 freepages_delay_total; #ifndef __GENKSYMS__ /* Delay waiting for thrashing page */ __u64 thrashing_count; __u64 thrashing_delay_total; #endif }; /* * Commands sent from userspace * Not versioned. New commands should only be inserted at the enum's end * prior to __TASKSTATS_CMD_MAX */ enum { TASKSTATS_CMD_UNSPEC = 0, /* Reserved */ TASKSTATS_CMD_GET, /* user->kernel request/get-response */ TASKSTATS_CMD_NEW, /* kernel->user event */ __TASKSTATS_CMD_MAX, }; #define TASKSTATS_CMD_MAX (__TASKSTATS_CMD_MAX - 1) enum { TASKSTATS_TYPE_UNSPEC = 0, /* Reserved */ TASKSTATS_TYPE_PID, /* Process id */ TASKSTATS_TYPE_TGID, /* Thread group id */ TASKSTATS_TYPE_STATS, /* taskstats structure */ TASKSTATS_TYPE_AGGR_PID, /* contains pid + stats */ TASKSTATS_TYPE_AGGR_TGID, /* contains tgid + stats */ TASKSTATS_TYPE_NULL, /* contains nothing */ __TASKSTATS_TYPE_MAX, }; #define TASKSTATS_TYPE_MAX (__TASKSTATS_TYPE_MAX - 1) enum { TASKSTATS_CMD_ATTR_UNSPEC = 0, TASKSTATS_CMD_ATTR_PID, TASKSTATS_CMD_ATTR_TGID, TASKSTATS_CMD_ATTR_REGISTER_CPUMASK, TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK, __TASKSTATS_CMD_ATTR_MAX, }; #define TASKSTATS_CMD_ATTR_MAX (__TASKSTATS_CMD_ATTR_MAX - 1) /* NETLINK_GENERIC related info */ #define TASKSTATS_GENL_NAME "TASKSTATS" #define TASKSTATS_GENL_VERSION 0x1 #endif /* _LINUX_TASKSTATS_H */ linux/tipc_netlink.h000064400000022263151027430560010547 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Copyright (c) 2014, Ericsson AB * 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. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _LINUX_TIPC_NETLINK_H_ #define _LINUX_TIPC_NETLINK_H_ #define TIPC_GENL_V2_NAME "TIPCv2" #define TIPC_GENL_V2_VERSION 0x1 /* Netlink commands */ enum { TIPC_NL_UNSPEC, TIPC_NL_LEGACY, TIPC_NL_BEARER_DISABLE, TIPC_NL_BEARER_ENABLE, TIPC_NL_BEARER_GET, TIPC_NL_BEARER_SET, TIPC_NL_SOCK_GET, TIPC_NL_PUBL_GET, TIPC_NL_LINK_GET, TIPC_NL_LINK_SET, TIPC_NL_LINK_RESET_STATS, TIPC_NL_MEDIA_GET, TIPC_NL_MEDIA_SET, TIPC_NL_NODE_GET, TIPC_NL_NET_GET, TIPC_NL_NET_SET, TIPC_NL_NAME_TABLE_GET, TIPC_NL_MON_SET, TIPC_NL_MON_GET, TIPC_NL_MON_PEER_GET, TIPC_NL_PEER_REMOVE, TIPC_NL_BEARER_ADD, TIPC_NL_UDP_GET_REMOTEIP, TIPC_NL_KEY_SET, TIPC_NL_KEY_FLUSH, TIPC_NL_ADDR_LEGACY_GET, __TIPC_NL_CMD_MAX, TIPC_NL_CMD_MAX = __TIPC_NL_CMD_MAX - 1 }; /* Top level netlink attributes */ enum { TIPC_NLA_UNSPEC, TIPC_NLA_BEARER, /* nest */ TIPC_NLA_SOCK, /* nest */ TIPC_NLA_PUBL, /* nest */ TIPC_NLA_LINK, /* nest */ TIPC_NLA_MEDIA, /* nest */ TIPC_NLA_NODE, /* nest */ TIPC_NLA_NET, /* nest */ TIPC_NLA_NAME_TABLE, /* nest */ TIPC_NLA_MON, /* nest */ TIPC_NLA_MON_PEER, /* nest */ __TIPC_NLA_MAX, TIPC_NLA_MAX = __TIPC_NLA_MAX - 1 }; /* Bearer info */ enum { TIPC_NLA_BEARER_UNSPEC, TIPC_NLA_BEARER_NAME, /* string */ TIPC_NLA_BEARER_PROP, /* nest */ TIPC_NLA_BEARER_DOMAIN, /* u32 */ TIPC_NLA_BEARER_UDP_OPTS, /* nest */ __TIPC_NLA_BEARER_MAX, TIPC_NLA_BEARER_MAX = __TIPC_NLA_BEARER_MAX - 1 }; enum { TIPC_NLA_UDP_UNSPEC, TIPC_NLA_UDP_LOCAL, /* sockaddr_storage */ TIPC_NLA_UDP_REMOTE, /* sockaddr_storage */ TIPC_NLA_UDP_MULTI_REMOTEIP, /* flag */ __TIPC_NLA_UDP_MAX, TIPC_NLA_UDP_MAX = __TIPC_NLA_UDP_MAX - 1 }; /* Socket info */ enum { TIPC_NLA_SOCK_UNSPEC, TIPC_NLA_SOCK_ADDR, /* u32 */ TIPC_NLA_SOCK_REF, /* u32 */ TIPC_NLA_SOCK_CON, /* nest */ TIPC_NLA_SOCK_HAS_PUBL, /* flag */ TIPC_NLA_SOCK_STAT, /* nest */ TIPC_NLA_SOCK_TYPE, /* u32 */ TIPC_NLA_SOCK_INO, /* u32 */ TIPC_NLA_SOCK_UID, /* u32 */ TIPC_NLA_SOCK_TIPC_STATE, /* u32 */ TIPC_NLA_SOCK_COOKIE, /* u64 */ TIPC_NLA_SOCK_PAD, /* flag */ TIPC_NLA_SOCK_GROUP, /* nest */ __TIPC_NLA_SOCK_MAX, TIPC_NLA_SOCK_MAX = __TIPC_NLA_SOCK_MAX - 1 }; /* Link info */ enum { TIPC_NLA_LINK_UNSPEC, TIPC_NLA_LINK_NAME, /* string */ TIPC_NLA_LINK_DEST, /* u32 */ TIPC_NLA_LINK_MTU, /* u32 */ TIPC_NLA_LINK_BROADCAST, /* flag */ TIPC_NLA_LINK_UP, /* flag */ TIPC_NLA_LINK_ACTIVE, /* flag */ TIPC_NLA_LINK_PROP, /* nest */ TIPC_NLA_LINK_STATS, /* nest */ TIPC_NLA_LINK_RX, /* u32 */ TIPC_NLA_LINK_TX, /* u32 */ __TIPC_NLA_LINK_MAX, TIPC_NLA_LINK_MAX = __TIPC_NLA_LINK_MAX - 1 }; /* Media info */ enum { TIPC_NLA_MEDIA_UNSPEC, TIPC_NLA_MEDIA_NAME, /* string */ TIPC_NLA_MEDIA_PROP, /* nest */ __TIPC_NLA_MEDIA_MAX, TIPC_NLA_MEDIA_MAX = __TIPC_NLA_MEDIA_MAX - 1 }; /* Node info */ enum { TIPC_NLA_NODE_UNSPEC, TIPC_NLA_NODE_ADDR, /* u32 */ TIPC_NLA_NODE_UP, /* flag */ TIPC_NLA_NODE_ID, /* data */ TIPC_NLA_NODE_KEY, /* data */ TIPC_NLA_NODE_KEY_MASTER, /* flag */ TIPC_NLA_NODE_REKEYING, /* u32 */ __TIPC_NLA_NODE_MAX, TIPC_NLA_NODE_MAX = __TIPC_NLA_NODE_MAX - 1 }; /* Net info */ enum { TIPC_NLA_NET_UNSPEC, TIPC_NLA_NET_ID, /* u32 */ TIPC_NLA_NET_ADDR, /* u32 */ TIPC_NLA_NET_NODEID, /* u64 */ TIPC_NLA_NET_NODEID_W1, /* u64 */ TIPC_NLA_NET_ADDR_LEGACY, /* flag */ __TIPC_NLA_NET_MAX, TIPC_NLA_NET_MAX = __TIPC_NLA_NET_MAX - 1 }; /* Name table info */ enum { TIPC_NLA_NAME_TABLE_UNSPEC, TIPC_NLA_NAME_TABLE_PUBL, /* nest */ __TIPC_NLA_NAME_TABLE_MAX, TIPC_NLA_NAME_TABLE_MAX = __TIPC_NLA_NAME_TABLE_MAX - 1 }; /* Monitor info */ enum { TIPC_NLA_MON_UNSPEC, TIPC_NLA_MON_ACTIVATION_THRESHOLD, /* u32 */ TIPC_NLA_MON_REF, /* u32 */ TIPC_NLA_MON_ACTIVE, /* flag */ TIPC_NLA_MON_BEARER_NAME, /* string */ TIPC_NLA_MON_PEERCNT, /* u32 */ TIPC_NLA_MON_LISTGEN, /* u32 */ __TIPC_NLA_MON_MAX, TIPC_NLA_MON_MAX = __TIPC_NLA_MON_MAX - 1 }; /* Publication info */ enum { TIPC_NLA_PUBL_UNSPEC, TIPC_NLA_PUBL_TYPE, /* u32 */ TIPC_NLA_PUBL_LOWER, /* u32 */ TIPC_NLA_PUBL_UPPER, /* u32 */ TIPC_NLA_PUBL_SCOPE, /* u32 */ TIPC_NLA_PUBL_NODE, /* u32 */ TIPC_NLA_PUBL_REF, /* u32 */ TIPC_NLA_PUBL_KEY, /* u32 */ __TIPC_NLA_PUBL_MAX, TIPC_NLA_PUBL_MAX = __TIPC_NLA_PUBL_MAX - 1 }; /* Monitor peer info */ enum { TIPC_NLA_MON_PEER_UNSPEC, TIPC_NLA_MON_PEER_ADDR, /* u32 */ TIPC_NLA_MON_PEER_DOMGEN, /* u32 */ TIPC_NLA_MON_PEER_APPLIED, /* u32 */ TIPC_NLA_MON_PEER_UPMAP, /* u64 */ TIPC_NLA_MON_PEER_MEMBERS, /* tlv */ TIPC_NLA_MON_PEER_UP, /* flag */ TIPC_NLA_MON_PEER_HEAD, /* flag */ TIPC_NLA_MON_PEER_LOCAL, /* flag */ TIPC_NLA_MON_PEER_PAD, /* flag */ __TIPC_NLA_MON_PEER_MAX, TIPC_NLA_MON_PEER_MAX = __TIPC_NLA_MON_PEER_MAX - 1 }; /* Nest, socket group info */ enum { TIPC_NLA_SOCK_GROUP_ID, /* u32 */ TIPC_NLA_SOCK_GROUP_OPEN, /* flag */ TIPC_NLA_SOCK_GROUP_NODE_SCOPE, /* flag */ TIPC_NLA_SOCK_GROUP_CLUSTER_SCOPE, /* flag */ TIPC_NLA_SOCK_GROUP_INSTANCE, /* u32 */ TIPC_NLA_SOCK_GROUP_BC_SEND_NEXT, /* u32 */ __TIPC_NLA_SOCK_GROUP_MAX, TIPC_NLA_SOCK_GROUP_MAX = __TIPC_NLA_SOCK_GROUP_MAX - 1 }; /* Nest, connection info */ enum { TIPC_NLA_CON_UNSPEC, TIPC_NLA_CON_FLAG, /* flag */ TIPC_NLA_CON_NODE, /* u32 */ TIPC_NLA_CON_SOCK, /* u32 */ TIPC_NLA_CON_TYPE, /* u32 */ TIPC_NLA_CON_INST, /* u32 */ __TIPC_NLA_CON_MAX, TIPC_NLA_CON_MAX = __TIPC_NLA_CON_MAX - 1 }; /* Nest, socket statistics info */ enum { TIPC_NLA_SOCK_STAT_RCVQ, /* u32 */ TIPC_NLA_SOCK_STAT_SENDQ, /* u32 */ TIPC_NLA_SOCK_STAT_LINK_CONG, /* flag */ TIPC_NLA_SOCK_STAT_CONN_CONG, /* flag */ TIPC_NLA_SOCK_STAT_DROP, /* u32 */ __TIPC_NLA_SOCK_STAT_MAX, TIPC_NLA_SOCK_STAT_MAX = __TIPC_NLA_SOCK_STAT_MAX - 1 }; /* Nest, link propreties. Valid for link, media and bearer */ enum { TIPC_NLA_PROP_UNSPEC, TIPC_NLA_PROP_PRIO, /* u32 */ TIPC_NLA_PROP_TOL, /* u32 */ TIPC_NLA_PROP_WIN, /* u32 */ TIPC_NLA_PROP_MTU, /* u32 */ TIPC_NLA_PROP_BROADCAST, /* u32 */ TIPC_NLA_PROP_BROADCAST_RATIO, /* u32 */ __TIPC_NLA_PROP_MAX, TIPC_NLA_PROP_MAX = __TIPC_NLA_PROP_MAX - 1 }; /* Nest, statistics info */ enum { TIPC_NLA_STATS_UNSPEC, TIPC_NLA_STATS_RX_INFO, /* u32 */ TIPC_NLA_STATS_RX_FRAGMENTS, /* u32 */ TIPC_NLA_STATS_RX_FRAGMENTED, /* u32 */ TIPC_NLA_STATS_RX_BUNDLES, /* u32 */ TIPC_NLA_STATS_RX_BUNDLED, /* u32 */ TIPC_NLA_STATS_TX_INFO, /* u32 */ TIPC_NLA_STATS_TX_FRAGMENTS, /* u32 */ TIPC_NLA_STATS_TX_FRAGMENTED, /* u32 */ TIPC_NLA_STATS_TX_BUNDLES, /* u32 */ TIPC_NLA_STATS_TX_BUNDLED, /* u32 */ TIPC_NLA_STATS_MSG_PROF_TOT, /* u32 */ TIPC_NLA_STATS_MSG_LEN_CNT, /* u32 */ TIPC_NLA_STATS_MSG_LEN_TOT, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P0, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P1, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P2, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P3, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P4, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P5, /* u32 */ TIPC_NLA_STATS_MSG_LEN_P6, /* u32 */ TIPC_NLA_STATS_RX_STATES, /* u32 */ TIPC_NLA_STATS_RX_PROBES, /* u32 */ TIPC_NLA_STATS_RX_NACKS, /* u32 */ TIPC_NLA_STATS_RX_DEFERRED, /* u32 */ TIPC_NLA_STATS_TX_STATES, /* u32 */ TIPC_NLA_STATS_TX_PROBES, /* u32 */ TIPC_NLA_STATS_TX_NACKS, /* u32 */ TIPC_NLA_STATS_TX_ACKS, /* u32 */ TIPC_NLA_STATS_RETRANSMITTED, /* u32 */ TIPC_NLA_STATS_DUPLICATES, /* u32 */ TIPC_NLA_STATS_LINK_CONGS, /* u32 */ TIPC_NLA_STATS_MAX_QUEUE, /* u32 */ TIPC_NLA_STATS_AVG_QUEUE, /* u32 */ __TIPC_NLA_STATS_MAX, TIPC_NLA_STATS_MAX = __TIPC_NLA_STATS_MAX - 1 }; #endif linux/inet_diag.h000064400000011100151027430560007773 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _INET_DIAG_H_ #define _INET_DIAG_H_ #include /* Just some random number */ #define TCPDIAG_GETSOCK 18 #define DCCPDIAG_GETSOCK 19 #define INET_DIAG_GETSOCK_MAX 24 /* Socket identity */ struct inet_diag_sockid { __be16 idiag_sport; __be16 idiag_dport; __be32 idiag_src[4]; __be32 idiag_dst[4]; __u32 idiag_if; __u32 idiag_cookie[2]; #define INET_DIAG_NOCOOKIE (~0U) }; /* Request structure */ struct inet_diag_req { __u8 idiag_family; /* Family of addresses. */ __u8 idiag_src_len; __u8 idiag_dst_len; __u8 idiag_ext; /* Query extended information */ struct inet_diag_sockid id; __u32 idiag_states; /* States to dump */ __u32 idiag_dbs; /* Tables to dump (NI) */ }; struct inet_diag_req_v2 { __u8 sdiag_family; __u8 sdiag_protocol; __u8 idiag_ext; __u8 pad; __u32 idiag_states; struct inet_diag_sockid id; }; /* * SOCK_RAW sockets require the underlied protocol to be * additionally specified so we can use @pad member for * this, but we can't rename it because userspace programs * still may depend on this name. Instead lets use another * structure definition as an alias for struct * @inet_diag_req_v2. */ struct inet_diag_req_raw { __u8 sdiag_family; __u8 sdiag_protocol; __u8 idiag_ext; __u8 sdiag_raw_protocol; __u32 idiag_states; struct inet_diag_sockid id; }; enum { INET_DIAG_REQ_NONE, INET_DIAG_REQ_BYTECODE, INET_DIAG_REQ_SK_BPF_STORAGES, INET_DIAG_REQ_PROTOCOL, __INET_DIAG_REQ_MAX, }; #define INET_DIAG_REQ_MAX (__INET_DIAG_REQ_MAX - 1) /* Bytecode is sequence of 4 byte commands followed by variable arguments. * All the commands identified by "code" are conditional jumps forward: * to offset cc+"yes" or to offset cc+"no". "yes" is supposed to be * length of the command and its arguments. */ struct inet_diag_bc_op { unsigned char code; unsigned char yes; unsigned short no; }; enum { INET_DIAG_BC_NOP, INET_DIAG_BC_JMP, INET_DIAG_BC_S_GE, INET_DIAG_BC_S_LE, INET_DIAG_BC_D_GE, INET_DIAG_BC_D_LE, INET_DIAG_BC_AUTO, INET_DIAG_BC_S_COND, INET_DIAG_BC_D_COND, INET_DIAG_BC_DEV_COND, /* u32 ifindex */ INET_DIAG_BC_MARK_COND, INET_DIAG_BC_S_EQ, INET_DIAG_BC_D_EQ, }; struct inet_diag_hostcond { __u8 family; __u8 prefix_len; int port; __be32 addr[0]; }; struct inet_diag_markcond { __u32 mark; __u32 mask; }; /* Base info structure. It contains socket identity (addrs/ports/cookie) * and, alas, the information shown by netstat. */ struct inet_diag_msg { __u8 idiag_family; __u8 idiag_state; __u8 idiag_timer; __u8 idiag_retrans; struct inet_diag_sockid id; __u32 idiag_expires; __u32 idiag_rqueue; __u32 idiag_wqueue; __u32 idiag_uid; __u32 idiag_inode; }; /* Extensions */ enum { INET_DIAG_NONE, INET_DIAG_MEMINFO, INET_DIAG_INFO, INET_DIAG_VEGASINFO, INET_DIAG_CONG, INET_DIAG_TOS, INET_DIAG_TCLASS, INET_DIAG_SKMEMINFO, INET_DIAG_SHUTDOWN, /* * Next extenstions cannot be requested in struct inet_diag_req_v2: * its field idiag_ext has only 8 bits. */ INET_DIAG_DCTCPINFO, /* request as INET_DIAG_VEGASINFO */ INET_DIAG_PROTOCOL, /* response attribute only */ INET_DIAG_SKV6ONLY, INET_DIAG_LOCALS, INET_DIAG_PEERS, INET_DIAG_PAD, INET_DIAG_MARK, /* only with CAP_NET_ADMIN */ INET_DIAG_BBRINFO, /* request as INET_DIAG_VEGASINFO */ INET_DIAG_CLASS_ID, /* request as INET_DIAG_TCLASS */ INET_DIAG_MD5SIG, INET_DIAG_ULP_INFO, INET_DIAG_SK_BPF_STORAGES, __INET_DIAG_MAX, }; #define INET_DIAG_MAX (__INET_DIAG_MAX - 1) enum { INET_ULP_INFO_UNSPEC, INET_ULP_INFO_NAME, INET_ULP_INFO_TLS, INET_ULP_INFO_MPTCP, __INET_ULP_INFO_MAX, }; #define INET_ULP_INFO_MAX (__INET_ULP_INFO_MAX - 1) /* INET_DIAG_MEM */ struct inet_diag_meminfo { __u32 idiag_rmem; __u32 idiag_wmem; __u32 idiag_fmem; __u32 idiag_tmem; }; /* INET_DIAG_VEGASINFO */ struct tcpvegas_info { __u32 tcpv_enabled; __u32 tcpv_rttcnt; __u32 tcpv_rtt; __u32 tcpv_minrtt; }; /* INET_DIAG_DCTCPINFO */ struct tcp_dctcp_info { __u16 dctcp_enabled; __u16 dctcp_ce_state; __u32 dctcp_alpha; __u32 dctcp_ab_ecn; __u32 dctcp_ab_tot; }; /* INET_DIAG_BBRINFO */ struct tcp_bbr_info { /* u64 bw: max-filtered BW (app throughput) estimate in Byte per sec: */ __u32 bbr_bw_lo; /* lower 32 bits of bw */ __u32 bbr_bw_hi; /* upper 32 bits of bw */ __u32 bbr_min_rtt; /* min-filtered RTT in uSec */ __u32 bbr_pacing_gain; /* pacing gain shifted left 8 bits */ __u32 bbr_cwnd_gain; /* cwnd gain shifted left 8 bits */ }; union tcp_cc_info { struct tcpvegas_info vegas; struct tcp_dctcp_info dctcp; struct tcp_bbr_info bbr; }; #endif /* _INET_DIAG_H_ */ linux/ndctl.h000064400000015322151027430560007166 0ustar00/* * Copyright (c) 2014-2016, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. */ #ifndef __NDCTL_H__ #define __NDCTL_H__ #include struct nd_cmd_dimm_flags { __u32 status; __u32 flags; } __attribute__((packed)); struct nd_cmd_get_config_size { __u32 status; __u32 config_size; __u32 max_xfer; } __attribute__((packed)); struct nd_cmd_get_config_data_hdr { __u32 in_offset; __u32 in_length; __u32 status; __u8 out_buf[0]; } __attribute__((packed)); struct nd_cmd_set_config_hdr { __u32 in_offset; __u32 in_length; __u8 in_buf[0]; } __attribute__((packed)); struct nd_cmd_vendor_hdr { __u32 opcode; __u32 in_length; __u8 in_buf[0]; } __attribute__((packed)); struct nd_cmd_vendor_tail { __u32 status; __u32 out_length; __u8 out_buf[0]; } __attribute__((packed)); struct nd_cmd_ars_cap { __u64 address; __u64 length; __u32 status; __u32 max_ars_out; __u32 clear_err_unit; __u16 flags; __u16 reserved; } __attribute__((packed)); struct nd_cmd_ars_start { __u64 address; __u64 length; __u16 type; __u8 flags; __u8 reserved[5]; __u32 status; __u32 scrub_time; } __attribute__((packed)); struct nd_cmd_ars_status { __u32 status; __u32 out_length; __u64 address; __u64 length; __u64 restart_address; __u64 restart_length; __u16 type; __u16 flags; __u32 num_records; struct nd_ars_record { __u32 handle; __u32 reserved; __u64 err_address; __u64 length; } __attribute__((packed)) records[0]; } __attribute__((packed)); struct nd_cmd_clear_error { __u64 address; __u64 length; __u32 status; __u8 reserved[4]; __u64 cleared; } __attribute__((packed)); enum { ND_CMD_IMPLEMENTED = 0, /* bus commands */ ND_CMD_ARS_CAP = 1, ND_CMD_ARS_START = 2, ND_CMD_ARS_STATUS = 3, ND_CMD_CLEAR_ERROR = 4, /* per-dimm commands */ ND_CMD_SMART = 1, ND_CMD_SMART_THRESHOLD = 2, ND_CMD_DIMM_FLAGS = 3, ND_CMD_GET_CONFIG_SIZE = 4, ND_CMD_GET_CONFIG_DATA = 5, ND_CMD_SET_CONFIG_DATA = 6, ND_CMD_VENDOR_EFFECT_LOG_SIZE = 7, ND_CMD_VENDOR_EFFECT_LOG = 8, ND_CMD_VENDOR = 9, ND_CMD_CALL = 10, }; enum { ND_ARS_VOLATILE = 1, ND_ARS_PERSISTENT = 2, ND_ARS_RETURN_PREV_DATA = 1 << 1, ND_CONFIG_LOCKED = 1, }; static __inline__ const char *nvdimm_bus_cmd_name(unsigned cmd) { static const char * const names[] = { [ND_CMD_ARS_CAP] = "ars_cap", [ND_CMD_ARS_START] = "ars_start", [ND_CMD_ARS_STATUS] = "ars_status", [ND_CMD_CLEAR_ERROR] = "clear_error", [ND_CMD_CALL] = "cmd_call", }; if (cmd < ARRAY_SIZE(names) && names[cmd]) return names[cmd]; return "unknown"; } static __inline__ const char *nvdimm_cmd_name(unsigned cmd) { static const char * const names[] = { [ND_CMD_SMART] = "smart", [ND_CMD_SMART_THRESHOLD] = "smart_thresh", [ND_CMD_DIMM_FLAGS] = "flags", [ND_CMD_GET_CONFIG_SIZE] = "get_size", [ND_CMD_GET_CONFIG_DATA] = "get_data", [ND_CMD_SET_CONFIG_DATA] = "set_data", [ND_CMD_VENDOR_EFFECT_LOG_SIZE] = "effect_size", [ND_CMD_VENDOR_EFFECT_LOG] = "effect_log", [ND_CMD_VENDOR] = "vendor", [ND_CMD_CALL] = "cmd_call", }; if (cmd < ARRAY_SIZE(names) && names[cmd]) return names[cmd]; return "unknown"; } #define ND_IOCTL 'N' #define ND_IOCTL_DIMM_FLAGS _IOWR(ND_IOCTL, ND_CMD_DIMM_FLAGS,\ struct nd_cmd_dimm_flags) #define ND_IOCTL_GET_CONFIG_SIZE _IOWR(ND_IOCTL, ND_CMD_GET_CONFIG_SIZE,\ struct nd_cmd_get_config_size) #define ND_IOCTL_GET_CONFIG_DATA _IOWR(ND_IOCTL, ND_CMD_GET_CONFIG_DATA,\ struct nd_cmd_get_config_data_hdr) #define ND_IOCTL_SET_CONFIG_DATA _IOWR(ND_IOCTL, ND_CMD_SET_CONFIG_DATA,\ struct nd_cmd_set_config_hdr) #define ND_IOCTL_VENDOR _IOWR(ND_IOCTL, ND_CMD_VENDOR,\ struct nd_cmd_vendor_hdr) #define ND_IOCTL_ARS_CAP _IOWR(ND_IOCTL, ND_CMD_ARS_CAP,\ struct nd_cmd_ars_cap) #define ND_IOCTL_ARS_START _IOWR(ND_IOCTL, ND_CMD_ARS_START,\ struct nd_cmd_ars_start) #define ND_IOCTL_ARS_STATUS _IOWR(ND_IOCTL, ND_CMD_ARS_STATUS,\ struct nd_cmd_ars_status) #define ND_IOCTL_CLEAR_ERROR _IOWR(ND_IOCTL, ND_CMD_CLEAR_ERROR,\ struct nd_cmd_clear_error) #define ND_DEVICE_DIMM 1 /* nd_dimm: container for "config data" */ #define ND_DEVICE_REGION_PMEM 2 /* nd_region: (parent of PMEM namespaces) */ #define ND_DEVICE_REGION_BLK 3 /* nd_region: (parent of BLK namespaces) */ #define ND_DEVICE_NAMESPACE_IO 4 /* legacy persistent memory */ #define ND_DEVICE_NAMESPACE_PMEM 5 /* PMEM namespace (may alias with BLK) */ #define ND_DEVICE_NAMESPACE_BLK 6 /* BLK namespace (may alias with PMEM) */ #define ND_DEVICE_DAX_PMEM 7 /* Device DAX interface to pmem */ enum nd_driver_flags { ND_DRIVER_DIMM = 1 << ND_DEVICE_DIMM, ND_DRIVER_REGION_PMEM = 1 << ND_DEVICE_REGION_PMEM, ND_DRIVER_REGION_BLK = 1 << ND_DEVICE_REGION_BLK, ND_DRIVER_NAMESPACE_IO = 1 << ND_DEVICE_NAMESPACE_IO, ND_DRIVER_NAMESPACE_PMEM = 1 << ND_DEVICE_NAMESPACE_PMEM, ND_DRIVER_NAMESPACE_BLK = 1 << ND_DEVICE_NAMESPACE_BLK, ND_DRIVER_DAX_PMEM = 1 << ND_DEVICE_DAX_PMEM, }; enum { ND_MIN_NAMESPACE_SIZE = PAGE_SIZE, }; enum ars_masks { ARS_STATUS_MASK = 0x0000FFFF, ARS_EXT_STATUS_SHIFT = 16, }; /* * struct nd_cmd_pkg * * is a wrapper to a quasi pass thru interface for invoking firmware * associated with nvdimms. * * INPUT PARAMETERS * * nd_family corresponds to the firmware (e.g. DSM) interface. * * nd_command are the function index advertised by the firmware. * * nd_size_in is the size of the input parameters being passed to firmware * * OUTPUT PARAMETERS * * nd_fw_size is the size of the data firmware wants to return for * the call. If nd_fw_size is greater than size of nd_size_out, only * the first nd_size_out bytes are returned. */ struct nd_cmd_pkg { __u64 nd_family; /* family of commands */ __u64 nd_command; __u32 nd_size_in; /* INPUT: size of input args */ __u32 nd_size_out; /* INPUT: size of payload */ __u32 nd_reserved2[9]; /* reserved must be zero */ __u32 nd_fw_size; /* OUTPUT: size fw wants to return */ unsigned char nd_payload[]; /* Contents of call */ }; /* These NVDIMM families represent pre-standardization command sets */ #define NVDIMM_FAMILY_INTEL 0 #define NVDIMM_FAMILY_HPE1 1 #define NVDIMM_FAMILY_HPE2 2 #define NVDIMM_FAMILY_MSFT 3 #define NVDIMM_FAMILY_HYPERV 4 #define NVDIMM_FAMILY_PAPR 5 #define ND_IOCTL_CALL _IOWR(ND_IOCTL, ND_CMD_CALL,\ struct nd_cmd_pkg) #endif /* __NDCTL_H__ */ linux/mqueue.h000064400000004231151027430560007360 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* Copyright (C) 2003 Krzysztof Benedyczak & Michal Wronski This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef _LINUX_MQUEUE_H #define _LINUX_MQUEUE_H #include #define MQ_PRIO_MAX 32768 /* per-uid limit of kernel memory used by mqueue, in bytes */ #define MQ_BYTES_MAX 819200 struct mq_attr { __kernel_long_t mq_flags; /* message queue flags */ __kernel_long_t mq_maxmsg; /* maximum number of messages */ __kernel_long_t mq_msgsize; /* maximum message size */ __kernel_long_t mq_curmsgs; /* number of messages currently queued */ __kernel_long_t __reserved[4]; /* ignored for input, zeroed for output */ }; /* * SIGEV_THREAD implementation: * SIGEV_THREAD must be implemented in user space. If SIGEV_THREAD is passed * to mq_notify, then * - sigev_signo must be the file descriptor of an AF_NETLINK socket. It's not * necessary that the socket is bound. * - sigev_value.sival_ptr must point to a cookie that is NOTIFY_COOKIE_LEN * bytes long. * If the notification is triggered, then the cookie is sent to the netlink * socket. The last byte of the cookie is replaced with the NOTIFY_?? codes: * NOTIFY_WOKENUP if the notification got triggered, NOTIFY_REMOVED if it was * removed, either due to a close() on the message queue fd or due to a * mq_notify() that removed the notification. */ #define NOTIFY_NONE 0 #define NOTIFY_WOKENUP 1 #define NOTIFY_REMOVED 2 #define NOTIFY_COOKIE_LEN 32 #endif linux/virtio_9p.h000064400000003771151027430560010013 0ustar00#ifndef _LINUX_VIRTIO_9P_H #define _LINUX_VIRTIO_9P_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include /* The feature bitmap for virtio 9P */ /* The mount point is specified in a config variable */ #define VIRTIO_9P_MOUNT_TAG 0 struct virtio_9p_config { /* length of the tag name */ __u16 tag_len; /* non-NULL terminated tag name */ __u8 tag[0]; } __attribute__((packed)); #endif /* _LINUX_VIRTIO_9P_H */ linux/nfs.h000064400000010624151027430560006650 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * NFS protocol definitions * * This file contains constants mostly for Version 2 of the protocol, * but also has a couple of NFSv3 bits in (notably the error codes). */ #ifndef _LINUX_NFS_H #define _LINUX_NFS_H #include #define NFS_PROGRAM 100003 #define NFS_PORT 2049 #define NFS_RDMA_PORT 20049 #define NFS_MAXDATA 8192 #define NFS_MAXPATHLEN 1024 #define NFS_MAXNAMLEN 255 #define NFS_MAXGROUPS 16 #define NFS_FHSIZE 32 #define NFS_COOKIESIZE 4 #define NFS_FIFO_DEV (-1) #define NFSMODE_FMT 0170000 #define NFSMODE_DIR 0040000 #define NFSMODE_CHR 0020000 #define NFSMODE_BLK 0060000 #define NFSMODE_REG 0100000 #define NFSMODE_LNK 0120000 #define NFSMODE_SOCK 0140000 #define NFSMODE_FIFO 0010000 #define NFS_MNT_PROGRAM 100005 #define NFS_MNT_VERSION 1 #define NFS_MNT3_VERSION 3 #define NFS_PIPE_DIRNAME "nfs" /* * NFS stats. The good thing with these values is that NFSv3 errors are * a superset of NFSv2 errors (with the exception of NFSERR_WFLUSH which * no-one uses anyway), so we can happily mix code as long as we make sure * no NFSv3 errors are returned to NFSv2 clients. * Error codes that have a `--' in the v2 column are not part of the * standard, but seem to be widely used nevertheless. */ enum nfs_stat { NFS_OK = 0, /* v2 v3 v4 */ NFSERR_PERM = 1, /* v2 v3 v4 */ NFSERR_NOENT = 2, /* v2 v3 v4 */ NFSERR_IO = 5, /* v2 v3 v4 */ NFSERR_NXIO = 6, /* v2 v3 v4 */ NFSERR_EAGAIN = 11, /* v2 v3 */ NFSERR_ACCES = 13, /* v2 v3 v4 */ NFSERR_EXIST = 17, /* v2 v3 v4 */ NFSERR_XDEV = 18, /* v3 v4 */ NFSERR_NODEV = 19, /* v2 v3 v4 */ NFSERR_NOTDIR = 20, /* v2 v3 v4 */ NFSERR_ISDIR = 21, /* v2 v3 v4 */ NFSERR_INVAL = 22, /* v2 v3 v4 */ NFSERR_FBIG = 27, /* v2 v3 v4 */ NFSERR_NOSPC = 28, /* v2 v3 v4 */ NFSERR_ROFS = 30, /* v2 v3 v4 */ NFSERR_MLINK = 31, /* v3 v4 */ NFSERR_OPNOTSUPP = 45, /* v2 v3 */ NFSERR_NAMETOOLONG = 63, /* v2 v3 v4 */ NFSERR_NOTEMPTY = 66, /* v2 v3 v4 */ NFSERR_DQUOT = 69, /* v2 v3 v4 */ NFSERR_STALE = 70, /* v2 v3 v4 */ NFSERR_REMOTE = 71, /* v2 v3 */ NFSERR_WFLUSH = 99, /* v2 */ NFSERR_BADHANDLE = 10001, /* v3 v4 */ NFSERR_NOT_SYNC = 10002, /* v3 */ NFSERR_BAD_COOKIE = 10003, /* v3 v4 */ NFSERR_NOTSUPP = 10004, /* v3 v4 */ NFSERR_TOOSMALL = 10005, /* v3 v4 */ NFSERR_SERVERFAULT = 10006, /* v3 v4 */ NFSERR_BADTYPE = 10007, /* v3 v4 */ NFSERR_JUKEBOX = 10008, /* v3 v4 */ NFSERR_SAME = 10009, /* v4 */ NFSERR_DENIED = 10010, /* v4 */ NFSERR_EXPIRED = 10011, /* v4 */ NFSERR_LOCKED = 10012, /* v4 */ NFSERR_GRACE = 10013, /* v4 */ NFSERR_FHEXPIRED = 10014, /* v4 */ NFSERR_SHARE_DENIED = 10015, /* v4 */ NFSERR_WRONGSEC = 10016, /* v4 */ NFSERR_CLID_INUSE = 10017, /* v4 */ NFSERR_RESOURCE = 10018, /* v4 */ NFSERR_MOVED = 10019, /* v4 */ NFSERR_NOFILEHANDLE = 10020, /* v4 */ NFSERR_MINOR_VERS_MISMATCH = 10021, /* v4 */ NFSERR_STALE_CLIENTID = 10022, /* v4 */ NFSERR_STALE_STATEID = 10023, /* v4 */ NFSERR_OLD_STATEID = 10024, /* v4 */ NFSERR_BAD_STATEID = 10025, /* v4 */ NFSERR_BAD_SEQID = 10026, /* v4 */ NFSERR_NOT_SAME = 10027, /* v4 */ NFSERR_LOCK_RANGE = 10028, /* v4 */ NFSERR_SYMLINK = 10029, /* v4 */ NFSERR_RESTOREFH = 10030, /* v4 */ NFSERR_LEASE_MOVED = 10031, /* v4 */ NFSERR_ATTRNOTSUPP = 10032, /* v4 */ NFSERR_NO_GRACE = 10033, /* v4 */ NFSERR_RECLAIM_BAD = 10034, /* v4 */ NFSERR_RECLAIM_CONFLICT = 10035,/* v4 */ NFSERR_BAD_XDR = 10036, /* v4 */ NFSERR_LOCKS_HELD = 10037, /* v4 */ NFSERR_OPENMODE = 10038, /* v4 */ NFSERR_BADOWNER = 10039, /* v4 */ NFSERR_BADCHAR = 10040, /* v4 */ NFSERR_BADNAME = 10041, /* v4 */ NFSERR_BAD_RANGE = 10042, /* v4 */ NFSERR_LOCK_NOTSUPP = 10043, /* v4 */ NFSERR_OP_ILLEGAL = 10044, /* v4 */ NFSERR_DEADLOCK = 10045, /* v4 */ NFSERR_FILE_OPEN = 10046, /* v4 */ NFSERR_ADMIN_REVOKED = 10047, /* v4 */ NFSERR_CB_PATH_DOWN = 10048, /* v4 */ }; /* NFSv2 file types - beware, these are not the same in NFSv3 */ enum nfs_ftype { NFNON = 0, NFREG = 1, NFDIR = 2, NFBLK = 3, NFCHR = 4, NFLNK = 5, NFSOCK = 6, NFBAD = 7, NFFIFO = 8 }; #endif /* _LINUX_NFS_H */ linux/virtio_fs.h000064400000001074151027430560010065 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ #ifndef _LINUX_VIRTIO_FS_H #define _LINUX_VIRTIO_FS_H #include #include #include #include struct virtio_fs_config { /* Filesystem name (UTF-8, not NUL-terminated, padded with NULs) */ __u8 tag[36]; /* Number of request queues */ __u32 num_request_queues; } __attribute__((packed)); /* For the id field in virtio_pci_shm_cap */ #define VIRTIO_FS_SHMCAP_ID_CACHE 0 #endif /* _LINUX_VIRTIO_FS_H */ linux/if_tunnel.h000064400000010640151027430560010043 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IF_TUNNEL_H_ #define _IF_TUNNEL_H_ #include #include #include #include #include #define SIOCGETTUNNEL (SIOCDEVPRIVATE + 0) #define SIOCADDTUNNEL (SIOCDEVPRIVATE + 1) #define SIOCDELTUNNEL (SIOCDEVPRIVATE + 2) #define SIOCCHGTUNNEL (SIOCDEVPRIVATE + 3) #define SIOCGETPRL (SIOCDEVPRIVATE + 4) #define SIOCADDPRL (SIOCDEVPRIVATE + 5) #define SIOCDELPRL (SIOCDEVPRIVATE + 6) #define SIOCCHGPRL (SIOCDEVPRIVATE + 7) #define SIOCGET6RD (SIOCDEVPRIVATE + 8) #define SIOCADD6RD (SIOCDEVPRIVATE + 9) #define SIOCDEL6RD (SIOCDEVPRIVATE + 10) #define SIOCCHG6RD (SIOCDEVPRIVATE + 11) #define GRE_CSUM __cpu_to_be16(0x8000) #define GRE_ROUTING __cpu_to_be16(0x4000) #define GRE_KEY __cpu_to_be16(0x2000) #define GRE_SEQ __cpu_to_be16(0x1000) #define GRE_STRICT __cpu_to_be16(0x0800) #define GRE_REC __cpu_to_be16(0x0700) #define GRE_ACK __cpu_to_be16(0x0080) #define GRE_FLAGS __cpu_to_be16(0x0078) #define GRE_VERSION __cpu_to_be16(0x0007) #define GRE_IS_CSUM(f) ((f) & GRE_CSUM) #define GRE_IS_ROUTING(f) ((f) & GRE_ROUTING) #define GRE_IS_KEY(f) ((f) & GRE_KEY) #define GRE_IS_SEQ(f) ((f) & GRE_SEQ) #define GRE_IS_STRICT(f) ((f) & GRE_STRICT) #define GRE_IS_REC(f) ((f) & GRE_REC) #define GRE_IS_ACK(f) ((f) & GRE_ACK) #define GRE_VERSION_0 __cpu_to_be16(0x0000) #define GRE_VERSION_1 __cpu_to_be16(0x0001) #define GRE_PROTO_PPP __cpu_to_be16(0x880b) #define GRE_PPTP_KEY_MASK __cpu_to_be32(0xffff) struct ip_tunnel_parm { char name[IFNAMSIZ]; int link; __be16 i_flags; __be16 o_flags; __be32 i_key; __be32 o_key; struct iphdr iph; }; enum { IFLA_IPTUN_UNSPEC, IFLA_IPTUN_LINK, IFLA_IPTUN_LOCAL, IFLA_IPTUN_REMOTE, IFLA_IPTUN_TTL, IFLA_IPTUN_TOS, IFLA_IPTUN_ENCAP_LIMIT, IFLA_IPTUN_FLOWINFO, IFLA_IPTUN_FLAGS, IFLA_IPTUN_PROTO, IFLA_IPTUN_PMTUDISC, IFLA_IPTUN_6RD_PREFIX, IFLA_IPTUN_6RD_RELAY_PREFIX, IFLA_IPTUN_6RD_PREFIXLEN, IFLA_IPTUN_6RD_RELAY_PREFIXLEN, IFLA_IPTUN_ENCAP_TYPE, IFLA_IPTUN_ENCAP_FLAGS, IFLA_IPTUN_ENCAP_SPORT, IFLA_IPTUN_ENCAP_DPORT, IFLA_IPTUN_COLLECT_METADATA, IFLA_IPTUN_FWMARK, __IFLA_IPTUN_MAX, }; #define IFLA_IPTUN_MAX (__IFLA_IPTUN_MAX - 1) enum tunnel_encap_types { TUNNEL_ENCAP_NONE, TUNNEL_ENCAP_FOU, TUNNEL_ENCAP_GUE, TUNNEL_ENCAP_MPLS, }; #define TUNNEL_ENCAP_FLAG_CSUM (1<<0) #define TUNNEL_ENCAP_FLAG_CSUM6 (1<<1) #define TUNNEL_ENCAP_FLAG_REMCSUM (1<<2) /* SIT-mode i_flags */ #define SIT_ISATAP 0x0001 struct ip_tunnel_prl { __be32 addr; __u16 flags; __u16 __reserved; __u32 datalen; __u32 __reserved2; /* data follows */ }; /* PRL flags */ #define PRL_DEFAULT 0x0001 struct ip_tunnel_6rd { struct in6_addr prefix; __be32 relay_prefix; __u16 prefixlen; __u16 relay_prefixlen; }; enum { IFLA_GRE_UNSPEC, IFLA_GRE_LINK, IFLA_GRE_IFLAGS, IFLA_GRE_OFLAGS, IFLA_GRE_IKEY, IFLA_GRE_OKEY, IFLA_GRE_LOCAL, IFLA_GRE_REMOTE, IFLA_GRE_TTL, IFLA_GRE_TOS, IFLA_GRE_PMTUDISC, IFLA_GRE_ENCAP_LIMIT, IFLA_GRE_FLOWINFO, IFLA_GRE_FLAGS, IFLA_GRE_ENCAP_TYPE, IFLA_GRE_ENCAP_FLAGS, IFLA_GRE_ENCAP_SPORT, IFLA_GRE_ENCAP_DPORT, IFLA_GRE_COLLECT_METADATA, IFLA_GRE_IGNORE_DF, IFLA_GRE_FWMARK, IFLA_GRE_ERSPAN_INDEX, IFLA_GRE_ERSPAN_VER, IFLA_GRE_ERSPAN_DIR, IFLA_GRE_ERSPAN_HWID, __IFLA_GRE_MAX, }; #define IFLA_GRE_MAX (__IFLA_GRE_MAX - 1) /* VTI-mode i_flags */ #define VTI_ISVTI ((__be16)0x0001) enum { IFLA_VTI_UNSPEC, IFLA_VTI_LINK, IFLA_VTI_IKEY, IFLA_VTI_OKEY, IFLA_VTI_LOCAL, IFLA_VTI_REMOTE, IFLA_VTI_FWMARK, __IFLA_VTI_MAX, }; #define IFLA_VTI_MAX (__IFLA_VTI_MAX - 1) #define TUNNEL_CSUM __cpu_to_be16(0x01) #define TUNNEL_ROUTING __cpu_to_be16(0x02) #define TUNNEL_KEY __cpu_to_be16(0x04) #define TUNNEL_SEQ __cpu_to_be16(0x08) #define TUNNEL_STRICT __cpu_to_be16(0x10) #define TUNNEL_REC __cpu_to_be16(0x20) #define TUNNEL_VERSION __cpu_to_be16(0x40) #define TUNNEL_NO_KEY __cpu_to_be16(0x80) #define TUNNEL_DONT_FRAGMENT __cpu_to_be16(0x0100) #define TUNNEL_OAM __cpu_to_be16(0x0200) #define TUNNEL_CRIT_OPT __cpu_to_be16(0x0400) #define TUNNEL_GENEVE_OPT __cpu_to_be16(0x0800) #define TUNNEL_VXLAN_OPT __cpu_to_be16(0x1000) #define TUNNEL_NOCACHE __cpu_to_be16(0x2000) #define TUNNEL_ERSPAN_OPT __cpu_to_be16(0x4000) #define TUNNEL_OPTIONS_PRESENT \ (TUNNEL_GENEVE_OPT | TUNNEL_VXLAN_OPT | TUNNEL_ERSPAN_OPT) #endif /* _IF_TUNNEL_H_ */ linux/wimax/i2400m.h000064400000037072151027430560010130 0ustar00/* * Intel Wireless WiMax Connection 2400m * Host-Device protocol interface definitions * * * Copyright (C) 2007-2008 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Intel Corporation * Inaky Perez-Gonzalez * - Initial implementation * * * This header defines the data structures and constants used to * communicate with the device. * * BOOTMODE/BOOTROM/FIRMWARE UPLOAD PROTOCOL * * The firmware upload protocol is quite simple and only requires a * handful of commands. See drivers/net/wimax/i2400m/fw.c for more * details. * * The BCF data structure is for the firmware file header. * * * THE DATA / CONTROL PROTOCOL * * This is the normal protocol spoken with the device once the * firmware is uploaded. It transports data payloads and control * messages back and forth. * * It consists 'messages' that pack one or more payloads each. The * format is described in detail in drivers/net/wimax/i2400m/rx.c and * tx.c. * * * THE L3L4 PROTOCOL * * The term L3L4 refers to Layer 3 (the device), Layer 4 (the * driver/host software). * * This is the control protocol used by the host to control the i2400m * device (scan, connect, disconnect...). This is sent to / received * as control frames. These frames consist of a header and zero or * more TLVs with information. We call each control frame a "message". * * Each message is composed of: * * HEADER * [TLV0 + PAYLOAD0] * [TLV1 + PAYLOAD1] * [...] * [TLVN + PAYLOADN] * * The HEADER is defined by 'struct i2400m_l3l4_hdr'. The payloads are * defined by a TLV structure (Type Length Value) which is a 'header' * (struct i2400m_tlv_hdr) and then the payload. * * All integers are represented as Little Endian. * * - REQUESTS AND EVENTS * * The requests can be clasified as follows: * * COMMAND: implies a request from the host to the device requesting * an action being performed. The device will reply with a * message (with the same type as the command), status and * no (TLV) payload. Execution of a command might cause * events (of different type) to be sent later on as * device's state changes. * * GET/SET: similar to COMMAND, but will not cause other * EVENTs. The reply, in the case of GET, will contain * TLVs with the requested information. * * EVENT: asynchronous messages sent from the device, maybe as a * consequence of previous COMMANDs but disassociated from * them. * * Only one request might be pending at the same time (ie: don't * parallelize nor post another GET request before the previous * COMMAND has been acknowledged with it's corresponding reply by the * device). * * The different requests and their formats are described below: * * I2400M_MT_* Message types * I2400M_MS_* Message status (for replies, events) * i2400m_tlv_* TLVs * * data types are named 'struct i2400m_msg_OPNAME', OPNAME matching the * operation. */ #ifndef __LINUX__WIMAX__I2400M_H__ #define __LINUX__WIMAX__I2400M_H__ #include #include /* * Host Device Interface (HDI) common to all busses */ /* Boot-mode (firmware upload mode) commands */ /* Header for the firmware file */ struct i2400m_bcf_hdr { __le32 module_type; __le32 header_len; __le32 header_version; __le32 module_id; __le32 module_vendor; __le32 date; /* BCD YYYMMDD */ __le32 size; /* in dwords */ __le32 key_size; /* in dwords */ __le32 modulus_size; /* in dwords */ __le32 exponent_size; /* in dwords */ __u8 reserved[88]; } __attribute__ ((packed)); /* Boot mode opcodes */ enum i2400m_brh_opcode { I2400M_BRH_READ = 1, I2400M_BRH_WRITE = 2, I2400M_BRH_JUMP = 3, I2400M_BRH_SIGNED_JUMP = 8, I2400M_BRH_HASH_PAYLOAD_ONLY = 9, }; /* Boot mode command masks and stuff */ enum i2400m_brh { I2400M_BRH_SIGNATURE = 0xcbbc0000, I2400M_BRH_SIGNATURE_MASK = 0xffff0000, I2400M_BRH_SIGNATURE_SHIFT = 16, I2400M_BRH_OPCODE_MASK = 0x0000000f, I2400M_BRH_RESPONSE_MASK = 0x000000f0, I2400M_BRH_RESPONSE_SHIFT = 4, I2400M_BRH_DIRECT_ACCESS = 0x00000400, I2400M_BRH_RESPONSE_REQUIRED = 0x00000200, I2400M_BRH_USE_CHECKSUM = 0x00000100, }; /** * i2400m_bootrom_header - Header for a boot-mode command * * @cmd: the above command descriptor * @target_addr: where on the device memory should the action be performed. * @data_size: for read/write, amount of data to be read/written * @block_checksum: checksum value (if applicable) * @payload: the beginning of data attached to this header */ struct i2400m_bootrom_header { __le32 command; /* Compose with enum i2400_brh */ __le32 target_addr; __le32 data_size; __le32 block_checksum; char payload[0]; } __attribute__ ((packed)); /* * Data / control protocol */ /* Packet types for the host-device interface */ enum i2400m_pt { I2400M_PT_DATA = 0, I2400M_PT_CTRL, I2400M_PT_TRACE, /* For device debug */ I2400M_PT_RESET_WARM, /* device reset */ I2400M_PT_RESET_COLD, /* USB[transport] reset, like reconnect */ I2400M_PT_EDATA, /* Extended RX data */ I2400M_PT_ILLEGAL }; /* * Payload for a data packet * * This is prefixed to each and every outgoing DATA type. */ struct i2400m_pl_data_hdr { __le32 reserved; } __attribute__((packed)); /* * Payload for an extended data packet * * New in fw v1.4 * * @reorder: if this payload has to be reorder or not (and how) * @cs: the type of data in the packet, as defined per (802.16e * T11.13.19.1). Currently only 2 (IPv4 packet) supported. * * This is prefixed to each and every INCOMING DATA packet. */ struct i2400m_pl_edata_hdr { __le32 reorder; /* bits defined in i2400m_ro */ __u8 cs; __u8 reserved[11]; } __attribute__((packed)); enum i2400m_cs { I2400M_CS_IPV4_0 = 0, I2400M_CS_IPV4 = 2, }; enum i2400m_ro { I2400M_RO_NEEDED = 0x01, I2400M_RO_TYPE = 0x03, I2400M_RO_TYPE_SHIFT = 1, I2400M_RO_CIN = 0x0f, I2400M_RO_CIN_SHIFT = 4, I2400M_RO_FBN = 0x07ff, I2400M_RO_FBN_SHIFT = 8, I2400M_RO_SN = 0x07ff, I2400M_RO_SN_SHIFT = 21, }; enum i2400m_ro_type { I2400M_RO_TYPE_RESET = 0, I2400M_RO_TYPE_PACKET, I2400M_RO_TYPE_WS, I2400M_RO_TYPE_PACKET_WS, }; /* Misc constants */ enum { I2400M_PL_ALIGN = 16, /* Payload data size alignment */ I2400M_PL_SIZE_MAX = 0x3EFF, I2400M_MAX_PLS_IN_MSG = 60, /* protocol barkers: sync sequences; for notifications they * are sent in groups of four. */ I2400M_H2D_PREVIEW_BARKER = 0xcafe900d, I2400M_COLD_RESET_BARKER = 0xc01dc01d, I2400M_WARM_RESET_BARKER = 0x50f750f7, I2400M_NBOOT_BARKER = 0xdeadbeef, I2400M_SBOOT_BARKER = 0x0ff1c1a1, I2400M_SBOOT_BARKER_6050 = 0x80000001, I2400M_ACK_BARKER = 0xfeedbabe, I2400M_D2H_MSG_BARKER = 0xbeefbabe, }; /* * Hardware payload descriptor * * Bitfields encoded in a struct to enforce typing semantics. * * Look in rx.c and tx.c for a full description of the format. */ struct i2400m_pld { __le32 val; } __attribute__ ((packed)); #define I2400M_PLD_SIZE_MASK 0x00003fff #define I2400M_PLD_TYPE_SHIFT 16 #define I2400M_PLD_TYPE_MASK 0x000f0000 /* * Header for a TX message or RX message * * @barker: preamble * @size: used for management of the FIFO queue buffer; before * sending, this is converted to be a real preamble. This * indicates the real size of the TX message that starts at this * point. If the highest bit is set, then this message is to be * skipped. * @sequence: sequence number of this message * @offset: offset where the message itself starts -- see the comments * in the file header about message header and payload descriptor * alignment. * @num_pls: number of payloads in this message * @padding: amount of padding bytes at the end of the message to make * it be of block-size aligned * * Look in rx.c and tx.c for a full description of the format. */ struct i2400m_msg_hdr { union { __le32 barker; __u32 size; /* same size type as barker!! */ }; union { __le32 sequence; __u32 offset; /* same size type as barker!! */ }; __le16 num_pls; __le16 rsv1; __le16 padding; __le16 rsv2; struct i2400m_pld pld[0]; } __attribute__ ((packed)); /* * L3/L4 control protocol */ enum { /* Interface version */ I2400M_L3L4_VERSION = 0x0100, }; /* Message types */ enum i2400m_mt { I2400M_MT_RESERVED = 0x0000, I2400M_MT_INVALID = 0xffff, I2400M_MT_REPORT_MASK = 0x8000, I2400M_MT_GET_SCAN_RESULT = 0x4202, I2400M_MT_SET_SCAN_PARAM = 0x4402, I2400M_MT_CMD_RF_CONTROL = 0x4602, I2400M_MT_CMD_SCAN = 0x4603, I2400M_MT_CMD_CONNECT = 0x4604, I2400M_MT_CMD_DISCONNECT = 0x4605, I2400M_MT_CMD_EXIT_IDLE = 0x4606, I2400M_MT_GET_LM_VERSION = 0x5201, I2400M_MT_GET_DEVICE_INFO = 0x5202, I2400M_MT_GET_LINK_STATUS = 0x5203, I2400M_MT_GET_STATISTICS = 0x5204, I2400M_MT_GET_STATE = 0x5205, I2400M_MT_GET_MEDIA_STATUS = 0x5206, I2400M_MT_SET_INIT_CONFIG = 0x5404, I2400M_MT_CMD_INIT = 0x5601, I2400M_MT_CMD_TERMINATE = 0x5602, I2400M_MT_CMD_MODE_OF_OP = 0x5603, I2400M_MT_CMD_RESET_DEVICE = 0x5604, I2400M_MT_CMD_MONITOR_CONTROL = 0x5605, I2400M_MT_CMD_ENTER_POWERSAVE = 0x5606, I2400M_MT_GET_TLS_OPERATION_RESULT = 0x6201, I2400M_MT_SET_EAP_SUCCESS = 0x6402, I2400M_MT_SET_EAP_FAIL = 0x6403, I2400M_MT_SET_EAP_KEY = 0x6404, I2400M_MT_CMD_SEND_EAP_RESPONSE = 0x6602, I2400M_MT_REPORT_SCAN_RESULT = 0xc002, I2400M_MT_REPORT_STATE = 0xd002, I2400M_MT_REPORT_POWERSAVE_READY = 0xd005, I2400M_MT_REPORT_EAP_REQUEST = 0xe002, I2400M_MT_REPORT_EAP_RESTART = 0xe003, I2400M_MT_REPORT_ALT_ACCEPT = 0xe004, I2400M_MT_REPORT_KEY_REQUEST = 0xe005, }; /* * Message Ack Status codes * * When a message is replied-to, this status is reported. */ enum i2400m_ms { I2400M_MS_DONE_OK = 0, I2400M_MS_DONE_IN_PROGRESS = 1, I2400M_MS_INVALID_OP = 2, I2400M_MS_BAD_STATE = 3, I2400M_MS_ILLEGAL_VALUE = 4, I2400M_MS_MISSING_PARAMS = 5, I2400M_MS_VERSION_ERROR = 6, I2400M_MS_ACCESSIBILITY_ERROR = 7, I2400M_MS_BUSY = 8, I2400M_MS_CORRUPTED_TLV = 9, I2400M_MS_UNINITIALIZED = 10, I2400M_MS_UNKNOWN_ERROR = 11, I2400M_MS_PRODUCTION_ERROR = 12, I2400M_MS_NO_RF = 13, I2400M_MS_NOT_READY_FOR_POWERSAVE = 14, I2400M_MS_THERMAL_CRITICAL = 15, I2400M_MS_MAX }; /** * i2400m_tlv - enumeration of the different types of TLVs * * TLVs stand for type-length-value and are the header for a payload * composed of almost anything. Each payload has a type assigned * and a length. */ enum i2400m_tlv { I2400M_TLV_L4_MESSAGE_VERSIONS = 129, I2400M_TLV_SYSTEM_STATE = 141, I2400M_TLV_MEDIA_STATUS = 161, I2400M_TLV_RF_OPERATION = 162, I2400M_TLV_RF_STATUS = 163, I2400M_TLV_DEVICE_RESET_TYPE = 132, I2400M_TLV_CONFIG_IDLE_PARAMETERS = 601, I2400M_TLV_CONFIG_IDLE_TIMEOUT = 611, I2400M_TLV_CONFIG_D2H_DATA_FORMAT = 614, I2400M_TLV_CONFIG_DL_HOST_REORDER = 615, }; struct i2400m_tlv_hdr { __le16 type; __le16 length; /* payload's */ __u8 pl[0]; } __attribute__((packed)); struct i2400m_l3l4_hdr { __le16 type; __le16 length; /* payload's */ __le16 version; __le16 resv1; __le16 status; __le16 resv2; struct i2400m_tlv_hdr pl[0]; } __attribute__((packed)); /** * i2400m_system_state - different states of the device */ enum i2400m_system_state { I2400M_SS_UNINITIALIZED = 1, I2400M_SS_INIT, I2400M_SS_READY, I2400M_SS_SCAN, I2400M_SS_STANDBY, I2400M_SS_CONNECTING, I2400M_SS_WIMAX_CONNECTED, I2400M_SS_DATA_PATH_CONNECTED, I2400M_SS_IDLE, I2400M_SS_DISCONNECTING, I2400M_SS_OUT_OF_ZONE, I2400M_SS_SLEEPACTIVE, I2400M_SS_PRODUCTION, I2400M_SS_CONFIG, I2400M_SS_RF_OFF, I2400M_SS_RF_SHUTDOWN, I2400M_SS_DEVICE_DISCONNECT, I2400M_SS_MAX, }; /** * i2400m_tlv_system_state - report on the state of the system * * @state: see enum i2400m_system_state */ struct i2400m_tlv_system_state { struct i2400m_tlv_hdr hdr; __le32 state; } __attribute__((packed)); struct i2400m_tlv_l4_message_versions { struct i2400m_tlv_hdr hdr; __le16 major; __le16 minor; __le16 branch; __le16 reserved; } __attribute__((packed)); struct i2400m_tlv_detailed_device_info { struct i2400m_tlv_hdr hdr; __u8 reserved1[400]; __u8 mac_address[ETH_ALEN]; __u8 reserved2[2]; } __attribute__((packed)); enum i2400m_rf_switch_status { I2400M_RF_SWITCH_ON = 1, I2400M_RF_SWITCH_OFF = 2, }; struct i2400m_tlv_rf_switches_status { struct i2400m_tlv_hdr hdr; __u8 sw_rf_switch; /* 1 ON, 2 OFF */ __u8 hw_rf_switch; /* 1 ON, 2 OFF */ __u8 reserved[2]; } __attribute__((packed)); enum { i2400m_rf_operation_on = 1, i2400m_rf_operation_off = 2 }; struct i2400m_tlv_rf_operation { struct i2400m_tlv_hdr hdr; __le32 status; /* 1 ON, 2 OFF */ } __attribute__((packed)); enum i2400m_tlv_reset_type { I2400M_RESET_TYPE_COLD = 1, I2400M_RESET_TYPE_WARM }; struct i2400m_tlv_device_reset_type { struct i2400m_tlv_hdr hdr; __le32 reset_type; } __attribute__((packed)); struct i2400m_tlv_config_idle_parameters { struct i2400m_tlv_hdr hdr; __le32 idle_timeout; /* 100 to 300000 ms [5min], 100 increments * 0 disabled */ __le32 idle_paging_interval; /* frames */ } __attribute__((packed)); enum i2400m_media_status { I2400M_MEDIA_STATUS_LINK_UP = 1, I2400M_MEDIA_STATUS_LINK_DOWN, I2400M_MEDIA_STATUS_LINK_RENEW, }; struct i2400m_tlv_media_status { struct i2400m_tlv_hdr hdr; __le32 media_status; } __attribute__((packed)); /* New in v1.4 */ struct i2400m_tlv_config_idle_timeout { struct i2400m_tlv_hdr hdr; __le32 timeout; /* 100 to 300000 ms [5min], 100 increments * 0 disabled */ } __attribute__((packed)); /* New in v1.4 -- for backward compat, will be removed */ struct i2400m_tlv_config_d2h_data_format { struct i2400m_tlv_hdr hdr; __u8 format; /* 0 old format, 1 enhanced */ __u8 reserved[3]; } __attribute__((packed)); /* New in v1.4 */ struct i2400m_tlv_config_dl_host_reorder { struct i2400m_tlv_hdr hdr; __u8 reorder; /* 0 disabled, 1 enabled */ __u8 reserved[3]; } __attribute__((packed)); #endif /* #ifndef __LINUX__WIMAX__I2400M_H__ */ linux/dlm_netlink.h000064400000002207151027430560010360 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2007 Red Hat, Inc. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License v.2. */ #ifndef _DLM_NETLINK_H #define _DLM_NETLINK_H #include #include enum { DLM_STATUS_WAITING = 1, DLM_STATUS_GRANTED = 2, DLM_STATUS_CONVERT = 3, }; #define DLM_LOCK_DATA_VERSION 1 struct dlm_lock_data { __u16 version; __u32 lockspace_id; int nodeid; int ownpid; __u32 id; __u32 remid; __u64 xid; __s8 status; __s8 grmode; __s8 rqmode; unsigned long timestamp; int resource_namelen; char resource_name[DLM_RESNAME_MAXLEN]; }; enum { DLM_CMD_UNSPEC = 0, DLM_CMD_HELLO, /* user->kernel */ DLM_CMD_TIMEOUT, /* kernel->user */ __DLM_CMD_MAX, }; #define DLM_CMD_MAX (__DLM_CMD_MAX - 1) enum { DLM_TYPE_UNSPEC = 0, DLM_TYPE_LOCK, __DLM_TYPE_MAX, }; #define DLM_TYPE_MAX (__DLM_TYPE_MAX - 1) #define DLM_GENL_VERSION 0x1 #define DLM_GENL_NAME "DLM" #endif /* _DLM_NETLINK_H */ linux/hsr_netlink.h000064400000002071151027430560010377 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright 2011-2013 Autronica Fire and Security AS * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * Author(s): * 2011-2013 Arvid Brodin, arvid.brodin@xdin.com */ #ifndef __UAPI_HSR_NETLINK_H #define __UAPI_HSR_NETLINK_H /* Generic Netlink HSR family definition */ /* attributes */ enum { HSR_A_UNSPEC, HSR_A_NODE_ADDR, HSR_A_IFINDEX, HSR_A_IF1_AGE, HSR_A_IF2_AGE, HSR_A_NODE_ADDR_B, HSR_A_IF1_SEQ, HSR_A_IF2_SEQ, HSR_A_IF1_IFINDEX, HSR_A_IF2_IFINDEX, HSR_A_ADDR_B_IFINDEX, __HSR_A_MAX, }; #define HSR_A_MAX (__HSR_A_MAX - 1) /* commands */ enum { HSR_C_UNSPEC, HSR_C_RING_ERROR, HSR_C_NODE_DOWN, HSR_C_GET_NODE_STATUS, HSR_C_SET_NODE_STATUS, HSR_C_GET_NODE_LIST, HSR_C_SET_NODE_LIST, __HSR_C_MAX, }; #define HSR_C_MAX (__HSR_C_MAX - 1) #endif /* __UAPI_HSR_NETLINK_H */ linux/serial_core.h000064400000014145151027430560010353 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * linux/drivers/char/serial_core.h * * Copyright (C) 2000 Deep Blue Solutions Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef LINUX_SERIAL_CORE_H #define LINUX_SERIAL_CORE_H #include /* * The type definitions. These are from Ted Ts'o's serial.h */ #define PORT_UNKNOWN 0 #define PORT_8250 1 #define PORT_16450 2 #define PORT_16550 3 #define PORT_16550A 4 #define PORT_CIRRUS 5 #define PORT_16650 6 #define PORT_16650V2 7 #define PORT_16750 8 #define PORT_STARTECH 9 #define PORT_16C950 10 #define PORT_16654 11 #define PORT_16850 12 #define PORT_RSA 13 #define PORT_NS16550A 14 #define PORT_XSCALE 15 #define PORT_RM9000 16 /* PMC-Sierra RM9xxx internal UART */ #define PORT_OCTEON 17 /* Cavium OCTEON internal UART */ #define PORT_AR7 18 /* Texas Instruments AR7 internal UART */ #define PORT_U6_16550A 19 /* ST-Ericsson U6xxx internal UART */ #define PORT_TEGRA 20 /* NVIDIA Tegra internal UART */ #define PORT_XR17D15X 21 /* Exar XR17D15x UART */ #define PORT_LPC3220 22 /* NXP LPC32xx SoC "Standard" UART */ #define PORT_8250_CIR 23 /* CIR infrared port, has its own driver */ #define PORT_XR17V35X 24 /* Exar XR17V35x UARTs */ #define PORT_BRCM_TRUMANAGE 25 #define PORT_ALTR_16550_F32 26 /* Altera 16550 UART with 32 FIFOs */ #define PORT_ALTR_16550_F64 27 /* Altera 16550 UART with 64 FIFOs */ #define PORT_ALTR_16550_F128 28 /* Altera 16550 UART with 128 FIFOs */ #define PORT_RT2880 29 /* Ralink RT2880 internal UART */ #define PORT_16550A_FSL64 30 /* Freescale 16550 UART with 64 FIFOs */ /* * ARM specific type numbers. These are not currently guaranteed * to be implemented, and will change in the future. These are * separate so any additions to the old serial.c that occur before * we are merged can be easily merged here. */ #define PORT_PXA 31 #define PORT_AMBA 32 #define PORT_CLPS711X 33 #define PORT_SA1100 34 #define PORT_UART00 35 #define PORT_OWL 36 #define PORT_21285 37 /* Sparc type numbers. */ #define PORT_SUNZILOG 38 #define PORT_SUNSAB 39 /* Nuvoton UART */ #define PORT_NPCM 40 /* Intel EG20 */ #define PORT_PCH_8LINE 44 #define PORT_PCH_2LINE 45 /* DEC */ #define PORT_DZ 46 #define PORT_ZS 47 /* Parisc type numbers. */ #define PORT_MUX 48 /* Atmel AT91 SoC */ #define PORT_ATMEL 49 /* Macintosh Zilog type numbers */ #define PORT_MAC_ZILOG 50 /* m68k : not yet implemented */ #define PORT_PMAC_ZILOG 51 /* SH-SCI */ #define PORT_SCI 52 #define PORT_SCIF 53 #define PORT_IRDA 54 /* Samsung S3C2410 SoC and derivatives thereof */ #define PORT_S3C2410 55 /* SGI IP22 aka Indy / Challenge S / Indigo 2 */ #define PORT_IP22ZILOG 56 /* Sharp LH7a40x -- an ARM9 SoC series */ #define PORT_LH7A40X 57 /* PPC CPM type number */ #define PORT_CPM 58 /* MPC52xx (and MPC512x) type numbers */ #define PORT_MPC52xx 59 /* IBM icom */ #define PORT_ICOM 60 /* Samsung S3C2440 SoC */ #define PORT_S3C2440 61 /* Motorola i.MX SoC */ #define PORT_IMX 62 /* Marvell MPSC */ #define PORT_MPSC 63 /* TXX9 type number */ #define PORT_TXX9 64 /* NEC VR4100 series SIU/DSIU */ #define PORT_VR41XX_SIU 65 #define PORT_VR41XX_DSIU 66 /* Samsung S3C2400 SoC */ #define PORT_S3C2400 67 /* M32R SIO */ #define PORT_M32R_SIO 68 /*Digi jsm */ #define PORT_JSM 69 #define PORT_PNX8XXX 70 /* Hilscher netx */ #define PORT_NETX 71 /* SUN4V Hypervisor Console */ #define PORT_SUNHV 72 #define PORT_S3C2412 73 /* Xilinx uartlite */ #define PORT_UARTLITE 74 /* Blackfin bf5xx */ #define PORT_BFIN 75 /* Micrel KS8695 */ #define PORT_KS8695 76 /* Broadcom SB1250, etc. SOC */ #define PORT_SB1250_DUART 77 /* Freescale ColdFire */ #define PORT_MCF 78 /* Blackfin SPORT */ #define PORT_BFIN_SPORT 79 /* MN10300 on-chip UART numbers */ #define PORT_MN10300 80 #define PORT_MN10300_CTS 81 #define PORT_SC26XX 82 /* SH-SCI */ #define PORT_SCIFA 83 #define PORT_S3C6400 84 /* NWPSERIAL, now removed */ #define PORT_NWPSERIAL 85 /* MAX3100 */ #define PORT_MAX3100 86 /* Timberdale UART */ #define PORT_TIMBUART 87 /* Qualcomm MSM SoCs */ #define PORT_MSM 88 /* BCM63xx family SoCs */ #define PORT_BCM63XX 89 /* Aeroflex Gaisler GRLIB APBUART */ #define PORT_APBUART 90 /* Altera UARTs */ #define PORT_ALTERA_JTAGUART 91 #define PORT_ALTERA_UART 92 /* SH-SCI */ #define PORT_SCIFB 93 /* MAX310X */ #define PORT_MAX310X 94 /* TI DA8xx/66AK2x */ #define PORT_DA830 95 /* TI OMAP-UART */ #define PORT_OMAP 96 /* VIA VT8500 SoC */ #define PORT_VT8500 97 /* Cadence (Xilinx Zynq) UART */ #define PORT_XUARTPS 98 /* Atheros AR933X SoC */ #define PORT_AR933X 99 /* Energy Micro efm32 SoC */ #define PORT_EFMUART 100 /* ARC (Synopsys) on-chip UART */ #define PORT_ARC 101 /* Rocketport EXPRESS/INFINITY */ #define PORT_RP2 102 /* Freescale lpuart */ #define PORT_LPUART 103 /* SH-SCI */ #define PORT_HSCIF 104 /* ST ASC type numbers */ #define PORT_ASC 105 /* Tilera TILE-Gx UART */ #define PORT_TILEGX 106 /* MEN 16z135 UART */ #define PORT_MEN_Z135 107 /* SC16IS74xx */ #define PORT_SC16IS7XX 108 /* MESON */ #define PORT_MESON 109 /* Conexant Digicolor */ #define PORT_DIGICOLOR 110 /* SPRD SERIAL */ #define PORT_SPRD 111 /* Cris v10 / v32 SoC */ #define PORT_CRIS 112 /* STM32 USART */ #define PORT_STM32 113 /* MVEBU UART */ #define PORT_MVEBU 114 /* Microchip PIC32 UART */ #define PORT_PIC32 115 /* MPS2 UART */ #define PORT_MPS2UART 116 /* MediaTek BTIF */ #define PORT_MTK_BTIF 117 /* Sunix UART */ #define PORT_SUNIX 121 #endif /* LINUX_SERIAL_CORE_H */ linux/vt.h000064400000005763151027430560006523 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_VT_H #define _LINUX_VT_H /* * These constants are also useful for user-level apps (e.g., VC * resizing). */ #define MIN_NR_CONSOLES 1 /* must be at least 1 */ #define MAX_NR_CONSOLES 63 /* serial lines start at 64 */ /* Note: the ioctl VT_GETSTATE does not work for consoles 16 and higher (since it returns a short) */ /* 0x56 is 'V', to avoid collision with termios and kd */ #define VT_OPENQRY 0x5600 /* find available vt */ struct vt_mode { char mode; /* vt mode */ char waitv; /* if set, hang on writes if not active */ short relsig; /* signal to raise on release req */ short acqsig; /* signal to raise on acquisition */ short frsig; /* unused (set to 0) */ }; #define VT_GETMODE 0x5601 /* get mode of active vt */ #define VT_SETMODE 0x5602 /* set mode of active vt */ #define VT_AUTO 0x00 /* auto vt switching */ #define VT_PROCESS 0x01 /* process controls switching */ #define VT_ACKACQ 0x02 /* acknowledge switch */ struct vt_stat { unsigned short v_active; /* active vt */ unsigned short v_signal; /* signal to send */ unsigned short v_state; /* vt bitmask */ }; #define VT_GETSTATE 0x5603 /* get global vt state info */ #define VT_SENDSIG 0x5604 /* signal to send to bitmask of vts */ #define VT_RELDISP 0x5605 /* release display */ #define VT_ACTIVATE 0x5606 /* make vt active */ #define VT_WAITACTIVE 0x5607 /* wait for vt active */ #define VT_DISALLOCATE 0x5608 /* free memory associated to vt */ struct vt_sizes { unsigned short v_rows; /* number of rows */ unsigned short v_cols; /* number of columns */ unsigned short v_scrollsize; /* number of lines of scrollback */ }; #define VT_RESIZE 0x5609 /* set kernel's idea of screensize */ struct vt_consize { unsigned short v_rows; /* number of rows */ unsigned short v_cols; /* number of columns */ unsigned short v_vlin; /* number of pixel rows on screen */ unsigned short v_clin; /* number of pixel rows per character */ unsigned short v_vcol; /* number of pixel columns on screen */ unsigned short v_ccol; /* number of pixel columns per character */ }; #define VT_RESIZEX 0x560A /* set kernel's idea of screensize + more */ #define VT_LOCKSWITCH 0x560B /* disallow vt switching */ #define VT_UNLOCKSWITCH 0x560C /* allow vt switching */ #define VT_GETHIFONTMASK 0x560D /* return hi font mask */ struct vt_event { unsigned int event; #define VT_EVENT_SWITCH 0x0001 /* Console switch */ #define VT_EVENT_BLANK 0x0002 /* Screen blank */ #define VT_EVENT_UNBLANK 0x0004 /* Screen unblank */ #define VT_EVENT_RESIZE 0x0008 /* Resize display */ #define VT_MAX_EVENT 0x000F unsigned int oldev; /* Old console */ unsigned int newev; /* New console (if changing) */ unsigned int pad[4]; /* Padding for expansion */ }; #define VT_WAITEVENT 0x560E /* Wait for an event */ struct vt_setactivate { unsigned int console; struct vt_mode mode; }; #define VT_SETACTIVATE 0x560F /* Activate and set the mode of a console */ #endif /* _LINUX_VT_H */ linux/time.h000064400000003324151027430560007017 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TIME_H #define _LINUX_TIME_H #include #include #ifndef _STRUCT_TIMESPEC #define _STRUCT_TIMESPEC struct timespec { __kernel_time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; #endif struct timeval { __kernel_time_t tv_sec; /* seconds */ __kernel_suseconds_t tv_usec; /* microseconds */ }; struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of dst correction */ }; /* * Names of the interval timers, and structure * defining a timer setting: */ #define ITIMER_REAL 0 #define ITIMER_VIRTUAL 1 #define ITIMER_PROF 2 struct itimerspec { struct timespec it_interval; /* timer period */ struct timespec it_value; /* timer expiration */ }; struct itimerval { struct timeval it_interval; /* timer interval */ struct timeval it_value; /* current value */ }; /* * The IDs of the various system clocks (for POSIX.1b interval timers): */ #define CLOCK_REALTIME 0 #define CLOCK_MONOTONIC 1 #define CLOCK_PROCESS_CPUTIME_ID 2 #define CLOCK_THREAD_CPUTIME_ID 3 #define CLOCK_MONOTONIC_RAW 4 #define CLOCK_REALTIME_COARSE 5 #define CLOCK_MONOTONIC_COARSE 6 #define CLOCK_BOOTTIME 7 #define CLOCK_REALTIME_ALARM 8 #define CLOCK_BOOTTIME_ALARM 9 /* * The driver implementing this got removed. The clock ID is kept as a * place holder. Do not reuse! */ #define CLOCK_SGI_CYCLE 10 #define CLOCK_TAI 11 #define MAX_CLOCKS 16 #define CLOCKS_MASK (CLOCK_REALTIME | CLOCK_MONOTONIC) #define CLOCKS_MONO CLOCK_MONOTONIC /* * The various flags for setting POSIX.1b interval timers: */ #define TIMER_ABSTIME 0x01 #endif /* _LINUX_TIME_H */ linux/userio.h000064400000002754151027430560007375 0ustar00/* SPDX-License-Identifier: LGPL-2.0+ WITH Linux-syscall-note */ /* * userio: virtual serio device support * Copyright (C) 2015 Red Hat * Copyright (C) 2015 Lyude (Stephen Chandler Paul) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * This is the public header used for user-space communication with the userio * driver. __attribute__((__packed__)) is used for all structs to keep ABI * compatibility between all architectures. */ #ifndef _USERIO_H #define _USERIO_H #include enum userio_cmd_type { USERIO_CMD_REGISTER = 0, USERIO_CMD_SET_PORT_TYPE = 1, USERIO_CMD_SEND_INTERRUPT = 2 }; /* * userio Commands * All commands sent to /dev/userio are encoded using this structure. The type * field should contain a USERIO_CMD* value that indicates what kind of command * is being sent to userio. The data field should contain the accompanying * argument for the command, if there is one. */ struct userio_cmd { __u8 type; __u8 data; } __attribute__((__packed__)); #endif /* !_USERIO_H */ linux/if_vlan.h000064400000003447151027430560007505 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * VLAN An implementation of 802.1Q VLAN tagging. * * Authors: Ben Greear * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #ifndef _LINUX_IF_VLAN_H_ #define _LINUX_IF_VLAN_H_ /* VLAN IOCTLs are found in sockios.h */ /* Passed in vlan_ioctl_args structure to determine behaviour. */ enum vlan_ioctl_cmds { ADD_VLAN_CMD, DEL_VLAN_CMD, SET_VLAN_INGRESS_PRIORITY_CMD, SET_VLAN_EGRESS_PRIORITY_CMD, GET_VLAN_INGRESS_PRIORITY_CMD, GET_VLAN_EGRESS_PRIORITY_CMD, SET_VLAN_NAME_TYPE_CMD, SET_VLAN_FLAG_CMD, GET_VLAN_REALDEV_NAME_CMD, /* If this works, you know it's a VLAN device, btw */ GET_VLAN_VID_CMD /* Get the VID of this VLAN (specified by name) */ }; enum vlan_flags { VLAN_FLAG_REORDER_HDR = 0x1, VLAN_FLAG_GVRP = 0x2, VLAN_FLAG_LOOSE_BINDING = 0x4, VLAN_FLAG_MVRP = 0x8, VLAN_FLAG_BRIDGE_BINDING = 0x10, }; enum vlan_name_types { VLAN_NAME_TYPE_PLUS_VID, /* Name will look like: vlan0005 */ VLAN_NAME_TYPE_RAW_PLUS_VID, /* name will look like: eth1.0005 */ VLAN_NAME_TYPE_PLUS_VID_NO_PAD, /* Name will look like: vlan5 */ VLAN_NAME_TYPE_RAW_PLUS_VID_NO_PAD, /* Name will look like: eth0.5 */ VLAN_NAME_TYPE_HIGHEST }; struct vlan_ioctl_args { int cmd; /* Should be one of the vlan_ioctl_cmds enum above. */ char device1[24]; union { char device2[24]; int VID; unsigned int skb_priority; unsigned int name_type; unsigned int bind_type; unsigned int flag; /* Matches vlan_dev_priv flags */ } u; short vlan_qos; }; #endif /* _LINUX_IF_VLAN_H_ */ linux/usbdevice_fs.h000064400000020175151027430560010525 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /*****************************************************************************/ /* * usbdevice_fs.h -- USB device file system. * * Copyright (C) 2000 * Thomas Sailer (sailer@ife.ee.ethz.ch) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * History: * 0.1 04.01.2000 Created */ /*****************************************************************************/ #ifndef _LINUX_USBDEVICE_FS_H #define _LINUX_USBDEVICE_FS_H #include #include /* --------------------------------------------------------------------- */ /* usbdevfs ioctl codes */ struct usbdevfs_ctrltransfer { __u8 bRequestType; __u8 bRequest; __u16 wValue; __u16 wIndex; __u16 wLength; __u32 timeout; /* in milliseconds */ void *data; }; struct usbdevfs_bulktransfer { unsigned int ep; unsigned int len; unsigned int timeout; /* in milliseconds */ void *data; }; struct usbdevfs_setinterface { unsigned int interface; unsigned int altsetting; }; struct usbdevfs_disconnectsignal { unsigned int signr; void *context; }; #define USBDEVFS_MAXDRIVERNAME 255 struct usbdevfs_getdriver { unsigned int interface; char driver[USBDEVFS_MAXDRIVERNAME + 1]; }; struct usbdevfs_connectinfo { unsigned int devnum; unsigned char slow; }; struct usbdevfs_conninfo_ex { __u32 size; /* Size of the structure from the kernel's */ /* point of view. Can be used by userspace */ /* to determine how much data can be */ /* used/trusted. */ __u32 busnum; /* USB bus number, as enumerated by the */ /* kernel, the device is connected to. */ __u32 devnum; /* Device address on the bus. */ __u32 speed; /* USB_SPEED_* constants from ch9.h */ __u8 num_ports; /* Number of ports the device is connected */ /* to on the way to the root hub. It may */ /* be bigger than size of 'ports' array so */ /* userspace can detect overflows. */ __u8 ports[7]; /* List of ports on the way from the root */ /* hub to the device. Current limit in */ /* USB specification is 7 tiers (root hub, */ /* 5 intermediate hubs, device), which */ /* gives at most 6 port entries. */ }; #define USBDEVFS_URB_SHORT_NOT_OK 0x01 #define USBDEVFS_URB_ISO_ASAP 0x02 #define USBDEVFS_URB_BULK_CONTINUATION 0x04 #define USBDEVFS_URB_NO_FSBR 0x20 /* Not used */ #define USBDEVFS_URB_ZERO_PACKET 0x40 #define USBDEVFS_URB_NO_INTERRUPT 0x80 #define USBDEVFS_URB_TYPE_ISO 0 #define USBDEVFS_URB_TYPE_INTERRUPT 1 #define USBDEVFS_URB_TYPE_CONTROL 2 #define USBDEVFS_URB_TYPE_BULK 3 struct usbdevfs_iso_packet_desc { unsigned int length; unsigned int actual_length; unsigned int status; }; struct usbdevfs_urb { unsigned char type; unsigned char endpoint; int status; unsigned int flags; void *buffer; int buffer_length; int actual_length; int start_frame; union { int number_of_packets; /* Only used for isoc urbs */ unsigned int stream_id; /* Only used with bulk streams */ }; int error_count; unsigned int signr; /* signal to be sent on completion, or 0 if none should be sent. */ void *usercontext; struct usbdevfs_iso_packet_desc iso_frame_desc[0]; }; /* ioctls for talking directly to drivers */ struct usbdevfs_ioctl { int ifno; /* interface 0..N ; negative numbers reserved */ int ioctl_code; /* MUST encode size + direction of data so the * macros in give correct values */ void *data; /* param buffer (in, or out) */ }; /* You can do most things with hubs just through control messages, * except find out what device connects to what port. */ struct usbdevfs_hub_portinfo { char nports; /* number of downstream ports in this hub */ char port [127]; /* e.g. port 3 connects to device 27 */ }; /* System and bus capability flags */ #define USBDEVFS_CAP_ZERO_PACKET 0x01 #define USBDEVFS_CAP_BULK_CONTINUATION 0x02 #define USBDEVFS_CAP_NO_PACKET_SIZE_LIM 0x04 #define USBDEVFS_CAP_BULK_SCATTER_GATHER 0x08 #define USBDEVFS_CAP_REAP_AFTER_DISCONNECT 0x10 #define USBDEVFS_CAP_MMAP 0x20 #define USBDEVFS_CAP_DROP_PRIVILEGES 0x40 #define USBDEVFS_CAP_CONNINFO_EX 0x80 #define USBDEVFS_CAP_SUSPEND 0x100 /* USBDEVFS_DISCONNECT_CLAIM flags & struct */ /* disconnect-and-claim if the driver matches the driver field */ #define USBDEVFS_DISCONNECT_CLAIM_IF_DRIVER 0x01 /* disconnect-and-claim except when the driver matches the driver field */ #define USBDEVFS_DISCONNECT_CLAIM_EXCEPT_DRIVER 0x02 struct usbdevfs_disconnect_claim { unsigned int interface; unsigned int flags; char driver[USBDEVFS_MAXDRIVERNAME + 1]; }; struct usbdevfs_streams { unsigned int num_streams; /* Not used by USBDEVFS_FREE_STREAMS */ unsigned int num_eps; unsigned char eps[0]; }; /* * USB_SPEED_* values returned by USBDEVFS_GET_SPEED are defined in * linux/usb/ch9.h */ #define USBDEVFS_CONTROL _IOWR('U', 0, struct usbdevfs_ctrltransfer) #define USBDEVFS_CONTROL32 _IOWR('U', 0, struct usbdevfs_ctrltransfer32) #define USBDEVFS_BULK _IOWR('U', 2, struct usbdevfs_bulktransfer) #define USBDEVFS_BULK32 _IOWR('U', 2, struct usbdevfs_bulktransfer32) #define USBDEVFS_RESETEP _IOR('U', 3, unsigned int) #define USBDEVFS_SETINTERFACE _IOR('U', 4, struct usbdevfs_setinterface) #define USBDEVFS_SETCONFIGURATION _IOR('U', 5, unsigned int) #define USBDEVFS_GETDRIVER _IOW('U', 8, struct usbdevfs_getdriver) #define USBDEVFS_SUBMITURB _IOR('U', 10, struct usbdevfs_urb) #define USBDEVFS_SUBMITURB32 _IOR('U', 10, struct usbdevfs_urb32) #define USBDEVFS_DISCARDURB _IO('U', 11) #define USBDEVFS_REAPURB _IOW('U', 12, void *) #define USBDEVFS_REAPURB32 _IOW('U', 12, __u32) #define USBDEVFS_REAPURBNDELAY _IOW('U', 13, void *) #define USBDEVFS_REAPURBNDELAY32 _IOW('U', 13, __u32) #define USBDEVFS_DISCSIGNAL _IOR('U', 14, struct usbdevfs_disconnectsignal) #define USBDEVFS_DISCSIGNAL32 _IOR('U', 14, struct usbdevfs_disconnectsignal32) #define USBDEVFS_CLAIMINTERFACE _IOR('U', 15, unsigned int) #define USBDEVFS_RELEASEINTERFACE _IOR('U', 16, unsigned int) #define USBDEVFS_CONNECTINFO _IOW('U', 17, struct usbdevfs_connectinfo) #define USBDEVFS_IOCTL _IOWR('U', 18, struct usbdevfs_ioctl) #define USBDEVFS_IOCTL32 _IOWR('U', 18, struct usbdevfs_ioctl32) #define USBDEVFS_HUB_PORTINFO _IOR('U', 19, struct usbdevfs_hub_portinfo) #define USBDEVFS_RESET _IO('U', 20) #define USBDEVFS_CLEAR_HALT _IOR('U', 21, unsigned int) #define USBDEVFS_DISCONNECT _IO('U', 22) #define USBDEVFS_CONNECT _IO('U', 23) #define USBDEVFS_CLAIM_PORT _IOR('U', 24, unsigned int) #define USBDEVFS_RELEASE_PORT _IOR('U', 25, unsigned int) #define USBDEVFS_GET_CAPABILITIES _IOR('U', 26, __u32) #define USBDEVFS_DISCONNECT_CLAIM _IOR('U', 27, struct usbdevfs_disconnect_claim) #define USBDEVFS_ALLOC_STREAMS _IOR('U', 28, struct usbdevfs_streams) #define USBDEVFS_FREE_STREAMS _IOR('U', 29, struct usbdevfs_streams) #define USBDEVFS_DROP_PRIVILEGES _IOW('U', 30, __u32) #define USBDEVFS_GET_SPEED _IO('U', 31) /* * Returns struct usbdevfs_conninfo_ex; length is variable to allow * extending size of the data returned. */ #define USBDEVFS_CONNINFO_EX(len) _IOC(_IOC_READ, 'U', 32, len) #define USBDEVFS_FORBID_SUSPEND _IO('U', 33) #define USBDEVFS_ALLOW_SUSPEND _IO('U', 34) #define USBDEVFS_WAIT_FOR_RESUME _IO('U', 35) #endif /* _LINUX_USBDEVICE_FS_H */ linux/auxvec.h000064400000003075151027430560007357 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_AUXVEC_H #define _LINUX_AUXVEC_H #include /* Symbolic values for the entries in the auxiliary table put on the initial stack */ #define AT_NULL 0 /* end of vector */ #define AT_IGNORE 1 /* entry should be ignored */ #define AT_EXECFD 2 /* file descriptor of program */ #define AT_PHDR 3 /* program headers for program */ #define AT_PHENT 4 /* size of program header entry */ #define AT_PHNUM 5 /* number of program headers */ #define AT_PAGESZ 6 /* system page size */ #define AT_BASE 7 /* base address of interpreter */ #define AT_FLAGS 8 /* flags */ #define AT_ENTRY 9 /* entry point of program */ #define AT_NOTELF 10 /* program is not ELF */ #define AT_UID 11 /* real uid */ #define AT_EUID 12 /* effective uid */ #define AT_GID 13 /* real gid */ #define AT_EGID 14 /* effective gid */ #define AT_PLATFORM 15 /* string identifying CPU for optimizations */ #define AT_HWCAP 16 /* arch dependent hints at CPU capabilities */ #define AT_CLKTCK 17 /* frequency at which times() increments */ /* AT_* values 18 through 22 are reserved */ #define AT_SECURE 23 /* secure mode boolean */ #define AT_BASE_PLATFORM 24 /* string identifying real platform, may * differ from AT_PLATFORM. */ #define AT_RANDOM 25 /* address of 16 random bytes */ #define AT_HWCAP2 26 /* extension of AT_HWCAP */ #define AT_EXECFN 31 /* filename of program */ #ifndef AT_MINSIGSTKSZ #define AT_MINSIGSTKSZ 51 /* minimal stack size for signal delivery */ #endif #endif /* _LINUX_AUXVEC_H */ linux/timex.h000064400000014403151027430560007207 0ustar00/***************************************************************************** * * * Copyright (c) David L. Mills 1993 * * * * Permission to use, copy, modify, and distribute this software and its * * documentation for any purpose and without fee is hereby granted, provided * * that the above copyright notice appears in all copies and that both the * * copyright notice and this permission notice appear in supporting * * documentation, and that the name University of Delaware not be used in * * advertising or publicity pertaining to distribution of the software * * without specific, written prior permission. The University of Delaware * * makes no representations about the suitability this software for any * * purpose. It is provided "as is" without express or implied warranty. * * * *****************************************************************************/ /* * Modification history timex.h * * 29 Dec 97 Russell King * Moved CLOCK_TICK_RATE, CLOCK_TICK_FACTOR and FINETUNE to asm/timex.h * for ARM machines * * 9 Jan 97 Adrian Sun * Shifted LATCH define to allow access to alpha machines. * * 26 Sep 94 David L. Mills * Added defines for hybrid phase/frequency-lock loop. * * 19 Mar 94 David L. Mills * Moved defines from kernel routines to header file and added new * defines for PPS phase-lock loop. * * 20 Feb 94 David L. Mills * Revised status codes and structures for external clock and PPS * signal discipline. * * 28 Nov 93 David L. Mills * Adjusted parameters to improve stability and increase poll * interval. * * 17 Sep 93 David L. Mills * Created file $NTP/include/sys/timex.h * 07 Oct 93 Torsten Duwe * Derived linux/timex.h * 1995-08-13 Torsten Duwe * kernel PLL updated to 1994-12-13 specs (rfc-1589) * 1997-08-30 Ulrich Windl * Added new constant NTP_PHASE_LIMIT * 2004-08-12 Christoph Lameter * Reworked time interpolation logic */ #ifndef _LINUX_TIMEX_H #define _LINUX_TIMEX_H #include #define NTP_API 4 /* NTP API version */ /* * syscall interface - used (mainly by NTP daemon) * to discipline kernel clock oscillator */ struct timex { unsigned int modes; /* mode selector */ __kernel_long_t offset; /* time offset (usec) */ __kernel_long_t freq; /* frequency offset (scaled ppm) */ __kernel_long_t maxerror;/* maximum error (usec) */ __kernel_long_t esterror;/* estimated error (usec) */ int status; /* clock command/status */ __kernel_long_t constant;/* pll time constant */ __kernel_long_t precision;/* clock precision (usec) (read only) */ __kernel_long_t tolerance;/* clock frequency tolerance (ppm) * (read only) */ struct timeval time; /* (read only, except for ADJ_SETOFFSET) */ __kernel_long_t tick; /* (modified) usecs between clock ticks */ __kernel_long_t ppsfreq;/* pps frequency (scaled ppm) (ro) */ __kernel_long_t jitter; /* pps jitter (us) (ro) */ int shift; /* interval duration (s) (shift) (ro) */ __kernel_long_t stabil; /* pps stability (scaled ppm) (ro) */ __kernel_long_t jitcnt; /* jitter limit exceeded (ro) */ __kernel_long_t calcnt; /* calibration intervals (ro) */ __kernel_long_t errcnt; /* calibration errors (ro) */ __kernel_long_t stbcnt; /* stability limit exceeded (ro) */ int tai; /* TAI offset (ro) */ int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; int :32; }; /* * Mode codes (timex.mode) */ #define ADJ_OFFSET 0x0001 /* time offset */ #define ADJ_FREQUENCY 0x0002 /* frequency offset */ #define ADJ_MAXERROR 0x0004 /* maximum time error */ #define ADJ_ESTERROR 0x0008 /* estimated time error */ #define ADJ_STATUS 0x0010 /* clock status */ #define ADJ_TIMECONST 0x0020 /* pll time constant */ #define ADJ_TAI 0x0080 /* set TAI offset */ #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */ #define ADJ_MICRO 0x1000 /* select microsecond resolution */ #define ADJ_NANO 0x2000 /* select nanosecond resolution */ #define ADJ_TICK 0x4000 /* tick value */ #define ADJ_OFFSET_SINGLESHOT 0x8001 /* old-fashioned adjtime */ #define ADJ_OFFSET_SS_READ 0xa001 /* read-only adjtime */ /* NTP userland likes the MOD_ prefix better */ #define MOD_OFFSET ADJ_OFFSET #define MOD_FREQUENCY ADJ_FREQUENCY #define MOD_MAXERROR ADJ_MAXERROR #define MOD_ESTERROR ADJ_ESTERROR #define MOD_STATUS ADJ_STATUS #define MOD_TIMECONST ADJ_TIMECONST #define MOD_TAI ADJ_TAI #define MOD_MICRO ADJ_MICRO #define MOD_NANO ADJ_NANO /* * Status codes (timex.status) */ #define STA_PLL 0x0001 /* enable PLL updates (rw) */ #define STA_PPSFREQ 0x0002 /* enable PPS freq discipline (rw) */ #define STA_PPSTIME 0x0004 /* enable PPS time discipline (rw) */ #define STA_FLL 0x0008 /* select frequency-lock mode (rw) */ #define STA_INS 0x0010 /* insert leap (rw) */ #define STA_DEL 0x0020 /* delete leap (rw) */ #define STA_UNSYNC 0x0040 /* clock unsynchronized (rw) */ #define STA_FREQHOLD 0x0080 /* hold frequency (rw) */ #define STA_PPSSIGNAL 0x0100 /* PPS signal present (ro) */ #define STA_PPSJITTER 0x0200 /* PPS signal jitter exceeded (ro) */ #define STA_PPSWANDER 0x0400 /* PPS signal wander exceeded (ro) */ #define STA_PPSERROR 0x0800 /* PPS signal calibration error (ro) */ #define STA_CLOCKERR 0x1000 /* clock hardware fault (ro) */ #define STA_NANO 0x2000 /* resolution (0 = us, 1 = ns) (ro) */ #define STA_MODE 0x4000 /* mode (0 = PLL, 1 = FLL) (ro) */ #define STA_CLK 0x8000 /* clock source (0 = A, 1 = B) (ro) */ /* read-only bits */ #define STA_RONLY (STA_PPSSIGNAL | STA_PPSJITTER | STA_PPSWANDER | \ STA_PPSERROR | STA_CLOCKERR | STA_NANO | STA_MODE | STA_CLK) /* * Clock states (time_state) */ #define TIME_OK 0 /* clock synchronized, no leap second */ #define TIME_INS 1 /* insert leap second */ #define TIME_DEL 2 /* delete leap second */ #define TIME_OOP 3 /* leap second in progress */ #define TIME_WAIT 4 /* leap second has occurred */ #define TIME_ERROR 5 /* clock not synchronized */ #define TIME_BAD TIME_ERROR /* bw compat */ #endif /* _LINUX_TIMEX_H */ linux/sched.h000064400000005355151027430560007155 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SCHED_H #define _LINUX_SCHED_H /* * cloning flags: */ #define CSIGNAL 0x000000ff /* signal mask to be sent at exit */ #define CLONE_VM 0x00000100 /* set if VM shared between processes */ #define CLONE_FS 0x00000200 /* set if fs info shared between processes */ #define CLONE_FILES 0x00000400 /* set if open files shared between processes */ #define CLONE_SIGHAND 0x00000800 /* set if signal handlers and blocked signals shared */ #define CLONE_PIDFD 0x00001000 /* set if a pidfd should be placed in parent */ #define CLONE_PTRACE 0x00002000 /* set if we want to let tracing continue on the child too */ #define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ #define CLONE_PARENT 0x00008000 /* set if we want to have the same parent as the cloner */ #define CLONE_THREAD 0x00010000 /* Same thread group? */ #define CLONE_NEWNS 0x00020000 /* New mount namespace group */ #define CLONE_SYSVSEM 0x00040000 /* share system V SEM_UNDO semantics */ #define CLONE_SETTLS 0x00080000 /* create a new TLS for the child */ #define CLONE_PARENT_SETTID 0x00100000 /* set the TID in the parent */ #define CLONE_CHILD_CLEARTID 0x00200000 /* clear the TID in the child */ #define CLONE_DETACHED 0x00400000 /* Unused, ignored */ #define CLONE_UNTRACED 0x00800000 /* set if the tracing process can't force CLONE_PTRACE on this clone */ #define CLONE_CHILD_SETTID 0x01000000 /* set the TID in the child */ #define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */ #define CLONE_NEWUTS 0x04000000 /* New utsname namespace */ #define CLONE_NEWIPC 0x08000000 /* New ipc namespace */ #define CLONE_NEWUSER 0x10000000 /* New user namespace */ #define CLONE_NEWPID 0x20000000 /* New pid namespace */ #define CLONE_NEWNET 0x40000000 /* New network namespace */ #define CLONE_IO 0x80000000 /* Clone io context */ /* * cloning flags intersect with CSIGNAL so can be used with unshare and clone3 * syscalls only: */ #define CLONE_NEWTIME 0x00000080 /* New time namespace */ /* * Scheduling policies */ #define SCHED_NORMAL 0 #define SCHED_FIFO 1 #define SCHED_RR 2 #define SCHED_BATCH 3 /* SCHED_ISO: reserved but not implemented yet */ #define SCHED_IDLE 5 #define SCHED_DEADLINE 6 /* Can be ORed in to make sure the process is reverted back to SCHED_NORMAL on fork */ #define SCHED_RESET_ON_FORK 0x40000000 /* * For the sched_{set,get}attr() calls */ #define SCHED_FLAG_RESET_ON_FORK 0x01 #define SCHED_FLAG_RECLAIM 0x02 #define SCHED_FLAG_DL_OVERRUN 0x04 #define SCHED_FLAG_KEEP_POLICY 0x08 #define SCHED_FLAG_ALL (SCHED_FLAG_RESET_ON_FORK | \ SCHED_FLAG_RECLAIM | \ SCHED_FLAG_DL_OVERRUN | \ SCHED_FLAG_KEEP_POLICY) #endif /* _LINUX_SCHED_H */ linux/meye.h000064400000004741151027430560007024 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Motion Eye video4linux driver for Sony Vaio PictureBook * * Copyright (C) 2001-2003 Stelian Pop * * Copyright (C) 2001-2002 Alcôve * * Copyright (C) 2000 Andrew Tridgell * * Earlier work by Werner Almesberger, Paul `Rusty' Russell and Paul Mackerras. * * Some parts borrowed from various video4linux drivers, especially * bttv-driver.c and zoran.c, see original files for credits. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _MEYE_H_ #define _MEYE_H_ /****************************************************************************/ /* Private API for handling mjpeg capture / playback. */ /****************************************************************************/ struct meye_params { unsigned char subsample; unsigned char quality; unsigned char sharpness; unsigned char agc; unsigned char picture; unsigned char framerate; }; /* query the extended parameters */ #define MEYEIOC_G_PARAMS _IOR ('v', BASE_VIDIOC_PRIVATE+0, struct meye_params) /* set the extended parameters */ #define MEYEIOC_S_PARAMS _IOW ('v', BASE_VIDIOC_PRIVATE+1, struct meye_params) /* queue a buffer for mjpeg capture */ #define MEYEIOC_QBUF_CAPT _IOW ('v', BASE_VIDIOC_PRIVATE+2, int) /* sync a previously queued mjpeg buffer */ #define MEYEIOC_SYNC _IOWR('v', BASE_VIDIOC_PRIVATE+3, int) /* get a still uncompressed snapshot */ #define MEYEIOC_STILLCAPT _IO ('v', BASE_VIDIOC_PRIVATE+4) /* get a jpeg compressed snapshot */ #define MEYEIOC_STILLJCAPT _IOR ('v', BASE_VIDIOC_PRIVATE+5, int) /* V4L2 private controls */ #define V4L2_CID_MEYE_AGC (V4L2_CID_USER_MEYE_BASE + 0) #define V4L2_CID_MEYE_PICTURE (V4L2_CID_USER_MEYE_BASE + 1) #define V4L2_CID_MEYE_FRAMERATE (V4L2_CID_USER_MEYE_BASE + 2) #endif linux/netfilter_ipv6/ip6_tables.h000064400000017513151027430560013056 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * 25-Jul-1998 Major changes to allow for ip chain table * * 3-Jan-2000 Named tables to allow packet selection for different uses. */ /* * Format of an IP6 firewall descriptor * * src, dst, src_mask, dst_mask are always stored in network byte order. * flags are stored in host byte order (of course). * Port numbers are stored in HOST byte order. */ #ifndef _IP6_TABLES_H #define _IP6_TABLES_H #include #include #include #include #define IP6T_FUNCTION_MAXNAMELEN XT_FUNCTION_MAXNAMELEN #define IP6T_TABLE_MAXNAMELEN XT_TABLE_MAXNAMELEN #define ip6t_match xt_match #define ip6t_target xt_target #define ip6t_table xt_table #define ip6t_get_revision xt_get_revision #define ip6t_entry_match xt_entry_match #define ip6t_entry_target xt_entry_target #define ip6t_standard_target xt_standard_target #define ip6t_error_target xt_error_target #define ip6t_counters xt_counters #define IP6T_CONTINUE XT_CONTINUE #define IP6T_RETURN XT_RETURN /* Pre-iptables-1.4.0 */ #include #define ip6t_tcp xt_tcp #define ip6t_udp xt_udp #define IP6T_TCP_INV_SRCPT XT_TCP_INV_SRCPT #define IP6T_TCP_INV_DSTPT XT_TCP_INV_DSTPT #define IP6T_TCP_INV_FLAGS XT_TCP_INV_FLAGS #define IP6T_TCP_INV_OPTION XT_TCP_INV_OPTION #define IP6T_TCP_INV_MASK XT_TCP_INV_MASK #define IP6T_UDP_INV_SRCPT XT_UDP_INV_SRCPT #define IP6T_UDP_INV_DSTPT XT_UDP_INV_DSTPT #define IP6T_UDP_INV_MASK XT_UDP_INV_MASK #define ip6t_counters_info xt_counters_info #define IP6T_STANDARD_TARGET XT_STANDARD_TARGET #define IP6T_ERROR_TARGET XT_ERROR_TARGET #define IP6T_MATCH_ITERATE(e, fn, args...) \ XT_MATCH_ITERATE(struct ip6t_entry, e, fn, ## args) #define IP6T_ENTRY_ITERATE(entries, size, fn, args...) \ XT_ENTRY_ITERATE(struct ip6t_entry, entries, size, fn, ## args) /* Yes, Virginia, you have to zero the padding. */ struct ip6t_ip6 { /* Source and destination IP6 addr */ struct in6_addr src, dst; /* Mask for src and dest IP6 addr */ struct in6_addr smsk, dmsk; char iniface[IFNAMSIZ], outiface[IFNAMSIZ]; unsigned char iniface_mask[IFNAMSIZ], outiface_mask[IFNAMSIZ]; /* Upper protocol number * - The allowed value is 0 (any) or protocol number of last parsable * header, which is 50 (ESP), 59 (No Next Header), 135 (MH), or * the non IPv6 extension headers. * - The protocol numbers of IPv6 extension headers except of ESP and * MH do not match any packets. * - You also need to set IP6T_FLAGS_PROTO to "flags" to check protocol. */ __u16 proto; /* TOS to match iff flags & IP6T_F_TOS */ __u8 tos; /* Flags word */ __u8 flags; /* Inverse flags */ __u8 invflags; }; /* Values for "flag" field in struct ip6t_ip6 (general ip6 structure). */ #define IP6T_F_PROTO 0x01 /* Set if rule cares about upper protocols */ #define IP6T_F_TOS 0x02 /* Match the TOS. */ #define IP6T_F_GOTO 0x04 /* Set if jump is a goto */ #define IP6T_F_MASK 0x07 /* All possible flag bits mask. */ /* Values for "inv" field in struct ip6t_ip6. */ #define IP6T_INV_VIA_IN 0x01 /* Invert the sense of IN IFACE. */ #define IP6T_INV_VIA_OUT 0x02 /* Invert the sense of OUT IFACE */ #define IP6T_INV_TOS 0x04 /* Invert the sense of TOS. */ #define IP6T_INV_SRCIP 0x08 /* Invert the sense of SRC IP. */ #define IP6T_INV_DSTIP 0x10 /* Invert the sense of DST OP. */ #define IP6T_INV_FRAG 0x20 /* Invert the sense of FRAG. */ #define IP6T_INV_PROTO XT_INV_PROTO #define IP6T_INV_MASK 0x7F /* All possible flag bits mask. */ /* This structure defines each of the firewall rules. Consists of 3 parts which are 1) general IP header stuff 2) match specific stuff 3) the target to perform if the rule matches */ struct ip6t_entry { struct ip6t_ip6 ipv6; /* Mark with fields that we care about. */ unsigned int nfcache; /* Size of ipt_entry + matches */ __u16 target_offset; /* Size of ipt_entry + matches + target */ __u16 next_offset; /* Back pointer */ unsigned int comefrom; /* Packet and byte counters. */ struct xt_counters counters; /* The matches (if any), then the target. */ unsigned char elems[0]; }; /* Standard entry */ struct ip6t_standard { struct ip6t_entry entry; struct xt_standard_target target; }; struct ip6t_error { struct ip6t_entry entry; struct xt_error_target target; }; #define IP6T_ENTRY_INIT(__size) \ { \ .target_offset = sizeof(struct ip6t_entry), \ .next_offset = (__size), \ } #define IP6T_STANDARD_INIT(__verdict) \ { \ .entry = IP6T_ENTRY_INIT(sizeof(struct ip6t_standard)), \ .target = XT_TARGET_INIT(XT_STANDARD_TARGET, \ sizeof(struct xt_standard_target)), \ .target.verdict = -(__verdict) - 1, \ } #define IP6T_ERROR_INIT \ { \ .entry = IP6T_ENTRY_INIT(sizeof(struct ip6t_error)), \ .target = XT_TARGET_INIT(XT_ERROR_TARGET, \ sizeof(struct xt_error_target)), \ .target.errorname = "ERROR", \ } /* * New IP firewall options for [gs]etsockopt at the RAW IP level. * Unlike BSD Linux inherits IP options so you don't have to use * a raw socket for this. Instead we check rights in the calls. * * ATTENTION: check linux/in6.h before adding new number here. */ #define IP6T_BASE_CTL 64 #define IP6T_SO_SET_REPLACE (IP6T_BASE_CTL) #define IP6T_SO_SET_ADD_COUNTERS (IP6T_BASE_CTL + 1) #define IP6T_SO_SET_MAX IP6T_SO_SET_ADD_COUNTERS #define IP6T_SO_GET_INFO (IP6T_BASE_CTL) #define IP6T_SO_GET_ENTRIES (IP6T_BASE_CTL + 1) #define IP6T_SO_GET_REVISION_MATCH (IP6T_BASE_CTL + 4) #define IP6T_SO_GET_REVISION_TARGET (IP6T_BASE_CTL + 5) #define IP6T_SO_GET_MAX IP6T_SO_GET_REVISION_TARGET /* obtain original address if REDIRECT'd connection */ #define IP6T_SO_ORIGINAL_DST 80 /* ICMP matching stuff */ struct ip6t_icmp { __u8 type; /* type to match */ __u8 code[2]; /* range of code */ __u8 invflags; /* Inverse flags */ }; /* Values for "inv" field for struct ipt_icmp. */ #define IP6T_ICMP_INV 0x01 /* Invert the sense of type/code test */ /* The argument to IP6T_SO_GET_INFO */ struct ip6t_getinfo { /* Which table: caller fills this in. */ char name[XT_TABLE_MAXNAMELEN]; /* Kernel fills these in. */ /* Which hook entry points are valid: bitmask */ unsigned int valid_hooks; /* Hook entry points: one per netfilter hook. */ unsigned int hook_entry[NF_INET_NUMHOOKS]; /* Underflow points. */ unsigned int underflow[NF_INET_NUMHOOKS]; /* Number of entries */ unsigned int num_entries; /* Size of entries. */ unsigned int size; }; /* The argument to IP6T_SO_SET_REPLACE. */ struct ip6t_replace { /* Which table. */ char name[XT_TABLE_MAXNAMELEN]; /* Which hook entry points are valid: bitmask. You can't change this. */ unsigned int valid_hooks; /* Number of entries */ unsigned int num_entries; /* Total size of new entries */ unsigned int size; /* Hook entry points. */ unsigned int hook_entry[NF_INET_NUMHOOKS]; /* Underflow points. */ unsigned int underflow[NF_INET_NUMHOOKS]; /* Information about old entries: */ /* Number of counters (must be equal to current number of entries). */ unsigned int num_counters; /* The old entries' counters. */ struct xt_counters *counters; /* The entries (hang off end: not really an array). */ struct ip6t_entry entries[0]; }; /* The argument to IP6T_SO_GET_ENTRIES. */ struct ip6t_get_entries { /* Which table: user fills this in. */ char name[XT_TABLE_MAXNAMELEN]; /* User fills this in: total entry size. */ unsigned int size; /* The entries. */ struct ip6t_entry entrytable[0]; }; /* Helper functions */ static __inline__ struct xt_entry_target * ip6t_get_target(struct ip6t_entry *e) { return (void *)e + e->target_offset; } /* * Main firewall chains definitions and global var's definitions. */ #endif /* _IP6_TABLES_H */ linux/netfilter_ipv6/ip6t_HL.h000064400000000630151027430560012263 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Hop Limit modification module for ip6tables * Maciej Soltysiak * Based on HW's TTL module */ #ifndef _IP6T_HL_H #define _IP6T_HL_H #include enum { IP6T_HL_SET = 0, IP6T_HL_INC, IP6T_HL_DEC }; #define IP6T_HL_MAXMODE IP6T_HL_DEC struct ip6t_HL_info { __u8 mode; __u8 hop_limit; }; #endif linux/netfilter_ipv6/ip6t_ipv6header.h000064400000001205151027430560014014 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* ipv6header match - matches IPv6 packets based on whether they contain certain headers */ /* Original idea: Brad Chapman * Rewritten by: Andras Kis-Szabo */ #ifndef __IPV6HEADER_H #define __IPV6HEADER_H #include struct ip6t_ipv6header_info { __u8 matchflags; __u8 invflags; __u8 modeflag; }; #define MASK_HOPOPTS 128 #define MASK_DSTOPTS 64 #define MASK_ROUTING 32 #define MASK_FRAGMENT 16 #define MASK_AH 8 #define MASK_ESP 4 #define MASK_NONE 2 #define MASK_PROTO 1 #endif /* __IPV6HEADER_H */ linux/netfilter_ipv6/ip6t_LOG.h000064400000001332151027430560012401 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_LOG_H #define _IP6T_LOG_H #warning "Please update iptables, this file will be removed soon!" /* make sure not to change this without changing netfilter.h:NF_LOG_* (!) */ #define IP6T_LOG_TCPSEQ 0x01 /* Log TCP sequence numbers */ #define IP6T_LOG_TCPOPT 0x02 /* Log TCP options */ #define IP6T_LOG_IPOPT 0x04 /* Log IP options */ #define IP6T_LOG_UID 0x08 /* Log UID owning local socket */ #define IP6T_LOG_NFLOG 0x10 /* Unsupported, don't use */ #define IP6T_LOG_MACDECODE 0x20 /* Decode MAC header */ #define IP6T_LOG_MASK 0x2f struct ip6t_log_info { unsigned char level; unsigned char logflags; char prefix[30]; }; #endif /*_IPT_LOG_H*/ linux/netfilter_ipv6/ip6t_mh.h000064400000000667151027430560012376 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_MH_H #define _IP6T_MH_H #include /* MH matching stuff */ struct ip6t_mh { __u8 types[2]; /* MH type range */ __u8 invflags; /* Inverse flags */ }; /* Values for "invflags" field in struct ip6t_mh. */ #define IP6T_MH_INV_TYPE 0x01 /* Invert the sense of type. */ #define IP6T_MH_INV_MASK 0x01 /* All possible flags. */ #endif /*_IP6T_MH_H*/ linux/netfilter_ipv6/ip6t_rt.h000064400000001731151027430560012410 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_RT_H #define _IP6T_RT_H #include #include #define IP6T_RT_HOPS 16 struct ip6t_rt { __u32 rt_type; /* Routing Type */ __u32 segsleft[2]; /* Segments Left */ __u32 hdrlen; /* Header Length */ __u8 flags; /* */ __u8 invflags; /* Inverse flags */ struct in6_addr addrs[IP6T_RT_HOPS]; /* Hops */ __u8 addrnr; /* Nr of Addresses */ }; #define IP6T_RT_TYP 0x01 #define IP6T_RT_SGS 0x02 #define IP6T_RT_LEN 0x04 #define IP6T_RT_RES 0x08 #define IP6T_RT_FST_MASK 0x30 #define IP6T_RT_FST 0x10 #define IP6T_RT_FST_NSTRICT 0x20 /* Values for "invflags" field in struct ip6t_rt. */ #define IP6T_RT_INV_TYP 0x01 /* Invert the sense of type. */ #define IP6T_RT_INV_SGS 0x02 /* Invert the sense of Segments. */ #define IP6T_RT_INV_LEN 0x04 /* Invert the sense of length. */ #define IP6T_RT_INV_MASK 0x07 /* All possible flags. */ #endif /*_IP6T_RT_H*/ linux/netfilter_ipv6/ip6t_hl.h000064400000000712151027430560012364 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* ip6tables module for matching the Hop Limit value * Maciej Soltysiak * Based on HW's ttl module */ #ifndef _IP6T_HL_H #define _IP6T_HL_H #include enum { IP6T_HL_EQ = 0, /* equals */ IP6T_HL_NE, /* not equals */ IP6T_HL_LT, /* less than */ IP6T_HL_GT, /* greater than */ }; struct ip6t_hl_info { __u8 mode; __u8 hop_limit; }; #endif linux/netfilter_ipv6/ip6t_opts.h000064400000001211151027430560012741 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_OPTS_H #define _IP6T_OPTS_H #include #define IP6T_OPTS_OPTSNR 16 struct ip6t_opts { __u32 hdrlen; /* Header Length */ __u8 flags; /* */ __u8 invflags; /* Inverse flags */ __u16 opts[IP6T_OPTS_OPTSNR]; /* opts */ __u8 optsnr; /* Nr of OPts */ }; #define IP6T_OPTS_LEN 0x01 #define IP6T_OPTS_OPTS 0x02 #define IP6T_OPTS_NSTRICT 0x04 /* Values for "invflags" field in struct ip6t_rt. */ #define IP6T_OPTS_INV_LEN 0x01 /* Invert the sense of length. */ #define IP6T_OPTS_INV_MASK 0x01 /* All possible flags. */ #endif /*_IP6T_OPTS_H*/ linux/netfilter_ipv6/ip6t_NPT.h000064400000000620151027430560012420 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __NETFILTER_IP6T_NPT #define __NETFILTER_IP6T_NPT #include #include struct ip6t_npt_tginfo { union nf_inet_addr src_pfx; union nf_inet_addr dst_pfx; __u8 src_pfx_len; __u8 dst_pfx_len; /* Used internally by the kernel */ __sum16 adjustment; }; #endif /* __NETFILTER_IP6T_NPT */ linux/netfilter_ipv6/ip6t_ah.h000064400000001221151027430560012345 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_AH_H #define _IP6T_AH_H #include struct ip6t_ah { __u32 spis[2]; /* Security Parameter Index */ __u32 hdrlen; /* Header Length */ __u8 hdrres; /* Test of the Reserved Filed */ __u8 invflags; /* Inverse flags */ }; #define IP6T_AH_SPI 0x01 #define IP6T_AH_LEN 0x02 #define IP6T_AH_RES 0x04 /* Values for "invflags" field in struct ip6t_ah. */ #define IP6T_AH_INV_SPI 0x01 /* Invert the sense of spi. */ #define IP6T_AH_INV_LEN 0x02 /* Invert the sense of length. */ #define IP6T_AH_INV_MASK 0x03 /* All possible flags. */ #endif /*_IP6T_AH_H*/ linux/netfilter_ipv6/ip6t_srh.h000064400000006351151027430560012562 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_SRH_H #define _IP6T_SRH_H #include #include /* Values for "mt_flags" field in struct ip6t_srh */ #define IP6T_SRH_NEXTHDR 0x0001 #define IP6T_SRH_LEN_EQ 0x0002 #define IP6T_SRH_LEN_GT 0x0004 #define IP6T_SRH_LEN_LT 0x0008 #define IP6T_SRH_SEGS_EQ 0x0010 #define IP6T_SRH_SEGS_GT 0x0020 #define IP6T_SRH_SEGS_LT 0x0040 #define IP6T_SRH_LAST_EQ 0x0080 #define IP6T_SRH_LAST_GT 0x0100 #define IP6T_SRH_LAST_LT 0x0200 #define IP6T_SRH_TAG 0x0400 #define IP6T_SRH_PSID 0x0800 #define IP6T_SRH_NSID 0x1000 #define IP6T_SRH_LSID 0x2000 #define IP6T_SRH_MASK 0x3FFF /* Values for "mt_invflags" field in struct ip6t_srh */ #define IP6T_SRH_INV_NEXTHDR 0x0001 #define IP6T_SRH_INV_LEN_EQ 0x0002 #define IP6T_SRH_INV_LEN_GT 0x0004 #define IP6T_SRH_INV_LEN_LT 0x0008 #define IP6T_SRH_INV_SEGS_EQ 0x0010 #define IP6T_SRH_INV_SEGS_GT 0x0020 #define IP6T_SRH_INV_SEGS_LT 0x0040 #define IP6T_SRH_INV_LAST_EQ 0x0080 #define IP6T_SRH_INV_LAST_GT 0x0100 #define IP6T_SRH_INV_LAST_LT 0x0200 #define IP6T_SRH_INV_TAG 0x0400 #define IP6T_SRH_INV_PSID 0x0800 #define IP6T_SRH_INV_NSID 0x1000 #define IP6T_SRH_INV_LSID 0x2000 #define IP6T_SRH_INV_MASK 0x3FFF /** * struct ip6t_srh - SRH match options * @ next_hdr: Next header field of SRH * @ hdr_len: Extension header length field of SRH * @ segs_left: Segments left field of SRH * @ last_entry: Last entry field of SRH * @ tag: Tag field of SRH * @ mt_flags: match options * @ mt_invflags: Invert the sense of match options */ struct ip6t_srh { __u8 next_hdr; __u8 hdr_len; __u8 segs_left; __u8 last_entry; __u16 tag; __u16 mt_flags; __u16 mt_invflags; }; /** * struct ip6t_srh1 - SRH match options (revision 1) * @ next_hdr: Next header field of SRH * @ hdr_len: Extension header length field of SRH * @ segs_left: Segments left field of SRH * @ last_entry: Last entry field of SRH * @ tag: Tag field of SRH * @ psid_addr: Address of previous SID in SRH SID list * @ nsid_addr: Address of NEXT SID in SRH SID list * @ lsid_addr: Address of LAST SID in SRH SID list * @ psid_msk: Mask of previous SID in SRH SID list * @ nsid_msk: Mask of next SID in SRH SID list * @ lsid_msk: MAsk of last SID in SRH SID list * @ mt_flags: match options * @ mt_invflags: Invert the sense of match options */ struct ip6t_srh1 { __u8 next_hdr; __u8 hdr_len; __u8 segs_left; __u8 last_entry; __u16 tag; struct in6_addr psid_addr; struct in6_addr nsid_addr; struct in6_addr lsid_addr; struct in6_addr psid_msk; struct in6_addr nsid_msk; struct in6_addr lsid_msk; __u16 mt_flags; __u16 mt_invflags; }; #endif /*_IP6T_SRH_H*/ linux/netfilter_ipv6/ip6t_REJECT.h000064400000000726151027430560012742 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_REJECT_H #define _IP6T_REJECT_H #include enum ip6t_reject_with { IP6T_ICMP6_NO_ROUTE, IP6T_ICMP6_ADM_PROHIBITED, IP6T_ICMP6_NOT_NEIGHBOUR, IP6T_ICMP6_ADDR_UNREACH, IP6T_ICMP6_PORT_UNREACH, IP6T_ICMP6_ECHOREPLY, IP6T_TCP_RESET, IP6T_ICMP6_POLICY_FAIL, IP6T_ICMP6_REJECT_ROUTE }; struct ip6t_reject_info { __u32 with; /* reject type */ }; #endif /*_IP6T_REJECT_H*/ linux/netfilter_ipv6/ip6t_frag.h000064400000001350151027430560012677 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6T_FRAG_H #define _IP6T_FRAG_H #include struct ip6t_frag { __u32 ids[2]; /* Identification range */ __u32 hdrlen; /* Header Length */ __u8 flags; /* Flags */ __u8 invflags; /* Inverse flags */ }; #define IP6T_FRAG_IDS 0x01 #define IP6T_FRAG_LEN 0x02 #define IP6T_FRAG_RES 0x04 #define IP6T_FRAG_FST 0x08 #define IP6T_FRAG_MF 0x10 #define IP6T_FRAG_NMF 0x20 /* Values for "invflags" field in struct ip6t_frag. */ #define IP6T_FRAG_INV_IDS 0x01 /* Invert the sense of ids. */ #define IP6T_FRAG_INV_LEN 0x02 /* Invert the sense of length. */ #define IP6T_FRAG_INV_MASK 0x03 /* All possible flags. */ #endif /*_IP6T_FRAG_H*/ linux/btf.h000064400000011274151027430560006637 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (c) 2018 Facebook */ #ifndef __LINUX_BTF_H__ #define __LINUX_BTF_H__ #include #define BTF_MAGIC 0xeB9F #define BTF_VERSION 1 struct btf_header { __u16 magic; __u8 version; __u8 flags; __u32 hdr_len; /* All offsets are in bytes relative to the end of this header */ __u32 type_off; /* offset of type section */ __u32 type_len; /* length of type section */ __u32 str_off; /* offset of string section */ __u32 str_len; /* length of string section */ }; /* Max # of type identifier */ #define BTF_MAX_TYPE 0x000fffff /* Max offset into the string section */ #define BTF_MAX_NAME_OFFSET 0x00ffffff /* Max # of struct/union/enum members or func args */ #define BTF_MAX_VLEN 0xffff struct btf_type { __u32 name_off; /* "info" bits arrangement * bits 0-15: vlen (e.g. # of struct's members) * bits 16-23: unused * bits 24-27: kind (e.g. int, ptr, array...etc) * bits 28-30: unused * bit 31: kind_flag, currently used by * struct, union and fwd */ __u32 info; /* "size" is used by INT, ENUM, STRUCT, UNION and DATASEC. * "size" tells the size of the type it is describing. * * "type" is used by PTR, TYPEDEF, VOLATILE, CONST, RESTRICT, * FUNC, FUNC_PROTO and VAR. * "type" is a type_id referring to another type. */ union { __u32 size; __u32 type; }; }; #define BTF_INFO_KIND(info) (((info) >> 24) & 0x1f) #define BTF_INFO_VLEN(info) ((info) & 0xffff) #define BTF_INFO_KFLAG(info) ((info) >> 31) #define BTF_KIND_UNKN 0 /* Unknown */ #define BTF_KIND_INT 1 /* Integer */ #define BTF_KIND_PTR 2 /* Pointer */ #define BTF_KIND_ARRAY 3 /* Array */ #define BTF_KIND_STRUCT 4 /* Struct */ #define BTF_KIND_UNION 5 /* Union */ #define BTF_KIND_ENUM 6 /* Enumeration */ #define BTF_KIND_FWD 7 /* Forward */ #define BTF_KIND_TYPEDEF 8 /* Typedef */ #define BTF_KIND_VOLATILE 9 /* Volatile */ #define BTF_KIND_CONST 10 /* Const */ #define BTF_KIND_RESTRICT 11 /* Restrict */ #define BTF_KIND_FUNC 12 /* Function */ #define BTF_KIND_FUNC_PROTO 13 /* Function Proto */ #define BTF_KIND_VAR 14 /* Variable */ #define BTF_KIND_DATASEC 15 /* Section */ #define BTF_KIND_FLOAT 16 /* Floating point */ #define BTF_KIND_MAX BTF_KIND_FLOAT #define NR_BTF_KINDS (BTF_KIND_MAX + 1) /* For some specific BTF_KIND, "struct btf_type" is immediately * followed by extra data. */ /* BTF_KIND_INT is followed by a u32 and the following * is the 32 bits arrangement: */ #define BTF_INT_ENCODING(VAL) (((VAL) & 0x0f000000) >> 24) #define BTF_INT_OFFSET(VAL) (((VAL) & 0x00ff0000) >> 16) #define BTF_INT_BITS(VAL) ((VAL) & 0x000000ff) /* Attributes stored in the BTF_INT_ENCODING */ #define BTF_INT_SIGNED (1 << 0) #define BTF_INT_CHAR (1 << 1) #define BTF_INT_BOOL (1 << 2) /* BTF_KIND_ENUM is followed by multiple "struct btf_enum". * The exact number of btf_enum is stored in the vlen (of the * info in "struct btf_type"). */ struct btf_enum { __u32 name_off; __s32 val; }; /* BTF_KIND_ARRAY is followed by one "struct btf_array" */ struct btf_array { __u32 type; __u32 index_type; __u32 nelems; }; /* BTF_KIND_STRUCT and BTF_KIND_UNION are followed * by multiple "struct btf_member". The exact number * of btf_member is stored in the vlen (of the info in * "struct btf_type"). */ struct btf_member { __u32 name_off; __u32 type; /* If the type info kind_flag is set, the btf_member offset * contains both member bitfield size and bit offset. The * bitfield size is set for bitfield members. If the type * info kind_flag is not set, the offset contains only bit * offset. */ __u32 offset; }; /* If the struct/union type info kind_flag is set, the * following two macros are used to access bitfield_size * and bit_offset from btf_member.offset. */ #define BTF_MEMBER_BITFIELD_SIZE(val) ((val) >> 24) #define BTF_MEMBER_BIT_OFFSET(val) ((val) & 0xffffff) /* BTF_KIND_FUNC_PROTO is followed by multiple "struct btf_param". * The exact number of btf_param is stored in the vlen (of the * info in "struct btf_type"). */ struct btf_param { __u32 name_off; __u32 type; }; enum { BTF_VAR_STATIC = 0, BTF_VAR_GLOBAL_ALLOCATED = 1, BTF_VAR_GLOBAL_EXTERN = 2, }; enum btf_func_linkage { BTF_FUNC_STATIC = 0, BTF_FUNC_GLOBAL = 1, BTF_FUNC_EXTERN = 2, }; /* BTF_KIND_VAR is followed by a single "struct btf_var" to describe * additional information related to the variable such as its linkage. */ struct btf_var { __u32 linkage; }; /* BTF_KIND_DATASEC is followed by multiple "struct btf_var_secinfo" * to describe all BTF_KIND_VAR types it contains along with it's * in-section offset as well as size. */ struct btf_var_secinfo { __u32 type; __u32 offset; __u32 size; }; #endif /* __LINUX_BTF_H__ */ linux/auto_fs.h000064400000014434151027430560007525 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright 1997 Transmeta Corporation - All Rights Reserved * Copyright 1999-2000 Jeremy Fitzhardinge * Copyright 2005-2006,2013,2017-2018 Ian Kent * * This file is part of the Linux kernel and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. * * ----------------------------------------------------------------------- */ #ifndef _LINUX_AUTO_FS_H #define _LINUX_AUTO_FS_H #include #include #include #define AUTOFS_PROTO_VERSION 5 #define AUTOFS_MIN_PROTO_VERSION 3 #define AUTOFS_MAX_PROTO_VERSION 5 #define AUTOFS_PROTO_SUBVERSION 6 /* * The wait_queue_token (autofs_wqt_t) is part of a structure which is passed * back to the kernel via ioctl from userspace. On architectures where 32- and * 64-bit userspace binaries can be executed it's important that the size of * autofs_wqt_t stays constant between 32- and 64-bit Linux kernels so that we * do not break the binary ABI interface by changing the structure size. */ #if defined(__ia64__) || defined(__alpha__) /* pure 64bit architectures */ typedef unsigned long autofs_wqt_t; #else typedef unsigned int autofs_wqt_t; #endif /* Packet types */ #define autofs_ptype_missing 0 /* Missing entry (mount request) */ #define autofs_ptype_expire 1 /* Expire entry (umount request) */ struct autofs_packet_hdr { int proto_version; /* Protocol version */ int type; /* Type of packet */ }; struct autofs_packet_missing { struct autofs_packet_hdr hdr; autofs_wqt_t wait_queue_token; int len; char name[NAME_MAX+1]; }; /* v3 expire (via ioctl) */ struct autofs_packet_expire { struct autofs_packet_hdr hdr; int len; char name[NAME_MAX+1]; }; #define AUTOFS_IOCTL 0x93 enum { AUTOFS_IOC_READY_CMD = 0x60, AUTOFS_IOC_FAIL_CMD, AUTOFS_IOC_CATATONIC_CMD, AUTOFS_IOC_PROTOVER_CMD, AUTOFS_IOC_SETTIMEOUT_CMD, AUTOFS_IOC_EXPIRE_CMD, }; #define AUTOFS_IOC_READY _IO(AUTOFS_IOCTL, AUTOFS_IOC_READY_CMD) #define AUTOFS_IOC_FAIL _IO(AUTOFS_IOCTL, AUTOFS_IOC_FAIL_CMD) #define AUTOFS_IOC_CATATONIC _IO(AUTOFS_IOCTL, AUTOFS_IOC_CATATONIC_CMD) #define AUTOFS_IOC_PROTOVER _IOR(AUTOFS_IOCTL, \ AUTOFS_IOC_PROTOVER_CMD, int) #define AUTOFS_IOC_SETTIMEOUT32 _IOWR(AUTOFS_IOCTL, \ AUTOFS_IOC_SETTIMEOUT_CMD, \ compat_ulong_t) #define AUTOFS_IOC_SETTIMEOUT _IOWR(AUTOFS_IOCTL, \ AUTOFS_IOC_SETTIMEOUT_CMD, \ unsigned long) #define AUTOFS_IOC_EXPIRE _IOR(AUTOFS_IOCTL, \ AUTOFS_IOC_EXPIRE_CMD, \ struct autofs_packet_expire) /* autofs version 4 and later definitions */ /* Mask for expire behaviour */ #define AUTOFS_EXP_NORMAL 0x00 #define AUTOFS_EXP_IMMEDIATE 0x01 #define AUTOFS_EXP_LEAVES 0x02 #define AUTOFS_EXP_FORCED 0x04 #define AUTOFS_TYPE_ANY 0U #define AUTOFS_TYPE_INDIRECT 1U #define AUTOFS_TYPE_DIRECT 2U #define AUTOFS_TYPE_OFFSET 4U static __inline__ void set_autofs_type_indirect(unsigned int *type) { *type = AUTOFS_TYPE_INDIRECT; } static __inline__ unsigned int autofs_type_indirect(unsigned int type) { return (type == AUTOFS_TYPE_INDIRECT); } static __inline__ void set_autofs_type_direct(unsigned int *type) { *type = AUTOFS_TYPE_DIRECT; } static __inline__ unsigned int autofs_type_direct(unsigned int type) { return (type == AUTOFS_TYPE_DIRECT); } static __inline__ void set_autofs_type_offset(unsigned int *type) { *type = AUTOFS_TYPE_OFFSET; } static __inline__ unsigned int autofs_type_offset(unsigned int type) { return (type == AUTOFS_TYPE_OFFSET); } static __inline__ unsigned int autofs_type_trigger(unsigned int type) { return (type == AUTOFS_TYPE_DIRECT || type == AUTOFS_TYPE_OFFSET); } /* * This isn't really a type as we use it to say "no type set" to * indicate we want to search for "any" mount in the * autofs_dev_ioctl_ismountpoint() device ioctl function. */ static __inline__ void set_autofs_type_any(unsigned int *type) { *type = AUTOFS_TYPE_ANY; } static __inline__ unsigned int autofs_type_any(unsigned int type) { return (type == AUTOFS_TYPE_ANY); } /* Daemon notification packet types */ enum autofs_notify { NFY_NONE, NFY_MOUNT, NFY_EXPIRE }; /* Kernel protocol version 4 packet types */ /* Expire entry (umount request) */ #define autofs_ptype_expire_multi 2 /* Kernel protocol version 5 packet types */ /* Indirect mount missing and expire requests. */ #define autofs_ptype_missing_indirect 3 #define autofs_ptype_expire_indirect 4 /* Direct mount missing and expire requests */ #define autofs_ptype_missing_direct 5 #define autofs_ptype_expire_direct 6 /* v4 multi expire (via pipe) */ struct autofs_packet_expire_multi { struct autofs_packet_hdr hdr; autofs_wqt_t wait_queue_token; int len; char name[NAME_MAX+1]; }; union autofs_packet_union { struct autofs_packet_hdr hdr; struct autofs_packet_missing missing; struct autofs_packet_expire expire; struct autofs_packet_expire_multi expire_multi; }; /* autofs v5 common packet struct */ struct autofs_v5_packet { struct autofs_packet_hdr hdr; autofs_wqt_t wait_queue_token; __u32 dev; __u64 ino; __u32 uid; __u32 gid; __u32 pid; __u32 tgid; __u32 len; char name[NAME_MAX+1]; }; typedef struct autofs_v5_packet autofs_packet_missing_indirect_t; typedef struct autofs_v5_packet autofs_packet_expire_indirect_t; typedef struct autofs_v5_packet autofs_packet_missing_direct_t; typedef struct autofs_v5_packet autofs_packet_expire_direct_t; union autofs_v5_packet_union { struct autofs_packet_hdr hdr; struct autofs_v5_packet v5_packet; autofs_packet_missing_indirect_t missing_indirect; autofs_packet_expire_indirect_t expire_indirect; autofs_packet_missing_direct_t missing_direct; autofs_packet_expire_direct_t expire_direct; }; enum { AUTOFS_IOC_EXPIRE_MULTI_CMD = 0x66, /* AUTOFS_IOC_EXPIRE_CMD + 1 */ AUTOFS_IOC_PROTOSUBVER_CMD, AUTOFS_IOC_ASKUMOUNT_CMD = 0x70, /* AUTOFS_DEV_IOCTL_VERSION_CMD - 1 */ }; #define AUTOFS_IOC_EXPIRE_MULTI _IOW(AUTOFS_IOCTL, \ AUTOFS_IOC_EXPIRE_MULTI_CMD, int) #define AUTOFS_IOC_PROTOSUBVER _IOR(AUTOFS_IOCTL, \ AUTOFS_IOC_PROTOSUBVER_CMD, int) #define AUTOFS_IOC_ASKUMOUNT _IOR(AUTOFS_IOCTL, \ AUTOFS_IOC_ASKUMOUNT_CMD, int) #endif /* _LINUX_AUTO_FS_H */ linux/nbd-netlink.h000064400000004550151027430560010270 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2017 Facebook. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #ifndef LINUX_NBD_NETLINK_H #define LINUX_NBD_NETLINK_H #define NBD_GENL_FAMILY_NAME "nbd" #define NBD_GENL_VERSION 0x1 #define NBD_GENL_MCAST_GROUP_NAME "nbd_mc_group" /* Configuration policy attributes, used for CONNECT */ enum { NBD_ATTR_UNSPEC, NBD_ATTR_INDEX, NBD_ATTR_SIZE_BYTES, NBD_ATTR_BLOCK_SIZE_BYTES, NBD_ATTR_TIMEOUT, NBD_ATTR_SERVER_FLAGS, NBD_ATTR_CLIENT_FLAGS, NBD_ATTR_SOCKETS, NBD_ATTR_DEAD_CONN_TIMEOUT, NBD_ATTR_DEVICE_LIST, NBD_ATTR_BACKEND_IDENTIFIER, __NBD_ATTR_MAX, }; #define NBD_ATTR_MAX (__NBD_ATTR_MAX - 1) /* * This is the format for multiple devices with NBD_ATTR_DEVICE_LIST * * [NBD_ATTR_DEVICE_LIST] * [NBD_DEVICE_ITEM] * [NBD_DEVICE_INDEX] * [NBD_DEVICE_CONNECTED] */ enum { NBD_DEVICE_ITEM_UNSPEC, NBD_DEVICE_ITEM, __NBD_DEVICE_ITEM_MAX, }; #define NBD_DEVICE_ITEM_MAX (__NBD_DEVICE_ITEM_MAX - 1) enum { NBD_DEVICE_UNSPEC, NBD_DEVICE_INDEX, NBD_DEVICE_CONNECTED, __NBD_DEVICE_MAX, }; #define NBD_DEVICE_ATTR_MAX (__NBD_DEVICE_MAX - 1) /* * This is the format for multiple sockets with NBD_ATTR_SOCKETS * * [NBD_ATTR_SOCKETS] * [NBD_SOCK_ITEM] * [NBD_SOCK_FD] * [NBD_SOCK_ITEM] * [NBD_SOCK_FD] */ enum { NBD_SOCK_ITEM_UNSPEC, NBD_SOCK_ITEM, __NBD_SOCK_ITEM_MAX, }; #define NBD_SOCK_ITEM_MAX (__NBD_SOCK_ITEM_MAX - 1) enum { NBD_SOCK_UNSPEC, NBD_SOCK_FD, __NBD_SOCK_MAX, }; #define NBD_SOCK_MAX (__NBD_SOCK_MAX - 1) enum { NBD_CMD_UNSPEC, NBD_CMD_CONNECT, NBD_CMD_DISCONNECT, NBD_CMD_RECONFIGURE, NBD_CMD_LINK_DEAD, NBD_CMD_STATUS, __NBD_CMD_MAX, }; #define NBD_CMD_MAX (__NBD_CMD_MAX - 1) #endif /* LINUX_NBD_NETLINK_H */ linux/snmp.h000064400000032537151027430560007046 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Definitions for MIBs * * Author: Hideaki YOSHIFUJI */ #ifndef _LINUX_SNMP_H #define _LINUX_SNMP_H /* ipstats mib definitions */ /* * RFC 1213: MIB-II * RFC 2011 (updates 1213): SNMPv2-MIB-IP * RFC 2863: Interfaces Group MIB * RFC 2465: IPv6 MIB: General Group * draft-ietf-ipv6-rfc2011-update-10.txt: MIB for IP: IP Statistics Tables */ enum { IPSTATS_MIB_NUM = 0, /* frequently written fields in fast path, kept in same cache line */ IPSTATS_MIB_INPKTS, /* InReceives */ IPSTATS_MIB_INOCTETS, /* InOctets */ IPSTATS_MIB_INDELIVERS, /* InDelivers */ IPSTATS_MIB_OUTFORWDATAGRAMS, /* OutForwDatagrams */ IPSTATS_MIB_OUTPKTS, /* OutRequests */ IPSTATS_MIB_OUTOCTETS, /* OutOctets */ /* other fields */ IPSTATS_MIB_INHDRERRORS, /* InHdrErrors */ IPSTATS_MIB_INTOOBIGERRORS, /* InTooBigErrors */ IPSTATS_MIB_INNOROUTES, /* InNoRoutes */ IPSTATS_MIB_INADDRERRORS, /* InAddrErrors */ IPSTATS_MIB_INUNKNOWNPROTOS, /* InUnknownProtos */ IPSTATS_MIB_INTRUNCATEDPKTS, /* InTruncatedPkts */ IPSTATS_MIB_INDISCARDS, /* InDiscards */ IPSTATS_MIB_OUTDISCARDS, /* OutDiscards */ IPSTATS_MIB_OUTNOROUTES, /* OutNoRoutes */ IPSTATS_MIB_REASMTIMEOUT, /* ReasmTimeout */ IPSTATS_MIB_REASMREQDS, /* ReasmReqds */ IPSTATS_MIB_REASMOKS, /* ReasmOKs */ IPSTATS_MIB_REASMFAILS, /* ReasmFails */ IPSTATS_MIB_FRAGOKS, /* FragOKs */ IPSTATS_MIB_FRAGFAILS, /* FragFails */ IPSTATS_MIB_FRAGCREATES, /* FragCreates */ IPSTATS_MIB_INMCASTPKTS, /* InMcastPkts */ IPSTATS_MIB_OUTMCASTPKTS, /* OutMcastPkts */ IPSTATS_MIB_INBCASTPKTS, /* InBcastPkts */ IPSTATS_MIB_OUTBCASTPKTS, /* OutBcastPkts */ IPSTATS_MIB_INMCASTOCTETS, /* InMcastOctets */ IPSTATS_MIB_OUTMCASTOCTETS, /* OutMcastOctets */ IPSTATS_MIB_INBCASTOCTETS, /* InBcastOctets */ IPSTATS_MIB_OUTBCASTOCTETS, /* OutBcastOctets */ IPSTATS_MIB_CSUMERRORS, /* InCsumErrors */ IPSTATS_MIB_NOECTPKTS, /* InNoECTPkts */ IPSTATS_MIB_ECT1PKTS, /* InECT1Pkts */ IPSTATS_MIB_ECT0PKTS, /* InECT0Pkts */ IPSTATS_MIB_CEPKTS, /* InCEPkts */ IPSTATS_MIB_REASM_OVERLAPS, /* ReasmOverlaps */ __IPSTATS_MIB_MAX }; /* icmp mib definitions */ /* * RFC 1213: MIB-II ICMP Group * RFC 2011 (updates 1213): SNMPv2 MIB for IP: ICMP group */ enum { ICMP_MIB_NUM = 0, ICMP_MIB_INMSGS, /* InMsgs */ ICMP_MIB_INERRORS, /* InErrors */ ICMP_MIB_INDESTUNREACHS, /* InDestUnreachs */ ICMP_MIB_INTIMEEXCDS, /* InTimeExcds */ ICMP_MIB_INPARMPROBS, /* InParmProbs */ ICMP_MIB_INSRCQUENCHS, /* InSrcQuenchs */ ICMP_MIB_INREDIRECTS, /* InRedirects */ ICMP_MIB_INECHOS, /* InEchos */ ICMP_MIB_INECHOREPS, /* InEchoReps */ ICMP_MIB_INTIMESTAMPS, /* InTimestamps */ ICMP_MIB_INTIMESTAMPREPS, /* InTimestampReps */ ICMP_MIB_INADDRMASKS, /* InAddrMasks */ ICMP_MIB_INADDRMASKREPS, /* InAddrMaskReps */ ICMP_MIB_OUTMSGS, /* OutMsgs */ ICMP_MIB_OUTERRORS, /* OutErrors */ ICMP_MIB_OUTDESTUNREACHS, /* OutDestUnreachs */ ICMP_MIB_OUTTIMEEXCDS, /* OutTimeExcds */ ICMP_MIB_OUTPARMPROBS, /* OutParmProbs */ ICMP_MIB_OUTSRCQUENCHS, /* OutSrcQuenchs */ ICMP_MIB_OUTREDIRECTS, /* OutRedirects */ ICMP_MIB_OUTECHOS, /* OutEchos */ ICMP_MIB_OUTECHOREPS, /* OutEchoReps */ ICMP_MIB_OUTTIMESTAMPS, /* OutTimestamps */ ICMP_MIB_OUTTIMESTAMPREPS, /* OutTimestampReps */ ICMP_MIB_OUTADDRMASKS, /* OutAddrMasks */ ICMP_MIB_OUTADDRMASKREPS, /* OutAddrMaskReps */ ICMP_MIB_CSUMERRORS, /* InCsumErrors */ __ICMP_MIB_MAX }; #define __ICMPMSG_MIB_MAX 512 /* Out+In for all 8-bit ICMP types */ /* icmp6 mib definitions */ /* * RFC 2466: ICMPv6-MIB */ enum { ICMP6_MIB_NUM = 0, ICMP6_MIB_INMSGS, /* InMsgs */ ICMP6_MIB_INERRORS, /* InErrors */ ICMP6_MIB_OUTMSGS, /* OutMsgs */ ICMP6_MIB_OUTERRORS, /* OutErrors */ ICMP6_MIB_CSUMERRORS, /* InCsumErrors */ __ICMP6_MIB_MAX }; #define __ICMP6MSG_MIB_MAX 512 /* Out+In for all 8-bit ICMPv6 types */ /* tcp mib definitions */ /* * RFC 1213: MIB-II TCP group * RFC 2012 (updates 1213): SNMPv2-MIB-TCP */ enum { TCP_MIB_NUM = 0, TCP_MIB_RTOALGORITHM, /* RtoAlgorithm */ TCP_MIB_RTOMIN, /* RtoMin */ TCP_MIB_RTOMAX, /* RtoMax */ TCP_MIB_MAXCONN, /* MaxConn */ TCP_MIB_ACTIVEOPENS, /* ActiveOpens */ TCP_MIB_PASSIVEOPENS, /* PassiveOpens */ TCP_MIB_ATTEMPTFAILS, /* AttemptFails */ TCP_MIB_ESTABRESETS, /* EstabResets */ TCP_MIB_CURRESTAB, /* CurrEstab */ TCP_MIB_INSEGS, /* InSegs */ TCP_MIB_OUTSEGS, /* OutSegs */ TCP_MIB_RETRANSSEGS, /* RetransSegs */ TCP_MIB_INERRS, /* InErrs */ TCP_MIB_OUTRSTS, /* OutRsts */ TCP_MIB_CSUMERRORS, /* InCsumErrors */ __TCP_MIB_MAX }; /* udp mib definitions */ /* * RFC 1213: MIB-II UDP group * RFC 2013 (updates 1213): SNMPv2-MIB-UDP */ enum { UDP_MIB_NUM = 0, UDP_MIB_INDATAGRAMS, /* InDatagrams */ UDP_MIB_NOPORTS, /* NoPorts */ UDP_MIB_INERRORS, /* InErrors */ UDP_MIB_OUTDATAGRAMS, /* OutDatagrams */ UDP_MIB_RCVBUFERRORS, /* RcvbufErrors */ UDP_MIB_SNDBUFERRORS, /* SndbufErrors */ UDP_MIB_CSUMERRORS, /* InCsumErrors */ UDP_MIB_IGNOREDMULTI, /* IgnoredMulti */ #ifndef __GENKSYMS__ UDP_MIB_MEMERRORS, /* MemErrors */ #endif __UDP_MIB_MAX }; /* linux mib definitions */ enum { LINUX_MIB_NUM = 0, LINUX_MIB_SYNCOOKIESSENT, /* SyncookiesSent */ LINUX_MIB_SYNCOOKIESRECV, /* SyncookiesRecv */ LINUX_MIB_SYNCOOKIESFAILED, /* SyncookiesFailed */ LINUX_MIB_EMBRYONICRSTS, /* EmbryonicRsts */ LINUX_MIB_PRUNECALLED, /* PruneCalled */ LINUX_MIB_RCVPRUNED, /* RcvPruned */ LINUX_MIB_OFOPRUNED, /* OfoPruned */ LINUX_MIB_OUTOFWINDOWICMPS, /* OutOfWindowIcmps */ LINUX_MIB_LOCKDROPPEDICMPS, /* LockDroppedIcmps */ LINUX_MIB_ARPFILTER, /* ArpFilter */ LINUX_MIB_TIMEWAITED, /* TimeWaited */ LINUX_MIB_TIMEWAITRECYCLED, /* TimeWaitRecycled */ LINUX_MIB_TIMEWAITKILLED, /* TimeWaitKilled */ LINUX_MIB_PAWSACTIVEREJECTED, /* PAWSActiveRejected */ LINUX_MIB_PAWSESTABREJECTED, /* PAWSEstabRejected */ LINUX_MIB_DELAYEDACKS, /* DelayedACKs */ LINUX_MIB_DELAYEDACKLOCKED, /* DelayedACKLocked */ LINUX_MIB_DELAYEDACKLOST, /* DelayedACKLost */ LINUX_MIB_LISTENOVERFLOWS, /* ListenOverflows */ LINUX_MIB_LISTENDROPS, /* ListenDrops */ LINUX_MIB_TCPHPHITS, /* TCPHPHits */ LINUX_MIB_TCPPUREACKS, /* TCPPureAcks */ LINUX_MIB_TCPHPACKS, /* TCPHPAcks */ LINUX_MIB_TCPRENORECOVERY, /* TCPRenoRecovery */ LINUX_MIB_TCPSACKRECOVERY, /* TCPSackRecovery */ LINUX_MIB_TCPSACKRENEGING, /* TCPSACKReneging */ LINUX_MIB_TCPSACKREORDER, /* TCPSACKReorder */ LINUX_MIB_TCPRENOREORDER, /* TCPRenoReorder */ LINUX_MIB_TCPTSREORDER, /* TCPTSReorder */ LINUX_MIB_TCPFULLUNDO, /* TCPFullUndo */ LINUX_MIB_TCPPARTIALUNDO, /* TCPPartialUndo */ LINUX_MIB_TCPDSACKUNDO, /* TCPDSACKUndo */ LINUX_MIB_TCPLOSSUNDO, /* TCPLossUndo */ LINUX_MIB_TCPLOSTRETRANSMIT, /* TCPLostRetransmit */ LINUX_MIB_TCPRENOFAILURES, /* TCPRenoFailures */ LINUX_MIB_TCPSACKFAILURES, /* TCPSackFailures */ LINUX_MIB_TCPLOSSFAILURES, /* TCPLossFailures */ LINUX_MIB_TCPFASTRETRANS, /* TCPFastRetrans */ LINUX_MIB_TCPSLOWSTARTRETRANS, /* TCPSlowStartRetrans */ LINUX_MIB_TCPTIMEOUTS, /* TCPTimeouts */ LINUX_MIB_TCPLOSSPROBES, /* TCPLossProbes */ LINUX_MIB_TCPLOSSPROBERECOVERY, /* TCPLossProbeRecovery */ LINUX_MIB_TCPRENORECOVERYFAIL, /* TCPRenoRecoveryFail */ LINUX_MIB_TCPSACKRECOVERYFAIL, /* TCPSackRecoveryFail */ LINUX_MIB_TCPRCVCOLLAPSED, /* TCPRcvCollapsed */ LINUX_MIB_TCPDSACKOLDSENT, /* TCPDSACKOldSent */ LINUX_MIB_TCPDSACKOFOSENT, /* TCPDSACKOfoSent */ LINUX_MIB_TCPDSACKRECV, /* TCPDSACKRecv */ LINUX_MIB_TCPDSACKOFORECV, /* TCPDSACKOfoRecv */ LINUX_MIB_TCPABORTONDATA, /* TCPAbortOnData */ LINUX_MIB_TCPABORTONCLOSE, /* TCPAbortOnClose */ LINUX_MIB_TCPABORTONMEMORY, /* TCPAbortOnMemory */ LINUX_MIB_TCPABORTONTIMEOUT, /* TCPAbortOnTimeout */ LINUX_MIB_TCPABORTONLINGER, /* TCPAbortOnLinger */ LINUX_MIB_TCPABORTFAILED, /* TCPAbortFailed */ LINUX_MIB_TCPMEMORYPRESSURES, /* TCPMemoryPressures */ LINUX_MIB_TCPMEMORYPRESSURESCHRONO, /* TCPMemoryPressuresChrono */ LINUX_MIB_TCPSACKDISCARD, /* TCPSACKDiscard */ LINUX_MIB_TCPDSACKIGNOREDOLD, /* TCPSACKIgnoredOld */ LINUX_MIB_TCPDSACKIGNOREDNOUNDO, /* TCPSACKIgnoredNoUndo */ LINUX_MIB_TCPSPURIOUSRTOS, /* TCPSpuriousRTOs */ LINUX_MIB_TCPMD5NOTFOUND, /* TCPMD5NotFound */ LINUX_MIB_TCPMD5UNEXPECTED, /* TCPMD5Unexpected */ LINUX_MIB_TCPMD5FAILURE, /* TCPMD5Failure */ LINUX_MIB_SACKSHIFTED, LINUX_MIB_SACKMERGED, LINUX_MIB_SACKSHIFTFALLBACK, LINUX_MIB_TCPBACKLOGDROP, LINUX_MIB_PFMEMALLOCDROP, LINUX_MIB_TCPMINTTLDROP, /* RFC 5082 */ LINUX_MIB_TCPDEFERACCEPTDROP, LINUX_MIB_IPRPFILTER, /* IP Reverse Path Filter (rp_filter) */ LINUX_MIB_TCPTIMEWAITOVERFLOW, /* TCPTimeWaitOverflow */ LINUX_MIB_TCPREQQFULLDOCOOKIES, /* TCPReqQFullDoCookies */ LINUX_MIB_TCPREQQFULLDROP, /* TCPReqQFullDrop */ LINUX_MIB_TCPRETRANSFAIL, /* TCPRetransFail */ LINUX_MIB_TCPRCVCOALESCE, /* TCPRcvCoalesce */ #ifndef __GENKSYMS__ LINUX_MIB_TCPBACKLOGCOALESCE, /* TCPBacklogCoalesce */ #endif LINUX_MIB_TCPOFOQUEUE, /* TCPOFOQueue */ LINUX_MIB_TCPOFODROP, /* TCPOFODrop */ LINUX_MIB_TCPOFOMERGE, /* TCPOFOMerge */ LINUX_MIB_TCPCHALLENGEACK, /* TCPChallengeACK */ LINUX_MIB_TCPSYNCHALLENGE, /* TCPSYNChallenge */ LINUX_MIB_TCPFASTOPENACTIVE, /* TCPFastOpenActive */ LINUX_MIB_TCPFASTOPENACTIVEFAIL, /* TCPFastOpenActiveFail */ LINUX_MIB_TCPFASTOPENPASSIVE, /* TCPFastOpenPassive*/ LINUX_MIB_TCPFASTOPENPASSIVEFAIL, /* TCPFastOpenPassiveFail */ LINUX_MIB_TCPFASTOPENLISTENOVERFLOW, /* TCPFastOpenListenOverflow */ LINUX_MIB_TCPFASTOPENCOOKIEREQD, /* TCPFastOpenCookieReqd */ LINUX_MIB_TCPFASTOPENBLACKHOLE, /* TCPFastOpenBlackholeDetect */ LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES, /* TCPSpuriousRtxHostQueues */ LINUX_MIB_BUSYPOLLRXPACKETS, /* BusyPollRxPackets */ LINUX_MIB_TCPAUTOCORKING, /* TCPAutoCorking */ LINUX_MIB_TCPFROMZEROWINDOWADV, /* TCPFromZeroWindowAdv */ LINUX_MIB_TCPTOZEROWINDOWADV, /* TCPToZeroWindowAdv */ LINUX_MIB_TCPWANTZEROWINDOWADV, /* TCPWantZeroWindowAdv */ LINUX_MIB_TCPSYNRETRANS, /* TCPSynRetrans */ LINUX_MIB_TCPORIGDATASENT, /* TCPOrigDataSent */ LINUX_MIB_TCPHYSTARTTRAINDETECT, /* TCPHystartTrainDetect */ LINUX_MIB_TCPHYSTARTTRAINCWND, /* TCPHystartTrainCwnd */ LINUX_MIB_TCPHYSTARTDELAYDETECT, /* TCPHystartDelayDetect */ LINUX_MIB_TCPHYSTARTDELAYCWND, /* TCPHystartDelayCwnd */ LINUX_MIB_TCPACKSKIPPEDSYNRECV, /* TCPACKSkippedSynRecv */ LINUX_MIB_TCPACKSKIPPEDPAWS, /* TCPACKSkippedPAWS */ LINUX_MIB_TCPACKSKIPPEDSEQ, /* TCPACKSkippedSeq */ LINUX_MIB_TCPACKSKIPPEDFINWAIT2, /* TCPACKSkippedFinWait2 */ LINUX_MIB_TCPACKSKIPPEDTIMEWAIT, /* TCPACKSkippedTimeWait */ LINUX_MIB_TCPACKSKIPPEDCHALLENGE, /* TCPACKSkippedChallenge */ LINUX_MIB_TCPWINPROBE, /* TCPWinProbe */ LINUX_MIB_TCPKEEPALIVE, /* TCPKeepAlive */ LINUX_MIB_TCPMTUPFAIL, /* TCPMTUPFail */ LINUX_MIB_TCPMTUPSUCCESS, /* TCPMTUPSuccess */ LINUX_MIB_TCPDELIVERED, /* TCPDelivered */ LINUX_MIB_TCPDELIVEREDCE, /* TCPDeliveredCE */ LINUX_MIB_TCPACKCOMPRESSED, /* TCPAckCompressed */ #ifndef __GENKSYMS__ LINUX_MIB_TCPZEROWINDOWDROP, /* TCPZeroWindowDrop */ LINUX_MIB_TCPRCVQDROP, /* TCPRcvQDrop */ LINUX_MIB_TCPWQUEUETOOBIG, /* TCPWqueueTooBig */ LINUX_MIB_TCPTIMEOUTREHASH, /* TCPTimeoutRehash */ #endif __LINUX_MIB_MAX }; /* linux Xfrm mib definitions */ enum { LINUX_MIB_XFRMNUM = 0, LINUX_MIB_XFRMINERROR, /* XfrmInError */ LINUX_MIB_XFRMINBUFFERERROR, /* XfrmInBufferError */ LINUX_MIB_XFRMINHDRERROR, /* XfrmInHdrError */ LINUX_MIB_XFRMINNOSTATES, /* XfrmInNoStates */ LINUX_MIB_XFRMINSTATEPROTOERROR, /* XfrmInStateProtoError */ LINUX_MIB_XFRMINSTATEMODEERROR, /* XfrmInStateModeError */ LINUX_MIB_XFRMINSTATESEQERROR, /* XfrmInStateSeqError */ LINUX_MIB_XFRMINSTATEEXPIRED, /* XfrmInStateExpired */ LINUX_MIB_XFRMINSTATEMISMATCH, /* XfrmInStateMismatch */ LINUX_MIB_XFRMINSTATEINVALID, /* XfrmInStateInvalid */ LINUX_MIB_XFRMINTMPLMISMATCH, /* XfrmInTmplMismatch */ LINUX_MIB_XFRMINNOPOLS, /* XfrmInNoPols */ LINUX_MIB_XFRMINPOLBLOCK, /* XfrmInPolBlock */ LINUX_MIB_XFRMINPOLERROR, /* XfrmInPolError */ LINUX_MIB_XFRMOUTERROR, /* XfrmOutError */ LINUX_MIB_XFRMOUTBUNDLEGENERROR, /* XfrmOutBundleGenError */ LINUX_MIB_XFRMOUTBUNDLECHECKERROR, /* XfrmOutBundleCheckError */ LINUX_MIB_XFRMOUTNOSTATES, /* XfrmOutNoStates */ LINUX_MIB_XFRMOUTSTATEPROTOERROR, /* XfrmOutStateProtoError */ LINUX_MIB_XFRMOUTSTATEMODEERROR, /* XfrmOutStateModeError */ LINUX_MIB_XFRMOUTSTATESEQERROR, /* XfrmOutStateSeqError */ LINUX_MIB_XFRMOUTSTATEEXPIRED, /* XfrmOutStateExpired */ LINUX_MIB_XFRMOUTPOLBLOCK, /* XfrmOutPolBlock */ LINUX_MIB_XFRMOUTPOLDEAD, /* XfrmOutPolDead */ LINUX_MIB_XFRMOUTPOLERROR, /* XfrmOutPolError */ LINUX_MIB_XFRMFWDHDRERROR, /* XfrmFwdHdrError*/ LINUX_MIB_XFRMOUTSTATEINVALID, /* XfrmOutStateInvalid */ LINUX_MIB_XFRMACQUIREERROR, /* XfrmAcquireError */ __LINUX_MIB_XFRMMAX }; /* linux TLS mib definitions */ enum { LINUX_MIB_TLSNUM = 0, LINUX_MIB_TLSCURRTXSW, /* TlsCurrTxSw */ LINUX_MIB_TLSCURRRXSW, /* TlsCurrRxSw */ LINUX_MIB_TLSCURRTXDEVICE, /* TlsCurrTxDevice */ LINUX_MIB_TLSCURRRXDEVICE, /* TlsCurrRxDevice */ LINUX_MIB_TLSTXSW, /* TlsTxSw */ LINUX_MIB_TLSRXSW, /* TlsRxSw */ LINUX_MIB_TLSTXDEVICE, /* TlsTxDevice */ LINUX_MIB_TLSRXDEVICE, /* TlsRxDevice */ LINUX_MIB_TLSDECRYPTERROR, /* TlsDecryptError */ LINUX_MIB_TLSRXDEVICERESYNC, /* TlsRxDeviceResync */ __LINUX_MIB_TLSMAX }; #endif /* _LINUX_SNMP_H */ linux/elf-fdpic.h000064400000002144151027430560007711 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* elf-fdpic.h: FDPIC ELF load map * * Copyright (C) 2003 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_ELF_FDPIC_H #define _LINUX_ELF_FDPIC_H #include #define PT_GNU_STACK (PT_LOOS + 0x474e551) /* segment mappings for ELF FDPIC libraries/executables/interpreters */ struct elf32_fdpic_loadseg { Elf32_Addr addr; /* core address to which mapped */ Elf32_Addr p_vaddr; /* VMA recorded in file */ Elf32_Word p_memsz; /* allocation size recorded in file */ }; struct elf32_fdpic_loadmap { Elf32_Half version; /* version of these structures, just in case... */ Elf32_Half nsegs; /* number of segments */ struct elf32_fdpic_loadseg segs[]; }; #define ELF32_FDPIC_LOADMAP_VERSION 0x0000 #endif /* _LINUX_ELF_FDPIC_H */ linux/capability.h000064400000032321151027430560010201 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * This is * * Andrew G. Morgan * Alexander Kjeldaas * with help from Aleph1, Roland Buresund and Andrew Main. * * See here for the libcap library ("POSIX draft" compliance): * * ftp://www.kernel.org/pub/linux/libs/security/linux-privs/kernel-2.6/ */ #ifndef _LINUX_CAPABILITY_H #define _LINUX_CAPABILITY_H #include /* User-level do most of the mapping between kernel and user capabilities based on the version tag given by the kernel. The kernel might be somewhat backwards compatible, but don't bet on it. */ /* Note, cap_t, is defined by POSIX (draft) to be an "opaque" pointer to a set of three capability sets. The transposition of 3*the following structure to such a composite is better handled in a user library since the draft standard requires the use of malloc/free etc.. */ #define _LINUX_CAPABILITY_VERSION_1 0x19980330 #define _LINUX_CAPABILITY_U32S_1 1 #define _LINUX_CAPABILITY_VERSION_2 0x20071026 /* deprecated - use v3 */ #define _LINUX_CAPABILITY_U32S_2 2 #define _LINUX_CAPABILITY_VERSION_3 0x20080522 #define _LINUX_CAPABILITY_U32S_3 2 typedef struct __user_cap_header_struct { __u32 version; int pid; } *cap_user_header_t; typedef struct __user_cap_data_struct { __u32 effective; __u32 permitted; __u32 inheritable; } *cap_user_data_t; #define VFS_CAP_REVISION_MASK 0xFF000000 #define VFS_CAP_REVISION_SHIFT 24 #define VFS_CAP_FLAGS_MASK ~VFS_CAP_REVISION_MASK #define VFS_CAP_FLAGS_EFFECTIVE 0x000001 #define VFS_CAP_REVISION_1 0x01000000 #define VFS_CAP_U32_1 1 #define XATTR_CAPS_SZ_1 (sizeof(__le32)*(1 + 2*VFS_CAP_U32_1)) #define VFS_CAP_REVISION_2 0x02000000 #define VFS_CAP_U32_2 2 #define XATTR_CAPS_SZ_2 (sizeof(__le32)*(1 + 2*VFS_CAP_U32_2)) #define VFS_CAP_REVISION_3 0x03000000 #define VFS_CAP_U32_3 2 #define XATTR_CAPS_SZ_3 (sizeof(__le32)*(2 + 2*VFS_CAP_U32_3)) #define XATTR_CAPS_SZ XATTR_CAPS_SZ_3 #define VFS_CAP_U32 VFS_CAP_U32_3 #define VFS_CAP_REVISION VFS_CAP_REVISION_3 struct vfs_cap_data { __le32 magic_etc; /* Little endian */ struct { __le32 permitted; /* Little endian */ __le32 inheritable; /* Little endian */ } data[VFS_CAP_U32]; }; /* * same as vfs_cap_data but with a rootid at the end */ struct vfs_ns_cap_data { __le32 magic_etc; struct { __le32 permitted; /* Little endian */ __le32 inheritable; /* Little endian */ } data[VFS_CAP_U32]; __le32 rootid; }; /* * Backwardly compatible definition for source code - trapped in a * 32-bit world. If you find you need this, please consider using * libcap to untrap yourself... */ #define _LINUX_CAPABILITY_VERSION _LINUX_CAPABILITY_VERSION_1 #define _LINUX_CAPABILITY_U32S _LINUX_CAPABILITY_U32S_1 /** ** POSIX-draft defined capabilities. **/ /* In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this overrides the restriction of changing file ownership and group ownership. */ #define CAP_CHOWN 0 /* Override all DAC access, including ACL execute access if [_POSIX_ACL] is defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. */ #define CAP_DAC_OVERRIDE 1 /* Overrides all DAC restrictions regarding read and search on files and directories, including ACL restrictions if [_POSIX_ACL] is defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. */ #define CAP_DAC_READ_SEARCH 2 /* Overrides all restrictions about allowed operations on files, where file owner ID must be equal to the user ID, except where CAP_FSETID is applicable. It doesn't override MAC and DAC restrictions. */ #define CAP_FOWNER 3 /* Overrides the following restrictions that the effective user ID shall match the file owner ID when setting the S_ISUID and S_ISGID bits on that file; that the effective group ID (or one of the supplementary group IDs) shall match the file owner ID when setting the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are cleared on successful return from chown(2) (not implemented). */ #define CAP_FSETID 4 /* Overrides the restriction that the real or effective user ID of a process sending a signal must match the real or effective user ID of the process receiving the signal. */ #define CAP_KILL 5 /* Allows setgid(2) manipulation */ /* Allows setgroups(2) */ /* Allows forged gids on socket credentials passing. */ #define CAP_SETGID 6 /* Allows set*uid(2) manipulation (including fsuid). */ /* Allows forged pids on socket credentials passing. */ #define CAP_SETUID 7 /** ** Linux-specific capabilities **/ /* Without VFS support for capabilities: * Transfer any capability in your permitted set to any pid, * remove any capability in your permitted set from any pid * With VFS support for capabilities (neither of above, but) * Add any capability from current's capability bounding set * to the current process' inheritable set * Allow taking bits out of capability bounding set * Allow modification of the securebits for a process */ #define CAP_SETPCAP 8 /* Allow modification of S_IMMUTABLE and S_APPEND file attributes */ #define CAP_LINUX_IMMUTABLE 9 /* Allows binding to TCP/UDP sockets below 1024 */ /* Allows binding to ATM VCIs below 32 */ #define CAP_NET_BIND_SERVICE 10 /* Allow broadcasting, listen to multicast */ #define CAP_NET_BROADCAST 11 /* Allow interface configuration */ /* Allow administration of IP firewall, masquerading and accounting */ /* Allow setting debug option on sockets */ /* Allow modification of routing tables */ /* Allow setting arbitrary process / process group ownership on sockets */ /* Allow binding to any address for transparent proxying (also via NET_RAW) */ /* Allow setting TOS (type of service) */ /* Allow setting promiscuous mode */ /* Allow clearing driver statistics */ /* Allow multicasting */ /* Allow read/write of device-specific registers */ /* Allow activation of ATM control sockets */ #define CAP_NET_ADMIN 12 /* Allow use of RAW sockets */ /* Allow use of PACKET sockets */ /* Allow binding to any address for transparent proxying (also via NET_ADMIN) */ #define CAP_NET_RAW 13 /* Allow locking of shared memory segments */ /* Allow mlock and mlockall (which doesn't really have anything to do with IPC) */ #define CAP_IPC_LOCK 14 /* Override IPC ownership checks */ #define CAP_IPC_OWNER 15 /* Insert and remove kernel modules - modify kernel without limit */ #define CAP_SYS_MODULE 16 /* Allow ioperm/iopl access */ /* Allow sending USB messages to any device via /dev/bus/usb */ #define CAP_SYS_RAWIO 17 /* Allow use of chroot() */ #define CAP_SYS_CHROOT 18 /* Allow ptrace() of any process */ #define CAP_SYS_PTRACE 19 /* Allow configuration of process accounting */ #define CAP_SYS_PACCT 20 /* Allow configuration of the secure attention key */ /* Allow administration of the random device */ /* Allow examination and configuration of disk quotas */ /* Allow setting the domainname */ /* Allow setting the hostname */ /* Allow calling bdflush() */ /* Allow mount() and umount(), setting up new smb connection */ /* Allow some autofs root ioctls */ /* Allow nfsservctl */ /* Allow VM86_REQUEST_IRQ */ /* Allow to read/write pci config on alpha */ /* Allow irix_prctl on mips (setstacksize) */ /* Allow flushing all cache on m68k (sys_cacheflush) */ /* Allow removing semaphores */ /* Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores and shared memory */ /* Allow locking/unlocking of shared memory segment */ /* Allow turning swap on/off */ /* Allow forged pids on socket credentials passing */ /* Allow setting readahead and flushing buffers on block devices */ /* Allow setting geometry in floppy driver */ /* Allow turning DMA on/off in xd driver */ /* Allow administration of md devices (mostly the above, but some extra ioctls) */ /* Allow tuning the ide driver */ /* Allow access to the nvram device */ /* Allow administration of apm_bios, serial and bttv (TV) device */ /* Allow manufacturer commands in isdn CAPI support driver */ /* Allow reading non-standardized portions of pci configuration space */ /* Allow DDI debug ioctl on sbpcd driver */ /* Allow setting up serial ports */ /* Allow sending raw qic-117 commands */ /* Allow enabling/disabling tagged queuing on SCSI controllers and sending arbitrary SCSI commands */ /* Allow setting encryption key on loopback filesystem */ /* Allow setting zone reclaim policy */ /* Allow everything under CAP_BPF and CAP_PERFMON for backward compatibility */ #define CAP_SYS_ADMIN 21 /* Allow use of reboot() */ #define CAP_SYS_BOOT 22 /* Allow raising priority and setting priority on other (different UID) processes */ /* Allow use of FIFO and round-robin (realtime) scheduling on own processes and setting the scheduling algorithm used by another process. */ /* Allow setting cpu affinity on other processes */ /* Allow setting realtime ioprio class */ /* Allow setting ioprio class on other processes */ #define CAP_SYS_NICE 23 /* Override resource limits. Set resource limits. */ /* Override quota limits. */ /* Override reserved space on ext2 filesystem */ /* Modify data journaling mode on ext3 filesystem (uses journaling resources) */ /* NOTE: ext2 honors fsuid when checking for resource overrides, so you can override using fsuid too */ /* Override size restrictions on IPC message queues */ /* Allow more than 64hz interrupts from the real-time clock */ /* Override max number of consoles on console allocation */ /* Override max number of keymaps */ /* Control memory reclaim behavior */ #define CAP_SYS_RESOURCE 24 /* Allow manipulation of system clock */ /* Allow irix_stime on mips */ /* Allow setting the real-time clock */ #define CAP_SYS_TIME 25 /* Allow configuration of tty devices */ /* Allow vhangup() of tty */ #define CAP_SYS_TTY_CONFIG 26 /* Allow the privileged aspects of mknod() */ #define CAP_MKNOD 27 /* Allow taking of leases on files */ #define CAP_LEASE 28 /* Allow writing the audit log via unicast netlink socket */ #define CAP_AUDIT_WRITE 29 /* Allow configuration of audit via unicast netlink socket */ #define CAP_AUDIT_CONTROL 30 /* Set or remove capabilities on files. Map uid=0 into a child user namespace. */ #define CAP_SETFCAP 31 /* Override MAC access. The base kernel enforces no MAC policy. An LSM may enforce a MAC policy, and if it does and it chooses to implement capability based overrides of that policy, this is the capability it should use to do so. */ #define CAP_MAC_OVERRIDE 32 /* Allow MAC configuration or state changes. The base kernel requires no MAC configuration. An LSM may enforce a MAC policy, and if it does and it chooses to implement capability based checks on modifications to that policy or the data required to maintain it, this is the capability it should use to do so. */ #define CAP_MAC_ADMIN 33 /* Allow configuring the kernel's syslog (printk behaviour) */ #define CAP_SYSLOG 34 /* Allow triggering something that will wake the system */ #define CAP_WAKE_ALARM 35 /* Allow preventing system suspends */ #define CAP_BLOCK_SUSPEND 36 /* Allow reading the audit log via multicast netlink socket */ #define CAP_AUDIT_READ 37 /* * Allow system performance and observability privileged operations * using perf_events, i915_perf and other kernel subsystems */ #define CAP_PERFMON 38 /* * CAP_BPF allows the following BPF operations: * - Creating all types of BPF maps * - Advanced verifier features * - Indirect variable access * - Bounded loops * - BPF to BPF function calls * - Scalar precision tracking * - Larger complexity limits * - Dead code elimination * - And potentially other features * - Loading BPF Type Format (BTF) data * - Retrieve xlated and JITed code of BPF programs * - Use bpf_spin_lock() helper * * CAP_PERFMON relaxes the verifier checks further: * - BPF progs can use of pointer-to-integer conversions * - speculation attack hardening measures are bypassed * - bpf_probe_read to read arbitrary kernel memory is allowed * - bpf_trace_printk to print kernel memory is allowed * * CAP_SYS_ADMIN is required to use bpf_probe_write_user. * * CAP_SYS_ADMIN is required to iterate system wide loaded * programs, maps, links, BTFs and convert their IDs to file descriptors. * * CAP_PERFMON and CAP_BPF are required to load tracing programs. * CAP_NET_ADMIN and CAP_BPF are required to load networking programs. */ #define CAP_BPF 39 /* Allow checkpoint/restore related operations */ /* Allow PID selection during clone3() */ /* Allow writing to ns_last_pid */ #define CAP_CHECKPOINT_RESTORE 40 #define CAP_LAST_CAP CAP_CHECKPOINT_RESTORE #define cap_valid(x) ((x) >= 0 && (x) <= CAP_LAST_CAP) /* * Bit location of each capability (used by user-space library and kernel) */ #define CAP_TO_INDEX(x) ((x) >> 5) /* 1 << 5 == bits in __u32 */ #define CAP_TO_MASK(x) (1 << ((x) & 31)) /* mask for indexed __u32 */ #endif /* _LINUX_CAPABILITY_H */ linux/netlink.h000064400000026347151027430560007537 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_NETLINK_H #define __LINUX_NETLINK_H #include #include /* for __kernel_sa_family_t */ #include #define NETLINK_ROUTE 0 /* Routing/device hook */ #define NETLINK_UNUSED 1 /* Unused number */ #define NETLINK_USERSOCK 2 /* Reserved for user mode socket protocols */ #define NETLINK_FIREWALL 3 /* Unused number, formerly ip_queue */ #define NETLINK_SOCK_DIAG 4 /* socket monitoring */ #define NETLINK_NFLOG 5 /* netfilter/iptables ULOG */ #define NETLINK_XFRM 6 /* ipsec */ #define NETLINK_SELINUX 7 /* SELinux event notifications */ #define NETLINK_ISCSI 8 /* Open-iSCSI */ #define NETLINK_AUDIT 9 /* auditing */ #define NETLINK_FIB_LOOKUP 10 #define NETLINK_CONNECTOR 11 #define NETLINK_NETFILTER 12 /* netfilter subsystem */ #define NETLINK_IP6_FW 13 #define NETLINK_DNRTMSG 14 /* DECnet routing messages */ #define NETLINK_KOBJECT_UEVENT 15 /* Kernel messages to userspace */ #define NETLINK_GENERIC 16 /* leave room for NETLINK_DM (DM Events) */ #define NETLINK_SCSITRANSPORT 18 /* SCSI Transports */ #define NETLINK_ECRYPTFS 19 #define NETLINK_RDMA 20 #define NETLINK_CRYPTO 21 /* Crypto layer */ #define NETLINK_SMC 22 /* SMC monitoring */ #define NETLINK_INET_DIAG NETLINK_SOCK_DIAG #define MAX_LINKS 32 struct sockaddr_nl { __kernel_sa_family_t nl_family; /* AF_NETLINK */ unsigned short nl_pad; /* zero */ __u32 nl_pid; /* port ID */ __u32 nl_groups; /* multicast groups mask */ }; struct nlmsghdr { __u32 nlmsg_len; /* Length of message including header */ __u16 nlmsg_type; /* Message content */ __u16 nlmsg_flags; /* Additional flags */ __u32 nlmsg_seq; /* Sequence number */ __u32 nlmsg_pid; /* Sending process port ID */ }; /* Flags values */ #define NLM_F_REQUEST 0x01 /* It is request message. */ #define NLM_F_MULTI 0x02 /* Multipart message, terminated by NLMSG_DONE */ #define NLM_F_ACK 0x04 /* Reply with ack, with zero or error code */ #define NLM_F_ECHO 0x08 /* Echo this request */ #define NLM_F_DUMP_INTR 0x10 /* Dump was inconsistent due to sequence change */ #define NLM_F_DUMP_FILTERED 0x20 /* Dump was filtered as requested */ /* Modifiers to GET request */ #define NLM_F_ROOT 0x100 /* specify tree root */ #define NLM_F_MATCH 0x200 /* return all matching */ #define NLM_F_ATOMIC 0x400 /* atomic GET */ #define NLM_F_DUMP (NLM_F_ROOT|NLM_F_MATCH) /* Modifiers to NEW request */ #define NLM_F_REPLACE 0x100 /* Override existing */ #define NLM_F_EXCL 0x200 /* Do not touch, if it exists */ #define NLM_F_CREATE 0x400 /* Create, if it does not exist */ #define NLM_F_APPEND 0x800 /* Add to end of list */ /* Modifiers to DELETE request */ #define NLM_F_NONREC 0x100 /* Do not delete recursively */ /* Flags for ACK message */ #define NLM_F_CAPPED 0x100 /* request was capped */ #define NLM_F_ACK_TLVS 0x200 /* extended ACK TVLs were included */ /* 4.4BSD ADD NLM_F_CREATE|NLM_F_EXCL 4.4BSD CHANGE NLM_F_REPLACE True CHANGE NLM_F_CREATE|NLM_F_REPLACE Append NLM_F_CREATE Check NLM_F_EXCL */ #define NLMSG_ALIGNTO 4U #define NLMSG_ALIGN(len) ( ((len)+NLMSG_ALIGNTO-1) & ~(NLMSG_ALIGNTO-1) ) #define NLMSG_HDRLEN ((int) NLMSG_ALIGN(sizeof(struct nlmsghdr))) #define NLMSG_LENGTH(len) ((len) + NLMSG_HDRLEN) #define NLMSG_SPACE(len) NLMSG_ALIGN(NLMSG_LENGTH(len)) #define NLMSG_DATA(nlh) ((void*)(((char*)nlh) + NLMSG_LENGTH(0))) #define NLMSG_NEXT(nlh,len) ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \ (struct nlmsghdr*)(((char*)(nlh)) + NLMSG_ALIGN((nlh)->nlmsg_len))) #define NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \ (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \ (nlh)->nlmsg_len <= (len)) #define NLMSG_PAYLOAD(nlh,len) ((nlh)->nlmsg_len - NLMSG_SPACE((len))) #define NLMSG_NOOP 0x1 /* Nothing. */ #define NLMSG_ERROR 0x2 /* Error */ #define NLMSG_DONE 0x3 /* End of a dump */ #define NLMSG_OVERRUN 0x4 /* Data lost */ #define NLMSG_MIN_TYPE 0x10 /* < 0x10: reserved control messages */ struct nlmsgerr { int error; struct nlmsghdr msg; /* * followed by the message contents unless NETLINK_CAP_ACK was set * or the ACK indicates success (error == 0) * message length is aligned with NLMSG_ALIGN() */ /* * followed by TLVs defined in enum nlmsgerr_attrs * if NETLINK_EXT_ACK was set */ }; /** * enum nlmsgerr_attrs - nlmsgerr attributes * @NLMSGERR_ATTR_UNUSED: unused * @NLMSGERR_ATTR_MSG: error message string (string) * @NLMSGERR_ATTR_OFFS: offset of the invalid attribute in the original * message, counting from the beginning of the header (u32) * @NLMSGERR_ATTR_COOKIE: arbitrary subsystem specific cookie to * be used - in the success case - to identify a created * object or operation or similar (binary) * @__NLMSGERR_ATTR_MAX: number of attributes * @NLMSGERR_ATTR_MAX: highest attribute number */ enum nlmsgerr_attrs { NLMSGERR_ATTR_UNUSED, NLMSGERR_ATTR_MSG, NLMSGERR_ATTR_OFFS, NLMSGERR_ATTR_COOKIE, __NLMSGERR_ATTR_MAX, NLMSGERR_ATTR_MAX = __NLMSGERR_ATTR_MAX - 1 }; #define NETLINK_ADD_MEMBERSHIP 1 #define NETLINK_DROP_MEMBERSHIP 2 #define NETLINK_PKTINFO 3 #define NETLINK_BROADCAST_ERROR 4 #define NETLINK_NO_ENOBUFS 5 #define NETLINK_RX_RING 6 #define NETLINK_TX_RING 7 #define NETLINK_LISTEN_ALL_NSID 8 #define NETLINK_LIST_MEMBERSHIPS 9 #define NETLINK_CAP_ACK 10 #define NETLINK_EXT_ACK 11 #define NETLINK_GET_STRICT_CHK 12 struct nl_pktinfo { __u32 group; }; struct nl_mmap_req { unsigned int nm_block_size; unsigned int nm_block_nr; unsigned int nm_frame_size; unsigned int nm_frame_nr; }; struct nl_mmap_hdr { unsigned int nm_status; unsigned int nm_len; __u32 nm_group; /* credentials */ __u32 nm_pid; __u32 nm_uid; __u32 nm_gid; }; enum nl_mmap_status { NL_MMAP_STATUS_UNUSED, NL_MMAP_STATUS_RESERVED, NL_MMAP_STATUS_VALID, NL_MMAP_STATUS_COPY, NL_MMAP_STATUS_SKIP, }; #define NL_MMAP_MSG_ALIGNMENT NLMSG_ALIGNTO #define NL_MMAP_MSG_ALIGN(sz) __ALIGN_KERNEL(sz, NL_MMAP_MSG_ALIGNMENT) #define NL_MMAP_HDRLEN NL_MMAP_MSG_ALIGN(sizeof(struct nl_mmap_hdr)) #define NET_MAJOR 36 /* Major 36 is reserved for networking */ enum { NETLINK_UNCONNECTED = 0, NETLINK_CONNECTED, }; /* * <------- NLA_HDRLEN ------> <-- NLA_ALIGN(payload)--> * +---------------------+- - -+- - - - - - - - - -+- - -+ * | Header | Pad | Payload | Pad | * | (struct nlattr) | ing | | ing | * +---------------------+- - -+- - - - - - - - - -+- - -+ * <-------------- nlattr->nla_len --------------> */ struct nlattr { __u16 nla_len; __u16 nla_type; }; /* * nla_type (16 bits) * +---+---+-------------------------------+ * | N | O | Attribute Type | * +---+---+-------------------------------+ * N := Carries nested attributes * O := Payload stored in network byte order * * Note: The N and O flag are mutually exclusive. */ #define NLA_F_NESTED (1 << 15) #define NLA_F_NET_BYTEORDER (1 << 14) #define NLA_TYPE_MASK ~(NLA_F_NESTED | NLA_F_NET_BYTEORDER) #define NLA_ALIGNTO 4 #define NLA_ALIGN(len) (((len) + NLA_ALIGNTO - 1) & ~(NLA_ALIGNTO - 1)) #define NLA_HDRLEN ((int) NLA_ALIGN(sizeof(struct nlattr))) /* Generic 32 bitflags attribute content sent to the kernel. * * The value is a bitmap that defines the values being set * The selector is a bitmask that defines which value is legit * * Examples: * value = 0x0, and selector = 0x1 * implies we are selecting bit 1 and we want to set its value to 0. * * value = 0x2, and selector = 0x2 * implies we are selecting bit 2 and we want to set its value to 1. * */ struct nla_bitfield32 { __u32 value; __u32 selector; }; /* * policy descriptions - it's specific to each family how this is used * Normally, it should be retrieved via a dump inside another attribute * specifying where it applies. */ /** * enum netlink_attribute_type - type of an attribute * @NL_ATTR_TYPE_INVALID: unused * @NL_ATTR_TYPE_FLAG: flag attribute (present/not present) * @NL_ATTR_TYPE_U8: 8-bit unsigned attribute * @NL_ATTR_TYPE_U16: 16-bit unsigned attribute * @NL_ATTR_TYPE_U32: 32-bit unsigned attribute * @NL_ATTR_TYPE_U64: 64-bit unsigned attribute * @NL_ATTR_TYPE_S8: 8-bit signed attribute * @NL_ATTR_TYPE_S16: 16-bit signed attribute * @NL_ATTR_TYPE_S32: 32-bit signed attribute * @NL_ATTR_TYPE_S64: 64-bit signed attribute * @NL_ATTR_TYPE_BINARY: binary data, min/max length may be specified * @NL_ATTR_TYPE_STRING: string, min/max length may be specified * @NL_ATTR_TYPE_NUL_STRING: NUL-terminated string, * min/max length may be specified * @NL_ATTR_TYPE_NESTED: nested, i.e. the content of this attribute * consists of sub-attributes. The nested policy and maxtype * inside may be specified. * @NL_ATTR_TYPE_NESTED_ARRAY: nested array, i.e. the content of this * attribute contains sub-attributes whose type is irrelevant * (just used to separate the array entries) and each such array * entry has attributes again, the policy for those inner ones * and the corresponding maxtype may be specified. * @NL_ATTR_TYPE_BITFIELD32: &struct nla_bitfield32 attribute */ enum netlink_attribute_type { NL_ATTR_TYPE_INVALID, NL_ATTR_TYPE_FLAG, NL_ATTR_TYPE_U8, NL_ATTR_TYPE_U16, NL_ATTR_TYPE_U32, NL_ATTR_TYPE_U64, NL_ATTR_TYPE_S8, NL_ATTR_TYPE_S16, NL_ATTR_TYPE_S32, NL_ATTR_TYPE_S64, NL_ATTR_TYPE_BINARY, NL_ATTR_TYPE_STRING, NL_ATTR_TYPE_NUL_STRING, NL_ATTR_TYPE_NESTED, NL_ATTR_TYPE_NESTED_ARRAY, NL_ATTR_TYPE_BITFIELD32, }; /** * enum netlink_policy_type_attr - policy type attributes * @NL_POLICY_TYPE_ATTR_UNSPEC: unused * @NL_POLICY_TYPE_ATTR_TYPE: type of the attribute, * &enum netlink_attribute_type (U32) * @NL_POLICY_TYPE_ATTR_MIN_VALUE_S: minimum value for signed * integers (S64) * @NL_POLICY_TYPE_ATTR_MAX_VALUE_S: maximum value for signed * integers (S64) * @NL_POLICY_TYPE_ATTR_MIN_VALUE_U: minimum value for unsigned * integers (U64) * @NL_POLICY_TYPE_ATTR_MAX_VALUE_U: maximum value for unsigned * integers (U64) * @NL_POLICY_TYPE_ATTR_MIN_LENGTH: minimum length for binary * attributes, no minimum if not given (U32) * @NL_POLICY_TYPE_ATTR_MAX_LENGTH: maximum length for binary * attributes, no maximum if not given (U32) * @NL_POLICY_TYPE_ATTR_POLICY_IDX: sub policy for nested and * nested array types (U32) * @NL_POLICY_TYPE_ATTR_POLICY_MAXTYPE: maximum sub policy * attribute for nested and nested array types, this can * in theory be < the size of the policy pointed to by * the index, if limited inside the nesting (U32) * @NL_POLICY_TYPE_ATTR_BITFIELD32_MASK: valid mask for the * bitfield32 type (U32) * @NL_POLICY_TYPE_ATTR_MASK: mask of valid bits for unsigned integers (U64) * @NL_POLICY_TYPE_ATTR_PAD: pad attribute for 64-bit alignment */ enum netlink_policy_type_attr { NL_POLICY_TYPE_ATTR_UNSPEC, NL_POLICY_TYPE_ATTR_TYPE, NL_POLICY_TYPE_ATTR_MIN_VALUE_S, NL_POLICY_TYPE_ATTR_MAX_VALUE_S, NL_POLICY_TYPE_ATTR_MIN_VALUE_U, NL_POLICY_TYPE_ATTR_MAX_VALUE_U, NL_POLICY_TYPE_ATTR_MIN_LENGTH, NL_POLICY_TYPE_ATTR_MAX_LENGTH, NL_POLICY_TYPE_ATTR_POLICY_IDX, NL_POLICY_TYPE_ATTR_POLICY_MAXTYPE, NL_POLICY_TYPE_ATTR_BITFIELD32_MASK, NL_POLICY_TYPE_ATTR_PAD, NL_POLICY_TYPE_ATTR_MASK, /* keep last */ __NL_POLICY_TYPE_ATTR_MAX, NL_POLICY_TYPE_ATTR_MAX = __NL_POLICY_TYPE_ATTR_MAX - 1 }; #endif /* __LINUX_NETLINK_H */ linux/dvb/frontend.h000064400000071074151027430560010462 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * frontend.h * * Copyright (C) 2000 Marcus Metzler * Ralph Metzler * Holger Waechtler * Andre Draszik * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBFRONTEND_H_ #define _DVBFRONTEND_H_ #include /** * enum fe_caps - Frontend capabilities * * @FE_IS_STUPID: There's something wrong at the * frontend, and it can't report its * capabilities. * @FE_CAN_INVERSION_AUTO: Can auto-detect frequency spectral * band inversion * @FE_CAN_FEC_1_2: Supports FEC 1/2 * @FE_CAN_FEC_2_3: Supports FEC 2/3 * @FE_CAN_FEC_3_4: Supports FEC 3/4 * @FE_CAN_FEC_4_5: Supports FEC 4/5 * @FE_CAN_FEC_5_6: Supports FEC 5/6 * @FE_CAN_FEC_6_7: Supports FEC 6/7 * @FE_CAN_FEC_7_8: Supports FEC 7/8 * @FE_CAN_FEC_8_9: Supports FEC 8/9 * @FE_CAN_FEC_AUTO: Can auto-detect FEC * @FE_CAN_QPSK: Supports QPSK modulation * @FE_CAN_QAM_16: Supports 16-QAM modulation * @FE_CAN_QAM_32: Supports 32-QAM modulation * @FE_CAN_QAM_64: Supports 64-QAM modulation * @FE_CAN_QAM_128: Supports 128-QAM modulation * @FE_CAN_QAM_256: Supports 256-QAM modulation * @FE_CAN_QAM_AUTO: Can auto-detect QAM modulation * @FE_CAN_TRANSMISSION_MODE_AUTO: Can auto-detect transmission mode * @FE_CAN_BANDWIDTH_AUTO: Can auto-detect bandwidth * @FE_CAN_GUARD_INTERVAL_AUTO: Can auto-detect guard interval * @FE_CAN_HIERARCHY_AUTO: Can auto-detect hierarchy * @FE_CAN_8VSB: Supports 8-VSB modulation * @FE_CAN_16VSB: Supporta 16-VSB modulation * @FE_HAS_EXTENDED_CAPS: Unused * @FE_CAN_MULTISTREAM: Supports multistream filtering * @FE_CAN_TURBO_FEC: Supports "turbo FEC" modulation * @FE_CAN_2G_MODULATION: Supports "2nd generation" modulation, * e. g. DVB-S2, DVB-T2, DVB-C2 * @FE_NEEDS_BENDING: Unused * @FE_CAN_RECOVER: Can recover from a cable unplug * automatically * @FE_CAN_MUTE_TS: Can stop spurious TS data output */ enum fe_caps { FE_IS_STUPID = 0, FE_CAN_INVERSION_AUTO = 0x1, FE_CAN_FEC_1_2 = 0x2, FE_CAN_FEC_2_3 = 0x4, FE_CAN_FEC_3_4 = 0x8, FE_CAN_FEC_4_5 = 0x10, FE_CAN_FEC_5_6 = 0x20, FE_CAN_FEC_6_7 = 0x40, FE_CAN_FEC_7_8 = 0x80, FE_CAN_FEC_8_9 = 0x100, FE_CAN_FEC_AUTO = 0x200, FE_CAN_QPSK = 0x400, FE_CAN_QAM_16 = 0x800, FE_CAN_QAM_32 = 0x1000, FE_CAN_QAM_64 = 0x2000, FE_CAN_QAM_128 = 0x4000, FE_CAN_QAM_256 = 0x8000, FE_CAN_QAM_AUTO = 0x10000, FE_CAN_TRANSMISSION_MODE_AUTO = 0x20000, FE_CAN_BANDWIDTH_AUTO = 0x40000, FE_CAN_GUARD_INTERVAL_AUTO = 0x80000, FE_CAN_HIERARCHY_AUTO = 0x100000, FE_CAN_8VSB = 0x200000, FE_CAN_16VSB = 0x400000, FE_HAS_EXTENDED_CAPS = 0x800000, FE_CAN_MULTISTREAM = 0x4000000, FE_CAN_TURBO_FEC = 0x8000000, FE_CAN_2G_MODULATION = 0x10000000, FE_NEEDS_BENDING = 0x20000000, FE_CAN_RECOVER = 0x40000000, FE_CAN_MUTE_TS = 0x80000000 }; /* * DEPRECATED: Should be kept just due to backward compatibility. */ enum fe_type { FE_QPSK, FE_QAM, FE_OFDM, FE_ATSC }; /** * struct dvb_frontend_info - Frontend properties and capabilities * * @name: Name of the frontend * @type: **DEPRECATED**. * Should not be used on modern programs, * as a frontend may have more than one type. * In order to get the support types of a given * frontend, use :c:type:`DTV_ENUM_DELSYS` * instead. * @frequency_min: Minimal frequency supported by the frontend. * @frequency_max: Minimal frequency supported by the frontend. * @frequency_stepsize: All frequencies are multiple of this value. * @frequency_tolerance: Frequency tolerance. * @symbol_rate_min: Minimal symbol rate, in bauds * (for Cable/Satellite systems). * @symbol_rate_max: Maximal symbol rate, in bauds * (for Cable/Satellite systems). * @symbol_rate_tolerance: Maximal symbol rate tolerance, in ppm * (for Cable/Satellite systems). * @notifier_delay: **DEPRECATED**. Not used by any driver. * @caps: Capabilities supported by the frontend, * as specified in &enum fe_caps. * * .. note: * * #. The frequencies are specified in Hz for Terrestrial and Cable * systems. * #. The frequencies are specified in kHz for Satellite systems. */ struct dvb_frontend_info { char name[128]; enum fe_type type; /* DEPRECATED. Use DTV_ENUM_DELSYS instead */ __u32 frequency_min; __u32 frequency_max; __u32 frequency_stepsize; __u32 frequency_tolerance; __u32 symbol_rate_min; __u32 symbol_rate_max; __u32 symbol_rate_tolerance; __u32 notifier_delay; /* DEPRECATED */ enum fe_caps caps; }; /** * struct dvb_diseqc_master_cmd - DiSEqC master command * * @msg: * DiSEqC message to be sent. It contains a 3 bytes header with: * framing + address + command, and an optional argument * of up to 3 bytes of data. * @msg_len: * Length of the DiSEqC message. Valid values are 3 to 6. * * Check out the DiSEqC bus spec available on http://www.eutelsat.org/ for * the possible messages that can be used. */ struct dvb_diseqc_master_cmd { __u8 msg[6]; __u8 msg_len; }; /** * struct dvb_diseqc_slave_reply - DiSEqC received data * * @msg: * DiSEqC message buffer to store a message received via DiSEqC. * It contains one byte header with: framing and * an optional argument of up to 3 bytes of data. * @msg_len: * Length of the DiSEqC message. Valid values are 0 to 4, * where 0 means no message. * @timeout: * Return from ioctl after timeout ms with errorcode when * no message was received. * * Check out the DiSEqC bus spec available on http://www.eutelsat.org/ for * the possible messages that can be used. */ struct dvb_diseqc_slave_reply { __u8 msg[4]; __u8 msg_len; int timeout; }; /** * enum fe_sec_voltage - DC Voltage used to feed the LNBf * * @SEC_VOLTAGE_13: Output 13V to the LNBf * @SEC_VOLTAGE_18: Output 18V to the LNBf * @SEC_VOLTAGE_OFF: Don't feed the LNBf with a DC voltage */ enum fe_sec_voltage { SEC_VOLTAGE_13, SEC_VOLTAGE_18, SEC_VOLTAGE_OFF }; /** * enum fe_sec_tone_mode - Type of tone to be send to the LNBf. * @SEC_TONE_ON: Sends a 22kHz tone burst to the antenna. * @SEC_TONE_OFF: Don't send a 22kHz tone to the antenna (except * if the ``FE_DISEQC_*`` ioctls are called). */ enum fe_sec_tone_mode { SEC_TONE_ON, SEC_TONE_OFF }; /** * enum fe_sec_mini_cmd - Type of mini burst to be sent * * @SEC_MINI_A: Sends a mini-DiSEqC 22kHz '0' Tone Burst to select * satellite-A * @SEC_MINI_B: Sends a mini-DiSEqC 22kHz '1' Data Burst to select * satellite-B */ enum fe_sec_mini_cmd { SEC_MINI_A, SEC_MINI_B }; /** * enum fe_status - Enumerates the possible frontend status. * @FE_NONE: The frontend doesn't have any kind of lock. * That's the initial frontend status * @FE_HAS_SIGNAL: Has found something above the noise level. * @FE_HAS_CARRIER: Has found a signal. * @FE_HAS_VITERBI: FEC inner coding (Viterbi, LDPC or other inner code). * is stable. * @FE_HAS_SYNC: Synchronization bytes was found. * @FE_HAS_LOCK: Digital TV were locked and everything is working. * @FE_TIMEDOUT: Fo lock within the last about 2 seconds. * @FE_REINIT: Frontend was reinitialized, application is recommended * to reset DiSEqC, tone and parameters. */ enum fe_status { FE_NONE = 0x00, FE_HAS_SIGNAL = 0x01, FE_HAS_CARRIER = 0x02, FE_HAS_VITERBI = 0x04, FE_HAS_SYNC = 0x08, FE_HAS_LOCK = 0x10, FE_TIMEDOUT = 0x20, FE_REINIT = 0x40, }; /** * enum fe_spectral_inversion - Type of inversion band * * @INVERSION_OFF: Don't do spectral band inversion. * @INVERSION_ON: Do spectral band inversion. * @INVERSION_AUTO: Autodetect spectral band inversion. * * This parameter indicates if spectral inversion should be presumed or * not. In the automatic setting (``INVERSION_AUTO``) the hardware will try * to figure out the correct setting by itself. If the hardware doesn't * support, the %dvb_frontend will try to lock at the carrier first with * inversion off. If it fails, it will try to enable inversion. */ enum fe_spectral_inversion { INVERSION_OFF, INVERSION_ON, INVERSION_AUTO }; /** * enum fe_code_rate - Type of Forward Error Correction (FEC) * * * @FEC_NONE: No Forward Error Correction Code * @FEC_1_2: Forward Error Correction Code 1/2 * @FEC_2_3: Forward Error Correction Code 2/3 * @FEC_3_4: Forward Error Correction Code 3/4 * @FEC_4_5: Forward Error Correction Code 4/5 * @FEC_5_6: Forward Error Correction Code 5/6 * @FEC_6_7: Forward Error Correction Code 6/7 * @FEC_7_8: Forward Error Correction Code 7/8 * @FEC_8_9: Forward Error Correction Code 8/9 * @FEC_AUTO: Autodetect Error Correction Code * @FEC_3_5: Forward Error Correction Code 3/5 * @FEC_9_10: Forward Error Correction Code 9/10 * @FEC_2_5: Forward Error Correction Code 2/5 * * Please note that not all FEC types are supported by a given standard. */ enum fe_code_rate { FEC_NONE = 0, FEC_1_2, FEC_2_3, FEC_3_4, FEC_4_5, FEC_5_6, FEC_6_7, FEC_7_8, FEC_8_9, FEC_AUTO, FEC_3_5, FEC_9_10, FEC_2_5, }; /** * enum fe_modulation - Type of modulation/constellation * @QPSK: QPSK modulation * @QAM_16: 16-QAM modulation * @QAM_32: 32-QAM modulation * @QAM_64: 64-QAM modulation * @QAM_128: 128-QAM modulation * @QAM_256: 256-QAM modulation * @QAM_AUTO: Autodetect QAM modulation * @VSB_8: 8-VSB modulation * @VSB_16: 16-VSB modulation * @PSK_8: 8-PSK modulation * @APSK_16: 16-APSK modulation * @APSK_32: 32-APSK modulation * @DQPSK: DQPSK modulation * @QAM_4_NR: 4-QAM-NR modulation * * Please note that not all modulations are supported by a given standard. * */ enum fe_modulation { QPSK, QAM_16, QAM_32, QAM_64, QAM_128, QAM_256, QAM_AUTO, VSB_8, VSB_16, PSK_8, APSK_16, APSK_32, DQPSK, QAM_4_NR, }; /** * enum fe_transmit_mode - Transmission mode * * @TRANSMISSION_MODE_AUTO: * Autodetect transmission mode. The hardware will try to find the * correct FFT-size (if capable) to fill in the missing parameters. * @TRANSMISSION_MODE_1K: * Transmission mode 1K * @TRANSMISSION_MODE_2K: * Transmission mode 2K * @TRANSMISSION_MODE_8K: * Transmission mode 8K * @TRANSMISSION_MODE_4K: * Transmission mode 4K * @TRANSMISSION_MODE_16K: * Transmission mode 16K * @TRANSMISSION_MODE_32K: * Transmission mode 32K * @TRANSMISSION_MODE_C1: * Single Carrier (C=1) transmission mode (DTMB only) * @TRANSMISSION_MODE_C3780: * Multi Carrier (C=3780) transmission mode (DTMB only) * * Please note that not all transmission modes are supported by a given * standard. */ enum fe_transmit_mode { TRANSMISSION_MODE_2K, TRANSMISSION_MODE_8K, TRANSMISSION_MODE_AUTO, TRANSMISSION_MODE_4K, TRANSMISSION_MODE_1K, TRANSMISSION_MODE_16K, TRANSMISSION_MODE_32K, TRANSMISSION_MODE_C1, TRANSMISSION_MODE_C3780, }; /** * enum fe_guard_interval - Guard interval * * @GUARD_INTERVAL_AUTO: Autodetect the guard interval * @GUARD_INTERVAL_1_128: Guard interval 1/128 * @GUARD_INTERVAL_1_32: Guard interval 1/32 * @GUARD_INTERVAL_1_16: Guard interval 1/16 * @GUARD_INTERVAL_1_8: Guard interval 1/8 * @GUARD_INTERVAL_1_4: Guard interval 1/4 * @GUARD_INTERVAL_19_128: Guard interval 19/128 * @GUARD_INTERVAL_19_256: Guard interval 19/256 * @GUARD_INTERVAL_PN420: PN length 420 (1/4) * @GUARD_INTERVAL_PN595: PN length 595 (1/6) * @GUARD_INTERVAL_PN945: PN length 945 (1/9) * * Please note that not all guard intervals are supported by a given standard. */ enum fe_guard_interval { GUARD_INTERVAL_1_32, GUARD_INTERVAL_1_16, GUARD_INTERVAL_1_8, GUARD_INTERVAL_1_4, GUARD_INTERVAL_AUTO, GUARD_INTERVAL_1_128, GUARD_INTERVAL_19_128, GUARD_INTERVAL_19_256, GUARD_INTERVAL_PN420, GUARD_INTERVAL_PN595, GUARD_INTERVAL_PN945, }; /** * enum fe_hierarchy - Hierarchy * @HIERARCHY_NONE: No hierarchy * @HIERARCHY_AUTO: Autodetect hierarchy (if supported) * @HIERARCHY_1: Hierarchy 1 * @HIERARCHY_2: Hierarchy 2 * @HIERARCHY_4: Hierarchy 4 * * Please note that not all hierarchy types are supported by a given standard. */ enum fe_hierarchy { HIERARCHY_NONE, HIERARCHY_1, HIERARCHY_2, HIERARCHY_4, HIERARCHY_AUTO }; /** * enum fe_interleaving - Interleaving * @INTERLEAVING_NONE: No interleaving. * @INTERLEAVING_AUTO: Auto-detect interleaving. * @INTERLEAVING_240: Interleaving of 240 symbols. * @INTERLEAVING_720: Interleaving of 720 symbols. * * Please note that, currently, only DTMB uses it. */ enum fe_interleaving { INTERLEAVING_NONE, INTERLEAVING_AUTO, INTERLEAVING_240, INTERLEAVING_720, }; /* DVBv5 property Commands */ #define DTV_UNDEFINED 0 #define DTV_TUNE 1 #define DTV_CLEAR 2 #define DTV_FREQUENCY 3 #define DTV_MODULATION 4 #define DTV_BANDWIDTH_HZ 5 #define DTV_INVERSION 6 #define DTV_DISEQC_MASTER 7 #define DTV_SYMBOL_RATE 8 #define DTV_INNER_FEC 9 #define DTV_VOLTAGE 10 #define DTV_TONE 11 #define DTV_PILOT 12 #define DTV_ROLLOFF 13 #define DTV_DISEQC_SLAVE_REPLY 14 /* Basic enumeration set for querying unlimited capabilities */ #define DTV_FE_CAPABILITY_COUNT 15 #define DTV_FE_CAPABILITY 16 #define DTV_DELIVERY_SYSTEM 17 /* ISDB-T and ISDB-Tsb */ #define DTV_ISDBT_PARTIAL_RECEPTION 18 #define DTV_ISDBT_SOUND_BROADCASTING 19 #define DTV_ISDBT_SB_SUBCHANNEL_ID 20 #define DTV_ISDBT_SB_SEGMENT_IDX 21 #define DTV_ISDBT_SB_SEGMENT_COUNT 22 #define DTV_ISDBT_LAYERA_FEC 23 #define DTV_ISDBT_LAYERA_MODULATION 24 #define DTV_ISDBT_LAYERA_SEGMENT_COUNT 25 #define DTV_ISDBT_LAYERA_TIME_INTERLEAVING 26 #define DTV_ISDBT_LAYERB_FEC 27 #define DTV_ISDBT_LAYERB_MODULATION 28 #define DTV_ISDBT_LAYERB_SEGMENT_COUNT 29 #define DTV_ISDBT_LAYERB_TIME_INTERLEAVING 30 #define DTV_ISDBT_LAYERC_FEC 31 #define DTV_ISDBT_LAYERC_MODULATION 32 #define DTV_ISDBT_LAYERC_SEGMENT_COUNT 33 #define DTV_ISDBT_LAYERC_TIME_INTERLEAVING 34 #define DTV_API_VERSION 35 #define DTV_CODE_RATE_HP 36 #define DTV_CODE_RATE_LP 37 #define DTV_GUARD_INTERVAL 38 #define DTV_TRANSMISSION_MODE 39 #define DTV_HIERARCHY 40 #define DTV_ISDBT_LAYER_ENABLED 41 #define DTV_STREAM_ID 42 #define DTV_ISDBS_TS_ID_LEGACY DTV_STREAM_ID #define DTV_DVBT2_PLP_ID_LEGACY 43 #define DTV_ENUM_DELSYS 44 /* ATSC-MH */ #define DTV_ATSCMH_FIC_VER 45 #define DTV_ATSCMH_PARADE_ID 46 #define DTV_ATSCMH_NOG 47 #define DTV_ATSCMH_TNOG 48 #define DTV_ATSCMH_SGN 49 #define DTV_ATSCMH_PRC 50 #define DTV_ATSCMH_RS_FRAME_MODE 51 #define DTV_ATSCMH_RS_FRAME_ENSEMBLE 52 #define DTV_ATSCMH_RS_CODE_MODE_PRI 53 #define DTV_ATSCMH_RS_CODE_MODE_SEC 54 #define DTV_ATSCMH_SCCC_BLOCK_MODE 55 #define DTV_ATSCMH_SCCC_CODE_MODE_A 56 #define DTV_ATSCMH_SCCC_CODE_MODE_B 57 #define DTV_ATSCMH_SCCC_CODE_MODE_C 58 #define DTV_ATSCMH_SCCC_CODE_MODE_D 59 #define DTV_INTERLEAVING 60 #define DTV_LNA 61 /* Quality parameters */ #define DTV_STAT_SIGNAL_STRENGTH 62 #define DTV_STAT_CNR 63 #define DTV_STAT_PRE_ERROR_BIT_COUNT 64 #define DTV_STAT_PRE_TOTAL_BIT_COUNT 65 #define DTV_STAT_POST_ERROR_BIT_COUNT 66 #define DTV_STAT_POST_TOTAL_BIT_COUNT 67 #define DTV_STAT_ERROR_BLOCK_COUNT 68 #define DTV_STAT_TOTAL_BLOCK_COUNT 69 /* Physical layer scrambling */ #define DTV_SCRAMBLING_SEQUENCE_INDEX 70 #define DTV_MAX_COMMAND DTV_SCRAMBLING_SEQUENCE_INDEX /** * enum fe_pilot - Type of pilot tone * * @PILOT_ON: Pilot tones enabled * @PILOT_OFF: Pilot tones disabled * @PILOT_AUTO: Autodetect pilot tones */ enum fe_pilot { PILOT_ON, PILOT_OFF, PILOT_AUTO, }; /** * enum fe_rolloff - Rolloff factor * @ROLLOFF_35: Roloff factor: α=35% * @ROLLOFF_20: Roloff factor: α=20% * @ROLLOFF_25: Roloff factor: α=25% * @ROLLOFF_AUTO: Auto-detect the roloff factor. * * .. note: * * Roloff factor of 35% is implied on DVB-S. On DVB-S2, it is default. */ enum fe_rolloff { ROLLOFF_35, ROLLOFF_20, ROLLOFF_25, ROLLOFF_AUTO, }; /** * enum fe_delivery_system - Type of the delivery system * * @SYS_UNDEFINED: * Undefined standard. Generally, indicates an error * @SYS_DVBC_ANNEX_A: * Cable TV: DVB-C following ITU-T J.83 Annex A spec * @SYS_DVBC_ANNEX_B: * Cable TV: DVB-C following ITU-T J.83 Annex B spec (ClearQAM) * @SYS_DVBC_ANNEX_C: * Cable TV: DVB-C following ITU-T J.83 Annex C spec * @SYS_ISDBC: * Cable TV: ISDB-C (no drivers yet) * @SYS_DVBT: * Terrestrial TV: DVB-T * @SYS_DVBT2: * Terrestrial TV: DVB-T2 * @SYS_ISDBT: * Terrestrial TV: ISDB-T * @SYS_ATSC: * Terrestrial TV: ATSC * @SYS_ATSCMH: * Terrestrial TV (mobile): ATSC-M/H * @SYS_DTMB: * Terrestrial TV: DTMB * @SYS_DVBS: * Satellite TV: DVB-S * @SYS_DVBS2: * Satellite TV: DVB-S2 * @SYS_TURBO: * Satellite TV: DVB-S Turbo * @SYS_ISDBS: * Satellite TV: ISDB-S * @SYS_DAB: * Digital audio: DAB (not fully supported) * @SYS_DSS: * Satellite TV: DSS (not fully supported) * @SYS_CMMB: * Terrestrial TV (mobile): CMMB (not fully supported) * @SYS_DVBH: * Terrestrial TV (mobile): DVB-H (standard deprecated) */ enum fe_delivery_system { SYS_UNDEFINED, SYS_DVBC_ANNEX_A, SYS_DVBC_ANNEX_B, SYS_DVBT, SYS_DSS, SYS_DVBS, SYS_DVBS2, SYS_DVBH, SYS_ISDBT, SYS_ISDBS, SYS_ISDBC, SYS_ATSC, SYS_ATSCMH, SYS_DTMB, SYS_CMMB, SYS_DAB, SYS_DVBT2, SYS_TURBO, SYS_DVBC_ANNEX_C, }; /* backward compatibility definitions for delivery systems */ #define SYS_DVBC_ANNEX_AC SYS_DVBC_ANNEX_A #define SYS_DMBTH SYS_DTMB /* DMB-TH is legacy name, use DTMB */ /* ATSC-MH specific parameters */ /** * enum atscmh_sccc_block_mode - Type of Series Concatenated Convolutional * Code Block Mode. * * @ATSCMH_SCCC_BLK_SEP: * Separate SCCC: the SCCC outer code mode shall be set independently * for each Group Region (A, B, C, D) * @ATSCMH_SCCC_BLK_COMB: * Combined SCCC: all four Regions shall have the same SCCC outer * code mode. * @ATSCMH_SCCC_BLK_RES: * Reserved. Shouldn't be used. */ enum atscmh_sccc_block_mode { ATSCMH_SCCC_BLK_SEP = 0, ATSCMH_SCCC_BLK_COMB = 1, ATSCMH_SCCC_BLK_RES = 2, }; /** * enum atscmh_sccc_code_mode - Type of Series Concatenated Convolutional * Code Rate. * * @ATSCMH_SCCC_CODE_HLF: * The outer code rate of a SCCC Block is 1/2 rate. * @ATSCMH_SCCC_CODE_QTR: * The outer code rate of a SCCC Block is 1/4 rate. * @ATSCMH_SCCC_CODE_RES: * Reserved. Should not be used. */ enum atscmh_sccc_code_mode { ATSCMH_SCCC_CODE_HLF = 0, ATSCMH_SCCC_CODE_QTR = 1, ATSCMH_SCCC_CODE_RES = 2, }; /** * enum atscmh_rs_frame_ensemble - Reed Solomon(RS) frame ensemble. * * @ATSCMH_RSFRAME_ENS_PRI: Primary Ensemble. * @ATSCMH_RSFRAME_ENS_SEC: Secondary Ensemble. */ enum atscmh_rs_frame_ensemble { ATSCMH_RSFRAME_ENS_PRI = 0, ATSCMH_RSFRAME_ENS_SEC = 1, }; /** * enum atscmh_rs_frame_mode - Reed Solomon (RS) frame mode. * * @ATSCMH_RSFRAME_PRI_ONLY: * Single Frame: There is only a primary RS Frame for all Group * Regions. * @ATSCMH_RSFRAME_PRI_SEC: * Dual Frame: There are two separate RS Frames: Primary RS Frame for * Group Region A and B and Secondary RS Frame for Group Region C and * D. * @ATSCMH_RSFRAME_RES: * Reserved. Shouldn't be used. */ enum atscmh_rs_frame_mode { ATSCMH_RSFRAME_PRI_ONLY = 0, ATSCMH_RSFRAME_PRI_SEC = 1, ATSCMH_RSFRAME_RES = 2, }; /** * enum atscmh_rs_code_mode * @ATSCMH_RSCODE_211_187: Reed Solomon code (211,187). * @ATSCMH_RSCODE_223_187: Reed Solomon code (223,187). * @ATSCMH_RSCODE_235_187: Reed Solomon code (235,187). * @ATSCMH_RSCODE_RES: Reserved. Shouldn't be used. */ enum atscmh_rs_code_mode { ATSCMH_RSCODE_211_187 = 0, ATSCMH_RSCODE_223_187 = 1, ATSCMH_RSCODE_235_187 = 2, ATSCMH_RSCODE_RES = 3, }; #define NO_STREAM_ID_FILTER (~0U) #define LNA_AUTO (~0U) /** * enum fecap_scale_params - scale types for the quality parameters. * * @FE_SCALE_NOT_AVAILABLE: That QoS measure is not available. That * could indicate a temporary or a permanent * condition. * @FE_SCALE_DECIBEL: The scale is measured in 0.001 dB steps, typically * used on signal measures. * @FE_SCALE_RELATIVE: The scale is a relative percentual measure, * ranging from 0 (0%) to 0xffff (100%). * @FE_SCALE_COUNTER: The scale counts the occurrence of an event, like * bit error, block error, lapsed time. */ enum fecap_scale_params { FE_SCALE_NOT_AVAILABLE = 0, FE_SCALE_DECIBEL, FE_SCALE_RELATIVE, FE_SCALE_COUNTER }; /** * struct dtv_stats - Used for reading a DTV status property * * @scale: * Filled with enum fecap_scale_params - the scale in usage * for that parameter * * @svalue: * integer value of the measure, for %FE_SCALE_DECIBEL, * used for dB measures. The unit is 0.001 dB. * * @uvalue: * unsigned integer value of the measure, used when @scale is * either %FE_SCALE_RELATIVE or %FE_SCALE_COUNTER. * * For most delivery systems, this will return a single value for each * parameter. * * It should be noticed, however, that new OFDM delivery systems like * ISDB can use different modulation types for each group of carriers. * On such standards, up to 8 groups of statistics can be provided, one * for each carrier group (called "layer" on ISDB). * * In order to be consistent with other delivery systems, the first * value refers to the entire set of carriers ("global"). * * @scale should use the value %FE_SCALE_NOT_AVAILABLE when * the value for the entire group of carriers or from one specific layer * is not provided by the hardware. * * @len should be filled with the latest filled status + 1. * * In other words, for ISDB, those values should be filled like:: * * u.st.stat.svalue[0] = global statistics; * u.st.stat.scale[0] = FE_SCALE_DECIBEL; * u.st.stat.value[1] = layer A statistics; * u.st.stat.scale[1] = FE_SCALE_NOT_AVAILABLE (if not available); * u.st.stat.svalue[2] = layer B statistics; * u.st.stat.scale[2] = FE_SCALE_DECIBEL; * u.st.stat.svalue[3] = layer C statistics; * u.st.stat.scale[3] = FE_SCALE_DECIBEL; * u.st.len = 4; */ struct dtv_stats { __u8 scale; /* enum fecap_scale_params type */ union { __u64 uvalue; /* for counters and relative scales */ __s64 svalue; /* for 0.001 dB measures */ }; } __attribute__ ((packed)); #define MAX_DTV_STATS 4 /** * struct dtv_fe_stats - store Digital TV frontend statistics * * @len: length of the statistics - if zero, stats is disabled. * @stat: array with digital TV statistics. * * On most standards, @len can either be 0 or 1. However, for ISDB, each * layer is modulated in separate. So, each layer may have its own set * of statistics. If so, stat[0] carries on a global value for the property. * Indexes 1 to 3 means layer A to B. */ struct dtv_fe_stats { __u8 len; struct dtv_stats stat[MAX_DTV_STATS]; } __attribute__ ((packed)); /** * struct dtv_property - store one of frontend command and its value * * @cmd: Digital TV command. * @reserved: Not used. * @u: Union with the values for the command. * @u.data: A unsigned 32 bits integer with command value. * @u.buffer: Struct to store bigger properties. * Currently unused. * @u.buffer.data: an unsigned 32-bits array. * @u.buffer.len: number of elements of the buffer. * @u.buffer.reserved1: Reserved. * @u.buffer.reserved2: Reserved. * @u.st: a &struct dtv_fe_stats array of statistics. * @result: Currently unused. * */ struct dtv_property { __u32 cmd; __u32 reserved[3]; union { __u32 data; struct dtv_fe_stats st; struct { __u8 data[32]; __u32 len; __u32 reserved1[3]; void *reserved2; } buffer; } u; int result; } __attribute__ ((packed)); /* num of properties cannot exceed DTV_IOCTL_MAX_MSGS per ioctl */ #define DTV_IOCTL_MAX_MSGS 64 /** * struct dtv_properties - a set of command/value pairs. * * @num: amount of commands stored at the struct. * @props: a pointer to &struct dtv_property. */ struct dtv_properties { __u32 num; struct dtv_property *props; }; /* * When set, this flag will disable any zigzagging or other "normal" tuning * behavior. Additionally, there will be no automatic monitoring of the lock * status, and hence no frontend events will be generated. If a frontend device * is closed, this flag will be automatically turned off when the device is * reopened read-write. */ #define FE_TUNE_MODE_ONESHOT 0x01 /* Digital TV Frontend API calls */ #define FE_GET_INFO _IOR('o', 61, struct dvb_frontend_info) #define FE_DISEQC_RESET_OVERLOAD _IO('o', 62) #define FE_DISEQC_SEND_MASTER_CMD _IOW('o', 63, struct dvb_diseqc_master_cmd) #define FE_DISEQC_RECV_SLAVE_REPLY _IOR('o', 64, struct dvb_diseqc_slave_reply) #define FE_DISEQC_SEND_BURST _IO('o', 65) /* fe_sec_mini_cmd_t */ #define FE_SET_TONE _IO('o', 66) /* fe_sec_tone_mode_t */ #define FE_SET_VOLTAGE _IO('o', 67) /* fe_sec_voltage_t */ #define FE_ENABLE_HIGH_LNB_VOLTAGE _IO('o', 68) /* int */ #define FE_READ_STATUS _IOR('o', 69, fe_status_t) #define FE_READ_BER _IOR('o', 70, __u32) #define FE_READ_SIGNAL_STRENGTH _IOR('o', 71, __u16) #define FE_READ_SNR _IOR('o', 72, __u16) #define FE_READ_UNCORRECTED_BLOCKS _IOR('o', 73, __u32) #define FE_SET_FRONTEND_TUNE_MODE _IO('o', 81) /* unsigned int */ #define FE_GET_EVENT _IOR('o', 78, struct dvb_frontend_event) #define FE_DISHNETWORK_SEND_LEGACY_CMD _IO('o', 80) /* unsigned int */ #define FE_SET_PROPERTY _IOW('o', 82, struct dtv_properties) #define FE_GET_PROPERTY _IOR('o', 83, struct dtv_properties) /* * DEPRECATED: Everything below is deprecated in favor of DVBv5 API * * The DVBv3 only ioctls, structs and enums should not be used on * newer programs, as it doesn't support the second generation of * digital TV standards, nor supports newer delivery systems. * They also don't support modern frontends with usually support multiple * delivery systems. * * Drivers shouldn't use them. * * New applications should use DVBv5 delivery system instead */ /* */ enum fe_bandwidth { BANDWIDTH_8_MHZ, BANDWIDTH_7_MHZ, BANDWIDTH_6_MHZ, BANDWIDTH_AUTO, BANDWIDTH_5_MHZ, BANDWIDTH_10_MHZ, BANDWIDTH_1_712_MHZ, }; /* This is kept for legacy userspace support */ typedef enum fe_sec_voltage fe_sec_voltage_t; typedef enum fe_caps fe_caps_t; typedef enum fe_type fe_type_t; typedef enum fe_sec_tone_mode fe_sec_tone_mode_t; typedef enum fe_sec_mini_cmd fe_sec_mini_cmd_t; typedef enum fe_status fe_status_t; typedef enum fe_spectral_inversion fe_spectral_inversion_t; typedef enum fe_code_rate fe_code_rate_t; typedef enum fe_modulation fe_modulation_t; typedef enum fe_transmit_mode fe_transmit_mode_t; typedef enum fe_bandwidth fe_bandwidth_t; typedef enum fe_guard_interval fe_guard_interval_t; typedef enum fe_hierarchy fe_hierarchy_t; typedef enum fe_pilot fe_pilot_t; typedef enum fe_rolloff fe_rolloff_t; typedef enum fe_delivery_system fe_delivery_system_t; /* DVBv3 structs */ struct dvb_qpsk_parameters { __u32 symbol_rate; /* symbol rate in Symbols per second */ fe_code_rate_t fec_inner; /* forward error correction (see above) */ }; struct dvb_qam_parameters { __u32 symbol_rate; /* symbol rate in Symbols per second */ fe_code_rate_t fec_inner; /* forward error correction (see above) */ fe_modulation_t modulation; /* modulation type (see above) */ }; struct dvb_vsb_parameters { fe_modulation_t modulation; /* modulation type (see above) */ }; struct dvb_ofdm_parameters { fe_bandwidth_t bandwidth; fe_code_rate_t code_rate_HP; /* high priority stream code rate */ fe_code_rate_t code_rate_LP; /* low priority stream code rate */ fe_modulation_t constellation; /* modulation type (see above) */ fe_transmit_mode_t transmission_mode; fe_guard_interval_t guard_interval; fe_hierarchy_t hierarchy_information; }; struct dvb_frontend_parameters { __u32 frequency; /* (absolute) frequency in Hz for DVB-C/DVB-T/ATSC */ /* intermediate frequency in kHz for DVB-S */ fe_spectral_inversion_t inversion; union { struct dvb_qpsk_parameters qpsk; /* DVB-S */ struct dvb_qam_parameters qam; /* DVB-C */ struct dvb_ofdm_parameters ofdm; /* DVB-T */ struct dvb_vsb_parameters vsb; /* ATSC */ } u; }; struct dvb_frontend_event { fe_status_t status; struct dvb_frontend_parameters parameters; }; /* DVBv3 API calls */ #define FE_SET_FRONTEND _IOW('o', 76, struct dvb_frontend_parameters) #define FE_GET_FRONTEND _IOR('o', 77, struct dvb_frontend_parameters) #endif /*_DVBFRONTEND_H_*/ linux/dvb/version.h000064400000002072151027430560010320 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * version.h * * Copyright (C) 2000 Holger Waechtler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBVERSION_H_ #define _DVBVERSION_H_ #define DVB_API_VERSION 5 #define DVB_API_VERSION_MINOR 11 #endif /*_DVBVERSION_H_*/ linux/dvb/video.h000064400000021131151027430560007736 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * video.h * * Copyright (C) 2000 Marcus Metzler * & Ralph Metzler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBVIDEO_H_ #define _DVBVIDEO_H_ #include #include typedef enum { VIDEO_FORMAT_4_3, /* Select 4:3 format */ VIDEO_FORMAT_16_9, /* Select 16:9 format. */ VIDEO_FORMAT_221_1 /* 2.21:1 */ } video_format_t; typedef enum { VIDEO_SYSTEM_PAL, VIDEO_SYSTEM_NTSC, VIDEO_SYSTEM_PALN, VIDEO_SYSTEM_PALNc, VIDEO_SYSTEM_PALM, VIDEO_SYSTEM_NTSC60, VIDEO_SYSTEM_PAL60, VIDEO_SYSTEM_PALM60 } video_system_t; typedef enum { VIDEO_PAN_SCAN, /* use pan and scan format */ VIDEO_LETTER_BOX, /* use letterbox format */ VIDEO_CENTER_CUT_OUT /* use center cut out format */ } video_displayformat_t; typedef struct { int w; int h; video_format_t aspect_ratio; } video_size_t; typedef enum { VIDEO_SOURCE_DEMUX, /* Select the demux as the main source */ VIDEO_SOURCE_MEMORY /* If this source is selected, the stream comes from the user through the write system call */ } video_stream_source_t; typedef enum { VIDEO_STOPPED, /* Video is stopped */ VIDEO_PLAYING, /* Video is currently playing */ VIDEO_FREEZED /* Video is freezed */ } video_play_state_t; /* Decoder commands */ #define VIDEO_CMD_PLAY (0) #define VIDEO_CMD_STOP (1) #define VIDEO_CMD_FREEZE (2) #define VIDEO_CMD_CONTINUE (3) /* Flags for VIDEO_CMD_FREEZE */ #define VIDEO_CMD_FREEZE_TO_BLACK (1 << 0) /* Flags for VIDEO_CMD_STOP */ #define VIDEO_CMD_STOP_TO_BLACK (1 << 0) #define VIDEO_CMD_STOP_IMMEDIATELY (1 << 1) /* Play input formats: */ /* The decoder has no special format requirements */ #define VIDEO_PLAY_FMT_NONE (0) /* The decoder requires full GOPs */ #define VIDEO_PLAY_FMT_GOP (1) /* The structure must be zeroed before use by the application This ensures it can be extended safely in the future. */ struct video_command { __u32 cmd; __u32 flags; union { struct { __u64 pts; } stop; struct { /* 0 or 1000 specifies normal speed, 1 specifies forward single stepping, -1 specifies backward single stepping, >1: playback at speed/1000 of the normal speed, <-1: reverse playback at (-speed/1000) of the normal speed. */ __s32 speed; __u32 format; } play; struct { __u32 data[16]; } raw; }; }; /* FIELD_UNKNOWN can be used if the hardware does not know whether the Vsync is for an odd, even or progressive (i.e. non-interlaced) field. */ #define VIDEO_VSYNC_FIELD_UNKNOWN (0) #define VIDEO_VSYNC_FIELD_ODD (1) #define VIDEO_VSYNC_FIELD_EVEN (2) #define VIDEO_VSYNC_FIELD_PROGRESSIVE (3) struct video_event { __s32 type; #define VIDEO_EVENT_SIZE_CHANGED 1 #define VIDEO_EVENT_FRAME_RATE_CHANGED 2 #define VIDEO_EVENT_DECODER_STOPPED 3 #define VIDEO_EVENT_VSYNC 4 /* unused, make sure to use atomic time for y2038 if it ever gets used */ long timestamp; union { video_size_t size; unsigned int frame_rate; /* in frames per 1000sec */ unsigned char vsync_field; /* unknown/odd/even/progressive */ } u; }; struct video_status { int video_blank; /* blank video on freeze? */ video_play_state_t play_state; /* current state of playback */ video_stream_source_t stream_source; /* current source (demux/memory) */ video_format_t video_format; /* current aspect ratio of stream*/ video_displayformat_t display_format;/* selected cropping mode */ }; struct video_still_picture { char *iFrame; /* pointer to a single iframe in memory */ __s32 size; }; typedef struct video_highlight { int active; /* 1=show highlight, 0=hide highlight */ __u8 contrast1; /* 7- 4 Pattern pixel contrast */ /* 3- 0 Background pixel contrast */ __u8 contrast2; /* 7- 4 Emphasis pixel-2 contrast */ /* 3- 0 Emphasis pixel-1 contrast */ __u8 color1; /* 7- 4 Pattern pixel color */ /* 3- 0 Background pixel color */ __u8 color2; /* 7- 4 Emphasis pixel-2 color */ /* 3- 0 Emphasis pixel-1 color */ __u32 ypos; /* 23-22 auto action mode */ /* 21-12 start y */ /* 9- 0 end y */ __u32 xpos; /* 23-22 button color number */ /* 21-12 start x */ /* 9- 0 end x */ } video_highlight_t; typedef struct video_spu { int active; int stream_id; } video_spu_t; typedef struct video_spu_palette { /* SPU Palette information */ int length; __u8 *palette; } video_spu_palette_t; typedef struct video_navi_pack { int length; /* 0 ... 1024 */ __u8 data[1024]; } video_navi_pack_t; typedef __u16 video_attributes_t; /* bits: descr. */ /* 15-14 Video compression mode (0=MPEG-1, 1=MPEG-2) */ /* 13-12 TV system (0=525/60, 1=625/50) */ /* 11-10 Aspect ratio (0=4:3, 3=16:9) */ /* 9- 8 permitted display mode on 4:3 monitor (0=both, 1=only pan-sca */ /* 7 line 21-1 data present in GOP (1=yes, 0=no) */ /* 6 line 21-2 data present in GOP (1=yes, 0=no) */ /* 5- 3 source resolution (0=720x480/576, 1=704x480/576, 2=352x480/57 */ /* 2 source letterboxed (1=yes, 0=no) */ /* 0 film/camera mode (0= *camera, 1=film (625/50 only)) */ /* bit definitions for capabilities: */ /* can the hardware decode MPEG1 and/or MPEG2? */ #define VIDEO_CAP_MPEG1 1 #define VIDEO_CAP_MPEG2 2 /* can you send a system and/or program stream to video device? (you still have to open the video and the audio device but only send the stream to the video device) */ #define VIDEO_CAP_SYS 4 #define VIDEO_CAP_PROG 8 /* can the driver also handle SPU, NAVI and CSS encoded data? (CSS API is not present yet) */ #define VIDEO_CAP_SPU 16 #define VIDEO_CAP_NAVI 32 #define VIDEO_CAP_CSS 64 #define VIDEO_STOP _IO('o', 21) #define VIDEO_PLAY _IO('o', 22) #define VIDEO_FREEZE _IO('o', 23) #define VIDEO_CONTINUE _IO('o', 24) #define VIDEO_SELECT_SOURCE _IO('o', 25) #define VIDEO_SET_BLANK _IO('o', 26) #define VIDEO_GET_STATUS _IOR('o', 27, struct video_status) #define VIDEO_GET_EVENT _IOR('o', 28, struct video_event) #define VIDEO_SET_DISPLAY_FORMAT _IO('o', 29) #define VIDEO_STILLPICTURE _IOW('o', 30, struct video_still_picture) #define VIDEO_FAST_FORWARD _IO('o', 31) #define VIDEO_SLOWMOTION _IO('o', 32) #define VIDEO_GET_CAPABILITIES _IOR('o', 33, unsigned int) #define VIDEO_CLEAR_BUFFER _IO('o', 34) #define VIDEO_SET_ID _IO('o', 35) #define VIDEO_SET_STREAMTYPE _IO('o', 36) #define VIDEO_SET_FORMAT _IO('o', 37) #define VIDEO_SET_SYSTEM _IO('o', 38) #define VIDEO_SET_HIGHLIGHT _IOW('o', 39, video_highlight_t) #define VIDEO_SET_SPU _IOW('o', 50, video_spu_t) #define VIDEO_SET_SPU_PALETTE _IOW('o', 51, video_spu_palette_t) #define VIDEO_GET_NAVI _IOR('o', 52, video_navi_pack_t) #define VIDEO_SET_ATTRIBUTES _IO('o', 53) #define VIDEO_GET_SIZE _IOR('o', 55, video_size_t) #define VIDEO_GET_FRAME_RATE _IOR('o', 56, unsigned int) /** * VIDEO_GET_PTS * * Read the 33 bit presentation time stamp as defined * in ITU T-REC-H.222.0 / ISO/IEC 13818-1. * * The PTS should belong to the currently played * frame if possible, but may also be a value close to it * like the PTS of the last decoded frame or the last PTS * extracted by the PES parser. */ #define VIDEO_GET_PTS _IOR('o', 57, __u64) /* Read the number of displayed frames since the decoder was started */ #define VIDEO_GET_FRAME_COUNT _IOR('o', 58, __u64) #define VIDEO_COMMAND _IOWR('o', 59, struct video_command) #define VIDEO_TRY_COMMAND _IOWR('o', 60, struct video_command) #endif /* _DVBVIDEO_H_ */ linux/dvb/audio.h000064400000011537151027430560007742 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * audio.h * * Copyright (C) 2000 Ralph Metzler * & Marcus Metzler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Lesser Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBAUDIO_H_ #define _DVBAUDIO_H_ #include typedef enum { AUDIO_SOURCE_DEMUX, /* Select the demux as the main source */ AUDIO_SOURCE_MEMORY /* Select internal memory as the main source */ } audio_stream_source_t; typedef enum { AUDIO_STOPPED, /* Device is stopped */ AUDIO_PLAYING, /* Device is currently playing */ AUDIO_PAUSED /* Device is paused */ } audio_play_state_t; typedef enum { AUDIO_STEREO, AUDIO_MONO_LEFT, AUDIO_MONO_RIGHT, AUDIO_MONO, AUDIO_STEREO_SWAPPED } audio_channel_select_t; typedef struct audio_mixer { unsigned int volume_left; unsigned int volume_right; // what else do we need? bass, pass-through, ... } audio_mixer_t; typedef struct audio_status { int AV_sync_state; /* sync audio and video? */ int mute_state; /* audio is muted */ audio_play_state_t play_state; /* current playback state */ audio_stream_source_t stream_source; /* current stream source */ audio_channel_select_t channel_select; /* currently selected channel */ int bypass_mode; /* pass on audio data to */ audio_mixer_t mixer_state; /* current mixer state */ } audio_status_t; /* separate decoder hardware */ typedef struct audio_karaoke { /* if Vocal1 or Vocal2 are non-zero, they get mixed */ int vocal1; /* into left and right t at 70% each */ int vocal2; /* if both, Vocal1 and Vocal2 are non-zero, Vocal1 gets*/ int melody; /* mixed into the left channel and */ /* Vocal2 into the right channel at 100% each. */ /* if Melody is non-zero, the melody channel gets mixed*/ } audio_karaoke_t; /* into left and right */ typedef __u16 audio_attributes_t; /* bits: descr. */ /* 15-13 audio coding mode (0=ac3, 2=mpeg1, 3=mpeg2ext, 4=LPCM, 6=DTS, */ /* 12 multichannel extension */ /* 11-10 audio type (0=not spec, 1=language included) */ /* 9- 8 audio application mode (0=not spec, 1=karaoke, 2=surround) */ /* 7- 6 Quantization / DRC (mpeg audio: 1=DRC exists)(lpcm: 0=16bit, */ /* 5- 4 Sample frequency fs (0=48kHz, 1=96kHz) */ /* 2- 0 number of audio channels (n+1 channels) */ /* for GET_CAPABILITIES and SET_FORMAT, the latter should only set one bit */ #define AUDIO_CAP_DTS 1 #define AUDIO_CAP_LPCM 2 #define AUDIO_CAP_MP1 4 #define AUDIO_CAP_MP2 8 #define AUDIO_CAP_MP3 16 #define AUDIO_CAP_AAC 32 #define AUDIO_CAP_OGG 64 #define AUDIO_CAP_SDDS 128 #define AUDIO_CAP_AC3 256 #define AUDIO_STOP _IO('o', 1) #define AUDIO_PLAY _IO('o', 2) #define AUDIO_PAUSE _IO('o', 3) #define AUDIO_CONTINUE _IO('o', 4) #define AUDIO_SELECT_SOURCE _IO('o', 5) #define AUDIO_SET_MUTE _IO('o', 6) #define AUDIO_SET_AV_SYNC _IO('o', 7) #define AUDIO_SET_BYPASS_MODE _IO('o', 8) #define AUDIO_CHANNEL_SELECT _IO('o', 9) #define AUDIO_GET_STATUS _IOR('o', 10, audio_status_t) #define AUDIO_GET_CAPABILITIES _IOR('o', 11, unsigned int) #define AUDIO_CLEAR_BUFFER _IO('o', 12) #define AUDIO_SET_ID _IO('o', 13) #define AUDIO_SET_MIXER _IOW('o', 14, audio_mixer_t) #define AUDIO_SET_STREAMTYPE _IO('o', 15) #define AUDIO_SET_EXT_ID _IO('o', 16) #define AUDIO_SET_ATTRIBUTES _IOW('o', 17, audio_attributes_t) #define AUDIO_SET_KARAOKE _IOW('o', 18, audio_karaoke_t) /** * AUDIO_GET_PTS * * Read the 33 bit presentation time stamp as defined * in ITU T-REC-H.222.0 / ISO/IEC 13818-1. * * The PTS should belong to the currently played * frame if possible, but may also be a value close to it * like the PTS of the last decoded frame or the last PTS * extracted by the PES parser. */ #define AUDIO_GET_PTS _IOR('o', 19, __u64) #define AUDIO_BILINGUAL_CHANNEL_SELECT _IO('o', 20) #endif /* _DVBAUDIO_H_ */ linux/dvb/osd.h000064400000013201151027430560007414 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * osd.h * * Copyright (C) 2001 Ralph Metzler * & Marcus Metzler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Lesser Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBOSD_H_ #define _DVBOSD_H_ typedef enum { // All functions return -2 on "not open" OSD_Close=1, // () // Disables OSD and releases the buffers // returns 0 on success OSD_Open, // (x0,y0,x1,y1,BitPerPixel[2/4/8](color&0x0F),mix[0..15](color&0xF0)) // Opens OSD with this size and bit depth // returns 0 on success, -1 on DRAM allocation error, -2 on "already open" OSD_Show, // () // enables OSD mode // returns 0 on success OSD_Hide, // () // disables OSD mode // returns 0 on success OSD_Clear, // () // Sets all pixel to color 0 // returns 0 on success OSD_Fill, // (color) // Sets all pixel to color // returns 0 on success OSD_SetColor, // (color,R{x0},G{y0},B{x1},opacity{y1}) // set palette entry to , and apply // R,G,B: 0..255 // R=Red, G=Green, B=Blue // opacity=0: pixel opacity 0% (only video pixel shows) // opacity=1..254: pixel opacity as specified in header // opacity=255: pixel opacity 100% (only OSD pixel shows) // returns 0 on success, -1 on error OSD_SetPalette, // (firstcolor{color},lastcolor{x0},data) // Set a number of entries in the palette // sets the entries "firstcolor" through "lastcolor" from the array "data" // data has 4 byte for each color: // R,G,B, and a opacity value: 0->transparent, 1..254->mix, 255->pixel OSD_SetTrans, // (transparency{color}) // Sets transparency of mixed pixel (0..15) // returns 0 on success OSD_SetPixel, // (x0,y0,color) // sets pixel , to color number // returns 0 on success, -1 on error OSD_GetPixel, // (x0,y0) // returns color number of pixel ,, or -1 OSD_SetRow, // (x0,y0,x1,data) // fills pixels x0,y through x1,y with the content of data[] // returns 0 on success, -1 on clipping all pixel (no pixel drawn) OSD_SetBlock, // (x0,y0,x1,y1,increment{color},data) // fills pixels x0,y0 through x1,y1 with the content of data[] // inc contains the width of one line in the data block, // inc<=0 uses blockwidth as linewidth // returns 0 on success, -1 on clipping all pixel OSD_FillRow, // (x0,y0,x1,color) // fills pixels x0,y through x1,y with the color // returns 0 on success, -1 on clipping all pixel OSD_FillBlock, // (x0,y0,x1,y1,color) // fills pixels x0,y0 through x1,y1 with the color // returns 0 on success, -1 on clipping all pixel OSD_Line, // (x0,y0,x1,y1,color) // draw a line from x0,y0 to x1,y1 with the color // returns 0 on success OSD_Query, // (x0,y0,x1,y1,xasp{color}}), yasp=11 // fills parameters with the picture dimensions and the pixel aspect ratio // returns 0 on success OSD_Test, // () // draws a test picture. for debugging purposes only // returns 0 on success // TODO: remove "test" in final version OSD_Text, // (x0,y0,size,color,text) OSD_SetWindow, // (x0) set window with number 0 * & Ralph Metzler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBNET_H_ #define _DVBNET_H_ #include /** * struct dvb_net_if - describes a DVB network interface * * @pid: Packet ID (PID) of the MPEG-TS that contains data * @if_num: number of the Digital TV interface. * @feedtype: Encapsulation type of the feed. * * A MPEG-TS stream may contain packet IDs with IP packages on it. * This struct describes it, and the type of encoding. * * @feedtype can be: * * - %DVB_NET_FEEDTYPE_MPE for MPE encoding * - %DVB_NET_FEEDTYPE_ULE for ULE encoding. */ struct dvb_net_if { __u16 pid; __u16 if_num; __u8 feedtype; #define DVB_NET_FEEDTYPE_MPE 0 /* multi protocol encapsulation */ #define DVB_NET_FEEDTYPE_ULE 1 /* ultra lightweight encapsulation */ }; #define NET_ADD_IF _IOWR('o', 52, struct dvb_net_if) #define NET_REMOVE_IF _IO('o', 53) #define NET_GET_IF _IOWR('o', 54, struct dvb_net_if) /* binary compatibility cruft: */ struct __dvb_net_if_old { __u16 pid; __u16 if_num; }; #define __NET_ADD_IF_OLD _IOWR('o', 52, struct __dvb_net_if_old) #define __NET_GET_IF_OLD _IOWR('o', 54, struct __dvb_net_if_old) #endif /*_DVBNET_H_*/ linux/dvb/ca.h000064400000010227151027430560007217 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * ca.h * * Copyright (C) 2000 Ralph Metzler * & Marcus Metzler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Lesser Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBCA_H_ #define _DVBCA_H_ /** * struct ca_slot_info - CA slot interface types and info. * * @num: slot number. * @type: slot type. * @flags: flags applicable to the slot. * * This struct stores the CA slot information. * * @type can be: * * - %CA_CI - CI high level interface; * - %CA_CI_LINK - CI link layer level interface; * - %CA_CI_PHYS - CI physical layer level interface; * - %CA_DESCR - built-in descrambler; * - %CA_SC -simple smart card interface. * * @flags can be: * * - %CA_CI_MODULE_PRESENT - module (or card) inserted; * - %CA_CI_MODULE_READY - module is ready for usage. */ struct ca_slot_info { int num; int type; #define CA_CI 1 #define CA_CI_LINK 2 #define CA_CI_PHYS 4 #define CA_DESCR 8 #define CA_SC 128 unsigned int flags; #define CA_CI_MODULE_PRESENT 1 #define CA_CI_MODULE_READY 2 }; /** * struct ca_descr_info - descrambler types and info. * * @num: number of available descramblers (keys). * @type: type of supported scrambling system. * * Identifies the number of descramblers and their type. * * @type can be: * * - %CA_ECD - European Common Descrambler (ECD) hardware; * - %CA_NDS - Videoguard (NDS) hardware; * - %CA_DSS - Distributed Sample Scrambling (DSS) hardware. */ struct ca_descr_info { unsigned int num; unsigned int type; #define CA_ECD 1 #define CA_NDS 2 #define CA_DSS 4 }; /** * struct ca_caps - CA slot interface capabilities. * * @slot_num: total number of CA card and module slots. * @slot_type: bitmap with all supported types as defined at * &struct ca_slot_info (e. g. %CA_CI, %CA_CI_LINK, etc). * @descr_num: total number of descrambler slots (keys) * @descr_type: bitmap with all supported types as defined at * &struct ca_descr_info (e. g. %CA_ECD, %CA_NDS, etc). */ struct ca_caps { unsigned int slot_num; unsigned int slot_type; unsigned int descr_num; unsigned int descr_type; }; /** * struct ca_msg - a message to/from a CI-CAM * * @index: unused * @type: unused * @length: length of the message * @msg: message * * This struct carries a message to be send/received from a CI CA module. */ struct ca_msg { unsigned int index; unsigned int type; unsigned int length; unsigned char msg[256]; }; /** * struct ca_descr - CA descrambler control words info * * @index: CA Descrambler slot * @parity: control words parity, where 0 means even and 1 means odd * @cw: CA Descrambler control words */ struct ca_descr { unsigned int index; unsigned int parity; unsigned char cw[8]; }; #define CA_RESET _IO('o', 128) #define CA_GET_CAP _IOR('o', 129, struct ca_caps) #define CA_GET_SLOT_INFO _IOR('o', 130, struct ca_slot_info) #define CA_GET_DESCR_INFO _IOR('o', 131, struct ca_descr_info) #define CA_GET_MSG _IOR('o', 132, struct ca_msg) #define CA_SEND_MSG _IOW('o', 133, struct ca_msg) #define CA_SET_DESCR _IOW('o', 134, struct ca_descr) /* This is needed for legacy userspace support */ typedef struct ca_slot_info ca_slot_info_t; typedef struct ca_descr_info ca_descr_info_t; typedef struct ca_caps ca_caps_t; typedef struct ca_msg ca_msg_t; typedef struct ca_descr ca_descr_t; #endif linux/dvb/dmx.h000064400000023701151027430560007425 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * dmx.h * * Copyright (C) 2000 Marcus Metzler * & Ralph Metzler * for convergence integrated media GmbH * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #ifndef _DVBDMX_H_ #define _DVBDMX_H_ #include #include #define DMX_FILTER_SIZE 16 /** * enum dmx_output - Output for the demux. * * @DMX_OUT_DECODER: * Streaming directly to decoder. * @DMX_OUT_TAP: * Output going to a memory buffer (to be retrieved via the read command). * Delivers the stream output to the demux device on which the ioctl * is called. * @DMX_OUT_TS_TAP: * Output multiplexed into a new TS (to be retrieved by reading from the * logical DVR device). Routes output to the logical DVR device * ``/dev/dvb/adapter?/dvr?``, which delivers a TS multiplexed from all * filters for which @DMX_OUT_TS_TAP was specified. * @DMX_OUT_TSDEMUX_TAP: * Like @DMX_OUT_TS_TAP but retrieved from the DMX device. */ enum dmx_output { DMX_OUT_DECODER, DMX_OUT_TAP, DMX_OUT_TS_TAP, DMX_OUT_TSDEMUX_TAP }; /** * enum dmx_input - Input from the demux. * * @DMX_IN_FRONTEND: Input from a front-end device. * @DMX_IN_DVR: Input from the logical DVR device. */ enum dmx_input { DMX_IN_FRONTEND, DMX_IN_DVR }; /** * enum dmx_ts_pes - type of the PES filter. * * @DMX_PES_AUDIO0: first audio PID. Also referred as @DMX_PES_AUDIO. * @DMX_PES_VIDEO0: first video PID. Also referred as @DMX_PES_VIDEO. * @DMX_PES_TELETEXT0: first teletext PID. Also referred as @DMX_PES_TELETEXT. * @DMX_PES_SUBTITLE0: first subtitle PID. Also referred as @DMX_PES_SUBTITLE. * @DMX_PES_PCR0: first Program Clock Reference PID. * Also referred as @DMX_PES_PCR. * * @DMX_PES_AUDIO1: second audio PID. * @DMX_PES_VIDEO1: second video PID. * @DMX_PES_TELETEXT1: second teletext PID. * @DMX_PES_SUBTITLE1: second subtitle PID. * @DMX_PES_PCR1: second Program Clock Reference PID. * * @DMX_PES_AUDIO2: third audio PID. * @DMX_PES_VIDEO2: third video PID. * @DMX_PES_TELETEXT2: third teletext PID. * @DMX_PES_SUBTITLE2: third subtitle PID. * @DMX_PES_PCR2: third Program Clock Reference PID. * * @DMX_PES_AUDIO3: fourth audio PID. * @DMX_PES_VIDEO3: fourth video PID. * @DMX_PES_TELETEXT3: fourth teletext PID. * @DMX_PES_SUBTITLE3: fourth subtitle PID. * @DMX_PES_PCR3: fourth Program Clock Reference PID. * * @DMX_PES_OTHER: any other PID. */ enum dmx_ts_pes { DMX_PES_AUDIO0, DMX_PES_VIDEO0, DMX_PES_TELETEXT0, DMX_PES_SUBTITLE0, DMX_PES_PCR0, DMX_PES_AUDIO1, DMX_PES_VIDEO1, DMX_PES_TELETEXT1, DMX_PES_SUBTITLE1, DMX_PES_PCR1, DMX_PES_AUDIO2, DMX_PES_VIDEO2, DMX_PES_TELETEXT2, DMX_PES_SUBTITLE2, DMX_PES_PCR2, DMX_PES_AUDIO3, DMX_PES_VIDEO3, DMX_PES_TELETEXT3, DMX_PES_SUBTITLE3, DMX_PES_PCR3, DMX_PES_OTHER }; #define DMX_PES_AUDIO DMX_PES_AUDIO0 #define DMX_PES_VIDEO DMX_PES_VIDEO0 #define DMX_PES_TELETEXT DMX_PES_TELETEXT0 #define DMX_PES_SUBTITLE DMX_PES_SUBTITLE0 #define DMX_PES_PCR DMX_PES_PCR0 /** * struct dmx_filter - Specifies a section header filter. * * @filter: bit array with bits to be matched at the section header. * @mask: bits that are valid at the filter bit array. * @mode: mode of match: if bit is zero, it will match if equal (positive * match); if bit is one, it will match if the bit is negated. * * Note: All arrays in this struct have a size of DMX_FILTER_SIZE (16 bytes). */ struct dmx_filter { __u8 filter[DMX_FILTER_SIZE]; __u8 mask[DMX_FILTER_SIZE]; __u8 mode[DMX_FILTER_SIZE]; }; /** * struct dmx_sct_filter_params - Specifies a section filter. * * @pid: PID to be filtered. * @filter: section header filter, as defined by &struct dmx_filter. * @timeout: maximum time to filter, in milliseconds. * @flags: extra flags for the section filter. * * Carries the configuration for a MPEG-TS section filter. * * The @flags can be: * * - %DMX_CHECK_CRC - only deliver sections where the CRC check succeeded; * - %DMX_ONESHOT - disable the section filter after one section * has been delivered; * - %DMX_IMMEDIATE_START - Start filter immediately without requiring a * :ref:`DMX_START`. */ struct dmx_sct_filter_params { __u16 pid; struct dmx_filter filter; __u32 timeout; __u32 flags; #define DMX_CHECK_CRC 1 #define DMX_ONESHOT 2 #define DMX_IMMEDIATE_START 4 }; /** * struct dmx_pes_filter_params - Specifies Packetized Elementary Stream (PES) * filter parameters. * * @pid: PID to be filtered. * @input: Demux input, as specified by &enum dmx_input. * @output: Demux output, as specified by &enum dmx_output. * @pes_type: Type of the pes filter, as specified by &enum dmx_pes_type. * @flags: Demux PES flags. */ struct dmx_pes_filter_params { __u16 pid; enum dmx_input input; enum dmx_output output; enum dmx_ts_pes pes_type; __u32 flags; }; /** * struct dmx_stc - Stores System Time Counter (STC) information. * * @num: input data: number of the STC, from 0 to N. * @base: output: divisor for STC to get 90 kHz clock. * @stc: output: stc in @base * 90 kHz units. */ struct dmx_stc { unsigned int num; unsigned int base; __u64 stc; }; /** * enum dmx_buffer_flags - DMX memory-mapped buffer flags * * @DMX_BUFFER_FLAG_HAD_CRC32_DISCARD: * Indicates that the Kernel discarded one or more frames due to wrong * CRC32 checksum. * @DMX_BUFFER_FLAG_TEI: * Indicates that the Kernel has detected a Transport Error indicator * (TEI) on a filtered pid. * @DMX_BUFFER_PKT_COUNTER_MISMATCH: * Indicates that the Kernel has detected a packet counter mismatch * on a filtered pid. * @DMX_BUFFER_FLAG_DISCONTINUITY_DETECTED: * Indicates that the Kernel has detected one or more frame discontinuity. * @DMX_BUFFER_FLAG_DISCONTINUITY_INDICATOR: * Received at least one packet with a frame discontinuity indicator. */ enum dmx_buffer_flags { DMX_BUFFER_FLAG_HAD_CRC32_DISCARD = 1 << 0, DMX_BUFFER_FLAG_TEI = 1 << 1, DMX_BUFFER_PKT_COUNTER_MISMATCH = 1 << 2, DMX_BUFFER_FLAG_DISCONTINUITY_DETECTED = 1 << 3, DMX_BUFFER_FLAG_DISCONTINUITY_INDICATOR = 1 << 4, }; /** * struct dmx_buffer - dmx buffer info * * @index: id number of the buffer * @bytesused: number of bytes occupied by data in the buffer (payload); * @offset: for buffers with memory == DMX_MEMORY_MMAP; * offset from the start of the device memory for this plane, * (or a "cookie" that should be passed to mmap() as offset) * @length: size in bytes of the buffer * @flags: bit array of buffer flags as defined by &enum dmx_buffer_flags. * Filled only at &DMX_DQBUF. * @count: monotonic counter for filled buffers. Helps to identify * data stream loses. Filled only at &DMX_DQBUF. * * Contains data exchanged by application and driver using one of the streaming * I/O methods. * * Please notice that, for &DMX_QBUF, only @index should be filled. * On &DMX_DQBUF calls, all fields will be filled by the Kernel. */ struct dmx_buffer { __u32 index; __u32 bytesused; __u32 offset; __u32 length; __u32 flags; __u32 count; }; /** * struct dmx_requestbuffers - request dmx buffer information * * @count: number of requested buffers, * @size: size in bytes of the requested buffer * * Contains data used for requesting a dmx buffer. * All reserved fields must be set to zero. */ struct dmx_requestbuffers { __u32 count; __u32 size; }; /** * struct dmx_exportbuffer - export of dmx buffer as DMABUF file descriptor * * @index: id number of the buffer * @flags: flags for newly created file, currently only O_CLOEXEC is * supported, refer to manual of open syscall for more details * @fd: file descriptor associated with DMABUF (set by driver) * * Contains data used for exporting a dmx buffer as DMABUF file descriptor. * The buffer is identified by a 'cookie' returned by DMX_QUERYBUF * (identical to the cookie used to mmap() the buffer to userspace). All * reserved fields must be set to zero. The field reserved0 is expected to * become a structure 'type' allowing an alternative layout of the structure * content. Therefore this field should not be used for any other extensions. */ struct dmx_exportbuffer { __u32 index; __u32 flags; __s32 fd; }; #define DMX_START _IO('o', 41) #define DMX_STOP _IO('o', 42) #define DMX_SET_FILTER _IOW('o', 43, struct dmx_sct_filter_params) #define DMX_SET_PES_FILTER _IOW('o', 44, struct dmx_pes_filter_params) #define DMX_SET_BUFFER_SIZE _IO('o', 45) #define DMX_GET_PES_PIDS _IOR('o', 47, __u16[5]) #define DMX_GET_STC _IOWR('o', 50, struct dmx_stc) #define DMX_ADD_PID _IOW('o', 51, __u16) #define DMX_REMOVE_PID _IOW('o', 52, __u16) /* This is needed for legacy userspace support */ typedef enum dmx_output dmx_output_t; typedef enum dmx_input dmx_input_t; typedef enum dmx_ts_pes dmx_pes_type_t; typedef struct dmx_filter dmx_filter_t; #define DMX_REQBUFS _IOWR('o', 60, struct dmx_requestbuffers) #define DMX_QUERYBUF _IOWR('o', 61, struct dmx_buffer) #define DMX_EXPBUF _IOWR('o', 62, struct dmx_exportbuffer) #define DMX_QBUF _IOWR('o', 63, struct dmx_buffer) #define DMX_DQBUF _IOWR('o', 64, struct dmx_buffer) #endif /* _DVBDMX_H_ */ linux/un.h000064400000000600151027430560006475 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_UN_H #define _LINUX_UN_H #include #define UNIX_PATH_MAX 108 struct sockaddr_un { __kernel_sa_family_t sun_family; /* AF_UNIX */ char sun_path[UNIX_PATH_MAX]; /* pathname */ }; #define SIOCUNIXFILE (SIOCPROTOPRIVATE + 0) /* open a socket file with O_PATH */ #endif /* _LINUX_UN_H */ linux/atalk.h000064400000001777151027430560007167 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_ATALK_H__ #define __LINUX_ATALK_H__ #include #include #include /* * AppleTalk networking structures * * The following are directly referenced from the University Of Michigan * netatalk for compatibility reasons. */ #define ATPORT_FIRST 1 #define ATPORT_RESERVED 128 #define ATPORT_LAST 254 /* 254 is only legal on localtalk */ #define ATADDR_ANYNET (__u16)0 #define ATADDR_ANYNODE (__u8)0 #define ATADDR_ANYPORT (__u8)0 #define ATADDR_BCAST (__u8)255 #define DDP_MAXSZ 587 #define DDP_MAXHOPS 15 /* 4 bits of hop counter */ #define SIOCATALKDIFADDR (SIOCPROTOPRIVATE + 0) struct atalk_addr { __be16 s_net; __u8 s_node; }; struct sockaddr_at { __kernel_sa_family_t sat_family; __u8 sat_port; struct atalk_addr sat_addr; char sat_zero[8]; }; struct atalk_netrange { __u8 nr_phase; __be16 nr_firstnet; __be16 nr_lastnet; }; #endif /* __LINUX_ATALK_H__ */ linux/nvram.h000064400000001024151027430560007177 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NVRAM_H #define _LINUX_NVRAM_H #include /* /dev/nvram ioctls */ #define NVRAM_INIT _IO('p', 0x40) /* initialize NVRAM and set checksum */ #define NVRAM_SETCKS _IO('p', 0x41) /* recalculate checksum */ /* for all current systems, this is where NVRAM starts */ #define NVRAM_FIRST_BYTE 14 /* all these functions expect an NVRAM offset, not an absolute */ #define NVRAM_OFFSET(x) ((x)-NVRAM_FIRST_BYTE) #endif /* _LINUX_NVRAM_H */ linux/mpls_iptunnel.h000064400000001371151027430560010752 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * mpls tunnel api * * Authors: * Roopa Prabhu * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_MPLS_IPTUNNEL_H #define _LINUX_MPLS_IPTUNNEL_H /* MPLS tunnel attributes * [RTA_ENCAP] = { * [MPLS_IPTUNNEL_DST] * [MPLS_IPTUNNEL_TTL] * } */ enum { MPLS_IPTUNNEL_UNSPEC, MPLS_IPTUNNEL_DST, MPLS_IPTUNNEL_TTL, __MPLS_IPTUNNEL_MAX, }; #define MPLS_IPTUNNEL_MAX (__MPLS_IPTUNNEL_MAX - 1) #endif /* _LINUX_MPLS_IPTUNNEL_H */ linux/mman.h000064400000002551151027430560007012 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MMAN_H #define _LINUX_MMAN_H #include #include #define MREMAP_MAYMOVE 1 #define MREMAP_FIXED 2 #define OVERCOMMIT_GUESS 0 #define OVERCOMMIT_ALWAYS 1 #define OVERCOMMIT_NEVER 2 /* * Huge page size encoding when MAP_HUGETLB is specified, and a huge page * size other than the default is desired. See hugetlb_encode.h. * All known huge page size encodings are provided here. It is the * responsibility of the application to know which sizes are supported on * the running system. See mmap(2) man page for details. */ #define MAP_HUGE_SHIFT HUGETLB_FLAG_ENCODE_SHIFT #define MAP_HUGE_MASK HUGETLB_FLAG_ENCODE_MASK #define MAP_HUGE_16KB HUGETLB_FLAG_ENCODE_16KB #define MAP_HUGE_64KB HUGETLB_FLAG_ENCODE_64KB #define MAP_HUGE_512KB HUGETLB_FLAG_ENCODE_512KB #define MAP_HUGE_1MB HUGETLB_FLAG_ENCODE_1MB #define MAP_HUGE_2MB HUGETLB_FLAG_ENCODE_2MB #define MAP_HUGE_8MB HUGETLB_FLAG_ENCODE_8MB #define MAP_HUGE_16MB HUGETLB_FLAG_ENCODE_16MB #define MAP_HUGE_32MB HUGETLB_FLAG_ENCODE_32MB #define MAP_HUGE_256MB HUGETLB_FLAG_ENCODE_256MB #define MAP_HUGE_512MB HUGETLB_FLAG_ENCODE_512MB #define MAP_HUGE_1GB HUGETLB_FLAG_ENCODE_1GB #define MAP_HUGE_2GB HUGETLB_FLAG_ENCODE_2GB #define MAP_HUGE_16GB HUGETLB_FLAG_ENCODE_16GB #endif /* _LINUX_MMAN_H */ linux/serial_reg.h000064400000036210151027430560010175 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * include/linux/serial_reg.h * * Copyright (C) 1992, 1994 by Theodore Ts'o. * * Redistribution of this file is permitted under the terms of the GNU * Public License (GPL) * * These are the UART port assignments, expressed as offsets from the base * register. These assignments should hold for any serial port based on * a 8250, 16450, or 16550(A). */ #ifndef _LINUX_SERIAL_REG_H #define _LINUX_SERIAL_REG_H /* * DLAB=0 */ #define UART_RX 0 /* In: Receive buffer */ #define UART_TX 0 /* Out: Transmit buffer */ #define UART_IER 1 /* Out: Interrupt Enable Register */ #define UART_IER_MSI 0x08 /* Enable Modem status interrupt */ #define UART_IER_RLSI 0x04 /* Enable receiver line status interrupt */ #define UART_IER_THRI 0x02 /* Enable Transmitter holding register int. */ #define UART_IER_RDI 0x01 /* Enable receiver data interrupt */ /* * Sleep mode for ST16650 and TI16750. For the ST16650, EFR[4]=1 */ #define UART_IERX_SLEEP 0x10 /* Enable sleep mode */ #define UART_IIR 2 /* In: Interrupt ID Register */ #define UART_IIR_NO_INT 0x01 /* No interrupts pending */ #define UART_IIR_ID 0x0e /* Mask for the interrupt ID */ #define UART_IIR_MSI 0x00 /* Modem status interrupt */ #define UART_IIR_THRI 0x02 /* Transmitter holding register empty */ #define UART_IIR_RDI 0x04 /* Receiver data interrupt */ #define UART_IIR_RLSI 0x06 /* Receiver line status interrupt */ #define UART_IIR_BUSY 0x07 /* DesignWare APB Busy Detect */ #define UART_IIR_RX_TIMEOUT 0x0c /* OMAP RX Timeout interrupt */ #define UART_IIR_XOFF 0x10 /* OMAP XOFF/Special Character */ #define UART_IIR_CTS_RTS_DSR 0x20 /* OMAP CTS/RTS/DSR Change */ #define UART_FCR 2 /* Out: FIFO Control Register */ #define UART_FCR_ENABLE_FIFO 0x01 /* Enable the FIFO */ #define UART_FCR_CLEAR_RCVR 0x02 /* Clear the RCVR FIFO */ #define UART_FCR_CLEAR_XMIT 0x04 /* Clear the XMIT FIFO */ #define UART_FCR_DMA_SELECT 0x08 /* For DMA applications */ /* * Note: The FIFO trigger levels are chip specific: * RX:76 = 00 01 10 11 TX:54 = 00 01 10 11 * PC16550D: 1 4 8 14 xx xx xx xx * TI16C550A: 1 4 8 14 xx xx xx xx * TI16C550C: 1 4 8 14 xx xx xx xx * ST16C550: 1 4 8 14 xx xx xx xx * ST16C650: 8 16 24 28 16 8 24 30 PORT_16650V2 * NS16C552: 1 4 8 14 xx xx xx xx * ST16C654: 8 16 56 60 8 16 32 56 PORT_16654 * TI16C750: 1 16 32 56 xx xx xx xx PORT_16750 * TI16C752: 8 16 56 60 8 16 32 56 * Tegra: 1 4 8 14 16 8 4 1 PORT_TEGRA */ #define UART_FCR_R_TRIG_00 0x00 #define UART_FCR_R_TRIG_01 0x40 #define UART_FCR_R_TRIG_10 0x80 #define UART_FCR_R_TRIG_11 0xc0 #define UART_FCR_T_TRIG_00 0x00 #define UART_FCR_T_TRIG_01 0x10 #define UART_FCR_T_TRIG_10 0x20 #define UART_FCR_T_TRIG_11 0x30 #define UART_FCR_TRIGGER_MASK 0xC0 /* Mask for the FIFO trigger range */ #define UART_FCR_TRIGGER_1 0x00 /* Mask for trigger set at 1 */ #define UART_FCR_TRIGGER_4 0x40 /* Mask for trigger set at 4 */ #define UART_FCR_TRIGGER_8 0x80 /* Mask for trigger set at 8 */ #define UART_FCR_TRIGGER_14 0xC0 /* Mask for trigger set at 14 */ /* 16650 definitions */ #define UART_FCR6_R_TRIGGER_8 0x00 /* Mask for receive trigger set at 1 */ #define UART_FCR6_R_TRIGGER_16 0x40 /* Mask for receive trigger set at 4 */ #define UART_FCR6_R_TRIGGER_24 0x80 /* Mask for receive trigger set at 8 */ #define UART_FCR6_R_TRIGGER_28 0xC0 /* Mask for receive trigger set at 14 */ #define UART_FCR6_T_TRIGGER_16 0x00 /* Mask for transmit trigger set at 16 */ #define UART_FCR6_T_TRIGGER_8 0x10 /* Mask for transmit trigger set at 8 */ #define UART_FCR6_T_TRIGGER_24 0x20 /* Mask for transmit trigger set at 24 */ #define UART_FCR6_T_TRIGGER_30 0x30 /* Mask for transmit trigger set at 30 */ #define UART_FCR7_64BYTE 0x20 /* Go into 64 byte mode (TI16C750 and some Freescale UARTs) */ #define UART_FCR_R_TRIG_SHIFT 6 #define UART_FCR_R_TRIG_BITS(x) \ (((x) & UART_FCR_TRIGGER_MASK) >> UART_FCR_R_TRIG_SHIFT) #define UART_FCR_R_TRIG_MAX_STATE 4 #define UART_LCR 3 /* Out: Line Control Register */ /* * Note: if the word length is 5 bits (UART_LCR_WLEN5), then setting * UART_LCR_STOP will select 1.5 stop bits, not 2 stop bits. */ #define UART_LCR_DLAB 0x80 /* Divisor latch access bit */ #define UART_LCR_SBC 0x40 /* Set break control */ #define UART_LCR_SPAR 0x20 /* Stick parity (?) */ #define UART_LCR_EPAR 0x10 /* Even parity select */ #define UART_LCR_PARITY 0x08 /* Parity Enable */ #define UART_LCR_STOP 0x04 /* Stop bits: 0=1 bit, 1=2 bits */ #define UART_LCR_WLEN5 0x00 /* Wordlength: 5 bits */ #define UART_LCR_WLEN6 0x01 /* Wordlength: 6 bits */ #define UART_LCR_WLEN7 0x02 /* Wordlength: 7 bits */ #define UART_LCR_WLEN8 0x03 /* Wordlength: 8 bits */ /* * Access to some registers depends on register access / configuration * mode. */ #define UART_LCR_CONF_MODE_A UART_LCR_DLAB /* Configutation mode A */ #define UART_LCR_CONF_MODE_B 0xBF /* Configutation mode B */ #define UART_MCR 4 /* Out: Modem Control Register */ #define UART_MCR_CLKSEL 0x80 /* Divide clock by 4 (TI16C752, EFR[4]=1) */ #define UART_MCR_TCRTLR 0x40 /* Access TCR/TLR (TI16C752, EFR[4]=1) */ #define UART_MCR_XONANY 0x20 /* Enable Xon Any (TI16C752, EFR[4]=1) */ #define UART_MCR_AFE 0x20 /* Enable auto-RTS/CTS (TI16C550C/TI16C750) */ #define UART_MCR_LOOP 0x10 /* Enable loopback test mode */ #define UART_MCR_OUT2 0x08 /* Out2 complement */ #define UART_MCR_OUT1 0x04 /* Out1 complement */ #define UART_MCR_RTS 0x02 /* RTS complement */ #define UART_MCR_DTR 0x01 /* DTR complement */ #define UART_LSR 5 /* In: Line Status Register */ #define UART_LSR_FIFOE 0x80 /* Fifo error */ #define UART_LSR_TEMT 0x40 /* Transmitter empty */ #define UART_LSR_THRE 0x20 /* Transmit-hold-register empty */ #define UART_LSR_BI 0x10 /* Break interrupt indicator */ #define UART_LSR_FE 0x08 /* Frame error indicator */ #define UART_LSR_PE 0x04 /* Parity error indicator */ #define UART_LSR_OE 0x02 /* Overrun error indicator */ #define UART_LSR_DR 0x01 /* Receiver data ready */ #define UART_LSR_BRK_ERROR_BITS 0x1E /* BI, FE, PE, OE bits */ #define UART_MSR 6 /* In: Modem Status Register */ #define UART_MSR_DCD 0x80 /* Data Carrier Detect */ #define UART_MSR_RI 0x40 /* Ring Indicator */ #define UART_MSR_DSR 0x20 /* Data Set Ready */ #define UART_MSR_CTS 0x10 /* Clear to Send */ #define UART_MSR_DDCD 0x08 /* Delta DCD */ #define UART_MSR_TERI 0x04 /* Trailing edge ring indicator */ #define UART_MSR_DDSR 0x02 /* Delta DSR */ #define UART_MSR_DCTS 0x01 /* Delta CTS */ #define UART_MSR_ANY_DELTA 0x0F /* Any of the delta bits! */ #define UART_SCR 7 /* I/O: Scratch Register */ /* * DLAB=1 */ #define UART_DLL 0 /* Out: Divisor Latch Low */ #define UART_DLM 1 /* Out: Divisor Latch High */ #define UART_DIV_MAX 0xFFFF /* Max divisor value */ /* * LCR=0xBF (or DLAB=1 for 16C660) */ #define UART_EFR 2 /* I/O: Extended Features Register */ #define UART_XR_EFR 9 /* I/O: Extended Features Register (XR17D15x) */ #define UART_EFR_CTS 0x80 /* CTS flow control */ #define UART_EFR_RTS 0x40 /* RTS flow control */ #define UART_EFR_SCD 0x20 /* Special character detect */ #define UART_EFR_ECB 0x10 /* Enhanced control bit */ /* * the low four bits control software flow control */ /* * LCR=0xBF, TI16C752, ST16650, ST16650A, ST16654 */ #define UART_XON1 4 /* I/O: Xon character 1 */ #define UART_XON2 5 /* I/O: Xon character 2 */ #define UART_XOFF1 6 /* I/O: Xoff character 1 */ #define UART_XOFF2 7 /* I/O: Xoff character 2 */ /* * EFR[4]=1 MCR[6]=1, TI16C752 */ #define UART_TI752_TCR 6 /* I/O: transmission control register */ #define UART_TI752_TLR 7 /* I/O: trigger level register */ /* * LCR=0xBF, XR16C85x */ #define UART_TRG 0 /* FCTR bit 7 selects Rx or Tx * In: Fifo count * Out: Fifo custom trigger levels */ /* * These are the definitions for the Programmable Trigger Register */ #define UART_TRG_1 0x01 #define UART_TRG_4 0x04 #define UART_TRG_8 0x08 #define UART_TRG_16 0x10 #define UART_TRG_32 0x20 #define UART_TRG_64 0x40 #define UART_TRG_96 0x60 #define UART_TRG_120 0x78 #define UART_TRG_128 0x80 #define UART_FCTR 1 /* Feature Control Register */ #define UART_FCTR_RTS_NODELAY 0x00 /* RTS flow control delay */ #define UART_FCTR_RTS_4DELAY 0x01 #define UART_FCTR_RTS_6DELAY 0x02 #define UART_FCTR_RTS_8DELAY 0x03 #define UART_FCTR_IRDA 0x04 /* IrDa data encode select */ #define UART_FCTR_TX_INT 0x08 /* Tx interrupt type select */ #define UART_FCTR_TRGA 0x00 /* Tx/Rx 550 trigger table select */ #define UART_FCTR_TRGB 0x10 /* Tx/Rx 650 trigger table select */ #define UART_FCTR_TRGC 0x20 /* Tx/Rx 654 trigger table select */ #define UART_FCTR_TRGD 0x30 /* Tx/Rx 850 programmable trigger select */ #define UART_FCTR_SCR_SWAP 0x40 /* Scratch pad register swap */ #define UART_FCTR_RX 0x00 /* Programmable trigger mode select */ #define UART_FCTR_TX 0x80 /* Programmable trigger mode select */ /* * LCR=0xBF, FCTR[6]=1 */ #define UART_EMSR 7 /* Extended Mode Select Register */ #define UART_EMSR_FIFO_COUNT 0x01 /* Rx/Tx select */ #define UART_EMSR_ALT_COUNT 0x02 /* Alternating count select */ /* * The Intel XScale on-chip UARTs define these bits */ #define UART_IER_DMAE 0x80 /* DMA Requests Enable */ #define UART_IER_UUE 0x40 /* UART Unit Enable */ #define UART_IER_NRZE 0x20 /* NRZ coding Enable */ #define UART_IER_RTOIE 0x10 /* Receiver Time Out Interrupt Enable */ #define UART_IIR_TOD 0x08 /* Character Timeout Indication Detected */ #define UART_FCR_PXAR1 0x00 /* receive FIFO threshold = 1 */ #define UART_FCR_PXAR8 0x40 /* receive FIFO threshold = 8 */ #define UART_FCR_PXAR16 0x80 /* receive FIFO threshold = 16 */ #define UART_FCR_PXAR32 0xc0 /* receive FIFO threshold = 32 */ /* * These register definitions are for the 16C950 */ #define UART_ASR 0x01 /* Additional Status Register */ #define UART_RFL 0x03 /* Receiver FIFO level */ #define UART_TFL 0x04 /* Transmitter FIFO level */ #define UART_ICR 0x05 /* Index Control Register */ /* The 16950 ICR registers */ #define UART_ACR 0x00 /* Additional Control Register */ #define UART_CPR 0x01 /* Clock Prescalar Register */ #define UART_TCR 0x02 /* Times Clock Register */ #define UART_CKS 0x03 /* Clock Select Register */ #define UART_TTL 0x04 /* Transmitter Interrupt Trigger Level */ #define UART_RTL 0x05 /* Receiver Interrupt Trigger Level */ #define UART_FCL 0x06 /* Flow Control Level Lower */ #define UART_FCH 0x07 /* Flow Control Level Higher */ #define UART_ID1 0x08 /* ID #1 */ #define UART_ID2 0x09 /* ID #2 */ #define UART_ID3 0x0A /* ID #3 */ #define UART_REV 0x0B /* Revision */ #define UART_CSR 0x0C /* Channel Software Reset */ #define UART_NMR 0x0D /* Nine-bit Mode Register */ #define UART_CTR 0xFF /* * The 16C950 Additional Control Register */ #define UART_ACR_RXDIS 0x01 /* Receiver disable */ #define UART_ACR_TXDIS 0x02 /* Transmitter disable */ #define UART_ACR_DSRFC 0x04 /* DSR Flow Control */ #define UART_ACR_TLENB 0x20 /* 950 trigger levels enable */ #define UART_ACR_ICRRD 0x40 /* ICR Read enable */ #define UART_ACR_ASREN 0x80 /* Additional status enable */ /* * These definitions are for the RSA-DV II/S card, from * * Kiyokazu SUTO */ #define UART_RSA_BASE (-8) #define UART_RSA_MSR ((UART_RSA_BASE) + 0) /* I/O: Mode Select Register */ #define UART_RSA_MSR_SWAP (1 << 0) /* Swap low/high 8 bytes in I/O port addr */ #define UART_RSA_MSR_FIFO (1 << 2) /* Enable the external FIFO */ #define UART_RSA_MSR_FLOW (1 << 3) /* Enable the auto RTS/CTS flow control */ #define UART_RSA_MSR_ITYP (1 << 4) /* Level (1) / Edge triger (0) */ #define UART_RSA_IER ((UART_RSA_BASE) + 1) /* I/O: Interrupt Enable Register */ #define UART_RSA_IER_Rx_FIFO_H (1 << 0) /* Enable Rx FIFO half full int. */ #define UART_RSA_IER_Tx_FIFO_H (1 << 1) /* Enable Tx FIFO half full int. */ #define UART_RSA_IER_Tx_FIFO_E (1 << 2) /* Enable Tx FIFO empty int. */ #define UART_RSA_IER_Rx_TOUT (1 << 3) /* Enable char receive timeout int */ #define UART_RSA_IER_TIMER (1 << 4) /* Enable timer interrupt */ #define UART_RSA_SRR ((UART_RSA_BASE) + 2) /* IN: Status Read Register */ #define UART_RSA_SRR_Tx_FIFO_NEMP (1 << 0) /* Tx FIFO is not empty (1) */ #define UART_RSA_SRR_Tx_FIFO_NHFL (1 << 1) /* Tx FIFO is not half full (1) */ #define UART_RSA_SRR_Tx_FIFO_NFUL (1 << 2) /* Tx FIFO is not full (1) */ #define UART_RSA_SRR_Rx_FIFO_NEMP (1 << 3) /* Rx FIFO is not empty (1) */ #define UART_RSA_SRR_Rx_FIFO_NHFL (1 << 4) /* Rx FIFO is not half full (1) */ #define UART_RSA_SRR_Rx_FIFO_NFUL (1 << 5) /* Rx FIFO is not full (1) */ #define UART_RSA_SRR_Rx_TOUT (1 << 6) /* Character reception timeout occurred (1) */ #define UART_RSA_SRR_TIMER (1 << 7) /* Timer interrupt occurred */ #define UART_RSA_FRR ((UART_RSA_BASE) + 2) /* OUT: FIFO Reset Register */ #define UART_RSA_TIVSR ((UART_RSA_BASE) + 3) /* I/O: Timer Interval Value Set Register */ #define UART_RSA_TCR ((UART_RSA_BASE) + 4) /* OUT: Timer Control Register */ #define UART_RSA_TCR_SWITCH (1 << 0) /* Timer on */ /* * The RSA DSV/II board has two fixed clock frequencies. One is the * standard rate, and the other is 8 times faster. */ #define SERIAL_RSA_BAUD_BASE (921600) #define SERIAL_RSA_BAUD_BASE_LO (SERIAL_RSA_BAUD_BASE / 8) /* Extra registers for TI DA8xx/66AK2x */ #define UART_DA830_PWREMU_MGMT 12 /* PWREMU_MGMT register bits */ #define UART_DA830_PWREMU_MGMT_FREE (1 << 0) /* Free-running mode */ #define UART_DA830_PWREMU_MGMT_URRST (1 << 13) /* Receiver reset/enable */ #define UART_DA830_PWREMU_MGMT_UTRST (1 << 14) /* Transmitter reset/enable */ /* * Extra serial register definitions for the internal UARTs * in TI OMAP processors. */ #define OMAP1_UART1_BASE 0xfffb0000 #define OMAP1_UART2_BASE 0xfffb0800 #define OMAP1_UART3_BASE 0xfffb9800 #define UART_OMAP_MDR1 0x08 /* Mode definition register */ #define UART_OMAP_MDR2 0x09 /* Mode definition register 2 */ #define UART_OMAP_SCR 0x10 /* Supplementary control register */ #define UART_OMAP_SSR 0x11 /* Supplementary status register */ #define UART_OMAP_EBLR 0x12 /* BOF length register */ #define UART_OMAP_OSC_12M_SEL 0x13 /* OMAP1510 12MHz osc select */ #define UART_OMAP_MVER 0x14 /* Module version register */ #define UART_OMAP_SYSC 0x15 /* System configuration register */ #define UART_OMAP_SYSS 0x16 /* System status register */ #define UART_OMAP_WER 0x17 /* Wake-up enable register */ #define UART_OMAP_TX_LVL 0x1a /* TX FIFO level register */ /* * These are the definitions for the MDR1 register */ #define UART_OMAP_MDR1_16X_MODE 0x00 /* UART 16x mode */ #define UART_OMAP_MDR1_SIR_MODE 0x01 /* SIR mode */ #define UART_OMAP_MDR1_16X_ABAUD_MODE 0x02 /* UART 16x auto-baud */ #define UART_OMAP_MDR1_13X_MODE 0x03 /* UART 13x mode */ #define UART_OMAP_MDR1_MIR_MODE 0x04 /* MIR mode */ #define UART_OMAP_MDR1_FIR_MODE 0x05 /* FIR mode */ #define UART_OMAP_MDR1_CIR_MODE 0x06 /* CIR mode */ #define UART_OMAP_MDR1_DISABLE 0x07 /* Disable (default state) */ /* * These are definitions for the Altera ALTR_16550_F32/F64/F128 * Normalized from 0x100 to 0x40 because of shift by 2 (32 bit regs). */ #define UART_ALTR_AFR 0x40 /* Additional Features Register */ #define UART_ALTR_EN_TXFIFO_LW 0x01 /* Enable the TX FIFO Low Watermark */ #define UART_ALTR_TX_LOW 0x41 /* Tx FIFO Low Watermark */ #endif /* _LINUX_SERIAL_REG_H */ linux/const.h000064400000001424151027430560007206 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* const.h: Macros for dealing with constants. */ #ifndef _LINUX_CONST_H #define _LINUX_CONST_H /* Some constant macros are used in both assembler and * C code. Therefore we cannot annotate them always with * 'UL' and other type specifiers unilaterally. We * use the following macros to deal with this. * * Similarly, _AT() will cast an expression with a type in C, but * leave it unchanged in asm. */ #ifdef __ASSEMBLY__ #define _AC(X,Y) X #define _AT(T,X) X #else #define __AC(X,Y) (X##Y) #define _AC(X,Y) __AC(X,Y) #define _AT(T,X) ((T)(X)) #endif #define _UL(x) (_AC(x, UL)) #define _ULL(x) (_AC(x, ULL)) #define _BITUL(x) (_UL(1) << (x)) #define _BITULL(x) (_ULL(1) << (x)) #endif /* _LINUX_CONST_H */ linux/oom.h000064400000000777151027430560006664 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __INCLUDE_LINUX_OOM_H #define __INCLUDE_LINUX_OOM_H /* * /proc//oom_score_adj set to OOM_SCORE_ADJ_MIN disables oom killing for * pid. */ #define OOM_SCORE_ADJ_MIN (-1000) #define OOM_SCORE_ADJ_MAX 1000 /* * /proc//oom_adj set to -17 protects from the oom killer for legacy * purposes. */ #define OOM_DISABLE (-17) /* inclusive */ #define OOM_ADJUST_MIN (-16) #define OOM_ADJUST_MAX 15 #endif /* __INCLUDE_LINUX_OOM_H */ linux/nfs4_mount.h000064400000003614151027430560010157 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NFS4_MOUNT_H #define _LINUX_NFS4_MOUNT_H /* * linux/include/linux/nfs4_mount.h * * Copyright (C) 2002 Trond Myklebust * * structure passed from user-space to kernel-space during an nfsv4 mount */ /* * WARNING! Do not delete or change the order of these fields. If * a new field is required then add it to the end. The version field * tracks which fields are present. This will ensure some measure of * mount-to-kernel version compatibility. Some of these aren't used yet * but here they are anyway. */ #define NFS4_MOUNT_VERSION 1 struct nfs_string { unsigned int len; const char * data; }; struct nfs4_mount_data { int version; /* 1 */ int flags; /* 1 */ int rsize; /* 1 */ int wsize; /* 1 */ int timeo; /* 1 */ int retrans; /* 1 */ int acregmin; /* 1 */ int acregmax; /* 1 */ int acdirmin; /* 1 */ int acdirmax; /* 1 */ /* see the definition of 'struct clientaddr4' in RFC3010 */ struct nfs_string client_addr; /* 1 */ /* Mount path */ struct nfs_string mnt_path; /* 1 */ /* Server details */ struct nfs_string hostname; /* 1 */ /* Server IP address */ unsigned int host_addrlen; /* 1 */ struct sockaddr * host_addr; /* 1 */ /* Transport protocol to use */ int proto; /* 1 */ /* Pseudo-flavours to use for authentication. See RFC2623 */ int auth_flavourlen; /* 1 */ int *auth_flavours; /* 1 */ }; /* bits in the flags field */ /* Note: the fields that correspond to existing NFSv2/v3 mount options * should mirror the values from include/linux/nfs_mount.h */ #define NFS4_MOUNT_SOFT 0x0001 /* 1 */ #define NFS4_MOUNT_INTR 0x0002 /* 1 */ #define NFS4_MOUNT_NOCTO 0x0010 /* 1 */ #define NFS4_MOUNT_NOAC 0x0020 /* 1 */ #define NFS4_MOUNT_STRICTLOCK 0x1000 /* 1 */ #define NFS4_MOUNT_UNSHARED 0x8000 /* 1 */ #define NFS4_MOUNT_FLAGMASK 0x9033 #endif linux/fanotify.h000064400000012335151027430560007702 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FANOTIFY_H #define _LINUX_FANOTIFY_H #include /* the following events that user-space can register for */ #define FAN_ACCESS 0x00000001 /* File was accessed */ #define FAN_MODIFY 0x00000002 /* File was modified */ #define FAN_CLOSE_WRITE 0x00000008 /* Writtable file closed */ #define FAN_CLOSE_NOWRITE 0x00000010 /* Unwrittable file closed */ #define FAN_OPEN 0x00000020 /* File was opened */ #define FAN_OPEN_EXEC 0x00001000 /* File was opened for exec */ #define FAN_Q_OVERFLOW 0x00004000 /* Event queued overflowed */ #define FAN_OPEN_PERM 0x00010000 /* File open in perm check */ #define FAN_ACCESS_PERM 0x00020000 /* File accessed in perm check */ #define FAN_OPEN_EXEC_PERM 0x00040000 /* File open/exec in perm check */ #define FAN_ONDIR 0x40000000 /* event occurred against dir */ #define FAN_EVENT_ON_CHILD 0x08000000 /* interested in child events */ /* helper events */ #define FAN_CLOSE (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE) /* close */ /* flags used for fanotify_init() */ #define FAN_CLOEXEC 0x00000001 #define FAN_NONBLOCK 0x00000002 /* These are NOT bitwise flags. Both bits are used together. */ #define FAN_CLASS_NOTIF 0x00000000 #define FAN_CLASS_CONTENT 0x00000004 #define FAN_CLASS_PRE_CONTENT 0x00000008 /* Deprecated - do not use this in programs and do not add new flags here! */ #define FAN_ALL_CLASS_BITS (FAN_CLASS_NOTIF | FAN_CLASS_CONTENT | \ FAN_CLASS_PRE_CONTENT) #define FAN_UNLIMITED_QUEUE 0x00000010 #define FAN_UNLIMITED_MARKS 0x00000020 #define FAN_ENABLE_AUDIT 0x00000040 /* Flags to determine fanotify event format */ #define FAN_REPORT_TID 0x00000100 /* event->pid is thread id */ /* Deprecated - do not use this in programs and do not add new flags here! */ #define FAN_ALL_INIT_FLAGS (FAN_CLOEXEC | FAN_NONBLOCK | \ FAN_ALL_CLASS_BITS | FAN_UNLIMITED_QUEUE |\ FAN_UNLIMITED_MARKS) /* flags used for fanotify_modify_mark() */ #define FAN_MARK_ADD 0x00000001 #define FAN_MARK_REMOVE 0x00000002 #define FAN_MARK_DONT_FOLLOW 0x00000004 #define FAN_MARK_ONLYDIR 0x00000008 /* FAN_MARK_MOUNT is 0x00000010 */ #define FAN_MARK_IGNORED_MASK 0x00000020 #define FAN_MARK_IGNORED_SURV_MODIFY 0x00000040 #define FAN_MARK_FLUSH 0x00000080 /* FAN_MARK_FILESYSTEM is 0x00000100 */ /* These are NOT bitwise flags. Both bits can be used togther. */ #define FAN_MARK_INODE 0x00000000 #define FAN_MARK_MOUNT 0x00000010 #define FAN_MARK_FILESYSTEM 0x00000100 /* These are NOT bitwise flags. Both bits can be used togther. */ #define FAN_MARK_INODE 0x00000000 #define FAN_MARK_MOUNT 0x00000010 /* Deprecated - do not use this in programs and do not add new flags here! */ #define FAN_ALL_MARK_FLAGS (FAN_MARK_ADD |\ FAN_MARK_REMOVE |\ FAN_MARK_DONT_FOLLOW |\ FAN_MARK_ONLYDIR |\ FAN_MARK_IGNORED_MASK |\ FAN_MARK_IGNORED_SURV_MODIFY |\ FAN_MARK_FLUSH|\ FAN_MARK_TYPE_MASK) /* Deprecated - do not use this in programs and do not add new flags here! */ #define FAN_ALL_EVENTS (FAN_ACCESS |\ FAN_MODIFY |\ FAN_CLOSE |\ FAN_OPEN) /* * All events which require a permission response from userspace */ /* Deprecated - do not use this in programs and do not add new flags here! */ #define FAN_ALL_PERM_EVENTS (FAN_OPEN_PERM |\ FAN_ACCESS_PERM) /* Deprecated - do not use this in programs and do not add new flags here! */ #define FAN_ALL_OUTGOING_EVENTS (FAN_ALL_EVENTS |\ FAN_ALL_PERM_EVENTS |\ FAN_Q_OVERFLOW) #define FANOTIFY_METADATA_VERSION 3 struct fanotify_event_metadata { __u32 event_len; __u8 vers; __u8 reserved; __u16 metadata_len; __aligned_u64 mask; __s32 fd; __s32 pid; }; /* * User space may need to record additional information about its decision. * The extra information type records what kind of information is included. * The default is none. We also define an extra information buffer whose * size is determined by the extra information type. * * If the information type is Audit Rule, then the information following * is the rule number that triggered the user space decision that * requires auditing. */ #define FAN_RESPONSE_INFO_NONE 0 #define FAN_RESPONSE_INFO_AUDIT_RULE 1 struct fanotify_response { __s32 fd; __u32 response; }; struct fanotify_response_info_header { __u8 type; __u8 pad; __u16 len; }; struct fanotify_response_info_audit_rule { struct fanotify_response_info_header hdr; __u32 rule_number; __u32 subj_trust; __u32 obj_trust; }; /* Legit userspace responses to a _PERM event */ #define FAN_ALLOW 0x01 #define FAN_DENY 0x02 #define FAN_AUDIT 0x10 /* Bitmask to create audit record for result */ #define FAN_INFO 0x20 /* Bitmask to indicate additional information */ /* No fd set in event */ #define FAN_NOFD -1 /* Helper functions to deal with fanotify_event_metadata buffers */ #define FAN_EVENT_METADATA_LEN (sizeof(struct fanotify_event_metadata)) #define FAN_EVENT_NEXT(meta, len) ((len) -= (meta)->event_len, \ (struct fanotify_event_metadata*)(((char *)(meta)) + \ (meta)->event_len)) #define FAN_EVENT_OK(meta, len) ((long)(len) >= (long)FAN_EVENT_METADATA_LEN && \ (long)(meta)->event_len >= (long)FAN_EVENT_METADATA_LEN && \ (long)(meta)->event_len <= (long)(len)) #endif /* _LINUX_FANOTIFY_H */ linux/openat2.h000064400000002411151027430560007425 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_OPENAT2_H #define _LINUX_OPENAT2_H #include /* * Arguments for how openat2(2) should open the target path. If only @flags and * @mode are non-zero, then openat2(2) operates very similarly to openat(2). * * However, unlike openat(2), unknown or invalid bits in @flags result in * -EINVAL rather than being silently ignored. @mode must be zero unless one of * {O_CREAT, O_TMPFILE} are set. * * @flags: O_* flags. * @mode: O_CREAT/O_TMPFILE file mode. * @resolve: RESOLVE_* flags. */ struct open_how { __u64 flags; __u64 mode; __u64 resolve; }; /* how->resolve flags for openat2(2). */ #define RESOLVE_NO_XDEV 0x01 /* Block mount-point crossings (includes bind-mounts). */ #define RESOLVE_NO_MAGICLINKS 0x02 /* Block traversal through procfs-style "magic-links". */ #define RESOLVE_NO_SYMLINKS 0x04 /* Block traversal through all symlinks (implies OEXT_NO_MAGICLINKS) */ #define RESOLVE_BENEATH 0x08 /* Block "lexical" trickery like "..", symlinks, and absolute paths which escape the dirfd. */ #define RESOLVE_IN_ROOT 0x10 /* Make all jumps to "/" and ".." be scoped inside the dirfd (similar to chroot(2)). */ #endif /* _LINUX_OPENAT2_H */ linux/netlink_diag.h000064400000002764151027430560010520 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __NETLINK_DIAG_H__ #define __NETLINK_DIAG_H__ #include struct netlink_diag_req { __u8 sdiag_family; __u8 sdiag_protocol; __u16 pad; __u32 ndiag_ino; __u32 ndiag_show; __u32 ndiag_cookie[2]; }; struct netlink_diag_msg { __u8 ndiag_family; __u8 ndiag_type; __u8 ndiag_protocol; __u8 ndiag_state; __u32 ndiag_portid; __u32 ndiag_dst_portid; __u32 ndiag_dst_group; __u32 ndiag_ino; __u32 ndiag_cookie[2]; }; struct netlink_diag_ring { __u32 ndr_block_size; __u32 ndr_block_nr; __u32 ndr_frame_size; __u32 ndr_frame_nr; }; enum { /* NETLINK_DIAG_NONE, standard nl API requires this attribute! */ NETLINK_DIAG_MEMINFO, NETLINK_DIAG_GROUPS, NETLINK_DIAG_RX_RING, NETLINK_DIAG_TX_RING, NETLINK_DIAG_FLAGS, __NETLINK_DIAG_MAX, }; #define NETLINK_DIAG_MAX (__NETLINK_DIAG_MAX - 1) #define NDIAG_PROTO_ALL ((__u8) ~0) #define NDIAG_SHOW_MEMINFO 0x00000001 /* show memory info of a socket */ #define NDIAG_SHOW_GROUPS 0x00000002 /* show groups of a netlink socket */ /* deprecated since 4.6 */ #define NDIAG_SHOW_RING_CFG 0x00000004 /* show ring configuration */ #define NDIAG_SHOW_FLAGS 0x00000008 /* show flags of a netlink socket */ /* flags */ #define NDIAG_FLAG_CB_RUNNING 0x00000001 #define NDIAG_FLAG_PKTINFO 0x00000002 #define NDIAG_FLAG_BROADCAST_ERROR 0x00000004 #define NDIAG_FLAG_NO_ENOBUFS 0x00000008 #define NDIAG_FLAG_LISTEN_ALL_NSID 0x00000010 #define NDIAG_FLAG_CAP_ACK 0x00000020 #endif linux/fadvise.h000064400000001512151027430560007477 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef FADVISE_H_INCLUDED #define FADVISE_H_INCLUDED #define POSIX_FADV_NORMAL 0 /* No further special treatment. */ #define POSIX_FADV_RANDOM 1 /* Expect random page references. */ #define POSIX_FADV_SEQUENTIAL 2 /* Expect sequential page references. */ #define POSIX_FADV_WILLNEED 3 /* Will need these pages. */ /* * The advise values for POSIX_FADV_DONTNEED and POSIX_ADV_NOREUSE * for s390-64 differ from the values for the rest of the world. */ #if defined(__s390x__) #define POSIX_FADV_DONTNEED 6 /* Don't need these pages. */ #define POSIX_FADV_NOREUSE 7 /* Data will be accessed once. */ #else #define POSIX_FADV_DONTNEED 4 /* Don't need these pages. */ #define POSIX_FADV_NOREUSE 5 /* Data will be accessed once. */ #endif #endif /* FADVISE_H_INCLUDED */ linux/agpgart.h000064400000007544151027430560007516 0ustar00/* * AGPGART module version 0.99 * Copyright (C) 1999 Jeff Hartmann * Copyright (C) 1999 Precision Insight, Inc. * Copyright (C) 1999 Xi Graphics, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * JEFF HARTMANN, OR ANY OTHER CONTRIBUTORS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef _AGP_H #define _AGP_H #define AGPIOC_BASE 'A' #define AGPIOC_INFO _IOR (AGPIOC_BASE, 0, struct agp_info*) #define AGPIOC_ACQUIRE _IO (AGPIOC_BASE, 1) #define AGPIOC_RELEASE _IO (AGPIOC_BASE, 2) #define AGPIOC_SETUP _IOW (AGPIOC_BASE, 3, struct agp_setup*) #define AGPIOC_RESERVE _IOW (AGPIOC_BASE, 4, struct agp_region*) #define AGPIOC_PROTECT _IOW (AGPIOC_BASE, 5, struct agp_region*) #define AGPIOC_ALLOCATE _IOWR(AGPIOC_BASE, 6, struct agp_allocate*) #define AGPIOC_DEALLOCATE _IOW (AGPIOC_BASE, 7, int) #define AGPIOC_BIND _IOW (AGPIOC_BASE, 8, struct agp_bind*) #define AGPIOC_UNBIND _IOW (AGPIOC_BASE, 9, struct agp_unbind*) #define AGPIOC_CHIPSET_FLUSH _IO (AGPIOC_BASE, 10) #define AGP_DEVICE "/dev/agpgart" #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #include #include struct agp_version { __u16 major; __u16 minor; }; typedef struct _agp_info { struct agp_version version; /* version of the driver */ __u32 bridge_id; /* bridge vendor/device */ __u32 agp_mode; /* mode info of bridge */ unsigned long aper_base;/* base of aperture */ size_t aper_size; /* size of aperture */ size_t pg_total; /* max pages (swap + system) */ size_t pg_system; /* max pages (system) */ size_t pg_used; /* current pages used */ } agp_info; typedef struct _agp_setup { __u32 agp_mode; /* mode info of bridge */ } agp_setup; /* * The "prot" down below needs still a "sleep" flag somehow ... */ typedef struct _agp_segment { __kernel_off_t pg_start; /* starting page to populate */ __kernel_size_t pg_count; /* number of pages */ int prot; /* prot flags for mmap */ } agp_segment; typedef struct _agp_region { __kernel_pid_t pid; /* pid of process */ __kernel_size_t seg_count; /* number of segments */ struct _agp_segment *seg_list; } agp_region; typedef struct _agp_allocate { int key; /* tag of allocation */ __kernel_size_t pg_count;/* number of pages */ __u32 type; /* 0 == normal, other devspec */ __u32 physical; /* device specific (some devices * need a phys address of the * actual page behind the gatt * table) */ } agp_allocate; typedef struct _agp_bind { int key; /* tag of allocation */ __kernel_off_t pg_start;/* starting page to populate */ } agp_bind; typedef struct _agp_unbind { int key; /* tag of allocation */ __u32 priority; /* priority for paging out */ } agp_unbind; #endif /* _AGP_H */ linux/fs.h000064400000032160151027430560006471 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FS_H #define _LINUX_FS_H /* * This file has definitions for some important file table structures * and constants and structures used by various generic file system * ioctl's. Please do not make any changes in this file before * sending patches for review to linux-fsdevel@vger.kernel.org and * linux-api@vger.kernel.org. */ #include #include #include /* Use of MS_* flags within the kernel is restricted to core mount(2) code. */ #include /* * It's silly to have NR_OPEN bigger than NR_FILE, but you can change * the file limit at runtime and only root can increase the per-process * nr_file rlimit, so it's safe to set up a ridiculously high absolute * upper limit on files-per-process. * * Some programs (notably those using select()) may have to be * recompiled to take full advantage of the new limits.. */ /* Fixed constants first: */ #undef NR_OPEN #define INR_OPEN_CUR 1024 /* Initial setting for nfile rlimits */ #define INR_OPEN_MAX 4096 /* Hard limit for nfile rlimits */ #define BLOCK_SIZE_BITS 10 #define BLOCK_SIZE (1< */ #ifndef _LINUX_L2TP_H_ #define _LINUX_L2TP_H_ #include #include #include #include /** * struct sockaddr_l2tpip - the sockaddr structure for L2TP-over-IP sockets * @l2tp_family: address family number AF_L2TPIP. * @l2tp_addr: protocol specific address information * @l2tp_conn_id: connection id of tunnel */ #define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */ struct sockaddr_l2tpip { /* The first fields must match struct sockaddr_in */ __kernel_sa_family_t l2tp_family; /* AF_INET */ __be16 l2tp_unused; /* INET port number (unused) */ struct in_addr l2tp_addr; /* Internet address */ __u32 l2tp_conn_id; /* Connection ID of tunnel */ /* Pad to size of `struct sockaddr'. */ unsigned char __pad[__SOCK_SIZE__ - sizeof(__kernel_sa_family_t) - sizeof(__be16) - sizeof(struct in_addr) - sizeof(__u32)]; }; /** * struct sockaddr_l2tpip6 - the sockaddr structure for L2TP-over-IPv6 sockets * @l2tp_family: address family number AF_L2TPIP. * @l2tp_addr: protocol specific address information * @l2tp_conn_id: connection id of tunnel */ struct sockaddr_l2tpip6 { /* The first fields must match struct sockaddr_in6 */ __kernel_sa_family_t l2tp_family; /* AF_INET6 */ __be16 l2tp_unused; /* INET port number (unused) */ __be32 l2tp_flowinfo; /* IPv6 flow information */ struct in6_addr l2tp_addr; /* IPv6 address */ __u32 l2tp_scope_id; /* scope id (new in RFC2553) */ __u32 l2tp_conn_id; /* Connection ID of tunnel */ }; /***************************************************************************** * NETLINK_GENERIC netlink family. *****************************************************************************/ /* * Commands. * Valid TLVs of each command are:- * TUNNEL_CREATE - CONN_ID, pw_type, netns, ifname, ipinfo, udpinfo, udpcsum, vlanid * TUNNEL_DELETE - CONN_ID * TUNNEL_MODIFY - CONN_ID, udpcsum * TUNNEL_GETSTATS - CONN_ID, (stats) * TUNNEL_GET - CONN_ID, (...) * SESSION_CREATE - SESSION_ID, PW_TYPE, data_seq, cookie, peer_cookie, l2spec * SESSION_DELETE - SESSION_ID * SESSION_MODIFY - SESSION_ID, data_seq * SESSION_GET - SESSION_ID, (...) * SESSION_GETSTATS - SESSION_ID, (stats) * */ enum { L2TP_CMD_NOOP, L2TP_CMD_TUNNEL_CREATE, L2TP_CMD_TUNNEL_DELETE, L2TP_CMD_TUNNEL_MODIFY, L2TP_CMD_TUNNEL_GET, L2TP_CMD_SESSION_CREATE, L2TP_CMD_SESSION_DELETE, L2TP_CMD_SESSION_MODIFY, L2TP_CMD_SESSION_GET, __L2TP_CMD_MAX, }; #define L2TP_CMD_MAX (__L2TP_CMD_MAX - 1) /* * ATTR types defined for L2TP */ enum { L2TP_ATTR_NONE, /* no data */ L2TP_ATTR_PW_TYPE, /* u16, enum l2tp_pwtype */ L2TP_ATTR_ENCAP_TYPE, /* u16, enum l2tp_encap_type */ L2TP_ATTR_OFFSET, /* u16 (not used) */ L2TP_ATTR_DATA_SEQ, /* u16 */ L2TP_ATTR_L2SPEC_TYPE, /* u8, enum l2tp_l2spec_type */ L2TP_ATTR_L2SPEC_LEN, /* u8 (not used) */ L2TP_ATTR_PROTO_VERSION, /* u8 */ L2TP_ATTR_IFNAME, /* string */ L2TP_ATTR_CONN_ID, /* u32 */ L2TP_ATTR_PEER_CONN_ID, /* u32 */ L2TP_ATTR_SESSION_ID, /* u32 */ L2TP_ATTR_PEER_SESSION_ID, /* u32 */ L2TP_ATTR_UDP_CSUM, /* u8 */ L2TP_ATTR_VLAN_ID, /* u16 */ L2TP_ATTR_COOKIE, /* 0, 4 or 8 bytes */ L2TP_ATTR_PEER_COOKIE, /* 0, 4 or 8 bytes */ L2TP_ATTR_DEBUG, /* u32, enum l2tp_debug_flags */ L2TP_ATTR_RECV_SEQ, /* u8 */ L2TP_ATTR_SEND_SEQ, /* u8 */ L2TP_ATTR_LNS_MODE, /* u8 */ L2TP_ATTR_USING_IPSEC, /* u8 */ L2TP_ATTR_RECV_TIMEOUT, /* msec */ L2TP_ATTR_FD, /* int */ L2TP_ATTR_IP_SADDR, /* u32 */ L2TP_ATTR_IP_DADDR, /* u32 */ L2TP_ATTR_UDP_SPORT, /* u16 */ L2TP_ATTR_UDP_DPORT, /* u16 */ L2TP_ATTR_MTU, /* u16 */ L2TP_ATTR_MRU, /* u16 */ L2TP_ATTR_STATS, /* nested */ L2TP_ATTR_IP6_SADDR, /* struct in6_addr */ L2TP_ATTR_IP6_DADDR, /* struct in6_addr */ L2TP_ATTR_UDP_ZERO_CSUM6_TX, /* flag */ L2TP_ATTR_UDP_ZERO_CSUM6_RX, /* flag */ L2TP_ATTR_PAD, __L2TP_ATTR_MAX, }; #define L2TP_ATTR_MAX (__L2TP_ATTR_MAX - 1) /* Nested in L2TP_ATTR_STATS */ enum { L2TP_ATTR_STATS_NONE, /* no data */ L2TP_ATTR_TX_PACKETS, /* u64 */ L2TP_ATTR_TX_BYTES, /* u64 */ L2TP_ATTR_TX_ERRORS, /* u64 */ L2TP_ATTR_RX_PACKETS, /* u64 */ L2TP_ATTR_RX_BYTES, /* u64 */ L2TP_ATTR_RX_SEQ_DISCARDS, /* u64 */ L2TP_ATTR_RX_OOS_PACKETS, /* u64 */ L2TP_ATTR_RX_ERRORS, /* u64 */ L2TP_ATTR_STATS_PAD, __L2TP_ATTR_STATS_MAX, }; #define L2TP_ATTR_STATS_MAX (__L2TP_ATTR_STATS_MAX - 1) enum l2tp_pwtype { L2TP_PWTYPE_NONE = 0x0000, L2TP_PWTYPE_ETH_VLAN = 0x0004, L2TP_PWTYPE_ETH = 0x0005, L2TP_PWTYPE_PPP = 0x0007, L2TP_PWTYPE_PPP_AC = 0x0008, L2TP_PWTYPE_IP = 0x000b, __L2TP_PWTYPE_MAX }; enum l2tp_l2spec_type { L2TP_L2SPECTYPE_NONE, L2TP_L2SPECTYPE_DEFAULT, }; enum l2tp_encap_type { L2TP_ENCAPTYPE_UDP, L2TP_ENCAPTYPE_IP, }; enum l2tp_seqmode { L2TP_SEQ_NONE = 0, L2TP_SEQ_IP = 1, L2TP_SEQ_ALL = 2, }; /** * enum l2tp_debug_flags - debug message categories for L2TP tunnels/sessions * * @L2TP_MSG_DEBUG: verbose debug (if compiled in) * @L2TP_MSG_CONTROL: userspace - kernel interface * @L2TP_MSG_SEQ: sequence numbers * @L2TP_MSG_DATA: data packets */ enum l2tp_debug_flags { L2TP_MSG_DEBUG = (1 << 0), L2TP_MSG_CONTROL = (1 << 1), L2TP_MSG_SEQ = (1 << 2), L2TP_MSG_DATA = (1 << 3), }; /* * NETLINK_GENERIC related info */ #define L2TP_GENL_NAME "l2tp" #define L2TP_GENL_VERSION 0x1 #define L2TP_GENL_MCGROUP "l2tp" #endif /* _LINUX_L2TP_H_ */ linux/ipv6.h000064400000007577151027430560006763 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPV6_H #define _IPV6_H #include #include #include #include /* The latest drafts declared increase in minimal mtu up to 1280. */ #define IPV6_MIN_MTU 1280 /* * Advanced API * source interface/address selection, source routing, etc... * *under construction* */ #if __UAPI_DEF_IN6_PKTINFO struct in6_pktinfo { struct in6_addr ipi6_addr; int ipi6_ifindex; }; #endif #if __UAPI_DEF_IP6_MTUINFO struct ip6_mtuinfo { struct sockaddr_in6 ip6m_addr; __u32 ip6m_mtu; }; #endif struct in6_ifreq { struct in6_addr ifr6_addr; __u32 ifr6_prefixlen; int ifr6_ifindex; }; #define IPV6_SRCRT_STRICT 0x01 /* Deprecated; will be removed */ #define IPV6_SRCRT_TYPE_0 0 /* Deprecated; will be removed */ #define IPV6_SRCRT_TYPE_2 2 /* IPv6 type 2 Routing Header */ #define IPV6_SRCRT_TYPE_4 4 /* Segment Routing with IPv6 */ /* * routing header */ struct ipv6_rt_hdr { __u8 nexthdr; __u8 hdrlen; __u8 type; __u8 segments_left; /* * type specific data * variable length field */ }; struct ipv6_opt_hdr { __u8 nexthdr; __u8 hdrlen; /* * TLV encoded option data follows. */ } __attribute__((packed)); /* required for some archs */ #define ipv6_destopt_hdr ipv6_opt_hdr #define ipv6_hopopt_hdr ipv6_opt_hdr /* Router Alert option values (RFC2711) */ #define IPV6_OPT_ROUTERALERT_MLD 0x0000 /* MLD(RFC2710) */ /* * routing header type 0 (used in cmsghdr struct) */ struct rt0_hdr { struct ipv6_rt_hdr rt_hdr; __u32 reserved; struct in6_addr addr[0]; #define rt0_type rt_hdr.type }; /* * routing header type 2 */ struct rt2_hdr { struct ipv6_rt_hdr rt_hdr; __u32 reserved; struct in6_addr addr; #define rt2_type rt_hdr.type }; /* * home address option in destination options header */ struct ipv6_destopt_hao { __u8 type; __u8 length; struct in6_addr addr; } __attribute__((packed)); /* * IPv6 fixed header * * BEWARE, it is incorrect. The first 4 bits of flow_lbl * are glued to priority now, forming "class". */ struct ipv6hdr { #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 priority:4, version:4; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 version:4, priority:4; #else #error "Please fix " #endif __u8 flow_lbl[3]; __be16 payload_len; __u8 nexthdr; __u8 hop_limit; struct in6_addr saddr; struct in6_addr daddr; }; /* index values for the variables in ipv6_devconf */ enum { DEVCONF_FORWARDING = 0, DEVCONF_HOPLIMIT, DEVCONF_MTU6, DEVCONF_ACCEPT_RA, DEVCONF_ACCEPT_REDIRECTS, DEVCONF_AUTOCONF, DEVCONF_DAD_TRANSMITS, DEVCONF_RTR_SOLICITS, DEVCONF_RTR_SOLICIT_INTERVAL, DEVCONF_RTR_SOLICIT_DELAY, DEVCONF_USE_TEMPADDR, DEVCONF_TEMP_VALID_LFT, DEVCONF_TEMP_PREFERED_LFT, DEVCONF_REGEN_MAX_RETRY, DEVCONF_MAX_DESYNC_FACTOR, DEVCONF_MAX_ADDRESSES, DEVCONF_FORCE_MLD_VERSION, DEVCONF_ACCEPT_RA_DEFRTR, DEVCONF_ACCEPT_RA_PINFO, DEVCONF_ACCEPT_RA_RTR_PREF, DEVCONF_RTR_PROBE_INTERVAL, DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN, DEVCONF_PROXY_NDP, DEVCONF_OPTIMISTIC_DAD, DEVCONF_ACCEPT_SOURCE_ROUTE, DEVCONF_MC_FORWARDING, DEVCONF_DISABLE_IPV6, DEVCONF_ACCEPT_DAD, DEVCONF_FORCE_TLLAO, DEVCONF_NDISC_NOTIFY, DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL, DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL, DEVCONF_SUPPRESS_FRAG_NDISC, DEVCONF_ACCEPT_RA_FROM_LOCAL, DEVCONF_USE_OPTIMISTIC, DEVCONF_ACCEPT_RA_MTU, DEVCONF_STABLE_SECRET, DEVCONF_USE_OIF_ADDRS_ONLY, DEVCONF_ACCEPT_RA_MIN_HOP_LIMIT, DEVCONF_IGNORE_ROUTES_WITH_LINKDOWN, DEVCONF_DROP_UNICAST_IN_L2_MULTICAST, DEVCONF_DROP_UNSOLICITED_NA, DEVCONF_KEEP_ADDR_ON_DOWN, DEVCONF_RTR_SOLICIT_MAX_INTERVAL, DEVCONF_SEG6_ENABLED, DEVCONF_SEG6_REQUIRE_HMAC, DEVCONF_ENHANCED_DAD, DEVCONF_ADDR_GEN_MODE, DEVCONF_DISABLE_POLICY, DEVCONF_ACCEPT_RA_RT_INFO_MIN_PLEN, DEVCONF_NDISC_TCLASS, DEVCONF_MAX }; #endif /* _IPV6_H */ linux/unix_diag.h000064400000002345151027430560010032 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UNIX_DIAG_H__ #define __UNIX_DIAG_H__ #include struct unix_diag_req { __u8 sdiag_family; __u8 sdiag_protocol; __u16 pad; __u32 udiag_states; __u32 udiag_ino; __u32 udiag_show; __u32 udiag_cookie[2]; }; #define UDIAG_SHOW_NAME 0x00000001 /* show name (not path) */ #define UDIAG_SHOW_VFS 0x00000002 /* show VFS inode info */ #define UDIAG_SHOW_PEER 0x00000004 /* show peer socket info */ #define UDIAG_SHOW_ICONS 0x00000008 /* show pending connections */ #define UDIAG_SHOW_RQLEN 0x00000010 /* show skb receive queue len */ #define UDIAG_SHOW_MEMINFO 0x00000020 /* show memory info of a socket */ struct unix_diag_msg { __u8 udiag_family; __u8 udiag_type; __u8 udiag_state; __u8 pad; __u32 udiag_ino; __u32 udiag_cookie[2]; }; enum { /* UNIX_DIAG_NONE, standard nl API requires this attribute! */ UNIX_DIAG_NAME, UNIX_DIAG_VFS, UNIX_DIAG_PEER, UNIX_DIAG_ICONS, UNIX_DIAG_RQLEN, UNIX_DIAG_MEMINFO, UNIX_DIAG_SHUTDOWN, __UNIX_DIAG_MAX, }; #define UNIX_DIAG_MAX (__UNIX_DIAG_MAX - 1) struct unix_diag_vfs { __u32 udiag_vfs_ino; __u32 udiag_vfs_dev; }; struct unix_diag_rqlen { __u32 udiag_rqueue; __u32 udiag_wqueue; }; #endif linux/patchkey.h000064400000001574151027430560007676 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * -- definition of _PATCHKEY macro * * Copyright (C) 2005 Stuart Brady * * This exists because awe_voice.h defined its own _PATCHKEY and it wasn't * clear whether removing this would break anything in userspace. * * Do not include this file directly. Please use instead. * For kernel code, use */ #ifndef _LINUX_PATCHKEY_H_INDIRECT #error "patchkey.h included directly" #endif #ifndef _LINUX_PATCHKEY_H #define _LINUX_PATCHKEY_H /* Endian macros. */ # include #if defined(__BYTE_ORDER) # if __BYTE_ORDER == __BIG_ENDIAN # define _PATCHKEY(id) (0xfd00|id) # elif __BYTE_ORDER == __LITTLE_ENDIAN # define _PATCHKEY(id) ((id<<8)|0x00fd) # else # error "could not determine byte order" # endif #endif #endif /* _LINUX_PATCHKEY_H */ linux/virtio_gpu.h000064400000026276151027430560010263 0ustar00/* * Virtio GPU Device * * Copyright Red Hat, Inc. 2013-2014 * * Authors: * Dave Airlie * Gerd Hoffmann * * This header is BSD licensed so anyone can use the definitions * to implement compatible drivers/servers: * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IBM OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef VIRTIO_GPU_HW_H #define VIRTIO_GPU_HW_H #include /* * VIRTIO_GPU_CMD_CTX_* * VIRTIO_GPU_CMD_*_3D */ #define VIRTIO_GPU_F_VIRGL 0 /* * VIRTIO_GPU_CMD_GET_EDID */ #define VIRTIO_GPU_F_EDID 1 /* * VIRTIO_GPU_CMD_RESOURCE_ASSIGN_UUID */ #define VIRTIO_GPU_F_RESOURCE_UUID 2 /* * VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB */ #define VIRTIO_GPU_F_RESOURCE_BLOB 3 /* * VIRTIO_GPU_CMD_CREATE_CONTEXT with * context_init and multiple timelines */ #define VIRTIO_GPU_F_CONTEXT_INIT 4 enum virtio_gpu_ctrl_type { VIRTIO_GPU_UNDEFINED = 0, /* 2d commands */ VIRTIO_GPU_CMD_GET_DISPLAY_INFO = 0x0100, VIRTIO_GPU_CMD_RESOURCE_CREATE_2D, VIRTIO_GPU_CMD_RESOURCE_UNREF, VIRTIO_GPU_CMD_SET_SCANOUT, VIRTIO_GPU_CMD_RESOURCE_FLUSH, VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D, VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING, VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING, VIRTIO_GPU_CMD_GET_CAPSET_INFO, VIRTIO_GPU_CMD_GET_CAPSET, VIRTIO_GPU_CMD_GET_EDID, VIRTIO_GPU_CMD_RESOURCE_ASSIGN_UUID, VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB, VIRTIO_GPU_CMD_SET_SCANOUT_BLOB, /* 3d commands */ VIRTIO_GPU_CMD_CTX_CREATE = 0x0200, VIRTIO_GPU_CMD_CTX_DESTROY, VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE, VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE, VIRTIO_GPU_CMD_RESOURCE_CREATE_3D, VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D, VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D, VIRTIO_GPU_CMD_SUBMIT_3D, VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB, VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB, /* cursor commands */ VIRTIO_GPU_CMD_UPDATE_CURSOR = 0x0300, VIRTIO_GPU_CMD_MOVE_CURSOR, /* success responses */ VIRTIO_GPU_RESP_OK_NODATA = 0x1100, VIRTIO_GPU_RESP_OK_DISPLAY_INFO, VIRTIO_GPU_RESP_OK_CAPSET_INFO, VIRTIO_GPU_RESP_OK_CAPSET, VIRTIO_GPU_RESP_OK_EDID, VIRTIO_GPU_RESP_OK_RESOURCE_UUID, VIRTIO_GPU_RESP_OK_MAP_INFO, /* error responses */ VIRTIO_GPU_RESP_ERR_UNSPEC = 0x1200, VIRTIO_GPU_RESP_ERR_OUT_OF_MEMORY, VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID, VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID, VIRTIO_GPU_RESP_ERR_INVALID_CONTEXT_ID, VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER, }; enum virtio_gpu_shm_id { VIRTIO_GPU_SHM_ID_UNDEFINED = 0, /* * VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB * VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB */ VIRTIO_GPU_SHM_ID_HOST_VISIBLE = 1 }; #define VIRTIO_GPU_FLAG_FENCE (1 << 0) /* * If the following flag is set, then ring_idx contains the index * of the command ring that needs to used when creating the fence */ #define VIRTIO_GPU_FLAG_INFO_RING_IDX (1 << 1) struct virtio_gpu_ctrl_hdr { __le32 type; __le32 flags; __le64 fence_id; __le32 ctx_id; __u8 ring_idx; __u8 padding[3]; }; /* data passed in the cursor vq */ struct virtio_gpu_cursor_pos { __le32 scanout_id; __le32 x; __le32 y; __le32 padding; }; /* VIRTIO_GPU_CMD_UPDATE_CURSOR, VIRTIO_GPU_CMD_MOVE_CURSOR */ struct virtio_gpu_update_cursor { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_cursor_pos pos; /* update & move */ __le32 resource_id; /* update only */ __le32 hot_x; /* update only */ __le32 hot_y; /* update only */ __le32 padding; }; /* data passed in the control vq, 2d related */ struct virtio_gpu_rect { __le32 x; __le32 y; __le32 width; __le32 height; }; /* VIRTIO_GPU_CMD_RESOURCE_UNREF */ struct virtio_gpu_resource_unref { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 padding; }; /* VIRTIO_GPU_CMD_RESOURCE_CREATE_2D: create a 2d resource with a format */ struct virtio_gpu_resource_create_2d { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 format; __le32 width; __le32 height; }; /* VIRTIO_GPU_CMD_SET_SCANOUT */ struct virtio_gpu_set_scanout { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_rect r; __le32 scanout_id; __le32 resource_id; }; /* VIRTIO_GPU_CMD_RESOURCE_FLUSH */ struct virtio_gpu_resource_flush { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_rect r; __le32 resource_id; __le32 padding; }; /* VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D: simple transfer to_host */ struct virtio_gpu_transfer_to_host_2d { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_rect r; __le64 offset; __le32 resource_id; __le32 padding; }; struct virtio_gpu_mem_entry { __le64 addr; __le32 length; __le32 padding; }; /* VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING */ struct virtio_gpu_resource_attach_backing { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 nr_entries; }; /* VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING */ struct virtio_gpu_resource_detach_backing { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 padding; }; /* VIRTIO_GPU_RESP_OK_DISPLAY_INFO */ #define VIRTIO_GPU_MAX_SCANOUTS 16 struct virtio_gpu_resp_display_info { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_display_one { struct virtio_gpu_rect r; __le32 enabled; __le32 flags; } pmodes[VIRTIO_GPU_MAX_SCANOUTS]; }; /* data passed in the control vq, 3d related */ struct virtio_gpu_box { __le32 x, y, z; __le32 w, h, d; }; /* VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D, VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D */ struct virtio_gpu_transfer_host_3d { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_box box; __le64 offset; __le32 resource_id; __le32 level; __le32 stride; __le32 layer_stride; }; /* VIRTIO_GPU_CMD_RESOURCE_CREATE_3D */ #define VIRTIO_GPU_RESOURCE_FLAG_Y_0_TOP (1 << 0) struct virtio_gpu_resource_create_3d { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 target; __le32 format; __le32 bind; __le32 width; __le32 height; __le32 depth; __le32 array_size; __le32 last_level; __le32 nr_samples; __le32 flags; __le32 padding; }; /* VIRTIO_GPU_CMD_CTX_CREATE */ #define VIRTIO_GPU_CONTEXT_INIT_CAPSET_ID_MASK 0x000000ff struct virtio_gpu_ctx_create { struct virtio_gpu_ctrl_hdr hdr; __le32 nlen; __le32 context_init; char debug_name[64]; }; /* VIRTIO_GPU_CMD_CTX_DESTROY */ struct virtio_gpu_ctx_destroy { struct virtio_gpu_ctrl_hdr hdr; }; /* VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE, VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE */ struct virtio_gpu_ctx_resource { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 padding; }; /* VIRTIO_GPU_CMD_SUBMIT_3D */ struct virtio_gpu_cmd_submit { struct virtio_gpu_ctrl_hdr hdr; __le32 size; __le32 padding; }; #define VIRTIO_GPU_CAPSET_VIRGL 1 #define VIRTIO_GPU_CAPSET_VIRGL2 2 /* VIRTIO_GPU_CMD_GET_CAPSET_INFO */ struct virtio_gpu_get_capset_info { struct virtio_gpu_ctrl_hdr hdr; __le32 capset_index; __le32 padding; }; /* VIRTIO_GPU_RESP_OK_CAPSET_INFO */ struct virtio_gpu_resp_capset_info { struct virtio_gpu_ctrl_hdr hdr; __le32 capset_id; __le32 capset_max_version; __le32 capset_max_size; __le32 padding; }; /* VIRTIO_GPU_CMD_GET_CAPSET */ struct virtio_gpu_get_capset { struct virtio_gpu_ctrl_hdr hdr; __le32 capset_id; __le32 capset_version; }; /* VIRTIO_GPU_RESP_OK_CAPSET */ struct virtio_gpu_resp_capset { struct virtio_gpu_ctrl_hdr hdr; __u8 capset_data[]; }; /* VIRTIO_GPU_CMD_GET_EDID */ struct virtio_gpu_cmd_get_edid { struct virtio_gpu_ctrl_hdr hdr; __le32 scanout; __le32 padding; }; /* VIRTIO_GPU_RESP_OK_EDID */ struct virtio_gpu_resp_edid { struct virtio_gpu_ctrl_hdr hdr; __le32 size; __le32 padding; __u8 edid[1024]; }; #define VIRTIO_GPU_EVENT_DISPLAY (1 << 0) struct virtio_gpu_config { __le32 events_read; __le32 events_clear; __le32 num_scanouts; __le32 num_capsets; }; /* simple formats for fbcon/X use */ enum virtio_gpu_formats { VIRTIO_GPU_FORMAT_B8G8R8A8_UNORM = 1, VIRTIO_GPU_FORMAT_B8G8R8X8_UNORM = 2, VIRTIO_GPU_FORMAT_A8R8G8B8_UNORM = 3, VIRTIO_GPU_FORMAT_X8R8G8B8_UNORM = 4, VIRTIO_GPU_FORMAT_R8G8B8A8_UNORM = 67, VIRTIO_GPU_FORMAT_X8B8G8R8_UNORM = 68, VIRTIO_GPU_FORMAT_A8B8G8R8_UNORM = 121, VIRTIO_GPU_FORMAT_R8G8B8X8_UNORM = 134, }; /* VIRTIO_GPU_CMD_RESOURCE_ASSIGN_UUID */ struct virtio_gpu_resource_assign_uuid { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 padding; }; /* VIRTIO_GPU_RESP_OK_RESOURCE_UUID */ struct virtio_gpu_resp_resource_uuid { struct virtio_gpu_ctrl_hdr hdr; __u8 uuid[16]; }; /* VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB */ struct virtio_gpu_resource_create_blob { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; #define VIRTIO_GPU_BLOB_MEM_GUEST 0x0001 #define VIRTIO_GPU_BLOB_MEM_HOST3D 0x0002 #define VIRTIO_GPU_BLOB_MEM_HOST3D_GUEST 0x0003 #define VIRTIO_GPU_BLOB_FLAG_USE_MAPPABLE 0x0001 #define VIRTIO_GPU_BLOB_FLAG_USE_SHAREABLE 0x0002 #define VIRTIO_GPU_BLOB_FLAG_USE_CROSS_DEVICE 0x0004 /* zero is invalid blob mem */ __le32 blob_mem; __le32 blob_flags; __le32 nr_entries; __le64 blob_id; __le64 size; /* * sizeof(nr_entries * virtio_gpu_mem_entry) bytes follow */ }; /* VIRTIO_GPU_CMD_SET_SCANOUT_BLOB */ struct virtio_gpu_set_scanout_blob { struct virtio_gpu_ctrl_hdr hdr; struct virtio_gpu_rect r; __le32 scanout_id; __le32 resource_id; __le32 width; __le32 height; __le32 format; __le32 padding; __le32 strides[4]; __le32 offsets[4]; }; /* VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB */ struct virtio_gpu_resource_map_blob { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 padding; __le64 offset; }; /* VIRTIO_GPU_RESP_OK_MAP_INFO */ #define VIRTIO_GPU_MAP_CACHE_MASK 0x0f #define VIRTIO_GPU_MAP_CACHE_NONE 0x00 #define VIRTIO_GPU_MAP_CACHE_CACHED 0x01 #define VIRTIO_GPU_MAP_CACHE_UNCACHED 0x02 #define VIRTIO_GPU_MAP_CACHE_WC 0x03 struct virtio_gpu_resp_map_info { struct virtio_gpu_ctrl_hdr hdr; __u32 map_info; __u32 padding; }; /* VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB */ struct virtio_gpu_resource_unmap_blob { struct virtio_gpu_ctrl_hdr hdr; __le32 resource_id; __le32 padding; }; #endif linux/arcfb.h000064400000000325151027430560007134 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_ARCFB_H__ #define __LINUX_ARCFB_H__ #define FBIO_WAITEVENT _IO('F', 0x88) #define FBIO_GETCONTROL2 _IOR('F', 0x89, size_t) #endif linux/android/binder.h000064400000032567151027430560010757 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2008 Google, Inc. * * Based on, but no longer compatible with, the original * OpenBinder.org binder driver interface, which is: * * Copyright (c) 2005 Palmsource, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef _LINUX_BINDER_H #define _LINUX_BINDER_H #include #include #define B_PACK_CHARS(c1, c2, c3, c4) \ ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4)) #define B_TYPE_LARGE 0x85 enum { BINDER_TYPE_BINDER = B_PACK_CHARS('s', 'b', '*', B_TYPE_LARGE), BINDER_TYPE_WEAK_BINDER = B_PACK_CHARS('w', 'b', '*', B_TYPE_LARGE), BINDER_TYPE_HANDLE = B_PACK_CHARS('s', 'h', '*', B_TYPE_LARGE), BINDER_TYPE_WEAK_HANDLE = B_PACK_CHARS('w', 'h', '*', B_TYPE_LARGE), BINDER_TYPE_FD = B_PACK_CHARS('f', 'd', '*', B_TYPE_LARGE), BINDER_TYPE_FDA = B_PACK_CHARS('f', 'd', 'a', B_TYPE_LARGE), BINDER_TYPE_PTR = B_PACK_CHARS('p', 't', '*', B_TYPE_LARGE), }; enum { FLAT_BINDER_FLAG_PRIORITY_MASK = 0xff, FLAT_BINDER_FLAG_ACCEPTS_FDS = 0x100, }; #ifdef BINDER_IPC_32BIT typedef __u32 binder_size_t; typedef __u32 binder_uintptr_t; #else typedef __u64 binder_size_t; typedef __u64 binder_uintptr_t; #endif /** * struct binder_object_header - header shared by all binder metadata objects. * @type: type of the object */ struct binder_object_header { __u32 type; }; /* * This is the flattened representation of a Binder object for transfer * between processes. The 'offsets' supplied as part of a binder transaction * contains offsets into the data where these structures occur. The Binder * driver takes care of re-writing the structure type and data as it moves * between processes. */ struct flat_binder_object { struct binder_object_header hdr; __u32 flags; /* 8 bytes of data. */ union { binder_uintptr_t binder; /* local object */ __u32 handle; /* remote object */ }; /* extra data associated with local object */ binder_uintptr_t cookie; }; /** * struct binder_fd_object - describes a filedescriptor to be fixed up. * @hdr: common header structure * @pad_flags: padding to remain compatible with old userspace code * @pad_binder: padding to remain compatible with old userspace code * @fd: file descriptor * @cookie: opaque data, used by user-space */ struct binder_fd_object { struct binder_object_header hdr; __u32 pad_flags; union { binder_uintptr_t pad_binder; __u32 fd; }; binder_uintptr_t cookie; }; /* struct binder_buffer_object - object describing a userspace buffer * @hdr: common header structure * @flags: one or more BINDER_BUFFER_* flags * @buffer: address of the buffer * @length: length of the buffer * @parent: index in offset array pointing to parent buffer * @parent_offset: offset in @parent pointing to this buffer * * A binder_buffer object represents an object that the * binder kernel driver can copy verbatim to the target * address space. A buffer itself may be pointed to from * within another buffer, meaning that the pointer inside * that other buffer needs to be fixed up as well. This * can be done by setting the BINDER_BUFFER_FLAG_HAS_PARENT * flag in @flags, by setting @parent buffer to the index * in the offset array pointing to the parent binder_buffer_object, * and by setting @parent_offset to the offset in the parent buffer * at which the pointer to this buffer is located. */ struct binder_buffer_object { struct binder_object_header hdr; __u32 flags; binder_uintptr_t buffer; binder_size_t length; binder_size_t parent; binder_size_t parent_offset; }; enum { BINDER_BUFFER_FLAG_HAS_PARENT = 0x01, }; /* struct binder_fd_array_object - object describing an array of fds in a buffer * @hdr: common header structure * @pad: padding to ensure correct alignment * @num_fds: number of file descriptors in the buffer * @parent: index in offset array to buffer holding the fd array * @parent_offset: start offset of fd array in the buffer * * A binder_fd_array object represents an array of file * descriptors embedded in a binder_buffer_object. It is * different from a regular binder_buffer_object because it * describes a list of file descriptors to fix up, not an opaque * blob of memory, and hence the kernel needs to treat it differently. * * An example of how this would be used is with Android's * native_handle_t object, which is a struct with a list of integers * and a list of file descriptors. The native_handle_t struct itself * will be represented by a struct binder_buffer_objct, whereas the * embedded list of file descriptors is represented by a * struct binder_fd_array_object with that binder_buffer_object as * a parent. */ struct binder_fd_array_object { struct binder_object_header hdr; __u32 pad; binder_size_t num_fds; binder_size_t parent; binder_size_t parent_offset; }; /* * On 64-bit platforms where user code may run in 32-bits the driver must * translate the buffer (and local binder) addresses appropriately. */ struct binder_write_read { binder_size_t write_size; /* bytes to write */ binder_size_t write_consumed; /* bytes consumed by driver */ binder_uintptr_t write_buffer; binder_size_t read_size; /* bytes to read */ binder_size_t read_consumed; /* bytes consumed by driver */ binder_uintptr_t read_buffer; }; /* Use with BINDER_VERSION, driver fills in fields. */ struct binder_version { /* driver protocol version -- increment with incompatible change */ __s32 protocol_version; }; /* This is the current protocol version. */ #ifdef BINDER_IPC_32BIT #define BINDER_CURRENT_PROTOCOL_VERSION 7 #else #define BINDER_CURRENT_PROTOCOL_VERSION 8 #endif /* * Use with BINDER_GET_NODE_DEBUG_INFO, driver reads ptr, writes to all fields. * Set ptr to NULL for the first call to get the info for the first node, and * then repeat the call passing the previously returned value to get the next * nodes. ptr will be 0 when there are no more nodes. */ struct binder_node_debug_info { binder_uintptr_t ptr; binder_uintptr_t cookie; __u32 has_strong_ref; __u32 has_weak_ref; }; #define BINDER_WRITE_READ _IOWR('b', 1, struct binder_write_read) #define BINDER_SET_IDLE_TIMEOUT _IOW('b', 3, __s64) #define BINDER_SET_MAX_THREADS _IOW('b', 5, __u32) #define BINDER_SET_IDLE_PRIORITY _IOW('b', 6, __s32) #define BINDER_SET_CONTEXT_MGR _IOW('b', 7, __s32) #define BINDER_THREAD_EXIT _IOW('b', 8, __s32) #define BINDER_VERSION _IOWR('b', 9, struct binder_version) #define BINDER_GET_NODE_DEBUG_INFO _IOWR('b', 11, struct binder_node_debug_info) /* * NOTE: Two special error codes you should check for when calling * in to the driver are: * * EINTR -- The operation has been interupted. This should be * handled by retrying the ioctl() until a different error code * is returned. * * ECONNREFUSED -- The driver is no longer accepting operations * from your process. That is, the process is being destroyed. * You should handle this by exiting from your process. Note * that once this error code is returned, all further calls to * the driver from any thread will return this same code. */ enum transaction_flags { TF_ONE_WAY = 0x01, /* this is a one-way call: async, no return */ TF_ROOT_OBJECT = 0x04, /* contents are the component's root object */ TF_STATUS_CODE = 0x08, /* contents are a 32-bit status code */ TF_ACCEPT_FDS = 0x10, /* allow replies with file descriptors */ }; struct binder_transaction_data { /* The first two are only used for bcTRANSACTION and brTRANSACTION, * identifying the target and contents of the transaction. */ union { /* target descriptor of command transaction */ __u32 handle; /* target descriptor of return transaction */ binder_uintptr_t ptr; } target; binder_uintptr_t cookie; /* target object cookie */ __u32 code; /* transaction command */ /* General information about the transaction. */ __u32 flags; pid_t sender_pid; uid_t sender_euid; binder_size_t data_size; /* number of bytes of data */ binder_size_t offsets_size; /* number of bytes of offsets */ /* If this transaction is inline, the data immediately * follows here; otherwise, it ends with a pointer to * the data buffer. */ union { struct { /* transaction data */ binder_uintptr_t buffer; /* offsets from buffer to flat_binder_object structs */ binder_uintptr_t offsets; } ptr; __u8 buf[8]; } data; }; struct binder_transaction_data_sg { struct binder_transaction_data transaction_data; binder_size_t buffers_size; }; struct binder_ptr_cookie { binder_uintptr_t ptr; binder_uintptr_t cookie; }; struct binder_handle_cookie { __u32 handle; binder_uintptr_t cookie; } __attribute__((packed)); struct binder_pri_desc { __s32 priority; __u32 desc; }; struct binder_pri_ptr_cookie { __s32 priority; binder_uintptr_t ptr; binder_uintptr_t cookie; }; enum binder_driver_return_protocol { BR_ERROR = _IOR('r', 0, __s32), /* * int: error code */ BR_OK = _IO('r', 1), /* No parameters! */ BR_TRANSACTION = _IOR('r', 2, struct binder_transaction_data), BR_REPLY = _IOR('r', 3, struct binder_transaction_data), /* * binder_transaction_data: the received command. */ BR_ACQUIRE_RESULT = _IOR('r', 4, __s32), /* * not currently supported * int: 0 if the last bcATTEMPT_ACQUIRE was not successful. * Else the remote object has acquired a primary reference. */ BR_DEAD_REPLY = _IO('r', 5), /* * The target of the last transaction (either a bcTRANSACTION or * a bcATTEMPT_ACQUIRE) is no longer with us. No parameters. */ BR_TRANSACTION_COMPLETE = _IO('r', 6), /* * No parameters... always refers to the last transaction requested * (including replies). Note that this will be sent even for * asynchronous transactions. */ BR_INCREFS = _IOR('r', 7, struct binder_ptr_cookie), BR_ACQUIRE = _IOR('r', 8, struct binder_ptr_cookie), BR_RELEASE = _IOR('r', 9, struct binder_ptr_cookie), BR_DECREFS = _IOR('r', 10, struct binder_ptr_cookie), /* * void *: ptr to binder * void *: cookie for binder */ BR_ATTEMPT_ACQUIRE = _IOR('r', 11, struct binder_pri_ptr_cookie), /* * not currently supported * int: priority * void *: ptr to binder * void *: cookie for binder */ BR_NOOP = _IO('r', 12), /* * No parameters. Do nothing and examine the next command. It exists * primarily so that we can replace it with a BR_SPAWN_LOOPER command. */ BR_SPAWN_LOOPER = _IO('r', 13), /* * No parameters. The driver has determined that a process has no * threads waiting to service incoming transactions. When a process * receives this command, it must spawn a new service thread and * register it via bcENTER_LOOPER. */ BR_FINISHED = _IO('r', 14), /* * not currently supported * stop threadpool thread */ BR_DEAD_BINDER = _IOR('r', 15, binder_uintptr_t), /* * void *: cookie */ BR_CLEAR_DEATH_NOTIFICATION_DONE = _IOR('r', 16, binder_uintptr_t), /* * void *: cookie */ BR_FAILED_REPLY = _IO('r', 17), /* * The the last transaction (either a bcTRANSACTION or * a bcATTEMPT_ACQUIRE) failed (e.g. out of memory). No parameters. */ }; enum binder_driver_command_protocol { BC_TRANSACTION = _IOW('c', 0, struct binder_transaction_data), BC_REPLY = _IOW('c', 1, struct binder_transaction_data), /* * binder_transaction_data: the sent command. */ BC_ACQUIRE_RESULT = _IOW('c', 2, __s32), /* * not currently supported * int: 0 if the last BR_ATTEMPT_ACQUIRE was not successful. * Else you have acquired a primary reference on the object. */ BC_FREE_BUFFER = _IOW('c', 3, binder_uintptr_t), /* * void *: ptr to transaction data received on a read */ BC_INCREFS = _IOW('c', 4, __u32), BC_ACQUIRE = _IOW('c', 5, __u32), BC_RELEASE = _IOW('c', 6, __u32), BC_DECREFS = _IOW('c', 7, __u32), /* * int: descriptor */ BC_INCREFS_DONE = _IOW('c', 8, struct binder_ptr_cookie), BC_ACQUIRE_DONE = _IOW('c', 9, struct binder_ptr_cookie), /* * void *: ptr to binder * void *: cookie for binder */ BC_ATTEMPT_ACQUIRE = _IOW('c', 10, struct binder_pri_desc), /* * not currently supported * int: priority * int: descriptor */ BC_REGISTER_LOOPER = _IO('c', 11), /* * No parameters. * Register a spawned looper thread with the device. */ BC_ENTER_LOOPER = _IO('c', 12), BC_EXIT_LOOPER = _IO('c', 13), /* * No parameters. * These two commands are sent as an application-level thread * enters and exits the binder loop, respectively. They are * used so the binder can have an accurate count of the number * of looping threads it has available. */ BC_REQUEST_DEATH_NOTIFICATION = _IOW('c', 14, struct binder_handle_cookie), /* * int: handle * void *: cookie */ BC_CLEAR_DEATH_NOTIFICATION = _IOW('c', 15, struct binder_handle_cookie), /* * int: handle * void *: cookie */ BC_DEAD_BINDER_DONE = _IOW('c', 16, binder_uintptr_t), /* * void *: cookie */ BC_TRANSACTION_SG = _IOW('c', 17, struct binder_transaction_data_sg), BC_REPLY_SG = _IOW('c', 18, struct binder_transaction_data_sg), /* * binder_transaction_data_sg: the sent command. */ }; #endif /* _LINUX_BINDER_H */ linux/spi/spidev.h000064400000011724151027430560010151 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * include/linux/spi/spidev.h * * Copyright (C) 2006 SWAPP * Andrea Paterniani * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef SPIDEV_H #define SPIDEV_H #include #include /* User space versions of kernel symbols for SPI clocking modes, * matching */ #define SPI_CPHA 0x01 #define SPI_CPOL 0x02 #define SPI_MODE_0 (0|0) #define SPI_MODE_1 (0|SPI_CPHA) #define SPI_MODE_2 (SPI_CPOL|0) #define SPI_MODE_3 (SPI_CPOL|SPI_CPHA) #define SPI_CS_HIGH 0x04 #define SPI_LSB_FIRST 0x08 #define SPI_3WIRE 0x10 #define SPI_LOOP 0x20 #define SPI_NO_CS 0x40 #define SPI_READY 0x80 #define SPI_TX_DUAL 0x100 #define SPI_TX_QUAD 0x200 #define SPI_RX_DUAL 0x400 #define SPI_RX_QUAD 0x800 /*---------------------------------------------------------------------------*/ /* IOCTL commands */ #define SPI_IOC_MAGIC 'k' /** * struct spi_ioc_transfer - describes a single SPI transfer * @tx_buf: Holds pointer to userspace buffer with transmit data, or null. * If no data is provided, zeroes are shifted out. * @rx_buf: Holds pointer to userspace buffer for receive data, or null. * @len: Length of tx and rx buffers, in bytes. * @speed_hz: Temporary override of the device's bitrate. * @bits_per_word: Temporary override of the device's wordsize. * @delay_usecs: If nonzero, how long to delay after the last bit transfer * before optionally deselecting the device before the next transfer. * @cs_change: True to deselect device before starting the next transfer. * * This structure is mapped directly to the kernel spi_transfer structure; * the fields have the same meanings, except of course that the pointers * are in a different address space (and may be of different sizes in some * cases, such as 32-bit i386 userspace over a 64-bit x86_64 kernel). * Zero-initialize the structure, including currently unused fields, to * accommodate potential future updates. * * SPI_IOC_MESSAGE gives userspace the equivalent of kernel spi_sync(). * Pass it an array of related transfers, they'll execute together. * Each transfer may be half duplex (either direction) or full duplex. * * struct spi_ioc_transfer mesg[4]; * ... * status = ioctl(fd, SPI_IOC_MESSAGE(4), mesg); * * So for example one transfer might send a nine bit command (right aligned * in a 16-bit word), the next could read a block of 8-bit data before * terminating that command by temporarily deselecting the chip; the next * could send a different nine bit command (re-selecting the chip), and the * last transfer might write some register values. */ struct spi_ioc_transfer { __u64 tx_buf; __u64 rx_buf; __u32 len; __u32 speed_hz; __u16 delay_usecs; __u8 bits_per_word; __u8 cs_change; __u8 tx_nbits; __u8 rx_nbits; __u16 pad; /* If the contents of 'struct spi_ioc_transfer' ever change * incompatibly, then the ioctl number (currently 0) must change; * ioctls with constant size fields get a bit more in the way of * error checking than ones (like this) where that field varies. * * NOTE: struct layout is the same in 64bit and 32bit userspace. */ }; /* not all platforms use or _IOC_TYPECHECK() ... */ #define SPI_MSGSIZE(N) \ ((((N)*(sizeof (struct spi_ioc_transfer))) < (1 << _IOC_SIZEBITS)) \ ? ((N)*(sizeof (struct spi_ioc_transfer))) : 0) #define SPI_IOC_MESSAGE(N) _IOW(SPI_IOC_MAGIC, 0, char[SPI_MSGSIZE(N)]) /* Read / Write of SPI mode (SPI_MODE_0..SPI_MODE_3) (limited to 8 bits) */ #define SPI_IOC_RD_MODE _IOR(SPI_IOC_MAGIC, 1, __u8) #define SPI_IOC_WR_MODE _IOW(SPI_IOC_MAGIC, 1, __u8) /* Read / Write SPI bit justification */ #define SPI_IOC_RD_LSB_FIRST _IOR(SPI_IOC_MAGIC, 2, __u8) #define SPI_IOC_WR_LSB_FIRST _IOW(SPI_IOC_MAGIC, 2, __u8) /* Read / Write SPI device word length (1..N) */ #define SPI_IOC_RD_BITS_PER_WORD _IOR(SPI_IOC_MAGIC, 3, __u8) #define SPI_IOC_WR_BITS_PER_WORD _IOW(SPI_IOC_MAGIC, 3, __u8) /* Read / Write SPI device default max speed hz */ #define SPI_IOC_RD_MAX_SPEED_HZ _IOR(SPI_IOC_MAGIC, 4, __u32) #define SPI_IOC_WR_MAX_SPEED_HZ _IOW(SPI_IOC_MAGIC, 4, __u32) /* Read / Write of the SPI mode field */ #define SPI_IOC_RD_MODE32 _IOR(SPI_IOC_MAGIC, 5, __u32) #define SPI_IOC_WR_MODE32 _IOW(SPI_IOC_MAGIC, 5, __u32) #endif /* SPIDEV_H */ linux/string.h000064400000000356151027430560007371 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_STRING_H_ #define _LINUX_STRING_H_ /* We don't want strings.h stuff being used by user stuff by accident */ #include #endif /* _LINUX_STRING_H_ */ linux/net_tstamp.h000064400000013256151027430560010244 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Userspace API for hardware time stamping of network packets * * Copyright (C) 2008,2009 Intel Corporation * Author: Patrick Ohly * */ #ifndef _NET_TIMESTAMPING_H #define _NET_TIMESTAMPING_H #include #include /* for SO_TIMESTAMPING */ /* SO_TIMESTAMPING gets an integer bit field comprised of these values */ enum { SOF_TIMESTAMPING_TX_HARDWARE = (1<<0), SOF_TIMESTAMPING_TX_SOFTWARE = (1<<1), SOF_TIMESTAMPING_RX_HARDWARE = (1<<2), SOF_TIMESTAMPING_RX_SOFTWARE = (1<<3), SOF_TIMESTAMPING_SOFTWARE = (1<<4), SOF_TIMESTAMPING_SYS_HARDWARE = (1<<5), SOF_TIMESTAMPING_RAW_HARDWARE = (1<<6), SOF_TIMESTAMPING_OPT_ID = (1<<7), SOF_TIMESTAMPING_TX_SCHED = (1<<8), SOF_TIMESTAMPING_TX_ACK = (1<<9), SOF_TIMESTAMPING_OPT_CMSG = (1<<10), SOF_TIMESTAMPING_OPT_TSONLY = (1<<11), SOF_TIMESTAMPING_OPT_STATS = (1<<12), SOF_TIMESTAMPING_OPT_PKTINFO = (1<<13), SOF_TIMESTAMPING_OPT_TX_SWHW = (1<<14), SOF_TIMESTAMPING_LAST = SOF_TIMESTAMPING_OPT_TX_SWHW, SOF_TIMESTAMPING_MASK = (SOF_TIMESTAMPING_LAST - 1) | SOF_TIMESTAMPING_LAST }; /* * SO_TIMESTAMPING flags are either for recording a packet timestamp or for * reporting the timestamp to user space. * Recording flags can be set both via socket options and control messages. */ #define SOF_TIMESTAMPING_TX_RECORD_MASK (SOF_TIMESTAMPING_TX_HARDWARE | \ SOF_TIMESTAMPING_TX_SOFTWARE | \ SOF_TIMESTAMPING_TX_SCHED | \ SOF_TIMESTAMPING_TX_ACK) /** * struct hwtstamp_config - %SIOCGHWTSTAMP and %SIOCSHWTSTAMP parameter * * @flags: one of HWTSTAMP_FLAG_* * @tx_type: one of HWTSTAMP_TX_* * @rx_filter: one of HWTSTAMP_FILTER_* * * %SIOCGHWTSTAMP and %SIOCSHWTSTAMP expect a &struct ifreq with a * ifr_data pointer to this structure. For %SIOCSHWTSTAMP, if the * driver or hardware does not support the requested @rx_filter value, * the driver may use a more general filter mode. In this case * @rx_filter will indicate the actual mode on return. */ struct hwtstamp_config { int flags; int tx_type; int rx_filter; }; /* possible values for hwtstamp_config->flags */ enum hwtstamp_flags { /* * With this flag, the user could get bond active interface's * PHC index. Note this PHC index is not stable as when there * is a failover, the bond active interface will be changed, so * will be the PHC index. */ HWTSTAMP_FLAG_BONDED_PHC_INDEX = (1<<0), #define HWTSTAMP_FLAG_BONDED_PHC_INDEX HWTSTAMP_FLAG_BONDED_PHC_INDEX HWTSTAMP_FLAG_LAST = HWTSTAMP_FLAG_BONDED_PHC_INDEX, HWTSTAMP_FLAG_MASK = (HWTSTAMP_FLAG_LAST - 1) | HWTSTAMP_FLAG_LAST }; /* possible values for hwtstamp_config->tx_type */ enum hwtstamp_tx_types { /* * No outgoing packet will need hardware time stamping; * should a packet arrive which asks for it, no hardware * time stamping will be done. */ HWTSTAMP_TX_OFF, /* * Enables hardware time stamping for outgoing packets; * the sender of the packet decides which are to be * time stamped by setting %SOF_TIMESTAMPING_TX_SOFTWARE * before sending the packet. */ HWTSTAMP_TX_ON, /* * Enables time stamping for outgoing packets just as * HWTSTAMP_TX_ON does, but also enables time stamp insertion * directly into Sync packets. In this case, transmitted Sync * packets will not received a time stamp via the socket error * queue. */ HWTSTAMP_TX_ONESTEP_SYNC, /* * Same as HWTSTAMP_TX_ONESTEP_SYNC, but also enables time * stamp insertion directly into PDelay_Resp packets. In this * case, neither transmitted Sync nor PDelay_Resp packets will * receive a time stamp via the socket error queue. */ HWTSTAMP_TX_ONESTEP_P2P, /* add new constants above here */ __HWTSTAMP_TX_CNT }; /* possible values for hwtstamp_config->rx_filter */ enum hwtstamp_rx_filters { /* time stamp no incoming packet at all */ HWTSTAMP_FILTER_NONE, /* time stamp any incoming packet */ HWTSTAMP_FILTER_ALL, /* return value: time stamp all packets requested plus some others */ HWTSTAMP_FILTER_SOME, /* PTP v1, UDP, any kind of event packet */ HWTSTAMP_FILTER_PTP_V1_L4_EVENT, /* PTP v1, UDP, Sync packet */ HWTSTAMP_FILTER_PTP_V1_L4_SYNC, /* PTP v1, UDP, Delay_req packet */ HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ, /* PTP v2, UDP, any kind of event packet */ HWTSTAMP_FILTER_PTP_V2_L4_EVENT, /* PTP v2, UDP, Sync packet */ HWTSTAMP_FILTER_PTP_V2_L4_SYNC, /* PTP v2, UDP, Delay_req packet */ HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ, /* 802.AS1, Ethernet, any kind of event packet */ HWTSTAMP_FILTER_PTP_V2_L2_EVENT, /* 802.AS1, Ethernet, Sync packet */ HWTSTAMP_FILTER_PTP_V2_L2_SYNC, /* 802.AS1, Ethernet, Delay_req packet */ HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ, /* PTP v2/802.AS1, any layer, any kind of event packet */ HWTSTAMP_FILTER_PTP_V2_EVENT, /* PTP v2/802.AS1, any layer, Sync packet */ HWTSTAMP_FILTER_PTP_V2_SYNC, /* PTP v2/802.AS1, any layer, Delay_req packet */ HWTSTAMP_FILTER_PTP_V2_DELAY_REQ, /* NTP, UDP, all versions and packet modes */ HWTSTAMP_FILTER_NTP_ALL, /* add new constants above here */ __HWTSTAMP_FILTER_CNT }; /* SCM_TIMESTAMPING_PKTINFO control message */ struct scm_ts_pktinfo { __u32 if_index; __u32 pkt_length; __u32 reserved[2]; }; /* * SO_TXTIME gets a struct sock_txtime with flags being an integer bit * field comprised of these values. */ enum txtime_flags { SOF_TXTIME_DEADLINE_MODE = (1 << 0), SOF_TXTIME_REPORT_ERRORS = (1 << 1), SOF_TXTIME_FLAGS_LAST = SOF_TXTIME_REPORT_ERRORS, SOF_TXTIME_FLAGS_MASK = (SOF_TXTIME_FLAGS_LAST - 1) | SOF_TXTIME_FLAGS_LAST }; struct sock_txtime { __kernel_clockid_t clockid;/* reference clockid */ __u32 flags; /* as defined by enum txtime_flags */ }; #endif /* _NET_TIMESTAMPING_H */ linux/parport.h000064400000007074151027430560007556 0ustar00/* * Any part of this program may be used in documents licensed under * the GNU Free Documentation License, Version 1.1 or any later version * published by the Free Software Foundation. */ #ifndef _PARPORT_H_ #define _PARPORT_H_ /* Start off with user-visible constants */ /* Maximum of 16 ports per machine */ #define PARPORT_MAX 16 /* Magic numbers */ #define PARPORT_IRQ_NONE -1 #define PARPORT_DMA_NONE -1 #define PARPORT_IRQ_AUTO -2 #define PARPORT_DMA_AUTO -2 #define PARPORT_DMA_NOFIFO -3 #define PARPORT_DISABLE -2 #define PARPORT_IRQ_PROBEONLY -3 #define PARPORT_IOHI_AUTO -1 #define PARPORT_CONTROL_STROBE 0x1 #define PARPORT_CONTROL_AUTOFD 0x2 #define PARPORT_CONTROL_INIT 0x4 #define PARPORT_CONTROL_SELECT 0x8 #define PARPORT_STATUS_ERROR 0x8 #define PARPORT_STATUS_SELECT 0x10 #define PARPORT_STATUS_PAPEROUT 0x20 #define PARPORT_STATUS_ACK 0x40 #define PARPORT_STATUS_BUSY 0x80 /* Type classes for Plug-and-Play probe. */ typedef enum { PARPORT_CLASS_LEGACY = 0, /* Non-IEEE1284 device */ PARPORT_CLASS_PRINTER, PARPORT_CLASS_MODEM, PARPORT_CLASS_NET, PARPORT_CLASS_HDC, /* Hard disk controller */ PARPORT_CLASS_PCMCIA, PARPORT_CLASS_MEDIA, /* Multimedia device */ PARPORT_CLASS_FDC, /* Floppy disk controller */ PARPORT_CLASS_PORTS, PARPORT_CLASS_SCANNER, PARPORT_CLASS_DIGCAM, PARPORT_CLASS_OTHER, /* Anything else */ PARPORT_CLASS_UNSPEC, /* No CLS field in ID */ PARPORT_CLASS_SCSIADAPTER } parport_device_class; /* The "modes" entry in parport is a bit field representing the capabilities of the hardware. */ #define PARPORT_MODE_PCSPP (1<<0) /* IBM PC registers available. */ #define PARPORT_MODE_TRISTATE (1<<1) /* Can tristate. */ #define PARPORT_MODE_EPP (1<<2) /* Hardware EPP. */ #define PARPORT_MODE_ECP (1<<3) /* Hardware ECP. */ #define PARPORT_MODE_COMPAT (1<<4) /* Hardware 'printer protocol'. */ #define PARPORT_MODE_DMA (1<<5) /* Hardware can DMA. */ #define PARPORT_MODE_SAFEININT (1<<6) /* SPP registers accessible in IRQ. */ /* IEEE1284 modes: Nibble mode, byte mode, ECP, ECPRLE and EPP are their own 'extensibility request' values. Others are special. 'Real' ECP modes must have the IEEE1284_MODE_ECP bit set. */ #define IEEE1284_MODE_NIBBLE 0 #define IEEE1284_MODE_BYTE (1<<0) #define IEEE1284_MODE_COMPAT (1<<8) #define IEEE1284_MODE_BECP (1<<9) /* Bounded ECP mode */ #define IEEE1284_MODE_ECP (1<<4) #define IEEE1284_MODE_ECPRLE (IEEE1284_MODE_ECP | (1<<5)) #define IEEE1284_MODE_ECPSWE (1<<10) /* Software-emulated */ #define IEEE1284_MODE_EPP (1<<6) #define IEEE1284_MODE_EPPSL (1<<11) /* EPP 1.7 */ #define IEEE1284_MODE_EPPSWE (1<<12) /* Software-emulated */ #define IEEE1284_DEVICEID (1<<2) /* This is a flag */ #define IEEE1284_EXT_LINK (1<<14) /* This flag causes the * extensibility link to * be requested, using * bits 0-6. */ /* For the benefit of parport_read/write, you can use these with * parport_negotiate to use address operations. They have no effect * other than to make parport_read/write use address transfers. */ #define IEEE1284_ADDR (1<<13) /* This is a flag */ #define IEEE1284_DATA 0 /* So is this */ /* Flags for block transfer operations. */ #define PARPORT_EPP_FAST (1<<0) /* Unreliable counts. */ #define PARPORT_W91284PIC (1<<1) /* have a Warp9 w91284pic in the device */ /* The rest is for the kernel only */ #endif /* _PARPORT_H_ */ linux/uleds.h000064400000001436151027430560007177 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Userspace driver support for the LED subsystem * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __ULEDS_H_ #define __ULEDS_H_ #define LED_MAX_NAME_SIZE 64 struct uleds_user_dev { char name[LED_MAX_NAME_SIZE]; int max_brightness; }; #endif /* __ULEDS_H_ */ linux/nfs2.h000064400000002674151027430560006740 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * NFS protocol definitions * * This file contains constants for Version 2 of the protocol. */ #ifndef _LINUX_NFS2_H #define _LINUX_NFS2_H #define NFS2_PORT 2049 #define NFS2_MAXDATA 8192 #define NFS2_MAXPATHLEN 1024 #define NFS2_MAXNAMLEN 255 #define NFS2_MAXGROUPS 16 #define NFS2_FHSIZE 32 #define NFS2_COOKIESIZE 4 #define NFS2_FIFO_DEV (-1) #define NFS2MODE_FMT 0170000 #define NFS2MODE_DIR 0040000 #define NFS2MODE_CHR 0020000 #define NFS2MODE_BLK 0060000 #define NFS2MODE_REG 0100000 #define NFS2MODE_LNK 0120000 #define NFS2MODE_SOCK 0140000 #define NFS2MODE_FIFO 0010000 /* NFSv2 file types - beware, these are not the same in NFSv3 */ enum nfs2_ftype { NF2NON = 0, NF2REG = 1, NF2DIR = 2, NF2BLK = 3, NF2CHR = 4, NF2LNK = 5, NF2SOCK = 6, NF2BAD = 7, NF2FIFO = 8 }; struct nfs2_fh { char data[NFS2_FHSIZE]; }; /* * Procedure numbers for NFSv2 */ #define NFS2_VERSION 2 #define NFSPROC_NULL 0 #define NFSPROC_GETATTR 1 #define NFSPROC_SETATTR 2 #define NFSPROC_ROOT 3 #define NFSPROC_LOOKUP 4 #define NFSPROC_READLINK 5 #define NFSPROC_READ 6 #define NFSPROC_WRITECACHE 7 #define NFSPROC_WRITE 8 #define NFSPROC_CREATE 9 #define NFSPROC_REMOVE 10 #define NFSPROC_RENAME 11 #define NFSPROC_LINK 12 #define NFSPROC_SYMLINK 13 #define NFSPROC_MKDIR 14 #define NFSPROC_RMDIR 15 #define NFSPROC_READDIR 16 #define NFSPROC_STATFS 17 #endif /* _LINUX_NFS2_H */ linux/fsmap.h000064400000010451151027430560007166 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * FS_IOC_GETFSMAP ioctl infrastructure. * * Copyright (C) 2017 Oracle. All Rights Reserved. * * Author: Darrick J. Wong */ #ifndef _LINUX_FSMAP_H #define _LINUX_FSMAP_H #include /* * Structure for FS_IOC_GETFSMAP. * * The memory layout for this call are the scalar values defined in * struct fsmap_head, followed by two struct fsmap that describe * the lower and upper bound of mappings to return, followed by an * array of struct fsmap mappings. * * fmh_iflags control the output of the call, whereas fmh_oflags report * on the overall record output. fmh_count should be set to the * length of the fmh_recs array, and fmh_entries will be set to the * number of entries filled out during each call. If fmh_count is * zero, the number of reverse mappings will be returned in * fmh_entries, though no mappings will be returned. fmh_reserved * must be set to zero. * * The two elements in the fmh_keys array are used to constrain the * output. The first element in the array should represent the * lowest disk mapping ("low key") that the user wants to learn * about. If this value is all zeroes, the filesystem will return * the first entry it knows about. For a subsequent call, the * contents of fsmap_head.fmh_recs[fsmap_head.fmh_count - 1] should be * copied into fmh_keys[0] to have the kernel start where it left off. * * The second element in the fmh_keys array should represent the * highest disk mapping ("high key") that the user wants to learn * about. If this value is all ones, the filesystem will not stop * until it runs out of mapping to return or runs out of space in * fmh_recs. * * fmr_device can be either a 32-bit cookie representing a device, or * a 32-bit dev_t if the FMH_OF_DEV_T flag is set. fmr_physical, * fmr_offset, and fmr_length are expressed in units of bytes. * fmr_owner is either an inode number, or a special value if * FMR_OF_SPECIAL_OWNER is set in fmr_flags. */ struct fsmap { __u32 fmr_device; /* device id */ __u32 fmr_flags; /* mapping flags */ __u64 fmr_physical; /* device offset of segment */ __u64 fmr_owner; /* owner id */ __u64 fmr_offset; /* file offset of segment */ __u64 fmr_length; /* length of segment */ __u64 fmr_reserved[3]; /* must be zero */ }; struct fsmap_head { __u32 fmh_iflags; /* control flags */ __u32 fmh_oflags; /* output flags */ __u32 fmh_count; /* # of entries in array incl. input */ __u32 fmh_entries; /* # of entries filled in (output). */ __u64 fmh_reserved[6]; /* must be zero */ struct fsmap fmh_keys[2]; /* low and high keys for the mapping search */ struct fsmap fmh_recs[]; /* returned records */ }; /* Size of an fsmap_head with room for nr records. */ static __inline__ size_t fsmap_sizeof( unsigned int nr) { return sizeof(struct fsmap_head) + nr * sizeof(struct fsmap); } /* Start the next fsmap query at the end of the current query results. */ static __inline__ void fsmap_advance( struct fsmap_head *head) { head->fmh_keys[0] = head->fmh_recs[head->fmh_entries - 1]; } /* fmh_iflags values - set by FS_IOC_GETFSMAP caller in the header. */ /* no flags defined yet */ #define FMH_IF_VALID 0 /* fmh_oflags values - returned in the header segment only. */ #define FMH_OF_DEV_T 0x1 /* fmr_device values will be dev_t */ /* fmr_flags values - returned for each non-header segment */ #define FMR_OF_PREALLOC 0x1 /* segment = unwritten pre-allocation */ #define FMR_OF_ATTR_FORK 0x2 /* segment = attribute fork */ #define FMR_OF_EXTENT_MAP 0x4 /* segment = extent map */ #define FMR_OF_SHARED 0x8 /* segment = shared with another file */ #define FMR_OF_SPECIAL_OWNER 0x10 /* owner is a special value */ #define FMR_OF_LAST 0x20 /* segment is the last in the dataset */ /* Each FS gets to define its own special owner codes. */ #define FMR_OWNER(type, code) (((__u64)type << 32) | \ ((__u64)code & 0xFFFFFFFFULL)) #define FMR_OWNER_TYPE(owner) ((__u32)((__u64)owner >> 32)) #define FMR_OWNER_CODE(owner) ((__u32)(((__u64)owner & 0xFFFFFFFFULL))) #define FMR_OWN_FREE FMR_OWNER(0, 1) /* free space */ #define FMR_OWN_UNKNOWN FMR_OWNER(0, 2) /* unknown owner */ #define FMR_OWN_METADATA FMR_OWNER(0, 3) /* metadata */ #define FS_IOC_GETFSMAP _IOWR('X', 59, struct fsmap_head) #endif /* _LINUX_FSMAP_H */ linux/romfs_fs.h000064400000002326151027430560007700 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_ROMFS_FS_H #define __LINUX_ROMFS_FS_H #include #include /* The basic structures of the romfs filesystem */ #define ROMBSIZE BLOCK_SIZE #define ROMBSBITS BLOCK_SIZE_BITS #define ROMBMASK (ROMBSIZE-1) #define ROMFS_MAGIC 0x7275 #define ROMFS_MAXFN 128 #define __mkw(h,l) (((h)&0x00ff)<< 8|((l)&0x00ff)) #define __mkl(h,l) (((h)&0xffff)<<16|((l)&0xffff)) #define __mk4(a,b,c,d) cpu_to_be32(__mkl(__mkw(a,b),__mkw(c,d))) #define ROMSB_WORD0 __mk4('-','r','o','m') #define ROMSB_WORD1 __mk4('1','f','s','-') /* On-disk "super block" */ struct romfs_super_block { __be32 word0; __be32 word1; __be32 size; __be32 checksum; char name[0]; /* volume name */ }; /* On disk inode */ struct romfs_inode { __be32 next; /* low 4 bits see ROMFH_ */ __be32 spec; __be32 size; __be32 checksum; char name[0]; }; #define ROMFH_TYPE 7 #define ROMFH_HRD 0 #define ROMFH_DIR 1 #define ROMFH_REG 2 #define ROMFH_SYM 3 #define ROMFH_BLK 4 #define ROMFH_CHR 5 #define ROMFH_SCK 6 #define ROMFH_FIF 7 #define ROMFH_EXEC 8 /* Alignment */ #define ROMFH_SIZE 16 #define ROMFH_PAD (ROMFH_SIZE-1) #define ROMFH_MASK (~ROMFH_PAD) #endif linux/cifs/cifs_mount.h000064400000002237151027430560011155 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * * Author(s): Scott Lovenberg (scott.lovenberg@gmail.com) * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Lesser General Public License for more details. */ #ifndef _CIFS_MOUNT_H #define _CIFS_MOUNT_H /* Max string lengths for cifs mounting options. */ #define CIFS_MAX_DOMAINNAME_LEN 256 /* max fully qualified domain name */ #define CIFS_MAX_USERNAME_LEN 256 /* reasonable max for current servers */ #define CIFS_MAX_PASSWORD_LEN 512 /* Windows max seems to be 256 wide chars */ #define CIFS_MAX_SHARE_LEN 256 /* reasonable max share name length */ #define CIFS_NI_MAXHOST 1024 /* max host name length (256 * 4 bytes) */ #endif /* _CIFS_MOUNT_H */ linux/cifs/cifs_netlink.h000064400000003127151027430560011456 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * Netlink routines for CIFS * * Copyright (c) 2020 Samuel Cabrero */ #ifndef LINUX_CIFS_NETLINK_H #define LINUX_CIFS_NETLINK_H #define CIFS_GENL_NAME "cifs" #define CIFS_GENL_VERSION 0x1 #define CIFS_GENL_MCGRP_SWN_NAME "cifs_mcgrp_swn" enum cifs_genl_multicast_groups { CIFS_GENL_MCGRP_SWN, }; enum cifs_genl_attributes { CIFS_GENL_ATTR_UNSPEC, CIFS_GENL_ATTR_SWN_REGISTRATION_ID, CIFS_GENL_ATTR_SWN_NET_NAME, CIFS_GENL_ATTR_SWN_SHARE_NAME, CIFS_GENL_ATTR_SWN_IP, CIFS_GENL_ATTR_SWN_NET_NAME_NOTIFY, CIFS_GENL_ATTR_SWN_SHARE_NAME_NOTIFY, CIFS_GENL_ATTR_SWN_IP_NOTIFY, CIFS_GENL_ATTR_SWN_KRB_AUTH, CIFS_GENL_ATTR_SWN_USER_NAME, CIFS_GENL_ATTR_SWN_PASSWORD, CIFS_GENL_ATTR_SWN_DOMAIN_NAME, CIFS_GENL_ATTR_SWN_NOTIFICATION_TYPE, CIFS_GENL_ATTR_SWN_RESOURCE_STATE, CIFS_GENL_ATTR_SWN_RESOURCE_NAME, __CIFS_GENL_ATTR_MAX, }; #define CIFS_GENL_ATTR_MAX (__CIFS_GENL_ATTR_MAX - 1) enum cifs_genl_commands { CIFS_GENL_CMD_UNSPEC, CIFS_GENL_CMD_SWN_REGISTER, CIFS_GENL_CMD_SWN_UNREGISTER, CIFS_GENL_CMD_SWN_NOTIFY, __CIFS_GENL_CMD_MAX }; #define CIFS_GENL_CMD_MAX (__CIFS_GENL_CMD_MAX - 1) enum cifs_swn_notification_type { CIFS_SWN_NOTIFICATION_RESOURCE_CHANGE = 0x01, CIFS_SWN_NOTIFICATION_CLIENT_MOVE = 0x02, CIFS_SWN_NOTIFICATION_SHARE_MOVE = 0x03, CIFS_SWN_NOTIFICATION_IP_CHANGE = 0x04, }; enum cifs_swn_resource_state { CIFS_SWN_RESOURCE_STATE_UNKNOWN = 0x00, CIFS_SWN_RESOURCE_STATE_AVAILABLE = 0x01, CIFS_SWN_RESOURCE_STATE_UNAVAILABLE = 0xFF }; #endif /* LINUX_CIFS_NETLINK_H */ linux/inotify.h000064400000006334151027430560007546 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Inode based directory notification for Linux * * Copyright (C) 2005 John McCutchan */ #ifndef _LINUX_INOTIFY_H #define _LINUX_INOTIFY_H /* For O_CLOEXEC and O_NONBLOCK */ #include #include /* * struct inotify_event - structure read from the inotify device for each event * * When you are watching a directory, you will receive the filename for events * such as IN_CREATE, IN_DELETE, IN_OPEN, IN_CLOSE, ..., relative to the wd. */ struct inotify_event { __s32 wd; /* watch descriptor */ __u32 mask; /* watch mask */ __u32 cookie; /* cookie to synchronize two events */ __u32 len; /* length (including nulls) of name */ char name[0]; /* stub for possible name */ }; /* the following are legal, implemented events that user-space can watch for */ #define IN_ACCESS 0x00000001 /* File was accessed */ #define IN_MODIFY 0x00000002 /* File was modified */ #define IN_ATTRIB 0x00000004 /* Metadata changed */ #define IN_CLOSE_WRITE 0x00000008 /* Writtable file was closed */ #define IN_CLOSE_NOWRITE 0x00000010 /* Unwrittable file closed */ #define IN_OPEN 0x00000020 /* File was opened */ #define IN_MOVED_FROM 0x00000040 /* File was moved from X */ #define IN_MOVED_TO 0x00000080 /* File was moved to Y */ #define IN_CREATE 0x00000100 /* Subfile was created */ #define IN_DELETE 0x00000200 /* Subfile was deleted */ #define IN_DELETE_SELF 0x00000400 /* Self was deleted */ #define IN_MOVE_SELF 0x00000800 /* Self was moved */ /* the following are legal events. they are sent as needed to any watch */ #define IN_UNMOUNT 0x00002000 /* Backing fs was unmounted */ #define IN_Q_OVERFLOW 0x00004000 /* Event queued overflowed */ #define IN_IGNORED 0x00008000 /* File was ignored */ /* helper events */ #define IN_CLOSE (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) /* close */ #define IN_MOVE (IN_MOVED_FROM | IN_MOVED_TO) /* moves */ /* special flags */ #define IN_ONLYDIR 0x01000000 /* only watch the path if it is a directory */ #define IN_DONT_FOLLOW 0x02000000 /* don't follow a sym link */ #define IN_EXCL_UNLINK 0x04000000 /* exclude events on unlinked objects */ #define IN_MASK_CREATE 0x10000000 /* only create watches */ #define IN_MASK_ADD 0x20000000 /* add to the mask of an already existing watch */ #define IN_ISDIR 0x40000000 /* event occurred against dir */ #define IN_ONESHOT 0x80000000 /* only send event once */ /* * All of the events - we build the list by hand so that we can add flags in * the future and not break backward compatibility. Apps will get only the * events that they originally wanted. Be sure to add new events here! */ #define IN_ALL_EVENTS (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | \ IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | \ IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF | \ IN_MOVE_SELF) /* Flags for sys_inotify_init1. */ #define IN_CLOEXEC O_CLOEXEC #define IN_NONBLOCK O_NONBLOCK /* * ioctl numbers: inotify uses 'I' prefix for all ioctls, * except historical FIONREAD, which is based on 'T'. * * INOTIFY_IOC_SETNEXTWD: set desired number of next created * watch descriptor. */ #define INOTIFY_IOC_SETNEXTWD _IOW('I', 0, __s32) #endif /* _LINUX_INOTIFY_H */ linux/rose.h000064400000004270151027430560007032 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * These are the public elements of the Linux kernel Rose implementation. * For kernel AX.25 see the file ax25.h. This file requires ax25.h for the * definition of the ax25_address structure. */ #ifndef ROSE_KERNEL_H #define ROSE_KERNEL_H #include #include #define ROSE_MTU 251 #define ROSE_MAX_DIGIS 6 #define ROSE_DEFER 1 #define ROSE_T1 2 #define ROSE_T2 3 #define ROSE_T3 4 #define ROSE_IDLE 5 #define ROSE_QBITINCL 6 #define ROSE_HOLDBACK 7 #define SIOCRSGCAUSE (SIOCPROTOPRIVATE+0) #define SIOCRSSCAUSE (SIOCPROTOPRIVATE+1) #define SIOCRSL2CALL (SIOCPROTOPRIVATE+2) #define SIOCRSSL2CALL (SIOCPROTOPRIVATE+2) #define SIOCRSACCEPT (SIOCPROTOPRIVATE+3) #define SIOCRSCLRRT (SIOCPROTOPRIVATE+4) #define SIOCRSGL2CALL (SIOCPROTOPRIVATE+5) #define SIOCRSGFACILITIES (SIOCPROTOPRIVATE+6) #define ROSE_DTE_ORIGINATED 0x00 #define ROSE_NUMBER_BUSY 0x01 #define ROSE_INVALID_FACILITY 0x03 #define ROSE_NETWORK_CONGESTION 0x05 #define ROSE_OUT_OF_ORDER 0x09 #define ROSE_ACCESS_BARRED 0x0B #define ROSE_NOT_OBTAINABLE 0x0D #define ROSE_REMOTE_PROCEDURE 0x11 #define ROSE_LOCAL_PROCEDURE 0x13 #define ROSE_SHIP_ABSENT 0x39 typedef struct { char rose_addr[5]; } rose_address; struct sockaddr_rose { __kernel_sa_family_t srose_family; rose_address srose_addr; ax25_address srose_call; int srose_ndigis; ax25_address srose_digi; }; struct full_sockaddr_rose { __kernel_sa_family_t srose_family; rose_address srose_addr; ax25_address srose_call; unsigned int srose_ndigis; ax25_address srose_digis[ROSE_MAX_DIGIS]; }; struct rose_route_struct { rose_address address; unsigned short mask; ax25_address neighbour; char device[16]; unsigned char ndigis; ax25_address digipeaters[AX25_MAX_DIGIS]; }; struct rose_cause_struct { unsigned char cause; unsigned char diagnostic; }; struct rose_facilities_struct { rose_address source_addr, dest_addr; ax25_address source_call, dest_call; unsigned char source_ndigis, dest_ndigis; ax25_address source_digis[ROSE_MAX_DIGIS]; ax25_address dest_digis[ROSE_MAX_DIGIS]; unsigned int rand; rose_address fail_addr; ax25_address fail_call; }; #endif linux/packet_diag.h000064400000003210151027430560010306 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __PACKET_DIAG_H__ #define __PACKET_DIAG_H__ #include struct packet_diag_req { __u8 sdiag_family; __u8 sdiag_protocol; __u16 pad; __u32 pdiag_ino; __u32 pdiag_show; __u32 pdiag_cookie[2]; }; #define PACKET_SHOW_INFO 0x00000001 /* Basic packet_sk information */ #define PACKET_SHOW_MCLIST 0x00000002 /* A set of packet_diag_mclist-s */ #define PACKET_SHOW_RING_CFG 0x00000004 /* Rings configuration parameters */ #define PACKET_SHOW_FANOUT 0x00000008 #define PACKET_SHOW_MEMINFO 0x00000010 #define PACKET_SHOW_FILTER 0x00000020 struct packet_diag_msg { __u8 pdiag_family; __u8 pdiag_type; __u16 pdiag_num; __u32 pdiag_ino; __u32 pdiag_cookie[2]; }; enum { /* PACKET_DIAG_NONE, standard nl API requires this attribute! */ PACKET_DIAG_INFO, PACKET_DIAG_MCLIST, PACKET_DIAG_RX_RING, PACKET_DIAG_TX_RING, PACKET_DIAG_FANOUT, PACKET_DIAG_UID, PACKET_DIAG_MEMINFO, PACKET_DIAG_FILTER, __PACKET_DIAG_MAX, }; #define PACKET_DIAG_MAX (__PACKET_DIAG_MAX - 1) struct packet_diag_info { __u32 pdi_index; __u32 pdi_version; __u32 pdi_reserve; __u32 pdi_copy_thresh; __u32 pdi_tstamp; __u32 pdi_flags; #define PDI_RUNNING 0x1 #define PDI_AUXDATA 0x2 #define PDI_ORIGDEV 0x4 #define PDI_VNETHDR 0x8 #define PDI_LOSS 0x10 }; struct packet_diag_mclist { __u32 pdmc_index; __u32 pdmc_count; __u16 pdmc_type; __u16 pdmc_alen; __u8 pdmc_addr[32]; /* MAX_ADDR_LEN */ }; struct packet_diag_ring { __u32 pdr_block_size; __u32 pdr_block_nr; __u32 pdr_frame_size; __u32 pdr_frame_nr; __u32 pdr_retire_tmo; __u32 pdr_sizeof_priv; __u32 pdr_features; }; #endif linux/sysctl.h000064400000062362151027430560007411 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * sysctl.h: General linux system control interface * * Begun 24 March 1995, Stephen Tweedie * **************************************************************** **************************************************************** ** ** WARNING: ** The values in this file are exported to user space via ** the sysctl() binary interface. Do *NOT* change the ** numbering of any existing values here, and do not change ** any numbers within any one set of values. If you have to ** redefine an existing interface, use a new number for it. ** The kernel will then return -ENOTDIR to any application using ** the old binary interface. ** **************************************************************** **************************************************************** */ #ifndef _LINUX_SYSCTL_H #define _LINUX_SYSCTL_H #include #include #define CTL_MAXNAME 10 /* how many path components do we allow in a call to sysctl? In other words, what is the largest acceptable value for the nlen member of a struct __sysctl_args to have? */ struct __sysctl_args { int *name; int nlen; void *oldval; size_t *oldlenp; void *newval; size_t newlen; unsigned long __unused[4]; }; /* Define sysctl names first */ /* Top-level names: */ enum { CTL_KERN=1, /* General kernel info and control */ CTL_VM=2, /* VM management */ CTL_NET=3, /* Networking */ CTL_PROC=4, /* removal breaks strace(1) compilation */ CTL_FS=5, /* Filesystems */ CTL_DEBUG=6, /* Debugging */ CTL_DEV=7, /* Devices */ CTL_BUS=8, /* Busses */ CTL_ABI=9, /* Binary emulation */ CTL_CPU=10, /* CPU stuff (speed scaling, etc) */ CTL_ARLAN=254, /* arlan wireless driver */ CTL_S390DBF=5677, /* s390 debug */ CTL_SUNRPC=7249, /* sunrpc debug */ CTL_PM=9899, /* frv power management */ CTL_FRV=9898, /* frv specific sysctls */ }; /* CTL_BUS names: */ enum { CTL_BUS_ISA=1 /* ISA */ }; /* /proc/sys/fs/inotify/ */ enum { INOTIFY_MAX_USER_INSTANCES=1, /* max instances per user */ INOTIFY_MAX_USER_WATCHES=2, /* max watches per user */ INOTIFY_MAX_QUEUED_EVENTS=3 /* max queued events per instance */ }; /* CTL_KERN names: */ enum { KERN_OSTYPE=1, /* string: system version */ KERN_OSRELEASE=2, /* string: system release */ KERN_OSREV=3, /* int: system revision */ KERN_VERSION=4, /* string: compile time info */ KERN_SECUREMASK=5, /* struct: maximum rights mask */ KERN_PROF=6, /* table: profiling information */ KERN_NODENAME=7, /* string: hostname */ KERN_DOMAINNAME=8, /* string: domainname */ KERN_PANIC=15, /* int: panic timeout */ KERN_REALROOTDEV=16, /* real root device to mount after initrd */ KERN_SPARC_REBOOT=21, /* reboot command on Sparc */ KERN_CTLALTDEL=22, /* int: allow ctl-alt-del to reboot */ KERN_PRINTK=23, /* struct: control printk logging parameters */ KERN_NAMETRANS=24, /* Name translation */ KERN_PPC_HTABRECLAIM=25, /* turn htab reclaimation on/off on PPC */ KERN_PPC_ZEROPAGED=26, /* turn idle page zeroing on/off on PPC */ KERN_PPC_POWERSAVE_NAP=27, /* use nap mode for power saving */ KERN_MODPROBE=28, /* string: modprobe path */ KERN_SG_BIG_BUFF=29, /* int: sg driver reserved buffer size */ KERN_ACCT=30, /* BSD process accounting parameters */ KERN_PPC_L2CR=31, /* l2cr register on PPC */ KERN_RTSIGNR=32, /* Number of rt sigs queued */ KERN_RTSIGMAX=33, /* Max queuable */ KERN_SHMMAX=34, /* long: Maximum shared memory segment */ KERN_MSGMAX=35, /* int: Maximum size of a messege */ KERN_MSGMNB=36, /* int: Maximum message queue size */ KERN_MSGPOOL=37, /* int: Maximum system message pool size */ KERN_SYSRQ=38, /* int: Sysreq enable */ KERN_MAX_THREADS=39, /* int: Maximum nr of threads in the system */ KERN_RANDOM=40, /* Random driver */ KERN_SHMALL=41, /* int: Maximum size of shared memory */ KERN_MSGMNI=42, /* int: msg queue identifiers */ KERN_SEM=43, /* struct: sysv semaphore limits */ KERN_SPARC_STOP_A=44, /* int: Sparc Stop-A enable */ KERN_SHMMNI=45, /* int: shm array identifiers */ KERN_OVERFLOWUID=46, /* int: overflow UID */ KERN_OVERFLOWGID=47, /* int: overflow GID */ KERN_SHMPATH=48, /* string: path to shm fs */ KERN_HOTPLUG=49, /* string: path to uevent helper (deprecated) */ KERN_IEEE_EMULATION_WARNINGS=50, /* int: unimplemented ieee instructions */ KERN_S390_USER_DEBUG_LOGGING=51, /* int: dumps of user faults */ KERN_CORE_USES_PID=52, /* int: use core or core.%pid */ KERN_TAINTED=53, /* int: various kernel tainted flags */ KERN_CADPID=54, /* int: PID of the process to notify on CAD */ KERN_PIDMAX=55, /* int: PID # limit */ KERN_CORE_PATTERN=56, /* string: pattern for core-file names */ KERN_PANIC_ON_OOPS=57, /* int: whether we will panic on an oops */ KERN_HPPA_PWRSW=58, /* int: hppa soft-power enable */ KERN_HPPA_UNALIGNED=59, /* int: hppa unaligned-trap enable */ KERN_PRINTK_RATELIMIT=60, /* int: tune printk ratelimiting */ KERN_PRINTK_RATELIMIT_BURST=61, /* int: tune printk ratelimiting */ KERN_PTY=62, /* dir: pty driver */ KERN_NGROUPS_MAX=63, /* int: NGROUPS_MAX */ KERN_SPARC_SCONS_PWROFF=64, /* int: serial console power-off halt */ KERN_HZ_TIMER=65, /* int: hz timer on or off */ KERN_UNKNOWN_NMI_PANIC=66, /* int: unknown nmi panic flag */ KERN_BOOTLOADER_TYPE=67, /* int: boot loader type */ KERN_RANDOMIZE=68, /* int: randomize virtual address space */ KERN_SETUID_DUMPABLE=69, /* int: behaviour of dumps for setuid core */ KERN_SPIN_RETRY=70, /* int: number of spinlock retries */ KERN_ACPI_VIDEO_FLAGS=71, /* int: flags for setting up video after ACPI sleep */ KERN_IA64_UNALIGNED=72, /* int: ia64 unaligned userland trap enable */ KERN_COMPAT_LOG=73, /* int: print compat layer messages */ KERN_MAX_LOCK_DEPTH=74, /* int: rtmutex's maximum lock depth */ KERN_NMI_WATCHDOG=75, /* int: enable/disable nmi watchdog */ KERN_PANIC_ON_NMI=76, /* int: whether we will panic on an unrecovered */ KERN_PANIC_ON_WARN=77, /* int: call panic() in WARN() functions */ KERN_PANIC_PRINT=78, /* ulong: bitmask to print system info on panic */ }; /* CTL_VM names: */ enum { VM_UNUSED1=1, /* was: struct: Set vm swapping control */ VM_UNUSED2=2, /* was; int: Linear or sqrt() swapout for hogs */ VM_UNUSED3=3, /* was: struct: Set free page thresholds */ VM_UNUSED4=4, /* Spare */ VM_OVERCOMMIT_MEMORY=5, /* Turn off the virtual memory safety limit */ VM_UNUSED5=6, /* was: struct: Set buffer memory thresholds */ VM_UNUSED7=7, /* was: struct: Set cache memory thresholds */ VM_UNUSED8=8, /* was: struct: Control kswapd behaviour */ VM_UNUSED9=9, /* was: struct: Set page table cache parameters */ VM_PAGE_CLUSTER=10, /* int: set number of pages to swap together */ VM_DIRTY_BACKGROUND=11, /* dirty_background_ratio */ VM_DIRTY_RATIO=12, /* dirty_ratio */ VM_DIRTY_WB_CS=13, /* dirty_writeback_centisecs */ VM_DIRTY_EXPIRE_CS=14, /* dirty_expire_centisecs */ VM_NR_PDFLUSH_THREADS=15, /* nr_pdflush_threads */ VM_OVERCOMMIT_RATIO=16, /* percent of RAM to allow overcommit in */ VM_PAGEBUF=17, /* struct: Control pagebuf parameters */ VM_HUGETLB_PAGES=18, /* int: Number of available Huge Pages */ VM_SWAPPINESS=19, /* Tendency to steal mapped memory */ VM_LOWMEM_RESERVE_RATIO=20,/* reservation ratio for lower memory zones */ VM_MIN_FREE_KBYTES=21, /* Minimum free kilobytes to maintain */ VM_MAX_MAP_COUNT=22, /* int: Maximum number of mmaps/address-space */ VM_LAPTOP_MODE=23, /* vm laptop mode */ VM_BLOCK_DUMP=24, /* block dump mode */ VM_HUGETLB_GROUP=25, /* permitted hugetlb group */ VM_VFS_CACHE_PRESSURE=26, /* dcache/icache reclaim pressure */ VM_LEGACY_VA_LAYOUT=27, /* legacy/compatibility virtual address space layout */ VM_SWAP_TOKEN_TIMEOUT=28, /* default time for token time out */ VM_DROP_PAGECACHE=29, /* int: nuke lots of pagecache */ VM_PERCPU_PAGELIST_FRACTION=30,/* int: fraction of pages in each percpu_pagelist */ VM_ZONE_RECLAIM_MODE=31, /* reclaim local zone memory before going off node */ VM_MIN_UNMAPPED=32, /* Set min percent of unmapped pages */ VM_PANIC_ON_OOM=33, /* panic at out-of-memory */ VM_VDSO_ENABLED=34, /* map VDSO into new processes? */ VM_MIN_SLAB=35, /* Percent pages ignored by zone reclaim */ }; /* CTL_NET names: */ enum { NET_CORE=1, NET_ETHER=2, NET_802=3, NET_UNIX=4, NET_IPV4=5, NET_IPX=6, NET_ATALK=7, NET_NETROM=8, NET_AX25=9, NET_BRIDGE=10, NET_ROSE=11, NET_IPV6=12, NET_X25=13, NET_TR=14, NET_DECNET=15, NET_ECONET=16, NET_SCTP=17, NET_LLC=18, NET_NETFILTER=19, NET_DCCP=20, NET_IRDA=412, }; /* /proc/sys/kernel/random */ enum { RANDOM_POOLSIZE=1, RANDOM_ENTROPY_COUNT=2, RANDOM_READ_THRESH=3, RANDOM_WRITE_THRESH=4, RANDOM_BOOT_ID=5, RANDOM_UUID=6 }; /* /proc/sys/kernel/pty */ enum { PTY_MAX=1, PTY_NR=2 }; /* /proc/sys/bus/isa */ enum { BUS_ISA_MEM_BASE=1, BUS_ISA_PORT_BASE=2, BUS_ISA_PORT_SHIFT=3 }; /* /proc/sys/net/core */ enum { NET_CORE_WMEM_MAX=1, NET_CORE_RMEM_MAX=2, NET_CORE_WMEM_DEFAULT=3, NET_CORE_RMEM_DEFAULT=4, /* was NET_CORE_DESTROY_DELAY */ NET_CORE_MAX_BACKLOG=6, NET_CORE_FASTROUTE=7, NET_CORE_MSG_COST=8, NET_CORE_MSG_BURST=9, NET_CORE_OPTMEM_MAX=10, NET_CORE_HOT_LIST_LENGTH=11, NET_CORE_DIVERT_VERSION=12, NET_CORE_NO_CONG_THRESH=13, NET_CORE_NO_CONG=14, NET_CORE_LO_CONG=15, NET_CORE_MOD_CONG=16, NET_CORE_DEV_WEIGHT=17, NET_CORE_SOMAXCONN=18, NET_CORE_BUDGET=19, NET_CORE_AEVENT_ETIME=20, NET_CORE_AEVENT_RSEQTH=21, NET_CORE_WARNINGS=22, }; /* /proc/sys/net/ethernet */ /* /proc/sys/net/802 */ /* /proc/sys/net/unix */ enum { NET_UNIX_DESTROY_DELAY=1, NET_UNIX_DELETE_DELAY=2, NET_UNIX_MAX_DGRAM_QLEN=3, }; /* /proc/sys/net/netfilter */ enum { NET_NF_CONNTRACK_MAX=1, NET_NF_CONNTRACK_TCP_TIMEOUT_SYN_SENT=2, NET_NF_CONNTRACK_TCP_TIMEOUT_SYN_RECV=3, NET_NF_CONNTRACK_TCP_TIMEOUT_ESTABLISHED=4, NET_NF_CONNTRACK_TCP_TIMEOUT_FIN_WAIT=5, NET_NF_CONNTRACK_TCP_TIMEOUT_CLOSE_WAIT=6, NET_NF_CONNTRACK_TCP_TIMEOUT_LAST_ACK=7, NET_NF_CONNTRACK_TCP_TIMEOUT_TIME_WAIT=8, NET_NF_CONNTRACK_TCP_TIMEOUT_CLOSE=9, NET_NF_CONNTRACK_UDP_TIMEOUT=10, NET_NF_CONNTRACK_UDP_TIMEOUT_STREAM=11, NET_NF_CONNTRACK_ICMP_TIMEOUT=12, NET_NF_CONNTRACK_GENERIC_TIMEOUT=13, NET_NF_CONNTRACK_BUCKETS=14, NET_NF_CONNTRACK_LOG_INVALID=15, NET_NF_CONNTRACK_TCP_TIMEOUT_MAX_RETRANS=16, NET_NF_CONNTRACK_TCP_LOOSE=17, NET_NF_CONNTRACK_TCP_BE_LIBERAL=18, NET_NF_CONNTRACK_TCP_MAX_RETRANS=19, NET_NF_CONNTRACK_SCTP_TIMEOUT_CLOSED=20, NET_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_WAIT=21, NET_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_ECHOED=22, NET_NF_CONNTRACK_SCTP_TIMEOUT_ESTABLISHED=23, NET_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_SENT=24, NET_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_RECD=25, NET_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_ACK_SENT=26, NET_NF_CONNTRACK_COUNT=27, NET_NF_CONNTRACK_ICMPV6_TIMEOUT=28, NET_NF_CONNTRACK_FRAG6_TIMEOUT=29, NET_NF_CONNTRACK_FRAG6_LOW_THRESH=30, NET_NF_CONNTRACK_FRAG6_HIGH_THRESH=31, NET_NF_CONNTRACK_CHECKSUM=32, }; /* /proc/sys/net/ipv4 */ enum { /* v2.0 compatibile variables */ NET_IPV4_FORWARD=8, NET_IPV4_DYNADDR=9, NET_IPV4_CONF=16, NET_IPV4_NEIGH=17, NET_IPV4_ROUTE=18, NET_IPV4_FIB_HASH=19, NET_IPV4_NETFILTER=20, NET_IPV4_TCP_TIMESTAMPS=33, NET_IPV4_TCP_WINDOW_SCALING=34, NET_IPV4_TCP_SACK=35, NET_IPV4_TCP_RETRANS_COLLAPSE=36, NET_IPV4_DEFAULT_TTL=37, NET_IPV4_AUTOCONFIG=38, NET_IPV4_NO_PMTU_DISC=39, NET_IPV4_TCP_SYN_RETRIES=40, NET_IPV4_IPFRAG_HIGH_THRESH=41, NET_IPV4_IPFRAG_LOW_THRESH=42, NET_IPV4_IPFRAG_TIME=43, NET_IPV4_TCP_MAX_KA_PROBES=44, NET_IPV4_TCP_KEEPALIVE_TIME=45, NET_IPV4_TCP_KEEPALIVE_PROBES=46, NET_IPV4_TCP_RETRIES1=47, NET_IPV4_TCP_RETRIES2=48, NET_IPV4_TCP_FIN_TIMEOUT=49, NET_IPV4_IP_MASQ_DEBUG=50, NET_TCP_SYNCOOKIES=51, NET_TCP_STDURG=52, NET_TCP_RFC1337=53, NET_TCP_SYN_TAILDROP=54, NET_TCP_MAX_SYN_BACKLOG=55, NET_IPV4_LOCAL_PORT_RANGE=56, NET_IPV4_ICMP_ECHO_IGNORE_ALL=57, NET_IPV4_ICMP_ECHO_IGNORE_BROADCASTS=58, NET_IPV4_ICMP_SOURCEQUENCH_RATE=59, NET_IPV4_ICMP_DESTUNREACH_RATE=60, NET_IPV4_ICMP_TIMEEXCEED_RATE=61, NET_IPV4_ICMP_PARAMPROB_RATE=62, NET_IPV4_ICMP_ECHOREPLY_RATE=63, NET_IPV4_ICMP_IGNORE_BOGUS_ERROR_RESPONSES=64, NET_IPV4_IGMP_MAX_MEMBERSHIPS=65, NET_TCP_TW_RECYCLE=66, NET_IPV4_ALWAYS_DEFRAG=67, NET_IPV4_TCP_KEEPALIVE_INTVL=68, NET_IPV4_INET_PEER_THRESHOLD=69, NET_IPV4_INET_PEER_MINTTL=70, NET_IPV4_INET_PEER_MAXTTL=71, NET_IPV4_INET_PEER_GC_MINTIME=72, NET_IPV4_INET_PEER_GC_MAXTIME=73, NET_TCP_ORPHAN_RETRIES=74, NET_TCP_ABORT_ON_OVERFLOW=75, NET_TCP_SYNACK_RETRIES=76, NET_TCP_MAX_ORPHANS=77, NET_TCP_MAX_TW_BUCKETS=78, NET_TCP_FACK=79, NET_TCP_REORDERING=80, NET_TCP_ECN=81, NET_TCP_DSACK=82, NET_TCP_MEM=83, NET_TCP_WMEM=84, NET_TCP_RMEM=85, NET_TCP_APP_WIN=86, NET_TCP_ADV_WIN_SCALE=87, NET_IPV4_NONLOCAL_BIND=88, NET_IPV4_ICMP_RATELIMIT=89, NET_IPV4_ICMP_RATEMASK=90, NET_TCP_TW_REUSE=91, NET_TCP_FRTO=92, NET_TCP_LOW_LATENCY=93, NET_IPV4_IPFRAG_SECRET_INTERVAL=94, NET_IPV4_IGMP_MAX_MSF=96, NET_TCP_NO_METRICS_SAVE=97, NET_TCP_DEFAULT_WIN_SCALE=105, NET_TCP_MODERATE_RCVBUF=106, NET_TCP_TSO_WIN_DIVISOR=107, NET_TCP_BIC_BETA=108, NET_IPV4_ICMP_ERRORS_USE_INBOUND_IFADDR=109, NET_TCP_CONG_CONTROL=110, NET_TCP_ABC=111, NET_IPV4_IPFRAG_MAX_DIST=112, NET_TCP_MTU_PROBING=113, NET_TCP_BASE_MSS=114, NET_IPV4_TCP_WORKAROUND_SIGNED_WINDOWS=115, NET_TCP_DMA_COPYBREAK=116, NET_TCP_SLOW_START_AFTER_IDLE=117, NET_CIPSOV4_CACHE_ENABLE=118, NET_CIPSOV4_CACHE_BUCKET_SIZE=119, NET_CIPSOV4_RBM_OPTFMT=120, NET_CIPSOV4_RBM_STRICTVALID=121, NET_TCP_AVAIL_CONG_CONTROL=122, NET_TCP_ALLOWED_CONG_CONTROL=123, NET_TCP_MAX_SSTHRESH=124, NET_TCP_FRTO_RESPONSE=125, }; enum { NET_IPV4_ROUTE_FLUSH=1, NET_IPV4_ROUTE_MIN_DELAY=2, /* obsolete since 2.6.25 */ NET_IPV4_ROUTE_MAX_DELAY=3, /* obsolete since 2.6.25 */ NET_IPV4_ROUTE_GC_THRESH=4, NET_IPV4_ROUTE_MAX_SIZE=5, NET_IPV4_ROUTE_GC_MIN_INTERVAL=6, NET_IPV4_ROUTE_GC_TIMEOUT=7, NET_IPV4_ROUTE_GC_INTERVAL=8, /* obsolete since 2.6.38 */ NET_IPV4_ROUTE_REDIRECT_LOAD=9, NET_IPV4_ROUTE_REDIRECT_NUMBER=10, NET_IPV4_ROUTE_REDIRECT_SILENCE=11, NET_IPV4_ROUTE_ERROR_COST=12, NET_IPV4_ROUTE_ERROR_BURST=13, NET_IPV4_ROUTE_GC_ELASTICITY=14, NET_IPV4_ROUTE_MTU_EXPIRES=15, NET_IPV4_ROUTE_MIN_PMTU=16, NET_IPV4_ROUTE_MIN_ADVMSS=17, NET_IPV4_ROUTE_SECRET_INTERVAL=18, NET_IPV4_ROUTE_GC_MIN_INTERVAL_MS=19, }; enum { NET_PROTO_CONF_ALL=-2, NET_PROTO_CONF_DEFAULT=-3 /* And device ifindices ... */ }; enum { NET_IPV4_CONF_FORWARDING=1, NET_IPV4_CONF_MC_FORWARDING=2, NET_IPV4_CONF_PROXY_ARP=3, NET_IPV4_CONF_ACCEPT_REDIRECTS=4, NET_IPV4_CONF_SECURE_REDIRECTS=5, NET_IPV4_CONF_SEND_REDIRECTS=6, NET_IPV4_CONF_SHARED_MEDIA=7, NET_IPV4_CONF_RP_FILTER=8, NET_IPV4_CONF_ACCEPT_SOURCE_ROUTE=9, NET_IPV4_CONF_BOOTP_RELAY=10, NET_IPV4_CONF_LOG_MARTIANS=11, NET_IPV4_CONF_TAG=12, NET_IPV4_CONF_ARPFILTER=13, NET_IPV4_CONF_MEDIUM_ID=14, NET_IPV4_CONF_NOXFRM=15, NET_IPV4_CONF_NOPOLICY=16, NET_IPV4_CONF_FORCE_IGMP_VERSION=17, NET_IPV4_CONF_ARP_ANNOUNCE=18, NET_IPV4_CONF_ARP_IGNORE=19, NET_IPV4_CONF_PROMOTE_SECONDARIES=20, NET_IPV4_CONF_ARP_ACCEPT=21, NET_IPV4_CONF_ARP_NOTIFY=22, }; /* /proc/sys/net/ipv4/netfilter */ enum { NET_IPV4_NF_CONNTRACK_MAX=1, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_SYN_SENT=2, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_SYN_RECV=3, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_ESTABLISHED=4, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_FIN_WAIT=5, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_CLOSE_WAIT=6, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_LAST_ACK=7, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_TIME_WAIT=8, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_CLOSE=9, NET_IPV4_NF_CONNTRACK_UDP_TIMEOUT=10, NET_IPV4_NF_CONNTRACK_UDP_TIMEOUT_STREAM=11, NET_IPV4_NF_CONNTRACK_ICMP_TIMEOUT=12, NET_IPV4_NF_CONNTRACK_GENERIC_TIMEOUT=13, NET_IPV4_NF_CONNTRACK_BUCKETS=14, NET_IPV4_NF_CONNTRACK_LOG_INVALID=15, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_MAX_RETRANS=16, NET_IPV4_NF_CONNTRACK_TCP_LOOSE=17, NET_IPV4_NF_CONNTRACK_TCP_BE_LIBERAL=18, NET_IPV4_NF_CONNTRACK_TCP_MAX_RETRANS=19, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_CLOSED=20, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_WAIT=21, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_ECHOED=22, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_ESTABLISHED=23, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_SENT=24, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_RECD=25, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_ACK_SENT=26, NET_IPV4_NF_CONNTRACK_COUNT=27, NET_IPV4_NF_CONNTRACK_CHECKSUM=28, }; /* /proc/sys/net/ipv6 */ enum { NET_IPV6_CONF=16, NET_IPV6_NEIGH=17, NET_IPV6_ROUTE=18, NET_IPV6_ICMP=19, NET_IPV6_BINDV6ONLY=20, NET_IPV6_IP6FRAG_HIGH_THRESH=21, NET_IPV6_IP6FRAG_LOW_THRESH=22, NET_IPV6_IP6FRAG_TIME=23, NET_IPV6_IP6FRAG_SECRET_INTERVAL=24, NET_IPV6_MLD_MAX_MSF=25, }; enum { NET_IPV6_ROUTE_FLUSH=1, NET_IPV6_ROUTE_GC_THRESH=2, NET_IPV6_ROUTE_MAX_SIZE=3, NET_IPV6_ROUTE_GC_MIN_INTERVAL=4, NET_IPV6_ROUTE_GC_TIMEOUT=5, NET_IPV6_ROUTE_GC_INTERVAL=6, NET_IPV6_ROUTE_GC_ELASTICITY=7, NET_IPV6_ROUTE_MTU_EXPIRES=8, NET_IPV6_ROUTE_MIN_ADVMSS=9, NET_IPV6_ROUTE_GC_MIN_INTERVAL_MS=10 }; enum { NET_IPV6_FORWARDING=1, NET_IPV6_HOP_LIMIT=2, NET_IPV6_MTU=3, NET_IPV6_ACCEPT_RA=4, NET_IPV6_ACCEPT_REDIRECTS=5, NET_IPV6_AUTOCONF=6, NET_IPV6_DAD_TRANSMITS=7, NET_IPV6_RTR_SOLICITS=8, NET_IPV6_RTR_SOLICIT_INTERVAL=9, NET_IPV6_RTR_SOLICIT_DELAY=10, NET_IPV6_USE_TEMPADDR=11, NET_IPV6_TEMP_VALID_LFT=12, NET_IPV6_TEMP_PREFERED_LFT=13, NET_IPV6_REGEN_MAX_RETRY=14, NET_IPV6_MAX_DESYNC_FACTOR=15, NET_IPV6_MAX_ADDRESSES=16, NET_IPV6_FORCE_MLD_VERSION=17, NET_IPV6_ACCEPT_RA_DEFRTR=18, NET_IPV6_ACCEPT_RA_PINFO=19, NET_IPV6_ACCEPT_RA_RTR_PREF=20, NET_IPV6_RTR_PROBE_INTERVAL=21, NET_IPV6_ACCEPT_RA_RT_INFO_MAX_PLEN=22, NET_IPV6_PROXY_NDP=23, NET_IPV6_ACCEPT_SOURCE_ROUTE=25, NET_IPV6_ACCEPT_RA_FROM_LOCAL=26, NET_IPV6_ACCEPT_RA_RT_INFO_MIN_PLEN=27, __NET_IPV6_MAX }; /* /proc/sys/net/ipv6/icmp */ enum { NET_IPV6_ICMP_RATELIMIT=1 }; /* /proc/sys/net//neigh/ */ enum { NET_NEIGH_MCAST_SOLICIT=1, NET_NEIGH_UCAST_SOLICIT=2, NET_NEIGH_APP_SOLICIT=3, NET_NEIGH_RETRANS_TIME=4, NET_NEIGH_REACHABLE_TIME=5, NET_NEIGH_DELAY_PROBE_TIME=6, NET_NEIGH_GC_STALE_TIME=7, NET_NEIGH_UNRES_QLEN=8, NET_NEIGH_PROXY_QLEN=9, NET_NEIGH_ANYCAST_DELAY=10, NET_NEIGH_PROXY_DELAY=11, NET_NEIGH_LOCKTIME=12, NET_NEIGH_GC_INTERVAL=13, NET_NEIGH_GC_THRESH1=14, NET_NEIGH_GC_THRESH2=15, NET_NEIGH_GC_THRESH3=16, NET_NEIGH_RETRANS_TIME_MS=17, NET_NEIGH_REACHABLE_TIME_MS=18, }; /* /proc/sys/net/dccp */ enum { NET_DCCP_DEFAULT=1, }; /* /proc/sys/net/ipx */ enum { NET_IPX_PPROP_BROADCASTING=1, NET_IPX_FORWARDING=2 }; /* /proc/sys/net/llc */ enum { NET_LLC2=1, NET_LLC_STATION=2, }; /* /proc/sys/net/llc/llc2 */ enum { NET_LLC2_TIMEOUT=1, }; /* /proc/sys/net/llc/station */ enum { NET_LLC_STATION_ACK_TIMEOUT=1, }; /* /proc/sys/net/llc/llc2/timeout */ enum { NET_LLC2_ACK_TIMEOUT=1, NET_LLC2_P_TIMEOUT=2, NET_LLC2_REJ_TIMEOUT=3, NET_LLC2_BUSY_TIMEOUT=4, }; /* /proc/sys/net/appletalk */ enum { NET_ATALK_AARP_EXPIRY_TIME=1, NET_ATALK_AARP_TICK_TIME=2, NET_ATALK_AARP_RETRANSMIT_LIMIT=3, NET_ATALK_AARP_RESOLVE_TIME=4 }; /* /proc/sys/net/netrom */ enum { NET_NETROM_DEFAULT_PATH_QUALITY=1, NET_NETROM_OBSOLESCENCE_COUNT_INITIALISER=2, NET_NETROM_NETWORK_TTL_INITIALISER=3, NET_NETROM_TRANSPORT_TIMEOUT=4, NET_NETROM_TRANSPORT_MAXIMUM_TRIES=5, NET_NETROM_TRANSPORT_ACKNOWLEDGE_DELAY=6, NET_NETROM_TRANSPORT_BUSY_DELAY=7, NET_NETROM_TRANSPORT_REQUESTED_WINDOW_SIZE=8, NET_NETROM_TRANSPORT_NO_ACTIVITY_TIMEOUT=9, NET_NETROM_ROUTING_CONTROL=10, NET_NETROM_LINK_FAILS_COUNT=11, NET_NETROM_RESET=12 }; /* /proc/sys/net/ax25 */ enum { NET_AX25_IP_DEFAULT_MODE=1, NET_AX25_DEFAULT_MODE=2, NET_AX25_BACKOFF_TYPE=3, NET_AX25_CONNECT_MODE=4, NET_AX25_STANDARD_WINDOW=5, NET_AX25_EXTENDED_WINDOW=6, NET_AX25_T1_TIMEOUT=7, NET_AX25_T2_TIMEOUT=8, NET_AX25_T3_TIMEOUT=9, NET_AX25_IDLE_TIMEOUT=10, NET_AX25_N2=11, NET_AX25_PACLEN=12, NET_AX25_PROTOCOL=13, NET_AX25_DAMA_SLAVE_TIMEOUT=14 }; /* /proc/sys/net/rose */ enum { NET_ROSE_RESTART_REQUEST_TIMEOUT=1, NET_ROSE_CALL_REQUEST_TIMEOUT=2, NET_ROSE_RESET_REQUEST_TIMEOUT=3, NET_ROSE_CLEAR_REQUEST_TIMEOUT=4, NET_ROSE_ACK_HOLD_BACK_TIMEOUT=5, NET_ROSE_ROUTING_CONTROL=6, NET_ROSE_LINK_FAIL_TIMEOUT=7, NET_ROSE_MAX_VCS=8, NET_ROSE_WINDOW_SIZE=9, NET_ROSE_NO_ACTIVITY_TIMEOUT=10 }; /* /proc/sys/net/x25 */ enum { NET_X25_RESTART_REQUEST_TIMEOUT=1, NET_X25_CALL_REQUEST_TIMEOUT=2, NET_X25_RESET_REQUEST_TIMEOUT=3, NET_X25_CLEAR_REQUEST_TIMEOUT=4, NET_X25_ACK_HOLD_BACK_TIMEOUT=5, NET_X25_FORWARD=6 }; /* /proc/sys/net/token-ring */ enum { NET_TR_RIF_TIMEOUT=1 }; /* /proc/sys/net/decnet/ */ enum { NET_DECNET_NODE_TYPE = 1, NET_DECNET_NODE_ADDRESS = 2, NET_DECNET_NODE_NAME = 3, NET_DECNET_DEFAULT_DEVICE = 4, NET_DECNET_TIME_WAIT = 5, NET_DECNET_DN_COUNT = 6, NET_DECNET_DI_COUNT = 7, NET_DECNET_DR_COUNT = 8, NET_DECNET_DST_GC_INTERVAL = 9, NET_DECNET_CONF = 10, NET_DECNET_NO_FC_MAX_CWND = 11, NET_DECNET_MEM = 12, NET_DECNET_RMEM = 13, NET_DECNET_WMEM = 14, NET_DECNET_DEBUG_LEVEL = 255 }; /* /proc/sys/net/decnet/conf/ */ enum { NET_DECNET_CONF_LOOPBACK = -2, NET_DECNET_CONF_DDCMP = -3, NET_DECNET_CONF_PPP = -4, NET_DECNET_CONF_X25 = -5, NET_DECNET_CONF_GRE = -6, NET_DECNET_CONF_ETHER = -7 /* ... and ifindex of devices */ }; /* /proc/sys/net/decnet/conf// */ enum { NET_DECNET_CONF_DEV_PRIORITY = 1, NET_DECNET_CONF_DEV_T1 = 2, NET_DECNET_CONF_DEV_T2 = 3, NET_DECNET_CONF_DEV_T3 = 4, NET_DECNET_CONF_DEV_FORWARDING = 5, NET_DECNET_CONF_DEV_BLKSIZE = 6, NET_DECNET_CONF_DEV_STATE = 7 }; /* /proc/sys/net/sctp */ enum { NET_SCTP_RTO_INITIAL = 1, NET_SCTP_RTO_MIN = 2, NET_SCTP_RTO_MAX = 3, NET_SCTP_RTO_ALPHA = 4, NET_SCTP_RTO_BETA = 5, NET_SCTP_VALID_COOKIE_LIFE = 6, NET_SCTP_ASSOCIATION_MAX_RETRANS = 7, NET_SCTP_PATH_MAX_RETRANS = 8, NET_SCTP_MAX_INIT_RETRANSMITS = 9, NET_SCTP_HB_INTERVAL = 10, NET_SCTP_PRESERVE_ENABLE = 11, NET_SCTP_MAX_BURST = 12, NET_SCTP_ADDIP_ENABLE = 13, NET_SCTP_PRSCTP_ENABLE = 14, NET_SCTP_SNDBUF_POLICY = 15, NET_SCTP_SACK_TIMEOUT = 16, NET_SCTP_RCVBUF_POLICY = 17, }; /* /proc/sys/net/bridge */ enum { NET_BRIDGE_NF_CALL_ARPTABLES = 1, NET_BRIDGE_NF_CALL_IPTABLES = 2, NET_BRIDGE_NF_CALL_IP6TABLES = 3, NET_BRIDGE_NF_FILTER_VLAN_TAGGED = 4, NET_BRIDGE_NF_FILTER_PPPOE_TAGGED = 5, }; /* CTL_FS names: */ enum { FS_NRINODE=1, /* int:current number of allocated inodes */ FS_STATINODE=2, FS_MAXINODE=3, /* int:maximum number of inodes that can be allocated */ FS_NRDQUOT=4, /* int:current number of allocated dquots */ FS_MAXDQUOT=5, /* int:maximum number of dquots that can be allocated */ FS_NRFILE=6, /* int:current number of allocated filedescriptors */ FS_MAXFILE=7, /* int:maximum number of filedescriptors that can be allocated */ FS_DENTRY=8, FS_NRSUPER=9, /* int:current number of allocated super_blocks */ FS_MAXSUPER=10, /* int:maximum number of super_blocks that can be allocated */ FS_OVERFLOWUID=11, /* int: overflow UID */ FS_OVERFLOWGID=12, /* int: overflow GID */ FS_LEASES=13, /* int: leases enabled */ FS_DIR_NOTIFY=14, /* int: directory notification enabled */ FS_LEASE_TIME=15, /* int: maximum time to wait for a lease break */ FS_DQSTATS=16, /* disc quota usage statistics and control */ FS_XFS=17, /* struct: control xfs parameters */ FS_AIO_NR=18, /* current system-wide number of aio requests */ FS_AIO_MAX_NR=19, /* system-wide maximum number of aio requests */ FS_INOTIFY=20, /* inotify submenu */ FS_OCFS2=988, /* ocfs2 */ }; /* /proc/sys/fs/quota/ */ enum { FS_DQ_LOOKUPS = 1, FS_DQ_DROPS = 2, FS_DQ_READS = 3, FS_DQ_WRITES = 4, FS_DQ_CACHE_HITS = 5, FS_DQ_ALLOCATED = 6, FS_DQ_FREE = 7, FS_DQ_SYNCS = 8, FS_DQ_WARNINGS = 9, }; /* CTL_DEBUG names: */ /* CTL_DEV names: */ enum { DEV_CDROM=1, DEV_HWMON=2, DEV_PARPORT=3, DEV_RAID=4, DEV_MAC_HID=5, DEV_SCSI=6, DEV_IPMI=7, }; /* /proc/sys/dev/cdrom */ enum { DEV_CDROM_INFO=1, DEV_CDROM_AUTOCLOSE=2, DEV_CDROM_AUTOEJECT=3, DEV_CDROM_DEBUG=4, DEV_CDROM_LOCK=5, DEV_CDROM_CHECK_MEDIA=6 }; /* /proc/sys/dev/parport */ enum { DEV_PARPORT_DEFAULT=-3 }; /* /proc/sys/dev/raid */ enum { DEV_RAID_SPEED_LIMIT_MIN=1, DEV_RAID_SPEED_LIMIT_MAX=2 }; /* /proc/sys/dev/parport/default */ enum { DEV_PARPORT_DEFAULT_TIMESLICE=1, DEV_PARPORT_DEFAULT_SPINTIME=2 }; /* /proc/sys/dev/parport/parport n */ enum { DEV_PARPORT_SPINTIME=1, DEV_PARPORT_BASE_ADDR=2, DEV_PARPORT_IRQ=3, DEV_PARPORT_DMA=4, DEV_PARPORT_MODES=5, DEV_PARPORT_DEVICES=6, DEV_PARPORT_AUTOPROBE=16 }; /* /proc/sys/dev/parport/parport n/devices/ */ enum { DEV_PARPORT_DEVICES_ACTIVE=-3, }; /* /proc/sys/dev/parport/parport n/devices/device n */ enum { DEV_PARPORT_DEVICE_TIMESLICE=1, }; /* /proc/sys/dev/mac_hid */ enum { DEV_MAC_HID_KEYBOARD_SENDS_LINUX_KEYCODES=1, DEV_MAC_HID_KEYBOARD_LOCK_KEYCODES=2, DEV_MAC_HID_MOUSE_BUTTON_EMULATION=3, DEV_MAC_HID_MOUSE_BUTTON2_KEYCODE=4, DEV_MAC_HID_MOUSE_BUTTON3_KEYCODE=5, DEV_MAC_HID_ADB_MOUSE_SENDS_KEYCODES=6 }; /* /proc/sys/dev/scsi */ enum { DEV_SCSI_LOGGING_LEVEL=1, }; /* /proc/sys/dev/ipmi */ enum { DEV_IPMI_POWEROFF_POWERCYCLE=1, }; /* /proc/sys/abi */ enum { ABI_DEFHANDLER_COFF=1, /* default handler for coff binaries */ ABI_DEFHANDLER_ELF=2, /* default handler for ELF binaries */ ABI_DEFHANDLER_LCALL7=3,/* default handler for procs using lcall7 */ ABI_DEFHANDLER_LIBCSO=4,/* default handler for an libc.so ELF interp */ ABI_TRACE=5, /* tracing flags */ ABI_FAKE_UTSNAME=6, /* fake target utsname information */ }; #endif /* _LINUX_SYSCTL_H */ linux/omap3isp.h000064400000050565151027430560007625 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * omap3isp.h * * TI OMAP3 ISP - User-space API * * Copyright (C) 2010 Nokia Corporation * Copyright (C) 2009 Texas Instruments, Inc. * * Contacts: Laurent Pinchart * Sakari Ailus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OMAP3_ISP_USER_H #define OMAP3_ISP_USER_H #include #include /* * Private IOCTLs * * VIDIOC_OMAP3ISP_CCDC_CFG: Set CCDC configuration * VIDIOC_OMAP3ISP_PRV_CFG: Set preview engine configuration * VIDIOC_OMAP3ISP_AEWB_CFG: Set AEWB module configuration * VIDIOC_OMAP3ISP_HIST_CFG: Set histogram module configuration * VIDIOC_OMAP3ISP_AF_CFG: Set auto-focus module configuration * VIDIOC_OMAP3ISP_STAT_REQ: Read statistics (AEWB/AF/histogram) data * VIDIOC_OMAP3ISP_STAT_EN: Enable/disable a statistics module */ #define VIDIOC_OMAP3ISP_CCDC_CFG \ _IOWR('V', BASE_VIDIOC_PRIVATE + 1, struct omap3isp_ccdc_update_config) #define VIDIOC_OMAP3ISP_PRV_CFG \ _IOWR('V', BASE_VIDIOC_PRIVATE + 2, struct omap3isp_prev_update_config) #define VIDIOC_OMAP3ISP_AEWB_CFG \ _IOWR('V', BASE_VIDIOC_PRIVATE + 3, struct omap3isp_h3a_aewb_config) #define VIDIOC_OMAP3ISP_HIST_CFG \ _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct omap3isp_hist_config) #define VIDIOC_OMAP3ISP_AF_CFG \ _IOWR('V', BASE_VIDIOC_PRIVATE + 5, struct omap3isp_h3a_af_config) #define VIDIOC_OMAP3ISP_STAT_REQ \ _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct omap3isp_stat_data) #define VIDIOC_OMAP3ISP_STAT_REQ_TIME32 \ _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct omap3isp_stat_data_time32) #define VIDIOC_OMAP3ISP_STAT_EN \ _IOWR('V', BASE_VIDIOC_PRIVATE + 7, unsigned long) /* * Events * * V4L2_EVENT_OMAP3ISP_AEWB: AEWB statistics data ready * V4L2_EVENT_OMAP3ISP_AF: AF statistics data ready * V4L2_EVENT_OMAP3ISP_HIST: Histogram statistics data ready */ #define V4L2_EVENT_OMAP3ISP_CLASS (V4L2_EVENT_PRIVATE_START | 0x100) #define V4L2_EVENT_OMAP3ISP_AEWB (V4L2_EVENT_OMAP3ISP_CLASS | 0x1) #define V4L2_EVENT_OMAP3ISP_AF (V4L2_EVENT_OMAP3ISP_CLASS | 0x2) #define V4L2_EVENT_OMAP3ISP_HIST (V4L2_EVENT_OMAP3ISP_CLASS | 0x3) struct omap3isp_stat_event_status { __u32 frame_number; __u16 config_counter; __u8 buf_err; }; /* AE/AWB related structures and flags*/ /* H3A Range Constants */ #define OMAP3ISP_AEWB_MAX_SATURATION_LIM 1023 #define OMAP3ISP_AEWB_MIN_WIN_H 2 #define OMAP3ISP_AEWB_MAX_WIN_H 256 #define OMAP3ISP_AEWB_MIN_WIN_W 6 #define OMAP3ISP_AEWB_MAX_WIN_W 256 #define OMAP3ISP_AEWB_MIN_WINVC 1 #define OMAP3ISP_AEWB_MIN_WINHC 1 #define OMAP3ISP_AEWB_MAX_WINVC 128 #define OMAP3ISP_AEWB_MAX_WINHC 36 #define OMAP3ISP_AEWB_MAX_WINSTART 4095 #define OMAP3ISP_AEWB_MIN_SUB_INC 2 #define OMAP3ISP_AEWB_MAX_SUB_INC 32 #define OMAP3ISP_AEWB_MAX_BUF_SIZE 83600 #define OMAP3ISP_AF_IIRSH_MIN 0 #define OMAP3ISP_AF_IIRSH_MAX 4095 #define OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MIN 1 #define OMAP3ISP_AF_PAXEL_HORIZONTAL_COUNT_MAX 36 #define OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MIN 1 #define OMAP3ISP_AF_PAXEL_VERTICAL_COUNT_MAX 128 #define OMAP3ISP_AF_PAXEL_INCREMENT_MIN 2 #define OMAP3ISP_AF_PAXEL_INCREMENT_MAX 32 #define OMAP3ISP_AF_PAXEL_HEIGHT_MIN 2 #define OMAP3ISP_AF_PAXEL_HEIGHT_MAX 256 #define OMAP3ISP_AF_PAXEL_WIDTH_MIN 16 #define OMAP3ISP_AF_PAXEL_WIDTH_MAX 256 #define OMAP3ISP_AF_PAXEL_HZSTART_MIN 1 #define OMAP3ISP_AF_PAXEL_HZSTART_MAX 4095 #define OMAP3ISP_AF_PAXEL_VTSTART_MIN 0 #define OMAP3ISP_AF_PAXEL_VTSTART_MAX 4095 #define OMAP3ISP_AF_THRESHOLD_MAX 255 #define OMAP3ISP_AF_COEF_MAX 4095 #define OMAP3ISP_AF_PAXEL_SIZE 48 #define OMAP3ISP_AF_MAX_BUF_SIZE 221184 /** * struct omap3isp_h3a_aewb_config - AE AWB configuration reset values * saturation_limit: Saturation limit. * @win_height: Window Height. Range 2 - 256, even values only. * @win_width: Window Width. Range 6 - 256, even values only. * @ver_win_count: Vertical Window Count. Range 1 - 128. * @hor_win_count: Horizontal Window Count. Range 1 - 36. * @ver_win_start: Vertical Window Start. Range 0 - 4095. * @hor_win_start: Horizontal Window Start. Range 0 - 4095. * @blk_ver_win_start: Black Vertical Windows Start. Range 0 - 4095. * @blk_win_height: Black Window Height. Range 2 - 256, even values only. * @subsample_ver_inc: Subsample Vertical points increment Range 2 - 32, even * values only. * @subsample_hor_inc: Subsample Horizontal points increment Range 2 - 32, even * values only. * @alaw_enable: AEW ALAW EN flag. */ struct omap3isp_h3a_aewb_config { /* * Common fields. * They should be the first ones and must be in the same order as in * ispstat_generic_config struct. */ __u32 buf_size; __u16 config_counter; /* Private fields */ __u16 saturation_limit; __u16 win_height; __u16 win_width; __u16 ver_win_count; __u16 hor_win_count; __u16 ver_win_start; __u16 hor_win_start; __u16 blk_ver_win_start; __u16 blk_win_height; __u16 subsample_ver_inc; __u16 subsample_hor_inc; __u8 alaw_enable; }; /** * struct omap3isp_stat_data - Statistic data sent to or received from user * @ts: Timestamp of returned framestats. * @buf: Pointer to pass to user. * @frame_number: Frame number of requested stats. * @cur_frame: Current frame number being processed. * @config_counter: Number of the configuration associated with the data. */ struct omap3isp_stat_data { struct timeval ts; void *buf; __u32 buf_size; __u16 frame_number; __u16 cur_frame; __u16 config_counter; }; /* Histogram related structs */ /* Flags for number of bins */ #define OMAP3ISP_HIST_BINS_32 0 #define OMAP3ISP_HIST_BINS_64 1 #define OMAP3ISP_HIST_BINS_128 2 #define OMAP3ISP_HIST_BINS_256 3 /* Number of bins * 4 colors * 4-bytes word */ #define OMAP3ISP_HIST_MEM_SIZE_BINS(n) ((1 << ((n)+5))*4*4) #define OMAP3ISP_HIST_MEM_SIZE 1024 #define OMAP3ISP_HIST_MIN_REGIONS 1 #define OMAP3ISP_HIST_MAX_REGIONS 4 #define OMAP3ISP_HIST_MAX_WB_GAIN 255 #define OMAP3ISP_HIST_MIN_WB_GAIN 0 #define OMAP3ISP_HIST_MAX_BIT_WIDTH 14 #define OMAP3ISP_HIST_MIN_BIT_WIDTH 8 #define OMAP3ISP_HIST_MAX_WG 4 #define OMAP3ISP_HIST_MAX_BUF_SIZE 4096 /* Source */ #define OMAP3ISP_HIST_SOURCE_CCDC 0 #define OMAP3ISP_HIST_SOURCE_MEM 1 /* CFA pattern */ #define OMAP3ISP_HIST_CFA_BAYER 0 #define OMAP3ISP_HIST_CFA_FOVEONX3 1 struct omap3isp_hist_region { __u16 h_start; __u16 h_end; __u16 v_start; __u16 v_end; }; struct omap3isp_hist_config { /* * Common fields. * They should be the first ones and must be in the same order as in * ispstat_generic_config struct. */ __u32 buf_size; __u16 config_counter; __u8 num_acc_frames; /* Num of image frames to be processed and accumulated for each histogram frame */ __u16 hist_bins; /* number of bins: 32, 64, 128, or 256 */ __u8 cfa; /* BAYER or FOVEON X3 */ __u8 wg[OMAP3ISP_HIST_MAX_WG]; /* White Balance Gain */ __u8 num_regions; /* number of regions to be configured */ struct omap3isp_hist_region region[OMAP3ISP_HIST_MAX_REGIONS]; }; /* Auto Focus related structs */ #define OMAP3ISP_AF_NUM_COEF 11 enum omap3isp_h3a_af_fvmode { OMAP3ISP_AF_MODE_SUMMED = 0, OMAP3ISP_AF_MODE_PEAK = 1 }; /* Red, Green, and blue pixel location in the AF windows */ enum omap3isp_h3a_af_rgbpos { OMAP3ISP_AF_GR_GB_BAYER = 0, /* GR and GB as Bayer pattern */ OMAP3ISP_AF_RG_GB_BAYER = 1, /* RG and GB as Bayer pattern */ OMAP3ISP_AF_GR_BG_BAYER = 2, /* GR and BG as Bayer pattern */ OMAP3ISP_AF_RG_BG_BAYER = 3, /* RG and BG as Bayer pattern */ OMAP3ISP_AF_GG_RB_CUSTOM = 4, /* GG and RB as custom pattern */ OMAP3ISP_AF_RB_GG_CUSTOM = 5 /* RB and GG as custom pattern */ }; /* Contains the information regarding the Horizontal Median Filter */ struct omap3isp_h3a_af_hmf { __u8 enable; /* Status of Horizontal Median Filter */ __u8 threshold; /* Threshold Value for Horizontal Median Filter */ }; /* Contains the information regarding the IIR Filters */ struct omap3isp_h3a_af_iir { __u16 h_start; /* IIR horizontal start */ __u16 coeff_set0[OMAP3ISP_AF_NUM_COEF]; /* Filter coefficient, set 0 */ __u16 coeff_set1[OMAP3ISP_AF_NUM_COEF]; /* Filter coefficient, set 1 */ }; /* Contains the information regarding the Paxels Structure in AF Engine */ struct omap3isp_h3a_af_paxel { __u16 h_start; /* Horizontal Start Position */ __u16 v_start; /* Vertical Start Position */ __u8 width; /* Width of the Paxel */ __u8 height; /* Height of the Paxel */ __u8 h_cnt; /* Horizontal Count */ __u8 v_cnt; /* vertical Count */ __u8 line_inc; /* Line Increment */ }; /* Contains the parameters required for hardware set up of AF Engine */ struct omap3isp_h3a_af_config { /* * Common fields. * They should be the first ones and must be in the same order as in * ispstat_generic_config struct. */ __u32 buf_size; __u16 config_counter; struct omap3isp_h3a_af_hmf hmf; /* HMF configurations */ struct omap3isp_h3a_af_iir iir; /* IIR filter configurations */ struct omap3isp_h3a_af_paxel paxel; /* Paxel parameters */ enum omap3isp_h3a_af_rgbpos rgb_pos; /* RGB Positions */ enum omap3isp_h3a_af_fvmode fvmode; /* Accumulator mode */ __u8 alaw_enable; /* AF ALAW status */ }; /* ISP CCDC structs */ /* Abstraction layer CCDC configurations */ #define OMAP3ISP_CCDC_ALAW (1 << 0) #define OMAP3ISP_CCDC_LPF (1 << 1) #define OMAP3ISP_CCDC_BLCLAMP (1 << 2) #define OMAP3ISP_CCDC_BCOMP (1 << 3) #define OMAP3ISP_CCDC_FPC (1 << 4) #define OMAP3ISP_CCDC_CULL (1 << 5) #define OMAP3ISP_CCDC_CONFIG_LSC (1 << 7) #define OMAP3ISP_CCDC_TBL_LSC (1 << 8) #define OMAP3ISP_RGB_MAX 3 /* Enumeration constants for Alaw input width */ enum omap3isp_alaw_ipwidth { OMAP3ISP_ALAW_BIT12_3 = 0x3, OMAP3ISP_ALAW_BIT11_2 = 0x4, OMAP3ISP_ALAW_BIT10_1 = 0x5, OMAP3ISP_ALAW_BIT9_0 = 0x6 }; /** * struct omap3isp_ccdc_lsc_config - LSC configuration * @offset: Table Offset of the gain table. * @gain_mode_n: Vertical dimension of a paxel in LSC configuration. * @gain_mode_m: Horizontal dimension of a paxel in LSC configuration. * @gain_format: Gain table format. * @fmtsph: Start pixel horizontal from start of the HS sync pulse. * @fmtlnh: Number of pixels in horizontal direction to use for the data * reformatter. * @fmtslv: Start line from start of VS sync pulse for the data reformatter. * @fmtlnv: Number of lines in vertical direction for the data reformatter. * @initial_x: X position, in pixels, of the first active pixel in reference * to the first active paxel. Must be an even number. * @initial_y: Y position, in pixels, of the first active pixel in reference * to the first active paxel. Must be an even number. * @size: Size of LSC gain table. Filled when loaded from userspace. */ struct omap3isp_ccdc_lsc_config { __u16 offset; __u8 gain_mode_n; __u8 gain_mode_m; __u8 gain_format; __u16 fmtsph; __u16 fmtlnh; __u16 fmtslv; __u16 fmtlnv; __u8 initial_x; __u8 initial_y; __u32 size; }; /** * struct omap3isp_ccdc_bclamp - Optical & Digital black clamp subtract * @obgain: Optical black average gain. * @obstpixel: Start Pixel w.r.t. HS pulse in Optical black sample. * @oblines: Optical Black Sample lines. * @oblen: Optical Black Sample Length. * @dcsubval: Digital Black Clamp subtract value. */ struct omap3isp_ccdc_bclamp { __u8 obgain; __u8 obstpixel; __u8 oblines; __u8 oblen; __u16 dcsubval; }; /** * struct omap3isp_ccdc_fpc - Faulty Pixels Correction * @fpnum: Number of faulty pixels to be corrected in the frame. * @fpcaddr: Memory address of the FPC Table */ struct omap3isp_ccdc_fpc { __u16 fpnum; __u32 fpcaddr; }; /** * struct omap3isp_ccdc_blcomp - Black Level Compensation parameters * @b_mg: B/Mg pixels. 2's complement. -128 to +127. * @gb_g: Gb/G pixels. 2's complement. -128 to +127. * @gr_cy: Gr/Cy pixels. 2's complement. -128 to +127. * @r_ye: R/Ye pixels. 2's complement. -128 to +127. */ struct omap3isp_ccdc_blcomp { __u8 b_mg; __u8 gb_g; __u8 gr_cy; __u8 r_ye; }; /** * omap3isp_ccdc_culling - Culling parameters * @v_pattern: Vertical culling pattern. * @h_odd: Horizontal Culling pattern for odd lines. * @h_even: Horizontal Culling pattern for even lines. */ struct omap3isp_ccdc_culling { __u8 v_pattern; __u16 h_odd; __u16 h_even; }; /** * omap3isp_ccdc_update_config - CCDC configuration * @update: Specifies which CCDC registers should be updated. * @flag: Specifies which CCDC functions should be enabled. * @alawip: Enable/Disable A-Law compression. * @bclamp: Black clamp control register. * @blcomp: Black level compensation value for RGrGbB Pixels. 2's complement. * @fpc: Number of faulty pixels corrected in the frame, address of FPC table. * @cull: Cull control register. * @lsc: Pointer to LSC gain table. */ struct omap3isp_ccdc_update_config { __u16 update; __u16 flag; enum omap3isp_alaw_ipwidth alawip; struct omap3isp_ccdc_bclamp *bclamp; struct omap3isp_ccdc_blcomp *blcomp; struct omap3isp_ccdc_fpc *fpc; struct omap3isp_ccdc_lsc_config *lsc_cfg; struct omap3isp_ccdc_culling *cull; __u8 *lsc; }; /* Preview configurations */ #define OMAP3ISP_PREV_LUMAENH (1 << 0) #define OMAP3ISP_PREV_INVALAW (1 << 1) #define OMAP3ISP_PREV_HRZ_MED (1 << 2) #define OMAP3ISP_PREV_CFA (1 << 3) #define OMAP3ISP_PREV_CHROMA_SUPP (1 << 4) #define OMAP3ISP_PREV_WB (1 << 5) #define OMAP3ISP_PREV_BLKADJ (1 << 6) #define OMAP3ISP_PREV_RGB2RGB (1 << 7) #define OMAP3ISP_PREV_COLOR_CONV (1 << 8) #define OMAP3ISP_PREV_YC_LIMIT (1 << 9) #define OMAP3ISP_PREV_DEFECT_COR (1 << 10) /* Bit 11 was OMAP3ISP_PREV_GAMMABYPASS, now merged with OMAP3ISP_PREV_GAMMA */ #define OMAP3ISP_PREV_DRK_FRM_CAPTURE (1 << 12) #define OMAP3ISP_PREV_DRK_FRM_SUBTRACT (1 << 13) #define OMAP3ISP_PREV_LENS_SHADING (1 << 14) #define OMAP3ISP_PREV_NF (1 << 15) #define OMAP3ISP_PREV_GAMMA (1 << 16) #define OMAP3ISP_PREV_NF_TBL_SIZE 64 #define OMAP3ISP_PREV_CFA_TBL_SIZE 576 #define OMAP3ISP_PREV_CFA_BLK_SIZE (OMAP3ISP_PREV_CFA_TBL_SIZE / 4) #define OMAP3ISP_PREV_GAMMA_TBL_SIZE 1024 #define OMAP3ISP_PREV_YENH_TBL_SIZE 128 #define OMAP3ISP_PREV_DETECT_CORRECT_CHANNELS 4 /** * struct omap3isp_prev_hmed - Horizontal Median Filter * @odddist: Distance between consecutive pixels of same color in the odd line. * @evendist: Distance between consecutive pixels of same color in the even * line. * @thres: Horizontal median filter threshold. */ struct omap3isp_prev_hmed { __u8 odddist; __u8 evendist; __u8 thres; }; /* * Enumeration for CFA Formats supported by preview */ enum omap3isp_cfa_fmt { OMAP3ISP_CFAFMT_BAYER, OMAP3ISP_CFAFMT_SONYVGA, OMAP3ISP_CFAFMT_RGBFOVEON, OMAP3ISP_CFAFMT_DNSPL, OMAP3ISP_CFAFMT_HONEYCOMB, OMAP3ISP_CFAFMT_RRGGBBFOVEON }; /** * struct omap3isp_prev_cfa - CFA Interpolation * @format: CFA Format Enum value supported by preview. * @gradthrs_vert: CFA Gradient Threshold - Vertical. * @gradthrs_horz: CFA Gradient Threshold - Horizontal. * @table: Pointer to the CFA table. */ struct omap3isp_prev_cfa { enum omap3isp_cfa_fmt format; __u8 gradthrs_vert; __u8 gradthrs_horz; __u32 table[4][OMAP3ISP_PREV_CFA_BLK_SIZE]; }; /** * struct omap3isp_prev_csup - Chrominance Suppression * @gain: Gain. * @thres: Threshold. * @hypf_en: Flag to enable/disable the High Pass Filter. */ struct omap3isp_prev_csup { __u8 gain; __u8 thres; __u8 hypf_en; }; /** * struct omap3isp_prev_wbal - White Balance * @dgain: Digital gain (U10Q8). * @coef3: White balance gain - COEF 3 (U8Q5). * @coef2: White balance gain - COEF 2 (U8Q5). * @coef1: White balance gain - COEF 1 (U8Q5). * @coef0: White balance gain - COEF 0 (U8Q5). */ struct omap3isp_prev_wbal { __u16 dgain; __u8 coef3; __u8 coef2; __u8 coef1; __u8 coef0; }; /** * struct omap3isp_prev_blkadj - Black Level Adjustment * @red: Black level offset adjustment for Red in 2's complement format * @green: Black level offset adjustment for Green in 2's complement format * @blue: Black level offset adjustment for Blue in 2's complement format */ struct omap3isp_prev_blkadj { /*Black level offset adjustment for Red in 2's complement format */ __u8 red; /*Black level offset adjustment for Green in 2's complement format */ __u8 green; /* Black level offset adjustment for Blue in 2's complement format */ __u8 blue; }; /** * struct omap3isp_prev_rgbtorgb - RGB to RGB Blending * @matrix: Blending values(S12Q8 format) * [RR] [GR] [BR] * [RG] [GG] [BG] * [RB] [GB] [BB] * @offset: Blending offset value for R,G,B in 2's complement integer format. */ struct omap3isp_prev_rgbtorgb { __u16 matrix[OMAP3ISP_RGB_MAX][OMAP3ISP_RGB_MAX]; __u16 offset[OMAP3ISP_RGB_MAX]; }; /** * struct omap3isp_prev_csc - Color Space Conversion from RGB-YCbYCr * @matrix: Color space conversion coefficients(S10Q8) * [CSCRY] [CSCGY] [CSCBY] * [CSCRCB] [CSCGCB] [CSCBCB] * [CSCRCR] [CSCGCR] [CSCBCR] * @offset: CSC offset values for Y offset, CB offset and CR offset respectively */ struct omap3isp_prev_csc { __u16 matrix[OMAP3ISP_RGB_MAX][OMAP3ISP_RGB_MAX]; __s16 offset[OMAP3ISP_RGB_MAX]; }; /** * struct omap3isp_prev_yclimit - Y, C Value Limit * @minC: Minimum C value * @maxC: Maximum C value * @minY: Minimum Y value * @maxY: Maximum Y value */ struct omap3isp_prev_yclimit { __u8 minC; __u8 maxC; __u8 minY; __u8 maxY; }; /** * struct omap3isp_prev_dcor - Defect correction * @couplet_mode_en: Flag to enable or disable the couplet dc Correction in NF * @detect_correct: Thresholds for correction bit 0:10 detect 16:25 correct */ struct omap3isp_prev_dcor { __u8 couplet_mode_en; __u32 detect_correct[OMAP3ISP_PREV_DETECT_CORRECT_CHANNELS]; }; /** * struct omap3isp_prev_nf - Noise Filter * @spread: Spread value to be used in Noise Filter * @table: Pointer to the Noise Filter table */ struct omap3isp_prev_nf { __u8 spread; __u32 table[OMAP3ISP_PREV_NF_TBL_SIZE]; }; /** * struct omap3isp_prev_gtables - Gamma correction tables * @red: Array for red gamma table. * @green: Array for green gamma table. * @blue: Array for blue gamma table. */ struct omap3isp_prev_gtables { __u32 red[OMAP3ISP_PREV_GAMMA_TBL_SIZE]; __u32 green[OMAP3ISP_PREV_GAMMA_TBL_SIZE]; __u32 blue[OMAP3ISP_PREV_GAMMA_TBL_SIZE]; }; /** * struct omap3isp_prev_luma - Luma enhancement * @table: Array for luma enhancement table. */ struct omap3isp_prev_luma { __u32 table[OMAP3ISP_PREV_YENH_TBL_SIZE]; }; /** * struct omap3isp_prev_update_config - Preview engine configuration (user) * @update: Specifies which ISP Preview registers should be updated. * @flag: Specifies which ISP Preview functions should be enabled. * @shading_shift: 3bit value of shift used in shading compensation. * @luma: Pointer to luma enhancement structure. * @hmed: Pointer to structure containing the odd and even distance. * between the pixels in the image along with the filter threshold. * @cfa: Pointer to structure containing the CFA interpolation table, CFA. * format in the image, vertical and horizontal gradient threshold. * @csup: Pointer to Structure for Chrominance Suppression coefficients. * @wbal: Pointer to structure for White Balance. * @blkadj: Pointer to structure for Black Adjustment. * @rgb2rgb: Pointer to structure for RGB to RGB Blending. * @csc: Pointer to structure for Color Space Conversion from RGB-YCbYCr. * @yclimit: Pointer to structure for Y, C Value Limit. * @dcor: Pointer to structure for defect correction. * @nf: Pointer to structure for Noise Filter * @gamma: Pointer to gamma structure. */ struct omap3isp_prev_update_config { __u32 update; __u32 flag; __u32 shading_shift; struct omap3isp_prev_luma *luma; struct omap3isp_prev_hmed *hmed; struct omap3isp_prev_cfa *cfa; struct omap3isp_prev_csup *csup; struct omap3isp_prev_wbal *wbal; struct omap3isp_prev_blkadj *blkadj; struct omap3isp_prev_rgbtorgb *rgb2rgb; struct omap3isp_prev_csc *csc; struct omap3isp_prev_yclimit *yclimit; struct omap3isp_prev_dcor *dcor; struct omap3isp_prev_nf *nf; struct omap3isp_prev_gtables *gamma; }; #endif /* OMAP3_ISP_USER_H */ linux/i8k.h000064400000002770151027430560006560 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * i8k.h -- Linux driver for accessing the SMM BIOS on Dell laptops * * Copyright (C) 2001 Massimo Dal Zotto * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #ifndef _LINUX_I8K_H #define _LINUX_I8K_H #define I8K_PROC "/proc/i8k" #define I8K_PROC_FMT "1.0" #define I8K_BIOS_VERSION _IOR ('i', 0x80, int) /* broken: meant 4 bytes */ #define I8K_MACHINE_ID _IOR ('i', 0x81, int) /* broken: meant 16 bytes */ #define I8K_POWER_STATUS _IOR ('i', 0x82, size_t) #define I8K_FN_STATUS _IOR ('i', 0x83, size_t) #define I8K_GET_TEMP _IOR ('i', 0x84, size_t) #define I8K_GET_SPEED _IOWR('i', 0x85, size_t) #define I8K_GET_FAN _IOWR('i', 0x86, size_t) #define I8K_SET_FAN _IOWR('i', 0x87, size_t) #define I8K_FAN_LEFT 1 #define I8K_FAN_RIGHT 0 #define I8K_FAN_OFF 0 #define I8K_FAN_LOW 1 #define I8K_FAN_HIGH 2 #define I8K_FAN_TURBO 3 #define I8K_FAN_MAX I8K_FAN_TURBO #define I8K_VOL_UP 1 #define I8K_VOL_DOWN 2 #define I8K_VOL_MUTE 4 #define I8K_AC 1 #define I8K_BATTERY 0 #endif linux/genetlink.h000064400000004177151027430560010050 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_GENERIC_NETLINK_H #define __LINUX_GENERIC_NETLINK_H #include #include #define GENL_NAMSIZ 16 /* length of family name */ #define GENL_MIN_ID NLMSG_MIN_TYPE #define GENL_MAX_ID 1023 struct genlmsghdr { __u8 cmd; __u8 version; __u16 reserved; }; #define GENL_HDRLEN NLMSG_ALIGN(sizeof(struct genlmsghdr)) #define GENL_ADMIN_PERM 0x01 #define GENL_CMD_CAP_DO 0x02 #define GENL_CMD_CAP_DUMP 0x04 #define GENL_CMD_CAP_HASPOL 0x08 #define GENL_UNS_ADMIN_PERM 0x10 /* * List of reserved static generic netlink identifiers: */ #define GENL_ID_CTRL NLMSG_MIN_TYPE #define GENL_ID_VFS_DQUOT (NLMSG_MIN_TYPE + 1) #define GENL_ID_PMCRAID (NLMSG_MIN_TYPE + 2) /* must be last reserved + 1 */ #define GENL_START_ALLOC (NLMSG_MIN_TYPE + 3) /************************************************************************** * Controller **************************************************************************/ enum { CTRL_CMD_UNSPEC, CTRL_CMD_NEWFAMILY, CTRL_CMD_DELFAMILY, CTRL_CMD_GETFAMILY, CTRL_CMD_NEWOPS, CTRL_CMD_DELOPS, CTRL_CMD_GETOPS, CTRL_CMD_NEWMCAST_GRP, CTRL_CMD_DELMCAST_GRP, CTRL_CMD_GETMCAST_GRP, /* unused */ CTRL_CMD_GETPOLICY, __CTRL_CMD_MAX, }; #define CTRL_CMD_MAX (__CTRL_CMD_MAX - 1) enum { CTRL_ATTR_UNSPEC, CTRL_ATTR_FAMILY_ID, CTRL_ATTR_FAMILY_NAME, CTRL_ATTR_VERSION, CTRL_ATTR_HDRSIZE, CTRL_ATTR_MAXATTR, CTRL_ATTR_OPS, CTRL_ATTR_MCAST_GROUPS, CTRL_ATTR_POLICY, CTRL_ATTR_OP_POLICY, CTRL_ATTR_OP, __CTRL_ATTR_MAX, }; #define CTRL_ATTR_MAX (__CTRL_ATTR_MAX - 1) enum { CTRL_ATTR_OP_UNSPEC, CTRL_ATTR_OP_ID, CTRL_ATTR_OP_FLAGS, __CTRL_ATTR_OP_MAX, }; #define CTRL_ATTR_OP_MAX (__CTRL_ATTR_OP_MAX - 1) enum { CTRL_ATTR_MCAST_GRP_UNSPEC, CTRL_ATTR_MCAST_GRP_NAME, CTRL_ATTR_MCAST_GRP_ID, __CTRL_ATTR_MCAST_GRP_MAX, }; enum { CTRL_ATTR_POLICY_UNSPEC, CTRL_ATTR_POLICY_DO, CTRL_ATTR_POLICY_DUMP, __CTRL_ATTR_POLICY_DUMP_MAX, CTRL_ATTR_POLICY_DUMP_MAX = __CTRL_ATTR_POLICY_DUMP_MAX - 1 }; #define CTRL_ATTR_MCAST_GRP_MAX (__CTRL_ATTR_MCAST_GRP_MAX - 1) #endif /* __LINUX_GENERIC_NETLINK_H */ linux/ethtool_netlink.h000064400000054452151027430560011273 0ustar00/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */ /* * include/uapi/linux/ethtool_netlink.h - netlink interface for ethtool * * See Documentation/networking/ethtool-netlink.txt in kernel source tree for * doucumentation of the interface. */ #ifndef _LINUX_ETHTOOL_NETLINK_H_ #define _LINUX_ETHTOOL_NETLINK_H_ #include /* message types - userspace to kernel */ enum { ETHTOOL_MSG_USER_NONE, ETHTOOL_MSG_STRSET_GET, ETHTOOL_MSG_LINKINFO_GET, ETHTOOL_MSG_LINKINFO_SET, ETHTOOL_MSG_LINKMODES_GET, ETHTOOL_MSG_LINKMODES_SET, ETHTOOL_MSG_LINKSTATE_GET, ETHTOOL_MSG_DEBUG_GET, ETHTOOL_MSG_DEBUG_SET, ETHTOOL_MSG_WOL_GET, ETHTOOL_MSG_WOL_SET, ETHTOOL_MSG_FEATURES_GET, ETHTOOL_MSG_FEATURES_SET, ETHTOOL_MSG_PRIVFLAGS_GET, ETHTOOL_MSG_PRIVFLAGS_SET, ETHTOOL_MSG_RINGS_GET, ETHTOOL_MSG_RINGS_SET, ETHTOOL_MSG_CHANNELS_GET, ETHTOOL_MSG_CHANNELS_SET, ETHTOOL_MSG_COALESCE_GET, ETHTOOL_MSG_COALESCE_SET, ETHTOOL_MSG_PAUSE_GET, ETHTOOL_MSG_PAUSE_SET, ETHTOOL_MSG_EEE_GET, ETHTOOL_MSG_EEE_SET, ETHTOOL_MSG_TSINFO_GET, ETHTOOL_MSG_CABLE_TEST_ACT, ETHTOOL_MSG_CABLE_TEST_TDR_ACT, ETHTOOL_MSG_TUNNEL_INFO_GET, ETHTOOL_MSG_FEC_GET, ETHTOOL_MSG_FEC_SET, ETHTOOL_MSG_MODULE_EEPROM_GET, ETHTOOL_MSG_STATS_GET, /* add new constants above here */ __ETHTOOL_MSG_USER_CNT, ETHTOOL_MSG_USER_MAX = __ETHTOOL_MSG_USER_CNT - 1 }; /* message types - kernel to userspace */ enum { ETHTOOL_MSG_KERNEL_NONE, ETHTOOL_MSG_STRSET_GET_REPLY, ETHTOOL_MSG_LINKINFO_GET_REPLY, ETHTOOL_MSG_LINKINFO_NTF, ETHTOOL_MSG_LINKMODES_GET_REPLY, ETHTOOL_MSG_LINKMODES_NTF, ETHTOOL_MSG_LINKSTATE_GET_REPLY, ETHTOOL_MSG_DEBUG_GET_REPLY, ETHTOOL_MSG_DEBUG_NTF, ETHTOOL_MSG_WOL_GET_REPLY, ETHTOOL_MSG_WOL_NTF, ETHTOOL_MSG_FEATURES_GET_REPLY, ETHTOOL_MSG_FEATURES_SET_REPLY, ETHTOOL_MSG_FEATURES_NTF, ETHTOOL_MSG_PRIVFLAGS_GET_REPLY, ETHTOOL_MSG_PRIVFLAGS_NTF, ETHTOOL_MSG_RINGS_GET_REPLY, ETHTOOL_MSG_RINGS_NTF, ETHTOOL_MSG_CHANNELS_GET_REPLY, ETHTOOL_MSG_CHANNELS_NTF, ETHTOOL_MSG_COALESCE_GET_REPLY, ETHTOOL_MSG_COALESCE_NTF, ETHTOOL_MSG_PAUSE_GET_REPLY, ETHTOOL_MSG_PAUSE_NTF, ETHTOOL_MSG_EEE_GET_REPLY, ETHTOOL_MSG_EEE_NTF, ETHTOOL_MSG_TSINFO_GET_REPLY, ETHTOOL_MSG_CABLE_TEST_NTF, ETHTOOL_MSG_CABLE_TEST_TDR_NTF, ETHTOOL_MSG_TUNNEL_INFO_GET_REPLY, ETHTOOL_MSG_FEC_GET_REPLY, ETHTOOL_MSG_FEC_NTF, ETHTOOL_MSG_MODULE_EEPROM_GET_REPLY, ETHTOOL_MSG_STATS_GET_REPLY, /* add new constants above here */ __ETHTOOL_MSG_KERNEL_CNT, ETHTOOL_MSG_KERNEL_MAX = __ETHTOOL_MSG_KERNEL_CNT - 1 }; /* request header */ /* use compact bitsets in reply */ #define ETHTOOL_FLAG_COMPACT_BITSETS (1 << 0) /* provide optional reply for SET or ACT requests */ #define ETHTOOL_FLAG_OMIT_REPLY (1 << 1) /* request statistics, if supported by the driver */ #define ETHTOOL_FLAG_STATS (1 << 2) #define ETHTOOL_FLAG_ALL (ETHTOOL_FLAG_COMPACT_BITSETS | \ ETHTOOL_FLAG_OMIT_REPLY | \ ETHTOOL_FLAG_STATS) enum { ETHTOOL_A_HEADER_UNSPEC, ETHTOOL_A_HEADER_DEV_INDEX, /* u32 */ ETHTOOL_A_HEADER_DEV_NAME, /* string */ ETHTOOL_A_HEADER_FLAGS, /* u32 - ETHTOOL_FLAG_* */ /* add new constants above here */ __ETHTOOL_A_HEADER_CNT, ETHTOOL_A_HEADER_MAX = __ETHTOOL_A_HEADER_CNT - 1 }; /* bit sets */ enum { ETHTOOL_A_BITSET_BIT_UNSPEC, ETHTOOL_A_BITSET_BIT_INDEX, /* u32 */ ETHTOOL_A_BITSET_BIT_NAME, /* string */ ETHTOOL_A_BITSET_BIT_VALUE, /* flag */ /* add new constants above here */ __ETHTOOL_A_BITSET_BIT_CNT, ETHTOOL_A_BITSET_BIT_MAX = __ETHTOOL_A_BITSET_BIT_CNT - 1 }; enum { ETHTOOL_A_BITSET_BITS_UNSPEC, ETHTOOL_A_BITSET_BITS_BIT, /* nest - _A_BITSET_BIT_* */ /* add new constants above here */ __ETHTOOL_A_BITSET_BITS_CNT, ETHTOOL_A_BITSET_BITS_MAX = __ETHTOOL_A_BITSET_BITS_CNT - 1 }; enum { ETHTOOL_A_BITSET_UNSPEC, ETHTOOL_A_BITSET_NOMASK, /* flag */ ETHTOOL_A_BITSET_SIZE, /* u32 */ ETHTOOL_A_BITSET_BITS, /* nest - _A_BITSET_BITS_* */ ETHTOOL_A_BITSET_VALUE, /* binary */ ETHTOOL_A_BITSET_MASK, /* binary */ /* add new constants above here */ __ETHTOOL_A_BITSET_CNT, ETHTOOL_A_BITSET_MAX = __ETHTOOL_A_BITSET_CNT - 1 }; /* string sets */ enum { ETHTOOL_A_STRING_UNSPEC, ETHTOOL_A_STRING_INDEX, /* u32 */ ETHTOOL_A_STRING_VALUE, /* string */ /* add new constants above here */ __ETHTOOL_A_STRING_CNT, ETHTOOL_A_STRING_MAX = __ETHTOOL_A_STRING_CNT - 1 }; enum { ETHTOOL_A_STRINGS_UNSPEC, ETHTOOL_A_STRINGS_STRING, /* nest - _A_STRINGS_* */ /* add new constants above here */ __ETHTOOL_A_STRINGS_CNT, ETHTOOL_A_STRINGS_MAX = __ETHTOOL_A_STRINGS_CNT - 1 }; enum { ETHTOOL_A_STRINGSET_UNSPEC, ETHTOOL_A_STRINGSET_ID, /* u32 */ ETHTOOL_A_STRINGSET_COUNT, /* u32 */ ETHTOOL_A_STRINGSET_STRINGS, /* nest - _A_STRINGS_* */ /* add new constants above here */ __ETHTOOL_A_STRINGSET_CNT, ETHTOOL_A_STRINGSET_MAX = __ETHTOOL_A_STRINGSET_CNT - 1 }; enum { ETHTOOL_A_STRINGSETS_UNSPEC, ETHTOOL_A_STRINGSETS_STRINGSET, /* nest - _A_STRINGSET_* */ /* add new constants above here */ __ETHTOOL_A_STRINGSETS_CNT, ETHTOOL_A_STRINGSETS_MAX = __ETHTOOL_A_STRINGSETS_CNT - 1 }; /* STRSET */ enum { ETHTOOL_A_STRSET_UNSPEC, ETHTOOL_A_STRSET_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_STRSET_STRINGSETS, /* nest - _A_STRINGSETS_* */ ETHTOOL_A_STRSET_COUNTS_ONLY, /* flag */ /* add new constants above here */ __ETHTOOL_A_STRSET_CNT, ETHTOOL_A_STRSET_MAX = __ETHTOOL_A_STRSET_CNT - 1 }; /* LINKINFO */ enum { ETHTOOL_A_LINKINFO_UNSPEC, ETHTOOL_A_LINKINFO_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_LINKINFO_PORT, /* u8 */ ETHTOOL_A_LINKINFO_PHYADDR, /* u8 */ ETHTOOL_A_LINKINFO_TP_MDIX, /* u8 */ ETHTOOL_A_LINKINFO_TP_MDIX_CTRL, /* u8 */ ETHTOOL_A_LINKINFO_TRANSCEIVER, /* u8 */ /* add new constants above here */ __ETHTOOL_A_LINKINFO_CNT, ETHTOOL_A_LINKINFO_MAX = __ETHTOOL_A_LINKINFO_CNT - 1 }; /* LINKMODES */ enum { ETHTOOL_A_LINKMODES_UNSPEC, ETHTOOL_A_LINKMODES_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_LINKMODES_AUTONEG, /* u8 */ ETHTOOL_A_LINKMODES_OURS, /* bitset */ ETHTOOL_A_LINKMODES_PEER, /* bitset */ ETHTOOL_A_LINKMODES_SPEED, /* u32 */ ETHTOOL_A_LINKMODES_DUPLEX, /* u8 */ ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG, /* u8 */ ETHTOOL_A_LINKMODES_MASTER_SLAVE_STATE, /* u8 */ ETHTOOL_A_LINKMODES_LANES, /* u32 */ /* add new constants above here */ __ETHTOOL_A_LINKMODES_CNT, ETHTOOL_A_LINKMODES_MAX = __ETHTOOL_A_LINKMODES_CNT - 1 }; /* LINKSTATE */ enum { ETHTOOL_A_LINKSTATE_UNSPEC, ETHTOOL_A_LINKSTATE_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_LINKSTATE_LINK, /* u8 */ ETHTOOL_A_LINKSTATE_SQI, /* u32 */ ETHTOOL_A_LINKSTATE_SQI_MAX, /* u32 */ ETHTOOL_A_LINKSTATE_EXT_STATE, /* u8 */ ETHTOOL_A_LINKSTATE_EXT_SUBSTATE, /* u8 */ /* add new constants above here */ __ETHTOOL_A_LINKSTATE_CNT, ETHTOOL_A_LINKSTATE_MAX = __ETHTOOL_A_LINKSTATE_CNT - 1 }; /* DEBUG */ enum { ETHTOOL_A_DEBUG_UNSPEC, ETHTOOL_A_DEBUG_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_DEBUG_MSGMASK, /* bitset */ /* add new constants above here */ __ETHTOOL_A_DEBUG_CNT, ETHTOOL_A_DEBUG_MAX = __ETHTOOL_A_DEBUG_CNT - 1 }; /* WOL */ enum { ETHTOOL_A_WOL_UNSPEC, ETHTOOL_A_WOL_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_WOL_MODES, /* bitset */ ETHTOOL_A_WOL_SOPASS, /* binary */ /* add new constants above here */ __ETHTOOL_A_WOL_CNT, ETHTOOL_A_WOL_MAX = __ETHTOOL_A_WOL_CNT - 1 }; /* FEATURES */ enum { ETHTOOL_A_FEATURES_UNSPEC, ETHTOOL_A_FEATURES_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_FEATURES_HW, /* bitset */ ETHTOOL_A_FEATURES_WANTED, /* bitset */ ETHTOOL_A_FEATURES_ACTIVE, /* bitset */ ETHTOOL_A_FEATURES_NOCHANGE, /* bitset */ /* add new constants above here */ __ETHTOOL_A_FEATURES_CNT, ETHTOOL_A_FEATURES_MAX = __ETHTOOL_A_FEATURES_CNT - 1 }; /* PRIVFLAGS */ enum { ETHTOOL_A_PRIVFLAGS_UNSPEC, ETHTOOL_A_PRIVFLAGS_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_PRIVFLAGS_FLAGS, /* bitset */ /* add new constants above here */ __ETHTOOL_A_PRIVFLAGS_CNT, ETHTOOL_A_PRIVFLAGS_MAX = __ETHTOOL_A_PRIVFLAGS_CNT - 1 }; /* RINGS */ enum { ETHTOOL_TCP_DATA_SPLIT_UNKNOWN = 0, ETHTOOL_TCP_DATA_SPLIT_DISABLED, ETHTOOL_TCP_DATA_SPLIT_ENABLED, }; enum { ETHTOOL_A_RINGS_UNSPEC, ETHTOOL_A_RINGS_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_RINGS_RX_MAX, /* u32 */ ETHTOOL_A_RINGS_RX_MINI_MAX, /* u32 */ ETHTOOL_A_RINGS_RX_JUMBO_MAX, /* u32 */ ETHTOOL_A_RINGS_TX_MAX, /* u32 */ ETHTOOL_A_RINGS_RX, /* u32 */ ETHTOOL_A_RINGS_RX_MINI, /* u32 */ ETHTOOL_A_RINGS_RX_JUMBO, /* u32 */ ETHTOOL_A_RINGS_TX, /* u32 */ ETHTOOL_A_RINGS_RX_BUF_LEN, /* u32 */ ETHTOOL_A_RINGS_TCP_DATA_SPLIT, /* u8 */ /* add new constants above here */ __ETHTOOL_A_RINGS_CNT, ETHTOOL_A_RINGS_MAX = (__ETHTOOL_A_RINGS_CNT - 1) }; /* CHANNELS */ enum { ETHTOOL_A_CHANNELS_UNSPEC, ETHTOOL_A_CHANNELS_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_CHANNELS_RX_MAX, /* u32 */ ETHTOOL_A_CHANNELS_TX_MAX, /* u32 */ ETHTOOL_A_CHANNELS_OTHER_MAX, /* u32 */ ETHTOOL_A_CHANNELS_COMBINED_MAX, /* u32 */ ETHTOOL_A_CHANNELS_RX_COUNT, /* u32 */ ETHTOOL_A_CHANNELS_TX_COUNT, /* u32 */ ETHTOOL_A_CHANNELS_OTHER_COUNT, /* u32 */ ETHTOOL_A_CHANNELS_COMBINED_COUNT, /* u32 */ /* add new constants above here */ __ETHTOOL_A_CHANNELS_CNT, ETHTOOL_A_CHANNELS_MAX = (__ETHTOOL_A_CHANNELS_CNT - 1) }; /* COALESCE */ enum { ETHTOOL_A_COALESCE_UNSPEC, ETHTOOL_A_COALESCE_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_COALESCE_RX_USECS, /* u32 */ ETHTOOL_A_COALESCE_RX_MAX_FRAMES, /* u32 */ ETHTOOL_A_COALESCE_RX_USECS_IRQ, /* u32 */ ETHTOOL_A_COALESCE_RX_MAX_FRAMES_IRQ, /* u32 */ ETHTOOL_A_COALESCE_TX_USECS, /* u32 */ ETHTOOL_A_COALESCE_TX_MAX_FRAMES, /* u32 */ ETHTOOL_A_COALESCE_TX_USECS_IRQ, /* u32 */ ETHTOOL_A_COALESCE_TX_MAX_FRAMES_IRQ, /* u32 */ ETHTOOL_A_COALESCE_STATS_BLOCK_USECS, /* u32 */ ETHTOOL_A_COALESCE_USE_ADAPTIVE_RX, /* u8 */ ETHTOOL_A_COALESCE_USE_ADAPTIVE_TX, /* u8 */ ETHTOOL_A_COALESCE_PKT_RATE_LOW, /* u32 */ ETHTOOL_A_COALESCE_RX_USECS_LOW, /* u32 */ ETHTOOL_A_COALESCE_RX_MAX_FRAMES_LOW, /* u32 */ ETHTOOL_A_COALESCE_TX_USECS_LOW, /* u32 */ ETHTOOL_A_COALESCE_TX_MAX_FRAMES_LOW, /* u32 */ ETHTOOL_A_COALESCE_PKT_RATE_HIGH, /* u32 */ ETHTOOL_A_COALESCE_RX_USECS_HIGH, /* u32 */ ETHTOOL_A_COALESCE_RX_MAX_FRAMES_HIGH, /* u32 */ ETHTOOL_A_COALESCE_TX_USECS_HIGH, /* u32 */ ETHTOOL_A_COALESCE_TX_MAX_FRAMES_HIGH, /* u32 */ ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL, /* u32 */ ETHTOOL_A_COALESCE_USE_CQE_MODE_TX, /* u8 */ ETHTOOL_A_COALESCE_USE_CQE_MODE_RX, /* u8 */ /* add new constants above here */ __ETHTOOL_A_COALESCE_CNT, ETHTOOL_A_COALESCE_MAX = (__ETHTOOL_A_COALESCE_CNT - 1) }; /* PAUSE */ enum { ETHTOOL_A_PAUSE_UNSPEC, ETHTOOL_A_PAUSE_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_PAUSE_AUTONEG, /* u8 */ ETHTOOL_A_PAUSE_RX, /* u8 */ ETHTOOL_A_PAUSE_TX, /* u8 */ ETHTOOL_A_PAUSE_STATS, /* nest - _PAUSE_STAT_* */ /* add new constants above here */ __ETHTOOL_A_PAUSE_CNT, ETHTOOL_A_PAUSE_MAX = (__ETHTOOL_A_PAUSE_CNT - 1) }; enum { ETHTOOL_A_PAUSE_STAT_UNSPEC, ETHTOOL_A_PAUSE_STAT_PAD, ETHTOOL_A_PAUSE_STAT_TX_FRAMES, ETHTOOL_A_PAUSE_STAT_RX_FRAMES, /* add new constants above here */ __ETHTOOL_A_PAUSE_STAT_CNT, ETHTOOL_A_PAUSE_STAT_MAX = (__ETHTOOL_A_PAUSE_STAT_CNT - 1) }; /* EEE */ enum { ETHTOOL_A_EEE_UNSPEC, ETHTOOL_A_EEE_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_EEE_MODES_OURS, /* bitset */ ETHTOOL_A_EEE_MODES_PEER, /* bitset */ ETHTOOL_A_EEE_ACTIVE, /* u8 */ ETHTOOL_A_EEE_ENABLED, /* u8 */ ETHTOOL_A_EEE_TX_LPI_ENABLED, /* u8 */ ETHTOOL_A_EEE_TX_LPI_TIMER, /* u32 */ /* add new constants above here */ __ETHTOOL_A_EEE_CNT, ETHTOOL_A_EEE_MAX = (__ETHTOOL_A_EEE_CNT - 1) }; /* TSINFO */ enum { ETHTOOL_A_TSINFO_UNSPEC, ETHTOOL_A_TSINFO_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_TSINFO_TIMESTAMPING, /* bitset */ ETHTOOL_A_TSINFO_TX_TYPES, /* bitset */ ETHTOOL_A_TSINFO_RX_FILTERS, /* bitset */ ETHTOOL_A_TSINFO_PHC_INDEX, /* u32 */ /* add new constants above here */ __ETHTOOL_A_TSINFO_CNT, ETHTOOL_A_TSINFO_MAX = (__ETHTOOL_A_TSINFO_CNT - 1) }; /* CABLE TEST */ enum { ETHTOOL_A_CABLE_TEST_UNSPEC, ETHTOOL_A_CABLE_TEST_HEADER, /* nest - _A_HEADER_* */ /* add new constants above here */ __ETHTOOL_A_CABLE_TEST_CNT, ETHTOOL_A_CABLE_TEST_MAX = __ETHTOOL_A_CABLE_TEST_CNT - 1 }; /* CABLE TEST NOTIFY */ enum { ETHTOOL_A_CABLE_RESULT_CODE_UNSPEC, ETHTOOL_A_CABLE_RESULT_CODE_OK, ETHTOOL_A_CABLE_RESULT_CODE_OPEN, ETHTOOL_A_CABLE_RESULT_CODE_SAME_SHORT, ETHTOOL_A_CABLE_RESULT_CODE_CROSS_SHORT, }; enum { ETHTOOL_A_CABLE_PAIR_A, ETHTOOL_A_CABLE_PAIR_B, ETHTOOL_A_CABLE_PAIR_C, ETHTOOL_A_CABLE_PAIR_D, }; enum { ETHTOOL_A_CABLE_RESULT_UNSPEC, ETHTOOL_A_CABLE_RESULT_PAIR, /* u8 ETHTOOL_A_CABLE_PAIR_ */ ETHTOOL_A_CABLE_RESULT_CODE, /* u8 ETHTOOL_A_CABLE_RESULT_CODE_ */ __ETHTOOL_A_CABLE_RESULT_CNT, ETHTOOL_A_CABLE_RESULT_MAX = (__ETHTOOL_A_CABLE_RESULT_CNT - 1) }; enum { ETHTOOL_A_CABLE_FAULT_LENGTH_UNSPEC, ETHTOOL_A_CABLE_FAULT_LENGTH_PAIR, /* u8 ETHTOOL_A_CABLE_PAIR_ */ ETHTOOL_A_CABLE_FAULT_LENGTH_CM, /* u32 */ __ETHTOOL_A_CABLE_FAULT_LENGTH_CNT, ETHTOOL_A_CABLE_FAULT_LENGTH_MAX = (__ETHTOOL_A_CABLE_FAULT_LENGTH_CNT - 1) }; enum { ETHTOOL_A_CABLE_TEST_NTF_STATUS_UNSPEC, ETHTOOL_A_CABLE_TEST_NTF_STATUS_STARTED, ETHTOOL_A_CABLE_TEST_NTF_STATUS_COMPLETED }; enum { ETHTOOL_A_CABLE_NEST_UNSPEC, ETHTOOL_A_CABLE_NEST_RESULT, /* nest - ETHTOOL_A_CABLE_RESULT_ */ ETHTOOL_A_CABLE_NEST_FAULT_LENGTH, /* nest - ETHTOOL_A_CABLE_FAULT_LENGTH_ */ __ETHTOOL_A_CABLE_NEST_CNT, ETHTOOL_A_CABLE_NEST_MAX = (__ETHTOOL_A_CABLE_NEST_CNT - 1) }; enum { ETHTOOL_A_CABLE_TEST_NTF_UNSPEC, ETHTOOL_A_CABLE_TEST_NTF_HEADER, /* nest - ETHTOOL_A_HEADER_* */ ETHTOOL_A_CABLE_TEST_NTF_STATUS, /* u8 - _STARTED/_COMPLETE */ ETHTOOL_A_CABLE_TEST_NTF_NEST, /* nest - of results: */ __ETHTOOL_A_CABLE_TEST_NTF_CNT, ETHTOOL_A_CABLE_TEST_NTF_MAX = (__ETHTOOL_A_CABLE_TEST_NTF_CNT - 1) }; /* CABLE TEST TDR */ enum { ETHTOOL_A_CABLE_TEST_TDR_CFG_UNSPEC, ETHTOOL_A_CABLE_TEST_TDR_CFG_FIRST, /* u32 */ ETHTOOL_A_CABLE_TEST_TDR_CFG_LAST, /* u32 */ ETHTOOL_A_CABLE_TEST_TDR_CFG_STEP, /* u32 */ ETHTOOL_A_CABLE_TEST_TDR_CFG_PAIR, /* u8 */ /* add new constants above here */ __ETHTOOL_A_CABLE_TEST_TDR_CFG_CNT, ETHTOOL_A_CABLE_TEST_TDR_CFG_MAX = __ETHTOOL_A_CABLE_TEST_TDR_CFG_CNT - 1 }; enum { ETHTOOL_A_CABLE_TEST_TDR_UNSPEC, ETHTOOL_A_CABLE_TEST_TDR_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_CABLE_TEST_TDR_CFG, /* nest - *_TDR_CFG_* */ /* add new constants above here */ __ETHTOOL_A_CABLE_TEST_TDR_CNT, ETHTOOL_A_CABLE_TEST_TDR_MAX = __ETHTOOL_A_CABLE_TEST_TDR_CNT - 1 }; /* CABLE TEST TDR NOTIFY */ enum { ETHTOOL_A_CABLE_AMPLITUDE_UNSPEC, ETHTOOL_A_CABLE_AMPLITUDE_PAIR, /* u8 */ ETHTOOL_A_CABLE_AMPLITUDE_mV, /* s16 */ __ETHTOOL_A_CABLE_AMPLITUDE_CNT, ETHTOOL_A_CABLE_AMPLITUDE_MAX = (__ETHTOOL_A_CABLE_AMPLITUDE_CNT - 1) }; enum { ETHTOOL_A_CABLE_PULSE_UNSPEC, ETHTOOL_A_CABLE_PULSE_mV, /* s16 */ __ETHTOOL_A_CABLE_PULSE_CNT, ETHTOOL_A_CABLE_PULSE_MAX = (__ETHTOOL_A_CABLE_PULSE_CNT - 1) }; enum { ETHTOOL_A_CABLE_STEP_UNSPEC, ETHTOOL_A_CABLE_STEP_FIRST_DISTANCE, /* u32 */ ETHTOOL_A_CABLE_STEP_LAST_DISTANCE, /* u32 */ ETHTOOL_A_CABLE_STEP_STEP_DISTANCE, /* u32 */ __ETHTOOL_A_CABLE_STEP_CNT, ETHTOOL_A_CABLE_STEP_MAX = (__ETHTOOL_A_CABLE_STEP_CNT - 1) }; enum { ETHTOOL_A_CABLE_TDR_NEST_UNSPEC, ETHTOOL_A_CABLE_TDR_NEST_STEP, /* nest - ETHTTOOL_A_CABLE_STEP */ ETHTOOL_A_CABLE_TDR_NEST_AMPLITUDE, /* nest - ETHTOOL_A_CABLE_AMPLITUDE */ ETHTOOL_A_CABLE_TDR_NEST_PULSE, /* nest - ETHTOOL_A_CABLE_PULSE */ __ETHTOOL_A_CABLE_TDR_NEST_CNT, ETHTOOL_A_CABLE_TDR_NEST_MAX = (__ETHTOOL_A_CABLE_TDR_NEST_CNT - 1) }; enum { ETHTOOL_A_CABLE_TEST_TDR_NTF_UNSPEC, ETHTOOL_A_CABLE_TEST_TDR_NTF_HEADER, /* nest - ETHTOOL_A_HEADER_* */ ETHTOOL_A_CABLE_TEST_TDR_NTF_STATUS, /* u8 - _STARTED/_COMPLETE */ ETHTOOL_A_CABLE_TEST_TDR_NTF_NEST, /* nest - of results: */ /* add new constants above here */ __ETHTOOL_A_CABLE_TEST_TDR_NTF_CNT, ETHTOOL_A_CABLE_TEST_TDR_NTF_MAX = __ETHTOOL_A_CABLE_TEST_TDR_NTF_CNT - 1 }; /* TUNNEL INFO */ enum { ETHTOOL_UDP_TUNNEL_TYPE_VXLAN, ETHTOOL_UDP_TUNNEL_TYPE_GENEVE, ETHTOOL_UDP_TUNNEL_TYPE_VXLAN_GPE, __ETHTOOL_UDP_TUNNEL_TYPE_CNT }; enum { ETHTOOL_A_TUNNEL_UDP_ENTRY_UNSPEC, ETHTOOL_A_TUNNEL_UDP_ENTRY_PORT, /* be16 */ ETHTOOL_A_TUNNEL_UDP_ENTRY_TYPE, /* u32 */ /* add new constants above here */ __ETHTOOL_A_TUNNEL_UDP_ENTRY_CNT, ETHTOOL_A_TUNNEL_UDP_ENTRY_MAX = (__ETHTOOL_A_TUNNEL_UDP_ENTRY_CNT - 1) }; enum { ETHTOOL_A_TUNNEL_UDP_TABLE_UNSPEC, ETHTOOL_A_TUNNEL_UDP_TABLE_SIZE, /* u32 */ ETHTOOL_A_TUNNEL_UDP_TABLE_TYPES, /* bitset */ ETHTOOL_A_TUNNEL_UDP_TABLE_ENTRY, /* nest - _UDP_ENTRY_* */ /* add new constants above here */ __ETHTOOL_A_TUNNEL_UDP_TABLE_CNT, ETHTOOL_A_TUNNEL_UDP_TABLE_MAX = (__ETHTOOL_A_TUNNEL_UDP_TABLE_CNT - 1) }; enum { ETHTOOL_A_TUNNEL_UDP_UNSPEC, ETHTOOL_A_TUNNEL_UDP_TABLE, /* nest - _UDP_TABLE_* */ /* add new constants above here */ __ETHTOOL_A_TUNNEL_UDP_CNT, ETHTOOL_A_TUNNEL_UDP_MAX = (__ETHTOOL_A_TUNNEL_UDP_CNT - 1) }; enum { ETHTOOL_A_TUNNEL_INFO_UNSPEC, ETHTOOL_A_TUNNEL_INFO_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_TUNNEL_INFO_UDP_PORTS, /* nest - _UDP_TABLE */ /* add new constants above here */ __ETHTOOL_A_TUNNEL_INFO_CNT, ETHTOOL_A_TUNNEL_INFO_MAX = (__ETHTOOL_A_TUNNEL_INFO_CNT - 1) }; /* FEC */ enum { ETHTOOL_A_FEC_UNSPEC, ETHTOOL_A_FEC_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_FEC_MODES, /* bitset */ ETHTOOL_A_FEC_AUTO, /* u8 */ ETHTOOL_A_FEC_ACTIVE, /* u32 */ ETHTOOL_A_FEC_STATS, /* nest - _A_FEC_STAT */ __ETHTOOL_A_FEC_CNT, ETHTOOL_A_FEC_MAX = (__ETHTOOL_A_FEC_CNT - 1) }; enum { ETHTOOL_A_FEC_STAT_UNSPEC, ETHTOOL_A_FEC_STAT_PAD, ETHTOOL_A_FEC_STAT_CORRECTED, /* array, u64 */ ETHTOOL_A_FEC_STAT_UNCORR, /* array, u64 */ ETHTOOL_A_FEC_STAT_CORR_BITS, /* array, u64 */ /* add new constants above here */ __ETHTOOL_A_FEC_STAT_CNT, ETHTOOL_A_FEC_STAT_MAX = (__ETHTOOL_A_FEC_STAT_CNT - 1) }; /* MODULE EEPROM */ enum { ETHTOOL_A_MODULE_EEPROM_UNSPEC, ETHTOOL_A_MODULE_EEPROM_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_MODULE_EEPROM_OFFSET, /* u32 */ ETHTOOL_A_MODULE_EEPROM_LENGTH, /* u32 */ ETHTOOL_A_MODULE_EEPROM_PAGE, /* u8 */ ETHTOOL_A_MODULE_EEPROM_BANK, /* u8 */ ETHTOOL_A_MODULE_EEPROM_I2C_ADDRESS, /* u8 */ ETHTOOL_A_MODULE_EEPROM_DATA, /* binary */ __ETHTOOL_A_MODULE_EEPROM_CNT, ETHTOOL_A_MODULE_EEPROM_MAX = (__ETHTOOL_A_MODULE_EEPROM_CNT - 1) }; /* STATS */ enum { ETHTOOL_A_STATS_UNSPEC, ETHTOOL_A_STATS_PAD, ETHTOOL_A_STATS_HEADER, /* nest - _A_HEADER_* */ ETHTOOL_A_STATS_GROUPS, /* bitset */ ETHTOOL_A_STATS_GRP, /* nest - _A_STATS_GRP_* */ /* add new constants above here */ __ETHTOOL_A_STATS_CNT, ETHTOOL_A_STATS_MAX = (__ETHTOOL_A_STATS_CNT - 1) }; enum { ETHTOOL_STATS_ETH_PHY, ETHTOOL_STATS_ETH_MAC, ETHTOOL_STATS_ETH_CTRL, ETHTOOL_STATS_RMON, /* add new constants above here */ __ETHTOOL_STATS_CNT }; enum { ETHTOOL_A_STATS_GRP_UNSPEC, ETHTOOL_A_STATS_GRP_PAD, ETHTOOL_A_STATS_GRP_ID, /* u32 */ ETHTOOL_A_STATS_GRP_SS_ID, /* u32 */ ETHTOOL_A_STATS_GRP_STAT, /* nest */ ETHTOOL_A_STATS_GRP_HIST_RX, /* nest */ ETHTOOL_A_STATS_GRP_HIST_TX, /* nest */ ETHTOOL_A_STATS_GRP_HIST_BKT_LOW, /* u32 */ ETHTOOL_A_STATS_GRP_HIST_BKT_HI, /* u32 */ ETHTOOL_A_STATS_GRP_HIST_VAL, /* u64 */ /* add new constants above here */ __ETHTOOL_A_STATS_GRP_CNT, ETHTOOL_A_STATS_GRP_MAX = (__ETHTOOL_A_STATS_CNT - 1) }; enum { /* 30.3.2.1.5 aSymbolErrorDuringCarrier */ ETHTOOL_A_STATS_ETH_PHY_5_SYM_ERR, /* add new constants above here */ __ETHTOOL_A_STATS_ETH_PHY_CNT, ETHTOOL_A_STATS_ETH_PHY_MAX = (__ETHTOOL_A_STATS_ETH_PHY_CNT - 1) }; enum { /* 30.3.1.1.2 aFramesTransmittedOK */ ETHTOOL_A_STATS_ETH_MAC_2_TX_PKT, /* 30.3.1.1.3 aSingleCollisionFrames */ ETHTOOL_A_STATS_ETH_MAC_3_SINGLE_COL, /* 30.3.1.1.4 aMultipleCollisionFrames */ ETHTOOL_A_STATS_ETH_MAC_4_MULTI_COL, /* 30.3.1.1.5 aFramesReceivedOK */ ETHTOOL_A_STATS_ETH_MAC_5_RX_PKT, /* 30.3.1.1.6 aFrameCheckSequenceErrors */ ETHTOOL_A_STATS_ETH_MAC_6_FCS_ERR, /* 30.3.1.1.7 aAlignmentErrors */ ETHTOOL_A_STATS_ETH_MAC_7_ALIGN_ERR, /* 30.3.1.1.8 aOctetsTransmittedOK */ ETHTOOL_A_STATS_ETH_MAC_8_TX_BYTES, /* 30.3.1.1.9 aFramesWithDeferredXmissions */ ETHTOOL_A_STATS_ETH_MAC_9_TX_DEFER, /* 30.3.1.1.10 aLateCollisions */ ETHTOOL_A_STATS_ETH_MAC_10_LATE_COL, /* 30.3.1.1.11 aFramesAbortedDueToXSColls */ ETHTOOL_A_STATS_ETH_MAC_11_XS_COL, /* 30.3.1.1.12 aFramesLostDueToIntMACXmitError */ ETHTOOL_A_STATS_ETH_MAC_12_TX_INT_ERR, /* 30.3.1.1.13 aCarrierSenseErrors */ ETHTOOL_A_STATS_ETH_MAC_13_CS_ERR, /* 30.3.1.1.14 aOctetsReceivedOK */ ETHTOOL_A_STATS_ETH_MAC_14_RX_BYTES, /* 30.3.1.1.15 aFramesLostDueToIntMACRcvError */ ETHTOOL_A_STATS_ETH_MAC_15_RX_INT_ERR, /* 30.3.1.1.18 aMulticastFramesXmittedOK */ ETHTOOL_A_STATS_ETH_MAC_18_TX_MCAST, /* 30.3.1.1.19 aBroadcastFramesXmittedOK */ ETHTOOL_A_STATS_ETH_MAC_19_TX_BCAST, /* 30.3.1.1.20 aFramesWithExcessiveDeferral */ ETHTOOL_A_STATS_ETH_MAC_20_XS_DEFER, /* 30.3.1.1.21 aMulticastFramesReceivedOK */ ETHTOOL_A_STATS_ETH_MAC_21_RX_MCAST, /* 30.3.1.1.22 aBroadcastFramesReceivedOK */ ETHTOOL_A_STATS_ETH_MAC_22_RX_BCAST, /* 30.3.1.1.23 aInRangeLengthErrors */ ETHTOOL_A_STATS_ETH_MAC_23_IR_LEN_ERR, /* 30.3.1.1.24 aOutOfRangeLengthField */ ETHTOOL_A_STATS_ETH_MAC_24_OOR_LEN, /* 30.3.1.1.25 aFrameTooLongErrors */ ETHTOOL_A_STATS_ETH_MAC_25_TOO_LONG_ERR, /* add new constants above here */ __ETHTOOL_A_STATS_ETH_MAC_CNT, ETHTOOL_A_STATS_ETH_MAC_MAX = (__ETHTOOL_A_STATS_ETH_MAC_CNT - 1) }; enum { /* 30.3.3.3 aMACControlFramesTransmitted */ ETHTOOL_A_STATS_ETH_CTRL_3_TX, /* 30.3.3.4 aMACControlFramesReceived */ ETHTOOL_A_STATS_ETH_CTRL_4_RX, /* 30.3.3.5 aUnsupportedOpcodesReceived */ ETHTOOL_A_STATS_ETH_CTRL_5_RX_UNSUP, /* add new constants above here */ __ETHTOOL_A_STATS_ETH_CTRL_CNT, ETHTOOL_A_STATS_ETH_CTRL_MAX = (__ETHTOOL_A_STATS_ETH_CTRL_CNT - 1) }; enum { /* etherStatsUndersizePkts */ ETHTOOL_A_STATS_RMON_UNDERSIZE, /* etherStatsOversizePkts */ ETHTOOL_A_STATS_RMON_OVERSIZE, /* etherStatsFragments */ ETHTOOL_A_STATS_RMON_FRAG, /* etherStatsJabbers */ ETHTOOL_A_STATS_RMON_JABBER, /* add new constants above here */ __ETHTOOL_A_STATS_RMON_CNT, ETHTOOL_A_STATS_RMON_MAX = (__ETHTOOL_A_STATS_RMON_CNT - 1) }; /* generic netlink info */ #define ETHTOOL_GENL_NAME "ethtool" #define ETHTOOL_GENL_VERSION 1 #define ETHTOOL_MCGRP_MONITOR_NAME "monitor" #endif /* _LINUX_ETHTOOL_NETLINK_H_ */ linux/media-bus-format.h000064400000014413151027430560011216 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Media Bus API header * * Copyright (C) 2009, Guennadi Liakhovetski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __LINUX_MEDIA_BUS_FORMAT_H #define __LINUX_MEDIA_BUS_FORMAT_H /* * These bus formats uniquely identify data formats on the data bus. Format 0 * is reserved, MEDIA_BUS_FMT_FIXED shall be used by host-client pairs, where * the data format is fixed. Additionally, "2X8" means that one pixel is * transferred in two 8-bit samples, "BE" or "LE" specify in which order those * samples are transferred over the bus: "LE" means that the least significant * bits are transferred first, "BE" means that the most significant bits are * transferred first, and "PADHI" and "PADLO" define which bits - low or high, * in the incomplete high byte, are filled with padding bits. * * The bus formats are grouped by type, bus_width, bits per component, samples * per pixel and order of subsamples. Numerical values are sorted using generic * numerical sort order (8 thus comes before 10). * * As their value can't change when a new bus format is inserted in the * enumeration, the bus formats are explicitly given a numerical value. The next * free values for each category are listed below, update them when inserting * new pixel codes. */ #define MEDIA_BUS_FMT_FIXED 0x0001 /* RGB - next is 0x101b */ #define MEDIA_BUS_FMT_RGB444_1X12 0x1016 #define MEDIA_BUS_FMT_RGB444_2X8_PADHI_BE 0x1001 #define MEDIA_BUS_FMT_RGB444_2X8_PADHI_LE 0x1002 #define MEDIA_BUS_FMT_RGB555_2X8_PADHI_BE 0x1003 #define MEDIA_BUS_FMT_RGB555_2X8_PADHI_LE 0x1004 #define MEDIA_BUS_FMT_RGB565_1X16 0x1017 #define MEDIA_BUS_FMT_BGR565_2X8_BE 0x1005 #define MEDIA_BUS_FMT_BGR565_2X8_LE 0x1006 #define MEDIA_BUS_FMT_RGB565_2X8_BE 0x1007 #define MEDIA_BUS_FMT_RGB565_2X8_LE 0x1008 #define MEDIA_BUS_FMT_RGB666_1X18 0x1009 #define MEDIA_BUS_FMT_RBG888_1X24 0x100e #define MEDIA_BUS_FMT_RGB666_1X24_CPADHI 0x1015 #define MEDIA_BUS_FMT_RGB666_1X7X3_SPWG 0x1010 #define MEDIA_BUS_FMT_BGR888_1X24 0x1013 #define MEDIA_BUS_FMT_GBR888_1X24 0x1014 #define MEDIA_BUS_FMT_RGB888_1X24 0x100a #define MEDIA_BUS_FMT_RGB888_2X12_BE 0x100b #define MEDIA_BUS_FMT_RGB888_2X12_LE 0x100c #define MEDIA_BUS_FMT_RGB888_1X7X4_SPWG 0x1011 #define MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA 0x1012 #define MEDIA_BUS_FMT_ARGB8888_1X32 0x100d #define MEDIA_BUS_FMT_RGB888_1X32_PADHI 0x100f #define MEDIA_BUS_FMT_RGB101010_1X30 0x1018 #define MEDIA_BUS_FMT_RGB121212_1X36 0x1019 #define MEDIA_BUS_FMT_RGB161616_1X48 0x101a /* YUV (including grey) - next is 0x202c */ #define MEDIA_BUS_FMT_Y8_1X8 0x2001 #define MEDIA_BUS_FMT_UV8_1X8 0x2015 #define MEDIA_BUS_FMT_UYVY8_1_5X8 0x2002 #define MEDIA_BUS_FMT_VYUY8_1_5X8 0x2003 #define MEDIA_BUS_FMT_YUYV8_1_5X8 0x2004 #define MEDIA_BUS_FMT_YVYU8_1_5X8 0x2005 #define MEDIA_BUS_FMT_UYVY8_2X8 0x2006 #define MEDIA_BUS_FMT_VYUY8_2X8 0x2007 #define MEDIA_BUS_FMT_YUYV8_2X8 0x2008 #define MEDIA_BUS_FMT_YVYU8_2X8 0x2009 #define MEDIA_BUS_FMT_Y10_1X10 0x200a #define MEDIA_BUS_FMT_UYVY10_2X10 0x2018 #define MEDIA_BUS_FMT_VYUY10_2X10 0x2019 #define MEDIA_BUS_FMT_YUYV10_2X10 0x200b #define MEDIA_BUS_FMT_YVYU10_2X10 0x200c #define MEDIA_BUS_FMT_Y12_1X12 0x2013 #define MEDIA_BUS_FMT_UYVY12_2X12 0x201c #define MEDIA_BUS_FMT_VYUY12_2X12 0x201d #define MEDIA_BUS_FMT_YUYV12_2X12 0x201e #define MEDIA_BUS_FMT_YVYU12_2X12 0x201f #define MEDIA_BUS_FMT_UYVY8_1X16 0x200f #define MEDIA_BUS_FMT_VYUY8_1X16 0x2010 #define MEDIA_BUS_FMT_YUYV8_1X16 0x2011 #define MEDIA_BUS_FMT_YVYU8_1X16 0x2012 #define MEDIA_BUS_FMT_YDYUYDYV8_1X16 0x2014 #define MEDIA_BUS_FMT_UYVY10_1X20 0x201a #define MEDIA_BUS_FMT_VYUY10_1X20 0x201b #define MEDIA_BUS_FMT_YUYV10_1X20 0x200d #define MEDIA_BUS_FMT_YVYU10_1X20 0x200e #define MEDIA_BUS_FMT_VUY8_1X24 0x2024 #define MEDIA_BUS_FMT_YUV8_1X24 0x2025 #define MEDIA_BUS_FMT_UYYVYY8_0_5X24 0x2026 #define MEDIA_BUS_FMT_UYVY12_1X24 0x2020 #define MEDIA_BUS_FMT_VYUY12_1X24 0x2021 #define MEDIA_BUS_FMT_YUYV12_1X24 0x2022 #define MEDIA_BUS_FMT_YVYU12_1X24 0x2023 #define MEDIA_BUS_FMT_YUV10_1X30 0x2016 #define MEDIA_BUS_FMT_UYYVYY10_0_5X30 0x2027 #define MEDIA_BUS_FMT_AYUV8_1X32 0x2017 #define MEDIA_BUS_FMT_UYYVYY12_0_5X36 0x2028 #define MEDIA_BUS_FMT_YUV12_1X36 0x2029 #define MEDIA_BUS_FMT_YUV16_1X48 0x202a #define MEDIA_BUS_FMT_UYYVYY16_0_5X48 0x202b /* Bayer - next is 0x3021 */ #define MEDIA_BUS_FMT_SBGGR8_1X8 0x3001 #define MEDIA_BUS_FMT_SGBRG8_1X8 0x3013 #define MEDIA_BUS_FMT_SGRBG8_1X8 0x3002 #define MEDIA_BUS_FMT_SRGGB8_1X8 0x3014 #define MEDIA_BUS_FMT_SBGGR10_ALAW8_1X8 0x3015 #define MEDIA_BUS_FMT_SGBRG10_ALAW8_1X8 0x3016 #define MEDIA_BUS_FMT_SGRBG10_ALAW8_1X8 0x3017 #define MEDIA_BUS_FMT_SRGGB10_ALAW8_1X8 0x3018 #define MEDIA_BUS_FMT_SBGGR10_DPCM8_1X8 0x300b #define MEDIA_BUS_FMT_SGBRG10_DPCM8_1X8 0x300c #define MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8 0x3009 #define MEDIA_BUS_FMT_SRGGB10_DPCM8_1X8 0x300d #define MEDIA_BUS_FMT_SBGGR10_2X8_PADHI_BE 0x3003 #define MEDIA_BUS_FMT_SBGGR10_2X8_PADHI_LE 0x3004 #define MEDIA_BUS_FMT_SBGGR10_2X8_PADLO_BE 0x3005 #define MEDIA_BUS_FMT_SBGGR10_2X8_PADLO_LE 0x3006 #define MEDIA_BUS_FMT_SBGGR10_1X10 0x3007 #define MEDIA_BUS_FMT_SGBRG10_1X10 0x300e #define MEDIA_BUS_FMT_SGRBG10_1X10 0x300a #define MEDIA_BUS_FMT_SRGGB10_1X10 0x300f #define MEDIA_BUS_FMT_SBGGR12_1X12 0x3008 #define MEDIA_BUS_FMT_SGBRG12_1X12 0x3010 #define MEDIA_BUS_FMT_SGRBG12_1X12 0x3011 #define MEDIA_BUS_FMT_SRGGB12_1X12 0x3012 #define MEDIA_BUS_FMT_SBGGR14_1X14 0x3019 #define MEDIA_BUS_FMT_SGBRG14_1X14 0x301a #define MEDIA_BUS_FMT_SGRBG14_1X14 0x301b #define MEDIA_BUS_FMT_SRGGB14_1X14 0x301c #define MEDIA_BUS_FMT_SBGGR16_1X16 0x301d #define MEDIA_BUS_FMT_SGBRG16_1X16 0x301e #define MEDIA_BUS_FMT_SGRBG16_1X16 0x301f #define MEDIA_BUS_FMT_SRGGB16_1X16 0x3020 /* JPEG compressed formats - next is 0x4002 */ #define MEDIA_BUS_FMT_JPEG_1X8 0x4001 /* Vendor specific formats - next is 0x5002 */ /* S5C73M3 sensor specific interleaved UYVY and JPEG */ #define MEDIA_BUS_FMT_S5C_UYVY_JPEG_1X8 0x5001 /* HSV - next is 0x6002 */ #define MEDIA_BUS_FMT_AHSV8888_1X32 0x6001 #endif /* __LINUX_MEDIA_BUS_FORMAT_H */ linux/screen_info.h000064400000004657151027430560010365 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _SCREEN_INFO_H #define _SCREEN_INFO_H #include /* * These are set up by the setup-routine at boot-time: */ struct screen_info { __u8 orig_x; /* 0x00 */ __u8 orig_y; /* 0x01 */ __u16 ext_mem_k; /* 0x02 */ __u16 orig_video_page; /* 0x04 */ __u8 orig_video_mode; /* 0x06 */ __u8 orig_video_cols; /* 0x07 */ __u8 flags; /* 0x08 */ __u8 unused2; /* 0x09 */ __u16 orig_video_ega_bx;/* 0x0a */ __u16 unused3; /* 0x0c */ __u8 orig_video_lines; /* 0x0e */ __u8 orig_video_isVGA; /* 0x0f */ __u16 orig_video_points;/* 0x10 */ /* VESA graphic mode -- linear frame buffer */ __u16 lfb_width; /* 0x12 */ __u16 lfb_height; /* 0x14 */ __u16 lfb_depth; /* 0x16 */ __u32 lfb_base; /* 0x18 */ __u32 lfb_size; /* 0x1c */ __u16 cl_magic, cl_offset; /* 0x20 */ __u16 lfb_linelength; /* 0x24 */ __u8 red_size; /* 0x26 */ __u8 red_pos; /* 0x27 */ __u8 green_size; /* 0x28 */ __u8 green_pos; /* 0x29 */ __u8 blue_size; /* 0x2a */ __u8 blue_pos; /* 0x2b */ __u8 rsvd_size; /* 0x2c */ __u8 rsvd_pos; /* 0x2d */ __u16 vesapm_seg; /* 0x2e */ __u16 vesapm_off; /* 0x30 */ __u16 pages; /* 0x32 */ __u16 vesa_attributes; /* 0x34 */ __u32 capabilities; /* 0x36 */ __u32 ext_lfb_base; /* 0x3a */ __u8 _reserved[2]; /* 0x3e */ } __attribute__((packed)); #define VIDEO_TYPE_MDA 0x10 /* Monochrome Text Display */ #define VIDEO_TYPE_CGA 0x11 /* CGA Display */ #define VIDEO_TYPE_EGAM 0x20 /* EGA/VGA in Monochrome Mode */ #define VIDEO_TYPE_EGAC 0x21 /* EGA in Color Mode */ #define VIDEO_TYPE_VGAC 0x22 /* VGA+ in Color Mode */ #define VIDEO_TYPE_VLFB 0x23 /* VESA VGA in graphic mode */ #define VIDEO_TYPE_PICA_S3 0x30 /* ACER PICA-61 local S3 video */ #define VIDEO_TYPE_MIPS_G364 0x31 /* MIPS Magnum 4000 G364 video */ #define VIDEO_TYPE_SGI 0x33 /* Various SGI graphics hardware */ #define VIDEO_TYPE_TGAC 0x40 /* DEC TGA */ #define VIDEO_TYPE_SUN 0x50 /* Sun frame buffer. */ #define VIDEO_TYPE_SUNPCI 0x51 /* Sun PCI based frame buffer. */ #define VIDEO_TYPE_PMAC 0x60 /* PowerMacintosh frame buffer. */ #define VIDEO_TYPE_EFI 0x70 /* EFI graphic mode */ #define VIDEO_FLAGS_NOCURSOR (1 << 0) /* The video mode has no cursor set */ #define VIDEO_CAPABILITY_SKIP_QUIRKS (1 << 0) #define VIDEO_CAPABILITY_64BIT_BASE (1 << 1) /* Frame buffer base is 64-bit */ #endif /* _SCREEN_INFO_H */ linux/tiocl.h000064400000003301151027430560007166 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TIOCL_H #define _LINUX_TIOCL_H #define TIOCL_SETSEL 2 /* set a selection */ #define TIOCL_SELCHAR 0 /* select characters */ #define TIOCL_SELWORD 1 /* select whole words */ #define TIOCL_SELLINE 2 /* select whole lines */ #define TIOCL_SELPOINTER 3 /* show the pointer */ #define TIOCL_SELCLEAR 4 /* clear visibility of selection */ #define TIOCL_SELMOUSEREPORT 16 /* report beginning of selection */ #define TIOCL_SELBUTTONMASK 15 /* button mask for report */ /* selection extent */ struct tiocl_selection { unsigned short xs; /* X start */ unsigned short ys; /* Y start */ unsigned short xe; /* X end */ unsigned short ye; /* Y end */ unsigned short sel_mode; /* selection mode */ }; #define TIOCL_PASTESEL 3 /* paste previous selection */ #define TIOCL_UNBLANKSCREEN 4 /* unblank screen */ #define TIOCL_SELLOADLUT 5 /* set characters to be considered alphabetic when selecting */ /* u32[8] bit array, 4 bytes-aligned with type */ /* these two don't return a value: they write it back in the type */ #define TIOCL_GETSHIFTSTATE 6 /* write shift state */ #define TIOCL_GETMOUSEREPORTING 7 /* write whether mouse event are reported */ #define TIOCL_SETVESABLANK 10 /* set vesa blanking mode */ #define TIOCL_SETKMSGREDIRECT 11 /* restrict kernel messages to a vt */ #define TIOCL_GETFGCONSOLE 12 /* get foreground vt */ #define TIOCL_SCROLLCONSOLE 13 /* scroll console */ #define TIOCL_BLANKSCREEN 14 /* keep screen blank even if a key is pressed */ #define TIOCL_BLANKEDSCREEN 15 /* return which vt was blanked */ #define TIOCL_GETKMSGREDIRECT 17 /* get the vt the kernel messages are restricted to */ #endif /* _LINUX_TIOCL_H */ linux/sysinfo.h000064400000002031151027430560007545 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SYSINFO_H #define _LINUX_SYSINFO_H #include #define SI_LOAD_SHIFT 16 struct sysinfo { __kernel_long_t uptime; /* Seconds since boot */ __kernel_ulong_t loads[3]; /* 1, 5, and 15 minute load averages */ __kernel_ulong_t totalram; /* Total usable main memory size */ __kernel_ulong_t freeram; /* Available memory size */ __kernel_ulong_t sharedram; /* Amount of shared memory */ __kernel_ulong_t bufferram; /* Memory used by buffers */ __kernel_ulong_t totalswap; /* Total swap space size */ __kernel_ulong_t freeswap; /* swap space still available */ __u16 procs; /* Number of current processes */ __u16 pad; /* Explicit padding for m68k */ __kernel_ulong_t totalhigh; /* Total high memory size */ __kernel_ulong_t freehigh; /* Available high memory size */ __u32 mem_unit; /* Memory unit size in bytes */ char _f[20-2*sizeof(__kernel_ulong_t)-sizeof(__u32)]; /* Padding: libc5 uses this.. */ }; #endif /* _LINUX_SYSINFO_H */ linux/dlm_device.h000064400000004757151027430560010167 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /****************************************************************************** ******************************************************************************* ** ** Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. ** Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved. ** ** This copyrighted material is made available to anyone wishing to use, ** modify, copy, or redistribute it subject to the terms and conditions ** of the GNU General Public License v.2. ** ******************************************************************************* ******************************************************************************/ #ifndef _LINUX_DLM_DEVICE_H #define _LINUX_DLM_DEVICE_H /* This is the device interface for dlm, most users will use a library * interface. */ #include #include #define DLM_USER_LVB_LEN 32 /* Version of the device interface */ #define DLM_DEVICE_VERSION_MAJOR 6 #define DLM_DEVICE_VERSION_MINOR 0 #define DLM_DEVICE_VERSION_PATCH 2 /* struct passed to the lock write */ struct dlm_lock_params { __u8 mode; __u8 namelen; __u16 unused; __u32 flags; __u32 lkid; __u32 parent; __u64 xid; __u64 timeout; void *castparam; void *castaddr; void *bastparam; void *bastaddr; struct dlm_lksb *lksb; char lvb[DLM_USER_LVB_LEN]; char name[0]; }; struct dlm_lspace_params { __u32 flags; __u32 minor; char name[0]; }; struct dlm_purge_params { __u32 nodeid; __u32 pid; }; struct dlm_write_request { __u32 version[3]; __u8 cmd; __u8 is64bit; __u8 unused[2]; union { struct dlm_lock_params lock; struct dlm_lspace_params lspace; struct dlm_purge_params purge; } i; }; struct dlm_device_version { __u32 version[3]; }; /* struct read from the "device" fd, consists mainly of userspace pointers for the library to use */ struct dlm_lock_result { __u32 version[3]; __u32 length; void * user_astaddr; void * user_astparam; struct dlm_lksb * user_lksb; struct dlm_lksb lksb; __u8 bast_mode; __u8 unused[3]; /* Offsets may be zero if no data is present */ __u32 lvb_offset; }; /* Commands passed to the device */ #define DLM_USER_LOCK 1 #define DLM_USER_UNLOCK 2 #define DLM_USER_QUERY 3 #define DLM_USER_CREATE_LOCKSPACE 4 #define DLM_USER_REMOVE_LOCKSPACE 5 #define DLM_USER_PURGE 6 #define DLM_USER_DEADLOCK 7 /* Lockspace flags */ #define DLM_USER_LSFLG_AUTOFREE 1 #define DLM_USER_LSFLG_FORCEFREE 2 #endif linux/sem.h000064400000005743151027430560006654 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SEM_H #define _LINUX_SEM_H #include /* semop flags */ #define SEM_UNDO 0x1000 /* undo the operation on exit */ /* semctl Command Definitions. */ #define GETPID 11 /* get sempid */ #define GETVAL 12 /* get semval */ #define GETALL 13 /* get all semval's */ #define GETNCNT 14 /* get semncnt */ #define GETZCNT 15 /* get semzcnt */ #define SETVAL 16 /* set semval */ #define SETALL 17 /* set all semval's */ /* ipcs ctl cmds */ #define SEM_STAT 18 #define SEM_INFO 19 #define SEM_STAT_ANY 20 /* Obsolete, used only for backwards compatibility and libc5 compiles */ struct semid_ds { struct ipc_perm sem_perm; /* permissions .. see ipc.h */ __kernel_time_t sem_otime; /* last semop time */ __kernel_time_t sem_ctime; /* create/last semctl() time */ struct sem *sem_base; /* ptr to first semaphore in array */ struct sem_queue *sem_pending; /* pending operations to be processed */ struct sem_queue **sem_pending_last; /* last pending operation */ struct sem_undo *undo; /* undo requests on this array */ unsigned short sem_nsems; /* no. of semaphores in array */ }; /* Include the definition of semid64_ds */ #include /* semop system calls takes an array of these. */ struct sembuf { unsigned short sem_num; /* semaphore index in array */ short sem_op; /* semaphore operation */ short sem_flg; /* operation flags */ }; /* arg for semctl system calls. */ union semun { int val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */ unsigned short *array; /* array for GETALL & SETALL */ struct seminfo *__buf; /* buffer for IPC_INFO */ void *__pad; }; struct seminfo { int semmap; int semmni; int semmns; int semmnu; int semmsl; int semopm; int semume; int semusz; int semvmx; int semaem; }; /* * SEMMNI, SEMMSL and SEMMNS are default values which can be * modified by sysctl. * The values has been chosen to be larger than necessary for any * known configuration. * * SEMOPM should not be increased beyond 1000, otherwise there is the * risk that semop()/semtimedop() fails due to kernel memory fragmentation when * allocating the sop array. */ #define SEMMNI 32000 /* <= IPCMNI max # of semaphore identifiers */ #define SEMMSL 32000 /* <= INT_MAX max num of semaphores per id */ #define SEMMNS (SEMMNI*SEMMSL) /* <= INT_MAX max # of semaphores in system */ #define SEMOPM 500 /* <= 1 000 max num of ops per semop call */ #define SEMVMX 32767 /* <= 32767 semaphore maximum value */ #define SEMAEM SEMVMX /* adjust on exit max value */ /* unused */ #define SEMUME SEMOPM /* max num of undo entries per process */ #define SEMMNU SEMMNS /* num of undo structures system wide */ #define SEMMAP SEMMNS /* # of entries in semaphore map */ #define SEMUSZ 20 /* sizeof struct sem_undo */ #endif /* _LINUX_SEM_H */ linux/qnxtypes.h000064400000001160151027430560007750 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Name : qnxtypes.h * Author : Richard Frowijn * Function : standard qnx types * History : 22-03-1998 created * */ #ifndef _QNX4TYPES_H #define _QNX4TYPES_H #include typedef __le16 qnx4_nxtnt_t; typedef __u8 qnx4_ftype_t; typedef struct { __le32 xtnt_blk; __le32 xtnt_size; } qnx4_xtnt_t; typedef __le16 qnx4_mode_t; typedef __le16 qnx4_muid_t; typedef __le16 qnx4_mgid_t; typedef __le32 qnx4_off_t; typedef __le16 qnx4_nlink_t; #endif linux/virtio_crypto.h000064400000033062151027430560010777 0ustar00#ifndef _VIRTIO_CRYPTO_H #define _VIRTIO_CRYPTO_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IBM OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #define VIRTIO_CRYPTO_SERVICE_CIPHER 0 #define VIRTIO_CRYPTO_SERVICE_HASH 1 #define VIRTIO_CRYPTO_SERVICE_MAC 2 #define VIRTIO_CRYPTO_SERVICE_AEAD 3 #define VIRTIO_CRYPTO_OPCODE(service, op) (((service) << 8) | (op)) struct virtio_crypto_ctrl_header { #define VIRTIO_CRYPTO_CIPHER_CREATE_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_CIPHER, 0x02) #define VIRTIO_CRYPTO_CIPHER_DESTROY_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_CIPHER, 0x03) #define VIRTIO_CRYPTO_HASH_CREATE_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_HASH, 0x02) #define VIRTIO_CRYPTO_HASH_DESTROY_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_HASH, 0x03) #define VIRTIO_CRYPTO_MAC_CREATE_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_MAC, 0x02) #define VIRTIO_CRYPTO_MAC_DESTROY_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_MAC, 0x03) #define VIRTIO_CRYPTO_AEAD_CREATE_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_AEAD, 0x02) #define VIRTIO_CRYPTO_AEAD_DESTROY_SESSION \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_AEAD, 0x03) __le32 opcode; __le32 algo; __le32 flag; /* data virtqueue id */ __le32 queue_id; }; struct virtio_crypto_cipher_session_para { #define VIRTIO_CRYPTO_NO_CIPHER 0 #define VIRTIO_CRYPTO_CIPHER_ARC4 1 #define VIRTIO_CRYPTO_CIPHER_AES_ECB 2 #define VIRTIO_CRYPTO_CIPHER_AES_CBC 3 #define VIRTIO_CRYPTO_CIPHER_AES_CTR 4 #define VIRTIO_CRYPTO_CIPHER_DES_ECB 5 #define VIRTIO_CRYPTO_CIPHER_DES_CBC 6 #define VIRTIO_CRYPTO_CIPHER_3DES_ECB 7 #define VIRTIO_CRYPTO_CIPHER_3DES_CBC 8 #define VIRTIO_CRYPTO_CIPHER_3DES_CTR 9 #define VIRTIO_CRYPTO_CIPHER_KASUMI_F8 10 #define VIRTIO_CRYPTO_CIPHER_SNOW3G_UEA2 11 #define VIRTIO_CRYPTO_CIPHER_AES_F8 12 #define VIRTIO_CRYPTO_CIPHER_AES_XTS 13 #define VIRTIO_CRYPTO_CIPHER_ZUC_EEA3 14 __le32 algo; /* length of key */ __le32 keylen; #define VIRTIO_CRYPTO_OP_ENCRYPT 1 #define VIRTIO_CRYPTO_OP_DECRYPT 2 /* encrypt or decrypt */ __le32 op; __le32 padding; }; struct virtio_crypto_session_input { /* Device-writable part */ __le64 session_id; __le32 status; __le32 padding; }; struct virtio_crypto_cipher_session_req { struct virtio_crypto_cipher_session_para para; __u8 padding[32]; }; struct virtio_crypto_hash_session_para { #define VIRTIO_CRYPTO_NO_HASH 0 #define VIRTIO_CRYPTO_HASH_MD5 1 #define VIRTIO_CRYPTO_HASH_SHA1 2 #define VIRTIO_CRYPTO_HASH_SHA_224 3 #define VIRTIO_CRYPTO_HASH_SHA_256 4 #define VIRTIO_CRYPTO_HASH_SHA_384 5 #define VIRTIO_CRYPTO_HASH_SHA_512 6 #define VIRTIO_CRYPTO_HASH_SHA3_224 7 #define VIRTIO_CRYPTO_HASH_SHA3_256 8 #define VIRTIO_CRYPTO_HASH_SHA3_384 9 #define VIRTIO_CRYPTO_HASH_SHA3_512 10 #define VIRTIO_CRYPTO_HASH_SHA3_SHAKE128 11 #define VIRTIO_CRYPTO_HASH_SHA3_SHAKE256 12 __le32 algo; /* hash result length */ __le32 hash_result_len; __u8 padding[8]; }; struct virtio_crypto_hash_create_session_req { struct virtio_crypto_hash_session_para para; __u8 padding[40]; }; struct virtio_crypto_mac_session_para { #define VIRTIO_CRYPTO_NO_MAC 0 #define VIRTIO_CRYPTO_MAC_HMAC_MD5 1 #define VIRTIO_CRYPTO_MAC_HMAC_SHA1 2 #define VIRTIO_CRYPTO_MAC_HMAC_SHA_224 3 #define VIRTIO_CRYPTO_MAC_HMAC_SHA_256 4 #define VIRTIO_CRYPTO_MAC_HMAC_SHA_384 5 #define VIRTIO_CRYPTO_MAC_HMAC_SHA_512 6 #define VIRTIO_CRYPTO_MAC_CMAC_3DES 25 #define VIRTIO_CRYPTO_MAC_CMAC_AES 26 #define VIRTIO_CRYPTO_MAC_KASUMI_F9 27 #define VIRTIO_CRYPTO_MAC_SNOW3G_UIA2 28 #define VIRTIO_CRYPTO_MAC_GMAC_AES 41 #define VIRTIO_CRYPTO_MAC_GMAC_TWOFISH 42 #define VIRTIO_CRYPTO_MAC_CBCMAC_AES 49 #define VIRTIO_CRYPTO_MAC_CBCMAC_KASUMI_F9 50 #define VIRTIO_CRYPTO_MAC_XCBC_AES 53 __le32 algo; /* hash result length */ __le32 hash_result_len; /* length of authenticated key */ __le32 auth_key_len; __le32 padding; }; struct virtio_crypto_mac_create_session_req { struct virtio_crypto_mac_session_para para; __u8 padding[40]; }; struct virtio_crypto_aead_session_para { #define VIRTIO_CRYPTO_NO_AEAD 0 #define VIRTIO_CRYPTO_AEAD_GCM 1 #define VIRTIO_CRYPTO_AEAD_CCM 2 #define VIRTIO_CRYPTO_AEAD_CHACHA20_POLY1305 3 __le32 algo; /* length of key */ __le32 key_len; /* hash result length */ __le32 hash_result_len; /* length of the additional authenticated data (AAD) in bytes */ __le32 aad_len; /* encrypt or decrypt, See above VIRTIO_CRYPTO_OP_* */ __le32 op; __le32 padding; }; struct virtio_crypto_aead_create_session_req { struct virtio_crypto_aead_session_para para; __u8 padding[32]; }; struct virtio_crypto_alg_chain_session_para { #define VIRTIO_CRYPTO_SYM_ALG_CHAIN_ORDER_HASH_THEN_CIPHER 1 #define VIRTIO_CRYPTO_SYM_ALG_CHAIN_ORDER_CIPHER_THEN_HASH 2 __le32 alg_chain_order; /* Plain hash */ #define VIRTIO_CRYPTO_SYM_HASH_MODE_PLAIN 1 /* Authenticated hash (mac) */ #define VIRTIO_CRYPTO_SYM_HASH_MODE_AUTH 2 /* Nested hash */ #define VIRTIO_CRYPTO_SYM_HASH_MODE_NESTED 3 __le32 hash_mode; struct virtio_crypto_cipher_session_para cipher_param; union { struct virtio_crypto_hash_session_para hash_param; struct virtio_crypto_mac_session_para mac_param; __u8 padding[16]; } u; /* length of the additional authenticated data (AAD) in bytes */ __le32 aad_len; __le32 padding; }; struct virtio_crypto_alg_chain_session_req { struct virtio_crypto_alg_chain_session_para para; }; struct virtio_crypto_sym_create_session_req { union { struct virtio_crypto_cipher_session_req cipher; struct virtio_crypto_alg_chain_session_req chain; __u8 padding[48]; } u; /* Device-readable part */ /* No operation */ #define VIRTIO_CRYPTO_SYM_OP_NONE 0 /* Cipher only operation on the data */ #define VIRTIO_CRYPTO_SYM_OP_CIPHER 1 /* * Chain any cipher with any hash or mac operation. The order * depends on the value of alg_chain_order param */ #define VIRTIO_CRYPTO_SYM_OP_ALGORITHM_CHAINING 2 __le32 op_type; __le32 padding; }; struct virtio_crypto_destroy_session_req { /* Device-readable part */ __le64 session_id; __u8 padding[48]; }; /* The request of the control virtqueue's packet */ struct virtio_crypto_op_ctrl_req { struct virtio_crypto_ctrl_header header; union { struct virtio_crypto_sym_create_session_req sym_create_session; struct virtio_crypto_hash_create_session_req hash_create_session; struct virtio_crypto_mac_create_session_req mac_create_session; struct virtio_crypto_aead_create_session_req aead_create_session; struct virtio_crypto_destroy_session_req destroy_session; __u8 padding[56]; } u; }; struct virtio_crypto_op_header { #define VIRTIO_CRYPTO_CIPHER_ENCRYPT \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_CIPHER, 0x00) #define VIRTIO_CRYPTO_CIPHER_DECRYPT \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_CIPHER, 0x01) #define VIRTIO_CRYPTO_HASH \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_HASH, 0x00) #define VIRTIO_CRYPTO_MAC \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_MAC, 0x00) #define VIRTIO_CRYPTO_AEAD_ENCRYPT \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_AEAD, 0x00) #define VIRTIO_CRYPTO_AEAD_DECRYPT \ VIRTIO_CRYPTO_OPCODE(VIRTIO_CRYPTO_SERVICE_AEAD, 0x01) __le32 opcode; /* algo should be service-specific algorithms */ __le32 algo; /* session_id should be service-specific algorithms */ __le64 session_id; /* control flag to control the request */ __le32 flag; __le32 padding; }; struct virtio_crypto_cipher_para { /* * Byte Length of valid IV/Counter * * For block ciphers in CBC or F8 mode, or for Kasumi in F8 mode, or for * SNOW3G in UEA2 mode, this is the length of the IV (which * must be the same as the block length of the cipher). * For block ciphers in CTR mode, this is the length of the counter * (which must be the same as the block length of the cipher). * For AES-XTS, this is the 128bit tweak, i, from IEEE Std 1619-2007. * * The IV/Counter will be updated after every partial cryptographic * operation. */ __le32 iv_len; /* length of source data */ __le32 src_data_len; /* length of dst data */ __le32 dst_data_len; __le32 padding; }; struct virtio_crypto_hash_para { /* length of source data */ __le32 src_data_len; /* hash result length */ __le32 hash_result_len; }; struct virtio_crypto_mac_para { struct virtio_crypto_hash_para hash; }; struct virtio_crypto_aead_para { /* * Byte Length of valid IV data pointed to by the below iv_addr * parameter. * * For GCM mode, this is either 12 (for 96-bit IVs) or 16, in which * case iv_addr points to J0. * For CCM mode, this is the length of the nonce, which can be in the * range 7 to 13 inclusive. */ __le32 iv_len; /* length of additional auth data */ __le32 aad_len; /* length of source data */ __le32 src_data_len; /* length of dst data */ __le32 dst_data_len; }; struct virtio_crypto_cipher_data_req { /* Device-readable part */ struct virtio_crypto_cipher_para para; __u8 padding[24]; }; struct virtio_crypto_hash_data_req { /* Device-readable part */ struct virtio_crypto_hash_para para; __u8 padding[40]; }; struct virtio_crypto_mac_data_req { /* Device-readable part */ struct virtio_crypto_mac_para para; __u8 padding[40]; }; struct virtio_crypto_alg_chain_data_para { __le32 iv_len; /* Length of source data */ __le32 src_data_len; /* Length of destination data */ __le32 dst_data_len; /* Starting point for cipher processing in source data */ __le32 cipher_start_src_offset; /* Length of the source data that the cipher will be computed on */ __le32 len_to_cipher; /* Starting point for hash processing in source data */ __le32 hash_start_src_offset; /* Length of the source data that the hash will be computed on */ __le32 len_to_hash; /* Length of the additional auth data */ __le32 aad_len; /* Length of the hash result */ __le32 hash_result_len; __le32 reserved; }; struct virtio_crypto_alg_chain_data_req { /* Device-readable part */ struct virtio_crypto_alg_chain_data_para para; }; struct virtio_crypto_sym_data_req { union { struct virtio_crypto_cipher_data_req cipher; struct virtio_crypto_alg_chain_data_req chain; __u8 padding[40]; } u; /* See above VIRTIO_CRYPTO_SYM_OP_* */ __le32 op_type; __le32 padding; }; struct virtio_crypto_aead_data_req { /* Device-readable part */ struct virtio_crypto_aead_para para; __u8 padding[32]; }; /* The request of the data virtqueue's packet */ struct virtio_crypto_op_data_req { struct virtio_crypto_op_header header; union { struct virtio_crypto_sym_data_req sym_req; struct virtio_crypto_hash_data_req hash_req; struct virtio_crypto_mac_data_req mac_req; struct virtio_crypto_aead_data_req aead_req; __u8 padding[48]; } u; }; #define VIRTIO_CRYPTO_OK 0 #define VIRTIO_CRYPTO_ERR 1 #define VIRTIO_CRYPTO_BADMSG 2 #define VIRTIO_CRYPTO_NOTSUPP 3 #define VIRTIO_CRYPTO_INVSESS 4 /* Invalid session id */ /* The accelerator hardware is ready */ #define VIRTIO_CRYPTO_S_HW_READY (1 << 0) struct virtio_crypto_config { /* See VIRTIO_CRYPTO_OP_* above */ __u32 status; /* * Maximum number of data queue */ __u32 max_dataqueues; /* * Specifies the services mask which the device support, * see VIRTIO_CRYPTO_SERVICE_* above */ __u32 crypto_services; /* Detailed algorithms mask */ __u32 cipher_algo_l; __u32 cipher_algo_h; __u32 hash_algo; __u32 mac_algo_l; __u32 mac_algo_h; __u32 aead_algo; /* Maximum length of cipher key */ __u32 max_cipher_key_len; /* Maximum length of authenticated key */ __u32 max_auth_key_len; __u32 reserve; /* Maximum size of each crypto request's content */ __u64 max_size; }; struct virtio_crypto_inhdr { /* See VIRTIO_CRYPTO_* above */ __u8 status; }; #endif linux/genwqe/genwqe_card.h000064400000042612151027430560011631 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __GENWQE_CARD_H__ #define __GENWQE_CARD_H__ /** * IBM Accelerator Family 'GenWQE' * * (C) Copyright IBM Corp. 2013 * * Author: Frank Haverkamp * Author: Joerg-Stephan Vogt * Author: Michael Jung * Author: Michael Ruettger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2 only) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ /* * User-space API for the GenWQE card. For debugging and test purposes * the register addresses are included here too. */ #include #include /* Basename of sysfs, debugfs and /dev interfaces */ #define GENWQE_DEVNAME "genwqe" #define GENWQE_TYPE_ALTERA_230 0x00 /* GenWQE4 Stratix-IV-230 */ #define GENWQE_TYPE_ALTERA_530 0x01 /* GenWQE4 Stratix-IV-530 */ #define GENWQE_TYPE_ALTERA_A4 0x02 /* GenWQE5 A4 Stratix-V-A4 */ #define GENWQE_TYPE_ALTERA_A7 0x03 /* GenWQE5 A7 Stratix-V-A7 */ /* MMIO Unit offsets: Each UnitID occupies a defined address range */ #define GENWQE_UID_OFFS(uid) ((uid) << 24) #define GENWQE_SLU_OFFS GENWQE_UID_OFFS(0) #define GENWQE_HSU_OFFS GENWQE_UID_OFFS(1) #define GENWQE_APP_OFFS GENWQE_UID_OFFS(2) #define GENWQE_MAX_UNITS 3 /* Common offsets per UnitID */ #define IO_EXTENDED_ERROR_POINTER 0x00000048 #define IO_ERROR_INJECT_SELECTOR 0x00000060 #define IO_EXTENDED_DIAG_SELECTOR 0x00000070 #define IO_EXTENDED_DIAG_READ_MBX 0x00000078 #define IO_EXTENDED_DIAG_MAP(ring) (0x00000500 | ((ring) << 3)) #define GENWQE_EXTENDED_DIAG_SELECTOR(ring, trace) (((ring) << 8) | (trace)) /* UnitID 0: Service Layer Unit (SLU) */ /* SLU: Unit Configuration Register */ #define IO_SLU_UNITCFG 0x00000000 #define IO_SLU_UNITCFG_TYPE_MASK 0x000000000ff00000 /* 27:20 */ /* SLU: Fault Isolation Register (FIR) (ac_slu_fir) */ #define IO_SLU_FIR 0x00000008 /* read only, wr direct */ #define IO_SLU_FIR_CLR 0x00000010 /* read and clear */ /* SLU: First Error Capture Register (FEC/WOF) */ #define IO_SLU_FEC 0x00000018 #define IO_SLU_ERR_ACT_MASK 0x00000020 #define IO_SLU_ERR_ATTN_MASK 0x00000028 #define IO_SLU_FIRX1_ACT_MASK 0x00000030 #define IO_SLU_FIRX0_ACT_MASK 0x00000038 #define IO_SLU_SEC_LEM_DEBUG_OVR 0x00000040 #define IO_SLU_EXTENDED_ERR_PTR 0x00000048 #define IO_SLU_COMMON_CONFIG 0x00000060 #define IO_SLU_FLASH_FIR 0x00000108 #define IO_SLU_SLC_FIR 0x00000110 #define IO_SLU_RIU_TRAP 0x00000280 #define IO_SLU_FLASH_FEC 0x00000308 #define IO_SLU_SLC_FEC 0x00000310 /* * The Virtual Function's Access is from offset 0x00010000 * The Physical Function's Access is from offset 0x00050000 * Single Shared Registers exists only at offset 0x00060000 * * SLC: Queue Virtual Window Window for accessing into a specific VF * queue. When accessing the 0x10000 space using the 0x50000 address * segment, the value indicated here is used to specify which VF * register is decoded. This register, and the 0x50000 register space * can only be accessed by the PF. Example, if this register is set to * 0x2, then a read from 0x50000 is the same as a read from 0x10000 * from VF=2. */ /* SLC: Queue Segment */ #define IO_SLC_QUEUE_SEGMENT 0x00010000 #define IO_SLC_VF_QUEUE_SEGMENT 0x00050000 /* SLC: Queue Offset */ #define IO_SLC_QUEUE_OFFSET 0x00010008 #define IO_SLC_VF_QUEUE_OFFSET 0x00050008 /* SLC: Queue Configuration */ #define IO_SLC_QUEUE_CONFIG 0x00010010 #define IO_SLC_VF_QUEUE_CONFIG 0x00050010 /* SLC: Job Timout/Only accessible for the PF */ #define IO_SLC_APPJOB_TIMEOUT 0x00010018 #define IO_SLC_VF_APPJOB_TIMEOUT 0x00050018 #define TIMEOUT_250MS 0x0000000f #define HEARTBEAT_DISABLE 0x0000ff00 /* SLC: Queue InitSequence Register */ #define IO_SLC_QUEUE_INITSQN 0x00010020 #define IO_SLC_VF_QUEUE_INITSQN 0x00050020 /* SLC: Queue Wrap */ #define IO_SLC_QUEUE_WRAP 0x00010028 #define IO_SLC_VF_QUEUE_WRAP 0x00050028 /* SLC: Queue Status */ #define IO_SLC_QUEUE_STATUS 0x00010100 #define IO_SLC_VF_QUEUE_STATUS 0x00050100 /* SLC: Queue Working Time */ #define IO_SLC_QUEUE_WTIME 0x00010030 #define IO_SLC_VF_QUEUE_WTIME 0x00050030 /* SLC: Queue Error Counts */ #define IO_SLC_QUEUE_ERRCNTS 0x00010038 #define IO_SLC_VF_QUEUE_ERRCNTS 0x00050038 /* SLC: Queue Loast Response Word */ #define IO_SLC_QUEUE_LRW 0x00010040 #define IO_SLC_VF_QUEUE_LRW 0x00050040 /* SLC: Freerunning Timer */ #define IO_SLC_FREE_RUNNING_TIMER 0x00010108 #define IO_SLC_VF_FREE_RUNNING_TIMER 0x00050108 /* SLC: Queue Virtual Access Region */ #define IO_PF_SLC_VIRTUAL_REGION 0x00050000 /* SLC: Queue Virtual Window */ #define IO_PF_SLC_VIRTUAL_WINDOW 0x00060000 /* SLC: DDCB Application Job Pending [n] (n=0:63) */ #define IO_PF_SLC_JOBPEND(n) (0x00061000 + 8*(n)) #define IO_SLC_JOBPEND(n) IO_PF_SLC_JOBPEND(n) /* SLC: Parser Trap RAM [n] (n=0:31) */ #define IO_SLU_SLC_PARSE_TRAP(n) (0x00011000 + 8*(n)) /* SLC: Dispatcher Trap RAM [n] (n=0:31) */ #define IO_SLU_SLC_DISP_TRAP(n) (0x00011200 + 8*(n)) /* Global Fault Isolation Register (GFIR) */ #define IO_SLC_CFGREG_GFIR 0x00020000 #define GFIR_ERR_TRIGGER 0x0000ffff /* SLU: Soft Reset Register */ #define IO_SLC_CFGREG_SOFTRESET 0x00020018 /* SLU: Misc Debug Register */ #define IO_SLC_MISC_DEBUG 0x00020060 #define IO_SLC_MISC_DEBUG_CLR 0x00020068 #define IO_SLC_MISC_DEBUG_SET 0x00020070 /* Temperature Sensor Reading */ #define IO_SLU_TEMPERATURE_SENSOR 0x00030000 #define IO_SLU_TEMPERATURE_CONFIG 0x00030008 /* Voltage Margining Control */ #define IO_SLU_VOLTAGE_CONTROL 0x00030080 #define IO_SLU_VOLTAGE_NOMINAL 0x00000000 #define IO_SLU_VOLTAGE_DOWN5 0x00000006 #define IO_SLU_VOLTAGE_UP5 0x00000007 /* Direct LED Control Register */ #define IO_SLU_LEDCONTROL 0x00030100 /* SLU: Flashbus Direct Access -A5 */ #define IO_SLU_FLASH_DIRECTACCESS 0x00040010 /* SLU: Flashbus Direct Access2 -A5 */ #define IO_SLU_FLASH_DIRECTACCESS2 0x00040020 /* SLU: Flashbus Command Interface -A5 */ #define IO_SLU_FLASH_CMDINTF 0x00040030 /* SLU: BitStream Loaded */ #define IO_SLU_BITSTREAM 0x00040040 /* This Register has a switch which will change the CAs to UR */ #define IO_HSU_ERR_BEHAVIOR 0x01001010 #define IO_SLC2_SQB_TRAP 0x00062000 #define IO_SLC2_QUEUE_MANAGER_TRAP 0x00062008 #define IO_SLC2_FLS_MASTER_TRAP 0x00062010 /* UnitID 1: HSU Registers */ #define IO_HSU_UNITCFG 0x01000000 #define IO_HSU_FIR 0x01000008 #define IO_HSU_FIR_CLR 0x01000010 #define IO_HSU_FEC 0x01000018 #define IO_HSU_ERR_ACT_MASK 0x01000020 #define IO_HSU_ERR_ATTN_MASK 0x01000028 #define IO_HSU_FIRX1_ACT_MASK 0x01000030 #define IO_HSU_FIRX0_ACT_MASK 0x01000038 #define IO_HSU_SEC_LEM_DEBUG_OVR 0x01000040 #define IO_HSU_EXTENDED_ERR_PTR 0x01000048 #define IO_HSU_COMMON_CONFIG 0x01000060 /* UnitID 2: Application Unit (APP) */ #define IO_APP_UNITCFG 0x02000000 #define IO_APP_FIR 0x02000008 #define IO_APP_FIR_CLR 0x02000010 #define IO_APP_FEC 0x02000018 #define IO_APP_ERR_ACT_MASK 0x02000020 #define IO_APP_ERR_ATTN_MASK 0x02000028 #define IO_APP_FIRX1_ACT_MASK 0x02000030 #define IO_APP_FIRX0_ACT_MASK 0x02000038 #define IO_APP_SEC_LEM_DEBUG_OVR 0x02000040 #define IO_APP_EXTENDED_ERR_PTR 0x02000048 #define IO_APP_COMMON_CONFIG 0x02000060 #define IO_APP_DEBUG_REG_01 0x02010000 #define IO_APP_DEBUG_REG_02 0x02010008 #define IO_APP_DEBUG_REG_03 0x02010010 #define IO_APP_DEBUG_REG_04 0x02010018 #define IO_APP_DEBUG_REG_05 0x02010020 #define IO_APP_DEBUG_REG_06 0x02010028 #define IO_APP_DEBUG_REG_07 0x02010030 #define IO_APP_DEBUG_REG_08 0x02010038 #define IO_APP_DEBUG_REG_09 0x02010040 #define IO_APP_DEBUG_REG_10 0x02010048 #define IO_APP_DEBUG_REG_11 0x02010050 #define IO_APP_DEBUG_REG_12 0x02010058 #define IO_APP_DEBUG_REG_13 0x02010060 #define IO_APP_DEBUG_REG_14 0x02010068 #define IO_APP_DEBUG_REG_15 0x02010070 #define IO_APP_DEBUG_REG_16 0x02010078 #define IO_APP_DEBUG_REG_17 0x02010080 #define IO_APP_DEBUG_REG_18 0x02010088 /* Read/write from/to registers */ struct genwqe_reg_io { __u64 num; /* register offset/address */ __u64 val64; }; /* * All registers of our card will return values not equal this values. * If we see IO_ILLEGAL_VALUE on any of our MMIO register reads, the * card can be considered as unusable. It will need recovery. */ #define IO_ILLEGAL_VALUE 0xffffffffffffffffull /* * Generic DDCB execution interface. * * This interface is a first prototype resulting from discussions we * had with other teams which wanted to use the Genwqe card. It allows * to issue a DDCB request in a generic way. The request will block * until it finishes or time out with error. * * Some DDCBs require DMA addresses to be specified in the ASIV * block. The interface provies the capability to let the kernel * driver know where those addresses are by specifying the ATS field, * such that it can replace the user-space addresses with appropriate * DMA addresses or DMA addresses of a scatter gather list which is * dynamically created. * * Our hardware will refuse DDCB execution if the ATS field is not as * expected. That means the DDCB execution engine in the chip knows * where it expects DMA addresses within the ASIV part of the DDCB and * will check that against the ATS field definition. Any invalid or * unknown ATS content will lead to DDCB refusal. */ /* Genwqe chip Units */ #define DDCB_ACFUNC_SLU 0x00 /* chip service layer unit */ #define DDCB_ACFUNC_APP 0x01 /* chip application */ /* DDCB return codes (RETC) */ #define DDCB_RETC_IDLE 0x0000 /* Unexecuted/DDCB created */ #define DDCB_RETC_PENDING 0x0101 /* Pending Execution */ #define DDCB_RETC_COMPLETE 0x0102 /* Cmd complete. No error */ #define DDCB_RETC_FAULT 0x0104 /* App Err, recoverable */ #define DDCB_RETC_ERROR 0x0108 /* App Err, non-recoverable */ #define DDCB_RETC_FORCED_ERROR 0x01ff /* overwritten by driver */ #define DDCB_RETC_UNEXEC 0x0110 /* Unexe/Removed from queue */ #define DDCB_RETC_TERM 0x0120 /* Terminated */ #define DDCB_RETC_RES0 0x0140 /* Reserved */ #define DDCB_RETC_RES1 0x0180 /* Reserved */ /* DDCB Command Options (CMDOPT) */ #define DDCB_OPT_ECHO_FORCE_NO 0x0000 /* ECHO DDCB */ #define DDCB_OPT_ECHO_FORCE_102 0x0001 /* force return code */ #define DDCB_OPT_ECHO_FORCE_104 0x0002 #define DDCB_OPT_ECHO_FORCE_108 0x0003 #define DDCB_OPT_ECHO_FORCE_110 0x0004 /* only on PF ! */ #define DDCB_OPT_ECHO_FORCE_120 0x0005 #define DDCB_OPT_ECHO_FORCE_140 0x0006 #define DDCB_OPT_ECHO_FORCE_180 0x0007 #define DDCB_OPT_ECHO_COPY_NONE (0 << 5) #define DDCB_OPT_ECHO_COPY_ALL (1 << 5) /* Definitions of Service Layer Commands */ #define SLCMD_ECHO_SYNC 0x00 /* PF/VF */ #define SLCMD_MOVE_FLASH 0x06 /* PF only */ #define SLCMD_MOVE_FLASH_FLAGS_MODE 0x03 /* bit 0 and 1 used for mode */ #define SLCMD_MOVE_FLASH_FLAGS_DLOAD 0 /* mode: download */ #define SLCMD_MOVE_FLASH_FLAGS_EMUL 1 /* mode: emulation */ #define SLCMD_MOVE_FLASH_FLAGS_UPLOAD 2 /* mode: upload */ #define SLCMD_MOVE_FLASH_FLAGS_VERIFY 3 /* mode: verify */ #define SLCMD_MOVE_FLASH_FLAG_NOTAP (1 << 2)/* just dump DDCB and exit */ #define SLCMD_MOVE_FLASH_FLAG_POLL (1 << 3)/* wait for RETC >= 0102 */ #define SLCMD_MOVE_FLASH_FLAG_PARTITION (1 << 4) #define SLCMD_MOVE_FLASH_FLAG_ERASE (1 << 5) enum genwqe_card_state { GENWQE_CARD_UNUSED = 0, GENWQE_CARD_USED = 1, GENWQE_CARD_FATAL_ERROR = 2, GENWQE_CARD_RELOAD_BITSTREAM = 3, GENWQE_CARD_STATE_MAX, }; /* common struct for chip image exchange */ struct genwqe_bitstream { __u64 data_addr; /* pointer to image data */ __u32 size; /* size of image file */ __u32 crc; /* crc of this image */ __u64 target_addr; /* starting address in Flash */ __u32 partition; /* '0', '1', or 'v' */ __u32 uid; /* 1=host/x=dram */ __u64 slu_id; /* informational/sim: SluID */ __u64 app_id; /* informational/sim: AppID */ __u16 retc; /* returned from processing */ __u16 attn; /* attention code from processing */ __u32 progress; /* progress code from processing */ }; /* Issuing a specific DDCB command */ #define DDCB_LENGTH 256 /* for debug data */ #define DDCB_ASIV_LENGTH 104 /* len of the DDCB ASIV array */ #define DDCB_ASIV_LENGTH_ATS 96 /* ASIV in ATS architecture */ #define DDCB_ASV_LENGTH 64 /* len of the DDCB ASV array */ #define DDCB_FIXUPS 12 /* maximum number of fixups */ struct genwqe_debug_data { char driver_version[64]; __u64 slu_unitcfg; __u64 app_unitcfg; __u8 ddcb_before[DDCB_LENGTH]; __u8 ddcb_prev[DDCB_LENGTH]; __u8 ddcb_finished[DDCB_LENGTH]; }; /* * Address Translation Specification (ATS) definitions * * Each 4 bit within the ATS 64-bit word specify the required address * translation at the defined offset. * * 63 LSB * 6666.5555.5555.5544.4444.4443.3333.3333 ... 11 * 3210.9876.5432.1098.7654.3210.9876.5432 ... 1098.7654.3210 * * offset: 0x00 0x08 0x10 0x18 0x20 0x28 0x30 0x38 ... 0x68 0x70 0x78 * res res res res ASIV ... * The first 4 entries in the ATS word are reserved. The following nibbles * each describe at an 8 byte offset the format of the required data. */ #define ATS_TYPE_DATA 0x0ull /* data */ #define ATS_TYPE_FLAT_RD 0x4ull /* flat buffer read only */ #define ATS_TYPE_FLAT_RDWR 0x5ull /* flat buffer read/write */ #define ATS_TYPE_SGL_RD 0x6ull /* sgl read only */ #define ATS_TYPE_SGL_RDWR 0x7ull /* sgl read/write */ #define ATS_SET_FLAGS(_struct, _field, _flags) \ (((_flags) & 0xf) << (44 - (4 * (offsetof(_struct, _field) / 8)))) #define ATS_GET_FLAGS(_ats, _byte_offs) \ (((_ats) >> (44 - (4 * ((_byte_offs) / 8)))) & 0xf) /** * struct genwqe_ddcb_cmd - User parameter for generic DDCB commands * * On the way into the kernel the driver will read the whole data * structure. On the way out the driver will not copy the ASIV data * back to user-space. */ struct genwqe_ddcb_cmd { /* START of data copied to/from driver */ __u64 next_addr; /* chaining genwqe_ddcb_cmd */ __u64 flags; /* reserved */ __u8 acfunc; /* accelerators functional unit */ __u8 cmd; /* command to execute */ __u8 asiv_length; /* used parameter length */ __u8 asv_length; /* length of valid return values */ __u16 cmdopts; /* command options */ __u16 retc; /* return code from processing */ __u16 attn; /* attention code from processing */ __u16 vcrc; /* variant crc16 */ __u32 progress; /* progress code from processing */ __u64 deque_ts; /* dequeue time stamp */ __u64 cmplt_ts; /* completion time stamp */ __u64 disp_ts; /* SW processing start */ /* move to end and avoid copy-back */ __u64 ddata_addr; /* collect debug data */ /* command specific values */ __u8 asv[DDCB_ASV_LENGTH]; /* END of data copied from driver */ union { struct { __u64 ats; __u8 asiv[DDCB_ASIV_LENGTH_ATS]; }; /* used for flash update to keep it backward compatible */ __u8 __asiv[DDCB_ASIV_LENGTH]; }; /* END of data copied to driver */ }; #define GENWQE_IOC_CODE 0xa5 /* Access functions */ #define GENWQE_READ_REG64 _IOR(GENWQE_IOC_CODE, 30, struct genwqe_reg_io) #define GENWQE_WRITE_REG64 _IOW(GENWQE_IOC_CODE, 31, struct genwqe_reg_io) #define GENWQE_READ_REG32 _IOR(GENWQE_IOC_CODE, 32, struct genwqe_reg_io) #define GENWQE_WRITE_REG32 _IOW(GENWQE_IOC_CODE, 33, struct genwqe_reg_io) #define GENWQE_READ_REG16 _IOR(GENWQE_IOC_CODE, 34, struct genwqe_reg_io) #define GENWQE_WRITE_REG16 _IOW(GENWQE_IOC_CODE, 35, struct genwqe_reg_io) #define GENWQE_GET_CARD_STATE _IOR(GENWQE_IOC_CODE, 36, enum genwqe_card_state) /** * struct genwqe_mem - Memory pinning/unpinning information * @addr: virtual user space address * @size: size of the area pin/dma-map/unmap * direction: 0: read/1: read and write * * Avoid pinning and unpinning of memory pages dynamically. Instead * the idea is to pin the whole buffer space required for DDCB * opertionas in advance. The driver will reuse this pinning and the * memory associated with it to setup the sglists for the DDCB * requests without the need to allocate and free memory or map and * unmap to get the DMA addresses. * * The inverse operation needs to be called after the pinning is not * needed anymore. The pinnings else the pinnings will get removed * after the device is closed. Note that pinnings will required * memory. */ struct genwqe_mem { __u64 addr; __u64 size; __u64 direction; __u64 flags; }; #define GENWQE_PIN_MEM _IOWR(GENWQE_IOC_CODE, 40, struct genwqe_mem) #define GENWQE_UNPIN_MEM _IOWR(GENWQE_IOC_CODE, 41, struct genwqe_mem) /* * Generic synchronous DDCB execution interface. * Synchronously execute a DDCB. * * Return: 0 on success or negative error code. * -EINVAL: Invalid parameters (ASIV_LEN, ASV_LEN, illegal fixups * no mappings found/could not create mappings * -EFAULT: illegal addresses in fixups, purging failed * -EBADMSG: enqueing failed, retc != DDCB_RETC_COMPLETE */ #define GENWQE_EXECUTE_DDCB \ _IOWR(GENWQE_IOC_CODE, 50, struct genwqe_ddcb_cmd) #define GENWQE_EXECUTE_RAW_DDCB \ _IOWR(GENWQE_IOC_CODE, 51, struct genwqe_ddcb_cmd) /* Service Layer functions (PF only) */ #define GENWQE_SLU_UPDATE _IOWR(GENWQE_IOC_CODE, 80, struct genwqe_bitstream) #define GENWQE_SLU_READ _IOWR(GENWQE_IOC_CODE, 81, struct genwqe_bitstream) #endif /* __GENWQE_CARD_H__ */ linux/if_xdp.h000064400000005703151027430560007335 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * if_xdp: XDP socket user-space interface * Copyright(c) 2018 Intel Corporation. * * Author(s): Björn Töpel * Magnus Karlsson */ #ifndef _LINUX_IF_XDP_H #define _LINUX_IF_XDP_H #include /* Options for the sxdp_flags field */ #define XDP_SHARED_UMEM (1 << 0) #define XDP_COPY (1 << 1) /* Force copy-mode */ #define XDP_ZEROCOPY (1 << 2) /* Force zero-copy mode */ /* If this option is set, the driver might go sleep and in that case * the XDP_RING_NEED_WAKEUP flag in the fill and/or Tx rings will be * set. If it is set, the application need to explicitly wake up the * driver with a poll() (Rx and Tx) or sendto() (Tx only). If you are * running the driver and the application on the same core, you should * use this option so that the kernel will yield to the user space * application. */ #define XDP_USE_NEED_WAKEUP (1 << 3) /* Flags for xsk_umem_config flags */ #define XDP_UMEM_UNALIGNED_CHUNK_FLAG (1 << 0) struct sockaddr_xdp { __u16 sxdp_family; __u16 sxdp_flags; __u32 sxdp_ifindex; __u32 sxdp_queue_id; __u32 sxdp_shared_umem_fd; }; /* XDP_RING flags */ #define XDP_RING_NEED_WAKEUP (1 << 0) struct xdp_ring_offset { __u64 producer; __u64 consumer; __u64 desc; __u64 flags; }; struct xdp_mmap_offsets { struct xdp_ring_offset rx; struct xdp_ring_offset tx; struct xdp_ring_offset fr; /* Fill */ struct xdp_ring_offset cr; /* Completion */ }; /* XDP socket options */ #define XDP_MMAP_OFFSETS 1 #define XDP_RX_RING 2 #define XDP_TX_RING 3 #define XDP_UMEM_REG 4 #define XDP_UMEM_FILL_RING 5 #define XDP_UMEM_COMPLETION_RING 6 #define XDP_STATISTICS 7 #define XDP_OPTIONS 8 struct xdp_umem_reg { __u64 addr; /* Start of packet data area */ __u64 len; /* Length of packet data area */ __u32 chunk_size; __u32 headroom; __u32 flags; }; struct xdp_statistics { __u64 rx_dropped; /* Dropped for other reasons */ __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */ __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */ __u64 rx_ring_full; /* Dropped due to rx ring being full */ __u64 rx_fill_ring_empty_descs; /* Failed to retrieve item from fill ring */ __u64 tx_ring_empty_descs; /* Failed to retrieve item from tx ring */ }; struct xdp_options { __u32 flags; }; /* Flags for the flags field of struct xdp_options */ #define XDP_OPTIONS_ZEROCOPY (1 << 0) /* Pgoff for mmaping the rings */ #define XDP_PGOFF_RX_RING 0 #define XDP_PGOFF_TX_RING 0x80000000 #define XDP_UMEM_PGOFF_FILL_RING 0x100000000ULL #define XDP_UMEM_PGOFF_COMPLETION_RING 0x180000000ULL /* Masks for unaligned chunks mode */ #define XSK_UNALIGNED_BUF_OFFSET_SHIFT 48 #define XSK_UNALIGNED_BUF_ADDR_MASK \ ((1ULL << XSK_UNALIGNED_BUF_OFFSET_SHIFT) - 1) /* Rx/Tx descriptor */ struct xdp_desc { __u64 addr; __u32 len; __u32 options; }; /* UMEM descriptor is __u64 */ #endif /* _LINUX_IF_XDP_H */ linux/netfilter_arp/arp_tables.h000064400000013557151027430560013044 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Format of an ARP firewall descriptor * * src, tgt, src_mask, tgt_mask, arpop, arpop_mask are always stored in * network byte order. * flags are stored in host byte order (of course). */ #ifndef _ARPTABLES_H #define _ARPTABLES_H #include #include #include #include #define ARPT_FUNCTION_MAXNAMELEN XT_FUNCTION_MAXNAMELEN #define ARPT_TABLE_MAXNAMELEN XT_TABLE_MAXNAMELEN #define arpt_entry_target xt_entry_target #define arpt_standard_target xt_standard_target #define arpt_error_target xt_error_target #define ARPT_CONTINUE XT_CONTINUE #define ARPT_RETURN XT_RETURN #define arpt_counters_info xt_counters_info #define arpt_counters xt_counters #define ARPT_STANDARD_TARGET XT_STANDARD_TARGET #define ARPT_ERROR_TARGET XT_ERROR_TARGET #define ARPT_ENTRY_ITERATE(entries, size, fn, args...) \ XT_ENTRY_ITERATE(struct arpt_entry, entries, size, fn, ## args) #define ARPT_DEV_ADDR_LEN_MAX 16 struct arpt_devaddr_info { char addr[ARPT_DEV_ADDR_LEN_MAX]; char mask[ARPT_DEV_ADDR_LEN_MAX]; }; /* Yes, Virginia, you have to zero the padding. */ struct arpt_arp { /* Source and target IP addr */ struct in_addr src, tgt; /* Mask for src and target IP addr */ struct in_addr smsk, tmsk; /* Device hw address length, src+target device addresses */ __u8 arhln, arhln_mask; struct arpt_devaddr_info src_devaddr; struct arpt_devaddr_info tgt_devaddr; /* ARP operation code. */ __be16 arpop, arpop_mask; /* ARP hardware address and protocol address format. */ __be16 arhrd, arhrd_mask; __be16 arpro, arpro_mask; /* The protocol address length is only accepted if it is 4 * so there is no use in offering a way to do filtering on it. */ char iniface[IFNAMSIZ], outiface[IFNAMSIZ]; unsigned char iniface_mask[IFNAMSIZ], outiface_mask[IFNAMSIZ]; /* Flags word */ __u8 flags; /* Inverse flags */ __u16 invflags; }; /* Values for "flag" field in struct arpt_ip (general arp structure). * No flags defined yet. */ #define ARPT_F_MASK 0x00 /* All possible flag bits mask. */ /* Values for "inv" field in struct arpt_arp. */ #define ARPT_INV_VIA_IN 0x0001 /* Invert the sense of IN IFACE. */ #define ARPT_INV_VIA_OUT 0x0002 /* Invert the sense of OUT IFACE */ #define ARPT_INV_SRCIP 0x0004 /* Invert the sense of SRC IP. */ #define ARPT_INV_TGTIP 0x0008 /* Invert the sense of TGT IP. */ #define ARPT_INV_SRCDEVADDR 0x0010 /* Invert the sense of SRC DEV ADDR. */ #define ARPT_INV_TGTDEVADDR 0x0020 /* Invert the sense of TGT DEV ADDR. */ #define ARPT_INV_ARPOP 0x0040 /* Invert the sense of ARP OP. */ #define ARPT_INV_ARPHRD 0x0080 /* Invert the sense of ARP HRD. */ #define ARPT_INV_ARPPRO 0x0100 /* Invert the sense of ARP PRO. */ #define ARPT_INV_ARPHLN 0x0200 /* Invert the sense of ARP HLN. */ #define ARPT_INV_MASK 0x03FF /* All possible flag bits mask. */ /* This structure defines each of the firewall rules. Consists of 3 parts which are 1) general ARP header stuff 2) match specific stuff 3) the target to perform if the rule matches */ struct arpt_entry { struct arpt_arp arp; /* Size of arpt_entry + matches */ __u16 target_offset; /* Size of arpt_entry + matches + target */ __u16 next_offset; /* Back pointer */ unsigned int comefrom; /* Packet and byte counters. */ struct xt_counters counters; /* The matches (if any), then the target. */ unsigned char elems[0]; }; /* * New IP firewall options for [gs]etsockopt at the RAW IP level. * Unlike BSD Linux inherits IP options so you don't have to use a raw * socket for this. Instead we check rights in the calls. * * ATTENTION: check linux/in.h before adding new number here. */ #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_SET_ADD_COUNTERS (ARPT_BASE_CTL + 1) #define ARPT_SO_SET_MAX ARPT_SO_SET_ADD_COUNTERS #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) /* #define ARPT_SO_GET_REVISION_MATCH (APRT_BASE_CTL + 2) */ #define ARPT_SO_GET_REVISION_TARGET (ARPT_BASE_CTL + 3) #define ARPT_SO_GET_MAX (ARPT_SO_GET_REVISION_TARGET) /* The argument to ARPT_SO_GET_INFO */ struct arpt_getinfo { /* Which table: caller fills this in. */ char name[XT_TABLE_MAXNAMELEN]; /* Kernel fills these in. */ /* Which hook entry points are valid: bitmask */ unsigned int valid_hooks; /* Hook entry points: one per netfilter hook. */ unsigned int hook_entry[NF_ARP_NUMHOOKS]; /* Underflow points. */ unsigned int underflow[NF_ARP_NUMHOOKS]; /* Number of entries */ unsigned int num_entries; /* Size of entries. */ unsigned int size; }; /* The argument to ARPT_SO_SET_REPLACE. */ struct arpt_replace { /* Which table. */ char name[XT_TABLE_MAXNAMELEN]; /* Which hook entry points are valid: bitmask. You can't change this. */ unsigned int valid_hooks; /* Number of entries */ unsigned int num_entries; /* Total size of new entries */ unsigned int size; /* Hook entry points. */ unsigned int hook_entry[NF_ARP_NUMHOOKS]; /* Underflow points. */ unsigned int underflow[NF_ARP_NUMHOOKS]; /* Information about old entries: */ /* Number of counters (must be equal to current number of entries). */ unsigned int num_counters; /* The old entries' counters. */ struct xt_counters *counters; /* The entries (hang off end: not really an array). */ struct arpt_entry entries[0]; }; /* The argument to ARPT_SO_GET_ENTRIES. */ struct arpt_get_entries { /* Which table: user fills this in. */ char name[XT_TABLE_MAXNAMELEN]; /* User fills this in: total entry size. */ unsigned int size; /* The entries. */ struct arpt_entry entrytable[0]; }; /* Helper functions */ static __inline__ struct xt_entry_target *arpt_get_target(struct arpt_entry *e) { return (void *)e + e->target_offset; } /* * Main firewall chains definitions and global var's definitions. */ #endif /* _ARPTABLES_H */ linux/netfilter_arp/arpt_mangle.h000064400000001136151027430560013207 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ARPT_MANGLE_H #define _ARPT_MANGLE_H #include #define ARPT_MANGLE_ADDR_LEN_MAX sizeof(struct in_addr) struct arpt_mangle { char src_devaddr[ARPT_DEV_ADDR_LEN_MAX]; char tgt_devaddr[ARPT_DEV_ADDR_LEN_MAX]; union { struct in_addr src_ip; } u_s; union { struct in_addr tgt_ip; } u_t; __u8 flags; int target; }; #define ARPT_MANGLE_SDEV 0x01 #define ARPT_MANGLE_TDEV 0x02 #define ARPT_MANGLE_SIP 0x04 #define ARPT_MANGLE_TIP 0x08 #define ARPT_MANGLE_MASK 0x0f #endif /* _ARPT_MANGLE_H */ linux/qnx4_fs.h000064400000004430151027430560007442 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Name : qnx4_fs.h * Author : Richard Frowijn * Function : qnx4 global filesystem definitions * History : 23-03-1998 created */ #ifndef _LINUX_QNX4_FS_H #define _LINUX_QNX4_FS_H #include #include #include #define QNX4_ROOT_INO 1 #define QNX4_MAX_XTNTS_PER_XBLK 60 /* for di_status */ #define QNX4_FILE_USED 0x01 #define QNX4_FILE_MODIFIED 0x02 #define QNX4_FILE_BUSY 0x04 #define QNX4_FILE_LINK 0x08 #define QNX4_FILE_INODE 0x10 #define QNX4_FILE_FSYSCLEAN 0x20 #define QNX4_I_MAP_SLOTS 8 #define QNX4_Z_MAP_SLOTS 64 #define QNX4_VALID_FS 0x0001 /* Clean fs. */ #define QNX4_ERROR_FS 0x0002 /* fs has errors. */ #define QNX4_BLOCK_SIZE 0x200 /* blocksize of 512 bytes */ #define QNX4_BLOCK_SIZE_BITS 9 /* blocksize shift */ #define QNX4_DIR_ENTRY_SIZE 0x040 /* dir entry size of 64 bytes */ #define QNX4_DIR_ENTRY_SIZE_BITS 6 /* dir entry size shift */ #define QNX4_XBLK_ENTRY_SIZE 0x200 /* xblk entry size */ #define QNX4_INODES_PER_BLOCK 0x08 /* 512 / 64 */ /* for filenames */ #define QNX4_SHORT_NAME_MAX 16 #define QNX4_NAME_MAX 48 /* * This is the original qnx4 inode layout on disk. */ struct qnx4_inode_entry { char di_fname[QNX4_SHORT_NAME_MAX]; qnx4_off_t di_size; qnx4_xtnt_t di_first_xtnt; __le32 di_xblk; __le32 di_ftime; __le32 di_mtime; __le32 di_atime; __le32 di_ctime; qnx4_nxtnt_t di_num_xtnts; qnx4_mode_t di_mode; qnx4_muid_t di_uid; qnx4_mgid_t di_gid; qnx4_nlink_t di_nlink; __u8 di_zero[4]; qnx4_ftype_t di_type; __u8 di_status; }; struct qnx4_link_info { char dl_fname[QNX4_NAME_MAX]; __le32 dl_inode_blk; __u8 dl_inode_ndx; __u8 dl_spare[10]; __u8 dl_status; }; struct qnx4_xblk { __le32 xblk_next_xblk; __le32 xblk_prev_xblk; __u8 xblk_num_xtnts; __u8 xblk_spare[3]; __le32 xblk_num_blocks; qnx4_xtnt_t xblk_xtnts[QNX4_MAX_XTNTS_PER_XBLK]; char xblk_signature[8]; qnx4_xtnt_t xblk_first_xtnt; }; struct qnx4_super_block { struct qnx4_inode_entry RootDir; struct qnx4_inode_entry Inode; struct qnx4_inode_entry Boot; struct qnx4_inode_entry AltBoot; }; #endif linux/adb.h000064400000002164151027430560006610 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Definitions for ADB (Apple Desktop Bus) support. */ #ifndef __ADB_H #define __ADB_H /* ADB commands */ #define ADB_BUSRESET 0 #define ADB_FLUSH(id) (0x01 | ((id) << 4)) #define ADB_WRITEREG(id, reg) (0x08 | (reg) | ((id) << 4)) #define ADB_READREG(id, reg) (0x0C | (reg) | ((id) << 4)) /* ADB default device IDs (upper 4 bits of ADB command byte) */ #define ADB_DONGLE 1 /* "software execution control" devices */ #define ADB_KEYBOARD 2 #define ADB_MOUSE 3 #define ADB_TABLET 4 #define ADB_MODEM 5 #define ADB_MISC 7 /* maybe a monitor */ #define ADB_RET_OK 0 #define ADB_RET_TIMEOUT 3 /* The kind of ADB request. The controller may emulate some or all of those CUDA/PMU packet kinds */ #define ADB_PACKET 0 #define CUDA_PACKET 1 #define ERROR_PACKET 2 #define TIMER_PACKET 3 #define POWER_PACKET 4 #define MACIIC_PACKET 5 #define PMU_PACKET 6 #define ADB_QUERY 7 /* ADB queries */ /* ADB_QUERY_GETDEVINFO * Query ADB slot for device presence * data[2] = id, rep[0] = orig addr, rep[1] = handler_id */ #define ADB_QUERY_GETDEVINFO 1 #endif /* __ADB_H */ linux/termios.h000064400000000772151027430560007547 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TERMIOS_H #define _LINUX_TERMIOS_H #include #include #define NFF 5 struct termiox { __u16 x_hflag; __u16 x_cflag; __u16 x_rflag[NFF]; __u16 x_sflag; }; #define RTSXOFF 0x0001 /* RTS flow control on input */ #define CTSXON 0x0002 /* CTS flow control on output */ #define DTRXOFF 0x0004 /* DTR flow control on input */ #define DSRXON 0x0008 /* DCD flow control on output */ #endif linux/idxd.h000064400000020341151027430560007007 0ustar00/* SPDX-License-Identifier: LGPL-2.1 WITH Linux-syscall-note */ /* Copyright(c) 2019 Intel Corporation. All rights rsvd. */ #ifndef _USR_IDXD_H_ #define _USR_IDXD_H_ #include /* Driver command error status */ enum idxd_scmd_stat { IDXD_SCMD_DEV_ENABLED = 0x80000010, IDXD_SCMD_DEV_NOT_ENABLED = 0x80000020, IDXD_SCMD_WQ_ENABLED = 0x80000021, IDXD_SCMD_DEV_DMA_ERR = 0x80020000, IDXD_SCMD_WQ_NO_GRP = 0x80030000, IDXD_SCMD_WQ_NO_NAME = 0x80040000, IDXD_SCMD_WQ_NO_SVM = 0x80050000, IDXD_SCMD_WQ_NO_THRESH = 0x80060000, IDXD_SCMD_WQ_PORTAL_ERR = 0x80070000, IDXD_SCMD_WQ_RES_ALLOC_ERR = 0x80080000, IDXD_SCMD_PERCPU_ERR = 0x80090000, IDXD_SCMD_DMA_CHAN_ERR = 0x800a0000, IDXD_SCMD_CDEV_ERR = 0x800b0000, IDXD_SCMD_WQ_NO_SWQ_SUPPORT = 0x800c0000, IDXD_SCMD_WQ_NONE_CONFIGURED = 0x800d0000, IDXD_SCMD_WQ_NO_SIZE = 0x800e0000, IDXD_SCMD_WQ_NO_PRIV = 0x800f0000, IDXD_SCMD_WQ_IRQ_ERR = 0x80100000, IDXD_SCMD_WQ_USER_NO_IOMMU = 0x80110000, }; #define IDXD_SCMD_SOFTERR_MASK 0x80000000 #define IDXD_SCMD_SOFTERR_SHIFT 16 /* Descriptor flags */ #define IDXD_OP_FLAG_FENCE 0x0001 #define IDXD_OP_FLAG_BOF 0x0002 #define IDXD_OP_FLAG_CRAV 0x0004 #define IDXD_OP_FLAG_RCR 0x0008 #define IDXD_OP_FLAG_RCI 0x0010 #define IDXD_OP_FLAG_CRSTS 0x0020 #define IDXD_OP_FLAG_CR 0x0080 #define IDXD_OP_FLAG_CC 0x0100 #define IDXD_OP_FLAG_ADDR1_TCS 0x0200 #define IDXD_OP_FLAG_ADDR2_TCS 0x0400 #define IDXD_OP_FLAG_ADDR3_TCS 0x0800 #define IDXD_OP_FLAG_CR_TCS 0x1000 #define IDXD_OP_FLAG_STORD 0x2000 #define IDXD_OP_FLAG_DRDBK 0x4000 #define IDXD_OP_FLAG_DSTS 0x8000 /* IAX */ #define IDXD_OP_FLAG_RD_SRC2_AECS 0x010000 #define IDXD_OP_FLAG_RD_SRC2_2ND 0x020000 #define IDXD_OP_FLAG_WR_SRC2_AECS_COMP 0x040000 #define IDXD_OP_FLAG_WR_SRC2_AECS_OVFL 0x080000 #define IDXD_OP_FLAG_SRC2_STS 0x100000 #define IDXD_OP_FLAG_CRC_RFC3720 0x200000 /* Opcode */ enum dsa_opcode { DSA_OPCODE_NOOP = 0, DSA_OPCODE_BATCH, DSA_OPCODE_DRAIN, DSA_OPCODE_MEMMOVE, DSA_OPCODE_MEMFILL, DSA_OPCODE_COMPARE, DSA_OPCODE_COMPVAL, DSA_OPCODE_CR_DELTA, DSA_OPCODE_AP_DELTA, DSA_OPCODE_DUALCAST, DSA_OPCODE_CRCGEN = 0x10, DSA_OPCODE_COPY_CRC, DSA_OPCODE_DIF_CHECK, DSA_OPCODE_DIF_INS, DSA_OPCODE_DIF_STRP, DSA_OPCODE_DIF_UPDT, DSA_OPCODE_CFLUSH = 0x20, }; enum iax_opcode { IAX_OPCODE_NOOP = 0, IAX_OPCODE_DRAIN = 2, IAX_OPCODE_MEMMOVE, IAX_OPCODE_DECOMPRESS = 0x42, IAX_OPCODE_COMPRESS, IAX_OPCODE_CRC64, IAX_OPCODE_ZERO_DECOMP_32 = 0x48, IAX_OPCODE_ZERO_DECOMP_16, IAX_OPCODE_ZERO_COMP_32 = 0x4c, IAX_OPCODE_ZERO_COMP_16, IAX_OPCODE_SCAN = 0x50, IAX_OPCODE_SET_MEMBER, IAX_OPCODE_EXTRACT, IAX_OPCODE_SELECT, IAX_OPCODE_RLE_BURST, IAX_OPCODE_FIND_UNIQUE, IAX_OPCODE_EXPAND, }; /* Completion record status */ enum dsa_completion_status { DSA_COMP_NONE = 0, DSA_COMP_SUCCESS, DSA_COMP_SUCCESS_PRED, DSA_COMP_PAGE_FAULT_NOBOF, DSA_COMP_PAGE_FAULT_IR, DSA_COMP_BATCH_FAIL, DSA_COMP_BATCH_PAGE_FAULT, DSA_COMP_DR_OFFSET_NOINC, DSA_COMP_DR_OFFSET_ERANGE, DSA_COMP_DIF_ERR, DSA_COMP_BAD_OPCODE = 0x10, DSA_COMP_INVALID_FLAGS, DSA_COMP_NOZERO_RESERVE, DSA_COMP_XFER_ERANGE, DSA_COMP_DESC_CNT_ERANGE, DSA_COMP_DR_ERANGE, DSA_COMP_OVERLAP_BUFFERS, DSA_COMP_DCAST_ERR, DSA_COMP_DESCLIST_ALIGN, DSA_COMP_INT_HANDLE_INVAL, DSA_COMP_CRA_XLAT, DSA_COMP_CRA_ALIGN, DSA_COMP_ADDR_ALIGN, DSA_COMP_PRIV_BAD, DSA_COMP_TRAFFIC_CLASS_CONF, DSA_COMP_PFAULT_RDBA, DSA_COMP_HW_ERR1, DSA_COMP_HW_ERR_DRB, DSA_COMP_TRANSLATION_FAIL, }; enum iax_completion_status { IAX_COMP_NONE = 0, IAX_COMP_SUCCESS, IAX_COMP_PAGE_FAULT_IR = 0x04, IAX_COMP_ANALYTICS_ERROR = 0x0a, IAX_COMP_OUTBUF_OVERFLOW, IAX_COMP_BAD_OPCODE = 0x10, IAX_COMP_INVALID_FLAGS, IAX_COMP_NOZERO_RESERVE, IAX_COMP_INVALID_SIZE, IAX_COMP_OVERLAP_BUFFERS = 0x16, IAX_COMP_INT_HANDLE_INVAL = 0x19, IAX_COMP_CRA_XLAT, IAX_COMP_CRA_ALIGN, IAX_COMP_ADDR_ALIGN, IAX_COMP_PRIV_BAD, IAX_COMP_TRAFFIC_CLASS_CONF, IAX_COMP_PFAULT_RDBA, IAX_COMP_HW_ERR1, IAX_COMP_HW_ERR_DRB, IAX_COMP_TRANSLATION_FAIL, IAX_COMP_PRS_TIMEOUT, IAX_COMP_WATCHDOG, IAX_COMP_INVALID_COMP_FLAG = 0x30, IAX_COMP_INVALID_FILTER_FLAG, IAX_COMP_INVALID_INPUT_SIZE, IAX_COMP_INVALID_NUM_ELEMS, IAX_COMP_INVALID_SRC1_WIDTH, IAX_COMP_INVALID_INVERT_OUT, }; #define DSA_COMP_STATUS_MASK 0x7f #define DSA_COMP_STATUS_WRITE 0x80 struct dsa_hw_desc { uint32_t pasid:20; uint32_t rsvd:11; uint32_t priv:1; uint32_t flags:24; uint32_t opcode:8; uint64_t completion_addr; union { uint64_t src_addr; uint64_t rdback_addr; uint64_t pattern; uint64_t desc_list_addr; }; union { uint64_t dst_addr; uint64_t rdback_addr2; uint64_t src2_addr; uint64_t comp_pattern; }; union { uint32_t xfer_size; uint32_t desc_count; }; uint16_t int_handle; uint16_t rsvd1; union { uint8_t expected_res; /* create delta record */ struct { uint64_t delta_addr; uint32_t max_delta_size; uint32_t delt_rsvd; uint8_t expected_res_mask; }; uint32_t delta_rec_size; uint64_t dest2; /* CRC */ struct { uint32_t crc_seed; uint32_t crc_rsvd; uint64_t seed_addr; }; /* DIF check or strip */ struct { uint8_t src_dif_flags; uint8_t dif_chk_res; uint8_t dif_chk_flags; uint8_t dif_chk_res2[5]; uint32_t chk_ref_tag_seed; uint16_t chk_app_tag_mask; uint16_t chk_app_tag_seed; }; /* DIF insert */ struct { uint8_t dif_ins_res; uint8_t dest_dif_flag; uint8_t dif_ins_flags; uint8_t dif_ins_res2[13]; uint32_t ins_ref_tag_seed; uint16_t ins_app_tag_mask; uint16_t ins_app_tag_seed; }; /* DIF update */ struct { uint8_t src_upd_flags; uint8_t upd_dest_flags; uint8_t dif_upd_flags; uint8_t dif_upd_res[5]; uint32_t src_ref_tag_seed; uint16_t src_app_tag_mask; uint16_t src_app_tag_seed; uint32_t dest_ref_tag_seed; uint16_t dest_app_tag_mask; uint16_t dest_app_tag_seed; }; uint8_t op_specific[24]; }; } __attribute__((packed)); struct iax_hw_desc { uint32_t pasid:20; uint32_t rsvd:11; uint32_t priv:1; uint32_t flags:24; uint32_t opcode:8; uint64_t completion_addr; uint64_t src1_addr; uint64_t dst_addr; uint32_t src1_size; uint16_t int_handle; union { uint16_t compr_flags; uint16_t decompr_flags; }; uint64_t src2_addr; uint32_t max_dst_size; uint32_t src2_size; uint32_t filter_flags; uint32_t num_inputs; } __attribute__((packed)); struct dsa_raw_desc { uint64_t field[8]; } __attribute__((packed)); /* * The status field will be modified by hardware, therefore it should be * __volatile__ and prevent the compiler from optimize the read. */ struct dsa_completion_record { __volatile__ uint8_t status; union { uint8_t result; uint8_t dif_status; }; uint16_t rsvd; uint32_t bytes_completed; uint64_t fault_addr; union { /* common record */ struct { uint32_t invalid_flags:24; uint32_t rsvd2:8; }; uint32_t delta_rec_size; uint64_t crc_val; /* DIF check & strip */ struct { uint32_t dif_chk_ref_tag; uint16_t dif_chk_app_tag_mask; uint16_t dif_chk_app_tag; }; /* DIF insert */ struct { uint64_t dif_ins_res; uint32_t dif_ins_ref_tag; uint16_t dif_ins_app_tag_mask; uint16_t dif_ins_app_tag; }; /* DIF update */ struct { uint32_t dif_upd_src_ref_tag; uint16_t dif_upd_src_app_tag_mask; uint16_t dif_upd_src_app_tag; uint32_t dif_upd_dest_ref_tag; uint16_t dif_upd_dest_app_tag_mask; uint16_t dif_upd_dest_app_tag; }; uint8_t op_specific[16]; }; } __attribute__((packed)); struct dsa_raw_completion_record { uint64_t field[4]; } __attribute__((packed)); struct iax_completion_record { __volatile__ uint8_t status; uint8_t error_code; uint16_t rsvd; uint32_t bytes_completed; uint64_t fault_addr; uint32_t invalid_flags; uint32_t rsvd2; uint32_t output_size; uint8_t output_bits; uint8_t rsvd3; uint16_t xor_csum; uint32_t crc; uint32_t min; uint32_t max; uint32_t sum; uint64_t rsvd4[2]; } __attribute__((packed)); struct iax_raw_completion_record { uint64_t field[8]; } __attribute__((packed)); #endif linux/i2o-dev.h000064400000026443151027430560007335 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * I2O user space accessible structures/APIs * * (c) Copyright 1999, 2000 Red Hat Software * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * ************************************************************************* * * This header file defines the I2O APIs that are available to both * the kernel and user level applications. Kernel specific structures * are defined in i2o_osm. OSMs should include _only_ i2o_osm.h which * automatically includes this file. * */ #ifndef _I2O_DEV_H #define _I2O_DEV_H /* How many controllers are we allowing */ #define MAX_I2O_CONTROLLERS 32 #include #include /* * I2O Control IOCTLs and structures */ #define I2O_MAGIC_NUMBER 'i' #define I2OGETIOPS _IOR(I2O_MAGIC_NUMBER,0,__u8[MAX_I2O_CONTROLLERS]) #define I2OHRTGET _IOWR(I2O_MAGIC_NUMBER,1,struct i2o_cmd_hrtlct) #define I2OLCTGET _IOWR(I2O_MAGIC_NUMBER,2,struct i2o_cmd_hrtlct) #define I2OPARMSET _IOWR(I2O_MAGIC_NUMBER,3,struct i2o_cmd_psetget) #define I2OPARMGET _IOWR(I2O_MAGIC_NUMBER,4,struct i2o_cmd_psetget) #define I2OSWDL _IOWR(I2O_MAGIC_NUMBER,5,struct i2o_sw_xfer) #define I2OSWUL _IOWR(I2O_MAGIC_NUMBER,6,struct i2o_sw_xfer) #define I2OSWDEL _IOWR(I2O_MAGIC_NUMBER,7,struct i2o_sw_xfer) #define I2OVALIDATE _IOR(I2O_MAGIC_NUMBER,8,__u32) #define I2OHTML _IOWR(I2O_MAGIC_NUMBER,9,struct i2o_html) #define I2OEVTREG _IOW(I2O_MAGIC_NUMBER,10,struct i2o_evt_id) #define I2OEVTGET _IOR(I2O_MAGIC_NUMBER,11,struct i2o_evt_info) #define I2OPASSTHRU _IOR(I2O_MAGIC_NUMBER,12,struct i2o_cmd_passthru) #define I2OPASSTHRU32 _IOR(I2O_MAGIC_NUMBER,12,struct i2o_cmd_passthru32) struct i2o_cmd_passthru32 { unsigned int iop; /* IOP unit number */ __u32 msg; /* message */ }; struct i2o_cmd_passthru { unsigned int iop; /* IOP unit number */ void *msg; /* message */ }; struct i2o_cmd_hrtlct { unsigned int iop; /* IOP unit number */ void *resbuf; /* Buffer for result */ unsigned int *reslen; /* Buffer length in bytes */ }; struct i2o_cmd_psetget { unsigned int iop; /* IOP unit number */ unsigned int tid; /* Target device TID */ void *opbuf; /* Operation List buffer */ unsigned int oplen; /* Operation List buffer length in bytes */ void *resbuf; /* Result List buffer */ unsigned int *reslen; /* Result List buffer length in bytes */ }; struct i2o_sw_xfer { unsigned int iop; /* IOP unit number */ unsigned char flags; /* Flags field */ unsigned char sw_type; /* Software type */ unsigned int sw_id; /* Software ID */ void *buf; /* Pointer to software buffer */ unsigned int *swlen; /* Length of software data */ unsigned int *maxfrag; /* Maximum fragment count */ unsigned int *curfrag; /* Current fragment count */ }; struct i2o_html { unsigned int iop; /* IOP unit number */ unsigned int tid; /* Target device ID */ unsigned int page; /* HTML page */ void *resbuf; /* Buffer for reply HTML page */ unsigned int *reslen; /* Length in bytes of reply buffer */ void *qbuf; /* Pointer to HTTP query string */ unsigned int qlen; /* Length in bytes of query string buffer */ }; #define I2O_EVT_Q_LEN 32 struct i2o_evt_id { unsigned int iop; unsigned int tid; unsigned int evt_mask; }; /* Event data size = frame size - message header + evt indicator */ #define I2O_EVT_DATA_SIZE 88 struct i2o_evt_info { struct i2o_evt_id id; unsigned char evt_data[I2O_EVT_DATA_SIZE]; unsigned int data_size; }; struct i2o_evt_get { struct i2o_evt_info info; int pending; int lost; }; typedef struct i2o_sg_io_hdr { unsigned int flags; /* see I2O_DPT_SG_IO_FLAGS */ } i2o_sg_io_hdr_t; /************************************************************************** * HRT related constants and structures **************************************************************************/ #define I2O_BUS_LOCAL 0 #define I2O_BUS_ISA 1 #define I2O_BUS_EISA 2 /* was I2O_BUS_MCA 3 */ #define I2O_BUS_PCI 4 #define I2O_BUS_PCMCIA 5 #define I2O_BUS_NUBUS 6 #define I2O_BUS_CARDBUS 7 #define I2O_BUS_UNKNOWN 0x80 typedef struct _i2o_pci_bus { __u8 PciFunctionNumber; __u8 PciDeviceNumber; __u8 PciBusNumber; __u8 reserved; __u16 PciVendorID; __u16 PciDeviceID; } i2o_pci_bus; typedef struct _i2o_local_bus { __u16 LbBaseIOPort; __u16 reserved; __u32 LbBaseMemoryAddress; } i2o_local_bus; typedef struct _i2o_isa_bus { __u16 IsaBaseIOPort; __u8 CSN; __u8 reserved; __u32 IsaBaseMemoryAddress; } i2o_isa_bus; typedef struct _i2o_eisa_bus_info { __u16 EisaBaseIOPort; __u8 reserved; __u8 EisaSlotNumber; __u32 EisaBaseMemoryAddress; } i2o_eisa_bus; typedef struct _i2o_mca_bus { __u16 McaBaseIOPort; __u8 reserved; __u8 McaSlotNumber; __u32 McaBaseMemoryAddress; } i2o_mca_bus; typedef struct _i2o_other_bus { __u16 BaseIOPort; __u16 reserved; __u32 BaseMemoryAddress; } i2o_other_bus; typedef struct _i2o_hrt_entry { __u32 adapter_id; __u32 parent_tid:12; __u32 state:4; __u32 bus_num:8; __u32 bus_type:8; union { i2o_pci_bus pci_bus; i2o_local_bus local_bus; i2o_isa_bus isa_bus; i2o_eisa_bus eisa_bus; i2o_mca_bus mca_bus; i2o_other_bus other_bus; } bus; } i2o_hrt_entry; typedef struct _i2o_hrt { __u16 num_entries; __u8 entry_len; __u8 hrt_version; __u32 change_ind; i2o_hrt_entry hrt_entry[1]; } i2o_hrt; typedef struct _i2o_lct_entry { __u32 entry_size:16; __u32 tid:12; __u32 reserved:4; __u32 change_ind; __u32 device_flags; __u32 class_id:12; __u32 version:4; __u32 vendor_id:16; __u32 sub_class; __u32 user_tid:12; __u32 parent_tid:12; __u32 bios_info:8; __u8 identity_tag[8]; __u32 event_capabilities; } i2o_lct_entry; typedef struct _i2o_lct { __u32 table_size:16; __u32 boot_tid:12; __u32 lct_ver:4; __u32 iop_flags; __u32 change_ind; i2o_lct_entry lct_entry[1]; } i2o_lct; typedef struct _i2o_status_block { __u16 org_id; __u16 reserved; __u16 iop_id:12; __u16 reserved1:4; __u16 host_unit_id; __u16 segment_number:12; __u16 i2o_version:4; __u8 iop_state; __u8 msg_type; __u16 inbound_frame_size; __u8 init_code; __u8 reserved2; __u32 max_inbound_frames; __u32 cur_inbound_frames; __u32 max_outbound_frames; char product_id[24]; __u32 expected_lct_size; __u32 iop_capabilities; __u32 desired_mem_size; __u32 current_mem_size; __u32 current_mem_base; __u32 desired_io_size; __u32 current_io_size; __u32 current_io_base; __u32 reserved3:24; __u32 cmd_status:8; } i2o_status_block; /* Event indicator mask flags */ #define I2O_EVT_IND_STATE_CHANGE 0x80000000 #define I2O_EVT_IND_GENERAL_WARNING 0x40000000 #define I2O_EVT_IND_CONFIGURATION_FLAG 0x20000000 #define I2O_EVT_IND_LOCK_RELEASE 0x10000000 #define I2O_EVT_IND_CAPABILITY_CHANGE 0x08000000 #define I2O_EVT_IND_DEVICE_RESET 0x04000000 #define I2O_EVT_IND_EVT_MASK_MODIFIED 0x02000000 #define I2O_EVT_IND_FIELD_MODIFIED 0x01000000 #define I2O_EVT_IND_VENDOR_EVT 0x00800000 #define I2O_EVT_IND_DEVICE_STATE 0x00400000 /* Executive event indicitors */ #define I2O_EVT_IND_EXEC_RESOURCE_LIMITS 0x00000001 #define I2O_EVT_IND_EXEC_CONNECTION_FAIL 0x00000002 #define I2O_EVT_IND_EXEC_ADAPTER_FAULT 0x00000004 #define I2O_EVT_IND_EXEC_POWER_FAIL 0x00000008 #define I2O_EVT_IND_EXEC_RESET_PENDING 0x00000010 #define I2O_EVT_IND_EXEC_RESET_IMMINENT 0x00000020 #define I2O_EVT_IND_EXEC_HW_FAIL 0x00000040 #define I2O_EVT_IND_EXEC_XCT_CHANGE 0x00000080 #define I2O_EVT_IND_EXEC_NEW_LCT_ENTRY 0x00000100 #define I2O_EVT_IND_EXEC_MODIFIED_LCT 0x00000200 #define I2O_EVT_IND_EXEC_DDM_AVAILABILITY 0x00000400 /* Random Block Storage Event Indicators */ #define I2O_EVT_IND_BSA_VOLUME_LOAD 0x00000001 #define I2O_EVT_IND_BSA_VOLUME_UNLOAD 0x00000002 #define I2O_EVT_IND_BSA_VOLUME_UNLOAD_REQ 0x00000004 #define I2O_EVT_IND_BSA_CAPACITY_CHANGE 0x00000008 #define I2O_EVT_IND_BSA_SCSI_SMART 0x00000010 /* Event data for generic events */ #define I2O_EVT_STATE_CHANGE_NORMAL 0x00 #define I2O_EVT_STATE_CHANGE_SUSPENDED 0x01 #define I2O_EVT_STATE_CHANGE_RESTART 0x02 #define I2O_EVT_STATE_CHANGE_NA_RECOVER 0x03 #define I2O_EVT_STATE_CHANGE_NA_NO_RECOVER 0x04 #define I2O_EVT_STATE_CHANGE_QUIESCE_REQUEST 0x05 #define I2O_EVT_STATE_CHANGE_FAILED 0x10 #define I2O_EVT_STATE_CHANGE_FAULTED 0x11 #define I2O_EVT_GEN_WARNING_NORMAL 0x00 #define I2O_EVT_GEN_WARNING_ERROR_THRESHOLD 0x01 #define I2O_EVT_GEN_WARNING_MEDIA_FAULT 0x02 #define I2O_EVT_CAPABILITY_OTHER 0x01 #define I2O_EVT_CAPABILITY_CHANGED 0x02 #define I2O_EVT_SENSOR_STATE_CHANGED 0x01 /* * I2O classes / subclasses */ /* Class ID and Code Assignments * (LCT.ClassID.Version field) */ #define I2O_CLASS_VERSION_10 0x00 #define I2O_CLASS_VERSION_11 0x01 /* Class code names * (from v1.5 Table 6-1 Class Code Assignments.) */ #define I2O_CLASS_EXECUTIVE 0x000 #define I2O_CLASS_DDM 0x001 #define I2O_CLASS_RANDOM_BLOCK_STORAGE 0x010 #define I2O_CLASS_SEQUENTIAL_STORAGE 0x011 #define I2O_CLASS_LAN 0x020 #define I2O_CLASS_WAN 0x030 #define I2O_CLASS_FIBRE_CHANNEL_PORT 0x040 #define I2O_CLASS_FIBRE_CHANNEL_PERIPHERAL 0x041 #define I2O_CLASS_SCSI_PERIPHERAL 0x051 #define I2O_CLASS_ATE_PORT 0x060 #define I2O_CLASS_ATE_PERIPHERAL 0x061 #define I2O_CLASS_FLOPPY_CONTROLLER 0x070 #define I2O_CLASS_FLOPPY_DEVICE 0x071 #define I2O_CLASS_BUS_ADAPTER 0x080 #define I2O_CLASS_PEER_TRANSPORT_AGENT 0x090 #define I2O_CLASS_PEER_TRANSPORT 0x091 #define I2O_CLASS_END 0xfff /* * Rest of 0x092 - 0x09f reserved for peer-to-peer classes */ #define I2O_CLASS_MATCH_ANYCLASS 0xffffffff /* * Subclasses */ #define I2O_SUBCLASS_i960 0x001 #define I2O_SUBCLASS_HDM 0x020 #define I2O_SUBCLASS_ISM 0x021 /* Operation functions */ #define I2O_PARAMS_FIELD_GET 0x0001 #define I2O_PARAMS_LIST_GET 0x0002 #define I2O_PARAMS_MORE_GET 0x0003 #define I2O_PARAMS_SIZE_GET 0x0004 #define I2O_PARAMS_TABLE_GET 0x0005 #define I2O_PARAMS_FIELD_SET 0x0006 #define I2O_PARAMS_LIST_SET 0x0007 #define I2O_PARAMS_ROW_ADD 0x0008 #define I2O_PARAMS_ROW_DELETE 0x0009 #define I2O_PARAMS_TABLE_CLEAR 0x000A /* * I2O serial number conventions / formats * (circa v1.5) */ #define I2O_SNFORMAT_UNKNOWN 0 #define I2O_SNFORMAT_BINARY 1 #define I2O_SNFORMAT_ASCII 2 #define I2O_SNFORMAT_UNICODE 3 #define I2O_SNFORMAT_LAN48_MAC 4 #define I2O_SNFORMAT_WAN 5 /* * Plus new in v2.0 (Yellowstone pdf doc) */ #define I2O_SNFORMAT_LAN64_MAC 6 #define I2O_SNFORMAT_DDM 7 #define I2O_SNFORMAT_IEEE_REG64 8 #define I2O_SNFORMAT_IEEE_REG128 9 #define I2O_SNFORMAT_UNKNOWN2 0xff /* * I2O Get Status State values */ #define ADAPTER_STATE_INITIALIZING 0x01 #define ADAPTER_STATE_RESET 0x02 #define ADAPTER_STATE_HOLD 0x04 #define ADAPTER_STATE_READY 0x05 #define ADAPTER_STATE_OPERATIONAL 0x08 #define ADAPTER_STATE_FAILED 0x10 #define ADAPTER_STATE_FAULTED 0x11 /* * Software module types */ #define I2O_SOFTWARE_MODULE_IRTOS 0x11 #define I2O_SOFTWARE_MODULE_IOP_PRIVATE 0x22 #define I2O_SOFTWARE_MODULE_IOP_CONFIG 0x23 /* * Vendors */ #define I2O_VENDOR_DPT 0x001b /* * DPT / Adaptec specific values for i2o_sg_io_hdr flags. */ #define I2O_DPT_SG_FLAG_INTERPRET 0x00010000 #define I2O_DPT_SG_FLAG_PHYSICAL 0x00020000 #define I2O_DPT_FLASH_FRAG_SIZE 0x10000 #define I2O_DPT_FLASH_READ 0x0101 #define I2O_DPT_FLASH_WRITE 0x0102 #endif /* _I2O_DEV_H */ linux/vm_sockets_diag.h000064400000001703151027430560011221 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* AF_VSOCK sock_diag(7) interface for querying open sockets */ #ifndef __VM_SOCKETS_DIAG_H__ #define __VM_SOCKETS_DIAG_H__ #include /* Request */ struct vsock_diag_req { __u8 sdiag_family; /* must be AF_VSOCK */ __u8 sdiag_protocol; /* must be 0 */ __u16 pad; /* must be 0 */ __u32 vdiag_states; /* query bitmap (e.g. 1 << TCP_LISTEN) */ __u32 vdiag_ino; /* must be 0 (reserved) */ __u32 vdiag_show; /* must be 0 (reserved) */ __u32 vdiag_cookie[2]; }; /* Response */ struct vsock_diag_msg { __u8 vdiag_family; /* AF_VSOCK */ __u8 vdiag_type; /* SOCK_STREAM or SOCK_DGRAM */ __u8 vdiag_state; /* sk_state (e.g. TCP_LISTEN) */ __u8 vdiag_shutdown; /* local RCV_SHUTDOWN | SEND_SHUTDOWN */ __u32 vdiag_src_cid; __u32 vdiag_src_port; __u32 vdiag_dst_cid; __u32 vdiag_dst_port; __u32 vdiag_ino; __u32 vdiag_cookie[2]; }; #endif /* __VM_SOCKETS_DIAG_H__ */ linux/igmp.h000064400000005770151027430560007024 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Linux NET3: Internet Group Management Protocol [IGMP] * * Authors: * Alan Cox * * Extended to talk the BSD extended IGMP protocol of mrouted 3.6 * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IGMP_H #define _LINUX_IGMP_H #include #include /* * IGMP protocol structures */ /* * Header in on cable format */ struct igmphdr { __u8 type; __u8 code; /* For newer IGMP */ __sum16 csum; __be32 group; }; /* V3 group record types [grec_type] */ #define IGMPV3_MODE_IS_INCLUDE 1 #define IGMPV3_MODE_IS_EXCLUDE 2 #define IGMPV3_CHANGE_TO_INCLUDE 3 #define IGMPV3_CHANGE_TO_EXCLUDE 4 #define IGMPV3_ALLOW_NEW_SOURCES 5 #define IGMPV3_BLOCK_OLD_SOURCES 6 struct igmpv3_grec { __u8 grec_type; __u8 grec_auxwords; __be16 grec_nsrcs; __be32 grec_mca; __be32 grec_src[0]; }; struct igmpv3_report { __u8 type; __u8 resv1; __sum16 csum; __be16 resv2; __be16 ngrec; struct igmpv3_grec grec[0]; }; struct igmpv3_query { __u8 type; __u8 code; __sum16 csum; __be32 group; #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 qrv:3, suppress:1, resv:4; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 resv:4, suppress:1, qrv:3; #else #error "Please fix " #endif __u8 qqic; __be16 nsrcs; __be32 srcs[0]; }; #define IGMP_HOST_MEMBERSHIP_QUERY 0x11 /* From RFC1112 */ #define IGMP_HOST_MEMBERSHIP_REPORT 0x12 /* Ditto */ #define IGMP_DVMRP 0x13 /* DVMRP routing */ #define IGMP_PIM 0x14 /* PIM routing */ #define IGMP_TRACE 0x15 #define IGMPV2_HOST_MEMBERSHIP_REPORT 0x16 /* V2 version of 0x12 */ #define IGMP_HOST_LEAVE_MESSAGE 0x17 #define IGMPV3_HOST_MEMBERSHIP_REPORT 0x22 /* V3 version of 0x12 */ #define IGMP_MTRACE_RESP 0x1e #define IGMP_MTRACE 0x1f #define IGMP_MRDISC_ADV 0x30 /* From RFC4286 */ /* * Use the BSD names for these for compatibility */ #define IGMP_DELAYING_MEMBER 0x01 #define IGMP_IDLE_MEMBER 0x02 #define IGMP_LAZY_MEMBER 0x03 #define IGMP_SLEEPING_MEMBER 0x04 #define IGMP_AWAKENING_MEMBER 0x05 #define IGMP_MINLEN 8 #define IGMP_MAX_HOST_REPORT_DELAY 10 /* max delay for response to */ /* query (in seconds) */ #define IGMP_TIMER_SCALE 10 /* denotes that the igmphdr->timer field */ /* specifies time in 10th of seconds */ #define IGMP_AGE_THRESHOLD 400 /* If this host don't hear any IGMP V1 */ /* message in this period of time, */ /* revert to IGMP v2 router. */ #define IGMP_ALL_HOSTS htonl(0xE0000001L) #define IGMP_ALL_ROUTER htonl(0xE0000002L) #define IGMPV3_ALL_MCR htonl(0xE0000016L) #define IGMP_LOCAL_GROUP htonl(0xE0000000L) #define IGMP_LOCAL_GROUP_MASK htonl(0xFFFFFF00L) /* * struct for keeping the multicast list in */ #endif /* _LINUX_IGMP_H */ linux/virtio_snd.h000064400000022130151027430560010235 0ustar00/* SPDX-License-Identifier: BSD-3-Clause */ /* * Copyright (C) 2021 OpenSynergy GmbH */ #ifndef VIRTIO_SND_IF_H #define VIRTIO_SND_IF_H #include /******************************************************************************* * CONFIGURATION SPACE */ struct virtio_snd_config { /* # of available physical jacks */ __le32 jacks; /* # of available PCM streams */ __le32 streams; /* # of available channel maps */ __le32 chmaps; }; enum { /* device virtqueue indexes */ VIRTIO_SND_VQ_CONTROL = 0, VIRTIO_SND_VQ_EVENT, VIRTIO_SND_VQ_TX, VIRTIO_SND_VQ_RX, /* # of device virtqueues */ VIRTIO_SND_VQ_MAX }; /******************************************************************************* * COMMON DEFINITIONS */ /* supported dataflow directions */ enum { VIRTIO_SND_D_OUTPUT = 0, VIRTIO_SND_D_INPUT }; enum { /* jack control request types */ VIRTIO_SND_R_JACK_INFO = 1, VIRTIO_SND_R_JACK_REMAP, /* PCM control request types */ VIRTIO_SND_R_PCM_INFO = 0x0100, VIRTIO_SND_R_PCM_SET_PARAMS, VIRTIO_SND_R_PCM_PREPARE, VIRTIO_SND_R_PCM_RELEASE, VIRTIO_SND_R_PCM_START, VIRTIO_SND_R_PCM_STOP, /* channel map control request types */ VIRTIO_SND_R_CHMAP_INFO = 0x0200, /* jack event types */ VIRTIO_SND_EVT_JACK_CONNECTED = 0x1000, VIRTIO_SND_EVT_JACK_DISCONNECTED, /* PCM event types */ VIRTIO_SND_EVT_PCM_PERIOD_ELAPSED = 0x1100, VIRTIO_SND_EVT_PCM_XRUN, /* common status codes */ VIRTIO_SND_S_OK = 0x8000, VIRTIO_SND_S_BAD_MSG, VIRTIO_SND_S_NOT_SUPP, VIRTIO_SND_S_IO_ERR }; /* common header */ struct virtio_snd_hdr { __le32 code; }; /* event notification */ struct virtio_snd_event { /* VIRTIO_SND_EVT_XXX */ struct virtio_snd_hdr hdr; /* optional event data */ __le32 data; }; /* common control request to query an item information */ struct virtio_snd_query_info { /* VIRTIO_SND_R_XXX_INFO */ struct virtio_snd_hdr hdr; /* item start identifier */ __le32 start_id; /* item count to query */ __le32 count; /* item information size in bytes */ __le32 size; }; /* common item information header */ struct virtio_snd_info { /* function group node id (High Definition Audio Specification 7.1.2) */ __le32 hda_fn_nid; }; /******************************************************************************* * JACK CONTROL MESSAGES */ struct virtio_snd_jack_hdr { /* VIRTIO_SND_R_JACK_XXX */ struct virtio_snd_hdr hdr; /* 0 ... virtio_snd_config::jacks - 1 */ __le32 jack_id; }; /* supported jack features */ enum { VIRTIO_SND_JACK_F_REMAP = 0 }; struct virtio_snd_jack_info { /* common header */ struct virtio_snd_info hdr; /* supported feature bit map (1 << VIRTIO_SND_JACK_F_XXX) */ __le32 features; /* pin configuration (High Definition Audio Specification 7.3.3.31) */ __le32 hda_reg_defconf; /* pin capabilities (High Definition Audio Specification 7.3.4.9) */ __le32 hda_reg_caps; /* current jack connection status (0: disconnected, 1: connected) */ __u8 connected; __u8 padding[7]; }; /* jack remapping control request */ struct virtio_snd_jack_remap { /* .code = VIRTIO_SND_R_JACK_REMAP */ struct virtio_snd_jack_hdr hdr; /* selected association number */ __le32 association; /* selected sequence number */ __le32 sequence; }; /******************************************************************************* * PCM CONTROL MESSAGES */ struct virtio_snd_pcm_hdr { /* VIRTIO_SND_R_PCM_XXX */ struct virtio_snd_hdr hdr; /* 0 ... virtio_snd_config::streams - 1 */ __le32 stream_id; }; /* supported PCM stream features */ enum { VIRTIO_SND_PCM_F_SHMEM_HOST = 0, VIRTIO_SND_PCM_F_SHMEM_GUEST, VIRTIO_SND_PCM_F_MSG_POLLING, VIRTIO_SND_PCM_F_EVT_SHMEM_PERIODS, VIRTIO_SND_PCM_F_EVT_XRUNS }; /* supported PCM sample formats */ enum { /* analog formats (width / physical width) */ VIRTIO_SND_PCM_FMT_IMA_ADPCM = 0, /* 4 / 4 bits */ VIRTIO_SND_PCM_FMT_MU_LAW, /* 8 / 8 bits */ VIRTIO_SND_PCM_FMT_A_LAW, /* 8 / 8 bits */ VIRTIO_SND_PCM_FMT_S8, /* 8 / 8 bits */ VIRTIO_SND_PCM_FMT_U8, /* 8 / 8 bits */ VIRTIO_SND_PCM_FMT_S16, /* 16 / 16 bits */ VIRTIO_SND_PCM_FMT_U16, /* 16 / 16 bits */ VIRTIO_SND_PCM_FMT_S18_3, /* 18 / 24 bits */ VIRTIO_SND_PCM_FMT_U18_3, /* 18 / 24 bits */ VIRTIO_SND_PCM_FMT_S20_3, /* 20 / 24 bits */ VIRTIO_SND_PCM_FMT_U20_3, /* 20 / 24 bits */ VIRTIO_SND_PCM_FMT_S24_3, /* 24 / 24 bits */ VIRTIO_SND_PCM_FMT_U24_3, /* 24 / 24 bits */ VIRTIO_SND_PCM_FMT_S20, /* 20 / 32 bits */ VIRTIO_SND_PCM_FMT_U20, /* 20 / 32 bits */ VIRTIO_SND_PCM_FMT_S24, /* 24 / 32 bits */ VIRTIO_SND_PCM_FMT_U24, /* 24 / 32 bits */ VIRTIO_SND_PCM_FMT_S32, /* 32 / 32 bits */ VIRTIO_SND_PCM_FMT_U32, /* 32 / 32 bits */ VIRTIO_SND_PCM_FMT_FLOAT, /* 32 / 32 bits */ VIRTIO_SND_PCM_FMT_FLOAT64, /* 64 / 64 bits */ /* digital formats (width / physical width) */ VIRTIO_SND_PCM_FMT_DSD_U8, /* 8 / 8 bits */ VIRTIO_SND_PCM_FMT_DSD_U16, /* 16 / 16 bits */ VIRTIO_SND_PCM_FMT_DSD_U32, /* 32 / 32 bits */ VIRTIO_SND_PCM_FMT_IEC958_SUBFRAME /* 32 / 32 bits */ }; /* supported PCM frame rates */ enum { VIRTIO_SND_PCM_RATE_5512 = 0, VIRTIO_SND_PCM_RATE_8000, VIRTIO_SND_PCM_RATE_11025, VIRTIO_SND_PCM_RATE_16000, VIRTIO_SND_PCM_RATE_22050, VIRTIO_SND_PCM_RATE_32000, VIRTIO_SND_PCM_RATE_44100, VIRTIO_SND_PCM_RATE_48000, VIRTIO_SND_PCM_RATE_64000, VIRTIO_SND_PCM_RATE_88200, VIRTIO_SND_PCM_RATE_96000, VIRTIO_SND_PCM_RATE_176400, VIRTIO_SND_PCM_RATE_192000, VIRTIO_SND_PCM_RATE_384000 }; struct virtio_snd_pcm_info { /* common header */ struct virtio_snd_info hdr; /* supported feature bit map (1 << VIRTIO_SND_PCM_F_XXX) */ __le32 features; /* supported sample format bit map (1 << VIRTIO_SND_PCM_FMT_XXX) */ __le64 formats; /* supported frame rate bit map (1 << VIRTIO_SND_PCM_RATE_XXX) */ __le64 rates; /* dataflow direction (VIRTIO_SND_D_XXX) */ __u8 direction; /* minimum # of supported channels */ __u8 channels_min; /* maximum # of supported channels */ __u8 channels_max; __u8 padding[5]; }; /* set PCM stream format */ struct virtio_snd_pcm_set_params { /* .code = VIRTIO_SND_R_PCM_SET_PARAMS */ struct virtio_snd_pcm_hdr hdr; /* size of the hardware buffer */ __le32 buffer_bytes; /* size of the hardware period */ __le32 period_bytes; /* selected feature bit map (1 << VIRTIO_SND_PCM_F_XXX) */ __le32 features; /* selected # of channels */ __u8 channels; /* selected sample format (VIRTIO_SND_PCM_FMT_XXX) */ __u8 format; /* selected frame rate (VIRTIO_SND_PCM_RATE_XXX) */ __u8 rate; __u8 padding; }; /******************************************************************************* * PCM I/O MESSAGES */ /* I/O request header */ struct virtio_snd_pcm_xfer { /* 0 ... virtio_snd_config::streams - 1 */ __le32 stream_id; }; /* I/O request status */ struct virtio_snd_pcm_status { /* VIRTIO_SND_S_XXX */ __le32 status; /* current device latency */ __le32 latency_bytes; }; /******************************************************************************* * CHANNEL MAP CONTROL MESSAGES */ struct virtio_snd_chmap_hdr { /* VIRTIO_SND_R_CHMAP_XXX */ struct virtio_snd_hdr hdr; /* 0 ... virtio_snd_config::chmaps - 1 */ __le32 chmap_id; }; /* standard channel position definition */ enum { VIRTIO_SND_CHMAP_NONE = 0, /* undefined */ VIRTIO_SND_CHMAP_NA, /* silent */ VIRTIO_SND_CHMAP_MONO, /* mono stream */ VIRTIO_SND_CHMAP_FL, /* front left */ VIRTIO_SND_CHMAP_FR, /* front right */ VIRTIO_SND_CHMAP_RL, /* rear left */ VIRTIO_SND_CHMAP_RR, /* rear right */ VIRTIO_SND_CHMAP_FC, /* front center */ VIRTIO_SND_CHMAP_LFE, /* low frequency (LFE) */ VIRTIO_SND_CHMAP_SL, /* side left */ VIRTIO_SND_CHMAP_SR, /* side right */ VIRTIO_SND_CHMAP_RC, /* rear center */ VIRTIO_SND_CHMAP_FLC, /* front left center */ VIRTIO_SND_CHMAP_FRC, /* front right center */ VIRTIO_SND_CHMAP_RLC, /* rear left center */ VIRTIO_SND_CHMAP_RRC, /* rear right center */ VIRTIO_SND_CHMAP_FLW, /* front left wide */ VIRTIO_SND_CHMAP_FRW, /* front right wide */ VIRTIO_SND_CHMAP_FLH, /* front left high */ VIRTIO_SND_CHMAP_FCH, /* front center high */ VIRTIO_SND_CHMAP_FRH, /* front right high */ VIRTIO_SND_CHMAP_TC, /* top center */ VIRTIO_SND_CHMAP_TFL, /* top front left */ VIRTIO_SND_CHMAP_TFR, /* top front right */ VIRTIO_SND_CHMAP_TFC, /* top front center */ VIRTIO_SND_CHMAP_TRL, /* top rear left */ VIRTIO_SND_CHMAP_TRR, /* top rear right */ VIRTIO_SND_CHMAP_TRC, /* top rear center */ VIRTIO_SND_CHMAP_TFLC, /* top front left center */ VIRTIO_SND_CHMAP_TFRC, /* top front right center */ VIRTIO_SND_CHMAP_TSL, /* top side left */ VIRTIO_SND_CHMAP_TSR, /* top side right */ VIRTIO_SND_CHMAP_LLFE, /* left LFE */ VIRTIO_SND_CHMAP_RLFE, /* right LFE */ VIRTIO_SND_CHMAP_BC, /* bottom center */ VIRTIO_SND_CHMAP_BLC, /* bottom left center */ VIRTIO_SND_CHMAP_BRC /* bottom right center */ }; /* maximum possible number of channels */ #define VIRTIO_SND_CHMAP_MAX_SIZE 18 struct virtio_snd_chmap_info { /* common header */ struct virtio_snd_info hdr; /* dataflow direction (VIRTIO_SND_D_XXX) */ __u8 direction; /* # of valid channel position values */ __u8 channels; /* channel position values (VIRTIO_SND_CHMAP_XXX) */ __u8 positions[VIRTIO_SND_CHMAP_MAX_SIZE]; }; #endif /* VIRTIO_SND_IF_H */ linux/fsl_hypervisor.h000064400000016205151027430560011141 0ustar00/* SPDX-License-Identifier: ((GPL-2.0+ WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Freescale hypervisor ioctl and kernel interface * * Copyright (C) 2008-2011 Freescale Semiconductor, Inc. * Author: Timur Tabi * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Freescale Semiconductor nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") as published by the Free Software * Foundation, either version 2 of that License or (at your option) any * later version. * * This software is provided by Freescale Semiconductor "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 Freescale Semiconductor 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. * * This file is used by the Freescale hypervisor management driver. It can * also be included by applications that need to communicate with the driver * via the ioctl interface. */ #ifndef FSL_HYPERVISOR_H #define FSL_HYPERVISOR_H #include /** * struct fsl_hv_ioctl_restart - restart a partition * @ret: return error code from the hypervisor * @partition: the ID of the partition to restart, or -1 for the * calling partition * * Used by FSL_HV_IOCTL_PARTITION_RESTART */ struct fsl_hv_ioctl_restart { __u32 ret; __u32 partition; }; /** * struct fsl_hv_ioctl_status - get a partition's status * @ret: return error code from the hypervisor * @partition: the ID of the partition to query, or -1 for the * calling partition * @status: The returned status of the partition * * Used by FSL_HV_IOCTL_PARTITION_GET_STATUS * * Values of 'status': * 0 = Stopped * 1 = Running * 2 = Starting * 3 = Stopping */ struct fsl_hv_ioctl_status { __u32 ret; __u32 partition; __u32 status; }; /** * struct fsl_hv_ioctl_start - start a partition * @ret: return error code from the hypervisor * @partition: the ID of the partition to control * @entry_point: The offset within the guest IMA to start execution * @load: If non-zero, reload the partition's images before starting * * Used by FSL_HV_IOCTL_PARTITION_START */ struct fsl_hv_ioctl_start { __u32 ret; __u32 partition; __u32 entry_point; __u32 load; }; /** * struct fsl_hv_ioctl_stop - stop a partition * @ret: return error code from the hypervisor * @partition: the ID of the partition to stop, or -1 for the calling * partition * * Used by FSL_HV_IOCTL_PARTITION_STOP */ struct fsl_hv_ioctl_stop { __u32 ret; __u32 partition; }; /** * struct fsl_hv_ioctl_memcpy - copy memory between partitions * @ret: return error code from the hypervisor * @source: the partition ID of the source partition, or -1 for this * partition * @target: the partition ID of the target partition, or -1 for this * partition * @reserved: reserved, must be set to 0 * @local_addr: user-space virtual address of a buffer in the local * partition * @remote_addr: guest physical address of a buffer in the * remote partition * @count: the number of bytes to copy. Both the local and remote * buffers must be at least 'count' bytes long * * Used by FSL_HV_IOCTL_MEMCPY * * The 'local' partition is the partition that calls this ioctl. The * 'remote' partition is a different partition. The data is copied from * the 'source' paritition' to the 'target' partition. * * The buffer in the remote partition must be guest physically * contiguous. * * This ioctl does not support copying memory between two remote * partitions or within the same partition, so either 'source' or * 'target' (but not both) must be -1. In other words, either * * source == local and target == remote * or * source == remote and target == local */ struct fsl_hv_ioctl_memcpy { __u32 ret; __u32 source; __u32 target; __u32 reserved; /* padding to ensure local_vaddr is aligned */ __u64 local_vaddr; __u64 remote_paddr; __u64 count; }; /** * struct fsl_hv_ioctl_doorbell - ring a doorbell * @ret: return error code from the hypervisor * @doorbell: the handle of the doorbell to ring doorbell * * Used by FSL_HV_IOCTL_DOORBELL */ struct fsl_hv_ioctl_doorbell { __u32 ret; __u32 doorbell; }; /** * struct fsl_hv_ioctl_prop - get/set a device tree property * @ret: return error code from the hypervisor * @handle: handle of partition whose tree to access * @path: virtual address of path name of node to access * @propname: virtual address of name of property to access * @propval: virtual address of property data buffer * @proplen: Size of property data buffer * @reserved: reserved, must be set to 0 * * Used by FSL_HV_IOCTL_DOORBELL */ struct fsl_hv_ioctl_prop { __u32 ret; __u32 handle; __u64 path; __u64 propname; __u64 propval; __u32 proplen; __u32 reserved; /* padding to ensure structure is aligned */ }; /* The ioctl type, documented in ioctl-number.txt */ #define FSL_HV_IOCTL_TYPE 0xAF /* Restart another partition */ #define FSL_HV_IOCTL_PARTITION_RESTART \ _IOWR(FSL_HV_IOCTL_TYPE, 1, struct fsl_hv_ioctl_restart) /* Get a partition's status */ #define FSL_HV_IOCTL_PARTITION_GET_STATUS \ _IOWR(FSL_HV_IOCTL_TYPE, 2, struct fsl_hv_ioctl_status) /* Boot another partition */ #define FSL_HV_IOCTL_PARTITION_START \ _IOWR(FSL_HV_IOCTL_TYPE, 3, struct fsl_hv_ioctl_start) /* Stop this or another partition */ #define FSL_HV_IOCTL_PARTITION_STOP \ _IOWR(FSL_HV_IOCTL_TYPE, 4, struct fsl_hv_ioctl_stop) /* Copy data from one partition to another */ #define FSL_HV_IOCTL_MEMCPY \ _IOWR(FSL_HV_IOCTL_TYPE, 5, struct fsl_hv_ioctl_memcpy) /* Ring a doorbell */ #define FSL_HV_IOCTL_DOORBELL \ _IOWR(FSL_HV_IOCTL_TYPE, 6, struct fsl_hv_ioctl_doorbell) /* Get a property from another guest's device tree */ #define FSL_HV_IOCTL_GETPROP \ _IOWR(FSL_HV_IOCTL_TYPE, 7, struct fsl_hv_ioctl_prop) /* Set a property in another guest's device tree */ #define FSL_HV_IOCTL_SETPROP \ _IOWR(FSL_HV_IOCTL_TYPE, 8, struct fsl_hv_ioctl_prop) #endif /* FSL_HYPERVISOR_H */ linux/auto_fs4.h000064400000000703151027430560007603 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright 1999-2000 Jeremy Fitzhardinge * * This file is part of the Linux kernel and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. */ #ifndef _LINUX_AUTO_FS4_H #define _LINUX_AUTO_FS4_H #include #endif /* _LINUX_AUTO_FS4_H */ linux/tipc_sockets_diag.h000064400000000724151027430560011540 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* AF_TIPC sock_diag interface for querying open sockets */ #ifndef __TIPC_SOCKETS_DIAG_H__ #define __TIPC_SOCKETS_DIAG_H__ #include #include /* Request */ struct tipc_sock_diag_req { __u8 sdiag_family; /* must be AF_TIPC */ __u8 sdiag_protocol; /* must be 0 */ __u16 pad; /* must be 0 */ __u32 tidiag_states; /* query*/ }; #endif /* __TIPC_SOCKETS_DIAG_H__ */ linux/mei.h000064400000006623151027430560006640 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Copyright(c) 2003-2015 Intel Corporation. All rights reserved. * Intel Management Engine Interface (Intel MEI) Linux driver * Intel MEI Interface Header */ #ifndef _LINUX_MEI_H #define _LINUX_MEI_H #include /* * This IOCTL is used to associate the current file descriptor with a * FW Client (given by UUID). This opens a communication channel * between a host client and a FW client. From this point every read and write * will communicate with the associated FW client. * Only in close() (file_operation release()) the communication between * the clients is disconnected * * The IOCTL argument is a struct with a union that contains * the input parameter and the output parameter for this IOCTL. * * The input parameter is UUID of the FW Client. * The output parameter is the properties of the FW client * (FW protocol version and max message size). * */ #define IOCTL_MEI_CONNECT_CLIENT \ _IOWR('H' , 0x01, struct mei_connect_client_data) /* * Intel MEI client information struct */ struct mei_client { __u32 max_msg_length; __u8 protocol_version; __u8 reserved[3]; }; /* * IOCTL Connect Client Data structure */ struct mei_connect_client_data { union { uuid_le in_client_uuid; struct mei_client out_client_properties; }; }; /** * DOC: set and unset event notification for a connected client * * The IOCTL argument is 1 for enabling event notification and 0 for * disabling the service * Return: -EOPNOTSUPP if the devices doesn't support the feature */ #define IOCTL_MEI_NOTIFY_SET _IOW('H', 0x02, __u32) /** * DOC: retrieve notification * * The IOCTL output argument is 1 if an event was is pending and 0 otherwise * the ioctl has to be called in order to acknowledge pending event * * Return: -EOPNOTSUPP if the devices doesn't support the feature */ #define IOCTL_MEI_NOTIFY_GET _IOR('H', 0x03, __u32) /** * struct mei_connect_client_vtag - mei client information struct with vtag * * @in_client_uuid: UUID of client to connect * @vtag: virtual tag * @reserved: reserved for future use */ struct mei_connect_client_vtag { uuid_le in_client_uuid; __u8 vtag; __u8 reserved[3]; }; /** * struct mei_connect_client_data_vtag - IOCTL connect data union * * @connect: input connect data * @out_client_properties: output client data */ struct mei_connect_client_data_vtag { union { struct mei_connect_client_vtag connect; struct mei_client out_client_properties; }; }; /** * DOC: * This IOCTL is used to associate the current file descriptor with a * FW Client (given by UUID), and virtual tag (vtag). * The IOCTL opens a communication channel between a host client and * a FW client on a tagged channel. From this point on, every read * and write will communicate with the associated FW client with * on the tagged channel. * Upone close() the communication is terminated. * * The IOCTL argument is a struct with a union that contains * the input parameter and the output parameter for this IOCTL. * * The input parameter is UUID of the FW Client, a vtag [0,255] * The output parameter is the properties of the FW client * (FW protocool version and max message size). * * Clients that do not support tagged connection * will respond with -EOPNOTSUPP. */ #define IOCTL_MEI_CONNECT_CLIENT_VTAG \ _IOWR('H', 0x04, struct mei_connect_client_data_vtag) #endif /* _LINUX_MEI_H */ linux/caif/caif_socket.h000064400000013310151027430560011231 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* linux/caif_socket.h * CAIF Definitions for CAIF socket and network layer * Copyright (C) ST-Ericsson AB 2010 * Author: Sjur Brendeland * License terms: GNU General Public License (GPL) version 2 */ #ifndef _LINUX_CAIF_SOCKET_H #define _LINUX_CAIF_SOCKET_H #include #include /** * enum caif_link_selector - Physical Link Selection. * @CAIF_LINK_HIGH_BANDW: Physical interface for high-bandwidth * traffic. * @CAIF_LINK_LOW_LATENCY: Physical interface for low-latency * traffic. * * CAIF Link Layers can register their link properties. * This enum is used for choosing between CAIF Link Layers when * setting up CAIF Channels when multiple CAIF Link Layers exists. */ enum caif_link_selector { CAIF_LINK_HIGH_BANDW, CAIF_LINK_LOW_LATENCY }; /** * enum caif_channel_priority - CAIF channel priorities. * * @CAIF_PRIO_MIN: Min priority for a channel. * @CAIF_PRIO_LOW: Low-priority channel. * @CAIF_PRIO_NORMAL: Normal/default priority level. * @CAIF_PRIO_HIGH: High priority level * @CAIF_PRIO_MAX: Max priority for channel * * Priority can be set on CAIF Channels in order to * prioritize between traffic on different CAIF Channels. * These priority levels are recommended, but the priority value * is not restricted to the values defined in this enum, any value * between CAIF_PRIO_MIN and CAIF_PRIO_MAX could be used. */ enum caif_channel_priority { CAIF_PRIO_MIN = 0x01, CAIF_PRIO_LOW = 0x04, CAIF_PRIO_NORMAL = 0x0f, CAIF_PRIO_HIGH = 0x14, CAIF_PRIO_MAX = 0x1F }; /** * enum caif_protocol_type - CAIF Channel type. * @CAIFPROTO_AT: Classic AT channel. * @CAIFPROTO_DATAGRAM: Datagram channel. * @CAIFPROTO_DATAGRAM_LOOP: Datagram loopback channel, used for testing. * @CAIFPROTO_UTIL: Utility (Psock) channel. * @CAIFPROTO_RFM: Remote File Manager * @CAIFPROTO_DEBUG: Debug link * * This enum defines the CAIF Channel type to be used. This defines * the service to connect to on the modem. */ enum caif_protocol_type { CAIFPROTO_AT, CAIFPROTO_DATAGRAM, CAIFPROTO_DATAGRAM_LOOP, CAIFPROTO_UTIL, CAIFPROTO_RFM, CAIFPROTO_DEBUG, _CAIFPROTO_MAX }; #define CAIFPROTO_MAX _CAIFPROTO_MAX /** * enum caif_at_type - AT Service Endpoint * @CAIF_ATTYPE_PLAIN: Connects to a plain vanilla AT channel. */ enum caif_at_type { CAIF_ATTYPE_PLAIN = 2 }; /** * enum caif_debug_type - Content selection for debug connection * @CAIF_DEBUG_TRACE_INTERACTIVE: Connection will contain * both trace and interactive debug. * @CAIF_DEBUG_TRACE: Connection contains trace only. * @CAIF_DEBUG_INTERACTIVE: Connection to interactive debug. */ enum caif_debug_type { CAIF_DEBUG_TRACE_INTERACTIVE = 0, CAIF_DEBUG_TRACE, CAIF_DEBUG_INTERACTIVE, }; /** * enum caif_debug_service - Debug Service Endpoint * @CAIF_RADIO_DEBUG_SERVICE: Debug service on the Radio sub-system * @CAIF_APP_DEBUG_SERVICE: Debug for the applications sub-system */ enum caif_debug_service { CAIF_RADIO_DEBUG_SERVICE = 1, CAIF_APP_DEBUG_SERVICE }; /** * struct sockaddr_caif - the sockaddr structure for CAIF sockets. * @family: Address family number, must be AF_CAIF. * @u: Union of address data 'switched' by family. * : * @u.at: Applies when family = CAIFPROTO_AT. * * @u.at.type: Type of AT link to set up (enum caif_at_type). * * @u.util: Applies when family = CAIFPROTO_UTIL * * @u.util.service: Utility service name. * * @u.dgm: Applies when family = CAIFPROTO_DATAGRAM * * @u.dgm.connection_id: Datagram connection id. * * @u.dgm.nsapi: NSAPI of the PDP-Context. * * @u.rfm: Applies when family = CAIFPROTO_RFM * * @u.rfm.connection_id: Connection ID for RFM. * * @u.rfm.volume: Volume to mount. * * @u.dbg: Applies when family = CAIFPROTO_DEBUG. * * @u.dbg.type: Type of debug connection to set up * (caif_debug_type). * * @u.dbg.service: Service sub-system to connect (caif_debug_service * Description: * This structure holds the connect parameters used for setting up a * CAIF Channel. It defines the service to connect to on the modem. */ struct sockaddr_caif { __kernel_sa_family_t family; union { struct { __u8 type; /* type: enum caif_at_type */ } at; /* CAIFPROTO_AT */ struct { char service[16]; } util; /* CAIFPROTO_UTIL */ union { __u32 connection_id; __u8 nsapi; } dgm; /* CAIFPROTO_DATAGRAM(_LOOP)*/ struct { __u32 connection_id; char volume[16]; } rfm; /* CAIFPROTO_RFM */ struct { __u8 type; /* type:enum caif_debug_type */ __u8 service; /* service:caif_debug_service */ } dbg; /* CAIFPROTO_DEBUG */ } u; }; /** * enum caif_socket_opts - CAIF option values for getsockopt and setsockopt. * * @CAIFSO_LINK_SELECT: Selector used if multiple CAIF Link layers are * available. Either a high bandwidth * link can be selected (CAIF_LINK_HIGH_BANDW) or * or a low latency link (CAIF_LINK_LOW_LATENCY). * This option is of type __u32. * Alternatively SO_BINDTODEVICE can be used. * * @CAIFSO_REQ_PARAM: Used to set the request parameters for a * utility channel. (maximum 256 bytes). This * option must be set before connecting. * * @CAIFSO_RSP_PARAM: Gets the response parameters for a utility * channel. (maximum 256 bytes). This option * is valid after a successful connect. * * * This enum defines the CAIF Socket options to be used on a socket * of type PF_CAIF. * */ enum caif_socket_opts { CAIFSO_LINK_SELECT = 127, CAIFSO_REQ_PARAM = 128, CAIFSO_RSP_PARAM = 129, }; #endif /* _LINUX_CAIF_SOCKET_H */ linux/caif/if_caif.h000064400000002021151027430560010334 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) ST-Ericsson AB 2010 * Author: Sjur Brendeland * License terms: GNU General Public License (GPL) version 2 */ #ifndef IF_CAIF_H_ #define IF_CAIF_H_ #include #include #include /** * enum ifla_caif - CAIF NetlinkRT parameters. * @IFLA_CAIF_IPV4_CONNID: Connection ID for IPv4 PDP Context. * The type of attribute is NLA_U32. * @IFLA_CAIF_IPV6_CONNID: Connection ID for IPv6 PDP Context. * The type of attribute is NLA_U32. * @IFLA_CAIF_LOOPBACK: If different from zero, device is doing loopback * The type of attribute is NLA_U8. * * When using RT Netlink to create, destroy or configure a CAIF IP interface, * enum ifla_caif is used to specify the configuration attributes. */ enum ifla_caif { __IFLA_CAIF_UNSPEC, IFLA_CAIF_IPV4_CONNID, IFLA_CAIF_IPV6_CONNID, IFLA_CAIF_LOOPBACK, __IFLA_CAIF_MAX }; #define IFLA_CAIF_MAX (__IFLA_CAIF_MAX-1) #endif /*IF_CAIF_H_*/ linux/batadv_packet.h000064400000050017151027430560010652 0ustar00/* SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) */ /* Copyright (C) 2007-2018 B.A.T.M.A.N. contributors: * * Marek Lindner, Simon Wunderlich * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #ifndef _LINUX_BATADV_PACKET_H_ #define _LINUX_BATADV_PACKET_H_ #include #include #include /** * batadv_tp_is_error() - Check throughput meter return code for error * @n: throughput meter return code * * Return: 0 when not error was detected, != 0 otherwise */ #define batadv_tp_is_error(n) ((__u8)(n) > 127 ? 1 : 0) /** * enum batadv_packettype - types for batman-adv encapsulated packets * @BATADV_IV_OGM: originator messages for B.A.T.M.A.N. IV * @BATADV_BCAST: broadcast packets carrying broadcast payload * @BATADV_CODED: network coded packets * @BATADV_ELP: echo location packets for B.A.T.M.A.N. V * @BATADV_OGM2: originator messages for B.A.T.M.A.N. V * * @BATADV_UNICAST: unicast packets carrying unicast payload traffic * @BATADV_UNICAST_FRAG: unicast packets carrying a fragment of the original * payload packet * @BATADV_UNICAST_4ADDR: unicast packet including the originator address of * the sender * @BATADV_ICMP: unicast packet like IP ICMP used for ping or traceroute * @BATADV_UNICAST_TVLV: unicast packet carrying TVLV containers */ enum batadv_packettype { /* 0x00 - 0x3f: local packets or special rules for handling */ BATADV_IV_OGM = 0x00, BATADV_BCAST = 0x01, BATADV_CODED = 0x02, BATADV_ELP = 0x03, BATADV_OGM2 = 0x04, /* 0x40 - 0x7f: unicast */ #define BATADV_UNICAST_MIN 0x40 BATADV_UNICAST = 0x40, BATADV_UNICAST_FRAG = 0x41, BATADV_UNICAST_4ADDR = 0x42, BATADV_ICMP = 0x43, BATADV_UNICAST_TVLV = 0x44, #define BATADV_UNICAST_MAX 0x7f /* 0x80 - 0xff: reserved */ }; /** * enum batadv_subtype - packet subtype for unicast4addr * @BATADV_P_DATA: user payload * @BATADV_P_DAT_DHT_GET: DHT request message * @BATADV_P_DAT_DHT_PUT: DHT store message * @BATADV_P_DAT_CACHE_REPLY: ARP reply generated by DAT */ enum batadv_subtype { BATADV_P_DATA = 0x01, BATADV_P_DAT_DHT_GET = 0x02, BATADV_P_DAT_DHT_PUT = 0x03, BATADV_P_DAT_CACHE_REPLY = 0x04, }; /* this file is included by batctl which needs these defines */ #define BATADV_COMPAT_VERSION 15 /** * enum batadv_iv_flags - flags used in B.A.T.M.A.N. IV OGM packets * @BATADV_NOT_BEST_NEXT_HOP: flag is set when ogm packet is forwarded and was * previously received from someone else than the best neighbor. * @BATADV_PRIMARIES_FIRST_HOP: flag unused. * @BATADV_DIRECTLINK: flag is for the first hop or if rebroadcasted from a * one hop neighbor on the interface where it was originally received. */ enum batadv_iv_flags { BATADV_NOT_BEST_NEXT_HOP = 1UL << 0, BATADV_PRIMARIES_FIRST_HOP = 1UL << 1, BATADV_DIRECTLINK = 1UL << 2, }; /** * enum batadv_icmp_packettype - ICMP message types * @BATADV_ECHO_REPLY: success reply to BATADV_ECHO_REQUEST * @BATADV_DESTINATION_UNREACHABLE: failure when route to destination not found * @BATADV_ECHO_REQUEST: request BATADV_ECHO_REPLY from destination * @BATADV_TTL_EXCEEDED: error after BATADV_ECHO_REQUEST traversed too many hops * @BATADV_PARAMETER_PROBLEM: return code for malformed messages * @BATADV_TP: throughput meter packet */ enum batadv_icmp_packettype { BATADV_ECHO_REPLY = 0, BATADV_DESTINATION_UNREACHABLE = 3, BATADV_ECHO_REQUEST = 8, BATADV_TTL_EXCEEDED = 11, BATADV_PARAMETER_PROBLEM = 12, BATADV_TP = 15, }; /** * enum batadv_mcast_flags - flags for multicast capabilities and settings * @BATADV_MCAST_WANT_ALL_UNSNOOPABLES: we want all packets destined for * 224.0.0.0/24 or ff02::1 * @BATADV_MCAST_WANT_ALL_IPV4: we want all IPv4 multicast packets * @BATADV_MCAST_WANT_ALL_IPV6: we want all IPv6 multicast packets */ enum batadv_mcast_flags { BATADV_MCAST_WANT_ALL_UNSNOOPABLES = 1UL << 0, BATADV_MCAST_WANT_ALL_IPV4 = 1UL << 1, BATADV_MCAST_WANT_ALL_IPV6 = 1UL << 2, }; /* tt data subtypes */ #define BATADV_TT_DATA_TYPE_MASK 0x0F /** * enum batadv_tt_data_flags - flags for tt data tvlv * @BATADV_TT_OGM_DIFF: TT diff propagated through OGM * @BATADV_TT_REQUEST: TT request message * @BATADV_TT_RESPONSE: TT response message * @BATADV_TT_FULL_TABLE: contains full table to replace existing table */ enum batadv_tt_data_flags { BATADV_TT_OGM_DIFF = 1UL << 0, BATADV_TT_REQUEST = 1UL << 1, BATADV_TT_RESPONSE = 1UL << 2, BATADV_TT_FULL_TABLE = 1UL << 4, }; /** * enum batadv_vlan_flags - flags for the four MSB of any vlan ID field * @BATADV_VLAN_HAS_TAG: whether the field contains a valid vlan tag or not */ enum batadv_vlan_flags { BATADV_VLAN_HAS_TAG = 1UL << 15, }; /** * enum batadv_bla_claimframe - claim frame types for the bridge loop avoidance * @BATADV_CLAIM_TYPE_CLAIM: claim of a client mac address * @BATADV_CLAIM_TYPE_UNCLAIM: unclaim of a client mac address * @BATADV_CLAIM_TYPE_ANNOUNCE: announcement of backbone with current crc * @BATADV_CLAIM_TYPE_REQUEST: request of full claim table * @BATADV_CLAIM_TYPE_LOOPDETECT: mesh-traversing loop detect packet */ enum batadv_bla_claimframe { BATADV_CLAIM_TYPE_CLAIM = 0x00, BATADV_CLAIM_TYPE_UNCLAIM = 0x01, BATADV_CLAIM_TYPE_ANNOUNCE = 0x02, BATADV_CLAIM_TYPE_REQUEST = 0x03, BATADV_CLAIM_TYPE_LOOPDETECT = 0x04, }; /** * enum batadv_tvlv_type - tvlv type definitions * @BATADV_TVLV_GW: gateway tvlv * @BATADV_TVLV_DAT: distributed arp table tvlv * @BATADV_TVLV_NC: network coding tvlv * @BATADV_TVLV_TT: translation table tvlv * @BATADV_TVLV_ROAM: roaming advertisement tvlv * @BATADV_TVLV_MCAST: multicast capability tvlv */ enum batadv_tvlv_type { BATADV_TVLV_GW = 0x01, BATADV_TVLV_DAT = 0x02, BATADV_TVLV_NC = 0x03, BATADV_TVLV_TT = 0x04, BATADV_TVLV_ROAM = 0x05, BATADV_TVLV_MCAST = 0x06, }; #pragma pack(2) /* the destination hardware field in the ARP frame is used to * transport the claim type and the group id */ struct batadv_bla_claim_dst { __u8 magic[3]; /* FF:43:05 */ __u8 type; /* bla_claimframe */ __be16 group; /* group id */ }; /** * struct batadv_ogm_packet - ogm (routing protocol) packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @flags: contains routing relevant flags - see enum batadv_iv_flags * @seqno: sequence identification * @orig: address of the source node * @prev_sender: address of the previous sender * @reserved: reserved byte for alignment * @tq: transmission quality * @tvlv_len: length of tvlv data following the ogm header */ struct batadv_ogm_packet { __u8 packet_type; __u8 version; __u8 ttl; __u8 flags; __be32 seqno; __u8 orig[ETH_ALEN]; __u8 prev_sender[ETH_ALEN]; __u8 reserved; __u8 tq; __be16 tvlv_len; }; #define BATADV_OGM_HLEN sizeof(struct batadv_ogm_packet) /** * struct batadv_ogm2_packet - ogm2 (routing protocol) packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the general header * @ttl: time to live for this packet, part of the general header * @flags: reseved for routing relevant flags - currently always 0 * @seqno: sequence number * @orig: originator mac address * @tvlv_len: length of the appended tvlv buffer (in bytes) * @throughput: the currently flooded path throughput */ struct batadv_ogm2_packet { __u8 packet_type; __u8 version; __u8 ttl; __u8 flags; __be32 seqno; __u8 orig[ETH_ALEN]; __be16 tvlv_len; __be32 throughput; }; #define BATADV_OGM2_HLEN sizeof(struct batadv_ogm2_packet) /** * struct batadv_elp_packet - elp (neighbor discovery) packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @orig: originator mac address * @seqno: sequence number * @elp_interval: currently used ELP sending interval in ms */ struct batadv_elp_packet { __u8 packet_type; __u8 version; __u8 orig[ETH_ALEN]; __be32 seqno; __be32 elp_interval; }; #define BATADV_ELP_HLEN sizeof(struct batadv_elp_packet) /** * struct batadv_icmp_header - common members among all the ICMP packets * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @msg_type: ICMP packet type * @dst: address of the destination node * @orig: address of the source node * @uid: local ICMP socket identifier * @align: not used - useful for alignment purposes only * * This structure is used for ICMP packets parsing only and it is never sent * over the wire. The alignment field at the end is there to ensure that * members are padded the same way as they are in real packets. */ struct batadv_icmp_header { __u8 packet_type; __u8 version; __u8 ttl; __u8 msg_type; /* see ICMP message types above */ __u8 dst[ETH_ALEN]; __u8 orig[ETH_ALEN]; __u8 uid; __u8 align[3]; }; /** * struct batadv_icmp_packet - ICMP packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @msg_type: ICMP packet type * @dst: address of the destination node * @orig: address of the source node * @uid: local ICMP socket identifier * @reserved: not used - useful for alignment * @seqno: ICMP sequence number */ struct batadv_icmp_packet { __u8 packet_type; __u8 version; __u8 ttl; __u8 msg_type; /* see ICMP message types above */ __u8 dst[ETH_ALEN]; __u8 orig[ETH_ALEN]; __u8 uid; __u8 reserved; __be16 seqno; }; /** * struct batadv_icmp_tp_packet - ICMP TP Meter packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @msg_type: ICMP packet type * @dst: address of the destination node * @orig: address of the source node * @uid: local ICMP socket identifier * @subtype: TP packet subtype (see batadv_icmp_tp_subtype) * @session: TP session identifier * @seqno: the TP sequence number * @timestamp: time when the packet has been sent. This value is filled in a * TP_MSG and echoed back in the next TP_ACK so that the sender can compute the * RTT. Since it is read only by the host which wrote it, there is no need to * store it using network order */ struct batadv_icmp_tp_packet { __u8 packet_type; __u8 version; __u8 ttl; __u8 msg_type; /* see ICMP message types above */ __u8 dst[ETH_ALEN]; __u8 orig[ETH_ALEN]; __u8 uid; __u8 subtype; __u8 session[2]; __be32 seqno; __be32 timestamp; }; /** * enum batadv_icmp_tp_subtype - ICMP TP Meter packet subtypes * @BATADV_TP_MSG: Msg from sender to receiver * @BATADV_TP_ACK: acknowledgment from receiver to sender */ enum batadv_icmp_tp_subtype { BATADV_TP_MSG = 0, BATADV_TP_ACK, }; #define BATADV_RR_LEN 16 /** * struct batadv_icmp_packet_rr - ICMP RouteRecord packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @msg_type: ICMP packet type * @dst: address of the destination node * @orig: address of the source node * @uid: local ICMP socket identifier * @rr_cur: number of entries the rr array * @seqno: ICMP sequence number * @rr: route record array */ struct batadv_icmp_packet_rr { __u8 packet_type; __u8 version; __u8 ttl; __u8 msg_type; /* see ICMP message types above */ __u8 dst[ETH_ALEN]; __u8 orig[ETH_ALEN]; __u8 uid; __u8 rr_cur; __be16 seqno; __u8 rr[BATADV_RR_LEN][ETH_ALEN]; }; #define BATADV_ICMP_MAX_PACKET_SIZE sizeof(struct batadv_icmp_packet_rr) /* All packet headers in front of an ethernet header have to be completely * divisible by 2 but not by 4 to make the payload after the ethernet * header again 4 bytes boundary aligned. * * A packing of 2 is necessary to avoid extra padding at the end of the struct * caused by a structure member which is larger than two bytes. Otherwise * the structure would not fulfill the previously mentioned rule to avoid the * misalignment of the payload after the ethernet header. It may also lead to * leakage of information when the padding it not initialized before sending. */ /** * struct batadv_unicast_packet - unicast packet for network payload * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @ttvn: translation table version number * @dest: originator destination of the unicast packet */ struct batadv_unicast_packet { __u8 packet_type; __u8 version; __u8 ttl; __u8 ttvn; /* destination translation table version number */ __u8 dest[ETH_ALEN]; /* "4 bytes boundary + 2 bytes" long to make the payload after the * following ethernet header again 4 bytes boundary aligned */ }; /** * struct batadv_unicast_4addr_packet - extended unicast packet * @u: common unicast packet header * @src: address of the source * @subtype: packet subtype * @reserved: reserved byte for alignment */ struct batadv_unicast_4addr_packet { struct batadv_unicast_packet u; __u8 src[ETH_ALEN]; __u8 subtype; __u8 reserved; /* "4 bytes boundary + 2 bytes" long to make the payload after the * following ethernet header again 4 bytes boundary aligned */ }; /** * struct batadv_frag_packet - fragmented packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @dest: final destination used when routing fragments * @orig: originator of the fragment used when merging the packet * @no: fragment number within this sequence * @priority: priority of frame, from ToS IP precedence or 802.1p * @reserved: reserved byte for alignment * @seqno: sequence identification * @total_size: size of the merged packet */ struct batadv_frag_packet { __u8 packet_type; __u8 version; /* batman version field */ __u8 ttl; #if defined(__BIG_ENDIAN_BITFIELD) __u8 no:4; __u8 priority:3; __u8 reserved:1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 reserved:1; __u8 priority:3; __u8 no:4; #else #error "unknown bitfield endianness" #endif __u8 dest[ETH_ALEN]; __u8 orig[ETH_ALEN]; __be16 seqno; __be16 total_size; }; /** * struct batadv_bcast_packet - broadcast packet for network payload * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @reserved: reserved byte for alignment * @seqno: sequence identification * @orig: originator of the broadcast packet */ struct batadv_bcast_packet { __u8 packet_type; __u8 version; /* batman version field */ __u8 ttl; __u8 reserved; __be32 seqno; __u8 orig[ETH_ALEN]; /* "4 bytes boundary + 2 bytes" long to make the payload after the * following ethernet header again 4 bytes boundary aligned */ }; /** * struct batadv_coded_packet - network coded packet * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @first_source: original source of first included packet * @first_orig_dest: original destinal of first included packet * @first_crc: checksum of first included packet * @first_ttvn: tt-version number of first included packet * @second_ttl: ttl of second packet * @second_dest: second receiver of this coded packet * @second_source: original source of second included packet * @second_orig_dest: original destination of second included packet * @second_crc: checksum of second included packet * @second_ttvn: tt version number of second included packet * @coded_len: length of network coded part of the payload */ struct batadv_coded_packet { __u8 packet_type; __u8 version; /* batman version field */ __u8 ttl; __u8 first_ttvn; /* __u8 first_dest[ETH_ALEN]; - saved in mac header destination */ __u8 first_source[ETH_ALEN]; __u8 first_orig_dest[ETH_ALEN]; __be32 first_crc; __u8 second_ttl; __u8 second_ttvn; __u8 second_dest[ETH_ALEN]; __u8 second_source[ETH_ALEN]; __u8 second_orig_dest[ETH_ALEN]; __be32 second_crc; __be16 coded_len; }; /** * struct batadv_unicast_tvlv_packet - generic unicast packet with tvlv payload * @packet_type: batman-adv packet type, part of the general header * @version: batman-adv protocol version, part of the genereal header * @ttl: time to live for this packet, part of the genereal header * @reserved: reserved field (for packet alignment) * @src: address of the source * @dst: address of the destination * @tvlv_len: length of tvlv data following the unicast tvlv header * @align: 2 bytes to align the header to a 4 byte boundary */ struct batadv_unicast_tvlv_packet { __u8 packet_type; __u8 version; /* batman version field */ __u8 ttl; __u8 reserved; __u8 dst[ETH_ALEN]; __u8 src[ETH_ALEN]; __be16 tvlv_len; __u16 align; }; /** * struct batadv_tvlv_hdr - base tvlv header struct * @type: tvlv container type (see batadv_tvlv_type) * @version: tvlv container version * @len: tvlv container length */ struct batadv_tvlv_hdr { __u8 type; __u8 version; __be16 len; }; /** * struct batadv_tvlv_gateway_data - gateway data propagated through gw tvlv * container * @bandwidth_down: advertised uplink download bandwidth * @bandwidth_up: advertised uplink upload bandwidth */ struct batadv_tvlv_gateway_data { __be32 bandwidth_down; __be32 bandwidth_up; }; /** * struct batadv_tvlv_tt_data - tt data propagated through the tt tvlv container * @flags: translation table flags (see batadv_tt_data_flags) * @ttvn: translation table version number * @num_vlan: number of announced VLANs. In the TVLV this struct is followed by * one batadv_tvlv_tt_vlan_data object per announced vlan */ struct batadv_tvlv_tt_data { __u8 flags; __u8 ttvn; __be16 num_vlan; }; /** * struct batadv_tvlv_tt_vlan_data - vlan specific tt data propagated through * the tt tvlv container * @crc: crc32 checksum of the entries belonging to this vlan * @vid: vlan identifier * @reserved: unused, useful for alignment purposes */ struct batadv_tvlv_tt_vlan_data { __be32 crc; __be16 vid; __u16 reserved; }; /** * struct batadv_tvlv_tt_change - translation table diff data * @flags: status indicators concerning the non-mesh client (see * batadv_tt_client_flags) * @reserved: reserved field - useful for alignment purposes only * @addr: mac address of non-mesh client that triggered this tt change * @vid: VLAN identifier */ struct batadv_tvlv_tt_change { __u8 flags; __u8 reserved[3]; __u8 addr[ETH_ALEN]; __be16 vid; }; /** * struct batadv_tvlv_roam_adv - roaming advertisement * @client: mac address of roaming client * @vid: VLAN identifier */ struct batadv_tvlv_roam_adv { __u8 client[ETH_ALEN]; __be16 vid; }; /** * struct batadv_tvlv_mcast_data - payload of a multicast tvlv * @flags: multicast flags announced by the orig node * @reserved: reserved field */ struct batadv_tvlv_mcast_data { __u8 flags; __u8 reserved[3]; }; #pragma pack() #endif /* _LINUX_BATADV_PACKET_H_ */ linux/virtio_mmio.h000064400000011551151027430560010417 0ustar00/* * Virtio platform device driver * * Copyright 2011, ARM Ltd. * * Based on Virtio PCI driver by Anthony Liguori, copyright IBM Corp. 2007 * * This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _LINUX_VIRTIO_MMIO_H #define _LINUX_VIRTIO_MMIO_H /* * Control registers */ /* Magic value ("virt" string) - Read Only */ #define VIRTIO_MMIO_MAGIC_VALUE 0x000 /* Virtio device version - Read Only */ #define VIRTIO_MMIO_VERSION 0x004 /* Virtio device ID - Read Only */ #define VIRTIO_MMIO_DEVICE_ID 0x008 /* Virtio vendor ID - Read Only */ #define VIRTIO_MMIO_VENDOR_ID 0x00c /* Bitmask of the features supported by the device (host) * (32 bits per set) - Read Only */ #define VIRTIO_MMIO_DEVICE_FEATURES 0x010 /* Device (host) features set selector - Write Only */ #define VIRTIO_MMIO_DEVICE_FEATURES_SEL 0x014 /* Bitmask of features activated by the driver (guest) * (32 bits per set) - Write Only */ #define VIRTIO_MMIO_DRIVER_FEATURES 0x020 /* Activated features set selector - Write Only */ #define VIRTIO_MMIO_DRIVER_FEATURES_SEL 0x024 #ifndef VIRTIO_MMIO_NO_LEGACY /* LEGACY DEVICES ONLY! */ /* Guest's memory page size in bytes - Write Only */ #define VIRTIO_MMIO_GUEST_PAGE_SIZE 0x028 #endif /* Queue selector - Write Only */ #define VIRTIO_MMIO_QUEUE_SEL 0x030 /* Maximum size of the currently selected queue - Read Only */ #define VIRTIO_MMIO_QUEUE_NUM_MAX 0x034 /* Queue size for the currently selected queue - Write Only */ #define VIRTIO_MMIO_QUEUE_NUM 0x038 #ifndef VIRTIO_MMIO_NO_LEGACY /* LEGACY DEVICES ONLY! */ /* Used Ring alignment for the currently selected queue - Write Only */ #define VIRTIO_MMIO_QUEUE_ALIGN 0x03c /* Guest's PFN for the currently selected queue - Read Write */ #define VIRTIO_MMIO_QUEUE_PFN 0x040 #endif /* Ready bit for the currently selected queue - Read Write */ #define VIRTIO_MMIO_QUEUE_READY 0x044 /* Queue notifier - Write Only */ #define VIRTIO_MMIO_QUEUE_NOTIFY 0x050 /* Interrupt status - Read Only */ #define VIRTIO_MMIO_INTERRUPT_STATUS 0x060 /* Interrupt acknowledge - Write Only */ #define VIRTIO_MMIO_INTERRUPT_ACK 0x064 /* Device status register - Read Write */ #define VIRTIO_MMIO_STATUS 0x070 /* Selected queue's Descriptor Table address, 64 bits in two halves */ #define VIRTIO_MMIO_QUEUE_DESC_LOW 0x080 #define VIRTIO_MMIO_QUEUE_DESC_HIGH 0x084 /* Selected queue's Available Ring address, 64 bits in two halves */ #define VIRTIO_MMIO_QUEUE_AVAIL_LOW 0x090 #define VIRTIO_MMIO_QUEUE_AVAIL_HIGH 0x094 /* Selected queue's Used Ring address, 64 bits in two halves */ #define VIRTIO_MMIO_QUEUE_USED_LOW 0x0a0 #define VIRTIO_MMIO_QUEUE_USED_HIGH 0x0a4 /* Shared memory region id */ #define VIRTIO_MMIO_SHM_SEL 0x0ac /* Shared memory region length, 64 bits in two halves */ #define VIRTIO_MMIO_SHM_LEN_LOW 0x0b0 #define VIRTIO_MMIO_SHM_LEN_HIGH 0x0b4 /* Shared memory region base address, 64 bits in two halves */ #define VIRTIO_MMIO_SHM_BASE_LOW 0x0b8 #define VIRTIO_MMIO_SHM_BASE_HIGH 0x0bc /* Configuration atomicity value */ #define VIRTIO_MMIO_CONFIG_GENERATION 0x0fc /* The config space is defined by each driver as * the per-driver configuration space - Read Write */ #define VIRTIO_MMIO_CONFIG 0x100 /* * Interrupt flags (re: interrupt status & acknowledge registers) */ #define VIRTIO_MMIO_INT_VRING (1 << 0) #define VIRTIO_MMIO_INT_CONFIG (1 << 1) #endif linux/gtp.h000064400000001251151027430560006650 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_GTP_H_ #define _LINUX_GTP_H_ enum gtp_genl_cmds { GTP_CMD_NEWPDP, GTP_CMD_DELPDP, GTP_CMD_GETPDP, GTP_CMD_MAX, }; enum gtp_version { GTP_V0 = 0, GTP_V1, }; enum gtp_attrs { GTPA_UNSPEC = 0, GTPA_LINK, GTPA_VERSION, GTPA_TID, /* for GTPv0 only */ GTPA_PEER_ADDRESS, /* Remote GSN peer, either SGSN or GGSN */ #define GTPA_SGSN_ADDRESS GTPA_PEER_ADDRESS /* maintain legacy attr name */ GTPA_MS_ADDRESS, GTPA_FLOW, GTPA_NET_NS_FD, GTPA_I_TEI, /* for GTPv1 only */ GTPA_O_TEI, /* for GTPv1 only */ GTPA_PAD, __GTPA_MAX, }; #define GTPA_MAX (__GTPA_MAX + 1) #endif /* _LINUX_GTP_H_ */ linux/atm.h000064400000017320151027430560006643 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm.h - general ATM declarations */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ /* * WARNING: User-space programs should not #include directly. * Instead, #include */ #ifndef _LINUX_ATM_H #define _LINUX_ATM_H /* * BEGIN_xx and END_xx markers are used for automatic generation of * documentation. Do not change them. */ #include #include #include #include /* general ATM constants */ #define ATM_CELL_SIZE 53 /* ATM cell size incl. header */ #define ATM_CELL_PAYLOAD 48 /* ATM payload size */ #define ATM_AAL0_SDU 52 /* AAL0 SDU size */ #define ATM_MAX_AAL34_PDU 65535 /* maximum AAL3/4 PDU payload */ #define ATM_AAL5_TRAILER 8 /* AAL5 trailer size */ #define ATM_MAX_AAL5_PDU 65535 /* maximum AAL5 PDU payload */ #define ATM_MAX_CDV 9999 /* maximum (default) CDV */ #define ATM_NOT_RSV_VCI 32 /* first non-reserved VCI value */ #define ATM_MAX_VPI 255 /* maximum VPI at the UNI */ #define ATM_MAX_VPI_NNI 4096 /* maximum VPI at the NNI */ #define ATM_MAX_VCI 65535 /* maximum VCI */ /* "protcol" values for the socket system call */ #define ATM_NO_AAL 0 /* AAL not specified */ #define ATM_AAL0 13 /* "raw" ATM cells */ #define ATM_AAL1 1 /* AAL1 (CBR) */ #define ATM_AAL2 2 /* AAL2 (VBR) */ #define ATM_AAL34 3 /* AAL3/4 (data) */ #define ATM_AAL5 5 /* AAL5 (data) */ /* * socket option name coding functions * * Note that __SO_ENCODE and __SO_LEVEL are somewhat a hack since the * << 22 only reserves 9 bits for the level. On some architectures * SOL_SOCKET is 0xFFFF, so that's a bit of a problem */ #define __SO_ENCODE(l,n,t) ((((l) & 0x1FF) << 22) | ((n) << 16) | \ sizeof(t)) #define __SO_LEVEL_MATCH(c,m) (((c) >> 22) == ((m) & 0x1FF)) #define __SO_NUMBER(c) (((c) >> 16) & 0x3f) #define __SO_SIZE(c) ((c) & 0x3fff) /* * ATM layer */ #define SO_SETCLP __SO_ENCODE(SOL_ATM,0,int) /* set CLP bit value - TODO */ #define SO_CIRANGE __SO_ENCODE(SOL_ATM,1,struct atm_cirange) /* connection identifier range; socket must be bound or connected */ #define SO_ATMQOS __SO_ENCODE(SOL_ATM,2,struct atm_qos) /* Quality of Service setting */ #define SO_ATMSAP __SO_ENCODE(SOL_ATM,3,struct atm_sap) /* Service Access Point */ #define SO_ATMPVC __SO_ENCODE(SOL_ATM,4,struct sockaddr_atmpvc) /* "PVC" address (also for SVCs); get only */ #define SO_MULTIPOINT __SO_ENCODE(SOL_ATM, 5, int) /* make this vc a p2mp */ /* * Note @@@: since the socket layers don't really distinguish the control and * the data plane but generally seems to be data plane-centric, any layer is * about equally wrong for the SAP. If you have a better idea about this, * please speak up ... */ /* ATM cell header (for AAL0) */ /* BEGIN_CH */ #define ATM_HDR_GFC_MASK 0xf0000000 #define ATM_HDR_GFC_SHIFT 28 #define ATM_HDR_VPI_MASK 0x0ff00000 #define ATM_HDR_VPI_SHIFT 20 #define ATM_HDR_VCI_MASK 0x000ffff0 #define ATM_HDR_VCI_SHIFT 4 #define ATM_HDR_PTI_MASK 0x0000000e #define ATM_HDR_PTI_SHIFT 1 #define ATM_HDR_CLP 0x00000001 /* END_CH */ /* PTI codings */ /* BEGIN_PTI */ #define ATM_PTI_US0 0 /* user data cell, congestion not exp, SDU-type 0 */ #define ATM_PTI_US1 1 /* user data cell, congestion not exp, SDU-type 1 */ #define ATM_PTI_UCES0 2 /* user data cell, cong. experienced, SDU-type 0 */ #define ATM_PTI_UCES1 3 /* user data cell, cong. experienced, SDU-type 1 */ #define ATM_PTI_SEGF5 4 /* segment OAM F5 flow related cell */ #define ATM_PTI_E2EF5 5 /* end-to-end OAM F5 flow related cell */ #define ATM_PTI_RSV_RM 6 /* reserved for traffic control/resource mgmt */ #define ATM_PTI_RSV 7 /* reserved */ /* END_PTI */ /* * The following items should stay in linux/atm.h, which should be linked to * netatm/atm.h */ /* Traffic description */ #define ATM_NONE 0 /* no traffic */ #define ATM_UBR 1 #define ATM_CBR 2 #define ATM_VBR 3 #define ATM_ABR 4 #define ATM_ANYCLASS 5 /* compatible with everything */ #define ATM_MAX_PCR -1 /* maximum available PCR */ struct atm_trafprm { unsigned char traffic_class; /* traffic class (ATM_UBR, ...) */ int max_pcr; /* maximum PCR in cells per second */ int pcr; /* desired PCR in cells per second */ int min_pcr; /* minimum PCR in cells per second */ int max_cdv; /* maximum CDV in microseconds */ int max_sdu; /* maximum SDU in bytes */ /* extra params for ABR */ unsigned int icr; /* Initial Cell Rate (24-bit) */ unsigned int tbe; /* Transient Buffer Exposure (24-bit) */ unsigned int frtt : 24; /* Fixed Round Trip Time (24-bit) */ unsigned int rif : 4; /* Rate Increment Factor (4-bit) */ unsigned int rdf : 4; /* Rate Decrease Factor (4-bit) */ unsigned int nrm_pres :1; /* nrm present bit */ unsigned int trm_pres :1; /* rm present bit */ unsigned int adtf_pres :1; /* adtf present bit */ unsigned int cdf_pres :1; /* cdf present bit*/ unsigned int nrm :3; /* Max # of Cells for each forward RM cell (3-bit) */ unsigned int trm :3; /* Time between forward RM cells (3-bit) */ unsigned int adtf :10; /* ACR Decrease Time Factor (10-bit) */ unsigned int cdf :3; /* Cutoff Decrease Factor (3-bit) */ unsigned int spare :9; /* spare bits */ }; struct atm_qos { struct atm_trafprm txtp; /* parameters in TX direction */ struct atm_trafprm rxtp __ATM_API_ALIGN; /* parameters in RX direction */ unsigned char aal __ATM_API_ALIGN; }; /* PVC addressing */ #define ATM_ITF_ANY -1 /* "magic" PVC address values */ #define ATM_VPI_ANY -1 #define ATM_VCI_ANY -1 #define ATM_VPI_UNSPEC -2 #define ATM_VCI_UNSPEC -2 struct sockaddr_atmpvc { unsigned short sap_family; /* address family, AF_ATMPVC */ struct { /* PVC address */ short itf; /* ATM interface */ short vpi; /* VPI (only 8 bits at UNI) */ int vci; /* VCI (only 16 bits at UNI) */ } sap_addr __ATM_API_ALIGN; /* PVC address */ }; /* SVC addressing */ #define ATM_ESA_LEN 20 /* ATM End System Address length */ #define ATM_E164_LEN 12 /* maximum E.164 number length */ #define ATM_AFI_DCC 0x39 /* DCC ATM Format */ #define ATM_AFI_ICD 0x47 /* ICD ATM Format */ #define ATM_AFI_E164 0x45 /* E.164 ATM Format */ #define ATM_AFI_LOCAL 0x49 /* Local ATM Format */ #define ATM_AFI_DCC_GROUP 0xBD /* DCC ATM Group Format */ #define ATM_AFI_ICD_GROUP 0xC5 /* ICD ATM Group Format */ #define ATM_AFI_E164_GROUP 0xC3 /* E.164 ATM Group Format */ #define ATM_AFI_LOCAL_GROUP 0xC7 /* Local ATM Group Format */ #define ATM_LIJ_NONE 0 /* no leaf-initiated join */ #define ATM_LIJ 1 /* request joining */ #define ATM_LIJ_RPJ 2 /* set to root-prompted join */ #define ATM_LIJ_NJ 3 /* set to network join */ struct sockaddr_atmsvc { unsigned short sas_family; /* address family, AF_ATMSVC */ struct { /* SVC address */ unsigned char prv[ATM_ESA_LEN];/* private ATM address */ char pub[ATM_E164_LEN+1]; /* public address (E.164) */ /* unused addresses must be bzero'ed */ char lij_type; /* role in LIJ call; one of ATM_LIJ* */ __u32 lij_id; /* LIJ call identifier */ } sas_addr __ATM_API_ALIGN; /* SVC address */ }; static __inline__ int atmsvc_addr_in_use(struct sockaddr_atmsvc addr) { return *addr.sas_addr.prv || *addr.sas_addr.pub; } static __inline__ int atmpvc_addr_in_use(struct sockaddr_atmpvc addr) { return addr.sap_addr.itf || addr.sap_addr.vpi || addr.sap_addr.vci; } /* * Some stuff for linux/sockios.h */ struct atmif_sioc { int number; int length; void *arg; }; typedef unsigned short atm_backend_t; #endif /* _LINUX_ATM_H */ linux/iso_fs.h000064400000014525151027430560007350 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ISOFS_FS_H #define _ISOFS_FS_H #include #include /* * The isofs filesystem constants/structures */ /* This part borrowed from the bsd386 isofs */ #define ISODCL(from, to) (to - from + 1) struct iso_volume_descriptor { __u8 type[ISODCL(1,1)]; /* 711 */ char id[ISODCL(2,6)]; __u8 version[ISODCL(7,7)]; __u8 data[ISODCL(8,2048)]; }; /* volume descriptor types */ #define ISO_VD_PRIMARY 1 #define ISO_VD_SUPPLEMENTARY 2 #define ISO_VD_END 255 #define ISO_STANDARD_ID "CD001" struct iso_primary_descriptor { __u8 type [ISODCL ( 1, 1)]; /* 711 */ char id [ISODCL ( 2, 6)]; __u8 version [ISODCL ( 7, 7)]; /* 711 */ __u8 unused1 [ISODCL ( 8, 8)]; char system_id [ISODCL ( 9, 40)]; /* achars */ char volume_id [ISODCL ( 41, 72)]; /* dchars */ __u8 unused2 [ISODCL ( 73, 80)]; __u8 volume_space_size [ISODCL ( 81, 88)]; /* 733 */ __u8 unused3 [ISODCL ( 89, 120)]; __u8 volume_set_size [ISODCL (121, 124)]; /* 723 */ __u8 volume_sequence_number [ISODCL (125, 128)]; /* 723 */ __u8 logical_block_size [ISODCL (129, 132)]; /* 723 */ __u8 path_table_size [ISODCL (133, 140)]; /* 733 */ __u8 type_l_path_table [ISODCL (141, 144)]; /* 731 */ __u8 opt_type_l_path_table [ISODCL (145, 148)]; /* 731 */ __u8 type_m_path_table [ISODCL (149, 152)]; /* 732 */ __u8 opt_type_m_path_table [ISODCL (153, 156)]; /* 732 */ __u8 root_directory_record [ISODCL (157, 190)]; /* 9.1 */ char volume_set_id [ISODCL (191, 318)]; /* dchars */ char publisher_id [ISODCL (319, 446)]; /* achars */ char preparer_id [ISODCL (447, 574)]; /* achars */ char application_id [ISODCL (575, 702)]; /* achars */ char copyright_file_id [ISODCL (703, 739)]; /* 7.5 dchars */ char abstract_file_id [ISODCL (740, 776)]; /* 7.5 dchars */ char bibliographic_file_id [ISODCL (777, 813)]; /* 7.5 dchars */ __u8 creation_date [ISODCL (814, 830)]; /* 8.4.26.1 */ __u8 modification_date [ISODCL (831, 847)]; /* 8.4.26.1 */ __u8 expiration_date [ISODCL (848, 864)]; /* 8.4.26.1 */ __u8 effective_date [ISODCL (865, 881)]; /* 8.4.26.1 */ __u8 file_structure_version [ISODCL (882, 882)]; /* 711 */ __u8 unused4 [ISODCL (883, 883)]; __u8 application_data [ISODCL (884, 1395)]; __u8 unused5 [ISODCL (1396, 2048)]; }; /* Almost the same as the primary descriptor but two fields are specified */ struct iso_supplementary_descriptor { __u8 type [ISODCL ( 1, 1)]; /* 711 */ char id [ISODCL ( 2, 6)]; __u8 version [ISODCL ( 7, 7)]; /* 711 */ __u8 flags [ISODCL ( 8, 8)]; /* 853 */ char system_id [ISODCL ( 9, 40)]; /* achars */ char volume_id [ISODCL ( 41, 72)]; /* dchars */ __u8 unused2 [ISODCL ( 73, 80)]; __u8 volume_space_size [ISODCL ( 81, 88)]; /* 733 */ __u8 escape [ISODCL ( 89, 120)]; /* 856 */ __u8 volume_set_size [ISODCL (121, 124)]; /* 723 */ __u8 volume_sequence_number [ISODCL (125, 128)]; /* 723 */ __u8 logical_block_size [ISODCL (129, 132)]; /* 723 */ __u8 path_table_size [ISODCL (133, 140)]; /* 733 */ __u8 type_l_path_table [ISODCL (141, 144)]; /* 731 */ __u8 opt_type_l_path_table [ISODCL (145, 148)]; /* 731 */ __u8 type_m_path_table [ISODCL (149, 152)]; /* 732 */ __u8 opt_type_m_path_table [ISODCL (153, 156)]; /* 732 */ __u8 root_directory_record [ISODCL (157, 190)]; /* 9.1 */ char volume_set_id [ISODCL (191, 318)]; /* dchars */ char publisher_id [ISODCL (319, 446)]; /* achars */ char preparer_id [ISODCL (447, 574)]; /* achars */ char application_id [ISODCL (575, 702)]; /* achars */ char copyright_file_id [ISODCL (703, 739)]; /* 7.5 dchars */ char abstract_file_id [ISODCL (740, 776)]; /* 7.5 dchars */ char bibliographic_file_id [ISODCL (777, 813)]; /* 7.5 dchars */ __u8 creation_date [ISODCL (814, 830)]; /* 8.4.26.1 */ __u8 modification_date [ISODCL (831, 847)]; /* 8.4.26.1 */ __u8 expiration_date [ISODCL (848, 864)]; /* 8.4.26.1 */ __u8 effective_date [ISODCL (865, 881)]; /* 8.4.26.1 */ __u8 file_structure_version [ISODCL (882, 882)]; /* 711 */ __u8 unused4 [ISODCL (883, 883)]; __u8 application_data [ISODCL (884, 1395)]; __u8 unused5 [ISODCL (1396, 2048)]; }; #define HS_STANDARD_ID "CDROM" struct hs_volume_descriptor { __u8 foo [ISODCL ( 1, 8)]; /* 733 */ __u8 type [ISODCL ( 9, 9)]; /* 711 */ char id [ISODCL ( 10, 14)]; __u8 version [ISODCL ( 15, 15)]; /* 711 */ __u8 data[ISODCL(16,2048)]; }; struct hs_primary_descriptor { __u8 foo [ISODCL ( 1, 8)]; /* 733 */ __u8 type [ISODCL ( 9, 9)]; /* 711 */ __u8 id [ISODCL ( 10, 14)]; __u8 version [ISODCL ( 15, 15)]; /* 711 */ __u8 unused1 [ISODCL ( 16, 16)]; /* 711 */ char system_id [ISODCL ( 17, 48)]; /* achars */ char volume_id [ISODCL ( 49, 80)]; /* dchars */ __u8 unused2 [ISODCL ( 81, 88)]; /* 733 */ __u8 volume_space_size [ISODCL ( 89, 96)]; /* 733 */ __u8 unused3 [ISODCL ( 97, 128)]; /* 733 */ __u8 volume_set_size [ISODCL (129, 132)]; /* 723 */ __u8 volume_sequence_number [ISODCL (133, 136)]; /* 723 */ __u8 logical_block_size [ISODCL (137, 140)]; /* 723 */ __u8 path_table_size [ISODCL (141, 148)]; /* 733 */ __u8 type_l_path_table [ISODCL (149, 152)]; /* 731 */ __u8 unused4 [ISODCL (153, 180)]; /* 733 */ __u8 root_directory_record [ISODCL (181, 214)]; /* 9.1 */ }; /* We use this to help us look up the parent inode numbers. */ struct iso_path_table{ __u8 name_len[2]; /* 721 */ __u8 extent[4]; /* 731 */ __u8 parent[2]; /* 721 */ char name[0]; } __attribute__((packed)); /* high sierra is identical to iso, except that the date is only 6 bytes, and there is an extra reserved byte after the flags */ struct iso_directory_record { __u8 length [ISODCL (1, 1)]; /* 711 */ __u8 ext_attr_length [ISODCL (2, 2)]; /* 711 */ __u8 extent [ISODCL (3, 10)]; /* 733 */ __u8 size [ISODCL (11, 18)]; /* 733 */ __u8 date [ISODCL (19, 25)]; /* 7 by 711 */ __u8 flags [ISODCL (26, 26)]; __u8 file_unit_size [ISODCL (27, 27)]; /* 711 */ __u8 interleave [ISODCL (28, 28)]; /* 711 */ __u8 volume_sequence_number [ISODCL (29, 32)]; /* 723 */ __u8 name_len [ISODCL (33, 33)]; /* 711 */ char name [0]; } __attribute__((packed)); #define ISOFS_BLOCK_BITS 11 #define ISOFS_BLOCK_SIZE 2048 #define ISOFS_BUFFER_SIZE(INODE) ((INODE)->i_sb->s_blocksize) #define ISOFS_BUFFER_BITS(INODE) ((INODE)->i_sb->s_blocksize_bits) #endif /* _ISOFS_FS_H */ linux/uuid.h000064400000002514151027430560007027 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * UUID/GUID definition * * Copyright (C) 2010, Intel Corp. * Huang Ying * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _LINUX_UUID_H_ #define _LINUX_UUID_H_ #include typedef struct { __u8 b[16]; } guid_t; #define GUID_INIT(a, b, c, d0, d1, d2, d3, d4, d5, d6, d7) \ ((guid_t) \ {{ (a) & 0xff, ((a) >> 8) & 0xff, ((a) >> 16) & 0xff, ((a) >> 24) & 0xff, \ (b) & 0xff, ((b) >> 8) & 0xff, \ (c) & 0xff, ((c) >> 8) & 0xff, \ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }}) /* backwards compatibility, don't use in new code */ typedef guid_t uuid_le; #define UUID_LE(a, b, c, d0, d1, d2, d3, d4, d5, d6, d7) \ GUID_INIT(a, b, c, d0, d1, d2, d3, d4, d5, d6, d7) #define NULL_UUID_LE \ UUID_LE(0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, \ 0x00, 0x00, 0x00, 0x00) #endif /* _LINUX_UUID_H_ */ linux/netrom.h000064400000001447151027430560007371 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * These are the public elements of the Linux kernel NET/ROM implementation. * For kernel AX.25 see the file ax25.h. This file requires ax25.h for the * definition of the ax25_address structure. */ #ifndef NETROM_KERNEL_H #define NETROM_KERNEL_H #include #define NETROM_MTU 236 #define NETROM_T1 1 #define NETROM_T2 2 #define NETROM_N2 3 #define NETROM_T4 6 #define NETROM_IDLE 7 #define SIOCNRDECOBS (SIOCPROTOPRIVATE+2) struct nr_route_struct { #define NETROM_NEIGH 0 #define NETROM_NODE 1 int type; ax25_address callsign; char device[16]; unsigned int quality; char mnemonic[7]; ax25_address neighbour; unsigned int obs_count; unsigned int ndigis; ax25_address digipeaters[AX25_MAX_DIGIS]; }; #endif linux/if_infiniband.h000064400000002335151027430560010641 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-2-Clause) */ /* * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available at * , or the OpenIB.org BSD * license, available in the LICENSE.TXT file accompanying this * software. These details are also available at * . * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright (c) 2004 Topspin Communications. All rights reserved. * * $Id$ */ #ifndef _LINUX_IF_INFINIBAND_H #define _LINUX_IF_INFINIBAND_H #define INFINIBAND_ALEN 20 /* Octets in IPoIB HW addr */ #endif /* _LINUX_IF_INFINIBAND_H */ linux/if_packet.h000064400000017357151027430560010021 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_IF_PACKET_H #define __LINUX_IF_PACKET_H #include struct sockaddr_pkt { unsigned short spkt_family; unsigned char spkt_device[14]; __be16 spkt_protocol; }; struct sockaddr_ll { unsigned short sll_family; __be16 sll_protocol; int sll_ifindex; unsigned short sll_hatype; unsigned char sll_pkttype; unsigned char sll_halen; unsigned char sll_addr[8]; }; /* Packet types */ #define PACKET_HOST 0 /* To us */ #define PACKET_BROADCAST 1 /* To all */ #define PACKET_MULTICAST 2 /* To group */ #define PACKET_OTHERHOST 3 /* To someone else */ #define PACKET_OUTGOING 4 /* Outgoing of any type */ #define PACKET_LOOPBACK 5 /* MC/BRD frame looped back */ #define PACKET_USER 6 /* To user space */ #define PACKET_KERNEL 7 /* To kernel space */ /* Unused, PACKET_FASTROUTE and PACKET_LOOPBACK are invisible to user space */ #define PACKET_FASTROUTE 6 /* Fastrouted frame */ /* Packet socket options */ #define PACKET_ADD_MEMBERSHIP 1 #define PACKET_DROP_MEMBERSHIP 2 #define PACKET_RECV_OUTPUT 3 /* Value 4 is still used by obsolete turbo-packet. */ #define PACKET_RX_RING 5 #define PACKET_STATISTICS 6 #define PACKET_COPY_THRESH 7 #define PACKET_AUXDATA 8 #define PACKET_ORIGDEV 9 #define PACKET_VERSION 10 #define PACKET_HDRLEN 11 #define PACKET_RESERVE 12 #define PACKET_TX_RING 13 #define PACKET_LOSS 14 #define PACKET_VNET_HDR 15 #define PACKET_TX_TIMESTAMP 16 #define PACKET_TIMESTAMP 17 #define PACKET_FANOUT 18 #define PACKET_TX_HAS_OFF 19 #define PACKET_QDISC_BYPASS 20 #define PACKET_ROLLOVER_STATS 21 #define PACKET_FANOUT_DATA 22 #define PACKET_FANOUT_HASH 0 #define PACKET_FANOUT_LB 1 #define PACKET_FANOUT_CPU 2 #define PACKET_FANOUT_ROLLOVER 3 #define PACKET_FANOUT_RND 4 #define PACKET_FANOUT_QM 5 #define PACKET_FANOUT_CBPF 6 #define PACKET_FANOUT_EBPF 7 #define PACKET_FANOUT_FLAG_ROLLOVER 0x1000 #define PACKET_FANOUT_FLAG_UNIQUEID 0x2000 #define PACKET_FANOUT_FLAG_DEFRAG 0x8000 struct tpacket_stats { unsigned int tp_packets; unsigned int tp_drops; }; struct tpacket_stats_v3 { unsigned int tp_packets; unsigned int tp_drops; unsigned int tp_freeze_q_cnt; }; struct tpacket_rollover_stats { __aligned_u64 tp_all; __aligned_u64 tp_huge; __aligned_u64 tp_failed; }; union tpacket_stats_u { struct tpacket_stats stats1; struct tpacket_stats_v3 stats3; }; struct tpacket_auxdata { __u32 tp_status; __u32 tp_len; __u32 tp_snaplen; __u16 tp_mac; __u16 tp_net; __u16 tp_vlan_tci; __u16 tp_vlan_tpid; }; /* Rx ring - header status */ #define TP_STATUS_KERNEL 0 #define TP_STATUS_USER (1 << 0) #define TP_STATUS_COPY (1 << 1) #define TP_STATUS_LOSING (1 << 2) #define TP_STATUS_CSUMNOTREADY (1 << 3) #define TP_STATUS_VLAN_VALID (1 << 4) /* auxdata has valid tp_vlan_tci */ #define TP_STATUS_BLK_TMO (1 << 5) #define TP_STATUS_VLAN_TPID_VALID (1 << 6) /* auxdata has valid tp_vlan_tpid */ #define TP_STATUS_CSUM_VALID (1 << 7) /* Tx ring - header status */ #define TP_STATUS_AVAILABLE 0 #define TP_STATUS_SEND_REQUEST (1 << 0) #define TP_STATUS_SENDING (1 << 1) #define TP_STATUS_WRONG_FORMAT (1 << 2) /* Rx and Tx ring - header status */ #define TP_STATUS_TS_SOFTWARE (1 << 29) #define TP_STATUS_TS_SYS_HARDWARE (1 << 30) /* deprecated, never set */ #define TP_STATUS_TS_RAW_HARDWARE (1 << 31) /* Rx ring - feature request bits */ #define TP_FT_REQ_FILL_RXHASH 0x1 struct tpacket_hdr { unsigned long tp_status; unsigned int tp_len; unsigned int tp_snaplen; unsigned short tp_mac; unsigned short tp_net; unsigned int tp_sec; unsigned int tp_usec; }; #define TPACKET_ALIGNMENT 16 #define TPACKET_ALIGN(x) (((x)+TPACKET_ALIGNMENT-1)&~(TPACKET_ALIGNMENT-1)) #define TPACKET_HDRLEN (TPACKET_ALIGN(sizeof(struct tpacket_hdr)) + sizeof(struct sockaddr_ll)) struct tpacket2_hdr { __u32 tp_status; __u32 tp_len; __u32 tp_snaplen; __u16 tp_mac; __u16 tp_net; __u32 tp_sec; __u32 tp_nsec; __u16 tp_vlan_tci; __u16 tp_vlan_tpid; __u8 tp_padding[4]; }; struct tpacket_hdr_variant1 { __u32 tp_rxhash; __u32 tp_vlan_tci; __u16 tp_vlan_tpid; __u16 tp_padding; }; struct tpacket3_hdr { __u32 tp_next_offset; __u32 tp_sec; __u32 tp_nsec; __u32 tp_snaplen; __u32 tp_len; __u32 tp_status; __u16 tp_mac; __u16 tp_net; /* pkt_hdr variants */ union { struct tpacket_hdr_variant1 hv1; }; __u8 tp_padding[8]; }; struct tpacket_bd_ts { unsigned int ts_sec; union { unsigned int ts_usec; unsigned int ts_nsec; }; }; struct tpacket_hdr_v1 { __u32 block_status; __u32 num_pkts; __u32 offset_to_first_pkt; /* Number of valid bytes (including padding) * blk_len <= tp_block_size */ __u32 blk_len; /* * Quite a few uses of sequence number: * 1. Make sure cache flush etc worked. * Well, one can argue - why not use the increasing ts below? * But look at 2. below first. * 2. When you pass around blocks to other user space decoders, * you can see which blk[s] is[are] outstanding etc. * 3. Validate kernel code. */ __aligned_u64 seq_num; /* * ts_last_pkt: * * Case 1. Block has 'N'(N >=1) packets and TMO'd(timed out) * ts_last_pkt == 'time-stamp of last packet' and NOT the * time when the timer fired and the block was closed. * By providing the ts of the last packet we can absolutely * guarantee that time-stamp wise, the first packet in the * next block will never precede the last packet of the * previous block. * Case 2. Block has zero packets and TMO'd * ts_last_pkt = time when the timer fired and the block * was closed. * Case 3. Block has 'N' packets and NO TMO. * ts_last_pkt = time-stamp of the last pkt in the block. * * ts_first_pkt: * Is always the time-stamp when the block was opened. * Case a) ZERO packets * No packets to deal with but atleast you know the * time-interval of this block. * Case b) Non-zero packets * Use the ts of the first packet in the block. * */ struct tpacket_bd_ts ts_first_pkt, ts_last_pkt; }; union tpacket_bd_header_u { struct tpacket_hdr_v1 bh1; }; struct tpacket_block_desc { __u32 version; __u32 offset_to_priv; union tpacket_bd_header_u hdr; }; #define TPACKET2_HDRLEN (TPACKET_ALIGN(sizeof(struct tpacket2_hdr)) + sizeof(struct sockaddr_ll)) #define TPACKET3_HDRLEN (TPACKET_ALIGN(sizeof(struct tpacket3_hdr)) + sizeof(struct sockaddr_ll)) enum tpacket_versions { TPACKET_V1, TPACKET_V2, TPACKET_V3 }; /* Frame structure: - Start. Frame must be aligned to TPACKET_ALIGNMENT=16 - struct tpacket_hdr - pad to TPACKET_ALIGNMENT=16 - struct sockaddr_ll - Gap, chosen so that packet data (Start+tp_net) alignes to TPACKET_ALIGNMENT=16 - Start+tp_mac: [ Optional MAC header ] - Start+tp_net: Packet data, aligned to TPACKET_ALIGNMENT=16. - Pad to align to TPACKET_ALIGNMENT=16 */ struct tpacket_req { unsigned int tp_block_size; /* Minimal size of contiguous block */ unsigned int tp_block_nr; /* Number of blocks */ unsigned int tp_frame_size; /* Size of frame */ unsigned int tp_frame_nr; /* Total number of frames */ }; struct tpacket_req3 { unsigned int tp_block_size; /* Minimal size of contiguous block */ unsigned int tp_block_nr; /* Number of blocks */ unsigned int tp_frame_size; /* Size of frame */ unsigned int tp_frame_nr; /* Total number of frames */ unsigned int tp_retire_blk_tov; /* timeout in msecs */ unsigned int tp_sizeof_priv; /* offset to private data area */ unsigned int tp_feature_req_word; }; union tpacket_req_u { struct tpacket_req req; struct tpacket_req3 req3; }; struct packet_mreq { int mr_ifindex; unsigned short mr_type; unsigned short mr_alen; unsigned char mr_address[8]; }; #define PACKET_MR_MULTICAST 0 #define PACKET_MR_PROMISC 1 #define PACKET_MR_ALLMULTI 2 #define PACKET_MR_UNICAST 3 #endif linux/bpqether.h000064400000001725151027430560007676 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __BPQETHER_H #define __BPQETHER_H /* * Defines for the BPQETHER pseudo device driver */ #include #define SIOCSBPQETHOPT (SIOCDEVPRIVATE+0) /* reserved */ #define SIOCSBPQETHADDR (SIOCDEVPRIVATE+1) struct bpq_ethaddr { unsigned char destination[ETH_ALEN]; unsigned char accept[ETH_ALEN]; }; /* * For SIOCSBPQETHOPT - this is compatible with PI2/PacketTwin card drivers, * currently not implemented, though. If someone wants to hook a radio * to his Ethernet card he may find this useful. ;-) */ #define SIOCGBPQETHPARAM 0x5000 /* get Level 1 parameters */ #define SIOCSBPQETHPARAM 0x5001 /* set */ struct bpq_req { int cmd; int speed; /* unused */ int clockmode; /* unused */ int txdelay; unsigned char persist; /* unused */ int slotime; /* unused */ int squeldelay; int dmachan; /* unused */ int irq; /* unused */ }; #endif linux/uvcvideo.h000064400000005113151027430560007703 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_UVCVIDEO_H_ #define __LINUX_UVCVIDEO_H_ #include #include /* * Dynamic controls */ /* Data types for UVC control data */ #define UVC_CTRL_DATA_TYPE_RAW 0 #define UVC_CTRL_DATA_TYPE_SIGNED 1 #define UVC_CTRL_DATA_TYPE_UNSIGNED 2 #define UVC_CTRL_DATA_TYPE_BOOLEAN 3 #define UVC_CTRL_DATA_TYPE_ENUM 4 #define UVC_CTRL_DATA_TYPE_BITMASK 5 /* Control flags */ #define UVC_CTRL_FLAG_SET_CUR (1 << 0) #define UVC_CTRL_FLAG_GET_CUR (1 << 1) #define UVC_CTRL_FLAG_GET_MIN (1 << 2) #define UVC_CTRL_FLAG_GET_MAX (1 << 3) #define UVC_CTRL_FLAG_GET_RES (1 << 4) #define UVC_CTRL_FLAG_GET_DEF (1 << 5) /* Control should be saved at suspend and restored at resume. */ #define UVC_CTRL_FLAG_RESTORE (1 << 6) /* Control can be updated by the camera. */ #define UVC_CTRL_FLAG_AUTO_UPDATE (1 << 7) /* Control supports asynchronous reporting */ #define UVC_CTRL_FLAG_ASYNCHRONOUS (1 << 8) #define UVC_CTRL_FLAG_GET_RANGE \ (UVC_CTRL_FLAG_GET_CUR | UVC_CTRL_FLAG_GET_MIN | \ UVC_CTRL_FLAG_GET_MAX | UVC_CTRL_FLAG_GET_RES | \ UVC_CTRL_FLAG_GET_DEF) #define UVC_MENU_NAME_LEN 32 struct uvc_menu_info { __u32 value; __u8 name[UVC_MENU_NAME_LEN]; }; struct uvc_xu_control_mapping { __u32 id; __u8 name[32]; __u8 entity[16]; __u8 selector; __u8 size; __u8 offset; __u32 v4l2_type; __u32 data_type; struct uvc_menu_info *menu_info; __u32 menu_count; __u32 reserved[4]; }; struct uvc_xu_control_query { __u8 unit; __u8 selector; __u8 query; /* Video Class-Specific Request Code, */ /* defined in linux/usb/video.h A.8. */ __u16 size; __u8 *data; }; #define UVCIOC_CTRL_MAP _IOWR('u', 0x20, struct uvc_xu_control_mapping) #define UVCIOC_CTRL_QUERY _IOWR('u', 0x21, struct uvc_xu_control_query) /* * Metadata node */ /** * struct uvc_meta_buf - metadata buffer building block * @ns - system timestamp of the payload in nanoseconds * @sof - USB Frame Number * @length - length of the payload header * @flags - payload header flags * @buf - optional device-specific header data * * UVC metadata nodes fill buffers with possibly multiple instances of this * struct. The first two fields are added by the driver, they can be used for * clock synchronisation. The rest is an exact copy of a UVC payload header. * Only complete objects with complete buffers are included. Therefore it's * always sizeof(meta->ns) + sizeof(meta->sof) + meta->length bytes large. */ struct uvc_meta_buf { __u64 ns; __u16 sof; __u8 length; __u8 flags; __u8 buf[]; } __attribute__((packed)); #endif linux/if_pppox.h000064400000011417151027430560007707 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /*************************************************************************** * Linux PPP over X - Generic PPP transport layer sockets * Linux PPP over Ethernet (PPPoE) Socket Implementation (RFC 2516) * * This file supplies definitions required by the PPP over Ethernet driver * (pppox.c). All version information wrt this file is located in pppox.c * * License: * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #ifndef __LINUX_IF_PPPOX_H #define __LINUX_IF_PPPOX_H #include #include #include #include #include #include #include #include /* For user-space programs to pick up these definitions * which they wouldn't get otherwise without defining __KERNEL__ */ #ifndef AF_PPPOX #define AF_PPPOX 24 #define PF_PPPOX AF_PPPOX #endif /* !(AF_PPPOX) */ /************************************************************************ * PPPoE addressing definition */ typedef __be16 sid_t; struct pppoe_addr { sid_t sid; /* Session identifier */ unsigned char remote[ETH_ALEN]; /* Remote address */ char dev[IFNAMSIZ]; /* Local device to use */ }; /************************************************************************ * PPTP addressing definition */ struct pptp_addr { __u16 call_id; struct in_addr sin_addr; }; /************************************************************************ * Protocols supported by AF_PPPOX */ #define PX_PROTO_OE 0 /* Currently just PPPoE */ #define PX_PROTO_OL2TP 1 /* Now L2TP also */ #define PX_PROTO_PPTP 2 #define PX_MAX_PROTO 3 struct sockaddr_pppox { __kernel_sa_family_t sa_family; /* address family, AF_PPPOX */ unsigned int sa_protocol; /* protocol identifier */ union { struct pppoe_addr pppoe; struct pptp_addr pptp; } sa_addr; } __attribute__((packed)); /* The use of the above union isn't viable because the size of this * struct must stay fixed over time -- applications use sizeof(struct * sockaddr_pppox) to fill it. We use a protocol specific sockaddr * type instead. */ struct sockaddr_pppol2tp { __kernel_sa_family_t sa_family; /* address family, AF_PPPOX */ unsigned int sa_protocol; /* protocol identifier */ struct pppol2tp_addr pppol2tp; } __attribute__((packed)); struct sockaddr_pppol2tpin6 { __kernel_sa_family_t sa_family; /* address family, AF_PPPOX */ unsigned int sa_protocol; /* protocol identifier */ struct pppol2tpin6_addr pppol2tp; } __attribute__((packed)); /* The L2TPv3 protocol changes tunnel and session ids from 16 to 32 * bits. So we need a different sockaddr structure. */ struct sockaddr_pppol2tpv3 { __kernel_sa_family_t sa_family; /* address family, AF_PPPOX */ unsigned int sa_protocol; /* protocol identifier */ struct pppol2tpv3_addr pppol2tp; } __attribute__((packed)); struct sockaddr_pppol2tpv3in6 { __kernel_sa_family_t sa_family; /* address family, AF_PPPOX */ unsigned int sa_protocol; /* protocol identifier */ struct pppol2tpv3in6_addr pppol2tp; } __attribute__((packed)); /********************************************************************* * * ioctl interface for defining forwarding of connections * ********************************************************************/ #define PPPOEIOCSFWD _IOW(0xB1 ,0, size_t) #define PPPOEIOCDFWD _IO(0xB1 ,1) /*#define PPPOEIOCGFWD _IOWR(0xB1,2, size_t)*/ /* Codes to identify message types */ #define PADI_CODE 0x09 #define PADO_CODE 0x07 #define PADR_CODE 0x19 #define PADS_CODE 0x65 #define PADT_CODE 0xa7 struct pppoe_tag { __be16 tag_type; __be16 tag_len; char tag_data[0]; } __attribute__ ((packed)); /* Tag identifiers */ #define PTT_EOL __cpu_to_be16(0x0000) #define PTT_SRV_NAME __cpu_to_be16(0x0101) #define PTT_AC_NAME __cpu_to_be16(0x0102) #define PTT_HOST_UNIQ __cpu_to_be16(0x0103) #define PTT_AC_COOKIE __cpu_to_be16(0x0104) #define PTT_VENDOR __cpu_to_be16(0x0105) #define PTT_RELAY_SID __cpu_to_be16(0x0110) #define PTT_SRV_ERR __cpu_to_be16(0x0201) #define PTT_SYS_ERR __cpu_to_be16(0x0202) #define PTT_GEN_ERR __cpu_to_be16(0x0203) struct pppoe_hdr { #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 type : 4; __u8 ver : 4; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 ver : 4; __u8 type : 4; #else #error "Please fix " #endif __u8 code; __be16 sid; __be16 length; struct pppoe_tag tag[0]; } __attribute__((packed)); /* Length of entire PPPoE + PPP header */ #define PPPOE_SES_HLEN 8 #endif /* __LINUX_IF_PPPOX_H */ linux/hdlc/ioctl.h000064400000005141151027430560010104 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __HDLC_IOCTL_H__ #define __HDLC_IOCTL_H__ #define GENERIC_HDLC_VERSION 4 /* For synchronization with sethdlc utility */ #define CLOCK_DEFAULT 0 /* Default setting */ #define CLOCK_EXT 1 /* External TX and RX clock - DTE */ #define CLOCK_INT 2 /* Internal TX and RX clock - DCE */ #define CLOCK_TXINT 3 /* Internal TX and external RX clock */ #define CLOCK_TXFROMRX 4 /* TX clock derived from external RX clock */ #define ENCODING_DEFAULT 0 /* Default setting */ #define ENCODING_NRZ 1 #define ENCODING_NRZI 2 #define ENCODING_FM_MARK 3 #define ENCODING_FM_SPACE 4 #define ENCODING_MANCHESTER 5 #define PARITY_DEFAULT 0 /* Default setting */ #define PARITY_NONE 1 /* No parity */ #define PARITY_CRC16_PR0 2 /* CRC16, initial value 0x0000 */ #define PARITY_CRC16_PR1 3 /* CRC16, initial value 0xFFFF */ #define PARITY_CRC16_PR0_CCITT 4 /* CRC16, initial 0x0000, ITU-T version */ #define PARITY_CRC16_PR1_CCITT 5 /* CRC16, initial 0xFFFF, ITU-T version */ #define PARITY_CRC32_PR0_CCITT 6 /* CRC32, initial value 0x00000000 */ #define PARITY_CRC32_PR1_CCITT 7 /* CRC32, initial value 0xFFFFFFFF */ #define LMI_DEFAULT 0 /* Default setting */ #define LMI_NONE 1 /* No LMI, all PVCs are static */ #define LMI_ANSI 2 /* ANSI Annex D */ #define LMI_CCITT 3 /* ITU-T Annex A */ #define LMI_CISCO 4 /* The "original" LMI, aka Gang of Four */ #ifndef __ASSEMBLY__ typedef struct { unsigned int clock_rate; /* bits per second */ unsigned int clock_type; /* internal, external, TX-internal etc. */ unsigned short loopback; } sync_serial_settings; /* V.35, V.24, X.21 */ typedef struct { unsigned int clock_rate; /* bits per second */ unsigned int clock_type; /* internal, external, TX-internal etc. */ unsigned short loopback; unsigned int slot_map; } te1_settings; /* T1, E1 */ typedef struct { unsigned short encoding; unsigned short parity; } raw_hdlc_proto; typedef struct { unsigned int t391; unsigned int t392; unsigned int n391; unsigned int n392; unsigned int n393; unsigned short lmi; unsigned short dce; /* 1 for DCE (network side) operation */ } fr_proto; typedef struct { unsigned int dlci; } fr_proto_pvc; /* for creating/deleting FR PVCs */ typedef struct { unsigned int dlci; char master[IFNAMSIZ]; /* Name of master FRAD device */ }fr_proto_pvc_info; /* for returning PVC information only */ typedef struct { unsigned int interval; unsigned int timeout; } cisco_proto; /* PPP doesn't need any info now - supply length = 0 to ioctl */ #endif /* __ASSEMBLY__ */ #endif /* __HDLC_IOCTL_H__ */ linux/netfilter_decnet.h000064400000003673151027430560011406 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_DECNET_NETFILTER_H #define __LINUX_DECNET_NETFILTER_H /* DECnet-specific defines for netfilter. * This file (C) Steve Whitehouse 1999 derived from the * ipv4 netfilter header file which is * (C)1998 Rusty Russell -- This code is GPL. */ #include /* only for userspace compatibility */ #include /* for INT_MIN, INT_MAX */ /* IP Cache bits. */ /* Src IP address. */ #define NFC_DN_SRC 0x0001 /* Dest IP address. */ #define NFC_DN_DST 0x0002 /* Input device. */ #define NFC_DN_IF_IN 0x0004 /* Output device. */ #define NFC_DN_IF_OUT 0x0008 /* kernel define is in netfilter_defs.h */ #define NF_DN_NUMHOOKS 7 /* DECnet Hooks */ /* After promisc drops, checksum checks. */ #define NF_DN_PRE_ROUTING 0 /* If the packet is destined for this box. */ #define NF_DN_LOCAL_IN 1 /* If the packet is destined for another interface. */ #define NF_DN_FORWARD 2 /* Packets coming from a local process. */ #define NF_DN_LOCAL_OUT 3 /* Packets about to hit the wire. */ #define NF_DN_POST_ROUTING 4 /* Input Hello Packets */ #define NF_DN_HELLO 5 /* Input Routing Packets */ #define NF_DN_ROUTE 6 enum nf_dn_hook_priorities { NF_DN_PRI_FIRST = INT_MIN, NF_DN_PRI_CONNTRACK = -200, NF_DN_PRI_MANGLE = -150, NF_DN_PRI_NAT_DST = -100, NF_DN_PRI_FILTER = 0, NF_DN_PRI_NAT_SRC = 100, NF_DN_PRI_DNRTMSG = 200, NF_DN_PRI_LAST = INT_MAX, }; struct nf_dn_rtmsg { int nfdn_ifindex; }; #define NFDN_RTMSG(r) ((unsigned char *)(r) + NLMSG_ALIGN(sizeof(struct nf_dn_rtmsg))) /* backwards compatibility for userspace */ #define DNRMG_L1_GROUP 0x01 #define DNRMG_L2_GROUP 0x02 enum { DNRNG_NLGRP_NONE, #define DNRNG_NLGRP_NONE DNRNG_NLGRP_NONE DNRNG_NLGRP_L1, #define DNRNG_NLGRP_L1 DNRNG_NLGRP_L1 DNRNG_NLGRP_L2, #define DNRNG_NLGRP_L2 DNRNG_NLGRP_L2 __DNRNG_NLGRP_MAX }; #define DNRNG_NLGRP_MAX (__DNRNG_NLGRP_MAX - 1) #endif /*__LINUX_DECNET_NETFILTER_H*/ linux/major.h000064400000011151151027430560007166 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MAJOR_H #define _LINUX_MAJOR_H /* * This file has definitions for major device numbers. * For the device number assignments, see Documentation/admin-guide/devices.rst. */ #define UNNAMED_MAJOR 0 #define MEM_MAJOR 1 #define RAMDISK_MAJOR 1 #define FLOPPY_MAJOR 2 #define PTY_MASTER_MAJOR 2 #define IDE0_MAJOR 3 #define HD_MAJOR IDE0_MAJOR #define PTY_SLAVE_MAJOR 3 #define TTY_MAJOR 4 #define TTYAUX_MAJOR 5 #define LP_MAJOR 6 #define VCS_MAJOR 7 #define LOOP_MAJOR 7 #define SCSI_DISK0_MAJOR 8 #define SCSI_TAPE_MAJOR 9 #define MD_MAJOR 9 #define MISC_MAJOR 10 #define SCSI_CDROM_MAJOR 11 #define MUX_MAJOR 11 /* PA-RISC only */ #define XT_DISK_MAJOR 13 #define INPUT_MAJOR 13 #define SOUND_MAJOR 14 #define CDU31A_CDROM_MAJOR 15 #define JOYSTICK_MAJOR 15 #define GOLDSTAR_CDROM_MAJOR 16 #define OPTICS_CDROM_MAJOR 17 #define SANYO_CDROM_MAJOR 18 #define CYCLADES_MAJOR 19 #define CYCLADESAUX_MAJOR 20 #define MITSUMI_X_CDROM_MAJOR 20 #define MFM_ACORN_MAJOR 21 /* ARM Linux /dev/mfm */ #define SCSI_GENERIC_MAJOR 21 #define IDE1_MAJOR 22 #define DIGICU_MAJOR 22 #define DIGI_MAJOR 23 #define MITSUMI_CDROM_MAJOR 23 #define CDU535_CDROM_MAJOR 24 #define STL_SERIALMAJOR 24 #define MATSUSHITA_CDROM_MAJOR 25 #define STL_CALLOUTMAJOR 25 #define MATSUSHITA_CDROM2_MAJOR 26 #define QIC117_TAPE_MAJOR 27 #define MATSUSHITA_CDROM3_MAJOR 27 #define MATSUSHITA_CDROM4_MAJOR 28 #define STL_SIOMEMMAJOR 28 #define ACSI_MAJOR 28 #define AZTECH_CDROM_MAJOR 29 #define FB_MAJOR 29 /* /dev/fb* framebuffers */ #define MTD_BLOCK_MAJOR 31 #define CM206_CDROM_MAJOR 32 #define IDE2_MAJOR 33 #define IDE3_MAJOR 34 #define Z8530_MAJOR 34 #define XPRAM_MAJOR 35 /* Expanded storage on S/390: "slow ram"*/ #define NETLINK_MAJOR 36 #define PS2ESDI_MAJOR 36 #define IDETAPE_MAJOR 37 #define Z2RAM_MAJOR 37 #define APBLOCK_MAJOR 38 /* AP1000 Block device */ #define DDV_MAJOR 39 /* AP1000 DDV block device */ #define NBD_MAJOR 43 /* Network block device */ #define RISCOM8_NORMAL_MAJOR 48 #define DAC960_MAJOR 48 /* 48..55 */ #define RISCOM8_CALLOUT_MAJOR 49 #define MKISS_MAJOR 55 #define DSP56K_MAJOR 55 /* DSP56001 processor device */ #define IDE4_MAJOR 56 #define IDE5_MAJOR 57 #define SCSI_DISK1_MAJOR 65 #define SCSI_DISK2_MAJOR 66 #define SCSI_DISK3_MAJOR 67 #define SCSI_DISK4_MAJOR 68 #define SCSI_DISK5_MAJOR 69 #define SCSI_DISK6_MAJOR 70 #define SCSI_DISK7_MAJOR 71 #define COMPAQ_SMART2_MAJOR 72 #define COMPAQ_SMART2_MAJOR1 73 #define COMPAQ_SMART2_MAJOR2 74 #define COMPAQ_SMART2_MAJOR3 75 #define COMPAQ_SMART2_MAJOR4 76 #define COMPAQ_SMART2_MAJOR5 77 #define COMPAQ_SMART2_MAJOR6 78 #define COMPAQ_SMART2_MAJOR7 79 #define SPECIALIX_NORMAL_MAJOR 75 #define SPECIALIX_CALLOUT_MAJOR 76 #define AURORA_MAJOR 79 #define I2O_MAJOR 80 /* 80->87 */ #define SHMIQ_MAJOR 85 /* Linux/mips, SGI /dev/shmiq */ #define SCSI_CHANGER_MAJOR 86 #define IDE6_MAJOR 88 #define IDE7_MAJOR 89 #define IDE8_MAJOR 90 #define MTD_CHAR_MAJOR 90 #define IDE9_MAJOR 91 #define DASD_MAJOR 94 #define MDISK_MAJOR 95 #define UBD_MAJOR 98 #define PP_MAJOR 99 #define JSFD_MAJOR 99 #define PHONE_MAJOR 100 #define COMPAQ_CISS_MAJOR 104 #define COMPAQ_CISS_MAJOR1 105 #define COMPAQ_CISS_MAJOR2 106 #define COMPAQ_CISS_MAJOR3 107 #define COMPAQ_CISS_MAJOR4 108 #define COMPAQ_CISS_MAJOR5 109 #define COMPAQ_CISS_MAJOR6 110 #define COMPAQ_CISS_MAJOR7 111 #define VIODASD_MAJOR 112 #define VIOCD_MAJOR 113 #define ATARAID_MAJOR 114 #define SCSI_DISK8_MAJOR 128 #define SCSI_DISK9_MAJOR 129 #define SCSI_DISK10_MAJOR 130 #define SCSI_DISK11_MAJOR 131 #define SCSI_DISK12_MAJOR 132 #define SCSI_DISK13_MAJOR 133 #define SCSI_DISK14_MAJOR 134 #define SCSI_DISK15_MAJOR 135 #define UNIX98_PTY_MASTER_MAJOR 128 #define UNIX98_PTY_MAJOR_COUNT 8 #define UNIX98_PTY_SLAVE_MAJOR (UNIX98_PTY_MASTER_MAJOR+UNIX98_PTY_MAJOR_COUNT) #define DRBD_MAJOR 147 #define RTF_MAJOR 150 #define RAW_MAJOR 162 #define USB_ACM_MAJOR 166 #define USB_ACM_AUX_MAJOR 167 #define USB_CHAR_MAJOR 180 #define MMC_BLOCK_MAJOR 179 #define VXVM_MAJOR 199 /* VERITAS volume i/o driver */ #define VXSPEC_MAJOR 200 /* VERITAS volume config driver */ #define VXDMP_MAJOR 201 /* VERITAS volume multipath driver */ #define XENVBD_MAJOR 202 /* Xen virtual block device */ #define MSR_MAJOR 202 #define CPUID_MAJOR 203 #define OSST_MAJOR 206 /* OnStream-SCx0 SCSI tape */ #define IBM_TTY3270_MAJOR 227 #define IBM_FS3270_MAJOR 228 #define VIOTAPE_MAJOR 230 #define BLOCK_EXT_MAJOR 259 #define SCSI_OSD_MAJOR 260 /* open-osd's OSD scsi device */ #endif linux/utsname.h000064400000001235151027430560007534 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_UTSNAME_H #define _LINUX_UTSNAME_H #define __OLD_UTS_LEN 8 struct oldold_utsname { char sysname[9]; char nodename[9]; char release[9]; char version[9]; char machine[9]; }; #define __NEW_UTS_LEN 64 struct old_utsname { char sysname[65]; char nodename[65]; char release[65]; char version[65]; char machine[65]; }; struct new_utsname { char sysname[__NEW_UTS_LEN + 1]; char nodename[__NEW_UTS_LEN + 1]; char release[__NEW_UTS_LEN + 1]; char version[__NEW_UTS_LEN + 1]; char machine[__NEW_UTS_LEN + 1]; char domainname[__NEW_UTS_LEN + 1]; }; #endif /* _LINUX_UTSNAME_H */ linux/ipc.h000064400000004065151027430560006637 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_IPC_H #define _LINUX_IPC_H #include #define IPC_PRIVATE ((__kernel_key_t) 0) /* Obsolete, used only for backwards compatibility and libc5 compiles */ struct ipc_perm { __kernel_key_t key; __kernel_uid_t uid; __kernel_gid_t gid; __kernel_uid_t cuid; __kernel_gid_t cgid; __kernel_mode_t mode; unsigned short seq; }; /* Include the definition of ipc64_perm */ #include /* resource get request flags */ #define IPC_CREAT 00001000 /* create if key is nonexistent */ #define IPC_EXCL 00002000 /* fail if key exists */ #define IPC_NOWAIT 00004000 /* return error on wait */ /* these fields are used by the DIPC package so the kernel as standard should avoid using them if possible */ #define IPC_DIPC 00010000 /* make it distributed */ #define IPC_OWN 00020000 /* this machine is the DIPC owner */ /* * Control commands used with semctl, msgctl and shmctl * see also specific commands in sem.h, msg.h and shm.h */ #define IPC_RMID 0 /* remove resource */ #define IPC_SET 1 /* set ipc_perm options */ #define IPC_STAT 2 /* get ipc_perm options */ #define IPC_INFO 3 /* see ipcs */ /* * Version flags for semctl, msgctl, and shmctl commands * These are passed as bitflags or-ed with the actual command */ #define IPC_OLD 0 /* Old version (no 32-bit UID support on many architectures) */ #define IPC_64 0x0100 /* New version (support 32-bit UIDs, bigger message sizes, etc. */ /* * These are used to wrap system calls. * * See architecture code for ugly details.. */ struct ipc_kludge { struct msgbuf *msgp; long msgtyp; }; #define SEMOP 1 #define SEMGET 2 #define SEMCTL 3 #define SEMTIMEDOP 4 #define MSGSND 11 #define MSGRCV 12 #define MSGGET 13 #define MSGCTL 14 #define SHMAT 21 #define SHMDT 22 #define SHMGET 23 #define SHMCTL 24 /* Used by the DIPC package, try and avoid reusing it */ #define DIPC 25 #define IPCCALL(version,op) ((version)<<16 | (op)) #endif /* _LINUX_IPC_H */ linux/vfio.h000064400000145777151027430560007047 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * VFIO API definition * * Copyright (C) 2012 Red Hat, Inc. All rights reserved. * Author: Alex Williamson * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef VFIO_H #define VFIO_H #include #include #define VFIO_API_VERSION 0 /* Kernel & User level defines for VFIO IOCTLs. */ /* Extensions */ #define VFIO_TYPE1_IOMMU 1 #define VFIO_SPAPR_TCE_IOMMU 2 #define VFIO_TYPE1v2_IOMMU 3 /* * IOMMU enforces DMA cache coherence (ex. PCIe NoSnoop stripping). This * capability is subject to change as groups are added or removed. */ #define VFIO_DMA_CC_IOMMU 4 /* Check if EEH is supported */ #define VFIO_EEH 5 /* Two-stage IOMMU */ #define VFIO_TYPE1_NESTING_IOMMU 6 /* Implies v2 */ #define VFIO_SPAPR_TCE_v2_IOMMU 7 /* * The No-IOMMU IOMMU offers no translation or isolation for devices and * supports no ioctls outside of VFIO_CHECK_EXTENSION. Use of VFIO's No-IOMMU * code will taint the host kernel and should be used with extreme caution. */ #define VFIO_NOIOMMU_IOMMU 8 /* * The IOCTL interface is designed for extensibility by embedding the * structure length (argsz) and flags into structures passed between * kernel and userspace. We therefore use the _IO() macro for these * defines to avoid implicitly embedding a size into the ioctl request. * As structure fields are added, argsz will increase to match and flag * bits will be defined to indicate additional fields with valid data. * It's *always* the caller's responsibility to indicate the size of * the structure passed by setting argsz appropriately. */ #define VFIO_TYPE (';') #define VFIO_BASE 100 /* * For extension of INFO ioctls, VFIO makes use of a capability chain * designed after PCI/e capabilities. A flag bit indicates whether * this capability chain is supported and a field defined in the fixed * structure defines the offset of the first capability in the chain. * This field is only valid when the corresponding bit in the flags * bitmap is set. This offset field is relative to the start of the * INFO buffer, as is the next field within each capability header. * The id within the header is a shared address space per INFO ioctl, * while the version field is specific to the capability id. The * contents following the header are specific to the capability id. */ struct vfio_info_cap_header { __u16 id; /* Identifies capability */ __u16 version; /* Version specific to the capability ID */ __u32 next; /* Offset of next capability */ }; /* * Callers of INFO ioctls passing insufficiently sized buffers will see * the capability chain flag bit set, a zero value for the first capability * offset (if available within the provided argsz), and argsz will be * updated to report the necessary buffer size. For compatibility, the * INFO ioctl will not report error in this case, but the capability chain * will not be available. */ /* -------- IOCTLs for VFIO file descriptor (/dev/vfio/vfio) -------- */ /** * VFIO_GET_API_VERSION - _IO(VFIO_TYPE, VFIO_BASE + 0) * * Report the version of the VFIO API. This allows us to bump the entire * API version should we later need to add or change features in incompatible * ways. * Return: VFIO_API_VERSION * Availability: Always */ #define VFIO_GET_API_VERSION _IO(VFIO_TYPE, VFIO_BASE + 0) /** * VFIO_CHECK_EXTENSION - _IOW(VFIO_TYPE, VFIO_BASE + 1, __u32) * * Check whether an extension is supported. * Return: 0 if not supported, 1 (or some other positive integer) if supported. * Availability: Always */ #define VFIO_CHECK_EXTENSION _IO(VFIO_TYPE, VFIO_BASE + 1) /** * VFIO_SET_IOMMU - _IOW(VFIO_TYPE, VFIO_BASE + 2, __s32) * * Set the iommu to the given type. The type must be supported by an * iommu driver as verified by calling CHECK_EXTENSION using the same * type. A group must be set to this file descriptor before this * ioctl is available. The IOMMU interfaces enabled by this call are * specific to the value set. * Return: 0 on success, -errno on failure * Availability: When VFIO group attached */ #define VFIO_SET_IOMMU _IO(VFIO_TYPE, VFIO_BASE + 2) /* -------- IOCTLs for GROUP file descriptors (/dev/vfio/$GROUP) -------- */ /** * VFIO_GROUP_GET_STATUS - _IOR(VFIO_TYPE, VFIO_BASE + 3, * struct vfio_group_status) * * Retrieve information about the group. Fills in provided * struct vfio_group_info. Caller sets argsz. * Return: 0 on succes, -errno on failure. * Availability: Always */ struct vfio_group_status { __u32 argsz; __u32 flags; #define VFIO_GROUP_FLAGS_VIABLE (1 << 0) #define VFIO_GROUP_FLAGS_CONTAINER_SET (1 << 1) }; #define VFIO_GROUP_GET_STATUS _IO(VFIO_TYPE, VFIO_BASE + 3) /** * VFIO_GROUP_SET_CONTAINER - _IOW(VFIO_TYPE, VFIO_BASE + 4, __s32) * * Set the container for the VFIO group to the open VFIO file * descriptor provided. Groups may only belong to a single * container. Containers may, at their discretion, support multiple * groups. Only when a container is set are all of the interfaces * of the VFIO file descriptor and the VFIO group file descriptor * available to the user. * Return: 0 on success, -errno on failure. * Availability: Always */ #define VFIO_GROUP_SET_CONTAINER _IO(VFIO_TYPE, VFIO_BASE + 4) /** * VFIO_GROUP_UNSET_CONTAINER - _IO(VFIO_TYPE, VFIO_BASE + 5) * * Remove the group from the attached container. This is the * opposite of the SET_CONTAINER call and returns the group to * an initial state. All device file descriptors must be released * prior to calling this interface. When removing the last group * from a container, the IOMMU will be disabled and all state lost, * effectively also returning the VFIO file descriptor to an initial * state. * Return: 0 on success, -errno on failure. * Availability: When attached to container */ #define VFIO_GROUP_UNSET_CONTAINER _IO(VFIO_TYPE, VFIO_BASE + 5) /** * VFIO_GROUP_GET_DEVICE_FD - _IOW(VFIO_TYPE, VFIO_BASE + 6, char) * * Return a new file descriptor for the device object described by * the provided string. The string should match a device listed in * the devices subdirectory of the IOMMU group sysfs entry. The * group containing the device must already be added to this context. * Return: new file descriptor on success, -errno on failure. * Availability: When attached to container */ #define VFIO_GROUP_GET_DEVICE_FD _IO(VFIO_TYPE, VFIO_BASE + 6) /* --------------- IOCTLs for DEVICE file descriptors --------------- */ /** * VFIO_DEVICE_GET_INFO - _IOR(VFIO_TYPE, VFIO_BASE + 7, * struct vfio_device_info) * * Retrieve information about the device. Fills in provided * struct vfio_device_info. Caller sets argsz. * Return: 0 on success, -errno on failure. */ struct vfio_device_info { __u32 argsz; __u32 flags; #define VFIO_DEVICE_FLAGS_RESET (1 << 0) /* Device supports reset */ #define VFIO_DEVICE_FLAGS_PCI (1 << 1) /* vfio-pci device */ #define VFIO_DEVICE_FLAGS_PLATFORM (1 << 2) /* vfio-platform device */ #define VFIO_DEVICE_FLAGS_AMBA (1 << 3) /* vfio-amba device */ #define VFIO_DEVICE_FLAGS_CCW (1 << 4) /* vfio-ccw device */ #define VFIO_DEVICE_FLAGS_AP (1 << 5) /* vfio-ap device */ #define VFIO_DEVICE_FLAGS_CAPS (1 << 7) /* Info supports caps */ __u32 num_regions; /* Max region index + 1 */ __u32 num_irqs; /* Max IRQ index + 1 */ __u32 cap_offset; /* Offset within info struct of first cap */ }; #define VFIO_DEVICE_GET_INFO _IO(VFIO_TYPE, VFIO_BASE + 7) /* * Vendor driver using Mediated device framework should provide device_api * attribute in supported type attribute groups. Device API string should be one * of the following corresponding to device flags in vfio_device_info structure. */ #define VFIO_DEVICE_API_PCI_STRING "vfio-pci" #define VFIO_DEVICE_API_PLATFORM_STRING "vfio-platform" #define VFIO_DEVICE_API_AMBA_STRING "vfio-amba" #define VFIO_DEVICE_API_CCW_STRING "vfio-ccw" #define VFIO_DEVICE_API_AP_STRING "vfio-ap" /* * The following capabilities are unique to s390 zPCI devices. Their contents * are further-defined in vfio_zdev.h */ #define VFIO_DEVICE_INFO_CAP_ZPCI_BASE 1 #define VFIO_DEVICE_INFO_CAP_ZPCI_GROUP 2 #define VFIO_DEVICE_INFO_CAP_ZPCI_UTIL 3 #define VFIO_DEVICE_INFO_CAP_ZPCI_PFIP 4 /** * VFIO_DEVICE_GET_REGION_INFO - _IOWR(VFIO_TYPE, VFIO_BASE + 8, * struct vfio_region_info) * * Retrieve information about a device region. Caller provides * struct vfio_region_info with index value set. Caller sets argsz. * Implementation of region mapping is bus driver specific. This is * intended to describe MMIO, I/O port, as well as bus specific * regions (ex. PCI config space). Zero sized regions may be used * to describe unimplemented regions (ex. unimplemented PCI BARs). * Return: 0 on success, -errno on failure. */ struct vfio_region_info { __u32 argsz; __u32 flags; #define VFIO_REGION_INFO_FLAG_READ (1 << 0) /* Region supports read */ #define VFIO_REGION_INFO_FLAG_WRITE (1 << 1) /* Region supports write */ #define VFIO_REGION_INFO_FLAG_MMAP (1 << 2) /* Region supports mmap */ #define VFIO_REGION_INFO_FLAG_CAPS (1 << 3) /* Info supports caps */ __u32 index; /* Region index */ __u32 cap_offset; /* Offset within info struct of first cap */ __u64 size; /* Region size (bytes) */ __u64 offset; /* Region offset from start of device fd */ }; #define VFIO_DEVICE_GET_REGION_INFO _IO(VFIO_TYPE, VFIO_BASE + 8) /* * The sparse mmap capability allows finer granularity of specifying areas * within a region with mmap support. When specified, the user should only * mmap the offset ranges specified by the areas array. mmaps outside of the * areas specified may fail (such as the range covering a PCI MSI-X table) or * may result in improper device behavior. * * The structures below define version 1 of this capability. */ #define VFIO_REGION_INFO_CAP_SPARSE_MMAP 1 struct vfio_region_sparse_mmap_area { __u64 offset; /* Offset of mmap'able area within region */ __u64 size; /* Size of mmap'able area */ }; struct vfio_region_info_cap_sparse_mmap { struct vfio_info_cap_header header; __u32 nr_areas; __u32 reserved; struct vfio_region_sparse_mmap_area areas[]; }; /* * The device specific type capability allows regions unique to a specific * device or class of devices to be exposed. This helps solve the problem for * vfio bus drivers of defining which region indexes correspond to which region * on the device, without needing to resort to static indexes, as done by * vfio-pci. For instance, if we were to go back in time, we might remove * VFIO_PCI_VGA_REGION_INDEX and let vfio-pci simply define that all indexes * greater than or equal to VFIO_PCI_NUM_REGIONS are device specific and we'd * make a "VGA" device specific type to describe the VGA access space. This * means that non-VGA devices wouldn't need to waste this index, and thus the * address space associated with it due to implementation of device file * descriptor offsets in vfio-pci. * * The current implementation is now part of the user ABI, so we can't use this * for VGA, but there are other upcoming use cases, such as opregions for Intel * IGD devices and framebuffers for vGPU devices. We missed VGA, but we'll * use this for future additions. * * The structure below defines version 1 of this capability. */ #define VFIO_REGION_INFO_CAP_TYPE 2 struct vfio_region_info_cap_type { struct vfio_info_cap_header header; __u32 type; /* global per bus driver */ __u32 subtype; /* type specific */ }; /* * List of region types, global per bus driver. * If you introduce a new type, please add it here. */ /* PCI region type containing a PCI vendor part */ #define VFIO_REGION_TYPE_PCI_VENDOR_TYPE (1 << 31) #define VFIO_REGION_TYPE_PCI_VENDOR_MASK (0xffff) #define VFIO_REGION_TYPE_GFX (1) #define VFIO_REGION_TYPE_CCW (2) #define VFIO_REGION_TYPE_MIGRATION (3) /* sub-types for VFIO_REGION_TYPE_PCI_* */ /* 8086 vendor PCI sub-types */ #define VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION (1) #define VFIO_REGION_SUBTYPE_INTEL_IGD_HOST_CFG (2) #define VFIO_REGION_SUBTYPE_INTEL_IGD_LPC_CFG (3) /* 10de vendor PCI sub-types */ /* * NVIDIA GPU NVlink2 RAM is coherent RAM mapped onto the host address space. */ #define VFIO_REGION_SUBTYPE_NVIDIA_NVLINK2_RAM (1) /* 1014 vendor PCI sub-types */ /* * IBM NPU NVlink2 ATSD (Address Translation Shootdown) register of NPU * to do TLB invalidation on a GPU. */ #define VFIO_REGION_SUBTYPE_IBM_NVLINK2_ATSD (1) /* sub-types for VFIO_REGION_TYPE_GFX */ #define VFIO_REGION_SUBTYPE_GFX_EDID (1) /** * struct vfio_region_gfx_edid - EDID region layout. * * Set display link state and EDID blob. * * The EDID blob has monitor information such as brand, name, serial * number, physical size, supported video modes and more. * * This special region allows userspace (typically qemu) set a virtual * EDID for the virtual monitor, which allows a flexible display * configuration. * * For the edid blob spec look here: * https://en.wikipedia.org/wiki/Extended_Display_Identification_Data * * On linux systems you can find the EDID blob in sysfs: * /sys/class/drm/${card}/${connector}/edid * * You can use the edid-decode ulility (comes with xorg-x11-utils) to * decode the EDID blob. * * @edid_offset: location of the edid blob, relative to the * start of the region (readonly). * @edid_max_size: max size of the edid blob (readonly). * @edid_size: actual edid size (read/write). * @link_state: display link state (read/write). * VFIO_DEVICE_GFX_LINK_STATE_UP: Monitor is turned on. * VFIO_DEVICE_GFX_LINK_STATE_DOWN: Monitor is turned off. * @max_xres: max display width (0 == no limitation, readonly). * @max_yres: max display height (0 == no limitation, readonly). * * EDID update protocol: * (1) set link-state to down. * (2) update edid blob and size. * (3) set link-state to up. */ struct vfio_region_gfx_edid { __u32 edid_offset; __u32 edid_max_size; __u32 edid_size; __u32 max_xres; __u32 max_yres; __u32 link_state; #define VFIO_DEVICE_GFX_LINK_STATE_UP 1 #define VFIO_DEVICE_GFX_LINK_STATE_DOWN 2 }; /* sub-types for VFIO_REGION_TYPE_CCW */ #define VFIO_REGION_SUBTYPE_CCW_ASYNC_CMD (1) #define VFIO_REGION_SUBTYPE_CCW_SCHIB (2) #define VFIO_REGION_SUBTYPE_CCW_CRW (3) /* sub-types for VFIO_REGION_TYPE_MIGRATION */ #define VFIO_REGION_SUBTYPE_MIGRATION (1) /* * The structure vfio_device_migration_info is placed at the 0th offset of * the VFIO_REGION_SUBTYPE_MIGRATION region to get and set VFIO device related * migration information. Field accesses from this structure are only supported * at their native width and alignment. Otherwise, the result is undefined and * vendor drivers should return an error. * * device_state: (read/write) * - The user application writes to this field to inform the vendor driver * about the device state to be transitioned to. * - The vendor driver should take the necessary actions to change the * device state. After successful transition to a given state, the * vendor driver should return success on write(device_state, state) * system call. If the device state transition fails, the vendor driver * should return an appropriate -errno for the fault condition. * - On the user application side, if the device state transition fails, * that is, if write(device_state, state) returns an error, read * device_state again to determine the current state of the device from * the vendor driver. * - The vendor driver should return previous state of the device unless * the vendor driver has encountered an internal error, in which case * the vendor driver may report the device_state VFIO_DEVICE_STATE_ERROR. * - The user application must use the device reset ioctl to recover the * device from VFIO_DEVICE_STATE_ERROR state. If the device is * indicated to be in a valid device state by reading device_state, the * user application may attempt to transition the device to any valid * state reachable from the current state or terminate itself. * * device_state consists of 3 bits: * - If bit 0 is set, it indicates the _RUNNING state. If bit 0 is clear, * it indicates the _STOP state. When the device state is changed to * _STOP, driver should stop the device before write() returns. * - If bit 1 is set, it indicates the _SAVING state, which means that the * driver should start gathering device state information that will be * provided to the VFIO user application to save the device's state. * - If bit 2 is set, it indicates the _RESUMING state, which means that * the driver should prepare to resume the device. Data provided through * the migration region should be used to resume the device. * Bits 3 - 31 are reserved for future use. To preserve them, the user * application should perform a read-modify-write operation on this * field when modifying the specified bits. * * +------- _RESUMING * |+------ _SAVING * ||+----- _RUNNING * ||| * 000b => Device Stopped, not saving or resuming * 001b => Device running, which is the default state * 010b => Stop the device & save the device state, stop-and-copy state * 011b => Device running and save the device state, pre-copy state * 100b => Device stopped and the device state is resuming * 101b => Invalid state * 110b => Error state * 111b => Invalid state * * State transitions: * * _RESUMING _RUNNING Pre-copy Stop-and-copy _STOP * (100b) (001b) (011b) (010b) (000b) * 0. Running or default state * | * * 1. Normal Shutdown (optional) * |------------------------------------->| * * 2. Save the state or suspend * |------------------------->|---------->| * * 3. Save the state during live migration * |----------->|------------>|---------->| * * 4. Resuming * |<---------| * * 5. Resumed * |--------->| * * 0. Default state of VFIO device is _RUNNING when the user application starts. * 1. During normal shutdown of the user application, the user application may * optionally change the VFIO device state from _RUNNING to _STOP. This * transition is optional. The vendor driver must support this transition but * must not require it. * 2. When the user application saves state or suspends the application, the * device state transitions from _RUNNING to stop-and-copy and then to _STOP. * On state transition from _RUNNING to stop-and-copy, driver must stop the * device, save the device state and send it to the application through the * migration region. The sequence to be followed for such transition is given * below. * 3. In live migration of user application, the state transitions from _RUNNING * to pre-copy, to stop-and-copy, and to _STOP. * On state transition from _RUNNING to pre-copy, the driver should start * gathering the device state while the application is still running and send * the device state data to application through the migration region. * On state transition from pre-copy to stop-and-copy, the driver must stop * the device, save the device state and send it to the user application * through the migration region. * Vendor drivers must support the pre-copy state even for implementations * where no data is provided to the user before the stop-and-copy state. The * user must not be required to consume all migration data before the device * transitions to a new state, including the stop-and-copy state. * The sequence to be followed for above two transitions is given below. * 4. To start the resuming phase, the device state should be transitioned from * the _RUNNING to the _RESUMING state. * In the _RESUMING state, the driver should use the device state data * received through the migration region to resume the device. * 5. After providing saved device data to the driver, the application should * change the state from _RESUMING to _RUNNING. * * reserved: * Reads on this field return zero and writes are ignored. * * pending_bytes: (read only) * The number of pending bytes still to be migrated from the vendor driver. * * data_offset: (read only) * The user application should read data_offset field from the migration * region. The user application should read the device data from this * offset within the migration region during the _SAVING state or write * the device data during the _RESUMING state. See below for details of * sequence to be followed. * * data_size: (read/write) * The user application should read data_size to get the size in bytes of * the data copied in the migration region during the _SAVING state and * write the size in bytes of the data copied in the migration region * during the _RESUMING state. * * The format of the migration region is as follows: * ------------------------------------------------------------------ * |vfio_device_migration_info| data section | * | | /////////////////////////////// | * ------------------------------------------------------------------ * ^ ^ * offset 0-trapped part data_offset * * The structure vfio_device_migration_info is always followed by the data * section in the region, so data_offset will always be nonzero. The offset * from where the data is copied is decided by the kernel driver. The data * section can be trapped, mmapped, or partitioned, depending on how the kernel * driver defines the data section. The data section partition can be defined * as mapped by the sparse mmap capability. If mmapped, data_offset must be * page aligned, whereas initial section which contains the * vfio_device_migration_info structure, might not end at the offset, which is * page aligned. The user is not required to access through mmap regardless * of the capabilities of the region mmap. * The vendor driver should determine whether and how to partition the data * section. The vendor driver should return data_offset accordingly. * * The sequence to be followed while in pre-copy state and stop-and-copy state * is as follows: * a. Read pending_bytes, indicating the start of a new iteration to get device * data. Repeated read on pending_bytes at this stage should have no side * effects. * If pending_bytes == 0, the user application should not iterate to get data * for that device. * If pending_bytes > 0, perform the following steps. * b. Read data_offset, indicating that the vendor driver should make data * available through the data section. The vendor driver should return this * read operation only after data is available from (region + data_offset) * to (region + data_offset + data_size). * c. Read data_size, which is the amount of data in bytes available through * the migration region. * Read on data_offset and data_size should return the offset and size of * the current buffer if the user application reads data_offset and * data_size more than once here. * d. Read data_size bytes of data from (region + data_offset) from the * migration region. * e. Process the data. * f. Read pending_bytes, which indicates that the data from the previous * iteration has been read. If pending_bytes > 0, go to step b. * * The user application can transition from the _SAVING|_RUNNING * (pre-copy state) to the _SAVING (stop-and-copy) state regardless of the * number of pending bytes. The user application should iterate in _SAVING * (stop-and-copy) until pending_bytes is 0. * * The sequence to be followed while _RESUMING device state is as follows: * While data for this device is available, repeat the following steps: * a. Read data_offset from where the user application should write data. * b. Write migration data starting at the migration region + data_offset for * the length determined by data_size from the migration source. * c. Write data_size, which indicates to the vendor driver that data is * written in the migration region. Vendor driver must return this write * operations on consuming data. Vendor driver should apply the * user-provided migration region data to the device resume state. * * If an error occurs during the above sequences, the vendor driver can return * an error code for next read() or write() operation, which will terminate the * loop. The user application should then take the next necessary action, for * example, failing migration or terminating the user application. * * For the user application, data is opaque. The user application should write * data in the same order as the data is received and the data should be of * same transaction size at the source. */ struct vfio_device_migration_info { __u32 device_state; /* VFIO device state */ #define VFIO_DEVICE_STATE_STOP (0) #define VFIO_DEVICE_STATE_RUNNING (1 << 0) #define VFIO_DEVICE_STATE_SAVING (1 << 1) #define VFIO_DEVICE_STATE_RESUMING (1 << 2) #define VFIO_DEVICE_STATE_MASK (VFIO_DEVICE_STATE_RUNNING | \ VFIO_DEVICE_STATE_SAVING | \ VFIO_DEVICE_STATE_RESUMING) #define VFIO_DEVICE_STATE_VALID(state) \ (state & VFIO_DEVICE_STATE_RESUMING ? \ (state & VFIO_DEVICE_STATE_MASK) == VFIO_DEVICE_STATE_RESUMING : 1) #define VFIO_DEVICE_STATE_IS_ERROR(state) \ ((state & VFIO_DEVICE_STATE_MASK) == (VFIO_DEVICE_STATE_SAVING | \ VFIO_DEVICE_STATE_RESUMING)) #define VFIO_DEVICE_STATE_SET_ERROR(state) \ ((state & ~VFIO_DEVICE_STATE_MASK) | VFIO_DEVICE_SATE_SAVING | \ VFIO_DEVICE_STATE_RESUMING) __u32 reserved; __u64 pending_bytes; __u64 data_offset; __u64 data_size; }; /* * The MSIX mappable capability informs that MSIX data of a BAR can be mmapped * which allows direct access to non-MSIX registers which happened to be within * the same system page. * * Even though the userspace gets direct access to the MSIX data, the existing * VFIO_DEVICE_SET_IRQS interface must still be used for MSIX configuration. */ #define VFIO_REGION_INFO_CAP_MSIX_MAPPABLE 3 /* * Capability with compressed real address (aka SSA - small system address) * where GPU RAM is mapped on a system bus. Used by a GPU for DMA routing * and by the userspace to associate a NVLink bridge with a GPU. */ #define VFIO_REGION_INFO_CAP_NVLINK2_SSATGT 4 struct vfio_region_info_cap_nvlink2_ssatgt { struct vfio_info_cap_header header; __u64 tgt; }; /* * Capability with an NVLink link speed. The value is read by * the NVlink2 bridge driver from the bridge's "ibm,nvlink-speed" * property in the device tree. The value is fixed in the hardware * and failing to provide the correct value results in the link * not working with no indication from the driver why. */ #define VFIO_REGION_INFO_CAP_NVLINK2_LNKSPD 5 struct vfio_region_info_cap_nvlink2_lnkspd { struct vfio_info_cap_header header; __u32 link_speed; __u32 __pad; }; /** * VFIO_DEVICE_GET_IRQ_INFO - _IOWR(VFIO_TYPE, VFIO_BASE + 9, * struct vfio_irq_info) * * Retrieve information about a device IRQ. Caller provides * struct vfio_irq_info with index value set. Caller sets argsz. * Implementation of IRQ mapping is bus driver specific. Indexes * using multiple IRQs are primarily intended to support MSI-like * interrupt blocks. Zero count irq blocks may be used to describe * unimplemented interrupt types. * * The EVENTFD flag indicates the interrupt index supports eventfd based * signaling. * * The MASKABLE flags indicates the index supports MASK and UNMASK * actions described below. * * AUTOMASKED indicates that after signaling, the interrupt line is * automatically masked by VFIO and the user needs to unmask the line * to receive new interrupts. This is primarily intended to distinguish * level triggered interrupts. * * The NORESIZE flag indicates that the interrupt lines within the index * are setup as a set and new subindexes cannot be enabled without first * disabling the entire index. This is used for interrupts like PCI MSI * and MSI-X where the driver may only use a subset of the available * indexes, but VFIO needs to enable a specific number of vectors * upfront. In the case of MSI-X, where the user can enable MSI-X and * then add and unmask vectors, it's up to userspace to make the decision * whether to allocate the maximum supported number of vectors or tear * down setup and incrementally increase the vectors as each is enabled. */ struct vfio_irq_info { __u32 argsz; __u32 flags; #define VFIO_IRQ_INFO_EVENTFD (1 << 0) #define VFIO_IRQ_INFO_MASKABLE (1 << 1) #define VFIO_IRQ_INFO_AUTOMASKED (1 << 2) #define VFIO_IRQ_INFO_NORESIZE (1 << 3) __u32 index; /* IRQ index */ __u32 count; /* Number of IRQs within this index */ }; #define VFIO_DEVICE_GET_IRQ_INFO _IO(VFIO_TYPE, VFIO_BASE + 9) /** * VFIO_DEVICE_SET_IRQS - _IOW(VFIO_TYPE, VFIO_BASE + 10, struct vfio_irq_set) * * Set signaling, masking, and unmasking of interrupts. Caller provides * struct vfio_irq_set with all fields set. 'start' and 'count' indicate * the range of subindexes being specified. * * The DATA flags specify the type of data provided. If DATA_NONE, the * operation performs the specified action immediately on the specified * interrupt(s). For example, to unmask AUTOMASKED interrupt [0,0]: * flags = (DATA_NONE|ACTION_UNMASK), index = 0, start = 0, count = 1. * * DATA_BOOL allows sparse support for the same on arrays of interrupts. * For example, to mask interrupts [0,1] and [0,3] (but not [0,2]): * flags = (DATA_BOOL|ACTION_MASK), index = 0, start = 1, count = 3, * data = {1,0,1} * * DATA_EVENTFD binds the specified ACTION to the provided __s32 eventfd. * A value of -1 can be used to either de-assign interrupts if already * assigned or skip un-assigned interrupts. For example, to set an eventfd * to be trigger for interrupts [0,0] and [0,2]: * flags = (DATA_EVENTFD|ACTION_TRIGGER), index = 0, start = 0, count = 3, * data = {fd1, -1, fd2} * If index [0,1] is previously set, two count = 1 ioctls calls would be * required to set [0,0] and [0,2] without changing [0,1]. * * Once a signaling mechanism is set, DATA_BOOL or DATA_NONE can be used * with ACTION_TRIGGER to perform kernel level interrupt loopback testing * from userspace (ie. simulate hardware triggering). * * Setting of an event triggering mechanism to userspace for ACTION_TRIGGER * enables the interrupt index for the device. Individual subindex interrupts * can be disabled using the -1 value for DATA_EVENTFD or the index can be * disabled as a whole with: flags = (DATA_NONE|ACTION_TRIGGER), count = 0. * * Note that ACTION_[UN]MASK specify user->kernel signaling (irqfds) while * ACTION_TRIGGER specifies kernel->user signaling. */ struct vfio_irq_set { __u32 argsz; __u32 flags; #define VFIO_IRQ_SET_DATA_NONE (1 << 0) /* Data not present */ #define VFIO_IRQ_SET_DATA_BOOL (1 << 1) /* Data is bool (u8) */ #define VFIO_IRQ_SET_DATA_EVENTFD (1 << 2) /* Data is eventfd (s32) */ #define VFIO_IRQ_SET_ACTION_MASK (1 << 3) /* Mask interrupt */ #define VFIO_IRQ_SET_ACTION_UNMASK (1 << 4) /* Unmask interrupt */ #define VFIO_IRQ_SET_ACTION_TRIGGER (1 << 5) /* Trigger interrupt */ __u32 index; __u32 start; __u32 count; __u8 data[]; }; #define VFIO_DEVICE_SET_IRQS _IO(VFIO_TYPE, VFIO_BASE + 10) #define VFIO_IRQ_SET_DATA_TYPE_MASK (VFIO_IRQ_SET_DATA_NONE | \ VFIO_IRQ_SET_DATA_BOOL | \ VFIO_IRQ_SET_DATA_EVENTFD) #define VFIO_IRQ_SET_ACTION_TYPE_MASK (VFIO_IRQ_SET_ACTION_MASK | \ VFIO_IRQ_SET_ACTION_UNMASK | \ VFIO_IRQ_SET_ACTION_TRIGGER) /** * VFIO_DEVICE_RESET - _IO(VFIO_TYPE, VFIO_BASE + 11) * * Reset a device. */ #define VFIO_DEVICE_RESET _IO(VFIO_TYPE, VFIO_BASE + 11) /* * The VFIO-PCI bus driver makes use of the following fixed region and * IRQ index mapping. Unimplemented regions return a size of zero. * Unimplemented IRQ types return a count of zero. */ enum { VFIO_PCI_BAR0_REGION_INDEX, VFIO_PCI_BAR1_REGION_INDEX, VFIO_PCI_BAR2_REGION_INDEX, VFIO_PCI_BAR3_REGION_INDEX, VFIO_PCI_BAR4_REGION_INDEX, VFIO_PCI_BAR5_REGION_INDEX, VFIO_PCI_ROM_REGION_INDEX, VFIO_PCI_CONFIG_REGION_INDEX, /* * Expose VGA regions defined for PCI base class 03, subclass 00. * This includes I/O port ranges 0x3b0 to 0x3bb and 0x3c0 to 0x3df * as well as the MMIO range 0xa0000 to 0xbffff. Each implemented * range is found at it's identity mapped offset from the region * offset, for example 0x3b0 is region_info.offset + 0x3b0. Areas * between described ranges are unimplemented. */ VFIO_PCI_VGA_REGION_INDEX, VFIO_PCI_NUM_REGIONS = 9 /* Fixed user ABI, region indexes >=9 use */ /* device specific cap to define content. */ }; enum { VFIO_PCI_INTX_IRQ_INDEX, VFIO_PCI_MSI_IRQ_INDEX, VFIO_PCI_MSIX_IRQ_INDEX, VFIO_PCI_ERR_IRQ_INDEX, VFIO_PCI_REQ_IRQ_INDEX, VFIO_PCI_NUM_IRQS }; /* * The vfio-ccw bus driver makes use of the following fixed region and * IRQ index mapping. Unimplemented regions return a size of zero. * Unimplemented IRQ types return a count of zero. */ enum { VFIO_CCW_CONFIG_REGION_INDEX, VFIO_CCW_NUM_REGIONS }; enum { VFIO_CCW_IO_IRQ_INDEX, VFIO_CCW_CRW_IRQ_INDEX, VFIO_CCW_REQ_IRQ_INDEX, VFIO_CCW_NUM_IRQS }; /** * VFIO_DEVICE_GET_PCI_HOT_RESET_INFO - _IORW(VFIO_TYPE, VFIO_BASE + 12, * struct vfio_pci_hot_reset_info) * * Return: 0 on success, -errno on failure: * -enospc = insufficient buffer, -enodev = unsupported for device. */ struct vfio_pci_dependent_device { __u32 group_id; __u16 segment; __u8 bus; __u8 devfn; /* Use PCI_SLOT/PCI_FUNC */ }; struct vfio_pci_hot_reset_info { __u32 argsz; __u32 flags; __u32 count; struct vfio_pci_dependent_device devices[]; }; #define VFIO_DEVICE_GET_PCI_HOT_RESET_INFO _IO(VFIO_TYPE, VFIO_BASE + 12) /** * VFIO_DEVICE_PCI_HOT_RESET - _IOW(VFIO_TYPE, VFIO_BASE + 13, * struct vfio_pci_hot_reset) * * Return: 0 on success, -errno on failure. */ struct vfio_pci_hot_reset { __u32 argsz; __u32 flags; __u32 count; __s32 group_fds[]; }; #define VFIO_DEVICE_PCI_HOT_RESET _IO(VFIO_TYPE, VFIO_BASE + 13) /** * VFIO_DEVICE_QUERY_GFX_PLANE - _IOW(VFIO_TYPE, VFIO_BASE + 14, * struct vfio_device_query_gfx_plane) * * Set the drm_plane_type and flags, then retrieve the gfx plane info. * * flags supported: * - VFIO_GFX_PLANE_TYPE_PROBE and VFIO_GFX_PLANE_TYPE_DMABUF are set * to ask if the mdev supports dma-buf. 0 on support, -EINVAL on no * support for dma-buf. * - VFIO_GFX_PLANE_TYPE_PROBE and VFIO_GFX_PLANE_TYPE_REGION are set * to ask if the mdev supports region. 0 on support, -EINVAL on no * support for region. * - VFIO_GFX_PLANE_TYPE_DMABUF or VFIO_GFX_PLANE_TYPE_REGION is set * with each call to query the plane info. * - Others are invalid and return -EINVAL. * * Note: * 1. Plane could be disabled by guest. In that case, success will be * returned with zero-initialized drm_format, size, width and height * fields. * 2. x_hot/y_hot is set to 0xFFFFFFFF if no hotspot information available * * Return: 0 on success, -errno on other failure. */ struct vfio_device_gfx_plane_info { __u32 argsz; __u32 flags; #define VFIO_GFX_PLANE_TYPE_PROBE (1 << 0) #define VFIO_GFX_PLANE_TYPE_DMABUF (1 << 1) #define VFIO_GFX_PLANE_TYPE_REGION (1 << 2) /* in */ __u32 drm_plane_type; /* type of plane: DRM_PLANE_TYPE_* */ /* out */ __u32 drm_format; /* drm format of plane */ __u64 drm_format_mod; /* tiled mode */ __u32 width; /* width of plane */ __u32 height; /* height of plane */ __u32 stride; /* stride of plane */ __u32 size; /* size of plane in bytes, align on page*/ __u32 x_pos; /* horizontal position of cursor plane */ __u32 y_pos; /* vertical position of cursor plane*/ __u32 x_hot; /* horizontal position of cursor hotspot */ __u32 y_hot; /* vertical position of cursor hotspot */ union { __u32 region_index; /* region index */ __u32 dmabuf_id; /* dma-buf id */ }; }; #define VFIO_DEVICE_QUERY_GFX_PLANE _IO(VFIO_TYPE, VFIO_BASE + 14) /** * VFIO_DEVICE_GET_GFX_DMABUF - _IOW(VFIO_TYPE, VFIO_BASE + 15, __u32) * * Return a new dma-buf file descriptor for an exposed guest framebuffer * described by the provided dmabuf_id. The dmabuf_id is returned from VFIO_ * DEVICE_QUERY_GFX_PLANE as a token of the exposed guest framebuffer. */ #define VFIO_DEVICE_GET_GFX_DMABUF _IO(VFIO_TYPE, VFIO_BASE + 15) /** * VFIO_DEVICE_IOEVENTFD - _IOW(VFIO_TYPE, VFIO_BASE + 16, * struct vfio_device_ioeventfd) * * Perform a write to the device at the specified device fd offset, with * the specified data and width when the provided eventfd is triggered. * vfio bus drivers may not support this for all regions, for all widths, * or at all. vfio-pci currently only enables support for BAR regions, * excluding the MSI-X vector table. * * Return: 0 on success, -errno on failure. */ struct vfio_device_ioeventfd { __u32 argsz; __u32 flags; #define VFIO_DEVICE_IOEVENTFD_8 (1 << 0) /* 1-byte write */ #define VFIO_DEVICE_IOEVENTFD_16 (1 << 1) /* 2-byte write */ #define VFIO_DEVICE_IOEVENTFD_32 (1 << 2) /* 4-byte write */ #define VFIO_DEVICE_IOEVENTFD_64 (1 << 3) /* 8-byte write */ #define VFIO_DEVICE_IOEVENTFD_SIZE_MASK (0xf) __u64 offset; /* device fd offset of write */ __u64 data; /* data to be written */ __s32 fd; /* -1 for de-assignment */ }; #define VFIO_DEVICE_IOEVENTFD _IO(VFIO_TYPE, VFIO_BASE + 16) /** * VFIO_DEVICE_FEATURE - _IORW(VFIO_TYPE, VFIO_BASE + 17, * struct vfio_device_feature) * * Get, set, or probe feature data of the device. The feature is selected * using the FEATURE_MASK portion of the flags field. Support for a feature * can be probed by setting both the FEATURE_MASK and PROBE bits. A probe * may optionally include the GET and/or SET bits to determine read vs write * access of the feature respectively. Probing a feature will return success * if the feature is supported and all of the optionally indicated GET/SET * methods are supported. The format of the data portion of the structure is * specific to the given feature. The data portion is not required for * probing. GET and SET are mutually exclusive, except for use with PROBE. * * Return 0 on success, -errno on failure. */ struct vfio_device_feature { __u32 argsz; __u32 flags; #define VFIO_DEVICE_FEATURE_MASK (0xffff) /* 16-bit feature index */ #define VFIO_DEVICE_FEATURE_GET (1 << 16) /* Get feature into data[] */ #define VFIO_DEVICE_FEATURE_SET (1 << 17) /* Set feature from data[] */ #define VFIO_DEVICE_FEATURE_PROBE (1 << 18) /* Probe feature support */ __u8 data[]; }; #define VFIO_DEVICE_FEATURE _IO(VFIO_TYPE, VFIO_BASE + 17) /* * Provide support for setting a PCI VF Token, which is used as a shared * secret between PF and VF drivers. This feature may only be set on a * PCI SR-IOV PF when SR-IOV is enabled on the PF and there are no existing * open VFs. Data provided when setting this feature is a 16-byte array * (__u8 b[16]), representing a UUID. */ #define VFIO_DEVICE_FEATURE_PCI_VF_TOKEN (0) /* -------- API for Type1 VFIO IOMMU -------- */ /** * VFIO_IOMMU_GET_INFO - _IOR(VFIO_TYPE, VFIO_BASE + 12, struct vfio_iommu_info) * * Retrieve information about the IOMMU object. Fills in provided * struct vfio_iommu_info. Caller sets argsz. * * XXX Should we do these by CHECK_EXTENSION too? */ struct vfio_iommu_type1_info { __u32 argsz; __u32 flags; #define VFIO_IOMMU_INFO_PGSIZES (1 << 0) /* supported page sizes info */ #define VFIO_IOMMU_INFO_CAPS (1 << 1) /* Info supports caps */ __u64 iova_pgsizes; /* Bitmap of supported page sizes */ __u32 cap_offset; /* Offset within info struct of first cap */ }; /* * The IOVA capability allows to report the valid IOVA range(s) * excluding any non-relaxable reserved regions exposed by * devices attached to the container. Any DMA map attempt * outside the valid iova range will return error. * * The structures below define version 1 of this capability. */ #define VFIO_IOMMU_TYPE1_INFO_CAP_IOVA_RANGE 1 struct vfio_iova_range { __u64 start; __u64 end; }; struct vfio_iommu_type1_info_cap_iova_range { struct vfio_info_cap_header header; __u32 nr_iovas; __u32 reserved; struct vfio_iova_range iova_ranges[]; }; /* * The migration capability allows to report supported features for migration. * * The structures below define version 1 of this capability. * * The existence of this capability indicates that IOMMU kernel driver supports * dirty page logging. * * pgsize_bitmap: Kernel driver returns bitmap of supported page sizes for dirty * page logging. * max_dirty_bitmap_size: Kernel driver returns maximum supported dirty bitmap * size in bytes that can be used by user applications when getting the dirty * bitmap. */ #define VFIO_IOMMU_TYPE1_INFO_CAP_MIGRATION 2 struct vfio_iommu_type1_info_cap_migration { struct vfio_info_cap_header header; __u32 flags; __u64 pgsize_bitmap; __u64 max_dirty_bitmap_size; /* in bytes */ }; /* * The DMA available capability allows to report the current number of * simultaneously outstanding DMA mappings that are allowed. * * The structure below defines version 1 of this capability. * * avail: specifies the current number of outstanding DMA mappings allowed. */ #define VFIO_IOMMU_TYPE1_INFO_DMA_AVAIL 3 struct vfio_iommu_type1_info_dma_avail { struct vfio_info_cap_header header; __u32 avail; }; #define VFIO_IOMMU_GET_INFO _IO(VFIO_TYPE, VFIO_BASE + 12) /** * VFIO_IOMMU_MAP_DMA - _IOW(VFIO_TYPE, VFIO_BASE + 13, struct vfio_dma_map) * * Map process virtual addresses to IO virtual addresses using the * provided struct vfio_dma_map. Caller sets argsz. READ &/ WRITE required. */ struct vfio_iommu_type1_dma_map { __u32 argsz; __u32 flags; #define VFIO_DMA_MAP_FLAG_READ (1 << 0) /* readable from device */ #define VFIO_DMA_MAP_FLAG_WRITE (1 << 1) /* writable from device */ __u64 vaddr; /* Process virtual address */ __u64 iova; /* IO virtual address */ __u64 size; /* Size of mapping (bytes) */ }; #define VFIO_IOMMU_MAP_DMA _IO(VFIO_TYPE, VFIO_BASE + 13) struct vfio_bitmap { __u64 pgsize; /* page size for bitmap in bytes */ __u64 size; /* in bytes */ __u64 *data; /* one bit per page */ }; /** * VFIO_IOMMU_UNMAP_DMA - _IOWR(VFIO_TYPE, VFIO_BASE + 14, * struct vfio_dma_unmap) * * Unmap IO virtual addresses using the provided struct vfio_dma_unmap. * Caller sets argsz. The actual unmapped size is returned in the size * field. No guarantee is made to the user that arbitrary unmaps of iova * or size different from those used in the original mapping call will * succeed. * VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP should be set to get the dirty bitmap * before unmapping IO virtual addresses. When this flag is set, the user must * provide a struct vfio_bitmap in data[]. User must provide zero-allocated * memory via vfio_bitmap.data and its size in the vfio_bitmap.size field. * A bit in the bitmap represents one page, of user provided page size in * vfio_bitmap.pgsize field, consecutively starting from iova offset. Bit set * indicates that the page at that offset from iova is dirty. A Bitmap of the * pages in the range of unmapped size is returned in the user-provided * vfio_bitmap.data. */ struct vfio_iommu_type1_dma_unmap { __u32 argsz; __u32 flags; #define VFIO_DMA_UNMAP_FLAG_GET_DIRTY_BITMAP (1 << 0) __u64 iova; /* IO virtual address */ __u64 size; /* Size of mapping (bytes) */ __u8 data[]; }; #define VFIO_IOMMU_UNMAP_DMA _IO(VFIO_TYPE, VFIO_BASE + 14) /* * IOCTLs to enable/disable IOMMU container usage. * No parameters are supported. */ #define VFIO_IOMMU_ENABLE _IO(VFIO_TYPE, VFIO_BASE + 15) #define VFIO_IOMMU_DISABLE _IO(VFIO_TYPE, VFIO_BASE + 16) /** * VFIO_IOMMU_DIRTY_PAGES - _IOWR(VFIO_TYPE, VFIO_BASE + 17, * struct vfio_iommu_type1_dirty_bitmap) * IOCTL is used for dirty pages logging. * Caller should set flag depending on which operation to perform, details as * below: * * Calling the IOCTL with VFIO_IOMMU_DIRTY_PAGES_FLAG_START flag set, instructs * the IOMMU driver to log pages that are dirtied or potentially dirtied by * the device; designed to be used when a migration is in progress. Dirty pages * are logged until logging is disabled by user application by calling the IOCTL * with VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP flag. * * Calling the IOCTL with VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP flag set, instructs * the IOMMU driver to stop logging dirtied pages. * * Calling the IOCTL with VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP flag set * returns the dirty pages bitmap for IOMMU container for a given IOVA range. * The user must specify the IOVA range and the pgsize through the structure * vfio_iommu_type1_dirty_bitmap_get in the data[] portion. This interface * supports getting a bitmap of the smallest supported pgsize only and can be * modified in future to get a bitmap of any specified supported pgsize. The * user must provide a zeroed memory area for the bitmap memory and specify its * size in bitmap.size. One bit is used to represent one page consecutively * starting from iova offset. The user should provide page size in bitmap.pgsize * field. A bit set in the bitmap indicates that the page at that offset from * iova is dirty. The caller must set argsz to a value including the size of * structure vfio_iommu_type1_dirty_bitmap_get, but excluding the size of the * actual bitmap. If dirty pages logging is not enabled, an error will be * returned. * * Only one of the flags _START, _STOP and _GET may be specified at a time. * */ struct vfio_iommu_type1_dirty_bitmap { __u32 argsz; __u32 flags; #define VFIO_IOMMU_DIRTY_PAGES_FLAG_START (1 << 0) #define VFIO_IOMMU_DIRTY_PAGES_FLAG_STOP (1 << 1) #define VFIO_IOMMU_DIRTY_PAGES_FLAG_GET_BITMAP (1 << 2) __u8 data[]; }; struct vfio_iommu_type1_dirty_bitmap_get { __u64 iova; /* IO virtual address */ __u64 size; /* Size of iova range */ struct vfio_bitmap bitmap; }; #define VFIO_IOMMU_DIRTY_PAGES _IO(VFIO_TYPE, VFIO_BASE + 17) /* -------- Additional API for SPAPR TCE (Server POWERPC) IOMMU -------- */ /* * The SPAPR TCE DDW info struct provides the information about * the details of Dynamic DMA window capability. * * @pgsizes contains a page size bitmask, 4K/64K/16M are supported. * @max_dynamic_windows_supported tells the maximum number of windows * which the platform can create. * @levels tells the maximum number of levels in multi-level IOMMU tables; * this allows splitting a table into smaller chunks which reduces * the amount of physically contiguous memory required for the table. */ struct vfio_iommu_spapr_tce_ddw_info { __u64 pgsizes; /* Bitmap of supported page sizes */ __u32 max_dynamic_windows_supported; __u32 levels; }; /* * The SPAPR TCE info struct provides the information about the PCI bus * address ranges available for DMA, these values are programmed into * the hardware so the guest has to know that information. * * The DMA 32 bit window start is an absolute PCI bus address. * The IOVA address passed via map/unmap ioctls are absolute PCI bus * addresses too so the window works as a filter rather than an offset * for IOVA addresses. * * Flags supported: * - VFIO_IOMMU_SPAPR_INFO_DDW: informs the userspace that dynamic DMA windows * (DDW) support is present. @ddw is only supported when DDW is present. */ struct vfio_iommu_spapr_tce_info { __u32 argsz; __u32 flags; #define VFIO_IOMMU_SPAPR_INFO_DDW (1 << 0) /* DDW supported */ __u32 dma32_window_start; /* 32 bit window start (bytes) */ __u32 dma32_window_size; /* 32 bit window size (bytes) */ struct vfio_iommu_spapr_tce_ddw_info ddw; }; #define VFIO_IOMMU_SPAPR_TCE_GET_INFO _IO(VFIO_TYPE, VFIO_BASE + 12) /* * EEH PE operation struct provides ways to: * - enable/disable EEH functionality; * - unfreeze IO/DMA for frozen PE; * - read PE state; * - reset PE; * - configure PE; * - inject EEH error. */ struct vfio_eeh_pe_err { __u32 type; __u32 func; __u64 addr; __u64 mask; }; struct vfio_eeh_pe_op { __u32 argsz; __u32 flags; __u32 op; union { struct vfio_eeh_pe_err err; }; }; #define VFIO_EEH_PE_DISABLE 0 /* Disable EEH functionality */ #define VFIO_EEH_PE_ENABLE 1 /* Enable EEH functionality */ #define VFIO_EEH_PE_UNFREEZE_IO 2 /* Enable IO for frozen PE */ #define VFIO_EEH_PE_UNFREEZE_DMA 3 /* Enable DMA for frozen PE */ #define VFIO_EEH_PE_GET_STATE 4 /* PE state retrieval */ #define VFIO_EEH_PE_STATE_NORMAL 0 /* PE in functional state */ #define VFIO_EEH_PE_STATE_RESET 1 /* PE reset in progress */ #define VFIO_EEH_PE_STATE_STOPPED 2 /* Stopped DMA and IO */ #define VFIO_EEH_PE_STATE_STOPPED_DMA 4 /* Stopped DMA only */ #define VFIO_EEH_PE_STATE_UNAVAIL 5 /* State unavailable */ #define VFIO_EEH_PE_RESET_DEACTIVATE 5 /* Deassert PE reset */ #define VFIO_EEH_PE_RESET_HOT 6 /* Assert hot reset */ #define VFIO_EEH_PE_RESET_FUNDAMENTAL 7 /* Assert fundamental reset */ #define VFIO_EEH_PE_CONFIGURE 8 /* PE configuration */ #define VFIO_EEH_PE_INJECT_ERR 9 /* Inject EEH error */ #define VFIO_EEH_PE_OP _IO(VFIO_TYPE, VFIO_BASE + 21) /** * VFIO_IOMMU_SPAPR_REGISTER_MEMORY - _IOW(VFIO_TYPE, VFIO_BASE + 17, struct vfio_iommu_spapr_register_memory) * * Registers user space memory where DMA is allowed. It pins * user pages and does the locked memory accounting so * subsequent VFIO_IOMMU_MAP_DMA/VFIO_IOMMU_UNMAP_DMA calls * get faster. */ struct vfio_iommu_spapr_register_memory { __u32 argsz; __u32 flags; __u64 vaddr; /* Process virtual address */ __u64 size; /* Size of mapping (bytes) */ }; #define VFIO_IOMMU_SPAPR_REGISTER_MEMORY _IO(VFIO_TYPE, VFIO_BASE + 17) /** * VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY - _IOW(VFIO_TYPE, VFIO_BASE + 18, struct vfio_iommu_spapr_register_memory) * * Unregisters user space memory registered with * VFIO_IOMMU_SPAPR_REGISTER_MEMORY. * Uses vfio_iommu_spapr_register_memory for parameters. */ #define VFIO_IOMMU_SPAPR_UNREGISTER_MEMORY _IO(VFIO_TYPE, VFIO_BASE + 18) /** * VFIO_IOMMU_SPAPR_TCE_CREATE - _IOWR(VFIO_TYPE, VFIO_BASE + 19, struct vfio_iommu_spapr_tce_create) * * Creates an additional TCE table and programs it (sets a new DMA window) * to every IOMMU group in the container. It receives page shift, window * size and number of levels in the TCE table being created. * * It allocates and returns an offset on a PCI bus of the new DMA window. */ struct vfio_iommu_spapr_tce_create { __u32 argsz; __u32 flags; /* in */ __u32 page_shift; __u32 __resv1; __u64 window_size; __u32 levels; __u32 __resv2; /* out */ __u64 start_addr; }; #define VFIO_IOMMU_SPAPR_TCE_CREATE _IO(VFIO_TYPE, VFIO_BASE + 19) /** * VFIO_IOMMU_SPAPR_TCE_REMOVE - _IOW(VFIO_TYPE, VFIO_BASE + 20, struct vfio_iommu_spapr_tce_remove) * * Unprograms a TCE table from all groups in the container and destroys it. * It receives a PCI bus offset as a window id. */ struct vfio_iommu_spapr_tce_remove { __u32 argsz; __u32 flags; /* in */ __u64 start_addr; }; #define VFIO_IOMMU_SPAPR_TCE_REMOVE _IO(VFIO_TYPE, VFIO_BASE + 20) /* ***************************************************************** */ #endif /* VFIO_H */ linux/tipc.h000064400000021171151027430560007020 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * include/uapi/linux/tipc.h: Header for TIPC socket interface * * Copyright (c) 2003-2006, 2015-2016 Ericsson AB * Copyright (c) 2005, 2010-2011, Wind River Systems * 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. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _LINUX_TIPC_H_ #define _LINUX_TIPC_H_ #include #include /* * TIPC addressing primitives */ struct tipc_socket_addr { __u32 ref; __u32 node; }; struct tipc_service_addr { __u32 type; __u32 instance; }; struct tipc_service_range { __u32 type; __u32 lower; __u32 upper; }; /* * Application-accessible service types */ #define TIPC_NODE_STATE 0 /* node state service type */ #define TIPC_TOP_SRV 1 /* topology server service type */ #define TIPC_LINK_STATE 2 /* link state service type */ #define TIPC_RESERVED_TYPES 64 /* lowest user-allowed service type */ /* * Publication scopes when binding service / service range */ enum tipc_scope { TIPC_CLUSTER_SCOPE = 2, /* 0 can also be used */ TIPC_NODE_SCOPE = 3 }; /* * Limiting values for messages */ #define TIPC_MAX_USER_MSG_SIZE 66000U /* * Message importance levels */ #define TIPC_LOW_IMPORTANCE 0 #define TIPC_MEDIUM_IMPORTANCE 1 #define TIPC_HIGH_IMPORTANCE 2 #define TIPC_CRITICAL_IMPORTANCE 3 /* * Msg rejection/connection shutdown reasons */ #define TIPC_OK 0 #define TIPC_ERR_NO_NAME 1 #define TIPC_ERR_NO_PORT 2 #define TIPC_ERR_NO_NODE 3 #define TIPC_ERR_OVERLOAD 4 #define TIPC_CONN_SHUTDOWN 5 /* * TIPC topology subscription service definitions */ #define TIPC_SUB_PORTS 0x01 /* filter: evt at each match */ #define TIPC_SUB_SERVICE 0x02 /* filter: evt at first up/last down */ #define TIPC_SUB_CANCEL 0x04 /* filter: cancel a subscription */ #define TIPC_WAIT_FOREVER (~0) /* timeout for permanent subscription */ struct tipc_subscr { struct tipc_service_range seq; /* range of interest */ __u32 timeout; /* subscription duration (in ms) */ __u32 filter; /* bitmask of filter options */ char usr_handle[8]; /* available for subscriber use */ }; #define TIPC_PUBLISHED 1 /* publication event */ #define TIPC_WITHDRAWN 2 /* withdrawal event */ #define TIPC_SUBSCR_TIMEOUT 3 /* subscription timeout event */ struct tipc_event { __u32 event; /* event type */ __u32 found_lower; /* matching range */ __u32 found_upper; /* " " */ struct tipc_socket_addr port; /* associated socket */ struct tipc_subscr s; /* associated subscription */ }; /* * Socket API */ #ifndef AF_TIPC #define AF_TIPC 30 #endif #ifndef PF_TIPC #define PF_TIPC AF_TIPC #endif #ifndef SOL_TIPC #define SOL_TIPC 271 #endif #define TIPC_ADDR_MCAST 1 #define TIPC_SERVICE_RANGE 1 #define TIPC_SERVICE_ADDR 2 #define TIPC_SOCKET_ADDR 3 struct sockaddr_tipc { unsigned short family; unsigned char addrtype; signed char scope; union { struct tipc_socket_addr id; struct tipc_service_range nameseq; struct { struct tipc_service_addr name; __u32 domain; } name; } addr; }; /* * Ancillary data objects supported by recvmsg() */ #define TIPC_ERRINFO 1 /* error info */ #define TIPC_RETDATA 2 /* returned data */ #define TIPC_DESTNAME 3 /* destination name */ /* * TIPC-specific socket option names */ #define TIPC_IMPORTANCE 127 /* Default: TIPC_LOW_IMPORTANCE */ #define TIPC_SRC_DROPPABLE 128 /* Default: based on socket type */ #define TIPC_DEST_DROPPABLE 129 /* Default: based on socket type */ #define TIPC_CONN_TIMEOUT 130 /* Default: 8000 (ms) */ #define TIPC_NODE_RECVQ_DEPTH 131 /* Default: none (read only) */ #define TIPC_SOCK_RECVQ_DEPTH 132 /* Default: none (read only) */ #define TIPC_MCAST_BROADCAST 133 /* Default: TIPC selects. No arg */ #define TIPC_MCAST_REPLICAST 134 /* Default: TIPC selects. No arg */ #define TIPC_GROUP_JOIN 135 /* Takes struct tipc_group_req* */ #define TIPC_GROUP_LEAVE 136 /* No argument */ #define TIPC_SOCK_RECVQ_USED 137 /* Default: none (read only) */ #define TIPC_NODELAY 138 /* Default: false */ /* * Flag values */ #define TIPC_GROUP_LOOPBACK 0x1 /* Receive copy of sent msg when match */ #define TIPC_GROUP_MEMBER_EVTS 0x2 /* Receive membership events in socket */ struct tipc_group_req { __u32 type; /* group id */ __u32 instance; /* member id */ __u32 scope; /* cluster/node */ __u32 flags; }; /* * Maximum sizes of TIPC bearer-related names (including terminating NULL) * The string formatting for each name element is: * media: media * interface: media:interface name * link: node:interface-node:interface */ #define TIPC_NODEID_LEN 16 #define TIPC_MAX_MEDIA_NAME 16 #define TIPC_MAX_IF_NAME 16 #define TIPC_MAX_BEARER_NAME 32 #define TIPC_MAX_LINK_NAME 68 #define SIOCGETLINKNAME SIOCPROTOPRIVATE #define SIOCGETNODEID (SIOCPROTOPRIVATE + 1) struct tipc_sioc_ln_req { __u32 peer; __u32 bearer_id; char linkname[TIPC_MAX_LINK_NAME]; }; struct tipc_sioc_nodeid_req { __u32 peer; char node_id[TIPC_NODEID_LEN]; }; /* * TIPC Crypto, AEAD */ #define TIPC_AEAD_ALG_NAME (32) struct tipc_aead_key { char alg_name[TIPC_AEAD_ALG_NAME]; unsigned int keylen; /* in bytes */ char key[]; }; #define TIPC_AEAD_KEYLEN_MIN (16 + 4) #define TIPC_AEAD_KEYLEN_MAX (32 + 4) #define TIPC_AEAD_KEY_SIZE_MAX (sizeof(struct tipc_aead_key) + \ TIPC_AEAD_KEYLEN_MAX) static __inline__ int tipc_aead_key_size(struct tipc_aead_key *key) { return sizeof(*key) + key->keylen; } #define TIPC_REKEYING_NOW (~0U) /* The macros and functions below are deprecated: */ #define TIPC_CFG_SRV 0 #define TIPC_ZONE_SCOPE 1 #define TIPC_ADDR_NAMESEQ 1 #define TIPC_ADDR_NAME 2 #define TIPC_ADDR_ID 3 #define TIPC_NODE_BITS 12 #define TIPC_CLUSTER_BITS 12 #define TIPC_ZONE_BITS 8 #define TIPC_NODE_OFFSET 0 #define TIPC_CLUSTER_OFFSET TIPC_NODE_BITS #define TIPC_ZONE_OFFSET (TIPC_CLUSTER_OFFSET + TIPC_CLUSTER_BITS) #define TIPC_NODE_SIZE ((1UL << TIPC_NODE_BITS) - 1) #define TIPC_CLUSTER_SIZE ((1UL << TIPC_CLUSTER_BITS) - 1) #define TIPC_ZONE_SIZE ((1UL << TIPC_ZONE_BITS) - 1) #define TIPC_NODE_MASK (TIPC_NODE_SIZE << TIPC_NODE_OFFSET) #define TIPC_CLUSTER_MASK (TIPC_CLUSTER_SIZE << TIPC_CLUSTER_OFFSET) #define TIPC_ZONE_MASK (TIPC_ZONE_SIZE << TIPC_ZONE_OFFSET) #define TIPC_ZONE_CLUSTER_MASK (TIPC_ZONE_MASK | TIPC_CLUSTER_MASK) #define tipc_portid tipc_socket_addr #define tipc_name tipc_service_addr #define tipc_name_seq tipc_service_range static __inline__ __u32 tipc_addr(unsigned int zone, unsigned int cluster, unsigned int node) { return (zone << TIPC_ZONE_OFFSET) | (cluster << TIPC_CLUSTER_OFFSET) | node; } static __inline__ unsigned int tipc_zone(__u32 addr) { return addr >> TIPC_ZONE_OFFSET; } static __inline__ unsigned int tipc_cluster(__u32 addr) { return (addr & TIPC_CLUSTER_MASK) >> TIPC_CLUSTER_OFFSET; } static __inline__ unsigned int tipc_node(__u32 addr) { return addr & TIPC_NODE_MASK; } #endif linux/phonet.h000064400000011105151027430560007352 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /** * file phonet.h * * Phonet sockets kernel interface * * Copyright (C) 2008 Nokia Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef LINUX_PHONET_H #define LINUX_PHONET_H #include #include /* Automatic protocol selection */ #define PN_PROTO_TRANSPORT 0 /* Phonet datagram socket */ #define PN_PROTO_PHONET 1 /* Phonet pipe */ #define PN_PROTO_PIPE 2 #define PHONET_NPROTO 3 /* Socket options for SOL_PNPIPE level */ #define PNPIPE_ENCAP 1 #define PNPIPE_IFINDEX 2 #define PNPIPE_HANDLE 3 #define PNPIPE_INITSTATE 4 #define PNADDR_ANY 0 #define PNADDR_BROADCAST 0xFC #define PNPORT_RESOURCE_ROUTING 0 /* Values for PNPIPE_ENCAP option */ #define PNPIPE_ENCAP_NONE 0 #define PNPIPE_ENCAP_IP 1 /* ioctls */ #define SIOCPNGETOBJECT (SIOCPROTOPRIVATE + 0) #define SIOCPNENABLEPIPE (SIOCPROTOPRIVATE + 13) #define SIOCPNADDRESOURCE (SIOCPROTOPRIVATE + 14) #define SIOCPNDELRESOURCE (SIOCPROTOPRIVATE + 15) /* Phonet protocol header */ struct phonethdr { __u8 pn_rdev; __u8 pn_sdev; __u8 pn_res; __be16 pn_length; __u8 pn_robj; __u8 pn_sobj; } __attribute__((packed)); /* Common Phonet payload header */ struct phonetmsg { __u8 pn_trans_id; /* transaction ID */ __u8 pn_msg_id; /* message type */ union { struct { __u8 pn_submsg_id; /* message subtype */ __u8 pn_data[5]; } base; struct { __u16 pn_e_res_id; /* extended resource ID */ __u8 pn_e_submsg_id; /* message subtype */ __u8 pn_e_data[3]; } ext; } pn_msg_u; }; #define PN_COMMON_MESSAGE 0xF0 #define PN_COMMGR 0x10 #define PN_PREFIX 0xE0 /* resource for extended messages */ #define pn_submsg_id pn_msg_u.base.pn_submsg_id #define pn_e_submsg_id pn_msg_u.ext.pn_e_submsg_id #define pn_e_res_id pn_msg_u.ext.pn_e_res_id #define pn_data pn_msg_u.base.pn_data #define pn_e_data pn_msg_u.ext.pn_e_data /* data for unreachable errors */ #define PN_COMM_SERVICE_NOT_IDENTIFIED_RESP 0x01 #define PN_COMM_ISA_ENTITY_NOT_REACHABLE_RESP 0x14 #define pn_orig_msg_id pn_data[0] #define pn_status pn_data[1] #define pn_e_orig_msg_id pn_e_data[0] #define pn_e_status pn_e_data[1] /* Phonet socket address structure */ struct sockaddr_pn { __kernel_sa_family_t spn_family; __u8 spn_obj; __u8 spn_dev; __u8 spn_resource; __u8 spn_zero[sizeof(struct sockaddr) - sizeof(__kernel_sa_family_t) - 3]; } __attribute__((packed)); /* Well known address */ #define PN_DEV_PC 0x10 static __inline__ __u16 pn_object(__u8 addr, __u16 port) { return (addr << 8) | (port & 0x3ff); } static __inline__ __u8 pn_obj(__u16 handle) { return handle & 0xff; } static __inline__ __u8 pn_dev(__u16 handle) { return handle >> 8; } static __inline__ __u16 pn_port(__u16 handle) { return handle & 0x3ff; } static __inline__ __u8 pn_addr(__u16 handle) { return (handle >> 8) & 0xfc; } static __inline__ void pn_sockaddr_set_addr(struct sockaddr_pn *spn, __u8 addr) { spn->spn_dev &= 0x03; spn->spn_dev |= addr & 0xfc; } static __inline__ void pn_sockaddr_set_port(struct sockaddr_pn *spn, __u16 port) { spn->spn_dev &= 0xfc; spn->spn_dev |= (port >> 8) & 0x03; spn->spn_obj = port & 0xff; } static __inline__ void pn_sockaddr_set_object(struct sockaddr_pn *spn, __u16 handle) { spn->spn_dev = pn_dev(handle); spn->spn_obj = pn_obj(handle); } static __inline__ void pn_sockaddr_set_resource(struct sockaddr_pn *spn, __u8 resource) { spn->spn_resource = resource; } static __inline__ __u8 pn_sockaddr_get_addr(const struct sockaddr_pn *spn) { return spn->spn_dev & 0xfc; } static __inline__ __u16 pn_sockaddr_get_port(const struct sockaddr_pn *spn) { return ((spn->spn_dev & 0x03) << 8) | spn->spn_obj; } static __inline__ __u16 pn_sockaddr_get_object(const struct sockaddr_pn *spn) { return pn_object(spn->spn_dev, spn->spn_obj); } static __inline__ __u8 pn_sockaddr_get_resource(const struct sockaddr_pn *spn) { return spn->spn_resource; } /* Phonet device ioctl requests */ #endif /* LINUX_PHONET_H */ linux/version.h000064400000000656151027430560007553 0ustar00#define LINUX_VERSION_CODE 266752 #define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c)) #define RHEL_MAJOR 8 #define RHEL_MINOR 10 #define RHEL_RELEASE_VERSION(a,b) (((a) << 8) + (b)) #define RHEL_RELEASE_CODE 2058 #define RHEL_RELEASE "553.81.1" #define LINUX_VERSION_MAJOR 4 #define LINUX_VERSION_PATCHLEVEL 18 #define LINUX_VERSION_SUBLEVEL 0 #define KERNEL_HEADERS_CHECKSUM "ea6cbf40c5ca102e2767b8057b08120d97f31640" linux/falloc.h000064400000007000151027430560007314 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _FALLOC_H_ #define _FALLOC_H_ #define FALLOC_FL_KEEP_SIZE 0x01 /* default is extend size */ #define FALLOC_FL_PUNCH_HOLE 0x02 /* de-allocates range */ #define FALLOC_FL_NO_HIDE_STALE 0x04 /* reserved codepoint */ /* * FALLOC_FL_COLLAPSE_RANGE is used to remove a range of a file * without leaving a hole in the file. The contents of the file beyond * the range being removed is appended to the start offset of the range * being removed (i.e. the hole that was punched is "collapsed"), * resulting in a file layout that looks like the range that was * removed never existed. As such collapsing a range of a file changes * the size of the file, reducing it by the same length of the range * that has been removed by the operation. * * Different filesystems may implement different limitations on the * granularity of the operation. Most will limit operations to * filesystem block size boundaries, but this boundary may be larger or * smaller depending on the filesystem and/or the configuration of the * filesystem or file. * * Attempting to collapse a range that crosses the end of the file is * considered an illegal operation - just use ftruncate(2) if you need * to collapse a range that crosses EOF. */ #define FALLOC_FL_COLLAPSE_RANGE 0x08 /* * FALLOC_FL_ZERO_RANGE is used to convert a range of file to zeros preferably * without issuing data IO. Blocks should be preallocated for the regions that * span holes in the file, and the entire range is preferable converted to * unwritten extents - even though file system may choose to zero out the * extent or do whatever which will result in reading zeros from the range * while the range remains allocated for the file. * * This can be also used to preallocate blocks past EOF in the same way as * with fallocate. Flag FALLOC_FL_KEEP_SIZE should cause the inode * size to remain the same. */ #define FALLOC_FL_ZERO_RANGE 0x10 /* * FALLOC_FL_INSERT_RANGE is use to insert space within the file size without * overwriting any existing data. The contents of the file beyond offset are * shifted towards right by len bytes to create a hole. As such, this * operation will increase the size of the file by len bytes. * * Different filesystems may implement different limitations on the granularity * of the operation. Most will limit operations to filesystem block size * boundaries, but this boundary may be larger or smaller depending on * the filesystem and/or the configuration of the filesystem or file. * * Attempting to insert space using this flag at OR beyond the end of * the file is considered an illegal operation - just use ftruncate(2) or * fallocate(2) with mode 0 for such type of operations. */ #define FALLOC_FL_INSERT_RANGE 0x20 /* * FALLOC_FL_UNSHARE_RANGE is used to unshare shared blocks within the * file size without overwriting any existing data. The purpose of this * call is to preemptively reallocate any blocks that are subject to * copy-on-write. * * Different filesystems may implement different limitations on the * granularity of the operation. Most will limit operations to filesystem * block size boundaries, but this boundary may be larger or smaller * depending on the filesystem and/or the configuration of the filesystem * or file. * * This flag can only be used with allocate-mode fallocate, which is * to say that it cannot be used with the punch, zero, collapse, or * insert range modes. */ #define FALLOC_FL_UNSHARE_RANGE 0x40 #endif /* _FALLOC_H_ */ linux/membarrier.h000064400000017333151027430560010213 0ustar00#ifndef _LINUX_MEMBARRIER_H #define _LINUX_MEMBARRIER_H /* * linux/membarrier.h * * membarrier system call API * * Copyright (c) 2010, 2015 Mathieu Desnoyers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * enum membarrier_cmd - membarrier system call command * @MEMBARRIER_CMD_QUERY: Query the set of supported commands. It returns * a bitmask of valid commands. * @MEMBARRIER_CMD_GLOBAL: Execute a memory barrier on all running threads. * Upon return from system call, the caller thread * is ensured that all running threads have passed * through a state where all memory accesses to * user-space addresses match program order between * entry to and return from the system call * (non-running threads are de facto in such a * state). This covers threads from all processes * running on the system. This command returns 0. * @MEMBARRIER_CMD_GLOBAL_EXPEDITED: * Execute a memory barrier on all running threads * of all processes which previously registered * with MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED. * Upon return from system call, the caller thread * is ensured that all running threads have passed * through a state where all memory accesses to * user-space addresses match program order between * entry to and return from the system call * (non-running threads are de facto in such a * state). This only covers threads from processes * which registered with * MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED. * This command returns 0. Given that * registration is about the intent to receive * the barriers, it is valid to invoke * MEMBARRIER_CMD_GLOBAL_EXPEDITED from a * non-registered process. * @MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED: * Register the process intent to receive * MEMBARRIER_CMD_GLOBAL_EXPEDITED memory * barriers. Always returns 0. * @MEMBARRIER_CMD_PRIVATE_EXPEDITED: * Execute a memory barrier on each running * thread belonging to the same process as the current * thread. Upon return from system call, the * caller thread is ensured that all its running * threads siblings have passed through a state * where all memory accesses to user-space * addresses match program order between entry * to and return from the system call * (non-running threads are de facto in such a * state). This only covers threads from the * same process as the caller thread. This * command returns 0 on success. The * "expedited" commands complete faster than * the non-expedited ones, they never block, * but have the downside of causing extra * overhead. A process needs to register its * intent to use the private expedited command * prior to using it, otherwise this command * returns -EPERM. * @MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED: * Register the process intent to use * MEMBARRIER_CMD_PRIVATE_EXPEDITED. Always * returns 0. * @MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE: * In addition to provide memory ordering * guarantees described in * MEMBARRIER_CMD_PRIVATE_EXPEDITED, ensure * the caller thread, upon return from system * call, that all its running threads siblings * have executed a core serializing * instruction. (architectures are required to * guarantee that non-running threads issue * core serializing instructions before they * resume user-space execution). This only * covers threads from the same process as the * caller thread. This command returns 0 on * success. The "expedited" commands complete * faster than the non-expedited ones, they * never block, but have the downside of * causing extra overhead. If this command is * not implemented by an architecture, -EINVAL * is returned. A process needs to register its * intent to use the private expedited sync * core command prior to using it, otherwise * this command returns -EPERM. * @MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE: * Register the process intent to use * MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE. * If this command is not implemented by an * architecture, -EINVAL is returned. * Returns 0 on success. * @MEMBARRIER_CMD_SHARED: * Alias to MEMBARRIER_CMD_GLOBAL. Provided for * header backward compatibility. * * Command to be passed to the membarrier system call. The commands need to * be a single bit each, except for MEMBARRIER_CMD_QUERY which is assigned to * the value 0. */ enum membarrier_cmd { MEMBARRIER_CMD_QUERY = 0, MEMBARRIER_CMD_GLOBAL = (1 << 0), MEMBARRIER_CMD_GLOBAL_EXPEDITED = (1 << 1), MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED = (1 << 2), MEMBARRIER_CMD_PRIVATE_EXPEDITED = (1 << 3), MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED = (1 << 4), MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE = (1 << 5), MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE = (1 << 6), /* Alias for header backward compatibility. */ MEMBARRIER_CMD_SHARED = MEMBARRIER_CMD_GLOBAL, }; #endif /* _LINUX_MEMBARRIER_H */ linux/atmbr2684.h000064400000006307151027430560007516 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_ATMBR2684_H #define _LINUX_ATMBR2684_H #include #include #include /* For IFNAMSIZ */ /* * Type of media we're bridging (ethernet, token ring, etc) Currently only * ethernet is supported */ #define BR2684_MEDIA_ETHERNET (0) /* 802.3 */ #define BR2684_MEDIA_802_4 (1) /* 802.4 */ #define BR2684_MEDIA_TR (2) /* 802.5 - token ring */ #define BR2684_MEDIA_FDDI (3) #define BR2684_MEDIA_802_6 (4) /* 802.6 */ /* used only at device creation: */ #define BR2684_FLAG_ROUTED (1<<16) /* payload is routed, not bridged */ /* * Is there FCS inbound on this VC? This currently isn't supported. */ #define BR2684_FCSIN_NO (0) #define BR2684_FCSIN_IGNORE (1) #define BR2684_FCSIN_VERIFY (2) /* * Is there FCS outbound on this VC? This currently isn't supported. */ #define BR2684_FCSOUT_NO (0) #define BR2684_FCSOUT_SENDZERO (1) #define BR2684_FCSOUT_GENERATE (2) /* * Does this VC include LLC encapsulation? */ #define BR2684_ENCAPS_VC (0) /* VC-mux */ #define BR2684_ENCAPS_LLC (1) #define BR2684_ENCAPS_AUTODETECT (2) /* Unsuported */ /* * Is this VC bridged or routed? */ #define BR2684_PAYLOAD_ROUTED (0) #define BR2684_PAYLOAD_BRIDGED (1) /* * This is for the ATM_NEWBACKENDIF call - these are like socket families: * the first element of the structure is the backend number and the rest * is per-backend specific */ struct atm_newif_br2684 { atm_backend_t backend_num; /* ATM_BACKEND_BR2684 */ int media; /* BR2684_MEDIA_*, flags in upper bits */ char ifname[IFNAMSIZ]; int mtu; }; /* * This structure is used to specify a br2684 interface - either by a * positive integer (returned by ATM_NEWBACKENDIF) or the interfaces name */ #define BR2684_FIND_BYNOTHING (0) #define BR2684_FIND_BYNUM (1) #define BR2684_FIND_BYIFNAME (2) struct br2684_if_spec { int method; /* BR2684_FIND_* */ union { char ifname[IFNAMSIZ]; int devnum; } spec; }; /* * This is for the ATM_SETBACKEND call - these are like socket families: * the first element of the structure is the backend number and the rest * is per-backend specific */ struct atm_backend_br2684 { atm_backend_t backend_num; /* ATM_BACKEND_BR2684 */ struct br2684_if_spec ifspec; int fcs_in; /* BR2684_FCSIN_* */ int fcs_out; /* BR2684_FCSOUT_* */ int fcs_auto; /* 1: fcs_{in,out} disabled if no FCS rx'ed */ int encaps; /* BR2684_ENCAPS_* */ int has_vpiid; /* 1: use vpn_id - Unsupported */ __u8 vpn_id[7]; int send_padding; /* unsupported */ int min_size; /* we will pad smaller packets than this */ }; /* * The BR2684_SETFILT ioctl is an experimental mechanism for folks * terminating a large number of IP-only vcc's. When netfilter allows * efficient per-if in/out filters, this support will be removed */ struct br2684_filter { __be32 prefix; /* network byte order */ __be32 netmask; /* 0 = disable filter */ }; struct br2684_filter_set { struct br2684_if_spec ifspec; struct br2684_filter filter; }; enum br2684_payload { p_routed = BR2684_PAYLOAD_ROUTED, p_bridged = BR2684_PAYLOAD_BRIDGED, }; #define BR2684_SETFILT _IOW( 'a', ATMIOC_BACKEND + 0, \ struct br2684_filter_set) #endif /* _LINUX_ATMBR2684_H */ linux/nilfs2_api.h000064400000016645151027430560010121 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * nilfs2_api.h - NILFS2 user space API * * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. */ #ifndef _LINUX_NILFS2_API_H #define _LINUX_NILFS2_API_H #include #include /** * struct nilfs_cpinfo - checkpoint information * @ci_flags: flags * @ci_pad: padding * @ci_cno: checkpoint number * @ci_create: creation timestamp * @ci_nblk_inc: number of blocks incremented by this checkpoint * @ci_inodes_count: inodes count * @ci_blocks_count: blocks count * @ci_next: next checkpoint number in snapshot list */ struct nilfs_cpinfo { __u32 ci_flags; __u32 ci_pad; __u64 ci_cno; __u64 ci_create; __u64 ci_nblk_inc; __u64 ci_inodes_count; __u64 ci_blocks_count; __u64 ci_next; }; /* checkpoint flags */ enum { NILFS_CPINFO_SNAPSHOT, NILFS_CPINFO_INVALID, NILFS_CPINFO_SKETCH, NILFS_CPINFO_MINOR, }; #define NILFS_CPINFO_FNS(flag, name) \ static __inline__ int \ nilfs_cpinfo_##name(const struct nilfs_cpinfo *cpinfo) \ { \ return !!(cpinfo->ci_flags & (1UL << NILFS_CPINFO_##flag)); \ } NILFS_CPINFO_FNS(SNAPSHOT, snapshot) NILFS_CPINFO_FNS(INVALID, invalid) NILFS_CPINFO_FNS(MINOR, minor) /** * nilfs_suinfo - segment usage information * @sui_lastmod: timestamp of last modification * @sui_nblocks: number of written blocks in segment * @sui_flags: segment usage flags */ struct nilfs_suinfo { __u64 sui_lastmod; __u32 sui_nblocks; __u32 sui_flags; }; /* segment usage flags */ enum { NILFS_SUINFO_ACTIVE, NILFS_SUINFO_DIRTY, NILFS_SUINFO_ERROR, }; #define NILFS_SUINFO_FNS(flag, name) \ static __inline__ int \ nilfs_suinfo_##name(const struct nilfs_suinfo *si) \ { \ return si->sui_flags & (1UL << NILFS_SUINFO_##flag); \ } NILFS_SUINFO_FNS(ACTIVE, active) NILFS_SUINFO_FNS(DIRTY, dirty) NILFS_SUINFO_FNS(ERROR, error) static __inline__ int nilfs_suinfo_clean(const struct nilfs_suinfo *si) { return !si->sui_flags; } /** * nilfs_suinfo_update - segment usage information update * @sup_segnum: segment number * @sup_flags: flags for which fields are active in sup_sui * @sup_reserved: reserved necessary for alignment * @sup_sui: segment usage information */ struct nilfs_suinfo_update { __u64 sup_segnum; __u32 sup_flags; __u32 sup_reserved; struct nilfs_suinfo sup_sui; }; enum { NILFS_SUINFO_UPDATE_LASTMOD, NILFS_SUINFO_UPDATE_NBLOCKS, NILFS_SUINFO_UPDATE_FLAGS, __NR_NILFS_SUINFO_UPDATE_FIELDS, }; #define NILFS_SUINFO_UPDATE_FNS(flag, name) \ static __inline__ void \ nilfs_suinfo_update_set_##name(struct nilfs_suinfo_update *sup) \ { \ sup->sup_flags |= 1UL << NILFS_SUINFO_UPDATE_##flag; \ } \ static __inline__ void \ nilfs_suinfo_update_clear_##name(struct nilfs_suinfo_update *sup) \ { \ sup->sup_flags &= ~(1UL << NILFS_SUINFO_UPDATE_##flag); \ } \ static __inline__ int \ nilfs_suinfo_update_##name(const struct nilfs_suinfo_update *sup) \ { \ return !!(sup->sup_flags & (1UL << NILFS_SUINFO_UPDATE_##flag));\ } NILFS_SUINFO_UPDATE_FNS(LASTMOD, lastmod) NILFS_SUINFO_UPDATE_FNS(NBLOCKS, nblocks) NILFS_SUINFO_UPDATE_FNS(FLAGS, flags) enum { NILFS_CHECKPOINT, NILFS_SNAPSHOT, }; /** * struct nilfs_cpmode - change checkpoint mode structure * @cm_cno: checkpoint number * @cm_mode: mode of checkpoint * @cm_pad: padding */ struct nilfs_cpmode { __u64 cm_cno; __u32 cm_mode; __u32 cm_pad; }; /** * struct nilfs_argv - argument vector * @v_base: pointer on data array from userspace * @v_nmembs: number of members in data array * @v_size: size of data array in bytes * @v_flags: flags * @v_index: start number of target data items */ struct nilfs_argv { __u64 v_base; __u32 v_nmembs; /* number of members */ __u16 v_size; /* size of members */ __u16 v_flags; __u64 v_index; }; /** * struct nilfs_period - period of checkpoint numbers * @p_start: start checkpoint number (inclusive) * @p_end: end checkpoint number (exclusive) */ struct nilfs_period { __u64 p_start; __u64 p_end; }; /** * struct nilfs_cpstat - checkpoint statistics * @cs_cno: checkpoint number * @cs_ncps: number of checkpoints * @cs_nsss: number of snapshots */ struct nilfs_cpstat { __u64 cs_cno; __u64 cs_ncps; __u64 cs_nsss; }; /** * struct nilfs_sustat - segment usage statistics * @ss_nsegs: number of segments * @ss_ncleansegs: number of clean segments * @ss_ndirtysegs: number of dirty segments * @ss_ctime: creation time of the last segment * @ss_nongc_ctime: creation time of the last segment not for GC * @ss_prot_seq: least sequence number of segments which must not be reclaimed */ struct nilfs_sustat { __u64 ss_nsegs; __u64 ss_ncleansegs; __u64 ss_ndirtysegs; __u64 ss_ctime; __u64 ss_nongc_ctime; __u64 ss_prot_seq; }; /** * struct nilfs_vinfo - virtual block number information * @vi_vblocknr: virtual block number * @vi_start: start checkpoint number (inclusive) * @vi_end: end checkpoint number (exclusive) * @vi_blocknr: disk block number */ struct nilfs_vinfo { __u64 vi_vblocknr; __u64 vi_start; __u64 vi_end; __u64 vi_blocknr; }; /** * struct nilfs_vdesc - descriptor of virtual block number * @vd_ino: inode number * @vd_cno: checkpoint number * @vd_vblocknr: virtual block number * @vd_period: period of checkpoint numbers * @vd_blocknr: disk block number * @vd_offset: logical block offset inside a file * @vd_flags: flags (data or node block) * @vd_pad: padding */ struct nilfs_vdesc { __u64 vd_ino; __u64 vd_cno; __u64 vd_vblocknr; struct nilfs_period vd_period; __u64 vd_blocknr; __u64 vd_offset; __u32 vd_flags; __u32 vd_pad; }; /** * struct nilfs_bdesc - descriptor of disk block number * @bd_ino: inode number * @bd_oblocknr: disk block address (for skipping dead blocks) * @bd_blocknr: disk block address * @bd_offset: logical block offset inside a file * @bd_level: level in the b-tree organization * @bd_pad: padding */ struct nilfs_bdesc { __u64 bd_ino; __u64 bd_oblocknr; __u64 bd_blocknr; __u64 bd_offset; __u32 bd_level; __u32 bd_pad; }; #define NILFS_IOCTL_IDENT 'n' #define NILFS_IOCTL_CHANGE_CPMODE \ _IOW(NILFS_IOCTL_IDENT, 0x80, struct nilfs_cpmode) #define NILFS_IOCTL_DELETE_CHECKPOINT \ _IOW(NILFS_IOCTL_IDENT, 0x81, __u64) #define NILFS_IOCTL_GET_CPINFO \ _IOR(NILFS_IOCTL_IDENT, 0x82, struct nilfs_argv) #define NILFS_IOCTL_GET_CPSTAT \ _IOR(NILFS_IOCTL_IDENT, 0x83, struct nilfs_cpstat) #define NILFS_IOCTL_GET_SUINFO \ _IOR(NILFS_IOCTL_IDENT, 0x84, struct nilfs_argv) #define NILFS_IOCTL_GET_SUSTAT \ _IOR(NILFS_IOCTL_IDENT, 0x85, struct nilfs_sustat) #define NILFS_IOCTL_GET_VINFO \ _IOWR(NILFS_IOCTL_IDENT, 0x86, struct nilfs_argv) #define NILFS_IOCTL_GET_BDESCS \ _IOWR(NILFS_IOCTL_IDENT, 0x87, struct nilfs_argv) #define NILFS_IOCTL_CLEAN_SEGMENTS \ _IOW(NILFS_IOCTL_IDENT, 0x88, struct nilfs_argv[5]) #define NILFS_IOCTL_SYNC \ _IOR(NILFS_IOCTL_IDENT, 0x8A, __u64) #define NILFS_IOCTL_RESIZE \ _IOW(NILFS_IOCTL_IDENT, 0x8B, __u64) #define NILFS_IOCTL_SET_ALLOC_RANGE \ _IOW(NILFS_IOCTL_IDENT, 0x8C, __u64[2]) #define NILFS_IOCTL_SET_SUINFO \ _IOW(NILFS_IOCTL_IDENT, 0x8D, struct nilfs_argv) #endif /* _LINUX_NILFS2_API_H */ linux/v4l2-dv-timings.h000064400000075512151027430560010737 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * V4L2 DV timings header. * * Copyright (C) 2012-2016 Hans Verkuil * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #ifndef _V4L2_DV_TIMINGS_H #define _V4L2_DV_TIMINGS_H #if __GNUC__ < 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ < 6)) /* Sadly gcc versions older than 4.6 have a bug in how they initialize anonymous unions where they require additional curly brackets. This violates the C1x standard. This workaround adds the curly brackets if needed. */ #define V4L2_INIT_BT_TIMINGS(_width, args...) \ { .bt = { _width , ## args } } #else #define V4L2_INIT_BT_TIMINGS(_width, args...) \ .bt = { _width , ## args } #endif /* CEA-861-F timings (i.e. standard HDTV timings) */ #define V4L2_DV_BT_CEA_640X480P59_94 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(640, 480, 0, 0, \ 25175000, 16, 96, 48, 10, 2, 33, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 1) \ } /* Note: these are the nominal timings, for HDMI links this format is typically * double-clocked to meet the minimum pixelclock requirements. */ #define V4L2_DV_BT_CEA_720X480I59_94 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(720, 480, 1, 0, \ 13500000, 19, 62, 57, 4, 3, 15, 4, 3, 16, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_HALF_LINE | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_PICTURE_ASPECT | V4L2_DV_FL_HAS_CEA861_VIC, \ { 4, 3 }, 6) \ } #define V4L2_DV_BT_CEA_720X480P59_94 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(720, 480, 0, 0, \ 27000000, 16, 62, 60, 9, 6, 30, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_PICTURE_ASPECT | \ V4L2_DV_FL_HAS_CEA861_VIC, { 4, 3 }, 2) \ } /* Note: these are the nominal timings, for HDMI links this format is typically * double-clocked to meet the minimum pixelclock requirements. */ #define V4L2_DV_BT_CEA_720X576I50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(720, 576, 1, 0, \ 13500000, 12, 63, 69, 2, 3, 19, 2, 3, 20, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_HALF_LINE | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_PICTURE_ASPECT | V4L2_DV_FL_HAS_CEA861_VIC, \ { 4, 3 }, 21) \ } #define V4L2_DV_BT_CEA_720X576P50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(720, 576, 0, 0, \ 27000000, 12, 64, 68, 5, 5, 39, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_PICTURE_ASPECT | \ V4L2_DV_FL_HAS_CEA861_VIC, { 4, 3 }, 17) \ } #define V4L2_DV_BT_CEA_1280X720P24 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 720, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 59400000, 1760, 40, 220, 5, 5, 20, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 60) \ } #define V4L2_DV_BT_CEA_1280X720P25 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 720, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 2420, 40, 220, 5, 5, 20, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 61) \ } #define V4L2_DV_BT_CEA_1280X720P30 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 720, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 1760, 40, 220, 5, 5, 20, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 62) \ } #define V4L2_DV_BT_CEA_1280X720P50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 720, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 440, 40, 220, 5, 5, 20, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 19) \ } #define V4L2_DV_BT_CEA_1280X720P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 720, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 110, 40, 220, 5, 5, 20, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 4) \ } #define V4L2_DV_BT_CEA_1920X1080P24 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 638, 44, 148, 4, 5, 36, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 32) \ } #define V4L2_DV_BT_CEA_1920X1080P25 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 528, 44, 148, 4, 5, 36, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 33) \ } #define V4L2_DV_BT_CEA_1920X1080P30 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 88, 44, 148, 4, 5, 36, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 34) \ } #define V4L2_DV_BT_CEA_1920X1080I50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 1, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 528, 44, 148, 2, 5, 15, 2, 5, 16, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_HALF_LINE | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 20) \ } #define V4L2_DV_BT_CEA_1920X1080P50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 148500000, 528, 44, 148, 4, 5, 36, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 31) \ } #define V4L2_DV_BT_CEA_1920X1080I60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 1, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 74250000, 88, 44, 148, 2, 5, 15, 2, 5, 16, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | \ V4L2_DV_FL_HALF_LINE | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 5) \ } #define V4L2_DV_BT_CEA_1920X1080P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1080, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 148500000, 88, 44, 148, 4, 5, 36, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 16) \ } #define V4L2_DV_BT_CEA_3840X2160P24 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(3840, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 297000000, 1276, 88, 296, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC | V4L2_DV_FL_HAS_HDMI_VIC, \ { 0, 0 }, 93, 3) \ } #define V4L2_DV_BT_CEA_3840X2160P25 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(3840, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 297000000, 1056, 88, 296, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC | \ V4L2_DV_FL_HAS_HDMI_VIC, { 0, 0 }, 94, 2) \ } #define V4L2_DV_BT_CEA_3840X2160P30 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(3840, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 297000000, 176, 88, 296, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC | V4L2_DV_FL_HAS_HDMI_VIC, \ { 0, 0 }, 95, 1) \ } #define V4L2_DV_BT_CEA_3840X2160P50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(3840, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 594000000, 1056, 88, 296, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 96) \ } #define V4L2_DV_BT_CEA_3840X2160P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(3840, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 594000000, 176, 88, 296, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 97) \ } #define V4L2_DV_BT_CEA_4096X2160P24 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 297000000, 1020, 88, 296, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC | V4L2_DV_FL_HAS_HDMI_VIC, \ { 0, 0 }, 98, 4) \ } #define V4L2_DV_BT_CEA_4096X2160P25 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 297000000, 968, 88, 128, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 99) \ } #define V4L2_DV_BT_CEA_4096X2160P30 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 297000000, 88, 88, 128, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 100) \ } #define V4L2_DV_BT_CEA_4096X2160P50 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 594000000, 968, 88, 128, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_IS_CE_VIDEO | V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 101) \ } #define V4L2_DV_BT_CEA_4096X2160P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 594000000, 88, 88, 128, 8, 10, 72, 0, 0, 0, \ V4L2_DV_BT_STD_CEA861, \ V4L2_DV_FL_CAN_REDUCE_FPS | V4L2_DV_FL_IS_CE_VIDEO | \ V4L2_DV_FL_HAS_CEA861_VIC, { 0, 0 }, 102) \ } /* VESA Discrete Monitor Timings as per version 1.0, revision 12 */ #define V4L2_DV_BT_DMT_640X350P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(640, 350, 0, V4L2_DV_HSYNC_POS_POL, \ 31500000, 32, 64, 96, 32, 3, 60, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_640X400P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(640, 400, 0, V4L2_DV_VSYNC_POS_POL, \ 31500000, 32, 64, 96, 1, 3, 41, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_720X400P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(720, 400, 0, V4L2_DV_VSYNC_POS_POL, \ 35500000, 36, 72, 108, 1, 3, 42, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } /* VGA resolutions */ #define V4L2_DV_BT_DMT_640X480P60 V4L2_DV_BT_CEA_640X480P59_94 #define V4L2_DV_BT_DMT_640X480P72 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(640, 480, 0, 0, \ 31500000, 24, 40, 128, 9, 3, 28, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_640X480P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(640, 480, 0, 0, \ 31500000, 16, 64, 120, 1, 3, 16, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_640X480P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(640, 480, 0, 0, \ 36000000, 56, 56, 80, 1, 3, 25, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } /* SVGA resolutions */ #define V4L2_DV_BT_DMT_800X600P56 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(800, 600, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 36000000, 24, 72, 128, 1, 2, 22, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_800X600P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(800, 600, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 40000000, 40, 128, 88, 1, 4, 23, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_800X600P72 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(800, 600, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 50000000, 56, 120, 64, 37, 6, 23, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_800X600P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(800, 600, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 49500000, 16, 80, 160, 1, 3, 21, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_800X600P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(800, 600, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 56250000, 32, 64, 152, 1, 3, 27, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_800X600P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(800, 600, 0, V4L2_DV_HSYNC_POS_POL, \ 73250000, 48, 32, 80, 3, 4, 29, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_848X480P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(848, 480, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 33750000, 16, 112, 112, 6, 8, 23, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1024X768I43 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1024, 768, 1, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 44900000, 8, 176, 56, 0, 4, 20, 0, 4, 21, \ V4L2_DV_BT_STD_DMT, 0) \ } /* XGA resolutions */ #define V4L2_DV_BT_DMT_1024X768P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1024, 768, 0, 0, \ 65000000, 24, 136, 160, 3, 6, 29, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1024X768P70 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1024, 768, 0, 0, \ 75000000, 24, 136, 144, 3, 6, 29, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1024X768P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1024, 768, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 78750000, 16, 96, 176, 1, 3, 28, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1024X768P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1024, 768, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 94500000, 48, 96, 208, 1, 3, 36, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1024X768P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1024, 768, 0, V4L2_DV_HSYNC_POS_POL, \ 115500000, 48, 32, 80, 3, 4, 38, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } /* XGA+ resolution */ #define V4L2_DV_BT_DMT_1152X864P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1152, 864, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 108000000, 64, 128, 256, 1, 3, 32, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1280X720P60 V4L2_DV_BT_CEA_1280X720P60 /* WXGA resolutions */ #define V4L2_DV_BT_DMT_1280X768P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 768, 0, V4L2_DV_HSYNC_POS_POL, \ 68250000, 48, 32, 80, 3, 7, 12, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1280X768P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 768, 0, V4L2_DV_VSYNC_POS_POL, \ 79500000, 64, 128, 192, 3, 7, 20, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1280X768P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 768, 0, V4L2_DV_VSYNC_POS_POL, \ 102250000, 80, 128, 208, 3, 7, 27, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1280X768P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 768, 0, V4L2_DV_VSYNC_POS_POL, \ 117500000, 80, 136, 216, 3, 7, 31, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1280X768P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 768, 0, V4L2_DV_HSYNC_POS_POL, \ 140250000, 48, 32, 80, 3, 7, 35, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1280X800P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 800, 0, V4L2_DV_HSYNC_POS_POL, \ 71000000, 48, 32, 80, 3, 6, 14, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1280X800P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 800, 0, V4L2_DV_VSYNC_POS_POL, \ 83500000, 72, 128, 200, 3, 6, 22, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1280X800P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 800, 0, V4L2_DV_VSYNC_POS_POL, \ 106500000, 80, 128, 208, 3, 6, 29, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1280X800P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 800, 0, V4L2_DV_VSYNC_POS_POL, \ 122500000, 80, 136, 216, 3, 6, 34, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1280X800P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 800, 0, V4L2_DV_HSYNC_POS_POL, \ 146250000, 48, 32, 80, 3, 6, 38, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1280X960P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 960, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 108000000, 96, 112, 312, 1, 3, 36, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1280X960P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 960, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 148500000, 64, 160, 224, 1, 3, 47, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1280X960P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 960, 0, V4L2_DV_HSYNC_POS_POL, \ 175500000, 48, 32, 80, 3, 4, 50, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } /* SXGA resolutions */ #define V4L2_DV_BT_DMT_1280X1024P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 1024, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 108000000, 48, 112, 248, 1, 3, 38, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1280X1024P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 1024, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 135000000, 16, 144, 248, 1, 3, 38, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1280X1024P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 1024, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 157500000, 64, 160, 224, 1, 3, 44, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1280X1024P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1280, 1024, 0, V4L2_DV_HSYNC_POS_POL, \ 187250000, 48, 32, 80, 3, 7, 50, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1360X768P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1360, 768, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 85500000, 64, 112, 256, 3, 6, 18, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1360X768P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1360, 768, 0, V4L2_DV_HSYNC_POS_POL, \ 148250000, 48, 32, 80, 3, 5, 37, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1366X768P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1366, 768, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 85500000, 70, 143, 213, 3, 3, 24, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1366X768P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1366, 768, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 72000000, 14, 56, 64, 1, 3, 28, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, V4L2_DV_FL_REDUCED_BLANKING) \ } /* SXGA+ resolutions */ #define V4L2_DV_BT_DMT_1400X1050P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1400, 1050, 0, V4L2_DV_HSYNC_POS_POL, \ 101000000, 48, 32, 80, 3, 4, 23, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1400X1050P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1400, 1050, 0, V4L2_DV_VSYNC_POS_POL, \ 121750000, 88, 144, 232, 3, 4, 32, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1400X1050P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1400, 1050, 0, V4L2_DV_VSYNC_POS_POL, \ 156000000, 104, 144, 248, 3, 4, 42, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1400X1050P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1400, 1050, 0, V4L2_DV_VSYNC_POS_POL, \ 179500000, 104, 152, 256, 3, 4, 48, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1400X1050P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1400, 1050, 0, V4L2_DV_HSYNC_POS_POL, \ 208000000, 48, 32, 80, 3, 4, 55, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } /* WXGA+ resolutions */ #define V4L2_DV_BT_DMT_1440X900P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1440, 900, 0, V4L2_DV_HSYNC_POS_POL, \ 88750000, 48, 32, 80, 3, 6, 17, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1440X900P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1440, 900, 0, V4L2_DV_VSYNC_POS_POL, \ 106500000, 80, 152, 232, 3, 6, 25, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1440X900P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1440, 900, 0, V4L2_DV_VSYNC_POS_POL, \ 136750000, 96, 152, 248, 3, 6, 33, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1440X900P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1440, 900, 0, V4L2_DV_VSYNC_POS_POL, \ 157000000, 104, 152, 256, 3, 6, 39, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1440X900P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1440, 900, 0, V4L2_DV_HSYNC_POS_POL, \ 182750000, 48, 32, 80, 3, 6, 44, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1600X900P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 900, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 108000000, 24, 80, 96, 1, 3, 96, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, V4L2_DV_FL_REDUCED_BLANKING) \ } /* UXGA resolutions */ #define V4L2_DV_BT_DMT_1600X1200P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 1200, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 162000000, 64, 192, 304, 1, 3, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1600X1200P65 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 1200, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 175500000, 64, 192, 304, 1, 3, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1600X1200P70 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 1200, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 189000000, 64, 192, 304, 1, 3, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1600X1200P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 1200, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 202500000, 64, 192, 304, 1, 3, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1600X1200P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 1200, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 229500000, 64, 192, 304, 1, 3, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1600X1200P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1600, 1200, 0, V4L2_DV_HSYNC_POS_POL, \ 268250000, 48, 32, 80, 3, 4, 64, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } /* WSXGA+ resolutions */ #define V4L2_DV_BT_DMT_1680X1050P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1680, 1050, 0, V4L2_DV_HSYNC_POS_POL, \ 119000000, 48, 32, 80, 3, 6, 21, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1680X1050P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1680, 1050, 0, V4L2_DV_VSYNC_POS_POL, \ 146250000, 104, 176, 280, 3, 6, 30, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1680X1050P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1680, 1050, 0, V4L2_DV_VSYNC_POS_POL, \ 187000000, 120, 176, 296, 3, 6, 40, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1680X1050P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1680, 1050, 0, V4L2_DV_VSYNC_POS_POL, \ 214750000, 128, 176, 304, 3, 6, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1680X1050P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1680, 1050, 0, V4L2_DV_HSYNC_POS_POL, \ 245500000, 48, 32, 80, 3, 6, 53, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1792X1344P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1792, 1344, 0, V4L2_DV_VSYNC_POS_POL, \ 204750000, 128, 200, 328, 1, 3, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1792X1344P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1792, 1344, 0, V4L2_DV_VSYNC_POS_POL, \ 261000000, 96, 216, 352, 1, 3, 69, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1792X1344P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1792, 1344, 0, V4L2_DV_HSYNC_POS_POL, \ 333250000, 48, 32, 80, 3, 4, 72, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1856X1392P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1856, 1392, 0, V4L2_DV_VSYNC_POS_POL, \ 218250000, 96, 224, 352, 1, 3, 43, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1856X1392P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1856, 1392, 0, V4L2_DV_VSYNC_POS_POL, \ 288000000, 128, 224, 352, 1, 3, 104, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1856X1392P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1856, 1392, 0, V4L2_DV_HSYNC_POS_POL, \ 356500000, 48, 32, 80, 3, 4, 75, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1920X1080P60 V4L2_DV_BT_CEA_1920X1080P60 /* WUXGA resolutions */ #define V4L2_DV_BT_DMT_1920X1200P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1200, 0, V4L2_DV_HSYNC_POS_POL, \ 154000000, 48, 32, 80, 3, 6, 26, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1920X1200P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1200, 0, V4L2_DV_VSYNC_POS_POL, \ 193250000, 136, 200, 336, 3, 6, 36, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1920X1200P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1200, 0, V4L2_DV_VSYNC_POS_POL, \ 245250000, 136, 208, 344, 3, 6, 46, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1920X1200P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1200, 0, V4L2_DV_VSYNC_POS_POL, \ 281250000, 144, 208, 352, 3, 6, 53, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_1920X1200P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1200, 0, V4L2_DV_HSYNC_POS_POL, \ 317000000, 48, 32, 80, 3, 6, 62, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_1920X1440P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1440, 0, V4L2_DV_VSYNC_POS_POL, \ 234000000, 128, 208, 344, 1, 3, 56, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1920X1440P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1440, 0, V4L2_DV_VSYNC_POS_POL, \ 297000000, 144, 224, 352, 1, 3, 56, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, 0) \ } #define V4L2_DV_BT_DMT_1920X1440P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(1920, 1440, 0, V4L2_DV_HSYNC_POS_POL, \ 380500000, 48, 32, 80, 3, 4, 78, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_2048X1152P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(2048, 1152, 0, \ V4L2_DV_HSYNC_POS_POL | V4L2_DV_VSYNC_POS_POL, \ 162000000, 26, 80, 96, 1, 3, 44, 0, 0, 0, \ V4L2_DV_BT_STD_DMT, V4L2_DV_FL_REDUCED_BLANKING) \ } /* WQXGA resolutions */ #define V4L2_DV_BT_DMT_2560X1600P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(2560, 1600, 0, V4L2_DV_HSYNC_POS_POL, \ 268500000, 48, 32, 80, 3, 6, 37, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_2560X1600P60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(2560, 1600, 0, V4L2_DV_VSYNC_POS_POL, \ 348500000, 192, 280, 472, 3, 6, 49, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_2560X1600P75 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(2560, 1600, 0, V4L2_DV_VSYNC_POS_POL, \ 443250000, 208, 280, 488, 3, 6, 63, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_2560X1600P85 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(2560, 1600, 0, V4L2_DV_VSYNC_POS_POL, \ 505250000, 208, 280, 488, 3, 6, 73, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, 0) \ } #define V4L2_DV_BT_DMT_2560X1600P120_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(2560, 1600, 0, V4L2_DV_HSYNC_POS_POL, \ 552750000, 48, 32, 80, 3, 6, 85, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } /* 4K resolutions */ #define V4L2_DV_BT_DMT_4096X2160P60_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, V4L2_DV_HSYNC_POS_POL, \ 556744000, 8, 32, 40, 48, 8, 6, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } #define V4L2_DV_BT_DMT_4096X2160P59_94_RB { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(4096, 2160, 0, V4L2_DV_HSYNC_POS_POL, \ 556188000, 8, 32, 40, 48, 8, 6, 0, 0, 0, \ V4L2_DV_BT_STD_DMT | V4L2_DV_BT_STD_CVT, \ V4L2_DV_FL_REDUCED_BLANKING) \ } /* SDI timings definitions */ /* SMPTE-125M */ #define V4L2_DV_BT_SDI_720X487I60 { \ .type = V4L2_DV_BT_656_1120, \ V4L2_INIT_BT_TIMINGS(720, 487, 1, \ V4L2_DV_HSYNC_POS_POL, \ 13500000, 16, 121, 0, 0, 19, 0, 0, 19, 0, \ V4L2_DV_BT_STD_SDI, \ V4L2_DV_FL_FIRST_FIELD_EXTRA_LINE) \ } #endif linux/psci.h000064400000010350151027430560007014 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ARM Power State and Coordination Interface (PSCI) header * * This header holds common PSCI defines and macros shared * by: ARM kernel, ARM64 kernel, KVM ARM/ARM64 and user space. * * Copyright (C) 2014 Linaro Ltd. * Author: Anup Patel */ #ifndef _LINUX_PSCI_H #define _LINUX_PSCI_H /* * PSCI v0.1 interface * * The PSCI v0.1 function numbers are implementation defined. * * Only PSCI return values such as: SUCCESS, NOT_SUPPORTED, * INVALID_PARAMS, and DENIED defined below are applicable * to PSCI v0.1. */ /* PSCI v0.2 interface */ #define PSCI_0_2_FN_BASE 0x84000000 #define PSCI_0_2_FN(n) (PSCI_0_2_FN_BASE + (n)) #define PSCI_0_2_64BIT 0x40000000 #define PSCI_0_2_FN64_BASE \ (PSCI_0_2_FN_BASE + PSCI_0_2_64BIT) #define PSCI_0_2_FN64(n) (PSCI_0_2_FN64_BASE + (n)) #define PSCI_0_2_FN_PSCI_VERSION PSCI_0_2_FN(0) #define PSCI_0_2_FN_CPU_SUSPEND PSCI_0_2_FN(1) #define PSCI_0_2_FN_CPU_OFF PSCI_0_2_FN(2) #define PSCI_0_2_FN_CPU_ON PSCI_0_2_FN(3) #define PSCI_0_2_FN_AFFINITY_INFO PSCI_0_2_FN(4) #define PSCI_0_2_FN_MIGRATE PSCI_0_2_FN(5) #define PSCI_0_2_FN_MIGRATE_INFO_TYPE PSCI_0_2_FN(6) #define PSCI_0_2_FN_MIGRATE_INFO_UP_CPU PSCI_0_2_FN(7) #define PSCI_0_2_FN_SYSTEM_OFF PSCI_0_2_FN(8) #define PSCI_0_2_FN_SYSTEM_RESET PSCI_0_2_FN(9) #define PSCI_0_2_FN64_CPU_SUSPEND PSCI_0_2_FN64(1) #define PSCI_0_2_FN64_CPU_ON PSCI_0_2_FN64(3) #define PSCI_0_2_FN64_AFFINITY_INFO PSCI_0_2_FN64(4) #define PSCI_0_2_FN64_MIGRATE PSCI_0_2_FN64(5) #define PSCI_0_2_FN64_MIGRATE_INFO_UP_CPU PSCI_0_2_FN64(7) #define PSCI_1_0_FN_PSCI_FEATURES PSCI_0_2_FN(10) #define PSCI_1_0_FN_SYSTEM_SUSPEND PSCI_0_2_FN(14) #define PSCI_1_0_FN_SET_SUSPEND_MODE PSCI_0_2_FN(15) #define PSCI_1_1_FN_SYSTEM_RESET2 PSCI_0_2_FN(18) #define PSCI_1_0_FN64_SYSTEM_SUSPEND PSCI_0_2_FN64(14) #define PSCI_1_1_FN64_SYSTEM_RESET2 PSCI_0_2_FN64(18) /* PSCI v0.2 power state encoding for CPU_SUSPEND function */ #define PSCI_0_2_POWER_STATE_ID_MASK 0xffff #define PSCI_0_2_POWER_STATE_ID_SHIFT 0 #define PSCI_0_2_POWER_STATE_TYPE_SHIFT 16 #define PSCI_0_2_POWER_STATE_TYPE_MASK \ (0x1 << PSCI_0_2_POWER_STATE_TYPE_SHIFT) #define PSCI_0_2_POWER_STATE_AFFL_SHIFT 24 #define PSCI_0_2_POWER_STATE_AFFL_MASK \ (0x3 << PSCI_0_2_POWER_STATE_AFFL_SHIFT) /* PSCI extended power state encoding for CPU_SUSPEND function */ #define PSCI_1_0_EXT_POWER_STATE_ID_MASK 0xfffffff #define PSCI_1_0_EXT_POWER_STATE_ID_SHIFT 0 #define PSCI_1_0_EXT_POWER_STATE_TYPE_SHIFT 30 #define PSCI_1_0_EXT_POWER_STATE_TYPE_MASK \ (0x1 << PSCI_1_0_EXT_POWER_STATE_TYPE_SHIFT) /* PSCI v0.2 affinity level state returned by AFFINITY_INFO */ #define PSCI_0_2_AFFINITY_LEVEL_ON 0 #define PSCI_0_2_AFFINITY_LEVEL_OFF 1 #define PSCI_0_2_AFFINITY_LEVEL_ON_PENDING 2 /* PSCI v0.2 multicore support in Trusted OS returned by MIGRATE_INFO_TYPE */ #define PSCI_0_2_TOS_UP_MIGRATE 0 #define PSCI_0_2_TOS_UP_NO_MIGRATE 1 #define PSCI_0_2_TOS_MP 2 /* PSCI version decoding (independent of PSCI version) */ #define PSCI_VERSION_MAJOR_SHIFT 16 #define PSCI_VERSION_MINOR_MASK \ ((1U << PSCI_VERSION_MAJOR_SHIFT) - 1) #define PSCI_VERSION_MAJOR_MASK ~PSCI_VERSION_MINOR_MASK #define PSCI_VERSION_MAJOR(ver) \ (((ver) & PSCI_VERSION_MAJOR_MASK) >> PSCI_VERSION_MAJOR_SHIFT) #define PSCI_VERSION_MINOR(ver) \ ((ver) & PSCI_VERSION_MINOR_MASK) #define PSCI_VERSION(maj, min) \ ((((maj) << PSCI_VERSION_MAJOR_SHIFT) & PSCI_VERSION_MAJOR_MASK) | \ ((min) & PSCI_VERSION_MINOR_MASK)) /* PSCI features decoding (>=1.0) */ #define PSCI_1_0_FEATURES_CPU_SUSPEND_PF_SHIFT 1 #define PSCI_1_0_FEATURES_CPU_SUSPEND_PF_MASK \ (0x1 << PSCI_1_0_FEATURES_CPU_SUSPEND_PF_SHIFT) #define PSCI_1_0_OS_INITIATED BIT(0) #define PSCI_1_0_SUSPEND_MODE_PC 0 #define PSCI_1_0_SUSPEND_MODE_OSI 1 /* PSCI return values (inclusive of all PSCI versions) */ #define PSCI_RET_SUCCESS 0 #define PSCI_RET_NOT_SUPPORTED -1 #define PSCI_RET_INVALID_PARAMS -2 #define PSCI_RET_DENIED -3 #define PSCI_RET_ALREADY_ON -4 #define PSCI_RET_ON_PENDING -5 #define PSCI_RET_INTERNAL_FAILURE -6 #define PSCI_RET_NOT_PRESENT -7 #define PSCI_RET_DISABLED -8 #define PSCI_RET_INVALID_ADDRESS -9 #endif /* _LINUX_PSCI_H */ linux/omapfb.h000064400000013436151027430560007332 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * File: include/linux/omapfb.h * * Framebuffer driver for TI OMAP boards * * Copyright (C) 2004 Nokia Corporation * Author: Imre Deak * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __LINUX_OMAPFB_H__ #define __LINUX_OMAPFB_H__ #include #include #include /* IOCTL commands. */ #define OMAP_IOW(num, dtype) _IOW('O', num, dtype) #define OMAP_IOR(num, dtype) _IOR('O', num, dtype) #define OMAP_IOWR(num, dtype) _IOWR('O', num, dtype) #define OMAP_IO(num) _IO('O', num) #define OMAPFB_MIRROR OMAP_IOW(31, int) #define OMAPFB_SYNC_GFX OMAP_IO(37) #define OMAPFB_VSYNC OMAP_IO(38) #define OMAPFB_SET_UPDATE_MODE OMAP_IOW(40, int) #define OMAPFB_GET_CAPS OMAP_IOR(42, struct omapfb_caps) #define OMAPFB_GET_UPDATE_MODE OMAP_IOW(43, int) #define OMAPFB_LCD_TEST OMAP_IOW(45, int) #define OMAPFB_CTRL_TEST OMAP_IOW(46, int) #define OMAPFB_UPDATE_WINDOW_OLD OMAP_IOW(47, struct omapfb_update_window_old) #define OMAPFB_SET_COLOR_KEY OMAP_IOW(50, struct omapfb_color_key) #define OMAPFB_GET_COLOR_KEY OMAP_IOW(51, struct omapfb_color_key) #define OMAPFB_SETUP_PLANE OMAP_IOW(52, struct omapfb_plane_info) #define OMAPFB_QUERY_PLANE OMAP_IOW(53, struct omapfb_plane_info) #define OMAPFB_UPDATE_WINDOW OMAP_IOW(54, struct omapfb_update_window) #define OMAPFB_SETUP_MEM OMAP_IOW(55, struct omapfb_mem_info) #define OMAPFB_QUERY_MEM OMAP_IOW(56, struct omapfb_mem_info) #define OMAPFB_WAITFORVSYNC OMAP_IO(57) #define OMAPFB_MEMORY_READ OMAP_IOR(58, struct omapfb_memory_read) #define OMAPFB_GET_OVERLAY_COLORMODE OMAP_IOR(59, struct omapfb_ovl_colormode) #define OMAPFB_WAITFORGO OMAP_IO(60) #define OMAPFB_GET_VRAM_INFO OMAP_IOR(61, struct omapfb_vram_info) #define OMAPFB_SET_TEARSYNC OMAP_IOW(62, struct omapfb_tearsync_info) #define OMAPFB_GET_DISPLAY_INFO OMAP_IOR(63, struct omapfb_display_info) #define OMAPFB_CAPS_GENERIC_MASK 0x00000fff #define OMAPFB_CAPS_LCDC_MASK 0x00fff000 #define OMAPFB_CAPS_PANEL_MASK 0xff000000 #define OMAPFB_CAPS_MANUAL_UPDATE 0x00001000 #define OMAPFB_CAPS_TEARSYNC 0x00002000 #define OMAPFB_CAPS_PLANE_RELOCATE_MEM 0x00004000 #define OMAPFB_CAPS_PLANE_SCALE 0x00008000 #define OMAPFB_CAPS_WINDOW_PIXEL_DOUBLE 0x00010000 #define OMAPFB_CAPS_WINDOW_SCALE 0x00020000 #define OMAPFB_CAPS_WINDOW_OVERLAY 0x00040000 #define OMAPFB_CAPS_WINDOW_ROTATE 0x00080000 #define OMAPFB_CAPS_SET_BACKLIGHT 0x01000000 /* Values from DSP must map to lower 16-bits */ #define OMAPFB_FORMAT_MASK 0x00ff #define OMAPFB_FORMAT_FLAG_DOUBLE 0x0100 #define OMAPFB_FORMAT_FLAG_TEARSYNC 0x0200 #define OMAPFB_FORMAT_FLAG_FORCE_VSYNC 0x0400 #define OMAPFB_FORMAT_FLAG_ENABLE_OVERLAY 0x0800 #define OMAPFB_FORMAT_FLAG_DISABLE_OVERLAY 0x1000 #define OMAPFB_MEMTYPE_SDRAM 0 #define OMAPFB_MEMTYPE_SRAM 1 #define OMAPFB_MEMTYPE_MAX 1 #define OMAPFB_MEM_IDX_ENABLED 0x80 #define OMAPFB_MEM_IDX_MASK 0x7f enum omapfb_color_format { OMAPFB_COLOR_RGB565 = 0, OMAPFB_COLOR_YUV422, OMAPFB_COLOR_YUV420, OMAPFB_COLOR_CLUT_8BPP, OMAPFB_COLOR_CLUT_4BPP, OMAPFB_COLOR_CLUT_2BPP, OMAPFB_COLOR_CLUT_1BPP, OMAPFB_COLOR_RGB444, OMAPFB_COLOR_YUY422, OMAPFB_COLOR_ARGB16, OMAPFB_COLOR_RGB24U, /* RGB24, 32-bit container */ OMAPFB_COLOR_RGB24P, /* RGB24, 24-bit container */ OMAPFB_COLOR_ARGB32, OMAPFB_COLOR_RGBA32, OMAPFB_COLOR_RGBX32, }; struct omapfb_update_window { __u32 x, y; __u32 width, height; __u32 format; __u32 out_x, out_y; __u32 out_width, out_height; __u32 reserved[8]; }; struct omapfb_update_window_old { __u32 x, y; __u32 width, height; __u32 format; }; enum omapfb_plane { OMAPFB_PLANE_GFX = 0, OMAPFB_PLANE_VID1, OMAPFB_PLANE_VID2, }; enum omapfb_channel_out { OMAPFB_CHANNEL_OUT_LCD = 0, OMAPFB_CHANNEL_OUT_DIGIT, }; struct omapfb_plane_info { __u32 pos_x; __u32 pos_y; __u8 enabled; __u8 channel_out; __u8 mirror; __u8 mem_idx; __u32 out_width; __u32 out_height; __u32 reserved2[12]; }; struct omapfb_mem_info { __u32 size; __u8 type; __u8 reserved[3]; }; struct omapfb_caps { __u32 ctrl; __u32 plane_color; __u32 wnd_color; }; enum omapfb_color_key_type { OMAPFB_COLOR_KEY_DISABLED = 0, OMAPFB_COLOR_KEY_GFX_DST, OMAPFB_COLOR_KEY_VID_SRC, }; struct omapfb_color_key { __u8 channel_out; __u32 background; __u32 trans_key; __u8 key_type; }; enum omapfb_update_mode { OMAPFB_UPDATE_DISABLED = 0, OMAPFB_AUTO_UPDATE, OMAPFB_MANUAL_UPDATE }; struct omapfb_memory_read { __u16 x; __u16 y; __u16 w; __u16 h; size_t buffer_size; void *buffer; }; struct omapfb_ovl_colormode { __u8 overlay_idx; __u8 mode_idx; __u32 bits_per_pixel; __u32 nonstd; struct fb_bitfield red; struct fb_bitfield green; struct fb_bitfield blue; struct fb_bitfield transp; }; struct omapfb_vram_info { __u32 total; __u32 free; __u32 largest_free_block; __u32 reserved[5]; }; struct omapfb_tearsync_info { __u8 enabled; __u8 reserved1[3]; __u16 line; __u16 reserved2; }; struct omapfb_display_info { __u16 xres; __u16 yres; __u32 width; /* phys width of the display in micrometers */ __u32 height; /* phys height of the display in micrometers */ __u32 reserved[5]; }; #endif /* __LINUX_OMAPFB_H__ */ linux/msg.h000064400000006456151027430560006660 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MSG_H #define _LINUX_MSG_H #include /* ipcs ctl commands */ #define MSG_STAT 11 #define MSG_INFO 12 #define MSG_STAT_ANY 13 /* msgrcv options */ #define MSG_NOERROR 010000 /* no error if message is too big */ #define MSG_EXCEPT 020000 /* recv any msg except of specified type.*/ #define MSG_COPY 040000 /* copy (not remove) all queue messages */ /* Obsolete, used only for backwards compatibility and libc5 compiles */ struct msqid_ds { struct ipc_perm msg_perm; struct msg *msg_first; /* first message on queue,unused */ struct msg *msg_last; /* last message in queue,unused */ __kernel_time_t msg_stime; /* last msgsnd time */ __kernel_time_t msg_rtime; /* last msgrcv time */ __kernel_time_t msg_ctime; /* last change time */ unsigned long msg_lcbytes; /* Reuse junk fields for 32 bit */ unsigned long msg_lqbytes; /* ditto */ unsigned short msg_cbytes; /* current number of bytes on queue */ unsigned short msg_qnum; /* number of messages in queue */ unsigned short msg_qbytes; /* max number of bytes on queue */ __kernel_ipc_pid_t msg_lspid; /* pid of last msgsnd */ __kernel_ipc_pid_t msg_lrpid; /* last receive pid */ }; /* Include the definition of msqid64_ds */ #include /* message buffer for msgsnd and msgrcv calls */ struct msgbuf { __kernel_long_t mtype; /* type of message */ char mtext[1]; /* message text */ }; /* buffer for msgctl calls IPC_INFO, MSG_INFO */ struct msginfo { int msgpool; int msgmap; int msgmax; int msgmnb; int msgmni; int msgssz; int msgtql; unsigned short msgseg; }; /* * MSGMNI, MSGMAX and MSGMNB are default values which can be * modified by sysctl. * * MSGMNI is the upper limit for the number of messages queues per * namespace. * It has been chosen to be as large possible without facilitating * scenarios where userspace causes overflows when adjusting the limits via * operations of the form retrieve current limit; add X; update limit". * * MSGMNB is the default size of a new message queue. Non-root tasks can * decrease the size with msgctl(IPC_SET), root tasks * (actually: CAP_SYS_RESOURCE) can both increase and decrease the queue * size. The optimal value is application dependent. * 16384 is used because it was always used (since 0.99.10) * * MAXMAX is the maximum size of an individual message, it's a global * (per-namespace) limit that applies for all message queues. * It's set to 1/2 of MSGMNB, to ensure that at least two messages fit into * the queue. This is also an arbitrary choice (since 2.6.0). */ #define MSGMNI 32000 /* <= IPCMNI */ /* max # of msg queue identifiers */ #define MSGMAX 8192 /* <= INT_MAX */ /* max size of message (bytes) */ #define MSGMNB 16384 /* <= INT_MAX */ /* default max size of a message queue */ /* unused */ #define MSGPOOL (MSGMNI * MSGMNB / 1024) /* size in kbytes of message pool */ #define MSGTQL MSGMNB /* number of system message headers */ #define MSGMAP MSGMNB /* number of entries in message map */ #define MSGSSZ 16 /* message segment size */ #define __MSGSEG ((MSGPOOL * 1024) / MSGSSZ) /* max no. of segments */ #define MSGSEG (__MSGSEG <= 0xffff ? __MSGSEG : 0xffff) #endif /* _LINUX_MSG_H */ linux/tty_flags.h000064400000010657151027430560010064 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TTY_FLAGS_H #define _LINUX_TTY_FLAGS_H /* * Definitions for async_struct (and serial_struct) flags field also * shared by the tty_port flags structures. * * Define ASYNCB_* for convenient use with {test,set,clear}_bit. * * Bits [0..ASYNCB_LAST_USER] are userspace defined/visible/changeable * [x] in the bit comments indicates the flag is defunct and no longer used. */ #define ASYNCB_HUP_NOTIFY 0 /* Notify getty on hangups and closes * on the callout port */ #define ASYNCB_FOURPORT 1 /* Set OUT1, OUT2 per AST Fourport settings */ #define ASYNCB_SAK 2 /* Secure Attention Key (Orange book) */ #define ASYNCB_SPLIT_TERMIOS 3 /* [x] Separate termios for dialin/callout */ #define ASYNCB_SPD_HI 4 /* Use 57600 instead of 38400 bps */ #define ASYNCB_SPD_VHI 5 /* Use 115200 instead of 38400 bps */ #define ASYNCB_SKIP_TEST 6 /* Skip UART test during autoconfiguration */ #define ASYNCB_AUTO_IRQ 7 /* Do automatic IRQ during * autoconfiguration */ #define ASYNCB_SESSION_LOCKOUT 8 /* [x] Lock out cua opens based on session */ #define ASYNCB_PGRP_LOCKOUT 9 /* [x] Lock out cua opens based on pgrp */ #define ASYNCB_CALLOUT_NOHUP 10 /* [x] Don't do hangups for cua device */ #define ASYNCB_HARDPPS_CD 11 /* Call hardpps when CD goes high */ #define ASYNCB_SPD_SHI 12 /* Use 230400 instead of 38400 bps */ #define ASYNCB_LOW_LATENCY 13 /* Request low latency behaviour */ #define ASYNCB_BUGGY_UART 14 /* This is a buggy UART, skip some safety * checks. Note: can be dangerous! */ #define ASYNCB_AUTOPROBE 15 /* [x] Port was autoprobed by PCI/PNP code */ #define ASYNCB_MAGIC_MULTIPLIER 16 /* Use special CLK or divisor */ #define ASYNCB_LAST_USER 16 /* * Internal flags used only by kernel (read-only) * * WARNING: These flags are no longer used and have been superceded by the * TTY_PORT_ flags in the iflags field (and not userspace-visible) */ #ifndef _KERNEL_ #define ASYNCB_INITIALIZED 31 /* Serial port was initialized */ #define ASYNCB_SUSPENDED 30 /* Serial port is suspended */ #define ASYNCB_NORMAL_ACTIVE 29 /* Normal device is active */ #define ASYNCB_BOOT_AUTOCONF 28 /* Autoconfigure port on bootup */ #define ASYNCB_CLOSING 27 /* Serial port is closing */ #define ASYNCB_CTS_FLOW 26 /* Do CTS flow control */ #define ASYNCB_CHECK_CD 25 /* i.e., CLOCAL */ #define ASYNCB_SHARE_IRQ 24 /* for multifunction cards, no longer used */ #define ASYNCB_CONS_FLOW 23 /* flow control for console */ #define ASYNCB_FIRST_KERNEL 22 #endif /* Masks */ #define ASYNC_HUP_NOTIFY (1U << ASYNCB_HUP_NOTIFY) #define ASYNC_SUSPENDED (1U << ASYNCB_SUSPENDED) #define ASYNC_FOURPORT (1U << ASYNCB_FOURPORT) #define ASYNC_SAK (1U << ASYNCB_SAK) #define ASYNC_SPLIT_TERMIOS (1U << ASYNCB_SPLIT_TERMIOS) #define ASYNC_SPD_HI (1U << ASYNCB_SPD_HI) #define ASYNC_SPD_VHI (1U << ASYNCB_SPD_VHI) #define ASYNC_SKIP_TEST (1U << ASYNCB_SKIP_TEST) #define ASYNC_AUTO_IRQ (1U << ASYNCB_AUTO_IRQ) #define ASYNC_SESSION_LOCKOUT (1U << ASYNCB_SESSION_LOCKOUT) #define ASYNC_PGRP_LOCKOUT (1U << ASYNCB_PGRP_LOCKOUT) #define ASYNC_CALLOUT_NOHUP (1U << ASYNCB_CALLOUT_NOHUP) #define ASYNC_HARDPPS_CD (1U << ASYNCB_HARDPPS_CD) #define ASYNC_SPD_SHI (1U << ASYNCB_SPD_SHI) #define ASYNC_LOW_LATENCY (1U << ASYNCB_LOW_LATENCY) #define ASYNC_BUGGY_UART (1U << ASYNCB_BUGGY_UART) #define ASYNC_AUTOPROBE (1U << ASYNCB_AUTOPROBE) #define ASYNC_MAGIC_MULTIPLIER (1U << ASYNCB_MAGIC_MULTIPLIER) #define ASYNC_FLAGS ((1U << (ASYNCB_LAST_USER + 1)) - 1) #define ASYNC_DEPRECATED (ASYNC_SESSION_LOCKOUT | ASYNC_PGRP_LOCKOUT | \ ASYNC_CALLOUT_NOHUP | ASYNC_AUTOPROBE) #define ASYNC_USR_MASK (ASYNC_SPD_MASK|ASYNC_CALLOUT_NOHUP| \ ASYNC_LOW_LATENCY) #define ASYNC_SPD_CUST (ASYNC_SPD_HI|ASYNC_SPD_VHI) #define ASYNC_SPD_WARP (ASYNC_SPD_HI|ASYNC_SPD_SHI) #define ASYNC_SPD_MASK (ASYNC_SPD_HI|ASYNC_SPD_VHI|ASYNC_SPD_SHI) #ifndef _KERNEL_ /* These flags are no longer used (and were always masked from userspace) */ #define ASYNC_INITIALIZED (1U << ASYNCB_INITIALIZED) #define ASYNC_NORMAL_ACTIVE (1U << ASYNCB_NORMAL_ACTIVE) #define ASYNC_BOOT_AUTOCONF (1U << ASYNCB_BOOT_AUTOCONF) #define ASYNC_CLOSING (1U << ASYNCB_CLOSING) #define ASYNC_CTS_FLOW (1U << ASYNCB_CTS_FLOW) #define ASYNC_CHECK_CD (1U << ASYNCB_CHECK_CD) #define ASYNC_SHARE_IRQ (1U << ASYNCB_SHARE_IRQ) #define ASYNC_CONS_FLOW (1U << ASYNCB_CONS_FLOW) #define ASYNC_INTERNAL_FLAGS (~((1U << ASYNCB_FIRST_KERNEL) - 1)) #endif #endif linux/netfilter_ipv4.h000064400000004171151027430560011020 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* IPv4-specific defines for netfilter. * (C)1998 Rusty Russell -- This code is GPL. */ #ifndef __LINUX_IP_NETFILTER_H #define __LINUX_IP_NETFILTER_H #include /* only for userspace compatibility */ #include /* for INT_MIN, INT_MAX */ /* IP Cache bits. */ /* Src IP address. */ #define NFC_IP_SRC 0x0001 /* Dest IP address. */ #define NFC_IP_DST 0x0002 /* Input device. */ #define NFC_IP_IF_IN 0x0004 /* Output device. */ #define NFC_IP_IF_OUT 0x0008 /* TOS. */ #define NFC_IP_TOS 0x0010 /* Protocol. */ #define NFC_IP_PROTO 0x0020 /* IP options. */ #define NFC_IP_OPTIONS 0x0040 /* Frag & flags. */ #define NFC_IP_FRAG 0x0080 /* Per-protocol information: only matters if proto match. */ /* TCP flags. */ #define NFC_IP_TCPFLAGS 0x0100 /* Source port. */ #define NFC_IP_SRC_PT 0x0200 /* Dest port. */ #define NFC_IP_DST_PT 0x0400 /* Something else about the proto */ #define NFC_IP_PROTO_UNKNOWN 0x2000 /* IP Hooks */ /* After promisc drops, checksum checks. */ #define NF_IP_PRE_ROUTING 0 /* If the packet is destined for this box. */ #define NF_IP_LOCAL_IN 1 /* If the packet is destined for another interface. */ #define NF_IP_FORWARD 2 /* Packets coming from a local process. */ #define NF_IP_LOCAL_OUT 3 /* Packets about to hit the wire. */ #define NF_IP_POST_ROUTING 4 #define NF_IP_NUMHOOKS 5 enum nf_ip_hook_priorities { NF_IP_PRI_FIRST = INT_MIN, NF_IP_PRI_RAW_BEFORE_DEFRAG = -450, NF_IP_PRI_CONNTRACK_DEFRAG = -400, NF_IP_PRI_RAW = -300, NF_IP_PRI_SELINUX_FIRST = -225, NF_IP_PRI_CONNTRACK = -200, NF_IP_PRI_MANGLE = -150, NF_IP_PRI_NAT_DST = -100, NF_IP_PRI_FILTER = 0, NF_IP_PRI_SECURITY = 50, NF_IP_PRI_NAT_SRC = 100, NF_IP_PRI_SELINUX_LAST = 225, NF_IP_PRI_CONNTRACK_HELPER = 300, NF_IP_PRI_CONNTRACK_CONFIRM = INT_MAX, NF_IP_PRI_LAST = INT_MAX, }; /* Arguments for setsockopt SOL_IP: */ /* 2.0 firewalling went from 64 through 71 (and +256, +512, etc). */ /* 2.2 firewalling (+ masq) went from 64 through 76 */ /* 2.4 firewalling went 64 through 67. */ #define SO_ORIGINAL_DST 80 #endif /* __LINUX_IP_NETFILTER_H */ linux/vtpm_proxy.h000064400000003267151027430560010316 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Definitions for the VTPM proxy driver * Copyright (c) 2015, 2016, IBM Corporation * Copyright (C) 2016 Intel Corporation * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #ifndef _LINUX_VTPM_PROXY_H #define _LINUX_VTPM_PROXY_H #include #include /** * enum vtpm_proxy_flags - flags for the proxy TPM * @VTPM_PROXY_FLAG_TPM2: the proxy TPM uses TPM 2.0 protocol */ enum vtpm_proxy_flags { VTPM_PROXY_FLAG_TPM2 = 1, }; /** * struct vtpm_proxy_new_dev - parameter structure for the * %VTPM_PROXY_IOC_NEW_DEV ioctl * @flags: flags for the proxy TPM * @tpm_num: index of the TPM device * @fd: the file descriptor used by the proxy TPM * @major: the major number of the TPM device * @minor: the minor number of the TPM device */ struct vtpm_proxy_new_dev { __u32 flags; /* input */ __u32 tpm_num; /* output */ __u32 fd; /* output */ __u32 major; /* output */ __u32 minor; /* output */ }; #define VTPM_PROXY_IOC_NEW_DEV _IOWR(0xa1, 0x00, struct vtpm_proxy_new_dev) /* vendor specific commands to set locality */ #define TPM2_CC_SET_LOCALITY 0x20001000 #define TPM_ORD_SET_LOCALITY 0x20001000 #endif /* _LINUX_VTPM_PROXY_H */ linux/sdla.h000064400000005427151027430560007012 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the Frame relay interface. * * Version: @(#)if_ifrad.h 0.20 13 Apr 96 * * Author: Mike McLagan * * Changes: * 0.15 Mike McLagan Structure packing * * 0.20 Mike McLagan New flags for S508 buffer handling * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef SDLA_H #define SDLA_H /* adapter type */ #define SDLA_TYPES #define SDLA_S502A 5020 #define SDLA_S502E 5021 #define SDLA_S503 5030 #define SDLA_S507 5070 #define SDLA_S508 5080 #define SDLA_S509 5090 #define SDLA_UNKNOWN -1 /* port selection flags for the S508 */ #define SDLA_S508_PORT_V35 0x00 #define SDLA_S508_PORT_RS232 0x02 /* Z80 CPU speeds */ #define SDLA_CPU_3M 0x00 #define SDLA_CPU_5M 0x01 #define SDLA_CPU_7M 0x02 #define SDLA_CPU_8M 0x03 #define SDLA_CPU_10M 0x04 #define SDLA_CPU_16M 0x05 #define SDLA_CPU_12M 0x06 /* some private IOCTLs */ #define SDLA_IDENTIFY (FRAD_LAST_IOCTL + 1) #define SDLA_CPUSPEED (FRAD_LAST_IOCTL + 2) #define SDLA_PROTOCOL (FRAD_LAST_IOCTL + 3) #define SDLA_CLEARMEM (FRAD_LAST_IOCTL + 4) #define SDLA_WRITEMEM (FRAD_LAST_IOCTL + 5) #define SDLA_READMEM (FRAD_LAST_IOCTL + 6) struct sdla_mem { int addr; int len; void *data; }; #define SDLA_START (FRAD_LAST_IOCTL + 7) #define SDLA_STOP (FRAD_LAST_IOCTL + 8) /* some offsets in the Z80's memory space */ #define SDLA_NMIADDR 0x0000 #define SDLA_CONF_ADDR 0x0010 #define SDLA_S502A_NMIADDR 0x0066 #define SDLA_CODE_BASEADDR 0x0100 #define SDLA_WINDOW_SIZE 0x2000 #define SDLA_ADDR_MASK 0x1FFF /* largest handleable block of data */ #define SDLA_MAX_DATA 4080 #define SDLA_MAX_MTU 4072 /* MAX_DATA - sizeof(fradhdr) */ #define SDLA_MAX_DLCI 24 /* this should be the same as frad_conf */ struct sdla_conf { short station; short config; short kbaud; short clocking; short max_frm; short T391; short T392; short N391; short N392; short N393; short CIR_fwd; short Bc_fwd; short Be_fwd; short CIR_bwd; short Bc_bwd; short Be_bwd; }; /* this should be the same as dlci_conf */ struct sdla_dlci_conf { short config; short CIR_fwd; short Bc_fwd; short Be_fwd; short CIR_bwd; short Bc_bwd; short Be_bwd; short Tc_fwd; short Tc_bwd; short Tf_max; short Tb_max; }; #endif /* SDLA_H */ linux/if_alg.h000064400000001662151027430560007305 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * if_alg: User-space algorithm interface * * Copyright (c) 2010 Herbert Xu * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #ifndef _LINUX_IF_ALG_H #define _LINUX_IF_ALG_H #include struct sockaddr_alg { __u16 salg_family; __u8 salg_type[14]; __u32 salg_feat; __u32 salg_mask; __u8 salg_name[64]; }; struct af_alg_iv { __u32 ivlen; __u8 iv[0]; }; /* Socket options */ #define ALG_SET_KEY 1 #define ALG_SET_IV 2 #define ALG_SET_OP 3 #define ALG_SET_AEAD_ASSOCLEN 4 #define ALG_SET_AEAD_AUTHSIZE 5 /* Operations */ #define ALG_OP_DECRYPT 0 #define ALG_OP_ENCRYPT 1 #endif /* _LINUX_IF_ALG_H */ linux/atmsvc.h000064400000003475151027430560007365 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmsvc.h - ATM signaling kernel-demon interface definitions */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #ifndef _LINUX_ATMSVC_H #define _LINUX_ATMSVC_H #include #include #include #define ATMSIGD_CTRL _IO('a',ATMIOC_SPECIAL) /* become ATM signaling demon control socket */ enum atmsvc_msg_type { as_catch_null, as_bind, as_connect, as_accept, as_reject, as_listen, as_okay, as_error, as_indicate, as_close, as_itf_notify, as_modify, as_identify, as_terminate, as_addparty, as_dropparty }; struct atmsvc_msg { enum atmsvc_msg_type type; atm_kptr_t vcc; atm_kptr_t listen_vcc; /* indicate */ int reply; /* for okay and close: */ /* < 0: error before active */ /* (sigd has discarded ctx) */ /* ==0: success */ /* > 0: error when active (still */ /* need to close) */ struct sockaddr_atmpvc pvc; /* indicate, okay (connect) */ struct sockaddr_atmsvc local; /* local SVC address */ struct atm_qos qos; /* QOS parameters */ struct atm_sap sap; /* SAP */ unsigned int session; /* for p2pm */ struct sockaddr_atmsvc svc; /* SVC address */ } __ATM_API_ALIGN; /* * Message contents: see ftp://icaftp.epfl.ch/pub/linux/atm/docs/isp-*.tar.gz */ /* * Some policy stuff for atmsigd and for net/atm/svc.c. Both have to agree on * what PCR is used to request bandwidth from the device driver. net/atm/svc.c * tries to do better than that, but only if there's no routing decision (i.e. * if signaling only uses one ATM interface). */ #define SELECT_TOP_PCR(tp) ((tp).pcr ? (tp).pcr : \ (tp).max_pcr && (tp).max_pcr != ATM_MAX_PCR ? (tp).max_pcr : \ (tp).min_pcr ? (tp).min_pcr : ATM_MAX_PCR) #endif linux/mpls.h000064400000004376151027430560007044 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _MPLS_H #define _MPLS_H #include #include /* Reference: RFC 5462, RFC 3032 * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Label | TC |S| TTL | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * Label: Label Value, 20 bits * TC: Traffic Class field, 3 bits * S: Bottom of Stack, 1 bit * TTL: Time to Live, 8 bits */ struct mpls_label { __be32 entry; }; #define MPLS_LS_LABEL_MASK 0xFFFFF000 #define MPLS_LS_LABEL_SHIFT 12 #define MPLS_LS_TC_MASK 0x00000E00 #define MPLS_LS_TC_SHIFT 9 #define MPLS_LS_S_MASK 0x00000100 #define MPLS_LS_S_SHIFT 8 #define MPLS_LS_TTL_MASK 0x000000FF #define MPLS_LS_TTL_SHIFT 0 /* Reserved labels */ #define MPLS_LABEL_IPV4NULL 0 /* RFC3032 */ #define MPLS_LABEL_RTALERT 1 /* RFC3032 */ #define MPLS_LABEL_IPV6NULL 2 /* RFC3032 */ #define MPLS_LABEL_IMPLNULL 3 /* RFC3032 */ #define MPLS_LABEL_ENTROPY 7 /* RFC6790 */ #define MPLS_LABEL_GAL 13 /* RFC5586 */ #define MPLS_LABEL_OAMALERT 14 /* RFC3429 */ #define MPLS_LABEL_EXTENSION 15 /* RFC7274 */ #define MPLS_LABEL_FIRST_UNRESERVED 16 /* RFC3032 */ /* These are embedded into IFLA_STATS_AF_SPEC: * [IFLA_STATS_AF_SPEC] * -> [AF_MPLS] * -> [MPLS_STATS_xxx] * * Attributes: * [MPLS_STATS_LINK] = { * struct mpls_link_stats * } */ enum { MPLS_STATS_UNSPEC, /* also used as 64bit pad attribute */ MPLS_STATS_LINK, __MPLS_STATS_MAX, }; #define MPLS_STATS_MAX (__MPLS_STATS_MAX - 1) struct mpls_link_stats { __u64 rx_packets; /* total packets received */ __u64 tx_packets; /* total packets transmitted */ __u64 rx_bytes; /* total bytes received */ __u64 tx_bytes; /* total bytes transmitted */ __u64 rx_errors; /* bad packets received */ __u64 tx_errors; /* packet transmit problems */ __u64 rx_dropped; /* packet dropped on receive */ __u64 tx_dropped; /* packet dropped on transmit */ __u64 rx_noroute; /* no route for packet dest */ }; #endif /* _MPLS_H */ linux/gpio.h000064400000015137151027430560007024 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * - userspace ABI for the GPIO character devices * * Copyright (C) 2016 Linus Walleij * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _GPIO_H_ #define _GPIO_H_ #include #include /** * struct gpiochip_info - Information about a certain GPIO chip * @name: the Linux kernel name of this GPIO chip * @label: a functional name for this GPIO chip, such as a product * number, may be NULL * @lines: number of GPIO lines on this chip */ struct gpiochip_info { char name[32]; char label[32]; __u32 lines; }; /* Informational flags */ #define GPIOLINE_FLAG_KERNEL (1UL << 0) /* Line used by the kernel */ #define GPIOLINE_FLAG_IS_OUT (1UL << 1) #define GPIOLINE_FLAG_ACTIVE_LOW (1UL << 2) #define GPIOLINE_FLAG_OPEN_DRAIN (1UL << 3) #define GPIOLINE_FLAG_OPEN_SOURCE (1UL << 4) #define GPIOLINE_FLAG_BIAS_PULL_UP (1UL << 5) #define GPIOLINE_FLAG_BIAS_PULL_DOWN (1UL << 6) #define GPIOLINE_FLAG_BIAS_DISABLE (1UL << 7) /** * struct gpioline_info - Information about a certain GPIO line * @line_offset: the local offset on this GPIO device, fill this in when * requesting the line information from the kernel * @flags: various flags for this line * @name: the name of this GPIO line, such as the output pin of the line on the * chip, a rail or a pin header name on a board, as specified by the gpio * chip, may be NULL * @consumer: a functional name for the consumer of this GPIO line as set by * whatever is using it, will be NULL if there is no current user but may * also be NULL if the consumer doesn't set this up */ struct gpioline_info { __u32 line_offset; __u32 flags; char name[32]; char consumer[32]; }; /* Maximum number of requested handles */ #define GPIOHANDLES_MAX 64 /* Linerequest flags */ #define GPIOHANDLE_REQUEST_INPUT (1UL << 0) #define GPIOHANDLE_REQUEST_OUTPUT (1UL << 1) #define GPIOHANDLE_REQUEST_ACTIVE_LOW (1UL << 2) #define GPIOHANDLE_REQUEST_OPEN_DRAIN (1UL << 3) #define GPIOHANDLE_REQUEST_OPEN_SOURCE (1UL << 4) #define GPIOHANDLE_REQUEST_BIAS_PULL_UP (1UL << 5) #define GPIOHANDLE_REQUEST_BIAS_PULL_DOWN (1UL << 6) #define GPIOHANDLE_REQUEST_BIAS_DISABLE (1UL << 7) /** * struct gpiohandle_request - Information about a GPIO handle request * @lineoffsets: an array desired lines, specified by offset index for the * associated GPIO device * @flags: desired flags for the desired GPIO lines, such as * GPIOHANDLE_REQUEST_OUTPUT, GPIOHANDLE_REQUEST_ACTIVE_LOW etc, OR:ed * together. Note that even if multiple lines are requested, the same flags * must be applicable to all of them, if you want lines with individual * flags set, request them one by one. It is possible to select * a batch of input or output lines, but they must all have the same * characteristics, i.e. all inputs or all outputs, all active low etc * @default_values: if the GPIOHANDLE_REQUEST_OUTPUT is set for a requested * line, this specifies the default output value, should be 0 (low) or * 1 (high), anything else than 0 or 1 will be interpreted as 1 (high) * @consumer_label: a desired consumer label for the selected GPIO line(s) * such as "my-bitbanged-relay" * @lines: number of lines requested in this request, i.e. the number of * valid fields in the above arrays, set to 1 to request a single line * @fd: if successful this field will contain a valid anonymous file handle * after a GPIO_GET_LINEHANDLE_IOCTL operation, zero or negative value * means error */ struct gpiohandle_request { __u32 lineoffsets[GPIOHANDLES_MAX]; __u32 flags; __u8 default_values[GPIOHANDLES_MAX]; char consumer_label[32]; __u32 lines; int fd; }; /** * struct gpiohandle_config - Configuration for a GPIO handle request * @flags: updated flags for the requested GPIO lines, such as * GPIOHANDLE_REQUEST_OUTPUT, GPIOHANDLE_REQUEST_ACTIVE_LOW etc, OR:ed * together * @default_values: if the GPIOHANDLE_REQUEST_OUTPUT is set in flags, * this specifies the default output value, should be 0 (low) or * 1 (high), anything else than 0 or 1 will be interpreted as 1 (high) * @padding: reserved for future use and should be zero filled */ struct gpiohandle_config { __u32 flags; __u8 default_values[GPIOHANDLES_MAX]; __u32 padding[4]; /* padding for future use */ }; #define GPIOHANDLE_SET_CONFIG_IOCTL _IOWR(0xB4, 0x0a, struct gpiohandle_config) /** * struct gpiohandle_data - Information of values on a GPIO handle * @values: when getting the state of lines this contains the current * state of a line, when setting the state of lines these should contain * the desired target state */ struct gpiohandle_data { __u8 values[GPIOHANDLES_MAX]; }; #define GPIOHANDLE_GET_LINE_VALUES_IOCTL _IOWR(0xB4, 0x08, struct gpiohandle_data) #define GPIOHANDLE_SET_LINE_VALUES_IOCTL _IOWR(0xB4, 0x09, struct gpiohandle_data) /* Eventrequest flags */ #define GPIOEVENT_REQUEST_RISING_EDGE (1UL << 0) #define GPIOEVENT_REQUEST_FALLING_EDGE (1UL << 1) #define GPIOEVENT_REQUEST_BOTH_EDGES ((1UL << 0) | (1UL << 1)) /** * struct gpioevent_request - Information about a GPIO event request * @lineoffset: the desired line to subscribe to events from, specified by * offset index for the associated GPIO device * @handleflags: desired handle flags for the desired GPIO line, such as * GPIOHANDLE_REQUEST_ACTIVE_LOW or GPIOHANDLE_REQUEST_OPEN_DRAIN * @eventflags: desired flags for the desired GPIO event line, such as * GPIOEVENT_REQUEST_RISING_EDGE or GPIOEVENT_REQUEST_FALLING_EDGE * @consumer_label: a desired consumer label for the selected GPIO line(s) * such as "my-listener" * @fd: if successful this field will contain a valid anonymous file handle * after a GPIO_GET_LINEEVENT_IOCTL operation, zero or negative value * means error */ struct gpioevent_request { __u32 lineoffset; __u32 handleflags; __u32 eventflags; char consumer_label[32]; int fd; }; /** * GPIO event types */ #define GPIOEVENT_EVENT_RISING_EDGE 0x01 #define GPIOEVENT_EVENT_FALLING_EDGE 0x02 /** * struct gpioevent_data - The actual event being pushed to userspace * @timestamp: best estimate of time of event occurrence, in nanoseconds * @id: event identifier */ struct gpioevent_data { __u64 timestamp; __u32 id; }; #define GPIO_GET_CHIPINFO_IOCTL _IOR(0xB4, 0x01, struct gpiochip_info) #define GPIO_GET_LINEINFO_IOCTL _IOWR(0xB4, 0x02, struct gpioline_info) #define GPIO_GET_LINEHANDLE_IOCTL _IOWR(0xB4, 0x03, struct gpiohandle_request) #define GPIO_GET_LINEEVENT_IOCTL _IOWR(0xB4, 0x04, struct gpioevent_request) #endif /* _GPIO_H_ */ linux/nfs_idmap.h000064400000004303151027430560010017 0ustar00/* * include/uapi/linux/nfs_idmap.h * * UID and GID to name mapping for clients. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Marius Aamodt Eriksen * * 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. Neither the name of the University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NFS_IDMAP_H #define NFS_IDMAP_H #include /* XXX from bits/utmp.h */ #define IDMAP_NAMESZ 128 #define IDMAP_TYPE_USER 0 #define IDMAP_TYPE_GROUP 1 #define IDMAP_CONV_IDTONAME 0 #define IDMAP_CONV_NAMETOID 1 #define IDMAP_STATUS_INVALIDMSG 0x01 #define IDMAP_STATUS_AGAIN 0x02 #define IDMAP_STATUS_LOOKUPFAIL 0x04 #define IDMAP_STATUS_SUCCESS 0x08 struct idmap_msg { __u8 im_type; __u8 im_conv; char im_name[IDMAP_NAMESZ]; __u32 im_id; __u8 im_status; }; #endif /* NFS_IDMAP_H */ linux/serial.h000064400000007432151027430560007344 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * include/linux/serial.h * * Copyright (C) 1992 by Theodore Ts'o. * * Redistribution of this file is permitted under the terms of the GNU * Public License (GPL) */ #ifndef _LINUX_SERIAL_H #define _LINUX_SERIAL_H #include #include struct serial_struct { int type; int line; unsigned int port; int irq; int flags; int xmit_fifo_size; int custom_divisor; int baud_base; unsigned short close_delay; char io_type; char reserved_char[1]; int hub6; unsigned short closing_wait; /* time to wait before closing */ unsigned short closing_wait2; /* no longer used... */ unsigned char *iomem_base; unsigned short iomem_reg_shift; unsigned int port_high; unsigned long iomap_base; /* cookie passed into ioremap */ }; /* * For the close wait times, 0 means wait forever for serial port to * flush its output. 65535 means don't wait at all. */ #define ASYNC_CLOSING_WAIT_INF 0 #define ASYNC_CLOSING_WAIT_NONE 65535 /* * These are the supported serial types. */ #define PORT_UNKNOWN 0 #define PORT_8250 1 #define PORT_16450 2 #define PORT_16550 3 #define PORT_16550A 4 #define PORT_CIRRUS 5 /* usurped by cyclades.c */ #define PORT_16650 6 #define PORT_16650V2 7 #define PORT_16750 8 #define PORT_STARTECH 9 /* usurped by cyclades.c */ #define PORT_16C950 10 /* Oxford Semiconductor */ #define PORT_16654 11 #define PORT_16850 12 #define PORT_RSA 13 /* RSA-DV II/S card */ #define PORT_MAX 13 #define SERIAL_IO_PORT 0 #define SERIAL_IO_HUB6 1 #define SERIAL_IO_MEM 2 #define SERIAL_IO_MEM32 3 #define SERIAL_IO_AU 4 #define SERIAL_IO_TSI 5 #define SERIAL_IO_MEM32BE 6 #define SERIAL_IO_MEM16 7 #define UART_CLEAR_FIFO 0x01 #define UART_USE_FIFO 0x02 #define UART_STARTECH 0x04 #define UART_NATSEMI 0x08 /* * Multiport serial configuration structure --- external structure */ struct serial_multiport_struct { int irq; int port1; unsigned char mask1, match1; int port2; unsigned char mask2, match2; int port3; unsigned char mask3, match3; int port4; unsigned char mask4, match4; int port_monitor; int reserved[32]; }; /* * Serial input interrupt line counters -- external structure * Four lines can interrupt: CTS, DSR, RI, DCD */ struct serial_icounter_struct { int cts, dsr, rng, dcd; int rx, tx; int frame, overrun, parity, brk; int buf_overrun; int reserved[9]; }; /* * Serial interface for controlling RS485 settings on chips with suitable * support. Set with TIOCSRS485 and get with TIOCGRS485 if supported by your * platform. The set function returns the new state, with any unsupported bits * reverted appropriately. */ struct serial_rs485 { __u32 flags; /* RS485 feature flags */ #define SER_RS485_ENABLED (1 << 0) /* If enabled */ #define SER_RS485_RTS_ON_SEND (1 << 1) /* Logical level for RTS pin when sending */ #define SER_RS485_RTS_AFTER_SEND (1 << 2) /* Logical level for RTS pin after sent*/ #define SER_RS485_RX_DURING_TX (1 << 4) #define SER_RS485_TERMINATE_BUS (1 << 5) /* Enable bus termination (if supported) */ __u32 delay_rts_before_send; /* Delay before send (milliseconds) */ __u32 delay_rts_after_send; /* Delay after send (milliseconds) */ __u32 padding[5]; /* Memory is cheap, new structs are a royal PITA .. */ }; /* * Serial interface for controlling ISO7816 settings on chips with suitable * support. Set with TIOCSISO7816 and get with TIOCGISO7816 if supported by * your platform. */ struct serial_iso7816 { __u32 flags; /* ISO7816 feature flags */ #define SER_ISO7816_ENABLED (1 << 0) #define SER_ISO7816_T_PARAM (0x0f << 4) #define SER_ISO7816_T(t) (((t) & 0x0f) << 4) __u32 tg; __u32 sc_fi; __u32 sc_di; __u32 clk; __u32 reserved[5]; }; #endif /* _LINUX_SERIAL_H */ linux/tcp_metrics.h000064400000003015151027430560010372 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* tcp_metrics.h - TCP Metrics Interface */ #ifndef _LINUX_TCP_METRICS_H #define _LINUX_TCP_METRICS_H #include /* NETLINK_GENERIC related info */ #define TCP_METRICS_GENL_NAME "tcp_metrics" #define TCP_METRICS_GENL_VERSION 0x1 enum tcp_metric_index { TCP_METRIC_RTT, /* in ms units */ TCP_METRIC_RTTVAR, /* in ms units */ TCP_METRIC_SSTHRESH, TCP_METRIC_CWND, TCP_METRIC_REORDERING, TCP_METRIC_RTT_US, /* in usec units */ TCP_METRIC_RTTVAR_US, /* in usec units */ /* Always last. */ __TCP_METRIC_MAX, }; #define TCP_METRIC_MAX (__TCP_METRIC_MAX - 1) enum { TCP_METRICS_ATTR_UNSPEC, TCP_METRICS_ATTR_ADDR_IPV4, /* u32 */ TCP_METRICS_ATTR_ADDR_IPV6, /* binary */ TCP_METRICS_ATTR_AGE, /* msecs */ TCP_METRICS_ATTR_TW_TSVAL, /* u32, raw, rcv tsval */ TCP_METRICS_ATTR_TW_TS_STAMP, /* s32, sec age */ TCP_METRICS_ATTR_VALS, /* nested +1, u32 */ TCP_METRICS_ATTR_FOPEN_MSS, /* u16 */ TCP_METRICS_ATTR_FOPEN_SYN_DROPS, /* u16, count of drops */ TCP_METRICS_ATTR_FOPEN_SYN_DROP_TS, /* msecs age */ TCP_METRICS_ATTR_FOPEN_COOKIE, /* binary */ TCP_METRICS_ATTR_SADDR_IPV4, /* u32 */ TCP_METRICS_ATTR_SADDR_IPV6, /* binary */ TCP_METRICS_ATTR_PAD, __TCP_METRICS_ATTR_MAX, }; #define TCP_METRICS_ATTR_MAX (__TCP_METRICS_ATTR_MAX - 1) enum { TCP_METRICS_CMD_UNSPEC, TCP_METRICS_CMD_GET, TCP_METRICS_CMD_DEL, __TCP_METRICS_CMD_MAX, }; #define TCP_METRICS_CMD_MAX (__TCP_METRICS_CMD_MAX - 1) #endif /* _LINUX_TCP_METRICS_H */ linux/mrp_bridge.h000064400000003254151027430560010175 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _LINUX_MRP_BRIDGE_H_ #define _LINUX_MRP_BRIDGE_H_ #include #include #define MRP_MAX_FRAME_LENGTH 200 #define MRP_DEFAULT_PRIO 0x8000 #define MRP_DOMAIN_UUID_LENGTH 16 #define MRP_VERSION 1 #define MRP_FRAME_PRIO 7 #define MRP_OUI_LENGTH 3 #define MRP_MANUFACTURE_DATA_LENGTH 2 enum br_mrp_ring_role_type { BR_MRP_RING_ROLE_DISABLED, BR_MRP_RING_ROLE_MRC, BR_MRP_RING_ROLE_MRM, BR_MRP_RING_ROLE_MRA, }; enum br_mrp_in_role_type { BR_MRP_IN_ROLE_DISABLED, BR_MRP_IN_ROLE_MIC, BR_MRP_IN_ROLE_MIM, }; enum br_mrp_ring_state_type { BR_MRP_RING_STATE_OPEN, BR_MRP_RING_STATE_CLOSED, }; enum br_mrp_in_state_type { BR_MRP_IN_STATE_OPEN, BR_MRP_IN_STATE_CLOSED, }; enum br_mrp_port_state_type { BR_MRP_PORT_STATE_DISABLED, BR_MRP_PORT_STATE_BLOCKED, BR_MRP_PORT_STATE_FORWARDING, BR_MRP_PORT_STATE_NOT_CONNECTED, }; enum br_mrp_port_role_type { BR_MRP_PORT_ROLE_PRIMARY, BR_MRP_PORT_ROLE_SECONDARY, BR_MRP_PORT_ROLE_INTER, }; enum br_mrp_tlv_header_type { BR_MRP_TLV_HEADER_END = 0x0, BR_MRP_TLV_HEADER_COMMON = 0x1, BR_MRP_TLV_HEADER_RING_TEST = 0x2, BR_MRP_TLV_HEADER_RING_TOPO = 0x3, BR_MRP_TLV_HEADER_RING_LINK_DOWN = 0x4, BR_MRP_TLV_HEADER_RING_LINK_UP = 0x5, BR_MRP_TLV_HEADER_IN_TEST = 0x6, BR_MRP_TLV_HEADER_IN_TOPO = 0x7, BR_MRP_TLV_HEADER_IN_LINK_DOWN = 0x8, BR_MRP_TLV_HEADER_IN_LINK_UP = 0x9, BR_MRP_TLV_HEADER_IN_LINK_STATUS = 0xa, BR_MRP_TLV_HEADER_OPTION = 0x7f, }; enum br_mrp_sub_tlv_header_type { BR_MRP_SUB_TLV_HEADER_TEST_MGR_NACK = 0x1, BR_MRP_SUB_TLV_HEADER_TEST_PROPAGATE = 0x2, BR_MRP_SUB_TLV_HEADER_TEST_AUTO_MGR = 0x3, }; #endif linux/suspend_ioctls.h000064400000002627151027430560011124 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SUSPEND_IOCTLS_H #define _LINUX_SUSPEND_IOCTLS_H #include /* * This structure is used to pass the values needed for the identification * of the resume swap area from a user space to the kernel via the * SNAPSHOT_SET_SWAP_AREA ioctl */ struct resume_swap_area { __kernel_loff_t offset; __u32 dev; } __attribute__((packed)); #define SNAPSHOT_IOC_MAGIC '3' #define SNAPSHOT_FREEZE _IO(SNAPSHOT_IOC_MAGIC, 1) #define SNAPSHOT_UNFREEZE _IO(SNAPSHOT_IOC_MAGIC, 2) #define SNAPSHOT_ATOMIC_RESTORE _IO(SNAPSHOT_IOC_MAGIC, 4) #define SNAPSHOT_FREE _IO(SNAPSHOT_IOC_MAGIC, 5) #define SNAPSHOT_FREE_SWAP_PAGES _IO(SNAPSHOT_IOC_MAGIC, 9) #define SNAPSHOT_S2RAM _IO(SNAPSHOT_IOC_MAGIC, 11) #define SNAPSHOT_SET_SWAP_AREA _IOW(SNAPSHOT_IOC_MAGIC, 13, \ struct resume_swap_area) #define SNAPSHOT_GET_IMAGE_SIZE _IOR(SNAPSHOT_IOC_MAGIC, 14, __kernel_loff_t) #define SNAPSHOT_PLATFORM_SUPPORT _IO(SNAPSHOT_IOC_MAGIC, 15) #define SNAPSHOT_POWER_OFF _IO(SNAPSHOT_IOC_MAGIC, 16) #define SNAPSHOT_CREATE_IMAGE _IOW(SNAPSHOT_IOC_MAGIC, 17, int) #define SNAPSHOT_PREF_IMAGE_SIZE _IO(SNAPSHOT_IOC_MAGIC, 18) #define SNAPSHOT_AVAIL_SWAP_SIZE _IOR(SNAPSHOT_IOC_MAGIC, 19, __kernel_loff_t) #define SNAPSHOT_ALLOC_SWAP_PAGE _IOR(SNAPSHOT_IOC_MAGIC, 20, __kernel_loff_t) #define SNAPSHOT_IOC_MAXNR 20 #endif /* _LINUX_SUSPEND_IOCTLS_H */ linux/iommu.h000064400000011450151027430560007206 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * IOMMU user API definitions */ #ifndef _IOMMU_H #define _IOMMU_H #include #define IOMMU_FAULT_PERM_READ (1 << 0) /* read */ #define IOMMU_FAULT_PERM_WRITE (1 << 1) /* write */ #define IOMMU_FAULT_PERM_EXEC (1 << 2) /* exec */ #define IOMMU_FAULT_PERM_PRIV (1 << 3) /* privileged */ /* Generic fault types, can be expanded IRQ remapping fault */ enum iommu_fault_type { IOMMU_FAULT_DMA_UNRECOV = 1, /* unrecoverable fault */ IOMMU_FAULT_PAGE_REQ, /* page request fault */ }; enum iommu_fault_reason { IOMMU_FAULT_REASON_UNKNOWN = 0, /* Could not access the PASID table (fetch caused external abort) */ IOMMU_FAULT_REASON_PASID_FETCH, /* PASID entry is invalid or has configuration errors */ IOMMU_FAULT_REASON_BAD_PASID_ENTRY, /* * PASID is out of range (e.g. exceeds the maximum PASID * supported by the IOMMU) or disabled. */ IOMMU_FAULT_REASON_PASID_INVALID, /* * An external abort occurred fetching (or updating) a translation * table descriptor */ IOMMU_FAULT_REASON_WALK_EABT, /* * Could not access the page table entry (Bad address), * actual translation fault */ IOMMU_FAULT_REASON_PTE_FETCH, /* Protection flag check failed */ IOMMU_FAULT_REASON_PERMISSION, /* access flag check failed */ IOMMU_FAULT_REASON_ACCESS, /* Output address of a translation stage caused Address Size fault */ IOMMU_FAULT_REASON_OOR_ADDRESS, }; /** * struct iommu_fault_unrecoverable - Unrecoverable fault data * @reason: reason of the fault, from &enum iommu_fault_reason * @flags: parameters of this fault (IOMMU_FAULT_UNRECOV_* values) * @pasid: Process Address Space ID * @perm: requested permission access using by the incoming transaction * (IOMMU_FAULT_PERM_* values) * @addr: offending page address * @fetch_addr: address that caused a fetch abort, if any */ struct iommu_fault_unrecoverable { __u32 reason; #define IOMMU_FAULT_UNRECOV_PASID_VALID (1 << 0) #define IOMMU_FAULT_UNRECOV_ADDR_VALID (1 << 1) #define IOMMU_FAULT_UNRECOV_FETCH_ADDR_VALID (1 << 2) __u32 flags; __u32 pasid; __u32 perm; __u64 addr; __u64 fetch_addr; }; /** * struct iommu_fault_page_request - Page Request data * @flags: encodes whether the corresponding fields are valid and whether this * is the last page in group (IOMMU_FAULT_PAGE_REQUEST_* values). * When IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID is set, the page response * must have the same PASID value as the page request. When it is clear, * the page response should not have a PASID. * @pasid: Process Address Space ID * @grpid: Page Request Group Index * @perm: requested page permissions (IOMMU_FAULT_PERM_* values) * @addr: page address * @private_data: device-specific private information */ struct iommu_fault_page_request { #define IOMMU_FAULT_PAGE_REQUEST_PASID_VALID (1 << 0) #define IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE (1 << 1) #define IOMMU_FAULT_PAGE_REQUEST_PRIV_DATA (1 << 2) #define IOMMU_FAULT_PAGE_RESPONSE_NEEDS_PASID (1 << 3) __u32 flags; __u32 pasid; __u32 grpid; __u32 perm; __u64 addr; __u64 private_data[2]; }; /** * struct iommu_fault - Generic fault data * @type: fault type from &enum iommu_fault_type * @padding: reserved for future use (should be zero) * @event: fault event, when @type is %IOMMU_FAULT_DMA_UNRECOV * @prm: Page Request message, when @type is %IOMMU_FAULT_PAGE_REQ * @padding2: sets the fault size to allow for future extensions */ struct iommu_fault { __u32 type; __u32 padding; union { struct iommu_fault_unrecoverable event; struct iommu_fault_page_request prm; __u8 padding2[56]; }; }; /** * enum iommu_page_response_code - Return status of fault handlers * @IOMMU_PAGE_RESP_SUCCESS: Fault has been handled and the page tables * populated, retry the access. This is "Success" in PCI PRI. * @IOMMU_PAGE_RESP_FAILURE: General error. Drop all subsequent faults from * this device if possible. This is "Response Failure" in PCI PRI. * @IOMMU_PAGE_RESP_INVALID: Could not handle this fault, don't retry the * access. This is "Invalid Request" in PCI PRI. */ enum iommu_page_response_code { IOMMU_PAGE_RESP_SUCCESS = 0, IOMMU_PAGE_RESP_INVALID, IOMMU_PAGE_RESP_FAILURE, }; /** * struct iommu_page_response - Generic page response information * @argsz: User filled size of this data * @version: API version of this structure * @flags: encodes whether the corresponding fields are valid * (IOMMU_FAULT_PAGE_RESPONSE_* values) * @pasid: Process Address Space ID * @grpid: Page Request Group Index * @code: response code from &enum iommu_page_response_code */ struct iommu_page_response { __u32 argsz; #define IOMMU_PAGE_RESP_VERSION_1 1 __u32 version; #define IOMMU_PAGE_RESP_PASID_VALID (1 << 0) __u32 flags; __u32 pasid; __u32 grpid; __u32 code; }; #endif /* _IOMMU_H */ linux/xilinx-v4l2-controls.h000064400000005640151027430560012025 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Xilinx Controls Header * * Copyright (C) 2013-2015 Ideas on Board * Copyright (C) 2013-2015 Xilinx, Inc. * * Contacts: Hyun Kwon * Laurent Pinchart * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __UAPI_XILINX_V4L2_CONTROLS_H__ #define __UAPI_XILINX_V4L2_CONTROLS_H__ #include #define V4L2_CID_XILINX_OFFSET 0xc000 #define V4L2_CID_XILINX_BASE (V4L2_CID_USER_BASE + V4L2_CID_XILINX_OFFSET) /* * Private Controls for Xilinx Video IPs */ /* * Xilinx TPG Video IP */ #define V4L2_CID_XILINX_TPG (V4L2_CID_USER_BASE + 0xc000) /* Draw cross hairs */ #define V4L2_CID_XILINX_TPG_CROSS_HAIRS (V4L2_CID_XILINX_TPG + 1) /* Enable a moving box */ #define V4L2_CID_XILINX_TPG_MOVING_BOX (V4L2_CID_XILINX_TPG + 2) /* Mask out a color component */ #define V4L2_CID_XILINX_TPG_COLOR_MASK (V4L2_CID_XILINX_TPG + 3) /* Enable a stuck pixel feature */ #define V4L2_CID_XILINX_TPG_STUCK_PIXEL (V4L2_CID_XILINX_TPG + 4) /* Enable a noisy output */ #define V4L2_CID_XILINX_TPG_NOISE (V4L2_CID_XILINX_TPG + 5) /* Enable the motion feature */ #define V4L2_CID_XILINX_TPG_MOTION (V4L2_CID_XILINX_TPG + 6) /* Configure the motion speed of moving patterns */ #define V4L2_CID_XILINX_TPG_MOTION_SPEED (V4L2_CID_XILINX_TPG + 7) /* The row of horizontal cross hair location */ #define V4L2_CID_XILINX_TPG_CROSS_HAIR_ROW (V4L2_CID_XILINX_TPG + 8) /* The colum of vertical cross hair location */ #define V4L2_CID_XILINX_TPG_CROSS_HAIR_COLUMN (V4L2_CID_XILINX_TPG + 9) /* Set starting point of sine wave for horizontal component */ #define V4L2_CID_XILINX_TPG_ZPLATE_HOR_START (V4L2_CID_XILINX_TPG + 10) /* Set speed of the horizontal component */ #define V4L2_CID_XILINX_TPG_ZPLATE_HOR_SPEED (V4L2_CID_XILINX_TPG + 11) /* Set starting point of sine wave for vertical component */ #define V4L2_CID_XILINX_TPG_ZPLATE_VER_START (V4L2_CID_XILINX_TPG + 12) /* Set speed of the vertical component */ #define V4L2_CID_XILINX_TPG_ZPLATE_VER_SPEED (V4L2_CID_XILINX_TPG + 13) /* Moving box size */ #define V4L2_CID_XILINX_TPG_BOX_SIZE (V4L2_CID_XILINX_TPG + 14) /* Moving box color */ #define V4L2_CID_XILINX_TPG_BOX_COLOR (V4L2_CID_XILINX_TPG + 15) /* Upper limit count of generated stuck pixels */ #define V4L2_CID_XILINX_TPG_STUCK_PIXEL_THRESH (V4L2_CID_XILINX_TPG + 16) /* Noise level */ #define V4L2_CID_XILINX_TPG_NOISE_GAIN (V4L2_CID_XILINX_TPG + 17) #endif /* __UAPI_XILINX_V4L2_CONTROLS_H__ */ linux/keyboard.h000064400000030757151027430560007673 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_KEYBOARD_H #define __LINUX_KEYBOARD_H #include #define KG_SHIFT 0 #define KG_CTRL 2 #define KG_ALT 3 #define KG_ALTGR 1 #define KG_SHIFTL 4 #define KG_KANASHIFT 4 #define KG_SHIFTR 5 #define KG_CTRLL 6 #define KG_CTRLR 7 #define KG_CAPSSHIFT 8 #define NR_SHIFT 9 #define NR_KEYS 256 #define MAX_NR_KEYMAPS 256 /* This means 128Kb if all keymaps are allocated. Only the superuser may increase the number of keymaps beyond MAX_NR_OF_USER_KEYMAPS. */ #define MAX_NR_OF_USER_KEYMAPS 256 /* should be at least 7 */ #define MAX_NR_FUNC 256 /* max nr of strings assigned to keys */ #define KT_LATIN 0 /* we depend on this being zero */ #define KT_LETTER 11 /* symbol that can be acted upon by CapsLock */ #define KT_FN 1 #define KT_SPEC 2 #define KT_PAD 3 #define KT_DEAD 4 #define KT_CONS 5 #define KT_CUR 6 #define KT_SHIFT 7 #define KT_META 8 #define KT_ASCII 9 #define KT_LOCK 10 #define KT_SLOCK 12 #define KT_DEAD2 13 #define KT_BRL 14 #define K(t,v) (((t)<<8)|(v)) #define KTYP(x) ((x) >> 8) #define KVAL(x) ((x) & 0xff) #define K_F1 K(KT_FN,0) #define K_F2 K(KT_FN,1) #define K_F3 K(KT_FN,2) #define K_F4 K(KT_FN,3) #define K_F5 K(KT_FN,4) #define K_F6 K(KT_FN,5) #define K_F7 K(KT_FN,6) #define K_F8 K(KT_FN,7) #define K_F9 K(KT_FN,8) #define K_F10 K(KT_FN,9) #define K_F11 K(KT_FN,10) #define K_F12 K(KT_FN,11) #define K_F13 K(KT_FN,12) #define K_F14 K(KT_FN,13) #define K_F15 K(KT_FN,14) #define K_F16 K(KT_FN,15) #define K_F17 K(KT_FN,16) #define K_F18 K(KT_FN,17) #define K_F19 K(KT_FN,18) #define K_F20 K(KT_FN,19) #define K_FIND K(KT_FN,20) #define K_INSERT K(KT_FN,21) #define K_REMOVE K(KT_FN,22) #define K_SELECT K(KT_FN,23) #define K_PGUP K(KT_FN,24) /* PGUP is a synonym for PRIOR */ #define K_PGDN K(KT_FN,25) /* PGDN is a synonym for NEXT */ #define K_MACRO K(KT_FN,26) #define K_HELP K(KT_FN,27) #define K_DO K(KT_FN,28) #define K_PAUSE K(KT_FN,29) #define K_F21 K(KT_FN,30) #define K_F22 K(KT_FN,31) #define K_F23 K(KT_FN,32) #define K_F24 K(KT_FN,33) #define K_F25 K(KT_FN,34) #define K_F26 K(KT_FN,35) #define K_F27 K(KT_FN,36) #define K_F28 K(KT_FN,37) #define K_F29 K(KT_FN,38) #define K_F30 K(KT_FN,39) #define K_F31 K(KT_FN,40) #define K_F32 K(KT_FN,41) #define K_F33 K(KT_FN,42) #define K_F34 K(KT_FN,43) #define K_F35 K(KT_FN,44) #define K_F36 K(KT_FN,45) #define K_F37 K(KT_FN,46) #define K_F38 K(KT_FN,47) #define K_F39 K(KT_FN,48) #define K_F40 K(KT_FN,49) #define K_F41 K(KT_FN,50) #define K_F42 K(KT_FN,51) #define K_F43 K(KT_FN,52) #define K_F44 K(KT_FN,53) #define K_F45 K(KT_FN,54) #define K_F46 K(KT_FN,55) #define K_F47 K(KT_FN,56) #define K_F48 K(KT_FN,57) #define K_F49 K(KT_FN,58) #define K_F50 K(KT_FN,59) #define K_F51 K(KT_FN,60) #define K_F52 K(KT_FN,61) #define K_F53 K(KT_FN,62) #define K_F54 K(KT_FN,63) #define K_F55 K(KT_FN,64) #define K_F56 K(KT_FN,65) #define K_F57 K(KT_FN,66) #define K_F58 K(KT_FN,67) #define K_F59 K(KT_FN,68) #define K_F60 K(KT_FN,69) #define K_F61 K(KT_FN,70) #define K_F62 K(KT_FN,71) #define K_F63 K(KT_FN,72) #define K_F64 K(KT_FN,73) #define K_F65 K(KT_FN,74) #define K_F66 K(KT_FN,75) #define K_F67 K(KT_FN,76) #define K_F68 K(KT_FN,77) #define K_F69 K(KT_FN,78) #define K_F70 K(KT_FN,79) #define K_F71 K(KT_FN,80) #define K_F72 K(KT_FN,81) #define K_F73 K(KT_FN,82) #define K_F74 K(KT_FN,83) #define K_F75 K(KT_FN,84) #define K_F76 K(KT_FN,85) #define K_F77 K(KT_FN,86) #define K_F78 K(KT_FN,87) #define K_F79 K(KT_FN,88) #define K_F80 K(KT_FN,89) #define K_F81 K(KT_FN,90) #define K_F82 K(KT_FN,91) #define K_F83 K(KT_FN,92) #define K_F84 K(KT_FN,93) #define K_F85 K(KT_FN,94) #define K_F86 K(KT_FN,95) #define K_F87 K(KT_FN,96) #define K_F88 K(KT_FN,97) #define K_F89 K(KT_FN,98) #define K_F90 K(KT_FN,99) #define K_F91 K(KT_FN,100) #define K_F92 K(KT_FN,101) #define K_F93 K(KT_FN,102) #define K_F94 K(KT_FN,103) #define K_F95 K(KT_FN,104) #define K_F96 K(KT_FN,105) #define K_F97 K(KT_FN,106) #define K_F98 K(KT_FN,107) #define K_F99 K(KT_FN,108) #define K_F100 K(KT_FN,109) #define K_F101 K(KT_FN,110) #define K_F102 K(KT_FN,111) #define K_F103 K(KT_FN,112) #define K_F104 K(KT_FN,113) #define K_F105 K(KT_FN,114) #define K_F106 K(KT_FN,115) #define K_F107 K(KT_FN,116) #define K_F108 K(KT_FN,117) #define K_F109 K(KT_FN,118) #define K_F110 K(KT_FN,119) #define K_F111 K(KT_FN,120) #define K_F112 K(KT_FN,121) #define K_F113 K(KT_FN,122) #define K_F114 K(KT_FN,123) #define K_F115 K(KT_FN,124) #define K_F116 K(KT_FN,125) #define K_F117 K(KT_FN,126) #define K_F118 K(KT_FN,127) #define K_F119 K(KT_FN,128) #define K_F120 K(KT_FN,129) #define K_F121 K(KT_FN,130) #define K_F122 K(KT_FN,131) #define K_F123 K(KT_FN,132) #define K_F124 K(KT_FN,133) #define K_F125 K(KT_FN,134) #define K_F126 K(KT_FN,135) #define K_F127 K(KT_FN,136) #define K_F128 K(KT_FN,137) #define K_F129 K(KT_FN,138) #define K_F130 K(KT_FN,139) #define K_F131 K(KT_FN,140) #define K_F132 K(KT_FN,141) #define K_F133 K(KT_FN,142) #define K_F134 K(KT_FN,143) #define K_F135 K(KT_FN,144) #define K_F136 K(KT_FN,145) #define K_F137 K(KT_FN,146) #define K_F138 K(KT_FN,147) #define K_F139 K(KT_FN,148) #define K_F140 K(KT_FN,149) #define K_F141 K(KT_FN,150) #define K_F142 K(KT_FN,151) #define K_F143 K(KT_FN,152) #define K_F144 K(KT_FN,153) #define K_F145 K(KT_FN,154) #define K_F146 K(KT_FN,155) #define K_F147 K(KT_FN,156) #define K_F148 K(KT_FN,157) #define K_F149 K(KT_FN,158) #define K_F150 K(KT_FN,159) #define K_F151 K(KT_FN,160) #define K_F152 K(KT_FN,161) #define K_F153 K(KT_FN,162) #define K_F154 K(KT_FN,163) #define K_F155 K(KT_FN,164) #define K_F156 K(KT_FN,165) #define K_F157 K(KT_FN,166) #define K_F158 K(KT_FN,167) #define K_F159 K(KT_FN,168) #define K_F160 K(KT_FN,169) #define K_F161 K(KT_FN,170) #define K_F162 K(KT_FN,171) #define K_F163 K(KT_FN,172) #define K_F164 K(KT_FN,173) #define K_F165 K(KT_FN,174) #define K_F166 K(KT_FN,175) #define K_F167 K(KT_FN,176) #define K_F168 K(KT_FN,177) #define K_F169 K(KT_FN,178) #define K_F170 K(KT_FN,179) #define K_F171 K(KT_FN,180) #define K_F172 K(KT_FN,181) #define K_F173 K(KT_FN,182) #define K_F174 K(KT_FN,183) #define K_F175 K(KT_FN,184) #define K_F176 K(KT_FN,185) #define K_F177 K(KT_FN,186) #define K_F178 K(KT_FN,187) #define K_F179 K(KT_FN,188) #define K_F180 K(KT_FN,189) #define K_F181 K(KT_FN,190) #define K_F182 K(KT_FN,191) #define K_F183 K(KT_FN,192) #define K_F184 K(KT_FN,193) #define K_F185 K(KT_FN,194) #define K_F186 K(KT_FN,195) #define K_F187 K(KT_FN,196) #define K_F188 K(KT_FN,197) #define K_F189 K(KT_FN,198) #define K_F190 K(KT_FN,199) #define K_F191 K(KT_FN,200) #define K_F192 K(KT_FN,201) #define K_F193 K(KT_FN,202) #define K_F194 K(KT_FN,203) #define K_F195 K(KT_FN,204) #define K_F196 K(KT_FN,205) #define K_F197 K(KT_FN,206) #define K_F198 K(KT_FN,207) #define K_F199 K(KT_FN,208) #define K_F200 K(KT_FN,209) #define K_F201 K(KT_FN,210) #define K_F202 K(KT_FN,211) #define K_F203 K(KT_FN,212) #define K_F204 K(KT_FN,213) #define K_F205 K(KT_FN,214) #define K_F206 K(KT_FN,215) #define K_F207 K(KT_FN,216) #define K_F208 K(KT_FN,217) #define K_F209 K(KT_FN,218) #define K_F210 K(KT_FN,219) #define K_F211 K(KT_FN,220) #define K_F212 K(KT_FN,221) #define K_F213 K(KT_FN,222) #define K_F214 K(KT_FN,223) #define K_F215 K(KT_FN,224) #define K_F216 K(KT_FN,225) #define K_F217 K(KT_FN,226) #define K_F218 K(KT_FN,227) #define K_F219 K(KT_FN,228) #define K_F220 K(KT_FN,229) #define K_F221 K(KT_FN,230) #define K_F222 K(KT_FN,231) #define K_F223 K(KT_FN,232) #define K_F224 K(KT_FN,233) #define K_F225 K(KT_FN,234) #define K_F226 K(KT_FN,235) #define K_F227 K(KT_FN,236) #define K_F228 K(KT_FN,237) #define K_F229 K(KT_FN,238) #define K_F230 K(KT_FN,239) #define K_F231 K(KT_FN,240) #define K_F232 K(KT_FN,241) #define K_F233 K(KT_FN,242) #define K_F234 K(KT_FN,243) #define K_F235 K(KT_FN,244) #define K_F236 K(KT_FN,245) #define K_F237 K(KT_FN,246) #define K_F238 K(KT_FN,247) #define K_F239 K(KT_FN,248) #define K_F240 K(KT_FN,249) #define K_F241 K(KT_FN,250) #define K_F242 K(KT_FN,251) #define K_F243 K(KT_FN,252) #define K_F244 K(KT_FN,253) #define K_F245 K(KT_FN,254) #define K_UNDO K(KT_FN,255) #define K_HOLE K(KT_SPEC,0) #define K_ENTER K(KT_SPEC,1) #define K_SH_REGS K(KT_SPEC,2) #define K_SH_MEM K(KT_SPEC,3) #define K_SH_STAT K(KT_SPEC,4) #define K_BREAK K(KT_SPEC,5) #define K_CONS K(KT_SPEC,6) #define K_CAPS K(KT_SPEC,7) #define K_NUM K(KT_SPEC,8) #define K_HOLD K(KT_SPEC,9) #define K_SCROLLFORW K(KT_SPEC,10) #define K_SCROLLBACK K(KT_SPEC,11) #define K_BOOT K(KT_SPEC,12) #define K_CAPSON K(KT_SPEC,13) #define K_COMPOSE K(KT_SPEC,14) #define K_SAK K(KT_SPEC,15) #define K_DECRCONSOLE K(KT_SPEC,16) #define K_INCRCONSOLE K(KT_SPEC,17) #define K_SPAWNCONSOLE K(KT_SPEC,18) #define K_BARENUMLOCK K(KT_SPEC,19) #define K_ALLOCATED K(KT_SPEC,126) /* dynamically allocated keymap */ #define K_NOSUCHMAP K(KT_SPEC,127) /* returned by KDGKBENT */ #define K_P0 K(KT_PAD,0) #define K_P1 K(KT_PAD,1) #define K_P2 K(KT_PAD,2) #define K_P3 K(KT_PAD,3) #define K_P4 K(KT_PAD,4) #define K_P5 K(KT_PAD,5) #define K_P6 K(KT_PAD,6) #define K_P7 K(KT_PAD,7) #define K_P8 K(KT_PAD,8) #define K_P9 K(KT_PAD,9) #define K_PPLUS K(KT_PAD,10) /* key-pad plus */ #define K_PMINUS K(KT_PAD,11) /* key-pad minus */ #define K_PSTAR K(KT_PAD,12) /* key-pad asterisk (star) */ #define K_PSLASH K(KT_PAD,13) /* key-pad slash */ #define K_PENTER K(KT_PAD,14) /* key-pad enter */ #define K_PCOMMA K(KT_PAD,15) /* key-pad comma: kludge... */ #define K_PDOT K(KT_PAD,16) /* key-pad dot (period): kludge... */ #define K_PPLUSMINUS K(KT_PAD,17) /* key-pad plus/minus */ #define K_PPARENL K(KT_PAD,18) /* key-pad left parenthesis */ #define K_PPARENR K(KT_PAD,19) /* key-pad right parenthesis */ #define NR_PAD 20 #define K_DGRAVE K(KT_DEAD,0) #define K_DACUTE K(KT_DEAD,1) #define K_DCIRCM K(KT_DEAD,2) #define K_DTILDE K(KT_DEAD,3) #define K_DDIERE K(KT_DEAD,4) #define K_DCEDIL K(KT_DEAD,5) #define NR_DEAD 6 #define K_DOWN K(KT_CUR,0) #define K_LEFT K(KT_CUR,1) #define K_RIGHT K(KT_CUR,2) #define K_UP K(KT_CUR,3) #define K_SHIFT K(KT_SHIFT,KG_SHIFT) #define K_CTRL K(KT_SHIFT,KG_CTRL) #define K_ALT K(KT_SHIFT,KG_ALT) #define K_ALTGR K(KT_SHIFT,KG_ALTGR) #define K_SHIFTL K(KT_SHIFT,KG_SHIFTL) #define K_SHIFTR K(KT_SHIFT,KG_SHIFTR) #define K_CTRLL K(KT_SHIFT,KG_CTRLL) #define K_CTRLR K(KT_SHIFT,KG_CTRLR) #define K_CAPSSHIFT K(KT_SHIFT,KG_CAPSSHIFT) #define K_ASC0 K(KT_ASCII,0) #define K_ASC1 K(KT_ASCII,1) #define K_ASC2 K(KT_ASCII,2) #define K_ASC3 K(KT_ASCII,3) #define K_ASC4 K(KT_ASCII,4) #define K_ASC5 K(KT_ASCII,5) #define K_ASC6 K(KT_ASCII,6) #define K_ASC7 K(KT_ASCII,7) #define K_ASC8 K(KT_ASCII,8) #define K_ASC9 K(KT_ASCII,9) #define K_HEX0 K(KT_ASCII,10) #define K_HEX1 K(KT_ASCII,11) #define K_HEX2 K(KT_ASCII,12) #define K_HEX3 K(KT_ASCII,13) #define K_HEX4 K(KT_ASCII,14) #define K_HEX5 K(KT_ASCII,15) #define K_HEX6 K(KT_ASCII,16) #define K_HEX7 K(KT_ASCII,17) #define K_HEX8 K(KT_ASCII,18) #define K_HEX9 K(KT_ASCII,19) #define K_HEXa K(KT_ASCII,20) #define K_HEXb K(KT_ASCII,21) #define K_HEXc K(KT_ASCII,22) #define K_HEXd K(KT_ASCII,23) #define K_HEXe K(KT_ASCII,24) #define K_HEXf K(KT_ASCII,25) #define NR_ASCII 26 #define K_SHIFTLOCK K(KT_LOCK,KG_SHIFT) #define K_CTRLLOCK K(KT_LOCK,KG_CTRL) #define K_ALTLOCK K(KT_LOCK,KG_ALT) #define K_ALTGRLOCK K(KT_LOCK,KG_ALTGR) #define K_SHIFTLLOCK K(KT_LOCK,KG_SHIFTL) #define K_SHIFTRLOCK K(KT_LOCK,KG_SHIFTR) #define K_CTRLLLOCK K(KT_LOCK,KG_CTRLL) #define K_CTRLRLOCK K(KT_LOCK,KG_CTRLR) #define K_CAPSSHIFTLOCK K(KT_LOCK,KG_CAPSSHIFT) #define K_SHIFT_SLOCK K(KT_SLOCK,KG_SHIFT) #define K_CTRL_SLOCK K(KT_SLOCK,KG_CTRL) #define K_ALT_SLOCK K(KT_SLOCK,KG_ALT) #define K_ALTGR_SLOCK K(KT_SLOCK,KG_ALTGR) #define K_SHIFTL_SLOCK K(KT_SLOCK,KG_SHIFTL) #define K_SHIFTR_SLOCK K(KT_SLOCK,KG_SHIFTR) #define K_CTRLL_SLOCK K(KT_SLOCK,KG_CTRLL) #define K_CTRLR_SLOCK K(KT_SLOCK,KG_CTRLR) #define K_CAPSSHIFT_SLOCK K(KT_SLOCK,KG_CAPSSHIFT) #define NR_LOCK 9 #define K_BRL_BLANK K(KT_BRL, 0) #define K_BRL_DOT1 K(KT_BRL, 1) #define K_BRL_DOT2 K(KT_BRL, 2) #define K_BRL_DOT3 K(KT_BRL, 3) #define K_BRL_DOT4 K(KT_BRL, 4) #define K_BRL_DOT5 K(KT_BRL, 5) #define K_BRL_DOT6 K(KT_BRL, 6) #define K_BRL_DOT7 K(KT_BRL, 7) #define K_BRL_DOT8 K(KT_BRL, 8) #define K_BRL_DOT9 K(KT_BRL, 9) #define K_BRL_DOT10 K(KT_BRL, 10) #define NR_BRL 11 #define MAX_DIACR 256 #endif /* __LINUX_KEYBOARD_H */ linux/nl80211.h000064400001216640151027430560007076 0ustar00#ifndef __LINUX_NL80211_H #define __LINUX_NL80211_H /* * 802.11 netlink interface public header * * Copyright 2006-2010 Johannes Berg * Copyright 2008 Michael Wu * Copyright 2008 Luis Carlos Cobo * Copyright 2008 Michael Buesch * Copyright 2008, 2009 Luis R. Rodriguez * Copyright 2008 Jouni Malinen * Copyright 2008 Colin McCabe * Copyright 2015-2017 Intel Deutschland GmbH * Copyright (C) 2018-2022 Intel Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ /* * This header file defines the userspace API to the wireless stack. Please * be careful not to break things - i.e. don't move anything around or so * unless you can demonstrate that it breaks neither API nor ABI. * * Additions to the API should be accompanied by actual implementations in * an upstream driver, so that example implementations exist in case there * are ever concerns about the precise semantics of the API or changes are * needed, and to ensure that code for dead (no longer implemented) API * can actually be identified and removed. * Nonetheless, semantics should also be documented carefully in this file. */ #include #define NL80211_GENL_NAME "nl80211" #define NL80211_MULTICAST_GROUP_CONFIG "config" #define NL80211_MULTICAST_GROUP_SCAN "scan" #define NL80211_MULTICAST_GROUP_REG "regulatory" #define NL80211_MULTICAST_GROUP_MLME "mlme" #define NL80211_MULTICAST_GROUP_VENDOR "vendor" #define NL80211_MULTICAST_GROUP_NAN "nan" #define NL80211_MULTICAST_GROUP_TESTMODE "testmode" #define NL80211_EDMG_BW_CONFIG_MIN 4 #define NL80211_EDMG_BW_CONFIG_MAX 15 #define NL80211_EDMG_CHANNELS_MIN 1 #define NL80211_EDMG_CHANNELS_MAX 0x3c /* 0b00111100 */ /** * DOC: Station handling * * Stations are added per interface, but a special case exists with VLAN * interfaces. When a station is bound to an AP interface, it may be moved * into a VLAN identified by a VLAN interface index (%NL80211_ATTR_STA_VLAN). * The station is still assumed to belong to the AP interface it was added * to. * * Station handling varies per interface type and depending on the driver's * capabilities. * * For drivers supporting TDLS with external setup (WIPHY_FLAG_SUPPORTS_TDLS * and WIPHY_FLAG_TDLS_EXTERNAL_SETUP), the station lifetime is as follows: * - a setup station entry is added, not yet authorized, without any rate * or capability information, this just exists to avoid race conditions * - when the TDLS setup is done, a single NL80211_CMD_SET_STATION is valid * to add rate and capability information to the station and at the same * time mark it authorized. * - %NL80211_TDLS_ENABLE_LINK is then used * - after this, the only valid operation is to remove it by tearing down * the TDLS link (%NL80211_TDLS_DISABLE_LINK) * * TODO: need more info for other interface types */ /** * DOC: Frame transmission/registration support * * Frame transmission and registration support exists to allow userspace * management entities such as wpa_supplicant react to management frames * that are not being handled by the kernel. This includes, for example, * certain classes of action frames that cannot be handled in the kernel * for various reasons. * * Frame registration is done on a per-interface basis and registrations * cannot be removed other than by closing the socket. It is possible to * specify a registration filter to register, for example, only for a * certain type of action frame. In particular with action frames, those * that userspace registers for will not be returned as unhandled by the * driver, so that the registered application has to take responsibility * for doing that. * * The type of frame that can be registered for is also dependent on the * driver and interface type. The frame types are advertised in wiphy * attributes so applications know what to expect. * * NOTE: When an interface changes type while registrations are active, * these registrations are ignored until the interface type is * changed again. This means that changing the interface type can * lead to a situation that couldn't otherwise be produced, but * any such registrations will be dormant in the sense that they * will not be serviced, i.e. they will not receive any frames. * * Frame transmission allows userspace to send for example the required * responses to action frames. It is subject to some sanity checking, * but many frames can be transmitted. When a frame was transmitted, its * status is indicated to the sending socket. * * For more technical details, see the corresponding command descriptions * below. */ /** * DOC: Virtual interface / concurrency capabilities * * Some devices are able to operate with virtual MACs, they can have * more than one virtual interface. The capability handling for this * is a bit complex though, as there may be a number of restrictions * on the types of concurrency that are supported. * * To start with, each device supports the interface types listed in * the %NL80211_ATTR_SUPPORTED_IFTYPES attribute, but by listing the * types there no concurrency is implied. * * Once concurrency is desired, more attributes must be observed: * To start with, since some interface types are purely managed in * software, like the AP-VLAN type in mac80211 for example, there's * an additional list of these, they can be added at any time and * are only restricted by some semantic restrictions (e.g. AP-VLAN * cannot be added without a corresponding AP interface). This list * is exported in the %NL80211_ATTR_SOFTWARE_IFTYPES attribute. * * Further, the list of supported combinations is exported. This is * in the %NL80211_ATTR_INTERFACE_COMBINATIONS attribute. Basically, * it exports a list of "groups", and at any point in time the * interfaces that are currently active must fall into any one of * the advertised groups. Within each group, there are restrictions * on the number of interfaces of different types that are supported * and also the number of different channels, along with potentially * some other restrictions. See &enum nl80211_if_combination_attrs. * * All together, these attributes define the concurrency of virtual * interfaces that a given device supports. */ /** * DOC: packet coalesce support * * In most cases, host that receives IPv4 and IPv6 multicast/broadcast * packets does not do anything with these packets. Therefore the * reception of these unwanted packets causes unnecessary processing * and power consumption. * * Packet coalesce feature helps to reduce number of received interrupts * to host by buffering these packets in firmware/hardware for some * predefined time. Received interrupt will be generated when one of the * following events occur. * a) Expiration of hardware timer whose expiration time is set to maximum * coalescing delay of matching coalesce rule. * b) Coalescing buffer in hardware reaches it's limit. * c) Packet doesn't match any of the configured coalesce rules. * * User needs to configure following parameters for creating a coalesce * rule. * a) Maximum coalescing delay * b) List of packet patterns which needs to be matched * c) Condition for coalescence. pattern 'match' or 'no match' * Multiple such rules can be created. */ /** * DOC: WPA/WPA2 EAPOL handshake offload * * By setting @NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_PSK flag drivers * can indicate they support offloading EAPOL handshakes for WPA/WPA2 * preshared key authentication in station mode. In %NL80211_CMD_CONNECT * the preshared key should be specified using %NL80211_ATTR_PMK. Drivers * supporting this offload may reject the %NL80211_CMD_CONNECT when no * preshared key material is provided, for example when that driver does * not support setting the temporal keys through %NL80211_CMD_NEW_KEY. * * Similarly @NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_1X flag can be * set by drivers indicating offload support of the PTK/GTK EAPOL * handshakes during 802.1X authentication in station mode. In order to * use the offload the %NL80211_CMD_CONNECT should have * %NL80211_ATTR_WANT_1X_4WAY_HS attribute flag. Drivers supporting this * offload may reject the %NL80211_CMD_CONNECT when the attribute flag is * not present. * * By setting @NL80211_EXT_FEATURE_4WAY_HANDSHAKE_AP_PSK flag drivers * can indicate they support offloading EAPOL handshakes for WPA/WPA2 * preshared key authentication in AP mode. In %NL80211_CMD_START_AP * the preshared key should be specified using %NL80211_ATTR_PMK. Drivers * supporting this offload may reject the %NL80211_CMD_START_AP when no * preshared key material is provided, for example when that driver does * not support setting the temporal keys through %NL80211_CMD_NEW_KEY. * * For 802.1X the PMK or PMK-R0 are set by providing %NL80211_ATTR_PMK * using %NL80211_CMD_SET_PMK. For offloaded FT support also * %NL80211_ATTR_PMKR0_NAME must be provided. */ /** * DOC: FILS shared key authentication offload * * FILS shared key authentication offload can be advertized by drivers by * setting @NL80211_EXT_FEATURE_FILS_SK_OFFLOAD flag. The drivers that support * FILS shared key authentication offload should be able to construct the * authentication and association frames for FILS shared key authentication and * eventually do a key derivation as per IEEE 802.11ai. The below additional * parameters should be given to driver in %NL80211_CMD_CONNECT and/or in * %NL80211_CMD_UPDATE_CONNECT_PARAMS. * %NL80211_ATTR_FILS_ERP_USERNAME - used to construct keyname_nai * %NL80211_ATTR_FILS_ERP_REALM - used to construct keyname_nai * %NL80211_ATTR_FILS_ERP_NEXT_SEQ_NUM - used to construct erp message * %NL80211_ATTR_FILS_ERP_RRK - used to generate the rIK and rMSK * rIK should be used to generate an authentication tag on the ERP message and * rMSK should be used to derive a PMKSA. * rIK, rMSK should be generated and keyname_nai, sequence number should be used * as specified in IETF RFC 6696. * * When FILS shared key authentication is completed, driver needs to provide the * below additional parameters to userspace, which can be either after setting * up a connection or after roaming. * %NL80211_ATTR_FILS_KEK - used for key renewal * %NL80211_ATTR_FILS_ERP_NEXT_SEQ_NUM - used in further EAP-RP exchanges * %NL80211_ATTR_PMKID - used to identify the PMKSA used/generated * %Nl80211_ATTR_PMK - used to update PMKSA cache in userspace * The PMKSA can be maintained in userspace persistently so that it can be used * later after reboots or wifi turn off/on also. * * %NL80211_ATTR_FILS_CACHE_ID is the cache identifier advertized by a FILS * capable AP supporting PMK caching. It specifies the scope within which the * PMKSAs are cached in an ESS. %NL80211_CMD_SET_PMKSA and * %NL80211_CMD_DEL_PMKSA are enhanced to allow support for PMKSA caching based * on FILS cache identifier. Additionally %NL80211_ATTR_PMK is used with * %NL80211_SET_PMKSA to specify the PMK corresponding to a PMKSA for driver to * use in a FILS shared key connection with PMKSA caching. */ /** * DOC: SAE authentication offload * * By setting @NL80211_EXT_FEATURE_SAE_OFFLOAD flag drivers can indicate they * support offloading SAE authentication for WPA3-Personal networks in station * mode. Similarly @NL80211_EXT_FEATURE_SAE_OFFLOAD_AP flag can be set by * drivers indicating the offload support in AP mode. * * The password for SAE should be specified using %NL80211_ATTR_SAE_PASSWORD in * %NL80211_CMD_CONNECT and %NL80211_CMD_START_AP for station and AP mode * respectively. */ /** * DOC: VLAN offload support for setting group keys and binding STAs to VLANs * * By setting @NL80211_EXT_FEATURE_VLAN_OFFLOAD flag drivers can indicate they * support offloading VLAN functionality in a manner where the driver exposes a * single netdev that uses VLAN tagged frames and separate VLAN-specific netdevs * can then be added using RTM_NEWLINK/IFLA_VLAN_ID similarly to the Ethernet * case. Frames received from stations that are not assigned to any VLAN are * delivered on the main netdev and frames to such stations can be sent through * that main netdev. * * %NL80211_CMD_NEW_KEY (for group keys), %NL80211_CMD_NEW_STATION, and * %NL80211_CMD_SET_STATION will optionally specify vlan_id using * %NL80211_ATTR_VLAN_ID. */ /** * DOC: TID configuration * * TID config support can be checked in the %NL80211_ATTR_TID_CONFIG * attribute given in wiphy capabilities. * * The necessary configuration parameters are mentioned in * &enum nl80211_tid_config_attr and it will be passed to the * %NL80211_CMD_SET_TID_CONFIG command in %NL80211_ATTR_TID_CONFIG. * * If the configuration needs to be applied for specific peer then the MAC * address of the peer needs to be passed in %NL80211_ATTR_MAC, otherwise the * configuration will be applied for all the connected peers in the vif except * any peers that have peer specific configuration for the TID by default; if * the %NL80211_TID_CONFIG_ATTR_OVERRIDE flag is set, peer specific values * will be overwritten. * * All this configuration is valid only for STA's current connection * i.e. the configuration will be reset to default when the STA connects back * after disconnection/roaming, and this configuration will be cleared when * the interface goes down. */ /** * DOC: FILS shared key crypto offload * * This feature is applicable to drivers running in AP mode. * * FILS shared key crypto offload can be advertised by drivers by setting * @NL80211_EXT_FEATURE_FILS_CRYPTO_OFFLOAD flag. The drivers that support * FILS shared key crypto offload should be able to encrypt and decrypt * association frames for FILS shared key authentication as per IEEE 802.11ai. * With this capability, for FILS key derivation, drivers depend on userspace. * * After FILS key derivation, userspace shares the FILS AAD details with the * driver and the driver stores the same to use in decryption of association * request and in encryption of association response. The below parameters * should be given to the driver in %NL80211_CMD_SET_FILS_AAD. * %NL80211_ATTR_MAC - STA MAC address, used for storing FILS AAD per STA * %NL80211_ATTR_FILS_KEK - Used for encryption or decryption * %NL80211_ATTR_FILS_NONCES - Used for encryption or decryption * (STA Nonce 16 bytes followed by AP Nonce 16 bytes) * * Once the association is done, the driver cleans the FILS AAD data. */ /** * DOC: Multi-Link Operation * * In Multi-Link Operation, a connection between to MLDs utilizes multiple * links. To use this in nl80211, various commands and responses now need * to or will include the new %NL80211_ATTR_MLO_LINKS attribute. * Additionally, various commands that need to operate on a specific link * now need to be given the %NL80211_ATTR_MLO_LINK_ID attribute, e.g. to * use %NL80211_CMD_START_AP or similar functions. */ /** * enum nl80211_commands - supported nl80211 commands * * @NL80211_CMD_UNSPEC: unspecified command to catch errors * * @NL80211_CMD_GET_WIPHY: request information about a wiphy or dump request * to get a list of all present wiphys. * @NL80211_CMD_SET_WIPHY: set wiphy parameters, needs %NL80211_ATTR_WIPHY or * %NL80211_ATTR_IFINDEX; can be used to set %NL80211_ATTR_WIPHY_NAME, * %NL80211_ATTR_WIPHY_TXQ_PARAMS, %NL80211_ATTR_WIPHY_FREQ, * %NL80211_ATTR_WIPHY_FREQ_OFFSET (and the attributes determining the * channel width; this is used for setting monitor mode channel), * %NL80211_ATTR_WIPHY_RETRY_SHORT, %NL80211_ATTR_WIPHY_RETRY_LONG, * %NL80211_ATTR_WIPHY_FRAG_THRESHOLD, and/or * %NL80211_ATTR_WIPHY_RTS_THRESHOLD. However, for setting the channel, * see %NL80211_CMD_SET_CHANNEL instead, the support here is for backward * compatibility only. * @NL80211_CMD_NEW_WIPHY: Newly created wiphy, response to get request * or rename notification. Has attributes %NL80211_ATTR_WIPHY and * %NL80211_ATTR_WIPHY_NAME. * @NL80211_CMD_DEL_WIPHY: Wiphy deleted. Has attributes * %NL80211_ATTR_WIPHY and %NL80211_ATTR_WIPHY_NAME. * * @NL80211_CMD_GET_INTERFACE: Request an interface's configuration; * either a dump request for all interfaces or a specific get with a * single %NL80211_ATTR_IFINDEX is supported. * @NL80211_CMD_SET_INTERFACE: Set type of a virtual interface, requires * %NL80211_ATTR_IFINDEX and %NL80211_ATTR_IFTYPE. * @NL80211_CMD_NEW_INTERFACE: Newly created virtual interface or response * to %NL80211_CMD_GET_INTERFACE. Has %NL80211_ATTR_IFINDEX, * %NL80211_ATTR_WIPHY and %NL80211_ATTR_IFTYPE attributes. Can also * be sent from userspace to request creation of a new virtual interface, * then requires attributes %NL80211_ATTR_WIPHY, %NL80211_ATTR_IFTYPE and * %NL80211_ATTR_IFNAME. * @NL80211_CMD_DEL_INTERFACE: Virtual interface was deleted, has attributes * %NL80211_ATTR_IFINDEX and %NL80211_ATTR_WIPHY. Can also be sent from * userspace to request deletion of a virtual interface, then requires * attribute %NL80211_ATTR_IFINDEX. If multiple BSSID advertisements are * enabled using %NL80211_ATTR_MBSSID_CONFIG, %NL80211_ATTR_MBSSID_ELEMS, * and if this command is used for the transmitting interface, then all * the non-transmitting interfaces are deleted as well. * * @NL80211_CMD_GET_KEY: Get sequence counter information for a key specified * by %NL80211_ATTR_KEY_IDX and/or %NL80211_ATTR_MAC. %NL80211_ATTR_MAC * represents peer's MLD address for MLO pairwise key. For MLO group key, * the link is identified by %NL80211_ATTR_MLO_LINK_ID. * @NL80211_CMD_SET_KEY: Set key attributes %NL80211_ATTR_KEY_DEFAULT, * %NL80211_ATTR_KEY_DEFAULT_MGMT, or %NL80211_ATTR_KEY_THRESHOLD. * For MLO connection, the link to set default key is identified by * %NL80211_ATTR_MLO_LINK_ID. * @NL80211_CMD_NEW_KEY: add a key with given %NL80211_ATTR_KEY_DATA, * %NL80211_ATTR_KEY_IDX, %NL80211_ATTR_MAC, %NL80211_ATTR_KEY_CIPHER, * and %NL80211_ATTR_KEY_SEQ attributes. %NL80211_ATTR_MAC represents * peer's MLD address for MLO pairwise key. The link to add MLO * group key is identified by %NL80211_ATTR_MLO_LINK_ID. * @NL80211_CMD_DEL_KEY: delete a key identified by %NL80211_ATTR_KEY_IDX * or %NL80211_ATTR_MAC. %NL80211_ATTR_MAC represents peer's MLD address * for MLO pairwise key. The link to delete group key is identified by * %NL80211_ATTR_MLO_LINK_ID. * * @NL80211_CMD_GET_BEACON: (not used) * @NL80211_CMD_SET_BEACON: change the beacon on an access point interface * using the %NL80211_ATTR_BEACON_HEAD and %NL80211_ATTR_BEACON_TAIL * attributes. For drivers that generate the beacon and probe responses * internally, the following attributes must be provided: %NL80211_ATTR_IE, * %NL80211_ATTR_IE_PROBE_RESP and %NL80211_ATTR_IE_ASSOC_RESP. * @NL80211_CMD_START_AP: Start AP operation on an AP interface, parameters * are like for %NL80211_CMD_SET_BEACON, and additionally parameters that * do not change are used, these include %NL80211_ATTR_BEACON_INTERVAL, * %NL80211_ATTR_DTIM_PERIOD, %NL80211_ATTR_SSID, * %NL80211_ATTR_HIDDEN_SSID, %NL80211_ATTR_CIPHERS_PAIRWISE, * %NL80211_ATTR_CIPHER_GROUP, %NL80211_ATTR_WPA_VERSIONS, * %NL80211_ATTR_AKM_SUITES, %NL80211_ATTR_PRIVACY, * %NL80211_ATTR_AUTH_TYPE, %NL80211_ATTR_INACTIVITY_TIMEOUT, * %NL80211_ATTR_ACL_POLICY and %NL80211_ATTR_MAC_ADDRS. * The channel to use can be set on the interface or be given using the * %NL80211_ATTR_WIPHY_FREQ and %NL80211_ATTR_WIPHY_FREQ_OFFSET, and the * attributes determining channel width. * @NL80211_CMD_NEW_BEACON: old alias for %NL80211_CMD_START_AP * @NL80211_CMD_STOP_AP: Stop AP operation on the given interface * @NL80211_CMD_DEL_BEACON: old alias for %NL80211_CMD_STOP_AP * * @NL80211_CMD_GET_STATION: Get station attributes for station identified by * %NL80211_ATTR_MAC on the interface identified by %NL80211_ATTR_IFINDEX. * @NL80211_CMD_SET_STATION: Set station attributes for station identified by * %NL80211_ATTR_MAC on the interface identified by %NL80211_ATTR_IFINDEX. * @NL80211_CMD_NEW_STATION: Add a station with given attributes to the * interface identified by %NL80211_ATTR_IFINDEX. * @NL80211_CMD_DEL_STATION: Remove a station identified by %NL80211_ATTR_MAC * or, if no MAC address given, all stations, on the interface identified * by %NL80211_ATTR_IFINDEX. For MLD station, MLD address is used in * %NL80211_ATTR_MAC. %NL80211_ATTR_MGMT_SUBTYPE and * %NL80211_ATTR_REASON_CODE can optionally be used to specify which type * of disconnection indication should be sent to the station * (Deauthentication or Disassociation frame and reason code for that * frame). * * @NL80211_CMD_GET_MPATH: Get mesh path attributes for mesh path to * destination %NL80211_ATTR_MAC on the interface identified by * %NL80211_ATTR_IFINDEX. * @NL80211_CMD_SET_MPATH: Set mesh path attributes for mesh path to * destination %NL80211_ATTR_MAC on the interface identified by * %NL80211_ATTR_IFINDEX. * @NL80211_CMD_NEW_MPATH: Create a new mesh path for the destination given by * %NL80211_ATTR_MAC via %NL80211_ATTR_MPATH_NEXT_HOP. * @NL80211_CMD_DEL_MPATH: Delete a mesh path to the destination given by * %NL80211_ATTR_MAC. * @NL80211_CMD_NEW_PATH: Add a mesh path with given attributes to the * interface identified by %NL80211_ATTR_IFINDEX. * @NL80211_CMD_DEL_PATH: Remove a mesh path identified by %NL80211_ATTR_MAC * or, if no MAC address given, all mesh paths, on the interface identified * by %NL80211_ATTR_IFINDEX. * @NL80211_CMD_SET_BSS: Set BSS attributes for BSS identified by * %NL80211_ATTR_IFINDEX. * * @NL80211_CMD_GET_REG: ask the wireless core to send us its currently set * regulatory domain. If %NL80211_ATTR_WIPHY is specified and the device * has a private regulatory domain, it will be returned. Otherwise, the * global regdomain will be returned. * A device will have a private regulatory domain if it uses the * regulatory_hint() API. Even when a private regdomain is used the channel * information will still be mended according to further hints from * the regulatory core to help with compliance. A dump version of this API * is now available which will returns the global regdomain as well as * all private regdomains of present wiphys (for those that have it). * If a wiphy is self-managed (%NL80211_ATTR_WIPHY_SELF_MANAGED_REG), then * its private regdomain is the only valid one for it. The regulatory * core is not used to help with compliance in this case. * @NL80211_CMD_SET_REG: Set current regulatory domain. CRDA sends this command * after being queried by the kernel. CRDA replies by sending a regulatory * domain structure which consists of %NL80211_ATTR_REG_ALPHA set to our * current alpha2 if it found a match. It also provides * NL80211_ATTR_REG_RULE_FLAGS, and a set of regulatory rules. Each * regulatory rule is a nested set of attributes given by * %NL80211_ATTR_REG_RULE_FREQ_[START|END] and * %NL80211_ATTR_FREQ_RANGE_MAX_BW with an attached power rule given by * %NL80211_ATTR_REG_RULE_POWER_MAX_ANT_GAIN and * %NL80211_ATTR_REG_RULE_POWER_MAX_EIRP. * @NL80211_CMD_REQ_SET_REG: ask the wireless core to set the regulatory domain * to the specified ISO/IEC 3166-1 alpha2 country code. The core will * store this as a valid request and then query userspace for it. * * @NL80211_CMD_GET_MESH_CONFIG: Get mesh networking properties for the * interface identified by %NL80211_ATTR_IFINDEX * * @NL80211_CMD_SET_MESH_CONFIG: Set mesh networking properties for the * interface identified by %NL80211_ATTR_IFINDEX * * @NL80211_CMD_SET_MGMT_EXTRA_IE: Set extra IEs for management frames. The * interface is identified with %NL80211_ATTR_IFINDEX and the management * frame subtype with %NL80211_ATTR_MGMT_SUBTYPE. The extra IE data to be * added to the end of the specified management frame is specified with * %NL80211_ATTR_IE. If the command succeeds, the requested data will be * added to all specified management frames generated by * kernel/firmware/driver. * Note: This command has been removed and it is only reserved at this * point to avoid re-using existing command number. The functionality this * command was planned for has been provided with cleaner design with the * option to specify additional IEs in NL80211_CMD_TRIGGER_SCAN, * NL80211_CMD_AUTHENTICATE, NL80211_CMD_ASSOCIATE, * NL80211_CMD_DEAUTHENTICATE, and NL80211_CMD_DISASSOCIATE. * * @NL80211_CMD_GET_SCAN: get scan results * @NL80211_CMD_TRIGGER_SCAN: trigger a new scan with the given parameters * %NL80211_ATTR_TX_NO_CCK_RATE is used to decide whether to send the * probe requests at CCK rate or not. %NL80211_ATTR_BSSID can be used to * specify a BSSID to scan for; if not included, the wildcard BSSID will * be used. * @NL80211_CMD_NEW_SCAN_RESULTS: scan notification (as a reply to * NL80211_CMD_GET_SCAN and on the "scan" multicast group) * @NL80211_CMD_SCAN_ABORTED: scan was aborted, for unspecified reasons, * partial scan results may be available * * @NL80211_CMD_START_SCHED_SCAN: start a scheduled scan at certain * intervals and certain number of cycles, as specified by * %NL80211_ATTR_SCHED_SCAN_PLANS. If %NL80211_ATTR_SCHED_SCAN_PLANS is * not specified and only %NL80211_ATTR_SCHED_SCAN_INTERVAL is specified, * scheduled scan will run in an infinite loop with the specified interval. * These attributes are mutually exculsive, * i.e. NL80211_ATTR_SCHED_SCAN_INTERVAL must not be passed if * NL80211_ATTR_SCHED_SCAN_PLANS is defined. * If for some reason scheduled scan is aborted by the driver, all scan * plans are canceled (including scan plans that did not start yet). * Like with normal scans, if SSIDs (%NL80211_ATTR_SCAN_SSIDS) * are passed, they are used in the probe requests. For * broadcast, a broadcast SSID must be passed (ie. an empty * string). If no SSID is passed, no probe requests are sent and * a passive scan is performed. %NL80211_ATTR_SCAN_FREQUENCIES, * if passed, define which channels should be scanned; if not * passed, all channels allowed for the current regulatory domain * are used. Extra IEs can also be passed from the userspace by * using the %NL80211_ATTR_IE attribute. The first cycle of the * scheduled scan can be delayed by %NL80211_ATTR_SCHED_SCAN_DELAY * is supplied. If the device supports multiple concurrent scheduled * scans, it will allow such when the caller provides the flag attribute * %NL80211_ATTR_SCHED_SCAN_MULTI to indicate user-space support for it. * @NL80211_CMD_STOP_SCHED_SCAN: stop a scheduled scan. Returns -ENOENT if * scheduled scan is not running. The caller may assume that as soon * as the call returns, it is safe to start a new scheduled scan again. * @NL80211_CMD_SCHED_SCAN_RESULTS: indicates that there are scheduled scan * results available. * @NL80211_CMD_SCHED_SCAN_STOPPED: indicates that the scheduled scan has * stopped. The driver may issue this event at any time during a * scheduled scan. One reason for stopping the scan is if the hardware * does not support starting an association or a normal scan while running * a scheduled scan. This event is also sent when the * %NL80211_CMD_STOP_SCHED_SCAN command is received or when the interface * is brought down while a scheduled scan was running. * * @NL80211_CMD_GET_SURVEY: get survey resuls, e.g. channel occupation * or noise level * @NL80211_CMD_NEW_SURVEY_RESULTS: survey data notification (as a reply to * NL80211_CMD_GET_SURVEY and on the "scan" multicast group) * * @NL80211_CMD_SET_PMKSA: Add a PMKSA cache entry using %NL80211_ATTR_MAC * (for the BSSID), %NL80211_ATTR_PMKID, and optionally %NL80211_ATTR_PMK * (PMK is used for PTKSA derivation in case of FILS shared key offload) or * using %NL80211_ATTR_SSID, %NL80211_ATTR_FILS_CACHE_ID, * %NL80211_ATTR_PMKID, and %NL80211_ATTR_PMK in case of FILS * authentication where %NL80211_ATTR_FILS_CACHE_ID is the identifier * advertized by a FILS capable AP identifying the scope of PMKSA in an * ESS. * @NL80211_CMD_DEL_PMKSA: Delete a PMKSA cache entry, using %NL80211_ATTR_MAC * (for the BSSID) and %NL80211_ATTR_PMKID or using %NL80211_ATTR_SSID, * %NL80211_ATTR_FILS_CACHE_ID, and %NL80211_ATTR_PMKID in case of FILS * authentication. * @NL80211_CMD_FLUSH_PMKSA: Flush all PMKSA cache entries. * * @NL80211_CMD_REG_CHANGE: indicates to userspace the regulatory domain * has been changed and provides details of the request information * that caused the change such as who initiated the regulatory request * (%NL80211_ATTR_REG_INITIATOR), the wiphy_idx * (%NL80211_ATTR_REG_ALPHA2) on which the request was made from if * the initiator was %NL80211_REGDOM_SET_BY_COUNTRY_IE or * %NL80211_REGDOM_SET_BY_DRIVER, the type of regulatory domain * set (%NL80211_ATTR_REG_TYPE), if the type of regulatory domain is * %NL80211_REG_TYPE_COUNTRY the alpha2 to which we have moved on * to (%NL80211_ATTR_REG_ALPHA2). * @NL80211_CMD_REG_BEACON_HINT: indicates to userspace that an AP beacon * has been found while world roaming thus enabling active scan or * any mode of operation that initiates TX (beacons) on a channel * where we would not have been able to do either before. As an example * if you are world roaming (regulatory domain set to world or if your * driver is using a custom world roaming regulatory domain) and while * doing a passive scan on the 5 GHz band you find an AP there (if not * on a DFS channel) you will now be able to actively scan for that AP * or use AP mode on your card on that same channel. Note that this will * never be used for channels 1-11 on the 2 GHz band as they are always * enabled world wide. This beacon hint is only sent if your device had * either disabled active scanning or beaconing on a channel. We send to * userspace the wiphy on which we removed a restriction from * (%NL80211_ATTR_WIPHY) and the channel on which this occurred * before (%NL80211_ATTR_FREQ_BEFORE) and after (%NL80211_ATTR_FREQ_AFTER) * the beacon hint was processed. * * @NL80211_CMD_AUTHENTICATE: authentication request and notification. * This command is used both as a command (request to authenticate) and * as an event on the "mlme" multicast group indicating completion of the * authentication process. * When used as a command, %NL80211_ATTR_IFINDEX is used to identify the * interface. %NL80211_ATTR_MAC is used to specify PeerSTAAddress (and * BSSID in case of station mode). %NL80211_ATTR_SSID is used to specify * the SSID (mainly for association, but is included in authentication * request, too, to help BSS selection. %NL80211_ATTR_WIPHY_FREQ + * %NL80211_ATTR_WIPHY_FREQ_OFFSET is used to specify the frequence of the * channel in MHz. %NL80211_ATTR_AUTH_TYPE is used to specify the * authentication type. %NL80211_ATTR_IE is used to define IEs * (VendorSpecificInfo, but also including RSN IE and FT IEs) to be added * to the frame. * When used as an event, this reports reception of an Authentication * frame in station and IBSS modes when the local MLME processed the * frame, i.e., it was for the local STA and was received in correct * state. This is similar to MLME-AUTHENTICATE.confirm primitive in the * MLME SAP interface (kernel providing MLME, userspace SME). The * included %NL80211_ATTR_FRAME attribute contains the management frame * (including both the header and frame body, but not FCS). This event is * also used to indicate if the authentication attempt timed out. In that * case the %NL80211_ATTR_FRAME attribute is replaced with a * %NL80211_ATTR_TIMED_OUT flag (and %NL80211_ATTR_MAC to indicate which * pending authentication timed out). * @NL80211_CMD_ASSOCIATE: association request and notification; like * NL80211_CMD_AUTHENTICATE but for Association and Reassociation * (similar to MLME-ASSOCIATE.request, MLME-REASSOCIATE.request, * MLME-ASSOCIATE.confirm or MLME-REASSOCIATE.confirm primitives). The * %NL80211_ATTR_PREV_BSSID attribute is used to specify whether the * request is for the initial association to an ESS (that attribute not * included) or for reassociation within the ESS (that attribute is * included). * @NL80211_CMD_DEAUTHENTICATE: deauthentication request and notification; like * NL80211_CMD_AUTHENTICATE but for Deauthentication frames (similar to * MLME-DEAUTHENTICATION.request and MLME-DEAUTHENTICATE.indication * primitives). * @NL80211_CMD_DISASSOCIATE: disassociation request and notification; like * NL80211_CMD_AUTHENTICATE but for Disassociation frames (similar to * MLME-DISASSOCIATE.request and MLME-DISASSOCIATE.indication primitives). * * @NL80211_CMD_MICHAEL_MIC_FAILURE: notification of a locally detected Michael * MIC (part of TKIP) failure; sent on the "mlme" multicast group; the * event includes %NL80211_ATTR_MAC to describe the source MAC address of * the frame with invalid MIC, %NL80211_ATTR_KEY_TYPE to show the key * type, %NL80211_ATTR_KEY_IDX to indicate the key identifier, and * %NL80211_ATTR_KEY_SEQ to indicate the TSC value of the frame; this * event matches with MLME-MICHAELMICFAILURE.indication() primitive * * @NL80211_CMD_JOIN_IBSS: Join a new IBSS -- given at least an SSID and a * FREQ attribute (for the initial frequency if no peer can be found) * and optionally a MAC (as BSSID) and FREQ_FIXED attribute if those * should be fixed rather than automatically determined. Can only be * executed on a network interface that is UP, and fixed BSSID/FREQ * may be rejected. Another optional parameter is the beacon interval, * given in the %NL80211_ATTR_BEACON_INTERVAL attribute, which if not * given defaults to 100 TU (102.4ms). * @NL80211_CMD_LEAVE_IBSS: Leave the IBSS -- no special arguments, the IBSS is * determined by the network interface. * * @NL80211_CMD_TESTMODE: testmode command, takes a wiphy (or ifindex) attribute * to identify the device, and the TESTDATA blob attribute to pass through * to the driver. * * @NL80211_CMD_CONNECT: connection request and notification; this command * requests to connect to a specified network but without separating * auth and assoc steps. For this, you need to specify the SSID in a * %NL80211_ATTR_SSID attribute, and can optionally specify the association * IEs in %NL80211_ATTR_IE, %NL80211_ATTR_AUTH_TYPE, * %NL80211_ATTR_USE_MFP, %NL80211_ATTR_MAC, %NL80211_ATTR_WIPHY_FREQ, * %NL80211_ATTR_WIPHY_FREQ_OFFSET, %NL80211_ATTR_CONTROL_PORT, * %NL80211_ATTR_CONTROL_PORT_ETHERTYPE, * %NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT, * %NL80211_ATTR_CONTROL_PORT_OVER_NL80211, %NL80211_ATTR_MAC_HINT, and * %NL80211_ATTR_WIPHY_FREQ_HINT. * If included, %NL80211_ATTR_MAC and %NL80211_ATTR_WIPHY_FREQ are * restrictions on BSS selection, i.e., they effectively prevent roaming * within the ESS. %NL80211_ATTR_MAC_HINT and %NL80211_ATTR_WIPHY_FREQ_HINT * can be included to provide a recommendation of the initial BSS while * allowing the driver to roam to other BSSes within the ESS and also to * ignore this recommendation if the indicated BSS is not ideal. Only one * set of BSSID,frequency parameters is used (i.e., either the enforcing * %NL80211_ATTR_MAC,%NL80211_ATTR_WIPHY_FREQ or the less strict * %NL80211_ATTR_MAC_HINT and %NL80211_ATTR_WIPHY_FREQ_HINT). * %NL80211_ATTR_PREV_BSSID can be used to request a reassociation within * the ESS in case the device is already associated and an association with * a different BSS is desired. * Background scan period can optionally be * specified in %NL80211_ATTR_BG_SCAN_PERIOD, * if not specified default background scan configuration * in driver is used and if period value is 0, bg scan will be disabled. * This attribute is ignored if driver does not support roam scan. * It is also sent as an event, with the BSSID and response IEs when the * connection is established or failed to be established. This can be * determined by the %NL80211_ATTR_STATUS_CODE attribute (0 = success, * non-zero = failure). If %NL80211_ATTR_TIMED_OUT is included in the * event, the connection attempt failed due to not being able to initiate * authentication/association or not receiving a response from the AP. * Non-zero %NL80211_ATTR_STATUS_CODE value is indicated in that case as * well to remain backwards compatible. * @NL80211_CMD_ROAM: Notification indicating the card/driver roamed by itself. * When a security association was established on an 802.1X network using * fast transition, this event should be followed by an * %NL80211_CMD_PORT_AUTHORIZED event. * Following a %NL80211_CMD_ROAM event userspace can issue * %NL80211_CMD_GET_SCAN in order to obtain the scan information for the * new BSS the card/driver roamed to. * @NL80211_CMD_DISCONNECT: drop a given connection; also used to notify * userspace that a connection was dropped by the AP or due to other * reasons, for this the %NL80211_ATTR_DISCONNECTED_BY_AP and * %NL80211_ATTR_REASON_CODE attributes are used. * * @NL80211_CMD_SET_WIPHY_NETNS: Set a wiphy's netns. Note that all devices * associated with this wiphy must be down and will follow. * * @NL80211_CMD_REMAIN_ON_CHANNEL: Request to remain awake on the specified * channel for the specified amount of time. This can be used to do * off-channel operations like transmit a Public Action frame and wait for * a response while being associated to an AP on another channel. * %NL80211_ATTR_IFINDEX is used to specify which interface (and thus * radio) is used. %NL80211_ATTR_WIPHY_FREQ is used to specify the * frequency for the operation. * %NL80211_ATTR_DURATION is used to specify the duration in milliseconds * to remain on the channel. This command is also used as an event to * notify when the requested duration starts (it may take a while for the * driver to schedule this time due to other concurrent needs for the * radio). * When called, this operation returns a cookie (%NL80211_ATTR_COOKIE) * that will be included with any events pertaining to this request; * the cookie is also used to cancel the request. * @NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL: This command can be used to cancel a * pending remain-on-channel duration if the desired operation has been * completed prior to expiration of the originally requested duration. * %NL80211_ATTR_WIPHY or %NL80211_ATTR_IFINDEX is used to specify the * radio. The %NL80211_ATTR_COOKIE attribute must be given as well to * uniquely identify the request. * This command is also used as an event to notify when a requested * remain-on-channel duration has expired. * * @NL80211_CMD_SET_TX_BITRATE_MASK: Set the mask of rates to be used in TX * rate selection. %NL80211_ATTR_IFINDEX is used to specify the interface * and @NL80211_ATTR_TX_RATES the set of allowed rates. * * @NL80211_CMD_REGISTER_FRAME: Register for receiving certain mgmt frames * (via @NL80211_CMD_FRAME) for processing in userspace. This command * requires an interface index, a frame type attribute (optional for * backward compatibility reasons, if not given assumes action frames) * and a match attribute containing the first few bytes of the frame * that should match, e.g. a single byte for only a category match or * four bytes for vendor frames including the OUI. The registration * cannot be dropped, but is removed automatically when the netlink * socket is closed. Multiple registrations can be made. * The %NL80211_ATTR_RECEIVE_MULTICAST flag attribute can be given if * %NL80211_EXT_FEATURE_MULTICAST_REGISTRATIONS is available, in which * case the registration can also be modified to include/exclude the * flag, rather than requiring unregistration to change it. * @NL80211_CMD_REGISTER_ACTION: Alias for @NL80211_CMD_REGISTER_FRAME for * backward compatibility * @NL80211_CMD_FRAME: Management frame TX request and RX notification. This * command is used both as a request to transmit a management frame and * as an event indicating reception of a frame that was not processed in * kernel code, but is for us (i.e., which may need to be processed in a * user space application). %NL80211_ATTR_FRAME is used to specify the * frame contents (including header). %NL80211_ATTR_WIPHY_FREQ is used * to indicate on which channel the frame is to be transmitted or was * received. If this channel is not the current channel (remain-on-channel * or the operational channel) the device will switch to the given channel * and transmit the frame, optionally waiting for a response for the time * specified using %NL80211_ATTR_DURATION. When called, this operation * returns a cookie (%NL80211_ATTR_COOKIE) that will be included with the * TX status event pertaining to the TX request. * %NL80211_ATTR_TX_NO_CCK_RATE is used to decide whether to send the * management frames at CCK rate or not in 2GHz band. * %NL80211_ATTR_CSA_C_OFFSETS_TX is an array of offsets to CSA * counters which will be updated to the current value. This attribute * is used during CSA period. * For TX on an MLD, the frequency can be omitted and the link ID be * specified, or if transmitting to a known peer MLD (with MLD addresses * in the frame) both can be omitted and the link will be selected by * lower layers. * For RX notification, %NL80211_ATTR_RX_HW_TIMESTAMP may be included to * indicate the frame RX timestamp and %NL80211_ATTR_TX_HW_TIMESTAMP may * be included to indicate the ack TX timestamp. * @NL80211_CMD_FRAME_WAIT_CANCEL: When an off-channel TX was requested, this * command may be used with the corresponding cookie to cancel the wait * time if it is known that it is no longer necessary. This command is * also sent as an event whenever the driver has completed the off-channel * wait time. * @NL80211_CMD_ACTION: Alias for @NL80211_CMD_FRAME for backward compatibility. * @NL80211_CMD_FRAME_TX_STATUS: Report TX status of a management frame * transmitted with %NL80211_CMD_FRAME. %NL80211_ATTR_COOKIE identifies * the TX command and %NL80211_ATTR_FRAME includes the contents of the * frame. %NL80211_ATTR_ACK flag is included if the recipient acknowledged * the frame. %NL80211_ATTR_TX_HW_TIMESTAMP may be included to indicate the * tx timestamp and %NL80211_ATTR_RX_HW_TIMESTAMP may be included to * indicate the ack RX timestamp. * @NL80211_CMD_ACTION_TX_STATUS: Alias for @NL80211_CMD_FRAME_TX_STATUS for * backward compatibility. * * @NL80211_CMD_SET_POWER_SAVE: Set powersave, using %NL80211_ATTR_PS_STATE * @NL80211_CMD_GET_POWER_SAVE: Get powersave status in %NL80211_ATTR_PS_STATE * * @NL80211_CMD_SET_CQM: Connection quality monitor configuration. This command * is used to configure connection quality monitoring notification trigger * levels. * @NL80211_CMD_NOTIFY_CQM: Connection quality monitor notification. This * command is used as an event to indicate the that a trigger level was * reached. * @NL80211_CMD_SET_CHANNEL: Set the channel (using %NL80211_ATTR_WIPHY_FREQ * and the attributes determining channel width) the given interface * (identifed by %NL80211_ATTR_IFINDEX) shall operate on. * In case multiple channels are supported by the device, the mechanism * with which it switches channels is implementation-defined. * When a monitor interface is given, it can only switch channel while * no other interfaces are operating to avoid disturbing the operation * of any other interfaces, and other interfaces will again take * precedence when they are used. * * @NL80211_CMD_SET_WDS_PEER: Set the MAC address of the peer on a WDS interface * (no longer supported). * * @NL80211_CMD_SET_MULTICAST_TO_UNICAST: Configure if this AP should perform * multicast to unicast conversion. When enabled, all multicast packets * with ethertype ARP, IPv4 or IPv6 (possibly within an 802.1Q header) * will be sent out to each station once with the destination (multicast) * MAC address replaced by the station's MAC address. Note that this may * break certain expectations of the receiver, e.g. the ability to drop * unicast IP packets encapsulated in multicast L2 frames, or the ability * to not send destination unreachable messages in such cases. * This can only be toggled per BSS. Configure this on an interface of * type %NL80211_IFTYPE_AP. It applies to all its VLAN interfaces * (%NL80211_IFTYPE_AP_VLAN), except for those in 4addr (WDS) mode. * If %NL80211_ATTR_MULTICAST_TO_UNICAST_ENABLED is not present with this * command, the feature is disabled. * * @NL80211_CMD_JOIN_MESH: Join a mesh. The mesh ID must be given, and initial * mesh config parameters may be given. * @NL80211_CMD_LEAVE_MESH: Leave the mesh network -- no special arguments, the * network is determined by the network interface. * * @NL80211_CMD_UNPROT_DEAUTHENTICATE: Unprotected deauthentication frame * notification. This event is used to indicate that an unprotected * deauthentication frame was dropped when MFP is in use. * @NL80211_CMD_UNPROT_DISASSOCIATE: Unprotected disassociation frame * notification. This event is used to indicate that an unprotected * disassociation frame was dropped when MFP is in use. * * @NL80211_CMD_NEW_PEER_CANDIDATE: Notification on the reception of a * beacon or probe response from a compatible mesh peer. This is only * sent while no station information (sta_info) exists for the new peer * candidate and when @NL80211_MESH_SETUP_USERSPACE_AUTH, * @NL80211_MESH_SETUP_USERSPACE_AMPE, or * @NL80211_MESH_SETUP_USERSPACE_MPM is set. On reception of this * notification, userspace may decide to create a new station * (@NL80211_CMD_NEW_STATION). To stop this notification from * reoccurring, the userspace authentication daemon may want to create the * new station with the AUTHENTICATED flag unset and maybe change it later * depending on the authentication result. * * @NL80211_CMD_GET_WOWLAN: get Wake-on-Wireless-LAN (WoWLAN) settings. * @NL80211_CMD_SET_WOWLAN: set Wake-on-Wireless-LAN (WoWLAN) settings. * Since wireless is more complex than wired ethernet, it supports * various triggers. These triggers can be configured through this * command with the %NL80211_ATTR_WOWLAN_TRIGGERS attribute. For * more background information, see * https://wireless.wiki.kernel.org/en/users/Documentation/WoWLAN. * The @NL80211_CMD_SET_WOWLAN command can also be used as a notification * from the driver reporting the wakeup reason. In this case, the * @NL80211_ATTR_WOWLAN_TRIGGERS attribute will contain the reason * for the wakeup, if it was caused by wireless. If it is not present * in the wakeup notification, the wireless device didn't cause the * wakeup but reports that it was woken up. * * @NL80211_CMD_SET_REKEY_OFFLOAD: This command is used give the driver * the necessary information for supporting GTK rekey offload. This * feature is typically used during WoWLAN. The configuration data * is contained in %NL80211_ATTR_REKEY_DATA (which is nested and * contains the data in sub-attributes). After rekeying happened, * this command may also be sent by the driver as an MLME event to * inform userspace of the new replay counter. * * @NL80211_CMD_PMKSA_CANDIDATE: This is used as an event to inform userspace * of PMKSA caching dandidates. * * @NL80211_CMD_TDLS_OPER: Perform a high-level TDLS command (e.g. link setup). * In addition, this can be used as an event to request userspace to take * actions on TDLS links (set up a new link or tear down an existing one). * In such events, %NL80211_ATTR_TDLS_OPERATION indicates the requested * operation, %NL80211_ATTR_MAC contains the peer MAC address, and * %NL80211_ATTR_REASON_CODE the reason code to be used (only with * %NL80211_TDLS_TEARDOWN). * @NL80211_CMD_TDLS_MGMT: Send a TDLS management frame. The * %NL80211_ATTR_TDLS_ACTION attribute determines the type of frame to be * sent. Public Action codes (802.11-2012 8.1.5.1) will be sent as * 802.11 management frames, while TDLS action codes (802.11-2012 * 8.5.13.1) will be encapsulated and sent as data frames. The currently * supported Public Action code is %WLAN_PUB_ACTION_TDLS_DISCOVER_RES * and the currently supported TDLS actions codes are given in * &enum ieee80211_tdls_actioncode. * * @NL80211_CMD_UNEXPECTED_FRAME: Used by an application controlling an AP * (or GO) interface (i.e. hostapd) to ask for unexpected frames to * implement sending deauth to stations that send unexpected class 3 * frames. Also used as the event sent by the kernel when such a frame * is received. * For the event, the %NL80211_ATTR_MAC attribute carries the TA and * other attributes like the interface index are present. * If used as the command it must have an interface index and you can * only unsubscribe from the event by closing the socket. Subscription * is also for %NL80211_CMD_UNEXPECTED_4ADDR_FRAME events. * * @NL80211_CMD_UNEXPECTED_4ADDR_FRAME: Sent as an event indicating that the * associated station identified by %NL80211_ATTR_MAC sent a 4addr frame * and wasn't already in a 4-addr VLAN. The event will be sent similarly * to the %NL80211_CMD_UNEXPECTED_FRAME event, to the same listener. * * @NL80211_CMD_PROBE_CLIENT: Probe an associated station on an AP interface * by sending a null data frame to it and reporting when the frame is * acknowleged. This is used to allow timing out inactive clients. Uses * %NL80211_ATTR_IFINDEX and %NL80211_ATTR_MAC. The command returns a * direct reply with an %NL80211_ATTR_COOKIE that is later used to match * up the event with the request. The event includes the same data and * has %NL80211_ATTR_ACK set if the frame was ACKed. * * @NL80211_CMD_REGISTER_BEACONS: Register this socket to receive beacons from * other BSSes when any interfaces are in AP mode. This helps implement * OLBC handling in hostapd. Beacons are reported in %NL80211_CMD_FRAME * messages. Note that per PHY only one application may register. * * @NL80211_CMD_SET_NOACK_MAP: sets a bitmap for the individual TIDs whether * No Acknowledgement Policy should be applied. * * @NL80211_CMD_CH_SWITCH_NOTIFY: An AP or GO may decide to switch channels * independently of the userspace SME, send this event indicating * %NL80211_ATTR_IFINDEX is now on %NL80211_ATTR_WIPHY_FREQ and the * attributes determining channel width. This indication may also be * sent when a remotely-initiated switch (e.g., when a STA receives a CSA * from the remote AP) is completed; * * @NL80211_CMD_CH_SWITCH_STARTED_NOTIFY: Notify that a channel switch * has been started on an interface, regardless of the initiator * (ie. whether it was requested from a remote device or * initiated on our own). It indicates that * %NL80211_ATTR_IFINDEX will be on %NL80211_ATTR_WIPHY_FREQ * after %NL80211_ATTR_CH_SWITCH_COUNT TBTT's. The userspace may * decide to react to this indication by requesting other * interfaces to change channel as well. * * @NL80211_CMD_START_P2P_DEVICE: Start the given P2P Device, identified by * its %NL80211_ATTR_WDEV identifier. It must have been created with * %NL80211_CMD_NEW_INTERFACE previously. After it has been started, the * P2P Device can be used for P2P operations, e.g. remain-on-channel and * public action frame TX. * @NL80211_CMD_STOP_P2P_DEVICE: Stop the given P2P Device, identified by * its %NL80211_ATTR_WDEV identifier. * * @NL80211_CMD_CONN_FAILED: connection request to an AP failed; used to * notify userspace that AP has rejected the connection request from a * station, due to particular reason. %NL80211_ATTR_CONN_FAILED_REASON * is used for this. * * @NL80211_CMD_SET_MCAST_RATE: Change the rate used to send multicast frames * for IBSS or MESH vif. * * @NL80211_CMD_SET_MAC_ACL: sets ACL for MAC address based access control. * This is to be used with the drivers advertising the support of MAC * address based access control. List of MAC addresses is passed in * %NL80211_ATTR_MAC_ADDRS and ACL policy is passed in * %NL80211_ATTR_ACL_POLICY. Driver will enable ACL with this list, if it * is not already done. The new list will replace any existing list. Driver * will clear its ACL when the list of MAC addresses passed is empty. This * command is used in AP/P2P GO mode. Driver has to make sure to clear its * ACL list during %NL80211_CMD_STOP_AP. * * @NL80211_CMD_RADAR_DETECT: Start a Channel availability check (CAC). Once * a radar is detected or the channel availability scan (CAC) has finished * or was aborted, or a radar was detected, usermode will be notified with * this event. This command is also used to notify userspace about radars * while operating on this channel. * %NL80211_ATTR_RADAR_EVENT is used to inform about the type of the * event. * * @NL80211_CMD_GET_PROTOCOL_FEATURES: Get global nl80211 protocol features, * i.e. features for the nl80211 protocol rather than device features. * Returns the features in the %NL80211_ATTR_PROTOCOL_FEATURES bitmap. * * @NL80211_CMD_UPDATE_FT_IES: Pass down the most up-to-date Fast Transition * Information Element to the WLAN driver * * @NL80211_CMD_FT_EVENT: Send a Fast transition event from the WLAN driver * to the supplicant. This will carry the target AP's MAC address along * with the relevant Information Elements. This event is used to report * received FT IEs (MDIE, FTIE, RSN IE, TIE, RICIE). * * @NL80211_CMD_CRIT_PROTOCOL_START: Indicates user-space will start running * a critical protocol that needs more reliability in the connection to * complete. * * @NL80211_CMD_CRIT_PROTOCOL_STOP: Indicates the connection reliability can * return back to normal. * * @NL80211_CMD_GET_COALESCE: Get currently supported coalesce rules. * @NL80211_CMD_SET_COALESCE: Configure coalesce rules or clear existing rules. * * @NL80211_CMD_CHANNEL_SWITCH: Perform a channel switch by announcing the * new channel information (Channel Switch Announcement - CSA) * in the beacon for some time (as defined in the * %NL80211_ATTR_CH_SWITCH_COUNT parameter) and then change to the * new channel. Userspace provides the new channel information (using * %NL80211_ATTR_WIPHY_FREQ and the attributes determining channel * width). %NL80211_ATTR_CH_SWITCH_BLOCK_TX may be supplied to inform * other station that transmission must be blocked until the channel * switch is complete. * * @NL80211_CMD_VENDOR: Vendor-specified command/event. The command is specified * by the %NL80211_ATTR_VENDOR_ID attribute and a sub-command in * %NL80211_ATTR_VENDOR_SUBCMD. Parameter(s) can be transported in * %NL80211_ATTR_VENDOR_DATA. * For feature advertisement, the %NL80211_ATTR_VENDOR_DATA attribute is * used in the wiphy data as a nested attribute containing descriptions * (&struct nl80211_vendor_cmd_info) of the supported vendor commands. * This may also be sent as an event with the same attributes. * * @NL80211_CMD_SET_QOS_MAP: Set Interworking QoS mapping for IP DSCP values. * The QoS mapping information is included in %NL80211_ATTR_QOS_MAP. If * that attribute is not included, QoS mapping is disabled. Since this * QoS mapping is relevant for IP packets, it is only valid during an * association. This is cleared on disassociation and AP restart. * * @NL80211_CMD_ADD_TX_TS: Ask the kernel to add a traffic stream for the given * %NL80211_ATTR_TSID and %NL80211_ATTR_MAC with %NL80211_ATTR_USER_PRIO * and %NL80211_ATTR_ADMITTED_TIME parameters. * Note that the action frame handshake with the AP shall be handled by * userspace via the normal management RX/TX framework, this only sets * up the TX TS in the driver/device. * If the admitted time attribute is not added then the request just checks * if a subsequent setup could be successful, the intent is to use this to * avoid setting up a session with the AP when local restrictions would * make that impossible. However, the subsequent "real" setup may still * fail even if the check was successful. * @NL80211_CMD_DEL_TX_TS: Remove an existing TS with the %NL80211_ATTR_TSID * and %NL80211_ATTR_MAC parameters. It isn't necessary to call this * before removing a station entry entirely, or before disassociating * or similar, cleanup will happen in the driver/device in this case. * * @NL80211_CMD_GET_MPP: Get mesh path attributes for mesh proxy path to * destination %NL80211_ATTR_MAC on the interface identified by * %NL80211_ATTR_IFINDEX. * * @NL80211_CMD_JOIN_OCB: Join the OCB network. The center frequency and * bandwidth of a channel must be given. * @NL80211_CMD_LEAVE_OCB: Leave the OCB network -- no special arguments, the * network is determined by the network interface. * * @NL80211_CMD_TDLS_CHANNEL_SWITCH: Start channel-switching with a TDLS peer, * identified by the %NL80211_ATTR_MAC parameter. A target channel is * provided via %NL80211_ATTR_WIPHY_FREQ and other attributes determining * channel width/type. The target operating class is given via * %NL80211_ATTR_OPER_CLASS. * The driver is responsible for continually initiating channel-switching * operations and returning to the base channel for communication with the * AP. * @NL80211_CMD_TDLS_CANCEL_CHANNEL_SWITCH: Stop channel-switching with a TDLS * peer given by %NL80211_ATTR_MAC. Both peers must be on the base channel * when this command completes. * * @NL80211_CMD_WIPHY_REG_CHANGE: Similar to %NL80211_CMD_REG_CHANGE, but used * as an event to indicate changes for devices with wiphy-specific regdom * management. * * @NL80211_CMD_ABORT_SCAN: Stop an ongoing scan. Returns -ENOENT if a scan is * not running. The driver indicates the status of the scan through * cfg80211_scan_done(). * * @NL80211_CMD_START_NAN: Start NAN operation, identified by its * %NL80211_ATTR_WDEV interface. This interface must have been * previously created with %NL80211_CMD_NEW_INTERFACE. After it * has been started, the NAN interface will create or join a * cluster. This command must have a valid * %NL80211_ATTR_NAN_MASTER_PREF attribute and optional * %NL80211_ATTR_BANDS attributes. If %NL80211_ATTR_BANDS is * omitted or set to 0, it means don't-care and the device will * decide what to use. After this command NAN functions can be * added. * @NL80211_CMD_STOP_NAN: Stop the NAN operation, identified by * its %NL80211_ATTR_WDEV interface. * @NL80211_CMD_ADD_NAN_FUNCTION: Add a NAN function. The function is defined * with %NL80211_ATTR_NAN_FUNC nested attribute. When called, this * operation returns the strictly positive and unique instance id * (%NL80211_ATTR_NAN_FUNC_INST_ID) and a cookie (%NL80211_ATTR_COOKIE) * of the function upon success. * Since instance ID's can be re-used, this cookie is the right * way to identify the function. This will avoid races when a termination * event is handled by the user space after it has already added a new * function that got the same instance id from the kernel as the one * which just terminated. * This cookie may be used in NAN events even before the command * returns, so userspace shouldn't process NAN events until it processes * the response to this command. * Look at %NL80211_ATTR_SOCKET_OWNER as well. * @NL80211_CMD_DEL_NAN_FUNCTION: Delete a NAN function by cookie. * This command is also used as a notification sent when a NAN function is * terminated. This will contain a %NL80211_ATTR_NAN_FUNC_INST_ID * and %NL80211_ATTR_COOKIE attributes. * @NL80211_CMD_CHANGE_NAN_CONFIG: Change current NAN * configuration. NAN must be operational (%NL80211_CMD_START_NAN * was executed). It must contain at least one of the following * attributes: %NL80211_ATTR_NAN_MASTER_PREF, * %NL80211_ATTR_BANDS. If %NL80211_ATTR_BANDS is omitted, the * current configuration is not changed. If it is present but * set to zero, the configuration is changed to don't-care * (i.e. the device can decide what to do). * @NL80211_CMD_NAN_FUNC_MATCH: Notification sent when a match is reported. * This will contain a %NL80211_ATTR_NAN_MATCH nested attribute and * %NL80211_ATTR_COOKIE. * * @NL80211_CMD_UPDATE_CONNECT_PARAMS: Update one or more connect parameters * for subsequent roaming cases if the driver or firmware uses internal * BSS selection. This command can be issued only while connected and it * does not result in a change for the current association. Currently, * only the %NL80211_ATTR_IE data is used and updated with this command. * * @NL80211_CMD_SET_PMK: For offloaded 4-Way handshake, set the PMK or PMK-R0 * for the given authenticator address (specified with %NL80211_ATTR_MAC). * When %NL80211_ATTR_PMKR0_NAME is set, %NL80211_ATTR_PMK specifies the * PMK-R0, otherwise it specifies the PMK. * @NL80211_CMD_DEL_PMK: For offloaded 4-Way handshake, delete the previously * configured PMK for the authenticator address identified by * %NL80211_ATTR_MAC. * @NL80211_CMD_PORT_AUTHORIZED: An event that indicates an 802.1X FT roam was * completed successfully. Drivers that support 4 way handshake offload * should send this event after indicating 802.1X FT assocation with * %NL80211_CMD_ROAM. If the 4 way handshake failed %NL80211_CMD_DISCONNECT * should be indicated instead. * @NL80211_CMD_CONTROL_PORT_FRAME: Control Port (e.g. PAE) frame TX request * and RX notification. This command is used both as a request to transmit * a control port frame and as a notification that a control port frame * has been received. %NL80211_ATTR_FRAME is used to specify the * frame contents. The frame is the raw EAPoL data, without ethernet or * 802.11 headers. * For an MLD transmitter, the %NL80211_ATTR_MLO_LINK_ID may be given and * its effect will depend on the destination: If the destination is known * to be an MLD, this will be used as a hint to select the link to transmit * the frame on. If the destination is not an MLD, this will select both * the link to transmit on and the source address will be set to the link * address of that link. * When used as an event indication %NL80211_ATTR_CONTROL_PORT_ETHERTYPE, * %NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT and %NL80211_ATTR_MAC are added * indicating the protocol type of the received frame; whether the frame * was received unencrypted and the MAC address of the peer respectively. * * @NL80211_CMD_RELOAD_REGDB: Request that the regdb firmware file is reloaded. * * @NL80211_CMD_EXTERNAL_AUTH: This interface is exclusively defined for host * drivers that do not define separate commands for authentication and * association, but rely on user space for the authentication to happen. * This interface acts both as the event request (driver to user space) * to trigger the authentication and command response (userspace to * driver) to indicate the authentication status. * * User space uses the %NL80211_CMD_CONNECT command to the host driver to * trigger a connection. The host driver selects a BSS and further uses * this interface to offload only the authentication part to the user * space. Authentication frames are passed between the driver and user * space through the %NL80211_CMD_FRAME interface. Host driver proceeds * further with the association after getting successful authentication * status. User space indicates the authentication status through * %NL80211_ATTR_STATUS_CODE attribute in %NL80211_CMD_EXTERNAL_AUTH * command interface. * * Host driver sends MLD address of the AP with %NL80211_ATTR_MLD_ADDR in * %NL80211_CMD_EXTERNAL_AUTH event to indicate user space to enable MLO * during the authentication offload in STA mode while connecting to MLD * APs. Host driver should check %NL80211_ATTR_MLO_SUPPORT flag capability * in %NL80211_CMD_CONNECT to know whether the user space supports enabling * MLO during the authentication offload or not. * User space should enable MLO during the authentication only when it * receives the AP MLD address in authentication offload request. User * space shouldn't enable MLO when the authentication offload request * doesn't indicate the AP MLD address even if the AP is MLO capable. * User space should use %NL80211_ATTR_MLD_ADDR as peer's MLD address and * interface address identified by %NL80211_ATTR_IFINDEX as self MLD * address. User space and host driver to use MLD addresses in RA, TA and * BSSID fields of the frames between them, and host driver translates the * MLD addresses to/from link addresses based on the link chosen for the * authentication. * * Host driver reports this status on an authentication failure to the * user space through the connect result as the user space would have * initiated the connection through the connect request. * * @NL80211_CMD_STA_OPMODE_CHANGED: An event that notify station's * ht opmode or vht opmode changes using any of %NL80211_ATTR_SMPS_MODE, * %NL80211_ATTR_CHANNEL_WIDTH,%NL80211_ATTR_NSS attributes with its * address(specified in %NL80211_ATTR_MAC). * * @NL80211_CMD_GET_FTM_RESPONDER_STATS: Retrieve FTM responder statistics, in * the %NL80211_ATTR_FTM_RESPONDER_STATS attribute. * * @NL80211_CMD_PEER_MEASUREMENT_START: start a (set of) peer measurement(s) * with the given parameters, which are encapsulated in the nested * %NL80211_ATTR_PEER_MEASUREMENTS attribute. Optionally, MAC address * randomization may be enabled and configured by specifying the * %NL80211_ATTR_MAC and %NL80211_ATTR_MAC_MASK attributes. * If a timeout is requested, use the %NL80211_ATTR_TIMEOUT attribute. * A u64 cookie for further %NL80211_ATTR_COOKIE use is returned in * the netlink extended ack message. * * To cancel a measurement, close the socket that requested it. * * Measurement results are reported to the socket that requested the * measurement using @NL80211_CMD_PEER_MEASUREMENT_RESULT when they * become available, so applications must ensure a large enough socket * buffer size. * * Depending on driver support it may or may not be possible to start * multiple concurrent measurements. * @NL80211_CMD_PEER_MEASUREMENT_RESULT: This command number is used for the * result notification from the driver to the requesting socket. * @NL80211_CMD_PEER_MEASUREMENT_COMPLETE: Notification only, indicating that * the measurement completed, using the measurement cookie * (%NL80211_ATTR_COOKIE). * * @NL80211_CMD_NOTIFY_RADAR: Notify the kernel that a radar signal was * detected and reported by a neighboring device on the channel * indicated by %NL80211_ATTR_WIPHY_FREQ and other attributes * determining the width and type. * * @NL80211_CMD_UPDATE_OWE_INFO: This interface allows the host driver to * offload OWE processing to user space. This intends to support * OWE AKM by the host drivers that implement SME but rely * on the user space for the cryptographic/DH IE processing in AP mode. * * @NL80211_CMD_PROBE_MESH_LINK: The requirement for mesh link metric * refreshing, is that from one mesh point we be able to send some data * frames to other mesh points which are not currently selected as a * primary traffic path, but which are only 1 hop away. The absence of * the primary path to the chosen node makes it necessary to apply some * form of marking on a chosen packet stream so that the packets can be * properly steered to the selected node for testing, and not by the * regular mesh path lookup. Further, the packets must be of type data * so that the rate control (often embedded in firmware) is used for * rate selection. * * Here attribute %NL80211_ATTR_MAC is used to specify connected mesh * peer MAC address and %NL80211_ATTR_FRAME is used to specify the frame * content. The frame is ethernet data. * * @NL80211_CMD_SET_TID_CONFIG: Data frame TID specific configuration * is passed using %NL80211_ATTR_TID_CONFIG attribute. * * @NL80211_CMD_UNPROT_BEACON: Unprotected or incorrectly protected Beacon * frame. This event is used to indicate that a received Beacon frame was * dropped because it did not include a valid MME MIC while beacon * protection was enabled (BIGTK configured in station mode). * * @NL80211_CMD_CONTROL_PORT_FRAME_TX_STATUS: Report TX status of a control * port frame transmitted with %NL80211_CMD_CONTROL_PORT_FRAME. * %NL80211_ATTR_COOKIE identifies the TX command and %NL80211_ATTR_FRAME * includes the contents of the frame. %NL80211_ATTR_ACK flag is included * if the recipient acknowledged the frame. * * @NL80211_CMD_SET_SAR_SPECS: SAR power limitation configuration is * passed using %NL80211_ATTR_SAR_SPEC. %NL80211_ATTR_WIPHY is used to * specify the wiphy index to be applied to. * * @NL80211_CMD_OBSS_COLOR_COLLISION: This notification is sent out whenever * mac80211/drv detects a bss color collision. * * @NL80211_CMD_COLOR_CHANGE_REQUEST: This command is used to indicate that * userspace wants to change the BSS color. * * @NL80211_CMD_COLOR_CHANGE_STARTED: Notify userland, that a color change has * started * * @NL80211_CMD_COLOR_CHANGE_ABORTED: Notify userland, that the color change has * been aborted * * @NL80211_CMD_COLOR_CHANGE_COMPLETED: Notify userland that the color change * has completed * * @NL80211_CMD_SET_FILS_AAD: Set FILS AAD data to the driver using - * &NL80211_ATTR_MAC - for STA MAC address * &NL80211_ATTR_FILS_KEK - for KEK * &NL80211_ATTR_FILS_NONCES - for FILS Nonces * (STA Nonce 16 bytes followed by AP Nonce 16 bytes) * * @NL80211_CMD_ASSOC_COMEBACK: notification about an association * temporal rejection with comeback. The event includes %NL80211_ATTR_MAC * to describe the BSSID address of the AP and %NL80211_ATTR_TIMEOUT to * specify the timeout value. * * @NL80211_CMD_ADD_LINK: Add a new link to an interface. The * %NL80211_ATTR_MLO_LINK_ID attribute is used for the new link. * @NL80211_CMD_REMOVE_LINK: Remove a link from an interface. This may come * without %NL80211_ATTR_MLO_LINK_ID as an easy way to remove all links * in preparation for e.g. roaming to a regular (non-MLO) AP. * * @NL80211_CMD_ADD_LINK_STA: Add a link to an MLD station * @NL80211_CMD_MODIFY_LINK_STA: Modify a link of an MLD station * @NL80211_CMD_REMOVE_LINK_STA: Remove a link of an MLD station * * @NL80211_CMD_SET_HW_TIMESTAMP: Enable/disable HW timestamping of Timing * measurement and Fine timing measurement frames. If %NL80211_ATTR_MAC * is included, enable/disable HW timestamping only for frames to/from the * specified MAC address. Otherwise enable/disable HW timestamping for * all TM/FTM frames (including ones that were enabled with specific MAC * address). If %NL80211_ATTR_HW_TIMESTAMP_ENABLED is not included, disable * HW timestamping. * The number of peers that HW timestamping can be enabled for concurrently * is indicated by %NL80211_ATTR_MAX_HW_TIMESTAMP_PEERS. * * @NL80211_CMD_MAX: highest used command number * @__NL80211_CMD_AFTER_LAST: internal use */ enum nl80211_commands { /* don't change the order or add anything between, this is ABI! */ NL80211_CMD_UNSPEC, NL80211_CMD_GET_WIPHY, /* can dump */ NL80211_CMD_SET_WIPHY, NL80211_CMD_NEW_WIPHY, NL80211_CMD_DEL_WIPHY, NL80211_CMD_GET_INTERFACE, /* can dump */ NL80211_CMD_SET_INTERFACE, NL80211_CMD_NEW_INTERFACE, NL80211_CMD_DEL_INTERFACE, NL80211_CMD_GET_KEY, NL80211_CMD_SET_KEY, NL80211_CMD_NEW_KEY, NL80211_CMD_DEL_KEY, NL80211_CMD_GET_BEACON, NL80211_CMD_SET_BEACON, NL80211_CMD_START_AP, NL80211_CMD_NEW_BEACON = NL80211_CMD_START_AP, NL80211_CMD_STOP_AP, NL80211_CMD_DEL_BEACON = NL80211_CMD_STOP_AP, NL80211_CMD_GET_STATION, NL80211_CMD_SET_STATION, NL80211_CMD_NEW_STATION, NL80211_CMD_DEL_STATION, NL80211_CMD_GET_MPATH, NL80211_CMD_SET_MPATH, NL80211_CMD_NEW_MPATH, NL80211_CMD_DEL_MPATH, NL80211_CMD_SET_BSS, NL80211_CMD_SET_REG, NL80211_CMD_REQ_SET_REG, NL80211_CMD_GET_MESH_CONFIG, NL80211_CMD_SET_MESH_CONFIG, NL80211_CMD_SET_MGMT_EXTRA_IE /* reserved; not used */, NL80211_CMD_GET_REG, NL80211_CMD_GET_SCAN, NL80211_CMD_TRIGGER_SCAN, NL80211_CMD_NEW_SCAN_RESULTS, NL80211_CMD_SCAN_ABORTED, NL80211_CMD_REG_CHANGE, NL80211_CMD_AUTHENTICATE, NL80211_CMD_ASSOCIATE, NL80211_CMD_DEAUTHENTICATE, NL80211_CMD_DISASSOCIATE, NL80211_CMD_MICHAEL_MIC_FAILURE, NL80211_CMD_REG_BEACON_HINT, NL80211_CMD_JOIN_IBSS, NL80211_CMD_LEAVE_IBSS, NL80211_CMD_TESTMODE, NL80211_CMD_CONNECT, NL80211_CMD_ROAM, NL80211_CMD_DISCONNECT, NL80211_CMD_SET_WIPHY_NETNS, NL80211_CMD_GET_SURVEY, NL80211_CMD_NEW_SURVEY_RESULTS, NL80211_CMD_SET_PMKSA, NL80211_CMD_DEL_PMKSA, NL80211_CMD_FLUSH_PMKSA, NL80211_CMD_REMAIN_ON_CHANNEL, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL, NL80211_CMD_SET_TX_BITRATE_MASK, NL80211_CMD_REGISTER_FRAME, NL80211_CMD_REGISTER_ACTION = NL80211_CMD_REGISTER_FRAME, NL80211_CMD_FRAME, NL80211_CMD_ACTION = NL80211_CMD_FRAME, NL80211_CMD_FRAME_TX_STATUS, NL80211_CMD_ACTION_TX_STATUS = NL80211_CMD_FRAME_TX_STATUS, NL80211_CMD_SET_POWER_SAVE, NL80211_CMD_GET_POWER_SAVE, NL80211_CMD_SET_CQM, NL80211_CMD_NOTIFY_CQM, NL80211_CMD_SET_CHANNEL, NL80211_CMD_SET_WDS_PEER, NL80211_CMD_FRAME_WAIT_CANCEL, NL80211_CMD_JOIN_MESH, NL80211_CMD_LEAVE_MESH, NL80211_CMD_UNPROT_DEAUTHENTICATE, NL80211_CMD_UNPROT_DISASSOCIATE, NL80211_CMD_NEW_PEER_CANDIDATE, NL80211_CMD_GET_WOWLAN, NL80211_CMD_SET_WOWLAN, NL80211_CMD_START_SCHED_SCAN, NL80211_CMD_STOP_SCHED_SCAN, NL80211_CMD_SCHED_SCAN_RESULTS, NL80211_CMD_SCHED_SCAN_STOPPED, NL80211_CMD_SET_REKEY_OFFLOAD, NL80211_CMD_PMKSA_CANDIDATE, NL80211_CMD_TDLS_OPER, NL80211_CMD_TDLS_MGMT, NL80211_CMD_UNEXPECTED_FRAME, NL80211_CMD_PROBE_CLIENT, NL80211_CMD_REGISTER_BEACONS, NL80211_CMD_UNEXPECTED_4ADDR_FRAME, NL80211_CMD_SET_NOACK_MAP, NL80211_CMD_CH_SWITCH_NOTIFY, NL80211_CMD_START_P2P_DEVICE, NL80211_CMD_STOP_P2P_DEVICE, NL80211_CMD_CONN_FAILED, NL80211_CMD_SET_MCAST_RATE, NL80211_CMD_SET_MAC_ACL, NL80211_CMD_RADAR_DETECT, NL80211_CMD_GET_PROTOCOL_FEATURES, NL80211_CMD_UPDATE_FT_IES, NL80211_CMD_FT_EVENT, NL80211_CMD_CRIT_PROTOCOL_START, NL80211_CMD_CRIT_PROTOCOL_STOP, NL80211_CMD_GET_COALESCE, NL80211_CMD_SET_COALESCE, NL80211_CMD_CHANNEL_SWITCH, NL80211_CMD_VENDOR, NL80211_CMD_SET_QOS_MAP, NL80211_CMD_ADD_TX_TS, NL80211_CMD_DEL_TX_TS, NL80211_CMD_GET_MPP, NL80211_CMD_JOIN_OCB, NL80211_CMD_LEAVE_OCB, NL80211_CMD_CH_SWITCH_STARTED_NOTIFY, NL80211_CMD_TDLS_CHANNEL_SWITCH, NL80211_CMD_TDLS_CANCEL_CHANNEL_SWITCH, NL80211_CMD_WIPHY_REG_CHANGE, NL80211_CMD_ABORT_SCAN, NL80211_CMD_START_NAN, NL80211_CMD_STOP_NAN, NL80211_CMD_ADD_NAN_FUNCTION, NL80211_CMD_DEL_NAN_FUNCTION, NL80211_CMD_CHANGE_NAN_CONFIG, NL80211_CMD_NAN_MATCH, NL80211_CMD_SET_MULTICAST_TO_UNICAST, NL80211_CMD_UPDATE_CONNECT_PARAMS, NL80211_CMD_SET_PMK, NL80211_CMD_DEL_PMK, NL80211_CMD_PORT_AUTHORIZED, NL80211_CMD_RELOAD_REGDB, NL80211_CMD_EXTERNAL_AUTH, NL80211_CMD_STA_OPMODE_CHANGED, NL80211_CMD_CONTROL_PORT_FRAME, NL80211_CMD_GET_FTM_RESPONDER_STATS, NL80211_CMD_PEER_MEASUREMENT_START, NL80211_CMD_PEER_MEASUREMENT_RESULT, NL80211_CMD_PEER_MEASUREMENT_COMPLETE, NL80211_CMD_NOTIFY_RADAR, NL80211_CMD_UPDATE_OWE_INFO, NL80211_CMD_PROBE_MESH_LINK, NL80211_CMD_SET_TID_CONFIG, NL80211_CMD_UNPROT_BEACON, NL80211_CMD_CONTROL_PORT_FRAME_TX_STATUS, NL80211_CMD_SET_SAR_SPECS, NL80211_CMD_OBSS_COLOR_COLLISION, NL80211_CMD_COLOR_CHANGE_REQUEST, NL80211_CMD_COLOR_CHANGE_STARTED, NL80211_CMD_COLOR_CHANGE_ABORTED, NL80211_CMD_COLOR_CHANGE_COMPLETED, NL80211_CMD_SET_FILS_AAD, NL80211_CMD_ASSOC_COMEBACK, NL80211_CMD_ADD_LINK, NL80211_CMD_REMOVE_LINK, NL80211_CMD_ADD_LINK_STA, NL80211_CMD_MODIFY_LINK_STA, NL80211_CMD_REMOVE_LINK_STA, NL80211_CMD_SET_HW_TIMESTAMP, /* add new commands above here */ /* used to define NL80211_CMD_MAX below */ __NL80211_CMD_AFTER_LAST, NL80211_CMD_MAX = __NL80211_CMD_AFTER_LAST - 1 }; /* * Allow user space programs to use #ifdef on new commands by defining them * here */ #define NL80211_CMD_SET_BSS NL80211_CMD_SET_BSS #define NL80211_CMD_SET_MGMT_EXTRA_IE NL80211_CMD_SET_MGMT_EXTRA_IE #define NL80211_CMD_REG_CHANGE NL80211_CMD_REG_CHANGE #define NL80211_CMD_AUTHENTICATE NL80211_CMD_AUTHENTICATE #define NL80211_CMD_ASSOCIATE NL80211_CMD_ASSOCIATE #define NL80211_CMD_DEAUTHENTICATE NL80211_CMD_DEAUTHENTICATE #define NL80211_CMD_DISASSOCIATE NL80211_CMD_DISASSOCIATE #define NL80211_CMD_REG_BEACON_HINT NL80211_CMD_REG_BEACON_HINT #define NL80211_ATTR_FEATURE_FLAGS NL80211_ATTR_FEATURE_FLAGS /* source-level API compatibility */ #define NL80211_CMD_GET_MESH_PARAMS NL80211_CMD_GET_MESH_CONFIG #define NL80211_CMD_SET_MESH_PARAMS NL80211_CMD_SET_MESH_CONFIG #define NL80211_MESH_SETUP_VENDOR_PATH_SEL_IE NL80211_MESH_SETUP_IE /** * enum nl80211_attrs - nl80211 netlink attributes * * @NL80211_ATTR_UNSPEC: unspecified attribute to catch errors * * @NL80211_ATTR_WIPHY: index of wiphy to operate on, cf. * /sys/class/ieee80211//index * @NL80211_ATTR_WIPHY_NAME: wiphy name (used for renaming) * @NL80211_ATTR_WIPHY_TXQ_PARAMS: a nested array of TX queue parameters * @NL80211_ATTR_WIPHY_FREQ: frequency of the selected channel in MHz, * defines the channel together with the (deprecated) * %NL80211_ATTR_WIPHY_CHANNEL_TYPE attribute or the attributes * %NL80211_ATTR_CHANNEL_WIDTH and if needed %NL80211_ATTR_CENTER_FREQ1 * and %NL80211_ATTR_CENTER_FREQ2 * @NL80211_ATTR_CHANNEL_WIDTH: u32 attribute containing one of the values * of &enum nl80211_chan_width, describing the channel width. See the * documentation of the enum for more information. * @NL80211_ATTR_CENTER_FREQ1: Center frequency of the first part of the * channel, used for anything but 20 MHz bandwidth. In S1G this is the * operating channel center frequency. * @NL80211_ATTR_CENTER_FREQ2: Center frequency of the second part of the * channel, used only for 80+80 MHz bandwidth * @NL80211_ATTR_WIPHY_CHANNEL_TYPE: included with NL80211_ATTR_WIPHY_FREQ * if HT20 or HT40 are to be used (i.e., HT disabled if not included): * NL80211_CHAN_NO_HT = HT not allowed (i.e., same as not including * this attribute) * NL80211_CHAN_HT20 = HT20 only * NL80211_CHAN_HT40MINUS = secondary channel is below the primary channel * NL80211_CHAN_HT40PLUS = secondary channel is above the primary channel * This attribute is now deprecated. * @NL80211_ATTR_WIPHY_RETRY_SHORT: TX retry limit for frames whose length is * less than or equal to the RTS threshold; allowed range: 1..255; * dot11ShortRetryLimit; u8 * @NL80211_ATTR_WIPHY_RETRY_LONG: TX retry limit for frames whose length is * greater than the RTS threshold; allowed range: 1..255; * dot11ShortLongLimit; u8 * @NL80211_ATTR_WIPHY_FRAG_THRESHOLD: fragmentation threshold, i.e., maximum * length in octets for frames; allowed range: 256..8000, disable * fragmentation with (u32)-1; dot11FragmentationThreshold; u32 * @NL80211_ATTR_WIPHY_RTS_THRESHOLD: RTS threshold (TX frames with length * larger than or equal to this use RTS/CTS handshake); allowed range: * 0..65536, disable with (u32)-1; dot11RTSThreshold; u32 * @NL80211_ATTR_WIPHY_COVERAGE_CLASS: Coverage Class as defined by IEEE 802.11 * section 7.3.2.9; dot11CoverageClass; u8 * * @NL80211_ATTR_IFINDEX: network interface index of the device to operate on * @NL80211_ATTR_IFNAME: network interface name * @NL80211_ATTR_IFTYPE: type of virtual interface, see &enum nl80211_iftype * * @NL80211_ATTR_WDEV: wireless device identifier, used for pseudo-devices * that don't have a netdev (u64) * * @NL80211_ATTR_MAC: MAC address (various uses) * * @NL80211_ATTR_KEY_DATA: (temporal) key data; for TKIP this consists of * 16 bytes encryption key followed by 8 bytes each for TX and RX MIC * keys * @NL80211_ATTR_KEY_IDX: key ID (u8, 0-3) * @NL80211_ATTR_KEY_CIPHER: key cipher suite (u32, as defined by IEEE 802.11 * section 7.3.2.25.1, e.g. 0x000FAC04) * @NL80211_ATTR_KEY_SEQ: transmit key sequence number (IV/PN) for TKIP and * CCMP keys, each six bytes in little endian * @NL80211_ATTR_KEY_DEFAULT: Flag attribute indicating the key is default key * @NL80211_ATTR_KEY_DEFAULT_MGMT: Flag attribute indicating the key is the * default management key * @NL80211_ATTR_CIPHER_SUITES_PAIRWISE: For crypto settings for connect or * other commands, indicates which pairwise cipher suites are used * @NL80211_ATTR_CIPHER_SUITE_GROUP: For crypto settings for connect or * other commands, indicates which group cipher suite is used * * @NL80211_ATTR_BEACON_INTERVAL: beacon interval in TU * @NL80211_ATTR_DTIM_PERIOD: DTIM period for beaconing * @NL80211_ATTR_BEACON_HEAD: portion of the beacon before the TIM IE * @NL80211_ATTR_BEACON_TAIL: portion of the beacon after the TIM IE * * @NL80211_ATTR_STA_AID: Association ID for the station (u16) * @NL80211_ATTR_STA_FLAGS: flags, nested element with NLA_FLAG attributes of * &enum nl80211_sta_flags (deprecated, use %NL80211_ATTR_STA_FLAGS2) * @NL80211_ATTR_STA_LISTEN_INTERVAL: listen interval as defined by * IEEE 802.11 7.3.1.6 (u16). * @NL80211_ATTR_STA_SUPPORTED_RATES: supported rates, array of supported * rates as defined by IEEE 802.11 7.3.2.2 but without the length * restriction (at most %NL80211_MAX_SUPP_RATES). * @NL80211_ATTR_STA_VLAN: interface index of VLAN interface to move station * to, or the AP interface the station was originally added to. * @NL80211_ATTR_STA_INFO: information about a station, part of station info * given for %NL80211_CMD_GET_STATION, nested attribute containing * info as possible, see &enum nl80211_sta_info. * * @NL80211_ATTR_WIPHY_BANDS: Information about an operating bands, * consisting of a nested array. * * @NL80211_ATTR_MESH_ID: mesh id (1-32 bytes). * @NL80211_ATTR_STA_PLINK_ACTION: action to perform on the mesh peer link * (see &enum nl80211_plink_action). * @NL80211_ATTR_MPATH_NEXT_HOP: MAC address of the next hop for a mesh path. * @NL80211_ATTR_MPATH_INFO: information about a mesh_path, part of mesh path * info given for %NL80211_CMD_GET_MPATH, nested attribute described at * &enum nl80211_mpath_info. * * @NL80211_ATTR_MNTR_FLAGS: flags, nested element with NLA_FLAG attributes of * &enum nl80211_mntr_flags. * * @NL80211_ATTR_REG_ALPHA2: an ISO-3166-alpha2 country code for which the * current regulatory domain should be set to or is already set to. * For example, 'CR', for Costa Rica. This attribute is used by the kernel * to query the CRDA to retrieve one regulatory domain. This attribute can * also be used by userspace to query the kernel for the currently set * regulatory domain. We chose an alpha2 as that is also used by the * IEEE-802.11 country information element to identify a country. * Users can also simply ask the wireless core to set regulatory domain * to a specific alpha2. * @NL80211_ATTR_REG_RULES: a nested array of regulatory domain regulatory * rules. * * @NL80211_ATTR_BSS_CTS_PROT: whether CTS protection is enabled (u8, 0 or 1) * @NL80211_ATTR_BSS_SHORT_PREAMBLE: whether short preamble is enabled * (u8, 0 or 1) * @NL80211_ATTR_BSS_SHORT_SLOT_TIME: whether short slot time enabled * (u8, 0 or 1) * @NL80211_ATTR_BSS_BASIC_RATES: basic rates, array of basic * rates in format defined by IEEE 802.11 7.3.2.2 but without the length * restriction (at most %NL80211_MAX_SUPP_RATES). * * @NL80211_ATTR_HT_CAPABILITY: HT Capability information element (from * association request when used with NL80211_CMD_NEW_STATION) * * @NL80211_ATTR_SUPPORTED_IFTYPES: nested attribute containing all * supported interface types, each a flag attribute with the number * of the interface mode. * * @NL80211_ATTR_MGMT_SUBTYPE: Management frame subtype for * %NL80211_CMD_SET_MGMT_EXTRA_IE. * * @NL80211_ATTR_IE: Information element(s) data (used, e.g., with * %NL80211_CMD_SET_MGMT_EXTRA_IE). * * @NL80211_ATTR_MAX_NUM_SCAN_SSIDS: number of SSIDs you can scan with * a single scan request, a wiphy attribute. * @NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS: number of SSIDs you can * scan with a single scheduled scan request, a wiphy attribute. * @NL80211_ATTR_MAX_SCAN_IE_LEN: maximum length of information elements * that can be added to a scan request * @NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN: maximum length of information * elements that can be added to a scheduled scan request * @NL80211_ATTR_MAX_MATCH_SETS: maximum number of sets that can be * used with @NL80211_ATTR_SCHED_SCAN_MATCH, a wiphy attribute. * * @NL80211_ATTR_SCAN_FREQUENCIES: nested attribute with frequencies (in MHz) * @NL80211_ATTR_SCAN_SSIDS: nested attribute with SSIDs, leave out for passive * scanning and include a zero-length SSID (wildcard) for wildcard scan * @NL80211_ATTR_BSS: scan result BSS * * @NL80211_ATTR_REG_INITIATOR: indicates who requested the regulatory domain * currently in effect. This could be any of the %NL80211_REGDOM_SET_BY_* * @NL80211_ATTR_REG_TYPE: indicates the type of the regulatory domain currently * set. This can be one of the nl80211_reg_type (%NL80211_REGDOM_TYPE_*) * * @NL80211_ATTR_SUPPORTED_COMMANDS: wiphy attribute that specifies * an array of command numbers (i.e. a mapping index to command number) * that the driver for the given wiphy supports. * * @NL80211_ATTR_FRAME: frame data (binary attribute), including frame header * and body, but not FCS; used, e.g., with NL80211_CMD_AUTHENTICATE and * NL80211_CMD_ASSOCIATE events * @NL80211_ATTR_SSID: SSID (binary attribute, 0..32 octets) * @NL80211_ATTR_AUTH_TYPE: AuthenticationType, see &enum nl80211_auth_type, * represented as a u32 * @NL80211_ATTR_REASON_CODE: ReasonCode for %NL80211_CMD_DEAUTHENTICATE and * %NL80211_CMD_DISASSOCIATE, u16 * * @NL80211_ATTR_KEY_TYPE: Key Type, see &enum nl80211_key_type, represented as * a u32 * * @NL80211_ATTR_FREQ_BEFORE: A channel which has suffered a regulatory change * due to considerations from a beacon hint. This attribute reflects * the state of the channel _before_ the beacon hint processing. This * attributes consists of a nested attribute containing * NL80211_FREQUENCY_ATTR_* * @NL80211_ATTR_FREQ_AFTER: A channel which has suffered a regulatory change * due to considerations from a beacon hint. This attribute reflects * the state of the channel _after_ the beacon hint processing. This * attributes consists of a nested attribute containing * NL80211_FREQUENCY_ATTR_* * * @NL80211_ATTR_CIPHER_SUITES: a set of u32 values indicating the supported * cipher suites * * @NL80211_ATTR_FREQ_FIXED: a flag indicating the IBSS should not try to look * for other networks on different channels * * @NL80211_ATTR_TIMED_OUT: a flag indicating than an operation timed out; this * is used, e.g., with %NL80211_CMD_AUTHENTICATE event * * @NL80211_ATTR_USE_MFP: Whether management frame protection (IEEE 802.11w) is * used for the association (&enum nl80211_mfp, represented as a u32); * this attribute can be used with %NL80211_CMD_ASSOCIATE and * %NL80211_CMD_CONNECT requests. %NL80211_MFP_OPTIONAL is not allowed for * %NL80211_CMD_ASSOCIATE since user space SME is expected and hence, it * must have decided whether to use management frame protection or not. * Setting %NL80211_MFP_OPTIONAL with a %NL80211_CMD_CONNECT request will * let the driver (or the firmware) decide whether to use MFP or not. * * @NL80211_ATTR_STA_FLAGS2: Attribute containing a * &struct nl80211_sta_flag_update. * * @NL80211_ATTR_CONTROL_PORT: A flag indicating whether user space controls * IEEE 802.1X port, i.e., sets/clears %NL80211_STA_FLAG_AUTHORIZED, in * station mode. If the flag is included in %NL80211_CMD_ASSOCIATE * request, the driver will assume that the port is unauthorized until * authorized by user space. Otherwise, port is marked authorized by * default in station mode. * @NL80211_ATTR_CONTROL_PORT_ETHERTYPE: A 16-bit value indicating the * ethertype that will be used for key negotiation. It can be * specified with the associate and connect commands. If it is not * specified, the value defaults to 0x888E (PAE, 802.1X). This * attribute is also used as a flag in the wiphy information to * indicate that protocols other than PAE are supported. * @NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT: When included along with * %NL80211_ATTR_CONTROL_PORT_ETHERTYPE, indicates that the custom * ethertype frames used for key negotiation must not be encrypted. * @NL80211_ATTR_CONTROL_PORT_OVER_NL80211: A flag indicating whether control * port frames (e.g. of type given in %NL80211_ATTR_CONTROL_PORT_ETHERTYPE) * will be sent directly to the network interface or sent via the NL80211 * socket. If this attribute is missing, then legacy behavior of sending * control port frames directly to the network interface is used. If the * flag is included, then control port frames are sent over NL80211 instead * using %CMD_CONTROL_PORT_FRAME. If control port routing over NL80211 is * to be used then userspace must also use the %NL80211_ATTR_SOCKET_OWNER * flag. When used with %NL80211_ATTR_CONTROL_PORT_NO_PREAUTH, pre-auth * frames are not forwared over the control port. * * @NL80211_ATTR_TESTDATA: Testmode data blob, passed through to the driver. * We recommend using nested, driver-specific attributes within this. * * @NL80211_ATTR_DISCONNECTED_BY_AP: A flag indicating that the DISCONNECT * event was due to the AP disconnecting the station, and not due to * a local disconnect request. * @NL80211_ATTR_STATUS_CODE: StatusCode for the %NL80211_CMD_CONNECT * event (u16) * @NL80211_ATTR_PRIVACY: Flag attribute, used with connect(), indicating * that protected APs should be used. This is also used with NEW_BEACON to * indicate that the BSS is to use protection. * * @NL80211_ATTR_CIPHERS_PAIRWISE: Used with CONNECT, ASSOCIATE, and NEW_BEACON * to indicate which unicast key ciphers will be used with the connection * (an array of u32). * @NL80211_ATTR_CIPHER_GROUP: Used with CONNECT, ASSOCIATE, and NEW_BEACON to * indicate which group key cipher will be used with the connection (a * u32). * @NL80211_ATTR_WPA_VERSIONS: Used with CONNECT, ASSOCIATE, and NEW_BEACON to * indicate which WPA version(s) the AP we want to associate with is using * (a u32 with flags from &enum nl80211_wpa_versions). * @NL80211_ATTR_AKM_SUITES: Used with CONNECT, ASSOCIATE, and NEW_BEACON to * indicate which key management algorithm(s) to use (an array of u32). * This attribute is also sent in response to @NL80211_CMD_GET_WIPHY, * indicating the supported AKM suites, intended for specific drivers which * implement SME and have constraints on which AKMs are supported and also * the cases where an AKM support is offloaded to the driver/firmware. * If there is no such notification from the driver, user space should * assume the driver supports all the AKM suites. * * @NL80211_ATTR_REQ_IE: (Re)association request information elements as * sent out by the card, for ROAM and successful CONNECT events. * @NL80211_ATTR_RESP_IE: (Re)association response information elements as * sent by peer, for ROAM and successful CONNECT events. * * @NL80211_ATTR_PREV_BSSID: previous BSSID, to be used in ASSOCIATE and CONNECT * commands to specify a request to reassociate within an ESS, i.e., to use * Reassociate Request frame (with the value of this attribute in the * Current AP address field) instead of Association Request frame which is * used for the initial association to an ESS. * * @NL80211_ATTR_KEY: key information in a nested attribute with * %NL80211_KEY_* sub-attributes * @NL80211_ATTR_KEYS: array of keys for static WEP keys for connect() * and join_ibss(), key information is in a nested attribute each * with %NL80211_KEY_* sub-attributes * * @NL80211_ATTR_PID: Process ID of a network namespace. * * @NL80211_ATTR_GENERATION: Used to indicate consistent snapshots for * dumps. This number increases whenever the object list being * dumped changes, and as such userspace can verify that it has * obtained a complete and consistent snapshot by verifying that * all dump messages contain the same generation number. If it * changed then the list changed and the dump should be repeated * completely from scratch. * * @NL80211_ATTR_4ADDR: Use 4-address frames on a virtual interface * * @NL80211_ATTR_SURVEY_INFO: survey information about a channel, part of * the survey response for %NL80211_CMD_GET_SURVEY, nested attribute * containing info as possible, see &enum survey_info. * * @NL80211_ATTR_PMKID: PMK material for PMKSA caching. * @NL80211_ATTR_MAX_NUM_PMKIDS: maximum number of PMKIDs a firmware can * cache, a wiphy attribute. * * @NL80211_ATTR_DURATION: Duration of an operation in milliseconds, u32. * @NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION: Device attribute that * specifies the maximum duration that can be requested with the * remain-on-channel operation, in milliseconds, u32. * * @NL80211_ATTR_COOKIE: Generic 64-bit cookie to identify objects. * * @NL80211_ATTR_TX_RATES: Nested set of attributes * (enum nl80211_tx_rate_attributes) describing TX rates per band. The * enum nl80211_band value is used as the index (nla_type() of the nested * data. If a band is not included, it will be configured to allow all * rates based on negotiated supported rates information. This attribute * is used with %NL80211_CMD_SET_TX_BITRATE_MASK and with starting AP, * and joining mesh networks (not IBSS yet). In the later case, it must * specify just a single bitrate, which is to be used for the beacon. * The driver must also specify support for this with the extended * features NL80211_EXT_FEATURE_BEACON_RATE_LEGACY, * NL80211_EXT_FEATURE_BEACON_RATE_HT, * NL80211_EXT_FEATURE_BEACON_RATE_VHT and * NL80211_EXT_FEATURE_BEACON_RATE_HE. * * @NL80211_ATTR_FRAME_MATCH: A binary attribute which typically must contain * at least one byte, currently used with @NL80211_CMD_REGISTER_FRAME. * @NL80211_ATTR_FRAME_TYPE: A u16 indicating the frame type/subtype for the * @NL80211_CMD_REGISTER_FRAME command. * @NL80211_ATTR_TX_FRAME_TYPES: wiphy capability attribute, which is a * nested attribute of %NL80211_ATTR_FRAME_TYPE attributes, containing * information about which frame types can be transmitted with * %NL80211_CMD_FRAME. * @NL80211_ATTR_RX_FRAME_TYPES: wiphy capability attribute, which is a * nested attribute of %NL80211_ATTR_FRAME_TYPE attributes, containing * information about which frame types can be registered for RX. * * @NL80211_ATTR_ACK: Flag attribute indicating that the frame was * acknowledged by the recipient. * * @NL80211_ATTR_PS_STATE: powersave state, using &enum nl80211_ps_state values. * * @NL80211_ATTR_CQM: connection quality monitor configuration in a * nested attribute with %NL80211_ATTR_CQM_* sub-attributes. * * @NL80211_ATTR_LOCAL_STATE_CHANGE: Flag attribute to indicate that a command * is requesting a local authentication/association state change without * invoking actual management frame exchange. This can be used with * NL80211_CMD_AUTHENTICATE, NL80211_CMD_DEAUTHENTICATE, * NL80211_CMD_DISASSOCIATE. * * @NL80211_ATTR_AP_ISOLATE: (AP mode) Do not forward traffic between stations * connected to this BSS. * * @NL80211_ATTR_WIPHY_TX_POWER_SETTING: Transmit power setting type. See * &enum nl80211_tx_power_setting for possible values. * @NL80211_ATTR_WIPHY_TX_POWER_LEVEL: Transmit power level in signed mBm units. * This is used in association with @NL80211_ATTR_WIPHY_TX_POWER_SETTING * for non-automatic settings. * * @NL80211_ATTR_SUPPORT_IBSS_RSN: The device supports IBSS RSN, which mostly * means support for per-station GTKs. * * @NL80211_ATTR_WIPHY_ANTENNA_TX: Bitmap of allowed antennas for transmitting. * This can be used to mask out antennas which are not attached or should * not be used for transmitting. If an antenna is not selected in this * bitmap the hardware is not allowed to transmit on this antenna. * * Each bit represents one antenna, starting with antenna 1 at the first * bit. Depending on which antennas are selected in the bitmap, 802.11n * drivers can derive which chainmasks to use (if all antennas belonging to * a particular chain are disabled this chain should be disabled) and if * a chain has diversity antennas wether diversity should be used or not. * HT capabilities (STBC, TX Beamforming, Antenna selection) can be * derived from the available chains after applying the antenna mask. * Non-802.11n drivers can derive wether to use diversity or not. * Drivers may reject configurations or RX/TX mask combinations they cannot * support by returning -EINVAL. * * @NL80211_ATTR_WIPHY_ANTENNA_RX: Bitmap of allowed antennas for receiving. * This can be used to mask out antennas which are not attached or should * not be used for receiving. If an antenna is not selected in this bitmap * the hardware should not be configured to receive on this antenna. * For a more detailed description see @NL80211_ATTR_WIPHY_ANTENNA_TX. * * @NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX: Bitmap of antennas which are available * for configuration as TX antennas via the above parameters. * * @NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX: Bitmap of antennas which are available * for configuration as RX antennas via the above parameters. * * @NL80211_ATTR_MCAST_RATE: Multicast tx rate (in 100 kbps) for IBSS * * @NL80211_ATTR_OFFCHANNEL_TX_OK: For management frame TX, the frame may be * transmitted on another channel when the channel given doesn't match * the current channel. If the current channel doesn't match and this * flag isn't set, the frame will be rejected. This is also used as an * nl80211 capability flag. * * @NL80211_ATTR_BSS_HT_OPMODE: HT operation mode (u16) * * @NL80211_ATTR_KEY_DEFAULT_TYPES: A nested attribute containing flags * attributes, specifying what a key should be set as default as. * See &enum nl80211_key_default_types. * * @NL80211_ATTR_MESH_SETUP: Optional mesh setup parameters. These cannot be * changed once the mesh is active. * @NL80211_ATTR_MESH_CONFIG: Mesh configuration parameters, a nested attribute * containing attributes from &enum nl80211_meshconf_params. * @NL80211_ATTR_SUPPORT_MESH_AUTH: Currently, this means the underlying driver * allows auth frames in a mesh to be passed to userspace for processing via * the @NL80211_MESH_SETUP_USERSPACE_AUTH flag. * @NL80211_ATTR_STA_PLINK_STATE: The state of a mesh peer link as defined in * &enum nl80211_plink_state. Used when userspace is driving the peer link * management state machine. @NL80211_MESH_SETUP_USERSPACE_AMPE or * @NL80211_MESH_SETUP_USERSPACE_MPM must be enabled. * * @NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED: indicates, as part of the wiphy * capabilities, the supported WoWLAN triggers * @NL80211_ATTR_WOWLAN_TRIGGERS: used by %NL80211_CMD_SET_WOWLAN to * indicate which WoW triggers should be enabled. This is also * used by %NL80211_CMD_GET_WOWLAN to get the currently enabled WoWLAN * triggers. * * @NL80211_ATTR_SCHED_SCAN_INTERVAL: Interval between scheduled scan * cycles, in msecs. * * @NL80211_ATTR_SCHED_SCAN_MATCH: Nested attribute with one or more * sets of attributes to match during scheduled scans. Only BSSs * that match any of the sets will be reported. These are * pass-thru filter rules. * For a match to succeed, the BSS must match all attributes of a * set. Since not every hardware supports matching all types of * attributes, there is no guarantee that the reported BSSs are * fully complying with the match sets and userspace needs to be * able to ignore them by itself. * Thus, the implementation is somewhat hardware-dependent, but * this is only an optimization and the userspace application * needs to handle all the non-filtered results anyway. * If the match attributes don't make sense when combined with * the values passed in @NL80211_ATTR_SCAN_SSIDS (eg. if an SSID * is included in the probe request, but the match attributes * will never let it go through), -EINVAL may be returned. * If omitted, no filtering is done. * * @NL80211_ATTR_INTERFACE_COMBINATIONS: Nested attribute listing the supported * interface combinations. In each nested item, it contains attributes * defined in &enum nl80211_if_combination_attrs. * @NL80211_ATTR_SOFTWARE_IFTYPES: Nested attribute (just like * %NL80211_ATTR_SUPPORTED_IFTYPES) containing the interface types that * are managed in software: interfaces of these types aren't subject to * any restrictions in their number or combinations. * * @NL80211_ATTR_REKEY_DATA: nested attribute containing the information * necessary for GTK rekeying in the device, see &enum nl80211_rekey_data. * * @NL80211_ATTR_SCAN_SUPP_RATES: rates per to be advertised as supported in scan, * nested array attribute containing an entry for each band, with the entry * being a list of supported rates as defined by IEEE 802.11 7.3.2.2 but * without the length restriction (at most %NL80211_MAX_SUPP_RATES). * * @NL80211_ATTR_HIDDEN_SSID: indicates whether SSID is to be hidden from Beacon * and Probe Response (when response to wildcard Probe Request); see * &enum nl80211_hidden_ssid, represented as a u32 * * @NL80211_ATTR_IE_PROBE_RESP: Information element(s) for Probe Response frame. * This is used with %NL80211_CMD_NEW_BEACON and %NL80211_CMD_SET_BEACON to * provide extra IEs (e.g., WPS/P2P IE) into Probe Response frames when the * driver (or firmware) replies to Probe Request frames. * @NL80211_ATTR_IE_ASSOC_RESP: Information element(s) for (Re)Association * Response frames. This is used with %NL80211_CMD_NEW_BEACON and * %NL80211_CMD_SET_BEACON to provide extra IEs (e.g., WPS/P2P IE) into * (Re)Association Response frames when the driver (or firmware) replies to * (Re)Association Request frames. * * @NL80211_ATTR_STA_WME: Nested attribute containing the wme configuration * of the station, see &enum nl80211_sta_wme_attr. * @NL80211_ATTR_SUPPORT_AP_UAPSD: the device supports uapsd when working * as AP. * * @NL80211_ATTR_ROAM_SUPPORT: Indicates whether the firmware is capable of * roaming to another AP in the same ESS if the signal lever is low. * * @NL80211_ATTR_PMKSA_CANDIDATE: Nested attribute containing the PMKSA caching * candidate information, see &enum nl80211_pmksa_candidate_attr. * * @NL80211_ATTR_TX_NO_CCK_RATE: Indicates whether to use CCK rate or not * for management frames transmission. In order to avoid p2p probe/action * frames are being transmitted at CCK rate in 2GHz band, the user space * applications use this attribute. * This attribute is used with %NL80211_CMD_TRIGGER_SCAN and * %NL80211_CMD_FRAME commands. * * @NL80211_ATTR_TDLS_ACTION: Low level TDLS action code (e.g. link setup * request, link setup confirm, link teardown, etc.). Values are * described in the TDLS (802.11z) specification. * @NL80211_ATTR_TDLS_DIALOG_TOKEN: Non-zero token for uniquely identifying a * TDLS conversation between two devices. * @NL80211_ATTR_TDLS_OPERATION: High level TDLS operation; see * &enum nl80211_tdls_operation, represented as a u8. * @NL80211_ATTR_TDLS_SUPPORT: A flag indicating the device can operate * as a TDLS peer sta. * @NL80211_ATTR_TDLS_EXTERNAL_SETUP: The TDLS discovery/setup and teardown * procedures should be performed by sending TDLS packets via * %NL80211_CMD_TDLS_MGMT. Otherwise %NL80211_CMD_TDLS_OPER should be * used for asking the driver to perform a TDLS operation. * * @NL80211_ATTR_DEVICE_AP_SME: This u32 attribute may be listed for devices * that have AP support to indicate that they have the AP SME integrated * with support for the features listed in this attribute, see * &enum nl80211_ap_sme_features. * * @NL80211_ATTR_DONT_WAIT_FOR_ACK: Used with %NL80211_CMD_FRAME, this tells * the driver to not wait for an acknowledgement. Note that due to this, * it will also not give a status callback nor return a cookie. This is * mostly useful for probe responses to save airtime. * * @NL80211_ATTR_FEATURE_FLAGS: This u32 attribute contains flags from * &enum nl80211_feature_flags and is advertised in wiphy information. * @NL80211_ATTR_PROBE_RESP_OFFLOAD: Indicates that the HW responds to probe * requests while operating in AP-mode. * This attribute holds a bitmap of the supported protocols for * offloading (see &enum nl80211_probe_resp_offload_support_attr). * * @NL80211_ATTR_PROBE_RESP: Probe Response template data. Contains the entire * probe-response frame. The DA field in the 802.11 header is zero-ed out, * to be filled by the FW. * @NL80211_ATTR_DISABLE_HT: Force HT capable interfaces to disable * this feature during association. This is a flag attribute. * Currently only supported in mac80211 drivers. * @NL80211_ATTR_DISABLE_VHT: Force VHT capable interfaces to disable * this feature during association. This is a flag attribute. * Currently only supported in mac80211 drivers. * @NL80211_ATTR_DISABLE_HE: Force HE capable interfaces to disable * this feature during association. This is a flag attribute. * Currently only supported in mac80211 drivers. * @NL80211_ATTR_HT_CAPABILITY_MASK: Specify which bits of the * ATTR_HT_CAPABILITY to which attention should be paid. * Currently, only mac80211 NICs support this feature. * The values that may be configured are: * MCS rates, MAX-AMSDU, HT-20-40 and HT_CAP_SGI_40 * AMPDU density and AMPDU factor. * All values are treated as suggestions and may be ignored * by the driver as required. The actual values may be seen in * the station debugfs ht_caps file. * * @NL80211_ATTR_DFS_REGION: region for regulatory rules which this country * abides to when initiating radiation on DFS channels. A country maps * to one DFS region. * * @NL80211_ATTR_NOACK_MAP: This u16 bitmap contains the No Ack Policy of * up to 16 TIDs. * * @NL80211_ATTR_INACTIVITY_TIMEOUT: timeout value in seconds, this can be * used by the drivers which has MLME in firmware and does not have support * to report per station tx/rx activity to free up the station entry from * the list. This needs to be used when the driver advertises the * capability to timeout the stations. * * @NL80211_ATTR_RX_SIGNAL_DBM: signal strength in dBm (as a 32-bit int); * this attribute is (depending on the driver capabilities) added to * received frames indicated with %NL80211_CMD_FRAME. * * @NL80211_ATTR_BG_SCAN_PERIOD: Background scan period in seconds * or 0 to disable background scan. * * @NL80211_ATTR_USER_REG_HINT_TYPE: type of regulatory hint passed from * userspace. If unset it is assumed the hint comes directly from * a user. If set code could specify exactly what type of source * was used to provide the hint. For the different types of * allowed user regulatory hints see nl80211_user_reg_hint_type. * * @NL80211_ATTR_CONN_FAILED_REASON: The reason for which AP has rejected * the connection request from a station. nl80211_connect_failed_reason * enum has different reasons of connection failure. * * @NL80211_ATTR_AUTH_DATA: Fields and elements in Authentication frames. * This contains the authentication frame body (non-IE and IE data), * excluding the Authentication algorithm number, i.e., starting at the * Authentication transaction sequence number field. It is used with * authentication algorithms that need special fields to be added into * the frames (SAE and FILS). Currently, only the SAE cases use the * initial two fields (Authentication transaction sequence number and * Status code). However, those fields are included in the attribute data * for all authentication algorithms to keep the attribute definition * consistent. * * @NL80211_ATTR_VHT_CAPABILITY: VHT Capability information element (from * association request when used with NL80211_CMD_NEW_STATION) * * @NL80211_ATTR_SCAN_FLAGS: scan request control flags (u32) * * @NL80211_ATTR_P2P_CTWINDOW: P2P GO Client Traffic Window (u8), used with * the START_AP and SET_BSS commands * @NL80211_ATTR_P2P_OPPPS: P2P GO opportunistic PS (u8), used with the * START_AP and SET_BSS commands. This can have the values 0 or 1; * if not given in START_AP 0 is assumed, if not given in SET_BSS * no change is made. * * @NL80211_ATTR_LOCAL_MESH_POWER_MODE: local mesh STA link-specific power mode * defined in &enum nl80211_mesh_power_mode. * * @NL80211_ATTR_ACL_POLICY: ACL policy, see &enum nl80211_acl_policy, * carried in a u32 attribute * * @NL80211_ATTR_MAC_ADDRS: Array of nested MAC addresses, used for * MAC ACL. * * @NL80211_ATTR_MAC_ACL_MAX: u32 attribute to advertise the maximum * number of MAC addresses that a device can support for MAC * ACL. * * @NL80211_ATTR_RADAR_EVENT: Type of radar event for notification to userspace, * contains a value of enum nl80211_radar_event (u32). * * @NL80211_ATTR_EXT_CAPA: 802.11 extended capabilities that the kernel driver * has and handles. The format is the same as the IE contents. See * 802.11-2012 8.4.2.29 for more information. * @NL80211_ATTR_EXT_CAPA_MASK: Extended capabilities that the kernel driver * has set in the %NL80211_ATTR_EXT_CAPA value, for multibit fields. * * @NL80211_ATTR_STA_CAPABILITY: Station capabilities (u16) are advertised to * the driver, e.g., to enable TDLS power save (PU-APSD). * * @NL80211_ATTR_STA_EXT_CAPABILITY: Station extended capabilities are * advertised to the driver, e.g., to enable TDLS off channel operations * and PU-APSD. * * @NL80211_ATTR_PROTOCOL_FEATURES: global nl80211 feature flags, see * &enum nl80211_protocol_features, the attribute is a u32. * * @NL80211_ATTR_SPLIT_WIPHY_DUMP: flag attribute, userspace supports * receiving the data for a single wiphy split across multiple * messages, given with wiphy dump message * * @NL80211_ATTR_MDID: Mobility Domain Identifier * * @NL80211_ATTR_IE_RIC: Resource Information Container Information * Element * * @NL80211_ATTR_CRIT_PROT_ID: critical protocol identifier requiring increased * reliability, see &enum nl80211_crit_proto_id (u16). * @NL80211_ATTR_MAX_CRIT_PROT_DURATION: duration in milliseconds in which * the connection should have increased reliability (u16). * * @NL80211_ATTR_PEER_AID: Association ID for the peer TDLS station (u16). * This is similar to @NL80211_ATTR_STA_AID but with a difference of being * allowed to be used with the first @NL80211_CMD_SET_STATION command to * update a TDLS peer STA entry. * * @NL80211_ATTR_COALESCE_RULE: Coalesce rule information. * * @NL80211_ATTR_CH_SWITCH_COUNT: u32 attribute specifying the number of TBTT's * until the channel switch event. * @NL80211_ATTR_CH_SWITCH_BLOCK_TX: flag attribute specifying that transmission * must be blocked on the current channel (before the channel switch * operation). Also included in the channel switch started event if quiet * was requested by the AP. * @NL80211_ATTR_CSA_IES: Nested set of attributes containing the IE information * for the time while performing a channel switch. * @NL80211_ATTR_CNTDWN_OFFS_BEACON: An array of offsets (u16) to the channel * switch or color change counters in the beacons tail (%NL80211_ATTR_BEACON_TAIL). * @NL80211_ATTR_CNTDWN_OFFS_PRESP: An array of offsets (u16) to the channel * switch or color change counters in the probe response (%NL80211_ATTR_PROBE_RESP). * * @NL80211_ATTR_RXMGMT_FLAGS: flags for nl80211_send_mgmt(), u32. * As specified in the &enum nl80211_rxmgmt_flags. * * @NL80211_ATTR_STA_SUPPORTED_CHANNELS: array of supported channels. * * @NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES: array of supported * operating classes. * * @NL80211_ATTR_HANDLE_DFS: A flag indicating whether user space * controls DFS operation in IBSS mode. If the flag is included in * %NL80211_CMD_JOIN_IBSS request, the driver will allow use of DFS * channels and reports radar events to userspace. Userspace is required * to react to radar events, e.g. initiate a channel switch or leave the * IBSS network. * * @NL80211_ATTR_SUPPORT_5_MHZ: A flag indicating that the device supports * 5 MHz channel bandwidth. * @NL80211_ATTR_SUPPORT_10_MHZ: A flag indicating that the device supports * 10 MHz channel bandwidth. * * @NL80211_ATTR_OPMODE_NOTIF: Operating mode field from Operating Mode * Notification Element based on association request when used with * %NL80211_CMD_NEW_STATION or %NL80211_CMD_SET_STATION (only when * %NL80211_FEATURE_FULL_AP_CLIENT_STATE is supported, or with TDLS); * u8 attribute. * * @NL80211_ATTR_VENDOR_ID: The vendor ID, either a 24-bit OUI or, if * %NL80211_VENDOR_ID_IS_LINUX is set, a special Linux ID (not used yet) * @NL80211_ATTR_VENDOR_SUBCMD: vendor sub-command * @NL80211_ATTR_VENDOR_DATA: data for the vendor command, if any; this * attribute is also used for vendor command feature advertisement * @NL80211_ATTR_VENDOR_EVENTS: used for event list advertising in the wiphy * info, containing a nested array of possible events * * @NL80211_ATTR_QOS_MAP: IP DSCP mapping for Interworking QoS mapping. This * data is in the format defined for the payload of the QoS Map Set element * in IEEE Std 802.11-2012, 8.4.2.97. * * @NL80211_ATTR_MAC_HINT: MAC address recommendation as initial BSS * @NL80211_ATTR_WIPHY_FREQ_HINT: frequency of the recommended initial BSS * * @NL80211_ATTR_MAX_AP_ASSOC_STA: Device attribute that indicates how many * associated stations are supported in AP mode (including P2P GO); u32. * Since drivers may not have a fixed limit on the maximum number (e.g., * other concurrent operations may affect this), drivers are allowed to * advertise values that cannot always be met. In such cases, an attempt * to add a new station entry with @NL80211_CMD_NEW_STATION may fail. * * @NL80211_ATTR_CSA_C_OFFSETS_TX: An array of csa counter offsets (u16) which * should be updated when the frame is transmitted. * @NL80211_ATTR_MAX_CSA_COUNTERS: U8 attribute used to advertise the maximum * supported number of csa counters. * * @NL80211_ATTR_TDLS_PEER_CAPABILITY: flags for TDLS peer capabilities, u32. * As specified in the &enum nl80211_tdls_peer_capability. * * @NL80211_ATTR_SOCKET_OWNER: Flag attribute, if set during interface * creation then the new interface will be owned by the netlink socket * that created it and will be destroyed when the socket is closed. * If set during scheduled scan start then the new scan req will be * owned by the netlink socket that created it and the scheduled scan will * be stopped when the socket is closed. * If set during configuration of regulatory indoor operation then the * regulatory indoor configuration would be owned by the netlink socket * that configured the indoor setting, and the indoor operation would be * cleared when the socket is closed. * If set during NAN interface creation, the interface will be destroyed * if the socket is closed just like any other interface. Moreover, NAN * notifications will be sent in unicast to that socket. Without this * attribute, the notifications will be sent to the %NL80211_MCGRP_NAN * multicast group. * If set during %NL80211_CMD_ASSOCIATE or %NL80211_CMD_CONNECT the * station will deauthenticate when the socket is closed. * If set during %NL80211_CMD_JOIN_IBSS the IBSS will be automatically * torn down when the socket is closed. * If set during %NL80211_CMD_JOIN_MESH the mesh setup will be * automatically torn down when the socket is closed. * If set during %NL80211_CMD_START_AP the AP will be automatically * disabled when the socket is closed. * * @NL80211_ATTR_TDLS_INITIATOR: flag attribute indicating the current end is * the TDLS link initiator. * * @NL80211_ATTR_USE_RRM: flag for indicating whether the current connection * shall support Radio Resource Measurements (11k). This attribute can be * used with %NL80211_CMD_ASSOCIATE and %NL80211_CMD_CONNECT requests. * User space applications are expected to use this flag only if the * underlying device supports these minimal RRM features: * %NL80211_FEATURE_DS_PARAM_SET_IE_IN_PROBES, * %NL80211_FEATURE_QUIET, * Or, if global RRM is supported, see: * %NL80211_EXT_FEATURE_RRM * If this flag is used, driver must add the Power Capabilities IE to the * association request. In addition, it must also set the RRM capability * flag in the association request's Capability Info field. * * @NL80211_ATTR_WIPHY_DYN_ACK: flag attribute used to enable ACK timeout * estimation algorithm (dynack). In order to activate dynack * %NL80211_FEATURE_ACKTO_ESTIMATION feature flag must be set by lower * drivers to indicate dynack capability. Dynack is automatically disabled * setting valid value for coverage class. * * @NL80211_ATTR_TSID: a TSID value (u8 attribute) * @NL80211_ATTR_USER_PRIO: user priority value (u8 attribute) * @NL80211_ATTR_ADMITTED_TIME: admitted time in units of 32 microseconds * (per second) (u16 attribute) * * @NL80211_ATTR_SMPS_MODE: SMPS mode to use (ap mode). see * &enum nl80211_smps_mode. * * @NL80211_ATTR_OPER_CLASS: operating class * * @NL80211_ATTR_MAC_MASK: MAC address mask * * @NL80211_ATTR_WIPHY_SELF_MANAGED_REG: flag attribute indicating this device * is self-managing its regulatory information and any regulatory domain * obtained from it is coming from the device's wiphy and not the global * cfg80211 regdomain. * * @NL80211_ATTR_EXT_FEATURES: extended feature flags contained in a byte * array. The feature flags are identified by their bit index (see &enum * nl80211_ext_feature_index). The bit index is ordered starting at the * least-significant bit of the first byte in the array, ie. bit index 0 * is located at bit 0 of byte 0. bit index 25 would be located at bit 1 * of byte 3 (u8 array). * * @NL80211_ATTR_SURVEY_RADIO_STATS: Request overall radio statistics to be * returned along with other survey data. If set, @NL80211_CMD_GET_SURVEY * may return a survey entry without a channel indicating global radio * statistics (only some values are valid and make sense.) * For devices that don't return such an entry even then, the information * should be contained in the result as the sum of the respective counters * over all channels. * * @NL80211_ATTR_SCHED_SCAN_DELAY: delay before the first cycle of a * scheduled scan is started. Or the delay before a WoWLAN * net-detect scan is started, counting from the moment the * system is suspended. This value is a u32, in seconds. * @NL80211_ATTR_REG_INDOOR: flag attribute, if set indicates that the device * is operating in an indoor environment. * * @NL80211_ATTR_MAX_NUM_SCHED_SCAN_PLANS: maximum number of scan plans for * scheduled scan supported by the device (u32), a wiphy attribute. * @NL80211_ATTR_MAX_SCAN_PLAN_INTERVAL: maximum interval (in seconds) for * a scan plan (u32), a wiphy attribute. * @NL80211_ATTR_MAX_SCAN_PLAN_ITERATIONS: maximum number of iterations in * a scan plan (u32), a wiphy attribute. * @NL80211_ATTR_SCHED_SCAN_PLANS: a list of scan plans for scheduled scan. * Each scan plan defines the number of scan iterations and the interval * between scans. The last scan plan will always run infinitely, * thus it must not specify the number of iterations, only the interval * between scans. The scan plans are executed sequentially. * Each scan plan is a nested attribute of &enum nl80211_sched_scan_plan. * @NL80211_ATTR_PBSS: flag attribute. If set it means operate * in a PBSS. Specified in %NL80211_CMD_CONNECT to request * connecting to a PCP, and in %NL80211_CMD_START_AP to start * a PCP instead of AP. Relevant for DMG networks only. * @NL80211_ATTR_BSS_SELECT: nested attribute for driver supporting the * BSS selection feature. When used with %NL80211_CMD_GET_WIPHY it contains * attributes according &enum nl80211_bss_select_attr to indicate what * BSS selection behaviours are supported. When used with %NL80211_CMD_CONNECT * it contains the behaviour-specific attribute containing the parameters for * BSS selection to be done by driver and/or firmware. * * @NL80211_ATTR_STA_SUPPORT_P2P_PS: whether P2P PS mechanism supported * or not. u8, one of the values of &enum nl80211_sta_p2p_ps_status * * @NL80211_ATTR_PAD: attribute used for padding for 64-bit alignment * * @NL80211_ATTR_IFTYPE_EXT_CAPA: Nested attribute of the following attributes: * %NL80211_ATTR_IFTYPE, %NL80211_ATTR_EXT_CAPA, * %NL80211_ATTR_EXT_CAPA_MASK, to specify the extended capabilities and * other interface-type specific capabilities per interface type. For MLO, * %NL80211_ATTR_EML_CAPABILITY and %NL80211_ATTR_MLD_CAPA_AND_OPS are * present. * * @NL80211_ATTR_MU_MIMO_GROUP_DATA: array of 24 bytes that defines a MU-MIMO * groupID for monitor mode. * The first 8 bytes are a mask that defines the membership in each * group (there are 64 groups, group 0 and 63 are reserved), * each bit represents a group and set to 1 for being a member in * that group and 0 for not being a member. * The remaining 16 bytes define the position in each group: 2 bits for * each group. * (smaller group numbers represented on most significant bits and bigger * group numbers on least significant bits.) * This attribute is used only if all interfaces are in monitor mode. * Set this attribute in order to monitor packets using the given MU-MIMO * groupID data. * to turn off that feature set all the bits of the groupID to zero. * @NL80211_ATTR_MU_MIMO_FOLLOW_MAC_ADDR: mac address for the sniffer to follow * when using MU-MIMO air sniffer. * to turn that feature off set an invalid mac address * (e.g. FF:FF:FF:FF:FF:FF) * * @NL80211_ATTR_SCAN_START_TIME_TSF: The time at which the scan was actually * started (u64). The time is the TSF of the BSS the interface that * requested the scan is connected to (if available, otherwise this * attribute must not be included). * @NL80211_ATTR_SCAN_START_TIME_TSF_BSSID: The BSS according to which * %NL80211_ATTR_SCAN_START_TIME_TSF is set. * @NL80211_ATTR_MEASUREMENT_DURATION: measurement duration in TUs (u16). If * %NL80211_ATTR_MEASUREMENT_DURATION_MANDATORY is not set, this is the * maximum measurement duration allowed. This attribute is used with * measurement requests. It can also be used with %NL80211_CMD_TRIGGER_SCAN * if the scan is used for beacon report radio measurement. * @NL80211_ATTR_MEASUREMENT_DURATION_MANDATORY: flag attribute that indicates * that the duration specified with %NL80211_ATTR_MEASUREMENT_DURATION is * mandatory. If this flag is not set, the duration is the maximum duration * and the actual measurement duration may be shorter. * * @NL80211_ATTR_MESH_PEER_AID: Association ID for the mesh peer (u16). This is * used to pull the stored data for mesh peer in power save state. * * @NL80211_ATTR_NAN_MASTER_PREF: the master preference to be used by * %NL80211_CMD_START_NAN and optionally with * %NL80211_CMD_CHANGE_NAN_CONFIG. Its type is u8 and it can't be 0. * Also, values 1 and 255 are reserved for certification purposes and * should not be used during a normal device operation. * @NL80211_ATTR_BANDS: operating bands configuration. This is a u32 * bitmask of BIT(NL80211_BAND_*) as described in %enum * nl80211_band. For instance, for NL80211_BAND_2GHZ, bit 0 * would be set. This attribute is used with * %NL80211_CMD_START_NAN and %NL80211_CMD_CHANGE_NAN_CONFIG, and * it is optional. If no bands are set, it means don't-care and * the device will decide what to use. * @NL80211_ATTR_NAN_FUNC: a function that can be added to NAN. See * &enum nl80211_nan_func_attributes for description of this nested * attribute. * @NL80211_ATTR_NAN_MATCH: used to report a match. This is a nested attribute. * See &enum nl80211_nan_match_attributes. * @NL80211_ATTR_FILS_KEK: KEK for FILS (Re)Association Request/Response frame * protection. * @NL80211_ATTR_FILS_NONCES: Nonces (part of AAD) for FILS (Re)Association * Request/Response frame protection. This attribute contains the 16 octet * STA Nonce followed by 16 octets of AP Nonce. * * @NL80211_ATTR_MULTICAST_TO_UNICAST_ENABLED: Indicates whether or not multicast * packets should be send out as unicast to all stations (flag attribute). * * @NL80211_ATTR_BSSID: The BSSID of the AP. Note that %NL80211_ATTR_MAC is also * used in various commands/events for specifying the BSSID. * * @NL80211_ATTR_SCHED_SCAN_RELATIVE_RSSI: Relative RSSI threshold by which * other BSSs has to be better or slightly worse than the current * connected BSS so that they get reported to user space. * This will give an opportunity to userspace to consider connecting to * other matching BSSs which have better or slightly worse RSSI than * the current connected BSS by using an offloaded operation to avoid * unnecessary wakeups. * * @NL80211_ATTR_SCHED_SCAN_RSSI_ADJUST: When present the RSSI level for BSSs in * the specified band is to be adjusted before doing * %NL80211_ATTR_SCHED_SCAN_RELATIVE_RSSI based comparison to figure out * better BSSs. The attribute value is a packed structure * value as specified by &struct nl80211_bss_select_rssi_adjust. * * @NL80211_ATTR_TIMEOUT_REASON: The reason for which an operation timed out. * u32 attribute with an &enum nl80211_timeout_reason value. This is used, * e.g., with %NL80211_CMD_CONNECT event. * * @NL80211_ATTR_FILS_ERP_USERNAME: EAP Re-authentication Protocol (ERP) * username part of NAI used to refer keys rRK and rIK. This is used with * %NL80211_CMD_CONNECT. * * @NL80211_ATTR_FILS_ERP_REALM: EAP Re-authentication Protocol (ERP) realm part * of NAI specifying the domain name of the ER server. This is used with * %NL80211_CMD_CONNECT. * * @NL80211_ATTR_FILS_ERP_NEXT_SEQ_NUM: Unsigned 16-bit ERP next sequence number * to use in ERP messages. This is used in generating the FILS wrapped data * for FILS authentication and is used with %NL80211_CMD_CONNECT. * * @NL80211_ATTR_FILS_ERP_RRK: ERP re-authentication Root Key (rRK) for the * NAI specified by %NL80211_ATTR_FILS_ERP_USERNAME and * %NL80211_ATTR_FILS_ERP_REALM. This is used for generating rIK and rMSK * from successful FILS authentication and is used with * %NL80211_CMD_CONNECT. * * @NL80211_ATTR_FILS_CACHE_ID: A 2-octet identifier advertized by a FILS AP * identifying the scope of PMKSAs. This is used with * @NL80211_CMD_SET_PMKSA and @NL80211_CMD_DEL_PMKSA. * * @NL80211_ATTR_PMK: attribute for passing PMK key material. Used with * %NL80211_CMD_SET_PMKSA for the PMKSA identified by %NL80211_ATTR_PMKID. * For %NL80211_CMD_CONNECT and %NL80211_CMD_START_AP it is used to provide * PSK for offloading 4-way handshake for WPA/WPA2-PSK networks. For 802.1X * authentication it is used with %NL80211_CMD_SET_PMK. For offloaded FT * support this attribute specifies the PMK-R0 if NL80211_ATTR_PMKR0_NAME * is included as well. * * @NL80211_ATTR_SCHED_SCAN_MULTI: flag attribute which user-space shall use to * indicate that it supports multiple active scheduled scan requests. * @NL80211_ATTR_SCHED_SCAN_MAX_REQS: indicates maximum number of scheduled * scan request that may be active for the device (u32). * * @NL80211_ATTR_WANT_1X_4WAY_HS: flag attribute which user-space can include * in %NL80211_CMD_CONNECT to indicate that for 802.1X authentication it * wants to use the supported offload of the 4-way handshake. * @NL80211_ATTR_PMKR0_NAME: PMK-R0 Name for offloaded FT. * @NL80211_ATTR_PORT_AUTHORIZED: (reserved) * * @NL80211_ATTR_EXTERNAL_AUTH_ACTION: Identify the requested external * authentication operation (u32 attribute with an * &enum nl80211_external_auth_action value). This is used with the * %NL80211_CMD_EXTERNAL_AUTH request event. * @NL80211_ATTR_EXTERNAL_AUTH_SUPPORT: Flag attribute indicating that the user * space supports external authentication. This attribute shall be used * with %NL80211_CMD_CONNECT and %NL80211_CMD_START_AP request. The driver * may offload authentication processing to user space if this capability * is indicated in the respective requests from the user space. (This flag * attribute deprecated for %NL80211_CMD_START_AP, use * %NL80211_ATTR_AP_SETTINGS_FLAGS) * * @NL80211_ATTR_NSS: Station's New/updated RX_NSS value notified using this * u8 attribute. This is used with %NL80211_CMD_STA_OPMODE_CHANGED. * * @NL80211_ATTR_TXQ_STATS: TXQ statistics (nested attribute, see &enum * nl80211_txq_stats) * @NL80211_ATTR_TXQ_LIMIT: Total packet limit for the TXQ queues for this phy. * The smaller of this and the memory limit is enforced. * @NL80211_ATTR_TXQ_MEMORY_LIMIT: Total memory limit (in bytes) for the * TXQ queues for this phy. The smaller of this and the packet limit is * enforced. * @NL80211_ATTR_TXQ_QUANTUM: TXQ scheduler quantum (bytes). Number of bytes * a flow is assigned on each round of the DRR scheduler. * @NL80211_ATTR_HE_CAPABILITY: HE Capability information element (from * association request when used with NL80211_CMD_NEW_STATION). Can be set * only if %NL80211_STA_FLAG_WME is set. * * @NL80211_ATTR_FTM_RESPONDER: nested attribute which user-space can include * in %NL80211_CMD_START_AP or %NL80211_CMD_SET_BEACON for fine timing * measurement (FTM) responder functionality and containing parameters as * possible, see &enum nl80211_ftm_responder_attr * * @NL80211_ATTR_FTM_RESPONDER_STATS: Nested attribute with FTM responder * statistics, see &enum nl80211_ftm_responder_stats. * * @NL80211_ATTR_TIMEOUT: Timeout for the given operation in milliseconds (u32), * if the attribute is not given no timeout is requested. Note that 0 is an * invalid value. * * @NL80211_ATTR_PEER_MEASUREMENTS: peer measurements request (and result) * data, uses nested attributes specified in * &enum nl80211_peer_measurement_attrs. * This is also used for capability advertisement in the wiphy information, * with the appropriate sub-attributes. * * @NL80211_ATTR_AIRTIME_WEIGHT: Station's weight when scheduled by the airtime * scheduler. * * @NL80211_ATTR_STA_TX_POWER_SETTING: Transmit power setting type (u8) for * station associated with the AP. See &enum nl80211_tx_power_setting for * possible values. * @NL80211_ATTR_STA_TX_POWER: Transmit power level (s16) in dBm units. This * allows to set Tx power for a station. If this attribute is not included, * the default per-interface tx power setting will be overriding. Driver * should be picking up the lowest tx power, either tx power per-interface * or per-station. * * @NL80211_ATTR_SAE_PASSWORD: attribute for passing SAE password material. It * is used with %NL80211_CMD_CONNECT to provide password for offloading * SAE authentication for WPA3-Personal networks. * * @NL80211_ATTR_TWT_RESPONDER: Enable target wait time responder support. * * @NL80211_ATTR_HE_OBSS_PD: nested attribute for OBSS Packet Detection * functionality. * * @NL80211_ATTR_WIPHY_EDMG_CHANNELS: bitmap that indicates the 2.16 GHz * channel(s) that are allowed to be used for EDMG transmissions. * Defined by IEEE P802.11ay/D4.0 section 9.4.2.251. (u8 attribute) * @NL80211_ATTR_WIPHY_EDMG_BW_CONFIG: Channel BW Configuration subfield encodes * the allowed channel bandwidth configurations. (u8 attribute) * Defined by IEEE P802.11ay/D4.0 section 9.4.2.251, Table 13. * * @NL80211_ATTR_VLAN_ID: VLAN ID (1..4094) for the station and VLAN group key * (u16). * * @NL80211_ATTR_HE_BSS_COLOR: nested attribute for BSS Color Settings. * * @NL80211_ATTR_IFTYPE_AKM_SUITES: nested array attribute, with each entry * using attributes from &enum nl80211_iftype_akm_attributes. This * attribute is sent in a response to %NL80211_CMD_GET_WIPHY indicating * supported AKM suites capability per interface. AKMs advertised in * %NL80211_ATTR_AKM_SUITES are default capabilities if AKM suites not * advertised for a specific interface type. * * @NL80211_ATTR_TID_CONFIG: TID specific configuration in a * nested attribute with &enum nl80211_tid_config_attr sub-attributes; * on output (in wiphy attributes) it contains only the feature sub- * attributes. * * @NL80211_ATTR_CONTROL_PORT_NO_PREAUTH: disable preauth frame rx on control * port in order to forward/receive them as ordinary data frames. * * @NL80211_ATTR_PMK_LIFETIME: Maximum lifetime for PMKSA in seconds (u32, * dot11RSNAConfigPMKReauthThreshold; 0 is not a valid value). * An optional parameter configured through %NL80211_CMD_SET_PMKSA. * Drivers that trigger roaming need to know the lifetime of the * configured PMKSA for triggering the full vs. PMKSA caching based * authentication. This timeout helps authentication methods like SAE, * where PMK gets updated only by going through a full (new SAE) * authentication instead of getting updated during an association for EAP * authentication. No new full authentication within the PMK expiry shall * result in a disassociation at the end of the lifetime. * * @NL80211_ATTR_PMK_REAUTH_THRESHOLD: Reauthentication threshold time, in * terms of percentage of %NL80211_ATTR_PMK_LIFETIME * (u8, dot11RSNAConfigPMKReauthThreshold, 1..100). This is an optional * parameter configured through %NL80211_CMD_SET_PMKSA. Requests the * driver to trigger a full authentication roam (without PMKSA caching) * after the reauthentication threshold time, but before the PMK lifetime * has expired. * * Authentication methods like SAE need to be able to generate a new PMKSA * entry without having to force a disconnection after the PMK timeout. If * no roaming occurs between the reauth threshold and PMK expiration, * disassociation is still forced. * @NL80211_ATTR_RECEIVE_MULTICAST: multicast flag for the * %NL80211_CMD_REGISTER_FRAME command, see the description there. * @NL80211_ATTR_WIPHY_FREQ_OFFSET: offset of the associated * %NL80211_ATTR_WIPHY_FREQ in positive KHz. Only valid when supplied with * an %NL80211_ATTR_WIPHY_FREQ_OFFSET. * @NL80211_ATTR_CENTER_FREQ1_OFFSET: Center frequency offset in KHz for the * first channel segment specified in %NL80211_ATTR_CENTER_FREQ1. * @NL80211_ATTR_SCAN_FREQ_KHZ: nested attribute with KHz frequencies * * @NL80211_ATTR_HE_6GHZ_CAPABILITY: HE 6 GHz Band Capability element (from * association request when used with NL80211_CMD_NEW_STATION). * * @NL80211_ATTR_FILS_DISCOVERY: Optional parameter to configure FILS * discovery. It is a nested attribute, see * &enum nl80211_fils_discovery_attributes. * * @NL80211_ATTR_UNSOL_BCAST_PROBE_RESP: Optional parameter to configure * unsolicited broadcast probe response. It is a nested attribute, see * &enum nl80211_unsol_bcast_probe_resp_attributes. * * @NL80211_ATTR_S1G_CAPABILITY: S1G Capability information element (from * association request when used with NL80211_CMD_NEW_STATION) * @NL80211_ATTR_S1G_CAPABILITY_MASK: S1G Capability Information element * override mask. Used with NL80211_ATTR_S1G_CAPABILITY in * NL80211_CMD_ASSOCIATE or NL80211_CMD_CONNECT. * * @NL80211_ATTR_SAE_PWE: Indicates the mechanism(s) allowed for SAE PWE * derivation in WPA3-Personal networks which are using SAE authentication. * This is a u8 attribute that encapsulates one of the values from * &enum nl80211_sae_pwe_mechanism. * * @NL80211_ATTR_SAR_SPEC: SAR power limitation specification when * used with %NL80211_CMD_SET_SAR_SPECS. The message contains fields * of %nl80211_sar_attrs which specifies the sar type and related * sar specs. Sar specs contains array of %nl80211_sar_specs_attrs. * * @NL80211_ATTR_RECONNECT_REQUESTED: flag attribute, used with deauth and * disassoc events to indicate that an immediate reconnect to the AP * is desired. * * @NL80211_ATTR_OBSS_COLOR_BITMAP: bitmap of the u64 BSS colors for the * %NL80211_CMD_OBSS_COLOR_COLLISION event. * * @NL80211_ATTR_COLOR_CHANGE_COUNT: u8 attribute specifying the number of TBTT's * until the color switch event. * @NL80211_ATTR_COLOR_CHANGE_COLOR: u8 attribute specifying the color that we are * switching to * @NL80211_ATTR_COLOR_CHANGE_ELEMS: Nested set of attributes containing the IE * information for the time while performing a color switch. * * @NL80211_ATTR_MBSSID_CONFIG: Nested attribute for multiple BSSID * advertisements (MBSSID) parameters in AP mode. * Kernel uses this attribute to indicate the driver's support for MBSSID * and enhanced multi-BSSID advertisements (EMA AP) to the userspace. * Userspace should use this attribute to configure per interface MBSSID * parameters. * See &enum nl80211_mbssid_config_attributes for details. * * @NL80211_ATTR_MBSSID_ELEMS: Nested parameter to pass multiple BSSID elements. * Mandatory parameter for the transmitting interface to enable MBSSID. * Optional for the non-transmitting interfaces. * * @NL80211_ATTR_RADAR_BACKGROUND: Configure dedicated offchannel chain * available for radar/CAC detection on some hw. This chain can't be used * to transmit or receive frames and it is bounded to a running wdev. * Background radar/CAC detection allows to avoid the CAC downtime * switching on a different channel during CAC detection on the selected * radar channel. * * @NL80211_ATTR_AP_SETTINGS_FLAGS: u32 attribute contains ap settings flags, * enumerated in &enum nl80211_ap_settings_flags. This attribute shall be * used with %NL80211_CMD_START_AP request. * * @NL80211_ATTR_EHT_CAPABILITY: EHT Capability information element (from * association request when used with NL80211_CMD_NEW_STATION). Can be set * only if %NL80211_STA_FLAG_WME is set. * * @NL80211_ATTR_MLO_LINK_ID: A (u8) link ID for use with MLO, to be used with * various commands that need a link ID to operate. * @NL80211_ATTR_MLO_LINKS: A nested array of links, each containing some * per-link information and a link ID. * @NL80211_ATTR_MLD_ADDR: An MLD address, used with various commands such as * authenticate/associate. * * @NL80211_ATTR_MLO_SUPPORT: Flag attribute to indicate user space supports MLO * connection. Used with %NL80211_CMD_CONNECT. If this attribute is not * included in NL80211_CMD_CONNECT drivers must not perform MLO connection. * * @NL80211_ATTR_MAX_NUM_AKM_SUITES: U16 attribute. Indicates maximum number of * AKM suites allowed for %NL80211_CMD_CONNECT, %NL80211_CMD_ASSOCIATE and * %NL80211_CMD_START_AP in %NL80211_CMD_GET_WIPHY response. If this * attribute is not present userspace shall consider maximum number of AKM * suites allowed as %NL80211_MAX_NR_AKM_SUITES which is the legacy maximum * number prior to the introduction of this attribute. * * @NL80211_ATTR_EML_CAPABILITY: EML Capability information (u16) * @NL80211_ATTR_MLD_CAPA_AND_OPS: MLD Capabilities and Operations (u16) * * @NL80211_ATTR_TX_HW_TIMESTAMP: Hardware timestamp for TX operation in * nanoseconds (u64). This is the device clock timestamp so it will * probably reset when the device is stopped or the firmware is reset. * When used with %NL80211_CMD_FRAME_TX_STATUS, indicates the frame TX * timestamp. When used with %NL80211_CMD_FRAME RX notification, indicates * the ack TX timestamp. * @NL80211_ATTR_RX_HW_TIMESTAMP: Hardware timestamp for RX operation in * nanoseconds (u64). This is the device clock timestamp so it will * probably reset when the device is stopped or the firmware is reset. * When used with %NL80211_CMD_FRAME_TX_STATUS, indicates the ack RX * timestamp. When used with %NL80211_CMD_FRAME RX notification, indicates * the incoming frame RX timestamp. * @NL80211_ATTR_TD_BITMAP: Transition Disable bitmap, for subsequent * (re)associations. * * @NL80211_ATTR_PUNCT_BITMAP: (u32) Preamble puncturing bitmap, lowest * bit corresponds to the lowest 20 MHz channel. Each bit set to 1 * indicates that the sub-channel is punctured. Higher 16 bits are * reserved. * * @NL80211_ATTR_MAX_HW_TIMESTAMP_PEERS: Maximum number of peers that HW * timestamping can be enabled for concurrently (u16), a wiphy attribute. * A value of 0xffff indicates setting for all peers (i.e. not specifying * an address with %NL80211_CMD_SET_HW_TIMESTAMP) is supported. * @NL80211_ATTR_HW_TIMESTAMP_ENABLED: Indicates whether HW timestamping should * be enabled or not (flag attribute). * * @NL80211_ATTR_EMA_RNR_ELEMS: Optional nested attribute for * reduced neighbor report (RNR) elements. This attribute can be used * only when NL80211_MBSSID_CONFIG_ATTR_EMA is enabled. * Userspace is responsible for splitting the RNR into multiple * elements such that each element excludes the non-transmitting * profiles already included in the MBSSID element * (%NL80211_ATTR_MBSSID_ELEMS) at the same index. Each EMA beacon * will be generated by adding MBSSID and RNR elements at the same * index. If the userspace includes more RNR elements than number of * MBSSID elements then these will be added in every EMA beacon. * * @NUM_NL80211_ATTR: total number of nl80211_attrs available * @NL80211_ATTR_MAX: highest attribute number currently defined * @__NL80211_ATTR_AFTER_LAST: internal use */ enum nl80211_attrs { /* don't change the order or add anything between, this is ABI! */ NL80211_ATTR_UNSPEC, NL80211_ATTR_WIPHY, NL80211_ATTR_WIPHY_NAME, NL80211_ATTR_IFINDEX, NL80211_ATTR_IFNAME, NL80211_ATTR_IFTYPE, NL80211_ATTR_MAC, NL80211_ATTR_KEY_DATA, NL80211_ATTR_KEY_IDX, NL80211_ATTR_KEY_CIPHER, NL80211_ATTR_KEY_SEQ, NL80211_ATTR_KEY_DEFAULT, NL80211_ATTR_BEACON_INTERVAL, NL80211_ATTR_DTIM_PERIOD, NL80211_ATTR_BEACON_HEAD, NL80211_ATTR_BEACON_TAIL, NL80211_ATTR_STA_AID, NL80211_ATTR_STA_FLAGS, NL80211_ATTR_STA_LISTEN_INTERVAL, NL80211_ATTR_STA_SUPPORTED_RATES, NL80211_ATTR_STA_VLAN, NL80211_ATTR_STA_INFO, NL80211_ATTR_WIPHY_BANDS, NL80211_ATTR_MNTR_FLAGS, NL80211_ATTR_MESH_ID, NL80211_ATTR_STA_PLINK_ACTION, NL80211_ATTR_MPATH_NEXT_HOP, NL80211_ATTR_MPATH_INFO, NL80211_ATTR_BSS_CTS_PROT, NL80211_ATTR_BSS_SHORT_PREAMBLE, NL80211_ATTR_BSS_SHORT_SLOT_TIME, NL80211_ATTR_HT_CAPABILITY, NL80211_ATTR_SUPPORTED_IFTYPES, NL80211_ATTR_REG_ALPHA2, NL80211_ATTR_REG_RULES, NL80211_ATTR_MESH_CONFIG, NL80211_ATTR_BSS_BASIC_RATES, NL80211_ATTR_WIPHY_TXQ_PARAMS, NL80211_ATTR_WIPHY_FREQ, NL80211_ATTR_WIPHY_CHANNEL_TYPE, NL80211_ATTR_KEY_DEFAULT_MGMT, NL80211_ATTR_MGMT_SUBTYPE, NL80211_ATTR_IE, NL80211_ATTR_MAX_NUM_SCAN_SSIDS, NL80211_ATTR_SCAN_FREQUENCIES, NL80211_ATTR_SCAN_SSIDS, NL80211_ATTR_GENERATION, /* replaces old SCAN_GENERATION */ NL80211_ATTR_BSS, NL80211_ATTR_REG_INITIATOR, NL80211_ATTR_REG_TYPE, NL80211_ATTR_SUPPORTED_COMMANDS, NL80211_ATTR_FRAME, NL80211_ATTR_SSID, NL80211_ATTR_AUTH_TYPE, NL80211_ATTR_REASON_CODE, NL80211_ATTR_KEY_TYPE, NL80211_ATTR_MAX_SCAN_IE_LEN, NL80211_ATTR_CIPHER_SUITES, NL80211_ATTR_FREQ_BEFORE, NL80211_ATTR_FREQ_AFTER, NL80211_ATTR_FREQ_FIXED, NL80211_ATTR_WIPHY_RETRY_SHORT, NL80211_ATTR_WIPHY_RETRY_LONG, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, NL80211_ATTR_WIPHY_RTS_THRESHOLD, NL80211_ATTR_TIMED_OUT, NL80211_ATTR_USE_MFP, NL80211_ATTR_STA_FLAGS2, NL80211_ATTR_CONTROL_PORT, NL80211_ATTR_TESTDATA, NL80211_ATTR_PRIVACY, NL80211_ATTR_DISCONNECTED_BY_AP, NL80211_ATTR_STATUS_CODE, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, NL80211_ATTR_CIPHER_SUITE_GROUP, NL80211_ATTR_WPA_VERSIONS, NL80211_ATTR_AKM_SUITES, NL80211_ATTR_REQ_IE, NL80211_ATTR_RESP_IE, NL80211_ATTR_PREV_BSSID, NL80211_ATTR_KEY, NL80211_ATTR_KEYS, NL80211_ATTR_PID, NL80211_ATTR_4ADDR, NL80211_ATTR_SURVEY_INFO, NL80211_ATTR_PMKID, NL80211_ATTR_MAX_NUM_PMKIDS, NL80211_ATTR_DURATION, NL80211_ATTR_COOKIE, NL80211_ATTR_WIPHY_COVERAGE_CLASS, NL80211_ATTR_TX_RATES, NL80211_ATTR_FRAME_MATCH, NL80211_ATTR_ACK, NL80211_ATTR_PS_STATE, NL80211_ATTR_CQM, NL80211_ATTR_LOCAL_STATE_CHANGE, NL80211_ATTR_AP_ISOLATE, NL80211_ATTR_WIPHY_TX_POWER_SETTING, NL80211_ATTR_WIPHY_TX_POWER_LEVEL, NL80211_ATTR_TX_FRAME_TYPES, NL80211_ATTR_RX_FRAME_TYPES, NL80211_ATTR_FRAME_TYPE, NL80211_ATTR_CONTROL_PORT_ETHERTYPE, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT, NL80211_ATTR_SUPPORT_IBSS_RSN, NL80211_ATTR_WIPHY_ANTENNA_TX, NL80211_ATTR_WIPHY_ANTENNA_RX, NL80211_ATTR_MCAST_RATE, NL80211_ATTR_OFFCHANNEL_TX_OK, NL80211_ATTR_BSS_HT_OPMODE, NL80211_ATTR_KEY_DEFAULT_TYPES, NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION, NL80211_ATTR_MESH_SETUP, NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX, NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX, NL80211_ATTR_SUPPORT_MESH_AUTH, NL80211_ATTR_STA_PLINK_STATE, NL80211_ATTR_WOWLAN_TRIGGERS, NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED, NL80211_ATTR_SCHED_SCAN_INTERVAL, NL80211_ATTR_INTERFACE_COMBINATIONS, NL80211_ATTR_SOFTWARE_IFTYPES, NL80211_ATTR_REKEY_DATA, NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS, NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN, NL80211_ATTR_SCAN_SUPP_RATES, NL80211_ATTR_HIDDEN_SSID, NL80211_ATTR_IE_PROBE_RESP, NL80211_ATTR_IE_ASSOC_RESP, NL80211_ATTR_STA_WME, NL80211_ATTR_SUPPORT_AP_UAPSD, NL80211_ATTR_ROAM_SUPPORT, NL80211_ATTR_SCHED_SCAN_MATCH, NL80211_ATTR_MAX_MATCH_SETS, NL80211_ATTR_PMKSA_CANDIDATE, NL80211_ATTR_TX_NO_CCK_RATE, NL80211_ATTR_TDLS_ACTION, NL80211_ATTR_TDLS_DIALOG_TOKEN, NL80211_ATTR_TDLS_OPERATION, NL80211_ATTR_TDLS_SUPPORT, NL80211_ATTR_TDLS_EXTERNAL_SETUP, NL80211_ATTR_DEVICE_AP_SME, NL80211_ATTR_DONT_WAIT_FOR_ACK, NL80211_ATTR_FEATURE_FLAGS, NL80211_ATTR_PROBE_RESP_OFFLOAD, NL80211_ATTR_PROBE_RESP, NL80211_ATTR_DFS_REGION, NL80211_ATTR_DISABLE_HT, NL80211_ATTR_HT_CAPABILITY_MASK, NL80211_ATTR_NOACK_MAP, NL80211_ATTR_INACTIVITY_TIMEOUT, NL80211_ATTR_RX_SIGNAL_DBM, NL80211_ATTR_BG_SCAN_PERIOD, NL80211_ATTR_WDEV, NL80211_ATTR_USER_REG_HINT_TYPE, NL80211_ATTR_CONN_FAILED_REASON, NL80211_ATTR_AUTH_DATA, NL80211_ATTR_VHT_CAPABILITY, NL80211_ATTR_SCAN_FLAGS, NL80211_ATTR_CHANNEL_WIDTH, NL80211_ATTR_CENTER_FREQ1, NL80211_ATTR_CENTER_FREQ2, NL80211_ATTR_P2P_CTWINDOW, NL80211_ATTR_P2P_OPPPS, NL80211_ATTR_LOCAL_MESH_POWER_MODE, NL80211_ATTR_ACL_POLICY, NL80211_ATTR_MAC_ADDRS, NL80211_ATTR_MAC_ACL_MAX, NL80211_ATTR_RADAR_EVENT, NL80211_ATTR_EXT_CAPA, NL80211_ATTR_EXT_CAPA_MASK, NL80211_ATTR_STA_CAPABILITY, NL80211_ATTR_STA_EXT_CAPABILITY, NL80211_ATTR_PROTOCOL_FEATURES, NL80211_ATTR_SPLIT_WIPHY_DUMP, NL80211_ATTR_DISABLE_VHT, NL80211_ATTR_VHT_CAPABILITY_MASK, NL80211_ATTR_MDID, NL80211_ATTR_IE_RIC, NL80211_ATTR_CRIT_PROT_ID, NL80211_ATTR_MAX_CRIT_PROT_DURATION, NL80211_ATTR_PEER_AID, NL80211_ATTR_COALESCE_RULE, NL80211_ATTR_CH_SWITCH_COUNT, NL80211_ATTR_CH_SWITCH_BLOCK_TX, NL80211_ATTR_CSA_IES, NL80211_ATTR_CNTDWN_OFFS_BEACON, NL80211_ATTR_CNTDWN_OFFS_PRESP, NL80211_ATTR_RXMGMT_FLAGS, NL80211_ATTR_STA_SUPPORTED_CHANNELS, NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES, NL80211_ATTR_HANDLE_DFS, NL80211_ATTR_SUPPORT_5_MHZ, NL80211_ATTR_SUPPORT_10_MHZ, NL80211_ATTR_OPMODE_NOTIF, NL80211_ATTR_VENDOR_ID, NL80211_ATTR_VENDOR_SUBCMD, NL80211_ATTR_VENDOR_DATA, NL80211_ATTR_VENDOR_EVENTS, NL80211_ATTR_QOS_MAP, NL80211_ATTR_MAC_HINT, NL80211_ATTR_WIPHY_FREQ_HINT, NL80211_ATTR_MAX_AP_ASSOC_STA, NL80211_ATTR_TDLS_PEER_CAPABILITY, NL80211_ATTR_SOCKET_OWNER, NL80211_ATTR_CSA_C_OFFSETS_TX, NL80211_ATTR_MAX_CSA_COUNTERS, NL80211_ATTR_TDLS_INITIATOR, NL80211_ATTR_USE_RRM, NL80211_ATTR_WIPHY_DYN_ACK, NL80211_ATTR_TSID, NL80211_ATTR_USER_PRIO, NL80211_ATTR_ADMITTED_TIME, NL80211_ATTR_SMPS_MODE, NL80211_ATTR_OPER_CLASS, NL80211_ATTR_MAC_MASK, NL80211_ATTR_WIPHY_SELF_MANAGED_REG, NL80211_ATTR_EXT_FEATURES, NL80211_ATTR_SURVEY_RADIO_STATS, NL80211_ATTR_NETNS_FD, NL80211_ATTR_SCHED_SCAN_DELAY, NL80211_ATTR_REG_INDOOR, NL80211_ATTR_MAX_NUM_SCHED_SCAN_PLANS, NL80211_ATTR_MAX_SCAN_PLAN_INTERVAL, NL80211_ATTR_MAX_SCAN_PLAN_ITERATIONS, NL80211_ATTR_SCHED_SCAN_PLANS, NL80211_ATTR_PBSS, NL80211_ATTR_BSS_SELECT, NL80211_ATTR_STA_SUPPORT_P2P_PS, NL80211_ATTR_PAD, NL80211_ATTR_IFTYPE_EXT_CAPA, NL80211_ATTR_MU_MIMO_GROUP_DATA, NL80211_ATTR_MU_MIMO_FOLLOW_MAC_ADDR, NL80211_ATTR_SCAN_START_TIME_TSF, NL80211_ATTR_SCAN_START_TIME_TSF_BSSID, NL80211_ATTR_MEASUREMENT_DURATION, NL80211_ATTR_MEASUREMENT_DURATION_MANDATORY, NL80211_ATTR_MESH_PEER_AID, NL80211_ATTR_NAN_MASTER_PREF, NL80211_ATTR_BANDS, NL80211_ATTR_NAN_FUNC, NL80211_ATTR_NAN_MATCH, NL80211_ATTR_FILS_KEK, NL80211_ATTR_FILS_NONCES, NL80211_ATTR_MULTICAST_TO_UNICAST_ENABLED, NL80211_ATTR_BSSID, NL80211_ATTR_SCHED_SCAN_RELATIVE_RSSI, NL80211_ATTR_SCHED_SCAN_RSSI_ADJUST, NL80211_ATTR_TIMEOUT_REASON, NL80211_ATTR_FILS_ERP_USERNAME, NL80211_ATTR_FILS_ERP_REALM, NL80211_ATTR_FILS_ERP_NEXT_SEQ_NUM, NL80211_ATTR_FILS_ERP_RRK, NL80211_ATTR_FILS_CACHE_ID, NL80211_ATTR_PMK, NL80211_ATTR_SCHED_SCAN_MULTI, NL80211_ATTR_SCHED_SCAN_MAX_REQS, NL80211_ATTR_WANT_1X_4WAY_HS, NL80211_ATTR_PMKR0_NAME, NL80211_ATTR_PORT_AUTHORIZED, NL80211_ATTR_EXTERNAL_AUTH_ACTION, NL80211_ATTR_EXTERNAL_AUTH_SUPPORT, NL80211_ATTR_NSS, NL80211_ATTR_ACK_SIGNAL, NL80211_ATTR_CONTROL_PORT_OVER_NL80211, NL80211_ATTR_TXQ_STATS, NL80211_ATTR_TXQ_LIMIT, NL80211_ATTR_TXQ_MEMORY_LIMIT, NL80211_ATTR_TXQ_QUANTUM, NL80211_ATTR_HE_CAPABILITY, NL80211_ATTR_FTM_RESPONDER, NL80211_ATTR_FTM_RESPONDER_STATS, NL80211_ATTR_TIMEOUT, NL80211_ATTR_PEER_MEASUREMENTS, NL80211_ATTR_AIRTIME_WEIGHT, NL80211_ATTR_STA_TX_POWER_SETTING, NL80211_ATTR_STA_TX_POWER, NL80211_ATTR_SAE_PASSWORD, NL80211_ATTR_TWT_RESPONDER, NL80211_ATTR_HE_OBSS_PD, NL80211_ATTR_WIPHY_EDMG_CHANNELS, NL80211_ATTR_WIPHY_EDMG_BW_CONFIG, NL80211_ATTR_VLAN_ID, NL80211_ATTR_HE_BSS_COLOR, NL80211_ATTR_IFTYPE_AKM_SUITES, NL80211_ATTR_TID_CONFIG, NL80211_ATTR_CONTROL_PORT_NO_PREAUTH, NL80211_ATTR_PMK_LIFETIME, NL80211_ATTR_PMK_REAUTH_THRESHOLD, NL80211_ATTR_RECEIVE_MULTICAST, NL80211_ATTR_WIPHY_FREQ_OFFSET, NL80211_ATTR_CENTER_FREQ1_OFFSET, NL80211_ATTR_SCAN_FREQ_KHZ, NL80211_ATTR_HE_6GHZ_CAPABILITY, NL80211_ATTR_FILS_DISCOVERY, NL80211_ATTR_UNSOL_BCAST_PROBE_RESP, NL80211_ATTR_S1G_CAPABILITY, NL80211_ATTR_S1G_CAPABILITY_MASK, NL80211_ATTR_SAE_PWE, NL80211_ATTR_RECONNECT_REQUESTED, NL80211_ATTR_SAR_SPEC, NL80211_ATTR_DISABLE_HE, NL80211_ATTR_OBSS_COLOR_BITMAP, NL80211_ATTR_COLOR_CHANGE_COUNT, NL80211_ATTR_COLOR_CHANGE_COLOR, NL80211_ATTR_COLOR_CHANGE_ELEMS, NL80211_ATTR_MBSSID_CONFIG, NL80211_ATTR_MBSSID_ELEMS, NL80211_ATTR_RADAR_BACKGROUND, NL80211_ATTR_AP_SETTINGS_FLAGS, NL80211_ATTR_EHT_CAPABILITY, NL80211_ATTR_DISABLE_EHT, NL80211_ATTR_MLO_LINKS, NL80211_ATTR_MLO_LINK_ID, NL80211_ATTR_MLD_ADDR, NL80211_ATTR_MLO_SUPPORT, NL80211_ATTR_MAX_NUM_AKM_SUITES, NL80211_ATTR_EML_CAPABILITY, NL80211_ATTR_MLD_CAPA_AND_OPS, NL80211_ATTR_TX_HW_TIMESTAMP, NL80211_ATTR_RX_HW_TIMESTAMP, NL80211_ATTR_TD_BITMAP, NL80211_ATTR_PUNCT_BITMAP, NL80211_ATTR_MAX_HW_TIMESTAMP_PEERS, NL80211_ATTR_HW_TIMESTAMP_ENABLED, NL80211_ATTR_EMA_RNR_ELEMS, /* add attributes here, update the policy in nl80211.c */ __NL80211_ATTR_AFTER_LAST, NUM_NL80211_ATTR = __NL80211_ATTR_AFTER_LAST, NL80211_ATTR_MAX = __NL80211_ATTR_AFTER_LAST - 1 }; /* source-level API compatibility */ #define NL80211_ATTR_SCAN_GENERATION NL80211_ATTR_GENERATION #define NL80211_ATTR_MESH_PARAMS NL80211_ATTR_MESH_CONFIG #define NL80211_ATTR_IFACE_SOCKET_OWNER NL80211_ATTR_SOCKET_OWNER #define NL80211_ATTR_SAE_DATA NL80211_ATTR_AUTH_DATA #define NL80211_ATTR_CSA_C_OFF_BEACON NL80211_ATTR_CNTDWN_OFFS_BEACON #define NL80211_ATTR_CSA_C_OFF_PRESP NL80211_ATTR_CNTDWN_OFFS_PRESP /* * Allow user space programs to use #ifdef on new attributes by defining them * here */ #define NL80211_CMD_CONNECT NL80211_CMD_CONNECT #define NL80211_ATTR_HT_CAPABILITY NL80211_ATTR_HT_CAPABILITY #define NL80211_ATTR_BSS_BASIC_RATES NL80211_ATTR_BSS_BASIC_RATES #define NL80211_ATTR_WIPHY_TXQ_PARAMS NL80211_ATTR_WIPHY_TXQ_PARAMS #define NL80211_ATTR_WIPHY_FREQ NL80211_ATTR_WIPHY_FREQ #define NL80211_ATTR_WIPHY_CHANNEL_TYPE NL80211_ATTR_WIPHY_CHANNEL_TYPE #define NL80211_ATTR_MGMT_SUBTYPE NL80211_ATTR_MGMT_SUBTYPE #define NL80211_ATTR_IE NL80211_ATTR_IE #define NL80211_ATTR_REG_INITIATOR NL80211_ATTR_REG_INITIATOR #define NL80211_ATTR_REG_TYPE NL80211_ATTR_REG_TYPE #define NL80211_ATTR_FRAME NL80211_ATTR_FRAME #define NL80211_ATTR_SSID NL80211_ATTR_SSID #define NL80211_ATTR_AUTH_TYPE NL80211_ATTR_AUTH_TYPE #define NL80211_ATTR_REASON_CODE NL80211_ATTR_REASON_CODE #define NL80211_ATTR_CIPHER_SUITES_PAIRWISE NL80211_ATTR_CIPHER_SUITES_PAIRWISE #define NL80211_ATTR_CIPHER_SUITE_GROUP NL80211_ATTR_CIPHER_SUITE_GROUP #define NL80211_ATTR_WPA_VERSIONS NL80211_ATTR_WPA_VERSIONS #define NL80211_ATTR_AKM_SUITES NL80211_ATTR_AKM_SUITES #define NL80211_ATTR_KEY NL80211_ATTR_KEY #define NL80211_ATTR_KEYS NL80211_ATTR_KEYS #define NL80211_ATTR_FEATURE_FLAGS NL80211_ATTR_FEATURE_FLAGS #define NL80211_WIPHY_NAME_MAXLEN 64 #define NL80211_MAX_SUPP_RATES 32 #define NL80211_MAX_SUPP_HT_RATES 77 #define NL80211_MAX_SUPP_REG_RULES 128 #define NL80211_TKIP_DATA_OFFSET_ENCR_KEY 0 #define NL80211_TKIP_DATA_OFFSET_TX_MIC_KEY 16 #define NL80211_TKIP_DATA_OFFSET_RX_MIC_KEY 24 #define NL80211_HT_CAPABILITY_LEN 26 #define NL80211_VHT_CAPABILITY_LEN 12 #define NL80211_HE_MIN_CAPABILITY_LEN 16 #define NL80211_HE_MAX_CAPABILITY_LEN 54 #define NL80211_MAX_NR_CIPHER_SUITES 5 /* * NL80211_MAX_NR_AKM_SUITES is obsolete when %NL80211_ATTR_MAX_NUM_AKM_SUITES * present in %NL80211_CMD_GET_WIPHY response. */ #define NL80211_MAX_NR_AKM_SUITES 2 #define NL80211_EHT_MIN_CAPABILITY_LEN 13 #define NL80211_EHT_MAX_CAPABILITY_LEN 51 #define NL80211_MIN_REMAIN_ON_CHANNEL_TIME 10 /* default RSSI threshold for scan results if none specified. */ #define NL80211_SCAN_RSSI_THOLD_OFF -300 #define NL80211_CQM_TXE_MAX_INTVL 1800 /** * enum nl80211_iftype - (virtual) interface types * * @NL80211_IFTYPE_UNSPECIFIED: unspecified type, driver decides * @NL80211_IFTYPE_ADHOC: independent BSS member * @NL80211_IFTYPE_STATION: managed BSS member * @NL80211_IFTYPE_AP: access point * @NL80211_IFTYPE_AP_VLAN: VLAN interface for access points; VLAN interfaces * are a bit special in that they must always be tied to a pre-existing * AP type interface. * @NL80211_IFTYPE_WDS: wireless distribution interface * @NL80211_IFTYPE_MONITOR: monitor interface receiving all frames * @NL80211_IFTYPE_MESH_POINT: mesh point * @NL80211_IFTYPE_P2P_CLIENT: P2P client * @NL80211_IFTYPE_P2P_GO: P2P group owner * @NL80211_IFTYPE_P2P_DEVICE: P2P device interface type, this is not a netdev * and therefore can't be created in the normal ways, use the * %NL80211_CMD_START_P2P_DEVICE and %NL80211_CMD_STOP_P2P_DEVICE * commands to create and destroy one * @NL80211_IFTYPE_OCB: Outside Context of a BSS * This mode corresponds to the MIB variable dot11OCBActivated=true * @NL80211_IFTYPE_NAN: NAN device interface type (not a netdev) * @NL80211_IFTYPE_MAX: highest interface type number currently defined * @NUM_NL80211_IFTYPES: number of defined interface types * * These values are used with the %NL80211_ATTR_IFTYPE * to set the type of an interface. * */ enum nl80211_iftype { NL80211_IFTYPE_UNSPECIFIED, NL80211_IFTYPE_ADHOC, NL80211_IFTYPE_STATION, NL80211_IFTYPE_AP, NL80211_IFTYPE_AP_VLAN, NL80211_IFTYPE_WDS, NL80211_IFTYPE_MONITOR, NL80211_IFTYPE_MESH_POINT, NL80211_IFTYPE_P2P_CLIENT, NL80211_IFTYPE_P2P_GO, NL80211_IFTYPE_P2P_DEVICE, NL80211_IFTYPE_OCB, NL80211_IFTYPE_NAN, /* keep last */ NUM_NL80211_IFTYPES, NL80211_IFTYPE_MAX = NUM_NL80211_IFTYPES - 1 }; /** * enum nl80211_sta_flags - station flags * * Station flags. When a station is added to an AP interface, it is * assumed to be already associated (and hence authenticated.) * * @__NL80211_STA_FLAG_INVALID: attribute number 0 is reserved * @NL80211_STA_FLAG_AUTHORIZED: station is authorized (802.1X) * @NL80211_STA_FLAG_SHORT_PREAMBLE: station is capable of receiving frames * with short barker preamble * @NL80211_STA_FLAG_WME: station is WME/QoS capable * @NL80211_STA_FLAG_MFP: station uses management frame protection * @NL80211_STA_FLAG_AUTHENTICATED: station is authenticated * @NL80211_STA_FLAG_TDLS_PEER: station is a TDLS peer -- this flag should * only be used in managed mode (even in the flags mask). Note that the * flag can't be changed, it is only valid while adding a station, and * attempts to change it will silently be ignored (rather than rejected * as errors.) * @NL80211_STA_FLAG_ASSOCIATED: station is associated; used with drivers * that support %NL80211_FEATURE_FULL_AP_CLIENT_STATE to transition a * previously added station into associated state * @NL80211_STA_FLAG_MAX: highest station flag number currently defined * @__NL80211_STA_FLAG_AFTER_LAST: internal use */ enum nl80211_sta_flags { __NL80211_STA_FLAG_INVALID, NL80211_STA_FLAG_AUTHORIZED, NL80211_STA_FLAG_SHORT_PREAMBLE, NL80211_STA_FLAG_WME, NL80211_STA_FLAG_MFP, NL80211_STA_FLAG_AUTHENTICATED, NL80211_STA_FLAG_TDLS_PEER, NL80211_STA_FLAG_ASSOCIATED, /* keep last */ __NL80211_STA_FLAG_AFTER_LAST, NL80211_STA_FLAG_MAX = __NL80211_STA_FLAG_AFTER_LAST - 1 }; /** * enum nl80211_sta_p2p_ps_status - station support of P2P PS * * @NL80211_P2P_PS_UNSUPPORTED: station doesn't support P2P PS mechanism * @@NL80211_P2P_PS_SUPPORTED: station supports P2P PS mechanism * @NUM_NL80211_P2P_PS_STATUS: number of values */ enum nl80211_sta_p2p_ps_status { NL80211_P2P_PS_UNSUPPORTED = 0, NL80211_P2P_PS_SUPPORTED, NUM_NL80211_P2P_PS_STATUS, }; #define NL80211_STA_FLAG_MAX_OLD_API NL80211_STA_FLAG_TDLS_PEER /** * struct nl80211_sta_flag_update - station flags mask/set * @mask: mask of station flags to set * @set: which values to set them to * * Both mask and set contain bits as per &enum nl80211_sta_flags. */ struct nl80211_sta_flag_update { __u32 mask; __u32 set; } __attribute__((packed)); /** * enum nl80211_he_gi - HE guard interval * @NL80211_RATE_INFO_HE_GI_0_8: 0.8 usec * @NL80211_RATE_INFO_HE_GI_1_6: 1.6 usec * @NL80211_RATE_INFO_HE_GI_3_2: 3.2 usec */ enum nl80211_he_gi { NL80211_RATE_INFO_HE_GI_0_8, NL80211_RATE_INFO_HE_GI_1_6, NL80211_RATE_INFO_HE_GI_3_2, }; /** * enum nl80211_he_ltf - HE long training field * @NL80211_RATE_INFO_HE_1xLTF: 3.2 usec * @NL80211_RATE_INFO_HE_2xLTF: 6.4 usec * @NL80211_RATE_INFO_HE_4xLTF: 12.8 usec */ enum nl80211_he_ltf { NL80211_RATE_INFO_HE_1XLTF, NL80211_RATE_INFO_HE_2XLTF, NL80211_RATE_INFO_HE_4XLTF, }; /** * enum nl80211_he_ru_alloc - HE RU allocation values * @NL80211_RATE_INFO_HE_RU_ALLOC_26: 26-tone RU allocation * @NL80211_RATE_INFO_HE_RU_ALLOC_52: 52-tone RU allocation * @NL80211_RATE_INFO_HE_RU_ALLOC_106: 106-tone RU allocation * @NL80211_RATE_INFO_HE_RU_ALLOC_242: 242-tone RU allocation * @NL80211_RATE_INFO_HE_RU_ALLOC_484: 484-tone RU allocation * @NL80211_RATE_INFO_HE_RU_ALLOC_996: 996-tone RU allocation * @NL80211_RATE_INFO_HE_RU_ALLOC_2x996: 2x996-tone RU allocation */ enum nl80211_he_ru_alloc { NL80211_RATE_INFO_HE_RU_ALLOC_26, NL80211_RATE_INFO_HE_RU_ALLOC_52, NL80211_RATE_INFO_HE_RU_ALLOC_106, NL80211_RATE_INFO_HE_RU_ALLOC_242, NL80211_RATE_INFO_HE_RU_ALLOC_484, NL80211_RATE_INFO_HE_RU_ALLOC_996, NL80211_RATE_INFO_HE_RU_ALLOC_2x996, }; /** * enum nl80211_eht_gi - EHT guard interval * @NL80211_RATE_INFO_EHT_GI_0_8: 0.8 usec * @NL80211_RATE_INFO_EHT_GI_1_6: 1.6 usec * @NL80211_RATE_INFO_EHT_GI_3_2: 3.2 usec */ enum nl80211_eht_gi { NL80211_RATE_INFO_EHT_GI_0_8, NL80211_RATE_INFO_EHT_GI_1_6, NL80211_RATE_INFO_EHT_GI_3_2, }; /** * enum nl80211_eht_ru_alloc - EHT RU allocation values * @NL80211_RATE_INFO_EHT_RU_ALLOC_26: 26-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_52: 52-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_52P26: 52+26-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_106: 106-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_106P26: 106+26 tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_242: 242-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_484: 484-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_484P242: 484+242 tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_996: 996-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_996P484: 996+484 tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_996P484P242: 996+484+242 tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_2x996: 2x996-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_2x996P484: 2x996+484 tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_3x996: 3x996-tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_3x996P484: 3x996+484 tone RU allocation * @NL80211_RATE_INFO_EHT_RU_ALLOC_4x996: 4x996-tone RU allocation */ enum nl80211_eht_ru_alloc { NL80211_RATE_INFO_EHT_RU_ALLOC_26, NL80211_RATE_INFO_EHT_RU_ALLOC_52, NL80211_RATE_INFO_EHT_RU_ALLOC_52P26, NL80211_RATE_INFO_EHT_RU_ALLOC_106, NL80211_RATE_INFO_EHT_RU_ALLOC_106P26, NL80211_RATE_INFO_EHT_RU_ALLOC_242, NL80211_RATE_INFO_EHT_RU_ALLOC_484, NL80211_RATE_INFO_EHT_RU_ALLOC_484P242, NL80211_RATE_INFO_EHT_RU_ALLOC_996, NL80211_RATE_INFO_EHT_RU_ALLOC_996P484, NL80211_RATE_INFO_EHT_RU_ALLOC_996P484P242, NL80211_RATE_INFO_EHT_RU_ALLOC_2x996, NL80211_RATE_INFO_EHT_RU_ALLOC_2x996P484, NL80211_RATE_INFO_EHT_RU_ALLOC_3x996, NL80211_RATE_INFO_EHT_RU_ALLOC_3x996P484, NL80211_RATE_INFO_EHT_RU_ALLOC_4x996, }; /** * enum nl80211_rate_info - bitrate information * * These attribute types are used with %NL80211_STA_INFO_TXRATE * when getting information about the bitrate of a station. * There are 2 attributes for bitrate, a legacy one that represents * a 16-bit value, and new one that represents a 32-bit value. * If the rate value fits into 16 bit, both attributes are reported * with the same value. If the rate is too high to fit into 16 bits * (>6.5535Gbps) only 32-bit attribute is included. * User space tools encouraged to use the 32-bit attribute and fall * back to the 16-bit one for compatibility with older kernels. * * @__NL80211_RATE_INFO_INVALID: attribute number 0 is reserved * @NL80211_RATE_INFO_BITRATE: total bitrate (u16, 100kbit/s) * @NL80211_RATE_INFO_MCS: mcs index for 802.11n (u8) * @NL80211_RATE_INFO_40_MHZ_WIDTH: 40 MHz dualchannel bitrate * @NL80211_RATE_INFO_SHORT_GI: 400ns guard interval * @NL80211_RATE_INFO_BITRATE32: total bitrate (u32, 100kbit/s) * @NL80211_RATE_INFO_MAX: highest rate_info number currently defined * @NL80211_RATE_INFO_VHT_MCS: MCS index for VHT (u8) * @NL80211_RATE_INFO_VHT_NSS: number of streams in VHT (u8) * @NL80211_RATE_INFO_80_MHZ_WIDTH: 80 MHz VHT rate * @NL80211_RATE_INFO_80P80_MHZ_WIDTH: unused - 80+80 is treated the * same as 160 for purposes of the bitrates * @NL80211_RATE_INFO_160_MHZ_WIDTH: 160 MHz VHT rate * @NL80211_RATE_INFO_10_MHZ_WIDTH: 10 MHz width - note that this is * a legacy rate and will be reported as the actual bitrate, i.e. * half the base (20 MHz) rate * @NL80211_RATE_INFO_5_MHZ_WIDTH: 5 MHz width - note that this is * a legacy rate and will be reported as the actual bitrate, i.e. * a quarter of the base (20 MHz) rate * @NL80211_RATE_INFO_HE_MCS: HE MCS index (u8, 0-11) * @NL80211_RATE_INFO_HE_NSS: HE NSS value (u8, 1-8) * @NL80211_RATE_INFO_HE_GI: HE guard interval identifier * (u8, see &enum nl80211_he_gi) * @NL80211_RATE_INFO_HE_DCM: HE DCM value (u8, 0/1) * @NL80211_RATE_INFO_RU_ALLOC: HE RU allocation, if not present then * non-OFDMA was used (u8, see &enum nl80211_he_ru_alloc) * @NL80211_RATE_INFO_320_MHZ_WIDTH: 320 MHz bitrate * @NL80211_RATE_INFO_EHT_MCS: EHT MCS index (u8, 0-15) * @NL80211_RATE_INFO_EHT_NSS: EHT NSS value (u8, 1-8) * @NL80211_RATE_INFO_EHT_GI: EHT guard interval identifier * (u8, see &enum nl80211_eht_gi) * @NL80211_RATE_INFO_EHT_RU_ALLOC: EHT RU allocation, if not present then * non-OFDMA was used (u8, see &enum nl80211_eht_ru_alloc) * @__NL80211_RATE_INFO_AFTER_LAST: internal use */ enum nl80211_rate_info { __NL80211_RATE_INFO_INVALID, NL80211_RATE_INFO_BITRATE, NL80211_RATE_INFO_MCS, NL80211_RATE_INFO_40_MHZ_WIDTH, NL80211_RATE_INFO_SHORT_GI, NL80211_RATE_INFO_BITRATE32, NL80211_RATE_INFO_VHT_MCS, NL80211_RATE_INFO_VHT_NSS, NL80211_RATE_INFO_80_MHZ_WIDTH, NL80211_RATE_INFO_80P80_MHZ_WIDTH, NL80211_RATE_INFO_160_MHZ_WIDTH, NL80211_RATE_INFO_10_MHZ_WIDTH, NL80211_RATE_INFO_5_MHZ_WIDTH, NL80211_RATE_INFO_HE_MCS, NL80211_RATE_INFO_HE_NSS, NL80211_RATE_INFO_HE_GI, NL80211_RATE_INFO_HE_DCM, NL80211_RATE_INFO_HE_RU_ALLOC, NL80211_RATE_INFO_320_MHZ_WIDTH, NL80211_RATE_INFO_EHT_MCS, NL80211_RATE_INFO_EHT_NSS, NL80211_RATE_INFO_EHT_GI, NL80211_RATE_INFO_EHT_RU_ALLOC, /* keep last */ __NL80211_RATE_INFO_AFTER_LAST, NL80211_RATE_INFO_MAX = __NL80211_RATE_INFO_AFTER_LAST - 1 }; /** * enum nl80211_sta_bss_param - BSS information collected by STA * * These attribute types are used with %NL80211_STA_INFO_BSS_PARAM * when getting information about the bitrate of a station. * * @__NL80211_STA_BSS_PARAM_INVALID: attribute number 0 is reserved * @NL80211_STA_BSS_PARAM_CTS_PROT: whether CTS protection is enabled (flag) * @NL80211_STA_BSS_PARAM_SHORT_PREAMBLE: whether short preamble is enabled * (flag) * @NL80211_STA_BSS_PARAM_SHORT_SLOT_TIME: whether short slot time is enabled * (flag) * @NL80211_STA_BSS_PARAM_DTIM_PERIOD: DTIM period for beaconing (u8) * @NL80211_STA_BSS_PARAM_BEACON_INTERVAL: Beacon interval (u16) * @NL80211_STA_BSS_PARAM_MAX: highest sta_bss_param number currently defined * @__NL80211_STA_BSS_PARAM_AFTER_LAST: internal use */ enum nl80211_sta_bss_param { __NL80211_STA_BSS_PARAM_INVALID, NL80211_STA_BSS_PARAM_CTS_PROT, NL80211_STA_BSS_PARAM_SHORT_PREAMBLE, NL80211_STA_BSS_PARAM_SHORT_SLOT_TIME, NL80211_STA_BSS_PARAM_DTIM_PERIOD, NL80211_STA_BSS_PARAM_BEACON_INTERVAL, /* keep last */ __NL80211_STA_BSS_PARAM_AFTER_LAST, NL80211_STA_BSS_PARAM_MAX = __NL80211_STA_BSS_PARAM_AFTER_LAST - 1 }; /** * enum nl80211_sta_info - station information * * These attribute types are used with %NL80211_ATTR_STA_INFO * when getting information about a station. * * @__NL80211_STA_INFO_INVALID: attribute number 0 is reserved * @NL80211_STA_INFO_INACTIVE_TIME: time since last activity (u32, msecs) * @NL80211_STA_INFO_RX_BYTES: total received bytes (MPDU length) * (u32, from this station) * @NL80211_STA_INFO_TX_BYTES: total transmitted bytes (MPDU length) * (u32, to this station) * @NL80211_STA_INFO_RX_BYTES64: total received bytes (MPDU length) * (u64, from this station) * @NL80211_STA_INFO_TX_BYTES64: total transmitted bytes (MPDU length) * (u64, to this station) * @NL80211_STA_INFO_SIGNAL: signal strength of last received PPDU (u8, dBm) * @NL80211_STA_INFO_TX_BITRATE: current unicast tx rate, nested attribute * containing info as possible, see &enum nl80211_rate_info * @NL80211_STA_INFO_RX_PACKETS: total received packet (MSDUs and MMPDUs) * (u32, from this station) * @NL80211_STA_INFO_TX_PACKETS: total transmitted packets (MSDUs and MMPDUs) * (u32, to this station) * @NL80211_STA_INFO_TX_RETRIES: total retries (MPDUs) (u32, to this station) * @NL80211_STA_INFO_TX_FAILED: total failed packets (MPDUs) * (u32, to this station) * @NL80211_STA_INFO_SIGNAL_AVG: signal strength average (u8, dBm) * @NL80211_STA_INFO_LLID: the station's mesh LLID * @NL80211_STA_INFO_PLID: the station's mesh PLID * @NL80211_STA_INFO_PLINK_STATE: peer link state for the station * (see %enum nl80211_plink_state) * @NL80211_STA_INFO_RX_BITRATE: last unicast data frame rx rate, nested * attribute, like NL80211_STA_INFO_TX_BITRATE. * @NL80211_STA_INFO_BSS_PARAM: current station's view of BSS, nested attribute * containing info as possible, see &enum nl80211_sta_bss_param * @NL80211_STA_INFO_CONNECTED_TIME: time since the station is last connected * @NL80211_STA_INFO_STA_FLAGS: Contains a struct nl80211_sta_flag_update. * @NL80211_STA_INFO_BEACON_LOSS: count of times beacon loss was detected (u32) * @NL80211_STA_INFO_T_OFFSET: timing offset with respect to this STA (s64) * @NL80211_STA_INFO_LOCAL_PM: local mesh STA link-specific power mode * @NL80211_STA_INFO_PEER_PM: peer mesh STA link-specific power mode * @NL80211_STA_INFO_NONPEER_PM: neighbor mesh STA power save mode towards * non-peer STA * @NL80211_STA_INFO_CHAIN_SIGNAL: per-chain signal strength of last PPDU * Contains a nested array of signal strength attributes (u8, dBm) * @NL80211_STA_INFO_CHAIN_SIGNAL_AVG: per-chain signal strength average * Same format as NL80211_STA_INFO_CHAIN_SIGNAL. * @NL80211_STA_EXPECTED_THROUGHPUT: expected throughput considering also the * 802.11 header (u32, kbps) * @NL80211_STA_INFO_RX_DROP_MISC: RX packets dropped for unspecified reasons * (u64) * @NL80211_STA_INFO_BEACON_RX: number of beacons received from this peer (u64) * @NL80211_STA_INFO_BEACON_SIGNAL_AVG: signal strength average * for beacons only (u8, dBm) * @NL80211_STA_INFO_TID_STATS: per-TID statistics (see &enum nl80211_tid_stats) * This is a nested attribute where each the inner attribute number is the * TID+1 and the special TID 16 (i.e. value 17) is used for non-QoS frames; * each one of those is again nested with &enum nl80211_tid_stats * attributes carrying the actual values. * @NL80211_STA_INFO_RX_DURATION: aggregate PPDU duration for all frames * received from the station (u64, usec) * @NL80211_STA_INFO_PAD: attribute used for padding for 64-bit alignment * @NL80211_STA_INFO_ACK_SIGNAL: signal strength of the last ACK frame(u8, dBm) * @NL80211_STA_INFO_ACK_SIGNAL_AVG: avg signal strength of ACK frames (s8, dBm) * @NL80211_STA_INFO_RX_MPDUS: total number of received packets (MPDUs) * (u32, from this station) * @NL80211_STA_INFO_FCS_ERROR_COUNT: total number of packets (MPDUs) received * with an FCS error (u32, from this station). This count may not include * some packets with an FCS error due to TA corruption. Hence this counter * might not be fully accurate. * @NL80211_STA_INFO_CONNECTED_TO_GATE: set to true if STA has a path to a * mesh gate (u8, 0 or 1) * @NL80211_STA_INFO_TX_DURATION: aggregate PPDU duration for all frames * sent to the station (u64, usec) * @NL80211_STA_INFO_AIRTIME_WEIGHT: current airtime weight for station (u16) * @NL80211_STA_INFO_AIRTIME_LINK_METRIC: airtime link metric for mesh station * @NL80211_STA_INFO_ASSOC_AT_BOOTTIME: Timestamp (CLOCK_BOOTTIME, nanoseconds) * of STA's association * @NL80211_STA_INFO_CONNECTED_TO_AS: set to true if STA has a path to a * authentication server (u8, 0 or 1) * @__NL80211_STA_INFO_AFTER_LAST: internal * @NL80211_STA_INFO_MAX: highest possible station info attribute */ enum nl80211_sta_info { __NL80211_STA_INFO_INVALID, NL80211_STA_INFO_INACTIVE_TIME, NL80211_STA_INFO_RX_BYTES, NL80211_STA_INFO_TX_BYTES, NL80211_STA_INFO_LLID, NL80211_STA_INFO_PLID, NL80211_STA_INFO_PLINK_STATE, NL80211_STA_INFO_SIGNAL, NL80211_STA_INFO_TX_BITRATE, NL80211_STA_INFO_RX_PACKETS, NL80211_STA_INFO_TX_PACKETS, NL80211_STA_INFO_TX_RETRIES, NL80211_STA_INFO_TX_FAILED, NL80211_STA_INFO_SIGNAL_AVG, NL80211_STA_INFO_RX_BITRATE, NL80211_STA_INFO_BSS_PARAM, NL80211_STA_INFO_CONNECTED_TIME, NL80211_STA_INFO_STA_FLAGS, NL80211_STA_INFO_BEACON_LOSS, NL80211_STA_INFO_T_OFFSET, NL80211_STA_INFO_LOCAL_PM, NL80211_STA_INFO_PEER_PM, NL80211_STA_INFO_NONPEER_PM, NL80211_STA_INFO_RX_BYTES64, NL80211_STA_INFO_TX_BYTES64, NL80211_STA_INFO_CHAIN_SIGNAL, NL80211_STA_INFO_CHAIN_SIGNAL_AVG, NL80211_STA_INFO_EXPECTED_THROUGHPUT, NL80211_STA_INFO_RX_DROP_MISC, NL80211_STA_INFO_BEACON_RX, NL80211_STA_INFO_BEACON_SIGNAL_AVG, NL80211_STA_INFO_TID_STATS, NL80211_STA_INFO_RX_DURATION, NL80211_STA_INFO_PAD, NL80211_STA_INFO_ACK_SIGNAL, NL80211_STA_INFO_ACK_SIGNAL_AVG, NL80211_STA_INFO_RX_MPDUS, NL80211_STA_INFO_FCS_ERROR_COUNT, NL80211_STA_INFO_CONNECTED_TO_GATE, NL80211_STA_INFO_TX_DURATION, NL80211_STA_INFO_AIRTIME_WEIGHT, NL80211_STA_INFO_AIRTIME_LINK_METRIC, NL80211_STA_INFO_ASSOC_AT_BOOTTIME, NL80211_STA_INFO_CONNECTED_TO_AS, /* keep last */ __NL80211_STA_INFO_AFTER_LAST, NL80211_STA_INFO_MAX = __NL80211_STA_INFO_AFTER_LAST - 1 }; /* we renamed this - stay compatible */ #define NL80211_STA_INFO_DATA_ACK_SIGNAL_AVG NL80211_STA_INFO_ACK_SIGNAL_AVG /** * enum nl80211_tid_stats - per TID statistics attributes * @__NL80211_TID_STATS_INVALID: attribute number 0 is reserved * @NL80211_TID_STATS_RX_MSDU: number of MSDUs received (u64) * @NL80211_TID_STATS_TX_MSDU: number of MSDUs transmitted (or * attempted to transmit; u64) * @NL80211_TID_STATS_TX_MSDU_RETRIES: number of retries for * transmitted MSDUs (not counting the first attempt; u64) * @NL80211_TID_STATS_TX_MSDU_FAILED: number of failed transmitted * MSDUs (u64) * @NL80211_TID_STATS_PAD: attribute used for padding for 64-bit alignment * @NL80211_TID_STATS_TXQ_STATS: TXQ stats (nested attribute) * @NUM_NL80211_TID_STATS: number of attributes here * @NL80211_TID_STATS_MAX: highest numbered attribute here */ enum nl80211_tid_stats { __NL80211_TID_STATS_INVALID, NL80211_TID_STATS_RX_MSDU, NL80211_TID_STATS_TX_MSDU, NL80211_TID_STATS_TX_MSDU_RETRIES, NL80211_TID_STATS_TX_MSDU_FAILED, NL80211_TID_STATS_PAD, NL80211_TID_STATS_TXQ_STATS, /* keep last */ NUM_NL80211_TID_STATS, NL80211_TID_STATS_MAX = NUM_NL80211_TID_STATS - 1 }; /** * enum nl80211_txq_stats - per TXQ statistics attributes * @__NL80211_TXQ_STATS_INVALID: attribute number 0 is reserved * @NUM_NL80211_TXQ_STATS: number of attributes here * @NL80211_TXQ_STATS_BACKLOG_BYTES: number of bytes currently backlogged * @NL80211_TXQ_STATS_BACKLOG_PACKETS: number of packets currently * backlogged * @NL80211_TXQ_STATS_FLOWS: total number of new flows seen * @NL80211_TXQ_STATS_DROPS: total number of packet drops * @NL80211_TXQ_STATS_ECN_MARKS: total number of packet ECN marks * @NL80211_TXQ_STATS_OVERLIMIT: number of drops due to queue space overflow * @NL80211_TXQ_STATS_OVERMEMORY: number of drops due to memory limit overflow * (only for per-phy stats) * @NL80211_TXQ_STATS_COLLISIONS: number of hash collisions * @NL80211_TXQ_STATS_TX_BYTES: total number of bytes dequeued from TXQ * @NL80211_TXQ_STATS_TX_PACKETS: total number of packets dequeued from TXQ * @NL80211_TXQ_STATS_MAX_FLOWS: number of flow buckets for PHY * @NL80211_TXQ_STATS_MAX: highest numbered attribute here */ enum nl80211_txq_stats { __NL80211_TXQ_STATS_INVALID, NL80211_TXQ_STATS_BACKLOG_BYTES, NL80211_TXQ_STATS_BACKLOG_PACKETS, NL80211_TXQ_STATS_FLOWS, NL80211_TXQ_STATS_DROPS, NL80211_TXQ_STATS_ECN_MARKS, NL80211_TXQ_STATS_OVERLIMIT, NL80211_TXQ_STATS_OVERMEMORY, NL80211_TXQ_STATS_COLLISIONS, NL80211_TXQ_STATS_TX_BYTES, NL80211_TXQ_STATS_TX_PACKETS, NL80211_TXQ_STATS_MAX_FLOWS, /* keep last */ NUM_NL80211_TXQ_STATS, NL80211_TXQ_STATS_MAX = NUM_NL80211_TXQ_STATS - 1 }; /** * enum nl80211_mpath_flags - nl80211 mesh path flags * * @NL80211_MPATH_FLAG_ACTIVE: the mesh path is active * @NL80211_MPATH_FLAG_RESOLVING: the mesh path discovery process is running * @NL80211_MPATH_FLAG_SN_VALID: the mesh path contains a valid SN * @NL80211_MPATH_FLAG_FIXED: the mesh path has been manually set * @NL80211_MPATH_FLAG_RESOLVED: the mesh path discovery process succeeded */ enum nl80211_mpath_flags { NL80211_MPATH_FLAG_ACTIVE = 1<<0, NL80211_MPATH_FLAG_RESOLVING = 1<<1, NL80211_MPATH_FLAG_SN_VALID = 1<<2, NL80211_MPATH_FLAG_FIXED = 1<<3, NL80211_MPATH_FLAG_RESOLVED = 1<<4, }; /** * enum nl80211_mpath_info - mesh path information * * These attribute types are used with %NL80211_ATTR_MPATH_INFO when getting * information about a mesh path. * * @__NL80211_MPATH_INFO_INVALID: attribute number 0 is reserved * @NL80211_MPATH_INFO_FRAME_QLEN: number of queued frames for this destination * @NL80211_MPATH_INFO_SN: destination sequence number * @NL80211_MPATH_INFO_METRIC: metric (cost) of this mesh path * @NL80211_MPATH_INFO_EXPTIME: expiration time for the path, in msec from now * @NL80211_MPATH_INFO_FLAGS: mesh path flags, enumerated in * &enum nl80211_mpath_flags; * @NL80211_MPATH_INFO_DISCOVERY_TIMEOUT: total path discovery timeout, in msec * @NL80211_MPATH_INFO_DISCOVERY_RETRIES: mesh path discovery retries * @NL80211_MPATH_INFO_HOP_COUNT: hop count to destination * @NL80211_MPATH_INFO_PATH_CHANGE: total number of path changes to destination * @NL80211_MPATH_INFO_MAX: highest mesh path information attribute number * currently defined * @__NL80211_MPATH_INFO_AFTER_LAST: internal use */ enum nl80211_mpath_info { __NL80211_MPATH_INFO_INVALID, NL80211_MPATH_INFO_FRAME_QLEN, NL80211_MPATH_INFO_SN, NL80211_MPATH_INFO_METRIC, NL80211_MPATH_INFO_EXPTIME, NL80211_MPATH_INFO_FLAGS, NL80211_MPATH_INFO_DISCOVERY_TIMEOUT, NL80211_MPATH_INFO_DISCOVERY_RETRIES, NL80211_MPATH_INFO_HOP_COUNT, NL80211_MPATH_INFO_PATH_CHANGE, /* keep last */ __NL80211_MPATH_INFO_AFTER_LAST, NL80211_MPATH_INFO_MAX = __NL80211_MPATH_INFO_AFTER_LAST - 1 }; /** * enum nl80211_band_iftype_attr - Interface type data attributes * * @__NL80211_BAND_IFTYPE_ATTR_INVALID: attribute number 0 is reserved * @NL80211_BAND_IFTYPE_ATTR_IFTYPES: nested attribute containing a flag attribute * for each interface type that supports the band data * @NL80211_BAND_IFTYPE_ATTR_HE_CAP_MAC: HE MAC capabilities as in HE * capabilities IE * @NL80211_BAND_IFTYPE_ATTR_HE_CAP_PHY: HE PHY capabilities as in HE * capabilities IE * @NL80211_BAND_IFTYPE_ATTR_HE_CAP_MCS_SET: HE supported NSS/MCS as in HE * capabilities IE * @NL80211_BAND_IFTYPE_ATTR_HE_CAP_PPE: HE PPE thresholds information as * defined in HE capabilities IE * @NL80211_BAND_IFTYPE_ATTR_HE_6GHZ_CAPA: HE 6GHz band capabilities (__le16), * given for all 6 GHz band channels * @NL80211_BAND_IFTYPE_ATTR_VENDOR_ELEMS: vendor element capabilities that are * advertised on this band/for this iftype (binary) * @NL80211_BAND_IFTYPE_ATTR_EHT_CAP_MAC: EHT MAC capabilities as in EHT * capabilities element * @NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PHY: EHT PHY capabilities as in EHT * capabilities element * @NL80211_BAND_IFTYPE_ATTR_EHT_CAP_MCS_SET: EHT supported NSS/MCS as in EHT * capabilities element * @NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PPE: EHT PPE thresholds information as * defined in EHT capabilities element * @__NL80211_BAND_IFTYPE_ATTR_AFTER_LAST: internal use * @NL80211_BAND_IFTYPE_ATTR_MAX: highest band attribute currently defined */ enum nl80211_band_iftype_attr { __NL80211_BAND_IFTYPE_ATTR_INVALID, NL80211_BAND_IFTYPE_ATTR_IFTYPES, NL80211_BAND_IFTYPE_ATTR_HE_CAP_MAC, NL80211_BAND_IFTYPE_ATTR_HE_CAP_PHY, NL80211_BAND_IFTYPE_ATTR_HE_CAP_MCS_SET, NL80211_BAND_IFTYPE_ATTR_HE_CAP_PPE, NL80211_BAND_IFTYPE_ATTR_HE_6GHZ_CAPA, NL80211_BAND_IFTYPE_ATTR_VENDOR_ELEMS, NL80211_BAND_IFTYPE_ATTR_EHT_CAP_MAC, NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PHY, NL80211_BAND_IFTYPE_ATTR_EHT_CAP_MCS_SET, NL80211_BAND_IFTYPE_ATTR_EHT_CAP_PPE, /* keep last */ __NL80211_BAND_IFTYPE_ATTR_AFTER_LAST, NL80211_BAND_IFTYPE_ATTR_MAX = __NL80211_BAND_IFTYPE_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_band_attr - band attributes * @__NL80211_BAND_ATTR_INVALID: attribute number 0 is reserved * @NL80211_BAND_ATTR_FREQS: supported frequencies in this band, * an array of nested frequency attributes * @NL80211_BAND_ATTR_RATES: supported bitrates in this band, * an array of nested bitrate attributes * @NL80211_BAND_ATTR_HT_MCS_SET: 16-byte attribute containing the MCS set as * defined in 802.11n * @NL80211_BAND_ATTR_HT_CAPA: HT capabilities, as in the HT information IE * @NL80211_BAND_ATTR_HT_AMPDU_FACTOR: A-MPDU factor, as in 11n * @NL80211_BAND_ATTR_HT_AMPDU_DENSITY: A-MPDU density, as in 11n * @NL80211_BAND_ATTR_VHT_MCS_SET: 32-byte attribute containing the MCS set as * defined in 802.11ac * @NL80211_BAND_ATTR_VHT_CAPA: VHT capabilities, as in the HT information IE * @NL80211_BAND_ATTR_IFTYPE_DATA: nested array attribute, with each entry using * attributes from &enum nl80211_band_iftype_attr * @NL80211_BAND_ATTR_EDMG_CHANNELS: bitmap that indicates the 2.16 GHz * channel(s) that are allowed to be used for EDMG transmissions. * Defined by IEEE P802.11ay/D4.0 section 9.4.2.251. * @NL80211_BAND_ATTR_EDMG_BW_CONFIG: Channel BW Configuration subfield encodes * the allowed channel bandwidth configurations. * Defined by IEEE P802.11ay/D4.0 section 9.4.2.251, Table 13. * @NL80211_BAND_ATTR_S1G_MCS_NSS_SET: S1G capabilities, supported S1G-MCS and NSS * set subfield, as in the S1G information IE, 5 bytes * @NL80211_BAND_ATTR_S1G_CAPA: S1G capabilities information subfield as in the * S1G information IE, 10 bytes * @NL80211_BAND_ATTR_MAX: highest band attribute currently defined * @__NL80211_BAND_ATTR_AFTER_LAST: internal use */ enum nl80211_band_attr { __NL80211_BAND_ATTR_INVALID, NL80211_BAND_ATTR_FREQS, NL80211_BAND_ATTR_RATES, NL80211_BAND_ATTR_HT_MCS_SET, NL80211_BAND_ATTR_HT_CAPA, NL80211_BAND_ATTR_HT_AMPDU_FACTOR, NL80211_BAND_ATTR_HT_AMPDU_DENSITY, NL80211_BAND_ATTR_VHT_MCS_SET, NL80211_BAND_ATTR_VHT_CAPA, NL80211_BAND_ATTR_IFTYPE_DATA, NL80211_BAND_ATTR_EDMG_CHANNELS, NL80211_BAND_ATTR_EDMG_BW_CONFIG, NL80211_BAND_ATTR_S1G_MCS_NSS_SET, NL80211_BAND_ATTR_S1G_CAPA, /* keep last */ __NL80211_BAND_ATTR_AFTER_LAST, NL80211_BAND_ATTR_MAX = __NL80211_BAND_ATTR_AFTER_LAST - 1 }; #define NL80211_BAND_ATTR_HT_CAPA NL80211_BAND_ATTR_HT_CAPA /** * enum nl80211_wmm_rule - regulatory wmm rule * * @__NL80211_WMMR_INVALID: attribute number 0 is reserved * @NL80211_WMMR_CW_MIN: Minimum contention window slot. * @NL80211_WMMR_CW_MAX: Maximum contention window slot. * @NL80211_WMMR_AIFSN: Arbitration Inter Frame Space. * @NL80211_WMMR_TXOP: Maximum allowed tx operation time. * @nl80211_WMMR_MAX: highest possible wmm rule. * @__NL80211_WMMR_LAST: Internal use. */ enum nl80211_wmm_rule { __NL80211_WMMR_INVALID, NL80211_WMMR_CW_MIN, NL80211_WMMR_CW_MAX, NL80211_WMMR_AIFSN, NL80211_WMMR_TXOP, /* keep last */ __NL80211_WMMR_LAST, NL80211_WMMR_MAX = __NL80211_WMMR_LAST - 1 }; /** * enum nl80211_frequency_attr - frequency attributes * @__NL80211_FREQUENCY_ATTR_INVALID: attribute number 0 is reserved * @NL80211_FREQUENCY_ATTR_FREQ: Frequency in MHz * @NL80211_FREQUENCY_ATTR_DISABLED: Channel is disabled in current * regulatory domain. * @NL80211_FREQUENCY_ATTR_NO_IR: no mechanisms that initiate radiation * are permitted on this channel, this includes sending probe * requests, or modes of operation that require beaconing. * @NL80211_FREQUENCY_ATTR_RADAR: Radar detection is mandatory * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_MAX_TX_POWER: Maximum transmission power in mBm * (100 * dBm). * @NL80211_FREQUENCY_ATTR_DFS_STATE: current state for DFS * (enum nl80211_dfs_state) * @NL80211_FREQUENCY_ATTR_DFS_TIME: time in miliseconds for how long * this channel is in this DFS state. * @NL80211_FREQUENCY_ATTR_NO_HT40_MINUS: HT40- isn't possible with this * channel as the control channel * @NL80211_FREQUENCY_ATTR_NO_HT40_PLUS: HT40+ isn't possible with this * channel as the control channel * @NL80211_FREQUENCY_ATTR_NO_80MHZ: any 80 MHz channel using this channel * as the primary or any of the secondary channels isn't possible, * this includes 80+80 channels * @NL80211_FREQUENCY_ATTR_NO_160MHZ: any 160 MHz (but not 80+80) channel * using this channel as the primary or any of the secondary channels * isn't possible * @NL80211_FREQUENCY_ATTR_DFS_CAC_TIME: DFS CAC time in milliseconds. * @NL80211_FREQUENCY_ATTR_INDOOR_ONLY: Only indoor use is permitted on this * channel. A channel that has the INDOOR_ONLY attribute can only be * used when there is a clear assessment that the device is operating in * an indoor surroundings, i.e., it is connected to AC power (and not * through portable DC inverters) or is under the control of a master * that is acting as an AP and is connected to AC power. * @NL80211_FREQUENCY_ATTR_IR_CONCURRENT: IR operation is allowed on this * channel if it's connected concurrently to a BSS on the same channel on * the 2 GHz band or to a channel in the same UNII band (on the 5 GHz * band), and IEEE80211_CHAN_RADAR is not set. Instantiating a GO or TDLS * off-channel on a channel that has the IR_CONCURRENT attribute set can be * done when there is a clear assessment that the device is operating under * the guidance of an authorized master, i.e., setting up a GO or TDLS * off-channel while the device is also connected to an AP with DFS and * radar detection on the UNII band (it is up to user-space, i.e., * wpa_supplicant to perform the required verifications). Using this * attribute for IR is disallowed for master interfaces (IBSS, AP). * @NL80211_FREQUENCY_ATTR_NO_20MHZ: 20 MHz operation is not allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_NO_10MHZ: 10 MHz operation is not allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_WMM: this channel has wmm limitations. * This is a nested attribute that contains the wmm limitation per AC. * (see &enum nl80211_wmm_rule) * @NL80211_FREQUENCY_ATTR_NO_HE: HE operation is not allowed on this channel * in current regulatory domain. * @NL80211_FREQUENCY_ATTR_OFFSET: frequency offset in KHz * @NL80211_FREQUENCY_ATTR_1MHZ: 1 MHz operation is allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_2MHZ: 2 MHz operation is allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_4MHZ: 4 MHz operation is allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_8MHZ: 8 MHz operation is allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_16MHZ: 16 MHz operation is allowed * on this channel in current regulatory domain. * @NL80211_FREQUENCY_ATTR_NO_320MHZ: any 320 MHz channel using this channel * as the primary or any of the secondary channels isn't possible * @NL80211_FREQUENCY_ATTR_NO_EHT: EHT operation is not allowed on this channel * in current regulatory domain. * @NL80211_FREQUENCY_ATTR_MAX: highest frequency attribute number * currently defined * @__NL80211_FREQUENCY_ATTR_AFTER_LAST: internal use * * See https://apps.fcc.gov/eas/comments/GetPublishedDocument.html?id=327&tn=528122 * for more information on the FCC description of the relaxations allowed * by NL80211_FREQUENCY_ATTR_INDOOR_ONLY and * NL80211_FREQUENCY_ATTR_IR_CONCURRENT. */ enum nl80211_frequency_attr { __NL80211_FREQUENCY_ATTR_INVALID, NL80211_FREQUENCY_ATTR_FREQ, NL80211_FREQUENCY_ATTR_DISABLED, NL80211_FREQUENCY_ATTR_NO_IR, __NL80211_FREQUENCY_ATTR_NO_IBSS, NL80211_FREQUENCY_ATTR_RADAR, NL80211_FREQUENCY_ATTR_MAX_TX_POWER, NL80211_FREQUENCY_ATTR_DFS_STATE, NL80211_FREQUENCY_ATTR_DFS_TIME, NL80211_FREQUENCY_ATTR_NO_HT40_MINUS, NL80211_FREQUENCY_ATTR_NO_HT40_PLUS, NL80211_FREQUENCY_ATTR_NO_80MHZ, NL80211_FREQUENCY_ATTR_NO_160MHZ, NL80211_FREQUENCY_ATTR_DFS_CAC_TIME, NL80211_FREQUENCY_ATTR_INDOOR_ONLY, NL80211_FREQUENCY_ATTR_IR_CONCURRENT, NL80211_FREQUENCY_ATTR_NO_20MHZ, NL80211_FREQUENCY_ATTR_NO_10MHZ, NL80211_FREQUENCY_ATTR_WMM, NL80211_FREQUENCY_ATTR_NO_HE, NL80211_FREQUENCY_ATTR_OFFSET, NL80211_FREQUENCY_ATTR_1MHZ, NL80211_FREQUENCY_ATTR_2MHZ, NL80211_FREQUENCY_ATTR_4MHZ, NL80211_FREQUENCY_ATTR_8MHZ, NL80211_FREQUENCY_ATTR_16MHZ, NL80211_FREQUENCY_ATTR_NO_320MHZ, NL80211_FREQUENCY_ATTR_NO_EHT, /* keep last */ __NL80211_FREQUENCY_ATTR_AFTER_LAST, NL80211_FREQUENCY_ATTR_MAX = __NL80211_FREQUENCY_ATTR_AFTER_LAST - 1 }; #define NL80211_FREQUENCY_ATTR_MAX_TX_POWER NL80211_FREQUENCY_ATTR_MAX_TX_POWER #define NL80211_FREQUENCY_ATTR_PASSIVE_SCAN NL80211_FREQUENCY_ATTR_NO_IR #define NL80211_FREQUENCY_ATTR_NO_IBSS NL80211_FREQUENCY_ATTR_NO_IR #define NL80211_FREQUENCY_ATTR_NO_IR NL80211_FREQUENCY_ATTR_NO_IR #define NL80211_FREQUENCY_ATTR_GO_CONCURRENT \ NL80211_FREQUENCY_ATTR_IR_CONCURRENT /** * enum nl80211_bitrate_attr - bitrate attributes * @__NL80211_BITRATE_ATTR_INVALID: attribute number 0 is reserved * @NL80211_BITRATE_ATTR_RATE: Bitrate in units of 100 kbps * @NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE: Short preamble supported * in 2.4 GHz band. * @NL80211_BITRATE_ATTR_MAX: highest bitrate attribute number * currently defined * @__NL80211_BITRATE_ATTR_AFTER_LAST: internal use */ enum nl80211_bitrate_attr { __NL80211_BITRATE_ATTR_INVALID, NL80211_BITRATE_ATTR_RATE, NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE, /* keep last */ __NL80211_BITRATE_ATTR_AFTER_LAST, NL80211_BITRATE_ATTR_MAX = __NL80211_BITRATE_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_initiator - Indicates the initiator of a reg domain request * @NL80211_REGDOM_SET_BY_CORE: Core queried CRDA for a dynamic world * regulatory domain. * @NL80211_REGDOM_SET_BY_USER: User asked the wireless core to set the * regulatory domain. * @NL80211_REGDOM_SET_BY_DRIVER: a wireless drivers has hinted to the * wireless core it thinks its knows the regulatory domain we should be in. * @NL80211_REGDOM_SET_BY_COUNTRY_IE: the wireless core has received an * 802.11 country information element with regulatory information it * thinks we should consider. cfg80211 only processes the country * code from the IE, and relies on the regulatory domain information * structure passed by userspace (CRDA) from our wireless-regdb. * If a channel is enabled but the country code indicates it should * be disabled we disable the channel and re-enable it upon disassociation. */ enum nl80211_reg_initiator { NL80211_REGDOM_SET_BY_CORE, NL80211_REGDOM_SET_BY_USER, NL80211_REGDOM_SET_BY_DRIVER, NL80211_REGDOM_SET_BY_COUNTRY_IE, }; /** * enum nl80211_reg_type - specifies the type of regulatory domain * @NL80211_REGDOM_TYPE_COUNTRY: the regulatory domain set is one that pertains * to a specific country. When this is set you can count on the * ISO / IEC 3166 alpha2 country code being valid. * @NL80211_REGDOM_TYPE_WORLD: the regulatory set domain is the world regulatory * domain. * @NL80211_REGDOM_TYPE_CUSTOM_WORLD: the regulatory domain set is a custom * driver specific world regulatory domain. These do not apply system-wide * and are only applicable to the individual devices which have requested * them to be applied. * @NL80211_REGDOM_TYPE_INTERSECTION: the regulatory domain set is the product * of an intersection between two regulatory domains -- the previously * set regulatory domain on the system and the last accepted regulatory * domain request to be processed. */ enum nl80211_reg_type { NL80211_REGDOM_TYPE_COUNTRY, NL80211_REGDOM_TYPE_WORLD, NL80211_REGDOM_TYPE_CUSTOM_WORLD, NL80211_REGDOM_TYPE_INTERSECTION, }; /** * enum nl80211_reg_rule_attr - regulatory rule attributes * @__NL80211_REG_RULE_ATTR_INVALID: attribute number 0 is reserved * @NL80211_ATTR_REG_RULE_FLAGS: a set of flags which specify additional * considerations for a given frequency range. These are the * &enum nl80211_reg_rule_flags. * @NL80211_ATTR_FREQ_RANGE_START: starting frequencry for the regulatory * rule in KHz. This is not a center of frequency but an actual regulatory * band edge. * @NL80211_ATTR_FREQ_RANGE_END: ending frequency for the regulatory rule * in KHz. This is not a center a frequency but an actual regulatory * band edge. * @NL80211_ATTR_FREQ_RANGE_MAX_BW: maximum allowed bandwidth for this * frequency range, in KHz. * @NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN: the maximum allowed antenna gain * for a given frequency range. The value is in mBi (100 * dBi). * If you don't have one then don't send this. * @NL80211_ATTR_POWER_RULE_MAX_EIRP: the maximum allowed EIRP for * a given frequency range. The value is in mBm (100 * dBm). * @NL80211_ATTR_DFS_CAC_TIME: DFS CAC time in milliseconds. * If not present or 0 default CAC time will be used. * @NL80211_REG_RULE_ATTR_MAX: highest regulatory rule attribute number * currently defined * @__NL80211_REG_RULE_ATTR_AFTER_LAST: internal use */ enum nl80211_reg_rule_attr { __NL80211_REG_RULE_ATTR_INVALID, NL80211_ATTR_REG_RULE_FLAGS, NL80211_ATTR_FREQ_RANGE_START, NL80211_ATTR_FREQ_RANGE_END, NL80211_ATTR_FREQ_RANGE_MAX_BW, NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN, NL80211_ATTR_POWER_RULE_MAX_EIRP, NL80211_ATTR_DFS_CAC_TIME, /* keep last */ __NL80211_REG_RULE_ATTR_AFTER_LAST, NL80211_REG_RULE_ATTR_MAX = __NL80211_REG_RULE_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_sched_scan_match_attr - scheduled scan match attributes * @__NL80211_SCHED_SCAN_MATCH_ATTR_INVALID: attribute number 0 is reserved * @NL80211_SCHED_SCAN_MATCH_ATTR_SSID: SSID to be used for matching, * only report BSS with matching SSID. * (This cannot be used together with BSSID.) * @NL80211_SCHED_SCAN_MATCH_ATTR_RSSI: RSSI threshold (in dBm) for reporting a * BSS in scan results. Filtering is turned off if not specified. Note that * if this attribute is in a match set of its own, then it is treated as * the default value for all matchsets with an SSID, rather than being a * matchset of its own without an RSSI filter. This is due to problems with * how this API was implemented in the past. Also, due to the same problem, * the only way to create a matchset with only an RSSI filter (with this * attribute) is if there's only a single matchset with the RSSI attribute. * @NL80211_SCHED_SCAN_MATCH_ATTR_RELATIVE_RSSI: Flag indicating whether * %NL80211_SCHED_SCAN_MATCH_ATTR_RSSI to be used as absolute RSSI or * relative to current bss's RSSI. * @NL80211_SCHED_SCAN_MATCH_ATTR_RSSI_ADJUST: When present the RSSI level for * BSS-es in the specified band is to be adjusted before doing * RSSI-based BSS selection. The attribute value is a packed structure * value as specified by &struct nl80211_bss_select_rssi_adjust. * @NL80211_SCHED_SCAN_MATCH_ATTR_BSSID: BSSID to be used for matching * (this cannot be used together with SSID). * @NL80211_SCHED_SCAN_MATCH_PER_BAND_RSSI: Nested attribute that carries the * band specific minimum rssi thresholds for the bands defined in * enum nl80211_band. The minimum rssi threshold value(s32) specific to a * band shall be encapsulated in attribute with type value equals to one * of the NL80211_BAND_* defined in enum nl80211_band. For example, the * minimum rssi threshold value for 2.4GHZ band shall be encapsulated * within an attribute of type NL80211_BAND_2GHZ. And one or more of such * attributes will be nested within this attribute. * @NL80211_SCHED_SCAN_MATCH_ATTR_MAX: highest scheduled scan filter * attribute number currently defined * @__NL80211_SCHED_SCAN_MATCH_ATTR_AFTER_LAST: internal use */ enum nl80211_sched_scan_match_attr { __NL80211_SCHED_SCAN_MATCH_ATTR_INVALID, NL80211_SCHED_SCAN_MATCH_ATTR_SSID, NL80211_SCHED_SCAN_MATCH_ATTR_RSSI, NL80211_SCHED_SCAN_MATCH_ATTR_RELATIVE_RSSI, NL80211_SCHED_SCAN_MATCH_ATTR_RSSI_ADJUST, NL80211_SCHED_SCAN_MATCH_ATTR_BSSID, NL80211_SCHED_SCAN_MATCH_PER_BAND_RSSI, /* keep last */ __NL80211_SCHED_SCAN_MATCH_ATTR_AFTER_LAST, NL80211_SCHED_SCAN_MATCH_ATTR_MAX = __NL80211_SCHED_SCAN_MATCH_ATTR_AFTER_LAST - 1 }; /* only for backward compatibility */ #define NL80211_ATTR_SCHED_SCAN_MATCH_SSID NL80211_SCHED_SCAN_MATCH_ATTR_SSID /** * enum nl80211_reg_rule_flags - regulatory rule flags * * @NL80211_RRF_NO_OFDM: OFDM modulation not allowed * @NL80211_RRF_NO_CCK: CCK modulation not allowed * @NL80211_RRF_NO_INDOOR: indoor operation not allowed * @NL80211_RRF_NO_OUTDOOR: outdoor operation not allowed * @NL80211_RRF_DFS: DFS support is required to be used * @NL80211_RRF_PTP_ONLY: this is only for Point To Point links * @NL80211_RRF_PTMP_ONLY: this is only for Point To Multi Point links * @NL80211_RRF_NO_IR: no mechanisms that initiate radiation are allowed, * this includes probe requests or modes of operation that require * beaconing. * @NL80211_RRF_AUTO_BW: maximum available bandwidth should be calculated * base on contiguous rules and wider channels will be allowed to cross * multiple contiguous/overlapping frequency ranges. * @NL80211_RRF_IR_CONCURRENT: See %NL80211_FREQUENCY_ATTR_IR_CONCURRENT * @NL80211_RRF_NO_HT40MINUS: channels can't be used in HT40- operation * @NL80211_RRF_NO_HT40PLUS: channels can't be used in HT40+ operation * @NL80211_RRF_NO_80MHZ: 80MHz operation not allowed * @NL80211_RRF_NO_160MHZ: 160MHz operation not allowed * @NL80211_RRF_NO_HE: HE operation not allowed * @NL80211_RRF_NO_320MHZ: 320MHz operation not allowed */ enum nl80211_reg_rule_flags { NL80211_RRF_NO_OFDM = 1<<0, NL80211_RRF_NO_CCK = 1<<1, NL80211_RRF_NO_INDOOR = 1<<2, NL80211_RRF_NO_OUTDOOR = 1<<3, NL80211_RRF_DFS = 1<<4, NL80211_RRF_PTP_ONLY = 1<<5, NL80211_RRF_PTMP_ONLY = 1<<6, NL80211_RRF_NO_IR = 1<<7, __NL80211_RRF_NO_IBSS = 1<<8, NL80211_RRF_AUTO_BW = 1<<11, NL80211_RRF_IR_CONCURRENT = 1<<12, NL80211_RRF_NO_HT40MINUS = 1<<13, NL80211_RRF_NO_HT40PLUS = 1<<14, NL80211_RRF_NO_80MHZ = 1<<15, NL80211_RRF_NO_160MHZ = 1<<16, NL80211_RRF_NO_HE = 1<<17, NL80211_RRF_NO_320MHZ = 1<<18, }; #define NL80211_RRF_PASSIVE_SCAN NL80211_RRF_NO_IR #define NL80211_RRF_NO_IBSS NL80211_RRF_NO_IR #define NL80211_RRF_NO_IR NL80211_RRF_NO_IR #define NL80211_RRF_NO_HT40 (NL80211_RRF_NO_HT40MINUS |\ NL80211_RRF_NO_HT40PLUS) #define NL80211_RRF_GO_CONCURRENT NL80211_RRF_IR_CONCURRENT /* For backport compatibility with older userspace */ #define NL80211_RRF_NO_IR_ALL (NL80211_RRF_NO_IR | __NL80211_RRF_NO_IBSS) /** * enum nl80211_dfs_regions - regulatory DFS regions * * @NL80211_DFS_UNSET: Country has no DFS master region specified * @NL80211_DFS_FCC: Country follows DFS master rules from FCC * @NL80211_DFS_ETSI: Country follows DFS master rules from ETSI * @NL80211_DFS_JP: Country follows DFS master rules from JP/MKK/Telec */ enum nl80211_dfs_regions { NL80211_DFS_UNSET = 0, NL80211_DFS_FCC = 1, NL80211_DFS_ETSI = 2, NL80211_DFS_JP = 3, }; /** * enum nl80211_user_reg_hint_type - type of user regulatory hint * * @NL80211_USER_REG_HINT_USER: a user sent the hint. This is always * assumed if the attribute is not set. * @NL80211_USER_REG_HINT_CELL_BASE: the hint comes from a cellular * base station. Device drivers that have been tested to work * properly to support this type of hint can enable these hints * by setting the NL80211_FEATURE_CELL_BASE_REG_HINTS feature * capability on the struct wiphy. The wireless core will * ignore all cell base station hints until at least one device * present has been registered with the wireless core that * has listed NL80211_FEATURE_CELL_BASE_REG_HINTS as a * supported feature. * @NL80211_USER_REG_HINT_INDOOR: a user sent an hint indicating that the * platform is operating in an indoor environment. */ enum nl80211_user_reg_hint_type { NL80211_USER_REG_HINT_USER = 0, NL80211_USER_REG_HINT_CELL_BASE = 1, NL80211_USER_REG_HINT_INDOOR = 2, }; /** * enum nl80211_survey_info - survey information * * These attribute types are used with %NL80211_ATTR_SURVEY_INFO * when getting information about a survey. * * @__NL80211_SURVEY_INFO_INVALID: attribute number 0 is reserved * @NL80211_SURVEY_INFO_FREQUENCY: center frequency of channel * @NL80211_SURVEY_INFO_NOISE: noise level of channel (u8, dBm) * @NL80211_SURVEY_INFO_IN_USE: channel is currently being used * @NL80211_SURVEY_INFO_TIME: amount of time (in ms) that the radio * was turned on (on channel or globally) * @NL80211_SURVEY_INFO_TIME_BUSY: amount of the time the primary * channel was sensed busy (either due to activity or energy detect) * @NL80211_SURVEY_INFO_TIME_EXT_BUSY: amount of time the extension * channel was sensed busy * @NL80211_SURVEY_INFO_TIME_RX: amount of time the radio spent * receiving data (on channel or globally) * @NL80211_SURVEY_INFO_TIME_TX: amount of time the radio spent * transmitting data (on channel or globally) * @NL80211_SURVEY_INFO_TIME_SCAN: time the radio spent for scan * (on this channel or globally) * @NL80211_SURVEY_INFO_PAD: attribute used for padding for 64-bit alignment * @NL80211_SURVEY_INFO_TIME_BSS_RX: amount of time the radio spent * receiving frames destined to the local BSS * @NL80211_SURVEY_INFO_MAX: highest survey info attribute number * currently defined * @NL80211_SURVEY_INFO_FREQUENCY_OFFSET: center frequency offset in KHz * @__NL80211_SURVEY_INFO_AFTER_LAST: internal use */ enum nl80211_survey_info { __NL80211_SURVEY_INFO_INVALID, NL80211_SURVEY_INFO_FREQUENCY, NL80211_SURVEY_INFO_NOISE, NL80211_SURVEY_INFO_IN_USE, NL80211_SURVEY_INFO_TIME, NL80211_SURVEY_INFO_TIME_BUSY, NL80211_SURVEY_INFO_TIME_EXT_BUSY, NL80211_SURVEY_INFO_TIME_RX, NL80211_SURVEY_INFO_TIME_TX, NL80211_SURVEY_INFO_TIME_SCAN, NL80211_SURVEY_INFO_PAD, NL80211_SURVEY_INFO_TIME_BSS_RX, NL80211_SURVEY_INFO_FREQUENCY_OFFSET, /* keep last */ __NL80211_SURVEY_INFO_AFTER_LAST, NL80211_SURVEY_INFO_MAX = __NL80211_SURVEY_INFO_AFTER_LAST - 1 }; /* keep old names for compatibility */ #define NL80211_SURVEY_INFO_CHANNEL_TIME NL80211_SURVEY_INFO_TIME #define NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY NL80211_SURVEY_INFO_TIME_BUSY #define NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY NL80211_SURVEY_INFO_TIME_EXT_BUSY #define NL80211_SURVEY_INFO_CHANNEL_TIME_RX NL80211_SURVEY_INFO_TIME_RX #define NL80211_SURVEY_INFO_CHANNEL_TIME_TX NL80211_SURVEY_INFO_TIME_TX /** * enum nl80211_mntr_flags - monitor configuration flags * * Monitor configuration flags. * * @__NL80211_MNTR_FLAG_INVALID: reserved * * @NL80211_MNTR_FLAG_FCSFAIL: pass frames with bad FCS * @NL80211_MNTR_FLAG_PLCPFAIL: pass frames with bad PLCP * @NL80211_MNTR_FLAG_CONTROL: pass control frames * @NL80211_MNTR_FLAG_OTHER_BSS: disable BSSID filtering * @NL80211_MNTR_FLAG_COOK_FRAMES: report frames after processing. * overrides all other flags. * @NL80211_MNTR_FLAG_ACTIVE: use the configured MAC address * and ACK incoming unicast packets. * * @__NL80211_MNTR_FLAG_AFTER_LAST: internal use * @NL80211_MNTR_FLAG_MAX: highest possible monitor flag */ enum nl80211_mntr_flags { __NL80211_MNTR_FLAG_INVALID, NL80211_MNTR_FLAG_FCSFAIL, NL80211_MNTR_FLAG_PLCPFAIL, NL80211_MNTR_FLAG_CONTROL, NL80211_MNTR_FLAG_OTHER_BSS, NL80211_MNTR_FLAG_COOK_FRAMES, NL80211_MNTR_FLAG_ACTIVE, /* keep last */ __NL80211_MNTR_FLAG_AFTER_LAST, NL80211_MNTR_FLAG_MAX = __NL80211_MNTR_FLAG_AFTER_LAST - 1 }; /** * enum nl80211_mesh_power_mode - mesh power save modes * * @NL80211_MESH_POWER_UNKNOWN: The mesh power mode of the mesh STA is * not known or has not been set yet. * @NL80211_MESH_POWER_ACTIVE: Active mesh power mode. The mesh STA is * in Awake state all the time. * @NL80211_MESH_POWER_LIGHT_SLEEP: Light sleep mode. The mesh STA will * alternate between Active and Doze states, but will wake up for * neighbor's beacons. * @NL80211_MESH_POWER_DEEP_SLEEP: Deep sleep mode. The mesh STA will * alternate between Active and Doze states, but may not wake up * for neighbor's beacons. * * @__NL80211_MESH_POWER_AFTER_LAST - internal use * @NL80211_MESH_POWER_MAX - highest possible power save level */ enum nl80211_mesh_power_mode { NL80211_MESH_POWER_UNKNOWN, NL80211_MESH_POWER_ACTIVE, NL80211_MESH_POWER_LIGHT_SLEEP, NL80211_MESH_POWER_DEEP_SLEEP, __NL80211_MESH_POWER_AFTER_LAST, NL80211_MESH_POWER_MAX = __NL80211_MESH_POWER_AFTER_LAST - 1 }; /** * enum nl80211_meshconf_params - mesh configuration parameters * * Mesh configuration parameters. These can be changed while the mesh is * active. * * @__NL80211_MESHCONF_INVALID: internal use * * @NL80211_MESHCONF_RETRY_TIMEOUT: specifies the initial retry timeout in * millisecond units, used by the Peer Link Open message * * @NL80211_MESHCONF_CONFIRM_TIMEOUT: specifies the initial confirm timeout, in * millisecond units, used by the peer link management to close a peer link * * @NL80211_MESHCONF_HOLDING_TIMEOUT: specifies the holding timeout, in * millisecond units * * @NL80211_MESHCONF_MAX_PEER_LINKS: maximum number of peer links allowed * on this mesh interface * * @NL80211_MESHCONF_MAX_RETRIES: specifies the maximum number of peer link * open retries that can be sent to establish a new peer link instance in a * mesh * * @NL80211_MESHCONF_TTL: specifies the value of TTL field set at a source mesh * point. * * @NL80211_MESHCONF_AUTO_OPEN_PLINKS: whether we should automatically open * peer links when we detect compatible mesh peers. Disabled if * @NL80211_MESH_SETUP_USERSPACE_MPM or @NL80211_MESH_SETUP_USERSPACE_AMPE are * set. * * @NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES: the number of action frames * containing a PREQ that an MP can send to a particular destination (path * target) * * @NL80211_MESHCONF_PATH_REFRESH_TIME: how frequently to refresh mesh paths * (in milliseconds) * * @NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT: minimum length of time to wait * until giving up on a path discovery (in milliseconds) * * @NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT: The time (in TUs) for which mesh * points receiving a PREQ shall consider the forwarding information from * the root to be valid. (TU = time unit) * * @NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL: The minimum interval of time (in * TUs) during which an MP can send only one action frame containing a PREQ * reference element * * @NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME: The interval of time (in TUs) * that it takes for an HWMP information element to propagate across the * mesh * * @NL80211_MESHCONF_HWMP_ROOTMODE: whether root mode is enabled or not * * @NL80211_MESHCONF_ELEMENT_TTL: specifies the value of TTL field set at a * source mesh point for path selection elements. * * @NL80211_MESHCONF_HWMP_RANN_INTERVAL: The interval of time (in TUs) between * root announcements are transmitted. * * @NL80211_MESHCONF_GATE_ANNOUNCEMENTS: Advertise that this mesh station has * access to a broader network beyond the MBSS. This is done via Root * Announcement frames. * * @NL80211_MESHCONF_HWMP_PERR_MIN_INTERVAL: The minimum interval of time (in * TUs) during which a mesh STA can send only one Action frame containing a * PERR element. * * @NL80211_MESHCONF_FORWARDING: set Mesh STA as forwarding or non-forwarding * or forwarding entity (default is TRUE - forwarding entity) * * @NL80211_MESHCONF_RSSI_THRESHOLD: RSSI threshold in dBm. This specifies the * threshold for average signal strength of candidate station to establish * a peer link. * * @NL80211_MESHCONF_SYNC_OFFSET_MAX_NEIGHBOR: maximum number of neighbors * to synchronize to for 11s default synchronization method * (see 11C.12.2.2) * * @NL80211_MESHCONF_HT_OPMODE: set mesh HT protection mode. * * @NL80211_MESHCONF_ATTR_MAX: highest possible mesh configuration attribute * * @NL80211_MESHCONF_HWMP_PATH_TO_ROOT_TIMEOUT: The time (in TUs) for * which mesh STAs receiving a proactive PREQ shall consider the forwarding * information to the root mesh STA to be valid. * * @NL80211_MESHCONF_HWMP_ROOT_INTERVAL: The interval of time (in TUs) between * proactive PREQs are transmitted. * * @NL80211_MESHCONF_HWMP_CONFIRMATION_INTERVAL: The minimum interval of time * (in TUs) during which a mesh STA can send only one Action frame * containing a PREQ element for root path confirmation. * * @NL80211_MESHCONF_POWER_MODE: Default mesh power mode for new peer links. * type &enum nl80211_mesh_power_mode (u32) * * @NL80211_MESHCONF_AWAKE_WINDOW: awake window duration (in TUs) * * @NL80211_MESHCONF_PLINK_TIMEOUT: If no tx activity is seen from a STA we've * established peering with for longer than this time (in seconds), then * remove it from the STA's list of peers. You may set this to 0 to disable * the removal of the STA. Default is 30 minutes. * * @NL80211_MESHCONF_CONNECTED_TO_GATE: If set to true then this mesh STA * will advertise that it is connected to a gate in the mesh formation * field. If left unset then the mesh formation field will only * advertise such if there is an active root mesh path. * * @NL80211_MESHCONF_NOLEARN: Try to avoid multi-hop path discovery (e.g. * PREQ/PREP for HWMP) if the destination is a direct neighbor. Note that * this might not be the optimal decision as a multi-hop route might be * better. So if using this setting you will likely also want to disable * dot11MeshForwarding and use another mesh routing protocol on top. * * @NL80211_MESHCONF_CONNECTED_TO_AS: If set to true then this mesh STA * will advertise that it is connected to a authentication server * in the mesh formation field. * * @__NL80211_MESHCONF_ATTR_AFTER_LAST: internal use */ enum nl80211_meshconf_params { __NL80211_MESHCONF_INVALID, NL80211_MESHCONF_RETRY_TIMEOUT, NL80211_MESHCONF_CONFIRM_TIMEOUT, NL80211_MESHCONF_HOLDING_TIMEOUT, NL80211_MESHCONF_MAX_PEER_LINKS, NL80211_MESHCONF_MAX_RETRIES, NL80211_MESHCONF_TTL, NL80211_MESHCONF_AUTO_OPEN_PLINKS, NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES, NL80211_MESHCONF_PATH_REFRESH_TIME, NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT, NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT, NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL, NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME, NL80211_MESHCONF_HWMP_ROOTMODE, NL80211_MESHCONF_ELEMENT_TTL, NL80211_MESHCONF_HWMP_RANN_INTERVAL, NL80211_MESHCONF_GATE_ANNOUNCEMENTS, NL80211_MESHCONF_HWMP_PERR_MIN_INTERVAL, NL80211_MESHCONF_FORWARDING, NL80211_MESHCONF_RSSI_THRESHOLD, NL80211_MESHCONF_SYNC_OFFSET_MAX_NEIGHBOR, NL80211_MESHCONF_HT_OPMODE, NL80211_MESHCONF_HWMP_PATH_TO_ROOT_TIMEOUT, NL80211_MESHCONF_HWMP_ROOT_INTERVAL, NL80211_MESHCONF_HWMP_CONFIRMATION_INTERVAL, NL80211_MESHCONF_POWER_MODE, NL80211_MESHCONF_AWAKE_WINDOW, NL80211_MESHCONF_PLINK_TIMEOUT, NL80211_MESHCONF_CONNECTED_TO_GATE, NL80211_MESHCONF_NOLEARN, NL80211_MESHCONF_CONNECTED_TO_AS, /* keep last */ __NL80211_MESHCONF_ATTR_AFTER_LAST, NL80211_MESHCONF_ATTR_MAX = __NL80211_MESHCONF_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_mesh_setup_params - mesh setup parameters * * Mesh setup parameters. These are used to start/join a mesh and cannot be * changed while the mesh is active. * * @__NL80211_MESH_SETUP_INVALID: Internal use * * @NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL: Enable this option to use a * vendor specific path selection algorithm or disable it to use the * default HWMP. * * @NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC: Enable this option to use a * vendor specific path metric or disable it to use the default Airtime * metric. * * @NL80211_MESH_SETUP_IE: Information elements for this mesh, for instance, a * robust security network ie, or a vendor specific information element * that vendors will use to identify the path selection methods and * metrics in use. * * @NL80211_MESH_SETUP_USERSPACE_AUTH: Enable this option if an authentication * daemon will be authenticating mesh candidates. * * @NL80211_MESH_SETUP_USERSPACE_AMPE: Enable this option if an authentication * daemon will be securing peer link frames. AMPE is a secured version of * Mesh Peering Management (MPM) and is implemented with the assistance of * a userspace daemon. When this flag is set, the kernel will send peer * management frames to a userspace daemon that will implement AMPE * functionality (security capabilities selection, key confirmation, and * key management). When the flag is unset (default), the kernel can * autonomously complete (unsecured) mesh peering without the need of a * userspace daemon. * * @NL80211_MESH_SETUP_ENABLE_VENDOR_SYNC: Enable this option to use a * vendor specific synchronization method or disable it to use the default * neighbor offset synchronization * * @NL80211_MESH_SETUP_USERSPACE_MPM: Enable this option if userspace will * implement an MPM which handles peer allocation and state. * * @NL80211_MESH_SETUP_AUTH_PROTOCOL: Inform the kernel of the authentication * method (u8, as defined in IEEE 8.4.2.100.6, e.g. 0x1 for SAE). * Default is no authentication method required. * * @NL80211_MESH_SETUP_ATTR_MAX: highest possible mesh setup attribute number * * @__NL80211_MESH_SETUP_ATTR_AFTER_LAST: Internal use */ enum nl80211_mesh_setup_params { __NL80211_MESH_SETUP_INVALID, NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL, NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC, NL80211_MESH_SETUP_IE, NL80211_MESH_SETUP_USERSPACE_AUTH, NL80211_MESH_SETUP_USERSPACE_AMPE, NL80211_MESH_SETUP_ENABLE_VENDOR_SYNC, NL80211_MESH_SETUP_USERSPACE_MPM, NL80211_MESH_SETUP_AUTH_PROTOCOL, /* keep last */ __NL80211_MESH_SETUP_ATTR_AFTER_LAST, NL80211_MESH_SETUP_ATTR_MAX = __NL80211_MESH_SETUP_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_txq_attr - TX queue parameter attributes * @__NL80211_TXQ_ATTR_INVALID: Attribute number 0 is reserved * @NL80211_TXQ_ATTR_AC: AC identifier (NL80211_AC_*) * @NL80211_TXQ_ATTR_TXOP: Maximum burst time in units of 32 usecs, 0 meaning * disabled * @NL80211_TXQ_ATTR_CWMIN: Minimum contention window [a value of the form * 2^n-1 in the range 1..32767] * @NL80211_TXQ_ATTR_CWMAX: Maximum contention window [a value of the form * 2^n-1 in the range 1..32767] * @NL80211_TXQ_ATTR_AIFS: Arbitration interframe space [0..255] * @__NL80211_TXQ_ATTR_AFTER_LAST: Internal * @NL80211_TXQ_ATTR_MAX: Maximum TXQ attribute number */ enum nl80211_txq_attr { __NL80211_TXQ_ATTR_INVALID, NL80211_TXQ_ATTR_AC, NL80211_TXQ_ATTR_TXOP, NL80211_TXQ_ATTR_CWMIN, NL80211_TXQ_ATTR_CWMAX, NL80211_TXQ_ATTR_AIFS, /* keep last */ __NL80211_TXQ_ATTR_AFTER_LAST, NL80211_TXQ_ATTR_MAX = __NL80211_TXQ_ATTR_AFTER_LAST - 1 }; enum nl80211_ac { NL80211_AC_VO, NL80211_AC_VI, NL80211_AC_BE, NL80211_AC_BK, NL80211_NUM_ACS }; /* backward compat */ #define NL80211_TXQ_ATTR_QUEUE NL80211_TXQ_ATTR_AC #define NL80211_TXQ_Q_VO NL80211_AC_VO #define NL80211_TXQ_Q_VI NL80211_AC_VI #define NL80211_TXQ_Q_BE NL80211_AC_BE #define NL80211_TXQ_Q_BK NL80211_AC_BK /** * enum nl80211_channel_type - channel type * @NL80211_CHAN_NO_HT: 20 MHz, non-HT channel * @NL80211_CHAN_HT20: 20 MHz HT channel * @NL80211_CHAN_HT40MINUS: HT40 channel, secondary channel * below the control channel * @NL80211_CHAN_HT40PLUS: HT40 channel, secondary channel * above the control channel */ enum nl80211_channel_type { NL80211_CHAN_NO_HT, NL80211_CHAN_HT20, NL80211_CHAN_HT40MINUS, NL80211_CHAN_HT40PLUS }; /** * enum nl80211_key_mode - Key mode * * @NL80211_KEY_RX_TX: (Default) * Key can be used for Rx and Tx immediately * * The following modes can only be selected for unicast keys and when the * driver supports @NL80211_EXT_FEATURE_EXT_KEY_ID: * * @NL80211_KEY_NO_TX: Only allowed in combination with @NL80211_CMD_NEW_KEY: * Unicast key can only be used for Rx, Tx not allowed, yet * @NL80211_KEY_SET_TX: Only allowed in combination with @NL80211_CMD_SET_KEY: * The unicast key identified by idx and mac is cleared for Tx and becomes * the preferred Tx key for the station. */ enum nl80211_key_mode { NL80211_KEY_RX_TX, NL80211_KEY_NO_TX, NL80211_KEY_SET_TX }; /** * enum nl80211_chan_width - channel width definitions * * These values are used with the %NL80211_ATTR_CHANNEL_WIDTH * attribute. * * @NL80211_CHAN_WIDTH_20_NOHT: 20 MHz, non-HT channel * @NL80211_CHAN_WIDTH_20: 20 MHz HT channel * @NL80211_CHAN_WIDTH_40: 40 MHz channel, the %NL80211_ATTR_CENTER_FREQ1 * attribute must be provided as well * @NL80211_CHAN_WIDTH_80: 80 MHz channel, the %NL80211_ATTR_CENTER_FREQ1 * attribute must be provided as well * @NL80211_CHAN_WIDTH_80P80: 80+80 MHz channel, the %NL80211_ATTR_CENTER_FREQ1 * and %NL80211_ATTR_CENTER_FREQ2 attributes must be provided as well * @NL80211_CHAN_WIDTH_160: 160 MHz channel, the %NL80211_ATTR_CENTER_FREQ1 * attribute must be provided as well * @NL80211_CHAN_WIDTH_5: 5 MHz OFDM channel * @NL80211_CHAN_WIDTH_10: 10 MHz OFDM channel * @NL80211_CHAN_WIDTH_1: 1 MHz OFDM channel * @NL80211_CHAN_WIDTH_2: 2 MHz OFDM channel * @NL80211_CHAN_WIDTH_4: 4 MHz OFDM channel * @NL80211_CHAN_WIDTH_8: 8 MHz OFDM channel * @NL80211_CHAN_WIDTH_16: 16 MHz OFDM channel * @NL80211_CHAN_WIDTH_320: 320 MHz channel, the %NL80211_ATTR_CENTER_FREQ1 * attribute must be provided as well */ enum nl80211_chan_width { NL80211_CHAN_WIDTH_20_NOHT, NL80211_CHAN_WIDTH_20, NL80211_CHAN_WIDTH_40, NL80211_CHAN_WIDTH_80, NL80211_CHAN_WIDTH_80P80, NL80211_CHAN_WIDTH_160, NL80211_CHAN_WIDTH_5, NL80211_CHAN_WIDTH_10, NL80211_CHAN_WIDTH_1, NL80211_CHAN_WIDTH_2, NL80211_CHAN_WIDTH_4, NL80211_CHAN_WIDTH_8, NL80211_CHAN_WIDTH_16, NL80211_CHAN_WIDTH_320, }; /** * enum nl80211_bss_scan_width - control channel width for a BSS * * These values are used with the %NL80211_BSS_CHAN_WIDTH attribute. * * @NL80211_BSS_CHAN_WIDTH_20: control channel is 20 MHz wide or compatible * @NL80211_BSS_CHAN_WIDTH_10: control channel is 10 MHz wide * @NL80211_BSS_CHAN_WIDTH_5: control channel is 5 MHz wide * @NL80211_BSS_CHAN_WIDTH_1: control channel is 1 MHz wide * @NL80211_BSS_CHAN_WIDTH_2: control channel is 2 MHz wide */ enum nl80211_bss_scan_width { NL80211_BSS_CHAN_WIDTH_20, NL80211_BSS_CHAN_WIDTH_10, NL80211_BSS_CHAN_WIDTH_5, NL80211_BSS_CHAN_WIDTH_1, NL80211_BSS_CHAN_WIDTH_2, }; /** * enum nl80211_bss - netlink attributes for a BSS * * @__NL80211_BSS_INVALID: invalid * @NL80211_BSS_BSSID: BSSID of the BSS (6 octets) * @NL80211_BSS_FREQUENCY: frequency in MHz (u32) * @NL80211_BSS_TSF: TSF of the received probe response/beacon (u64) * (if @NL80211_BSS_PRESP_DATA is present then this is known to be * from a probe response, otherwise it may be from the same beacon * that the NL80211_BSS_BEACON_TSF will be from) * @NL80211_BSS_BEACON_INTERVAL: beacon interval of the (I)BSS (u16) * @NL80211_BSS_CAPABILITY: capability field (CPU order, u16) * @NL80211_BSS_INFORMATION_ELEMENTS: binary attribute containing the * raw information elements from the probe response/beacon (bin); * if the %NL80211_BSS_BEACON_IES attribute is present and the data is * different then the IEs here are from a Probe Response frame; otherwise * they are from a Beacon frame. * However, if the driver does not indicate the source of the IEs, these * IEs may be from either frame subtype. * If present, the @NL80211_BSS_PRESP_DATA attribute indicates that the * data here is known to be from a probe response, without any heuristics. * @NL80211_BSS_SIGNAL_MBM: signal strength of probe response/beacon * in mBm (100 * dBm) (s32) * @NL80211_BSS_SIGNAL_UNSPEC: signal strength of the probe response/beacon * in unspecified units, scaled to 0..100 (u8) * @NL80211_BSS_STATUS: status, if this BSS is "used" * @NL80211_BSS_SEEN_MS_AGO: age of this BSS entry in ms * @NL80211_BSS_BEACON_IES: binary attribute containing the raw information * elements from a Beacon frame (bin); not present if no Beacon frame has * yet been received * @NL80211_BSS_CHAN_WIDTH: channel width of the control channel * (u32, enum nl80211_bss_scan_width) * @NL80211_BSS_BEACON_TSF: TSF of the last received beacon (u64) * (not present if no beacon frame has been received yet) * @NL80211_BSS_PRESP_DATA: the data in @NL80211_BSS_INFORMATION_ELEMENTS and * @NL80211_BSS_TSF is known to be from a probe response (flag attribute) * @NL80211_BSS_LAST_SEEN_BOOTTIME: CLOCK_BOOTTIME timestamp when this entry * was last updated by a received frame. The value is expected to be * accurate to about 10ms. (u64, nanoseconds) * @NL80211_BSS_PAD: attribute used for padding for 64-bit alignment * @NL80211_BSS_PARENT_TSF: the time at the start of reception of the first * octet of the timestamp field of the last beacon/probe received for * this BSS. The time is the TSF of the BSS specified by * @NL80211_BSS_PARENT_BSSID. (u64). * @NL80211_BSS_PARENT_BSSID: the BSS according to which @NL80211_BSS_PARENT_TSF * is set. * @NL80211_BSS_CHAIN_SIGNAL: per-chain signal strength of last BSS update. * Contains a nested array of signal strength attributes (u8, dBm), * using the nesting index as the antenna number. * @NL80211_BSS_FREQUENCY_OFFSET: frequency offset in KHz * @NL80211_BSS_MLO_LINK_ID: MLO link ID of the BSS (u8). * @NL80211_BSS_MLD_ADDR: MLD address of this BSS if connected to it. * @__NL80211_BSS_AFTER_LAST: internal * @NL80211_BSS_MAX: highest BSS attribute */ enum nl80211_bss { __NL80211_BSS_INVALID, NL80211_BSS_BSSID, NL80211_BSS_FREQUENCY, NL80211_BSS_TSF, NL80211_BSS_BEACON_INTERVAL, NL80211_BSS_CAPABILITY, NL80211_BSS_INFORMATION_ELEMENTS, NL80211_BSS_SIGNAL_MBM, NL80211_BSS_SIGNAL_UNSPEC, NL80211_BSS_STATUS, NL80211_BSS_SEEN_MS_AGO, NL80211_BSS_BEACON_IES, NL80211_BSS_CHAN_WIDTH, NL80211_BSS_BEACON_TSF, NL80211_BSS_PRESP_DATA, NL80211_BSS_LAST_SEEN_BOOTTIME, NL80211_BSS_PAD, NL80211_BSS_PARENT_TSF, NL80211_BSS_PARENT_BSSID, NL80211_BSS_CHAIN_SIGNAL, NL80211_BSS_FREQUENCY_OFFSET, NL80211_BSS_MLO_LINK_ID, NL80211_BSS_MLD_ADDR, /* keep last */ __NL80211_BSS_AFTER_LAST, NL80211_BSS_MAX = __NL80211_BSS_AFTER_LAST - 1 }; /** * enum nl80211_bss_status - BSS "status" * @NL80211_BSS_STATUS_AUTHENTICATED: Authenticated with this BSS. * Note that this is no longer used since cfg80211 no longer * keeps track of whether or not authentication was done with * a given BSS. * @NL80211_BSS_STATUS_ASSOCIATED: Associated with this BSS. * @NL80211_BSS_STATUS_IBSS_JOINED: Joined to this IBSS. * * The BSS status is a BSS attribute in scan dumps, which * indicates the status the interface has wrt. this BSS. */ enum nl80211_bss_status { NL80211_BSS_STATUS_AUTHENTICATED, NL80211_BSS_STATUS_ASSOCIATED, NL80211_BSS_STATUS_IBSS_JOINED, }; /** * enum nl80211_auth_type - AuthenticationType * * @NL80211_AUTHTYPE_OPEN_SYSTEM: Open System authentication * @NL80211_AUTHTYPE_SHARED_KEY: Shared Key authentication (WEP only) * @NL80211_AUTHTYPE_FT: Fast BSS Transition (IEEE 802.11r) * @NL80211_AUTHTYPE_NETWORK_EAP: Network EAP (some Cisco APs and mainly LEAP) * @NL80211_AUTHTYPE_SAE: Simultaneous authentication of equals * @NL80211_AUTHTYPE_FILS_SK: Fast Initial Link Setup shared key * @NL80211_AUTHTYPE_FILS_SK_PFS: Fast Initial Link Setup shared key with PFS * @NL80211_AUTHTYPE_FILS_PK: Fast Initial Link Setup public key * @__NL80211_AUTHTYPE_NUM: internal * @NL80211_AUTHTYPE_MAX: maximum valid auth algorithm * @NL80211_AUTHTYPE_AUTOMATIC: determine automatically (if necessary by * trying multiple times); this is invalid in netlink -- leave out * the attribute for this on CONNECT commands. */ enum nl80211_auth_type { NL80211_AUTHTYPE_OPEN_SYSTEM, NL80211_AUTHTYPE_SHARED_KEY, NL80211_AUTHTYPE_FT, NL80211_AUTHTYPE_NETWORK_EAP, NL80211_AUTHTYPE_SAE, NL80211_AUTHTYPE_FILS_SK, NL80211_AUTHTYPE_FILS_SK_PFS, NL80211_AUTHTYPE_FILS_PK, /* keep last */ __NL80211_AUTHTYPE_NUM, NL80211_AUTHTYPE_MAX = __NL80211_AUTHTYPE_NUM - 1, NL80211_AUTHTYPE_AUTOMATIC }; /** * enum nl80211_key_type - Key Type * @NL80211_KEYTYPE_GROUP: Group (broadcast/multicast) key * @NL80211_KEYTYPE_PAIRWISE: Pairwise (unicast/individual) key * @NL80211_KEYTYPE_PEERKEY: PeerKey (DLS) * @NUM_NL80211_KEYTYPES: number of defined key types */ enum nl80211_key_type { NL80211_KEYTYPE_GROUP, NL80211_KEYTYPE_PAIRWISE, NL80211_KEYTYPE_PEERKEY, NUM_NL80211_KEYTYPES }; /** * enum nl80211_mfp - Management frame protection state * @NL80211_MFP_NO: Management frame protection not used * @NL80211_MFP_REQUIRED: Management frame protection required * @NL80211_MFP_OPTIONAL: Management frame protection is optional */ enum nl80211_mfp { NL80211_MFP_NO, NL80211_MFP_REQUIRED, NL80211_MFP_OPTIONAL, }; enum nl80211_wpa_versions { NL80211_WPA_VERSION_1 = 1 << 0, NL80211_WPA_VERSION_2 = 1 << 1, NL80211_WPA_VERSION_3 = 1 << 2, }; /** * enum nl80211_key_default_types - key default types * @__NL80211_KEY_DEFAULT_TYPE_INVALID: invalid * @NL80211_KEY_DEFAULT_TYPE_UNICAST: key should be used as default * unicast key * @NL80211_KEY_DEFAULT_TYPE_MULTICAST: key should be used as default * multicast key * @NUM_NL80211_KEY_DEFAULT_TYPES: number of default types */ enum nl80211_key_default_types { __NL80211_KEY_DEFAULT_TYPE_INVALID, NL80211_KEY_DEFAULT_TYPE_UNICAST, NL80211_KEY_DEFAULT_TYPE_MULTICAST, NUM_NL80211_KEY_DEFAULT_TYPES }; /** * enum nl80211_key_attributes - key attributes * @__NL80211_KEY_INVALID: invalid * @NL80211_KEY_DATA: (temporal) key data; for TKIP this consists of * 16 bytes encryption key followed by 8 bytes each for TX and RX MIC * keys * @NL80211_KEY_IDX: key ID (u8, 0-3) * @NL80211_KEY_CIPHER: key cipher suite (u32, as defined by IEEE 802.11 * section 7.3.2.25.1, e.g. 0x000FAC04) * @NL80211_KEY_SEQ: transmit key sequence number (IV/PN) for TKIP and * CCMP keys, each six bytes in little endian * @NL80211_KEY_DEFAULT: flag indicating default key * @NL80211_KEY_DEFAULT_MGMT: flag indicating default management key * @NL80211_KEY_TYPE: the key type from enum nl80211_key_type, if not * specified the default depends on whether a MAC address was * given with the command using the key or not (u32) * @NL80211_KEY_DEFAULT_TYPES: A nested attribute containing flags * attributes, specifying what a key should be set as default as. * See &enum nl80211_key_default_types. * @NL80211_KEY_MODE: the mode from enum nl80211_key_mode. * Defaults to @NL80211_KEY_RX_TX. * @NL80211_KEY_DEFAULT_BEACON: flag indicating default Beacon frame key * * @__NL80211_KEY_AFTER_LAST: internal * @NL80211_KEY_MAX: highest key attribute */ enum nl80211_key_attributes { __NL80211_KEY_INVALID, NL80211_KEY_DATA, NL80211_KEY_IDX, NL80211_KEY_CIPHER, NL80211_KEY_SEQ, NL80211_KEY_DEFAULT, NL80211_KEY_DEFAULT_MGMT, NL80211_KEY_TYPE, NL80211_KEY_DEFAULT_TYPES, NL80211_KEY_MODE, NL80211_KEY_DEFAULT_BEACON, /* keep last */ __NL80211_KEY_AFTER_LAST, NL80211_KEY_MAX = __NL80211_KEY_AFTER_LAST - 1 }; /** * enum nl80211_tx_rate_attributes - TX rate set attributes * @__NL80211_TXRATE_INVALID: invalid * @NL80211_TXRATE_LEGACY: Legacy (non-MCS) rates allowed for TX rate selection * in an array of rates as defined in IEEE 802.11 7.3.2.2 (u8 values with * 1 = 500 kbps) but without the IE length restriction (at most * %NL80211_MAX_SUPP_RATES in a single array). * @NL80211_TXRATE_HT: HT (MCS) rates allowed for TX rate selection * in an array of MCS numbers. * @NL80211_TXRATE_VHT: VHT rates allowed for TX rate selection, * see &struct nl80211_txrate_vht * @NL80211_TXRATE_GI: configure GI, see &enum nl80211_txrate_gi * @NL80211_TXRATE_HE: HE rates allowed for TX rate selection, * see &struct nl80211_txrate_he * @NL80211_TXRATE_HE_GI: configure HE GI, 0.8us, 1.6us and 3.2us. * @NL80211_TXRATE_HE_LTF: configure HE LTF, 1XLTF, 2XLTF and 4XLTF. * @__NL80211_TXRATE_AFTER_LAST: internal * @NL80211_TXRATE_MAX: highest TX rate attribute */ enum nl80211_tx_rate_attributes { __NL80211_TXRATE_INVALID, NL80211_TXRATE_LEGACY, NL80211_TXRATE_HT, NL80211_TXRATE_VHT, NL80211_TXRATE_GI, NL80211_TXRATE_HE, NL80211_TXRATE_HE_GI, NL80211_TXRATE_HE_LTF, /* keep last */ __NL80211_TXRATE_AFTER_LAST, NL80211_TXRATE_MAX = __NL80211_TXRATE_AFTER_LAST - 1 }; #define NL80211_TXRATE_MCS NL80211_TXRATE_HT #define NL80211_VHT_NSS_MAX 8 /** * struct nl80211_txrate_vht - VHT MCS/NSS txrate bitmap * @mcs: MCS bitmap table for each NSS (array index 0 for 1 stream, etc.) */ struct nl80211_txrate_vht { __u16 mcs[NL80211_VHT_NSS_MAX]; }; #define NL80211_HE_NSS_MAX 8 /** * struct nl80211_txrate_he - HE MCS/NSS txrate bitmap * @mcs: MCS bitmap table for each NSS (array index 0 for 1 stream, etc.) */ struct nl80211_txrate_he { __u16 mcs[NL80211_HE_NSS_MAX]; }; enum nl80211_txrate_gi { NL80211_TXRATE_DEFAULT_GI, NL80211_TXRATE_FORCE_SGI, NL80211_TXRATE_FORCE_LGI, }; /** * enum nl80211_band - Frequency band * @NL80211_BAND_2GHZ: 2.4 GHz ISM band * @NL80211_BAND_5GHZ: around 5 GHz band (4.9 - 5.7 GHz) * @NL80211_BAND_60GHZ: around 60 GHz band (58.32 - 69.12 GHz) * @NL80211_BAND_6GHZ: around 6 GHz band (5.9 - 7.2 GHz) * @NL80211_BAND_S1GHZ: around 900MHz, supported by S1G PHYs * @NL80211_BAND_LC: light communication band (placeholder) * @NUM_NL80211_BANDS: number of bands, avoid using this in userspace * since newer kernel versions may support more bands */ enum nl80211_band { NL80211_BAND_2GHZ, NL80211_BAND_5GHZ, NL80211_BAND_60GHZ, NL80211_BAND_6GHZ, NL80211_BAND_S1GHZ, NL80211_BAND_LC, NUM_NL80211_BANDS, }; /** * enum nl80211_ps_state - powersave state * @NL80211_PS_DISABLED: powersave is disabled * @NL80211_PS_ENABLED: powersave is enabled */ enum nl80211_ps_state { NL80211_PS_DISABLED, NL80211_PS_ENABLED, }; /** * enum nl80211_attr_cqm - connection quality monitor attributes * @__NL80211_ATTR_CQM_INVALID: invalid * @NL80211_ATTR_CQM_RSSI_THOLD: RSSI threshold in dBm. This value specifies * the threshold for the RSSI level at which an event will be sent. Zero * to disable. Alternatively, if %NL80211_EXT_FEATURE_CQM_RSSI_LIST is * set, multiple values can be supplied as a low-to-high sorted array of * threshold values in dBm. Events will be sent when the RSSI value * crosses any of the thresholds. * @NL80211_ATTR_CQM_RSSI_HYST: RSSI hysteresis in dBm. This value specifies * the minimum amount the RSSI level must change after an event before a * new event may be issued (to reduce effects of RSSI oscillation). * @NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT: RSSI threshold event * @NL80211_ATTR_CQM_PKT_LOSS_EVENT: a u32 value indicating that this many * consecutive packets were not acknowledged by the peer * @NL80211_ATTR_CQM_TXE_RATE: TX error rate in %. Minimum % of TX failures * during the given %NL80211_ATTR_CQM_TXE_INTVL before an * %NL80211_CMD_NOTIFY_CQM with reported %NL80211_ATTR_CQM_TXE_RATE and * %NL80211_ATTR_CQM_TXE_PKTS is generated. * @NL80211_ATTR_CQM_TXE_PKTS: number of attempted packets in a given * %NL80211_ATTR_CQM_TXE_INTVL before %NL80211_ATTR_CQM_TXE_RATE is * checked. * @NL80211_ATTR_CQM_TXE_INTVL: interval in seconds. Specifies the periodic * interval in which %NL80211_ATTR_CQM_TXE_PKTS and * %NL80211_ATTR_CQM_TXE_RATE must be satisfied before generating an * %NL80211_CMD_NOTIFY_CQM. Set to 0 to turn off TX error reporting. * @NL80211_ATTR_CQM_BEACON_LOSS_EVENT: flag attribute that's set in a beacon * loss event * @NL80211_ATTR_CQM_RSSI_LEVEL: the RSSI value in dBm that triggered the * RSSI threshold event. * @__NL80211_ATTR_CQM_AFTER_LAST: internal * @NL80211_ATTR_CQM_MAX: highest key attribute */ enum nl80211_attr_cqm { __NL80211_ATTR_CQM_INVALID, NL80211_ATTR_CQM_RSSI_THOLD, NL80211_ATTR_CQM_RSSI_HYST, NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT, NL80211_ATTR_CQM_PKT_LOSS_EVENT, NL80211_ATTR_CQM_TXE_RATE, NL80211_ATTR_CQM_TXE_PKTS, NL80211_ATTR_CQM_TXE_INTVL, NL80211_ATTR_CQM_BEACON_LOSS_EVENT, NL80211_ATTR_CQM_RSSI_LEVEL, /* keep last */ __NL80211_ATTR_CQM_AFTER_LAST, NL80211_ATTR_CQM_MAX = __NL80211_ATTR_CQM_AFTER_LAST - 1 }; /** * enum nl80211_cqm_rssi_threshold_event - RSSI threshold event * @NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW: The RSSI level is lower than the * configured threshold * @NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH: The RSSI is higher than the * configured threshold * @NL80211_CQM_RSSI_BEACON_LOSS_EVENT: (reserved, never sent) */ enum nl80211_cqm_rssi_threshold_event { NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW, NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH, NL80211_CQM_RSSI_BEACON_LOSS_EVENT, }; /** * enum nl80211_tx_power_setting - TX power adjustment * @NL80211_TX_POWER_AUTOMATIC: automatically determine transmit power * @NL80211_TX_POWER_LIMITED: limit TX power by the mBm parameter * @NL80211_TX_POWER_FIXED: fix TX power to the mBm parameter */ enum nl80211_tx_power_setting { NL80211_TX_POWER_AUTOMATIC, NL80211_TX_POWER_LIMITED, NL80211_TX_POWER_FIXED, }; /** * enum nl80211_tid_config - TID config state * @NL80211_TID_CONFIG_ENABLE: Enable config for the TID * @NL80211_TID_CONFIG_DISABLE: Disable config for the TID */ enum nl80211_tid_config { NL80211_TID_CONFIG_ENABLE, NL80211_TID_CONFIG_DISABLE, }; /* enum nl80211_tx_rate_setting - TX rate configuration type * @NL80211_TX_RATE_AUTOMATIC: automatically determine TX rate * @NL80211_TX_RATE_LIMITED: limit the TX rate by the TX rate parameter * @NL80211_TX_RATE_FIXED: fix TX rate to the TX rate parameter */ enum nl80211_tx_rate_setting { NL80211_TX_RATE_AUTOMATIC, NL80211_TX_RATE_LIMITED, NL80211_TX_RATE_FIXED, }; /* enum nl80211_tid_config_attr - TID specific configuration. * @NL80211_TID_CONFIG_ATTR_PAD: pad attribute for 64-bit values * @NL80211_TID_CONFIG_ATTR_VIF_SUPP: a bitmap (u64) of attributes supported * for per-vif configuration; doesn't list the ones that are generic * (%NL80211_TID_CONFIG_ATTR_TIDS, %NL80211_TID_CONFIG_ATTR_OVERRIDE). * @NL80211_TID_CONFIG_ATTR_PEER_SUPP: same as the previous per-vif one, but * per peer instead. * @NL80211_TID_CONFIG_ATTR_OVERRIDE: flag attribue, if set indicates * that the new configuration overrides all previous peer * configurations, otherwise previous peer specific configurations * should be left untouched. * @NL80211_TID_CONFIG_ATTR_TIDS: a bitmask value of TIDs (bit 0 to 7) * Its type is u16. * @NL80211_TID_CONFIG_ATTR_NOACK: Configure ack policy for the TID. * specified in %NL80211_TID_CONFIG_ATTR_TID. see %enum nl80211_tid_config. * Its type is u8. * @NL80211_TID_CONFIG_ATTR_RETRY_SHORT: Number of retries used with data frame * transmission, user-space sets this configuration in * &NL80211_CMD_SET_TID_CONFIG. It is u8 type, min value is 1 and * the max value is advertised by the driver in this attribute on * output in wiphy capabilities. * @NL80211_TID_CONFIG_ATTR_RETRY_LONG: Number of retries used with data frame * transmission, user-space sets this configuration in * &NL80211_CMD_SET_TID_CONFIG. Its type is u8, min value is 1 and * the max value is advertised by the driver in this attribute on * output in wiphy capabilities. * @NL80211_TID_CONFIG_ATTR_AMPDU_CTRL: Enable/Disable MPDU aggregation * for the TIDs specified in %NL80211_TID_CONFIG_ATTR_TIDS. * Its type is u8, using the values from &nl80211_tid_config. * @NL80211_TID_CONFIG_ATTR_RTSCTS_CTRL: Enable/Disable RTS_CTS for the TIDs * specified in %NL80211_TID_CONFIG_ATTR_TIDS. It is u8 type, using * the values from &nl80211_tid_config. * @NL80211_TID_CONFIG_ATTR_AMSDU_CTRL: Enable/Disable MSDU aggregation * for the TIDs specified in %NL80211_TID_CONFIG_ATTR_TIDS. * Its type is u8, using the values from &nl80211_tid_config. * @NL80211_TID_CONFIG_ATTR_TX_RATE_TYPE: This attribute will be useful * to notfiy the driver that what type of txrate should be used * for the TIDs specified in %NL80211_TID_CONFIG_ATTR_TIDS. using * the values form &nl80211_tx_rate_setting. * @NL80211_TID_CONFIG_ATTR_TX_RATE: Data frame TX rate mask should be applied * with the parameters passed through %NL80211_ATTR_TX_RATES. * configuration is applied to the data frame for the tid to that connected * station. */ enum nl80211_tid_config_attr { __NL80211_TID_CONFIG_ATTR_INVALID, NL80211_TID_CONFIG_ATTR_PAD, NL80211_TID_CONFIG_ATTR_VIF_SUPP, NL80211_TID_CONFIG_ATTR_PEER_SUPP, NL80211_TID_CONFIG_ATTR_OVERRIDE, NL80211_TID_CONFIG_ATTR_TIDS, NL80211_TID_CONFIG_ATTR_NOACK, NL80211_TID_CONFIG_ATTR_RETRY_SHORT, NL80211_TID_CONFIG_ATTR_RETRY_LONG, NL80211_TID_CONFIG_ATTR_AMPDU_CTRL, NL80211_TID_CONFIG_ATTR_RTSCTS_CTRL, NL80211_TID_CONFIG_ATTR_AMSDU_CTRL, NL80211_TID_CONFIG_ATTR_TX_RATE_TYPE, NL80211_TID_CONFIG_ATTR_TX_RATE, /* keep last */ __NL80211_TID_CONFIG_ATTR_AFTER_LAST, NL80211_TID_CONFIG_ATTR_MAX = __NL80211_TID_CONFIG_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_packet_pattern_attr - packet pattern attribute * @__NL80211_PKTPAT_INVALID: invalid number for nested attribute * @NL80211_PKTPAT_PATTERN: the pattern, values where the mask has * a zero bit are ignored * @NL80211_PKTPAT_MASK: pattern mask, must be long enough to have * a bit for each byte in the pattern. The lowest-order bit corresponds * to the first byte of the pattern, but the bytes of the pattern are * in a little-endian-like format, i.e. the 9th byte of the pattern * corresponds to the lowest-order bit in the second byte of the mask. * For example: The match 00:xx:00:00:xx:00:00:00:00:xx:xx:xx (where * xx indicates "don't care") would be represented by a pattern of * twelve zero bytes, and a mask of "0xed,0x01". * Note that the pattern matching is done as though frames were not * 802.11 frames but 802.3 frames, i.e. the frame is fully unpacked * first (including SNAP header unpacking) and then matched. * @NL80211_PKTPAT_OFFSET: packet offset, pattern is matched after * these fixed number of bytes of received packet * @NUM_NL80211_PKTPAT: number of attributes * @MAX_NL80211_PKTPAT: max attribute number */ enum nl80211_packet_pattern_attr { __NL80211_PKTPAT_INVALID, NL80211_PKTPAT_MASK, NL80211_PKTPAT_PATTERN, NL80211_PKTPAT_OFFSET, NUM_NL80211_PKTPAT, MAX_NL80211_PKTPAT = NUM_NL80211_PKTPAT - 1, }; /** * struct nl80211_pattern_support - packet pattern support information * @max_patterns: maximum number of patterns supported * @min_pattern_len: minimum length of each pattern * @max_pattern_len: maximum length of each pattern * @max_pkt_offset: maximum Rx packet offset * * This struct is carried in %NL80211_WOWLAN_TRIG_PKT_PATTERN when * that is part of %NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED or in * %NL80211_ATTR_COALESCE_RULE_PKT_PATTERN when that is part of * %NL80211_ATTR_COALESCE_RULE in the capability information given * by the kernel to userspace. */ struct nl80211_pattern_support { __u32 max_patterns; __u32 min_pattern_len; __u32 max_pattern_len; __u32 max_pkt_offset; } __attribute__((packed)); /* only for backward compatibility */ #define __NL80211_WOWLAN_PKTPAT_INVALID __NL80211_PKTPAT_INVALID #define NL80211_WOWLAN_PKTPAT_MASK NL80211_PKTPAT_MASK #define NL80211_WOWLAN_PKTPAT_PATTERN NL80211_PKTPAT_PATTERN #define NL80211_WOWLAN_PKTPAT_OFFSET NL80211_PKTPAT_OFFSET #define NUM_NL80211_WOWLAN_PKTPAT NUM_NL80211_PKTPAT #define MAX_NL80211_WOWLAN_PKTPAT MAX_NL80211_PKTPAT #define nl80211_wowlan_pattern_support nl80211_pattern_support /** * enum nl80211_wowlan_triggers - WoWLAN trigger definitions * @__NL80211_WOWLAN_TRIG_INVALID: invalid number for nested attributes * @NL80211_WOWLAN_TRIG_ANY: wake up on any activity, do not really put * the chip into a special state -- works best with chips that have * support for low-power operation already (flag) * Note that this mode is incompatible with all of the others, if * any others are even supported by the device. * @NL80211_WOWLAN_TRIG_DISCONNECT: wake up on disconnect, the way disconnect * is detected is implementation-specific (flag) * @NL80211_WOWLAN_TRIG_MAGIC_PKT: wake up on magic packet (6x 0xff, followed * by 16 repetitions of MAC addr, anywhere in payload) (flag) * @NL80211_WOWLAN_TRIG_PKT_PATTERN: wake up on the specified packet patterns * which are passed in an array of nested attributes, each nested attribute * defining a with attributes from &struct nl80211_wowlan_trig_pkt_pattern. * Each pattern defines a wakeup packet. Packet offset is associated with * each pattern which is used while matching the pattern. The matching is * done on the MSDU, i.e. as though the packet was an 802.3 packet, so the * pattern matching is done after the packet is converted to the MSDU. * * In %NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED, it is a binary attribute * carrying a &struct nl80211_pattern_support. * * When reporting wakeup. it is a u32 attribute containing the 0-based * index of the pattern that caused the wakeup, in the patterns passed * to the kernel when configuring. * @NL80211_WOWLAN_TRIG_GTK_REKEY_SUPPORTED: Not a real trigger, and cannot be * used when setting, used only to indicate that GTK rekeying is supported * by the device (flag) * @NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE: wake up on GTK rekey failure (if * done by the device) (flag) * @NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST: wake up on EAP Identity Request * packet (flag) * @NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE: wake up on 4-way handshake (flag) * @NL80211_WOWLAN_TRIG_RFKILL_RELEASE: wake up when rfkill is released * (on devices that have rfkill in the device) (flag) * @NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211: For wakeup reporting only, contains * the 802.11 packet that caused the wakeup, e.g. a deauth frame. The frame * may be truncated, the @NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211_LEN * attribute contains the original length. * @NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211_LEN: Original length of the 802.11 * packet, may be bigger than the @NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211 * attribute if the packet was truncated somewhere. * @NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023: For wakeup reporting only, contains the * 802.11 packet that caused the wakeup, e.g. a magic packet. The frame may * be truncated, the @NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023_LEN attribute * contains the original length. * @NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023_LEN: Original length of the 802.3 * packet, may be bigger than the @NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023 * attribute if the packet was truncated somewhere. * @NL80211_WOWLAN_TRIG_TCP_CONNECTION: TCP connection wake, see DOC section * "TCP connection wakeup" for more details. This is a nested attribute * containing the exact information for establishing and keeping alive * the TCP connection. * @NL80211_WOWLAN_TRIG_TCP_WAKEUP_MATCH: For wakeup reporting only, the * wakeup packet was received on the TCP connection * @NL80211_WOWLAN_TRIG_WAKEUP_TCP_CONNLOST: For wakeup reporting only, the * TCP connection was lost or failed to be established * @NL80211_WOWLAN_TRIG_WAKEUP_TCP_NOMORETOKENS: For wakeup reporting only, * the TCP connection ran out of tokens to use for data to send to the * service * @NL80211_WOWLAN_TRIG_NET_DETECT: wake up when a configured network * is detected. This is a nested attribute that contains the * same attributes used with @NL80211_CMD_START_SCHED_SCAN. It * specifies how the scan is performed (e.g. the interval, the * channels to scan and the initial delay) as well as the scan * results that will trigger a wake (i.e. the matchsets). This * attribute is also sent in a response to * @NL80211_CMD_GET_WIPHY, indicating the number of match sets * supported by the driver (u32). * @NL80211_WOWLAN_TRIG_NET_DETECT_RESULTS: nested attribute * containing an array with information about what triggered the * wake up. If no elements are present in the array, it means * that the information is not available. If more than one * element is present, it means that more than one match * occurred. * Each element in the array is a nested attribute that contains * one optional %NL80211_ATTR_SSID attribute and one optional * %NL80211_ATTR_SCAN_FREQUENCIES attribute. At least one of * these attributes must be present. If * %NL80211_ATTR_SCAN_FREQUENCIES contains more than one * frequency, it means that the match occurred in more than one * channel. * @NUM_NL80211_WOWLAN_TRIG: number of wake on wireless triggers * @MAX_NL80211_WOWLAN_TRIG: highest wowlan trigger attribute number * * These nested attributes are used to configure the wakeup triggers and * to report the wakeup reason(s). */ enum nl80211_wowlan_triggers { __NL80211_WOWLAN_TRIG_INVALID, NL80211_WOWLAN_TRIG_ANY, NL80211_WOWLAN_TRIG_DISCONNECT, NL80211_WOWLAN_TRIG_MAGIC_PKT, NL80211_WOWLAN_TRIG_PKT_PATTERN, NL80211_WOWLAN_TRIG_GTK_REKEY_SUPPORTED, NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE, NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST, NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE, NL80211_WOWLAN_TRIG_RFKILL_RELEASE, NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211, NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211_LEN, NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023, NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023_LEN, NL80211_WOWLAN_TRIG_TCP_CONNECTION, NL80211_WOWLAN_TRIG_WAKEUP_TCP_MATCH, NL80211_WOWLAN_TRIG_WAKEUP_TCP_CONNLOST, NL80211_WOWLAN_TRIG_WAKEUP_TCP_NOMORETOKENS, NL80211_WOWLAN_TRIG_NET_DETECT, NL80211_WOWLAN_TRIG_NET_DETECT_RESULTS, /* keep last */ NUM_NL80211_WOWLAN_TRIG, MAX_NL80211_WOWLAN_TRIG = NUM_NL80211_WOWLAN_TRIG - 1 }; /** * DOC: TCP connection wakeup * * Some devices can establish a TCP connection in order to be woken up by a * packet coming in from outside their network segment, or behind NAT. If * configured, the device will establish a TCP connection to the given * service, and periodically send data to that service. The first data * packet is usually transmitted after SYN/ACK, also ACKing the SYN/ACK. * The data packets can optionally include a (little endian) sequence * number (in the TCP payload!) that is generated by the device, and, also * optionally, a token from a list of tokens. This serves as a keep-alive * with the service, and for NATed connections, etc. * * During this keep-alive period, the server doesn't send any data to the * client. When receiving data, it is compared against the wakeup pattern * (and mask) and if it matches, the host is woken up. Similarly, if the * connection breaks or cannot be established to start with, the host is * also woken up. * * Developer's note: ARP offload is required for this, otherwise TCP * response packets might not go through correctly. */ /** * struct nl80211_wowlan_tcp_data_seq - WoWLAN TCP data sequence * @start: starting value * @offset: offset of sequence number in packet * @len: length of the sequence value to write, 1 through 4 * * Note: don't confuse with the TCP sequence number(s), this is for the * keepalive packet payload. The actual value is written into the packet * in little endian. */ struct nl80211_wowlan_tcp_data_seq { __u32 start, offset, len; }; /** * struct nl80211_wowlan_tcp_data_token - WoWLAN TCP data token config * @offset: offset of token in packet * @len: length of each token * @token_stream: stream of data to be used for the tokens, the length must * be a multiple of @len for this to make sense */ struct nl80211_wowlan_tcp_data_token { __u32 offset, len; __u8 token_stream[]; }; /** * struct nl80211_wowlan_tcp_data_token_feature - data token features * @min_len: minimum token length * @max_len: maximum token length * @bufsize: total available token buffer size (max size of @token_stream) */ struct nl80211_wowlan_tcp_data_token_feature { __u32 min_len, max_len, bufsize; }; /** * enum nl80211_wowlan_tcp_attrs - WoWLAN TCP connection parameters * @__NL80211_WOWLAN_TCP_INVALID: invalid number for nested attributes * @NL80211_WOWLAN_TCP_SRC_IPV4: source IPv4 address (in network byte order) * @NL80211_WOWLAN_TCP_DST_IPV4: destination IPv4 address * (in network byte order) * @NL80211_WOWLAN_TCP_DST_MAC: destination MAC address, this is given because * route lookup when configured might be invalid by the time we suspend, * and doing a route lookup when suspending is no longer possible as it * might require ARP querying. * @NL80211_WOWLAN_TCP_SRC_PORT: source port (u16); optional, if not given a * socket and port will be allocated * @NL80211_WOWLAN_TCP_DST_PORT: destination port (u16) * @NL80211_WOWLAN_TCP_DATA_PAYLOAD: data packet payload, at least one byte. * For feature advertising, a u32 attribute holding the maximum length * of the data payload. * @NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ: data packet sequence configuration * (if desired), a &struct nl80211_wowlan_tcp_data_seq. For feature * advertising it is just a flag * @NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN: data packet token configuration, * see &struct nl80211_wowlan_tcp_data_token and for advertising see * &struct nl80211_wowlan_tcp_data_token_feature. * @NL80211_WOWLAN_TCP_DATA_INTERVAL: data interval in seconds, maximum * interval in feature advertising (u32) * @NL80211_WOWLAN_TCP_WAKE_PAYLOAD: wake packet payload, for advertising a * u32 attribute holding the maximum length * @NL80211_WOWLAN_TCP_WAKE_MASK: Wake packet payload mask, not used for * feature advertising. The mask works like @NL80211_PKTPAT_MASK * but on the TCP payload only. * @NUM_NL80211_WOWLAN_TCP: number of TCP attributes * @MAX_NL80211_WOWLAN_TCP: highest attribute number */ enum nl80211_wowlan_tcp_attrs { __NL80211_WOWLAN_TCP_INVALID, NL80211_WOWLAN_TCP_SRC_IPV4, NL80211_WOWLAN_TCP_DST_IPV4, NL80211_WOWLAN_TCP_DST_MAC, NL80211_WOWLAN_TCP_SRC_PORT, NL80211_WOWLAN_TCP_DST_PORT, NL80211_WOWLAN_TCP_DATA_PAYLOAD, NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ, NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN, NL80211_WOWLAN_TCP_DATA_INTERVAL, NL80211_WOWLAN_TCP_WAKE_PAYLOAD, NL80211_WOWLAN_TCP_WAKE_MASK, /* keep last */ NUM_NL80211_WOWLAN_TCP, MAX_NL80211_WOWLAN_TCP = NUM_NL80211_WOWLAN_TCP - 1 }; /** * struct nl80211_coalesce_rule_support - coalesce rule support information * @max_rules: maximum number of rules supported * @pat: packet pattern support information * @max_delay: maximum supported coalescing delay in msecs * * This struct is carried in %NL80211_ATTR_COALESCE_RULE in the * capability information given by the kernel to userspace. */ struct nl80211_coalesce_rule_support { __u32 max_rules; struct nl80211_pattern_support pat; __u32 max_delay; } __attribute__((packed)); /** * enum nl80211_attr_coalesce_rule - coalesce rule attribute * @__NL80211_COALESCE_RULE_INVALID: invalid number for nested attribute * @NL80211_ATTR_COALESCE_RULE_DELAY: delay in msecs used for packet coalescing * @NL80211_ATTR_COALESCE_RULE_CONDITION: condition for packet coalescence, * see &enum nl80211_coalesce_condition. * @NL80211_ATTR_COALESCE_RULE_PKT_PATTERN: packet offset, pattern is matched * after these fixed number of bytes of received packet * @NUM_NL80211_ATTR_COALESCE_RULE: number of attributes * @NL80211_ATTR_COALESCE_RULE_MAX: max attribute number */ enum nl80211_attr_coalesce_rule { __NL80211_COALESCE_RULE_INVALID, NL80211_ATTR_COALESCE_RULE_DELAY, NL80211_ATTR_COALESCE_RULE_CONDITION, NL80211_ATTR_COALESCE_RULE_PKT_PATTERN, /* keep last */ NUM_NL80211_ATTR_COALESCE_RULE, NL80211_ATTR_COALESCE_RULE_MAX = NUM_NL80211_ATTR_COALESCE_RULE - 1 }; /** * enum nl80211_coalesce_condition - coalesce rule conditions * @NL80211_COALESCE_CONDITION_MATCH: coalaesce Rx packets when patterns * in a rule are matched. * @NL80211_COALESCE_CONDITION_NO_MATCH: coalesce Rx packets when patterns * in a rule are not matched. */ enum nl80211_coalesce_condition { NL80211_COALESCE_CONDITION_MATCH, NL80211_COALESCE_CONDITION_NO_MATCH }; /** * enum nl80211_iface_limit_attrs - limit attributes * @NL80211_IFACE_LIMIT_UNSPEC: (reserved) * @NL80211_IFACE_LIMIT_MAX: maximum number of interfaces that * can be chosen from this set of interface types (u32) * @NL80211_IFACE_LIMIT_TYPES: nested attribute containing a * flag attribute for each interface type in this set * @NUM_NL80211_IFACE_LIMIT: number of attributes * @MAX_NL80211_IFACE_LIMIT: highest attribute number */ enum nl80211_iface_limit_attrs { NL80211_IFACE_LIMIT_UNSPEC, NL80211_IFACE_LIMIT_MAX, NL80211_IFACE_LIMIT_TYPES, /* keep last */ NUM_NL80211_IFACE_LIMIT, MAX_NL80211_IFACE_LIMIT = NUM_NL80211_IFACE_LIMIT - 1 }; /** * enum nl80211_if_combination_attrs -- interface combination attributes * * @NL80211_IFACE_COMB_UNSPEC: (reserved) * @NL80211_IFACE_COMB_LIMITS: Nested attributes containing the limits * for given interface types, see &enum nl80211_iface_limit_attrs. * @NL80211_IFACE_COMB_MAXNUM: u32 attribute giving the total number of * interfaces that can be created in this group. This number doesn't * apply to interfaces purely managed in software, which are listed * in a separate attribute %NL80211_ATTR_INTERFACES_SOFTWARE. * @NL80211_IFACE_COMB_STA_AP_BI_MATCH: flag attribute specifying that * beacon intervals within this group must be all the same even for * infrastructure and AP/GO combinations, i.e. the GO(s) must adopt * the infrastructure network's beacon interval. * @NL80211_IFACE_COMB_NUM_CHANNELS: u32 attribute specifying how many * different channels may be used within this group. * @NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS: u32 attribute containing the bitmap * of supported channel widths for radar detection. * @NL80211_IFACE_COMB_RADAR_DETECT_REGIONS: u32 attribute containing the bitmap * of supported regulatory regions for radar detection. * @NL80211_IFACE_COMB_BI_MIN_GCD: u32 attribute specifying the minimum GCD of * different beacon intervals supported by all the interface combinations * in this group (if not present, all beacon intervals be identical). * @NUM_NL80211_IFACE_COMB: number of attributes * @MAX_NL80211_IFACE_COMB: highest attribute number * * Examples: * limits = [ #{STA} <= 1, #{AP} <= 1 ], matching BI, channels = 1, max = 2 * => allows an AP and a STA that must match BIs * * numbers = [ #{AP, P2P-GO} <= 8 ], BI min gcd, channels = 1, max = 8, * => allows 8 of AP/GO that can have BI gcd >= min gcd * * numbers = [ #{STA} <= 2 ], channels = 2, max = 2 * => allows two STAs on the same or on different channels * * numbers = [ #{STA} <= 1, #{P2P-client,P2P-GO} <= 3 ], max = 4 * => allows a STA plus three P2P interfaces * * The list of these four possibilities could completely be contained * within the %NL80211_ATTR_INTERFACE_COMBINATIONS attribute to indicate * that any of these groups must match. * * "Combinations" of just a single interface will not be listed here, * a single interface of any valid interface type is assumed to always * be possible by itself. This means that implicitly, for each valid * interface type, the following group always exists: * numbers = [ #{} <= 1 ], channels = 1, max = 1 */ enum nl80211_if_combination_attrs { NL80211_IFACE_COMB_UNSPEC, NL80211_IFACE_COMB_LIMITS, NL80211_IFACE_COMB_MAXNUM, NL80211_IFACE_COMB_STA_AP_BI_MATCH, NL80211_IFACE_COMB_NUM_CHANNELS, NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS, NL80211_IFACE_COMB_RADAR_DETECT_REGIONS, NL80211_IFACE_COMB_BI_MIN_GCD, /* keep last */ NUM_NL80211_IFACE_COMB, MAX_NL80211_IFACE_COMB = NUM_NL80211_IFACE_COMB - 1 }; /** * enum nl80211_plink_state - state of a mesh peer link finite state machine * * @NL80211_PLINK_LISTEN: initial state, considered the implicit * state of non existent mesh peer links * @NL80211_PLINK_OPN_SNT: mesh plink open frame has been sent to * this mesh peer * @NL80211_PLINK_OPN_RCVD: mesh plink open frame has been received * from this mesh peer * @NL80211_PLINK_CNF_RCVD: mesh plink confirm frame has been * received from this mesh peer * @NL80211_PLINK_ESTAB: mesh peer link is established * @NL80211_PLINK_HOLDING: mesh peer link is being closed or cancelled * @NL80211_PLINK_BLOCKED: all frames transmitted from this mesh * plink are discarded, except for authentication frames * @NUM_NL80211_PLINK_STATES: number of peer link states * @MAX_NL80211_PLINK_STATES: highest numerical value of plink states */ enum nl80211_plink_state { NL80211_PLINK_LISTEN, NL80211_PLINK_OPN_SNT, NL80211_PLINK_OPN_RCVD, NL80211_PLINK_CNF_RCVD, NL80211_PLINK_ESTAB, NL80211_PLINK_HOLDING, NL80211_PLINK_BLOCKED, /* keep last */ NUM_NL80211_PLINK_STATES, MAX_NL80211_PLINK_STATES = NUM_NL80211_PLINK_STATES - 1 }; /** * enum nl80211_plink_action - actions to perform in mesh peers * * @NL80211_PLINK_ACTION_NO_ACTION: perform no action * @NL80211_PLINK_ACTION_OPEN: start mesh peer link establishment * @NL80211_PLINK_ACTION_BLOCK: block traffic from this mesh peer * @NUM_NL80211_PLINK_ACTIONS: number of possible actions */ enum plink_actions { NL80211_PLINK_ACTION_NO_ACTION, NL80211_PLINK_ACTION_OPEN, NL80211_PLINK_ACTION_BLOCK, NUM_NL80211_PLINK_ACTIONS, }; #define NL80211_KCK_LEN 16 #define NL80211_KEK_LEN 16 #define NL80211_KCK_EXT_LEN 24 #define NL80211_KEK_EXT_LEN 32 #define NL80211_KCK_EXT_LEN_32 32 #define NL80211_REPLAY_CTR_LEN 8 /** * enum nl80211_rekey_data - attributes for GTK rekey offload * @__NL80211_REKEY_DATA_INVALID: invalid number for nested attributes * @NL80211_REKEY_DATA_KEK: key encryption key (binary) * @NL80211_REKEY_DATA_KCK: key confirmation key (binary) * @NL80211_REKEY_DATA_REPLAY_CTR: replay counter (binary) * @NL80211_REKEY_DATA_AKM: AKM data (OUI, suite type) * @NUM_NL80211_REKEY_DATA: number of rekey attributes (internal) * @MAX_NL80211_REKEY_DATA: highest rekey attribute (internal) */ enum nl80211_rekey_data { __NL80211_REKEY_DATA_INVALID, NL80211_REKEY_DATA_KEK, NL80211_REKEY_DATA_KCK, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REKEY_DATA_AKM, /* keep last */ NUM_NL80211_REKEY_DATA, MAX_NL80211_REKEY_DATA = NUM_NL80211_REKEY_DATA - 1 }; /** * enum nl80211_hidden_ssid - values for %NL80211_ATTR_HIDDEN_SSID * @NL80211_HIDDEN_SSID_NOT_IN_USE: do not hide SSID (i.e., broadcast it in * Beacon frames) * @NL80211_HIDDEN_SSID_ZERO_LEN: hide SSID by using zero-length SSID element * in Beacon frames * @NL80211_HIDDEN_SSID_ZERO_CONTENTS: hide SSID by using correct length of SSID * element in Beacon frames but zero out each byte in the SSID */ enum nl80211_hidden_ssid { NL80211_HIDDEN_SSID_NOT_IN_USE, NL80211_HIDDEN_SSID_ZERO_LEN, NL80211_HIDDEN_SSID_ZERO_CONTENTS }; /** * enum nl80211_sta_wme_attr - station WME attributes * @__NL80211_STA_WME_INVALID: invalid number for nested attribute * @NL80211_STA_WME_UAPSD_QUEUES: bitmap of uapsd queues. the format * is the same as the AC bitmap in the QoS info field. * @NL80211_STA_WME_MAX_SP: max service period. the format is the same * as the MAX_SP field in the QoS info field (but already shifted down). * @__NL80211_STA_WME_AFTER_LAST: internal * @NL80211_STA_WME_MAX: highest station WME attribute */ enum nl80211_sta_wme_attr { __NL80211_STA_WME_INVALID, NL80211_STA_WME_UAPSD_QUEUES, NL80211_STA_WME_MAX_SP, /* keep last */ __NL80211_STA_WME_AFTER_LAST, NL80211_STA_WME_MAX = __NL80211_STA_WME_AFTER_LAST - 1 }; /** * enum nl80211_pmksa_candidate_attr - attributes for PMKSA caching candidates * @__NL80211_PMKSA_CANDIDATE_INVALID: invalid number for nested attributes * @NL80211_PMKSA_CANDIDATE_INDEX: candidate index (u32; the smaller, the higher * priority) * @NL80211_PMKSA_CANDIDATE_BSSID: candidate BSSID (6 octets) * @NL80211_PMKSA_CANDIDATE_PREAUTH: RSN pre-authentication supported (flag) * @NUM_NL80211_PMKSA_CANDIDATE: number of PMKSA caching candidate attributes * (internal) * @MAX_NL80211_PMKSA_CANDIDATE: highest PMKSA caching candidate attribute * (internal) */ enum nl80211_pmksa_candidate_attr { __NL80211_PMKSA_CANDIDATE_INVALID, NL80211_PMKSA_CANDIDATE_INDEX, NL80211_PMKSA_CANDIDATE_BSSID, NL80211_PMKSA_CANDIDATE_PREAUTH, /* keep last */ NUM_NL80211_PMKSA_CANDIDATE, MAX_NL80211_PMKSA_CANDIDATE = NUM_NL80211_PMKSA_CANDIDATE - 1 }; /** * enum nl80211_tdls_operation - values for %NL80211_ATTR_TDLS_OPERATION * @NL80211_TDLS_DISCOVERY_REQ: Send a TDLS discovery request * @NL80211_TDLS_SETUP: Setup TDLS link * @NL80211_TDLS_TEARDOWN: Teardown a TDLS link which is already established * @NL80211_TDLS_ENABLE_LINK: Enable TDLS link * @NL80211_TDLS_DISABLE_LINK: Disable TDLS link */ enum nl80211_tdls_operation { NL80211_TDLS_DISCOVERY_REQ, NL80211_TDLS_SETUP, NL80211_TDLS_TEARDOWN, NL80211_TDLS_ENABLE_LINK, NL80211_TDLS_DISABLE_LINK, }; /** * enum nl80211_ap_sme_features - device-integrated AP features * @NL80211_AP_SME_SA_QUERY_OFFLOAD: SA Query procedures offloaded to driver * when user space indicates support for SA Query procedures offload during * "start ap" with %NL80211_AP_SETTINGS_SA_QUERY_OFFLOAD_SUPPORT. */ enum nl80211_ap_sme_features { NL80211_AP_SME_SA_QUERY_OFFLOAD = 1 << 0, }; /** * enum nl80211_feature_flags - device/driver features * @NL80211_FEATURE_SK_TX_STATUS: This driver supports reflecting back * TX status to the socket error queue when requested with the * socket option. * @NL80211_FEATURE_HT_IBSS: This driver supports IBSS with HT datarates. * @NL80211_FEATURE_INACTIVITY_TIMER: This driver takes care of freeing up * the connected inactive stations in AP mode. * @NL80211_FEATURE_CELL_BASE_REG_HINTS: This driver has been tested * to work properly to support receiving regulatory hints from * cellular base stations. * @NL80211_FEATURE_P2P_DEVICE_NEEDS_CHANNEL: (no longer available, only * here to reserve the value for API/ABI compatibility) * @NL80211_FEATURE_SAE: This driver supports simultaneous authentication of * equals (SAE) with user space SME (NL80211_CMD_AUTHENTICATE) in station * mode * @NL80211_FEATURE_LOW_PRIORITY_SCAN: This driver supports low priority scan * @NL80211_FEATURE_SCAN_FLUSH: Scan flush is supported * @NL80211_FEATURE_AP_SCAN: Support scanning using an AP vif * @NL80211_FEATURE_VIF_TXPOWER: The driver supports per-vif TX power setting * @NL80211_FEATURE_NEED_OBSS_SCAN: The driver expects userspace to perform * OBSS scans and generate 20/40 BSS coex reports. This flag is used only * for drivers implementing the CONNECT API, for AUTH/ASSOC it is implied. * @NL80211_FEATURE_P2P_GO_CTWIN: P2P GO implementation supports CT Window * setting * @NL80211_FEATURE_P2P_GO_OPPPS: P2P GO implementation supports opportunistic * powersave * @NL80211_FEATURE_FULL_AP_CLIENT_STATE: The driver supports full state * transitions for AP clients. Without this flag (and if the driver * doesn't have the AP SME in the device) the driver supports adding * stations only when they're associated and adds them in associated * state (to later be transitioned into authorized), with this flag * they should be added before even sending the authentication reply * and then transitioned into authenticated, associated and authorized * states using station flags. * Note that even for drivers that support this, the default is to add * stations in authenticated/associated state, so to add unauthenticated * stations the authenticated/associated bits have to be set in the mask. * @NL80211_FEATURE_ADVERTISE_CHAN_LIMITS: cfg80211 advertises channel limits * (HT40, VHT 80/160 MHz) if this flag is set * @NL80211_FEATURE_USERSPACE_MPM: This driver supports a userspace Mesh * Peering Management entity which may be implemented by registering for * beacons or NL80211_CMD_NEW_PEER_CANDIDATE events. The mesh beacon is * still generated by the driver. * @NL80211_FEATURE_ACTIVE_MONITOR: This driver supports an active monitor * interface. An active monitor interface behaves like a normal monitor * interface, but gets added to the driver. It ensures that incoming * unicast packets directed at the configured interface address get ACKed. * @NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE: This driver supports dynamic * channel bandwidth change (e.g., HT 20 <-> 40 MHz channel) during the * lifetime of a BSS. * @NL80211_FEATURE_DS_PARAM_SET_IE_IN_PROBES: This device adds a DS Parameter * Set IE to probe requests. * @NL80211_FEATURE_WFA_TPC_IE_IN_PROBES: This device adds a WFA TPC Report IE * to probe requests. * @NL80211_FEATURE_QUIET: This device, in client mode, supports Quiet Period * requests sent to it by an AP. * @NL80211_FEATURE_TX_POWER_INSERTION: This device is capable of inserting the * current tx power value into the TPC Report IE in the spectrum * management TPC Report action frame, and in the Radio Measurement Link * Measurement Report action frame. * @NL80211_FEATURE_ACKTO_ESTIMATION: This driver supports dynamic ACK timeout * estimation (dynack). %NL80211_ATTR_WIPHY_DYN_ACK flag attribute is used * to enable dynack. * @NL80211_FEATURE_STATIC_SMPS: Device supports static spatial * multiplexing powersave, ie. can turn off all but one chain * even on HT connections that should be using more chains. * @NL80211_FEATURE_DYNAMIC_SMPS: Device supports dynamic spatial * multiplexing powersave, ie. can turn off all but one chain * and then wake the rest up as required after, for example, * rts/cts handshake. * @NL80211_FEATURE_SUPPORTS_WMM_ADMISSION: the device supports setting up WMM * TSPEC sessions (TID aka TSID 0-7) with the %NL80211_CMD_ADD_TX_TS * command. Standard IEEE 802.11 TSPEC setup is not yet supported, it * needs to be able to handle Block-Ack agreements and other things. * @NL80211_FEATURE_MAC_ON_CREATE: Device supports configuring * the vif's MAC address upon creation. * See 'macaddr' field in the vif_params (cfg80211.h). * @NL80211_FEATURE_TDLS_CHANNEL_SWITCH: Driver supports channel switching when * operating as a TDLS peer. * @NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR: This device/driver supports using a * random MAC address during scan (if the device is unassociated); the * %NL80211_SCAN_FLAG_RANDOM_ADDR flag may be set for scans and the MAC * address mask/value will be used. * @NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR: This device/driver supports * using a random MAC address for every scan iteration during scheduled * scan (while not associated), the %NL80211_SCAN_FLAG_RANDOM_ADDR may * be set for scheduled scan and the MAC address mask/value will be used. * @NL80211_FEATURE_ND_RANDOM_MAC_ADDR: This device/driver supports using a * random MAC address for every scan iteration during "net detect", i.e. * scan in unassociated WoWLAN, the %NL80211_SCAN_FLAG_RANDOM_ADDR may * be set for scheduled scan and the MAC address mask/value will be used. */ enum nl80211_feature_flags { NL80211_FEATURE_SK_TX_STATUS = 1 << 0, NL80211_FEATURE_HT_IBSS = 1 << 1, NL80211_FEATURE_INACTIVITY_TIMER = 1 << 2, NL80211_FEATURE_CELL_BASE_REG_HINTS = 1 << 3, NL80211_FEATURE_P2P_DEVICE_NEEDS_CHANNEL = 1 << 4, NL80211_FEATURE_SAE = 1 << 5, NL80211_FEATURE_LOW_PRIORITY_SCAN = 1 << 6, NL80211_FEATURE_SCAN_FLUSH = 1 << 7, NL80211_FEATURE_AP_SCAN = 1 << 8, NL80211_FEATURE_VIF_TXPOWER = 1 << 9, NL80211_FEATURE_NEED_OBSS_SCAN = 1 << 10, NL80211_FEATURE_P2P_GO_CTWIN = 1 << 11, NL80211_FEATURE_P2P_GO_OPPPS = 1 << 12, /* bit 13 is reserved */ NL80211_FEATURE_ADVERTISE_CHAN_LIMITS = 1 << 14, NL80211_FEATURE_FULL_AP_CLIENT_STATE = 1 << 15, NL80211_FEATURE_USERSPACE_MPM = 1 << 16, NL80211_FEATURE_ACTIVE_MONITOR = 1 << 17, NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE = 1 << 18, NL80211_FEATURE_DS_PARAM_SET_IE_IN_PROBES = 1 << 19, NL80211_FEATURE_WFA_TPC_IE_IN_PROBES = 1 << 20, NL80211_FEATURE_QUIET = 1 << 21, NL80211_FEATURE_TX_POWER_INSERTION = 1 << 22, NL80211_FEATURE_ACKTO_ESTIMATION = 1 << 23, NL80211_FEATURE_STATIC_SMPS = 1 << 24, NL80211_FEATURE_DYNAMIC_SMPS = 1 << 25, NL80211_FEATURE_SUPPORTS_WMM_ADMISSION = 1 << 26, NL80211_FEATURE_MAC_ON_CREATE = 1 << 27, NL80211_FEATURE_TDLS_CHANNEL_SWITCH = 1 << 28, NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR = 1 << 29, NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR = 1 << 30, NL80211_FEATURE_ND_RANDOM_MAC_ADDR = 1 << 31, }; /** * enum nl80211_ext_feature_index - bit index of extended features. * @NL80211_EXT_FEATURE_VHT_IBSS: This driver supports IBSS with VHT datarates. * @NL80211_EXT_FEATURE_RRM: This driver supports RRM. When featured, user can * request to use RRM (see %NL80211_ATTR_USE_RRM) with * %NL80211_CMD_ASSOCIATE and %NL80211_CMD_CONNECT requests, which will set * the ASSOC_REQ_USE_RRM flag in the association request even if * NL80211_FEATURE_QUIET is not advertized. * @NL80211_EXT_FEATURE_MU_MIMO_AIR_SNIFFER: This device supports MU-MIMO air * sniffer which means that it can be configured to hear packets from * certain groups which can be configured by the * %NL80211_ATTR_MU_MIMO_GROUP_DATA attribute, * or can be configured to follow a station by configuring the * %NL80211_ATTR_MU_MIMO_FOLLOW_MAC_ADDR attribute. * @NL80211_EXT_FEATURE_SCAN_START_TIME: This driver includes the actual * time the scan started in scan results event. The time is the TSF of * the BSS that the interface that requested the scan is connected to * (if available). * @NL80211_EXT_FEATURE_BSS_PARENT_TSF: Per BSS, this driver reports the * time the last beacon/probe was received. The time is the TSF of the * BSS that the interface that requested the scan is connected to * (if available). * @NL80211_EXT_FEATURE_SET_SCAN_DWELL: This driver supports configuration of * channel dwell time. * @NL80211_EXT_FEATURE_BEACON_RATE_LEGACY: Driver supports beacon rate * configuration (AP/mesh), supporting a legacy (non HT/VHT) rate. * @NL80211_EXT_FEATURE_BEACON_RATE_HT: Driver supports beacon rate * configuration (AP/mesh) with HT rates. * @NL80211_EXT_FEATURE_BEACON_RATE_VHT: Driver supports beacon rate * configuration (AP/mesh) with VHT rates. * @NL80211_EXT_FEATURE_FILS_STA: This driver supports Fast Initial Link Setup * with user space SME (NL80211_CMD_AUTHENTICATE) in station mode. * @NL80211_EXT_FEATURE_MGMT_TX_RANDOM_TA: This driver supports randomized TA * in @NL80211_CMD_FRAME while not associated. * @NL80211_EXT_FEATURE_MGMT_TX_RANDOM_TA_CONNECTED: This driver supports * randomized TA in @NL80211_CMD_FRAME while associated. * @NL80211_EXT_FEATURE_SCHED_SCAN_RELATIVE_RSSI: The driver supports sched_scan * for reporting BSSs with better RSSI than the current connected BSS * (%NL80211_ATTR_SCHED_SCAN_RELATIVE_RSSI). * @NL80211_EXT_FEATURE_CQM_RSSI_LIST: With this driver the * %NL80211_ATTR_CQM_RSSI_THOLD attribute accepts a list of zero or more * RSSI threshold values to monitor rather than exactly one threshold. * @NL80211_EXT_FEATURE_FILS_SK_OFFLOAD: Driver SME supports FILS shared key * authentication with %NL80211_CMD_CONNECT. * @NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_PSK: Device wants to do 4-way * handshake with PSK in station mode (PSK is passed as part of the connect * and associate commands), doing it in the host might not be supported. * @NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_1X: Device wants to do doing 4-way * handshake with 802.1X in station mode (will pass EAP frames to the host * and accept the set_pmk/del_pmk commands), doing it in the host might not * be supported. * @NL80211_EXT_FEATURE_FILS_MAX_CHANNEL_TIME: Driver is capable of overriding * the max channel attribute in the FILS request params IE with the * actual dwell time. * @NL80211_EXT_FEATURE_ACCEPT_BCAST_PROBE_RESP: Driver accepts broadcast probe * response * @NL80211_EXT_FEATURE_OCE_PROBE_REQ_HIGH_TX_RATE: Driver supports sending * the first probe request in each channel at rate of at least 5.5Mbps. * @NL80211_EXT_FEATURE_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION: Driver supports * probe request tx deferral and suppression * @NL80211_EXT_FEATURE_MFP_OPTIONAL: Driver supports the %NL80211_MFP_OPTIONAL * value in %NL80211_ATTR_USE_MFP. * @NL80211_EXT_FEATURE_LOW_SPAN_SCAN: Driver supports low span scan. * @NL80211_EXT_FEATURE_LOW_POWER_SCAN: Driver supports low power scan. * @NL80211_EXT_FEATURE_HIGH_ACCURACY_SCAN: Driver supports high accuracy scan. * @NL80211_EXT_FEATURE_DFS_OFFLOAD: HW/driver will offload DFS actions. * Device or driver will do all DFS-related actions by itself, * informing user-space about CAC progress, radar detection event, * channel change triggered by radar detection event. * No need to start CAC from user-space, no need to react to * "radar detected" event. * @NL80211_EXT_FEATURE_CONTROL_PORT_OVER_NL80211: Driver supports sending and * receiving control port frames over nl80211 instead of the netdevice. * @NL80211_EXT_FEATURE_ACK_SIGNAL_SUPPORT: This driver/device supports * (average) ACK signal strength reporting. * @NL80211_EXT_FEATURE_TXQS: Driver supports FQ-CoDel-enabled intermediate * TXQs. * @NL80211_EXT_FEATURE_SCAN_RANDOM_SN: Driver/device supports randomizing the * SN in probe request frames if requested by %NL80211_SCAN_FLAG_RANDOM_SN. * @NL80211_EXT_FEATURE_SCAN_MIN_PREQ_CONTENT: Driver/device can omit all data * except for supported rates from the probe request content if requested * by the %NL80211_SCAN_FLAG_MIN_PREQ_CONTENT flag. * @NL80211_EXT_FEATURE_ENABLE_FTM_RESPONDER: Driver supports enabling fine * timing measurement responder role. * * @NL80211_EXT_FEATURE_CAN_REPLACE_PTK0: Driver/device confirm that they are * able to rekey an in-use key correctly. Userspace must not rekey PTK keys * if this flag is not set. Ignoring this can leak clear text packets and/or * freeze the connection. * @NL80211_EXT_FEATURE_EXT_KEY_ID: Driver supports "Extended Key ID for * Individually Addressed Frames" from IEEE802.11-2016. * * @NL80211_EXT_FEATURE_AIRTIME_FAIRNESS: Driver supports getting airtime * fairness for transmitted packets and has enabled airtime fairness * scheduling. * * @NL80211_EXT_FEATURE_AP_PMKSA_CACHING: Driver/device supports PMKSA caching * (set/del PMKSA operations) in AP mode. * * @NL80211_EXT_FEATURE_SCHED_SCAN_BAND_SPECIFIC_RSSI_THOLD: Driver supports * filtering of sched scan results using band specific RSSI thresholds. * * @NL80211_EXT_FEATURE_STA_TX_PWR: This driver supports controlling tx power * to a station. * * @NL80211_EXT_FEATURE_SAE_OFFLOAD: Device wants to do SAE authentication in * station mode (SAE password is passed as part of the connect command). * * @NL80211_EXT_FEATURE_VLAN_OFFLOAD: The driver supports a single netdev * with VLAN tagged frames and separate VLAN-specific netdevs added using * vconfig similarly to the Ethernet case. * * @NL80211_EXT_FEATURE_AQL: The driver supports the Airtime Queue Limit (AQL) * feature, which prevents bufferbloat by using the expected transmission * time to limit the amount of data buffered in the hardware. * * @NL80211_EXT_FEATURE_BEACON_PROTECTION: The driver supports Beacon protection * and can receive key configuration for BIGTK using key indexes 6 and 7. * @NL80211_EXT_FEATURE_BEACON_PROTECTION_CLIENT: The driver supports Beacon * protection as a client only and cannot transmit protected beacons. * * @NL80211_EXT_FEATURE_CONTROL_PORT_NO_PREAUTH: The driver can disable the * forwarding of preauth frames over the control port. They are then * handled as ordinary data frames. * * @NL80211_EXT_FEATURE_PROTECTED_TWT: Driver supports protected TWT frames * * @NL80211_EXT_FEATURE_DEL_IBSS_STA: The driver supports removing stations * in IBSS mode, essentially by dropping their state. * * @NL80211_EXT_FEATURE_MULTICAST_REGISTRATIONS: management frame registrations * are possible for multicast frames and those will be reported properly. * * @NL80211_EXT_FEATURE_SCAN_FREQ_KHZ: This driver supports receiving and * reporting scan request with %NL80211_ATTR_SCAN_FREQ_KHZ. In order to * report %NL80211_ATTR_SCAN_FREQ_KHZ, %NL80211_SCAN_FLAG_FREQ_KHZ must be * included in the scan request. * * @NL80211_EXT_FEATURE_CONTROL_PORT_OVER_NL80211_TX_STATUS: The driver * can report tx status for control port over nl80211 tx operations. * * @NL80211_EXT_FEATURE_OPERATING_CHANNEL_VALIDATION: Driver supports Operating * Channel Validation (OCV) when using driver's SME for RSNA handshakes. * * @NL80211_EXT_FEATURE_4WAY_HANDSHAKE_AP_PSK: Device wants to do 4-way * handshake with PSK in AP mode (PSK is passed as part of the start AP * command). * * @NL80211_EXT_FEATURE_SAE_OFFLOAD_AP: Device wants to do SAE authentication * in AP mode (SAE password is passed as part of the start AP command). * * @NL80211_EXT_FEATURE_FILS_DISCOVERY: Driver/device supports FILS discovery * frames transmission * * @NL80211_EXT_FEATURE_UNSOL_BCAST_PROBE_RESP: Driver/device supports * unsolicited broadcast probe response transmission * * @NL80211_EXT_FEATURE_BEACON_RATE_HE: Driver supports beacon rate * configuration (AP/mesh) with HE rates. * * @NL80211_EXT_FEATURE_SECURE_LTF: Device supports secure LTF measurement * exchange protocol. * * @NL80211_EXT_FEATURE_SECURE_RTT: Device supports secure RTT measurement * exchange protocol. * * @NL80211_EXT_FEATURE_PROT_RANGE_NEGO_AND_MEASURE: Device supports management * frame protection for all management frames exchanged during the * negotiation and range measurement procedure. * * @NL80211_EXT_FEATURE_BSS_COLOR: The driver supports BSS color collision * detection and change announcemnts. * * @NL80211_EXT_FEATURE_FILS_CRYPTO_OFFLOAD: Driver running in AP mode supports * FILS encryption and decryption for (Re)Association Request and Response * frames. Userspace has to share FILS AAD details to the driver by using * @NL80211_CMD_SET_FILS_AAD. * * @NL80211_EXT_FEATURE_RADAR_BACKGROUND: Device supports background radar/CAC * detection. * * @NL80211_EXT_FEATURE_POWERED_ADDR_CHANGE: Device can perform a MAC address * change without having to bring the underlying network device down * first. For example, in station mode this can be used to vary the * origin MAC address prior to a connection to a new AP for privacy * or other reasons. Note that certain driver specific restrictions * might apply, e.g. no scans in progress, no offchannel operations * in progress, and no active connections. * * @NL80211_EXT_FEATURE_PUNCT: Driver supports preamble puncturing in AP mode. * * @NL80211_EXT_FEATURE_SECURE_NAN: Device supports NAN Pairing which enables * authentication, data encryption and message integrity. * * @NL80211_EXT_FEATURE_AUTH_AND_DEAUTH_RANDOM_TA: Device supports randomized TA * in authentication and deauthentication frames sent to unassociated peer * using @NL80211_CMD_FRAME. * * @NUM_NL80211_EXT_FEATURES: number of extended features. * @MAX_NL80211_EXT_FEATURES: highest extended feature index. */ enum nl80211_ext_feature_index { NL80211_EXT_FEATURE_VHT_IBSS, NL80211_EXT_FEATURE_RRM, NL80211_EXT_FEATURE_MU_MIMO_AIR_SNIFFER, NL80211_EXT_FEATURE_SCAN_START_TIME, NL80211_EXT_FEATURE_BSS_PARENT_TSF, NL80211_EXT_FEATURE_SET_SCAN_DWELL, NL80211_EXT_FEATURE_BEACON_RATE_LEGACY, NL80211_EXT_FEATURE_BEACON_RATE_HT, NL80211_EXT_FEATURE_BEACON_RATE_VHT, NL80211_EXT_FEATURE_FILS_STA, NL80211_EXT_FEATURE_MGMT_TX_RANDOM_TA, NL80211_EXT_FEATURE_MGMT_TX_RANDOM_TA_CONNECTED, NL80211_EXT_FEATURE_SCHED_SCAN_RELATIVE_RSSI, NL80211_EXT_FEATURE_CQM_RSSI_LIST, NL80211_EXT_FEATURE_FILS_SK_OFFLOAD, NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_PSK, NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_1X, NL80211_EXT_FEATURE_FILS_MAX_CHANNEL_TIME, NL80211_EXT_FEATURE_ACCEPT_BCAST_PROBE_RESP, NL80211_EXT_FEATURE_OCE_PROBE_REQ_HIGH_TX_RATE, NL80211_EXT_FEATURE_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION, NL80211_EXT_FEATURE_MFP_OPTIONAL, NL80211_EXT_FEATURE_LOW_SPAN_SCAN, NL80211_EXT_FEATURE_LOW_POWER_SCAN, NL80211_EXT_FEATURE_HIGH_ACCURACY_SCAN, NL80211_EXT_FEATURE_DFS_OFFLOAD, NL80211_EXT_FEATURE_CONTROL_PORT_OVER_NL80211, NL80211_EXT_FEATURE_ACK_SIGNAL_SUPPORT, /* we renamed this - stay compatible */ NL80211_EXT_FEATURE_DATA_ACK_SIGNAL_SUPPORT = NL80211_EXT_FEATURE_ACK_SIGNAL_SUPPORT, NL80211_EXT_FEATURE_TXQS, NL80211_EXT_FEATURE_SCAN_RANDOM_SN, NL80211_EXT_FEATURE_SCAN_MIN_PREQ_CONTENT, NL80211_EXT_FEATURE_CAN_REPLACE_PTK0, NL80211_EXT_FEATURE_ENABLE_FTM_RESPONDER, NL80211_EXT_FEATURE_AIRTIME_FAIRNESS, NL80211_EXT_FEATURE_AP_PMKSA_CACHING, NL80211_EXT_FEATURE_SCHED_SCAN_BAND_SPECIFIC_RSSI_THOLD, NL80211_EXT_FEATURE_EXT_KEY_ID, NL80211_EXT_FEATURE_STA_TX_PWR, NL80211_EXT_FEATURE_SAE_OFFLOAD, NL80211_EXT_FEATURE_VLAN_OFFLOAD, NL80211_EXT_FEATURE_AQL, NL80211_EXT_FEATURE_BEACON_PROTECTION, NL80211_EXT_FEATURE_CONTROL_PORT_NO_PREAUTH, NL80211_EXT_FEATURE_PROTECTED_TWT, NL80211_EXT_FEATURE_DEL_IBSS_STA, NL80211_EXT_FEATURE_MULTICAST_REGISTRATIONS, NL80211_EXT_FEATURE_BEACON_PROTECTION_CLIENT, NL80211_EXT_FEATURE_SCAN_FREQ_KHZ, NL80211_EXT_FEATURE_CONTROL_PORT_OVER_NL80211_TX_STATUS, NL80211_EXT_FEATURE_OPERATING_CHANNEL_VALIDATION, NL80211_EXT_FEATURE_4WAY_HANDSHAKE_AP_PSK, NL80211_EXT_FEATURE_SAE_OFFLOAD_AP, NL80211_EXT_FEATURE_FILS_DISCOVERY, NL80211_EXT_FEATURE_UNSOL_BCAST_PROBE_RESP, NL80211_EXT_FEATURE_BEACON_RATE_HE, NL80211_EXT_FEATURE_SECURE_LTF, NL80211_EXT_FEATURE_SECURE_RTT, NL80211_EXT_FEATURE_PROT_RANGE_NEGO_AND_MEASURE, NL80211_EXT_FEATURE_BSS_COLOR, NL80211_EXT_FEATURE_FILS_CRYPTO_OFFLOAD, NL80211_EXT_FEATURE_RADAR_BACKGROUND, NL80211_EXT_FEATURE_POWERED_ADDR_CHANGE, NL80211_EXT_FEATURE_PUNCT, NL80211_EXT_FEATURE_SECURE_NAN, NL80211_EXT_FEATURE_AUTH_AND_DEAUTH_RANDOM_TA, /* add new features before the definition below */ NUM_NL80211_EXT_FEATURES, MAX_NL80211_EXT_FEATURES = NUM_NL80211_EXT_FEATURES - 1 }; /** * enum nl80211_probe_resp_offload_support_attr - optional supported * protocols for probe-response offloading by the driver/FW. * To be used with the %NL80211_ATTR_PROBE_RESP_OFFLOAD attribute. * Each enum value represents a bit in the bitmap of supported * protocols. Typically a subset of probe-requests belonging to a * supported protocol will be excluded from offload and uploaded * to the host. * * @NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS: Support for WPS ver. 1 * @NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2: Support for WPS ver. 2 * @NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P: Support for P2P * @NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U: Support for 802.11u */ enum nl80211_probe_resp_offload_support_attr { NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS = 1<<0, NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2 = 1<<1, NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P = 1<<2, NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U = 1<<3, }; /** * enum nl80211_connect_failed_reason - connection request failed reasons * @NL80211_CONN_FAIL_MAX_CLIENTS: Maximum number of clients that can be * handled by the AP is reached. * @NL80211_CONN_FAIL_BLOCKED_CLIENT: Connection request is rejected due to ACL. */ enum nl80211_connect_failed_reason { NL80211_CONN_FAIL_MAX_CLIENTS, NL80211_CONN_FAIL_BLOCKED_CLIENT, }; /** * enum nl80211_timeout_reason - timeout reasons * * @NL80211_TIMEOUT_UNSPECIFIED: Timeout reason unspecified. * @NL80211_TIMEOUT_SCAN: Scan (AP discovery) timed out. * @NL80211_TIMEOUT_AUTH: Authentication timed out. * @NL80211_TIMEOUT_ASSOC: Association timed out. */ enum nl80211_timeout_reason { NL80211_TIMEOUT_UNSPECIFIED, NL80211_TIMEOUT_SCAN, NL80211_TIMEOUT_AUTH, NL80211_TIMEOUT_ASSOC, }; /** * enum nl80211_scan_flags - scan request control flags * * Scan request control flags are used to control the handling * of NL80211_CMD_TRIGGER_SCAN and NL80211_CMD_START_SCHED_SCAN * requests. * * NL80211_SCAN_FLAG_LOW_SPAN, NL80211_SCAN_FLAG_LOW_POWER, and * NL80211_SCAN_FLAG_HIGH_ACCURACY flags are exclusive of each other, i.e., only * one of them can be used in the request. * * @NL80211_SCAN_FLAG_LOW_PRIORITY: scan request has low priority * @NL80211_SCAN_FLAG_FLUSH: flush cache before scanning * @NL80211_SCAN_FLAG_AP: force a scan even if the interface is configured * as AP and the beaconing has already been configured. This attribute is * dangerous because will destroy stations performance as a lot of frames * will be lost while scanning off-channel, therefore it must be used only * when really needed * @NL80211_SCAN_FLAG_RANDOM_ADDR: use a random MAC address for this scan (or * for scheduled scan: a different one for every scan iteration). When the * flag is set, depending on device capabilities the @NL80211_ATTR_MAC and * @NL80211_ATTR_MAC_MASK attributes may also be given in which case only * the masked bits will be preserved from the MAC address and the remainder * randomised. If the attributes are not given full randomisation (46 bits, * locally administered 1, multicast 0) is assumed. * This flag must not be requested when the feature isn't supported, check * the nl80211 feature flags for the device. * @NL80211_SCAN_FLAG_FILS_MAX_CHANNEL_TIME: fill the dwell time in the FILS * request parameters IE in the probe request * @NL80211_SCAN_FLAG_ACCEPT_BCAST_PROBE_RESP: accept broadcast probe responses * @NL80211_SCAN_FLAG_OCE_PROBE_REQ_HIGH_TX_RATE: send probe request frames at * rate of at least 5.5M. In case non OCE AP is discovered in the channel, * only the first probe req in the channel will be sent in high rate. * @NL80211_SCAN_FLAG_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION: allow probe request * tx deferral (dot11FILSProbeDelay shall be set to 15ms) * and suppression (if it has received a broadcast Probe Response frame, * Beacon frame or FILS Discovery frame from an AP that the STA considers * a suitable candidate for (re-)association - suitable in terms of * SSID and/or RSSI. * @NL80211_SCAN_FLAG_LOW_SPAN: Span corresponds to the total time taken to * accomplish the scan. Thus, this flag intends the driver to perform the * scan request with lesser span/duration. It is specific to the driver * implementations on how this is accomplished. Scan accuracy may get * impacted with this flag. * @NL80211_SCAN_FLAG_LOW_POWER: This flag intends the scan attempts to consume * optimal possible power. Drivers can resort to their specific means to * optimize the power. Scan accuracy may get impacted with this flag. * @NL80211_SCAN_FLAG_HIGH_ACCURACY: Accuracy here intends to the extent of scan * results obtained. Thus HIGH_ACCURACY scan flag aims to get maximum * possible scan results. This flag hints the driver to use the best * possible scan configuration to improve the accuracy in scanning. * Latency and power use may get impacted with this flag. * @NL80211_SCAN_FLAG_RANDOM_SN: randomize the sequence number in probe * request frames from this scan to avoid correlation/tracking being * possible. * @NL80211_SCAN_FLAG_MIN_PREQ_CONTENT: minimize probe request content to * only have supported rates and no additional capabilities (unless * added by userspace explicitly.) * @NL80211_SCAN_FLAG_FREQ_KHZ: report scan results with * %NL80211_ATTR_SCAN_FREQ_KHZ. This also means * %NL80211_ATTR_SCAN_FREQUENCIES will not be included. * @NL80211_SCAN_FLAG_COLOCATED_6GHZ: scan for collocated APs reported by * 2.4/5 GHz APs. When the flag is set, the scan logic will use the * information from the RNR element found in beacons/probe responses * received on the 2.4/5 GHz channels to actively scan only the 6GHz * channels on which APs are expected to be found. Note that when not set, * the scan logic would scan all 6GHz channels, but since transmission of * probe requests on non PSC channels is limited, it is highly likely that * these channels would passively be scanned. Also note that when the flag * is set, in addition to the colocated APs, PSC channels would also be * scanned if the user space has asked for it. */ enum nl80211_scan_flags { NL80211_SCAN_FLAG_LOW_PRIORITY = 1<<0, NL80211_SCAN_FLAG_FLUSH = 1<<1, NL80211_SCAN_FLAG_AP = 1<<2, NL80211_SCAN_FLAG_RANDOM_ADDR = 1<<3, NL80211_SCAN_FLAG_FILS_MAX_CHANNEL_TIME = 1<<4, NL80211_SCAN_FLAG_ACCEPT_BCAST_PROBE_RESP = 1<<5, NL80211_SCAN_FLAG_OCE_PROBE_REQ_HIGH_TX_RATE = 1<<6, NL80211_SCAN_FLAG_OCE_PROBE_REQ_DEFERRAL_SUPPRESSION = 1<<7, NL80211_SCAN_FLAG_LOW_SPAN = 1<<8, NL80211_SCAN_FLAG_LOW_POWER = 1<<9, NL80211_SCAN_FLAG_HIGH_ACCURACY = 1<<10, NL80211_SCAN_FLAG_RANDOM_SN = 1<<11, NL80211_SCAN_FLAG_MIN_PREQ_CONTENT = 1<<12, NL80211_SCAN_FLAG_FREQ_KHZ = 1<<13, NL80211_SCAN_FLAG_COLOCATED_6GHZ = 1<<14, }; /** * enum nl80211_acl_policy - access control policy * * Access control policy is applied on a MAC list set by * %NL80211_CMD_START_AP and %NL80211_CMD_SET_MAC_ACL, to * be used with %NL80211_ATTR_ACL_POLICY. * * @NL80211_ACL_POLICY_ACCEPT_UNLESS_LISTED: Deny stations which are * listed in ACL, i.e. allow all the stations which are not listed * in ACL to authenticate. * @NL80211_ACL_POLICY_DENY_UNLESS_LISTED: Allow the stations which are listed * in ACL, i.e. deny all the stations which are not listed in ACL. */ enum nl80211_acl_policy { NL80211_ACL_POLICY_ACCEPT_UNLESS_LISTED, NL80211_ACL_POLICY_DENY_UNLESS_LISTED, }; /** * enum nl80211_smps_mode - SMPS mode * * Requested SMPS mode (for AP mode) * * @NL80211_SMPS_OFF: SMPS off (use all antennas). * @NL80211_SMPS_STATIC: static SMPS (use a single antenna) * @NL80211_SMPS_DYNAMIC: dynamic smps (start with a single antenna and * turn on other antennas after CTS/RTS). */ enum nl80211_smps_mode { NL80211_SMPS_OFF, NL80211_SMPS_STATIC, NL80211_SMPS_DYNAMIC, __NL80211_SMPS_AFTER_LAST, NL80211_SMPS_MAX = __NL80211_SMPS_AFTER_LAST - 1 }; /** * enum nl80211_radar_event - type of radar event for DFS operation * * Type of event to be used with NL80211_ATTR_RADAR_EVENT to inform userspace * about detected radars or success of the channel available check (CAC) * * @NL80211_RADAR_DETECTED: A radar pattern has been detected. The channel is * now unusable. * @NL80211_RADAR_CAC_FINISHED: Channel Availability Check has been finished, * the channel is now available. * @NL80211_RADAR_CAC_ABORTED: Channel Availability Check has been aborted, no * change to the channel status. * @NL80211_RADAR_NOP_FINISHED: The Non-Occupancy Period for this channel is * over, channel becomes usable. * @NL80211_RADAR_PRE_CAC_EXPIRED: Channel Availability Check done on this * non-operating channel is expired and no longer valid. New CAC must * be done on this channel before starting the operation. This is not * applicable for ETSI dfs domain where pre-CAC is valid for ever. * @NL80211_RADAR_CAC_STARTED: Channel Availability Check has been started, * should be generated by HW if NL80211_EXT_FEATURE_DFS_OFFLOAD is enabled. */ enum nl80211_radar_event { NL80211_RADAR_DETECTED, NL80211_RADAR_CAC_FINISHED, NL80211_RADAR_CAC_ABORTED, NL80211_RADAR_NOP_FINISHED, NL80211_RADAR_PRE_CAC_EXPIRED, NL80211_RADAR_CAC_STARTED, }; /** * enum nl80211_dfs_state - DFS states for channels * * Channel states used by the DFS code. * * @NL80211_DFS_USABLE: The channel can be used, but channel availability * check (CAC) must be performed before using it for AP or IBSS. * @NL80211_DFS_UNAVAILABLE: A radar has been detected on this channel, it * is therefore marked as not available. * @NL80211_DFS_AVAILABLE: The channel has been CAC checked and is available. */ enum nl80211_dfs_state { NL80211_DFS_USABLE, NL80211_DFS_UNAVAILABLE, NL80211_DFS_AVAILABLE, }; /** * enum nl80211_protocol_features - nl80211 protocol features * @NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP: nl80211 supports splitting * wiphy dumps (if requested by the application with the attribute * %NL80211_ATTR_SPLIT_WIPHY_DUMP. Also supported is filtering the * wiphy dump by %NL80211_ATTR_WIPHY, %NL80211_ATTR_IFINDEX or * %NL80211_ATTR_WDEV. */ enum nl80211_protocol_features { NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP = 1 << 0, }; /** * enum nl80211_crit_proto_id - nl80211 critical protocol identifiers * * @NL80211_CRIT_PROTO_UNSPEC: protocol unspecified. * @NL80211_CRIT_PROTO_DHCP: BOOTP or DHCPv6 protocol. * @NL80211_CRIT_PROTO_EAPOL: EAPOL protocol. * @NL80211_CRIT_PROTO_APIPA: APIPA protocol. * @NUM_NL80211_CRIT_PROTO: must be kept last. */ enum nl80211_crit_proto_id { NL80211_CRIT_PROTO_UNSPEC, NL80211_CRIT_PROTO_DHCP, NL80211_CRIT_PROTO_EAPOL, NL80211_CRIT_PROTO_APIPA, /* add other protocols before this one */ NUM_NL80211_CRIT_PROTO }; /* maximum duration for critical protocol measures */ #define NL80211_CRIT_PROTO_MAX_DURATION 5000 /* msec */ /** * enum nl80211_rxmgmt_flags - flags for received management frame. * * Used by cfg80211_rx_mgmt() * * @NL80211_RXMGMT_FLAG_ANSWERED: frame was answered by device/driver. * @NL80211_RXMGMT_FLAG_EXTERNAL_AUTH: Host driver intends to offload * the authentication. Exclusively defined for host drivers that * advertises the SME functionality but would like the userspace * to handle certain authentication algorithms (e.g. SAE). */ enum nl80211_rxmgmt_flags { NL80211_RXMGMT_FLAG_ANSWERED = 1 << 0, NL80211_RXMGMT_FLAG_EXTERNAL_AUTH = 1 << 1, }; /* * If this flag is unset, the lower 24 bits are an OUI, if set * a Linux nl80211 vendor ID is used (no such IDs are allocated * yet, so that's not valid so far) */ #define NL80211_VENDOR_ID_IS_LINUX 0x80000000 /** * struct nl80211_vendor_cmd_info - vendor command data * @vendor_id: If the %NL80211_VENDOR_ID_IS_LINUX flag is clear, then the * value is a 24-bit OUI; if it is set then a separately allocated ID * may be used, but no such IDs are allocated yet. New IDs should be * added to this file when needed. * @subcmd: sub-command ID for the command */ struct nl80211_vendor_cmd_info { __u32 vendor_id; __u32 subcmd; }; /** * enum nl80211_tdls_peer_capability - TDLS peer flags. * * Used by tdls_mgmt() to determine which conditional elements need * to be added to TDLS Setup frames. * * @NL80211_TDLS_PEER_HT: TDLS peer is HT capable. * @NL80211_TDLS_PEER_VHT: TDLS peer is VHT capable. * @NL80211_TDLS_PEER_WMM: TDLS peer is WMM capable. * @NL80211_TDLS_PEER_HE: TDLS peer is HE capable. */ enum nl80211_tdls_peer_capability { NL80211_TDLS_PEER_HT = 1<<0, NL80211_TDLS_PEER_VHT = 1<<1, NL80211_TDLS_PEER_WMM = 1<<2, NL80211_TDLS_PEER_HE = 1<<3, }; /** * enum nl80211_sched_scan_plan - scanning plan for scheduled scan * @__NL80211_SCHED_SCAN_PLAN_INVALID: attribute number 0 is reserved * @NL80211_SCHED_SCAN_PLAN_INTERVAL: interval between scan iterations. In * seconds (u32). * @NL80211_SCHED_SCAN_PLAN_ITERATIONS: number of scan iterations in this * scan plan (u32). The last scan plan must not specify this attribute * because it will run infinitely. A value of zero is invalid as it will * make the scan plan meaningless. * @NL80211_SCHED_SCAN_PLAN_MAX: highest scheduled scan plan attribute number * currently defined * @__NL80211_SCHED_SCAN_PLAN_AFTER_LAST: internal use */ enum nl80211_sched_scan_plan { __NL80211_SCHED_SCAN_PLAN_INVALID, NL80211_SCHED_SCAN_PLAN_INTERVAL, NL80211_SCHED_SCAN_PLAN_ITERATIONS, /* keep last */ __NL80211_SCHED_SCAN_PLAN_AFTER_LAST, NL80211_SCHED_SCAN_PLAN_MAX = __NL80211_SCHED_SCAN_PLAN_AFTER_LAST - 1 }; /** * struct nl80211_bss_select_rssi_adjust - RSSI adjustment parameters. * * @band: band of BSS that must match for RSSI value adjustment. The value * of this field is according to &enum nl80211_band. * @delta: value used to adjust the RSSI value of matching BSS in dB. */ struct nl80211_bss_select_rssi_adjust { __u8 band; __s8 delta; } __attribute__((packed)); /** * enum nl80211_bss_select_attr - attributes for bss selection. * * @__NL80211_BSS_SELECT_ATTR_INVALID: reserved. * @NL80211_BSS_SELECT_ATTR_RSSI: Flag indicating only RSSI-based BSS selection * is requested. * @NL80211_BSS_SELECT_ATTR_BAND_PREF: attribute indicating BSS * selection should be done such that the specified band is preferred. * When there are multiple BSS-es in the preferred band, the driver * shall use RSSI-based BSS selection as a second step. The value of * this attribute is according to &enum nl80211_band (u32). * @NL80211_BSS_SELECT_ATTR_RSSI_ADJUST: When present the RSSI level for * BSS-es in the specified band is to be adjusted before doing * RSSI-based BSS selection. The attribute value is a packed structure * value as specified by &struct nl80211_bss_select_rssi_adjust. * @NL80211_BSS_SELECT_ATTR_MAX: highest bss select attribute number. * @__NL80211_BSS_SELECT_ATTR_AFTER_LAST: internal use. * * One and only one of these attributes are found within %NL80211_ATTR_BSS_SELECT * for %NL80211_CMD_CONNECT. It specifies the required BSS selection behaviour * which the driver shall use. */ enum nl80211_bss_select_attr { __NL80211_BSS_SELECT_ATTR_INVALID, NL80211_BSS_SELECT_ATTR_RSSI, NL80211_BSS_SELECT_ATTR_BAND_PREF, NL80211_BSS_SELECT_ATTR_RSSI_ADJUST, /* keep last */ __NL80211_BSS_SELECT_ATTR_AFTER_LAST, NL80211_BSS_SELECT_ATTR_MAX = __NL80211_BSS_SELECT_ATTR_AFTER_LAST - 1 }; /** * enum nl80211_nan_function_type - NAN function type * * Defines the function type of a NAN function * * @NL80211_NAN_FUNC_PUBLISH: function is publish * @NL80211_NAN_FUNC_SUBSCRIBE: function is subscribe * @NL80211_NAN_FUNC_FOLLOW_UP: function is follow-up */ enum nl80211_nan_function_type { NL80211_NAN_FUNC_PUBLISH, NL80211_NAN_FUNC_SUBSCRIBE, NL80211_NAN_FUNC_FOLLOW_UP, /* keep last */ __NL80211_NAN_FUNC_TYPE_AFTER_LAST, NL80211_NAN_FUNC_MAX_TYPE = __NL80211_NAN_FUNC_TYPE_AFTER_LAST - 1, }; /** * enum nl80211_nan_publish_type - NAN publish tx type * * Defines how to send publish Service Discovery Frames * * @NL80211_NAN_SOLICITED_PUBLISH: publish function is solicited * @NL80211_NAN_UNSOLICITED_PUBLISH: publish function is unsolicited */ enum nl80211_nan_publish_type { NL80211_NAN_SOLICITED_PUBLISH = 1 << 0, NL80211_NAN_UNSOLICITED_PUBLISH = 1 << 1, }; /** * enum nl80211_nan_func_term_reason - NAN functions termination reason * * Defines termination reasons of a NAN function * * @NL80211_NAN_FUNC_TERM_REASON_USER_REQUEST: requested by user * @NL80211_NAN_FUNC_TERM_REASON_TTL_EXPIRED: timeout * @NL80211_NAN_FUNC_TERM_REASON_ERROR: errored */ enum nl80211_nan_func_term_reason { NL80211_NAN_FUNC_TERM_REASON_USER_REQUEST, NL80211_NAN_FUNC_TERM_REASON_TTL_EXPIRED, NL80211_NAN_FUNC_TERM_REASON_ERROR, }; #define NL80211_NAN_FUNC_SERVICE_ID_LEN 6 #define NL80211_NAN_FUNC_SERVICE_SPEC_INFO_MAX_LEN 0xff #define NL80211_NAN_FUNC_SRF_MAX_LEN 0xff /** * enum nl80211_nan_func_attributes - NAN function attributes * @__NL80211_NAN_FUNC_INVALID: invalid * @NL80211_NAN_FUNC_TYPE: &enum nl80211_nan_function_type (u8). * @NL80211_NAN_FUNC_SERVICE_ID: 6 bytes of the service ID hash as * specified in NAN spec. This is a binary attribute. * @NL80211_NAN_FUNC_PUBLISH_TYPE: relevant if the function's type is * publish. Defines the transmission type for the publish Service Discovery * Frame, see &enum nl80211_nan_publish_type. Its type is u8. * @NL80211_NAN_FUNC_PUBLISH_BCAST: relevant if the function is a solicited * publish. Should the solicited publish Service Discovery Frame be sent to * the NAN Broadcast address. This is a flag. * @NL80211_NAN_FUNC_SUBSCRIBE_ACTIVE: relevant if the function's type is * subscribe. Is the subscribe active. This is a flag. * @NL80211_NAN_FUNC_FOLLOW_UP_ID: relevant if the function's type is follow up. * The instance ID for the follow up Service Discovery Frame. This is u8. * @NL80211_NAN_FUNC_FOLLOW_UP_REQ_ID: relevant if the function's type * is follow up. This is a u8. * The requestor instance ID for the follow up Service Discovery Frame. * @NL80211_NAN_FUNC_FOLLOW_UP_DEST: the MAC address of the recipient of the * follow up Service Discovery Frame. This is a binary attribute. * @NL80211_NAN_FUNC_CLOSE_RANGE: is this function limited for devices in a * close range. The range itself (RSSI) is defined by the device. * This is a flag. * @NL80211_NAN_FUNC_TTL: strictly positive number of DWs this function should * stay active. If not present infinite TTL is assumed. This is a u32. * @NL80211_NAN_FUNC_SERVICE_INFO: array of bytes describing the service * specific info. This is a binary attribute. * @NL80211_NAN_FUNC_SRF: Service Receive Filter. This is a nested attribute. * See &enum nl80211_nan_srf_attributes. * @NL80211_NAN_FUNC_RX_MATCH_FILTER: Receive Matching filter. This is a nested * attribute. It is a list of binary values. * @NL80211_NAN_FUNC_TX_MATCH_FILTER: Transmit Matching filter. This is a * nested attribute. It is a list of binary values. * @NL80211_NAN_FUNC_INSTANCE_ID: The instance ID of the function. * Its type is u8 and it cannot be 0. * @NL80211_NAN_FUNC_TERM_REASON: NAN function termination reason. * See &enum nl80211_nan_func_term_reason. * * @NUM_NL80211_NAN_FUNC_ATTR: internal * @NL80211_NAN_FUNC_ATTR_MAX: highest NAN function attribute */ enum nl80211_nan_func_attributes { __NL80211_NAN_FUNC_INVALID, NL80211_NAN_FUNC_TYPE, NL80211_NAN_FUNC_SERVICE_ID, NL80211_NAN_FUNC_PUBLISH_TYPE, NL80211_NAN_FUNC_PUBLISH_BCAST, NL80211_NAN_FUNC_SUBSCRIBE_ACTIVE, NL80211_NAN_FUNC_FOLLOW_UP_ID, NL80211_NAN_FUNC_FOLLOW_UP_REQ_ID, NL80211_NAN_FUNC_FOLLOW_UP_DEST, NL80211_NAN_FUNC_CLOSE_RANGE, NL80211_NAN_FUNC_TTL, NL80211_NAN_FUNC_SERVICE_INFO, NL80211_NAN_FUNC_SRF, NL80211_NAN_FUNC_RX_MATCH_FILTER, NL80211_NAN_FUNC_TX_MATCH_FILTER, NL80211_NAN_FUNC_INSTANCE_ID, NL80211_NAN_FUNC_TERM_REASON, /* keep last */ NUM_NL80211_NAN_FUNC_ATTR, NL80211_NAN_FUNC_ATTR_MAX = NUM_NL80211_NAN_FUNC_ATTR - 1 }; /** * enum nl80211_nan_srf_attributes - NAN Service Response filter attributes * @__NL80211_NAN_SRF_INVALID: invalid * @NL80211_NAN_SRF_INCLUDE: present if the include bit of the SRF set. * This is a flag. * @NL80211_NAN_SRF_BF: Bloom Filter. Present if and only if * %NL80211_NAN_SRF_MAC_ADDRS isn't present. This attribute is binary. * @NL80211_NAN_SRF_BF_IDX: index of the Bloom Filter. Mandatory if * %NL80211_NAN_SRF_BF is present. This is a u8. * @NL80211_NAN_SRF_MAC_ADDRS: list of MAC addresses for the SRF. Present if * and only if %NL80211_NAN_SRF_BF isn't present. This is a nested * attribute. Each nested attribute is a MAC address. * @NUM_NL80211_NAN_SRF_ATTR: internal * @NL80211_NAN_SRF_ATTR_MAX: highest NAN SRF attribute */ enum nl80211_nan_srf_attributes { __NL80211_NAN_SRF_INVALID, NL80211_NAN_SRF_INCLUDE, NL80211_NAN_SRF_BF, NL80211_NAN_SRF_BF_IDX, NL80211_NAN_SRF_MAC_ADDRS, /* keep last */ NUM_NL80211_NAN_SRF_ATTR, NL80211_NAN_SRF_ATTR_MAX = NUM_NL80211_NAN_SRF_ATTR - 1, }; /** * enum nl80211_nan_match_attributes - NAN match attributes * @__NL80211_NAN_MATCH_INVALID: invalid * @NL80211_NAN_MATCH_FUNC_LOCAL: the local function that had the * match. This is a nested attribute. * See &enum nl80211_nan_func_attributes. * @NL80211_NAN_MATCH_FUNC_PEER: the peer function * that caused the match. This is a nested attribute. * See &enum nl80211_nan_func_attributes. * * @NUM_NL80211_NAN_MATCH_ATTR: internal * @NL80211_NAN_MATCH_ATTR_MAX: highest NAN match attribute */ enum nl80211_nan_match_attributes { __NL80211_NAN_MATCH_INVALID, NL80211_NAN_MATCH_FUNC_LOCAL, NL80211_NAN_MATCH_FUNC_PEER, /* keep last */ NUM_NL80211_NAN_MATCH_ATTR, NL80211_NAN_MATCH_ATTR_MAX = NUM_NL80211_NAN_MATCH_ATTR - 1 }; /** * nl80211_external_auth_action - Action to perform with external * authentication request. Used by NL80211_ATTR_EXTERNAL_AUTH_ACTION. * @NL80211_EXTERNAL_AUTH_START: Start the authentication. * @NL80211_EXTERNAL_AUTH_ABORT: Abort the ongoing authentication. */ enum nl80211_external_auth_action { NL80211_EXTERNAL_AUTH_START, NL80211_EXTERNAL_AUTH_ABORT, }; /** * enum nl80211_ftm_responder_attributes - fine timing measurement * responder attributes * @__NL80211_FTM_RESP_ATTR_INVALID: Invalid * @NL80211_FTM_RESP_ATTR_ENABLED: FTM responder is enabled * @NL80211_FTM_RESP_ATTR_LCI: The content of Measurement Report Element * (9.4.2.22 in 802.11-2016) with type 8 - LCI (9.4.2.22.10), * i.e. starting with the measurement token * @NL80211_FTM_RESP_ATTR_CIVIC: The content of Measurement Report Element * (9.4.2.22 in 802.11-2016) with type 11 - Civic (Section 9.4.2.22.13), * i.e. starting with the measurement token * @__NL80211_FTM_RESP_ATTR_LAST: Internal * @NL80211_FTM_RESP_ATTR_MAX: highest FTM responder attribute. */ enum nl80211_ftm_responder_attributes { __NL80211_FTM_RESP_ATTR_INVALID, NL80211_FTM_RESP_ATTR_ENABLED, NL80211_FTM_RESP_ATTR_LCI, NL80211_FTM_RESP_ATTR_CIVICLOC, /* keep last */ __NL80211_FTM_RESP_ATTR_LAST, NL80211_FTM_RESP_ATTR_MAX = __NL80211_FTM_RESP_ATTR_LAST - 1, }; /* * enum nl80211_ftm_responder_stats - FTM responder statistics * * These attribute types are used with %NL80211_ATTR_FTM_RESPONDER_STATS * when getting FTM responder statistics. * * @__NL80211_FTM_STATS_INVALID: attribute number 0 is reserved * @NL80211_FTM_STATS_SUCCESS_NUM: number of FTM sessions in which all frames * were ssfully answered (u32) * @NL80211_FTM_STATS_PARTIAL_NUM: number of FTM sessions in which part of the * frames were successfully answered (u32) * @NL80211_FTM_STATS_FAILED_NUM: number of failed FTM sessions (u32) * @NL80211_FTM_STATS_ASAP_NUM: number of ASAP sessions (u32) * @NL80211_FTM_STATS_NON_ASAP_NUM: number of non-ASAP sessions (u32) * @NL80211_FTM_STATS_TOTAL_DURATION_MSEC: total sessions durations - gives an * indication of how much time the responder was busy (u64, msec) * @NL80211_FTM_STATS_UNKNOWN_TRIGGERS_NUM: number of unknown FTM triggers - * triggers from initiators that didn't finish successfully the negotiation * phase with the responder (u32) * @NL80211_FTM_STATS_RESCHEDULE_REQUESTS_NUM: number of FTM reschedule requests * - initiator asks for a new scheduling although it already has scheduled * FTM slot (u32) * @NL80211_FTM_STATS_OUT_OF_WINDOW_TRIGGERS_NUM: number of FTM triggers out of * scheduled window (u32) * @NL80211_FTM_STATS_PAD: used for padding, ignore * @__NL80211_TXQ_ATTR_AFTER_LAST: Internal * @NL80211_FTM_STATS_MAX: highest possible FTM responder stats attribute */ enum nl80211_ftm_responder_stats { __NL80211_FTM_STATS_INVALID, NL80211_FTM_STATS_SUCCESS_NUM, NL80211_FTM_STATS_PARTIAL_NUM, NL80211_FTM_STATS_FAILED_NUM, NL80211_FTM_STATS_ASAP_NUM, NL80211_FTM_STATS_NON_ASAP_NUM, NL80211_FTM_STATS_TOTAL_DURATION_MSEC, NL80211_FTM_STATS_UNKNOWN_TRIGGERS_NUM, NL80211_FTM_STATS_RESCHEDULE_REQUESTS_NUM, NL80211_FTM_STATS_OUT_OF_WINDOW_TRIGGERS_NUM, NL80211_FTM_STATS_PAD, /* keep last */ __NL80211_FTM_STATS_AFTER_LAST, NL80211_FTM_STATS_MAX = __NL80211_FTM_STATS_AFTER_LAST - 1 }; /** * enum nl80211_preamble - frame preamble types * @NL80211_PREAMBLE_LEGACY: legacy (HR/DSSS, OFDM, ERP PHY) preamble * @NL80211_PREAMBLE_HT: HT preamble * @NL80211_PREAMBLE_VHT: VHT preamble * @NL80211_PREAMBLE_DMG: DMG preamble * @NL80211_PREAMBLE_HE: HE preamble */ enum nl80211_preamble { NL80211_PREAMBLE_LEGACY, NL80211_PREAMBLE_HT, NL80211_PREAMBLE_VHT, NL80211_PREAMBLE_DMG, NL80211_PREAMBLE_HE, }; /** * enum nl80211_peer_measurement_type - peer measurement types * @NL80211_PMSR_TYPE_INVALID: invalid/unused, needed as we use * these numbers also for attributes * * @NL80211_PMSR_TYPE_FTM: flight time measurement * * @NUM_NL80211_PMSR_TYPES: internal * @NL80211_PMSR_TYPE_MAX: highest type number */ enum nl80211_peer_measurement_type { NL80211_PMSR_TYPE_INVALID, NL80211_PMSR_TYPE_FTM, NUM_NL80211_PMSR_TYPES, NL80211_PMSR_TYPE_MAX = NUM_NL80211_PMSR_TYPES - 1 }; /** * enum nl80211_peer_measurement_status - peer measurement status * @NL80211_PMSR_STATUS_SUCCESS: measurement completed successfully * @NL80211_PMSR_STATUS_REFUSED: measurement was locally refused * @NL80211_PMSR_STATUS_TIMEOUT: measurement timed out * @NL80211_PMSR_STATUS_FAILURE: measurement failed, a type-dependent * reason may be available in the response data */ enum nl80211_peer_measurement_status { NL80211_PMSR_STATUS_SUCCESS, NL80211_PMSR_STATUS_REFUSED, NL80211_PMSR_STATUS_TIMEOUT, NL80211_PMSR_STATUS_FAILURE, }; /** * enum nl80211_peer_measurement_req - peer measurement request attributes * @__NL80211_PMSR_REQ_ATTR_INVALID: invalid * * @NL80211_PMSR_REQ_ATTR_DATA: This is a nested attribute with measurement * type-specific request data inside. The attributes used are from the * enums named nl80211_peer_measurement__req. * @NL80211_PMSR_REQ_ATTR_GET_AP_TSF: include AP TSF timestamp, if supported * (flag attribute) * * @NUM_NL80211_PMSR_REQ_ATTRS: internal * @NL80211_PMSR_REQ_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_req { __NL80211_PMSR_REQ_ATTR_INVALID, NL80211_PMSR_REQ_ATTR_DATA, NL80211_PMSR_REQ_ATTR_GET_AP_TSF, /* keep last */ NUM_NL80211_PMSR_REQ_ATTRS, NL80211_PMSR_REQ_ATTR_MAX = NUM_NL80211_PMSR_REQ_ATTRS - 1 }; /** * enum nl80211_peer_measurement_resp - peer measurement response attributes * @__NL80211_PMSR_RESP_ATTR_INVALID: invalid * * @NL80211_PMSR_RESP_ATTR_DATA: This is a nested attribute with measurement * type-specific results inside. The attributes used are from the enums * named nl80211_peer_measurement__resp. * @NL80211_PMSR_RESP_ATTR_STATUS: u32 value with the measurement status * (using values from &enum nl80211_peer_measurement_status.) * @NL80211_PMSR_RESP_ATTR_HOST_TIME: host time (%CLOCK_BOOTTIME) when the * result was measured; this value is not expected to be accurate to * more than 20ms. (u64, nanoseconds) * @NL80211_PMSR_RESP_ATTR_AP_TSF: TSF of the AP that the interface * doing the measurement is connected to when the result was measured. * This shall be accurately reported if supported and requested * (u64, usec) * @NL80211_PMSR_RESP_ATTR_FINAL: If results are sent to the host partially * (*e.g. with FTM per-burst data) this flag will be cleared on all but * the last result; if all results are combined it's set on the single * result. * @NL80211_PMSR_RESP_ATTR_PAD: padding for 64-bit attributes, ignore * * @NUM_NL80211_PMSR_RESP_ATTRS: internal * @NL80211_PMSR_RESP_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_resp { __NL80211_PMSR_RESP_ATTR_INVALID, NL80211_PMSR_RESP_ATTR_DATA, NL80211_PMSR_RESP_ATTR_STATUS, NL80211_PMSR_RESP_ATTR_HOST_TIME, NL80211_PMSR_RESP_ATTR_AP_TSF, NL80211_PMSR_RESP_ATTR_FINAL, NL80211_PMSR_RESP_ATTR_PAD, /* keep last */ NUM_NL80211_PMSR_RESP_ATTRS, NL80211_PMSR_RESP_ATTR_MAX = NUM_NL80211_PMSR_RESP_ATTRS - 1 }; /** * enum nl80211_peer_measurement_peer_attrs - peer attributes for measurement * @__NL80211_PMSR_PEER_ATTR_INVALID: invalid * * @NL80211_PMSR_PEER_ATTR_ADDR: peer's MAC address * @NL80211_PMSR_PEER_ATTR_CHAN: channel definition, nested, using top-level * attributes like %NL80211_ATTR_WIPHY_FREQ etc. * @NL80211_PMSR_PEER_ATTR_REQ: This is a nested attribute indexed by * measurement type, with attributes from the * &enum nl80211_peer_measurement_req inside. * @NL80211_PMSR_PEER_ATTR_RESP: This is a nested attribute indexed by * measurement type, with attributes from the * &enum nl80211_peer_measurement_resp inside. * * @NUM_NL80211_PMSR_PEER_ATTRS: internal * @NL80211_PMSR_PEER_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_peer_attrs { __NL80211_PMSR_PEER_ATTR_INVALID, NL80211_PMSR_PEER_ATTR_ADDR, NL80211_PMSR_PEER_ATTR_CHAN, NL80211_PMSR_PEER_ATTR_REQ, NL80211_PMSR_PEER_ATTR_RESP, /* keep last */ NUM_NL80211_PMSR_PEER_ATTRS, NL80211_PMSR_PEER_ATTR_MAX = NUM_NL80211_PMSR_PEER_ATTRS - 1, }; /** * enum nl80211_peer_measurement_attrs - peer measurement attributes * @__NL80211_PMSR_ATTR_INVALID: invalid * * @NL80211_PMSR_ATTR_MAX_PEERS: u32 attribute used for capability * advertisement only, indicates the maximum number of peers * measurements can be done with in a single request * @NL80211_PMSR_ATTR_REPORT_AP_TSF: flag attribute in capability * indicating that the connected AP's TSF can be reported in * measurement results * @NL80211_PMSR_ATTR_RANDOMIZE_MAC_ADDR: flag attribute in capability * indicating that MAC address randomization is supported. * @NL80211_PMSR_ATTR_TYPE_CAPA: capabilities reported by the device, * this contains a nesting indexed by measurement type, and * type-specific capabilities inside, which are from the enums * named nl80211_peer_measurement__capa. * @NL80211_PMSR_ATTR_PEERS: nested attribute, the nesting index is * meaningless, just a list of peers to measure with, with the * sub-attributes taken from * &enum nl80211_peer_measurement_peer_attrs. * * @NUM_NL80211_PMSR_ATTR: internal * @NL80211_PMSR_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_attrs { __NL80211_PMSR_ATTR_INVALID, NL80211_PMSR_ATTR_MAX_PEERS, NL80211_PMSR_ATTR_REPORT_AP_TSF, NL80211_PMSR_ATTR_RANDOMIZE_MAC_ADDR, NL80211_PMSR_ATTR_TYPE_CAPA, NL80211_PMSR_ATTR_PEERS, /* keep last */ NUM_NL80211_PMSR_ATTR, NL80211_PMSR_ATTR_MAX = NUM_NL80211_PMSR_ATTR - 1 }; /** * enum nl80211_peer_measurement_ftm_capa - FTM capabilities * @__NL80211_PMSR_FTM_CAPA_ATTR_INVALID: invalid * * @NL80211_PMSR_FTM_CAPA_ATTR_ASAP: flag attribute indicating ASAP mode * is supported * @NL80211_PMSR_FTM_CAPA_ATTR_NON_ASAP: flag attribute indicating non-ASAP * mode is supported * @NL80211_PMSR_FTM_CAPA_ATTR_REQ_LCI: flag attribute indicating if LCI * data can be requested during the measurement * @NL80211_PMSR_FTM_CAPA_ATTR_REQ_CIVICLOC: flag attribute indicating if civic * location data can be requested during the measurement * @NL80211_PMSR_FTM_CAPA_ATTR_PREAMBLES: u32 bitmap attribute of bits * from &enum nl80211_preamble. * @NL80211_PMSR_FTM_CAPA_ATTR_BANDWIDTHS: bitmap of values from * &enum nl80211_chan_width indicating the supported channel * bandwidths for FTM. Note that a higher channel bandwidth may be * configured to allow for other measurements types with different * bandwidth requirement in the same measurement. * @NL80211_PMSR_FTM_CAPA_ATTR_MAX_BURSTS_EXPONENT: u32 attribute indicating * the maximum bursts exponent that can be used (if not present anything * is valid) * @NL80211_PMSR_FTM_CAPA_ATTR_MAX_FTMS_PER_BURST: u32 attribute indicating * the maximum FTMs per burst (if not present anything is valid) * @NL80211_PMSR_FTM_CAPA_ATTR_TRIGGER_BASED: flag attribute indicating if * trigger based ranging measurement is supported * @NL80211_PMSR_FTM_CAPA_ATTR_NON_TRIGGER_BASED: flag attribute indicating * if non trigger based ranging measurement is supported * * @NUM_NL80211_PMSR_FTM_CAPA_ATTR: internal * @NL80211_PMSR_FTM_CAPA_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_ftm_capa { __NL80211_PMSR_FTM_CAPA_ATTR_INVALID, NL80211_PMSR_FTM_CAPA_ATTR_ASAP, NL80211_PMSR_FTM_CAPA_ATTR_NON_ASAP, NL80211_PMSR_FTM_CAPA_ATTR_REQ_LCI, NL80211_PMSR_FTM_CAPA_ATTR_REQ_CIVICLOC, NL80211_PMSR_FTM_CAPA_ATTR_PREAMBLES, NL80211_PMSR_FTM_CAPA_ATTR_BANDWIDTHS, NL80211_PMSR_FTM_CAPA_ATTR_MAX_BURSTS_EXPONENT, NL80211_PMSR_FTM_CAPA_ATTR_MAX_FTMS_PER_BURST, NL80211_PMSR_FTM_CAPA_ATTR_TRIGGER_BASED, NL80211_PMSR_FTM_CAPA_ATTR_NON_TRIGGER_BASED, /* keep last */ NUM_NL80211_PMSR_FTM_CAPA_ATTR, NL80211_PMSR_FTM_CAPA_ATTR_MAX = NUM_NL80211_PMSR_FTM_CAPA_ATTR - 1 }; /** * enum nl80211_peer_measurement_ftm_req - FTM request attributes * @__NL80211_PMSR_FTM_REQ_ATTR_INVALID: invalid * * @NL80211_PMSR_FTM_REQ_ATTR_ASAP: ASAP mode requested (flag) * @NL80211_PMSR_FTM_REQ_ATTR_PREAMBLE: preamble type (see * &enum nl80211_preamble), optional for DMG (u32) * @NL80211_PMSR_FTM_REQ_ATTR_NUM_BURSTS_EXP: number of bursts exponent as in * 802.11-2016 9.4.2.168 "Fine Timing Measurement Parameters element" * (u8, 0-15, optional with default 15 i.e. "no preference") * @NL80211_PMSR_FTM_REQ_ATTR_BURST_PERIOD: interval between bursts in units * of 100ms (u16, optional with default 0) * @NL80211_PMSR_FTM_REQ_ATTR_BURST_DURATION: burst duration, as in 802.11-2016 * Table 9-257 "Burst Duration field encoding" (u8, 0-15, optional with * default 15 i.e. "no preference") * @NL80211_PMSR_FTM_REQ_ATTR_FTMS_PER_BURST: number of successful FTM frames * requested per burst * (u8, 0-31, optional with default 0 i.e. "no preference") * @NL80211_PMSR_FTM_REQ_ATTR_NUM_FTMR_RETRIES: number of FTMR frame retries * (u8, default 3) * @NL80211_PMSR_FTM_REQ_ATTR_REQUEST_LCI: request LCI data (flag) * @NL80211_PMSR_FTM_REQ_ATTR_REQUEST_CIVICLOC: request civic location data * (flag) * @NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED: request trigger based ranging * measurement (flag). * This attribute and %NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED are * mutually exclusive. * if neither %NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED nor * %NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED is set, EDCA based * ranging will be used. * @NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED: request non trigger based * ranging measurement (flag) * This attribute and %NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED are * mutually exclusive. * if neither %NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED nor * %NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED is set, EDCA based * ranging will be used. * @NL80211_PMSR_FTM_REQ_ATTR_LMR_FEEDBACK: negotiate for LMR feedback. Only * valid if either %NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED or * %NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED is set. * @NL80211_PMSR_FTM_REQ_ATTR_BSS_COLOR: optional. The BSS color of the * responder. Only valid if %NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED * or %NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED is set. * * @NUM_NL80211_PMSR_FTM_REQ_ATTR: internal * @NL80211_PMSR_FTM_REQ_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_ftm_req { __NL80211_PMSR_FTM_REQ_ATTR_INVALID, NL80211_PMSR_FTM_REQ_ATTR_ASAP, NL80211_PMSR_FTM_REQ_ATTR_PREAMBLE, NL80211_PMSR_FTM_REQ_ATTR_NUM_BURSTS_EXP, NL80211_PMSR_FTM_REQ_ATTR_BURST_PERIOD, NL80211_PMSR_FTM_REQ_ATTR_BURST_DURATION, NL80211_PMSR_FTM_REQ_ATTR_FTMS_PER_BURST, NL80211_PMSR_FTM_REQ_ATTR_NUM_FTMR_RETRIES, NL80211_PMSR_FTM_REQ_ATTR_REQUEST_LCI, NL80211_PMSR_FTM_REQ_ATTR_REQUEST_CIVICLOC, NL80211_PMSR_FTM_REQ_ATTR_TRIGGER_BASED, NL80211_PMSR_FTM_REQ_ATTR_NON_TRIGGER_BASED, NL80211_PMSR_FTM_REQ_ATTR_LMR_FEEDBACK, NL80211_PMSR_FTM_REQ_ATTR_BSS_COLOR, /* keep last */ NUM_NL80211_PMSR_FTM_REQ_ATTR, NL80211_PMSR_FTM_REQ_ATTR_MAX = NUM_NL80211_PMSR_FTM_REQ_ATTR - 1 }; /** * enum nl80211_peer_measurement_ftm_failure_reasons - FTM failure reasons * @NL80211_PMSR_FTM_FAILURE_UNSPECIFIED: unspecified failure, not used * @NL80211_PMSR_FTM_FAILURE_NO_RESPONSE: no response from the FTM responder * @NL80211_PMSR_FTM_FAILURE_REJECTED: FTM responder rejected measurement * @NL80211_PMSR_FTM_FAILURE_WRONG_CHANNEL: we already know the peer is * on a different channel, so can't measure (if we didn't know, we'd * try and get no response) * @NL80211_PMSR_FTM_FAILURE_PEER_NOT_CAPABLE: peer can't actually do FTM * @NL80211_PMSR_FTM_FAILURE_INVALID_TIMESTAMP: invalid T1/T4 timestamps * received * @NL80211_PMSR_FTM_FAILURE_PEER_BUSY: peer reports busy, you may retry * later (see %NL80211_PMSR_FTM_RESP_ATTR_BUSY_RETRY_TIME) * @NL80211_PMSR_FTM_FAILURE_BAD_CHANGED_PARAMS: parameters were changed * by the peer and are no longer supported */ enum nl80211_peer_measurement_ftm_failure_reasons { NL80211_PMSR_FTM_FAILURE_UNSPECIFIED, NL80211_PMSR_FTM_FAILURE_NO_RESPONSE, NL80211_PMSR_FTM_FAILURE_REJECTED, NL80211_PMSR_FTM_FAILURE_WRONG_CHANNEL, NL80211_PMSR_FTM_FAILURE_PEER_NOT_CAPABLE, NL80211_PMSR_FTM_FAILURE_INVALID_TIMESTAMP, NL80211_PMSR_FTM_FAILURE_PEER_BUSY, NL80211_PMSR_FTM_FAILURE_BAD_CHANGED_PARAMS, }; /** * enum nl80211_peer_measurement_ftm_resp - FTM response attributes * @__NL80211_PMSR_FTM_RESP_ATTR_INVALID: invalid * * @NL80211_PMSR_FTM_RESP_ATTR_FAIL_REASON: FTM-specific failure reason * (u32, optional) * @NL80211_PMSR_FTM_RESP_ATTR_BURST_INDEX: optional, if bursts are reported * as separate results then it will be the burst index 0...(N-1) and * the top level will indicate partial results (u32) * @NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_ATTEMPTS: number of FTM Request frames * transmitted (u32, optional) * @NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_SUCCESSES: number of FTM Request frames * that were acknowleged (u32, optional) * @NL80211_PMSR_FTM_RESP_ATTR_BUSY_RETRY_TIME: retry time received from the * busy peer (u32, seconds) * @NL80211_PMSR_FTM_RESP_ATTR_NUM_BURSTS_EXP: actual number of bursts exponent * used by the responder (similar to request, u8) * @NL80211_PMSR_FTM_RESP_ATTR_BURST_DURATION: actual burst duration used by * the responder (similar to request, u8) * @NL80211_PMSR_FTM_RESP_ATTR_FTMS_PER_BURST: actual FTMs per burst used * by the responder (similar to request, u8) * @NL80211_PMSR_FTM_RESP_ATTR_RSSI_AVG: average RSSI across all FTM action * frames (optional, s32, 1/2 dBm) * @NL80211_PMSR_FTM_RESP_ATTR_RSSI_SPREAD: RSSI spread across all FTM action * frames (optional, s32, 1/2 dBm) * @NL80211_PMSR_FTM_RESP_ATTR_TX_RATE: bitrate we used for the response to the * FTM action frame (optional, nested, using &enum nl80211_rate_info * attributes) * @NL80211_PMSR_FTM_RESP_ATTR_RX_RATE: bitrate the responder used for the FTM * action frame (optional, nested, using &enum nl80211_rate_info attrs) * @NL80211_PMSR_FTM_RESP_ATTR_RTT_AVG: average RTT (s64, picoseconds, optional * but one of RTT/DIST must be present) * @NL80211_PMSR_FTM_RESP_ATTR_RTT_VARIANCE: RTT variance (u64, ps^2, note that * standard deviation is the square root of variance, optional) * @NL80211_PMSR_FTM_RESP_ATTR_RTT_SPREAD: RTT spread (u64, picoseconds, * optional) * @NL80211_PMSR_FTM_RESP_ATTR_DIST_AVG: average distance (s64, mm, optional * but one of RTT/DIST must be present) * @NL80211_PMSR_FTM_RESP_ATTR_DIST_VARIANCE: distance variance (u64, mm^2, note * that standard deviation is the square root of variance, optional) * @NL80211_PMSR_FTM_RESP_ATTR_DIST_SPREAD: distance spread (u64, mm, optional) * @NL80211_PMSR_FTM_RESP_ATTR_LCI: LCI data from peer (binary, optional); * this is the contents of the Measurement Report Element (802.11-2016 * 9.4.2.22.1) starting with the Measurement Token, with Measurement * Type 8. * @NL80211_PMSR_FTM_RESP_ATTR_CIVICLOC: civic location data from peer * (binary, optional); * this is the contents of the Measurement Report Element (802.11-2016 * 9.4.2.22.1) starting with the Measurement Token, with Measurement * Type 11. * @NL80211_PMSR_FTM_RESP_ATTR_PAD: ignore, for u64/s64 padding only * * @NUM_NL80211_PMSR_FTM_RESP_ATTR: internal * @NL80211_PMSR_FTM_RESP_ATTR_MAX: highest attribute number */ enum nl80211_peer_measurement_ftm_resp { __NL80211_PMSR_FTM_RESP_ATTR_INVALID, NL80211_PMSR_FTM_RESP_ATTR_FAIL_REASON, NL80211_PMSR_FTM_RESP_ATTR_BURST_INDEX, NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_ATTEMPTS, NL80211_PMSR_FTM_RESP_ATTR_NUM_FTMR_SUCCESSES, NL80211_PMSR_FTM_RESP_ATTR_BUSY_RETRY_TIME, NL80211_PMSR_FTM_RESP_ATTR_NUM_BURSTS_EXP, NL80211_PMSR_FTM_RESP_ATTR_BURST_DURATION, NL80211_PMSR_FTM_RESP_ATTR_FTMS_PER_BURST, NL80211_PMSR_FTM_RESP_ATTR_RSSI_AVG, NL80211_PMSR_FTM_RESP_ATTR_RSSI_SPREAD, NL80211_PMSR_FTM_RESP_ATTR_TX_RATE, NL80211_PMSR_FTM_RESP_ATTR_RX_RATE, NL80211_PMSR_FTM_RESP_ATTR_RTT_AVG, NL80211_PMSR_FTM_RESP_ATTR_RTT_VARIANCE, NL80211_PMSR_FTM_RESP_ATTR_RTT_SPREAD, NL80211_PMSR_FTM_RESP_ATTR_DIST_AVG, NL80211_PMSR_FTM_RESP_ATTR_DIST_VARIANCE, NL80211_PMSR_FTM_RESP_ATTR_DIST_SPREAD, NL80211_PMSR_FTM_RESP_ATTR_LCI, NL80211_PMSR_FTM_RESP_ATTR_CIVICLOC, NL80211_PMSR_FTM_RESP_ATTR_PAD, /* keep last */ NUM_NL80211_PMSR_FTM_RESP_ATTR, NL80211_PMSR_FTM_RESP_ATTR_MAX = NUM_NL80211_PMSR_FTM_RESP_ATTR - 1 }; /** * enum nl80211_obss_pd_attributes - OBSS packet detection attributes * @__NL80211_HE_OBSS_PD_ATTR_INVALID: Invalid * * @NL80211_HE_OBSS_PD_ATTR_MIN_OFFSET: the OBSS PD minimum tx power offset. * @NL80211_HE_OBSS_PD_ATTR_MAX_OFFSET: the OBSS PD maximum tx power offset. * @NL80211_HE_OBSS_PD_ATTR_NON_SRG_MAX_OFFSET: the non-SRG OBSS PD maximum * tx power offset. * @NL80211_HE_OBSS_PD_ATTR_BSS_COLOR_BITMAP: bitmap that indicates the BSS color * values used by members of the SRG. * @NL80211_HE_OBSS_PD_ATTR_PARTIAL_BSSID_BITMAP: bitmap that indicates the partial * BSSID values used by members of the SRG. * @NL80211_HE_OBSS_PD_ATTR_SR_CTRL: The SR Control field of SRP element. * * @__NL80211_HE_OBSS_PD_ATTR_LAST: Internal * @NL80211_HE_OBSS_PD_ATTR_MAX: highest OBSS PD attribute. */ enum nl80211_obss_pd_attributes { __NL80211_HE_OBSS_PD_ATTR_INVALID, NL80211_HE_OBSS_PD_ATTR_MIN_OFFSET, NL80211_HE_OBSS_PD_ATTR_MAX_OFFSET, NL80211_HE_OBSS_PD_ATTR_NON_SRG_MAX_OFFSET, NL80211_HE_OBSS_PD_ATTR_BSS_COLOR_BITMAP, NL80211_HE_OBSS_PD_ATTR_PARTIAL_BSSID_BITMAP, NL80211_HE_OBSS_PD_ATTR_SR_CTRL, /* keep last */ __NL80211_HE_OBSS_PD_ATTR_LAST, NL80211_HE_OBSS_PD_ATTR_MAX = __NL80211_HE_OBSS_PD_ATTR_LAST - 1, }; /** * enum nl80211_bss_color_attributes - BSS Color attributes * @__NL80211_HE_BSS_COLOR_ATTR_INVALID: Invalid * * @NL80211_HE_BSS_COLOR_ATTR_COLOR: the current BSS Color. * @NL80211_HE_BSS_COLOR_ATTR_DISABLED: is BSS coloring disabled. * @NL80211_HE_BSS_COLOR_ATTR_PARTIAL: the AID equation to be used.. * * @__NL80211_HE_BSS_COLOR_ATTR_LAST: Internal * @NL80211_HE_BSS_COLOR_ATTR_MAX: highest BSS Color attribute. */ enum nl80211_bss_color_attributes { __NL80211_HE_BSS_COLOR_ATTR_INVALID, NL80211_HE_BSS_COLOR_ATTR_COLOR, NL80211_HE_BSS_COLOR_ATTR_DISABLED, NL80211_HE_BSS_COLOR_ATTR_PARTIAL, /* keep last */ __NL80211_HE_BSS_COLOR_ATTR_LAST, NL80211_HE_BSS_COLOR_ATTR_MAX = __NL80211_HE_BSS_COLOR_ATTR_LAST - 1, }; /** * enum nl80211_iftype_akm_attributes - interface type AKM attributes * @__NL80211_IFTYPE_AKM_ATTR_INVALID: Invalid * * @NL80211_IFTYPE_AKM_ATTR_IFTYPES: nested attribute containing a flag * attribute for each interface type that supports AKM suites specified in * %NL80211_IFTYPE_AKM_ATTR_SUITES * @NL80211_IFTYPE_AKM_ATTR_SUITES: an array of u32. Used to indicate supported * AKM suites for the specified interface types. * * @__NL80211_IFTYPE_AKM_ATTR_LAST: Internal * @NL80211_IFTYPE_AKM_ATTR_MAX: highest interface type AKM attribute. */ enum nl80211_iftype_akm_attributes { __NL80211_IFTYPE_AKM_ATTR_INVALID, NL80211_IFTYPE_AKM_ATTR_IFTYPES, NL80211_IFTYPE_AKM_ATTR_SUITES, /* keep last */ __NL80211_IFTYPE_AKM_ATTR_LAST, NL80211_IFTYPE_AKM_ATTR_MAX = __NL80211_IFTYPE_AKM_ATTR_LAST - 1, }; /** * enum nl80211_fils_discovery_attributes - FILS discovery configuration * from IEEE Std 802.11ai-2016, Annex C.3 MIB detail. * * @__NL80211_FILS_DISCOVERY_ATTR_INVALID: Invalid * * @NL80211_FILS_DISCOVERY_ATTR_INT_MIN: Minimum packet interval (u32, TU). * Allowed range: 0..10000 (TU = Time Unit) * @NL80211_FILS_DISCOVERY_ATTR_INT_MAX: Maximum packet interval (u32, TU). * Allowed range: 0..10000 (TU = Time Unit) * @NL80211_FILS_DISCOVERY_ATTR_TMPL: Template data for FILS discovery action * frame including the headers. * * @__NL80211_FILS_DISCOVERY_ATTR_LAST: Internal * @NL80211_FILS_DISCOVERY_ATTR_MAX: highest attribute */ enum nl80211_fils_discovery_attributes { __NL80211_FILS_DISCOVERY_ATTR_INVALID, NL80211_FILS_DISCOVERY_ATTR_INT_MIN, NL80211_FILS_DISCOVERY_ATTR_INT_MAX, NL80211_FILS_DISCOVERY_ATTR_TMPL, /* keep last */ __NL80211_FILS_DISCOVERY_ATTR_LAST, NL80211_FILS_DISCOVERY_ATTR_MAX = __NL80211_FILS_DISCOVERY_ATTR_LAST - 1 }; /* * FILS discovery template minimum length with action frame headers and * mandatory fields. */ #define NL80211_FILS_DISCOVERY_TMPL_MIN_LEN 42 /** * enum nl80211_unsol_bcast_probe_resp_attributes - Unsolicited broadcast probe * response configuration. Applicable only in 6GHz. * * @__NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_INVALID: Invalid * * @NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_INT: Maximum packet interval (u32, TU). * Allowed range: 0..20 (TU = Time Unit). IEEE P802.11ax/D6.0 * 26.17.2.3.2 (AP behavior for fast passive scanning). * @NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_TMPL: Unsolicited broadcast probe response * frame template (binary). * * @__NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_LAST: Internal * @NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_MAX: highest attribute */ enum nl80211_unsol_bcast_probe_resp_attributes { __NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_INVALID, NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_INT, NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_TMPL, /* keep last */ __NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_LAST, NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_MAX = __NL80211_UNSOL_BCAST_PROBE_RESP_ATTR_LAST - 1 }; /** * enum nl80211_sae_pwe_mechanism - The mechanism(s) allowed for SAE PWE * derivation. Applicable only when WPA3-Personal SAE authentication is * used. * * @NL80211_SAE_PWE_UNSPECIFIED: not specified, used internally to indicate that * attribute is not present from userspace. * @NL80211_SAE_PWE_HUNT_AND_PECK: hunting-and-pecking loop only * @NL80211_SAE_PWE_HASH_TO_ELEMENT: hash-to-element only * @NL80211_SAE_PWE_BOTH: both hunting-and-pecking loop and hash-to-element * can be used. */ enum nl80211_sae_pwe_mechanism { NL80211_SAE_PWE_UNSPECIFIED, NL80211_SAE_PWE_HUNT_AND_PECK, NL80211_SAE_PWE_HASH_TO_ELEMENT, NL80211_SAE_PWE_BOTH, }; /** * enum nl80211_sar_type - type of SAR specs * * @NL80211_SAR_TYPE_POWER: power limitation specified in 0.25dBm unit * */ enum nl80211_sar_type { NL80211_SAR_TYPE_POWER, /* add new type here */ /* Keep last */ NUM_NL80211_SAR_TYPE, }; /** * enum nl80211_sar_attrs - Attributes for SAR spec * * @NL80211_SAR_ATTR_TYPE: the SAR type as defined in &enum nl80211_sar_type. * * @NL80211_SAR_ATTR_SPECS: Nested array of SAR power * limit specifications. Each specification contains a set * of %nl80211_sar_specs_attrs. * * For SET operation, it contains array of %NL80211_SAR_ATTR_SPECS_POWER * and %NL80211_SAR_ATTR_SPECS_RANGE_INDEX. * * For sar_capa dump, it contains array of * %NL80211_SAR_ATTR_SPECS_START_FREQ * and %NL80211_SAR_ATTR_SPECS_END_FREQ. * * @__NL80211_SAR_ATTR_LAST: Internal * @NL80211_SAR_ATTR_MAX: highest sar attribute * * These attributes are used with %NL80211_CMD_SET_SAR_SPEC */ enum nl80211_sar_attrs { __NL80211_SAR_ATTR_INVALID, NL80211_SAR_ATTR_TYPE, NL80211_SAR_ATTR_SPECS, __NL80211_SAR_ATTR_LAST, NL80211_SAR_ATTR_MAX = __NL80211_SAR_ATTR_LAST - 1, }; /** * enum nl80211_sar_specs_attrs - Attributes for SAR power limit specs * * @NL80211_SAR_ATTR_SPECS_POWER: Required (s32)value to specify the actual * power limit value in units of 0.25 dBm if type is * NL80211_SAR_TYPE_POWER. (i.e., a value of 44 represents 11 dBm). * 0 means userspace doesn't have SAR limitation on this associated range. * * @NL80211_SAR_ATTR_SPECS_RANGE_INDEX: Required (u32) value to specify the * index of exported freq range table and the associated power limitation * is applied to this range. * * Userspace isn't required to set all the ranges advertised by WLAN driver, * and userspace can skip some certain ranges. These skipped ranges don't * have SAR limitations, and they are same as setting the * %NL80211_SAR_ATTR_SPECS_POWER to any unreasonable high value because any * value higher than regulatory allowed value just means SAR power * limitation is removed, but it's required to set at least one range. * It's not allowed to set duplicated range in one SET operation. * * Every SET operation overwrites previous SET operation. * * @NL80211_SAR_ATTR_SPECS_START_FREQ: Required (u32) value to specify the start * frequency of this range edge when registering SAR capability to wiphy. * It's not a channel center frequency. The unit is kHz. * * @NL80211_SAR_ATTR_SPECS_END_FREQ: Required (u32) value to specify the end * frequency of this range edge when registering SAR capability to wiphy. * It's not a channel center frequency. The unit is kHz. * * @__NL80211_SAR_ATTR_SPECS_LAST: Internal * @NL80211_SAR_ATTR_SPECS_MAX: highest sar specs attribute */ enum nl80211_sar_specs_attrs { __NL80211_SAR_ATTR_SPECS_INVALID, NL80211_SAR_ATTR_SPECS_POWER, NL80211_SAR_ATTR_SPECS_RANGE_INDEX, NL80211_SAR_ATTR_SPECS_START_FREQ, NL80211_SAR_ATTR_SPECS_END_FREQ, __NL80211_SAR_ATTR_SPECS_LAST, NL80211_SAR_ATTR_SPECS_MAX = __NL80211_SAR_ATTR_SPECS_LAST - 1, }; /** * enum nl80211_mbssid_config_attributes - multiple BSSID (MBSSID) and enhanced * multi-BSSID advertisements (EMA) in AP mode. * Kernel uses some of these attributes to advertise driver's support for * MBSSID and EMA. * Remaining attributes should be used by the userspace to configure the * features. * * @__NL80211_MBSSID_CONFIG_ATTR_INVALID: Invalid * * @NL80211_MBSSID_CONFIG_ATTR_MAX_INTERFACES: Used by the kernel to advertise * the maximum number of MBSSID interfaces supported by the driver. * Driver should indicate MBSSID support by setting * wiphy->mbssid_max_interfaces to a value more than or equal to 2. * * @NL80211_MBSSID_CONFIG_ATTR_MAX_EMA_PROFILE_PERIODICITY: Used by the kernel * to advertise the maximum profile periodicity supported by the driver * if EMA is enabled. Driver should indicate EMA support to the userspace * by setting wiphy->ema_max_profile_periodicity to * a non-zero value. * * @NL80211_MBSSID_CONFIG_ATTR_INDEX: Mandatory parameter to pass the index of * this BSS (u8) in the multiple BSSID set. * Value must be set to 0 for the transmitting interface and non-zero for * all non-transmitting interfaces. The userspace will be responsible * for using unique indices for the interfaces. * Range: 0 to wiphy->mbssid_max_interfaces-1. * * @NL80211_MBSSID_CONFIG_ATTR_TX_IFINDEX: Mandatory parameter for * a non-transmitted profile which provides the interface index (u32) of * the transmitted profile. The value must match one of the interface * indices advertised by the kernel. Optional if the interface being set up * is the transmitting one, however, if provided then the value must match * the interface index of the same. * * @NL80211_MBSSID_CONFIG_ATTR_EMA: Flag used to enable EMA AP feature. * Setting this flag is permitted only if the driver advertises EMA support * by setting wiphy->ema_max_profile_periodicity to non-zero. * * @__NL80211_MBSSID_CONFIG_ATTR_LAST: Internal * @NL80211_MBSSID_CONFIG_ATTR_MAX: highest attribute */ enum nl80211_mbssid_config_attributes { __NL80211_MBSSID_CONFIG_ATTR_INVALID, NL80211_MBSSID_CONFIG_ATTR_MAX_INTERFACES, NL80211_MBSSID_CONFIG_ATTR_MAX_EMA_PROFILE_PERIODICITY, NL80211_MBSSID_CONFIG_ATTR_INDEX, NL80211_MBSSID_CONFIG_ATTR_TX_IFINDEX, NL80211_MBSSID_CONFIG_ATTR_EMA, /* keep last */ __NL80211_MBSSID_CONFIG_ATTR_LAST, NL80211_MBSSID_CONFIG_ATTR_MAX = __NL80211_MBSSID_CONFIG_ATTR_LAST - 1, }; /** * enum nl80211_ap_settings_flags - AP settings flags * * @NL80211_AP_SETTINGS_EXTERNAL_AUTH_SUPPORT: AP supports external * authentication. * @NL80211_AP_SETTINGS_SA_QUERY_OFFLOAD_SUPPORT: Userspace supports SA Query * procedures offload to driver. If driver advertises * %NL80211_AP_SME_SA_QUERY_OFFLOAD in AP SME features, userspace shall * ignore SA Query procedures and validations when this flag is set by * userspace. */ enum nl80211_ap_settings_flags { NL80211_AP_SETTINGS_EXTERNAL_AUTH_SUPPORT = 1 << 0, NL80211_AP_SETTINGS_SA_QUERY_OFFLOAD_SUPPORT = 1 << 1, }; #endif /* __LINUX_NL80211_H */ linux/cciss_ioctl.h000064400000005311151027430560010355 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef CCISS_IOCTLH #define CCISS_IOCTLH #include #include #include #define CCISS_IOC_MAGIC 'B' typedef struct _cciss_pci_info_struct { unsigned char bus; unsigned char dev_fn; unsigned short domain; __u32 board_id; } cciss_pci_info_struct; typedef struct _cciss_coalint_struct { __u32 delay; __u32 count; } cciss_coalint_struct; typedef char NodeName_type[16]; typedef __u32 Heartbeat_type; #define CISS_PARSCSIU2 0x0001 #define CISS_PARCSCIU3 0x0002 #define CISS_FIBRE1G 0x0100 #define CISS_FIBRE2G 0x0200 typedef __u32 BusTypes_type; typedef char FirmwareVer_type[4]; typedef __u32 DriverVer_type; #define MAX_KMALLOC_SIZE 128000 typedef struct _IOCTL_Command_struct { LUNAddr_struct LUN_info; RequestBlock_struct Request; ErrorInfo_struct error_info; WORD buf_size; /* size in bytes of the buf */ BYTE *buf; } IOCTL_Command_struct; typedef struct _BIG_IOCTL_Command_struct { LUNAddr_struct LUN_info; RequestBlock_struct Request; ErrorInfo_struct error_info; DWORD malloc_size; /* < MAX_KMALLOC_SIZE in cciss.c */ DWORD buf_size; /* size in bytes of the buf */ /* < malloc_size * MAXSGENTRIES */ BYTE *buf; } BIG_IOCTL_Command_struct; typedef struct _LogvolInfo_struct{ __u32 LunID; int num_opens; /* number of opens on the logical volume */ int num_parts; /* number of partitions configured on logvol */ } LogvolInfo_struct; #define CCISS_GETPCIINFO _IOR(CCISS_IOC_MAGIC, 1, cciss_pci_info_struct) #define CCISS_GETINTINFO _IOR(CCISS_IOC_MAGIC, 2, cciss_coalint_struct) #define CCISS_SETINTINFO _IOW(CCISS_IOC_MAGIC, 3, cciss_coalint_struct) #define CCISS_GETNODENAME _IOR(CCISS_IOC_MAGIC, 4, NodeName_type) #define CCISS_SETNODENAME _IOW(CCISS_IOC_MAGIC, 5, NodeName_type) #define CCISS_GETHEARTBEAT _IOR(CCISS_IOC_MAGIC, 6, Heartbeat_type) #define CCISS_GETBUSTYPES _IOR(CCISS_IOC_MAGIC, 7, BusTypes_type) #define CCISS_GETFIRMVER _IOR(CCISS_IOC_MAGIC, 8, FirmwareVer_type) #define CCISS_GETDRIVVER _IOR(CCISS_IOC_MAGIC, 9, DriverVer_type) #define CCISS_REVALIDVOLS _IO(CCISS_IOC_MAGIC, 10) #define CCISS_PASSTHRU _IOWR(CCISS_IOC_MAGIC, 11, IOCTL_Command_struct) #define CCISS_DEREGDISK _IO(CCISS_IOC_MAGIC, 12) /* no longer used... use REGNEWD instead */ #define CCISS_REGNEWDISK _IOW(CCISS_IOC_MAGIC, 13, int) #define CCISS_REGNEWD _IO(CCISS_IOC_MAGIC, 14) #define CCISS_RESCANDISK _IO(CCISS_IOC_MAGIC, 16) #define CCISS_GETLUNINFO _IOR(CCISS_IOC_MAGIC, 17, LogvolInfo_struct) #define CCISS_BIG_PASSTHRU _IOWR(CCISS_IOC_MAGIC, 18, BIG_IOCTL_Command_struct) #endif /* CCISS_IOCTLH */ linux/nfs_mount.h000064400000004136151027430560010073 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NFS_MOUNT_H #define _LINUX_NFS_MOUNT_H /* * linux/include/linux/nfs_mount.h * * Copyright (C) 1992 Rick Sladkey * * structure passed from user-space to kernel-space during an nfs mount */ #include #include #include #include /* * WARNING! Do not delete or change the order of these fields. If * a new field is required then add it to the end. The version field * tracks which fields are present. This will ensure some measure of * mount-to-kernel version compatibility. Some of these aren't used yet * but here they are anyway. */ #define NFS_MOUNT_VERSION 6 #define NFS_MAX_CONTEXT_LEN 256 struct nfs_mount_data { int version; /* 1 */ int fd; /* 1 */ struct nfs2_fh old_root; /* 1 */ int flags; /* 1 */ int rsize; /* 1 */ int wsize; /* 1 */ int timeo; /* 1 */ int retrans; /* 1 */ int acregmin; /* 1 */ int acregmax; /* 1 */ int acdirmin; /* 1 */ int acdirmax; /* 1 */ struct sockaddr_in addr; /* 1 */ char hostname[NFS_MAXNAMLEN + 1]; /* 1 */ int namlen; /* 2 */ unsigned int bsize; /* 3 */ struct nfs3_fh root; /* 4 */ int pseudoflavor; /* 5 */ char context[NFS_MAX_CONTEXT_LEN + 1]; /* 6 */ }; /* bits in the flags field visible to user space */ #define NFS_MOUNT_SOFT 0x0001 /* 1 */ #define NFS_MOUNT_INTR 0x0002 /* 1 */ /* now unused, but ABI */ #define NFS_MOUNT_SECURE 0x0004 /* 1 */ #define NFS_MOUNT_POSIX 0x0008 /* 1 */ #define NFS_MOUNT_NOCTO 0x0010 /* 1 */ #define NFS_MOUNT_NOAC 0x0020 /* 1 */ #define NFS_MOUNT_TCP 0x0040 /* 2 */ #define NFS_MOUNT_VER3 0x0080 /* 3 */ #define NFS_MOUNT_KERBEROS 0x0100 /* 3 */ #define NFS_MOUNT_NONLM 0x0200 /* 3 */ #define NFS_MOUNT_BROKEN_SUID 0x0400 /* 4 */ #define NFS_MOUNT_NOACL 0x0800 /* 4 */ #define NFS_MOUNT_STRICTLOCK 0x1000 /* reserved for NFSv4 */ #define NFS_MOUNT_SECFLAVOUR 0x2000 /* 5 non-text parsed mount data only */ #define NFS_MOUNT_NORDIRPLUS 0x4000 /* 5 */ #define NFS_MOUNT_UNSHARED 0x8000 /* 5 */ #define NFS_MOUNT_FLAGMASK 0xFFFF #endif linux/vm_sockets.h000064400000014536151027430560010245 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * VMware vSockets Driver * * Copyright (C) 2007-2013 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation version 2 and no later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #ifndef _VM_SOCKETS_H #define _VM_SOCKETS_H #include #include /* Option name for STREAM socket buffer size. Use as the option name in * setsockopt(3) or getsockopt(3) to set or get an unsigned long long that * specifies the size of the buffer underlying a vSockets STREAM socket. * Value is clamped to the MIN and MAX. */ #define SO_VM_SOCKETS_BUFFER_SIZE 0 /* Option name for STREAM socket minimum buffer size. Use as the option name * in setsockopt(3) or getsockopt(3) to set or get an unsigned long long that * specifies the minimum size allowed for the buffer underlying a vSockets * STREAM socket. */ #define SO_VM_SOCKETS_BUFFER_MIN_SIZE 1 /* Option name for STREAM socket maximum buffer size. Use as the option name * in setsockopt(3) or getsockopt(3) to set or get an unsigned long long * that specifies the maximum size allowed for the buffer underlying a * vSockets STREAM socket. */ #define SO_VM_SOCKETS_BUFFER_MAX_SIZE 2 /* Option name for socket peer's host-specific VM ID. Use as the option name * in getsockopt(3) to get a host-specific identifier for the peer endpoint's * VM. The identifier is a signed integer. * Only available for hypervisor endpoints. */ #define SO_VM_SOCKETS_PEER_HOST_VM_ID 3 /* Option name for determining if a socket is trusted. Use as the option name * in getsockopt(3) to determine if a socket is trusted. The value is a * signed integer. */ #define SO_VM_SOCKETS_TRUSTED 5 /* Option name for STREAM socket connection timeout. Use as the option name * in setsockopt(3) or getsockopt(3) to set or get the connection * timeout for a STREAM socket. */ #define SO_VM_SOCKETS_CONNECT_TIMEOUT 6 /* Option name for using non-blocking send/receive. Use as the option name * for setsockopt(3) or getsockopt(3) to set or get the non-blocking * transmit/receive flag for a STREAM socket. This flag determines whether * send() and recv() can be called in non-blocking contexts for the given * socket. The value is a signed integer. * * This option is only relevant to kernel endpoints, where descheduling the * thread of execution is not allowed, for example, while holding a spinlock. * It is not to be confused with conventional non-blocking socket operations. * * Only available for hypervisor endpoints. */ #define SO_VM_SOCKETS_NONBLOCK_TXRX 7 /* The vSocket equivalent of INADDR_ANY. This works for the svm_cid field of * sockaddr_vm and indicates the context ID of the current endpoint. */ #define VMADDR_CID_ANY -1U /* Bind to any available port. Works for the svm_port field of * sockaddr_vm. */ #define VMADDR_PORT_ANY -1U /* Use this as the destination CID in an address when referring to the * hypervisor. VMCI relies on it being 0, but this would be useful for other * transports too. */ #define VMADDR_CID_HYPERVISOR 0 /* Use this as the destination CID in an address when referring to the * local communication (loopback). * (This was VMADDR_CID_RESERVED, but even VMCI doesn't use it anymore, * it was a legacy value from an older release). */ #define VMADDR_CID_LOCAL 1 /* Use this as the destination CID in an address when referring to the host * (any process other than the hypervisor). VMCI relies on it being 2, but * this would be useful for other transports too. */ #define VMADDR_CID_HOST 2 /* The current default use case for the vsock channel is the following: * local vsock communication between guest and host and nested VMs setup. * In addition to this, implicitly, the vsock packets are forwarded to the host * if no host->guest vsock transport is set. * * Set this flag value in the sockaddr_vm corresponding field if the vsock * packets need to be always forwarded to the host. Using this behavior, * vsock communication between sibling VMs can be setup. * * This way can explicitly distinguish between vsock channels created for * different use cases, such as nested VMs (or local communication between * guest and host) and sibling VMs. * * The flag can be set in the connect logic in the user space application flow. * In the listen logic (from kernel space) the flag is set on the remote peer * address. This happens for an incoming connection when it is routed from the * host and comes from the guest (local CID and remote CID > VMADDR_CID_HOST). */ #define VMADDR_FLAG_TO_HOST 0x01 /* Invalid vSockets version. */ #define VM_SOCKETS_INVALID_VERSION -1U /* The epoch (first) component of the vSockets version. A single byte * representing the epoch component of the vSockets version. */ #define VM_SOCKETS_VERSION_EPOCH(_v) (((_v) & 0xFF000000) >> 24) /* The major (second) component of the vSockets version. A single byte * representing the major component of the vSockets version. Typically * changes for every major release of a product. */ #define VM_SOCKETS_VERSION_MAJOR(_v) (((_v) & 0x00FF0000) >> 16) /* The minor (third) component of the vSockets version. Two bytes representing * the minor component of the vSockets version. */ #define VM_SOCKETS_VERSION_MINOR(_v) (((_v) & 0x0000FFFF)) /* Address structure for vSockets. The address family should be set to * AF_VSOCK. The structure members should all align on their natural * boundaries without resorting to compiler packing directives. The total size * of this structure should be exactly the same as that of struct sockaddr. */ struct sockaddr_vm { __kernel_sa_family_t svm_family; unsigned short svm_reserved1; unsigned int svm_port; unsigned int svm_cid; __u8 svm_flags; unsigned char svm_zero[sizeof(struct sockaddr) - sizeof(sa_family_t) - sizeof(unsigned short) - sizeof(unsigned int) - sizeof(unsigned int) - sizeof(__u8)]; }; #define IOCTL_VM_SOCKETS_GET_LOCAL_CID _IO(7, 0xb9) #endif /* _VM_SOCKETS_H */ linux/v4l2-common.h000064400000010121151027430560010127 0ustar00/* SPDX-License-Identifier: ((GPL-2.0+ WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * include/linux/v4l2-common.h * * Common V4L2 and V4L2 subdev definitions. * * Users are advised to #include this file either through videodev2.h * (V4L2) or through v4l2-subdev.h (V4L2 subdev) rather than to refer * to this file directly. * * Copyright (C) 2012 Nokia Corporation * Contact: Sakari Ailus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Alternatively you can redistribute this file under the terms of the * BSD license as stated below: * * 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 names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __V4L2_COMMON__ #define __V4L2_COMMON__ #include /* * * Selection interface definitions * */ /* Current cropping area */ #define V4L2_SEL_TGT_CROP 0x0000 /* Default cropping area */ #define V4L2_SEL_TGT_CROP_DEFAULT 0x0001 /* Cropping bounds */ #define V4L2_SEL_TGT_CROP_BOUNDS 0x0002 /* Native frame size */ #define V4L2_SEL_TGT_NATIVE_SIZE 0x0003 /* Current composing area */ #define V4L2_SEL_TGT_COMPOSE 0x0100 /* Default composing area */ #define V4L2_SEL_TGT_COMPOSE_DEFAULT 0x0101 /* Composing bounds */ #define V4L2_SEL_TGT_COMPOSE_BOUNDS 0x0102 /* Current composing area plus all padding pixels */ #define V4L2_SEL_TGT_COMPOSE_PADDED 0x0103 /* Backward compatibility target definitions --- to be removed. */ #define V4L2_SEL_TGT_CROP_ACTIVE V4L2_SEL_TGT_CROP #define V4L2_SEL_TGT_COMPOSE_ACTIVE V4L2_SEL_TGT_COMPOSE #define V4L2_SUBDEV_SEL_TGT_CROP_ACTUAL V4L2_SEL_TGT_CROP #define V4L2_SUBDEV_SEL_TGT_COMPOSE_ACTUAL V4L2_SEL_TGT_COMPOSE #define V4L2_SUBDEV_SEL_TGT_CROP_BOUNDS V4L2_SEL_TGT_CROP_BOUNDS #define V4L2_SUBDEV_SEL_TGT_COMPOSE_BOUNDS V4L2_SEL_TGT_COMPOSE_BOUNDS /* Selection flags */ #define V4L2_SEL_FLAG_GE (1 << 0) #define V4L2_SEL_FLAG_LE (1 << 1) #define V4L2_SEL_FLAG_KEEP_CONFIG (1 << 2) /* Backward compatibility flag definitions --- to be removed. */ #define V4L2_SUBDEV_SEL_FLAG_SIZE_GE V4L2_SEL_FLAG_GE #define V4L2_SUBDEV_SEL_FLAG_SIZE_LE V4L2_SEL_FLAG_LE #define V4L2_SUBDEV_SEL_FLAG_KEEP_CONFIG V4L2_SEL_FLAG_KEEP_CONFIG struct v4l2_edid { __u32 pad; __u32 start_block; __u32 blocks; __u32 reserved[5]; __u8 *edid; }; #endif /* __V4L2_COMMON__ */ linux/atm_eni.h000064400000001210151027430560007465 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm_eni.h - Driver-specific declarations of the ENI driver (for use by driver-specific utilities) */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #ifndef LINUX_ATM_ENI_H #define LINUX_ATM_ENI_H #include struct eni_multipliers { int tx,rx; /* values are in percent and must be > 100 */ }; #define ENI_MEMDUMP _IOW('a',ATMIOC_SARPRV,struct atmif_sioc) /* printk memory map */ #define ENI_SETMULT _IOW('a',ATMIOC_SARPRV+7,struct atmif_sioc) /* set buffer multipliers */ #endif linux/irqnr.h000064400000000150151027430560007206 0ustar00/* * There isn't anything here anymore, but the file must not be empty or patch * will delete it. */ linux/soundcard.h000064400000131726151027430560010053 0ustar00/* * Copyright by Hannu Savolainen 1993-1997 * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef SOUNDCARD_H #define SOUNDCARD_H /* * OSS interface version. With versions earlier than 3.6 this value is * an integer with value less than 361. In versions 3.6 and later * it's a six digit hexadecimal value. For example value * of 0x030600 represents OSS version 3.6.0. * Use ioctl(fd, OSS_GETVERSION, &int) to get the version number of * the currently active driver. */ #define SOUND_VERSION 0x030802 #define OPEN_SOUND_SYSTEM /* In Linux we need to be prepared for cross compiling */ #include /* Endian macros. */ # include /* * Supported card ID numbers (Should be somewhere else?) */ #define SNDCARD_ADLIB 1 #define SNDCARD_SB 2 #define SNDCARD_PAS 3 #define SNDCARD_GUS 4 #define SNDCARD_MPU401 5 #define SNDCARD_SB16 6 #define SNDCARD_SB16MIDI 7 #define SNDCARD_UART6850 8 #define SNDCARD_GUS16 9 #define SNDCARD_MSS 10 #define SNDCARD_PSS 11 #define SNDCARD_SSCAPE 12 #define SNDCARD_PSS_MPU 13 #define SNDCARD_PSS_MSS 14 #define SNDCARD_SSCAPE_MSS 15 #define SNDCARD_TRXPRO 16 #define SNDCARD_TRXPRO_SB 17 #define SNDCARD_TRXPRO_MPU 18 #define SNDCARD_MAD16 19 #define SNDCARD_MAD16_MPU 20 #define SNDCARD_CS4232 21 #define SNDCARD_CS4232_MPU 22 #define SNDCARD_MAUI 23 #define SNDCARD_PSEUDO_MSS 24 #define SNDCARD_GUSPNP 25 #define SNDCARD_UART401 26 /* Sound card numbers 27 to N are reserved. Don't add more numbers here. */ /*********************************** * IOCTL Commands for /dev/sequencer */ #ifndef _SIOWR #if defined(_IOWR) && (defined(_AIX) || (!defined(sun) && !defined(sparc) && !defined(__sparc__) && !defined(__INCioctlh) && !defined(__Lynx__))) /* Use already defined ioctl defines if they exist (except with Sun or Sparc) */ #define SIOCPARM_MASK IOCPARM_MASK #define SIOC_VOID IOC_VOID #define SIOC_OUT IOC_OUT #define SIOC_IN IOC_IN #define SIOC_INOUT IOC_INOUT #define _SIOC_SIZE _IOC_SIZE #define _SIOC_DIR _IOC_DIR #define _SIOC_NONE _IOC_NONE #define _SIOC_READ _IOC_READ #define _SIOC_WRITE _IOC_WRITE #define _SIO _IO #define _SIOR _IOR #define _SIOW _IOW #define _SIOWR _IOWR #else /* Ioctl's have the command encoded in the lower word, * and the size of any in or out parameters in the upper * word. The high 2 bits of the upper word are used * to encode the in/out status of the parameter; for now * we restrict parameters to at most 8191 bytes. */ /* #define SIOCTYPE (0xff<<8) */ #define SIOCPARM_MASK 0x1fff /* parameters must be < 8192 bytes */ #define SIOC_VOID 0x00000000 /* no parameters */ #define SIOC_OUT 0x20000000 /* copy out parameters */ #define SIOC_IN 0x40000000 /* copy in parameters */ #define SIOC_INOUT (SIOC_IN|SIOC_OUT) /* the 0x20000000 is so we can distinguish new ioctl's from old */ #define _SIO(x,y) ((int)(SIOC_VOID|(x<<8)|y)) #define _SIOR(x,y,t) ((int)(SIOC_OUT|((sizeof(t)&SIOCPARM_MASK)<<16)|(x<<8)|y)) #define _SIOW(x,y,t) ((int)(SIOC_IN|((sizeof(t)&SIOCPARM_MASK)<<16)|(x<<8)|y)) /* this should be _SIORW, but stdio got there first */ #define _SIOWR(x,y,t) ((int)(SIOC_INOUT|((sizeof(t)&SIOCPARM_MASK)<<16)|(x<<8)|y)) #define _SIOC_SIZE(x) ((x>>16)&SIOCPARM_MASK) #define _SIOC_DIR(x) (x & 0xf0000000) #define _SIOC_NONE SIOC_VOID #define _SIOC_READ SIOC_OUT #define _SIOC_WRITE SIOC_IN # endif /* _IOWR */ #endif /* !_SIOWR */ #define SNDCTL_SEQ_RESET _SIO ('Q', 0) #define SNDCTL_SEQ_SYNC _SIO ('Q', 1) #define SNDCTL_SYNTH_INFO _SIOWR('Q', 2, struct synth_info) #define SNDCTL_SEQ_CTRLRATE _SIOWR('Q', 3, int) /* Set/get timer resolution (HZ) */ #define SNDCTL_SEQ_GETOUTCOUNT _SIOR ('Q', 4, int) #define SNDCTL_SEQ_GETINCOUNT _SIOR ('Q', 5, int) #define SNDCTL_SEQ_PERCMODE _SIOW ('Q', 6, int) #define SNDCTL_FM_LOAD_INSTR _SIOW ('Q', 7, struct sbi_instrument) /* Obsolete. Don't use!!!!!! */ #define SNDCTL_SEQ_TESTMIDI _SIOW ('Q', 8, int) #define SNDCTL_SEQ_RESETSAMPLES _SIOW ('Q', 9, int) #define SNDCTL_SEQ_NRSYNTHS _SIOR ('Q',10, int) #define SNDCTL_SEQ_NRMIDIS _SIOR ('Q',11, int) #define SNDCTL_MIDI_INFO _SIOWR('Q',12, struct midi_info) #define SNDCTL_SEQ_THRESHOLD _SIOW ('Q',13, int) #define SNDCTL_SYNTH_MEMAVL _SIOWR('Q',14, int) /* in=dev#, out=memsize */ #define SNDCTL_FM_4OP_ENABLE _SIOW ('Q',15, int) /* in=dev# */ #define SNDCTL_SEQ_PANIC _SIO ('Q',17) #define SNDCTL_SEQ_OUTOFBAND _SIOW ('Q',18, struct seq_event_rec) #define SNDCTL_SEQ_GETTIME _SIOR ('Q',19, int) #define SNDCTL_SYNTH_ID _SIOWR('Q',20, struct synth_info) #define SNDCTL_SYNTH_CONTROL _SIOWR('Q',21, struct synth_control) #define SNDCTL_SYNTH_REMOVESAMPLE _SIOWR('Q',22, struct remove_sample) typedef struct synth_control { int devno; /* Synthesizer # */ char data[4000]; /* Device spesific command/data record */ }synth_control; typedef struct remove_sample { int devno; /* Synthesizer # */ int bankno; /* MIDI bank # (0=General MIDI) */ int instrno; /* MIDI instrument number */ } remove_sample; typedef struct seq_event_rec { unsigned char arr[8]; } seq_event_rec; #define SNDCTL_TMR_TIMEBASE _SIOWR('T', 1, int) #define SNDCTL_TMR_START _SIO ('T', 2) #define SNDCTL_TMR_STOP _SIO ('T', 3) #define SNDCTL_TMR_CONTINUE _SIO ('T', 4) #define SNDCTL_TMR_TEMPO _SIOWR('T', 5, int) #define SNDCTL_TMR_SOURCE _SIOWR('T', 6, int) # define TMR_INTERNAL 0x00000001 # define TMR_EXTERNAL 0x00000002 # define TMR_MODE_MIDI 0x00000010 # define TMR_MODE_FSK 0x00000020 # define TMR_MODE_CLS 0x00000040 # define TMR_MODE_SMPTE 0x00000080 #define SNDCTL_TMR_METRONOME _SIOW ('T', 7, int) #define SNDCTL_TMR_SELECT _SIOW ('T', 8, int) /* * Some big endian/little endian handling macros */ #define _LINUX_PATCHKEY_H_INDIRECT #include #undef _LINUX_PATCHKEY_H_INDIRECT # if defined(__BYTE_ORDER) # if __BYTE_ORDER == __BIG_ENDIAN # define AFMT_S16_NE AFMT_S16_BE # elif __BYTE_ORDER == __LITTLE_ENDIAN # define AFMT_S16_NE AFMT_S16_LE # else # error "could not determine byte order" # endif # endif /* * Sample loading mechanism for internal synthesizers (/dev/sequencer) * The following patch_info structure has been designed to support * Gravis UltraSound. It tries to be universal format for uploading * sample based patches but is probably too limited. * * (PBD) As Hannu guessed, the GUS structure is too limited for * the WaveFront, but this is the right place for a constant definition. */ struct patch_info { unsigned short key; /* Use WAVE_PATCH here */ #define WAVE_PATCH _PATCHKEY(0x04) #define GUS_PATCH WAVE_PATCH #define WAVEFRONT_PATCH _PATCHKEY(0x06) short device_no; /* Synthesizer number */ short instr_no; /* Midi pgm# */ unsigned int mode; /* * The least significant byte has the same format than the GUS .PAT * files */ #define WAVE_16_BITS 0x01 /* bit 0 = 8 or 16 bit wave data. */ #define WAVE_UNSIGNED 0x02 /* bit 1 = Signed - Unsigned data. */ #define WAVE_LOOPING 0x04 /* bit 2 = looping enabled-1. */ #define WAVE_BIDIR_LOOP 0x08 /* bit 3 = Set is bidirectional looping. */ #define WAVE_LOOP_BACK 0x10 /* bit 4 = Set is looping backward. */ #define WAVE_SUSTAIN_ON 0x20 /* bit 5 = Turn sustaining on. (Env. pts. 3)*/ #define WAVE_ENVELOPES 0x40 /* bit 6 = Enable envelopes - 1 */ #define WAVE_FAST_RELEASE 0x80 /* bit 7 = Shut off immediately after note off */ /* (use the env_rate/env_offs fields). */ /* Linux specific bits */ #define WAVE_VIBRATO 0x00010000 /* The vibrato info is valid */ #define WAVE_TREMOLO 0x00020000 /* The tremolo info is valid */ #define WAVE_SCALE 0x00040000 /* The scaling info is valid */ #define WAVE_FRACTIONS 0x00080000 /* Fraction information is valid */ /* Reserved bits */ #define WAVE_ROM 0x40000000 /* For future use */ #define WAVE_MULAW 0x20000000 /* For future use */ /* Other bits must be zeroed */ int len; /* Size of the wave data in bytes */ int loop_start, loop_end; /* Byte offsets from the beginning */ /* * The base_freq and base_note fields are used when computing the * playback speed for a note. The base_note defines the tone frequency * which is heard if the sample is played using the base_freq as the * playback speed. * * The low_note and high_note fields define the minimum and maximum note * frequencies for which this sample is valid. It is possible to define * more than one samples for an instrument number at the same time. The * low_note and high_note fields are used to select the most suitable one. * * The fields base_note, high_note and low_note should contain * the note frequency multiplied by 1000. For example value for the * middle A is 440*1000. */ unsigned int base_freq; unsigned int base_note; unsigned int high_note; unsigned int low_note; int panning; /* -128=left, 127=right */ int detuning; /* New fields introduced in version 1.99.5 */ /* Envelope. Enabled by mode bit WAVE_ENVELOPES */ unsigned char env_rate[ 6 ]; /* GUS HW ramping rate */ unsigned char env_offset[ 6 ]; /* 255 == 100% */ /* * The tremolo, vibrato and scale info are not supported yet. * Enable by setting the mode bits WAVE_TREMOLO, WAVE_VIBRATO or * WAVE_SCALE */ unsigned char tremolo_sweep; unsigned char tremolo_rate; unsigned char tremolo_depth; unsigned char vibrato_sweep; unsigned char vibrato_rate; unsigned char vibrato_depth; int scale_frequency; unsigned int scale_factor; /* from 0 to 2048 or 0 to 2 */ int volume; int fractions; int reserved1; int spare[2]; char data[1]; /* The waveform data starts here */ }; struct sysex_info { short key; /* Use SYSEX_PATCH or MAUI_PATCH here */ #define SYSEX_PATCH _PATCHKEY(0x05) #define MAUI_PATCH _PATCHKEY(0x06) short device_no; /* Synthesizer number */ int len; /* Size of the sysex data in bytes */ unsigned char data[1]; /* Sysex data starts here */ }; /* * /dev/sequencer input events. * * The data written to the /dev/sequencer is a stream of events. Events * are records of 4 or 8 bytes. The first byte defines the size. * Any number of events can be written with a write call. There * is a set of macros for sending these events. Use these macros if you * want to maximize portability of your program. * * Events SEQ_WAIT, SEQ_MIDIPUTC and SEQ_ECHO. Are also input events. * (All input events are currently 4 bytes long. Be prepared to support * 8 byte events also. If you receive any event having first byte >= 128, * it's a 8 byte event. * * The events are documented at the end of this file. * * Normal events (4 bytes) * There is also a 8 byte version of most of the 4 byte events. The * 8 byte one is recommended. */ #define SEQ_NOTEOFF 0 #define SEQ_FMNOTEOFF SEQ_NOTEOFF /* Just old name */ #define SEQ_NOTEON 1 #define SEQ_FMNOTEON SEQ_NOTEON #define SEQ_WAIT TMR_WAIT_ABS #define SEQ_PGMCHANGE 3 #define SEQ_FMPGMCHANGE SEQ_PGMCHANGE #define SEQ_SYNCTIMER TMR_START #define SEQ_MIDIPUTC 5 #define SEQ_DRUMON 6 /*** OBSOLETE ***/ #define SEQ_DRUMOFF 7 /*** OBSOLETE ***/ #define SEQ_ECHO TMR_ECHO /* For synching programs with output */ #define SEQ_AFTERTOUCH 9 #define SEQ_CONTROLLER 10 /******************************************* * Midi controller numbers ******************************************* * Controllers 0 to 31 (0x00 to 0x1f) and * 32 to 63 (0x20 to 0x3f) are continuous * controllers. * In the MIDI 1.0 these controllers are sent using * two messages. Controller numbers 0 to 31 are used * to send the MSB and the controller numbers 32 to 63 * are for the LSB. Note that just 7 bits are used in MIDI bytes. */ #define CTL_BANK_SELECT 0x00 #define CTL_MODWHEEL 0x01 #define CTL_BREATH 0x02 /* undefined 0x03 */ #define CTL_FOOT 0x04 #define CTL_PORTAMENTO_TIME 0x05 #define CTL_DATA_ENTRY 0x06 #define CTL_MAIN_VOLUME 0x07 #define CTL_BALANCE 0x08 /* undefined 0x09 */ #define CTL_PAN 0x0a #define CTL_EXPRESSION 0x0b /* undefined 0x0c */ /* undefined 0x0d */ /* undefined 0x0e */ /* undefined 0x0f */ #define CTL_GENERAL_PURPOSE1 0x10 #define CTL_GENERAL_PURPOSE2 0x11 #define CTL_GENERAL_PURPOSE3 0x12 #define CTL_GENERAL_PURPOSE4 0x13 /* undefined 0x14 - 0x1f */ /* undefined 0x20 */ /* The controller numbers 0x21 to 0x3f are reserved for the */ /* least significant bytes of the controllers 0x00 to 0x1f. */ /* These controllers are not recognised by the driver. */ /* Controllers 64 to 69 (0x40 to 0x45) are on/off switches. */ /* 0=OFF and 127=ON (intermediate values are possible) */ #define CTL_DAMPER_PEDAL 0x40 #define CTL_SUSTAIN 0x40 /* Alias */ #define CTL_HOLD 0x40 /* Alias */ #define CTL_PORTAMENTO 0x41 #define CTL_SOSTENUTO 0x42 #define CTL_SOFT_PEDAL 0x43 /* undefined 0x44 */ #define CTL_HOLD2 0x45 /* undefined 0x46 - 0x4f */ #define CTL_GENERAL_PURPOSE5 0x50 #define CTL_GENERAL_PURPOSE6 0x51 #define CTL_GENERAL_PURPOSE7 0x52 #define CTL_GENERAL_PURPOSE8 0x53 /* undefined 0x54 - 0x5a */ #define CTL_EXT_EFF_DEPTH 0x5b #define CTL_TREMOLO_DEPTH 0x5c #define CTL_CHORUS_DEPTH 0x5d #define CTL_DETUNE_DEPTH 0x5e #define CTL_CELESTE_DEPTH 0x5e /* Alias for the above one */ #define CTL_PHASER_DEPTH 0x5f #define CTL_DATA_INCREMENT 0x60 #define CTL_DATA_DECREMENT 0x61 #define CTL_NONREG_PARM_NUM_LSB 0x62 #define CTL_NONREG_PARM_NUM_MSB 0x63 #define CTL_REGIST_PARM_NUM_LSB 0x64 #define CTL_REGIST_PARM_NUM_MSB 0x65 /* undefined 0x66 - 0x78 */ /* reserved 0x79 - 0x7f */ /* Pseudo controllers (not midi compatible) */ #define CTRL_PITCH_BENDER 255 #define CTRL_PITCH_BENDER_RANGE 254 #define CTRL_EXPRESSION 253 /* Obsolete */ #define CTRL_MAIN_VOLUME 252 /* Obsolete */ #define SEQ_BALANCE 11 #define SEQ_VOLMODE 12 /* * Volume mode decides how volumes are used */ #define VOL_METHOD_ADAGIO 1 #define VOL_METHOD_LINEAR 2 /* * Note! SEQ_WAIT, SEQ_MIDIPUTC and SEQ_ECHO are used also as * input events. */ /* * Event codes 0xf0 to 0xfc are reserved for future extensions. */ #define SEQ_FULLSIZE 0xfd /* Long events */ /* * SEQ_FULLSIZE events are used for loading patches/samples to the * synthesizer devices. These events are passed directly to the driver * of the associated synthesizer device. There is no limit to the size * of the extended events. These events are not queued but executed * immediately when the write() is called (execution can take several * seconds of time). * * When a SEQ_FULLSIZE message is written to the device, it must * be written using exactly one write() call. Other events cannot * be mixed to the same write. * * For FM synths (YM3812/OPL3) use struct sbi_instrument and write it to the * /dev/sequencer. Don't write other data together with the instrument structure * Set the key field of the structure to FM_PATCH. The device field is used to * route the patch to the corresponding device. * * For wave table use struct patch_info. Initialize the key field * to WAVE_PATCH. */ #define SEQ_PRIVATE 0xfe /* Low level HW dependent events (8 bytes) */ #define SEQ_EXTENDED 0xff /* Extended events (8 bytes) OBSOLETE */ /* * Record for FM patches */ typedef unsigned char sbi_instr_data[32]; struct sbi_instrument { unsigned short key; /* FM_PATCH or OPL3_PATCH */ #define FM_PATCH _PATCHKEY(0x01) #define OPL3_PATCH _PATCHKEY(0x03) short device; /* Synth# (0-4) */ int channel; /* Program# to be initialized */ sbi_instr_data operators; /* Register settings for operator cells (.SBI format) */ }; struct synth_info { /* Read only */ char name[30]; int device; /* 0-N. INITIALIZE BEFORE CALLING */ int synth_type; #define SYNTH_TYPE_FM 0 #define SYNTH_TYPE_SAMPLE 1 #define SYNTH_TYPE_MIDI 2 /* Midi interface */ int synth_subtype; #define FM_TYPE_ADLIB 0x00 #define FM_TYPE_OPL3 0x01 #define MIDI_TYPE_MPU401 0x401 #define SAMPLE_TYPE_BASIC 0x10 #define SAMPLE_TYPE_GUS SAMPLE_TYPE_BASIC #define SAMPLE_TYPE_WAVEFRONT 0x11 int perc_mode; /* No longer supported */ int nr_voices; int nr_drums; /* Obsolete field */ int instr_bank_size; unsigned int capabilities; #define SYNTH_CAP_PERCMODE 0x00000001 /* No longer used */ #define SYNTH_CAP_OPL3 0x00000002 /* Set if OPL3 supported */ #define SYNTH_CAP_INPUT 0x00000004 /* Input (MIDI) device */ int dummies[19]; /* Reserve space */ }; struct sound_timer_info { char name[32]; int caps; }; #define MIDI_CAP_MPU401 1 /* MPU-401 intelligent mode */ struct midi_info { char name[30]; int device; /* 0-N. INITIALIZE BEFORE CALLING */ unsigned int capabilities; /* To be defined later */ int dev_type; int dummies[18]; /* Reserve space */ }; /******************************************** * ioctl commands for the /dev/midi## */ typedef struct { unsigned char cmd; char nr_args, nr_returns; unsigned char data[30]; } mpu_command_rec; #define SNDCTL_MIDI_PRETIME _SIOWR('m', 0, int) #define SNDCTL_MIDI_MPUMODE _SIOWR('m', 1, int) #define SNDCTL_MIDI_MPUCMD _SIOWR('m', 2, mpu_command_rec) /******************************************** * IOCTL commands for /dev/dsp and /dev/audio */ #define SNDCTL_DSP_RESET _SIO ('P', 0) #define SNDCTL_DSP_SYNC _SIO ('P', 1) #define SNDCTL_DSP_SPEED _SIOWR('P', 2, int) #define SNDCTL_DSP_STEREO _SIOWR('P', 3, int) #define SNDCTL_DSP_GETBLKSIZE _SIOWR('P', 4, int) #define SNDCTL_DSP_SAMPLESIZE SNDCTL_DSP_SETFMT #define SNDCTL_DSP_CHANNELS _SIOWR('P', 6, int) #define SOUND_PCM_WRITE_CHANNELS SNDCTL_DSP_CHANNELS #define SOUND_PCM_WRITE_FILTER _SIOWR('P', 7, int) #define SNDCTL_DSP_POST _SIO ('P', 8) #define SNDCTL_DSP_SUBDIVIDE _SIOWR('P', 9, int) #define SNDCTL_DSP_SETFRAGMENT _SIOWR('P',10, int) /* Audio data formats (Note! U8=8 and S16_LE=16 for compatibility) */ #define SNDCTL_DSP_GETFMTS _SIOR ('P',11, int) /* Returns a mask */ #define SNDCTL_DSP_SETFMT _SIOWR('P',5, int) /* Selects ONE fmt*/ # define AFMT_QUERY 0x00000000 /* Return current fmt */ # define AFMT_MU_LAW 0x00000001 # define AFMT_A_LAW 0x00000002 # define AFMT_IMA_ADPCM 0x00000004 # define AFMT_U8 0x00000008 # define AFMT_S16_LE 0x00000010 /* Little endian signed 16*/ # define AFMT_S16_BE 0x00000020 /* Big endian signed 16 */ # define AFMT_S8 0x00000040 # define AFMT_U16_LE 0x00000080 /* Little endian U16 */ # define AFMT_U16_BE 0x00000100 /* Big endian U16 */ # define AFMT_MPEG 0x00000200 /* MPEG (2) audio */ # define AFMT_AC3 0x00000400 /* Dolby Digital AC3 */ /* * Buffer status queries. */ typedef struct audio_buf_info { int fragments; /* # of available fragments (partially usend ones not counted) */ int fragstotal; /* Total # of fragments allocated */ int fragsize; /* Size of a fragment in bytes */ int bytes; /* Available space in bytes (includes partially used fragments) */ /* Note! 'bytes' could be more than fragments*fragsize */ } audio_buf_info; #define SNDCTL_DSP_GETOSPACE _SIOR ('P',12, audio_buf_info) #define SNDCTL_DSP_GETISPACE _SIOR ('P',13, audio_buf_info) #define SNDCTL_DSP_NONBLOCK _SIO ('P',14) #define SNDCTL_DSP_GETCAPS _SIOR ('P',15, int) # define DSP_CAP_REVISION 0x000000ff /* Bits for revision level (0 to 255) */ # define DSP_CAP_DUPLEX 0x00000100 /* Full duplex record/playback */ # define DSP_CAP_REALTIME 0x00000200 /* Real time capability */ # define DSP_CAP_BATCH 0x00000400 /* Device has some kind of */ /* internal buffers which may */ /* cause some delays and */ /* decrease precision of timing */ # define DSP_CAP_COPROC 0x00000800 /* Has a coprocessor */ /* Sometimes it's a DSP */ /* but usually not */ # define DSP_CAP_TRIGGER 0x00001000 /* Supports SETTRIGGER */ # define DSP_CAP_MMAP 0x00002000 /* Supports mmap() */ # define DSP_CAP_MULTI 0x00004000 /* support multiple open */ # define DSP_CAP_BIND 0x00008000 /* channel binding to front/rear/cneter/lfe */ #define SNDCTL_DSP_GETTRIGGER _SIOR ('P',16, int) #define SNDCTL_DSP_SETTRIGGER _SIOW ('P',16, int) # define PCM_ENABLE_INPUT 0x00000001 # define PCM_ENABLE_OUTPUT 0x00000002 typedef struct count_info { int bytes; /* Total # of bytes processed */ int blocks; /* # of fragment transitions since last time */ int ptr; /* Current DMA pointer value */ } count_info; #define SNDCTL_DSP_GETIPTR _SIOR ('P',17, count_info) #define SNDCTL_DSP_GETOPTR _SIOR ('P',18, count_info) typedef struct buffmem_desc { unsigned *buffer; int size; } buffmem_desc; #define SNDCTL_DSP_MAPINBUF _SIOR ('P', 19, buffmem_desc) #define SNDCTL_DSP_MAPOUTBUF _SIOR ('P', 20, buffmem_desc) #define SNDCTL_DSP_SETSYNCRO _SIO ('P', 21) #define SNDCTL_DSP_SETDUPLEX _SIO ('P', 22) #define SNDCTL_DSP_GETODELAY _SIOR ('P', 23, int) #define SNDCTL_DSP_GETCHANNELMASK _SIOWR('P', 64, int) #define SNDCTL_DSP_BIND_CHANNEL _SIOWR('P', 65, int) # define DSP_BIND_QUERY 0x00000000 # define DSP_BIND_FRONT 0x00000001 # define DSP_BIND_SURR 0x00000002 # define DSP_BIND_CENTER_LFE 0x00000004 # define DSP_BIND_HANDSET 0x00000008 # define DSP_BIND_MIC 0x00000010 # define DSP_BIND_MODEM1 0x00000020 # define DSP_BIND_MODEM2 0x00000040 # define DSP_BIND_I2S 0x00000080 # define DSP_BIND_SPDIF 0x00000100 #define SNDCTL_DSP_SETSPDIF _SIOW ('P', 66, int) #define SNDCTL_DSP_GETSPDIF _SIOR ('P', 67, int) # define SPDIF_PRO 0x0001 # define SPDIF_N_AUD 0x0002 # define SPDIF_COPY 0x0004 # define SPDIF_PRE 0x0008 # define SPDIF_CC 0x07f0 # define SPDIF_L 0x0800 # define SPDIF_DRS 0x4000 # define SPDIF_V 0x8000 /* * Application's profile defines the way how playback underrun situations should be handled. * * APF_NORMAL (the default) and APF_NETWORK make the driver to cleanup the * playback buffer whenever an underrun occurs. This consumes some time * prevents looping the existing buffer. * APF_CPUINTENS is intended to be set by CPU intensive applications which * are likely to run out of time occasionally. In this mode the buffer cleanup is * disabled which saves CPU time but also let's the previous buffer content to * be played during the "pause" after the underrun. */ #define SNDCTL_DSP_PROFILE _SIOW ('P', 23, int) #define APF_NORMAL 0 /* Normal applications */ #define APF_NETWORK 1 /* Underruns probably caused by an "external" delay */ #define APF_CPUINTENS 2 /* Underruns probably caused by "overheating" the CPU */ #define SOUND_PCM_READ_RATE _SIOR ('P', 2, int) #define SOUND_PCM_READ_CHANNELS _SIOR ('P', 6, int) #define SOUND_PCM_READ_BITS _SIOR ('P', 5, int) #define SOUND_PCM_READ_FILTER _SIOR ('P', 7, int) /* Some alias names */ #define SOUND_PCM_WRITE_BITS SNDCTL_DSP_SETFMT #define SOUND_PCM_WRITE_RATE SNDCTL_DSP_SPEED #define SOUND_PCM_POST SNDCTL_DSP_POST #define SOUND_PCM_RESET SNDCTL_DSP_RESET #define SOUND_PCM_SYNC SNDCTL_DSP_SYNC #define SOUND_PCM_SUBDIVIDE SNDCTL_DSP_SUBDIVIDE #define SOUND_PCM_SETFRAGMENT SNDCTL_DSP_SETFRAGMENT #define SOUND_PCM_GETFMTS SNDCTL_DSP_GETFMTS #define SOUND_PCM_SETFMT SNDCTL_DSP_SETFMT #define SOUND_PCM_GETOSPACE SNDCTL_DSP_GETOSPACE #define SOUND_PCM_GETISPACE SNDCTL_DSP_GETISPACE #define SOUND_PCM_NONBLOCK SNDCTL_DSP_NONBLOCK #define SOUND_PCM_GETCAPS SNDCTL_DSP_GETCAPS #define SOUND_PCM_GETTRIGGER SNDCTL_DSP_GETTRIGGER #define SOUND_PCM_SETTRIGGER SNDCTL_DSP_SETTRIGGER #define SOUND_PCM_SETSYNCRO SNDCTL_DSP_SETSYNCRO #define SOUND_PCM_GETIPTR SNDCTL_DSP_GETIPTR #define SOUND_PCM_GETOPTR SNDCTL_DSP_GETOPTR #define SOUND_PCM_MAPINBUF SNDCTL_DSP_MAPINBUF #define SOUND_PCM_MAPOUTBUF SNDCTL_DSP_MAPOUTBUF /* * ioctl calls to be used in communication with coprocessors and * DSP chips. */ typedef struct copr_buffer { int command; /* Set to 0 if not used */ int flags; #define CPF_NONE 0x0000 #define CPF_FIRST 0x0001 /* First block */ #define CPF_LAST 0x0002 /* Last block */ int len; int offs; /* If required by the device (0 if not used) */ unsigned char data[4000]; /* NOTE! 4000 is not 4k */ } copr_buffer; typedef struct copr_debug_buf { int command; /* Used internally. Set to 0 */ int parm1; int parm2; int flags; int len; /* Length of data in bytes */ } copr_debug_buf; typedef struct copr_msg { int len; unsigned char data[4000]; } copr_msg; #define SNDCTL_COPR_RESET _SIO ('C', 0) #define SNDCTL_COPR_LOAD _SIOWR('C', 1, copr_buffer) #define SNDCTL_COPR_RDATA _SIOWR('C', 2, copr_debug_buf) #define SNDCTL_COPR_RCODE _SIOWR('C', 3, copr_debug_buf) #define SNDCTL_COPR_WDATA _SIOW ('C', 4, copr_debug_buf) #define SNDCTL_COPR_WCODE _SIOW ('C', 5, copr_debug_buf) #define SNDCTL_COPR_RUN _SIOWR('C', 6, copr_debug_buf) #define SNDCTL_COPR_HALT _SIOWR('C', 7, copr_debug_buf) #define SNDCTL_COPR_SENDMSG _SIOWR('C', 8, copr_msg) #define SNDCTL_COPR_RCVMSG _SIOR ('C', 9, copr_msg) /********************************************* * IOCTL commands for /dev/mixer */ /* * Mixer devices * * There can be up to 20 different analog mixer channels. The * SOUND_MIXER_NRDEVICES gives the currently supported maximum. * The SOUND_MIXER_READ_DEVMASK returns a bitmask which tells * the devices supported by the particular mixer. */ #define SOUND_MIXER_NRDEVICES 25 #define SOUND_MIXER_VOLUME 0 #define SOUND_MIXER_BASS 1 #define SOUND_MIXER_TREBLE 2 #define SOUND_MIXER_SYNTH 3 #define SOUND_MIXER_PCM 4 #define SOUND_MIXER_SPEAKER 5 #define SOUND_MIXER_LINE 6 #define SOUND_MIXER_MIC 7 #define SOUND_MIXER_CD 8 #define SOUND_MIXER_IMIX 9 /* Recording monitor */ #define SOUND_MIXER_ALTPCM 10 #define SOUND_MIXER_RECLEV 11 /* Recording level */ #define SOUND_MIXER_IGAIN 12 /* Input gain */ #define SOUND_MIXER_OGAIN 13 /* Output gain */ /* * The AD1848 codec and compatibles have three line level inputs * (line, aux1 and aux2). Since each card manufacturer have assigned * different meanings to these inputs, it's inpractical to assign * specific meanings (line, cd, synth etc.) to them. */ #define SOUND_MIXER_LINE1 14 /* Input source 1 (aux1) */ #define SOUND_MIXER_LINE2 15 /* Input source 2 (aux2) */ #define SOUND_MIXER_LINE3 16 /* Input source 3 (line) */ #define SOUND_MIXER_DIGITAL1 17 /* Digital (input) 1 */ #define SOUND_MIXER_DIGITAL2 18 /* Digital (input) 2 */ #define SOUND_MIXER_DIGITAL3 19 /* Digital (input) 3 */ #define SOUND_MIXER_PHONEIN 20 /* Phone input */ #define SOUND_MIXER_PHONEOUT 21 /* Phone output */ #define SOUND_MIXER_VIDEO 22 /* Video/TV (audio) in */ #define SOUND_MIXER_RADIO 23 /* Radio in */ #define SOUND_MIXER_MONITOR 24 /* Monitor (usually mic) volume */ /* Some on/off settings (SOUND_SPECIAL_MIN - SOUND_SPECIAL_MAX) */ /* Not counted to SOUND_MIXER_NRDEVICES, but use the same number space */ #define SOUND_ONOFF_MIN 28 #define SOUND_ONOFF_MAX 30 /* Note! Number 31 cannot be used since the sign bit is reserved */ #define SOUND_MIXER_NONE 31 /* * The following unsupported macros are no longer functional. * Use SOUND_MIXER_PRIVATE# macros in future. */ #define SOUND_MIXER_ENHANCE SOUND_MIXER_NONE #define SOUND_MIXER_MUTE SOUND_MIXER_NONE #define SOUND_MIXER_LOUD SOUND_MIXER_NONE #define SOUND_DEVICE_LABELS {"Vol ", "Bass ", "Trebl", "Synth", "Pcm ", "Spkr ", "Line ", \ "Mic ", "CD ", "Mix ", "Pcm2 ", "Rec ", "IGain", "OGain", \ "Line1", "Line2", "Line3", "Digital1", "Digital2", "Digital3", \ "PhoneIn", "PhoneOut", "Video", "Radio", "Monitor"} #define SOUND_DEVICE_NAMES {"vol", "bass", "treble", "synth", "pcm", "speaker", "line", \ "mic", "cd", "mix", "pcm2", "rec", "igain", "ogain", \ "line1", "line2", "line3", "dig1", "dig2", "dig3", \ "phin", "phout", "video", "radio", "monitor"} /* Device bitmask identifiers */ #define SOUND_MIXER_RECSRC 0xff /* Arg contains a bit for each recording source */ #define SOUND_MIXER_DEVMASK 0xfe /* Arg contains a bit for each supported device */ #define SOUND_MIXER_RECMASK 0xfd /* Arg contains a bit for each supported recording source */ #define SOUND_MIXER_CAPS 0xfc # define SOUND_CAP_EXCL_INPUT 0x00000001 /* Only one recording source at a time */ #define SOUND_MIXER_STEREODEVS 0xfb /* Mixer channels supporting stereo */ #define SOUND_MIXER_OUTSRC 0xfa /* Arg contains a bit for each input source to output */ #define SOUND_MIXER_OUTMASK 0xf9 /* Arg contains a bit for each supported input source to output */ /* Device mask bits */ #define SOUND_MASK_VOLUME (1 << SOUND_MIXER_VOLUME) #define SOUND_MASK_BASS (1 << SOUND_MIXER_BASS) #define SOUND_MASK_TREBLE (1 << SOUND_MIXER_TREBLE) #define SOUND_MASK_SYNTH (1 << SOUND_MIXER_SYNTH) #define SOUND_MASK_PCM (1 << SOUND_MIXER_PCM) #define SOUND_MASK_SPEAKER (1 << SOUND_MIXER_SPEAKER) #define SOUND_MASK_LINE (1 << SOUND_MIXER_LINE) #define SOUND_MASK_MIC (1 << SOUND_MIXER_MIC) #define SOUND_MASK_CD (1 << SOUND_MIXER_CD) #define SOUND_MASK_IMIX (1 << SOUND_MIXER_IMIX) #define SOUND_MASK_ALTPCM (1 << SOUND_MIXER_ALTPCM) #define SOUND_MASK_RECLEV (1 << SOUND_MIXER_RECLEV) #define SOUND_MASK_IGAIN (1 << SOUND_MIXER_IGAIN) #define SOUND_MASK_OGAIN (1 << SOUND_MIXER_OGAIN) #define SOUND_MASK_LINE1 (1 << SOUND_MIXER_LINE1) #define SOUND_MASK_LINE2 (1 << SOUND_MIXER_LINE2) #define SOUND_MASK_LINE3 (1 << SOUND_MIXER_LINE3) #define SOUND_MASK_DIGITAL1 (1 << SOUND_MIXER_DIGITAL1) #define SOUND_MASK_DIGITAL2 (1 << SOUND_MIXER_DIGITAL2) #define SOUND_MASK_DIGITAL3 (1 << SOUND_MIXER_DIGITAL3) #define SOUND_MASK_PHONEIN (1 << SOUND_MIXER_PHONEIN) #define SOUND_MASK_PHONEOUT (1 << SOUND_MIXER_PHONEOUT) #define SOUND_MASK_RADIO (1 << SOUND_MIXER_RADIO) #define SOUND_MASK_VIDEO (1 << SOUND_MIXER_VIDEO) #define SOUND_MASK_MONITOR (1 << SOUND_MIXER_MONITOR) /* Obsolete macros */ #define SOUND_MASK_MUTE (1 << SOUND_MIXER_MUTE) #define SOUND_MASK_ENHANCE (1 << SOUND_MIXER_ENHANCE) #define SOUND_MASK_LOUD (1 << SOUND_MIXER_LOUD) #define MIXER_READ(dev) _SIOR('M', dev, int) #define SOUND_MIXER_READ_VOLUME MIXER_READ(SOUND_MIXER_VOLUME) #define SOUND_MIXER_READ_BASS MIXER_READ(SOUND_MIXER_BASS) #define SOUND_MIXER_READ_TREBLE MIXER_READ(SOUND_MIXER_TREBLE) #define SOUND_MIXER_READ_SYNTH MIXER_READ(SOUND_MIXER_SYNTH) #define SOUND_MIXER_READ_PCM MIXER_READ(SOUND_MIXER_PCM) #define SOUND_MIXER_READ_SPEAKER MIXER_READ(SOUND_MIXER_SPEAKER) #define SOUND_MIXER_READ_LINE MIXER_READ(SOUND_MIXER_LINE) #define SOUND_MIXER_READ_MIC MIXER_READ(SOUND_MIXER_MIC) #define SOUND_MIXER_READ_CD MIXER_READ(SOUND_MIXER_CD) #define SOUND_MIXER_READ_IMIX MIXER_READ(SOUND_MIXER_IMIX) #define SOUND_MIXER_READ_ALTPCM MIXER_READ(SOUND_MIXER_ALTPCM) #define SOUND_MIXER_READ_RECLEV MIXER_READ(SOUND_MIXER_RECLEV) #define SOUND_MIXER_READ_IGAIN MIXER_READ(SOUND_MIXER_IGAIN) #define SOUND_MIXER_READ_OGAIN MIXER_READ(SOUND_MIXER_OGAIN) #define SOUND_MIXER_READ_LINE1 MIXER_READ(SOUND_MIXER_LINE1) #define SOUND_MIXER_READ_LINE2 MIXER_READ(SOUND_MIXER_LINE2) #define SOUND_MIXER_READ_LINE3 MIXER_READ(SOUND_MIXER_LINE3) /* Obsolete macros */ #define SOUND_MIXER_READ_MUTE MIXER_READ(SOUND_MIXER_MUTE) #define SOUND_MIXER_READ_ENHANCE MIXER_READ(SOUND_MIXER_ENHANCE) #define SOUND_MIXER_READ_LOUD MIXER_READ(SOUND_MIXER_LOUD) #define SOUND_MIXER_READ_RECSRC MIXER_READ(SOUND_MIXER_RECSRC) #define SOUND_MIXER_READ_DEVMASK MIXER_READ(SOUND_MIXER_DEVMASK) #define SOUND_MIXER_READ_RECMASK MIXER_READ(SOUND_MIXER_RECMASK) #define SOUND_MIXER_READ_STEREODEVS MIXER_READ(SOUND_MIXER_STEREODEVS) #define SOUND_MIXER_READ_CAPS MIXER_READ(SOUND_MIXER_CAPS) #define MIXER_WRITE(dev) _SIOWR('M', dev, int) #define SOUND_MIXER_WRITE_VOLUME MIXER_WRITE(SOUND_MIXER_VOLUME) #define SOUND_MIXER_WRITE_BASS MIXER_WRITE(SOUND_MIXER_BASS) #define SOUND_MIXER_WRITE_TREBLE MIXER_WRITE(SOUND_MIXER_TREBLE) #define SOUND_MIXER_WRITE_SYNTH MIXER_WRITE(SOUND_MIXER_SYNTH) #define SOUND_MIXER_WRITE_PCM MIXER_WRITE(SOUND_MIXER_PCM) #define SOUND_MIXER_WRITE_SPEAKER MIXER_WRITE(SOUND_MIXER_SPEAKER) #define SOUND_MIXER_WRITE_LINE MIXER_WRITE(SOUND_MIXER_LINE) #define SOUND_MIXER_WRITE_MIC MIXER_WRITE(SOUND_MIXER_MIC) #define SOUND_MIXER_WRITE_CD MIXER_WRITE(SOUND_MIXER_CD) #define SOUND_MIXER_WRITE_IMIX MIXER_WRITE(SOUND_MIXER_IMIX) #define SOUND_MIXER_WRITE_ALTPCM MIXER_WRITE(SOUND_MIXER_ALTPCM) #define SOUND_MIXER_WRITE_RECLEV MIXER_WRITE(SOUND_MIXER_RECLEV) #define SOUND_MIXER_WRITE_IGAIN MIXER_WRITE(SOUND_MIXER_IGAIN) #define SOUND_MIXER_WRITE_OGAIN MIXER_WRITE(SOUND_MIXER_OGAIN) #define SOUND_MIXER_WRITE_LINE1 MIXER_WRITE(SOUND_MIXER_LINE1) #define SOUND_MIXER_WRITE_LINE2 MIXER_WRITE(SOUND_MIXER_LINE2) #define SOUND_MIXER_WRITE_LINE3 MIXER_WRITE(SOUND_MIXER_LINE3) /* Obsolete macros */ #define SOUND_MIXER_WRITE_MUTE MIXER_WRITE(SOUND_MIXER_MUTE) #define SOUND_MIXER_WRITE_ENHANCE MIXER_WRITE(SOUND_MIXER_ENHANCE) #define SOUND_MIXER_WRITE_LOUD MIXER_WRITE(SOUND_MIXER_LOUD) #define SOUND_MIXER_WRITE_RECSRC MIXER_WRITE(SOUND_MIXER_RECSRC) typedef struct mixer_info { char id[16]; char name[32]; int modify_counter; int fillers[10]; } mixer_info; typedef struct _old_mixer_info /* Obsolete */ { char id[16]; char name[32]; } _old_mixer_info; #define SOUND_MIXER_INFO _SIOR ('M', 101, mixer_info) #define SOUND_OLD_MIXER_INFO _SIOR ('M', 101, _old_mixer_info) /* * A mechanism for accessing "proprietary" mixer features. This method * permits passing 128 bytes of arbitrary data between a mixer application * and the mixer driver. Interpretation of the record is defined by * the particular mixer driver. */ typedef unsigned char mixer_record[128]; #define SOUND_MIXER_ACCESS _SIOWR('M', 102, mixer_record) /* * Two ioctls for special souncard function */ #define SOUND_MIXER_AGC _SIOWR('M', 103, int) #define SOUND_MIXER_3DSE _SIOWR('M', 104, int) /* * The SOUND_MIXER_PRIVATE# commands can be redefined by low level drivers. * These features can be used when accessing device specific features. */ #define SOUND_MIXER_PRIVATE1 _SIOWR('M', 111, int) #define SOUND_MIXER_PRIVATE2 _SIOWR('M', 112, int) #define SOUND_MIXER_PRIVATE3 _SIOWR('M', 113, int) #define SOUND_MIXER_PRIVATE4 _SIOWR('M', 114, int) #define SOUND_MIXER_PRIVATE5 _SIOWR('M', 115, int) /* * SOUND_MIXER_GETLEVELS and SOUND_MIXER_SETLEVELS calls can be used * for querying current mixer settings from the driver and for loading * default volume settings _prior_ activating the mixer (loading * doesn't affect current state of the mixer hardware). These calls * are for internal use only. */ typedef struct mixer_vol_table { int num; /* Index to volume table */ char name[32]; int levels[32]; } mixer_vol_table; #define SOUND_MIXER_GETLEVELS _SIOWR('M', 116, mixer_vol_table) #define SOUND_MIXER_SETLEVELS _SIOWR('M', 117, mixer_vol_table) /* * An ioctl for identifying the driver version. It will return value * of the SOUND_VERSION macro used when compiling the driver. * This call was introduced in OSS version 3.6 and it will not work * with earlier versions (returns EINVAL). */ #define OSS_GETVERSION _SIOR ('M', 118, int) /* * Level 2 event types for /dev/sequencer */ /* * The 4 most significant bits of byte 0 specify the class of * the event: * * 0x8X = system level events, * 0x9X = device/port specific events, event[1] = device/port, * The last 4 bits give the subtype: * 0x02 = Channel event (event[3] = chn). * 0x01 = note event (event[4] = note). * (0x01 is not used alone but always with bit 0x02). * event[2] = MIDI message code (0x80=note off etc.) * */ #define EV_SEQ_LOCAL 0x80 #define EV_TIMING 0x81 #define EV_CHN_COMMON 0x92 #define EV_CHN_VOICE 0x93 #define EV_SYSEX 0x94 /* * Event types 200 to 220 are reserved for application use. * These numbers will not be used by the driver. */ /* * Events for event type EV_CHN_VOICE */ #define MIDI_NOTEOFF 0x80 #define MIDI_NOTEON 0x90 #define MIDI_KEY_PRESSURE 0xA0 /* * Events for event type EV_CHN_COMMON */ #define MIDI_CTL_CHANGE 0xB0 #define MIDI_PGM_CHANGE 0xC0 #define MIDI_CHN_PRESSURE 0xD0 #define MIDI_PITCH_BEND 0xE0 #define MIDI_SYSTEM_PREFIX 0xF0 /* * Timer event types */ #define TMR_WAIT_REL 1 /* Time relative to the prev time */ #define TMR_WAIT_ABS 2 /* Absolute time since TMR_START */ #define TMR_STOP 3 #define TMR_START 4 #define TMR_CONTINUE 5 #define TMR_TEMPO 6 #define TMR_ECHO 8 #define TMR_CLOCK 9 /* MIDI clock */ #define TMR_SPP 10 /* Song position pointer */ #define TMR_TIMESIG 11 /* Time signature */ /* * Local event types */ #define LOCL_STARTAUDIO 1 /* * Some convenience macros to simplify programming of the * /dev/sequencer interface * * This is a legacy interface for applications written against * the OSSlib-3.8 style interface. It is no longer possible * to actually link against OSSlib with this header, but we * still provide these macros for programs using them. * * If you want to use OSSlib, it is recommended that you get * the GPL version of OSS-4.x and build against that version * of the header. * * We redefine the extern keyword so that make headers_check * does not complain about SEQ_USE_EXTBUF. */ #define SEQ_DECLAREBUF() SEQ_USE_EXTBUF() void seqbuf_dump(void); /* This function must be provided by programs */ #define SEQ_PM_DEFINES int __foo_bar___ #define SEQ_LOAD_GMINSTR(dev, instr) #define SEQ_LOAD_GMDRUM(dev, drum) #define _SEQ_EXTERN extern #define SEQ_USE_EXTBUF() \ _SEQ_EXTERN unsigned char _seqbuf[]; \ _SEQ_EXTERN int _seqbuflen; _SEQ_EXTERN int _seqbufptr #ifndef USE_SIMPLE_MACROS /* Sample seqbuf_dump() implementation: * * SEQ_DEFINEBUF (2048); -- Defines a buffer for 2048 bytes * * int seqfd; -- The file descriptor for /dev/sequencer. * * void * seqbuf_dump () * { * if (_seqbufptr) * if (write (seqfd, _seqbuf, _seqbufptr) == -1) * { * perror ("write /dev/sequencer"); * exit (-1); * } * _seqbufptr = 0; * } */ #define SEQ_DEFINEBUF(len) unsigned char _seqbuf[len]; int _seqbuflen = len;int _seqbufptr = 0 #define _SEQ_NEEDBUF(len) if ((_seqbufptr+(len)) > _seqbuflen) seqbuf_dump() #define _SEQ_ADVBUF(len) _seqbufptr += len #define SEQ_DUMPBUF seqbuf_dump #else /* * This variation of the sequencer macros is used just to format one event * using fixed buffer. * * The program using the macro library must define the following macros before * using this library. * * #define _seqbuf name of the buffer (unsigned char[]) * #define _SEQ_ADVBUF(len) If the applic needs to know the exact * size of the event, this macro can be used. * Otherwise this must be defined as empty. * #define _seqbufptr Define the name of index variable or 0 if * not required. */ #define _SEQ_NEEDBUF(len) /* empty */ #endif #define SEQ_VOLUME_MODE(dev, mode) {_SEQ_NEEDBUF(8);\ _seqbuf[_seqbufptr] = SEQ_EXTENDED;\ _seqbuf[_seqbufptr+1] = SEQ_VOLMODE;\ _seqbuf[_seqbufptr+2] = (dev);\ _seqbuf[_seqbufptr+3] = (mode);\ _seqbuf[_seqbufptr+4] = 0;\ _seqbuf[_seqbufptr+5] = 0;\ _seqbuf[_seqbufptr+6] = 0;\ _seqbuf[_seqbufptr+7] = 0;\ _SEQ_ADVBUF(8);} /* * Midi voice messages */ #define _CHN_VOICE(dev, event, chn, note, parm) \ {_SEQ_NEEDBUF(8);\ _seqbuf[_seqbufptr] = EV_CHN_VOICE;\ _seqbuf[_seqbufptr+1] = (dev);\ _seqbuf[_seqbufptr+2] = (event);\ _seqbuf[_seqbufptr+3] = (chn);\ _seqbuf[_seqbufptr+4] = (note);\ _seqbuf[_seqbufptr+5] = (parm);\ _seqbuf[_seqbufptr+6] = (0);\ _seqbuf[_seqbufptr+7] = 0;\ _SEQ_ADVBUF(8);} #define SEQ_START_NOTE(dev, chn, note, vol) \ _CHN_VOICE(dev, MIDI_NOTEON, chn, note, vol) #define SEQ_STOP_NOTE(dev, chn, note, vol) \ _CHN_VOICE(dev, MIDI_NOTEOFF, chn, note, vol) #define SEQ_KEY_PRESSURE(dev, chn, note, pressure) \ _CHN_VOICE(dev, MIDI_KEY_PRESSURE, chn, note, pressure) /* * Midi channel messages */ #define _CHN_COMMON(dev, event, chn, p1, p2, w14) \ {_SEQ_NEEDBUF(8);\ _seqbuf[_seqbufptr] = EV_CHN_COMMON;\ _seqbuf[_seqbufptr+1] = (dev);\ _seqbuf[_seqbufptr+2] = (event);\ _seqbuf[_seqbufptr+3] = (chn);\ _seqbuf[_seqbufptr+4] = (p1);\ _seqbuf[_seqbufptr+5] = (p2);\ *(short *)&_seqbuf[_seqbufptr+6] = (w14);\ _SEQ_ADVBUF(8);} /* * SEQ_SYSEX permits sending of sysex messages. (It may look that it permits * sending any MIDI bytes but it's absolutely not possible. Trying to do * so _will_ cause problems with MPU401 intelligent mode). * * Sysex messages are sent in blocks of 1 to 6 bytes. Longer messages must be * sent by calling SEQ_SYSEX() several times (there must be no other events * between them). First sysex fragment must have 0xf0 in the first byte * and the last byte (buf[len-1] of the last fragment must be 0xf7. No byte * between these sysex start and end markers cannot be larger than 0x7f. Also * lengths of each fragments (except the last one) must be 6. * * Breaking the above rules may work with some MIDI ports but is likely to * cause fatal problems with some other devices (such as MPU401). */ #define SEQ_SYSEX(dev, buf, len) \ {int ii, ll=(len); \ unsigned char *bufp=buf;\ if (ll>6)ll=6;\ _SEQ_NEEDBUF(8);\ _seqbuf[_seqbufptr] = EV_SYSEX;\ _seqbuf[_seqbufptr+1] = (dev);\ for(ii=0;ii>8)&0xff);\ _seqbuf[_seqbufptr+7] = 0;\ _SEQ_ADVBUF(8);} /* * The following 5 macros are incorrectly implemented and obsolete. * Use SEQ_BENDER and SEQ_CONTROL (with proper controller) instead. */ #define SEQ_PITCHBEND(dev, voice, value) SEQ_V2_X_CONTROL(dev, voice, CTRL_PITCH_BENDER, value) #define SEQ_BENDER_RANGE(dev, voice, value) SEQ_V2_X_CONTROL(dev, voice, CTRL_PITCH_BENDER_RANGE, value) #define SEQ_EXPRESSION(dev, voice, value) SEQ_CONTROL(dev, voice, CTL_EXPRESSION, value*128) #define SEQ_MAIN_VOLUME(dev, voice, value) SEQ_CONTROL(dev, voice, CTL_MAIN_VOLUME, (value*16383)/100) #define SEQ_PANNING(dev, voice, pos) SEQ_CONTROL(dev, voice, CTL_PAN, (pos+128) / 2) /* * Timing and synchronization macros */ #define _TIMER_EVENT(ev, parm) {_SEQ_NEEDBUF(8);\ _seqbuf[_seqbufptr+0] = EV_TIMING; \ _seqbuf[_seqbufptr+1] = (ev); \ _seqbuf[_seqbufptr+2] = 0;\ _seqbuf[_seqbufptr+3] = 0;\ *(unsigned int *)&_seqbuf[_seqbufptr+4] = (parm); \ _SEQ_ADVBUF(8);} #define SEQ_START_TIMER() _TIMER_EVENT(TMR_START, 0) #define SEQ_STOP_TIMER() _TIMER_EVENT(TMR_STOP, 0) #define SEQ_CONTINUE_TIMER() _TIMER_EVENT(TMR_CONTINUE, 0) #define SEQ_WAIT_TIME(ticks) _TIMER_EVENT(TMR_WAIT_ABS, ticks) #define SEQ_DELTA_TIME(ticks) _TIMER_EVENT(TMR_WAIT_REL, ticks) #define SEQ_ECHO_BACK(key) _TIMER_EVENT(TMR_ECHO, key) #define SEQ_SET_TEMPO(value) _TIMER_EVENT(TMR_TEMPO, value) #define SEQ_SONGPOS(pos) _TIMER_EVENT(TMR_SPP, pos) #define SEQ_TIME_SIGNATURE(sig) _TIMER_EVENT(TMR_TIMESIG, sig) /* * Local control events */ #define _LOCAL_EVENT(ev, parm) {_SEQ_NEEDBUF(8);\ _seqbuf[_seqbufptr+0] = EV_SEQ_LOCAL; \ _seqbuf[_seqbufptr+1] = (ev); \ _seqbuf[_seqbufptr+2] = 0;\ _seqbuf[_seqbufptr+3] = 0;\ *(unsigned int *)&_seqbuf[_seqbufptr+4] = (parm); \ _SEQ_ADVBUF(8);} #define SEQ_PLAYAUDIO(devmask) _LOCAL_EVENT(LOCL_STARTAUDIO, devmask) /* * Events for the level 1 interface only */ #define SEQ_MIDIOUT(device, byte) {_SEQ_NEEDBUF(4);\ _seqbuf[_seqbufptr] = SEQ_MIDIPUTC;\ _seqbuf[_seqbufptr+1] = (byte);\ _seqbuf[_seqbufptr+2] = (device);\ _seqbuf[_seqbufptr+3] = 0;\ _SEQ_ADVBUF(4);} /* * Patch loading. */ #define SEQ_WRPATCH(patchx, len) \ {if (_seqbufptr) SEQ_DUMPBUF();\ if (write(seqfd, (char*)(patchx), len)==-1) \ perror("Write patch: /dev/sequencer");} #define SEQ_WRPATCH2(patchx, len) \ (SEQ_DUMPBUF(), write(seqfd, (char*)(patchx), len)) #endif /* SOUNDCARD_H */ linux/lp.h000064400000010136151027430560006473 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * usr/include/linux/lp.h c.1991-1992 James Wiegand * many modifications copyright (C) 1992 Michael K. Johnson * Interrupt support added 1993 Nigel Gamble * Removed 8255 status defines from inside __KERNEL__ Marcelo Tosatti */ #ifndef _LINUX_LP_H #define _LINUX_LP_H #include #include /* * Per POSIX guidelines, this module reserves the LP and lp prefixes * These are the lp_table[minor].flags flags... */ #define LP_EXIST 0x0001 #define LP_SELEC 0x0002 #define LP_BUSY 0x0004 #define LP_BUSY_BIT_POS 2 #define LP_OFFL 0x0008 #define LP_NOPA 0x0010 #define LP_ERR 0x0020 #define LP_ABORT 0x0040 #define LP_CAREFUL 0x0080 /* obsoleted -arca */ #define LP_ABORTOPEN 0x0100 #define LP_TRUST_IRQ_ 0x0200 /* obsolete */ #define LP_NO_REVERSE 0x0400 /* No reverse mode available. */ #define LP_DATA_AVAIL 0x0800 /* Data is available. */ /* * bit defines for 8255 status port * base + 1 * accessed with LP_S(minor), which gets the byte... */ #define LP_PBUSY 0x80 /* inverted input, active high */ #define LP_PACK 0x40 /* unchanged input, active low */ #define LP_POUTPA 0x20 /* unchanged input, active high */ #define LP_PSELECD 0x10 /* unchanged input, active high */ #define LP_PERRORP 0x08 /* unchanged input, active low */ /* timeout for each character. This is relative to bus cycles -- it * is the count in a busy loop. THIS IS THE VALUE TO CHANGE if you * have extremely slow printing, or if the machine seems to slow down * a lot when you print. If you have slow printing, increase this * number and recompile, and if your system gets bogged down, decrease * this number. This can be changed with the tunelp(8) command as well. */ #define LP_INIT_CHAR 1000 /* The parallel port specs apparently say that there needs to be * a .5usec wait before and after the strobe. */ #define LP_INIT_WAIT 1 /* This is the amount of time that the driver waits for the printer to * catch up when the printer's buffer appears to be filled. If you * want to tune this and have a fast printer (i.e. HPIIIP), decrease * this number, and if you have a slow printer, increase this number. * This is in hundredths of a second, the default 2 being .05 second. * Or use the tunelp(8) command, which is especially nice if you want * change back and forth between character and graphics printing, which * are wildly different... */ #define LP_INIT_TIME 2 /* IOCTL numbers */ #define LPCHAR 0x0601 /* corresponds to LP_INIT_CHAR */ #define LPTIME 0x0602 /* corresponds to LP_INIT_TIME */ #define LPABORT 0x0604 /* call with TRUE arg to abort on error, FALSE to retry. Default is retry. */ #define LPSETIRQ 0x0605 /* call with new IRQ number, or 0 for polling (no IRQ) */ #define LPGETIRQ 0x0606 /* get the current IRQ number */ #define LPWAIT 0x0608 /* corresponds to LP_INIT_WAIT */ /* NOTE: LPCAREFUL is obsoleted and it' s always the default right now -arca */ #define LPCAREFUL 0x0609 /* call with TRUE arg to require out-of-paper, off- line, and error indicators good on all writes, FALSE to ignore them. Default is ignore. */ #define LPABORTOPEN 0x060a /* call with TRUE arg to abort open() on error, FALSE to ignore error. Default is ignore. */ #define LPGETSTATUS 0x060b /* return LP_S(minor) */ #define LPRESET 0x060c /* reset printer */ #ifdef LP_STATS #define LPGETSTATS 0x060d /* get statistics (struct lp_stats) */ #endif #define LPGETFLAGS 0x060e /* get status flags */ #define LPSETTIMEOUT_OLD 0x060f /* set parport timeout */ #define LPSETTIMEOUT_NEW \ _IOW(0x6, 0xf, __s64[2]) /* set parport timeout */ #if __BITS_PER_LONG == 64 #define LPSETTIMEOUT LPSETTIMEOUT_OLD #else #define LPSETTIMEOUT (sizeof(time_t) > sizeof(__kernel_long_t) ? \ LPSETTIMEOUT_NEW : LPSETTIMEOUT_OLD) #endif /* timeout for printk'ing a timeout, in jiffies (100ths of a second). This is also used for re-checking error conditions if LP_ABORT is not set. This is the default behavior. */ #define LP_TIMEOUT_INTERRUPT (60 * HZ) #define LP_TIMEOUT_POLLED (10 * HZ) #endif /* _LINUX_LP_H */ linux/vhost.h000064400000014422151027430560007225 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_VHOST_H #define _LINUX_VHOST_H /* Userspace interface for in-kernel virtio accelerators. */ /* vhost is used to reduce the number of system calls involved in virtio. * * Existing virtio net code is used in the guest without modification. * * This header includes interface used by userspace hypervisor for * device configuration. */ #include #include #include #define VHOST_FILE_UNBIND -1 /* ioctls */ #define VHOST_VIRTIO 0xAF /* Features bitmask for forward compatibility. Transport bits are used for * vhost specific features. */ #define VHOST_GET_FEATURES _IOR(VHOST_VIRTIO, 0x00, __u64) #define VHOST_SET_FEATURES _IOW(VHOST_VIRTIO, 0x00, __u64) /* Set current process as the (exclusive) owner of this file descriptor. This * must be called before any other vhost command. Further calls to * VHOST_OWNER_SET fail until VHOST_OWNER_RESET is called. */ #define VHOST_SET_OWNER _IO(VHOST_VIRTIO, 0x01) /* Give up ownership, and reset the device to default values. * Allows subsequent call to VHOST_OWNER_SET to succeed. */ #define VHOST_RESET_OWNER _IO(VHOST_VIRTIO, 0x02) /* Set up/modify memory layout */ #define VHOST_SET_MEM_TABLE _IOW(VHOST_VIRTIO, 0x03, struct vhost_memory) /* Write logging setup. */ /* Memory writes can optionally be logged by setting bit at an offset * (calculated from the physical address) from specified log base. * The bit is set using an atomic 32 bit operation. */ /* Set base address for logging. */ #define VHOST_SET_LOG_BASE _IOW(VHOST_VIRTIO, 0x04, __u64) /* Specify an eventfd file descriptor to signal on log write. */ #define VHOST_SET_LOG_FD _IOW(VHOST_VIRTIO, 0x07, int) /* Ring setup. */ /* Set number of descriptors in ring. This parameter can not * be modified while ring is running (bound to a device). */ #define VHOST_SET_VRING_NUM _IOW(VHOST_VIRTIO, 0x10, struct vhost_vring_state) /* Set addresses for the ring. */ #define VHOST_SET_VRING_ADDR _IOW(VHOST_VIRTIO, 0x11, struct vhost_vring_addr) /* Base value where queue looks for available descriptors */ #define VHOST_SET_VRING_BASE _IOW(VHOST_VIRTIO, 0x12, struct vhost_vring_state) /* Get accessor: reads index, writes value in num */ #define VHOST_GET_VRING_BASE _IOWR(VHOST_VIRTIO, 0x12, struct vhost_vring_state) /* Set the vring byte order in num. Valid values are VHOST_VRING_LITTLE_ENDIAN * or VHOST_VRING_BIG_ENDIAN (other values return -EINVAL). * The byte order cannot be changed while the device is active: trying to do so * returns -EBUSY. * This is a legacy only API that is simply ignored when VIRTIO_F_VERSION_1 is * set. * Not all kernel configurations support this ioctl, but all configurations that * support SET also support GET. */ #define VHOST_VRING_LITTLE_ENDIAN 0 #define VHOST_VRING_BIG_ENDIAN 1 #define VHOST_SET_VRING_ENDIAN _IOW(VHOST_VIRTIO, 0x13, struct vhost_vring_state) #define VHOST_GET_VRING_ENDIAN _IOW(VHOST_VIRTIO, 0x14, struct vhost_vring_state) /* The following ioctls use eventfd file descriptors to signal and poll * for events. */ /* Set eventfd to poll for added buffers */ #define VHOST_SET_VRING_KICK _IOW(VHOST_VIRTIO, 0x20, struct vhost_vring_file) /* Set eventfd to signal when buffers have beed used */ #define VHOST_SET_VRING_CALL _IOW(VHOST_VIRTIO, 0x21, struct vhost_vring_file) /* Set eventfd to signal an error */ #define VHOST_SET_VRING_ERR _IOW(VHOST_VIRTIO, 0x22, struct vhost_vring_file) /* Set busy loop timeout (in us) */ #define VHOST_SET_VRING_BUSYLOOP_TIMEOUT _IOW(VHOST_VIRTIO, 0x23, \ struct vhost_vring_state) /* Get busy loop timeout (in us) */ #define VHOST_GET_VRING_BUSYLOOP_TIMEOUT _IOW(VHOST_VIRTIO, 0x24, \ struct vhost_vring_state) /* Set or get vhost backend capability */ /* Use message type V2 */ #define VHOST_BACKEND_F_IOTLB_MSG_V2 0x1 /* IOTLB can accept batching hints */ #define VHOST_BACKEND_F_IOTLB_BATCH 0x2 #define VHOST_SET_BACKEND_FEATURES _IOW(VHOST_VIRTIO, 0x25, __u64) #define VHOST_GET_BACKEND_FEATURES _IOR(VHOST_VIRTIO, 0x26, __u64) /* VHOST_NET specific defines */ /* Attach virtio net ring to a raw socket, or tap device. * The socket must be already bound to an ethernet device, this device will be * used for transmit. Pass fd -1 to unbind from the socket and the transmit * device. This can be used to stop the ring (e.g. for migration). */ #define VHOST_NET_SET_BACKEND _IOW(VHOST_VIRTIO, 0x30, struct vhost_vring_file) /* VHOST_SCSI specific defines */ #define VHOST_SCSI_SET_ENDPOINT _IOW(VHOST_VIRTIO, 0x40, struct vhost_scsi_target) #define VHOST_SCSI_CLEAR_ENDPOINT _IOW(VHOST_VIRTIO, 0x41, struct vhost_scsi_target) /* Changing this breaks userspace. */ #define VHOST_SCSI_GET_ABI_VERSION _IOW(VHOST_VIRTIO, 0x42, int) /* Set and get the events missed flag */ #define VHOST_SCSI_SET_EVENTS_MISSED _IOW(VHOST_VIRTIO, 0x43, __u32) #define VHOST_SCSI_GET_EVENTS_MISSED _IOW(VHOST_VIRTIO, 0x44, __u32) /* VHOST_VSOCK specific defines */ #define VHOST_VSOCK_SET_GUEST_CID _IOW(VHOST_VIRTIO, 0x60, __u64) #define VHOST_VSOCK_SET_RUNNING _IOW(VHOST_VIRTIO, 0x61, int) /* VHOST_VDPA specific defines */ /* Get the device id. The device ids follow the same definition of * the device id defined in virtio-spec. */ #define VHOST_VDPA_GET_DEVICE_ID _IOR(VHOST_VIRTIO, 0x70, __u32) /* Get and set the status. The status bits follow the same definition * of the device status defined in virtio-spec. */ #define VHOST_VDPA_GET_STATUS _IOR(VHOST_VIRTIO, 0x71, __u8) #define VHOST_VDPA_SET_STATUS _IOW(VHOST_VIRTIO, 0x72, __u8) /* Get and set the device config. The device config follows the same * definition of the device config defined in virtio-spec. */ #define VHOST_VDPA_GET_CONFIG _IOR(VHOST_VIRTIO, 0x73, \ struct vhost_vdpa_config) #define VHOST_VDPA_SET_CONFIG _IOW(VHOST_VIRTIO, 0x74, \ struct vhost_vdpa_config) /* Enable/disable the ring. */ #define VHOST_VDPA_SET_VRING_ENABLE _IOW(VHOST_VIRTIO, 0x75, \ struct vhost_vring_state) /* Get the max ring size. */ #define VHOST_VDPA_GET_VRING_NUM _IOR(VHOST_VIRTIO, 0x76, __u16) /* Set event fd for config interrupt*/ #define VHOST_VDPA_SET_CONFIG_CALL _IOW(VHOST_VIRTIO, 0x77, int) /* Get the valid iova range */ #define VHOST_VDPA_GET_IOVA_RANGE _IOR(VHOST_VIRTIO, 0x78, \ struct vhost_vdpa_iova_range) #endif linux/seg6_hmac.h000064400000000647151027430560007722 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SEG6_HMAC_H #define _LINUX_SEG6_HMAC_H #include #include #define SEG6_HMAC_SECRET_LEN 64 #define SEG6_HMAC_FIELD_LEN 32 struct sr6_tlv_hmac { struct sr6_tlv tlvhdr; __u16 reserved; __be32 hmackeyid; __u8 hmac[SEG6_HMAC_FIELD_LEN]; }; enum { SEG6_HMAC_ALGO_SHA1 = 1, SEG6_HMAC_ALGO_SHA256 = 2, }; #endif linux/virtio_balloon.h000064400000012232151027430560011101 0ustar00#ifndef _LINUX_VIRTIO_BALLOON_H #define _LINUX_VIRTIO_BALLOON_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include /* The feature bitmap for virtio balloon */ #define VIRTIO_BALLOON_F_MUST_TELL_HOST 0 /* Tell before reclaiming pages */ #define VIRTIO_BALLOON_F_STATS_VQ 1 /* Memory Stats virtqueue */ #define VIRTIO_BALLOON_F_DEFLATE_ON_OOM 2 /* Deflate balloon on OOM */ #define VIRTIO_BALLOON_F_FREE_PAGE_HINT 3 /* VQ to report free pages */ #define VIRTIO_BALLOON_F_PAGE_POISON 4 /* Guest is using page poisoning */ #define VIRTIO_BALLOON_F_REPORTING 5 /* Page reporting virtqueue */ /* Size of a PFN in the balloon interface. */ #define VIRTIO_BALLOON_PFN_SHIFT 12 #define VIRTIO_BALLOON_CMD_ID_STOP 0 #define VIRTIO_BALLOON_CMD_ID_DONE 1 struct virtio_balloon_config { /* Number of pages host wants Guest to give up. */ __u32 num_pages; /* Number of pages we've actually got in balloon. */ __u32 actual; /* * Free page hint command id, readonly by guest. * Was previously named free_page_report_cmd_id so we * need to carry that name for legacy support. */ union { __u32 free_page_hint_cmd_id; __u32 free_page_report_cmd_id; /* deprecated */ }; /* Stores PAGE_POISON if page poisoning is in use */ __u32 poison_val; }; #define VIRTIO_BALLOON_S_SWAP_IN 0 /* Amount of memory swapped in */ #define VIRTIO_BALLOON_S_SWAP_OUT 1 /* Amount of memory swapped out */ #define VIRTIO_BALLOON_S_MAJFLT 2 /* Number of major faults */ #define VIRTIO_BALLOON_S_MINFLT 3 /* Number of minor faults */ #define VIRTIO_BALLOON_S_MEMFREE 4 /* Total amount of free memory */ #define VIRTIO_BALLOON_S_MEMTOT 5 /* Total amount of memory */ #define VIRTIO_BALLOON_S_AVAIL 6 /* Available memory as in /proc */ #define VIRTIO_BALLOON_S_CACHES 7 /* Disk caches */ #define VIRTIO_BALLOON_S_HTLB_PGALLOC 8 /* Hugetlb page allocations */ #define VIRTIO_BALLOON_S_HTLB_PGFAIL 9 /* Hugetlb page allocation failures */ #define VIRTIO_BALLOON_S_NR 10 #define VIRTIO_BALLOON_S_NAMES_WITH_PREFIX(VIRTIO_BALLOON_S_NAMES_prefix) { \ VIRTIO_BALLOON_S_NAMES_prefix "swap-in", \ VIRTIO_BALLOON_S_NAMES_prefix "swap-out", \ VIRTIO_BALLOON_S_NAMES_prefix "major-faults", \ VIRTIO_BALLOON_S_NAMES_prefix "minor-faults", \ VIRTIO_BALLOON_S_NAMES_prefix "free-memory", \ VIRTIO_BALLOON_S_NAMES_prefix "total-memory", \ VIRTIO_BALLOON_S_NAMES_prefix "available-memory", \ VIRTIO_BALLOON_S_NAMES_prefix "disk-caches", \ VIRTIO_BALLOON_S_NAMES_prefix "hugetlb-allocations", \ VIRTIO_BALLOON_S_NAMES_prefix "hugetlb-failures" \ } #define VIRTIO_BALLOON_S_NAMES VIRTIO_BALLOON_S_NAMES_WITH_PREFIX("") /* * Memory statistics structure. * Driver fills an array of these structures and passes to device. * * NOTE: fields are laid out in a way that would make compiler add padding * between and after fields, so we have to use compiler-specific attributes to * pack it, to disable this padding. This also often causes compiler to * generate suboptimal code. * * We maintain this statistics structure format for backwards compatibility, * but don't follow this example. * * If implementing a similar structure, do something like the below instead: * struct virtio_balloon_stat { * __virtio16 tag; * __u8 reserved[6]; * __virtio64 val; * }; * * In other words, add explicit reserved fields to align field and * structure boundaries at field size, avoiding compiler padding * without the packed attribute. */ struct virtio_balloon_stat { __virtio16 tag; __virtio64 val; } __attribute__((packed)); #endif /* _LINUX_VIRTIO_BALLOON_H */ linux/kcov.h000064400000002113151027430560007016 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_KCOV_IOCTLS_H #define _LINUX_KCOV_IOCTLS_H #include #define KCOV_INIT_TRACE _IOR('c', 1, unsigned long) #define KCOV_ENABLE _IO('c', 100) #define KCOV_DISABLE _IO('c', 101) enum { /* * Tracing coverage collection mode. * Covered PCs are collected in a per-task buffer. * In new KCOV version the mode is chosen by calling * ioctl(fd, KCOV_ENABLE, mode). In older versions the mode argument * was supposed to be 0 in such a call. So, for reasons of backward * compatibility, we have chosen the value KCOV_TRACE_PC to be 0. */ KCOV_TRACE_PC = 0, /* Collecting comparison operands mode. */ KCOV_TRACE_CMP = 1, }; /* * The format for the types of collected comparisons. * * Bit 0 shows whether one of the arguments is a compile-time constant. * Bits 1 & 2 contain log2 of the argument size, up to 8 bytes. */ #define KCOV_CMP_CONST (1 << 0) #define KCOV_CMP_SIZE(n) ((n) << 1) #define KCOV_CMP_MASK KCOV_CMP_SIZE(3) #endif /* _LINUX_KCOV_IOCTLS_H */ linux/limits.h000064400000001651151027430560007363 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_LIMITS_H #define _LINUX_LIMITS_H #define NR_OPEN 1024 #define NGROUPS_MAX 65536 /* supplemental group IDs are available */ #define ARG_MAX 131072 /* # bytes of args + environ for exec() */ #define LINK_MAX 127 /* # links a file may have */ #define MAX_CANON 255 /* size of the canonical input queue */ #define MAX_INPUT 255 /* size of the type-ahead buffer */ #define NAME_MAX 255 /* # chars in a file name */ #define PATH_MAX 4096 /* # chars in a path name including nul */ #define PIPE_BUF 4096 /* # bytes in atomic write to a pipe */ #define XATTR_NAME_MAX 255 /* # chars in an extended attribute name */ #define XATTR_SIZE_MAX 65536 /* size of an extended attribute value (64k) */ #define XATTR_LIST_MAX 65536 /* size of extended attribute namelist (64k) */ #define RTSIG_MAX 32 #endif linux/cuda.h000064400000001611151027430560006772 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Definitions for talking to the CUDA. The CUDA is a microcontroller * which controls the ADB, system power, RTC, and various other things. * * Copyright (C) 1996 Paul Mackerras. */ #ifndef _LINUX_CUDA_H #define _LINUX_CUDA_H /* CUDA commands (2nd byte) */ #define CUDA_WARM_START 0 #define CUDA_AUTOPOLL 1 #define CUDA_GET_6805_ADDR 2 #define CUDA_GET_TIME 3 #define CUDA_GET_PRAM 7 #define CUDA_SET_6805_ADDR 8 #define CUDA_SET_TIME 9 #define CUDA_POWERDOWN 0xa #define CUDA_POWERUP_TIME 0xb #define CUDA_SET_PRAM 0xc #define CUDA_MS_RESET 0xd #define CUDA_SEND_DFAC 0xe #define CUDA_RESET_SYSTEM 0x11 #define CUDA_SET_IPL 0x12 #define CUDA_SET_AUTO_RATE 0x14 #define CUDA_GET_AUTO_RATE 0x16 #define CUDA_SET_DEVICE_LIST 0x19 #define CUDA_GET_DEVICE_LIST 0x1a #define CUDA_GET_SET_IIC 0x22 #endif /* _LINUX_CUDA_H */ linux/ip6_tunnel.h000064400000003641151027430560010146 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IP6_TUNNEL_H #define _IP6_TUNNEL_H #include #include /* For IFNAMSIZ. */ #include /* For struct in6_addr. */ #define IPV6_TLV_TNL_ENCAP_LIMIT 4 #define IPV6_DEFAULT_TNL_ENCAP_LIMIT 4 /* don't add encapsulation limit if one isn't present in inner packet */ #define IP6_TNL_F_IGN_ENCAP_LIMIT 0x1 /* copy the traffic class field from the inner packet */ #define IP6_TNL_F_USE_ORIG_TCLASS 0x2 /* copy the flowlabel from the inner packet */ #define IP6_TNL_F_USE_ORIG_FLOWLABEL 0x4 /* being used for Mobile IPv6 */ #define IP6_TNL_F_MIP6_DEV 0x8 /* copy DSCP from the outer packet */ #define IP6_TNL_F_RCV_DSCP_COPY 0x10 /* copy fwmark from inner packet */ #define IP6_TNL_F_USE_ORIG_FWMARK 0x20 /* allow remote endpoint on the local node */ #define IP6_TNL_F_ALLOW_LOCAL_REMOTE 0x40 struct ip6_tnl_parm { char name[IFNAMSIZ]; /* name of tunnel device */ int link; /* ifindex of underlying L2 interface */ __u8 proto; /* tunnel protocol */ __u8 encap_limit; /* encapsulation limit for tunnel */ __u8 hop_limit; /* hop limit for tunnel */ __be32 flowinfo; /* traffic class and flowlabel for tunnel */ __u32 flags; /* tunnel flags */ struct in6_addr laddr; /* local tunnel end-point address */ struct in6_addr raddr; /* remote tunnel end-point address */ }; struct ip6_tnl_parm2 { char name[IFNAMSIZ]; /* name of tunnel device */ int link; /* ifindex of underlying L2 interface */ __u8 proto; /* tunnel protocol */ __u8 encap_limit; /* encapsulation limit for tunnel */ __u8 hop_limit; /* hop limit for tunnel */ __be32 flowinfo; /* traffic class and flowlabel for tunnel */ __u32 flags; /* tunnel flags */ struct in6_addr laddr; /* local tunnel end-point address */ struct in6_addr raddr; /* remote tunnel end-point address */ __be16 i_flags; __be16 o_flags; __be32 i_key; __be32 o_key; }; #endif linux/udp.h000064400000003175151027430560006655 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the UDP protocol. * * Version: @(#)udp.h 1.0.2 04/28/93 * * Author: Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_UDP_H #define _LINUX_UDP_H #include struct udphdr { __be16 source; __be16 dest; __be16 len; __sum16 check; }; /* UDP socket options */ #define UDP_CORK 1 /* Never send partially complete segments */ #define UDP_ENCAP 100 /* Set the socket to accept encapsulated packets */ #define UDP_NO_CHECK6_TX 101 /* Disable sending checksum for UDP6X */ #define UDP_NO_CHECK6_RX 102 /* Disable accpeting checksum for UDP6 */ #define UDP_SEGMENT 103 /* Set GSO segmentation size */ #define UDP_GRO 104 /* This socket can receive UDP GRO packets */ /* UDP encapsulation types */ #define UDP_ENCAP_ESPINUDP_NON_IKE 1 /* draft-ietf-ipsec-nat-t-ike-00/01 */ #define UDP_ENCAP_ESPINUDP 2 /* draft-ietf-ipsec-udp-encaps-06 */ #define UDP_ENCAP_L2TPINUDP 3 /* rfc2661 */ #define UDP_ENCAP_GTP0 4 /* GSM TS 09.60 */ #define UDP_ENCAP_GTP1U 5 /* 3GPP TS 29.060 */ #define TCP_ENCAP_ESPINTCP 7 /* Yikes, this is really xfrm encap types. */ #endif /* _LINUX_UDP_H */ linux/pktcdvd.h000064400000005177151027430560007530 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2000 Jens Axboe * Copyright (C) 2001-2004 Peter Osterlund * * May be copied or modified under the terms of the GNU General Public * License. See linux/COPYING for more information. * * Packet writing layer for ATAPI and SCSI CD-R, CD-RW, DVD-R, and * DVD-RW devices. * */ #ifndef __PKTCDVD_H #define __PKTCDVD_H #include /* * 1 for normal debug messages, 2 is very verbose. 0 to turn it off. */ #define PACKET_DEBUG 1 #define MAX_WRITERS 8 #define PKT_RB_POOL_SIZE 512 /* * How long we should hold a non-full packet before starting data gathering. */ #define PACKET_WAIT_TIME (HZ * 5 / 1000) /* * use drive write caching -- we need deferred error handling to be * able to successfully recover with this option (drive will return good * status as soon as the cdb is validated). */ #if defined(CONFIG_CDROM_PKTCDVD_WCACHE) #define USE_WCACHING 1 #else #define USE_WCACHING 0 #endif /* * No user-servicable parts beyond this point -> */ /* * device types */ #define PACKET_CDR 1 #define PACKET_CDRW 2 #define PACKET_DVDR 3 #define PACKET_DVDRW 4 /* * flags */ #define PACKET_WRITABLE 1 /* pd is writable */ #define PACKET_NWA_VALID 2 /* next writable address valid */ #define PACKET_LRA_VALID 3 /* last recorded address valid */ #define PACKET_MERGE_SEGS 4 /* perform segment merging to keep */ /* underlying cdrom device happy */ /* * Disc status -- from READ_DISC_INFO */ #define PACKET_DISC_EMPTY 0 #define PACKET_DISC_INCOMPLETE 1 #define PACKET_DISC_COMPLETE 2 #define PACKET_DISC_OTHER 3 /* * write type, and corresponding data block type */ #define PACKET_MODE1 1 #define PACKET_MODE2 2 #define PACKET_BLOCK_MODE1 8 #define PACKET_BLOCK_MODE2 10 /* * Last session/border status */ #define PACKET_SESSION_EMPTY 0 #define PACKET_SESSION_INCOMPLETE 1 #define PACKET_SESSION_RESERVED 2 #define PACKET_SESSION_COMPLETE 3 #define PACKET_MCN "4a656e734178626f65323030300000" #undef PACKET_USE_LS #define PKT_CTRL_CMD_SETUP 0 #define PKT_CTRL_CMD_TEARDOWN 1 #define PKT_CTRL_CMD_STATUS 2 struct pkt_ctrl_command { __u32 command; /* in: Setup, teardown, status */ __u32 dev_index; /* in/out: Device index */ __u32 dev; /* in/out: Device nr for cdrw device */ __u32 pkt_dev; /* in/out: Device nr for packet device */ __u32 num_devices; /* out: Largest device index + 1 */ __u32 padding; /* Not used */ }; /* * packet ioctls */ #define PACKET_IOCTL_MAGIC ('X') #define PACKET_CTRL_CMD _IOWR(PACKET_IOCTL_MAGIC, 1, struct pkt_ctrl_command) #endif /* __PKTCDVD_H */ linux/libc-compat.h000064400000020141151027430560010247 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Compatibility interface for userspace libc header coordination: * * Define compatibility macros that are used to control the inclusion or * exclusion of UAPI structures and definitions in coordination with another * userspace C library. * * This header is intended to solve the problem of UAPI definitions that * conflict with userspace definitions. If a UAPI header has such conflicting * definitions then the solution is as follows: * * * Synchronize the UAPI header and the libc headers so either one can be * used and such that the ABI is preserved. If this is not possible then * no simple compatibility interface exists (you need to write translating * wrappers and rename things) and you can't use this interface. * * Then follow this process: * * (a) Include libc-compat.h in the UAPI header. * e.g. #include * This include must be as early as possible. * * (b) In libc-compat.h add enough code to detect that the comflicting * userspace libc header has been included first. * * (c) If the userspace libc header has been included first define a set of * guard macros of the form __UAPI_DEF_FOO and set their values to 1, else * set their values to 0. * * (d) Back in the UAPI header with the conflicting definitions, guard the * definitions with: * #if __UAPI_DEF_FOO * ... * #endif * * This fixes the situation where the linux headers are included *after* the * libc headers. To fix the problem with the inclusion in the other order the * userspace libc headers must be fixed like this: * * * For all definitions that conflict with kernel definitions wrap those * defines in the following: * #if !__UAPI_DEF_FOO * ... * #endif * * This prevents the redefinition of a construct already defined by the kernel. */ #ifndef _LIBC_COMPAT_H #define _LIBC_COMPAT_H /* We have included glibc headers... */ #if defined(__GLIBC__) /* Coordinate with glibc net/if.h header. */ #if defined(_NET_IF_H) && defined(__USE_MISC) /* GLIBC headers included first so don't define anything * that would already be defined. */ #define __UAPI_DEF_IF_IFCONF 0 #define __UAPI_DEF_IF_IFMAP 0 #define __UAPI_DEF_IF_IFNAMSIZ 0 #define __UAPI_DEF_IF_IFREQ 0 /* Everything up to IFF_DYNAMIC, matches net/if.h until glibc 2.23 */ #define __UAPI_DEF_IF_NET_DEVICE_FLAGS 0 /* For the future if glibc adds IFF_LOWER_UP, IFF_DORMANT and IFF_ECHO */ #ifndef __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO #define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 1 #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO */ #else /* _NET_IF_H */ /* Linux headers included first, and we must define everything * we need. The expectation is that glibc will check the * __UAPI_DEF_* defines and adjust appropriately. */ #define __UAPI_DEF_IF_IFCONF 1 #define __UAPI_DEF_IF_IFMAP 1 #define __UAPI_DEF_IF_IFNAMSIZ 1 #define __UAPI_DEF_IF_IFREQ 1 /* Everything up to IFF_DYNAMIC, matches net/if.h until glibc 2.23 */ #define __UAPI_DEF_IF_NET_DEVICE_FLAGS 1 /* For the future if glibc adds IFF_LOWER_UP, IFF_DORMANT and IFF_ECHO */ #define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 1 #endif /* _NET_IF_H */ /* Coordinate with glibc netinet/in.h header. */ #if defined(_NETINET_IN_H) /* GLIBC headers included first so don't define anything * that would already be defined. */ #define __UAPI_DEF_IN_ADDR 0 #define __UAPI_DEF_IN_IPPROTO 0 #define __UAPI_DEF_IN_PKTINFO 0 #define __UAPI_DEF_IP_MREQ 0 #define __UAPI_DEF_SOCKADDR_IN 0 #define __UAPI_DEF_IN_CLASS 0 #define __UAPI_DEF_IN6_ADDR 0 /* The exception is the in6_addr macros which must be defined * if the glibc code didn't define them. This guard matches * the guard in glibc/inet/netinet/in.h which defines the * additional in6_addr macros e.g. s6_addr16, and s6_addr32. */ #if defined(__USE_MISC) || defined (__USE_GNU) #define __UAPI_DEF_IN6_ADDR_ALT 0 #else #define __UAPI_DEF_IN6_ADDR_ALT 1 #endif #define __UAPI_DEF_SOCKADDR_IN6 0 #define __UAPI_DEF_IPV6_MREQ 0 #define __UAPI_DEF_IPPROTO_V6 0 #define __UAPI_DEF_IPV6_OPTIONS 0 #define __UAPI_DEF_IN6_PKTINFO 0 #define __UAPI_DEF_IP6_MTUINFO 0 #else /* Linux headers included first, and we must define everything * we need. The expectation is that glibc will check the * __UAPI_DEF_* defines and adjust appropriately. */ #define __UAPI_DEF_IN_ADDR 1 #define __UAPI_DEF_IN_IPPROTO 1 #define __UAPI_DEF_IN_PKTINFO 1 #define __UAPI_DEF_IP_MREQ 1 #define __UAPI_DEF_SOCKADDR_IN 1 #define __UAPI_DEF_IN_CLASS 1 #define __UAPI_DEF_IN6_ADDR 1 /* We unconditionally define the in6_addr macros and glibc must * coordinate. */ #define __UAPI_DEF_IN6_ADDR_ALT 1 #define __UAPI_DEF_SOCKADDR_IN6 1 #define __UAPI_DEF_IPV6_MREQ 1 #define __UAPI_DEF_IPPROTO_V6 1 #define __UAPI_DEF_IPV6_OPTIONS 1 #define __UAPI_DEF_IN6_PKTINFO 1 #define __UAPI_DEF_IP6_MTUINFO 1 #endif /* _NETINET_IN_H */ /* Coordinate with glibc netipx/ipx.h header. */ #if defined(__NETIPX_IPX_H) #define __UAPI_DEF_SOCKADDR_IPX 0 #define __UAPI_DEF_IPX_ROUTE_DEFINITION 0 #define __UAPI_DEF_IPX_INTERFACE_DEFINITION 0 #define __UAPI_DEF_IPX_CONFIG_DATA 0 #define __UAPI_DEF_IPX_ROUTE_DEF 0 #else /* defined(__NETIPX_IPX_H) */ #define __UAPI_DEF_SOCKADDR_IPX 1 #define __UAPI_DEF_IPX_ROUTE_DEFINITION 1 #define __UAPI_DEF_IPX_INTERFACE_DEFINITION 1 #define __UAPI_DEF_IPX_CONFIG_DATA 1 #define __UAPI_DEF_IPX_ROUTE_DEF 1 #endif /* defined(__NETIPX_IPX_H) */ /* Definitions for xattr.h */ #if defined(_SYS_XATTR_H) #define __UAPI_DEF_XATTR 0 #else #define __UAPI_DEF_XATTR 1 #endif /* If we did not see any headers from any supported C libraries, * or we are being included in the kernel, then define everything * that we need. Check for previous __UAPI_* definitions to give * unsupported C libraries a way to opt out of any kernel definition. */ #else /* !defined(__GLIBC__) */ /* Definitions for if.h */ #ifndef __UAPI_DEF_IF_IFCONF #define __UAPI_DEF_IF_IFCONF 1 #endif #ifndef __UAPI_DEF_IF_IFMAP #define __UAPI_DEF_IF_IFMAP 1 #endif #ifndef __UAPI_DEF_IF_IFNAMSIZ #define __UAPI_DEF_IF_IFNAMSIZ 1 #endif #ifndef __UAPI_DEF_IF_IFREQ #define __UAPI_DEF_IF_IFREQ 1 #endif /* Everything up to IFF_DYNAMIC, matches net/if.h until glibc 2.23 */ #ifndef __UAPI_DEF_IF_NET_DEVICE_FLAGS #define __UAPI_DEF_IF_NET_DEVICE_FLAGS 1 #endif /* For the future if glibc adds IFF_LOWER_UP, IFF_DORMANT and IFF_ECHO */ #ifndef __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO #define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 1 #endif /* Definitions for in.h */ #ifndef __UAPI_DEF_IN_ADDR #define __UAPI_DEF_IN_ADDR 1 #endif #ifndef __UAPI_DEF_IN_IPPROTO #define __UAPI_DEF_IN_IPPROTO 1 #endif #ifndef __UAPI_DEF_IN_PKTINFO #define __UAPI_DEF_IN_PKTINFO 1 #endif #ifndef __UAPI_DEF_IP_MREQ #define __UAPI_DEF_IP_MREQ 1 #endif #ifndef __UAPI_DEF_SOCKADDR_IN #define __UAPI_DEF_SOCKADDR_IN 1 #endif #ifndef __UAPI_DEF_IN_CLASS #define __UAPI_DEF_IN_CLASS 1 #endif /* Definitions for in6.h */ #ifndef __UAPI_DEF_IN6_ADDR #define __UAPI_DEF_IN6_ADDR 1 #endif #ifndef __UAPI_DEF_IN6_ADDR_ALT #define __UAPI_DEF_IN6_ADDR_ALT 1 #endif #ifndef __UAPI_DEF_SOCKADDR_IN6 #define __UAPI_DEF_SOCKADDR_IN6 1 #endif #ifndef __UAPI_DEF_IPV6_MREQ #define __UAPI_DEF_IPV6_MREQ 1 #endif #ifndef __UAPI_DEF_IPPROTO_V6 #define __UAPI_DEF_IPPROTO_V6 1 #endif #ifndef __UAPI_DEF_IPV6_OPTIONS #define __UAPI_DEF_IPV6_OPTIONS 1 #endif #ifndef __UAPI_DEF_IN6_PKTINFO #define __UAPI_DEF_IN6_PKTINFO 1 #endif #ifndef __UAPI_DEF_IP6_MTUINFO #define __UAPI_DEF_IP6_MTUINFO 1 #endif /* Definitions for ipx.h */ #ifndef __UAPI_DEF_SOCKADDR_IPX #define __UAPI_DEF_SOCKADDR_IPX 1 #endif #ifndef __UAPI_DEF_IPX_ROUTE_DEFINITION #define __UAPI_DEF_IPX_ROUTE_DEFINITION 1 #endif #ifndef __UAPI_DEF_IPX_INTERFACE_DEFINITION #define __UAPI_DEF_IPX_INTERFACE_DEFINITION 1 #endif #ifndef __UAPI_DEF_IPX_CONFIG_DATA #define __UAPI_DEF_IPX_CONFIG_DATA 1 #endif #ifndef __UAPI_DEF_IPX_ROUTE_DEF #define __UAPI_DEF_IPX_ROUTE_DEF 1 #endif /* Definitions for xattr.h */ #ifndef __UAPI_DEF_XATTR #define __UAPI_DEF_XATTR 1 #endif #endif /* __GLIBC__ */ #endif /* _LIBC_COMPAT_H */ linux/neighbour.h000064400000012022151027430560010036 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_NEIGHBOUR_H #define __LINUX_NEIGHBOUR_H #include #include struct ndmsg { __u8 ndm_family; __u8 ndm_pad1; __u16 ndm_pad2; __s32 ndm_ifindex; __u16 ndm_state; __u8 ndm_flags; __u8 ndm_type; }; enum { NDA_UNSPEC, NDA_DST, NDA_LLADDR, NDA_CACHEINFO, NDA_PROBES, NDA_VLAN, NDA_PORT, NDA_VNI, NDA_IFINDEX, NDA_MASTER, NDA_LINK_NETNSID, NDA_SRC_VNI, NDA_PROTOCOL, /* Originator of entry */ __RH_RESERVED_NDA_NH_ID, NDA_FDB_EXT_ATTRS, __NDA_MAX }; #define NDA_MAX (__NDA_MAX - 1) /* * Neighbor Cache Entry Flags */ #define NTF_USE 0x01 #define NTF_SELF 0x02 #define NTF_MASTER 0x04 #define NTF_PROXY 0x08 /* == ATF_PUBL */ #define NTF_EXT_LEARNED 0x10 #define NTF_OFFLOADED 0x20 #define NTF_STICKY 0x40 #define NTF_ROUTER 0x80 /* * Neighbor Cache Entry States. */ #define NUD_INCOMPLETE 0x01 #define NUD_REACHABLE 0x02 #define NUD_STALE 0x04 #define NUD_DELAY 0x08 #define NUD_PROBE 0x10 #define NUD_FAILED 0x20 /* Dummy states */ #define NUD_NOARP 0x40 #define NUD_PERMANENT 0x80 #define NUD_NONE 0x00 /* NUD_NOARP & NUD_PERMANENT are pseudostates, they never change * and make no address resolution or NUD. * NUD_PERMANENT also cannot be deleted by garbage collectors. * When NTF_EXT_LEARNED is set for a bridge fdb entry the different cache entry * states don't make sense and thus are ignored. Such entries don't age and * can roam. */ struct nda_cacheinfo { __u32 ndm_confirmed; __u32 ndm_used; __u32 ndm_updated; __u32 ndm_refcnt; }; /***************************************************************** * Neighbour tables specific messages. * * To retrieve the neighbour tables send RTM_GETNEIGHTBL with the * NLM_F_DUMP flag set. Every neighbour table configuration is * spread over multiple messages to avoid running into message * size limits on systems with many interfaces. The first message * in the sequence transports all not device specific data such as * statistics, configuration, and the default parameter set. * This message is followed by 0..n messages carrying device * specific parameter sets. * Although the ordering should be sufficient, NDTA_NAME can be * used to identify sequences. The initial message can be identified * by checking for NDTA_CONFIG. The device specific messages do * not contain this TLV but have NDTPA_IFINDEX set to the * corresponding interface index. * * To change neighbour table attributes, send RTM_SETNEIGHTBL * with NDTA_NAME set. Changeable attribute include NDTA_THRESH[1-3], * NDTA_GC_INTERVAL, and all TLVs in NDTA_PARMS unless marked * otherwise. Device specific parameter sets can be changed by * setting NDTPA_IFINDEX to the interface index of the corresponding * device. ****/ struct ndt_stats { __u64 ndts_allocs; __u64 ndts_destroys; __u64 ndts_hash_grows; __u64 ndts_res_failed; __u64 ndts_lookups; __u64 ndts_hits; __u64 ndts_rcv_probes_mcast; __u64 ndts_rcv_probes_ucast; __u64 ndts_periodic_gc_runs; __u64 ndts_forced_gc_runs; __u64 ndts_table_fulls; }; enum { NDTPA_UNSPEC, NDTPA_IFINDEX, /* u32, unchangeable */ NDTPA_REFCNT, /* u32, read-only */ NDTPA_REACHABLE_TIME, /* u64, read-only, msecs */ NDTPA_BASE_REACHABLE_TIME, /* u64, msecs */ NDTPA_RETRANS_TIME, /* u64, msecs */ NDTPA_GC_STALETIME, /* u64, msecs */ NDTPA_DELAY_PROBE_TIME, /* u64, msecs */ NDTPA_QUEUE_LEN, /* u32 */ NDTPA_APP_PROBES, /* u32 */ NDTPA_UCAST_PROBES, /* u32 */ NDTPA_MCAST_PROBES, /* u32 */ NDTPA_ANYCAST_DELAY, /* u64, msecs */ NDTPA_PROXY_DELAY, /* u64, msecs */ NDTPA_PROXY_QLEN, /* u32 */ NDTPA_LOCKTIME, /* u64, msecs */ NDTPA_QUEUE_LENBYTES, /* u32 */ NDTPA_MCAST_REPROBES, /* u32 */ NDTPA_PAD, __NDTPA_MAX }; #define NDTPA_MAX (__NDTPA_MAX - 1) struct ndtmsg { __u8 ndtm_family; __u8 ndtm_pad1; __u16 ndtm_pad2; }; struct ndt_config { __u16 ndtc_key_len; __u16 ndtc_entry_size; __u32 ndtc_entries; __u32 ndtc_last_flush; /* delta to now in msecs */ __u32 ndtc_last_rand; /* delta to now in msecs */ __u32 ndtc_hash_rnd; __u32 ndtc_hash_mask; __u32 ndtc_hash_chain_gc; __u32 ndtc_proxy_qlen; }; enum { NDTA_UNSPEC, NDTA_NAME, /* char *, unchangeable */ NDTA_THRESH1, /* u32 */ NDTA_THRESH2, /* u32 */ NDTA_THRESH3, /* u32 */ NDTA_CONFIG, /* struct ndt_config, read-only */ NDTA_PARMS, /* nested TLV NDTPA_* */ NDTA_STATS, /* struct ndt_stats, read-only */ NDTA_GC_INTERVAL, /* u64, msecs */ NDTA_PAD, __NDTA_MAX }; #define NDTA_MAX (__NDTA_MAX - 1) /* FDB activity notification bits used in NFEA_ACTIVITY_NOTIFY: * - FDB_NOTIFY_BIT - notify on activity/expire for any entry * - FDB_NOTIFY_INACTIVE_BIT - mark as inactive to avoid multiple notifications */ enum { FDB_NOTIFY_BIT = (1 << 0), FDB_NOTIFY_INACTIVE_BIT = (1 << 1) }; /* embedded into NDA_FDB_EXT_ATTRS: * [NDA_FDB_EXT_ATTRS] = { * [NFEA_ACTIVITY_NOTIFY] * ... * } */ enum { NFEA_UNSPEC, NFEA_ACTIVITY_NOTIFY, NFEA_DONT_REFRESH, __NFEA_MAX }; #define NFEA_MAX (__NFEA_MAX - 1) #endif linux/vbox_err.h000064400000016131151027430560007707 0ustar00/* SPDX-License-Identifier: MIT */ /* Copyright (C) 2017 Oracle Corporation */ #ifndef __UAPI_VBOX_ERR_H__ #define __UAPI_VBOX_ERR_H__ #define VINF_SUCCESS 0 #define VERR_GENERAL_FAILURE (-1) #define VERR_INVALID_PARAMETER (-2) #define VERR_INVALID_MAGIC (-3) #define VERR_INVALID_HANDLE (-4) #define VERR_LOCK_FAILED (-5) #define VERR_INVALID_POINTER (-6) #define VERR_IDT_FAILED (-7) #define VERR_NO_MEMORY (-8) #define VERR_ALREADY_LOADED (-9) #define VERR_PERMISSION_DENIED (-10) #define VERR_VERSION_MISMATCH (-11) #define VERR_NOT_IMPLEMENTED (-12) #define VERR_INVALID_FLAGS (-13) #define VERR_NOT_EQUAL (-18) #define VERR_NOT_SYMLINK (-19) #define VERR_NO_TMP_MEMORY (-20) #define VERR_INVALID_FMODE (-21) #define VERR_WRONG_ORDER (-22) #define VERR_NO_TLS_FOR_SELF (-23) #define VERR_FAILED_TO_SET_SELF_TLS (-24) #define VERR_NO_CONT_MEMORY (-26) #define VERR_NO_PAGE_MEMORY (-27) #define VERR_THREAD_IS_DEAD (-29) #define VERR_THREAD_NOT_WAITABLE (-30) #define VERR_PAGE_TABLE_NOT_PRESENT (-31) #define VERR_INVALID_CONTEXT (-32) #define VERR_TIMER_BUSY (-33) #define VERR_ADDRESS_CONFLICT (-34) #define VERR_UNRESOLVED_ERROR (-35) #define VERR_INVALID_FUNCTION (-36) #define VERR_NOT_SUPPORTED (-37) #define VERR_ACCESS_DENIED (-38) #define VERR_INTERRUPTED (-39) #define VERR_TIMEOUT (-40) #define VERR_BUFFER_OVERFLOW (-41) #define VERR_TOO_MUCH_DATA (-42) #define VERR_MAX_THRDS_REACHED (-43) #define VERR_MAX_PROCS_REACHED (-44) #define VERR_SIGNAL_REFUSED (-45) #define VERR_SIGNAL_PENDING (-46) #define VERR_SIGNAL_INVALID (-47) #define VERR_STATE_CHANGED (-48) #define VERR_INVALID_UUID_FORMAT (-49) #define VERR_PROCESS_NOT_FOUND (-50) #define VERR_PROCESS_RUNNING (-51) #define VERR_TRY_AGAIN (-52) #define VERR_PARSE_ERROR (-53) #define VERR_OUT_OF_RANGE (-54) #define VERR_NUMBER_TOO_BIG (-55) #define VERR_NO_DIGITS (-56) #define VERR_NEGATIVE_UNSIGNED (-57) #define VERR_NO_TRANSLATION (-58) #define VERR_NOT_FOUND (-78) #define VERR_INVALID_STATE (-79) #define VERR_OUT_OF_RESOURCES (-80) #define VERR_FILE_NOT_FOUND (-102) #define VERR_PATH_NOT_FOUND (-103) #define VERR_INVALID_NAME (-104) #define VERR_ALREADY_EXISTS (-105) #define VERR_TOO_MANY_OPEN_FILES (-106) #define VERR_SEEK (-107) #define VERR_NEGATIVE_SEEK (-108) #define VERR_SEEK_ON_DEVICE (-109) #define VERR_EOF (-110) #define VERR_READ_ERROR (-111) #define VERR_WRITE_ERROR (-112) #define VERR_WRITE_PROTECT (-113) #define VERR_SHARING_VIOLATION (-114) #define VERR_FILE_LOCK_FAILED (-115) #define VERR_FILE_LOCK_VIOLATION (-116) #define VERR_CANT_CREATE (-117) #define VERR_CANT_DELETE_DIRECTORY (-118) #define VERR_NOT_SAME_DEVICE (-119) #define VERR_FILENAME_TOO_LONG (-120) #define VERR_MEDIA_NOT_PRESENT (-121) #define VERR_MEDIA_NOT_RECOGNIZED (-122) #define VERR_FILE_NOT_LOCKED (-123) #define VERR_FILE_LOCK_LOST (-124) #define VERR_DIR_NOT_EMPTY (-125) #define VERR_NOT_A_DIRECTORY (-126) #define VERR_IS_A_DIRECTORY (-127) #define VERR_FILE_TOO_BIG (-128) #define VERR_NET_IO_ERROR (-400) #define VERR_NET_OUT_OF_RESOURCES (-401) #define VERR_NET_HOST_NOT_FOUND (-402) #define VERR_NET_PATH_NOT_FOUND (-403) #define VERR_NET_PRINT_ERROR (-404) #define VERR_NET_NO_NETWORK (-405) #define VERR_NET_NOT_UNIQUE_NAME (-406) #define VERR_NET_IN_PROGRESS (-436) #define VERR_NET_ALREADY_IN_PROGRESS (-437) #define VERR_NET_NOT_SOCKET (-438) #define VERR_NET_DEST_ADDRESS_REQUIRED (-439) #define VERR_NET_MSG_SIZE (-440) #define VERR_NET_PROTOCOL_TYPE (-441) #define VERR_NET_PROTOCOL_NOT_AVAILABLE (-442) #define VERR_NET_PROTOCOL_NOT_SUPPORTED (-443) #define VERR_NET_SOCKET_TYPE_NOT_SUPPORTED (-444) #define VERR_NET_OPERATION_NOT_SUPPORTED (-445) #define VERR_NET_PROTOCOL_FAMILY_NOT_SUPPORTED (-446) #define VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED (-447) #define VERR_NET_ADDRESS_IN_USE (-448) #define VERR_NET_ADDRESS_NOT_AVAILABLE (-449) #define VERR_NET_DOWN (-450) #define VERR_NET_UNREACHABLE (-451) #define VERR_NET_CONNECTION_RESET (-452) #define VERR_NET_CONNECTION_ABORTED (-453) #define VERR_NET_CONNECTION_RESET_BY_PEER (-454) #define VERR_NET_NO_BUFFER_SPACE (-455) #define VERR_NET_ALREADY_CONNECTED (-456) #define VERR_NET_NOT_CONNECTED (-457) #define VERR_NET_SHUTDOWN (-458) #define VERR_NET_TOO_MANY_REFERENCES (-459) #define VERR_NET_CONNECTION_TIMED_OUT (-460) #define VERR_NET_CONNECTION_REFUSED (-461) #define VERR_NET_HOST_DOWN (-464) #define VERR_NET_HOST_UNREACHABLE (-465) #define VERR_NET_PROTOCOL_ERROR (-466) #define VERR_NET_INCOMPLETE_TX_PACKET (-467) /* misc. unsorted codes */ #define VERR_RESOURCE_BUSY (-138) #define VERR_DISK_FULL (-152) #define VERR_TOO_MANY_SYMLINKS (-156) #define VERR_NO_MORE_FILES (-201) #define VERR_INTERNAL_ERROR (-225) #define VERR_INTERNAL_ERROR_2 (-226) #define VERR_INTERNAL_ERROR_3 (-227) #define VERR_INTERNAL_ERROR_4 (-228) #define VERR_DEV_IO_ERROR (-250) #define VERR_IO_BAD_LENGTH (-255) #define VERR_BROKEN_PIPE (-301) #define VERR_NO_DATA (-304) #define VERR_SEM_DESTROYED (-363) #define VERR_DEADLOCK (-365) #define VERR_BAD_EXE_FORMAT (-608) #define VINF_HGCM_ASYNC_EXECUTE (2903) #endif linux/kvm_para.h000064400000001751151027430560007663 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_KVM_PARA_H #define __LINUX_KVM_PARA_H /* * This header file provides a method for making a hypercall to the host * Architectures should define: * - kvm_hypercall0, kvm_hypercall1... * - kvm_arch_para_features * - kvm_para_available */ /* Return values for hypercalls */ #define KVM_ENOSYS 1000 #define KVM_EFAULT EFAULT #define KVM_EINVAL EINVAL #define KVM_E2BIG E2BIG #define KVM_EPERM EPERM #define KVM_EOPNOTSUPP 95 #define KVM_HC_VAPIC_POLL_IRQ 1 #define KVM_HC_MMU_OP 2 #define KVM_HC_FEATURES 3 #define KVM_HC_PPC_MAP_MAGIC_PAGE 4 #define KVM_HC_KICK_CPU 5 #define KVM_HC_MIPS_GET_CLOCK_FREQ 6 #define KVM_HC_MIPS_EXIT_VM 7 #define KVM_HC_MIPS_CONSOLE_OUTPUT 8 #define KVM_HC_CLOCK_PAIRING 9 #define KVM_HC_SEND_IPI 10 #define KVM_HC_SCHED_YIELD 11 #define KVM_HC_MAP_GPA_RANGE 12 /* * hypercalls use architecture specific */ #include #endif /* __LINUX_KVM_PARA_H */ linux/netdevice.h000064400000004315151027430560010030 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the Interfaces handler. * * Version: @(#)dev.h 1.0.10 08/12/93 * * Authors: Ross Biro * Fred N. van Kempen, * Corey Minyard * Donald J. Becker, * Alan Cox, * Bjorn Ekwall. * Pekka Riikonen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Moved to /usr/include/linux for NET3 */ #ifndef _LINUX_NETDEVICE_H #define _LINUX_NETDEVICE_H #include #include #include #include #define MAX_ADDR_LEN 32 /* Largest hardware address length */ /* Initial net device group. All devices belong to group 0 by default. */ #define INIT_NETDEV_GROUP 0 /* interface name assignment types (sysfs name_assign_type attribute) */ #define NET_NAME_UNKNOWN 0 /* unknown origin (not exposed to userspace) */ #define NET_NAME_ENUM 1 /* enumerated by kernel */ #define NET_NAME_PREDICTABLE 2 /* predictably named by the kernel */ #define NET_NAME_USER 3 /* provided by user-space */ #define NET_NAME_RENAMED 4 /* renamed by user-space */ /* Media selection options. */ enum { IF_PORT_UNKNOWN = 0, IF_PORT_10BASE2, IF_PORT_10BASET, IF_PORT_AUI, IF_PORT_100BASET, IF_PORT_100BASETX, IF_PORT_100BASEFX }; /* hardware address assignment types */ #define NET_ADDR_PERM 0 /* address is permanent (default) */ #define NET_ADDR_RANDOM 1 /* address is generated randomly */ #define NET_ADDR_STOLEN 2 /* address is stolen from other device */ #define NET_ADDR_SET 3 /* address is set using * dev_set_mac_address() */ #endif /* _LINUX_NETDEVICE_H */ linux/atmppp.h000064400000001177151027430560007366 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmppp.h - RFC2364 PPPoATM */ /* Written 2000 by Mitchell Blank Jr */ #ifndef _LINUX_ATMPPP_H #define _LINUX_ATMPPP_H #include #define PPPOATM_ENCAPS_AUTODETECT (0) #define PPPOATM_ENCAPS_VC (1) #define PPPOATM_ENCAPS_LLC (2) /* * This is for the ATM_SETBACKEND call - these are like socket families: * the first element of the structure is the backend number and the rest * is per-backend specific */ struct atm_backend_ppp { atm_backend_t backend_num; /* ATM_BACKEND_PPP */ int encaps; /* PPPOATM_ENCAPS_* */ }; #endif /* _LINUX_ATMPPP_H */ linux/bcache.h000064400000020256151027430560007271 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_BCACHE_H #define _LINUX_BCACHE_H /* * Bcache on disk data structures */ #include #define BITMASK(name, type, field, offset, size) \ static __inline__ __u64 name(const type *k) \ { return (k->field >> offset) & ~(~0ULL << size); } \ \ static __inline__ void SET_##name(type *k, __u64 v) \ { \ k->field &= ~(~(~0ULL << size) << offset); \ k->field |= (v & ~(~0ULL << size)) << offset; \ } /* Btree keys - all units are in sectors */ struct bkey { __u64 high; __u64 low; __u64 ptr[]; }; #define KEY_FIELD(name, field, offset, size) \ BITMASK(name, struct bkey, field, offset, size) #define PTR_FIELD(name, offset, size) \ static __inline__ __u64 name(const struct bkey *k, unsigned i) \ { return (k->ptr[i] >> offset) & ~(~0ULL << size); } \ \ static __inline__ void SET_##name(struct bkey *k, unsigned i, __u64 v) \ { \ k->ptr[i] &= ~(~(~0ULL << size) << offset); \ k->ptr[i] |= (v & ~(~0ULL << size)) << offset; \ } #define KEY_SIZE_BITS 16 #define KEY_MAX_U64S 8 KEY_FIELD(KEY_PTRS, high, 60, 3) KEY_FIELD(HEADER_SIZE, high, 58, 2) KEY_FIELD(KEY_CSUM, high, 56, 2) KEY_FIELD(KEY_PINNED, high, 55, 1) KEY_FIELD(KEY_DIRTY, high, 36, 1) KEY_FIELD(KEY_SIZE, high, 20, KEY_SIZE_BITS) KEY_FIELD(KEY_INODE, high, 0, 20) /* Next time I change the on disk format, KEY_OFFSET() won't be 64 bits */ static __inline__ __u64 KEY_OFFSET(const struct bkey *k) { return k->low; } static __inline__ void SET_KEY_OFFSET(struct bkey *k, __u64 v) { k->low = v; } /* * The high bit being set is a relic from when we used it to do binary * searches - it told you where a key started. It's not used anymore, * and can probably be safely dropped. */ #define KEY(inode, offset, size) \ ((struct bkey) { \ .high = (1ULL << 63) | ((__u64) (size) << 20) | (inode), \ .low = (offset) \ }) #define ZERO_KEY KEY(0, 0, 0) #define MAX_KEY_INODE (~(~0 << 20)) #define MAX_KEY_OFFSET (~0ULL >> 1) #define MAX_KEY KEY(MAX_KEY_INODE, MAX_KEY_OFFSET, 0) #define KEY_START(k) (KEY_OFFSET(k) - KEY_SIZE(k)) #define START_KEY(k) KEY(KEY_INODE(k), KEY_START(k), 0) #define PTR_DEV_BITS 12 PTR_FIELD(PTR_DEV, 51, PTR_DEV_BITS) PTR_FIELD(PTR_OFFSET, 8, 43) PTR_FIELD(PTR_GEN, 0, 8) #define PTR_CHECK_DEV ((1 << PTR_DEV_BITS) - 1) #define MAKE_PTR(gen, offset, dev) \ ((((__u64) dev) << 51) | ((__u64) offset) << 8 | gen) /* Bkey utility code */ static __inline__ unsigned long bkey_u64s(const struct bkey *k) { return (sizeof(struct bkey) / sizeof(__u64)) + KEY_PTRS(k); } static __inline__ unsigned long bkey_bytes(const struct bkey *k) { return bkey_u64s(k) * sizeof(__u64); } #define bkey_copy(_dest, _src) memcpy(_dest, _src, bkey_bytes(_src)) static __inline__ void bkey_copy_key(struct bkey *dest, const struct bkey *src) { SET_KEY_INODE(dest, KEY_INODE(src)); SET_KEY_OFFSET(dest, KEY_OFFSET(src)); } static __inline__ struct bkey *bkey_next(const struct bkey *k) { __u64 *d = (void *) k; return (struct bkey *) (d + bkey_u64s(k)); } static __inline__ struct bkey *bkey_idx(const struct bkey *k, unsigned nr_keys) { __u64 *d = (void *) k; return (struct bkey *) (d + nr_keys); } /* Enough for a key with 6 pointers */ #define BKEY_PAD 8 #define BKEY_PADDED(key) \ union { struct bkey key; __u64 key ## _pad[BKEY_PAD]; } /* Superblock */ /* Version 0: Cache device * Version 1: Backing device * Version 2: Seed pointer into btree node checksum * Version 3: Cache device with new UUID format * Version 4: Backing device with data offset */ #define BCACHE_SB_VERSION_CDEV 0 #define BCACHE_SB_VERSION_BDEV 1 #define BCACHE_SB_VERSION_CDEV_WITH_UUID 3 #define BCACHE_SB_VERSION_BDEV_WITH_OFFSET 4 #define BCACHE_SB_MAX_VERSION 4 #define SB_SECTOR 8 #define SB_SIZE 4096 #define SB_LABEL_SIZE 32 #define SB_JOURNAL_BUCKETS 256U /* SB_JOURNAL_BUCKETS must be divisible by BITS_PER_LONG */ #define MAX_CACHES_PER_SET 8 #define BDEV_DATA_START_DEFAULT 16 /* sectors */ struct cache_sb { __u64 csum; __u64 offset; /* sector where this sb was written */ __u64 version; __u8 magic[16]; __u8 uuid[16]; union { __u8 set_uuid[16]; __u64 set_magic; }; __u8 label[SB_LABEL_SIZE]; __u64 flags; __u64 seq; __u64 pad[8]; union { struct { /* Cache devices */ __u64 nbuckets; /* device size */ __u16 block_size; /* sectors */ __u16 bucket_size; /* sectors */ __u16 nr_in_set; __u16 nr_this_dev; }; struct { /* Backing devices */ __u64 data_offset; /* * block_size from the cache device section is still used by * backing devices, so don't add anything here until we fix * things to not need it for backing devices anymore */ }; }; __u32 last_mount; /* time_t */ __u16 first_bucket; union { __u16 njournal_buckets; __u16 keys; }; __u64 d[SB_JOURNAL_BUCKETS]; /* journal buckets */ }; static __inline__ _Bool SB_IS_BDEV(const struct cache_sb *sb) { return sb->version == BCACHE_SB_VERSION_BDEV || sb->version == BCACHE_SB_VERSION_BDEV_WITH_OFFSET; } BITMASK(CACHE_SYNC, struct cache_sb, flags, 0, 1); BITMASK(CACHE_DISCARD, struct cache_sb, flags, 1, 1); BITMASK(CACHE_REPLACEMENT, struct cache_sb, flags, 2, 3); #define CACHE_REPLACEMENT_LRU 0U #define CACHE_REPLACEMENT_FIFO 1U #define CACHE_REPLACEMENT_RANDOM 2U BITMASK(BDEV_CACHE_MODE, struct cache_sb, flags, 0, 4); #define CACHE_MODE_WRITETHROUGH 0U #define CACHE_MODE_WRITEBACK 1U #define CACHE_MODE_WRITEAROUND 2U #define CACHE_MODE_NONE 3U BITMASK(BDEV_STATE, struct cache_sb, flags, 61, 2); #define BDEV_STATE_NONE 0U #define BDEV_STATE_CLEAN 1U #define BDEV_STATE_DIRTY 2U #define BDEV_STATE_STALE 3U /* * Magic numbers * * The various other data structures have their own magic numbers, which are * xored with the first part of the cache set's UUID */ #define JSET_MAGIC 0x245235c1a3625032ULL #define PSET_MAGIC 0x6750e15f87337f91ULL #define BSET_MAGIC 0x90135c78b99e07f5ULL static __inline__ __u64 jset_magic(struct cache_sb *sb) { return sb->set_magic ^ JSET_MAGIC; } static __inline__ __u64 pset_magic(struct cache_sb *sb) { return sb->set_magic ^ PSET_MAGIC; } static __inline__ __u64 bset_magic(struct cache_sb *sb) { return sb->set_magic ^ BSET_MAGIC; } /* * Journal * * On disk format for a journal entry: * seq is monotonically increasing; every journal entry has its own unique * sequence number. * * last_seq is the oldest journal entry that still has keys the btree hasn't * flushed to disk yet. * * version is for on disk format changes. */ #define BCACHE_JSET_VERSION_UUIDv1 1 #define BCACHE_JSET_VERSION_UUID 1 /* Always latest UUID format */ #define BCACHE_JSET_VERSION 1 struct jset { __u64 csum; __u64 magic; __u64 seq; __u32 version; __u32 keys; __u64 last_seq; BKEY_PADDED(uuid_bucket); BKEY_PADDED(btree_root); __u16 btree_level; __u16 pad[3]; __u64 prio_bucket[MAX_CACHES_PER_SET]; union { struct bkey start[0]; __u64 d[0]; }; }; /* Bucket prios/gens */ struct prio_set { __u64 csum; __u64 magic; __u64 seq; __u32 version; __u32 pad; __u64 next_bucket; struct bucket_disk { __u16 prio; __u8 gen; } __attribute((packed)) data[]; }; /* UUIDS - per backing device/flash only volume metadata */ struct uuid_entry { union { struct { __u8 uuid[16]; __u8 label[32]; __u32 first_reg; __u32 last_reg; __u32 invalidated; __u32 flags; /* Size of flash only volumes */ __u64 sectors; }; __u8 pad[128]; }; }; BITMASK(UUID_FLASH_ONLY, struct uuid_entry, flags, 0, 1); /* Btree nodes */ /* Version 1: Seed pointer into btree node checksum */ #define BCACHE_BSET_CSUM 1 #define BCACHE_BSET_VERSION 1 /* * Btree nodes * * On disk a btree node is a list/log of these; within each set the keys are * sorted */ struct bset { __u64 csum; __u64 magic; __u64 seq; __u32 version; __u32 keys; union { struct bkey start[0]; __u64 d[0]; }; }; /* OBSOLETE */ /* UUIDS - per backing device/flash only volume metadata */ struct uuid_entry_v0 { __u8 uuid[16]; __u8 label[32]; __u32 first_reg; __u32 last_reg; __u32 invalidated; __u32 pad; }; #endif /* _LINUX_BCACHE_H */ linux/vmcore.h000064400000000657151027430560007362 0ustar00/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _VMCORE_H #define _VMCORE_H #include #define VMCOREDD_NOTE_NAME "LINUX" #define VMCOREDD_MAX_NAME_BYTES 44 struct vmcoredd_header { __u32 n_namesz; /* Name size */ __u32 n_descsz; /* Content size */ __u32 n_type; /* NT_VMCOREDD */ __u8 name[8]; /* LINUX\0\0\0 */ __u8 dump_name[VMCOREDD_MAX_NAME_BYTES]; /* Device dump's name */ }; #endif /* _VMCORE_H */ linux/magic.h000064400000006713151027430560007146 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_MAGIC_H__ #define __LINUX_MAGIC_H__ #define ADFS_SUPER_MAGIC 0xadf5 #define AFFS_SUPER_MAGIC 0xadff #define AFS_SUPER_MAGIC 0x5346414F #define AUTOFS_SUPER_MAGIC 0x0187 #define CODA_SUPER_MAGIC 0x73757245 #define CRAMFS_MAGIC 0x28cd3d45 /* some random number */ #define CRAMFS_MAGIC_WEND 0x453dcd28 /* magic number with the wrong endianess */ #define DEBUGFS_MAGIC 0x64626720 #define SECURITYFS_MAGIC 0x73636673 #define SELINUX_MAGIC 0xf97cff8c #define SMACK_MAGIC 0x43415d53 /* "SMAC" */ #define RAMFS_MAGIC 0x858458f6 /* some random number */ #define TMPFS_MAGIC 0x01021994 #define HUGETLBFS_MAGIC 0x958458f6 /* some random number */ #define SQUASHFS_MAGIC 0x73717368 #define ECRYPTFS_SUPER_MAGIC 0xf15f #define EFS_SUPER_MAGIC 0x414A53 #define EXT2_SUPER_MAGIC 0xEF53 #define EXT3_SUPER_MAGIC 0xEF53 #define XENFS_SUPER_MAGIC 0xabba1974 #define EXT4_SUPER_MAGIC 0xEF53 #define BTRFS_SUPER_MAGIC 0x9123683E #define NILFS_SUPER_MAGIC 0x3434 #define F2FS_SUPER_MAGIC 0xF2F52010 #define HPFS_SUPER_MAGIC 0xf995e849 #define ISOFS_SUPER_MAGIC 0x9660 #define JFFS2_SUPER_MAGIC 0x72b6 #define XFS_SUPER_MAGIC 0x58465342 /* "XFSB" */ #define PSTOREFS_MAGIC 0x6165676C #define EFIVARFS_MAGIC 0xde5e81e4 #define HOSTFS_SUPER_MAGIC 0x00c0ffee #define OVERLAYFS_SUPER_MAGIC 0x794c7630 #define MINIX_SUPER_MAGIC 0x137F /* minix v1 fs, 14 char names */ #define MINIX_SUPER_MAGIC2 0x138F /* minix v1 fs, 30 char names */ #define MINIX2_SUPER_MAGIC 0x2468 /* minix v2 fs, 14 char names */ #define MINIX2_SUPER_MAGIC2 0x2478 /* minix v2 fs, 30 char names */ #define MINIX3_SUPER_MAGIC 0x4d5a /* minix v3 fs, 60 char names */ #define MSDOS_SUPER_MAGIC 0x4d44 /* MD */ #define NCP_SUPER_MAGIC 0x564c /* Guess, what 0x564c is :-) */ #define NFS_SUPER_MAGIC 0x6969 #define OCFS2_SUPER_MAGIC 0x7461636f #define OPENPROM_SUPER_MAGIC 0x9fa1 #define QNX4_SUPER_MAGIC 0x002f /* qnx4 fs detection */ #define QNX6_SUPER_MAGIC 0x68191122 /* qnx6 fs detection */ #define AFS_FS_MAGIC 0x6B414653 #define REISERFS_SUPER_MAGIC 0x52654973 /* used by gcc */ /* used by file system utilities that look at the superblock, etc. */ #define REISERFS_SUPER_MAGIC_STRING "ReIsErFs" #define REISER2FS_SUPER_MAGIC_STRING "ReIsEr2Fs" #define REISER2FS_JR_SUPER_MAGIC_STRING "ReIsEr3Fs" #define SMB_SUPER_MAGIC 0x517B #define CGROUP_SUPER_MAGIC 0x27e0eb #define CGROUP2_SUPER_MAGIC 0x63677270 #define RDTGROUP_SUPER_MAGIC 0x7655821 #define STACK_END_MAGIC 0x57AC6E9D #define TRACEFS_MAGIC 0x74726163 #define V9FS_MAGIC 0x01021997 #define BDEVFS_MAGIC 0x62646576 #define DAXFS_MAGIC 0x64646178 #define BINFMTFS_MAGIC 0x42494e4d #define DEVPTS_SUPER_MAGIC 0x1cd1 #define FUTEXFS_SUPER_MAGIC 0xBAD1DEA #define PIPEFS_MAGIC 0x50495045 #define PROC_SUPER_MAGIC 0x9fa0 #define SOCKFS_MAGIC 0x534F434B #define SYSFS_MAGIC 0x62656572 #define USBDEVICE_SUPER_MAGIC 0x9fa2 #define MTD_INODE_FS_MAGIC 0x11307854 #define ANON_INODE_FS_MAGIC 0x09041934 #define BTRFS_TEST_MAGIC 0x73727279 #define NSFS_MAGIC 0x6e736673 #define BPF_FS_MAGIC 0xcafe4a11 #define AAFS_MAGIC 0x5a3c69f0 /* Since UDF 2.01 is ISO 13346 based... */ #define UDF_SUPER_MAGIC 0x15013346 #define BALLOON_KVM_MAGIC 0x13661366 #define ZSMALLOC_MAGIC 0x58295829 #define DMA_BUF_MAGIC 0x444d4142 /* "DMAB" */ #define PPC_CMM_MAGIC 0xc7571590 #endif /* __LINUX_MAGIC_H__ */ linux/aspeed-lpc-ctrl.h000064400000003364151027430560011044 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright 2017 IBM Corp. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_ASPEED_LPC_CTRL_H #define _LINUX_ASPEED_LPC_CTRL_H #include #include /* Window types */ #define ASPEED_LPC_CTRL_WINDOW_FLASH 1 #define ASPEED_LPC_CTRL_WINDOW_MEMORY 2 /* * This driver provides a window for the host to access a BMC resource * across the BMC <-> Host LPC bus. * * window_type: The BMC resource that the host will access through the * window. BMC flash and BMC RAM. * * window_id: For each window type there may be multiple windows, * these are referenced by ID. * * flags: Reserved for future use, this field is expected to be * zeroed. * * addr: Address on the host LPC bus that the specified window should * be mapped. This address must be power of two aligned. * * offset: Offset into the BMC window that should be mapped to the * host (at addr). This must be a multiple of size. * * size: The size of the mapping. The smallest possible size is 64K. * This must be power of two aligned. * */ struct aspeed_lpc_ctrl_mapping { __u8 window_type; __u8 window_id; __u16 flags; __u32 addr; __u32 offset; __u32 size; }; #define __ASPEED_LPC_CTRL_IOCTL_MAGIC 0xb2 #define ASPEED_LPC_CTRL_IOCTL_GET_SIZE _IOWR(__ASPEED_LPC_CTRL_IOCTL_MAGIC, \ 0x00, struct aspeed_lpc_ctrl_mapping) #define ASPEED_LPC_CTRL_IOCTL_MAP _IOW(__ASPEED_LPC_CTRL_IOCTL_MAGIC, \ 0x01, struct aspeed_lpc_ctrl_mapping) #endif /* _LINUX_ASPEED_LPC_CTRL_H */ linux/kvm.h000064400000170171151027430560006663 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_KVM_H #define __LINUX_KVM_H /* * Userspace interface for /dev/kvm - kernel based virtual machine * * Note: you must update KVM_API_VERSION if you change this interface. */ #include #include #include #include #define KVM_API_VERSION 12 /* *** Deprecated interfaces *** */ #define KVM_TRC_SHIFT 16 #define KVM_TRC_ENTRYEXIT (1 << KVM_TRC_SHIFT) #define KVM_TRC_HANDLER (1 << (KVM_TRC_SHIFT + 1)) #define KVM_TRC_VMENTRY (KVM_TRC_ENTRYEXIT + 0x01) #define KVM_TRC_VMEXIT (KVM_TRC_ENTRYEXIT + 0x02) #define KVM_TRC_PAGE_FAULT (KVM_TRC_HANDLER + 0x01) #define KVM_TRC_HEAD_SIZE 12 #define KVM_TRC_CYCLE_SIZE 8 #define KVM_TRC_EXTRA_MAX 7 #define KVM_TRC_INJ_VIRQ (KVM_TRC_HANDLER + 0x02) #define KVM_TRC_REDELIVER_EVT (KVM_TRC_HANDLER + 0x03) #define KVM_TRC_PEND_INTR (KVM_TRC_HANDLER + 0x04) #define KVM_TRC_IO_READ (KVM_TRC_HANDLER + 0x05) #define KVM_TRC_IO_WRITE (KVM_TRC_HANDLER + 0x06) #define KVM_TRC_CR_READ (KVM_TRC_HANDLER + 0x07) #define KVM_TRC_CR_WRITE (KVM_TRC_HANDLER + 0x08) #define KVM_TRC_DR_READ (KVM_TRC_HANDLER + 0x09) #define KVM_TRC_DR_WRITE (KVM_TRC_HANDLER + 0x0A) #define KVM_TRC_MSR_READ (KVM_TRC_HANDLER + 0x0B) #define KVM_TRC_MSR_WRITE (KVM_TRC_HANDLER + 0x0C) #define KVM_TRC_CPUID (KVM_TRC_HANDLER + 0x0D) #define KVM_TRC_INTR (KVM_TRC_HANDLER + 0x0E) #define KVM_TRC_NMI (KVM_TRC_HANDLER + 0x0F) #define KVM_TRC_VMMCALL (KVM_TRC_HANDLER + 0x10) #define KVM_TRC_HLT (KVM_TRC_HANDLER + 0x11) #define KVM_TRC_CLTS (KVM_TRC_HANDLER + 0x12) #define KVM_TRC_LMSW (KVM_TRC_HANDLER + 0x13) #define KVM_TRC_APIC_ACCESS (KVM_TRC_HANDLER + 0x14) #define KVM_TRC_TDP_FAULT (KVM_TRC_HANDLER + 0x15) #define KVM_TRC_GTLB_WRITE (KVM_TRC_HANDLER + 0x16) #define KVM_TRC_STLB_WRITE (KVM_TRC_HANDLER + 0x17) #define KVM_TRC_STLB_INVAL (KVM_TRC_HANDLER + 0x18) #define KVM_TRC_PPC_INSTR (KVM_TRC_HANDLER + 0x19) struct kvm_user_trace_setup { __u32 buf_size; __u32 buf_nr; }; #define __KVM_DEPRECATED_MAIN_W_0x06 \ _IOW(KVMIO, 0x06, struct kvm_user_trace_setup) #define __KVM_DEPRECATED_MAIN_0x07 _IO(KVMIO, 0x07) #define __KVM_DEPRECATED_MAIN_0x08 _IO(KVMIO, 0x08) #define __KVM_DEPRECATED_VM_R_0x70 _IOR(KVMIO, 0x70, struct kvm_assigned_irq) struct kvm_breakpoint { __u32 enabled; __u32 padding; __u64 address; }; struct kvm_debug_guest { __u32 enabled; __u32 pad; struct kvm_breakpoint breakpoints[4]; __u32 singlestep; }; #define __KVM_DEPRECATED_VCPU_W_0x87 _IOW(KVMIO, 0x87, struct kvm_debug_guest) /* *** End of deprecated interfaces *** */ /* for KVM_CREATE_MEMORY_REGION */ struct kvm_memory_region { __u32 slot; __u32 flags; __u64 guest_phys_addr; __u64 memory_size; /* bytes */ }; /* for KVM_SET_USER_MEMORY_REGION */ struct kvm_userspace_memory_region { __u32 slot; __u32 flags; __u64 guest_phys_addr; __u64 memory_size; /* bytes */ __u64 userspace_addr; /* start of the userspace allocated memory */ }; /* * The bit 0 ~ bit 15 of kvm_memory_region::flags are visible for userspace, * other bits are reserved for kvm internal use which are defined in * include/linux/kvm_host.h. */ #define KVM_MEM_LOG_DIRTY_PAGES (1UL << 0) #define KVM_MEM_READONLY (1UL << 1) /* for KVM_IRQ_LINE */ struct kvm_irq_level { /* * ACPI gsi notion of irq. * For IA-64 (APIC model) IOAPIC0: irq 0-23; IOAPIC1: irq 24-47.. * For X86 (standard AT mode) PIC0/1: irq 0-15. IOAPIC0: 0-23.. * For ARM: See Documentation/virt/kvm/api.rst */ union { __u32 irq; __s32 status; }; __u32 level; }; struct kvm_irqchip { __u32 chip_id; __u32 pad; union { char dummy[512]; /* reserving space */ #ifdef __KVM_HAVE_PIT struct kvm_pic_state pic; #endif #ifdef __KVM_HAVE_IOAPIC struct kvm_ioapic_state ioapic; #endif } chip; }; /* for KVM_CREATE_PIT2 */ struct kvm_pit_config { __u32 flags; __u32 pad[15]; }; #define KVM_PIT_SPEAKER_DUMMY 1 struct kvm_s390_skeys { __u64 start_gfn; __u64 count; __u64 skeydata_addr; __u32 flags; __u32 reserved[9]; }; #define KVM_S390_CMMA_PEEK (1 << 0) /** * kvm_s390_cmma_log - Used for CMMA migration. * * Used both for input and output. * * @start_gfn: Guest page number to start from. * @count: Size of the result buffer. * @flags: Control operation mode via KVM_S390_CMMA_* flags * @remaining: Used with KVM_S390_GET_CMMA_BITS. Indicates how many dirty * pages are still remaining. * @mask: Used with KVM_S390_SET_CMMA_BITS. Bitmap of bits to actually set * in the PGSTE. * @values: Pointer to the values buffer. * * Used in KVM_S390_{G,S}ET_CMMA_BITS ioctls. */ struct kvm_s390_cmma_log { __u64 start_gfn; __u32 count; __u32 flags; union { __u64 remaining; __u64 mask; }; __u64 values; }; struct kvm_hyperv_exit { #define KVM_EXIT_HYPERV_SYNIC 1 #define KVM_EXIT_HYPERV_HCALL 2 #define KVM_EXIT_HYPERV_SYNDBG 3 __u32 type; __u32 pad1; union { struct { __u32 msr; __u32 pad2; __u64 control; __u64 evt_page; __u64 msg_page; } synic; struct { __u64 input; __u64 result; __u64 params[2]; } hcall; struct { __u32 msr; __u32 pad2; __u64 control; __u64 status; __u64 send_page; __u64 recv_page; __u64 pending_page; } syndbg; } u; }; struct kvm_xen_exit { #define KVM_EXIT_XEN_HCALL 1 __u32 type; union { struct { __u32 longmode; __u32 cpl; __u64 input; __u64 result; __u64 params[6]; } hcall; } u; }; #define KVM_S390_GET_SKEYS_NONE 1 #define KVM_S390_SKEYS_MAX 1048576 #define KVM_EXIT_UNKNOWN 0 #define KVM_EXIT_EXCEPTION 1 #define KVM_EXIT_IO 2 #define KVM_EXIT_HYPERCALL 3 #define KVM_EXIT_DEBUG 4 #define KVM_EXIT_HLT 5 #define KVM_EXIT_MMIO 6 #define KVM_EXIT_IRQ_WINDOW_OPEN 7 #define KVM_EXIT_SHUTDOWN 8 #define KVM_EXIT_FAIL_ENTRY 9 #define KVM_EXIT_INTR 10 #define KVM_EXIT_SET_TPR 11 #define KVM_EXIT_TPR_ACCESS 12 #define KVM_EXIT_S390_SIEIC 13 #define KVM_EXIT_S390_RESET 14 #define KVM_EXIT_DCR 15 /* deprecated */ #define KVM_EXIT_NMI 16 #define KVM_EXIT_INTERNAL_ERROR 17 #define KVM_EXIT_OSI 18 #define KVM_EXIT_PAPR_HCALL 19 #define KVM_EXIT_S390_UCONTROL 20 #define KVM_EXIT_WATCHDOG 21 #define KVM_EXIT_S390_TSCH 22 #define KVM_EXIT_EPR 23 #define KVM_EXIT_SYSTEM_EVENT 24 #define KVM_EXIT_S390_STSI 25 #define KVM_EXIT_IOAPIC_EOI 26 #define KVM_EXIT_HYPERV 27 #define KVM_EXIT_ARM_NISV 28 #define KVM_EXIT_X86_RDMSR 29 #define KVM_EXIT_X86_WRMSR 30 #define KVM_EXIT_DIRTY_RING_FULL 31 #define KVM_EXIT_AP_RESET_HOLD 32 #define KVM_EXIT_X86_BUS_LOCK 33 #define KVM_EXIT_XEN 34 /* For KVM_EXIT_INTERNAL_ERROR */ /* Emulate instruction failed. */ #define KVM_INTERNAL_ERROR_EMULATION 1 /* Encounter unexpected simultaneous exceptions. */ #define KVM_INTERNAL_ERROR_SIMUL_EX 2 /* Encounter unexpected vm-exit due to delivery event. */ #define KVM_INTERNAL_ERROR_DELIVERY_EV 3 /* Encounter unexpected vm-exit reason */ #define KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON 4 /* Flags that describe what fields in emulation_failure hold valid data. */ #define KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES (1ULL << 0) /* for KVM_RUN, returned by mmap(vcpu_fd, offset=0) */ struct kvm_run { /* in */ __u8 request_interrupt_window; __u8 immediate_exit; __u8 padding1[6]; /* out */ __u32 exit_reason; __u8 ready_for_interrupt_injection; __u8 if_flag; __u16 flags; /* in (pre_kvm_run), out (post_kvm_run) */ __u64 cr8; __u64 apic_base; #ifdef __KVM_S390 /* the processor status word for s390 */ __u64 psw_mask; /* psw upper half */ __u64 psw_addr; /* psw lower half */ #endif union { /* KVM_EXIT_UNKNOWN */ struct { __u64 hardware_exit_reason; } hw; /* KVM_EXIT_FAIL_ENTRY */ struct { __u64 hardware_entry_failure_reason; __u32 cpu; } fail_entry; /* KVM_EXIT_EXCEPTION */ struct { __u32 exception; __u32 error_code; } ex; /* KVM_EXIT_IO */ struct { #define KVM_EXIT_IO_IN 0 #define KVM_EXIT_IO_OUT 1 __u8 direction; __u8 size; /* bytes */ __u16 port; __u32 count; __u64 data_offset; /* relative to kvm_run start */ } io; /* KVM_EXIT_DEBUG */ struct { struct kvm_debug_exit_arch arch; } debug; /* KVM_EXIT_MMIO */ struct { __u64 phys_addr; __u8 data[8]; __u32 len; __u8 is_write; } mmio; /* KVM_EXIT_HYPERCALL */ struct { __u64 nr; __u64 args[6]; __u64 ret; __u32 longmode; __u32 pad; } hypercall; /* KVM_EXIT_TPR_ACCESS */ struct { __u64 rip; __u32 is_write; __u32 pad; } tpr_access; /* KVM_EXIT_S390_SIEIC */ struct { __u8 icptcode; __u16 ipa; __u32 ipb; } s390_sieic; /* KVM_EXIT_S390_RESET */ #define KVM_S390_RESET_POR 1 #define KVM_S390_RESET_CLEAR 2 #define KVM_S390_RESET_SUBSYSTEM 4 #define KVM_S390_RESET_CPU_INIT 8 #define KVM_S390_RESET_IPL 16 __u64 s390_reset_flags; /* KVM_EXIT_S390_UCONTROL */ struct { __u64 trans_exc_code; __u32 pgm_code; } s390_ucontrol; /* KVM_EXIT_DCR (deprecated) */ struct { __u32 dcrn; __u32 data; __u8 is_write; } dcr; /* KVM_EXIT_INTERNAL_ERROR */ struct { __u32 suberror; /* Available with KVM_CAP_INTERNAL_ERROR_DATA: */ __u32 ndata; __u64 data[16]; } internal; /* * KVM_INTERNAL_ERROR_EMULATION * * "struct emulation_failure" is an overlay of "struct internal" * that is used for the KVM_INTERNAL_ERROR_EMULATION sub-type of * KVM_EXIT_INTERNAL_ERROR. Note, unlike other internal error * sub-types, this struct is ABI! It also needs to be backwards * compatible with "struct internal". Take special care that * "ndata" is correct, that new fields are enumerated in "flags", * and that each flag enumerates fields that are 64-bit aligned * and sized (so that ndata+internal.data[] is valid/accurate). * * Space beyond the defined fields may be used to store arbitrary * debug information relating to the emulation failure. It is * accounted for in "ndata" but the format is unspecified and is * not represented in "flags". Any such information is *not* ABI! */ struct { __u32 suberror; __u32 ndata; __u64 flags; union { struct { __u8 insn_size; __u8 insn_bytes[15]; }; }; /* Arbitrary debug data may follow. */ } emulation_failure; /* KVM_EXIT_OSI */ struct { __u64 gprs[32]; } osi; /* KVM_EXIT_PAPR_HCALL */ struct { __u64 nr; __u64 ret; __u64 args[9]; } papr_hcall; /* KVM_EXIT_S390_TSCH */ struct { __u16 subchannel_id; __u16 subchannel_nr; __u32 io_int_parm; __u32 io_int_word; __u32 ipb; __u8 dequeued; } s390_tsch; /* KVM_EXIT_EPR */ struct { __u32 epr; } epr; /* KVM_EXIT_SYSTEM_EVENT */ struct { #define KVM_SYSTEM_EVENT_SHUTDOWN 1 #define KVM_SYSTEM_EVENT_RESET 2 #define KVM_SYSTEM_EVENT_CRASH 3 __u32 type; __u64 flags; } system_event; /* KVM_EXIT_S390_STSI */ struct { __u64 addr; __u8 ar; __u8 reserved; __u8 fc; __u8 sel1; __u16 sel2; } s390_stsi; /* KVM_EXIT_IOAPIC_EOI */ struct { __u8 vector; } eoi; /* KVM_EXIT_HYPERV */ struct kvm_hyperv_exit hyperv; /* KVM_EXIT_ARM_NISV */ struct { __u64 esr_iss; __u64 fault_ipa; } arm_nisv; /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */ struct { __u8 error; /* user -> kernel */ __u8 pad[7]; #define KVM_MSR_EXIT_REASON_INVAL (1 << 0) #define KVM_MSR_EXIT_REASON_UNKNOWN (1 << 1) #define KVM_MSR_EXIT_REASON_FILTER (1 << 2) __u32 reason; /* kernel -> user */ __u32 index; /* kernel -> user */ __u64 data; /* kernel <-> user */ } msr; /* KVM_EXIT_XEN */ struct kvm_xen_exit xen; /* Fix the size of the union. */ char padding[256]; }; /* 2048 is the size of the char array used to bound/pad the size * of the union that holds sync regs. */ #define SYNC_REGS_SIZE_BYTES 2048 /* * shared registers between kvm and userspace. * kvm_valid_regs specifies the register classes set by the host * kvm_dirty_regs specified the register classes dirtied by userspace * struct kvm_sync_regs is architecture specific, as well as the * bits for kvm_valid_regs and kvm_dirty_regs */ __u64 kvm_valid_regs; __u64 kvm_dirty_regs; union { struct kvm_sync_regs regs; char padding[SYNC_REGS_SIZE_BYTES]; } s; }; /* for KVM_REGISTER_COALESCED_MMIO / KVM_UNREGISTER_COALESCED_MMIO */ struct kvm_coalesced_mmio_zone { __u64 addr; __u32 size; union { __u32 pad; __u32 pio; }; }; struct kvm_coalesced_mmio { __u64 phys_addr; __u32 len; union { __u32 pad; __u32 pio; }; __u8 data[8]; }; struct kvm_coalesced_mmio_ring { __u32 first, last; struct kvm_coalesced_mmio coalesced_mmio[0]; }; #define KVM_COALESCED_MMIO_MAX \ ((PAGE_SIZE - sizeof(struct kvm_coalesced_mmio_ring)) / \ sizeof(struct kvm_coalesced_mmio)) /* for KVM_TRANSLATE */ struct kvm_translation { /* in */ __u64 linear_address; /* out */ __u64 physical_address; __u8 valid; __u8 writeable; __u8 usermode; __u8 pad[5]; }; /* for KVM_S390_MEM_OP */ struct kvm_s390_mem_op { /* in */ __u64 gaddr; /* the guest address */ __u64 flags; /* flags */ __u32 size; /* amount of bytes */ __u32 op; /* type of operation */ __u64 buf; /* buffer in userspace */ union { struct { __u8 ar; /* the access register number */ __u8 key; /* access key, ignored if flag unset */ }; __u32 sida_offset; /* offset into the sida */ __u8 reserved[32]; /* ignored */ }; }; /* types for kvm_s390_mem_op->op */ #define KVM_S390_MEMOP_LOGICAL_READ 0 #define KVM_S390_MEMOP_LOGICAL_WRITE 1 #define KVM_S390_MEMOP_SIDA_READ 2 #define KVM_S390_MEMOP_SIDA_WRITE 3 #define KVM_S390_MEMOP_ABSOLUTE_READ 4 #define KVM_S390_MEMOP_ABSOLUTE_WRITE 5 /* flags for kvm_s390_mem_op->flags */ #define KVM_S390_MEMOP_F_CHECK_ONLY (1ULL << 0) #define KVM_S390_MEMOP_F_INJECT_EXCEPTION (1ULL << 1) #define KVM_S390_MEMOP_F_SKEY_PROTECTION (1ULL << 2) /* for KVM_INTERRUPT */ struct kvm_interrupt { /* in */ __u32 irq; }; /* for KVM_GET_DIRTY_LOG */ struct kvm_dirty_log { __u32 slot; __u32 padding1; union { void *dirty_bitmap; /* one bit per page */ __u64 padding2; }; }; /* for KVM_CLEAR_DIRTY_LOG */ struct kvm_clear_dirty_log { __u32 slot; __u32 num_pages; __u64 first_page; union { void *dirty_bitmap; /* one bit per page */ __u64 padding2; }; }; /* for KVM_SET_SIGNAL_MASK */ struct kvm_signal_mask { __u32 len; __u8 sigset[0]; }; /* for KVM_TPR_ACCESS_REPORTING */ struct kvm_tpr_access_ctl { __u32 enabled; __u32 flags; __u32 reserved[8]; }; /* for KVM_SET_VAPIC_ADDR */ struct kvm_vapic_addr { __u64 vapic_addr; }; /* for KVM_SET_MP_STATE */ /* not all states are valid on all architectures */ #define KVM_MP_STATE_RUNNABLE 0 #define KVM_MP_STATE_UNINITIALIZED 1 #define KVM_MP_STATE_INIT_RECEIVED 2 #define KVM_MP_STATE_HALTED 3 #define KVM_MP_STATE_SIPI_RECEIVED 4 #define KVM_MP_STATE_STOPPED 5 #define KVM_MP_STATE_CHECK_STOP 6 #define KVM_MP_STATE_OPERATING 7 #define KVM_MP_STATE_LOAD 8 #define KVM_MP_STATE_AP_RESET_HOLD 9 struct kvm_mp_state { __u32 mp_state; }; struct kvm_s390_psw { __u64 mask; __u64 addr; }; /* valid values for type in kvm_s390_interrupt */ #define KVM_S390_SIGP_STOP 0xfffe0000u #define KVM_S390_PROGRAM_INT 0xfffe0001u #define KVM_S390_SIGP_SET_PREFIX 0xfffe0002u #define KVM_S390_RESTART 0xfffe0003u #define KVM_S390_INT_PFAULT_INIT 0xfffe0004u #define KVM_S390_INT_PFAULT_DONE 0xfffe0005u #define KVM_S390_MCHK 0xfffe1000u #define KVM_S390_INT_CLOCK_COMP 0xffff1004u #define KVM_S390_INT_CPU_TIMER 0xffff1005u #define KVM_S390_INT_VIRTIO 0xffff2603u #define KVM_S390_INT_SERVICE 0xffff2401u #define KVM_S390_INT_EMERGENCY 0xffff1201u #define KVM_S390_INT_EXTERNAL_CALL 0xffff1202u /* Anything below 0xfffe0000u is taken by INT_IO */ #define KVM_S390_INT_IO(ai,cssid,ssid,schid) \ (((schid)) | \ ((ssid) << 16) | \ ((cssid) << 18) | \ ((ai) << 26)) #define KVM_S390_INT_IO_MIN 0x00000000u #define KVM_S390_INT_IO_MAX 0xfffdffffu #define KVM_S390_INT_IO_AI_MASK 0x04000000u struct kvm_s390_interrupt { __u32 type; __u32 parm; __u64 parm64; }; struct kvm_s390_io_info { __u16 subchannel_id; __u16 subchannel_nr; __u32 io_int_parm; __u32 io_int_word; }; struct kvm_s390_ext_info { __u32 ext_params; __u32 pad; __u64 ext_params2; }; struct kvm_s390_pgm_info { __u64 trans_exc_code; __u64 mon_code; __u64 per_address; __u32 data_exc_code; __u16 code; __u16 mon_class_nr; __u8 per_code; __u8 per_atmid; __u8 exc_access_id; __u8 per_access_id; __u8 op_access_id; #define KVM_S390_PGM_FLAGS_ILC_VALID 0x01 #define KVM_S390_PGM_FLAGS_ILC_0 0x02 #define KVM_S390_PGM_FLAGS_ILC_1 0x04 #define KVM_S390_PGM_FLAGS_ILC_MASK 0x06 #define KVM_S390_PGM_FLAGS_NO_REWIND 0x08 __u8 flags; __u8 pad[2]; }; struct kvm_s390_prefix_info { __u32 address; }; struct kvm_s390_extcall_info { __u16 code; }; struct kvm_s390_emerg_info { __u16 code; }; #define KVM_S390_STOP_FLAG_STORE_STATUS 0x01 struct kvm_s390_stop_info { __u32 flags; }; struct kvm_s390_mchk_info { __u64 cr14; __u64 mcic; __u64 failing_storage_address; __u32 ext_damage_code; __u32 pad; __u8 fixed_logout[16]; }; struct kvm_s390_irq { __u64 type; union { struct kvm_s390_io_info io; struct kvm_s390_ext_info ext; struct kvm_s390_pgm_info pgm; struct kvm_s390_emerg_info emerg; struct kvm_s390_extcall_info extcall; struct kvm_s390_prefix_info prefix; struct kvm_s390_stop_info stop; struct kvm_s390_mchk_info mchk; char reserved[64]; } u; }; struct kvm_s390_irq_state { __u64 buf; __u32 flags; /* will stay unused for compatibility reasons */ __u32 len; __u32 reserved[4]; /* will stay unused for compatibility reasons */ }; /* for KVM_SET_GUEST_DEBUG */ #define KVM_GUESTDBG_ENABLE 0x00000001 #define KVM_GUESTDBG_SINGLESTEP 0x00000002 struct kvm_guest_debug { __u32 control; __u32 pad; struct kvm_guest_debug_arch arch; }; enum { kvm_ioeventfd_flag_nr_datamatch, kvm_ioeventfd_flag_nr_pio, kvm_ioeventfd_flag_nr_deassign, kvm_ioeventfd_flag_nr_virtio_ccw_notify, kvm_ioeventfd_flag_nr_fast_mmio, kvm_ioeventfd_flag_nr_max, }; #define KVM_IOEVENTFD_FLAG_DATAMATCH (1 << kvm_ioeventfd_flag_nr_datamatch) #define KVM_IOEVENTFD_FLAG_PIO (1 << kvm_ioeventfd_flag_nr_pio) #define KVM_IOEVENTFD_FLAG_DEASSIGN (1 << kvm_ioeventfd_flag_nr_deassign) #define KVM_IOEVENTFD_FLAG_VIRTIO_CCW_NOTIFY \ (1 << kvm_ioeventfd_flag_nr_virtio_ccw_notify) #define KVM_IOEVENTFD_VALID_FLAG_MASK ((1 << kvm_ioeventfd_flag_nr_max) - 1) struct kvm_ioeventfd { __u64 datamatch; __u64 addr; /* legal pio/mmio address */ __u32 len; /* 1, 2, 4, or 8 bytes; or 0 to ignore length */ __s32 fd; __u32 flags; __u8 pad[36]; }; #define KVM_X86_DISABLE_EXITS_MWAIT (1 << 0) #define KVM_X86_DISABLE_EXITS_HLT (1 << 1) #define KVM_X86_DISABLE_EXITS_PAUSE (1 << 2) #define KVM_X86_DISABLE_EXITS_CSTATE (1 << 3) #define KVM_X86_DISABLE_VALID_EXITS (KVM_X86_DISABLE_EXITS_MWAIT | \ KVM_X86_DISABLE_EXITS_HLT | \ KVM_X86_DISABLE_EXITS_PAUSE | \ KVM_X86_DISABLE_EXITS_CSTATE) /* for KVM_ENABLE_CAP */ struct kvm_enable_cap { /* in */ __u32 cap; __u32 flags; __u64 args[4]; __u8 pad[64]; }; /* for KVM_PPC_GET_PVINFO */ #define KVM_PPC_PVINFO_FLAGS_EV_IDLE (1<<0) struct kvm_ppc_pvinfo { /* out */ __u32 flags; __u32 hcall[4]; __u8 pad[108]; }; /* for KVM_PPC_GET_SMMU_INFO */ #define KVM_PPC_PAGE_SIZES_MAX_SZ 8 struct kvm_ppc_one_page_size { __u32 page_shift; /* Page shift (or 0) */ __u32 pte_enc; /* Encoding in the HPTE (>>12) */ }; struct kvm_ppc_one_seg_page_size { __u32 page_shift; /* Base page shift of segment (or 0) */ __u32 slb_enc; /* SLB encoding for BookS */ struct kvm_ppc_one_page_size enc[KVM_PPC_PAGE_SIZES_MAX_SZ]; }; #define KVM_PPC_PAGE_SIZES_REAL 0x00000001 #define KVM_PPC_1T_SEGMENTS 0x00000002 #define KVM_PPC_NO_HASH 0x00000004 struct kvm_ppc_smmu_info { __u64 flags; __u32 slb_size; __u16 data_keys; /* # storage keys supported for data */ __u16 instr_keys; /* # storage keys supported for instructions */ struct kvm_ppc_one_seg_page_size sps[KVM_PPC_PAGE_SIZES_MAX_SZ]; }; /* for KVM_PPC_RESIZE_HPT_{PREPARE,COMMIT} */ struct kvm_ppc_resize_hpt { __u64 flags; __u32 shift; __u32 pad; }; #define KVMIO 0xAE /* machine type bits, to be used as argument to KVM_CREATE_VM */ #define KVM_VM_S390_UCONTROL 1 /* on ppc, 0 indicate default, 1 should force HV and 2 PR */ #define KVM_VM_PPC_HV 1 #define KVM_VM_PPC_PR 2 /* on MIPS, 0 forces trap & emulate, 1 forces VZ ASE */ #define KVM_VM_MIPS_TE 0 #define KVM_VM_MIPS_VZ 1 #define KVM_S390_SIE_PAGE_OFFSET 1 /* * On arm64, machine type can be used to request the physical * address size for the VM. Bits[7-0] are reserved for the guest * PA size shift (i.e, log2(PA_Size)). For backward compatibility, * value 0 implies the default IPA size, 40bits. */ #define KVM_VM_TYPE_ARM_IPA_SIZE_MASK 0xffULL #define KVM_VM_TYPE_ARM_IPA_SIZE(x) \ ((x) & KVM_VM_TYPE_ARM_IPA_SIZE_MASK) /* * ioctls for /dev/kvm fds: */ #define KVM_GET_API_VERSION _IO(KVMIO, 0x00) #define KVM_CREATE_VM _IO(KVMIO, 0x01) /* returns a VM fd */ #define KVM_GET_MSR_INDEX_LIST _IOWR(KVMIO, 0x02, struct kvm_msr_list) #define KVM_S390_ENABLE_SIE _IO(KVMIO, 0x06) /* * Check if a kvm extension is available. Argument is extension number, * return is 1 (yes) or 0 (no, sorry). */ #define KVM_CHECK_EXTENSION _IO(KVMIO, 0x03) /* * Get size for mmap(vcpu_fd) */ #define KVM_GET_VCPU_MMAP_SIZE _IO(KVMIO, 0x04) /* in bytes */ #define KVM_GET_SUPPORTED_CPUID _IOWR(KVMIO, 0x05, struct kvm_cpuid2) #define KVM_TRACE_ENABLE __KVM_DEPRECATED_MAIN_W_0x06 #define KVM_TRACE_PAUSE __KVM_DEPRECATED_MAIN_0x07 #define KVM_TRACE_DISABLE __KVM_DEPRECATED_MAIN_0x08 #define KVM_GET_EMULATED_CPUID _IOWR(KVMIO, 0x09, struct kvm_cpuid2) #define KVM_GET_MSR_FEATURE_INDEX_LIST _IOWR(KVMIO, 0x0a, struct kvm_msr_list) /* * Extension capability list. */ #define KVM_CAP_IRQCHIP 0 #define KVM_CAP_HLT 1 #define KVM_CAP_MMU_SHADOW_CACHE_CONTROL 2 #define KVM_CAP_USER_MEMORY 3 #define KVM_CAP_SET_TSS_ADDR 4 #define KVM_CAP_VAPIC 6 #define KVM_CAP_EXT_CPUID 7 #define KVM_CAP_CLOCKSOURCE 8 #define KVM_CAP_NR_VCPUS 9 /* returns recommended max vcpus per vm */ #define KVM_CAP_NR_MEMSLOTS 10 /* returns max memory slots per vm */ #define KVM_CAP_PIT 11 #define KVM_CAP_NOP_IO_DELAY 12 #define KVM_CAP_PV_MMU 13 #define KVM_CAP_MP_STATE 14 #define KVM_CAP_COALESCED_MMIO 15 #define KVM_CAP_SYNC_MMU 16 /* Changes to host mmap are reflected in guest */ #define KVM_CAP_IOMMU 18 /* Bug in KVM_SET_USER_MEMORY_REGION fixed: */ #define KVM_CAP_DESTROY_MEMORY_REGION_WORKS 21 #define KVM_CAP_USER_NMI 22 #ifdef __KVM_HAVE_GUEST_DEBUG #define KVM_CAP_SET_GUEST_DEBUG 23 #endif #ifdef __KVM_HAVE_PIT #define KVM_CAP_REINJECT_CONTROL 24 #endif #define KVM_CAP_IRQ_ROUTING 25 #define KVM_CAP_IRQ_INJECT_STATUS 26 #define KVM_CAP_ASSIGN_DEV_IRQ 29 /* Another bug in KVM_SET_USER_MEMORY_REGION fixed: */ #define KVM_CAP_JOIN_MEMORY_REGIONS_WORKS 30 #ifdef __KVM_HAVE_MCE #define KVM_CAP_MCE 31 #endif #define KVM_CAP_IRQFD 32 #ifdef __KVM_HAVE_PIT #define KVM_CAP_PIT2 33 #endif #define KVM_CAP_SET_BOOT_CPU_ID 34 #ifdef __KVM_HAVE_PIT_STATE2 #define KVM_CAP_PIT_STATE2 35 #endif #define KVM_CAP_IOEVENTFD 36 #define KVM_CAP_SET_IDENTITY_MAP_ADDR 37 #ifdef __KVM_HAVE_XEN_HVM #define KVM_CAP_XEN_HVM 38 #endif #define KVM_CAP_ADJUST_CLOCK 39 #define KVM_CAP_INTERNAL_ERROR_DATA 40 #ifdef __KVM_HAVE_VCPU_EVENTS #define KVM_CAP_VCPU_EVENTS 41 #endif #define KVM_CAP_S390_PSW 42 #define KVM_CAP_PPC_SEGSTATE 43 #define KVM_CAP_HYPERV 44 #define KVM_CAP_HYPERV_VAPIC 45 #define KVM_CAP_HYPERV_SPIN 46 #define KVM_CAP_PCI_SEGMENT 47 #define KVM_CAP_PPC_PAIRED_SINGLES 48 #define KVM_CAP_INTR_SHADOW 49 #ifdef __KVM_HAVE_DEBUGREGS #define KVM_CAP_DEBUGREGS 50 #endif #define KVM_CAP_X86_ROBUST_SINGLESTEP 51 #define KVM_CAP_PPC_OSI 52 #define KVM_CAP_PPC_UNSET_IRQ 53 #define KVM_CAP_ENABLE_CAP 54 #ifdef __KVM_HAVE_XSAVE #define KVM_CAP_XSAVE 55 #endif #ifdef __KVM_HAVE_XCRS #define KVM_CAP_XCRS 56 #endif #define KVM_CAP_PPC_GET_PVINFO 57 #define KVM_CAP_PPC_IRQ_LEVEL 58 #define KVM_CAP_ASYNC_PF 59 #define KVM_CAP_TSC_CONTROL 60 #define KVM_CAP_GET_TSC_KHZ 61 #define KVM_CAP_PPC_BOOKE_SREGS 62 #define KVM_CAP_SPAPR_TCE 63 #define KVM_CAP_PPC_SMT 64 #define KVM_CAP_PPC_RMA 65 #define KVM_CAP_MAX_VCPUS 66 /* returns max vcpus per vm */ #define KVM_CAP_PPC_HIOR 67 #define KVM_CAP_PPC_PAPR 68 #define KVM_CAP_SW_TLB 69 #define KVM_CAP_ONE_REG 70 #define KVM_CAP_S390_GMAP 71 #define KVM_CAP_TSC_DEADLINE_TIMER 72 #define KVM_CAP_S390_UCONTROL 73 #define KVM_CAP_SYNC_REGS 74 #define KVM_CAP_PCI_2_3 75 #define KVM_CAP_KVMCLOCK_CTRL 76 #define KVM_CAP_SIGNAL_MSI 77 #define KVM_CAP_PPC_GET_SMMU_INFO 78 #define KVM_CAP_S390_COW 79 #define KVM_CAP_PPC_ALLOC_HTAB 80 #define KVM_CAP_READONLY_MEM 81 #define KVM_CAP_IRQFD_RESAMPLE 82 #define KVM_CAP_PPC_BOOKE_WATCHDOG 83 #define KVM_CAP_PPC_HTAB_FD 84 #define KVM_CAP_S390_CSS_SUPPORT 85 #define KVM_CAP_PPC_EPR 86 #define KVM_CAP_ARM_PSCI 87 #define KVM_CAP_ARM_SET_DEVICE_ADDR 88 #define KVM_CAP_DEVICE_CTRL 89 #define KVM_CAP_IRQ_MPIC 90 #define KVM_CAP_PPC_RTAS 91 #define KVM_CAP_IRQ_XICS 92 #define KVM_CAP_ARM_EL1_32BIT 93 #define KVM_CAP_SPAPR_MULTITCE 94 #define KVM_CAP_EXT_EMUL_CPUID 95 #define KVM_CAP_HYPERV_TIME 96 #define KVM_CAP_IOAPIC_POLARITY_IGNORED 97 #define KVM_CAP_ENABLE_CAP_VM 98 #define KVM_CAP_S390_IRQCHIP 99 #define KVM_CAP_IOEVENTFD_NO_LENGTH 100 #define KVM_CAP_VM_ATTRIBUTES 101 #define KVM_CAP_ARM_PSCI_0_2 102 #define KVM_CAP_PPC_FIXUP_HCALL 103 #define KVM_CAP_PPC_ENABLE_HCALL 104 #define KVM_CAP_CHECK_EXTENSION_VM 105 #define KVM_CAP_S390_USER_SIGP 106 #define KVM_CAP_S390_VECTOR_REGISTERS 107 #define KVM_CAP_S390_MEM_OP 108 #define KVM_CAP_S390_USER_STSI 109 #define KVM_CAP_S390_SKEYS 110 #define KVM_CAP_MIPS_FPU 111 #define KVM_CAP_MIPS_MSA 112 #define KVM_CAP_S390_INJECT_IRQ 113 #define KVM_CAP_S390_IRQ_STATE 114 #define KVM_CAP_PPC_HWRNG 115 #define KVM_CAP_DISABLE_QUIRKS 116 #define KVM_CAP_X86_SMM 117 #define KVM_CAP_MULTI_ADDRESS_SPACE 118 #define KVM_CAP_GUEST_DEBUG_HW_BPS 119 #define KVM_CAP_GUEST_DEBUG_HW_WPS 120 #define KVM_CAP_SPLIT_IRQCHIP 121 #define KVM_CAP_IOEVENTFD_ANY_LENGTH 122 #define KVM_CAP_HYPERV_SYNIC 123 #define KVM_CAP_S390_RI 124 #define KVM_CAP_SPAPR_TCE_64 125 #define KVM_CAP_ARM_PMU_V3 126 #define KVM_CAP_VCPU_ATTRIBUTES 127 #define KVM_CAP_MAX_VCPU_ID 128 #define KVM_CAP_X2APIC_API 129 #define KVM_CAP_S390_USER_INSTR0 130 #define KVM_CAP_MSI_DEVID 131 #define KVM_CAP_PPC_HTM 132 #define KVM_CAP_SPAPR_RESIZE_HPT 133 #define KVM_CAP_PPC_MMU_RADIX 134 #define KVM_CAP_PPC_MMU_HASH_V3 135 #define KVM_CAP_IMMEDIATE_EXIT 136 #define KVM_CAP_MIPS_VZ 137 #define KVM_CAP_MIPS_TE 138 #define KVM_CAP_MIPS_64BIT 139 #define KVM_CAP_S390_GS 140 #define KVM_CAP_S390_AIS 141 #define KVM_CAP_SPAPR_TCE_VFIO 142 #define KVM_CAP_X86_DISABLE_EXITS 143 #define KVM_CAP_ARM_USER_IRQ 144 #define KVM_CAP_S390_CMMA_MIGRATION 145 #define KVM_CAP_PPC_FWNMI 146 #define KVM_CAP_PPC_SMT_POSSIBLE 147 #define KVM_CAP_HYPERV_SYNIC2 148 #define KVM_CAP_HYPERV_VP_INDEX 149 #define KVM_CAP_S390_AIS_MIGRATION 150 #define KVM_CAP_PPC_GET_CPU_CHAR 151 #define KVM_CAP_S390_BPB 152 #define KVM_CAP_GET_MSR_FEATURES 153 #define KVM_CAP_HYPERV_EVENTFD 154 #define KVM_CAP_HYPERV_TLBFLUSH 155 #define KVM_CAP_S390_HPAGE_1M 156 #define KVM_CAP_NESTED_STATE 157 #define KVM_CAP_ARM_INJECT_SERROR_ESR 158 #define KVM_CAP_MSR_PLATFORM_INFO 159 #define KVM_CAP_PPC_NESTED_HV 160 #define KVM_CAP_HYPERV_SEND_IPI 161 #define KVM_CAP_COALESCED_PIO 162 #define KVM_CAP_HYPERV_ENLIGHTENED_VMCS 163 #define KVM_CAP_EXCEPTION_PAYLOAD 164 #define KVM_CAP_ARM_VM_IPA_SIZE 165 #define KVM_CAP_MANUAL_DIRTY_LOG_PROTECT 166 /* Obsolete */ #define KVM_CAP_HYPERV_CPUID 167 #define KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 168 #define KVM_CAP_PPC_IRQ_XIVE 169 #define KVM_CAP_ARM_SVE 170 #define KVM_CAP_ARM_PTRAUTH_ADDRESS 171 #define KVM_CAP_ARM_PTRAUTH_GENERIC 172 #define KVM_CAP_PMU_EVENT_FILTER 173 #define KVM_CAP_ARM_IRQ_LINE_LAYOUT_2 174 #define KVM_CAP_HYPERV_DIRECT_TLBFLUSH 175 #define KVM_CAP_PPC_GUEST_DEBUG_SSTEP 176 #define KVM_CAP_ARM_NISV_TO_USER 177 #define KVM_CAP_ARM_INJECT_EXT_DABT 178 #define KVM_CAP_S390_VCPU_RESETS 179 #define KVM_CAP_S390_PROTECTED 180 #define KVM_CAP_PPC_SECURE_GUEST 181 #define KVM_CAP_HALT_POLL 182 #define KVM_CAP_ASYNC_PF_INT 183 #define KVM_CAP_LAST_CPU 184 #define KVM_CAP_SMALLER_MAXPHYADDR 185 #define KVM_CAP_S390_DIAG318 186 #define KVM_CAP_STEAL_TIME 187 #define KVM_CAP_X86_USER_SPACE_MSR 188 #define KVM_CAP_X86_MSR_FILTER 189 #define KVM_CAP_ENFORCE_PV_FEATURE_CPUID 190 #define KVM_CAP_SYS_HYPERV_CPUID 191 #define KVM_CAP_DIRTY_LOG_RING 192 #define KVM_CAP_X86_BUS_LOCK_EXIT 193 #define KVM_CAP_SET_GUEST_DEBUG2 195 #define KVM_CAP_SGX_ATTRIBUTE 196 #define KVM_CAP_VM_COPY_ENC_CONTEXT_FROM 197 #define KVM_CAP_HYPERV_ENFORCE_CPUID 199 #define KVM_CAP_SREGS2 200 #define KVM_CAP_EXIT_HYPERCALL 201 #define KVM_CAP_BINARY_STATS_FD 203 #define KVM_CAP_EXIT_ON_EMULATION_FAILURE 204 #define KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM 206 #define KVM_CAP_XSAVE2 208 #define KVM_CAP_SYS_ATTRIBUTES 209 #define KVM_CAP_S390_MEM_OP_EXTENSION 211 #define KVM_CAP_PMU_CAPABILITY 212 #define KVM_CAP_DISABLE_QUIRKS2 213 #define KVM_CAP_VM_TSC_CONTROL 214 #define KVM_CAP_SYSTEM_EVENT_DATA 215 #define KVM_CAP_ARM_SYSTEM_SUSPEND 216 #define KVM_CAP_S390_PROTECTED_DUMP 217 #define KVM_CAP_S390_ZPCI_OP 221 #define KVM_CAP_S390_CPU_TOPOLOGY 222 #ifdef KVM_CAP_IRQ_ROUTING struct kvm_irq_routing_irqchip { __u32 irqchip; __u32 pin; }; struct kvm_irq_routing_msi { __u32 address_lo; __u32 address_hi; __u32 data; union { __u32 pad; __u32 devid; }; }; struct kvm_irq_routing_s390_adapter { __u64 ind_addr; __u64 summary_addr; __u64 ind_offset; __u32 summary_offset; __u32 adapter_id; }; struct kvm_irq_routing_hv_sint { __u32 vcpu; __u32 sint; }; struct kvm_irq_routing_xen_evtchn { __u32 port; __u32 vcpu; __u32 priority; }; #define KVM_IRQ_ROUTING_XEN_EVTCHN_PRIO_2LEVEL ((__u32)(-1)) /* gsi routing entry types */ #define KVM_IRQ_ROUTING_IRQCHIP 1 #define KVM_IRQ_ROUTING_MSI 2 #define KVM_IRQ_ROUTING_S390_ADAPTER 3 #define KVM_IRQ_ROUTING_HV_SINT 4 #define KVM_IRQ_ROUTING_XEN_EVTCHN 5 struct kvm_irq_routing_entry { __u32 gsi; __u32 type; __u32 flags; __u32 pad; union { struct kvm_irq_routing_irqchip irqchip; struct kvm_irq_routing_msi msi; struct kvm_irq_routing_s390_adapter adapter; struct kvm_irq_routing_hv_sint hv_sint; struct kvm_irq_routing_xen_evtchn xen_evtchn; __u32 pad[8]; } u; }; struct kvm_irq_routing { __u32 nr; __u32 flags; struct kvm_irq_routing_entry entries[0]; }; #endif #ifdef KVM_CAP_MCE /* x86 MCE */ struct kvm_x86_mce { __u64 status; __u64 addr; __u64 misc; __u64 mcg_status; __u8 bank; __u8 pad1[7]; __u64 pad2[3]; }; #endif #ifdef KVM_CAP_XEN_HVM #define KVM_XEN_HVM_CONFIG_HYPERCALL_MSR (1 << 0) #define KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL (1 << 1) #define KVM_XEN_HVM_CONFIG_SHARED_INFO (1 << 2) #define KVM_XEN_HVM_CONFIG_RUNSTATE (1 << 3) #define KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL (1 << 4) struct kvm_xen_hvm_config { __u32 flags; __u32 msr; __u64 blob_addr_32; __u64 blob_addr_64; __u8 blob_size_32; __u8 blob_size_64; __u8 pad2[30]; }; #endif #define KVM_IRQFD_FLAG_DEASSIGN (1 << 0) /* * Available with KVM_CAP_IRQFD_RESAMPLE * * KVM_IRQFD_FLAG_RESAMPLE indicates resamplefd is valid and specifies * the irqfd to operate in resampling mode for level triggered interrupt * emulation. See Documentation/virt/kvm/api.rst. */ #define KVM_IRQFD_FLAG_RESAMPLE (1 << 1) struct kvm_irqfd { __u32 fd; __u32 gsi; __u32 flags; __u32 resamplefd; __u8 pad[16]; }; /* For KVM_CAP_ADJUST_CLOCK */ /* Do not use 1, KVM_CHECK_EXTENSION returned it before we had flags. */ #define KVM_CLOCK_TSC_STABLE 2 #define KVM_CLOCK_REALTIME (1 << 2) #define KVM_CLOCK_HOST_TSC (1 << 3) struct kvm_clock_data { __u64 clock; __u32 flags; __u32 pad0; __u64 realtime; __u64 host_tsc; __u32 pad[4]; }; /* For KVM_CAP_SW_TLB */ #define KVM_MMU_FSL_BOOKE_NOHV 0 #define KVM_MMU_FSL_BOOKE_HV 1 struct kvm_config_tlb { __u64 params; __u64 array; __u32 mmu_type; __u32 array_len; }; struct kvm_dirty_tlb { __u64 bitmap; __u32 num_dirty; }; /* Available with KVM_CAP_ONE_REG */ #define KVM_REG_ARCH_MASK 0xff00000000000000ULL #define KVM_REG_GENERIC 0x0000000000000000ULL /* * Architecture specific registers are to be defined in arch headers and * ORed with the arch identifier. */ #define KVM_REG_PPC 0x1000000000000000ULL #define KVM_REG_X86 0x2000000000000000ULL #define KVM_REG_IA64 0x3000000000000000ULL #define KVM_REG_ARM 0x4000000000000000ULL #define KVM_REG_S390 0x5000000000000000ULL #define KVM_REG_ARM64 0x6000000000000000ULL #define KVM_REG_MIPS 0x7000000000000000ULL #define KVM_REG_SIZE_SHIFT 52 #define KVM_REG_SIZE_MASK 0x00f0000000000000ULL #define KVM_REG_SIZE_U8 0x0000000000000000ULL #define KVM_REG_SIZE_U16 0x0010000000000000ULL #define KVM_REG_SIZE_U32 0x0020000000000000ULL #define KVM_REG_SIZE_U64 0x0030000000000000ULL #define KVM_REG_SIZE_U128 0x0040000000000000ULL #define KVM_REG_SIZE_U256 0x0050000000000000ULL #define KVM_REG_SIZE_U512 0x0060000000000000ULL #define KVM_REG_SIZE_U1024 0x0070000000000000ULL #define KVM_REG_SIZE_U2048 0x0080000000000000ULL struct kvm_reg_list { __u64 n; /* number of regs */ __u64 reg[0]; }; struct kvm_one_reg { __u64 id; __u64 addr; }; #define KVM_MSI_VALID_DEVID (1U << 0) struct kvm_msi { __u32 address_lo; __u32 address_hi; __u32 data; __u32 flags; __u32 devid; __u8 pad[12]; }; struct kvm_arm_device_addr { __u64 id; __u64 addr; }; /* * Device control API, available with KVM_CAP_DEVICE_CTRL */ #define KVM_CREATE_DEVICE_TEST 1 struct kvm_create_device { __u32 type; /* in: KVM_DEV_TYPE_xxx */ __u32 fd; /* out: device handle */ __u32 flags; /* in: KVM_CREATE_DEVICE_xxx */ }; struct kvm_device_attr { __u32 flags; /* no flags currently defined */ __u32 group; /* device-defined */ __u64 attr; /* group-defined */ __u64 addr; /* userspace address of attr data */ }; #define KVM_DEV_VFIO_GROUP 1 #define KVM_DEV_VFIO_GROUP_ADD 1 #define KVM_DEV_VFIO_GROUP_DEL 2 #define KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE 3 enum kvm_device_type { KVM_DEV_TYPE_FSL_MPIC_20 = 1, #define KVM_DEV_TYPE_FSL_MPIC_20 KVM_DEV_TYPE_FSL_MPIC_20 KVM_DEV_TYPE_FSL_MPIC_42, #define KVM_DEV_TYPE_FSL_MPIC_42 KVM_DEV_TYPE_FSL_MPIC_42 KVM_DEV_TYPE_XICS, #define KVM_DEV_TYPE_XICS KVM_DEV_TYPE_XICS KVM_DEV_TYPE_VFIO, #define KVM_DEV_TYPE_VFIO KVM_DEV_TYPE_VFIO KVM_DEV_TYPE_ARM_VGIC_V2, #define KVM_DEV_TYPE_ARM_VGIC_V2 KVM_DEV_TYPE_ARM_VGIC_V2 KVM_DEV_TYPE_FLIC, #define KVM_DEV_TYPE_FLIC KVM_DEV_TYPE_FLIC KVM_DEV_TYPE_ARM_VGIC_V3, #define KVM_DEV_TYPE_ARM_VGIC_V3 KVM_DEV_TYPE_ARM_VGIC_V3 KVM_DEV_TYPE_ARM_VGIC_ITS, #define KVM_DEV_TYPE_ARM_VGIC_ITS KVM_DEV_TYPE_ARM_VGIC_ITS KVM_DEV_TYPE_XIVE, #define KVM_DEV_TYPE_XIVE KVM_DEV_TYPE_XIVE KVM_DEV_TYPE_ARM_PV_TIME, #define KVM_DEV_TYPE_ARM_PV_TIME KVM_DEV_TYPE_ARM_PV_TIME KVM_DEV_TYPE_MAX, }; struct kvm_vfio_spapr_tce { __s32 groupfd; __s32 tablefd; }; /* * ioctls for VM fds */ #define KVM_SET_MEMORY_REGION _IOW(KVMIO, 0x40, struct kvm_memory_region) /* * KVM_CREATE_VCPU receives as a parameter the vcpu slot, and returns * a vcpu fd. */ #define KVM_CREATE_VCPU _IO(KVMIO, 0x41) #define KVM_GET_DIRTY_LOG _IOW(KVMIO, 0x42, struct kvm_dirty_log) /* KVM_SET_MEMORY_ALIAS is obsolete: */ #define KVM_SET_MEMORY_ALIAS _IOW(KVMIO, 0x43, struct kvm_memory_alias) #define KVM_SET_NR_MMU_PAGES _IO(KVMIO, 0x44) #define KVM_GET_NR_MMU_PAGES _IO(KVMIO, 0x45) #define KVM_SET_USER_MEMORY_REGION _IOW(KVMIO, 0x46, \ struct kvm_userspace_memory_region) #define KVM_SET_TSS_ADDR _IO(KVMIO, 0x47) #define KVM_SET_IDENTITY_MAP_ADDR _IOW(KVMIO, 0x48, __u64) /* enable ucontrol for s390 */ struct kvm_s390_ucas_mapping { __u64 user_addr; __u64 vcpu_addr; __u64 length; }; #define KVM_S390_UCAS_MAP _IOW(KVMIO, 0x50, struct kvm_s390_ucas_mapping) #define KVM_S390_UCAS_UNMAP _IOW(KVMIO, 0x51, struct kvm_s390_ucas_mapping) #define KVM_S390_VCPU_FAULT _IOW(KVMIO, 0x52, unsigned long) /* Device model IOC */ #define KVM_CREATE_IRQCHIP _IO(KVMIO, 0x60) #define KVM_IRQ_LINE _IOW(KVMIO, 0x61, struct kvm_irq_level) #define KVM_GET_IRQCHIP _IOWR(KVMIO, 0x62, struct kvm_irqchip) #define KVM_SET_IRQCHIP _IOR(KVMIO, 0x63, struct kvm_irqchip) #define KVM_CREATE_PIT _IO(KVMIO, 0x64) #define KVM_GET_PIT _IOWR(KVMIO, 0x65, struct kvm_pit_state) #define KVM_SET_PIT _IOR(KVMIO, 0x66, struct kvm_pit_state) #define KVM_IRQ_LINE_STATUS _IOWR(KVMIO, 0x67, struct kvm_irq_level) #define KVM_REGISTER_COALESCED_MMIO \ _IOW(KVMIO, 0x67, struct kvm_coalesced_mmio_zone) #define KVM_UNREGISTER_COALESCED_MMIO \ _IOW(KVMIO, 0x68, struct kvm_coalesced_mmio_zone) #define KVM_ASSIGN_PCI_DEVICE _IOR(KVMIO, 0x69, \ struct kvm_assigned_pci_dev) #define KVM_SET_GSI_ROUTING _IOW(KVMIO, 0x6a, struct kvm_irq_routing) /* deprecated, replaced by KVM_ASSIGN_DEV_IRQ */ #define KVM_ASSIGN_IRQ __KVM_DEPRECATED_VM_R_0x70 #define KVM_ASSIGN_DEV_IRQ _IOW(KVMIO, 0x70, struct kvm_assigned_irq) #define KVM_REINJECT_CONTROL _IO(KVMIO, 0x71) #define KVM_DEASSIGN_PCI_DEVICE _IOW(KVMIO, 0x72, \ struct kvm_assigned_pci_dev) #define KVM_ASSIGN_SET_MSIX_NR _IOW(KVMIO, 0x73, \ struct kvm_assigned_msix_nr) #define KVM_ASSIGN_SET_MSIX_ENTRY _IOW(KVMIO, 0x74, \ struct kvm_assigned_msix_entry) #define KVM_DEASSIGN_DEV_IRQ _IOW(KVMIO, 0x75, struct kvm_assigned_irq) #define KVM_IRQFD _IOW(KVMIO, 0x76, struct kvm_irqfd) #define KVM_CREATE_PIT2 _IOW(KVMIO, 0x77, struct kvm_pit_config) #define KVM_SET_BOOT_CPU_ID _IO(KVMIO, 0x78) #define KVM_IOEVENTFD _IOW(KVMIO, 0x79, struct kvm_ioeventfd) #define KVM_XEN_HVM_CONFIG _IOW(KVMIO, 0x7a, struct kvm_xen_hvm_config) #define KVM_SET_CLOCK _IOW(KVMIO, 0x7b, struct kvm_clock_data) #define KVM_GET_CLOCK _IOR(KVMIO, 0x7c, struct kvm_clock_data) /* Available with KVM_CAP_PIT_STATE2 */ #define KVM_GET_PIT2 _IOR(KVMIO, 0x9f, struct kvm_pit_state2) #define KVM_SET_PIT2 _IOW(KVMIO, 0xa0, struct kvm_pit_state2) /* Available with KVM_CAP_PPC_GET_PVINFO */ #define KVM_PPC_GET_PVINFO _IOW(KVMIO, 0xa1, struct kvm_ppc_pvinfo) /* Available with KVM_CAP_TSC_CONTROL */ #define KVM_SET_TSC_KHZ _IO(KVMIO, 0xa2) #define KVM_GET_TSC_KHZ _IO(KVMIO, 0xa3) /* Available with KVM_CAP_PCI_2_3 */ #define KVM_ASSIGN_SET_INTX_MASK _IOW(KVMIO, 0xa4, \ struct kvm_assigned_pci_dev) /* Available with KVM_CAP_SIGNAL_MSI */ #define KVM_SIGNAL_MSI _IOW(KVMIO, 0xa5, struct kvm_msi) /* Available with KVM_CAP_PPC_GET_SMMU_INFO */ #define KVM_PPC_GET_SMMU_INFO _IOR(KVMIO, 0xa6, struct kvm_ppc_smmu_info) /* Available with KVM_CAP_PPC_ALLOC_HTAB */ #define KVM_PPC_ALLOCATE_HTAB _IOWR(KVMIO, 0xa7, __u32) #define KVM_CREATE_SPAPR_TCE _IOW(KVMIO, 0xa8, struct kvm_create_spapr_tce) #define KVM_CREATE_SPAPR_TCE_64 _IOW(KVMIO, 0xa8, \ struct kvm_create_spapr_tce_64) /* Available with KVM_CAP_RMA */ #define KVM_ALLOCATE_RMA _IOR(KVMIO, 0xa9, struct kvm_allocate_rma) /* Available with KVM_CAP_PPC_HTAB_FD */ #define KVM_PPC_GET_HTAB_FD _IOW(KVMIO, 0xaa, struct kvm_get_htab_fd) /* Available with KVM_CAP_ARM_SET_DEVICE_ADDR */ #define KVM_ARM_SET_DEVICE_ADDR _IOW(KVMIO, 0xab, struct kvm_arm_device_addr) /* Available with KVM_CAP_PPC_RTAS */ #define KVM_PPC_RTAS_DEFINE_TOKEN _IOW(KVMIO, 0xac, struct kvm_rtas_token_args) /* Available with KVM_CAP_SPAPR_RESIZE_HPT */ #define KVM_PPC_RESIZE_HPT_PREPARE _IOR(KVMIO, 0xad, struct kvm_ppc_resize_hpt) #define KVM_PPC_RESIZE_HPT_COMMIT _IOR(KVMIO, 0xae, struct kvm_ppc_resize_hpt) /* Available with KVM_CAP_PPC_RADIX_MMU or KVM_CAP_PPC_HASH_MMU_V3 */ #define KVM_PPC_CONFIGURE_V3_MMU _IOW(KVMIO, 0xaf, struct kvm_ppc_mmuv3_cfg) /* Available with KVM_CAP_PPC_RADIX_MMU */ #define KVM_PPC_GET_RMMU_INFO _IOW(KVMIO, 0xb0, struct kvm_ppc_rmmu_info) /* Available with KVM_CAP_PPC_GET_CPU_CHAR */ #define KVM_PPC_GET_CPU_CHAR _IOR(KVMIO, 0xb1, struct kvm_ppc_cpu_char) /* Available with KVM_CAP_PMU_EVENT_FILTER */ #define KVM_SET_PMU_EVENT_FILTER _IOW(KVMIO, 0xb2, struct kvm_pmu_event_filter) #define KVM_PPC_SVM_OFF _IO(KVMIO, 0xb3) /* ioctl for vm fd */ #define KVM_CREATE_DEVICE _IOWR(KVMIO, 0xe0, struct kvm_create_device) /* ioctls for fds returned by KVM_CREATE_DEVICE */ #define KVM_SET_DEVICE_ATTR _IOW(KVMIO, 0xe1, struct kvm_device_attr) #define KVM_GET_DEVICE_ATTR _IOW(KVMIO, 0xe2, struct kvm_device_attr) #define KVM_HAS_DEVICE_ATTR _IOW(KVMIO, 0xe3, struct kvm_device_attr) /* * ioctls for vcpu fds */ #define KVM_RUN _IO(KVMIO, 0x80) #define KVM_GET_REGS _IOR(KVMIO, 0x81, struct kvm_regs) #define KVM_SET_REGS _IOW(KVMIO, 0x82, struct kvm_regs) #define KVM_GET_SREGS _IOR(KVMIO, 0x83, struct kvm_sregs) #define KVM_SET_SREGS _IOW(KVMIO, 0x84, struct kvm_sregs) #define KVM_TRANSLATE _IOWR(KVMIO, 0x85, struct kvm_translation) #define KVM_INTERRUPT _IOW(KVMIO, 0x86, struct kvm_interrupt) /* KVM_DEBUG_GUEST is no longer supported, use KVM_SET_GUEST_DEBUG instead */ #define KVM_DEBUG_GUEST __KVM_DEPRECATED_VCPU_W_0x87 #define KVM_GET_MSRS _IOWR(KVMIO, 0x88, struct kvm_msrs) #define KVM_SET_MSRS _IOW(KVMIO, 0x89, struct kvm_msrs) #define KVM_SET_CPUID _IOW(KVMIO, 0x8a, struct kvm_cpuid) #define KVM_SET_SIGNAL_MASK _IOW(KVMIO, 0x8b, struct kvm_signal_mask) #define KVM_GET_FPU _IOR(KVMIO, 0x8c, struct kvm_fpu) #define KVM_SET_FPU _IOW(KVMIO, 0x8d, struct kvm_fpu) #define KVM_GET_LAPIC _IOR(KVMIO, 0x8e, struct kvm_lapic_state) #define KVM_SET_LAPIC _IOW(KVMIO, 0x8f, struct kvm_lapic_state) #define KVM_SET_CPUID2 _IOW(KVMIO, 0x90, struct kvm_cpuid2) #define KVM_GET_CPUID2 _IOWR(KVMIO, 0x91, struct kvm_cpuid2) /* Available with KVM_CAP_VAPIC */ #define KVM_TPR_ACCESS_REPORTING _IOWR(KVMIO, 0x92, struct kvm_tpr_access_ctl) /* Available with KVM_CAP_VAPIC */ #define KVM_SET_VAPIC_ADDR _IOW(KVMIO, 0x93, struct kvm_vapic_addr) /* valid for virtual machine (for floating interrupt)_and_ vcpu */ #define KVM_S390_INTERRUPT _IOW(KVMIO, 0x94, struct kvm_s390_interrupt) /* store status for s390 */ #define KVM_S390_STORE_STATUS_NOADDR (-1ul) #define KVM_S390_STORE_STATUS_PREFIXED (-2ul) #define KVM_S390_STORE_STATUS _IOW(KVMIO, 0x95, unsigned long) /* initial ipl psw for s390 */ #define KVM_S390_SET_INITIAL_PSW _IOW(KVMIO, 0x96, struct kvm_s390_psw) /* initial reset for s390 */ #define KVM_S390_INITIAL_RESET _IO(KVMIO, 0x97) #define KVM_GET_MP_STATE _IOR(KVMIO, 0x98, struct kvm_mp_state) #define KVM_SET_MP_STATE _IOW(KVMIO, 0x99, struct kvm_mp_state) /* Available with KVM_CAP_USER_NMI */ #define KVM_NMI _IO(KVMIO, 0x9a) /* Available with KVM_CAP_SET_GUEST_DEBUG */ #define KVM_SET_GUEST_DEBUG _IOW(KVMIO, 0x9b, struct kvm_guest_debug) /* MCE for x86 */ #define KVM_X86_SETUP_MCE _IOW(KVMIO, 0x9c, __u64) #define KVM_X86_GET_MCE_CAP_SUPPORTED _IOR(KVMIO, 0x9d, __u64) #define KVM_X86_SET_MCE _IOW(KVMIO, 0x9e, struct kvm_x86_mce) /* Available with KVM_CAP_VCPU_EVENTS */ #define KVM_GET_VCPU_EVENTS _IOR(KVMIO, 0x9f, struct kvm_vcpu_events) #define KVM_SET_VCPU_EVENTS _IOW(KVMIO, 0xa0, struct kvm_vcpu_events) /* Available with KVM_CAP_DEBUGREGS */ #define KVM_GET_DEBUGREGS _IOR(KVMIO, 0xa1, struct kvm_debugregs) #define KVM_SET_DEBUGREGS _IOW(KVMIO, 0xa2, struct kvm_debugregs) /* * vcpu version available with KVM_ENABLE_CAP * vm version available with KVM_CAP_ENABLE_CAP_VM */ #define KVM_ENABLE_CAP _IOW(KVMIO, 0xa3, struct kvm_enable_cap) /* Available with KVM_CAP_XSAVE */ #define KVM_GET_XSAVE _IOR(KVMIO, 0xa4, struct kvm_xsave) #define KVM_SET_XSAVE _IOW(KVMIO, 0xa5, struct kvm_xsave) /* Available with KVM_CAP_XCRS */ #define KVM_GET_XCRS _IOR(KVMIO, 0xa6, struct kvm_xcrs) #define KVM_SET_XCRS _IOW(KVMIO, 0xa7, struct kvm_xcrs) /* Available with KVM_CAP_SW_TLB */ #define KVM_DIRTY_TLB _IOW(KVMIO, 0xaa, struct kvm_dirty_tlb) /* Available with KVM_CAP_ONE_REG */ #define KVM_GET_ONE_REG _IOW(KVMIO, 0xab, struct kvm_one_reg) #define KVM_SET_ONE_REG _IOW(KVMIO, 0xac, struct kvm_one_reg) /* VM is being stopped by host */ #define KVM_KVMCLOCK_CTRL _IO(KVMIO, 0xad) #define KVM_ARM_VCPU_INIT _IOW(KVMIO, 0xae, struct kvm_vcpu_init) #define KVM_ARM_PREFERRED_TARGET _IOR(KVMIO, 0xaf, struct kvm_vcpu_init) #define KVM_GET_REG_LIST _IOWR(KVMIO, 0xb0, struct kvm_reg_list) /* Available with KVM_CAP_S390_MEM_OP */ #define KVM_S390_MEM_OP _IOW(KVMIO, 0xb1, struct kvm_s390_mem_op) /* Available with KVM_CAP_S390_SKEYS */ #define KVM_S390_GET_SKEYS _IOW(KVMIO, 0xb2, struct kvm_s390_skeys) #define KVM_S390_SET_SKEYS _IOW(KVMIO, 0xb3, struct kvm_s390_skeys) /* Available with KVM_CAP_S390_INJECT_IRQ */ #define KVM_S390_IRQ _IOW(KVMIO, 0xb4, struct kvm_s390_irq) /* Available with KVM_CAP_S390_IRQ_STATE */ #define KVM_S390_SET_IRQ_STATE _IOW(KVMIO, 0xb5, struct kvm_s390_irq_state) #define KVM_S390_GET_IRQ_STATE _IOW(KVMIO, 0xb6, struct kvm_s390_irq_state) /* Available with KVM_CAP_X86_SMM */ #define KVM_SMI _IO(KVMIO, 0xb7) /* Available with KVM_CAP_S390_CMMA_MIGRATION */ #define KVM_S390_GET_CMMA_BITS _IOWR(KVMIO, 0xb8, struct kvm_s390_cmma_log) #define KVM_S390_SET_CMMA_BITS _IOW(KVMIO, 0xb9, struct kvm_s390_cmma_log) /* Memory Encryption Commands */ #define KVM_MEMORY_ENCRYPT_OP _IOWR(KVMIO, 0xba, unsigned long) struct kvm_enc_region { __u64 addr; __u64 size; }; #define KVM_MEMORY_ENCRYPT_REG_REGION _IOR(KVMIO, 0xbb, struct kvm_enc_region) #define KVM_MEMORY_ENCRYPT_UNREG_REGION _IOR(KVMIO, 0xbc, struct kvm_enc_region) /* Available with KVM_CAP_HYPERV_EVENTFD */ #define KVM_HYPERV_EVENTFD _IOW(KVMIO, 0xbd, struct kvm_hyperv_eventfd) /* Available with KVM_CAP_NESTED_STATE */ #define KVM_GET_NESTED_STATE _IOWR(KVMIO, 0xbe, struct kvm_nested_state) #define KVM_SET_NESTED_STATE _IOW(KVMIO, 0xbf, struct kvm_nested_state) /* Available with KVM_CAP_MANUAL_DIRTY_LOG_PROTECT_2 */ #define KVM_CLEAR_DIRTY_LOG _IOWR(KVMIO, 0xc0, struct kvm_clear_dirty_log) /* Available with KVM_CAP_HYPERV_CPUID (vcpu) / KVM_CAP_SYS_HYPERV_CPUID (system) */ #define KVM_GET_SUPPORTED_HV_CPUID _IOWR(KVMIO, 0xc1, struct kvm_cpuid2) /* Available with KVM_CAP_ARM_SVE */ #define KVM_ARM_VCPU_FINALIZE _IOW(KVMIO, 0xc2, int) /* Available with KVM_CAP_S390_VCPU_RESETS */ #define KVM_S390_NORMAL_RESET _IO(KVMIO, 0xc3) #define KVM_S390_CLEAR_RESET _IO(KVMIO, 0xc4) struct kvm_s390_pv_sec_parm { __u64 origin; __u64 length; }; struct kvm_s390_pv_unp { __u64 addr; __u64 size; __u64 tweak; }; enum pv_cmd_dmp_id { KVM_PV_DUMP_INIT, KVM_PV_DUMP_CONFIG_STOR_STATE, KVM_PV_DUMP_COMPLETE, KVM_PV_DUMP_CPU, }; struct kvm_s390_pv_dmp { __u64 subcmd; __u64 buff_addr; __u64 buff_len; __u64 gaddr; /* For dump storage state */ __u64 reserved[4]; }; enum pv_cmd_info_id { KVM_PV_INFO_VM, KVM_PV_INFO_DUMP, }; struct kvm_s390_pv_info_dump { __u64 dump_cpu_buffer_len; __u64 dump_config_mem_buffer_per_1m; __u64 dump_config_finalize_len; }; struct kvm_s390_pv_info_vm { __u64 inst_calls_list[4]; __u64 max_cpus; __u64 max_guests; __u64 max_guest_addr; __u64 feature_indication; }; struct kvm_s390_pv_info_header { __u32 id; __u32 len_max; __u32 len_written; __u32 reserved; }; struct kvm_s390_pv_info { struct kvm_s390_pv_info_header header; union { struct kvm_s390_pv_info_dump dump; struct kvm_s390_pv_info_vm vm; }; }; enum pv_cmd_id { KVM_PV_ENABLE, KVM_PV_DISABLE, KVM_PV_SET_SEC_PARMS, KVM_PV_UNPACK, KVM_PV_VERIFY, KVM_PV_PREP_RESET, KVM_PV_UNSHARE_ALL, KVM_PV_INFO, KVM_PV_DUMP, }; struct kvm_pv_cmd { __u32 cmd; /* Command to be executed */ __u16 rc; /* Ultravisor return code */ __u16 rrc; /* Ultravisor return reason code */ __u64 data; /* Data or address */ __u32 flags; /* flags for future extensions. Must be 0 for now */ __u32 reserved[3]; }; /* Available with KVM_CAP_S390_PROTECTED */ #define KVM_S390_PV_COMMAND _IOWR(KVMIO, 0xc5, struct kvm_pv_cmd) /* Available with KVM_CAP_X86_MSR_FILTER */ #define KVM_X86_SET_MSR_FILTER _IOW(KVMIO, 0xc6, struct kvm_msr_filter) /* Available with KVM_CAP_DIRTY_LOG_RING */ #define KVM_RESET_DIRTY_RINGS _IO(KVMIO, 0xc7) /* Per-VM Xen attributes */ #define KVM_XEN_HVM_GET_ATTR _IOWR(KVMIO, 0xc8, struct kvm_xen_hvm_attr) #define KVM_XEN_HVM_SET_ATTR _IOW(KVMIO, 0xc9, struct kvm_xen_hvm_attr) struct kvm_xen_hvm_attr { __u16 type; __u16 pad[3]; union { __u8 long_mode; __u8 vector; struct { __u64 gfn; } shared_info; __u64 pad[8]; } u; }; /* Available with KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_SHARED_INFO */ #define KVM_XEN_ATTR_TYPE_LONG_MODE 0x0 #define KVM_XEN_ATTR_TYPE_SHARED_INFO 0x1 #define KVM_XEN_ATTR_TYPE_UPCALL_VECTOR 0x2 /* Per-vCPU Xen attributes */ #define KVM_XEN_VCPU_GET_ATTR _IOWR(KVMIO, 0xca, struct kvm_xen_vcpu_attr) #define KVM_XEN_VCPU_SET_ATTR _IOW(KVMIO, 0xcb, struct kvm_xen_vcpu_attr) #define KVM_GET_SREGS2 _IOR(KVMIO, 0xcc, struct kvm_sregs2) #define KVM_SET_SREGS2 _IOW(KVMIO, 0xcd, struct kvm_sregs2) struct kvm_xen_vcpu_attr { __u16 type; __u16 pad[3]; union { __u64 gpa; __u64 pad[8]; struct { __u64 state; __u64 state_entry_time; __u64 time_running; __u64 time_runnable; __u64 time_blocked; __u64 time_offline; } runstate; } u; }; /* Available with KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_SHARED_INFO */ #define KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO 0x0 #define KVM_XEN_VCPU_ATTR_TYPE_VCPU_TIME_INFO 0x1 #define KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR 0x2 #define KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT 0x3 #define KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA 0x4 #define KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST 0x5 /* Secure Encrypted Virtualization command */ enum sev_cmd_id { /* Guest initialization commands */ KVM_SEV_INIT = 0, KVM_SEV_ES_INIT, /* Guest launch commands */ KVM_SEV_LAUNCH_START, KVM_SEV_LAUNCH_UPDATE_DATA, KVM_SEV_LAUNCH_UPDATE_VMSA, KVM_SEV_LAUNCH_SECRET, KVM_SEV_LAUNCH_MEASURE, KVM_SEV_LAUNCH_FINISH, /* Guest migration commands (outgoing) */ KVM_SEV_SEND_START, KVM_SEV_SEND_UPDATE_DATA, KVM_SEV_SEND_UPDATE_VMSA, KVM_SEV_SEND_FINISH, /* Guest migration commands (incoming) */ KVM_SEV_RECEIVE_START, KVM_SEV_RECEIVE_UPDATE_DATA, KVM_SEV_RECEIVE_UPDATE_VMSA, KVM_SEV_RECEIVE_FINISH, /* Guest status and debug commands */ KVM_SEV_GUEST_STATUS, KVM_SEV_DBG_DECRYPT, KVM_SEV_DBG_ENCRYPT, /* Guest certificates commands */ KVM_SEV_CERT_EXPORT, /* Attestation report */ KVM_SEV_GET_ATTESTATION_REPORT, /* Guest Migration Extension */ KVM_SEV_SEND_CANCEL, KVM_SEV_NR_MAX, }; struct kvm_sev_cmd { __u32 id; __u64 data; __u32 error; __u32 sev_fd; }; struct kvm_sev_launch_start { __u32 handle; __u32 policy; __u64 dh_uaddr; __u32 dh_len; __u64 session_uaddr; __u32 session_len; }; struct kvm_sev_launch_update_data { __u64 uaddr; __u32 len; }; struct kvm_sev_launch_secret { __u64 hdr_uaddr; __u32 hdr_len; __u64 guest_uaddr; __u32 guest_len; __u64 trans_uaddr; __u32 trans_len; }; struct kvm_sev_launch_measure { __u64 uaddr; __u32 len; }; struct kvm_sev_guest_status { __u32 handle; __u32 policy; __u32 state; }; struct kvm_sev_dbg { __u64 src_uaddr; __u64 dst_uaddr; __u32 len; }; struct kvm_sev_attestation_report { __u8 mnonce[16]; __u64 uaddr; __u32 len; }; struct kvm_sev_send_start { __u32 policy; __u64 pdh_cert_uaddr; __u32 pdh_cert_len; __u64 plat_certs_uaddr; __u32 plat_certs_len; __u64 amd_certs_uaddr; __u32 amd_certs_len; __u64 session_uaddr; __u32 session_len; }; struct kvm_sev_send_update_data { __u64 hdr_uaddr; __u32 hdr_len; __u64 guest_uaddr; __u32 guest_len; __u64 trans_uaddr; __u32 trans_len; }; struct kvm_sev_receive_start { __u32 handle; __u32 policy; __u64 pdh_uaddr; __u32 pdh_len; __u64 session_uaddr; __u32 session_len; }; struct kvm_sev_receive_update_data { __u64 hdr_uaddr; __u32 hdr_len; __u64 guest_uaddr; __u32 guest_len; __u64 trans_uaddr; __u32 trans_len; }; #define KVM_DEV_ASSIGN_ENABLE_IOMMU (1 << 0) #define KVM_DEV_ASSIGN_PCI_2_3 (1 << 1) #define KVM_DEV_ASSIGN_MASK_INTX (1 << 2) struct kvm_assigned_pci_dev { __u32 assigned_dev_id; __u32 busnr; __u32 devfn; __u32 flags; __u32 segnr; union { __u32 reserved[11]; }; }; #define KVM_DEV_IRQ_HOST_INTX (1 << 0) #define KVM_DEV_IRQ_HOST_MSI (1 << 1) #define KVM_DEV_IRQ_HOST_MSIX (1 << 2) #define KVM_DEV_IRQ_GUEST_INTX (1 << 8) #define KVM_DEV_IRQ_GUEST_MSI (1 << 9) #define KVM_DEV_IRQ_GUEST_MSIX (1 << 10) #define KVM_DEV_IRQ_HOST_MASK 0x00ff #define KVM_DEV_IRQ_GUEST_MASK 0xff00 struct kvm_assigned_irq { __u32 assigned_dev_id; __u32 host_irq; /* ignored (legacy field) */ __u32 guest_irq; __u32 flags; union { __u32 reserved[12]; }; }; struct kvm_assigned_msix_nr { __u32 assigned_dev_id; __u16 entry_nr; __u16 padding; }; #define KVM_MAX_MSIX_PER_DEV 256 struct kvm_assigned_msix_entry { __u32 assigned_dev_id; __u32 gsi; __u16 entry; /* The index of entry in the MSI-X table */ __u16 padding[3]; }; #define KVM_X2APIC_API_USE_32BIT_IDS (1ULL << 0) #define KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK (1ULL << 1) /* Available with KVM_CAP_ARM_USER_IRQ */ /* Bits for run->s.regs.device_irq_level */ #define KVM_ARM_DEV_EL1_VTIMER (1 << 0) #define KVM_ARM_DEV_EL1_PTIMER (1 << 1) #define KVM_ARM_DEV_PMU (1 << 2) struct kvm_hyperv_eventfd { __u32 conn_id; __s32 fd; __u32 flags; __u32 padding[3]; }; #define KVM_HYPERV_CONN_ID_MASK 0x00ffffff #define KVM_HYPERV_EVENTFD_DEASSIGN (1 << 0) #define KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE (1 << 0) #define KVM_DIRTY_LOG_INITIALLY_SET (1 << 1) /* * Arch needs to define the macro after implementing the dirty ring * feature. KVM_DIRTY_LOG_PAGE_OFFSET should be defined as the * starting page offset of the dirty ring structures. */ #ifndef KVM_DIRTY_LOG_PAGE_OFFSET #define KVM_DIRTY_LOG_PAGE_OFFSET 0 #endif /* * KVM dirty GFN flags, defined as: * * |---------------+---------------+--------------| * | bit 1 (reset) | bit 0 (dirty) | Status | * |---------------+---------------+--------------| * | 0 | 0 | Invalid GFN | * | 0 | 1 | Dirty GFN | * | 1 | X | GFN to reset | * |---------------+---------------+--------------| * * Lifecycle of a dirty GFN goes like: * * dirtied harvested reset * 00 -----------> 01 -------------> 1X -------+ * ^ | * | | * +------------------------------------------+ * * The userspace program is only responsible for the 01->1X state * conversion after harvesting an entry. Also, it must not skip any * dirty bits, so that dirty bits are always harvested in sequence. */ #define KVM_DIRTY_GFN_F_DIRTY _BITUL(0) #define KVM_DIRTY_GFN_F_RESET _BITUL(1) #define KVM_DIRTY_GFN_F_MASK 0x3 /* * KVM dirty rings should be mapped at KVM_DIRTY_LOG_PAGE_OFFSET of * per-vcpu mmaped regions as an array of struct kvm_dirty_gfn. The * size of the gfn buffer is decided by the first argument when * enabling KVM_CAP_DIRTY_LOG_RING. */ struct kvm_dirty_gfn { __u32 flags; __u32 slot; __u64 offset; }; #define KVM_BUS_LOCK_DETECTION_OFF (1 << 0) #define KVM_BUS_LOCK_DETECTION_EXIT (1 << 1) #define KVM_PMU_CAP_DISABLE (1 << 0) /** * struct kvm_stats_header - Header of per vm/vcpu binary statistics data. * @flags: Some extra information for header, always 0 for now. * @name_size: The size in bytes of the memory which contains statistics * name string including trailing '\0'. The memory is allocated * at the send of statistics descriptor. * @num_desc: The number of statistics the vm or vcpu has. * @id_offset: The offset of the vm/vcpu stats' id string in the file pointed * by vm/vcpu stats fd. * @desc_offset: The offset of the vm/vcpu stats' descriptor block in the file * pointd by vm/vcpu stats fd. * @data_offset: The offset of the vm/vcpu stats' data block in the file * pointed by vm/vcpu stats fd. * * This is the header userspace needs to read from stats fd before any other * readings. It is used by userspace to discover all the information about the * vm/vcpu's binary statistics. * Userspace reads this header from the start of the vm/vcpu's stats fd. */ struct kvm_stats_header { __u32 flags; __u32 name_size; __u32 num_desc; __u32 id_offset; __u32 desc_offset; __u32 data_offset; }; #define KVM_STATS_TYPE_SHIFT 0 #define KVM_STATS_TYPE_MASK (0xF << KVM_STATS_TYPE_SHIFT) #define KVM_STATS_TYPE_CUMULATIVE (0x0 << KVM_STATS_TYPE_SHIFT) #define KVM_STATS_TYPE_INSTANT (0x1 << KVM_STATS_TYPE_SHIFT) #define KVM_STATS_TYPE_PEAK (0x2 << KVM_STATS_TYPE_SHIFT) #define KVM_STATS_TYPE_LINEAR_HIST (0x3 << KVM_STATS_TYPE_SHIFT) #define KVM_STATS_TYPE_LOG_HIST (0x4 << KVM_STATS_TYPE_SHIFT) #define KVM_STATS_TYPE_MAX KVM_STATS_TYPE_LOG_HIST #define KVM_STATS_UNIT_SHIFT 4 #define KVM_STATS_UNIT_MASK (0xF << KVM_STATS_UNIT_SHIFT) #define KVM_STATS_UNIT_NONE (0x0 << KVM_STATS_UNIT_SHIFT) #define KVM_STATS_UNIT_BYTES (0x1 << KVM_STATS_UNIT_SHIFT) #define KVM_STATS_UNIT_SECONDS (0x2 << KVM_STATS_UNIT_SHIFT) #define KVM_STATS_UNIT_CYCLES (0x3 << KVM_STATS_UNIT_SHIFT) #define KVM_STATS_UNIT_MAX KVM_STATS_UNIT_CYCLES #define KVM_STATS_BASE_SHIFT 8 #define KVM_STATS_BASE_MASK (0xF << KVM_STATS_BASE_SHIFT) #define KVM_STATS_BASE_POW10 (0x0 << KVM_STATS_BASE_SHIFT) #define KVM_STATS_BASE_POW2 (0x1 << KVM_STATS_BASE_SHIFT) #define KVM_STATS_BASE_MAX KVM_STATS_BASE_POW2 /** * struct kvm_stats_desc - Descriptor of a KVM statistics. * @flags: Annotations of the stats, like type, unit, etc. * @exponent: Used together with @flags to determine the unit. * @size: The number of data items for this stats. * Every data item is of type __u64. * @offset: The offset of the stats to the start of stat structure in * structure kvm or kvm_vcpu. * @bucket_size: A parameter value used for histogram stats. It is only used * for linear histogram stats, specifying the size of the bucket; * @name: The name string for the stats. Its size is indicated by the * &kvm_stats_header->name_size. */ struct kvm_stats_desc { __u32 flags; __s16 exponent; __u16 size; __u32 offset; __u32 bucket_size; char name[]; }; #define KVM_GET_STATS_FD _IO(KVMIO, 0xce) /* Available with KVM_CAP_XSAVE2 */ #define KVM_GET_XSAVE2 _IOR(KVMIO, 0xcf, struct kvm_xsave) /* Available with KVM_CAP_S390_PROTECTED_DUMP */ #define KVM_S390_PV_CPU_COMMAND _IOWR(KVMIO, 0xd0, struct kvm_pv_cmd) /* Available with KVM_CAP_S390_ZPCI_OP */ #define KVM_S390_ZPCI_OP _IOW(KVMIO, 0xd1, struct kvm_s390_zpci_op) struct kvm_s390_zpci_op { /* in */ __u32 fh; /* target device */ __u8 op; /* operation to perform */ __u8 pad[3]; union { /* for KVM_S390_ZPCIOP_REG_AEN */ struct { __u64 ibv; /* Guest addr of interrupt bit vector */ __u64 sb; /* Guest addr of summary bit */ __u32 flags; __u32 noi; /* Number of interrupts */ __u8 isc; /* Guest interrupt subclass */ __u8 sbo; /* Offset of guest summary bit vector */ __u16 pad; } reg_aen; __u64 reserved[8]; } u; }; /* types for kvm_s390_zpci_op->op */ #define KVM_S390_ZPCIOP_REG_AEN 0 #define KVM_S390_ZPCIOP_DEREG_AEN 1 /* flags for kvm_s390_zpci_op->u.reg_aen.flags */ #define KVM_S390_ZPCIOP_REGAEN_HOST (1 << 0) #endif /* __LINUX_KVM_H */ linux/i2c-dev.h000064400000005064151027430560007315 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* i2c-dev.h - i2c-bus driver, char device interface Copyright (C) 1995-97 Simon G. Vogl Copyright (C) 1998-99 Frodo Looijaard This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _LINUX_I2C_DEV_H #define _LINUX_I2C_DEV_H #include /* /dev/i2c-X ioctl commands. The ioctl's parameter is always an * unsigned long, except for: * - I2C_FUNCS, takes pointer to an unsigned long * - I2C_RDWR, takes pointer to struct i2c_rdwr_ioctl_data * - I2C_SMBUS, takes pointer to struct i2c_smbus_ioctl_data */ #define I2C_RETRIES 0x0701 /* number of times a device address should be polled when not acknowledging */ #define I2C_TIMEOUT 0x0702 /* set timeout in units of 10 ms */ /* NOTE: Slave address is 7 or 10 bits, but 10-bit addresses * are NOT supported! (due to code brokenness) */ #define I2C_SLAVE 0x0703 /* Use this slave address */ #define I2C_SLAVE_FORCE 0x0706 /* Use this slave address, even if it is already in use by a driver! */ #define I2C_TENBIT 0x0704 /* 0 for 7 bit addrs, != 0 for 10 bit */ #define I2C_FUNCS 0x0705 /* Get the adapter functionality mask */ #define I2C_RDWR 0x0707 /* Combined R/W transfer (one STOP only) */ #define I2C_PEC 0x0708 /* != 0 to use PEC with SMBus */ #define I2C_SMBUS 0x0720 /* SMBus transfer */ /* This is the structure as used in the I2C_SMBUS ioctl call */ struct i2c_smbus_ioctl_data { __u8 read_write; __u8 command; __u32 size; union i2c_smbus_data *data; }; /* This is the structure as used in the I2C_RDWR ioctl call */ struct i2c_rdwr_ioctl_data { struct i2c_msg *msgs; /* pointers to i2c_msgs */ __u32 nmsgs; /* number of i2c_msgs */ }; #define I2C_RDWR_IOCTL_MAX_MSGS 42 /* Originally defined with a typo, keep it for compatibility */ #define I2C_RDRW_IOCTL_MAX_MSGS I2C_RDWR_IOCTL_MAX_MSGS #endif /* _LINUX_I2C_DEV_H */ linux/if_team.h000064400000005050151027430560007463 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * include/linux/if_team.h - Network team device driver header * Copyright (c) 2011 Jiri Pirko * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef _LINUX_IF_TEAM_H_ #define _LINUX_IF_TEAM_H_ #define TEAM_STRING_MAX_LEN 32 /********************************** * NETLINK_GENERIC netlink family. **********************************/ enum { TEAM_CMD_NOOP, TEAM_CMD_OPTIONS_SET, TEAM_CMD_OPTIONS_GET, TEAM_CMD_PORT_LIST_GET, __TEAM_CMD_MAX, TEAM_CMD_MAX = (__TEAM_CMD_MAX - 1), }; enum { TEAM_ATTR_UNSPEC, TEAM_ATTR_TEAM_IFINDEX, /* u32 */ TEAM_ATTR_LIST_OPTION, /* nest */ TEAM_ATTR_LIST_PORT, /* nest */ __TEAM_ATTR_MAX, TEAM_ATTR_MAX = __TEAM_ATTR_MAX - 1, }; /* Nested layout of get/set msg: * * [TEAM_ATTR_LIST_OPTION] * [TEAM_ATTR_ITEM_OPTION] * [TEAM_ATTR_OPTION_*], ... * [TEAM_ATTR_ITEM_OPTION] * [TEAM_ATTR_OPTION_*], ... * ... * [TEAM_ATTR_LIST_PORT] * [TEAM_ATTR_ITEM_PORT] * [TEAM_ATTR_PORT_*], ... * [TEAM_ATTR_ITEM_PORT] * [TEAM_ATTR_PORT_*], ... * ... */ enum { TEAM_ATTR_ITEM_OPTION_UNSPEC, TEAM_ATTR_ITEM_OPTION, /* nest */ __TEAM_ATTR_ITEM_OPTION_MAX, TEAM_ATTR_ITEM_OPTION_MAX = __TEAM_ATTR_ITEM_OPTION_MAX - 1, }; enum { TEAM_ATTR_OPTION_UNSPEC, TEAM_ATTR_OPTION_NAME, /* string */ TEAM_ATTR_OPTION_CHANGED, /* flag */ TEAM_ATTR_OPTION_TYPE, /* u8 */ TEAM_ATTR_OPTION_DATA, /* dynamic */ TEAM_ATTR_OPTION_REMOVED, /* flag */ TEAM_ATTR_OPTION_PORT_IFINDEX, /* u32 */ /* for per-port options */ TEAM_ATTR_OPTION_ARRAY_INDEX, /* u32 */ /* for array options */ __TEAM_ATTR_OPTION_MAX, TEAM_ATTR_OPTION_MAX = __TEAM_ATTR_OPTION_MAX - 1, }; enum { TEAM_ATTR_ITEM_PORT_UNSPEC, TEAM_ATTR_ITEM_PORT, /* nest */ __TEAM_ATTR_ITEM_PORT_MAX, TEAM_ATTR_ITEM_PORT_MAX = __TEAM_ATTR_ITEM_PORT_MAX - 1, }; enum { TEAM_ATTR_PORT_UNSPEC, TEAM_ATTR_PORT_IFINDEX, /* u32 */ TEAM_ATTR_PORT_CHANGED, /* flag */ TEAM_ATTR_PORT_LINKUP, /* flag */ TEAM_ATTR_PORT_SPEED, /* u32 */ TEAM_ATTR_PORT_DUPLEX, /* u8 */ TEAM_ATTR_PORT_REMOVED, /* flag */ __TEAM_ATTR_PORT_MAX, TEAM_ATTR_PORT_MAX = __TEAM_ATTR_PORT_MAX - 1, }; /* * NETLINK_GENERIC related info */ #define TEAM_GENL_NAME "team" #define TEAM_GENL_VERSION 0x1 #define TEAM_GENL_CHANGE_EVENT_MC_GRP_NAME "change_event" #endif /* _LINUX_IF_TEAM_H_ */ linux/if_x25.h000064400000001561151027430560007156 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Linux X.25 packet to device interface * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _IF_X25_H #define _IF_X25_H #include /* Documentation/networking/x25-iface.txt */ #define X25_IFACE_DATA 0x00 #define X25_IFACE_CONNECT 0x01 #define X25_IFACE_DISCONNECT 0x02 #define X25_IFACE_PARAMS 0x03 #endif /* _IF_X25_H */ linux/bfs_fs.h000064400000003545151027430560007330 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/bfs_fs.h - BFS data structures on disk. * Copyright (C) 1999 Tigran Aivazian */ #ifndef _LINUX_BFS_FS_H #define _LINUX_BFS_FS_H #include #define BFS_BSIZE_BITS 9 #define BFS_BSIZE (1<i_vtype) */ #define BFS_VDIR 2L #define BFS_VREG 1L /* BFS inode layout on disk */ struct bfs_inode { __le16 i_ino; __u16 i_unused; __le32 i_sblock; __le32 i_eblock; __le32 i_eoffset; __le32 i_vtype; __le32 i_mode; __le32 i_uid; __le32 i_gid; __le32 i_nlink; __le32 i_atime; __le32 i_mtime; __le32 i_ctime; __u32 i_padding[4]; }; #define BFS_NAMELEN 14 #define BFS_DIRENT_SIZE 16 #define BFS_DIRS_PER_BLOCK 32 struct bfs_dirent { __le16 ino; char name[BFS_NAMELEN]; }; /* BFS superblock layout on disk */ struct bfs_super_block { __le32 s_magic; __le32 s_start; __le32 s_end; __le32 s_from; __le32 s_to; __s32 s_bfrom; __s32 s_bto; char s_fsname[6]; char s_volume[6]; __u32 s_padding[118]; }; #define BFS_OFF2INO(offset) \ ((((offset) - BFS_BSIZE) / sizeof(struct bfs_inode)) + BFS_ROOT_INO) #define BFS_INO2OFF(ino) \ ((__u32)(((ino) - BFS_ROOT_INO) * sizeof(struct bfs_inode)) + BFS_BSIZE) #define BFS_NZFILESIZE(ip) \ ((le32_to_cpu((ip)->i_eoffset) + 1) - le32_to_cpu((ip)->i_sblock) * BFS_BSIZE) #define BFS_FILESIZE(ip) \ ((ip)->i_sblock == 0 ? 0 : BFS_NZFILESIZE(ip)) #define BFS_FILEBLOCKS(ip) \ ((ip)->i_sblock == 0 ? 0 : (le32_to_cpu((ip)->i_eblock) + 1) - le32_to_cpu((ip)->i_sblock)) #define BFS_UNCLEAN(bfs_sb, sb) \ ((le32_to_cpu(bfs_sb->s_from) != -1) && (le32_to_cpu(bfs_sb->s_to) != -1) && !(sb->s_flags & SB_RDONLY)) #endif /* _LINUX_BFS_FS_H */ linux/uio.h000064400000001334151027430560006654 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Berkeley style UIO structures - Alan Cox 1994. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef __LINUX_UIO_H #define __LINUX_UIO_H #include struct iovec { void *iov_base; /* BSD uses caddr_t (1003.1g requires void *) */ __kernel_size_t iov_len; /* Must be size_t (1003.1g) */ }; /* * UIO_MAXIOV shall be at least 16 1003.1g (5.4.1.1) */ #define UIO_FASTIOV 8 #define UIO_MAXIOV 1024 #endif /* __LINUX_UIO_H */ linux/times.h000064400000000426151027430560007202 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TIMES_H #define _LINUX_TIMES_H #include struct tms { __kernel_clock_t tms_utime; __kernel_clock_t tms_stime; __kernel_clock_t tms_cutime; __kernel_clock_t tms_cstime; }; #endif linux/hdlcdrv.h000064400000005534151027430560007514 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * hdlcdrv.h -- HDLC packet radio network driver. * The Linux soundcard driver for 1200 baud and 9600 baud packet radio * (C) 1996-1998 by Thomas Sailer, HB9JNX/AE4WA */ #ifndef _HDLCDRV_H #define _HDLCDRV_H /* -------------------------------------------------------------------- */ /* * structs for the IOCTL commands */ struct hdlcdrv_params { int iobase; int irq; int dma; int dma2; int seriobase; int pariobase; int midiiobase; }; struct hdlcdrv_channel_params { int tx_delay; /* the transmitter keyup delay in 10ms units */ int tx_tail; /* the transmitter keyoff delay in 10ms units */ int slottime; /* the slottime in 10ms; usually 10 = 100ms */ int ppersist; /* the p-persistence 0..255 */ int fulldup; /* some driver do not support full duplex, setting */ /* this just makes them send even if DCD is on */ }; struct hdlcdrv_old_channel_state { int ptt; int dcd; int ptt_keyed; }; struct hdlcdrv_channel_state { int ptt; int dcd; int ptt_keyed; unsigned long tx_packets; unsigned long tx_errors; unsigned long rx_packets; unsigned long rx_errors; }; struct hdlcdrv_ioctl { int cmd; union { struct hdlcdrv_params mp; struct hdlcdrv_channel_params cp; struct hdlcdrv_channel_state cs; struct hdlcdrv_old_channel_state ocs; unsigned int calibrate; unsigned char bits; char modename[128]; char drivername[32]; } data; }; /* -------------------------------------------------------------------- */ /* * ioctl values */ #define HDLCDRVCTL_GETMODEMPAR 0 #define HDLCDRVCTL_SETMODEMPAR 1 #define HDLCDRVCTL_MODEMPARMASK 2 /* not handled by hdlcdrv */ #define HDLCDRVCTL_GETCHANNELPAR 10 #define HDLCDRVCTL_SETCHANNELPAR 11 #define HDLCDRVCTL_OLDGETSTAT 20 #define HDLCDRVCTL_CALIBRATE 21 #define HDLCDRVCTL_GETSTAT 22 /* * these are mainly for debugging purposes */ #define HDLCDRVCTL_GETSAMPLES 30 #define HDLCDRVCTL_GETBITS 31 /* * not handled by hdlcdrv, but by its depending drivers */ #define HDLCDRVCTL_GETMODE 40 #define HDLCDRVCTL_SETMODE 41 #define HDLCDRVCTL_MODELIST 42 #define HDLCDRVCTL_DRIVERNAME 43 /* * mask of needed modem parameters, returned by HDLCDRVCTL_MODEMPARMASK */ #define HDLCDRV_PARMASK_IOBASE (1<<0) #define HDLCDRV_PARMASK_IRQ (1<<1) #define HDLCDRV_PARMASK_DMA (1<<2) #define HDLCDRV_PARMASK_DMA2 (1<<3) #define HDLCDRV_PARMASK_SERIOBASE (1<<4) #define HDLCDRV_PARMASK_PARIOBASE (1<<5) #define HDLCDRV_PARMASK_MIDIIOBASE (1<<6) /* -------------------------------------------------------------------- */ /* -------------------------------------------------------------------- */ #endif /* _HDLCDRV_H */ /* -------------------------------------------------------------------- */ linux/auto_dev-ioctl.h000064400000011572151027430560011003 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright 2008 Red Hat, Inc. All rights reserved. * Copyright 2008 Ian Kent * * This file is part of the Linux kernel and is made available under * the terms of the GNU General Public License, version 2, or at your * option, any later version, incorporated herein by reference. */ #ifndef _LINUX_AUTO_DEV_IOCTL_H #define _LINUX_AUTO_DEV_IOCTL_H #include #include #define AUTOFS_DEVICE_NAME "autofs" #define AUTOFS_DEV_IOCTL_VERSION_MAJOR 1 #define AUTOFS_DEV_IOCTL_VERSION_MINOR 1 #define AUTOFS_DEV_IOCTL_SIZE sizeof(struct autofs_dev_ioctl) /* * An ioctl interface for autofs mount point control. */ struct args_protover { __u32 version; }; struct args_protosubver { __u32 sub_version; }; struct args_openmount { __u32 devid; }; struct args_ready { __u32 token; }; struct args_fail { __u32 token; __s32 status; }; struct args_setpipefd { __s32 pipefd; }; struct args_timeout { __u64 timeout; }; struct args_requester { __u32 uid; __u32 gid; }; struct args_expire { __u32 how; }; struct args_askumount { __u32 may_umount; }; struct args_ismountpoint { union { struct args_in { __u32 type; } in; struct args_out { __u32 devid; __u32 magic; } out; }; }; /* * All the ioctls use this structure. * When sending a path size must account for the total length * of the chunk of memory otherwise is is the size of the * structure. */ struct autofs_dev_ioctl { __u32 ver_major; __u32 ver_minor; __u32 size; /* total size of data passed in * including this struct */ __s32 ioctlfd; /* automount command fd */ /* Command parameters */ union { struct args_protover protover; struct args_protosubver protosubver; struct args_openmount openmount; struct args_ready ready; struct args_fail fail; struct args_setpipefd setpipefd; struct args_timeout timeout; struct args_requester requester; struct args_expire expire; struct args_askumount askumount; struct args_ismountpoint ismountpoint; }; char path[0]; }; static __inline__ void init_autofs_dev_ioctl(struct autofs_dev_ioctl *in) { memset(in, 0, AUTOFS_DEV_IOCTL_SIZE); in->ver_major = AUTOFS_DEV_IOCTL_VERSION_MAJOR; in->ver_minor = AUTOFS_DEV_IOCTL_VERSION_MINOR; in->size = AUTOFS_DEV_IOCTL_SIZE; in->ioctlfd = -1; } enum { /* Get various version info */ AUTOFS_DEV_IOCTL_VERSION_CMD = 0x71, AUTOFS_DEV_IOCTL_PROTOVER_CMD, AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD, /* Open mount ioctl fd */ AUTOFS_DEV_IOCTL_OPENMOUNT_CMD, /* Close mount ioctl fd */ AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD, /* Mount/expire status returns */ AUTOFS_DEV_IOCTL_READY_CMD, AUTOFS_DEV_IOCTL_FAIL_CMD, /* Activate/deactivate autofs mount */ AUTOFS_DEV_IOCTL_SETPIPEFD_CMD, AUTOFS_DEV_IOCTL_CATATONIC_CMD, /* Expiry timeout */ AUTOFS_DEV_IOCTL_TIMEOUT_CMD, /* Get mount last requesting uid and gid */ AUTOFS_DEV_IOCTL_REQUESTER_CMD, /* Check for eligible expire candidates */ AUTOFS_DEV_IOCTL_EXPIRE_CMD, /* Request busy status */ AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD, /* Check if path is a mountpoint */ AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD, }; #define AUTOFS_DEV_IOCTL_VERSION \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_VERSION_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_PROTOVER \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_PROTOVER_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_PROTOSUBVER \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_OPENMOUNT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_OPENMOUNT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_CLOSEMOUNT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_READY \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_READY_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_FAIL \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_FAIL_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_SETPIPEFD \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_SETPIPEFD_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_CATATONIC \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_CATATONIC_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_TIMEOUT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_TIMEOUT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_REQUESTER \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_REQUESTER_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_EXPIRE \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_EXPIRE_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_ASKUMOUNT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD, struct autofs_dev_ioctl) #define AUTOFS_DEV_IOCTL_ISMOUNTPOINT \ _IOWR(AUTOFS_IOCTL, \ AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD, struct autofs_dev_ioctl) #endif /* _LINUX_AUTO_DEV_IOCTL_H */ linux/swab.h000064400000015411151027430560007015 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SWAB_H #define _LINUX_SWAB_H #include #include #include /* * casts are necessary for constants, because we never know how for sure * how U/UL/ULL map to __u16, __u32, __u64. At least not in a portable way. */ #define ___constant_swab16(x) ((__u16)( \ (((__u16)(x) & (__u16)0x00ffU) << 8) | \ (((__u16)(x) & (__u16)0xff00U) >> 8))) #define ___constant_swab32(x) ((__u32)( \ (((__u32)(x) & (__u32)0x000000ffUL) << 24) | \ (((__u32)(x) & (__u32)0x0000ff00UL) << 8) | \ (((__u32)(x) & (__u32)0x00ff0000UL) >> 8) | \ (((__u32)(x) & (__u32)0xff000000UL) >> 24))) #define ___constant_swab64(x) ((__u64)( \ (((__u64)(x) & (__u64)0x00000000000000ffULL) << 56) | \ (((__u64)(x) & (__u64)0x000000000000ff00ULL) << 40) | \ (((__u64)(x) & (__u64)0x0000000000ff0000ULL) << 24) | \ (((__u64)(x) & (__u64)0x00000000ff000000ULL) << 8) | \ (((__u64)(x) & (__u64)0x000000ff00000000ULL) >> 8) | \ (((__u64)(x) & (__u64)0x0000ff0000000000ULL) >> 24) | \ (((__u64)(x) & (__u64)0x00ff000000000000ULL) >> 40) | \ (((__u64)(x) & (__u64)0xff00000000000000ULL) >> 56))) #define ___constant_swahw32(x) ((__u32)( \ (((__u32)(x) & (__u32)0x0000ffffUL) << 16) | \ (((__u32)(x) & (__u32)0xffff0000UL) >> 16))) #define ___constant_swahb32(x) ((__u32)( \ (((__u32)(x) & (__u32)0x00ff00ffUL) << 8) | \ (((__u32)(x) & (__u32)0xff00ff00UL) >> 8))) /* * Implement the following as inlines, but define the interface using * macros to allow constant folding when possible: * ___swab16, ___swab32, ___swab64, ___swahw32, ___swahb32 */ static __inline__ __u16 __fswab16(__u16 val) { #if defined (__arch_swab16) return __arch_swab16(val); #else return ___constant_swab16(val); #endif } static __inline__ __u32 __fswab32(__u32 val) { #if defined(__arch_swab32) return __arch_swab32(val); #else return ___constant_swab32(val); #endif } static __inline__ __u64 __fswab64(__u64 val) { #if defined (__arch_swab64) return __arch_swab64(val); #elif defined(__SWAB_64_THRU_32__) __u32 h = val >> 32; __u32 l = val & ((1ULL << 32) - 1); return (((__u64)__fswab32(l)) << 32) | ((__u64)(__fswab32(h))); #else return ___constant_swab64(val); #endif } static __inline__ __u32 __fswahw32(__u32 val) { #ifdef __arch_swahw32 return __arch_swahw32(val); #else return ___constant_swahw32(val); #endif } static __inline__ __u32 __fswahb32(__u32 val) { #ifdef __arch_swahb32 return __arch_swahb32(val); #else return ___constant_swahb32(val); #endif } /** * __swab16 - return a byteswapped 16-bit value * @x: value to byteswap */ #ifdef __HAVE_BUILTIN_BSWAP16__ #define __swab16(x) (__u16)__builtin_bswap16((__u16)(x)) #else #define __swab16(x) \ (__builtin_constant_p((__u16)(x)) ? \ ___constant_swab16(x) : \ __fswab16(x)) #endif /** * __swab32 - return a byteswapped 32-bit value * @x: value to byteswap */ #ifdef __HAVE_BUILTIN_BSWAP32__ #define __swab32(x) (__u32)__builtin_bswap32((__u32)(x)) #else #define __swab32(x) \ (__builtin_constant_p((__u32)(x)) ? \ ___constant_swab32(x) : \ __fswab32(x)) #endif /** * __swab64 - return a byteswapped 64-bit value * @x: value to byteswap */ #ifdef __HAVE_BUILTIN_BSWAP64__ #define __swab64(x) (__u64)__builtin_bswap64((__u64)(x)) #else #define __swab64(x) \ (__builtin_constant_p((__u64)(x)) ? \ ___constant_swab64(x) : \ __fswab64(x)) #endif static __always_inline unsigned long __swab(const unsigned long y) { #if __BITS_PER_LONG == 64 return __swab64(y); #else /* __BITS_PER_LONG == 32 */ return __swab32(y); #endif } /** * __swahw32 - return a word-swapped 32-bit value * @x: value to wordswap * * __swahw32(0x12340000) is 0x00001234 */ #define __swahw32(x) \ (__builtin_constant_p((__u32)(x)) ? \ ___constant_swahw32(x) : \ __fswahw32(x)) /** * __swahb32 - return a high and low byte-swapped 32-bit value * @x: value to byteswap * * __swahb32(0x12345678) is 0x34127856 */ #define __swahb32(x) \ (__builtin_constant_p((__u32)(x)) ? \ ___constant_swahb32(x) : \ __fswahb32(x)) /** * __swab16p - return a byteswapped 16-bit value from a pointer * @p: pointer to a naturally-aligned 16-bit value */ static __always_inline __u16 __swab16p(const __u16 *p) { #ifdef __arch_swab16p return __arch_swab16p(p); #else return __swab16(*p); #endif } /** * __swab32p - return a byteswapped 32-bit value from a pointer * @p: pointer to a naturally-aligned 32-bit value */ static __always_inline __u32 __swab32p(const __u32 *p) { #ifdef __arch_swab32p return __arch_swab32p(p); #else return __swab32(*p); #endif } /** * __swab64p - return a byteswapped 64-bit value from a pointer * @p: pointer to a naturally-aligned 64-bit value */ static __always_inline __u64 __swab64p(const __u64 *p) { #ifdef __arch_swab64p return __arch_swab64p(p); #else return __swab64(*p); #endif } /** * __swahw32p - return a wordswapped 32-bit value from a pointer * @p: pointer to a naturally-aligned 32-bit value * * See __swahw32() for details of wordswapping. */ static __inline__ __u32 __swahw32p(const __u32 *p) { #ifdef __arch_swahw32p return __arch_swahw32p(p); #else return __swahw32(*p); #endif } /** * __swahb32p - return a high and low byteswapped 32-bit value from a pointer * @p: pointer to a naturally-aligned 32-bit value * * See __swahb32() for details of high/low byteswapping. */ static __inline__ __u32 __swahb32p(const __u32 *p) { #ifdef __arch_swahb32p return __arch_swahb32p(p); #else return __swahb32(*p); #endif } /** * __swab16s - byteswap a 16-bit value in-place * @p: pointer to a naturally-aligned 16-bit value */ static __inline__ void __swab16s(__u16 *p) { #ifdef __arch_swab16s __arch_swab16s(p); #else *p = __swab16p(p); #endif } /** * __swab32s - byteswap a 32-bit value in-place * @p: pointer to a naturally-aligned 32-bit value */ static __always_inline void __swab32s(__u32 *p) { #ifdef __arch_swab32s __arch_swab32s(p); #else *p = __swab32p(p); #endif } /** * __swab64s - byteswap a 64-bit value in-place * @p: pointer to a naturally-aligned 64-bit value */ static __always_inline void __swab64s(__u64 *p) { #ifdef __arch_swab64s __arch_swab64s(p); #else *p = __swab64p(p); #endif } /** * __swahw32s - wordswap a 32-bit value in-place * @p: pointer to a naturally-aligned 32-bit value * * See __swahw32() for details of wordswapping */ static __inline__ void __swahw32s(__u32 *p) { #ifdef __arch_swahw32s __arch_swahw32s(p); #else *p = __swahw32p(p); #endif } /** * __swahb32s - high and low byteswap a 32-bit value in-place * @p: pointer to a naturally-aligned 32-bit value * * See __swahb32() for details of high and low byte swapping */ static __inline__ void __swahb32s(__u32 *p) { #ifdef __arch_swahb32s __arch_swahb32s(p); #else *p = __swahb32p(p); #endif } #endif /* _LINUX_SWAB_H */ linux/virtio_mem.h000064400000015765151027430560010247 0ustar00/* SPDX-License-Identifier: BSD-3-Clause */ /* * Virtio Mem Device * * Copyright Red Hat, Inc. 2020 * * Authors: * David Hildenbrand * * This header is BSD licensed so anyone can use the definitions * to implement compatible drivers/servers: * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IBM OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _LINUX_VIRTIO_MEM_H #define _LINUX_VIRTIO_MEM_H #include #include #include #include /* * Each virtio-mem device manages a dedicated region in physical address * space. Each device can belong to a single NUMA node, multiple devices * for a single NUMA node are possible. A virtio-mem device is like a * "resizable DIMM" consisting of small memory blocks that can be plugged * or unplugged. The device driver is responsible for (un)plugging memory * blocks on demand. * * Virtio-mem devices can only operate on their assigned memory region in * order to (un)plug memory. A device cannot (un)plug memory belonging to * other devices. * * The "region_size" corresponds to the maximum amount of memory that can * be provided by a device. The "size" corresponds to the amount of memory * that is currently plugged. "requested_size" corresponds to a request * from the device to the device driver to (un)plug blocks. The * device driver should try to (un)plug blocks in order to reach the * "requested_size". It is impossible to plug more memory than requested. * * The "usable_region_size" represents the memory region that can actually * be used to (un)plug memory. It is always at least as big as the * "requested_size" and will grow dynamically. It will only shrink when * explicitly triggered (VIRTIO_MEM_REQ_UNPLUG). * * There are no guarantees what will happen if unplugged memory is * read/written. In general, unplugged memory should not be touched, because * the resulting action is undefined. There is one exception: without * VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE, unplugged memory inside the usable * region can be read, to simplify creation of memory dumps. * * It can happen that the device cannot process a request, because it is * busy. The device driver has to retry later. * * Usually, during system resets all memory will get unplugged, so the * device driver can start with a clean state. However, in specific * scenarios (if the device is busy) it can happen that the device still * has memory plugged. The device driver can request to unplug all memory * (VIRTIO_MEM_REQ_UNPLUG) - which might take a while to succeed if the * device is busy. */ /* --- virtio-mem: feature bits --- */ /* node_id is an ACPI PXM and is valid */ #define VIRTIO_MEM_F_ACPI_PXM 0 /* unplugged memory must not be accessed */ #define VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE 1 /* --- virtio-mem: guest -> host requests --- */ /* request to plug memory blocks */ #define VIRTIO_MEM_REQ_PLUG 0 /* request to unplug memory blocks */ #define VIRTIO_MEM_REQ_UNPLUG 1 /* request to unplug all blocks and shrink the usable size */ #define VIRTIO_MEM_REQ_UNPLUG_ALL 2 /* request information about the plugged state of memory blocks */ #define VIRTIO_MEM_REQ_STATE 3 struct virtio_mem_req_plug { __virtio64 addr; __virtio16 nb_blocks; __virtio16 padding[3]; }; struct virtio_mem_req_unplug { __virtio64 addr; __virtio16 nb_blocks; __virtio16 padding[3]; }; struct virtio_mem_req_state { __virtio64 addr; __virtio16 nb_blocks; __virtio16 padding[3]; }; struct virtio_mem_req { __virtio16 type; __virtio16 padding[3]; union { struct virtio_mem_req_plug plug; struct virtio_mem_req_unplug unplug; struct virtio_mem_req_state state; } u; }; /* --- virtio-mem: host -> guest response --- */ /* * Request processed successfully, applicable for * - VIRTIO_MEM_REQ_PLUG * - VIRTIO_MEM_REQ_UNPLUG * - VIRTIO_MEM_REQ_UNPLUG_ALL * - VIRTIO_MEM_REQ_STATE */ #define VIRTIO_MEM_RESP_ACK 0 /* * Request denied - e.g. trying to plug more than requested, applicable for * - VIRTIO_MEM_REQ_PLUG */ #define VIRTIO_MEM_RESP_NACK 1 /* * Request cannot be processed right now, try again later, applicable for * - VIRTIO_MEM_REQ_PLUG * - VIRTIO_MEM_REQ_UNPLUG * - VIRTIO_MEM_REQ_UNPLUG_ALL */ #define VIRTIO_MEM_RESP_BUSY 2 /* * Error in request (e.g. addresses/alignment), applicable for * - VIRTIO_MEM_REQ_PLUG * - VIRTIO_MEM_REQ_UNPLUG * - VIRTIO_MEM_REQ_STATE */ #define VIRTIO_MEM_RESP_ERROR 3 /* State of memory blocks is "plugged" */ #define VIRTIO_MEM_STATE_PLUGGED 0 /* State of memory blocks is "unplugged" */ #define VIRTIO_MEM_STATE_UNPLUGGED 1 /* State of memory blocks is "mixed" */ #define VIRTIO_MEM_STATE_MIXED 2 struct virtio_mem_resp_state { __virtio16 state; }; struct virtio_mem_resp { __virtio16 type; __virtio16 padding[3]; union { struct virtio_mem_resp_state state; } u; }; /* --- virtio-mem: configuration --- */ struct virtio_mem_config { /* Block size and alignment. Cannot change. */ __le64 block_size; /* Valid with VIRTIO_MEM_F_ACPI_PXM. Cannot change. */ __le16 node_id; __u8 padding[6]; /* Start address of the memory region. Cannot change. */ __le64 addr; /* Region size (maximum). Cannot change. */ __le64 region_size; /* * Currently usable region size. Can grow up to region_size. Can * shrink due to VIRTIO_MEM_REQ_UNPLUG_ALL (in which case no config * update will be sent). */ __le64 usable_region_size; /* * Currently used size. Changes due to plug/unplug requests, but no * config updates will be sent. */ __le64 plugged_size; /* Requested size. New plug requests cannot exceed it. Can change. */ __le64 requested_size; }; #endif /* _LINUX_VIRTIO_MEM_H */ linux/nilfs2_ondisk.h000064400000043161151027430560010630 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * nilfs2_ondisk.h - NILFS2 on-disk structures * * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. */ /* * linux/include/linux/ext2_fs.h * * Copyright (C) 1992, 1993, 1994, 1995 * Remy Card (card@masi.ibp.fr) * Laboratoire MASI - Institut Blaise Pascal * Universite Pierre et Marie Curie (Paris VI) * * from * * linux/include/linux/minix_fs.h * * Copyright (C) 1991, 1992 Linus Torvalds */ #ifndef _LINUX_NILFS2_ONDISK_H #define _LINUX_NILFS2_ONDISK_H #include #include #define NILFS_INODE_BMAP_SIZE 7 /** * struct nilfs_inode - structure of an inode on disk * @i_blocks: blocks count * @i_size: size in bytes * @i_ctime: creation time (seconds) * @i_mtime: modification time (seconds) * @i_ctime_nsec: creation time (nano seconds) * @i_mtime_nsec: modification time (nano seconds) * @i_uid: user id * @i_gid: group id * @i_mode: file mode * @i_links_count: links count * @i_flags: file flags * @i_bmap: block mapping * @i_xattr: extended attributes * @i_generation: file generation (for NFS) * @i_pad: padding */ struct nilfs_inode { __le64 i_blocks; __le64 i_size; __le64 i_ctime; __le64 i_mtime; __le32 i_ctime_nsec; __le32 i_mtime_nsec; __le32 i_uid; __le32 i_gid; __le16 i_mode; __le16 i_links_count; __le32 i_flags; __le64 i_bmap[NILFS_INODE_BMAP_SIZE]; #define i_device_code i_bmap[0] __le64 i_xattr; __le32 i_generation; __le32 i_pad; }; #define NILFS_MIN_INODE_SIZE 128 /** * struct nilfs_super_root - structure of super root * @sr_sum: check sum * @sr_bytes: byte count of the structure * @sr_flags: flags (reserved) * @sr_nongc_ctime: write time of the last segment not for cleaner operation * @sr_dat: DAT file inode * @sr_cpfile: checkpoint file inode * @sr_sufile: segment usage file inode */ struct nilfs_super_root { __le32 sr_sum; __le16 sr_bytes; __le16 sr_flags; __le64 sr_nongc_ctime; struct nilfs_inode sr_dat; struct nilfs_inode sr_cpfile; struct nilfs_inode sr_sufile; }; #define NILFS_SR_MDT_OFFSET(inode_size, i) \ ((unsigned long)&((struct nilfs_super_root *)0)->sr_dat + \ (inode_size) * (i)) #define NILFS_SR_DAT_OFFSET(inode_size) NILFS_SR_MDT_OFFSET(inode_size, 0) #define NILFS_SR_CPFILE_OFFSET(inode_size) NILFS_SR_MDT_OFFSET(inode_size, 1) #define NILFS_SR_SUFILE_OFFSET(inode_size) NILFS_SR_MDT_OFFSET(inode_size, 2) #define NILFS_SR_BYTES(inode_size) NILFS_SR_MDT_OFFSET(inode_size, 3) /* * Maximal mount counts */ #define NILFS_DFL_MAX_MNT_COUNT 50 /* 50 mounts */ /* * File system states (sbp->s_state, nilfs->ns_mount_state) */ #define NILFS_VALID_FS 0x0001 /* Unmounted cleanly */ #define NILFS_ERROR_FS 0x0002 /* Errors detected */ #define NILFS_RESIZE_FS 0x0004 /* Resize required */ /* * Mount flags (sbi->s_mount_opt) */ #define NILFS_MOUNT_ERROR_MODE 0x0070 /* Error mode mask */ #define NILFS_MOUNT_ERRORS_CONT 0x0010 /* Continue on errors */ #define NILFS_MOUNT_ERRORS_RO 0x0020 /* Remount fs ro on errors */ #define NILFS_MOUNT_ERRORS_PANIC 0x0040 /* Panic on errors */ #define NILFS_MOUNT_BARRIER 0x1000 /* Use block barriers */ #define NILFS_MOUNT_STRICT_ORDER 0x2000 /* * Apply strict in-order * semantics also for data */ #define NILFS_MOUNT_NORECOVERY 0x4000 /* * Disable write access during * mount-time recovery */ #define NILFS_MOUNT_DISCARD 0x8000 /* Issue DISCARD requests */ /** * struct nilfs_super_block - structure of super block on disk */ struct nilfs_super_block { /*00*/ __le32 s_rev_level; /* Revision level */ __le16 s_minor_rev_level; /* minor revision level */ __le16 s_magic; /* Magic signature */ __le16 s_bytes; /* * Bytes count of CRC calculation * for this structure. s_reserved * is excluded. */ __le16 s_flags; /* flags */ __le32 s_crc_seed; /* Seed value of CRC calculation */ /*10*/ __le32 s_sum; /* Check sum of super block */ __le32 s_log_block_size; /* * Block size represented as follows * blocksize = * 1 << (s_log_block_size + 10) */ __le64 s_nsegments; /* Number of segments in filesystem */ /*20*/ __le64 s_dev_size; /* block device size in bytes */ __le64 s_first_data_block; /* 1st seg disk block number */ /*30*/ __le32 s_blocks_per_segment; /* number of blocks per full segment */ __le32 s_r_segments_percentage; /* Reserved segments percentage */ __le64 s_last_cno; /* Last checkpoint number */ /*40*/ __le64 s_last_pseg; /* disk block addr pseg written last */ __le64 s_last_seq; /* seq. number of seg written last */ /*50*/ __le64 s_free_blocks_count; /* Free blocks count */ __le64 s_ctime; /* * Creation time (execution time of * newfs) */ /*60*/ __le64 s_mtime; /* Mount time */ __le64 s_wtime; /* Write time */ /*70*/ __le16 s_mnt_count; /* Mount count */ __le16 s_max_mnt_count; /* Maximal mount count */ __le16 s_state; /* File system state */ __le16 s_errors; /* Behaviour when detecting errors */ __le64 s_lastcheck; /* time of last check */ /*80*/ __le32 s_checkinterval; /* max. time between checks */ __le32 s_creator_os; /* OS */ __le16 s_def_resuid; /* Default uid for reserved blocks */ __le16 s_def_resgid; /* Default gid for reserved blocks */ __le32 s_first_ino; /* First non-reserved inode */ /*90*/ __le16 s_inode_size; /* Size of an inode */ __le16 s_dat_entry_size; /* Size of a dat entry */ __le16 s_checkpoint_size; /* Size of a checkpoint */ __le16 s_segment_usage_size; /* Size of a segment usage */ /*98*/ __u8 s_uuid[16]; /* 128-bit uuid for volume */ /*A8*/ char s_volume_name[80]; /* volume name */ /*F8*/ __le32 s_c_interval; /* Commit interval of segment */ __le32 s_c_block_max; /* * Threshold of data amount for * the segment construction */ /*100*/ __le64 s_feature_compat; /* Compatible feature set */ __le64 s_feature_compat_ro; /* Read-only compatible feature set */ __le64 s_feature_incompat; /* Incompatible feature set */ __u32 s_reserved[186]; /* padding to the end of the block */ }; /* * Codes for operating systems */ #define NILFS_OS_LINUX 0 /* Codes from 1 to 4 are reserved to keep compatibility with ext2 creator-OS */ /* * Revision levels */ #define NILFS_CURRENT_REV 2 /* current major revision */ #define NILFS_MINOR_REV 0 /* minor revision */ #define NILFS_MIN_SUPP_REV 2 /* minimum supported revision */ /* * Feature set definitions * * If there is a bit set in the incompatible feature set that the kernel * doesn't know about, it should refuse to mount the filesystem. */ #define NILFS_FEATURE_COMPAT_RO_BLOCK_COUNT 0x00000001ULL #define NILFS_FEATURE_COMPAT_SUPP 0ULL #define NILFS_FEATURE_COMPAT_RO_SUPP NILFS_FEATURE_COMPAT_RO_BLOCK_COUNT #define NILFS_FEATURE_INCOMPAT_SUPP 0ULL /* * Bytes count of super_block for CRC-calculation */ #define NILFS_SB_BYTES \ ((long)&((struct nilfs_super_block *)0)->s_reserved) /* * Special inode number */ #define NILFS_ROOT_INO 2 /* Root file inode */ #define NILFS_DAT_INO 3 /* DAT file */ #define NILFS_CPFILE_INO 4 /* checkpoint file */ #define NILFS_SUFILE_INO 5 /* segment usage file */ #define NILFS_IFILE_INO 6 /* ifile */ #define NILFS_ATIME_INO 7 /* Atime file (reserved) */ #define NILFS_XATTR_INO 8 /* Xattribute file (reserved) */ #define NILFS_SKETCH_INO 10 /* Sketch file */ #define NILFS_USER_INO 11 /* Fisrt user's file inode number */ #define NILFS_SB_OFFSET_BYTES 1024 /* byte offset of nilfs superblock */ #define NILFS_SEG_MIN_BLOCKS 16 /* * Minimum number of blocks in * a full segment */ #define NILFS_PSEG_MIN_BLOCKS 2 /* * Minimum number of blocks in * a partial segment */ #define NILFS_MIN_NRSVSEGS 8 /* * Minimum number of reserved * segments */ /* * We call DAT, cpfile, and sufile root metadata files. Inodes of * these files are written in super root block instead of ifile, and * garbage collector doesn't keep any past versions of these files. */ #define NILFS_ROOT_METADATA_FILE(ino) \ ((ino) >= NILFS_DAT_INO && (ino) <= NILFS_SUFILE_INO) /* * bytes offset of secondary super block */ #define NILFS_SB2_OFFSET_BYTES(devsize) ((((devsize) >> 12) - 1) << 12) /* * Maximal count of links to a file */ #define NILFS_LINK_MAX 32000 /* * Structure of a directory entry * (Same as ext2) */ #define NILFS_NAME_LEN 255 /* * Block size limitations */ #define NILFS_MIN_BLOCK_SIZE 1024 #define NILFS_MAX_BLOCK_SIZE 65536 /* * The new version of the directory entry. Since V0 structures are * stored in intel byte order, and the name_len field could never be * bigger than 255 chars, it's safe to reclaim the extra byte for the * file_type field. */ struct nilfs_dir_entry { __le64 inode; /* Inode number */ __le16 rec_len; /* Directory entry length */ __u8 name_len; /* Name length */ __u8 file_type; /* Dir entry type (file, dir, etc) */ char name[NILFS_NAME_LEN]; /* File name */ char pad; }; /* * NILFS directory file types. Only the low 3 bits are used. The * other bits are reserved for now. */ enum { NILFS_FT_UNKNOWN, NILFS_FT_REG_FILE, NILFS_FT_DIR, NILFS_FT_CHRDEV, NILFS_FT_BLKDEV, NILFS_FT_FIFO, NILFS_FT_SOCK, NILFS_FT_SYMLINK, NILFS_FT_MAX }; /* * NILFS_DIR_PAD defines the directory entries boundaries * * NOTE: It must be a multiple of 8 */ #define NILFS_DIR_PAD 8 #define NILFS_DIR_ROUND (NILFS_DIR_PAD - 1) #define NILFS_DIR_REC_LEN(name_len) (((name_len) + 12 + NILFS_DIR_ROUND) & \ ~NILFS_DIR_ROUND) #define NILFS_MAX_REC_LEN ((1 << 16) - 1) /** * struct nilfs_finfo - file information * @fi_ino: inode number * @fi_cno: checkpoint number * @fi_nblocks: number of blocks (including intermediate blocks) * @fi_ndatablk: number of file data blocks */ struct nilfs_finfo { __le64 fi_ino; __le64 fi_cno; __le32 fi_nblocks; __le32 fi_ndatablk; }; /** * struct nilfs_binfo_v - information on a data block (except DAT) * @bi_vblocknr: virtual block number * @bi_blkoff: block offset */ struct nilfs_binfo_v { __le64 bi_vblocknr; __le64 bi_blkoff; }; /** * struct nilfs_binfo_dat - information on a DAT node block * @bi_blkoff: block offset * @bi_level: level * @bi_pad: padding */ struct nilfs_binfo_dat { __le64 bi_blkoff; __u8 bi_level; __u8 bi_pad[7]; }; /** * union nilfs_binfo: block information * @bi_v: nilfs_binfo_v structure * @bi_dat: nilfs_binfo_dat structure */ union nilfs_binfo { struct nilfs_binfo_v bi_v; struct nilfs_binfo_dat bi_dat; }; /** * struct nilfs_segment_summary - segment summary header * @ss_datasum: checksum of data * @ss_sumsum: checksum of segment summary * @ss_magic: magic number * @ss_bytes: size of this structure in bytes * @ss_flags: flags * @ss_seq: sequence number * @ss_create: creation timestamp * @ss_next: next segment * @ss_nblocks: number of blocks * @ss_nfinfo: number of finfo structures * @ss_sumbytes: total size of segment summary in bytes * @ss_pad: padding * @ss_cno: checkpoint number */ struct nilfs_segment_summary { __le32 ss_datasum; __le32 ss_sumsum; __le32 ss_magic; __le16 ss_bytes; __le16 ss_flags; __le64 ss_seq; __le64 ss_create; __le64 ss_next; __le32 ss_nblocks; __le32 ss_nfinfo; __le32 ss_sumbytes; __le32 ss_pad; __le64 ss_cno; /* array of finfo structures */ }; #define NILFS_SEGSUM_MAGIC 0x1eaffa11 /* segment summary magic number */ /* * Segment summary flags */ #define NILFS_SS_LOGBGN 0x0001 /* begins a logical segment */ #define NILFS_SS_LOGEND 0x0002 /* ends a logical segment */ #define NILFS_SS_SR 0x0004 /* has super root */ #define NILFS_SS_SYNDT 0x0008 /* includes data only updates */ #define NILFS_SS_GC 0x0010 /* segment written for cleaner operation */ /** * struct nilfs_btree_node - header of B-tree node block * @bn_flags: flags * @bn_level: level * @bn_nchildren: number of children * @bn_pad: padding */ struct nilfs_btree_node { __u8 bn_flags; __u8 bn_level; __le16 bn_nchildren; __le32 bn_pad; }; /* flags */ #define NILFS_BTREE_NODE_ROOT 0x01 /* level */ #define NILFS_BTREE_LEVEL_DATA 0 #define NILFS_BTREE_LEVEL_NODE_MIN (NILFS_BTREE_LEVEL_DATA + 1) #define NILFS_BTREE_LEVEL_MAX 14 /* Max level (exclusive) */ /** * struct nilfs_direct_node - header of built-in bmap array * @dn_flags: flags * @dn_pad: padding */ struct nilfs_direct_node { __u8 dn_flags; __u8 pad[7]; }; /** * struct nilfs_palloc_group_desc - block group descriptor * @pg_nfrees: number of free entries in block group */ struct nilfs_palloc_group_desc { __le32 pg_nfrees; }; /** * struct nilfs_dat_entry - disk address translation entry * @de_blocknr: block number * @de_start: start checkpoint number * @de_end: end checkpoint number * @de_rsv: reserved for future use */ struct nilfs_dat_entry { __le64 de_blocknr; __le64 de_start; __le64 de_end; __le64 de_rsv; }; #define NILFS_MIN_DAT_ENTRY_SIZE 32 /** * struct nilfs_snapshot_list - snapshot list * @ssl_next: next checkpoint number on snapshot list * @ssl_prev: previous checkpoint number on snapshot list */ struct nilfs_snapshot_list { __le64 ssl_next; __le64 ssl_prev; }; /** * struct nilfs_checkpoint - checkpoint structure * @cp_flags: flags * @cp_checkpoints_count: checkpoints count in a block * @cp_snapshot_list: snapshot list * @cp_cno: checkpoint number * @cp_create: creation timestamp * @cp_nblk_inc: number of blocks incremented by this checkpoint * @cp_inodes_count: inodes count * @cp_blocks_count: blocks count * @cp_ifile_inode: inode of ifile */ struct nilfs_checkpoint { __le32 cp_flags; __le32 cp_checkpoints_count; struct nilfs_snapshot_list cp_snapshot_list; __le64 cp_cno; __le64 cp_create; __le64 cp_nblk_inc; __le64 cp_inodes_count; __le64 cp_blocks_count; /* * Do not change the byte offset of ifile inode. * To keep the compatibility of the disk format, * additional fields should be added behind cp_ifile_inode. */ struct nilfs_inode cp_ifile_inode; }; #define NILFS_MIN_CHECKPOINT_SIZE (64 + NILFS_MIN_INODE_SIZE) /* checkpoint flags */ enum { NILFS_CHECKPOINT_SNAPSHOT, NILFS_CHECKPOINT_INVALID, NILFS_CHECKPOINT_SKETCH, NILFS_CHECKPOINT_MINOR, }; #define NILFS_CHECKPOINT_FNS(flag, name) \ static __inline__ void \ nilfs_checkpoint_set_##name(struct nilfs_checkpoint *cp) \ { \ cp->cp_flags = cpu_to_le32(le32_to_cpu(cp->cp_flags) | \ (1UL << NILFS_CHECKPOINT_##flag)); \ } \ static __inline__ void \ nilfs_checkpoint_clear_##name(struct nilfs_checkpoint *cp) \ { \ cp->cp_flags = cpu_to_le32(le32_to_cpu(cp->cp_flags) & \ ~(1UL << NILFS_CHECKPOINT_##flag)); \ } \ static __inline__ int \ nilfs_checkpoint_##name(const struct nilfs_checkpoint *cp) \ { \ return !!(le32_to_cpu(cp->cp_flags) & \ (1UL << NILFS_CHECKPOINT_##flag)); \ } NILFS_CHECKPOINT_FNS(SNAPSHOT, snapshot) NILFS_CHECKPOINT_FNS(INVALID, invalid) NILFS_CHECKPOINT_FNS(MINOR, minor) /** * struct nilfs_cpfile_header - checkpoint file header * @ch_ncheckpoints: number of checkpoints * @ch_nsnapshots: number of snapshots * @ch_snapshot_list: snapshot list */ struct nilfs_cpfile_header { __le64 ch_ncheckpoints; __le64 ch_nsnapshots; struct nilfs_snapshot_list ch_snapshot_list; }; #define NILFS_CPFILE_FIRST_CHECKPOINT_OFFSET \ ((sizeof(struct nilfs_cpfile_header) + \ sizeof(struct nilfs_checkpoint) - 1) / \ sizeof(struct nilfs_checkpoint)) /** * struct nilfs_segment_usage - segment usage * @su_lastmod: last modified timestamp * @su_nblocks: number of blocks in segment * @su_flags: flags */ struct nilfs_segment_usage { __le64 su_lastmod; __le32 su_nblocks; __le32 su_flags; }; #define NILFS_MIN_SEGMENT_USAGE_SIZE 16 /* segment usage flag */ enum { NILFS_SEGMENT_USAGE_ACTIVE, NILFS_SEGMENT_USAGE_DIRTY, NILFS_SEGMENT_USAGE_ERROR, }; #define NILFS_SEGMENT_USAGE_FNS(flag, name) \ static __inline__ void \ nilfs_segment_usage_set_##name(struct nilfs_segment_usage *su) \ { \ su->su_flags = cpu_to_le32(le32_to_cpu(su->su_flags) | \ (1UL << NILFS_SEGMENT_USAGE_##flag));\ } \ static __inline__ void \ nilfs_segment_usage_clear_##name(struct nilfs_segment_usage *su) \ { \ su->su_flags = \ cpu_to_le32(le32_to_cpu(su->su_flags) & \ ~(1UL << NILFS_SEGMENT_USAGE_##flag)); \ } \ static __inline__ int \ nilfs_segment_usage_##name(const struct nilfs_segment_usage *su) \ { \ return !!(le32_to_cpu(su->su_flags) & \ (1UL << NILFS_SEGMENT_USAGE_##flag)); \ } NILFS_SEGMENT_USAGE_FNS(ACTIVE, active) NILFS_SEGMENT_USAGE_FNS(DIRTY, dirty) NILFS_SEGMENT_USAGE_FNS(ERROR, error) static __inline__ void nilfs_segment_usage_set_clean(struct nilfs_segment_usage *su) { su->su_lastmod = cpu_to_le64(0); su->su_nblocks = cpu_to_le32(0); su->su_flags = cpu_to_le32(0); } static __inline__ int nilfs_segment_usage_clean(const struct nilfs_segment_usage *su) { return !le32_to_cpu(su->su_flags); } /** * struct nilfs_sufile_header - segment usage file header * @sh_ncleansegs: number of clean segments * @sh_ndirtysegs: number of dirty segments * @sh_last_alloc: last allocated segment number */ struct nilfs_sufile_header { __le64 sh_ncleansegs; __le64 sh_ndirtysegs; __le64 sh_last_alloc; /* ... */ }; #define NILFS_SUFILE_FIRST_SEGMENT_USAGE_OFFSET \ ((sizeof(struct nilfs_sufile_header) + \ sizeof(struct nilfs_segment_usage) - 1) / \ sizeof(struct nilfs_segment_usage)) #endif /* _LINUX_NILFS2_ONDISK_H */ linux/sockios.h000064400000013732151027430560007537 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions of the socket-level I/O control calls. * * Version: @(#)sockios.h 1.0.2 03/09/93 * * Authors: Ross Biro * Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_SOCKIOS_H #define _LINUX_SOCKIOS_H #include /* Linux-specific socket ioctls */ #define SIOCINQ FIONREAD #define SIOCOUTQ TIOCOUTQ /* output queue size (not sent + not acked) */ #define SOCK_IOC_TYPE 0x89 /* Routing table calls. */ #define SIOCADDRT 0x890B /* add routing table entry */ #define SIOCDELRT 0x890C /* delete routing table entry */ #define SIOCRTMSG 0x890D /* unused */ /* Socket configuration controls. */ #define SIOCGIFNAME 0x8910 /* get iface name */ #define SIOCSIFLINK 0x8911 /* set iface channel */ #define SIOCGIFCONF 0x8912 /* get iface list */ #define SIOCGIFFLAGS 0x8913 /* get flags */ #define SIOCSIFFLAGS 0x8914 /* set flags */ #define SIOCGIFADDR 0x8915 /* get PA address */ #define SIOCSIFADDR 0x8916 /* set PA address */ #define SIOCGIFDSTADDR 0x8917 /* get remote PA address */ #define SIOCSIFDSTADDR 0x8918 /* set remote PA address */ #define SIOCGIFBRDADDR 0x8919 /* get broadcast PA address */ #define SIOCSIFBRDADDR 0x891a /* set broadcast PA address */ #define SIOCGIFNETMASK 0x891b /* get network PA mask */ #define SIOCSIFNETMASK 0x891c /* set network PA mask */ #define SIOCGIFMETRIC 0x891d /* get metric */ #define SIOCSIFMETRIC 0x891e /* set metric */ #define SIOCGIFMEM 0x891f /* get memory address (BSD) */ #define SIOCSIFMEM 0x8920 /* set memory address (BSD) */ #define SIOCGIFMTU 0x8921 /* get MTU size */ #define SIOCSIFMTU 0x8922 /* set MTU size */ #define SIOCSIFNAME 0x8923 /* set interface name */ #define SIOCSIFHWADDR 0x8924 /* set hardware address */ #define SIOCGIFENCAP 0x8925 /* get/set encapsulations */ #define SIOCSIFENCAP 0x8926 #define SIOCGIFHWADDR 0x8927 /* Get hardware address */ #define SIOCGIFSLAVE 0x8929 /* Driver slaving support */ #define SIOCSIFSLAVE 0x8930 #define SIOCADDMULTI 0x8931 /* Multicast address lists */ #define SIOCDELMULTI 0x8932 #define SIOCGIFINDEX 0x8933 /* name -> if_index mapping */ #define SIOGIFINDEX SIOCGIFINDEX /* misprint compatibility :-) */ #define SIOCSIFPFLAGS 0x8934 /* set/get extended flags set */ #define SIOCGIFPFLAGS 0x8935 #define SIOCDIFADDR 0x8936 /* delete PA address */ #define SIOCSIFHWBROADCAST 0x8937 /* set hardware broadcast addr */ #define SIOCGIFCOUNT 0x8938 /* get number of devices */ #define SIOCGIFBR 0x8940 /* Bridging support */ #define SIOCSIFBR 0x8941 /* Set bridging options */ #define SIOCGIFTXQLEN 0x8942 /* Get the tx queue length */ #define SIOCSIFTXQLEN 0x8943 /* Set the tx queue length */ /* SIOCGIFDIVERT was: 0x8944 Frame diversion support */ /* SIOCSIFDIVERT was: 0x8945 Set frame diversion options */ #define SIOCETHTOOL 0x8946 /* Ethtool interface */ #define SIOCGMIIPHY 0x8947 /* Get address of MII PHY in use. */ #define SIOCGMIIREG 0x8948 /* Read MII PHY register. */ #define SIOCSMIIREG 0x8949 /* Write MII PHY register. */ #define SIOCWANDEV 0x894A /* get/set netdev parameters */ #define SIOCOUTQNSD 0x894B /* output queue size (not sent only) */ #define SIOCGSKNS 0x894C /* get socket network namespace */ /* ARP cache control calls. */ /* 0x8950 - 0x8952 * obsolete calls, don't re-use */ #define SIOCDARP 0x8953 /* delete ARP table entry */ #define SIOCGARP 0x8954 /* get ARP table entry */ #define SIOCSARP 0x8955 /* set ARP table entry */ /* RARP cache control calls. */ #define SIOCDRARP 0x8960 /* delete RARP table entry */ #define SIOCGRARP 0x8961 /* get RARP table entry */ #define SIOCSRARP 0x8962 /* set RARP table entry */ /* Driver configuration calls */ #define SIOCGIFMAP 0x8970 /* Get device parameters */ #define SIOCSIFMAP 0x8971 /* Set device parameters */ /* DLCI configuration calls */ #define SIOCADDDLCI 0x8980 /* Create new DLCI device */ #define SIOCDELDLCI 0x8981 /* Delete DLCI device */ #define SIOCGIFVLAN 0x8982 /* 802.1Q VLAN support */ #define SIOCSIFVLAN 0x8983 /* Set 802.1Q VLAN options */ /* bonding calls */ #define SIOCBONDENSLAVE 0x8990 /* enslave a device to the bond */ #define SIOCBONDRELEASE 0x8991 /* release a slave from the bond*/ #define SIOCBONDSETHWADDR 0x8992 /* set the hw addr of the bond */ #define SIOCBONDSLAVEINFOQUERY 0x8993 /* rtn info about slave state */ #define SIOCBONDINFOQUERY 0x8994 /* rtn info about bond state */ #define SIOCBONDCHANGEACTIVE 0x8995 /* update to a new active slave */ /* bridge calls */ #define SIOCBRADDBR 0x89a0 /* create new bridge device */ #define SIOCBRDELBR 0x89a1 /* remove bridge device */ #define SIOCBRADDIF 0x89a2 /* add interface to bridge */ #define SIOCBRDELIF 0x89a3 /* remove interface from bridge */ /* hardware time stamping: parameters in linux/net_tstamp.h */ #define SIOCSHWTSTAMP 0x89b0 /* set and get config */ #define SIOCGHWTSTAMP 0x89b1 /* get config */ /* Device private ioctl calls */ /* * These 16 ioctls are available to devices via the do_ioctl() device * vector. Each device should include this file and redefine these names * as their own. Because these are device dependent it is a good idea * _NOT_ to issue them to random objects and hope. * * THESE IOCTLS ARE _DEPRECATED_ AND WILL DISAPPEAR IN 2.5.X -DaveM */ #define SIOCDEVPRIVATE 0x89F0 /* to 89FF */ /* * These 16 ioctl calls are protocol private */ #define SIOCPROTOPRIVATE 0x89E0 /* to 89EF */ #endif /* _LINUX_SOCKIOS_H */ linux/cec-funcs.h000064400000151215151027430560007732 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * cec - HDMI Consumer Electronics Control message functions * * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #ifndef _CEC_UAPI_FUNCS_H #define _CEC_UAPI_FUNCS_H #include /* One Touch Play Feature */ static __inline__ void cec_msg_active_source(struct cec_msg *msg, __u16 phys_addr) { msg->len = 4; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_ACTIVE_SOURCE; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; } static __inline__ void cec_ops_active_source(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } static __inline__ void cec_msg_image_view_on(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_IMAGE_VIEW_ON; } static __inline__ void cec_msg_text_view_on(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_TEXT_VIEW_ON; } /* Routing Control Feature */ static __inline__ void cec_msg_inactive_source(struct cec_msg *msg, __u16 phys_addr) { msg->len = 4; msg->msg[1] = CEC_MSG_INACTIVE_SOURCE; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; } static __inline__ void cec_ops_inactive_source(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } static __inline__ void cec_msg_request_active_source(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_REQUEST_ACTIVE_SOURCE; msg->reply = reply ? CEC_MSG_ACTIVE_SOURCE : 0; } static __inline__ void cec_msg_routing_information(struct cec_msg *msg, __u16 phys_addr) { msg->len = 4; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_ROUTING_INFORMATION; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; } static __inline__ void cec_ops_routing_information(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } static __inline__ void cec_msg_routing_change(struct cec_msg *msg, int reply, __u16 orig_phys_addr, __u16 new_phys_addr) { msg->len = 6; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_ROUTING_CHANGE; msg->msg[2] = orig_phys_addr >> 8; msg->msg[3] = orig_phys_addr & 0xff; msg->msg[4] = new_phys_addr >> 8; msg->msg[5] = new_phys_addr & 0xff; msg->reply = reply ? CEC_MSG_ROUTING_INFORMATION : 0; } static __inline__ void cec_ops_routing_change(const struct cec_msg *msg, __u16 *orig_phys_addr, __u16 *new_phys_addr) { *orig_phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *new_phys_addr = (msg->msg[4] << 8) | msg->msg[5]; } static __inline__ void cec_msg_set_stream_path(struct cec_msg *msg, __u16 phys_addr) { msg->len = 4; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_SET_STREAM_PATH; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; } static __inline__ void cec_ops_set_stream_path(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } /* Standby Feature */ static __inline__ void cec_msg_standby(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_STANDBY; } /* One Touch Record Feature */ static __inline__ void cec_msg_record_off(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_RECORD_OFF; msg->reply = reply ? CEC_MSG_RECORD_STATUS : 0; } struct cec_op_arib_data { __u16 transport_id; __u16 service_id; __u16 orig_network_id; }; struct cec_op_atsc_data { __u16 transport_id; __u16 program_number; }; struct cec_op_dvb_data { __u16 transport_id; __u16 service_id; __u16 orig_network_id; }; struct cec_op_channel_data { __u8 channel_number_fmt; __u16 major; __u16 minor; }; struct cec_op_digital_service_id { __u8 service_id_method; __u8 dig_bcast_system; union { struct cec_op_arib_data arib; struct cec_op_atsc_data atsc; struct cec_op_dvb_data dvb; struct cec_op_channel_data channel; }; }; struct cec_op_record_src { __u8 type; union { struct cec_op_digital_service_id digital; struct { __u8 ana_bcast_type; __u16 ana_freq; __u8 bcast_system; } analog; struct { __u8 plug; } ext_plug; struct { __u16 phys_addr; } ext_phys_addr; }; }; static __inline__ void cec_set_digital_service_id(__u8 *msg, const struct cec_op_digital_service_id *digital) { *msg++ = (digital->service_id_method << 7) | digital->dig_bcast_system; if (digital->service_id_method == CEC_OP_SERVICE_ID_METHOD_BY_CHANNEL) { *msg++ = (digital->channel.channel_number_fmt << 2) | (digital->channel.major >> 8); *msg++ = digital->channel.major & 0xff; *msg++ = digital->channel.minor >> 8; *msg++ = digital->channel.minor & 0xff; *msg++ = 0; *msg++ = 0; return; } switch (digital->dig_bcast_system) { case CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_GEN: case CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_CABLE: case CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_SAT: case CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_T: *msg++ = digital->atsc.transport_id >> 8; *msg++ = digital->atsc.transport_id & 0xff; *msg++ = digital->atsc.program_number >> 8; *msg++ = digital->atsc.program_number & 0xff; *msg++ = 0; *msg++ = 0; break; default: *msg++ = digital->dvb.transport_id >> 8; *msg++ = digital->dvb.transport_id & 0xff; *msg++ = digital->dvb.service_id >> 8; *msg++ = digital->dvb.service_id & 0xff; *msg++ = digital->dvb.orig_network_id >> 8; *msg++ = digital->dvb.orig_network_id & 0xff; break; } } static __inline__ void cec_get_digital_service_id(const __u8 *msg, struct cec_op_digital_service_id *digital) { digital->service_id_method = msg[0] >> 7; digital->dig_bcast_system = msg[0] & 0x7f; if (digital->service_id_method == CEC_OP_SERVICE_ID_METHOD_BY_CHANNEL) { digital->channel.channel_number_fmt = msg[1] >> 2; digital->channel.major = ((msg[1] & 3) << 6) | msg[2]; digital->channel.minor = (msg[3] << 8) | msg[4]; return; } digital->dvb.transport_id = (msg[1] << 8) | msg[2]; digital->dvb.service_id = (msg[3] << 8) | msg[4]; digital->dvb.orig_network_id = (msg[5] << 8) | msg[6]; } static __inline__ void cec_msg_record_on_own(struct cec_msg *msg) { msg->len = 3; msg->msg[1] = CEC_MSG_RECORD_ON; msg->msg[2] = CEC_OP_RECORD_SRC_OWN; } static __inline__ void cec_msg_record_on_digital(struct cec_msg *msg, const struct cec_op_digital_service_id *digital) { msg->len = 10; msg->msg[1] = CEC_MSG_RECORD_ON; msg->msg[2] = CEC_OP_RECORD_SRC_DIGITAL; cec_set_digital_service_id(msg->msg + 3, digital); } static __inline__ void cec_msg_record_on_analog(struct cec_msg *msg, __u8 ana_bcast_type, __u16 ana_freq, __u8 bcast_system) { msg->len = 7; msg->msg[1] = CEC_MSG_RECORD_ON; msg->msg[2] = CEC_OP_RECORD_SRC_ANALOG; msg->msg[3] = ana_bcast_type; msg->msg[4] = ana_freq >> 8; msg->msg[5] = ana_freq & 0xff; msg->msg[6] = bcast_system; } static __inline__ void cec_msg_record_on_plug(struct cec_msg *msg, __u8 plug) { msg->len = 4; msg->msg[1] = CEC_MSG_RECORD_ON; msg->msg[2] = CEC_OP_RECORD_SRC_EXT_PLUG; msg->msg[3] = plug; } static __inline__ void cec_msg_record_on_phys_addr(struct cec_msg *msg, __u16 phys_addr) { msg->len = 5; msg->msg[1] = CEC_MSG_RECORD_ON; msg->msg[2] = CEC_OP_RECORD_SRC_EXT_PHYS_ADDR; msg->msg[3] = phys_addr >> 8; msg->msg[4] = phys_addr & 0xff; } static __inline__ void cec_msg_record_on(struct cec_msg *msg, int reply, const struct cec_op_record_src *rec_src) { switch (rec_src->type) { case CEC_OP_RECORD_SRC_OWN: cec_msg_record_on_own(msg); break; case CEC_OP_RECORD_SRC_DIGITAL: cec_msg_record_on_digital(msg, &rec_src->digital); break; case CEC_OP_RECORD_SRC_ANALOG: cec_msg_record_on_analog(msg, rec_src->analog.ana_bcast_type, rec_src->analog.ana_freq, rec_src->analog.bcast_system); break; case CEC_OP_RECORD_SRC_EXT_PLUG: cec_msg_record_on_plug(msg, rec_src->ext_plug.plug); break; case CEC_OP_RECORD_SRC_EXT_PHYS_ADDR: cec_msg_record_on_phys_addr(msg, rec_src->ext_phys_addr.phys_addr); break; } msg->reply = reply ? CEC_MSG_RECORD_STATUS : 0; } static __inline__ void cec_ops_record_on(const struct cec_msg *msg, struct cec_op_record_src *rec_src) { rec_src->type = msg->msg[2]; switch (rec_src->type) { case CEC_OP_RECORD_SRC_OWN: break; case CEC_OP_RECORD_SRC_DIGITAL: cec_get_digital_service_id(msg->msg + 3, &rec_src->digital); break; case CEC_OP_RECORD_SRC_ANALOG: rec_src->analog.ana_bcast_type = msg->msg[3]; rec_src->analog.ana_freq = (msg->msg[4] << 8) | msg->msg[5]; rec_src->analog.bcast_system = msg->msg[6]; break; case CEC_OP_RECORD_SRC_EXT_PLUG: rec_src->ext_plug.plug = msg->msg[3]; break; case CEC_OP_RECORD_SRC_EXT_PHYS_ADDR: rec_src->ext_phys_addr.phys_addr = (msg->msg[3] << 8) | msg->msg[4]; break; } } static __inline__ void cec_msg_record_status(struct cec_msg *msg, __u8 rec_status) { msg->len = 3; msg->msg[1] = CEC_MSG_RECORD_STATUS; msg->msg[2] = rec_status; } static __inline__ void cec_ops_record_status(const struct cec_msg *msg, __u8 *rec_status) { *rec_status = msg->msg[2]; } static __inline__ void cec_msg_record_tv_screen(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_RECORD_TV_SCREEN; msg->reply = reply ? CEC_MSG_RECORD_ON : 0; } /* Timer Programming Feature */ static __inline__ void cec_msg_timer_status(struct cec_msg *msg, __u8 timer_overlap_warning, __u8 media_info, __u8 prog_info, __u8 prog_error, __u8 duration_hr, __u8 duration_min) { msg->len = 3; msg->msg[1] = CEC_MSG_TIMER_STATUS; msg->msg[2] = (timer_overlap_warning << 7) | (media_info << 5) | (prog_info ? 0x10 : 0) | (prog_info ? prog_info : prog_error); if (prog_info == CEC_OP_PROG_INFO_NOT_ENOUGH_SPACE || prog_info == CEC_OP_PROG_INFO_MIGHT_NOT_BE_ENOUGH_SPACE || prog_error == CEC_OP_PROG_ERROR_DUPLICATE) { msg->len += 2; msg->msg[3] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[4] = ((duration_min / 10) << 4) | (duration_min % 10); } } static __inline__ void cec_ops_timer_status(const struct cec_msg *msg, __u8 *timer_overlap_warning, __u8 *media_info, __u8 *prog_info, __u8 *prog_error, __u8 *duration_hr, __u8 *duration_min) { *timer_overlap_warning = msg->msg[2] >> 7; *media_info = (msg->msg[2] >> 5) & 3; if (msg->msg[2] & 0x10) { *prog_info = msg->msg[2] & 0xf; *prog_error = 0; } else { *prog_info = 0; *prog_error = msg->msg[2] & 0xf; } if (*prog_info == CEC_OP_PROG_INFO_NOT_ENOUGH_SPACE || *prog_info == CEC_OP_PROG_INFO_MIGHT_NOT_BE_ENOUGH_SPACE || *prog_error == CEC_OP_PROG_ERROR_DUPLICATE) { *duration_hr = (msg->msg[3] >> 4) * 10 + (msg->msg[3] & 0xf); *duration_min = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); } else { *duration_hr = *duration_min = 0; } } static __inline__ void cec_msg_timer_cleared_status(struct cec_msg *msg, __u8 timer_cleared_status) { msg->len = 3; msg->msg[1] = CEC_MSG_TIMER_CLEARED_STATUS; msg->msg[2] = timer_cleared_status; } static __inline__ void cec_ops_timer_cleared_status(const struct cec_msg *msg, __u8 *timer_cleared_status) { *timer_cleared_status = msg->msg[2]; } static __inline__ void cec_msg_clear_analogue_timer(struct cec_msg *msg, int reply, __u8 day, __u8 month, __u8 start_hr, __u8 start_min, __u8 duration_hr, __u8 duration_min, __u8 recording_seq, __u8 ana_bcast_type, __u16 ana_freq, __u8 bcast_system) { msg->len = 13; msg->msg[1] = CEC_MSG_CLEAR_ANALOGUE_TIMER; msg->msg[2] = day; msg->msg[3] = month; /* Hours and minutes are in BCD format */ msg->msg[4] = ((start_hr / 10) << 4) | (start_hr % 10); msg->msg[5] = ((start_min / 10) << 4) | (start_min % 10); msg->msg[6] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[7] = ((duration_min / 10) << 4) | (duration_min % 10); msg->msg[8] = recording_seq; msg->msg[9] = ana_bcast_type; msg->msg[10] = ana_freq >> 8; msg->msg[11] = ana_freq & 0xff; msg->msg[12] = bcast_system; msg->reply = reply ? CEC_MSG_TIMER_CLEARED_STATUS : 0; } static __inline__ void cec_ops_clear_analogue_timer(const struct cec_msg *msg, __u8 *day, __u8 *month, __u8 *start_hr, __u8 *start_min, __u8 *duration_hr, __u8 *duration_min, __u8 *recording_seq, __u8 *ana_bcast_type, __u16 *ana_freq, __u8 *bcast_system) { *day = msg->msg[2]; *month = msg->msg[3]; /* Hours and minutes are in BCD format */ *start_hr = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); *start_min = (msg->msg[5] >> 4) * 10 + (msg->msg[5] & 0xf); *duration_hr = (msg->msg[6] >> 4) * 10 + (msg->msg[6] & 0xf); *duration_min = (msg->msg[7] >> 4) * 10 + (msg->msg[7] & 0xf); *recording_seq = msg->msg[8]; *ana_bcast_type = msg->msg[9]; *ana_freq = (msg->msg[10] << 8) | msg->msg[11]; *bcast_system = msg->msg[12]; } static __inline__ void cec_msg_clear_digital_timer(struct cec_msg *msg, int reply, __u8 day, __u8 month, __u8 start_hr, __u8 start_min, __u8 duration_hr, __u8 duration_min, __u8 recording_seq, const struct cec_op_digital_service_id *digital) { msg->len = 16; msg->reply = reply ? CEC_MSG_TIMER_CLEARED_STATUS : 0; msg->msg[1] = CEC_MSG_CLEAR_DIGITAL_TIMER; msg->msg[2] = day; msg->msg[3] = month; /* Hours and minutes are in BCD format */ msg->msg[4] = ((start_hr / 10) << 4) | (start_hr % 10); msg->msg[5] = ((start_min / 10) << 4) | (start_min % 10); msg->msg[6] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[7] = ((duration_min / 10) << 4) | (duration_min % 10); msg->msg[8] = recording_seq; cec_set_digital_service_id(msg->msg + 9, digital); } static __inline__ void cec_ops_clear_digital_timer(const struct cec_msg *msg, __u8 *day, __u8 *month, __u8 *start_hr, __u8 *start_min, __u8 *duration_hr, __u8 *duration_min, __u8 *recording_seq, struct cec_op_digital_service_id *digital) { *day = msg->msg[2]; *month = msg->msg[3]; /* Hours and minutes are in BCD format */ *start_hr = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); *start_min = (msg->msg[5] >> 4) * 10 + (msg->msg[5] & 0xf); *duration_hr = (msg->msg[6] >> 4) * 10 + (msg->msg[6] & 0xf); *duration_min = (msg->msg[7] >> 4) * 10 + (msg->msg[7] & 0xf); *recording_seq = msg->msg[8]; cec_get_digital_service_id(msg->msg + 9, digital); } static __inline__ void cec_msg_clear_ext_timer(struct cec_msg *msg, int reply, __u8 day, __u8 month, __u8 start_hr, __u8 start_min, __u8 duration_hr, __u8 duration_min, __u8 recording_seq, __u8 ext_src_spec, __u8 plug, __u16 phys_addr) { msg->len = 13; msg->msg[1] = CEC_MSG_CLEAR_EXT_TIMER; msg->msg[2] = day; msg->msg[3] = month; /* Hours and minutes are in BCD format */ msg->msg[4] = ((start_hr / 10) << 4) | (start_hr % 10); msg->msg[5] = ((start_min / 10) << 4) | (start_min % 10); msg->msg[6] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[7] = ((duration_min / 10) << 4) | (duration_min % 10); msg->msg[8] = recording_seq; msg->msg[9] = ext_src_spec; msg->msg[10] = plug; msg->msg[11] = phys_addr >> 8; msg->msg[12] = phys_addr & 0xff; msg->reply = reply ? CEC_MSG_TIMER_CLEARED_STATUS : 0; } static __inline__ void cec_ops_clear_ext_timer(const struct cec_msg *msg, __u8 *day, __u8 *month, __u8 *start_hr, __u8 *start_min, __u8 *duration_hr, __u8 *duration_min, __u8 *recording_seq, __u8 *ext_src_spec, __u8 *plug, __u16 *phys_addr) { *day = msg->msg[2]; *month = msg->msg[3]; /* Hours and minutes are in BCD format */ *start_hr = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); *start_min = (msg->msg[5] >> 4) * 10 + (msg->msg[5] & 0xf); *duration_hr = (msg->msg[6] >> 4) * 10 + (msg->msg[6] & 0xf); *duration_min = (msg->msg[7] >> 4) * 10 + (msg->msg[7] & 0xf); *recording_seq = msg->msg[8]; *ext_src_spec = msg->msg[9]; *plug = msg->msg[10]; *phys_addr = (msg->msg[11] << 8) | msg->msg[12]; } static __inline__ void cec_msg_set_analogue_timer(struct cec_msg *msg, int reply, __u8 day, __u8 month, __u8 start_hr, __u8 start_min, __u8 duration_hr, __u8 duration_min, __u8 recording_seq, __u8 ana_bcast_type, __u16 ana_freq, __u8 bcast_system) { msg->len = 13; msg->msg[1] = CEC_MSG_SET_ANALOGUE_TIMER; msg->msg[2] = day; msg->msg[3] = month; /* Hours and minutes are in BCD format */ msg->msg[4] = ((start_hr / 10) << 4) | (start_hr % 10); msg->msg[5] = ((start_min / 10) << 4) | (start_min % 10); msg->msg[6] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[7] = ((duration_min / 10) << 4) | (duration_min % 10); msg->msg[8] = recording_seq; msg->msg[9] = ana_bcast_type; msg->msg[10] = ana_freq >> 8; msg->msg[11] = ana_freq & 0xff; msg->msg[12] = bcast_system; msg->reply = reply ? CEC_MSG_TIMER_STATUS : 0; } static __inline__ void cec_ops_set_analogue_timer(const struct cec_msg *msg, __u8 *day, __u8 *month, __u8 *start_hr, __u8 *start_min, __u8 *duration_hr, __u8 *duration_min, __u8 *recording_seq, __u8 *ana_bcast_type, __u16 *ana_freq, __u8 *bcast_system) { *day = msg->msg[2]; *month = msg->msg[3]; /* Hours and minutes are in BCD format */ *start_hr = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); *start_min = (msg->msg[5] >> 4) * 10 + (msg->msg[5] & 0xf); *duration_hr = (msg->msg[6] >> 4) * 10 + (msg->msg[6] & 0xf); *duration_min = (msg->msg[7] >> 4) * 10 + (msg->msg[7] & 0xf); *recording_seq = msg->msg[8]; *ana_bcast_type = msg->msg[9]; *ana_freq = (msg->msg[10] << 8) | msg->msg[11]; *bcast_system = msg->msg[12]; } static __inline__ void cec_msg_set_digital_timer(struct cec_msg *msg, int reply, __u8 day, __u8 month, __u8 start_hr, __u8 start_min, __u8 duration_hr, __u8 duration_min, __u8 recording_seq, const struct cec_op_digital_service_id *digital) { msg->len = 16; msg->reply = reply ? CEC_MSG_TIMER_STATUS : 0; msg->msg[1] = CEC_MSG_SET_DIGITAL_TIMER; msg->msg[2] = day; msg->msg[3] = month; /* Hours and minutes are in BCD format */ msg->msg[4] = ((start_hr / 10) << 4) | (start_hr % 10); msg->msg[5] = ((start_min / 10) << 4) | (start_min % 10); msg->msg[6] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[7] = ((duration_min / 10) << 4) | (duration_min % 10); msg->msg[8] = recording_seq; cec_set_digital_service_id(msg->msg + 9, digital); } static __inline__ void cec_ops_set_digital_timer(const struct cec_msg *msg, __u8 *day, __u8 *month, __u8 *start_hr, __u8 *start_min, __u8 *duration_hr, __u8 *duration_min, __u8 *recording_seq, struct cec_op_digital_service_id *digital) { *day = msg->msg[2]; *month = msg->msg[3]; /* Hours and minutes are in BCD format */ *start_hr = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); *start_min = (msg->msg[5] >> 4) * 10 + (msg->msg[5] & 0xf); *duration_hr = (msg->msg[6] >> 4) * 10 + (msg->msg[6] & 0xf); *duration_min = (msg->msg[7] >> 4) * 10 + (msg->msg[7] & 0xf); *recording_seq = msg->msg[8]; cec_get_digital_service_id(msg->msg + 9, digital); } static __inline__ void cec_msg_set_ext_timer(struct cec_msg *msg, int reply, __u8 day, __u8 month, __u8 start_hr, __u8 start_min, __u8 duration_hr, __u8 duration_min, __u8 recording_seq, __u8 ext_src_spec, __u8 plug, __u16 phys_addr) { msg->len = 13; msg->msg[1] = CEC_MSG_SET_EXT_TIMER; msg->msg[2] = day; msg->msg[3] = month; /* Hours and minutes are in BCD format */ msg->msg[4] = ((start_hr / 10) << 4) | (start_hr % 10); msg->msg[5] = ((start_min / 10) << 4) | (start_min % 10); msg->msg[6] = ((duration_hr / 10) << 4) | (duration_hr % 10); msg->msg[7] = ((duration_min / 10) << 4) | (duration_min % 10); msg->msg[8] = recording_seq; msg->msg[9] = ext_src_spec; msg->msg[10] = plug; msg->msg[11] = phys_addr >> 8; msg->msg[12] = phys_addr & 0xff; msg->reply = reply ? CEC_MSG_TIMER_STATUS : 0; } static __inline__ void cec_ops_set_ext_timer(const struct cec_msg *msg, __u8 *day, __u8 *month, __u8 *start_hr, __u8 *start_min, __u8 *duration_hr, __u8 *duration_min, __u8 *recording_seq, __u8 *ext_src_spec, __u8 *plug, __u16 *phys_addr) { *day = msg->msg[2]; *month = msg->msg[3]; /* Hours and minutes are in BCD format */ *start_hr = (msg->msg[4] >> 4) * 10 + (msg->msg[4] & 0xf); *start_min = (msg->msg[5] >> 4) * 10 + (msg->msg[5] & 0xf); *duration_hr = (msg->msg[6] >> 4) * 10 + (msg->msg[6] & 0xf); *duration_min = (msg->msg[7] >> 4) * 10 + (msg->msg[7] & 0xf); *recording_seq = msg->msg[8]; *ext_src_spec = msg->msg[9]; *plug = msg->msg[10]; *phys_addr = (msg->msg[11] << 8) | msg->msg[12]; } static __inline__ void cec_msg_set_timer_program_title(struct cec_msg *msg, const char *prog_title) { unsigned int len = strlen(prog_title); if (len > 14) len = 14; msg->len = 2 + len; msg->msg[1] = CEC_MSG_SET_TIMER_PROGRAM_TITLE; memcpy(msg->msg + 2, prog_title, len); } static __inline__ void cec_ops_set_timer_program_title(const struct cec_msg *msg, char *prog_title) { unsigned int len = msg->len > 2 ? msg->len - 2 : 0; if (len > 14) len = 14; memcpy(prog_title, msg->msg + 2, len); prog_title[len] = '\0'; } /* System Information Feature */ static __inline__ void cec_msg_cec_version(struct cec_msg *msg, __u8 cec_version) { msg->len = 3; msg->msg[1] = CEC_MSG_CEC_VERSION; msg->msg[2] = cec_version; } static __inline__ void cec_ops_cec_version(const struct cec_msg *msg, __u8 *cec_version) { *cec_version = msg->msg[2]; } static __inline__ void cec_msg_get_cec_version(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GET_CEC_VERSION; msg->reply = reply ? CEC_MSG_CEC_VERSION : 0; } static __inline__ void cec_msg_report_physical_addr(struct cec_msg *msg, __u16 phys_addr, __u8 prim_devtype) { msg->len = 5; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_REPORT_PHYSICAL_ADDR; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; msg->msg[4] = prim_devtype; } static __inline__ void cec_ops_report_physical_addr(const struct cec_msg *msg, __u16 *phys_addr, __u8 *prim_devtype) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *prim_devtype = msg->msg[4]; } static __inline__ void cec_msg_give_physical_addr(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_PHYSICAL_ADDR; msg->reply = reply ? CEC_MSG_REPORT_PHYSICAL_ADDR : 0; } static __inline__ void cec_msg_set_menu_language(struct cec_msg *msg, const char *language) { msg->len = 5; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_SET_MENU_LANGUAGE; memcpy(msg->msg + 2, language, 3); } static __inline__ void cec_ops_set_menu_language(const struct cec_msg *msg, char *language) { memcpy(language, msg->msg + 2, 3); language[3] = '\0'; } static __inline__ void cec_msg_get_menu_language(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GET_MENU_LANGUAGE; msg->reply = reply ? CEC_MSG_SET_MENU_LANGUAGE : 0; } /* * Assumes a single RC Profile byte and a single Device Features byte, * i.e. no extended features are supported by this helper function. * * As of CEC 2.0 no extended features are defined, should those be added * in the future, then this function needs to be adapted or a new function * should be added. */ static __inline__ void cec_msg_report_features(struct cec_msg *msg, __u8 cec_version, __u8 all_device_types, __u8 rc_profile, __u8 dev_features) { msg->len = 6; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_REPORT_FEATURES; msg->msg[2] = cec_version; msg->msg[3] = all_device_types; msg->msg[4] = rc_profile; msg->msg[5] = dev_features; } static __inline__ void cec_ops_report_features(const struct cec_msg *msg, __u8 *cec_version, __u8 *all_device_types, const __u8 **rc_profile, const __u8 **dev_features) { const __u8 *p = &msg->msg[4]; *cec_version = msg->msg[2]; *all_device_types = msg->msg[3]; *rc_profile = p; *dev_features = NULL; while (p < &msg->msg[14] && (*p & CEC_OP_FEAT_EXT)) p++; if (!(*p & CEC_OP_FEAT_EXT)) { *dev_features = p + 1; while (p < &msg->msg[15] && (*p & CEC_OP_FEAT_EXT)) p++; } if (*p & CEC_OP_FEAT_EXT) *rc_profile = *dev_features = NULL; } static __inline__ void cec_msg_give_features(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_FEATURES; msg->reply = reply ? CEC_MSG_REPORT_FEATURES : 0; } /* Deck Control Feature */ static __inline__ void cec_msg_deck_control(struct cec_msg *msg, __u8 deck_control_mode) { msg->len = 3; msg->msg[1] = CEC_MSG_DECK_CONTROL; msg->msg[2] = deck_control_mode; } static __inline__ void cec_ops_deck_control(const struct cec_msg *msg, __u8 *deck_control_mode) { *deck_control_mode = msg->msg[2]; } static __inline__ void cec_msg_deck_status(struct cec_msg *msg, __u8 deck_info) { msg->len = 3; msg->msg[1] = CEC_MSG_DECK_STATUS; msg->msg[2] = deck_info; } static __inline__ void cec_ops_deck_status(const struct cec_msg *msg, __u8 *deck_info) { *deck_info = msg->msg[2]; } static __inline__ void cec_msg_give_deck_status(struct cec_msg *msg, int reply, __u8 status_req) { msg->len = 3; msg->msg[1] = CEC_MSG_GIVE_DECK_STATUS; msg->msg[2] = status_req; msg->reply = reply ? CEC_MSG_DECK_STATUS : 0; } static __inline__ void cec_ops_give_deck_status(const struct cec_msg *msg, __u8 *status_req) { *status_req = msg->msg[2]; } static __inline__ void cec_msg_play(struct cec_msg *msg, __u8 play_mode) { msg->len = 3; msg->msg[1] = CEC_MSG_PLAY; msg->msg[2] = play_mode; } static __inline__ void cec_ops_play(const struct cec_msg *msg, __u8 *play_mode) { *play_mode = msg->msg[2]; } /* Tuner Control Feature */ struct cec_op_tuner_device_info { __u8 rec_flag; __u8 tuner_display_info; __u8 is_analog; union { struct cec_op_digital_service_id digital; struct { __u8 ana_bcast_type; __u16 ana_freq; __u8 bcast_system; } analog; }; }; static __inline__ void cec_msg_tuner_device_status_analog(struct cec_msg *msg, __u8 rec_flag, __u8 tuner_display_info, __u8 ana_bcast_type, __u16 ana_freq, __u8 bcast_system) { msg->len = 7; msg->msg[1] = CEC_MSG_TUNER_DEVICE_STATUS; msg->msg[2] = (rec_flag << 7) | tuner_display_info; msg->msg[3] = ana_bcast_type; msg->msg[4] = ana_freq >> 8; msg->msg[5] = ana_freq & 0xff; msg->msg[6] = bcast_system; } static __inline__ void cec_msg_tuner_device_status_digital(struct cec_msg *msg, __u8 rec_flag, __u8 tuner_display_info, const struct cec_op_digital_service_id *digital) { msg->len = 10; msg->msg[1] = CEC_MSG_TUNER_DEVICE_STATUS; msg->msg[2] = (rec_flag << 7) | tuner_display_info; cec_set_digital_service_id(msg->msg + 3, digital); } static __inline__ void cec_msg_tuner_device_status(struct cec_msg *msg, const struct cec_op_tuner_device_info *tuner_dev_info) { if (tuner_dev_info->is_analog) cec_msg_tuner_device_status_analog(msg, tuner_dev_info->rec_flag, tuner_dev_info->tuner_display_info, tuner_dev_info->analog.ana_bcast_type, tuner_dev_info->analog.ana_freq, tuner_dev_info->analog.bcast_system); else cec_msg_tuner_device_status_digital(msg, tuner_dev_info->rec_flag, tuner_dev_info->tuner_display_info, &tuner_dev_info->digital); } static __inline__ void cec_ops_tuner_device_status(const struct cec_msg *msg, struct cec_op_tuner_device_info *tuner_dev_info) { tuner_dev_info->is_analog = msg->len < 10; tuner_dev_info->rec_flag = msg->msg[2] >> 7; tuner_dev_info->tuner_display_info = msg->msg[2] & 0x7f; if (tuner_dev_info->is_analog) { tuner_dev_info->analog.ana_bcast_type = msg->msg[3]; tuner_dev_info->analog.ana_freq = (msg->msg[4] << 8) | msg->msg[5]; tuner_dev_info->analog.bcast_system = msg->msg[6]; return; } cec_get_digital_service_id(msg->msg + 3, &tuner_dev_info->digital); } static __inline__ void cec_msg_give_tuner_device_status(struct cec_msg *msg, int reply, __u8 status_req) { msg->len = 3; msg->msg[1] = CEC_MSG_GIVE_TUNER_DEVICE_STATUS; msg->msg[2] = status_req; msg->reply = reply ? CEC_MSG_TUNER_DEVICE_STATUS : 0; } static __inline__ void cec_ops_give_tuner_device_status(const struct cec_msg *msg, __u8 *status_req) { *status_req = msg->msg[2]; } static __inline__ void cec_msg_select_analogue_service(struct cec_msg *msg, __u8 ana_bcast_type, __u16 ana_freq, __u8 bcast_system) { msg->len = 6; msg->msg[1] = CEC_MSG_SELECT_ANALOGUE_SERVICE; msg->msg[2] = ana_bcast_type; msg->msg[3] = ana_freq >> 8; msg->msg[4] = ana_freq & 0xff; msg->msg[5] = bcast_system; } static __inline__ void cec_ops_select_analogue_service(const struct cec_msg *msg, __u8 *ana_bcast_type, __u16 *ana_freq, __u8 *bcast_system) { *ana_bcast_type = msg->msg[2]; *ana_freq = (msg->msg[3] << 8) | msg->msg[4]; *bcast_system = msg->msg[5]; } static __inline__ void cec_msg_select_digital_service(struct cec_msg *msg, const struct cec_op_digital_service_id *digital) { msg->len = 9; msg->msg[1] = CEC_MSG_SELECT_DIGITAL_SERVICE; cec_set_digital_service_id(msg->msg + 2, digital); } static __inline__ void cec_ops_select_digital_service(const struct cec_msg *msg, struct cec_op_digital_service_id *digital) { cec_get_digital_service_id(msg->msg + 2, digital); } static __inline__ void cec_msg_tuner_step_decrement(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_TUNER_STEP_DECREMENT; } static __inline__ void cec_msg_tuner_step_increment(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_TUNER_STEP_INCREMENT; } /* Vendor Specific Commands Feature */ static __inline__ void cec_msg_device_vendor_id(struct cec_msg *msg, __u32 vendor_id) { msg->len = 5; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_DEVICE_VENDOR_ID; msg->msg[2] = vendor_id >> 16; msg->msg[3] = (vendor_id >> 8) & 0xff; msg->msg[4] = vendor_id & 0xff; } static __inline__ void cec_ops_device_vendor_id(const struct cec_msg *msg, __u32 *vendor_id) { *vendor_id = (msg->msg[2] << 16) | (msg->msg[3] << 8) | msg->msg[4]; } static __inline__ void cec_msg_give_device_vendor_id(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_DEVICE_VENDOR_ID; msg->reply = reply ? CEC_MSG_DEVICE_VENDOR_ID : 0; } static __inline__ void cec_msg_vendor_command(struct cec_msg *msg, __u8 size, const __u8 *vendor_cmd) { if (size > 14) size = 14; msg->len = 2 + size; msg->msg[1] = CEC_MSG_VENDOR_COMMAND; memcpy(msg->msg + 2, vendor_cmd, size); } static __inline__ void cec_ops_vendor_command(const struct cec_msg *msg, __u8 *size, const __u8 **vendor_cmd) { *size = msg->len - 2; if (*size > 14) *size = 14; *vendor_cmd = msg->msg + 2; } static __inline__ void cec_msg_vendor_command_with_id(struct cec_msg *msg, __u32 vendor_id, __u8 size, const __u8 *vendor_cmd) { if (size > 11) size = 11; msg->len = 5 + size; msg->msg[1] = CEC_MSG_VENDOR_COMMAND_WITH_ID; msg->msg[2] = vendor_id >> 16; msg->msg[3] = (vendor_id >> 8) & 0xff; msg->msg[4] = vendor_id & 0xff; memcpy(msg->msg + 5, vendor_cmd, size); } static __inline__ void cec_ops_vendor_command_with_id(const struct cec_msg *msg, __u32 *vendor_id, __u8 *size, const __u8 **vendor_cmd) { *size = msg->len - 5; if (*size > 11) *size = 11; *vendor_id = (msg->msg[2] << 16) | (msg->msg[3] << 8) | msg->msg[4]; *vendor_cmd = msg->msg + 5; } static __inline__ void cec_msg_vendor_remote_button_down(struct cec_msg *msg, __u8 size, const __u8 *rc_code) { if (size > 14) size = 14; msg->len = 2 + size; msg->msg[1] = CEC_MSG_VENDOR_REMOTE_BUTTON_DOWN; memcpy(msg->msg + 2, rc_code, size); } static __inline__ void cec_ops_vendor_remote_button_down(const struct cec_msg *msg, __u8 *size, const __u8 **rc_code) { *size = msg->len - 2; if (*size > 14) *size = 14; *rc_code = msg->msg + 2; } static __inline__ void cec_msg_vendor_remote_button_up(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_VENDOR_REMOTE_BUTTON_UP; } /* OSD Display Feature */ static __inline__ void cec_msg_set_osd_string(struct cec_msg *msg, __u8 disp_ctl, const char *osd) { unsigned int len = strlen(osd); if (len > 13) len = 13; msg->len = 3 + len; msg->msg[1] = CEC_MSG_SET_OSD_STRING; msg->msg[2] = disp_ctl; memcpy(msg->msg + 3, osd, len); } static __inline__ void cec_ops_set_osd_string(const struct cec_msg *msg, __u8 *disp_ctl, char *osd) { unsigned int len = msg->len > 3 ? msg->len - 3 : 0; *disp_ctl = msg->msg[2]; if (len > 13) len = 13; memcpy(osd, msg->msg + 3, len); osd[len] = '\0'; } /* Device OSD Transfer Feature */ static __inline__ void cec_msg_set_osd_name(struct cec_msg *msg, const char *name) { unsigned int len = strlen(name); if (len > 14) len = 14; msg->len = 2 + len; msg->msg[1] = CEC_MSG_SET_OSD_NAME; memcpy(msg->msg + 2, name, len); } static __inline__ void cec_ops_set_osd_name(const struct cec_msg *msg, char *name) { unsigned int len = msg->len > 2 ? msg->len - 2 : 0; if (len > 14) len = 14; memcpy(name, msg->msg + 2, len); name[len] = '\0'; } static __inline__ void cec_msg_give_osd_name(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_OSD_NAME; msg->reply = reply ? CEC_MSG_SET_OSD_NAME : 0; } /* Device Menu Control Feature */ static __inline__ void cec_msg_menu_status(struct cec_msg *msg, __u8 menu_state) { msg->len = 3; msg->msg[1] = CEC_MSG_MENU_STATUS; msg->msg[2] = menu_state; } static __inline__ void cec_ops_menu_status(const struct cec_msg *msg, __u8 *menu_state) { *menu_state = msg->msg[2]; } static __inline__ void cec_msg_menu_request(struct cec_msg *msg, int reply, __u8 menu_req) { msg->len = 3; msg->msg[1] = CEC_MSG_MENU_REQUEST; msg->msg[2] = menu_req; msg->reply = reply ? CEC_MSG_MENU_STATUS : 0; } static __inline__ void cec_ops_menu_request(const struct cec_msg *msg, __u8 *menu_req) { *menu_req = msg->msg[2]; } struct cec_op_ui_command { __u8 ui_cmd; __u8 has_opt_arg; union { struct cec_op_channel_data channel_identifier; __u8 ui_broadcast_type; __u8 ui_sound_presentation_control; __u8 play_mode; __u8 ui_function_media; __u8 ui_function_select_av_input; __u8 ui_function_select_audio_input; }; }; static __inline__ void cec_msg_user_control_pressed(struct cec_msg *msg, const struct cec_op_ui_command *ui_cmd) { msg->len = 3; msg->msg[1] = CEC_MSG_USER_CONTROL_PRESSED; msg->msg[2] = ui_cmd->ui_cmd; if (!ui_cmd->has_opt_arg) return; switch (ui_cmd->ui_cmd) { case 0x56: case 0x57: case 0x60: case 0x68: case 0x69: case 0x6a: /* The optional operand is one byte for all these ui commands */ msg->len++; msg->msg[3] = ui_cmd->play_mode; break; case 0x67: msg->len += 4; msg->msg[3] = (ui_cmd->channel_identifier.channel_number_fmt << 2) | (ui_cmd->channel_identifier.major >> 8); msg->msg[4] = ui_cmd->channel_identifier.major & 0xff; msg->msg[5] = ui_cmd->channel_identifier.minor >> 8; msg->msg[6] = ui_cmd->channel_identifier.minor & 0xff; break; } } static __inline__ void cec_ops_user_control_pressed(const struct cec_msg *msg, struct cec_op_ui_command *ui_cmd) { ui_cmd->ui_cmd = msg->msg[2]; ui_cmd->has_opt_arg = 0; if (msg->len == 3) return; switch (ui_cmd->ui_cmd) { case 0x56: case 0x57: case 0x60: case 0x68: case 0x69: case 0x6a: /* The optional operand is one byte for all these ui commands */ ui_cmd->play_mode = msg->msg[3]; ui_cmd->has_opt_arg = 1; break; case 0x67: if (msg->len < 7) break; ui_cmd->has_opt_arg = 1; ui_cmd->channel_identifier.channel_number_fmt = msg->msg[3] >> 2; ui_cmd->channel_identifier.major = ((msg->msg[3] & 3) << 6) | msg->msg[4]; ui_cmd->channel_identifier.minor = (msg->msg[5] << 8) | msg->msg[6]; break; } } static __inline__ void cec_msg_user_control_released(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_USER_CONTROL_RELEASED; } /* Remote Control Passthrough Feature */ /* Power Status Feature */ static __inline__ void cec_msg_report_power_status(struct cec_msg *msg, __u8 pwr_state) { msg->len = 3; msg->msg[1] = CEC_MSG_REPORT_POWER_STATUS; msg->msg[2] = pwr_state; } static __inline__ void cec_ops_report_power_status(const struct cec_msg *msg, __u8 *pwr_state) { *pwr_state = msg->msg[2]; } static __inline__ void cec_msg_give_device_power_status(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_DEVICE_POWER_STATUS; msg->reply = reply ? CEC_MSG_REPORT_POWER_STATUS : 0; } /* General Protocol Messages */ static __inline__ void cec_msg_feature_abort(struct cec_msg *msg, __u8 abort_msg, __u8 reason) { msg->len = 4; msg->msg[1] = CEC_MSG_FEATURE_ABORT; msg->msg[2] = abort_msg; msg->msg[3] = reason; } static __inline__ void cec_ops_feature_abort(const struct cec_msg *msg, __u8 *abort_msg, __u8 *reason) { *abort_msg = msg->msg[2]; *reason = msg->msg[3]; } /* This changes the current message into a feature abort message */ static __inline__ void cec_msg_reply_feature_abort(struct cec_msg *msg, __u8 reason) { cec_msg_set_reply_to(msg, msg); msg->len = 4; msg->msg[2] = msg->msg[1]; msg->msg[3] = reason; msg->msg[1] = CEC_MSG_FEATURE_ABORT; } static __inline__ void cec_msg_abort(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_ABORT; } /* System Audio Control Feature */ static __inline__ void cec_msg_report_audio_status(struct cec_msg *msg, __u8 aud_mute_status, __u8 aud_vol_status) { msg->len = 3; msg->msg[1] = CEC_MSG_REPORT_AUDIO_STATUS; msg->msg[2] = (aud_mute_status << 7) | (aud_vol_status & 0x7f); } static __inline__ void cec_ops_report_audio_status(const struct cec_msg *msg, __u8 *aud_mute_status, __u8 *aud_vol_status) { *aud_mute_status = msg->msg[2] >> 7; *aud_vol_status = msg->msg[2] & 0x7f; } static __inline__ void cec_msg_give_audio_status(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_AUDIO_STATUS; msg->reply = reply ? CEC_MSG_REPORT_AUDIO_STATUS : 0; } static __inline__ void cec_msg_set_system_audio_mode(struct cec_msg *msg, __u8 sys_aud_status) { msg->len = 3; msg->msg[1] = CEC_MSG_SET_SYSTEM_AUDIO_MODE; msg->msg[2] = sys_aud_status; } static __inline__ void cec_ops_set_system_audio_mode(const struct cec_msg *msg, __u8 *sys_aud_status) { *sys_aud_status = msg->msg[2]; } static __inline__ void cec_msg_system_audio_mode_request(struct cec_msg *msg, int reply, __u16 phys_addr) { msg->len = phys_addr == 0xffff ? 2 : 4; msg->msg[1] = CEC_MSG_SYSTEM_AUDIO_MODE_REQUEST; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; msg->reply = reply ? CEC_MSG_SET_SYSTEM_AUDIO_MODE : 0; } static __inline__ void cec_ops_system_audio_mode_request(const struct cec_msg *msg, __u16 *phys_addr) { if (msg->len < 4) *phys_addr = 0xffff; else *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } static __inline__ void cec_msg_system_audio_mode_status(struct cec_msg *msg, __u8 sys_aud_status) { msg->len = 3; msg->msg[1] = CEC_MSG_SYSTEM_AUDIO_MODE_STATUS; msg->msg[2] = sys_aud_status; } static __inline__ void cec_ops_system_audio_mode_status(const struct cec_msg *msg, __u8 *sys_aud_status) { *sys_aud_status = msg->msg[2]; } static __inline__ void cec_msg_give_system_audio_mode_status(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_GIVE_SYSTEM_AUDIO_MODE_STATUS; msg->reply = reply ? CEC_MSG_SYSTEM_AUDIO_MODE_STATUS : 0; } static __inline__ void cec_msg_report_short_audio_descriptor(struct cec_msg *msg, __u8 num_descriptors, const __u32 *descriptors) { unsigned int i; if (num_descriptors > 4) num_descriptors = 4; msg->len = 2 + num_descriptors * 3; msg->msg[1] = CEC_MSG_REPORT_SHORT_AUDIO_DESCRIPTOR; for (i = 0; i < num_descriptors; i++) { msg->msg[2 + i * 3] = (descriptors[i] >> 16) & 0xff; msg->msg[3 + i * 3] = (descriptors[i] >> 8) & 0xff; msg->msg[4 + i * 3] = descriptors[i] & 0xff; } } static __inline__ void cec_ops_report_short_audio_descriptor(const struct cec_msg *msg, __u8 *num_descriptors, __u32 *descriptors) { unsigned int i; *num_descriptors = (msg->len - 2) / 3; if (*num_descriptors > 4) *num_descriptors = 4; for (i = 0; i < *num_descriptors; i++) descriptors[i] = (msg->msg[2 + i * 3] << 16) | (msg->msg[3 + i * 3] << 8) | msg->msg[4 + i * 3]; } static __inline__ void cec_msg_request_short_audio_descriptor(struct cec_msg *msg, int reply, __u8 num_descriptors, const __u8 *audio_format_id, const __u8 *audio_format_code) { unsigned int i; if (num_descriptors > 4) num_descriptors = 4; msg->len = 2 + num_descriptors; msg->msg[1] = CEC_MSG_REQUEST_SHORT_AUDIO_DESCRIPTOR; msg->reply = reply ? CEC_MSG_REPORT_SHORT_AUDIO_DESCRIPTOR : 0; for (i = 0; i < num_descriptors; i++) msg->msg[2 + i] = (audio_format_id[i] << 6) | (audio_format_code[i] & 0x3f); } static __inline__ void cec_ops_request_short_audio_descriptor(const struct cec_msg *msg, __u8 *num_descriptors, __u8 *audio_format_id, __u8 *audio_format_code) { unsigned int i; *num_descriptors = msg->len - 2; if (*num_descriptors > 4) *num_descriptors = 4; for (i = 0; i < *num_descriptors; i++) { audio_format_id[i] = msg->msg[2 + i] >> 6; audio_format_code[i] = msg->msg[2 + i] & 0x3f; } } static __inline__ void cec_msg_set_audio_volume_level(struct cec_msg *msg, __u8 audio_volume_level) { msg->len = 3; msg->msg[1] = CEC_MSG_SET_AUDIO_VOLUME_LEVEL; msg->msg[2] = audio_volume_level; } static __inline__ void cec_ops_set_audio_volume_level(const struct cec_msg *msg, __u8 *audio_volume_level) { *audio_volume_level = msg->msg[2]; } /* Audio Rate Control Feature */ static __inline__ void cec_msg_set_audio_rate(struct cec_msg *msg, __u8 audio_rate) { msg->len = 3; msg->msg[1] = CEC_MSG_SET_AUDIO_RATE; msg->msg[2] = audio_rate; } static __inline__ void cec_ops_set_audio_rate(const struct cec_msg *msg, __u8 *audio_rate) { *audio_rate = msg->msg[2]; } /* Audio Return Channel Control Feature */ static __inline__ void cec_msg_report_arc_initiated(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_REPORT_ARC_INITIATED; } static __inline__ void cec_msg_initiate_arc(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_INITIATE_ARC; msg->reply = reply ? CEC_MSG_REPORT_ARC_INITIATED : 0; } static __inline__ void cec_msg_request_arc_initiation(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_REQUEST_ARC_INITIATION; msg->reply = reply ? CEC_MSG_INITIATE_ARC : 0; } static __inline__ void cec_msg_report_arc_terminated(struct cec_msg *msg) { msg->len = 2; msg->msg[1] = CEC_MSG_REPORT_ARC_TERMINATED; } static __inline__ void cec_msg_terminate_arc(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_TERMINATE_ARC; msg->reply = reply ? CEC_MSG_REPORT_ARC_TERMINATED : 0; } static __inline__ void cec_msg_request_arc_termination(struct cec_msg *msg, int reply) { msg->len = 2; msg->msg[1] = CEC_MSG_REQUEST_ARC_TERMINATION; msg->reply = reply ? CEC_MSG_TERMINATE_ARC : 0; } /* Dynamic Audio Lipsync Feature */ /* Only for CEC 2.0 and up */ static __inline__ void cec_msg_report_current_latency(struct cec_msg *msg, __u16 phys_addr, __u8 video_latency, __u8 low_latency_mode, __u8 audio_out_compensated, __u8 audio_out_delay) { msg->len = 6; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_REPORT_CURRENT_LATENCY; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; msg->msg[4] = video_latency; msg->msg[5] = (low_latency_mode << 2) | audio_out_compensated; if (audio_out_compensated == 3) msg->msg[msg->len++] = audio_out_delay; } static __inline__ void cec_ops_report_current_latency(const struct cec_msg *msg, __u16 *phys_addr, __u8 *video_latency, __u8 *low_latency_mode, __u8 *audio_out_compensated, __u8 *audio_out_delay) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *video_latency = msg->msg[4]; *low_latency_mode = (msg->msg[5] >> 2) & 1; *audio_out_compensated = msg->msg[5] & 3; if (*audio_out_compensated == 3 && msg->len >= 7) *audio_out_delay = msg->msg[6]; else *audio_out_delay = 0; } static __inline__ void cec_msg_request_current_latency(struct cec_msg *msg, int reply, __u16 phys_addr) { msg->len = 4; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_REQUEST_CURRENT_LATENCY; msg->msg[2] = phys_addr >> 8; msg->msg[3] = phys_addr & 0xff; msg->reply = reply ? CEC_MSG_REPORT_CURRENT_LATENCY : 0; } static __inline__ void cec_ops_request_current_latency(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } /* Capability Discovery and Control Feature */ static __inline__ void cec_msg_cdc_hec_inquire_state(struct cec_msg *msg, __u16 phys_addr1, __u16 phys_addr2) { msg->len = 9; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_INQUIRE_STATE; msg->msg[5] = phys_addr1 >> 8; msg->msg[6] = phys_addr1 & 0xff; msg->msg[7] = phys_addr2 >> 8; msg->msg[8] = phys_addr2 & 0xff; } static __inline__ void cec_ops_cdc_hec_inquire_state(const struct cec_msg *msg, __u16 *phys_addr, __u16 *phys_addr1, __u16 *phys_addr2) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *phys_addr1 = (msg->msg[5] << 8) | msg->msg[6]; *phys_addr2 = (msg->msg[7] << 8) | msg->msg[8]; } static __inline__ void cec_msg_cdc_hec_report_state(struct cec_msg *msg, __u16 target_phys_addr, __u8 hec_func_state, __u8 host_func_state, __u8 enc_func_state, __u8 cdc_errcode, __u8 has_field, __u16 hec_field) { msg->len = has_field ? 10 : 8; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_REPORT_STATE; msg->msg[5] = target_phys_addr >> 8; msg->msg[6] = target_phys_addr & 0xff; msg->msg[7] = (hec_func_state << 6) | (host_func_state << 4) | (enc_func_state << 2) | cdc_errcode; if (has_field) { msg->msg[8] = hec_field >> 8; msg->msg[9] = hec_field & 0xff; } } static __inline__ void cec_ops_cdc_hec_report_state(const struct cec_msg *msg, __u16 *phys_addr, __u16 *target_phys_addr, __u8 *hec_func_state, __u8 *host_func_state, __u8 *enc_func_state, __u8 *cdc_errcode, __u8 *has_field, __u16 *hec_field) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *target_phys_addr = (msg->msg[5] << 8) | msg->msg[6]; *hec_func_state = msg->msg[7] >> 6; *host_func_state = (msg->msg[7] >> 4) & 3; *enc_func_state = (msg->msg[7] >> 4) & 3; *cdc_errcode = msg->msg[7] & 3; *has_field = msg->len >= 10; *hec_field = *has_field ? ((msg->msg[8] << 8) | msg->msg[9]) : 0; } static __inline__ void cec_msg_cdc_hec_set_state(struct cec_msg *msg, __u16 phys_addr1, __u16 phys_addr2, __u8 hec_set_state, __u16 phys_addr3, __u16 phys_addr4, __u16 phys_addr5) { msg->len = 10; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_INQUIRE_STATE; msg->msg[5] = phys_addr1 >> 8; msg->msg[6] = phys_addr1 & 0xff; msg->msg[7] = phys_addr2 >> 8; msg->msg[8] = phys_addr2 & 0xff; msg->msg[9] = hec_set_state; if (phys_addr3 != CEC_PHYS_ADDR_INVALID) { msg->msg[msg->len++] = phys_addr3 >> 8; msg->msg[msg->len++] = phys_addr3 & 0xff; if (phys_addr4 != CEC_PHYS_ADDR_INVALID) { msg->msg[msg->len++] = phys_addr4 >> 8; msg->msg[msg->len++] = phys_addr4 & 0xff; if (phys_addr5 != CEC_PHYS_ADDR_INVALID) { msg->msg[msg->len++] = phys_addr5 >> 8; msg->msg[msg->len++] = phys_addr5 & 0xff; } } } } static __inline__ void cec_ops_cdc_hec_set_state(const struct cec_msg *msg, __u16 *phys_addr, __u16 *phys_addr1, __u16 *phys_addr2, __u8 *hec_set_state, __u16 *phys_addr3, __u16 *phys_addr4, __u16 *phys_addr5) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *phys_addr1 = (msg->msg[5] << 8) | msg->msg[6]; *phys_addr2 = (msg->msg[7] << 8) | msg->msg[8]; *hec_set_state = msg->msg[9]; *phys_addr3 = *phys_addr4 = *phys_addr5 = CEC_PHYS_ADDR_INVALID; if (msg->len >= 12) *phys_addr3 = (msg->msg[10] << 8) | msg->msg[11]; if (msg->len >= 14) *phys_addr4 = (msg->msg[12] << 8) | msg->msg[13]; if (msg->len >= 16) *phys_addr5 = (msg->msg[14] << 8) | msg->msg[15]; } static __inline__ void cec_msg_cdc_hec_set_state_adjacent(struct cec_msg *msg, __u16 phys_addr1, __u8 hec_set_state) { msg->len = 8; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_SET_STATE_ADJACENT; msg->msg[5] = phys_addr1 >> 8; msg->msg[6] = phys_addr1 & 0xff; msg->msg[7] = hec_set_state; } static __inline__ void cec_ops_cdc_hec_set_state_adjacent(const struct cec_msg *msg, __u16 *phys_addr, __u16 *phys_addr1, __u8 *hec_set_state) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *phys_addr1 = (msg->msg[5] << 8) | msg->msg[6]; *hec_set_state = msg->msg[7]; } static __inline__ void cec_msg_cdc_hec_request_deactivation(struct cec_msg *msg, __u16 phys_addr1, __u16 phys_addr2, __u16 phys_addr3) { msg->len = 11; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_REQUEST_DEACTIVATION; msg->msg[5] = phys_addr1 >> 8; msg->msg[6] = phys_addr1 & 0xff; msg->msg[7] = phys_addr2 >> 8; msg->msg[8] = phys_addr2 & 0xff; msg->msg[9] = phys_addr3 >> 8; msg->msg[10] = phys_addr3 & 0xff; } static __inline__ void cec_ops_cdc_hec_request_deactivation(const struct cec_msg *msg, __u16 *phys_addr, __u16 *phys_addr1, __u16 *phys_addr2, __u16 *phys_addr3) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *phys_addr1 = (msg->msg[5] << 8) | msg->msg[6]; *phys_addr2 = (msg->msg[7] << 8) | msg->msg[8]; *phys_addr3 = (msg->msg[9] << 8) | msg->msg[10]; } static __inline__ void cec_msg_cdc_hec_notify_alive(struct cec_msg *msg) { msg->len = 5; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_NOTIFY_ALIVE; } static __inline__ void cec_ops_cdc_hec_notify_alive(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } static __inline__ void cec_msg_cdc_hec_discover(struct cec_msg *msg) { msg->len = 5; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HEC_DISCOVER; } static __inline__ void cec_ops_cdc_hec_discover(const struct cec_msg *msg, __u16 *phys_addr) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; } static __inline__ void cec_msg_cdc_hpd_set_state(struct cec_msg *msg, __u8 input_port, __u8 hpd_state) { msg->len = 6; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HPD_SET_STATE; msg->msg[5] = (input_port << 4) | hpd_state; } static __inline__ void cec_ops_cdc_hpd_set_state(const struct cec_msg *msg, __u16 *phys_addr, __u8 *input_port, __u8 *hpd_state) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *input_port = msg->msg[5] >> 4; *hpd_state = msg->msg[5] & 0xf; } static __inline__ void cec_msg_cdc_hpd_report_state(struct cec_msg *msg, __u8 hpd_state, __u8 hpd_error) { msg->len = 6; msg->msg[0] |= 0xf; /* broadcast */ msg->msg[1] = CEC_MSG_CDC_MESSAGE; /* msg[2] and msg[3] (phys_addr) are filled in by the CEC framework */ msg->msg[4] = CEC_MSG_CDC_HPD_REPORT_STATE; msg->msg[5] = (hpd_state << 4) | hpd_error; } static __inline__ void cec_ops_cdc_hpd_report_state(const struct cec_msg *msg, __u16 *phys_addr, __u8 *hpd_state, __u8 *hpd_error) { *phys_addr = (msg->msg[2] << 8) | msg->msg[3]; *hpd_state = msg->msg[5] >> 4; *hpd_error = msg->msg[5] & 0xf; } #endif linux/nfsd/cld.h000064400000006062151027430560007557 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Upcall description for nfsdcld communication * * Copyright (c) 2012 Red Hat, Inc. * Author(s): Jeff Layton * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _NFSD_CLD_H #define _NFSD_CLD_H #include /* latest upcall version available */ #define CLD_UPCALL_VERSION 2 /* defined by RFC3530 */ #define NFS4_OPAQUE_LIMIT 1024 #ifndef SHA256_DIGEST_SIZE #define SHA256_DIGEST_SIZE 32 #endif enum cld_command { Cld_Create, /* create a record for this cm_id */ Cld_Remove, /* remove record of this cm_id */ Cld_Check, /* is this cm_id allowed? */ Cld_GraceDone, /* grace period is complete */ Cld_GraceStart, /* grace start (upload client records) */ Cld_GetVersion, /* query max supported upcall version */ }; /* representation of long-form NFSv4 client ID */ struct cld_name { __u16 cn_len; /* length of cm_id */ unsigned char cn_id[NFS4_OPAQUE_LIMIT]; /* client-provided */ } __attribute__((packed)); /* sha256 hash of the kerberos principal */ struct cld_princhash { __u8 cp_len; /* length of cp_data */ unsigned char cp_data[SHA256_DIGEST_SIZE]; /* hash of principal */ } __attribute__((packed)); struct cld_clntinfo { struct cld_name cc_name; struct cld_princhash cc_princhash; } __attribute__((packed)); /* message struct for communication with userspace */ struct cld_msg { __u8 cm_vers; /* upcall version */ __u8 cm_cmd; /* upcall command */ __s16 cm_status; /* return code */ __u32 cm_xid; /* transaction id */ union { __s64 cm_gracetime; /* grace period start time */ struct cld_name cm_name; __u8 cm_version; /* for getting max version */ } __attribute__((packed)) cm_u; } __attribute__((packed)); /* version 2 message can include hash of kerberos principal */ struct cld_msg_v2 { __u8 cm_vers; /* upcall version */ __u8 cm_cmd; /* upcall command */ __s16 cm_status; /* return code */ __u32 cm_xid; /* transaction id */ union { struct cld_name cm_name; __u8 cm_version; /* for getting max version */ struct cld_clntinfo cm_clntinfo; /* name & princ hash */ } __attribute__((packed)) cm_u; } __attribute__((packed)); struct cld_msg_hdr { __u8 cm_vers; /* upcall version */ __u8 cm_cmd; /* upcall command */ __s16 cm_status; /* return code */ __u32 cm_xid; /* transaction id */ } __attribute__((packed)); #endif /* !_NFSD_CLD_H */ linux/nfsd/stats.h000064400000000645151027430560010154 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/include/linux/nfsd/stats.h * * Statistics for NFS server. * * Copyright (C) 1995, 1996 Olaf Kirch */ #ifndef LINUX_NFSD_STATS_H #define LINUX_NFSD_STATS_H #include /* thread usage wraps very million seconds (approx one fortnight) */ #define NFSD_USAGE_WRAP (HZ*1000000) #endif /* LINUX_NFSD_STATS_H */ linux/nfsd/debug.h000064400000001340151027430560010075 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/include/linux/nfsd/debug.h * * Debugging-related stuff for nfsd * * Copyright (C) 1995 Olaf Kirch */ #ifndef LINUX_NFSD_DEBUG_H #define LINUX_NFSD_DEBUG_H #include /* * knfsd debug flags */ #define NFSDDBG_SOCK 0x0001 #define NFSDDBG_FH 0x0002 #define NFSDDBG_EXPORT 0x0004 #define NFSDDBG_SVC 0x0008 #define NFSDDBG_PROC 0x0010 #define NFSDDBG_FILEOP 0x0020 #define NFSDDBG_AUTH 0x0040 #define NFSDDBG_REPCACHE 0x0080 #define NFSDDBG_XDR 0x0100 #define NFSDDBG_LOCKD 0x0200 #define NFSDDBG_PNFS 0x0400 #define NFSDDBG_ALL 0x7FFF #define NFSDDBG_NOCHANGE 0xFFFF #endif /* LINUX_NFSD_DEBUG_H */ linux/nfsd/export.h000064400000004101151027430560010326 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/nfsd/export.h * * Public declarations for NFS exports. The definitions for the * syscall interface are in nfsctl.h * * Copyright (C) 1995-1997 Olaf Kirch */ #ifndef NFSD_EXPORT_H #define NFSD_EXPORT_H # include /* * Important limits for the exports stuff. */ #define NFSCLNT_IDMAX 1024 #define NFSCLNT_ADDRMAX 16 #define NFSCLNT_KEYMAX 32 /* * Export flags. * * Please update the expflags[] array in fs/nfsd/export.c when adding * a new flag. */ #define NFSEXP_READONLY 0x0001 #define NFSEXP_INSECURE_PORT 0x0002 #define NFSEXP_ROOTSQUASH 0x0004 #define NFSEXP_ALLSQUASH 0x0008 #define NFSEXP_ASYNC 0x0010 #define NFSEXP_GATHERED_WRITES 0x0020 #define NFSEXP_NOREADDIRPLUS 0x0040 #define NFSEXP_SECURITY_LABEL 0x0080 /* 0x100 currently unused */ #define NFSEXP_NOHIDE 0x0200 #define NFSEXP_NOSUBTREECHECK 0x0400 #define NFSEXP_NOAUTHNLM 0x0800 /* Don't authenticate NLM requests - just trust */ #define NFSEXP_MSNFS 0x1000 /* do silly things that MS clients expect; no longer supported */ #define NFSEXP_FSID 0x2000 #define NFSEXP_CROSSMOUNT 0x4000 #define NFSEXP_NOACL 0x8000 /* reserved for possible ACL related use */ /* * The NFSEXP_V4ROOT flag causes the kernel to give access only to NFSv4 * clients, and only to the single directory that is the root of the * export; further lookup and readdir operations are treated as if every * subdirectory was a mountpoint, and ignored if they are not themselves * exported. This is used by nfsd and mountd to construct the NFSv4 * pseudofilesystem, which provides access only to paths leading to each * exported filesystem. */ #define NFSEXP_V4ROOT 0x10000 #define NFSEXP_PNFS 0x20000 /* All flags that we claim to support. (Note we don't support NOACL.) */ #define NFSEXP_ALLFLAGS 0x3FEFF /* The flags that may vary depending on security flavor: */ #define NFSEXP_SECINFO_FLAGS (NFSEXP_READONLY | NFSEXP_ROOTSQUASH \ | NFSEXP_ALLSQUASH \ | NFSEXP_INSECURE_PORT) #endif /* NFSD_EXPORT_H */ linux/if_ppp.h000064400000000035151027430560007332 0ustar00#include linux/tty.h000064400000003061151027430560006677 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_TTY_H #define _LINUX_TTY_H /* * 'tty.h' defines some structures used by tty_io.c and some defines. */ #define NR_LDISCS 30 /* line disciplines */ #define N_TTY 0 #define N_SLIP 1 #define N_MOUSE 2 #define N_PPP 3 #define N_STRIP 4 #define N_AX25 5 #define N_X25 6 /* X.25 async */ #define N_6PACK 7 #define N_MASC 8 /* Reserved for Mobitex module */ #define N_R3964 9 /* Reserved for Simatic R3964 module */ #define N_PROFIBUS_FDL 10 /* Reserved for Profibus */ #define N_IRDA 11 /* Linux IrDa - http://irda.sourceforge.net/ */ #define N_SMSBLOCK 12 /* SMS block mode - for talking to GSM data */ /* cards about SMS messages */ #define N_HDLC 13 /* synchronous HDLC */ #define N_SYNC_PPP 14 /* synchronous PPP */ #define N_HCI 15 /* Bluetooth HCI UART */ #define N_GIGASET_M101 16 /* Siemens Gigaset M101 serial DECT adapter */ #define N_SLCAN 17 /* Serial / USB serial CAN Adaptors */ #define N_PPS 18 /* Pulse per Second */ #define N_V253 19 /* Codec control over voice modem */ #define N_CAIF 20 /* CAIF protocol for talking to modems */ #define N_GSM0710 21 /* GSM 0710 Mux */ #define N_TI_WL 22 /* for TI's WL BT, FM, GPS combo chips */ #define N_TRACESINK 23 /* Trace data routing for MIPI P1149.7 */ #define N_TRACEROUTER 24 /* Trace data routing for MIPI P1149.7 */ #define N_NCI 25 /* NFC NCI UART */ #define N_SPEAKUP 26 /* Speakup communication with synths */ #define N_NULL 27 /* Null ldisc used for error handling */ #endif /* _LINUX_TTY_H */ linux/atmlec.h000064400000004515151027430560007331 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ATM Lan Emulation Daemon driver interface * * Marko Kiiskila */ #ifndef _ATMLEC_H_ #define _ATMLEC_H_ #include #include #include #include #include /* ATM lec daemon control socket */ #define ATMLEC_CTRL _IO('a', ATMIOC_LANE) #define ATMLEC_DATA _IO('a', ATMIOC_LANE+1) #define ATMLEC_MCAST _IO('a', ATMIOC_LANE+2) /* Maximum number of LEC interfaces (tweakable) */ #define MAX_LEC_ITF 48 typedef enum { l_set_mac_addr, l_del_mac_addr, l_svc_setup, l_addr_delete, l_topology_change, l_flush_complete, l_arp_update, l_narp_req, /* LANE2 mandates the use of this */ l_config, l_flush_tran_id, l_set_lecid, l_arp_xmt, l_rdesc_arp_xmt, l_associate_req, l_should_bridge /* should we bridge this MAC? */ } atmlec_msg_type; #define ATMLEC_MSG_TYPE_MAX l_should_bridge struct atmlec_config_msg { unsigned int maximum_unknown_frame_count; unsigned int max_unknown_frame_time; unsigned short max_retry_count; unsigned int aging_time; unsigned int forward_delay_time; unsigned int arp_response_time; unsigned int flush_timeout; unsigned int path_switching_delay; unsigned int lane_version; /* LANE2: 1 for LANEv1, 2 for LANEv2 */ int mtu; int is_proxy; }; struct atmlec_msg { atmlec_msg_type type; int sizeoftlvs; /* LANE2: if != 0, tlvs follow */ union { struct { unsigned char mac_addr[ETH_ALEN]; unsigned char atm_addr[ATM_ESA_LEN]; unsigned int flag; /* * Topology_change flag, * remoteflag, permanent flag, * lecid, transaction id */ unsigned int targetless_le_arp; /* LANE2 */ unsigned int no_source_le_narp; /* LANE2 */ } normal; struct atmlec_config_msg config; struct { __u16 lec_id; /* requestor lec_id */ __u32 tran_id; /* transaction id */ unsigned char mac_addr[ETH_ALEN]; /* dst mac addr */ unsigned char atm_addr[ATM_ESA_LEN]; /* reqestor ATM addr */ } proxy; /* * For mapping LE_ARP requests to responses. Filled by * zeppelin, returned by kernel. Used only when proxying */ } content; } __ATM_API_ALIGN; struct atmlec_ioc { int dev_num; unsigned char atm_addr[ATM_ESA_LEN]; unsigned char receive; /* 1= receive vcc, 0 = send vcc */ }; #endif /* _ATMLEC_H_ */ linux/lwtunnel.h000064400000004203151027430560007726 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LWTUNNEL_H_ #define _LWTUNNEL_H_ #include enum lwtunnel_encap_types { LWTUNNEL_ENCAP_NONE, LWTUNNEL_ENCAP_MPLS, LWTUNNEL_ENCAP_IP, LWTUNNEL_ENCAP_ILA, LWTUNNEL_ENCAP_IP6, LWTUNNEL_ENCAP_SEG6, LWTUNNEL_ENCAP_BPF, LWTUNNEL_ENCAP_SEG6_LOCAL, __LWTUNNEL_ENCAP_MAX, }; #define LWTUNNEL_ENCAP_MAX (__LWTUNNEL_ENCAP_MAX - 1) enum lwtunnel_ip_t { LWTUNNEL_IP_UNSPEC, LWTUNNEL_IP_ID, LWTUNNEL_IP_DST, LWTUNNEL_IP_SRC, LWTUNNEL_IP_TTL, LWTUNNEL_IP_TOS, LWTUNNEL_IP_FLAGS, LWTUNNEL_IP_PAD, LWTUNNEL_IP_OPTS, __LWTUNNEL_IP_MAX, }; #define LWTUNNEL_IP_MAX (__LWTUNNEL_IP_MAX - 1) enum lwtunnel_ip6_t { LWTUNNEL_IP6_UNSPEC, LWTUNNEL_IP6_ID, LWTUNNEL_IP6_DST, LWTUNNEL_IP6_SRC, LWTUNNEL_IP6_HOPLIMIT, LWTUNNEL_IP6_TC, LWTUNNEL_IP6_FLAGS, LWTUNNEL_IP6_PAD, LWTUNNEL_IP6_OPTS, __LWTUNNEL_IP6_MAX, }; #define LWTUNNEL_IP6_MAX (__LWTUNNEL_IP6_MAX - 1) enum { LWTUNNEL_IP_OPTS_UNSPEC, LWTUNNEL_IP_OPTS_GENEVE, LWTUNNEL_IP_OPTS_VXLAN, LWTUNNEL_IP_OPTS_ERSPAN, __LWTUNNEL_IP_OPTS_MAX, }; #define LWTUNNEL_IP_OPTS_MAX (__LWTUNNEL_IP_OPTS_MAX - 1) enum { LWTUNNEL_IP_OPT_GENEVE_UNSPEC, LWTUNNEL_IP_OPT_GENEVE_CLASS, LWTUNNEL_IP_OPT_GENEVE_TYPE, LWTUNNEL_IP_OPT_GENEVE_DATA, __LWTUNNEL_IP_OPT_GENEVE_MAX, }; #define LWTUNNEL_IP_OPT_GENEVE_MAX (__LWTUNNEL_IP_OPT_GENEVE_MAX - 1) enum { LWTUNNEL_IP_OPT_VXLAN_UNSPEC, LWTUNNEL_IP_OPT_VXLAN_GBP, __LWTUNNEL_IP_OPT_VXLAN_MAX, }; #define LWTUNNEL_IP_OPT_VXLAN_MAX (__LWTUNNEL_IP_OPT_VXLAN_MAX - 1) enum { LWTUNNEL_IP_OPT_ERSPAN_UNSPEC, LWTUNNEL_IP_OPT_ERSPAN_VER, LWTUNNEL_IP_OPT_ERSPAN_INDEX, LWTUNNEL_IP_OPT_ERSPAN_DIR, LWTUNNEL_IP_OPT_ERSPAN_HWID, __LWTUNNEL_IP_OPT_ERSPAN_MAX, }; #define LWTUNNEL_IP_OPT_ERSPAN_MAX (__LWTUNNEL_IP_OPT_ERSPAN_MAX - 1) enum { LWT_BPF_PROG_UNSPEC, LWT_BPF_PROG_FD, LWT_BPF_PROG_NAME, __LWT_BPF_PROG_MAX, }; #define LWT_BPF_PROG_MAX (__LWT_BPF_PROG_MAX - 1) enum { LWT_BPF_UNSPEC, LWT_BPF_IN, LWT_BPF_OUT, LWT_BPF_XMIT, LWT_BPF_XMIT_HEADROOM, __LWT_BPF_MAX, }; #define LWT_BPF_MAX (__LWT_BPF_MAX - 1) #define LWT_BPF_MAX_HEADROOM 256 #endif /* _LWTUNNEL_H_ */ linux/atm_zatm.h000064400000003004151027430560007670 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm_zatm.h - Driver-specific declarations of the ZATM driver (for use by driver-specific utilities) */ /* Written 1995-1999 by Werner Almesberger, EPFL LRC/ICA */ #ifndef LINUX_ATM_ZATM_H #define LINUX_ATM_ZATM_H /* * Note: non-kernel programs including this file must also include * sys/types.h for struct timeval */ #include #include #define ZATM_GETPOOL _IOW('a',ATMIOC_SARPRV+1,struct atmif_sioc) /* get pool statistics */ #define ZATM_GETPOOLZ _IOW('a',ATMIOC_SARPRV+2,struct atmif_sioc) /* get statistics and zero */ #define ZATM_SETPOOL _IOW('a',ATMIOC_SARPRV+3,struct atmif_sioc) /* set pool parameters */ struct zatm_pool_info { int ref_count; /* free buffer pool usage counters */ int low_water,high_water; /* refill parameters */ int rqa_count,rqu_count; /* queue condition counters */ int offset,next_off; /* alignment optimizations: offset */ int next_cnt,next_thres; /* repetition counter and threshold */ }; struct zatm_pool_req { int pool_num; /* pool number */ struct zatm_pool_info info; /* actual information */ }; #define ZATM_OAM_POOL 0 /* free buffer pool for OAM cells */ #define ZATM_AAL0_POOL 1 /* free buffer pool for AAL0 cells */ #define ZATM_AAL5_POOL_BASE 2 /* first AAL5 free buffer pool */ #define ZATM_LAST_POOL ZATM_AAL5_POOL_BASE+10 /* max. 64 kB */ #define ZATM_TIMER_HISTORY_SIZE 16 /* number of timer adjustments to record; must be 2^n */ #endif linux/cycx_cfm.h000064400000005656151027430560007666 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * cycx_cfm.h Cyclom 2X WAN Link Driver. * Definitions for the Cyclom 2X Firmware Module (CFM). * * Author: Arnaldo Carvalho de Melo * * Copyright: (c) 1998-2003 Arnaldo Carvalho de Melo * * Based on sdlasfm.h by Gene Kozin <74604.152@compuserve.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * ============================================================================ * 1998/08/08 acme Initial version. */ #ifndef _CYCX_CFM_H #define _CYCX_CFM_H /* Defines */ #define CFM_VERSION 2 #define CFM_SIGNATURE "CFM - Cyclades CYCX Firmware Module" /* min/max */ #define CFM_IMAGE_SIZE 0x20000 /* max size of CYCX code image file */ #define CFM_DESCR_LEN 256 /* max length of description string */ #define CFM_MAX_CYCX 1 /* max number of compatible adapters */ #define CFM_LOAD_BUFSZ 0x400 /* buffer size for reset code (buffer_load) */ /* Firmware Commands */ #define GEN_POWER_ON 0x1280 #define GEN_SET_SEG 0x1401 /* boot segment setting. */ #define GEN_BOOT_DAT 0x1402 /* boot data. */ #define GEN_START 0x1403 /* board start. */ #define GEN_DEFPAR 0x1404 /* buffer length for boot. */ /* Adapter Types */ #define CYCX_2X 2 /* for now only the 2X is supported, no plans to support 8X or 16X */ #define CYCX_8X 8 #define CYCX_16X 16 #define CFID_X25_2X 5200 /** * struct cycx_fw_info - firmware module information. * @codeid - firmware ID * @version - firmware version number * @adapter - compatible adapter types * @memsize - minimum memory size * @reserved - reserved * @startoffs - entry point offset * @winoffs - dual-port memory window offset * @codeoffs - code load offset * @codesize - code size * @dataoffs - configuration data load offset * @datasize - configuration data size */ struct cycx_fw_info { unsigned short codeid; unsigned short version; unsigned short adapter[CFM_MAX_CYCX]; unsigned long memsize; unsigned short reserved[2]; unsigned short startoffs; unsigned short winoffs; unsigned short codeoffs; unsigned long codesize; unsigned short dataoffs; unsigned long datasize; }; /** * struct cycx_firmware - CYCX firmware file structure * @signature - CFM file signature * @version - file format version * @checksum - info + image * @reserved - reserved * @descr - description string * @info - firmware module info * @image - code image (variable size) */ struct cycx_firmware { char signature[80]; unsigned short version; unsigned short checksum; unsigned short reserved[6]; char descr[CFM_DESCR_LEN]; struct cycx_fw_info info; unsigned char image[0]; }; struct cycx_fw_header { unsigned long reset_size; unsigned long data_size; unsigned long code_size; }; #endif /* _CYCX_CFM_H */ linux/nubus.h000064400000017777151027430560007236 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* nubus.h: various definitions and prototypes for NuBus drivers to use. Originally written by Alan Cox. Hacked to death by C. Scott Ananian and David Huggins-Daines. Some of the constants in here are from the corresponding NetBSD/OpenBSD header file, by Allen Briggs. We figured out the rest of them on our own. */ #ifndef LINUX_NUBUS_H #define LINUX_NUBUS_H #include enum nubus_category { NUBUS_CAT_BOARD = 0x0001, NUBUS_CAT_DISPLAY = 0x0003, NUBUS_CAT_NETWORK = 0x0004, NUBUS_CAT_COMMUNICATIONS = 0x0006, NUBUS_CAT_FONT = 0x0009, NUBUS_CAT_CPU = 0x000A, /* For lack of a better name */ NUBUS_CAT_DUODOCK = 0x0020 }; enum nubus_type_network { NUBUS_TYPE_ETHERNET = 0x0001, NUBUS_TYPE_RS232 = 0x0002 }; enum nubus_type_display { NUBUS_TYPE_VIDEO = 0x0001 }; enum nubus_type_cpu { NUBUS_TYPE_68020 = 0x0003, NUBUS_TYPE_68030 = 0x0004, NUBUS_TYPE_68040 = 0x0005 }; /* Known tuples: (according to TattleTech and Slots) * 68030 motherboards: <10,4,0,24> * 68040 motherboards: <10,5,0,24> * DuoDock Plus: <32,1,1,2> * * Toby Frame Buffer card: <3,1,1,1> * RBV built-in video (IIci): <3,1,1,24> * Valkyrie built-in video (Q630): <3,1,1,46> * Macintosh Display Card: <3,1,1,25> * Sonora built-in video (P460): <3,1,1,34> * Jet framebuffer (DuoDock Plus): <3,1,1,41> * * SONIC comm-slot/on-board and DuoDock Ethernet: <4,1,1,272> * SONIC LC-PDS Ethernet (Dayna, but like Apple 16-bit, sort of): <4,1,1,271> * Apple SONIC LC-PDS Ethernet ("Apple Ethernet LC Twisted-Pair Card"): <4,1,0,281> * Sonic Systems Ethernet A-Series Card: <4,1,268,256> * Asante MacCon NuBus-A: <4,1,260,256> (alpha-1.0,1.1 revision) * ROM on the above card: <2,1,0,0> * Cabletron ethernet card: <4,1,1,265> * Farallon ethernet card: <4,1,268,256> (identical to Sonic Systems card) * Kinetics EtherPort IIN: <4,1,259,262> * API Engineering EtherRun_LCa PDS enet card: <4,1,282,256> * * Add your devices to the list! You can obtain the "Slots" utility * from Apple's FTP site at: * ftp://dev.apple.com/devworld/Tool_Chest/Devices_-_Hardware/NuBus_Slot_Manager/ * * Alternately, TattleTech can be found at any Info-Mac mirror site. * or from its distribution site: ftp://ftp.decismkr.com/dms */ /* DrSW: Uniquely identifies the software interface to a board. This is usually the one you want to look at when writing a driver. It's not as useful as you think, though, because as we should know by now (duh), "Apple Compatible" can mean a lot of things... */ /* Add known DrSW values here */ enum nubus_drsw { /* NUBUS_CAT_DISPLAY */ NUBUS_DRSW_APPLE = 0x0001, NUBUS_DRSW_APPLE_HIRES = 0x0013, /* MacII HiRes card driver */ /* NUBUS_CAT_NETWORK */ NUBUS_DRSW_3COM = 0x0000, NUBUS_DRSW_CABLETRON = 0x0001, NUBUS_DRSW_SONIC_LC = 0x0001, NUBUS_DRSW_KINETICS = 0x0103, NUBUS_DRSW_ASANTE = 0x0104, NUBUS_DRSW_TECHWORKS = 0x0109, NUBUS_DRSW_DAYNA = 0x010b, NUBUS_DRSW_FARALLON = 0x010c, NUBUS_DRSW_APPLE_SN = 0x010f, NUBUS_DRSW_DAYNA2 = 0x0115, NUBUS_DRSW_FOCUS = 0x011a, NUBUS_DRSW_ASANTE_CS = 0x011d, /* use asante SMC9194 driver */ NUBUS_DRSW_DAYNA_LC = 0x011e, /* NUBUS_CAT_CPU */ NUBUS_DRSW_NONE = 0x0000, }; /* DrHW: Uniquely identifies the hardware interface to a board (or at least, it should... some video cards are known to incorrectly identify themselves as Toby cards) */ /* Add known DrHW values here */ enum nubus_drhw { /* NUBUS_CAT_DISPLAY */ NUBUS_DRHW_APPLE_TFB = 0x0001, /* Toby frame buffer card */ NUBUS_DRHW_APPLE_WVC = 0x0006, /* Apple Workstation Video Card */ NUBUS_DRHW_SIGMA_CLRMAX = 0x0007, /* Sigma Design ColorMax */ NUBUS_DRHW_APPLE_SE30 = 0x0009, /* Apple SE/30 video */ NUBUS_DRHW_APPLE_HRVC = 0x0013, /* Mac II High-Res Video Card */ NUBUS_DRHW_APPLE_MVC = 0x0014, /* Mac II Monochrome Video Card */ NUBUS_DRHW_APPLE_PVC = 0x0017, /* Mac II Portrait Video Card */ NUBUS_DRHW_APPLE_RBV1 = 0x0018, /* IIci RBV video */ NUBUS_DRHW_APPLE_MDC = 0x0019, /* Macintosh Display Card */ NUBUS_DRHW_APPLE_VSC = 0x0020, /* Duo MiniDock ViSC framebuffer */ NUBUS_DRHW_APPLE_SONORA = 0x0022, /* Sonora built-in video */ NUBUS_DRHW_APPLE_JET = 0x0029, /* Jet framebuffer (DuoDock) */ NUBUS_DRHW_APPLE_24AC = 0x002b, /* Mac 24AC Video Card */ NUBUS_DRHW_APPLE_VALKYRIE = 0x002e, NUBUS_DRHW_SMAC_GFX = 0x0105, /* SuperMac GFX */ NUBUS_DRHW_RASTER_CB264 = 0x013B, /* RasterOps ColorBoard 264 */ NUBUS_DRHW_MICRON_XCEED = 0x0146, /* Micron Exceed color */ NUBUS_DRHW_RDIUS_GSC = 0x0153, /* Radius GS/C */ NUBUS_DRHW_SMAC_SPEC8 = 0x017B, /* SuperMac Spectrum/8 */ NUBUS_DRHW_SMAC_SPEC24 = 0x017C, /* SuperMac Spectrum/24 */ NUBUS_DRHW_RASTER_CB364 = 0x026F, /* RasterOps ColorBoard 364 */ NUBUS_DRHW_RDIUS_DCGX = 0x027C, /* Radius DirectColor/GX */ NUBUS_DRHW_RDIUS_PC8 = 0x0291, /* Radius PrecisionColor 8 */ NUBUS_DRHW_LAPIS_PCS8 = 0x0292, /* Lapis ProColorServer 8 */ NUBUS_DRHW_RASTER_24XLI = 0x02A0, /* RasterOps 8/24 XLi */ NUBUS_DRHW_RASTER_PBPGT = 0x02A5, /* RasterOps PaintBoard Prism GT */ NUBUS_DRHW_EMACH_FSX = 0x02AE, /* E-Machines Futura SX */ NUBUS_DRHW_RASTER_24XLTV = 0x02B7, /* RasterOps 24XLTV */ NUBUS_DRHW_SMAC_THUND24 = 0x02CB, /* SuperMac Thunder/24 */ NUBUS_DRHW_SMAC_THUNDLGHT = 0x03D9, /* SuperMac ThunderLight */ NUBUS_DRHW_RDIUS_PC24XP = 0x0406, /* Radius PrecisionColor 24Xp */ NUBUS_DRHW_RDIUS_PC24X = 0x040A, /* Radius PrecisionColor 24X */ NUBUS_DRHW_RDIUS_PC8XJ = 0x040B, /* Radius PrecisionColor 8XJ */ /* NUBUS_CAT_NETWORK */ NUBUS_DRHW_INTERLAN = 0x0100, NUBUS_DRHW_SMC9194 = 0x0101, NUBUS_DRHW_KINETICS = 0x0106, NUBUS_DRHW_CABLETRON = 0x0109, NUBUS_DRHW_ASANTE_LC = 0x010f, NUBUS_DRHW_SONIC = 0x0110, NUBUS_DRHW_TECHWORKS = 0x0112, NUBUS_DRHW_APPLE_SONIC_NB = 0x0118, NUBUS_DRHW_APPLE_SONIC_LC = 0x0119, NUBUS_DRHW_FOCUS = 0x011c, NUBUS_DRHW_SONNET = 0x011d, }; /* Resource IDs: These are the identifiers for the various weird and wonderful tidbits of information that may or may not reside in the NuBus ROM directory. */ enum nubus_res_id { NUBUS_RESID_TYPE = 0x0001, NUBUS_RESID_NAME = 0x0002, NUBUS_RESID_ICON = 0x0003, NUBUS_RESID_DRVRDIR = 0x0004, NUBUS_RESID_LOADREC = 0x0005, NUBUS_RESID_BOOTREC = 0x0006, NUBUS_RESID_FLAGS = 0x0007, NUBUS_RESID_HWDEVID = 0x0008, NUBUS_RESID_MINOR_BASEOS = 0x000a, NUBUS_RESID_MINOR_LENGTH = 0x000b, NUBUS_RESID_MAJOR_BASEOS = 0x000c, NUBUS_RESID_MAJOR_LENGTH = 0x000d, NUBUS_RESID_CICN = 0x000f, NUBUS_RESID_ICL8 = 0x0010, NUBUS_RESID_ICL4 = 0x0011, }; /* Category-specific resources. */ enum nubus_board_res_id { NUBUS_RESID_BOARDID = 0x0020, NUBUS_RESID_PRAMINITDATA = 0x0021, NUBUS_RESID_PRIMARYINIT = 0x0022, NUBUS_RESID_TIMEOUTCONST = 0x0023, NUBUS_RESID_VENDORINFO = 0x0024, NUBUS_RESID_BOARDFLAGS = 0x0025, NUBUS_RESID_SECONDINIT = 0x0026, /* Not sure why Apple put these next two in here */ NUBUS_RESID_VIDNAMES = 0x0041, NUBUS_RESID_VIDMODES = 0x007e }; /* Fields within the vendor info directory */ enum nubus_vendor_res_id { NUBUS_RESID_VEND_ID = 0x0001, NUBUS_RESID_VEND_SERIAL = 0x0002, NUBUS_RESID_VEND_REV = 0x0003, NUBUS_RESID_VEND_PART = 0x0004, NUBUS_RESID_VEND_DATE = 0x0005 }; enum nubus_net_res_id { NUBUS_RESID_MAC_ADDRESS = 0x0080 }; enum nubus_cpu_res_id { NUBUS_RESID_MEMINFO = 0x0081, NUBUS_RESID_ROMINFO = 0x0082 }; enum nubus_display_res_id { NUBUS_RESID_GAMMADIR = 0x0040, NUBUS_RESID_FIRSTMODE = 0x0080, NUBUS_RESID_SECONDMODE = 0x0081, NUBUS_RESID_THIRDMODE = 0x0082, NUBUS_RESID_FOURTHMODE = 0x0083, NUBUS_RESID_FIFTHMODE = 0x0084, NUBUS_RESID_SIXTHMODE = 0x0085 }; #endif /* LINUX_NUBUS_H */ linux/if_slip.h000064400000001550151027430560007505 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Swansea University Computer Society NET3 * * This file declares the constants of special use with the SLIP/CSLIP/ * KISS TNC driver. */ #ifndef __LINUX_SLIP_H #define __LINUX_SLIP_H #define SL_MODE_SLIP 0 #define SL_MODE_CSLIP 1 #define SL_MODE_KISS 4 #define SL_OPT_SIXBIT 2 #define SL_OPT_ADAPTIVE 8 /* * VSV = ioctl for keepalive & outfill in SLIP driver */ #define SIOCSKEEPALIVE (SIOCDEVPRIVATE) /* Set keepalive timeout in sec */ #define SIOCGKEEPALIVE (SIOCDEVPRIVATE+1) /* Get keepalive timeout */ #define SIOCSOUTFILL (SIOCDEVPRIVATE+2) /* Set outfill timeout */ #define SIOCGOUTFILL (SIOCDEVPRIVATE+3) /* Get outfill timeout */ #define SIOCSLEASE (SIOCDEVPRIVATE+4) /* Set "leased" line type */ #define SIOCGLEASE (SIOCDEVPRIVATE+5) /* Get line type */ #endif linux/if_addrlabel.h000064400000001321151027430560010444 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * if_addrlabel.h - netlink interface for address labels * * Copyright (C)2007 USAGI/WIDE Project, All Rights Reserved. * * Authors: * YOSHIFUJI Hideaki @ USAGI/WIDE */ #ifndef __LINUX_IF_ADDRLABEL_H #define __LINUX_IF_ADDRLABEL_H #include struct ifaddrlblmsg { __u8 ifal_family; /* Address family */ __u8 __ifal_reserved; /* Reserved */ __u8 ifal_prefixlen; /* Prefix length */ __u8 ifal_flags; /* Flags */ __u32 ifal_index; /* Link index */ __u32 ifal_seq; /* sequence number */ }; enum { IFAL_ADDRESS = 1, IFAL_LABEL = 2, __IFAL_MAX }; #define IFAL_MAX (__IFAL_MAX - 1) #endif linux/connector.h000064400000004315151027430560010054 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * connector.h * * 2004-2005 Copyright (c) Evgeniy Polyakov * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __CONNECTOR_H #define __CONNECTOR_H #include /* * Process Events connector unique ids -- used for message routing */ #define CN_IDX_PROC 0x1 #define CN_VAL_PROC 0x1 #define CN_IDX_CIFS 0x2 #define CN_VAL_CIFS 0x1 #define CN_W1_IDX 0x3 /* w1 communication */ #define CN_W1_VAL 0x1 #define CN_IDX_V86D 0x4 #define CN_VAL_V86D_UVESAFB 0x1 #define CN_IDX_BB 0x5 /* BlackBoard, from the TSP GPL sampling framework */ #define CN_DST_IDX 0x6 #define CN_DST_VAL 0x1 #define CN_IDX_DM 0x7 /* Device Mapper */ #define CN_VAL_DM_USERSPACE_LOG 0x1 #define CN_IDX_DRBD 0x8 #define CN_VAL_DRBD 0x1 #define CN_KVP_IDX 0x9 /* HyperV KVP */ #define CN_KVP_VAL 0x1 /* queries from the kernel */ #define CN_VSS_IDX 0xA /* HyperV VSS */ #define CN_VSS_VAL 0x1 /* queries from the kernel */ #define CN_NETLINK_USERS 11 /* Highest index + 1 */ /* * Maximum connector's message size. */ #define CONNECTOR_MAX_MSG_SIZE 16384 /* * idx and val are unique identifiers which * are used for message routing and * must be registered in connector.h for in-kernel usage. */ struct cb_id { __u32 idx; __u32 val; }; struct cn_msg { struct cb_id id; __u32 seq; __u32 ack; __u16 len; /* Length of the following data */ __u16 flags; __u8 data[0]; }; #endif /* __CONNECTOR_H */ linux/mroute.h000064400000012463151027430560007400 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_MROUTE_H #define __LINUX_MROUTE_H #include #include #include /* For struct in_addr. */ /* Based on the MROUTING 3.5 defines primarily to keep * source compatibility with BSD. * * See the mrouted code for the original history. * * Protocol Independent Multicast (PIM) data structures included * Carlos Picoto (cap@di.fc.ul.pt) */ #define MRT_BASE 200 #define MRT_INIT (MRT_BASE) /* Activate the kernel mroute code */ #define MRT_DONE (MRT_BASE+1) /* Shutdown the kernel mroute */ #define MRT_ADD_VIF (MRT_BASE+2) /* Add a virtual interface */ #define MRT_DEL_VIF (MRT_BASE+3) /* Delete a virtual interface */ #define MRT_ADD_MFC (MRT_BASE+4) /* Add a multicast forwarding entry */ #define MRT_DEL_MFC (MRT_BASE+5) /* Delete a multicast forwarding entry */ #define MRT_VERSION (MRT_BASE+6) /* Get the kernel multicast version */ #define MRT_ASSERT (MRT_BASE+7) /* Activate PIM assert mode */ #define MRT_PIM (MRT_BASE+8) /* enable PIM code */ #define MRT_TABLE (MRT_BASE+9) /* Specify mroute table ID */ #define MRT_ADD_MFC_PROXY (MRT_BASE+10) /* Add a (*,*|G) mfc entry */ #define MRT_DEL_MFC_PROXY (MRT_BASE+11) /* Del a (*,*|G) mfc entry */ #define MRT_MAX (MRT_BASE+11) #define SIOCGETVIFCNT SIOCPROTOPRIVATE /* IP protocol privates */ #define SIOCGETSGCNT (SIOCPROTOPRIVATE+1) #define SIOCGETRPF (SIOCPROTOPRIVATE+2) #define MAXVIFS 32 typedef unsigned long vifbitmap_t; /* User mode code depends on this lot */ typedef unsigned short vifi_t; #define ALL_VIFS ((vifi_t)(-1)) /* Same idea as select */ #define VIFM_SET(n,m) ((m)|=(1<<(n))) #define VIFM_CLR(n,m) ((m)&=~(1<<(n))) #define VIFM_ISSET(n,m) ((m)&(1<<(n))) #define VIFM_CLRALL(m) ((m)=0) #define VIFM_COPY(mfrom,mto) ((mto)=(mfrom)) #define VIFM_SAME(m1,m2) ((m1)==(m2)) /* Passed by mrouted for an MRT_ADD_VIF - again we use the * mrouted 3.6 structures for compatibility */ struct vifctl { vifi_t vifc_vifi; /* Index of VIF */ unsigned char vifc_flags; /* VIFF_ flags */ unsigned char vifc_threshold; /* ttl limit */ unsigned int vifc_rate_limit; /* Rate limiter values (NI) */ union { struct in_addr vifc_lcl_addr; /* Local interface address */ int vifc_lcl_ifindex; /* Local interface index */ }; struct in_addr vifc_rmt_addr; /* IPIP tunnel addr */ }; #define VIFF_TUNNEL 0x1 /* IPIP tunnel */ #define VIFF_SRCRT 0x2 /* NI */ #define VIFF_REGISTER 0x4 /* register vif */ #define VIFF_USE_IFINDEX 0x8 /* use vifc_lcl_ifindex instead of vifc_lcl_addr to find an interface */ /* Cache manipulation structures for mrouted and PIMd */ struct mfcctl { struct in_addr mfcc_origin; /* Origin of mcast */ struct in_addr mfcc_mcastgrp; /* Group in question */ vifi_t mfcc_parent; /* Where it arrived */ unsigned char mfcc_ttls[MAXVIFS]; /* Where it is going */ unsigned int mfcc_pkt_cnt; /* pkt count for src-grp */ unsigned int mfcc_byte_cnt; unsigned int mfcc_wrong_if; int mfcc_expire; }; /* Group count retrieval for mrouted */ struct sioc_sg_req { struct in_addr src; struct in_addr grp; unsigned long pktcnt; unsigned long bytecnt; unsigned long wrong_if; }; /* To get vif packet counts */ struct sioc_vif_req { vifi_t vifi; /* Which iface */ unsigned long icount; /* In packets */ unsigned long ocount; /* Out packets */ unsigned long ibytes; /* In bytes */ unsigned long obytes; /* Out bytes */ }; /* This is the format the mroute daemon expects to see IGMP control * data. Magically happens to be like an IP packet as per the original */ struct igmpmsg { __u32 unused1,unused2; unsigned char im_msgtype; /* What is this */ unsigned char im_mbz; /* Must be zero */ unsigned char im_vif; /* Interface (this ought to be a vifi_t!) */ unsigned char unused3; struct in_addr im_src,im_dst; }; /* ipmr netlink table attributes */ enum { IPMRA_TABLE_UNSPEC, IPMRA_TABLE_ID, IPMRA_TABLE_CACHE_RES_QUEUE_LEN, IPMRA_TABLE_MROUTE_REG_VIF_NUM, IPMRA_TABLE_MROUTE_DO_ASSERT, IPMRA_TABLE_MROUTE_DO_PIM, IPMRA_TABLE_VIFS, __IPMRA_TABLE_MAX }; #define IPMRA_TABLE_MAX (__IPMRA_TABLE_MAX - 1) /* ipmr netlink vif attribute format * [ IPMRA_TABLE_VIFS ] - nested attribute * [ IPMRA_VIF ] - nested attribute * [ IPMRA_VIFA_xxx ] */ enum { IPMRA_VIF_UNSPEC, IPMRA_VIF, __IPMRA_VIF_MAX }; #define IPMRA_VIF_MAX (__IPMRA_VIF_MAX - 1) /* vif-specific attributes */ enum { IPMRA_VIFA_UNSPEC, IPMRA_VIFA_IFINDEX, IPMRA_VIFA_VIF_ID, IPMRA_VIFA_FLAGS, IPMRA_VIFA_BYTES_IN, IPMRA_VIFA_BYTES_OUT, IPMRA_VIFA_PACKETS_IN, IPMRA_VIFA_PACKETS_OUT, IPMRA_VIFA_LOCAL_ADDR, IPMRA_VIFA_REMOTE_ADDR, IPMRA_VIFA_PAD, __IPMRA_VIFA_MAX }; #define IPMRA_VIFA_MAX (__IPMRA_VIFA_MAX - 1) /* ipmr netlink cache report attributes */ enum { IPMRA_CREPORT_UNSPEC, IPMRA_CREPORT_MSGTYPE, IPMRA_CREPORT_VIF_ID, IPMRA_CREPORT_SRC_ADDR, IPMRA_CREPORT_DST_ADDR, IPMRA_CREPORT_PKT, __IPMRA_CREPORT_MAX }; #define IPMRA_CREPORT_MAX (__IPMRA_CREPORT_MAX - 1) /* That's all usermode folks */ #define MFC_ASSERT_THRESH (3*HZ) /* Maximal freq. of asserts */ /* Pseudo messages used by mrouted */ #define IGMPMSG_NOCACHE 1 /* Kern cache fill request to mrouted */ #define IGMPMSG_WRONGVIF 2 /* For PIM assert processing (unused) */ #define IGMPMSG_WHOLEPKT 3 /* For PIM Register processing */ #endif /* __LINUX_MROUTE_H */ linux/pps.h000064400000011176151027430560006667 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * PPS API header * * Copyright (C) 2005-2009 Rodolfo Giometti * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef _PPS_H_ #define _PPS_H_ #include #define PPS_VERSION "5.3.6" #define PPS_MAX_SOURCES 16 /* should be enough... */ /* Implementation note: the logical states ``assert'' and ``clear'' * are implemented in terms of the chip register, i.e. ``assert'' * means the bit is set. */ /* * 3.2 New data structures */ #define PPS_API_VERS_1 1 #define PPS_API_VERS PPS_API_VERS_1 /* we use API version 1 */ #define PPS_MAX_NAME_LEN 32 /* 32-bit vs. 64-bit compatibility. * * 0n i386, the alignment of a uint64_t is only 4 bytes, while on most other * architectures it's 8 bytes. On i386, there will be no padding between the * two consecutive 'struct pps_ktime' members of struct pps_kinfo and struct * pps_kparams. But on most platforms there will be padding to ensure correct * alignment. * * The simple fix is probably to add an explicit padding. * [David Woodhouse] */ struct pps_ktime { __s64 sec; __s32 nsec; __u32 flags; }; struct pps_ktime_compat { __s64 sec; __s32 nsec; __u32 flags; } __attribute__((packed, aligned(4))); #define PPS_TIME_INVALID (1<<0) /* used to specify timeout==NULL */ struct pps_kinfo { __u32 assert_sequence; /* seq. num. of assert event */ __u32 clear_sequence; /* seq. num. of clear event */ struct pps_ktime assert_tu; /* time of assert event */ struct pps_ktime clear_tu; /* time of clear event */ int current_mode; /* current mode bits */ }; struct pps_kinfo_compat { __u32 assert_sequence; /* seq. num. of assert event */ __u32 clear_sequence; /* seq. num. of clear event */ struct pps_ktime_compat assert_tu; /* time of assert event */ struct pps_ktime_compat clear_tu; /* time of clear event */ int current_mode; /* current mode bits */ }; struct pps_kparams { int api_version; /* API version # */ int mode; /* mode bits */ struct pps_ktime assert_off_tu; /* offset compensation for assert */ struct pps_ktime clear_off_tu; /* offset compensation for clear */ }; /* * 3.3 Mode bit definitions */ /* Device/implementation parameters */ #define PPS_CAPTUREASSERT 0x01 /* capture assert events */ #define PPS_CAPTURECLEAR 0x02 /* capture clear events */ #define PPS_CAPTUREBOTH 0x03 /* capture assert and clear events */ #define PPS_OFFSETASSERT 0x10 /* apply compensation for assert event */ #define PPS_OFFSETCLEAR 0x20 /* apply compensation for clear event */ #define PPS_CANWAIT 0x100 /* can we wait for an event? */ #define PPS_CANPOLL 0x200 /* bit reserved for future use */ /* Kernel actions */ #define PPS_ECHOASSERT 0x40 /* feed back assert event to output */ #define PPS_ECHOCLEAR 0x80 /* feed back clear event to output */ /* Timestamp formats */ #define PPS_TSFMT_TSPEC 0x1000 /* select timespec format */ #define PPS_TSFMT_NTPFP 0x2000 /* select NTP format */ /* * 3.4.4 New functions: disciplining the kernel timebase */ /* Kernel consumers */ #define PPS_KC_HARDPPS 0 /* hardpps() (or equivalent) */ #define PPS_KC_HARDPPS_PLL 1 /* hardpps() constrained to use a phase-locked loop */ #define PPS_KC_HARDPPS_FLL 2 /* hardpps() constrained to use a frequency-locked loop */ /* * Here begins the implementation-specific part! */ struct pps_fdata { struct pps_kinfo info; struct pps_ktime timeout; }; struct pps_fdata_compat { struct pps_kinfo_compat info; struct pps_ktime_compat timeout; }; struct pps_bind_args { int tsformat; /* format of time stamps */ int edge; /* selected event type */ int consumer; /* selected kernel consumer */ }; #include #define PPS_GETPARAMS _IOR('p', 0xa1, struct pps_kparams *) #define PPS_SETPARAMS _IOW('p', 0xa2, struct pps_kparams *) #define PPS_GETCAP _IOR('p', 0xa3, int *) #define PPS_FETCH _IOWR('p', 0xa4, struct pps_fdata *) #define PPS_KC_BIND _IOW('p', 0xa5, struct pps_bind_args *) #endif /* _PPS_H_ */ linux/vfio_ccw.h000064400000002445151027430560007663 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Interfaces for vfio-ccw * * Copyright IBM Corp. 2017 * * Author(s): Dong Jia Shi */ #ifndef _VFIO_CCW_H_ #define _VFIO_CCW_H_ #include /* used for START SUBCHANNEL, always present */ struct ccw_io_region { #define ORB_AREA_SIZE 12 __u8 orb_area[ORB_AREA_SIZE]; #define SCSW_AREA_SIZE 12 __u8 scsw_area[SCSW_AREA_SIZE]; #define IRB_AREA_SIZE 96 __u8 irb_area[IRB_AREA_SIZE]; __u32 ret_code; } __attribute__((packed)); /* * used for processing commands that trigger asynchronous actions * Note: this is controlled by a capability */ #define VFIO_CCW_ASYNC_CMD_HSCH (1 << 0) #define VFIO_CCW_ASYNC_CMD_CSCH (1 << 1) struct ccw_cmd_region { __u32 command; __u32 ret_code; } __attribute__((packed)); /* * Used for processing commands that read the subchannel-information block * Reading this region triggers a stsch() to hardware * Note: this is controlled by a capability */ struct ccw_schib_region { #define SCHIB_AREA_SIZE 52 __u8 schib_area[SCHIB_AREA_SIZE]; } __attribute__((packed)); /* * Used for returning a Channel Report Word to userspace. * Note: this is controlled by a capability */ struct ccw_crw_region { __u32 crw; __u32 pad; } __attribute__((packed)); #endif linux/bpfilter.h000064400000000721151027430560007666 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_BPFILTER_H #define _LINUX_BPFILTER_H #include enum { BPFILTER_IPT_SO_SET_REPLACE = 64, BPFILTER_IPT_SO_SET_ADD_COUNTERS = 65, BPFILTER_IPT_SET_MAX, }; enum { BPFILTER_IPT_SO_GET_INFO = 64, BPFILTER_IPT_SO_GET_ENTRIES = 65, BPFILTER_IPT_SO_GET_REVISION_MATCH = 66, BPFILTER_IPT_SO_GET_REVISION_TARGET = 67, BPFILTER_IPT_GET_MAX, }; #endif /* _LINUX_BPFILTER_H */ linux/gsmmux.h000064400000002021151027430560007372 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_GSMMUX_H #define _LINUX_GSMMUX_H #include #include #include struct gsm_config { unsigned int adaption; unsigned int encapsulation; unsigned int initiator; unsigned int t1; unsigned int t2; unsigned int t3; unsigned int n2; unsigned int mru; unsigned int mtu; unsigned int k; unsigned int i; unsigned int unused[8]; /* Padding for expansion without breaking stuff */ }; #define GSMIOC_GETCONF _IOR('G', 0, struct gsm_config) #define GSMIOC_SETCONF _IOW('G', 1, struct gsm_config) struct gsm_netconfig { unsigned int adaption; /* Adaption to use in network mode */ unsigned short protocol;/* Protocol to use - only ETH_P_IP supported */ unsigned short unused2; char if_name[IFNAMSIZ]; /* interface name format string */ __u8 unused[28]; /* For future use */ }; #define GSMIOC_ENABLE_NET _IOW('G', 2, struct gsm_netconfig) #define GSMIOC_DISABLE_NET _IO('G', 3) #endif linux/mdio.h000064400000041570151027430560007016 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/mdio.h: definitions for MDIO (clause 45) transceivers * Copyright 2006-2009 Solarflare Communications Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation, incorporated herein by reference. */ #ifndef __LINUX_MDIO_H__ #define __LINUX_MDIO_H__ #include #include /* MDIO Manageable Devices (MMDs). */ #define MDIO_MMD_PMAPMD 1 /* Physical Medium Attachment/ * Physical Medium Dependent */ #define MDIO_MMD_WIS 2 /* WAN Interface Sublayer */ #define MDIO_MMD_PCS 3 /* Physical Coding Sublayer */ #define MDIO_MMD_PHYXS 4 /* PHY Extender Sublayer */ #define MDIO_MMD_DTEXS 5 /* DTE Extender Sublayer */ #define MDIO_MMD_TC 6 /* Transmission Convergence */ #define MDIO_MMD_AN 7 /* Auto-Negotiation */ #define MDIO_MMD_C22EXT 29 /* Clause 22 extension */ #define MDIO_MMD_VEND1 30 /* Vendor specific 1 */ #define MDIO_MMD_VEND2 31 /* Vendor specific 2 */ /* Generic MDIO registers. */ #define MDIO_CTRL1 MII_BMCR #define MDIO_STAT1 MII_BMSR #define MDIO_DEVID1 MII_PHYSID1 #define MDIO_DEVID2 MII_PHYSID2 #define MDIO_SPEED 4 /* Speed ability */ #define MDIO_DEVS1 5 /* Devices in package */ #define MDIO_DEVS2 6 #define MDIO_CTRL2 7 /* 10G control 2 */ #define MDIO_STAT2 8 /* 10G status 2 */ #define MDIO_PMA_TXDIS 9 /* 10G PMA/PMD transmit disable */ #define MDIO_PMA_RXDET 10 /* 10G PMA/PMD receive signal detect */ #define MDIO_PMA_EXTABLE 11 /* 10G PMA/PMD extended ability */ #define MDIO_PKGID1 14 /* Package identifier */ #define MDIO_PKGID2 15 #define MDIO_AN_ADVERTISE 16 /* AN advertising (base page) */ #define MDIO_AN_LPA 19 /* AN LP abilities (base page) */ #define MDIO_PCS_EEE_ABLE 20 /* EEE Capability register */ #define MDIO_PCS_EEE_ABLE2 21 /* EEE Capability register 2 */ #define MDIO_PMA_NG_EXTABLE 21 /* 2.5G/5G PMA/PMD extended ability */ #define MDIO_PCS_EEE_WK_ERR 22 /* EEE wake error counter */ #define MDIO_PHYXS_LNSTAT 24 /* PHY XGXS lane state */ #define MDIO_AN_EEE_ADV 60 /* EEE advertisement */ #define MDIO_AN_EEE_LPABLE 61 /* EEE link partner ability */ #define MDIO_AN_EEE_ADV2 62 /* EEE advertisement 2 */ #define MDIO_AN_EEE_LPABLE2 63 /* EEE link partner ability 2 */ /* Media-dependent registers. */ #define MDIO_PMA_10GBT_SWAPPOL 130 /* 10GBASE-T pair swap & polarity */ #define MDIO_PMA_10GBT_TXPWR 131 /* 10GBASE-T TX power control */ #define MDIO_PMA_10GBT_SNR 133 /* 10GBASE-T SNR margin, lane A. * Lanes B-D are numbered 134-136. */ #define MDIO_PMA_10GBR_FECABLE 170 /* 10GBASE-R FEC ability */ #define MDIO_PCS_10GBX_STAT1 24 /* 10GBASE-X PCS status 1 */ #define MDIO_PCS_10GBRT_STAT1 32 /* 10GBASE-R/-T PCS status 1 */ #define MDIO_PCS_10GBRT_STAT2 33 /* 10GBASE-R/-T PCS status 2 */ #define MDIO_AN_10GBT_CTRL 32 /* 10GBASE-T auto-negotiation control */ #define MDIO_AN_10GBT_STAT 33 /* 10GBASE-T auto-negotiation status */ /* LASI (Link Alarm Status Interrupt) registers, defined by XENPAK MSA. */ #define MDIO_PMA_LASI_RXCTRL 0x9000 /* RX_ALARM control */ #define MDIO_PMA_LASI_TXCTRL 0x9001 /* TX_ALARM control */ #define MDIO_PMA_LASI_CTRL 0x9002 /* LASI control */ #define MDIO_PMA_LASI_RXSTAT 0x9003 /* RX_ALARM status */ #define MDIO_PMA_LASI_TXSTAT 0x9004 /* TX_ALARM status */ #define MDIO_PMA_LASI_STAT 0x9005 /* LASI status */ /* Control register 1. */ /* Enable extended speed selection */ #define MDIO_CTRL1_SPEEDSELEXT (BMCR_SPEED1000 | BMCR_SPEED100) /* All speed selection bits */ #define MDIO_CTRL1_SPEEDSEL (MDIO_CTRL1_SPEEDSELEXT | 0x003c) #define MDIO_CTRL1_FULLDPLX BMCR_FULLDPLX #define MDIO_CTRL1_LPOWER BMCR_PDOWN #define MDIO_CTRL1_RESET BMCR_RESET #define MDIO_PMA_CTRL1_LOOPBACK 0x0001 #define MDIO_PMA_CTRL1_SPEED1000 BMCR_SPEED1000 #define MDIO_PMA_CTRL1_SPEED100 BMCR_SPEED100 #define MDIO_PCS_CTRL1_LOOPBACK BMCR_LOOPBACK #define MDIO_PHYXS_CTRL1_LOOPBACK BMCR_LOOPBACK #define MDIO_AN_CTRL1_RESTART BMCR_ANRESTART #define MDIO_AN_CTRL1_ENABLE BMCR_ANENABLE #define MDIO_AN_CTRL1_XNP 0x2000 /* Enable extended next page */ #define MDIO_PCS_CTRL1_CLKSTOP_EN 0x400 /* Stop the clock during LPI */ /* 10 Gb/s */ #define MDIO_CTRL1_SPEED10G (MDIO_CTRL1_SPEEDSELEXT | 0x00) /* 10PASS-TS/2BASE-TL */ #define MDIO_CTRL1_SPEED10P2B (MDIO_CTRL1_SPEEDSELEXT | 0x04) /* 2.5 Gb/s */ #define MDIO_CTRL1_SPEED2_5G (MDIO_CTRL1_SPEEDSELEXT | 0x18) /* 5 Gb/s */ #define MDIO_CTRL1_SPEED5G (MDIO_CTRL1_SPEEDSELEXT | 0x1c) /* Status register 1. */ #define MDIO_STAT1_LPOWERABLE 0x0002 /* Low-power ability */ #define MDIO_STAT1_LSTATUS BMSR_LSTATUS #define MDIO_STAT1_FAULT 0x0080 /* Fault */ #define MDIO_AN_STAT1_LPABLE 0x0001 /* Link partner AN ability */ #define MDIO_AN_STAT1_ABLE BMSR_ANEGCAPABLE #define MDIO_AN_STAT1_RFAULT BMSR_RFAULT #define MDIO_AN_STAT1_COMPLETE BMSR_ANEGCOMPLETE #define MDIO_AN_STAT1_PAGE 0x0040 /* Page received */ #define MDIO_AN_STAT1_XNP 0x0080 /* Extended next page status */ /* Speed register. */ #define MDIO_SPEED_10G 0x0001 /* 10G capable */ #define MDIO_PMA_SPEED_2B 0x0002 /* 2BASE-TL capable */ #define MDIO_PMA_SPEED_10P 0x0004 /* 10PASS-TS capable */ #define MDIO_PMA_SPEED_1000 0x0010 /* 1000M capable */ #define MDIO_PMA_SPEED_100 0x0020 /* 100M capable */ #define MDIO_PMA_SPEED_10 0x0040 /* 10M capable */ #define MDIO_PCS_SPEED_10P2B 0x0002 /* 10PASS-TS/2BASE-TL capable */ #define MDIO_PCS_SPEED_2_5G 0x0040 /* 2.5G capable */ #define MDIO_PCS_SPEED_5G 0x0080 /* 5G capable */ /* Device present registers. */ #define MDIO_DEVS_PRESENT(devad) (1 << (devad)) #define MDIO_DEVS_C22PRESENT MDIO_DEVS_PRESENT(0) #define MDIO_DEVS_PMAPMD MDIO_DEVS_PRESENT(MDIO_MMD_PMAPMD) #define MDIO_DEVS_WIS MDIO_DEVS_PRESENT(MDIO_MMD_WIS) #define MDIO_DEVS_PCS MDIO_DEVS_PRESENT(MDIO_MMD_PCS) #define MDIO_DEVS_PHYXS MDIO_DEVS_PRESENT(MDIO_MMD_PHYXS) #define MDIO_DEVS_DTEXS MDIO_DEVS_PRESENT(MDIO_MMD_DTEXS) #define MDIO_DEVS_TC MDIO_DEVS_PRESENT(MDIO_MMD_TC) #define MDIO_DEVS_AN MDIO_DEVS_PRESENT(MDIO_MMD_AN) #define MDIO_DEVS_C22EXT MDIO_DEVS_PRESENT(MDIO_MMD_C22EXT) #define MDIO_DEVS_VEND1 MDIO_DEVS_PRESENT(MDIO_MMD_VEND1) #define MDIO_DEVS_VEND2 MDIO_DEVS_PRESENT(MDIO_MMD_VEND2) /* Control register 2. */ #define MDIO_PMA_CTRL2_TYPE 0x000f /* PMA/PMD type selection */ #define MDIO_PMA_CTRL2_10GBCX4 0x0000 /* 10GBASE-CX4 type */ #define MDIO_PMA_CTRL2_10GBEW 0x0001 /* 10GBASE-EW type */ #define MDIO_PMA_CTRL2_10GBLW 0x0002 /* 10GBASE-LW type */ #define MDIO_PMA_CTRL2_10GBSW 0x0003 /* 10GBASE-SW type */ #define MDIO_PMA_CTRL2_10GBLX4 0x0004 /* 10GBASE-LX4 type */ #define MDIO_PMA_CTRL2_10GBER 0x0005 /* 10GBASE-ER type */ #define MDIO_PMA_CTRL2_10GBLR 0x0006 /* 10GBASE-LR type */ #define MDIO_PMA_CTRL2_10GBSR 0x0007 /* 10GBASE-SR type */ #define MDIO_PMA_CTRL2_10GBLRM 0x0008 /* 10GBASE-LRM type */ #define MDIO_PMA_CTRL2_10GBT 0x0009 /* 10GBASE-T type */ #define MDIO_PMA_CTRL2_10GBKX4 0x000a /* 10GBASE-KX4 type */ #define MDIO_PMA_CTRL2_10GBKR 0x000b /* 10GBASE-KR type */ #define MDIO_PMA_CTRL2_1000BT 0x000c /* 1000BASE-T type */ #define MDIO_PMA_CTRL2_1000BKX 0x000d /* 1000BASE-KX type */ #define MDIO_PMA_CTRL2_100BTX 0x000e /* 100BASE-TX type */ #define MDIO_PMA_CTRL2_10BT 0x000f /* 10BASE-T type */ #define MDIO_PMA_CTRL2_2_5GBT 0x0030 /* 2.5GBaseT type */ #define MDIO_PMA_CTRL2_5GBT 0x0031 /* 5GBaseT type */ #define MDIO_PCS_CTRL2_TYPE 0x0003 /* PCS type selection */ #define MDIO_PCS_CTRL2_10GBR 0x0000 /* 10GBASE-R type */ #define MDIO_PCS_CTRL2_10GBX 0x0001 /* 10GBASE-X type */ #define MDIO_PCS_CTRL2_10GBW 0x0002 /* 10GBASE-W type */ #define MDIO_PCS_CTRL2_10GBT 0x0003 /* 10GBASE-T type */ /* Status register 2. */ #define MDIO_STAT2_RXFAULT 0x0400 /* Receive fault */ #define MDIO_STAT2_TXFAULT 0x0800 /* Transmit fault */ #define MDIO_STAT2_DEVPRST 0xc000 /* Device present */ #define MDIO_STAT2_DEVPRST_VAL 0x8000 /* Device present value */ #define MDIO_PMA_STAT2_LBABLE 0x0001 /* PMA loopback ability */ #define MDIO_PMA_STAT2_10GBEW 0x0002 /* 10GBASE-EW ability */ #define MDIO_PMA_STAT2_10GBLW 0x0004 /* 10GBASE-LW ability */ #define MDIO_PMA_STAT2_10GBSW 0x0008 /* 10GBASE-SW ability */ #define MDIO_PMA_STAT2_10GBLX4 0x0010 /* 10GBASE-LX4 ability */ #define MDIO_PMA_STAT2_10GBER 0x0020 /* 10GBASE-ER ability */ #define MDIO_PMA_STAT2_10GBLR 0x0040 /* 10GBASE-LR ability */ #define MDIO_PMA_STAT2_10GBSR 0x0080 /* 10GBASE-SR ability */ #define MDIO_PMD_STAT2_TXDISAB 0x0100 /* PMD TX disable ability */ #define MDIO_PMA_STAT2_EXTABLE 0x0200 /* Extended abilities */ #define MDIO_PMA_STAT2_RXFLTABLE 0x1000 /* Receive fault ability */ #define MDIO_PMA_STAT2_TXFLTABLE 0x2000 /* Transmit fault ability */ #define MDIO_PCS_STAT2_10GBR 0x0001 /* 10GBASE-R capable */ #define MDIO_PCS_STAT2_10GBX 0x0002 /* 10GBASE-X capable */ #define MDIO_PCS_STAT2_10GBW 0x0004 /* 10GBASE-W capable */ #define MDIO_PCS_STAT2_RXFLTABLE 0x1000 /* Receive fault ability */ #define MDIO_PCS_STAT2_TXFLTABLE 0x2000 /* Transmit fault ability */ /* Transmit disable register. */ #define MDIO_PMD_TXDIS_GLOBAL 0x0001 /* Global PMD TX disable */ #define MDIO_PMD_TXDIS_0 0x0002 /* PMD TX disable 0 */ #define MDIO_PMD_TXDIS_1 0x0004 /* PMD TX disable 1 */ #define MDIO_PMD_TXDIS_2 0x0008 /* PMD TX disable 2 */ #define MDIO_PMD_TXDIS_3 0x0010 /* PMD TX disable 3 */ /* Receive signal detect register. */ #define MDIO_PMD_RXDET_GLOBAL 0x0001 /* Global PMD RX signal detect */ #define MDIO_PMD_RXDET_0 0x0002 /* PMD RX signal detect 0 */ #define MDIO_PMD_RXDET_1 0x0004 /* PMD RX signal detect 1 */ #define MDIO_PMD_RXDET_2 0x0008 /* PMD RX signal detect 2 */ #define MDIO_PMD_RXDET_3 0x0010 /* PMD RX signal detect 3 */ /* Extended abilities register. */ #define MDIO_PMA_EXTABLE_10GCX4 0x0001 /* 10GBASE-CX4 ability */ #define MDIO_PMA_EXTABLE_10GBLRM 0x0002 /* 10GBASE-LRM ability */ #define MDIO_PMA_EXTABLE_10GBT 0x0004 /* 10GBASE-T ability */ #define MDIO_PMA_EXTABLE_10GBKX4 0x0008 /* 10GBASE-KX4 ability */ #define MDIO_PMA_EXTABLE_10GBKR 0x0010 /* 10GBASE-KR ability */ #define MDIO_PMA_EXTABLE_1000BT 0x0020 /* 1000BASE-T ability */ #define MDIO_PMA_EXTABLE_1000BKX 0x0040 /* 1000BASE-KX ability */ #define MDIO_PMA_EXTABLE_100BTX 0x0080 /* 100BASE-TX ability */ #define MDIO_PMA_EXTABLE_10BT 0x0100 /* 10BASE-T ability */ #define MDIO_PMA_EXTABLE_NBT 0x4000 /* 2.5/5GBASE-T ability */ /* PHY XGXS lane state register. */ #define MDIO_PHYXS_LNSTAT_SYNC0 0x0001 #define MDIO_PHYXS_LNSTAT_SYNC1 0x0002 #define MDIO_PHYXS_LNSTAT_SYNC2 0x0004 #define MDIO_PHYXS_LNSTAT_SYNC3 0x0008 #define MDIO_PHYXS_LNSTAT_ALIGN 0x1000 /* PMA 10GBASE-T pair swap & polarity */ #define MDIO_PMA_10GBT_SWAPPOL_ABNX 0x0001 /* Pair A/B uncrossed */ #define MDIO_PMA_10GBT_SWAPPOL_CDNX 0x0002 /* Pair C/D uncrossed */ #define MDIO_PMA_10GBT_SWAPPOL_AREV 0x0100 /* Pair A polarity reversed */ #define MDIO_PMA_10GBT_SWAPPOL_BREV 0x0200 /* Pair B polarity reversed */ #define MDIO_PMA_10GBT_SWAPPOL_CREV 0x0400 /* Pair C polarity reversed */ #define MDIO_PMA_10GBT_SWAPPOL_DREV 0x0800 /* Pair D polarity reversed */ /* PMA 10GBASE-T TX power register. */ #define MDIO_PMA_10GBT_TXPWR_SHORT 0x0001 /* Short-reach mode */ /* PMA 10GBASE-T SNR registers. */ /* Value is SNR margin in dB, clamped to range [-127, 127], plus 0x8000. */ #define MDIO_PMA_10GBT_SNR_BIAS 0x8000 #define MDIO_PMA_10GBT_SNR_MAX 127 /* PMA 10GBASE-R FEC ability register. */ #define MDIO_PMA_10GBR_FECABLE_ABLE 0x0001 /* FEC ability */ #define MDIO_PMA_10GBR_FECABLE_ERRABLE 0x0002 /* FEC error indic. ability */ /* PCS 10GBASE-R/-T status register 1. */ #define MDIO_PCS_10GBRT_STAT1_BLKLK 0x0001 /* Block lock attained */ /* PCS 10GBASE-R/-T status register 2. */ #define MDIO_PCS_10GBRT_STAT2_ERR 0x00ff #define MDIO_PCS_10GBRT_STAT2_BER 0x3f00 /* AN 10GBASE-T control register. */ #define MDIO_AN_10GBT_CTRL_ADV2_5G 0x0080 /* Advertise 2.5GBASE-T */ #define MDIO_AN_10GBT_CTRL_ADV5G 0x0100 /* Advertise 5GBASE-T */ #define MDIO_AN_10GBT_CTRL_ADV10G 0x1000 /* Advertise 10GBASE-T */ /* AN 10GBASE-T status register. */ #define MDIO_AN_10GBT_STAT_LP2_5G 0x0020 /* LP is 2.5GBT capable */ #define MDIO_AN_10GBT_STAT_LP5G 0x0040 /* LP is 5GBT capable */ #define MDIO_AN_10GBT_STAT_LPTRR 0x0200 /* LP training reset req. */ #define MDIO_AN_10GBT_STAT_LPLTABLE 0x0400 /* LP loop timing ability */ #define MDIO_AN_10GBT_STAT_LP10G 0x0800 /* LP is 10GBT capable */ #define MDIO_AN_10GBT_STAT_REMOK 0x1000 /* Remote OK */ #define MDIO_AN_10GBT_STAT_LOCOK 0x2000 /* Local OK */ #define MDIO_AN_10GBT_STAT_MS 0x4000 /* Master/slave config */ #define MDIO_AN_10GBT_STAT_MSFLT 0x8000 /* Master/slave config fault */ /* EEE Supported/Advertisement/LP Advertisement registers. * * EEE capability Register (3.20), Advertisement (7.60) and * Link partner ability (7.61) registers have and can use the same identical * bit masks. */ #define MDIO_AN_EEE_ADV_100TX 0x0002 /* Advertise 100TX EEE cap */ #define MDIO_AN_EEE_ADV_1000T 0x0004 /* Advertise 1000T EEE cap */ /* Note: the two defines above can be potentially used by the user-land * and cannot remove them now. * So, we define the new generic MDIO_EEE_100TX and MDIO_EEE_1000T macros * using the previous ones (that can be considered obsolete). */ #define MDIO_EEE_100TX MDIO_AN_EEE_ADV_100TX /* 100TX EEE cap */ #define MDIO_EEE_1000T MDIO_AN_EEE_ADV_1000T /* 1000T EEE cap */ #define MDIO_EEE_10GT 0x0008 /* 10GT EEE cap */ #define MDIO_EEE_1000KX 0x0010 /* 1000KX EEE cap */ #define MDIO_EEE_10GKX4 0x0020 /* 10G KX4 EEE cap */ #define MDIO_EEE_10GKR 0x0040 /* 10G KR EEE cap */ #define MDIO_EEE_40GR_FW 0x0100 /* 40G R fast wake */ #define MDIO_EEE_40GR_DS 0x0200 /* 40G R deep sleep */ #define MDIO_EEE_100GR_FW 0x1000 /* 100G R fast wake */ #define MDIO_EEE_100GR_DS 0x2000 /* 100G R deep sleep */ #define MDIO_EEE_2_5GT 0x0001 /* 2.5GT EEE cap */ #define MDIO_EEE_5GT 0x0002 /* 5GT EEE cap */ /* 2.5G/5G Extended abilities register. */ #define MDIO_PMA_NG_EXTABLE_2_5GBT 0x0001 /* 2.5GBASET ability */ #define MDIO_PMA_NG_EXTABLE_5GBT 0x0002 /* 5GBASET ability */ /* LASI RX_ALARM control/status registers. */ #define MDIO_PMA_LASI_RX_PHYXSLFLT 0x0001 /* PHY XS RX local fault */ #define MDIO_PMA_LASI_RX_PCSLFLT 0x0008 /* PCS RX local fault */ #define MDIO_PMA_LASI_RX_PMALFLT 0x0010 /* PMA/PMD RX local fault */ #define MDIO_PMA_LASI_RX_OPTICPOWERFLT 0x0020 /* RX optical power fault */ #define MDIO_PMA_LASI_RX_WISLFLT 0x0200 /* WIS local fault */ /* LASI TX_ALARM control/status registers. */ #define MDIO_PMA_LASI_TX_PHYXSLFLT 0x0001 /* PHY XS TX local fault */ #define MDIO_PMA_LASI_TX_PCSLFLT 0x0008 /* PCS TX local fault */ #define MDIO_PMA_LASI_TX_PMALFLT 0x0010 /* PMA/PMD TX local fault */ #define MDIO_PMA_LASI_TX_LASERPOWERFLT 0x0080 /* Laser output power fault */ #define MDIO_PMA_LASI_TX_LASERTEMPFLT 0x0100 /* Laser temperature fault */ #define MDIO_PMA_LASI_TX_LASERBICURRFLT 0x0200 /* Laser bias current fault */ /* LASI control/status registers. */ #define MDIO_PMA_LASI_LSALARM 0x0001 /* LS_ALARM enable/status */ #define MDIO_PMA_LASI_TXALARM 0x0002 /* TX_ALARM enable/status */ #define MDIO_PMA_LASI_RXALARM 0x0004 /* RX_ALARM enable/status */ /* Mapping between MDIO PRTAD/DEVAD and mii_ioctl_data::phy_id */ #define MDIO_PHY_ID_C45 0x8000 #define MDIO_PHY_ID_PRTAD 0x03e0 #define MDIO_PHY_ID_DEVAD 0x001f #define MDIO_PHY_ID_C45_MASK \ (MDIO_PHY_ID_C45 | MDIO_PHY_ID_PRTAD | MDIO_PHY_ID_DEVAD) static __inline__ __u16 mdio_phy_id_c45(int prtad, int devad) { return MDIO_PHY_ID_C45 | (prtad << 5) | devad; } /* UsxgmiiChannelInfo[15:0] for USXGMII in-band auto-negotiation.*/ #define MDIO_USXGMII_EEE_CLK_STP 0x0080 /* EEE clock stop supported */ #define MDIO_USXGMII_EEE 0x0100 /* EEE supported */ #define MDIO_USXGMII_SPD_MASK 0x0e00 /* USXGMII speed mask */ #define MDIO_USXGMII_FULL_DUPLEX 0x1000 /* USXGMII full duplex */ #define MDIO_USXGMII_DPX_SPD_MASK 0x1e00 /* USXGMII duplex and speed bits */ #define MDIO_USXGMII_10 0x0000 /* 10Mbps */ #define MDIO_USXGMII_10HALF 0x0000 /* 10Mbps half-duplex */ #define MDIO_USXGMII_10FULL 0x1000 /* 10Mbps full-duplex */ #define MDIO_USXGMII_100 0x0200 /* 100Mbps */ #define MDIO_USXGMII_100HALF 0x0200 /* 100Mbps half-duplex */ #define MDIO_USXGMII_100FULL 0x1200 /* 100Mbps full-duplex */ #define MDIO_USXGMII_1000 0x0400 /* 1000Mbps */ #define MDIO_USXGMII_1000HALF 0x0400 /* 1000Mbps half-duplex */ #define MDIO_USXGMII_1000FULL 0x1400 /* 1000Mbps full-duplex */ #define MDIO_USXGMII_10G 0x0600 /* 10Gbps */ #define MDIO_USXGMII_10GHALF 0x0600 /* 10Gbps half-duplex */ #define MDIO_USXGMII_10GFULL 0x1600 /* 10Gbps full-duplex */ #define MDIO_USXGMII_2500 0x0800 /* 2500Mbps */ #define MDIO_USXGMII_2500HALF 0x0800 /* 2500Mbps half-duplex */ #define MDIO_USXGMII_2500FULL 0x1800 /* 2500Mbps full-duplex */ #define MDIO_USXGMII_5000 0x0a00 /* 5000Mbps */ #define MDIO_USXGMII_5000HALF 0x0a00 /* 5000Mbps half-duplex */ #define MDIO_USXGMII_5000FULL 0x1a00 /* 5000Mbps full-duplex */ #define MDIO_USXGMII_LINK 0x8000 /* PHY link with copper-side partner */ #endif /* __LINUX_MDIO_H__ */ linux/nitro_enclaves.h000064400000031540151027430560011075 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. */ #ifndef _LINUX_NITRO_ENCLAVES_H_ #define _LINUX_NITRO_ENCLAVES_H_ #include /** * DOC: Nitro Enclaves (NE) Kernel Driver Interface */ /** * NE_CREATE_VM - The command is used to create a slot that is associated with * an enclave VM. * The generated unique slot id is an output parameter. * The ioctl can be invoked on the /dev/nitro_enclaves fd, before * setting any resources, such as memory and vCPUs, for an * enclave. Memory and vCPUs are set for the slot mapped to an enclave. * A NE CPU pool has to be set before calling this function. The * pool can be set after the NE driver load, using * /sys/module/nitro_enclaves/parameters/ne_cpus. * Its format is the detailed in the cpu-lists section: * https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html * CPU 0 and its siblings have to remain available for the * primary / parent VM, so they cannot be set for enclaves. Full * CPU core(s), from the same NUMA node, need(s) to be included * in the CPU pool. * * Context: Process context. * Return: * * Enclave file descriptor - Enclave file descriptor used with * ioctl calls to set vCPUs and memory * regions, then start the enclave. * * -1 - There was a failure in the ioctl logic. * On failure, errno is set to: * * EFAULT - copy_to_user() failure. * * ENOMEM - Memory allocation failure for internal * bookkeeping variables. * * NE_ERR_NO_CPUS_AVAIL_IN_POOL - No NE CPU pool set / no CPUs available * in the pool. * * Error codes from get_unused_fd_flags() and anon_inode_getfile(). * * Error codes from the NE PCI device request. */ #define NE_CREATE_VM _IOR(0xAE, 0x20, __u64) /** * NE_ADD_VCPU - The command is used to set a vCPU for an enclave. The vCPU can * be auto-chosen from the NE CPU pool or it can be set by the * caller, with the note that it needs to be available in the NE * CPU pool. Full CPU core(s), from the same NUMA node, need(s) to * be associated with an enclave. * The vCPU id is an input / output parameter. If its value is 0, * then a CPU is chosen from the enclave CPU pool and returned via * this parameter. * The ioctl can be invoked on the enclave fd, before an enclave * is started. * * Context: Process context. * Return: * * 0 - Logic succesfully completed. * * -1 - There was a failure in the ioctl logic. * On failure, errno is set to: * * EFAULT - copy_from_user() / copy_to_user() failure. * * ENOMEM - Memory allocation failure for internal * bookkeeping variables. * * EIO - Current task mm is not the same as the one * that created the enclave. * * NE_ERR_NO_CPUS_AVAIL_IN_POOL - No CPUs available in the NE CPU pool. * * NE_ERR_VCPU_ALREADY_USED - The provided vCPU is already used. * * NE_ERR_VCPU_NOT_IN_CPU_POOL - The provided vCPU is not available in the * NE CPU pool. * * NE_ERR_VCPU_INVALID_CPU_CORE - The core id of the provided vCPU is invalid * or out of range. * * NE_ERR_NOT_IN_INIT_STATE - The enclave is not in init state * (init = before being started). * * NE_ERR_INVALID_VCPU - The provided vCPU is not in the available * CPUs range. * * Error codes from the NE PCI device request. */ #define NE_ADD_VCPU _IOWR(0xAE, 0x21, __u32) /** * NE_GET_IMAGE_LOAD_INFO - The command is used to get information needed for * in-memory enclave image loading e.g. offset in * enclave memory to start placing the enclave image. * The image load info is an input / output parameter. * It includes info provided by the caller - flags - * and returns the offset in enclave memory where to * start placing the enclave image. * The ioctl can be invoked on the enclave fd, before * an enclave is started. * * Context: Process context. * Return: * * 0 - Logic succesfully completed. * * -1 - There was a failure in the ioctl logic. * On failure, errno is set to: * * EFAULT - copy_from_user() / copy_to_user() failure. * * NE_ERR_NOT_IN_INIT_STATE - The enclave is not in init state (init = * before being started). * * NE_ERR_INVALID_FLAG_VALUE - The value of the provided flag is invalid. */ #define NE_GET_IMAGE_LOAD_INFO _IOWR(0xAE, 0x22, struct ne_image_load_info) /** * NE_SET_USER_MEMORY_REGION - The command is used to set a memory region for an * enclave, given the allocated memory from the * userspace. Enclave memory needs to be from the * same NUMA node as the enclave CPUs. * The user memory region is an input parameter. It * includes info provided by the caller - flags, * memory size and userspace address. * The ioctl can be invoked on the enclave fd, * before an enclave is started. * * Context: Process context. * Return: * * 0 - Logic succesfully completed. * * -1 - There was a failure in the ioctl logic. * On failure, errno is set to: * * EFAULT - copy_from_user() failure. * * EINVAL - Invalid physical memory region(s) e.g. * unaligned address. * * EIO - Current task mm is not the same as * the one that created the enclave. * * ENOMEM - Memory allocation failure for internal * bookkeeping variables. * * NE_ERR_NOT_IN_INIT_STATE - The enclave is not in init state * (init = before being started). * * NE_ERR_INVALID_MEM_REGION_SIZE - The memory size of the region is not * multiple of 2 MiB. * * NE_ERR_INVALID_MEM_REGION_ADDR - Invalid user space address given. * * NE_ERR_UNALIGNED_MEM_REGION_ADDR - Unaligned user space address given. * * NE_ERR_MEM_REGION_ALREADY_USED - The memory region is already used. * * NE_ERR_MEM_NOT_HUGE_PAGE - The memory region is not backed by * huge pages. * * NE_ERR_MEM_DIFFERENT_NUMA_NODE - The memory region is not from the same * NUMA node as the CPUs. * * NE_ERR_MEM_MAX_REGIONS - The number of memory regions set for * the enclave reached maximum. * * NE_ERR_INVALID_PAGE_SIZE - The memory region is not backed by * pages multiple of 2 MiB. * * NE_ERR_INVALID_FLAG_VALUE - The value of the provided flag is invalid. * * Error codes from get_user_pages(). * * Error codes from the NE PCI device request. */ #define NE_SET_USER_MEMORY_REGION _IOW(0xAE, 0x23, struct ne_user_memory_region) /** * NE_START_ENCLAVE - The command is used to trigger enclave start after the * enclave resources, such as memory and CPU, have been set. * The enclave start info is an input / output parameter. It * includes info provided by the caller - enclave cid and * flags - and returns the cid (if input cid is 0). * The ioctl can be invoked on the enclave fd, after an * enclave slot is created and resources, such as memory and * vCPUs are set for an enclave. * * Context: Process context. * Return: * * 0 - Logic succesfully completed. * * -1 - There was a failure in the ioctl logic. * On failure, errno is set to: * * EFAULT - copy_from_user() / copy_to_user() failure. * * NE_ERR_NOT_IN_INIT_STATE - The enclave is not in init state * (init = before being started). * * NE_ERR_NO_MEM_REGIONS_ADDED - No memory regions are set. * * NE_ERR_NO_VCPUS_ADDED - No vCPUs are set. * * NE_ERR_FULL_CORES_NOT_USED - Full core(s) not set for the enclave. * * NE_ERR_ENCLAVE_MEM_MIN_SIZE - Enclave memory is less than minimum * memory size (64 MiB). * * NE_ERR_INVALID_FLAG_VALUE - The value of the provided flag is invalid. * * NE_ERR_INVALID_ENCLAVE_CID - The provided enclave CID is invalid. * * Error codes from the NE PCI device request. */ #define NE_START_ENCLAVE _IOWR(0xAE, 0x24, struct ne_enclave_start_info) /** * DOC: NE specific error codes */ /** * NE_ERR_VCPU_ALREADY_USED - The provided vCPU is already used. */ #define NE_ERR_VCPU_ALREADY_USED (256) /** * NE_ERR_VCPU_NOT_IN_CPU_POOL - The provided vCPU is not available in the * NE CPU pool. */ #define NE_ERR_VCPU_NOT_IN_CPU_POOL (257) /** * NE_ERR_VCPU_INVALID_CPU_CORE - The core id of the provided vCPU is invalid * or out of range of the NE CPU pool. */ #define NE_ERR_VCPU_INVALID_CPU_CORE (258) /** * NE_ERR_INVALID_MEM_REGION_SIZE - The user space memory region size is not * multiple of 2 MiB. */ #define NE_ERR_INVALID_MEM_REGION_SIZE (259) /** * NE_ERR_INVALID_MEM_REGION_ADDR - The user space memory region address range * is invalid. */ #define NE_ERR_INVALID_MEM_REGION_ADDR (260) /** * NE_ERR_UNALIGNED_MEM_REGION_ADDR - The user space memory region address is * not aligned. */ #define NE_ERR_UNALIGNED_MEM_REGION_ADDR (261) /** * NE_ERR_MEM_REGION_ALREADY_USED - The user space memory region is already used. */ #define NE_ERR_MEM_REGION_ALREADY_USED (262) /** * NE_ERR_MEM_NOT_HUGE_PAGE - The user space memory region is not backed by * contiguous physical huge page(s). */ #define NE_ERR_MEM_NOT_HUGE_PAGE (263) /** * NE_ERR_MEM_DIFFERENT_NUMA_NODE - The user space memory region is backed by * pages from different NUMA nodes than the CPUs. */ #define NE_ERR_MEM_DIFFERENT_NUMA_NODE (264) /** * NE_ERR_MEM_MAX_REGIONS - The supported max memory regions per enclaves has * been reached. */ #define NE_ERR_MEM_MAX_REGIONS (265) /** * NE_ERR_NO_MEM_REGIONS_ADDED - The command to start an enclave is triggered * and no memory regions are added. */ #define NE_ERR_NO_MEM_REGIONS_ADDED (266) /** * NE_ERR_NO_VCPUS_ADDED - The command to start an enclave is triggered and no * vCPUs are added. */ #define NE_ERR_NO_VCPUS_ADDED (267) /** * NE_ERR_ENCLAVE_MEM_MIN_SIZE - The enclave memory size is lower than the * minimum supported. */ #define NE_ERR_ENCLAVE_MEM_MIN_SIZE (268) /** * NE_ERR_FULL_CORES_NOT_USED - The command to start an enclave is triggered and * full CPU cores are not set. */ #define NE_ERR_FULL_CORES_NOT_USED (269) /** * NE_ERR_NOT_IN_INIT_STATE - The enclave is not in init state when setting * resources or triggering start. */ #define NE_ERR_NOT_IN_INIT_STATE (270) /** * NE_ERR_INVALID_VCPU - The provided vCPU is out of range of the available CPUs. */ #define NE_ERR_INVALID_VCPU (271) /** * NE_ERR_NO_CPUS_AVAIL_IN_POOL - The command to create an enclave is triggered * and no CPUs are available in the pool. */ #define NE_ERR_NO_CPUS_AVAIL_IN_POOL (272) /** * NE_ERR_INVALID_PAGE_SIZE - The user space memory region is not backed by pages * multiple of 2 MiB. */ #define NE_ERR_INVALID_PAGE_SIZE (273) /** * NE_ERR_INVALID_FLAG_VALUE - The provided flag value is invalid. */ #define NE_ERR_INVALID_FLAG_VALUE (274) /** * NE_ERR_INVALID_ENCLAVE_CID - The provided enclave CID is invalid, either * being a well-known value or the CID of the * parent / primary VM. */ #define NE_ERR_INVALID_ENCLAVE_CID (275) /** * DOC: Image load info flags */ /** * NE_EIF_IMAGE - Enclave Image Format (EIF) */ #define NE_EIF_IMAGE (0x01) #define NE_IMAGE_LOAD_MAX_FLAG_VAL (0x02) /** * struct ne_image_load_info - Info necessary for in-memory enclave image * loading (in / out). * @flags: Flags to determine the enclave image type * (e.g. Enclave Image Format - EIF) (in). * @memory_offset: Offset in enclave memory where to start placing the * enclave image (out). */ struct ne_image_load_info { __u64 flags; __u64 memory_offset; }; /** * DOC: User memory region flags */ /** * NE_DEFAULT_MEMORY_REGION - Memory region for enclave general usage. */ #define NE_DEFAULT_MEMORY_REGION (0x00) #define NE_MEMORY_REGION_MAX_FLAG_VAL (0x01) /** * struct ne_user_memory_region - Memory region to be set for an enclave (in). * @flags: Flags to determine the usage for the memory region (in). * @memory_size: The size, in bytes, of the memory region to be set for * an enclave (in). * @userspace_addr: The start address of the userspace allocated memory of * the memory region to set for an enclave (in). */ struct ne_user_memory_region { __u64 flags; __u64 memory_size; __u64 userspace_addr; }; /** * DOC: Enclave start info flags */ /** * NE_ENCLAVE_PRODUCTION_MODE - Start enclave in production mode. */ #define NE_ENCLAVE_PRODUCTION_MODE (0x00) /** * NE_ENCLAVE_DEBUG_MODE - Start enclave in debug mode. */ #define NE_ENCLAVE_DEBUG_MODE (0x01) #define NE_ENCLAVE_START_MAX_FLAG_VAL (0x02) /** * struct ne_enclave_start_info - Setup info necessary for enclave start (in / out). * @flags: Flags for the enclave to start with (e.g. debug mode) (in). * @enclave_cid: Context ID (CID) for the enclave vsock device. If 0 as * input, the CID is autogenerated by the hypervisor and * returned back as output by the driver (in / out). */ struct ne_enclave_start_info { __u64 flags; __u64 enclave_cid; }; #endif /* _LINUX_NITRO_ENCLAVES_H_ */ linux/gen_stats.h000064400000002766151027430560010061 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_GEN_STATS_H #define __LINUX_GEN_STATS_H #include enum { TCA_STATS_UNSPEC, TCA_STATS_BASIC, TCA_STATS_RATE_EST, TCA_STATS_QUEUE, TCA_STATS_APP, TCA_STATS_RATE_EST64, TCA_STATS_PAD, TCA_STATS_BASIC_HW, TCA_STATS_PKT64, __TCA_STATS_MAX, }; #define TCA_STATS_MAX (__TCA_STATS_MAX - 1) /** * struct gnet_stats_basic - byte/packet throughput statistics * @bytes: number of seen bytes * @packets: number of seen packets */ struct gnet_stats_basic { __u64 bytes; __u32 packets; }; /** * struct gnet_stats_rate_est - rate estimator * @bps: current byte rate * @pps: current packet rate */ struct gnet_stats_rate_est { __u32 bps; __u32 pps; }; /** * struct gnet_stats_rate_est64 - rate estimator * @bps: current byte rate * @pps: current packet rate */ struct gnet_stats_rate_est64 { __u64 bps; __u64 pps; }; /** * struct gnet_stats_queue - queuing statistics * @qlen: queue length * @backlog: backlog size of queue * @drops: number of dropped packets * @requeues: number of requeues * @overlimits: number of enqueues over the limit */ struct gnet_stats_queue { __u32 qlen; __u32 backlog; __u32 drops; __u32 requeues; __u32 overlimits; }; /** * struct gnet_estimator - rate estimator configuration * @interval: sampling period * @ewma_log: the log of measurement window weight */ struct gnet_estimator { signed char interval; unsigned char ewma_log; }; #endif /* __LINUX_GEN_STATS_H */ linux/cec.h000064400000111473151027430560006620 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * cec - HDMI Consumer Electronics Control public header * * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved. */ #ifndef _CEC_UAPI_H #define _CEC_UAPI_H #include #include #define CEC_MAX_MSG_SIZE 16 /** * struct cec_msg - CEC message structure. * @tx_ts: Timestamp in nanoseconds using CLOCK_MONOTONIC. Set by the * driver when the message transmission has finished. * @rx_ts: Timestamp in nanoseconds using CLOCK_MONOTONIC. Set by the * driver when the message was received. * @len: Length in bytes of the message. * @timeout: The timeout (in ms) that is used to timeout CEC_RECEIVE. * Set to 0 if you want to wait forever. This timeout can also be * used with CEC_TRANSMIT as the timeout for waiting for a reply. * If 0, then it will use a 1 second timeout instead of waiting * forever as is done with CEC_RECEIVE. * @sequence: The framework assigns a sequence number to messages that are * sent. This can be used to track replies to previously sent * messages. * @flags: Set to 0. * @msg: The message payload. * @reply: This field is ignored with CEC_RECEIVE and is only used by * CEC_TRANSMIT. If non-zero, then wait for a reply with this * opcode. Set to CEC_MSG_FEATURE_ABORT if you want to wait for * a possible ABORT reply. If there was an error when sending the * msg or FeatureAbort was returned, then reply is set to 0. * If reply is non-zero upon return, then len/msg are set to * the received message. * If reply is zero upon return and status has the * CEC_TX_STATUS_FEATURE_ABORT bit set, then len/msg are set to * the received feature abort message. * If reply is zero upon return and status has the * CEC_TX_STATUS_MAX_RETRIES bit set, then no reply was seen at * all. If reply is non-zero for CEC_TRANSMIT and the message is a * broadcast, then -EINVAL is returned. * if reply is non-zero, then timeout is set to 1000 (the required * maximum response time). * @rx_status: The message receive status bits. Set by the driver. * @tx_status: The message transmit status bits. Set by the driver. * @tx_arb_lost_cnt: The number of 'Arbitration Lost' events. Set by the driver. * @tx_nack_cnt: The number of 'Not Acknowledged' events. Set by the driver. * @tx_low_drive_cnt: The number of 'Low Drive Detected' events. Set by the * driver. * @tx_error_cnt: The number of 'Error' events. Set by the driver. */ struct cec_msg { __u64 tx_ts; __u64 rx_ts; __u32 len; __u32 timeout; __u32 sequence; __u32 flags; __u8 msg[CEC_MAX_MSG_SIZE]; __u8 reply; __u8 rx_status; __u8 tx_status; __u8 tx_arb_lost_cnt; __u8 tx_nack_cnt; __u8 tx_low_drive_cnt; __u8 tx_error_cnt; }; /** * cec_msg_initiator - return the initiator's logical address. * @msg: the message structure */ static __inline__ __u8 cec_msg_initiator(const struct cec_msg *msg) { return msg->msg[0] >> 4; } /** * cec_msg_destination - return the destination's logical address. * @msg: the message structure */ static __inline__ __u8 cec_msg_destination(const struct cec_msg *msg) { return msg->msg[0] & 0xf; } /** * cec_msg_opcode - return the opcode of the message, -1 for poll * @msg: the message structure */ static __inline__ int cec_msg_opcode(const struct cec_msg *msg) { return msg->len > 1 ? msg->msg[1] : -1; } /** * cec_msg_is_broadcast - return true if this is a broadcast message. * @msg: the message structure */ static __inline__ int cec_msg_is_broadcast(const struct cec_msg *msg) { return (msg->msg[0] & 0xf) == 0xf; } /** * cec_msg_init - initialize the message structure. * @msg: the message structure * @initiator: the logical address of the initiator * @destination:the logical address of the destination (0xf for broadcast) * * The whole structure is zeroed, the len field is set to 1 (i.e. a poll * message) and the initiator and destination are filled in. */ static __inline__ void cec_msg_init(struct cec_msg *msg, __u8 initiator, __u8 destination) { memset(msg, 0, sizeof(*msg)); msg->msg[0] = (initiator << 4) | destination; msg->len = 1; } /** * cec_msg_set_reply_to - fill in destination/initiator in a reply message. * @msg: the message structure for the reply * @orig: the original message structure * * Set the msg destination to the orig initiator and the msg initiator to the * orig destination. Note that msg and orig may be the same pointer, in which * case the change is done in place. */ static __inline__ void cec_msg_set_reply_to(struct cec_msg *msg, struct cec_msg *orig) { /* The destination becomes the initiator and vice versa */ msg->msg[0] = (cec_msg_destination(orig) << 4) | cec_msg_initiator(orig); msg->reply = msg->timeout = 0; } /* cec_msg flags field */ #define CEC_MSG_FL_REPLY_TO_FOLLOWERS (1 << 0) #define CEC_MSG_FL_RAW (1 << 1) /* cec_msg tx/rx_status field */ #define CEC_TX_STATUS_OK (1 << 0) #define CEC_TX_STATUS_ARB_LOST (1 << 1) #define CEC_TX_STATUS_NACK (1 << 2) #define CEC_TX_STATUS_LOW_DRIVE (1 << 3) #define CEC_TX_STATUS_ERROR (1 << 4) #define CEC_TX_STATUS_MAX_RETRIES (1 << 5) #define CEC_TX_STATUS_ABORTED (1 << 6) #define CEC_TX_STATUS_TIMEOUT (1 << 7) #define CEC_RX_STATUS_OK (1 << 0) #define CEC_RX_STATUS_TIMEOUT (1 << 1) #define CEC_RX_STATUS_FEATURE_ABORT (1 << 2) #define CEC_RX_STATUS_ABORTED (1 << 3) static __inline__ int cec_msg_status_is_ok(const struct cec_msg *msg) { if (msg->tx_status && !(msg->tx_status & CEC_TX_STATUS_OK)) return 0; if (msg->rx_status && !(msg->rx_status & CEC_RX_STATUS_OK)) return 0; if (!msg->tx_status && !msg->rx_status) return 0; return !(msg->rx_status & CEC_RX_STATUS_FEATURE_ABORT); } #define CEC_LOG_ADDR_INVALID 0xff #define CEC_PHYS_ADDR_INVALID 0xffff /* * The maximum number of logical addresses one device can be assigned to. * The CEC 2.0 spec allows for only 2 logical addresses at the moment. The * Analog Devices CEC hardware supports 3. So let's go wild and go for 4. */ #define CEC_MAX_LOG_ADDRS 4 /* The logical addresses defined by CEC 2.0 */ #define CEC_LOG_ADDR_TV 0 #define CEC_LOG_ADDR_RECORD_1 1 #define CEC_LOG_ADDR_RECORD_2 2 #define CEC_LOG_ADDR_TUNER_1 3 #define CEC_LOG_ADDR_PLAYBACK_1 4 #define CEC_LOG_ADDR_AUDIOSYSTEM 5 #define CEC_LOG_ADDR_TUNER_2 6 #define CEC_LOG_ADDR_TUNER_3 7 #define CEC_LOG_ADDR_PLAYBACK_2 8 #define CEC_LOG_ADDR_RECORD_3 9 #define CEC_LOG_ADDR_TUNER_4 10 #define CEC_LOG_ADDR_PLAYBACK_3 11 #define CEC_LOG_ADDR_BACKUP_1 12 #define CEC_LOG_ADDR_BACKUP_2 13 #define CEC_LOG_ADDR_SPECIFIC 14 #define CEC_LOG_ADDR_UNREGISTERED 15 /* as initiator address */ #define CEC_LOG_ADDR_BROADCAST 15 /* as destination address */ /* The logical address types that the CEC device wants to claim */ #define CEC_LOG_ADDR_TYPE_TV 0 #define CEC_LOG_ADDR_TYPE_RECORD 1 #define CEC_LOG_ADDR_TYPE_TUNER 2 #define CEC_LOG_ADDR_TYPE_PLAYBACK 3 #define CEC_LOG_ADDR_TYPE_AUDIOSYSTEM 4 #define CEC_LOG_ADDR_TYPE_SPECIFIC 5 #define CEC_LOG_ADDR_TYPE_UNREGISTERED 6 /* * Switches should use UNREGISTERED. * Processors should use SPECIFIC. */ #define CEC_LOG_ADDR_MASK_TV (1 << CEC_LOG_ADDR_TV) #define CEC_LOG_ADDR_MASK_RECORD ((1 << CEC_LOG_ADDR_RECORD_1) | \ (1 << CEC_LOG_ADDR_RECORD_2) | \ (1 << CEC_LOG_ADDR_RECORD_3)) #define CEC_LOG_ADDR_MASK_TUNER ((1 << CEC_LOG_ADDR_TUNER_1) | \ (1 << CEC_LOG_ADDR_TUNER_2) | \ (1 << CEC_LOG_ADDR_TUNER_3) | \ (1 << CEC_LOG_ADDR_TUNER_4)) #define CEC_LOG_ADDR_MASK_PLAYBACK ((1 << CEC_LOG_ADDR_PLAYBACK_1) | \ (1 << CEC_LOG_ADDR_PLAYBACK_2) | \ (1 << CEC_LOG_ADDR_PLAYBACK_3)) #define CEC_LOG_ADDR_MASK_AUDIOSYSTEM (1 << CEC_LOG_ADDR_AUDIOSYSTEM) #define CEC_LOG_ADDR_MASK_BACKUP ((1 << CEC_LOG_ADDR_BACKUP_1) | \ (1 << CEC_LOG_ADDR_BACKUP_2)) #define CEC_LOG_ADDR_MASK_SPECIFIC (1 << CEC_LOG_ADDR_SPECIFIC) #define CEC_LOG_ADDR_MASK_UNREGISTERED (1 << CEC_LOG_ADDR_UNREGISTERED) static __inline__ int cec_has_tv(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_TV; } static __inline__ int cec_has_record(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_RECORD; } static __inline__ int cec_has_tuner(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_TUNER; } static __inline__ int cec_has_playback(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_PLAYBACK; } static __inline__ int cec_has_audiosystem(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_AUDIOSYSTEM; } static __inline__ int cec_has_backup(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_BACKUP; } static __inline__ int cec_has_specific(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_SPECIFIC; } static __inline__ int cec_is_unregistered(__u16 log_addr_mask) { return log_addr_mask & CEC_LOG_ADDR_MASK_UNREGISTERED; } static __inline__ int cec_is_unconfigured(__u16 log_addr_mask) { return log_addr_mask == 0; } /* * Use this if there is no vendor ID (CEC_G_VENDOR_ID) or if the vendor ID * should be disabled (CEC_S_VENDOR_ID) */ #define CEC_VENDOR_ID_NONE 0xffffffff /* The message handling modes */ /* Modes for initiator */ #define CEC_MODE_NO_INITIATOR (0x0 << 0) #define CEC_MODE_INITIATOR (0x1 << 0) #define CEC_MODE_EXCL_INITIATOR (0x2 << 0) #define CEC_MODE_INITIATOR_MSK 0x0f /* Modes for follower */ #define CEC_MODE_NO_FOLLOWER (0x0 << 4) #define CEC_MODE_FOLLOWER (0x1 << 4) #define CEC_MODE_EXCL_FOLLOWER (0x2 << 4) #define CEC_MODE_EXCL_FOLLOWER_PASSTHRU (0x3 << 4) #define CEC_MODE_MONITOR_PIN (0xd << 4) #define CEC_MODE_MONITOR (0xe << 4) #define CEC_MODE_MONITOR_ALL (0xf << 4) #define CEC_MODE_FOLLOWER_MSK 0xf0 /* Userspace has to configure the physical address */ #define CEC_CAP_PHYS_ADDR (1 << 0) /* Userspace has to configure the logical addresses */ #define CEC_CAP_LOG_ADDRS (1 << 1) /* Userspace can transmit messages (and thus become follower as well) */ #define CEC_CAP_TRANSMIT (1 << 2) /* * Passthrough all messages instead of processing them. */ #define CEC_CAP_PASSTHROUGH (1 << 3) /* Supports remote control */ #define CEC_CAP_RC (1 << 4) /* Hardware can monitor all messages, not just directed and broadcast. */ #define CEC_CAP_MONITOR_ALL (1 << 5) /* Hardware can use CEC only if the HDMI HPD pin is high. */ #define CEC_CAP_NEEDS_HPD (1 << 6) /* Hardware can monitor CEC pin transitions */ #define CEC_CAP_MONITOR_PIN (1 << 7) /* CEC_ADAP_G_CONNECTOR_INFO is available */ #define CEC_CAP_CONNECTOR_INFO (1 << 8) /** * struct cec_caps - CEC capabilities structure. * @driver: name of the CEC device driver. * @name: name of the CEC device. @driver + @name must be unique. * @available_log_addrs: number of available logical addresses. * @capabilities: capabilities of the CEC adapter. * @version: version of the CEC adapter framework. */ struct cec_caps { char driver[32]; char name[32]; __u32 available_log_addrs; __u32 capabilities; __u32 version; }; /** * struct cec_log_addrs - CEC logical addresses structure. * @log_addr: the claimed logical addresses. Set by the driver. * @log_addr_mask: current logical address mask. Set by the driver. * @cec_version: the CEC version that the adapter should implement. Set by the * caller. * @num_log_addrs: how many logical addresses should be claimed. Set by the * caller. * @vendor_id: the vendor ID of the device. Set by the caller. * @flags: flags. * @osd_name: the OSD name of the device. Set by the caller. * @primary_device_type: the primary device type for each logical address. * Set by the caller. * @log_addr_type: the logical address types. Set by the caller. * @all_device_types: CEC 2.0: all device types represented by the logical * address. Set by the caller. * @features: CEC 2.0: The logical address features. Set by the caller. */ struct cec_log_addrs { __u8 log_addr[CEC_MAX_LOG_ADDRS]; __u16 log_addr_mask; __u8 cec_version; __u8 num_log_addrs; __u32 vendor_id; __u32 flags; char osd_name[15]; __u8 primary_device_type[CEC_MAX_LOG_ADDRS]; __u8 log_addr_type[CEC_MAX_LOG_ADDRS]; /* CEC 2.0 */ __u8 all_device_types[CEC_MAX_LOG_ADDRS]; __u8 features[CEC_MAX_LOG_ADDRS][12]; }; /* Allow a fallback to unregistered */ #define CEC_LOG_ADDRS_FL_ALLOW_UNREG_FALLBACK (1 << 0) /* Passthrough RC messages to the input subsystem */ #define CEC_LOG_ADDRS_FL_ALLOW_RC_PASSTHRU (1 << 1) /* CDC-Only device: supports only CDC messages */ #define CEC_LOG_ADDRS_FL_CDC_ONLY (1 << 2) /** * struct cec_drm_connector_info - tells which drm connector is * associated with the CEC adapter. * @card_no: drm card number * @connector_id: drm connector ID */ struct cec_drm_connector_info { __u32 card_no; __u32 connector_id; }; #define CEC_CONNECTOR_TYPE_NO_CONNECTOR 0 #define CEC_CONNECTOR_TYPE_DRM 1 /** * struct cec_connector_info - tells if and which connector is * associated with the CEC adapter. * @type: connector type (if any) * @drm: drm connector info */ struct cec_connector_info { __u32 type; union { struct cec_drm_connector_info drm; __u32 raw[16]; }; }; /* Events */ /* Event that occurs when the adapter state changes */ #define CEC_EVENT_STATE_CHANGE 1 /* * This event is sent when messages are lost because the application * didn't empty the message queue in time */ #define CEC_EVENT_LOST_MSGS 2 #define CEC_EVENT_PIN_CEC_LOW 3 #define CEC_EVENT_PIN_CEC_HIGH 4 #define CEC_EVENT_PIN_HPD_LOW 5 #define CEC_EVENT_PIN_HPD_HIGH 6 #define CEC_EVENT_PIN_5V_LOW 7 #define CEC_EVENT_PIN_5V_HIGH 8 #define CEC_EVENT_FL_INITIAL_STATE (1 << 0) #define CEC_EVENT_FL_DROPPED_EVENTS (1 << 1) /** * struct cec_event_state_change - used when the CEC adapter changes state. * @phys_addr: the current physical address * @log_addr_mask: the current logical address mask * @have_conn_info: if non-zero, then HDMI connector information is available. * This field is only valid if CEC_CAP_CONNECTOR_INFO is set. If that * capability is set and @have_conn_info is zero, then that indicates * that the HDMI connector device is not instantiated, either because * the HDMI driver is still configuring the device or because the HDMI * device was unbound. */ struct cec_event_state_change { __u16 phys_addr; __u16 log_addr_mask; __u16 have_conn_info; }; /** * struct cec_event_lost_msgs - tells you how many messages were lost. * @lost_msgs: how many messages were lost. */ struct cec_event_lost_msgs { __u32 lost_msgs; }; /** * struct cec_event - CEC event structure * @ts: the timestamp of when the event was sent. * @event: the event. * array. * @state_change: the event payload for CEC_EVENT_STATE_CHANGE. * @lost_msgs: the event payload for CEC_EVENT_LOST_MSGS. * @raw: array to pad the union. */ struct cec_event { __u64 ts; __u32 event; __u32 flags; union { struct cec_event_state_change state_change; struct cec_event_lost_msgs lost_msgs; __u32 raw[16]; }; }; /* ioctls */ /* Adapter capabilities */ #define CEC_ADAP_G_CAPS _IOWR('a', 0, struct cec_caps) /* * phys_addr is either 0 (if this is the CEC root device) * or a valid physical address obtained from the sink's EDID * as read by this CEC device (if this is a source device) * or a physical address obtained and modified from a sink * EDID and used for a sink CEC device. * If nothing is connected, then phys_addr is 0xffff. * See HDMI 1.4b, section 8.7 (Physical Address). * * The CEC_ADAP_S_PHYS_ADDR ioctl may not be available if that is handled * internally. */ #define CEC_ADAP_G_PHYS_ADDR _IOR('a', 1, __u16) #define CEC_ADAP_S_PHYS_ADDR _IOW('a', 2, __u16) /* * Configure the CEC adapter. It sets the device type and which * logical types it will try to claim. It will return which * logical addresses it could actually claim. * An error is returned if the adapter is disabled or if there * is no physical address assigned. */ #define CEC_ADAP_G_LOG_ADDRS _IOR('a', 3, struct cec_log_addrs) #define CEC_ADAP_S_LOG_ADDRS _IOWR('a', 4, struct cec_log_addrs) /* Transmit/receive a CEC command */ #define CEC_TRANSMIT _IOWR('a', 5, struct cec_msg) #define CEC_RECEIVE _IOWR('a', 6, struct cec_msg) /* Dequeue CEC events */ #define CEC_DQEVENT _IOWR('a', 7, struct cec_event) /* * Get and set the message handling mode for this filehandle. */ #define CEC_G_MODE _IOR('a', 8, __u32) #define CEC_S_MODE _IOW('a', 9, __u32) /* Get the connector info */ #define CEC_ADAP_G_CONNECTOR_INFO _IOR('a', 10, struct cec_connector_info) /* * The remainder of this header defines all CEC messages and operands. * The format matters since it the cec-ctl utility parses it to generate * code for implementing all these messages. * * Comments ending with 'Feature' group messages for each feature. * If messages are part of multiple features, then the "Has also" * comment is used to list the previously defined messages that are * supported by the feature. * * Before operands are defined a comment is added that gives the * name of the operand and in brackets the variable name of the * corresponding argument in the cec-funcs.h function. */ /* Messages */ /* One Touch Play Feature */ #define CEC_MSG_ACTIVE_SOURCE 0x82 #define CEC_MSG_IMAGE_VIEW_ON 0x04 #define CEC_MSG_TEXT_VIEW_ON 0x0d /* Routing Control Feature */ /* * Has also: * CEC_MSG_ACTIVE_SOURCE */ #define CEC_MSG_INACTIVE_SOURCE 0x9d #define CEC_MSG_REQUEST_ACTIVE_SOURCE 0x85 #define CEC_MSG_ROUTING_CHANGE 0x80 #define CEC_MSG_ROUTING_INFORMATION 0x81 #define CEC_MSG_SET_STREAM_PATH 0x86 /* Standby Feature */ #define CEC_MSG_STANDBY 0x36 /* One Touch Record Feature */ #define CEC_MSG_RECORD_OFF 0x0b #define CEC_MSG_RECORD_ON 0x09 /* Record Source Type Operand (rec_src_type) */ #define CEC_OP_RECORD_SRC_OWN 1 #define CEC_OP_RECORD_SRC_DIGITAL 2 #define CEC_OP_RECORD_SRC_ANALOG 3 #define CEC_OP_RECORD_SRC_EXT_PLUG 4 #define CEC_OP_RECORD_SRC_EXT_PHYS_ADDR 5 /* Service Identification Method Operand (service_id_method) */ #define CEC_OP_SERVICE_ID_METHOD_BY_DIG_ID 0 #define CEC_OP_SERVICE_ID_METHOD_BY_CHANNEL 1 /* Digital Service Broadcast System Operand (dig_bcast_system) */ #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_GEN 0x00 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_GEN 0x01 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_GEN 0x02 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_BS 0x08 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_CS 0x09 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_T 0x0a #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_CABLE 0x10 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_SAT 0x11 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_T 0x12 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_C 0x18 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_S 0x19 #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_S2 0x1a #define CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_T 0x1b /* Analogue Broadcast Type Operand (ana_bcast_type) */ #define CEC_OP_ANA_BCAST_TYPE_CABLE 0 #define CEC_OP_ANA_BCAST_TYPE_SATELLITE 1 #define CEC_OP_ANA_BCAST_TYPE_TERRESTRIAL 2 /* Broadcast System Operand (bcast_system) */ #define CEC_OP_BCAST_SYSTEM_PAL_BG 0x00 #define CEC_OP_BCAST_SYSTEM_SECAM_LQ 0x01 /* SECAM L' */ #define CEC_OP_BCAST_SYSTEM_PAL_M 0x02 #define CEC_OP_BCAST_SYSTEM_NTSC_M 0x03 #define CEC_OP_BCAST_SYSTEM_PAL_I 0x04 #define CEC_OP_BCAST_SYSTEM_SECAM_DK 0x05 #define CEC_OP_BCAST_SYSTEM_SECAM_BG 0x06 #define CEC_OP_BCAST_SYSTEM_SECAM_L 0x07 #define CEC_OP_BCAST_SYSTEM_PAL_DK 0x08 #define CEC_OP_BCAST_SYSTEM_OTHER 0x1f /* Channel Number Format Operand (channel_number_fmt) */ #define CEC_OP_CHANNEL_NUMBER_FMT_1_PART 0x01 #define CEC_OP_CHANNEL_NUMBER_FMT_2_PART 0x02 #define CEC_MSG_RECORD_STATUS 0x0a /* Record Status Operand (rec_status) */ #define CEC_OP_RECORD_STATUS_CUR_SRC 0x01 #define CEC_OP_RECORD_STATUS_DIG_SERVICE 0x02 #define CEC_OP_RECORD_STATUS_ANA_SERVICE 0x03 #define CEC_OP_RECORD_STATUS_EXT_INPUT 0x04 #define CEC_OP_RECORD_STATUS_NO_DIG_SERVICE 0x05 #define CEC_OP_RECORD_STATUS_NO_ANA_SERVICE 0x06 #define CEC_OP_RECORD_STATUS_NO_SERVICE 0x07 #define CEC_OP_RECORD_STATUS_INVALID_EXT_PLUG 0x09 #define CEC_OP_RECORD_STATUS_INVALID_EXT_PHYS_ADDR 0x0a #define CEC_OP_RECORD_STATUS_UNSUP_CA 0x0b #define CEC_OP_RECORD_STATUS_NO_CA_ENTITLEMENTS 0x0c #define CEC_OP_RECORD_STATUS_CANT_COPY_SRC 0x0d #define CEC_OP_RECORD_STATUS_NO_MORE_COPIES 0x0e #define CEC_OP_RECORD_STATUS_NO_MEDIA 0x10 #define CEC_OP_RECORD_STATUS_PLAYING 0x11 #define CEC_OP_RECORD_STATUS_ALREADY_RECORDING 0x12 #define CEC_OP_RECORD_STATUS_MEDIA_PROT 0x13 #define CEC_OP_RECORD_STATUS_NO_SIGNAL 0x14 #define CEC_OP_RECORD_STATUS_MEDIA_PROBLEM 0x15 #define CEC_OP_RECORD_STATUS_NO_SPACE 0x16 #define CEC_OP_RECORD_STATUS_PARENTAL_LOCK 0x17 #define CEC_OP_RECORD_STATUS_TERMINATED_OK 0x1a #define CEC_OP_RECORD_STATUS_ALREADY_TERM 0x1b #define CEC_OP_RECORD_STATUS_OTHER 0x1f #define CEC_MSG_RECORD_TV_SCREEN 0x0f /* Timer Programming Feature */ #define CEC_MSG_CLEAR_ANALOGUE_TIMER 0x33 /* Recording Sequence Operand (recording_seq) */ #define CEC_OP_REC_SEQ_SUNDAY 0x01 #define CEC_OP_REC_SEQ_MONDAY 0x02 #define CEC_OP_REC_SEQ_TUESDAY 0x04 #define CEC_OP_REC_SEQ_WEDNESDAY 0x08 #define CEC_OP_REC_SEQ_THURSDAY 0x10 #define CEC_OP_REC_SEQ_FRIDAY 0x20 #define CEC_OP_REC_SEQ_SATERDAY 0x40 #define CEC_OP_REC_SEQ_ONCE_ONLY 0x00 #define CEC_MSG_CLEAR_DIGITAL_TIMER 0x99 #define CEC_MSG_CLEAR_EXT_TIMER 0xa1 /* External Source Specifier Operand (ext_src_spec) */ #define CEC_OP_EXT_SRC_PLUG 0x04 #define CEC_OP_EXT_SRC_PHYS_ADDR 0x05 #define CEC_MSG_SET_ANALOGUE_TIMER 0x34 #define CEC_MSG_SET_DIGITAL_TIMER 0x97 #define CEC_MSG_SET_EXT_TIMER 0xa2 #define CEC_MSG_SET_TIMER_PROGRAM_TITLE 0x67 #define CEC_MSG_TIMER_CLEARED_STATUS 0x43 /* Timer Cleared Status Data Operand (timer_cleared_status) */ #define CEC_OP_TIMER_CLR_STAT_RECORDING 0x00 #define CEC_OP_TIMER_CLR_STAT_NO_MATCHING 0x01 #define CEC_OP_TIMER_CLR_STAT_NO_INFO 0x02 #define CEC_OP_TIMER_CLR_STAT_CLEARED 0x80 #define CEC_MSG_TIMER_STATUS 0x35 /* Timer Overlap Warning Operand (timer_overlap_warning) */ #define CEC_OP_TIMER_OVERLAP_WARNING_NO_OVERLAP 0 #define CEC_OP_TIMER_OVERLAP_WARNING_OVERLAP 1 /* Media Info Operand (media_info) */ #define CEC_OP_MEDIA_INFO_UNPROT_MEDIA 0 #define CEC_OP_MEDIA_INFO_PROT_MEDIA 1 #define CEC_OP_MEDIA_INFO_NO_MEDIA 2 /* Programmed Indicator Operand (prog_indicator) */ #define CEC_OP_PROG_IND_NOT_PROGRAMMED 0 #define CEC_OP_PROG_IND_PROGRAMMED 1 /* Programmed Info Operand (prog_info) */ #define CEC_OP_PROG_INFO_ENOUGH_SPACE 0x08 #define CEC_OP_PROG_INFO_NOT_ENOUGH_SPACE 0x09 #define CEC_OP_PROG_INFO_MIGHT_NOT_BE_ENOUGH_SPACE 0x0b #define CEC_OP_PROG_INFO_NONE_AVAILABLE 0x0a /* Not Programmed Error Info Operand (prog_error) */ #define CEC_OP_PROG_ERROR_NO_FREE_TIMER 0x01 #define CEC_OP_PROG_ERROR_DATE_OUT_OF_RANGE 0x02 #define CEC_OP_PROG_ERROR_REC_SEQ_ERROR 0x03 #define CEC_OP_PROG_ERROR_INV_EXT_PLUG 0x04 #define CEC_OP_PROG_ERROR_INV_EXT_PHYS_ADDR 0x05 #define CEC_OP_PROG_ERROR_CA_UNSUPP 0x06 #define CEC_OP_PROG_ERROR_INSUF_CA_ENTITLEMENTS 0x07 #define CEC_OP_PROG_ERROR_RESOLUTION_UNSUPP 0x08 #define CEC_OP_PROG_ERROR_PARENTAL_LOCK 0x09 #define CEC_OP_PROG_ERROR_CLOCK_FAILURE 0x0a #define CEC_OP_PROG_ERROR_DUPLICATE 0x0e /* System Information Feature */ #define CEC_MSG_CEC_VERSION 0x9e /* CEC Version Operand (cec_version) */ #define CEC_OP_CEC_VERSION_1_3A 4 #define CEC_OP_CEC_VERSION_1_4 5 #define CEC_OP_CEC_VERSION_2_0 6 #define CEC_MSG_GET_CEC_VERSION 0x9f #define CEC_MSG_GIVE_PHYSICAL_ADDR 0x83 #define CEC_MSG_GET_MENU_LANGUAGE 0x91 #define CEC_MSG_REPORT_PHYSICAL_ADDR 0x84 /* Primary Device Type Operand (prim_devtype) */ #define CEC_OP_PRIM_DEVTYPE_TV 0 #define CEC_OP_PRIM_DEVTYPE_RECORD 1 #define CEC_OP_PRIM_DEVTYPE_TUNER 3 #define CEC_OP_PRIM_DEVTYPE_PLAYBACK 4 #define CEC_OP_PRIM_DEVTYPE_AUDIOSYSTEM 5 #define CEC_OP_PRIM_DEVTYPE_SWITCH 6 #define CEC_OP_PRIM_DEVTYPE_PROCESSOR 7 #define CEC_MSG_SET_MENU_LANGUAGE 0x32 #define CEC_MSG_REPORT_FEATURES 0xa6 /* HDMI 2.0 */ /* All Device Types Operand (all_device_types) */ #define CEC_OP_ALL_DEVTYPE_TV 0x80 #define CEC_OP_ALL_DEVTYPE_RECORD 0x40 #define CEC_OP_ALL_DEVTYPE_TUNER 0x20 #define CEC_OP_ALL_DEVTYPE_PLAYBACK 0x10 #define CEC_OP_ALL_DEVTYPE_AUDIOSYSTEM 0x08 #define CEC_OP_ALL_DEVTYPE_SWITCH 0x04 /* * And if you wondering what happened to PROCESSOR devices: those should * be mapped to a SWITCH. */ /* Valid for RC Profile and Device Feature operands */ #define CEC_OP_FEAT_EXT 0x80 /* Extension bit */ /* RC Profile Operand (rc_profile) */ #define CEC_OP_FEAT_RC_TV_PROFILE_NONE 0x00 #define CEC_OP_FEAT_RC_TV_PROFILE_1 0x02 #define CEC_OP_FEAT_RC_TV_PROFILE_2 0x06 #define CEC_OP_FEAT_RC_TV_PROFILE_3 0x0a #define CEC_OP_FEAT_RC_TV_PROFILE_4 0x0e #define CEC_OP_FEAT_RC_SRC_HAS_DEV_ROOT_MENU 0x50 #define CEC_OP_FEAT_RC_SRC_HAS_DEV_SETUP_MENU 0x48 #define CEC_OP_FEAT_RC_SRC_HAS_CONTENTS_MENU 0x44 #define CEC_OP_FEAT_RC_SRC_HAS_MEDIA_TOP_MENU 0x42 #define CEC_OP_FEAT_RC_SRC_HAS_MEDIA_CONTEXT_MENU 0x41 /* Device Feature Operand (dev_features) */ #define CEC_OP_FEAT_DEV_HAS_RECORD_TV_SCREEN 0x40 #define CEC_OP_FEAT_DEV_HAS_SET_OSD_STRING 0x20 #define CEC_OP_FEAT_DEV_HAS_DECK_CONTROL 0x10 #define CEC_OP_FEAT_DEV_HAS_SET_AUDIO_RATE 0x08 #define CEC_OP_FEAT_DEV_SINK_HAS_ARC_TX 0x04 #define CEC_OP_FEAT_DEV_SOURCE_HAS_ARC_RX 0x02 #define CEC_OP_FEAT_DEV_HAS_SET_AUDIO_VOLUME_LEVEL 0x01 #define CEC_MSG_GIVE_FEATURES 0xa5 /* HDMI 2.0 */ /* Deck Control Feature */ #define CEC_MSG_DECK_CONTROL 0x42 /* Deck Control Mode Operand (deck_control_mode) */ #define CEC_OP_DECK_CTL_MODE_SKIP_FWD 1 #define CEC_OP_DECK_CTL_MODE_SKIP_REV 2 #define CEC_OP_DECK_CTL_MODE_STOP 3 #define CEC_OP_DECK_CTL_MODE_EJECT 4 #define CEC_MSG_DECK_STATUS 0x1b /* Deck Info Operand (deck_info) */ #define CEC_OP_DECK_INFO_PLAY 0x11 #define CEC_OP_DECK_INFO_RECORD 0x12 #define CEC_OP_DECK_INFO_PLAY_REV 0x13 #define CEC_OP_DECK_INFO_STILL 0x14 #define CEC_OP_DECK_INFO_SLOW 0x15 #define CEC_OP_DECK_INFO_SLOW_REV 0x16 #define CEC_OP_DECK_INFO_FAST_FWD 0x17 #define CEC_OP_DECK_INFO_FAST_REV 0x18 #define CEC_OP_DECK_INFO_NO_MEDIA 0x19 #define CEC_OP_DECK_INFO_STOP 0x1a #define CEC_OP_DECK_INFO_SKIP_FWD 0x1b #define CEC_OP_DECK_INFO_SKIP_REV 0x1c #define CEC_OP_DECK_INFO_INDEX_SEARCH_FWD 0x1d #define CEC_OP_DECK_INFO_INDEX_SEARCH_REV 0x1e #define CEC_OP_DECK_INFO_OTHER 0x1f #define CEC_MSG_GIVE_DECK_STATUS 0x1a /* Status Request Operand (status_req) */ #define CEC_OP_STATUS_REQ_ON 1 #define CEC_OP_STATUS_REQ_OFF 2 #define CEC_OP_STATUS_REQ_ONCE 3 #define CEC_MSG_PLAY 0x41 /* Play Mode Operand (play_mode) */ #define CEC_OP_PLAY_MODE_PLAY_FWD 0x24 #define CEC_OP_PLAY_MODE_PLAY_REV 0x20 #define CEC_OP_PLAY_MODE_PLAY_STILL 0x25 #define CEC_OP_PLAY_MODE_PLAY_FAST_FWD_MIN 0x05 #define CEC_OP_PLAY_MODE_PLAY_FAST_FWD_MED 0x06 #define CEC_OP_PLAY_MODE_PLAY_FAST_FWD_MAX 0x07 #define CEC_OP_PLAY_MODE_PLAY_FAST_REV_MIN 0x09 #define CEC_OP_PLAY_MODE_PLAY_FAST_REV_MED 0x0a #define CEC_OP_PLAY_MODE_PLAY_FAST_REV_MAX 0x0b #define CEC_OP_PLAY_MODE_PLAY_SLOW_FWD_MIN 0x15 #define CEC_OP_PLAY_MODE_PLAY_SLOW_FWD_MED 0x16 #define CEC_OP_PLAY_MODE_PLAY_SLOW_FWD_MAX 0x17 #define CEC_OP_PLAY_MODE_PLAY_SLOW_REV_MIN 0x19 #define CEC_OP_PLAY_MODE_PLAY_SLOW_REV_MED 0x1a #define CEC_OP_PLAY_MODE_PLAY_SLOW_REV_MAX 0x1b /* Tuner Control Feature */ #define CEC_MSG_GIVE_TUNER_DEVICE_STATUS 0x08 #define CEC_MSG_SELECT_ANALOGUE_SERVICE 0x92 #define CEC_MSG_SELECT_DIGITAL_SERVICE 0x93 #define CEC_MSG_TUNER_DEVICE_STATUS 0x07 /* Recording Flag Operand (rec_flag) */ #define CEC_OP_REC_FLAG_USED 0 #define CEC_OP_REC_FLAG_NOT_USED 1 /* Tuner Display Info Operand (tuner_display_info) */ #define CEC_OP_TUNER_DISPLAY_INFO_DIGITAL 0 #define CEC_OP_TUNER_DISPLAY_INFO_NONE 1 #define CEC_OP_TUNER_DISPLAY_INFO_ANALOGUE 2 #define CEC_MSG_TUNER_STEP_DECREMENT 0x06 #define CEC_MSG_TUNER_STEP_INCREMENT 0x05 /* Vendor Specific Commands Feature */ /* * Has also: * CEC_MSG_CEC_VERSION * CEC_MSG_GET_CEC_VERSION */ #define CEC_MSG_DEVICE_VENDOR_ID 0x87 #define CEC_MSG_GIVE_DEVICE_VENDOR_ID 0x8c #define CEC_MSG_VENDOR_COMMAND 0x89 #define CEC_MSG_VENDOR_COMMAND_WITH_ID 0xa0 #define CEC_MSG_VENDOR_REMOTE_BUTTON_DOWN 0x8a #define CEC_MSG_VENDOR_REMOTE_BUTTON_UP 0x8b /* OSD Display Feature */ #define CEC_MSG_SET_OSD_STRING 0x64 /* Display Control Operand (disp_ctl) */ #define CEC_OP_DISP_CTL_DEFAULT 0x00 #define CEC_OP_DISP_CTL_UNTIL_CLEARED 0x40 #define CEC_OP_DISP_CTL_CLEAR 0x80 /* Device OSD Transfer Feature */ #define CEC_MSG_GIVE_OSD_NAME 0x46 #define CEC_MSG_SET_OSD_NAME 0x47 /* Device Menu Control Feature */ #define CEC_MSG_MENU_REQUEST 0x8d /* Menu Request Type Operand (menu_req) */ #define CEC_OP_MENU_REQUEST_ACTIVATE 0x00 #define CEC_OP_MENU_REQUEST_DEACTIVATE 0x01 #define CEC_OP_MENU_REQUEST_QUERY 0x02 #define CEC_MSG_MENU_STATUS 0x8e /* Menu State Operand (menu_state) */ #define CEC_OP_MENU_STATE_ACTIVATED 0x00 #define CEC_OP_MENU_STATE_DEACTIVATED 0x01 #define CEC_MSG_USER_CONTROL_PRESSED 0x44 /* UI Broadcast Type Operand (ui_bcast_type) */ #define CEC_OP_UI_BCAST_TYPE_TOGGLE_ALL 0x00 #define CEC_OP_UI_BCAST_TYPE_TOGGLE_DIG_ANA 0x01 #define CEC_OP_UI_BCAST_TYPE_ANALOGUE 0x10 #define CEC_OP_UI_BCAST_TYPE_ANALOGUE_T 0x20 #define CEC_OP_UI_BCAST_TYPE_ANALOGUE_CABLE 0x30 #define CEC_OP_UI_BCAST_TYPE_ANALOGUE_SAT 0x40 #define CEC_OP_UI_BCAST_TYPE_DIGITAL 0x50 #define CEC_OP_UI_BCAST_TYPE_DIGITAL_T 0x60 #define CEC_OP_UI_BCAST_TYPE_DIGITAL_CABLE 0x70 #define CEC_OP_UI_BCAST_TYPE_DIGITAL_SAT 0x80 #define CEC_OP_UI_BCAST_TYPE_DIGITAL_COM_SAT 0x90 #define CEC_OP_UI_BCAST_TYPE_DIGITAL_COM_SAT2 0x91 #define CEC_OP_UI_BCAST_TYPE_IP 0xa0 /* UI Sound Presentation Control Operand (ui_snd_pres_ctl) */ #define CEC_OP_UI_SND_PRES_CTL_DUAL_MONO 0x10 #define CEC_OP_UI_SND_PRES_CTL_KARAOKE 0x20 #define CEC_OP_UI_SND_PRES_CTL_DOWNMIX 0x80 #define CEC_OP_UI_SND_PRES_CTL_REVERB 0x90 #define CEC_OP_UI_SND_PRES_CTL_EQUALIZER 0xa0 #define CEC_OP_UI_SND_PRES_CTL_BASS_UP 0xb1 #define CEC_OP_UI_SND_PRES_CTL_BASS_NEUTRAL 0xb2 #define CEC_OP_UI_SND_PRES_CTL_BASS_DOWN 0xb3 #define CEC_OP_UI_SND_PRES_CTL_TREBLE_UP 0xc1 #define CEC_OP_UI_SND_PRES_CTL_TREBLE_NEUTRAL 0xc2 #define CEC_OP_UI_SND_PRES_CTL_TREBLE_DOWN 0xc3 #define CEC_MSG_USER_CONTROL_RELEASED 0x45 /* Remote Control Passthrough Feature */ /* * Has also: * CEC_MSG_USER_CONTROL_PRESSED * CEC_MSG_USER_CONTROL_RELEASED */ /* Power Status Feature */ #define CEC_MSG_GIVE_DEVICE_POWER_STATUS 0x8f #define CEC_MSG_REPORT_POWER_STATUS 0x90 /* Power Status Operand (pwr_state) */ #define CEC_OP_POWER_STATUS_ON 0 #define CEC_OP_POWER_STATUS_STANDBY 1 #define CEC_OP_POWER_STATUS_TO_ON 2 #define CEC_OP_POWER_STATUS_TO_STANDBY 3 /* General Protocol Messages */ #define CEC_MSG_FEATURE_ABORT 0x00 /* Abort Reason Operand (reason) */ #define CEC_OP_ABORT_UNRECOGNIZED_OP 0 #define CEC_OP_ABORT_INCORRECT_MODE 1 #define CEC_OP_ABORT_NO_SOURCE 2 #define CEC_OP_ABORT_INVALID_OP 3 #define CEC_OP_ABORT_REFUSED 4 #define CEC_OP_ABORT_UNDETERMINED 5 #define CEC_MSG_ABORT 0xff /* System Audio Control Feature */ /* * Has also: * CEC_MSG_USER_CONTROL_PRESSED * CEC_MSG_USER_CONTROL_RELEASED */ #define CEC_MSG_GIVE_AUDIO_STATUS 0x71 #define CEC_MSG_GIVE_SYSTEM_AUDIO_MODE_STATUS 0x7d #define CEC_MSG_REPORT_AUDIO_STATUS 0x7a /* Audio Mute Status Operand (aud_mute_status) */ #define CEC_OP_AUD_MUTE_STATUS_OFF 0 #define CEC_OP_AUD_MUTE_STATUS_ON 1 #define CEC_MSG_REPORT_SHORT_AUDIO_DESCRIPTOR 0xa3 #define CEC_MSG_REQUEST_SHORT_AUDIO_DESCRIPTOR 0xa4 #define CEC_MSG_SET_SYSTEM_AUDIO_MODE 0x72 /* System Audio Status Operand (sys_aud_status) */ #define CEC_OP_SYS_AUD_STATUS_OFF 0 #define CEC_OP_SYS_AUD_STATUS_ON 1 #define CEC_MSG_SYSTEM_AUDIO_MODE_REQUEST 0x70 #define CEC_MSG_SYSTEM_AUDIO_MODE_STATUS 0x7e /* Audio Format ID Operand (audio_format_id) */ #define CEC_OP_AUD_FMT_ID_CEA861 0 #define CEC_OP_AUD_FMT_ID_CEA861_CXT 1 #define CEC_MSG_SET_AUDIO_VOLUME_LEVEL 0x73 /* Audio Rate Control Feature */ #define CEC_MSG_SET_AUDIO_RATE 0x9a /* Audio Rate Operand (audio_rate) */ #define CEC_OP_AUD_RATE_OFF 0 #define CEC_OP_AUD_RATE_WIDE_STD 1 #define CEC_OP_AUD_RATE_WIDE_FAST 2 #define CEC_OP_AUD_RATE_WIDE_SLOW 3 #define CEC_OP_AUD_RATE_NARROW_STD 4 #define CEC_OP_AUD_RATE_NARROW_FAST 5 #define CEC_OP_AUD_RATE_NARROW_SLOW 6 /* Audio Return Channel Control Feature */ #define CEC_MSG_INITIATE_ARC 0xc0 #define CEC_MSG_REPORT_ARC_INITIATED 0xc1 #define CEC_MSG_REPORT_ARC_TERMINATED 0xc2 #define CEC_MSG_REQUEST_ARC_INITIATION 0xc3 #define CEC_MSG_REQUEST_ARC_TERMINATION 0xc4 #define CEC_MSG_TERMINATE_ARC 0xc5 /* Dynamic Audio Lipsync Feature */ /* Only for CEC 2.0 and up */ #define CEC_MSG_REQUEST_CURRENT_LATENCY 0xa7 #define CEC_MSG_REPORT_CURRENT_LATENCY 0xa8 /* Low Latency Mode Operand (low_latency_mode) */ #define CEC_OP_LOW_LATENCY_MODE_OFF 0 #define CEC_OP_LOW_LATENCY_MODE_ON 1 /* Audio Output Compensated Operand (audio_out_compensated) */ #define CEC_OP_AUD_OUT_COMPENSATED_NA 0 #define CEC_OP_AUD_OUT_COMPENSATED_DELAY 1 #define CEC_OP_AUD_OUT_COMPENSATED_NO_DELAY 2 #define CEC_OP_AUD_OUT_COMPENSATED_PARTIAL_DELAY 3 /* Capability Discovery and Control Feature */ #define CEC_MSG_CDC_MESSAGE 0xf8 /* Ethernet-over-HDMI: nobody ever does this... */ #define CEC_MSG_CDC_HEC_INQUIRE_STATE 0x00 #define CEC_MSG_CDC_HEC_REPORT_STATE 0x01 /* HEC Functionality State Operand (hec_func_state) */ #define CEC_OP_HEC_FUNC_STATE_NOT_SUPPORTED 0 #define CEC_OP_HEC_FUNC_STATE_INACTIVE 1 #define CEC_OP_HEC_FUNC_STATE_ACTIVE 2 #define CEC_OP_HEC_FUNC_STATE_ACTIVATION_FIELD 3 /* Host Functionality State Operand (host_func_state) */ #define CEC_OP_HOST_FUNC_STATE_NOT_SUPPORTED 0 #define CEC_OP_HOST_FUNC_STATE_INACTIVE 1 #define CEC_OP_HOST_FUNC_STATE_ACTIVE 2 /* ENC Functionality State Operand (enc_func_state) */ #define CEC_OP_ENC_FUNC_STATE_EXT_CON_NOT_SUPPORTED 0 #define CEC_OP_ENC_FUNC_STATE_EXT_CON_INACTIVE 1 #define CEC_OP_ENC_FUNC_STATE_EXT_CON_ACTIVE 2 /* CDC Error Code Operand (cdc_errcode) */ #define CEC_OP_CDC_ERROR_CODE_NONE 0 #define CEC_OP_CDC_ERROR_CODE_CAP_UNSUPPORTED 1 #define CEC_OP_CDC_ERROR_CODE_WRONG_STATE 2 #define CEC_OP_CDC_ERROR_CODE_OTHER 3 /* HEC Support Operand (hec_support) */ #define CEC_OP_HEC_SUPPORT_NO 0 #define CEC_OP_HEC_SUPPORT_YES 1 /* HEC Activation Operand (hec_activation) */ #define CEC_OP_HEC_ACTIVATION_ON 0 #define CEC_OP_HEC_ACTIVATION_OFF 1 #define CEC_MSG_CDC_HEC_SET_STATE_ADJACENT 0x02 #define CEC_MSG_CDC_HEC_SET_STATE 0x03 /* HEC Set State Operand (hec_set_state) */ #define CEC_OP_HEC_SET_STATE_DEACTIVATE 0 #define CEC_OP_HEC_SET_STATE_ACTIVATE 1 #define CEC_MSG_CDC_HEC_REQUEST_DEACTIVATION 0x04 #define CEC_MSG_CDC_HEC_NOTIFY_ALIVE 0x05 #define CEC_MSG_CDC_HEC_DISCOVER 0x06 /* Hotplug Detect messages */ #define CEC_MSG_CDC_HPD_SET_STATE 0x10 /* HPD State Operand (hpd_state) */ #define CEC_OP_HPD_STATE_CP_EDID_DISABLE 0 #define CEC_OP_HPD_STATE_CP_EDID_ENABLE 1 #define CEC_OP_HPD_STATE_CP_EDID_DISABLE_ENABLE 2 #define CEC_OP_HPD_STATE_EDID_DISABLE 3 #define CEC_OP_HPD_STATE_EDID_ENABLE 4 #define CEC_OP_HPD_STATE_EDID_DISABLE_ENABLE 5 #define CEC_MSG_CDC_HPD_REPORT_STATE 0x11 /* HPD Error Code Operand (hpd_error) */ #define CEC_OP_HPD_ERROR_NONE 0 #define CEC_OP_HPD_ERROR_INITIATOR_NOT_CAPABLE 1 #define CEC_OP_HPD_ERROR_INITIATOR_WRONG_STATE 2 #define CEC_OP_HPD_ERROR_OTHER 3 #define CEC_OP_HPD_ERROR_NONE_NO_VIDEO 4 /* End of Messages */ /* Helper functions to identify the 'special' CEC devices */ static __inline__ int cec_is_2nd_tv(const struct cec_log_addrs *las) { /* * It is a second TV if the logical address is 14 or 15 and the * primary device type is a TV. */ return las->num_log_addrs && las->log_addr[0] >= CEC_LOG_ADDR_SPECIFIC && las->primary_device_type[0] == CEC_OP_PRIM_DEVTYPE_TV; } static __inline__ int cec_is_processor(const struct cec_log_addrs *las) { /* * It is a processor if the logical address is 12-15 and the * primary device type is a Processor. */ return las->num_log_addrs && las->log_addr[0] >= CEC_LOG_ADDR_BACKUP_1 && las->primary_device_type[0] == CEC_OP_PRIM_DEVTYPE_PROCESSOR; } static __inline__ int cec_is_switch(const struct cec_log_addrs *las) { /* * It is a switch if the logical address is 15 and the * primary device type is a Switch and the CDC-Only flag is not set. */ return las->num_log_addrs == 1 && las->log_addr[0] == CEC_LOG_ADDR_UNREGISTERED && las->primary_device_type[0] == CEC_OP_PRIM_DEVTYPE_SWITCH && !(las->flags & CEC_LOG_ADDRS_FL_CDC_ONLY); } static __inline__ int cec_is_cdc_only(const struct cec_log_addrs *las) { /* * It is a CDC-only device if the logical address is 15 and the * primary device type is a Switch and the CDC-Only flag is set. */ return las->num_log_addrs == 1 && las->log_addr[0] == CEC_LOG_ADDR_UNREGISTERED && las->primary_device_type[0] == CEC_OP_PRIM_DEVTYPE_SWITCH && (las->flags & CEC_LOG_ADDRS_FL_CDC_ONLY); } #endif linux/eventpoll.h000064400000005256151027430560010077 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * include/linux/eventpoll.h ( Efficient event polling implementation ) * Copyright (C) 2001,...,2006 Davide Libenzi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Davide Libenzi * */ #ifndef _LINUX_EVENTPOLL_H #define _LINUX_EVENTPOLL_H /* For O_CLOEXEC */ #include #include /* Flags for epoll_create1. */ #define EPOLL_CLOEXEC O_CLOEXEC /* Valid opcodes to issue to sys_epoll_ctl() */ #define EPOLL_CTL_ADD 1 #define EPOLL_CTL_DEL 2 #define EPOLL_CTL_MOD 3 /* Epoll event masks */ #define EPOLLIN (__poll_t)0x00000001 #define EPOLLPRI (__poll_t)0x00000002 #define EPOLLOUT (__poll_t)0x00000004 #define EPOLLERR (__poll_t)0x00000008 #define EPOLLHUP (__poll_t)0x00000010 #define EPOLLNVAL (__poll_t)0x00000020 #define EPOLLRDNORM (__poll_t)0x00000040 #define EPOLLRDBAND (__poll_t)0x00000080 #define EPOLLWRNORM (__poll_t)0x00000100 #define EPOLLWRBAND (__poll_t)0x00000200 #define EPOLLMSG (__poll_t)0x00000400 #define EPOLLRDHUP (__poll_t)0x00002000 /* Set exclusive wakeup mode for the target file descriptor */ #define EPOLLEXCLUSIVE (__poll_t)(1U << 28) /* * Request the handling of system wakeup events so as to prevent system suspends * from happening while those events are being processed. * * Assuming neither EPOLLET nor EPOLLONESHOT is set, system suspends will not be * re-allowed until epoll_wait is called again after consuming the wakeup * event(s). * * Requires CAP_BLOCK_SUSPEND */ #define EPOLLWAKEUP (__poll_t)(1U << 29) /* Set the One Shot behaviour for the target file descriptor */ #define EPOLLONESHOT (__poll_t)(1U << 30) /* Set the Edge Triggered behaviour for the target file descriptor */ #define EPOLLET (__poll_t)(1U << 31) /* * On x86-64 make the 64bit structure have the same alignment as the * 32bit structure. This makes 32bit emulation easier. * * UML/x86_64 needs the same packing as x86_64 */ #ifdef __x86_64__ #define EPOLL_PACKED __attribute__((packed)) #else #define EPOLL_PACKED #endif struct epoll_event { __poll_t events; __u64 data; } EPOLL_PACKED; #ifdef CONFIG_PM_SLEEP static __inline__ void ep_take_care_of_epollwakeup(struct epoll_event *epev) { if ((epev->events & EPOLLWAKEUP) && !capable(CAP_BLOCK_SUSPEND)) epev->events &= ~EPOLLWAKEUP; } #else static __inline__ void ep_take_care_of_epollwakeup(struct epoll_event *epev) { epev->events &= ~EPOLLWAKEUP; } #endif #endif /* _LINUX_EVENTPOLL_H */ linux/ultrasound.h000064400000010722151027430560010261 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ULTRASOUND_H_ #define _ULTRASOUND_H_ /* * ultrasound.h - Macros for programming the Gravis Ultrasound * These macros are extremely device dependent * and not portable. */ /* * Copyright (C) by Hannu Savolainen 1993-1997 * * OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL) * Version 2 (June 1991). See the "COPYING" file distributed with this software * for more info. */ /* * Private events for Gravis Ultrasound (GUS) * * Format: * byte 0 - SEQ_PRIVATE (0xfe) * byte 1 - Synthesizer device number (0-N) * byte 2 - Command (see below) * byte 3 - Voice number (0-31) * bytes 4 and 5 - parameter P1 (unsigned short) * bytes 6 and 7 - parameter P2 (unsigned short) * * Commands: * Each command affects one voice defined in byte 3. * Unused parameters (P1 and/or P2 *MUST* be initialized to zero). * _GUS_NUMVOICES - Sets max. number of concurrent voices (P1=14-31, default 16) * _GUS_VOICESAMPLE- ************ OBSOLETE ************* * _GUS_VOICEON - Starts voice (P1=voice mode) * _GUS_VOICEOFF - Stops voice (no parameters) * _GUS_VOICEFADE - Stops the voice smoothly. * _GUS_VOICEMODE - Alters the voice mode, don't start or stop voice (P1=voice mode) * _GUS_VOICEBALA - Sets voice balance (P1, 0=left, 7=middle and 15=right, default 7) * _GUS_VOICEFREQ - Sets voice (sample) playback frequency (P1=Hz) * _GUS_VOICEVOL - Sets voice volume (P1=volume, 0xfff=max, 0xeff=half, 0x000=off) * _GUS_VOICEVOL2 - Sets voice volume (P1=volume, 0xfff=max, 0xeff=half, 0x000=off) * (Like GUS_VOICEVOL but doesn't change the hw * volume. It just updates volume in the voice table). * * _GUS_RAMPRANGE - Sets limits for volume ramping (P1=low volume, P2=high volume) * _GUS_RAMPRATE - Sets the speed for volume ramping (P1=scale, P2=rate) * _GUS_RAMPMODE - Sets the volume ramping mode (P1=ramping mode) * _GUS_RAMPON - Starts volume ramping (no parameters) * _GUS_RAMPOFF - Stops volume ramping (no parameters) * _GUS_VOLUME_SCALE - Changes the volume calculation constants * for all voices. */ #define _GUS_NUMVOICES 0x00 #define _GUS_VOICESAMPLE 0x01 /* OBSOLETE */ #define _GUS_VOICEON 0x02 #define _GUS_VOICEOFF 0x03 #define _GUS_VOICEMODE 0x04 #define _GUS_VOICEBALA 0x05 #define _GUS_VOICEFREQ 0x06 #define _GUS_VOICEVOL 0x07 #define _GUS_RAMPRANGE 0x08 #define _GUS_RAMPRATE 0x09 #define _GUS_RAMPMODE 0x0a #define _GUS_RAMPON 0x0b #define _GUS_RAMPOFF 0x0c #define _GUS_VOICEFADE 0x0d #define _GUS_VOLUME_SCALE 0x0e #define _GUS_VOICEVOL2 0x0f #define _GUS_VOICE_POS 0x10 /* * GUS API macros */ #define _GUS_CMD(chn, voice, cmd, p1, p2) \ {_SEQ_NEEDBUF(8); _seqbuf[_seqbufptr] = SEQ_PRIVATE;\ _seqbuf[_seqbufptr+1] = (chn); _seqbuf[_seqbufptr+2] = cmd;\ _seqbuf[_seqbufptr+3] = voice;\ *(unsigned short*)&_seqbuf[_seqbufptr+4] = p1;\ *(unsigned short*)&_seqbuf[_seqbufptr+6] = p2;\ _SEQ_ADVBUF(8);} #define GUS_NUMVOICES(chn, p1) _GUS_CMD(chn, 0, _GUS_NUMVOICES, (p1), 0) #define GUS_VOICESAMPLE(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_VOICESAMPLE, (p1), 0) /* OBSOLETE */ #define GUS_VOICEON(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_VOICEON, (p1), 0) #define GUS_VOICEOFF(chn, voice) _GUS_CMD(chn, voice, _GUS_VOICEOFF, 0, 0) #define GUS_VOICEFADE(chn, voice) _GUS_CMD(chn, voice, _GUS_VOICEFADE, 0, 0) #define GUS_VOICEMODE(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_VOICEMODE, (p1), 0) #define GUS_VOICEBALA(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_VOICEBALA, (p1), 0) #define GUS_VOICEFREQ(chn, voice, p) _GUS_CMD(chn, voice, _GUS_VOICEFREQ, \ (p) & 0xffff, ((p) >> 16) & 0xffff) #define GUS_VOICEVOL(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_VOICEVOL, (p1), 0) #define GUS_VOICEVOL2(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_VOICEVOL2, (p1), 0) #define GUS_RAMPRANGE(chn, voice, low, high) _GUS_CMD(chn, voice, _GUS_RAMPRANGE, (low), (high)) #define GUS_RAMPRATE(chn, voice, p1, p2) _GUS_CMD(chn, voice, _GUS_RAMPRATE, (p1), (p2)) #define GUS_RAMPMODE(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_RAMPMODE, (p1), 0) #define GUS_RAMPON(chn, voice, p1) _GUS_CMD(chn, voice, _GUS_RAMPON, (p1), 0) #define GUS_RAMPOFF(chn, voice) _GUS_CMD(chn, voice, _GUS_RAMPOFF, 0, 0) #define GUS_VOLUME_SCALE(chn, voice, p1, p2) _GUS_CMD(chn, voice, _GUS_VOLUME_SCALE, (p1), (p2)) #define GUS_VOICE_POS(chn, voice, p) _GUS_CMD(chn, voice, _GUS_VOICE_POS, \ (p) & 0xffff, ((p) >> 16) & 0xffff) #endif linux/ppdev.h000064400000006213151027430560007177 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * linux/include/linux/ppdev.h * * User-space parallel port device driver (header file). * * Copyright (C) 1998-9 Tim Waugh * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Added PPGETTIME/PPSETTIME, Fred Barnes, 1999 * Added PPGETMODES/PPGETMODE/PPGETPHASE, Fred Barnes , 03/01/2001 */ #define PP_IOCTL 'p' /* Set mode for read/write (e.g. IEEE1284_MODE_EPP) */ #define PPSETMODE _IOW(PP_IOCTL, 0x80, int) /* Read status */ #define PPRSTATUS _IOR(PP_IOCTL, 0x81, unsigned char) #define PPWSTATUS OBSOLETE__IOW(PP_IOCTL, 0x82, unsigned char) /* Read/write control */ #define PPRCONTROL _IOR(PP_IOCTL, 0x83, unsigned char) #define PPWCONTROL _IOW(PP_IOCTL, 0x84, unsigned char) struct ppdev_frob_struct { unsigned char mask; unsigned char val; }; #define PPFCONTROL _IOW(PP_IOCTL, 0x8e, struct ppdev_frob_struct) /* Read/write data */ #define PPRDATA _IOR(PP_IOCTL, 0x85, unsigned char) #define PPWDATA _IOW(PP_IOCTL, 0x86, unsigned char) /* Read/write econtrol (not used) */ #define PPRECONTROL OBSOLETE__IOR(PP_IOCTL, 0x87, unsigned char) #define PPWECONTROL OBSOLETE__IOW(PP_IOCTL, 0x88, unsigned char) /* Read/write FIFO (not used) */ #define PPRFIFO OBSOLETE__IOR(PP_IOCTL, 0x89, unsigned char) #define PPWFIFO OBSOLETE__IOW(PP_IOCTL, 0x8a, unsigned char) /* Claim the port to start using it */ #define PPCLAIM _IO(PP_IOCTL, 0x8b) /* Release the port when you aren't using it */ #define PPRELEASE _IO(PP_IOCTL, 0x8c) /* Yield the port (release it if another driver is waiting, * then reclaim) */ #define PPYIELD _IO(PP_IOCTL, 0x8d) /* Register device exclusively (must be before PPCLAIM). */ #define PPEXCL _IO(PP_IOCTL, 0x8f) /* Data line direction: non-zero for input mode. */ #define PPDATADIR _IOW(PP_IOCTL, 0x90, int) /* Negotiate a particular IEEE 1284 mode. */ #define PPNEGOT _IOW(PP_IOCTL, 0x91, int) /* Set control lines when an interrupt occurs. */ #define PPWCTLONIRQ _IOW(PP_IOCTL, 0x92, unsigned char) /* Clear (and return) interrupt count. */ #define PPCLRIRQ _IOR(PP_IOCTL, 0x93, int) /* Set the IEEE 1284 phase that we're in (e.g. IEEE1284_PH_FWD_IDLE) */ #define PPSETPHASE _IOW(PP_IOCTL, 0x94, int) /* Set and get port timeout (struct timeval's) */ #define PPGETTIME _IOR(PP_IOCTL, 0x95, struct timeval) #define PPSETTIME _IOW(PP_IOCTL, 0x96, struct timeval) /* Get available modes (what the hardware can do) */ #define PPGETMODES _IOR(PP_IOCTL, 0x97, unsigned int) /* Get the current mode and phaze */ #define PPGETMODE _IOR(PP_IOCTL, 0x98, int) #define PPGETPHASE _IOR(PP_IOCTL, 0x99, int) /* get/set flags */ #define PPGETFLAGS _IOR(PP_IOCTL, 0x9a, int) #define PPSETFLAGS _IOW(PP_IOCTL, 0x9b, int) /* flags visible to the world */ #define PP_FASTWRITE (1<<2) #define PP_FASTREAD (1<<3) #define PP_W91284PIC (1<<4) /* only masks user-visible flags */ #define PP_FLAGMASK (PP_FASTWRITE | PP_FASTREAD | PP_W91284PIC) linux/reboot.h000064400000002477151027430560007363 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_REBOOT_H #define _LINUX_REBOOT_H /* * Magic values required to use _reboot() system call. */ #define LINUX_REBOOT_MAGIC1 0xfee1dead #define LINUX_REBOOT_MAGIC2 672274793 #define LINUX_REBOOT_MAGIC2A 85072278 #define LINUX_REBOOT_MAGIC2B 369367448 #define LINUX_REBOOT_MAGIC2C 537993216 /* * Commands accepted by the _reboot() system call. * * RESTART Restart system using default command and mode. * HALT Stop OS and give system control to ROM monitor, if any. * CAD_ON Ctrl-Alt-Del sequence causes RESTART command. * CAD_OFF Ctrl-Alt-Del sequence sends SIGINT to init task. * POWER_OFF Stop OS and remove all power from system, if possible. * RESTART2 Restart system using given command string. * SW_SUSPEND Suspend system using software suspend if compiled in. * KEXEC Restart system using a previously loaded Linux kernel */ #define LINUX_REBOOT_CMD_RESTART 0x01234567 #define LINUX_REBOOT_CMD_HALT 0xCDEF0123 #define LINUX_REBOOT_CMD_CAD_ON 0x89ABCDEF #define LINUX_REBOOT_CMD_CAD_OFF 0x00000000 #define LINUX_REBOOT_CMD_POWER_OFF 0x4321FEDC #define LINUX_REBOOT_CMD_RESTART2 0xA1B2C3D4 #define LINUX_REBOOT_CMD_SW_SUSPEND 0xD000FCE2 #define LINUX_REBOOT_CMD_KEXEC 0x45584543 #endif /* _LINUX_REBOOT_H */ linux/tc_ematch/tc_em_cmp.h000064400000000636151027430560011741 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_EM_CMP_H #define __LINUX_TC_EM_CMP_H #include #include struct tcf_em_cmp { __u32 val; __u32 mask; __u16 off; __u8 align:4; __u8 flags:4; __u8 layer:4; __u8 opnd:4; }; enum { TCF_EM_ALIGN_U8 = 1, TCF_EM_ALIGN_U16 = 2, TCF_EM_ALIGN_U32 = 4 }; #define TCF_EM_CMP_TRANS 1 #endif linux/tc_ematch/tc_em_nbyte.h000064400000000377151027430560012305 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_EM_NBYTE_H #define __LINUX_TC_EM_NBYTE_H #include #include struct tcf_em_nbyte { __u16 off; __u16 len:12; __u8 layer:4; }; #endif linux/tc_ematch/tc_em_text.h000064400000000600151027430560012135 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_EM_TEXT_H #define __LINUX_TC_EM_TEXT_H #include #include #define TC_EM_TEXT_ALGOSIZ 16 struct tcf_em_text { char algo[TC_EM_TEXT_ALGOSIZ]; __u16 from_offset; __u16 to_offset; __u16 pattern_len; __u8 from_layer:4; __u8 to_layer:4; __u8 pad; }; #endif linux/tc_ematch/tc_em_ipt.h000064400000000607151027430560011754 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_EM_IPT_H #define __LINUX_TC_EM_IPT_H #include #include enum { TCA_EM_IPT_UNSPEC, TCA_EM_IPT_HOOK, TCA_EM_IPT_MATCH_NAME, TCA_EM_IPT_MATCH_REVISION, TCA_EM_IPT_NFPROTO, TCA_EM_IPT_MATCH_DATA, __TCA_EM_IPT_MAX }; #define TCA_EM_IPT_MAX (__TCA_EM_IPT_MAX - 1) #endif linux/tc_ematch/tc_em_meta.h000064400000004104151027430560012102 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_EM_META_H #define __LINUX_TC_EM_META_H #include #include enum { TCA_EM_META_UNSPEC, TCA_EM_META_HDR, TCA_EM_META_LVALUE, TCA_EM_META_RVALUE, __TCA_EM_META_MAX }; #define TCA_EM_META_MAX (__TCA_EM_META_MAX - 1) struct tcf_meta_val { __u16 kind; __u8 shift; __u8 op; }; #define TCF_META_TYPE_MASK (0xf << 12) #define TCF_META_TYPE(kind) (((kind) & TCF_META_TYPE_MASK) >> 12) #define TCF_META_ID_MASK 0x7ff #define TCF_META_ID(kind) ((kind) & TCF_META_ID_MASK) enum { TCF_META_TYPE_VAR, TCF_META_TYPE_INT, __TCF_META_TYPE_MAX }; #define TCF_META_TYPE_MAX (__TCF_META_TYPE_MAX - 1) enum { TCF_META_ID_VALUE, TCF_META_ID_RANDOM, TCF_META_ID_LOADAVG_0, TCF_META_ID_LOADAVG_1, TCF_META_ID_LOADAVG_2, TCF_META_ID_DEV, TCF_META_ID_PRIORITY, TCF_META_ID_PROTOCOL, TCF_META_ID_PKTTYPE, TCF_META_ID_PKTLEN, TCF_META_ID_DATALEN, TCF_META_ID_MACLEN, TCF_META_ID_NFMARK, TCF_META_ID_TCINDEX, TCF_META_ID_RTCLASSID, TCF_META_ID_RTIIF, TCF_META_ID_SK_FAMILY, TCF_META_ID_SK_STATE, TCF_META_ID_SK_REUSE, TCF_META_ID_SK_BOUND_IF, TCF_META_ID_SK_REFCNT, TCF_META_ID_SK_SHUTDOWN, TCF_META_ID_SK_PROTO, TCF_META_ID_SK_TYPE, TCF_META_ID_SK_RCVBUF, TCF_META_ID_SK_RMEM_ALLOC, TCF_META_ID_SK_WMEM_ALLOC, TCF_META_ID_SK_OMEM_ALLOC, TCF_META_ID_SK_WMEM_QUEUED, TCF_META_ID_SK_RCV_QLEN, TCF_META_ID_SK_SND_QLEN, TCF_META_ID_SK_ERR_QLEN, TCF_META_ID_SK_FORWARD_ALLOCS, TCF_META_ID_SK_SNDBUF, TCF_META_ID_SK_ALLOCS, __TCF_META_ID_SK_ROUTE_CAPS, /* unimplemented but in ABI already */ TCF_META_ID_SK_HASH, TCF_META_ID_SK_LINGERTIME, TCF_META_ID_SK_ACK_BACKLOG, TCF_META_ID_SK_MAX_ACK_BACKLOG, TCF_META_ID_SK_PRIO, TCF_META_ID_SK_RCVLOWAT, TCF_META_ID_SK_RCVTIMEO, TCF_META_ID_SK_SNDTIMEO, TCF_META_ID_SK_SENDMSG_OFF, TCF_META_ID_SK_WRITE_PENDING, TCF_META_ID_VLAN_TAG, TCF_META_ID_RXHASH, __TCF_META_ID_MAX }; #define TCF_META_ID_MAX (__TCF_META_ID_MAX - 1) struct tcf_meta_hdr { struct tcf_meta_val left; struct tcf_meta_val right; }; #endif linux/if_plip.h000064400000001224151027430560007500 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * NET3 PLIP tuning facilities for the new Niibe PLIP. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #ifndef _LINUX_IF_PLIP_H #define _LINUX_IF_PLIP_H #include #define SIOCDEVPLIP SIOCDEVPRIVATE struct plipconf { unsigned short pcmd; unsigned long nibble; unsigned long trigger; }; #define PLIP_GET_TIMEOUT 0x1 #define PLIP_SET_TIMEOUT 0x2 #endif linux/phantom.h000064400000003166151027430560007533 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (C) 2005-2007 Jiri Slaby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef __PHANTOM_H #define __PHANTOM_H #include /* PHN_(G/S)ET_REG param */ struct phm_reg { __u32 reg; __u32 value; }; /* PHN_(G/S)ET_REGS param */ struct phm_regs { __u32 count; __u32 mask; __u32 values[8]; }; #define PH_IOC_MAGIC 'p' #define PHN_GET_REG _IOWR(PH_IOC_MAGIC, 0, struct phm_reg *) #define PHN_SET_REG _IOW(PH_IOC_MAGIC, 1, struct phm_reg *) #define PHN_GET_REGS _IOWR(PH_IOC_MAGIC, 2, struct phm_regs *) #define PHN_SET_REGS _IOW(PH_IOC_MAGIC, 3, struct phm_regs *) /* this ioctl tells the driver, that the caller is not OpenHaptics and might * use improved registers update (no more phantom switchoffs when using * libphantom) */ #define PHN_NOT_OH _IO(PH_IOC_MAGIC, 4) #define PHN_GETREG _IOWR(PH_IOC_MAGIC, 5, struct phm_reg) #define PHN_SETREG _IOW(PH_IOC_MAGIC, 6, struct phm_reg) #define PHN_GETREGS _IOWR(PH_IOC_MAGIC, 7, struct phm_regs) #define PHN_SETREGS _IOW(PH_IOC_MAGIC, 8, struct phm_regs) #define PHN_CONTROL 0x6 /* control byte in iaddr space */ #define PHN_CTL_AMP 0x1 /* switch after torques change */ #define PHN_CTL_BUT 0x2 /* is button switched */ #define PHN_CTL_IRQ 0x10 /* is irq enabled */ #define PHN_ZERO_FORCE 2048 /* zero torque on motor */ #endif linux/mroute6.h000064400000010741151027430560007463 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_MROUTE6_H #define __LINUX_MROUTE6_H #include #include #include #include /* For struct sockaddr_in6. */ /* * Based on the MROUTING 3.5 defines primarily to keep * source compatibility with BSD. * * See the pim6sd code for the original history. * * Protocol Independent Multicast (PIM) data structures included * Carlos Picoto (cap@di.fc.ul.pt) * */ #define MRT6_BASE 200 #define MRT6_INIT (MRT6_BASE) /* Activate the kernel mroute code */ #define MRT6_DONE (MRT6_BASE+1) /* Shutdown the kernel mroute */ #define MRT6_ADD_MIF (MRT6_BASE+2) /* Add a virtual interface */ #define MRT6_DEL_MIF (MRT6_BASE+3) /* Delete a virtual interface */ #define MRT6_ADD_MFC (MRT6_BASE+4) /* Add a multicast forwarding entry */ #define MRT6_DEL_MFC (MRT6_BASE+5) /* Delete a multicast forwarding entry */ #define MRT6_VERSION (MRT6_BASE+6) /* Get the kernel multicast version */ #define MRT6_ASSERT (MRT6_BASE+7) /* Activate PIM assert mode */ #define MRT6_PIM (MRT6_BASE+8) /* enable PIM code */ #define MRT6_TABLE (MRT6_BASE+9) /* Specify mroute table ID */ #define MRT6_ADD_MFC_PROXY (MRT6_BASE+10) /* Add a (*,*|G) mfc entry */ #define MRT6_DEL_MFC_PROXY (MRT6_BASE+11) /* Del a (*,*|G) mfc entry */ #define MRT6_MAX (MRT6_BASE+11) #define SIOCGETMIFCNT_IN6 SIOCPROTOPRIVATE /* IP protocol privates */ #define SIOCGETSGCNT_IN6 (SIOCPROTOPRIVATE+1) #define SIOCGETRPF (SIOCPROTOPRIVATE+2) #define MAXMIFS 32 typedef unsigned long mifbitmap_t; /* User mode code depends on this lot */ typedef unsigned short mifi_t; #define ALL_MIFS ((mifi_t)(-1)) #ifndef IF_SETSIZE #define IF_SETSIZE 256 #endif typedef __u32 if_mask; #define NIFBITS (sizeof(if_mask) * 8) /* bits per mask */ typedef struct if_set { if_mask ifs_bits[__KERNEL_DIV_ROUND_UP(IF_SETSIZE, NIFBITS)]; } if_set; #define IF_SET(n, p) ((p)->ifs_bits[(n)/NIFBITS] |= (1 << ((n) % NIFBITS))) #define IF_CLR(n, p) ((p)->ifs_bits[(n)/NIFBITS] &= ~(1 << ((n) % NIFBITS))) #define IF_ISSET(n, p) ((p)->ifs_bits[(n)/NIFBITS] & (1 << ((n) % NIFBITS))) #define IF_COPY(f, t) bcopy(f, t, sizeof(*(f))) #define IF_ZERO(p) bzero(p, sizeof(*(p))) /* * Passed by mrouted for an MRT_ADD_MIF - again we use the * mrouted 3.6 structures for compatibility */ struct mif6ctl { mifi_t mif6c_mifi; /* Index of MIF */ unsigned char mif6c_flags; /* MIFF_ flags */ unsigned char vifc_threshold; /* ttl limit */ __u16 mif6c_pifi; /* the index of the physical IF */ unsigned int vifc_rate_limit; /* Rate limiter values (NI) */ }; #define MIFF_REGISTER 0x1 /* register vif */ /* * Cache manipulation structures for mrouted and PIMd */ struct mf6cctl { struct sockaddr_in6 mf6cc_origin; /* Origin of mcast */ struct sockaddr_in6 mf6cc_mcastgrp; /* Group in question */ mifi_t mf6cc_parent; /* Where it arrived */ struct if_set mf6cc_ifset; /* Where it is going */ }; /* * Group count retrieval for pim6sd */ struct sioc_sg_req6 { struct sockaddr_in6 src; struct sockaddr_in6 grp; unsigned long pktcnt; unsigned long bytecnt; unsigned long wrong_if; }; /* * To get vif packet counts */ struct sioc_mif_req6 { mifi_t mifi; /* Which iface */ unsigned long icount; /* In packets */ unsigned long ocount; /* Out packets */ unsigned long ibytes; /* In bytes */ unsigned long obytes; /* Out bytes */ }; /* * That's all usermode folks */ /* * Structure used to communicate from kernel to multicast router. * We'll overlay the structure onto an MLD header (not an IPv6 heder like igmpmsg{} * used for IPv4 implementation). This is because this structure will be passed via an * IPv6 raw socket, on which an application will only receiver the payload i.e the data after * the IPv6 header and all the extension headers. (See section 3 of RFC 3542) */ struct mrt6msg { #define MRT6MSG_NOCACHE 1 #define MRT6MSG_WRONGMIF 2 #define MRT6MSG_WHOLEPKT 3 /* used for use level encap */ __u8 im6_mbz; /* must be zero */ __u8 im6_msgtype; /* what type of message */ __u16 im6_mif; /* mif rec'd on */ __u32 im6_pad; /* padding for 64 bit arch */ struct in6_addr im6_src, im6_dst; }; /* ip6mr netlink cache report attributes */ enum { IP6MRA_CREPORT_UNSPEC, IP6MRA_CREPORT_MSGTYPE, IP6MRA_CREPORT_MIF_ID, IP6MRA_CREPORT_SRC_ADDR, IP6MRA_CREPORT_DST_ADDR, IP6MRA_CREPORT_PKT, __IP6MRA_CREPORT_MAX }; #define IP6MRA_CREPORT_MAX (__IP6MRA_CREPORT_MAX - 1) #endif /* __LINUX_MROUTE6_H */ linux/binfmts.h000064400000001164151027430560007523 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_BINFMTS_H #define _LINUX_BINFMTS_H #include struct pt_regs; /* * These are the maximum length and maximum number of strings passed to the * execve() system call. MAX_ARG_STRLEN is essentially random but serves to * prevent the kernel from being unduly impacted by misaddressed pointers. * MAX_ARG_STRINGS is chosen to fit in a signed 32-bit integer. */ #define MAX_ARG_STRLEN (PAGE_SIZE * 32) #define MAX_ARG_STRINGS 0x7FFFFFFF /* sizeof(linux_binprm->buf) */ #define BINPRM_BUF_SIZE 256 #endif /* _LINUX_BINFMTS_H */ linux/x25.h000064400000006752151027430560006507 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * These are the public elements of the Linux kernel X.25 implementation. * * History * mar/20/00 Daniela Squassoni Disabling/enabling of facilities * negotiation. * apr/02/05 Shaun Pereira Selective sub address matching with * call user data */ #ifndef X25_KERNEL_H #define X25_KERNEL_H #include #include #define SIOCX25GSUBSCRIP (SIOCPROTOPRIVATE + 0) #define SIOCX25SSUBSCRIP (SIOCPROTOPRIVATE + 1) #define SIOCX25GFACILITIES (SIOCPROTOPRIVATE + 2) #define SIOCX25SFACILITIES (SIOCPROTOPRIVATE + 3) #define SIOCX25GCALLUSERDATA (SIOCPROTOPRIVATE + 4) #define SIOCX25SCALLUSERDATA (SIOCPROTOPRIVATE + 5) #define SIOCX25GCAUSEDIAG (SIOCPROTOPRIVATE + 6) #define SIOCX25SCUDMATCHLEN (SIOCPROTOPRIVATE + 7) #define SIOCX25CALLACCPTAPPRV (SIOCPROTOPRIVATE + 8) #define SIOCX25SENDCALLACCPT (SIOCPROTOPRIVATE + 9) #define SIOCX25GDTEFACILITIES (SIOCPROTOPRIVATE + 10) #define SIOCX25SDTEFACILITIES (SIOCPROTOPRIVATE + 11) #define SIOCX25SCAUSEDIAG (SIOCPROTOPRIVATE + 12) /* * Values for {get,set}sockopt. */ #define X25_QBITINCL 1 /* * X.25 Packet Size values. */ #define X25_PS16 4 #define X25_PS32 5 #define X25_PS64 6 #define X25_PS128 7 #define X25_PS256 8 #define X25_PS512 9 #define X25_PS1024 10 #define X25_PS2048 11 #define X25_PS4096 12 /* * An X.121 address, it is held as ASCII text, null terminated, up to 15 * digits and a null terminator. */ struct x25_address { char x25_addr[16]; }; /* * Linux X.25 Address structure, used for bind, and connect mostly. */ struct sockaddr_x25 { __kernel_sa_family_t sx25_family; /* Must be AF_X25 */ struct x25_address sx25_addr; /* X.121 Address */ }; /* * DTE/DCE subscription options. * * As this is missing lots of options, user should expect major * changes of this structure in 2.5.x which might break compatibilty. * The somewhat ugly dimension 200-sizeof() is needed to maintain * backward compatibility. */ struct x25_subscrip_struct { char device[200-sizeof(unsigned long)]; unsigned long global_facil_mask; /* 0 to disable negotiation */ unsigned int extended; }; /* values for above global_facil_mask */ #define X25_MASK_REVERSE 0x01 #define X25_MASK_THROUGHPUT 0x02 #define X25_MASK_PACKET_SIZE 0x04 #define X25_MASK_WINDOW_SIZE 0x08 #define X25_MASK_CALLING_AE 0x10 #define X25_MASK_CALLED_AE 0x20 /* * Routing table control structure. */ struct x25_route_struct { struct x25_address address; unsigned int sigdigits; char device[200]; }; /* * Facilities structure. */ struct x25_facilities { unsigned int winsize_in, winsize_out; unsigned int pacsize_in, pacsize_out; unsigned int throughput; unsigned int reverse; }; /* * ITU DTE facilities * Only the called and calling address * extension are currently implemented. * The rest are in place to avoid the struct * changing size if someone needs them later */ struct x25_dte_facilities { __u16 delay_cumul; __u16 delay_target; __u16 delay_max; __u8 min_throughput; __u8 expedited; __u8 calling_len; __u8 called_len; __u8 calling_ae[20]; __u8 called_ae[20]; }; /* * Call User Data structure. */ struct x25_calluserdata { unsigned int cudlength; unsigned char cuddata[128]; }; /* * Call clearing Cause and Diagnostic structure. */ struct x25_causediag { unsigned char cause; unsigned char diagnostic; }; /* * Further optional call user data match length selection */ struct x25_subaddr { unsigned int cudmatchlength; }; #endif linux/signal.h000064400000000604151027430560007334 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SIGNAL_H #define _LINUX_SIGNAL_H #include #include #define SS_ONSTACK 1 #define SS_DISABLE 2 /* bit-flags */ #define SS_AUTODISARM (1U << 31) /* disable sas during sighandling */ /* mask for all SS_xxx flags */ #define SS_FLAG_BITS SS_AUTODISARM #endif /* _LINUX_SIGNAL_H */ linux/thermal.h000064400000006355151027430560007524 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_THERMAL_H #define _LINUX_THERMAL_H #define THERMAL_NAME_LENGTH 20 enum thermal_device_mode { THERMAL_DEVICE_DISABLED = 0, THERMAL_DEVICE_ENABLED, }; enum thermal_trip_type { THERMAL_TRIP_ACTIVE = 0, THERMAL_TRIP_PASSIVE, THERMAL_TRIP_HOT, THERMAL_TRIP_CRITICAL, }; /* Adding event notification support elements */ #define THERMAL_GENL_FAMILY_NAME "thermal" #define THERMAL_GENL_VERSION 0x01 #define THERMAL_GENL_SAMPLING_GROUP_NAME "sampling" #define THERMAL_GENL_EVENT_GROUP_NAME "event" /* Attributes of thermal_genl_family */ enum thermal_genl_attr { THERMAL_GENL_ATTR_UNSPEC, THERMAL_GENL_ATTR_TZ, THERMAL_GENL_ATTR_TZ_ID, THERMAL_GENL_ATTR_TZ_TEMP, THERMAL_GENL_ATTR_TZ_TRIP, THERMAL_GENL_ATTR_TZ_TRIP_ID, THERMAL_GENL_ATTR_TZ_TRIP_TYPE, THERMAL_GENL_ATTR_TZ_TRIP_TEMP, THERMAL_GENL_ATTR_TZ_TRIP_HYST, THERMAL_GENL_ATTR_TZ_MODE, THERMAL_GENL_ATTR_TZ_NAME, THERMAL_GENL_ATTR_TZ_CDEV_WEIGHT, THERMAL_GENL_ATTR_TZ_GOV, THERMAL_GENL_ATTR_TZ_GOV_NAME, THERMAL_GENL_ATTR_CDEV, THERMAL_GENL_ATTR_CDEV_ID, THERMAL_GENL_ATTR_CDEV_CUR_STATE, THERMAL_GENL_ATTR_CDEV_MAX_STATE, THERMAL_GENL_ATTR_CDEV_NAME, THERMAL_GENL_ATTR_GOV_NAME, THERMAL_GENL_ATTR_CPU_CAPABILITY, THERMAL_GENL_ATTR_CPU_CAPABILITY_ID, THERMAL_GENL_ATTR_CPU_CAPABILITY_PERFORMANCE, THERMAL_GENL_ATTR_CPU_CAPABILITY_EFFICIENCY, __THERMAL_GENL_ATTR_MAX, }; #define THERMAL_GENL_ATTR_MAX (__THERMAL_GENL_ATTR_MAX - 1) enum thermal_genl_sampling { THERMAL_GENL_SAMPLING_TEMP, __THERMAL_GENL_SAMPLING_MAX, }; #define THERMAL_GENL_SAMPLING_MAX (__THERMAL_GENL_SAMPLING_MAX - 1) /* Events of thermal_genl_family */ enum thermal_genl_event { THERMAL_GENL_EVENT_UNSPEC, THERMAL_GENL_EVENT_TZ_CREATE, /* Thermal zone creation */ THERMAL_GENL_EVENT_TZ_DELETE, /* Thermal zone deletion */ THERMAL_GENL_EVENT_TZ_DISABLE, /* Thermal zone disabed */ THERMAL_GENL_EVENT_TZ_ENABLE, /* Thermal zone enabled */ THERMAL_GENL_EVENT_TZ_TRIP_UP, /* Trip point crossed the way up */ THERMAL_GENL_EVENT_TZ_TRIP_DOWN, /* Trip point crossed the way down */ THERMAL_GENL_EVENT_TZ_TRIP_CHANGE, /* Trip point changed */ THERMAL_GENL_EVENT_TZ_TRIP_ADD, /* Trip point added */ THERMAL_GENL_EVENT_TZ_TRIP_DELETE, /* Trip point deleted */ THERMAL_GENL_EVENT_CDEV_ADD, /* Cdev bound to the thermal zone */ THERMAL_GENL_EVENT_CDEV_DELETE, /* Cdev unbound */ THERMAL_GENL_EVENT_CDEV_STATE_UPDATE, /* Cdev state updated */ THERMAL_GENL_EVENT_TZ_GOV_CHANGE, /* Governor policy changed */ THERMAL_GENL_EVENT_CPU_CAPABILITY_CHANGE, /* CPU capability changed */ __THERMAL_GENL_EVENT_MAX, }; #define THERMAL_GENL_EVENT_MAX (__THERMAL_GENL_EVENT_MAX - 1) /* Commands supported by the thermal_genl_family */ enum thermal_genl_cmd { THERMAL_GENL_CMD_UNSPEC, THERMAL_GENL_CMD_TZ_GET_ID, /* List of thermal zones id */ THERMAL_GENL_CMD_TZ_GET_TRIP, /* List of thermal trips */ THERMAL_GENL_CMD_TZ_GET_TEMP, /* Get the thermal zone temperature */ THERMAL_GENL_CMD_TZ_GET_GOV, /* Get the thermal zone governor */ THERMAL_GENL_CMD_TZ_GET_MODE, /* Get the thermal zone mode */ THERMAL_GENL_CMD_CDEV_GET, /* List of cdev id */ __THERMAL_GENL_CMD_MAX, }; #define THERMAL_GENL_CMD_MAX (__THERMAL_GENL_CMD_MAX - 1) #endif /* _LINUX_THERMAL_H */ linux/sed-opal.h000064400000006313151027430560007566 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright © 2016 Intel Corporation * * Authors: * Rafael Antognolli * Scott Bauer * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #ifndef _SED_OPAL_H #define _SED_OPAL_H #include #define OPAL_KEY_MAX 256 #define OPAL_MAX_LRS 9 enum opal_mbr { OPAL_MBR_ENABLE = 0x0, OPAL_MBR_DISABLE = 0x01, }; enum opal_user { OPAL_ADMIN1 = 0x0, OPAL_USER1 = 0x01, OPAL_USER2 = 0x02, OPAL_USER3 = 0x03, OPAL_USER4 = 0x04, OPAL_USER5 = 0x05, OPAL_USER6 = 0x06, OPAL_USER7 = 0x07, OPAL_USER8 = 0x08, OPAL_USER9 = 0x09, }; enum opal_lock_state { OPAL_RO = 0x01, /* 0001 */ OPAL_RW = 0x02, /* 0010 */ OPAL_LK = 0x04, /* 0100 */ }; struct opal_key { __u8 lr; __u8 key_len; __u8 __align[6]; __u8 key[OPAL_KEY_MAX]; }; struct opal_lr_act { struct opal_key key; __u32 sum; __u8 num_lrs; __u8 lr[OPAL_MAX_LRS]; __u8 align[2]; /* Align to 8 byte boundary */ }; struct opal_session_info { __u32 sum; __u32 who; struct opal_key opal_key; }; struct opal_user_lr_setup { __u64 range_start; __u64 range_length; __u32 RLE; /* Read Lock enabled */ __u32 WLE; /* Write Lock Enabled */ struct opal_session_info session; }; struct opal_lock_unlock { struct opal_session_info session; __u32 l_state; __u8 __align[4]; }; struct opal_new_pw { struct opal_session_info session; /* When we're not operating in sum, and we first set * passwords we need to set them via ADMIN authority. * After passwords are changed, we can set them via, * User authorities. * Because of this restriction we need to know about * Two different users. One in 'session' which we will use * to start the session and new_userr_pw as the user we're * chaning the pw for. */ struct opal_session_info new_user_pw; }; struct opal_mbr_data { struct opal_key key; __u8 enable_disable; __u8 __align[7]; }; #define IOC_OPAL_SAVE _IOW('p', 220, struct opal_lock_unlock) #define IOC_OPAL_LOCK_UNLOCK _IOW('p', 221, struct opal_lock_unlock) #define IOC_OPAL_TAKE_OWNERSHIP _IOW('p', 222, struct opal_key) #define IOC_OPAL_ACTIVATE_LSP _IOW('p', 223, struct opal_lr_act) #define IOC_OPAL_SET_PW _IOW('p', 224, struct opal_new_pw) #define IOC_OPAL_ACTIVATE_USR _IOW('p', 225, struct opal_session_info) #define IOC_OPAL_REVERT_TPR _IOW('p', 226, struct opal_key) #define IOC_OPAL_LR_SETUP _IOW('p', 227, struct opal_user_lr_setup) #define IOC_OPAL_ADD_USR_TO_LR _IOW('p', 228, struct opal_lock_unlock) #define IOC_OPAL_ENABLE_DISABLE_MBR _IOW('p', 229, struct opal_mbr_data) #define IOC_OPAL_ERASE_LR _IOW('p', 230, struct opal_session_info) #define IOC_OPAL_SECURE_ERASE_LR _IOW('p', 231, struct opal_session_info) #endif /* _SED_OPAL_H */ linux/v4l2-subdev.h000064400000013720151027430560010137 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * V4L2 subdev userspace API * * Copyright (C) 2010 Nokia Corporation * * Contacts: Laurent Pinchart * Sakari Ailus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LINUX_V4L2_SUBDEV_H #define __LINUX_V4L2_SUBDEV_H #include #include #include #include /** * enum v4l2_subdev_format_whence - Media bus format type * @V4L2_SUBDEV_FORMAT_TRY: try format, for negotiation only * @V4L2_SUBDEV_FORMAT_ACTIVE: active format, applied to the device */ enum v4l2_subdev_format_whence { V4L2_SUBDEV_FORMAT_TRY = 0, V4L2_SUBDEV_FORMAT_ACTIVE = 1, }; /** * struct v4l2_subdev_format - Pad-level media bus format * @which: format type (from enum v4l2_subdev_format_whence) * @pad: pad number, as reported by the media API * @format: media bus format (format code and frame size) */ struct v4l2_subdev_format { __u32 which; __u32 pad; struct v4l2_mbus_framefmt format; __u32 reserved[8]; }; /** * struct v4l2_subdev_crop - Pad-level crop settings * @which: format type (from enum v4l2_subdev_format_whence) * @pad: pad number, as reported by the media API * @rect: pad crop rectangle boundaries */ struct v4l2_subdev_crop { __u32 which; __u32 pad; struct v4l2_rect rect; __u32 reserved[8]; }; /** * struct v4l2_subdev_mbus_code_enum - Media bus format enumeration * @pad: pad number, as reported by the media API * @index: format index during enumeration * @code: format code (MEDIA_BUS_FMT_ definitions) * @which: format type (from enum v4l2_subdev_format_whence) */ struct v4l2_subdev_mbus_code_enum { __u32 pad; __u32 index; __u32 code; __u32 which; __u32 reserved[8]; }; /** * struct v4l2_subdev_frame_size_enum - Media bus format enumeration * @pad: pad number, as reported by the media API * @index: format index during enumeration * @code: format code (MEDIA_BUS_FMT_ definitions) * @which: format type (from enum v4l2_subdev_format_whence) */ struct v4l2_subdev_frame_size_enum { __u32 index; __u32 pad; __u32 code; __u32 min_width; __u32 max_width; __u32 min_height; __u32 max_height; __u32 which; __u32 reserved[8]; }; /** * struct v4l2_subdev_frame_interval - Pad-level frame rate * @pad: pad number, as reported by the media API * @interval: frame interval in seconds */ struct v4l2_subdev_frame_interval { __u32 pad; struct v4l2_fract interval; __u32 reserved[9]; }; /** * struct v4l2_subdev_frame_interval_enum - Frame interval enumeration * @pad: pad number, as reported by the media API * @index: frame interval index during enumeration * @code: format code (MEDIA_BUS_FMT_ definitions) * @width: frame width in pixels * @height: frame height in pixels * @interval: frame interval in seconds * @which: format type (from enum v4l2_subdev_format_whence) */ struct v4l2_subdev_frame_interval_enum { __u32 index; __u32 pad; __u32 code; __u32 width; __u32 height; struct v4l2_fract interval; __u32 which; __u32 reserved[8]; }; /** * struct v4l2_subdev_selection - selection info * * @which: either V4L2_SUBDEV_FORMAT_ACTIVE or V4L2_SUBDEV_FORMAT_TRY * @pad: pad number, as reported by the media API * @target: Selection target, used to choose one of possible rectangles, * defined in v4l2-common.h; V4L2_SEL_TGT_* . * @flags: constraint flags, defined in v4l2-common.h; V4L2_SEL_FLAG_*. * @r: coordinates of the selection window * @reserved: for future use, set to zero for now * * Hardware may use multiple helper windows to process a video stream. * The structure is used to exchange this selection areas between * an application and a driver. */ struct v4l2_subdev_selection { __u32 which; __u32 pad; __u32 target; __u32 flags; struct v4l2_rect r; __u32 reserved[8]; }; /* Backwards compatibility define --- to be removed */ #define v4l2_subdev_edid v4l2_edid #define VIDIOC_SUBDEV_G_FMT _IOWR('V', 4, struct v4l2_subdev_format) #define VIDIOC_SUBDEV_S_FMT _IOWR('V', 5, struct v4l2_subdev_format) #define VIDIOC_SUBDEV_G_FRAME_INTERVAL _IOWR('V', 21, struct v4l2_subdev_frame_interval) #define VIDIOC_SUBDEV_S_FRAME_INTERVAL _IOWR('V', 22, struct v4l2_subdev_frame_interval) #define VIDIOC_SUBDEV_ENUM_MBUS_CODE _IOWR('V', 2, struct v4l2_subdev_mbus_code_enum) #define VIDIOC_SUBDEV_ENUM_FRAME_SIZE _IOWR('V', 74, struct v4l2_subdev_frame_size_enum) #define VIDIOC_SUBDEV_ENUM_FRAME_INTERVAL _IOWR('V', 75, struct v4l2_subdev_frame_interval_enum) #define VIDIOC_SUBDEV_G_CROP _IOWR('V', 59, struct v4l2_subdev_crop) #define VIDIOC_SUBDEV_S_CROP _IOWR('V', 60, struct v4l2_subdev_crop) #define VIDIOC_SUBDEV_G_SELECTION _IOWR('V', 61, struct v4l2_subdev_selection) #define VIDIOC_SUBDEV_S_SELECTION _IOWR('V', 62, struct v4l2_subdev_selection) /* The following ioctls are identical to the ioctls in videodev2.h */ #define VIDIOC_SUBDEV_G_EDID _IOWR('V', 40, struct v4l2_edid) #define VIDIOC_SUBDEV_S_EDID _IOWR('V', 41, struct v4l2_edid) #define VIDIOC_SUBDEV_S_DV_TIMINGS _IOWR('V', 87, struct v4l2_dv_timings) #define VIDIOC_SUBDEV_G_DV_TIMINGS _IOWR('V', 88, struct v4l2_dv_timings) #define VIDIOC_SUBDEV_ENUM_DV_TIMINGS _IOWR('V', 98, struct v4l2_enum_dv_timings) #define VIDIOC_SUBDEV_QUERY_DV_TIMINGS _IOR('V', 99, struct v4l2_dv_timings) #define VIDIOC_SUBDEV_DV_TIMINGS_CAP _IOWR('V', 100, struct v4l2_dv_timings_cap) #endif linux/seg6_iptunnel.h000064400000001637151027430560010650 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * SR-IPv6 implementation * * Author: * David Lebrun * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_SEG6_IPTUNNEL_H #define _LINUX_SEG6_IPTUNNEL_H #include /* For struct ipv6_sr_hdr. */ enum { SEG6_IPTUNNEL_UNSPEC, SEG6_IPTUNNEL_SRH, __SEG6_IPTUNNEL_MAX, }; #define SEG6_IPTUNNEL_MAX (__SEG6_IPTUNNEL_MAX - 1) struct seg6_iptunnel_encap { int mode; struct ipv6_sr_hdr srh[0]; }; #define SEG6_IPTUN_ENCAP_SIZE(x) ((sizeof(*x)) + (((x)->srh->hdrlen + 1) << 3)) enum { SEG6_IPTUN_MODE_INLINE, SEG6_IPTUN_MODE_ENCAP, SEG6_IPTUN_MODE_L2ENCAP, }; #endif linux/module.h000064400000000377151027430560007353 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MODULE_H #define _LINUX_MODULE_H /* Flags for sys_finit_module: */ #define MODULE_INIT_IGNORE_MODVERSIONS 1 #define MODULE_INIT_IGNORE_VERMAGIC 2 #endif /* _LINUX_MODULE_H */ linux/ppp-comp.h000064400000004737151027430560007625 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ppp-comp.h - Definitions for doing PPP packet compression. * * Copyright 1994-1998 Paul Mackerras. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #ifndef _NET_PPP_COMP_H #define _NET_PPP_COMP_H /* * CCP codes. */ #define CCP_CONFREQ 1 #define CCP_CONFACK 2 #define CCP_TERMREQ 5 #define CCP_TERMACK 6 #define CCP_RESETREQ 14 #define CCP_RESETACK 15 /* * Max # bytes for a CCP option */ #define CCP_MAX_OPTION_LENGTH 32 /* * Parts of a CCP packet. */ #define CCP_CODE(dp) ((dp)[0]) #define CCP_ID(dp) ((dp)[1]) #define CCP_LENGTH(dp) (((dp)[2] << 8) + (dp)[3]) #define CCP_HDRLEN 4 #define CCP_OPT_CODE(dp) ((dp)[0]) #define CCP_OPT_LENGTH(dp) ((dp)[1]) #define CCP_OPT_MINLEN 2 /* * Definitions for BSD-Compress. */ #define CI_BSD_COMPRESS 21 /* config. option for BSD-Compress */ #define CILEN_BSD_COMPRESS 3 /* length of config. option */ /* Macros for handling the 3rd byte of the BSD-Compress config option. */ #define BSD_NBITS(x) ((x) & 0x1F) /* number of bits requested */ #define BSD_VERSION(x) ((x) >> 5) /* version of option format */ #define BSD_CURRENT_VERSION 1 /* current version number */ #define BSD_MAKE_OPT(v, n) (((v) << 5) | (n)) #define BSD_MIN_BITS 9 /* smallest code size supported */ #define BSD_MAX_BITS 15 /* largest code size supported */ /* * Definitions for Deflate. */ #define CI_DEFLATE 26 /* config option for Deflate */ #define CI_DEFLATE_DRAFT 24 /* value used in original draft RFC */ #define CILEN_DEFLATE 4 /* length of its config option */ #define DEFLATE_MIN_SIZE 9 #define DEFLATE_MAX_SIZE 15 #define DEFLATE_METHOD_VAL 8 #define DEFLATE_SIZE(x) (((x) >> 4) + 8) #define DEFLATE_METHOD(x) ((x) & 0x0F) #define DEFLATE_MAKE_OPT(w) ((((w) - 8) << 4) + DEFLATE_METHOD_VAL) #define DEFLATE_CHK_SEQUENCE 0 /* * Definitions for MPPE. */ #define CI_MPPE 18 /* config option for MPPE */ #define CILEN_MPPE 6 /* length of config option */ /* * Definitions for other, as yet unsupported, compression methods. */ #define CI_PREDICTOR_1 1 /* config option for Predictor-1 */ #define CILEN_PREDICTOR_1 2 /* length of its config option */ #define CI_PREDICTOR_2 2 /* config option for Predictor-2 */ #define CILEN_PREDICTOR_2 2 /* length of its config option */ #endif /* _NET_PPP_COMP_H */ linux/hyperv.h000064400000025620151027430560007401 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * * Copyright (c) 2011, Microsoft Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307 USA. * * Authors: * Haiyang Zhang * Hank Janssen * K. Y. Srinivasan * */ #ifndef _HYPERV_H #define _HYPERV_H #include /* * Framework version for util services. */ #define UTIL_FW_MINOR 0 #define UTIL_WS2K8_FW_MAJOR 1 #define UTIL_WS2K8_FW_VERSION (UTIL_WS2K8_FW_MAJOR << 16 | UTIL_FW_MINOR) #define UTIL_FW_MAJOR 3 #define UTIL_FW_VERSION (UTIL_FW_MAJOR << 16 | UTIL_FW_MINOR) /* * Implementation of host controlled snapshot of the guest. */ #define VSS_OP_REGISTER 128 /* Daemon code with full handshake support. */ #define VSS_OP_REGISTER1 129 enum hv_vss_op { VSS_OP_CREATE = 0, VSS_OP_DELETE, VSS_OP_HOT_BACKUP, VSS_OP_GET_DM_INFO, VSS_OP_BU_COMPLETE, /* * Following operations are only supported with IC version >= 5.0 */ VSS_OP_FREEZE, /* Freeze the file systems in the VM */ VSS_OP_THAW, /* Unfreeze the file systems */ VSS_OP_AUTO_RECOVER, VSS_OP_COUNT /* Number of operations, must be last */ }; /* * Header for all VSS messages. */ struct hv_vss_hdr { __u8 operation; __u8 reserved[7]; } __attribute__((packed)); /* * Flag values for the hv_vss_check_feature. Linux supports only * one value. */ #define VSS_HBU_NO_AUTO_RECOVERY 0x00000005 struct hv_vss_check_feature { __u32 flags; } __attribute__((packed)); struct hv_vss_check_dm_info { __u32 flags; } __attribute__((packed)); /* * struct hv_vss_msg encodes the fields that the Linux VSS * driver accesses. However, FREEZE messages from Hyper-V contain * additional LUN information that Linux doesn't use and are not * represented in struct hv_vss_msg. A received FREEZE message may * be as large as 6,260 bytes, so the driver must allocate at least * that much space, not sizeof(struct hv_vss_msg). Other messages * such as AUTO_RECOVER may be as large as 12,500 bytes. However, * because the Linux VSS driver responds that it doesn't support * auto-recovery, it should not receive such messages. */ struct hv_vss_msg { union { struct hv_vss_hdr vss_hdr; int error; }; union { struct hv_vss_check_feature vss_cf; struct hv_vss_check_dm_info dm_info; }; } __attribute__((packed)); /* * Implementation of a host to guest copy facility. */ #define FCOPY_VERSION_0 0 #define FCOPY_VERSION_1 1 #define FCOPY_CURRENT_VERSION FCOPY_VERSION_1 #define W_MAX_PATH 260 enum hv_fcopy_op { START_FILE_COPY = 0, WRITE_TO_FILE, COMPLETE_FCOPY, CANCEL_FCOPY, }; struct hv_fcopy_hdr { __u32 operation; __u8 service_id0[16]; /* currently unused */ __u8 service_id1[16]; /* currently unused */ } __attribute__((packed)); #define OVER_WRITE 0x1 #define CREATE_PATH 0x2 struct hv_start_fcopy { struct hv_fcopy_hdr hdr; __u16 file_name[W_MAX_PATH]; __u16 path_name[W_MAX_PATH]; __u32 copy_flags; __u64 file_size; } __attribute__((packed)); /* * The file is chunked into fragments. */ #define DATA_FRAGMENT (6 * 1024) struct hv_do_fcopy { struct hv_fcopy_hdr hdr; __u32 pad; __u64 offset; __u32 size; __u8 data[DATA_FRAGMENT]; } __attribute__((packed)); /* * An implementation of HyperV key value pair (KVP) functionality for Linux. * * * Copyright (C) 2010, Novell, Inc. * Author : K. Y. Srinivasan * */ /* * Maximum value size - used for both key names and value data, and includes * any applicable NULL terminators. * * Note: This limit is somewhat arbitrary, but falls easily within what is * supported for all native guests (back to Win 2000) and what is reasonable * for the IC KVP exchange functionality. Note that Windows Me/98/95 are * limited to 255 character key names. * * MSDN recommends not storing data values larger than 2048 bytes in the * registry. * * Note: This value is used in defining the KVP exchange message - this value * cannot be modified without affecting the message size and compatibility. */ /* * bytes, including any null terminators */ #define HV_KVP_EXCHANGE_MAX_VALUE_SIZE (2048) /* * Maximum key size - the registry limit for the length of an entry name * is 256 characters, including the null terminator */ #define HV_KVP_EXCHANGE_MAX_KEY_SIZE (512) /* * In Linux, we implement the KVP functionality in two components: * 1) The kernel component which is packaged as part of the hv_utils driver * is responsible for communicating with the host and responsible for * implementing the host/guest protocol. 2) A user level daemon that is * responsible for data gathering. * * Host/Guest Protocol: The host iterates over an index and expects the guest * to assign a key name to the index and also return the value corresponding to * the key. The host will have atmost one KVP transaction outstanding at any * given point in time. The host side iteration stops when the guest returns * an error. Microsoft has specified the following mapping of key names to * host specified index: * * Index Key Name * 0 FullyQualifiedDomainName * 1 IntegrationServicesVersion * 2 NetworkAddressIPv4 * 3 NetworkAddressIPv6 * 4 OSBuildNumber * 5 OSName * 6 OSMajorVersion * 7 OSMinorVersion * 8 OSVersion * 9 ProcessorArchitecture * * The Windows host expects the Key Name and Key Value to be encoded in utf16. * * Guest Kernel/KVP Daemon Protocol: As noted earlier, we implement all of the * data gathering functionality in a user mode daemon. The user level daemon * is also responsible for binding the key name to the index as well. The * kernel and user-level daemon communicate using a connector channel. * * The user mode component first registers with the * kernel component. Subsequently, the kernel component requests, data * for the specified keys. In response to this message the user mode component * fills in the value corresponding to the specified key. We overload the * sequence field in the cn_msg header to define our KVP message types. * * * The kernel component simply acts as a conduit for communication between the * Windows host and the user-level daemon. The kernel component passes up the * index received from the Host to the user-level daemon. If the index is * valid (supported), the corresponding key as well as its * value (both are strings) is returned. If the index is invalid * (not supported), a NULL key string is returned. */ /* * Registry value types. */ #define REG_SZ 1 #define REG_U32 4 #define REG_U64 8 /* * As we look at expanding the KVP functionality to include * IP injection functionality, we need to maintain binary * compatibility with older daemons. * * The KVP opcodes are defined by the host and it was unfortunate * that I chose to treat the registration operation as part of the * KVP operations defined by the host. * Here is the level of compatibility * (between the user level daemon and the kernel KVP driver) that we * will implement: * * An older daemon will always be supported on a newer driver. * A given user level daemon will require a minimal version of the * kernel driver. * If we cannot handle the version differences, we will fail gracefully * (this can happen when we have a user level daemon that is more * advanced than the KVP driver. * * We will use values used in this handshake for determining if we have * workable user level daemon and the kernel driver. We begin by taking the * registration opcode out of the KVP opcode namespace. We will however, * maintain compatibility with the existing user-level daemon code. */ /* * Daemon code not supporting IP injection (legacy daemon). */ #define KVP_OP_REGISTER 4 /* * Daemon code supporting IP injection. * The KVP opcode field is used to communicate the * registration information; so define a namespace that * will be distinct from the host defined KVP opcode. */ #define KVP_OP_REGISTER1 100 enum hv_kvp_exchg_op { KVP_OP_GET = 0, KVP_OP_SET, KVP_OP_DELETE, KVP_OP_ENUMERATE, KVP_OP_GET_IP_INFO, KVP_OP_SET_IP_INFO, KVP_OP_COUNT /* Number of operations, must be last. */ }; enum hv_kvp_exchg_pool { KVP_POOL_EXTERNAL = 0, KVP_POOL_GUEST, KVP_POOL_AUTO, KVP_POOL_AUTO_EXTERNAL, KVP_POOL_AUTO_INTERNAL, KVP_POOL_COUNT /* Number of pools, must be last. */ }; /* * Some Hyper-V status codes. */ #define HV_S_OK 0x00000000 #define HV_E_FAIL 0x80004005 #define HV_S_CONT 0x80070103 #define HV_ERROR_NOT_SUPPORTED 0x80070032 #define HV_ERROR_MACHINE_LOCKED 0x800704F7 #define HV_ERROR_DEVICE_NOT_CONNECTED 0x8007048F #define HV_INVALIDARG 0x80070057 #define HV_GUID_NOTFOUND 0x80041002 #define HV_ERROR_ALREADY_EXISTS 0x80070050 #define HV_ERROR_DISK_FULL 0x80070070 #define ADDR_FAMILY_NONE 0x00 #define ADDR_FAMILY_IPV4 0x01 #define ADDR_FAMILY_IPV6 0x02 #define MAX_ADAPTER_ID_SIZE 128 #define MAX_IP_ADDR_SIZE 1024 #define MAX_GATEWAY_SIZE 512 struct hv_kvp_ipaddr_value { __u16 adapter_id[MAX_ADAPTER_ID_SIZE]; __u8 addr_family; __u8 dhcp_enabled; __u16 ip_addr[MAX_IP_ADDR_SIZE]; __u16 sub_net[MAX_IP_ADDR_SIZE]; __u16 gate_way[MAX_GATEWAY_SIZE]; __u16 dns_addr[MAX_IP_ADDR_SIZE]; } __attribute__((packed)); struct hv_kvp_hdr { __u8 operation; __u8 pool; __u16 pad; } __attribute__((packed)); struct hv_kvp_exchg_msg_value { __u32 value_type; __u32 key_size; __u32 value_size; __u8 key[HV_KVP_EXCHANGE_MAX_KEY_SIZE]; union { __u8 value[HV_KVP_EXCHANGE_MAX_VALUE_SIZE]; __u32 value_u32; __u64 value_u64; }; } __attribute__((packed)); struct hv_kvp_msg_enumerate { __u32 index; struct hv_kvp_exchg_msg_value data; } __attribute__((packed)); struct hv_kvp_msg_get { struct hv_kvp_exchg_msg_value data; }; struct hv_kvp_msg_set { struct hv_kvp_exchg_msg_value data; }; struct hv_kvp_msg_delete { __u32 key_size; __u8 key[HV_KVP_EXCHANGE_MAX_KEY_SIZE]; }; struct hv_kvp_register { __u8 version[HV_KVP_EXCHANGE_MAX_KEY_SIZE]; }; struct hv_kvp_msg { union { struct hv_kvp_hdr kvp_hdr; int error; }; union { struct hv_kvp_msg_get kvp_get; struct hv_kvp_msg_set kvp_set; struct hv_kvp_msg_delete kvp_delete; struct hv_kvp_msg_enumerate kvp_enum_data; struct hv_kvp_ipaddr_value kvp_ip_val; struct hv_kvp_register kvp_register; } body; } __attribute__((packed)); struct hv_kvp_ip_msg { __u8 operation; __u8 pool; struct hv_kvp_ipaddr_value kvp_ip_val; } __attribute__((packed)); #endif /* _HYPERV_H */ linux/vfio_zdev.h000064400000004756151027430560010066 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * VFIO Region definitions for ZPCI devices * * Copyright IBM Corp. 2020 * * Author(s): Pierre Morel * Matthew Rosato */ #ifndef _VFIO_ZDEV_H_ #define _VFIO_ZDEV_H_ #include #include /** * VFIO_DEVICE_INFO_CAP_ZPCI_BASE - Base PCI Function information * * This capability provides a set of descriptive information about the * associated PCI function. */ struct vfio_device_info_cap_zpci_base { struct vfio_info_cap_header header; __u64 start_dma; /* Start of available DMA addresses */ __u64 end_dma; /* End of available DMA addresses */ __u16 pchid; /* Physical Channel ID */ __u16 vfn; /* Virtual function number */ __u16 fmb_length; /* Measurement Block Length (in bytes) */ __u8 pft; /* PCI Function Type */ __u8 gid; /* PCI function group ID */ /* End of version 1 */ __u32 fh; /* PCI function handle */ /* End of version 2 */ }; /** * VFIO_DEVICE_INFO_CAP_ZPCI_GROUP - Base PCI Function Group information * * This capability provides a set of descriptive information about the group of * PCI functions that the associated device belongs to. */ struct vfio_device_info_cap_zpci_group { struct vfio_info_cap_header header; __u64 dasm; /* DMA Address space mask */ __u64 msi_addr; /* MSI address */ __u64 flags; #define VFIO_DEVICE_INFO_ZPCI_FLAG_REFRESH 1 /* Program-specified TLB refresh */ __u16 mui; /* Measurement Block Update Interval */ __u16 noi; /* Maximum number of MSIs */ __u16 maxstbl; /* Maximum Store Block Length */ __u8 version; /* Supported PCI Version */ /* End of version 1 */ __u8 reserved; __u16 imaxstbl; /* Maximum Interpreted Store Block Length */ /* End of version 2 */ }; /** * VFIO_DEVICE_INFO_CAP_ZPCI_UTIL - Utility String * * This capability provides the utility string for the associated device, which * is a device identifier string made up of EBCDID characters. 'size' specifies * the length of 'util_str'. */ struct vfio_device_info_cap_zpci_util { struct vfio_info_cap_header header; __u32 size; __u8 util_str[]; }; /** * VFIO_DEVICE_INFO_CAP_ZPCI_PFIP - PCI Function Path * * This capability provides the PCI function path string, which is an identifier * that describes the internal hardware path of the device. 'size' specifies * the length of 'pfip'. */ struct vfio_device_info_cap_zpci_pfip { struct vfio_info_cap_header header; __u32 size; __u8 pfip[]; }; #endif linux/vbox_vmmdev_types.h000064400000020244151027430560011641 0ustar00/* SPDX-License-Identifier: (GPL-2.0 OR CDDL-1.0) */ /* * Virtual Device for Guest <-> VMM/Host communication, type definitions * which are also used for the vboxguest ioctl interface / by vboxsf * * Copyright (C) 2006-2016 Oracle Corporation */ #ifndef __UAPI_VBOX_VMMDEV_TYPES_H__ #define __UAPI_VBOX_VMMDEV_TYPES_H__ #include #include /* * We cannot use linux' compiletime_assert here because it expects to be used * inside a function only. Use a typedef to a char array with a negative size. */ #define VMMDEV_ASSERT_SIZE(type, size) \ typedef char type ## _asrt_size[1 - 2*!!(sizeof(struct type) != (size))] /** enum vmmdev_request_type - VMMDev request types. */ enum vmmdev_request_type { VMMDEVREQ_INVALID_REQUEST = 0, VMMDEVREQ_GET_MOUSE_STATUS = 1, VMMDEVREQ_SET_MOUSE_STATUS = 2, VMMDEVREQ_SET_POINTER_SHAPE = 3, VMMDEVREQ_GET_HOST_VERSION = 4, VMMDEVREQ_IDLE = 5, VMMDEVREQ_GET_HOST_TIME = 10, VMMDEVREQ_GET_HYPERVISOR_INFO = 20, VMMDEVREQ_SET_HYPERVISOR_INFO = 21, VMMDEVREQ_REGISTER_PATCH_MEMORY = 22, /* since version 3.0.6 */ VMMDEVREQ_DEREGISTER_PATCH_MEMORY = 23, /* since version 3.0.6 */ VMMDEVREQ_SET_POWER_STATUS = 30, VMMDEVREQ_ACKNOWLEDGE_EVENTS = 41, VMMDEVREQ_CTL_GUEST_FILTER_MASK = 42, VMMDEVREQ_REPORT_GUEST_INFO = 50, VMMDEVREQ_REPORT_GUEST_INFO2 = 58, /* since version 3.2.0 */ VMMDEVREQ_REPORT_GUEST_STATUS = 59, /* since version 3.2.8 */ VMMDEVREQ_REPORT_GUEST_USER_STATE = 74, /* since version 4.3 */ /* Retrieve a display resize request sent by the host, deprecated. */ VMMDEVREQ_GET_DISPLAY_CHANGE_REQ = 51, VMMDEVREQ_VIDEMODE_SUPPORTED = 52, VMMDEVREQ_GET_HEIGHT_REDUCTION = 53, /** * @VMMDEVREQ_GET_DISPLAY_CHANGE_REQ2: * Retrieve a display resize request sent by the host. * * Queries a display resize request sent from the host. If the * event_ack member is sent to true and there is an unqueried request * available for one of the virtual display then that request will * be returned. If several displays have unqueried requests the lowest * numbered display will be chosen first. Only the most recent unseen * request for each display is remembered. * If event_ack is set to false, the last host request queried with * event_ack set is resent, or failing that the most recent received * from the host. If no host request was ever received then all zeros * are returned. */ VMMDEVREQ_GET_DISPLAY_CHANGE_REQ2 = 54, VMMDEVREQ_REPORT_GUEST_CAPABILITIES = 55, VMMDEVREQ_SET_GUEST_CAPABILITIES = 56, VMMDEVREQ_VIDEMODE_SUPPORTED2 = 57, /* since version 3.2.0 */ VMMDEVREQ_GET_DISPLAY_CHANGE_REQEX = 80, /* since version 4.2.4 */ VMMDEVREQ_HGCM_CONNECT = 60, VMMDEVREQ_HGCM_DISCONNECT = 61, VMMDEVREQ_HGCM_CALL32 = 62, VMMDEVREQ_HGCM_CALL64 = 63, VMMDEVREQ_HGCM_CANCEL = 64, VMMDEVREQ_HGCM_CANCEL2 = 65, VMMDEVREQ_VIDEO_ACCEL_ENABLE = 70, VMMDEVREQ_VIDEO_ACCEL_FLUSH = 71, VMMDEVREQ_VIDEO_SET_VISIBLE_REGION = 72, VMMDEVREQ_GET_SEAMLESS_CHANGE_REQ = 73, VMMDEVREQ_QUERY_CREDENTIALS = 100, VMMDEVREQ_REPORT_CREDENTIALS_JUDGEMENT = 101, VMMDEVREQ_REPORT_GUEST_STATS = 110, VMMDEVREQ_GET_MEMBALLOON_CHANGE_REQ = 111, VMMDEVREQ_GET_STATISTICS_CHANGE_REQ = 112, VMMDEVREQ_CHANGE_MEMBALLOON = 113, VMMDEVREQ_GET_VRDPCHANGE_REQ = 150, VMMDEVREQ_LOG_STRING = 200, VMMDEVREQ_GET_CPU_HOTPLUG_REQ = 210, VMMDEVREQ_SET_CPU_HOTPLUG_STATUS = 211, VMMDEVREQ_REGISTER_SHARED_MODULE = 212, VMMDEVREQ_UNREGISTER_SHARED_MODULE = 213, VMMDEVREQ_CHECK_SHARED_MODULES = 214, VMMDEVREQ_GET_PAGE_SHARING_STATUS = 215, VMMDEVREQ_DEBUG_IS_PAGE_SHARED = 216, VMMDEVREQ_GET_SESSION_ID = 217, /* since version 3.2.8 */ VMMDEVREQ_WRITE_COREDUMP = 218, VMMDEVREQ_GUEST_HEARTBEAT = 219, VMMDEVREQ_HEARTBEAT_CONFIGURE = 220, /* Ensure the enum is a 32 bit data-type */ VMMDEVREQ_SIZEHACK = 0x7fffffff }; #if __BITS_PER_LONG == 64 #define VMMDEVREQ_HGCM_CALL VMMDEVREQ_HGCM_CALL64 #else #define VMMDEVREQ_HGCM_CALL VMMDEVREQ_HGCM_CALL32 #endif /** HGCM service location types. */ enum vmmdev_hgcm_service_location_type { VMMDEV_HGCM_LOC_INVALID = 0, VMMDEV_HGCM_LOC_LOCALHOST = 1, VMMDEV_HGCM_LOC_LOCALHOST_EXISTING = 2, /* Ensure the enum is a 32 bit data-type */ VMMDEV_HGCM_LOC_SIZEHACK = 0x7fffffff }; /** HGCM host service location. */ struct vmmdev_hgcm_service_location_localhost { /** Service name */ char service_name[128]; }; VMMDEV_ASSERT_SIZE(vmmdev_hgcm_service_location_localhost, 128); /** HGCM service location. */ struct vmmdev_hgcm_service_location { /** Type of the location. */ enum vmmdev_hgcm_service_location_type type; union { struct vmmdev_hgcm_service_location_localhost localhost; } u; }; VMMDEV_ASSERT_SIZE(vmmdev_hgcm_service_location, 128 + 4); /** HGCM function parameter type. */ enum vmmdev_hgcm_function_parameter_type { VMMDEV_HGCM_PARM_TYPE_INVALID = 0, VMMDEV_HGCM_PARM_TYPE_32BIT = 1, VMMDEV_HGCM_PARM_TYPE_64BIT = 2, /** Deprecated Doesn't work, use PAGELIST. */ VMMDEV_HGCM_PARM_TYPE_PHYSADDR = 3, /** In and Out, user-memory */ VMMDEV_HGCM_PARM_TYPE_LINADDR = 4, /** In, user-memory (read; host<-guest) */ VMMDEV_HGCM_PARM_TYPE_LINADDR_IN = 5, /** Out, user-memory (write; host->guest) */ VMMDEV_HGCM_PARM_TYPE_LINADDR_OUT = 6, /** In and Out, kernel-memory */ VMMDEV_HGCM_PARM_TYPE_LINADDR_KERNEL = 7, /** In, kernel-memory (read; host<-guest) */ VMMDEV_HGCM_PARM_TYPE_LINADDR_KERNEL_IN = 8, /** Out, kernel-memory (write; host->guest) */ VMMDEV_HGCM_PARM_TYPE_LINADDR_KERNEL_OUT = 9, /** Physical addresses of locked pages for a buffer. */ VMMDEV_HGCM_PARM_TYPE_PAGELIST = 10, /* Ensure the enum is a 32 bit data-type */ VMMDEV_HGCM_PARM_TYPE_SIZEHACK = 0x7fffffff }; /** HGCM function parameter, 32-bit client. */ struct vmmdev_hgcm_function_parameter32 { enum vmmdev_hgcm_function_parameter_type type; union { __u32 value32; __u64 value64; struct { __u32 size; union { __u32 phys_addr; __u32 linear_addr; } u; } pointer; struct { /** Size of the buffer described by the page list. */ __u32 size; /** Relative to the request header. */ __u32 offset; } page_list; } u; } __attribute__((packed)); VMMDEV_ASSERT_SIZE(vmmdev_hgcm_function_parameter32, 4 + 8); /** HGCM function parameter, 64-bit client. */ struct vmmdev_hgcm_function_parameter64 { enum vmmdev_hgcm_function_parameter_type type; union { __u32 value32; __u64 value64; struct { __u32 size; union { __u64 phys_addr; __u64 linear_addr; } u; } __attribute__((packed)) pointer; struct { /** Size of the buffer described by the page list. */ __u32 size; /** Relative to the request header. */ __u32 offset; } page_list; } __attribute__((packed)) u; } __attribute__((packed)); VMMDEV_ASSERT_SIZE(vmmdev_hgcm_function_parameter64, 4 + 12); #if __BITS_PER_LONG == 64 #define vmmdev_hgcm_function_parameter vmmdev_hgcm_function_parameter64 #else #define vmmdev_hgcm_function_parameter vmmdev_hgcm_function_parameter32 #endif #define VMMDEV_HGCM_F_PARM_DIRECTION_NONE 0x00000000U #define VMMDEV_HGCM_F_PARM_DIRECTION_TO_HOST 0x00000001U #define VMMDEV_HGCM_F_PARM_DIRECTION_FROM_HOST 0x00000002U #define VMMDEV_HGCM_F_PARM_DIRECTION_BOTH 0x00000003U /** * struct vmmdev_hgcm_pagelist - VMMDEV_HGCM_PARM_TYPE_PAGELIST parameters * point to this structure to actually describe the buffer. */ struct vmmdev_hgcm_pagelist { __u32 flags; /** VMMDEV_HGCM_F_PARM_*. */ __u16 offset_first_page; /** Data offset in the first page. */ __u16 page_count; /** Number of pages. */ __u64 pages[1]; /** Page addresses. */ }; VMMDEV_ASSERT_SIZE(vmmdev_hgcm_pagelist, 4 + 2 + 2 + 8); #endif linux/errno.h000064400000000027151027430560007203 0ustar00#include linux/a.out.h000064400000015354151027430560007115 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __A_OUT_GNU_H__ #define __A_OUT_GNU_H__ #define __GNU_EXEC_MACROS__ #ifndef __STRUCT_EXEC_OVERRIDE__ #include #endif /* __STRUCT_EXEC_OVERRIDE__ */ #ifndef __ASSEMBLY__ /* these go in the N_MACHTYPE field */ enum machine_type { #if defined (M_OLDSUN2) M__OLDSUN2 = M_OLDSUN2, #else M_OLDSUN2 = 0, #endif #if defined (M_68010) M__68010 = M_68010, #else M_68010 = 1, #endif #if defined (M_68020) M__68020 = M_68020, #else M_68020 = 2, #endif #if defined (M_SPARC) M__SPARC = M_SPARC, #else M_SPARC = 3, #endif /* skip a bunch so we don't run into any of sun's numbers */ M_386 = 100, M_MIPS1 = 151, /* MIPS R3000/R3000 binary */ M_MIPS2 = 152 /* MIPS R6000/R4000 binary */ }; #if !defined (N_MAGIC) #define N_MAGIC(exec) ((exec).a_info & 0xffff) #endif #define N_MACHTYPE(exec) ((enum machine_type)(((exec).a_info >> 16) & 0xff)) #define N_FLAGS(exec) (((exec).a_info >> 24) & 0xff) #define N_SET_INFO(exec, magic, type, flags) \ ((exec).a_info = ((magic) & 0xffff) \ | (((int)(type) & 0xff) << 16) \ | (((flags) & 0xff) << 24)) #define N_SET_MAGIC(exec, magic) \ ((exec).a_info = (((exec).a_info & 0xffff0000) | ((magic) & 0xffff))) #define N_SET_MACHTYPE(exec, machtype) \ ((exec).a_info = \ ((exec).a_info&0xff00ffff) | ((((int)(machtype))&0xff) << 16)) #define N_SET_FLAGS(exec, flags) \ ((exec).a_info = \ ((exec).a_info&0x00ffffff) | (((flags) & 0xff) << 24)) /* Code indicating object file or impure executable. */ #define OMAGIC 0407 /* Code indicating pure executable. */ #define NMAGIC 0410 /* Code indicating demand-paged executable. */ #define ZMAGIC 0413 /* This indicates a demand-paged executable with the header in the text. The first page is unmapped to help trap NULL pointer references */ #define QMAGIC 0314 /* Code indicating core file. */ #define CMAGIC 0421 #if !defined (N_BADMAG) #define N_BADMAG(x) (N_MAGIC(x) != OMAGIC \ && N_MAGIC(x) != NMAGIC \ && N_MAGIC(x) != ZMAGIC \ && N_MAGIC(x) != QMAGIC) #endif #define _N_HDROFF(x) (1024 - sizeof (struct exec)) #if !defined (N_TXTOFF) #define N_TXTOFF(x) \ (N_MAGIC(x) == ZMAGIC ? _N_HDROFF((x)) + sizeof (struct exec) : \ (N_MAGIC(x) == QMAGIC ? 0 : sizeof (struct exec))) #endif #if !defined (N_DATOFF) #define N_DATOFF(x) (N_TXTOFF(x) + (x).a_text) #endif #if !defined (N_TRELOFF) #define N_TRELOFF(x) (N_DATOFF(x) + (x).a_data) #endif #if !defined (N_DRELOFF) #define N_DRELOFF(x) (N_TRELOFF(x) + N_TRSIZE(x)) #endif #if !defined (N_SYMOFF) #define N_SYMOFF(x) (N_DRELOFF(x) + N_DRSIZE(x)) #endif #if !defined (N_STROFF) #define N_STROFF(x) (N_SYMOFF(x) + N_SYMSIZE(x)) #endif /* Address of text segment in memory after it is loaded. */ #if !defined (N_TXTADDR) #define N_TXTADDR(x) (N_MAGIC(x) == QMAGIC ? PAGE_SIZE : 0) #endif /* Address of data segment in memory after it is loaded. */ #include #if defined(__i386__) || defined(__mc68000__) #define SEGMENT_SIZE 1024 #else #ifndef SEGMENT_SIZE #define SEGMENT_SIZE getpagesize() #endif #endif #define _N_SEGMENT_ROUND(x) ALIGN(x, SEGMENT_SIZE) #define _N_TXTENDADDR(x) (N_TXTADDR(x)+(x).a_text) #ifndef N_DATADDR #define N_DATADDR(x) \ (N_MAGIC(x)==OMAGIC? (_N_TXTENDADDR(x)) \ : (_N_SEGMENT_ROUND (_N_TXTENDADDR(x)))) #endif /* Address of bss segment in memory after it is loaded. */ #if !defined (N_BSSADDR) #define N_BSSADDR(x) (N_DATADDR(x) + (x).a_data) #endif #if !defined (N_NLIST_DECLARED) struct nlist { union { char *n_name; struct nlist *n_next; long n_strx; } n_un; unsigned char n_type; char n_other; short n_desc; unsigned long n_value; }; #endif /* no N_NLIST_DECLARED. */ #if !defined (N_UNDF) #define N_UNDF 0 #endif #if !defined (N_ABS) #define N_ABS 2 #endif #if !defined (N_TEXT) #define N_TEXT 4 #endif #if !defined (N_DATA) #define N_DATA 6 #endif #if !defined (N_BSS) #define N_BSS 8 #endif #if !defined (N_FN) #define N_FN 15 #endif #if !defined (N_EXT) #define N_EXT 1 #endif #if !defined (N_TYPE) #define N_TYPE 036 #endif #if !defined (N_STAB) #define N_STAB 0340 #endif /* The following type indicates the definition of a symbol as being an indirect reference to another symbol. The other symbol appears as an undefined reference, immediately following this symbol. Indirection is asymmetrical. The other symbol's value will be used to satisfy requests for the indirect symbol, but not vice versa. If the other symbol does not have a definition, libraries will be searched to find a definition. */ #define N_INDR 0xa /* The following symbols refer to set elements. All the N_SET[ATDB] symbols with the same name form one set. Space is allocated for the set in the text section, and each set element's value is stored into one word of the space. The first word of the space is the length of the set (number of elements). The address of the set is made into an N_SETV symbol whose name is the same as the name of the set. This symbol acts like a N_DATA global symbol in that it can satisfy undefined external references. */ /* These appear as input to LD, in a .o file. */ #define N_SETA 0x14 /* Absolute set element symbol */ #define N_SETT 0x16 /* Text set element symbol */ #define N_SETD 0x18 /* Data set element symbol */ #define N_SETB 0x1A /* Bss set element symbol */ /* This is output from LD. */ #define N_SETV 0x1C /* Pointer to set vector in data area. */ #if !defined (N_RELOCATION_INFO_DECLARED) /* This structure describes a single relocation to be performed. The text-relocation section of the file is a vector of these structures, all of which apply to the text section. Likewise, the data-relocation section applies to the data section. */ struct relocation_info { /* Address (within segment) to be relocated. */ int r_address; /* The meaning of r_symbolnum depends on r_extern. */ unsigned int r_symbolnum:24; /* Nonzero means value is a pc-relative offset and it should be relocated for changes in its own address as well as for changes in the symbol or section specified. */ unsigned int r_pcrel:1; /* Length (as exponent of 2) of the field to be relocated. Thus, a value of 2 indicates 1<<2 bytes. */ unsigned int r_length:2; /* 1 => relocate with value of symbol. r_symbolnum is the index of the symbol in file's the symbol table. 0 => relocate with the address of a segment. r_symbolnum is N_TEXT, N_DATA, N_BSS or N_ABS (the N_EXT bit may be set also, but signifies nothing). */ unsigned int r_extern:1; /* Four bits that aren't used, but when writing an object file it is desirable to clear them. */ unsigned int r_pad:4; }; #endif /* no N_RELOCATION_INFO_DECLARED. */ #endif /*__ASSEMBLY__ */ #endif /* __A_OUT_GNU_H__ */ linux/net_dropmon.h000064400000005552151027430560010412 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __NET_DROPMON_H #define __NET_DROPMON_H #include #include struct net_dm_drop_point { __u8 pc[8]; __u32 count; }; #define is_drop_point_hw(x) do {\ int ____i, ____j;\ for (____i = 0; ____i < 8; i ____i++)\ ____j |= x[____i];\ ____j;\ } while (0) #define NET_DM_CFG_VERSION 0 #define NET_DM_CFG_ALERT_COUNT 1 #define NET_DM_CFG_ALERT_DELAY 2 #define NET_DM_CFG_MAX 3 struct net_dm_config_entry { __u32 type; __u64 data __attribute__((aligned(8))); }; struct net_dm_config_msg { __u32 entries; struct net_dm_config_entry options[0]; }; struct net_dm_alert_msg { __u32 entries; struct net_dm_drop_point points[0]; }; struct net_dm_user_msg { union { struct net_dm_config_msg user; struct net_dm_alert_msg alert; } u; }; /* These are the netlink message types for this protocol */ enum { NET_DM_CMD_UNSPEC = 0, NET_DM_CMD_ALERT, NET_DM_CMD_CONFIG, NET_DM_CMD_START, NET_DM_CMD_STOP, NET_DM_CMD_PACKET_ALERT, NET_DM_CMD_CONFIG_GET, NET_DM_CMD_CONFIG_NEW, NET_DM_CMD_STATS_GET, NET_DM_CMD_STATS_NEW, _NET_DM_CMD_MAX, }; #define NET_DM_CMD_MAX (_NET_DM_CMD_MAX - 1) /* * Our group identifiers */ #define NET_DM_GRP_ALERT 1 enum net_dm_attr { NET_DM_ATTR_UNSPEC, NET_DM_ATTR_ALERT_MODE, /* u8 */ NET_DM_ATTR_PC, /* u64 */ NET_DM_ATTR_SYMBOL, /* string */ NET_DM_ATTR_IN_PORT, /* nested */ NET_DM_ATTR_TIMESTAMP, /* u64 */ NET_DM_ATTR_PROTO, /* u16 */ NET_DM_ATTR_PAYLOAD, /* binary */ NET_DM_ATTR_PAD, NET_DM_ATTR_TRUNC_LEN, /* u32 */ NET_DM_ATTR_ORIG_LEN, /* u32 */ NET_DM_ATTR_QUEUE_LEN, /* u32 */ NET_DM_ATTR_STATS, /* nested */ NET_DM_ATTR_HW_STATS, /* nested */ NET_DM_ATTR_ORIGIN, /* u16 */ NET_DM_ATTR_HW_TRAP_GROUP_NAME, /* string */ NET_DM_ATTR_HW_TRAP_NAME, /* string */ NET_DM_ATTR_HW_ENTRIES, /* nested */ NET_DM_ATTR_HW_ENTRY, /* nested */ NET_DM_ATTR_HW_TRAP_COUNT, /* u32 */ NET_DM_ATTR_SW_DROPS, /* flag */ NET_DM_ATTR_HW_DROPS, /* flag */ NET_DM_ATTR_FLOW_ACTION_COOKIE, /* binary */ NET_DM_ATTR_REASON, /* string */ __NET_DM_ATTR_MAX, NET_DM_ATTR_MAX = __NET_DM_ATTR_MAX - 1 }; /** * enum net_dm_alert_mode - Alert mode. * @NET_DM_ALERT_MODE_SUMMARY: A summary of recent drops is sent to user space. * @NET_DM_ALERT_MODE_PACKET: Each dropped packet is sent to user space along * with metadata. */ enum net_dm_alert_mode { NET_DM_ALERT_MODE_SUMMARY, NET_DM_ALERT_MODE_PACKET, }; enum { NET_DM_ATTR_PORT_NETDEV_IFINDEX, /* u32 */ NET_DM_ATTR_PORT_NETDEV_NAME, /* string */ __NET_DM_ATTR_PORT_MAX, NET_DM_ATTR_PORT_MAX = __NET_DM_ATTR_PORT_MAX - 1 }; enum { NET_DM_ATTR_STATS_DROPPED, /* u64 */ __NET_DM_ATTR_STATS_MAX, NET_DM_ATTR_STATS_MAX = __NET_DM_ATTR_STATS_MAX - 1 }; enum net_dm_origin { NET_DM_ORIGIN_SW, NET_DM_ORIGIN_HW, }; #endif linux/ipmi.h000064400000036122151027430560007021 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * ipmi.h * * MontaVista IPMI interface * * Author: MontaVista Software, Inc. * Corey Minyard * source@mvista.com * * Copyright 2002 MontaVista Software Inc. * */ #ifndef __LINUX_IPMI_H #define __LINUX_IPMI_H #include /* * This file describes an interface to an IPMI driver. You have to * have a fairly good understanding of IPMI to use this, so go read * the specs first before actually trying to do anything. * * With that said, this driver provides a multi-user interface to the * IPMI driver, and it allows multiple IPMI physical interfaces below * the driver. The physical interfaces bind as a lower layer on the * driver. They appear as interfaces to the application using this * interface. * * Multi-user means that multiple applications may use the driver, * send commands, receive responses, etc. The driver keeps track of * commands the user sends and tracks the responses. The responses * will go back to the application that send the command. If the * response doesn't come back in time, the driver will return a * timeout error response to the application. Asynchronous events * from the BMC event queue will go to all users bound to the driver. * The incoming event queue in the BMC will automatically be flushed * if it becomes full and it is queried once a second to see if * anything is in it. Incoming commands to the driver will get * delivered as commands. */ /* * This is an overlay for all the address types, so it's easy to * determine the actual address type. This is kind of like addresses * work for sockets. */ #define IPMI_MAX_ADDR_SIZE 32 struct ipmi_addr { /* Try to take these from the "Channel Medium Type" table in section 6.5 of the IPMI 1.5 manual. */ int addr_type; short channel; char data[IPMI_MAX_ADDR_SIZE]; }; /* * When the address is not used, the type will be set to this value. * The channel is the BMC's channel number for the channel (usually * 0), or IPMC_BMC_CHANNEL if communicating directly with the BMC. */ #define IPMI_SYSTEM_INTERFACE_ADDR_TYPE 0x0c struct ipmi_system_interface_addr { int addr_type; short channel; unsigned char lun; }; /* An IPMB Address. */ #define IPMI_IPMB_ADDR_TYPE 0x01 /* Used for broadcast get device id as described in section 17.9 of the IPMI 1.5 manual. */ #define IPMI_IPMB_BROADCAST_ADDR_TYPE 0x41 struct ipmi_ipmb_addr { int addr_type; short channel; unsigned char slave_addr; unsigned char lun; }; /* * Used for messages received directly from an IPMB that have not gone * through a MC. This is for systems that sit right on an IPMB so * they can receive commands and respond to them. */ #define IPMI_IPMB_DIRECT_ADDR_TYPE 0x81 struct ipmi_ipmb_direct_addr { int addr_type; short channel; unsigned char slave_addr; unsigned char rs_lun; unsigned char rq_lun; }; /* * A LAN Address. This is an address to/from a LAN interface bridged * by the BMC, not an address actually out on the LAN. * * A conscious decision was made here to deviate slightly from the IPMI * spec. We do not use rqSWID and rsSWID like it shows in the * message. Instead, we use remote_SWID and local_SWID. This means * that any message (a request or response) from another device will * always have exactly the same address. If you didn't do this, * requests and responses from the same device would have different * addresses, and that's not too cool. * * In this address, the remote_SWID is always the SWID the remote * message came from, or the SWID we are sending the message to. * local_SWID is always our SWID. Note that having our SWID in the * message is a little weird, but this is required. */ #define IPMI_LAN_ADDR_TYPE 0x04 struct ipmi_lan_addr { int addr_type; short channel; unsigned char privilege; unsigned char session_handle; unsigned char remote_SWID; unsigned char local_SWID; unsigned char lun; }; /* * Channel for talking directly with the BMC. When using this * channel, This is for the system interface address type only. FIXME * - is this right, or should we use -1? */ #define IPMI_BMC_CHANNEL 0xf #define IPMI_NUM_CHANNELS 0x10 /* * Used to signify an "all channel" bitmask. This is more than the * actual number of channels because this is used in userland and * will cover us if the number of channels is extended. */ #define IPMI_CHAN_ALL (~0) /* * A raw IPMI message without any addressing. This covers both * commands and responses. The completion code is always the first * byte of data in the response (as the spec shows the messages laid * out). */ struct ipmi_msg { unsigned char netfn; unsigned char cmd; unsigned short data_len; unsigned char *data; }; struct kernel_ipmi_msg { unsigned char netfn; unsigned char cmd; unsigned short data_len; unsigned char *data; }; /* * Various defines that are useful for IPMI applications. */ #define IPMI_INVALID_CMD_COMPLETION_CODE 0xC1 #define IPMI_TIMEOUT_COMPLETION_CODE 0xC3 #define IPMI_UNKNOWN_ERR_COMPLETION_CODE 0xff /* * Receive types for messages coming from the receive interface. This * is used for the receive in-kernel interface and in the receive * IOCTL. * * The "IPMI_RESPONSE_RESPNOSE_TYPE" is a little strange sounding, but * it allows you to get the message results when you send a response * message. */ #define IPMI_RESPONSE_RECV_TYPE 1 /* A response to a command */ #define IPMI_ASYNC_EVENT_RECV_TYPE 2 /* Something from the event queue */ #define IPMI_CMD_RECV_TYPE 3 /* A command from somewhere else */ #define IPMI_RESPONSE_RESPONSE_TYPE 4 /* The response for a sent response, giving any error status for sending the response. When you send a response message, this will be returned. */ #define IPMI_OEM_RECV_TYPE 5 /* The response for OEM Channels */ /* Note that async events and received commands do not have a completion code as the first byte of the incoming data, unlike a response. */ /* * Modes for ipmi_set_maint_mode() and the userland IOCTL. The AUTO * setting is the default and means it will be set on certain * commands. Hard setting it on and off will override automatic * operation. */ #define IPMI_MAINTENANCE_MODE_AUTO 0 #define IPMI_MAINTENANCE_MODE_OFF 1 #define IPMI_MAINTENANCE_MODE_ON 2 /* * The userland interface */ /* * The userland interface for the IPMI driver is a standard character * device, with each instance of an interface registered as a minor * number under the major character device. * * The read and write calls do not work, to get messages in and out * requires ioctl calls because of the complexity of the data. select * and poll do work, so you can wait for input using the file * descriptor, you just can use read to get it. * * In general, you send a command down to the interface and receive * responses back. You can use the msgid value to correlate commands * and responses, the driver will take care of figuring out which * incoming messages are for which command and find the proper msgid * value to report. You will only receive reponses for commands you * send. Asynchronous events, however, go to all open users, so you * must be ready to handle these (or ignore them if you don't care). * * The address type depends upon the channel type. When talking * directly to the BMC (IPMC_BMC_CHANNEL), the address is ignored * (IPMI_UNUSED_ADDR_TYPE). When talking to an IPMB channel, you must * supply a valid IPMB address with the addr_type set properly. * * When talking to normal channels, the driver takes care of the * details of formatting and sending messages on that channel. You do * not, for instance, have to format a send command, you just send * whatever command you want to the channel, the driver will create * the send command, automatically issue receive command and get even * commands, and pass those up to the proper user. */ /* The magic IOCTL value for this interface. */ #define IPMI_IOC_MAGIC 'i' /* Messages sent to the interface are this format. */ struct ipmi_req { unsigned char *addr; /* Address to send the message to. */ unsigned int addr_len; long msgid; /* The sequence number for the message. This exact value will be reported back in the response to this request if it is a command. If it is a response, this will be used as the sequence value for the response. */ struct ipmi_msg msg; }; /* * Send a message to the interfaces. error values are: * - EFAULT - an address supplied was invalid. * - EINVAL - The address supplied was not valid, or the command * was not allowed. * - EMSGSIZE - The message to was too large. * - ENOMEM - Buffers could not be allocated for the command. */ #define IPMICTL_SEND_COMMAND _IOR(IPMI_IOC_MAGIC, 13, \ struct ipmi_req) /* Messages sent to the interface with timing parameters are this format. */ struct ipmi_req_settime { struct ipmi_req req; /* See ipmi_request_settime() above for details on these values. */ int retries; unsigned int retry_time_ms; }; /* * Send a message to the interfaces with timing parameters. error values * are: * - EFAULT - an address supplied was invalid. * - EINVAL - The address supplied was not valid, or the command * was not allowed. * - EMSGSIZE - The message to was too large. * - ENOMEM - Buffers could not be allocated for the command. */ #define IPMICTL_SEND_COMMAND_SETTIME _IOR(IPMI_IOC_MAGIC, 21, \ struct ipmi_req_settime) /* Messages received from the interface are this format. */ struct ipmi_recv { int recv_type; /* Is this a command, response or an asyncronous event. */ unsigned char *addr; /* Address the message was from is put here. The caller must supply the memory. */ unsigned int addr_len; /* The size of the address buffer. The caller supplies the full buffer length, this value is updated to the actual message length when the message is received. */ long msgid; /* The sequence number specified in the request if this is a response. If this is a command, this will be the sequence number from the command. */ struct ipmi_msg msg; /* The data field must point to a buffer. The data_size field must be set to the size of the message buffer. The caller supplies the full buffer length, this value is updated to the actual message length when the message is received. */ }; /* * Receive a message. error values: * - EAGAIN - no messages in the queue. * - EFAULT - an address supplied was invalid. * - EINVAL - The address supplied was not valid. * - EMSGSIZE - The message to was too large to fit into the message buffer, * the message will be left in the buffer. */ #define IPMICTL_RECEIVE_MSG _IOWR(IPMI_IOC_MAGIC, 12, \ struct ipmi_recv) /* * Like RECEIVE_MSG, but if the message won't fit in the buffer, it * will truncate the contents instead of leaving the data in the * buffer. */ #define IPMICTL_RECEIVE_MSG_TRUNC _IOWR(IPMI_IOC_MAGIC, 11, \ struct ipmi_recv) /* Register to get commands from other entities on this interface. */ struct ipmi_cmdspec { unsigned char netfn; unsigned char cmd; }; /* * Register to receive a specific command. error values: * - EFAULT - an address supplied was invalid. * - EBUSY - The netfn/cmd supplied was already in use. * - ENOMEM - could not allocate memory for the entry. */ #define IPMICTL_REGISTER_FOR_CMD _IOR(IPMI_IOC_MAGIC, 14, \ struct ipmi_cmdspec) /* * Unregister a registered command. error values: * - EFAULT - an address supplied was invalid. * - ENOENT - The netfn/cmd was not found registered for this user. */ #define IPMICTL_UNREGISTER_FOR_CMD _IOR(IPMI_IOC_MAGIC, 15, \ struct ipmi_cmdspec) /* * Register to get commands from other entities on specific channels. * This way, you can only listen on specific channels, or have messages * from some channels go to one place and other channels to someplace * else. The chans field is a bitmask, (1 << channel) for each channel. * It may be IPMI_CHAN_ALL for all channels. */ struct ipmi_cmdspec_chans { unsigned int netfn; unsigned int cmd; unsigned int chans; }; /* * Register to receive a specific command on specific channels. error values: * - EFAULT - an address supplied was invalid. * - EBUSY - One of the netfn/cmd/chans supplied was already in use. * - ENOMEM - could not allocate memory for the entry. */ #define IPMICTL_REGISTER_FOR_CMD_CHANS _IOR(IPMI_IOC_MAGIC, 28, \ struct ipmi_cmdspec_chans) /* * Unregister some netfn/cmd/chans. error values: * - EFAULT - an address supplied was invalid. * - ENOENT - None of the netfn/cmd/chans were found registered for this user. */ #define IPMICTL_UNREGISTER_FOR_CMD_CHANS _IOR(IPMI_IOC_MAGIC, 29, \ struct ipmi_cmdspec_chans) /* * Set whether this interface receives events. Note that the first * user registered for events will get all pending events for the * interface. error values: * - EFAULT - an address supplied was invalid. */ #define IPMICTL_SET_GETS_EVENTS_CMD _IOR(IPMI_IOC_MAGIC, 16, int) /* * Set and get the slave address and LUN that we will use for our * source messages. Note that this affects the interface, not just * this user, so it will affect all users of this interface. This is * so some initialization code can come in and do the OEM-specific * things it takes to determine your address (if not the BMC) and set * it for everyone else. You should probably leave the LUN alone. */ struct ipmi_channel_lun_address_set { unsigned short channel; unsigned char value; }; #define IPMICTL_SET_MY_CHANNEL_ADDRESS_CMD \ _IOR(IPMI_IOC_MAGIC, 24, struct ipmi_channel_lun_address_set) #define IPMICTL_GET_MY_CHANNEL_ADDRESS_CMD \ _IOR(IPMI_IOC_MAGIC, 25, struct ipmi_channel_lun_address_set) #define IPMICTL_SET_MY_CHANNEL_LUN_CMD \ _IOR(IPMI_IOC_MAGIC, 26, struct ipmi_channel_lun_address_set) #define IPMICTL_GET_MY_CHANNEL_LUN_CMD \ _IOR(IPMI_IOC_MAGIC, 27, struct ipmi_channel_lun_address_set) /* Legacy interfaces, these only set IPMB 0. */ #define IPMICTL_SET_MY_ADDRESS_CMD _IOR(IPMI_IOC_MAGIC, 17, unsigned int) #define IPMICTL_GET_MY_ADDRESS_CMD _IOR(IPMI_IOC_MAGIC, 18, unsigned int) #define IPMICTL_SET_MY_LUN_CMD _IOR(IPMI_IOC_MAGIC, 19, unsigned int) #define IPMICTL_GET_MY_LUN_CMD _IOR(IPMI_IOC_MAGIC, 20, unsigned int) /* * Get/set the default timing values for an interface. You shouldn't * generally mess with these. */ struct ipmi_timing_parms { int retries; unsigned int retry_time_ms; }; #define IPMICTL_SET_TIMING_PARMS_CMD _IOR(IPMI_IOC_MAGIC, 22, \ struct ipmi_timing_parms) #define IPMICTL_GET_TIMING_PARMS_CMD _IOR(IPMI_IOC_MAGIC, 23, \ struct ipmi_timing_parms) /* * Set the maintenance mode. See ipmi_set_maintenance_mode() above * for a description of what this does. */ #define IPMICTL_GET_MAINTENANCE_MODE_CMD _IOR(IPMI_IOC_MAGIC, 30, int) #define IPMICTL_SET_MAINTENANCE_MODE_CMD _IOW(IPMI_IOC_MAGIC, 31, int) #endif /* __LINUX_IPMI_H */ linux/devlink.h000064400000052064151027430560007522 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * include/uapi/linux/devlink.h - Network physical device Netlink interface * Copyright (c) 2016 Mellanox Technologies. All rights reserved. * Copyright (c) 2016 Jiri Pirko * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef _LINUX_DEVLINK_H_ #define _LINUX_DEVLINK_H_ #include #define DEVLINK_GENL_NAME "devlink" #define DEVLINK_GENL_VERSION 0x1 #define DEVLINK_GENL_MCGRP_CONFIG_NAME "config" enum devlink_command { /* don't change the order or add anything between, this is ABI! */ DEVLINK_CMD_UNSPEC, DEVLINK_CMD_GET, /* can dump */ DEVLINK_CMD_SET, DEVLINK_CMD_NEW, DEVLINK_CMD_DEL, DEVLINK_CMD_PORT_GET, /* can dump */ DEVLINK_CMD_PORT_SET, DEVLINK_CMD_PORT_NEW, DEVLINK_CMD_PORT_DEL, DEVLINK_CMD_PORT_SPLIT, DEVLINK_CMD_PORT_UNSPLIT, DEVLINK_CMD_SB_GET, /* can dump */ DEVLINK_CMD_SB_SET, DEVLINK_CMD_SB_NEW, DEVLINK_CMD_SB_DEL, DEVLINK_CMD_SB_POOL_GET, /* can dump */ DEVLINK_CMD_SB_POOL_SET, DEVLINK_CMD_SB_POOL_NEW, DEVLINK_CMD_SB_POOL_DEL, DEVLINK_CMD_SB_PORT_POOL_GET, /* can dump */ DEVLINK_CMD_SB_PORT_POOL_SET, DEVLINK_CMD_SB_PORT_POOL_NEW, DEVLINK_CMD_SB_PORT_POOL_DEL, DEVLINK_CMD_SB_TC_POOL_BIND_GET, /* can dump */ DEVLINK_CMD_SB_TC_POOL_BIND_SET, DEVLINK_CMD_SB_TC_POOL_BIND_NEW, DEVLINK_CMD_SB_TC_POOL_BIND_DEL, /* Shared buffer occupancy monitoring commands */ DEVLINK_CMD_SB_OCC_SNAPSHOT, DEVLINK_CMD_SB_OCC_MAX_CLEAR, DEVLINK_CMD_ESWITCH_GET, #define DEVLINK_CMD_ESWITCH_MODE_GET /* obsolete, never use this! */ \ DEVLINK_CMD_ESWITCH_GET DEVLINK_CMD_ESWITCH_SET, #define DEVLINK_CMD_ESWITCH_MODE_SET /* obsolete, never use this! */ \ DEVLINK_CMD_ESWITCH_SET DEVLINK_CMD_DPIPE_TABLE_GET, DEVLINK_CMD_DPIPE_ENTRIES_GET, DEVLINK_CMD_DPIPE_HEADERS_GET, DEVLINK_CMD_DPIPE_TABLE_COUNTERS_SET, DEVLINK_CMD_RESOURCE_SET, DEVLINK_CMD_RESOURCE_DUMP, /* Hot driver reload, makes configuration changes take place. The * devlink instance is not released during the process. */ DEVLINK_CMD_RELOAD, DEVLINK_CMD_PARAM_GET, /* can dump */ DEVLINK_CMD_PARAM_SET, DEVLINK_CMD_PARAM_NEW, DEVLINK_CMD_PARAM_DEL, DEVLINK_CMD_REGION_GET, DEVLINK_CMD_REGION_SET, DEVLINK_CMD_REGION_NEW, DEVLINK_CMD_REGION_DEL, DEVLINK_CMD_REGION_READ, DEVLINK_CMD_PORT_PARAM_GET, /* can dump */ DEVLINK_CMD_PORT_PARAM_SET, DEVLINK_CMD_PORT_PARAM_NEW, DEVLINK_CMD_PORT_PARAM_DEL, DEVLINK_CMD_INFO_GET, /* can dump */ DEVLINK_CMD_HEALTH_REPORTER_GET, DEVLINK_CMD_HEALTH_REPORTER_SET, DEVLINK_CMD_HEALTH_REPORTER_RECOVER, DEVLINK_CMD_HEALTH_REPORTER_DIAGNOSE, DEVLINK_CMD_HEALTH_REPORTER_DUMP_GET, DEVLINK_CMD_HEALTH_REPORTER_DUMP_CLEAR, DEVLINK_CMD_FLASH_UPDATE, DEVLINK_CMD_FLASH_UPDATE_END, /* notification only */ DEVLINK_CMD_FLASH_UPDATE_STATUS, /* notification only */ DEVLINK_CMD_TRAP_GET, /* can dump */ DEVLINK_CMD_TRAP_SET, DEVLINK_CMD_TRAP_NEW, DEVLINK_CMD_TRAP_DEL, DEVLINK_CMD_TRAP_GROUP_GET, /* can dump */ DEVLINK_CMD_TRAP_GROUP_SET, DEVLINK_CMD_TRAP_GROUP_NEW, DEVLINK_CMD_TRAP_GROUP_DEL, DEVLINK_CMD_TRAP_POLICER_GET, /* can dump */ DEVLINK_CMD_TRAP_POLICER_SET, DEVLINK_CMD_TRAP_POLICER_NEW, DEVLINK_CMD_TRAP_POLICER_DEL, DEVLINK_CMD_HEALTH_REPORTER_TEST, DEVLINK_CMD_RATE_GET, /* can dump */ DEVLINK_CMD_RATE_SET, DEVLINK_CMD_RATE_NEW, DEVLINK_CMD_RATE_DEL, __RH_RESERVED_DEVLINK_CMD_LINECARD_GET, /* can dump */ __RH_RESERVED_DEVLINK_CMD_LINECARD_SET, __RH_RESERVED_DEVLINK_CMD_LINECARD_NEW, __RH_RESERVED_DEVLINK_CMD_LINECARD_DEL, DEVLINK_CMD_SELFTESTS_GET, /* can dump */ DEVLINK_CMD_SELFTESTS_RUN, /* add new commands above here */ __DEVLINK_CMD_MAX, DEVLINK_CMD_MAX = __DEVLINK_CMD_MAX - 1 }; enum devlink_port_type { DEVLINK_PORT_TYPE_NOTSET, DEVLINK_PORT_TYPE_AUTO, DEVLINK_PORT_TYPE_ETH, DEVLINK_PORT_TYPE_IB, }; enum devlink_sb_pool_type { DEVLINK_SB_POOL_TYPE_INGRESS, DEVLINK_SB_POOL_TYPE_EGRESS, }; /* static threshold - limiting the maximum number of bytes. * dynamic threshold - limiting the maximum number of bytes * based on the currently available free space in the shared buffer pool. * In this mode, the maximum quota is calculated based * on the following formula: * max_quota = alpha / (1 + alpha) * Free_Buffer * While Free_Buffer is the amount of none-occupied buffer associated to * the relevant pool. * The value range which can be passed is 0-20 and serves * for computation of alpha by following formula: * alpha = 2 ^ (passed_value - 10) */ enum devlink_sb_threshold_type { DEVLINK_SB_THRESHOLD_TYPE_STATIC, DEVLINK_SB_THRESHOLD_TYPE_DYNAMIC, }; #define DEVLINK_SB_THRESHOLD_TO_ALPHA_MAX 20 enum devlink_eswitch_mode { DEVLINK_ESWITCH_MODE_LEGACY, DEVLINK_ESWITCH_MODE_SWITCHDEV, }; enum devlink_eswitch_inline_mode { DEVLINK_ESWITCH_INLINE_MODE_NONE, DEVLINK_ESWITCH_INLINE_MODE_LINK, DEVLINK_ESWITCH_INLINE_MODE_NETWORK, DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT, }; enum devlink_eswitch_encap_mode { DEVLINK_ESWITCH_ENCAP_MODE_NONE, DEVLINK_ESWITCH_ENCAP_MODE_BASIC, }; enum devlink_port_flavour { DEVLINK_PORT_FLAVOUR_PHYSICAL, /* Any kind of a port physically * facing the user. */ DEVLINK_PORT_FLAVOUR_CPU, /* CPU port */ DEVLINK_PORT_FLAVOUR_DSA, /* Distributed switch architecture * interconnect port. */ DEVLINK_PORT_FLAVOUR_PCI_PF, /* Represents eswitch port for * the PCI PF. It is an internal * port that faces the PCI PF. */ DEVLINK_PORT_FLAVOUR_PCI_VF, /* Represents eswitch port * for the PCI VF. It is an internal * port that faces the PCI VF. */ DEVLINK_PORT_FLAVOUR_VIRTUAL, /* Any virtual port facing the user. */ DEVLINK_PORT_FLAVOUR_UNUSED, /* Port which exists in the switch, but * is not used in any way. */ DEVLINK_PORT_FLAVOUR_PCI_SF, /* Represents eswitch port * for the PCI SF. It is an internal * port that faces the PCI SF. */ }; enum devlink_rate_type { DEVLINK_RATE_TYPE_LEAF, DEVLINK_RATE_TYPE_NODE, }; enum devlink_param_cmode { DEVLINK_PARAM_CMODE_RUNTIME, DEVLINK_PARAM_CMODE_DRIVERINIT, DEVLINK_PARAM_CMODE_PERMANENT, /* Add new configuration modes above */ __DEVLINK_PARAM_CMODE_MAX, DEVLINK_PARAM_CMODE_MAX = __DEVLINK_PARAM_CMODE_MAX - 1 }; enum devlink_param_fw_load_policy_value { DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_DRIVER, DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_FLASH, DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_DISK, DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_UNKNOWN, }; enum devlink_param_reset_dev_on_drv_probe_value { DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_UNKNOWN, DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_ALWAYS, DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_NEVER, DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_DISK, }; enum { DEVLINK_ATTR_STATS_RX_PACKETS, /* u64 */ DEVLINK_ATTR_STATS_RX_BYTES, /* u64 */ DEVLINK_ATTR_STATS_RX_DROPPED, /* u64 */ __DEVLINK_ATTR_STATS_MAX, DEVLINK_ATTR_STATS_MAX = __DEVLINK_ATTR_STATS_MAX - 1 }; /* Specify what sections of a flash component can be overwritten when * performing an update. Overwriting of firmware binary sections is always * implicitly assumed to be allowed. * * Each section must be documented in * Documentation/networking/devlink/devlink-flash.rst * */ enum { DEVLINK_FLASH_OVERWRITE_SETTINGS_BIT, DEVLINK_FLASH_OVERWRITE_IDENTIFIERS_BIT, __DEVLINK_FLASH_OVERWRITE_MAX_BIT, DEVLINK_FLASH_OVERWRITE_MAX_BIT = __DEVLINK_FLASH_OVERWRITE_MAX_BIT - 1 }; #define DEVLINK_FLASH_OVERWRITE_SETTINGS _BITUL(DEVLINK_FLASH_OVERWRITE_SETTINGS_BIT) #define DEVLINK_FLASH_OVERWRITE_IDENTIFIERS _BITUL(DEVLINK_FLASH_OVERWRITE_IDENTIFIERS_BIT) #define DEVLINK_SUPPORTED_FLASH_OVERWRITE_SECTIONS \ (_BITUL(__DEVLINK_FLASH_OVERWRITE_MAX_BIT) - 1) enum devlink_attr_selftest_id { DEVLINK_ATTR_SELFTEST_ID_UNSPEC, DEVLINK_ATTR_SELFTEST_ID_FLASH, /* flag */ __DEVLINK_ATTR_SELFTEST_ID_MAX, DEVLINK_ATTR_SELFTEST_ID_MAX = __DEVLINK_ATTR_SELFTEST_ID_MAX - 1 }; enum devlink_selftest_status { DEVLINK_SELFTEST_STATUS_SKIP, DEVLINK_SELFTEST_STATUS_PASS, DEVLINK_SELFTEST_STATUS_FAIL }; enum devlink_attr_selftest_result { DEVLINK_ATTR_SELFTEST_RESULT_UNSPEC, DEVLINK_ATTR_SELFTEST_RESULT, /* nested */ DEVLINK_ATTR_SELFTEST_RESULT_ID, /* u32, enum devlink_attr_selftest_id */ DEVLINK_ATTR_SELFTEST_RESULT_STATUS, /* u8, enum devlink_selftest_status */ __DEVLINK_ATTR_SELFTEST_RESULT_MAX, DEVLINK_ATTR_SELFTEST_RESULT_MAX = __DEVLINK_ATTR_SELFTEST_RESULT_MAX - 1 }; /** * enum devlink_trap_action - Packet trap action. * @DEVLINK_TRAP_ACTION_DROP: Packet is dropped by the device and a copy is not * sent to the CPU. * @DEVLINK_TRAP_ACTION_TRAP: The sole copy of the packet is sent to the CPU. * @DEVLINK_TRAP_ACTION_MIRROR: Packet is forwarded by the device and a copy is * sent to the CPU. */ enum devlink_trap_action { DEVLINK_TRAP_ACTION_DROP, DEVLINK_TRAP_ACTION_TRAP, DEVLINK_TRAP_ACTION_MIRROR, }; /** * enum devlink_trap_type - Packet trap type. * @DEVLINK_TRAP_TYPE_DROP: Trap reason is a drop. Trapped packets are only * processed by devlink and not injected to the * kernel's Rx path. * @DEVLINK_TRAP_TYPE_EXCEPTION: Trap reason is an exception. Packet was not * forwarded as intended due to an exception * (e.g., missing neighbour entry) and trapped to * control plane for resolution. Trapped packets * are processed by devlink and injected to * the kernel's Rx path. * @DEVLINK_TRAP_TYPE_CONTROL: Packet was trapped because it is required for * the correct functioning of the control plane. * For example, an ARP request packet. Trapped * packets are injected to the kernel's Rx path, * but not reported to drop monitor. */ enum devlink_trap_type { DEVLINK_TRAP_TYPE_DROP, DEVLINK_TRAP_TYPE_EXCEPTION, DEVLINK_TRAP_TYPE_CONTROL, }; enum { /* Trap can report input port as metadata */ DEVLINK_ATTR_TRAP_METADATA_TYPE_IN_PORT, /* Trap can report flow action cookie as metadata */ DEVLINK_ATTR_TRAP_METADATA_TYPE_FA_COOKIE, }; enum devlink_reload_action { DEVLINK_RELOAD_ACTION_UNSPEC, DEVLINK_RELOAD_ACTION_DRIVER_REINIT, /* Driver entities re-instantiation */ DEVLINK_RELOAD_ACTION_FW_ACTIVATE, /* FW activate */ /* Add new reload actions above */ __DEVLINK_RELOAD_ACTION_MAX, DEVLINK_RELOAD_ACTION_MAX = __DEVLINK_RELOAD_ACTION_MAX - 1 }; enum devlink_reload_limit { DEVLINK_RELOAD_LIMIT_UNSPEC, /* unspecified, no constraints */ DEVLINK_RELOAD_LIMIT_NO_RESET, /* No reset allowed, no down time allowed, * no link flap and no configuration is lost. */ /* Add new reload limit above */ __DEVLINK_RELOAD_LIMIT_MAX, DEVLINK_RELOAD_LIMIT_MAX = __DEVLINK_RELOAD_LIMIT_MAX - 1 }; #define DEVLINK_RELOAD_LIMITS_VALID_MASK (_BITUL(__DEVLINK_RELOAD_LIMIT_MAX) - 1) enum devlink_attr { /* don't change the order or add anything between, this is ABI! */ DEVLINK_ATTR_UNSPEC, /* bus name + dev name together are a handle for devlink entity */ DEVLINK_ATTR_BUS_NAME, /* string */ DEVLINK_ATTR_DEV_NAME, /* string */ DEVLINK_ATTR_PORT_INDEX, /* u32 */ DEVLINK_ATTR_PORT_TYPE, /* u16 */ DEVLINK_ATTR_PORT_DESIRED_TYPE, /* u16 */ DEVLINK_ATTR_PORT_NETDEV_IFINDEX, /* u32 */ DEVLINK_ATTR_PORT_NETDEV_NAME, /* string */ DEVLINK_ATTR_PORT_IBDEV_NAME, /* string */ DEVLINK_ATTR_PORT_SPLIT_COUNT, /* u32 */ DEVLINK_ATTR_PORT_SPLIT_GROUP, /* u32 */ DEVLINK_ATTR_SB_INDEX, /* u32 */ DEVLINK_ATTR_SB_SIZE, /* u32 */ DEVLINK_ATTR_SB_INGRESS_POOL_COUNT, /* u16 */ DEVLINK_ATTR_SB_EGRESS_POOL_COUNT, /* u16 */ DEVLINK_ATTR_SB_INGRESS_TC_COUNT, /* u16 */ DEVLINK_ATTR_SB_EGRESS_TC_COUNT, /* u16 */ DEVLINK_ATTR_SB_POOL_INDEX, /* u16 */ DEVLINK_ATTR_SB_POOL_TYPE, /* u8 */ DEVLINK_ATTR_SB_POOL_SIZE, /* u32 */ DEVLINK_ATTR_SB_POOL_THRESHOLD_TYPE, /* u8 */ DEVLINK_ATTR_SB_THRESHOLD, /* u32 */ DEVLINK_ATTR_SB_TC_INDEX, /* u16 */ DEVLINK_ATTR_SB_OCC_CUR, /* u32 */ DEVLINK_ATTR_SB_OCC_MAX, /* u32 */ DEVLINK_ATTR_ESWITCH_MODE, /* u16 */ DEVLINK_ATTR_ESWITCH_INLINE_MODE, /* u8 */ DEVLINK_ATTR_DPIPE_TABLES, /* nested */ DEVLINK_ATTR_DPIPE_TABLE, /* nested */ DEVLINK_ATTR_DPIPE_TABLE_NAME, /* string */ DEVLINK_ATTR_DPIPE_TABLE_SIZE, /* u64 */ DEVLINK_ATTR_DPIPE_TABLE_MATCHES, /* nested */ DEVLINK_ATTR_DPIPE_TABLE_ACTIONS, /* nested */ DEVLINK_ATTR_DPIPE_TABLE_COUNTERS_ENABLED, /* u8 */ DEVLINK_ATTR_DPIPE_ENTRIES, /* nested */ DEVLINK_ATTR_DPIPE_ENTRY, /* nested */ DEVLINK_ATTR_DPIPE_ENTRY_INDEX, /* u64 */ DEVLINK_ATTR_DPIPE_ENTRY_MATCH_VALUES, /* nested */ DEVLINK_ATTR_DPIPE_ENTRY_ACTION_VALUES, /* nested */ DEVLINK_ATTR_DPIPE_ENTRY_COUNTER, /* u64 */ DEVLINK_ATTR_DPIPE_MATCH, /* nested */ DEVLINK_ATTR_DPIPE_MATCH_VALUE, /* nested */ DEVLINK_ATTR_DPIPE_MATCH_TYPE, /* u32 */ DEVLINK_ATTR_DPIPE_ACTION, /* nested */ DEVLINK_ATTR_DPIPE_ACTION_VALUE, /* nested */ DEVLINK_ATTR_DPIPE_ACTION_TYPE, /* u32 */ DEVLINK_ATTR_DPIPE_VALUE, DEVLINK_ATTR_DPIPE_VALUE_MASK, DEVLINK_ATTR_DPIPE_VALUE_MAPPING, /* u32 */ DEVLINK_ATTR_DPIPE_HEADERS, /* nested */ DEVLINK_ATTR_DPIPE_HEADER, /* nested */ DEVLINK_ATTR_DPIPE_HEADER_NAME, /* string */ DEVLINK_ATTR_DPIPE_HEADER_ID, /* u32 */ DEVLINK_ATTR_DPIPE_HEADER_FIELDS, /* nested */ DEVLINK_ATTR_DPIPE_HEADER_GLOBAL, /* u8 */ DEVLINK_ATTR_DPIPE_HEADER_INDEX, /* u32 */ DEVLINK_ATTR_DPIPE_FIELD, /* nested */ DEVLINK_ATTR_DPIPE_FIELD_NAME, /* string */ DEVLINK_ATTR_DPIPE_FIELD_ID, /* u32 */ DEVLINK_ATTR_DPIPE_FIELD_BITWIDTH, /* u32 */ DEVLINK_ATTR_DPIPE_FIELD_MAPPING_TYPE, /* u32 */ DEVLINK_ATTR_PAD, DEVLINK_ATTR_ESWITCH_ENCAP_MODE, /* u8 */ DEVLINK_ATTR_RESOURCE_LIST, /* nested */ DEVLINK_ATTR_RESOURCE, /* nested */ DEVLINK_ATTR_RESOURCE_NAME, /* string */ DEVLINK_ATTR_RESOURCE_ID, /* u64 */ DEVLINK_ATTR_RESOURCE_SIZE, /* u64 */ DEVLINK_ATTR_RESOURCE_SIZE_NEW, /* u64 */ DEVLINK_ATTR_RESOURCE_SIZE_VALID, /* u8 */ DEVLINK_ATTR_RESOURCE_SIZE_MIN, /* u64 */ DEVLINK_ATTR_RESOURCE_SIZE_MAX, /* u64 */ DEVLINK_ATTR_RESOURCE_SIZE_GRAN, /* u64 */ DEVLINK_ATTR_RESOURCE_UNIT, /* u8 */ DEVLINK_ATTR_RESOURCE_OCC, /* u64 */ DEVLINK_ATTR_DPIPE_TABLE_RESOURCE_ID, /* u64 */ DEVLINK_ATTR_DPIPE_TABLE_RESOURCE_UNITS,/* u64 */ DEVLINK_ATTR_PORT_FLAVOUR, /* u16 */ DEVLINK_ATTR_PORT_NUMBER, /* u32 */ DEVLINK_ATTR_PORT_SPLIT_SUBPORT_NUMBER, /* u32 */ DEVLINK_ATTR_PARAM, /* nested */ DEVLINK_ATTR_PARAM_NAME, /* string */ DEVLINK_ATTR_PARAM_GENERIC, /* flag */ DEVLINK_ATTR_PARAM_TYPE, /* u8 */ DEVLINK_ATTR_PARAM_VALUES_LIST, /* nested */ DEVLINK_ATTR_PARAM_VALUE, /* nested */ DEVLINK_ATTR_PARAM_VALUE_DATA, /* dynamic */ DEVLINK_ATTR_PARAM_VALUE_CMODE, /* u8 */ DEVLINK_ATTR_REGION_NAME, /* string */ DEVLINK_ATTR_REGION_SIZE, /* u64 */ DEVLINK_ATTR_REGION_SNAPSHOTS, /* nested */ DEVLINK_ATTR_REGION_SNAPSHOT, /* nested */ DEVLINK_ATTR_REGION_SNAPSHOT_ID, /* u32 */ DEVLINK_ATTR_REGION_CHUNKS, /* nested */ DEVLINK_ATTR_REGION_CHUNK, /* nested */ DEVLINK_ATTR_REGION_CHUNK_DATA, /* binary */ DEVLINK_ATTR_REGION_CHUNK_ADDR, /* u64 */ DEVLINK_ATTR_REGION_CHUNK_LEN, /* u64 */ DEVLINK_ATTR_INFO_DRIVER_NAME, /* string */ DEVLINK_ATTR_INFO_SERIAL_NUMBER, /* string */ DEVLINK_ATTR_INFO_VERSION_FIXED, /* nested */ DEVLINK_ATTR_INFO_VERSION_RUNNING, /* nested */ DEVLINK_ATTR_INFO_VERSION_STORED, /* nested */ DEVLINK_ATTR_INFO_VERSION_NAME, /* string */ DEVLINK_ATTR_INFO_VERSION_VALUE, /* string */ DEVLINK_ATTR_SB_POOL_CELL_SIZE, /* u32 */ DEVLINK_ATTR_FMSG, /* nested */ DEVLINK_ATTR_FMSG_OBJ_NEST_START, /* flag */ DEVLINK_ATTR_FMSG_PAIR_NEST_START, /* flag */ DEVLINK_ATTR_FMSG_ARR_NEST_START, /* flag */ DEVLINK_ATTR_FMSG_NEST_END, /* flag */ DEVLINK_ATTR_FMSG_OBJ_NAME, /* string */ DEVLINK_ATTR_FMSG_OBJ_VALUE_TYPE, /* u8 */ DEVLINK_ATTR_FMSG_OBJ_VALUE_DATA, /* dynamic */ DEVLINK_ATTR_HEALTH_REPORTER, /* nested */ DEVLINK_ATTR_HEALTH_REPORTER_NAME, /* string */ DEVLINK_ATTR_HEALTH_REPORTER_STATE, /* u8 */ DEVLINK_ATTR_HEALTH_REPORTER_ERR_COUNT, /* u64 */ DEVLINK_ATTR_HEALTH_REPORTER_RECOVER_COUNT, /* u64 */ DEVLINK_ATTR_HEALTH_REPORTER_DUMP_TS, /* u64 */ DEVLINK_ATTR_HEALTH_REPORTER_GRACEFUL_PERIOD, /* u64 */ DEVLINK_ATTR_HEALTH_REPORTER_AUTO_RECOVER, /* u8 */ DEVLINK_ATTR_FLASH_UPDATE_FILE_NAME, /* string */ DEVLINK_ATTR_FLASH_UPDATE_COMPONENT, /* string */ DEVLINK_ATTR_FLASH_UPDATE_STATUS_MSG, /* string */ DEVLINK_ATTR_FLASH_UPDATE_STATUS_DONE, /* u64 */ DEVLINK_ATTR_FLASH_UPDATE_STATUS_TOTAL, /* u64 */ DEVLINK_ATTR_PORT_PCI_PF_NUMBER, /* u16 */ DEVLINK_ATTR_PORT_PCI_VF_NUMBER, /* u16 */ DEVLINK_ATTR_STATS, /* nested */ DEVLINK_ATTR_TRAP_NAME, /* string */ /* enum devlink_trap_action */ DEVLINK_ATTR_TRAP_ACTION, /* u8 */ /* enum devlink_trap_type */ DEVLINK_ATTR_TRAP_TYPE, /* u8 */ DEVLINK_ATTR_TRAP_GENERIC, /* flag */ DEVLINK_ATTR_TRAP_METADATA, /* nested */ DEVLINK_ATTR_TRAP_GROUP_NAME, /* string */ DEVLINK_ATTR_RELOAD_FAILED, /* u8 0 or 1 */ DEVLINK_ATTR_HEALTH_REPORTER_DUMP_TS_NS, /* u64 */ DEVLINK_ATTR_NETNS_FD, /* u32 */ DEVLINK_ATTR_NETNS_PID, /* u32 */ DEVLINK_ATTR_NETNS_ID, /* u32 */ DEVLINK_ATTR_HEALTH_REPORTER_AUTO_DUMP, /* u8 */ DEVLINK_ATTR_TRAP_POLICER_ID, /* u32 */ DEVLINK_ATTR_TRAP_POLICER_RATE, /* u64 */ DEVLINK_ATTR_TRAP_POLICER_BURST, /* u64 */ DEVLINK_ATTR_PORT_FUNCTION, /* nested */ DEVLINK_ATTR_INFO_BOARD_SERIAL_NUMBER, /* string */ DEVLINK_ATTR_PORT_LANES, /* u32 */ DEVLINK_ATTR_PORT_SPLITTABLE, /* u8 */ DEVLINK_ATTR_PORT_EXTERNAL, /* u8 */ DEVLINK_ATTR_PORT_CONTROLLER_NUMBER, /* u32 */ DEVLINK_ATTR_FLASH_UPDATE_STATUS_TIMEOUT, /* u64 */ DEVLINK_ATTR_FLASH_UPDATE_OVERWRITE_MASK, /* bitfield32 */ DEVLINK_ATTR_RELOAD_ACTION, /* u8 */ DEVLINK_ATTR_RELOAD_ACTIONS_PERFORMED, /* bitfield32 */ DEVLINK_ATTR_RELOAD_LIMITS, /* bitfield32 */ DEVLINK_ATTR_DEV_STATS, /* nested */ DEVLINK_ATTR_RELOAD_STATS, /* nested */ DEVLINK_ATTR_RELOAD_STATS_ENTRY, /* nested */ DEVLINK_ATTR_RELOAD_STATS_LIMIT, /* u8 */ DEVLINK_ATTR_RELOAD_STATS_VALUE, /* u32 */ DEVLINK_ATTR_REMOTE_RELOAD_STATS, /* nested */ DEVLINK_ATTR_RELOAD_ACTION_INFO, /* nested */ DEVLINK_ATTR_RELOAD_ACTION_STATS, /* nested */ DEVLINK_ATTR_PORT_PCI_SF_NUMBER, /* u32 */ DEVLINK_ATTR_RATE_TYPE, /* u16 */ DEVLINK_ATTR_RATE_TX_SHARE, /* u64 */ DEVLINK_ATTR_RATE_TX_MAX, /* u64 */ DEVLINK_ATTR_RATE_NODE_NAME, /* string */ DEVLINK_ATTR_RATE_PARENT_NODE_NAME, /* string */ DEVLINK_ATTR_REGION_MAX_SNAPSHOTS, /* u32 */ __RH_RESERVED_DEVLINK_ATTR_LINECARD_INDEX, /* u32 */ __RH_RESERVED_DEVLINK_ATTR_LINECARD_STATE, /* u8 */ __RH_RESERVED_DEVLINK_ATTR_LINECARD_TYPE, /* string */ __RH_RESERVED_DEVLINK_ATTR_LINECARD_SUPPORTED_TYPES, /* nested */ __RH_RESERVED_DEVLINK_ATTR_NESTED_DEVLINK, /* nested */ DEVLINK_ATTR_SELFTESTS, /* nested */ /* add new attributes above here, update the policy in devlink.c */ __DEVLINK_ATTR_MAX, DEVLINK_ATTR_MAX = __DEVLINK_ATTR_MAX - 1 }; /* Mapping between internal resource described by the field and system * structure */ enum devlink_dpipe_field_mapping_type { DEVLINK_DPIPE_FIELD_MAPPING_TYPE_NONE, DEVLINK_DPIPE_FIELD_MAPPING_TYPE_IFINDEX, }; /* Match type - specify the type of the match */ enum devlink_dpipe_match_type { DEVLINK_DPIPE_MATCH_TYPE_FIELD_EXACT, }; /* Action type - specify the action type */ enum devlink_dpipe_action_type { DEVLINK_DPIPE_ACTION_TYPE_FIELD_MODIFY, }; enum devlink_dpipe_field_ethernet_id { DEVLINK_DPIPE_FIELD_ETHERNET_DST_MAC, }; enum devlink_dpipe_field_ipv4_id { DEVLINK_DPIPE_FIELD_IPV4_DST_IP, }; enum devlink_dpipe_field_ipv6_id { DEVLINK_DPIPE_FIELD_IPV6_DST_IP, }; enum devlink_dpipe_header_id { DEVLINK_DPIPE_HEADER_ETHERNET, DEVLINK_DPIPE_HEADER_IPV4, DEVLINK_DPIPE_HEADER_IPV6, }; enum devlink_resource_unit { DEVLINK_RESOURCE_UNIT_ENTRY, }; enum devlink_port_function_attr { DEVLINK_PORT_FUNCTION_ATTR_UNSPEC, DEVLINK_PORT_FUNCTION_ATTR_HW_ADDR, /* binary */ DEVLINK_PORT_FN_ATTR_STATE, /* u8 */ DEVLINK_PORT_FN_ATTR_OPSTATE, /* u8 */ __DEVLINK_PORT_FUNCTION_ATTR_MAX, DEVLINK_PORT_FUNCTION_ATTR_MAX = __DEVLINK_PORT_FUNCTION_ATTR_MAX - 1 }; enum devlink_port_fn_state { DEVLINK_PORT_FN_STATE_INACTIVE, DEVLINK_PORT_FN_STATE_ACTIVE, }; /** * enum devlink_port_fn_opstate - indicates operational state of the function * @DEVLINK_PORT_FN_OPSTATE_ATTACHED: Driver is attached to the function. * For graceful tear down of the function, after inactivation of the * function, user should wait for operational state to turn DETACHED. * @DEVLINK_PORT_FN_OPSTATE_DETACHED: Driver is detached from the function. * It is safe to delete the port. */ enum devlink_port_fn_opstate { DEVLINK_PORT_FN_OPSTATE_DETACHED, DEVLINK_PORT_FN_OPSTATE_ATTACHED, }; #endif /* _LINUX_DEVLINK_H_ */ linux/vdpa.h000064400000002615151027430560007015 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * vdpa device management interface * Copyright (c) 2020 Mellanox Technologies Ltd. All rights reserved. */ #ifndef _LINUX_VDPA_H_ #define _LINUX_VDPA_H_ #define VDPA_GENL_NAME "vdpa" #define VDPA_GENL_VERSION 0x1 enum vdpa_command { VDPA_CMD_UNSPEC, VDPA_CMD_MGMTDEV_NEW, VDPA_CMD_MGMTDEV_GET, /* can dump */ VDPA_CMD_DEV_NEW, VDPA_CMD_DEV_DEL, VDPA_CMD_DEV_GET, /* can dump */ VDPA_CMD_DEV_CONFIG_GET, /* can dump */ }; enum vdpa_attr { VDPA_ATTR_UNSPEC, /* Pad attribute for 64b alignment */ VDPA_ATTR_PAD = VDPA_ATTR_UNSPEC, /* bus name (optional) + dev name together make the parent device handle */ VDPA_ATTR_MGMTDEV_BUS_NAME, /* string */ VDPA_ATTR_MGMTDEV_DEV_NAME, /* string */ VDPA_ATTR_MGMTDEV_SUPPORTED_CLASSES, /* u64 */ VDPA_ATTR_DEV_NAME, /* string */ VDPA_ATTR_DEV_ID, /* u32 */ VDPA_ATTR_DEV_VENDOR_ID, /* u32 */ VDPA_ATTR_DEV_MAX_VQS, /* u32 */ VDPA_ATTR_DEV_MAX_VQ_SIZE, /* u16 */ VDPA_ATTR_DEV_MIN_VQ_SIZE, /* u16 */ VDPA_ATTR_DEV_NET_CFG_MACADDR, /* binary */ VDPA_ATTR_DEV_NET_STATUS, /* u8 */ VDPA_ATTR_DEV_NET_CFG_MAX_VQP, /* u16 */ VDPA_ATTR_DEV_NET_CFG_MTU, /* u16 */ VDPA_ATTR_DEV_NEGOTIATED_FEATURES, /* u64 */ VDPA_ATTR_DEV_MGMTDEV_MAX_VQS, /* u32 */ VDPA_ATTR_DEV_SUPPORTED_FEATURES, /* u64 */ /* new attributes must be added above here */ VDPA_ATTR_MAX, }; #endif linux/cryptouser.h000064400000006500151027430560010277 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Crypto user configuration API. * * Copyright (C) 2011 secunet Security Networks AG * Copyright (C) 2011 Steffen Klassert * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include /* Netlink configuration messages. */ enum { CRYPTO_MSG_BASE = 0x10, CRYPTO_MSG_NEWALG = 0x10, CRYPTO_MSG_DELALG, CRYPTO_MSG_UPDATEALG, CRYPTO_MSG_GETALG, CRYPTO_MSG_DELRNG, __CRYPTO_MSG_MAX }; #define CRYPTO_MSG_MAX (__CRYPTO_MSG_MAX - 1) #define CRYPTO_NR_MSGTYPES (CRYPTO_MSG_MAX + 1 - CRYPTO_MSG_BASE) #define CRYPTO_MAX_NAME 64 /* Netlink message attributes. */ enum crypto_attr_type_t { CRYPTOCFGA_UNSPEC, CRYPTOCFGA_PRIORITY_VAL, /* __u32 */ CRYPTOCFGA_REPORT_LARVAL, /* struct crypto_report_larval */ CRYPTOCFGA_REPORT_HASH, /* struct crypto_report_hash */ CRYPTOCFGA_REPORT_BLKCIPHER, /* struct crypto_report_blkcipher */ CRYPTOCFGA_REPORT_AEAD, /* struct crypto_report_aead */ CRYPTOCFGA_REPORT_COMPRESS, /* struct crypto_report_comp */ CRYPTOCFGA_REPORT_RNG, /* struct crypto_report_rng */ CRYPTOCFGA_REPORT_CIPHER, /* struct crypto_report_cipher */ CRYPTOCFGA_REPORT_AKCIPHER, /* struct crypto_report_akcipher */ CRYPTOCFGA_REPORT_KPP, /* struct crypto_report_kpp */ CRYPTOCFGA_REPORT_ACOMP, /* struct crypto_report_acomp */ __CRYPTOCFGA_MAX #define CRYPTOCFGA_MAX (__CRYPTOCFGA_MAX - 1) }; struct crypto_user_alg { char cru_name[CRYPTO_MAX_NAME]; char cru_driver_name[CRYPTO_MAX_NAME]; char cru_module_name[CRYPTO_MAX_NAME]; __u32 cru_type; __u32 cru_mask; __u32 cru_refcnt; __u32 cru_flags; }; struct crypto_report_larval { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_hash { char type[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int digestsize; }; struct crypto_report_cipher { char type[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int min_keysize; unsigned int max_keysize; }; struct crypto_report_blkcipher { char type[CRYPTO_MAX_NAME]; char geniv[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int min_keysize; unsigned int max_keysize; unsigned int ivsize; }; struct crypto_report_aead { char type[CRYPTO_MAX_NAME]; char geniv[CRYPTO_MAX_NAME]; unsigned int blocksize; unsigned int maxauthsize; unsigned int ivsize; }; struct crypto_report_comp { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_rng { char type[CRYPTO_MAX_NAME]; unsigned int seedsize; }; struct crypto_report_akcipher { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_kpp { char type[CRYPTO_MAX_NAME]; }; struct crypto_report_acomp { char type[CRYPTO_MAX_NAME]; }; #define CRYPTO_REPORT_MAXSIZE (sizeof(struct crypto_user_alg) + \ sizeof(struct crypto_report_blkcipher)) linux/rpmsg.h000064400000001040151027430560007202 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 2016, Linaro Ltd. */ #ifndef _RPMSG_H_ #define _RPMSG_H_ #include #include /** * struct rpmsg_endpoint_info - endpoint info representation * @name: name of service * @src: local address * @dst: destination address */ struct rpmsg_endpoint_info { char name[32]; __u32 src; __u32 dst; }; #define RPMSG_CREATE_EPT_IOCTL _IOW(0xb5, 0x1, struct rpmsg_endpoint_info) #define RPMSG_DESTROY_EPT_IOCTL _IO(0xb5, 0x2) #endif linux/if_hippi.h000064400000010213151027430560007643 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the HIPPI interface. * * Version: @(#)if_hippi.h 1.0.0 05/26/97 * * Author: Fred N. van Kempen, * Donald Becker, * Alan Cox, * Steve Whitehouse, * Jes Sorensen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_HIPPI_H #define _LINUX_IF_HIPPI_H #include #include /* * HIPPI magic constants. */ #define HIPPI_ALEN 6 /* Bytes in one HIPPI hw-addr */ #define HIPPI_HLEN sizeof(struct hippi_hdr) #define HIPPI_ZLEN 0 /* Min. bytes in frame without FCS */ #define HIPPI_DATA_LEN 65280 /* Max. bytes in payload */ #define HIPPI_FRAME_LEN (HIPPI_DATA_LEN + HIPPI_HLEN) /* Max. bytes in frame without FCS */ /* * Define LLC and SNAP constants. */ #define HIPPI_EXTENDED_SAP 0xAA #define HIPPI_UI_CMD 0x03 /* * Do we need to list some sort of ID's here? */ /* * HIPPI statistics collection data. */ struct hipnet_statistics { int rx_packets; /* total packets received */ int tx_packets; /* total packets transmitted */ int rx_errors; /* bad packets received */ int tx_errors; /* packet transmit problems */ int rx_dropped; /* no space in linux buffers */ int tx_dropped; /* no space available in linux */ /* detailed rx_errors: */ int rx_length_errors; int rx_over_errors; /* receiver ring buff overflow */ int rx_crc_errors; /* recved pkt with crc error */ int rx_frame_errors; /* recv'd frame alignment error */ int rx_fifo_errors; /* recv'r fifo overrun */ int rx_missed_errors; /* receiver missed packet */ /* detailed tx_errors */ int tx_aborted_errors; int tx_carrier_errors; int tx_fifo_errors; int tx_heartbeat_errors; int tx_window_errors; }; struct hippi_fp_hdr { #if 0 __u8 ulp; /* must contain 4 */ #if defined (__BIG_ENDIAN_BITFIELD) __u8 d1_data_present:1; /* must be 1 */ __u8 start_d2_burst_boundary:1; /* must be zero */ __u8 reserved:6; /* must be zero */ #if 0 __u16 reserved1:5; __u16 d1_area_size:8; /* must be 3 */ __u16 d2_offset:3; /* must be zero */ #endif #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 reserved:6; /* must be zero */ __u8 start_d2_burst_boundary:1; /* must be zero */ __u8 d1_data_present:1; /* must be 1 */ #if 0 __u16 d2_offset:3; /* must be zero */ __u16 d1_area_size:8; /* must be 3 */ __u16 reserved1:5; /* must be zero */ #endif #else #error "Please fix " #endif #else __be32 fixed; #endif __be32 d2_size; } __attribute__((packed)); struct hippi_le_hdr { #if defined (__BIG_ENDIAN_BITFIELD) __u8 fc:3; __u8 double_wide:1; __u8 message_type:4; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 message_type:4; __u8 double_wide:1; __u8 fc:3; #endif __u8 dest_switch_addr[3]; #if defined (__BIG_ENDIAN_BITFIELD) __u8 dest_addr_type:4, src_addr_type:4; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 src_addr_type:4, dest_addr_type:4; #endif __u8 src_switch_addr[3]; __u16 reserved; __u8 daddr[HIPPI_ALEN]; __u16 locally_administered; __u8 saddr[HIPPI_ALEN]; } __attribute__((packed)); #define HIPPI_OUI_LEN 3 /* * Looks like the dsap and ssap fields have been swapped by mistake in * RFC 2067 "IP over HIPPI". */ struct hippi_snap_hdr { __u8 dsap; /* always 0xAA */ __u8 ssap; /* always 0xAA */ __u8 ctrl; /* always 0x03 */ __u8 oui[HIPPI_OUI_LEN]; /* organizational universal id (zero)*/ __be16 ethertype; /* packet type ID field */ } __attribute__((packed)); struct hippi_hdr { struct hippi_fp_hdr fp; struct hippi_le_hdr le; struct hippi_snap_hdr snap; } __attribute__((packed)); #endif /* _LINUX_IF_HIPPI_H */ linux/tc_act/tc_skbmod.h000064400000001113151027430560011255 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2016, Jamal Hadi Salim */ #ifndef __LINUX_TC_SKBMOD_H #define __LINUX_TC_SKBMOD_H #include #define SKBMOD_F_DMAC 0x1 #define SKBMOD_F_SMAC 0x2 #define SKBMOD_F_ETYPE 0x4 #define SKBMOD_F_SWAPMAC 0x8 #define SKBMOD_F_ECN 0x10 struct tc_skbmod { tc_gen; __u64 flags; }; enum { TCA_SKBMOD_UNSPEC, TCA_SKBMOD_TM, TCA_SKBMOD_PARMS, TCA_SKBMOD_DMAC, TCA_SKBMOD_SMAC, TCA_SKBMOD_ETYPE, TCA_SKBMOD_PAD, __TCA_SKBMOD_MAX }; #define TCA_SKBMOD_MAX (__TCA_SKBMOD_MAX - 1) #endif linux/tc_act/tc_ipt.h000064400000000637151027430560010604 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_IPT_H #define __LINUX_TC_IPT_H #include enum { TCA_IPT_UNSPEC, TCA_IPT_TABLE, TCA_IPT_HOOK, TCA_IPT_INDEX, TCA_IPT_CNT, TCA_IPT_TM, TCA_IPT_TARG, TCA_IPT_PAD, __TCA_IPT_MAX }; #define TCA_IPT_MAX (__TCA_IPT_MAX - 1) #endif linux/tc_act/tc_mpls.h000064400000002000151027430560010745 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (C) 2019 Netronome Systems, Inc. */ #ifndef __LINUX_TC_MPLS_H #define __LINUX_TC_MPLS_H #include #define TCA_MPLS_ACT_POP 1 #define TCA_MPLS_ACT_PUSH 2 #define TCA_MPLS_ACT_MODIFY 3 #define TCA_MPLS_ACT_DEC_TTL 4 #define TCA_MPLS_ACT_MAC_PUSH 5 struct tc_mpls { tc_gen; /* generic TC action fields. */ int m_action; /* action of type TCA_MPLS_ACT_*. */ }; enum { TCA_MPLS_UNSPEC, TCA_MPLS_TM, /* struct tcf_t; time values associated with action. */ TCA_MPLS_PARMS, /* struct tc_mpls; action type and general TC fields. */ TCA_MPLS_PAD, TCA_MPLS_PROTO, /* be16; eth_type of pushed or next (for pop) header. */ TCA_MPLS_LABEL, /* u32; MPLS label. Lower 20 bits are used. */ TCA_MPLS_TC, /* u8; MPLS TC field. Lower 3 bits are used. */ TCA_MPLS_TTL, /* u8; MPLS TTL field. Must not be 0. */ TCA_MPLS_BOS, /* u8; MPLS BOS field. Either 1 or 0. */ __TCA_MPLS_MAX, }; #define TCA_MPLS_MAX (__TCA_MPLS_MAX - 1) #endif linux/tc_act/tc_nat.h000064400000000650151027430560010565 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_NAT_H #define __LINUX_TC_NAT_H #include #include enum { TCA_NAT_UNSPEC, TCA_NAT_PARMS, TCA_NAT_TM, TCA_NAT_PAD, __TCA_NAT_MAX }; #define TCA_NAT_MAX (__TCA_NAT_MAX - 1) #define TCA_NAT_FLAG_EGRESS 1 struct tc_nat { tc_gen; __be32 old_addr; __be32 new_addr; __be32 mask; __u32 flags; }; #endif linux/tc_act/tc_mirred.h000064400000001330151027430560011261 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_MIR_H #define __LINUX_TC_MIR_H #include #include #define TCA_EGRESS_REDIR 1 /* packet redirect to EGRESS*/ #define TCA_EGRESS_MIRROR 2 /* mirror packet to EGRESS */ #define TCA_INGRESS_REDIR 3 /* packet redirect to INGRESS*/ #define TCA_INGRESS_MIRROR 4 /* mirror packet to INGRESS */ struct tc_mirred { tc_gen; int eaction; /* one of IN/EGRESS_MIRROR/REDIR */ __u32 ifindex; /* ifindex of egress port */ }; enum { TCA_MIRRED_UNSPEC, TCA_MIRRED_TM, TCA_MIRRED_PARMS, TCA_MIRRED_PAD, __TCA_MIRRED_MAX }; #define TCA_MIRRED_MAX (__TCA_MIRRED_MAX - 1) #endif linux/tc_act/tc_csum.h000064400000001204151027430560010746 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_CSUM_H #define __LINUX_TC_CSUM_H #include #include enum { TCA_CSUM_UNSPEC, TCA_CSUM_PARMS, TCA_CSUM_TM, TCA_CSUM_PAD, __TCA_CSUM_MAX }; #define TCA_CSUM_MAX (__TCA_CSUM_MAX - 1) enum { TCA_CSUM_UPDATE_FLAG_IPV4HDR = 1, TCA_CSUM_UPDATE_FLAG_ICMP = 2, TCA_CSUM_UPDATE_FLAG_IGMP = 4, TCA_CSUM_UPDATE_FLAG_TCP = 8, TCA_CSUM_UPDATE_FLAG_UDP = 16, TCA_CSUM_UPDATE_FLAG_UDPLITE = 32, TCA_CSUM_UPDATE_FLAG_SCTP = 64, }; struct tc_csum { tc_gen; __u32 update_flags; }; #endif /* __LINUX_TC_CSUM_H */ linux/tc_act/tc_tunnel_key.h000064400000004656151027430560012172 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2016, Amir Vadai * Copyright (c) 2016, Mellanox Technologies. All rights reserved. */ #ifndef __LINUX_TC_TUNNEL_KEY_H #define __LINUX_TC_TUNNEL_KEY_H #include #define TCA_TUNNEL_KEY_ACT_SET 1 #define TCA_TUNNEL_KEY_ACT_RELEASE 2 struct tc_tunnel_key { tc_gen; int t_action; }; enum { TCA_TUNNEL_KEY_UNSPEC, TCA_TUNNEL_KEY_TM, TCA_TUNNEL_KEY_PARMS, TCA_TUNNEL_KEY_ENC_IPV4_SRC, /* be32 */ TCA_TUNNEL_KEY_ENC_IPV4_DST, /* be32 */ TCA_TUNNEL_KEY_ENC_IPV6_SRC, /* struct in6_addr */ TCA_TUNNEL_KEY_ENC_IPV6_DST, /* struct in6_addr */ TCA_TUNNEL_KEY_ENC_KEY_ID, /* be64 */ TCA_TUNNEL_KEY_PAD, TCA_TUNNEL_KEY_ENC_DST_PORT, /* be16 */ TCA_TUNNEL_KEY_NO_CSUM, /* u8 */ TCA_TUNNEL_KEY_ENC_OPTS, /* Nested TCA_TUNNEL_KEY_ENC_OPTS_ * attributes */ TCA_TUNNEL_KEY_ENC_TOS, /* u8 */ TCA_TUNNEL_KEY_ENC_TTL, /* u8 */ TCA_TUNNEL_KEY_NO_FRAG, /* flag */ __TCA_TUNNEL_KEY_MAX, }; #define TCA_TUNNEL_KEY_MAX (__TCA_TUNNEL_KEY_MAX - 1) enum { TCA_TUNNEL_KEY_ENC_OPTS_UNSPEC, TCA_TUNNEL_KEY_ENC_OPTS_GENEVE, /* Nested * TCA_TUNNEL_KEY_ENC_OPTS_ * attributes */ TCA_TUNNEL_KEY_ENC_OPTS_VXLAN, /* Nested * TCA_TUNNEL_KEY_ENC_OPTS_ * attributes */ TCA_TUNNEL_KEY_ENC_OPTS_ERSPAN, /* Nested * TCA_TUNNEL_KEY_ENC_OPTS_ * attributes */ __TCA_TUNNEL_KEY_ENC_OPTS_MAX, }; #define TCA_TUNNEL_KEY_ENC_OPTS_MAX (__TCA_TUNNEL_KEY_ENC_OPTS_MAX - 1) enum { TCA_TUNNEL_KEY_ENC_OPT_GENEVE_UNSPEC, TCA_TUNNEL_KEY_ENC_OPT_GENEVE_CLASS, /* be16 */ TCA_TUNNEL_KEY_ENC_OPT_GENEVE_TYPE, /* u8 */ TCA_TUNNEL_KEY_ENC_OPT_GENEVE_DATA, /* 4 to 128 bytes */ __TCA_TUNNEL_KEY_ENC_OPT_GENEVE_MAX, }; #define TCA_TUNNEL_KEY_ENC_OPT_GENEVE_MAX \ (__TCA_TUNNEL_KEY_ENC_OPT_GENEVE_MAX - 1) enum { TCA_TUNNEL_KEY_ENC_OPT_VXLAN_UNSPEC, TCA_TUNNEL_KEY_ENC_OPT_VXLAN_GBP, /* u32 */ __TCA_TUNNEL_KEY_ENC_OPT_VXLAN_MAX, }; #define TCA_TUNNEL_KEY_ENC_OPT_VXLAN_MAX \ (__TCA_TUNNEL_KEY_ENC_OPT_VXLAN_MAX - 1) enum { TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_UNSPEC, TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_VER, /* u8 */ TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_INDEX, /* be32 */ TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_DIR, /* u8 */ TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_HWID, /* u8 */ __TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_MAX, }; #define TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_MAX \ (__TCA_TUNNEL_KEY_ENC_OPT_ERSPAN_MAX - 1) #endif linux/tc_act/tc_bpf.h000064400000000775151027430560010562 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2015 Jiri Pirko */ #ifndef __LINUX_TC_BPF_H #define __LINUX_TC_BPF_H #include struct tc_act_bpf { tc_gen; }; enum { TCA_ACT_BPF_UNSPEC, TCA_ACT_BPF_TM, TCA_ACT_BPF_PARMS, TCA_ACT_BPF_OPS_LEN, TCA_ACT_BPF_OPS, TCA_ACT_BPF_FD, TCA_ACT_BPF_NAME, TCA_ACT_BPF_PAD, TCA_ACT_BPF_TAG, TCA_ACT_BPF_ID, __TCA_ACT_BPF_MAX, }; #define TCA_ACT_BPF_MAX (__TCA_ACT_BPF_MAX - 1) #endif linux/tc_act/tc_connmark.h000064400000000606151027430560011614 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_TC_CONNMARK_H #define __UAPI_TC_CONNMARK_H #include #include struct tc_connmark { tc_gen; __u16 zone; }; enum { TCA_CONNMARK_UNSPEC, TCA_CONNMARK_PARMS, TCA_CONNMARK_TM, TCA_CONNMARK_PAD, __TCA_CONNMARK_MAX }; #define TCA_CONNMARK_MAX (__TCA_CONNMARK_MAX - 1) #endif linux/tc_act/tc_sample.h000064400000000710151027430560011261 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_SAMPLE_H #define __LINUX_TC_SAMPLE_H #include #include #include struct tc_sample { tc_gen; }; enum { TCA_SAMPLE_UNSPEC, TCA_SAMPLE_TM, TCA_SAMPLE_PARMS, TCA_SAMPLE_RATE, TCA_SAMPLE_TRUNC_SIZE, TCA_SAMPLE_PSAMPLE_GROUP, TCA_SAMPLE_PAD, __TCA_SAMPLE_MAX }; #define TCA_SAMPLE_MAX (__TCA_SAMPLE_MAX - 1) #endif linux/tc_act/tc_gact.h000064400000001162151027430560010720 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_GACT_H #define __LINUX_TC_GACT_H #include #include struct tc_gact { tc_gen; }; struct tc_gact_p { #define PGACT_NONE 0 #define PGACT_NETRAND 1 #define PGACT_DETERM 2 #define MAX_RAND (PGACT_DETERM + 1 ) __u16 ptype; __u16 pval; int paction; }; enum { TCA_GACT_UNSPEC, TCA_GACT_TM, TCA_GACT_PARMS, TCA_GACT_PROB, TCA_GACT_PAD, __TCA_GACT_MAX }; #define TCA_GACT_MAX (__TCA_GACT_MAX - 1) #endif linux/tc_act/tc_ife.h000064400000001130151027430560010540 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_TC_IFE_H #define __UAPI_TC_IFE_H #include #include #include /* Flag bits for now just encoding/decoding; mutually exclusive */ #define IFE_ENCODE 1 #define IFE_DECODE 0 struct tc_ife { tc_gen; __u16 flags; }; /*XXX: We need to encode the total number of bytes consumed */ enum { TCA_IFE_UNSPEC, TCA_IFE_PARMS, TCA_IFE_TM, TCA_IFE_DMAC, TCA_IFE_SMAC, TCA_IFE_TYPE, TCA_IFE_METALST, TCA_IFE_PAD, __TCA_IFE_MAX }; #define TCA_IFE_MAX (__TCA_IFE_MAX - 1) #endif linux/tc_act/tc_ct.h000064400000001646151027430560010417 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_TC_CT_H #define __UAPI_TC_CT_H #include #include enum { TCA_CT_UNSPEC, TCA_CT_PARMS, TCA_CT_TM, TCA_CT_ACTION, /* u16 */ TCA_CT_ZONE, /* u16 */ TCA_CT_MARK, /* u32 */ TCA_CT_MARK_MASK, /* u32 */ TCA_CT_LABELS, /* u128 */ TCA_CT_LABELS_MASK, /* u128 */ TCA_CT_NAT_IPV4_MIN, /* be32 */ TCA_CT_NAT_IPV4_MAX, /* be32 */ TCA_CT_NAT_IPV6_MIN, /* struct in6_addr */ TCA_CT_NAT_IPV6_MAX, /* struct in6_addr */ TCA_CT_NAT_PORT_MIN, /* be16 */ TCA_CT_NAT_PORT_MAX, /* be16 */ TCA_CT_PAD, __TCA_CT_MAX }; #define TCA_CT_MAX (__TCA_CT_MAX - 1) #define TCA_CT_ACT_COMMIT (1 << 0) #define TCA_CT_ACT_FORCE (1 << 1) #define TCA_CT_ACT_CLEAR (1 << 2) #define TCA_CT_ACT_NAT (1 << 3) #define TCA_CT_ACT_NAT_SRC (1 << 4) #define TCA_CT_ACT_NAT_DST (1 << 5) struct tc_ct { tc_gen; }; #endif /* __UAPI_TC_CT_H */ linux/tc_act/tc_vlan.h000064400000001240151027430560010737 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2014 Jiri Pirko */ #ifndef __LINUX_TC_VLAN_H #define __LINUX_TC_VLAN_H #include #define TCA_VLAN_ACT_POP 1 #define TCA_VLAN_ACT_PUSH 2 #define TCA_VLAN_ACT_MODIFY 3 #define TCA_VLAN_ACT_POP_ETH 4 #define TCA_VLAN_ACT_PUSH_ETH 5 struct tc_vlan { tc_gen; int v_action; }; enum { TCA_VLAN_UNSPEC, TCA_VLAN_TM, TCA_VLAN_PARMS, TCA_VLAN_PUSH_VLAN_ID, TCA_VLAN_PUSH_VLAN_PROTOCOL, TCA_VLAN_PAD, TCA_VLAN_PUSH_VLAN_PRIORITY, TCA_VLAN_PUSH_ETH_DST, TCA_VLAN_PUSH_ETH_SRC, __TCA_VLAN_MAX, }; #define TCA_VLAN_MAX (__TCA_VLAN_MAX - 1) #endif linux/tc_act/tc_gate.h000064400000001546151027430560010730 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* Copyright 2020 NXP */ #ifndef __LINUX_TC_GATE_H #define __LINUX_TC_GATE_H #include struct tc_gate { tc_gen; }; enum { TCA_GATE_ENTRY_UNSPEC, TCA_GATE_ENTRY_INDEX, TCA_GATE_ENTRY_GATE, TCA_GATE_ENTRY_INTERVAL, TCA_GATE_ENTRY_IPV, TCA_GATE_ENTRY_MAX_OCTETS, __TCA_GATE_ENTRY_MAX, }; #define TCA_GATE_ENTRY_MAX (__TCA_GATE_ENTRY_MAX - 1) enum { TCA_GATE_ONE_ENTRY_UNSPEC, TCA_GATE_ONE_ENTRY, __TCA_GATE_ONE_ENTRY_MAX, }; #define TCA_GATE_ONE_ENTRY_MAX (__TCA_GATE_ONE_ENTRY_MAX - 1) enum { TCA_GATE_UNSPEC, TCA_GATE_TM, TCA_GATE_PARMS, TCA_GATE_PAD, TCA_GATE_PRIORITY, TCA_GATE_ENTRY_LIST, TCA_GATE_BASE_TIME, TCA_GATE_CYCLE_TIME, TCA_GATE_CYCLE_TIME_EXT, TCA_GATE_FLAGS, TCA_GATE_CLOCKID, __TCA_GATE_MAX, }; #define TCA_GATE_MAX (__TCA_GATE_MAX - 1) #endif linux/tc_act/tc_pedit.h000064400000002767151027430560011123 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_PED_H #define __LINUX_TC_PED_H #include #include enum { TCA_PEDIT_UNSPEC, TCA_PEDIT_TM, TCA_PEDIT_PARMS, TCA_PEDIT_PAD, TCA_PEDIT_PARMS_EX, TCA_PEDIT_KEYS_EX, TCA_PEDIT_KEY_EX, __TCA_PEDIT_MAX }; #define TCA_PEDIT_MAX (__TCA_PEDIT_MAX - 1) enum { TCA_PEDIT_KEY_EX_HTYPE = 1, TCA_PEDIT_KEY_EX_CMD = 2, __TCA_PEDIT_KEY_EX_MAX }; #define TCA_PEDIT_KEY_EX_MAX (__TCA_PEDIT_KEY_EX_MAX - 1) /* TCA_PEDIT_KEY_EX_HDR_TYPE_NETWROK is a special case for legacy users. It * means no specific header type - offset is relative to the network layer */ enum pedit_header_type { TCA_PEDIT_KEY_EX_HDR_TYPE_NETWORK = 0, TCA_PEDIT_KEY_EX_HDR_TYPE_ETH = 1, TCA_PEDIT_KEY_EX_HDR_TYPE_IP4 = 2, TCA_PEDIT_KEY_EX_HDR_TYPE_IP6 = 3, TCA_PEDIT_KEY_EX_HDR_TYPE_TCP = 4, TCA_PEDIT_KEY_EX_HDR_TYPE_UDP = 5, __PEDIT_HDR_TYPE_MAX, }; #define TCA_PEDIT_HDR_TYPE_MAX (__PEDIT_HDR_TYPE_MAX - 1) enum pedit_cmd { TCA_PEDIT_KEY_EX_CMD_SET = 0, TCA_PEDIT_KEY_EX_CMD_ADD = 1, __PEDIT_CMD_MAX, }; #define TCA_PEDIT_CMD_MAX (__PEDIT_CMD_MAX - 1) struct tc_pedit_key { __u32 mask; /* AND */ __u32 val; /*XOR */ __u32 off; /*offset */ __u32 at; __u32 offmask; __u32 shift; }; struct tc_pedit_sel { tc_gen; unsigned char nkeys; unsigned char flags; struct tc_pedit_key keys[0]; }; #define tc_pedit tc_pedit_sel #endif linux/tc_act/tc_skbedit.h000064400000001520151027430560011425 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 2008, Intel Corporation. * * Author: Alexander Duyck */ #ifndef __LINUX_TC_SKBEDIT_H #define __LINUX_TC_SKBEDIT_H #include #define SKBEDIT_F_PRIORITY 0x1 #define SKBEDIT_F_QUEUE_MAPPING 0x2 #define SKBEDIT_F_MARK 0x4 #define SKBEDIT_F_PTYPE 0x8 #define SKBEDIT_F_MASK 0x10 #define SKBEDIT_F_INHERITDSFIELD 0x20 #define SKBEDIT_F_TXQ_SKBHASH 0x40 struct tc_skbedit { tc_gen; }; enum { TCA_SKBEDIT_UNSPEC, TCA_SKBEDIT_TM, TCA_SKBEDIT_PARMS, TCA_SKBEDIT_PRIORITY, TCA_SKBEDIT_QUEUE_MAPPING, TCA_SKBEDIT_MARK, TCA_SKBEDIT_PAD, TCA_SKBEDIT_PTYPE, TCA_SKBEDIT_MASK, TCA_SKBEDIT_FLAGS, TCA_SKBEDIT_QUEUE_MAPPING_MAX, __TCA_SKBEDIT_MAX }; #define TCA_SKBEDIT_MAX (__TCA_SKBEDIT_MAX - 1) #endif linux/tc_act/tc_ctinfo.h000064400000001054151027430560011264 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_TC_CTINFO_H #define __UAPI_TC_CTINFO_H #include #include struct tc_ctinfo { tc_gen; }; enum { TCA_CTINFO_UNSPEC, TCA_CTINFO_PAD, TCA_CTINFO_TM, TCA_CTINFO_ACT, TCA_CTINFO_ZONE, TCA_CTINFO_PARMS_DSCP_MASK, TCA_CTINFO_PARMS_DSCP_STATEMASK, TCA_CTINFO_PARMS_CPMARK_MASK, TCA_CTINFO_STATS_DSCP_SET, TCA_CTINFO_STATS_DSCP_ERROR, TCA_CTINFO_STATS_CPMARK_SET, __TCA_CTINFO_MAX }; #define TCA_CTINFO_MAX (__TCA_CTINFO_MAX - 1) #endif linux/tc_act/tc_defact.h000064400000000502151027430560011225 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_TC_DEF_H #define __LINUX_TC_DEF_H #include struct tc_defact { tc_gen; }; enum { TCA_DEF_UNSPEC, TCA_DEF_TM, TCA_DEF_PARMS, TCA_DEF_DATA, TCA_DEF_PAD, __TCA_DEF_MAX }; #define TCA_DEF_MAX (__TCA_DEF_MAX - 1) #endif linux/audit.h000064400000047652151027430560007203 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* audit.h -- Auditing support * * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina. * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Written by Rickard E. (Rik) Faith * */ #ifndef _LINUX_AUDIT_H_ #define _LINUX_AUDIT_H_ #include #include /* The netlink messages for the audit system is divided into blocks: * 1000 - 1099 are for commanding the audit system * 1100 - 1199 user space trusted application messages * 1200 - 1299 messages internal to the audit daemon * 1300 - 1399 audit event messages * 1400 - 1499 SE Linux use * 1500 - 1599 kernel LSPP events * 1600 - 1699 kernel crypto events * 1700 - 1799 kernel anomaly records * 1800 - 1899 kernel integrity events * 1900 - 1999 future kernel use * 2000 is for otherwise unclassified kernel audit messages (legacy) * 2001 - 2099 unused (kernel) * 2100 - 2199 user space anomaly records * 2200 - 2299 user space actions taken in response to anomalies * 2300 - 2399 user space generated LSPP events * 2400 - 2499 user space crypto events * 2500 - 2999 future user space (maybe integrity labels and related events) * * Messages from 1000-1199 are bi-directional. 1200-1299 & 2100 - 2999 are * exclusively user space. 1300-2099 is kernel --> user space * communication. */ #define AUDIT_GET 1000 /* Get status */ #define AUDIT_SET 1001 /* Set status (enable/disable/auditd) */ #define AUDIT_LIST 1002 /* List syscall rules -- deprecated */ #define AUDIT_ADD 1003 /* Add syscall rule -- deprecated */ #define AUDIT_DEL 1004 /* Delete syscall rule -- deprecated */ #define AUDIT_USER 1005 /* Message from userspace -- deprecated */ #define AUDIT_LOGIN 1006 /* Define the login id and information */ #define AUDIT_WATCH_INS 1007 /* Insert file/dir watch entry */ #define AUDIT_WATCH_REM 1008 /* Remove file/dir watch entry */ #define AUDIT_WATCH_LIST 1009 /* List all file/dir watches */ #define AUDIT_SIGNAL_INFO 1010 /* Get info about sender of signal to auditd */ #define AUDIT_ADD_RULE 1011 /* Add syscall filtering rule */ #define AUDIT_DEL_RULE 1012 /* Delete syscall filtering rule */ #define AUDIT_LIST_RULES 1013 /* List syscall filtering rules */ #define AUDIT_TRIM 1014 /* Trim junk from watched tree */ #define AUDIT_MAKE_EQUIV 1015 /* Append to watched tree */ #define AUDIT_TTY_GET 1016 /* Get TTY auditing status */ #define AUDIT_TTY_SET 1017 /* Set TTY auditing status */ #define AUDIT_SET_FEATURE 1018 /* Turn an audit feature on or off */ #define AUDIT_GET_FEATURE 1019 /* Get which features are enabled */ #define AUDIT_FIRST_USER_MSG 1100 /* Userspace messages mostly uninteresting to kernel */ #define AUDIT_USER_AVC 1107 /* We filter this differently */ #define AUDIT_USER_TTY 1124 /* Non-ICANON TTY input meaning */ #define AUDIT_LAST_USER_MSG 1199 #define AUDIT_FIRST_USER_MSG2 2100 /* More user space messages */ #define AUDIT_LAST_USER_MSG2 2999 #define AUDIT_DAEMON_START 1200 /* Daemon startup record */ #define AUDIT_DAEMON_END 1201 /* Daemon normal stop record */ #define AUDIT_DAEMON_ABORT 1202 /* Daemon error stop record */ #define AUDIT_DAEMON_CONFIG 1203 /* Daemon config change */ #define AUDIT_SYSCALL 1300 /* Syscall event */ /* #define AUDIT_FS_WATCH 1301 * Deprecated */ #define AUDIT_PATH 1302 /* Filename path information */ #define AUDIT_IPC 1303 /* IPC record */ #define AUDIT_SOCKETCALL 1304 /* sys_socketcall arguments */ #define AUDIT_CONFIG_CHANGE 1305 /* Audit system configuration change */ #define AUDIT_SOCKADDR 1306 /* sockaddr copied as syscall arg */ #define AUDIT_CWD 1307 /* Current working directory */ #define AUDIT_EXECVE 1309 /* execve arguments */ #define AUDIT_IPC_SET_PERM 1311 /* IPC new permissions record type */ #define AUDIT_MQ_OPEN 1312 /* POSIX MQ open record type */ #define AUDIT_MQ_SENDRECV 1313 /* POSIX MQ send/receive record type */ #define AUDIT_MQ_NOTIFY 1314 /* POSIX MQ notify record type */ #define AUDIT_MQ_GETSETATTR 1315 /* POSIX MQ get/set attribute record type */ #define AUDIT_KERNEL_OTHER 1316 /* For use by 3rd party modules */ #define AUDIT_FD_PAIR 1317 /* audit record for pipe/socketpair */ #define AUDIT_OBJ_PID 1318 /* ptrace target */ #define AUDIT_TTY 1319 /* Input on an administrative TTY */ #define AUDIT_EOE 1320 /* End of multi-record event */ #define AUDIT_BPRM_FCAPS 1321 /* Information about fcaps increasing perms */ #define AUDIT_CAPSET 1322 /* Record showing argument to sys_capset */ #define AUDIT_MMAP 1323 /* Record showing descriptor and flags in mmap */ #define AUDIT_NETFILTER_PKT 1324 /* Packets traversing netfilter chains */ #define AUDIT_NETFILTER_CFG 1325 /* Netfilter chain modifications */ #define AUDIT_SECCOMP 1326 /* Secure Computing event */ #define AUDIT_PROCTITLE 1327 /* Proctitle emit event */ #define AUDIT_FEATURE_CHANGE 1328 /* audit log listing feature changes */ #define AUDIT_REPLACE 1329 /* Replace auditd if this packet unanswerd */ #define AUDIT_KERN_MODULE 1330 /* Kernel Module events */ #define AUDIT_FANOTIFY 1331 /* Fanotify access decision */ #define AUDIT_TIME_INJOFFSET 1332 /* Timekeeping offset injected */ #define AUDIT_TIME_ADJNTPVAL 1333 /* NTP value adjustment */ #define AUDIT_BPF 1334 /* BPF subsystem */ #define AUDIT_EVENT_LISTENER 1335 /* Task joined multicast read socket */ #define AUDIT_OPENAT2 1337 /* Record showing openat2 how args */ #define AUDIT_AVC 1400 /* SE Linux avc denial or grant */ #define AUDIT_SELINUX_ERR 1401 /* Internal SE Linux Errors */ #define AUDIT_AVC_PATH 1402 /* dentry, vfsmount pair from avc */ #define AUDIT_MAC_POLICY_LOAD 1403 /* Policy file load */ #define AUDIT_MAC_STATUS 1404 /* Changed enforcing,permissive,off */ #define AUDIT_MAC_CONFIG_CHANGE 1405 /* Changes to booleans */ #define AUDIT_MAC_UNLBL_ALLOW 1406 /* NetLabel: allow unlabeled traffic */ #define AUDIT_MAC_CIPSOV4_ADD 1407 /* NetLabel: add CIPSOv4 DOI entry */ #define AUDIT_MAC_CIPSOV4_DEL 1408 /* NetLabel: del CIPSOv4 DOI entry */ #define AUDIT_MAC_MAP_ADD 1409 /* NetLabel: add LSM domain mapping */ #define AUDIT_MAC_MAP_DEL 1410 /* NetLabel: del LSM domain mapping */ #define AUDIT_MAC_IPSEC_ADDSA 1411 /* Not used */ #define AUDIT_MAC_IPSEC_DELSA 1412 /* Not used */ #define AUDIT_MAC_IPSEC_ADDSPD 1413 /* Not used */ #define AUDIT_MAC_IPSEC_DELSPD 1414 /* Not used */ #define AUDIT_MAC_IPSEC_EVENT 1415 /* Audit an IPSec event */ #define AUDIT_MAC_UNLBL_STCADD 1416 /* NetLabel: add a static label */ #define AUDIT_MAC_UNLBL_STCDEL 1417 /* NetLabel: del a static label */ #define AUDIT_MAC_CALIPSO_ADD 1418 /* NetLabel: add CALIPSO DOI entry */ #define AUDIT_MAC_CALIPSO_DEL 1419 /* NetLabel: del CALIPSO DOI entry */ #define AUDIT_FIRST_KERN_ANOM_MSG 1700 #define AUDIT_LAST_KERN_ANOM_MSG 1799 #define AUDIT_ANOM_PROMISCUOUS 1700 /* Device changed promiscuous mode */ #define AUDIT_ANOM_ABEND 1701 /* Process ended abnormally */ #define AUDIT_ANOM_LINK 1702 /* Suspicious use of file links */ #define AUDIT_ANOM_CREAT 1703 /* Suspicious file creation */ #define AUDIT_INTEGRITY_DATA 1800 /* Data integrity verification */ #define AUDIT_INTEGRITY_METADATA 1801 /* Metadata integrity verification */ #define AUDIT_INTEGRITY_STATUS 1802 /* Integrity enable status */ #define AUDIT_INTEGRITY_HASH 1803 /* Integrity HASH type */ #define AUDIT_INTEGRITY_PCR 1804 /* PCR invalidation msgs */ #define AUDIT_INTEGRITY_RULE 1805 /* policy rule */ #define AUDIT_INTEGRITY_EVM_XATTR 1806 /* New EVM-covered xattr */ #define AUDIT_INTEGRITY_POLICY_RULE 1807 /* IMA policy rules */ #define AUDIT_KERNEL 2000 /* Asynchronous audit record. NOT A REQUEST. */ /* Rule flags */ #define AUDIT_FILTER_USER 0x00 /* Apply rule to user-generated messages */ #define AUDIT_FILTER_TASK 0x01 /* Apply rule at task creation (not syscall) */ #define AUDIT_FILTER_ENTRY 0x02 /* Apply rule at syscall entry */ #define AUDIT_FILTER_WATCH 0x03 /* Apply rule to file system watches */ #define AUDIT_FILTER_EXIT 0x04 /* Apply rule at syscall exit */ #define AUDIT_FILTER_EXCLUDE 0x05 /* Apply rule before record creation */ #define AUDIT_FILTER_TYPE AUDIT_FILTER_EXCLUDE /* obsolete misleading naming */ #define AUDIT_FILTER_FS 0x06 /* Apply rule at __audit_inode_child */ #define AUDIT_NR_FILTERS 7 #define AUDIT_FILTER_PREPEND 0x10 /* Prepend to front of list */ /* Rule actions */ #define AUDIT_NEVER 0 /* Do not build context if rule matches */ #define AUDIT_POSSIBLE 1 /* Build context if rule matches */ #define AUDIT_ALWAYS 2 /* Generate audit record if rule matches */ /* Rule structure sizes -- if these change, different AUDIT_ADD and * AUDIT_LIST commands must be implemented. */ #define AUDIT_MAX_FIELDS 64 #define AUDIT_MAX_KEY_LEN 256 #define AUDIT_BITMASK_SIZE 64 #define AUDIT_WORD(nr) ((__u32)((nr)/32)) #define AUDIT_BIT(nr) (1U << ((nr) - AUDIT_WORD(nr)*32)) #define AUDIT_SYSCALL_CLASSES 16 #define AUDIT_CLASS_DIR_WRITE 0 #define AUDIT_CLASS_DIR_WRITE_32 1 #define AUDIT_CLASS_CHATTR 2 #define AUDIT_CLASS_CHATTR_32 3 #define AUDIT_CLASS_READ 4 #define AUDIT_CLASS_READ_32 5 #define AUDIT_CLASS_WRITE 6 #define AUDIT_CLASS_WRITE_32 7 #define AUDIT_CLASS_SIGNAL 8 #define AUDIT_CLASS_SIGNAL_32 9 /* This bitmask is used to validate user input. It represents all bits that * are currently used in an audit field constant understood by the kernel. * If you are adding a new #define AUDIT_, please ensure that * AUDIT_UNUSED_BITS is updated if need be. */ #define AUDIT_UNUSED_BITS 0x07FFFC00 /* AUDIT_FIELD_COMPARE rule list */ #define AUDIT_COMPARE_UID_TO_OBJ_UID 1 #define AUDIT_COMPARE_GID_TO_OBJ_GID 2 #define AUDIT_COMPARE_EUID_TO_OBJ_UID 3 #define AUDIT_COMPARE_EGID_TO_OBJ_GID 4 #define AUDIT_COMPARE_AUID_TO_OBJ_UID 5 #define AUDIT_COMPARE_SUID_TO_OBJ_UID 6 #define AUDIT_COMPARE_SGID_TO_OBJ_GID 7 #define AUDIT_COMPARE_FSUID_TO_OBJ_UID 8 #define AUDIT_COMPARE_FSGID_TO_OBJ_GID 9 #define AUDIT_COMPARE_UID_TO_AUID 10 #define AUDIT_COMPARE_UID_TO_EUID 11 #define AUDIT_COMPARE_UID_TO_FSUID 12 #define AUDIT_COMPARE_UID_TO_SUID 13 #define AUDIT_COMPARE_AUID_TO_FSUID 14 #define AUDIT_COMPARE_AUID_TO_SUID 15 #define AUDIT_COMPARE_AUID_TO_EUID 16 #define AUDIT_COMPARE_EUID_TO_SUID 17 #define AUDIT_COMPARE_EUID_TO_FSUID 18 #define AUDIT_COMPARE_SUID_TO_FSUID 19 #define AUDIT_COMPARE_GID_TO_EGID 20 #define AUDIT_COMPARE_GID_TO_FSGID 21 #define AUDIT_COMPARE_GID_TO_SGID 22 #define AUDIT_COMPARE_EGID_TO_FSGID 23 #define AUDIT_COMPARE_EGID_TO_SGID 24 #define AUDIT_COMPARE_SGID_TO_FSGID 25 #define AUDIT_MAX_FIELD_COMPARE AUDIT_COMPARE_SGID_TO_FSGID /* Rule fields */ /* These are useful when checking the * task structure at task creation time * (AUDIT_PER_TASK). */ #define AUDIT_PID 0 #define AUDIT_UID 1 #define AUDIT_EUID 2 #define AUDIT_SUID 3 #define AUDIT_FSUID 4 #define AUDIT_GID 5 #define AUDIT_EGID 6 #define AUDIT_SGID 7 #define AUDIT_FSGID 8 #define AUDIT_LOGINUID 9 #define AUDIT_PERS 10 #define AUDIT_ARCH 11 #define AUDIT_MSGTYPE 12 #define AUDIT_SUBJ_USER 13 /* security label user */ #define AUDIT_SUBJ_ROLE 14 /* security label role */ #define AUDIT_SUBJ_TYPE 15 /* security label type */ #define AUDIT_SUBJ_SEN 16 /* security label sensitivity label */ #define AUDIT_SUBJ_CLR 17 /* security label clearance label */ #define AUDIT_PPID 18 #define AUDIT_OBJ_USER 19 #define AUDIT_OBJ_ROLE 20 #define AUDIT_OBJ_TYPE 21 #define AUDIT_OBJ_LEV_LOW 22 #define AUDIT_OBJ_LEV_HIGH 23 #define AUDIT_LOGINUID_SET 24 #define AUDIT_SESSIONID 25 /* Session ID */ #define AUDIT_FSTYPE 26 /* FileSystem Type */ /* These are ONLY useful when checking * at syscall exit time (AUDIT_AT_EXIT). */ #define AUDIT_DEVMAJOR 100 #define AUDIT_DEVMINOR 101 #define AUDIT_INODE 102 #define AUDIT_EXIT 103 #define AUDIT_SUCCESS 104 /* exit >= 0; value ignored */ #define AUDIT_WATCH 105 #define AUDIT_PERM 106 #define AUDIT_DIR 107 #define AUDIT_FILETYPE 108 #define AUDIT_OBJ_UID 109 #define AUDIT_OBJ_GID 110 #define AUDIT_FIELD_COMPARE 111 #define AUDIT_EXE 112 #define AUDIT_SADDR_FAM 113 #define AUDIT_ARG0 200 #define AUDIT_ARG1 (AUDIT_ARG0+1) #define AUDIT_ARG2 (AUDIT_ARG0+2) #define AUDIT_ARG3 (AUDIT_ARG0+3) #define AUDIT_FILTERKEY 210 #define AUDIT_NEGATE 0x80000000 /* These are the supported operators. * 4 2 1 8 * = > < ? * ---------- * 0 0 0 0 00 nonsense * 0 0 0 1 08 & bit mask * 0 0 1 0 10 < * 0 1 0 0 20 > * 0 1 1 0 30 != * 1 0 0 0 40 = * 1 0 0 1 48 &= bit test * 1 0 1 0 50 <= * 1 1 0 0 60 >= * 1 1 1 1 78 all operators */ #define AUDIT_BIT_MASK 0x08000000 #define AUDIT_LESS_THAN 0x10000000 #define AUDIT_GREATER_THAN 0x20000000 #define AUDIT_NOT_EQUAL 0x30000000 #define AUDIT_EQUAL 0x40000000 #define AUDIT_BIT_TEST (AUDIT_BIT_MASK|AUDIT_EQUAL) #define AUDIT_LESS_THAN_OR_EQUAL (AUDIT_LESS_THAN|AUDIT_EQUAL) #define AUDIT_GREATER_THAN_OR_EQUAL (AUDIT_GREATER_THAN|AUDIT_EQUAL) #define AUDIT_OPERATORS (AUDIT_EQUAL|AUDIT_NOT_EQUAL|AUDIT_BIT_MASK) enum { Audit_equal, Audit_not_equal, Audit_bitmask, Audit_bittest, Audit_lt, Audit_gt, Audit_le, Audit_ge, Audit_bad }; /* Status symbols */ /* Mask values */ #define AUDIT_STATUS_ENABLED 0x0001 #define AUDIT_STATUS_FAILURE 0x0002 #define AUDIT_STATUS_PID 0x0004 #define AUDIT_STATUS_RATE_LIMIT 0x0008 #define AUDIT_STATUS_BACKLOG_LIMIT 0x0010 #define AUDIT_STATUS_BACKLOG_WAIT_TIME 0x0020 #define AUDIT_STATUS_LOST 0x0040 #define AUDIT_STATUS_BACKLOG_WAIT_TIME_ACTUAL 0x0080 #define AUDIT_FEATURE_BITMAP_BACKLOG_LIMIT 0x00000001 #define AUDIT_FEATURE_BITMAP_BACKLOG_WAIT_TIME 0x00000002 #define AUDIT_FEATURE_BITMAP_EXECUTABLE_PATH 0x00000004 #define AUDIT_FEATURE_BITMAP_EXCLUDE_EXTEND 0x00000008 #define AUDIT_FEATURE_BITMAP_SESSIONID_FILTER 0x00000010 #define AUDIT_FEATURE_BITMAP_LOST_RESET 0x00000020 #define AUDIT_FEATURE_BITMAP_FILTER_FS 0x00000040 #define AUDIT_FEATURE_BITMAP_ALL (AUDIT_FEATURE_BITMAP_BACKLOG_LIMIT | \ AUDIT_FEATURE_BITMAP_BACKLOG_WAIT_TIME | \ AUDIT_FEATURE_BITMAP_EXECUTABLE_PATH | \ AUDIT_FEATURE_BITMAP_EXCLUDE_EXTEND | \ AUDIT_FEATURE_BITMAP_SESSIONID_FILTER | \ AUDIT_FEATURE_BITMAP_LOST_RESET | \ AUDIT_FEATURE_BITMAP_FILTER_FS) /* deprecated: AUDIT_VERSION_* */ #define AUDIT_VERSION_LATEST AUDIT_FEATURE_BITMAP_ALL #define AUDIT_VERSION_BACKLOG_LIMIT AUDIT_FEATURE_BITMAP_BACKLOG_LIMIT #define AUDIT_VERSION_BACKLOG_WAIT_TIME AUDIT_FEATURE_BITMAP_BACKLOG_WAIT_TIME /* Failure-to-log actions */ #define AUDIT_FAIL_SILENT 0 #define AUDIT_FAIL_PRINTK 1 #define AUDIT_FAIL_PANIC 2 /* * These bits disambiguate different calling conventions that share an * ELF machine type, bitness, and endianness */ #define __AUDIT_ARCH_CONVENTION_MASK 0x30000000 #define __AUDIT_ARCH_CONVENTION_MIPS64_N32 0x20000000 /* distinguish syscall tables */ #define __AUDIT_ARCH_64BIT 0x80000000 #define __AUDIT_ARCH_LE 0x40000000 #define AUDIT_ARCH_AARCH64 (EM_AARCH64|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_ALPHA (EM_ALPHA|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_ARM (EM_ARM|__AUDIT_ARCH_LE) #define AUDIT_ARCH_ARMEB (EM_ARM) #define AUDIT_ARCH_CRIS (EM_CRIS|__AUDIT_ARCH_LE) #define AUDIT_ARCH_FRV (EM_FRV) #define AUDIT_ARCH_I386 (EM_386|__AUDIT_ARCH_LE) #define AUDIT_ARCH_IA64 (EM_IA_64|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_M32R (EM_M32R) #define AUDIT_ARCH_M68K (EM_68K) #define AUDIT_ARCH_MICROBLAZE (EM_MICROBLAZE) #define AUDIT_ARCH_MIPS (EM_MIPS) #define AUDIT_ARCH_MIPSEL (EM_MIPS|__AUDIT_ARCH_LE) #define AUDIT_ARCH_MIPS64 (EM_MIPS|__AUDIT_ARCH_64BIT) #define AUDIT_ARCH_MIPS64N32 (EM_MIPS|__AUDIT_ARCH_64BIT|\ __AUDIT_ARCH_CONVENTION_MIPS64_N32) #define AUDIT_ARCH_MIPSEL64 (EM_MIPS|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_MIPSEL64N32 (EM_MIPS|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE|\ __AUDIT_ARCH_CONVENTION_MIPS64_N32) #define AUDIT_ARCH_OPENRISC (EM_OPENRISC) #define AUDIT_ARCH_PARISC (EM_PARISC) #define AUDIT_ARCH_PARISC64 (EM_PARISC|__AUDIT_ARCH_64BIT) #define AUDIT_ARCH_PPC (EM_PPC) /* do not define AUDIT_ARCH_PPCLE since it is not supported by audit */ #define AUDIT_ARCH_PPC64 (EM_PPC64|__AUDIT_ARCH_64BIT) #define AUDIT_ARCH_PPC64LE (EM_PPC64|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_S390 (EM_S390) #define AUDIT_ARCH_S390X (EM_S390|__AUDIT_ARCH_64BIT) #define AUDIT_ARCH_SH (EM_SH) #define AUDIT_ARCH_SHEL (EM_SH|__AUDIT_ARCH_LE) #define AUDIT_ARCH_SH64 (EM_SH|__AUDIT_ARCH_64BIT) #define AUDIT_ARCH_SHEL64 (EM_SH|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_SPARC (EM_SPARC) #define AUDIT_ARCH_SPARC64 (EM_SPARCV9|__AUDIT_ARCH_64BIT) #define AUDIT_ARCH_TILEGX (EM_TILEGX|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_ARCH_TILEGX32 (EM_TILEGX|__AUDIT_ARCH_LE) #define AUDIT_ARCH_TILEPRO (EM_TILEPRO|__AUDIT_ARCH_LE) #define AUDIT_ARCH_X86_64 (EM_X86_64|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE) #define AUDIT_PERM_EXEC 1 #define AUDIT_PERM_WRITE 2 #define AUDIT_PERM_READ 4 #define AUDIT_PERM_ATTR 8 /* MAX_AUDIT_MESSAGE_LENGTH is set in audit:lib/libaudit.h as: * 8970 // PATH_MAX*2+CONTEXT_SIZE*2+11+256+1 * max header+body+tailer: 44 + 29 + 32 + 262 + 7 + pad */ #define AUDIT_MESSAGE_TEXT_MAX 8560 /* Multicast Netlink socket groups (default up to 32) */ enum audit_nlgrps { AUDIT_NLGRP_NONE, /* Group 0 not used */ AUDIT_NLGRP_READLOG, /* "best effort" read only socket */ __AUDIT_NLGRP_MAX }; #define AUDIT_NLGRP_MAX (__AUDIT_NLGRP_MAX - 1) struct audit_status { __u32 mask; /* Bit mask for valid entries */ __u32 enabled; /* 1 = enabled, 0 = disabled */ __u32 failure; /* Failure-to-log action */ __u32 pid; /* pid of auditd process */ __u32 rate_limit; /* messages rate limit (per second) */ __u32 backlog_limit; /* waiting messages limit */ __u32 lost; /* messages lost */ __u32 backlog; /* messages waiting in queue */ union { __u32 version; /* deprecated: audit api version num */ __u32 feature_bitmap; /* bitmap of kernel audit features */ }; __u32 backlog_wait_time;/* message queue wait timeout */ __u32 backlog_wait_time_actual;/* time spent waiting while * message limit exceeded */ }; struct audit_features { #define AUDIT_FEATURE_VERSION 1 __u32 vers; __u32 mask; /* which bits we are dealing with */ __u32 features; /* which feature to enable/disable */ __u32 lock; /* which features to lock */ }; #define AUDIT_FEATURE_ONLY_UNSET_LOGINUID 0 #define AUDIT_FEATURE_LOGINUID_IMMUTABLE 1 #define AUDIT_LAST_FEATURE AUDIT_FEATURE_LOGINUID_IMMUTABLE #define audit_feature_valid(x) ((x) >= 0 && (x) <= AUDIT_LAST_FEATURE) #define AUDIT_FEATURE_TO_MASK(x) (1 << ((x) & 31)) /* mask for __u32 */ struct audit_tty_status { __u32 enabled; /* 1 = enabled, 0 = disabled */ __u32 log_passwd; /* 1 = enabled, 0 = disabled */ }; #define AUDIT_UID_UNSET (unsigned int)-1 #define AUDIT_SID_UNSET ((unsigned int)-1) /* audit_rule_data supports filter rules with both integer and string * fields. It corresponds with AUDIT_ADD_RULE, AUDIT_DEL_RULE and * AUDIT_LIST_RULES requests. */ struct audit_rule_data { __u32 flags; /* AUDIT_PER_{TASK,CALL}, AUDIT_PREPEND */ __u32 action; /* AUDIT_NEVER, AUDIT_POSSIBLE, AUDIT_ALWAYS */ __u32 field_count; __u32 mask[AUDIT_BITMASK_SIZE]; /* syscall(s) affected */ __u32 fields[AUDIT_MAX_FIELDS]; __u32 values[AUDIT_MAX_FIELDS]; __u32 fieldflags[AUDIT_MAX_FIELDS]; __u32 buflen; /* total length of string fields */ char buf[]; /* string fields buffer */ }; #endif /* _LINUX_AUDIT_H_ */ linux/cdrom.h000064400000070273151027430560007174 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * -- * General header file for linux CD-ROM drivers * Copyright (C) 1992 David Giller, rafetmad@oxy.edu * 1994, 1995 Eberhard Mönkeberg, emoenke@gwdg.de * 1996 David van Leeuwen, david@tm.tno.nl * 1997, 1998 Erik Andersen, andersee@debian.org * 1998-2002 Jens Axboe, axboe@suse.de */ #ifndef _LINUX_CDROM_H #define _LINUX_CDROM_H #include #include /******************************************************* * As of Linux 2.1.x, all Linux CD-ROM application programs will use this * (and only this) include file. It is my hope to provide Linux with * a uniform interface between software accessing CD-ROMs and the various * device drivers that actually talk to the drives. There may still be * 23 different kinds of strange CD-ROM drives, but at least there will * now be one, and only one, Linux CD-ROM interface. * * Additionally, as of Linux 2.1.x, all Linux application programs * should use the O_NONBLOCK option when opening a CD-ROM device * for subsequent ioctl commands. This allows for neat system errors * like "No medium found" or "Wrong medium type" upon attempting to * mount or play an empty slot, mount an audio disc, or play a data disc. * Generally, changing an application program to support O_NONBLOCK * is as easy as the following: * - drive = open("/dev/cdrom", O_RDONLY); * + drive = open("/dev/cdrom", O_RDONLY | O_NONBLOCK); * It is worth the small change. * * Patches for many common CD programs (provided by David A. van Leeuwen) * can be found at: ftp://ftp.gwdg.de/pub/linux/cdrom/drivers/cm206/ * *******************************************************/ /* When a driver supports a certain function, but the cdrom drive we are * using doesn't, we will return the error EDRIVE_CANT_DO_THIS. We will * borrow the "Operation not supported" error from the network folks to * accomplish this. Maybe someday we will get a more targeted error code, * but this will do for now... */ #define EDRIVE_CANT_DO_THIS EOPNOTSUPP /******************************************************* * The CD-ROM IOCTL commands -- these should be supported by * all the various cdrom drivers. For the CD-ROM ioctls, we * will commandeer byte 0x53, or 'S'. *******************************************************/ #define CDROMPAUSE 0x5301 /* Pause Audio Operation */ #define CDROMRESUME 0x5302 /* Resume paused Audio Operation */ #define CDROMPLAYMSF 0x5303 /* Play Audio MSF (struct cdrom_msf) */ #define CDROMPLAYTRKIND 0x5304 /* Play Audio Track/index (struct cdrom_ti) */ #define CDROMREADTOCHDR 0x5305 /* Read TOC header (struct cdrom_tochdr) */ #define CDROMREADTOCENTRY 0x5306 /* Read TOC entry (struct cdrom_tocentry) */ #define CDROMSTOP 0x5307 /* Stop the cdrom drive */ #define CDROMSTART 0x5308 /* Start the cdrom drive */ #define CDROMEJECT 0x5309 /* Ejects the cdrom media */ #define CDROMVOLCTRL 0x530a /* Control output volume (struct cdrom_volctrl) */ #define CDROMSUBCHNL 0x530b /* Read subchannel data (struct cdrom_subchnl) */ #define CDROMREADMODE2 0x530c /* Read CDROM mode 2 data (2336 Bytes) (struct cdrom_read) */ #define CDROMREADMODE1 0x530d /* Read CDROM mode 1 data (2048 Bytes) (struct cdrom_read) */ #define CDROMREADAUDIO 0x530e /* (struct cdrom_read_audio) */ #define CDROMEJECT_SW 0x530f /* enable(1)/disable(0) auto-ejecting */ #define CDROMMULTISESSION 0x5310 /* Obtain the start-of-last-session address of multi session disks (struct cdrom_multisession) */ #define CDROM_GET_MCN 0x5311 /* Obtain the "Universal Product Code" if available (struct cdrom_mcn) */ #define CDROM_GET_UPC CDROM_GET_MCN /* This one is deprecated, but here anyway for compatibility */ #define CDROMRESET 0x5312 /* hard-reset the drive */ #define CDROMVOLREAD 0x5313 /* Get the drive's volume setting (struct cdrom_volctrl) */ #define CDROMREADRAW 0x5314 /* read data in raw mode (2352 Bytes) (struct cdrom_read) */ /* * These ioctls are used only used in aztcd.c and optcd.c */ #define CDROMREADCOOKED 0x5315 /* read data in cooked mode */ #define CDROMSEEK 0x5316 /* seek msf address */ /* * This ioctl is only used by the scsi-cd driver. It is for playing audio in logical block addressing mode. */ #define CDROMPLAYBLK 0x5317 /* (struct cdrom_blk) */ /* * These ioctls are only used in optcd.c */ #define CDROMREADALL 0x5318 /* read all 2646 bytes */ /* * These ioctls are (now) only in ide-cd.c for controlling * drive spindown time. They should be implemented in the * Uniform driver, via generic packet commands, GPCMD_MODE_SELECT_10, * GPCMD_MODE_SENSE_10 and the GPMODE_POWER_PAGE... * -Erik */ #define CDROMGETSPINDOWN 0x531d #define CDROMSETSPINDOWN 0x531e /* * These ioctls are implemented through the uniform CD-ROM driver * They _will_ be adopted by all CD-ROM drivers, when all the CD-ROM * drivers are eventually ported to the uniform CD-ROM driver interface. */ #define CDROMCLOSETRAY 0x5319 /* pendant of CDROMEJECT */ #define CDROM_SET_OPTIONS 0x5320 /* Set behavior options */ #define CDROM_CLEAR_OPTIONS 0x5321 /* Clear behavior options */ #define CDROM_SELECT_SPEED 0x5322 /* Set the CD-ROM speed */ #define CDROM_SELECT_DISC 0x5323 /* Select disc (for juke-boxes) */ #define CDROM_MEDIA_CHANGED 0x5325 /* Check is media changed */ #define CDROM_DRIVE_STATUS 0x5326 /* Get tray position, etc. */ #define CDROM_DISC_STATUS 0x5327 /* Get disc type, etc. */ #define CDROM_CHANGER_NSLOTS 0x5328 /* Get number of slots */ #define CDROM_LOCKDOOR 0x5329 /* lock or unlock door */ #define CDROM_DEBUG 0x5330 /* Turn debug messages on/off */ #define CDROM_GET_CAPABILITY 0x5331 /* get capabilities */ /* Note that scsi/scsi_ioctl.h also uses 0x5382 - 0x5386. * Future CDROM ioctls should be kept below 0x537F */ /* This ioctl is only used by sbpcd at the moment */ #define CDROMAUDIOBUFSIZ 0x5382 /* set the audio buffer size */ /* conflict with SCSI_IOCTL_GET_IDLUN */ /* DVD-ROM Specific ioctls */ #define DVD_READ_STRUCT 0x5390 /* Read structure */ #define DVD_WRITE_STRUCT 0x5391 /* Write structure */ #define DVD_AUTH 0x5392 /* Authentication */ #define CDROM_SEND_PACKET 0x5393 /* send a packet to the drive */ #define CDROM_NEXT_WRITABLE 0x5394 /* get next writable block */ #define CDROM_LAST_WRITTEN 0x5395 /* get last block written on disc */ /******************************************************* * CDROM IOCTL structures *******************************************************/ /* Address in MSF format */ struct cdrom_msf0 { __u8 minute; __u8 second; __u8 frame; }; /* Address in either MSF or logical format */ union cdrom_addr { struct cdrom_msf0 msf; int lba; }; /* This struct is used by the CDROMPLAYMSF ioctl */ struct cdrom_msf { __u8 cdmsf_min0; /* start minute */ __u8 cdmsf_sec0; /* start second */ __u8 cdmsf_frame0; /* start frame */ __u8 cdmsf_min1; /* end minute */ __u8 cdmsf_sec1; /* end second */ __u8 cdmsf_frame1; /* end frame */ }; /* This struct is used by the CDROMPLAYTRKIND ioctl */ struct cdrom_ti { __u8 cdti_trk0; /* start track */ __u8 cdti_ind0; /* start index */ __u8 cdti_trk1; /* end track */ __u8 cdti_ind1; /* end index */ }; /* This struct is used by the CDROMREADTOCHDR ioctl */ struct cdrom_tochdr { __u8 cdth_trk0; /* start track */ __u8 cdth_trk1; /* end track */ }; /* This struct is used by the CDROMVOLCTRL and CDROMVOLREAD ioctls */ struct cdrom_volctrl { __u8 channel0; __u8 channel1; __u8 channel2; __u8 channel3; }; /* This struct is used by the CDROMSUBCHNL ioctl */ struct cdrom_subchnl { __u8 cdsc_format; __u8 cdsc_audiostatus; __u8 cdsc_adr: 4; __u8 cdsc_ctrl: 4; __u8 cdsc_trk; __u8 cdsc_ind; union cdrom_addr cdsc_absaddr; union cdrom_addr cdsc_reladdr; }; /* This struct is used by the CDROMREADTOCENTRY ioctl */ struct cdrom_tocentry { __u8 cdte_track; __u8 cdte_adr :4; __u8 cdte_ctrl :4; __u8 cdte_format; union cdrom_addr cdte_addr; __u8 cdte_datamode; }; /* This struct is used by the CDROMREADMODE1, and CDROMREADMODE2 ioctls */ struct cdrom_read { int cdread_lba; char *cdread_bufaddr; int cdread_buflen; }; /* This struct is used by the CDROMREADAUDIO ioctl */ struct cdrom_read_audio { union cdrom_addr addr; /* frame address */ __u8 addr_format; /* CDROM_LBA or CDROM_MSF */ int nframes; /* number of 2352-byte-frames to read at once */ __u8 *buf; /* frame buffer (size: nframes*2352 bytes) */ }; /* This struct is used with the CDROMMULTISESSION ioctl */ struct cdrom_multisession { union cdrom_addr addr; /* frame address: start-of-last-session (not the new "frame 16"!). Only valid if the "xa_flag" is true. */ __u8 xa_flag; /* 1: "is XA disk" */ __u8 addr_format; /* CDROM_LBA or CDROM_MSF */ }; /* This struct is used with the CDROM_GET_MCN ioctl. * Very few audio discs actually have Universal Product Code information, * which should just be the Medium Catalog Number on the box. Also note * that the way the codeis written on CD is _not_ uniform across all discs! */ struct cdrom_mcn { __u8 medium_catalog_number[14]; /* 13 ASCII digits, null-terminated */ }; /* This is used by the CDROMPLAYBLK ioctl */ struct cdrom_blk { unsigned from; unsigned short len; }; #define CDROM_PACKET_SIZE 12 #define CGC_DATA_UNKNOWN 0 #define CGC_DATA_WRITE 1 #define CGC_DATA_READ 2 #define CGC_DATA_NONE 3 /* for CDROM_PACKET_COMMAND ioctl */ struct cdrom_generic_command { unsigned char cmd[CDROM_PACKET_SIZE]; unsigned char *buffer; unsigned int buflen; int stat; struct request_sense *sense; unsigned char data_direction; int quiet; int timeout; void *reserved[1]; /* unused, actually */ }; /* * A CD-ROM physical sector size is 2048, 2052, 2056, 2324, 2332, 2336, * 2340, or 2352 bytes long. * Sector types of the standard CD-ROM data formats: * * format sector type user data size (bytes) * ----------------------------------------------------------------------------- * 1 (Red Book) CD-DA 2352 (CD_FRAMESIZE_RAW) * 2 (Yellow Book) Mode1 Form1 2048 (CD_FRAMESIZE) * 3 (Yellow Book) Mode1 Form2 2336 (CD_FRAMESIZE_RAW0) * 4 (Green Book) Mode2 Form1 2048 (CD_FRAMESIZE) * 5 (Green Book) Mode2 Form2 2328 (2324+4 spare bytes) * * * The layout of the standard CD-ROM data formats: * ----------------------------------------------------------------------------- * - audio (red): | audio_sample_bytes | * | 2352 | * * - data (yellow, mode1): | sync - head - data - EDC - zero - ECC | * | 12 - 4 - 2048 - 4 - 8 - 276 | * * - data (yellow, mode2): | sync - head - data | * | 12 - 4 - 2336 | * * - XA data (green, mode2 form1): | sync - head - sub - data - EDC - ECC | * | 12 - 4 - 8 - 2048 - 4 - 276 | * * - XA data (green, mode2 form2): | sync - head - sub - data - Spare | * | 12 - 4 - 8 - 2324 - 4 | * */ /* Some generally useful CD-ROM information -- mostly based on the above */ #define CD_MINS 74 /* max. minutes per CD, not really a limit */ #define CD_SECS 60 /* seconds per minute */ #define CD_FRAMES 75 /* frames per second */ #define CD_SYNC_SIZE 12 /* 12 sync bytes per raw data frame */ #define CD_MSF_OFFSET 150 /* MSF numbering offset of first frame */ #define CD_CHUNK_SIZE 24 /* lowest-level "data bytes piece" */ #define CD_NUM_OF_CHUNKS 98 /* chunks per frame */ #define CD_FRAMESIZE_SUB 96 /* subchannel data "frame" size */ #define CD_HEAD_SIZE 4 /* header (address) bytes per raw data frame */ #define CD_SUBHEAD_SIZE 8 /* subheader bytes per raw XA data frame */ #define CD_EDC_SIZE 4 /* bytes EDC per most raw data frame types */ #define CD_ZERO_SIZE 8 /* bytes zero per yellow book mode 1 frame */ #define CD_ECC_SIZE 276 /* bytes ECC per most raw data frame types */ #define CD_FRAMESIZE 2048 /* bytes per frame, "cooked" mode */ #define CD_FRAMESIZE_RAW 2352 /* bytes per frame, "raw" mode */ #define CD_FRAMESIZE_RAWER 2646 /* The maximum possible returned bytes */ /* most drives don't deliver everything: */ #define CD_FRAMESIZE_RAW1 (CD_FRAMESIZE_RAW-CD_SYNC_SIZE) /*2340*/ #define CD_FRAMESIZE_RAW0 (CD_FRAMESIZE_RAW-CD_SYNC_SIZE-CD_HEAD_SIZE) /*2336*/ #define CD_XA_HEAD (CD_HEAD_SIZE+CD_SUBHEAD_SIZE) /* "before data" part of raw XA frame */ #define CD_XA_TAIL (CD_EDC_SIZE+CD_ECC_SIZE) /* "after data" part of raw XA frame */ #define CD_XA_SYNC_HEAD (CD_SYNC_SIZE+CD_XA_HEAD) /* sync bytes + header of XA frame */ /* CD-ROM address types (cdrom_tocentry.cdte_format) */ #define CDROM_LBA 0x01 /* "logical block": first frame is #0 */ #define CDROM_MSF 0x02 /* "minute-second-frame": binary, not bcd here! */ /* bit to tell whether track is data or audio (cdrom_tocentry.cdte_ctrl) */ #define CDROM_DATA_TRACK 0x04 /* The leadout track is always 0xAA, regardless of # of tracks on disc */ #define CDROM_LEADOUT 0xAA /* audio states (from SCSI-2, but seen with other drives, too) */ #define CDROM_AUDIO_INVALID 0x00 /* audio status not supported */ #define CDROM_AUDIO_PLAY 0x11 /* audio play operation in progress */ #define CDROM_AUDIO_PAUSED 0x12 /* audio play operation paused */ #define CDROM_AUDIO_COMPLETED 0x13 /* audio play successfully completed */ #define CDROM_AUDIO_ERROR 0x14 /* audio play stopped due to error */ #define CDROM_AUDIO_NO_STATUS 0x15 /* no current audio status to return */ /* capability flags used with the uniform CD-ROM driver */ #define CDC_CLOSE_TRAY 0x1 /* caddy systems _can't_ close */ #define CDC_OPEN_TRAY 0x2 /* but _can_ eject. */ #define CDC_LOCK 0x4 /* disable manual eject */ #define CDC_SELECT_SPEED 0x8 /* programmable speed */ #define CDC_SELECT_DISC 0x10 /* select disc from juke-box */ #define CDC_MULTI_SESSION 0x20 /* read sessions>1 */ #define CDC_MCN 0x40 /* Medium Catalog Number */ #define CDC_MEDIA_CHANGED 0x80 /* media changed */ #define CDC_PLAY_AUDIO 0x100 /* audio functions */ #define CDC_RESET 0x200 /* hard reset device */ #define CDC_DRIVE_STATUS 0x800 /* driver implements drive status */ #define CDC_GENERIC_PACKET 0x1000 /* driver implements generic packets */ #define CDC_CD_R 0x2000 /* drive is a CD-R */ #define CDC_CD_RW 0x4000 /* drive is a CD-RW */ #define CDC_DVD 0x8000 /* drive is a DVD */ #define CDC_DVD_R 0x10000 /* drive can write DVD-R */ #define CDC_DVD_RAM 0x20000 /* drive can write DVD-RAM */ #define CDC_MO_DRIVE 0x40000 /* drive is an MO device */ #define CDC_MRW 0x80000 /* drive can read MRW */ #define CDC_MRW_W 0x100000 /* drive can write MRW */ #define CDC_RAM 0x200000 /* ok to open for WRITE */ /* drive status possibilities returned by CDROM_DRIVE_STATUS ioctl */ #define CDS_NO_INFO 0 /* if not implemented */ #define CDS_NO_DISC 1 #define CDS_TRAY_OPEN 2 #define CDS_DRIVE_NOT_READY 3 #define CDS_DISC_OK 4 /* return values for the CDROM_DISC_STATUS ioctl */ /* can also return CDS_NO_[INFO|DISC], from above */ #define CDS_AUDIO 100 #define CDS_DATA_1 101 #define CDS_DATA_2 102 #define CDS_XA_2_1 103 #define CDS_XA_2_2 104 #define CDS_MIXED 105 /* User-configurable behavior options for the uniform CD-ROM driver */ #define CDO_AUTO_CLOSE 0x1 /* close tray on first open() */ #define CDO_AUTO_EJECT 0x2 /* open tray on last release() */ #define CDO_USE_FFLAGS 0x4 /* use O_NONBLOCK information on open */ #define CDO_LOCK 0x8 /* lock tray on open files */ #define CDO_CHECK_TYPE 0x10 /* check type on open for data */ /* Special codes used when specifying changer slots. */ #define CDSL_NONE (INT_MAX-1) #define CDSL_CURRENT INT_MAX /* For partition based multisession access. IDE can handle 64 partitions * per drive - SCSI CD-ROM's use minors to differentiate between the * various drives, so we can't do multisessions the same way there. * Use the -o session=x option to mount on them. */ #define CD_PART_MAX 64 #define CD_PART_MASK (CD_PART_MAX - 1) /********************************************************************* * Generic Packet commands, MMC commands, and such *********************************************************************/ /* The generic packet command opcodes for CD/DVD Logical Units, * From Table 57 of the SFF8090 Ver. 3 (Mt. Fuji) draft standard. */ #define GPCMD_BLANK 0xa1 #define GPCMD_CLOSE_TRACK 0x5b #define GPCMD_FLUSH_CACHE 0x35 #define GPCMD_FORMAT_UNIT 0x04 #define GPCMD_GET_CONFIGURATION 0x46 #define GPCMD_GET_EVENT_STATUS_NOTIFICATION 0x4a #define GPCMD_GET_PERFORMANCE 0xac #define GPCMD_INQUIRY 0x12 #define GPCMD_LOAD_UNLOAD 0xa6 #define GPCMD_MECHANISM_STATUS 0xbd #define GPCMD_MODE_SELECT_10 0x55 #define GPCMD_MODE_SENSE_10 0x5a #define GPCMD_PAUSE_RESUME 0x4b #define GPCMD_PLAY_AUDIO_10 0x45 #define GPCMD_PLAY_AUDIO_MSF 0x47 #define GPCMD_PLAY_AUDIO_TI 0x48 #define GPCMD_PLAY_CD 0xbc #define GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e #define GPCMD_READ_10 0x28 #define GPCMD_READ_12 0xa8 #define GPCMD_READ_BUFFER 0x3c #define GPCMD_READ_BUFFER_CAPACITY 0x5c #define GPCMD_READ_CDVD_CAPACITY 0x25 #define GPCMD_READ_CD 0xbe #define GPCMD_READ_CD_MSF 0xb9 #define GPCMD_READ_DISC_INFO 0x51 #define GPCMD_READ_DVD_STRUCTURE 0xad #define GPCMD_READ_FORMAT_CAPACITIES 0x23 #define GPCMD_READ_HEADER 0x44 #define GPCMD_READ_TRACK_RZONE_INFO 0x52 #define GPCMD_READ_SUBCHANNEL 0x42 #define GPCMD_READ_TOC_PMA_ATIP 0x43 #define GPCMD_REPAIR_RZONE_TRACK 0x58 #define GPCMD_REPORT_KEY 0xa4 #define GPCMD_REQUEST_SENSE 0x03 #define GPCMD_RESERVE_RZONE_TRACK 0x53 #define GPCMD_SEND_CUE_SHEET 0x5d #define GPCMD_SCAN 0xba #define GPCMD_SEEK 0x2b #define GPCMD_SEND_DVD_STRUCTURE 0xbf #define GPCMD_SEND_EVENT 0xa2 #define GPCMD_SEND_KEY 0xa3 #define GPCMD_SEND_OPC 0x54 #define GPCMD_SET_READ_AHEAD 0xa7 #define GPCMD_SET_STREAMING 0xb6 #define GPCMD_START_STOP_UNIT 0x1b #define GPCMD_STOP_PLAY_SCAN 0x4e #define GPCMD_TEST_UNIT_READY 0x00 #define GPCMD_VERIFY_10 0x2f #define GPCMD_WRITE_10 0x2a #define GPCMD_WRITE_12 0xaa #define GPCMD_WRITE_AND_VERIFY_10 0x2e #define GPCMD_WRITE_BUFFER 0x3b /* This is listed as optional in ATAPI 2.6, but is (curiously) * missing from Mt. Fuji, Table 57. It _is_ mentioned in Mt. Fuji * Table 377 as an MMC command for SCSi devices though... Most ATAPI * drives support it. */ #define GPCMD_SET_SPEED 0xbb /* This seems to be a SCSI specific CD-ROM opcode * to play data at track/index */ #define GPCMD_PLAYAUDIO_TI 0x48 /* * From MS Media Status Notification Support Specification. For * older drives only. */ #define GPCMD_GET_MEDIA_STATUS 0xda /* Mode page codes for mode sense/set */ #define GPMODE_VENDOR_PAGE 0x00 #define GPMODE_R_W_ERROR_PAGE 0x01 #define GPMODE_WRITE_PARMS_PAGE 0x05 #define GPMODE_WCACHING_PAGE 0x08 #define GPMODE_AUDIO_CTL_PAGE 0x0e #define GPMODE_POWER_PAGE 0x1a #define GPMODE_FAULT_FAIL_PAGE 0x1c #define GPMODE_TO_PROTECT_PAGE 0x1d #define GPMODE_CAPABILITIES_PAGE 0x2a #define GPMODE_ALL_PAGES 0x3f /* Not in Mt. Fuji, but in ATAPI 2.6 -- deprecated now in favor * of MODE_SENSE_POWER_PAGE */ #define GPMODE_CDROM_PAGE 0x0d /* DVD struct types */ #define DVD_STRUCT_PHYSICAL 0x00 #define DVD_STRUCT_COPYRIGHT 0x01 #define DVD_STRUCT_DISCKEY 0x02 #define DVD_STRUCT_BCA 0x03 #define DVD_STRUCT_MANUFACT 0x04 struct dvd_layer { __u8 book_version : 4; __u8 book_type : 4; __u8 min_rate : 4; __u8 disc_size : 4; __u8 layer_type : 4; __u8 track_path : 1; __u8 nlayers : 2; __u8 track_density : 4; __u8 linear_density : 4; __u8 bca : 1; __u32 start_sector; __u32 end_sector; __u32 end_sector_l0; }; #define DVD_LAYERS 4 struct dvd_physical { __u8 type; __u8 layer_num; struct dvd_layer layer[DVD_LAYERS]; }; struct dvd_copyright { __u8 type; __u8 layer_num; __u8 cpst; __u8 rmi; }; struct dvd_disckey { __u8 type; unsigned agid : 2; __u8 value[2048]; }; struct dvd_bca { __u8 type; int len; __u8 value[188]; }; struct dvd_manufact { __u8 type; __u8 layer_num; int len; __u8 value[2048]; }; typedef union { __u8 type; struct dvd_physical physical; struct dvd_copyright copyright; struct dvd_disckey disckey; struct dvd_bca bca; struct dvd_manufact manufact; } dvd_struct; /* * DVD authentication ioctl */ /* Authentication states */ #define DVD_LU_SEND_AGID 0 #define DVD_HOST_SEND_CHALLENGE 1 #define DVD_LU_SEND_KEY1 2 #define DVD_LU_SEND_CHALLENGE 3 #define DVD_HOST_SEND_KEY2 4 /* Termination states */ #define DVD_AUTH_ESTABLISHED 5 #define DVD_AUTH_FAILURE 6 /* Other functions */ #define DVD_LU_SEND_TITLE_KEY 7 #define DVD_LU_SEND_ASF 8 #define DVD_INVALIDATE_AGID 9 #define DVD_LU_SEND_RPC_STATE 10 #define DVD_HOST_SEND_RPC_STATE 11 /* State data */ typedef __u8 dvd_key[5]; /* 40-bit value, MSB is first elem. */ typedef __u8 dvd_challenge[10]; /* 80-bit value, MSB is first elem. */ struct dvd_lu_send_agid { __u8 type; unsigned agid : 2; }; struct dvd_host_send_challenge { __u8 type; unsigned agid : 2; dvd_challenge chal; }; struct dvd_send_key { __u8 type; unsigned agid : 2; dvd_key key; }; struct dvd_lu_send_challenge { __u8 type; unsigned agid : 2; dvd_challenge chal; }; #define DVD_CPM_NO_COPYRIGHT 0 #define DVD_CPM_COPYRIGHTED 1 #define DVD_CP_SEC_NONE 0 #define DVD_CP_SEC_EXIST 1 #define DVD_CGMS_UNRESTRICTED 0 #define DVD_CGMS_SINGLE 2 #define DVD_CGMS_RESTRICTED 3 struct dvd_lu_send_title_key { __u8 type; unsigned agid : 2; dvd_key title_key; int lba; unsigned cpm : 1; unsigned cp_sec : 1; unsigned cgms : 2; }; struct dvd_lu_send_asf { __u8 type; unsigned agid : 2; unsigned asf : 1; }; struct dvd_host_send_rpcstate { __u8 type; __u8 pdrc; }; struct dvd_lu_send_rpcstate { __u8 type : 2; __u8 vra : 3; __u8 ucca : 3; __u8 region_mask; __u8 rpc_scheme; }; typedef union { __u8 type; struct dvd_lu_send_agid lsa; struct dvd_host_send_challenge hsc; struct dvd_send_key lsk; struct dvd_lu_send_challenge lsc; struct dvd_send_key hsk; struct dvd_lu_send_title_key lstk; struct dvd_lu_send_asf lsasf; struct dvd_host_send_rpcstate hrpcs; struct dvd_lu_send_rpcstate lrpcs; } dvd_authinfo; struct request_sense { #if defined(__BIG_ENDIAN_BITFIELD) __u8 valid : 1; __u8 error_code : 7; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 error_code : 7; __u8 valid : 1; #endif __u8 segment_number; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved1 : 2; __u8 ili : 1; __u8 reserved2 : 1; __u8 sense_key : 4; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 sense_key : 4; __u8 reserved2 : 1; __u8 ili : 1; __u8 reserved1 : 2; #endif __u8 information[4]; __u8 add_sense_len; __u8 command_info[4]; __u8 asc; __u8 ascq; __u8 fruc; __u8 sks[3]; __u8 asb[46]; }; /* * feature profile */ #define CDF_RWRT 0x0020 /* "Random Writable" */ #define CDF_HWDM 0x0024 /* "Hardware Defect Management" */ #define CDF_MRW 0x0028 /* * media status bits */ #define CDM_MRW_NOTMRW 0 #define CDM_MRW_BGFORMAT_INACTIVE 1 #define CDM_MRW_BGFORMAT_ACTIVE 2 #define CDM_MRW_BGFORMAT_COMPLETE 3 /* * mrw address spaces */ #define MRW_LBA_DMA 0 #define MRW_LBA_GAA 1 /* * mrw mode pages (first is deprecated) -- probed at init time and * cdi->mrw_mode_page is set */ #define MRW_MODE_PC_PRE1 0x2c #define MRW_MODE_PC 0x03 struct mrw_feature_desc { __be16 feature_code; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved1 : 2; __u8 feature_version : 4; __u8 persistent : 1; __u8 curr : 1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 curr : 1; __u8 persistent : 1; __u8 feature_version : 4; __u8 reserved1 : 2; #endif __u8 add_len; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved2 : 7; __u8 write : 1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 write : 1; __u8 reserved2 : 7; #endif __u8 reserved3; __u8 reserved4; __u8 reserved5; }; /* cf. mmc4r02g.pdf 5.3.10 Random Writable Feature (0020h) pg 197 of 635 */ struct rwrt_feature_desc { __be16 feature_code; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved1 : 2; __u8 feature_version : 4; __u8 persistent : 1; __u8 curr : 1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 curr : 1; __u8 persistent : 1; __u8 feature_version : 4; __u8 reserved1 : 2; #endif __u8 add_len; __u32 last_lba; __u32 block_size; __u16 blocking; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved2 : 7; __u8 page_present : 1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 page_present : 1; __u8 reserved2 : 7; #endif __u8 reserved3; }; typedef struct { __be16 disc_information_length; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved1 : 3; __u8 erasable : 1; __u8 border_status : 2; __u8 disc_status : 2; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 disc_status : 2; __u8 border_status : 2; __u8 erasable : 1; __u8 reserved1 : 3; #else #error "Please fix " #endif __u8 n_first_track; __u8 n_sessions_lsb; __u8 first_track_lsb; __u8 last_track_lsb; #if defined(__BIG_ENDIAN_BITFIELD) __u8 did_v : 1; __u8 dbc_v : 1; __u8 uru : 1; __u8 reserved2 : 2; __u8 dbit : 1; __u8 mrw_status : 2; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 mrw_status : 2; __u8 dbit : 1; __u8 reserved2 : 2; __u8 uru : 1; __u8 dbc_v : 1; __u8 did_v : 1; #endif __u8 disc_type; __u8 n_sessions_msb; __u8 first_track_msb; __u8 last_track_msb; __u32 disc_id; __u32 lead_in; __u32 lead_out; __u8 disc_bar_code[8]; __u8 reserved3; __u8 n_opc; } disc_information; typedef struct { __be16 track_information_length; __u8 track_lsb; __u8 session_lsb; __u8 reserved1; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved2 : 2; __u8 damage : 1; __u8 copy : 1; __u8 track_mode : 4; __u8 rt : 1; __u8 blank : 1; __u8 packet : 1; __u8 fp : 1; __u8 data_mode : 4; __u8 reserved3 : 6; __u8 lra_v : 1; __u8 nwa_v : 1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 track_mode : 4; __u8 copy : 1; __u8 damage : 1; __u8 reserved2 : 2; __u8 data_mode : 4; __u8 fp : 1; __u8 packet : 1; __u8 blank : 1; __u8 rt : 1; __u8 nwa_v : 1; __u8 lra_v : 1; __u8 reserved3 : 6; #endif __be32 track_start; __be32 next_writable; __be32 free_blocks; __be32 fixed_packet_size; __be32 track_size; __be32 last_rec_address; } track_information; struct feature_header { __u32 data_len; __u8 reserved1; __u8 reserved2; __u16 curr_profile; }; struct mode_page_header { __be16 mode_data_length; __u8 medium_type; __u8 reserved1; __u8 reserved2; __u8 reserved3; __be16 desc_length; }; /* removable medium feature descriptor */ struct rm_feature_desc { __be16 feature_code; #if defined(__BIG_ENDIAN_BITFIELD) __u8 reserved1:2; __u8 feature_version:4; __u8 persistent:1; __u8 curr:1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 curr:1; __u8 persistent:1; __u8 feature_version:4; __u8 reserved1:2; #endif __u8 add_len; #if defined(__BIG_ENDIAN_BITFIELD) __u8 mech_type:3; __u8 load:1; __u8 eject:1; __u8 pvnt_jmpr:1; __u8 dbml:1; __u8 lock:1; #elif defined(__LITTLE_ENDIAN_BITFIELD) __u8 lock:1; __u8 dbml:1; __u8 pvnt_jmpr:1; __u8 eject:1; __u8 load:1; __u8 mech_type:3; #endif __u8 reserved2; __u8 reserved3; __u8 reserved4; }; #endif /* _LINUX_CDROM_H */ linux/atmclip.h000064400000001100151027430560007500 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmclip.h - Classical IP over ATM */ /* Written 1995-1998 by Werner Almesberger, EPFL LRC/ICA */ #ifndef LINUX_ATMCLIP_H #define LINUX_ATMCLIP_H #include #include #define RFC1483LLC_LEN 8 /* LLC+OUI+PID = 8 */ #define RFC1626_MTU 9180 /* RFC1626 default MTU */ #define CLIP_DEFAULT_IDLETIMER 1200 /* 20 minutes, see RFC1755 */ #define CLIP_CHECK_INTERVAL 10 /* check every ten seconds */ #define SIOCMKCLIP _IO('a',ATMIOC_CLIP) /* create IP interface */ #endif linux/virtio_console.h000064400000006100151027430560011112 0ustar00/* * This header, excluding the #ifdef __KERNEL__ part, is BSD licensed so * anyone can use the definitions to implement compatible drivers/servers: * * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Copyright (C) Red Hat, Inc., 2009, 2010, 2011 * Copyright (C) Amit Shah , 2009, 2010, 2011 */ #ifndef _LINUX_VIRTIO_CONSOLE_H #define _LINUX_VIRTIO_CONSOLE_H #include #include #include #include /* Feature bits */ #define VIRTIO_CONSOLE_F_SIZE 0 /* Does host provide console size? */ #define VIRTIO_CONSOLE_F_MULTIPORT 1 /* Does host provide multiple ports? */ #define VIRTIO_CONSOLE_F_EMERG_WRITE 2 /* Does host support emergency write? */ #define VIRTIO_CONSOLE_BAD_ID (~(__u32)0) struct virtio_console_config { /* colums of the screens */ __u16 cols; /* rows of the screens */ __u16 rows; /* max. number of ports this device can hold */ __u32 max_nr_ports; /* emergency write register */ __u32 emerg_wr; } __attribute__((packed)); /* * A message that's passed between the Host and the Guest for a * particular port. */ struct virtio_console_control { __virtio32 id; /* Port number */ __virtio16 event; /* The kind of control event (see below) */ __virtio16 value; /* Extra information for the key */ }; /* Some events for control messages */ #define VIRTIO_CONSOLE_DEVICE_READY 0 #define VIRTIO_CONSOLE_PORT_ADD 1 #define VIRTIO_CONSOLE_PORT_REMOVE 2 #define VIRTIO_CONSOLE_PORT_READY 3 #define VIRTIO_CONSOLE_CONSOLE_PORT 4 #define VIRTIO_CONSOLE_RESIZE 5 #define VIRTIO_CONSOLE_PORT_OPEN 6 #define VIRTIO_CONSOLE_PORT_NAME 7 #endif /* _LINUX_VIRTIO_CONSOLE_H */ linux/elf.h000064400000032237151027430560006634 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_ELF_H #define _LINUX_ELF_H #include #include /* 32-bit ELF base types. */ typedef __u32 Elf32_Addr; typedef __u16 Elf32_Half; typedef __u32 Elf32_Off; typedef __s32 Elf32_Sword; typedef __u32 Elf32_Word; /* 64-bit ELF base types. */ typedef __u64 Elf64_Addr; typedef __u16 Elf64_Half; typedef __s16 Elf64_SHalf; typedef __u64 Elf64_Off; typedef __s32 Elf64_Sword; typedef __u32 Elf64_Word; typedef __u64 Elf64_Xword; typedef __s64 Elf64_Sxword; /* These constants are for the segment types stored in the image headers */ #define PT_NULL 0 #define PT_LOAD 1 #define PT_DYNAMIC 2 #define PT_INTERP 3 #define PT_NOTE 4 #define PT_SHLIB 5 #define PT_PHDR 6 #define PT_TLS 7 /* Thread local storage segment */ #define PT_LOOS 0x60000000 /* OS-specific */ #define PT_HIOS 0x6fffffff /* OS-specific */ #define PT_LOPROC 0x70000000 #define PT_HIPROC 0x7fffffff #define PT_GNU_EH_FRAME 0x6474e550 #define PT_GNU_STACK (PT_LOOS + 0x474e551) /* * Extended Numbering * * If the real number of program header table entries is larger than * or equal to PN_XNUM(0xffff), it is set to sh_info field of the * section header at index 0, and PN_XNUM is set to e_phnum * field. Otherwise, the section header at index 0 is zero * initialized, if it exists. * * Specifications are available in: * * - Oracle: Linker and Libraries. * Part No: 817–1984–19, August 2011. * http://docs.oracle.com/cd/E18752_01/pdf/817-1984.pdf * * - System V ABI AMD64 Architecture Processor Supplement * Draft Version 0.99.4, * January 13, 2010. * http://www.cs.washington.edu/education/courses/cse351/12wi/supp-docs/abi.pdf */ #define PN_XNUM 0xffff /* These constants define the different elf file types */ #define ET_NONE 0 #define ET_REL 1 #define ET_EXEC 2 #define ET_DYN 3 #define ET_CORE 4 #define ET_LOPROC 0xff00 #define ET_HIPROC 0xffff /* This is the info that is needed to parse the dynamic section of the file */ #define DT_NULL 0 #define DT_NEEDED 1 #define DT_PLTRELSZ 2 #define DT_PLTGOT 3 #define DT_HASH 4 #define DT_STRTAB 5 #define DT_SYMTAB 6 #define DT_RELA 7 #define DT_RELASZ 8 #define DT_RELAENT 9 #define DT_STRSZ 10 #define DT_SYMENT 11 #define DT_INIT 12 #define DT_FINI 13 #define DT_SONAME 14 #define DT_RPATH 15 #define DT_SYMBOLIC 16 #define DT_REL 17 #define DT_RELSZ 18 #define DT_RELENT 19 #define DT_PLTREL 20 #define DT_DEBUG 21 #define DT_TEXTREL 22 #define DT_JMPREL 23 #define DT_ENCODING 32 #define OLD_DT_LOOS 0x60000000 #define DT_LOOS 0x6000000d #define DT_HIOS 0x6ffff000 #define DT_VALRNGLO 0x6ffffd00 #define DT_VALRNGHI 0x6ffffdff #define DT_ADDRRNGLO 0x6ffffe00 #define DT_ADDRRNGHI 0x6ffffeff #define DT_VERSYM 0x6ffffff0 #define DT_RELACOUNT 0x6ffffff9 #define DT_RELCOUNT 0x6ffffffa #define DT_FLAGS_1 0x6ffffffb #define DT_VERDEF 0x6ffffffc #define DT_VERDEFNUM 0x6ffffffd #define DT_VERNEED 0x6ffffffe #define DT_VERNEEDNUM 0x6fffffff #define OLD_DT_HIOS 0x6fffffff #define DT_LOPROC 0x70000000 #define DT_HIPROC 0x7fffffff /* This info is needed when parsing the symbol table */ #define STB_LOCAL 0 #define STB_GLOBAL 1 #define STB_WEAK 2 #define STT_NOTYPE 0 #define STT_OBJECT 1 #define STT_FUNC 2 #define STT_SECTION 3 #define STT_FILE 4 #define STT_COMMON 5 #define STT_TLS 6 #define ELF_ST_BIND(x) ((x) >> 4) #define ELF_ST_TYPE(x) (((unsigned int) x) & 0xf) #define ELF32_ST_BIND(x) ELF_ST_BIND(x) #define ELF32_ST_TYPE(x) ELF_ST_TYPE(x) #define ELF64_ST_BIND(x) ELF_ST_BIND(x) #define ELF64_ST_TYPE(x) ELF_ST_TYPE(x) typedef struct dynamic{ Elf32_Sword d_tag; union{ Elf32_Sword d_val; Elf32_Addr d_ptr; } d_un; } Elf32_Dyn; typedef struct { Elf64_Sxword d_tag; /* entry tag value */ union { Elf64_Xword d_val; Elf64_Addr d_ptr; } d_un; } Elf64_Dyn; /* The following are used with relocations */ #define ELF32_R_SYM(x) ((x) >> 8) #define ELF32_R_TYPE(x) ((x) & 0xff) #define ELF64_R_SYM(i) ((i) >> 32) #define ELF64_R_TYPE(i) ((i) & 0xffffffff) typedef struct elf32_rel { Elf32_Addr r_offset; Elf32_Word r_info; } Elf32_Rel; typedef struct elf64_rel { Elf64_Addr r_offset; /* Location at which to apply the action */ Elf64_Xword r_info; /* index and type of relocation */ } Elf64_Rel; typedef struct elf32_rela{ Elf32_Addr r_offset; Elf32_Word r_info; Elf32_Sword r_addend; } Elf32_Rela; typedef struct elf64_rela { Elf64_Addr r_offset; /* Location at which to apply the action */ Elf64_Xword r_info; /* index and type of relocation */ Elf64_Sxword r_addend; /* Constant addend used to compute value */ } Elf64_Rela; typedef struct elf32_sym{ Elf32_Word st_name; Elf32_Addr st_value; Elf32_Word st_size; unsigned char st_info; unsigned char st_other; Elf32_Half st_shndx; } Elf32_Sym; typedef struct elf64_sym { Elf64_Word st_name; /* Symbol name, index in string tbl */ unsigned char st_info; /* Type and binding attributes */ unsigned char st_other; /* No defined meaning, 0 */ Elf64_Half st_shndx; /* Associated section index */ Elf64_Addr st_value; /* Value of the symbol */ Elf64_Xword st_size; /* Associated symbol size */ } Elf64_Sym; #define EI_NIDENT 16 typedef struct elf32_hdr{ unsigned char e_ident[EI_NIDENT]; Elf32_Half e_type; Elf32_Half e_machine; Elf32_Word e_version; Elf32_Addr e_entry; /* Entry point */ Elf32_Off e_phoff; Elf32_Off e_shoff; Elf32_Word e_flags; Elf32_Half e_ehsize; Elf32_Half e_phentsize; Elf32_Half e_phnum; Elf32_Half e_shentsize; Elf32_Half e_shnum; Elf32_Half e_shstrndx; } Elf32_Ehdr; typedef struct elf64_hdr { unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */ Elf64_Half e_type; Elf64_Half e_machine; Elf64_Word e_version; Elf64_Addr e_entry; /* Entry point virtual address */ Elf64_Off e_phoff; /* Program header table file offset */ Elf64_Off e_shoff; /* Section header table file offset */ Elf64_Word e_flags; Elf64_Half e_ehsize; Elf64_Half e_phentsize; Elf64_Half e_phnum; Elf64_Half e_shentsize; Elf64_Half e_shnum; Elf64_Half e_shstrndx; } Elf64_Ehdr; /* These constants define the permissions on sections in the program header, p_flags. */ #define PF_R 0x4 #define PF_W 0x2 #define PF_X 0x1 typedef struct elf32_phdr{ Elf32_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf32_Word p_filesz; Elf32_Word p_memsz; Elf32_Word p_flags; Elf32_Word p_align; } Elf32_Phdr; typedef struct elf64_phdr { Elf64_Word p_type; Elf64_Word p_flags; Elf64_Off p_offset; /* Segment file offset */ Elf64_Addr p_vaddr; /* Segment virtual address */ Elf64_Addr p_paddr; /* Segment physical address */ Elf64_Xword p_filesz; /* Segment size in file */ Elf64_Xword p_memsz; /* Segment size in memory */ Elf64_Xword p_align; /* Segment alignment, file & memory */ } Elf64_Phdr; /* sh_type */ #define SHT_NULL 0 #define SHT_PROGBITS 1 #define SHT_SYMTAB 2 #define SHT_STRTAB 3 #define SHT_RELA 4 #define SHT_HASH 5 #define SHT_DYNAMIC 6 #define SHT_NOTE 7 #define SHT_NOBITS 8 #define SHT_REL 9 #define SHT_SHLIB 10 #define SHT_DYNSYM 11 #define SHT_NUM 12 #define SHT_LOPROC 0x70000000 #define SHT_HIPROC 0x7fffffff #define SHT_LOUSER 0x80000000 #define SHT_HIUSER 0xffffffff /* sh_flags */ #define SHF_WRITE 0x1 #define SHF_ALLOC 0x2 #define SHF_EXECINSTR 0x4 #define SHF_RELA_LIVEPATCH 0x00100000 #define SHF_RO_AFTER_INIT 0x00200000 #define SHF_MASKPROC 0xf0000000 /* special section indexes */ #define SHN_UNDEF 0 #define SHN_LORESERVE 0xff00 #define SHN_LOPROC 0xff00 #define SHN_HIPROC 0xff1f #define SHN_LIVEPATCH 0xff20 #define SHN_ABS 0xfff1 #define SHN_COMMON 0xfff2 #define SHN_HIRESERVE 0xffff typedef struct elf32_shdr { Elf32_Word sh_name; Elf32_Word sh_type; Elf32_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf32_Word sh_size; Elf32_Word sh_link; Elf32_Word sh_info; Elf32_Word sh_addralign; Elf32_Word sh_entsize; } Elf32_Shdr; typedef struct elf64_shdr { Elf64_Word sh_name; /* Section name, index in string tbl */ Elf64_Word sh_type; /* Type of section */ Elf64_Xword sh_flags; /* Miscellaneous section attributes */ Elf64_Addr sh_addr; /* Section virtual addr at execution */ Elf64_Off sh_offset; /* Section file offset */ Elf64_Xword sh_size; /* Size of section in bytes */ Elf64_Word sh_link; /* Index of another section */ Elf64_Word sh_info; /* Additional section information */ Elf64_Xword sh_addralign; /* Section alignment */ Elf64_Xword sh_entsize; /* Entry size if section holds table */ } Elf64_Shdr; #define EI_MAG0 0 /* e_ident[] indexes */ #define EI_MAG1 1 #define EI_MAG2 2 #define EI_MAG3 3 #define EI_CLASS 4 #define EI_DATA 5 #define EI_VERSION 6 #define EI_OSABI 7 #define EI_PAD 8 #define ELFMAG0 0x7f /* EI_MAG */ #define ELFMAG1 'E' #define ELFMAG2 'L' #define ELFMAG3 'F' #define ELFMAG "\177ELF" #define SELFMAG 4 #define ELFCLASSNONE 0 /* EI_CLASS */ #define ELFCLASS32 1 #define ELFCLASS64 2 #define ELFCLASSNUM 3 #define ELFDATANONE 0 /* e_ident[EI_DATA] */ #define ELFDATA2LSB 1 #define ELFDATA2MSB 2 #define EV_NONE 0 /* e_version, EI_VERSION */ #define EV_CURRENT 1 #define EV_NUM 2 #define ELFOSABI_NONE 0 #define ELFOSABI_LINUX 3 #ifndef ELF_OSABI #define ELF_OSABI ELFOSABI_NONE #endif /* * Notes used in ET_CORE. Architectures export some of the arch register sets * using the corresponding note types via the PTRACE_GETREGSET and * PTRACE_SETREGSET requests. */ #define NT_PRSTATUS 1 #define NT_PRFPREG 2 #define NT_PRPSINFO 3 #define NT_TASKSTRUCT 4 #define NT_AUXV 6 /* * Note to userspace developers: size of NT_SIGINFO note may increase * in the future to accomodate more fields, don't assume it is fixed! */ #define NT_SIGINFO 0x53494749 #define NT_FILE 0x46494c45 #define NT_PRXFPREG 0x46e62b7f /* copied from gdb5.1/include/elf/common.h */ #define NT_PPC_VMX 0x100 /* PowerPC Altivec/VMX registers */ #define NT_PPC_SPE 0x101 /* PowerPC SPE/EVR registers */ #define NT_PPC_VSX 0x102 /* PowerPC VSX registers */ #define NT_PPC_TAR 0x103 /* Target Address Register */ #define NT_PPC_PPR 0x104 /* Program Priority Register */ #define NT_PPC_DSCR 0x105 /* Data Stream Control Register */ #define NT_PPC_EBB 0x106 /* Event Based Branch Registers */ #define NT_PPC_PMU 0x107 /* Performance Monitor Registers */ #define NT_PPC_TM_CGPR 0x108 /* TM checkpointed GPR Registers */ #define NT_PPC_TM_CFPR 0x109 /* TM checkpointed FPR Registers */ #define NT_PPC_TM_CVMX 0x10a /* TM checkpointed VMX Registers */ #define NT_PPC_TM_CVSX 0x10b /* TM checkpointed VSX Registers */ #define NT_PPC_TM_SPR 0x10c /* TM Special Purpose Registers */ #define NT_PPC_TM_CTAR 0x10d /* TM checkpointed Target Address Register */ #define NT_PPC_TM_CPPR 0x10e /* TM checkpointed Program Priority Register */ #define NT_PPC_TM_CDSCR 0x10f /* TM checkpointed Data Stream Control Register */ #define NT_PPC_PKEY 0x110 /* Memory Protection Keys registers */ #define NT_386_TLS 0x200 /* i386 TLS slots (struct user_desc) */ #define NT_386_IOPERM 0x201 /* x86 io permission bitmap (1=deny) */ #define NT_X86_XSTATE 0x202 /* x86 extended state using xsave */ #define NT_S390_HIGH_GPRS 0x300 /* s390 upper register halves */ #define NT_S390_TIMER 0x301 /* s390 timer register */ #define NT_S390_TODCMP 0x302 /* s390 TOD clock comparator register */ #define NT_S390_TODPREG 0x303 /* s390 TOD programmable register */ #define NT_S390_CTRS 0x304 /* s390 control registers */ #define NT_S390_PREFIX 0x305 /* s390 prefix register */ #define NT_S390_LAST_BREAK 0x306 /* s390 breaking event address */ #define NT_S390_SYSTEM_CALL 0x307 /* s390 system call restart data */ #define NT_S390_TDB 0x308 /* s390 transaction diagnostic block */ #define NT_S390_VXRS_LOW 0x309 /* s390 vector registers 0-15 upper half */ #define NT_S390_VXRS_HIGH 0x30a /* s390 vector registers 16-31 */ #define NT_S390_GS_CB 0x30b /* s390 guarded storage registers */ #define NT_S390_GS_BC 0x30c /* s390 guarded storage broadcast control block */ #define NT_S390_RI_CB 0x30d /* s390 runtime instrumentation */ #define NT_ARM_VFP 0x400 /* ARM VFP/NEON registers */ #define NT_ARM_TLS 0x401 /* ARM TLS register */ #define NT_ARM_HW_BREAK 0x402 /* ARM hardware breakpoint registers */ #define NT_ARM_HW_WATCH 0x403 /* ARM hardware watchpoint registers */ #define NT_ARM_SYSTEM_CALL 0x404 /* ARM system call number */ #define NT_ARM_SVE 0x405 /* ARM Scalable Vector Extension registers */ #define NT_ARM_PAC_MASK 0x406 /* ARM pointer authentication code masks */ #define NT_ARM_PACA_KEYS 0x407 /* ARM pointer authentication address keys */ #define NT_ARM_PACG_KEYS 0x408 /* ARM pointer authentication generic key */ #define NT_ARC_V2 0x600 /* ARCv2 accumulator/extra registers */ #define NT_VMCOREDD 0x700 /* Vmcore Device Dump Note */ /* Note header in a PT_NOTE section */ typedef struct elf32_note { Elf32_Word n_namesz; /* Name size */ Elf32_Word n_descsz; /* Content size */ Elf32_Word n_type; /* Content type */ } Elf32_Nhdr; /* Note header in a PT_NOTE section */ typedef struct elf64_note { Elf64_Word n_namesz; /* Name size */ Elf64_Word n_descsz; /* Content size */ Elf64_Word n_type; /* Content type */ } Elf64_Nhdr; #endif /* _LINUX_ELF_H */ linux/arm_sdei.h000064400000005277151027430560007655 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (C) 2017 Arm Ltd. */ #ifndef _LINUX_ARM_SDEI_H #define _LINUX_ARM_SDEI_H #define SDEI_1_0_FN_BASE 0xC4000020 #define SDEI_1_0_MASK 0xFFFFFFE0 #define SDEI_1_0_FN(n) (SDEI_1_0_FN_BASE + (n)) #define SDEI_1_0_FN_SDEI_VERSION SDEI_1_0_FN(0x00) #define SDEI_1_0_FN_SDEI_EVENT_REGISTER SDEI_1_0_FN(0x01) #define SDEI_1_0_FN_SDEI_EVENT_ENABLE SDEI_1_0_FN(0x02) #define SDEI_1_0_FN_SDEI_EVENT_DISABLE SDEI_1_0_FN(0x03) #define SDEI_1_0_FN_SDEI_EVENT_CONTEXT SDEI_1_0_FN(0x04) #define SDEI_1_0_FN_SDEI_EVENT_COMPLETE SDEI_1_0_FN(0x05) #define SDEI_1_0_FN_SDEI_EVENT_COMPLETE_AND_RESUME SDEI_1_0_FN(0x06) #define SDEI_1_0_FN_SDEI_EVENT_UNREGISTER SDEI_1_0_FN(0x07) #define SDEI_1_0_FN_SDEI_EVENT_STATUS SDEI_1_0_FN(0x08) #define SDEI_1_0_FN_SDEI_EVENT_GET_INFO SDEI_1_0_FN(0x09) #define SDEI_1_0_FN_SDEI_EVENT_ROUTING_SET SDEI_1_0_FN(0x0A) #define SDEI_1_0_FN_SDEI_PE_MASK SDEI_1_0_FN(0x0B) #define SDEI_1_0_FN_SDEI_PE_UNMASK SDEI_1_0_FN(0x0C) #define SDEI_1_0_FN_SDEI_INTERRUPT_BIND SDEI_1_0_FN(0x0D) #define SDEI_1_0_FN_SDEI_INTERRUPT_RELEASE SDEI_1_0_FN(0x0E) #define SDEI_1_0_FN_SDEI_PRIVATE_RESET SDEI_1_0_FN(0x11) #define SDEI_1_0_FN_SDEI_SHARED_RESET SDEI_1_0_FN(0x12) #define SDEI_VERSION_MAJOR_SHIFT 48 #define SDEI_VERSION_MAJOR_MASK 0x7fff #define SDEI_VERSION_MINOR_SHIFT 32 #define SDEI_VERSION_MINOR_MASK 0xffff #define SDEI_VERSION_VENDOR_SHIFT 0 #define SDEI_VERSION_VENDOR_MASK 0xffffffff #define SDEI_VERSION_MAJOR(x) (x>>SDEI_VERSION_MAJOR_SHIFT & SDEI_VERSION_MAJOR_MASK) #define SDEI_VERSION_MINOR(x) (x>>SDEI_VERSION_MINOR_SHIFT & SDEI_VERSION_MINOR_MASK) #define SDEI_VERSION_VENDOR(x) (x>>SDEI_VERSION_VENDOR_SHIFT & SDEI_VERSION_VENDOR_MASK) /* SDEI return values */ #define SDEI_SUCCESS 0 #define SDEI_NOT_SUPPORTED -1 #define SDEI_INVALID_PARAMETERS -2 #define SDEI_DENIED -3 #define SDEI_PENDING -5 #define SDEI_OUT_OF_RESOURCE -10 /* EVENT_REGISTER flags */ #define SDEI_EVENT_REGISTER_RM_ANY 0 #define SDEI_EVENT_REGISTER_RM_PE 1 /* EVENT_STATUS return value bits */ #define SDEI_EVENT_STATUS_RUNNING 2 #define SDEI_EVENT_STATUS_ENABLED 1 #define SDEI_EVENT_STATUS_REGISTERED 0 /* EVENT_COMPLETE status values */ #define SDEI_EV_HANDLED 0 #define SDEI_EV_FAILED 1 /* GET_INFO values */ #define SDEI_EVENT_INFO_EV_TYPE 0 #define SDEI_EVENT_INFO_EV_SIGNALED 1 #define SDEI_EVENT_INFO_EV_PRIORITY 2 #define SDEI_EVENT_INFO_EV_ROUTING_MODE 3 #define SDEI_EVENT_INFO_EV_ROUTING_AFF 4 /* and their results */ #define SDEI_EVENT_TYPE_PRIVATE 0 #define SDEI_EVENT_TYPE_SHARED 1 #define SDEI_EVENT_PRIORITY_NORMAL 0 #define SDEI_EVENT_PRIORITY_CRITICAL 1 #endif /* _LINUX_ARM_SDEI_H */ linux/mmc/ioctl.h000064400000004355151027430560007754 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef LINUX_MMC_IOCTL_H #define LINUX_MMC_IOCTL_H #include struct mmc_ioc_cmd { /* Implies direction of data. true = write, false = read */ int write_flag; /* Application-specific command. true = precede with CMD55 */ int is_acmd; __u32 opcode; __u32 arg; __u32 response[4]; /* CMD response */ unsigned int flags; unsigned int blksz; unsigned int blocks; /* * Sleep at least postsleep_min_us useconds, and at most * postsleep_max_us useconds *after* issuing command. Needed for * some read commands for which cards have no other way of indicating * they're ready for the next command (i.e. there is no equivalent of * a "busy" indicator for read operations). */ unsigned int postsleep_min_us; unsigned int postsleep_max_us; /* * Override driver-computed timeouts. Note the difference in units! */ unsigned int data_timeout_ns; unsigned int cmd_timeout_ms; /* * For 64-bit machines, the next member, ``__u64 data_ptr``, wants to * be 8-byte aligned. Make sure this struct is the same size when * built for 32-bit. */ __u32 __pad; /* DAT buffer */ __u64 data_ptr; }; #define mmc_ioc_cmd_set_data(ic, ptr) ic.data_ptr = (__u64)(unsigned long) ptr /** * struct mmc_ioc_multi_cmd - multi command information * @num_of_cmds: Number of commands to send. Must be equal to or less than * MMC_IOC_MAX_CMDS. * @cmds: Array of commands with length equal to 'num_of_cmds' */ struct mmc_ioc_multi_cmd { __u64 num_of_cmds; struct mmc_ioc_cmd cmds[0]; }; #define MMC_IOC_CMD _IOWR(MMC_BLOCK_MAJOR, 0, struct mmc_ioc_cmd) /* * MMC_IOC_MULTI_CMD: Used to send an array of MMC commands described by * the structure mmc_ioc_multi_cmd. The MMC driver will issue all * commands in array in sequence to card. */ #define MMC_IOC_MULTI_CMD _IOWR(MMC_BLOCK_MAJOR, 1, struct mmc_ioc_multi_cmd) /* * Since this ioctl is only meant to enhance (and not replace) normal access * to the mmc bus device, an upper data transfer limit of MMC_IOC_MAX_BYTES * is enforced per ioctl call. For larger data transfers, use the normal * block device operations. */ #define MMC_IOC_MAX_BYTES (512L * 1024) #define MMC_IOC_MAX_CMDS 255 #endif /* LINUX_MMC_IOCTL_H */ linux/netfilter.h000064400000003434151027430560010057 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_NETFILTER_H #define __LINUX_NETFILTER_H #include #include #include /* Responses from hook functions. */ #define NF_DROP 0 #define NF_ACCEPT 1 #define NF_STOLEN 2 #define NF_QUEUE 3 #define NF_REPEAT 4 #define NF_STOP 5 /* Deprecated, for userspace nf_queue compatibility. */ #define NF_MAX_VERDICT NF_STOP /* we overload the higher bits for encoding auxiliary data such as the queue * number or errno values. Not nice, but better than additional function * arguments. */ #define NF_VERDICT_MASK 0x000000ff /* extra verdict flags have mask 0x0000ff00 */ #define NF_VERDICT_FLAG_QUEUE_BYPASS 0x00008000 /* queue number (NF_QUEUE) or errno (NF_DROP) */ #define NF_VERDICT_QMASK 0xffff0000 #define NF_VERDICT_QBITS 16 #define NF_QUEUE_NR(x) ((((x) << 16) & NF_VERDICT_QMASK) | NF_QUEUE) #define NF_DROP_ERR(x) (((-x) << 16) | NF_DROP) /* only for userspace compatibility */ /* Generic cache responses from hook functions. <= 0x2000 is used for protocol-flags. */ #define NFC_UNKNOWN 0x4000 #define NFC_ALTERED 0x8000 /* NF_VERDICT_BITS should be 8 now, but userspace might break if this changes */ #define NF_VERDICT_BITS 16 enum nf_inet_hooks { NF_INET_PRE_ROUTING, NF_INET_LOCAL_IN, NF_INET_FORWARD, NF_INET_LOCAL_OUT, NF_INET_POST_ROUTING, NF_INET_NUMHOOKS }; enum nf_dev_hooks { NF_NETDEV_INGRESS, NF_NETDEV_NUMHOOKS }; enum { NFPROTO_UNSPEC = 0, NFPROTO_INET = 1, NFPROTO_IPV4 = 2, NFPROTO_ARP = 3, NFPROTO_NETDEV = 5, NFPROTO_BRIDGE = 7, NFPROTO_IPV6 = 10, NFPROTO_DECNET = 12, NFPROTO_NUMPROTO, }; union nf_inet_addr { __u32 all[4]; __be32 ip; __be32 ip6[4]; struct in_addr in; struct in6_addr in6; }; #endif /* __LINUX_NETFILTER_H */ linux/flat.h000064400000004144151027430560007010 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2002-2003 David McCullough * Copyright (C) 1998 Kenneth Albanowski * The Silver Hammer Group, Ltd. * * This file provides the definitions and structures needed to * support uClinux flat-format executables. */ #ifndef _LINUX_FLAT_H #define _LINUX_FLAT_H #define FLAT_VERSION 0x00000004L #ifdef CONFIG_BINFMT_SHARED_FLAT #define MAX_SHARED_LIBS (4) #else #define MAX_SHARED_LIBS (1) #endif /* * To make everything easier to port and manage cross platform * development, all fields are in network byte order. */ struct flat_hdr { char magic[4]; unsigned long rev; /* version (as above) */ unsigned long entry; /* Offset of first executable instruction with text segment from beginning of file */ unsigned long data_start; /* Offset of data segment from beginning of file */ unsigned long data_end; /* Offset of end of data segment from beginning of file */ unsigned long bss_end; /* Offset of end of bss segment from beginning of file */ /* (It is assumed that data_end through bss_end forms the bss segment.) */ unsigned long stack_size; /* Size of stack, in bytes */ unsigned long reloc_start; /* Offset of relocation records from beginning of file */ unsigned long reloc_count; /* Number of relocation records */ unsigned long flags; unsigned long build_date; /* When the program/library was built */ unsigned long filler[5]; /* Reservered, set to zero */ }; #define FLAT_FLAG_RAM 0x0001 /* load program entirely into RAM */ #define FLAT_FLAG_GOTPIC 0x0002 /* program is PIC with GOT */ #define FLAT_FLAG_GZIP 0x0004 /* all but the header is compressed */ #define FLAT_FLAG_GZDATA 0x0008 /* only data/relocs are compressed (for XIP) */ #define FLAT_FLAG_KTRACE 0x0010 /* output useful kernel trace for debugging */ #endif /* _LINUX_FLAT_H */ linux/cciss_defs.h000064400000006321151027430560010166 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef CCISS_DEFS_H #define CCISS_DEFS_H #include /* general boundary definitions */ #define SENSEINFOBYTES 32 /* note that this value may vary between host implementations */ /* Command Status value */ #define CMD_SUCCESS 0x0000 #define CMD_TARGET_STATUS 0x0001 #define CMD_DATA_UNDERRUN 0x0002 #define CMD_DATA_OVERRUN 0x0003 #define CMD_INVALID 0x0004 #define CMD_PROTOCOL_ERR 0x0005 #define CMD_HARDWARE_ERR 0x0006 #define CMD_CONNECTION_LOST 0x0007 #define CMD_ABORTED 0x0008 #define CMD_ABORT_FAILED 0x0009 #define CMD_UNSOLICITED_ABORT 0x000A #define CMD_TIMEOUT 0x000B #define CMD_UNABORTABLE 0x000C /* transfer direction */ #define XFER_NONE 0x00 #define XFER_WRITE 0x01 #define XFER_READ 0x02 #define XFER_RSVD 0x03 /* task attribute */ #define ATTR_UNTAGGED 0x00 #define ATTR_SIMPLE 0x04 #define ATTR_HEADOFQUEUE 0x05 #define ATTR_ORDERED 0x06 #define ATTR_ACA 0x07 /* cdb type */ #define TYPE_CMD 0x00 #define TYPE_MSG 0x01 /* Type defs used in the following structs */ #define BYTE __u8 #define WORD __u16 #define HWORD __u16 #define DWORD __u32 #define CISS_MAX_LUN 1024 #define LEVEL2LUN 1 /* index into Target(x) structure, due to byte swapping */ #define LEVEL3LUN 0 #pragma pack(1) /* Command List Structure */ typedef union _SCSI3Addr_struct { struct { BYTE Dev; BYTE Bus:6; BYTE Mode:2; /* b00 */ } PeripDev; struct { BYTE DevLSB; BYTE DevMSB:6; BYTE Mode:2; /* b01 */ } LogDev; struct { BYTE Dev:5; BYTE Bus:3; BYTE Targ:6; BYTE Mode:2; /* b10 */ } LogUnit; } SCSI3Addr_struct; typedef struct _PhysDevAddr_struct { DWORD TargetId:24; DWORD Bus:6; DWORD Mode:2; SCSI3Addr_struct Target[2]; /* 2 level target device addr */ } PhysDevAddr_struct; typedef struct _LogDevAddr_struct { DWORD VolId:30; DWORD Mode:2; BYTE reserved[4]; } LogDevAddr_struct; typedef union _LUNAddr_struct { BYTE LunAddrBytes[8]; SCSI3Addr_struct SCSI3Lun[4]; PhysDevAddr_struct PhysDev; LogDevAddr_struct LogDev; } LUNAddr_struct; typedef struct _RequestBlock_struct { BYTE CDBLen; struct { BYTE Type:3; BYTE Attribute:3; BYTE Direction:2; } Type; HWORD Timeout; BYTE CDB[16]; } RequestBlock_struct; typedef union _MoreErrInfo_struct{ struct { BYTE Reserved[3]; BYTE Type; DWORD ErrorInfo; } Common_Info; struct{ BYTE Reserved[2]; BYTE offense_size; /* size of offending entry */ BYTE offense_num; /* byte # of offense 0-base */ DWORD offense_value; } Invalid_Cmd; } MoreErrInfo_struct; typedef struct _ErrorInfo_struct { BYTE ScsiStatus; BYTE SenseLen; HWORD CommandStatus; DWORD ResidualCnt; MoreErrInfo_struct MoreErrInfo; BYTE SenseInfo[SENSEINFOBYTES]; } ErrorInfo_struct; #pragma pack() #endif /* CCISS_DEFS_H */ linux/v4l2-controls.h000064400000145101151027430560010511 0ustar00/* SPDX-License-Identifier: ((GPL-2.0+ WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Video for Linux Two controls header file * * Copyright (C) 1999-2012 the contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Alternatively you can redistribute this file under the terms of the * BSD license as stated below: * * 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 names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The contents of this header was split off from videodev2.h. All control * definitions should be added to this header, which is included by * videodev2.h. */ #ifndef __LINUX_V4L2_CONTROLS_H #define __LINUX_V4L2_CONTROLS_H #include /* Control classes */ #define V4L2_CTRL_CLASS_USER 0x00980000 /* Old-style 'user' controls */ #define V4L2_CTRL_CLASS_MPEG 0x00990000 /* MPEG-compression controls */ #define V4L2_CTRL_CLASS_CAMERA 0x009a0000 /* Camera class controls */ #define V4L2_CTRL_CLASS_FM_TX 0x009b0000 /* FM Modulator controls */ #define V4L2_CTRL_CLASS_FLASH 0x009c0000 /* Camera flash controls */ #define V4L2_CTRL_CLASS_JPEG 0x009d0000 /* JPEG-compression controls */ #define V4L2_CTRL_CLASS_IMAGE_SOURCE 0x009e0000 /* Image source controls */ #define V4L2_CTRL_CLASS_IMAGE_PROC 0x009f0000 /* Image processing controls */ #define V4L2_CTRL_CLASS_DV 0x00a00000 /* Digital Video controls */ #define V4L2_CTRL_CLASS_FM_RX 0x00a10000 /* FM Receiver controls */ #define V4L2_CTRL_CLASS_RF_TUNER 0x00a20000 /* RF tuner controls */ #define V4L2_CTRL_CLASS_DETECT 0x00a30000 /* Detection controls */ /* User-class control IDs */ #define V4L2_CID_BASE (V4L2_CTRL_CLASS_USER | 0x900) #define V4L2_CID_USER_BASE V4L2_CID_BASE #define V4L2_CID_USER_CLASS (V4L2_CTRL_CLASS_USER | 1) #define V4L2_CID_BRIGHTNESS (V4L2_CID_BASE+0) #define V4L2_CID_CONTRAST (V4L2_CID_BASE+1) #define V4L2_CID_SATURATION (V4L2_CID_BASE+2) #define V4L2_CID_HUE (V4L2_CID_BASE+3) #define V4L2_CID_AUDIO_VOLUME (V4L2_CID_BASE+5) #define V4L2_CID_AUDIO_BALANCE (V4L2_CID_BASE+6) #define V4L2_CID_AUDIO_BASS (V4L2_CID_BASE+7) #define V4L2_CID_AUDIO_TREBLE (V4L2_CID_BASE+8) #define V4L2_CID_AUDIO_MUTE (V4L2_CID_BASE+9) #define V4L2_CID_AUDIO_LOUDNESS (V4L2_CID_BASE+10) #define V4L2_CID_BLACK_LEVEL (V4L2_CID_BASE+11) /* Deprecated */ #define V4L2_CID_AUTO_WHITE_BALANCE (V4L2_CID_BASE+12) #define V4L2_CID_DO_WHITE_BALANCE (V4L2_CID_BASE+13) #define V4L2_CID_RED_BALANCE (V4L2_CID_BASE+14) #define V4L2_CID_BLUE_BALANCE (V4L2_CID_BASE+15) #define V4L2_CID_GAMMA (V4L2_CID_BASE+16) #define V4L2_CID_WHITENESS (V4L2_CID_GAMMA) /* Deprecated */ #define V4L2_CID_EXPOSURE (V4L2_CID_BASE+17) #define V4L2_CID_AUTOGAIN (V4L2_CID_BASE+18) #define V4L2_CID_GAIN (V4L2_CID_BASE+19) #define V4L2_CID_HFLIP (V4L2_CID_BASE+20) #define V4L2_CID_VFLIP (V4L2_CID_BASE+21) #define V4L2_CID_POWER_LINE_FREQUENCY (V4L2_CID_BASE+24) enum v4l2_power_line_frequency { V4L2_CID_POWER_LINE_FREQUENCY_DISABLED = 0, V4L2_CID_POWER_LINE_FREQUENCY_50HZ = 1, V4L2_CID_POWER_LINE_FREQUENCY_60HZ = 2, V4L2_CID_POWER_LINE_FREQUENCY_AUTO = 3, }; #define V4L2_CID_HUE_AUTO (V4L2_CID_BASE+25) #define V4L2_CID_WHITE_BALANCE_TEMPERATURE (V4L2_CID_BASE+26) #define V4L2_CID_SHARPNESS (V4L2_CID_BASE+27) #define V4L2_CID_BACKLIGHT_COMPENSATION (V4L2_CID_BASE+28) #define V4L2_CID_CHROMA_AGC (V4L2_CID_BASE+29) #define V4L2_CID_COLOR_KILLER (V4L2_CID_BASE+30) #define V4L2_CID_COLORFX (V4L2_CID_BASE+31) enum v4l2_colorfx { V4L2_COLORFX_NONE = 0, V4L2_COLORFX_BW = 1, V4L2_COLORFX_SEPIA = 2, V4L2_COLORFX_NEGATIVE = 3, V4L2_COLORFX_EMBOSS = 4, V4L2_COLORFX_SKETCH = 5, V4L2_COLORFX_SKY_BLUE = 6, V4L2_COLORFX_GRASS_GREEN = 7, V4L2_COLORFX_SKIN_WHITEN = 8, V4L2_COLORFX_VIVID = 9, V4L2_COLORFX_AQUA = 10, V4L2_COLORFX_ART_FREEZE = 11, V4L2_COLORFX_SILHOUETTE = 12, V4L2_COLORFX_SOLARIZATION = 13, V4L2_COLORFX_ANTIQUE = 14, V4L2_COLORFX_SET_CBCR = 15, }; #define V4L2_CID_AUTOBRIGHTNESS (V4L2_CID_BASE+32) #define V4L2_CID_BAND_STOP_FILTER (V4L2_CID_BASE+33) #define V4L2_CID_ROTATE (V4L2_CID_BASE+34) #define V4L2_CID_BG_COLOR (V4L2_CID_BASE+35) #define V4L2_CID_CHROMA_GAIN (V4L2_CID_BASE+36) #define V4L2_CID_ILLUMINATORS_1 (V4L2_CID_BASE+37) #define V4L2_CID_ILLUMINATORS_2 (V4L2_CID_BASE+38) #define V4L2_CID_MIN_BUFFERS_FOR_CAPTURE (V4L2_CID_BASE+39) #define V4L2_CID_MIN_BUFFERS_FOR_OUTPUT (V4L2_CID_BASE+40) #define V4L2_CID_ALPHA_COMPONENT (V4L2_CID_BASE+41) #define V4L2_CID_COLORFX_CBCR (V4L2_CID_BASE+42) /* last CID + 1 */ #define V4L2_CID_LASTP1 (V4L2_CID_BASE+43) /* USER-class private control IDs */ /* The base for the meye driver controls. See linux/meye.h for the list * of controls. We reserve 16 controls for this driver. */ #define V4L2_CID_USER_MEYE_BASE (V4L2_CID_USER_BASE + 0x1000) /* The base for the bttv driver controls. * We reserve 32 controls for this driver. */ #define V4L2_CID_USER_BTTV_BASE (V4L2_CID_USER_BASE + 0x1010) /* The base for the s2255 driver controls. * We reserve 16 controls for this driver. */ #define V4L2_CID_USER_S2255_BASE (V4L2_CID_USER_BASE + 0x1030) /* * The base for the si476x driver controls. See include/media/drv-intf/si476x.h * for the list of controls. Total of 16 controls is reserved for this driver */ #define V4L2_CID_USER_SI476X_BASE (V4L2_CID_USER_BASE + 0x1040) /* The base for the TI VPE driver controls. Total of 16 controls is reserved for * this driver */ #define V4L2_CID_USER_TI_VPE_BASE (V4L2_CID_USER_BASE + 0x1050) /* The base for the saa7134 driver controls. * We reserve 16 controls for this driver. */ #define V4L2_CID_USER_SAA7134_BASE (V4L2_CID_USER_BASE + 0x1060) /* The base for the adv7180 driver controls. * We reserve 16 controls for this driver. */ #define V4L2_CID_USER_ADV7180_BASE (V4L2_CID_USER_BASE + 0x1070) /* The base for the tc358743 driver controls. * We reserve 16 controls for this driver. */ #define V4L2_CID_USER_TC358743_BASE (V4L2_CID_USER_BASE + 0x1080) /* The base for the max217x driver controls. * We reserve 32 controls for this driver */ #define V4L2_CID_USER_MAX217X_BASE (V4L2_CID_USER_BASE + 0x1090) /* The base for the imx driver controls. * We reserve 16 controls for this driver. */ #define V4L2_CID_USER_IMX_BASE (V4L2_CID_USER_BASE + 0x1090) /* MPEG-class control IDs */ /* The MPEG controls are applicable to all codec controls * and the 'MPEG' part of the define is historical */ #define V4L2_CID_MPEG_BASE (V4L2_CTRL_CLASS_MPEG | 0x900) #define V4L2_CID_MPEG_CLASS (V4L2_CTRL_CLASS_MPEG | 1) /* MPEG streams, specific to multiplexed streams */ #define V4L2_CID_MPEG_STREAM_TYPE (V4L2_CID_MPEG_BASE+0) enum v4l2_mpeg_stream_type { V4L2_MPEG_STREAM_TYPE_MPEG2_PS = 0, /* MPEG-2 program stream */ V4L2_MPEG_STREAM_TYPE_MPEG2_TS = 1, /* MPEG-2 transport stream */ V4L2_MPEG_STREAM_TYPE_MPEG1_SS = 2, /* MPEG-1 system stream */ V4L2_MPEG_STREAM_TYPE_MPEG2_DVD = 3, /* MPEG-2 DVD-compatible stream */ V4L2_MPEG_STREAM_TYPE_MPEG1_VCD = 4, /* MPEG-1 VCD-compatible stream */ V4L2_MPEG_STREAM_TYPE_MPEG2_SVCD = 5, /* MPEG-2 SVCD-compatible stream */ }; #define V4L2_CID_MPEG_STREAM_PID_PMT (V4L2_CID_MPEG_BASE+1) #define V4L2_CID_MPEG_STREAM_PID_AUDIO (V4L2_CID_MPEG_BASE+2) #define V4L2_CID_MPEG_STREAM_PID_VIDEO (V4L2_CID_MPEG_BASE+3) #define V4L2_CID_MPEG_STREAM_PID_PCR (V4L2_CID_MPEG_BASE+4) #define V4L2_CID_MPEG_STREAM_PES_ID_AUDIO (V4L2_CID_MPEG_BASE+5) #define V4L2_CID_MPEG_STREAM_PES_ID_VIDEO (V4L2_CID_MPEG_BASE+6) #define V4L2_CID_MPEG_STREAM_VBI_FMT (V4L2_CID_MPEG_BASE+7) enum v4l2_mpeg_stream_vbi_fmt { V4L2_MPEG_STREAM_VBI_FMT_NONE = 0, /* No VBI in the MPEG stream */ V4L2_MPEG_STREAM_VBI_FMT_IVTV = 1, /* VBI in private packets, IVTV format */ }; /* MPEG audio controls specific to multiplexed streams */ #define V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ (V4L2_CID_MPEG_BASE+100) enum v4l2_mpeg_audio_sampling_freq { V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100 = 0, V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000 = 1, V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000 = 2, }; #define V4L2_CID_MPEG_AUDIO_ENCODING (V4L2_CID_MPEG_BASE+101) enum v4l2_mpeg_audio_encoding { V4L2_MPEG_AUDIO_ENCODING_LAYER_1 = 0, V4L2_MPEG_AUDIO_ENCODING_LAYER_2 = 1, V4L2_MPEG_AUDIO_ENCODING_LAYER_3 = 2, V4L2_MPEG_AUDIO_ENCODING_AAC = 3, V4L2_MPEG_AUDIO_ENCODING_AC3 = 4, }; #define V4L2_CID_MPEG_AUDIO_L1_BITRATE (V4L2_CID_MPEG_BASE+102) enum v4l2_mpeg_audio_l1_bitrate { V4L2_MPEG_AUDIO_L1_BITRATE_32K = 0, V4L2_MPEG_AUDIO_L1_BITRATE_64K = 1, V4L2_MPEG_AUDIO_L1_BITRATE_96K = 2, V4L2_MPEG_AUDIO_L1_BITRATE_128K = 3, V4L2_MPEG_AUDIO_L1_BITRATE_160K = 4, V4L2_MPEG_AUDIO_L1_BITRATE_192K = 5, V4L2_MPEG_AUDIO_L1_BITRATE_224K = 6, V4L2_MPEG_AUDIO_L1_BITRATE_256K = 7, V4L2_MPEG_AUDIO_L1_BITRATE_288K = 8, V4L2_MPEG_AUDIO_L1_BITRATE_320K = 9, V4L2_MPEG_AUDIO_L1_BITRATE_352K = 10, V4L2_MPEG_AUDIO_L1_BITRATE_384K = 11, V4L2_MPEG_AUDIO_L1_BITRATE_416K = 12, V4L2_MPEG_AUDIO_L1_BITRATE_448K = 13, }; #define V4L2_CID_MPEG_AUDIO_L2_BITRATE (V4L2_CID_MPEG_BASE+103) enum v4l2_mpeg_audio_l2_bitrate { V4L2_MPEG_AUDIO_L2_BITRATE_32K = 0, V4L2_MPEG_AUDIO_L2_BITRATE_48K = 1, V4L2_MPEG_AUDIO_L2_BITRATE_56K = 2, V4L2_MPEG_AUDIO_L2_BITRATE_64K = 3, V4L2_MPEG_AUDIO_L2_BITRATE_80K = 4, V4L2_MPEG_AUDIO_L2_BITRATE_96K = 5, V4L2_MPEG_AUDIO_L2_BITRATE_112K = 6, V4L2_MPEG_AUDIO_L2_BITRATE_128K = 7, V4L2_MPEG_AUDIO_L2_BITRATE_160K = 8, V4L2_MPEG_AUDIO_L2_BITRATE_192K = 9, V4L2_MPEG_AUDIO_L2_BITRATE_224K = 10, V4L2_MPEG_AUDIO_L2_BITRATE_256K = 11, V4L2_MPEG_AUDIO_L2_BITRATE_320K = 12, V4L2_MPEG_AUDIO_L2_BITRATE_384K = 13, }; #define V4L2_CID_MPEG_AUDIO_L3_BITRATE (V4L2_CID_MPEG_BASE+104) enum v4l2_mpeg_audio_l3_bitrate { V4L2_MPEG_AUDIO_L3_BITRATE_32K = 0, V4L2_MPEG_AUDIO_L3_BITRATE_40K = 1, V4L2_MPEG_AUDIO_L3_BITRATE_48K = 2, V4L2_MPEG_AUDIO_L3_BITRATE_56K = 3, V4L2_MPEG_AUDIO_L3_BITRATE_64K = 4, V4L2_MPEG_AUDIO_L3_BITRATE_80K = 5, V4L2_MPEG_AUDIO_L3_BITRATE_96K = 6, V4L2_MPEG_AUDIO_L3_BITRATE_112K = 7, V4L2_MPEG_AUDIO_L3_BITRATE_128K = 8, V4L2_MPEG_AUDIO_L3_BITRATE_160K = 9, V4L2_MPEG_AUDIO_L3_BITRATE_192K = 10, V4L2_MPEG_AUDIO_L3_BITRATE_224K = 11, V4L2_MPEG_AUDIO_L3_BITRATE_256K = 12, V4L2_MPEG_AUDIO_L3_BITRATE_320K = 13, }; #define V4L2_CID_MPEG_AUDIO_MODE (V4L2_CID_MPEG_BASE+105) enum v4l2_mpeg_audio_mode { V4L2_MPEG_AUDIO_MODE_STEREO = 0, V4L2_MPEG_AUDIO_MODE_JOINT_STEREO = 1, V4L2_MPEG_AUDIO_MODE_DUAL = 2, V4L2_MPEG_AUDIO_MODE_MONO = 3, }; #define V4L2_CID_MPEG_AUDIO_MODE_EXTENSION (V4L2_CID_MPEG_BASE+106) enum v4l2_mpeg_audio_mode_extension { V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_4 = 0, V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_8 = 1, V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_12 = 2, V4L2_MPEG_AUDIO_MODE_EXTENSION_BOUND_16 = 3, }; #define V4L2_CID_MPEG_AUDIO_EMPHASIS (V4L2_CID_MPEG_BASE+107) enum v4l2_mpeg_audio_emphasis { V4L2_MPEG_AUDIO_EMPHASIS_NONE = 0, V4L2_MPEG_AUDIO_EMPHASIS_50_DIV_15_uS = 1, V4L2_MPEG_AUDIO_EMPHASIS_CCITT_J17 = 2, }; #define V4L2_CID_MPEG_AUDIO_CRC (V4L2_CID_MPEG_BASE+108) enum v4l2_mpeg_audio_crc { V4L2_MPEG_AUDIO_CRC_NONE = 0, V4L2_MPEG_AUDIO_CRC_CRC16 = 1, }; #define V4L2_CID_MPEG_AUDIO_MUTE (V4L2_CID_MPEG_BASE+109) #define V4L2_CID_MPEG_AUDIO_AAC_BITRATE (V4L2_CID_MPEG_BASE+110) #define V4L2_CID_MPEG_AUDIO_AC3_BITRATE (V4L2_CID_MPEG_BASE+111) enum v4l2_mpeg_audio_ac3_bitrate { V4L2_MPEG_AUDIO_AC3_BITRATE_32K = 0, V4L2_MPEG_AUDIO_AC3_BITRATE_40K = 1, V4L2_MPEG_AUDIO_AC3_BITRATE_48K = 2, V4L2_MPEG_AUDIO_AC3_BITRATE_56K = 3, V4L2_MPEG_AUDIO_AC3_BITRATE_64K = 4, V4L2_MPEG_AUDIO_AC3_BITRATE_80K = 5, V4L2_MPEG_AUDIO_AC3_BITRATE_96K = 6, V4L2_MPEG_AUDIO_AC3_BITRATE_112K = 7, V4L2_MPEG_AUDIO_AC3_BITRATE_128K = 8, V4L2_MPEG_AUDIO_AC3_BITRATE_160K = 9, V4L2_MPEG_AUDIO_AC3_BITRATE_192K = 10, V4L2_MPEG_AUDIO_AC3_BITRATE_224K = 11, V4L2_MPEG_AUDIO_AC3_BITRATE_256K = 12, V4L2_MPEG_AUDIO_AC3_BITRATE_320K = 13, V4L2_MPEG_AUDIO_AC3_BITRATE_384K = 14, V4L2_MPEG_AUDIO_AC3_BITRATE_448K = 15, V4L2_MPEG_AUDIO_AC3_BITRATE_512K = 16, V4L2_MPEG_AUDIO_AC3_BITRATE_576K = 17, V4L2_MPEG_AUDIO_AC3_BITRATE_640K = 18, }; #define V4L2_CID_MPEG_AUDIO_DEC_PLAYBACK (V4L2_CID_MPEG_BASE+112) enum v4l2_mpeg_audio_dec_playback { V4L2_MPEG_AUDIO_DEC_PLAYBACK_AUTO = 0, V4L2_MPEG_AUDIO_DEC_PLAYBACK_STEREO = 1, V4L2_MPEG_AUDIO_DEC_PLAYBACK_LEFT = 2, V4L2_MPEG_AUDIO_DEC_PLAYBACK_RIGHT = 3, V4L2_MPEG_AUDIO_DEC_PLAYBACK_MONO = 4, V4L2_MPEG_AUDIO_DEC_PLAYBACK_SWAPPED_STEREO = 5, }; #define V4L2_CID_MPEG_AUDIO_DEC_MULTILINGUAL_PLAYBACK (V4L2_CID_MPEG_BASE+113) /* MPEG video controls specific to multiplexed streams */ #define V4L2_CID_MPEG_VIDEO_ENCODING (V4L2_CID_MPEG_BASE+200) enum v4l2_mpeg_video_encoding { V4L2_MPEG_VIDEO_ENCODING_MPEG_1 = 0, V4L2_MPEG_VIDEO_ENCODING_MPEG_2 = 1, V4L2_MPEG_VIDEO_ENCODING_MPEG_4_AVC = 2, }; #define V4L2_CID_MPEG_VIDEO_ASPECT (V4L2_CID_MPEG_BASE+201) enum v4l2_mpeg_video_aspect { V4L2_MPEG_VIDEO_ASPECT_1x1 = 0, V4L2_MPEG_VIDEO_ASPECT_4x3 = 1, V4L2_MPEG_VIDEO_ASPECT_16x9 = 2, V4L2_MPEG_VIDEO_ASPECT_221x100 = 3, }; #define V4L2_CID_MPEG_VIDEO_B_FRAMES (V4L2_CID_MPEG_BASE+202) #define V4L2_CID_MPEG_VIDEO_GOP_SIZE (V4L2_CID_MPEG_BASE+203) #define V4L2_CID_MPEG_VIDEO_GOP_CLOSURE (V4L2_CID_MPEG_BASE+204) #define V4L2_CID_MPEG_VIDEO_PULLDOWN (V4L2_CID_MPEG_BASE+205) #define V4L2_CID_MPEG_VIDEO_BITRATE_MODE (V4L2_CID_MPEG_BASE+206) enum v4l2_mpeg_video_bitrate_mode { V4L2_MPEG_VIDEO_BITRATE_MODE_VBR = 0, V4L2_MPEG_VIDEO_BITRATE_MODE_CBR = 1, }; #define V4L2_CID_MPEG_VIDEO_BITRATE (V4L2_CID_MPEG_BASE+207) #define V4L2_CID_MPEG_VIDEO_BITRATE_PEAK (V4L2_CID_MPEG_BASE+208) #define V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION (V4L2_CID_MPEG_BASE+209) #define V4L2_CID_MPEG_VIDEO_MUTE (V4L2_CID_MPEG_BASE+210) #define V4L2_CID_MPEG_VIDEO_MUTE_YUV (V4L2_CID_MPEG_BASE+211) #define V4L2_CID_MPEG_VIDEO_DECODER_SLICE_INTERFACE (V4L2_CID_MPEG_BASE+212) #define V4L2_CID_MPEG_VIDEO_DECODER_MPEG4_DEBLOCK_FILTER (V4L2_CID_MPEG_BASE+213) #define V4L2_CID_MPEG_VIDEO_CYCLIC_INTRA_REFRESH_MB (V4L2_CID_MPEG_BASE+214) #define V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE (V4L2_CID_MPEG_BASE+215) #define V4L2_CID_MPEG_VIDEO_HEADER_MODE (V4L2_CID_MPEG_BASE+216) enum v4l2_mpeg_video_header_mode { V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE = 0, V4L2_MPEG_VIDEO_HEADER_MODE_JOINED_WITH_1ST_FRAME = 1, }; #define V4L2_CID_MPEG_VIDEO_MAX_REF_PIC (V4L2_CID_MPEG_BASE+217) #define V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE (V4L2_CID_MPEG_BASE+218) #define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_BYTES (V4L2_CID_MPEG_BASE+219) #define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MAX_MB (V4L2_CID_MPEG_BASE+220) #define V4L2_CID_MPEG_VIDEO_MULTI_SLICE_MODE (V4L2_CID_MPEG_BASE+221) enum v4l2_mpeg_video_multi_slice_mode { V4L2_MPEG_VIDEO_MULTI_SLICE_MODE_SINGLE = 0, V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_MB = 1, V4L2_MPEG_VIDEO_MULTI_SICE_MODE_MAX_BYTES = 2, }; #define V4L2_CID_MPEG_VIDEO_VBV_SIZE (V4L2_CID_MPEG_BASE+222) #define V4L2_CID_MPEG_VIDEO_DEC_PTS (V4L2_CID_MPEG_BASE+223) #define V4L2_CID_MPEG_VIDEO_DEC_FRAME (V4L2_CID_MPEG_BASE+224) #define V4L2_CID_MPEG_VIDEO_VBV_DELAY (V4L2_CID_MPEG_BASE+225) #define V4L2_CID_MPEG_VIDEO_REPEAT_SEQ_HEADER (V4L2_CID_MPEG_BASE+226) #define V4L2_CID_MPEG_VIDEO_MV_H_SEARCH_RANGE (V4L2_CID_MPEG_BASE+227) #define V4L2_CID_MPEG_VIDEO_MV_V_SEARCH_RANGE (V4L2_CID_MPEG_BASE+228) #define V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME (V4L2_CID_MPEG_BASE+229) #define V4L2_CID_MPEG_VIDEO_MPEG2_SLICE_PARAMS (V4L2_CID_MPEG_BASE+250) #define V4L2_CID_MPEG_VIDEO_MPEG2_QUANTIZATION (V4L2_CID_MPEG_BASE+251) #define V4L2_CID_MPEG_VIDEO_H263_I_FRAME_QP (V4L2_CID_MPEG_BASE+300) #define V4L2_CID_MPEG_VIDEO_H263_P_FRAME_QP (V4L2_CID_MPEG_BASE+301) #define V4L2_CID_MPEG_VIDEO_H263_B_FRAME_QP (V4L2_CID_MPEG_BASE+302) #define V4L2_CID_MPEG_VIDEO_H263_MIN_QP (V4L2_CID_MPEG_BASE+303) #define V4L2_CID_MPEG_VIDEO_H263_MAX_QP (V4L2_CID_MPEG_BASE+304) #define V4L2_CID_MPEG_VIDEO_H264_I_FRAME_QP (V4L2_CID_MPEG_BASE+350) #define V4L2_CID_MPEG_VIDEO_H264_P_FRAME_QP (V4L2_CID_MPEG_BASE+351) #define V4L2_CID_MPEG_VIDEO_H264_B_FRAME_QP (V4L2_CID_MPEG_BASE+352) #define V4L2_CID_MPEG_VIDEO_H264_MIN_QP (V4L2_CID_MPEG_BASE+353) #define V4L2_CID_MPEG_VIDEO_H264_MAX_QP (V4L2_CID_MPEG_BASE+354) #define V4L2_CID_MPEG_VIDEO_H264_8X8_TRANSFORM (V4L2_CID_MPEG_BASE+355) #define V4L2_CID_MPEG_VIDEO_H264_CPB_SIZE (V4L2_CID_MPEG_BASE+356) #define V4L2_CID_MPEG_VIDEO_H264_ENTROPY_MODE (V4L2_CID_MPEG_BASE+357) enum v4l2_mpeg_video_h264_entropy_mode { V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CAVLC = 0, V4L2_MPEG_VIDEO_H264_ENTROPY_MODE_CABAC = 1, }; #define V4L2_CID_MPEG_VIDEO_H264_I_PERIOD (V4L2_CID_MPEG_BASE+358) #define V4L2_CID_MPEG_VIDEO_H264_LEVEL (V4L2_CID_MPEG_BASE+359) enum v4l2_mpeg_video_h264_level { V4L2_MPEG_VIDEO_H264_LEVEL_1_0 = 0, V4L2_MPEG_VIDEO_H264_LEVEL_1B = 1, V4L2_MPEG_VIDEO_H264_LEVEL_1_1 = 2, V4L2_MPEG_VIDEO_H264_LEVEL_1_2 = 3, V4L2_MPEG_VIDEO_H264_LEVEL_1_3 = 4, V4L2_MPEG_VIDEO_H264_LEVEL_2_0 = 5, V4L2_MPEG_VIDEO_H264_LEVEL_2_1 = 6, V4L2_MPEG_VIDEO_H264_LEVEL_2_2 = 7, V4L2_MPEG_VIDEO_H264_LEVEL_3_0 = 8, V4L2_MPEG_VIDEO_H264_LEVEL_3_1 = 9, V4L2_MPEG_VIDEO_H264_LEVEL_3_2 = 10, V4L2_MPEG_VIDEO_H264_LEVEL_4_0 = 11, V4L2_MPEG_VIDEO_H264_LEVEL_4_1 = 12, V4L2_MPEG_VIDEO_H264_LEVEL_4_2 = 13, V4L2_MPEG_VIDEO_H264_LEVEL_5_0 = 14, V4L2_MPEG_VIDEO_H264_LEVEL_5_1 = 15, }; #define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA (V4L2_CID_MPEG_BASE+360) #define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA (V4L2_CID_MPEG_BASE+361) #define V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE (V4L2_CID_MPEG_BASE+362) enum v4l2_mpeg_video_h264_loop_filter_mode { V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED = 0, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED = 1, V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY = 2, }; #define V4L2_CID_MPEG_VIDEO_H264_PROFILE (V4L2_CID_MPEG_BASE+363) enum v4l2_mpeg_video_h264_profile { V4L2_MPEG_VIDEO_H264_PROFILE_BASELINE = 0, V4L2_MPEG_VIDEO_H264_PROFILE_CONSTRAINED_BASELINE = 1, V4L2_MPEG_VIDEO_H264_PROFILE_MAIN = 2, V4L2_MPEG_VIDEO_H264_PROFILE_EXTENDED = 3, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH = 4, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10 = 5, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422 = 6, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_PREDICTIVE = 7, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_10_INTRA = 8, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_422_INTRA = 9, V4L2_MPEG_VIDEO_H264_PROFILE_HIGH_444_INTRA = 10, V4L2_MPEG_VIDEO_H264_PROFILE_CAVLC_444_INTRA = 11, V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_BASELINE = 12, V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH = 13, V4L2_MPEG_VIDEO_H264_PROFILE_SCALABLE_HIGH_INTRA = 14, V4L2_MPEG_VIDEO_H264_PROFILE_STEREO_HIGH = 15, V4L2_MPEG_VIDEO_H264_PROFILE_MULTIVIEW_HIGH = 16, }; #define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT (V4L2_CID_MPEG_BASE+364) #define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH (V4L2_CID_MPEG_BASE+365) #define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_ENABLE (V4L2_CID_MPEG_BASE+366) #define V4L2_CID_MPEG_VIDEO_H264_VUI_SAR_IDC (V4L2_CID_MPEG_BASE+367) enum v4l2_mpeg_video_h264_vui_sar_idc { V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_UNSPECIFIED = 0, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_1x1 = 1, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_12x11 = 2, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_10x11 = 3, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_16x11 = 4, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_40x33 = 5, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_24x11 = 6, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_20x11 = 7, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_32x11 = 8, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_80x33 = 9, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_18x11 = 10, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_15x11 = 11, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_64x33 = 12, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_160x99 = 13, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_4x3 = 14, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_3x2 = 15, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_2x1 = 16, V4L2_MPEG_VIDEO_H264_VUI_SAR_IDC_EXTENDED = 17, }; #define V4L2_CID_MPEG_VIDEO_H264_SEI_FRAME_PACKING (V4L2_CID_MPEG_BASE+368) #define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_CURRENT_FRAME_0 (V4L2_CID_MPEG_BASE+369) #define V4L2_CID_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE (V4L2_CID_MPEG_BASE+370) enum v4l2_mpeg_video_h264_sei_fp_arrangement_type { V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_CHECKERBOARD = 0, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_COLUMN = 1, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_ROW = 2, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_SIDE_BY_SIDE = 3, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TOP_BOTTOM = 4, V4L2_MPEG_VIDEO_H264_SEI_FP_ARRANGEMENT_TYPE_TEMPORAL = 5, }; #define V4L2_CID_MPEG_VIDEO_H264_FMO (V4L2_CID_MPEG_BASE+371) #define V4L2_CID_MPEG_VIDEO_H264_FMO_MAP_TYPE (V4L2_CID_MPEG_BASE+372) enum v4l2_mpeg_video_h264_fmo_map_type { V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_INTERLEAVED_SLICES = 0, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_SCATTERED_SLICES = 1, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_FOREGROUND_WITH_LEFT_OVER = 2, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_BOX_OUT = 3, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_RASTER_SCAN = 4, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_WIPE_SCAN = 5, V4L2_MPEG_VIDEO_H264_FMO_MAP_TYPE_EXPLICIT = 6, }; #define V4L2_CID_MPEG_VIDEO_H264_FMO_SLICE_GROUP (V4L2_CID_MPEG_BASE+373) #define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_DIRECTION (V4L2_CID_MPEG_BASE+374) enum v4l2_mpeg_video_h264_fmo_change_dir { V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_RIGHT = 0, V4L2_MPEG_VIDEO_H264_FMO_CHANGE_DIR_LEFT = 1, }; #define V4L2_CID_MPEG_VIDEO_H264_FMO_CHANGE_RATE (V4L2_CID_MPEG_BASE+375) #define V4L2_CID_MPEG_VIDEO_H264_FMO_RUN_LENGTH (V4L2_CID_MPEG_BASE+376) #define V4L2_CID_MPEG_VIDEO_H264_ASO (V4L2_CID_MPEG_BASE+377) #define V4L2_CID_MPEG_VIDEO_H264_ASO_SLICE_ORDER (V4L2_CID_MPEG_BASE+378) #define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING (V4L2_CID_MPEG_BASE+379) #define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_TYPE (V4L2_CID_MPEG_BASE+380) enum v4l2_mpeg_video_h264_hierarchical_coding_type { V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_B = 0, V4L2_MPEG_VIDEO_H264_HIERARCHICAL_CODING_P = 1, }; #define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER (V4L2_CID_MPEG_BASE+381) #define V4L2_CID_MPEG_VIDEO_H264_HIERARCHICAL_CODING_LAYER_QP (V4L2_CID_MPEG_BASE+382) #define V4L2_CID_MPEG_VIDEO_MPEG4_I_FRAME_QP (V4L2_CID_MPEG_BASE+400) #define V4L2_CID_MPEG_VIDEO_MPEG4_P_FRAME_QP (V4L2_CID_MPEG_BASE+401) #define V4L2_CID_MPEG_VIDEO_MPEG4_B_FRAME_QP (V4L2_CID_MPEG_BASE+402) #define V4L2_CID_MPEG_VIDEO_MPEG4_MIN_QP (V4L2_CID_MPEG_BASE+403) #define V4L2_CID_MPEG_VIDEO_MPEG4_MAX_QP (V4L2_CID_MPEG_BASE+404) #define V4L2_CID_MPEG_VIDEO_MPEG4_LEVEL (V4L2_CID_MPEG_BASE+405) enum v4l2_mpeg_video_mpeg4_level { V4L2_MPEG_VIDEO_MPEG4_LEVEL_0 = 0, V4L2_MPEG_VIDEO_MPEG4_LEVEL_0B = 1, V4L2_MPEG_VIDEO_MPEG4_LEVEL_1 = 2, V4L2_MPEG_VIDEO_MPEG4_LEVEL_2 = 3, V4L2_MPEG_VIDEO_MPEG4_LEVEL_3 = 4, V4L2_MPEG_VIDEO_MPEG4_LEVEL_3B = 5, V4L2_MPEG_VIDEO_MPEG4_LEVEL_4 = 6, V4L2_MPEG_VIDEO_MPEG4_LEVEL_5 = 7, }; #define V4L2_CID_MPEG_VIDEO_MPEG4_PROFILE (V4L2_CID_MPEG_BASE+406) enum v4l2_mpeg_video_mpeg4_profile { V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE = 0, V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_SIMPLE = 1, V4L2_MPEG_VIDEO_MPEG4_PROFILE_CORE = 2, V4L2_MPEG_VIDEO_MPEG4_PROFILE_SIMPLE_SCALABLE = 3, V4L2_MPEG_VIDEO_MPEG4_PROFILE_ADVANCED_CODING_EFFICIENCY = 4, }; #define V4L2_CID_MPEG_VIDEO_MPEG4_QPEL (V4L2_CID_MPEG_BASE+407) /* Control IDs for VP8 streams * Although VP8 is not part of MPEG we add these controls to the MPEG class * as that class is already handling other video compression standards */ #define V4L2_CID_MPEG_VIDEO_VPX_NUM_PARTITIONS (V4L2_CID_MPEG_BASE+500) enum v4l2_vp8_num_partitions { V4L2_CID_MPEG_VIDEO_VPX_1_PARTITION = 0, V4L2_CID_MPEG_VIDEO_VPX_2_PARTITIONS = 1, V4L2_CID_MPEG_VIDEO_VPX_4_PARTITIONS = 2, V4L2_CID_MPEG_VIDEO_VPX_8_PARTITIONS = 3, }; #define V4L2_CID_MPEG_VIDEO_VPX_IMD_DISABLE_4X4 (V4L2_CID_MPEG_BASE+501) #define V4L2_CID_MPEG_VIDEO_VPX_NUM_REF_FRAMES (V4L2_CID_MPEG_BASE+502) enum v4l2_vp8_num_ref_frames { V4L2_CID_MPEG_VIDEO_VPX_1_REF_FRAME = 0, V4L2_CID_MPEG_VIDEO_VPX_2_REF_FRAME = 1, V4L2_CID_MPEG_VIDEO_VPX_3_REF_FRAME = 2, }; #define V4L2_CID_MPEG_VIDEO_VPX_FILTER_LEVEL (V4L2_CID_MPEG_BASE+503) #define V4L2_CID_MPEG_VIDEO_VPX_FILTER_SHARPNESS (V4L2_CID_MPEG_BASE+504) #define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_REF_PERIOD (V4L2_CID_MPEG_BASE+505) #define V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_SEL (V4L2_CID_MPEG_BASE+506) enum v4l2_vp8_golden_frame_sel { V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_PREV = 0, V4L2_CID_MPEG_VIDEO_VPX_GOLDEN_FRAME_USE_REF_PERIOD = 1, }; #define V4L2_CID_MPEG_VIDEO_VPX_MIN_QP (V4L2_CID_MPEG_BASE+507) #define V4L2_CID_MPEG_VIDEO_VPX_MAX_QP (V4L2_CID_MPEG_BASE+508) #define V4L2_CID_MPEG_VIDEO_VPX_I_FRAME_QP (V4L2_CID_MPEG_BASE+509) #define V4L2_CID_MPEG_VIDEO_VPX_P_FRAME_QP (V4L2_CID_MPEG_BASE+510) #define V4L2_CID_MPEG_VIDEO_VPX_PROFILE (V4L2_CID_MPEG_BASE+511) /* CIDs for HEVC encoding. */ #define V4L2_CID_MPEG_VIDEO_HEVC_MIN_QP (V4L2_CID_MPEG_BASE + 600) #define V4L2_CID_MPEG_VIDEO_HEVC_MAX_QP (V4L2_CID_MPEG_BASE + 601) #define V4L2_CID_MPEG_VIDEO_HEVC_I_FRAME_QP (V4L2_CID_MPEG_BASE + 602) #define V4L2_CID_MPEG_VIDEO_HEVC_P_FRAME_QP (V4L2_CID_MPEG_BASE + 603) #define V4L2_CID_MPEG_VIDEO_HEVC_B_FRAME_QP (V4L2_CID_MPEG_BASE + 604) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_QP (V4L2_CID_MPEG_BASE + 605) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_TYPE (V4L2_CID_MPEG_BASE + 606) enum v4l2_mpeg_video_hevc_hier_coding_type { V4L2_MPEG_VIDEO_HEVC_HIERARCHICAL_CODING_B = 0, V4L2_MPEG_VIDEO_HEVC_HIERARCHICAL_CODING_P = 1, }; #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_LAYER (V4L2_CID_MPEG_BASE + 607) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L0_QP (V4L2_CID_MPEG_BASE + 608) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L1_QP (V4L2_CID_MPEG_BASE + 609) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L2_QP (V4L2_CID_MPEG_BASE + 610) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L3_QP (V4L2_CID_MPEG_BASE + 611) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L4_QP (V4L2_CID_MPEG_BASE + 612) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L5_QP (V4L2_CID_MPEG_BASE + 613) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L6_QP (V4L2_CID_MPEG_BASE + 614) #define V4L2_CID_MPEG_VIDEO_HEVC_PROFILE (V4L2_CID_MPEG_BASE + 615) enum v4l2_mpeg_video_hevc_profile { V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN = 0, V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_STILL_PICTURE = 1, V4L2_MPEG_VIDEO_HEVC_PROFILE_MAIN_10 = 2, }; #define V4L2_CID_MPEG_VIDEO_HEVC_LEVEL (V4L2_CID_MPEG_BASE + 616) enum v4l2_mpeg_video_hevc_level { V4L2_MPEG_VIDEO_HEVC_LEVEL_1 = 0, V4L2_MPEG_VIDEO_HEVC_LEVEL_2 = 1, V4L2_MPEG_VIDEO_HEVC_LEVEL_2_1 = 2, V4L2_MPEG_VIDEO_HEVC_LEVEL_3 = 3, V4L2_MPEG_VIDEO_HEVC_LEVEL_3_1 = 4, V4L2_MPEG_VIDEO_HEVC_LEVEL_4 = 5, V4L2_MPEG_VIDEO_HEVC_LEVEL_4_1 = 6, V4L2_MPEG_VIDEO_HEVC_LEVEL_5 = 7, V4L2_MPEG_VIDEO_HEVC_LEVEL_5_1 = 8, V4L2_MPEG_VIDEO_HEVC_LEVEL_5_2 = 9, V4L2_MPEG_VIDEO_HEVC_LEVEL_6 = 10, V4L2_MPEG_VIDEO_HEVC_LEVEL_6_1 = 11, V4L2_MPEG_VIDEO_HEVC_LEVEL_6_2 = 12, }; #define V4L2_CID_MPEG_VIDEO_HEVC_FRAME_RATE_RESOLUTION (V4L2_CID_MPEG_BASE + 617) #define V4L2_CID_MPEG_VIDEO_HEVC_TIER (V4L2_CID_MPEG_BASE + 618) enum v4l2_mpeg_video_hevc_tier { V4L2_MPEG_VIDEO_HEVC_TIER_MAIN = 0, V4L2_MPEG_VIDEO_HEVC_TIER_HIGH = 1, }; #define V4L2_CID_MPEG_VIDEO_HEVC_MAX_PARTITION_DEPTH (V4L2_CID_MPEG_BASE + 619) #define V4L2_CID_MPEG_VIDEO_HEVC_LOOP_FILTER_MODE (V4L2_CID_MPEG_BASE + 620) enum v4l2_cid_mpeg_video_hevc_loop_filter_mode { V4L2_MPEG_VIDEO_HEVC_LOOP_FILTER_MODE_DISABLED = 0, V4L2_MPEG_VIDEO_HEVC_LOOP_FILTER_MODE_ENABLED = 1, V4L2_MPEG_VIDEO_HEVC_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY = 2, }; #define V4L2_CID_MPEG_VIDEO_HEVC_LF_BETA_OFFSET_DIV2 (V4L2_CID_MPEG_BASE + 621) #define V4L2_CID_MPEG_VIDEO_HEVC_LF_TC_OFFSET_DIV2 (V4L2_CID_MPEG_BASE + 622) #define V4L2_CID_MPEG_VIDEO_HEVC_REFRESH_TYPE (V4L2_CID_MPEG_BASE + 623) enum v4l2_cid_mpeg_video_hevc_refresh_type { V4L2_MPEG_VIDEO_HEVC_REFRESH_NONE = 0, V4L2_MPEG_VIDEO_HEVC_REFRESH_CRA = 1, V4L2_MPEG_VIDEO_HEVC_REFRESH_IDR = 2, }; #define V4L2_CID_MPEG_VIDEO_HEVC_REFRESH_PERIOD (V4L2_CID_MPEG_BASE + 624) #define V4L2_CID_MPEG_VIDEO_HEVC_LOSSLESS_CU (V4L2_CID_MPEG_BASE + 625) #define V4L2_CID_MPEG_VIDEO_HEVC_CONST_INTRA_PRED (V4L2_CID_MPEG_BASE + 626) #define V4L2_CID_MPEG_VIDEO_HEVC_WAVEFRONT (V4L2_CID_MPEG_BASE + 627) #define V4L2_CID_MPEG_VIDEO_HEVC_GENERAL_PB (V4L2_CID_MPEG_BASE + 628) #define V4L2_CID_MPEG_VIDEO_HEVC_TEMPORAL_ID (V4L2_CID_MPEG_BASE + 629) #define V4L2_CID_MPEG_VIDEO_HEVC_STRONG_SMOOTHING (V4L2_CID_MPEG_BASE + 630) #define V4L2_CID_MPEG_VIDEO_HEVC_MAX_NUM_MERGE_MV_MINUS1 (V4L2_CID_MPEG_BASE + 631) #define V4L2_CID_MPEG_VIDEO_HEVC_INTRA_PU_SPLIT (V4L2_CID_MPEG_BASE + 632) #define V4L2_CID_MPEG_VIDEO_HEVC_TMV_PREDICTION (V4L2_CID_MPEG_BASE + 633) #define V4L2_CID_MPEG_VIDEO_HEVC_WITHOUT_STARTCODE (V4L2_CID_MPEG_BASE + 634) #define V4L2_CID_MPEG_VIDEO_HEVC_SIZE_OF_LENGTH_FIELD (V4L2_CID_MPEG_BASE + 635) enum v4l2_cid_mpeg_video_hevc_size_of_length_field { V4L2_MPEG_VIDEO_HEVC_SIZE_0 = 0, V4L2_MPEG_VIDEO_HEVC_SIZE_1 = 1, V4L2_MPEG_VIDEO_HEVC_SIZE_2 = 2, V4L2_MPEG_VIDEO_HEVC_SIZE_4 = 3, }; #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L0_BR (V4L2_CID_MPEG_BASE + 636) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L1_BR (V4L2_CID_MPEG_BASE + 637) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L2_BR (V4L2_CID_MPEG_BASE + 638) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L3_BR (V4L2_CID_MPEG_BASE + 639) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L4_BR (V4L2_CID_MPEG_BASE + 640) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L5_BR (V4L2_CID_MPEG_BASE + 641) #define V4L2_CID_MPEG_VIDEO_HEVC_HIER_CODING_L6_BR (V4L2_CID_MPEG_BASE + 642) #define V4L2_CID_MPEG_VIDEO_REF_NUMBER_FOR_PFRAMES (V4L2_CID_MPEG_BASE + 643) #define V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR (V4L2_CID_MPEG_BASE + 644) /* MPEG-class control IDs specific to the CX2341x driver as defined by V4L2 */ #define V4L2_CID_MPEG_CX2341X_BASE (V4L2_CTRL_CLASS_MPEG | 0x1000) #define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+0) enum v4l2_mpeg_cx2341x_video_spatial_filter_mode { V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_MANUAL = 0, V4L2_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE_AUTO = 1, }; #define V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+1) #define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+2) enum v4l2_mpeg_cx2341x_video_luma_spatial_filter_type { V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_OFF = 0, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_1D_VERT = 2, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_HV_SEPARABLE = 3, V4L2_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE_2D_SYM_NON_SEPARABLE = 4, }; #define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+3) enum v4l2_mpeg_cx2341x_video_chroma_spatial_filter_type { V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_OFF = 0, V4L2_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE_1D_HOR = 1, }; #define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE (V4L2_CID_MPEG_CX2341X_BASE+4) enum v4l2_mpeg_cx2341x_video_temporal_filter_mode { V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_MANUAL = 0, V4L2_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE_AUTO = 1, }; #define V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER (V4L2_CID_MPEG_CX2341X_BASE+5) #define V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE (V4L2_CID_MPEG_CX2341X_BASE+6) enum v4l2_mpeg_cx2341x_video_median_filter_type { V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_OFF = 0, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR = 1, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_VERT = 2, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_HOR_VERT = 3, V4L2_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE_DIAG = 4, }; #define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+7) #define V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+8) #define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM (V4L2_CID_MPEG_CX2341X_BASE+9) #define V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP (V4L2_CID_MPEG_CX2341X_BASE+10) #define V4L2_CID_MPEG_CX2341X_STREAM_INSERT_NAV_PACKETS (V4L2_CID_MPEG_CX2341X_BASE+11) /* MPEG-class control IDs specific to the Samsung MFC 5.1 driver as defined by V4L2 */ #define V4L2_CID_MPEG_MFC51_BASE (V4L2_CTRL_CLASS_MPEG | 0x1100) #define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY (V4L2_CID_MPEG_MFC51_BASE+0) #define V4L2_CID_MPEG_MFC51_VIDEO_DECODER_H264_DISPLAY_DELAY_ENABLE (V4L2_CID_MPEG_MFC51_BASE+1) #define V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE (V4L2_CID_MPEG_MFC51_BASE+2) enum v4l2_mpeg_mfc51_video_frame_skip_mode { V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_DISABLED = 0, V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_LEVEL_LIMIT = 1, V4L2_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE_BUF_LIMIT = 2, }; #define V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE (V4L2_CID_MPEG_MFC51_BASE+3) enum v4l2_mpeg_mfc51_video_force_frame_type { V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_DISABLED = 0, V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME = 1, V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_NOT_CODED = 2, }; #define V4L2_CID_MPEG_MFC51_VIDEO_PADDING (V4L2_CID_MPEG_MFC51_BASE+4) #define V4L2_CID_MPEG_MFC51_VIDEO_PADDING_YUV (V4L2_CID_MPEG_MFC51_BASE+5) #define V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT (V4L2_CID_MPEG_MFC51_BASE+6) #define V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF (V4L2_CID_MPEG_MFC51_BASE+7) #define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_ACTIVITY (V4L2_CID_MPEG_MFC51_BASE+50) #define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_DARK (V4L2_CID_MPEG_MFC51_BASE+51) #define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_SMOOTH (V4L2_CID_MPEG_MFC51_BASE+52) #define V4L2_CID_MPEG_MFC51_VIDEO_H264_ADAPTIVE_RC_STATIC (V4L2_CID_MPEG_MFC51_BASE+53) #define V4L2_CID_MPEG_MFC51_VIDEO_H264_NUM_REF_PIC_FOR_P (V4L2_CID_MPEG_MFC51_BASE+54) /* Camera class control IDs */ #define V4L2_CID_CAMERA_CLASS_BASE (V4L2_CTRL_CLASS_CAMERA | 0x900) #define V4L2_CID_CAMERA_CLASS (V4L2_CTRL_CLASS_CAMERA | 1) #define V4L2_CID_EXPOSURE_AUTO (V4L2_CID_CAMERA_CLASS_BASE+1) enum v4l2_exposure_auto_type { V4L2_EXPOSURE_AUTO = 0, V4L2_EXPOSURE_MANUAL = 1, V4L2_EXPOSURE_SHUTTER_PRIORITY = 2, V4L2_EXPOSURE_APERTURE_PRIORITY = 3 }; #define V4L2_CID_EXPOSURE_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+2) #define V4L2_CID_EXPOSURE_AUTO_PRIORITY (V4L2_CID_CAMERA_CLASS_BASE+3) #define V4L2_CID_PAN_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+4) #define V4L2_CID_TILT_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+5) #define V4L2_CID_PAN_RESET (V4L2_CID_CAMERA_CLASS_BASE+6) #define V4L2_CID_TILT_RESET (V4L2_CID_CAMERA_CLASS_BASE+7) #define V4L2_CID_PAN_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+8) #define V4L2_CID_TILT_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+9) #define V4L2_CID_FOCUS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+10) #define V4L2_CID_FOCUS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+11) #define V4L2_CID_FOCUS_AUTO (V4L2_CID_CAMERA_CLASS_BASE+12) #define V4L2_CID_ZOOM_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+13) #define V4L2_CID_ZOOM_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+14) #define V4L2_CID_ZOOM_CONTINUOUS (V4L2_CID_CAMERA_CLASS_BASE+15) #define V4L2_CID_PRIVACY (V4L2_CID_CAMERA_CLASS_BASE+16) #define V4L2_CID_IRIS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+17) #define V4L2_CID_IRIS_RELATIVE (V4L2_CID_CAMERA_CLASS_BASE+18) #define V4L2_CID_AUTO_EXPOSURE_BIAS (V4L2_CID_CAMERA_CLASS_BASE+19) #define V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE (V4L2_CID_CAMERA_CLASS_BASE+20) enum v4l2_auto_n_preset_white_balance { V4L2_WHITE_BALANCE_MANUAL = 0, V4L2_WHITE_BALANCE_AUTO = 1, V4L2_WHITE_BALANCE_INCANDESCENT = 2, V4L2_WHITE_BALANCE_FLUORESCENT = 3, V4L2_WHITE_BALANCE_FLUORESCENT_H = 4, V4L2_WHITE_BALANCE_HORIZON = 5, V4L2_WHITE_BALANCE_DAYLIGHT = 6, V4L2_WHITE_BALANCE_FLASH = 7, V4L2_WHITE_BALANCE_CLOUDY = 8, V4L2_WHITE_BALANCE_SHADE = 9, }; #define V4L2_CID_WIDE_DYNAMIC_RANGE (V4L2_CID_CAMERA_CLASS_BASE+21) #define V4L2_CID_IMAGE_STABILIZATION (V4L2_CID_CAMERA_CLASS_BASE+22) #define V4L2_CID_ISO_SENSITIVITY (V4L2_CID_CAMERA_CLASS_BASE+23) #define V4L2_CID_ISO_SENSITIVITY_AUTO (V4L2_CID_CAMERA_CLASS_BASE+24) enum v4l2_iso_sensitivity_auto_type { V4L2_ISO_SENSITIVITY_MANUAL = 0, V4L2_ISO_SENSITIVITY_AUTO = 1, }; #define V4L2_CID_EXPOSURE_METERING (V4L2_CID_CAMERA_CLASS_BASE+25) enum v4l2_exposure_metering { V4L2_EXPOSURE_METERING_AVERAGE = 0, V4L2_EXPOSURE_METERING_CENTER_WEIGHTED = 1, V4L2_EXPOSURE_METERING_SPOT = 2, V4L2_EXPOSURE_METERING_MATRIX = 3, }; #define V4L2_CID_SCENE_MODE (V4L2_CID_CAMERA_CLASS_BASE+26) enum v4l2_scene_mode { V4L2_SCENE_MODE_NONE = 0, V4L2_SCENE_MODE_BACKLIGHT = 1, V4L2_SCENE_MODE_BEACH_SNOW = 2, V4L2_SCENE_MODE_CANDLE_LIGHT = 3, V4L2_SCENE_MODE_DAWN_DUSK = 4, V4L2_SCENE_MODE_FALL_COLORS = 5, V4L2_SCENE_MODE_FIREWORKS = 6, V4L2_SCENE_MODE_LANDSCAPE = 7, V4L2_SCENE_MODE_NIGHT = 8, V4L2_SCENE_MODE_PARTY_INDOOR = 9, V4L2_SCENE_MODE_PORTRAIT = 10, V4L2_SCENE_MODE_SPORTS = 11, V4L2_SCENE_MODE_SUNSET = 12, V4L2_SCENE_MODE_TEXT = 13, }; #define V4L2_CID_3A_LOCK (V4L2_CID_CAMERA_CLASS_BASE+27) #define V4L2_LOCK_EXPOSURE (1 << 0) #define V4L2_LOCK_WHITE_BALANCE (1 << 1) #define V4L2_LOCK_FOCUS (1 << 2) #define V4L2_CID_AUTO_FOCUS_START (V4L2_CID_CAMERA_CLASS_BASE+28) #define V4L2_CID_AUTO_FOCUS_STOP (V4L2_CID_CAMERA_CLASS_BASE+29) #define V4L2_CID_AUTO_FOCUS_STATUS (V4L2_CID_CAMERA_CLASS_BASE+30) #define V4L2_AUTO_FOCUS_STATUS_IDLE (0 << 0) #define V4L2_AUTO_FOCUS_STATUS_BUSY (1 << 0) #define V4L2_AUTO_FOCUS_STATUS_REACHED (1 << 1) #define V4L2_AUTO_FOCUS_STATUS_FAILED (1 << 2) #define V4L2_CID_AUTO_FOCUS_RANGE (V4L2_CID_CAMERA_CLASS_BASE+31) enum v4l2_auto_focus_range { V4L2_AUTO_FOCUS_RANGE_AUTO = 0, V4L2_AUTO_FOCUS_RANGE_NORMAL = 1, V4L2_AUTO_FOCUS_RANGE_MACRO = 2, V4L2_AUTO_FOCUS_RANGE_INFINITY = 3, }; #define V4L2_CID_PAN_SPEED (V4L2_CID_CAMERA_CLASS_BASE+32) #define V4L2_CID_TILT_SPEED (V4L2_CID_CAMERA_CLASS_BASE+33) /* FM Modulator class control IDs */ #define V4L2_CID_FM_TX_CLASS_BASE (V4L2_CTRL_CLASS_FM_TX | 0x900) #define V4L2_CID_FM_TX_CLASS (V4L2_CTRL_CLASS_FM_TX | 1) #define V4L2_CID_RDS_TX_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 1) #define V4L2_CID_RDS_TX_PI (V4L2_CID_FM_TX_CLASS_BASE + 2) #define V4L2_CID_RDS_TX_PTY (V4L2_CID_FM_TX_CLASS_BASE + 3) #define V4L2_CID_RDS_TX_PS_NAME (V4L2_CID_FM_TX_CLASS_BASE + 5) #define V4L2_CID_RDS_TX_RADIO_TEXT (V4L2_CID_FM_TX_CLASS_BASE + 6) #define V4L2_CID_RDS_TX_MONO_STEREO (V4L2_CID_FM_TX_CLASS_BASE + 7) #define V4L2_CID_RDS_TX_ARTIFICIAL_HEAD (V4L2_CID_FM_TX_CLASS_BASE + 8) #define V4L2_CID_RDS_TX_COMPRESSED (V4L2_CID_FM_TX_CLASS_BASE + 9) #define V4L2_CID_RDS_TX_DYNAMIC_PTY (V4L2_CID_FM_TX_CLASS_BASE + 10) #define V4L2_CID_RDS_TX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_TX_CLASS_BASE + 11) #define V4L2_CID_RDS_TX_TRAFFIC_PROGRAM (V4L2_CID_FM_TX_CLASS_BASE + 12) #define V4L2_CID_RDS_TX_MUSIC_SPEECH (V4L2_CID_FM_TX_CLASS_BASE + 13) #define V4L2_CID_RDS_TX_ALT_FREQS_ENABLE (V4L2_CID_FM_TX_CLASS_BASE + 14) #define V4L2_CID_RDS_TX_ALT_FREQS (V4L2_CID_FM_TX_CLASS_BASE + 15) #define V4L2_CID_AUDIO_LIMITER_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 64) #define V4L2_CID_AUDIO_LIMITER_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 65) #define V4L2_CID_AUDIO_LIMITER_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 66) #define V4L2_CID_AUDIO_COMPRESSION_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 80) #define V4L2_CID_AUDIO_COMPRESSION_GAIN (V4L2_CID_FM_TX_CLASS_BASE + 81) #define V4L2_CID_AUDIO_COMPRESSION_THRESHOLD (V4L2_CID_FM_TX_CLASS_BASE + 82) #define V4L2_CID_AUDIO_COMPRESSION_ATTACK_TIME (V4L2_CID_FM_TX_CLASS_BASE + 83) #define V4L2_CID_AUDIO_COMPRESSION_RELEASE_TIME (V4L2_CID_FM_TX_CLASS_BASE + 84) #define V4L2_CID_PILOT_TONE_ENABLED (V4L2_CID_FM_TX_CLASS_BASE + 96) #define V4L2_CID_PILOT_TONE_DEVIATION (V4L2_CID_FM_TX_CLASS_BASE + 97) #define V4L2_CID_PILOT_TONE_FREQUENCY (V4L2_CID_FM_TX_CLASS_BASE + 98) #define V4L2_CID_TUNE_PREEMPHASIS (V4L2_CID_FM_TX_CLASS_BASE + 112) enum v4l2_preemphasis { V4L2_PREEMPHASIS_DISABLED = 0, V4L2_PREEMPHASIS_50_uS = 1, V4L2_PREEMPHASIS_75_uS = 2, }; #define V4L2_CID_TUNE_POWER_LEVEL (V4L2_CID_FM_TX_CLASS_BASE + 113) #define V4L2_CID_TUNE_ANTENNA_CAPACITOR (V4L2_CID_FM_TX_CLASS_BASE + 114) /* Flash and privacy (indicator) light controls */ #define V4L2_CID_FLASH_CLASS_BASE (V4L2_CTRL_CLASS_FLASH | 0x900) #define V4L2_CID_FLASH_CLASS (V4L2_CTRL_CLASS_FLASH | 1) #define V4L2_CID_FLASH_LED_MODE (V4L2_CID_FLASH_CLASS_BASE + 1) enum v4l2_flash_led_mode { V4L2_FLASH_LED_MODE_NONE, V4L2_FLASH_LED_MODE_FLASH, V4L2_FLASH_LED_MODE_TORCH, }; #define V4L2_CID_FLASH_STROBE_SOURCE (V4L2_CID_FLASH_CLASS_BASE + 2) enum v4l2_flash_strobe_source { V4L2_FLASH_STROBE_SOURCE_SOFTWARE, V4L2_FLASH_STROBE_SOURCE_EXTERNAL, }; #define V4L2_CID_FLASH_STROBE (V4L2_CID_FLASH_CLASS_BASE + 3) #define V4L2_CID_FLASH_STROBE_STOP (V4L2_CID_FLASH_CLASS_BASE + 4) #define V4L2_CID_FLASH_STROBE_STATUS (V4L2_CID_FLASH_CLASS_BASE + 5) #define V4L2_CID_FLASH_TIMEOUT (V4L2_CID_FLASH_CLASS_BASE + 6) #define V4L2_CID_FLASH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 7) #define V4L2_CID_FLASH_TORCH_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 8) #define V4L2_CID_FLASH_INDICATOR_INTENSITY (V4L2_CID_FLASH_CLASS_BASE + 9) #define V4L2_CID_FLASH_FAULT (V4L2_CID_FLASH_CLASS_BASE + 10) #define V4L2_FLASH_FAULT_OVER_VOLTAGE (1 << 0) #define V4L2_FLASH_FAULT_TIMEOUT (1 << 1) #define V4L2_FLASH_FAULT_OVER_TEMPERATURE (1 << 2) #define V4L2_FLASH_FAULT_SHORT_CIRCUIT (1 << 3) #define V4L2_FLASH_FAULT_OVER_CURRENT (1 << 4) #define V4L2_FLASH_FAULT_INDICATOR (1 << 5) #define V4L2_FLASH_FAULT_UNDER_VOLTAGE (1 << 6) #define V4L2_FLASH_FAULT_INPUT_VOLTAGE (1 << 7) #define V4L2_FLASH_FAULT_LED_OVER_TEMPERATURE (1 << 8) #define V4L2_CID_FLASH_CHARGE (V4L2_CID_FLASH_CLASS_BASE + 11) #define V4L2_CID_FLASH_READY (V4L2_CID_FLASH_CLASS_BASE + 12) /* JPEG-class control IDs */ #define V4L2_CID_JPEG_CLASS_BASE (V4L2_CTRL_CLASS_JPEG | 0x900) #define V4L2_CID_JPEG_CLASS (V4L2_CTRL_CLASS_JPEG | 1) #define V4L2_CID_JPEG_CHROMA_SUBSAMPLING (V4L2_CID_JPEG_CLASS_BASE + 1) enum v4l2_jpeg_chroma_subsampling { V4L2_JPEG_CHROMA_SUBSAMPLING_444 = 0, V4L2_JPEG_CHROMA_SUBSAMPLING_422 = 1, V4L2_JPEG_CHROMA_SUBSAMPLING_420 = 2, V4L2_JPEG_CHROMA_SUBSAMPLING_411 = 3, V4L2_JPEG_CHROMA_SUBSAMPLING_410 = 4, V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY = 5, }; #define V4L2_CID_JPEG_RESTART_INTERVAL (V4L2_CID_JPEG_CLASS_BASE + 2) #define V4L2_CID_JPEG_COMPRESSION_QUALITY (V4L2_CID_JPEG_CLASS_BASE + 3) #define V4L2_CID_JPEG_ACTIVE_MARKER (V4L2_CID_JPEG_CLASS_BASE + 4) #define V4L2_JPEG_ACTIVE_MARKER_APP0 (1 << 0) #define V4L2_JPEG_ACTIVE_MARKER_APP1 (1 << 1) #define V4L2_JPEG_ACTIVE_MARKER_COM (1 << 16) #define V4L2_JPEG_ACTIVE_MARKER_DQT (1 << 17) #define V4L2_JPEG_ACTIVE_MARKER_DHT (1 << 18) /* Image source controls */ #define V4L2_CID_IMAGE_SOURCE_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_SOURCE | 0x900) #define V4L2_CID_IMAGE_SOURCE_CLASS (V4L2_CTRL_CLASS_IMAGE_SOURCE | 1) #define V4L2_CID_VBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 1) #define V4L2_CID_HBLANK (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 2) #define V4L2_CID_ANALOGUE_GAIN (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 3) #define V4L2_CID_TEST_PATTERN_RED (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 4) #define V4L2_CID_TEST_PATTERN_GREENR (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 5) #define V4L2_CID_TEST_PATTERN_BLUE (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 6) #define V4L2_CID_TEST_PATTERN_GREENB (V4L2_CID_IMAGE_SOURCE_CLASS_BASE + 7) /* Image processing controls */ #define V4L2_CID_IMAGE_PROC_CLASS_BASE (V4L2_CTRL_CLASS_IMAGE_PROC | 0x900) #define V4L2_CID_IMAGE_PROC_CLASS (V4L2_CTRL_CLASS_IMAGE_PROC | 1) #define V4L2_CID_LINK_FREQ (V4L2_CID_IMAGE_PROC_CLASS_BASE + 1) #define V4L2_CID_PIXEL_RATE (V4L2_CID_IMAGE_PROC_CLASS_BASE + 2) #define V4L2_CID_TEST_PATTERN (V4L2_CID_IMAGE_PROC_CLASS_BASE + 3) #define V4L2_CID_DEINTERLACING_MODE (V4L2_CID_IMAGE_PROC_CLASS_BASE + 4) #define V4L2_CID_DIGITAL_GAIN (V4L2_CID_IMAGE_PROC_CLASS_BASE + 5) /* DV-class control IDs defined by V4L2 */ #define V4L2_CID_DV_CLASS_BASE (V4L2_CTRL_CLASS_DV | 0x900) #define V4L2_CID_DV_CLASS (V4L2_CTRL_CLASS_DV | 1) #define V4L2_CID_DV_TX_HOTPLUG (V4L2_CID_DV_CLASS_BASE + 1) #define V4L2_CID_DV_TX_RXSENSE (V4L2_CID_DV_CLASS_BASE + 2) #define V4L2_CID_DV_TX_EDID_PRESENT (V4L2_CID_DV_CLASS_BASE + 3) #define V4L2_CID_DV_TX_MODE (V4L2_CID_DV_CLASS_BASE + 4) enum v4l2_dv_tx_mode { V4L2_DV_TX_MODE_DVI_D = 0, V4L2_DV_TX_MODE_HDMI = 1, }; #define V4L2_CID_DV_TX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 5) enum v4l2_dv_rgb_range { V4L2_DV_RGB_RANGE_AUTO = 0, V4L2_DV_RGB_RANGE_LIMITED = 1, V4L2_DV_RGB_RANGE_FULL = 2, }; #define V4L2_CID_DV_TX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 6) enum v4l2_dv_it_content_type { V4L2_DV_IT_CONTENT_TYPE_GRAPHICS = 0, V4L2_DV_IT_CONTENT_TYPE_PHOTO = 1, V4L2_DV_IT_CONTENT_TYPE_CINEMA = 2, V4L2_DV_IT_CONTENT_TYPE_GAME = 3, V4L2_DV_IT_CONTENT_TYPE_NO_ITC = 4, }; #define V4L2_CID_DV_RX_POWER_PRESENT (V4L2_CID_DV_CLASS_BASE + 100) #define V4L2_CID_DV_RX_RGB_RANGE (V4L2_CID_DV_CLASS_BASE + 101) #define V4L2_CID_DV_RX_IT_CONTENT_TYPE (V4L2_CID_DV_CLASS_BASE + 102) #define V4L2_CID_FM_RX_CLASS_BASE (V4L2_CTRL_CLASS_FM_RX | 0x900) #define V4L2_CID_FM_RX_CLASS (V4L2_CTRL_CLASS_FM_RX | 1) #define V4L2_CID_TUNE_DEEMPHASIS (V4L2_CID_FM_RX_CLASS_BASE + 1) enum v4l2_deemphasis { V4L2_DEEMPHASIS_DISABLED = V4L2_PREEMPHASIS_DISABLED, V4L2_DEEMPHASIS_50_uS = V4L2_PREEMPHASIS_50_uS, V4L2_DEEMPHASIS_75_uS = V4L2_PREEMPHASIS_75_uS, }; #define V4L2_CID_RDS_RECEPTION (V4L2_CID_FM_RX_CLASS_BASE + 2) #define V4L2_CID_RDS_RX_PTY (V4L2_CID_FM_RX_CLASS_BASE + 3) #define V4L2_CID_RDS_RX_PS_NAME (V4L2_CID_FM_RX_CLASS_BASE + 4) #define V4L2_CID_RDS_RX_RADIO_TEXT (V4L2_CID_FM_RX_CLASS_BASE + 5) #define V4L2_CID_RDS_RX_TRAFFIC_ANNOUNCEMENT (V4L2_CID_FM_RX_CLASS_BASE + 6) #define V4L2_CID_RDS_RX_TRAFFIC_PROGRAM (V4L2_CID_FM_RX_CLASS_BASE + 7) #define V4L2_CID_RDS_RX_MUSIC_SPEECH (V4L2_CID_FM_RX_CLASS_BASE + 8) #define V4L2_CID_RF_TUNER_CLASS_BASE (V4L2_CTRL_CLASS_RF_TUNER | 0x900) #define V4L2_CID_RF_TUNER_CLASS (V4L2_CTRL_CLASS_RF_TUNER | 1) #define V4L2_CID_RF_TUNER_BANDWIDTH_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 11) #define V4L2_CID_RF_TUNER_BANDWIDTH (V4L2_CID_RF_TUNER_CLASS_BASE + 12) #define V4L2_CID_RF_TUNER_RF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 32) #define V4L2_CID_RF_TUNER_LNA_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 41) #define V4L2_CID_RF_TUNER_LNA_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 42) #define V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 51) #define V4L2_CID_RF_TUNER_MIXER_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 52) #define V4L2_CID_RF_TUNER_IF_GAIN_AUTO (V4L2_CID_RF_TUNER_CLASS_BASE + 61) #define V4L2_CID_RF_TUNER_IF_GAIN (V4L2_CID_RF_TUNER_CLASS_BASE + 62) #define V4L2_CID_RF_TUNER_PLL_LOCK (V4L2_CID_RF_TUNER_CLASS_BASE + 91) /* Detection-class control IDs defined by V4L2 */ #define V4L2_CID_DETECT_CLASS_BASE (V4L2_CTRL_CLASS_DETECT | 0x900) #define V4L2_CID_DETECT_CLASS (V4L2_CTRL_CLASS_DETECT | 1) #define V4L2_CID_DETECT_MD_MODE (V4L2_CID_DETECT_CLASS_BASE + 1) enum v4l2_detect_md_mode { V4L2_DETECT_MD_MODE_DISABLED = 0, V4L2_DETECT_MD_MODE_GLOBAL = 1, V4L2_DETECT_MD_MODE_THRESHOLD_GRID = 2, V4L2_DETECT_MD_MODE_REGION_GRID = 3, }; #define V4L2_CID_DETECT_MD_GLOBAL_THRESHOLD (V4L2_CID_DETECT_CLASS_BASE + 2) #define V4L2_CID_DETECT_MD_THRESHOLD_GRID (V4L2_CID_DETECT_CLASS_BASE + 3) #define V4L2_CID_DETECT_MD_REGION_GRID (V4L2_CID_DETECT_CLASS_BASE + 4) #define V4L2_MPEG2_PICTURE_CODING_TYPE_I 1 #define V4L2_MPEG2_PICTURE_CODING_TYPE_P 2 #define V4L2_MPEG2_PICTURE_CODING_TYPE_B 3 #define V4L2_MPEG2_PICTURE_CODING_TYPE_D 4 struct v4l2_mpeg2_sequence { /* ISO/IEC 13818-2, ITU-T Rec. H.262: Sequence header */ __u16 horizontal_size; __u16 vertical_size; __u32 vbv_buffer_size; /* ISO/IEC 13818-2, ITU-T Rec. H.262: Sequence extension */ __u8 profile_and_level_indication; __u8 progressive_sequence; __u8 chroma_format; __u8 pad; }; struct v4l2_mpeg2_picture { /* ISO/IEC 13818-2, ITU-T Rec. H.262: Picture header */ __u8 picture_coding_type; /* ISO/IEC 13818-2, ITU-T Rec. H.262: Picture coding extension */ __u8 f_code[2][2]; __u8 intra_dc_precision; __u8 picture_structure; __u8 top_field_first; __u8 frame_pred_frame_dct; __u8 concealment_motion_vectors; __u8 q_scale_type; __u8 intra_vlc_format; __u8 alternate_scan; __u8 repeat_first_field; __u8 progressive_frame; __u8 pad; }; struct v4l2_ctrl_mpeg2_slice_params { __u32 bit_size; __u32 data_bit_offset; struct v4l2_mpeg2_sequence sequence; struct v4l2_mpeg2_picture picture; /* ISO/IEC 13818-2, ITU-T Rec. H.262: Slice */ __u8 quantiser_scale_code; __u8 backward_ref_index; __u8 forward_ref_index; __u8 pad; }; struct v4l2_ctrl_mpeg2_quantization { /* ISO/IEC 13818-2, ITU-T Rec. H.262: Quant matrix extension */ __u8 load_intra_quantiser_matrix; __u8 load_non_intra_quantiser_matrix; __u8 load_chroma_intra_quantiser_matrix; __u8 load_chroma_non_intra_quantiser_matrix; __u8 intra_quantiser_matrix[64]; __u8 non_intra_quantiser_matrix[64]; __u8 chroma_intra_quantiser_matrix[64]; __u8 chroma_non_intra_quantiser_matrix[64]; }; #endif linux/am437x-vpfe.h000064400000007141151027430560010043 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) 2013 - 2014 Texas Instruments, Inc. * * Benoit Parrot * Lad, Prabhakar * * This program is free software; you may redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef AM437X_VPFE_USER_H #define AM437X_VPFE_USER_H #include enum vpfe_ccdc_data_size { VPFE_CCDC_DATA_16BITS = 0, VPFE_CCDC_DATA_15BITS, VPFE_CCDC_DATA_14BITS, VPFE_CCDC_DATA_13BITS, VPFE_CCDC_DATA_12BITS, VPFE_CCDC_DATA_11BITS, VPFE_CCDC_DATA_10BITS, VPFE_CCDC_DATA_8BITS, }; /* enum for No of pixel per line to be avg. in Black Clamping*/ enum vpfe_ccdc_sample_length { VPFE_CCDC_SAMPLE_1PIXELS = 0, VPFE_CCDC_SAMPLE_2PIXELS, VPFE_CCDC_SAMPLE_4PIXELS, VPFE_CCDC_SAMPLE_8PIXELS, VPFE_CCDC_SAMPLE_16PIXELS, }; /* enum for No of lines in Black Clamping */ enum vpfe_ccdc_sample_line { VPFE_CCDC_SAMPLE_1LINES = 0, VPFE_CCDC_SAMPLE_2LINES, VPFE_CCDC_SAMPLE_4LINES, VPFE_CCDC_SAMPLE_8LINES, VPFE_CCDC_SAMPLE_16LINES, }; /* enum for Alaw gamma width */ enum vpfe_ccdc_gamma_width { VPFE_CCDC_GAMMA_BITS_15_6 = 0, /* use bits 15-6 for gamma */ VPFE_CCDC_GAMMA_BITS_14_5, VPFE_CCDC_GAMMA_BITS_13_4, VPFE_CCDC_GAMMA_BITS_12_3, VPFE_CCDC_GAMMA_BITS_11_2, VPFE_CCDC_GAMMA_BITS_10_1, VPFE_CCDC_GAMMA_BITS_09_0, /* use bits 9-0 for gamma */ }; /* structure for ALaw */ struct vpfe_ccdc_a_law { /* Enable/disable A-Law */ unsigned char enable; /* Gamma Width Input */ enum vpfe_ccdc_gamma_width gamma_wd; }; /* structure for Black Clamping */ struct vpfe_ccdc_black_clamp { unsigned char enable; /* only if bClampEnable is TRUE */ enum vpfe_ccdc_sample_length sample_pixel; /* only if bClampEnable is TRUE */ enum vpfe_ccdc_sample_line sample_ln; /* only if bClampEnable is TRUE */ unsigned short start_pixel; /* only if bClampEnable is TRUE */ unsigned short sgain; /* only if bClampEnable is FALSE */ unsigned short dc_sub; }; /* structure for Black Level Compensation */ struct vpfe_ccdc_black_compensation { /* Constant value to subtract from Red component */ char r; /* Constant value to subtract from Gr component */ char gr; /* Constant value to subtract from Blue component */ char b; /* Constant value to subtract from Gb component */ char gb; }; /* Structure for CCDC configuration parameters for raw capture mode passed * by application */ struct vpfe_ccdc_config_params_raw { /* data size value from 8 to 16 bits */ enum vpfe_ccdc_data_size data_sz; /* Structure for Optional A-Law */ struct vpfe_ccdc_a_law alaw; /* Structure for Optical Black Clamp */ struct vpfe_ccdc_black_clamp blk_clamp; /* Structure for Black Compensation */ struct vpfe_ccdc_black_compensation blk_comp; }; /* * Private IOCTL * VIDIOC_AM437X_CCDC_CFG - Set CCDC configuration for raw capture * This is an experimental ioctl that will change in future kernels. So use * this ioctl with care ! **/ #define VIDIOC_AM437X_CCDC_CFG \ _IOW('V', BASE_VIDIOC_PRIVATE + 1, void *) #endif /* AM437X_VPFE_USER_H */ linux/if_frad.h000064400000005713151027430560007457 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * DLCI/FRAD Definitions for Frame Relay Access Devices. DLCI devices are * created for each DLCI associated with a FRAD. The FRAD driver * is not truly a network device, but the lower level device * handler. This allows other FRAD manufacturers to use the DLCI * code, including its RFC1490 encapsulation alongside the current * implementation for the Sangoma cards. * * Version: @(#)if_ifrad.h 0.15 31 Mar 96 * * Author: Mike McLagan * * Changes: * 0.15 Mike McLagan changed structure defs (packed) * re-arranged flags * added DLCI_RET vars * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _FRAD_H_ #define _FRAD_H_ #include /* Structures and constants associated with the DLCI device driver */ struct dlci_add { char devname[IFNAMSIZ]; short dlci; }; #define DLCI_GET_CONF (SIOCDEVPRIVATE + 2) #define DLCI_SET_CONF (SIOCDEVPRIVATE + 3) /* * These are related to the Sangoma SDLA and should remain in order. * Code within the SDLA module is based on the specifics of this * structure. Change at your own peril. */ struct dlci_conf { short flags; short CIR_fwd; short Bc_fwd; short Be_fwd; short CIR_bwd; short Bc_bwd; short Be_bwd; /* these are part of the status read */ short Tc_fwd; short Tc_bwd; short Tf_max; short Tb_max; /* add any new fields here above is a mirror of sdla_dlci_conf */ }; #define DLCI_GET_SLAVE (SIOCDEVPRIVATE + 4) /* configuration flags for DLCI */ #define DLCI_IGNORE_CIR_OUT 0x0001 #define DLCI_ACCOUNT_CIR_IN 0x0002 #define DLCI_BUFFER_IF 0x0008 #define DLCI_VALID_FLAGS 0x000B /* defines for the actual Frame Relay hardware */ #define FRAD_GET_CONF (SIOCDEVPRIVATE) #define FRAD_SET_CONF (SIOCDEVPRIVATE + 1) #define FRAD_LAST_IOCTL FRAD_SET_CONF /* * Based on the setup for the Sangoma SDLA. If changes are * necessary to this structure, a routine will need to be * added to that module to copy fields. */ struct frad_conf { short station; short flags; short kbaud; short clocking; short mtu; short T391; short T392; short N391; short N392; short N393; short CIR_fwd; short Bc_fwd; short Be_fwd; short CIR_bwd; short Bc_bwd; short Be_bwd; /* Add new fields here, above is a mirror of the sdla_conf */ }; #define FRAD_STATION_CPE 0x0000 #define FRAD_STATION_NODE 0x0001 #define FRAD_TX_IGNORE_CIR 0x0001 #define FRAD_RX_ACCOUNT_CIR 0x0002 #define FRAD_DROP_ABORTED 0x0004 #define FRAD_BUFFERIF 0x0008 #define FRAD_STATS 0x0010 #define FRAD_MCI 0x0100 #define FRAD_AUTODLCI 0x8000 #define FRAD_VALID_FLAGS 0x811F #define FRAD_CLOCK_INT 0x0001 #define FRAD_CLOCK_EXT 0x0000 #endif /* _FRAD_H_ */ linux/net.h000064400000004045151027430560006650 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * NET An implementation of the SOCKET network access protocol. * This is the master header file for the Linux NET layer, * or, in plain English: the networking handling part of the * kernel. * * Version: @(#)net.h 1.0.3 05/25/93 * * Authors: Orest Zborowski, * Ross Biro * Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_NET_H #define _LINUX_NET_H #include #include #define NPROTO AF_MAX #define SYS_SOCKET 1 /* sys_socket(2) */ #define SYS_BIND 2 /* sys_bind(2) */ #define SYS_CONNECT 3 /* sys_connect(2) */ #define SYS_LISTEN 4 /* sys_listen(2) */ #define SYS_ACCEPT 5 /* sys_accept(2) */ #define SYS_GETSOCKNAME 6 /* sys_getsockname(2) */ #define SYS_GETPEERNAME 7 /* sys_getpeername(2) */ #define SYS_SOCKETPAIR 8 /* sys_socketpair(2) */ #define SYS_SEND 9 /* sys_send(2) */ #define SYS_RECV 10 /* sys_recv(2) */ #define SYS_SENDTO 11 /* sys_sendto(2) */ #define SYS_RECVFROM 12 /* sys_recvfrom(2) */ #define SYS_SHUTDOWN 13 /* sys_shutdown(2) */ #define SYS_SETSOCKOPT 14 /* sys_setsockopt(2) */ #define SYS_GETSOCKOPT 15 /* sys_getsockopt(2) */ #define SYS_SENDMSG 16 /* sys_sendmsg(2) */ #define SYS_RECVMSG 17 /* sys_recvmsg(2) */ #define SYS_ACCEPT4 18 /* sys_accept4(2) */ #define SYS_RECVMMSG 19 /* sys_recvmmsg(2) */ #define SYS_SENDMMSG 20 /* sys_sendmmsg(2) */ typedef enum { SS_FREE = 0, /* not allocated */ SS_UNCONNECTED, /* unconnected to any socket */ SS_CONNECTING, /* in process of connecting */ SS_CONNECTED, /* connected to socket */ SS_DISCONNECTING /* in process of disconnecting */ } socket_state; #define __SO_ACCEPTCON (1 << 16) /* performed a listen */ #endif /* _LINUX_NET_H */ linux/coda.h000064400000042141151027430560006767 0ustar00/* You may distribute this file under either of the two licenses that follow at your discretion. */ /* BLURB lgpl Coda File System Release 5 Copyright (c) 1987-1999 Carnegie Mellon University Additional copyrights listed below This code is distributed "AS IS" without warranty of any kind under the terms of the GNU Library General Public Licence Version 2, as shown in the file LICENSE, or under the license shown below. The technical and financial contributors to Coda are listed in the file CREDITS. Additional copyrights */ /* Coda: an Experimental Distributed File System Release 4.0 Copyright (c) 1987-1999 Carnegie Mellon University All Rights Reserved Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation, and that credit is given to Carnegie Mellon University in all documents and publicity pertaining to direct or indirect use of this code or its derivatives. CODA IS AN EXPERIMENTAL SOFTWARE SYSTEM AND IS KNOWN TO HAVE BUGS, SOME OF WHICH MAY HAVE SERIOUS CONSEQUENCES. CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING DIRECTLY OR INDIRECTLY FROM THE USE OF THIS SOFTWARE OR OF ANY DERIVATIVE WORK. Carnegie Mellon encourages users of this software to return any improvements or extensions that they make, and to grant Carnegie Mellon the rights to redistribute these changes without encumbrance. */ /* * * Based on cfs.h from Mach, but revamped for increased simplicity. * Linux modifications by * Peter Braam, Aug 1996 */ #ifndef _CODA_HEADER_ #define _CODA_HEADER_ /* Catch new _KERNEL defn for NetBSD and DJGPP/__CYGWIN32__ */ #if defined(__NetBSD__) || \ ((defined(DJGPP) || defined(__CYGWIN32__)) && !defined(KERNEL)) #include #endif #ifndef CODA_MAXSYMLINKS #define CODA_MAXSYMLINKS 10 #endif #if defined(DJGPP) || defined(__CYGWIN32__) #ifdef KERNEL typedef unsigned long u_long; typedef unsigned int u_int; typedef unsigned short u_short; typedef u_long ino_t; typedef u_long dev_t; typedef void * caddr_t; #ifdef DOS typedef unsigned __int64 u_quad_t; #else typedef unsigned long long u_quad_t; #endif #define __inline__ struct timespec { long ts_sec; long ts_nsec; }; #else /* DJGPP but not KERNEL */ #include typedef unsigned long long u_quad_t; #endif /* !KERNEL */ #endif /* !DJGPP */ #if defined(__linux__) #include #define cdev_t u_quad_t #if !defined(_UQUAD_T_) && (!defined(__GLIBC__) || __GLIBC__ < 2) #define _UQUAD_T_ 1 typedef unsigned long long u_quad_t; #endif #else #define cdev_t dev_t #endif #ifdef __CYGWIN32__ struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; #endif #ifndef __BIT_TYPES_DEFINED__ #define __BIT_TYPES_DEFINED__ typedef signed char int8_t; typedef unsigned char u_int8_t; typedef short int16_t; typedef unsigned short u_int16_t; typedef int int32_t; typedef unsigned int u_int32_t; #endif /* * Cfs constants */ #define CODA_MAXNAMLEN 255 #define CODA_MAXPATHLEN 1024 #define CODA_MAXSYMLINK 10 /* these are Coda's version of O_RDONLY etc combinations * to deal with VFS open modes */ #define C_O_READ 0x001 #define C_O_WRITE 0x002 #define C_O_TRUNC 0x010 #define C_O_EXCL 0x100 #define C_O_CREAT 0x200 /* these are to find mode bits in Venus */ #define C_M_READ 00400 #define C_M_WRITE 00200 /* for access Venus will use */ #define C_A_C_OK 8 /* Test for writing upon create. */ #define C_A_R_OK 4 /* Test for read permission. */ #define C_A_W_OK 2 /* Test for write permission. */ #define C_A_X_OK 1 /* Test for execute permission. */ #define C_A_F_OK 0 /* Test for existence. */ #ifndef _VENUS_DIRENT_T_ #define _VENUS_DIRENT_T_ 1 struct venus_dirent { u_int32_t d_fileno; /* file number of entry */ u_int16_t d_reclen; /* length of this record */ u_int8_t d_type; /* file type, see below */ u_int8_t d_namlen; /* length of string in d_name */ char d_name[CODA_MAXNAMLEN + 1];/* name must be no longer than this */ }; #undef DIRSIZ #define DIRSIZ(dp) ((sizeof (struct venus_dirent) - (CODA_MAXNAMLEN+1)) + \ (((dp)->d_namlen+1 + 3) &~ 3)) /* * File types */ #define CDT_UNKNOWN 0 #define CDT_FIFO 1 #define CDT_CHR 2 #define CDT_DIR 4 #define CDT_BLK 6 #define CDT_REG 8 #define CDT_LNK 10 #define CDT_SOCK 12 #define CDT_WHT 14 /* * Convert between stat structure types and directory types. */ #define IFTOCDT(mode) (((mode) & 0170000) >> 12) #define CDTTOIF(dirtype) ((dirtype) << 12) #endif #ifndef _VUID_T_ #define _VUID_T_ typedef u_int32_t vuid_t; typedef u_int32_t vgid_t; #endif /*_VUID_T_ */ struct CodaFid { u_int32_t opaque[4]; }; #define coda_f2i(fid)\ (fid ? (fid->opaque[3] ^ (fid->opaque[2]<<10) ^ (fid->opaque[1]<<20) ^ fid->opaque[0]) : 0) #ifndef _VENUS_VATTR_T_ #define _VENUS_VATTR_T_ /* * Vnode types. VNON means no type. */ enum coda_vtype { C_VNON, C_VREG, C_VDIR, C_VBLK, C_VCHR, C_VLNK, C_VSOCK, C_VFIFO, C_VBAD }; struct coda_vattr { long va_type; /* vnode type (for create) */ u_short va_mode; /* files access mode and type */ short va_nlink; /* number of references to file */ vuid_t va_uid; /* owner user id */ vgid_t va_gid; /* owner group id */ long va_fileid; /* file id */ u_quad_t va_size; /* file size in bytes */ long va_blocksize; /* blocksize preferred for i/o */ struct timespec va_atime; /* time of last access */ struct timespec va_mtime; /* time of last modification */ struct timespec va_ctime; /* time file changed */ u_long va_gen; /* generation number of file */ u_long va_flags; /* flags defined for file */ cdev_t va_rdev; /* device special file represents */ u_quad_t va_bytes; /* bytes of disk space held by file */ u_quad_t va_filerev; /* file modification number */ }; #endif /* structure used by CODA_STATFS for getting cache information from venus */ struct coda_statfs { int32_t f_blocks; int32_t f_bfree; int32_t f_bavail; int32_t f_files; int32_t f_ffree; }; /* * Kernel <--> Venus communications. */ #define CODA_ROOT 2 #define CODA_OPEN_BY_FD 3 #define CODA_OPEN 4 #define CODA_CLOSE 5 #define CODA_IOCTL 6 #define CODA_GETATTR 7 #define CODA_SETATTR 8 #define CODA_ACCESS 9 #define CODA_LOOKUP 10 #define CODA_CREATE 11 #define CODA_REMOVE 12 #define CODA_LINK 13 #define CODA_RENAME 14 #define CODA_MKDIR 15 #define CODA_RMDIR 16 #define CODA_SYMLINK 18 #define CODA_READLINK 19 #define CODA_FSYNC 20 #define CODA_VGET 22 #define CODA_SIGNAL 23 #define CODA_REPLACE 24 /* DOWNCALL */ #define CODA_FLUSH 25 /* DOWNCALL */ #define CODA_PURGEUSER 26 /* DOWNCALL */ #define CODA_ZAPFILE 27 /* DOWNCALL */ #define CODA_ZAPDIR 28 /* DOWNCALL */ #define CODA_PURGEFID 30 /* DOWNCALL */ #define CODA_OPEN_BY_PATH 31 #define CODA_RESOLVE 32 #define CODA_REINTEGRATE 33 #define CODA_STATFS 34 #define CODA_STORE 35 #define CODA_RELEASE 36 #define CODA_NCALLS 37 #define DOWNCALL(opcode) (opcode >= CODA_REPLACE && opcode <= CODA_PURGEFID) #define VC_MAXDATASIZE 8192 #define VC_MAXMSGSIZE sizeof(union inputArgs)+sizeof(union outputArgs) +\ VC_MAXDATASIZE #define CIOC_KERNEL_VERSION _IOWR('c', 10, size_t) #define CODA_KERNEL_VERSION 3 /* 128-bit file identifiers */ /* * Venus <-> Coda RPC arguments */ struct coda_in_hdr { u_int32_t opcode; u_int32_t unique; /* Keep multiple outstanding msgs distinct */ pid_t pid; pid_t pgid; vuid_t uid; }; /* Really important that opcode and unique are 1st two fields! */ struct coda_out_hdr { u_int32_t opcode; u_int32_t unique; u_int32_t result; }; /* coda_root: NO_IN */ struct coda_root_out { struct coda_out_hdr oh; struct CodaFid VFid; }; struct coda_root_in { struct coda_in_hdr in; }; /* coda_open: */ struct coda_open_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_open_out { struct coda_out_hdr oh; cdev_t dev; ino_t inode; }; /* coda_store: */ struct coda_store_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_store_out { struct coda_out_hdr out; }; /* coda_release: */ struct coda_release_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_release_out { struct coda_out_hdr out; }; /* coda_close: */ struct coda_close_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_close_out { struct coda_out_hdr out; }; /* coda_ioctl: */ struct coda_ioctl_in { struct coda_in_hdr ih; struct CodaFid VFid; int cmd; int len; int rwflag; char *data; /* Place holder for data. */ }; struct coda_ioctl_out { struct coda_out_hdr oh; int len; caddr_t data; /* Place holder for data. */ }; /* coda_getattr: */ struct coda_getattr_in { struct coda_in_hdr ih; struct CodaFid VFid; }; struct coda_getattr_out { struct coda_out_hdr oh; struct coda_vattr attr; }; /* coda_setattr: NO_OUT */ struct coda_setattr_in { struct coda_in_hdr ih; struct CodaFid VFid; struct coda_vattr attr; }; struct coda_setattr_out { struct coda_out_hdr out; }; /* coda_access: NO_OUT */ struct coda_access_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_access_out { struct coda_out_hdr out; }; /* lookup flags */ #define CLU_CASE_SENSITIVE 0x01 #define CLU_CASE_INSENSITIVE 0x02 /* coda_lookup: */ struct coda_lookup_in { struct coda_in_hdr ih; struct CodaFid VFid; int name; /* Place holder for data. */ int flags; }; struct coda_lookup_out { struct coda_out_hdr oh; struct CodaFid VFid; int vtype; }; /* coda_create: */ struct coda_create_in { struct coda_in_hdr ih; struct CodaFid VFid; struct coda_vattr attr; int excl; int mode; int name; /* Place holder for data. */ }; struct coda_create_out { struct coda_out_hdr oh; struct CodaFid VFid; struct coda_vattr attr; }; /* coda_remove: NO_OUT */ struct coda_remove_in { struct coda_in_hdr ih; struct CodaFid VFid; int name; /* Place holder for data. */ }; struct coda_remove_out { struct coda_out_hdr out; }; /* coda_link: NO_OUT */ struct coda_link_in { struct coda_in_hdr ih; struct CodaFid sourceFid; /* cnode to link *to* */ struct CodaFid destFid; /* Directory in which to place link */ int tname; /* Place holder for data. */ }; struct coda_link_out { struct coda_out_hdr out; }; /* coda_rename: NO_OUT */ struct coda_rename_in { struct coda_in_hdr ih; struct CodaFid sourceFid; int srcname; struct CodaFid destFid; int destname; }; struct coda_rename_out { struct coda_out_hdr out; }; /* coda_mkdir: */ struct coda_mkdir_in { struct coda_in_hdr ih; struct CodaFid VFid; struct coda_vattr attr; int name; /* Place holder for data. */ }; struct coda_mkdir_out { struct coda_out_hdr oh; struct CodaFid VFid; struct coda_vattr attr; }; /* coda_rmdir: NO_OUT */ struct coda_rmdir_in { struct coda_in_hdr ih; struct CodaFid VFid; int name; /* Place holder for data. */ }; struct coda_rmdir_out { struct coda_out_hdr out; }; /* coda_symlink: NO_OUT */ struct coda_symlink_in { struct coda_in_hdr ih; struct CodaFid VFid; /* Directory to put symlink in */ int srcname; struct coda_vattr attr; int tname; }; struct coda_symlink_out { struct coda_out_hdr out; }; /* coda_readlink: */ struct coda_readlink_in { struct coda_in_hdr ih; struct CodaFid VFid; }; struct coda_readlink_out { struct coda_out_hdr oh; int count; caddr_t data; /* Place holder for data. */ }; /* coda_fsync: NO_OUT */ struct coda_fsync_in { struct coda_in_hdr ih; struct CodaFid VFid; }; struct coda_fsync_out { struct coda_out_hdr out; }; /* coda_vget: */ struct coda_vget_in { struct coda_in_hdr ih; struct CodaFid VFid; }; struct coda_vget_out { struct coda_out_hdr oh; struct CodaFid VFid; int vtype; }; /* CODA_SIGNAL is out-of-band, doesn't need data. */ /* CODA_INVALIDATE is a venus->kernel call */ /* CODA_FLUSH is a venus->kernel call */ /* coda_purgeuser: */ /* CODA_PURGEUSER is a venus->kernel call */ struct coda_purgeuser_out { struct coda_out_hdr oh; vuid_t uid; }; /* coda_zapfile: */ /* CODA_ZAPFILE is a venus->kernel call */ struct coda_zapfile_out { struct coda_out_hdr oh; struct CodaFid CodaFid; }; /* coda_zapdir: */ /* CODA_ZAPDIR is a venus->kernel call */ struct coda_zapdir_out { struct coda_out_hdr oh; struct CodaFid CodaFid; }; /* coda_purgefid: */ /* CODA_PURGEFID is a venus->kernel call */ struct coda_purgefid_out { struct coda_out_hdr oh; struct CodaFid CodaFid; }; /* coda_replace: */ /* CODA_REPLACE is a venus->kernel call */ struct coda_replace_out { /* coda_replace is a venus->kernel call */ struct coda_out_hdr oh; struct CodaFid NewFid; struct CodaFid OldFid; }; /* coda_open_by_fd: */ struct coda_open_by_fd_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_open_by_fd_out { struct coda_out_hdr oh; int fd; }; /* coda_open_by_path: */ struct coda_open_by_path_in { struct coda_in_hdr ih; struct CodaFid VFid; int flags; }; struct coda_open_by_path_out { struct coda_out_hdr oh; int path; }; /* coda_statfs: NO_IN */ struct coda_statfs_in { struct coda_in_hdr in; }; struct coda_statfs_out { struct coda_out_hdr oh; struct coda_statfs stat; }; /* * Occasionally, we don't cache the fid returned by CODA_LOOKUP. * For instance, if the fid is inconsistent. * This case is handled by setting the top bit of the type result parameter. */ #define CODA_NOCACHE 0x80000000 union inputArgs { struct coda_in_hdr ih; /* NB: every struct below begins with an ih */ struct coda_open_in coda_open; struct coda_store_in coda_store; struct coda_release_in coda_release; struct coda_close_in coda_close; struct coda_ioctl_in coda_ioctl; struct coda_getattr_in coda_getattr; struct coda_setattr_in coda_setattr; struct coda_access_in coda_access; struct coda_lookup_in coda_lookup; struct coda_create_in coda_create; struct coda_remove_in coda_remove; struct coda_link_in coda_link; struct coda_rename_in coda_rename; struct coda_mkdir_in coda_mkdir; struct coda_rmdir_in coda_rmdir; struct coda_symlink_in coda_symlink; struct coda_readlink_in coda_readlink; struct coda_fsync_in coda_fsync; struct coda_vget_in coda_vget; struct coda_open_by_fd_in coda_open_by_fd; struct coda_open_by_path_in coda_open_by_path; struct coda_statfs_in coda_statfs; }; union outputArgs { struct coda_out_hdr oh; /* NB: every struct below begins with an oh */ struct coda_root_out coda_root; struct coda_open_out coda_open; struct coda_ioctl_out coda_ioctl; struct coda_getattr_out coda_getattr; struct coda_lookup_out coda_lookup; struct coda_create_out coda_create; struct coda_mkdir_out coda_mkdir; struct coda_readlink_out coda_readlink; struct coda_vget_out coda_vget; struct coda_purgeuser_out coda_purgeuser; struct coda_zapfile_out coda_zapfile; struct coda_zapdir_out coda_zapdir; struct coda_purgefid_out coda_purgefid; struct coda_replace_out coda_replace; struct coda_open_by_fd_out coda_open_by_fd; struct coda_open_by_path_out coda_open_by_path; struct coda_statfs_out coda_statfs; }; union coda_downcalls { /* CODA_INVALIDATE is a venus->kernel call */ /* CODA_FLUSH is a venus->kernel call */ struct coda_purgeuser_out purgeuser; struct coda_zapfile_out zapfile; struct coda_zapdir_out zapdir; struct coda_purgefid_out purgefid; struct coda_replace_out replace; }; /* * Used for identifying usage of "Control" and pioctls */ #define PIOCPARM_MASK 0x0000ffff struct ViceIoctl { void *in; /* Data to be transferred in */ void *out; /* Data to be transferred out */ u_short in_size; /* Size of input buffer <= 2K */ u_short out_size; /* Maximum size of output buffer, <= 2K */ }; struct PioctlData { const char *path; int follow; struct ViceIoctl vi; }; #define CODA_CONTROL ".CONTROL" #define CODA_CONTROLLEN 8 #define CTL_INO -1 /* Data passed to mount */ #define CODA_MOUNT_VERSION 1 struct coda_mount_data { int version; int fd; /* Opened device */ }; #endif /* _CODA_HEADER_ */ linux/seccomp.h000064400000004321151027430560007510 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SECCOMP_H #define _LINUX_SECCOMP_H #include /* Valid values for seccomp.mode and prctl(PR_SET_SECCOMP, ) */ #define SECCOMP_MODE_DISABLED 0 /* seccomp is not in use. */ #define SECCOMP_MODE_STRICT 1 /* uses hard-coded filter. */ #define SECCOMP_MODE_FILTER 2 /* uses user-supplied filter. */ /* Valid operations for seccomp syscall. */ #define SECCOMP_SET_MODE_STRICT 0 #define SECCOMP_SET_MODE_FILTER 1 #define SECCOMP_GET_ACTION_AVAIL 2 /* Valid flags for SECCOMP_SET_MODE_FILTER */ #define SECCOMP_FILTER_FLAG_TSYNC (1UL << 0) #define SECCOMP_FILTER_FLAG_LOG (1UL << 1) #define SECCOMP_FILTER_FLAG_SPEC_ALLOW (1UL << 2) /* * All BPF programs must return a 32-bit value. * The bottom 16-bits are for optional return data. * The upper 16-bits are ordered from least permissive values to most, * as a signed value (so 0x8000000 is negative). * * The ordering ensures that a min_t() over composed return values always * selects the least permissive choice. */ #define SECCOMP_RET_KILL_PROCESS 0x80000000U /* kill the process */ #define SECCOMP_RET_KILL_THREAD 0x00000000U /* kill the thread */ #define SECCOMP_RET_KILL SECCOMP_RET_KILL_THREAD #define SECCOMP_RET_TRAP 0x00030000U /* disallow and force a SIGSYS */ #define SECCOMP_RET_ERRNO 0x00050000U /* returns an errno */ #define SECCOMP_RET_TRACE 0x7ff00000U /* pass to a tracer or disallow */ #define SECCOMP_RET_LOG 0x7ffc0000U /* allow after logging */ #define SECCOMP_RET_ALLOW 0x7fff0000U /* allow */ /* Masks for the return value sections. */ #define SECCOMP_RET_ACTION_FULL 0xffff0000U #define SECCOMP_RET_ACTION 0x7fff0000U #define SECCOMP_RET_DATA 0x0000ffffU /** * struct seccomp_data - the format the BPF program executes over. * @nr: the system call number * @arch: indicates system call convention as an AUDIT_ARCH_* value * as defined in . * @instruction_pointer: at the time of the system call. * @args: up to 6 system call arguments always stored as 64-bit values * regardless of the architecture. */ struct seccomp_data { int nr; __u32 arch; __u64 instruction_pointer; __u64 args[6]; }; #endif /* _LINUX_SECCOMP_H */ linux/if_arp.h000064400000014661151027430560007327 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the ARP (RFC 826) protocol. * * Version: @(#)if_arp.h 1.0.1 04/16/93 * * Authors: Original taken from Berkeley UNIX 4.3, (c) UCB 1986-1988 * Portions taken from the KA9Q/NOS (v2.00m PA0GRI) source. * Ross Biro * Fred N. van Kempen, * Florian La Roche, * Jonathan Layes * Arnaldo Carvalho de Melo ARPHRD_HWX25 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_ARP_H #define _LINUX_IF_ARP_H #include /* ARP protocol HARDWARE identifiers. */ #define ARPHRD_NETROM 0 /* from KA9Q: NET/ROM pseudo */ #define ARPHRD_ETHER 1 /* Ethernet 10Mbps */ #define ARPHRD_EETHER 2 /* Experimental Ethernet */ #define ARPHRD_AX25 3 /* AX.25 Level 2 */ #define ARPHRD_PRONET 4 /* PROnet token ring */ #define ARPHRD_CHAOS 5 /* Chaosnet */ #define ARPHRD_IEEE802 6 /* IEEE 802.2 Ethernet/TR/TB */ #define ARPHRD_ARCNET 7 /* ARCnet */ #define ARPHRD_APPLETLK 8 /* APPLEtalk */ #define ARPHRD_DLCI 15 /* Frame Relay DLCI */ #define ARPHRD_ATM 19 /* ATM */ #define ARPHRD_METRICOM 23 /* Metricom STRIP (new IANA id) */ #define ARPHRD_IEEE1394 24 /* IEEE 1394 IPv4 - RFC 2734 */ #define ARPHRD_EUI64 27 /* EUI-64 */ #define ARPHRD_INFINIBAND 32 /* InfiniBand */ /* Dummy types for non ARP hardware */ #define ARPHRD_SLIP 256 #define ARPHRD_CSLIP 257 #define ARPHRD_SLIP6 258 #define ARPHRD_CSLIP6 259 #define ARPHRD_RSRVD 260 /* Notional KISS type */ #define ARPHRD_ADAPT 264 #define ARPHRD_ROSE 270 #define ARPHRD_X25 271 /* CCITT X.25 */ #define ARPHRD_HWX25 272 /* Boards with X.25 in firmware */ #define ARPHRD_CAN 280 /* Controller Area Network */ #define ARPHRD_PPP 512 #define ARPHRD_CISCO 513 /* Cisco HDLC */ #define ARPHRD_HDLC ARPHRD_CISCO #define ARPHRD_LAPB 516 /* LAPB */ #define ARPHRD_DDCMP 517 /* Digital's DDCMP protocol */ #define ARPHRD_RAWHDLC 518 /* Raw HDLC */ #define ARPHRD_RAWIP 519 /* Raw IP */ #define ARPHRD_TUNNEL 768 /* IPIP tunnel */ #define ARPHRD_TUNNEL6 769 /* IP6IP6 tunnel */ #define ARPHRD_FRAD 770 /* Frame Relay Access Device */ #define ARPHRD_SKIP 771 /* SKIP vif */ #define ARPHRD_LOOPBACK 772 /* Loopback device */ #define ARPHRD_LOCALTLK 773 /* Localtalk device */ #define ARPHRD_FDDI 774 /* Fiber Distributed Data Interface */ #define ARPHRD_BIF 775 /* AP1000 BIF */ #define ARPHRD_SIT 776 /* sit0 device - IPv6-in-IPv4 */ #define ARPHRD_IPDDP 777 /* IP over DDP tunneller */ #define ARPHRD_IPGRE 778 /* GRE over IP */ #define ARPHRD_PIMREG 779 /* PIMSM register interface */ #define ARPHRD_HIPPI 780 /* High Performance Parallel Interface */ #define ARPHRD_ASH 781 /* Nexus 64Mbps Ash */ #define ARPHRD_ECONET 782 /* Acorn Econet */ #define ARPHRD_IRDA 783 /* Linux-IrDA */ /* ARP works differently on different FC media .. so */ #define ARPHRD_FCPP 784 /* Point to point fibrechannel */ #define ARPHRD_FCAL 785 /* Fibrechannel arbitrated loop */ #define ARPHRD_FCPL 786 /* Fibrechannel public loop */ #define ARPHRD_FCFABRIC 787 /* Fibrechannel fabric */ /* 787->799 reserved for fibrechannel media types */ #define ARPHRD_IEEE802_TR 800 /* Magic type ident for TR */ #define ARPHRD_IEEE80211 801 /* IEEE 802.11 */ #define ARPHRD_IEEE80211_PRISM 802 /* IEEE 802.11 + Prism2 header */ #define ARPHRD_IEEE80211_RADIOTAP 803 /* IEEE 802.11 + radiotap header */ #define ARPHRD_IEEE802154 804 #define ARPHRD_IEEE802154_MONITOR 805 /* IEEE 802.15.4 network monitor */ #define ARPHRD_PHONET 820 /* PhoNet media type */ #define ARPHRD_PHONET_PIPE 821 /* PhoNet pipe header */ #define ARPHRD_CAIF 822 /* CAIF media type */ #define ARPHRD_IP6GRE 823 /* GRE over IPv6 */ #define ARPHRD_NETLINK 824 /* Netlink header */ #define ARPHRD_6LOWPAN 825 /* IPv6 over LoWPAN */ #define ARPHRD_VSOCKMON 826 /* Vsock monitor header */ #define ARPHRD_VOID 0xFFFF /* Void type, nothing is known */ #define ARPHRD_NONE 0xFFFE /* zero header length */ /* ARP protocol opcodes. */ #define ARPOP_REQUEST 1 /* ARP request */ #define ARPOP_REPLY 2 /* ARP reply */ #define ARPOP_RREQUEST 3 /* RARP request */ #define ARPOP_RREPLY 4 /* RARP reply */ #define ARPOP_InREQUEST 8 /* InARP request */ #define ARPOP_InREPLY 9 /* InARP reply */ #define ARPOP_NAK 10 /* (ATM)ARP NAK */ /* ARP ioctl request. */ struct arpreq { struct sockaddr arp_pa; /* protocol address */ struct sockaddr arp_ha; /* hardware address */ int arp_flags; /* flags */ struct sockaddr arp_netmask; /* netmask (only for proxy arps) */ char arp_dev[16]; }; struct arpreq_old { struct sockaddr arp_pa; /* protocol address */ struct sockaddr arp_ha; /* hardware address */ int arp_flags; /* flags */ struct sockaddr arp_netmask; /* netmask (only for proxy arps) */ }; /* ARP Flag values. */ #define ATF_COM 0x02 /* completed entry (ha valid) */ #define ATF_PERM 0x04 /* permanent entry */ #define ATF_PUBL 0x08 /* publish entry */ #define ATF_USETRAILERS 0x10 /* has requested trailers */ #define ATF_NETMASK 0x20 /* want to use a netmask (only for proxy entries) */ #define ATF_DONTPUB 0x40 /* don't answer this addresses */ /* * This structure defines an ethernet arp header. */ struct arphdr { __be16 ar_hrd; /* format of hardware address */ __be16 ar_pro; /* format of protocol address */ unsigned char ar_hln; /* length of hardware address */ unsigned char ar_pln; /* length of protocol address */ __be16 ar_op; /* ARP opcode (command) */ #if 0 /* * Ethernet looks like this : This bit is variable sized however... */ unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */ unsigned char ar_sip[4]; /* sender IP address */ unsigned char ar_tha[ETH_ALEN]; /* target hardware address */ unsigned char ar_tip[4]; /* target IP address */ #endif }; #endif /* _LINUX_IF_ARP_H */ linux/if_cablemodem.h000064400000001732151027430560010630 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _LINUX_CABLEMODEM_H_ #define _LINUX_CABLEMODEM_H_ /* * Author: Franco Venturi * Copyright 1998 Franco Venturi * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software * Foundation; either version 2 of the License, or (at * your option) any later version. */ /* some useful defines for sb1000.c e cmconfig.c - fv */ #define SIOCGCMSTATS (SIOCDEVPRIVATE+0) /* get cable modem stats */ #define SIOCGCMFIRMWARE (SIOCDEVPRIVATE+1) /* get cm firmware version */ #define SIOCGCMFREQUENCY (SIOCDEVPRIVATE+2) /* get cable modem frequency */ #define SIOCSCMFREQUENCY (SIOCDEVPRIVATE+3) /* set cable modem frequency */ #define SIOCGCMPIDS (SIOCDEVPRIVATE+4) /* get cable modem PIDs */ #define SIOCSCMPIDS (SIOCDEVPRIVATE+5) /* set cable modem PIDs */ #endif linux/virtio_types.h000064400000004151151027430560010620 0ustar00#ifndef _LINUX_VIRTIO_TYPES_H #define _LINUX_VIRTIO_TYPES_H /* Type definitions for virtio implementations. * * This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Copyright (C) 2014 Red Hat, Inc. * Author: Michael S. Tsirkin */ #include /* * __virtio{16,32,64} have the following meaning: * - __u{16,32,64} for virtio devices in legacy mode, accessed in native endian * - __le{16,32,64} for standard-compliant virtio devices */ typedef __u16 __bitwise __virtio16; typedef __u32 __bitwise __virtio32; typedef __u64 __bitwise __virtio64; #endif /* _LINUX_VIRTIO_TYPES_H */ linux/shm.h000064400000007311151027430560006650 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SHM_H_ #define _LINUX_SHM_H_ #include #include #include #include /* * SHMMNI, SHMMAX and SHMALL are default upper limits which can be * modified by sysctl. The SHMMAX and SHMALL values have been chosen to * be as large possible without facilitating scenarios where userspace * causes overflows when adjusting the limits via operations of the form * "retrieve current limit; add X; update limit". It is therefore not * advised to make SHMMAX and SHMALL any larger. These limits are * suitable for both 32 and 64-bit systems. */ #define SHMMIN 1 /* min shared seg size (bytes) */ #define SHMMNI 4096 /* max num of segs system wide */ #define SHMMAX (ULONG_MAX - (1UL << 24)) /* max shared seg size (bytes) */ #define SHMALL (ULONG_MAX - (1UL << 24)) /* max shm system wide (pages) */ #define SHMSEG SHMMNI /* max shared segs per process */ /* Obsolete, used only for backwards compatibility and libc5 compiles */ struct shmid_ds { struct ipc_perm shm_perm; /* operation perms */ int shm_segsz; /* size of segment (bytes) */ __kernel_time_t shm_atime; /* last attach time */ __kernel_time_t shm_dtime; /* last detach time */ __kernel_time_t shm_ctime; /* last change time */ __kernel_ipc_pid_t shm_cpid; /* pid of creator */ __kernel_ipc_pid_t shm_lpid; /* pid of last operator */ unsigned short shm_nattch; /* no. of current attaches */ unsigned short shm_unused; /* compatibility */ void *shm_unused2; /* ditto - used by DIPC */ void *shm_unused3; /* unused */ }; /* Include the definition of shmid64_ds and shminfo64 */ #include /* * shmget() shmflg values. */ /* The bottom nine bits are the same as open(2) mode flags */ #define SHM_R 0400 /* or S_IRUGO from */ #define SHM_W 0200 /* or S_IWUGO from */ /* Bits 9 & 10 are IPC_CREAT and IPC_EXCL */ #define SHM_HUGETLB 04000 /* segment will use huge TLB pages */ #define SHM_NORESERVE 010000 /* don't check for reservations */ /* * Huge page size encoding when SHM_HUGETLB is specified, and a huge page * size other than the default is desired. See hugetlb_encode.h */ #define SHM_HUGE_SHIFT HUGETLB_FLAG_ENCODE_SHIFT #define SHM_HUGE_MASK HUGETLB_FLAG_ENCODE_MASK #define SHM_HUGE_64KB HUGETLB_FLAG_ENCODE_64KB #define SHM_HUGE_512KB HUGETLB_FLAG_ENCODE_512KB #define SHM_HUGE_1MB HUGETLB_FLAG_ENCODE_1MB #define SHM_HUGE_2MB HUGETLB_FLAG_ENCODE_2MB #define SHM_HUGE_8MB HUGETLB_FLAG_ENCODE_8MB #define SHM_HUGE_16MB HUGETLB_FLAG_ENCODE_16MB #define SHM_HUGE_32MB HUGETLB_FLAG_ENCODE_32MB #define SHM_HUGE_256MB HUGETLB_FLAG_ENCODE_256MB #define SHM_HUGE_512MB HUGETLB_FLAG_ENCODE_512MB #define SHM_HUGE_1GB HUGETLB_FLAG_ENCODE_1GB #define SHM_HUGE_2GB HUGETLB_FLAG_ENCODE_2GB #define SHM_HUGE_16GB HUGETLB_FLAG_ENCODE_16GB /* * shmat() shmflg values */ #define SHM_RDONLY 010000 /* read-only access */ #define SHM_RND 020000 /* round attach address to SHMLBA boundary */ #define SHM_REMAP 040000 /* take-over region on attach */ #define SHM_EXEC 0100000 /* execution access */ /* super user shmctl commands */ #define SHM_LOCK 11 #define SHM_UNLOCK 12 /* ipcs ctl commands */ #define SHM_STAT 13 #define SHM_INFO 14 #define SHM_STAT_ANY 15 /* Obsolete, used only for backwards compatibility */ struct shminfo { int shmmax; int shmmin; int shmmni; int shmseg; int shmall; }; struct shm_info { int used_ids; __kernel_ulong_t shm_tot; /* total allocated shm */ __kernel_ulong_t shm_rss; /* total resident shm */ __kernel_ulong_t shm_swp; /* total swapped shm */ __kernel_ulong_t swap_attempts; __kernel_ulong_t swap_successes; }; #endif /* _LINUX_SHM_H_ */ linux/atmdev.h000064400000016775151027430560007357 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmdev.h - ATM device driver declarations and various related items */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #ifndef LINUX_ATMDEV_H #define LINUX_ATMDEV_H #include #include #include #define ESI_LEN 6 #define ATM_OC3_PCR (155520000/270*260/8/53) /* OC3 link rate: 155520000 bps SONET overhead: /270*260 (9 section, 1 path) bits per cell: /8/53 max cell rate: 353207.547 cells/sec */ #define ATM_25_PCR ((25600000/8-8000)/54) /* 25 Mbps ATM cell rate (59111) */ #define ATM_OC12_PCR (622080000/1080*1040/8/53) /* OC12 link rate: 622080000 bps SONET overhead: /1080*1040 bits per cell: /8/53 max cell rate: 1412830.188 cells/sec */ #define ATM_DS3_PCR (8000*12) /* DS3: 12 cells in a 125 usec time slot */ #define __AAL_STAT_ITEMS \ __HANDLE_ITEM(tx); /* TX okay */ \ __HANDLE_ITEM(tx_err); /* TX errors */ \ __HANDLE_ITEM(rx); /* RX okay */ \ __HANDLE_ITEM(rx_err); /* RX errors */ \ __HANDLE_ITEM(rx_drop); /* RX out of memory */ struct atm_aal_stats { #define __HANDLE_ITEM(i) int i __AAL_STAT_ITEMS #undef __HANDLE_ITEM }; struct atm_dev_stats { struct atm_aal_stats aal0; struct atm_aal_stats aal34; struct atm_aal_stats aal5; } __ATM_API_ALIGN; #define ATM_GETLINKRATE _IOW('a',ATMIOC_ITF+1,struct atmif_sioc) /* get link rate */ #define ATM_GETNAMES _IOW('a',ATMIOC_ITF+3,struct atm_iobuf) /* get interface names (numbers) */ #define ATM_GETTYPE _IOW('a',ATMIOC_ITF+4,struct atmif_sioc) /* get interface type name */ #define ATM_GETESI _IOW('a',ATMIOC_ITF+5,struct atmif_sioc) /* get interface ESI */ #define ATM_GETADDR _IOW('a',ATMIOC_ITF+6,struct atmif_sioc) /* get itf's local ATM addr. list */ #define ATM_RSTADDR _IOW('a',ATMIOC_ITF+7,struct atmif_sioc) /* reset itf's ATM address list */ #define ATM_ADDADDR _IOW('a',ATMIOC_ITF+8,struct atmif_sioc) /* add a local ATM address */ #define ATM_DELADDR _IOW('a',ATMIOC_ITF+9,struct atmif_sioc) /* remove a local ATM address */ #define ATM_GETCIRANGE _IOW('a',ATMIOC_ITF+10,struct atmif_sioc) /* get connection identifier range */ #define ATM_SETCIRANGE _IOW('a',ATMIOC_ITF+11,struct atmif_sioc) /* set connection identifier range */ #define ATM_SETESI _IOW('a',ATMIOC_ITF+12,struct atmif_sioc) /* set interface ESI */ #define ATM_SETESIF _IOW('a',ATMIOC_ITF+13,struct atmif_sioc) /* force interface ESI */ #define ATM_ADDLECSADDR _IOW('a', ATMIOC_ITF+14, struct atmif_sioc) /* register a LECS address */ #define ATM_DELLECSADDR _IOW('a', ATMIOC_ITF+15, struct atmif_sioc) /* unregister a LECS address */ #define ATM_GETLECSADDR _IOW('a', ATMIOC_ITF+16, struct atmif_sioc) /* retrieve LECS address(es) */ #define ATM_GETSTAT _IOW('a',ATMIOC_SARCOM+0,struct atmif_sioc) /* get AAL layer statistics */ #define ATM_GETSTATZ _IOW('a',ATMIOC_SARCOM+1,struct atmif_sioc) /* get AAL layer statistics and zero */ #define ATM_GETLOOP _IOW('a',ATMIOC_SARCOM+2,struct atmif_sioc) /* get loopback mode */ #define ATM_SETLOOP _IOW('a',ATMIOC_SARCOM+3,struct atmif_sioc) /* set loopback mode */ #define ATM_QUERYLOOP _IOW('a',ATMIOC_SARCOM+4,struct atmif_sioc) /* query supported loopback modes */ #define ATM_SETSC _IOW('a',ATMIOC_SPECIAL+1,int) /* enable or disable single-copy */ #define ATM_SETBACKEND _IOW('a',ATMIOC_SPECIAL+2,atm_backend_t) /* set backend handler */ #define ATM_NEWBACKENDIF _IOW('a',ATMIOC_SPECIAL+3,atm_backend_t) /* use backend to make new if */ #define ATM_ADDPARTY _IOW('a', ATMIOC_SPECIAL+4,struct atm_iobuf) /* add party to p2mp call */ #ifdef CONFIG_COMPAT /* It actually takes struct sockaddr_atmsvc, not struct atm_iobuf */ #define COMPAT_ATM_ADDPARTY _IOW('a', ATMIOC_SPECIAL+4,struct compat_atm_iobuf) #endif #define ATM_DROPPARTY _IOW('a', ATMIOC_SPECIAL+5,int) /* drop party from p2mp call */ /* * These are backend handkers that can be set via the ATM_SETBACKEND call * above. In the future we may support dynamic loading of these - for now, * they're just being used to share the ATMIOC_BACKEND ioctls */ #define ATM_BACKEND_RAW 0 #define ATM_BACKEND_PPP 1 /* PPPoATM - RFC2364 */ #define ATM_BACKEND_BR2684 2 /* Bridged RFC1483/2684 */ /* for ATM_GETTYPE */ #define ATM_ITFTYP_LEN 8 /* maximum length of interface type name */ /* * Loopback modes for ATM_{PHY,SAR}_{GET,SET}LOOP */ /* Point of loopback CPU-->SAR-->PHY-->line--> ... */ #define __ATM_LM_NONE 0 /* no loop back ^ ^ ^ ^ */ #define __ATM_LM_AAL 1 /* loop back PDUs --' | | | */ #define __ATM_LM_ATM 2 /* loop back ATM cells ---' | | */ /* RESERVED 4 loop back on PHY side ---' */ #define __ATM_LM_PHY 8 /* loop back bits (digital) ----' | */ #define __ATM_LM_ANALOG 16 /* loop back the analog signal --------' */ /* Direction of loopback */ #define __ATM_LM_MKLOC(n) ((n)) /* Local (i.e. loop TX to RX) */ #define __ATM_LM_MKRMT(n) ((n) << 8) /* Remote (i.e. loop RX to TX) */ #define __ATM_LM_XTLOC(n) ((n) & 0xff) #define __ATM_LM_XTRMT(n) (((n) >> 8) & 0xff) #define ATM_LM_NONE 0 /* no loopback */ #define ATM_LM_LOC_AAL __ATM_LM_MKLOC(__ATM_LM_AAL) #define ATM_LM_LOC_ATM __ATM_LM_MKLOC(__ATM_LM_ATM) #define ATM_LM_LOC_PHY __ATM_LM_MKLOC(__ATM_LM_PHY) #define ATM_LM_LOC_ANALOG __ATM_LM_MKLOC(__ATM_LM_ANALOG) #define ATM_LM_RMT_AAL __ATM_LM_MKRMT(__ATM_LM_AAL) #define ATM_LM_RMT_ATM __ATM_LM_MKRMT(__ATM_LM_ATM) #define ATM_LM_RMT_PHY __ATM_LM_MKRMT(__ATM_LM_PHY) #define ATM_LM_RMT_ANALOG __ATM_LM_MKRMT(__ATM_LM_ANALOG) /* * Note: ATM_LM_LOC_* and ATM_LM_RMT_* can be combined, provided that * __ATM_LM_XTLOC(x) <= __ATM_LM_XTRMT(x) */ struct atm_iobuf { int length; void *buffer; }; /* for ATM_GETCIRANGE / ATM_SETCIRANGE */ #define ATM_CI_MAX -1 /* use maximum range of VPI/VCI */ struct atm_cirange { signed char vpi_bits; /* 1..8, ATM_CI_MAX (-1) for maximum */ signed char vci_bits; /* 1..16, ATM_CI_MAX (-1) for maximum */ }; /* for ATM_SETSC; actually taken from the ATM_VF number space */ #define ATM_SC_RX 1024 /* enable RX single-copy */ #define ATM_SC_TX 2048 /* enable TX single-copy */ #define ATM_BACKLOG_DEFAULT 32 /* if we get more, we're likely to time out anyway */ /* MF: change_qos (Modify) flags */ #define ATM_MF_IMMED 1 /* Block until change is effective */ #define ATM_MF_INC_RSV 2 /* Change reservation on increase */ #define ATM_MF_INC_SHP 4 /* Change shaping on increase */ #define ATM_MF_DEC_RSV 8 /* Change reservation on decrease */ #define ATM_MF_DEC_SHP 16 /* Change shaping on decrease */ #define ATM_MF_BWD 32 /* Set the backward direction parameters */ #define ATM_MF_SET (ATM_MF_INC_RSV | ATM_MF_INC_SHP | ATM_MF_DEC_RSV | \ ATM_MF_DEC_SHP | ATM_MF_BWD) /* * ATM_VS_* are used to express VC state in a human-friendly way. */ #define ATM_VS_IDLE 0 /* VC is not used */ #define ATM_VS_CONNECTED 1 /* VC is connected */ #define ATM_VS_CLOSING 2 /* VC is closing */ #define ATM_VS_LISTEN 3 /* VC is listening for incoming setups */ #define ATM_VS_INUSE 4 /* VC is in use (registered with atmsigd) */ #define ATM_VS_BOUND 5 /* VC is bound */ #define ATM_VS2TXT_MAP \ "IDLE", "CONNECTED", "CLOSING", "LISTEN", "INUSE", "BOUND" #define ATM_VF2TXT_MAP \ "ADDR", "READY", "PARTIAL", "REGIS", \ "RELEASED", "HASQOS", "LISTEN", "META", \ "256", "512", "1024", "2048", \ "SESSION", "HASSAP", "BOUND", "CLOSE" #endif /* LINUX_ATMDEV_H */ linux/v4l2-mediabus.h000064400000011755151027430560010446 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Media Bus API header * * Copyright (C) 2009, Guennadi Liakhovetski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __LINUX_V4L2_MEDIABUS_H #define __LINUX_V4L2_MEDIABUS_H #include #include #include /** * struct v4l2_mbus_framefmt - frame format on the media bus * @width: image width * @height: image height * @code: data format code (from enum v4l2_mbus_pixelcode) * @field: used interlacing type (from enum v4l2_field) * @colorspace: colorspace of the data (from enum v4l2_colorspace) * @ycbcr_enc: YCbCr encoding of the data (from enum v4l2_ycbcr_encoding) * @quantization: quantization of the data (from enum v4l2_quantization) * @xfer_func: transfer function of the data (from enum v4l2_xfer_func) */ struct v4l2_mbus_framefmt { __u32 width; __u32 height; __u32 code; __u32 field; __u32 colorspace; __u16 ycbcr_enc; __u16 quantization; __u16 xfer_func; __u16 reserved[11]; }; /* * enum v4l2_mbus_pixelcode and its definitions are now deprecated, and * MEDIA_BUS_FMT_ definitions (defined in media-bus-format.h) should be * used instead. * * New defines should only be added to media-bus-format.h. The * v4l2_mbus_pixelcode enum is frozen. */ #define V4L2_MBUS_FROM_MEDIA_BUS_FMT(name) \ V4L2_MBUS_FMT_ ## name = MEDIA_BUS_FMT_ ## name enum v4l2_mbus_pixelcode { V4L2_MBUS_FROM_MEDIA_BUS_FMT(FIXED), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB444_2X8_PADHI_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB444_2X8_PADHI_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB555_2X8_PADHI_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB555_2X8_PADHI_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(BGR565_2X8_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(BGR565_2X8_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB565_2X8_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB565_2X8_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB666_1X18), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB888_1X24), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB888_2X12_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(RGB888_2X12_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(ARGB8888_1X32), V4L2_MBUS_FROM_MEDIA_BUS_FMT(Y8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UV8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY8_1_5X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY8_1_5X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV8_1_5X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU8_1_5X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY8_2X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY8_2X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV8_2X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU8_2X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(Y10_1X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY10_2X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY10_2X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV10_2X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU10_2X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(Y12_1X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY8_1X16), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY8_1X16), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV8_1X16), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU8_1X16), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YDYUYDYV8_1X16), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY10_1X20), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY10_1X20), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV10_1X20), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU10_1X20), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUV10_1X30), V4L2_MBUS_FROM_MEDIA_BUS_FMT(AYUV8_1X32), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY12_2X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY12_2X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV12_2X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU12_2X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(UYVY12_1X24), V4L2_MBUS_FROM_MEDIA_BUS_FMT(VYUY12_1X24), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YUYV12_1X24), V4L2_MBUS_FROM_MEDIA_BUS_FMT(YVYU12_1X24), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGBRG8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGRBG8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SRGGB8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_ALAW8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGBRG10_ALAW8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGRBG10_ALAW8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SRGGB10_ALAW8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_DPCM8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGBRG10_DPCM8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGRBG10_DPCM8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SRGGB10_DPCM8_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_2X8_PADHI_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_2X8_PADHI_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_2X8_PADLO_BE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_2X8_PADLO_LE), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR10_1X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGBRG10_1X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGRBG10_1X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SRGGB10_1X10), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SBGGR12_1X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGBRG12_1X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SGRBG12_1X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(SRGGB12_1X12), V4L2_MBUS_FROM_MEDIA_BUS_FMT(JPEG_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(S5C_UYVY_JPEG_1X8), V4L2_MBUS_FROM_MEDIA_BUS_FMT(AHSV8888_1X32), }; #endif linux/b1lli.h000064400000003265151027430560007070 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: b1lli.h,v 1.8.8.3 2001/09/23 22:25:05 kai Exp $ * * ISDN lowlevel-module for AVM B1-card. * * Copyright 1996 by Carsten Paeth (calle@calle.in-berlin.de) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef _B1LLI_H_ #define _B1LLI_H_ /* * struct for loading t4 file */ typedef struct avmb1_t4file { int len; unsigned char *data; } avmb1_t4file; typedef struct avmb1_loaddef { int contr; avmb1_t4file t4file; } avmb1_loaddef; typedef struct avmb1_loadandconfigdef { int contr; avmb1_t4file t4file; avmb1_t4file t4config; } avmb1_loadandconfigdef; typedef struct avmb1_resetdef { int contr; } avmb1_resetdef; typedef struct avmb1_getdef { int contr; int cardtype; int cardstate; } avmb1_getdef; /* * struct for adding new cards */ typedef struct avmb1_carddef { int port; int irq; } avmb1_carddef; #define AVM_CARDTYPE_B1 0 #define AVM_CARDTYPE_T1 1 #define AVM_CARDTYPE_M1 2 #define AVM_CARDTYPE_M2 3 typedef struct avmb1_extcarddef { int port; int irq; int cardtype; int cardnr; /* for HEMA/T1 */ } avmb1_extcarddef; #define AVMB1_LOAD 0 /* load image to card */ #define AVMB1_ADDCARD 1 /* add a new card - OBSOLETE */ #define AVMB1_RESETCARD 2 /* reset a card */ #define AVMB1_LOAD_AND_CONFIG 3 /* load image and config to card */ #define AVMB1_ADDCARD_WITH_TYPE 4 /* add a new card, with cardtype */ #define AVMB1_GET_CARDINFO 5 /* get cardtype */ #define AVMB1_REMOVECARD 6 /* remove a card - OBSOLETE */ #define AVMB1_REGISTERCARD_IS_OBSOLETE #endif /* _B1LLI_H_ */ linux/bt-bmc.h000064400000001074151027430560007225 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 2015-2016, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_BT_BMC_H #define _LINUX_BT_BMC_H #include #define __BT_BMC_IOCTL_MAGIC 0xb1 #define BT_BMC_IOCTL_SMS_ATN _IO(__BT_BMC_IOCTL_MAGIC, 0x00) #endif /* _LINUX_BT_BMC_H */ linux/seg6.h000064400000002222151027430560006721 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * SR-IPv6 implementation * * Author: * David Lebrun * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_SEG6_H #define _LINUX_SEG6_H #include #include /* For struct in6_addr. */ /* * SRH */ struct ipv6_sr_hdr { __u8 nexthdr; __u8 hdrlen; __u8 type; __u8 segments_left; __u8 first_segment; /* Represents the last_entry field of SRH */ __u8 flags; __u16 tag; struct in6_addr segments[0]; }; #define SR6_FLAG1_PROTECTED (1 << 6) #define SR6_FLAG1_OAM (1 << 5) #define SR6_FLAG1_ALERT (1 << 4) #define SR6_FLAG1_HMAC (1 << 3) #define SR6_TLV_INGRESS 1 #define SR6_TLV_EGRESS 2 #define SR6_TLV_OPAQUE 3 #define SR6_TLV_PADDING 4 #define SR6_TLV_HMAC 5 #define sr_has_hmac(srh) ((srh)->flags & SR6_FLAG1_HMAC) struct sr6_tlv { __u8 type; __u8 len; __u8 data[0]; }; #endif linux/llc.h000064400000006134151027430560006635 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * IEEE 802.2 User Interface SAPs for Linux, data structures and indicators. * * Copyright (c) 2001 by Jay Schulist * * This program can be redistributed or modified under the terms of the * GNU General Public License as published by the Free Software Foundation. * This program is distributed without any warranty or implied warranty * of merchantability or fitness for a particular purpose. * * See the GNU General Public License for more details. */ #ifndef __LINUX_LLC_H #define __LINUX_LLC_H #include #include /* For IFHWADDRLEN. */ #define __LLC_SOCK_SIZE__ 16 /* sizeof(sockaddr_llc), word align. */ struct sockaddr_llc { __kernel_sa_family_t sllc_family; /* AF_LLC */ __kernel_sa_family_t sllc_arphrd; /* ARPHRD_ETHER */ unsigned char sllc_test; unsigned char sllc_xid; unsigned char sllc_ua; /* UA data, only for SOCK_STREAM. */ unsigned char sllc_sap; unsigned char sllc_mac[IFHWADDRLEN]; unsigned char __pad[__LLC_SOCK_SIZE__ - sizeof(__kernel_sa_family_t) * 2 - sizeof(unsigned char) * 4 - IFHWADDRLEN]; }; /* sockopt definitions. */ enum llc_sockopts { LLC_OPT_UNKNOWN = 0, LLC_OPT_RETRY, /* max retrans attempts. */ LLC_OPT_SIZE, /* max PDU size (octets). */ LLC_OPT_ACK_TMR_EXP, /* ack expire time (secs). */ LLC_OPT_P_TMR_EXP, /* pf cycle expire time (secs). */ LLC_OPT_REJ_TMR_EXP, /* rej sent expire time (secs). */ LLC_OPT_BUSY_TMR_EXP, /* busy state expire time (secs). */ LLC_OPT_TX_WIN, /* tx window size. */ LLC_OPT_RX_WIN, /* rx window size. */ LLC_OPT_PKTINFO, /* ancillary packet information. */ LLC_OPT_MAX }; #define LLC_OPT_MAX_RETRY 100 #define LLC_OPT_MAX_SIZE 4196 #define LLC_OPT_MAX_WIN 127 #define LLC_OPT_MAX_ACK_TMR_EXP 60 #define LLC_OPT_MAX_P_TMR_EXP 60 #define LLC_OPT_MAX_REJ_TMR_EXP 60 #define LLC_OPT_MAX_BUSY_TMR_EXP 60 /* LLC SAP types. */ #define LLC_SAP_NULL 0x00 /* NULL SAP. */ #define LLC_SAP_LLC 0x02 /* LLC Sublayer Management. */ #define LLC_SAP_SNA 0x04 /* SNA Path Control. */ #define LLC_SAP_PNM 0x0E /* Proway Network Management. */ #define LLC_SAP_IP 0x06 /* TCP/IP. */ #define LLC_SAP_BSPAN 0x42 /* Bridge Spanning Tree Proto */ #define LLC_SAP_MMS 0x4E /* Manufacturing Message Srv. */ #define LLC_SAP_8208 0x7E /* ISO 8208 */ #define LLC_SAP_3COM 0x80 /* 3COM. */ #define LLC_SAP_PRO 0x8E /* Proway Active Station List */ #define LLC_SAP_SNAP 0xAA /* SNAP. */ #define LLC_SAP_BANYAN 0xBC /* Banyan. */ #define LLC_SAP_IPX 0xE0 /* IPX/SPX. */ #define LLC_SAP_NETBEUI 0xF0 /* NetBEUI. */ #define LLC_SAP_LANMGR 0xF4 /* LanManager. */ #define LLC_SAP_IMPL 0xF8 /* IMPL */ #define LLC_SAP_DISC 0xFC /* Discovery */ #define LLC_SAP_OSI 0xFE /* OSI Network Layers. */ #define LLC_SAP_LAR 0xDC /* LAN Address Resolution */ #define LLC_SAP_RM 0xD4 /* Resource Management */ #define LLC_SAP_GLOBAL 0xFF /* Global SAP. */ struct llc_pktinfo { int lpi_ifindex; unsigned char lpi_sap; unsigned char lpi_mac[IFHWADDRLEN]; }; #endif /* __LINUX_LLC_H */ linux/fb.h000064400000040135151027430560006451 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FB_H #define _LINUX_FB_H #include #include /* Definitions of frame buffers */ #define FB_MAX 32 /* sufficient for now */ /* ioctls 0x46 is 'F' */ #define FBIOGET_VSCREENINFO 0x4600 #define FBIOPUT_VSCREENINFO 0x4601 #define FBIOGET_FSCREENINFO 0x4602 #define FBIOGETCMAP 0x4604 #define FBIOPUTCMAP 0x4605 #define FBIOPAN_DISPLAY 0x4606 #define FBIO_CURSOR _IOWR('F', 0x08, struct fb_cursor) /* 0x4607-0x460B are defined below */ /* #define FBIOGET_MONITORSPEC 0x460C */ /* #define FBIOPUT_MONITORSPEC 0x460D */ /* #define FBIOSWITCH_MONIBIT 0x460E */ #define FBIOGET_CON2FBMAP 0x460F #define FBIOPUT_CON2FBMAP 0x4610 #define FBIOBLANK 0x4611 /* arg: 0 or vesa level + 1 */ #define FBIOGET_VBLANK _IOR('F', 0x12, struct fb_vblank) #define FBIO_ALLOC 0x4613 #define FBIO_FREE 0x4614 #define FBIOGET_GLYPH 0x4615 #define FBIOGET_HWCINFO 0x4616 #define FBIOPUT_MODEINFO 0x4617 #define FBIOGET_DISPINFO 0x4618 #define FBIO_WAITFORVSYNC _IOW('F', 0x20, __u32) #define FB_TYPE_PACKED_PIXELS 0 /* Packed Pixels */ #define FB_TYPE_PLANES 1 /* Non interleaved planes */ #define FB_TYPE_INTERLEAVED_PLANES 2 /* Interleaved planes */ #define FB_TYPE_TEXT 3 /* Text/attributes */ #define FB_TYPE_VGA_PLANES 4 /* EGA/VGA planes */ #define FB_TYPE_FOURCC 5 /* Type identified by a V4L2 FOURCC */ #define FB_AUX_TEXT_MDA 0 /* Monochrome text */ #define FB_AUX_TEXT_CGA 1 /* CGA/EGA/VGA Color text */ #define FB_AUX_TEXT_S3_MMIO 2 /* S3 MMIO fasttext */ #define FB_AUX_TEXT_MGA_STEP16 3 /* MGA Millenium I: text, attr, 14 reserved bytes */ #define FB_AUX_TEXT_MGA_STEP8 4 /* other MGAs: text, attr, 6 reserved bytes */ #define FB_AUX_TEXT_SVGA_GROUP 8 /* 8-15: SVGA tileblit compatible modes */ #define FB_AUX_TEXT_SVGA_MASK 7 /* lower three bits says step */ #define FB_AUX_TEXT_SVGA_STEP2 8 /* SVGA text mode: text, attr */ #define FB_AUX_TEXT_SVGA_STEP4 9 /* SVGA text mode: text, attr, 2 reserved bytes */ #define FB_AUX_TEXT_SVGA_STEP8 10 /* SVGA text mode: text, attr, 6 reserved bytes */ #define FB_AUX_TEXT_SVGA_STEP16 11 /* SVGA text mode: text, attr, 14 reserved bytes */ #define FB_AUX_TEXT_SVGA_LAST 15 /* reserved up to 15 */ #define FB_AUX_VGA_PLANES_VGA4 0 /* 16 color planes (EGA/VGA) */ #define FB_AUX_VGA_PLANES_CFB4 1 /* CFB4 in planes (VGA) */ #define FB_AUX_VGA_PLANES_CFB8 2 /* CFB8 in planes (VGA) */ #define FB_VISUAL_MONO01 0 /* Monochr. 1=Black 0=White */ #define FB_VISUAL_MONO10 1 /* Monochr. 1=White 0=Black */ #define FB_VISUAL_TRUECOLOR 2 /* True color */ #define FB_VISUAL_PSEUDOCOLOR 3 /* Pseudo color (like atari) */ #define FB_VISUAL_DIRECTCOLOR 4 /* Direct color */ #define FB_VISUAL_STATIC_PSEUDOCOLOR 5 /* Pseudo color readonly */ #define FB_VISUAL_FOURCC 6 /* Visual identified by a V4L2 FOURCC */ #define FB_ACCEL_NONE 0 /* no hardware accelerator */ #define FB_ACCEL_ATARIBLITT 1 /* Atari Blitter */ #define FB_ACCEL_AMIGABLITT 2 /* Amiga Blitter */ #define FB_ACCEL_S3_TRIO64 3 /* Cybervision64 (S3 Trio64) */ #define FB_ACCEL_NCR_77C32BLT 4 /* RetinaZ3 (NCR 77C32BLT) */ #define FB_ACCEL_S3_VIRGE 5 /* Cybervision64/3D (S3 ViRGE) */ #define FB_ACCEL_ATI_MACH64GX 6 /* ATI Mach 64GX family */ #define FB_ACCEL_DEC_TGA 7 /* DEC 21030 TGA */ #define FB_ACCEL_ATI_MACH64CT 8 /* ATI Mach 64CT family */ #define FB_ACCEL_ATI_MACH64VT 9 /* ATI Mach 64CT family VT class */ #define FB_ACCEL_ATI_MACH64GT 10 /* ATI Mach 64CT family GT class */ #define FB_ACCEL_SUN_CREATOR 11 /* Sun Creator/Creator3D */ #define FB_ACCEL_SUN_CGSIX 12 /* Sun cg6 */ #define FB_ACCEL_SUN_LEO 13 /* Sun leo/zx */ #define FB_ACCEL_IMS_TWINTURBO 14 /* IMS Twin Turbo */ #define FB_ACCEL_3DLABS_PERMEDIA2 15 /* 3Dlabs Permedia 2 */ #define FB_ACCEL_MATROX_MGA2064W 16 /* Matrox MGA2064W (Millenium) */ #define FB_ACCEL_MATROX_MGA1064SG 17 /* Matrox MGA1064SG (Mystique) */ #define FB_ACCEL_MATROX_MGA2164W 18 /* Matrox MGA2164W (Millenium II) */ #define FB_ACCEL_MATROX_MGA2164W_AGP 19 /* Matrox MGA2164W (Millenium II) */ #define FB_ACCEL_MATROX_MGAG100 20 /* Matrox G100 (Productiva G100) */ #define FB_ACCEL_MATROX_MGAG200 21 /* Matrox G200 (Myst, Mill, ...) */ #define FB_ACCEL_SUN_CG14 22 /* Sun cgfourteen */ #define FB_ACCEL_SUN_BWTWO 23 /* Sun bwtwo */ #define FB_ACCEL_SUN_CGTHREE 24 /* Sun cgthree */ #define FB_ACCEL_SUN_TCX 25 /* Sun tcx */ #define FB_ACCEL_MATROX_MGAG400 26 /* Matrox G400 */ #define FB_ACCEL_NV3 27 /* nVidia RIVA 128 */ #define FB_ACCEL_NV4 28 /* nVidia RIVA TNT */ #define FB_ACCEL_NV5 29 /* nVidia RIVA TNT2 */ #define FB_ACCEL_CT_6555x 30 /* C&T 6555x */ #define FB_ACCEL_3DFX_BANSHEE 31 /* 3Dfx Banshee */ #define FB_ACCEL_ATI_RAGE128 32 /* ATI Rage128 family */ #define FB_ACCEL_IGS_CYBER2000 33 /* CyberPro 2000 */ #define FB_ACCEL_IGS_CYBER2010 34 /* CyberPro 2010 */ #define FB_ACCEL_IGS_CYBER5000 35 /* CyberPro 5000 */ #define FB_ACCEL_SIS_GLAMOUR 36 /* SiS 300/630/540 */ #define FB_ACCEL_3DLABS_PERMEDIA3 37 /* 3Dlabs Permedia 3 */ #define FB_ACCEL_ATI_RADEON 38 /* ATI Radeon family */ #define FB_ACCEL_I810 39 /* Intel 810/815 */ #define FB_ACCEL_SIS_GLAMOUR_2 40 /* SiS 315, 650, 740 */ #define FB_ACCEL_SIS_XABRE 41 /* SiS 330 ("Xabre") */ #define FB_ACCEL_I830 42 /* Intel 830M/845G/85x/865G */ #define FB_ACCEL_NV_10 43 /* nVidia Arch 10 */ #define FB_ACCEL_NV_20 44 /* nVidia Arch 20 */ #define FB_ACCEL_NV_30 45 /* nVidia Arch 30 */ #define FB_ACCEL_NV_40 46 /* nVidia Arch 40 */ #define FB_ACCEL_XGI_VOLARI_V 47 /* XGI Volari V3XT, V5, V8 */ #define FB_ACCEL_XGI_VOLARI_Z 48 /* XGI Volari Z7 */ #define FB_ACCEL_OMAP1610 49 /* TI OMAP16xx */ #define FB_ACCEL_TRIDENT_TGUI 50 /* Trident TGUI */ #define FB_ACCEL_TRIDENT_3DIMAGE 51 /* Trident 3DImage */ #define FB_ACCEL_TRIDENT_BLADE3D 52 /* Trident Blade3D */ #define FB_ACCEL_TRIDENT_BLADEXP 53 /* Trident BladeXP */ #define FB_ACCEL_CIRRUS_ALPINE 53 /* Cirrus Logic 543x/544x/5480 */ #define FB_ACCEL_NEOMAGIC_NM2070 90 /* NeoMagic NM2070 */ #define FB_ACCEL_NEOMAGIC_NM2090 91 /* NeoMagic NM2090 */ #define FB_ACCEL_NEOMAGIC_NM2093 92 /* NeoMagic NM2093 */ #define FB_ACCEL_NEOMAGIC_NM2097 93 /* NeoMagic NM2097 */ #define FB_ACCEL_NEOMAGIC_NM2160 94 /* NeoMagic NM2160 */ #define FB_ACCEL_NEOMAGIC_NM2200 95 /* NeoMagic NM2200 */ #define FB_ACCEL_NEOMAGIC_NM2230 96 /* NeoMagic NM2230 */ #define FB_ACCEL_NEOMAGIC_NM2360 97 /* NeoMagic NM2360 */ #define FB_ACCEL_NEOMAGIC_NM2380 98 /* NeoMagic NM2380 */ #define FB_ACCEL_PXA3XX 99 /* PXA3xx */ #define FB_ACCEL_SAVAGE4 0x80 /* S3 Savage4 */ #define FB_ACCEL_SAVAGE3D 0x81 /* S3 Savage3D */ #define FB_ACCEL_SAVAGE3D_MV 0x82 /* S3 Savage3D-MV */ #define FB_ACCEL_SAVAGE2000 0x83 /* S3 Savage2000 */ #define FB_ACCEL_SAVAGE_MX_MV 0x84 /* S3 Savage/MX-MV */ #define FB_ACCEL_SAVAGE_MX 0x85 /* S3 Savage/MX */ #define FB_ACCEL_SAVAGE_IX_MV 0x86 /* S3 Savage/IX-MV */ #define FB_ACCEL_SAVAGE_IX 0x87 /* S3 Savage/IX */ #define FB_ACCEL_PROSAVAGE_PM 0x88 /* S3 ProSavage PM133 */ #define FB_ACCEL_PROSAVAGE_KM 0x89 /* S3 ProSavage KM133 */ #define FB_ACCEL_S3TWISTER_P 0x8a /* S3 Twister */ #define FB_ACCEL_S3TWISTER_K 0x8b /* S3 TwisterK */ #define FB_ACCEL_SUPERSAVAGE 0x8c /* S3 Supersavage */ #define FB_ACCEL_PROSAVAGE_DDR 0x8d /* S3 ProSavage DDR */ #define FB_ACCEL_PROSAVAGE_DDRK 0x8e /* S3 ProSavage DDR-K */ #define FB_ACCEL_PUV3_UNIGFX 0xa0 /* PKUnity-v3 Unigfx */ #define FB_CAP_FOURCC 1 /* Device supports FOURCC-based formats */ struct fb_fix_screeninfo { char id[16]; /* identification string eg "TT Builtin" */ unsigned long smem_start; /* Start of frame buffer mem */ /* (physical address) */ __u32 smem_len; /* Length of frame buffer mem */ __u32 type; /* see FB_TYPE_* */ __u32 type_aux; /* Interleave for interleaved Planes */ __u32 visual; /* see FB_VISUAL_* */ __u16 xpanstep; /* zero if no hardware panning */ __u16 ypanstep; /* zero if no hardware panning */ __u16 ywrapstep; /* zero if no hardware ywrap */ __u32 line_length; /* length of a line in bytes */ unsigned long mmio_start; /* Start of Memory Mapped I/O */ /* (physical address) */ __u32 mmio_len; /* Length of Memory Mapped I/O */ __u32 accel; /* Indicate to driver which */ /* specific chip/card we have */ __u16 capabilities; /* see FB_CAP_* */ __u16 reserved[2]; /* Reserved for future compatibility */ }; /* Interpretation of offset for color fields: All offsets are from the right, * inside a "pixel" value, which is exactly 'bits_per_pixel' wide (means: you * can use the offset as right argument to <<). A pixel afterwards is a bit * stream and is written to video memory as that unmodified. * * For pseudocolor: offset and length should be the same for all color * components. Offset specifies the position of the least significant bit * of the pallette index in a pixel value. Length indicates the number * of available palette entries (i.e. # of entries = 1 << length). */ struct fb_bitfield { __u32 offset; /* beginning of bitfield */ __u32 length; /* length of bitfield */ __u32 msb_right; /* != 0 : Most significant bit is */ /* right */ }; #define FB_NONSTD_HAM 1 /* Hold-And-Modify (HAM) */ #define FB_NONSTD_REV_PIX_IN_B 2 /* order of pixels in each byte is reversed */ #define FB_ACTIVATE_NOW 0 /* set values immediately (or vbl)*/ #define FB_ACTIVATE_NXTOPEN 1 /* activate on next open */ #define FB_ACTIVATE_TEST 2 /* don't set, round up impossible */ #define FB_ACTIVATE_MASK 15 /* values */ #define FB_ACTIVATE_VBL 16 /* activate values on next vbl */ #define FB_CHANGE_CMAP_VBL 32 /* change colormap on vbl */ #define FB_ACTIVATE_ALL 64 /* change all VCs on this fb */ #define FB_ACTIVATE_FORCE 128 /* force apply even when no change*/ #define FB_ACTIVATE_INV_MODE 256 /* invalidate videomode */ #define FB_ACTIVATE_KD_TEXT 512 /* for KDSET vt ioctl */ #define FB_ACCELF_TEXT 1 /* (OBSOLETE) see fb_info.flags and vc_mode */ #define FB_SYNC_HOR_HIGH_ACT 1 /* horizontal sync high active */ #define FB_SYNC_VERT_HIGH_ACT 2 /* vertical sync high active */ #define FB_SYNC_EXT 4 /* external sync */ #define FB_SYNC_COMP_HIGH_ACT 8 /* composite sync high active */ #define FB_SYNC_BROADCAST 16 /* broadcast video timings */ /* vtotal = 144d/288n/576i => PAL */ /* vtotal = 121d/242n/484i => NTSC */ #define FB_SYNC_ON_GREEN 32 /* sync on green */ #define FB_VMODE_NONINTERLACED 0 /* non interlaced */ #define FB_VMODE_INTERLACED 1 /* interlaced */ #define FB_VMODE_DOUBLE 2 /* double scan */ #define FB_VMODE_ODD_FLD_FIRST 4 /* interlaced: top line first */ #define FB_VMODE_MASK 255 #define FB_VMODE_YWRAP 256 /* ywrap instead of panning */ #define FB_VMODE_SMOOTH_XPAN 512 /* smooth xpan possible (internally used) */ #define FB_VMODE_CONUPDATE 512 /* don't update x/yoffset */ /* * Display rotation support */ #define FB_ROTATE_UR 0 #define FB_ROTATE_CW 1 #define FB_ROTATE_UD 2 #define FB_ROTATE_CCW 3 #define PICOS2KHZ(a) (1000000000UL/(a)) #define KHZ2PICOS(a) (1000000000UL/(a)) struct fb_var_screeninfo { __u32 xres; /* visible resolution */ __u32 yres; __u32 xres_virtual; /* virtual resolution */ __u32 yres_virtual; __u32 xoffset; /* offset from virtual to visible */ __u32 yoffset; /* resolution */ __u32 bits_per_pixel; /* guess what */ __u32 grayscale; /* 0 = color, 1 = grayscale, */ /* >1 = FOURCC */ struct fb_bitfield red; /* bitfield in fb mem if true color, */ struct fb_bitfield green; /* else only length is significant */ struct fb_bitfield blue; struct fb_bitfield transp; /* transparency */ __u32 nonstd; /* != 0 Non standard pixel format */ __u32 activate; /* see FB_ACTIVATE_* */ __u32 height; /* height of picture in mm */ __u32 width; /* width of picture in mm */ __u32 accel_flags; /* (OBSOLETE) see fb_info.flags */ /* Timing: All values in pixclocks, except pixclock (of course) */ __u32 pixclock; /* pixel clock in ps (pico seconds) */ __u32 left_margin; /* time from sync to picture */ __u32 right_margin; /* time from picture to sync */ __u32 upper_margin; /* time from sync to picture */ __u32 lower_margin; __u32 hsync_len; /* length of horizontal sync */ __u32 vsync_len; /* length of vertical sync */ __u32 sync; /* see FB_SYNC_* */ __u32 vmode; /* see FB_VMODE_* */ __u32 rotate; /* angle we rotate counter clockwise */ __u32 colorspace; /* colorspace for FOURCC-based modes */ __u32 reserved[4]; /* Reserved for future compatibility */ }; struct fb_cmap { __u32 start; /* First entry */ __u32 len; /* Number of entries */ __u16 *red; /* Red values */ __u16 *green; __u16 *blue; __u16 *transp; /* transparency, can be NULL */ }; struct fb_con2fbmap { __u32 console; __u32 framebuffer; }; /* VESA Blanking Levels */ #define VESA_NO_BLANKING 0 #define VESA_VSYNC_SUSPEND 1 #define VESA_HSYNC_SUSPEND 2 #define VESA_POWERDOWN 3 enum { /* screen: unblanked, hsync: on, vsync: on */ FB_BLANK_UNBLANK = VESA_NO_BLANKING, /* screen: blanked, hsync: on, vsync: on */ FB_BLANK_NORMAL = VESA_NO_BLANKING + 1, /* screen: blanked, hsync: on, vsync: off */ FB_BLANK_VSYNC_SUSPEND = VESA_VSYNC_SUSPEND + 1, /* screen: blanked, hsync: off, vsync: on */ FB_BLANK_HSYNC_SUSPEND = VESA_HSYNC_SUSPEND + 1, /* screen: blanked, hsync: off, vsync: off */ FB_BLANK_POWERDOWN = VESA_POWERDOWN + 1 }; #define FB_VBLANK_VBLANKING 0x001 /* currently in a vertical blank */ #define FB_VBLANK_HBLANKING 0x002 /* currently in a horizontal blank */ #define FB_VBLANK_HAVE_VBLANK 0x004 /* vertical blanks can be detected */ #define FB_VBLANK_HAVE_HBLANK 0x008 /* horizontal blanks can be detected */ #define FB_VBLANK_HAVE_COUNT 0x010 /* global retrace counter is available */ #define FB_VBLANK_HAVE_VCOUNT 0x020 /* the vcount field is valid */ #define FB_VBLANK_HAVE_HCOUNT 0x040 /* the hcount field is valid */ #define FB_VBLANK_VSYNCING 0x080 /* currently in a vsync */ #define FB_VBLANK_HAVE_VSYNC 0x100 /* verical syncs can be detected */ struct fb_vblank { __u32 flags; /* FB_VBLANK flags */ __u32 count; /* counter of retraces since boot */ __u32 vcount; /* current scanline position */ __u32 hcount; /* current scandot position */ __u32 reserved[4]; /* reserved for future compatibility */ }; /* Internal HW accel */ #define ROP_COPY 0 #define ROP_XOR 1 struct fb_copyarea { __u32 dx; __u32 dy; __u32 width; __u32 height; __u32 sx; __u32 sy; }; struct fb_fillrect { __u32 dx; /* screen-relative */ __u32 dy; __u32 width; __u32 height; __u32 color; __u32 rop; }; struct fb_image { __u32 dx; /* Where to place image */ __u32 dy; __u32 width; /* Size of image */ __u32 height; __u32 fg_color; /* Only used when a mono bitmap */ __u32 bg_color; __u8 depth; /* Depth of the image */ const char *data; /* Pointer to image data */ struct fb_cmap cmap; /* color map info */ }; /* * hardware cursor control */ #define FB_CUR_SETIMAGE 0x01 #define FB_CUR_SETPOS 0x02 #define FB_CUR_SETHOT 0x04 #define FB_CUR_SETCMAP 0x08 #define FB_CUR_SETSHAPE 0x10 #define FB_CUR_SETSIZE 0x20 #define FB_CUR_SETALL 0xFF struct fbcurpos { __u16 x, y; }; struct fb_cursor { __u16 set; /* what to set */ __u16 enable; /* cursor on/off */ __u16 rop; /* bitop operation */ const char *mask; /* cursor mask bits */ struct fbcurpos hot; /* cursor hot spot */ struct fb_image image; /* Cursor image */ }; /* Settings for the generic backlight code */ #define FB_BACKLIGHT_LEVELS 128 #define FB_BACKLIGHT_MAX 0xFF #endif /* _LINUX_FB_H */ linux/aio_abi.h000064400000006531151027430560007447 0ustar00/* include/linux/aio_abi.h * * Copyright 2000,2001,2002 Red Hat. * * Written by Benjamin LaHaise * * Distribute under the terms of the GPLv2 (see ../../COPYING) or under * the following terms. * * Permission to use, copy, modify, and distribute this software and its * documentation is hereby granted, provided that the above copyright * notice appears in all copies. This software is provided without any * warranty, express or implied. Red Hat makes no representations about * the suitability of this software for any purpose. * * IN NO EVENT SHALL RED HAT BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF RED HAT HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * RED HAT DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND * RED HAT HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. */ #ifndef __LINUX__AIO_ABI_H #define __LINUX__AIO_ABI_H #include #include #include typedef __kernel_ulong_t aio_context_t; enum { IOCB_CMD_PREAD = 0, IOCB_CMD_PWRITE = 1, IOCB_CMD_FSYNC = 2, IOCB_CMD_FDSYNC = 3, /* These two are experimental. * IOCB_CMD_PREADX = 4, * IOCB_CMD_POLL = 5, */ IOCB_CMD_NOOP = 6, IOCB_CMD_PREADV = 7, IOCB_CMD_PWRITEV = 8, }; /* * Valid flags for the "aio_flags" member of the "struct iocb". * * IOCB_FLAG_RESFD - Set if the "aio_resfd" member of the "struct iocb" * is valid. * IOCB_FLAG_IOPRIO - Set if the "aio_reqprio" member of the "struct iocb" * is valid. */ #define IOCB_FLAG_RESFD (1 << 0) #define IOCB_FLAG_IOPRIO (1 << 1) /* read() from /dev/aio returns these structures. */ struct io_event { __u64 data; /* the data field from the iocb */ __u64 obj; /* what iocb this event came from */ __s64 res; /* result code for this event */ __s64 res2; /* secondary result */ }; /* * we always use a 64bit off_t when communicating * with userland. its up to libraries to do the * proper padding and aio_error abstraction */ struct iocb { /* these are internal to the kernel/libc. */ __u64 aio_data; /* data to be returned in event's data */ #if defined(__BYTE_ORDER) ? __BYTE_ORDER == __LITTLE_ENDIAN : defined(__LITTLE_ENDIAN) __u32 aio_key; /* the kernel sets aio_key to the req # */ __kernel_rwf_t aio_rw_flags; /* RWF_* flags */ #elif defined(__BYTE_ORDER) ? __BYTE_ORDER == __BIG_ENDIAN : defined(__BIG_ENDIAN) __kernel_rwf_t aio_rw_flags; /* RWF_* flags */ __u32 aio_key; /* the kernel sets aio_key to the req # */ #else #error edit for your odd byteorder. #endif /* common fields */ __u16 aio_lio_opcode; /* see IOCB_CMD_ above */ __s16 aio_reqprio; __u32 aio_fildes; __u64 aio_buf; __u64 aio_nbytes; __s64 aio_offset; /* extra parameters */ __u64 aio_reserved2; /* TODO: use this for a (struct sigevent *) */ /* flags for the "struct iocb" */ __u32 aio_flags; /* * if the IOCB_FLAG_RESFD flag of "aio_flags" is set, this is an * eventfd to signal AIO readiness to */ __u32 aio_resfd; }; /* 64 bytes */ #undef IFBIG #undef IFLITTLE #endif /* __LINUX__AIO_ABI_H */ linux/pfrut.h000064400000017463151027430560007232 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Platform Firmware Runtime Update header * * Copyright(c) 2021 Intel Corporation. All rights reserved. */ #ifndef __PFRUT_H__ #define __PFRUT_H__ #include #include #define PFRUT_IOCTL_MAGIC 0xEE /** * PFRU_IOC_SET_REV - _IOW(PFRUT_IOCTL_MAGIC, 0x01, unsigned int) * * Return: * * 0 - success * * -EFAULT - fail to read the revision id * * -EINVAL - user provides an invalid revision id * * Set the Revision ID for Platform Firmware Runtime Update. */ #define PFRU_IOC_SET_REV _IOW(PFRUT_IOCTL_MAGIC, 0x01, unsigned int) /** * PFRU_IOC_STAGE - _IOW(PFRUT_IOCTL_MAGIC, 0x02, unsigned int) * * Return: * * 0 - success * * -EINVAL - stage phase returns invalid result * * Stage a capsule image from communication buffer and perform authentication. */ #define PFRU_IOC_STAGE _IOW(PFRUT_IOCTL_MAGIC, 0x02, unsigned int) /** * PFRU_IOC_ACTIVATE - _IOW(PFRUT_IOCTL_MAGIC, 0x03, unsigned int) * * Return: * * 0 - success * * -EINVAL - activate phase returns invalid result * * Activate a previously staged capsule image. */ #define PFRU_IOC_ACTIVATE _IOW(PFRUT_IOCTL_MAGIC, 0x03, unsigned int) /** * PFRU_IOC_STAGE_ACTIVATE - _IOW(PFRUT_IOCTL_MAGIC, 0x04, unsigned int) * * Return: * * 0 - success * * -EINVAL - stage/activate phase returns invalid result. * * Perform both stage and activation action. */ #define PFRU_IOC_STAGE_ACTIVATE _IOW(PFRUT_IOCTL_MAGIC, 0x04, unsigned int) /** * PFRU_IOC_QUERY_CAP - _IOR(PFRUT_IOCTL_MAGIC, 0x05, * struct pfru_update_cap_info) * * Return: * * 0 - success * * -EINVAL - query phase returns invalid result * * -EFAULT - the result fails to be copied to userspace * * Retrieve information on the Platform Firmware Runtime Update capability. * The information is a struct pfru_update_cap_info. */ #define PFRU_IOC_QUERY_CAP _IOR(PFRUT_IOCTL_MAGIC, 0x05, struct pfru_update_cap_info) /** * struct pfru_payload_hdr - Capsule file payload header. * * @sig: Signature of this capsule file. * @hdr_version: Revision of this header structure. * @hdr_size: Size of this header, including the OemHeader bytes. * @hw_ver: The supported firmware version. * @rt_ver: Version of the code injection image. * @platform_id: A platform specific GUID to specify the platform what * this capsule image support. */ struct pfru_payload_hdr { __u32 sig; __u32 hdr_version; __u32 hdr_size; __u32 hw_ver; __u32 rt_ver; __u8 platform_id[16]; }; enum pfru_dsm_status { DSM_SUCCEED = 0, DSM_FUNC_NOT_SUPPORT = 1, DSM_INVAL_INPUT = 2, DSM_HARDWARE_ERR = 3, DSM_RETRY_SUGGESTED = 4, DSM_UNKNOWN = 5, DSM_FUNC_SPEC_ERR = 6, }; /** * struct pfru_update_cap_info - Runtime update capability information. * * @status: Indicator of whether this query succeed. * @update_cap: Bitmap to indicate whether the feature is supported. * @code_type: A buffer containing an image type GUID. * @fw_version: Platform firmware version. * @code_rt_version: Code injection runtime version for anti-rollback. * @drv_type: A buffer containing an image type GUID. * @drv_rt_version: The version of the driver update runtime code. * @drv_svn: The secure version number(SVN) of the driver update runtime code. * @platform_id: A buffer containing a platform ID GUID. * @oem_id: A buffer containing an OEM ID GUID. * @oem_info_len: Length of the buffer containing the vendor specific information. */ struct pfru_update_cap_info { __u32 status; __u32 update_cap; __u8 code_type[16]; __u32 fw_version; __u32 code_rt_version; __u8 drv_type[16]; __u32 drv_rt_version; __u32 drv_svn; __u8 platform_id[16]; __u8 oem_id[16]; __u32 oem_info_len; }; /** * struct pfru_com_buf_info - Communication buffer information. * * @status: Indicator of whether this query succeed. * @ext_status: Implementation specific query result. * @addr_lo: Low 32bit physical address of the communication buffer to hold * a runtime update package. * @addr_hi: High 32bit physical address of the communication buffer to hold * a runtime update package. * @buf_size: Maximum size in bytes of the communication buffer. */ struct pfru_com_buf_info { __u32 status; __u32 ext_status; __u64 addr_lo; __u64 addr_hi; __u32 buf_size; }; /** * struct pfru_updated_result - Platform firmware runtime update result information. * @status: Indicator of whether this update succeed. * @ext_status: Implementation specific update result. * @low_auth_time: Low 32bit value of image authentication time in nanosecond. * @high_auth_time: High 32bit value of image authentication time in nanosecond. * @low_exec_time: Low 32bit value of image execution time in nanosecond. * @high_exec_time: High 32bit value of image execution time in nanosecond. */ struct pfru_updated_result { __u32 status; __u32 ext_status; __u64 low_auth_time; __u64 high_auth_time; __u64 low_exec_time; __u64 high_exec_time; }; /** * struct pfrt_log_data_info - Log Data from telemetry service. * @status: Indicator of whether this update succeed. * @ext_status: Implementation specific update result. * @chunk1_addr_lo: Low 32bit physical address of the telemetry data chunk1 * starting address. * @chunk1_addr_hi: High 32bit physical address of the telemetry data chunk1 * starting address. * @chunk2_addr_lo: Low 32bit physical address of the telemetry data chunk2 * starting address. * @chunk2_addr_hi: High 32bit physical address of the telemetry data chunk2 * starting address. * @max_data_size: Maximum supported size of data of all data chunks combined. * @chunk1_size: Data size in bytes of the telemetry data chunk1 buffer. * @chunk2_size: Data size in bytes of the telemetry data chunk2 buffer. * @rollover_cnt: Number of times telemetry data buffer is overwritten * since telemetry buffer reset. * @reset_cnt: Number of times telemetry services resets that results in * rollover count and data chunk buffers are reset. */ struct pfrt_log_data_info { __u32 status; __u32 ext_status; __u64 chunk1_addr_lo; __u64 chunk1_addr_hi; __u64 chunk2_addr_lo; __u64 chunk2_addr_hi; __u32 max_data_size; __u32 chunk1_size; __u32 chunk2_size; __u32 rollover_cnt; __u32 reset_cnt; }; /** * struct pfrt_log_info - Telemetry log information. * @log_level: The telemetry log level. * @log_type: The telemetry log type(history and execution). * @log_revid: The telemetry log revision id. */ struct pfrt_log_info { __u32 log_level; __u32 log_type; __u32 log_revid; }; /** * PFRT_LOG_IOC_SET_INFO - _IOW(PFRUT_IOCTL_MAGIC, 0x06, * struct pfrt_log_info) * * Return: * * 0 - success * * -EFAULT - fail to get the setting parameter * * -EINVAL - fail to set the log level * * Set the PFRT log level and log type. The input information is * a struct pfrt_log_info. */ #define PFRT_LOG_IOC_SET_INFO _IOW(PFRUT_IOCTL_MAGIC, 0x06, struct pfrt_log_info) /** * PFRT_LOG_IOC_GET_INFO - _IOR(PFRUT_IOCTL_MAGIC, 0x07, * struct pfrt_log_info) * * Return: * * 0 - success * * -EINVAL - fail to get the log level * * -EFAULT - fail to copy the result back to userspace * * Retrieve log level and log type of the telemetry. The information is * a struct pfrt_log_info. */ #define PFRT_LOG_IOC_GET_INFO _IOR(PFRUT_IOCTL_MAGIC, 0x07, struct pfrt_log_info) /** * PFRT_LOG_IOC_GET_DATA_INFO - _IOR(PFRUT_IOCTL_MAGIC, 0x08, * struct pfrt_log_data_info) * * Return: * * 0 - success * * -EINVAL - fail to get the log buffer information * * -EFAULT - fail to copy the log buffer information to userspace * * Retrieve data information about the telemetry. The information * is a struct pfrt_log_data_info. */ #define PFRT_LOG_IOC_GET_DATA_INFO _IOR(PFRUT_IOCTL_MAGIC, 0x08, struct pfrt_log_data_info) #endif /* __PFRUT_H__ */ linux/dma-buf.h000064400000012177151027430560007402 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Framework for buffer objects that can be shared across devices/subsystems. * * Copyright(C) 2015 Intel Ltd * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ #ifndef _DMA_BUF_UAPI_H_ #define _DMA_BUF_UAPI_H_ #include /* begin/end dma-buf functions used for userspace mmap. */ struct dma_buf_sync { __u64 flags; }; #define DMA_BUF_SYNC_READ (1 << 0) #define DMA_BUF_SYNC_WRITE (2 << 0) #define DMA_BUF_SYNC_RW (DMA_BUF_SYNC_READ | DMA_BUF_SYNC_WRITE) #define DMA_BUF_SYNC_START (0 << 2) #define DMA_BUF_SYNC_END (1 << 2) #define DMA_BUF_SYNC_VALID_FLAGS_MASK \ (DMA_BUF_SYNC_RW | DMA_BUF_SYNC_END) #define DMA_BUF_NAME_LEN 32 /** * struct dma_buf_export_sync_file - Get a sync_file from a dma-buf * * Userspace can perform a DMA_BUF_IOCTL_EXPORT_SYNC_FILE to retrieve the * current set of fences on a dma-buf file descriptor as a sync_file. CPU * waits via poll() or other driver-specific mechanisms typically wait on * whatever fences are on the dma-buf at the time the wait begins. This * is similar except that it takes a snapshot of the current fences on the * dma-buf for waiting later instead of waiting immediately. This is * useful for modern graphics APIs such as Vulkan which assume an explicit * synchronization model but still need to inter-operate with dma-buf. * * The intended usage pattern is the following: * * 1. Export a sync_file with flags corresponding to the expected GPU usage * via DMA_BUF_IOCTL_EXPORT_SYNC_FILE. * * 2. Submit rendering work which uses the dma-buf. The work should wait on * the exported sync file before rendering and produce another sync_file * when complete. * * 3. Import the rendering-complete sync_file into the dma-buf with flags * corresponding to the GPU usage via DMA_BUF_IOCTL_IMPORT_SYNC_FILE. * * Unlike doing implicit synchronization via a GPU kernel driver's exec ioctl, * the above is not a single atomic operation. If userspace wants to ensure * ordering via these fences, it is the respnosibility of userspace to use * locks or other mechanisms to ensure that no other context adds fences or * submits work between steps 1 and 3 above. */ struct dma_buf_export_sync_file { /** * @flags: Read/write flags * * Must be DMA_BUF_SYNC_READ, DMA_BUF_SYNC_WRITE, or both. * * If DMA_BUF_SYNC_READ is set and DMA_BUF_SYNC_WRITE is not set, * the returned sync file waits on any writers of the dma-buf to * complete. Waiting on the returned sync file is equivalent to * poll() with POLLIN. * * If DMA_BUF_SYNC_WRITE is set, the returned sync file waits on * any users of the dma-buf (read or write) to complete. Waiting * on the returned sync file is equivalent to poll() with POLLOUT. * If both DMA_BUF_SYNC_WRITE and DMA_BUF_SYNC_READ are set, this * is equivalent to just DMA_BUF_SYNC_WRITE. */ __u32 flags; /** @fd: Returned sync file descriptor */ __s32 fd; }; /** * struct dma_buf_import_sync_file - Insert a sync_file into a dma-buf * * Userspace can perform a DMA_BUF_IOCTL_IMPORT_SYNC_FILE to insert a * sync_file into a dma-buf for the purposes of implicit synchronization * with other dma-buf consumers. This allows clients using explicitly * synchronized APIs such as Vulkan to inter-op with dma-buf consumers * which expect implicit synchronization such as OpenGL or most media * drivers/video. */ struct dma_buf_import_sync_file { /** * @flags: Read/write flags * * Must be DMA_BUF_SYNC_READ, DMA_BUF_SYNC_WRITE, or both. * * If DMA_BUF_SYNC_READ is set and DMA_BUF_SYNC_WRITE is not set, * this inserts the sync_file as a read-only fence. Any subsequent * implicitly synchronized writes to this dma-buf will wait on this * fence but reads will not. * * If DMA_BUF_SYNC_WRITE is set, this inserts the sync_file as a * write fence. All subsequent implicitly synchronized access to * this dma-buf will wait on this fence. */ __u32 flags; /** @fd: Sync file descriptor */ __s32 fd; }; #define DMA_BUF_BASE 'b' #define DMA_BUF_IOCTL_SYNC _IOW(DMA_BUF_BASE, 0, struct dma_buf_sync) /* 32/64bitness of this uapi was botched in android, there's no difference * between them in actual uapi, they're just different numbers. */ #define DMA_BUF_SET_NAME _IOW(DMA_BUF_BASE, 1, const char *) #define DMA_BUF_SET_NAME_A _IOW(DMA_BUF_BASE, 1, __u32) #define DMA_BUF_SET_NAME_B _IOW(DMA_BUF_BASE, 1, __u64) #define DMA_BUF_IOCTL_EXPORT_SYNC_FILE _IOWR(DMA_BUF_BASE, 2, struct dma_buf_export_sync_file) #define DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW(DMA_BUF_BASE, 3, struct dma_buf_import_sync_file) #endif linux/pmu.h000064400000012307151027430560006663 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Definitions for talking to the PMU. The PMU is a microcontroller * which controls battery charging and system power on PowerBook 3400 * and 2400 models as well as the RTC and various other things. * * Copyright (C) 1998 Paul Mackerras. */ #ifndef _LINUX_PMU_H #define _LINUX_PMU_H #define PMU_DRIVER_VERSION 2 /* * PMU commands */ #define PMU_POWER_CTRL0 0x10 /* control power of some devices */ #define PMU_POWER_CTRL 0x11 /* control power of some devices */ #define PMU_ADB_CMD 0x20 /* send ADB packet */ #define PMU_ADB_POLL_OFF 0x21 /* disable ADB auto-poll */ #define PMU_WRITE_NVRAM 0x33 /* write non-volatile RAM */ #define PMU_READ_NVRAM 0x3b /* read non-volatile RAM */ #define PMU_SET_RTC 0x30 /* set real-time clock */ #define PMU_READ_RTC 0x38 /* read real-time clock */ #define PMU_SET_VOLBUTTON 0x40 /* set volume up/down position */ #define PMU_BACKLIGHT_BRIGHT 0x41 /* set backlight brightness */ #define PMU_GET_VOLBUTTON 0x48 /* get volume up/down position */ #define PMU_PCEJECT 0x4c /* eject PC-card from slot */ #define PMU_BATTERY_STATE 0x6b /* report battery state etc. */ #define PMU_SMART_BATTERY_STATE 0x6f /* report battery state (new way) */ #define PMU_SET_INTR_MASK 0x70 /* set PMU interrupt mask */ #define PMU_INT_ACK 0x78 /* read interrupt bits */ #define PMU_SHUTDOWN 0x7e /* turn power off */ #define PMU_CPU_SPEED 0x7d /* control CPU speed on some models */ #define PMU_SLEEP 0x7f /* put CPU to sleep */ #define PMU_POWER_EVENTS 0x8f /* Send power-event commands to PMU */ #define PMU_I2C_CMD 0x9a /* I2C operations */ #define PMU_RESET 0xd0 /* reset CPU */ #define PMU_GET_BRIGHTBUTTON 0xd9 /* report brightness up/down pos */ #define PMU_GET_COVER 0xdc /* report cover open/closed */ #define PMU_SYSTEM_READY 0xdf /* tell PMU we are awake */ #define PMU_GET_VERSION 0xea /* read the PMU version */ /* Bits to use with the PMU_POWER_CTRL0 command */ #define PMU_POW0_ON 0x80 /* OR this to power ON the device */ #define PMU_POW0_OFF 0x00 /* leave bit 7 to 0 to power it OFF */ #define PMU_POW0_HARD_DRIVE 0x04 /* Hard drive power (on wallstreet/lombard ?) */ /* Bits to use with the PMU_POWER_CTRL command */ #define PMU_POW_ON 0x80 /* OR this to power ON the device */ #define PMU_POW_OFF 0x00 /* leave bit 7 to 0 to power it OFF */ #define PMU_POW_BACKLIGHT 0x01 /* backlight power */ #define PMU_POW_CHARGER 0x02 /* battery charger power */ #define PMU_POW_IRLED 0x04 /* IR led power (on wallstreet) */ #define PMU_POW_MEDIABAY 0x08 /* media bay power (wallstreet/lombard ?) */ /* Bits in PMU interrupt and interrupt mask bytes */ #define PMU_INT_PCEJECT 0x04 /* PC-card eject buttons */ #define PMU_INT_SNDBRT 0x08 /* sound/brightness up/down buttons */ #define PMU_INT_ADB 0x10 /* ADB autopoll or reply data */ #define PMU_INT_BATTERY 0x20 /* Battery state change */ #define PMU_INT_ENVIRONMENT 0x40 /* Environment interrupts */ #define PMU_INT_TICK 0x80 /* 1-second tick interrupt */ /* Other bits in PMU interrupt valid when PMU_INT_ADB is set */ #define PMU_INT_ADB_AUTO 0x04 /* ADB autopoll, when PMU_INT_ADB */ #define PMU_INT_WAITING_CHARGER 0x01 /* ??? */ #define PMU_INT_AUTO_SRQ_POLL 0x02 /* ??? */ /* Bits in the environement message (either obtained via PMU_GET_COVER, * or via PMU_INT_ENVIRONMENT on core99 */ #define PMU_ENV_LID_CLOSED 0x01 /* The lid is closed */ /* I2C related definitions */ #define PMU_I2C_MODE_SIMPLE 0 #define PMU_I2C_MODE_STDSUB 1 #define PMU_I2C_MODE_COMBINED 2 #define PMU_I2C_BUS_STATUS 0 #define PMU_I2C_BUS_SYSCLK 1 #define PMU_I2C_BUS_POWER 2 #define PMU_I2C_STATUS_OK 0 #define PMU_I2C_STATUS_DATAREAD 1 #define PMU_I2C_STATUS_BUSY 0xfe /* Kind of PMU (model) */ enum { PMU_UNKNOWN, PMU_OHARE_BASED, /* 2400, 3400, 3500 (old G3 powerbook) */ PMU_HEATHROW_BASED, /* PowerBook G3 series */ PMU_PADDINGTON_BASED, /* 1999 PowerBook G3 */ PMU_KEYLARGO_BASED, /* Core99 motherboard (PMU99) */ PMU_68K_V1, /* 68K PMU, version 1 */ PMU_68K_V2, /* 68K PMU, version 2 */ }; /* PMU PMU_POWER_EVENTS commands */ enum { PMU_PWR_GET_POWERUP_EVENTS = 0x00, PMU_PWR_SET_POWERUP_EVENTS = 0x01, PMU_PWR_CLR_POWERUP_EVENTS = 0x02, PMU_PWR_GET_WAKEUP_EVENTS = 0x03, PMU_PWR_SET_WAKEUP_EVENTS = 0x04, PMU_PWR_CLR_WAKEUP_EVENTS = 0x05, }; /* Power events wakeup bits */ enum { PMU_PWR_WAKEUP_KEY = 0x01, /* Wake on key press */ PMU_PWR_WAKEUP_AC_INSERT = 0x02, /* Wake on AC adapter plug */ PMU_PWR_WAKEUP_AC_CHANGE = 0x04, PMU_PWR_WAKEUP_LID_OPEN = 0x08, PMU_PWR_WAKEUP_RING = 0x10, }; /* * Ioctl commands for the /dev/pmu device */ #include /* no param */ #define PMU_IOC_SLEEP _IO('B', 0) /* out param: u32* backlight value: 0 to 15 */ #define PMU_IOC_GET_BACKLIGHT _IOR('B', 1, size_t) /* in param: u32 backlight value: 0 to 15 */ #define PMU_IOC_SET_BACKLIGHT _IOW('B', 2, size_t) /* out param: u32* PMU model */ #define PMU_IOC_GET_MODEL _IOR('B', 3, size_t) /* out param: u32* has_adb: 0 or 1 */ #define PMU_IOC_HAS_ADB _IOR('B', 4, size_t) /* out param: u32* can_sleep: 0 or 1 */ #define PMU_IOC_CAN_SLEEP _IOR('B', 5, size_t) /* no param, but historically was _IOR('B', 6, 0), meaning 4 bytes */ #define PMU_IOC_GRAB_BACKLIGHT _IOR('B', 6, size_t) #endif /* _LINUX_PMU_H */ linux/virtio_input.h000064400000004712151027430560010616 0ustar00#ifndef _LINUX_VIRTIO_INPUT_H #define _LINUX_VIRTIO_INPUT_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL IBM OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include enum virtio_input_config_select { VIRTIO_INPUT_CFG_UNSET = 0x00, VIRTIO_INPUT_CFG_ID_NAME = 0x01, VIRTIO_INPUT_CFG_ID_SERIAL = 0x02, VIRTIO_INPUT_CFG_ID_DEVIDS = 0x03, VIRTIO_INPUT_CFG_PROP_BITS = 0x10, VIRTIO_INPUT_CFG_EV_BITS = 0x11, VIRTIO_INPUT_CFG_ABS_INFO = 0x12, }; struct virtio_input_absinfo { __u32 min; __u32 max; __u32 fuzz; __u32 flat; __u32 res; }; struct virtio_input_devids { __u16 bustype; __u16 vendor; __u16 product; __u16 version; }; struct virtio_input_config { __u8 select; __u8 subsel; __u8 size; __u8 reserved[5]; union { char string[128]; __u8 bitmap[128]; struct virtio_input_absinfo abs; struct virtio_input_devids ids; } u; }; struct virtio_input_event { __le16 type; __le16 code; __le32 value; }; #endif /* _LINUX_VIRTIO_INPUT_H */ linux/bcm933xx_hcs.h000064400000000643151027430560010277 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Broadcom Cable Modem firmware format */ #ifndef __BCM933XX_HCS_H #define __BCM933XX_HCS_H #include struct bcm_hcs { __u16 magic; __u16 control; __u16 rev_maj; __u16 rev_min; __u32 build_date; __u32 filelen; __u32 ldaddress; char filename[64]; __u16 hcs; __u16 her_znaet_chto; __u32 crc; }; #endif /* __BCM933XX_HCS */ linux/kfd_sysfs.h000064400000010376151027430560010061 0ustar00/* SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT */ /* * Copyright 2021 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KFD_SYSFS_H_INCLUDED #define KFD_SYSFS_H_INCLUDED /* Capability bits in node properties */ #define HSA_CAP_HOT_PLUGGABLE 0x00000001 #define HSA_CAP_ATS_PRESENT 0x00000002 #define HSA_CAP_SHARED_WITH_GRAPHICS 0x00000004 #define HSA_CAP_QUEUE_SIZE_POW2 0x00000008 #define HSA_CAP_QUEUE_SIZE_32BIT 0x00000010 #define HSA_CAP_QUEUE_IDLE_EVENT 0x00000020 #define HSA_CAP_VA_LIMIT 0x00000040 #define HSA_CAP_WATCH_POINTS_SUPPORTED 0x00000080 #define HSA_CAP_WATCH_POINTS_TOTALBITS_MASK 0x00000f00 #define HSA_CAP_WATCH_POINTS_TOTALBITS_SHIFT 8 #define HSA_CAP_DOORBELL_TYPE_TOTALBITS_MASK 0x00003000 #define HSA_CAP_DOORBELL_TYPE_TOTALBITS_SHIFT 12 #define HSA_CAP_DOORBELL_TYPE_PRE_1_0 0x0 #define HSA_CAP_DOORBELL_TYPE_1_0 0x1 #define HSA_CAP_DOORBELL_TYPE_2_0 0x2 #define HSA_CAP_AQL_QUEUE_DOUBLE_MAP 0x00004000 /* Old buggy user mode depends on this being 0 */ #define HSA_CAP_RESERVED_WAS_SRAM_EDCSUPPORTED 0x00080000 #define HSA_CAP_MEM_EDCSUPPORTED 0x00100000 #define HSA_CAP_RASEVENTNOTIFY 0x00200000 #define HSA_CAP_ASIC_REVISION_MASK 0x03c00000 #define HSA_CAP_ASIC_REVISION_SHIFT 22 #define HSA_CAP_SRAM_EDCSUPPORTED 0x04000000 #define HSA_CAP_SVMAPI_SUPPORTED 0x08000000 #define HSA_CAP_FLAGS_COHERENTHOSTACCESS 0x10000000 #define HSA_CAP_RESERVED 0xe00f8000 /* Heap types in memory properties */ #define HSA_MEM_HEAP_TYPE_SYSTEM 0 #define HSA_MEM_HEAP_TYPE_FB_PUBLIC 1 #define HSA_MEM_HEAP_TYPE_FB_PRIVATE 2 #define HSA_MEM_HEAP_TYPE_GPU_GDS 3 #define HSA_MEM_HEAP_TYPE_GPU_LDS 4 #define HSA_MEM_HEAP_TYPE_GPU_SCRATCH 5 /* Flag bits in memory properties */ #define HSA_MEM_FLAGS_HOT_PLUGGABLE 0x00000001 #define HSA_MEM_FLAGS_NON_VOLATILE 0x00000002 #define HSA_MEM_FLAGS_RESERVED 0xfffffffc /* Cache types in cache properties */ #define HSA_CACHE_TYPE_DATA 0x00000001 #define HSA_CACHE_TYPE_INSTRUCTION 0x00000002 #define HSA_CACHE_TYPE_CPU 0x00000004 #define HSA_CACHE_TYPE_HSACU 0x00000008 #define HSA_CACHE_TYPE_RESERVED 0xfffffff0 /* Link types in IO link properties (matches CRAT link types) */ #define HSA_IOLINK_TYPE_UNDEFINED 0 #define HSA_IOLINK_TYPE_HYPERTRANSPORT 1 #define HSA_IOLINK_TYPE_PCIEXPRESS 2 #define HSA_IOLINK_TYPE_AMBA 3 #define HSA_IOLINK_TYPE_MIPI 4 #define HSA_IOLINK_TYPE_QPI_1_1 5 #define HSA_IOLINK_TYPE_RESERVED1 6 #define HSA_IOLINK_TYPE_RESERVED2 7 #define HSA_IOLINK_TYPE_RAPID_IO 8 #define HSA_IOLINK_TYPE_INFINIBAND 9 #define HSA_IOLINK_TYPE_RESERVED3 10 #define HSA_IOLINK_TYPE_XGMI 11 #define HSA_IOLINK_TYPE_XGOP 12 #define HSA_IOLINK_TYPE_GZ 13 #define HSA_IOLINK_TYPE_ETHERNET_RDMA 14 #define HSA_IOLINK_TYPE_RDMA_OTHER 15 #define HSA_IOLINK_TYPE_OTHER 16 /* Flag bits in IO link properties (matches CRAT flags, excluding the * bi-directional flag, which is not offially part of the CRAT spec, and * only used internally in KFD) */ #define HSA_IOLINK_FLAGS_ENABLED (1 << 0) #define HSA_IOLINK_FLAGS_NON_COHERENT (1 << 1) #define HSA_IOLINK_FLAGS_NO_ATOMICS_32_BIT (1 << 2) #define HSA_IOLINK_FLAGS_NO_ATOMICS_64_BIT (1 << 3) #define HSA_IOLINK_FLAGS_NO_PEER_TO_PEER_DMA (1 << 4) #define HSA_IOLINK_FLAGS_RESERVED 0xffffffe0 #endif linux/byteorder/big_endian.h000064400000006726151027430560012150 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_BYTEORDER_BIG_ENDIAN_H #define _LINUX_BYTEORDER_BIG_ENDIAN_H #ifndef __BIG_ENDIAN #define __BIG_ENDIAN 4321 #endif #ifndef __BIG_ENDIAN_BITFIELD #define __BIG_ENDIAN_BITFIELD #endif #include #include #define __constant_htonl(x) ((__be32)(__u32)(x)) #define __constant_ntohl(x) ((__u32)(__be32)(x)) #define __constant_htons(x) ((__be16)(__u16)(x)) #define __constant_ntohs(x) ((__u16)(__be16)(x)) #define __constant_cpu_to_le64(x) ((__le64)___constant_swab64((x))) #define __constant_le64_to_cpu(x) ___constant_swab64((__u64)(__le64)(x)) #define __constant_cpu_to_le32(x) ((__le32)___constant_swab32((x))) #define __constant_le32_to_cpu(x) ___constant_swab32((__u32)(__le32)(x)) #define __constant_cpu_to_le16(x) ((__le16)___constant_swab16((x))) #define __constant_le16_to_cpu(x) ___constant_swab16((__u16)(__le16)(x)) #define __constant_cpu_to_be64(x) ((__be64)(__u64)(x)) #define __constant_be64_to_cpu(x) ((__u64)(__be64)(x)) #define __constant_cpu_to_be32(x) ((__be32)(__u32)(x)) #define __constant_be32_to_cpu(x) ((__u32)(__be32)(x)) #define __constant_cpu_to_be16(x) ((__be16)(__u16)(x)) #define __constant_be16_to_cpu(x) ((__u16)(__be16)(x)) #define __cpu_to_le64(x) ((__le64)__swab64((x))) #define __le64_to_cpu(x) __swab64((__u64)(__le64)(x)) #define __cpu_to_le32(x) ((__le32)__swab32((x))) #define __le32_to_cpu(x) __swab32((__u32)(__le32)(x)) #define __cpu_to_le16(x) ((__le16)__swab16((x))) #define __le16_to_cpu(x) __swab16((__u16)(__le16)(x)) #define __cpu_to_be64(x) ((__be64)(__u64)(x)) #define __be64_to_cpu(x) ((__u64)(__be64)(x)) #define __cpu_to_be32(x) ((__be32)(__u32)(x)) #define __be32_to_cpu(x) ((__u32)(__be32)(x)) #define __cpu_to_be16(x) ((__be16)(__u16)(x)) #define __be16_to_cpu(x) ((__u16)(__be16)(x)) static __always_inline __le64 __cpu_to_le64p(const __u64 *p) { return (__le64)__swab64p(p); } static __always_inline __u64 __le64_to_cpup(const __le64 *p) { return __swab64p((__u64 *)p); } static __always_inline __le32 __cpu_to_le32p(const __u32 *p) { return (__le32)__swab32p(p); } static __always_inline __u32 __le32_to_cpup(const __le32 *p) { return __swab32p((__u32 *)p); } static __always_inline __le16 __cpu_to_le16p(const __u16 *p) { return (__le16)__swab16p(p); } static __always_inline __u16 __le16_to_cpup(const __le16 *p) { return __swab16p((__u16 *)p); } static __always_inline __be64 __cpu_to_be64p(const __u64 *p) { return (__be64)*p; } static __always_inline __u64 __be64_to_cpup(const __be64 *p) { return (__u64)*p; } static __always_inline __be32 __cpu_to_be32p(const __u32 *p) { return (__be32)*p; } static __always_inline __u32 __be32_to_cpup(const __be32 *p) { return (__u32)*p; } static __always_inline __be16 __cpu_to_be16p(const __u16 *p) { return (__be16)*p; } static __always_inline __u16 __be16_to_cpup(const __be16 *p) { return (__u16)*p; } #define __cpu_to_le64s(x) __swab64s((x)) #define __le64_to_cpus(x) __swab64s((x)) #define __cpu_to_le32s(x) __swab32s((x)) #define __le32_to_cpus(x) __swab32s((x)) #define __cpu_to_le16s(x) __swab16s((x)) #define __le16_to_cpus(x) __swab16s((x)) #define __cpu_to_be64s(x) do { (void)(x); } while (0) #define __be64_to_cpus(x) do { (void)(x); } while (0) #define __cpu_to_be32s(x) do { (void)(x); } while (0) #define __be32_to_cpus(x) do { (void)(x); } while (0) #define __cpu_to_be16s(x) do { (void)(x); } while (0) #define __be16_to_cpus(x) do { (void)(x); } while (0) #endif /* _LINUX_BYTEORDER_BIG_ENDIAN_H */ linux/byteorder/little_endian.h000064400000007033151027430560012674 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_BYTEORDER_LITTLE_ENDIAN_H #define _LINUX_BYTEORDER_LITTLE_ENDIAN_H #ifndef __LITTLE_ENDIAN #define __LITTLE_ENDIAN 1234 #endif #ifndef __LITTLE_ENDIAN_BITFIELD #define __LITTLE_ENDIAN_BITFIELD #endif #include #include #define __constant_htonl(x) ((__be32)___constant_swab32((x))) #define __constant_ntohl(x) ___constant_swab32((__be32)(x)) #define __constant_htons(x) ((__be16)___constant_swab16((x))) #define __constant_ntohs(x) ___constant_swab16((__be16)(x)) #define __constant_cpu_to_le64(x) ((__le64)(__u64)(x)) #define __constant_le64_to_cpu(x) ((__u64)(__le64)(x)) #define __constant_cpu_to_le32(x) ((__le32)(__u32)(x)) #define __constant_le32_to_cpu(x) ((__u32)(__le32)(x)) #define __constant_cpu_to_le16(x) ((__le16)(__u16)(x)) #define __constant_le16_to_cpu(x) ((__u16)(__le16)(x)) #define __constant_cpu_to_be64(x) ((__be64)___constant_swab64((x))) #define __constant_be64_to_cpu(x) ___constant_swab64((__u64)(__be64)(x)) #define __constant_cpu_to_be32(x) ((__be32)___constant_swab32((x))) #define __constant_be32_to_cpu(x) ___constant_swab32((__u32)(__be32)(x)) #define __constant_cpu_to_be16(x) ((__be16)___constant_swab16((x))) #define __constant_be16_to_cpu(x) ___constant_swab16((__u16)(__be16)(x)) #define __cpu_to_le64(x) ((__le64)(__u64)(x)) #define __le64_to_cpu(x) ((__u64)(__le64)(x)) #define __cpu_to_le32(x) ((__le32)(__u32)(x)) #define __le32_to_cpu(x) ((__u32)(__le32)(x)) #define __cpu_to_le16(x) ((__le16)(__u16)(x)) #define __le16_to_cpu(x) ((__u16)(__le16)(x)) #define __cpu_to_be64(x) ((__be64)__swab64((x))) #define __be64_to_cpu(x) __swab64((__u64)(__be64)(x)) #define __cpu_to_be32(x) ((__be32)__swab32((x))) #define __be32_to_cpu(x) __swab32((__u32)(__be32)(x)) #define __cpu_to_be16(x) ((__be16)__swab16((x))) #define __be16_to_cpu(x) __swab16((__u16)(__be16)(x)) static __always_inline __le64 __cpu_to_le64p(const __u64 *p) { return (__le64)*p; } static __always_inline __u64 __le64_to_cpup(const __le64 *p) { return (__u64)*p; } static __always_inline __le32 __cpu_to_le32p(const __u32 *p) { return (__le32)*p; } static __always_inline __u32 __le32_to_cpup(const __le32 *p) { return (__u32)*p; } static __always_inline __le16 __cpu_to_le16p(const __u16 *p) { return (__le16)*p; } static __always_inline __u16 __le16_to_cpup(const __le16 *p) { return (__u16)*p; } static __always_inline __be64 __cpu_to_be64p(const __u64 *p) { return (__be64)__swab64p(p); } static __always_inline __u64 __be64_to_cpup(const __be64 *p) { return __swab64p((__u64 *)p); } static __always_inline __be32 __cpu_to_be32p(const __u32 *p) { return (__be32)__swab32p(p); } static __always_inline __u32 __be32_to_cpup(const __be32 *p) { return __swab32p((__u32 *)p); } static __always_inline __be16 __cpu_to_be16p(const __u16 *p) { return (__be16)__swab16p(p); } static __always_inline __u16 __be16_to_cpup(const __be16 *p) { return __swab16p((__u16 *)p); } #define __cpu_to_le64s(x) do { (void)(x); } while (0) #define __le64_to_cpus(x) do { (void)(x); } while (0) #define __cpu_to_le32s(x) do { (void)(x); } while (0) #define __le32_to_cpus(x) do { (void)(x); } while (0) #define __cpu_to_le16s(x) do { (void)(x); } while (0) #define __le16_to_cpus(x) do { (void)(x); } while (0) #define __cpu_to_be64s(x) __swab64s((x)) #define __be64_to_cpus(x) __swab64s((x)) #define __cpu_to_be32s(x) __swab32s((x)) #define __be32_to_cpus(x) __swab32s((x)) #define __cpu_to_be16s(x) __swab16s((x)) #define __be16_to_cpus(x) __swab16s((x)) #endif /* _LINUX_BYTEORDER_LITTLE_ENDIAN_H */ linux/mtio.h000064400000017757151027430560007050 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/mtio.h header file for Linux. Written by H. Bergman * * Modified for special ioctls provided by zftape in September 1997 * by C.-J. Heine. */ #ifndef _LINUX_MTIO_H #define _LINUX_MTIO_H #include #include /* * Structures and definitions for mag tape io control commands */ /* structure for MTIOCTOP - mag tape op command */ struct mtop { short mt_op; /* operations defined below */ int mt_count; /* how many of them */ }; /* Magnetic Tape operations [Not all operations supported by all drivers]: */ #define MTRESET 0 /* +reset drive in case of problems */ #define MTFSF 1 /* forward space over FileMark, * position at first record of next file */ #define MTBSF 2 /* backward space FileMark (position before FM) */ #define MTFSR 3 /* forward space record */ #define MTBSR 4 /* backward space record */ #define MTWEOF 5 /* write an end-of-file record (mark) */ #define MTREW 6 /* rewind */ #define MTOFFL 7 /* rewind and put the drive offline (eject?) */ #define MTNOP 8 /* no op, set status only (read with MTIOCGET) */ #define MTRETEN 9 /* retension tape */ #define MTBSFM 10 /* +backward space FileMark, position at FM */ #define MTFSFM 11 /* +forward space FileMark, position at FM */ #define MTEOM 12 /* goto end of recorded media (for appending files). * MTEOM positions after the last FM, ready for * appending another file. */ #define MTERASE 13 /* erase tape -- be careful! */ #define MTRAS1 14 /* run self test 1 (nondestructive) */ #define MTRAS2 15 /* run self test 2 (destructive) */ #define MTRAS3 16 /* reserved for self test 3 */ #define MTSETBLK 20 /* set block length (SCSI) */ #define MTSETDENSITY 21 /* set tape density (SCSI) */ #define MTSEEK 22 /* seek to block (Tandberg, etc.) */ #define MTTELL 23 /* tell block (Tandberg, etc.) */ #define MTSETDRVBUFFER 24 /* set the drive buffering according to SCSI-2 */ /* ordinary buffered operation with code 1 */ #define MTFSS 25 /* space forward over setmarks */ #define MTBSS 26 /* space backward over setmarks */ #define MTWSM 27 /* write setmarks */ #define MTLOCK 28 /* lock the drive door */ #define MTUNLOCK 29 /* unlock the drive door */ #define MTLOAD 30 /* execute the SCSI load command */ #define MTUNLOAD 31 /* execute the SCSI unload command */ #define MTCOMPRESSION 32/* control compression with SCSI mode page 15 */ #define MTSETPART 33 /* Change the active tape partition */ #define MTMKPART 34 /* Format the tape with one or two partitions */ #define MTWEOFI 35 /* write an end-of-file record (mark) in immediate mode */ /* structure for MTIOCGET - mag tape get status command */ struct mtget { long mt_type; /* type of magtape device */ long mt_resid; /* residual count: (not sure) * number of bytes ignored, or * number of files not skipped, or * number of records not skipped. */ /* the following registers are device dependent */ long mt_dsreg; /* status register */ long mt_gstat; /* generic (device independent) status */ long mt_erreg; /* error register */ /* The next two fields are not always used */ __kernel_daddr_t mt_fileno; /* number of current file on tape */ __kernel_daddr_t mt_blkno; /* current block number */ }; /* * Constants for mt_type. Not all of these are supported, * and these are not all of the ones that are supported. */ #define MT_ISUNKNOWN 0x01 #define MT_ISQIC02 0x02 /* Generic QIC-02 tape streamer */ #define MT_ISWT5150 0x03 /* Wangtek 5150EQ, QIC-150, QIC-02 */ #define MT_ISARCHIVE_5945L2 0x04 /* Archive 5945L-2, QIC-24, QIC-02? */ #define MT_ISCMSJ500 0x05 /* CMS Jumbo 500 (QIC-02?) */ #define MT_ISTDC3610 0x06 /* Tandberg 6310, QIC-24 */ #define MT_ISARCHIVE_VP60I 0x07 /* Archive VP60i, QIC-02 */ #define MT_ISARCHIVE_2150L 0x08 /* Archive Viper 2150L */ #define MT_ISARCHIVE_2060L 0x09 /* Archive Viper 2060L */ #define MT_ISARCHIVESC499 0x0A /* Archive SC-499 QIC-36 controller */ #define MT_ISQIC02_ALL_FEATURES 0x0F /* Generic QIC-02 with all features */ #define MT_ISWT5099EEN24 0x11 /* Wangtek 5099-een24, 60MB, QIC-24 */ #define MT_ISTEAC_MT2ST 0x12 /* Teac MT-2ST 155mb drive, Teac DC-1 card (Wangtek type) */ #define MT_ISEVEREX_FT40A 0x32 /* Everex FT40A (QIC-40) */ #define MT_ISDDS1 0x51 /* DDS device without partitions */ #define MT_ISDDS2 0x52 /* DDS device with partitions */ #define MT_ISONSTREAM_SC 0x61 /* OnStream SCSI tape drives (SC-x0) and SCSI emulated (DI, DP, USB) */ #define MT_ISSCSI1 0x71 /* Generic ANSI SCSI-1 tape unit */ #define MT_ISSCSI2 0x72 /* Generic ANSI SCSI-2 tape unit */ /* QIC-40/80/3010/3020 ftape supported drives. * 20bit vendor ID + 0x800000 (see ftape-vendors.h) */ #define MT_ISFTAPE_UNKNOWN 0x800000 /* obsolete */ #define MT_ISFTAPE_FLAG 0x800000 /* structure for MTIOCPOS - mag tape get position command */ struct mtpos { long mt_blkno; /* current block number */ }; /* mag tape io control commands */ #define MTIOCTOP _IOW('m', 1, struct mtop) /* do a mag tape op */ #define MTIOCGET _IOR('m', 2, struct mtget) /* get tape status */ #define MTIOCPOS _IOR('m', 3, struct mtpos) /* get tape position */ /* Generic Mag Tape (device independent) status macros for examining * mt_gstat -- HP-UX compatible. * There is room for more generic status bits here, but I don't * know which of them are reserved. At least three or so should * be added to make this really useful. */ #define GMT_EOF(x) ((x) & 0x80000000) #define GMT_BOT(x) ((x) & 0x40000000) #define GMT_EOT(x) ((x) & 0x20000000) #define GMT_SM(x) ((x) & 0x10000000) /* DDS setmark */ #define GMT_EOD(x) ((x) & 0x08000000) /* DDS EOD */ #define GMT_WR_PROT(x) ((x) & 0x04000000) /* #define GMT_ ? ((x) & 0x02000000) */ #define GMT_ONLINE(x) ((x) & 0x01000000) #define GMT_D_6250(x) ((x) & 0x00800000) #define GMT_D_1600(x) ((x) & 0x00400000) #define GMT_D_800(x) ((x) & 0x00200000) /* #define GMT_ ? ((x) & 0x00100000) */ /* #define GMT_ ? ((x) & 0x00080000) */ #define GMT_DR_OPEN(x) ((x) & 0x00040000) /* door open (no tape) */ /* #define GMT_ ? ((x) & 0x00020000) */ #define GMT_IM_REP_EN(x) ((x) & 0x00010000) /* immediate report mode */ #define GMT_CLN(x) ((x) & 0x00008000) /* cleaning requested */ /* 15 generic status bits unused */ /* SCSI-tape specific definitions */ /* Bitfield shifts in the status */ #define MT_ST_BLKSIZE_SHIFT 0 #define MT_ST_BLKSIZE_MASK 0xffffff #define MT_ST_DENSITY_SHIFT 24 #define MT_ST_DENSITY_MASK 0xff000000 #define MT_ST_SOFTERR_SHIFT 0 #define MT_ST_SOFTERR_MASK 0xffff /* Bitfields for the MTSETDRVBUFFER ioctl */ #define MT_ST_OPTIONS 0xf0000000 #define MT_ST_BOOLEANS 0x10000000 #define MT_ST_SETBOOLEANS 0x30000000 #define MT_ST_CLEARBOOLEANS 0x40000000 #define MT_ST_WRITE_THRESHOLD 0x20000000 #define MT_ST_DEF_BLKSIZE 0x50000000 #define MT_ST_DEF_OPTIONS 0x60000000 #define MT_ST_TIMEOUTS 0x70000000 #define MT_ST_SET_TIMEOUT (MT_ST_TIMEOUTS | 0x000000) #define MT_ST_SET_LONG_TIMEOUT (MT_ST_TIMEOUTS | 0x100000) #define MT_ST_SET_CLN 0x80000000 #define MT_ST_BUFFER_WRITES 0x1 #define MT_ST_ASYNC_WRITES 0x2 #define MT_ST_READ_AHEAD 0x4 #define MT_ST_DEBUGGING 0x8 #define MT_ST_TWO_FM 0x10 #define MT_ST_FAST_MTEOM 0x20 #define MT_ST_AUTO_LOCK 0x40 #define MT_ST_DEF_WRITES 0x80 #define MT_ST_CAN_BSR 0x100 #define MT_ST_NO_BLKLIMS 0x200 #define MT_ST_CAN_PARTITIONS 0x400 #define MT_ST_SCSI2LOGICAL 0x800 #define MT_ST_SYSV 0x1000 #define MT_ST_NOWAIT 0x2000 #define MT_ST_SILI 0x4000 #define MT_ST_NOWAIT_EOF 0x8000 /* The mode parameters to be controlled. Parameter chosen with bits 20-28 */ #define MT_ST_CLEAR_DEFAULT 0xfffff #define MT_ST_DEF_DENSITY (MT_ST_DEF_OPTIONS | 0x100000) #define MT_ST_DEF_COMPRESSION (MT_ST_DEF_OPTIONS | 0x200000) #define MT_ST_DEF_DRVBUFFER (MT_ST_DEF_OPTIONS | 0x300000) /* The offset for the arguments for the special HP changer load command. */ #define MT_ST_HPLOADER_OFFSET 10000 #endif /* _LINUX_MTIO_H */ linux/if_bridge.h000064400000046072151027430560010002 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Linux ethernet bridge * * Authors: * Lennert Buytenhek * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_BRIDGE_H #define _LINUX_IF_BRIDGE_H #include #include #include #define SYSFS_BRIDGE_ATTR "bridge" #define SYSFS_BRIDGE_FDB "brforward" #define SYSFS_BRIDGE_PORT_SUBDIR "brif" #define SYSFS_BRIDGE_PORT_ATTR "brport" #define SYSFS_BRIDGE_PORT_LINK "bridge" #define BRCTL_VERSION 1 #define BRCTL_GET_VERSION 0 #define BRCTL_GET_BRIDGES 1 #define BRCTL_ADD_BRIDGE 2 #define BRCTL_DEL_BRIDGE 3 #define BRCTL_ADD_IF 4 #define BRCTL_DEL_IF 5 #define BRCTL_GET_BRIDGE_INFO 6 #define BRCTL_GET_PORT_LIST 7 #define BRCTL_SET_BRIDGE_FORWARD_DELAY 8 #define BRCTL_SET_BRIDGE_HELLO_TIME 9 #define BRCTL_SET_BRIDGE_MAX_AGE 10 #define BRCTL_SET_AGEING_TIME 11 #define BRCTL_SET_GC_INTERVAL 12 #define BRCTL_GET_PORT_INFO 13 #define BRCTL_SET_BRIDGE_STP_STATE 14 #define BRCTL_SET_BRIDGE_PRIORITY 15 #define BRCTL_SET_PORT_PRIORITY 16 #define BRCTL_SET_PATH_COST 17 #define BRCTL_GET_FDB_ENTRIES 18 #define BR_STATE_DISABLED 0 #define BR_STATE_LISTENING 1 #define BR_STATE_LEARNING 2 #define BR_STATE_FORWARDING 3 #define BR_STATE_BLOCKING 4 struct __bridge_info { __u64 designated_root; __u64 bridge_id; __u32 root_path_cost; __u32 max_age; __u32 hello_time; __u32 forward_delay; __u32 bridge_max_age; __u32 bridge_hello_time; __u32 bridge_forward_delay; __u8 topology_change; __u8 topology_change_detected; __u8 root_port; __u8 stp_enabled; __u32 ageing_time; __u32 gc_interval; __u32 hello_timer_value; __u32 tcn_timer_value; __u32 topology_change_timer_value; __u32 gc_timer_value; }; struct __port_info { __u64 designated_root; __u64 designated_bridge; __u16 port_id; __u16 designated_port; __u32 path_cost; __u32 designated_cost; __u8 state; __u8 top_change_ack; __u8 config_pending; __u8 unused0; __u32 message_age_timer_value; __u32 forward_delay_timer_value; __u32 hold_timer_value; }; struct __fdb_entry { __u8 mac_addr[ETH_ALEN]; __u8 port_no; __u8 is_local; __u32 ageing_timer_value; __u8 port_hi; __u8 pad0; __u16 unused; }; /* Bridge Flags */ #define BRIDGE_FLAGS_MASTER 1 /* Bridge command to/from master */ #define BRIDGE_FLAGS_SELF 2 /* Bridge command to/from lowerdev */ #define BRIDGE_MODE_VEB 0 /* Default loopback mode */ #define BRIDGE_MODE_VEPA 1 /* 802.1Qbg defined VEPA mode */ #define BRIDGE_MODE_UNDEF 0xFFFF /* mode undefined */ /* Bridge management nested attributes * [IFLA_AF_SPEC] = { * [IFLA_BRIDGE_FLAGS] * [IFLA_BRIDGE_MODE] * [IFLA_BRIDGE_VLAN_INFO] * } */ enum { IFLA_BRIDGE_FLAGS, IFLA_BRIDGE_MODE, IFLA_BRIDGE_VLAN_INFO, IFLA_BRIDGE_VLAN_TUNNEL_INFO, IFLA_BRIDGE_MRP, IFLA_BRIDGE_CFM, IFLA_BRIDGE_MST, __IFLA_BRIDGE_MAX, }; #define IFLA_BRIDGE_MAX (__IFLA_BRIDGE_MAX - 1) #define BRIDGE_VLAN_INFO_MASTER (1<<0) /* Operate on Bridge device as well */ #define BRIDGE_VLAN_INFO_PVID (1<<1) /* VLAN is PVID, ingress untagged */ #define BRIDGE_VLAN_INFO_UNTAGGED (1<<2) /* VLAN egresses untagged */ #define BRIDGE_VLAN_INFO_RANGE_BEGIN (1<<3) /* VLAN is start of vlan range */ #define BRIDGE_VLAN_INFO_RANGE_END (1<<4) /* VLAN is end of vlan range */ #define BRIDGE_VLAN_INFO_BRENTRY (1<<5) /* Global bridge VLAN entry */ #define BRIDGE_VLAN_INFO_ONLY_OPTS (1<<6) /* Skip create/delete/flags */ struct bridge_vlan_info { __u16 flags; __u16 vid; }; enum { IFLA_BRIDGE_VLAN_TUNNEL_UNSPEC, IFLA_BRIDGE_VLAN_TUNNEL_ID, IFLA_BRIDGE_VLAN_TUNNEL_VID, IFLA_BRIDGE_VLAN_TUNNEL_FLAGS, __IFLA_BRIDGE_VLAN_TUNNEL_MAX, }; #define IFLA_BRIDGE_VLAN_TUNNEL_MAX (__IFLA_BRIDGE_VLAN_TUNNEL_MAX - 1) struct bridge_vlan_xstats { __u64 rx_bytes; __u64 rx_packets; __u64 tx_bytes; __u64 tx_packets; __u16 vid; __u16 flags; __u32 pad2; }; enum { IFLA_BRIDGE_MRP_UNSPEC, IFLA_BRIDGE_MRP_INSTANCE, IFLA_BRIDGE_MRP_PORT_STATE, IFLA_BRIDGE_MRP_PORT_ROLE, IFLA_BRIDGE_MRP_RING_STATE, IFLA_BRIDGE_MRP_RING_ROLE, IFLA_BRIDGE_MRP_START_TEST, IFLA_BRIDGE_MRP_INFO, IFLA_BRIDGE_MRP_IN_ROLE, IFLA_BRIDGE_MRP_IN_STATE, IFLA_BRIDGE_MRP_START_IN_TEST, __IFLA_BRIDGE_MRP_MAX, }; #define IFLA_BRIDGE_MRP_MAX (__IFLA_BRIDGE_MRP_MAX - 1) enum { IFLA_BRIDGE_MRP_INSTANCE_UNSPEC, IFLA_BRIDGE_MRP_INSTANCE_RING_ID, IFLA_BRIDGE_MRP_INSTANCE_P_IFINDEX, IFLA_BRIDGE_MRP_INSTANCE_S_IFINDEX, IFLA_BRIDGE_MRP_INSTANCE_PRIO, __IFLA_BRIDGE_MRP_INSTANCE_MAX, }; #define IFLA_BRIDGE_MRP_INSTANCE_MAX (__IFLA_BRIDGE_MRP_INSTANCE_MAX - 1) enum { IFLA_BRIDGE_MRP_PORT_STATE_UNSPEC, IFLA_BRIDGE_MRP_PORT_STATE_STATE, __IFLA_BRIDGE_MRP_PORT_STATE_MAX, }; #define IFLA_BRIDGE_MRP_PORT_STATE_MAX (__IFLA_BRIDGE_MRP_PORT_STATE_MAX - 1) enum { IFLA_BRIDGE_MRP_PORT_ROLE_UNSPEC, IFLA_BRIDGE_MRP_PORT_ROLE_ROLE, __IFLA_BRIDGE_MRP_PORT_ROLE_MAX, }; #define IFLA_BRIDGE_MRP_PORT_ROLE_MAX (__IFLA_BRIDGE_MRP_PORT_ROLE_MAX - 1) enum { IFLA_BRIDGE_MRP_RING_STATE_UNSPEC, IFLA_BRIDGE_MRP_RING_STATE_RING_ID, IFLA_BRIDGE_MRP_RING_STATE_STATE, __IFLA_BRIDGE_MRP_RING_STATE_MAX, }; #define IFLA_BRIDGE_MRP_RING_STATE_MAX (__IFLA_BRIDGE_MRP_RING_STATE_MAX - 1) enum { IFLA_BRIDGE_MRP_RING_ROLE_UNSPEC, IFLA_BRIDGE_MRP_RING_ROLE_RING_ID, IFLA_BRIDGE_MRP_RING_ROLE_ROLE, __IFLA_BRIDGE_MRP_RING_ROLE_MAX, }; #define IFLA_BRIDGE_MRP_RING_ROLE_MAX (__IFLA_BRIDGE_MRP_RING_ROLE_MAX - 1) enum { IFLA_BRIDGE_MRP_START_TEST_UNSPEC, IFLA_BRIDGE_MRP_START_TEST_RING_ID, IFLA_BRIDGE_MRP_START_TEST_INTERVAL, IFLA_BRIDGE_MRP_START_TEST_MAX_MISS, IFLA_BRIDGE_MRP_START_TEST_PERIOD, IFLA_BRIDGE_MRP_START_TEST_MONITOR, __IFLA_BRIDGE_MRP_START_TEST_MAX, }; #define IFLA_BRIDGE_MRP_START_TEST_MAX (__IFLA_BRIDGE_MRP_START_TEST_MAX - 1) enum { IFLA_BRIDGE_MRP_INFO_UNSPEC, IFLA_BRIDGE_MRP_INFO_RING_ID, IFLA_BRIDGE_MRP_INFO_P_IFINDEX, IFLA_BRIDGE_MRP_INFO_S_IFINDEX, IFLA_BRIDGE_MRP_INFO_PRIO, IFLA_BRIDGE_MRP_INFO_RING_STATE, IFLA_BRIDGE_MRP_INFO_RING_ROLE, IFLA_BRIDGE_MRP_INFO_TEST_INTERVAL, IFLA_BRIDGE_MRP_INFO_TEST_MAX_MISS, IFLA_BRIDGE_MRP_INFO_TEST_MONITOR, IFLA_BRIDGE_MRP_INFO_I_IFINDEX, IFLA_BRIDGE_MRP_INFO_IN_STATE, IFLA_BRIDGE_MRP_INFO_IN_ROLE, IFLA_BRIDGE_MRP_INFO_IN_TEST_INTERVAL, IFLA_BRIDGE_MRP_INFO_IN_TEST_MAX_MISS, __IFLA_BRIDGE_MRP_INFO_MAX, }; #define IFLA_BRIDGE_MRP_INFO_MAX (__IFLA_BRIDGE_MRP_INFO_MAX - 1) enum { IFLA_BRIDGE_MRP_IN_STATE_UNSPEC, IFLA_BRIDGE_MRP_IN_STATE_IN_ID, IFLA_BRIDGE_MRP_IN_STATE_STATE, __IFLA_BRIDGE_MRP_IN_STATE_MAX, }; #define IFLA_BRIDGE_MRP_IN_STATE_MAX (__IFLA_BRIDGE_MRP_IN_STATE_MAX - 1) enum { IFLA_BRIDGE_MRP_IN_ROLE_UNSPEC, IFLA_BRIDGE_MRP_IN_ROLE_RING_ID, IFLA_BRIDGE_MRP_IN_ROLE_IN_ID, IFLA_BRIDGE_MRP_IN_ROLE_ROLE, IFLA_BRIDGE_MRP_IN_ROLE_I_IFINDEX, __IFLA_BRIDGE_MRP_IN_ROLE_MAX, }; #define IFLA_BRIDGE_MRP_IN_ROLE_MAX (__IFLA_BRIDGE_MRP_IN_ROLE_MAX - 1) enum { IFLA_BRIDGE_MRP_START_IN_TEST_UNSPEC, IFLA_BRIDGE_MRP_START_IN_TEST_IN_ID, IFLA_BRIDGE_MRP_START_IN_TEST_INTERVAL, IFLA_BRIDGE_MRP_START_IN_TEST_MAX_MISS, IFLA_BRIDGE_MRP_START_IN_TEST_PERIOD, __IFLA_BRIDGE_MRP_START_IN_TEST_MAX, }; #define IFLA_BRIDGE_MRP_START_IN_TEST_MAX (__IFLA_BRIDGE_MRP_START_IN_TEST_MAX - 1) struct br_mrp_instance { __u32 ring_id; __u32 p_ifindex; __u32 s_ifindex; __u16 prio; }; struct br_mrp_ring_state { __u32 ring_id; __u32 ring_state; }; struct br_mrp_ring_role { __u32 ring_id; __u32 ring_role; }; struct br_mrp_start_test { __u32 ring_id; __u32 interval; __u32 max_miss; __u32 period; __u32 monitor; }; struct br_mrp_in_state { __u32 in_state; __u16 in_id; }; struct br_mrp_in_role { __u32 ring_id; __u32 in_role; __u32 i_ifindex; __u16 in_id; }; struct br_mrp_start_in_test { __u32 interval; __u32 max_miss; __u32 period; __u16 in_id; }; enum { IFLA_BRIDGE_CFM_UNSPEC, IFLA_BRIDGE_CFM_MEP_CREATE, IFLA_BRIDGE_CFM_MEP_DELETE, IFLA_BRIDGE_CFM_MEP_CONFIG, IFLA_BRIDGE_CFM_CC_CONFIG, IFLA_BRIDGE_CFM_CC_PEER_MEP_ADD, IFLA_BRIDGE_CFM_CC_PEER_MEP_REMOVE, IFLA_BRIDGE_CFM_CC_RDI, IFLA_BRIDGE_CFM_CC_CCM_TX, IFLA_BRIDGE_CFM_MEP_CREATE_INFO, IFLA_BRIDGE_CFM_MEP_CONFIG_INFO, IFLA_BRIDGE_CFM_CC_CONFIG_INFO, IFLA_BRIDGE_CFM_CC_RDI_INFO, IFLA_BRIDGE_CFM_CC_CCM_TX_INFO, IFLA_BRIDGE_CFM_CC_PEER_MEP_INFO, IFLA_BRIDGE_CFM_MEP_STATUS_INFO, IFLA_BRIDGE_CFM_CC_PEER_STATUS_INFO, __IFLA_BRIDGE_CFM_MAX, }; #define IFLA_BRIDGE_CFM_MAX (__IFLA_BRIDGE_CFM_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_CREATE_UNSPEC, IFLA_BRIDGE_CFM_MEP_CREATE_INSTANCE, IFLA_BRIDGE_CFM_MEP_CREATE_DOMAIN, IFLA_BRIDGE_CFM_MEP_CREATE_DIRECTION, IFLA_BRIDGE_CFM_MEP_CREATE_IFINDEX, __IFLA_BRIDGE_CFM_MEP_CREATE_MAX, }; #define IFLA_BRIDGE_CFM_MEP_CREATE_MAX (__IFLA_BRIDGE_CFM_MEP_CREATE_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_DELETE_UNSPEC, IFLA_BRIDGE_CFM_MEP_DELETE_INSTANCE, __IFLA_BRIDGE_CFM_MEP_DELETE_MAX, }; #define IFLA_BRIDGE_CFM_MEP_DELETE_MAX (__IFLA_BRIDGE_CFM_MEP_DELETE_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_CONFIG_UNSPEC, IFLA_BRIDGE_CFM_MEP_CONFIG_INSTANCE, IFLA_BRIDGE_CFM_MEP_CONFIG_UNICAST_MAC, IFLA_BRIDGE_CFM_MEP_CONFIG_MDLEVEL, IFLA_BRIDGE_CFM_MEP_CONFIG_MEPID, __IFLA_BRIDGE_CFM_MEP_CONFIG_MAX, }; #define IFLA_BRIDGE_CFM_MEP_CONFIG_MAX (__IFLA_BRIDGE_CFM_MEP_CONFIG_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_CONFIG_UNSPEC, IFLA_BRIDGE_CFM_CC_CONFIG_INSTANCE, IFLA_BRIDGE_CFM_CC_CONFIG_ENABLE, IFLA_BRIDGE_CFM_CC_CONFIG_EXP_INTERVAL, IFLA_BRIDGE_CFM_CC_CONFIG_EXP_MAID, __IFLA_BRIDGE_CFM_CC_CONFIG_MAX, }; #define IFLA_BRIDGE_CFM_CC_CONFIG_MAX (__IFLA_BRIDGE_CFM_CC_CONFIG_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_PEER_MEP_UNSPEC, IFLA_BRIDGE_CFM_CC_PEER_MEP_INSTANCE, IFLA_BRIDGE_CFM_CC_PEER_MEPID, __IFLA_BRIDGE_CFM_CC_PEER_MEP_MAX, }; #define IFLA_BRIDGE_CFM_CC_PEER_MEP_MAX (__IFLA_BRIDGE_CFM_CC_PEER_MEP_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_RDI_UNSPEC, IFLA_BRIDGE_CFM_CC_RDI_INSTANCE, IFLA_BRIDGE_CFM_CC_RDI_RDI, __IFLA_BRIDGE_CFM_CC_RDI_MAX, }; #define IFLA_BRIDGE_CFM_CC_RDI_MAX (__IFLA_BRIDGE_CFM_CC_RDI_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_CCM_TX_UNSPEC, IFLA_BRIDGE_CFM_CC_CCM_TX_INSTANCE, IFLA_BRIDGE_CFM_CC_CCM_TX_DMAC, IFLA_BRIDGE_CFM_CC_CCM_TX_SEQ_NO_UPDATE, IFLA_BRIDGE_CFM_CC_CCM_TX_PERIOD, IFLA_BRIDGE_CFM_CC_CCM_TX_IF_TLV, IFLA_BRIDGE_CFM_CC_CCM_TX_IF_TLV_VALUE, IFLA_BRIDGE_CFM_CC_CCM_TX_PORT_TLV, IFLA_BRIDGE_CFM_CC_CCM_TX_PORT_TLV_VALUE, __IFLA_BRIDGE_CFM_CC_CCM_TX_MAX, }; #define IFLA_BRIDGE_CFM_CC_CCM_TX_MAX (__IFLA_BRIDGE_CFM_CC_CCM_TX_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_STATUS_UNSPEC, IFLA_BRIDGE_CFM_MEP_STATUS_INSTANCE, IFLA_BRIDGE_CFM_MEP_STATUS_OPCODE_UNEXP_SEEN, IFLA_BRIDGE_CFM_MEP_STATUS_VERSION_UNEXP_SEEN, IFLA_BRIDGE_CFM_MEP_STATUS_RX_LEVEL_LOW_SEEN, __IFLA_BRIDGE_CFM_MEP_STATUS_MAX, }; #define IFLA_BRIDGE_CFM_MEP_STATUS_MAX (__IFLA_BRIDGE_CFM_MEP_STATUS_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_PEER_STATUS_UNSPEC, IFLA_BRIDGE_CFM_CC_PEER_STATUS_INSTANCE, IFLA_BRIDGE_CFM_CC_PEER_STATUS_PEER_MEPID, IFLA_BRIDGE_CFM_CC_PEER_STATUS_CCM_DEFECT, IFLA_BRIDGE_CFM_CC_PEER_STATUS_RDI, IFLA_BRIDGE_CFM_CC_PEER_STATUS_PORT_TLV_VALUE, IFLA_BRIDGE_CFM_CC_PEER_STATUS_IF_TLV_VALUE, IFLA_BRIDGE_CFM_CC_PEER_STATUS_SEEN, IFLA_BRIDGE_CFM_CC_PEER_STATUS_TLV_SEEN, IFLA_BRIDGE_CFM_CC_PEER_STATUS_SEQ_UNEXP_SEEN, __IFLA_BRIDGE_CFM_CC_PEER_STATUS_MAX, }; #define IFLA_BRIDGE_CFM_CC_PEER_STATUS_MAX (__IFLA_BRIDGE_CFM_CC_PEER_STATUS_MAX - 1) enum { IFLA_BRIDGE_MST_UNSPEC, IFLA_BRIDGE_MST_ENTRY, __IFLA_BRIDGE_MST_MAX, }; #define IFLA_BRIDGE_MST_MAX (__IFLA_BRIDGE_MST_MAX - 1) enum { IFLA_BRIDGE_MST_ENTRY_UNSPEC, IFLA_BRIDGE_MST_ENTRY_MSTI, IFLA_BRIDGE_MST_ENTRY_STATE, __IFLA_BRIDGE_MST_ENTRY_MAX, }; #define IFLA_BRIDGE_MST_ENTRY_MAX (__IFLA_BRIDGE_MST_ENTRY_MAX - 1) struct bridge_stp_xstats { __u64 transition_blk; __u64 transition_fwd; __u64 rx_bpdu; __u64 tx_bpdu; __u64 rx_tcn; __u64 tx_tcn; }; /* Bridge vlan RTM header */ struct br_vlan_msg { __u8 family; __u8 reserved1; __u16 reserved2; __u32 ifindex; }; enum { BRIDGE_VLANDB_DUMP_UNSPEC, BRIDGE_VLANDB_DUMP_FLAGS, __BRIDGE_VLANDB_DUMP_MAX, }; #define BRIDGE_VLANDB_DUMP_MAX (__BRIDGE_VLANDB_DUMP_MAX - 1) /* flags used in BRIDGE_VLANDB_DUMP_FLAGS attribute to affect dumps */ #define BRIDGE_VLANDB_DUMPF_STATS (1 << 0) /* Include stats in the dump */ #define BRIDGE_VLANDB_DUMPF_GLOBAL (1 << 1) /* Dump global vlan options only */ /* Bridge vlan RTM attributes * [BRIDGE_VLANDB_ENTRY] = { * [BRIDGE_VLANDB_ENTRY_INFO] * ... * } * [BRIDGE_VLANDB_GLOBAL_OPTIONS] = { * [BRIDGE_VLANDB_GOPTS_ID] * ... * } */ enum { BRIDGE_VLANDB_UNSPEC, BRIDGE_VLANDB_ENTRY, BRIDGE_VLANDB_GLOBAL_OPTIONS, __BRIDGE_VLANDB_MAX, }; #define BRIDGE_VLANDB_MAX (__BRIDGE_VLANDB_MAX - 1) enum { BRIDGE_VLANDB_ENTRY_UNSPEC, BRIDGE_VLANDB_ENTRY_INFO, BRIDGE_VLANDB_ENTRY_RANGE, BRIDGE_VLANDB_ENTRY_STATE, BRIDGE_VLANDB_ENTRY_TUNNEL_INFO, BRIDGE_VLANDB_ENTRY_STATS, BRIDGE_VLANDB_ENTRY_MCAST_ROUTER, __BRIDGE_VLANDB_ENTRY_MAX, }; #define BRIDGE_VLANDB_ENTRY_MAX (__BRIDGE_VLANDB_ENTRY_MAX - 1) /* [BRIDGE_VLANDB_ENTRY] = { * [BRIDGE_VLANDB_ENTRY_TUNNEL_INFO] = { * [BRIDGE_VLANDB_TINFO_ID] * ... * } * } */ enum { BRIDGE_VLANDB_TINFO_UNSPEC, BRIDGE_VLANDB_TINFO_ID, BRIDGE_VLANDB_TINFO_CMD, __BRIDGE_VLANDB_TINFO_MAX, }; #define BRIDGE_VLANDB_TINFO_MAX (__BRIDGE_VLANDB_TINFO_MAX - 1) /* [BRIDGE_VLANDB_ENTRY] = { * [BRIDGE_VLANDB_ENTRY_STATS] = { * [BRIDGE_VLANDB_STATS_RX_BYTES] * ... * } * ... * } */ enum { BRIDGE_VLANDB_STATS_UNSPEC, BRIDGE_VLANDB_STATS_RX_BYTES, BRIDGE_VLANDB_STATS_RX_PACKETS, BRIDGE_VLANDB_STATS_TX_BYTES, BRIDGE_VLANDB_STATS_TX_PACKETS, BRIDGE_VLANDB_STATS_PAD, __BRIDGE_VLANDB_STATS_MAX, }; #define BRIDGE_VLANDB_STATS_MAX (__BRIDGE_VLANDB_STATS_MAX - 1) enum { BRIDGE_VLANDB_GOPTS_UNSPEC, BRIDGE_VLANDB_GOPTS_ID, BRIDGE_VLANDB_GOPTS_RANGE, BRIDGE_VLANDB_GOPTS_MCAST_SNOOPING, BRIDGE_VLANDB_GOPTS_MCAST_IGMP_VERSION, BRIDGE_VLANDB_GOPTS_MCAST_MLD_VERSION, BRIDGE_VLANDB_GOPTS_MCAST_LAST_MEMBER_CNT, BRIDGE_VLANDB_GOPTS_MCAST_STARTUP_QUERY_CNT, BRIDGE_VLANDB_GOPTS_MCAST_LAST_MEMBER_INTVL, BRIDGE_VLANDB_GOPTS_PAD, BRIDGE_VLANDB_GOPTS_MCAST_MEMBERSHIP_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERIER_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERY_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERY_RESPONSE_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_STARTUP_QUERY_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERIER, BRIDGE_VLANDB_GOPTS_MCAST_ROUTER_PORTS, BRIDGE_VLANDB_GOPTS_MCAST_QUERIER_STATE, BRIDGE_VLANDB_GOPTS_MSTI, __BRIDGE_VLANDB_GOPTS_MAX }; #define BRIDGE_VLANDB_GOPTS_MAX (__BRIDGE_VLANDB_GOPTS_MAX - 1) /* Bridge multicast database attributes * [MDBA_MDB] = { * [MDBA_MDB_ENTRY] = { * [MDBA_MDB_ENTRY_INFO] { * struct br_mdb_entry * [MDBA_MDB_EATTR attributes] * } * } * } * [MDBA_ROUTER] = { * [MDBA_ROUTER_PORT] = { * u32 ifindex * [MDBA_ROUTER_PATTR attributes] * } * } */ enum { MDBA_UNSPEC, MDBA_MDB, MDBA_ROUTER, __MDBA_MAX, }; #define MDBA_MAX (__MDBA_MAX - 1) enum { MDBA_MDB_UNSPEC, MDBA_MDB_ENTRY, __MDBA_MDB_MAX, }; #define MDBA_MDB_MAX (__MDBA_MDB_MAX - 1) enum { MDBA_MDB_ENTRY_UNSPEC, MDBA_MDB_ENTRY_INFO, __MDBA_MDB_ENTRY_MAX, }; #define MDBA_MDB_ENTRY_MAX (__MDBA_MDB_ENTRY_MAX - 1) /* per mdb entry additional attributes */ enum { MDBA_MDB_EATTR_UNSPEC, MDBA_MDB_EATTR_TIMER, MDBA_MDB_EATTR_SRC_LIST, MDBA_MDB_EATTR_GROUP_MODE, MDBA_MDB_EATTR_SOURCE, MDBA_MDB_EATTR_RTPROT, __MDBA_MDB_EATTR_MAX }; #define MDBA_MDB_EATTR_MAX (__MDBA_MDB_EATTR_MAX - 1) /* per mdb entry source */ enum { MDBA_MDB_SRCLIST_UNSPEC, MDBA_MDB_SRCLIST_ENTRY, __MDBA_MDB_SRCLIST_MAX }; #define MDBA_MDB_SRCLIST_MAX (__MDBA_MDB_SRCLIST_MAX - 1) /* per mdb entry per source attributes * these are embedded in MDBA_MDB_SRCLIST_ENTRY */ enum { MDBA_MDB_SRCATTR_UNSPEC, MDBA_MDB_SRCATTR_ADDRESS, MDBA_MDB_SRCATTR_TIMER, __MDBA_MDB_SRCATTR_MAX }; #define MDBA_MDB_SRCATTR_MAX (__MDBA_MDB_SRCATTR_MAX - 1) /* multicast router types */ enum { MDB_RTR_TYPE_DISABLED, MDB_RTR_TYPE_TEMP_QUERY, MDB_RTR_TYPE_PERM, MDB_RTR_TYPE_TEMP }; enum { MDBA_ROUTER_UNSPEC, MDBA_ROUTER_PORT, __MDBA_ROUTER_MAX, }; #define MDBA_ROUTER_MAX (__MDBA_ROUTER_MAX - 1) /* router port attributes */ enum { MDBA_ROUTER_PATTR_UNSPEC, MDBA_ROUTER_PATTR_TIMER, MDBA_ROUTER_PATTR_TYPE, MDBA_ROUTER_PATTR_INET_TIMER, MDBA_ROUTER_PATTR_INET6_TIMER, MDBA_ROUTER_PATTR_VID, __MDBA_ROUTER_PATTR_MAX }; #define MDBA_ROUTER_PATTR_MAX (__MDBA_ROUTER_PATTR_MAX - 1) struct br_port_msg { __u8 family; __u32 ifindex; }; struct br_mdb_entry { __u32 ifindex; #define MDB_TEMPORARY 0 #define MDB_PERMANENT 1 __u8 state; #define MDB_FLAGS_OFFLOAD (1 << 0) #define MDB_FLAGS_FAST_LEAVE (1 << 1) #define MDB_FLAGS_STAR_EXCL (1 << 2) #define MDB_FLAGS_BLOCKED (1 << 3) __u8 flags; __u16 vid; struct { union { __be32 ip4; struct in6_addr ip6; unsigned char mac_addr[ETH_ALEN]; } u; __be16 proto; } addr; }; enum { MDBA_SET_ENTRY_UNSPEC, MDBA_SET_ENTRY, MDBA_SET_ENTRY_ATTRS, __MDBA_SET_ENTRY_MAX, }; #define MDBA_SET_ENTRY_MAX (__MDBA_SET_ENTRY_MAX - 1) /* [MDBA_SET_ENTRY_ATTRS] = { * [MDBE_ATTR_xxx] * ... * } */ enum { MDBE_ATTR_UNSPEC, MDBE_ATTR_SOURCE, __MDBE_ATTR_MAX, }; #define MDBE_ATTR_MAX (__MDBE_ATTR_MAX - 1) /* Embedded inside LINK_XSTATS_TYPE_BRIDGE */ enum { BRIDGE_XSTATS_UNSPEC, BRIDGE_XSTATS_VLAN, BRIDGE_XSTATS_MCAST, BRIDGE_XSTATS_PAD, BRIDGE_XSTATS_STP, __BRIDGE_XSTATS_MAX }; #define BRIDGE_XSTATS_MAX (__BRIDGE_XSTATS_MAX - 1) enum { BR_MCAST_DIR_RX, BR_MCAST_DIR_TX, BR_MCAST_DIR_SIZE }; /* IGMP/MLD statistics */ struct br_mcast_stats { __u64 igmp_v1queries[BR_MCAST_DIR_SIZE]; __u64 igmp_v2queries[BR_MCAST_DIR_SIZE]; __u64 igmp_v3queries[BR_MCAST_DIR_SIZE]; __u64 igmp_leaves[BR_MCAST_DIR_SIZE]; __u64 igmp_v1reports[BR_MCAST_DIR_SIZE]; __u64 igmp_v2reports[BR_MCAST_DIR_SIZE]; __u64 igmp_v3reports[BR_MCAST_DIR_SIZE]; __u64 igmp_parse_errors; __u64 mld_v1queries[BR_MCAST_DIR_SIZE]; __u64 mld_v2queries[BR_MCAST_DIR_SIZE]; __u64 mld_leaves[BR_MCAST_DIR_SIZE]; __u64 mld_v1reports[BR_MCAST_DIR_SIZE]; __u64 mld_v2reports[BR_MCAST_DIR_SIZE]; __u64 mld_parse_errors; __u64 mcast_bytes[BR_MCAST_DIR_SIZE]; __u64 mcast_packets[BR_MCAST_DIR_SIZE]; }; /* bridge boolean options * BR_BOOLOPT_NO_LL_LEARN - disable learning from link-local packets * BR_BOOLOPT_MCAST_VLAN_SNOOPING - control vlan multicast snooping * * IMPORTANT: if adding a new option do not forget to handle * it in br_boolopt_toggle/get and bridge sysfs */ enum br_boolopt_id { BR_BOOLOPT_NO_LL_LEARN, BR_BOOLOPT_MCAST_VLAN_SNOOPING, BR_BOOLOPT_MST_ENABLE, BR_BOOLOPT_MAX }; /* struct br_boolopt_multi - change multiple bridge boolean options * * @optval: new option values (bit per option) * @optmask: options to change (bit per option) */ struct br_boolopt_multi { __u32 optval; __u32 optmask; }; enum { BRIDGE_QUERIER_UNSPEC, BRIDGE_QUERIER_IP_ADDRESS, BRIDGE_QUERIER_IP_PORT, BRIDGE_QUERIER_IP_OTHER_TIMER, BRIDGE_QUERIER_PAD, BRIDGE_QUERIER_IPV6_ADDRESS, BRIDGE_QUERIER_IPV6_PORT, BRIDGE_QUERIER_IPV6_OTHER_TIMER, __BRIDGE_QUERIER_MAX }; #define BRIDGE_QUERIER_MAX (__BRIDGE_QUERIER_MAX - 1) #endif /* _LINUX_IF_BRIDGE_H */ linux/hidraw.h000064400000003711151027430560007337 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 2007 Jiri Kosina */ /* * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _HIDRAW_H #define _HIDRAW_H #include #include struct hidraw_report_descriptor { __u32 size; __u8 value[HID_MAX_DESCRIPTOR_SIZE]; }; struct hidraw_devinfo { __u32 bustype; __s16 vendor; __s16 product; }; /* ioctl interface */ #define HIDIOCGRDESCSIZE _IOR('H', 0x01, int) #define HIDIOCGRDESC _IOR('H', 0x02, struct hidraw_report_descriptor) #define HIDIOCGRAWINFO _IOR('H', 0x03, struct hidraw_devinfo) #define HIDIOCGRAWNAME(len) _IOC(_IOC_READ, 'H', 0x04, len) #define HIDIOCGRAWPHYS(len) _IOC(_IOC_READ, 'H', 0x05, len) /* The first byte of SFEATURE and GFEATURE is the report number */ #define HIDIOCSFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len) #define HIDIOCGFEATURE(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x07, len) #define HIDIOCGRAWUNIQ(len) _IOC(_IOC_READ, 'H', 0x08, len) /* The first byte of SINPUT and GINPUT is the report number */ #define HIDIOCSINPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x09, len) #define HIDIOCGINPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0A, len) /* The first byte of SOUTPUT and GOUTPUT is the report number */ #define HIDIOCSOUTPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0B, len) #define HIDIOCGOUTPUT(len) _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x0C, len) #define HIDRAW_FIRST_MINOR 0 #define HIDRAW_MAX_DEVICES 64 /* number of reports to buffer */ #define HIDRAW_BUFFER_SIZE 64 /* kernel-only API declarations */ #endif /* _HIDRAW_H */ linux/hsi/cs-protocol.h000064400000007110151027430560011105 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * cmt-speech interface definitions * * Copyright (C) 2008,2009,2010 Nokia Corporation. All rights reserved. * * Contact: Kai Vehmanen * Original author: Peter Ujfalusi * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef _CS_PROTOCOL_H #define _CS_PROTOCOL_H #include #include /* chardev parameters */ #define CS_DEV_FILE_NAME "/dev/cmt_speech" /* user-space API versioning */ #define CS_IF_VERSION 2 /* APE kernel <-> user space messages */ #define CS_CMD_SHIFT 28 #define CS_DOMAIN_SHIFT 24 #define CS_CMD_MASK 0xff000000 #define CS_PARAM_MASK 0xffffff #define CS_CMD(id, dom) \ (((id) << CS_CMD_SHIFT) | ((dom) << CS_DOMAIN_SHIFT)) #define CS_ERROR CS_CMD(1, 0) #define CS_RX_DATA_RECEIVED CS_CMD(2, 0) #define CS_TX_DATA_READY CS_CMD(3, 0) #define CS_TX_DATA_SENT CS_CMD(4, 0) /* params to CS_ERROR indication */ #define CS_ERR_PEER_RESET 0 /* ioctl interface */ /* parameters to CS_CONFIG_BUFS ioctl */ #define CS_FEAT_TSTAMP_RX_CTRL (1 << 0) #define CS_FEAT_ROLLING_RX_COUNTER (2 << 0) /* parameters to CS_GET_STATE ioctl */ #define CS_STATE_CLOSED 0 #define CS_STATE_OPENED 1 /* resource allocated */ #define CS_STATE_CONFIGURED 2 /* data path active */ /* maximum number of TX/RX buffers */ #define CS_MAX_BUFFERS_SHIFT 4 #define CS_MAX_BUFFERS (1 << CS_MAX_BUFFERS_SHIFT) /* Parameters for setting up the data buffers */ struct cs_buffer_config { __u32 rx_bufs; /* number of RX buffer slots */ __u32 tx_bufs; /* number of TX buffer slots */ __u32 buf_size; /* bytes */ __u32 flags; /* see CS_FEAT_* */ __u32 reserved[4]; }; /* * struct for monotonic timestamp taken when the * last control command was received */ struct cs_timestamp { __u32 tv_sec; /* seconds */ __u32 tv_nsec; /* nanoseconds */ }; /* * Struct describing the layout and contents of the driver mmap area. * This information is meant as read-only information for the application. */ struct cs_mmap_config_block { __u32 reserved1; __u32 buf_size; /* 0=disabled, otherwise the transfer size */ __u32 rx_bufs; /* # of RX buffers */ __u32 tx_bufs; /* # of TX buffers */ __u32 reserved2; /* array of offsets within the mmap area for each RX and TX buffer */ __u32 rx_offsets[CS_MAX_BUFFERS]; __u32 tx_offsets[CS_MAX_BUFFERS]; __u32 rx_ptr; __u32 rx_ptr_boundary; __u32 reserved3[2]; /* enabled with CS_FEAT_TSTAMP_RX_CTRL */ struct cs_timestamp tstamp_rx_ctrl; }; #define CS_IO_MAGIC 'C' #define CS_IOW(num, dtype) _IOW(CS_IO_MAGIC, num, dtype) #define CS_IOR(num, dtype) _IOR(CS_IO_MAGIC, num, dtype) #define CS_IOWR(num, dtype) _IOWR(CS_IO_MAGIC, num, dtype) #define CS_IO(num) _IO(CS_IO_MAGIC, num) #define CS_GET_STATE CS_IOR(21, unsigned int) #define CS_SET_WAKELINE CS_IOW(23, unsigned int) #define CS_GET_IF_VERSION CS_IOR(30, unsigned int) #define CS_CONFIG_BUFS CS_IOW(31, struct cs_buffer_config) #endif /* _CS_PROTOCOL_H */ linux/hsi/hsi_char.h000064400000003547151027430560010433 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Part of the HSI character device driver. * * Copyright (C) 2010 Nokia Corporation. All rights reserved. * * Contact: Andras Domokos * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef __HSI_CHAR_H #define __HSI_CHAR_H #include #define HSI_CHAR_MAGIC 'k' #define HSC_IOW(num, dtype) _IOW(HSI_CHAR_MAGIC, num, dtype) #define HSC_IOR(num, dtype) _IOR(HSI_CHAR_MAGIC, num, dtype) #define HSC_IOWR(num, dtype) _IOWR(HSI_CHAR_MAGIC, num, dtype) #define HSC_IO(num) _IO(HSI_CHAR_MAGIC, num) #define HSC_RESET HSC_IO(16) #define HSC_SET_PM HSC_IO(17) #define HSC_SEND_BREAK HSC_IO(18) #define HSC_SET_RX HSC_IOW(19, struct hsc_rx_config) #define HSC_GET_RX HSC_IOW(20, struct hsc_rx_config) #define HSC_SET_TX HSC_IOW(21, struct hsc_tx_config) #define HSC_GET_TX HSC_IOW(22, struct hsc_tx_config) #define HSC_PM_DISABLE 0 #define HSC_PM_ENABLE 1 #define HSC_MODE_STREAM 1 #define HSC_MODE_FRAME 2 #define HSC_FLOW_SYNC 0 #define HSC_ARB_RR 0 #define HSC_ARB_PRIO 1 struct hsc_rx_config { __u32 mode; __u32 flow; __u32 channels; }; struct hsc_tx_config { __u32 mode; __u32 channels; __u32 speed; __u32 arb_mode; }; #endif /* __HSI_CHAR_H */ linux/firewire-cdev.h000064400000125556151027430560010630 0ustar00/* * Char device interface. * * Copyright (C) 2005-2007 Kristian Hoegsberg * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef _LINUX_FIREWIRE_CDEV_H #define _LINUX_FIREWIRE_CDEV_H #include #include #include /* available since kernel version 2.6.22 */ #define FW_CDEV_EVENT_BUS_RESET 0x00 #define FW_CDEV_EVENT_RESPONSE 0x01 #define FW_CDEV_EVENT_REQUEST 0x02 #define FW_CDEV_EVENT_ISO_INTERRUPT 0x03 /* available since kernel version 2.6.30 */ #define FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED 0x04 #define FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED 0x05 /* available since kernel version 2.6.36 */ #define FW_CDEV_EVENT_REQUEST2 0x06 #define FW_CDEV_EVENT_PHY_PACKET_SENT 0x07 #define FW_CDEV_EVENT_PHY_PACKET_RECEIVED 0x08 #define FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL 0x09 /** * struct fw_cdev_event_common - Common part of all fw_cdev_event_ types * @closure: For arbitrary use by userspace * @type: Discriminates the fw_cdev_event_ types * * This struct may be used to access generic members of all fw_cdev_event_ * types regardless of the specific type. * * Data passed in the @closure field for a request will be returned in the * corresponding event. It is big enough to hold a pointer on all platforms. * The ioctl used to set @closure depends on the @type of event. */ struct fw_cdev_event_common { __u64 closure; __u32 type; }; /** * struct fw_cdev_event_bus_reset - Sent when a bus reset occurred * @closure: See &fw_cdev_event_common; set by %FW_CDEV_IOC_GET_INFO ioctl * @type: See &fw_cdev_event_common; always %FW_CDEV_EVENT_BUS_RESET * @node_id: New node ID of this node * @local_node_id: Node ID of the local node, i.e. of the controller * @bm_node_id: Node ID of the bus manager * @irm_node_id: Node ID of the iso resource manager * @root_node_id: Node ID of the root node * @generation: New bus generation * * This event is sent when the bus the device belongs to goes through a bus * reset. It provides information about the new bus configuration, such as * new node ID for this device, new root ID, and others. * * If @bm_node_id is 0xffff right after bus reset it can be reread by an * %FW_CDEV_IOC_GET_INFO ioctl after bus manager selection was finished. * Kernels with ABI version < 4 do not set @bm_node_id. */ struct fw_cdev_event_bus_reset { __u64 closure; __u32 type; __u32 node_id; __u32 local_node_id; __u32 bm_node_id; __u32 irm_node_id; __u32 root_node_id; __u32 generation; }; /** * struct fw_cdev_event_response - Sent when a response packet was received * @closure: See &fw_cdev_event_common; set by %FW_CDEV_IOC_SEND_REQUEST * or %FW_CDEV_IOC_SEND_BROADCAST_REQUEST * or %FW_CDEV_IOC_SEND_STREAM_PACKET ioctl * @type: See &fw_cdev_event_common; always %FW_CDEV_EVENT_RESPONSE * @rcode: Response code returned by the remote node * @length: Data length, i.e. the response's payload size in bytes * @data: Payload data, if any * * This event is sent when the stack receives a response to an outgoing request * sent by %FW_CDEV_IOC_SEND_REQUEST ioctl. The payload data for responses * carrying data (read and lock responses) follows immediately and can be * accessed through the @data field. * * The event is also generated after conclusions of transactions that do not * involve response packets. This includes unified write transactions, * broadcast write transactions, and transmission of asynchronous stream * packets. @rcode indicates success or failure of such transmissions. */ struct fw_cdev_event_response { __u64 closure; __u32 type; __u32 rcode; __u32 length; __u32 data[0]; }; /** * struct fw_cdev_event_request - Old version of &fw_cdev_event_request2 * @type: See &fw_cdev_event_common; always %FW_CDEV_EVENT_REQUEST * * This event is sent instead of &fw_cdev_event_request2 if the kernel or * the client implements ABI version <= 3. &fw_cdev_event_request lacks * essential information; use &fw_cdev_event_request2 instead. */ struct fw_cdev_event_request { __u64 closure; __u32 type; __u32 tcode; __u64 offset; __u32 handle; __u32 length; __u32 data[0]; }; /** * struct fw_cdev_event_request2 - Sent on incoming request to an address region * @closure: See &fw_cdev_event_common; set by %FW_CDEV_IOC_ALLOCATE ioctl * @type: See &fw_cdev_event_common; always %FW_CDEV_EVENT_REQUEST2 * @tcode: Transaction code of the incoming request * @offset: The offset into the 48-bit per-node address space * @source_node_id: Sender node ID * @destination_node_id: Destination node ID * @card: The index of the card from which the request came * @generation: Bus generation in which the request is valid * @handle: Reference to the kernel-side pending request * @length: Data length, i.e. the request's payload size in bytes * @data: Incoming data, if any * * This event is sent when the stack receives an incoming request to an address * region registered using the %FW_CDEV_IOC_ALLOCATE ioctl. The request is * guaranteed to be completely contained in the specified region. Userspace is * responsible for sending the response by %FW_CDEV_IOC_SEND_RESPONSE ioctl, * using the same @handle. * * The payload data for requests carrying data (write and lock requests) * follows immediately and can be accessed through the @data field. * * Unlike &fw_cdev_event_request, @tcode of lock requests is one of the * firewire-core specific %TCODE_LOCK_MASK_SWAP...%TCODE_LOCK_VENDOR_DEPENDENT, * i.e. encodes the extended transaction code. * * @card may differ from &fw_cdev_get_info.card because requests are received * from all cards of the Linux host. @source_node_id, @destination_node_id, and * @generation pertain to that card. Destination node ID and bus generation may * therefore differ from the corresponding fields of the last * &fw_cdev_event_bus_reset. * * @destination_node_id may also differ from the current node ID because of a * non-local bus ID part or in case of a broadcast write request. Note, a * client must call an %FW_CDEV_IOC_SEND_RESPONSE ioctl even in case of a * broadcast write request; the kernel will then release the kernel-side pending * request but will not actually send a response packet. * * In case of a write request to FCP_REQUEST or FCP_RESPONSE, the kernel already * sent a write response immediately after the request was received; in this * case the client must still call an %FW_CDEV_IOC_SEND_RESPONSE ioctl to * release the kernel-side pending request, though another response won't be * sent. * * If the client subsequently needs to initiate requests to the sender node of * an &fw_cdev_event_request2, it needs to use a device file with matching * card index, node ID, and generation for outbound requests. */ struct fw_cdev_event_request2 { __u64 closure; __u32 type; __u32 tcode; __u64 offset; __u32 source_node_id; __u32 destination_node_id; __u32 card; __u32 generation; __u32 handle; __u32 length; __u32 data[0]; }; /** * struct fw_cdev_event_iso_interrupt - Sent when an iso packet was completed * @closure: See &fw_cdev_event_common; * set by %FW_CDEV_CREATE_ISO_CONTEXT ioctl * @type: See &fw_cdev_event_common; always %FW_CDEV_EVENT_ISO_INTERRUPT * @cycle: Cycle counter of the last completed packet * @header_length: Total length of following headers, in bytes * @header: Stripped headers, if any * * This event is sent when the controller has completed an &fw_cdev_iso_packet * with the %FW_CDEV_ISO_INTERRUPT bit set, when explicitly requested with * %FW_CDEV_IOC_FLUSH_ISO, or when there have been so many completed packets * without the interrupt bit set that the kernel's internal buffer for @header * is about to overflow. (In the last case, ABI versions < 5 drop header data * up to the next interrupt packet.) * * Isochronous transmit events (context type %FW_CDEV_ISO_CONTEXT_TRANSMIT): * * In version 3 and some implementations of version 2 of the ABI, &header_length * is a multiple of 4 and &header contains timestamps of all packets up until * the interrupt packet. The format of the timestamps is as described below for * isochronous reception. In version 1 of the ABI, &header_length was 0. * * Isochronous receive events (context type %FW_CDEV_ISO_CONTEXT_RECEIVE): * * The headers stripped of all packets up until and including the interrupt * packet are returned in the @header field. The amount of header data per * packet is as specified at iso context creation by * &fw_cdev_create_iso_context.header_size. * * Hence, _interrupt.header_length / _context.header_size is the number of * packets received in this interrupt event. The client can now iterate * through the mmap()'ed DMA buffer according to this number of packets and * to the buffer sizes as the client specified in &fw_cdev_queue_iso. * * Since version 2 of this ABI, the portion for each packet in _interrupt.header * consists of the 1394 isochronous packet header, followed by a timestamp * quadlet if &fw_cdev_create_iso_context.header_size > 4, followed by quadlets * from the packet payload if &fw_cdev_create_iso_context.header_size > 8. * * Format of 1394 iso packet header: 16 bits data_length, 2 bits tag, 6 bits * channel, 4 bits tcode, 4 bits sy, in big endian byte order. * data_length is the actual received size of the packet without the four * 1394 iso packet header bytes. * * Format of timestamp: 16 bits invalid, 3 bits cycleSeconds, 13 bits * cycleCount, in big endian byte order. * * In version 1 of the ABI, no timestamp quadlet was inserted; instead, payload * data followed directly after the 1394 is header if header_size > 4. * Behaviour of ver. 1 of this ABI is no longer available since ABI ver. 2. */ struct fw_cdev_event_iso_interrupt { __u64 closure; __u32 type; __u32 cycle; __u32 header_length; __u32 header[0]; }; /** * struct fw_cdev_event_iso_interrupt_mc - An iso buffer chunk was completed * @closure: See &fw_cdev_event_common; * set by %FW_CDEV_CREATE_ISO_CONTEXT ioctl * @type: %FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL * @completed: Offset into the receive buffer; data before this offset is valid * * This event is sent in multichannel contexts (context type * %FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL) for &fw_cdev_iso_packet buffer * chunks that have been completely filled and that have the * %FW_CDEV_ISO_INTERRUPT bit set, or when explicitly requested with * %FW_CDEV_IOC_FLUSH_ISO. * * The buffer is continuously filled with the following data, per packet: * - the 1394 iso packet header as described at &fw_cdev_event_iso_interrupt, * but in little endian byte order, * - packet payload (as many bytes as specified in the data_length field of * the 1394 iso packet header) in big endian byte order, * - 0...3 padding bytes as needed to align the following trailer quadlet, * - trailer quadlet, containing the reception timestamp as described at * &fw_cdev_event_iso_interrupt, but in little endian byte order. * * Hence the per-packet size is data_length (rounded up to a multiple of 4) + 8. * When processing the data, stop before a packet that would cross the * @completed offset. * * A packet near the end of a buffer chunk will typically spill over into the * next queued buffer chunk. It is the responsibility of the client to check * for this condition, assemble a broken-up packet from its parts, and not to * re-queue any buffer chunks in which as yet unread packet parts reside. */ struct fw_cdev_event_iso_interrupt_mc { __u64 closure; __u32 type; __u32 completed; }; /** * struct fw_cdev_event_iso_resource - Iso resources were allocated or freed * @closure: See &fw_cdev_event_common; * set by %FW_CDEV_IOC_(DE)ALLOCATE_ISO_RESOURCE(_ONCE) ioctl * @type: %FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED or * %FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED * @handle: Reference by which an allocated resource can be deallocated * @channel: Isochronous channel which was (de)allocated, if any * @bandwidth: Bandwidth allocation units which were (de)allocated, if any * * An %FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED event is sent after an isochronous * resource was allocated at the IRM. The client has to check @channel and * @bandwidth for whether the allocation actually succeeded. * * An %FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED event is sent after an isochronous * resource was deallocated at the IRM. It is also sent when automatic * reallocation after a bus reset failed. * * @channel is <0 if no channel was (de)allocated or if reallocation failed. * @bandwidth is 0 if no bandwidth was (de)allocated or if reallocation failed. */ struct fw_cdev_event_iso_resource { __u64 closure; __u32 type; __u32 handle; __s32 channel; __s32 bandwidth; }; /** * struct fw_cdev_event_phy_packet - A PHY packet was transmitted or received * @closure: See &fw_cdev_event_common; set by %FW_CDEV_IOC_SEND_PHY_PACKET * or %FW_CDEV_IOC_RECEIVE_PHY_PACKETS ioctl * @type: %FW_CDEV_EVENT_PHY_PACKET_SENT or %..._RECEIVED * @rcode: %RCODE_..., indicates success or failure of transmission * @length: Data length in bytes * @data: Incoming data * * If @type is %FW_CDEV_EVENT_PHY_PACKET_SENT, @length is 0 and @data empty, * except in case of a ping packet: Then, @length is 4, and @data[0] is the * ping time in 49.152MHz clocks if @rcode is %RCODE_COMPLETE. * * If @type is %FW_CDEV_EVENT_PHY_PACKET_RECEIVED, @length is 8 and @data * consists of the two PHY packet quadlets, in host byte order. */ struct fw_cdev_event_phy_packet { __u64 closure; __u32 type; __u32 rcode; __u32 length; __u32 data[0]; }; /** * union fw_cdev_event - Convenience union of fw_cdev_event_ types * @common: Valid for all types * @bus_reset: Valid if @common.type == %FW_CDEV_EVENT_BUS_RESET * @response: Valid if @common.type == %FW_CDEV_EVENT_RESPONSE * @request: Valid if @common.type == %FW_CDEV_EVENT_REQUEST * @request2: Valid if @common.type == %FW_CDEV_EVENT_REQUEST2 * @iso_interrupt: Valid if @common.type == %FW_CDEV_EVENT_ISO_INTERRUPT * @iso_interrupt_mc: Valid if @common.type == * %FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL * @iso_resource: Valid if @common.type == * %FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED or * %FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED * @phy_packet: Valid if @common.type == * %FW_CDEV_EVENT_PHY_PACKET_SENT or * %FW_CDEV_EVENT_PHY_PACKET_RECEIVED * * Convenience union for userspace use. Events could be read(2) into an * appropriately aligned char buffer and then cast to this union for further * processing. Note that for a request, response or iso_interrupt event, * the data[] or header[] may make the size of the full event larger than * sizeof(union fw_cdev_event). Also note that if you attempt to read(2) * an event into a buffer that is not large enough for it, the data that does * not fit will be discarded so that the next read(2) will return a new event. */ union fw_cdev_event { struct fw_cdev_event_common common; struct fw_cdev_event_bus_reset bus_reset; struct fw_cdev_event_response response; struct fw_cdev_event_request request; struct fw_cdev_event_request2 request2; /* added in 2.6.36 */ struct fw_cdev_event_iso_interrupt iso_interrupt; struct fw_cdev_event_iso_interrupt_mc iso_interrupt_mc; /* added in 2.6.36 */ struct fw_cdev_event_iso_resource iso_resource; /* added in 2.6.30 */ struct fw_cdev_event_phy_packet phy_packet; /* added in 2.6.36 */ }; /* available since kernel version 2.6.22 */ #define FW_CDEV_IOC_GET_INFO _IOWR('#', 0x00, struct fw_cdev_get_info) #define FW_CDEV_IOC_SEND_REQUEST _IOW('#', 0x01, struct fw_cdev_send_request) #define FW_CDEV_IOC_ALLOCATE _IOWR('#', 0x02, struct fw_cdev_allocate) #define FW_CDEV_IOC_DEALLOCATE _IOW('#', 0x03, struct fw_cdev_deallocate) #define FW_CDEV_IOC_SEND_RESPONSE _IOW('#', 0x04, struct fw_cdev_send_response) #define FW_CDEV_IOC_INITIATE_BUS_RESET _IOW('#', 0x05, struct fw_cdev_initiate_bus_reset) #define FW_CDEV_IOC_ADD_DESCRIPTOR _IOWR('#', 0x06, struct fw_cdev_add_descriptor) #define FW_CDEV_IOC_REMOVE_DESCRIPTOR _IOW('#', 0x07, struct fw_cdev_remove_descriptor) #define FW_CDEV_IOC_CREATE_ISO_CONTEXT _IOWR('#', 0x08, struct fw_cdev_create_iso_context) #define FW_CDEV_IOC_QUEUE_ISO _IOWR('#', 0x09, struct fw_cdev_queue_iso) #define FW_CDEV_IOC_START_ISO _IOW('#', 0x0a, struct fw_cdev_start_iso) #define FW_CDEV_IOC_STOP_ISO _IOW('#', 0x0b, struct fw_cdev_stop_iso) /* available since kernel version 2.6.24 */ #define FW_CDEV_IOC_GET_CYCLE_TIMER _IOR('#', 0x0c, struct fw_cdev_get_cycle_timer) /* available since kernel version 2.6.30 */ #define FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE _IOWR('#', 0x0d, struct fw_cdev_allocate_iso_resource) #define FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE _IOW('#', 0x0e, struct fw_cdev_deallocate) #define FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE _IOW('#', 0x0f, struct fw_cdev_allocate_iso_resource) #define FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE_ONCE _IOW('#', 0x10, struct fw_cdev_allocate_iso_resource) #define FW_CDEV_IOC_GET_SPEED _IO('#', 0x11) /* returns speed code */ #define FW_CDEV_IOC_SEND_BROADCAST_REQUEST _IOW('#', 0x12, struct fw_cdev_send_request) #define FW_CDEV_IOC_SEND_STREAM_PACKET _IOW('#', 0x13, struct fw_cdev_send_stream_packet) /* available since kernel version 2.6.34 */ #define FW_CDEV_IOC_GET_CYCLE_TIMER2 _IOWR('#', 0x14, struct fw_cdev_get_cycle_timer2) /* available since kernel version 2.6.36 */ #define FW_CDEV_IOC_SEND_PHY_PACKET _IOWR('#', 0x15, struct fw_cdev_send_phy_packet) #define FW_CDEV_IOC_RECEIVE_PHY_PACKETS _IOW('#', 0x16, struct fw_cdev_receive_phy_packets) #define FW_CDEV_IOC_SET_ISO_CHANNELS _IOW('#', 0x17, struct fw_cdev_set_iso_channels) /* available since kernel version 3.4 */ #define FW_CDEV_IOC_FLUSH_ISO _IOW('#', 0x18, struct fw_cdev_flush_iso) /* * ABI version history * 1 (2.6.22) - initial version * (2.6.24) - added %FW_CDEV_IOC_GET_CYCLE_TIMER * 2 (2.6.30) - changed &fw_cdev_event_iso_interrupt.header if * &fw_cdev_create_iso_context.header_size is 8 or more * - added %FW_CDEV_IOC_*_ISO_RESOURCE*, * %FW_CDEV_IOC_GET_SPEED, %FW_CDEV_IOC_SEND_BROADCAST_REQUEST, * %FW_CDEV_IOC_SEND_STREAM_PACKET * (2.6.32) - added time stamp to xmit &fw_cdev_event_iso_interrupt * (2.6.33) - IR has always packet-per-buffer semantics now, not one of * dual-buffer or packet-per-buffer depending on hardware * - shared use and auto-response for FCP registers * 3 (2.6.34) - made &fw_cdev_get_cycle_timer reliable * - added %FW_CDEV_IOC_GET_CYCLE_TIMER2 * 4 (2.6.36) - added %FW_CDEV_EVENT_REQUEST2, %FW_CDEV_EVENT_PHY_PACKET_*, * and &fw_cdev_allocate.region_end * - implemented &fw_cdev_event_bus_reset.bm_node_id * - added %FW_CDEV_IOC_SEND_PHY_PACKET, _RECEIVE_PHY_PACKETS * - added %FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL, * %FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL, and * %FW_CDEV_IOC_SET_ISO_CHANNELS * 5 (3.4) - send %FW_CDEV_EVENT_ISO_INTERRUPT events when needed to * avoid dropping data * - added %FW_CDEV_IOC_FLUSH_ISO */ /** * struct fw_cdev_get_info - General purpose information ioctl * @version: The version field is just a running serial number. Both an * input parameter (ABI version implemented by the client) and * output parameter (ABI version implemented by the kernel). * A client shall fill in the ABI @version for which the client * was implemented. This is necessary for forward compatibility. * @rom_length: If @rom is non-zero, up to @rom_length bytes of Configuration * ROM will be copied into that user space address. In either * case, @rom_length is updated with the actual length of the * Configuration ROM. * @rom: If non-zero, address of a buffer to be filled by a copy of the * device's Configuration ROM * @bus_reset: If non-zero, address of a buffer to be filled by a * &struct fw_cdev_event_bus_reset with the current state * of the bus. This does not cause a bus reset to happen. * @bus_reset_closure: Value of &closure in this and subsequent bus reset events * @card: The index of the card this device belongs to * * The %FW_CDEV_IOC_GET_INFO ioctl is usually the very first one which a client * performs right after it opened a /dev/fw* file. * * As a side effect, reception of %FW_CDEV_EVENT_BUS_RESET events to be read(2) * is started by this ioctl. */ struct fw_cdev_get_info { __u32 version; __u32 rom_length; __u64 rom; __u64 bus_reset; __u64 bus_reset_closure; __u32 card; }; /** * struct fw_cdev_send_request - Send an asynchronous request packet * @tcode: Transaction code of the request * @length: Length of outgoing payload, in bytes * @offset: 48-bit offset at destination node * @closure: Passed back to userspace in the response event * @data: Userspace pointer to payload * @generation: The bus generation where packet is valid * * Send a request to the device. This ioctl implements all outgoing requests. * Both quadlet and block request specify the payload as a pointer to the data * in the @data field. Once the transaction completes, the kernel writes an * &fw_cdev_event_response event back. The @closure field is passed back to * user space in the response event. */ struct fw_cdev_send_request { __u32 tcode; __u32 length; __u64 offset; __u64 closure; __u64 data; __u32 generation; }; /** * struct fw_cdev_send_response - Send an asynchronous response packet * @rcode: Response code as determined by the userspace handler * @length: Length of outgoing payload, in bytes * @data: Userspace pointer to payload * @handle: The handle from the &fw_cdev_event_request * * Send a response to an incoming request. By setting up an address range using * the %FW_CDEV_IOC_ALLOCATE ioctl, userspace can listen for incoming requests. An * incoming request will generate an %FW_CDEV_EVENT_REQUEST, and userspace must * send a reply using this ioctl. The event has a handle to the kernel-side * pending transaction, which should be used with this ioctl. */ struct fw_cdev_send_response { __u32 rcode; __u32 length; __u64 data; __u32 handle; }; /** * struct fw_cdev_allocate - Allocate a CSR in an address range * @offset: Start offset of the address range * @closure: To be passed back to userspace in request events * @length: Length of the CSR, in bytes * @handle: Handle to the allocation, written by the kernel * @region_end: First address above the address range (added in ABI v4, 2.6.36) * * Allocate an address range in the 48-bit address space on the local node * (the controller). This allows userspace to listen for requests with an * offset within that address range. Every time when the kernel receives a * request within the range, an &fw_cdev_event_request2 event will be emitted. * (If the kernel or the client implements ABI version <= 3, an * &fw_cdev_event_request will be generated instead.) * * The @closure field is passed back to userspace in these request events. * The @handle field is an out parameter, returning a handle to the allocated * range to be used for later deallocation of the range. * * The address range is allocated on all local nodes. The address allocation * is exclusive except for the FCP command and response registers. If an * exclusive address region is already in use, the ioctl fails with errno set * to %EBUSY. * * If kernel and client implement ABI version >= 4, the kernel looks up a free * spot of size @length inside [@offset..@region_end) and, if found, writes * the start address of the new CSR back in @offset. I.e. @offset is an * in and out parameter. If this automatic placement of a CSR in a bigger * address range is not desired, the client simply needs to set @region_end * = @offset + @length. * * If the kernel or the client implements ABI version <= 3, @region_end is * ignored and effectively assumed to be @offset + @length. * * @region_end is only present in a kernel header >= 2.6.36. If necessary, * this can for example be tested by #ifdef FW_CDEV_EVENT_REQUEST2. */ struct fw_cdev_allocate { __u64 offset; __u64 closure; __u32 length; __u32 handle; __u64 region_end; /* available since kernel version 2.6.36 */ }; /** * struct fw_cdev_deallocate - Free a CSR address range or isochronous resource * @handle: Handle to the address range or iso resource, as returned by the * kernel when the range or resource was allocated */ struct fw_cdev_deallocate { __u32 handle; }; #define FW_CDEV_LONG_RESET 0 #define FW_CDEV_SHORT_RESET 1 /** * struct fw_cdev_initiate_bus_reset - Initiate a bus reset * @type: %FW_CDEV_SHORT_RESET or %FW_CDEV_LONG_RESET * * Initiate a bus reset for the bus this device is on. The bus reset can be * either the original (long) bus reset or the arbitrated (short) bus reset * introduced in 1394a-2000. * * The ioctl returns immediately. A subsequent &fw_cdev_event_bus_reset * indicates when the reset actually happened. Since ABI v4, this may be * considerably later than the ioctl because the kernel ensures a grace period * between subsequent bus resets as per IEEE 1394 bus management specification. */ struct fw_cdev_initiate_bus_reset { __u32 type; }; /** * struct fw_cdev_add_descriptor - Add contents to the local node's config ROM * @immediate: If non-zero, immediate key to insert before pointer * @key: Upper 8 bits of root directory pointer * @data: Userspace pointer to contents of descriptor block * @length: Length of descriptor block data, in quadlets * @handle: Handle to the descriptor, written by the kernel * * Add a descriptor block and optionally a preceding immediate key to the local * node's Configuration ROM. * * The @key field specifies the upper 8 bits of the descriptor root directory * pointer and the @data and @length fields specify the contents. The @key * should be of the form 0xXX000000. The offset part of the root directory entry * will be filled in by the kernel. * * If not 0, the @immediate field specifies an immediate key which will be * inserted before the root directory pointer. * * @immediate, @key, and @data array elements are CPU-endian quadlets. * * If successful, the kernel adds the descriptor and writes back a @handle to * the kernel-side object to be used for later removal of the descriptor block * and immediate key. The kernel will also generate a bus reset to signal the * change of the Configuration ROM to other nodes. * * This ioctl affects the Configuration ROMs of all local nodes. * The ioctl only succeeds on device files which represent a local node. */ struct fw_cdev_add_descriptor { __u32 immediate; __u32 key; __u64 data; __u32 length; __u32 handle; }; /** * struct fw_cdev_remove_descriptor - Remove contents from the Configuration ROM * @handle: Handle to the descriptor, as returned by the kernel when the * descriptor was added * * Remove a descriptor block and accompanying immediate key from the local * nodes' Configuration ROMs. The kernel will also generate a bus reset to * signal the change of the Configuration ROM to other nodes. */ struct fw_cdev_remove_descriptor { __u32 handle; }; #define FW_CDEV_ISO_CONTEXT_TRANSMIT 0 #define FW_CDEV_ISO_CONTEXT_RECEIVE 1 #define FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL 2 /* added in 2.6.36 */ /** * struct fw_cdev_create_iso_context - Create a context for isochronous I/O * @type: %FW_CDEV_ISO_CONTEXT_TRANSMIT or %FW_CDEV_ISO_CONTEXT_RECEIVE or * %FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL * @header_size: Header size to strip in single-channel reception * @channel: Channel to bind to in single-channel reception or transmission * @speed: Transmission speed * @closure: To be returned in &fw_cdev_event_iso_interrupt or * &fw_cdev_event_iso_interrupt_multichannel * @handle: Handle to context, written back by kernel * * Prior to sending or receiving isochronous I/O, a context must be created. * The context records information about the transmit or receive configuration * and typically maps to an underlying hardware resource. A context is set up * for either sending or receiving. It is bound to a specific isochronous * @channel. * * In case of multichannel reception, @header_size and @channel are ignored * and the channels are selected by %FW_CDEV_IOC_SET_ISO_CHANNELS. * * For %FW_CDEV_ISO_CONTEXT_RECEIVE contexts, @header_size must be at least 4 * and must be a multiple of 4. It is ignored in other context types. * * @speed is ignored in receive context types. * * If a context was successfully created, the kernel writes back a handle to the * context, which must be passed in for subsequent operations on that context. * * Limitations: * No more than one iso context can be created per fd. * The total number of contexts that all userspace and kernelspace drivers can * create on a card at a time is a hardware limit, typically 4 or 8 contexts per * direction, and of them at most one multichannel receive context. */ struct fw_cdev_create_iso_context { __u32 type; __u32 header_size; __u32 channel; __u32 speed; __u64 closure; __u32 handle; }; /** * struct fw_cdev_set_iso_channels - Select channels in multichannel reception * @channels: Bitmask of channels to listen to * @handle: Handle of the mutichannel receive context * * @channels is the bitwise or of 1ULL << n for each channel n to listen to. * * The ioctl fails with errno %EBUSY if there is already another receive context * on a channel in @channels. In that case, the bitmask of all unoccupied * channels is returned in @channels. */ struct fw_cdev_set_iso_channels { __u64 channels; __u32 handle; }; #define FW_CDEV_ISO_PAYLOAD_LENGTH(v) (v) #define FW_CDEV_ISO_INTERRUPT (1 << 16) #define FW_CDEV_ISO_SKIP (1 << 17) #define FW_CDEV_ISO_SYNC (1 << 17) #define FW_CDEV_ISO_TAG(v) ((v) << 18) #define FW_CDEV_ISO_SY(v) ((v) << 20) #define FW_CDEV_ISO_HEADER_LENGTH(v) ((v) << 24) /** * struct fw_cdev_iso_packet - Isochronous packet * @control: Contains the header length (8 uppermost bits), * the sy field (4 bits), the tag field (2 bits), a sync flag * or a skip flag (1 bit), an interrupt flag (1 bit), and the * payload length (16 lowermost bits) * @header: Header and payload in case of a transmit context. * * &struct fw_cdev_iso_packet is used to describe isochronous packet queues. * Use the FW_CDEV_ISO_ macros to fill in @control. * The @header array is empty in case of receive contexts. * * Context type %FW_CDEV_ISO_CONTEXT_TRANSMIT: * * @control.HEADER_LENGTH must be a multiple of 4. It specifies the numbers of * bytes in @header that will be prepended to the packet's payload. These bytes * are copied into the kernel and will not be accessed after the ioctl has * returned. * * The @control.SY and TAG fields are copied to the iso packet header. These * fields are specified by IEEE 1394a and IEC 61883-1. * * The @control.SKIP flag specifies that no packet is to be sent in a frame. * When using this, all other fields except @control.INTERRUPT must be zero. * * When a packet with the @control.INTERRUPT flag set has been completed, an * &fw_cdev_event_iso_interrupt event will be sent. * * Context type %FW_CDEV_ISO_CONTEXT_RECEIVE: * * @control.HEADER_LENGTH must be a multiple of the context's header_size. * If the HEADER_LENGTH is larger than the context's header_size, multiple * packets are queued for this entry. * * The @control.SY and TAG fields are ignored. * * If the @control.SYNC flag is set, the context drops all packets until a * packet with a sy field is received which matches &fw_cdev_start_iso.sync. * * @control.PAYLOAD_LENGTH defines how many payload bytes can be received for * one packet (in addition to payload quadlets that have been defined as headers * and are stripped and returned in the &fw_cdev_event_iso_interrupt structure). * If more bytes are received, the additional bytes are dropped. If less bytes * are received, the remaining bytes in this part of the payload buffer will not * be written to, not even by the next packet. I.e., packets received in * consecutive frames will not necessarily be consecutive in memory. If an * entry has queued multiple packets, the PAYLOAD_LENGTH is divided equally * among them. * * When a packet with the @control.INTERRUPT flag set has been completed, an * &fw_cdev_event_iso_interrupt event will be sent. An entry that has queued * multiple receive packets is completed when its last packet is completed. * * Context type %FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL: * * Here, &fw_cdev_iso_packet would be more aptly named _iso_buffer_chunk since * it specifies a chunk of the mmap()'ed buffer, while the number and alignment * of packets to be placed into the buffer chunk is not known beforehand. * * @control.PAYLOAD_LENGTH is the size of the buffer chunk and specifies room * for header, payload, padding, and trailer bytes of one or more packets. * It must be a multiple of 4. * * @control.HEADER_LENGTH, TAG and SY are ignored. SYNC is treated as described * for single-channel reception. * * When a buffer chunk with the @control.INTERRUPT flag set has been filled * entirely, an &fw_cdev_event_iso_interrupt_mc event will be sent. */ struct fw_cdev_iso_packet { __u32 control; __u32 header[0]; }; /** * struct fw_cdev_queue_iso - Queue isochronous packets for I/O * @packets: Userspace pointer to an array of &fw_cdev_iso_packet * @data: Pointer into mmap()'ed payload buffer * @size: Size of the @packets array, in bytes * @handle: Isochronous context handle * * Queue a number of isochronous packets for reception or transmission. * This ioctl takes a pointer to an array of &fw_cdev_iso_packet structs, * which describe how to transmit from or receive into a contiguous region * of a mmap()'ed payload buffer. As part of transmit packet descriptors, * a series of headers can be supplied, which will be prepended to the * payload during DMA. * * The kernel may or may not queue all packets, but will write back updated * values of the @packets, @data and @size fields, so the ioctl can be * resubmitted easily. * * In case of a multichannel receive context, @data must be quadlet-aligned * relative to the buffer start. */ struct fw_cdev_queue_iso { __u64 packets; __u64 data; __u32 size; __u32 handle; }; #define FW_CDEV_ISO_CONTEXT_MATCH_TAG0 1 #define FW_CDEV_ISO_CONTEXT_MATCH_TAG1 2 #define FW_CDEV_ISO_CONTEXT_MATCH_TAG2 4 #define FW_CDEV_ISO_CONTEXT_MATCH_TAG3 8 #define FW_CDEV_ISO_CONTEXT_MATCH_ALL_TAGS 15 /** * struct fw_cdev_start_iso - Start an isochronous transmission or reception * @cycle: Cycle in which to start I/O. If @cycle is greater than or * equal to 0, the I/O will start on that cycle. * @sync: Determines the value to wait for for receive packets that have * the %FW_CDEV_ISO_SYNC bit set * @tags: Tag filter bit mask. Only valid for isochronous reception. * Determines the tag values for which packets will be accepted. * Use FW_CDEV_ISO_CONTEXT_MATCH_ macros to set @tags. * @handle: Isochronous context handle within which to transmit or receive */ struct fw_cdev_start_iso { __s32 cycle; __u32 sync; __u32 tags; __u32 handle; }; /** * struct fw_cdev_stop_iso - Stop an isochronous transmission or reception * @handle: Handle of isochronous context to stop */ struct fw_cdev_stop_iso { __u32 handle; }; /** * struct fw_cdev_flush_iso - flush completed iso packets * @handle: handle of isochronous context to flush * * For %FW_CDEV_ISO_CONTEXT_TRANSMIT or %FW_CDEV_ISO_CONTEXT_RECEIVE contexts, * report any completed packets. * * For %FW_CDEV_ISO_CONTEXT_RECEIVE_MULTICHANNEL contexts, report the current * offset in the receive buffer, if it has changed; this is typically in the * middle of some buffer chunk. * * Any %FW_CDEV_EVENT_ISO_INTERRUPT or %FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL * events generated by this ioctl are sent synchronously, i.e., are available * for reading from the file descriptor when this ioctl returns. */ struct fw_cdev_flush_iso { __u32 handle; }; /** * struct fw_cdev_get_cycle_timer - read cycle timer register * @local_time: system time, in microseconds since the Epoch * @cycle_timer: Cycle Time register contents * * Same as %FW_CDEV_IOC_GET_CYCLE_TIMER2, but fixed to use %CLOCK_REALTIME * and only with microseconds resolution. * * In version 1 and 2 of the ABI, this ioctl returned unreliable (non- * monotonic) @cycle_timer values on certain controllers. */ struct fw_cdev_get_cycle_timer { __u64 local_time; __u32 cycle_timer; }; /** * struct fw_cdev_get_cycle_timer2 - read cycle timer register * @tv_sec: system time, seconds * @tv_nsec: system time, sub-seconds part in nanoseconds * @clk_id: input parameter, clock from which to get the system time * @cycle_timer: Cycle Time register contents * * The %FW_CDEV_IOC_GET_CYCLE_TIMER2 ioctl reads the isochronous cycle timer * and also the system clock. This allows to correlate reception time of * isochronous packets with system time. * * @clk_id lets you choose a clock like with POSIX' clock_gettime function. * Supported @clk_id values are POSIX' %CLOCK_REALTIME and %CLOCK_MONOTONIC * and Linux' %CLOCK_MONOTONIC_RAW. * * @cycle_timer consists of 7 bits cycleSeconds, 13 bits cycleCount, and * 12 bits cycleOffset, in host byte order. Cf. the Cycle Time register * per IEEE 1394 or Isochronous Cycle Timer register per OHCI-1394. */ struct fw_cdev_get_cycle_timer2 { __s64 tv_sec; __s32 tv_nsec; __s32 clk_id; __u32 cycle_timer; }; /** * struct fw_cdev_allocate_iso_resource - (De)allocate a channel or bandwidth * @closure: Passed back to userspace in corresponding iso resource events * @channels: Isochronous channels of which one is to be (de)allocated * @bandwidth: Isochronous bandwidth units to be (de)allocated * @handle: Handle to the allocation, written by the kernel (only valid in * case of %FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE ioctls) * * The %FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE ioctl initiates allocation of an * isochronous channel and/or of isochronous bandwidth at the isochronous * resource manager (IRM). Only one of the channels specified in @channels is * allocated. An %FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED is sent after * communication with the IRM, indicating success or failure in the event data. * The kernel will automatically reallocate the resources after bus resets. * Should a reallocation fail, an %FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED event * will be sent. The kernel will also automatically deallocate the resources * when the file descriptor is closed. * * The %FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE ioctl can be used to initiate * deallocation of resources which were allocated as described above. * An %FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED event concludes this operation. * * The %FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE ioctl is a variant of allocation * without automatic re- or deallocation. * An %FW_CDEV_EVENT_ISO_RESOURCE_ALLOCATED event concludes this operation, * indicating success or failure in its data. * * The %FW_CDEV_IOC_DEALLOCATE_ISO_RESOURCE_ONCE ioctl works like * %FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE except that resources are freed * instead of allocated. * An %FW_CDEV_EVENT_ISO_RESOURCE_DEALLOCATED event concludes this operation. * * To summarize, %FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE allocates iso resources * for the lifetime of the fd or @handle. * In contrast, %FW_CDEV_IOC_ALLOCATE_ISO_RESOURCE_ONCE allocates iso resources * for the duration of a bus generation. * * @channels is a host-endian bitfield with the least significant bit * representing channel 0 and the most significant bit representing channel 63: * 1ULL << c for each channel c that is a candidate for (de)allocation. * * @bandwidth is expressed in bandwidth allocation units, i.e. the time to send * one quadlet of data (payload or header data) at speed S1600. */ struct fw_cdev_allocate_iso_resource { __u64 closure; __u64 channels; __u32 bandwidth; __u32 handle; }; /** * struct fw_cdev_send_stream_packet - send an asynchronous stream packet * @length: Length of outgoing payload, in bytes * @tag: Data format tag * @channel: Isochronous channel to transmit to * @sy: Synchronization code * @closure: Passed back to userspace in the response event * @data: Userspace pointer to payload * @generation: The bus generation where packet is valid * @speed: Speed to transmit at * * The %FW_CDEV_IOC_SEND_STREAM_PACKET ioctl sends an asynchronous stream packet * to every device which is listening to the specified channel. The kernel * writes an &fw_cdev_event_response event which indicates success or failure of * the transmission. */ struct fw_cdev_send_stream_packet { __u32 length; __u32 tag; __u32 channel; __u32 sy; __u64 closure; __u64 data; __u32 generation; __u32 speed; }; /** * struct fw_cdev_send_phy_packet - send a PHY packet * @closure: Passed back to userspace in the PHY-packet-sent event * @data: First and second quadlet of the PHY packet * @generation: The bus generation where packet is valid * * The %FW_CDEV_IOC_SEND_PHY_PACKET ioctl sends a PHY packet to all nodes * on the same card as this device. After transmission, an * %FW_CDEV_EVENT_PHY_PACKET_SENT event is generated. * * The payload @data[] shall be specified in host byte order. Usually, * @data[1] needs to be the bitwise inverse of @data[0]. VersaPHY packets * are an exception to this rule. * * The ioctl is only permitted on device files which represent a local node. */ struct fw_cdev_send_phy_packet { __u64 closure; __u32 data[2]; __u32 generation; }; /** * struct fw_cdev_receive_phy_packets - start reception of PHY packets * @closure: Passed back to userspace in phy packet events * * This ioctl activates issuing of %FW_CDEV_EVENT_PHY_PACKET_RECEIVED due to * incoming PHY packets from any node on the same bus as the device. * * The ioctl is only permitted on device files which represent a local node. */ struct fw_cdev_receive_phy_packets { __u64 closure; }; #define FW_CDEV_VERSION 3 /* Meaningless legacy macro; don't use it. */ #endif /* _LINUX_FIREWIRE_CDEV_H */ linux/xattr.h000064400000005454151027430560007231 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* File: linux/xattr.h Extended attributes handling. Copyright (C) 2001 by Andreas Gruenbacher Copyright (c) 2001-2002 Silicon Graphics, Inc. All Rights Reserved. Copyright (c) 2004 Red Hat, Inc., James Morris */ #include #ifndef _LINUX_XATTR_H #define _LINUX_XATTR_H #if __UAPI_DEF_XATTR #define __USE_KERNEL_XATTR_DEFS #define XATTR_CREATE 0x1 /* set value, fail if attr already exists */ #define XATTR_REPLACE 0x2 /* set value, fail if attr does not exist */ #endif /* Namespaces */ #define XATTR_OS2_PREFIX "os2." #define XATTR_OS2_PREFIX_LEN (sizeof(XATTR_OS2_PREFIX) - 1) #define XATTR_MAC_OSX_PREFIX "osx." #define XATTR_MAC_OSX_PREFIX_LEN (sizeof(XATTR_MAC_OSX_PREFIX) - 1) #define XATTR_BTRFS_PREFIX "btrfs." #define XATTR_BTRFS_PREFIX_LEN (sizeof(XATTR_BTRFS_PREFIX) - 1) #define XATTR_SECURITY_PREFIX "security." #define XATTR_SECURITY_PREFIX_LEN (sizeof(XATTR_SECURITY_PREFIX) - 1) #define XATTR_SYSTEM_PREFIX "system." #define XATTR_SYSTEM_PREFIX_LEN (sizeof(XATTR_SYSTEM_PREFIX) - 1) #define XATTR_TRUSTED_PREFIX "trusted." #define XATTR_TRUSTED_PREFIX_LEN (sizeof(XATTR_TRUSTED_PREFIX) - 1) #define XATTR_USER_PREFIX "user." #define XATTR_USER_PREFIX_LEN (sizeof(XATTR_USER_PREFIX) - 1) /* Security namespace */ #define XATTR_EVM_SUFFIX "evm" #define XATTR_NAME_EVM XATTR_SECURITY_PREFIX XATTR_EVM_SUFFIX #define XATTR_IMA_SUFFIX "ima" #define XATTR_NAME_IMA XATTR_SECURITY_PREFIX XATTR_IMA_SUFFIX #define XATTR_SELINUX_SUFFIX "selinux" #define XATTR_NAME_SELINUX XATTR_SECURITY_PREFIX XATTR_SELINUX_SUFFIX #define XATTR_SMACK_SUFFIX "SMACK64" #define XATTR_SMACK_IPIN "SMACK64IPIN" #define XATTR_SMACK_IPOUT "SMACK64IPOUT" #define XATTR_SMACK_EXEC "SMACK64EXEC" #define XATTR_SMACK_TRANSMUTE "SMACK64TRANSMUTE" #define XATTR_SMACK_MMAP "SMACK64MMAP" #define XATTR_NAME_SMACK XATTR_SECURITY_PREFIX XATTR_SMACK_SUFFIX #define XATTR_NAME_SMACKIPIN XATTR_SECURITY_PREFIX XATTR_SMACK_IPIN #define XATTR_NAME_SMACKIPOUT XATTR_SECURITY_PREFIX XATTR_SMACK_IPOUT #define XATTR_NAME_SMACKEXEC XATTR_SECURITY_PREFIX XATTR_SMACK_EXEC #define XATTR_NAME_SMACKTRANSMUTE XATTR_SECURITY_PREFIX XATTR_SMACK_TRANSMUTE #define XATTR_NAME_SMACKMMAP XATTR_SECURITY_PREFIX XATTR_SMACK_MMAP #define XATTR_APPARMOR_SUFFIX "apparmor" #define XATTR_NAME_APPARMOR XATTR_SECURITY_PREFIX XATTR_APPARMOR_SUFFIX #define XATTR_CAPS_SUFFIX "capability" #define XATTR_NAME_CAPS XATTR_SECURITY_PREFIX XATTR_CAPS_SUFFIX #define XATTR_POSIX_ACL_ACCESS "posix_acl_access" #define XATTR_NAME_POSIX_ACL_ACCESS XATTR_SYSTEM_PREFIX XATTR_POSIX_ACL_ACCESS #define XATTR_POSIX_ACL_DEFAULT "posix_acl_default" #define XATTR_NAME_POSIX_ACL_DEFAULT XATTR_SYSTEM_PREFIX XATTR_POSIX_ACL_DEFAULT #endif /* _LINUX_XATTR_H */ linux/mmtimer.h000064400000004105151027430560007531 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Intel Multimedia Timer device interface * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (c) 2001-2004 Silicon Graphics, Inc. All rights reserved. * * This file should define an interface compatible with the IA-PC Multimedia * Timers Draft Specification (rev. 0.97) from Intel. Note that some * hardware may not be able to safely export its registers to userspace, * so the ioctl interface should support all necessary functionality. * * 11/01/01 - jbarnes - initial revision * 9/10/04 - Christoph Lameter - remove interrupt support * 9/17/04 - jbarnes - remove test program, move some #defines to the driver */ #ifndef _LINUX_MMTIMER_H #define _LINUX_MMTIMER_H /* * Breakdown of the ioctl's available. An 'optional' next to the command * indicates that supporting this command is optional, while 'required' * commands must be implemented if conformance is desired. * * MMTIMER_GETOFFSET - optional * Should return the offset (relative to the start of the page where the * registers are mapped) for the counter in question. * * MMTIMER_GETRES - required * The resolution of the clock in femto (10^-15) seconds * * MMTIMER_GETFREQ - required * Frequency of the clock in Hz * * MMTIMER_GETBITS - required * Number of bits in the clock's counter * * MMTIMER_MMAPAVAIL - required * Returns nonzero if the registers can be mmap'd into userspace, 0 otherwise * * MMTIMER_GETCOUNTER - required * Gets the current value in the counter */ #define MMTIMER_IOCTL_BASE 'm' #define MMTIMER_GETOFFSET _IO(MMTIMER_IOCTL_BASE, 0) #define MMTIMER_GETRES _IOR(MMTIMER_IOCTL_BASE, 1, unsigned long) #define MMTIMER_GETFREQ _IOR(MMTIMER_IOCTL_BASE, 2, unsigned long) #define MMTIMER_GETBITS _IO(MMTIMER_IOCTL_BASE, 4) #define MMTIMER_MMAPAVAIL _IO(MMTIMER_IOCTL_BASE, 6) #define MMTIMER_GETCOUNTER _IOR(MMTIMER_IOCTL_BASE, 9, unsigned long) #endif /* _LINUX_MMTIMER_H */ linux/hw_breakpoint.h000064400000001346151027430560010717 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_HW_BREAKPOINT_H #define _LINUX_HW_BREAKPOINT_H enum { HW_BREAKPOINT_LEN_1 = 1, HW_BREAKPOINT_LEN_2 = 2, HW_BREAKPOINT_LEN_3 = 3, HW_BREAKPOINT_LEN_4 = 4, HW_BREAKPOINT_LEN_5 = 5, HW_BREAKPOINT_LEN_6 = 6, HW_BREAKPOINT_LEN_7 = 7, HW_BREAKPOINT_LEN_8 = 8, }; enum { HW_BREAKPOINT_EMPTY = 0, HW_BREAKPOINT_R = 1, HW_BREAKPOINT_W = 2, HW_BREAKPOINT_RW = HW_BREAKPOINT_R | HW_BREAKPOINT_W, HW_BREAKPOINT_X = 4, HW_BREAKPOINT_INVALID = HW_BREAKPOINT_RW | HW_BREAKPOINT_X, }; enum bp_type_idx { TYPE_INST = 0, #ifdef CONFIG_HAVE_MIXED_BREAKPOINTS_REGS TYPE_DATA = 0, #else TYPE_DATA = 1, #endif TYPE_MAX }; #endif /* _LINUX_HW_BREAKPOINT_H */ linux/hid.h000064400000003555151027430560006633 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 1999 Andreas Gal * Copyright (c) 2000-2001 Vojtech Pavlik * Copyright (c) 2006-2007 Jiri Kosina */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Should you need to contact me, the author, you can do so either by * e-mail - mail your message to , or by paper mail: * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic */ #ifndef __HID_H #define __HID_H /* * USB HID (Human Interface Device) interface class code */ #define USB_INTERFACE_CLASS_HID 3 /* * USB HID interface subclass and protocol codes */ #define USB_INTERFACE_SUBCLASS_BOOT 1 #define USB_INTERFACE_PROTOCOL_KEYBOARD 1 #define USB_INTERFACE_PROTOCOL_MOUSE 2 /* * HID class requests */ #define HID_REQ_GET_REPORT 0x01 #define HID_REQ_GET_IDLE 0x02 #define HID_REQ_GET_PROTOCOL 0x03 #define HID_REQ_SET_REPORT 0x09 #define HID_REQ_SET_IDLE 0x0A #define HID_REQ_SET_PROTOCOL 0x0B /* * HID class descriptor types */ #define HID_DT_HID (USB_TYPE_CLASS | 0x01) #define HID_DT_REPORT (USB_TYPE_CLASS | 0x02) #define HID_DT_PHYSICAL (USB_TYPE_CLASS | 0x03) #define HID_MAX_DESCRIPTOR_SIZE 4096 #endif /* __HID_H */ linux/kernel.h000064400000000666151027430560007347 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_KERNEL_H #define _LINUX_KERNEL_H #include /* * 'kernel.h' contains some often-used function prototypes etc */ #define __ALIGN_KERNEL(x, a) __ALIGN_KERNEL_MASK(x, (typeof(x))(a) - 1) #define __ALIGN_KERNEL_MASK(x, mask) (((x) + (mask)) & ~(mask)) #define __KERNEL_DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) #endif /* _LINUX_KERNEL_H */ linux/ethtool.h000064400000243617151027430560007552 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ethtool.h: Defines for Linux ethtool. * * Copyright (C) 1998 David S. Miller (davem@redhat.com) * Copyright 2001 Jeff Garzik * Portions Copyright 2001 Sun Microsystems (thockin@sun.com) * Portions Copyright 2002 Intel (eli.kupermann@intel.com, * christopher.leech@intel.com, * scott.feldman@intel.com) * Portions Copyright (C) Sun Microsystems 2008 */ #ifndef _LINUX_ETHTOOL_H #define _LINUX_ETHTOOL_H #include #include #include #include /* for INT_MAX */ /* All structures exposed to userland should be defined such that they * have the same layout for 32-bit and 64-bit userland. */ /* Note on reserved space. * Reserved fields must not be accessed directly by user space because * they may be replaced by a different field in the future. They must * be initialized to zero before making the request, e.g. via memset * of the entire structure or implicitly by not being set in a structure * initializer. */ /** * struct ethtool_cmd - DEPRECATED, link control and status * This structure is DEPRECATED, please use struct ethtool_link_settings. * @cmd: Command number = %ETHTOOL_GSET or %ETHTOOL_SSET * @supported: Bitmask of %SUPPORTED_* flags for the link modes, * physical connectors and other link features for which the * interface supports autonegotiation or auto-detection. * Read-only. * @advertising: Bitmask of %ADVERTISED_* flags for the link modes, * physical connectors and other link features that are * advertised through autonegotiation or enabled for * auto-detection. * @speed: Low bits of the speed, 1Mb units, 0 to INT_MAX or SPEED_UNKNOWN * @duplex: Duplex mode; one of %DUPLEX_* * @port: Physical connector type; one of %PORT_* * @phy_address: MDIO address of PHY (transceiver); 0 or 255 if not * applicable. For clause 45 PHYs this is the PRTAD. * @transceiver: Historically used to distinguish different possible * PHY types, but not in a consistent way. Deprecated. * @autoneg: Enable/disable autonegotiation and auto-detection; * either %AUTONEG_DISABLE or %AUTONEG_ENABLE * @mdio_support: Bitmask of %ETH_MDIO_SUPPORTS_* flags for the MDIO * protocols supported by the interface; 0 if unknown. * Read-only. * @maxtxpkt: Historically used to report TX IRQ coalescing; now * obsoleted by &struct ethtool_coalesce. Read-only; deprecated. * @maxrxpkt: Historically used to report RX IRQ coalescing; now * obsoleted by &struct ethtool_coalesce. Read-only; deprecated. * @speed_hi: High bits of the speed, 1Mb units, 0 to INT_MAX or SPEED_UNKNOWN * @eth_tp_mdix: Ethernet twisted-pair MDI(-X) status; one of * %ETH_TP_MDI_*. If the status is unknown or not applicable, the * value will be %ETH_TP_MDI_INVALID. Read-only. * @eth_tp_mdix_ctrl: Ethernet twisted pair MDI(-X) control; one of * %ETH_TP_MDI_*. If MDI(-X) control is not implemented, reads * yield %ETH_TP_MDI_INVALID and writes may be ignored or rejected. * When written successfully, the link should be renegotiated if * necessary. * @lp_advertising: Bitmask of %ADVERTISED_* flags for the link modes * and other link features that the link partner advertised * through autonegotiation; 0 if unknown or not applicable. * Read-only. * @reserved: Reserved for future use; see the note on reserved space. * * The link speed in Mbps is split between @speed and @speed_hi. Use * the ethtool_cmd_speed() and ethtool_cmd_speed_set() functions to * access it. * * If autonegotiation is disabled, the speed and @duplex represent the * fixed link mode and are writable if the driver supports multiple * link modes. If it is enabled then they are read-only; if the link * is up they represent the negotiated link mode; if the link is down, * the speed is 0, %SPEED_UNKNOWN or the highest enabled speed and * @duplex is %DUPLEX_UNKNOWN or the best enabled duplex mode. * * Some hardware interfaces may have multiple PHYs and/or physical * connectors fitted or do not allow the driver to detect which are * fitted. For these interfaces @port and/or @phy_address may be * writable, possibly dependent on @autoneg being %AUTONEG_DISABLE. * Otherwise, attempts to write different values may be ignored or * rejected. * * Users should assume that all fields not marked read-only are * writable and subject to validation by the driver. They should use * %ETHTOOL_GSET to get the current values before making specific * changes and then applying them with %ETHTOOL_SSET. * * Drivers that implement set_settings() should validate all fields * other than @cmd that are not described as read-only or deprecated, * and must ignore all fields described as read-only. * * Deprecated fields should be ignored by both users and drivers. */ struct ethtool_cmd { __u32 cmd; __u32 supported; __u32 advertising; __u16 speed; __u8 duplex; __u8 port; __u8 phy_address; __u8 transceiver; __u8 autoneg; __u8 mdio_support; __u32 maxtxpkt; __u32 maxrxpkt; __u16 speed_hi; __u8 eth_tp_mdix; __u8 eth_tp_mdix_ctrl; __u32 lp_advertising; __u32 reserved[2]; }; static __inline__ void ethtool_cmd_speed_set(struct ethtool_cmd *ep, __u32 speed) { ep->speed = (__u16)(speed & 0xFFFF); ep->speed_hi = (__u16)(speed >> 16); } static __inline__ __u32 ethtool_cmd_speed(const struct ethtool_cmd *ep) { return (ep->speed_hi << 16) | ep->speed; } /* Device supports clause 22 register access to PHY or peripherals * using the interface defined in . This should not be * set if there are known to be no such peripherals present or if * the driver only emulates clause 22 registers for compatibility. */ #define ETH_MDIO_SUPPORTS_C22 1 /* Device supports clause 45 register access to PHY or peripherals * using the interface defined in and . * This should not be set if there are known to be no such peripherals * present. */ #define ETH_MDIO_SUPPORTS_C45 2 #define ETHTOOL_FWVERS_LEN 32 #define ETHTOOL_BUSINFO_LEN 32 #define ETHTOOL_EROMVERS_LEN 32 /** * struct ethtool_drvinfo - general driver and device information * @cmd: Command number = %ETHTOOL_GDRVINFO * @driver: Driver short name. This should normally match the name * in its bus driver structure (e.g. pci_driver::name). Must * not be an empty string. * @version: Driver version string; may be an empty string * @fw_version: Firmware version string; may be an empty string * @erom_version: Expansion ROM version string; may be an empty string * @bus_info: Device bus address. This should match the dev_name() * string for the underlying bus device, if there is one. May be * an empty string. * @reserved2: Reserved for future use; see the note on reserved space. * @n_priv_flags: Number of flags valid for %ETHTOOL_GPFLAGS and * %ETHTOOL_SPFLAGS commands; also the number of strings in the * %ETH_SS_PRIV_FLAGS set * @n_stats: Number of u64 statistics returned by the %ETHTOOL_GSTATS * command; also the number of strings in the %ETH_SS_STATS set * @testinfo_len: Number of results returned by the %ETHTOOL_TEST * command; also the number of strings in the %ETH_SS_TEST set * @eedump_len: Size of EEPROM accessible through the %ETHTOOL_GEEPROM * and %ETHTOOL_SEEPROM commands, in bytes * @regdump_len: Size of register dump returned by the %ETHTOOL_GREGS * command, in bytes * * Users can use the %ETHTOOL_GSSET_INFO command to get the number of * strings in any string set (from Linux 2.6.34). * * Drivers should set at most @driver, @version, @fw_version and * @bus_info in their get_drvinfo() implementation. The ethtool * core fills in the other fields using other driver operations. */ struct ethtool_drvinfo { __u32 cmd; char driver[32]; char version[32]; char fw_version[ETHTOOL_FWVERS_LEN]; char bus_info[ETHTOOL_BUSINFO_LEN]; char erom_version[ETHTOOL_EROMVERS_LEN]; char reserved2[12]; __u32 n_priv_flags; __u32 n_stats; __u32 testinfo_len; __u32 eedump_len; __u32 regdump_len; }; #define SOPASS_MAX 6 /** * struct ethtool_wolinfo - Wake-On-Lan configuration * @cmd: Command number = %ETHTOOL_GWOL or %ETHTOOL_SWOL * @supported: Bitmask of %WAKE_* flags for supported Wake-On-Lan modes. * Read-only. * @wolopts: Bitmask of %WAKE_* flags for enabled Wake-On-Lan modes. * @sopass: SecureOn(tm) password; meaningful only if %WAKE_MAGICSECURE * is set in @wolopts. */ struct ethtool_wolinfo { __u32 cmd; __u32 supported; __u32 wolopts; __u8 sopass[SOPASS_MAX]; }; /* for passing single values */ struct ethtool_value { __u32 cmd; __u32 data; }; #define PFC_STORM_PREVENTION_AUTO 0xffff #define PFC_STORM_PREVENTION_DISABLE 0 enum tunable_id { ETHTOOL_ID_UNSPEC, ETHTOOL_RX_COPYBREAK, ETHTOOL_TX_COPYBREAK, ETHTOOL_PFC_PREVENTION_TOUT, /* timeout in msecs */ ETHTOOL_TX_COPYBREAK_BUF_SIZE, /* * Add your fresh new tunable attribute above and remember to update * tunable_strings[] in net/ethtool/common.c */ __ETHTOOL_TUNABLE_COUNT, }; enum tunable_type_id { ETHTOOL_TUNABLE_UNSPEC, ETHTOOL_TUNABLE_U8, ETHTOOL_TUNABLE_U16, ETHTOOL_TUNABLE_U32, ETHTOOL_TUNABLE_U64, ETHTOOL_TUNABLE_STRING, ETHTOOL_TUNABLE_S8, ETHTOOL_TUNABLE_S16, ETHTOOL_TUNABLE_S32, ETHTOOL_TUNABLE_S64, }; struct ethtool_tunable { __u32 cmd; __u32 id; __u32 type_id; __u32 len; void *data[0]; }; #define DOWNSHIFT_DEV_DEFAULT_COUNT 0xff #define DOWNSHIFT_DEV_DISABLE 0 /* Time in msecs after which link is reported as down * 0 = lowest time supported by the PHY * 0xff = off, link down detection according to standard */ #define ETHTOOL_PHY_FAST_LINK_DOWN_ON 0 #define ETHTOOL_PHY_FAST_LINK_DOWN_OFF 0xff /* Energy Detect Power Down (EDPD) is a feature supported by some PHYs, where * the PHY's RX & TX blocks are put into a low-power mode when there is no * link detected (typically cable is un-plugged). For RX, only a minimal * link-detection is available, and for TX the PHY wakes up to send link pulses * to avoid any lock-ups in case the peer PHY may also be running in EDPD mode. * * Some PHYs may support configuration of the wake-up interval for TX pulses, * and some PHYs may support only disabling TX pulses entirely. For the latter * a special value is required (ETHTOOL_PHY_EDPD_NO_TX) so that this can be * configured from userspace (should the user want it). * * The interval units for TX wake-up are in milliseconds, since this should * cover a reasonable range of intervals: * - from 1 millisecond, which does not sound like much of a power-saver * - to ~65 seconds which is quite a lot to wait for a link to come up when * plugging a cable */ #define ETHTOOL_PHY_EDPD_DFLT_TX_MSECS 0xffff #define ETHTOOL_PHY_EDPD_NO_TX 0xfffe #define ETHTOOL_PHY_EDPD_DISABLE 0 enum phy_tunable_id { ETHTOOL_PHY_ID_UNSPEC, ETHTOOL_PHY_DOWNSHIFT, ETHTOOL_PHY_FAST_LINK_DOWN, ETHTOOL_PHY_EDPD, /* * Add your fresh new phy tunable attribute above and remember to update * phy_tunable_strings[] in net/ethtool/common.c */ __ETHTOOL_PHY_TUNABLE_COUNT, }; /** * struct ethtool_regs - hardware register dump * @cmd: Command number = %ETHTOOL_GREGS * @version: Dump format version. This is driver-specific and may * distinguish different chips/revisions. Drivers must use new * version numbers whenever the dump format changes in an * incompatible way. * @len: On entry, the real length of @data. On return, the number of * bytes used. * @data: Buffer for the register dump * * Users should use %ETHTOOL_GDRVINFO to find the maximum length of * a register dump for the interface. They must allocate the buffer * immediately following this structure. */ struct ethtool_regs { __u32 cmd; __u32 version; __u32 len; __u8 data[0]; }; /** * struct ethtool_eeprom - EEPROM dump * @cmd: Command number = %ETHTOOL_GEEPROM, %ETHTOOL_GMODULEEEPROM or * %ETHTOOL_SEEPROM * @magic: A 'magic cookie' value to guard against accidental changes. * The value passed in to %ETHTOOL_SEEPROM must match the value * returned by %ETHTOOL_GEEPROM for the same device. This is * unused when @cmd is %ETHTOOL_GMODULEEEPROM. * @offset: Offset within the EEPROM to begin reading/writing, in bytes * @len: On entry, number of bytes to read/write. On successful * return, number of bytes actually read/written. In case of * error, this may indicate at what point the error occurred. * @data: Buffer to read/write from * * Users may use %ETHTOOL_GDRVINFO or %ETHTOOL_GMODULEINFO to find * the length of an on-board or module EEPROM, respectively. They * must allocate the buffer immediately following this structure. */ struct ethtool_eeprom { __u32 cmd; __u32 magic; __u32 offset; __u32 len; __u8 data[0]; }; /** * struct ethtool_eee - Energy Efficient Ethernet information * @cmd: ETHTOOL_{G,S}EEE * @supported: Mask of %SUPPORTED_* flags for the speed/duplex combinations * for which there is EEE support. * @advertised: Mask of %ADVERTISED_* flags for the speed/duplex combinations * advertised as eee capable. * @lp_advertised: Mask of %ADVERTISED_* flags for the speed/duplex * combinations advertised by the link partner as eee capable. * @eee_active: Result of the eee auto negotiation. * @eee_enabled: EEE configured mode (enabled/disabled). * @tx_lpi_enabled: Whether the interface should assert its tx lpi, given * that eee was negotiated. * @tx_lpi_timer: Time in microseconds the interface delays prior to asserting * its tx lpi (after reaching 'idle' state). Effective only when eee * was negotiated and tx_lpi_enabled was set. * @reserved: Reserved for future use; see the note on reserved space. */ struct ethtool_eee { __u32 cmd; __u32 supported; __u32 advertised; __u32 lp_advertised; __u32 eee_active; __u32 eee_enabled; __u32 tx_lpi_enabled; __u32 tx_lpi_timer; __u32 reserved[2]; }; /** * struct ethtool_modinfo - plugin module eeprom information * @cmd: %ETHTOOL_GMODULEINFO * @type: Standard the module information conforms to %ETH_MODULE_SFF_xxxx * @eeprom_len: Length of the eeprom * @reserved: Reserved for future use; see the note on reserved space. * * This structure is used to return the information to * properly size memory for a subsequent call to %ETHTOOL_GMODULEEEPROM. * The type code indicates the eeprom data format */ struct ethtool_modinfo { __u32 cmd; __u32 type; __u32 eeprom_len; __u32 reserved[8]; }; /** * struct ethtool_coalesce - coalescing parameters for IRQs and stats updates * @cmd: ETHTOOL_{G,S}COALESCE * @rx_coalesce_usecs: How many usecs to delay an RX interrupt after * a packet arrives. * @rx_max_coalesced_frames: Maximum number of packets to receive * before an RX interrupt. * @rx_coalesce_usecs_irq: Same as @rx_coalesce_usecs, except that * this value applies while an IRQ is being serviced by the host. * @rx_max_coalesced_frames_irq: Same as @rx_max_coalesced_frames, * except that this value applies while an IRQ is being serviced * by the host. * @tx_coalesce_usecs: How many usecs to delay a TX interrupt after * a packet is sent. * @tx_max_coalesced_frames: Maximum number of packets to be sent * before a TX interrupt. * @tx_coalesce_usecs_irq: Same as @tx_coalesce_usecs, except that * this value applies while an IRQ is being serviced by the host. * @tx_max_coalesced_frames_irq: Same as @tx_max_coalesced_frames, * except that this value applies while an IRQ is being serviced * by the host. * @stats_block_coalesce_usecs: How many usecs to delay in-memory * statistics block updates. Some drivers do not have an * in-memory statistic block, and in such cases this value is * ignored. This value must not be zero. * @use_adaptive_rx_coalesce: Enable adaptive RX coalescing. * @use_adaptive_tx_coalesce: Enable adaptive TX coalescing. * @pkt_rate_low: Threshold for low packet rate (packets per second). * @rx_coalesce_usecs_low: How many usecs to delay an RX interrupt after * a packet arrives, when the packet rate is below @pkt_rate_low. * @rx_max_coalesced_frames_low: Maximum number of packets to be received * before an RX interrupt, when the packet rate is below @pkt_rate_low. * @tx_coalesce_usecs_low: How many usecs to delay a TX interrupt after * a packet is sent, when the packet rate is below @pkt_rate_low. * @tx_max_coalesced_frames_low: Maximum nuumber of packets to be sent before * a TX interrupt, when the packet rate is below @pkt_rate_low. * @pkt_rate_high: Threshold for high packet rate (packets per second). * @rx_coalesce_usecs_high: How many usecs to delay an RX interrupt after * a packet arrives, when the packet rate is above @pkt_rate_high. * @rx_max_coalesced_frames_high: Maximum number of packets to be received * before an RX interrupt, when the packet rate is above @pkt_rate_high. * @tx_coalesce_usecs_high: How many usecs to delay a TX interrupt after * a packet is sent, when the packet rate is above @pkt_rate_high. * @tx_max_coalesced_frames_high: Maximum number of packets to be sent before * a TX interrupt, when the packet rate is above @pkt_rate_high. * @rate_sample_interval: How often to do adaptive coalescing packet rate * sampling, measured in seconds. Must not be zero. * * Each pair of (usecs, max_frames) fields specifies that interrupts * should be coalesced until * (usecs > 0 && time_since_first_completion >= usecs) || * (max_frames > 0 && completed_frames >= max_frames) * * It is illegal to set both usecs and max_frames to zero as this * would cause interrupts to never be generated. To disable * coalescing, set usecs = 0 and max_frames = 1. * * Some implementations ignore the value of max_frames and use the * condition time_since_first_completion >= usecs * * This is deprecated. Drivers for hardware that does not support * counting completions should validate that max_frames == !rx_usecs. * * Adaptive RX/TX coalescing is an algorithm implemented by some * drivers to improve latency under low packet rates and improve * throughput under high packet rates. Some drivers only implement * one of RX or TX adaptive coalescing. Anything not implemented by * the driver causes these values to be silently ignored. * * When the packet rate is below @pkt_rate_high but above * @pkt_rate_low (both measured in packets per second) the * normal {rx,tx}_* coalescing parameters are used. */ struct ethtool_coalesce { __u32 cmd; __u32 rx_coalesce_usecs; __u32 rx_max_coalesced_frames; __u32 rx_coalesce_usecs_irq; __u32 rx_max_coalesced_frames_irq; __u32 tx_coalesce_usecs; __u32 tx_max_coalesced_frames; __u32 tx_coalesce_usecs_irq; __u32 tx_max_coalesced_frames_irq; __u32 stats_block_coalesce_usecs; __u32 use_adaptive_rx_coalesce; __u32 use_adaptive_tx_coalesce; __u32 pkt_rate_low; __u32 rx_coalesce_usecs_low; __u32 rx_max_coalesced_frames_low; __u32 tx_coalesce_usecs_low; __u32 tx_max_coalesced_frames_low; __u32 pkt_rate_high; __u32 rx_coalesce_usecs_high; __u32 rx_max_coalesced_frames_high; __u32 tx_coalesce_usecs_high; __u32 tx_max_coalesced_frames_high; __u32 rate_sample_interval; }; /** * struct ethtool_ringparam - RX/TX ring parameters * @cmd: Command number = %ETHTOOL_GRINGPARAM or %ETHTOOL_SRINGPARAM * @rx_max_pending: Maximum supported number of pending entries per * RX ring. Read-only. * @rx_mini_max_pending: Maximum supported number of pending entries * per RX mini ring. Read-only. * @rx_jumbo_max_pending: Maximum supported number of pending entries * per RX jumbo ring. Read-only. * @tx_max_pending: Maximum supported number of pending entries per * TX ring. Read-only. * @rx_pending: Current maximum number of pending entries per RX ring * @rx_mini_pending: Current maximum number of pending entries per RX * mini ring * @rx_jumbo_pending: Current maximum number of pending entries per RX * jumbo ring * @tx_pending: Current maximum supported number of pending entries * per TX ring * * If the interface does not have separate RX mini and/or jumbo rings, * @rx_mini_max_pending and/or @rx_jumbo_max_pending will be 0. * * There may also be driver-dependent minimum values for the number * of entries per ring. */ struct ethtool_ringparam { __u32 cmd; __u32 rx_max_pending; __u32 rx_mini_max_pending; __u32 rx_jumbo_max_pending; __u32 tx_max_pending; __u32 rx_pending; __u32 rx_mini_pending; __u32 rx_jumbo_pending; __u32 tx_pending; }; /** * struct ethtool_channels - configuring number of network channel * @cmd: ETHTOOL_{G,S}CHANNELS * @max_rx: Read only. Maximum number of receive channel the driver support. * @max_tx: Read only. Maximum number of transmit channel the driver support. * @max_other: Read only. Maximum number of other channel the driver support. * @max_combined: Read only. Maximum number of combined channel the driver * support. Set of queues RX, TX or other. * @rx_count: Valid values are in the range 1 to the max_rx. * @tx_count: Valid values are in the range 1 to the max_tx. * @other_count: Valid values are in the range 1 to the max_other. * @combined_count: Valid values are in the range 1 to the max_combined. * * This can be used to configure RX, TX and other channels. */ struct ethtool_channels { __u32 cmd; __u32 max_rx; __u32 max_tx; __u32 max_other; __u32 max_combined; __u32 rx_count; __u32 tx_count; __u32 other_count; __u32 combined_count; }; /** * struct ethtool_pauseparam - Ethernet pause (flow control) parameters * @cmd: Command number = %ETHTOOL_GPAUSEPARAM or %ETHTOOL_SPAUSEPARAM * @autoneg: Flag to enable autonegotiation of pause frame use * @rx_pause: Flag to enable reception of pause frames * @tx_pause: Flag to enable transmission of pause frames * * Drivers should reject a non-zero setting of @autoneg when * autoneogotiation is disabled (or not supported) for the link. * * If the link is autonegotiated, drivers should use * mii_advertise_flowctrl() or similar code to set the advertised * pause frame capabilities based on the @rx_pause and @tx_pause flags, * even if @autoneg is zero. They should also allow the advertised * pause frame capabilities to be controlled directly through the * advertising field of &struct ethtool_cmd. * * If @autoneg is non-zero, the MAC is configured to send and/or * receive pause frames according to the result of autonegotiation. * Otherwise, it is configured directly based on the @rx_pause and * @tx_pause flags. */ struct ethtool_pauseparam { __u32 cmd; __u32 autoneg; __u32 rx_pause; __u32 tx_pause; }; /* Link extended state */ enum ethtool_link_ext_state { ETHTOOL_LINK_EXT_STATE_AUTONEG, ETHTOOL_LINK_EXT_STATE_LINK_TRAINING_FAILURE, ETHTOOL_LINK_EXT_STATE_LINK_LOGICAL_MISMATCH, ETHTOOL_LINK_EXT_STATE_BAD_SIGNAL_INTEGRITY, ETHTOOL_LINK_EXT_STATE_NO_CABLE, ETHTOOL_LINK_EXT_STATE_CABLE_ISSUE, ETHTOOL_LINK_EXT_STATE_EEPROM_ISSUE, ETHTOOL_LINK_EXT_STATE_CALIBRATION_FAILURE, ETHTOOL_LINK_EXT_STATE_POWER_BUDGET_EXCEEDED, ETHTOOL_LINK_EXT_STATE_OVERHEAT, ETHTOOL_LINK_EXT_STATE_MODULE, }; /* More information in addition to ETHTOOL_LINK_EXT_STATE_AUTONEG. */ enum ethtool_link_ext_substate_autoneg { ETHTOOL_LINK_EXT_SUBSTATE_AN_NO_PARTNER_DETECTED = 1, ETHTOOL_LINK_EXT_SUBSTATE_AN_ACK_NOT_RECEIVED, ETHTOOL_LINK_EXT_SUBSTATE_AN_NEXT_PAGE_EXCHANGE_FAILED, ETHTOOL_LINK_EXT_SUBSTATE_AN_NO_PARTNER_DETECTED_FORCE_MODE, ETHTOOL_LINK_EXT_SUBSTATE_AN_FEC_MISMATCH_DURING_OVERRIDE, ETHTOOL_LINK_EXT_SUBSTATE_AN_NO_HCD, }; /* More information in addition to ETHTOOL_LINK_EXT_STATE_LINK_TRAINING_FAILURE. */ enum ethtool_link_ext_substate_link_training { ETHTOOL_LINK_EXT_SUBSTATE_LT_KR_FRAME_LOCK_NOT_ACQUIRED = 1, ETHTOOL_LINK_EXT_SUBSTATE_LT_KR_LINK_INHIBIT_TIMEOUT, ETHTOOL_LINK_EXT_SUBSTATE_LT_KR_LINK_PARTNER_DID_NOT_SET_RECEIVER_READY, ETHTOOL_LINK_EXT_SUBSTATE_LT_REMOTE_FAULT, }; /* More information in addition to ETHTOOL_LINK_EXT_STATE_LINK_LOGICAL_MISMATCH. */ enum ethtool_link_ext_substate_link_logical_mismatch { ETHTOOL_LINK_EXT_SUBSTATE_LLM_PCS_DID_NOT_ACQUIRE_BLOCK_LOCK = 1, ETHTOOL_LINK_EXT_SUBSTATE_LLM_PCS_DID_NOT_ACQUIRE_AM_LOCK, ETHTOOL_LINK_EXT_SUBSTATE_LLM_PCS_DID_NOT_GET_ALIGN_STATUS, ETHTOOL_LINK_EXT_SUBSTATE_LLM_FC_FEC_IS_NOT_LOCKED, ETHTOOL_LINK_EXT_SUBSTATE_LLM_RS_FEC_IS_NOT_LOCKED, }; /* More information in addition to ETHTOOL_LINK_EXT_STATE_BAD_SIGNAL_INTEGRITY. */ enum ethtool_link_ext_substate_bad_signal_integrity { ETHTOOL_LINK_EXT_SUBSTATE_BSI_LARGE_NUMBER_OF_PHYSICAL_ERRORS = 1, ETHTOOL_LINK_EXT_SUBSTATE_BSI_UNSUPPORTED_RATE, }; /* More information in addition to ETHTOOL_LINK_EXT_STATE_CABLE_ISSUE. */ enum ethtool_link_ext_substate_cable_issue { ETHTOOL_LINK_EXT_SUBSTATE_CI_UNSUPPORTED_CABLE = 1, ETHTOOL_LINK_EXT_SUBSTATE_CI_CABLE_TEST_FAILURE, }; /* More information in addition to ETHTOOL_LINK_EXT_STATE_MODULE. */ enum ethtool_link_ext_substate_module { ETHTOOL_LINK_EXT_SUBSTATE_MODULE_CMIS_NOT_READY = 1, }; #define ETH_GSTRING_LEN 32 /** * enum ethtool_stringset - string set ID * @ETH_SS_TEST: Self-test result names, for use with %ETHTOOL_TEST * @ETH_SS_STATS: Statistic names, for use with %ETHTOOL_GSTATS * @ETH_SS_PRIV_FLAGS: Driver private flag names, for use with * %ETHTOOL_GPFLAGS and %ETHTOOL_SPFLAGS * @ETH_SS_NTUPLE_FILTERS: Previously used with %ETHTOOL_GRXNTUPLE; * now deprecated * @ETH_SS_FEATURES: Device feature names * @ETH_SS_RSS_HASH_FUNCS: RSS hush function names * @ETH_SS_TUNABLES: tunable names * @ETH_SS_PHY_STATS: Statistic names, for use with %ETHTOOL_GPHYSTATS * @ETH_SS_PHY_TUNABLES: PHY tunable names * @ETH_SS_LINK_MODES: link mode names * @ETH_SS_MSG_CLASSES: debug message class names * @ETH_SS_WOL_MODES: wake-on-lan modes * @ETH_SS_SOF_TIMESTAMPING: SOF_TIMESTAMPING_* flags * @ETH_SS_TS_TX_TYPES: timestamping Tx types * @ETH_SS_TS_RX_FILTERS: timestamping Rx filters * @ETH_SS_UDP_TUNNEL_TYPES: UDP tunnel types * @ETH_SS_STATS_STD: standardized stats * @ETH_SS_STATS_ETH_PHY: names of IEEE 802.3 PHY statistics * @ETH_SS_STATS_ETH_MAC: names of IEEE 802.3 MAC statistics * @ETH_SS_STATS_ETH_CTRL: names of IEEE 802.3 MAC Control statistics * @ETH_SS_STATS_RMON: names of RMON statistics * * @ETH_SS_COUNT: number of defined string sets */ enum ethtool_stringset { ETH_SS_TEST = 0, ETH_SS_STATS, ETH_SS_PRIV_FLAGS, ETH_SS_NTUPLE_FILTERS, ETH_SS_FEATURES, ETH_SS_RSS_HASH_FUNCS, ETH_SS_TUNABLES, ETH_SS_PHY_STATS, ETH_SS_PHY_TUNABLES, ETH_SS_LINK_MODES, ETH_SS_MSG_CLASSES, ETH_SS_WOL_MODES, ETH_SS_SOF_TIMESTAMPING, ETH_SS_TS_TX_TYPES, ETH_SS_TS_RX_FILTERS, ETH_SS_UDP_TUNNEL_TYPES, ETH_SS_STATS_STD, ETH_SS_STATS_ETH_PHY, ETH_SS_STATS_ETH_MAC, ETH_SS_STATS_ETH_CTRL, ETH_SS_STATS_RMON, /* add new constants above here */ ETH_SS_COUNT }; /** * struct ethtool_gstrings - string set for data tagging * @cmd: Command number = %ETHTOOL_GSTRINGS * @string_set: String set ID; one of &enum ethtool_stringset * @len: On return, the number of strings in the string set * @data: Buffer for strings. Each string is null-padded to a size of * %ETH_GSTRING_LEN. * * Users must use %ETHTOOL_GSSET_INFO to find the number of strings in * the string set. They must allocate a buffer of the appropriate * size immediately following this structure. */ struct ethtool_gstrings { __u32 cmd; __u32 string_set; __u32 len; __u8 data[0]; }; /** * struct ethtool_sset_info - string set information * @cmd: Command number = %ETHTOOL_GSSET_INFO * @reserved: Reserved for future use; see the note on reserved space. * @sset_mask: On entry, a bitmask of string sets to query, with bits * numbered according to &enum ethtool_stringset. On return, a * bitmask of those string sets queried that are supported. * @data: Buffer for string set sizes. On return, this contains the * size of each string set that was queried and supported, in * order of ID. * * Example: The user passes in @sset_mask = 0x7 (sets 0, 1, 2) and on * return @sset_mask == 0x6 (sets 1, 2). Then @data[0] contains the * size of set 1 and @data[1] contains the size of set 2. * * Users must allocate a buffer of the appropriate size (4 * number of * sets queried) immediately following this structure. */ struct ethtool_sset_info { __u32 cmd; __u32 reserved; __u64 sset_mask; __u32 data[0]; }; /** * enum ethtool_test_flags - flags definition of ethtool_test * @ETH_TEST_FL_OFFLINE: if set perform online and offline tests, otherwise * only online tests. * @ETH_TEST_FL_FAILED: Driver set this flag if test fails. * @ETH_TEST_FL_EXTERNAL_LB: Application request to perform external loopback * test. * @ETH_TEST_FL_EXTERNAL_LB_DONE: Driver performed the external loopback test */ enum ethtool_test_flags { ETH_TEST_FL_OFFLINE = (1 << 0), ETH_TEST_FL_FAILED = (1 << 1), ETH_TEST_FL_EXTERNAL_LB = (1 << 2), ETH_TEST_FL_EXTERNAL_LB_DONE = (1 << 3), }; /** * struct ethtool_test - device self-test invocation * @cmd: Command number = %ETHTOOL_TEST * @flags: A bitmask of flags from &enum ethtool_test_flags. Some * flags may be set by the user on entry; others may be set by * the driver on return. * @reserved: Reserved for future use; see the note on reserved space. * @len: On return, the number of test results * @data: Array of test results * * Users must use %ETHTOOL_GSSET_INFO or %ETHTOOL_GDRVINFO to find the * number of test results that will be returned. They must allocate a * buffer of the appropriate size (8 * number of results) immediately * following this structure. */ struct ethtool_test { __u32 cmd; __u32 flags; __u32 reserved; __u32 len; __u64 data[0]; }; /** * struct ethtool_stats - device-specific statistics * @cmd: Command number = %ETHTOOL_GSTATS * @n_stats: On return, the number of statistics * @data: Array of statistics * * Users must use %ETHTOOL_GSSET_INFO or %ETHTOOL_GDRVINFO to find the * number of statistics that will be returned. They must allocate a * buffer of the appropriate size (8 * number of statistics) * immediately following this structure. */ struct ethtool_stats { __u32 cmd; __u32 n_stats; __u64 data[0]; }; /** * struct ethtool_perm_addr - permanent hardware address * @cmd: Command number = %ETHTOOL_GPERMADDR * @size: On entry, the size of the buffer. On return, the size of the * address. The command fails if the buffer is too small. * @data: Buffer for the address * * Users must allocate the buffer immediately following this structure. * A buffer size of %MAX_ADDR_LEN should be sufficient for any address * type. */ struct ethtool_perm_addr { __u32 cmd; __u32 size; __u8 data[0]; }; /* boolean flags controlling per-interface behavior characteristics. * When reading, the flag indicates whether or not a certain behavior * is enabled/present. When writing, the flag indicates whether * or not the driver should turn on (set) or off (clear) a behavior. * * Some behaviors may read-only (unconditionally absent or present). * If such is the case, return EINVAL in the set-flags operation if the * flag differs from the read-only value. */ enum ethtool_flags { ETH_FLAG_TXVLAN = (1 << 7), /* TX VLAN offload enabled */ ETH_FLAG_RXVLAN = (1 << 8), /* RX VLAN offload enabled */ ETH_FLAG_LRO = (1 << 15), /* LRO is enabled */ ETH_FLAG_NTUPLE = (1 << 27), /* N-tuple filters enabled */ ETH_FLAG_RXHASH = (1 << 28), }; /* The following structures are for supporting RX network flow * classification and RX n-tuple configuration. Note, all multibyte * fields, e.g., ip4src, ip4dst, psrc, pdst, spi, etc. are expected to * be in network byte order. */ /** * struct ethtool_tcpip4_spec - flow specification for TCP/IPv4 etc. * @ip4src: Source host * @ip4dst: Destination host * @psrc: Source port * @pdst: Destination port * @tos: Type-of-service * * This can be used to specify a TCP/IPv4, UDP/IPv4 or SCTP/IPv4 flow. */ struct ethtool_tcpip4_spec { __be32 ip4src; __be32 ip4dst; __be16 psrc; __be16 pdst; __u8 tos; }; /** * struct ethtool_ah_espip4_spec - flow specification for IPsec/IPv4 * @ip4src: Source host * @ip4dst: Destination host * @spi: Security parameters index * @tos: Type-of-service * * This can be used to specify an IPsec transport or tunnel over IPv4. */ struct ethtool_ah_espip4_spec { __be32 ip4src; __be32 ip4dst; __be32 spi; __u8 tos; }; #define ETH_RX_NFC_IP4 1 /** * struct ethtool_usrip4_spec - general flow specification for IPv4 * @ip4src: Source host * @ip4dst: Destination host * @l4_4_bytes: First 4 bytes of transport (layer 4) header * @tos: Type-of-service * @ip_ver: Value must be %ETH_RX_NFC_IP4; mask must be 0 * @proto: Transport protocol number; mask must be 0 */ struct ethtool_usrip4_spec { __be32 ip4src; __be32 ip4dst; __be32 l4_4_bytes; __u8 tos; __u8 ip_ver; __u8 proto; }; /** * struct ethtool_tcpip6_spec - flow specification for TCP/IPv6 etc. * @ip6src: Source host * @ip6dst: Destination host * @psrc: Source port * @pdst: Destination port * @tclass: Traffic Class * * This can be used to specify a TCP/IPv6, UDP/IPv6 or SCTP/IPv6 flow. */ struct ethtool_tcpip6_spec { __be32 ip6src[4]; __be32 ip6dst[4]; __be16 psrc; __be16 pdst; __u8 tclass; }; /** * struct ethtool_ah_espip6_spec - flow specification for IPsec/IPv6 * @ip6src: Source host * @ip6dst: Destination host * @spi: Security parameters index * @tclass: Traffic Class * * This can be used to specify an IPsec transport or tunnel over IPv6. */ struct ethtool_ah_espip6_spec { __be32 ip6src[4]; __be32 ip6dst[4]; __be32 spi; __u8 tclass; }; /** * struct ethtool_usrip6_spec - general flow specification for IPv6 * @ip6src: Source host * @ip6dst: Destination host * @l4_4_bytes: First 4 bytes of transport (layer 4) header * @tclass: Traffic Class * @l4_proto: Transport protocol number (nexthdr after any Extension Headers) */ struct ethtool_usrip6_spec { __be32 ip6src[4]; __be32 ip6dst[4]; __be32 l4_4_bytes; __u8 tclass; __u8 l4_proto; }; union ethtool_flow_union { struct ethtool_tcpip4_spec tcp_ip4_spec; struct ethtool_tcpip4_spec udp_ip4_spec; struct ethtool_tcpip4_spec sctp_ip4_spec; struct ethtool_ah_espip4_spec ah_ip4_spec; struct ethtool_ah_espip4_spec esp_ip4_spec; struct ethtool_usrip4_spec usr_ip4_spec; struct ethtool_tcpip6_spec tcp_ip6_spec; struct ethtool_tcpip6_spec udp_ip6_spec; struct ethtool_tcpip6_spec sctp_ip6_spec; struct ethtool_ah_espip6_spec ah_ip6_spec; struct ethtool_ah_espip6_spec esp_ip6_spec; struct ethtool_usrip6_spec usr_ip6_spec; struct ethhdr ether_spec; __u8 hdata[52]; }; /** * struct ethtool_flow_ext - additional RX flow fields * @h_dest: destination MAC address * @vlan_etype: VLAN EtherType * @vlan_tci: VLAN tag control information * @data: user defined data * @padding: Reserved for future use; see the note on reserved space. * * Note, @vlan_etype, @vlan_tci, and @data are only valid if %FLOW_EXT * is set in &struct ethtool_rx_flow_spec @flow_type. * @h_dest is valid if %FLOW_MAC_EXT is set. */ struct ethtool_flow_ext { __u8 padding[2]; unsigned char h_dest[ETH_ALEN]; __be16 vlan_etype; __be16 vlan_tci; __be32 data[2]; }; /** * struct ethtool_rx_flow_spec - classification rule for RX flows * @flow_type: Type of match to perform, e.g. %TCP_V4_FLOW * @h_u: Flow fields to match (dependent on @flow_type) * @h_ext: Additional fields to match * @m_u: Masks for flow field bits to be matched * @m_ext: Masks for additional field bits to be matched * Note, all additional fields must be ignored unless @flow_type * includes the %FLOW_EXT or %FLOW_MAC_EXT flag * (see &struct ethtool_flow_ext description). * @ring_cookie: RX ring/queue index to deliver to, or %RX_CLS_FLOW_DISC * if packets should be discarded, or %RX_CLS_FLOW_WAKE if the * packets should be used for Wake-on-LAN with %WAKE_FILTER * @location: Location of rule in the table. Locations must be * numbered such that a flow matching multiple rules will be * classified according to the first (lowest numbered) rule. */ struct ethtool_rx_flow_spec { __u32 flow_type; union ethtool_flow_union h_u; struct ethtool_flow_ext h_ext; union ethtool_flow_union m_u; struct ethtool_flow_ext m_ext; __u64 ring_cookie; __u32 location; }; /* How rings are laid out when accessing virtual functions or * offloaded queues is device specific. To allow users to do flow * steering and specify these queues the ring cookie is partitioned * into a 32bit queue index with an 8 bit virtual function id. * This also leaves the 3bytes for further specifiers. It is possible * future devices may support more than 256 virtual functions if * devices start supporting PCIe w/ARI. However at the moment I * do not know of any devices that support this so I do not reserve * space for this at this time. If a future patch consumes the next * byte it should be aware of this possibility. */ #define ETHTOOL_RX_FLOW_SPEC_RING 0x00000000FFFFFFFFLL #define ETHTOOL_RX_FLOW_SPEC_RING_VF 0x000000FF00000000LL #define ETHTOOL_RX_FLOW_SPEC_RING_VF_OFF 32 static __inline__ __u64 ethtool_get_flow_spec_ring(__u64 ring_cookie) { return ETHTOOL_RX_FLOW_SPEC_RING & ring_cookie; } static __inline__ __u64 ethtool_get_flow_spec_ring_vf(__u64 ring_cookie) { return (ETHTOOL_RX_FLOW_SPEC_RING_VF & ring_cookie) >> ETHTOOL_RX_FLOW_SPEC_RING_VF_OFF; } /** * struct ethtool_rxnfc - command to get or set RX flow classification rules * @cmd: Specific command number - %ETHTOOL_GRXFH, %ETHTOOL_SRXFH, * %ETHTOOL_GRXRINGS, %ETHTOOL_GRXCLSRLCNT, %ETHTOOL_GRXCLSRULE, * %ETHTOOL_GRXCLSRLALL, %ETHTOOL_SRXCLSRLDEL or %ETHTOOL_SRXCLSRLINS * @flow_type: Type of flow to be affected, e.g. %TCP_V4_FLOW * @data: Command-dependent value * @fs: Flow classification rule * @rss_context: RSS context to be affected * @rule_cnt: Number of rules to be affected * @rule_locs: Array of used rule locations * * For %ETHTOOL_GRXFH and %ETHTOOL_SRXFH, @data is a bitmask indicating * the fields included in the flow hash, e.g. %RXH_IP_SRC. The following * structure fields must not be used, except that if @flow_type includes * the %FLOW_RSS flag, then @rss_context determines which RSS context to * act on. * * For %ETHTOOL_GRXRINGS, @data is set to the number of RX rings/queues * on return. * * For %ETHTOOL_GRXCLSRLCNT, @rule_cnt is set to the number of defined * rules on return. If @data is non-zero on return then it is the * size of the rule table, plus the flag %RX_CLS_LOC_SPECIAL if the * driver supports any special location values. If that flag is not * set in @data then special location values should not be used. * * For %ETHTOOL_GRXCLSRULE, @fs.@location specifies the location of an * existing rule on entry and @fs contains the rule on return; if * @fs.@flow_type includes the %FLOW_RSS flag, then @rss_context is * filled with the RSS context ID associated with the rule. * * For %ETHTOOL_GRXCLSRLALL, @rule_cnt specifies the array size of the * user buffer for @rule_locs on entry. On return, @data is the size * of the rule table, @rule_cnt is the number of defined rules, and * @rule_locs contains the locations of the defined rules. Drivers * must use the second parameter to get_rxnfc() instead of @rule_locs. * * For %ETHTOOL_SRXCLSRLINS, @fs specifies the rule to add or update. * @fs.@location either specifies the location to use or is a special * location value with %RX_CLS_LOC_SPECIAL flag set. On return, * @fs.@location is the actual rule location. If @fs.@flow_type * includes the %FLOW_RSS flag, @rss_context is the RSS context ID to * use for flow spreading traffic which matches this rule. The value * from the rxfh indirection table will be added to @fs.@ring_cookie * to choose which ring to deliver to. * * For %ETHTOOL_SRXCLSRLDEL, @fs.@location specifies the location of an * existing rule on entry. * * A driver supporting the special location values for * %ETHTOOL_SRXCLSRLINS may add the rule at any suitable unused * location, and may remove a rule at a later location (lower * priority) that matches exactly the same set of flows. The special * values are %RX_CLS_LOC_ANY, selecting any location; * %RX_CLS_LOC_FIRST, selecting the first suitable location (maximum * priority); and %RX_CLS_LOC_LAST, selecting the last suitable * location (minimum priority). Additional special values may be * defined in future and drivers must return -%EINVAL for any * unrecognised value. */ struct ethtool_rxnfc { __u32 cmd; __u32 flow_type; __u64 data; struct ethtool_rx_flow_spec fs; union { __u32 rule_cnt; __u32 rss_context; }; __u32 rule_locs[0]; }; /** * struct ethtool_rxfh_indir - command to get or set RX flow hash indirection * @cmd: Specific command number - %ETHTOOL_GRXFHINDIR or %ETHTOOL_SRXFHINDIR * @size: On entry, the array size of the user buffer, which may be zero. * On return from %ETHTOOL_GRXFHINDIR, the array size of the hardware * indirection table. * @ring_index: RX ring/queue index for each hash value * * For %ETHTOOL_GRXFHINDIR, a @size of zero means that only the size * should be returned. For %ETHTOOL_SRXFHINDIR, a @size of zero means * the table should be reset to default values. This last feature * is not supported by the original implementations. */ struct ethtool_rxfh_indir { __u32 cmd; __u32 size; __u32 ring_index[0]; }; /** * struct ethtool_rxfh - command to get/set RX flow hash indir or/and hash key. * @cmd: Specific command number - %ETHTOOL_GRSSH or %ETHTOOL_SRSSH * @rss_context: RSS context identifier. Context 0 is the default for normal * traffic; other contexts can be referenced as the destination for RX flow * classification rules. %ETH_RXFH_CONTEXT_ALLOC is used with command * %ETHTOOL_SRSSH to allocate a new RSS context; on return this field will * contain the ID of the newly allocated context. * @indir_size: On entry, the array size of the user buffer for the * indirection table, which may be zero, or (for %ETHTOOL_SRSSH), * %ETH_RXFH_INDIR_NO_CHANGE. On return from %ETHTOOL_GRSSH, * the array size of the hardware indirection table. * @key_size: On entry, the array size of the user buffer for the hash key, * which may be zero. On return from %ETHTOOL_GRSSH, the size of the * hardware hash key. * @hfunc: Defines the current RSS hash function used by HW (or to be set to). * Valid values are one of the %ETH_RSS_HASH_*. * @rsvd8: Reserved for future use; see the note on reserved space. * @rsvd32: Reserved for future use; see the note on reserved space. * @rss_config: RX ring/queue index for each hash value i.e., indirection table * of @indir_size __u32 elements, followed by hash key of @key_size * bytes. * * For %ETHTOOL_GRSSH, a @indir_size and key_size of zero means that only the * size should be returned. For %ETHTOOL_SRSSH, an @indir_size of * %ETH_RXFH_INDIR_NO_CHANGE means that indir table setting is not requested * and a @indir_size of zero means the indir table should be reset to default * values (if @rss_context == 0) or that the RSS context should be deleted. * An hfunc of zero means that hash function setting is not requested. */ struct ethtool_rxfh { __u32 cmd; __u32 rss_context; __u32 indir_size; __u32 key_size; __u8 hfunc; __u8 rsvd8[3]; __u32 rsvd32; __u32 rss_config[0]; }; #define ETH_RXFH_CONTEXT_ALLOC 0xffffffff #define ETH_RXFH_INDIR_NO_CHANGE 0xffffffff /** * struct ethtool_rx_ntuple_flow_spec - specification for RX flow filter * @flow_type: Type of match to perform, e.g. %TCP_V4_FLOW * @h_u: Flow field values to match (dependent on @flow_type) * @m_u: Masks for flow field value bits to be ignored * @vlan_tag: VLAN tag to match * @vlan_tag_mask: Mask for VLAN tag bits to be ignored * @data: Driver-dependent data to match * @data_mask: Mask for driver-dependent data bits to be ignored * @action: RX ring/queue index to deliver to (non-negative) or other action * (negative, e.g. %ETHTOOL_RXNTUPLE_ACTION_DROP) * * For flow types %TCP_V4_FLOW, %UDP_V4_FLOW and %SCTP_V4_FLOW, where * a field value and mask are both zero this is treated as if all mask * bits are set i.e. the field is ignored. */ struct ethtool_rx_ntuple_flow_spec { __u32 flow_type; union { struct ethtool_tcpip4_spec tcp_ip4_spec; struct ethtool_tcpip4_spec udp_ip4_spec; struct ethtool_tcpip4_spec sctp_ip4_spec; struct ethtool_ah_espip4_spec ah_ip4_spec; struct ethtool_ah_espip4_spec esp_ip4_spec; struct ethtool_usrip4_spec usr_ip4_spec; struct ethhdr ether_spec; __u8 hdata[72]; } h_u, m_u; __u16 vlan_tag; __u16 vlan_tag_mask; __u64 data; __u64 data_mask; __s32 action; #define ETHTOOL_RXNTUPLE_ACTION_DROP (-1) /* drop packet */ #define ETHTOOL_RXNTUPLE_ACTION_CLEAR (-2) /* clear filter */ }; /** * struct ethtool_rx_ntuple - command to set or clear RX flow filter * @cmd: Command number - %ETHTOOL_SRXNTUPLE * @fs: Flow filter specification */ struct ethtool_rx_ntuple { __u32 cmd; struct ethtool_rx_ntuple_flow_spec fs; }; #define ETHTOOL_FLASH_MAX_FILENAME 128 enum ethtool_flash_op_type { ETHTOOL_FLASH_ALL_REGIONS = 0, }; /* for passing firmware flashing related parameters */ struct ethtool_flash { __u32 cmd; __u32 region; char data[ETHTOOL_FLASH_MAX_FILENAME]; }; /** * struct ethtool_dump - used for retrieving, setting device dump * @cmd: Command number - %ETHTOOL_GET_DUMP_FLAG, %ETHTOOL_GET_DUMP_DATA, or * %ETHTOOL_SET_DUMP * @version: FW version of the dump, filled in by driver * @flag: driver dependent flag for dump setting, filled in by driver during * get and filled in by ethtool for set operation. * flag must be initialized by macro ETH_FW_DUMP_DISABLE value when * firmware dump is disabled. * @len: length of dump data, used as the length of the user buffer on entry to * %ETHTOOL_GET_DUMP_DATA and this is returned as dump length by driver * for %ETHTOOL_GET_DUMP_FLAG command * @data: data collected for get dump data operation */ struct ethtool_dump { __u32 cmd; __u32 version; __u32 flag; __u32 len; __u8 data[0]; }; #define ETH_FW_DUMP_DISABLE 0 /* for returning and changing feature sets */ /** * struct ethtool_get_features_block - block with state of 32 features * @available: mask of changeable features * @requested: mask of features requested to be enabled if possible * @active: mask of currently enabled features * @never_changed: mask of features not changeable for any device */ struct ethtool_get_features_block { __u32 available; __u32 requested; __u32 active; __u32 never_changed; }; /** * struct ethtool_gfeatures - command to get state of device's features * @cmd: command number = %ETHTOOL_GFEATURES * @size: On entry, the number of elements in the features[] array; * on return, the number of elements in features[] needed to hold * all features * @features: state of features */ struct ethtool_gfeatures { __u32 cmd; __u32 size; struct ethtool_get_features_block features[0]; }; /** * struct ethtool_set_features_block - block with request for 32 features * @valid: mask of features to be changed * @requested: values of features to be changed */ struct ethtool_set_features_block { __u32 valid; __u32 requested; }; /** * struct ethtool_sfeatures - command to request change in device's features * @cmd: command number = %ETHTOOL_SFEATURES * @size: array size of the features[] array * @features: feature change masks */ struct ethtool_sfeatures { __u32 cmd; __u32 size; struct ethtool_set_features_block features[0]; }; /** * struct ethtool_ts_info - holds a device's timestamping and PHC association * @cmd: command number = %ETHTOOL_GET_TS_INFO * @so_timestamping: bit mask of the sum of the supported SO_TIMESTAMPING flags * @phc_index: device index of the associated PHC, or -1 if there is none * @tx_types: bit mask of the supported hwtstamp_tx_types enumeration values * @tx_reserved: Reserved for future use; see the note on reserved space. * @rx_filters: bit mask of the supported hwtstamp_rx_filters enumeration values * @rx_reserved: Reserved for future use; see the note on reserved space. * * The bits in the 'tx_types' and 'rx_filters' fields correspond to * the 'hwtstamp_tx_types' and 'hwtstamp_rx_filters' enumeration values, * respectively. For example, if the device supports HWTSTAMP_TX_ON, * then (1 << HWTSTAMP_TX_ON) in 'tx_types' will be set. * * Drivers should only report the filters they actually support without * upscaling in the SIOCSHWTSTAMP ioctl. If the SIOCSHWSTAMP request for * HWTSTAMP_FILTER_V1_SYNC is supported by HWTSTAMP_FILTER_V1_EVENT, then the * driver should only report HWTSTAMP_FILTER_V1_EVENT in this op. */ struct ethtool_ts_info { __u32 cmd; __u32 so_timestamping; __s32 phc_index; __u32 tx_types; __u32 tx_reserved[3]; __u32 rx_filters; __u32 rx_reserved[3]; }; /* * %ETHTOOL_SFEATURES changes features present in features[].valid to the * values of corresponding bits in features[].requested. Bits in .requested * not set in .valid or not changeable are ignored. * * Returns %EINVAL when .valid contains undefined or never-changeable bits * or size is not equal to required number of features words (32-bit blocks). * Returns >= 0 if request was completed; bits set in the value mean: * %ETHTOOL_F_UNSUPPORTED - there were bits set in .valid that are not * changeable (not present in %ETHTOOL_GFEATURES' features[].available) * those bits were ignored. * %ETHTOOL_F_WISH - some or all changes requested were recorded but the * resulting state of bits masked by .valid is not equal to .requested. * Probably there are other device-specific constraints on some features * in the set. When %ETHTOOL_F_UNSUPPORTED is set, .valid is considered * here as though ignored bits were cleared. * %ETHTOOL_F_COMPAT - some or all changes requested were made by calling * compatibility functions. Requested offload state cannot be properly * managed by kernel. * * Meaning of bits in the masks are obtained by %ETHTOOL_GSSET_INFO (number of * bits in the arrays - always multiple of 32) and %ETHTOOL_GSTRINGS commands * for ETH_SS_FEATURES string set. First entry in the table corresponds to least * significant bit in features[0] fields. Empty strings mark undefined features. */ enum ethtool_sfeatures_retval_bits { ETHTOOL_F_UNSUPPORTED__BIT, ETHTOOL_F_WISH__BIT, ETHTOOL_F_COMPAT__BIT, }; #define ETHTOOL_F_UNSUPPORTED (1 << ETHTOOL_F_UNSUPPORTED__BIT) #define ETHTOOL_F_WISH (1 << ETHTOOL_F_WISH__BIT) #define ETHTOOL_F_COMPAT (1 << ETHTOOL_F_COMPAT__BIT) #define MAX_NUM_QUEUE 4096 /** * struct ethtool_per_queue_op - apply sub command to the queues in mask. * @cmd: ETHTOOL_PERQUEUE * @sub_command: the sub command which apply to each queues * @queue_mask: Bitmap of the queues which sub command apply to * @data: A complete command structure following for each of the queues addressed */ struct ethtool_per_queue_op { __u32 cmd; __u32 sub_command; __u32 queue_mask[__KERNEL_DIV_ROUND_UP(MAX_NUM_QUEUE, 32)]; char data[]; }; /** * struct ethtool_fecparam - Ethernet Forward Error Correction parameters * @cmd: Command number = %ETHTOOL_GFECPARAM or %ETHTOOL_SFECPARAM * @active_fec: FEC mode which is active on the port, single bit set, GET only. * @fec: Bitmask of configured FEC modes. * @reserved: Reserved for future extensions, ignore on GET, write 0 for SET. * * Note that @reserved was never validated on input and ethtool user space * left it uninitialized when calling SET. Hence going forward it can only be * used to return a value to userspace with GET. * * FEC modes supported by the device can be read via %ETHTOOL_GLINKSETTINGS. * FEC settings are configured by link autonegotiation whenever it's enabled. * With autoneg on %ETHTOOL_GFECPARAM can be used to read the current mode. * * When autoneg is disabled %ETHTOOL_SFECPARAM controls the FEC settings. * It is recommended that drivers only accept a single bit set in @fec. * When multiple bits are set in @fec drivers may pick mode in an implementation * dependent way. Drivers should reject mixing %ETHTOOL_FEC_AUTO_BIT with other * FEC modes, because it's unclear whether in this case other modes constrain * AUTO or are independent choices. * Drivers must reject SET requests if they support none of the requested modes. * * If device does not support FEC drivers may use %ETHTOOL_FEC_NONE instead * of returning %EOPNOTSUPP from %ETHTOOL_GFECPARAM. * * See enum ethtool_fec_config_bits for definition of valid bits for both * @fec and @active_fec. */ struct ethtool_fecparam { __u32 cmd; /* bitmask of FEC modes */ __u32 active_fec; __u32 fec; __u32 reserved; }; /** * enum ethtool_fec_config_bits - flags definition of ethtool_fec_configuration * @ETHTOOL_FEC_NONE_BIT: FEC mode configuration is not supported. Should not * be used together with other bits. GET only. * @ETHTOOL_FEC_AUTO_BIT: Select default/best FEC mode automatically, usually * based link mode and SFP parameters read from module's * EEPROM. This bit does _not_ mean autonegotiation. * @ETHTOOL_FEC_OFF_BIT: No FEC Mode * @ETHTOOL_FEC_RS_BIT: Reed-Solomon FEC Mode * @ETHTOOL_FEC_BASER_BIT: Base-R/Reed-Solomon FEC Mode * @ETHTOOL_FEC_LLRS_BIT: Low Latency Reed Solomon FEC Mode (25G/50G Ethernet * Consortium) */ enum ethtool_fec_config_bits { ETHTOOL_FEC_NONE_BIT, ETHTOOL_FEC_AUTO_BIT, ETHTOOL_FEC_OFF_BIT, ETHTOOL_FEC_RS_BIT, ETHTOOL_FEC_BASER_BIT, ETHTOOL_FEC_LLRS_BIT, }; #define ETHTOOL_FEC_NONE (1 << ETHTOOL_FEC_NONE_BIT) #define ETHTOOL_FEC_AUTO (1 << ETHTOOL_FEC_AUTO_BIT) #define ETHTOOL_FEC_OFF (1 << ETHTOOL_FEC_OFF_BIT) #define ETHTOOL_FEC_RS (1 << ETHTOOL_FEC_RS_BIT) #define ETHTOOL_FEC_BASER (1 << ETHTOOL_FEC_BASER_BIT) #define ETHTOOL_FEC_LLRS (1 << ETHTOOL_FEC_LLRS_BIT) /* CMDs currently supported */ #define ETHTOOL_GSET 0x00000001 /* DEPRECATED, Get settings. * Please use ETHTOOL_GLINKSETTINGS */ #define ETHTOOL_SSET 0x00000002 /* DEPRECATED, Set settings. * Please use ETHTOOL_SLINKSETTINGS */ #define ETHTOOL_GDRVINFO 0x00000003 /* Get driver info. */ #define ETHTOOL_GREGS 0x00000004 /* Get NIC registers. */ #define ETHTOOL_GWOL 0x00000005 /* Get wake-on-lan options. */ #define ETHTOOL_SWOL 0x00000006 /* Set wake-on-lan options. */ #define ETHTOOL_GMSGLVL 0x00000007 /* Get driver message level */ #define ETHTOOL_SMSGLVL 0x00000008 /* Set driver msg level. */ #define ETHTOOL_NWAY_RST 0x00000009 /* Restart autonegotiation. */ /* Get link status for host, i.e. whether the interface *and* the * physical port (if there is one) are up (ethtool_value). */ #define ETHTOOL_GLINK 0x0000000a #define ETHTOOL_GEEPROM 0x0000000b /* Get EEPROM data */ #define ETHTOOL_SEEPROM 0x0000000c /* Set EEPROM data. */ #define ETHTOOL_GCOALESCE 0x0000000e /* Get coalesce config */ #define ETHTOOL_SCOALESCE 0x0000000f /* Set coalesce config. */ #define ETHTOOL_GRINGPARAM 0x00000010 /* Get ring parameters */ #define ETHTOOL_SRINGPARAM 0x00000011 /* Set ring parameters. */ #define ETHTOOL_GPAUSEPARAM 0x00000012 /* Get pause parameters */ #define ETHTOOL_SPAUSEPARAM 0x00000013 /* Set pause parameters. */ #define ETHTOOL_GRXCSUM 0x00000014 /* Get RX hw csum enable (ethtool_value) */ #define ETHTOOL_SRXCSUM 0x00000015 /* Set RX hw csum enable (ethtool_value) */ #define ETHTOOL_GTXCSUM 0x00000016 /* Get TX hw csum enable (ethtool_value) */ #define ETHTOOL_STXCSUM 0x00000017 /* Set TX hw csum enable (ethtool_value) */ #define ETHTOOL_GSG 0x00000018 /* Get scatter-gather enable * (ethtool_value) */ #define ETHTOOL_SSG 0x00000019 /* Set scatter-gather enable * (ethtool_value). */ #define ETHTOOL_TEST 0x0000001a /* execute NIC self-test. */ #define ETHTOOL_GSTRINGS 0x0000001b /* get specified string set */ #define ETHTOOL_PHYS_ID 0x0000001c /* identify the NIC */ #define ETHTOOL_GSTATS 0x0000001d /* get NIC-specific statistics */ #define ETHTOOL_GTSO 0x0000001e /* Get TSO enable (ethtool_value) */ #define ETHTOOL_STSO 0x0000001f /* Set TSO enable (ethtool_value) */ #define ETHTOOL_GPERMADDR 0x00000020 /* Get permanent hardware address */ #define ETHTOOL_GUFO 0x00000021 /* Get UFO enable (ethtool_value) */ #define ETHTOOL_SUFO 0x00000022 /* Set UFO enable (ethtool_value) */ #define ETHTOOL_GGSO 0x00000023 /* Get GSO enable (ethtool_value) */ #define ETHTOOL_SGSO 0x00000024 /* Set GSO enable (ethtool_value) */ #define ETHTOOL_GFLAGS 0x00000025 /* Get flags bitmap(ethtool_value) */ #define ETHTOOL_SFLAGS 0x00000026 /* Set flags bitmap(ethtool_value) */ #define ETHTOOL_GPFLAGS 0x00000027 /* Get driver-private flags bitmap */ #define ETHTOOL_SPFLAGS 0x00000028 /* Set driver-private flags bitmap */ #define ETHTOOL_GRXFH 0x00000029 /* Get RX flow hash configuration */ #define ETHTOOL_SRXFH 0x0000002a /* Set RX flow hash configuration */ #define ETHTOOL_GGRO 0x0000002b /* Get GRO enable (ethtool_value) */ #define ETHTOOL_SGRO 0x0000002c /* Set GRO enable (ethtool_value) */ #define ETHTOOL_GRXRINGS 0x0000002d /* Get RX rings available for LB */ #define ETHTOOL_GRXCLSRLCNT 0x0000002e /* Get RX class rule count */ #define ETHTOOL_GRXCLSRULE 0x0000002f /* Get RX classification rule */ #define ETHTOOL_GRXCLSRLALL 0x00000030 /* Get all RX classification rule */ #define ETHTOOL_SRXCLSRLDEL 0x00000031 /* Delete RX classification rule */ #define ETHTOOL_SRXCLSRLINS 0x00000032 /* Insert RX classification rule */ #define ETHTOOL_FLASHDEV 0x00000033 /* Flash firmware to device */ #define ETHTOOL_RESET 0x00000034 /* Reset hardware */ #define ETHTOOL_SRXNTUPLE 0x00000035 /* Add an n-tuple filter to device */ #define ETHTOOL_GRXNTUPLE 0x00000036 /* deprecated */ #define ETHTOOL_GSSET_INFO 0x00000037 /* Get string set info */ #define ETHTOOL_GRXFHINDIR 0x00000038 /* Get RX flow hash indir'n table */ #define ETHTOOL_SRXFHINDIR 0x00000039 /* Set RX flow hash indir'n table */ #define ETHTOOL_GFEATURES 0x0000003a /* Get device offload settings */ #define ETHTOOL_SFEATURES 0x0000003b /* Change device offload settings */ #define ETHTOOL_GCHANNELS 0x0000003c /* Get no of channels */ #define ETHTOOL_SCHANNELS 0x0000003d /* Set no of channels */ #define ETHTOOL_SET_DUMP 0x0000003e /* Set dump settings */ #define ETHTOOL_GET_DUMP_FLAG 0x0000003f /* Get dump settings */ #define ETHTOOL_GET_DUMP_DATA 0x00000040 /* Get dump data */ #define ETHTOOL_GET_TS_INFO 0x00000041 /* Get time stamping and PHC info */ #define ETHTOOL_GMODULEINFO 0x00000042 /* Get plug-in module information */ #define ETHTOOL_GMODULEEEPROM 0x00000043 /* Get plug-in module eeprom */ #define ETHTOOL_GEEE 0x00000044 /* Get EEE settings */ #define ETHTOOL_SEEE 0x00000045 /* Set EEE settings */ #define ETHTOOL_GRSSH 0x00000046 /* Get RX flow hash configuration */ #define ETHTOOL_SRSSH 0x00000047 /* Set RX flow hash configuration */ #define ETHTOOL_GTUNABLE 0x00000048 /* Get tunable configuration */ #define ETHTOOL_STUNABLE 0x00000049 /* Set tunable configuration */ #define ETHTOOL_GPHYSTATS 0x0000004a /* get PHY-specific statistics */ #define ETHTOOL_PERQUEUE 0x0000004b /* Set per queue options */ #define ETHTOOL_GLINKSETTINGS 0x0000004c /* Get ethtool_link_settings */ #define ETHTOOL_SLINKSETTINGS 0x0000004d /* Set ethtool_link_settings */ #define ETHTOOL_PHY_GTUNABLE 0x0000004e /* Get PHY tunable configuration */ #define ETHTOOL_PHY_STUNABLE 0x0000004f /* Set PHY tunable configuration */ #define ETHTOOL_GFECPARAM 0x00000050 /* Get FEC settings */ #define ETHTOOL_SFECPARAM 0x00000051 /* Set FEC settings */ /* compatibility with older code */ #define SPARC_ETH_GSET ETHTOOL_GSET #define SPARC_ETH_SSET ETHTOOL_SSET /* Link mode bit indices */ enum ethtool_link_mode_bit_indices { ETHTOOL_LINK_MODE_10baseT_Half_BIT = 0, ETHTOOL_LINK_MODE_10baseT_Full_BIT = 1, ETHTOOL_LINK_MODE_100baseT_Half_BIT = 2, ETHTOOL_LINK_MODE_100baseT_Full_BIT = 3, ETHTOOL_LINK_MODE_1000baseT_Half_BIT = 4, ETHTOOL_LINK_MODE_1000baseT_Full_BIT = 5, ETHTOOL_LINK_MODE_Autoneg_BIT = 6, ETHTOOL_LINK_MODE_TP_BIT = 7, ETHTOOL_LINK_MODE_AUI_BIT = 8, ETHTOOL_LINK_MODE_MII_BIT = 9, ETHTOOL_LINK_MODE_FIBRE_BIT = 10, ETHTOOL_LINK_MODE_BNC_BIT = 11, ETHTOOL_LINK_MODE_10000baseT_Full_BIT = 12, ETHTOOL_LINK_MODE_Pause_BIT = 13, ETHTOOL_LINK_MODE_Asym_Pause_BIT = 14, ETHTOOL_LINK_MODE_2500baseX_Full_BIT = 15, ETHTOOL_LINK_MODE_Backplane_BIT = 16, ETHTOOL_LINK_MODE_1000baseKX_Full_BIT = 17, ETHTOOL_LINK_MODE_10000baseKX4_Full_BIT = 18, ETHTOOL_LINK_MODE_10000baseKR_Full_BIT = 19, ETHTOOL_LINK_MODE_10000baseR_FEC_BIT = 20, ETHTOOL_LINK_MODE_20000baseMLD2_Full_BIT = 21, ETHTOOL_LINK_MODE_20000baseKR2_Full_BIT = 22, ETHTOOL_LINK_MODE_40000baseKR4_Full_BIT = 23, ETHTOOL_LINK_MODE_40000baseCR4_Full_BIT = 24, ETHTOOL_LINK_MODE_40000baseSR4_Full_BIT = 25, ETHTOOL_LINK_MODE_40000baseLR4_Full_BIT = 26, ETHTOOL_LINK_MODE_56000baseKR4_Full_BIT = 27, ETHTOOL_LINK_MODE_56000baseCR4_Full_BIT = 28, ETHTOOL_LINK_MODE_56000baseSR4_Full_BIT = 29, ETHTOOL_LINK_MODE_56000baseLR4_Full_BIT = 30, ETHTOOL_LINK_MODE_25000baseCR_Full_BIT = 31, /* Last allowed bit for __ETHTOOL_LINK_MODE_LEGACY_MASK is bit * 31. Please do NOT define any SUPPORTED_* or ADVERTISED_* * macro for bits > 31. The only way to use indices > 31 is to * use the new ETHTOOL_GLINKSETTINGS/ETHTOOL_SLINKSETTINGS API. */ ETHTOOL_LINK_MODE_25000baseKR_Full_BIT = 32, ETHTOOL_LINK_MODE_25000baseSR_Full_BIT = 33, ETHTOOL_LINK_MODE_50000baseCR2_Full_BIT = 34, ETHTOOL_LINK_MODE_50000baseKR2_Full_BIT = 35, ETHTOOL_LINK_MODE_100000baseKR4_Full_BIT = 36, ETHTOOL_LINK_MODE_100000baseSR4_Full_BIT = 37, ETHTOOL_LINK_MODE_100000baseCR4_Full_BIT = 38, ETHTOOL_LINK_MODE_100000baseLR4_ER4_Full_BIT = 39, ETHTOOL_LINK_MODE_50000baseSR2_Full_BIT = 40, ETHTOOL_LINK_MODE_1000baseX_Full_BIT = 41, ETHTOOL_LINK_MODE_10000baseCR_Full_BIT = 42, ETHTOOL_LINK_MODE_10000baseSR_Full_BIT = 43, ETHTOOL_LINK_MODE_10000baseLR_Full_BIT = 44, ETHTOOL_LINK_MODE_10000baseLRM_Full_BIT = 45, ETHTOOL_LINK_MODE_10000baseER_Full_BIT = 46, ETHTOOL_LINK_MODE_2500baseT_Full_BIT = 47, ETHTOOL_LINK_MODE_5000baseT_Full_BIT = 48, ETHTOOL_LINK_MODE_FEC_NONE_BIT = 49, ETHTOOL_LINK_MODE_FEC_RS_BIT = 50, ETHTOOL_LINK_MODE_FEC_BASER_BIT = 51, ETHTOOL_LINK_MODE_50000baseKR_Full_BIT = 52, ETHTOOL_LINK_MODE_50000baseSR_Full_BIT = 53, ETHTOOL_LINK_MODE_50000baseCR_Full_BIT = 54, ETHTOOL_LINK_MODE_50000baseLR_ER_FR_Full_BIT = 55, ETHTOOL_LINK_MODE_50000baseDR_Full_BIT = 56, ETHTOOL_LINK_MODE_100000baseKR2_Full_BIT = 57, ETHTOOL_LINK_MODE_100000baseSR2_Full_BIT = 58, ETHTOOL_LINK_MODE_100000baseCR2_Full_BIT = 59, ETHTOOL_LINK_MODE_100000baseLR2_ER2_FR2_Full_BIT = 60, ETHTOOL_LINK_MODE_100000baseDR2_Full_BIT = 61, ETHTOOL_LINK_MODE_200000baseKR4_Full_BIT = 62, ETHTOOL_LINK_MODE_200000baseSR4_Full_BIT = 63, ETHTOOL_LINK_MODE_200000baseLR4_ER4_FR4_Full_BIT = 64, ETHTOOL_LINK_MODE_200000baseDR4_Full_BIT = 65, ETHTOOL_LINK_MODE_200000baseCR4_Full_BIT = 66, ETHTOOL_LINK_MODE_100baseT1_Full_BIT = 67, ETHTOOL_LINK_MODE_1000baseT1_Full_BIT = 68, ETHTOOL_LINK_MODE_400000baseKR8_Full_BIT = 69, ETHTOOL_LINK_MODE_400000baseSR8_Full_BIT = 70, ETHTOOL_LINK_MODE_400000baseLR8_ER8_FR8_Full_BIT = 71, ETHTOOL_LINK_MODE_400000baseDR8_Full_BIT = 72, ETHTOOL_LINK_MODE_400000baseCR8_Full_BIT = 73, ETHTOOL_LINK_MODE_FEC_LLRS_BIT = 74, ETHTOOL_LINK_MODE_100000baseKR_Full_BIT = 75, ETHTOOL_LINK_MODE_100000baseSR_Full_BIT = 76, ETHTOOL_LINK_MODE_100000baseLR_ER_FR_Full_BIT = 77, ETHTOOL_LINK_MODE_100000baseCR_Full_BIT = 78, ETHTOOL_LINK_MODE_100000baseDR_Full_BIT = 79, ETHTOOL_LINK_MODE_200000baseKR2_Full_BIT = 80, ETHTOOL_LINK_MODE_200000baseSR2_Full_BIT = 81, ETHTOOL_LINK_MODE_200000baseLR2_ER2_FR2_Full_BIT = 82, ETHTOOL_LINK_MODE_200000baseDR2_Full_BIT = 83, ETHTOOL_LINK_MODE_200000baseCR2_Full_BIT = 84, ETHTOOL_LINK_MODE_400000baseKR4_Full_BIT = 85, ETHTOOL_LINK_MODE_400000baseSR4_Full_BIT = 86, ETHTOOL_LINK_MODE_400000baseLR4_ER4_FR4_Full_BIT = 87, ETHTOOL_LINK_MODE_400000baseDR4_Full_BIT = 88, ETHTOOL_LINK_MODE_400000baseCR4_Full_BIT = 89, ETHTOOL_LINK_MODE_100baseFX_Half_BIT = 90, ETHTOOL_LINK_MODE_100baseFX_Full_BIT = 91, /* must be last entry */ __ETHTOOL_LINK_MODE_MASK_NBITS, /* RHEL: Last known value for RHEL 8.0 needed for emulation layer * for old binary drivers compiled against RHEL 8.0 */ __ETHTOOL_LINK_MODE_LAST_RH80 = ETHTOOL_LINK_MODE_FEC_BASER_BIT, #ifdef __GENKSYMS__ /* RHEL: Enum __ETHTOOL_LINK_MODE_LAST and its value is protected by * KABI checker. * We also need to define __ETHTOOL_LINK_MODE_MASK_NBITS as macro * for KABI checker to preserve existing checksums of several * ethtool symbols. */ __ETHTOOL_LINK_MODE_LAST = __ETHTOOL_LINK_MODE_LAST_RH80, #define __ETHTOOL_LINK_MODE_MASK_NBITS (__ETHTOOL_LINK_MODE_LAST + 1) #endif }; #define __ETHTOOL_LINK_MODE_LEGACY_MASK(base_name) \ (1UL << (ETHTOOL_LINK_MODE_ ## base_name ## _BIT)) /* DEPRECATED macros. Please migrate to * ETHTOOL_GLINKSETTINGS/ETHTOOL_SLINKSETTINGS API. Please do NOT * define any new SUPPORTED_* macro for bits > 31. */ #define SUPPORTED_10baseT_Half __ETHTOOL_LINK_MODE_LEGACY_MASK(10baseT_Half) #define SUPPORTED_10baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10baseT_Full) #define SUPPORTED_100baseT_Half __ETHTOOL_LINK_MODE_LEGACY_MASK(100baseT_Half) #define SUPPORTED_100baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(100baseT_Full) #define SUPPORTED_1000baseT_Half __ETHTOOL_LINK_MODE_LEGACY_MASK(1000baseT_Half) #define SUPPORTED_1000baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(1000baseT_Full) #define SUPPORTED_Autoneg __ETHTOOL_LINK_MODE_LEGACY_MASK(Autoneg) #define SUPPORTED_TP __ETHTOOL_LINK_MODE_LEGACY_MASK(TP) #define SUPPORTED_AUI __ETHTOOL_LINK_MODE_LEGACY_MASK(AUI) #define SUPPORTED_MII __ETHTOOL_LINK_MODE_LEGACY_MASK(MII) #define SUPPORTED_FIBRE __ETHTOOL_LINK_MODE_LEGACY_MASK(FIBRE) #define SUPPORTED_BNC __ETHTOOL_LINK_MODE_LEGACY_MASK(BNC) #define SUPPORTED_10000baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseT_Full) #define SUPPORTED_Pause __ETHTOOL_LINK_MODE_LEGACY_MASK(Pause) #define SUPPORTED_Asym_Pause __ETHTOOL_LINK_MODE_LEGACY_MASK(Asym_Pause) #define SUPPORTED_2500baseX_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(2500baseX_Full) #define SUPPORTED_Backplane __ETHTOOL_LINK_MODE_LEGACY_MASK(Backplane) #define SUPPORTED_1000baseKX_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(1000baseKX_Full) #define SUPPORTED_10000baseKX4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseKX4_Full) #define SUPPORTED_10000baseKR_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseKR_Full) #define SUPPORTED_10000baseR_FEC __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseR_FEC) #define SUPPORTED_20000baseMLD2_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(20000baseMLD2_Full) #define SUPPORTED_20000baseKR2_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(20000baseKR2_Full) #define SUPPORTED_40000baseKR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseKR4_Full) #define SUPPORTED_40000baseCR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseCR4_Full) #define SUPPORTED_40000baseSR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseSR4_Full) #define SUPPORTED_40000baseLR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseLR4_Full) #define SUPPORTED_56000baseKR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseKR4_Full) #define SUPPORTED_56000baseCR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseCR4_Full) #define SUPPORTED_56000baseSR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseSR4_Full) #define SUPPORTED_56000baseLR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseLR4_Full) /* Please do not define any new SUPPORTED_* macro for bits > 31, see * notice above. */ /* * DEPRECATED macros. Please migrate to * ETHTOOL_GLINKSETTINGS/ETHTOOL_SLINKSETTINGS API. Please do NOT * define any new ADERTISE_* macro for bits > 31. */ #define ADVERTISED_10baseT_Half __ETHTOOL_LINK_MODE_LEGACY_MASK(10baseT_Half) #define ADVERTISED_10baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10baseT_Full) #define ADVERTISED_100baseT_Half __ETHTOOL_LINK_MODE_LEGACY_MASK(100baseT_Half) #define ADVERTISED_100baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(100baseT_Full) #define ADVERTISED_1000baseT_Half __ETHTOOL_LINK_MODE_LEGACY_MASK(1000baseT_Half) #define ADVERTISED_1000baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(1000baseT_Full) #define ADVERTISED_Autoneg __ETHTOOL_LINK_MODE_LEGACY_MASK(Autoneg) #define ADVERTISED_TP __ETHTOOL_LINK_MODE_LEGACY_MASK(TP) #define ADVERTISED_AUI __ETHTOOL_LINK_MODE_LEGACY_MASK(AUI) #define ADVERTISED_MII __ETHTOOL_LINK_MODE_LEGACY_MASK(MII) #define ADVERTISED_FIBRE __ETHTOOL_LINK_MODE_LEGACY_MASK(FIBRE) #define ADVERTISED_BNC __ETHTOOL_LINK_MODE_LEGACY_MASK(BNC) #define ADVERTISED_10000baseT_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseT_Full) #define ADVERTISED_Pause __ETHTOOL_LINK_MODE_LEGACY_MASK(Pause) #define ADVERTISED_Asym_Pause __ETHTOOL_LINK_MODE_LEGACY_MASK(Asym_Pause) #define ADVERTISED_2500baseX_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(2500baseX_Full) #define ADVERTISED_Backplane __ETHTOOL_LINK_MODE_LEGACY_MASK(Backplane) #define ADVERTISED_1000baseKX_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(1000baseKX_Full) #define ADVERTISED_10000baseKX4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseKX4_Full) #define ADVERTISED_10000baseKR_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseKR_Full) #define ADVERTISED_10000baseR_FEC __ETHTOOL_LINK_MODE_LEGACY_MASK(10000baseR_FEC) #define ADVERTISED_20000baseMLD2_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(20000baseMLD2_Full) #define ADVERTISED_20000baseKR2_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(20000baseKR2_Full) #define ADVERTISED_40000baseKR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseKR4_Full) #define ADVERTISED_40000baseCR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseCR4_Full) #define ADVERTISED_40000baseSR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseSR4_Full) #define ADVERTISED_40000baseLR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(40000baseLR4_Full) #define ADVERTISED_56000baseKR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseKR4_Full) #define ADVERTISED_56000baseCR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseCR4_Full) #define ADVERTISED_56000baseSR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseSR4_Full) #define ADVERTISED_56000baseLR4_Full __ETHTOOL_LINK_MODE_LEGACY_MASK(56000baseLR4_Full) /* Please do not define any new ADVERTISED_* macro for bits > 31, see * notice above. */ /* The following are all involved in forcing a particular link * mode for the device for setting things. When getting the * devices settings, these indicate the current mode and whether * it was forced up into this mode or autonegotiated. */ /* The forced speed, in units of 1Mb. All values 0 to INT_MAX are legal. * Update drivers/net/phy/phy.c:phy_speed_to_str() and * drivers/net/bonding/bond_3ad.c:__get_link_speed() when adding new values. */ #define SPEED_10 10 #define SPEED_100 100 #define SPEED_1000 1000 #define SPEED_2500 2500 #define SPEED_5000 5000 #define SPEED_10000 10000 #define SPEED_14000 14000 #define SPEED_20000 20000 #define SPEED_25000 25000 #define SPEED_40000 40000 #define SPEED_50000 50000 #define SPEED_56000 56000 #define SPEED_100000 100000 #define SPEED_200000 200000 #define SPEED_400000 400000 #define SPEED_UNKNOWN -1 static __inline__ int ethtool_validate_speed(__u32 speed) { return speed <= INT_MAX || speed == (__u32)SPEED_UNKNOWN; } /* Duplex, half or full. */ #define DUPLEX_HALF 0x00 #define DUPLEX_FULL 0x01 #define DUPLEX_UNKNOWN 0xff static __inline__ int ethtool_validate_duplex(__u8 duplex) { switch (duplex) { case DUPLEX_HALF: case DUPLEX_FULL: case DUPLEX_UNKNOWN: return 1; } return 0; } #define MASTER_SLAVE_CFG_UNSUPPORTED 0 #define MASTER_SLAVE_CFG_UNKNOWN 1 #define MASTER_SLAVE_CFG_MASTER_PREFERRED 2 #define MASTER_SLAVE_CFG_SLAVE_PREFERRED 3 #define MASTER_SLAVE_CFG_MASTER_FORCE 4 #define MASTER_SLAVE_CFG_SLAVE_FORCE 5 #define MASTER_SLAVE_STATE_UNSUPPORTED 0 #define MASTER_SLAVE_STATE_UNKNOWN 1 #define MASTER_SLAVE_STATE_MASTER 2 #define MASTER_SLAVE_STATE_SLAVE 3 #define MASTER_SLAVE_STATE_ERR 4 /* Which connector port. */ #define PORT_TP 0x00 #define PORT_AUI 0x01 #define PORT_MII 0x02 #define PORT_FIBRE 0x03 #define PORT_BNC 0x04 #define PORT_DA 0x05 #define PORT_NONE 0xef #define PORT_OTHER 0xff /* Which transceiver to use. */ #define XCVR_INTERNAL 0x00 /* PHY and MAC are in the same package */ #define XCVR_EXTERNAL 0x01 /* PHY and MAC are in different packages */ #define XCVR_DUMMY1 0x02 #define XCVR_DUMMY2 0x03 #define XCVR_DUMMY3 0x04 /* Enable or disable autonegotiation. */ #define AUTONEG_DISABLE 0x00 #define AUTONEG_ENABLE 0x01 /* MDI or MDI-X status/control - if MDI/MDI_X/AUTO is set then * the driver is required to renegotiate link */ #define ETH_TP_MDI_INVALID 0x00 /* status: unknown; control: unsupported */ #define ETH_TP_MDI 0x01 /* status: MDI; control: force MDI */ #define ETH_TP_MDI_X 0x02 /* status: MDI-X; control: force MDI-X */ #define ETH_TP_MDI_AUTO 0x03 /* control: auto-select */ /* Wake-On-Lan options. */ #define WAKE_PHY (1 << 0) #define WAKE_UCAST (1 << 1) #define WAKE_MCAST (1 << 2) #define WAKE_BCAST (1 << 3) #define WAKE_ARP (1 << 4) #define WAKE_MAGIC (1 << 5) #define WAKE_MAGICSECURE (1 << 6) /* only meaningful if WAKE_MAGIC */ #define WAKE_FILTER (1 << 7) #define WOL_MODE_COUNT 8 /* L2-L4 network traffic flow types */ #define TCP_V4_FLOW 0x01 /* hash or spec (tcp_ip4_spec) */ #define UDP_V4_FLOW 0x02 /* hash or spec (udp_ip4_spec) */ #define SCTP_V4_FLOW 0x03 /* hash or spec (sctp_ip4_spec) */ #define AH_ESP_V4_FLOW 0x04 /* hash only */ #define TCP_V6_FLOW 0x05 /* hash or spec (tcp_ip6_spec; nfc only) */ #define UDP_V6_FLOW 0x06 /* hash or spec (udp_ip6_spec; nfc only) */ #define SCTP_V6_FLOW 0x07 /* hash or spec (sctp_ip6_spec; nfc only) */ #define AH_ESP_V6_FLOW 0x08 /* hash only */ #define AH_V4_FLOW 0x09 /* hash or spec (ah_ip4_spec) */ #define ESP_V4_FLOW 0x0a /* hash or spec (esp_ip4_spec) */ #define AH_V6_FLOW 0x0b /* hash or spec (ah_ip6_spec; nfc only) */ #define ESP_V6_FLOW 0x0c /* hash or spec (esp_ip6_spec; nfc only) */ #define IPV4_USER_FLOW 0x0d /* spec only (usr_ip4_spec) */ #define IP_USER_FLOW IPV4_USER_FLOW #define IPV6_USER_FLOW 0x0e /* spec only (usr_ip6_spec; nfc only) */ #define IPV4_FLOW 0x10 /* hash only */ #define IPV6_FLOW 0x11 /* hash only */ #define ETHER_FLOW 0x12 /* spec only (ether_spec) */ /* Flag to enable additional fields in struct ethtool_rx_flow_spec */ #define FLOW_EXT 0x80000000 #define FLOW_MAC_EXT 0x40000000 /* Flag to enable RSS spreading of traffic matching rule (nfc only) */ #define FLOW_RSS 0x20000000 /* L3-L4 network traffic flow hash options */ #define RXH_L2DA (1 << 1) #define RXH_VLAN (1 << 2) #define RXH_L3_PROTO (1 << 3) #define RXH_IP_SRC (1 << 4) #define RXH_IP_DST (1 << 5) #define RXH_L4_B_0_1 (1 << 6) /* src port in case of TCP/UDP/SCTP */ #define RXH_L4_B_2_3 (1 << 7) /* dst port in case of TCP/UDP/SCTP */ #define RXH_DISCARD (1 << 31) #define RX_CLS_FLOW_DISC 0xffffffffffffffffULL #define RX_CLS_FLOW_WAKE 0xfffffffffffffffeULL /* Special RX classification rule insert location values */ #define RX_CLS_LOC_SPECIAL 0x80000000 /* flag */ #define RX_CLS_LOC_ANY 0xffffffff #define RX_CLS_LOC_FIRST 0xfffffffe #define RX_CLS_LOC_LAST 0xfffffffd /* EEPROM Standards for plug in modules */ #define ETH_MODULE_SFF_8079 0x1 #define ETH_MODULE_SFF_8079_LEN 256 #define ETH_MODULE_SFF_8472 0x2 #define ETH_MODULE_SFF_8472_LEN 512 #define ETH_MODULE_SFF_8636 0x3 #define ETH_MODULE_SFF_8636_LEN 256 #define ETH_MODULE_SFF_8436 0x4 #define ETH_MODULE_SFF_8436_LEN 256 #define ETH_MODULE_SFF_8636_MAX_LEN 640 #define ETH_MODULE_SFF_8436_MAX_LEN 640 /* Reset flags */ /* The reset() operation must clear the flags for the components which * were actually reset. On successful return, the flags indicate the * components which were not reset, either because they do not exist * in the hardware or because they cannot be reset independently. The * driver must never reset any components that were not requested. */ enum ethtool_reset_flags { /* These flags represent components dedicated to the interface * the command is addressed to. Shift any flag left by * ETH_RESET_SHARED_SHIFT to reset a shared component of the * same type. */ ETH_RESET_MGMT = 1 << 0, /* Management processor */ ETH_RESET_IRQ = 1 << 1, /* Interrupt requester */ ETH_RESET_DMA = 1 << 2, /* DMA engine */ ETH_RESET_FILTER = 1 << 3, /* Filtering/flow direction */ ETH_RESET_OFFLOAD = 1 << 4, /* Protocol offload */ ETH_RESET_MAC = 1 << 5, /* Media access controller */ ETH_RESET_PHY = 1 << 6, /* Transceiver/PHY */ ETH_RESET_RAM = 1 << 7, /* RAM shared between * multiple components */ ETH_RESET_AP = 1 << 8, /* Application processor */ ETH_RESET_DEDICATED = 0x0000ffff, /* All components dedicated to * this interface */ ETH_RESET_ALL = 0xffffffff, /* All components used by this * interface, even if shared */ }; #define ETH_RESET_SHARED_SHIFT 16 /** * struct ethtool_link_settings - link control and status * * IMPORTANT, Backward compatibility notice: When implementing new * user-space tools, please first try %ETHTOOL_GLINKSETTINGS, and * if it succeeds use %ETHTOOL_SLINKSETTINGS to change link * settings; do not use %ETHTOOL_SSET if %ETHTOOL_GLINKSETTINGS * succeeded: stick to %ETHTOOL_GLINKSETTINGS/%SLINKSETTINGS in * that case. Conversely, if %ETHTOOL_GLINKSETTINGS fails, use * %ETHTOOL_GSET to query and %ETHTOOL_SSET to change link * settings; do not use %ETHTOOL_SLINKSETTINGS if * %ETHTOOL_GLINKSETTINGS failed: stick to * %ETHTOOL_GSET/%ETHTOOL_SSET in that case. * * @cmd: Command number = %ETHTOOL_GLINKSETTINGS or %ETHTOOL_SLINKSETTINGS * @speed: Link speed (Mbps) * @duplex: Duplex mode; one of %DUPLEX_* * @port: Physical connector type; one of %PORT_* * @phy_address: MDIO address of PHY (transceiver); 0 or 255 if not * applicable. For clause 45 PHYs this is the PRTAD. * @autoneg: Enable/disable autonegotiation and auto-detection; * either %AUTONEG_DISABLE or %AUTONEG_ENABLE * @mdio_support: Bitmask of %ETH_MDIO_SUPPORTS_* flags for the MDIO * protocols supported by the interface; 0 if unknown. * Read-only. * @eth_tp_mdix: Ethernet twisted-pair MDI(-X) status; one of * %ETH_TP_MDI_*. If the status is unknown or not applicable, the * value will be %ETH_TP_MDI_INVALID. Read-only. * @eth_tp_mdix_ctrl: Ethernet twisted pair MDI(-X) control; one of * %ETH_TP_MDI_*. If MDI(-X) control is not implemented, reads * yield %ETH_TP_MDI_INVALID and writes may be ignored or rejected. * When written successfully, the link should be renegotiated if * necessary. * @link_mode_masks_nwords: Number of 32-bit words for each of the * supported, advertising, lp_advertising link mode bitmaps. For * %ETHTOOL_GLINKSETTINGS: on entry, number of words passed by user * (>= 0); on return, if handshake in progress, negative if * request size unsupported by kernel: absolute value indicates * kernel expected size and all the other fields but cmd * are 0; otherwise (handshake completed), strictly positive * to indicate size used by kernel and cmd field stays * %ETHTOOL_GLINKSETTINGS, all other fields populated by driver. For * %ETHTOOL_SLINKSETTINGS: must be valid on entry, ie. a positive * value returned previously by %ETHTOOL_GLINKSETTINGS, otherwise * refused. For drivers: ignore this field (use kernel's * __ETHTOOL_LINK_MODE_MASK_NBITS instead), any change to it will * be overwritten by kernel. * @supported: Bitmap with each bit meaning given by * %ethtool_link_mode_bit_indices for the link modes, physical * connectors and other link features for which the interface * supports autonegotiation or auto-detection. Read-only. * @advertising: Bitmap with each bit meaning given by * %ethtool_link_mode_bit_indices for the link modes, physical * connectors and other link features that are advertised through * autonegotiation or enabled for auto-detection. * @lp_advertising: Bitmap with each bit meaning given by * %ethtool_link_mode_bit_indices for the link modes, and other * link features that the link partner advertised through * autonegotiation; 0 if unknown or not applicable. Read-only. * @transceiver: Used to distinguish different possible PHY types, * reported consistently by PHYLIB. Read-only. * @master_slave_cfg: Master/slave port mode. * @master_slave_state: Master/slave port state. * @reserved: Reserved for future use; see the note on reserved space. * @reserved1: Reserved for future use; see the note on reserved space. * @link_mode_masks: Variable length bitmaps. * * If autonegotiation is disabled, the speed and @duplex represent the * fixed link mode and are writable if the driver supports multiple * link modes. If it is enabled then they are read-only; if the link * is up they represent the negotiated link mode; if the link is down, * the speed is 0, %SPEED_UNKNOWN or the highest enabled speed and * @duplex is %DUPLEX_UNKNOWN or the best enabled duplex mode. * * Some hardware interfaces may have multiple PHYs and/or physical * connectors fitted or do not allow the driver to detect which are * fitted. For these interfaces @port and/or @phy_address may be * writable, possibly dependent on @autoneg being %AUTONEG_DISABLE. * Otherwise, attempts to write different values may be ignored or * rejected. * * Deprecated %ethtool_cmd fields transceiver, maxtxpkt and maxrxpkt * are not available in %ethtool_link_settings. Until all drivers are * converted to ignore them or to the new %ethtool_link_settings API, * for both queries and changes, users should always try * %ETHTOOL_GLINKSETTINGS first, and if it fails with -ENOTSUPP stick * only to %ETHTOOL_GSET and %ETHTOOL_SSET consistently. If it * succeeds, then users should stick to %ETHTOOL_GLINKSETTINGS and * %ETHTOOL_SLINKSETTINGS (which would support drivers implementing * either %ethtool_cmd or %ethtool_link_settings). * * Users should assume that all fields not marked read-only are * writable and subject to validation by the driver. They should use * %ETHTOOL_GLINKSETTINGS to get the current values before making specific * changes and then applying them with %ETHTOOL_SLINKSETTINGS. * * Drivers that implement %get_link_ksettings and/or * %set_link_ksettings should ignore the @cmd * and @link_mode_masks_nwords fields (any change to them overwritten * by kernel), and rely only on kernel's internal * %__ETHTOOL_LINK_MODE_MASK_NBITS and * %ethtool_link_mode_mask_t. Drivers that implement * %set_link_ksettings() should validate all fields other than @cmd * and @link_mode_masks_nwords that are not described as read-only or * deprecated, and must ignore all fields described as read-only. */ struct ethtool_link_settings { __u32 cmd; __u32 speed; __u8 duplex; __u8 port; __u8 phy_address; __u8 autoneg; __u8 mdio_support; __u8 eth_tp_mdix; __u8 eth_tp_mdix_ctrl; __s8 link_mode_masks_nwords; __u8 transceiver; #ifndef __GENKSYMS__ __u8 master_slave_cfg; __u8 master_slave_state; __u8 reserved1[1]; #else __u8 reserved1[3]; #endif __u32 reserved[7]; __u32 link_mode_masks[0]; /* layout of link_mode_masks fields: * __u32 map_supported[link_mode_masks_nwords]; * __u32 map_advertising[link_mode_masks_nwords]; * __u32 map_lp_advertising[link_mode_masks_nwords]; */ }; #endif /* _LINUX_ETHTOOL_H */ linux/uhid.h000064400000011050151027430560007005 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef __UHID_H_ #define __UHID_H_ /* * User-space I/O driver support for HID subsystem * Copyright (c) 2012 David Herrmann */ /* * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. */ /* * Public header for user-space communication. We try to keep every structure * aligned but to be safe we also use __attribute__((__packed__)). Therefore, * the communication should be ABI compatible even between architectures. */ #include #include #include enum uhid_event_type { __UHID_LEGACY_CREATE, UHID_DESTROY, UHID_START, UHID_STOP, UHID_OPEN, UHID_CLOSE, UHID_OUTPUT, __UHID_LEGACY_OUTPUT_EV, __UHID_LEGACY_INPUT, UHID_GET_REPORT, UHID_GET_REPORT_REPLY, UHID_CREATE2, UHID_INPUT2, UHID_SET_REPORT, UHID_SET_REPORT_REPLY, }; struct uhid_create2_req { __u8 name[128]; __u8 phys[64]; __u8 uniq[64]; __u16 rd_size; __u16 bus; __u32 vendor; __u32 product; __u32 version; __u32 country; __u8 rd_data[HID_MAX_DESCRIPTOR_SIZE]; } __attribute__((__packed__)); enum uhid_dev_flag { UHID_DEV_NUMBERED_FEATURE_REPORTS = (1ULL << 0), UHID_DEV_NUMBERED_OUTPUT_REPORTS = (1ULL << 1), UHID_DEV_NUMBERED_INPUT_REPORTS = (1ULL << 2), }; struct uhid_start_req { __u64 dev_flags; }; #define UHID_DATA_MAX 4096 enum uhid_report_type { UHID_FEATURE_REPORT, UHID_OUTPUT_REPORT, UHID_INPUT_REPORT, }; struct uhid_input2_req { __u16 size; __u8 data[UHID_DATA_MAX]; } __attribute__((__packed__)); struct uhid_output_req { __u8 data[UHID_DATA_MAX]; __u16 size; __u8 rtype; } __attribute__((__packed__)); struct uhid_get_report_req { __u32 id; __u8 rnum; __u8 rtype; } __attribute__((__packed__)); struct uhid_get_report_reply_req { __u32 id; __u16 err; __u16 size; __u8 data[UHID_DATA_MAX]; } __attribute__((__packed__)); struct uhid_set_report_req { __u32 id; __u8 rnum; __u8 rtype; __u16 size; __u8 data[UHID_DATA_MAX]; } __attribute__((__packed__)); struct uhid_set_report_reply_req { __u32 id; __u16 err; } __attribute__((__packed__)); /* * Compat Layer * All these commands and requests are obsolete. You should avoid using them in * new code. We support them for backwards-compatibility, but you might not get * access to new feature in case you use them. */ enum uhid_legacy_event_type { UHID_CREATE = __UHID_LEGACY_CREATE, UHID_OUTPUT_EV = __UHID_LEGACY_OUTPUT_EV, UHID_INPUT = __UHID_LEGACY_INPUT, UHID_FEATURE = UHID_GET_REPORT, UHID_FEATURE_ANSWER = UHID_GET_REPORT_REPLY, }; /* Obsolete! Use UHID_CREATE2. */ struct uhid_create_req { __u8 name[128]; __u8 phys[64]; __u8 uniq[64]; __u8 *rd_data; __u16 rd_size; __u16 bus; __u32 vendor; __u32 product; __u32 version; __u32 country; } __attribute__((__packed__)); /* Obsolete! Use UHID_INPUT2. */ struct uhid_input_req { __u8 data[UHID_DATA_MAX]; __u16 size; } __attribute__((__packed__)); /* Obsolete! Kernel uses UHID_OUTPUT exclusively now. */ struct uhid_output_ev_req { __u16 type; __u16 code; __s32 value; } __attribute__((__packed__)); /* Obsolete! Kernel uses ABI compatible UHID_GET_REPORT. */ struct uhid_feature_req { __u32 id; __u8 rnum; __u8 rtype; } __attribute__((__packed__)); /* Obsolete! Use ABI compatible UHID_GET_REPORT_REPLY. */ struct uhid_feature_answer_req { __u32 id; __u16 err; __u16 size; __u8 data[UHID_DATA_MAX]; } __attribute__((__packed__)); /* * UHID Events * All UHID events from and to the kernel are encoded as "struct uhid_event". * The "type" field contains a UHID_* type identifier. All payload depends on * that type and can be accessed via ev->u.XYZ accordingly. * If user-space writes short events, they're extended with 0s by the kernel. If * the kernel writes short events, user-space shall extend them with 0s. */ struct uhid_event { __u32 type; union { struct uhid_create_req create; struct uhid_input_req input; struct uhid_output_req output; struct uhid_output_ev_req output_ev; struct uhid_feature_req feature; struct uhid_get_report_req get_report; struct uhid_feature_answer_req feature_answer; struct uhid_get_report_reply_req get_report_reply; struct uhid_create2_req create2; struct uhid_input2_req input2; struct uhid_set_report_req set_report; struct uhid_set_report_reply_req set_report_reply; struct uhid_start_req start; } u; } __attribute__((__packed__)); #endif /* __UHID_H_ */ linux/pg.h000064400000004532151027430560006471 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* pg.h (c) 1998 Grant R. Guenther Under the terms of the GNU General Public License pg.h defines the user interface to the generic ATAPI packet command driver for parallel port ATAPI devices (pg). The driver is loosely modelled after the generic SCSI driver, sg, although the actual interface is different. The pg driver provides a simple character device interface for sending ATAPI commands to a device. With the exception of the ATAPI reset operation, all operations are performed by a pair of read and write operations to the appropriate /dev/pgN device. A write operation delivers a command and any outbound data in a single buffer. Normally, the write will succeed unless the device is offline or malfunctioning, or there is already another command pending. If the write succeeds, it should be followed immediately by a read operation, to obtain any returned data and status information. A read will fail if there is no operation in progress. As a special case, the device can be reset with a write operation, and in this case, no following read is expected, or permitted. There are no ioctl() operations. Any single operation may transfer at most PG_MAX_DATA bytes. Note that the driver must copy the data through an internal buffer. In keeping with all current ATAPI devices, command packets are assumed to be exactly 12 bytes in length. To permit future changes to this interface, the headers in the read and write buffers contain a single character "magic" flag. Currently this flag must be the character "P". */ #ifndef _LINUX_PG_H #define _LINUX_PG_H #define PG_MAGIC 'P' #define PG_RESET 'Z' #define PG_COMMAND 'C' #define PG_MAX_DATA 32768 struct pg_write_hdr { char magic; /* == PG_MAGIC */ char func; /* PG_RESET or PG_COMMAND */ int dlen; /* number of bytes expected to transfer */ int timeout; /* number of seconds before timeout */ char packet[12]; /* packet command */ }; struct pg_read_hdr { char magic; /* == PG_MAGIC */ char scsi; /* "scsi" status == sense key */ int dlen; /* size of device transfer request */ int duration; /* time in seconds command took */ char pad[12]; /* not used */ }; #endif /* _LINUX_PG_H */ linux/vsockmon.h000064400000003535151027430560007724 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _VSOCKMON_H #define _VSOCKMON_H #include /* * vsockmon is the AF_VSOCK packet capture device. Packets captured have the * following layout: * * +-----------------------------------+ * | vsockmon header | * | (struct af_vsockmon_hdr) | * +-----------------------------------+ * | transport header | * | (af_vsockmon_hdr->len bytes long) | * +-----------------------------------+ * | payload | * | (until end of packet) | * +-----------------------------------+ * * The vsockmon header is a transport-independent description of the packet. * It duplicates some of the information from the transport header so that * no transport-specific knowledge is necessary to process packets. * * The transport header is useful for low-level transport-specific packet * analysis. Transport type is given in af_vsockmon_hdr->transport and * transport header length is given in af_vsockmon_hdr->len. * * If af_vsockmon_hdr->op is AF_VSOCK_OP_PAYLOAD then the payload follows the * transport header. Other ops do not have a payload. */ struct af_vsockmon_hdr { __le64 src_cid; __le64 dst_cid; __le32 src_port; __le32 dst_port; __le16 op; /* enum af_vsockmon_op */ __le16 transport; /* enum af_vsockmon_transport */ __le16 len; /* Transport header length */ __u8 reserved[2]; }; enum af_vsockmon_op { AF_VSOCK_OP_UNKNOWN = 0, AF_VSOCK_OP_CONNECT = 1, AF_VSOCK_OP_DISCONNECT = 2, AF_VSOCK_OP_CONTROL = 3, AF_VSOCK_OP_PAYLOAD = 4, }; enum af_vsockmon_transport { AF_VSOCK_TRANSPORT_UNKNOWN = 0, AF_VSOCK_TRANSPORT_NO_INFO = 1, /* No transport information */ /* Transport header type: struct virtio_vsock_hdr */ AF_VSOCK_TRANSPORT_VIRTIO = 2, }; #endif linux/futex.h000064400000011601151027430560007211 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FUTEX_H #define _LINUX_FUTEX_H #include /* Second argument to futex syscall */ #define FUTEX_WAIT 0 #define FUTEX_WAKE 1 #define FUTEX_FD 2 #define FUTEX_REQUEUE 3 #define FUTEX_CMP_REQUEUE 4 #define FUTEX_WAKE_OP 5 #define FUTEX_LOCK_PI 6 #define FUTEX_UNLOCK_PI 7 #define FUTEX_TRYLOCK_PI 8 #define FUTEX_WAIT_BITSET 9 #define FUTEX_WAKE_BITSET 10 #define FUTEX_WAIT_REQUEUE_PI 11 #define FUTEX_CMP_REQUEUE_PI 12 #define FUTEX_PRIVATE_FLAG 128 #define FUTEX_CLOCK_REALTIME 256 #define FUTEX_CMD_MASK ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME) #define FUTEX_WAIT_PRIVATE (FUTEX_WAIT | FUTEX_PRIVATE_FLAG) #define FUTEX_WAKE_PRIVATE (FUTEX_WAKE | FUTEX_PRIVATE_FLAG) #define FUTEX_REQUEUE_PRIVATE (FUTEX_REQUEUE | FUTEX_PRIVATE_FLAG) #define FUTEX_CMP_REQUEUE_PRIVATE (FUTEX_CMP_REQUEUE | FUTEX_PRIVATE_FLAG) #define FUTEX_WAKE_OP_PRIVATE (FUTEX_WAKE_OP | FUTEX_PRIVATE_FLAG) #define FUTEX_LOCK_PI_PRIVATE (FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG) #define FUTEX_UNLOCK_PI_PRIVATE (FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG) #define FUTEX_TRYLOCK_PI_PRIVATE (FUTEX_TRYLOCK_PI | FUTEX_PRIVATE_FLAG) #define FUTEX_WAIT_BITSET_PRIVATE (FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG) #define FUTEX_WAKE_BITSET_PRIVATE (FUTEX_WAKE_BITSET | FUTEX_PRIVATE_FLAG) #define FUTEX_WAIT_REQUEUE_PI_PRIVATE (FUTEX_WAIT_REQUEUE_PI | \ FUTEX_PRIVATE_FLAG) #define FUTEX_CMP_REQUEUE_PI_PRIVATE (FUTEX_CMP_REQUEUE_PI | \ FUTEX_PRIVATE_FLAG) /* * Support for robust futexes: the kernel cleans up held futexes at * thread exit time. */ /* * Per-lock list entry - embedded in user-space locks, somewhere close * to the futex field. (Note: user-space uses a double-linked list to * achieve O(1) list add and remove, but the kernel only needs to know * about the forward link) * * NOTE: this structure is part of the syscall ABI, and must not be * changed. */ struct robust_list { struct robust_list *next; }; /* * Per-thread list head: * * NOTE: this structure is part of the syscall ABI, and must only be * changed if the change is first communicated with the glibc folks. * (When an incompatible change is done, we'll increase the structure * size, which glibc will detect) */ struct robust_list_head { /* * The head of the list. Points back to itself if empty: */ struct robust_list list; /* * This relative offset is set by user-space, it gives the kernel * the relative position of the futex field to examine. This way * we keep userspace flexible, to freely shape its data-structure, * without hardcoding any particular offset into the kernel: */ long futex_offset; /* * The death of the thread may race with userspace setting * up a lock's links. So to handle this race, userspace first * sets this field to the address of the to-be-taken lock, * then does the lock acquire, and then adds itself to the * list, and then clears this field. Hence the kernel will * always have full knowledge of all locks that the thread * _might_ have taken. We check the owner TID in any case, * so only truly owned locks will be handled. */ struct robust_list *list_op_pending; }; /* * Are there any waiters for this robust futex: */ #define FUTEX_WAITERS 0x80000000 /* * The kernel signals via this bit that a thread holding a futex * has exited without unlocking the futex. The kernel also does * a FUTEX_WAKE on such futexes, after setting the bit, to wake * up any possible waiters: */ #define FUTEX_OWNER_DIED 0x40000000 /* * The rest of the robust-futex field is for the TID: */ #define FUTEX_TID_MASK 0x3fffffff /* * This limit protects against a deliberately circular list. * (Not worth introducing an rlimit for it) */ #define ROBUST_LIST_LIMIT 2048 /* * bitset with all bits set for the FUTEX_xxx_BITSET OPs to request a * match of any bit. */ #define FUTEX_BITSET_MATCH_ANY 0xffffffff #define FUTEX_OP_SET 0 /* *(int *)UADDR2 = OPARG; */ #define FUTEX_OP_ADD 1 /* *(int *)UADDR2 += OPARG; */ #define FUTEX_OP_OR 2 /* *(int *)UADDR2 |= OPARG; */ #define FUTEX_OP_ANDN 3 /* *(int *)UADDR2 &= ~OPARG; */ #define FUTEX_OP_XOR 4 /* *(int *)UADDR2 ^= OPARG; */ #define FUTEX_OP_OPARG_SHIFT 8 /* Use (1 << OPARG) instead of OPARG. */ #define FUTEX_OP_CMP_EQ 0 /* if (oldval == CMPARG) wake */ #define FUTEX_OP_CMP_NE 1 /* if (oldval != CMPARG) wake */ #define FUTEX_OP_CMP_LT 2 /* if (oldval < CMPARG) wake */ #define FUTEX_OP_CMP_LE 3 /* if (oldval <= CMPARG) wake */ #define FUTEX_OP_CMP_GT 4 /* if (oldval > CMPARG) wake */ #define FUTEX_OP_CMP_GE 5 /* if (oldval >= CMPARG) wake */ /* FUTEX_WAKE_OP will perform atomically int oldval = *(int *)UADDR2; *(int *)UADDR2 = oldval OP OPARG; if (oldval CMP CMPARG) wake UADDR2; */ #define FUTEX_OP(op, oparg, cmp, cmparg) \ (((op & 0xf) << 28) | ((cmp & 0xf) << 24) \ | ((oparg & 0xfff) << 12) | (cmparg & 0xfff)) #endif /* _LINUX_FUTEX_H */ linux/ppp-ioctl.h000064400000012543151027430560007773 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ppp-ioctl.h - PPP ioctl definitions. * * Copyright 1999-2002 Paul Mackerras. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #ifndef _PPP_IOCTL_H #define _PPP_IOCTL_H #include #include /* * Bit definitions for flags argument to PPPIOCGFLAGS/PPPIOCSFLAGS. */ #define SC_COMP_PROT 0x00000001 /* protocol compression (output) */ #define SC_COMP_AC 0x00000002 /* header compression (output) */ #define SC_COMP_TCP 0x00000004 /* TCP (VJ) compression (output) */ #define SC_NO_TCP_CCID 0x00000008 /* disable VJ connection-id comp. */ #define SC_REJ_COMP_AC 0x00000010 /* reject adrs/ctrl comp. on input */ #define SC_REJ_COMP_TCP 0x00000020 /* reject TCP (VJ) comp. on input */ #define SC_CCP_OPEN 0x00000040 /* Look at CCP packets */ #define SC_CCP_UP 0x00000080 /* May send/recv compressed packets */ #define SC_ENABLE_IP 0x00000100 /* IP packets may be exchanged */ #define SC_LOOP_TRAFFIC 0x00000200 /* send traffic to pppd */ #define SC_MULTILINK 0x00000400 /* do multilink encapsulation */ #define SC_MP_SHORTSEQ 0x00000800 /* use short MP sequence numbers */ #define SC_COMP_RUN 0x00001000 /* compressor has been inited */ #define SC_DECOMP_RUN 0x00002000 /* decompressor has been inited */ #define SC_MP_XSHORTSEQ 0x00004000 /* transmit short MP seq numbers */ #define SC_DEBUG 0x00010000 /* enable debug messages */ #define SC_LOG_INPKT 0x00020000 /* log contents of good pkts recvd */ #define SC_LOG_OUTPKT 0x00040000 /* log contents of pkts sent */ #define SC_LOG_RAWIN 0x00080000 /* log all chars received */ #define SC_LOG_FLUSH 0x00100000 /* log all chars flushed */ #define SC_SYNC 0x00200000 /* synchronous serial mode */ #define SC_MUST_COMP 0x00400000 /* no uncompressed packets may be sent or received */ #define SC_MASK 0x0f600fff /* bits that user can change */ /* state bits */ #define SC_XMIT_BUSY 0x10000000 /* (used by isdn_ppp?) */ #define SC_RCV_ODDP 0x08000000 /* have rcvd char with odd parity */ #define SC_RCV_EVNP 0x04000000 /* have rcvd char with even parity */ #define SC_RCV_B7_1 0x02000000 /* have rcvd char with bit 7 = 1 */ #define SC_RCV_B7_0 0x01000000 /* have rcvd char with bit 7 = 0 */ #define SC_DC_FERROR 0x00800000 /* fatal decomp error detected */ #define SC_DC_ERROR 0x00400000 /* non-fatal decomp error detected */ /* Used with PPPIOCGNPMODE/PPPIOCSNPMODE */ struct npioctl { int protocol; /* PPP protocol, e.g. PPP_IP */ enum NPmode mode; }; /* Structure describing a CCP configuration option, for PPPIOCSCOMPRESS */ struct ppp_option_data { __u8 *ptr; __u32 length; int transmit; }; /* For PPPIOCGL2TPSTATS */ struct pppol2tp_ioc_stats { __u16 tunnel_id; /* redundant */ __u16 session_id; /* if zero, get tunnel stats */ __u32 using_ipsec:1; /* valid only for session_id == 0 */ __aligned_u64 tx_packets; __aligned_u64 tx_bytes; __aligned_u64 tx_errors; __aligned_u64 rx_packets; __aligned_u64 rx_bytes; __aligned_u64 rx_seq_discards; __aligned_u64 rx_oos_packets; __aligned_u64 rx_errors; }; /* * Ioctl definitions. */ #define PPPIOCGFLAGS _IOR('t', 90, int) /* get configuration flags */ #define PPPIOCSFLAGS _IOW('t', 89, int) /* set configuration flags */ #define PPPIOCGASYNCMAP _IOR('t', 88, int) /* get async map */ #define PPPIOCSASYNCMAP _IOW('t', 87, int) /* set async map */ #define PPPIOCGUNIT _IOR('t', 86, int) /* get ppp unit number */ #define PPPIOCGRASYNCMAP _IOR('t', 85, int) /* get receive async map */ #define PPPIOCSRASYNCMAP _IOW('t', 84, int) /* set receive async map */ #define PPPIOCGMRU _IOR('t', 83, int) /* get max receive unit */ #define PPPIOCSMRU _IOW('t', 82, int) /* set max receive unit */ #define PPPIOCSMAXCID _IOW('t', 81, int) /* set VJ max slot ID */ #define PPPIOCGXASYNCMAP _IOR('t', 80, ext_accm) /* get extended ACCM */ #define PPPIOCSXASYNCMAP _IOW('t', 79, ext_accm) /* set extended ACCM */ #define PPPIOCXFERUNIT _IO('t', 78) /* transfer PPP unit */ #define PPPIOCSCOMPRESS _IOW('t', 77, struct ppp_option_data) #define PPPIOCGNPMODE _IOWR('t', 76, struct npioctl) /* get NP mode */ #define PPPIOCSNPMODE _IOW('t', 75, struct npioctl) /* set NP mode */ #define PPPIOCSPASS _IOW('t', 71, struct sock_fprog) /* set pass filter */ #define PPPIOCSACTIVE _IOW('t', 70, struct sock_fprog) /* set active filt */ #define PPPIOCGDEBUG _IOR('t', 65, int) /* Read debug level */ #define PPPIOCSDEBUG _IOW('t', 64, int) /* Set debug level */ #define PPPIOCGIDLE _IOR('t', 63, struct ppp_idle) /* get idle time */ #define PPPIOCNEWUNIT _IOWR('t', 62, int) /* create new ppp unit */ #define PPPIOCATTACH _IOW('t', 61, int) /* attach to ppp unit */ #define PPPIOCDETACH _IOW('t', 60, int) /* obsolete, do not use */ #define PPPIOCSMRRU _IOW('t', 59, int) /* set multilink MRU */ #define PPPIOCCONNECT _IOW('t', 58, int) /* connect channel to unit */ #define PPPIOCDISCONN _IO('t', 57) /* disconnect channel */ #define PPPIOCATTCHAN _IOW('t', 56, int) /* attach to ppp channel */ #define PPPIOCGCHAN _IOR('t', 55, int) /* get ppp channel number */ #define PPPIOCGL2TPSTATS _IOR('t', 54, struct pppol2tp_ioc_stats) #define SIOCGPPPSTATS (SIOCDEVPRIVATE + 0) #define SIOCGPPPVER (SIOCDEVPRIVATE + 1) /* NEVER change this!! */ #define SIOCGPPPCSTATS (SIOCDEVPRIVATE + 2) #endif /* _PPP_IOCTL_H */ linux/netconf.h000064400000001146151027430560007515 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_NETCONF_H_ #define _LINUX_NETCONF_H_ #include #include struct netconfmsg { __u8 ncm_family; }; enum { NETCONFA_UNSPEC, NETCONFA_IFINDEX, NETCONFA_FORWARDING, NETCONFA_RP_FILTER, NETCONFA_MC_FORWARDING, NETCONFA_PROXY_NEIGH, NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN, NETCONFA_INPUT, NETCONFA_BC_FORWARDING, __NETCONFA_MAX }; #define NETCONFA_MAX (__NETCONFA_MAX - 1) #define NETCONFA_ALL -1 #define NETCONFA_IFINDEX_ALL -1 #define NETCONFA_IFINDEX_DEFAULT -2 #endif /* _LINUX_NETCONF_H_ */ linux/nsfs.h000064400000001177151027430560007036 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_NSFS_H #define __LINUX_NSFS_H #include #define NSIO 0xb7 /* Returns a file descriptor that refers to an owning user namespace */ #define NS_GET_USERNS _IO(NSIO, 0x1) /* Returns a file descriptor that refers to a parent namespace */ #define NS_GET_PARENT _IO(NSIO, 0x2) /* Returns the type of namespace (CLONE_NEW* value) referred to by file descriptor */ #define NS_GET_NSTYPE _IO(NSIO, 0x3) /* Get owner UID (in the caller's user namespace) for a user namespace */ #define NS_GET_OWNER_UID _IO(NSIO, 0x4) #endif /* __LINUX_NSFS_H */ linux/dccp.h000064400000014444151027430560006777 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_DCCP_H #define _LINUX_DCCP_H #include #include /** * struct dccp_hdr - generic part of DCCP packet header * * @dccph_sport - Relevant port on the endpoint that sent this packet * @dccph_dport - Relevant port on the other endpoint * @dccph_doff - Data Offset from the start of the DCCP header, in 32-bit words * @dccph_ccval - Used by the HC-Sender CCID * @dccph_cscov - Parts of the packet that are covered by the Checksum field * @dccph_checksum - Internet checksum, depends on dccph_cscov * @dccph_x - 0 = 24 bit sequence number, 1 = 48 * @dccph_type - packet type, see DCCP_PKT_ prefixed macros * @dccph_seq - sequence number high or low order 24 bits, depends on dccph_x */ struct dccp_hdr { __be16 dccph_sport, dccph_dport; __u8 dccph_doff; #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 dccph_cscov:4, dccph_ccval:4; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 dccph_ccval:4, dccph_cscov:4; #else #error "Adjust your defines" #endif __sum16 dccph_checksum; #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 dccph_x:1, dccph_type:4, dccph_reserved:3; #elif defined(__BIG_ENDIAN_BITFIELD) __u8 dccph_reserved:3, dccph_type:4, dccph_x:1; #else #error "Adjust your defines" #endif __u8 dccph_seq2; __be16 dccph_seq; }; /** * struct dccp_hdr_ext - the low bits of a 48 bit seq packet * * @dccph_seq_low - low 24 bits of a 48 bit seq packet */ struct dccp_hdr_ext { __be32 dccph_seq_low; }; /** * struct dccp_hdr_request - Connection initiation request header * * @dccph_req_service - Service to which the client app wants to connect */ struct dccp_hdr_request { __be32 dccph_req_service; }; /** * struct dccp_hdr_ack_bits - acknowledgment bits common to most packets * * @dccph_resp_ack_nr_high - 48 bit ack number high order bits, contains GSR * @dccph_resp_ack_nr_low - 48 bit ack number low order bits, contains GSR */ struct dccp_hdr_ack_bits { __be16 dccph_reserved1; __be16 dccph_ack_nr_high; __be32 dccph_ack_nr_low; }; /** * struct dccp_hdr_response - Connection initiation response header * * @dccph_resp_ack - 48 bit Acknowledgment Number Subheader (5.3) * @dccph_resp_service - Echoes the Service Code on a received DCCP-Request */ struct dccp_hdr_response { struct dccp_hdr_ack_bits dccph_resp_ack; __be32 dccph_resp_service; }; /** * struct dccp_hdr_reset - Unconditionally shut down a connection * * @dccph_reset_ack - 48 bit Acknowledgment Number Subheader (5.6) * @dccph_reset_code - one of %dccp_reset_codes * @dccph_reset_data - the Data 1 ... Data 3 fields from 5.6 */ struct dccp_hdr_reset { struct dccp_hdr_ack_bits dccph_reset_ack; __u8 dccph_reset_code, dccph_reset_data[3]; }; enum dccp_pkt_type { DCCP_PKT_REQUEST = 0, DCCP_PKT_RESPONSE, DCCP_PKT_DATA, DCCP_PKT_ACK, DCCP_PKT_DATAACK, DCCP_PKT_CLOSEREQ, DCCP_PKT_CLOSE, DCCP_PKT_RESET, DCCP_PKT_SYNC, DCCP_PKT_SYNCACK, DCCP_PKT_INVALID, }; #define DCCP_NR_PKT_TYPES DCCP_PKT_INVALID static __inline__ unsigned int dccp_packet_hdr_len(const __u8 type) { if (type == DCCP_PKT_DATA) return 0; if (type == DCCP_PKT_DATAACK || type == DCCP_PKT_ACK || type == DCCP_PKT_SYNC || type == DCCP_PKT_SYNCACK || type == DCCP_PKT_CLOSE || type == DCCP_PKT_CLOSEREQ) return sizeof(struct dccp_hdr_ack_bits); if (type == DCCP_PKT_REQUEST) return sizeof(struct dccp_hdr_request); if (type == DCCP_PKT_RESPONSE) return sizeof(struct dccp_hdr_response); return sizeof(struct dccp_hdr_reset); } enum dccp_reset_codes { DCCP_RESET_CODE_UNSPECIFIED = 0, DCCP_RESET_CODE_CLOSED, DCCP_RESET_CODE_ABORTED, DCCP_RESET_CODE_NO_CONNECTION, DCCP_RESET_CODE_PACKET_ERROR, DCCP_RESET_CODE_OPTION_ERROR, DCCP_RESET_CODE_MANDATORY_ERROR, DCCP_RESET_CODE_CONNECTION_REFUSED, DCCP_RESET_CODE_BAD_SERVICE_CODE, DCCP_RESET_CODE_TOO_BUSY, DCCP_RESET_CODE_BAD_INIT_COOKIE, DCCP_RESET_CODE_AGGRESSION_PENALTY, DCCP_MAX_RESET_CODES /* Leave at the end! */ }; /* DCCP options */ enum { DCCPO_PADDING = 0, DCCPO_MANDATORY = 1, DCCPO_MIN_RESERVED = 3, DCCPO_MAX_RESERVED = 31, DCCPO_CHANGE_L = 32, DCCPO_CONFIRM_L = 33, DCCPO_CHANGE_R = 34, DCCPO_CONFIRM_R = 35, DCCPO_NDP_COUNT = 37, DCCPO_ACK_VECTOR_0 = 38, DCCPO_ACK_VECTOR_1 = 39, DCCPO_TIMESTAMP = 41, DCCPO_TIMESTAMP_ECHO = 42, DCCPO_ELAPSED_TIME = 43, DCCPO_MAX = 45, DCCPO_MIN_RX_CCID_SPECIFIC = 128, /* from sender to receiver */ DCCPO_MAX_RX_CCID_SPECIFIC = 191, DCCPO_MIN_TX_CCID_SPECIFIC = 192, /* from receiver to sender */ DCCPO_MAX_TX_CCID_SPECIFIC = 255, }; /* maximum size of a single TLV-encoded DCCP option (sans type/len bytes) */ #define DCCP_SINGLE_OPT_MAXLEN 253 /* DCCP CCIDS */ enum { DCCPC_CCID2 = 2, DCCPC_CCID3 = 3, }; /* DCCP features (RFC 4340 section 6.4) */ enum dccp_feature_numbers { DCCPF_RESERVED = 0, DCCPF_CCID = 1, DCCPF_SHORT_SEQNOS = 2, DCCPF_SEQUENCE_WINDOW = 3, DCCPF_ECN_INCAPABLE = 4, DCCPF_ACK_RATIO = 5, DCCPF_SEND_ACK_VECTOR = 6, DCCPF_SEND_NDP_COUNT = 7, DCCPF_MIN_CSUM_COVER = 8, DCCPF_DATA_CHECKSUM = 9, /* 10-127 reserved */ DCCPF_MIN_CCID_SPECIFIC = 128, DCCPF_SEND_LEV_RATE = 192, /* RFC 4342, sec. 8.4 */ DCCPF_MAX_CCID_SPECIFIC = 255, }; /* DCCP socket control message types for cmsg */ enum dccp_cmsg_type { DCCP_SCM_PRIORITY = 1, DCCP_SCM_QPOLICY_MAX = 0xFFFF, /* ^-- Up to here reserved exclusively for qpolicy parameters */ DCCP_SCM_MAX }; /* DCCP priorities for outgoing/queued packets */ enum dccp_packet_dequeueing_policy { DCCPQ_POLICY_SIMPLE, DCCPQ_POLICY_PRIO, DCCPQ_POLICY_MAX }; /* DCCP socket options */ #define DCCP_SOCKOPT_PACKET_SIZE 1 /* XXX deprecated, without effect */ #define DCCP_SOCKOPT_SERVICE 2 #define DCCP_SOCKOPT_CHANGE_L 3 #define DCCP_SOCKOPT_CHANGE_R 4 #define DCCP_SOCKOPT_GET_CUR_MPS 5 #define DCCP_SOCKOPT_SERVER_TIMEWAIT 6 #define DCCP_SOCKOPT_SEND_CSCOV 10 #define DCCP_SOCKOPT_RECV_CSCOV 11 #define DCCP_SOCKOPT_AVAILABLE_CCIDS 12 #define DCCP_SOCKOPT_CCID 13 #define DCCP_SOCKOPT_TX_CCID 14 #define DCCP_SOCKOPT_RX_CCID 15 #define DCCP_SOCKOPT_QPOLICY_ID 16 #define DCCP_SOCKOPT_QPOLICY_TXQLEN 17 #define DCCP_SOCKOPT_CCID_RX_INFO 128 #define DCCP_SOCKOPT_CCID_TX_INFO 192 /* maximum number of services provided on the same listening port */ #define DCCP_SERVICE_LIST_MAX_LEN 32 #endif /* _LINUX_DCCP_H */ linux/tls.h000064400000010300151027430560006653 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR Linux-OpenIB) */ /* * Copyright (c) 2016-2017, Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef _LINUX_TLS_H #define _LINUX_TLS_H #include /* TLS socket options */ #define TLS_TX 1 /* Set transmit parameters */ #define TLS_RX 2 /* Set receive parameters */ /* Supported versions */ #define TLS_VERSION_MINOR(ver) ((ver) & 0xFF) #define TLS_VERSION_MAJOR(ver) (((ver) >> 8) & 0xFF) #define TLS_VERSION_NUMBER(id) ((((id##_VERSION_MAJOR) & 0xFF) << 8) | \ ((id##_VERSION_MINOR) & 0xFF)) #define TLS_1_2_VERSION_MAJOR 0x3 #define TLS_1_2_VERSION_MINOR 0x3 #define TLS_1_2_VERSION TLS_VERSION_NUMBER(TLS_1_2) #define TLS_1_3_VERSION_MAJOR 0x3 #define TLS_1_3_VERSION_MINOR 0x4 #define TLS_1_3_VERSION TLS_VERSION_NUMBER(TLS_1_3) /* Supported ciphers */ #define TLS_CIPHER_AES_GCM_128 51 #define TLS_CIPHER_AES_GCM_128_IV_SIZE 8 #define TLS_CIPHER_AES_GCM_128_KEY_SIZE 16 #define TLS_CIPHER_AES_GCM_128_SALT_SIZE 4 #define TLS_CIPHER_AES_GCM_128_TAG_SIZE 16 #define TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE 8 #define TLS_CIPHER_AES_GCM_256 52 #define TLS_CIPHER_AES_GCM_256_IV_SIZE 8 #define TLS_CIPHER_AES_GCM_256_KEY_SIZE 32 #define TLS_CIPHER_AES_GCM_256_SALT_SIZE 4 #define TLS_CIPHER_AES_GCM_256_TAG_SIZE 16 #define TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE 8 #define TLS_CIPHER_AES_CCM_128 53 #define TLS_CIPHER_AES_CCM_128_IV_SIZE 8 #define TLS_CIPHER_AES_CCM_128_KEY_SIZE 16 #define TLS_CIPHER_AES_CCM_128_SALT_SIZE 4 #define TLS_CIPHER_AES_CCM_128_TAG_SIZE 16 #define TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE 8 #define TLS_SET_RECORD_TYPE 1 #define TLS_GET_RECORD_TYPE 2 struct tls_crypto_info { __u16 version; __u16 cipher_type; }; struct tls12_crypto_info_aes_gcm_128 { struct tls_crypto_info info; unsigned char iv[TLS_CIPHER_AES_GCM_128_IV_SIZE]; unsigned char key[TLS_CIPHER_AES_GCM_128_KEY_SIZE]; unsigned char salt[TLS_CIPHER_AES_GCM_128_SALT_SIZE]; unsigned char rec_seq[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE]; }; struct tls12_crypto_info_aes_gcm_256 { struct tls_crypto_info info; unsigned char iv[TLS_CIPHER_AES_GCM_256_IV_SIZE]; unsigned char key[TLS_CIPHER_AES_GCM_256_KEY_SIZE]; unsigned char salt[TLS_CIPHER_AES_GCM_256_SALT_SIZE]; unsigned char rec_seq[TLS_CIPHER_AES_GCM_256_REC_SEQ_SIZE]; }; struct tls12_crypto_info_aes_ccm_128 { struct tls_crypto_info info; unsigned char iv[TLS_CIPHER_AES_CCM_128_IV_SIZE]; unsigned char key[TLS_CIPHER_AES_CCM_128_KEY_SIZE]; unsigned char salt[TLS_CIPHER_AES_CCM_128_SALT_SIZE]; unsigned char rec_seq[TLS_CIPHER_AES_CCM_128_REC_SEQ_SIZE]; }; enum { TLS_INFO_UNSPEC, TLS_INFO_VERSION, TLS_INFO_CIPHER, TLS_INFO_TXCONF, TLS_INFO_RXCONF, __TLS_INFO_MAX, }; #define TLS_INFO_MAX (__TLS_INFO_MAX - 1) #define TLS_CONF_BASE 1 #define TLS_CONF_SW 2 #define TLS_CONF_HW 3 #define TLS_CONF_HW_RECORD 4 #endif /* _LINUX_TLS_H */ linux/msdos_fs.h000064400000015463151027430560007705 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MSDOS_FS_H #define _LINUX_MSDOS_FS_H #include #include #include /* * The MS-DOS filesystem constants/structures */ #ifndef SECTOR_SIZE #define SECTOR_SIZE 512 /* sector size (bytes) */ #endif #define SECTOR_BITS 9 /* log2(SECTOR_SIZE) */ #define MSDOS_DPB (MSDOS_DPS) /* dir entries per block */ #define MSDOS_DPB_BITS 4 /* log2(MSDOS_DPB) */ #define MSDOS_DPS (SECTOR_SIZE / sizeof(struct msdos_dir_entry)) #define MSDOS_DPS_BITS 4 /* log2(MSDOS_DPS) */ #define MSDOS_LONGNAME 256 /* maximum name length */ #define CF_LE_W(v) le16_to_cpu(v) #define CF_LE_L(v) le32_to_cpu(v) #define CT_LE_W(v) cpu_to_le16(v) #define CT_LE_L(v) cpu_to_le32(v) #define MSDOS_ROOT_INO 1 /* The root inode number */ #define MSDOS_FSINFO_INO 2 /* Used for managing the FSINFO block */ #define MSDOS_DIR_BITS 5 /* log2(sizeof(struct msdos_dir_entry)) */ /* directory limit */ #define FAT_MAX_DIR_ENTRIES (65536) #define FAT_MAX_DIR_SIZE (FAT_MAX_DIR_ENTRIES << MSDOS_DIR_BITS) #define ATTR_NONE 0 /* no attribute bits */ #define ATTR_RO 1 /* read-only */ #define ATTR_HIDDEN 2 /* hidden */ #define ATTR_SYS 4 /* system */ #define ATTR_VOLUME 8 /* volume label */ #define ATTR_DIR 16 /* directory */ #define ATTR_ARCH 32 /* archived */ /* attribute bits that are copied "as is" */ #define ATTR_UNUSED (ATTR_VOLUME | ATTR_ARCH | ATTR_SYS | ATTR_HIDDEN) /* bits that are used by the Windows 95/Windows NT extended FAT */ #define ATTR_EXT (ATTR_RO | ATTR_HIDDEN | ATTR_SYS | ATTR_VOLUME) #define CASE_LOWER_BASE 8 /* base is lower case */ #define CASE_LOWER_EXT 16 /* extension is lower case */ #define DELETED_FLAG 0xe5 /* marks file as deleted when in name[0] */ #define IS_FREE(n) (!*(n) || *(n) == DELETED_FLAG) #define FAT_LFN_LEN 255 /* maximum long name length */ #define MSDOS_NAME 11 /* maximum name length */ #define MSDOS_SLOTS 21 /* max # of slots for short and long names */ #define MSDOS_DOT ". " /* ".", padded to MSDOS_NAME chars */ #define MSDOS_DOTDOT ".. " /* "..", padded to MSDOS_NAME chars */ #define FAT_FIRST_ENT(s, x) ((MSDOS_SB(s)->fat_bits == 32 ? 0x0FFFFF00 : \ MSDOS_SB(s)->fat_bits == 16 ? 0xFF00 : 0xF00) | (x)) /* start of data cluster's entry (number of reserved clusters) */ #define FAT_START_ENT 2 /* maximum number of clusters */ #define MAX_FAT12 0xFF4 #define MAX_FAT16 0xFFF4 #define MAX_FAT32 0x0FFFFFF6 #define MAX_FAT(s) (MSDOS_SB(s)->fat_bits == 32 ? MAX_FAT32 : \ MSDOS_SB(s)->fat_bits == 16 ? MAX_FAT16 : MAX_FAT12) /* bad cluster mark */ #define BAD_FAT12 0xFF7 #define BAD_FAT16 0xFFF7 #define BAD_FAT32 0x0FFFFFF7 /* standard EOF */ #define EOF_FAT12 0xFFF #define EOF_FAT16 0xFFFF #define EOF_FAT32 0x0FFFFFFF #define FAT_ENT_FREE (0) #define FAT_ENT_BAD (BAD_FAT32) #define FAT_ENT_EOF (EOF_FAT32) #define FAT_FSINFO_SIG1 0x41615252 #define FAT_FSINFO_SIG2 0x61417272 #define IS_FSINFO(x) (le32_to_cpu((x)->signature1) == FAT_FSINFO_SIG1 \ && le32_to_cpu((x)->signature2) == FAT_FSINFO_SIG2) #define FAT_STATE_DIRTY 0x01 struct __fat_dirent { long d_ino; __kernel_off_t d_off; unsigned short d_reclen; char d_name[256]; /* We must not include limits.h! */ }; /* * ioctl commands */ #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, struct __fat_dirent[2]) #define VFAT_IOCTL_READDIR_SHORT _IOR('r', 2, struct __fat_dirent[2]) /* has used 0x72 ('r') in collision, so skip a few */ #define FAT_IOCTL_GET_ATTRIBUTES _IOR('r', 0x10, __u32) #define FAT_IOCTL_SET_ATTRIBUTES _IOW('r', 0x11, __u32) /*Android kernel has used 0x12, so we use 0x13*/ #define FAT_IOCTL_GET_VOLUME_ID _IOR('r', 0x13, __u32) struct fat_boot_sector { __u8 ignored[3]; /* Boot strap short or near jump */ __u8 system_id[8]; /* Name - can be used to special case partition manager volumes */ __u8 sector_size[2]; /* bytes per logical sector */ __u8 sec_per_clus; /* sectors/cluster */ __le16 reserved; /* reserved sectors */ __u8 fats; /* number of FATs */ __u8 dir_entries[2]; /* root directory entries */ __u8 sectors[2]; /* number of sectors */ __u8 media; /* media code */ __le16 fat_length; /* sectors/FAT */ __le16 secs_track; /* sectors per track */ __le16 heads; /* number of heads */ __le32 hidden; /* hidden sectors (unused) */ __le32 total_sect; /* number of sectors (if sectors == 0) */ union { struct { /* Extended BPB Fields for FAT16 */ __u8 drive_number; /* Physical drive number */ __u8 state; /* undocumented, but used for mount state. */ __u8 signature; /* extended boot signature */ __u8 vol_id[4]; /* volume ID */ __u8 vol_label[11]; /* volume label */ __u8 fs_type[8]; /* file system type */ /* other fields are not added here */ } fat16; struct { /* only used by FAT32 */ __le32 length; /* sectors/FAT */ __le16 flags; /* bit 8: fat mirroring, low 4: active fat */ __u8 version[2]; /* major, minor filesystem version */ __le32 root_cluster; /* first cluster in root directory */ __le16 info_sector; /* filesystem info sector */ __le16 backup_boot; /* backup boot sector */ __le16 reserved2[6]; /* Unused */ /* Extended BPB Fields for FAT32 */ __u8 drive_number; /* Physical drive number */ __u8 state; /* undocumented, but used for mount state. */ __u8 signature; /* extended boot signature */ __u8 vol_id[4]; /* volume ID */ __u8 vol_label[11]; /* volume label */ __u8 fs_type[8]; /* file system type */ /* other fields are not added here */ } fat32; }; }; struct fat_boot_fsinfo { __le32 signature1; /* 0x41615252L */ __le32 reserved1[120]; /* Nothing as far as I can tell */ __le32 signature2; /* 0x61417272L */ __le32 free_clusters; /* Free cluster count. -1 if unknown */ __le32 next_cluster; /* Most recently allocated cluster */ __le32 reserved2[4]; }; struct msdos_dir_entry { __u8 name[MSDOS_NAME];/* name and extension */ __u8 attr; /* attribute bits */ __u8 lcase; /* Case for base and extension */ __u8 ctime_cs; /* Creation time, centiseconds (0-199) */ __le16 ctime; /* Creation time */ __le16 cdate; /* Creation date */ __le16 adate; /* Last access date */ __le16 starthi; /* High 16 bits of cluster in FAT32 */ __le16 time,date,start;/* time, date and first cluster */ __le32 size; /* file size (in bytes) */ }; /* Up to 13 characters of the name */ struct msdos_dir_slot { __u8 id; /* sequence number for slot */ __u8 name0_4[10]; /* first 5 characters in name */ __u8 attr; /* attribute byte */ __u8 reserved; /* always 0 */ __u8 alias_checksum; /* checksum for 8.3 alias */ __u8 name5_10[12]; /* 6 more characters in name */ __le16 start; /* starting cluster number, 0 in long slots */ __u8 name11_12[4]; /* last 2 characters in name */ }; #endif /* _LINUX_MSDOS_FS_H */ linux/dcbnl.h000064400000061226151027430560007150 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (c) 2008-2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307 USA. * * Author: Lucy Liu */ #ifndef __LINUX_DCBNL_H__ #define __LINUX_DCBNL_H__ #include /* IEEE 802.1Qaz std supported values */ #define IEEE_8021QAZ_MAX_TCS 8 #define IEEE_8021QAZ_TSA_STRICT 0 #define IEEE_8021QAZ_TSA_CB_SHAPER 1 #define IEEE_8021QAZ_TSA_ETS 2 #define IEEE_8021QAZ_TSA_VENDOR 255 /* This structure contains the IEEE 802.1Qaz ETS managed object * * @willing: willing bit in ETS configuration TLV * @ets_cap: indicates supported capacity of ets feature * @cbs: credit based shaper ets algorithm supported * @tc_tx_bw: tc tx bandwidth indexed by traffic class * @tc_rx_bw: tc rx bandwidth indexed by traffic class * @tc_tsa: TSA Assignment table, indexed by traffic class * @prio_tc: priority assignment table mapping 8021Qp to traffic class * @tc_reco_bw: recommended tc bandwidth indexed by traffic class for TLV * @tc_reco_tsa: recommended tc bandwidth indexed by traffic class for TLV * @reco_prio_tc: recommended tc tx bandwidth indexed by traffic class for TLV * * Recommended values are used to set fields in the ETS recommendation TLV * with hardware offloaded LLDP. * * ---- * TSA Assignment 8 bit identifiers * 0 strict priority * 1 credit-based shaper * 2 enhanced transmission selection * 3-254 reserved * 255 vendor specific */ struct ieee_ets { __u8 willing; __u8 ets_cap; __u8 cbs; __u8 tc_tx_bw[IEEE_8021QAZ_MAX_TCS]; __u8 tc_rx_bw[IEEE_8021QAZ_MAX_TCS]; __u8 tc_tsa[IEEE_8021QAZ_MAX_TCS]; __u8 prio_tc[IEEE_8021QAZ_MAX_TCS]; __u8 tc_reco_bw[IEEE_8021QAZ_MAX_TCS]; __u8 tc_reco_tsa[IEEE_8021QAZ_MAX_TCS]; __u8 reco_prio_tc[IEEE_8021QAZ_MAX_TCS]; }; /* This structure contains rate limit extension to the IEEE 802.1Qaz ETS * managed object. * Values are 64 bits long and specified in Kbps to enable usage over both * slow and very fast networks. * * @tc_maxrate: maximal tc tx bandwidth indexed by traffic class */ struct ieee_maxrate { __u64 tc_maxrate[IEEE_8021QAZ_MAX_TCS]; }; enum dcbnl_cndd_states { DCB_CNDD_RESET = 0, DCB_CNDD_EDGE, DCB_CNDD_INTERIOR, DCB_CNDD_INTERIOR_READY, }; /* This structure contains the IEEE 802.1Qau QCN managed object. * *@rpg_enable: enable QCN RP *@rppp_max_rps: maximum number of RPs allowed for this CNPV on this port *@rpg_time_reset: time between rate increases if no CNMs received. * given in u-seconds *@rpg_byte_reset: transmitted data between rate increases if no CNMs received. * given in Bytes *@rpg_threshold: The number of times rpByteStage or rpTimeStage can count * before RP rate control state machine advances states *@rpg_max_rate: the maxinun rate, in Mbits per second, * at which an RP can transmit *@rpg_ai_rate: The rate, in Mbits per second, * used to increase rpTargetRate in the RPR_ACTIVE_INCREASE *@rpg_hai_rate: The rate, in Mbits per second, * used to increase rpTargetRate in the RPR_HYPER_INCREASE state *@rpg_gd: Upon CNM receive, flow rate is limited to (Fb/Gd)*CurrentRate. * rpgGd is given as log2(Gd), where Gd may only be powers of 2 *@rpg_min_dec_fac: The minimum factor by which the current transmit rate * can be changed by reception of a CNM. * value is given as percentage (1-100) *@rpg_min_rate: The minimum value, in bits per second, for rate to limit *@cndd_state_machine: The state of the congestion notification domain * defense state machine, as defined by IEEE 802.3Qau * section 32.1.1. In the interior ready state, * the QCN capable hardware may add CN-TAG TLV to the * outgoing traffic, to specifically identify outgoing * flows. */ struct ieee_qcn { __u8 rpg_enable[IEEE_8021QAZ_MAX_TCS]; __u32 rppp_max_rps[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_time_reset[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_byte_reset[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_threshold[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_max_rate[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_ai_rate[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_hai_rate[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_gd[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_min_dec_fac[IEEE_8021QAZ_MAX_TCS]; __u32 rpg_min_rate[IEEE_8021QAZ_MAX_TCS]; __u32 cndd_state_machine[IEEE_8021QAZ_MAX_TCS]; }; /* This structure contains the IEEE 802.1Qau QCN statistics. * *@rppp_rp_centiseconds: the number of RP-centiseconds accumulated * by RPs at this priority level on this Port *@rppp_created_rps: number of active RPs(flows) that react to CNMs */ struct ieee_qcn_stats { __u64 rppp_rp_centiseconds[IEEE_8021QAZ_MAX_TCS]; __u32 rppp_created_rps[IEEE_8021QAZ_MAX_TCS]; }; /* This structure contains the IEEE 802.1Qaz PFC managed object * * @pfc_cap: Indicates the number of traffic classes on the local device * that may simultaneously have PFC enabled. * @pfc_en: bitmap indicating pfc enabled traffic classes * @mbc: enable macsec bypass capability * @delay: the allowance made for a round-trip propagation delay of the * link in bits. * @requests: count of the sent pfc frames * @indications: count of the received pfc frames */ struct ieee_pfc { __u8 pfc_cap; __u8 pfc_en; __u8 mbc; __u16 delay; __u64 requests[IEEE_8021QAZ_MAX_TCS]; __u64 indications[IEEE_8021QAZ_MAX_TCS]; }; #define IEEE_8021Q_MAX_PRIORITIES 8 #define DCBX_MAX_BUFFERS 8 struct dcbnl_buffer { /* priority to buffer mapping */ __u8 prio2buffer[IEEE_8021Q_MAX_PRIORITIES]; /* buffer size in Bytes */ __u32 buffer_size[DCBX_MAX_BUFFERS]; __u32 total_size; }; /* CEE DCBX std supported values */ #define CEE_DCBX_MAX_PGS 8 #define CEE_DCBX_MAX_PRIO 8 /** * struct cee_pg - CEE Priority-Group managed object * * @willing: willing bit in the PG tlv * @error: error bit in the PG tlv * @pg_en: enable bit of the PG feature * @tcs_supported: number of traffic classes supported * @pg_bw: bandwidth percentage for each priority group * @prio_pg: priority to PG mapping indexed by priority */ struct cee_pg { __u8 willing; __u8 error; __u8 pg_en; __u8 tcs_supported; __u8 pg_bw[CEE_DCBX_MAX_PGS]; __u8 prio_pg[CEE_DCBX_MAX_PGS]; }; /** * struct cee_pfc - CEE PFC managed object * * @willing: willing bit in the PFC tlv * @error: error bit in the PFC tlv * @pfc_en: bitmap indicating pfc enabled traffic classes * @tcs_supported: number of traffic classes supported */ struct cee_pfc { __u8 willing; __u8 error; __u8 pfc_en; __u8 tcs_supported; }; /* IEEE 802.1Qaz std supported values */ #define IEEE_8021QAZ_APP_SEL_ETHERTYPE 1 #define IEEE_8021QAZ_APP_SEL_STREAM 2 #define IEEE_8021QAZ_APP_SEL_DGRAM 3 #define IEEE_8021QAZ_APP_SEL_ANY 4 #define IEEE_8021QAZ_APP_SEL_DSCP 5 /* This structure contains the IEEE 802.1Qaz APP managed object. This * object is also used for the CEE std as well. * * @selector: protocol identifier type * @protocol: protocol of type indicated * @priority: 3-bit unsigned integer indicating priority for IEEE * 8-bit 802.1p user priority bitmap for CEE * * ---- * Selector field values for IEEE 802.1Qaz * 0 Reserved * 1 Ethertype * 2 Well known port number over TCP or SCTP * 3 Well known port number over UDP or DCCP * 4 Well known port number over TCP, SCTP, UDP, or DCCP * 5-7 Reserved * * Selector field values for CEE * 0 Ethertype * 1 Well known port number over TCP or UDP * 2-3 Reserved */ struct dcb_app { __u8 selector; __u8 priority; __u16 protocol; }; /** * struct dcb_peer_app_info - APP feature information sent by the peer * * @willing: willing bit in the peer APP tlv * @error: error bit in the peer APP tlv * * In addition to this information the full peer APP tlv also contains * a table of 'app_count' APP objects defined above. */ struct dcb_peer_app_info { __u8 willing; __u8 error; }; struct dcbmsg { __u8 dcb_family; __u8 cmd; __u16 dcb_pad; }; /** * enum dcbnl_commands - supported DCB commands * * @DCB_CMD_UNDEFINED: unspecified command to catch errors * @DCB_CMD_GSTATE: request the state of DCB in the device * @DCB_CMD_SSTATE: set the state of DCB in the device * @DCB_CMD_PGTX_GCFG: request the priority group configuration for Tx * @DCB_CMD_PGTX_SCFG: set the priority group configuration for Tx * @DCB_CMD_PGRX_GCFG: request the priority group configuration for Rx * @DCB_CMD_PGRX_SCFG: set the priority group configuration for Rx * @DCB_CMD_PFC_GCFG: request the priority flow control configuration * @DCB_CMD_PFC_SCFG: set the priority flow control configuration * @DCB_CMD_SET_ALL: apply all changes to the underlying device * @DCB_CMD_GPERM_HWADDR: get the permanent MAC address of the underlying * device. Only useful when using bonding. * @DCB_CMD_GCAP: request the DCB capabilities of the device * @DCB_CMD_GNUMTCS: get the number of traffic classes currently supported * @DCB_CMD_SNUMTCS: set the number of traffic classes * @DCB_CMD_GBCN: set backward congestion notification configuration * @DCB_CMD_SBCN: get backward congestion notification configration. * @DCB_CMD_GAPP: get application protocol configuration * @DCB_CMD_SAPP: set application protocol configuration * @DCB_CMD_IEEE_SET: set IEEE 802.1Qaz configuration * @DCB_CMD_IEEE_GET: get IEEE 802.1Qaz configuration * @DCB_CMD_GDCBX: get DCBX engine configuration * @DCB_CMD_SDCBX: set DCBX engine configuration * @DCB_CMD_GFEATCFG: get DCBX features flags * @DCB_CMD_SFEATCFG: set DCBX features negotiation flags * @DCB_CMD_CEE_GET: get CEE aggregated configuration * @DCB_CMD_IEEE_DEL: delete IEEE 802.1Qaz configuration */ enum dcbnl_commands { DCB_CMD_UNDEFINED, DCB_CMD_GSTATE, DCB_CMD_SSTATE, DCB_CMD_PGTX_GCFG, DCB_CMD_PGTX_SCFG, DCB_CMD_PGRX_GCFG, DCB_CMD_PGRX_SCFG, DCB_CMD_PFC_GCFG, DCB_CMD_PFC_SCFG, DCB_CMD_SET_ALL, DCB_CMD_GPERM_HWADDR, DCB_CMD_GCAP, DCB_CMD_GNUMTCS, DCB_CMD_SNUMTCS, DCB_CMD_PFC_GSTATE, DCB_CMD_PFC_SSTATE, DCB_CMD_BCN_GCFG, DCB_CMD_BCN_SCFG, DCB_CMD_GAPP, DCB_CMD_SAPP, DCB_CMD_IEEE_SET, DCB_CMD_IEEE_GET, DCB_CMD_GDCBX, DCB_CMD_SDCBX, DCB_CMD_GFEATCFG, DCB_CMD_SFEATCFG, DCB_CMD_CEE_GET, DCB_CMD_IEEE_DEL, __DCB_CMD_ENUM_MAX, DCB_CMD_MAX = __DCB_CMD_ENUM_MAX - 1, }; /** * enum dcbnl_attrs - DCB top-level netlink attributes * * @DCB_ATTR_UNDEFINED: unspecified attribute to catch errors * @DCB_ATTR_IFNAME: interface name of the underlying device (NLA_STRING) * @DCB_ATTR_STATE: enable state of DCB in the device (NLA_U8) * @DCB_ATTR_PFC_STATE: enable state of PFC in the device (NLA_U8) * @DCB_ATTR_PFC_CFG: priority flow control configuration (NLA_NESTED) * @DCB_ATTR_NUM_TC: number of traffic classes supported in the device (NLA_U8) * @DCB_ATTR_PG_CFG: priority group configuration (NLA_NESTED) * @DCB_ATTR_SET_ALL: bool to commit changes to hardware or not (NLA_U8) * @DCB_ATTR_PERM_HWADDR: MAC address of the physical device (NLA_NESTED) * @DCB_ATTR_CAP: DCB capabilities of the device (NLA_NESTED) * @DCB_ATTR_NUMTCS: number of traffic classes supported (NLA_NESTED) * @DCB_ATTR_BCN: backward congestion notification configuration (NLA_NESTED) * @DCB_ATTR_IEEE: IEEE 802.1Qaz supported attributes (NLA_NESTED) * @DCB_ATTR_DCBX: DCBX engine configuration in the device (NLA_U8) * @DCB_ATTR_FEATCFG: DCBX features flags (NLA_NESTED) * @DCB_ATTR_CEE: CEE std supported attributes (NLA_NESTED) */ enum dcbnl_attrs { DCB_ATTR_UNDEFINED, DCB_ATTR_IFNAME, DCB_ATTR_STATE, DCB_ATTR_PFC_STATE, DCB_ATTR_PFC_CFG, DCB_ATTR_NUM_TC, DCB_ATTR_PG_CFG, DCB_ATTR_SET_ALL, DCB_ATTR_PERM_HWADDR, DCB_ATTR_CAP, DCB_ATTR_NUMTCS, DCB_ATTR_BCN, DCB_ATTR_APP, /* IEEE std attributes */ DCB_ATTR_IEEE, DCB_ATTR_DCBX, DCB_ATTR_FEATCFG, /* CEE nested attributes */ DCB_ATTR_CEE, __DCB_ATTR_ENUM_MAX, DCB_ATTR_MAX = __DCB_ATTR_ENUM_MAX - 1, }; /** * enum ieee_attrs - IEEE 802.1Qaz get/set attributes * * @DCB_ATTR_IEEE_UNSPEC: unspecified * @DCB_ATTR_IEEE_ETS: negotiated ETS configuration * @DCB_ATTR_IEEE_PFC: negotiated PFC configuration * @DCB_ATTR_IEEE_APP_TABLE: negotiated APP configuration * @DCB_ATTR_IEEE_PEER_ETS: peer ETS configuration - get only * @DCB_ATTR_IEEE_PEER_PFC: peer PFC configuration - get only * @DCB_ATTR_IEEE_PEER_APP: peer APP tlv - get only */ enum ieee_attrs { DCB_ATTR_IEEE_UNSPEC, DCB_ATTR_IEEE_ETS, DCB_ATTR_IEEE_PFC, DCB_ATTR_IEEE_APP_TABLE, DCB_ATTR_IEEE_PEER_ETS, DCB_ATTR_IEEE_PEER_PFC, DCB_ATTR_IEEE_PEER_APP, DCB_ATTR_IEEE_MAXRATE, DCB_ATTR_IEEE_QCN, DCB_ATTR_IEEE_QCN_STATS, DCB_ATTR_DCB_BUFFER, __DCB_ATTR_IEEE_MAX }; #define DCB_ATTR_IEEE_MAX (__DCB_ATTR_IEEE_MAX - 1) enum ieee_attrs_app { DCB_ATTR_IEEE_APP_UNSPEC, DCB_ATTR_IEEE_APP, __DCB_ATTR_IEEE_APP_MAX }; #define DCB_ATTR_IEEE_APP_MAX (__DCB_ATTR_IEEE_APP_MAX - 1) /** * enum cee_attrs - CEE DCBX get attributes. * * @DCB_ATTR_CEE_UNSPEC: unspecified * @DCB_ATTR_CEE_PEER_PG: peer PG configuration - get only * @DCB_ATTR_CEE_PEER_PFC: peer PFC configuration - get only * @DCB_ATTR_CEE_PEER_APP_TABLE: peer APP tlv - get only * @DCB_ATTR_CEE_TX_PG: TX PG configuration (DCB_CMD_PGTX_GCFG) * @DCB_ATTR_CEE_RX_PG: RX PG configuration (DCB_CMD_PGRX_GCFG) * @DCB_ATTR_CEE_PFC: PFC configuration (DCB_CMD_PFC_GCFG) * @DCB_ATTR_CEE_APP_TABLE: APP configuration (multi DCB_CMD_GAPP) * @DCB_ATTR_CEE_FEAT: DCBX features flags (DCB_CMD_GFEATCFG) * * An aggregated collection of the cee std negotiated parameters. */ enum cee_attrs { DCB_ATTR_CEE_UNSPEC, DCB_ATTR_CEE_PEER_PG, DCB_ATTR_CEE_PEER_PFC, DCB_ATTR_CEE_PEER_APP_TABLE, DCB_ATTR_CEE_TX_PG, DCB_ATTR_CEE_RX_PG, DCB_ATTR_CEE_PFC, DCB_ATTR_CEE_APP_TABLE, DCB_ATTR_CEE_FEAT, __DCB_ATTR_CEE_MAX }; #define DCB_ATTR_CEE_MAX (__DCB_ATTR_CEE_MAX - 1) enum peer_app_attr { DCB_ATTR_CEE_PEER_APP_UNSPEC, DCB_ATTR_CEE_PEER_APP_INFO, DCB_ATTR_CEE_PEER_APP, __DCB_ATTR_CEE_PEER_APP_MAX }; #define DCB_ATTR_CEE_PEER_APP_MAX (__DCB_ATTR_CEE_PEER_APP_MAX - 1) enum cee_attrs_app { DCB_ATTR_CEE_APP_UNSPEC, DCB_ATTR_CEE_APP, __DCB_ATTR_CEE_APP_MAX }; #define DCB_ATTR_CEE_APP_MAX (__DCB_ATTR_CEE_APP_MAX - 1) /** * enum dcbnl_pfc_attrs - DCB Priority Flow Control user priority nested attrs * * @DCB_PFC_UP_ATTR_UNDEFINED: unspecified attribute to catch errors * @DCB_PFC_UP_ATTR_0: Priority Flow Control value for User Priority 0 (NLA_U8) * @DCB_PFC_UP_ATTR_1: Priority Flow Control value for User Priority 1 (NLA_U8) * @DCB_PFC_UP_ATTR_2: Priority Flow Control value for User Priority 2 (NLA_U8) * @DCB_PFC_UP_ATTR_3: Priority Flow Control value for User Priority 3 (NLA_U8) * @DCB_PFC_UP_ATTR_4: Priority Flow Control value for User Priority 4 (NLA_U8) * @DCB_PFC_UP_ATTR_5: Priority Flow Control value for User Priority 5 (NLA_U8) * @DCB_PFC_UP_ATTR_6: Priority Flow Control value for User Priority 6 (NLA_U8) * @DCB_PFC_UP_ATTR_7: Priority Flow Control value for User Priority 7 (NLA_U8) * @DCB_PFC_UP_ATTR_MAX: highest attribute number currently defined * @DCB_PFC_UP_ATTR_ALL: apply to all priority flow control attrs (NLA_FLAG) * */ enum dcbnl_pfc_up_attrs { DCB_PFC_UP_ATTR_UNDEFINED, DCB_PFC_UP_ATTR_0, DCB_PFC_UP_ATTR_1, DCB_PFC_UP_ATTR_2, DCB_PFC_UP_ATTR_3, DCB_PFC_UP_ATTR_4, DCB_PFC_UP_ATTR_5, DCB_PFC_UP_ATTR_6, DCB_PFC_UP_ATTR_7, DCB_PFC_UP_ATTR_ALL, __DCB_PFC_UP_ATTR_ENUM_MAX, DCB_PFC_UP_ATTR_MAX = __DCB_PFC_UP_ATTR_ENUM_MAX - 1, }; /** * enum dcbnl_pg_attrs - DCB Priority Group attributes * * @DCB_PG_ATTR_UNDEFINED: unspecified attribute to catch errors * @DCB_PG_ATTR_TC_0: Priority Group Traffic Class 0 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_1: Priority Group Traffic Class 1 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_2: Priority Group Traffic Class 2 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_3: Priority Group Traffic Class 3 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_4: Priority Group Traffic Class 4 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_5: Priority Group Traffic Class 5 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_6: Priority Group Traffic Class 6 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_7: Priority Group Traffic Class 7 configuration (NLA_NESTED) * @DCB_PG_ATTR_TC_MAX: highest attribute number currently defined * @DCB_PG_ATTR_TC_ALL: apply to all traffic classes (NLA_NESTED) * @DCB_PG_ATTR_BW_ID_0: Percent of link bandwidth for Priority Group 0 (NLA_U8) * @DCB_PG_ATTR_BW_ID_1: Percent of link bandwidth for Priority Group 1 (NLA_U8) * @DCB_PG_ATTR_BW_ID_2: Percent of link bandwidth for Priority Group 2 (NLA_U8) * @DCB_PG_ATTR_BW_ID_3: Percent of link bandwidth for Priority Group 3 (NLA_U8) * @DCB_PG_ATTR_BW_ID_4: Percent of link bandwidth for Priority Group 4 (NLA_U8) * @DCB_PG_ATTR_BW_ID_5: Percent of link bandwidth for Priority Group 5 (NLA_U8) * @DCB_PG_ATTR_BW_ID_6: Percent of link bandwidth for Priority Group 6 (NLA_U8) * @DCB_PG_ATTR_BW_ID_7: Percent of link bandwidth for Priority Group 7 (NLA_U8) * @DCB_PG_ATTR_BW_ID_MAX: highest attribute number currently defined * @DCB_PG_ATTR_BW_ID_ALL: apply to all priority groups (NLA_FLAG) * */ enum dcbnl_pg_attrs { DCB_PG_ATTR_UNDEFINED, DCB_PG_ATTR_TC_0, DCB_PG_ATTR_TC_1, DCB_PG_ATTR_TC_2, DCB_PG_ATTR_TC_3, DCB_PG_ATTR_TC_4, DCB_PG_ATTR_TC_5, DCB_PG_ATTR_TC_6, DCB_PG_ATTR_TC_7, DCB_PG_ATTR_TC_MAX, DCB_PG_ATTR_TC_ALL, DCB_PG_ATTR_BW_ID_0, DCB_PG_ATTR_BW_ID_1, DCB_PG_ATTR_BW_ID_2, DCB_PG_ATTR_BW_ID_3, DCB_PG_ATTR_BW_ID_4, DCB_PG_ATTR_BW_ID_5, DCB_PG_ATTR_BW_ID_6, DCB_PG_ATTR_BW_ID_7, DCB_PG_ATTR_BW_ID_MAX, DCB_PG_ATTR_BW_ID_ALL, __DCB_PG_ATTR_ENUM_MAX, DCB_PG_ATTR_MAX = __DCB_PG_ATTR_ENUM_MAX - 1, }; /** * enum dcbnl_tc_attrs - DCB Traffic Class attributes * * @DCB_TC_ATTR_PARAM_UNDEFINED: unspecified attribute to catch errors * @DCB_TC_ATTR_PARAM_PGID: (NLA_U8) Priority group the traffic class belongs to * Valid values are: 0-7 * @DCB_TC_ATTR_PARAM_UP_MAPPING: (NLA_U8) Traffic class to user priority map * Some devices may not support changing the * user priority map of a TC. * @DCB_TC_ATTR_PARAM_STRICT_PRIO: (NLA_U8) Strict priority setting * 0 - none * 1 - group strict * 2 - link strict * @DCB_TC_ATTR_PARAM_BW_PCT: optional - (NLA_U8) If supported by the device and * not configured to use link strict priority, * this is the percentage of bandwidth of the * priority group this traffic class belongs to * @DCB_TC_ATTR_PARAM_ALL: (NLA_FLAG) all traffic class parameters * */ enum dcbnl_tc_attrs { DCB_TC_ATTR_PARAM_UNDEFINED, DCB_TC_ATTR_PARAM_PGID, DCB_TC_ATTR_PARAM_UP_MAPPING, DCB_TC_ATTR_PARAM_STRICT_PRIO, DCB_TC_ATTR_PARAM_BW_PCT, DCB_TC_ATTR_PARAM_ALL, __DCB_TC_ATTR_PARAM_ENUM_MAX, DCB_TC_ATTR_PARAM_MAX = __DCB_TC_ATTR_PARAM_ENUM_MAX - 1, }; /** * enum dcbnl_cap_attrs - DCB Capability attributes * * @DCB_CAP_ATTR_UNDEFINED: unspecified attribute to catch errors * @DCB_CAP_ATTR_ALL: (NLA_FLAG) all capability parameters * @DCB_CAP_ATTR_PG: (NLA_U8) device supports Priority Groups * @DCB_CAP_ATTR_PFC: (NLA_U8) device supports Priority Flow Control * @DCB_CAP_ATTR_UP2TC: (NLA_U8) device supports user priority to * traffic class mapping * @DCB_CAP_ATTR_PG_TCS: (NLA_U8) bitmap where each bit represents a * number of traffic classes the device * can be configured to use for Priority Groups * @DCB_CAP_ATTR_PFC_TCS: (NLA_U8) bitmap where each bit represents a * number of traffic classes the device can be * configured to use for Priority Flow Control * @DCB_CAP_ATTR_GSP: (NLA_U8) device supports group strict priority * @DCB_CAP_ATTR_BCN: (NLA_U8) device supports Backwards Congestion * Notification * @DCB_CAP_ATTR_DCBX: (NLA_U8) device supports DCBX engine * */ enum dcbnl_cap_attrs { DCB_CAP_ATTR_UNDEFINED, DCB_CAP_ATTR_ALL, DCB_CAP_ATTR_PG, DCB_CAP_ATTR_PFC, DCB_CAP_ATTR_UP2TC, DCB_CAP_ATTR_PG_TCS, DCB_CAP_ATTR_PFC_TCS, DCB_CAP_ATTR_GSP, DCB_CAP_ATTR_BCN, DCB_CAP_ATTR_DCBX, __DCB_CAP_ATTR_ENUM_MAX, DCB_CAP_ATTR_MAX = __DCB_CAP_ATTR_ENUM_MAX - 1, }; /** * DCBX capability flags * * @DCB_CAP_DCBX_HOST: DCBX negotiation is performed by the host LLDP agent. * 'set' routines are used to configure the device with * the negotiated parameters * * @DCB_CAP_DCBX_LLD_MANAGED: DCBX negotiation is not performed in the host but * by another entity * 'get' routines are used to retrieve the * negotiated parameters * 'set' routines can be used to set the initial * negotiation configuration * * @DCB_CAP_DCBX_VER_CEE: for a non-host DCBX engine, indicates the engine * supports the CEE protocol flavor * * @DCB_CAP_DCBX_VER_IEEE: for a non-host DCBX engine, indicates the engine * supports the IEEE protocol flavor * * @DCB_CAP_DCBX_STATIC: for a non-host DCBX engine, indicates the engine * supports static configuration (i.e no actual * negotiation is performed negotiated parameters equal * the initial configuration) * */ #define DCB_CAP_DCBX_HOST 0x01 #define DCB_CAP_DCBX_LLD_MANAGED 0x02 #define DCB_CAP_DCBX_VER_CEE 0x04 #define DCB_CAP_DCBX_VER_IEEE 0x08 #define DCB_CAP_DCBX_STATIC 0x10 /** * enum dcbnl_numtcs_attrs - number of traffic classes * * @DCB_NUMTCS_ATTR_UNDEFINED: unspecified attribute to catch errors * @DCB_NUMTCS_ATTR_ALL: (NLA_FLAG) all traffic class attributes * @DCB_NUMTCS_ATTR_PG: (NLA_U8) number of traffic classes used for * priority groups * @DCB_NUMTCS_ATTR_PFC: (NLA_U8) number of traffic classes which can * support priority flow control */ enum dcbnl_numtcs_attrs { DCB_NUMTCS_ATTR_UNDEFINED, DCB_NUMTCS_ATTR_ALL, DCB_NUMTCS_ATTR_PG, DCB_NUMTCS_ATTR_PFC, __DCB_NUMTCS_ATTR_ENUM_MAX, DCB_NUMTCS_ATTR_MAX = __DCB_NUMTCS_ATTR_ENUM_MAX - 1, }; enum dcbnl_bcn_attrs{ DCB_BCN_ATTR_UNDEFINED = 0, DCB_BCN_ATTR_RP_0, DCB_BCN_ATTR_RP_1, DCB_BCN_ATTR_RP_2, DCB_BCN_ATTR_RP_3, DCB_BCN_ATTR_RP_4, DCB_BCN_ATTR_RP_5, DCB_BCN_ATTR_RP_6, DCB_BCN_ATTR_RP_7, DCB_BCN_ATTR_RP_ALL, DCB_BCN_ATTR_BCNA_0, DCB_BCN_ATTR_BCNA_1, DCB_BCN_ATTR_ALPHA, DCB_BCN_ATTR_BETA, DCB_BCN_ATTR_GD, DCB_BCN_ATTR_GI, DCB_BCN_ATTR_TMAX, DCB_BCN_ATTR_TD, DCB_BCN_ATTR_RMIN, DCB_BCN_ATTR_W, DCB_BCN_ATTR_RD, DCB_BCN_ATTR_RU, DCB_BCN_ATTR_WRTT, DCB_BCN_ATTR_RI, DCB_BCN_ATTR_C, DCB_BCN_ATTR_ALL, __DCB_BCN_ATTR_ENUM_MAX, DCB_BCN_ATTR_MAX = __DCB_BCN_ATTR_ENUM_MAX - 1, }; /** * enum dcb_general_attr_values - general DCB attribute values * * @DCB_ATTR_UNDEFINED: value used to indicate an attribute is not supported * */ enum dcb_general_attr_values { DCB_ATTR_VALUE_UNDEFINED = 0xff }; #define DCB_APP_IDTYPE_ETHTYPE 0x00 #define DCB_APP_IDTYPE_PORTNUM 0x01 enum dcbnl_app_attrs { DCB_APP_ATTR_UNDEFINED, DCB_APP_ATTR_IDTYPE, DCB_APP_ATTR_ID, DCB_APP_ATTR_PRIORITY, __DCB_APP_ATTR_ENUM_MAX, DCB_APP_ATTR_MAX = __DCB_APP_ATTR_ENUM_MAX - 1, }; /** * enum dcbnl_featcfg_attrs - features conifiguration flags * * @DCB_FEATCFG_ATTR_UNDEFINED: unspecified attribute to catch errors * @DCB_FEATCFG_ATTR_ALL: (NLA_FLAG) all features configuration attributes * @DCB_FEATCFG_ATTR_PG: (NLA_U8) configuration flags for priority groups * @DCB_FEATCFG_ATTR_PFC: (NLA_U8) configuration flags for priority * flow control * @DCB_FEATCFG_ATTR_APP: (NLA_U8) configuration flags for application TLV * */ #define DCB_FEATCFG_ERROR 0x01 /* error in feature resolution */ #define DCB_FEATCFG_ENABLE 0x02 /* enable feature */ #define DCB_FEATCFG_WILLING 0x04 /* feature is willing */ #define DCB_FEATCFG_ADVERTISE 0x08 /* advertise feature */ enum dcbnl_featcfg_attrs { DCB_FEATCFG_ATTR_UNDEFINED, DCB_FEATCFG_ATTR_ALL, DCB_FEATCFG_ATTR_PG, DCB_FEATCFG_ATTR_PFC, DCB_FEATCFG_ATTR_APP, __DCB_FEATCFG_ATTR_ENUM_MAX, DCB_FEATCFG_ATTR_MAX = __DCB_FEATCFG_ATTR_ENUM_MAX - 1, }; #endif /* __LINUX_DCBNL_H__ */ linux/matroxfb.h000064400000002670151027430560007706 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_MATROXFB_H__ #define __LINUX_MATROXFB_H__ #include #include #include #include struct matroxioc_output_mode { __u32 output; /* which output */ #define MATROXFB_OUTPUT_PRIMARY 0x0000 #define MATROXFB_OUTPUT_SECONDARY 0x0001 #define MATROXFB_OUTPUT_DFP 0x0002 __u32 mode; /* which mode */ #define MATROXFB_OUTPUT_MODE_PAL 0x0001 #define MATROXFB_OUTPUT_MODE_NTSC 0x0002 #define MATROXFB_OUTPUT_MODE_MONITOR 0x0080 }; #define MATROXFB_SET_OUTPUT_MODE _IOW('n',0xFA,size_t) #define MATROXFB_GET_OUTPUT_MODE _IOWR('n',0xFA,size_t) /* bitfield */ #define MATROXFB_OUTPUT_CONN_PRIMARY (1 << MATROXFB_OUTPUT_PRIMARY) #define MATROXFB_OUTPUT_CONN_SECONDARY (1 << MATROXFB_OUTPUT_SECONDARY) #define MATROXFB_OUTPUT_CONN_DFP (1 << MATROXFB_OUTPUT_DFP) /* connect these outputs to this framebuffer */ #define MATROXFB_SET_OUTPUT_CONNECTION _IOW('n',0xF8,size_t) /* which outputs are connected to this framebuffer */ #define MATROXFB_GET_OUTPUT_CONNECTION _IOR('n',0xF8,size_t) /* which outputs are available for this framebuffer */ #define MATROXFB_GET_AVAILABLE_OUTPUTS _IOR('n',0xF9,size_t) /* which outputs exist on this framebuffer */ #define MATROXFB_GET_ALL_OUTPUTS _IOR('n',0xFB,size_t) enum matroxfb_ctrl_id { MATROXFB_CID_TESTOUT = V4L2_CID_PRIVATE_BASE, MATROXFB_CID_DEFLICKER, MATROXFB_CID_LAST }; #endif linux/sched/types.h000064400000005200151027430560010306 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SCHED_TYPES_H #define _LINUX_SCHED_TYPES_H #include struct sched_param { int sched_priority; }; #define SCHED_ATTR_SIZE_VER0 48 /* sizeof first published struct */ /* * Extended scheduling parameters data structure. * * This is needed because the original struct sched_param can not be * altered without introducing ABI issues with legacy applications * (e.g., in sched_getparam()). * * However, the possibility of specifying more than just a priority for * the tasks may be useful for a wide variety of application fields, e.g., * multimedia, streaming, automation and control, and many others. * * This variant (sched_attr) is meant at describing a so-called * sporadic time-constrained task. In such model a task is specified by: * - the activation period or minimum instance inter-arrival time; * - the maximum (or average, depending on the actual scheduling * discipline) computation time of all instances, a.k.a. runtime; * - the deadline (relative to the actual activation time) of each * instance. * Very briefly, a periodic (sporadic) task asks for the execution of * some specific computation --which is typically called an instance-- * (at most) every period. Moreover, each instance typically lasts no more * than the runtime and must be completed by time instant t equal to * the instance activation time + the deadline. * * This is reflected by the actual fields of the sched_attr structure: * * @size size of the structure, for fwd/bwd compat. * * @sched_policy task's scheduling policy * @sched_flags for customizing the scheduler behaviour * @sched_nice task's nice value (SCHED_NORMAL/BATCH) * @sched_priority task's static priority (SCHED_FIFO/RR) * @sched_deadline representative of the task's deadline * @sched_runtime representative of the task's runtime * @sched_period representative of the task's period * * Given this task model, there are a multiplicity of scheduling algorithms * and policies, that can be used to ensure all the tasks will make their * timing constraints. * * As of now, the SCHED_DEADLINE policy (sched_dl scheduling class) is the * only user of this new interface. More information about the algorithm * available in the scheduling class file or in Documentation/. */ struct sched_attr { __u32 size; __u32 sched_policy; __u64 sched_flags; /* SCHED_NORMAL, SCHED_BATCH */ __s32 sched_nice; /* SCHED_FIFO, SCHED_RR */ __u32 sched_priority; /* SCHED_DEADLINE */ __u64 sched_runtime; __u64 sched_deadline; __u64 sched_period; }; #endif /* _LINUX_SCHED_TYPES_H */ linux/virtio_iommu.h000064400000007307151027430560010610 0ustar00/* SPDX-License-Identifier: BSD-3-Clause */ /* * Virtio-iommu definition v0.12 * * Copyright (C) 2019 Arm Ltd. */ #ifndef _LINUX_VIRTIO_IOMMU_H #define _LINUX_VIRTIO_IOMMU_H #include /* Feature bits */ #define VIRTIO_IOMMU_F_INPUT_RANGE 0 #define VIRTIO_IOMMU_F_DOMAIN_RANGE 1 #define VIRTIO_IOMMU_F_MAP_UNMAP 2 #define VIRTIO_IOMMU_F_BYPASS 3 #define VIRTIO_IOMMU_F_PROBE 4 #define VIRTIO_IOMMU_F_MMIO 5 struct virtio_iommu_range_64 { __le64 start; __le64 end; }; struct virtio_iommu_range_32 { __le32 start; __le32 end; }; struct virtio_iommu_config { /* Supported page sizes */ __le64 page_size_mask; /* Supported IOVA range */ struct virtio_iommu_range_64 input_range; /* Max domain ID size */ struct virtio_iommu_range_32 domain_range; /* Probe buffer size */ __le32 probe_size; }; /* Request types */ #define VIRTIO_IOMMU_T_ATTACH 0x01 #define VIRTIO_IOMMU_T_DETACH 0x02 #define VIRTIO_IOMMU_T_MAP 0x03 #define VIRTIO_IOMMU_T_UNMAP 0x04 #define VIRTIO_IOMMU_T_PROBE 0x05 /* Status types */ #define VIRTIO_IOMMU_S_OK 0x00 #define VIRTIO_IOMMU_S_IOERR 0x01 #define VIRTIO_IOMMU_S_UNSUPP 0x02 #define VIRTIO_IOMMU_S_DEVERR 0x03 #define VIRTIO_IOMMU_S_INVAL 0x04 #define VIRTIO_IOMMU_S_RANGE 0x05 #define VIRTIO_IOMMU_S_NOENT 0x06 #define VIRTIO_IOMMU_S_FAULT 0x07 #define VIRTIO_IOMMU_S_NOMEM 0x08 struct virtio_iommu_req_head { __u8 type; __u8 reserved[3]; }; struct virtio_iommu_req_tail { __u8 status; __u8 reserved[3]; }; struct virtio_iommu_req_attach { struct virtio_iommu_req_head head; __le32 domain; __le32 endpoint; __u8 reserved[8]; struct virtio_iommu_req_tail tail; }; struct virtio_iommu_req_detach { struct virtio_iommu_req_head head; __le32 domain; __le32 endpoint; __u8 reserved[8]; struct virtio_iommu_req_tail tail; }; #define VIRTIO_IOMMU_MAP_F_READ (1 << 0) #define VIRTIO_IOMMU_MAP_F_WRITE (1 << 1) #define VIRTIO_IOMMU_MAP_F_MMIO (1 << 2) #define VIRTIO_IOMMU_MAP_F_MASK (VIRTIO_IOMMU_MAP_F_READ | \ VIRTIO_IOMMU_MAP_F_WRITE | \ VIRTIO_IOMMU_MAP_F_MMIO) struct virtio_iommu_req_map { struct virtio_iommu_req_head head; __le32 domain; __le64 virt_start; __le64 virt_end; __le64 phys_start; __le32 flags; struct virtio_iommu_req_tail tail; }; struct virtio_iommu_req_unmap { struct virtio_iommu_req_head head; __le32 domain; __le64 virt_start; __le64 virt_end; __u8 reserved[4]; struct virtio_iommu_req_tail tail; }; #define VIRTIO_IOMMU_PROBE_T_NONE 0 #define VIRTIO_IOMMU_PROBE_T_RESV_MEM 1 #define VIRTIO_IOMMU_PROBE_T_MASK 0xfff struct virtio_iommu_probe_property { __le16 type; __le16 length; }; #define VIRTIO_IOMMU_RESV_MEM_T_RESERVED 0 #define VIRTIO_IOMMU_RESV_MEM_T_MSI 1 struct virtio_iommu_probe_resv_mem { struct virtio_iommu_probe_property head; __u8 subtype; __u8 reserved[3]; __le64 start; __le64 end; }; struct virtio_iommu_req_probe { struct virtio_iommu_req_head head; __le32 endpoint; __u8 reserved[64]; __u8 properties[]; /* * Tail follows the variable-length properties array. No padding, * property lengths are all aligned on 8 bytes. */ }; /* Fault types */ #define VIRTIO_IOMMU_FAULT_R_UNKNOWN 0 #define VIRTIO_IOMMU_FAULT_R_DOMAIN 1 #define VIRTIO_IOMMU_FAULT_R_MAPPING 2 #define VIRTIO_IOMMU_FAULT_F_READ (1 << 0) #define VIRTIO_IOMMU_FAULT_F_WRITE (1 << 1) #define VIRTIO_IOMMU_FAULT_F_EXEC (1 << 2) #define VIRTIO_IOMMU_FAULT_F_ADDRESS (1 << 8) struct virtio_iommu_fault { __u8 reason; __u8 reserved[3]; __le32 flags; __le32 endpoint; __u8 reserved2[4]; __le64 address; }; #endif linux/lirc.h000064400000017205151027430560007015 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * lirc.h - linux infrared remote control header file * last modified 2010/07/13 by Jarod Wilson */ #ifndef _LINUX_LIRC_H #define _LINUX_LIRC_H #include #include #define PULSE_BIT 0x01000000 #define PULSE_MASK 0x00FFFFFF #define LIRC_MODE2_SPACE 0x00000000 #define LIRC_MODE2_PULSE 0x01000000 #define LIRC_MODE2_FREQUENCY 0x02000000 #define LIRC_MODE2_TIMEOUT 0x03000000 #define LIRC_VALUE_MASK 0x00FFFFFF #define LIRC_MODE2_MASK 0xFF000000 #define LIRC_SPACE(val) (((val)&LIRC_VALUE_MASK) | LIRC_MODE2_SPACE) #define LIRC_PULSE(val) (((val)&LIRC_VALUE_MASK) | LIRC_MODE2_PULSE) #define LIRC_FREQUENCY(val) (((val)&LIRC_VALUE_MASK) | LIRC_MODE2_FREQUENCY) #define LIRC_TIMEOUT(val) (((val)&LIRC_VALUE_MASK) | LIRC_MODE2_TIMEOUT) #define LIRC_VALUE(val) ((val)&LIRC_VALUE_MASK) #define LIRC_MODE2(val) ((val)&LIRC_MODE2_MASK) #define LIRC_IS_SPACE(val) (LIRC_MODE2(val) == LIRC_MODE2_SPACE) #define LIRC_IS_PULSE(val) (LIRC_MODE2(val) == LIRC_MODE2_PULSE) #define LIRC_IS_FREQUENCY(val) (LIRC_MODE2(val) == LIRC_MODE2_FREQUENCY) #define LIRC_IS_TIMEOUT(val) (LIRC_MODE2(val) == LIRC_MODE2_TIMEOUT) /* used heavily by lirc userspace */ #define lirc_t int /*** lirc compatible hardware features ***/ #define LIRC_MODE2SEND(x) (x) #define LIRC_SEND2MODE(x) (x) #define LIRC_MODE2REC(x) ((x) << 16) #define LIRC_REC2MODE(x) ((x) >> 16) #define LIRC_MODE_RAW 0x00000001 #define LIRC_MODE_PULSE 0x00000002 #define LIRC_MODE_MODE2 0x00000004 #define LIRC_MODE_SCANCODE 0x00000008 #define LIRC_MODE_LIRCCODE 0x00000010 #define LIRC_CAN_SEND_RAW LIRC_MODE2SEND(LIRC_MODE_RAW) #define LIRC_CAN_SEND_PULSE LIRC_MODE2SEND(LIRC_MODE_PULSE) #define LIRC_CAN_SEND_MODE2 LIRC_MODE2SEND(LIRC_MODE_MODE2) #define LIRC_CAN_SEND_LIRCCODE LIRC_MODE2SEND(LIRC_MODE_LIRCCODE) #define LIRC_CAN_SEND_MASK 0x0000003f #define LIRC_CAN_SET_SEND_CARRIER 0x00000100 #define LIRC_CAN_SET_SEND_DUTY_CYCLE 0x00000200 #define LIRC_CAN_SET_TRANSMITTER_MASK 0x00000400 #define LIRC_CAN_REC_RAW LIRC_MODE2REC(LIRC_MODE_RAW) #define LIRC_CAN_REC_PULSE LIRC_MODE2REC(LIRC_MODE_PULSE) #define LIRC_CAN_REC_MODE2 LIRC_MODE2REC(LIRC_MODE_MODE2) #define LIRC_CAN_REC_SCANCODE LIRC_MODE2REC(LIRC_MODE_SCANCODE) #define LIRC_CAN_REC_LIRCCODE LIRC_MODE2REC(LIRC_MODE_LIRCCODE) #define LIRC_CAN_REC_MASK LIRC_MODE2REC(LIRC_CAN_SEND_MASK) #define LIRC_CAN_SET_REC_CARRIER (LIRC_CAN_SET_SEND_CARRIER << 16) #define LIRC_CAN_SET_REC_DUTY_CYCLE (LIRC_CAN_SET_SEND_DUTY_CYCLE << 16) #define LIRC_CAN_SET_REC_DUTY_CYCLE_RANGE 0x40000000 #define LIRC_CAN_SET_REC_CARRIER_RANGE 0x80000000 #define LIRC_CAN_GET_REC_RESOLUTION 0x20000000 #define LIRC_CAN_SET_REC_TIMEOUT 0x10000000 #define LIRC_CAN_SET_REC_FILTER 0x08000000 #define LIRC_CAN_MEASURE_CARRIER 0x02000000 #define LIRC_CAN_USE_WIDEBAND_RECEIVER 0x04000000 #define LIRC_CAN_SEND(x) ((x)&LIRC_CAN_SEND_MASK) #define LIRC_CAN_REC(x) ((x)&LIRC_CAN_REC_MASK) #define LIRC_CAN_NOTIFY_DECODE 0x01000000 /*** IOCTL commands for lirc driver ***/ #define LIRC_GET_FEATURES _IOR('i', 0x00000000, __u32) #define LIRC_GET_SEND_MODE _IOR('i', 0x00000001, __u32) #define LIRC_GET_REC_MODE _IOR('i', 0x00000002, __u32) #define LIRC_GET_REC_RESOLUTION _IOR('i', 0x00000007, __u32) #define LIRC_GET_MIN_TIMEOUT _IOR('i', 0x00000008, __u32) #define LIRC_GET_MAX_TIMEOUT _IOR('i', 0x00000009, __u32) /* code length in bits, currently only for LIRC_MODE_LIRCCODE */ #define LIRC_GET_LENGTH _IOR('i', 0x0000000f, __u32) #define LIRC_SET_SEND_MODE _IOW('i', 0x00000011, __u32) #define LIRC_SET_REC_MODE _IOW('i', 0x00000012, __u32) /* Note: these can reset the according pulse_width */ #define LIRC_SET_SEND_CARRIER _IOW('i', 0x00000013, __u32) #define LIRC_SET_REC_CARRIER _IOW('i', 0x00000014, __u32) #define LIRC_SET_SEND_DUTY_CYCLE _IOW('i', 0x00000015, __u32) #define LIRC_SET_TRANSMITTER_MASK _IOW('i', 0x00000017, __u32) /* * when a timeout != 0 is set the driver will send a * LIRC_MODE2_TIMEOUT data packet, otherwise LIRC_MODE2_TIMEOUT is * never sent, timeout is disabled by default */ #define LIRC_SET_REC_TIMEOUT _IOW('i', 0x00000018, __u32) /* 1 enables, 0 disables timeout reports in MODE2 */ #define LIRC_SET_REC_TIMEOUT_REPORTS _IOW('i', 0x00000019, __u32) /* * if enabled from the next key press on the driver will send * LIRC_MODE2_FREQUENCY packets */ #define LIRC_SET_MEASURE_CARRIER_MODE _IOW('i', 0x0000001d, __u32) /* * to set a range use LIRC_SET_REC_CARRIER_RANGE with the * lower bound first and later LIRC_SET_REC_CARRIER with the upper bound */ #define LIRC_SET_REC_CARRIER_RANGE _IOW('i', 0x0000001f, __u32) #define LIRC_SET_WIDEBAND_RECEIVER _IOW('i', 0x00000023, __u32) /* * Return the recording timeout, which is either set by * the ioctl LIRC_SET_REC_TIMEOUT or by the kernel after setting the protocols. */ #define LIRC_GET_REC_TIMEOUT _IOR('i', 0x00000024, __u32) /* * struct lirc_scancode - decoded scancode with protocol for use with * LIRC_MODE_SCANCODE * * @timestamp: Timestamp in nanoseconds using CLOCK_MONOTONIC when IR * was decoded. * @flags: should be 0 for transmit. When receiving scancodes, * LIRC_SCANCODE_FLAG_TOGGLE or LIRC_SCANCODE_FLAG_REPEAT can be set * depending on the protocol * @rc_proto: see enum rc_proto * @keycode: the translated keycode. Set to 0 for transmit. * @scancode: the scancode received or to be sent */ struct lirc_scancode { __u64 timestamp; __u16 flags; __u16 rc_proto; __u32 keycode; __u64 scancode; }; /* Set if the toggle bit of rc-5 or rc-6 is enabled */ #define LIRC_SCANCODE_FLAG_TOGGLE 1 /* Set if this is a nec or sanyo repeat */ #define LIRC_SCANCODE_FLAG_REPEAT 2 /** * enum rc_proto - the Remote Controller protocol * * @RC_PROTO_UNKNOWN: Protocol not known * @RC_PROTO_OTHER: Protocol known but proprietary * @RC_PROTO_RC5: Philips RC5 protocol * @RC_PROTO_RC5X_20: Philips RC5x 20 bit protocol * @RC_PROTO_RC5_SZ: StreamZap variant of RC5 * @RC_PROTO_JVC: JVC protocol * @RC_PROTO_SONY12: Sony 12 bit protocol * @RC_PROTO_SONY15: Sony 15 bit protocol * @RC_PROTO_SONY20: Sony 20 bit protocol * @RC_PROTO_NEC: NEC protocol * @RC_PROTO_NECX: Extended NEC protocol * @RC_PROTO_NEC32: NEC 32 bit protocol * @RC_PROTO_SANYO: Sanyo protocol * @RC_PROTO_MCIR2_KBD: RC6-ish MCE keyboard * @RC_PROTO_MCIR2_MSE: RC6-ish MCE mouse * @RC_PROTO_RC6_0: Philips RC6-0-16 protocol * @RC_PROTO_RC6_6A_20: Philips RC6-6A-20 protocol * @RC_PROTO_RC6_6A_24: Philips RC6-6A-24 protocol * @RC_PROTO_RC6_6A_32: Philips RC6-6A-32 protocol * @RC_PROTO_RC6_MCE: MCE (Philips RC6-6A-32 subtype) protocol * @RC_PROTO_SHARP: Sharp protocol * @RC_PROTO_XMP: XMP protocol * @RC_PROTO_CEC: CEC protocol * @RC_PROTO_IMON: iMon Pad protocol */ enum rc_proto { RC_PROTO_UNKNOWN = 0, RC_PROTO_OTHER = 1, RC_PROTO_RC5 = 2, RC_PROTO_RC5X_20 = 3, RC_PROTO_RC5_SZ = 4, RC_PROTO_JVC = 5, RC_PROTO_SONY12 = 6, RC_PROTO_SONY15 = 7, RC_PROTO_SONY20 = 8, RC_PROTO_NEC = 9, RC_PROTO_NECX = 10, RC_PROTO_NEC32 = 11, RC_PROTO_SANYO = 12, RC_PROTO_MCIR2_KBD = 13, RC_PROTO_MCIR2_MSE = 14, RC_PROTO_RC6_0 = 15, RC_PROTO_RC6_6A_20 = 16, RC_PROTO_RC6_6A_24 = 17, RC_PROTO_RC6_6A_32 = 18, RC_PROTO_RC6_MCE = 19, RC_PROTO_SHARP = 20, RC_PROTO_XMP = 21, RC_PROTO_CEC = 22, RC_PROTO_IMON = 23, }; #endif linux/ip_vs.h000064400000032477151027430560007214 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * IP Virtual Server * data structure and functionality definitions */ #ifndef _IP_VS_H #define _IP_VS_H #include /* For __beXX types in userland */ #define IP_VS_VERSION_CODE 0x010201 #define NVERSION(version) \ (version >> 16) & 0xFF, \ (version >> 8) & 0xFF, \ version & 0xFF /* * Virtual Service Flags */ #define IP_VS_SVC_F_PERSISTENT 0x0001 /* persistent port */ #define IP_VS_SVC_F_HASHED 0x0002 /* hashed entry */ #define IP_VS_SVC_F_ONEPACKET 0x0004 /* one-packet scheduling */ #define IP_VS_SVC_F_SCHED1 0x0008 /* scheduler flag 1 */ #define IP_VS_SVC_F_SCHED2 0x0010 /* scheduler flag 2 */ #define IP_VS_SVC_F_SCHED3 0x0020 /* scheduler flag 3 */ #define IP_VS_SVC_F_SCHED_SH_FALLBACK IP_VS_SVC_F_SCHED1 /* SH fallback */ #define IP_VS_SVC_F_SCHED_SH_PORT IP_VS_SVC_F_SCHED2 /* SH use port */ /* * Destination Server Flags */ #define IP_VS_DEST_F_AVAILABLE 0x0001 /* server is available */ #define IP_VS_DEST_F_OVERLOAD 0x0002 /* server is overloaded */ /* * IPVS sync daemon states */ #define IP_VS_STATE_NONE 0x0000 /* daemon is stopped */ #define IP_VS_STATE_MASTER 0x0001 /* started as master */ #define IP_VS_STATE_BACKUP 0x0002 /* started as backup */ /* * IPVS socket options */ #define IP_VS_BASE_CTL (64+1024+64) /* base */ #define IP_VS_SO_SET_NONE IP_VS_BASE_CTL /* just peek */ #define IP_VS_SO_SET_INSERT (IP_VS_BASE_CTL+1) #define IP_VS_SO_SET_ADD (IP_VS_BASE_CTL+2) #define IP_VS_SO_SET_EDIT (IP_VS_BASE_CTL+3) #define IP_VS_SO_SET_DEL (IP_VS_BASE_CTL+4) #define IP_VS_SO_SET_FLUSH (IP_VS_BASE_CTL+5) #define IP_VS_SO_SET_LIST (IP_VS_BASE_CTL+6) #define IP_VS_SO_SET_ADDDEST (IP_VS_BASE_CTL+7) #define IP_VS_SO_SET_DELDEST (IP_VS_BASE_CTL+8) #define IP_VS_SO_SET_EDITDEST (IP_VS_BASE_CTL+9) #define IP_VS_SO_SET_TIMEOUT (IP_VS_BASE_CTL+10) #define IP_VS_SO_SET_STARTDAEMON (IP_VS_BASE_CTL+11) #define IP_VS_SO_SET_STOPDAEMON (IP_VS_BASE_CTL+12) #define IP_VS_SO_SET_RESTORE (IP_VS_BASE_CTL+13) #define IP_VS_SO_SET_SAVE (IP_VS_BASE_CTL+14) #define IP_VS_SO_SET_ZERO (IP_VS_BASE_CTL+15) #define IP_VS_SO_SET_MAX IP_VS_SO_SET_ZERO #define IP_VS_SO_GET_VERSION IP_VS_BASE_CTL #define IP_VS_SO_GET_INFO (IP_VS_BASE_CTL+1) #define IP_VS_SO_GET_SERVICES (IP_VS_BASE_CTL+2) #define IP_VS_SO_GET_SERVICE (IP_VS_BASE_CTL+3) #define IP_VS_SO_GET_DESTS (IP_VS_BASE_CTL+4) #define IP_VS_SO_GET_DEST (IP_VS_BASE_CTL+5) /* not used now */ #define IP_VS_SO_GET_TIMEOUT (IP_VS_BASE_CTL+6) #define IP_VS_SO_GET_DAEMON (IP_VS_BASE_CTL+7) #define IP_VS_SO_GET_MAX IP_VS_SO_GET_DAEMON /* * IPVS Connection Flags * Only flags 0..15 are sent to backup server */ #define IP_VS_CONN_F_FWD_MASK 0x0007 /* mask for the fwd methods */ #define IP_VS_CONN_F_MASQ 0x0000 /* masquerading/NAT */ #define IP_VS_CONN_F_LOCALNODE 0x0001 /* local node */ #define IP_VS_CONN_F_TUNNEL 0x0002 /* tunneling */ #define IP_VS_CONN_F_DROUTE 0x0003 /* direct routing */ #define IP_VS_CONN_F_BYPASS 0x0004 /* cache bypass */ #define IP_VS_CONN_F_SYNC 0x0020 /* entry created by sync */ #define IP_VS_CONN_F_HASHED 0x0040 /* hashed entry */ #define IP_VS_CONN_F_NOOUTPUT 0x0080 /* no output packets */ #define IP_VS_CONN_F_INACTIVE 0x0100 /* not established */ #define IP_VS_CONN_F_OUT_SEQ 0x0200 /* must do output seq adjust */ #define IP_VS_CONN_F_IN_SEQ 0x0400 /* must do input seq adjust */ #define IP_VS_CONN_F_SEQ_MASK 0x0600 /* in/out sequence mask */ #define IP_VS_CONN_F_NO_CPORT 0x0800 /* no client port set yet */ #define IP_VS_CONN_F_TEMPLATE 0x1000 /* template, not connection */ #define IP_VS_CONN_F_ONE_PACKET 0x2000 /* forward only one packet */ /* Initial bits allowed in backup server */ #define IP_VS_CONN_F_BACKUP_MASK (IP_VS_CONN_F_FWD_MASK | \ IP_VS_CONN_F_NOOUTPUT | \ IP_VS_CONN_F_INACTIVE | \ IP_VS_CONN_F_SEQ_MASK | \ IP_VS_CONN_F_NO_CPORT | \ IP_VS_CONN_F_TEMPLATE \ ) /* Bits allowed to update in backup server */ #define IP_VS_CONN_F_BACKUP_UPD_MASK (IP_VS_CONN_F_INACTIVE | \ IP_VS_CONN_F_SEQ_MASK) /* Flags that are not sent to backup server start from bit 16 */ #define IP_VS_CONN_F_NFCT (1 << 16) /* use netfilter conntrack */ /* Connection flags from destination that can be changed by user space */ #define IP_VS_CONN_F_DEST_MASK (IP_VS_CONN_F_FWD_MASK | \ IP_VS_CONN_F_ONE_PACKET | \ IP_VS_CONN_F_NFCT | \ 0) #define IP_VS_SCHEDNAME_MAXLEN 16 #define IP_VS_PENAME_MAXLEN 16 #define IP_VS_IFNAME_MAXLEN 16 #define IP_VS_PEDATA_MAXLEN 255 /* * The struct ip_vs_service_user and struct ip_vs_dest_user are * used to set IPVS rules through setsockopt. */ struct ip_vs_service_user { /* virtual service addresses */ __u16 protocol; __be32 addr; /* virtual ip address */ __be16 port; __u32 fwmark; /* firwall mark of service */ /* virtual service options */ char sched_name[IP_VS_SCHEDNAME_MAXLEN]; unsigned int flags; /* virtual service flags */ unsigned int timeout; /* persistent timeout in sec */ __be32 netmask; /* persistent netmask */ }; struct ip_vs_dest_user { /* destination server address */ __be32 addr; __be16 port; /* real server options */ unsigned int conn_flags; /* connection flags */ int weight; /* destination weight */ /* thresholds for active connections */ __u32 u_threshold; /* upper threshold */ __u32 l_threshold; /* lower threshold */ }; /* * IPVS statistics object (for user space) */ struct ip_vs_stats_user { __u32 conns; /* connections scheduled */ __u32 inpkts; /* incoming packets */ __u32 outpkts; /* outgoing packets */ __u64 inbytes; /* incoming bytes */ __u64 outbytes; /* outgoing bytes */ __u32 cps; /* current connection rate */ __u32 inpps; /* current in packet rate */ __u32 outpps; /* current out packet rate */ __u32 inbps; /* current in byte rate */ __u32 outbps; /* current out byte rate */ }; /* The argument to IP_VS_SO_GET_INFO */ struct ip_vs_getinfo { /* version number */ unsigned int version; /* size of connection hash table */ unsigned int size; /* number of virtual services */ unsigned int num_services; }; /* The argument to IP_VS_SO_GET_SERVICE */ struct ip_vs_service_entry { /* which service: user fills in these */ __u16 protocol; __be32 addr; /* virtual address */ __be16 port; __u32 fwmark; /* firwall mark of service */ /* service options */ char sched_name[IP_VS_SCHEDNAME_MAXLEN]; unsigned int flags; /* virtual service flags */ unsigned int timeout; /* persistent timeout */ __be32 netmask; /* persistent netmask */ /* number of real servers */ unsigned int num_dests; /* statistics */ struct ip_vs_stats_user stats; }; struct ip_vs_dest_entry { __be32 addr; /* destination address */ __be16 port; unsigned int conn_flags; /* connection flags */ int weight; /* destination weight */ __u32 u_threshold; /* upper threshold */ __u32 l_threshold; /* lower threshold */ __u32 activeconns; /* active connections */ __u32 inactconns; /* inactive connections */ __u32 persistconns; /* persistent connections */ /* statistics */ struct ip_vs_stats_user stats; }; /* The argument to IP_VS_SO_GET_DESTS */ struct ip_vs_get_dests { /* which service: user fills in these */ __u16 protocol; __be32 addr; /* virtual address */ __be16 port; __u32 fwmark; /* firwall mark of service */ /* number of real servers */ unsigned int num_dests; /* the real servers */ struct ip_vs_dest_entry entrytable[0]; }; /* The argument to IP_VS_SO_GET_SERVICES */ struct ip_vs_get_services { /* number of virtual services */ unsigned int num_services; /* service table */ struct ip_vs_service_entry entrytable[0]; }; /* The argument to IP_VS_SO_GET_TIMEOUT */ struct ip_vs_timeout_user { int tcp_timeout; int tcp_fin_timeout; int udp_timeout; }; /* The argument to IP_VS_SO_GET_DAEMON */ struct ip_vs_daemon_user { /* sync daemon state (master/backup) */ int state; /* multicast interface name */ char mcast_ifn[IP_VS_IFNAME_MAXLEN]; /* SyncID we belong to */ int syncid; }; /* * * IPVS Generic Netlink interface definitions * */ /* Generic Netlink family info */ #define IPVS_GENL_NAME "IPVS" #define IPVS_GENL_VERSION 0x1 struct ip_vs_flags { __u32 flags; __u32 mask; }; /* Generic Netlink command attributes */ enum { IPVS_CMD_UNSPEC = 0, IPVS_CMD_NEW_SERVICE, /* add service */ IPVS_CMD_SET_SERVICE, /* modify service */ IPVS_CMD_DEL_SERVICE, /* delete service */ IPVS_CMD_GET_SERVICE, /* get service info */ IPVS_CMD_NEW_DEST, /* add destination */ IPVS_CMD_SET_DEST, /* modify destination */ IPVS_CMD_DEL_DEST, /* delete destination */ IPVS_CMD_GET_DEST, /* get destination info */ IPVS_CMD_NEW_DAEMON, /* start sync daemon */ IPVS_CMD_DEL_DAEMON, /* stop sync daemon */ IPVS_CMD_GET_DAEMON, /* get sync daemon status */ IPVS_CMD_SET_CONFIG, /* set config settings */ IPVS_CMD_GET_CONFIG, /* get config settings */ IPVS_CMD_SET_INFO, /* only used in GET_INFO reply */ IPVS_CMD_GET_INFO, /* get general IPVS info */ IPVS_CMD_ZERO, /* zero all counters and stats */ IPVS_CMD_FLUSH, /* flush services and dests */ __IPVS_CMD_MAX, }; #define IPVS_CMD_MAX (__IPVS_CMD_MAX - 1) /* Attributes used in the first level of commands */ enum { IPVS_CMD_ATTR_UNSPEC = 0, IPVS_CMD_ATTR_SERVICE, /* nested service attribute */ IPVS_CMD_ATTR_DEST, /* nested destination attribute */ IPVS_CMD_ATTR_DAEMON, /* nested sync daemon attribute */ IPVS_CMD_ATTR_TIMEOUT_TCP, /* TCP connection timeout */ IPVS_CMD_ATTR_TIMEOUT_TCP_FIN, /* TCP FIN wait timeout */ IPVS_CMD_ATTR_TIMEOUT_UDP, /* UDP timeout */ __IPVS_CMD_ATTR_MAX, }; #define IPVS_CMD_ATTR_MAX (__IPVS_CMD_ATTR_MAX - 1) /* * Attributes used to describe a service * * Used inside nested attribute IPVS_CMD_ATTR_SERVICE */ enum { IPVS_SVC_ATTR_UNSPEC = 0, IPVS_SVC_ATTR_AF, /* address family */ IPVS_SVC_ATTR_PROTOCOL, /* virtual service protocol */ IPVS_SVC_ATTR_ADDR, /* virtual service address */ IPVS_SVC_ATTR_PORT, /* virtual service port */ IPVS_SVC_ATTR_FWMARK, /* firewall mark of service */ IPVS_SVC_ATTR_SCHED_NAME, /* name of scheduler */ IPVS_SVC_ATTR_FLAGS, /* virtual service flags */ IPVS_SVC_ATTR_TIMEOUT, /* persistent timeout */ IPVS_SVC_ATTR_NETMASK, /* persistent netmask */ IPVS_SVC_ATTR_STATS, /* nested attribute for service stats */ IPVS_SVC_ATTR_PE_NAME, /* name of ct retriever */ IPVS_SVC_ATTR_STATS64, /* nested attribute for service stats */ __IPVS_SVC_ATTR_MAX, }; #define IPVS_SVC_ATTR_MAX (__IPVS_SVC_ATTR_MAX - 1) /* * Attributes used to describe a destination (real server) * * Used inside nested attribute IPVS_CMD_ATTR_DEST */ enum { IPVS_DEST_ATTR_UNSPEC = 0, IPVS_DEST_ATTR_ADDR, /* real server address */ IPVS_DEST_ATTR_PORT, /* real server port */ IPVS_DEST_ATTR_FWD_METHOD, /* forwarding method */ IPVS_DEST_ATTR_WEIGHT, /* destination weight */ IPVS_DEST_ATTR_U_THRESH, /* upper threshold */ IPVS_DEST_ATTR_L_THRESH, /* lower threshold */ IPVS_DEST_ATTR_ACTIVE_CONNS, /* active connections */ IPVS_DEST_ATTR_INACT_CONNS, /* inactive connections */ IPVS_DEST_ATTR_PERSIST_CONNS, /* persistent connections */ IPVS_DEST_ATTR_STATS, /* nested attribute for dest stats */ IPVS_DEST_ATTR_ADDR_FAMILY, /* Address family of address */ IPVS_DEST_ATTR_STATS64, /* nested attribute for dest stats */ __IPVS_DEST_ATTR_MAX, }; #define IPVS_DEST_ATTR_MAX (__IPVS_DEST_ATTR_MAX - 1) /* * Attributes describing a sync daemon * * Used inside nested attribute IPVS_CMD_ATTR_DAEMON */ enum { IPVS_DAEMON_ATTR_UNSPEC = 0, IPVS_DAEMON_ATTR_STATE, /* sync daemon state (master/backup) */ IPVS_DAEMON_ATTR_MCAST_IFN, /* multicast interface name */ IPVS_DAEMON_ATTR_SYNC_ID, /* SyncID we belong to */ IPVS_DAEMON_ATTR_SYNC_MAXLEN, /* UDP Payload Size */ IPVS_DAEMON_ATTR_MCAST_GROUP, /* IPv4 Multicast Address */ IPVS_DAEMON_ATTR_MCAST_GROUP6, /* IPv6 Multicast Address */ IPVS_DAEMON_ATTR_MCAST_PORT, /* Multicast Port (base) */ IPVS_DAEMON_ATTR_MCAST_TTL, /* Multicast TTL */ __IPVS_DAEMON_ATTR_MAX, }; #define IPVS_DAEMON_ATTR_MAX (__IPVS_DAEMON_ATTR_MAX - 1) /* * Attributes used to describe service or destination entry statistics * * Used inside nested attributes IPVS_SVC_ATTR_STATS, IPVS_DEST_ATTR_STATS, * IPVS_SVC_ATTR_STATS64 and IPVS_DEST_ATTR_STATS64. */ enum { IPVS_STATS_ATTR_UNSPEC = 0, IPVS_STATS_ATTR_CONNS, /* connections scheduled */ IPVS_STATS_ATTR_INPKTS, /* incoming packets */ IPVS_STATS_ATTR_OUTPKTS, /* outgoing packets */ IPVS_STATS_ATTR_INBYTES, /* incoming bytes */ IPVS_STATS_ATTR_OUTBYTES, /* outgoing bytes */ IPVS_STATS_ATTR_CPS, /* current connection rate */ IPVS_STATS_ATTR_INPPS, /* current in packet rate */ IPVS_STATS_ATTR_OUTPPS, /* current out packet rate */ IPVS_STATS_ATTR_INBPS, /* current in byte rate */ IPVS_STATS_ATTR_OUTBPS, /* current out byte rate */ IPVS_STATS_ATTR_PAD, __IPVS_STATS_ATTR_MAX, }; #define IPVS_STATS_ATTR_MAX (__IPVS_STATS_ATTR_MAX - 1) /* Attributes used in response to IPVS_CMD_GET_INFO command */ enum { IPVS_INFO_ATTR_UNSPEC = 0, IPVS_INFO_ATTR_VERSION, /* IPVS version number */ IPVS_INFO_ATTR_CONN_TAB_SIZE, /* size of connection hash table */ __IPVS_INFO_ATTR_MAX, }; #define IPVS_INFO_ATTR_MAX (__IPVS_INFO_ATTR_MAX - 1) #endif /* _IP_VS_H */ linux/net_namespace.h000064400000001313151027430560010657 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Copyright (c) 2015 6WIND S.A. * Author: Nicolas Dichtel * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. */ #ifndef _LINUX_NET_NAMESPACE_H_ #define _LINUX_NET_NAMESPACE_H_ /* Attributes of RTM_NEWNSID/RTM_GETNSID messages */ enum { NETNSA_NONE, #define NETNSA_NSID_NOT_ASSIGNED -1 NETNSA_NSID, NETNSA_PID, NETNSA_FD, NETNSA_TARGET_NSID, NETNSA_CURRENT_NSID, __NETNSA_MAX, }; #define NETNSA_MAX (__NETNSA_MAX - 1) #endif /* _LINUX_NET_NAMESPACE_H_ */ linux/pci.h000064400000002544151027430560006637 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * pci.h * * PCI defines and function prototypes * Copyright 1994, Drew Eckhardt * Copyright 1997--1999 Martin Mares * * For more information, please consult the following manuals (look at * http://www.pcisig.com/ for how to get them): * * PCI BIOS Specification * PCI Local Bus Specification * PCI to PCI Bridge Specification * PCI System Design Guide */ #ifndef LINUX_PCI_H #define LINUX_PCI_H #include /* The pci register defines */ /* * The PCI interface treats multi-function devices as independent * devices. The slot/function address of each device is encoded * in a single byte as follows: * * 7:3 = slot * 2:0 = function */ #define PCI_DEVFN(slot, func) ((((slot) & 0x1f) << 3) | ((func) & 0x07)) #define PCI_SLOT(devfn) (((devfn) >> 3) & 0x1f) #define PCI_FUNC(devfn) ((devfn) & 0x07) /* Ioctls for /proc/bus/pci/X/Y nodes. */ #define PCIIOC_BASE ('P' << 24 | 'C' << 16 | 'I' << 8) #define PCIIOC_CONTROLLER (PCIIOC_BASE | 0x00) /* Get controller for PCI device. */ #define PCIIOC_MMAP_IS_IO (PCIIOC_BASE | 0x01) /* Set mmap state to I/O space. */ #define PCIIOC_MMAP_IS_MEM (PCIIOC_BASE | 0x02) /* Set mmap state to MEM space. */ #define PCIIOC_WRITE_COMBINE (PCIIOC_BASE | 0x03) /* Enable/disable write-combining. */ #endif /* LINUX_PCI_H */ linux/mic_common.h000064400000014567151027430560010214 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Intel MIC Platform Software Stack (MPSS) * * Copyright(c) 2013 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Intel MIC driver. * */ #ifndef __MIC_COMMON_H_ #define __MIC_COMMON_H_ #include #define __mic_align(a, x) (((a) + (x) - 1) & ~((x) - 1)) /** * struct mic_device_desc: Virtio device information shared between the * virtio driver and userspace backend * * @type: Device type: console/network/disk etc. Type 0/-1 terminates. * @num_vq: Number of virtqueues. * @feature_len: Number of bytes of feature bits. Multiply by 2: one for host features and one for guest acknowledgements. * @config_len: Number of bytes of the config array after virtqueues. * @status: A status byte, written by the Guest. * @config: Start of the following variable length config. */ struct mic_device_desc { __s8 type; __u8 num_vq; __u8 feature_len; __u8 config_len; __u8 status; __le64 config[0]; } __attribute__ ((aligned(8))); /** * struct mic_device_ctrl: Per virtio device information in the device page * used internally by the host and card side drivers. * * @vdev: Used for storing MIC vdev information by the guest. * @config_change: Set to 1 by host when a config change is requested. * @vdev_reset: Set to 1 by guest to indicate virtio device has been reset. * @guest_ack: Set to 1 by guest to ack a command. * @host_ack: Set to 1 by host to ack a command. * @used_address_updated: Set to 1 by guest when the used address should be * updated. * @c2h_vdev_db: The doorbell number to be used by guest. Set by host. * @h2c_vdev_db: The doorbell number to be used by host. Set by guest. */ struct mic_device_ctrl { __le64 vdev; __u8 config_change; __u8 vdev_reset; __u8 guest_ack; __u8 host_ack; __u8 used_address_updated; __s8 c2h_vdev_db; __s8 h2c_vdev_db; } __attribute__ ((aligned(8))); /** * struct mic_bootparam: Virtio device independent information in device page * * @magic: A magic value used by the card to ensure it can see the host * @h2c_config_db: Host to Card Virtio config doorbell set by card * @node_id: Unique id of the node * @h2c_scif_db - Host to card SCIF doorbell set by card * @c2h_scif_db - Card to host SCIF doorbell set by host * @scif_host_dma_addr - SCIF host queue pair DMA address * @scif_card_dma_addr - SCIF card queue pair DMA address */ struct mic_bootparam { __le32 magic; __s8 h2c_config_db; __u8 node_id; __u8 h2c_scif_db; __u8 c2h_scif_db; __u64 scif_host_dma_addr; __u64 scif_card_dma_addr; } __attribute__ ((aligned(8))); /** * struct mic_device_page: High level representation of the device page * * @bootparam: The bootparam structure is used for sharing information and * status updates between MIC host and card drivers. * @desc: Array of MIC virtio device descriptors. */ struct mic_device_page { struct mic_bootparam bootparam; struct mic_device_desc desc[0]; }; /** * struct mic_vqconfig: This is how we expect the device configuration field * for a virtqueue to be laid out in config space. * * @address: Guest/MIC physical address of the virtio ring * (avail and desc rings) * @used_address: Guest/MIC physical address of the used ring * @num: The number of entries in the virtio_ring */ struct mic_vqconfig { __le64 address; __le64 used_address; __le16 num; } __attribute__ ((aligned(8))); /* * The alignment to use between consumer and producer parts of vring. * This is pagesize for historical reasons. */ #define MIC_VIRTIO_RING_ALIGN 4096 #define MIC_MAX_VRINGS 4 #define MIC_VRING_ENTRIES 128 /* * Max vring entries (power of 2) to ensure desc and avail rings * fit in a single page */ #define MIC_MAX_VRING_ENTRIES 128 /** * Max size of the desc block in bytes: includes: * - struct mic_device_desc * - struct mic_vqconfig (num_vq of these) * - host and guest features * - virtio device config space */ #define MIC_MAX_DESC_BLK_SIZE 256 /** * struct _mic_vring_info - Host vring info exposed to userspace backend * for the avail index and magic for the card. * * @avail_idx: host avail idx * @magic: A magic debug cookie. */ struct _mic_vring_info { __u16 avail_idx; __le32 magic; }; /** * struct mic_vring - Vring information. * * @vr: The virtio ring. * @info: Host vring information exposed to the userspace backend for the * avail index and magic for the card. * @va: The va for the buffer allocated for vr and info. * @len: The length of the buffer required for allocating vr and info. */ struct mic_vring { struct vring vr; struct _mic_vring_info *info; void *va; int len; }; #define mic_aligned_desc_size(d) __mic_align(mic_desc_size(d), 8) #ifndef INTEL_MIC_CARD static __inline__ unsigned mic_desc_size(const struct mic_device_desc *desc) { return sizeof(*desc) + desc->num_vq * sizeof(struct mic_vqconfig) + desc->feature_len * 2 + desc->config_len; } static __inline__ struct mic_vqconfig * mic_vq_config(const struct mic_device_desc *desc) { return (struct mic_vqconfig *)(desc + 1); } static __inline__ __u8 *mic_vq_features(const struct mic_device_desc *desc) { return (__u8 *)(mic_vq_config(desc) + desc->num_vq); } static __inline__ __u8 *mic_vq_configspace(const struct mic_device_desc *desc) { return mic_vq_features(desc) + desc->feature_len * 2; } static __inline__ unsigned mic_total_desc_size(struct mic_device_desc *desc) { return mic_aligned_desc_size(desc) + sizeof(struct mic_device_ctrl); } #endif /* Device page size */ #define MIC_DP_SIZE 4096 #define MIC_MAGIC 0xc0ffee00 /** * enum mic_states - MIC states. */ enum mic_states { MIC_READY = 0, MIC_BOOTING, MIC_ONLINE, MIC_SHUTTING_DOWN, MIC_RESETTING, MIC_RESET_FAILED, MIC_LAST }; /** * enum mic_status - MIC status reported by card after * a host or card initiated shutdown or a card crash. */ enum mic_status { MIC_NOP = 0, MIC_CRASHED, MIC_HALTED, MIC_POWER_OFF, MIC_RESTART, MIC_STATUS_LAST }; #endif linux/ipmi_msgdefs.h000064400000006546151027430560010540 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * ipmi_smi.h * * MontaVista IPMI system management interface * * Author: MontaVista Software, Inc. * Corey Minyard * source@mvista.com * * Copyright 2002 MontaVista Software Inc. * */ #ifndef __LINUX_IPMI_MSGDEFS_H #define __LINUX_IPMI_MSGDEFS_H /* Various definitions for IPMI messages used by almost everything in the IPMI stack. */ /* NetFNs and commands used inside the IPMI stack. */ #define IPMI_NETFN_SENSOR_EVENT_REQUEST 0x04 #define IPMI_NETFN_SENSOR_EVENT_RESPONSE 0x05 #define IPMI_GET_EVENT_RECEIVER_CMD 0x01 #define IPMI_NETFN_APP_REQUEST 0x06 #define IPMI_NETFN_APP_RESPONSE 0x07 #define IPMI_GET_DEVICE_ID_CMD 0x01 #define IPMI_COLD_RESET_CMD 0x02 #define IPMI_WARM_RESET_CMD 0x03 #define IPMI_CLEAR_MSG_FLAGS_CMD 0x30 #define IPMI_GET_DEVICE_GUID_CMD 0x08 #define IPMI_GET_MSG_FLAGS_CMD 0x31 #define IPMI_SEND_MSG_CMD 0x34 #define IPMI_GET_MSG_CMD 0x33 #define IPMI_SET_BMC_GLOBAL_ENABLES_CMD 0x2e #define IPMI_GET_BMC_GLOBAL_ENABLES_CMD 0x2f #define IPMI_READ_EVENT_MSG_BUFFER_CMD 0x35 #define IPMI_GET_CHANNEL_INFO_CMD 0x42 /* Bit for BMC global enables. */ #define IPMI_BMC_RCV_MSG_INTR 0x01 #define IPMI_BMC_EVT_MSG_INTR 0x02 #define IPMI_BMC_EVT_MSG_BUFF 0x04 #define IPMI_BMC_SYS_LOG 0x08 #define IPMI_NETFN_STORAGE_REQUEST 0x0a #define IPMI_NETFN_STORAGE_RESPONSE 0x0b #define IPMI_ADD_SEL_ENTRY_CMD 0x44 #define IPMI_NETFN_FIRMWARE_REQUEST 0x08 #define IPMI_NETFN_FIRMWARE_RESPONSE 0x09 /* The default slave address */ #define IPMI_BMC_SLAVE_ADDR 0x20 /* The BT interface on high-end HP systems supports up to 255 bytes in * one transfer. Its "virtual" BMC supports some commands that are longer * than 128 bytes. Use the full 256, plus NetFn/LUN, Cmd, cCode, plus * some overhead; it's not worth the effort to dynamically size this based * on the results of the "Get BT Capabilities" command. */ #define IPMI_MAX_MSG_LENGTH 272 /* multiple of 16 */ #define IPMI_CC_NO_ERROR 0x00 #define IPMI_NODE_BUSY_ERR 0xc0 #define IPMI_INVALID_COMMAND_ERR 0xc1 #define IPMI_TIMEOUT_ERR 0xc3 #define IPMI_ERR_MSG_TRUNCATED 0xc6 #define IPMI_REQ_LEN_INVALID_ERR 0xc7 #define IPMI_REQ_LEN_EXCEEDED_ERR 0xc8 #define IPMI_DEVICE_IN_FW_UPDATE_ERR 0xd1 #define IPMI_DEVICE_IN_INIT_ERR 0xd2 #define IPMI_NOT_IN_MY_STATE_ERR 0xd5 /* IPMI 2.0 */ #define IPMI_LOST_ARBITRATION_ERR 0x81 #define IPMI_BUS_ERR 0x82 #define IPMI_NAK_ON_WRITE_ERR 0x83 #define IPMI_ERR_UNSPECIFIED 0xff #define IPMI_CHANNEL_PROTOCOL_IPMB 1 #define IPMI_CHANNEL_PROTOCOL_ICMB 2 #define IPMI_CHANNEL_PROTOCOL_SMBUS 4 #define IPMI_CHANNEL_PROTOCOL_KCS 5 #define IPMI_CHANNEL_PROTOCOL_SMIC 6 #define IPMI_CHANNEL_PROTOCOL_BT10 7 #define IPMI_CHANNEL_PROTOCOL_BT15 8 #define IPMI_CHANNEL_PROTOCOL_TMODE 9 #define IPMI_CHANNEL_MEDIUM_IPMB 1 #define IPMI_CHANNEL_MEDIUM_ICMB10 2 #define IPMI_CHANNEL_MEDIUM_ICMB09 3 #define IPMI_CHANNEL_MEDIUM_8023LAN 4 #define IPMI_CHANNEL_MEDIUM_ASYNC 5 #define IPMI_CHANNEL_MEDIUM_OTHER_LAN 6 #define IPMI_CHANNEL_MEDIUM_PCI_SMBUS 7 #define IPMI_CHANNEL_MEDIUM_SMBUS1 8 #define IPMI_CHANNEL_MEDIUM_SMBUS2 9 #define IPMI_CHANNEL_MEDIUM_USB1 10 #define IPMI_CHANNEL_MEDIUM_USB2 11 #define IPMI_CHANNEL_MEDIUM_SYSINTF 12 #define IPMI_CHANNEL_MEDIUM_OEM_MIN 0x60 #define IPMI_CHANNEL_MEDIUM_OEM_MAX 0x7f #endif /* __LINUX_IPMI_MSGDEFS_H */ linux/sound.h000064400000002325151027430560007211 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SOUND_H #define _LINUX_SOUND_H /* * Minor numbers for the sound driver. */ #include #define SND_DEV_CTL 0 /* Control port /dev/mixer */ #define SND_DEV_SEQ 1 /* Sequencer output /dev/sequencer (FM synthesizer and MIDI output) */ #define SND_DEV_MIDIN 2 /* Raw midi access */ #define SND_DEV_DSP 3 /* Digitized voice /dev/dsp */ #define SND_DEV_AUDIO 4 /* Sparc compatible /dev/audio */ #define SND_DEV_DSP16 5 /* Like /dev/dsp but 16 bits/sample */ /* #define SND_DEV_STATUS 6 */ /* /dev/sndstat (obsolete) */ #define SND_DEV_UNUSED 6 #define SND_DEV_AWFM 7 /* Reserved */ #define SND_DEV_SEQ2 8 /* /dev/sequencer, level 2 interface */ /* #define SND_DEV_SNDPROC 9 */ /* /dev/sndproc for programmable devices (not used) */ /* #define SND_DEV_DMMIDI 9 */ #define SND_DEV_SYNTH 9 /* Raw synth access /dev/synth (same as /dev/dmfm) */ #define SND_DEV_DMFM 10 /* Raw synth access /dev/dmfm */ #define SND_DEV_UNKNOWN11 11 #define SND_DEV_ADSP 12 /* Like /dev/dsp (obsolete) */ #define SND_DEV_AMIDI 13 /* Like /dev/midi (obsolete) */ #define SND_DEV_ADMMIDI 14 /* Like /dev/dmmidi (onsolete) */ #endif /* _LINUX_SOUND_H */ linux/ncsi.h000064400000007450151027430560007021 0ustar00/* * Copyright Samuel Mendoza-Jonas, IBM Corporation 2018. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef __UAPI_NCSI_NETLINK_H__ #define __UAPI_NCSI_NETLINK_H__ /** * enum ncsi_nl_commands - supported NCSI commands * * @NCSI_CMD_UNSPEC: unspecified command to catch errors * @NCSI_CMD_PKG_INFO: list package and channel attributes. Requires * NCSI_ATTR_IFINDEX. If NCSI_ATTR_PACKAGE_ID is specified returns the * specific package and its channels - otherwise a dump request returns * all packages and their associated channels. * @NCSI_CMD_SET_INTERFACE: set preferred package and channel combination. * Requires NCSI_ATTR_IFINDEX and the preferred NCSI_ATTR_PACKAGE_ID and * optionally the preferred NCSI_ATTR_CHANNEL_ID. * @NCSI_CMD_CLEAR_INTERFACE: clear any preferred package/channel combination. * Requires NCSI_ATTR_IFINDEX. * @NCSI_CMD_MAX: highest command number */ enum ncsi_nl_commands { NCSI_CMD_UNSPEC, NCSI_CMD_PKG_INFO, NCSI_CMD_SET_INTERFACE, NCSI_CMD_CLEAR_INTERFACE, __NCSI_CMD_AFTER_LAST, NCSI_CMD_MAX = __NCSI_CMD_AFTER_LAST - 1 }; /** * enum ncsi_nl_attrs - General NCSI netlink attributes * * @NCSI_ATTR_UNSPEC: unspecified attributes to catch errors * @NCSI_ATTR_IFINDEX: ifindex of network device using NCSI * @NCSI_ATTR_PACKAGE_LIST: nested array of NCSI_PKG_ATTR attributes * @NCSI_ATTR_PACKAGE_ID: package ID * @NCSI_ATTR_CHANNEL_ID: channel ID * @NCSI_ATTR_MAX: highest attribute number */ enum ncsi_nl_attrs { NCSI_ATTR_UNSPEC, NCSI_ATTR_IFINDEX, NCSI_ATTR_PACKAGE_LIST, NCSI_ATTR_PACKAGE_ID, NCSI_ATTR_CHANNEL_ID, __NCSI_ATTR_AFTER_LAST, NCSI_ATTR_MAX = __NCSI_ATTR_AFTER_LAST - 1 }; /** * enum ncsi_nl_pkg_attrs - NCSI netlink package-specific attributes * * @NCSI_PKG_ATTR_UNSPEC: unspecified attributes to catch errors * @NCSI_PKG_ATTR: nested array of package attributes * @NCSI_PKG_ATTR_ID: package ID * @NCSI_PKG_ATTR_FORCED: flag signifying a package has been set as preferred * @NCSI_PKG_ATTR_CHANNEL_LIST: nested array of NCSI_CHANNEL_ATTR attributes * @NCSI_PKG_ATTR_MAX: highest attribute number */ enum ncsi_nl_pkg_attrs { NCSI_PKG_ATTR_UNSPEC, NCSI_PKG_ATTR, NCSI_PKG_ATTR_ID, NCSI_PKG_ATTR_FORCED, NCSI_PKG_ATTR_CHANNEL_LIST, __NCSI_PKG_ATTR_AFTER_LAST, NCSI_PKG_ATTR_MAX = __NCSI_PKG_ATTR_AFTER_LAST - 1 }; /** * enum ncsi_nl_channel_attrs - NCSI netlink channel-specific attributes * * @NCSI_CHANNEL_ATTR_UNSPEC: unspecified attributes to catch errors * @NCSI_CHANNEL_ATTR: nested array of channel attributes * @NCSI_CHANNEL_ATTR_ID: channel ID * @NCSI_CHANNEL_ATTR_VERSION_MAJOR: channel major version number * @NCSI_CHANNEL_ATTR_VERSION_MINOR: channel minor version number * @NCSI_CHANNEL_ATTR_VERSION_STR: channel version string * @NCSI_CHANNEL_ATTR_LINK_STATE: channel link state flags * @NCSI_CHANNEL_ATTR_ACTIVE: channels with this flag are in * NCSI_CHANNEL_ACTIVE state * @NCSI_CHANNEL_ATTR_FORCED: flag signifying a channel has been set as * preferred * @NCSI_CHANNEL_ATTR_VLAN_LIST: nested array of NCSI_CHANNEL_ATTR_VLAN_IDs * @NCSI_CHANNEL_ATTR_VLAN_ID: VLAN ID being filtered on this channel * @NCSI_CHANNEL_ATTR_MAX: highest attribute number */ enum ncsi_nl_channel_attrs { NCSI_CHANNEL_ATTR_UNSPEC, NCSI_CHANNEL_ATTR, NCSI_CHANNEL_ATTR_ID, NCSI_CHANNEL_ATTR_VERSION_MAJOR, NCSI_CHANNEL_ATTR_VERSION_MINOR, NCSI_CHANNEL_ATTR_VERSION_STR, NCSI_CHANNEL_ATTR_LINK_STATE, NCSI_CHANNEL_ATTR_ACTIVE, NCSI_CHANNEL_ATTR_FORCED, NCSI_CHANNEL_ATTR_VLAN_LIST, NCSI_CHANNEL_ATTR_VLAN_ID, __NCSI_CHANNEL_ATTR_AFTER_LAST, NCSI_CHANNEL_ATTR_MAX = __NCSI_CHANNEL_ATTR_AFTER_LAST - 1 }; #endif /* __UAPI_NCSI_NETLINK_H__ */ linux/cyclades.h000064400000041324151027430560007652 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Revision: 3.0 $$Date: 1998/11/02 14:20:59 $ * linux/include/linux/cyclades.h * * This file was initially written by * Randolph Bentson and is maintained by * Ivan Passos . * * This file contains the general definitions for the cyclades.c driver *$Log: cyclades.h,v $ *Revision 3.1 2002/01/29 11:36:16 henrique *added throttle field on struct cyclades_port to indicate whether the *port is throttled or not * *Revision 3.1 2000/04/19 18:52:52 ivan *converted address fields to unsigned long and added fields for physical *addresses on cyclades_card structure; * *Revision 3.0 1998/11/02 14:20:59 ivan *added nports field on cyclades_card structure; * *Revision 2.5 1998/08/03 16:57:01 ivan *added cyclades_idle_stats structure; * *Revision 2.4 1998/06/01 12:09:53 ivan *removed closing_wait2 from cyclades_port structure; * *Revision 2.3 1998/03/16 18:01:12 ivan *changes in the cyclades_port structure to get it closer to the *standard serial port structure; *added constants for new ioctls; * *Revision 2.2 1998/02/17 16:50:00 ivan *changes in the cyclades_port structure (addition of shutdown_wait and *chip_rev variables); *added constants for new ioctls and for CD1400 rev. numbers. * *Revision 2.1 1997/10/24 16:03:00 ivan *added rflow (which allows enabling the CD1400 special flow control *feature) and rtsdtr_inv (which allows DTR/RTS pin inversion) to *cyclades_port structure; *added Alpha support * *Revision 2.0 1997/06/30 10:30:00 ivan *added some new doorbell command constants related to IOCTLW and *UART error signaling * *Revision 1.8 1997/06/03 15:30:00 ivan *added constant ZFIRM_HLT *added constant CyPCI_Ze_win ( = 2 * Cy_PCI_Zwin) * *Revision 1.7 1997/03/26 10:30:00 daniel *new entries at the end of cyclades_port struct to reallocate *variables illegally allocated within card memory. * *Revision 1.6 1996/09/09 18:35:30 bentson *fold in changes for Cyclom-Z -- including structures for *communicating with board as well modest changes to original *structures to support new features. * *Revision 1.5 1995/11/13 21:13:31 bentson *changes suggested by Michael Chastain *to support use of this file in non-kernel applications * * */ #ifndef _LINUX_CYCLADES_H #define _LINUX_CYCLADES_H #include struct cyclades_monitor { unsigned long int_count; unsigned long char_count; unsigned long char_max; unsigned long char_last; }; /* * These stats all reflect activity since the device was last initialized. * (i.e., since the port was opened with no other processes already having it * open) */ struct cyclades_idle_stats { __kernel_time_t in_use; /* Time device has been in use (secs) */ __kernel_time_t recv_idle; /* Time since last char received (secs) */ __kernel_time_t xmit_idle; /* Time since last char transmitted (secs) */ unsigned long recv_bytes; /* Bytes received */ unsigned long xmit_bytes; /* Bytes transmitted */ unsigned long overruns; /* Input overruns */ unsigned long frame_errs; /* Input framing errors */ unsigned long parity_errs; /* Input parity errors */ }; #define CYCLADES_MAGIC 0x4359 #define CYGETMON 0x435901 #define CYGETTHRESH 0x435902 #define CYSETTHRESH 0x435903 #define CYGETDEFTHRESH 0x435904 #define CYSETDEFTHRESH 0x435905 #define CYGETTIMEOUT 0x435906 #define CYSETTIMEOUT 0x435907 #define CYGETDEFTIMEOUT 0x435908 #define CYSETDEFTIMEOUT 0x435909 #define CYSETRFLOW 0x43590a #define CYGETRFLOW 0x43590b #define CYSETRTSDTR_INV 0x43590c #define CYGETRTSDTR_INV 0x43590d #define CYZSETPOLLCYCLE 0x43590e #define CYZGETPOLLCYCLE 0x43590f #define CYGETCD1400VER 0x435910 #define CYSETWAIT 0x435912 #define CYGETWAIT 0x435913 /*************** CYCLOM-Z ADDITIONS ***************/ #define CZIOC ('M' << 8) #define CZ_NBOARDS (CZIOC|0xfa) #define CZ_BOOT_START (CZIOC|0xfb) #define CZ_BOOT_DATA (CZIOC|0xfc) #define CZ_BOOT_END (CZIOC|0xfd) #define CZ_TEST (CZIOC|0xfe) #define CZ_DEF_POLL (HZ/25) #define MAX_BOARD 4 /* Max number of boards */ #define MAX_DEV 256 /* Max number of ports total */ #define CYZ_MAX_SPEED 921600 #define CYZ_FIFO_SIZE 16 #define CYZ_BOOT_NWORDS 0x100 struct CYZ_BOOT_CTRL { unsigned short nboard; int status[MAX_BOARD]; int nchannel[MAX_BOARD]; int fw_rev[MAX_BOARD]; unsigned long offset; unsigned long data[CYZ_BOOT_NWORDS]; }; #ifndef DP_WINDOW_SIZE /* * Memory Window Sizes */ #define DP_WINDOW_SIZE (0x00080000) /* window size 512 Kb */ #define ZE_DP_WINDOW_SIZE (0x00100000) /* window size 1 Mb (Ze and 8Zo V.2 */ #define CTRL_WINDOW_SIZE (0x00000080) /* runtime regs 128 bytes */ /* * CUSTOM_REG - Cyclom-Z/PCI Custom Registers Set. The driver * normally will access only interested on the fpga_id, fpga_version, * start_cpu and stop_cpu. */ struct CUSTOM_REG { __u32 fpga_id; /* FPGA Identification Register */ __u32 fpga_version; /* FPGA Version Number Register */ __u32 cpu_start; /* CPU start Register (write) */ __u32 cpu_stop; /* CPU stop Register (write) */ __u32 misc_reg; /* Miscellaneous Register */ __u32 idt_mode; /* IDT mode Register */ __u32 uart_irq_status; /* UART IRQ status Register */ __u32 clear_timer0_irq; /* Clear timer interrupt Register */ __u32 clear_timer1_irq; /* Clear timer interrupt Register */ __u32 clear_timer2_irq; /* Clear timer interrupt Register */ __u32 test_register; /* Test Register */ __u32 test_count; /* Test Count Register */ __u32 timer_select; /* Timer select register */ __u32 pr_uart_irq_status; /* Prioritized UART IRQ stat Reg */ __u32 ram_wait_state; /* RAM wait-state Register */ __u32 uart_wait_state; /* UART wait-state Register */ __u32 timer_wait_state; /* timer wait-state Register */ __u32 ack_wait_state; /* ACK wait State Register */ }; /* * RUNTIME_9060 - PLX PCI9060ES local configuration and shared runtime * registers. This structure can be used to access the 9060 registers * (memory mapped). */ struct RUNTIME_9060 { __u32 loc_addr_range; /* 00h - Local Address Range */ __u32 loc_addr_base; /* 04h - Local Address Base */ __u32 loc_arbitr; /* 08h - Local Arbitration */ __u32 endian_descr; /* 0Ch - Big/Little Endian Descriptor */ __u32 loc_rom_range; /* 10h - Local ROM Range */ __u32 loc_rom_base; /* 14h - Local ROM Base */ __u32 loc_bus_descr; /* 18h - Local Bus descriptor */ __u32 loc_range_mst; /* 1Ch - Local Range for Master to PCI */ __u32 loc_base_mst; /* 20h - Local Base for Master PCI */ __u32 loc_range_io; /* 24h - Local Range for Master IO */ __u32 pci_base_mst; /* 28h - PCI Base for Master PCI */ __u32 pci_conf_io; /* 2Ch - PCI configuration for Master IO */ __u32 filler1; /* 30h */ __u32 filler2; /* 34h */ __u32 filler3; /* 38h */ __u32 filler4; /* 3Ch */ __u32 mail_box_0; /* 40h - Mail Box 0 */ __u32 mail_box_1; /* 44h - Mail Box 1 */ __u32 mail_box_2; /* 48h - Mail Box 2 */ __u32 mail_box_3; /* 4Ch - Mail Box 3 */ __u32 filler5; /* 50h */ __u32 filler6; /* 54h */ __u32 filler7; /* 58h */ __u32 filler8; /* 5Ch */ __u32 pci_doorbell; /* 60h - PCI to Local Doorbell */ __u32 loc_doorbell; /* 64h - Local to PCI Doorbell */ __u32 intr_ctrl_stat; /* 68h - Interrupt Control/Status */ __u32 init_ctrl; /* 6Ch - EEPROM control, Init Control, etc */ }; /* Values for the Local Base Address re-map register */ #define WIN_RAM 0x00000001L /* set the sliding window to RAM */ #define WIN_CREG 0x14000001L /* set the window to custom Registers */ /* Values timer select registers */ #define TIMER_BY_1M 0x00 /* clock divided by 1M */ #define TIMER_BY_256K 0x01 /* clock divided by 256k */ #define TIMER_BY_128K 0x02 /* clock divided by 128k */ #define TIMER_BY_32K 0x03 /* clock divided by 32k */ /****************** ****************** *******************/ #endif #ifndef ZFIRM_ID /* #include "zfwint.h" */ /****************** ****************** *******************/ /* * This file contains the definitions for interfacing with the * Cyclom-Z ZFIRM Firmware. */ /* General Constant definitions */ #define MAX_CHAN 64 /* max number of channels per board */ /* firmware id structure (set after boot) */ #define ID_ADDRESS 0x00000180L /* signature/pointer address */ #define ZFIRM_ID 0x5557465AL /* ZFIRM/U signature */ #define ZFIRM_HLT 0x59505B5CL /* ZFIRM needs external power supply */ #define ZFIRM_RST 0x56040674L /* RST signal (due to FW reset) */ #define ZF_TINACT_DEF 1000 /* default inactivity timeout (1000 ms) */ #define ZF_TINACT ZF_TINACT_DEF struct FIRM_ID { __u32 signature; /* ZFIRM/U signature */ __u32 zfwctrl_addr; /* pointer to ZFW_CTRL structure */ }; /* Op. System id */ #define C_OS_LINUX 0x00000030 /* generic Linux system */ /* channel op_mode */ #define C_CH_DISABLE 0x00000000 /* channel is disabled */ #define C_CH_TXENABLE 0x00000001 /* channel Tx enabled */ #define C_CH_RXENABLE 0x00000002 /* channel Rx enabled */ #define C_CH_ENABLE 0x00000003 /* channel Tx/Rx enabled */ #define C_CH_LOOPBACK 0x00000004 /* Loopback mode */ /* comm_parity - parity */ #define C_PR_NONE 0x00000000 /* None */ #define C_PR_ODD 0x00000001 /* Odd */ #define C_PR_EVEN 0x00000002 /* Even */ #define C_PR_MARK 0x00000004 /* Mark */ #define C_PR_SPACE 0x00000008 /* Space */ #define C_PR_PARITY 0x000000ff #define C_PR_DISCARD 0x00000100 /* discard char with frame/par error */ #define C_PR_IGNORE 0x00000200 /* ignore frame/par error */ /* comm_data_l - data length and stop bits */ #define C_DL_CS5 0x00000001 #define C_DL_CS6 0x00000002 #define C_DL_CS7 0x00000004 #define C_DL_CS8 0x00000008 #define C_DL_CS 0x0000000f #define C_DL_1STOP 0x00000010 #define C_DL_15STOP 0x00000020 #define C_DL_2STOP 0x00000040 #define C_DL_STOP 0x000000f0 /* interrupt enabling/status */ #define C_IN_DISABLE 0x00000000 /* zero, disable interrupts */ #define C_IN_TXBEMPTY 0x00000001 /* tx buffer empty */ #define C_IN_TXLOWWM 0x00000002 /* tx buffer below LWM */ #define C_IN_RXHIWM 0x00000010 /* rx buffer above HWM */ #define C_IN_RXNNDT 0x00000020 /* rx no new data timeout */ #define C_IN_MDCD 0x00000100 /* modem DCD change */ #define C_IN_MDSR 0x00000200 /* modem DSR change */ #define C_IN_MRI 0x00000400 /* modem RI change */ #define C_IN_MCTS 0x00000800 /* modem CTS change */ #define C_IN_RXBRK 0x00001000 /* Break received */ #define C_IN_PR_ERROR 0x00002000 /* parity error */ #define C_IN_FR_ERROR 0x00004000 /* frame error */ #define C_IN_OVR_ERROR 0x00008000 /* overrun error */ #define C_IN_RXOFL 0x00010000 /* RX buffer overflow */ #define C_IN_IOCTLW 0x00020000 /* I/O control w/ wait */ #define C_IN_MRTS 0x00040000 /* modem RTS drop */ #define C_IN_ICHAR 0x00080000 /* flow control */ #define C_FL_OXX 0x00000001 /* output Xon/Xoff flow control */ #define C_FL_IXX 0x00000002 /* output Xon/Xoff flow control */ #define C_FL_OIXANY 0x00000004 /* output Xon/Xoff (any xon) */ #define C_FL_SWFLOW 0x0000000f /* flow status */ #define C_FS_TXIDLE 0x00000000 /* no Tx data in the buffer or UART */ #define C_FS_SENDING 0x00000001 /* UART is sending data */ #define C_FS_SWFLOW 0x00000002 /* Tx is stopped by received Xoff */ /* rs_control/rs_status RS-232 signals */ #define C_RS_PARAM 0x80000000 /* Indicates presence of parameter in IOCTLM command */ #define C_RS_RTS 0x00000001 /* RTS */ #define C_RS_DTR 0x00000004 /* DTR */ #define C_RS_DCD 0x00000100 /* CD */ #define C_RS_DSR 0x00000200 /* DSR */ #define C_RS_RI 0x00000400 /* RI */ #define C_RS_CTS 0x00000800 /* CTS */ /* commands Host <-> Board */ #define C_CM_RESET 0x01 /* reset/flush buffers */ #define C_CM_IOCTL 0x02 /* re-read CH_CTRL */ #define C_CM_IOCTLW 0x03 /* re-read CH_CTRL, intr when done */ #define C_CM_IOCTLM 0x04 /* RS-232 outputs change */ #define C_CM_SENDXOFF 0x10 /* send Xoff */ #define C_CM_SENDXON 0x11 /* send Xon */ #define C_CM_CLFLOW 0x12 /* Clear flow control (resume) */ #define C_CM_SENDBRK 0x41 /* send break */ #define C_CM_INTBACK 0x42 /* Interrupt back */ #define C_CM_SET_BREAK 0x43 /* Tx break on */ #define C_CM_CLR_BREAK 0x44 /* Tx break off */ #define C_CM_CMD_DONE 0x45 /* Previous command done */ #define C_CM_INTBACK2 0x46 /* Alternate Interrupt back */ #define C_CM_TINACT 0x51 /* set inactivity detection */ #define C_CM_IRQ_ENBL 0x52 /* enable generation of interrupts */ #define C_CM_IRQ_DSBL 0x53 /* disable generation of interrupts */ #define C_CM_ACK_ENBL 0x54 /* enable acknowledged interrupt mode */ #define C_CM_ACK_DSBL 0x55 /* disable acknowledged intr mode */ #define C_CM_FLUSH_RX 0x56 /* flushes Rx buffer */ #define C_CM_FLUSH_TX 0x57 /* flushes Tx buffer */ #define C_CM_Q_ENABLE 0x58 /* enables queue access from the driver */ #define C_CM_Q_DISABLE 0x59 /* disables queue access from the driver */ #define C_CM_TXBEMPTY 0x60 /* Tx buffer is empty */ #define C_CM_TXLOWWM 0x61 /* Tx buffer low water mark */ #define C_CM_RXHIWM 0x62 /* Rx buffer high water mark */ #define C_CM_RXNNDT 0x63 /* rx no new data timeout */ #define C_CM_TXFEMPTY 0x64 #define C_CM_ICHAR 0x65 #define C_CM_MDCD 0x70 /* modem DCD change */ #define C_CM_MDSR 0x71 /* modem DSR change */ #define C_CM_MRI 0x72 /* modem RI change */ #define C_CM_MCTS 0x73 /* modem CTS change */ #define C_CM_MRTS 0x74 /* modem RTS drop */ #define C_CM_RXBRK 0x84 /* Break received */ #define C_CM_PR_ERROR 0x85 /* Parity error */ #define C_CM_FR_ERROR 0x86 /* Frame error */ #define C_CM_OVR_ERROR 0x87 /* Overrun error */ #define C_CM_RXOFL 0x88 /* RX buffer overflow */ #define C_CM_CMDERROR 0x90 /* command error */ #define C_CM_FATAL 0x91 /* fatal error */ #define C_CM_HW_RESET 0x92 /* reset board */ /* * CH_CTRL - This per port structure contains all parameters * that control an specific port. It can be seen as the * configuration registers of a "super-serial-controller". */ struct CH_CTRL { __u32 op_mode; /* operation mode */ __u32 intr_enable; /* interrupt masking */ __u32 sw_flow; /* SW flow control */ __u32 flow_status; /* output flow status */ __u32 comm_baud; /* baud rate - numerically specified */ __u32 comm_parity; /* parity */ __u32 comm_data_l; /* data length/stop */ __u32 comm_flags; /* other flags */ __u32 hw_flow; /* HW flow control */ __u32 rs_control; /* RS-232 outputs */ __u32 rs_status; /* RS-232 inputs */ __u32 flow_xon; /* xon char */ __u32 flow_xoff; /* xoff char */ __u32 hw_overflow; /* hw overflow counter */ __u32 sw_overflow; /* sw overflow counter */ __u32 comm_error; /* frame/parity error counter */ __u32 ichar; __u32 filler[7]; }; /* * BUF_CTRL - This per channel structure contains * all Tx and Rx buffer control for a given channel. */ struct BUF_CTRL { __u32 flag_dma; /* buffers are in Host memory */ __u32 tx_bufaddr; /* address of the tx buffer */ __u32 tx_bufsize; /* tx buffer size */ __u32 tx_threshold; /* tx low water mark */ __u32 tx_get; /* tail index tx buf */ __u32 tx_put; /* head index tx buf */ __u32 rx_bufaddr; /* address of the rx buffer */ __u32 rx_bufsize; /* rx buffer size */ __u32 rx_threshold; /* rx high water mark */ __u32 rx_get; /* tail index rx buf */ __u32 rx_put; /* head index rx buf */ __u32 filler[5]; /* filler to align structures */ }; /* * BOARD_CTRL - This per board structure contains all global * control fields related to the board. */ struct BOARD_CTRL { /* static info provided by the on-board CPU */ __u32 n_channel; /* number of channels */ __u32 fw_version; /* firmware version */ /* static info provided by the driver */ __u32 op_system; /* op_system id */ __u32 dr_version; /* driver version */ /* board control area */ __u32 inactivity; /* inactivity control */ /* host to FW commands */ __u32 hcmd_channel; /* channel number */ __u32 hcmd_param; /* pointer to parameters */ /* FW to Host commands */ __u32 fwcmd_channel; /* channel number */ __u32 fwcmd_param; /* pointer to parameters */ __u32 zf_int_queue_addr; /* offset for INT_QUEUE structure */ /* filler so the structures are aligned */ __u32 filler[6]; }; /* Host Interrupt Queue */ #define QUEUE_SIZE (10*MAX_CHAN) struct INT_QUEUE { unsigned char intr_code[QUEUE_SIZE]; unsigned long channel[QUEUE_SIZE]; unsigned long param[QUEUE_SIZE]; unsigned long put; unsigned long get; }; /* * ZFW_CTRL - This is the data structure that includes all other * data structures used by the Firmware. */ struct ZFW_CTRL { struct BOARD_CTRL board_ctrl; struct CH_CTRL ch_ctrl[MAX_CHAN]; struct BUF_CTRL buf_ctrl[MAX_CHAN]; }; /****************** ****************** *******************/ #endif #endif /* _LINUX_CYCLADES_H */ linux/mic_ioctl.h000064400000004314151027430560010023 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Intel MIC Platform Software Stack (MPSS) * * Copyright(c) 2013 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Intel MIC Host driver. * */ #ifndef _MIC_IOCTL_H_ #define _MIC_IOCTL_H_ #include /* * mic_copy - MIC virtio descriptor copy. * * @iov: An array of IOVEC structures containing user space buffers. * @iovcnt: Number of IOVEC structures in iov. * @vr_idx: The vring index. * @update_used: A non zero value results in used index being updated. * @out_len: The aggregate of the total length written to or read from * the virtio device. */ struct mic_copy_desc { struct iovec *iov; __u32 iovcnt; __u8 vr_idx; __u8 update_used; __u32 out_len; }; /* * Add a new virtio device * The (struct mic_device_desc *) pointer points to a device page entry * for the virtio device consisting of: * - struct mic_device_desc * - struct mic_vqconfig (num_vq of these) * - host and guest features * - virtio device config space * The total size referenced by the pointer should equal the size returned * by desc_size() in mic_common.h */ #define MIC_VIRTIO_ADD_DEVICE _IOWR('s', 1, struct mic_device_desc *) /* * Copy the number of entries in the iovec and update the used index * if requested by the user. */ #define MIC_VIRTIO_COPY_DESC _IOWR('s', 2, struct mic_copy_desc *) /* * Notify virtio device of a config change * The (__u8 *) pointer points to config space values for the device * as they should be written into the device page. The total size * referenced by the pointer should equal the config_len field of struct * mic_device_desc. */ #define MIC_VIRTIO_CONFIG_CHANGE _IOWR('s', 5, __u8 *) #endif linux/errqueue.h000064400000002705151027430560007720 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_ERRQUEUE_H #define _LINUX_ERRQUEUE_H #include struct sock_extended_err { __u32 ee_errno; __u8 ee_origin; __u8 ee_type; __u8 ee_code; __u8 ee_pad; __u32 ee_info; __u32 ee_data; }; #define SO_EE_ORIGIN_NONE 0 #define SO_EE_ORIGIN_LOCAL 1 #define SO_EE_ORIGIN_ICMP 2 #define SO_EE_ORIGIN_ICMP6 3 #define SO_EE_ORIGIN_TXSTATUS 4 #define SO_EE_ORIGIN_ZEROCOPY 5 #define SO_EE_ORIGIN_TXTIME 6 #define SO_EE_ORIGIN_TIMESTAMPING SO_EE_ORIGIN_TXSTATUS #define SO_EE_OFFENDER(ee) ((struct sockaddr*)((ee)+1)) #define SO_EE_CODE_ZEROCOPY_COPIED 1 #define SO_EE_CODE_TXTIME_INVALID_PARAM 1 #define SO_EE_CODE_TXTIME_MISSED 2 /** * struct scm_timestamping - timestamps exposed through cmsg * * The timestamping interfaces SO_TIMESTAMPING, MSG_TSTAMP_* * communicate network timestamps by passing this struct in a cmsg with * recvmsg(). See Documentation/networking/timestamping.txt for details. */ struct scm_timestamping { struct timespec ts[3]; }; /* The type of scm_timestamping, passed in sock_extended_err ee_info. * This defines the type of ts[0]. For SCM_TSTAMP_SND only, if ts[0] * is zero, then this is a hardware timestamp and recorded in ts[2]. */ enum { SCM_TSTAMP_SND, /* driver passed skb to NIC, or HW */ SCM_TSTAMP_SCHED, /* data entered the packet scheduler */ SCM_TSTAMP_ACK, /* data acknowledged by peer */ }; #endif /* _LINUX_ERRQUEUE_H */ linux/rio_cm_cdev.h000064400000006260151027430560010334 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Copyright (c) 2015, Integrated Device Technology Inc. * Copyright (c) 2015, Prodrive Technologies * Copyright (c) 2015, RapidIO Trade Association * All rights reserved. * * This software is available to you under a choice of one of two licenses. * You may choose to be licensed under the terms of the GNU General Public * License(GPL) Version 2, or the BSD-3 Clause license below: * * 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. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _RIO_CM_CDEV_H_ #define _RIO_CM_CDEV_H_ #include struct rio_cm_channel { __u16 id; __u16 remote_channel; __u16 remote_destid; __u8 mport_id; }; struct rio_cm_msg { __u16 ch_num; __u16 size; __u32 rxto; /* receive timeout in mSec. 0 = blocking */ __u64 msg; }; struct rio_cm_accept { __u16 ch_num; __u16 pad0; __u32 wait_to; /* accept timeout in mSec. 0 = blocking */ }; /* RapidIO Channelized Messaging Driver IOCTLs */ #define RIO_CM_IOC_MAGIC 'c' #define RIO_CM_EP_GET_LIST_SIZE _IOWR(RIO_CM_IOC_MAGIC, 1, __u32) #define RIO_CM_EP_GET_LIST _IOWR(RIO_CM_IOC_MAGIC, 2, __u32) #define RIO_CM_CHAN_CREATE _IOWR(RIO_CM_IOC_MAGIC, 3, __u16) #define RIO_CM_CHAN_CLOSE _IOW(RIO_CM_IOC_MAGIC, 4, __u16) #define RIO_CM_CHAN_BIND _IOW(RIO_CM_IOC_MAGIC, 5, struct rio_cm_channel) #define RIO_CM_CHAN_LISTEN _IOW(RIO_CM_IOC_MAGIC, 6, __u16) #define RIO_CM_CHAN_ACCEPT _IOWR(RIO_CM_IOC_MAGIC, 7, struct rio_cm_accept) #define RIO_CM_CHAN_CONNECT _IOW(RIO_CM_IOC_MAGIC, 8, struct rio_cm_channel) #define RIO_CM_CHAN_SEND _IOW(RIO_CM_IOC_MAGIC, 9, struct rio_cm_msg) #define RIO_CM_CHAN_RECEIVE _IOWR(RIO_CM_IOC_MAGIC, 10, struct rio_cm_msg) #define RIO_CM_MPORT_GET_LIST _IOWR(RIO_CM_IOC_MAGIC, 11, __u32) #endif /* _RIO_CM_CDEV_H_ */ linux/ife.h000064400000000537151027430560006627 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_IFE_H #define __UAPI_IFE_H #define IFE_METAHDRLEN 2 enum { IFE_META_SKBMARK = 1, IFE_META_HASHID, IFE_META_PRIO, IFE_META_QMAP, IFE_META_TCINDEX, __IFE_META_MAX }; /*Can be overridden at runtime by module option*/ #define IFE_META_MAX (__IFE_META_MAX - 1) #endif linux/sonet.h000064400000004362151027430560007214 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* sonet.h - SONET/SHD physical layer control */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #ifndef LINUX_SONET_H #define LINUX_SONET_H #define __SONET_ITEMS \ __HANDLE_ITEM(section_bip); /* section parity errors (B1) */ \ __HANDLE_ITEM(line_bip); /* line parity errors (B2) */ \ __HANDLE_ITEM(path_bip); /* path parity errors (B3) */ \ __HANDLE_ITEM(line_febe); /* line parity errors at remote */ \ __HANDLE_ITEM(path_febe); /* path parity errors at remote */ \ __HANDLE_ITEM(corr_hcs); /* correctable header errors */ \ __HANDLE_ITEM(uncorr_hcs); /* uncorrectable header errors */ \ __HANDLE_ITEM(tx_cells); /* cells sent */ \ __HANDLE_ITEM(rx_cells); /* cells received */ struct sonet_stats { #define __HANDLE_ITEM(i) int i __SONET_ITEMS #undef __HANDLE_ITEM } __attribute__ ((packed)); #define SONET_GETSTAT _IOR('a',ATMIOC_PHYTYP,struct sonet_stats) /* get statistics */ #define SONET_GETSTATZ _IOR('a',ATMIOC_PHYTYP+1,struct sonet_stats) /* ... and zero counters */ #define SONET_SETDIAG _IOWR('a',ATMIOC_PHYTYP+2,int) /* set error insertion */ #define SONET_CLRDIAG _IOWR('a',ATMIOC_PHYTYP+3,int) /* clear error insertion */ #define SONET_GETDIAG _IOR('a',ATMIOC_PHYTYP+4,int) /* query error insertion */ #define SONET_SETFRAMING _IOW('a',ATMIOC_PHYTYP+5,int) /* set framing mode (SONET/SDH) */ #define SONET_GETFRAMING _IOR('a',ATMIOC_PHYTYP+6,int) /* get framing mode */ #define SONET_GETFRSENSE _IOR('a',ATMIOC_PHYTYP+7, \ unsigned char[SONET_FRSENSE_SIZE]) /* get framing sense information */ #define SONET_INS_SBIP 1 /* section BIP */ #define SONET_INS_LBIP 2 /* line BIP */ #define SONET_INS_PBIP 4 /* path BIP */ #define SONET_INS_FRAME 8 /* out of frame */ #define SONET_INS_LOS 16 /* set line to zero */ #define SONET_INS_LAIS 32 /* line alarm indication signal */ #define SONET_INS_PAIS 64 /* path alarm indication signal */ #define SONET_INS_HCS 128 /* insert HCS error */ #define SONET_FRAME_SONET 0 /* SONET STS-3 framing */ #define SONET_FRAME_SDH 1 /* SDH STM-1 framing */ #define SONET_FRSENSE_SIZE 6 /* C1[3],H1[3] (0xff for unknown) */ #endif /* LINUX_SONET_H */ linux/smiapp.h000064400000002042151027430560007346 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/uapi/linux/smiapp.h * * Generic driver for SMIA/SMIA++ compliant camera modules * * Copyright (C) 2014 Intel Corporation * Contact: Sakari Ailus * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * */ #ifndef __UAPI_LINUX_SMIAPP_H_ #define __UAPI_LINUX_SMIAPP_H_ #define V4L2_SMIAPP_TEST_PATTERN_MODE_DISABLED 0 #define V4L2_SMIAPP_TEST_PATTERN_MODE_SOLID_COLOUR 1 #define V4L2_SMIAPP_TEST_PATTERN_MODE_COLOUR_BARS 2 #define V4L2_SMIAPP_TEST_PATTERN_MODE_COLOUR_BARS_GREY 3 #define V4L2_SMIAPP_TEST_PATTERN_MODE_PN9 4 #endif /* __UAPI_LINUX_SMIAPP_H_ */ linux/isdn.h000064400000013216151027430560007017 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: isdn.h,v 1.125.2.3 2004/02/10 01:07:14 keil Exp $ * * Main header for the Linux ISDN subsystem (linklevel). * * Copyright 1994,95,96 by Fritz Elfert (fritz@isdn4linux.de) * Copyright 1995,96 by Thinking Objects Software GmbH Wuerzburg * Copyright 1995,96 by Michael Hipp (Michael.Hipp@student.uni-tuebingen.de) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef __ISDN_H__ #define __ISDN_H__ #include #include #define ISDN_MAX_DRIVERS 32 #define ISDN_MAX_CHANNELS 64 /* New ioctl-codes */ #define IIOCNETAIF _IO('I',1) #define IIOCNETDIF _IO('I',2) #define IIOCNETSCF _IO('I',3) #define IIOCNETGCF _IO('I',4) #define IIOCNETANM _IO('I',5) #define IIOCNETDNM _IO('I',6) #define IIOCNETGNM _IO('I',7) #define IIOCGETSET _IO('I',8) /* no longer supported */ #define IIOCSETSET _IO('I',9) /* no longer supported */ #define IIOCSETVER _IO('I',10) #define IIOCNETHUP _IO('I',11) #define IIOCSETGST _IO('I',12) #define IIOCSETBRJ _IO('I',13) #define IIOCSIGPRF _IO('I',14) #define IIOCGETPRF _IO('I',15) #define IIOCSETPRF _IO('I',16) #define IIOCGETMAP _IO('I',17) #define IIOCSETMAP _IO('I',18) #define IIOCNETASL _IO('I',19) #define IIOCNETDIL _IO('I',20) #define IIOCGETCPS _IO('I',21) #define IIOCGETDVR _IO('I',22) #define IIOCNETLCR _IO('I',23) /* dwabc ioctl for LCR from isdnlog */ #define IIOCNETDWRSET _IO('I',24) /* dwabc ioctl to reset abc-values to default on a net-interface */ #define IIOCNETALN _IO('I',32) #define IIOCNETDLN _IO('I',33) #define IIOCNETGPN _IO('I',34) #define IIOCDBGVAR _IO('I',127) #define IIOCDRVCTL _IO('I',128) /* cisco hdlck device private ioctls */ #define SIOCGKEEPPERIOD (SIOCDEVPRIVATE + 0) #define SIOCSKEEPPERIOD (SIOCDEVPRIVATE + 1) #define SIOCGDEBSERINT (SIOCDEVPRIVATE + 2) #define SIOCSDEBSERINT (SIOCDEVPRIVATE + 3) /* Packet encapsulations for net-interfaces */ #define ISDN_NET_ENCAP_ETHER 0 #define ISDN_NET_ENCAP_RAWIP 1 #define ISDN_NET_ENCAP_IPTYP 2 #define ISDN_NET_ENCAP_CISCOHDLC 3 /* Without SLARP and keepalive */ #define ISDN_NET_ENCAP_SYNCPPP 4 #define ISDN_NET_ENCAP_UIHDLC 5 #define ISDN_NET_ENCAP_CISCOHDLCK 6 /* With SLARP and keepalive */ #define ISDN_NET_ENCAP_X25IFACE 7 /* Documentation/networking/x25-iface.txt */ #define ISDN_NET_ENCAP_MAX_ENCAP ISDN_NET_ENCAP_X25IFACE /* Facility which currently uses an ISDN-channel */ #define ISDN_USAGE_NONE 0 #define ISDN_USAGE_RAW 1 #define ISDN_USAGE_MODEM 2 #define ISDN_USAGE_NET 3 #define ISDN_USAGE_VOICE 4 #define ISDN_USAGE_FAX 5 #define ISDN_USAGE_MASK 7 /* Mask to get plain usage */ #define ISDN_USAGE_DISABLED 32 /* This bit is set, if channel is disabled */ #define ISDN_USAGE_EXCLUSIVE 64 /* This bit is set, if channel is exclusive */ #define ISDN_USAGE_OUTGOING 128 /* This bit is set, if channel is outgoing */ #define ISDN_MODEM_NUMREG 24 /* Number of Modem-Registers */ #define ISDN_LMSNLEN 255 /* Length of tty's Listen-MSN string */ #define ISDN_CMSGLEN 50 /* Length of CONNECT-Message to add for Modem */ #define ISDN_MSNLEN 32 #define NET_DV 0x06 /* Data version for isdn_net_ioctl_cfg */ #define TTY_DV 0x06 /* Data version for iprofd etc. */ #define INF_DV 0x01 /* Data version for /dev/isdninfo */ typedef struct { char drvid[25]; unsigned long arg; } isdn_ioctl_struct; typedef struct { char name[10]; char phone[ISDN_MSNLEN]; int outgoing; } isdn_net_ioctl_phone; typedef struct { char name[10]; /* Name of interface */ char master[10]; /* Name of Master for Bundling */ char slave[10]; /* Name of Slave for Bundling */ char eaz[256]; /* EAZ/MSN */ char drvid[25]; /* DriverId for Bindings */ int onhtime; /* Hangup-Timeout */ int charge; /* Charge-Units */ int l2_proto; /* Layer-2 protocol */ int l3_proto; /* Layer-3 protocol */ int p_encap; /* Encapsulation */ int exclusive; /* Channel, if bound exclusive */ int dialmax; /* Dial Retry-Counter */ int slavedelay; /* Delay until slave starts up */ int cbdelay; /* Delay before Callback */ int chargehup; /* Flag: Charge-Hangup */ int ihup; /* Flag: Hangup-Timeout on incoming line */ int secure; /* Flag: Secure */ int callback; /* Flag: Callback */ int cbhup; /* Flag: Reject Call before Callback */ int pppbind; /* ippp device for bindings */ int chargeint; /* Use fixed charge interval length */ int triggercps; /* BogoCPS needed for triggering slave */ int dialtimeout; /* Dial-Timeout */ int dialwait; /* Time to wait after failed dial */ int dialmode; /* Flag: off / on / auto */ } isdn_net_ioctl_cfg; #define ISDN_NET_DIALMODE_MASK 0xC0 /* bits for status */ #define ISDN_NET_DM_OFF 0x00 /* this interface is stopped */ #define ISDN_NET_DM_MANUAL 0x40 /* this interface is on (manual) */ #define ISDN_NET_DM_AUTO 0x80 /* this interface is autodial */ #define ISDN_NET_DIALMODE(x) ((&(x))->flags & ISDN_NET_DIALMODE_MASK) #endif /* __ISDN_H__ */ linux/rio_mport_cdev.h000064400000022162151027430560011075 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */ /* * Copyright (c) 2015-2016, Integrated Device Technology Inc. * Copyright (c) 2015, Prodrive Technologies * Copyright (c) 2015, Texas Instruments Incorporated * Copyright (c) 2015, RapidIO Trade Association * All rights reserved. * * This software is available to you under a choice of one of two licenses. * You may choose to be licensed under the terms of the GNU General Public * License(GPL) Version 2, or the BSD-3 Clause license below: * * 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. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _RIO_MPORT_CDEV_H_ #define _RIO_MPORT_CDEV_H_ #include #include struct rio_mport_maint_io { __u16 rioid; /* destID of remote device */ __u8 hopcount; /* hopcount to remote device */ __u8 pad0[5]; __u32 offset; /* offset in register space */ __u32 length; /* length in bytes */ __u64 buffer; /* pointer to data buffer */ }; /* * Definitions for RapidIO data transfers: * - memory mapped (MAPPED) * - packet generation from memory (TRANSFER) */ #define RIO_TRANSFER_MODE_MAPPED (1 << 0) #define RIO_TRANSFER_MODE_TRANSFER (1 << 1) #define RIO_CAP_DBL_SEND (1 << 2) #define RIO_CAP_DBL_RECV (1 << 3) #define RIO_CAP_PW_SEND (1 << 4) #define RIO_CAP_PW_RECV (1 << 5) #define RIO_CAP_MAP_OUTB (1 << 6) #define RIO_CAP_MAP_INB (1 << 7) struct rio_mport_properties { __u16 hdid; __u8 id; /* Physical port ID */ __u8 index; __u32 flags; __u32 sys_size; /* Default addressing size */ __u8 port_ok; __u8 link_speed; __u8 link_width; __u8 pad0; __u32 dma_max_sge; __u32 dma_max_size; __u32 dma_align; __u32 transfer_mode; /* Default transfer mode */ __u32 cap_sys_size; /* Capable system sizes */ __u32 cap_addr_size; /* Capable addressing sizes */ __u32 cap_transfer_mode; /* Capable transfer modes */ __u32 cap_mport; /* Mport capabilities */ }; /* * Definitions for RapidIO events; * - incoming port-writes * - incoming doorbells */ #define RIO_DOORBELL (1 << 0) #define RIO_PORTWRITE (1 << 1) struct rio_doorbell { __u16 rioid; __u16 payload; }; struct rio_doorbell_filter { __u16 rioid; /* Use RIO_INVALID_DESTID to match all ids */ __u16 low; __u16 high; __u16 pad0; }; struct rio_portwrite { __u32 payload[16]; }; struct rio_pw_filter { __u32 mask; __u32 low; __u32 high; __u32 pad0; }; /* RapidIO base address for inbound requests set to value defined below * indicates that no specific RIO-to-local address translation is requested * and driver should use direct (one-to-one) address mapping. */ #define RIO_MAP_ANY_ADDR (__u64)(~((__u64) 0)) struct rio_mmap { __u16 rioid; __u16 pad0[3]; __u64 rio_addr; __u64 length; __u64 handle; __u64 address; }; struct rio_dma_mem { __u64 length; /* length of DMA memory */ __u64 dma_handle; /* handle associated with this memory */ __u64 address; }; struct rio_event { __u32 header; /* event type RIO_DOORBELL or RIO_PORTWRITE */ union { struct rio_doorbell doorbell; /* header for RIO_DOORBELL */ struct rio_portwrite portwrite; /* header for RIO_PORTWRITE */ } u; __u32 pad0; }; enum rio_transfer_sync { RIO_TRANSFER_SYNC, /* synchronous transfer */ RIO_TRANSFER_ASYNC, /* asynchronous transfer */ RIO_TRANSFER_FAF, /* fire-and-forget transfer */ }; enum rio_transfer_dir { RIO_TRANSFER_DIR_READ, /* Read operation */ RIO_TRANSFER_DIR_WRITE, /* Write operation */ }; /* * RapidIO data exchange transactions are lists of individual transfers. Each * transfer exchanges data between two RapidIO devices by remote direct memory * access and has its own completion code. * * The RapidIO specification defines four types of data exchange requests: * NREAD, NWRITE, SWRITE and NWRITE_R. The RapidIO DMA channel interface allows * to specify the required type of write operation or combination of them when * only the last data packet requires response. * * NREAD: read up to 256 bytes from remote device memory into local memory * NWRITE: write up to 256 bytes from local memory to remote device memory * without confirmation * SWRITE: as NWRITE, but all addresses and payloads must be 64-bit aligned * NWRITE_R: as NWRITE, but expect acknowledgment from remote device. * * The default exchange is chosen from NREAD and any of the WRITE modes as the * driver sees fit. For write requests the user can explicitly choose between * any of the write modes for each transaction. */ enum rio_exchange { RIO_EXCHANGE_DEFAULT, /* Default method */ RIO_EXCHANGE_NWRITE, /* All packets using NWRITE */ RIO_EXCHANGE_SWRITE, /* All packets using SWRITE */ RIO_EXCHANGE_NWRITE_R, /* Last packet NWRITE_R, others NWRITE */ RIO_EXCHANGE_SWRITE_R, /* Last packet NWRITE_R, others SWRITE */ RIO_EXCHANGE_NWRITE_R_ALL, /* All packets using NWRITE_R */ }; struct rio_transfer_io { __u64 rio_addr; /* Address in target's RIO mem space */ __u64 loc_addr; __u64 handle; __u64 offset; /* Offset in buffer */ __u64 length; /* Length in bytes */ __u16 rioid; /* Target destID */ __u16 method; /* Data exchange method, one of rio_exchange enum */ __u32 completion_code; /* Completion code for this transfer */ }; struct rio_transaction { __u64 block; /* Pointer to array of transfers */ __u32 count; /* Number of transfers */ __u32 transfer_mode; /* Data transfer mode */ __u16 sync; /* Synch method, one of rio_transfer_sync enum */ __u16 dir; /* Transfer direction, one of rio_transfer_dir enum */ __u32 pad0; }; struct rio_async_tx_wait { __u32 token; /* DMA transaction ID token */ __u32 timeout; /* Wait timeout in msec, if 0 use default TO */ }; #define RIO_MAX_DEVNAME_SZ 20 struct rio_rdev_info { __u16 destid; __u8 hopcount; __u8 pad0; __u32 comptag; char name[RIO_MAX_DEVNAME_SZ + 1]; }; /* Driver IOCTL codes */ #define RIO_MPORT_DRV_MAGIC 'm' #define RIO_MPORT_MAINT_HDID_SET \ _IOW(RIO_MPORT_DRV_MAGIC, 1, __u16) #define RIO_MPORT_MAINT_COMPTAG_SET \ _IOW(RIO_MPORT_DRV_MAGIC, 2, __u32) #define RIO_MPORT_MAINT_PORT_IDX_GET \ _IOR(RIO_MPORT_DRV_MAGIC, 3, __u32) #define RIO_MPORT_GET_PROPERTIES \ _IOR(RIO_MPORT_DRV_MAGIC, 4, struct rio_mport_properties) #define RIO_MPORT_MAINT_READ_LOCAL \ _IOR(RIO_MPORT_DRV_MAGIC, 5, struct rio_mport_maint_io) #define RIO_MPORT_MAINT_WRITE_LOCAL \ _IOW(RIO_MPORT_DRV_MAGIC, 6, struct rio_mport_maint_io) #define RIO_MPORT_MAINT_READ_REMOTE \ _IOR(RIO_MPORT_DRV_MAGIC, 7, struct rio_mport_maint_io) #define RIO_MPORT_MAINT_WRITE_REMOTE \ _IOW(RIO_MPORT_DRV_MAGIC, 8, struct rio_mport_maint_io) #define RIO_ENABLE_DOORBELL_RANGE \ _IOW(RIO_MPORT_DRV_MAGIC, 9, struct rio_doorbell_filter) #define RIO_DISABLE_DOORBELL_RANGE \ _IOW(RIO_MPORT_DRV_MAGIC, 10, struct rio_doorbell_filter) #define RIO_ENABLE_PORTWRITE_RANGE \ _IOW(RIO_MPORT_DRV_MAGIC, 11, struct rio_pw_filter) #define RIO_DISABLE_PORTWRITE_RANGE \ _IOW(RIO_MPORT_DRV_MAGIC, 12, struct rio_pw_filter) #define RIO_SET_EVENT_MASK \ _IOW(RIO_MPORT_DRV_MAGIC, 13, __u32) #define RIO_GET_EVENT_MASK \ _IOR(RIO_MPORT_DRV_MAGIC, 14, __u32) #define RIO_MAP_OUTBOUND \ _IOWR(RIO_MPORT_DRV_MAGIC, 15, struct rio_mmap) #define RIO_UNMAP_OUTBOUND \ _IOW(RIO_MPORT_DRV_MAGIC, 16, struct rio_mmap) #define RIO_MAP_INBOUND \ _IOWR(RIO_MPORT_DRV_MAGIC, 17, struct rio_mmap) #define RIO_UNMAP_INBOUND \ _IOW(RIO_MPORT_DRV_MAGIC, 18, __u64) #define RIO_ALLOC_DMA \ _IOWR(RIO_MPORT_DRV_MAGIC, 19, struct rio_dma_mem) #define RIO_FREE_DMA \ _IOW(RIO_MPORT_DRV_MAGIC, 20, __u64) #define RIO_TRANSFER \ _IOWR(RIO_MPORT_DRV_MAGIC, 21, struct rio_transaction) #define RIO_WAIT_FOR_ASYNC \ _IOW(RIO_MPORT_DRV_MAGIC, 22, struct rio_async_tx_wait) #define RIO_DEV_ADD \ _IOW(RIO_MPORT_DRV_MAGIC, 23, struct rio_rdev_info) #define RIO_DEV_DEL \ _IOW(RIO_MPORT_DRV_MAGIC, 24, struct rio_rdev_info) #endif /* _RIO_MPORT_CDEV_H_ */ linux/cgroupstats.h000064400000004253151027430560010441 0ustar00/* SPDX-License-Identifier: LGPL-2.1 WITH Linux-syscall-note */ /* cgroupstats.h - exporting per-cgroup statistics * * Copyright IBM Corporation, 2007 * Author Balbir Singh * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2.1 of the GNU Lesser General Public License * as published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef _LINUX_CGROUPSTATS_H #define _LINUX_CGROUPSTATS_H #include #include /* * Data shared between user space and kernel space on a per cgroup * basis. This data is shared using taskstats. * * Most of these states are derived by looking at the task->state value * For the nr_io_wait state, a flag in the delay accounting structure * indicates that the task is waiting on IO * * Each member is aligned to a 8 byte boundary. */ struct cgroupstats { __u64 nr_sleeping; /* Number of tasks sleeping */ __u64 nr_running; /* Number of tasks running */ __u64 nr_stopped; /* Number of tasks in stopped state */ __u64 nr_uninterruptible; /* Number of tasks in uninterruptible */ /* state */ __u64 nr_io_wait; /* Number of tasks waiting on IO */ }; /* * Commands sent from userspace * Not versioned. New commands should only be inserted at the enum's end * prior to __CGROUPSTATS_CMD_MAX */ enum { CGROUPSTATS_CMD_UNSPEC = __TASKSTATS_CMD_MAX, /* Reserved */ CGROUPSTATS_CMD_GET, /* user->kernel request/get-response */ CGROUPSTATS_CMD_NEW, /* kernel->user event */ __CGROUPSTATS_CMD_MAX, }; #define CGROUPSTATS_CMD_MAX (__CGROUPSTATS_CMD_MAX - 1) enum { CGROUPSTATS_TYPE_UNSPEC = 0, /* Reserved */ CGROUPSTATS_TYPE_CGROUP_STATS, /* contains name + stats */ __CGROUPSTATS_TYPE_MAX, }; #define CGROUPSTATS_TYPE_MAX (__CGROUPSTATS_TYPE_MAX - 1) enum { CGROUPSTATS_CMD_ATTR_UNSPEC = 0, CGROUPSTATS_CMD_ATTR_FD, __CGROUPSTATS_CMD_ATTR_MAX, }; #define CGROUPSTATS_CMD_ATTR_MAX (__CGROUPSTATS_CMD_ATTR_MAX - 1) #endif /* _LINUX_CGROUPSTATS_H */ linux/kcmp.h000064400000001012151027430560007003 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_KCMP_H #define _LINUX_KCMP_H #include /* Comparison type */ enum kcmp_type { KCMP_FILE, KCMP_VM, KCMP_FILES, KCMP_FS, KCMP_SIGHAND, KCMP_IO, KCMP_SYSVSEM, KCMP_EPOLL_TFD, KCMP_TYPES, }; /* Slot for KCMP_EPOLL_TFD */ struct kcmp_epoll_slot { __u32 efd; /* epoll file descriptor */ __u32 tfd; /* target file number */ __u32 toff; /* target offset within same numbered sequence */ }; #endif /* _LINUX_KCMP_H */ linux/poll.h000064400000000026151027430560007023 0ustar00#include linux/dm-log-userspace.h000064400000035527151027430560011242 0ustar00/* SPDX-License-Identifier: LGPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (C) 2006-2009 Red Hat, Inc. * * This file is released under the LGPL. */ #ifndef __DM_LOG_USERSPACE_H__ #define __DM_LOG_USERSPACE_H__ #include #include /* For DM_UUID_LEN */ /* * The device-mapper userspace log module consists of a kernel component and * a user-space component. The kernel component implements the API defined * in dm-dirty-log.h. Its purpose is simply to pass the parameters and * return values of those API functions between kernel and user-space. * * Below are defined the 'request_types' - DM_ULOG_CTR, DM_ULOG_DTR, etc. * These request types represent the different functions in the device-mapper * dirty log API. Each of these is described in more detail below. * * The user-space program must listen for requests from the kernel (representing * the various API functions) and process them. * * User-space begins by setting up the communication link (error checking * removed for clarity): * fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); * addr.nl_family = AF_NETLINK; * addr.nl_groups = CN_IDX_DM; * addr.nl_pid = 0; * r = bind(fd, (struct sockaddr *) &addr, sizeof(addr)); * opt = addr.nl_groups; * setsockopt(fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &opt, sizeof(opt)); * * User-space will then wait to receive requests form the kernel, which it * will process as described below. The requests are received in the form, * ((struct dm_ulog_request) + (additional data)). Depending on the request * type, there may or may not be 'additional data'. In the descriptions below, * you will see 'Payload-to-userspace' and 'Payload-to-kernel'. The * 'Payload-to-userspace' is what the kernel sends in 'additional data' as * necessary parameters to complete the request. The 'Payload-to-kernel' is * the 'additional data' returned to the kernel that contains the necessary * results of the request. The 'data_size' field in the dm_ulog_request * structure denotes the availability and amount of payload data. */ /* * DM_ULOG_CTR corresponds to (found in dm-dirty-log.h): * int (*ctr)(struct dm_dirty_log *log, struct dm_target *ti, * unsigned argc, char **argv); * * Payload-to-userspace: * A single string containing all the argv arguments separated by ' 's * Payload-to-kernel: * A NUL-terminated string that is the name of the device that is used * as the backing store for the log data. 'dm_get_device' will be called * on this device. ('dm_put_device' will be called on this device * automatically after calling DM_ULOG_DTR.) If there is no device needed * for log data, 'data_size' in the dm_ulog_request struct should be 0. * * The UUID contained in the dm_ulog_request structure is the reference that * will be used by all request types to a specific log. The constructor must * record this association with the instance created. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field, filling the * data field with the log device if necessary, and setting 'data_size' * appropriately. */ #define DM_ULOG_CTR 1 /* * DM_ULOG_DTR corresponds to (found in dm-dirty-log.h): * void (*dtr)(struct dm_dirty_log *log); * * Payload-to-userspace: * A single string containing all the argv arguments separated by ' 's * Payload-to-kernel: * None. ('data_size' in the dm_ulog_request struct should be 0.) * * The UUID contained in the dm_ulog_request structure is all that is * necessary to identify the log instance being destroyed. There is no * payload data. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and clearing * 'data_size' appropriately. */ #define DM_ULOG_DTR 2 /* * DM_ULOG_PRESUSPEND corresponds to (found in dm-dirty-log.h): * int (*presuspend)(struct dm_dirty_log *log); * * Payload-to-userspace: * None. * Payload-to-kernel: * None. * * The UUID contained in the dm_ulog_request structure is all that is * necessary to identify the log instance being presuspended. There is no * payload data. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_PRESUSPEND 3 /* * DM_ULOG_POSTSUSPEND corresponds to (found in dm-dirty-log.h): * int (*postsuspend)(struct dm_dirty_log *log); * * Payload-to-userspace: * None. * Payload-to-kernel: * None. * * The UUID contained in the dm_ulog_request structure is all that is * necessary to identify the log instance being postsuspended. There is no * payload data. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_POSTSUSPEND 4 /* * DM_ULOG_RESUME corresponds to (found in dm-dirty-log.h): * int (*resume)(struct dm_dirty_log *log); * * Payload-to-userspace: * None. * Payload-to-kernel: * None. * * The UUID contained in the dm_ulog_request structure is all that is * necessary to identify the log instance being resumed. There is no * payload data. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_RESUME 5 /* * DM_ULOG_GET_REGION_SIZE corresponds to (found in dm-dirty-log.h): * __u32 (*get_region_size)(struct dm_dirty_log *log); * * Payload-to-userspace: * None. * Payload-to-kernel: * __u64 - contains the region size * * The region size is something that was determined at constructor time. * It is returned in the payload area and 'data_size' is set to * reflect this. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field appropriately. */ #define DM_ULOG_GET_REGION_SIZE 6 /* * DM_ULOG_IS_CLEAN corresponds to (found in dm-dirty-log.h): * int (*is_clean)(struct dm_dirty_log *log, region_t region); * * Payload-to-userspace: * __u64 - the region to get clean status on * Payload-to-kernel: * __s64 - 1 if clean, 0 otherwise * * Payload is sizeof(__u64) and contains the region for which the clean * status is being made. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - filling the payload with 0 (not clean) or * 1 (clean), setting 'data_size' and 'error' appropriately. */ #define DM_ULOG_IS_CLEAN 7 /* * DM_ULOG_IN_SYNC corresponds to (found in dm-dirty-log.h): * int (*in_sync)(struct dm_dirty_log *log, region_t region, * int can_block); * * Payload-to-userspace: * __u64 - the region to get sync status on * Payload-to-kernel: * __s64 - 1 if in-sync, 0 otherwise * * Exactly the same as 'is_clean' above, except this time asking "has the * region been recovered?" vs. "is the region not being modified?" */ #define DM_ULOG_IN_SYNC 8 /* * DM_ULOG_FLUSH corresponds to (found in dm-dirty-log.h): * int (*flush)(struct dm_dirty_log *log); * * Payload-to-userspace: * If the 'integrated_flush' directive is present in the constructor * table, the payload is as same as DM_ULOG_MARK_REGION: * __u64 [] - region(s) to mark * else * None * Payload-to-kernel: * None. * * If the 'integrated_flush' option was used during the creation of the * log, mark region requests are carried as payload in the flush request. * Piggybacking the mark requests in this way allows for fewer communications * between kernel and userspace. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and clearing * 'data_size' appropriately. */ #define DM_ULOG_FLUSH 9 /* * DM_ULOG_MARK_REGION corresponds to (found in dm-dirty-log.h): * void (*mark_region)(struct dm_dirty_log *log, region_t region); * * Payload-to-userspace: * __u64 [] - region(s) to mark * Payload-to-kernel: * None. * * Incoming payload contains the one or more regions to mark dirty. * The number of regions contained in the payload can be determined from * 'data_size/sizeof(__u64)'. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and clearing * 'data_size' appropriately. */ #define DM_ULOG_MARK_REGION 10 /* * DM_ULOG_CLEAR_REGION corresponds to (found in dm-dirty-log.h): * void (*clear_region)(struct dm_dirty_log *log, region_t region); * * Payload-to-userspace: * __u64 [] - region(s) to clear * Payload-to-kernel: * None. * * Incoming payload contains the one or more regions to mark clean. * The number of regions contained in the payload can be determined from * 'data_size/sizeof(__u64)'. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and clearing * 'data_size' appropriately. */ #define DM_ULOG_CLEAR_REGION 11 /* * DM_ULOG_GET_RESYNC_WORK corresponds to (found in dm-dirty-log.h): * int (*get_resync_work)(struct dm_dirty_log *log, region_t *region); * * Payload-to-userspace: * None. * Payload-to-kernel: * { * __s64 i; -- 1 if recovery necessary, 0 otherwise * __u64 r; -- The region to recover if i=1 * } * 'data_size' should be set appropriately. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field appropriately. */ #define DM_ULOG_GET_RESYNC_WORK 12 /* * DM_ULOG_SET_REGION_SYNC corresponds to (found in dm-dirty-log.h): * void (*set_region_sync)(struct dm_dirty_log *log, * region_t region, int in_sync); * * Payload-to-userspace: * { * __u64 - region to set sync state on * __s64 - 0 if not-in-sync, 1 if in-sync * } * Payload-to-kernel: * None. * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and clearing * 'data_size' appropriately. */ #define DM_ULOG_SET_REGION_SYNC 13 /* * DM_ULOG_GET_SYNC_COUNT corresponds to (found in dm-dirty-log.h): * region_t (*get_sync_count)(struct dm_dirty_log *log); * * Payload-to-userspace: * None. * Payload-to-kernel: * __u64 - the number of in-sync regions * * No incoming payload. Kernel-bound payload contains the number of * regions that are in-sync (in a size_t). * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_GET_SYNC_COUNT 14 /* * DM_ULOG_STATUS_INFO corresponds to (found in dm-dirty-log.h): * int (*status)(struct dm_dirty_log *log, STATUSTYPE_INFO, * char *result, unsigned maxlen); * * Payload-to-userspace: * None. * Payload-to-kernel: * Character string containing STATUSTYPE_INFO * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_STATUS_INFO 15 /* * DM_ULOG_STATUS_TABLE corresponds to (found in dm-dirty-log.h): * int (*status)(struct dm_dirty_log *log, STATUSTYPE_TABLE, * char *result, unsigned maxlen); * * Payload-to-userspace: * None. * Payload-to-kernel: * Character string containing STATUSTYPE_TABLE * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_STATUS_TABLE 16 /* * DM_ULOG_IS_REMOTE_RECOVERING corresponds to (found in dm-dirty-log.h): * int (*is_remote_recovering)(struct dm_dirty_log *log, region_t region); * * Payload-to-userspace: * __u64 - region to determine recovery status on * Payload-to-kernel: * { * __s64 is_recovering; -- 0 if no, 1 if yes * __u64 in_sync_hint; -- lowest region still needing resync * } * * When the request has been processed, user-space must return the * dm_ulog_request to the kernel - setting the 'error' field and * 'data_size' appropriately. */ #define DM_ULOG_IS_REMOTE_RECOVERING 17 /* * (DM_ULOG_REQUEST_MASK & request_type) to get the request type * * Payload-to-userspace: * A single string containing all the argv arguments separated by ' 's * Payload-to-kernel: * None. ('data_size' in the dm_ulog_request struct should be 0.) * * We are reserving 8 bits of the 32-bit 'request_type' field for the * various request types above. The remaining 24-bits are currently * set to zero and are reserved for future use and compatibility concerns. * * User-space should always use DM_ULOG_REQUEST_TYPE to acquire the * request type from the 'request_type' field to maintain forward compatibility. */ #define DM_ULOG_REQUEST_MASK 0xFF #define DM_ULOG_REQUEST_TYPE(request_type) \ (DM_ULOG_REQUEST_MASK & (request_type)) /* * DM_ULOG_REQUEST_VERSION is incremented when there is a * change to the way information is passed between kernel * and userspace. This could be a structure change of * dm_ulog_request or a change in the way requests are * issued/handled. Changes are outlined here: * version 1: Initial implementation * version 2: DM_ULOG_CTR allowed to return a string containing a * device name that is to be registered with DM via * 'dm_get_device'. * version 3: DM_ULOG_FLUSH is capable of carrying payload for marking * regions. This "integrated flush" reduces the number of * requests between the kernel and userspace by effectively * merging 'mark' and 'flush' requests. A constructor table * argument ('integrated_flush') is required to turn this * feature on, so it is backwards compatible with older * userspace versions. */ #define DM_ULOG_REQUEST_VERSION 3 struct dm_ulog_request { /* * The local unique identifier (luid) and the universally unique * identifier (uuid) are used to tie a request to a specific * mirror log. A single machine log could probably make due with * just the 'luid', but a cluster-aware log must use the 'uuid' and * the 'luid'. The uuid is what is required for node to node * communication concerning a particular log, but the 'luid' helps * differentiate between logs that are being swapped and have the * same 'uuid'. (Think "live" and "inactive" device-mapper tables.) */ __u64 luid; char uuid[DM_UUID_LEN]; char padding[3]; /* Padding because DM_UUID_LEN = 129 */ __u32 version; /* See DM_ULOG_REQUEST_VERSION */ __s32 error; /* Used to report back processing errors */ __u32 seq; /* Sequence number for request */ __u32 request_type; /* DM_ULOG_* defined above */ __u32 data_size; /* How much data (not including this struct) */ char data[0]; }; #endif /* __DM_LOG_USERSPACE_H__ */ linux/nfsacl.h000064400000001316151027430560007326 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * File: linux/nfsacl.h * * (C) 2003 Andreas Gruenbacher */ #ifndef __LINUX_NFSACL_H #define __LINUX_NFSACL_H #define NFS_ACL_PROGRAM 100227 #define ACLPROC2_NULL 0 #define ACLPROC2_GETACL 1 #define ACLPROC2_SETACL 2 #define ACLPROC2_GETATTR 3 #define ACLPROC2_ACCESS 4 #define ACLPROC3_NULL 0 #define ACLPROC3_GETACL 1 #define ACLPROC3_SETACL 2 /* Flags for the getacl/setacl mode */ #define NFS_ACL 0x0001 #define NFS_ACLCNT 0x0002 #define NFS_DFACL 0x0004 #define NFS_DFACLCNT 0x0008 #define NFS_ACL_MASK 0x000f /* Flag for Default ACL entries */ #define NFS_ACL_DEFAULT 0x1000 #endif /* __LINUX_NFSACL_H */ linux/xfrm.h000064400000027332151027430560007042 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_XFRM_H #define _LINUX_XFRM_H #include #include /* All of the structures in this file may not change size as they are * passed into the kernel from userspace via netlink sockets. */ /* Structure to encapsulate addresses. I do not want to use * "standard" structure. My apologies. */ typedef union { __be32 a4; __be32 a6[4]; struct in6_addr in6; } xfrm_address_t; /* Ident of a specific xfrm_state. It is used on input to lookup * the state by (spi,daddr,ah/esp) or to store information about * spi, protocol and tunnel address on output. */ struct xfrm_id { xfrm_address_t daddr; __be32 spi; __u8 proto; }; struct xfrm_sec_ctx { __u8 ctx_doi; __u8 ctx_alg; __u16 ctx_len; __u32 ctx_sid; char ctx_str[0]; }; /* Security Context Domains of Interpretation */ #define XFRM_SC_DOI_RESERVED 0 #define XFRM_SC_DOI_LSM 1 /* Security Context Algorithms */ #define XFRM_SC_ALG_RESERVED 0 #define XFRM_SC_ALG_SELINUX 1 /* Selector, used as selector both on policy rules (SPD) and SAs. */ struct xfrm_selector { xfrm_address_t daddr; xfrm_address_t saddr; __be16 dport; __be16 dport_mask; __be16 sport; __be16 sport_mask; __u16 family; __u8 prefixlen_d; __u8 prefixlen_s; __u8 proto; int ifindex; __kernel_uid32_t user; }; #define XFRM_INF (~(__u64)0) struct xfrm_lifetime_cfg { __u64 soft_byte_limit; __u64 hard_byte_limit; __u64 soft_packet_limit; __u64 hard_packet_limit; __u64 soft_add_expires_seconds; __u64 hard_add_expires_seconds; __u64 soft_use_expires_seconds; __u64 hard_use_expires_seconds; }; struct xfrm_lifetime_cur { __u64 bytes; __u64 packets; __u64 add_time; __u64 use_time; }; struct xfrm_replay_state { __u32 oseq; __u32 seq; __u32 bitmap; }; #define XFRMA_REPLAY_ESN_MAX 4096 struct xfrm_replay_state_esn { unsigned int bmp_len; __u32 oseq; __u32 seq; __u32 oseq_hi; __u32 seq_hi; __u32 replay_window; __u32 bmp[0]; }; struct xfrm_algo { char alg_name[64]; unsigned int alg_key_len; /* in bits */ char alg_key[0]; }; struct xfrm_algo_auth { char alg_name[64]; unsigned int alg_key_len; /* in bits */ unsigned int alg_trunc_len; /* in bits */ char alg_key[0]; }; struct xfrm_algo_aead { char alg_name[64]; unsigned int alg_key_len; /* in bits */ unsigned int alg_icv_len; /* in bits */ char alg_key[0]; }; struct xfrm_stats { __u32 replay_window; __u32 replay; __u32 integrity_failed; }; enum { XFRM_POLICY_TYPE_MAIN = 0, XFRM_POLICY_TYPE_SUB = 1, XFRM_POLICY_TYPE_MAX = 2, XFRM_POLICY_TYPE_ANY = 255 }; enum { XFRM_POLICY_IN = 0, XFRM_POLICY_OUT = 1, XFRM_POLICY_FWD = 2, XFRM_POLICY_MASK = 3, XFRM_POLICY_MAX = 3 }; enum { XFRM_SHARE_ANY, /* No limitations */ XFRM_SHARE_SESSION, /* For this session only */ XFRM_SHARE_USER, /* For this user only */ XFRM_SHARE_UNIQUE /* Use once */ }; #define XFRM_MODE_TRANSPORT 0 #define XFRM_MODE_TUNNEL 1 #define XFRM_MODE_ROUTEOPTIMIZATION 2 #define XFRM_MODE_IN_TRIGGER 3 #define XFRM_MODE_BEET 4 #define XFRM_MODE_MAX 5 /* Netlink configuration messages. */ enum { XFRM_MSG_BASE = 0x10, XFRM_MSG_NEWSA = 0x10, #define XFRM_MSG_NEWSA XFRM_MSG_NEWSA XFRM_MSG_DELSA, #define XFRM_MSG_DELSA XFRM_MSG_DELSA XFRM_MSG_GETSA, #define XFRM_MSG_GETSA XFRM_MSG_GETSA XFRM_MSG_NEWPOLICY, #define XFRM_MSG_NEWPOLICY XFRM_MSG_NEWPOLICY XFRM_MSG_DELPOLICY, #define XFRM_MSG_DELPOLICY XFRM_MSG_DELPOLICY XFRM_MSG_GETPOLICY, #define XFRM_MSG_GETPOLICY XFRM_MSG_GETPOLICY XFRM_MSG_ALLOCSPI, #define XFRM_MSG_ALLOCSPI XFRM_MSG_ALLOCSPI XFRM_MSG_ACQUIRE, #define XFRM_MSG_ACQUIRE XFRM_MSG_ACQUIRE XFRM_MSG_EXPIRE, #define XFRM_MSG_EXPIRE XFRM_MSG_EXPIRE XFRM_MSG_UPDPOLICY, #define XFRM_MSG_UPDPOLICY XFRM_MSG_UPDPOLICY XFRM_MSG_UPDSA, #define XFRM_MSG_UPDSA XFRM_MSG_UPDSA XFRM_MSG_POLEXPIRE, #define XFRM_MSG_POLEXPIRE XFRM_MSG_POLEXPIRE XFRM_MSG_FLUSHSA, #define XFRM_MSG_FLUSHSA XFRM_MSG_FLUSHSA XFRM_MSG_FLUSHPOLICY, #define XFRM_MSG_FLUSHPOLICY XFRM_MSG_FLUSHPOLICY XFRM_MSG_NEWAE, #define XFRM_MSG_NEWAE XFRM_MSG_NEWAE XFRM_MSG_GETAE, #define XFRM_MSG_GETAE XFRM_MSG_GETAE XFRM_MSG_REPORT, #define XFRM_MSG_REPORT XFRM_MSG_REPORT XFRM_MSG_MIGRATE, #define XFRM_MSG_MIGRATE XFRM_MSG_MIGRATE XFRM_MSG_NEWSADINFO, #define XFRM_MSG_NEWSADINFO XFRM_MSG_NEWSADINFO XFRM_MSG_GETSADINFO, #define XFRM_MSG_GETSADINFO XFRM_MSG_GETSADINFO XFRM_MSG_NEWSPDINFO, #define XFRM_MSG_NEWSPDINFO XFRM_MSG_NEWSPDINFO XFRM_MSG_GETSPDINFO, #define XFRM_MSG_GETSPDINFO XFRM_MSG_GETSPDINFO XFRM_MSG_MAPPING, #define XFRM_MSG_MAPPING XFRM_MSG_MAPPING __XFRM_MSG_MAX }; #define XFRM_MSG_MAX (__XFRM_MSG_MAX - 1) #define XFRM_NR_MSGTYPES (XFRM_MSG_MAX + 1 - XFRM_MSG_BASE) /* * Generic LSM security context for comunicating to user space * NOTE: Same format as sadb_x_sec_ctx */ struct xfrm_user_sec_ctx { __u16 len; __u16 exttype; __u8 ctx_alg; /* LSMs: e.g., selinux == 1 */ __u8 ctx_doi; __u16 ctx_len; }; struct xfrm_user_tmpl { struct xfrm_id id; __u16 family; xfrm_address_t saddr; __u32 reqid; __u8 mode; __u8 share; __u8 optional; __u32 aalgos; __u32 ealgos; __u32 calgos; }; struct xfrm_encap_tmpl { __u16 encap_type; __be16 encap_sport; __be16 encap_dport; xfrm_address_t encap_oa; }; /* AEVENT flags */ enum xfrm_ae_ftype_t { XFRM_AE_UNSPEC, XFRM_AE_RTHR=1, /* replay threshold*/ XFRM_AE_RVAL=2, /* replay value */ XFRM_AE_LVAL=4, /* lifetime value */ XFRM_AE_ETHR=8, /* expiry timer threshold */ XFRM_AE_CR=16, /* Event cause is replay update */ XFRM_AE_CE=32, /* Event cause is timer expiry */ XFRM_AE_CU=64, /* Event cause is policy update */ __XFRM_AE_MAX #define XFRM_AE_MAX (__XFRM_AE_MAX - 1) }; struct xfrm_userpolicy_type { __u8 type; __u16 reserved1; __u8 reserved2; }; /* Netlink message attributes. */ enum xfrm_attr_type_t { XFRMA_UNSPEC, XFRMA_ALG_AUTH, /* struct xfrm_algo */ XFRMA_ALG_CRYPT, /* struct xfrm_algo */ XFRMA_ALG_COMP, /* struct xfrm_algo */ XFRMA_ENCAP, /* struct xfrm_algo + struct xfrm_encap_tmpl */ XFRMA_TMPL, /* 1 or more struct xfrm_user_tmpl */ XFRMA_SA, /* struct xfrm_usersa_info */ XFRMA_POLICY, /*struct xfrm_userpolicy_info */ XFRMA_SEC_CTX, /* struct xfrm_sec_ctx */ XFRMA_LTIME_VAL, XFRMA_REPLAY_VAL, XFRMA_REPLAY_THRESH, XFRMA_ETIMER_THRESH, XFRMA_SRCADDR, /* xfrm_address_t */ XFRMA_COADDR, /* xfrm_address_t */ XFRMA_LASTUSED, /* unsigned long */ XFRMA_POLICY_TYPE, /* struct xfrm_userpolicy_type */ XFRMA_MIGRATE, XFRMA_ALG_AEAD, /* struct xfrm_algo_aead */ XFRMA_KMADDRESS, /* struct xfrm_user_kmaddress */ XFRMA_ALG_AUTH_TRUNC, /* struct xfrm_algo_auth */ XFRMA_MARK, /* struct xfrm_mark */ XFRMA_TFCPAD, /* __u32 */ XFRMA_REPLAY_ESN_VAL, /* struct xfrm_replay_state_esn */ XFRMA_SA_EXTRA_FLAGS, /* __u32 */ XFRMA_PROTO, /* __u8 */ XFRMA_ADDRESS_FILTER, /* struct xfrm_address_filter */ XFRMA_PAD, XFRMA_OFFLOAD_DEV, /* struct xfrm_user_offload */ XFRMA_SET_MARK, /* __u32 */ XFRMA_SET_MARK_MASK, /* __u32 */ XFRMA_IF_ID, /* __u32 */ __XFRMA_MAX #define XFRMA_OUTPUT_MARK XFRMA_SET_MARK /* Compatibility */ #define XFRMA_MAX (__XFRMA_MAX - 1) }; struct xfrm_mark { __u32 v; /* value */ __u32 m; /* mask */ }; enum xfrm_sadattr_type_t { XFRMA_SAD_UNSPEC, XFRMA_SAD_CNT, XFRMA_SAD_HINFO, __XFRMA_SAD_MAX #define XFRMA_SAD_MAX (__XFRMA_SAD_MAX - 1) }; struct xfrmu_sadhinfo { __u32 sadhcnt; /* current hash bkts */ __u32 sadhmcnt; /* max allowed hash bkts */ }; enum xfrm_spdattr_type_t { XFRMA_SPD_UNSPEC, XFRMA_SPD_INFO, XFRMA_SPD_HINFO, XFRMA_SPD_IPV4_HTHRESH, XFRMA_SPD_IPV6_HTHRESH, __XFRMA_SPD_MAX #define XFRMA_SPD_MAX (__XFRMA_SPD_MAX - 1) }; struct xfrmu_spdinfo { __u32 incnt; __u32 outcnt; __u32 fwdcnt; __u32 inscnt; __u32 outscnt; __u32 fwdscnt; }; struct xfrmu_spdhinfo { __u32 spdhcnt; __u32 spdhmcnt; }; struct xfrmu_spdhthresh { __u8 lbits; __u8 rbits; }; struct xfrm_usersa_info { struct xfrm_selector sel; struct xfrm_id id; xfrm_address_t saddr; struct xfrm_lifetime_cfg lft; struct xfrm_lifetime_cur curlft; struct xfrm_stats stats; __u32 seq; __u32 reqid; __u16 family; __u8 mode; /* XFRM_MODE_xxx */ __u8 replay_window; __u8 flags; #define XFRM_STATE_NOECN 1 #define XFRM_STATE_DECAP_DSCP 2 #define XFRM_STATE_NOPMTUDISC 4 #define XFRM_STATE_WILDRECV 8 #define XFRM_STATE_ICMP 16 #define XFRM_STATE_AF_UNSPEC 32 #define XFRM_STATE_ALIGN4 64 #define XFRM_STATE_ESN 128 }; #define XFRM_SA_XFLAG_DONT_ENCAP_DSCP 1 struct xfrm_usersa_id { xfrm_address_t daddr; __be32 spi; __u16 family; __u8 proto; }; struct xfrm_aevent_id { struct xfrm_usersa_id sa_id; xfrm_address_t saddr; __u32 flags; __u32 reqid; }; struct xfrm_userspi_info { struct xfrm_usersa_info info; __u32 min; __u32 max; }; struct xfrm_userpolicy_info { struct xfrm_selector sel; struct xfrm_lifetime_cfg lft; struct xfrm_lifetime_cur curlft; __u32 priority; __u32 index; __u8 dir; __u8 action; #define XFRM_POLICY_ALLOW 0 #define XFRM_POLICY_BLOCK 1 __u8 flags; #define XFRM_POLICY_LOCALOK 1 /* Allow user to override global policy */ /* Automatically expand selector to include matching ICMP payloads. */ #define XFRM_POLICY_ICMP 2 __u8 share; }; struct xfrm_userpolicy_id { struct xfrm_selector sel; __u32 index; __u8 dir; }; struct xfrm_user_acquire { struct xfrm_id id; xfrm_address_t saddr; struct xfrm_selector sel; struct xfrm_userpolicy_info policy; __u32 aalgos; __u32 ealgos; __u32 calgos; __u32 seq; }; struct xfrm_user_expire { struct xfrm_usersa_info state; __u8 hard; }; struct xfrm_user_polexpire { struct xfrm_userpolicy_info pol; __u8 hard; }; struct xfrm_usersa_flush { __u8 proto; }; struct xfrm_user_report { __u8 proto; struct xfrm_selector sel; }; /* Used by MIGRATE to pass addresses IKE should use to perform * SA negotiation with the peer */ struct xfrm_user_kmaddress { xfrm_address_t local; xfrm_address_t remote; __u32 reserved; __u16 family; }; struct xfrm_user_migrate { xfrm_address_t old_daddr; xfrm_address_t old_saddr; xfrm_address_t new_daddr; xfrm_address_t new_saddr; __u8 proto; __u8 mode; __u16 reserved; __u32 reqid; __u16 old_family; __u16 new_family; }; struct xfrm_user_mapping { struct xfrm_usersa_id id; __u32 reqid; xfrm_address_t old_saddr; xfrm_address_t new_saddr; __be16 old_sport; __be16 new_sport; }; struct xfrm_address_filter { xfrm_address_t saddr; xfrm_address_t daddr; __u16 family; __u8 splen; __u8 dplen; }; struct xfrm_user_offload { int ifindex; __u8 flags; }; /* This flag was exposed without any kernel code that supporting it. * Unfortunately, strongswan has the code that uses sets this flag, * which makes impossible to reuse this bit. * * So leave it here to make sure that it won't be reused by mistake. */ #define XFRM_OFFLOAD_IPV6 1 #define XFRM_OFFLOAD_INBOUND 2 /* backwards compatibility for userspace */ #define XFRMGRP_ACQUIRE 1 #define XFRMGRP_EXPIRE 2 #define XFRMGRP_SA 4 #define XFRMGRP_POLICY 8 #define XFRMGRP_REPORT 0x20 enum xfrm_nlgroups { XFRMNLGRP_NONE, #define XFRMNLGRP_NONE XFRMNLGRP_NONE XFRMNLGRP_ACQUIRE, #define XFRMNLGRP_ACQUIRE XFRMNLGRP_ACQUIRE XFRMNLGRP_EXPIRE, #define XFRMNLGRP_EXPIRE XFRMNLGRP_EXPIRE XFRMNLGRP_SA, #define XFRMNLGRP_SA XFRMNLGRP_SA XFRMNLGRP_POLICY, #define XFRMNLGRP_POLICY XFRMNLGRP_POLICY XFRMNLGRP_AEVENTS, #define XFRMNLGRP_AEVENTS XFRMNLGRP_AEVENTS XFRMNLGRP_REPORT, #define XFRMNLGRP_REPORT XFRMNLGRP_REPORT XFRMNLGRP_MIGRATE, #define XFRMNLGRP_MIGRATE XFRMNLGRP_MIGRATE XFRMNLGRP_MAPPING, #define XFRMNLGRP_MAPPING XFRMNLGRP_MAPPING __XFRMNLGRP_MAX }; #define XFRMNLGRP_MAX (__XFRMNLGRP_MAX - 1) #endif /* _LINUX_XFRM_H */ linux/btrfs_tree.h000064400000061305151027430560010223 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _BTRFS_CTREE_H_ #define _BTRFS_CTREE_H_ #include #include /* * This header contains the structure definitions and constants used * by file system objects that can be retrieved using * the BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that * is needed to describe a leaf node's key or item contents. */ /* holds pointers to all of the tree roots */ #define BTRFS_ROOT_TREE_OBJECTID 1ULL /* stores information about which extents are in use, and reference counts */ #define BTRFS_EXTENT_TREE_OBJECTID 2ULL /* * chunk tree stores translations from logical -> physical block numbering * the super block points to the chunk tree */ #define BTRFS_CHUNK_TREE_OBJECTID 3ULL /* * stores information about which areas of a given device are in use. * one per device. The tree of tree roots points to the device tree */ #define BTRFS_DEV_TREE_OBJECTID 4ULL /* one per subvolume, storing files and directories */ #define BTRFS_FS_TREE_OBJECTID 5ULL /* directory objectid inside the root tree */ #define BTRFS_ROOT_TREE_DIR_OBJECTID 6ULL /* holds checksums of all the data extents */ #define BTRFS_CSUM_TREE_OBJECTID 7ULL /* holds quota configuration and tracking */ #define BTRFS_QUOTA_TREE_OBJECTID 8ULL /* for storing items that use the BTRFS_UUID_KEY* types */ #define BTRFS_UUID_TREE_OBJECTID 9ULL /* tracks free space in block groups. */ #define BTRFS_FREE_SPACE_TREE_OBJECTID 10ULL /* device stats in the device tree */ #define BTRFS_DEV_STATS_OBJECTID 0ULL /* for storing balance parameters in the root tree */ #define BTRFS_BALANCE_OBJECTID -4ULL /* orhpan objectid for tracking unlinked/truncated files */ #define BTRFS_ORPHAN_OBJECTID -5ULL /* does write ahead logging to speed up fsyncs */ #define BTRFS_TREE_LOG_OBJECTID -6ULL #define BTRFS_TREE_LOG_FIXUP_OBJECTID -7ULL /* for space balancing */ #define BTRFS_TREE_RELOC_OBJECTID -8ULL #define BTRFS_DATA_RELOC_TREE_OBJECTID -9ULL /* * extent checksums all have this objectid * this allows them to share the logging tree * for fsyncs */ #define BTRFS_EXTENT_CSUM_OBJECTID -10ULL /* For storing free space cache */ #define BTRFS_FREE_SPACE_OBJECTID -11ULL /* * The inode number assigned to the special inode for storing * free ino cache */ #define BTRFS_FREE_INO_OBJECTID -12ULL /* dummy objectid represents multiple objectids */ #define BTRFS_MULTIPLE_OBJECTIDS -255ULL /* * All files have objectids in this range. */ #define BTRFS_FIRST_FREE_OBJECTID 256ULL #define BTRFS_LAST_FREE_OBJECTID -256ULL #define BTRFS_FIRST_CHUNK_TREE_OBJECTID 256ULL /* * the device items go into the chunk tree. The key is in the form * [ 1 BTRFS_DEV_ITEM_KEY device_id ] */ #define BTRFS_DEV_ITEMS_OBJECTID 1ULL #define BTRFS_BTREE_INODE_OBJECTID 1 #define BTRFS_EMPTY_SUBVOL_DIR_OBJECTID 2 #define BTRFS_DEV_REPLACE_DEVID 0ULL /* * inode items have the data typically returned from stat and store other * info about object characteristics. There is one for every file and dir in * the FS */ #define BTRFS_INODE_ITEM_KEY 1 #define BTRFS_INODE_REF_KEY 12 #define BTRFS_INODE_EXTREF_KEY 13 #define BTRFS_XATTR_ITEM_KEY 24 #define BTRFS_ORPHAN_ITEM_KEY 48 /* reserve 2-15 close to the inode for later flexibility */ /* * dir items are the name -> inode pointers in a directory. There is one * for every name in a directory. */ #define BTRFS_DIR_LOG_ITEM_KEY 60 #define BTRFS_DIR_LOG_INDEX_KEY 72 #define BTRFS_DIR_ITEM_KEY 84 #define BTRFS_DIR_INDEX_KEY 96 /* * extent data is for file data */ #define BTRFS_EXTENT_DATA_KEY 108 /* * extent csums are stored in a separate tree and hold csums for * an entire extent on disk. */ #define BTRFS_EXTENT_CSUM_KEY 128 /* * root items point to tree roots. They are typically in the root * tree used by the super block to find all the other trees */ #define BTRFS_ROOT_ITEM_KEY 132 /* * root backrefs tie subvols and snapshots to the directory entries that * reference them */ #define BTRFS_ROOT_BACKREF_KEY 144 /* * root refs make a fast index for listing all of the snapshots and * subvolumes referenced by a given root. They point directly to the * directory item in the root that references the subvol */ #define BTRFS_ROOT_REF_KEY 156 /* * extent items are in the extent map tree. These record which blocks * are used, and how many references there are to each block */ #define BTRFS_EXTENT_ITEM_KEY 168 /* * The same as the BTRFS_EXTENT_ITEM_KEY, except it's metadata we already know * the length, so we save the level in key->offset instead of the length. */ #define BTRFS_METADATA_ITEM_KEY 169 #define BTRFS_TREE_BLOCK_REF_KEY 176 #define BTRFS_EXTENT_DATA_REF_KEY 178 #define BTRFS_EXTENT_REF_V0_KEY 180 #define BTRFS_SHARED_BLOCK_REF_KEY 182 #define BTRFS_SHARED_DATA_REF_KEY 184 /* * block groups give us hints into the extent allocation trees. Which * blocks are free etc etc */ #define BTRFS_BLOCK_GROUP_ITEM_KEY 192 /* * Every block group is represented in the free space tree by a free space info * item, which stores some accounting information. It is keyed on * (block_group_start, FREE_SPACE_INFO, block_group_length). */ #define BTRFS_FREE_SPACE_INFO_KEY 198 /* * A free space extent tracks an extent of space that is free in a block group. * It is keyed on (start, FREE_SPACE_EXTENT, length). */ #define BTRFS_FREE_SPACE_EXTENT_KEY 199 /* * When a block group becomes very fragmented, we convert it to use bitmaps * instead of extents. A free space bitmap is keyed on * (start, FREE_SPACE_BITMAP, length); the corresponding item is a bitmap with * (length / sectorsize) bits. */ #define BTRFS_FREE_SPACE_BITMAP_KEY 200 #define BTRFS_DEV_EXTENT_KEY 204 #define BTRFS_DEV_ITEM_KEY 216 #define BTRFS_CHUNK_ITEM_KEY 228 /* * Records the overall state of the qgroups. * There's only one instance of this key present, * (0, BTRFS_QGROUP_STATUS_KEY, 0) */ #define BTRFS_QGROUP_STATUS_KEY 240 /* * Records the currently used space of the qgroup. * One key per qgroup, (0, BTRFS_QGROUP_INFO_KEY, qgroupid). */ #define BTRFS_QGROUP_INFO_KEY 242 /* * Contains the user configured limits for the qgroup. * One key per qgroup, (0, BTRFS_QGROUP_LIMIT_KEY, qgroupid). */ #define BTRFS_QGROUP_LIMIT_KEY 244 /* * Records the child-parent relationship of qgroups. For * each relation, 2 keys are present: * (childid, BTRFS_QGROUP_RELATION_KEY, parentid) * (parentid, BTRFS_QGROUP_RELATION_KEY, childid) */ #define BTRFS_QGROUP_RELATION_KEY 246 /* * Obsolete name, see BTRFS_TEMPORARY_ITEM_KEY. */ #define BTRFS_BALANCE_ITEM_KEY 248 /* * The key type for tree items that are stored persistently, but do not need to * exist for extended period of time. The items can exist in any tree. * * [subtype, BTRFS_TEMPORARY_ITEM_KEY, data] * * Existing items: * * - balance status item * (BTRFS_BALANCE_OBJECTID, BTRFS_TEMPORARY_ITEM_KEY, 0) */ #define BTRFS_TEMPORARY_ITEM_KEY 248 /* * Obsolete name, see BTRFS_PERSISTENT_ITEM_KEY */ #define BTRFS_DEV_STATS_KEY 249 /* * The key type for tree items that are stored persistently and usually exist * for a long period, eg. filesystem lifetime. The item kinds can be status * information, stats or preference values. The item can exist in any tree. * * [subtype, BTRFS_PERSISTENT_ITEM_KEY, data] * * Existing items: * * - device statistics, store IO stats in the device tree, one key for all * stats * (BTRFS_DEV_STATS_OBJECTID, BTRFS_DEV_STATS_KEY, 0) */ #define BTRFS_PERSISTENT_ITEM_KEY 249 /* * Persistantly stores the device replace state in the device tree. * The key is built like this: (0, BTRFS_DEV_REPLACE_KEY, 0). */ #define BTRFS_DEV_REPLACE_KEY 250 /* * Stores items that allow to quickly map UUIDs to something else. * These items are part of the filesystem UUID tree. * The key is built like this: * (UUID_upper_64_bits, BTRFS_UUID_KEY*, UUID_lower_64_bits). */ #if BTRFS_UUID_SIZE != 16 #error "UUID items require BTRFS_UUID_SIZE == 16!" #endif #define BTRFS_UUID_KEY_SUBVOL 251 /* for UUIDs assigned to subvols */ #define BTRFS_UUID_KEY_RECEIVED_SUBVOL 252 /* for UUIDs assigned to * received subvols */ /* * string items are for debugging. They just store a short string of * data in the FS */ #define BTRFS_STRING_ITEM_KEY 253 /* 32 bytes in various csum fields */ #define BTRFS_CSUM_SIZE 32 /* csum types */ #define BTRFS_CSUM_TYPE_CRC32 0 /* * flags definitions for directory entry item type * * Used by: * struct btrfs_dir_item.type */ #define BTRFS_FT_UNKNOWN 0 #define BTRFS_FT_REG_FILE 1 #define BTRFS_FT_DIR 2 #define BTRFS_FT_CHRDEV 3 #define BTRFS_FT_BLKDEV 4 #define BTRFS_FT_FIFO 5 #define BTRFS_FT_SOCK 6 #define BTRFS_FT_SYMLINK 7 #define BTRFS_FT_XATTR 8 #define BTRFS_FT_MAX 9 /* * The key defines the order in the tree, and so it also defines (optimal) * block layout. * * objectid corresponds to the inode number. * * type tells us things about the object, and is a kind of stream selector. * so for a given inode, keys with type of 1 might refer to the inode data, * type of 2 may point to file data in the btree and type == 3 may point to * extents. * * offset is the starting byte offset for this key in the stream. * * btrfs_disk_key is in disk byte order. struct btrfs_key is always * in cpu native order. Otherwise they are identical and their sizes * should be the same (ie both packed) */ struct btrfs_disk_key { __le64 objectid; __u8 type; __le64 offset; } __attribute__ ((__packed__)); struct btrfs_key { __u64 objectid; __u8 type; __u64 offset; } __attribute__ ((__packed__)); struct btrfs_dev_item { /* the internal btrfs device id */ __le64 devid; /* size of the device */ __le64 total_bytes; /* bytes used */ __le64 bytes_used; /* optimal io alignment for this device */ __le32 io_align; /* optimal io width for this device */ __le32 io_width; /* minimal io size for this device */ __le32 sector_size; /* type and info about this device */ __le64 type; /* expected generation for this device */ __le64 generation; /* * starting byte of this partition on the device, * to allow for stripe alignment in the future */ __le64 start_offset; /* grouping information for allocation decisions */ __le32 dev_group; /* seek speed 0-100 where 100 is fastest */ __u8 seek_speed; /* bandwidth 0-100 where 100 is fastest */ __u8 bandwidth; /* btrfs generated uuid for this device */ __u8 uuid[BTRFS_UUID_SIZE]; /* uuid of FS who owns this device */ __u8 fsid[BTRFS_UUID_SIZE]; } __attribute__ ((__packed__)); struct btrfs_stripe { __le64 devid; __le64 offset; __u8 dev_uuid[BTRFS_UUID_SIZE]; } __attribute__ ((__packed__)); struct btrfs_chunk { /* size of this chunk in bytes */ __le64 length; /* objectid of the root referencing this chunk */ __le64 owner; __le64 stripe_len; __le64 type; /* optimal io alignment for this chunk */ __le32 io_align; /* optimal io width for this chunk */ __le32 io_width; /* minimal io size for this chunk */ __le32 sector_size; /* 2^16 stripes is quite a lot, a second limit is the size of a single * item in the btree */ __le16 num_stripes; /* sub stripes only matter for raid10 */ __le16 sub_stripes; struct btrfs_stripe stripe; /* additional stripes go here */ } __attribute__ ((__packed__)); #define BTRFS_FREE_SPACE_EXTENT 1 #define BTRFS_FREE_SPACE_BITMAP 2 struct btrfs_free_space_entry { __le64 offset; __le64 bytes; __u8 type; } __attribute__ ((__packed__)); struct btrfs_free_space_header { struct btrfs_disk_key location; __le64 generation; __le64 num_entries; __le64 num_bitmaps; } __attribute__ ((__packed__)); #define BTRFS_HEADER_FLAG_WRITTEN (1ULL << 0) #define BTRFS_HEADER_FLAG_RELOC (1ULL << 1) /* Super block flags */ /* Errors detected */ #define BTRFS_SUPER_FLAG_ERROR (1ULL << 2) #define BTRFS_SUPER_FLAG_SEEDING (1ULL << 32) #define BTRFS_SUPER_FLAG_METADUMP (1ULL << 33) #define BTRFS_SUPER_FLAG_METADUMP_V2 (1ULL << 34) #define BTRFS_SUPER_FLAG_CHANGING_FSID (1ULL << 35) /* * items in the extent btree are used to record the objectid of the * owner of the block and the number of references */ struct btrfs_extent_item { __le64 refs; __le64 generation; __le64 flags; } __attribute__ ((__packed__)); struct btrfs_extent_item_v0 { __le32 refs; } __attribute__ ((__packed__)); #define BTRFS_EXTENT_FLAG_DATA (1ULL << 0) #define BTRFS_EXTENT_FLAG_TREE_BLOCK (1ULL << 1) /* following flags only apply to tree blocks */ /* use full backrefs for extent pointers in the block */ #define BTRFS_BLOCK_FLAG_FULL_BACKREF (1ULL << 8) /* * this flag is only used internally by scrub and may be changed at any time * it is only declared here to avoid collisions */ #define BTRFS_EXTENT_FLAG_SUPER (1ULL << 48) struct btrfs_tree_block_info { struct btrfs_disk_key key; __u8 level; } __attribute__ ((__packed__)); struct btrfs_extent_data_ref { __le64 root; __le64 objectid; __le64 offset; __le32 count; } __attribute__ ((__packed__)); struct btrfs_shared_data_ref { __le32 count; } __attribute__ ((__packed__)); struct btrfs_extent_inline_ref { __u8 type; __le64 offset; } __attribute__ ((__packed__)); /* old style backrefs item */ struct btrfs_extent_ref_v0 { __le64 root; __le64 generation; __le64 objectid; __le32 count; } __attribute__ ((__packed__)); /* dev extents record free space on individual devices. The owner * field points back to the chunk allocation mapping tree that allocated * the extent. The chunk tree uuid field is a way to double check the owner */ struct btrfs_dev_extent { __le64 chunk_tree; __le64 chunk_objectid; __le64 chunk_offset; __le64 length; __u8 chunk_tree_uuid[BTRFS_UUID_SIZE]; } __attribute__ ((__packed__)); struct btrfs_inode_ref { __le64 index; __le16 name_len; /* name goes here */ } __attribute__ ((__packed__)); struct btrfs_inode_extref { __le64 parent_objectid; __le64 index; __le16 name_len; __u8 name[0]; /* name goes here */ } __attribute__ ((__packed__)); struct btrfs_timespec { __le64 sec; __le32 nsec; } __attribute__ ((__packed__)); struct btrfs_inode_item { /* nfs style generation number */ __le64 generation; /* transid that last touched this inode */ __le64 transid; __le64 size; __le64 nbytes; __le64 block_group; __le32 nlink; __le32 uid; __le32 gid; __le32 mode; __le64 rdev; __le64 flags; /* modification sequence number for NFS */ __le64 sequence; /* * a little future expansion, for more than this we can * just grow the inode item and version it */ __le64 reserved[4]; struct btrfs_timespec atime; struct btrfs_timespec ctime; struct btrfs_timespec mtime; struct btrfs_timespec otime; } __attribute__ ((__packed__)); struct btrfs_dir_log_item { __le64 end; } __attribute__ ((__packed__)); struct btrfs_dir_item { struct btrfs_disk_key location; __le64 transid; __le16 data_len; __le16 name_len; __u8 type; } __attribute__ ((__packed__)); #define BTRFS_ROOT_SUBVOL_RDONLY (1ULL << 0) /* * Internal in-memory flag that a subvolume has been marked for deletion but * still visible as a directory */ #define BTRFS_ROOT_SUBVOL_DEAD (1ULL << 48) struct btrfs_root_item { struct btrfs_inode_item inode; __le64 generation; __le64 root_dirid; __le64 bytenr; __le64 byte_limit; __le64 bytes_used; __le64 last_snapshot; __le64 flags; __le32 refs; struct btrfs_disk_key drop_progress; __u8 drop_level; __u8 level; /* * The following fields appear after subvol_uuids+subvol_times * were introduced. */ /* * This generation number is used to test if the new fields are valid * and up to date while reading the root item. Every time the root item * is written out, the "generation" field is copied into this field. If * anyone ever mounted the fs with an older kernel, we will have * mismatching generation values here and thus must invalidate the * new fields. See btrfs_update_root and btrfs_find_last_root for * details. * the offset of generation_v2 is also used as the start for the memset * when invalidating the fields. */ __le64 generation_v2; __u8 uuid[BTRFS_UUID_SIZE]; __u8 parent_uuid[BTRFS_UUID_SIZE]; __u8 received_uuid[BTRFS_UUID_SIZE]; __le64 ctransid; /* updated when an inode changes */ __le64 otransid; /* trans when created */ __le64 stransid; /* trans when sent. non-zero for received subvol */ __le64 rtransid; /* trans when received. non-zero for received subvol */ struct btrfs_timespec ctime; struct btrfs_timespec otime; struct btrfs_timespec stime; struct btrfs_timespec rtime; __le64 reserved[8]; /* for future */ } __attribute__ ((__packed__)); /* * this is used for both forward and backward root refs */ struct btrfs_root_ref { __le64 dirid; __le64 sequence; __le16 name_len; } __attribute__ ((__packed__)); struct btrfs_disk_balance_args { /* * profiles to operate on, single is denoted by * BTRFS_AVAIL_ALLOC_BIT_SINGLE */ __le64 profiles; /* * usage filter * BTRFS_BALANCE_ARGS_USAGE with a single value means '0..N' * BTRFS_BALANCE_ARGS_USAGE_RANGE - range syntax, min..max */ union { __le64 usage; struct { __le32 usage_min; __le32 usage_max; }; }; /* devid filter */ __le64 devid; /* devid subset filter [pstart..pend) */ __le64 pstart; __le64 pend; /* btrfs virtual address space subset filter [vstart..vend) */ __le64 vstart; __le64 vend; /* * profile to convert to, single is denoted by * BTRFS_AVAIL_ALLOC_BIT_SINGLE */ __le64 target; /* BTRFS_BALANCE_ARGS_* */ __le64 flags; /* * BTRFS_BALANCE_ARGS_LIMIT with value 'limit' * BTRFS_BALANCE_ARGS_LIMIT_RANGE - the extend version can use minimum * and maximum */ union { __le64 limit; struct { __le32 limit_min; __le32 limit_max; }; }; /* * Process chunks that cross stripes_min..stripes_max devices, * BTRFS_BALANCE_ARGS_STRIPES_RANGE */ __le32 stripes_min; __le32 stripes_max; __le64 unused[6]; } __attribute__ ((__packed__)); /* * store balance parameters to disk so that balance can be properly * resumed after crash or unmount */ struct btrfs_balance_item { /* BTRFS_BALANCE_* */ __le64 flags; struct btrfs_disk_balance_args data; struct btrfs_disk_balance_args meta; struct btrfs_disk_balance_args sys; __le64 unused[4]; } __attribute__ ((__packed__)); #define BTRFS_FILE_EXTENT_INLINE 0 #define BTRFS_FILE_EXTENT_REG 1 #define BTRFS_FILE_EXTENT_PREALLOC 2 #define BTRFS_FILE_EXTENT_TYPES 2 struct btrfs_file_extent_item { /* * transaction id that created this extent */ __le64 generation; /* * max number of bytes to hold this extent in ram * when we split a compressed extent we can't know how big * each of the resulting pieces will be. So, this is * an upper limit on the size of the extent in ram instead of * an exact limit. */ __le64 ram_bytes; /* * 32 bits for the various ways we might encode the data, * including compression and encryption. If any of these * are set to something a given disk format doesn't understand * it is treated like an incompat flag for reading and writing, * but not for stat. */ __u8 compression; __u8 encryption; __le16 other_encoding; /* spare for later use */ /* are we __inline__ data or a real extent? */ __u8 type; /* * disk space consumed by the extent, checksum blocks are included * in these numbers * * At this offset in the structure, the __inline__ extent data start. */ __le64 disk_bytenr; __le64 disk_num_bytes; /* * the logical offset in file blocks (no csums) * this extent record is for. This allows a file extent to point * into the middle of an existing extent on disk, sharing it * between two snapshots (useful if some bytes in the middle of the * extent have changed */ __le64 offset; /* * the logical number of file blocks (no csums included). This * always reflects the size uncompressed and without encoding. */ __le64 num_bytes; } __attribute__ ((__packed__)); struct btrfs_csum_item { __u8 csum; } __attribute__ ((__packed__)); struct btrfs_dev_stats_item { /* * grow this item struct at the end for future enhancements and keep * the existing values unchanged */ __le64 values[BTRFS_DEV_STAT_VALUES_MAX]; } __attribute__ ((__packed__)); #define BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS 0 #define BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID 1 #define BTRFS_DEV_REPLACE_ITEM_STATE_NEVER_STARTED 0 #define BTRFS_DEV_REPLACE_ITEM_STATE_STARTED 1 #define BTRFS_DEV_REPLACE_ITEM_STATE_SUSPENDED 2 #define BTRFS_DEV_REPLACE_ITEM_STATE_FINISHED 3 #define BTRFS_DEV_REPLACE_ITEM_STATE_CANCELED 4 struct btrfs_dev_replace_item { /* * grow this item struct at the end for future enhancements and keep * the existing values unchanged */ __le64 src_devid; __le64 cursor_left; __le64 cursor_right; __le64 cont_reading_from_srcdev_mode; __le64 replace_state; __le64 time_started; __le64 time_stopped; __le64 num_write_errors; __le64 num_uncorrectable_read_errors; } __attribute__ ((__packed__)); /* different types of block groups (and chunks) */ #define BTRFS_BLOCK_GROUP_DATA (1ULL << 0) #define BTRFS_BLOCK_GROUP_SYSTEM (1ULL << 1) #define BTRFS_BLOCK_GROUP_METADATA (1ULL << 2) #define BTRFS_BLOCK_GROUP_RAID0 (1ULL << 3) #define BTRFS_BLOCK_GROUP_RAID1 (1ULL << 4) #define BTRFS_BLOCK_GROUP_DUP (1ULL << 5) #define BTRFS_BLOCK_GROUP_RAID10 (1ULL << 6) #define BTRFS_BLOCK_GROUP_RAID5 (1ULL << 7) #define BTRFS_BLOCK_GROUP_RAID6 (1ULL << 8) #define BTRFS_BLOCK_GROUP_RESERVED (BTRFS_AVAIL_ALLOC_BIT_SINGLE | \ BTRFS_SPACE_INFO_GLOBAL_RSV) enum btrfs_raid_types { BTRFS_RAID_RAID10, BTRFS_RAID_RAID1, BTRFS_RAID_DUP, BTRFS_RAID_RAID0, BTRFS_RAID_SINGLE, BTRFS_RAID_RAID5, BTRFS_RAID_RAID6, BTRFS_NR_RAID_TYPES }; #define BTRFS_BLOCK_GROUP_TYPE_MASK (BTRFS_BLOCK_GROUP_DATA | \ BTRFS_BLOCK_GROUP_SYSTEM | \ BTRFS_BLOCK_GROUP_METADATA) #define BTRFS_BLOCK_GROUP_PROFILE_MASK (BTRFS_BLOCK_GROUP_RAID0 | \ BTRFS_BLOCK_GROUP_RAID1 | \ BTRFS_BLOCK_GROUP_RAID5 | \ BTRFS_BLOCK_GROUP_RAID6 | \ BTRFS_BLOCK_GROUP_DUP | \ BTRFS_BLOCK_GROUP_RAID10) #define BTRFS_BLOCK_GROUP_RAID56_MASK (BTRFS_BLOCK_GROUP_RAID5 | \ BTRFS_BLOCK_GROUP_RAID6) /* * We need a bit for restriper to be able to tell when chunks of type * SINGLE are available. This "extended" profile format is used in * fs_info->avail_*_alloc_bits (in-memory) and balance item fields * (on-disk). The corresponding on-disk bit in chunk.type is reserved * to avoid remappings between two formats in future. */ #define BTRFS_AVAIL_ALLOC_BIT_SINGLE (1ULL << 48) /* * A fake block group type that is used to communicate global block reserve * size to userspace via the SPACE_INFO ioctl. */ #define BTRFS_SPACE_INFO_GLOBAL_RSV (1ULL << 49) #define BTRFS_EXTENDED_PROFILE_MASK (BTRFS_BLOCK_GROUP_PROFILE_MASK | \ BTRFS_AVAIL_ALLOC_BIT_SINGLE) static __inline__ __u64 chunk_to_extended(__u64 flags) { if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0) flags |= BTRFS_AVAIL_ALLOC_BIT_SINGLE; return flags; } static __inline__ __u64 extended_to_chunk(__u64 flags) { return flags & ~BTRFS_AVAIL_ALLOC_BIT_SINGLE; } struct btrfs_block_group_item { __le64 used; __le64 chunk_objectid; __le64 flags; } __attribute__ ((__packed__)); struct btrfs_free_space_info { __le32 extent_count; __le32 flags; } __attribute__ ((__packed__)); #define BTRFS_FREE_SPACE_USING_BITMAPS (1ULL << 0) #define BTRFS_QGROUP_LEVEL_SHIFT 48 static __inline__ __u64 btrfs_qgroup_level(__u64 qgroupid) { return qgroupid >> BTRFS_QGROUP_LEVEL_SHIFT; } /* * is subvolume quota turned on? */ #define BTRFS_QGROUP_STATUS_FLAG_ON (1ULL << 0) /* * RESCAN is set during the initialization phase */ #define BTRFS_QGROUP_STATUS_FLAG_RESCAN (1ULL << 1) /* * Some qgroup entries are known to be out of date, * either because the configuration has changed in a way that * makes a rescan necessary, or because the fs has been mounted * with a non-qgroup-aware version. * Turning qouta off and on again makes it inconsistent, too. */ #define BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT (1ULL << 2) #define BTRFS_QGROUP_STATUS_VERSION 1 struct btrfs_qgroup_status_item { __le64 version; /* * the generation is updated during every commit. As older * versions of btrfs are not aware of qgroups, it will be * possible to detect inconsistencies by checking the * generation on mount time */ __le64 generation; /* flag definitions see above */ __le64 flags; /* * only used during scanning to record the progress * of the scan. It contains a logical address */ __le64 rescan; } __attribute__ ((__packed__)); struct btrfs_qgroup_info_item { __le64 generation; __le64 rfer; __le64 rfer_cmpr; __le64 excl; __le64 excl_cmpr; } __attribute__ ((__packed__)); struct btrfs_qgroup_limit_item { /* * only updated when any of the other values change */ __le64 flags; __le64 max_rfer; __le64 max_excl; __le64 rsv_rfer; __le64 rsv_excl; } __attribute__ ((__packed__)); #endif /* _BTRFS_CTREE_H_ */ linux/wireless.h000064400000123317151027430560007723 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * This file define a set of standard wireless extensions * * Version : 22 16.3.07 * * Authors : Jean Tourrilhes - HPL - * Copyright (c) 1997-2007 Jean Tourrilhes, All Rights Reserved. */ #ifndef _LINUX_WIRELESS_H #define _LINUX_WIRELESS_H /************************** DOCUMENTATION **************************/ /* * Initial APIs (1996 -> onward) : * ----------------------------- * Basically, the wireless extensions are for now a set of standard ioctl * call + /proc/net/wireless * * The entry /proc/net/wireless give statistics and information on the * driver. * This is better than having each driver having its entry because * its centralised and we may remove the driver module safely. * * Ioctl are used to configure the driver and issue commands. This is * better than command line options of insmod because we may want to * change dynamically (while the driver is running) some parameters. * * The ioctl mechanimsm are copied from standard devices ioctl. * We have the list of command plus a structure descibing the * data exchanged... * Note that to add these ioctl, I was obliged to modify : * # net/core/dev.c (two place + add include) * # net/ipv4/af_inet.c (one place + add include) * * /proc/net/wireless is a copy of /proc/net/dev. * We have a structure for data passed from the driver to /proc/net/wireless * Too add this, I've modified : * # net/core/dev.c (two other places) * # include/linux/netdevice.h (one place) * # include/linux/proc_fs.h (one place) * * New driver API (2002 -> onward) : * ------------------------------- * This file is only concerned with the user space API and common definitions. * The new driver API is defined and documented in : * # include/net/iw_handler.h * * Note as well that /proc/net/wireless implementation has now moved in : * # net/core/wireless.c * * Wireless Events (2002 -> onward) : * -------------------------------- * Events are defined at the end of this file, and implemented in : * # net/core/wireless.c * * Other comments : * -------------- * Do not add here things that are redundant with other mechanisms * (drivers init, ifconfig, /proc/net/dev, ...) and with are not * wireless specific. * * These wireless extensions are not magic : each driver has to provide * support for them... * * IMPORTANT NOTE : As everything in the kernel, this is very much a * work in progress. Contact me if you have ideas of improvements... */ /***************************** INCLUDES *****************************/ #include /* for __u* and __s* typedefs */ #include /* for "struct sockaddr" et al */ #include /* for IFNAMSIZ and co... */ /***************************** VERSION *****************************/ /* * This constant is used to know the availability of the wireless * extensions and to know which version of wireless extensions it is * (there is some stuff that will be added in the future...) * I just plan to increment with each new version. */ #define WIRELESS_EXT 22 /* * Changes : * * V2 to V3 * -------- * Alan Cox start some incompatibles changes. I've integrated a bit more. * - Encryption renamed to Encode to avoid US regulation problems * - Frequency changed from float to struct to avoid problems on old 386 * * V3 to V4 * -------- * - Add sensitivity * * V4 to V5 * -------- * - Missing encoding definitions in range * - Access points stuff * * V5 to V6 * -------- * - 802.11 support (ESSID ioctls) * * V6 to V7 * -------- * - define IW_ESSID_MAX_SIZE and IW_MAX_AP * * V7 to V8 * -------- * - Changed my e-mail address * - More 802.11 support (nickname, rate, rts, frag) * - List index in frequencies * * V8 to V9 * -------- * - Support for 'mode of operation' (ad-hoc, managed...) * - Support for unicast and multicast power saving * - Change encoding to support larger tokens (>64 bits) * - Updated iw_params (disable, flags) and use it for NWID * - Extracted iw_point from iwreq for clarity * * V9 to V10 * --------- * - Add PM capability to range structure * - Add PM modifier : MAX/MIN/RELATIVE * - Add encoding option : IW_ENCODE_NOKEY * - Add TxPower ioctls (work like TxRate) * * V10 to V11 * ---------- * - Add WE version in range (help backward/forward compatibility) * - Add retry ioctls (work like PM) * * V11 to V12 * ---------- * - Add SIOCSIWSTATS to get /proc/net/wireless programatically * - Add DEV PRIVATE IOCTL to avoid collisions in SIOCDEVPRIVATE space * - Add new statistics (frag, retry, beacon) * - Add average quality (for user space calibration) * * V12 to V13 * ---------- * - Document creation of new driver API. * - Extract union iwreq_data from struct iwreq (for new driver API). * - Rename SIOCSIWNAME as SIOCSIWCOMMIT * * V13 to V14 * ---------- * - Wireless Events support : define struct iw_event * - Define additional specific event numbers * - Add "addr" and "param" fields in union iwreq_data * - AP scanning stuff (SIOCSIWSCAN and friends) * * V14 to V15 * ---------- * - Add IW_PRIV_TYPE_ADDR for struct sockaddr private arg * - Make struct iw_freq signed (both m & e), add explicit padding * - Add IWEVCUSTOM for driver specific event/scanning token * - Add IW_MAX_GET_SPY for driver returning a lot of addresses * - Add IW_TXPOW_RANGE for range of Tx Powers * - Add IWEVREGISTERED & IWEVEXPIRED events for Access Points * - Add IW_MODE_MONITOR for passive monitor * * V15 to V16 * ---------- * - Increase the number of bitrates in iw_range to 32 (for 802.11g) * - Increase the number of frequencies in iw_range to 32 (for 802.11b+a) * - Reshuffle struct iw_range for increases, add filler * - Increase IW_MAX_AP to 64 for driver returning a lot of addresses * - Remove IW_MAX_GET_SPY because conflict with enhanced spy support * - Add SIOCSIWTHRSPY/SIOCGIWTHRSPY and "struct iw_thrspy" * - Add IW_ENCODE_TEMP and iw_range->encoding_login_index * * V16 to V17 * ---------- * - Add flags to frequency -> auto/fixed * - Document (struct iw_quality *)->updated, add new flags (INVALID) * - Wireless Event capability in struct iw_range * - Add support for relative TxPower (yick !) * * V17 to V18 (From Jouni Malinen ) * ---------- * - Add support for WPA/WPA2 * - Add extended encoding configuration (SIOCSIWENCODEEXT and * SIOCGIWENCODEEXT) * - Add SIOCSIWGENIE/SIOCGIWGENIE * - Add SIOCSIWMLME * - Add SIOCSIWPMKSA * - Add struct iw_range bit field for supported encoding capabilities * - Add optional scan request parameters for SIOCSIWSCAN * - Add SIOCSIWAUTH/SIOCGIWAUTH for setting authentication and WPA * related parameters (extensible up to 4096 parameter values) * - Add wireless events: IWEVGENIE, IWEVMICHAELMICFAILURE, * IWEVASSOCREQIE, IWEVASSOCRESPIE, IWEVPMKIDCAND * * V18 to V19 * ---------- * - Remove (struct iw_point *)->pointer from events and streams * - Remove header includes to help user space * - Increase IW_ENCODING_TOKEN_MAX from 32 to 64 * - Add IW_QUAL_ALL_UPDATED and IW_QUAL_ALL_INVALID macros * - Add explicit flag to tell stats are in dBm : IW_QUAL_DBM * - Add IW_IOCTL_IDX() and IW_EVENT_IDX() macros * * V19 to V20 * ---------- * - RtNetlink requests support (SET/GET) * * V20 to V21 * ---------- * - Remove (struct net_device *)->get_wireless_stats() * - Change length in ESSID and NICK to strlen() instead of strlen()+1 * - Add IW_RETRY_SHORT/IW_RETRY_LONG retry modifiers * - Power/Retry relative values no longer * 100000 * - Add explicit flag to tell stats are in 802.11k RCPI : IW_QUAL_RCPI * * V21 to V22 * ---------- * - Prevent leaking of kernel space in stream on 64 bits. */ /**************************** CONSTANTS ****************************/ /* -------------------------- IOCTL LIST -------------------------- */ /* Wireless Identification */ #define SIOCSIWCOMMIT 0x8B00 /* Commit pending changes to driver */ #define SIOCGIWNAME 0x8B01 /* get name == wireless protocol */ /* SIOCGIWNAME is used to verify the presence of Wireless Extensions. * Common values : "IEEE 802.11-DS", "IEEE 802.11-FH", "IEEE 802.11b"... * Don't put the name of your driver there, it's useless. */ /* Basic operations */ #define SIOCSIWNWID 0x8B02 /* set network id (pre-802.11) */ #define SIOCGIWNWID 0x8B03 /* get network id (the cell) */ #define SIOCSIWFREQ 0x8B04 /* set channel/frequency (Hz) */ #define SIOCGIWFREQ 0x8B05 /* get channel/frequency (Hz) */ #define SIOCSIWMODE 0x8B06 /* set operation mode */ #define SIOCGIWMODE 0x8B07 /* get operation mode */ #define SIOCSIWSENS 0x8B08 /* set sensitivity (dBm) */ #define SIOCGIWSENS 0x8B09 /* get sensitivity (dBm) */ /* Informative stuff */ #define SIOCSIWRANGE 0x8B0A /* Unused */ #define SIOCGIWRANGE 0x8B0B /* Get range of parameters */ #define SIOCSIWPRIV 0x8B0C /* Unused */ #define SIOCGIWPRIV 0x8B0D /* get private ioctl interface info */ #define SIOCSIWSTATS 0x8B0E /* Unused */ #define SIOCGIWSTATS 0x8B0F /* Get /proc/net/wireless stats */ /* SIOCGIWSTATS is strictly used between user space and the kernel, and * is never passed to the driver (i.e. the driver will never see it). */ /* Spy support (statistics per MAC address - used for Mobile IP support) */ #define SIOCSIWSPY 0x8B10 /* set spy addresses */ #define SIOCGIWSPY 0x8B11 /* get spy info (quality of link) */ #define SIOCSIWTHRSPY 0x8B12 /* set spy threshold (spy event) */ #define SIOCGIWTHRSPY 0x8B13 /* get spy threshold */ /* Access Point manipulation */ #define SIOCSIWAP 0x8B14 /* set access point MAC addresses */ #define SIOCGIWAP 0x8B15 /* get access point MAC addresses */ #define SIOCGIWAPLIST 0x8B17 /* Deprecated in favor of scanning */ #define SIOCSIWSCAN 0x8B18 /* trigger scanning (list cells) */ #define SIOCGIWSCAN 0x8B19 /* get scanning results */ /* 802.11 specific support */ #define SIOCSIWESSID 0x8B1A /* set ESSID (network name) */ #define SIOCGIWESSID 0x8B1B /* get ESSID */ #define SIOCSIWNICKN 0x8B1C /* set node name/nickname */ #define SIOCGIWNICKN 0x8B1D /* get node name/nickname */ /* As the ESSID and NICKN are strings up to 32 bytes long, it doesn't fit * within the 'iwreq' structure, so we need to use the 'data' member to * point to a string in user space, like it is done for RANGE... */ /* Other parameters useful in 802.11 and some other devices */ #define SIOCSIWRATE 0x8B20 /* set default bit rate (bps) */ #define SIOCGIWRATE 0x8B21 /* get default bit rate (bps) */ #define SIOCSIWRTS 0x8B22 /* set RTS/CTS threshold (bytes) */ #define SIOCGIWRTS 0x8B23 /* get RTS/CTS threshold (bytes) */ #define SIOCSIWFRAG 0x8B24 /* set fragmentation thr (bytes) */ #define SIOCGIWFRAG 0x8B25 /* get fragmentation thr (bytes) */ #define SIOCSIWTXPOW 0x8B26 /* set transmit power (dBm) */ #define SIOCGIWTXPOW 0x8B27 /* get transmit power (dBm) */ #define SIOCSIWRETRY 0x8B28 /* set retry limits and lifetime */ #define SIOCGIWRETRY 0x8B29 /* get retry limits and lifetime */ /* Encoding stuff (scrambling, hardware security, WEP...) */ #define SIOCSIWENCODE 0x8B2A /* set encoding token & mode */ #define SIOCGIWENCODE 0x8B2B /* get encoding token & mode */ /* Power saving stuff (power management, unicast and multicast) */ #define SIOCSIWPOWER 0x8B2C /* set Power Management settings */ #define SIOCGIWPOWER 0x8B2D /* get Power Management settings */ /* WPA : Generic IEEE 802.11 informatiom element (e.g., for WPA/RSN/WMM). * This ioctl uses struct iw_point and data buffer that includes IE id and len * fields. More than one IE may be included in the request. Setting the generic * IE to empty buffer (len=0) removes the generic IE from the driver. Drivers * are allowed to generate their own WPA/RSN IEs, but in these cases, drivers * are required to report the used IE as a wireless event, e.g., when * associating with an AP. */ #define SIOCSIWGENIE 0x8B30 /* set generic IE */ #define SIOCGIWGENIE 0x8B31 /* get generic IE */ /* WPA : IEEE 802.11 MLME requests */ #define SIOCSIWMLME 0x8B16 /* request MLME operation; uses * struct iw_mlme */ /* WPA : Authentication mode parameters */ #define SIOCSIWAUTH 0x8B32 /* set authentication mode params */ #define SIOCGIWAUTH 0x8B33 /* get authentication mode params */ /* WPA : Extended version of encoding configuration */ #define SIOCSIWENCODEEXT 0x8B34 /* set encoding token & mode */ #define SIOCGIWENCODEEXT 0x8B35 /* get encoding token & mode */ /* WPA2 : PMKSA cache management */ #define SIOCSIWPMKSA 0x8B36 /* PMKSA cache operation */ /* -------------------- DEV PRIVATE IOCTL LIST -------------------- */ /* These 32 ioctl are wireless device private, for 16 commands. * Each driver is free to use them for whatever purpose it chooses, * however the driver *must* export the description of those ioctls * with SIOCGIWPRIV and *must* use arguments as defined below. * If you don't follow those rules, DaveM is going to hate you (reason : * it make mixed 32/64bit operation impossible). */ #define SIOCIWFIRSTPRIV 0x8BE0 #define SIOCIWLASTPRIV 0x8BFF /* Previously, we were using SIOCDEVPRIVATE, but we now have our * separate range because of collisions with other tools such as * 'mii-tool'. * We now have 32 commands, so a bit more space ;-). * Also, all 'even' commands are only usable by root and don't return the * content of ifr/iwr to user (but you are not obliged to use the set/get * convention, just use every other two command). More details in iwpriv.c. * And I repeat : you are not forced to use them with iwpriv, but you * must be compliant with it. */ /* ------------------------- IOCTL STUFF ------------------------- */ /* The first and the last (range) */ #define SIOCIWFIRST 0x8B00 #define SIOCIWLAST SIOCIWLASTPRIV /* 0x8BFF */ #define IW_IOCTL_IDX(cmd) ((cmd) - SIOCIWFIRST) #define IW_HANDLER(id, func) \ [IW_IOCTL_IDX(id)] = func /* Odd : get (world access), even : set (root access) */ #define IW_IS_SET(cmd) (!((cmd) & 0x1)) #define IW_IS_GET(cmd) ((cmd) & 0x1) /* ----------------------- WIRELESS EVENTS ----------------------- */ /* Those are *NOT* ioctls, do not issue request on them !!! */ /* Most events use the same identifier as ioctl requests */ #define IWEVTXDROP 0x8C00 /* Packet dropped to excessive retry */ #define IWEVQUAL 0x8C01 /* Quality part of statistics (scan) */ #define IWEVCUSTOM 0x8C02 /* Driver specific ascii string */ #define IWEVREGISTERED 0x8C03 /* Discovered a new node (AP mode) */ #define IWEVEXPIRED 0x8C04 /* Expired a node (AP mode) */ #define IWEVGENIE 0x8C05 /* Generic IE (WPA, RSN, WMM, ..) * (scan results); This includes id and * length fields. One IWEVGENIE may * contain more than one IE. Scan * results may contain one or more * IWEVGENIE events. */ #define IWEVMICHAELMICFAILURE 0x8C06 /* Michael MIC failure * (struct iw_michaelmicfailure) */ #define IWEVASSOCREQIE 0x8C07 /* IEs used in (Re)Association Request. * The data includes id and length * fields and may contain more than one * IE. This event is required in * Managed mode if the driver * generates its own WPA/RSN IE. This * should be sent just before * IWEVREGISTERED event for the * association. */ #define IWEVASSOCRESPIE 0x8C08 /* IEs used in (Re)Association * Response. The data includes id and * length fields and may contain more * than one IE. This may be sent * between IWEVASSOCREQIE and * IWEVREGISTERED events for the * association. */ #define IWEVPMKIDCAND 0x8C09 /* PMKID candidate for RSN * pre-authentication * (struct iw_pmkid_cand) */ #define IWEVFIRST 0x8C00 #define IW_EVENT_IDX(cmd) ((cmd) - IWEVFIRST) /* ------------------------- PRIVATE INFO ------------------------- */ /* * The following is used with SIOCGIWPRIV. It allow a driver to define * the interface (name, type of data) for its private ioctl. * Privates ioctl are SIOCIWFIRSTPRIV -> SIOCIWLASTPRIV */ #define IW_PRIV_TYPE_MASK 0x7000 /* Type of arguments */ #define IW_PRIV_TYPE_NONE 0x0000 #define IW_PRIV_TYPE_BYTE 0x1000 /* Char as number */ #define IW_PRIV_TYPE_CHAR 0x2000 /* Char as character */ #define IW_PRIV_TYPE_INT 0x4000 /* 32 bits int */ #define IW_PRIV_TYPE_FLOAT 0x5000 /* struct iw_freq */ #define IW_PRIV_TYPE_ADDR 0x6000 /* struct sockaddr */ #define IW_PRIV_SIZE_FIXED 0x0800 /* Variable or fixed number of args */ #define IW_PRIV_SIZE_MASK 0x07FF /* Max number of those args */ /* * Note : if the number of args is fixed and the size < 16 octets, * instead of passing a pointer we will put args in the iwreq struct... */ /* ----------------------- OTHER CONSTANTS ----------------------- */ /* Maximum frequencies in the range struct */ #define IW_MAX_FREQUENCIES 32 /* Note : if you have something like 80 frequencies, * don't increase this constant and don't fill the frequency list. * The user will be able to set by channel anyway... */ /* Maximum bit rates in the range struct */ #define IW_MAX_BITRATES 32 /* Maximum tx powers in the range struct */ #define IW_MAX_TXPOWER 8 /* Note : if you more than 8 TXPowers, just set the max and min or * a few of them in the struct iw_range. */ /* Maximum of address that you may set with SPY */ #define IW_MAX_SPY 8 /* Maximum of address that you may get in the list of access points in range */ #define IW_MAX_AP 64 /* Maximum size of the ESSID and NICKN strings */ #define IW_ESSID_MAX_SIZE 32 /* Modes of operation */ #define IW_MODE_AUTO 0 /* Let the driver decides */ #define IW_MODE_ADHOC 1 /* Single cell network */ #define IW_MODE_INFRA 2 /* Multi cell network, roaming, ... */ #define IW_MODE_MASTER 3 /* Synchronisation master or Access Point */ #define IW_MODE_REPEAT 4 /* Wireless Repeater (forwarder) */ #define IW_MODE_SECOND 5 /* Secondary master/repeater (backup) */ #define IW_MODE_MONITOR 6 /* Passive monitor (listen only) */ #define IW_MODE_MESH 7 /* Mesh (IEEE 802.11s) network */ /* Statistics flags (bitmask in updated) */ #define IW_QUAL_QUAL_UPDATED 0x01 /* Value was updated since last read */ #define IW_QUAL_LEVEL_UPDATED 0x02 #define IW_QUAL_NOISE_UPDATED 0x04 #define IW_QUAL_ALL_UPDATED 0x07 #define IW_QUAL_DBM 0x08 /* Level + Noise are dBm */ #define IW_QUAL_QUAL_INVALID 0x10 /* Driver doesn't provide value */ #define IW_QUAL_LEVEL_INVALID 0x20 #define IW_QUAL_NOISE_INVALID 0x40 #define IW_QUAL_RCPI 0x80 /* Level + Noise are 802.11k RCPI */ #define IW_QUAL_ALL_INVALID 0x70 /* Frequency flags */ #define IW_FREQ_AUTO 0x00 /* Let the driver decides */ #define IW_FREQ_FIXED 0x01 /* Force a specific value */ /* Maximum number of size of encoding token available * they are listed in the range structure */ #define IW_MAX_ENCODING_SIZES 8 /* Maximum size of the encoding token in bytes */ #define IW_ENCODING_TOKEN_MAX 64 /* 512 bits (for now) */ /* Flags for encoding (along with the token) */ #define IW_ENCODE_INDEX 0x00FF /* Token index (if needed) */ #define IW_ENCODE_FLAGS 0xFF00 /* Flags defined below */ #define IW_ENCODE_MODE 0xF000 /* Modes defined below */ #define IW_ENCODE_DISABLED 0x8000 /* Encoding disabled */ #define IW_ENCODE_ENABLED 0x0000 /* Encoding enabled */ #define IW_ENCODE_RESTRICTED 0x4000 /* Refuse non-encoded packets */ #define IW_ENCODE_OPEN 0x2000 /* Accept non-encoded packets */ #define IW_ENCODE_NOKEY 0x0800 /* Key is write only, so not present */ #define IW_ENCODE_TEMP 0x0400 /* Temporary key */ /* Power management flags available (along with the value, if any) */ #define IW_POWER_ON 0x0000 /* No details... */ #define IW_POWER_TYPE 0xF000 /* Type of parameter */ #define IW_POWER_PERIOD 0x1000 /* Value is a period/duration of */ #define IW_POWER_TIMEOUT 0x2000 /* Value is a timeout (to go asleep) */ #define IW_POWER_MODE 0x0F00 /* Power Management mode */ #define IW_POWER_UNICAST_R 0x0100 /* Receive only unicast messages */ #define IW_POWER_MULTICAST_R 0x0200 /* Receive only multicast messages */ #define IW_POWER_ALL_R 0x0300 /* Receive all messages though PM */ #define IW_POWER_FORCE_S 0x0400 /* Force PM procedure for sending unicast */ #define IW_POWER_REPEATER 0x0800 /* Repeat broadcast messages in PM period */ #define IW_POWER_MODIFIER 0x000F /* Modify a parameter */ #define IW_POWER_MIN 0x0001 /* Value is a minimum */ #define IW_POWER_MAX 0x0002 /* Value is a maximum */ #define IW_POWER_RELATIVE 0x0004 /* Value is not in seconds/ms/us */ /* Transmit Power flags available */ #define IW_TXPOW_TYPE 0x00FF /* Type of value */ #define IW_TXPOW_DBM 0x0000 /* Value is in dBm */ #define IW_TXPOW_MWATT 0x0001 /* Value is in mW */ #define IW_TXPOW_RELATIVE 0x0002 /* Value is in arbitrary units */ #define IW_TXPOW_RANGE 0x1000 /* Range of value between min/max */ /* Retry limits and lifetime flags available */ #define IW_RETRY_ON 0x0000 /* No details... */ #define IW_RETRY_TYPE 0xF000 /* Type of parameter */ #define IW_RETRY_LIMIT 0x1000 /* Maximum number of retries*/ #define IW_RETRY_LIFETIME 0x2000 /* Maximum duration of retries in us */ #define IW_RETRY_MODIFIER 0x00FF /* Modify a parameter */ #define IW_RETRY_MIN 0x0001 /* Value is a minimum */ #define IW_RETRY_MAX 0x0002 /* Value is a maximum */ #define IW_RETRY_RELATIVE 0x0004 /* Value is not in seconds/ms/us */ #define IW_RETRY_SHORT 0x0010 /* Value is for short packets */ #define IW_RETRY_LONG 0x0020 /* Value is for long packets */ /* Scanning request flags */ #define IW_SCAN_DEFAULT 0x0000 /* Default scan of the driver */ #define IW_SCAN_ALL_ESSID 0x0001 /* Scan all ESSIDs */ #define IW_SCAN_THIS_ESSID 0x0002 /* Scan only this ESSID */ #define IW_SCAN_ALL_FREQ 0x0004 /* Scan all Frequencies */ #define IW_SCAN_THIS_FREQ 0x0008 /* Scan only this Frequency */ #define IW_SCAN_ALL_MODE 0x0010 /* Scan all Modes */ #define IW_SCAN_THIS_MODE 0x0020 /* Scan only this Mode */ #define IW_SCAN_ALL_RATE 0x0040 /* Scan all Bit-Rates */ #define IW_SCAN_THIS_RATE 0x0080 /* Scan only this Bit-Rate */ /* struct iw_scan_req scan_type */ #define IW_SCAN_TYPE_ACTIVE 0 #define IW_SCAN_TYPE_PASSIVE 1 /* Maximum size of returned data */ #define IW_SCAN_MAX_DATA 4096 /* In bytes */ /* Scan capability flags - in (struct iw_range *)->scan_capa */ #define IW_SCAN_CAPA_NONE 0x00 #define IW_SCAN_CAPA_ESSID 0x01 #define IW_SCAN_CAPA_BSSID 0x02 #define IW_SCAN_CAPA_CHANNEL 0x04 #define IW_SCAN_CAPA_MODE 0x08 #define IW_SCAN_CAPA_RATE 0x10 #define IW_SCAN_CAPA_TYPE 0x20 #define IW_SCAN_CAPA_TIME 0x40 /* Max number of char in custom event - use multiple of them if needed */ #define IW_CUSTOM_MAX 256 /* In bytes */ /* Generic information element */ #define IW_GENERIC_IE_MAX 1024 /* MLME requests (SIOCSIWMLME / struct iw_mlme) */ #define IW_MLME_DEAUTH 0 #define IW_MLME_DISASSOC 1 #define IW_MLME_AUTH 2 #define IW_MLME_ASSOC 3 /* SIOCSIWAUTH/SIOCGIWAUTH struct iw_param flags */ #define IW_AUTH_INDEX 0x0FFF #define IW_AUTH_FLAGS 0xF000 /* SIOCSIWAUTH/SIOCGIWAUTH parameters (0 .. 4095) * (IW_AUTH_INDEX mask in struct iw_param flags; this is the index of the * parameter that is being set/get to; value will be read/written to * struct iw_param value field) */ #define IW_AUTH_WPA_VERSION 0 #define IW_AUTH_CIPHER_PAIRWISE 1 #define IW_AUTH_CIPHER_GROUP 2 #define IW_AUTH_KEY_MGMT 3 #define IW_AUTH_TKIP_COUNTERMEASURES 4 #define IW_AUTH_DROP_UNENCRYPTED 5 #define IW_AUTH_80211_AUTH_ALG 6 #define IW_AUTH_WPA_ENABLED 7 #define IW_AUTH_RX_UNENCRYPTED_EAPOL 8 #define IW_AUTH_ROAMING_CONTROL 9 #define IW_AUTH_PRIVACY_INVOKED 10 #define IW_AUTH_CIPHER_GROUP_MGMT 11 #define IW_AUTH_MFP 12 /* IW_AUTH_WPA_VERSION values (bit field) */ #define IW_AUTH_WPA_VERSION_DISABLED 0x00000001 #define IW_AUTH_WPA_VERSION_WPA 0x00000002 #define IW_AUTH_WPA_VERSION_WPA2 0x00000004 /* IW_AUTH_PAIRWISE_CIPHER, IW_AUTH_GROUP_CIPHER, and IW_AUTH_CIPHER_GROUP_MGMT * values (bit field) */ #define IW_AUTH_CIPHER_NONE 0x00000001 #define IW_AUTH_CIPHER_WEP40 0x00000002 #define IW_AUTH_CIPHER_TKIP 0x00000004 #define IW_AUTH_CIPHER_CCMP 0x00000008 #define IW_AUTH_CIPHER_WEP104 0x00000010 #define IW_AUTH_CIPHER_AES_CMAC 0x00000020 /* IW_AUTH_KEY_MGMT values (bit field) */ #define IW_AUTH_KEY_MGMT_802_1X 1 #define IW_AUTH_KEY_MGMT_PSK 2 /* IW_AUTH_80211_AUTH_ALG values (bit field) */ #define IW_AUTH_ALG_OPEN_SYSTEM 0x00000001 #define IW_AUTH_ALG_SHARED_KEY 0x00000002 #define IW_AUTH_ALG_LEAP 0x00000004 /* IW_AUTH_ROAMING_CONTROL values */ #define IW_AUTH_ROAMING_ENABLE 0 /* driver/firmware based roaming */ #define IW_AUTH_ROAMING_DISABLE 1 /* user space program used for roaming * control */ /* IW_AUTH_MFP (management frame protection) values */ #define IW_AUTH_MFP_DISABLED 0 /* MFP disabled */ #define IW_AUTH_MFP_OPTIONAL 1 /* MFP optional */ #define IW_AUTH_MFP_REQUIRED 2 /* MFP required */ /* SIOCSIWENCODEEXT definitions */ #define IW_ENCODE_SEQ_MAX_SIZE 8 /* struct iw_encode_ext ->alg */ #define IW_ENCODE_ALG_NONE 0 #define IW_ENCODE_ALG_WEP 1 #define IW_ENCODE_ALG_TKIP 2 #define IW_ENCODE_ALG_CCMP 3 #define IW_ENCODE_ALG_PMK 4 #define IW_ENCODE_ALG_AES_CMAC 5 /* struct iw_encode_ext ->ext_flags */ #define IW_ENCODE_EXT_TX_SEQ_VALID 0x00000001 #define IW_ENCODE_EXT_RX_SEQ_VALID 0x00000002 #define IW_ENCODE_EXT_GROUP_KEY 0x00000004 #define IW_ENCODE_EXT_SET_TX_KEY 0x00000008 /* IWEVMICHAELMICFAILURE : struct iw_michaelmicfailure ->flags */ #define IW_MICFAILURE_KEY_ID 0x00000003 /* Key ID 0..3 */ #define IW_MICFAILURE_GROUP 0x00000004 #define IW_MICFAILURE_PAIRWISE 0x00000008 #define IW_MICFAILURE_STAKEY 0x00000010 #define IW_MICFAILURE_COUNT 0x00000060 /* 1 or 2 (0 = count not supported) */ /* Bit field values for enc_capa in struct iw_range */ #define IW_ENC_CAPA_WPA 0x00000001 #define IW_ENC_CAPA_WPA2 0x00000002 #define IW_ENC_CAPA_CIPHER_TKIP 0x00000004 #define IW_ENC_CAPA_CIPHER_CCMP 0x00000008 #define IW_ENC_CAPA_4WAY_HANDSHAKE 0x00000010 /* Event capability macros - in (struct iw_range *)->event_capa * Because we have more than 32 possible events, we use an array of * 32 bit bitmasks. Note : 32 bits = 0x20 = 2^5. */ #define IW_EVENT_CAPA_BASE(cmd) ((cmd >= SIOCIWFIRSTPRIV) ? \ (cmd - SIOCIWFIRSTPRIV + 0x60) : \ (cmd - SIOCIWFIRST)) #define IW_EVENT_CAPA_INDEX(cmd) (IW_EVENT_CAPA_BASE(cmd) >> 5) #define IW_EVENT_CAPA_MASK(cmd) (1 << (IW_EVENT_CAPA_BASE(cmd) & 0x1F)) /* Event capability constants - event autogenerated by the kernel * This list is valid for most 802.11 devices, customise as needed... */ #define IW_EVENT_CAPA_K_0 (IW_EVENT_CAPA_MASK(0x8B04) | \ IW_EVENT_CAPA_MASK(0x8B06) | \ IW_EVENT_CAPA_MASK(0x8B1A)) #define IW_EVENT_CAPA_K_1 (IW_EVENT_CAPA_MASK(0x8B2A)) /* "Easy" macro to set events in iw_range (less efficient) */ #define IW_EVENT_CAPA_SET(event_capa, cmd) (event_capa[IW_EVENT_CAPA_INDEX(cmd)] |= IW_EVENT_CAPA_MASK(cmd)) #define IW_EVENT_CAPA_SET_KERNEL(event_capa) {event_capa[0] |= IW_EVENT_CAPA_K_0; event_capa[1] |= IW_EVENT_CAPA_K_1; } /****************************** TYPES ******************************/ /* --------------------------- SUBTYPES --------------------------- */ /* * Generic format for most parameters that fit in an int */ struct iw_param { __s32 value; /* The value of the parameter itself */ __u8 fixed; /* Hardware should not use auto select */ __u8 disabled; /* Disable the feature */ __u16 flags; /* Various specifc flags (if any) */ }; /* * For all data larger than 16 octets, we need to use a * pointer to memory allocated in user space. */ struct iw_point { void *pointer; /* Pointer to the data (in user space) */ __u16 length; /* number of fields or size in bytes */ __u16 flags; /* Optional params */ }; /* * A frequency * For numbers lower than 10^9, we encode the number in 'm' and * set 'e' to 0 * For number greater than 10^9, we divide it by the lowest power * of 10 to get 'm' lower than 10^9, with 'm'= f / (10^'e')... * The power of 10 is in 'e', the result of the division is in 'm'. */ struct iw_freq { __s32 m; /* Mantissa */ __s16 e; /* Exponent */ __u8 i; /* List index (when in range struct) */ __u8 flags; /* Flags (fixed/auto) */ }; /* * Quality of the link */ struct iw_quality { __u8 qual; /* link quality (%retries, SNR, %missed beacons or better...) */ __u8 level; /* signal level (dBm) */ __u8 noise; /* noise level (dBm) */ __u8 updated; /* Flags to know if updated */ }; /* * Packet discarded in the wireless adapter due to * "wireless" specific problems... * Note : the list of counter and statistics in net_device_stats * is already pretty exhaustive, and you should use that first. * This is only additional stats... */ struct iw_discarded { __u32 nwid; /* Rx : Wrong nwid/essid */ __u32 code; /* Rx : Unable to code/decode (WEP) */ __u32 fragment; /* Rx : Can't perform MAC reassembly */ __u32 retries; /* Tx : Max MAC retries num reached */ __u32 misc; /* Others cases */ }; /* * Packet/Time period missed in the wireless adapter due to * "wireless" specific problems... */ struct iw_missed { __u32 beacon; /* Missed beacons/superframe */ }; /* * Quality range (for spy threshold) */ struct iw_thrspy { struct sockaddr addr; /* Source address (hw/mac) */ struct iw_quality qual; /* Quality of the link */ struct iw_quality low; /* Low threshold */ struct iw_quality high; /* High threshold */ }; /* * Optional data for scan request * * Note: these optional parameters are controlling parameters for the * scanning behavior, these do not apply to getting scan results * (SIOCGIWSCAN). Drivers are expected to keep a local BSS table and * provide a merged results with all BSSes even if the previous scan * request limited scanning to a subset, e.g., by specifying an SSID. * Especially, scan results are required to include an entry for the * current BSS if the driver is in Managed mode and associated with an AP. */ struct iw_scan_req { __u8 scan_type; /* IW_SCAN_TYPE_{ACTIVE,PASSIVE} */ __u8 essid_len; __u8 num_channels; /* num entries in channel_list; * 0 = scan all allowed channels */ __u8 flags; /* reserved as padding; use zero, this may * be used in the future for adding flags * to request different scan behavior */ struct sockaddr bssid; /* ff:ff:ff:ff:ff:ff for broadcast BSSID or * individual address of a specific BSS */ /* * Use this ESSID if IW_SCAN_THIS_ESSID flag is used instead of using * the current ESSID. This allows scan requests for specific ESSID * without having to change the current ESSID and potentially breaking * the current association. */ __u8 essid[IW_ESSID_MAX_SIZE]; /* * Optional parameters for changing the default scanning behavior. * These are based on the MLME-SCAN.request from IEEE Std 802.11. * TU is 1.024 ms. If these are set to 0, driver is expected to use * reasonable default values. min_channel_time defines the time that * will be used to wait for the first reply on each channel. If no * replies are received, next channel will be scanned after this. If * replies are received, total time waited on the channel is defined by * max_channel_time. */ __u32 min_channel_time; /* in TU */ __u32 max_channel_time; /* in TU */ struct iw_freq channel_list[IW_MAX_FREQUENCIES]; }; /* ------------------------- WPA SUPPORT ------------------------- */ /* * Extended data structure for get/set encoding (this is used with * SIOCSIWENCODEEXT/SIOCGIWENCODEEXT. struct iw_point and IW_ENCODE_* * flags are used in the same way as with SIOCSIWENCODE/SIOCGIWENCODE and * only the data contents changes (key data -> this structure, including * key data). * * If the new key is the first group key, it will be set as the default * TX key. Otherwise, default TX key index is only changed if * IW_ENCODE_EXT_SET_TX_KEY flag is set. * * Key will be changed with SIOCSIWENCODEEXT in all cases except for * special "change TX key index" operation which is indicated by setting * key_len = 0 and ext_flags |= IW_ENCODE_EXT_SET_TX_KEY. * * tx_seq/rx_seq are only used when respective * IW_ENCODE_EXT_{TX,RX}_SEQ_VALID flag is set in ext_flags. Normal * TKIP/CCMP operation is to set RX seq with SIOCSIWENCODEEXT and start * TX seq from zero whenever key is changed. SIOCGIWENCODEEXT is normally * used only by an Authenticator (AP or an IBSS station) to get the * current TX sequence number. Using TX_SEQ_VALID for SIOCSIWENCODEEXT and * RX_SEQ_VALID for SIOCGIWENCODEEXT are optional, but can be useful for * debugging/testing. */ struct iw_encode_ext { __u32 ext_flags; /* IW_ENCODE_EXT_* */ __u8 tx_seq[IW_ENCODE_SEQ_MAX_SIZE]; /* LSB first */ __u8 rx_seq[IW_ENCODE_SEQ_MAX_SIZE]; /* LSB first */ struct sockaddr addr; /* ff:ff:ff:ff:ff:ff for broadcast/multicast * (group) keys or unicast address for * individual keys */ __u16 alg; /* IW_ENCODE_ALG_* */ __u16 key_len; __u8 key[0]; }; /* SIOCSIWMLME data */ struct iw_mlme { __u16 cmd; /* IW_MLME_* */ __u16 reason_code; struct sockaddr addr; }; /* SIOCSIWPMKSA data */ #define IW_PMKSA_ADD 1 #define IW_PMKSA_REMOVE 2 #define IW_PMKSA_FLUSH 3 #define IW_PMKID_LEN 16 struct iw_pmksa { __u32 cmd; /* IW_PMKSA_* */ struct sockaddr bssid; __u8 pmkid[IW_PMKID_LEN]; }; /* IWEVMICHAELMICFAILURE data */ struct iw_michaelmicfailure { __u32 flags; struct sockaddr src_addr; __u8 tsc[IW_ENCODE_SEQ_MAX_SIZE]; /* LSB first */ }; /* IWEVPMKIDCAND data */ #define IW_PMKID_CAND_PREAUTH 0x00000001 /* RNS pre-authentication enabled */ struct iw_pmkid_cand { __u32 flags; /* IW_PMKID_CAND_* */ __u32 index; /* the smaller the index, the higher the * priority */ struct sockaddr bssid; }; /* ------------------------ WIRELESS STATS ------------------------ */ /* * Wireless statistics (used for /proc/net/wireless) */ struct iw_statistics { __u16 status; /* Status * - device dependent for now */ struct iw_quality qual; /* Quality of the link * (instant/mean/max) */ struct iw_discarded discard; /* Packet discarded counts */ struct iw_missed miss; /* Packet missed counts */ }; /* ------------------------ IOCTL REQUEST ------------------------ */ /* * This structure defines the payload of an ioctl, and is used * below. * * Note that this structure should fit on the memory footprint * of iwreq (which is the same as ifreq), which mean a max size of * 16 octets = 128 bits. Warning, pointers might be 64 bits wide... * You should check this when increasing the structures defined * above in this file... */ union iwreq_data { /* Config - generic */ char name[IFNAMSIZ]; /* Name : used to verify the presence of wireless extensions. * Name of the protocol/provider... */ struct iw_point essid; /* Extended network name */ struct iw_param nwid; /* network id (or domain - the cell) */ struct iw_freq freq; /* frequency or channel : * 0-1000 = channel * > 1000 = frequency in Hz */ struct iw_param sens; /* signal level threshold */ struct iw_param bitrate; /* default bit rate */ struct iw_param txpower; /* default transmit power */ struct iw_param rts; /* RTS threshold */ struct iw_param frag; /* Fragmentation threshold */ __u32 mode; /* Operation mode */ struct iw_param retry; /* Retry limits & lifetime */ struct iw_point encoding; /* Encoding stuff : tokens */ struct iw_param power; /* PM duration/timeout */ struct iw_quality qual; /* Quality part of statistics */ struct sockaddr ap_addr; /* Access point address */ struct sockaddr addr; /* Destination address (hw/mac) */ struct iw_param param; /* Other small parameters */ struct iw_point data; /* Other large parameters */ }; /* * The structure to exchange data for ioctl. * This structure is the same as 'struct ifreq', but (re)defined for * convenience... * Do I need to remind you about structure size (32 octets) ? */ struct iwreq { union { char ifrn_name[IFNAMSIZ]; /* if name, e.g. "eth0" */ } ifr_ifrn; /* Data part (defined just above) */ union iwreq_data u; }; /* -------------------------- IOCTL DATA -------------------------- */ /* * For those ioctl which want to exchange mode data that what could * fit in the above structure... */ /* * Range of parameters */ struct iw_range { /* Informative stuff (to choose between different interface) */ __u32 throughput; /* To give an idea... */ /* In theory this value should be the maximum benchmarked * TCP/IP throughput, because with most of these devices the * bit rate is meaningless (overhead an co) to estimate how * fast the connection will go and pick the fastest one. * I suggest people to play with Netperf or any benchmark... */ /* NWID (or domain id) */ __u32 min_nwid; /* Minimal NWID we are able to set */ __u32 max_nwid; /* Maximal NWID we are able to set */ /* Old Frequency (backward compat - moved lower ) */ __u16 old_num_channels; __u8 old_num_frequency; /* Scan capabilities */ __u8 scan_capa; /* IW_SCAN_CAPA_* bit field */ /* Wireless event capability bitmasks */ __u32 event_capa[6]; /* signal level threshold range */ __s32 sensitivity; /* Quality of link & SNR stuff */ /* Quality range (link, level, noise) * If the quality is absolute, it will be in the range [0 ; max_qual], * if the quality is dBm, it will be in the range [max_qual ; 0]. * Don't forget that we use 8 bit arithmetics... */ struct iw_quality max_qual; /* Quality of the link */ /* This should contain the average/typical values of the quality * indicator. This should be the threshold between a "good" and * a "bad" link (example : monitor going from green to orange). * Currently, user space apps like quality monitors don't have any * way to calibrate the measurement. With this, they can split * the range between 0 and max_qual in different quality level * (using a geometric subdivision centered on the average). * I expect that people doing the user space apps will feedback * us on which value we need to put in each driver... */ struct iw_quality avg_qual; /* Quality of the link */ /* Rates */ __u8 num_bitrates; /* Number of entries in the list */ __s32 bitrate[IW_MAX_BITRATES]; /* list, in bps */ /* RTS threshold */ __s32 min_rts; /* Minimal RTS threshold */ __s32 max_rts; /* Maximal RTS threshold */ /* Frag threshold */ __s32 min_frag; /* Minimal frag threshold */ __s32 max_frag; /* Maximal frag threshold */ /* Power Management duration & timeout */ __s32 min_pmp; /* Minimal PM period */ __s32 max_pmp; /* Maximal PM period */ __s32 min_pmt; /* Minimal PM timeout */ __s32 max_pmt; /* Maximal PM timeout */ __u16 pmp_flags; /* How to decode max/min PM period */ __u16 pmt_flags; /* How to decode max/min PM timeout */ __u16 pm_capa; /* What PM options are supported */ /* Encoder stuff */ __u16 encoding_size[IW_MAX_ENCODING_SIZES]; /* Different token sizes */ __u8 num_encoding_sizes; /* Number of entry in the list */ __u8 max_encoding_tokens; /* Max number of tokens */ /* For drivers that need a "login/passwd" form */ __u8 encoding_login_index; /* token index for login token */ /* Transmit power */ __u16 txpower_capa; /* What options are supported */ __u8 num_txpower; /* Number of entries in the list */ __s32 txpower[IW_MAX_TXPOWER]; /* list, in bps */ /* Wireless Extension version info */ __u8 we_version_compiled; /* Must be WIRELESS_EXT */ __u8 we_version_source; /* Last update of source */ /* Retry limits and lifetime */ __u16 retry_capa; /* What retry options are supported */ __u16 retry_flags; /* How to decode max/min retry limit */ __u16 r_time_flags; /* How to decode max/min retry life */ __s32 min_retry; /* Minimal number of retries */ __s32 max_retry; /* Maximal number of retries */ __s32 min_r_time; /* Minimal retry lifetime */ __s32 max_r_time; /* Maximal retry lifetime */ /* Frequency */ __u16 num_channels; /* Number of channels [0; num - 1] */ __u8 num_frequency; /* Number of entry in the list */ struct iw_freq freq[IW_MAX_FREQUENCIES]; /* list */ /* Note : this frequency list doesn't need to fit channel numbers, * because each entry contain its channel index */ __u32 enc_capa; /* IW_ENC_CAPA_* bit field */ }; /* * Private ioctl interface information */ struct iw_priv_args { __u32 cmd; /* Number of the ioctl to issue */ __u16 set_args; /* Type and number of args */ __u16 get_args; /* Type and number of args */ char name[IFNAMSIZ]; /* Name of the extension */ }; /* ----------------------- WIRELESS EVENTS ----------------------- */ /* * Wireless events are carried through the rtnetlink socket to user * space. They are encapsulated in the IFLA_WIRELESS field of * a RTM_NEWLINK message. */ /* * A Wireless Event. Contains basically the same data as the ioctl... */ struct iw_event { __u16 len; /* Real length of this stuff */ __u16 cmd; /* Wireless IOCTL */ union iwreq_data u; /* IOCTL fixed payload */ }; /* Size of the Event prefix (including padding and alignement junk) */ #define IW_EV_LCP_LEN (sizeof(struct iw_event) - sizeof(union iwreq_data)) /* Size of the various events */ #define IW_EV_CHAR_LEN (IW_EV_LCP_LEN + IFNAMSIZ) #define IW_EV_UINT_LEN (IW_EV_LCP_LEN + sizeof(__u32)) #define IW_EV_FREQ_LEN (IW_EV_LCP_LEN + sizeof(struct iw_freq)) #define IW_EV_PARAM_LEN (IW_EV_LCP_LEN + sizeof(struct iw_param)) #define IW_EV_ADDR_LEN (IW_EV_LCP_LEN + sizeof(struct sockaddr)) #define IW_EV_QUAL_LEN (IW_EV_LCP_LEN + sizeof(struct iw_quality)) /* iw_point events are special. First, the payload (extra data) come at * the end of the event, so they are bigger than IW_EV_POINT_LEN. Second, * we omit the pointer, so start at an offset. */ #define IW_EV_POINT_OFF (((char *) &(((struct iw_point *) NULL)->length)) - \ (char *) NULL) #define IW_EV_POINT_LEN (IW_EV_LCP_LEN + sizeof(struct iw_point) - \ IW_EV_POINT_OFF) /* Size of the Event prefix when packed in stream */ #define IW_EV_LCP_PK_LEN (4) /* Size of the various events when packed in stream */ #define IW_EV_CHAR_PK_LEN (IW_EV_LCP_PK_LEN + IFNAMSIZ) #define IW_EV_UINT_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(__u32)) #define IW_EV_FREQ_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct iw_freq)) #define IW_EV_PARAM_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct iw_param)) #define IW_EV_ADDR_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct sockaddr)) #define IW_EV_QUAL_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct iw_quality)) #define IW_EV_POINT_PK_LEN (IW_EV_LCP_PK_LEN + 4) #endif /* _LINUX_WIRELESS_H */ linux/atmarp.h000064400000002420151027430560007341 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atmarp.h - ATM ARP protocol and kernel-demon interface definitions */ /* Written 1995-1999 by Werner Almesberger, EPFL LRC/ICA */ #ifndef _LINUX_ATMARP_H #define _LINUX_ATMARP_H #include #include #include #define ATMARP_RETRY_DELAY 30 /* request next resolution or forget NAK after 30 sec - should go into atmclip.h */ #define ATMARP_MAX_UNRES_PACKETS 5 /* queue that many packets while waiting for the resolver */ #define ATMARPD_CTRL _IO('a',ATMIOC_CLIP+1) /* become atmarpd ctrl sock */ #define ATMARP_MKIP _IO('a',ATMIOC_CLIP+2) /* attach socket to IP */ #define ATMARP_SETENTRY _IO('a',ATMIOC_CLIP+3) /* fill or hide ARP entry */ #define ATMARP_ENCAP _IO('a',ATMIOC_CLIP+5) /* change encapsulation */ enum atmarp_ctrl_type { act_invalid, /* catch uninitialized structures */ act_need, /* need address resolution */ act_up, /* interface is coming up */ act_down, /* interface is going down */ act_change /* interface configuration has changed */ }; struct atmarp_ctrl { enum atmarp_ctrl_type type; /* message type */ int itf_num;/* interface number (if present) */ __be32 ip; /* IP address (act_need only) */ }; #endif linux/seg6_genl.h000064400000001115151027430560007726 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_SEG6_GENL_H #define _LINUX_SEG6_GENL_H #define SEG6_GENL_NAME "SEG6" #define SEG6_GENL_VERSION 0x1 enum { SEG6_ATTR_UNSPEC, SEG6_ATTR_DST, SEG6_ATTR_DSTLEN, SEG6_ATTR_HMACKEYID, SEG6_ATTR_SECRET, SEG6_ATTR_SECRETLEN, SEG6_ATTR_ALGID, SEG6_ATTR_HMACINFO, __SEG6_ATTR_MAX, }; #define SEG6_ATTR_MAX (__SEG6_ATTR_MAX - 1) enum { SEG6_CMD_UNSPEC, SEG6_CMD_SETHMAC, SEG6_CMD_DUMPHMAC, SEG6_CMD_SET_TUNSRC, SEG6_CMD_GET_TUNSRC, __SEG6_CMD_MAX, }; #define SEG6_CMD_MAX (__SEG6_CMD_MAX - 1) #endif linux/fuse.h000064400000055661151027430560007036 0ustar00/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-2-Clause) */ /* This file defines the kernel interface of FUSE Copyright (C) 2001-2008 Miklos Szeredi This program can be distributed under the terms of the GNU GPL. See the file COPYING. This -- and only this -- header file may also be distributed under the terms of the BSD Licence as follows: Copyright (C) 2001-2007 Miklos Szeredi. 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. THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This file defines the kernel interface of FUSE * * Protocol changelog: * * 7.1: * - add the following messages: * FUSE_SETATTR, FUSE_SYMLINK, FUSE_MKNOD, FUSE_MKDIR, FUSE_UNLINK, * FUSE_RMDIR, FUSE_RENAME, FUSE_LINK, FUSE_OPEN, FUSE_READ, FUSE_WRITE, * FUSE_RELEASE, FUSE_FSYNC, FUSE_FLUSH, FUSE_SETXATTR, FUSE_GETXATTR, * FUSE_LISTXATTR, FUSE_REMOVEXATTR, FUSE_OPENDIR, FUSE_READDIR, * FUSE_RELEASEDIR * - add padding to messages to accommodate 32-bit servers on 64-bit kernels * * 7.2: * - add FOPEN_DIRECT_IO and FOPEN_KEEP_CACHE flags * - add FUSE_FSYNCDIR message * * 7.3: * - add FUSE_ACCESS message * - add FUSE_CREATE message * - add filehandle to fuse_setattr_in * * 7.4: * - add frsize to fuse_kstatfs * - clean up request size limit checking * * 7.5: * - add flags and max_write to fuse_init_out * * 7.6: * - add max_readahead to fuse_init_in and fuse_init_out * * 7.7: * - add FUSE_INTERRUPT message * - add POSIX file lock support * * 7.8: * - add lock_owner and flags fields to fuse_release_in * - add FUSE_BMAP message * - add FUSE_DESTROY message * * 7.9: * - new fuse_getattr_in input argument of GETATTR * - add lk_flags in fuse_lk_in * - add lock_owner field to fuse_setattr_in, fuse_read_in and fuse_write_in * - add blksize field to fuse_attr * - add file flags field to fuse_read_in and fuse_write_in * - Add ATIME_NOW and MTIME_NOW flags to fuse_setattr_in * * 7.10 * - add nonseekable open flag * * 7.11 * - add IOCTL message * - add unsolicited notification support * - add POLL message and NOTIFY_POLL notification * * 7.12 * - add umask flag to input argument of create, mknod and mkdir * - add notification messages for invalidation of inodes and * directory entries * * 7.13 * - make max number of background requests and congestion threshold * tunables * * 7.14 * - add splice support to fuse device * * 7.15 * - add store notify * - add retrieve notify * * 7.16 * - add BATCH_FORGET request * - FUSE_IOCTL_UNRESTRICTED shall now return with array of 'struct * fuse_ioctl_iovec' instead of ambiguous 'struct iovec' * - add FUSE_IOCTL_32BIT flag * * 7.17 * - add FUSE_FLOCK_LOCKS and FUSE_RELEASE_FLOCK_UNLOCK * * 7.18 * - add FUSE_IOCTL_DIR flag * - add FUSE_NOTIFY_DELETE * * 7.19 * - add FUSE_FALLOCATE * * 7.20 * - add FUSE_AUTO_INVAL_DATA * * 7.21 * - add FUSE_READDIRPLUS * - send the requested events in POLL request * * 7.22 * - add FUSE_ASYNC_DIO * * 7.23 * - add FUSE_WRITEBACK_CACHE * - add time_gran to fuse_init_out * - add reserved space to fuse_init_out * - add FATTR_CTIME * - add ctime and ctimensec to fuse_setattr_in * - add FUSE_RENAME2 request * - add FUSE_NO_OPEN_SUPPORT flag * * 7.24 * - add FUSE_LSEEK for SEEK_HOLE and SEEK_DATA support * * 7.25 * - add FUSE_PARALLEL_DIROPS * * 7.26 * - add FUSE_HANDLE_KILLPRIV * - add FUSE_POSIX_ACL * * 7.27 * - add FUSE_ABORT_ERROR * * 7.28 * - add FUSE_COPY_FILE_RANGE * - add FOPEN_CACHE_DIR * - add FUSE_MAX_PAGES, add max_pages to init_out * - add FUSE_CACHE_SYMLINKS * * 7.29 * - add FUSE_NO_OPENDIR_SUPPORT flag * * 7.30 * - add FUSE_EXPLICIT_INVAL_DATA * - add FUSE_IOCTL_COMPAT_X32 * * 7.31 * - add FUSE_WRITE_KILL_PRIV flag * - add FUSE_SETUPMAPPING and FUSE_REMOVEMAPPING * - add map_alignment to fuse_init_out, add FUSE_MAP_ALIGNMENT flag * * 7.32 * - add flags to fuse_attr, add FUSE_ATTR_SUBMOUNT, add FUSE_SUBMOUNTS * * 7.33 * - add FUSE_HANDLE_KILLPRIV_V2, FUSE_WRITE_KILL_SUIDGID, FATTR_KILL_SUIDGID * - add FUSE_OPEN_KILL_SUIDGID * - extend fuse_setxattr_in, add FUSE_SETXATTR_EXT * - add FUSE_SETXATTR_ACL_KILL_SGID * - add FUSE_EXPIRE_ONLY flag to fuse_notify_inval_entry * - add FUSE_HAS_EXPIRE_ONLY * * 7.34 * - add FUSE_SYNCFS */ #ifndef _LINUX_FUSE_H #define _LINUX_FUSE_H #include /* * Version negotiation: * * Both the kernel and userspace send the version they support in the * INIT request and reply respectively. * * If the major versions match then both shall use the smallest * of the two minor versions for communication. * * If the kernel supports a larger major version, then userspace shall * reply with the major version it supports, ignore the rest of the * INIT message and expect a new INIT message from the kernel with a * matching major version. * * If the library supports a larger major version, then it shall fall * back to the major protocol version sent by the kernel for * communication and reply with that major version (and an arbitrary * supported minor version). */ /** Version number of this interface */ #define FUSE_KERNEL_VERSION 7 /** Minor version number of this interface */ #define FUSE_KERNEL_MINOR_VERSION 34 /** The node ID of the root inode */ #define FUSE_ROOT_ID 1 /* Make sure all structures are padded to 64bit boundary, so 32bit userspace works under 64bit kernels */ struct fuse_attr { uint64_t ino; uint64_t size; uint64_t blocks; uint64_t atime; uint64_t mtime; uint64_t ctime; uint32_t atimensec; uint32_t mtimensec; uint32_t ctimensec; uint32_t mode; uint32_t nlink; uint32_t uid; uint32_t gid; uint32_t rdev; uint32_t blksize; uint32_t flags; }; struct fuse_kstatfs { uint64_t blocks; uint64_t bfree; uint64_t bavail; uint64_t files; uint64_t ffree; uint32_t bsize; uint32_t namelen; uint32_t frsize; uint32_t padding; uint32_t spare[6]; }; struct fuse_file_lock { uint64_t start; uint64_t end; uint32_t type; uint32_t pid; /* tgid */ }; /** * Bitmasks for fuse_setattr_in.valid */ #define FATTR_MODE (1 << 0) #define FATTR_UID (1 << 1) #define FATTR_GID (1 << 2) #define FATTR_SIZE (1 << 3) #define FATTR_ATIME (1 << 4) #define FATTR_MTIME (1 << 5) #define FATTR_FH (1 << 6) #define FATTR_ATIME_NOW (1 << 7) #define FATTR_MTIME_NOW (1 << 8) #define FATTR_LOCKOWNER (1 << 9) #define FATTR_CTIME (1 << 10) #define FATTR_KILL_SUIDGID (1 << 11) /** * Flags returned by the OPEN request * * FOPEN_DIRECT_IO: bypass page cache for this open file * FOPEN_KEEP_CACHE: don't invalidate the data cache on open * FOPEN_NONSEEKABLE: the file is not seekable * FOPEN_CACHE_DIR: allow caching this directory */ #define FOPEN_DIRECT_IO (1 << 0) #define FOPEN_KEEP_CACHE (1 << 1) #define FOPEN_NONSEEKABLE (1 << 2) #define FOPEN_CACHE_DIR (1 << 3) /** * INIT request/reply flags * * FUSE_ASYNC_READ: asynchronous read requests * FUSE_POSIX_LOCKS: remote locking for POSIX file locks * FUSE_FILE_OPS: kernel sends file handle for fstat, etc... (not yet supported) * FUSE_ATOMIC_O_TRUNC: handles the O_TRUNC open flag in the filesystem * FUSE_EXPORT_SUPPORT: filesystem handles lookups of "." and ".." * FUSE_BIG_WRITES: filesystem can handle write size larger than 4kB * FUSE_DONT_MASK: don't apply umask to file mode on create operations * FUSE_SPLICE_WRITE: kernel supports splice write on the device * FUSE_SPLICE_MOVE: kernel supports splice move on the device * FUSE_SPLICE_READ: kernel supports splice read on the device * FUSE_FLOCK_LOCKS: remote locking for BSD style file locks * FUSE_HAS_IOCTL_DIR: kernel supports ioctl on directories * FUSE_AUTO_INVAL_DATA: automatically invalidate cached pages * FUSE_DO_READDIRPLUS: do READDIRPLUS (READDIR+LOOKUP in one) * FUSE_READDIRPLUS_AUTO: adaptive readdirplus * FUSE_ASYNC_DIO: asynchronous direct I/O submission * FUSE_WRITEBACK_CACHE: use writeback cache for buffered writes * FUSE_NO_OPEN_SUPPORT: kernel supports zero-message opens * FUSE_PARALLEL_DIROPS: allow parallel lookups and readdir * FUSE_HANDLE_KILLPRIV: fs handles killing suid/sgid/cap on write/chown/trunc * FUSE_POSIX_ACL: filesystem supports posix acls * FUSE_ABORT_ERROR: reading the device after abort returns ECONNABORTED * FUSE_MAX_PAGES: init_out.max_pages contains the max number of req pages * FUSE_CACHE_SYMLINKS: cache READLINK responses * FUSE_NO_OPENDIR_SUPPORT: kernel supports zero-message opendir * FUSE_EXPLICIT_INVAL_DATA: only invalidate cached pages on explicit request * FUSE_MAP_ALIGNMENT: init_out.map_alignment contains log2(byte alignment) for * foffset and moffset fields in struct * fuse_setupmapping_out and fuse_removemapping_one. * FUSE_SUBMOUNTS: kernel supports auto-mounting directory submounts * FUSE_HANDLE_KILLPRIV_V2: fs kills suid/sgid/cap on write/chown/trunc. * Upon write/truncate suid/sgid is only killed if caller * does not have CAP_FSETID. Additionally upon * write/truncate sgid is killed only if file has group * execute permission. (Same as Linux VFS behavior). * FUSE_SETXATTR_EXT: Server supports extended struct fuse_setxattr_in * FUSE_INIT_EXT: extended fuse_init_in request * FUSE_INIT_RESERVED: reserved, do not use * FUSE_HAS_EXPIRE_ONLY: kernel supports expiry-only entry invalidation */ #define FUSE_ASYNC_READ (1 << 0) #define FUSE_POSIX_LOCKS (1 << 1) #define FUSE_FILE_OPS (1 << 2) #define FUSE_ATOMIC_O_TRUNC (1 << 3) #define FUSE_EXPORT_SUPPORT (1 << 4) #define FUSE_BIG_WRITES (1 << 5) #define FUSE_DONT_MASK (1 << 6) #define FUSE_SPLICE_WRITE (1 << 7) #define FUSE_SPLICE_MOVE (1 << 8) #define FUSE_SPLICE_READ (1 << 9) #define FUSE_FLOCK_LOCKS (1 << 10) #define FUSE_HAS_IOCTL_DIR (1 << 11) #define FUSE_AUTO_INVAL_DATA (1 << 12) #define FUSE_DO_READDIRPLUS (1 << 13) #define FUSE_READDIRPLUS_AUTO (1 << 14) #define FUSE_ASYNC_DIO (1 << 15) #define FUSE_WRITEBACK_CACHE (1 << 16) #define FUSE_NO_OPEN_SUPPORT (1 << 17) #define FUSE_PARALLEL_DIROPS (1 << 18) #define FUSE_HANDLE_KILLPRIV (1 << 19) #define FUSE_POSIX_ACL (1 << 20) #define FUSE_ABORT_ERROR (1 << 21) #define FUSE_MAX_PAGES (1 << 22) #define FUSE_CACHE_SYMLINKS (1 << 23) #define FUSE_NO_OPENDIR_SUPPORT (1 << 24) #define FUSE_EXPLICIT_INVAL_DATA (1 << 25) #define FUSE_MAP_ALIGNMENT (1 << 26) #define FUSE_SUBMOUNTS (1 << 27) #define FUSE_HANDLE_KILLPRIV_V2 (1 << 28) #define FUSE_SETXATTR_EXT (1 << 29) #define FUSE_INIT_EXT (1 << 30) #define FUSE_INIT_RESERVED (1 << 31) /* bits 32..63 get shifted down 32 bits into the flags2 field */ #define FUSE_HAS_EXPIRE_ONLY (1ULL << 35) /** * CUSE INIT request/reply flags * * CUSE_UNRESTRICTED_IOCTL: use unrestricted ioctl */ #define CUSE_UNRESTRICTED_IOCTL (1 << 0) /** * Release flags */ #define FUSE_RELEASE_FLUSH (1 << 0) #define FUSE_RELEASE_FLOCK_UNLOCK (1 << 1) /** * Getattr flags */ #define FUSE_GETATTR_FH (1 << 0) /** * Lock flags */ #define FUSE_LK_FLOCK (1 << 0) /** * WRITE flags * * FUSE_WRITE_CACHE: delayed write from page cache, file handle is guessed * FUSE_WRITE_LOCKOWNER: lock_owner field is valid * FUSE_WRITE_KILL_SUIDGID: kill suid and sgid bits */ #define FUSE_WRITE_CACHE (1 << 0) #define FUSE_WRITE_LOCKOWNER (1 << 1) #define FUSE_WRITE_KILL_SUIDGID (1 << 2) /* Obsolete alias; this flag implies killing suid/sgid only. */ #define FUSE_WRITE_KILL_PRIV FUSE_WRITE_KILL_SUIDGID /** * Read flags */ #define FUSE_READ_LOCKOWNER (1 << 1) /** * Ioctl flags * * FUSE_IOCTL_COMPAT: 32bit compat ioctl on 64bit machine * FUSE_IOCTL_UNRESTRICTED: not restricted to well-formed ioctls, retry allowed * FUSE_IOCTL_RETRY: retry with new iovecs * FUSE_IOCTL_32BIT: 32bit ioctl * FUSE_IOCTL_DIR: is a directory * FUSE_IOCTL_COMPAT_X32: x32 compat ioctl on 64bit machine (64bit time_t) * * FUSE_IOCTL_MAX_IOV: maximum of in_iovecs + out_iovecs */ #define FUSE_IOCTL_COMPAT (1 << 0) #define FUSE_IOCTL_UNRESTRICTED (1 << 1) #define FUSE_IOCTL_RETRY (1 << 2) #define FUSE_IOCTL_32BIT (1 << 3) #define FUSE_IOCTL_DIR (1 << 4) #define FUSE_IOCTL_COMPAT_X32 (1 << 5) #define FUSE_IOCTL_MAX_IOV 256 /** * Poll flags * * FUSE_POLL_SCHEDULE_NOTIFY: request poll notify */ #define FUSE_POLL_SCHEDULE_NOTIFY (1 << 0) /** * Fsync flags * * FUSE_FSYNC_FDATASYNC: Sync data only, not metadata */ #define FUSE_FSYNC_FDATASYNC (1 << 0) /** * fuse_attr flags * * FUSE_ATTR_SUBMOUNT: Object is a submount root */ #define FUSE_ATTR_SUBMOUNT (1 << 0) /** * Open flags * FUSE_OPEN_KILL_SUIDGID: Kill suid and sgid if executable */ #define FUSE_OPEN_KILL_SUIDGID (1 << 0) /** * setxattr flags * FUSE_SETXATTR_ACL_KILL_SGID: Clear SGID when system.posix_acl_access is set */ #define FUSE_SETXATTR_ACL_KILL_SGID (1 << 0) /** * notify_inval_entry flags * FUSE_EXPIRE_ONLY */ #define FUSE_EXPIRE_ONLY (1 << 0) enum fuse_opcode { FUSE_LOOKUP = 1, FUSE_FORGET = 2, /* no reply */ FUSE_GETATTR = 3, FUSE_SETATTR = 4, FUSE_READLINK = 5, FUSE_SYMLINK = 6, FUSE_MKNOD = 8, FUSE_MKDIR = 9, FUSE_UNLINK = 10, FUSE_RMDIR = 11, FUSE_RENAME = 12, FUSE_LINK = 13, FUSE_OPEN = 14, FUSE_READ = 15, FUSE_WRITE = 16, FUSE_STATFS = 17, FUSE_RELEASE = 18, FUSE_FSYNC = 20, FUSE_SETXATTR = 21, FUSE_GETXATTR = 22, FUSE_LISTXATTR = 23, FUSE_REMOVEXATTR = 24, FUSE_FLUSH = 25, FUSE_INIT = 26, FUSE_OPENDIR = 27, FUSE_READDIR = 28, FUSE_RELEASEDIR = 29, FUSE_FSYNCDIR = 30, FUSE_GETLK = 31, FUSE_SETLK = 32, FUSE_SETLKW = 33, FUSE_ACCESS = 34, FUSE_CREATE = 35, FUSE_INTERRUPT = 36, FUSE_BMAP = 37, FUSE_DESTROY = 38, FUSE_IOCTL = 39, FUSE_POLL = 40, FUSE_NOTIFY_REPLY = 41, FUSE_BATCH_FORGET = 42, FUSE_FALLOCATE = 43, FUSE_READDIRPLUS = 44, FUSE_RENAME2 = 45, FUSE_LSEEK = 46, FUSE_COPY_FILE_RANGE = 47, FUSE_SETUPMAPPING = 48, FUSE_REMOVEMAPPING = 49, FUSE_SYNCFS = 50, /* CUSE specific operations */ CUSE_INIT = 4096, /* Reserved opcodes: helpful to detect structure endian-ness */ CUSE_INIT_BSWAP_RESERVED = 1048576, /* CUSE_INIT << 8 */ FUSE_INIT_BSWAP_RESERVED = 436207616, /* FUSE_INIT << 24 */ }; enum fuse_notify_code { FUSE_NOTIFY_POLL = 1, FUSE_NOTIFY_INVAL_INODE = 2, FUSE_NOTIFY_INVAL_ENTRY = 3, FUSE_NOTIFY_STORE = 4, FUSE_NOTIFY_RETRIEVE = 5, FUSE_NOTIFY_DELETE = 6, FUSE_NOTIFY_CODE_MAX, }; /* The read buffer is required to be at least 8k, but may be much larger */ #define FUSE_MIN_READ_BUFFER 8192 #define FUSE_COMPAT_ENTRY_OUT_SIZE 120 struct fuse_entry_out { uint64_t nodeid; /* Inode ID */ uint64_t generation; /* Inode generation: nodeid:gen must be unique for the fs's lifetime */ uint64_t entry_valid; /* Cache timeout for the name */ uint64_t attr_valid; /* Cache timeout for the attributes */ uint32_t entry_valid_nsec; uint32_t attr_valid_nsec; struct fuse_attr attr; }; struct fuse_forget_in { uint64_t nlookup; }; struct fuse_forget_one { uint64_t nodeid; uint64_t nlookup; }; struct fuse_batch_forget_in { uint32_t count; uint32_t dummy; }; struct fuse_getattr_in { uint32_t getattr_flags; uint32_t dummy; uint64_t fh; }; #define FUSE_COMPAT_ATTR_OUT_SIZE 96 struct fuse_attr_out { uint64_t attr_valid; /* Cache timeout for the attributes */ uint32_t attr_valid_nsec; uint32_t dummy; struct fuse_attr attr; }; #define FUSE_COMPAT_MKNOD_IN_SIZE 8 struct fuse_mknod_in { uint32_t mode; uint32_t rdev; uint32_t umask; uint32_t padding; }; struct fuse_mkdir_in { uint32_t mode; uint32_t umask; }; struct fuse_rename_in { uint64_t newdir; }; struct fuse_rename2_in { uint64_t newdir; uint32_t flags; uint32_t padding; }; struct fuse_link_in { uint64_t oldnodeid; }; struct fuse_setattr_in { uint32_t valid; uint32_t padding; uint64_t fh; uint64_t size; uint64_t lock_owner; uint64_t atime; uint64_t mtime; uint64_t ctime; uint32_t atimensec; uint32_t mtimensec; uint32_t ctimensec; uint32_t mode; uint32_t unused4; uint32_t uid; uint32_t gid; uint32_t unused5; }; struct fuse_open_in { uint32_t flags; uint32_t open_flags; /* FUSE_OPEN_... */ }; struct fuse_create_in { uint32_t flags; uint32_t mode; uint32_t umask; uint32_t open_flags; /* FUSE_OPEN_... */ }; struct fuse_open_out { uint64_t fh; uint32_t open_flags; uint32_t padding; }; struct fuse_release_in { uint64_t fh; uint32_t flags; uint32_t release_flags; uint64_t lock_owner; }; struct fuse_flush_in { uint64_t fh; uint32_t unused; uint32_t padding; uint64_t lock_owner; }; struct fuse_read_in { uint64_t fh; uint64_t offset; uint32_t size; uint32_t read_flags; uint64_t lock_owner; uint32_t flags; uint32_t padding; }; #define FUSE_COMPAT_WRITE_IN_SIZE 24 struct fuse_write_in { uint64_t fh; uint64_t offset; uint32_t size; uint32_t write_flags; uint64_t lock_owner; uint32_t flags; uint32_t padding; }; struct fuse_write_out { uint32_t size; uint32_t padding; }; #define FUSE_COMPAT_STATFS_SIZE 48 struct fuse_statfs_out { struct fuse_kstatfs st; }; struct fuse_fsync_in { uint64_t fh; uint32_t fsync_flags; uint32_t padding; }; #define FUSE_COMPAT_SETXATTR_IN_SIZE 8 struct fuse_setxattr_in { uint32_t size; uint32_t flags; uint32_t setxattr_flags; uint32_t padding; }; struct fuse_getxattr_in { uint32_t size; uint32_t padding; }; struct fuse_getxattr_out { uint32_t size; uint32_t padding; }; struct fuse_lk_in { uint64_t fh; uint64_t owner; struct fuse_file_lock lk; uint32_t lk_flags; uint32_t padding; }; struct fuse_lk_out { struct fuse_file_lock lk; }; struct fuse_access_in { uint32_t mask; uint32_t padding; }; struct fuse_init_in { uint32_t major; uint32_t minor; uint32_t max_readahead; uint32_t flags; uint32_t flags2; uint32_t unused[11]; }; #define FUSE_COMPAT_INIT_OUT_SIZE 8 #define FUSE_COMPAT_22_INIT_OUT_SIZE 24 struct fuse_init_out { uint32_t major; uint32_t minor; uint32_t max_readahead; uint32_t flags; uint16_t max_background; uint16_t congestion_threshold; uint32_t max_write; uint32_t time_gran; uint16_t max_pages; uint16_t map_alignment; uint32_t flags2; uint32_t unused[7]; }; #define CUSE_INIT_INFO_MAX 4096 struct cuse_init_in { uint32_t major; uint32_t minor; uint32_t unused; uint32_t flags; }; struct cuse_init_out { uint32_t major; uint32_t minor; uint32_t unused; uint32_t flags; uint32_t max_read; uint32_t max_write; uint32_t dev_major; /* chardev major */ uint32_t dev_minor; /* chardev minor */ uint32_t spare[10]; }; struct fuse_interrupt_in { uint64_t unique; }; struct fuse_bmap_in { uint64_t block; uint32_t blocksize; uint32_t padding; }; struct fuse_bmap_out { uint64_t block; }; struct fuse_ioctl_in { uint64_t fh; uint32_t flags; uint32_t cmd; uint64_t arg; uint32_t in_size; uint32_t out_size; }; struct fuse_ioctl_iovec { uint64_t base; uint64_t len; }; struct fuse_ioctl_out { int32_t result; uint32_t flags; uint32_t in_iovs; uint32_t out_iovs; }; struct fuse_poll_in { uint64_t fh; uint64_t kh; uint32_t flags; uint32_t events; }; struct fuse_poll_out { uint32_t revents; uint32_t padding; }; struct fuse_notify_poll_wakeup_out { uint64_t kh; }; struct fuse_fallocate_in { uint64_t fh; uint64_t offset; uint64_t length; uint32_t mode; uint32_t padding; }; struct fuse_in_header { uint32_t len; uint32_t opcode; uint64_t unique; uint64_t nodeid; uint32_t uid; uint32_t gid; uint32_t pid; uint32_t padding; }; struct fuse_out_header { uint32_t len; int32_t error; uint64_t unique; }; struct fuse_dirent { uint64_t ino; uint64_t off; uint32_t namelen; uint32_t type; char name[]; }; #define FUSE_NAME_OFFSET offsetof(struct fuse_dirent, name) #define FUSE_DIRENT_ALIGN(x) \ (((x) + sizeof(uint64_t) - 1) & ~(sizeof(uint64_t) - 1)) #define FUSE_DIRENT_SIZE(d) \ FUSE_DIRENT_ALIGN(FUSE_NAME_OFFSET + (d)->namelen) struct fuse_direntplus { struct fuse_entry_out entry_out; struct fuse_dirent dirent; }; #define FUSE_NAME_OFFSET_DIRENTPLUS \ offsetof(struct fuse_direntplus, dirent.name) #define FUSE_DIRENTPLUS_SIZE(d) \ FUSE_DIRENT_ALIGN(FUSE_NAME_OFFSET_DIRENTPLUS + (d)->dirent.namelen) struct fuse_notify_inval_inode_out { uint64_t ino; int64_t off; int64_t len; }; struct fuse_notify_inval_entry_out { uint64_t parent; uint32_t namelen; uint32_t flags; }; struct fuse_notify_delete_out { uint64_t parent; uint64_t child; uint32_t namelen; uint32_t padding; }; struct fuse_notify_store_out { uint64_t nodeid; uint64_t offset; uint32_t size; uint32_t padding; }; struct fuse_notify_retrieve_out { uint64_t notify_unique; uint64_t nodeid; uint64_t offset; uint32_t size; uint32_t padding; }; /* Matches the size of fuse_write_in */ struct fuse_notify_retrieve_in { uint64_t dummy1; uint64_t offset; uint32_t size; uint32_t dummy2; uint64_t dummy3; uint64_t dummy4; }; /* Device ioctls: */ #define FUSE_DEV_IOC_MAGIC 229 #define FUSE_DEV_IOC_CLONE _IOR(FUSE_DEV_IOC_MAGIC, 0, uint32_t) struct fuse_lseek_in { uint64_t fh; uint64_t offset; uint32_t whence; uint32_t padding; }; struct fuse_lseek_out { uint64_t offset; }; struct fuse_copy_file_range_in { uint64_t fh_in; uint64_t off_in; uint64_t nodeid_out; uint64_t fh_out; uint64_t off_out; uint64_t len; uint64_t flags; }; #define FUSE_SETUPMAPPING_FLAG_WRITE (1ull << 0) #define FUSE_SETUPMAPPING_FLAG_READ (1ull << 1) struct fuse_setupmapping_in { /* An already open handle */ uint64_t fh; /* Offset into the file to start the mapping */ uint64_t foffset; /* Length of mapping required */ uint64_t len; /* Flags, FUSE_SETUPMAPPING_FLAG_* */ uint64_t flags; /* Offset in Memory Window */ uint64_t moffset; }; struct fuse_removemapping_in { /* number of fuse_removemapping_one follows */ uint32_t count; }; struct fuse_removemapping_one { /* Offset into the dax window start the unmapping */ uint64_t moffset; /* Length of mapping required */ uint64_t len; }; #define FUSE_REMOVEMAPPING_MAX_ENTRY \ (PAGE_SIZE / sizeof(struct fuse_removemapping_one)) struct fuse_syncfs_in { uint64_t padding; }; #endif /* _LINUX_FUSE_H */ linux/nfs4.h000064400000014707151027430560006742 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/nfs4.h * * NFSv4 protocol definitions. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Kendrick Smith * Andy Adamson */ #ifndef _LINUX_NFS4_H #define _LINUX_NFS4_H #include #define NFS4_BITMAP_SIZE 3 #define NFS4_VERIFIER_SIZE 8 #define NFS4_STATEID_SEQID_SIZE 4 #define NFS4_STATEID_OTHER_SIZE 12 #define NFS4_STATEID_SIZE (NFS4_STATEID_SEQID_SIZE + NFS4_STATEID_OTHER_SIZE) #define NFS4_FHSIZE 128 #define NFS4_MAXPATHLEN PATH_MAX #define NFS4_MAXNAMLEN NAME_MAX #define NFS4_OPAQUE_LIMIT 1024 #define NFS4_MAX_SESSIONID_LEN 16 #define NFS4_ACCESS_READ 0x0001 #define NFS4_ACCESS_LOOKUP 0x0002 #define NFS4_ACCESS_MODIFY 0x0004 #define NFS4_ACCESS_EXTEND 0x0008 #define NFS4_ACCESS_DELETE 0x0010 #define NFS4_ACCESS_EXECUTE 0x0020 #define NFS4_ACCESS_XAREAD 0x0040 #define NFS4_ACCESS_XAWRITE 0x0080 #define NFS4_ACCESS_XALIST 0x0100 #define NFS4_FH_PERSISTENT 0x0000 #define NFS4_FH_NOEXPIRE_WITH_OPEN 0x0001 #define NFS4_FH_VOLATILE_ANY 0x0002 #define NFS4_FH_VOL_MIGRATION 0x0004 #define NFS4_FH_VOL_RENAME 0x0008 #define NFS4_OPEN_RESULT_CONFIRM 0x0002 #define NFS4_OPEN_RESULT_LOCKTYPE_POSIX 0x0004 #define NFS4_OPEN_RESULT_PRESERVE_UNLINKED 0x0008 #define NFS4_OPEN_RESULT_MAY_NOTIFY_LOCK 0x0020 #define NFS4_SHARE_ACCESS_MASK 0x000F #define NFS4_SHARE_ACCESS_READ 0x0001 #define NFS4_SHARE_ACCESS_WRITE 0x0002 #define NFS4_SHARE_ACCESS_BOTH 0x0003 #define NFS4_SHARE_DENY_READ 0x0001 #define NFS4_SHARE_DENY_WRITE 0x0002 #define NFS4_SHARE_DENY_BOTH 0x0003 /* nfs41 */ #define NFS4_SHARE_WANT_MASK 0xFF00 #define NFS4_SHARE_WANT_NO_PREFERENCE 0x0000 #define NFS4_SHARE_WANT_READ_DELEG 0x0100 #define NFS4_SHARE_WANT_WRITE_DELEG 0x0200 #define NFS4_SHARE_WANT_ANY_DELEG 0x0300 #define NFS4_SHARE_WANT_NO_DELEG 0x0400 #define NFS4_SHARE_WANT_CANCEL 0x0500 #define NFS4_SHARE_WHEN_MASK 0xF0000 #define NFS4_SHARE_SIGNAL_DELEG_WHEN_RESRC_AVAIL 0x10000 #define NFS4_SHARE_PUSH_DELEG_WHEN_UNCONTENDED 0x20000 #define NFS4_CDFC4_FORE 0x1 #define NFS4_CDFC4_BACK 0x2 #define NFS4_CDFC4_BOTH 0x3 #define NFS4_CDFC4_FORE_OR_BOTH 0x3 #define NFS4_CDFC4_BACK_OR_BOTH 0x7 #define NFS4_CDFS4_FORE 0x1 #define NFS4_CDFS4_BACK 0x2 #define NFS4_CDFS4_BOTH 0x3 #define NFS4_SET_TO_SERVER_TIME 0 #define NFS4_SET_TO_CLIENT_TIME 1 #define NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE 0 #define NFS4_ACE_ACCESS_DENIED_ACE_TYPE 1 #define NFS4_ACE_SYSTEM_AUDIT_ACE_TYPE 2 #define NFS4_ACE_SYSTEM_ALARM_ACE_TYPE 3 #define ACL4_SUPPORT_ALLOW_ACL 0x01 #define ACL4_SUPPORT_DENY_ACL 0x02 #define ACL4_SUPPORT_AUDIT_ACL 0x04 #define ACL4_SUPPORT_ALARM_ACL 0x08 #define NFS4_ACL_AUTO_INHERIT 0x00000001 #define NFS4_ACL_PROTECTED 0x00000002 #define NFS4_ACL_DEFAULTED 0x00000004 #define NFS4_ACE_FILE_INHERIT_ACE 0x00000001 #define NFS4_ACE_DIRECTORY_INHERIT_ACE 0x00000002 #define NFS4_ACE_NO_PROPAGATE_INHERIT_ACE 0x00000004 #define NFS4_ACE_INHERIT_ONLY_ACE 0x00000008 #define NFS4_ACE_SUCCESSFUL_ACCESS_ACE_FLAG 0x00000010 #define NFS4_ACE_FAILED_ACCESS_ACE_FLAG 0x00000020 #define NFS4_ACE_IDENTIFIER_GROUP 0x00000040 #define NFS4_ACE_INHERITED_ACE 0x00000080 #define NFS4_ACE_READ_DATA 0x00000001 #define NFS4_ACE_LIST_DIRECTORY 0x00000001 #define NFS4_ACE_WRITE_DATA 0x00000002 #define NFS4_ACE_ADD_FILE 0x00000002 #define NFS4_ACE_APPEND_DATA 0x00000004 #define NFS4_ACE_ADD_SUBDIRECTORY 0x00000004 #define NFS4_ACE_READ_NAMED_ATTRS 0x00000008 #define NFS4_ACE_WRITE_NAMED_ATTRS 0x00000010 #define NFS4_ACE_EXECUTE 0x00000020 #define NFS4_ACE_DELETE_CHILD 0x00000040 #define NFS4_ACE_READ_ATTRIBUTES 0x00000080 #define NFS4_ACE_WRITE_ATTRIBUTES 0x00000100 #define NFS4_ACE_WRITE_RETENTION 0x00000200 #define NFS4_ACE_WRITE_RETENTION_HOLD 0x00000400 #define NFS4_ACE_DELETE 0x00010000 #define NFS4_ACE_READ_ACL 0x00020000 #define NFS4_ACE_WRITE_ACL 0x00040000 #define NFS4_ACE_WRITE_OWNER 0x00080000 #define NFS4_ACE_SYNCHRONIZE 0x00100000 #define NFS4_ACE_GENERIC_READ 0x00120081 #define NFS4_ACE_GENERIC_WRITE 0x00160106 #define NFS4_ACE_GENERIC_EXECUTE 0x001200A0 #define NFS4_ACE_MASK_ALL 0x001F01FF #define EXCHGID4_FLAG_SUPP_MOVED_REFER 0x00000001 #define EXCHGID4_FLAG_SUPP_MOVED_MIGR 0x00000002 #define EXCHGID4_FLAG_BIND_PRINC_STATEID 0x00000100 #define EXCHGID4_FLAG_USE_NON_PNFS 0x00010000 #define EXCHGID4_FLAG_USE_PNFS_MDS 0x00020000 #define EXCHGID4_FLAG_USE_PNFS_DS 0x00040000 #define EXCHGID4_FLAG_MASK_PNFS 0x00070000 #define EXCHGID4_FLAG_UPD_CONFIRMED_REC_A 0x40000000 #define EXCHGID4_FLAG_CONFIRMED_R 0x80000000 #define EXCHGID4_FLAG_SUPP_FENCE_OPS 0x00000004 /* * Since the validity of these bits depends on whether * they're set in the argument or response, have separate * invalid flag masks for arg (_A) and resp (_R). */ #define EXCHGID4_FLAG_MASK_A 0x40070103 #define EXCHGID4_FLAG_MASK_R 0x80070103 #define EXCHGID4_2_FLAG_MASK_R 0x80070107 #define SEQ4_STATUS_CB_PATH_DOWN 0x00000001 #define SEQ4_STATUS_CB_GSS_CONTEXTS_EXPIRING 0x00000002 #define SEQ4_STATUS_CB_GSS_CONTEXTS_EXPIRED 0x00000004 #define SEQ4_STATUS_EXPIRED_ALL_STATE_REVOKED 0x00000008 #define SEQ4_STATUS_EXPIRED_SOME_STATE_REVOKED 0x00000010 #define SEQ4_STATUS_ADMIN_STATE_REVOKED 0x00000020 #define SEQ4_STATUS_RECALLABLE_STATE_REVOKED 0x00000040 #define SEQ4_STATUS_LEASE_MOVED 0x00000080 #define SEQ4_STATUS_RESTART_RECLAIM_NEEDED 0x00000100 #define SEQ4_STATUS_CB_PATH_DOWN_SESSION 0x00000200 #define SEQ4_STATUS_BACKCHANNEL_FAULT 0x00000400 #define NFS4_SECINFO_STYLE4_CURRENT_FH 0 #define NFS4_SECINFO_STYLE4_PARENT 1 #define NFS4_MAX_UINT64 (~(__u64)0) /* An NFS4 sessions server must support at least NFS4_MAX_OPS operations. * If a compound requires more operations, adjust NFS4_MAX_OPS accordingly. */ #define NFS4_MAX_OPS 8 /* Our NFS4 client back channel server only wants the cb_sequene and the * actual operation per compound */ #define NFS4_MAX_BACK_CHANNEL_OPS 2 #endif /* _LINUX_NFS4_H */ /* * Local variables: * c-basic-offset: 8 * End: */ linux/pcitest.h000064400000001307151027430560007533 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /** * pcitest.h - PCI test uapi defines * * Copyright (C) 2017 Texas Instruments * Author: Kishon Vijay Abraham I * */ #ifndef __UAPI_LINUX_PCITEST_H #define __UAPI_LINUX_PCITEST_H #define PCITEST_BAR _IO('P', 0x1) #define PCITEST_LEGACY_IRQ _IO('P', 0x2) #define PCITEST_MSI _IOW('P', 0x3, int) #define PCITEST_WRITE _IOW('P', 0x4, unsigned long) #define PCITEST_READ _IOW('P', 0x5, unsigned long) #define PCITEST_COPY _IOW('P', 0x6, unsigned long) #define PCITEST_MSIX _IOW('P', 0x7, int) #define PCITEST_SET_IRQTYPE _IOW('P', 0x8, int) #define PCITEST_GET_IRQTYPE _IO('P', 0x9) #endif /* __UAPI_LINUX_PCITEST_H */ linux/filter.h000064400000004250151027430560007345 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Linux Socket Filter Data Structures */ #ifndef __LINUX_FILTER_H__ #define __LINUX_FILTER_H__ #include #include /* * Current version of the filter code architecture. */ #define BPF_MAJOR_VERSION 1 #define BPF_MINOR_VERSION 1 /* * Try and keep these values and structures similar to BSD, especially * the BPF code definitions which need to match so you can share filters */ struct sock_filter { /* Filter block */ __u16 code; /* Actual filter code */ __u8 jt; /* Jump true */ __u8 jf; /* Jump false */ __u32 k; /* Generic multiuse field */ }; struct sock_fprog { /* Required for SO_ATTACH_FILTER. */ unsigned short len; /* Number of filter blocks */ struct sock_filter *filter; }; /* ret - BPF_K and BPF_X also apply */ #define BPF_RVAL(code) ((code) & 0x18) #define BPF_A 0x10 /* misc */ #define BPF_MISCOP(code) ((code) & 0xf8) #define BPF_TAX 0x00 #define BPF_TXA 0x80 /* * Macros for filter block array initializers. */ #ifndef BPF_STMT #define BPF_STMT(code, k) { (unsigned short)(code), 0, 0, k } #endif #ifndef BPF_JUMP #define BPF_JUMP(code, k, jt, jf) { (unsigned short)(code), jt, jf, k } #endif /* * Number of scratch memory words for: BPF_ST and BPF_STX */ #define BPF_MEMWORDS 16 /* RATIONALE. Negative offsets are invalid in BPF. We use them to reference ancillary data. Unlike introduction new instructions, it does not break existing compilers/optimizers. */ #define SKF_AD_OFF (-0x1000) #define SKF_AD_PROTOCOL 0 #define SKF_AD_PKTTYPE 4 #define SKF_AD_IFINDEX 8 #define SKF_AD_NLATTR 12 #define SKF_AD_NLATTR_NEST 16 #define SKF_AD_MARK 20 #define SKF_AD_QUEUE 24 #define SKF_AD_HATYPE 28 #define SKF_AD_RXHASH 32 #define SKF_AD_CPU 36 #define SKF_AD_ALU_XOR_X 40 #define SKF_AD_VLAN_TAG 44 #define SKF_AD_VLAN_TAG_PRESENT 48 #define SKF_AD_PAY_OFFSET 52 #define SKF_AD_RANDOM 56 #define SKF_AD_VLAN_TPID 60 #define SKF_AD_MAX 64 #define SKF_NET_OFF (-0x100000) #define SKF_LL_OFF (-0x200000) #define BPF_NET_OFF SKF_NET_OFF #define BPF_LL_OFF SKF_LL_OFF #endif /* __LINUX_FILTER_H__ */ linux/mptcp.h000064400000012750151027430560007207 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _MPTCP_H #define _MPTCP_H #include #include #define MPTCP_SUBFLOW_FLAG_MCAP_REM _BITUL(0) #define MPTCP_SUBFLOW_FLAG_MCAP_LOC _BITUL(1) #define MPTCP_SUBFLOW_FLAG_JOIN_REM _BITUL(2) #define MPTCP_SUBFLOW_FLAG_JOIN_LOC _BITUL(3) #define MPTCP_SUBFLOW_FLAG_BKUP_REM _BITUL(4) #define MPTCP_SUBFLOW_FLAG_BKUP_LOC _BITUL(5) #define MPTCP_SUBFLOW_FLAG_FULLY_ESTABLISHED _BITUL(6) #define MPTCP_SUBFLOW_FLAG_CONNECTED _BITUL(7) #define MPTCP_SUBFLOW_FLAG_MAPVALID _BITUL(8) enum { MPTCP_SUBFLOW_ATTR_UNSPEC, MPTCP_SUBFLOW_ATTR_TOKEN_REM, MPTCP_SUBFLOW_ATTR_TOKEN_LOC, MPTCP_SUBFLOW_ATTR_RELWRITE_SEQ, MPTCP_SUBFLOW_ATTR_MAP_SEQ, MPTCP_SUBFLOW_ATTR_MAP_SFSEQ, MPTCP_SUBFLOW_ATTR_SSN_OFFSET, MPTCP_SUBFLOW_ATTR_MAP_DATALEN, MPTCP_SUBFLOW_ATTR_FLAGS, MPTCP_SUBFLOW_ATTR_ID_REM, MPTCP_SUBFLOW_ATTR_ID_LOC, MPTCP_SUBFLOW_ATTR_PAD, __MPTCP_SUBFLOW_ATTR_MAX }; #define MPTCP_SUBFLOW_ATTR_MAX (__MPTCP_SUBFLOW_ATTR_MAX - 1) /* netlink interface */ #define MPTCP_PM_NAME "mptcp_pm" #define MPTCP_PM_CMD_GRP_NAME "mptcp_pm_cmds" #define MPTCP_PM_EV_GRP_NAME "mptcp_pm_events" #define MPTCP_PM_VER 0x1 /* * ATTR types defined for MPTCP */ enum { MPTCP_PM_ATTR_UNSPEC, MPTCP_PM_ATTR_ADDR, /* nested address */ MPTCP_PM_ATTR_RCV_ADD_ADDRS, /* u32 */ MPTCP_PM_ATTR_SUBFLOWS, /* u32 */ __MPTCP_PM_ATTR_MAX }; #define MPTCP_PM_ATTR_MAX (__MPTCP_PM_ATTR_MAX - 1) enum { MPTCP_PM_ADDR_ATTR_UNSPEC, MPTCP_PM_ADDR_ATTR_FAMILY, /* u16 */ MPTCP_PM_ADDR_ATTR_ID, /* u8 */ MPTCP_PM_ADDR_ATTR_ADDR4, /* struct in_addr */ MPTCP_PM_ADDR_ATTR_ADDR6, /* struct in6_addr */ MPTCP_PM_ADDR_ATTR_PORT, /* u16 */ MPTCP_PM_ADDR_ATTR_FLAGS, /* u32 */ MPTCP_PM_ADDR_ATTR_IF_IDX, /* s32 */ __MPTCP_PM_ADDR_ATTR_MAX }; #define MPTCP_PM_ADDR_ATTR_MAX (__MPTCP_PM_ADDR_ATTR_MAX - 1) #define MPTCP_PM_ADDR_FLAG_SIGNAL (1 << 0) #define MPTCP_PM_ADDR_FLAG_SUBFLOW (1 << 1) #define MPTCP_PM_ADDR_FLAG_BACKUP (1 << 2) #define MPTCP_PM_ADDR_FLAG_FULLMESH (1 << 3) #define MPTCP_PM_ADDR_FLAG_IMPLICIT (1 << 4) enum { MPTCP_PM_CMD_UNSPEC, MPTCP_PM_CMD_ADD_ADDR, MPTCP_PM_CMD_DEL_ADDR, MPTCP_PM_CMD_GET_ADDR, MPTCP_PM_CMD_FLUSH_ADDRS, MPTCP_PM_CMD_SET_LIMITS, MPTCP_PM_CMD_GET_LIMITS, MPTCP_PM_CMD_SET_FLAGS, __MPTCP_PM_CMD_AFTER_LAST }; #define MPTCP_INFO_FLAG_FALLBACK _BITUL(0) #define MPTCP_INFO_FLAG_REMOTE_KEY_RECEIVED _BITUL(1) struct mptcp_info { __u8 mptcpi_subflows; __u8 mptcpi_add_addr_signal; __u8 mptcpi_add_addr_accepted; __u8 mptcpi_subflows_max; __u8 mptcpi_add_addr_signal_max; __u8 mptcpi_add_addr_accepted_max; __u32 mptcpi_flags; __u32 mptcpi_token; __u64 mptcpi_write_seq; __u64 mptcpi_snd_una; __u64 mptcpi_rcv_nxt; __u8 mptcpi_local_addr_used; __u8 mptcpi_local_addr_max; }; /* * MPTCP_EVENT_CREATED: token, family, saddr4 | saddr6, daddr4 | daddr6, * sport, dport * A new MPTCP connection has been created. It is the good time to allocate * memory and send ADD_ADDR if needed. Depending on the traffic-patterns * it can take a long time until the MPTCP_EVENT_ESTABLISHED is sent. * * MPTCP_EVENT_ESTABLISHED: token, family, saddr4 | saddr6, daddr4 | daddr6, * sport, dport * A MPTCP connection is established (can start new subflows). * * MPTCP_EVENT_CLOSED: token * A MPTCP connection has stopped. * * MPTCP_EVENT_ANNOUNCED: token, rem_id, family, daddr4 | daddr6 [, dport] * A new address has been announced by the peer. * * MPTCP_EVENT_REMOVED: token, rem_id * An address has been lost by the peer. * * MPTCP_EVENT_SUB_ESTABLISHED: token, family, saddr4 | saddr6, * daddr4 | daddr6, sport, dport, backup, * if_idx [, error] * A new subflow has been established. 'error' should not be set. * * MPTCP_EVENT_SUB_CLOSED: token, family, saddr4 | saddr6, daddr4 | daddr6, * sport, dport, backup, if_idx [, error] * A subflow has been closed. An error (copy of sk_err) could be set if an * error has been detected for this subflow. * * MPTCP_EVENT_SUB_PRIORITY: token, family, saddr4 | saddr6, daddr4 | daddr6, * sport, dport, backup, if_idx [, error] * The priority of a subflow has changed. 'error' should not be set. */ enum mptcp_event_type { MPTCP_EVENT_UNSPEC = 0, MPTCP_EVENT_CREATED = 1, MPTCP_EVENT_ESTABLISHED = 2, MPTCP_EVENT_CLOSED = 3, MPTCP_EVENT_ANNOUNCED = 6, MPTCP_EVENT_REMOVED = 7, MPTCP_EVENT_SUB_ESTABLISHED = 10, MPTCP_EVENT_SUB_CLOSED = 11, MPTCP_EVENT_SUB_PRIORITY = 13, }; enum mptcp_event_attr { MPTCP_ATTR_UNSPEC = 0, MPTCP_ATTR_TOKEN, /* u32 */ MPTCP_ATTR_FAMILY, /* u16 */ MPTCP_ATTR_LOC_ID, /* u8 */ MPTCP_ATTR_REM_ID, /* u8 */ MPTCP_ATTR_SADDR4, /* be32 */ MPTCP_ATTR_SADDR6, /* struct in6_addr */ MPTCP_ATTR_DADDR4, /* be32 */ MPTCP_ATTR_DADDR6, /* struct in6_addr */ MPTCP_ATTR_SPORT, /* be16 */ MPTCP_ATTR_DPORT, /* be16 */ MPTCP_ATTR_BACKUP, /* u8 */ MPTCP_ATTR_ERROR, /* u8 */ MPTCP_ATTR_FLAGS, /* u16 */ MPTCP_ATTR_TIMEOUT, /* u32 */ MPTCP_ATTR_IF_IDX, /* s32 */ MPTCP_ATTR_RESET_REASON,/* u32 */ MPTCP_ATTR_RESET_FLAGS, /* u32 */ __MPTCP_ATTR_AFTER_LAST }; #define MPTCP_ATTR_MAX (__MPTCP_ATTR_AFTER_LAST - 1) /* MPTCP Reset reason codes, rfc8684 */ #define MPTCP_RST_EUNSPEC 0 #define MPTCP_RST_EMPTCP 1 #define MPTCP_RST_ERESOURCE 2 #define MPTCP_RST_EPROHIBIT 3 #define MPTCP_RST_EWQ2BIG 4 #define MPTCP_RST_EBADPERF 5 #define MPTCP_RST_EMIDDLEBOX 6 #endif /* _MPTCP_H */ linux/bsg.h000064400000004676151027430560006647 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef BSG_H #define BSG_H #include #define BSG_PROTOCOL_SCSI 0 #define BSG_SUB_PROTOCOL_SCSI_CMD 0 #define BSG_SUB_PROTOCOL_SCSI_TMF 1 #define BSG_SUB_PROTOCOL_SCSI_TRANSPORT 2 /* * For flag constants below: * sg.h sg_io_hdr also has bits defined for it's flags member. These * two flag values (0x10 and 0x20) have the same meaning in sg.h . For * bsg the BSG_FLAG_Q_AT_HEAD flag is ignored since it is the deafult. */ #define BSG_FLAG_Q_AT_TAIL 0x10 /* default is Q_AT_HEAD */ #define BSG_FLAG_Q_AT_HEAD 0x20 struct sg_io_v4 { __s32 guard; /* [i] 'Q' to differentiate from v3 */ __u32 protocol; /* [i] 0 -> SCSI , .... */ __u32 subprotocol; /* [i] 0 -> SCSI command, 1 -> SCSI task management function, .... */ __u32 request_len; /* [i] in bytes */ __u64 request; /* [i], [*i] {SCSI: cdb} */ __u64 request_tag; /* [i] {SCSI: task tag (only if flagged)} */ __u32 request_attr; /* [i] {SCSI: task attribute} */ __u32 request_priority; /* [i] {SCSI: task priority} */ __u32 request_extra; /* [i] {spare, for padding} */ __u32 max_response_len; /* [i] in bytes */ __u64 response; /* [i], [*o] {SCSI: (auto)sense data} */ /* "dout_": data out (to device); "din_": data in (from device) */ __u32 dout_iovec_count; /* [i] 0 -> "flat" dout transfer else dout_xfer points to array of iovec */ __u32 dout_xfer_len; /* [i] bytes to be transferred to device */ __u32 din_iovec_count; /* [i] 0 -> "flat" din transfer */ __u32 din_xfer_len; /* [i] bytes to be transferred from device */ __u64 dout_xferp; /* [i], [*i] */ __u64 din_xferp; /* [i], [*o] */ __u32 timeout; /* [i] units: millisecond */ __u32 flags; /* [i] bit mask */ __u64 usr_ptr; /* [i->o] unused internally */ __u32 spare_in; /* [i] */ __u32 driver_status; /* [o] 0 -> ok */ __u32 transport_status; /* [o] 0 -> ok */ __u32 device_status; /* [o] {SCSI: command completion status} */ __u32 retry_delay; /* [o] {SCSI: status auxiliary information} */ __u32 info; /* [o] additional information */ __u32 duration; /* [o] time to complete, in milliseconds */ __u32 response_len; /* [o] bytes of response actually written */ __s32 din_resid; /* [o] din_xfer_len - actual_din_xfer_len */ __s32 dout_resid; /* [o] dout_xfer_len - actual_dout_xfer_len */ __u64 generated_tag; /* [o] {SCSI: transport generated task tag} */ __u32 spare_out; /* [o] */ __u32 padding; }; #endif /* BSG_H */ linux/pr.h000064400000002061151027430560006477 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _PR_H #define _PR_H #include enum pr_type { PR_WRITE_EXCLUSIVE = 1, PR_EXCLUSIVE_ACCESS = 2, PR_WRITE_EXCLUSIVE_REG_ONLY = 3, PR_EXCLUSIVE_ACCESS_REG_ONLY = 4, PR_WRITE_EXCLUSIVE_ALL_REGS = 5, PR_EXCLUSIVE_ACCESS_ALL_REGS = 6, }; struct pr_reservation { __u64 key; __u32 type; __u32 flags; }; struct pr_registration { __u64 old_key; __u64 new_key; __u32 flags; __u32 __pad; }; struct pr_preempt { __u64 old_key; __u64 new_key; __u32 type; __u32 flags; }; struct pr_clear { __u64 key; __u32 flags; __u32 __pad; }; #define PR_FL_IGNORE_KEY (1 << 0) /* ignore existing key */ #define IOC_PR_REGISTER _IOW('p', 200, struct pr_registration) #define IOC_PR_RESERVE _IOW('p', 201, struct pr_reservation) #define IOC_PR_RELEASE _IOW('p', 202, struct pr_reservation) #define IOC_PR_PREEMPT _IOW('p', 203, struct pr_preempt) #define IOC_PR_PREEMPT_ABORT _IOW('p', 204, struct pr_preempt) #define IOC_PR_CLEAR _IOW('p', 205, struct pr_clear) #endif /* _PR_H */ linux/gigaset_dev.h000064400000002642151027430560010344 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * interface to user space for the gigaset driver * * Copyright (c) 2004 by Hansjoerg Lipp * * ===================================================================== * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * ===================================================================== */ #ifndef GIGASET_INTERFACE_H #define GIGASET_INTERFACE_H #include /* The magic IOCTL value for this interface. */ #define GIGASET_IOCTL 0x47 /* enable/disable device control via character device (lock out ISDN subsys) */ #define GIGASET_REDIR _IOWR(GIGASET_IOCTL, 0, int) /* enable adapter configuration mode (M10x only) */ #define GIGASET_CONFIG _IOWR(GIGASET_IOCTL, 1, int) /* set break characters (M105 only) */ #define GIGASET_BRKCHARS _IOW(GIGASET_IOCTL, 2, unsigned char[6]) /* get version information selected by arg[0] */ #define GIGASET_VERSION _IOWR(GIGASET_IOCTL, 3, unsigned[4]) /* values for GIGASET_VERSION arg[0] */ #define GIGVER_DRIVER 0 /* get driver version */ #define GIGVER_COMPAT 1 /* get interface compatibility version */ #define GIGVER_FWBASE 2 /* get base station firmware version */ #endif linux/in_route.h000064400000001650151027430560007705 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_IN_ROUTE_H #define _LINUX_IN_ROUTE_H /* IPv4 routing cache flags */ #define RTCF_DEAD RTNH_F_DEAD #define RTCF_ONLINK RTNH_F_ONLINK /* Obsolete flag. About to be deleted */ #define RTCF_NOPMTUDISC RTM_F_NOPMTUDISC #define RTCF_NOTIFY 0x00010000 #define RTCF_DIRECTDST 0x00020000 /* unused */ #define RTCF_REDIRECTED 0x00040000 #define RTCF_TPROXY 0x00080000 /* unused */ #define RTCF_FAST 0x00200000 /* unused */ #define RTCF_MASQ 0x00400000 /* unused */ #define RTCF_SNAT 0x00800000 /* unused */ #define RTCF_DOREDIRECT 0x01000000 #define RTCF_DIRECTSRC 0x04000000 #define RTCF_DNAT 0x08000000 #define RTCF_BROADCAST 0x10000000 #define RTCF_MULTICAST 0x20000000 #define RTCF_REJECT 0x40000000 /* unused */ #define RTCF_LOCAL 0x80000000 #define RTCF_NAT (RTCF_DNAT|RTCF_SNAT) #define RT_TOS(tos) ((tos)&IPTOS_TOS_MASK) #endif /* _LINUX_IN_ROUTE_H */ linux/scc.h000064400000010765151027430560006640 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: scc.h,v 1.29 1997/04/02 14:56:45 jreuter Exp jreuter $ */ #ifndef _SCC_H #define _SCC_H /* selection of hardware types */ #define PA0HZP 0x00 /* hardware type for PA0HZP SCC card and compatible */ #define EAGLE 0x01 /* hardware type for EAGLE card */ #define PC100 0x02 /* hardware type for PC100 card */ #define PRIMUS 0x04 /* hardware type for PRIMUS-PC (DG9BL) card */ #define DRSI 0x08 /* hardware type for DRSI PC*Packet card */ #define BAYCOM 0x10 /* hardware type for BayCom (U)SCC */ /* DEV ioctl() commands */ enum SCC_ioctl_cmds { SIOCSCCRESERVED = SIOCDEVPRIVATE, SIOCSCCCFG, SIOCSCCINI, SIOCSCCCHANINI, SIOCSCCSMEM, SIOCSCCGKISS, SIOCSCCSKISS, SIOCSCCGSTAT, SIOCSCCCAL }; /* Device parameter control (from WAMPES) */ enum L1_params { PARAM_DATA, PARAM_TXDELAY, PARAM_PERSIST, PARAM_SLOTTIME, PARAM_TXTAIL, PARAM_FULLDUP, PARAM_SOFTDCD, /* was: PARAM_HW */ PARAM_MUTE, /* ??? */ PARAM_DTR, PARAM_RTS, PARAM_SPEED, PARAM_ENDDELAY, /* ??? */ PARAM_GROUP, PARAM_IDLE, PARAM_MIN, PARAM_MAXKEY, PARAM_WAIT, PARAM_MAXDEFER, PARAM_TX, PARAM_HWEVENT = 31, PARAM_RETURN = 255 /* reset kiss mode */ }; /* fulldup parameter */ enum FULLDUP_modes { KISS_DUPLEX_HALF, /* normal CSMA operation */ KISS_DUPLEX_FULL, /* fullduplex, key down trx after transmission */ KISS_DUPLEX_LINK, /* fullduplex, key down trx after 'idletime' sec */ KISS_DUPLEX_OPTIMA /* fullduplex, let the protocol layer control the hw */ }; /* misc. parameters */ #define TIMER_OFF 65535U /* to switch off timers */ #define NO_SUCH_PARAM 65534U /* param not implemented */ /* HWEVENT parameter */ enum HWEVENT_opts { HWEV_DCD_ON, HWEV_DCD_OFF, HWEV_ALL_SENT }; /* channel grouping */ #define RXGROUP 0100 /* if set, only tx when all channels clear */ #define TXGROUP 0200 /* if set, don't transmit simultaneously */ /* Tx/Rx clock sources */ enum CLOCK_sources { CLK_DPLL, /* normal halfduplex operation */ CLK_EXTERNAL, /* external clocking (G3RUH/DF9IC modems) */ CLK_DIVIDER, /* Rx = DPLL, Tx = divider (fullduplex with */ /* modems without clock regeneration */ CLK_BRG /* experimental fullduplex mode with DPLL/BRG for */ /* MODEMs without clock recovery */ }; /* Tx state */ enum TX_state { TXS_IDLE, /* Transmitter off, no data pending */ TXS_BUSY, /* waiting for permission to send / tailtime */ TXS_ACTIVE, /* Transmitter on, sending data */ TXS_NEWFRAME, /* reset CRC and send (next) frame */ TXS_IDLE2, /* Transmitter on, no data pending */ TXS_WAIT, /* Waiting for Mintime to expire */ TXS_TIMEOUT /* We had a transmission timeout */ }; typedef unsigned long io_port; /* type definition for an 'io port address' */ /* SCC statistical information */ struct scc_stat { long rxints; /* Receiver interrupts */ long txints; /* Transmitter interrupts */ long exints; /* External/status interrupts */ long spints; /* Special receiver interrupts */ long txframes; /* Packets sent */ long rxframes; /* Number of Frames Actually Received */ long rxerrs; /* CRC Errors */ long txerrs; /* KISS errors */ unsigned int nospace; /* "Out of buffers" */ unsigned int rx_over; /* Receiver Overruns */ unsigned int tx_under; /* Transmitter Underruns */ unsigned int tx_state; /* Transmitter state */ int tx_queued; /* tx frames enqueued */ unsigned int maxqueue; /* allocated tx_buffers */ unsigned int bufsize; /* used buffersize */ }; struct scc_modem { long speed; /* Line speed, bps */ char clocksrc; /* 0 = DPLL, 1 = external, 2 = divider */ char nrz; /* NRZ instead of NRZI */ }; struct scc_kiss_cmd { int command; /* one of the KISS-Commands defined above */ unsigned param; /* KISS-Param */ }; struct scc_hw_config { io_port data_a; /* data port channel A */ io_port ctrl_a; /* control port channel A */ io_port data_b; /* data port channel B */ io_port ctrl_b; /* control port channel B */ io_port vector_latch; /* INTACK-Latch (#) */ io_port special; /* special function port */ int irq; /* irq */ long clock; /* clock */ char option; /* command for function port */ char brand; /* hardware type */ char escc; /* use ext. features of a 8580/85180/85280 */ }; /* (#) only one INTACK latch allowed. */ struct scc_mem_config { unsigned int dummy; unsigned int bufsize; }; struct scc_calibrate { unsigned int time; unsigned char pattern; }; #endif /* _SCC_H */ linux/if_macsec.h000064400000013310151027430560007766 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * include/uapi/linux/if_macsec.h - MACsec device * * Copyright (c) 2015 Sabrina Dubroca * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef _MACSEC_H #define _MACSEC_H #include #define MACSEC_GENL_NAME "macsec" #define MACSEC_GENL_VERSION 1 #define MACSEC_MAX_KEY_LEN 128 #define MACSEC_KEYID_LEN 16 /* cipher IDs as per IEEE802.1AEbn-2011 */ #define MACSEC_CIPHER_ID_GCM_AES_128 0x0080C20001000001ULL #define MACSEC_CIPHER_ID_GCM_AES_256 0x0080C20001000002ULL /* deprecated cipher ID for GCM-AES-128 */ #define MACSEC_DEFAULT_CIPHER_ID 0x0080020001000001ULL #define MACSEC_DEFAULT_CIPHER_ALT MACSEC_CIPHER_ID_GCM_AES_128 #define MACSEC_MIN_ICV_LEN 8 #define MACSEC_MAX_ICV_LEN 32 /* upper limit for ICV length as recommended by IEEE802.1AE-2006 */ #define MACSEC_STD_ICV_LEN 16 enum macsec_attrs { MACSEC_ATTR_UNSPEC, MACSEC_ATTR_IFINDEX, /* u32, ifindex of the MACsec netdevice */ MACSEC_ATTR_RXSC_CONFIG, /* config, nested macsec_rxsc_attrs */ MACSEC_ATTR_SA_CONFIG, /* config, nested macsec_sa_attrs */ MACSEC_ATTR_SECY, /* dump, nested macsec_secy_attrs */ MACSEC_ATTR_TXSA_LIST, /* dump, nested, macsec_sa_attrs for each TXSA */ MACSEC_ATTR_RXSC_LIST, /* dump, nested, macsec_rxsc_attrs for each RXSC */ MACSEC_ATTR_TXSC_STATS, /* dump, nested, macsec_txsc_stats_attr */ MACSEC_ATTR_SECY_STATS, /* dump, nested, macsec_secy_stats_attr */ __MACSEC_ATTR_END, NUM_MACSEC_ATTR = __MACSEC_ATTR_END, MACSEC_ATTR_MAX = __MACSEC_ATTR_END - 1, }; enum macsec_secy_attrs { MACSEC_SECY_ATTR_UNSPEC, MACSEC_SECY_ATTR_SCI, MACSEC_SECY_ATTR_ENCODING_SA, MACSEC_SECY_ATTR_WINDOW, MACSEC_SECY_ATTR_CIPHER_SUITE, MACSEC_SECY_ATTR_ICV_LEN, MACSEC_SECY_ATTR_PROTECT, MACSEC_SECY_ATTR_REPLAY, MACSEC_SECY_ATTR_OPER, MACSEC_SECY_ATTR_VALIDATE, MACSEC_SECY_ATTR_ENCRYPT, MACSEC_SECY_ATTR_INC_SCI, MACSEC_SECY_ATTR_ES, MACSEC_SECY_ATTR_SCB, MACSEC_SECY_ATTR_PAD, __MACSEC_SECY_ATTR_END, NUM_MACSEC_SECY_ATTR = __MACSEC_SECY_ATTR_END, MACSEC_SECY_ATTR_MAX = __MACSEC_SECY_ATTR_END - 1, }; enum macsec_rxsc_attrs { MACSEC_RXSC_ATTR_UNSPEC, MACSEC_RXSC_ATTR_SCI, /* config/dump, u64 */ MACSEC_RXSC_ATTR_ACTIVE, /* config/dump, u8 0..1 */ MACSEC_RXSC_ATTR_SA_LIST, /* dump, nested */ MACSEC_RXSC_ATTR_STATS, /* dump, nested, macsec_rxsc_stats_attr */ MACSEC_RXSC_ATTR_PAD, __MACSEC_RXSC_ATTR_END, NUM_MACSEC_RXSC_ATTR = __MACSEC_RXSC_ATTR_END, MACSEC_RXSC_ATTR_MAX = __MACSEC_RXSC_ATTR_END - 1, }; enum macsec_sa_attrs { MACSEC_SA_ATTR_UNSPEC, MACSEC_SA_ATTR_AN, /* config/dump, u8 0..3 */ MACSEC_SA_ATTR_ACTIVE, /* config/dump, u8 0..1 */ MACSEC_SA_ATTR_PN, /* config/dump, u32 */ MACSEC_SA_ATTR_KEY, /* config, data */ MACSEC_SA_ATTR_KEYID, /* config/dump, 128-bit */ MACSEC_SA_ATTR_STATS, /* dump, nested, macsec_sa_stats_attr */ MACSEC_SA_ATTR_PAD, __MACSEC_SA_ATTR_END, NUM_MACSEC_SA_ATTR = __MACSEC_SA_ATTR_END, MACSEC_SA_ATTR_MAX = __MACSEC_SA_ATTR_END - 1, }; enum macsec_nl_commands { MACSEC_CMD_GET_TXSC, MACSEC_CMD_ADD_RXSC, MACSEC_CMD_DEL_RXSC, MACSEC_CMD_UPD_RXSC, MACSEC_CMD_ADD_TXSA, MACSEC_CMD_DEL_TXSA, MACSEC_CMD_UPD_TXSA, MACSEC_CMD_ADD_RXSA, MACSEC_CMD_DEL_RXSA, MACSEC_CMD_UPD_RXSA, }; /* u64 per-RXSC stats */ enum macsec_rxsc_stats_attr { MACSEC_RXSC_STATS_ATTR_UNSPEC, MACSEC_RXSC_STATS_ATTR_IN_OCTETS_VALIDATED, MACSEC_RXSC_STATS_ATTR_IN_OCTETS_DECRYPTED, MACSEC_RXSC_STATS_ATTR_IN_PKTS_UNCHECKED, MACSEC_RXSC_STATS_ATTR_IN_PKTS_DELAYED, MACSEC_RXSC_STATS_ATTR_IN_PKTS_OK, MACSEC_RXSC_STATS_ATTR_IN_PKTS_INVALID, MACSEC_RXSC_STATS_ATTR_IN_PKTS_LATE, MACSEC_RXSC_STATS_ATTR_IN_PKTS_NOT_VALID, MACSEC_RXSC_STATS_ATTR_IN_PKTS_NOT_USING_SA, MACSEC_RXSC_STATS_ATTR_IN_PKTS_UNUSED_SA, MACSEC_RXSC_STATS_ATTR_PAD, __MACSEC_RXSC_STATS_ATTR_END, NUM_MACSEC_RXSC_STATS_ATTR = __MACSEC_RXSC_STATS_ATTR_END, MACSEC_RXSC_STATS_ATTR_MAX = __MACSEC_RXSC_STATS_ATTR_END - 1, }; /* u32 per-{RX,TX}SA stats */ enum macsec_sa_stats_attr { MACSEC_SA_STATS_ATTR_UNSPEC, MACSEC_SA_STATS_ATTR_IN_PKTS_OK, MACSEC_SA_STATS_ATTR_IN_PKTS_INVALID, MACSEC_SA_STATS_ATTR_IN_PKTS_NOT_VALID, MACSEC_SA_STATS_ATTR_IN_PKTS_NOT_USING_SA, MACSEC_SA_STATS_ATTR_IN_PKTS_UNUSED_SA, MACSEC_SA_STATS_ATTR_OUT_PKTS_PROTECTED, MACSEC_SA_STATS_ATTR_OUT_PKTS_ENCRYPTED, __MACSEC_SA_STATS_ATTR_END, NUM_MACSEC_SA_STATS_ATTR = __MACSEC_SA_STATS_ATTR_END, MACSEC_SA_STATS_ATTR_MAX = __MACSEC_SA_STATS_ATTR_END - 1, }; /* u64 per-TXSC stats */ enum macsec_txsc_stats_attr { MACSEC_TXSC_STATS_ATTR_UNSPEC, MACSEC_TXSC_STATS_ATTR_OUT_PKTS_PROTECTED, MACSEC_TXSC_STATS_ATTR_OUT_PKTS_ENCRYPTED, MACSEC_TXSC_STATS_ATTR_OUT_OCTETS_PROTECTED, MACSEC_TXSC_STATS_ATTR_OUT_OCTETS_ENCRYPTED, MACSEC_TXSC_STATS_ATTR_PAD, __MACSEC_TXSC_STATS_ATTR_END, NUM_MACSEC_TXSC_STATS_ATTR = __MACSEC_TXSC_STATS_ATTR_END, MACSEC_TXSC_STATS_ATTR_MAX = __MACSEC_TXSC_STATS_ATTR_END - 1, }; /* u64 per-SecY stats */ enum macsec_secy_stats_attr { MACSEC_SECY_STATS_ATTR_UNSPEC, MACSEC_SECY_STATS_ATTR_OUT_PKTS_UNTAGGED, MACSEC_SECY_STATS_ATTR_IN_PKTS_UNTAGGED, MACSEC_SECY_STATS_ATTR_OUT_PKTS_TOO_LONG, MACSEC_SECY_STATS_ATTR_IN_PKTS_NO_TAG, MACSEC_SECY_STATS_ATTR_IN_PKTS_BAD_TAG, MACSEC_SECY_STATS_ATTR_IN_PKTS_UNKNOWN_SCI, MACSEC_SECY_STATS_ATTR_IN_PKTS_NO_SCI, MACSEC_SECY_STATS_ATTR_IN_PKTS_OVERRUN, MACSEC_SECY_STATS_ATTR_PAD, __MACSEC_SECY_STATS_ATTR_END, NUM_MACSEC_SECY_STATS_ATTR = __MACSEC_SECY_STATS_ATTR_END, MACSEC_SECY_STATS_ATTR_MAX = __MACSEC_SECY_STATS_ATTR_END - 1, }; #endif /* _MACSEC_H */ linux/atm_tcp.h000064400000003126151027430560007510 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* atm_tcp.h - Driver-specific declarations of the ATMTCP driver (for use by driver-specific utilities) */ /* Written 1997-2000 by Werner Almesberger, EPFL LRC/ICA */ #ifndef LINUX_ATM_TCP_H #define LINUX_ATM_TCP_H #include #include #include #include /* * All values in struct atmtcp_hdr are in network byte order */ struct atmtcp_hdr { __u16 vpi; __u16 vci; __u32 length; /* ... of data part */ }; /* * All values in struct atmtcp_command are in host byte order */ #define ATMTCP_HDR_MAGIC (~0) /* this length indicates a command */ #define ATMTCP_CTRL_OPEN 1 /* request/reply */ #define ATMTCP_CTRL_CLOSE 2 /* request/reply */ struct atmtcp_control { struct atmtcp_hdr hdr; /* must be first */ int type; /* message type; both directions */ atm_kptr_t vcc; /* both directions */ struct sockaddr_atmpvc addr; /* suggested value from kernel */ struct atm_qos qos; /* both directions */ int result; /* to kernel only */ } __ATM_API_ALIGN; /* * Field usage: * Messge type dir. hdr.v?i type addr qos vcc result * ----------- ---- ------- ---- ---- --- --- ------ * OPEN K->D Y Y Y Y Y 0 * OPEN D->K - Y Y Y Y Y * CLOSE K->D - - Y - Y 0 * CLOSE D->K - - - - Y Y */ #define SIOCSIFATMTCP _IO('a',ATMIOC_ITF) /* set ATMTCP mode */ #define ATMTCP_CREATE _IO('a',ATMIOC_ITF+14) /* create persistent ATMTCP interface */ #define ATMTCP_REMOVE _IO('a',ATMIOC_ITF+15) /* destroy persistent ATMTCP interface */ #endif /* LINUX_ATM_TCP_H */ linux/psample.h000064400000004337151027430560007527 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __UAPI_PSAMPLE_H #define __UAPI_PSAMPLE_H enum { PSAMPLE_ATTR_IIFINDEX, PSAMPLE_ATTR_OIFINDEX, PSAMPLE_ATTR_ORIGSIZE, PSAMPLE_ATTR_SAMPLE_GROUP, PSAMPLE_ATTR_GROUP_SEQ, PSAMPLE_ATTR_SAMPLE_RATE, PSAMPLE_ATTR_DATA, PSAMPLE_ATTR_GROUP_REFCOUNT, PSAMPLE_ATTR_TUNNEL, PSAMPLE_ATTR_PAD, PSAMPLE_ATTR_OUT_TC, /* u16 */ PSAMPLE_ATTR_OUT_TC_OCC, /* u64, bytes */ PSAMPLE_ATTR_LATENCY, /* u64, nanoseconds */ PSAMPLE_ATTR_TIMESTAMP, /* u64, nanoseconds */ PSAMPLE_ATTR_PROTO, /* u16 */ __PSAMPLE_ATTR_MAX }; enum psample_command { PSAMPLE_CMD_SAMPLE, PSAMPLE_CMD_GET_GROUP, PSAMPLE_CMD_NEW_GROUP, PSAMPLE_CMD_DEL_GROUP, }; enum psample_tunnel_key_attr { PSAMPLE_TUNNEL_KEY_ATTR_ID, /* be64 Tunnel ID */ PSAMPLE_TUNNEL_KEY_ATTR_IPV4_SRC, /* be32 src IP address. */ PSAMPLE_TUNNEL_KEY_ATTR_IPV4_DST, /* be32 dst IP address. */ PSAMPLE_TUNNEL_KEY_ATTR_TOS, /* u8 Tunnel IP ToS. */ PSAMPLE_TUNNEL_KEY_ATTR_TTL, /* u8 Tunnel IP TTL. */ PSAMPLE_TUNNEL_KEY_ATTR_DONT_FRAGMENT, /* No argument, set DF. */ PSAMPLE_TUNNEL_KEY_ATTR_CSUM, /* No argument. CSUM packet. */ PSAMPLE_TUNNEL_KEY_ATTR_OAM, /* No argument. OAM frame. */ PSAMPLE_TUNNEL_KEY_ATTR_GENEVE_OPTS, /* Array of Geneve options. */ PSAMPLE_TUNNEL_KEY_ATTR_TP_SRC, /* be16 src Transport Port. */ PSAMPLE_TUNNEL_KEY_ATTR_TP_DST, /* be16 dst Transport Port. */ PSAMPLE_TUNNEL_KEY_ATTR_VXLAN_OPTS, /* Nested VXLAN opts* */ PSAMPLE_TUNNEL_KEY_ATTR_IPV6_SRC, /* struct in6_addr src IPv6 address. */ PSAMPLE_TUNNEL_KEY_ATTR_IPV6_DST, /* struct in6_addr dst IPv6 address. */ PSAMPLE_TUNNEL_KEY_ATTR_PAD, PSAMPLE_TUNNEL_KEY_ATTR_ERSPAN_OPTS, /* struct erspan_metadata */ PSAMPLE_TUNNEL_KEY_ATTR_IPV4_INFO_BRIDGE, /* No argument. IPV4_INFO_BRIDGE mode.*/ __PSAMPLE_TUNNEL_KEY_ATTR_MAX }; /* Can be overridden at runtime by module option */ #define PSAMPLE_ATTR_MAX (__PSAMPLE_ATTR_MAX - 1) #define PSAMPLE_NL_MCGRP_CONFIG_NAME "config" #define PSAMPLE_NL_MCGRP_SAMPLE_NAME "packets" #define PSAMPLE_GENL_NAME "psample" #define PSAMPLE_GENL_VERSION 1 #endif linux/baycom.h000064400000001563151027430560007336 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * The Linux BAYCOM driver for the Baycom serial 1200 baud modem * and the parallel 9600 baud modem * (C) 1997-1998 by Thomas Sailer, HB9JNX/AE4WA */ #ifndef _BAYCOM_H #define _BAYCOM_H /* -------------------------------------------------------------------- */ /* * structs for the IOCTL commands */ struct baycom_debug_data { unsigned long debug1; unsigned long debug2; long debug3; }; struct baycom_ioctl { int cmd; union { struct baycom_debug_data dbg; } data; }; /* -------------------------------------------------------------------- */ /* * ioctl values change for baycom */ #define BAYCOMCTL_GETDEBUG 0x92 /* -------------------------------------------------------------------- */ #endif /* _BAYCOM_H */ /* --------------------------------------------------------------------- */ linux/userfaultfd.h000064400000017136151027430560010413 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/userfaultfd.h * * Copyright (C) 2007 Davide Libenzi * Copyright (C) 2015 Red Hat, Inc. * */ #ifndef _LINUX_USERFAULTFD_H #define _LINUX_USERFAULTFD_H #include /* * If the UFFDIO_API is upgraded someday, the UFFDIO_UNREGISTER and * UFFDIO_WAKE ioctls should be defined as _IOW and not as _IOR. In * userfaultfd.h we assumed the kernel was reading (instead _IOC_READ * means the userland is reading). */ #define UFFD_API ((__u64)0xAA) #define UFFD_API_FEATURES (UFFD_FEATURE_PAGEFAULT_FLAG_WP | \ UFFD_FEATURE_EVENT_FORK | \ UFFD_FEATURE_EVENT_REMAP | \ UFFD_FEATURE_EVENT_REMOVE | \ UFFD_FEATURE_EVENT_UNMAP | \ UFFD_FEATURE_MISSING_HUGETLBFS | \ UFFD_FEATURE_MISSING_SHMEM | \ UFFD_FEATURE_SIGBUS | \ UFFD_FEATURE_THREAD_ID) #define UFFD_API_IOCTLS \ ((__u64)1 << _UFFDIO_REGISTER | \ (__u64)1 << _UFFDIO_UNREGISTER | \ (__u64)1 << _UFFDIO_API) #define UFFD_API_RANGE_IOCTLS \ ((__u64)1 << _UFFDIO_WAKE | \ (__u64)1 << _UFFDIO_COPY | \ (__u64)1 << _UFFDIO_ZEROPAGE | \ (__u64)1 << _UFFDIO_WRITEPROTECT) #define UFFD_API_RANGE_IOCTLS_BASIC \ ((__u64)1 << _UFFDIO_WAKE | \ (__u64)1 << _UFFDIO_COPY) /* * Valid ioctl command number range with this API is from 0x00 to * 0x3F. UFFDIO_API is the fixed number, everything else can be * changed by implementing a different UFFD_API. If sticking to the * same UFFD_API more ioctl can be added and userland will be aware of * which ioctl the running kernel implements through the ioctl command * bitmask written by the UFFDIO_API. */ #define _UFFDIO_REGISTER (0x00) #define _UFFDIO_UNREGISTER (0x01) #define _UFFDIO_WAKE (0x02) #define _UFFDIO_COPY (0x03) #define _UFFDIO_ZEROPAGE (0x04) #define _UFFDIO_WRITEPROTECT (0x06) #define _UFFDIO_API (0x3F) /* userfaultfd ioctl ids */ #define UFFDIO 0xAA #define UFFDIO_API _IOWR(UFFDIO, _UFFDIO_API, \ struct uffdio_api) #define UFFDIO_REGISTER _IOWR(UFFDIO, _UFFDIO_REGISTER, \ struct uffdio_register) #define UFFDIO_UNREGISTER _IOR(UFFDIO, _UFFDIO_UNREGISTER, \ struct uffdio_range) #define UFFDIO_WAKE _IOR(UFFDIO, _UFFDIO_WAKE, \ struct uffdio_range) #define UFFDIO_COPY _IOWR(UFFDIO, _UFFDIO_COPY, \ struct uffdio_copy) #define UFFDIO_ZEROPAGE _IOWR(UFFDIO, _UFFDIO_ZEROPAGE, \ struct uffdio_zeropage) #define UFFDIO_WRITEPROTECT _IOWR(UFFDIO, _UFFDIO_WRITEPROTECT, \ struct uffdio_writeprotect) /* read() structure */ struct uffd_msg { __u8 event; __u8 reserved1; __u16 reserved2; __u32 reserved3; union { struct { __u64 flags; __u64 address; union { __u32 ptid; } feat; } pagefault; struct { __u32 ufd; } fork; struct { __u64 from; __u64 to; __u64 len; } remap; struct { __u64 start; __u64 end; } remove; struct { /* unused reserved fields */ __u64 reserved1; __u64 reserved2; __u64 reserved3; } reserved; } arg; } __attribute__((packed)); /* * Start at 0x12 and not at 0 to be more strict against bugs. */ #define UFFD_EVENT_PAGEFAULT 0x12 #define UFFD_EVENT_FORK 0x13 #define UFFD_EVENT_REMAP 0x14 #define UFFD_EVENT_REMOVE 0x15 #define UFFD_EVENT_UNMAP 0x16 /* flags for UFFD_EVENT_PAGEFAULT */ #define UFFD_PAGEFAULT_FLAG_WRITE (1<<0) /* If this was a write fault */ #define UFFD_PAGEFAULT_FLAG_WP (1<<1) /* If reason is VM_UFFD_WP */ struct uffdio_api { /* userland asks for an API number and the features to enable */ __u64 api; /* * Kernel answers below with the all available features for * the API, this notifies userland of which events and/or * which flags for each event are enabled in the current * kernel. * * Note: UFFD_EVENT_PAGEFAULT and UFFD_PAGEFAULT_FLAG_WRITE * are to be considered implicitly always enabled in all kernels as * long as the uffdio_api.api requested matches UFFD_API. * * UFFD_FEATURE_MISSING_HUGETLBFS means an UFFDIO_REGISTER * with UFFDIO_REGISTER_MODE_MISSING mode will succeed on * hugetlbfs virtual memory ranges. Adding or not adding * UFFD_FEATURE_MISSING_HUGETLBFS to uffdio_api.features has * no real functional effect after UFFDIO_API returns, but * it's only useful for an initial feature set probe at * UFFDIO_API time. There are two ways to use it: * * 1) by adding UFFD_FEATURE_MISSING_HUGETLBFS to the * uffdio_api.features before calling UFFDIO_API, an error * will be returned by UFFDIO_API on a kernel without * hugetlbfs missing support * * 2) the UFFD_FEATURE_MISSING_HUGETLBFS can not be added in * uffdio_api.features and instead it will be set by the * kernel in the uffdio_api.features if the kernel supports * it, so userland can later check if the feature flag is * present in uffdio_api.features after UFFDIO_API * succeeded. * * UFFD_FEATURE_MISSING_SHMEM works the same as * UFFD_FEATURE_MISSING_HUGETLBFS, but it applies to shmem * (i.e. tmpfs and other shmem based APIs). * * UFFD_FEATURE_SIGBUS feature means no page-fault * (UFFD_EVENT_PAGEFAULT) event will be delivered, instead * a SIGBUS signal will be sent to the faulting process. * * UFFD_FEATURE_THREAD_ID pid of the page faulted task_struct will * be returned, if feature is not requested 0 will be returned. */ #define UFFD_FEATURE_PAGEFAULT_FLAG_WP (1<<0) #define UFFD_FEATURE_EVENT_FORK (1<<1) #define UFFD_FEATURE_EVENT_REMAP (1<<2) #define UFFD_FEATURE_EVENT_REMOVE (1<<3) #define UFFD_FEATURE_MISSING_HUGETLBFS (1<<4) #define UFFD_FEATURE_MISSING_SHMEM (1<<5) #define UFFD_FEATURE_EVENT_UNMAP (1<<6) #define UFFD_FEATURE_SIGBUS (1<<7) #define UFFD_FEATURE_THREAD_ID (1<<8) __u64 features; __u64 ioctls; }; struct uffdio_range { __u64 start; __u64 len; }; struct uffdio_register { struct uffdio_range range; #define UFFDIO_REGISTER_MODE_MISSING ((__u64)1<<0) #define UFFDIO_REGISTER_MODE_WP ((__u64)1<<1) __u64 mode; /* * kernel answers which ioctl commands are available for the * range, keep at the end as the last 8 bytes aren't read. */ __u64 ioctls; }; struct uffdio_copy { __u64 dst; __u64 src; __u64 len; #define UFFDIO_COPY_MODE_DONTWAKE ((__u64)1<<0) /* * UFFDIO_COPY_MODE_WP will map the page write protected on * the fly. UFFDIO_COPY_MODE_WP is available only if the * write protected ioctl is implemented for the range * according to the uffdio_register.ioctls. */ #define UFFDIO_COPY_MODE_WP ((__u64)1<<1) __u64 mode; /* * "copy" is written by the ioctl and must be at the end: the * copy_from_user will not read the last 8 bytes. */ __s64 copy; }; struct uffdio_zeropage { struct uffdio_range range; #define UFFDIO_ZEROPAGE_MODE_DONTWAKE ((__u64)1<<0) __u64 mode; /* * "zeropage" is written by the ioctl and must be at the end: * the copy_from_user will not read the last 8 bytes. */ __s64 zeropage; }; struct uffdio_writeprotect { struct uffdio_range range; /* * UFFDIO_WRITEPROTECT_MODE_WP: set the flag to write protect a range, * unset the flag to undo protection of a range which was previously * write protected. * * UFFDIO_WRITEPROTECT_MODE_DONTWAKE: set the flag to avoid waking up * any wait thread after the operation succeeds. * * NOTE: Write protecting a region (WP=1) is unrelated to page faults, * therefore DONTWAKE flag is meaningless with WP=1. Removing write * protection (WP=0) in response to a page fault wakes the faulting * task unless DONTWAKE is set. */ #define UFFDIO_WRITEPROTECT_MODE_WP ((__u64)1<<0) #define UFFDIO_WRITEPROTECT_MODE_DONTWAKE ((__u64)1<<1) __u64 mode; }; #endif /* _LINUX_USERFAULTFD_H */ linux/sctp.h000064400000106232151027430560007034 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* SCTP kernel implementation * (C) Copyright IBM Corp. 2001, 2004 * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2002 Intel Corp. * * This file is part of the SCTP kernel implementation * * This header represents the structures and constants needed to support * the SCTP Extension to the Sockets API. * * This SCTP implementation is free software; * you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This SCTP implementation is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied * ************************ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU CC; see the file COPYING. If not, see * . * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers * * Or submit a bug report through the following website: * http://www.sf.net/projects/lksctp * * Written or modified by: * La Monte H.P. Yarroll * R. Stewart * K. Morneau * Q. Xie * Karl Knutson * Jon Grimm * Daisy Chang * Ryan Layer * Ardelle Fan * Sridhar Samudrala * Inaky Perez-Gonzalez * Vlad Yasevich * * Any bugs reported given to us we will try to fix... any fixes shared will * be incorporated into the next SCTP release. */ #ifndef _SCTP_H #define _SCTP_H #include #include typedef __s32 sctp_assoc_t; #define SCTP_FUTURE_ASSOC 0 #define SCTP_CURRENT_ASSOC 1 #define SCTP_ALL_ASSOC 2 /* The following symbols come from the Sockets API Extensions for * SCTP . */ #define SCTP_RTOINFO 0 #define SCTP_ASSOCINFO 1 #define SCTP_INITMSG 2 #define SCTP_NODELAY 3 /* Get/set nodelay option. */ #define SCTP_AUTOCLOSE 4 #define SCTP_SET_PEER_PRIMARY_ADDR 5 #define SCTP_PRIMARY_ADDR 6 #define SCTP_ADAPTATION_LAYER 7 #define SCTP_DISABLE_FRAGMENTS 8 #define SCTP_PEER_ADDR_PARAMS 9 #define SCTP_DEFAULT_SEND_PARAM 10 #define SCTP_EVENTS 11 #define SCTP_I_WANT_MAPPED_V4_ADDR 12 /* Turn on/off mapped v4 addresses */ #define SCTP_MAXSEG 13 /* Get/set maximum fragment. */ #define SCTP_STATUS 14 #define SCTP_GET_PEER_ADDR_INFO 15 #define SCTP_DELAYED_ACK_TIME 16 #define SCTP_DELAYED_ACK SCTP_DELAYED_ACK_TIME #define SCTP_DELAYED_SACK SCTP_DELAYED_ACK_TIME #define SCTP_CONTEXT 17 #define SCTP_FRAGMENT_INTERLEAVE 18 #define SCTP_PARTIAL_DELIVERY_POINT 19 /* Set/Get partial delivery point */ #define SCTP_MAX_BURST 20 /* Set/Get max burst */ #define SCTP_AUTH_CHUNK 21 /* Set only: add a chunk type to authenticate */ #define SCTP_HMAC_IDENT 22 #define SCTP_AUTH_KEY 23 #define SCTP_AUTH_ACTIVE_KEY 24 #define SCTP_AUTH_DELETE_KEY 25 #define SCTP_PEER_AUTH_CHUNKS 26 /* Read only */ #define SCTP_LOCAL_AUTH_CHUNKS 27 /* Read only */ #define SCTP_GET_ASSOC_NUMBER 28 /* Read only */ #define SCTP_GET_ASSOC_ID_LIST 29 /* Read only */ #define SCTP_AUTO_ASCONF 30 #define SCTP_PEER_ADDR_THLDS 31 #define SCTP_RECVRCVINFO 32 #define SCTP_RECVNXTINFO 33 #define SCTP_DEFAULT_SNDINFO 34 #define SCTP_AUTH_DEACTIVATE_KEY 35 #define SCTP_REUSE_PORT 36 #define SCTP_PEER_ADDR_THLDS_V2 37 /* Internal Socket Options. Some of the sctp library functions are * implemented using these socket options. */ #define SCTP_SOCKOPT_BINDX_ADD 100 /* BINDX requests for adding addrs */ #define SCTP_SOCKOPT_BINDX_REM 101 /* BINDX requests for removing addrs. */ #define SCTP_SOCKOPT_PEELOFF 102 /* peel off association. */ /* Options 104-106 are deprecated and removed. Do not use this space */ #define SCTP_SOCKOPT_CONNECTX_OLD 107 /* CONNECTX old requests. */ #define SCTP_GET_PEER_ADDRS 108 /* Get all peer address. */ #define SCTP_GET_LOCAL_ADDRS 109 /* Get all local address. */ #define SCTP_SOCKOPT_CONNECTX 110 /* CONNECTX requests. */ #define SCTP_SOCKOPT_CONNECTX3 111 /* CONNECTX requests (updated) */ #define SCTP_GET_ASSOC_STATS 112 /* Read only */ #define SCTP_PR_SUPPORTED 113 #define SCTP_DEFAULT_PRINFO 114 #define SCTP_PR_ASSOC_STATUS 115 #define SCTP_PR_STREAM_STATUS 116 #define SCTP_RECONFIG_SUPPORTED 117 #define SCTP_ENABLE_STREAM_RESET 118 #define SCTP_RESET_STREAMS 119 #define SCTP_RESET_ASSOC 120 #define SCTP_ADD_STREAMS 121 #define SCTP_SOCKOPT_PEELOFF_FLAGS 122 #define SCTP_STREAM_SCHEDULER 123 #define SCTP_STREAM_SCHEDULER_VALUE 124 #define SCTP_INTERLEAVING_SUPPORTED 125 #define SCTP_SENDMSG_CONNECT 126 #define SCTP_EVENT 127 #define SCTP_ASCONF_SUPPORTED 128 #define SCTP_AUTH_SUPPORTED 129 #define SCTP_ECN_SUPPORTED 130 #define SCTP_EXPOSE_POTENTIALLY_FAILED_STATE 131 #define SCTP_EXPOSE_PF_STATE SCTP_EXPOSE_POTENTIALLY_FAILED_STATE #define SCTP_REMOTE_UDP_ENCAPS_PORT 132 #define SCTP_PLPMTUD_PROBE_INTERVAL 133 /* PR-SCTP policies */ #define SCTP_PR_SCTP_NONE 0x0000 #define SCTP_PR_SCTP_TTL 0x0010 #define SCTP_PR_SCTP_RTX 0x0020 #define SCTP_PR_SCTP_PRIO 0x0030 #define SCTP_PR_SCTP_MAX SCTP_PR_SCTP_PRIO #define SCTP_PR_SCTP_MASK 0x0030 #define __SCTP_PR_INDEX(x) ((x >> 4) - 1) #define SCTP_PR_INDEX(x) __SCTP_PR_INDEX(SCTP_PR_SCTP_ ## x) #define SCTP_PR_POLICY(x) ((x) & SCTP_PR_SCTP_MASK) #define SCTP_PR_SET_POLICY(flags, x) \ do { \ flags &= ~SCTP_PR_SCTP_MASK; \ flags |= x; \ } while (0) #define SCTP_PR_TTL_ENABLED(x) (SCTP_PR_POLICY(x) == SCTP_PR_SCTP_TTL) #define SCTP_PR_RTX_ENABLED(x) (SCTP_PR_POLICY(x) == SCTP_PR_SCTP_RTX) #define SCTP_PR_PRIO_ENABLED(x) (SCTP_PR_POLICY(x) == SCTP_PR_SCTP_PRIO) /* For enable stream reset */ #define SCTP_ENABLE_RESET_STREAM_REQ 0x01 #define SCTP_ENABLE_RESET_ASSOC_REQ 0x02 #define SCTP_ENABLE_CHANGE_ASSOC_REQ 0x04 #define SCTP_ENABLE_STRRESET_MASK 0x07 #define SCTP_STREAM_RESET_INCOMING 0x01 #define SCTP_STREAM_RESET_OUTGOING 0x02 /* These are bit fields for msghdr->msg_flags. See section 5.1. */ /* On user space Linux, these live in as an enum. */ enum sctp_msg_flags { MSG_NOTIFICATION = 0x8000, #define MSG_NOTIFICATION MSG_NOTIFICATION }; /* 5.3.1 SCTP Initiation Structure (SCTP_INIT) * * This cmsghdr structure provides information for initializing new * SCTP associations with sendmsg(). The SCTP_INITMSG socket option * uses this same data structure. This structure is not used for * recvmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ---------------------- * IPPROTO_SCTP SCTP_INIT struct sctp_initmsg */ struct sctp_initmsg { __u16 sinit_num_ostreams; __u16 sinit_max_instreams; __u16 sinit_max_attempts; __u16 sinit_max_init_timeo; }; /* 5.3.2 SCTP Header Information Structure (SCTP_SNDRCV) * * This cmsghdr structure specifies SCTP options for sendmsg() and * describes SCTP header information about a received message through * recvmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ---------------------- * IPPROTO_SCTP SCTP_SNDRCV struct sctp_sndrcvinfo */ struct sctp_sndrcvinfo { __u16 sinfo_stream; __u16 sinfo_ssn; __u16 sinfo_flags; __u32 sinfo_ppid; __u32 sinfo_context; __u32 sinfo_timetolive; __u32 sinfo_tsn; __u32 sinfo_cumtsn; sctp_assoc_t sinfo_assoc_id; }; /* 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO) * * This cmsghdr structure specifies SCTP options for sendmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ------------------- * IPPROTO_SCTP SCTP_SNDINFO struct sctp_sndinfo */ struct sctp_sndinfo { __u16 snd_sid; __u16 snd_flags; __u32 snd_ppid; __u32 snd_context; sctp_assoc_t snd_assoc_id; }; /* 5.3.5 SCTP Receive Information Structure (SCTP_RCVINFO) * * This cmsghdr structure describes SCTP receive information * about a received message through recvmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ------------------- * IPPROTO_SCTP SCTP_RCVINFO struct sctp_rcvinfo */ struct sctp_rcvinfo { __u16 rcv_sid; __u16 rcv_ssn; __u16 rcv_flags; __u32 rcv_ppid; __u32 rcv_tsn; __u32 rcv_cumtsn; __u32 rcv_context; sctp_assoc_t rcv_assoc_id; }; /* 5.3.6 SCTP Next Receive Information Structure (SCTP_NXTINFO) * * This cmsghdr structure describes SCTP receive information * of the next message that will be delivered through recvmsg() * if this information is already available when delivering * the current message. * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ------------------- * IPPROTO_SCTP SCTP_NXTINFO struct sctp_nxtinfo */ struct sctp_nxtinfo { __u16 nxt_sid; __u16 nxt_flags; __u32 nxt_ppid; __u32 nxt_length; sctp_assoc_t nxt_assoc_id; }; /* 5.3.7 SCTP PR-SCTP Information Structure (SCTP_PRINFO) * * This cmsghdr structure specifies SCTP options for sendmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ------------------- * IPPROTO_SCTP SCTP_PRINFO struct sctp_prinfo */ struct sctp_prinfo { __u16 pr_policy; __u32 pr_value; }; /* 5.3.8 SCTP AUTH Information Structure (SCTP_AUTHINFO) * * This cmsghdr structure specifies SCTP options for sendmsg(). * * cmsg_level cmsg_type cmsg_data[] * ------------ ------------ ------------------- * IPPROTO_SCTP SCTP_AUTHINFO struct sctp_authinfo */ struct sctp_authinfo { __u16 auth_keynumber; }; /* * sinfo_flags: 16 bits (unsigned integer) * * This field may contain any of the following flags and is composed of * a bitwise OR of these values. */ enum sctp_sinfo_flags { SCTP_UNORDERED = (1 << 0), /* Send/receive message unordered. */ SCTP_ADDR_OVER = (1 << 1), /* Override the primary destination. */ SCTP_ABORT = (1 << 2), /* Send an ABORT message to the peer. */ SCTP_SACK_IMMEDIATELY = (1 << 3), /* SACK should be sent without delay. */ /* 2 bits here have been used by SCTP_PR_SCTP_MASK */ SCTP_SENDALL = (1 << 6), SCTP_PR_SCTP_ALL = (1 << 7), SCTP_NOTIFICATION = MSG_NOTIFICATION, /* Next message is not user msg but notification. */ SCTP_EOF = MSG_FIN, /* Initiate graceful shutdown process. */ }; typedef union { __u8 raw; struct sctp_initmsg init; struct sctp_sndrcvinfo sndrcv; } sctp_cmsg_data_t; /* These are cmsg_types. */ typedef enum sctp_cmsg_type { SCTP_INIT, /* 5.2.1 SCTP Initiation Structure */ #define SCTP_INIT SCTP_INIT SCTP_SNDRCV, /* 5.2.2 SCTP Header Information Structure */ #define SCTP_SNDRCV SCTP_SNDRCV SCTP_SNDINFO, /* 5.3.4 SCTP Send Information Structure */ #define SCTP_SNDINFO SCTP_SNDINFO SCTP_RCVINFO, /* 5.3.5 SCTP Receive Information Structure */ #define SCTP_RCVINFO SCTP_RCVINFO SCTP_NXTINFO, /* 5.3.6 SCTP Next Receive Information Structure */ #define SCTP_NXTINFO SCTP_NXTINFO SCTP_PRINFO, /* 5.3.7 SCTP PR-SCTP Information Structure */ #define SCTP_PRINFO SCTP_PRINFO SCTP_AUTHINFO, /* 5.3.8 SCTP AUTH Information Structure */ #define SCTP_AUTHINFO SCTP_AUTHINFO SCTP_DSTADDRV4, /* 5.3.9 SCTP Destination IPv4 Address Structure */ #define SCTP_DSTADDRV4 SCTP_DSTADDRV4 SCTP_DSTADDRV6, /* 5.3.10 SCTP Destination IPv6 Address Structure */ #define SCTP_DSTADDRV6 SCTP_DSTADDRV6 } sctp_cmsg_t; /* * 5.3.1.1 SCTP_ASSOC_CHANGE * * Communication notifications inform the ULP that an SCTP association * has either begun or ended. The identifier for a new association is * provided by this notificaion. The notification information has the * following format: * */ struct sctp_assoc_change { __u16 sac_type; __u16 sac_flags; __u32 sac_length; __u16 sac_state; __u16 sac_error; __u16 sac_outbound_streams; __u16 sac_inbound_streams; sctp_assoc_t sac_assoc_id; __u8 sac_info[0]; }; /* * sac_state: 32 bits (signed integer) * * This field holds one of a number of values that communicate the * event that happened to the association. They include: * * Note: The following state names deviate from the API draft as * the names clash too easily with other kernel symbols. */ enum sctp_sac_state { SCTP_COMM_UP, SCTP_COMM_LOST, SCTP_RESTART, SCTP_SHUTDOWN_COMP, SCTP_CANT_STR_ASSOC, }; /* * 5.3.1.2 SCTP_PEER_ADDR_CHANGE * * When a destination address on a multi-homed peer encounters a change * an interface details event is sent. The information has the * following structure: */ struct sctp_paddr_change { __u16 spc_type; __u16 spc_flags; __u32 spc_length; struct sockaddr_storage spc_aaddr; int spc_state; int spc_error; sctp_assoc_t spc_assoc_id; } __attribute__((packed, aligned(4))); /* * spc_state: 32 bits (signed integer) * * This field holds one of a number of values that communicate the * event that happened to the address. They include: */ enum sctp_spc_state { SCTP_ADDR_AVAILABLE, SCTP_ADDR_UNREACHABLE, SCTP_ADDR_REMOVED, SCTP_ADDR_ADDED, SCTP_ADDR_MADE_PRIM, SCTP_ADDR_CONFIRMED, SCTP_ADDR_POTENTIALLY_FAILED, #define SCTP_ADDR_PF SCTP_ADDR_POTENTIALLY_FAILED }; /* * 5.3.1.3 SCTP_REMOTE_ERROR * * A remote peer may send an Operational Error message to its peer. * This message indicates a variety of error conditions on an * association. The entire error TLV as it appears on the wire is * included in a SCTP_REMOTE_ERROR event. Please refer to the SCTP * specification [SCTP] and any extensions for a list of possible * error formats. SCTP error TLVs have the format: */ struct sctp_remote_error { __u16 sre_type; __u16 sre_flags; __u32 sre_length; __be16 sre_error; sctp_assoc_t sre_assoc_id; __u8 sre_data[0]; }; /* * 5.3.1.4 SCTP_SEND_FAILED * * If SCTP cannot deliver a message it may return the message as a * notification. */ struct sctp_send_failed { __u16 ssf_type; __u16 ssf_flags; __u32 ssf_length; __u32 ssf_error; struct sctp_sndrcvinfo ssf_info; sctp_assoc_t ssf_assoc_id; __u8 ssf_data[0]; }; struct sctp_send_failed_event { __u16 ssf_type; __u16 ssf_flags; __u32 ssf_length; __u32 ssf_error; struct sctp_sndinfo ssfe_info; sctp_assoc_t ssf_assoc_id; __u8 ssf_data[0]; }; /* * ssf_flags: 16 bits (unsigned integer) * * The flag value will take one of the following values * * SCTP_DATA_UNSENT - Indicates that the data was never put on * the wire. * * SCTP_DATA_SENT - Indicates that the data was put on the wire. * Note that this does not necessarily mean that the * data was (or was not) successfully delivered. */ enum sctp_ssf_flags { SCTP_DATA_UNSENT, SCTP_DATA_SENT, }; /* * 5.3.1.5 SCTP_SHUTDOWN_EVENT * * When a peer sends a SHUTDOWN, SCTP delivers this notification to * inform the application that it should cease sending data. */ struct sctp_shutdown_event { __u16 sse_type; __u16 sse_flags; __u32 sse_length; sctp_assoc_t sse_assoc_id; }; /* * 5.3.1.6 SCTP_ADAPTATION_INDICATION * * When a peer sends a Adaptation Layer Indication parameter , SCTP * delivers this notification to inform the application * that of the peers requested adaptation layer. */ struct sctp_adaptation_event { __u16 sai_type; __u16 sai_flags; __u32 sai_length; __u32 sai_adaptation_ind; sctp_assoc_t sai_assoc_id; }; /* * 5.3.1.7 SCTP_PARTIAL_DELIVERY_EVENT * * When a receiver is engaged in a partial delivery of a * message this notification will be used to indicate * various events. */ struct sctp_pdapi_event { __u16 pdapi_type; __u16 pdapi_flags; __u32 pdapi_length; __u32 pdapi_indication; sctp_assoc_t pdapi_assoc_id; __u32 pdapi_stream; __u32 pdapi_seq; }; enum { SCTP_PARTIAL_DELIVERY_ABORTED=0, }; /* * 5.3.1.8. SCTP_AUTHENTICATION_EVENT * * When a receiver is using authentication this message will provide * notifications regarding new keys being made active as well as errors. */ struct sctp_authkey_event { __u16 auth_type; __u16 auth_flags; __u32 auth_length; __u16 auth_keynumber; __u16 auth_altkeynumber; __u32 auth_indication; sctp_assoc_t auth_assoc_id; }; enum { SCTP_AUTH_NEW_KEY, #define SCTP_AUTH_NEWKEY SCTP_AUTH_NEW_KEY /* compatible with before */ SCTP_AUTH_FREE_KEY, SCTP_AUTH_NO_AUTH, }; /* * 6.1.9. SCTP_SENDER_DRY_EVENT * * When the SCTP stack has no more user data to send or retransmit, this * notification is given to the user. Also, at the time when a user app * subscribes to this event, if there is no data to be sent or * retransmit, the stack will immediately send up this notification. */ struct sctp_sender_dry_event { __u16 sender_dry_type; __u16 sender_dry_flags; __u32 sender_dry_length; sctp_assoc_t sender_dry_assoc_id; }; #define SCTP_STREAM_RESET_INCOMING_SSN 0x0001 #define SCTP_STREAM_RESET_OUTGOING_SSN 0x0002 #define SCTP_STREAM_RESET_DENIED 0x0004 #define SCTP_STREAM_RESET_FAILED 0x0008 struct sctp_stream_reset_event { __u16 strreset_type; __u16 strreset_flags; __u32 strreset_length; sctp_assoc_t strreset_assoc_id; __u16 strreset_stream_list[]; }; #define SCTP_ASSOC_RESET_DENIED 0x0004 #define SCTP_ASSOC_RESET_FAILED 0x0008 struct sctp_assoc_reset_event { __u16 assocreset_type; __u16 assocreset_flags; __u32 assocreset_length; sctp_assoc_t assocreset_assoc_id; __u32 assocreset_local_tsn; __u32 assocreset_remote_tsn; }; #define SCTP_ASSOC_CHANGE_DENIED 0x0004 #define SCTP_ASSOC_CHANGE_FAILED 0x0008 #define SCTP_STREAM_CHANGE_DENIED SCTP_ASSOC_CHANGE_DENIED #define SCTP_STREAM_CHANGE_FAILED SCTP_ASSOC_CHANGE_FAILED struct sctp_stream_change_event { __u16 strchange_type; __u16 strchange_flags; __u32 strchange_length; sctp_assoc_t strchange_assoc_id; __u16 strchange_instrms; __u16 strchange_outstrms; }; /* * Described in Section 7.3 * Ancillary Data and Notification Interest Options */ struct sctp_event_subscribe { __u8 sctp_data_io_event; __u8 sctp_association_event; __u8 sctp_address_event; __u8 sctp_send_failure_event; __u8 sctp_peer_error_event; __u8 sctp_shutdown_event; __u8 sctp_partial_delivery_event; __u8 sctp_adaptation_layer_event; __u8 sctp_authentication_event; __u8 sctp_sender_dry_event; __u8 sctp_stream_reset_event; __u8 sctp_assoc_reset_event; __u8 sctp_stream_change_event; __u8 sctp_send_failure_event_event; }; /* * 5.3.1 SCTP Notification Structure * * The notification structure is defined as the union of all * notification types. * */ union sctp_notification { struct { __u16 sn_type; /* Notification type. */ __u16 sn_flags; __u32 sn_length; } sn_header; struct sctp_assoc_change sn_assoc_change; struct sctp_paddr_change sn_paddr_change; struct sctp_remote_error sn_remote_error; struct sctp_send_failed sn_send_failed; struct sctp_shutdown_event sn_shutdown_event; struct sctp_adaptation_event sn_adaptation_event; struct sctp_pdapi_event sn_pdapi_event; struct sctp_authkey_event sn_authkey_event; struct sctp_sender_dry_event sn_sender_dry_event; struct sctp_stream_reset_event sn_strreset_event; struct sctp_assoc_reset_event sn_assocreset_event; struct sctp_stream_change_event sn_strchange_event; struct sctp_send_failed_event sn_send_failed_event; }; /* Section 5.3.1 * All standard values for sn_type flags are greater than 2^15. * Values from 2^15 and down are reserved. */ enum sctp_sn_type { SCTP_SN_TYPE_BASE = (1<<15), SCTP_DATA_IO_EVENT = SCTP_SN_TYPE_BASE, #define SCTP_DATA_IO_EVENT SCTP_DATA_IO_EVENT SCTP_ASSOC_CHANGE, #define SCTP_ASSOC_CHANGE SCTP_ASSOC_CHANGE SCTP_PEER_ADDR_CHANGE, #define SCTP_PEER_ADDR_CHANGE SCTP_PEER_ADDR_CHANGE SCTP_SEND_FAILED, #define SCTP_SEND_FAILED SCTP_SEND_FAILED SCTP_REMOTE_ERROR, #define SCTP_REMOTE_ERROR SCTP_REMOTE_ERROR SCTP_SHUTDOWN_EVENT, #define SCTP_SHUTDOWN_EVENT SCTP_SHUTDOWN_EVENT SCTP_PARTIAL_DELIVERY_EVENT, #define SCTP_PARTIAL_DELIVERY_EVENT SCTP_PARTIAL_DELIVERY_EVENT SCTP_ADAPTATION_INDICATION, #define SCTP_ADAPTATION_INDICATION SCTP_ADAPTATION_INDICATION SCTP_AUTHENTICATION_EVENT, #define SCTP_AUTHENTICATION_INDICATION SCTP_AUTHENTICATION_EVENT SCTP_SENDER_DRY_EVENT, #define SCTP_SENDER_DRY_EVENT SCTP_SENDER_DRY_EVENT SCTP_STREAM_RESET_EVENT, #define SCTP_STREAM_RESET_EVENT SCTP_STREAM_RESET_EVENT SCTP_ASSOC_RESET_EVENT, #define SCTP_ASSOC_RESET_EVENT SCTP_ASSOC_RESET_EVENT SCTP_STREAM_CHANGE_EVENT, #define SCTP_STREAM_CHANGE_EVENT SCTP_STREAM_CHANGE_EVENT SCTP_SEND_FAILED_EVENT, #define SCTP_SEND_FAILED_EVENT SCTP_SEND_FAILED_EVENT SCTP_SN_TYPE_MAX = SCTP_SEND_FAILED_EVENT, #define SCTP_SN_TYPE_MAX SCTP_SN_TYPE_MAX }; /* Notification error codes used to fill up the error fields in some * notifications. * SCTP_PEER_ADDRESS_CHAGE : spc_error * SCTP_ASSOC_CHANGE : sac_error * These names should be potentially included in the draft 04 of the SCTP * sockets API specification. */ typedef enum sctp_sn_error { SCTP_FAILED_THRESHOLD, SCTP_RECEIVED_SACK, SCTP_HEARTBEAT_SUCCESS, SCTP_RESPONSE_TO_USER_REQ, SCTP_INTERNAL_ERROR, SCTP_SHUTDOWN_GUARD_EXPIRES, SCTP_PEER_FAULTY, } sctp_sn_error_t; /* * 7.1.1 Retransmission Timeout Parameters (SCTP_RTOINFO) * * The protocol parameters used to initialize and bound retransmission * timeout (RTO) are tunable. See [SCTP] for more information on how * these parameters are used in RTO calculation. */ struct sctp_rtoinfo { sctp_assoc_t srto_assoc_id; __u32 srto_initial; __u32 srto_max; __u32 srto_min; }; /* * 7.1.2 Association Parameters (SCTP_ASSOCINFO) * * This option is used to both examine and set various association and * endpoint parameters. */ struct sctp_assocparams { sctp_assoc_t sasoc_assoc_id; __u16 sasoc_asocmaxrxt; __u16 sasoc_number_peer_destinations; __u32 sasoc_peer_rwnd; __u32 sasoc_local_rwnd; __u32 sasoc_cookie_life; }; /* * 7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR) * * Requests that the peer mark the enclosed address as the association * primary. The enclosed address must be one of the association's * locally bound addresses. The following structure is used to make a * set primary request: */ struct sctp_setpeerprim { sctp_assoc_t sspp_assoc_id; struct sockaddr_storage sspp_addr; } __attribute__((packed, aligned(4))); /* * 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR) * * Requests that the local SCTP stack use the enclosed peer address as * the association primary. The enclosed address must be one of the * association peer's addresses. The following structure is used to * make a set peer primary request: */ struct sctp_prim { sctp_assoc_t ssp_assoc_id; struct sockaddr_storage ssp_addr; } __attribute__((packed, aligned(4))); /* For backward compatibility use, define the old name too */ #define sctp_setprim sctp_prim /* * 7.1.11 Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER) * * Requests that the local endpoint set the specified Adaptation Layer * Indication parameter for all future INIT and INIT-ACK exchanges. */ struct sctp_setadaptation { __u32 ssb_adaptation_ind; }; /* * 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS) * * Applications can enable or disable heartbeats for any peer address * of an association, modify an address's heartbeat interval, force a * heartbeat to be sent immediately, and adjust the address's maximum * number of retransmissions sent before an address is considered * unreachable. The following structure is used to access and modify an * address's parameters: */ enum sctp_spp_flags { SPP_HB_ENABLE = 1<<0, /*Enable heartbeats*/ SPP_HB_DISABLE = 1<<1, /*Disable heartbeats*/ SPP_HB = SPP_HB_ENABLE | SPP_HB_DISABLE, SPP_HB_DEMAND = 1<<2, /*Send heartbeat immediately*/ SPP_PMTUD_ENABLE = 1<<3, /*Enable PMTU discovery*/ SPP_PMTUD_DISABLE = 1<<4, /*Disable PMTU discovery*/ SPP_PMTUD = SPP_PMTUD_ENABLE | SPP_PMTUD_DISABLE, SPP_SACKDELAY_ENABLE = 1<<5, /*Enable SACK*/ SPP_SACKDELAY_DISABLE = 1<<6, /*Disable SACK*/ SPP_SACKDELAY = SPP_SACKDELAY_ENABLE | SPP_SACKDELAY_DISABLE, SPP_HB_TIME_IS_ZERO = 1<<7, /* Set HB delay to 0 */ SPP_IPV6_FLOWLABEL = 1<<8, SPP_DSCP = 1<<9, }; struct sctp_paddrparams { sctp_assoc_t spp_assoc_id; struct sockaddr_storage spp_address; __u32 spp_hbinterval; __u16 spp_pathmaxrxt; __u32 spp_pathmtu; __u32 spp_sackdelay; __u32 spp_flags; __u32 spp_ipv6_flowlabel; __u8 spp_dscp; } __attribute__((packed, aligned(4))); /* * 7.1.18. Add a chunk that must be authenticated (SCTP_AUTH_CHUNK) * * This set option adds a chunk type that the user is requesting to be * received only in an authenticated way. Changes to the list of chunks * will only effect future associations on the socket. */ struct sctp_authchunk { __u8 sauth_chunk; }; /* * 7.1.19. Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT) * * This option gets or sets the list of HMAC algorithms that the local * endpoint requires the peer to use. */ /* This here is only used by user space as is. It might not be a good idea * to export/reveal the whole structure with reserved fields etc. */ enum { SCTP_AUTH_HMAC_ID_SHA1 = 1, SCTP_AUTH_HMAC_ID_SHA256 = 3, }; struct sctp_hmacalgo { __u32 shmac_num_idents; __u16 shmac_idents[]; }; /* Sadly, user and kernel space have different names for * this structure member, so this is to not break anything. */ #define shmac_number_of_idents shmac_num_idents /* * 7.1.20. Set a shared key (SCTP_AUTH_KEY) * * This option will set a shared secret key which is used to build an * association shared key. */ struct sctp_authkey { sctp_assoc_t sca_assoc_id; __u16 sca_keynumber; __u16 sca_keylength; __u8 sca_key[]; }; /* * 7.1.21. Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY) * * This option will get or set the active shared key to be used to build * the association shared key. */ struct sctp_authkeyid { sctp_assoc_t scact_assoc_id; __u16 scact_keynumber; }; /* * 7.1.23. Get or set delayed ack timer (SCTP_DELAYED_SACK) * * This option will effect the way delayed acks are performed. This * option allows you to get or set the delayed ack time, in * milliseconds. It also allows changing the delayed ack frequency. * Changing the frequency to 1 disables the delayed sack algorithm. If * the assoc_id is 0, then this sets or gets the endpoints default * values. If the assoc_id field is non-zero, then the set or get * effects the specified association for the one to many model (the * assoc_id field is ignored by the one to one model). Note that if * sack_delay or sack_freq are 0 when setting this option, then the * current values will remain unchanged. */ struct sctp_sack_info { sctp_assoc_t sack_assoc_id; uint32_t sack_delay; uint32_t sack_freq; }; struct sctp_assoc_value { sctp_assoc_t assoc_id; uint32_t assoc_value; }; struct sctp_stream_value { sctp_assoc_t assoc_id; uint16_t stream_id; uint16_t stream_value; }; /* * 7.2.2 Peer Address Information * * Applications can retrieve information about a specific peer address * of an association, including its reachability state, congestion * window, and retransmission timer values. This information is * read-only. The following structure is used to access this * information: */ struct sctp_paddrinfo { sctp_assoc_t spinfo_assoc_id; struct sockaddr_storage spinfo_address; __s32 spinfo_state; __u32 spinfo_cwnd; __u32 spinfo_srtt; __u32 spinfo_rto; __u32 spinfo_mtu; } __attribute__((packed, aligned(4))); /* Peer addresses's state. */ /* UNKNOWN: Peer address passed by the upper layer in sendmsg or connect[x] * calls. * UNCONFIRMED: Peer address received in INIT/INIT-ACK address parameters. * Not yet confirmed by a heartbeat and not available for data * transfers. * ACTIVE : Peer address confirmed, active and available for data transfers. * INACTIVE: Peer address inactive and not available for data transfers. */ enum sctp_spinfo_state { SCTP_INACTIVE, SCTP_PF, #define SCTP_POTENTIALLY_FAILED SCTP_PF SCTP_ACTIVE, SCTP_UNCONFIRMED, SCTP_UNKNOWN = 0xffff /* Value used for transport state unknown */ }; /* * 7.2.1 Association Status (SCTP_STATUS) * * Applications can retrieve current status information about an * association, including association state, peer receiver window size, * number of unacked data chunks, and number of data chunks pending * receipt. This information is read-only. The following structure is * used to access this information: */ struct sctp_status { sctp_assoc_t sstat_assoc_id; __s32 sstat_state; __u32 sstat_rwnd; __u16 sstat_unackdata; __u16 sstat_penddata; __u16 sstat_instrms; __u16 sstat_outstrms; __u32 sstat_fragmentation_point; struct sctp_paddrinfo sstat_primary; }; /* * 7.2.3. Get the list of chunks the peer requires to be authenticated * (SCTP_PEER_AUTH_CHUNKS) * * This option gets a list of chunks for a specified association that * the peer requires to be received authenticated only. */ struct sctp_authchunks { sctp_assoc_t gauth_assoc_id; __u32 gauth_number_of_chunks; uint8_t gauth_chunks[]; }; /* The broken spelling has been released already in lksctp-tools header, * so don't break anyone, now that it's fixed. */ #define guth_number_of_chunks gauth_number_of_chunks /* Association states. */ enum sctp_sstat_state { SCTP_EMPTY = 0, SCTP_CLOSED = 1, SCTP_COOKIE_WAIT = 2, SCTP_COOKIE_ECHOED = 3, SCTP_ESTABLISHED = 4, SCTP_SHUTDOWN_PENDING = 5, SCTP_SHUTDOWN_SENT = 6, SCTP_SHUTDOWN_RECEIVED = 7, SCTP_SHUTDOWN_ACK_SENT = 8, }; /* * 8.2.6. Get the Current Identifiers of Associations * (SCTP_GET_ASSOC_ID_LIST) * * This option gets the current list of SCTP association identifiers of * the SCTP associations handled by a one-to-many style socket. */ struct sctp_assoc_ids { __u32 gaids_number_of_ids; sctp_assoc_t gaids_assoc_id[]; }; /* * 8.3, 8.5 get all peer/local addresses in an association. * This parameter struct is used by SCTP_GET_PEER_ADDRS and * SCTP_GET_LOCAL_ADDRS socket options used internally to implement * sctp_getpaddrs() and sctp_getladdrs() API. */ struct sctp_getaddrs_old { sctp_assoc_t assoc_id; int addr_num; struct sockaddr *addrs; }; struct sctp_getaddrs { sctp_assoc_t assoc_id; /*input*/ __u32 addr_num; /*output*/ __u8 addrs[0]; /*output, variable size*/ }; /* A socket user request obtained via SCTP_GET_ASSOC_STATS that retrieves * association stats. All stats are counts except sas_maxrto and * sas_obs_rto_ipaddr. maxrto is the max observed rto + transport since * the last call. Will return 0 when RTO was not update since last call */ struct sctp_assoc_stats { sctp_assoc_t sas_assoc_id; /* Input */ /* Transport of observed max RTO */ struct sockaddr_storage sas_obs_rto_ipaddr; __u64 sas_maxrto; /* Maximum Observed RTO for period */ __u64 sas_isacks; /* SACKs received */ __u64 sas_osacks; /* SACKs sent */ __u64 sas_opackets; /* Packets sent */ __u64 sas_ipackets; /* Packets received */ __u64 sas_rtxchunks; /* Retransmitted Chunks */ __u64 sas_outofseqtsns;/* TSN received > next expected */ __u64 sas_idupchunks; /* Dups received (ordered+unordered) */ __u64 sas_gapcnt; /* Gap Acknowledgements Received */ __u64 sas_ouodchunks; /* Unordered data chunks sent */ __u64 sas_iuodchunks; /* Unordered data chunks received */ __u64 sas_oodchunks; /* Ordered data chunks sent */ __u64 sas_iodchunks; /* Ordered data chunks received */ __u64 sas_octrlchunks; /* Control chunks sent */ __u64 sas_ictrlchunks; /* Control chunks received */ }; /* * 8.1 sctp_bindx() * * The flags parameter is formed from the bitwise OR of zero or more of the * following currently defined flags: */ #define SCTP_BINDX_ADD_ADDR 0x01 #define SCTP_BINDX_REM_ADDR 0x02 /* This is the structure that is passed as an argument(optval) to * getsockopt(SCTP_SOCKOPT_PEELOFF). */ typedef struct { sctp_assoc_t associd; int sd; } sctp_peeloff_arg_t; typedef struct { sctp_peeloff_arg_t p_arg; unsigned flags; } sctp_peeloff_flags_arg_t; /* * Peer Address Thresholds socket option */ struct sctp_paddrthlds { sctp_assoc_t spt_assoc_id; struct sockaddr_storage spt_address; __u16 spt_pathmaxrxt; __u16 spt_pathpfthld; }; /* Use a new structure with spt_pathcpthld for back compatibility */ struct sctp_paddrthlds_v2 { sctp_assoc_t spt_assoc_id; struct sockaddr_storage spt_address; __u16 spt_pathmaxrxt; __u16 spt_pathpfthld; __u16 spt_pathcpthld; }; /* * Socket Option for Getting the Association/Stream-Specific PR-SCTP Status */ struct sctp_prstatus { sctp_assoc_t sprstat_assoc_id; __u16 sprstat_sid; __u16 sprstat_policy; __u64 sprstat_abandoned_unsent; __u64 sprstat_abandoned_sent; }; struct sctp_default_prinfo { sctp_assoc_t pr_assoc_id; __u32 pr_value; __u16 pr_policy; }; struct sctp_info { __u32 sctpi_tag; __u32 sctpi_state; __u32 sctpi_rwnd; __u16 sctpi_unackdata; __u16 sctpi_penddata; __u16 sctpi_instrms; __u16 sctpi_outstrms; __u32 sctpi_fragmentation_point; __u32 sctpi_inqueue; __u32 sctpi_outqueue; __u32 sctpi_overall_error; __u32 sctpi_max_burst; __u32 sctpi_maxseg; __u32 sctpi_peer_rwnd; __u32 sctpi_peer_tag; __u8 sctpi_peer_capable; __u8 sctpi_peer_sack; __u16 __reserved1; /* assoc status info */ __u64 sctpi_isacks; __u64 sctpi_osacks; __u64 sctpi_opackets; __u64 sctpi_ipackets; __u64 sctpi_rtxchunks; __u64 sctpi_outofseqtsns; __u64 sctpi_idupchunks; __u64 sctpi_gapcnt; __u64 sctpi_ouodchunks; __u64 sctpi_iuodchunks; __u64 sctpi_oodchunks; __u64 sctpi_iodchunks; __u64 sctpi_octrlchunks; __u64 sctpi_ictrlchunks; /* primary transport info */ struct sockaddr_storage sctpi_p_address; __s32 sctpi_p_state; __u32 sctpi_p_cwnd; __u32 sctpi_p_srtt; __u32 sctpi_p_rto; __u32 sctpi_p_hbinterval; __u32 sctpi_p_pathmaxrxt; __u32 sctpi_p_sackdelay; __u32 sctpi_p_sackfreq; __u32 sctpi_p_ssthresh; __u32 sctpi_p_partial_bytes_acked; __u32 sctpi_p_flight_size; __u16 sctpi_p_error; __u16 __reserved2; /* sctp sock info */ __u32 sctpi_s_autoclose; __u32 sctpi_s_adaptation_ind; __u32 sctpi_s_pd_point; __u8 sctpi_s_nodelay; __u8 sctpi_s_disable_fragments; __u8 sctpi_s_v4mapped; __u8 sctpi_s_frag_interleave; __u32 sctpi_s_type; __u32 __reserved3; }; struct sctp_reset_streams { sctp_assoc_t srs_assoc_id; uint16_t srs_flags; uint16_t srs_number_streams; /* 0 == ALL */ uint16_t srs_stream_list[]; /* list if srs_num_streams is not 0 */ }; struct sctp_add_streams { sctp_assoc_t sas_assoc_id; uint16_t sas_instrms; uint16_t sas_outstrms; }; struct sctp_event { sctp_assoc_t se_assoc_id; uint16_t se_type; uint8_t se_on; }; struct sctp_udpencaps { sctp_assoc_t sue_assoc_id; struct sockaddr_storage sue_address; uint16_t sue_port; }; /* SCTP Stream schedulers */ enum sctp_sched_type { SCTP_SS_FCFS, SCTP_SS_DEFAULT = SCTP_SS_FCFS, SCTP_SS_PRIO, SCTP_SS_RR, SCTP_SS_MAX = SCTP_SS_RR }; /* Probe Interval socket option */ struct sctp_probeinterval { sctp_assoc_t spi_assoc_id; struct sockaddr_storage spi_address; __u32 spi_interval; }; #endif /* _SCTP_H */ linux/toshiba.h000064400000003612151027430560007512 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* toshiba.h -- Linux driver for accessing the SMM on Toshiba laptops * * Copyright (c) 1996-2000 Jonathan A. Buzzard (jonathan@buzzard.org.uk) * Copyright (c) 2015 Azael Avalos * * Thanks to Juergen Heinzl for the pointers * on making sure the structure is aligned and packed. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * */ #ifndef _LINUX_TOSHIBA_H #define _LINUX_TOSHIBA_H /* * Toshiba modules paths */ #define TOSH_PROC "/proc/toshiba" #define TOSH_DEVICE "/dev/toshiba" #define TOSHIBA_ACPI_PROC "/proc/acpi/toshiba" #define TOSHIBA_ACPI_DEVICE "/dev/toshiba_acpi" /* * Toshiba SMM structure */ typedef struct { unsigned int eax; unsigned int ebx __attribute__ ((packed)); unsigned int ecx __attribute__ ((packed)); unsigned int edx __attribute__ ((packed)); unsigned int esi __attribute__ ((packed)); unsigned int edi __attribute__ ((packed)); } SMMRegisters; /* * IOCTLs (0x90 - 0x91) */ #define TOSH_SMM _IOWR('t', 0x90, SMMRegisters) /* * Convenience toshiba_acpi command. * * The System Configuration Interface (SCI) is opened/closed internally * to avoid userspace of buggy BIOSes. * * The toshiba_acpi module checks whether the eax register is set with * SCI_GET (0xf300) or SCI_SET (0xf400), returning -EINVAL if not. */ #define TOSHIBA_ACPI_SCI _IOWR('t', 0x91, SMMRegisters) #endif /* _LINUX_TOSHIBA_H */ linux/capi.h000064400000006064151027430560007001 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* $Id: capi.h,v 1.4.6.1 2001/09/23 22:25:05 kai Exp $ * * CAPI 2.0 Interface for Linux * * Copyright 1997 by Carsten Paeth (calle@calle.in-berlin.de) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef __LINUX_CAPI_H__ #define __LINUX_CAPI_H__ #include #include #include /* * CAPI_REGISTER */ typedef struct capi_register_params { /* CAPI_REGISTER */ __u32 level3cnt; /* No. of simulatneous user data connections */ __u32 datablkcnt; /* No. of buffered data messages */ __u32 datablklen; /* Size of buffered data messages */ } capi_register_params; #define CAPI_REGISTER _IOW('C',0x01,struct capi_register_params) /* * CAPI_GET_MANUFACTURER */ #define CAPI_MANUFACTURER_LEN 64 #define CAPI_GET_MANUFACTURER _IOWR('C',0x06,int) /* broken: wanted size 64 (CAPI_MANUFACTURER_LEN) */ /* * CAPI_GET_VERSION */ typedef struct capi_version { __u32 majorversion; __u32 minorversion; __u32 majormanuversion; __u32 minormanuversion; } capi_version; #define CAPI_GET_VERSION _IOWR('C',0x07,struct capi_version) /* * CAPI_GET_SERIAL */ #define CAPI_SERIAL_LEN 8 #define CAPI_GET_SERIAL _IOWR('C',0x08,int) /* broken: wanted size 8 (CAPI_SERIAL_LEN) */ /* * CAPI_GET_PROFILE */ typedef struct capi_profile { __u16 ncontroller; /* number of installed controller */ __u16 nbchannel; /* number of B-Channels */ __u32 goptions; /* global options */ __u32 support1; /* B1 protocols support */ __u32 support2; /* B2 protocols support */ __u32 support3; /* B3 protocols support */ __u32 reserved[6]; /* reserved */ __u32 manu[5]; /* manufacturer specific information */ } capi_profile; #define CAPI_GET_PROFILE _IOWR('C',0x09,struct capi_profile) typedef struct capi_manufacturer_cmd { unsigned long cmd; void *data; } capi_manufacturer_cmd; /* * CAPI_MANUFACTURER_CMD */ #define CAPI_MANUFACTURER_CMD _IOWR('C',0x20, struct capi_manufacturer_cmd) /* * CAPI_GET_ERRCODE * capi errcode is set, * if read, write, or ioctl returns EIO, * ioctl returns errcode directly, and in arg, if != 0 */ #define CAPI_GET_ERRCODE _IOR('C',0x21, __u16) /* * CAPI_INSTALLED */ #define CAPI_INSTALLED _IOR('C',0x22, __u16) /* * member contr is input for * CAPI_GET_MANUFACTURER, CAPI_GET_VERSION, CAPI_GET_SERIAL * and CAPI_GET_PROFILE */ typedef union capi_ioctl_struct { __u32 contr; capi_register_params rparams; __u8 manufacturer[CAPI_MANUFACTURER_LEN]; capi_version version; __u8 serial[CAPI_SERIAL_LEN]; capi_profile profile; capi_manufacturer_cmd cmd; __u16 errcode; } capi_ioctl_struct; /* * Middleware extension */ #define CAPIFLAG_HIGHJACKING 0x0001 #define CAPI_GET_FLAGS _IOR('C',0x23, unsigned) #define CAPI_SET_FLAGS _IOR('C',0x24, unsigned) #define CAPI_CLR_FLAGS _IOR('C',0x25, unsigned) #define CAPI_NCCI_OPENCOUNT _IOR('C',0x26, unsigned) #define CAPI_NCCI_GETUNIT _IOR('C',0x27, unsigned) #endif /* __LINUX_CAPI_H__ */ linux/netfilter_ipv4/ipt_ttl.h000064400000000657151027430560012504 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* IP tables module for matching the value of the TTL * (C) 2000 by Harald Welte */ #ifndef _IPT_TTL_H #define _IPT_TTL_H #include enum { IPT_TTL_EQ = 0, /* equals */ IPT_TTL_NE, /* not equals */ IPT_TTL_LT, /* less than */ IPT_TTL_GT, /* greater than */ }; struct ipt_ttl_info { __u8 mode; __u8 ttl; }; #endif linux/netfilter_ipv4/ipt_ah.h000064400000000651151027430560012263 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPT_AH_H #define _IPT_AH_H #include struct ipt_ah { __u32 spis[2]; /* Security Parameter Index */ __u8 invflags; /* Inverse flags */ }; /* Values for "invflags" field in struct ipt_ah. */ #define IPT_AH_INV_SPI 0x01 /* Invert the sense of spi. */ #define IPT_AH_INV_MASK 0x01 /* All possible flags. */ #endif /*_IPT_AH_H*/ linux/netfilter_ipv4/ipt_ECN.h000064400000001605151027430560012300 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* Header file for iptables ipt_ECN target * * (C) 2002 by Harald Welte * * This software is distributed under GNU GPL v2, 1991 * * ipt_ECN.h,v 1.3 2002/05/29 12:17:40 laforge Exp */ #ifndef _IPT_ECN_TARGET_H #define _IPT_ECN_TARGET_H #include #include #define IPT_ECN_IP_MASK (~XT_DSCP_MASK) #define IPT_ECN_OP_SET_IP 0x01 /* set ECN bits of IPv4 header */ #define IPT_ECN_OP_SET_ECE 0x10 /* set ECE bit of TCP header */ #define IPT_ECN_OP_SET_CWR 0x20 /* set CWR bit of TCP header */ #define IPT_ECN_OP_MASK 0xce struct ipt_ECN_info { __u8 operation; /* bitset of operations */ __u8 ip_ect; /* ECT codepoint of IPv4 header, pre-shifted */ union { struct { __u8 ece:1, cwr:1; /* TCP ECT bits */ } tcp; } proto; }; #endif /* _IPT_ECN_TARGET_H */ linux/netfilter_ipv4/ip_tables.h000064400000014767151027430560012776 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * 25-Jul-1998 Major changes to allow for ip chain table * * 3-Jan-2000 Named tables to allow packet selection for different uses. */ /* * Format of an IP firewall descriptor * * src, dst, src_mask, dst_mask are always stored in network byte order. * flags are stored in host byte order (of course). * Port numbers are stored in HOST byte order. */ #ifndef _IPTABLES_H #define _IPTABLES_H #include #include #include #include #define IPT_FUNCTION_MAXNAMELEN XT_FUNCTION_MAXNAMELEN #define IPT_TABLE_MAXNAMELEN XT_TABLE_MAXNAMELEN #define ipt_match xt_match #define ipt_target xt_target #define ipt_table xt_table #define ipt_get_revision xt_get_revision #define ipt_entry_match xt_entry_match #define ipt_entry_target xt_entry_target #define ipt_standard_target xt_standard_target #define ipt_error_target xt_error_target #define ipt_counters xt_counters #define IPT_CONTINUE XT_CONTINUE #define IPT_RETURN XT_RETURN /* This group is older than old (iptables < v1.4.0-rc1~89) */ #include #define ipt_udp xt_udp #define ipt_tcp xt_tcp #define IPT_TCP_INV_SRCPT XT_TCP_INV_SRCPT #define IPT_TCP_INV_DSTPT XT_TCP_INV_DSTPT #define IPT_TCP_INV_FLAGS XT_TCP_INV_FLAGS #define IPT_TCP_INV_OPTION XT_TCP_INV_OPTION #define IPT_TCP_INV_MASK XT_TCP_INV_MASK #define IPT_UDP_INV_SRCPT XT_UDP_INV_SRCPT #define IPT_UDP_INV_DSTPT XT_UDP_INV_DSTPT #define IPT_UDP_INV_MASK XT_UDP_INV_MASK /* The argument to IPT_SO_ADD_COUNTERS. */ #define ipt_counters_info xt_counters_info /* Standard return verdict, or do jump. */ #define IPT_STANDARD_TARGET XT_STANDARD_TARGET /* Error verdict. */ #define IPT_ERROR_TARGET XT_ERROR_TARGET /* fn returns 0 to continue iteration */ #define IPT_MATCH_ITERATE(e, fn, args...) \ XT_MATCH_ITERATE(struct ipt_entry, e, fn, ## args) /* fn returns 0 to continue iteration */ #define IPT_ENTRY_ITERATE(entries, size, fn, args...) \ XT_ENTRY_ITERATE(struct ipt_entry, entries, size, fn, ## args) /* Yes, Virginia, you have to zero the padding. */ struct ipt_ip { /* Source and destination IP addr */ struct in_addr src, dst; /* Mask for src and dest IP addr */ struct in_addr smsk, dmsk; char iniface[IFNAMSIZ], outiface[IFNAMSIZ]; unsigned char iniface_mask[IFNAMSIZ], outiface_mask[IFNAMSIZ]; /* Protocol, 0 = ANY */ __u16 proto; /* Flags word */ __u8 flags; /* Inverse flags */ __u8 invflags; }; /* Values for "flag" field in struct ipt_ip (general ip structure). */ #define IPT_F_FRAG 0x01 /* Set if rule is a fragment rule */ #define IPT_F_GOTO 0x02 /* Set if jump is a goto */ #define IPT_F_MASK 0x03 /* All possible flag bits mask. */ /* Values for "inv" field in struct ipt_ip. */ #define IPT_INV_VIA_IN 0x01 /* Invert the sense of IN IFACE. */ #define IPT_INV_VIA_OUT 0x02 /* Invert the sense of OUT IFACE */ #define IPT_INV_TOS 0x04 /* Invert the sense of TOS. */ #define IPT_INV_SRCIP 0x08 /* Invert the sense of SRC IP. */ #define IPT_INV_DSTIP 0x10 /* Invert the sense of DST OP. */ #define IPT_INV_FRAG 0x20 /* Invert the sense of FRAG. */ #define IPT_INV_PROTO XT_INV_PROTO #define IPT_INV_MASK 0x7F /* All possible flag bits mask. */ /* This structure defines each of the firewall rules. Consists of 3 parts which are 1) general IP header stuff 2) match specific stuff 3) the target to perform if the rule matches */ struct ipt_entry { struct ipt_ip ip; /* Mark with fields that we care about. */ unsigned int nfcache; /* Size of ipt_entry + matches */ __u16 target_offset; /* Size of ipt_entry + matches + target */ __u16 next_offset; /* Back pointer */ unsigned int comefrom; /* Packet and byte counters. */ struct xt_counters counters; /* The matches (if any), then the target. */ unsigned char elems[0]; }; /* * New IP firewall options for [gs]etsockopt at the RAW IP level. * Unlike BSD Linux inherits IP options so you don't have to use a raw * socket for this. Instead we check rights in the calls. * * ATTENTION: check linux/in.h before adding new number here. */ #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_SET_ADD_COUNTERS (IPT_BASE_CTL + 1) #define IPT_SO_SET_MAX IPT_SO_SET_ADD_COUNTERS #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) #define IPT_SO_GET_REVISION_MATCH (IPT_BASE_CTL + 2) #define IPT_SO_GET_REVISION_TARGET (IPT_BASE_CTL + 3) #define IPT_SO_GET_MAX IPT_SO_GET_REVISION_TARGET /* ICMP matching stuff */ struct ipt_icmp { __u8 type; /* type to match */ __u8 code[2]; /* range of code */ __u8 invflags; /* Inverse flags */ }; /* Values for "inv" field for struct ipt_icmp. */ #define IPT_ICMP_INV 0x01 /* Invert the sense of type/code test */ /* The argument to IPT_SO_GET_INFO */ struct ipt_getinfo { /* Which table: caller fills this in. */ char name[XT_TABLE_MAXNAMELEN]; /* Kernel fills these in. */ /* Which hook entry points are valid: bitmask */ unsigned int valid_hooks; /* Hook entry points: one per netfilter hook. */ unsigned int hook_entry[NF_INET_NUMHOOKS]; /* Underflow points. */ unsigned int underflow[NF_INET_NUMHOOKS]; /* Number of entries */ unsigned int num_entries; /* Size of entries. */ unsigned int size; }; /* The argument to IPT_SO_SET_REPLACE. */ struct ipt_replace { /* Which table. */ char name[XT_TABLE_MAXNAMELEN]; /* Which hook entry points are valid: bitmask. You can't change this. */ unsigned int valid_hooks; /* Number of entries */ unsigned int num_entries; /* Total size of new entries */ unsigned int size; /* Hook entry points. */ unsigned int hook_entry[NF_INET_NUMHOOKS]; /* Underflow points. */ unsigned int underflow[NF_INET_NUMHOOKS]; /* Information about old entries: */ /* Number of counters (must be equal to current number of entries). */ unsigned int num_counters; /* The old entries' counters. */ struct xt_counters *counters; /* The entries (hang off end: not really an array). */ struct ipt_entry entries[0]; }; /* The argument to IPT_SO_GET_ENTRIES. */ struct ipt_get_entries { /* Which table: user fills this in. */ char name[XT_TABLE_MAXNAMELEN]; /* User fills this in: total entry size. */ unsigned int size; /* The entries. */ struct ipt_entry entrytable[0]; }; /* Helper functions */ static __inline__ struct xt_entry_target * ipt_get_target(struct ipt_entry *e) { return (void *)e + e->target_offset; } /* * Main firewall chains definitions and global var's definitions. */ #endif /* _IPTABLES_H */ linux/netfilter_ipv4/ipt_CLUSTERIP.h000064400000001465151027430560013251 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPT_CLUSTERIP_H_target #define _IPT_CLUSTERIP_H_target #include #include enum clusterip_hashmode { CLUSTERIP_HASHMODE_SIP = 0, CLUSTERIP_HASHMODE_SIP_SPT, CLUSTERIP_HASHMODE_SIP_SPT_DPT, }; #define CLUSTERIP_HASHMODE_MAX CLUSTERIP_HASHMODE_SIP_SPT_DPT #define CLUSTERIP_MAX_NODES 16 #define CLUSTERIP_FLAG_NEW 0x00000001 struct clusterip_config; struct ipt_clusterip_tgt_info { __u32 flags; /* only relevant for new ones */ __u8 clustermac[ETH_ALEN]; __u16 num_total_nodes; __u16 num_local_nodes; __u16 local_nodes[CLUSTERIP_MAX_NODES]; __u32 hash_mode; __u32 hash_initval; /* Used internally by the kernel */ struct clusterip_config *config; }; #endif /*_IPT_CLUSTERIP_H_target*/ linux/netfilter_ipv4/ipt_LOG.h000064400000001322151027430560012310 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPT_LOG_H #define _IPT_LOG_H #warning "Please update iptables, this file will be removed soon!" /* make sure not to change this without changing netfilter.h:NF_LOG_* (!) */ #define IPT_LOG_TCPSEQ 0x01 /* Log TCP sequence numbers */ #define IPT_LOG_TCPOPT 0x02 /* Log TCP options */ #define IPT_LOG_IPOPT 0x04 /* Log IP options */ #define IPT_LOG_UID 0x08 /* Log UID owning local socket */ #define IPT_LOG_NFLOG 0x10 /* Unsupported, don't reuse */ #define IPT_LOG_MACDECODE 0x20 /* Decode MAC header */ #define IPT_LOG_MASK 0x2f struct ipt_log_info { unsigned char level; unsigned char logflags; char prefix[30]; }; #endif /*_IPT_LOG_H*/ linux/netfilter_ipv4/ipt_TTL.h000064400000000567151027430560012344 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* TTL modification module for IP tables * (C) 2000 by Harald Welte */ #ifndef _IPT_TTL_H #define _IPT_TTL_H #include enum { IPT_TTL_SET = 0, IPT_TTL_INC, IPT_TTL_DEC }; #define IPT_TTL_MAXMODE IPT_TTL_DEC struct ipt_TTL_info { __u8 mode; __u8 ttl; }; #endif linux/netfilter_ipv4/ipt_REJECT.h000064400000000724151027430560012650 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPT_REJECT_H #define _IPT_REJECT_H enum ipt_reject_with { IPT_ICMP_NET_UNREACHABLE, IPT_ICMP_HOST_UNREACHABLE, IPT_ICMP_PROT_UNREACHABLE, IPT_ICMP_PORT_UNREACHABLE, IPT_ICMP_ECHOREPLY, IPT_ICMP_NET_PROHIBITED, IPT_ICMP_HOST_PROHIBITED, IPT_TCP_RESET, IPT_ICMP_ADMIN_PROHIBITED }; struct ipt_reject_info { enum ipt_reject_with with; /* reject type */ }; #endif /*_IPT_REJECT_H*/ linux/netfilter_ipv4/ipt_ecn.h000064400000000657151027430560012446 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _IPT_ECN_H #define _IPT_ECN_H #include #define ipt_ecn_info xt_ecn_info enum { IPT_ECN_IP_MASK = XT_ECN_IP_MASK, IPT_ECN_OP_MATCH_IP = XT_ECN_OP_MATCH_IP, IPT_ECN_OP_MATCH_ECE = XT_ECN_OP_MATCH_ECE, IPT_ECN_OP_MATCH_CWR = XT_ECN_OP_MATCH_CWR, IPT_ECN_OP_MATCH_MASK = XT_ECN_OP_MATCH_MASK, }; #endif /* IPT_ECN_H */ linux/stm.h000064400000002373151027430560006667 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * System Trace Module (STM) userspace interfaces * Copyright (c) 2014, Intel Corporation. * * STM class implements generic infrastructure for System Trace Module devices * as defined in MIPI STPv2 specification. */ #ifndef _LINUX_STM_H #define _LINUX_STM_H #include /* Maximum allowed master and channel values */ #define STP_MASTER_MAX 0xffff #define STP_CHANNEL_MAX 0xffff /** * struct stp_policy_id - identification for the STP policy * @size: size of the structure including real id[] length * @master: assigned master * @channel: first assigned channel * @width: number of requested channels * @id: identification string * * User must calculate the total size of the structure and put it into * @size field, fill out the @id and desired @width. In return, kernel * fills out @master, @channel and @width. */ struct stp_policy_id { __u32 size; __u16 master; __u16 channel; __u16 width; /* padding */ __u16 __reserved_0; __u32 __reserved_1; char id[0]; }; #define STP_POLICY_ID_SET _IOWR('%', 0, struct stp_policy_id) #define STP_POLICY_ID_GET _IOR('%', 1, struct stp_policy_id) #define STP_SET_OPTIONS _IOW('%', 2, __u64) #endif /* _LINUX_STM_H */ linux/fdreg.h000064400000012454151027430560007154 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FDREG_H #define _LINUX_FDREG_H /* * This file contains some defines for the floppy disk controller. * Various sources. Mostly "IBM Microcomputers: A Programmers * Handbook", Sanches and Canton. */ #ifdef FDPATCHES #define FD_IOPORT fdc_state[fdc].address #else /* It would be a lot saner just to force fdc_state[fdc].address to always be set ! FIXME */ #define FD_IOPORT 0x3f0 #endif /* Fd controller regs. S&C, about page 340 */ #define FD_STATUS (4 + FD_IOPORT ) #define FD_DATA (5 + FD_IOPORT ) /* Digital Output Register */ #define FD_DOR (2 + FD_IOPORT ) /* Digital Input Register (read) */ #define FD_DIR (7 + FD_IOPORT ) /* Diskette Control Register (write)*/ #define FD_DCR (7 + FD_IOPORT ) /* Bits of main status register */ #define STATUS_BUSYMASK 0x0F /* drive busy mask */ #define STATUS_BUSY 0x10 /* FDC busy */ #define STATUS_DMA 0x20 /* 0- DMA mode */ #define STATUS_DIR 0x40 /* 0- cpu->fdc */ #define STATUS_READY 0x80 /* Data reg ready */ /* Bits of FD_ST0 */ #define ST0_DS 0x03 /* drive select mask */ #define ST0_HA 0x04 /* Head (Address) */ #define ST0_NR 0x08 /* Not Ready */ #define ST0_ECE 0x10 /* Equipment check error */ #define ST0_SE 0x20 /* Seek end */ #define ST0_INTR 0xC0 /* Interrupt code mask */ /* Bits of FD_ST1 */ #define ST1_MAM 0x01 /* Missing Address Mark */ #define ST1_WP 0x02 /* Write Protect */ #define ST1_ND 0x04 /* No Data - unreadable */ #define ST1_OR 0x10 /* OverRun */ #define ST1_CRC 0x20 /* CRC error in data or addr */ #define ST1_EOC 0x80 /* End Of Cylinder */ /* Bits of FD_ST2 */ #define ST2_MAM 0x01 /* Missing Address Mark (again) */ #define ST2_BC 0x02 /* Bad Cylinder */ #define ST2_SNS 0x04 /* Scan Not Satisfied */ #define ST2_SEH 0x08 /* Scan Equal Hit */ #define ST2_WC 0x10 /* Wrong Cylinder */ #define ST2_CRC 0x20 /* CRC error in data field */ #define ST2_CM 0x40 /* Control Mark = deleted */ /* Bits of FD_ST3 */ #define ST3_HA 0x04 /* Head (Address) */ #define ST3_DS 0x08 /* drive is double-sided */ #define ST3_TZ 0x10 /* Track Zero signal (1=track 0) */ #define ST3_RY 0x20 /* drive is ready */ #define ST3_WP 0x40 /* Write Protect */ #define ST3_FT 0x80 /* Drive Fault */ /* Values for FD_COMMAND */ #define FD_RECALIBRATE 0x07 /* move to track 0 */ #define FD_SEEK 0x0F /* seek track */ #define FD_READ 0xE6 /* read with MT, MFM, SKip deleted */ #define FD_WRITE 0xC5 /* write with MT, MFM */ #define FD_SENSEI 0x08 /* Sense Interrupt Status */ #define FD_SPECIFY 0x03 /* specify HUT etc */ #define FD_FORMAT 0x4D /* format one track */ #define FD_VERSION 0x10 /* get version code */ #define FD_CONFIGURE 0x13 /* configure FIFO operation */ #define FD_PERPENDICULAR 0x12 /* perpendicular r/w mode */ #define FD_GETSTATUS 0x04 /* read ST3 */ #define FD_DUMPREGS 0x0E /* dump the contents of the fdc regs */ #define FD_READID 0xEA /* prints the header of a sector */ #define FD_UNLOCK 0x14 /* Fifo config unlock */ #define FD_LOCK 0x94 /* Fifo config lock */ #define FD_RSEEK_OUT 0x8f /* seek out (i.e. to lower tracks) */ #define FD_RSEEK_IN 0xcf /* seek in (i.e. to higher tracks) */ /* the following commands are new in the 82078. They are not used in the * floppy driver, except the first three. These commands may be useful for apps * which use the FDRAWCMD interface. For doc, get the 82078 spec sheets at * http://www.intel.com/design/archives/periphrl/docs/29046803.htm */ #define FD_PARTID 0x18 /* part id ("extended" version cmd) */ #define FD_SAVE 0x2e /* save fdc regs for later restore */ #define FD_DRIVESPEC 0x8e /* drive specification: Access to the * 2 Mbps data transfer rate for tape * drives */ #define FD_RESTORE 0x4e /* later restore */ #define FD_POWERDOWN 0x27 /* configure FDC's powersave features */ #define FD_FORMAT_N_WRITE 0xef /* format and write in one go. */ #define FD_OPTION 0x33 /* ISO format (which is a clean way to * pack more sectors on a track) */ /* DMA commands */ #define DMA_READ 0x46 #define DMA_WRITE 0x4A /* FDC version return types */ #define FDC_NONE 0x00 #define FDC_UNKNOWN 0x10 /* DO NOT USE THIS TYPE EXCEPT IF IDENTIFICATION FAILS EARLY */ #define FDC_8272A 0x20 /* Intel 8272a, NEC 765 */ #define FDC_765ED 0x30 /* Non-Intel 1MB-compatible FDC, can't detect */ #define FDC_82072 0x40 /* Intel 82072; 8272a + FIFO + DUMPREGS */ #define FDC_82072A 0x45 /* 82072A (on Sparcs) */ #define FDC_82077_ORIG 0x51 /* Original version of 82077AA, sans LOCK */ #define FDC_82077 0x52 /* 82077AA-1 */ #define FDC_82078_UNKN 0x5f /* Unknown 82078 variant */ #define FDC_82078 0x60 /* 44pin 82078 or 64pin 82078SL */ #define FDC_82078_1 0x61 /* 82078-1 (2Mbps fdc) */ #define FDC_S82078B 0x62 /* S82078B (first seen on Adaptec AVA-2825 VLB * SCSI/EIDE/Floppy controller) */ #define FDC_87306 0x63 /* National Semiconductor PC 87306 */ /* * Beware: the fdc type list is roughly sorted by increasing features. * Presence of features is tested by comparing the FDC version id with the * "oldest" version that has the needed feature. * If during FDC detection, an obscure test fails late in the sequence, don't * assign FDC_UNKNOWN. Else the FDC will be treated as a dumb 8272a, or worse. * This is especially true if the tests are unneeded. */ #define FD_RESET_DELAY 20 #endif linux/synclink.h000064400000021431151027430560007712 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * SyncLink Multiprotocol Serial Adapter Driver * * $Id: synclink.h,v 3.14 2006/07/17 20:15:43 paulkf Exp $ * * Copyright (C) 1998-2000 by Microgate Corporation * * Redistribution of this file is permitted under * the terms of the GNU Public License (GPL) */ #ifndef _SYNCLINK_H_ #define _SYNCLINK_H_ #define SYNCLINK_H_VERSION 3.6 #include #define BIT0 0x0001 #define BIT1 0x0002 #define BIT2 0x0004 #define BIT3 0x0008 #define BIT4 0x0010 #define BIT5 0x0020 #define BIT6 0x0040 #define BIT7 0x0080 #define BIT8 0x0100 #define BIT9 0x0200 #define BIT10 0x0400 #define BIT11 0x0800 #define BIT12 0x1000 #define BIT13 0x2000 #define BIT14 0x4000 #define BIT15 0x8000 #define BIT16 0x00010000 #define BIT17 0x00020000 #define BIT18 0x00040000 #define BIT19 0x00080000 #define BIT20 0x00100000 #define BIT21 0x00200000 #define BIT22 0x00400000 #define BIT23 0x00800000 #define BIT24 0x01000000 #define BIT25 0x02000000 #define BIT26 0x04000000 #define BIT27 0x08000000 #define BIT28 0x10000000 #define BIT29 0x20000000 #define BIT30 0x40000000 #define BIT31 0x80000000 #define HDLC_MAX_FRAME_SIZE 65535 #define MAX_ASYNC_TRANSMIT 4096 #define MAX_ASYNC_BUFFER_SIZE 4096 #define ASYNC_PARITY_NONE 0 #define ASYNC_PARITY_EVEN 1 #define ASYNC_PARITY_ODD 2 #define ASYNC_PARITY_SPACE 3 #define HDLC_FLAG_UNDERRUN_ABORT7 0x0000 #define HDLC_FLAG_UNDERRUN_ABORT15 0x0001 #define HDLC_FLAG_UNDERRUN_FLAG 0x0002 #define HDLC_FLAG_UNDERRUN_CRC 0x0004 #define HDLC_FLAG_SHARE_ZERO 0x0010 #define HDLC_FLAG_AUTO_CTS 0x0020 #define HDLC_FLAG_AUTO_DCD 0x0040 #define HDLC_FLAG_AUTO_RTS 0x0080 #define HDLC_FLAG_RXC_DPLL 0x0100 #define HDLC_FLAG_RXC_BRG 0x0200 #define HDLC_FLAG_RXC_TXCPIN 0x8000 #define HDLC_FLAG_RXC_RXCPIN 0x0000 #define HDLC_FLAG_TXC_DPLL 0x0400 #define HDLC_FLAG_TXC_BRG 0x0800 #define HDLC_FLAG_TXC_TXCPIN 0x0000 #define HDLC_FLAG_TXC_RXCPIN 0x0008 #define HDLC_FLAG_DPLL_DIV8 0x1000 #define HDLC_FLAG_DPLL_DIV16 0x2000 #define HDLC_FLAG_DPLL_DIV32 0x0000 #define HDLC_FLAG_HDLC_LOOPMODE 0x4000 #define HDLC_CRC_NONE 0 #define HDLC_CRC_16_CCITT 1 #define HDLC_CRC_32_CCITT 2 #define HDLC_CRC_MASK 0x00ff #define HDLC_CRC_RETURN_EX 0x8000 #define RX_OK 0 #define RX_CRC_ERROR 1 #define HDLC_TXIDLE_FLAGS 0 #define HDLC_TXIDLE_ALT_ZEROS_ONES 1 #define HDLC_TXIDLE_ZEROS 2 #define HDLC_TXIDLE_ONES 3 #define HDLC_TXIDLE_ALT_MARK_SPACE 4 #define HDLC_TXIDLE_SPACE 5 #define HDLC_TXIDLE_MARK 6 #define HDLC_TXIDLE_CUSTOM_8 0x10000000 #define HDLC_TXIDLE_CUSTOM_16 0x20000000 #define HDLC_ENCODING_NRZ 0 #define HDLC_ENCODING_NRZB 1 #define HDLC_ENCODING_NRZI_MARK 2 #define HDLC_ENCODING_NRZI_SPACE 3 #define HDLC_ENCODING_NRZI HDLC_ENCODING_NRZI_SPACE #define HDLC_ENCODING_BIPHASE_MARK 4 #define HDLC_ENCODING_BIPHASE_SPACE 5 #define HDLC_ENCODING_BIPHASE_LEVEL 6 #define HDLC_ENCODING_DIFF_BIPHASE_LEVEL 7 #define HDLC_PREAMBLE_LENGTH_8BITS 0 #define HDLC_PREAMBLE_LENGTH_16BITS 1 #define HDLC_PREAMBLE_LENGTH_32BITS 2 #define HDLC_PREAMBLE_LENGTH_64BITS 3 #define HDLC_PREAMBLE_PATTERN_NONE 0 #define HDLC_PREAMBLE_PATTERN_ZEROS 1 #define HDLC_PREAMBLE_PATTERN_FLAGS 2 #define HDLC_PREAMBLE_PATTERN_10 3 #define HDLC_PREAMBLE_PATTERN_01 4 #define HDLC_PREAMBLE_PATTERN_ONES 5 #define MGSL_MODE_ASYNC 1 #define MGSL_MODE_HDLC 2 #define MGSL_MODE_MONOSYNC 3 #define MGSL_MODE_BISYNC 4 #define MGSL_MODE_RAW 6 #define MGSL_MODE_BASE_CLOCK 7 #define MGSL_MODE_XSYNC 8 #define MGSL_BUS_TYPE_ISA 1 #define MGSL_BUS_TYPE_EISA 2 #define MGSL_BUS_TYPE_PCI 5 #define MGSL_INTERFACE_MASK 0xf #define MGSL_INTERFACE_DISABLE 0 #define MGSL_INTERFACE_RS232 1 #define MGSL_INTERFACE_V35 2 #define MGSL_INTERFACE_RS422 3 #define MGSL_INTERFACE_RTS_EN 0x10 #define MGSL_INTERFACE_LL 0x20 #define MGSL_INTERFACE_RL 0x40 #define MGSL_INTERFACE_MSB_FIRST 0x80 typedef struct _MGSL_PARAMS { /* Common */ unsigned long mode; /* Asynchronous or HDLC */ unsigned char loopback; /* internal loopback mode */ /* HDLC Only */ unsigned short flags; unsigned char encoding; /* NRZ, NRZI, etc. */ unsigned long clock_speed; /* external clock speed in bits per second */ unsigned char addr_filter; /* receive HDLC address filter, 0xFF = disable */ unsigned short crc_type; /* None, CRC16-CCITT, or CRC32-CCITT */ unsigned char preamble_length; unsigned char preamble; /* Async Only */ unsigned long data_rate; /* bits per second */ unsigned char data_bits; /* 7 or 8 data bits */ unsigned char stop_bits; /* 1 or 2 stop bits */ unsigned char parity; /* none, even, or odd */ } MGSL_PARAMS, *PMGSL_PARAMS; #define MICROGATE_VENDOR_ID 0x13c0 #define SYNCLINK_DEVICE_ID 0x0010 #define MGSCC_DEVICE_ID 0x0020 #define SYNCLINK_SCA_DEVICE_ID 0x0030 #define SYNCLINK_GT_DEVICE_ID 0x0070 #define SYNCLINK_GT4_DEVICE_ID 0x0080 #define SYNCLINK_AC_DEVICE_ID 0x0090 #define SYNCLINK_GT2_DEVICE_ID 0x00A0 #define MGSL_MAX_SERIAL_NUMBER 30 /* ** device diagnostics status */ #define DiagStatus_OK 0 #define DiagStatus_AddressFailure 1 #define DiagStatus_AddressConflict 2 #define DiagStatus_IrqFailure 3 #define DiagStatus_IrqConflict 4 #define DiagStatus_DmaFailure 5 #define DiagStatus_DmaConflict 6 #define DiagStatus_PciAdapterNotFound 7 #define DiagStatus_CantAssignPciResources 8 #define DiagStatus_CantAssignPciMemAddr 9 #define DiagStatus_CantAssignPciIoAddr 10 #define DiagStatus_CantAssignPciIrq 11 #define DiagStatus_MemoryError 12 #define SerialSignal_DCD 0x01 /* Data Carrier Detect */ #define SerialSignal_TXD 0x02 /* Transmit Data */ #define SerialSignal_RI 0x04 /* Ring Indicator */ #define SerialSignal_RXD 0x08 /* Receive Data */ #define SerialSignal_CTS 0x10 /* Clear to Send */ #define SerialSignal_RTS 0x20 /* Request to Send */ #define SerialSignal_DSR 0x40 /* Data Set Ready */ #define SerialSignal_DTR 0x80 /* Data Terminal Ready */ /* * Counters of the input lines (CTS, DSR, RI, CD) interrupts */ struct mgsl_icount { __u32 cts, dsr, rng, dcd, tx, rx; __u32 frame, parity, overrun, brk; __u32 buf_overrun; __u32 txok; __u32 txunder; __u32 txabort; __u32 txtimeout; __u32 rxshort; __u32 rxlong; __u32 rxabort; __u32 rxover; __u32 rxcrc; __u32 rxok; __u32 exithunt; __u32 rxidle; }; struct gpio_desc { __u32 state; __u32 smask; __u32 dir; __u32 dmask; }; #define DEBUG_LEVEL_DATA 1 #define DEBUG_LEVEL_ERROR 2 #define DEBUG_LEVEL_INFO 3 #define DEBUG_LEVEL_BH 4 #define DEBUG_LEVEL_ISR 5 /* ** Event bit flags for use with MgslWaitEvent */ #define MgslEvent_DsrActive 0x0001 #define MgslEvent_DsrInactive 0x0002 #define MgslEvent_Dsr 0x0003 #define MgslEvent_CtsActive 0x0004 #define MgslEvent_CtsInactive 0x0008 #define MgslEvent_Cts 0x000c #define MgslEvent_DcdActive 0x0010 #define MgslEvent_DcdInactive 0x0020 #define MgslEvent_Dcd 0x0030 #define MgslEvent_RiActive 0x0040 #define MgslEvent_RiInactive 0x0080 #define MgslEvent_Ri 0x00c0 #define MgslEvent_ExitHuntMode 0x0100 #define MgslEvent_IdleReceived 0x0200 /* Private IOCTL codes: * * MGSL_IOCSPARAMS set MGSL_PARAMS structure values * MGSL_IOCGPARAMS get current MGSL_PARAMS structure values * MGSL_IOCSTXIDLE set current transmit idle mode * MGSL_IOCGTXIDLE get current transmit idle mode * MGSL_IOCTXENABLE enable or disable transmitter * MGSL_IOCRXENABLE enable or disable receiver * MGSL_IOCTXABORT abort transmitting frame (HDLC) * MGSL_IOCGSTATS return current statistics * MGSL_IOCWAITEVENT wait for specified event to occur * MGSL_LOOPTXDONE transmit in HDLC LoopMode done * MGSL_IOCSIF set the serial interface type * MGSL_IOCGIF get the serial interface type */ #define MGSL_MAGIC_IOC 'm' #define MGSL_IOCSPARAMS _IOW(MGSL_MAGIC_IOC,0,struct _MGSL_PARAMS) #define MGSL_IOCGPARAMS _IOR(MGSL_MAGIC_IOC,1,struct _MGSL_PARAMS) #define MGSL_IOCSTXIDLE _IO(MGSL_MAGIC_IOC,2) #define MGSL_IOCGTXIDLE _IO(MGSL_MAGIC_IOC,3) #define MGSL_IOCTXENABLE _IO(MGSL_MAGIC_IOC,4) #define MGSL_IOCRXENABLE _IO(MGSL_MAGIC_IOC,5) #define MGSL_IOCTXABORT _IO(MGSL_MAGIC_IOC,6) #define MGSL_IOCGSTATS _IO(MGSL_MAGIC_IOC,7) #define MGSL_IOCWAITEVENT _IOWR(MGSL_MAGIC_IOC,8,int) #define MGSL_IOCCLRMODCOUNT _IO(MGSL_MAGIC_IOC,15) #define MGSL_IOCLOOPTXDONE _IO(MGSL_MAGIC_IOC,9) #define MGSL_IOCSIF _IO(MGSL_MAGIC_IOC,10) #define MGSL_IOCGIF _IO(MGSL_MAGIC_IOC,11) #define MGSL_IOCSGPIO _IOW(MGSL_MAGIC_IOC,16,struct gpio_desc) #define MGSL_IOCGGPIO _IOR(MGSL_MAGIC_IOC,17,struct gpio_desc) #define MGSL_IOCWAITGPIO _IOWR(MGSL_MAGIC_IOC,18,struct gpio_desc) #define MGSL_IOCSXSYNC _IO(MGSL_MAGIC_IOC, 19) #define MGSL_IOCGXSYNC _IO(MGSL_MAGIC_IOC, 20) #define MGSL_IOCSXCTRL _IO(MGSL_MAGIC_IOC, 21) #define MGSL_IOCGXCTRL _IO(MGSL_MAGIC_IOC, 22) #endif /* _SYNCLINK_H_ */ linux/udf_fs_i.h000064400000001271151027430560007636 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * udf_fs_i.h * * This file is intended for the Linux kernel/module. * * COPYRIGHT * This file is distributed under the terms of the GNU General Public * License (GPL). Copies of the GPL can be obtained from: * ftp://prep.ai.mit.edu/pub/gnu/GPL * Each contributing author retains all rights to their own work. */ #ifndef _UDF_FS_I_H #define _UDF_FS_I_H 1 /* exported IOCTLs, we have 'l', 0x40-0x7f */ #define UDF_GETEASIZE _IOR('l', 0x40, int) #define UDF_GETEABLOCK _IOR('l', 0x41, void *) #define UDF_GETVOLIDENT _IOR('l', 0x42, void *) #define UDF_RELOCATE_BLOCKS _IOWR('l', 0x43, long) #endif /* _UDF_FS_I_H */ linux/elfcore.h000064400000005663151027430560007510 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_ELFCORE_H #define _LINUX_ELFCORE_H #include #include #include #include #include #include struct elf_siginfo { int si_signo; /* signal number */ int si_code; /* extra code */ int si_errno; /* errno */ }; typedef elf_greg_t greg_t; typedef elf_gregset_t gregset_t; typedef elf_fpregset_t fpregset_t; typedef elf_fpxregset_t fpxregset_t; #define NGREG ELF_NGREG /* * Definitions to generate Intel SVR4-like core files. * These mostly have the same names as the SVR4 types with "elf_" * tacked on the front to prevent clashes with linux definitions, * and the typedef forms have been avoided. This is mostly like * the SVR4 structure, but more Linuxy, with things that Linux does * not support and which gdb doesn't really use excluded. * Fields present but not used are marked with "XXX". */ struct elf_prstatus { #if 0 long pr_flags; /* XXX Process flags */ short pr_why; /* XXX Reason for process halt */ short pr_what; /* XXX More detailed reason */ #endif struct elf_siginfo pr_info; /* Info associated with signal */ short pr_cursig; /* Current signal */ unsigned long pr_sigpend; /* Set of pending signals */ unsigned long pr_sighold; /* Set of held signals */ #if 0 struct sigaltstack pr_altstack; /* Alternate stack info */ struct sigaction pr_action; /* Signal action for current sig */ #endif pid_t pr_pid; pid_t pr_ppid; pid_t pr_pgrp; pid_t pr_sid; struct timeval pr_utime; /* User time */ struct timeval pr_stime; /* System time */ struct timeval pr_cutime; /* Cumulative user time */ struct timeval pr_cstime; /* Cumulative system time */ #if 0 long pr_instr; /* Current instruction */ #endif elf_gregset_t pr_reg; /* GP registers */ #ifdef CONFIG_BINFMT_ELF_FDPIC /* When using FDPIC, the loadmap addresses need to be communicated * to GDB in order for GDB to do the necessary relocations. The * fields (below) used to communicate this information are placed * immediately after ``pr_reg'', so that the loadmap addresses may * be viewed as part of the register set if so desired. */ unsigned long pr_exec_fdpic_loadmap; unsigned long pr_interp_fdpic_loadmap; #endif int pr_fpvalid; /* True if math co-processor being used. */ }; #define ELF_PRARGSZ (80) /* Number of chars for args */ struct elf_prpsinfo { char pr_state; /* numeric process state */ char pr_sname; /* char for pr_state */ char pr_zomb; /* zombie */ char pr_nice; /* nice val */ unsigned long pr_flag; /* flags */ __kernel_uid_t pr_uid; __kernel_gid_t pr_gid; pid_t pr_pid, pr_ppid, pr_pgrp, pr_sid; /* Lots missing */ char pr_fname[16]; /* filename of executable */ char pr_psargs[ELF_PRARGSZ]; /* initial part of arg list */ }; typedef struct elf_prstatus prstatus_t; typedef struct elf_prpsinfo prpsinfo_t; #define PRARGSZ ELF_PRARGSZ #endif /* _LINUX_ELFCORE_H */ linux/ip.h000064400000011170151027430560006467 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the IP protocol. * * Version: @(#)ip.h 1.0.2 04/28/93 * * Authors: Fred N. van Kempen, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IP_H #define _LINUX_IP_H #include #include #define IPTOS_TOS_MASK 0x1E #define IPTOS_TOS(tos) ((tos)&IPTOS_TOS_MASK) #define IPTOS_LOWDELAY 0x10 #define IPTOS_THROUGHPUT 0x08 #define IPTOS_RELIABILITY 0x04 #define IPTOS_MINCOST 0x02 #define IPTOS_PREC_MASK 0xE0 #define IPTOS_PREC(tos) ((tos)&IPTOS_PREC_MASK) #define IPTOS_PREC_NETCONTROL 0xe0 #define IPTOS_PREC_INTERNETCONTROL 0xc0 #define IPTOS_PREC_CRITIC_ECP 0xa0 #define IPTOS_PREC_FLASHOVERRIDE 0x80 #define IPTOS_PREC_FLASH 0x60 #define IPTOS_PREC_IMMEDIATE 0x40 #define IPTOS_PREC_PRIORITY 0x20 #define IPTOS_PREC_ROUTINE 0x00 /* IP options */ #define IPOPT_COPY 0x80 #define IPOPT_CLASS_MASK 0x60 #define IPOPT_NUMBER_MASK 0x1f #define IPOPT_COPIED(o) ((o)&IPOPT_COPY) #define IPOPT_CLASS(o) ((o)&IPOPT_CLASS_MASK) #define IPOPT_NUMBER(o) ((o)&IPOPT_NUMBER_MASK) #define IPOPT_CONTROL 0x00 #define IPOPT_RESERVED1 0x20 #define IPOPT_MEASUREMENT 0x40 #define IPOPT_RESERVED2 0x60 #define IPOPT_END (0 |IPOPT_CONTROL) #define IPOPT_NOOP (1 |IPOPT_CONTROL) #define IPOPT_SEC (2 |IPOPT_CONTROL|IPOPT_COPY) #define IPOPT_LSRR (3 |IPOPT_CONTROL|IPOPT_COPY) #define IPOPT_TIMESTAMP (4 |IPOPT_MEASUREMENT) #define IPOPT_CIPSO (6 |IPOPT_CONTROL|IPOPT_COPY) #define IPOPT_RR (7 |IPOPT_CONTROL) #define IPOPT_SID (8 |IPOPT_CONTROL|IPOPT_COPY) #define IPOPT_SSRR (9 |IPOPT_CONTROL|IPOPT_COPY) #define IPOPT_RA (20|IPOPT_CONTROL|IPOPT_COPY) #define IPVERSION 4 #define MAXTTL 255 #define IPDEFTTL 64 #define IPOPT_OPTVAL 0 #define IPOPT_OLEN 1 #define IPOPT_OFFSET 2 #define IPOPT_MINOFF 4 #define MAX_IPOPTLEN 40 #define IPOPT_NOP IPOPT_NOOP #define IPOPT_EOL IPOPT_END #define IPOPT_TS IPOPT_TIMESTAMP #define IPOPT_TS_TSONLY 0 /* timestamps only */ #define IPOPT_TS_TSANDADDR 1 /* timestamps and addresses */ #define IPOPT_TS_PRESPEC 3 /* specified modules only */ #define IPV4_BEET_PHMAXLEN 8 struct iphdr { #if defined(__LITTLE_ENDIAN_BITFIELD) __u8 ihl:4, version:4; #elif defined (__BIG_ENDIAN_BITFIELD) __u8 version:4, ihl:4; #else #error "Please fix " #endif __u8 tos; __be16 tot_len; __be16 id; __be16 frag_off; __u8 ttl; __u8 protocol; __sum16 check; __be32 saddr; __be32 daddr; /*The options start here. */ }; struct ip_auth_hdr { __u8 nexthdr; __u8 hdrlen; /* This one is measured in 32 bit units! */ __be16 reserved; __be32 spi; __be32 seq_no; /* Sequence number */ __u8 auth_data[0]; /* Variable len but >=4. Mind the 64 bit alignment! */ }; struct ip_esp_hdr { __be32 spi; __be32 seq_no; /* Sequence number */ __u8 enc_data[0]; /* Variable len but >=8. Mind the 64 bit alignment! */ }; struct ip_comp_hdr { __u8 nexthdr; __u8 flags; __be16 cpi; }; struct ip_beet_phdr { __u8 nexthdr; __u8 hdrlen; __u8 padlen; __u8 reserved; }; /* index values for the variables in ipv4_devconf */ enum { IPV4_DEVCONF_FORWARDING=1, IPV4_DEVCONF_MC_FORWARDING, IPV4_DEVCONF_PROXY_ARP, IPV4_DEVCONF_ACCEPT_REDIRECTS, IPV4_DEVCONF_SECURE_REDIRECTS, IPV4_DEVCONF_SEND_REDIRECTS, IPV4_DEVCONF_SHARED_MEDIA, IPV4_DEVCONF_RP_FILTER, IPV4_DEVCONF_ACCEPT_SOURCE_ROUTE, IPV4_DEVCONF_BOOTP_RELAY, IPV4_DEVCONF_LOG_MARTIANS, IPV4_DEVCONF_TAG, IPV4_DEVCONF_ARPFILTER, IPV4_DEVCONF_MEDIUM_ID, IPV4_DEVCONF_NOXFRM, IPV4_DEVCONF_NOPOLICY, IPV4_DEVCONF_FORCE_IGMP_VERSION, IPV4_DEVCONF_ARP_ANNOUNCE, IPV4_DEVCONF_ARP_IGNORE, IPV4_DEVCONF_PROMOTE_SECONDARIES, IPV4_DEVCONF_ARP_ACCEPT, IPV4_DEVCONF_ARP_NOTIFY, IPV4_DEVCONF_ACCEPT_LOCAL, IPV4_DEVCONF_SRC_VMARK, IPV4_DEVCONF_PROXY_ARP_PVLAN, IPV4_DEVCONF_ROUTE_LOCALNET, IPV4_DEVCONF_IGMPV2_UNSOLICITED_REPORT_INTERVAL, IPV4_DEVCONF_IGMPV3_UNSOLICITED_REPORT_INTERVAL, IPV4_DEVCONF_IGNORE_ROUTES_WITH_LINKDOWN, IPV4_DEVCONF_DROP_UNICAST_IN_L2_MULTICAST, IPV4_DEVCONF_DROP_GRATUITOUS_ARP, IPV4_DEVCONF_BC_FORWARDING, __IPV4_DEVCONF_MAX }; #define IPV4_DEVCONF_MAX (__IPV4_DEVCONF_MAX - 1) #endif /* _LINUX_IP_H */ linux/ivtv.h000064400000005716151027430560007060 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* Public ivtv API header Copyright (C) 2003-2004 Kevin Thayer Copyright (C) 2004-2007 Hans Verkuil This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __LINUX_IVTV_H__ #define __LINUX_IVTV_H__ #include #include /* ivtv knows several distinct output modes: MPEG streaming, YUV streaming, YUV updates through user DMA and the passthrough mode. In order to clearly tell the driver that we are in user DMA YUV mode you need to call IVTV_IOC_DMA_FRAME with y_source == NULL first (althrough if you don't then the first time DMA_FRAME is called the mode switch is done automatically). When you close the file handle the user DMA mode is exited again. While in one mode, you cannot use another mode (EBUSY is returned). All this means that if you want to change the YUV interlacing for the user DMA YUV mode you first need to do call IVTV_IOC_DMA_FRAME with y_source == NULL before you can set the correct format using VIDIOC_S_FMT. Eventually all this should be replaced with a proper V4L2 API, but for now we have to do it this way. */ struct ivtv_dma_frame { enum v4l2_buf_type type; /* V4L2_BUF_TYPE_VIDEO_OUTPUT */ __u32 pixelformat; /* 0 == same as destination */ void *y_source; /* if NULL and type == V4L2_BUF_TYPE_VIDEO_OUTPUT, then just switch to user DMA YUV output mode */ void *uv_source; /* Unused for RGB pixelformats */ struct v4l2_rect src; struct v4l2_rect dst; __u32 src_width; __u32 src_height; }; #define IVTV_IOC_DMA_FRAME _IOW ('V', BASE_VIDIOC_PRIVATE+0, struct ivtv_dma_frame) /* Select the passthrough mode (if the argument is non-zero). In the passthrough mode the output of the encoder is passed immediately into the decoder. */ #define IVTV_IOC_PASSTHROUGH_MODE _IOW ('V', BASE_VIDIOC_PRIVATE+1, int) /* Deprecated defines: applications should use the defines from videodev2.h */ #define IVTV_SLICED_TYPE_TELETEXT_B V4L2_MPEG_VBI_IVTV_TELETEXT_B #define IVTV_SLICED_TYPE_CAPTION_525 V4L2_MPEG_VBI_IVTV_CAPTION_525 #define IVTV_SLICED_TYPE_WSS_625 V4L2_MPEG_VBI_IVTV_WSS_625 #define IVTV_SLICED_TYPE_VPS V4L2_MPEG_VBI_IVTV_VPS #endif /* _LINUX_IVTV_H */ linux/prctl.h000064400000017527151027430560007217 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_PRCTL_H #define _LINUX_PRCTL_H #include /* Values to pass as first argument to prctl() */ #define PR_SET_PDEATHSIG 1 /* Second arg is a signal */ #define PR_GET_PDEATHSIG 2 /* Second arg is a ptr to return the signal */ /* Get/set current->mm->dumpable */ #define PR_GET_DUMPABLE 3 #define PR_SET_DUMPABLE 4 /* Get/set unaligned access control bits (if meaningful) */ #define PR_GET_UNALIGN 5 #define PR_SET_UNALIGN 6 # define PR_UNALIGN_NOPRINT 1 /* silently fix up unaligned user accesses */ # define PR_UNALIGN_SIGBUS 2 /* generate SIGBUS on unaligned user access */ /* Get/set whether or not to drop capabilities on setuid() away from * uid 0 (as per security/commoncap.c) */ #define PR_GET_KEEPCAPS 7 #define PR_SET_KEEPCAPS 8 /* Get/set floating-point emulation control bits (if meaningful) */ #define PR_GET_FPEMU 9 #define PR_SET_FPEMU 10 # define PR_FPEMU_NOPRINT 1 /* silently emulate fp operations accesses */ # define PR_FPEMU_SIGFPE 2 /* don't emulate fp operations, send SIGFPE instead */ /* Get/set floating-point exception mode (if meaningful) */ #define PR_GET_FPEXC 11 #define PR_SET_FPEXC 12 # define PR_FP_EXC_SW_ENABLE 0x80 /* Use FPEXC for FP exception enables */ # define PR_FP_EXC_DIV 0x010000 /* floating point divide by zero */ # define PR_FP_EXC_OVF 0x020000 /* floating point overflow */ # define PR_FP_EXC_UND 0x040000 /* floating point underflow */ # define PR_FP_EXC_RES 0x080000 /* floating point inexact result */ # define PR_FP_EXC_INV 0x100000 /* floating point invalid operation */ # define PR_FP_EXC_DISABLED 0 /* FP exceptions disabled */ # define PR_FP_EXC_NONRECOV 1 /* async non-recoverable exc. mode */ # define PR_FP_EXC_ASYNC 2 /* async recoverable exception mode */ # define PR_FP_EXC_PRECISE 3 /* precise exception mode */ /* Get/set whether we use statistical process timing or accurate timestamp * based process timing */ #define PR_GET_TIMING 13 #define PR_SET_TIMING 14 # define PR_TIMING_STATISTICAL 0 /* Normal, traditional, statistical process timing */ # define PR_TIMING_TIMESTAMP 1 /* Accurate timestamp based process timing */ #define PR_SET_NAME 15 /* Set process name */ #define PR_GET_NAME 16 /* Get process name */ /* Get/set process endian */ #define PR_GET_ENDIAN 19 #define PR_SET_ENDIAN 20 # define PR_ENDIAN_BIG 0 # define PR_ENDIAN_LITTLE 1 /* True little endian mode */ # define PR_ENDIAN_PPC_LITTLE 2 /* "PowerPC" pseudo little endian */ /* Get/set process seccomp mode */ #define PR_GET_SECCOMP 21 #define PR_SET_SECCOMP 22 /* Get/set the capability bounding set (as per security/commoncap.c) */ #define PR_CAPBSET_READ 23 #define PR_CAPBSET_DROP 24 /* Get/set the process' ability to use the timestamp counter instruction */ #define PR_GET_TSC 25 #define PR_SET_TSC 26 # define PR_TSC_ENABLE 1 /* allow the use of the timestamp counter */ # define PR_TSC_SIGSEGV 2 /* throw a SIGSEGV instead of reading the TSC */ /* Get/set securebits (as per security/commoncap.c) */ #define PR_GET_SECUREBITS 27 #define PR_SET_SECUREBITS 28 /* * Get/set the timerslack as used by poll/select/nanosleep * A value of 0 means "use default" */ #define PR_SET_TIMERSLACK 29 #define PR_GET_TIMERSLACK 30 #define PR_TASK_PERF_EVENTS_DISABLE 31 #define PR_TASK_PERF_EVENTS_ENABLE 32 /* * Set early/late kill mode for hwpoison memory corruption. * This influences when the process gets killed on a memory corruption. */ #define PR_MCE_KILL 33 # define PR_MCE_KILL_CLEAR 0 # define PR_MCE_KILL_SET 1 # define PR_MCE_KILL_LATE 0 # define PR_MCE_KILL_EARLY 1 # define PR_MCE_KILL_DEFAULT 2 #define PR_MCE_KILL_GET 34 /* * Tune up process memory map specifics. */ #define PR_SET_MM 35 # define PR_SET_MM_START_CODE 1 # define PR_SET_MM_END_CODE 2 # define PR_SET_MM_START_DATA 3 # define PR_SET_MM_END_DATA 4 # define PR_SET_MM_START_STACK 5 # define PR_SET_MM_START_BRK 6 # define PR_SET_MM_BRK 7 # define PR_SET_MM_ARG_START 8 # define PR_SET_MM_ARG_END 9 # define PR_SET_MM_ENV_START 10 # define PR_SET_MM_ENV_END 11 # define PR_SET_MM_AUXV 12 # define PR_SET_MM_EXE_FILE 13 # define PR_SET_MM_MAP 14 # define PR_SET_MM_MAP_SIZE 15 /* * This structure provides new memory descriptor * map which mostly modifies /proc/pid/stat[m] * output for a task. This mostly done in a * sake of checkpoint/restore functionality. */ struct prctl_mm_map { __u64 start_code; /* code section bounds */ __u64 end_code; __u64 start_data; /* data section bounds */ __u64 end_data; __u64 start_brk; /* heap for brk() syscall */ __u64 brk; __u64 start_stack; /* stack starts at */ __u64 arg_start; /* command line arguments bounds */ __u64 arg_end; __u64 env_start; /* environment variables bounds */ __u64 env_end; __u64 *auxv; /* auxiliary vector */ __u32 auxv_size; /* vector size */ __u32 exe_fd; /* /proc/$pid/exe link file */ }; /* * Set specific pid that is allowed to ptrace the current task. * A value of 0 mean "no process". */ #define PR_SET_PTRACER 0x59616d61 # define PR_SET_PTRACER_ANY ((unsigned long)-1) #define PR_SET_CHILD_SUBREAPER 36 #define PR_GET_CHILD_SUBREAPER 37 /* * If no_new_privs is set, then operations that grant new privileges (i.e. * execve) will either fail or not grant them. This affects suid/sgid, * file capabilities, and LSMs. * * Operations that merely manipulate or drop existing privileges (setresuid, * capset, etc.) will still work. Drop those privileges if you want them gone. * * Changing LSM security domain is considered a new privilege. So, for example, * asking selinux for a specific new context (e.g. with runcon) will result * in execve returning -EPERM. * * See Documentation/userspace-api/no_new_privs.rst for more details. */ #define PR_SET_NO_NEW_PRIVS 38 #define PR_GET_NO_NEW_PRIVS 39 #define PR_GET_TID_ADDRESS 40 #define PR_SET_THP_DISABLE 41 #define PR_GET_THP_DISABLE 42 /* * Tell the kernel to start/stop helping userspace manage bounds tables. */ #define PR_MPX_ENABLE_MANAGEMENT 43 #define PR_MPX_DISABLE_MANAGEMENT 44 #define PR_SET_FP_MODE 45 #define PR_GET_FP_MODE 46 # define PR_FP_MODE_FR (1 << 0) /* 64b FP registers */ # define PR_FP_MODE_FRE (1 << 1) /* 32b compatibility */ /* Control the ambient capability set */ #define PR_CAP_AMBIENT 47 # define PR_CAP_AMBIENT_IS_SET 1 # define PR_CAP_AMBIENT_RAISE 2 # define PR_CAP_AMBIENT_LOWER 3 # define PR_CAP_AMBIENT_CLEAR_ALL 4 /* arm64 Scalable Vector Extension controls */ /* Flag values must be kept in sync with ptrace NT_ARM_SVE interface */ #define PR_SVE_SET_VL 50 /* set task vector length */ # define PR_SVE_SET_VL_ONEXEC (1 << 18) /* defer effect until exec */ #define PR_SVE_GET_VL 51 /* get task vector length */ /* Bits common to PR_SVE_SET_VL and PR_SVE_GET_VL */ # define PR_SVE_VL_LEN_MASK 0xffff # define PR_SVE_VL_INHERIT (1 << 17) /* inherit across exec */ /* Per task speculation control */ #define PR_GET_SPECULATION_CTRL 52 #define PR_SET_SPECULATION_CTRL 53 /* Speculation control variants */ # define PR_SPEC_STORE_BYPASS 0 # define PR_SPEC_INDIRECT_BRANCH 1 /* Return and control values for PR_SET/GET_SPECULATION_CTRL */ # define PR_SPEC_NOT_AFFECTED 0 # define PR_SPEC_PRCTL (1UL << 0) # define PR_SPEC_ENABLE (1UL << 1) # define PR_SPEC_DISABLE (1UL << 2) # define PR_SPEC_FORCE_DISABLE (1UL << 3) # define PR_SPEC_DISABLE_NOEXEC (1UL << 4) /* Reset arm64 pointer authentication keys */ #define PR_PAC_RESET_KEYS 54 # define PR_PAC_APIAKEY (1UL << 0) # define PR_PAC_APIBKEY (1UL << 1) # define PR_PAC_APDAKEY (1UL << 2) # define PR_PAC_APDBKEY (1UL << 3) # define PR_PAC_APGAKEY (1UL << 4) /* Control reclaim behavior when allocating memory */ #define PR_SET_IO_FLUSHER 57 #define PR_GET_IO_FLUSHER 58 #endif /* _LINUX_PRCTL_H */ linux/if_addr.h000064400000003536151027430560007456 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_IF_ADDR_H #define __LINUX_IF_ADDR_H #include #include struct ifaddrmsg { __u8 ifa_family; __u8 ifa_prefixlen; /* The prefix length */ __u8 ifa_flags; /* Flags */ __u8 ifa_scope; /* Address scope */ __u32 ifa_index; /* Link index */ }; /* * Important comment: * IFA_ADDRESS is prefix address, rather than local interface address. * It makes no difference for normally configured broadcast interfaces, * but for point-to-point IFA_ADDRESS is DESTINATION address, * local address is supplied in IFA_LOCAL attribute. * * IFA_FLAGS is a u32 attribute that extends the u8 field ifa_flags. * If present, the value from struct ifaddrmsg will be ignored. */ enum { IFA_UNSPEC, IFA_ADDRESS, IFA_LOCAL, IFA_LABEL, IFA_BROADCAST, IFA_ANYCAST, IFA_CACHEINFO, IFA_MULTICAST, IFA_FLAGS, IFA_RT_PRIORITY, /* u32, priority/metric for prefix route */ IFA_TARGET_NETNSID, __IFA_MAX, }; #define IFA_MAX (__IFA_MAX - 1) /* ifa_flags */ #define IFA_F_SECONDARY 0x01 #define IFA_F_TEMPORARY IFA_F_SECONDARY #define IFA_F_NODAD 0x02 #define IFA_F_OPTIMISTIC 0x04 #define IFA_F_DADFAILED 0x08 #define IFA_F_HOMEADDRESS 0x10 #define IFA_F_DEPRECATED 0x20 #define IFA_F_TENTATIVE 0x40 #define IFA_F_PERMANENT 0x80 #define IFA_F_MANAGETEMPADDR 0x100 #define IFA_F_NOPREFIXROUTE 0x200 #define IFA_F_MCAUTOJOIN 0x400 #define IFA_F_STABLE_PRIVACY 0x800 struct ifa_cacheinfo { __u32 ifa_prefered; __u32 ifa_valid; __u32 cstamp; /* created timestamp, hundredths of seconds */ __u32 tstamp; /* updated timestamp, hundredths of seconds */ }; /* backwards compatibility for userspace */ #define IFA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ifaddrmsg)))) #define IFA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ifaddrmsg)) #endif linux/hiddev.h000064400000014311151027430560007322 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Copyright (c) 1999-2000 Vojtech Pavlik * * Sponsored by SuSE */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Should you need to contact me, the author, you can do so either by * e-mail - mail your message to , or by paper mail: * Vojtech Pavlik, Ucitelska 1576, Prague 8, 182 00 Czech Republic */ #ifndef _HIDDEV_H #define _HIDDEV_H #include /* * The event structure itself */ struct hiddev_event { unsigned hid; signed int value; }; struct hiddev_devinfo { __u32 bustype; __u32 busnum; __u32 devnum; __u32 ifnum; __s16 vendor; __s16 product; __s16 version; __u32 num_applications; }; struct hiddev_collection_info { __u32 index; __u32 type; __u32 usage; __u32 level; }; #define HID_STRING_SIZE 256 struct hiddev_string_descriptor { __s32 index; char value[HID_STRING_SIZE]; }; struct hiddev_report_info { __u32 report_type; __u32 report_id; __u32 num_fields; }; /* To do a GUSAGE/SUSAGE, fill in at least usage_code, report_type and * report_id. Set report_id to REPORT_ID_UNKNOWN if the rest of the fields * are unknown. Otherwise use a usage_ref struct filled in from a previous * successful GUSAGE call to save time. To actually send a value to the * device, perform a SUSAGE first, followed by a SREPORT. An INITREPORT or a * GREPORT isn't necessary for a GUSAGE to return valid data. */ #define HID_REPORT_ID_UNKNOWN 0xffffffff #define HID_REPORT_ID_FIRST 0x00000100 #define HID_REPORT_ID_NEXT 0x00000200 #define HID_REPORT_ID_MASK 0x000000ff #define HID_REPORT_ID_MAX 0x000000ff #define HID_REPORT_TYPE_INPUT 1 #define HID_REPORT_TYPE_OUTPUT 2 #define HID_REPORT_TYPE_FEATURE 3 #define HID_REPORT_TYPE_MIN 1 #define HID_REPORT_TYPE_MAX 3 struct hiddev_field_info { __u32 report_type; __u32 report_id; __u32 field_index; __u32 maxusage; __u32 flags; __u32 physical; /* physical usage for this field */ __u32 logical; /* logical usage for this field */ __u32 application; /* application usage for this field */ __s32 logical_minimum; __s32 logical_maximum; __s32 physical_minimum; __s32 physical_maximum; __u32 unit_exponent; __u32 unit; }; /* Fill in report_type, report_id and field_index to get the information on a * field. */ #define HID_FIELD_CONSTANT 0x001 #define HID_FIELD_VARIABLE 0x002 #define HID_FIELD_RELATIVE 0x004 #define HID_FIELD_WRAP 0x008 #define HID_FIELD_NONLINEAR 0x010 #define HID_FIELD_NO_PREFERRED 0x020 #define HID_FIELD_NULL_STATE 0x040 #define HID_FIELD_VOLATILE 0x080 #define HID_FIELD_BUFFERED_BYTE 0x100 struct hiddev_usage_ref { __u32 report_type; __u32 report_id; __u32 field_index; __u32 usage_index; __u32 usage_code; __s32 value; }; /* hiddev_usage_ref_multi is used for sending multiple bytes to a control. * It really manifests itself as setting the value of consecutive usages */ #define HID_MAX_MULTI_USAGES 1024 struct hiddev_usage_ref_multi { struct hiddev_usage_ref uref; __u32 num_values; __s32 values[HID_MAX_MULTI_USAGES]; }; /* FIELD_INDEX_NONE is returned in read() data from the kernel when flags * is set to (HIDDEV_FLAG_UREF | HIDDEV_FLAG_REPORT) and a new report has * been sent by the device */ #define HID_FIELD_INDEX_NONE 0xffffffff /* * Protocol version. */ #define HID_VERSION 0x010004 /* * IOCTLs (0x00 - 0x7f) */ #define HIDIOCGVERSION _IOR('H', 0x01, int) #define HIDIOCAPPLICATION _IO('H', 0x02) #define HIDIOCGDEVINFO _IOR('H', 0x03, struct hiddev_devinfo) #define HIDIOCGSTRING _IOR('H', 0x04, struct hiddev_string_descriptor) #define HIDIOCINITREPORT _IO('H', 0x05) #define HIDIOCGNAME(len) _IOC(_IOC_READ, 'H', 0x06, len) #define HIDIOCGREPORT _IOW('H', 0x07, struct hiddev_report_info) #define HIDIOCSREPORT _IOW('H', 0x08, struct hiddev_report_info) #define HIDIOCGREPORTINFO _IOWR('H', 0x09, struct hiddev_report_info) #define HIDIOCGFIELDINFO _IOWR('H', 0x0A, struct hiddev_field_info) #define HIDIOCGUSAGE _IOWR('H', 0x0B, struct hiddev_usage_ref) #define HIDIOCSUSAGE _IOW('H', 0x0C, struct hiddev_usage_ref) #define HIDIOCGUCODE _IOWR('H', 0x0D, struct hiddev_usage_ref) #define HIDIOCGFLAG _IOR('H', 0x0E, int) #define HIDIOCSFLAG _IOW('H', 0x0F, int) #define HIDIOCGCOLLECTIONINDEX _IOW('H', 0x10, struct hiddev_usage_ref) #define HIDIOCGCOLLECTIONINFO _IOWR('H', 0x11, struct hiddev_collection_info) #define HIDIOCGPHYS(len) _IOC(_IOC_READ, 'H', 0x12, len) /* For writing/reading to multiple/consecutive usages */ #define HIDIOCGUSAGES _IOWR('H', 0x13, struct hiddev_usage_ref_multi) #define HIDIOCSUSAGES _IOW('H', 0x14, struct hiddev_usage_ref_multi) /* * Flags to be used in HIDIOCSFLAG */ #define HIDDEV_FLAG_UREF 0x1 #define HIDDEV_FLAG_REPORT 0x2 #define HIDDEV_FLAGS 0x3 /* To traverse the input report descriptor info for a HID device, perform the * following: * * rinfo.report_type = HID_REPORT_TYPE_INPUT; * rinfo.report_id = HID_REPORT_ID_FIRST; * ret = ioctl(fd, HIDIOCGREPORTINFO, &rinfo); * * while (ret >= 0) { * for (i = 0; i < rinfo.num_fields; i++) { * finfo.report_type = rinfo.report_type; * finfo.report_id = rinfo.report_id; * finfo.field_index = i; * ioctl(fd, HIDIOCGFIELDINFO, &finfo); * for (j = 0; j < finfo.maxusage; j++) { * uref.report_type = rinfo.report_type; * uref.report_id = rinfo.report_id; * uref.field_index = i; * uref.usage_index = j; * ioctl(fd, HIDIOCGUCODE, &uref); * ioctl(fd, HIDIOCGUSAGE, &uref); * } * } * rinfo.report_id |= HID_REPORT_ID_NEXT; * ret = ioctl(fd, HIDIOCGREPORTINFO, &rinfo); * } */ #endif /* _HIDDEV_H */ linux/affs_hardblocks.h000064400000003010151027430560011164 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef AFFS_HARDBLOCKS_H #define AFFS_HARDBLOCKS_H #include /* Just the needed definitions for the RDB of an Amiga HD. */ struct RigidDiskBlock { __u32 rdb_ID; __be32 rdb_SummedLongs; __s32 rdb_ChkSum; __u32 rdb_HostID; __be32 rdb_BlockBytes; __u32 rdb_Flags; __u32 rdb_BadBlockList; __be32 rdb_PartitionList; __u32 rdb_FileSysHeaderList; __u32 rdb_DriveInit; __u32 rdb_Reserved1[6]; __u32 rdb_Cylinders; __u32 rdb_Sectors; __u32 rdb_Heads; __u32 rdb_Interleave; __u32 rdb_Park; __u32 rdb_Reserved2[3]; __u32 rdb_WritePreComp; __u32 rdb_ReducedWrite; __u32 rdb_StepRate; __u32 rdb_Reserved3[5]; __u32 rdb_RDBBlocksLo; __u32 rdb_RDBBlocksHi; __u32 rdb_LoCylinder; __u32 rdb_HiCylinder; __u32 rdb_CylBlocks; __u32 rdb_AutoParkSeconds; __u32 rdb_HighRDSKBlock; __u32 rdb_Reserved4; char rdb_DiskVendor[8]; char rdb_DiskProduct[16]; char rdb_DiskRevision[4]; char rdb_ControllerVendor[8]; char rdb_ControllerProduct[16]; char rdb_ControllerRevision[4]; __u32 rdb_Reserved5[10]; }; #define IDNAME_RIGIDDISK 0x5244534B /* "RDSK" */ struct PartitionBlock { __be32 pb_ID; __be32 pb_SummedLongs; __s32 pb_ChkSum; __u32 pb_HostID; __be32 pb_Next; __u32 pb_Flags; __u32 pb_Reserved1[2]; __u32 pb_DevFlags; __u8 pb_DriveName[32]; __u32 pb_Reserved2[15]; __be32 pb_Environment[17]; __u32 pb_EReserved[15]; }; #define IDNAME_PARTITION 0x50415254 /* "PART" */ #define RDB_ALLOCATION_LIMIT 16 #endif /* AFFS_HARDBLOCKS_H */ linux/fpga-dfl.h000064400000021030151027430560007533 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Header File for FPGA DFL User API * * Copyright (C) 2017-2018 Intel Corporation, Inc. * * Authors: * Kang Luwei * Zhang Yi * Wu Hao * Xiao Guangrong */ #ifndef _LINUX_FPGA_DFL_H #define _LINUX_FPGA_DFL_H #include #include #define DFL_FPGA_API_VERSION 0 /* * The IOCTL interface for DFL based FPGA is designed for extensibility by * embedding the structure length (argsz) and flags into structures passed * between kernel and userspace. This design referenced the VFIO IOCTL * interface (include/uapi/linux/vfio.h). */ #define DFL_FPGA_MAGIC 0xB6 #define DFL_FPGA_BASE 0 #define DFL_PORT_BASE 0x40 #define DFL_FME_BASE 0x80 /* Common IOCTLs for both FME and AFU file descriptor */ /** * DFL_FPGA_GET_API_VERSION - _IO(DFL_FPGA_MAGIC, DFL_FPGA_BASE + 0) * * Report the version of the driver API. * Return: Driver API Version. */ #define DFL_FPGA_GET_API_VERSION _IO(DFL_FPGA_MAGIC, DFL_FPGA_BASE + 0) /** * DFL_FPGA_CHECK_EXTENSION - _IO(DFL_FPGA_MAGIC, DFL_FPGA_BASE + 1) * * Check whether an extension is supported. * Return: 0 if not supported, otherwise the extension is supported. */ #define DFL_FPGA_CHECK_EXTENSION _IO(DFL_FPGA_MAGIC, DFL_FPGA_BASE + 1) /* IOCTLs for AFU file descriptor */ /** * DFL_FPGA_PORT_RESET - _IO(DFL_FPGA_MAGIC, DFL_PORT_BASE + 0) * * Reset the FPGA Port and its AFU. No parameters are supported. * Userspace can do Port reset at any time, e.g. during DMA or PR. But * it should never cause any system level issue, only functional failure * (e.g. DMA or PR operation failure) and be recoverable from the failure. * Return: 0 on success, -errno of failure */ #define DFL_FPGA_PORT_RESET _IO(DFL_FPGA_MAGIC, DFL_PORT_BASE + 0) /** * DFL_FPGA_PORT_GET_INFO - _IOR(DFL_FPGA_MAGIC, DFL_PORT_BASE + 1, * struct dfl_fpga_port_info) * * Retrieve information about the fpga port. * Driver fills the info in provided struct dfl_fpga_port_info. * Return: 0 on success, -errno on failure. */ struct dfl_fpga_port_info { /* Input */ __u32 argsz; /* Structure length */ /* Output */ __u32 flags; /* Zero for now */ __u32 num_regions; /* The number of supported regions */ __u32 num_umsgs; /* The number of allocated umsgs */ }; #define DFL_FPGA_PORT_GET_INFO _IO(DFL_FPGA_MAGIC, DFL_PORT_BASE + 1) /** * FPGA_PORT_GET_REGION_INFO - _IOWR(FPGA_MAGIC, PORT_BASE + 2, * struct dfl_fpga_port_region_info) * * Retrieve information about a device memory region. * Caller provides struct dfl_fpga_port_region_info with index value set. * Driver returns the region info in other fields. * Return: 0 on success, -errno on failure. */ struct dfl_fpga_port_region_info { /* input */ __u32 argsz; /* Structure length */ /* Output */ __u32 flags; /* Access permission */ #define DFL_PORT_REGION_READ (1 << 0) /* Region is readable */ #define DFL_PORT_REGION_WRITE (1 << 1) /* Region is writable */ #define DFL_PORT_REGION_MMAP (1 << 2) /* Can be mmaped to userspace */ /* Input */ __u32 index; /* Region index */ #define DFL_PORT_REGION_INDEX_AFU 0 /* AFU */ #define DFL_PORT_REGION_INDEX_STP 1 /* Signal Tap */ __u32 padding; /* Output */ __u64 size; /* Region size (bytes) */ __u64 offset; /* Region offset from start of device fd */ }; #define DFL_FPGA_PORT_GET_REGION_INFO _IO(DFL_FPGA_MAGIC, DFL_PORT_BASE + 2) /** * DFL_FPGA_PORT_DMA_MAP - _IOWR(DFL_FPGA_MAGIC, DFL_PORT_BASE + 3, * struct dfl_fpga_port_dma_map) * * Map the dma memory per user_addr and length which are provided by caller. * Driver fills the iova in provided struct afu_port_dma_map. * This interface only accepts page-size aligned user memory for dma mapping. * Return: 0 on success, -errno on failure. */ struct dfl_fpga_port_dma_map { /* Input */ __u32 argsz; /* Structure length */ __u32 flags; /* Zero for now */ __u64 user_addr; /* Process virtual address */ __u64 length; /* Length of mapping (bytes)*/ /* Output */ __u64 iova; /* IO virtual address */ }; #define DFL_FPGA_PORT_DMA_MAP _IO(DFL_FPGA_MAGIC, DFL_PORT_BASE + 3) /** * DFL_FPGA_PORT_DMA_UNMAP - _IOW(FPGA_MAGIC, PORT_BASE + 4, * struct dfl_fpga_port_dma_unmap) * * Unmap the dma memory per iova provided by caller. * Return: 0 on success, -errno on failure. */ struct dfl_fpga_port_dma_unmap { /* Input */ __u32 argsz; /* Structure length */ __u32 flags; /* Zero for now */ __u64 iova; /* IO virtual address */ }; #define DFL_FPGA_PORT_DMA_UNMAP _IO(DFL_FPGA_MAGIC, DFL_PORT_BASE + 4) /** * struct dfl_fpga_irq_set - the argument for DFL_FPGA_XXX_SET_IRQ ioctl. * * @start: Index of the first irq. * @count: The number of eventfd handler. * @evtfds: Eventfd handlers. */ struct dfl_fpga_irq_set { __u32 start; __u32 count; __s32 evtfds[]; }; /** * DFL_FPGA_PORT_ERR_GET_IRQ_NUM - _IOR(DFL_FPGA_MAGIC, DFL_PORT_BASE + 5, * __u32 num_irqs) * * Get the number of irqs supported by the fpga port error reporting private * feature. Currently hardware supports up to 1 irq. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_PORT_ERR_GET_IRQ_NUM _IOR(DFL_FPGA_MAGIC, \ DFL_PORT_BASE + 5, __u32) /** * DFL_FPGA_PORT_ERR_SET_IRQ - _IOW(DFL_FPGA_MAGIC, DFL_PORT_BASE + 6, * struct dfl_fpga_irq_set) * * Set fpga port error reporting interrupt trigger if evtfds[n] is valid. * Unset related interrupt trigger if evtfds[n] is a negative value. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_PORT_ERR_SET_IRQ _IOW(DFL_FPGA_MAGIC, \ DFL_PORT_BASE + 6, \ struct dfl_fpga_irq_set) /** * DFL_FPGA_PORT_UINT_GET_IRQ_NUM - _IOR(DFL_FPGA_MAGIC, DFL_PORT_BASE + 7, * __u32 num_irqs) * * Get the number of irqs supported by the fpga AFU interrupt private * feature. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_PORT_UINT_GET_IRQ_NUM _IOR(DFL_FPGA_MAGIC, \ DFL_PORT_BASE + 7, __u32) /** * DFL_FPGA_PORT_UINT_SET_IRQ - _IOW(DFL_FPGA_MAGIC, DFL_PORT_BASE + 8, * struct dfl_fpga_irq_set) * * Set fpga AFU interrupt trigger if evtfds[n] is valid. * Unset related interrupt trigger if evtfds[n] is a negative value. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_PORT_UINT_SET_IRQ _IOW(DFL_FPGA_MAGIC, \ DFL_PORT_BASE + 8, \ struct dfl_fpga_irq_set) /* IOCTLs for FME file descriptor */ /** * DFL_FPGA_FME_PORT_PR - _IOW(DFL_FPGA_MAGIC, DFL_FME_BASE + 0, * struct dfl_fpga_fme_port_pr) * * Driver does Partial Reconfiguration based on Port ID and Buffer (Image) * provided by caller. * Return: 0 on success, -errno on failure. * If DFL_FPGA_FME_PORT_PR returns -EIO, that indicates the HW has detected * some errors during PR, under this case, the user can fetch HW error info * from the status of FME's fpga manager. */ struct dfl_fpga_fme_port_pr { /* Input */ __u32 argsz; /* Structure length */ __u32 flags; /* Zero for now */ __u32 port_id; __u32 buffer_size; __u64 buffer_address; /* Userspace address to the buffer for PR */ }; #define DFL_FPGA_FME_PORT_PR _IO(DFL_FPGA_MAGIC, DFL_FME_BASE + 0) /** * DFL_FPGA_FME_PORT_RELEASE - _IOW(DFL_FPGA_MAGIC, DFL_FME_BASE + 1, * int port_id) * * Driver releases the port per Port ID provided by caller. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_FME_PORT_RELEASE _IOW(DFL_FPGA_MAGIC, DFL_FME_BASE + 1, int) /** * DFL_FPGA_FME_PORT_ASSIGN - _IOW(DFL_FPGA_MAGIC, DFL_FME_BASE + 2, * int port_id) * * Driver assigns the port back per Port ID provided by caller. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_FME_PORT_ASSIGN _IOW(DFL_FPGA_MAGIC, DFL_FME_BASE + 2, int) /** * DFL_FPGA_FME_ERR_GET_IRQ_NUM - _IOR(DFL_FPGA_MAGIC, DFL_FME_BASE + 3, * __u32 num_irqs) * * Get the number of irqs supported by the fpga fme error reporting private * feature. Currently hardware supports up to 1 irq. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_FME_ERR_GET_IRQ_NUM _IOR(DFL_FPGA_MAGIC, \ DFL_FME_BASE + 3, __u32) /** * DFL_FPGA_FME_ERR_SET_IRQ - _IOW(DFL_FPGA_MAGIC, DFL_FME_BASE + 4, * struct dfl_fpga_irq_set) * * Set fpga fme error reporting interrupt trigger if evtfds[n] is valid. * Unset related interrupt trigger if evtfds[n] is a negative value. * Return: 0 on success, -errno on failure. */ #define DFL_FPGA_FME_ERR_SET_IRQ _IOW(DFL_FPGA_MAGIC, \ DFL_FME_BASE + 4, \ struct dfl_fpga_irq_set) #endif /* _LINUX_FPGA_DFL_H */ linux/hash_info.h000064400000001631151027430560010016 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Hash Info: Hash algorithms information * * Copyright (c) 2013 Dmitry Kasatkin * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #ifndef _LINUX_HASH_INFO_H #define _LINUX_HASH_INFO_H enum hash_algo { HASH_ALGO_MD4, HASH_ALGO_MD5, HASH_ALGO_SHA1, HASH_ALGO_RIPE_MD_160, HASH_ALGO_SHA256, HASH_ALGO_SHA384, HASH_ALGO_SHA512, HASH_ALGO_SHA224, HASH_ALGO_RIPE_MD_128, HASH_ALGO_RIPE_MD_256, HASH_ALGO_RIPE_MD_320, HASH_ALGO_WP_256, HASH_ALGO_WP_384, HASH_ALGO_WP_512, HASH_ALGO_TGR_128, HASH_ALGO_TGR_160, HASH_ALGO_TGR_192, HASH_ALGO_SM3_256, HASH_ALGO__LAST }; #endif /* _LINUX_HASH_INFO_H */ linux/route.h000064400000004434151027430560007222 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the IP router interface. * * Version: @(#)route.h 1.0.3 05/27/93 * * Authors: Original taken from Berkeley UNIX 4.3, (c) UCB 1986-1988 * for the purposes of compatibility only. * * Fred N. van Kempen, * * Changes: * Mike McLagan : Routing by source * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_ROUTE_H #define _LINUX_ROUTE_H #include /* This structure gets passed by the SIOCADDRT and SIOCDELRT calls. */ struct rtentry { unsigned long rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; unsigned long rt_pad3; void *rt_pad4; short rt_metric; /* +1 for binary compatibility! */ char *rt_dev; /* forcing the device at add */ unsigned long rt_mtu; /* per route MTU/Window */ #define rt_mss rt_mtu /* Compatibility :-( */ unsigned long rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; #define RTF_UP 0x0001 /* route usable */ #define RTF_GATEWAY 0x0002 /* destination is a gateway */ #define RTF_HOST 0x0004 /* host entry (net otherwise) */ #define RTF_REINSTATE 0x0008 /* reinstate route after tmout */ #define RTF_DYNAMIC 0x0010 /* created dyn. (by redirect) */ #define RTF_MODIFIED 0x0020 /* modified dyn. (by redirect) */ #define RTF_MTU 0x0040 /* specific MTU for this route */ #define RTF_MSS RTF_MTU /* Compatibility :-( */ #define RTF_WINDOW 0x0080 /* per route window clamping */ #define RTF_IRTT 0x0100 /* Initial round trip time */ #define RTF_REJECT 0x0200 /* Reject route */ /* * uses RTF values >= 64k */ #endif /* _LINUX_ROUTE_H */ linux/loop.h000064400000006651151027430560007040 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * include/linux/loop.h * * Written by Theodore Ts'o, 3/29/93. * * Copyright 1993 by Theodore Ts'o. Redistribution of this file is * permitted under the GNU General Public License. */ #ifndef _LINUX_LOOP_H #define _LINUX_LOOP_H #define LO_NAME_SIZE 64 #define LO_KEY_SIZE 32 /* * Loop flags */ enum { LO_FLAGS_READ_ONLY = 1, LO_FLAGS_AUTOCLEAR = 4, LO_FLAGS_PARTSCAN = 8, LO_FLAGS_DIRECT_IO = 16, }; /* LO_FLAGS that can be set using LOOP_SET_STATUS(64) */ #define LOOP_SET_STATUS_SETTABLE_FLAGS (LO_FLAGS_AUTOCLEAR | LO_FLAGS_PARTSCAN) /* LO_FLAGS that can be cleared using LOOP_SET_STATUS(64) */ #define LOOP_SET_STATUS_CLEARABLE_FLAGS (LO_FLAGS_AUTOCLEAR) /* LO_FLAGS that can be set using LOOP_CONFIGURE */ #define LOOP_CONFIGURE_SETTABLE_FLAGS (LO_FLAGS_READ_ONLY | LO_FLAGS_AUTOCLEAR \ | LO_FLAGS_PARTSCAN | LO_FLAGS_DIRECT_IO) #include /* for __kernel_old_dev_t */ #include /* for __u64 */ /* Backwards compatibility version */ struct loop_info { int lo_number; /* ioctl r/o */ __kernel_old_dev_t lo_device; /* ioctl r/o */ unsigned long lo_inode; /* ioctl r/o */ __kernel_old_dev_t lo_rdevice; /* ioctl r/o */ int lo_offset; int lo_encrypt_type; int lo_encrypt_key_size; /* ioctl w/o */ int lo_flags; char lo_name[LO_NAME_SIZE]; unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */ unsigned long lo_init[2]; char reserved[4]; }; struct loop_info64 { __u64 lo_device; /* ioctl r/o */ __u64 lo_inode; /* ioctl r/o */ __u64 lo_rdevice; /* ioctl r/o */ __u64 lo_offset; __u64 lo_sizelimit;/* bytes, 0 == max available */ __u32 lo_number; /* ioctl r/o */ __u32 lo_encrypt_type; __u32 lo_encrypt_key_size; /* ioctl w/o */ __u32 lo_flags; __u8 lo_file_name[LO_NAME_SIZE]; __u8 lo_crypt_name[LO_NAME_SIZE]; __u8 lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */ __u64 lo_init[2]; }; /** * struct loop_config - Complete configuration for a loop device. * @fd: fd of the file to be used as a backing file for the loop device. * @block_size: block size to use; ignored if 0. * @info: struct loop_info64 to configure the loop device with. * * This structure is used with the LOOP_CONFIGURE ioctl, and can be used to * atomically setup and configure all loop device parameters at once. */ struct loop_config { __u32 fd; __u32 block_size; struct loop_info64 info; __u64 __reserved[8]; }; /* * Loop filter types */ #define LO_CRYPT_NONE 0 #define LO_CRYPT_XOR 1 #define LO_CRYPT_DES 2 #define LO_CRYPT_FISH2 3 /* Twofish encryption */ #define LO_CRYPT_BLOW 4 #define LO_CRYPT_CAST128 5 #define LO_CRYPT_IDEA 6 #define LO_CRYPT_DUMMY 9 #define LO_CRYPT_SKIPJACK 10 #define LO_CRYPT_CRYPTOAPI 18 #define MAX_LO_CRYPT 20 /* * IOCTL commands --- we will commandeer 0x4C ('L') */ #define LOOP_SET_FD 0x4C00 #define LOOP_CLR_FD 0x4C01 #define LOOP_SET_STATUS 0x4C02 #define LOOP_GET_STATUS 0x4C03 #define LOOP_SET_STATUS64 0x4C04 #define LOOP_GET_STATUS64 0x4C05 #define LOOP_CHANGE_FD 0x4C06 #define LOOP_SET_CAPACITY 0x4C07 #define LOOP_SET_DIRECT_IO 0x4C08 #define LOOP_SET_BLOCK_SIZE 0x4C09 #define LOOP_CONFIGURE 0x4C0A /* /dev/loop-control interface */ #define LOOP_CTL_ADD 0x4C80 #define LOOP_CTL_REMOVE 0x4C81 #define LOOP_CTL_GET_FREE 0x4C82 #endif /* _LINUX_LOOP_H */ linux/timerfd.h000064400000001650151027430560007513 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * include/linux/timerfd.h * * Copyright (C) 2007 Davide Libenzi * */ #ifndef _LINUX_TIMERFD_H #define _LINUX_TIMERFD_H #include /* For O_CLOEXEC and O_NONBLOCK */ #include /* For _IO helpers */ #include /* * CAREFUL: Check include/asm-generic/fcntl.h when defining * new flags, since they might collide with O_* ones. We want * to re-use O_* flags that couldn't possibly have a meaning * from eventfd, in order to leave a free define-space for * shared O_* flags. * * Also make sure to update the masks in include/linux/timerfd.h * when adding new flags. */ #define TFD_TIMER_ABSTIME (1 << 0) #define TFD_TIMER_CANCEL_ON_SET (1 << 1) #define TFD_CLOEXEC O_CLOEXEC #define TFD_NONBLOCK O_NONBLOCK #define TFD_IOC_SET_TICKS _IOW('T', 0, __u64) #endif /* _LINUX_TIMERFD_H */ linux/gfs2_ondisk.h000064400000034627151027430560010303 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. * Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License v.2. */ #ifndef __GFS2_ONDISK_DOT_H__ #define __GFS2_ONDISK_DOT_H__ #include #define GFS2_MAGIC 0x01161970 #define GFS2_BASIC_BLOCK 512 #define GFS2_BASIC_BLOCK_SHIFT 9 /* Lock numbers of the LM_TYPE_NONDISK type */ #define GFS2_MOUNT_LOCK 0 #define GFS2_LIVE_LOCK 1 #define GFS2_FREEZE_LOCK 2 #define GFS2_RENAME_LOCK 3 #define GFS2_CONTROL_LOCK 4 #define GFS2_MOUNTED_LOCK 5 /* Format numbers for various metadata types */ #define GFS2_FORMAT_NONE 0 #define GFS2_FORMAT_SB 100 #define GFS2_FORMAT_RG 200 #define GFS2_FORMAT_RB 300 #define GFS2_FORMAT_DI 400 #define GFS2_FORMAT_IN 500 #define GFS2_FORMAT_LF 600 #define GFS2_FORMAT_JD 700 #define GFS2_FORMAT_LH 800 #define GFS2_FORMAT_LD 900 #define GFS2_FORMAT_LB 1000 #define GFS2_FORMAT_EA 1600 #define GFS2_FORMAT_ED 1700 #define GFS2_FORMAT_QC 1400 /* These are format numbers for entities contained in files */ #define GFS2_FORMAT_RI 1100 #define GFS2_FORMAT_DE 1200 #define GFS2_FORMAT_QU 1500 /* These are part of the superblock */ #define GFS2_FORMAT_FS 1801 #define GFS2_FORMAT_MULTI 1900 /* * An on-disk inode number */ struct gfs2_inum { __be64 no_formal_ino; __be64 no_addr; }; /* * Generic metadata head structure * Every inplace buffer logged in the journal must start with this. */ #define GFS2_METATYPE_NONE 0 #define GFS2_METATYPE_SB 1 #define GFS2_METATYPE_RG 2 #define GFS2_METATYPE_RB 3 #define GFS2_METATYPE_DI 4 #define GFS2_METATYPE_IN 5 #define GFS2_METATYPE_LF 6 #define GFS2_METATYPE_JD 7 #define GFS2_METATYPE_LH 8 #define GFS2_METATYPE_LD 9 #define GFS2_METATYPE_LB 12 #define GFS2_METATYPE_EA 10 #define GFS2_METATYPE_ED 11 #define GFS2_METATYPE_QC 14 struct gfs2_meta_header { __be32 mh_magic; __be32 mh_type; __be64 __pad0; /* Was generation number in gfs1 */ __be32 mh_format; /* This union is to keep userspace happy */ union { __be32 mh_jid; /* Was incarnation number in gfs1 */ __be32 __pad1; }; }; /* * super-block structure * * It's probably good if SIZEOF_SB <= GFS2_BASIC_BLOCK (512 bytes) * * Order is important, need to be able to read old superblocks to do on-disk * version upgrades. */ /* Address of superblock in GFS2 basic blocks */ #define GFS2_SB_ADDR 128 /* The lock number for the superblock (must be zero) */ #define GFS2_SB_LOCK 0 /* Requirement: GFS2_LOCKNAME_LEN % 8 == 0 Includes: the fencing zero at the end */ #define GFS2_LOCKNAME_LEN 64 struct gfs2_sb { struct gfs2_meta_header sb_header; __be32 sb_fs_format; __be32 sb_multihost_format; __u32 __pad0; /* Was superblock flags in gfs1 */ __be32 sb_bsize; __be32 sb_bsize_shift; __u32 __pad1; /* Was journal segment size in gfs1 */ struct gfs2_inum sb_master_dir; /* Was jindex dinode in gfs1 */ struct gfs2_inum __pad2; /* Was rindex dinode in gfs1 */ struct gfs2_inum sb_root_dir; char sb_lockproto[GFS2_LOCKNAME_LEN]; char sb_locktable[GFS2_LOCKNAME_LEN]; struct gfs2_inum __pad3; /* Was quota inode in gfs1 */ struct gfs2_inum __pad4; /* Was licence inode in gfs1 */ #define GFS2_HAS_UUID 1 __u8 sb_uuid[16]; /* The UUID, maybe 0 for backwards compat */ }; /* * resource index structure */ struct gfs2_rindex { __be64 ri_addr; /* grp block disk address */ __be32 ri_length; /* length of rgrp header in fs blocks */ __u32 __pad; __be64 ri_data0; /* first data location */ __be32 ri_data; /* num of data blocks in rgrp */ __be32 ri_bitbytes; /* number of bytes in data bitmaps */ __u8 ri_reserved[64]; }; /* * resource group header structure */ /* Number of blocks per byte in rgrp */ #define GFS2_NBBY 4 #define GFS2_BIT_SIZE 2 #define GFS2_BIT_MASK 0x00000003 #define GFS2_BLKST_FREE 0 #define GFS2_BLKST_USED 1 #define GFS2_BLKST_UNLINKED 2 #define GFS2_BLKST_DINODE 3 #define GFS2_RGF_JOURNAL 0x00000001 #define GFS2_RGF_METAONLY 0x00000002 #define GFS2_RGF_DATAONLY 0x00000004 #define GFS2_RGF_NOALLOC 0x00000008 #define GFS2_RGF_TRIMMED 0x00000010 struct gfs2_inode_lvb { __be32 ri_magic; __be32 __pad; __be64 ri_generation_deleted; }; struct gfs2_rgrp_lvb { __be32 rl_magic; __be32 rl_flags; __be32 rl_free; __be32 rl_dinodes; __be64 rl_igeneration; __be32 rl_unlinked; __be32 __pad; }; struct gfs2_rgrp { struct gfs2_meta_header rg_header; __be32 rg_flags; __be32 rg_free; __be32 rg_dinodes; union { __be32 __pad; __be32 rg_skip; /* Distance to the next rgrp in fs blocks */ }; __be64 rg_igeneration; /* The following 3 fields are duplicated from gfs2_rindex to reduce reliance on the rindex */ __be64 rg_data0; /* First data location */ __be32 rg_data; /* Number of data blocks in rgrp */ __be32 rg_bitbytes; /* Number of bytes in data bitmaps */ __be32 rg_crc; /* crc32 of the structure with this field 0 */ __u8 rg_reserved[60]; /* Several fields from gfs1 now reserved */ }; /* * quota structure */ struct gfs2_quota { __be64 qu_limit; __be64 qu_warn; __be64 qu_value; __u8 qu_reserved[64]; }; /* * dinode structure */ #define GFS2_MAX_META_HEIGHT 10 #define GFS2_DIR_MAX_DEPTH 17 #define DT2IF(dt) (((dt) << 12) & S_IFMT) #define IF2DT(sif) (((sif) & S_IFMT) >> 12) enum { gfs2fl_Jdata = 0, gfs2fl_ExHash = 1, gfs2fl_Unused = 2, gfs2fl_EaIndirect = 3, gfs2fl_Directio = 4, gfs2fl_Immutable = 5, gfs2fl_AppendOnly = 6, gfs2fl_NoAtime = 7, gfs2fl_Sync = 8, gfs2fl_System = 9, gfs2fl_TopLevel = 10, gfs2fl_TruncInProg = 29, gfs2fl_InheritDirectio = 30, gfs2fl_InheritJdata = 31, }; /* Dinode flags */ #define GFS2_DIF_JDATA 0x00000001 #define GFS2_DIF_EXHASH 0x00000002 #define GFS2_DIF_UNUSED 0x00000004 /* only in gfs1 */ #define GFS2_DIF_EA_INDIRECT 0x00000008 #define GFS2_DIF_DIRECTIO 0x00000010 #define GFS2_DIF_IMMUTABLE 0x00000020 #define GFS2_DIF_APPENDONLY 0x00000040 #define GFS2_DIF_NOATIME 0x00000080 #define GFS2_DIF_SYNC 0x00000100 #define GFS2_DIF_SYSTEM 0x00000200 /* New in gfs2 */ #define GFS2_DIF_TOPDIR 0x00000400 /* New in gfs2 */ #define GFS2_DIF_TRUNC_IN_PROG 0x20000000 /* New in gfs2 */ #define GFS2_DIF_INHERIT_DIRECTIO 0x40000000 /* only in gfs1 */ #define GFS2_DIF_INHERIT_JDATA 0x80000000 struct gfs2_dinode { struct gfs2_meta_header di_header; struct gfs2_inum di_num; __be32 di_mode; /* mode of file */ __be32 di_uid; /* owner's user id */ __be32 di_gid; /* owner's group id */ __be32 di_nlink; /* number of links to this file */ __be64 di_size; /* number of bytes in file */ __be64 di_blocks; /* number of blocks in file */ __be64 di_atime; /* time last accessed */ __be64 di_mtime; /* time last modified */ __be64 di_ctime; /* time last changed */ __be32 di_major; /* device major number */ __be32 di_minor; /* device minor number */ /* This section varies from gfs1. Padding added to align with * remainder of dinode */ __be64 di_goal_meta; /* rgrp to alloc from next */ __be64 di_goal_data; /* data block goal */ __be64 di_generation; /* generation number for NFS */ __be32 di_flags; /* GFS2_DIF_... */ __be32 di_payload_format; /* GFS2_FORMAT_... */ __u16 __pad1; /* Was ditype in gfs1 */ __be16 di_height; /* height of metadata */ __u32 __pad2; /* Unused incarnation number from gfs1 */ /* These only apply to directories */ __u16 __pad3; /* Padding */ __be16 di_depth; /* Number of bits in the table */ __be32 di_entries; /* The number of entries in the directory */ struct gfs2_inum __pad4; /* Unused even in current gfs1 */ __be64 di_eattr; /* extended attribute block number */ __be32 di_atime_nsec; /* nsec portion of atime */ __be32 di_mtime_nsec; /* nsec portion of mtime */ __be32 di_ctime_nsec; /* nsec portion of ctime */ __u8 di_reserved[44]; }; /* * directory structure - many of these per directory file */ #define GFS2_FNAMESIZE 255 #define GFS2_DIRENT_SIZE(name_len) ((sizeof(struct gfs2_dirent) + (name_len) + 7) & ~7) #define GFS2_MIN_DIRENT_SIZE (GFS2_DIRENT_SIZE(1)) struct gfs2_dirent { struct gfs2_inum de_inum; __be32 de_hash; __be16 de_rec_len; __be16 de_name_len; __be16 de_type; __be16 de_rahead; union { __u8 __pad[12]; struct { __u32 de_cookie; /* ondisk value not used */ __u8 pad3[8]; }; }; }; /* * Header of leaf directory nodes */ struct gfs2_leaf { struct gfs2_meta_header lf_header; __be16 lf_depth; /* Depth of leaf */ __be16 lf_entries; /* Number of dirents in leaf */ __be32 lf_dirent_format; /* Format of the dirents */ __be64 lf_next; /* Next leaf, if overflow */ union { __u8 lf_reserved[64]; struct { __be64 lf_inode; /* Dir inode number */ __be32 lf_dist; /* Dist from inode on chain */ __be32 lf_nsec; /* Last ins/del usecs */ __be64 lf_sec; /* Last ins/del in secs */ __u8 lf_reserved2[40]; }; }; }; /* * Extended attribute header format * * This works in a similar way to dirents. There is a fixed size header * followed by a variable length section made up of the name and the * associated data. In the case of a "stuffed" entry, the value is * __inline__ directly after the name, the ea_num_ptrs entry will be * zero in that case. For non-"stuffed" entries, there will be * a set of pointers (aligned to 8 byte boundary) to the block(s) * containing the value. * * The blocks containing the values and the blocks containing the * extended attribute headers themselves all start with the common * metadata header. Each inode, if it has extended attributes, will * have either a single block containing the extended attribute headers * or a single indirect block pointing to blocks containing the * extended attribute headers. * * The maximum size of the data part of an extended attribute is 64k * so the number of blocks required depends upon block size. Since the * block size also determines the number of pointers in an indirect * block, its a fairly complicated calculation to work out the maximum * number of blocks that an inode may have relating to extended attributes. * */ #define GFS2_EA_MAX_NAME_LEN 255 #define GFS2_EA_MAX_DATA_LEN 65536 #define GFS2_EATYPE_UNUSED 0 #define GFS2_EATYPE_USR 1 #define GFS2_EATYPE_SYS 2 #define GFS2_EATYPE_SECURITY 3 #define GFS2_EATYPE_LAST 3 #define GFS2_EATYPE_VALID(x) ((x) <= GFS2_EATYPE_LAST) #define GFS2_EAFLAG_LAST 0x01 /* last ea in block */ struct gfs2_ea_header { __be32 ea_rec_len; __be32 ea_data_len; __u8 ea_name_len; /* no NULL pointer after the string */ __u8 ea_type; /* GFS2_EATYPE_... */ __u8 ea_flags; /* GFS2_EAFLAG_... */ __u8 ea_num_ptrs; __u32 __pad; }; /* * Log header structure */ #define GFS2_LOG_HEAD_UNMOUNT 0x00000001 /* log is clean */ #define GFS2_LOG_HEAD_FLUSH_NORMAL 0x00000002 /* normal log flush */ #define GFS2_LOG_HEAD_FLUSH_SYNC 0x00000004 /* Sync log flush */ #define GFS2_LOG_HEAD_FLUSH_SHUTDOWN 0x00000008 /* Shutdown log flush */ #define GFS2_LOG_HEAD_FLUSH_FREEZE 0x00000010 /* Freeze flush */ #define GFS2_LOG_HEAD_RECOVERY 0x00000020 /* Journal recovery */ #define GFS2_LOG_HEAD_USERSPACE 0x80000000 /* Written by gfs2-utils */ /* Log flush callers */ #define GFS2_LFC_SHUTDOWN 0x00000100 #define GFS2_LFC_JDATA_WPAGES 0x00000200 #define GFS2_LFC_SET_FLAGS 0x00000400 #define GFS2_LFC_AIL_EMPTY_GL 0x00000800 #define GFS2_LFC_AIL_FLUSH 0x00001000 #define GFS2_LFC_RGRP_GO_SYNC 0x00002000 #define GFS2_LFC_INODE_GO_SYNC 0x00004000 #define GFS2_LFC_INODE_GO_INVAL 0x00008000 #define GFS2_LFC_FREEZE_GO_SYNC 0x00010000 #define GFS2_LFC_KILL_SB 0x00020000 #define GFS2_LFC_DO_SYNC 0x00040000 #define GFS2_LFC_INPLACE_RESERVE 0x00080000 #define GFS2_LFC_WRITE_INODE 0x00100000 #define GFS2_LFC_MAKE_FS_RO 0x00200000 #define GFS2_LFC_SYNC_FS 0x00400000 #define GFS2_LFC_EVICT_INODE 0x00800000 #define GFS2_LFC_TRANS_END 0x01000000 #define GFS2_LFC_LOGD_JFLUSH_REQD 0x02000000 #define GFS2_LFC_LOGD_AIL_FLUSH_REQD 0x04000000 #define LH_V1_SIZE (offsetofend(struct gfs2_log_header, lh_hash)) struct gfs2_log_header { struct gfs2_meta_header lh_header; __be64 lh_sequence; /* Sequence number of this transaction */ __be32 lh_flags; /* GFS2_LOG_HEAD_... */ __be32 lh_tail; /* Block number of log tail */ __be32 lh_blkno; __be32 lh_hash; /* crc up to here with this field 0 */ /* Version 2 additional fields start here */ __be32 lh_crc; /* crc32c from lh_nsec to end of block */ __be32 lh_nsec; /* Nanoseconds of timestamp */ __be64 lh_sec; /* Seconds of timestamp */ __be64 lh_addr; /* Block addr of this log header (absolute) */ __be64 lh_jinode; /* Journal inode number */ __be64 lh_statfs_addr; /* Local statfs inode number */ __be64 lh_quota_addr; /* Local quota change inode number */ /* Statfs local changes (i.e. diff from global statfs) */ __be64 lh_local_total; __be64 lh_local_free; __be64 lh_local_dinodes; }; /* * Log type descriptor */ #define GFS2_LOG_DESC_METADATA 300 /* ld_data1 is the number of metadata blocks in the descriptor. ld_data2 is unused. */ #define GFS2_LOG_DESC_REVOKE 301 /* ld_data1 is the number of revoke blocks in the descriptor. ld_data2 is unused. */ #define GFS2_LOG_DESC_JDATA 302 /* ld_data1 is the number of data blocks in the descriptor. ld_data2 is unused. */ struct gfs2_log_descriptor { struct gfs2_meta_header ld_header; __be32 ld_type; /* GFS2_LOG_DESC_... */ __be32 ld_length; /* Number of buffers in this chunk */ __be32 ld_data1; /* descriptor-specific field */ __be32 ld_data2; /* descriptor-specific field */ __u8 ld_reserved[32]; }; /* * Inum Range * Describe a range of formal inode numbers allocated to * one machine to assign to inodes. */ #define GFS2_INUM_QUANTUM 1048576 struct gfs2_inum_range { __be64 ir_start; __be64 ir_length; }; /* * Statfs change * Describes an change to the pool of free and allocated * blocks. */ struct gfs2_statfs_change { __be64 sc_total; __be64 sc_free; __be64 sc_dinodes; }; /* * Quota change * Describes an allocation change for a particular * user or group. */ #define GFS2_QCF_USER 0x00000001 struct gfs2_quota_change { __be64 qc_change; __be32 qc_flags; /* GFS2_QCF_... */ __be32 qc_id; }; struct gfs2_quota_lvb { __be32 qb_magic; __u32 __pad; __be64 qb_limit; /* Hard limit of # blocks to alloc */ __be64 qb_warn; /* Warn user when alloc is above this # */ __be64 qb_value; /* Current # blocks allocated */ }; #endif /* __GFS2_ONDISK_DOT_H__ */ linux/sunrpc/debug.h000064400000002170151027430560010457 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * linux/include/linux/sunrpc/debug.h * * Debugging support for sunrpc module * * Copyright (C) 1996, Olaf Kirch */ #ifndef _LINUX_SUNRPC_DEBUG_H_ #define _LINUX_SUNRPC_DEBUG_H_ /* * RPC debug facilities */ #define RPCDBG_XPRT 0x0001 #define RPCDBG_CALL 0x0002 #define RPCDBG_DEBUG 0x0004 #define RPCDBG_NFS 0x0008 #define RPCDBG_AUTH 0x0010 #define RPCDBG_BIND 0x0020 #define RPCDBG_SCHED 0x0040 #define RPCDBG_TRANS 0x0080 #define RPCDBG_SVCXPRT 0x0100 #define RPCDBG_SVCDSP 0x0200 #define RPCDBG_MISC 0x0400 #define RPCDBG_CACHE 0x0800 #define RPCDBG_ALL 0x7fff /* * Declarations for the sysctl debug interface, which allows to read or * change the debug flags for rpc, nfs, nfsd, and lockd. Since the sunrpc * module currently registers its sysctl table dynamically, the sysctl path * for module FOO is . */ enum { CTL_RPCDEBUG = 1, CTL_NFSDEBUG, CTL_NFSDDEBUG, CTL_NLMDEBUG, CTL_SLOTTABLE_UDP, CTL_SLOTTABLE_TCP, CTL_MIN_RESVPORT, CTL_MAX_RESVPORT, }; #endif /* _LINUX_SUNRPC_DEBUG_H_ */ linux/veth.h000064400000000340151027430560007022 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __NET_VETH_H_ #define __NET_VETH_H_ enum { VETH_INFO_UNSPEC, VETH_INFO_PEER, __VETH_INFO_MAX #define VETH_INFO_MAX (__VETH_INFO_MAX - 1) }; #endif linux/if_tun.h000064400000010002151027430560007334 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Universal TUN/TAP device driver. * Copyright (C) 1999-2000 Maxim Krasnyansky * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __IF_TUN_H #define __IF_TUN_H #include #include #include /* Read queue size */ #define TUN_READQ_SIZE 500 /* TUN device type flags: deprecated. Use IFF_TUN/IFF_TAP instead. */ #define TUN_TUN_DEV IFF_TUN #define TUN_TAP_DEV IFF_TAP #define TUN_TYPE_MASK 0x000f /* Ioctl defines */ #define TUNSETNOCSUM _IOW('T', 200, int) #define TUNSETDEBUG _IOW('T', 201, int) #define TUNSETIFF _IOW('T', 202, int) #define TUNSETPERSIST _IOW('T', 203, int) #define TUNSETOWNER _IOW('T', 204, int) #define TUNSETLINK _IOW('T', 205, int) #define TUNSETGROUP _IOW('T', 206, int) #define TUNGETFEATURES _IOR('T', 207, unsigned int) #define TUNSETOFFLOAD _IOW('T', 208, unsigned int) #define TUNSETTXFILTER _IOW('T', 209, unsigned int) #define TUNGETIFF _IOR('T', 210, unsigned int) #define TUNGETSNDBUF _IOR('T', 211, int) #define TUNSETSNDBUF _IOW('T', 212, int) #define TUNATTACHFILTER _IOW('T', 213, struct sock_fprog) #define TUNDETACHFILTER _IOW('T', 214, struct sock_fprog) #define TUNGETVNETHDRSZ _IOR('T', 215, int) #define TUNSETVNETHDRSZ _IOW('T', 216, int) #define TUNSETQUEUE _IOW('T', 217, int) #define TUNSETIFINDEX _IOW('T', 218, unsigned int) #define TUNGETFILTER _IOR('T', 219, struct sock_fprog) #define TUNSETVNETLE _IOW('T', 220, int) #define TUNGETVNETLE _IOR('T', 221, int) /* The TUNSETVNETBE and TUNGETVNETBE ioctls are for cross-endian support on * little-endian hosts. Not all kernel configurations support them, but all * configurations that support SET also support GET. */ #define TUNSETVNETBE _IOW('T', 222, int) #define TUNGETVNETBE _IOR('T', 223, int) #define TUNSETSTEERINGEBPF _IOR('T', 224, int) #define TUNSETFILTEREBPF _IOR('T', 225, int) #define TUNSETCARRIER _IOW('T', 226, int) #define TUNGETDEVNETNS _IO('T', 227) /* TUNSETIFF ifr flags */ #define IFF_TUN 0x0001 #define IFF_TAP 0x0002 #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 #define IFF_NO_PI 0x1000 /* This flag has no real effect */ #define IFF_ONE_QUEUE 0x2000 #define IFF_VNET_HDR 0x4000 #define IFF_TUN_EXCL 0x8000 #define IFF_MULTI_QUEUE 0x0100 #define IFF_ATTACH_QUEUE 0x0200 #define IFF_DETACH_QUEUE 0x0400 /* read-only flag */ #define IFF_PERSIST 0x0800 #define IFF_NOFILTER 0x1000 /* Socket options */ #define TUN_TX_TIMESTAMP 1 /* Features for GSO (TUNSETOFFLOAD). */ #define TUN_F_CSUM 0x01 /* You can hand me unchecksummed packets. */ #define TUN_F_TSO4 0x02 /* I can handle TSO for IPv4 packets */ #define TUN_F_TSO6 0x04 /* I can handle TSO for IPv6 packets */ #define TUN_F_TSO_ECN 0x08 /* I can handle TSO with ECN bits. */ #define TUN_F_UFO 0x10 /* I can handle UFO packets */ /* Protocol info prepended to the packets (when IFF_NO_PI is not set) */ #define TUN_PKT_STRIP 0x0001 struct tun_pi { __u16 flags; __be16 proto; }; /* * Filter spec (used for SETXXFILTER ioctls) * This stuff is applicable only to the TAP (Ethernet) devices. * If the count is zero the filter is disabled and the driver accepts * all packets (promisc mode). * If the filter is enabled in order to accept broadcast packets * broadcast addr must be explicitly included in the addr list. */ #define TUN_FLT_ALLMULTI 0x0001 /* Accept all multicast packets */ struct tun_filter { __u16 flags; /* TUN_FLT_ flags see above */ __u16 count; /* Number of addresses */ __u8 addr[0][ETH_ALEN]; }; #endif /* __IF_TUN_H */ linux/efs_fs_sb.h000064400000004263151027430560010015 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * efs_fs_sb.h * * Copyright (c) 1999 Al Smith * * Portions derived from IRIX header files (c) 1988 Silicon Graphics */ #ifndef __EFS_FS_SB_H__ #define __EFS_FS_SB_H__ #include #include /* EFS superblock magic numbers */ #define EFS_MAGIC 0x072959 #define EFS_NEWMAGIC 0x07295a #define IS_EFS_MAGIC(x) ((x == EFS_MAGIC) || (x == EFS_NEWMAGIC)) #define EFS_SUPER 1 #define EFS_ROOTINODE 2 /* efs superblock on disk */ struct efs_super { __be32 fs_size; /* size of filesystem, in sectors */ __be32 fs_firstcg; /* bb offset to first cg */ __be32 fs_cgfsize; /* size of cylinder group in bb's */ __be16 fs_cgisize; /* bb's of inodes per cylinder group */ __be16 fs_sectors; /* sectors per track */ __be16 fs_heads; /* heads per cylinder */ __be16 fs_ncg; /* # of cylinder groups in filesystem */ __be16 fs_dirty; /* fs needs to be fsck'd */ __be32 fs_time; /* last super-block update */ __be32 fs_magic; /* magic number */ char fs_fname[6]; /* file system name */ char fs_fpack[6]; /* file system pack name */ __be32 fs_bmsize; /* size of bitmap in bytes */ __be32 fs_tfree; /* total free data blocks */ __be32 fs_tinode; /* total free inodes */ __be32 fs_bmblock; /* bitmap location. */ __be32 fs_replsb; /* Location of replicated superblock. */ __be32 fs_lastialloc; /* last allocated inode */ char fs_spare[20]; /* space for expansion - MUST BE ZERO */ __be32 fs_checksum; /* checksum of volume portion of fs */ }; /* efs superblock information in memory */ struct efs_sb_info { __u32 fs_magic; /* superblock magic number */ __u32 fs_start; /* first block of filesystem */ __u32 first_block; /* first data block in filesystem */ __u32 total_blocks; /* total number of blocks in filesystem */ __u32 group_size; /* # of blocks a group consists of */ __u32 data_free; /* # of free data blocks */ __u32 inode_free; /* # of free inodes */ __u16 inode_blocks; /* # of blocks used for inodes in every grp */ __u16 total_groups; /* # of groups */ }; #endif /* __EFS_FS_SB_H__ */ linux/fcntl.h000064400000010116151027430560007164 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FCNTL_H #define _LINUX_FCNTL_H #include #include #define F_SETLEASE (F_LINUX_SPECIFIC_BASE + 0) #define F_GETLEASE (F_LINUX_SPECIFIC_BASE + 1) /* * Cancel a blocking posix lock; internal use only until we expose an * asynchronous lock api to userspace: */ #define F_CANCELLK (F_LINUX_SPECIFIC_BASE + 5) /* Create a file descriptor with FD_CLOEXEC set. */ #define F_DUPFD_CLOEXEC (F_LINUX_SPECIFIC_BASE + 6) /* * Request nofications on a directory. * See below for events that may be notified. */ #define F_NOTIFY (F_LINUX_SPECIFIC_BASE+2) /* * Set and get of pipe page size array */ #define F_SETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 7) #define F_GETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 8) /* * Set/Get seals */ #define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9) #define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10) /* * Types of seals */ #define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */ #define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */ #define F_SEAL_GROW 0x0004 /* prevent file from growing */ #define F_SEAL_WRITE 0x0008 /* prevent writes */ /* (1U << 31) is reserved for signed error codes */ /* * Set/Get write life time hints. {GET,SET}_RW_HINT operate on the * underlying inode, while {GET,SET}_FILE_RW_HINT operate only on * the specific file. */ #define F_GET_RW_HINT (F_LINUX_SPECIFIC_BASE + 11) #define F_SET_RW_HINT (F_LINUX_SPECIFIC_BASE + 12) #define F_GET_FILE_RW_HINT (F_LINUX_SPECIFIC_BASE + 13) #define F_SET_FILE_RW_HINT (F_LINUX_SPECIFIC_BASE + 14) /* * Valid hint values for F_{GET,SET}_RW_HINT. 0 is "not set", or can be * used to clear any hints previously set. */ #define RWH_WRITE_LIFE_NOT_SET 0 #define RWH_WRITE_LIFE_NONE 1 #define RWH_WRITE_LIFE_SHORT 2 #define RWH_WRITE_LIFE_MEDIUM 3 #define RWH_WRITE_LIFE_LONG 4 #define RWH_WRITE_LIFE_EXTREME 5 /* * The originally introduced spelling is remained from the first * versions of the patch set that introduced the feature, see commit * v4.13-rc1~212^2~51. */ #define RWF_WRITE_LIFE_NOT_SET RWH_WRITE_LIFE_NOT_SET /* * Types of directory notifications that may be requested. */ #define DN_ACCESS 0x00000001 /* File accessed */ #define DN_MODIFY 0x00000002 /* File modified */ #define DN_CREATE 0x00000004 /* File created */ #define DN_DELETE 0x00000008 /* File removed */ #define DN_RENAME 0x00000010 /* File renamed */ #define DN_ATTRIB 0x00000020 /* File changed attibutes */ #define DN_MULTISHOT 0x80000000 /* Don't remove notifier */ /* * The constants AT_REMOVEDIR and AT_EACCESS have the same value. AT_EACCESS is * meaningful only to faccessat, while AT_REMOVEDIR is meaningful only to * unlinkat. The two functions do completely different things and therefore, * the flags can be allowed to overlap. For example, passing AT_REMOVEDIR to * faccessat would be undefined behavior and thus treating it equivalent to * AT_EACCESS is valid undefined behavior. */ #define AT_FDCWD -100 /* Special value used to indicate openat should use the current working directory. */ #define AT_SYMLINK_NOFOLLOW 0x100 /* Do not follow symbolic links. */ #define AT_EACCESS 0x200 /* Test access permitted for effective IDs, not real IDs. */ #define AT_REMOVEDIR 0x200 /* Remove directory instead of unlinking file. */ #define AT_SYMLINK_FOLLOW 0x400 /* Follow symbolic links. */ #define AT_NO_AUTOMOUNT 0x800 /* Suppress terminal automount traversal */ #define AT_EMPTY_PATH 0x1000 /* Allow empty relative pathname */ #define AT_STATX_SYNC_TYPE 0x6000 /* Type of synchronisation required from statx() */ #define AT_STATX_SYNC_AS_STAT 0x0000 /* - Do whatever stat() does */ #define AT_STATX_FORCE_SYNC 0x2000 /* - Force the attributes to be sync'd with the server */ #define AT_STATX_DONT_SYNC 0x4000 /* - Don't sync attributes with the server */ #define AT_RECURSIVE 0x8000 /* Apply to the entire subtree */ #endif /* _LINUX_FCNTL_H */ linux/rfkill.h000064400000014720151027430560007346 0ustar00/* * Copyright (C) 2006 - 2007 Ivo van Doorn * Copyright (C) 2007 Dmitry Torokhov * Copyright 2009 Johannes Berg * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __RFKILL_H #define __RFKILL_H #include /* define userspace visible states */ #define RFKILL_STATE_SOFT_BLOCKED 0 #define RFKILL_STATE_UNBLOCKED 1 #define RFKILL_STATE_HARD_BLOCKED 2 /** * enum rfkill_type - type of rfkill switch. * * @RFKILL_TYPE_ALL: toggles all switches (requests only - not a switch type) * @RFKILL_TYPE_WLAN: switch is on a 802.11 wireless network device. * @RFKILL_TYPE_BLUETOOTH: switch is on a bluetooth device. * @RFKILL_TYPE_UWB: switch is on a ultra wideband device. * @RFKILL_TYPE_WIMAX: switch is on a WiMAX device. * @RFKILL_TYPE_WWAN: switch is on a wireless WAN device. * @RFKILL_TYPE_GPS: switch is on a GPS device. * @RFKILL_TYPE_FM: switch is on a FM radio device. * @RFKILL_TYPE_NFC: switch is on an NFC device. * @NUM_RFKILL_TYPES: number of defined rfkill types */ enum rfkill_type { RFKILL_TYPE_ALL = 0, RFKILL_TYPE_WLAN, RFKILL_TYPE_BLUETOOTH, RFKILL_TYPE_UWB, RFKILL_TYPE_WIMAX, RFKILL_TYPE_WWAN, RFKILL_TYPE_GPS, RFKILL_TYPE_FM, RFKILL_TYPE_NFC, NUM_RFKILL_TYPES, }; /** * enum rfkill_operation - operation types * @RFKILL_OP_ADD: a device was added * @RFKILL_OP_DEL: a device was removed * @RFKILL_OP_CHANGE: a device's state changed -- userspace changes one device * @RFKILL_OP_CHANGE_ALL: userspace changes all devices (of a type, or all) * into a state, also updating the default state used for devices that * are hot-plugged later. */ enum rfkill_operation { RFKILL_OP_ADD = 0, RFKILL_OP_DEL, RFKILL_OP_CHANGE, RFKILL_OP_CHANGE_ALL, }; /** * enum rfkill_hard_block_reasons - hard block reasons * @RFKILL_HARD_BLOCK_SIGNAL: the hardware rfkill signal is active * @RFKILL_HARD_BLOCK_NOT_OWNER: the NIC is not owned by the host */ enum rfkill_hard_block_reasons { RFKILL_HARD_BLOCK_SIGNAL = 1 << 0, RFKILL_HARD_BLOCK_NOT_OWNER = 1 << 1, }; /** * struct rfkill_event - events for userspace on /dev/rfkill * @idx: index of dev rfkill * @type: type of the rfkill struct * @op: operation code * @hard: hard state (0/1) * @soft: soft state (0/1) * * Structure used for userspace communication on /dev/rfkill, * used for events from the kernel and control to the kernel. */ struct rfkill_event { __u32 idx; __u8 type; __u8 op; __u8 soft; __u8 hard; } __attribute__((packed)); /** * struct rfkill_event_ext - events for userspace on /dev/rfkill * @idx: index of dev rfkill * @type: type of the rfkill struct * @op: operation code * @hard: hard state (0/1) * @soft: soft state (0/1) * @hard_block_reasons: valid if hard is set. One or several reasons from * &enum rfkill_hard_block_reasons. * * Structure used for userspace communication on /dev/rfkill, * used for events from the kernel and control to the kernel. * * See the extensibility docs below. */ struct rfkill_event_ext { __u32 idx; __u8 type; __u8 op; __u8 soft; __u8 hard; /* * older kernels will accept/send only up to this point, * and if extended further up to any chunk marked below */ __u8 hard_block_reasons; } __attribute__((packed)); /** * DOC: Extensibility * * Originally, we had planned to allow backward and forward compatible * changes by just adding fields at the end of the structure that are * then not reported on older kernels on read(), and not written to by * older kernels on write(), with the kernel reporting the size it did * accept as the result. * * This would have allowed userspace to detect on read() and write() * which kernel structure version it was dealing with, and if was just * recompiled it would have gotten the new fields, but obviously not * accessed them, but things should've continued to work. * * Unfortunately, while actually exercising this mechanism to add the * hard block reasons field, we found that userspace (notably systemd) * did all kinds of fun things not in line with this scheme: * * 1. treat the (expected) short writes as an error; * 2. ask to read sizeof(struct rfkill_event) but then compare the * actual return value to RFKILL_EVENT_SIZE_V1 and treat any * mismatch as an error. * * As a consequence, just recompiling with a new struct version caused * things to no longer work correctly on old and new kernels. * * Hence, we've rolled back &struct rfkill_event to the original version * and added &struct rfkill_event_ext. This effectively reverts to the * old behaviour for all userspace, unless it explicitly opts in to the * rules outlined here by using the new &struct rfkill_event_ext. * * Additionally, some other userspace (bluez, g-s-d) was reading with a * large size but as streaming reads rather than message-based, or with * too strict checks for the returned size. So eventually, we completely * reverted this, and extended messages need to be opted in to by using * an ioctl: * * ioctl(fd, RFKILL_IOCTL_MAX_SIZE, sizeof(struct rfkill_event_ext)); * * Userspace using &struct rfkill_event_ext and the ioctl must adhere to * the following rules: * * 1. accept short writes, optionally using them to detect that it's * running on an older kernel; * 2. accept short reads, knowing that this means it's running on an * older kernel; * 3. treat reads that are as long as requested as acceptable, not * checking against RFKILL_EVENT_SIZE_V1 or such. */ #define RFKILL_EVENT_SIZE_V1 sizeof(struct rfkill_event) /* ioctl for turning off rfkill-input (if present) */ #define RFKILL_IOC_MAGIC 'R' #define RFKILL_IOC_NOINPUT 1 #define RFKILL_IOCTL_NOINPUT _IO(RFKILL_IOC_MAGIC, RFKILL_IOC_NOINPUT) #define RFKILL_IOC_MAX_SIZE 2 #define RFKILL_IOCTL_MAX_SIZE _IOW(RFKILL_IOC_MAGIC, RFKILL_IOC_EXT_SIZE, __u32) /* and that's all userspace gets */ #endif /* __RFKILL_H */ linux/sonypi.h000064400000012275151027430560007407 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Sony Programmable I/O Control Device driver for VAIO * * Copyright (C) 2001-2005 Stelian Pop * * Copyright (C) 2005 Narayanan R S * Copyright (C) 2001-2002 Alcôve * * Copyright (C) 2001 Michael Ashley * * Copyright (C) 2001 Junichi Morita * * Copyright (C) 2000 Takaya Kinjo * * Copyright (C) 2000 Andrew Tridgell * * Earlier work by Werner Almesberger, Paul `Rusty' Russell and Paul Mackerras. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #ifndef _SONYPI_H_ #define _SONYPI_H_ #include /* events the user application reading /dev/sonypi can use */ #define SONYPI_EVENT_IGNORE 0 #define SONYPI_EVENT_JOGDIAL_DOWN 1 #define SONYPI_EVENT_JOGDIAL_UP 2 #define SONYPI_EVENT_JOGDIAL_DOWN_PRESSED 3 #define SONYPI_EVENT_JOGDIAL_UP_PRESSED 4 #define SONYPI_EVENT_JOGDIAL_PRESSED 5 #define SONYPI_EVENT_JOGDIAL_RELEASED 6 /* obsolete */ #define SONYPI_EVENT_CAPTURE_PRESSED 7 #define SONYPI_EVENT_CAPTURE_RELEASED 8 /* obsolete */ #define SONYPI_EVENT_CAPTURE_PARTIALPRESSED 9 #define SONYPI_EVENT_CAPTURE_PARTIALRELEASED 10 #define SONYPI_EVENT_FNKEY_ESC 11 #define SONYPI_EVENT_FNKEY_F1 12 #define SONYPI_EVENT_FNKEY_F2 13 #define SONYPI_EVENT_FNKEY_F3 14 #define SONYPI_EVENT_FNKEY_F4 15 #define SONYPI_EVENT_FNKEY_F5 16 #define SONYPI_EVENT_FNKEY_F6 17 #define SONYPI_EVENT_FNKEY_F7 18 #define SONYPI_EVENT_FNKEY_F8 19 #define SONYPI_EVENT_FNKEY_F9 20 #define SONYPI_EVENT_FNKEY_F10 21 #define SONYPI_EVENT_FNKEY_F11 22 #define SONYPI_EVENT_FNKEY_F12 23 #define SONYPI_EVENT_FNKEY_1 24 #define SONYPI_EVENT_FNKEY_2 25 #define SONYPI_EVENT_FNKEY_D 26 #define SONYPI_EVENT_FNKEY_E 27 #define SONYPI_EVENT_FNKEY_F 28 #define SONYPI_EVENT_FNKEY_S 29 #define SONYPI_EVENT_FNKEY_B 30 #define SONYPI_EVENT_BLUETOOTH_PRESSED 31 #define SONYPI_EVENT_PKEY_P1 32 #define SONYPI_EVENT_PKEY_P2 33 #define SONYPI_EVENT_PKEY_P3 34 #define SONYPI_EVENT_BACK_PRESSED 35 #define SONYPI_EVENT_LID_CLOSED 36 #define SONYPI_EVENT_LID_OPENED 37 #define SONYPI_EVENT_BLUETOOTH_ON 38 #define SONYPI_EVENT_BLUETOOTH_OFF 39 #define SONYPI_EVENT_HELP_PRESSED 40 #define SONYPI_EVENT_FNKEY_ONLY 41 #define SONYPI_EVENT_JOGDIAL_FAST_DOWN 42 #define SONYPI_EVENT_JOGDIAL_FAST_UP 43 #define SONYPI_EVENT_JOGDIAL_FAST_DOWN_PRESSED 44 #define SONYPI_EVENT_JOGDIAL_FAST_UP_PRESSED 45 #define SONYPI_EVENT_JOGDIAL_VFAST_DOWN 46 #define SONYPI_EVENT_JOGDIAL_VFAST_UP 47 #define SONYPI_EVENT_JOGDIAL_VFAST_DOWN_PRESSED 48 #define SONYPI_EVENT_JOGDIAL_VFAST_UP_PRESSED 49 #define SONYPI_EVENT_ZOOM_PRESSED 50 #define SONYPI_EVENT_THUMBPHRASE_PRESSED 51 #define SONYPI_EVENT_MEYE_FACE 52 #define SONYPI_EVENT_MEYE_OPPOSITE 53 #define SONYPI_EVENT_MEMORYSTICK_INSERT 54 #define SONYPI_EVENT_MEMORYSTICK_EJECT 55 #define SONYPI_EVENT_ANYBUTTON_RELEASED 56 #define SONYPI_EVENT_BATTERY_INSERT 57 #define SONYPI_EVENT_BATTERY_REMOVE 58 #define SONYPI_EVENT_FNKEY_RELEASED 59 #define SONYPI_EVENT_WIRELESS_ON 60 #define SONYPI_EVENT_WIRELESS_OFF 61 #define SONYPI_EVENT_ZOOM_IN_PRESSED 62 #define SONYPI_EVENT_ZOOM_OUT_PRESSED 63 #define SONYPI_EVENT_CD_EJECT_PRESSED 64 #define SONYPI_EVENT_MODEKEY_PRESSED 65 #define SONYPI_EVENT_PKEY_P4 66 #define SONYPI_EVENT_PKEY_P5 67 #define SONYPI_EVENT_SETTINGKEY_PRESSED 68 #define SONYPI_EVENT_VOLUME_INC_PRESSED 69 #define SONYPI_EVENT_VOLUME_DEC_PRESSED 70 #define SONYPI_EVENT_BRIGHTNESS_PRESSED 71 #define SONYPI_EVENT_MEDIA_PRESSED 72 #define SONYPI_EVENT_VENDOR_PRESSED 73 /* get/set brightness */ #define SONYPI_IOCGBRT _IOR('v', 0, __u8) #define SONYPI_IOCSBRT _IOW('v', 0, __u8) /* get battery full capacity/remaining capacity */ #define SONYPI_IOCGBAT1CAP _IOR('v', 2, __u16) #define SONYPI_IOCGBAT1REM _IOR('v', 3, __u16) #define SONYPI_IOCGBAT2CAP _IOR('v', 4, __u16) #define SONYPI_IOCGBAT2REM _IOR('v', 5, __u16) /* get battery flags: battery1/battery2/ac adapter present */ #define SONYPI_BFLAGS_B1 0x01 #define SONYPI_BFLAGS_B2 0x02 #define SONYPI_BFLAGS_AC 0x04 #define SONYPI_IOCGBATFLAGS _IOR('v', 7, __u8) /* get/set bluetooth subsystem state on/off */ #define SONYPI_IOCGBLUE _IOR('v', 8, __u8) #define SONYPI_IOCSBLUE _IOW('v', 9, __u8) /* get/set fan state on/off */ #define SONYPI_IOCGFAN _IOR('v', 10, __u8) #define SONYPI_IOCSFAN _IOW('v', 11, __u8) /* get temperature (C) */ #define SONYPI_IOCGTEMP _IOR('v', 12, __u8) #endif /* _SONYPI_H_ */ linux/virtio_net.h000064400000024465151027430560010254 0ustar00#ifndef _LINUX_VIRTIO_NET_H #define _LINUX_VIRTIO_NET_H /* This header is BSD licensed so anyone can use the definitions to implement * compatible drivers/servers. * * 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. Neither the name of IBM nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include /* The feature bitmap for virtio net */ #define VIRTIO_NET_F_CSUM 0 /* Host handles pkts w/ partial csum */ #define VIRTIO_NET_F_GUEST_CSUM 1 /* Guest handles pkts w/ partial csum */ #define VIRTIO_NET_F_CTRL_GUEST_OFFLOADS 2 /* Dynamic offload configuration. */ #define VIRTIO_NET_F_MTU 3 /* Initial MTU advice */ #define VIRTIO_NET_F_MAC 5 /* Host has given MAC address. */ #define VIRTIO_NET_F_GUEST_TSO4 7 /* Guest can handle TSOv4 in. */ #define VIRTIO_NET_F_GUEST_TSO6 8 /* Guest can handle TSOv6 in. */ #define VIRTIO_NET_F_GUEST_ECN 9 /* Guest can handle TSO[6] w/ ECN in. */ #define VIRTIO_NET_F_GUEST_UFO 10 /* Guest can handle UFO in. */ #define VIRTIO_NET_F_HOST_TSO4 11 /* Host can handle TSOv4 in. */ #define VIRTIO_NET_F_HOST_TSO6 12 /* Host can handle TSOv6 in. */ #define VIRTIO_NET_F_HOST_ECN 13 /* Host can handle TSO[6] w/ ECN in. */ #define VIRTIO_NET_F_HOST_UFO 14 /* Host can handle UFO in. */ #define VIRTIO_NET_F_MRG_RXBUF 15 /* Host can merge receive buffers. */ #define VIRTIO_NET_F_STATUS 16 /* virtio_net_config.status available */ #define VIRTIO_NET_F_CTRL_VQ 17 /* Control channel available */ #define VIRTIO_NET_F_CTRL_RX 18 /* Control channel RX mode support */ #define VIRTIO_NET_F_CTRL_VLAN 19 /* Control channel VLAN filtering */ #define VIRTIO_NET_F_CTRL_RX_EXTRA 20 /* Extra RX mode control support */ #define VIRTIO_NET_F_GUEST_ANNOUNCE 21 /* Guest can announce device on the * network */ #define VIRTIO_NET_F_MQ 22 /* Device supports Receive Flow * Steering */ #define VIRTIO_NET_F_CTRL_MAC_ADDR 23 /* Set MAC address */ #define VIRTIO_NET_F_STANDBY 62 /* Act as standby for another device * with the same MAC. */ #define VIRTIO_NET_F_SPEED_DUPLEX 63 /* Device set linkspeed and duplex */ #ifndef VIRTIO_NET_NO_LEGACY #define VIRTIO_NET_F_GSO 6 /* Host handles pkts w/ any GSO type */ #endif /* VIRTIO_NET_NO_LEGACY */ #define VIRTIO_NET_S_LINK_UP 1 /* Link is up */ #define VIRTIO_NET_S_ANNOUNCE 2 /* Announcement is needed */ struct virtio_net_config { /* The config defining mac address (if VIRTIO_NET_F_MAC) */ __u8 mac[ETH_ALEN]; /* See VIRTIO_NET_F_STATUS and VIRTIO_NET_S_* above */ __u16 status; /* Maximum number of each of transmit and receive queues; * see VIRTIO_NET_F_MQ and VIRTIO_NET_CTRL_MQ. * Legal values are between 1 and 0x8000 */ __u16 max_virtqueue_pairs; /* Default maximum transmit unit advice */ __u16 mtu; /* * speed, in units of 1Mb. All values 0 to INT_MAX are legal. * Any other value stands for unknown. */ __u32 speed; /* * 0x00 - half duplex * 0x01 - full duplex * Any other value stands for unknown. */ __u8 duplex; } __attribute__((packed)); /* * This header comes first in the scatter-gather list. If you don't * specify GSO or CSUM features, you can simply ignore the header. * * This is bitwise-equivalent to the legacy struct virtio_net_hdr_mrg_rxbuf, * only flattened. */ struct virtio_net_hdr_v1 { #define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 /* Use csum_start, csum_offset */ #define VIRTIO_NET_HDR_F_DATA_VALID 2 /* Csum is valid */ __u8 flags; #define VIRTIO_NET_HDR_GSO_NONE 0 /* Not a GSO frame */ #define VIRTIO_NET_HDR_GSO_TCPV4 1 /* GSO frame, IPv4 TCP (TSO) */ #define VIRTIO_NET_HDR_GSO_UDP 3 /* GSO frame, IPv4 UDP (UFO) */ #define VIRTIO_NET_HDR_GSO_TCPV6 4 /* GSO frame, IPv6 TCP */ #define VIRTIO_NET_HDR_GSO_ECN 0x80 /* TCP has ECN set */ __u8 gso_type; __virtio16 hdr_len; /* Ethernet + IP + tcp/udp hdrs */ __virtio16 gso_size; /* Bytes to append to hdr_len per frame */ __virtio16 csum_start; /* Position to start checksumming from */ __virtio16 csum_offset; /* Offset after that to place checksum */ __virtio16 num_buffers; /* Number of merged rx buffers */ }; #ifndef VIRTIO_NET_NO_LEGACY /* This header comes first in the scatter-gather list. * For legacy virtio, if VIRTIO_F_ANY_LAYOUT is not negotiated, it must * be the first element of the scatter-gather list. If you don't * specify GSO or CSUM features, you can simply ignore the header. */ struct virtio_net_hdr { /* See VIRTIO_NET_HDR_F_* */ __u8 flags; /* See VIRTIO_NET_HDR_GSO_* */ __u8 gso_type; __virtio16 hdr_len; /* Ethernet + IP + tcp/udp hdrs */ __virtio16 gso_size; /* Bytes to append to hdr_len per frame */ __virtio16 csum_start; /* Position to start checksumming from */ __virtio16 csum_offset; /* Offset after that to place checksum */ }; /* This is the version of the header to use when the MRG_RXBUF * feature has been negotiated. */ struct virtio_net_hdr_mrg_rxbuf { struct virtio_net_hdr hdr; __virtio16 num_buffers; /* Number of merged rx buffers */ }; #endif /* ...VIRTIO_NET_NO_LEGACY */ /* * Control virtqueue data structures * * The control virtqueue expects a header in the first sg entry * and an ack/status response in the last entry. Data for the * command goes in between. */ struct virtio_net_ctrl_hdr { __u8 class; __u8 cmd; } __attribute__((packed)); typedef __u8 virtio_net_ctrl_ack; #define VIRTIO_NET_OK 0 #define VIRTIO_NET_ERR 1 /* * Control the RX mode, ie. promisucous, allmulti, etc... * All commands require an "out" sg entry containing a 1 byte * state value, zero = disable, non-zero = enable. Commands * 0 and 1 are supported with the VIRTIO_NET_F_CTRL_RX feature. * Commands 2-5 are added with VIRTIO_NET_F_CTRL_RX_EXTRA. */ #define VIRTIO_NET_CTRL_RX 0 #define VIRTIO_NET_CTRL_RX_PROMISC 0 #define VIRTIO_NET_CTRL_RX_ALLMULTI 1 #define VIRTIO_NET_CTRL_RX_ALLUNI 2 #define VIRTIO_NET_CTRL_RX_NOMULTI 3 #define VIRTIO_NET_CTRL_RX_NOUNI 4 #define VIRTIO_NET_CTRL_RX_NOBCAST 5 /* * Control the MAC * * The MAC filter table is managed by the hypervisor, the guest should * assume the size is infinite. Filtering should be considered * non-perfect, ie. based on hypervisor resources, the guest may * received packets from sources not specified in the filter list. * * In addition to the class/cmd header, the TABLE_SET command requires * two out scatterlists. Each contains a 4 byte count of entries followed * by a concatenated byte stream of the ETH_ALEN MAC addresses. The * first sg list contains unicast addresses, the second is for multicast. * This functionality is present if the VIRTIO_NET_F_CTRL_RX feature * is available. * * The ADDR_SET command requests one out scatterlist, it contains a * 6 bytes MAC address. This functionality is present if the * VIRTIO_NET_F_CTRL_MAC_ADDR feature is available. */ struct virtio_net_ctrl_mac { __virtio32 entries; __u8 macs[][ETH_ALEN]; } __attribute__((packed)); #define VIRTIO_NET_CTRL_MAC 1 #define VIRTIO_NET_CTRL_MAC_TABLE_SET 0 #define VIRTIO_NET_CTRL_MAC_ADDR_SET 1 /* * Control VLAN filtering * * The VLAN filter table is controlled via a simple ADD/DEL interface. * VLAN IDs not added may be filterd by the hypervisor. Del is the * opposite of add. Both commands expect an out entry containing a 2 * byte VLAN ID. VLAN filterting is available with the * VIRTIO_NET_F_CTRL_VLAN feature bit. */ #define VIRTIO_NET_CTRL_VLAN 2 #define VIRTIO_NET_CTRL_VLAN_ADD 0 #define VIRTIO_NET_CTRL_VLAN_DEL 1 /* * Control link announce acknowledgement * * The command VIRTIO_NET_CTRL_ANNOUNCE_ACK is used to indicate that * driver has recevied the notification; device would clear the * VIRTIO_NET_S_ANNOUNCE bit in the status field after it receives * this command. */ #define VIRTIO_NET_CTRL_ANNOUNCE 3 #define VIRTIO_NET_CTRL_ANNOUNCE_ACK 0 /* * Control Receive Flow Steering * * The command VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET * enables Receive Flow Steering, specifying the number of the transmit and * receive queues that will be used. After the command is consumed and acked by * the device, the device will not steer new packets on receive virtqueues * other than specified nor read from transmit virtqueues other than specified. * Accordingly, driver should not transmit new packets on virtqueues other than * specified. */ struct virtio_net_ctrl_mq { __virtio16 virtqueue_pairs; }; #define VIRTIO_NET_CTRL_MQ 4 #define VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET 0 #define VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN 1 #define VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX 0x8000 /* * Control network offloads * * Reconfigures the network offloads that Guest can handle. * * Available with the VIRTIO_NET_F_CTRL_GUEST_OFFLOADS feature bit. * * Command data format matches the feature bit mask exactly. * * See VIRTIO_NET_F_GUEST_* for the list of offloads * that can be enabled/disabled. */ #define VIRTIO_NET_CTRL_GUEST_OFFLOADS 5 #define VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET 0 #endif /* _LINUX_VIRTIO_NET_H */ linux/in6.h000064400000016416151027430560006563 0ustar00/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Types and definitions for AF_INET6 * Linux INET6 implementation * * Authors: * Pedro Roque * * Sources: * IPv6 Program Interfaces for BSD Systems * * * Advanced Sockets API for IPv6 * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IN6_H #define _LINUX_IN6_H #include #include /* * IPv6 address structure */ #if __UAPI_DEF_IN6_ADDR struct in6_addr { union { __u8 u6_addr8[16]; #if __UAPI_DEF_IN6_ADDR_ALT __be16 u6_addr16[8]; __be32 u6_addr32[4]; #endif } in6_u; #define s6_addr in6_u.u6_addr8 #if __UAPI_DEF_IN6_ADDR_ALT #define s6_addr16 in6_u.u6_addr16 #define s6_addr32 in6_u.u6_addr32 #endif }; #endif /* __UAPI_DEF_IN6_ADDR */ #if __UAPI_DEF_SOCKADDR_IN6 struct sockaddr_in6 { unsigned short int sin6_family; /* AF_INET6 */ __be16 sin6_port; /* Transport layer port # */ __be32 sin6_flowinfo; /* IPv6 flow information */ struct in6_addr sin6_addr; /* IPv6 address */ __u32 sin6_scope_id; /* scope id (new in RFC2553) */ }; #endif /* __UAPI_DEF_SOCKADDR_IN6 */ #if __UAPI_DEF_IPV6_MREQ struct ipv6_mreq { /* IPv6 multicast address of group */ struct in6_addr ipv6mr_multiaddr; /* local IPv6 address of interface */ int ipv6mr_ifindex; }; #endif /* __UAPI_DEF_IVP6_MREQ */ #define ipv6mr_acaddr ipv6mr_multiaddr struct in6_flowlabel_req { struct in6_addr flr_dst; __be32 flr_label; __u8 flr_action; __u8 flr_share; __u16 flr_flags; __u16 flr_expires; __u16 flr_linger; __u32 __flr_pad; /* Options in format of IPV6_PKTOPTIONS */ }; #define IPV6_FL_A_GET 0 #define IPV6_FL_A_PUT 1 #define IPV6_FL_A_RENEW 2 #define IPV6_FL_F_CREATE 1 #define IPV6_FL_F_EXCL 2 #define IPV6_FL_F_REFLECT 4 #define IPV6_FL_F_REMOTE 8 #define IPV6_FL_S_NONE 0 #define IPV6_FL_S_EXCL 1 #define IPV6_FL_S_PROCESS 2 #define IPV6_FL_S_USER 3 #define IPV6_FL_S_ANY 255 /* * Bitmask constant declarations to help applications select out the * flow label and priority fields. * * Note that this are in host byte order while the flowinfo field of * sockaddr_in6 is in network byte order. */ #define IPV6_FLOWINFO_FLOWLABEL 0x000fffff #define IPV6_FLOWINFO_PRIORITY 0x0ff00000 /* These definitions are obsolete */ #define IPV6_PRIORITY_UNCHARACTERIZED 0x0000 #define IPV6_PRIORITY_FILLER 0x0100 #define IPV6_PRIORITY_UNATTENDED 0x0200 #define IPV6_PRIORITY_RESERVED1 0x0300 #define IPV6_PRIORITY_BULK 0x0400 #define IPV6_PRIORITY_RESERVED2 0x0500 #define IPV6_PRIORITY_INTERACTIVE 0x0600 #define IPV6_PRIORITY_CONTROL 0x0700 #define IPV6_PRIORITY_8 0x0800 #define IPV6_PRIORITY_9 0x0900 #define IPV6_PRIORITY_10 0x0a00 #define IPV6_PRIORITY_11 0x0b00 #define IPV6_PRIORITY_12 0x0c00 #define IPV6_PRIORITY_13 0x0d00 #define IPV6_PRIORITY_14 0x0e00 #define IPV6_PRIORITY_15 0x0f00 /* * IPV6 extension headers */ #if __UAPI_DEF_IPPROTO_V6 #define IPPROTO_HOPOPTS 0 /* IPv6 hop-by-hop options */ #define IPPROTO_ROUTING 43 /* IPv6 routing header */ #define IPPROTO_FRAGMENT 44 /* IPv6 fragmentation header */ #define IPPROTO_ICMPV6 58 /* ICMPv6 */ #define IPPROTO_NONE 59 /* IPv6 no next header */ #define IPPROTO_DSTOPTS 60 /* IPv6 destination options */ #define IPPROTO_MH 135 /* IPv6 mobility header */ #endif /* __UAPI_DEF_IPPROTO_V6 */ /* * IPv6 TLV options. */ #define IPV6_TLV_PAD1 0 #define IPV6_TLV_PADN 1 #define IPV6_TLV_ROUTERALERT 5 #define IPV6_TLV_CALIPSO 7 /* RFC 5570 */ #define IPV6_TLV_JUMBO 194 #define IPV6_TLV_HAO 201 /* home address option */ /* * IPV6 socket options */ #if __UAPI_DEF_IPV6_OPTIONS #define IPV6_ADDRFORM 1 #define IPV6_2292PKTINFO 2 #define IPV6_2292HOPOPTS 3 #define IPV6_2292DSTOPTS 4 #define IPV6_2292RTHDR 5 #define IPV6_2292PKTOPTIONS 6 #define IPV6_CHECKSUM 7 #define IPV6_2292HOPLIMIT 8 #define IPV6_NEXTHOP 9 #define IPV6_AUTHHDR 10 /* obsolete */ #define IPV6_FLOWINFO 11 #define IPV6_UNICAST_HOPS 16 #define IPV6_MULTICAST_IF 17 #define IPV6_MULTICAST_HOPS 18 #define IPV6_MULTICAST_LOOP 19 #define IPV6_ADD_MEMBERSHIP 20 #define IPV6_DROP_MEMBERSHIP 21 #define IPV6_ROUTER_ALERT 22 #define IPV6_MTU_DISCOVER 23 #define IPV6_MTU 24 #define IPV6_RECVERR 25 #define IPV6_V6ONLY 26 #define IPV6_JOIN_ANYCAST 27 #define IPV6_LEAVE_ANYCAST 28 /* IPV6_MTU_DISCOVER values */ #define IPV6_PMTUDISC_DONT 0 #define IPV6_PMTUDISC_WANT 1 #define IPV6_PMTUDISC_DO 2 #define IPV6_PMTUDISC_PROBE 3 /* same as IPV6_PMTUDISC_PROBE, provided for symetry with IPv4 * also see comments on IP_PMTUDISC_INTERFACE */ #define IPV6_PMTUDISC_INTERFACE 4 /* weaker version of IPV6_PMTUDISC_INTERFACE, which allows packets to * get fragmented if they exceed the interface mtu */ #define IPV6_PMTUDISC_OMIT 5 /* Flowlabel */ #define IPV6_FLOWLABEL_MGR 32 #define IPV6_FLOWINFO_SEND 33 #define IPV6_IPSEC_POLICY 34 #define IPV6_XFRM_POLICY 35 #define IPV6_HDRINCL 36 #endif /* * Multicast: * Following socket options are shared between IPv4 and IPv6. * * MCAST_JOIN_GROUP 42 * MCAST_BLOCK_SOURCE 43 * MCAST_UNBLOCK_SOURCE 44 * MCAST_LEAVE_GROUP 45 * MCAST_JOIN_SOURCE_GROUP 46 * MCAST_LEAVE_SOURCE_GROUP 47 * MCAST_MSFILTER 48 */ /* * Advanced API (RFC3542) (1) * * Note: IPV6_RECVRTHDRDSTOPTS does not exist. see net/ipv6/datagram.c. */ #define IPV6_RECVPKTINFO 49 #define IPV6_PKTINFO 50 #define IPV6_RECVHOPLIMIT 51 #define IPV6_HOPLIMIT 52 #define IPV6_RECVHOPOPTS 53 #define IPV6_HOPOPTS 54 #define IPV6_RTHDRDSTOPTS 55 #define IPV6_RECVRTHDR 56 #define IPV6_RTHDR 57 #define IPV6_RECVDSTOPTS 58 #define IPV6_DSTOPTS 59 #define IPV6_RECVPATHMTU 60 #define IPV6_PATHMTU 61 #define IPV6_DONTFRAG 62 #if 0 /* not yet */ #define IPV6_USE_MIN_MTU 63 #endif /* * Netfilter (1) * * Following socket options are used in ip6_tables; * see include/linux/netfilter_ipv6/ip6_tables.h. * * IP6T_SO_SET_REPLACE / IP6T_SO_GET_INFO 64 * IP6T_SO_SET_ADD_COUNTERS / IP6T_SO_GET_ENTRIES 65 */ /* * Advanced API (RFC3542) (2) */ #define IPV6_RECVTCLASS 66 #define IPV6_TCLASS 67 /* * Netfilter (2) * * Following socket options are used in ip6_tables; * see include/linux/netfilter_ipv6/ip6_tables.h. * * IP6T_SO_GET_REVISION_MATCH 68 * IP6T_SO_GET_REVISION_TARGET 69 * IP6T_SO_ORIGINAL_DST 80 */ #define IPV6_AUTOFLOWLABEL 70 /* RFC5014: Source address selection */ #define IPV6_ADDR_PREFERENCES 72 #define IPV6_PREFER_SRC_TMP 0x0001 #define IPV6_PREFER_SRC_PUBLIC 0x0002 #define IPV6_PREFER_SRC_PUBTMP_DEFAULT 0x0100 #define IPV6_PREFER_SRC_COA 0x0004 #define IPV6_PREFER_SRC_HOME 0x0400 #define IPV6_PREFER_SRC_CGA 0x0008 #define IPV6_PREFER_SRC_NONCGA 0x0800 /* RFC5082: Generalized Ttl Security Mechanism */ #define IPV6_MINHOPCOUNT 73 #define IPV6_ORIGDSTADDR 74 #define IPV6_RECVORIGDSTADDR IPV6_ORIGDSTADDR #define IPV6_TRANSPARENT 75 #define IPV6_UNICAST_IF 76 #define IPV6_RECVFRAGSIZE 77 #define IPV6_FREEBIND 78 /* * Multicast Routing: * see include/uapi/linux/mroute6.h. * * MRT6_BASE 200 * ... * MRT6_MAX */ #endif /* _LINUX_IN6_H */ linux/bpf_common.h000064400000002527151027430560010204 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_BPF_COMMON_H__ #define __LINUX_BPF_COMMON_H__ /* Instruction classes */ #define BPF_CLASS(code) ((code) & 0x07) #define BPF_LD 0x00 #define BPF_LDX 0x01 #define BPF_ST 0x02 #define BPF_STX 0x03 #define BPF_ALU 0x04 #define BPF_JMP 0x05 #define BPF_RET 0x06 #define BPF_MISC 0x07 /* ld/ldx fields */ #define BPF_SIZE(code) ((code) & 0x18) #define BPF_W 0x00 /* 32-bit */ #define BPF_H 0x08 /* 16-bit */ #define BPF_B 0x10 /* 8-bit */ /* eBPF BPF_DW 0x18 64-bit */ #define BPF_MODE(code) ((code) & 0xe0) #define BPF_IMM 0x00 #define BPF_ABS 0x20 #define BPF_IND 0x40 #define BPF_MEM 0x60 #define BPF_LEN 0x80 #define BPF_MSH 0xa0 /* alu/jmp fields */ #define BPF_OP(code) ((code) & 0xf0) #define BPF_ADD 0x00 #define BPF_SUB 0x10 #define BPF_MUL 0x20 #define BPF_DIV 0x30 #define BPF_OR 0x40 #define BPF_AND 0x50 #define BPF_LSH 0x60 #define BPF_RSH 0x70 #define BPF_NEG 0x80 #define BPF_MOD 0x90 #define BPF_XOR 0xa0 #define BPF_JA 0x00 #define BPF_JEQ 0x10 #define BPF_JGT 0x20 #define BPF_JGE 0x30 #define BPF_JSET 0x40 #define BPF_SRC(code) ((code) & 0x08) #define BPF_K 0x00 #define BPF_X 0x08 #ifndef BPF_MAXINSNS #define BPF_MAXINSNS 4096 #endif #endif /* __LINUX_BPF_COMMON_H__ */ linux/posix_types.h000064400000002112151027430560010441 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_POSIX_TYPES_H #define _LINUX_POSIX_TYPES_H #include /* * This allows for 1024 file descriptors: if NR_OPEN is ever grown * beyond that you'll have to change this too. But 1024 fd's seem to be * enough even for such "real" unices like OSF/1, so hopefully this is * one limit that doesn't have to be changed [again]. * * Note that POSIX wants the FD_CLEAR(fd,fdsetp) defines to be in * (and thus ) - but this is a more logical * place for them. Solved by having dummy defines in . */ /* * This macro may have been defined in . But we always * use the one here. */ #undef __FD_SETSIZE #define __FD_SETSIZE 1024 typedef struct { unsigned long fds_bits[__FD_SETSIZE / (8 * sizeof(long))]; } __kernel_fd_set; /* Type of a signal handler. */ typedef void (*__kernel_sighandler_t)(int); /* Type of a SYSV IPC key. */ typedef int __kernel_key_t; typedef int __kernel_mqd_t; #include #endif /* _LINUX_POSIX_TYPES_H */ linux/fd.h000064400000026630151027430560006457 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_FD_H #define _LINUX_FD_H #include /* New file layout: Now the ioctl definitions immediately follow the * definitions of the structures that they use */ /* * Geometry */ struct floppy_struct { unsigned int size, /* nr of sectors total */ sect, /* sectors per track */ head, /* nr of heads */ track, /* nr of tracks */ stretch; /* bit 0 !=0 means double track steps */ /* bit 1 != 0 means swap sides */ /* bits 2..9 give the first sector */ /* number (the LSB is flipped) */ #define FD_STRETCH 1 #define FD_SWAPSIDES 2 #define FD_ZEROBASED 4 #define FD_SECTBASEMASK 0x3FC #define FD_MKSECTBASE(s) (((s) ^ 1) << 2) #define FD_SECTBASE(floppy) ((((floppy)->stretch & FD_SECTBASEMASK) >> 2) ^ 1) unsigned char gap, /* gap1 size */ rate, /* data rate. |= 0x40 for perpendicular */ #define FD_2M 0x4 #define FD_SIZECODEMASK 0x38 #define FD_SIZECODE(floppy) (((((floppy)->rate&FD_SIZECODEMASK)>> 3)+ 2) %8) #define FD_SECTSIZE(floppy) ( (floppy)->rate & FD_2M ? \ 512 : 128 << FD_SIZECODE(floppy) ) #define FD_PERP 0x40 spec1, /* stepping rate, head unload time */ fmt_gap; /* gap2 size */ const char * name; /* used only for predefined formats */ }; /* commands needing write access have 0x40 set */ /* commands needing super user access have 0x80 set */ #define FDCLRPRM _IO(2, 0x41) /* clear user-defined parameters */ #define FDSETPRM _IOW(2, 0x42, struct floppy_struct) #define FDSETMEDIAPRM FDSETPRM /* set user-defined parameters for current media */ #define FDDEFPRM _IOW(2, 0x43, struct floppy_struct) #define FDGETPRM _IOR(2, 0x04, struct floppy_struct) #define FDDEFMEDIAPRM FDDEFPRM #define FDGETMEDIAPRM FDGETPRM /* set/get disk parameters */ #define FDMSGON _IO(2,0x45) #define FDMSGOFF _IO(2,0x46) /* issue/don't issue kernel messages on media type change */ /* * Formatting (obsolete) */ #define FD_FILL_BYTE 0xF6 /* format fill byte. */ struct format_descr { unsigned int device,head,track; }; #define FDFMTBEG _IO(2,0x47) /* begin formatting a disk */ #define FDFMTTRK _IOW(2,0x48, struct format_descr) /* format the specified track */ #define FDFMTEND _IO(2,0x49) /* end formatting a disk */ /* * Error thresholds */ struct floppy_max_errors { unsigned int abort, /* number of errors to be reached before aborting */ read_track, /* maximal number of errors permitted to read an * entire track at once */ reset, /* maximal number of errors before a reset is tried */ recal, /* maximal number of errors before a recalibrate is * tried */ /* * Threshold for reporting FDC errors to the console. * Setting this to zero may flood your screen when using * ultra cheap floppies ;-) */ reporting; }; #define FDSETEMSGTRESH _IO(2,0x4a) /* set fdc error reporting threshold */ #define FDFLUSH _IO(2,0x4b) /* flush buffers for media; either for verifying media, or for * handling a media change without closing the file descriptor */ #define FDSETMAXERRS _IOW(2, 0x4c, struct floppy_max_errors) #define FDGETMAXERRS _IOR(2, 0x0e, struct floppy_max_errors) /* set/get abortion and read_track threshold. See also floppy_drive_params * structure */ typedef char floppy_drive_name[16]; #define FDGETDRVTYP _IOR(2, 0x0f, floppy_drive_name) /* get drive type: 5 1/4 or 3 1/2 */ /* * Drive parameters (user modifiable) */ struct floppy_drive_params { signed char cmos; /* CMOS type */ /* Spec2 is (HLD<<1 | ND), where HLD is head load time (1=2ms, 2=4 ms * etc) and ND is set means no DMA. Hardcoded to 6 (HLD=6ms, use DMA). */ unsigned long max_dtr; /* Step rate, usec */ unsigned long hlt; /* Head load/settle time, msec */ unsigned long hut; /* Head unload time (remnant of * 8" drives) */ unsigned long srt; /* Step rate, usec */ unsigned long spinup; /* time needed for spinup (expressed * in jiffies) */ unsigned long spindown; /* timeout needed for spindown */ unsigned char spindown_offset; /* decides in which position the disk * will stop */ unsigned char select_delay; /* delay to wait after select */ unsigned char rps; /* rotations per second */ unsigned char tracks; /* maximum number of tracks */ unsigned long timeout; /* timeout for interrupt requests */ unsigned char interleave_sect; /* if there are more sectors, use * interleave */ struct floppy_max_errors max_errors; char flags; /* various flags, including ftd_msg */ /* * Announce successful media type detection and media information loss after * disk changes. * Also used to enable/disable printing of overrun warnings. */ #define FTD_MSG 0x10 #define FD_BROKEN_DCL 0x20 #define FD_DEBUG 0x02 #define FD_SILENT_DCL_CLEAR 0x4 #define FD_INVERTED_DCL 0x80 /* must be 0x80, because of hardware considerations */ char read_track; /* use readtrack during probing? */ /* * Auto-detection. Each drive type has eight formats which are * used in succession to try to read the disk. If the FDC cannot lock onto * the disk, the next format is tried. This uses the variable 'probing'. */ short autodetect[8]; /* autodetected formats */ int checkfreq; /* how often should the drive be checked for disk * changes */ int native_format; /* native format of this drive */ }; enum { FD_NEED_TWADDLE_BIT, /* more magic */ FD_VERIFY_BIT, /* inquire for write protection */ FD_DISK_NEWCHANGE_BIT, /* change detected, and no action undertaken yet * to clear media change status */ FD_UNUSED_BIT, FD_DISK_CHANGED_BIT, /* disk has been changed since last i/o */ FD_DISK_WRITABLE_BIT, /* disk is writable */ FD_OPEN_SHOULD_FAIL_BIT }; #define FDSETDRVPRM _IOW(2, 0x90, struct floppy_drive_params) #define FDGETDRVPRM _IOR(2, 0x11, struct floppy_drive_params) /* set/get drive parameters */ /* * Current drive state (not directly modifiable by user, readonly) */ struct floppy_drive_struct { unsigned long flags; /* values for these flags */ #define FD_NEED_TWADDLE (1 << FD_NEED_TWADDLE_BIT) #define FD_VERIFY (1 << FD_VERIFY_BIT) #define FD_DISK_NEWCHANGE (1 << FD_DISK_NEWCHANGE_BIT) #define FD_DISK_CHANGED (1 << FD_DISK_CHANGED_BIT) #define FD_DISK_WRITABLE (1 << FD_DISK_WRITABLE_BIT) unsigned long spinup_date; unsigned long select_date; unsigned long first_read_date; short probed_format; short track; /* current track */ short maxblock; /* id of highest block read */ short maxtrack; /* id of highest half track read */ int generation; /* how many diskchanges? */ /* * (User-provided) media information is _not_ discarded after a media change * if the corresponding keep_data flag is non-zero. Positive values are * decremented after each probe. */ int keep_data; /* Prevent "aliased" accesses. */ int fd_ref; int fd_device; unsigned long last_checked; /* when was the drive last checked for a disk * change? */ char *dmabuf; int bufblocks; }; #define FDGETDRVSTAT _IOR(2, 0x12, struct floppy_drive_struct) #define FDPOLLDRVSTAT _IOR(2, 0x13, struct floppy_drive_struct) /* get drive state: GET returns the cached state, POLL polls for new state */ /* * reset FDC */ enum reset_mode { FD_RESET_IF_NEEDED, /* reset only if the reset flags is set */ FD_RESET_IF_RAWCMD, /* obsolete */ FD_RESET_ALWAYS /* reset always */ }; #define FDRESET _IO(2, 0x54) /* * FDC state */ struct floppy_fdc_state { int spec1; /* spec1 value last used */ int spec2; /* spec2 value last used */ int dtr; unsigned char version; /* FDC version code */ unsigned char dor; unsigned long address; /* io address */ unsigned int rawcmd:2; unsigned int reset:1; unsigned int need_configure:1; unsigned int perp_mode:2; unsigned int has_fifo:1; unsigned int driver_version; /* version code for floppy driver */ #define FD_DRIVER_VERSION 0x100 /* user programs using the floppy API should use floppy_fdc_state to * get the version number of the floppy driver that they are running * on. If this version number is bigger than the one compiled into the * user program (the FD_DRIVER_VERSION define), it should be prepared * to bigger structures */ unsigned char track[4]; /* Position of the heads of the 4 units attached to this FDC, * as stored on the FDC. In the future, the position as stored * on the FDC might not agree with the actual physical * position of these drive heads. By allowing such * disagreement, it will be possible to reset the FDC without * incurring the expensive cost of repositioning all heads. * Right now, these positions are hard wired to 0. */ }; #define FDGETFDCSTAT _IOR(2, 0x15, struct floppy_fdc_state) /* * Asynchronous Write error tracking */ struct floppy_write_errors { /* Write error logging. * * These fields can be cleared with the FDWERRORCLR ioctl. * Only writes that were attempted but failed due to a physical media * error are logged. write(2) calls that fail and return an error code * to the user process are not counted. */ unsigned int write_errors; /* number of physical write errors * encountered */ /* position of first and last write errors */ unsigned long first_error_sector; int first_error_generation; unsigned long last_error_sector; int last_error_generation; unsigned int badness; /* highest retry count for a read or write * operation */ }; #define FDWERRORCLR _IO(2, 0x56) /* clear write error and badness information */ #define FDWERRORGET _IOR(2, 0x17, struct floppy_write_errors) /* get write error and badness information */ /* * Raw commands */ /* new interface flag: now we can do them in batches */ #define FDHAVEBATCHEDRAWCMD struct floppy_raw_cmd { unsigned int flags; #define FD_RAW_READ 1 #define FD_RAW_WRITE 2 #define FD_RAW_NO_MOTOR 4 #define FD_RAW_DISK_CHANGE 4 /* out: disk change flag was set */ #define FD_RAW_INTR 8 /* wait for an interrupt */ #define FD_RAW_SPIN 0x10 /* spin up the disk for this command */ #define FD_RAW_NO_MOTOR_AFTER 0x20 /* switch the motor off after command * completion */ #define FD_RAW_NEED_DISK 0x40 /* this command needs a disk to be present */ #define FD_RAW_NEED_SEEK 0x80 /* this command uses an implied seek (soft) */ /* more "in" flags */ #define FD_RAW_MORE 0x100 /* more records follow */ #define FD_RAW_STOP_IF_FAILURE 0x200 /* stop if we encounter a failure */ #define FD_RAW_STOP_IF_SUCCESS 0x400 /* stop if command successful */ #define FD_RAW_SOFTFAILURE 0x800 /* consider the return value for failure * detection too */ /* more "out" flags */ #define FD_RAW_FAILURE 0x10000 /* command sent to fdc, fdc returned error */ #define FD_RAW_HARDFAILURE 0x20000 /* fdc had to be reset, or timed out */ void *data; char *kernel_data; /* location of data buffer in the kernel */ struct floppy_raw_cmd *next; /* used for chaining of raw cmd's * within the kernel */ long length; /* in: length of dma transfer. out: remaining bytes */ long phys_length; /* physical length, if different from dma length */ int buffer_length; /* length of allocated buffer */ unsigned char rate; unsigned char cmd_count; unsigned char cmd[16]; unsigned char reply_count; unsigned char reply[16]; int track; int resultcode; int reserved1; int reserved2; }; #define FDRAWCMD _IO(2, 0x58) /* send a raw command to the fdc. Structure size not included, because of * batches */ #define FDTWADDLE _IO(2, 0x59) /* flicker motor-on bit before reading a sector. Experimental */ #define FDEJECT _IO(2, 0x5a) /* eject the disk */ #endif /* _LINUX_FD_H */ linux/isdnif.h000064400000004502151027430560007334 0ustar00/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* $Id: isdnif.h,v 1.43.2.2 2004/01/12 23:08:35 keil Exp $ * * Linux ISDN subsystem * Definition of the interface between the subsystem and its low-level drivers. * * Copyright 1994,95,96 by Fritz Elfert (fritz@isdn4linux.de) * Copyright 1995,96 Thinking Objects Software GmbH Wuerzburg * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #ifndef __ISDNIF_H__ #define __ISDNIF_H__ /* * Values for general protocol-selection */ #define ISDN_PTYPE_UNKNOWN 0 /* Protocol undefined */ #define ISDN_PTYPE_1TR6 1 /* german 1TR6-protocol */ #define ISDN_PTYPE_EURO 2 /* EDSS1-protocol */ #define ISDN_PTYPE_LEASED 3 /* for leased lines */ #define ISDN_PTYPE_NI1 4 /* US NI-1 protocol */ #define ISDN_PTYPE_MAX 7 /* Max. 8 Protocols */ /* * Values for Layer-2-protocol-selection */ #define ISDN_PROTO_L2_X75I 0 /* X75/LAPB with I-Frames */ #define ISDN_PROTO_L2_X75UI 1 /* X75/LAPB with UI-Frames */ #define ISDN_PROTO_L2_X75BUI 2 /* X75/LAPB with UI-Frames */ #define ISDN_PROTO_L2_HDLC 3 /* HDLC */ #define ISDN_PROTO_L2_TRANS 4 /* Transparent (Voice) */ #define ISDN_PROTO_L2_X25DTE 5 /* X25/LAPB DTE mode */ #define ISDN_PROTO_L2_X25DCE 6 /* X25/LAPB DCE mode */ #define ISDN_PROTO_L2_V11096 7 /* V.110 bitrate adaption 9600 Baud */ #define ISDN_PROTO_L2_V11019 8 /* V.110 bitrate adaption 19200 Baud */ #define ISDN_PROTO_L2_V11038 9 /* V.110 bitrate adaption 38400 Baud */ #define ISDN_PROTO_L2_MODEM 10 /* Analog Modem on Board */ #define ISDN_PROTO_L2_FAX 11 /* Fax Group 2/3 */ #define ISDN_PROTO_L2_HDLC_56K 12 /* HDLC 56k */ #define ISDN_PROTO_L2_MAX 15 /* Max. 16 Protocols */ /* * Values for Layer-3-protocol-selection */ #define ISDN_PROTO_L3_TRANS 0 /* Transparent */ #define ISDN_PROTO_L3_TRANSDSP 1 /* Transparent with DSP */ #define ISDN_PROTO_L3_FCLASS2 2 /* Fax Group 2/3 CLASS 2 */ #define ISDN_PROTO_L3_FCLASS1 3 /* Fax Group 2/3 CLASS 1 */ #define ISDN_PROTO_L3_MAX 7 /* Max. 8 Protocols */ #endif /* __ISDNIF_H__ */ linux/minix_fs.h000064400000004112151027430560007671 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_MINIX_FS_H #define _LINUX_MINIX_FS_H #include #include /* * The minix filesystem constants/structures */ /* * Thanks to Kees J Bot for sending me the definitions of the new * minix filesystem (aka V2) with bigger inodes and 32-bit block * pointers. */ #define MINIX_ROOT_INO 1 /* Not the same as the bogus LINK_MAX in . Oh well. */ #define MINIX_LINK_MAX 250 #define MINIX2_LINK_MAX 65530 #define MINIX_I_MAP_SLOTS 8 #define MINIX_Z_MAP_SLOTS 64 #define MINIX_VALID_FS 0x0001 /* Clean fs. */ #define MINIX_ERROR_FS 0x0002 /* fs has errors. */ #define MINIX_INODES_PER_BLOCK ((BLOCK_SIZE)/(sizeof (struct minix_inode))) /* * This is the original minix inode layout on disk. * Note the 8-bit gid and atime and ctime. */ struct minix_inode { __u16 i_mode; __u16 i_uid; __u32 i_size; __u32 i_time; __u8 i_gid; __u8 i_nlinks; __u16 i_zone[9]; }; /* * The new minix inode has all the time entries, as well as * long block numbers and a third indirect block (7+1+1+1 * instead of 7+1+1). Also, some previously 8-bit values are * now 16-bit. The inode is now 64 bytes instead of 32. */ struct minix2_inode { __u16 i_mode; __u16 i_nlinks; __u16 i_uid; __u16 i_gid; __u32 i_size; __u32 i_atime; __u32 i_mtime; __u32 i_ctime; __u32 i_zone[10]; }; /* * minix super-block data on disk */ struct minix_super_block { __u16 s_ninodes; __u16 s_nzones; __u16 s_imap_blocks; __u16 s_zmap_blocks; __u16 s_firstdatazone; __u16 s_log_zone_size; __u32 s_max_size; __u16 s_magic; __u16 s_state; __u32 s_zones; }; /* * V3 minix super-block data on disk */ struct minix3_super_block { __u32 s_ninodes; __u16 s_pad0; __u16 s_imap_blocks; __u16 s_zmap_blocks; __u16 s_firstdatazone; __u16 s_log_zone_size; __u16 s_pad1; __u32 s_max_size; __u32 s_zones; __u16 s_magic; __u16 s_pad2; __u16 s_blocksize; __u8 s_disk_version; }; struct minix_dir_entry { __u16 inode; char name[0]; }; struct minix3_dir_entry { __u32 inode; char name[0]; }; #endif linux/resource.h000064400000004453151027430560007714 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _LINUX_RESOURCE_H #define _LINUX_RESOURCE_H #include #include /* * Resource control/accounting header file for linux */ /* * Definition of struct rusage taken from BSD 4.3 Reno * * We don't support all of these yet, but we might as well have them.... * Otherwise, each time we add new items, programs which depend on this * structure will lose. This reduces the chances of that happening. */ #define RUSAGE_SELF 0 #define RUSAGE_CHILDREN (-1) #define RUSAGE_BOTH (-2) /* sys_wait4() uses this */ #define RUSAGE_THREAD 1 /* only the calling thread */ struct rusage { struct timeval ru_utime; /* user time used */ struct timeval ru_stime; /* system time used */ __kernel_long_t ru_maxrss; /* maximum resident set size */ __kernel_long_t ru_ixrss; /* integral shared memory size */ __kernel_long_t ru_idrss; /* integral unshared data size */ __kernel_long_t ru_isrss; /* integral unshared stack size */ __kernel_long_t ru_minflt; /* page reclaims */ __kernel_long_t ru_majflt; /* page faults */ __kernel_long_t ru_nswap; /* swaps */ __kernel_long_t ru_inblock; /* block input operations */ __kernel_long_t ru_oublock; /* block output operations */ __kernel_long_t ru_msgsnd; /* messages sent */ __kernel_long_t ru_msgrcv; /* messages received */ __kernel_long_t ru_nsignals; /* signals received */ __kernel_long_t ru_nvcsw; /* voluntary context switches */ __kernel_long_t ru_nivcsw; /* involuntary " */ }; struct rlimit { __kernel_ulong_t rlim_cur; __kernel_ulong_t rlim_max; }; #define RLIM64_INFINITY (~0ULL) struct rlimit64 { __u64 rlim_cur; __u64 rlim_max; }; #define PRIO_MIN (-20) #define PRIO_MAX 20 #define PRIO_PROCESS 0 #define PRIO_PGRP 1 #define PRIO_USER 2 /* * Limit the stack by to some sane default: root can always * increase this limit if needed.. 8MB seems reasonable. */ #define _STK_LIM (8*1024*1024) /* * GPG2 wants 64kB of mlocked memory, to make sure pass phrases * and other sensitive information are never written to disk. */ #define MLOCK_LIMIT ((PAGE_SIZE > 64*1024) ? PAGE_SIZE : 64*1024) /* * Due to binary compatibility, the actual resource numbers * may be different for different linux versions.. */ #include #endif /* _LINUX_RESOURCE_H */ linux/kernel-page-flags.h000064400000001604151027430560011344 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef LINUX_KERNEL_PAGE_FLAGS_H #define LINUX_KERNEL_PAGE_FLAGS_H /* * Stable page flag bits exported to user space */ #define KPF_LOCKED 0 #define KPF_ERROR 1 #define KPF_REFERENCED 2 #define KPF_UPTODATE 3 #define KPF_DIRTY 4 #define KPF_LRU 5 #define KPF_ACTIVE 6 #define KPF_SLAB 7 #define KPF_WRITEBACK 8 #define KPF_RECLAIM 9 #define KPF_BUDDY 10 /* 11-20: new additions in 2.6.31 */ #define KPF_MMAP 11 #define KPF_ANON 12 #define KPF_SWAPCACHE 13 #define KPF_SWAPBACKED 14 #define KPF_COMPOUND_HEAD 15 #define KPF_COMPOUND_TAIL 16 #define KPF_HUGE 17 #define KPF_UNEVICTABLE 18 #define KPF_HWPOISON 19 #define KPF_NOPAGE 20 #define KPF_KSM 21 #define KPF_THP 22 #define KPF_OFFLINE 23 #define KPF_ZERO_PAGE 24 #define KPF_IDLE 25 #define KPF_PGTABLE 26 #endif /* LINUX_KERNEL_PAGE_FLAGS_H */ linux/posix_acl_xattr.h000064400000002133151027430560011261 0ustar00/* SPDX-License-Identifier: LGPL-2.1+ WITH Linux-syscall-note */ /* * Copyright (C) 2002 Andreas Gruenbacher * Copyright (C) 2016 Red Hat, Inc. * * This file is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #ifndef __UAPI_POSIX_ACL_XATTR_H #define __UAPI_POSIX_ACL_XATTR_H #include /* Supported ACL a_version fields */ #define POSIX_ACL_XATTR_VERSION 0x0002 /* An undefined entry e_id value */ #define ACL_UNDEFINED_ID (-1) struct posix_acl_xattr_entry { __le16 e_tag; __le16 e_perm; __le32 e_id; }; struct posix_acl_xattr_header { __le32 a_version; }; #endif /* __UAPI_POSIX_ACL_XATTR_H */ curses.h000064400000302451151027430560006231 0ustar00/**************************************************************************** * Copyright (c) 1998-2016,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim 1992,1995 * * and: Eric S. Raymond * * and: Thomas E. Dickey 1996-on * ****************************************************************************/ /* $Id: curses.h.in,v 1.257 2017/11/21 00:11:37 tom Exp $ */ #ifndef __NCURSES_H #define __NCURSES_H #define CURSES 1 #define CURSES_H 1 /* These are defined only in curses.h, and are used for conditional compiles */ #define NCURSES_VERSION_MAJOR 6 #define NCURSES_VERSION_MINOR 1 #define NCURSES_VERSION_PATCH 20180224 /* This is defined in more than one ncurses header, for identification */ #undef NCURSES_VERSION #define NCURSES_VERSION "6.1" /* * Identify the mouse encoding version. */ #define NCURSES_MOUSE_VERSION 2 /* * Definitions to facilitate DLL's. */ #include #if 1 #include #endif /* * User-definable tweak to disable the include of . */ #ifndef NCURSES_ENABLE_STDBOOL_H #define NCURSES_ENABLE_STDBOOL_H 1 #endif /* * NCURSES_ATTR_T is used to quiet compiler warnings when building ncurses * configured using --disable-macros. */ #ifndef NCURSES_ATTR_T #define NCURSES_ATTR_T int #endif /* * Expands to 'const' if ncurses is configured using --enable-const. Note that * doing so makes it incompatible with other implementations of X/Open Curses. */ #undef NCURSES_CONST #define NCURSES_CONST const #undef NCURSES_INLINE #define NCURSES_INLINE inline /* * The standard type used for color values, and for color-pairs. The latter * allows the curses library to enumerate the combinations of foreground and * background colors used by an application, and is normally the product of the * total foreground and background colors. * * X/Open uses "short" for both of these types, ultimately because they are * numbers from the SVr4 terminal database, which uses 16-bit signed values. */ #undef NCURSES_COLOR_T #define NCURSES_COLOR_T short #undef NCURSES_PAIRS_T #define NCURSES_PAIRS_T short /* * Definitions used to make WINDOW and similar structs opaque. */ #ifndef NCURSES_INTERNALS #define NCURSES_OPAQUE 0 #define NCURSES_OPAQUE_FORM 0 #define NCURSES_OPAQUE_MENU 0 #define NCURSES_OPAQUE_PANEL 0 #endif /* * Definition used to optionally suppress wattr* macros to help with the * transition from ncurses5 to ncurses6 by allowing the header files to * be shared across development packages for ncursesw in both ABIs. */ #ifndef NCURSES_WATTR_MACROS #define NCURSES_WATTR_MACROS 0 #endif /* * The reentrant code relies on the opaque setting, but adds features. */ #ifndef NCURSES_REENTRANT #define NCURSES_REENTRANT 0 #endif /* * Control whether bindings for interop support are added. */ #undef NCURSES_INTEROP_FUNCS #define NCURSES_INTEROP_FUNCS 1 /* * The internal type used for window dimensions. */ #undef NCURSES_SIZE_T #define NCURSES_SIZE_T short /* * Control whether tparm() supports varargs or fixed-parameter list. */ #undef NCURSES_TPARM_VARARGS #define NCURSES_TPARM_VARARGS 1 /* * Control type used for tparm's arguments. While X/Open equates long and * char* values, this is not always workable for 64-bit platforms. */ #undef NCURSES_TPARM_ARG #define NCURSES_TPARM_ARG intptr_t /* * Control whether ncurses uses wcwidth() for checking width of line-drawing * characters. */ #undef NCURSES_WCWIDTH_GRAPHICS #define NCURSES_WCWIDTH_GRAPHICS 1 /* * NCURSES_CH_T is used in building the library, but not used otherwise in * this header file, since that would make the normal/wide-character versions * of the header incompatible. */ #undef NCURSES_CH_T #define NCURSES_CH_T cchar_t #if 1 && defined(_LP64) typedef unsigned chtype; typedef unsigned mmask_t; #else typedef uint32_t chtype; typedef uint32_t mmask_t; #endif /* * We need FILE, etc. Include this before checking any feature symbols. */ #include /* * With XPG4, you must define _XOPEN_SOURCE_EXTENDED, it is redundant (or * conflicting) when _XOPEN_SOURCE is 500 or greater. If NCURSES_WIDECHAR is * not already defined, e.g., if the platform relies upon nonstandard feature * test macros, define it at this point if the standard feature test macros * indicate that it should be defined. */ #ifndef NCURSES_WIDECHAR #if defined(_XOPEN_SOURCE_EXTENDED) || (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0 >= 500)) #define NCURSES_WIDECHAR 1 #else #define NCURSES_WIDECHAR 0 #endif #endif /* NCURSES_WIDECHAR */ #include /* we need va_list */ #if NCURSES_WIDECHAR #include /* we want wchar_t */ #endif /* X/Open and SVr4 specify that curses implements 'bool'. However, C++ may also * implement it. If so, we must use the C++ compiler's type to avoid conflict * with other interfaces. * * A further complication is that may declare 'bool' to be a * different type, such as an enum which is not necessarily compatible with * C++. If we have , make 'bool' a macro, so users may #undef it. * Otherwise, let it remain a typedef to avoid conflicts with other #define's. * In either case, make a typedef for NCURSES_BOOL which can be used if needed * from either C or C++. */ #undef TRUE #define TRUE 1 #undef FALSE #define FALSE 0 typedef unsigned char NCURSES_BOOL; #if defined(__cplusplus) /* __cplusplus, etc. */ /* use the C++ compiler's bool type */ #define NCURSES_BOOL bool #else /* c89, c99, etc. */ #if NCURSES_ENABLE_STDBOOL_H #include /* use whatever the C compiler decides bool really is */ #define NCURSES_BOOL bool #else /* there is no predefined bool - use our own */ #undef bool #define bool NCURSES_BOOL #endif #endif /* !__cplusplus, etc. */ #ifdef __cplusplus extern "C" { #define NCURSES_CAST(type,value) static_cast(value) #else #define NCURSES_CAST(type,value) (type)(value) #endif #define NCURSES_OK_ADDR(p) (0 != NCURSES_CAST(const void *, (p))) /* * X/Open attributes. In the ncurses implementation, they are identical to the * A_ attributes. */ #define WA_ATTRIBUTES A_ATTRIBUTES #define WA_NORMAL A_NORMAL #define WA_STANDOUT A_STANDOUT #define WA_UNDERLINE A_UNDERLINE #define WA_REVERSE A_REVERSE #define WA_BLINK A_BLINK #define WA_DIM A_DIM #define WA_BOLD A_BOLD #define WA_ALTCHARSET A_ALTCHARSET #define WA_INVIS A_INVIS #define WA_PROTECT A_PROTECT #define WA_HORIZONTAL A_HORIZONTAL #define WA_LEFT A_LEFT #define WA_LOW A_LOW #define WA_RIGHT A_RIGHT #define WA_TOP A_TOP #define WA_VERTICAL A_VERTICAL #if 1 #define WA_ITALIC A_ITALIC /* ncurses extension */ #endif /* colors */ #define COLOR_BLACK 0 #define COLOR_RED 1 #define COLOR_GREEN 2 #define COLOR_YELLOW 3 #define COLOR_BLUE 4 #define COLOR_MAGENTA 5 #define COLOR_CYAN 6 #define COLOR_WHITE 7 /* line graphics */ #if 0 || NCURSES_REENTRANT NCURSES_WRAPPED_VAR(chtype*, acs_map); #define acs_map NCURSES_PUBLIC_VAR(acs_map()) #else extern NCURSES_EXPORT_VAR(chtype) acs_map[]; #endif #define NCURSES_ACS(c) (acs_map[NCURSES_CAST(unsigned char,(c))]) /* VT100 symbols begin here */ #define ACS_ULCORNER NCURSES_ACS('l') /* upper left corner */ #define ACS_LLCORNER NCURSES_ACS('m') /* lower left corner */ #define ACS_URCORNER NCURSES_ACS('k') /* upper right corner */ #define ACS_LRCORNER NCURSES_ACS('j') /* lower right corner */ #define ACS_LTEE NCURSES_ACS('t') /* tee pointing right */ #define ACS_RTEE NCURSES_ACS('u') /* tee pointing left */ #define ACS_BTEE NCURSES_ACS('v') /* tee pointing up */ #define ACS_TTEE NCURSES_ACS('w') /* tee pointing down */ #define ACS_HLINE NCURSES_ACS('q') /* horizontal line */ #define ACS_VLINE NCURSES_ACS('x') /* vertical line */ #define ACS_PLUS NCURSES_ACS('n') /* large plus or crossover */ #define ACS_S1 NCURSES_ACS('o') /* scan line 1 */ #define ACS_S9 NCURSES_ACS('s') /* scan line 9 */ #define ACS_DIAMOND NCURSES_ACS('`') /* diamond */ #define ACS_CKBOARD NCURSES_ACS('a') /* checker board (stipple) */ #define ACS_DEGREE NCURSES_ACS('f') /* degree symbol */ #define ACS_PLMINUS NCURSES_ACS('g') /* plus/minus */ #define ACS_BULLET NCURSES_ACS('~') /* bullet */ /* Teletype 5410v1 symbols begin here */ #define ACS_LARROW NCURSES_ACS(',') /* arrow pointing left */ #define ACS_RARROW NCURSES_ACS('+') /* arrow pointing right */ #define ACS_DARROW NCURSES_ACS('.') /* arrow pointing down */ #define ACS_UARROW NCURSES_ACS('-') /* arrow pointing up */ #define ACS_BOARD NCURSES_ACS('h') /* board of squares */ #define ACS_LANTERN NCURSES_ACS('i') /* lantern symbol */ #define ACS_BLOCK NCURSES_ACS('0') /* solid square block */ /* * These aren't documented, but a lot of System Vs have them anyway * (you can spot pprryyzz{{||}} in a lot of AT&T terminfo strings). * The ACS_names may not match AT&T's, our source didn't know them. */ #define ACS_S3 NCURSES_ACS('p') /* scan line 3 */ #define ACS_S7 NCURSES_ACS('r') /* scan line 7 */ #define ACS_LEQUAL NCURSES_ACS('y') /* less/equal */ #define ACS_GEQUAL NCURSES_ACS('z') /* greater/equal */ #define ACS_PI NCURSES_ACS('{') /* Pi */ #define ACS_NEQUAL NCURSES_ACS('|') /* not equal */ #define ACS_STERLING NCURSES_ACS('}') /* UK pound sign */ /* * Line drawing ACS names are of the form ACS_trbl, where t is the top, r * is the right, b is the bottom, and l is the left. t, r, b, and l might * be B (blank), S (single), D (double), or T (thick). The subset defined * here only uses B and S. */ #define ACS_BSSB ACS_ULCORNER #define ACS_SSBB ACS_LLCORNER #define ACS_BBSS ACS_URCORNER #define ACS_SBBS ACS_LRCORNER #define ACS_SBSS ACS_RTEE #define ACS_SSSB ACS_LTEE #define ACS_SSBS ACS_BTEE #define ACS_BSSS ACS_TTEE #define ACS_BSBS ACS_HLINE #define ACS_SBSB ACS_VLINE #define ACS_SSSS ACS_PLUS #undef ERR #define ERR (-1) #undef OK #define OK (0) /* values for the _flags member */ #define _SUBWIN 0x01 /* is this a sub-window? */ #define _ENDLINE 0x02 /* is the window flush right? */ #define _FULLWIN 0x04 /* is the window full-screen? */ #define _SCROLLWIN 0x08 /* bottom edge is at screen bottom? */ #define _ISPAD 0x10 /* is this window a pad? */ #define _HASMOVED 0x20 /* has cursor moved since last refresh? */ #define _WRAPPED 0x40 /* cursor was just wrappped */ /* * this value is used in the firstchar and lastchar fields to mark * unchanged lines */ #define _NOCHANGE -1 /* * this value is used in the oldindex field to mark lines created by insertions * and scrolls. */ #define _NEWINDEX -1 typedef struct screen SCREEN; typedef struct _win_st WINDOW; typedef chtype attr_t; /* ...must be at least as wide as chtype */ #if NCURSES_WIDECHAR #if 0 #ifdef mblen /* libutf8.h defines it w/o undefining first */ #undef mblen #endif #include #endif #if 1 #include /* ...to get mbstate_t, etc. */ #endif #if 0 typedef unsigned short wchar_t1; #endif #if 0 typedef unsigned int wint_t1; #endif /* * cchar_t stores an array of CCHARW_MAX wide characters. The first is * normally a spacing character. The others are non-spacing. If those * (spacing and nonspacing) do not fill the array, a null L'\0' follows. * Otherwise, a null is assumed to follow when extracting via getcchar(). */ #define CCHARW_MAX 5 typedef struct { attr_t attr; wchar_t chars[CCHARW_MAX]; #if 1 #undef NCURSES_EXT_COLORS #define NCURSES_EXT_COLORS 20180224 int ext_color; /* color pair, must be more than 16-bits */ #endif } cchar_t; #endif /* NCURSES_WIDECHAR */ #if !NCURSES_OPAQUE struct ldat; struct _win_st { NCURSES_SIZE_T _cury, _curx; /* current cursor position */ /* window location and size */ NCURSES_SIZE_T _maxy, _maxx; /* maximums of x and y, NOT window size */ NCURSES_SIZE_T _begy, _begx; /* screen coords of upper-left-hand corner */ short _flags; /* window state flags */ /* attribute tracking */ attr_t _attrs; /* current attribute for non-space character */ chtype _bkgd; /* current background char/attribute pair */ /* option values set by user */ bool _notimeout; /* no time out on function-key entry? */ bool _clear; /* consider all data in the window invalid? */ bool _leaveok; /* OK to not reset cursor on exit? */ bool _scroll; /* OK to scroll this window? */ bool _idlok; /* OK to use insert/delete line? */ bool _idcok; /* OK to use insert/delete char? */ bool _immed; /* window in immed mode? (not yet used) */ bool _sync; /* window in sync mode? */ bool _use_keypad; /* process function keys into KEY_ symbols? */ int _delay; /* 0 = nodelay, <0 = blocking, >0 = delay */ struct ldat *_line; /* the actual line data */ /* global screen state */ NCURSES_SIZE_T _regtop; /* top line of scrolling region */ NCURSES_SIZE_T _regbottom; /* bottom line of scrolling region */ /* these are used only if this is a sub-window */ int _parx; /* x coordinate of this window in parent */ int _pary; /* y coordinate of this window in parent */ WINDOW *_parent; /* pointer to parent if a sub-window */ /* these are used only if this is a pad */ struct pdat { NCURSES_SIZE_T _pad_y, _pad_x; NCURSES_SIZE_T _pad_top, _pad_left; NCURSES_SIZE_T _pad_bottom, _pad_right; } _pad; NCURSES_SIZE_T _yoffset; /* real begy is _begy + _yoffset */ #if NCURSES_WIDECHAR cchar_t _bkgrnd; /* current background char/attribute pair */ #if 1 int _color; /* current color-pair for non-space character */ #endif #endif }; #endif /* NCURSES_OPAQUE */ /* * This is an extension to support events... */ #if 1 #ifdef NCURSES_WGETCH_EVENTS #if !defined(__BEOS__) || defined(__HAIKU__) /* Fix _nc_timed_wait() on BEOS... */ # define NCURSES_EVENT_VERSION 1 #endif /* !defined(__BEOS__) */ /* * Bits to set in _nc_event.data.flags */ # define _NC_EVENT_TIMEOUT_MSEC 1 # define _NC_EVENT_FILE 2 # define _NC_EVENT_FILE_READABLE 2 # if 0 /* Not supported yet... */ # define _NC_EVENT_FILE_WRITABLE 4 # define _NC_EVENT_FILE_EXCEPTION 8 # endif typedef struct { int type; union { long timeout_msec; /* _NC_EVENT_TIMEOUT_MSEC */ struct { unsigned int flags; int fd; unsigned int result; } fev; /* _NC_EVENT_FILE */ } data; } _nc_event; typedef struct { int count; int result_flags; /* _NC_EVENT_TIMEOUT_MSEC or _NC_EVENT_FILE_READABLE */ _nc_event *events[1]; } _nc_eventlist; extern NCURSES_EXPORT(int) wgetch_events (WINDOW *, _nc_eventlist *); /* experimental */ extern NCURSES_EXPORT(int) wgetnstr_events (WINDOW *,char *,int,_nc_eventlist *);/* experimental */ #endif /* NCURSES_WGETCH_EVENTS */ #endif /* NCURSES_EXT_FUNCS */ /* * GCC (and some other compilers) define '__attribute__'; we're using this * macro to alert the compiler to flag inconsistencies in printf/scanf-like * function calls. Just in case '__attribute__' isn't defined, make a dummy. * Old versions of G++ do not accept it anyway, at least not consistently with * GCC. */ #if !(defined(__GNUC__) || defined(__GNUG__) || defined(__attribute__)) #define __attribute__(p) /* nothing */ #endif /* * We cannot define these in ncurses_cfg.h, since they require parameters to be * passed (that is non-portable). If you happen to be using gcc with warnings * enabled, define * GCC_PRINTF * GCC_SCANF * to improve checking of calls to printw(), etc. */ #ifndef GCC_PRINTFLIKE #if defined(GCC_PRINTF) && !defined(printf) #define GCC_PRINTFLIKE(fmt,var) __attribute__((format(printf,fmt,var))) #else #define GCC_PRINTFLIKE(fmt,var) /*nothing*/ #endif #endif #ifndef GCC_SCANFLIKE #if defined(GCC_SCANF) && !defined(scanf) #define GCC_SCANFLIKE(fmt,var) __attribute__((format(scanf,fmt,var))) #else #define GCC_SCANFLIKE(fmt,var) /*nothing*/ #endif #endif #ifndef GCC_NORETURN #define GCC_NORETURN /* nothing */ #endif #ifndef GCC_UNUSED #define GCC_UNUSED /* nothing */ #endif /* * Curses uses a helper function. Define our type for this to simplify * extending it for the sp-funcs feature. */ typedef int (*NCURSES_OUTC)(int); /* * Function prototypes. This is the complete X/Open Curses list of required * functions. Those marked `generated' will have sources generated from the * macro definitions later in this file, in order to satisfy XPG4.2 * requirements. */ extern NCURSES_EXPORT(int) addch (const chtype); /* generated */ extern NCURSES_EXPORT(int) addchnstr (const chtype *, int); /* generated */ extern NCURSES_EXPORT(int) addchstr (const chtype *); /* generated */ extern NCURSES_EXPORT(int) addnstr (const char *, int); /* generated */ extern NCURSES_EXPORT(int) addstr (const char *); /* generated */ extern NCURSES_EXPORT(int) attroff (NCURSES_ATTR_T); /* generated */ extern NCURSES_EXPORT(int) attron (NCURSES_ATTR_T); /* generated */ extern NCURSES_EXPORT(int) attrset (NCURSES_ATTR_T); /* generated */ extern NCURSES_EXPORT(int) attr_get (attr_t *, NCURSES_PAIRS_T *, void *); /* generated */ extern NCURSES_EXPORT(int) attr_off (attr_t, void *); /* generated */ extern NCURSES_EXPORT(int) attr_on (attr_t, void *); /* generated */ extern NCURSES_EXPORT(int) attr_set (attr_t, NCURSES_PAIRS_T, void *); /* generated */ extern NCURSES_EXPORT(int) baudrate (void); /* implemented */ extern NCURSES_EXPORT(int) beep (void); /* implemented */ extern NCURSES_EXPORT(int) bkgd (chtype); /* generated */ extern NCURSES_EXPORT(void) bkgdset (chtype); /* generated */ extern NCURSES_EXPORT(int) border (chtype,chtype,chtype,chtype,chtype,chtype,chtype,chtype); /* generated */ extern NCURSES_EXPORT(int) box (WINDOW *, chtype, chtype); /* generated */ extern NCURSES_EXPORT(bool) can_change_color (void); /* implemented */ extern NCURSES_EXPORT(int) cbreak (void); /* implemented */ extern NCURSES_EXPORT(int) chgat (int, attr_t, NCURSES_PAIRS_T, const void *); /* generated */ extern NCURSES_EXPORT(int) clear (void); /* generated */ extern NCURSES_EXPORT(int) clearok (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(int) clrtobot (void); /* generated */ extern NCURSES_EXPORT(int) clrtoeol (void); /* generated */ extern NCURSES_EXPORT(int) color_content (NCURSES_COLOR_T,NCURSES_COLOR_T*,NCURSES_COLOR_T*,NCURSES_COLOR_T*); /* implemented */ extern NCURSES_EXPORT(int) color_set (NCURSES_PAIRS_T,void*); /* generated */ extern NCURSES_EXPORT(int) COLOR_PAIR (int); /* generated */ extern NCURSES_EXPORT(int) copywin (const WINDOW*,WINDOW*,int,int,int,int,int,int,int); /* implemented */ extern NCURSES_EXPORT(int) curs_set (int); /* implemented */ extern NCURSES_EXPORT(int) def_prog_mode (void); /* implemented */ extern NCURSES_EXPORT(int) def_shell_mode (void); /* implemented */ extern NCURSES_EXPORT(int) delay_output (int); /* implemented */ extern NCURSES_EXPORT(int) delch (void); /* generated */ extern NCURSES_EXPORT(void) delscreen (SCREEN *); /* implemented */ extern NCURSES_EXPORT(int) delwin (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) deleteln (void); /* generated */ extern NCURSES_EXPORT(WINDOW *) derwin (WINDOW *,int,int,int,int); /* implemented */ extern NCURSES_EXPORT(int) doupdate (void); /* implemented */ extern NCURSES_EXPORT(WINDOW *) dupwin (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) echo (void); /* implemented */ extern NCURSES_EXPORT(int) echochar (const chtype); /* generated */ extern NCURSES_EXPORT(int) erase (void); /* generated */ extern NCURSES_EXPORT(int) endwin (void); /* implemented */ extern NCURSES_EXPORT(char) erasechar (void); /* implemented */ extern NCURSES_EXPORT(void) filter (void); /* implemented */ extern NCURSES_EXPORT(int) flash (void); /* implemented */ extern NCURSES_EXPORT(int) flushinp (void); /* implemented */ extern NCURSES_EXPORT(chtype) getbkgd (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getch (void); /* generated */ extern NCURSES_EXPORT(int) getnstr (char *, int); /* generated */ extern NCURSES_EXPORT(int) getstr (char *); /* generated */ extern NCURSES_EXPORT(WINDOW *) getwin (FILE *); /* implemented */ extern NCURSES_EXPORT(int) halfdelay (int); /* implemented */ extern NCURSES_EXPORT(bool) has_colors (void); /* implemented */ extern NCURSES_EXPORT(bool) has_ic (void); /* implemented */ extern NCURSES_EXPORT(bool) has_il (void); /* implemented */ extern NCURSES_EXPORT(int) hline (chtype, int); /* generated */ extern NCURSES_EXPORT(void) idcok (WINDOW *, bool); /* implemented */ extern NCURSES_EXPORT(int) idlok (WINDOW *, bool); /* implemented */ extern NCURSES_EXPORT(void) immedok (WINDOW *, bool); /* implemented */ extern NCURSES_EXPORT(chtype) inch (void); /* generated */ extern NCURSES_EXPORT(int) inchnstr (chtype *, int); /* generated */ extern NCURSES_EXPORT(int) inchstr (chtype *); /* generated */ extern NCURSES_EXPORT(WINDOW *) initscr (void); /* implemented */ extern NCURSES_EXPORT(int) init_color (NCURSES_COLOR_T,NCURSES_COLOR_T,NCURSES_COLOR_T,NCURSES_COLOR_T); /* implemented */ extern NCURSES_EXPORT(int) init_pair (NCURSES_PAIRS_T,NCURSES_COLOR_T,NCURSES_COLOR_T); /* implemented */ extern NCURSES_EXPORT(int) innstr (char *, int); /* generated */ extern NCURSES_EXPORT(int) insch (chtype); /* generated */ extern NCURSES_EXPORT(int) insdelln (int); /* generated */ extern NCURSES_EXPORT(int) insertln (void); /* generated */ extern NCURSES_EXPORT(int) insnstr (const char *, int); /* generated */ extern NCURSES_EXPORT(int) insstr (const char *); /* generated */ extern NCURSES_EXPORT(int) instr (char *); /* generated */ extern NCURSES_EXPORT(int) intrflush (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(bool) isendwin (void); /* implemented */ extern NCURSES_EXPORT(bool) is_linetouched (WINDOW *,int); /* implemented */ extern NCURSES_EXPORT(bool) is_wintouched (WINDOW *); /* implemented */ extern NCURSES_EXPORT(NCURSES_CONST char *) keyname (int); /* implemented */ extern NCURSES_EXPORT(int) keypad (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(char) killchar (void); /* implemented */ extern NCURSES_EXPORT(int) leaveok (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(char *) longname (void); /* implemented */ extern NCURSES_EXPORT(int) meta (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(int) move (int, int); /* generated */ extern NCURSES_EXPORT(int) mvaddch (int, int, const chtype); /* generated */ extern NCURSES_EXPORT(int) mvaddchnstr (int, int, const chtype *, int); /* generated */ extern NCURSES_EXPORT(int) mvaddchstr (int, int, const chtype *); /* generated */ extern NCURSES_EXPORT(int) mvaddnstr (int, int, const char *, int); /* generated */ extern NCURSES_EXPORT(int) mvaddstr (int, int, const char *); /* generated */ extern NCURSES_EXPORT(int) mvchgat (int, int, int, attr_t, NCURSES_PAIRS_T, const void *); /* generated */ extern NCURSES_EXPORT(int) mvcur (int,int,int,int); /* implemented */ extern NCURSES_EXPORT(int) mvdelch (int, int); /* generated */ extern NCURSES_EXPORT(int) mvderwin (WINDOW *, int, int); /* implemented */ extern NCURSES_EXPORT(int) mvgetch (int, int); /* generated */ extern NCURSES_EXPORT(int) mvgetnstr (int, int, char *, int); /* generated */ extern NCURSES_EXPORT(int) mvgetstr (int, int, char *); /* generated */ extern NCURSES_EXPORT(int) mvhline (int, int, chtype, int); /* generated */ extern NCURSES_EXPORT(chtype) mvinch (int, int); /* generated */ extern NCURSES_EXPORT(int) mvinchnstr (int, int, chtype *, int); /* generated */ extern NCURSES_EXPORT(int) mvinchstr (int, int, chtype *); /* generated */ extern NCURSES_EXPORT(int) mvinnstr (int, int, char *, int); /* generated */ extern NCURSES_EXPORT(int) mvinsch (int, int, chtype); /* generated */ extern NCURSES_EXPORT(int) mvinsnstr (int, int, const char *, int); /* generated */ extern NCURSES_EXPORT(int) mvinsstr (int, int, const char *); /* generated */ extern NCURSES_EXPORT(int) mvinstr (int, int, char *); /* generated */ extern NCURSES_EXPORT(int) mvprintw (int,int, const char *,...) /* implemented */ GCC_PRINTFLIKE(3,4); extern NCURSES_EXPORT(int) mvscanw (int,int, NCURSES_CONST char *,...) /* implemented */ GCC_SCANFLIKE(3,4); extern NCURSES_EXPORT(int) mvvline (int, int, chtype, int); /* generated */ extern NCURSES_EXPORT(int) mvwaddch (WINDOW *, int, int, const chtype); /* generated */ extern NCURSES_EXPORT(int) mvwaddchnstr (WINDOW *, int, int, const chtype *, int);/* generated */ extern NCURSES_EXPORT(int) mvwaddchstr (WINDOW *, int, int, const chtype *); /* generated */ extern NCURSES_EXPORT(int) mvwaddnstr (WINDOW *, int, int, const char *, int); /* generated */ extern NCURSES_EXPORT(int) mvwaddstr (WINDOW *, int, int, const char *); /* generated */ extern NCURSES_EXPORT(int) mvwchgat (WINDOW *, int, int, int, attr_t, NCURSES_PAIRS_T, const void *);/* generated */ extern NCURSES_EXPORT(int) mvwdelch (WINDOW *, int, int); /* generated */ extern NCURSES_EXPORT(int) mvwgetch (WINDOW *, int, int); /* generated */ extern NCURSES_EXPORT(int) mvwgetnstr (WINDOW *, int, int, char *, int); /* generated */ extern NCURSES_EXPORT(int) mvwgetstr (WINDOW *, int, int, char *); /* generated */ extern NCURSES_EXPORT(int) mvwhline (WINDOW *, int, int, chtype, int); /* generated */ extern NCURSES_EXPORT(int) mvwin (WINDOW *,int,int); /* implemented */ extern NCURSES_EXPORT(chtype) mvwinch (WINDOW *, int, int); /* generated */ extern NCURSES_EXPORT(int) mvwinchnstr (WINDOW *, int, int, chtype *, int); /* generated */ extern NCURSES_EXPORT(int) mvwinchstr (WINDOW *, int, int, chtype *); /* generated */ extern NCURSES_EXPORT(int) mvwinnstr (WINDOW *, int, int, char *, int); /* generated */ extern NCURSES_EXPORT(int) mvwinsch (WINDOW *, int, int, chtype); /* generated */ extern NCURSES_EXPORT(int) mvwinsnstr (WINDOW *, int, int, const char *, int); /* generated */ extern NCURSES_EXPORT(int) mvwinsstr (WINDOW *, int, int, const char *); /* generated */ extern NCURSES_EXPORT(int) mvwinstr (WINDOW *, int, int, char *); /* generated */ extern NCURSES_EXPORT(int) mvwprintw (WINDOW*,int,int, const char *,...) /* implemented */ GCC_PRINTFLIKE(4,5); extern NCURSES_EXPORT(int) mvwscanw (WINDOW *,int,int, NCURSES_CONST char *,...) /* implemented */ GCC_SCANFLIKE(4,5); extern NCURSES_EXPORT(int) mvwvline (WINDOW *,int, int, chtype, int); /* generated */ extern NCURSES_EXPORT(int) napms (int); /* implemented */ extern NCURSES_EXPORT(WINDOW *) newpad (int,int); /* implemented */ extern NCURSES_EXPORT(SCREEN *) newterm (NCURSES_CONST char *,FILE *,FILE *); /* implemented */ extern NCURSES_EXPORT(WINDOW *) newwin (int,int,int,int); /* implemented */ extern NCURSES_EXPORT(int) nl (void); /* implemented */ extern NCURSES_EXPORT(int) nocbreak (void); /* implemented */ extern NCURSES_EXPORT(int) nodelay (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(int) noecho (void); /* implemented */ extern NCURSES_EXPORT(int) nonl (void); /* implemented */ extern NCURSES_EXPORT(void) noqiflush (void); /* implemented */ extern NCURSES_EXPORT(int) noraw (void); /* implemented */ extern NCURSES_EXPORT(int) notimeout (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(int) overlay (const WINDOW*,WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) overwrite (const WINDOW*,WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) pair_content (NCURSES_PAIRS_T,NCURSES_COLOR_T*,NCURSES_COLOR_T*); /* implemented */ extern NCURSES_EXPORT(int) PAIR_NUMBER (int); /* generated */ extern NCURSES_EXPORT(int) pechochar (WINDOW *, const chtype); /* implemented */ extern NCURSES_EXPORT(int) pnoutrefresh (WINDOW*,int,int,int,int,int,int);/* implemented */ extern NCURSES_EXPORT(int) prefresh (WINDOW *,int,int,int,int,int,int); /* implemented */ extern NCURSES_EXPORT(int) printw (const char *,...) /* implemented */ GCC_PRINTFLIKE(1,2); extern NCURSES_EXPORT(int) putwin (WINDOW *, FILE *); /* implemented */ extern NCURSES_EXPORT(void) qiflush (void); /* implemented */ extern NCURSES_EXPORT(int) raw (void); /* implemented */ extern NCURSES_EXPORT(int) redrawwin (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) refresh (void); /* generated */ extern NCURSES_EXPORT(int) resetty (void); /* implemented */ extern NCURSES_EXPORT(int) reset_prog_mode (void); /* implemented */ extern NCURSES_EXPORT(int) reset_shell_mode (void); /* implemented */ extern NCURSES_EXPORT(int) ripoffline (int, int (*)(WINDOW *, int)); /* implemented */ extern NCURSES_EXPORT(int) savetty (void); /* implemented */ extern NCURSES_EXPORT(int) scanw (NCURSES_CONST char *,...) /* implemented */ GCC_SCANFLIKE(1,2); extern NCURSES_EXPORT(int) scr_dump (const char *); /* implemented */ extern NCURSES_EXPORT(int) scr_init (const char *); /* implemented */ extern NCURSES_EXPORT(int) scrl (int); /* generated */ extern NCURSES_EXPORT(int) scroll (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) scrollok (WINDOW *,bool); /* implemented */ extern NCURSES_EXPORT(int) scr_restore (const char *); /* implemented */ extern NCURSES_EXPORT(int) scr_set (const char *); /* implemented */ extern NCURSES_EXPORT(int) setscrreg (int,int); /* generated */ extern NCURSES_EXPORT(SCREEN *) set_term (SCREEN *); /* implemented */ extern NCURSES_EXPORT(int) slk_attroff (const chtype); /* implemented */ extern NCURSES_EXPORT(int) slk_attr_off (const attr_t, void *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) slk_attron (const chtype); /* implemented */ extern NCURSES_EXPORT(int) slk_attr_on (attr_t,void*); /* generated:WIDEC */ extern NCURSES_EXPORT(int) slk_attrset (const chtype); /* implemented */ extern NCURSES_EXPORT(attr_t) slk_attr (void); /* implemented */ extern NCURSES_EXPORT(int) slk_attr_set (const attr_t,NCURSES_PAIRS_T,void*); /* implemented */ extern NCURSES_EXPORT(int) slk_clear (void); /* implemented */ extern NCURSES_EXPORT(int) slk_color (NCURSES_PAIRS_T); /* implemented */ extern NCURSES_EXPORT(int) slk_init (int); /* implemented */ extern NCURSES_EXPORT(char *) slk_label (int); /* implemented */ extern NCURSES_EXPORT(int) slk_noutrefresh (void); /* implemented */ extern NCURSES_EXPORT(int) slk_refresh (void); /* implemented */ extern NCURSES_EXPORT(int) slk_restore (void); /* implemented */ extern NCURSES_EXPORT(int) slk_set (int,const char *,int); /* implemented */ extern NCURSES_EXPORT(int) slk_touch (void); /* implemented */ extern NCURSES_EXPORT(int) standout (void); /* generated */ extern NCURSES_EXPORT(int) standend (void); /* generated */ extern NCURSES_EXPORT(int) start_color (void); /* implemented */ extern NCURSES_EXPORT(WINDOW *) subpad (WINDOW *, int, int, int, int); /* implemented */ extern NCURSES_EXPORT(WINDOW *) subwin (WINDOW *, int, int, int, int); /* implemented */ extern NCURSES_EXPORT(int) syncok (WINDOW *, bool); /* implemented */ extern NCURSES_EXPORT(chtype) termattrs (void); /* implemented */ extern NCURSES_EXPORT(char *) termname (void); /* implemented */ extern NCURSES_EXPORT(void) timeout (int); /* generated */ extern NCURSES_EXPORT(int) touchline (WINDOW *, int, int); /* generated */ extern NCURSES_EXPORT(int) touchwin (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) typeahead (int); /* implemented */ extern NCURSES_EXPORT(int) ungetch (int); /* implemented */ extern NCURSES_EXPORT(int) untouchwin (WINDOW *); /* generated */ extern NCURSES_EXPORT(void) use_env (bool); /* implemented */ extern NCURSES_EXPORT(void) use_tioctl (bool); /* implemented */ extern NCURSES_EXPORT(int) vidattr (chtype); /* implemented */ extern NCURSES_EXPORT(int) vidputs (chtype, NCURSES_OUTC); /* implemented */ extern NCURSES_EXPORT(int) vline (chtype, int); /* generated */ extern NCURSES_EXPORT(int) vwprintw (WINDOW *, const char *,va_list); /* implemented */ extern NCURSES_EXPORT(int) vw_printw (WINDOW *, const char *,va_list); /* generated */ extern NCURSES_EXPORT(int) vwscanw (WINDOW *, NCURSES_CONST char *,va_list); /* implemented */ extern NCURSES_EXPORT(int) vw_scanw (WINDOW *, NCURSES_CONST char *,va_list); /* generated */ extern NCURSES_EXPORT(int) waddch (WINDOW *, const chtype); /* implemented */ extern NCURSES_EXPORT(int) waddchnstr (WINDOW *,const chtype *,int); /* implemented */ extern NCURSES_EXPORT(int) waddchstr (WINDOW *,const chtype *); /* generated */ extern NCURSES_EXPORT(int) waddnstr (WINDOW *,const char *,int); /* implemented */ extern NCURSES_EXPORT(int) waddstr (WINDOW *,const char *); /* generated */ extern NCURSES_EXPORT(int) wattron (WINDOW *, int); /* generated */ extern NCURSES_EXPORT(int) wattroff (WINDOW *, int); /* generated */ extern NCURSES_EXPORT(int) wattrset (WINDOW *, int); /* generated */ extern NCURSES_EXPORT(int) wattr_get (WINDOW *, attr_t *, NCURSES_PAIRS_T *, void *); /* generated */ extern NCURSES_EXPORT(int) wattr_on (WINDOW *, attr_t, void *); /* implemented */ extern NCURSES_EXPORT(int) wattr_off (WINDOW *, attr_t, void *); /* implemented */ extern NCURSES_EXPORT(int) wattr_set (WINDOW *, attr_t, NCURSES_PAIRS_T, void *); /* generated */ extern NCURSES_EXPORT(int) wbkgd (WINDOW *, chtype); /* implemented */ extern NCURSES_EXPORT(void) wbkgdset (WINDOW *,chtype); /* implemented */ extern NCURSES_EXPORT(int) wborder (WINDOW *,chtype,chtype,chtype,chtype,chtype,chtype,chtype,chtype); /* implemented */ extern NCURSES_EXPORT(int) wchgat (WINDOW *, int, attr_t, NCURSES_PAIRS_T, const void *);/* implemented */ extern NCURSES_EXPORT(int) wclear (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wclrtobot (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wclrtoeol (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wcolor_set (WINDOW*,NCURSES_PAIRS_T,void*); /* implemented */ extern NCURSES_EXPORT(void) wcursyncup (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wdelch (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wdeleteln (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) wechochar (WINDOW *, const chtype); /* implemented */ extern NCURSES_EXPORT(int) werase (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wgetch (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wgetnstr (WINDOW *,char *,int); /* implemented */ extern NCURSES_EXPORT(int) wgetstr (WINDOW *, char *); /* generated */ extern NCURSES_EXPORT(int) whline (WINDOW *, chtype, int); /* implemented */ extern NCURSES_EXPORT(chtype) winch (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) winchnstr (WINDOW *, chtype *, int); /* implemented */ extern NCURSES_EXPORT(int) winchstr (WINDOW *, chtype *); /* generated */ extern NCURSES_EXPORT(int) winnstr (WINDOW *, char *, int); /* implemented */ extern NCURSES_EXPORT(int) winsch (WINDOW *, chtype); /* implemented */ extern NCURSES_EXPORT(int) winsdelln (WINDOW *,int); /* implemented */ extern NCURSES_EXPORT(int) winsertln (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) winsnstr (WINDOW *, const char *,int); /* implemented */ extern NCURSES_EXPORT(int) winsstr (WINDOW *, const char *); /* generated */ extern NCURSES_EXPORT(int) winstr (WINDOW *, char *); /* generated */ extern NCURSES_EXPORT(int) wmove (WINDOW *,int,int); /* implemented */ extern NCURSES_EXPORT(int) wnoutrefresh (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wprintw (WINDOW *, const char *,...) /* implemented */ GCC_PRINTFLIKE(2,3); extern NCURSES_EXPORT(int) wredrawln (WINDOW *,int,int); /* implemented */ extern NCURSES_EXPORT(int) wrefresh (WINDOW *); /* implemented */ extern NCURSES_EXPORT(int) wscanw (WINDOW *, NCURSES_CONST char *,...) /* implemented */ GCC_SCANFLIKE(2,3); extern NCURSES_EXPORT(int) wscrl (WINDOW *,int); /* implemented */ extern NCURSES_EXPORT(int) wsetscrreg (WINDOW *,int,int); /* implemented */ extern NCURSES_EXPORT(int) wstandout (WINDOW *); /* generated */ extern NCURSES_EXPORT(int) wstandend (WINDOW *); /* generated */ extern NCURSES_EXPORT(void) wsyncdown (WINDOW *); /* implemented */ extern NCURSES_EXPORT(void) wsyncup (WINDOW *); /* implemented */ extern NCURSES_EXPORT(void) wtimeout (WINDOW *,int); /* implemented */ extern NCURSES_EXPORT(int) wtouchln (WINDOW *,int,int,int); /* implemented */ extern NCURSES_EXPORT(int) wvline (WINDOW *,chtype,int); /* implemented */ /* * These are also declared in : */ extern NCURSES_EXPORT(int) tigetflag (NCURSES_CONST char *); /* implemented */ extern NCURSES_EXPORT(int) tigetnum (NCURSES_CONST char *); /* implemented */ extern NCURSES_EXPORT(char *) tigetstr (NCURSES_CONST char *); /* implemented */ extern NCURSES_EXPORT(int) putp (const char *); /* implemented */ #if NCURSES_TPARM_VARARGS extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, ...); /* special */ #else extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG,NCURSES_TPARM_ARG); /* special */ extern NCURSES_EXPORT(char *) tparm_varargs (NCURSES_CONST char *, ...); /* special */ #endif extern NCURSES_EXPORT(char *) tiparm (const char *, ...); /* special */ /* * X/Open says this returns a bool; SVr4 also checked for out-of-range line. * The macro provides compatibility: */ #define is_linetouched(w,l) ((!(w) || ((l) > getmaxy(w)) || ((l) < 0)) ? ERR : (is_linetouched)((w),(l))) /* * These functions are not in X/Open, but we use them in macro definitions: */ extern NCURSES_EXPORT(int) getattrs (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getcurx (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getcury (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getbegx (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getbegy (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getmaxx (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getmaxy (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getparx (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) getpary (const WINDOW *); /* generated */ /* * vid_attr() was implemented originally based on a draft of X/Open curses. */ #if !NCURSES_WIDECHAR #define vid_attr(a,pair,opts) vidattr(a) #endif /* * These functions are extensions - not in X/Open Curses. */ #if 1 #undef NCURSES_EXT_FUNCS #define NCURSES_EXT_FUNCS 20180224 typedef int (*NCURSES_WINDOW_CB)(WINDOW *, void *); typedef int (*NCURSES_SCREEN_CB)(SCREEN *, void *); extern NCURSES_EXPORT(bool) is_term_resized (int, int); extern NCURSES_EXPORT(char *) keybound (int, int); extern NCURSES_EXPORT(const char *) curses_version (void); extern NCURSES_EXPORT(int) alloc_pair (int, int); extern NCURSES_EXPORT(int) assume_default_colors (int, int); extern NCURSES_EXPORT(int) define_key (const char *, int); extern NCURSES_EXPORT(int) extended_color_content(int, int *, int *, int *); extern NCURSES_EXPORT(int) extended_pair_content(int, int *, int *); extern NCURSES_EXPORT(int) extended_slk_color(int); extern NCURSES_EXPORT(int) find_pair (int, int); extern NCURSES_EXPORT(int) free_pair (int); extern NCURSES_EXPORT(int) get_escdelay (void); extern NCURSES_EXPORT(int) init_extended_color(int, int, int, int); extern NCURSES_EXPORT(int) init_extended_pair(int, int, int); extern NCURSES_EXPORT(int) key_defined (const char *); extern NCURSES_EXPORT(int) keyok (int, bool); extern NCURSES_EXPORT(void) reset_color_pairs (void); extern NCURSES_EXPORT(int) resize_term (int, int); extern NCURSES_EXPORT(int) resizeterm (int, int); extern NCURSES_EXPORT(int) set_escdelay (int); extern NCURSES_EXPORT(int) set_tabsize (int); extern NCURSES_EXPORT(int) use_default_colors (void); extern NCURSES_EXPORT(int) use_extended_names (bool); extern NCURSES_EXPORT(int) use_legacy_coding (int); extern NCURSES_EXPORT(int) use_screen (SCREEN *, NCURSES_SCREEN_CB, void *); extern NCURSES_EXPORT(int) use_window (WINDOW *, NCURSES_WINDOW_CB, void *); extern NCURSES_EXPORT(int) wresize (WINDOW *, int, int); extern NCURSES_EXPORT(void) nofilter(void); /* * These extensions provide access to information stored in the WINDOW even * when NCURSES_OPAQUE is set: */ extern NCURSES_EXPORT(WINDOW *) wgetparent (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_cleared (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_idcok (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_idlok (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_immedok (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_keypad (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_leaveok (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_nodelay (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_notimeout (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_pad (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_scrollok (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_subwin (const WINDOW *); /* generated */ extern NCURSES_EXPORT(bool) is_syncok (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) wgetdelay (const WINDOW *); /* generated */ extern NCURSES_EXPORT(int) wgetscrreg (const WINDOW *, int *, int *); /* generated */ #else #define curses_version() NCURSES_VERSION #endif /* * Extra extension-functions, which pass a SCREEN pointer rather than using * a global variable SP. */ #if 1 #undef NCURSES_SP_FUNCS #define NCURSES_SP_FUNCS 20180224 #define NCURSES_SP_NAME(name) name##_sp /* Define the sp-funcs helper function */ #define NCURSES_SP_OUTC NCURSES_SP_NAME(NCURSES_OUTC) typedef int (*NCURSES_SP_OUTC)(SCREEN*, int); extern NCURSES_EXPORT(SCREEN *) new_prescr (void); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(baudrate) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(beep) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(can_change_color) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(cbreak) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(curs_set) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(color_content) (SCREEN*, NCURSES_PAIRS_T, NCURSES_COLOR_T*, NCURSES_COLOR_T*, NCURSES_COLOR_T*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(def_prog_mode) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(def_shell_mode) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(delay_output) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(doupdate) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(echo) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(endwin) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(char) NCURSES_SP_NAME(erasechar) (SCREEN*);/* implemented:SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(filter) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(flash) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(flushinp) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(getwin) (SCREEN*, FILE *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(halfdelay) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_colors) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_ic) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_il) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_color) (SCREEN*, NCURSES_COLOR_T, NCURSES_COLOR_T, NCURSES_COLOR_T, NCURSES_COLOR_T); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_pair) (SCREEN*, NCURSES_PAIRS_T, NCURSES_COLOR_T, NCURSES_COLOR_T); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(intrflush) (SCREEN*, WINDOW*, bool); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(isendwin) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(NCURSES_CONST char *) NCURSES_SP_NAME(keyname) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(char) NCURSES_SP_NAME(killchar) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(longname) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mvcur) (SCREEN*, int, int, int, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(napms) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(newpad) (SCREEN*, int, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(SCREEN *) NCURSES_SP_NAME(newterm) (SCREEN*, NCURSES_CONST char *, FILE *, FILE *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(newwin) (SCREEN*, int, int, int, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nl) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nocbreak) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(noecho) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(nonl) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(noqiflush) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(noraw) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(pair_content) (SCREEN*, NCURSES_PAIRS_T, NCURSES_COLOR_T*, NCURSES_COLOR_T*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(qiflush) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(raw) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(reset_prog_mode) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(reset_shell_mode) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resetty) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ripoffline) (SCREEN*, int, int (*)(WINDOW *, int)); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(savetty) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_init) (SCREEN*, const char *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_restore) (SCREEN*, const char *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(scr_set) (SCREEN*, const char *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attroff) (SCREEN*, const chtype); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attron) (SCREEN*, const chtype); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attrset) (SCREEN*, const chtype); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(attr_t) NCURSES_SP_NAME(slk_attr) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_attr_set) (SCREEN*, const attr_t, NCURSES_PAIRS_T, void*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_clear) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_color) (SCREEN*, NCURSES_PAIRS_T); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_init) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(slk_label) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_noutrefresh) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_refresh) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_restore) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_set) (SCREEN*, int, const char *, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(slk_touch) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(start_color) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(chtype) NCURSES_SP_NAME(termattrs) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(termname) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(typeahead) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ungetch) (SCREEN*, int); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(use_env) (SCREEN*, bool); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(use_tioctl) (SCREEN*, bool); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vidattr) (SCREEN*, chtype); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vidputs) (SCREEN*, chtype, NCURSES_SP_OUTC); /* implemented:SP_FUNC */ #if 1 extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(keybound) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(alloc_pair) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(assume_default_colors) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(define_key) (SCREEN*, const char *, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(extended_color_content) (SCREEN*, int, int *, int *, int *); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(extended_pair_content) (SCREEN*, int, int *, int *); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(extended_slk_color) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(get_escdelay) (SCREEN*); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(find_pair) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(free_pair) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_extended_color) (SCREEN*, int, int, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(init_extended_pair) (SCREEN*, int, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(is_term_resized) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(key_defined) (SCREEN*, const char *); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(keyok) (SCREEN*, int, bool); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(nofilter) (SCREEN*); /* implemented */ /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(void) NCURSES_SP_NAME(reset_color_pairs) (SCREEN*); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resize_term) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(resizeterm) (SCREEN*, int, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(set_escdelay) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(set_tabsize) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(use_default_colors) (SCREEN*); /* implemented:EXT_SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(use_legacy_coding) (SCREEN*, int); /* implemented:EXT_SP_FUNC */ #endif #else #undef NCURSES_SP_FUNCS #define NCURSES_SP_FUNCS 0 #define NCURSES_SP_NAME(name) name #define NCURSES_SP_OUTC NCURSES_OUTC #endif /* attributes */ #define NCURSES_ATTR_SHIFT 8 #define NCURSES_BITS(mask,shift) (NCURSES_CAST(chtype,(mask)) << ((shift) + NCURSES_ATTR_SHIFT)) #define A_NORMAL (1U - 1U) #define A_ATTRIBUTES NCURSES_BITS(~(1U - 1U),0) #define A_CHARTEXT (NCURSES_BITS(1U,0) - 1U) #define A_COLOR NCURSES_BITS(((1U) << 8) - 1U,0) #define A_STANDOUT NCURSES_BITS(1U,8) #define A_UNDERLINE NCURSES_BITS(1U,9) #define A_REVERSE NCURSES_BITS(1U,10) #define A_BLINK NCURSES_BITS(1U,11) #define A_DIM NCURSES_BITS(1U,12) #define A_BOLD NCURSES_BITS(1U,13) #define A_ALTCHARSET NCURSES_BITS(1U,14) #define A_INVIS NCURSES_BITS(1U,15) #define A_PROTECT NCURSES_BITS(1U,16) #define A_HORIZONTAL NCURSES_BITS(1U,17) #define A_LEFT NCURSES_BITS(1U,18) #define A_LOW NCURSES_BITS(1U,19) #define A_RIGHT NCURSES_BITS(1U,20) #define A_TOP NCURSES_BITS(1U,21) #define A_VERTICAL NCURSES_BITS(1U,22) #if 1 #define A_ITALIC NCURSES_BITS(1U,23) /* ncurses extension */ #endif /* * Most of the pseudo functions are macros that either provide compatibility * with older versions of curses, or provide inline functionality to improve * performance. */ /* * These pseudo functions are always implemented as macros: */ #define getyx(win,y,x) (y = getcury(win), x = getcurx(win)) #define getbegyx(win,y,x) (y = getbegy(win), x = getbegx(win)) #define getmaxyx(win,y,x) (y = getmaxy(win), x = getmaxx(win)) #define getparyx(win,y,x) (y = getpary(win), x = getparx(win)) #define getsyx(y,x) do { if (newscr) { \ if (is_leaveok(newscr)) \ (y) = (x) = -1; \ else \ getyx(newscr,(y), (x)); \ } \ } while(0) #define setsyx(y,x) do { if (newscr) { \ if ((y) == -1 && (x) == -1) \ leaveok(newscr, TRUE); \ else { \ leaveok(newscr, FALSE); \ wmove(newscr, (y), (x)); \ } \ } \ } while(0) #ifndef NCURSES_NOMACROS /* * These miscellaneous pseudo functions are provided for compatibility: */ #define wgetstr(w, s) wgetnstr(w, s, -1) #define getnstr(s, n) wgetnstr(stdscr, s, (n)) #define setterm(term) setupterm(term, 1, (int *)0) #define fixterm() reset_prog_mode() #define resetterm() reset_shell_mode() #define saveterm() def_prog_mode() #define crmode() cbreak() #define nocrmode() nocbreak() #define gettmode() /* It seems older SYSV curses versions define these */ #if !NCURSES_OPAQUE #define getattrs(win) NCURSES_CAST(int, NCURSES_OK_ADDR(win) ? (win)->_attrs : A_NORMAL) #define getcurx(win) (NCURSES_OK_ADDR(win) ? (win)->_curx : ERR) #define getcury(win) (NCURSES_OK_ADDR(win) ? (win)->_cury : ERR) #define getbegx(win) (NCURSES_OK_ADDR(win) ? (win)->_begx : ERR) #define getbegy(win) (NCURSES_OK_ADDR(win) ? (win)->_begy : ERR) #define getmaxx(win) (NCURSES_OK_ADDR(win) ? ((win)->_maxx + 1) : ERR) #define getmaxy(win) (NCURSES_OK_ADDR(win) ? ((win)->_maxy + 1) : ERR) #define getparx(win) (NCURSES_OK_ADDR(win) ? (win)->_parx : ERR) #define getpary(win) (NCURSES_OK_ADDR(win) ? (win)->_pary : ERR) #endif /* NCURSES_OPAQUE */ #define wstandout(win) (wattrset(win,A_STANDOUT)) #define wstandend(win) (wattrset(win,A_NORMAL)) #define wattron(win,at) wattr_on(win, NCURSES_CAST(attr_t, at), NULL) #define wattroff(win,at) wattr_off(win, NCURSES_CAST(attr_t, at), NULL) #if !NCURSES_OPAQUE #if NCURSES_WATTR_MACROS #if NCURSES_WIDECHAR && 1 #define wattrset(win,at) \ (NCURSES_OK_ADDR(win) \ ? ((win)->_color = NCURSES_CAST(int, PAIR_NUMBER(at)), \ (win)->_attrs = NCURSES_CAST(attr_t, at), \ OK) \ : ERR) #else #define wattrset(win,at) \ (NCURSES_OK_ADDR(win) \ ? ((win)->_attrs = NCURSES_CAST(attr_t, at), \ OK) \ : ERR) #endif #endif /* NCURSES_WATTR_MACROS */ #endif /* NCURSES_OPAQUE */ #define scroll(win) wscrl(win,1) #define touchwin(win) wtouchln((win), 0, getmaxy(win), 1) #define touchline(win, s, c) wtouchln((win), s, c, 1) #define untouchwin(win) wtouchln((win), 0, getmaxy(win), 0) #define box(win, v, h) wborder(win, v, v, h, h, 0, 0, 0, 0) #define border(ls, rs, ts, bs, tl, tr, bl, br) wborder(stdscr, ls, rs, ts, bs, tl, tr, bl, br) #define hline(ch, n) whline(stdscr, ch, (n)) #define vline(ch, n) wvline(stdscr, ch, (n)) #define winstr(w, s) winnstr(w, s, -1) #define winchstr(w, s) winchnstr(w, s, -1) #define winsstr(w, s) winsnstr(w, s, -1) #if !NCURSES_OPAQUE #define redrawwin(win) wredrawln(win, 0, (NCURSES_OK_ADDR(win) ? (win)->_maxy+1 : -1)) #endif /* NCURSES_OPAQUE */ #define waddstr(win,str) waddnstr(win,str,-1) #define waddchstr(win,str) waddchnstr(win,str,-1) /* * These apply to the first 256 color pairs. */ #define COLOR_PAIR(n) (NCURSES_BITS((n), 0) & A_COLOR) #define PAIR_NUMBER(a) (NCURSES_CAST(int,((NCURSES_CAST(unsigned long,(a)) & A_COLOR) >> NCURSES_ATTR_SHIFT))) /* * pseudo functions for standard screen */ #define addch(ch) waddch(stdscr,(ch)) #define addchnstr(str,n) waddchnstr(stdscr,(str),(n)) #define addchstr(str) waddchstr(stdscr,(str)) #define addnstr(str,n) waddnstr(stdscr,(str),(n)) #define addstr(str) waddnstr(stdscr,(str),-1) #define attr_get(ap,cp,o) wattr_get(stdscr,(ap),(cp),(o)) #define attr_off(a,o) wattr_off(stdscr,(a),(o)) #define attr_on(a,o) wattr_on(stdscr,(a),(o)) #define attr_set(a,c,o) wattr_set(stdscr,(a),(c),(o)) #define attroff(at) wattroff(stdscr,(at)) #define attron(at) wattron(stdscr,(at)) #define attrset(at) wattrset(stdscr,(at)) #define bkgd(ch) wbkgd(stdscr,(ch)) #define bkgdset(ch) wbkgdset(stdscr,(ch)) #define chgat(n,a,c,o) wchgat(stdscr,(n),(a),(c),(o)) #define clear() wclear(stdscr) #define clrtobot() wclrtobot(stdscr) #define clrtoeol() wclrtoeol(stdscr) #define color_set(c,o) wcolor_set(stdscr,(c),(o)) #define delch() wdelch(stdscr) #define deleteln() winsdelln(stdscr,-1) #define echochar(c) wechochar(stdscr,(c)) #define erase() werase(stdscr) #define getch() wgetch(stdscr) #define getstr(str) wgetstr(stdscr,(str)) #define inch() winch(stdscr) #define inchnstr(s,n) winchnstr(stdscr,(s),(n)) #define inchstr(s) winchstr(stdscr,(s)) #define innstr(s,n) winnstr(stdscr,(s),(n)) #define insch(c) winsch(stdscr,(c)) #define insdelln(n) winsdelln(stdscr,(n)) #define insertln() winsdelln(stdscr,1) #define insnstr(s,n) winsnstr(stdscr,(s),(n)) #define insstr(s) winsstr(stdscr,(s)) #define instr(s) winstr(stdscr,(s)) #define move(y,x) wmove(stdscr,(y),(x)) #define refresh() wrefresh(stdscr) #define scrl(n) wscrl(stdscr,(n)) #define setscrreg(t,b) wsetscrreg(stdscr,(t),(b)) #define standend() wstandend(stdscr) #define standout() wstandout(stdscr) #define timeout(delay) wtimeout(stdscr,(delay)) #define wdeleteln(win) winsdelln(win,-1) #define winsertln(win) winsdelln(win,1) /* * mv functions */ #define mvwaddch(win,y,x,ch) (wmove((win),(y),(x)) == ERR ? ERR : waddch((win),(ch))) #define mvwaddchnstr(win,y,x,str,n) (wmove((win),(y),(x)) == ERR ? ERR : waddchnstr((win),(str),(n))) #define mvwaddchstr(win,y,x,str) (wmove((win),(y),(x)) == ERR ? ERR : waddchnstr((win),(str),-1)) #define mvwaddnstr(win,y,x,str,n) (wmove((win),(y),(x)) == ERR ? ERR : waddnstr((win),(str),(n))) #define mvwaddstr(win,y,x,str) (wmove((win),(y),(x)) == ERR ? ERR : waddnstr((win),(str),-1)) #define mvwchgat(win,y,x,n,a,c,o) (wmove((win),(y),(x)) == ERR ? ERR : wchgat((win),(n),(a),(c),(o))) #define mvwdelch(win,y,x) (wmove((win),(y),(x)) == ERR ? ERR : wdelch(win)) #define mvwgetch(win,y,x) (wmove((win),(y),(x)) == ERR ? ERR : wgetch(win)) #define mvwgetnstr(win,y,x,str,n) (wmove((win),(y),(x)) == ERR ? ERR : wgetnstr((win),(str),(n))) #define mvwgetstr(win,y,x,str) (wmove((win),(y),(x)) == ERR ? ERR : wgetstr((win),(str))) #define mvwhline(win,y,x,c,n) (wmove((win),(y),(x)) == ERR ? ERR : whline((win),(c),(n))) #define mvwinch(win,y,x) (wmove((win),(y),(x)) == ERR ? NCURSES_CAST(chtype, ERR) : winch(win)) #define mvwinchnstr(win,y,x,s,n) (wmove((win),(y),(x)) == ERR ? ERR : winchnstr((win),(s),(n))) #define mvwinchstr(win,y,x,s) (wmove((win),(y),(x)) == ERR ? ERR : winchstr((win),(s))) #define mvwinnstr(win,y,x,s,n) (wmove((win),(y),(x)) == ERR ? ERR : winnstr((win),(s),(n))) #define mvwinsch(win,y,x,c) (wmove((win),(y),(x)) == ERR ? ERR : winsch((win),(c))) #define mvwinsnstr(win,y,x,s,n) (wmove((win),(y),(x)) == ERR ? ERR : winsnstr((win),(s),(n))) #define mvwinsstr(win,y,x,s) (wmove((win),(y),(x)) == ERR ? ERR : winsstr((win),(s))) #define mvwinstr(win,y,x,s) (wmove((win),(y),(x)) == ERR ? ERR : winstr((win),(s))) #define mvwvline(win,y,x,c,n) (wmove((win),(y),(x)) == ERR ? ERR : wvline((win),(c),(n))) #define mvaddch(y,x,ch) mvwaddch(stdscr,(y),(x),(ch)) #define mvaddchnstr(y,x,str,n) mvwaddchnstr(stdscr,(y),(x),(str),(n)) #define mvaddchstr(y,x,str) mvwaddchstr(stdscr,(y),(x),(str)) #define mvaddnstr(y,x,str,n) mvwaddnstr(stdscr,(y),(x),(str),(n)) #define mvaddstr(y,x,str) mvwaddstr(stdscr,(y),(x),(str)) #define mvchgat(y,x,n,a,c,o) mvwchgat(stdscr,(y),(x),(n),(a),(c),(o)) #define mvdelch(y,x) mvwdelch(stdscr,(y),(x)) #define mvgetch(y,x) mvwgetch(stdscr,(y),(x)) #define mvgetnstr(y,x,str,n) mvwgetnstr(stdscr,(y),(x),(str),(n)) #define mvgetstr(y,x,str) mvwgetstr(stdscr,(y),(x),(str)) #define mvhline(y,x,c,n) mvwhline(stdscr,(y),(x),(c),(n)) #define mvinch(y,x) mvwinch(stdscr,(y),(x)) #define mvinchnstr(y,x,s,n) mvwinchnstr(stdscr,(y),(x),(s),(n)) #define mvinchstr(y,x,s) mvwinchstr(stdscr,(y),(x),(s)) #define mvinnstr(y,x,s,n) mvwinnstr(stdscr,(y),(x),(s),(n)) #define mvinsch(y,x,c) mvwinsch(stdscr,(y),(x),(c)) #define mvinsnstr(y,x,s,n) mvwinsnstr(stdscr,(y),(x),(s),(n)) #define mvinsstr(y,x,s) mvwinsstr(stdscr,(y),(x),(s)) #define mvinstr(y,x,s) mvwinstr(stdscr,(y),(x),(s)) #define mvvline(y,x,c,n) mvwvline(stdscr,(y),(x),(c),(n)) /* * Some wide-character functions can be implemented without the extensions. */ #if !NCURSES_OPAQUE #define getbkgd(win) (NCURSES_OK_ADDR(win) ? ((win)->_bkgd) : 0) #endif /* NCURSES_OPAQUE */ #define slk_attr_off(a,v) ((v) ? ERR : slk_attroff(a)) #define slk_attr_on(a,v) ((v) ? ERR : slk_attron(a)) #if !NCURSES_OPAQUE #if NCURSES_WATTR_MACROS #if NCURSES_WIDECHAR && 1 #define wattr_set(win,a,p,opts) \ (NCURSES_OK_ADDR(win) \ ? ((void)((win)->_attrs = ((a) & ~A_COLOR), \ (win)->_color = (opts) ? *(int *)(opts) : (p)), \ OK) \ : ERR) #define wattr_get(win,a,p,opts) \ (NCURSES_OK_ADDR(win) \ ? ((void)(NCURSES_OK_ADDR(a) \ ? (*(a) = (win)->_attrs) \ : OK), \ (void)(NCURSES_OK_ADDR(p) \ ? (*(p) = (NCURSES_PAIRS_T) (win)->_color) \ : OK), \ (void)(NCURSES_OK_ADDR(opts) \ ? (*(int *)(opts) = (win)->_color) \ : OK), \ OK) \ : ERR) #else /* !(NCURSES_WIDECHAR && NCURSES_EXE_COLORS) */ #define wattr_set(win,a,p,opts) \ (NCURSES_OK_ADDR(win) \ ? ((void)((win)->_attrs = (((a) & ~A_COLOR) | \ (attr_t)COLOR_PAIR(p))), \ OK) \ : ERR) #define wattr_get(win,a,p,opts) \ (NCURSES_OK_ADDR(win) \ ? ((void)(NCURSES_OK_ADDR(a) \ ? (*(a) = (win)->_attrs) \ : OK), \ (void)(NCURSES_OK_ADDR(p) \ ? (*(p) = (NCURSES_PAIRS_T) PAIR_NUMBER((win)->_attrs)) \ : OK), \ OK) \ : ERR) #endif /* (NCURSES_WIDECHAR && NCURSES_EXE_COLORS) */ #endif /* NCURSES_WATTR_MACROS */ #endif /* NCURSES_OPAQUE */ /* * X/Open curses deprecates SVr4 vwprintw/vwscanw, which are supposed to use * varargs.h. It adds new calls vw_printw/vw_scanw, which are supposed to * use POSIX stdarg.h. The ncurses versions of vwprintw/vwscanw already * use stdarg.h, so... */ #define vw_printw vwprintw #define vw_scanw vwscanw /* * Export fallback function for use in C++ binding. */ #if !1 #define vsscanf(a,b,c) _nc_vsscanf(a,b,c) NCURSES_EXPORT(int) vsscanf(const char *, const char *, va_list); #endif /* * These macros are extensions - not in X/Open Curses. */ #if 1 #if !NCURSES_OPAQUE #define is_cleared(win) (NCURSES_OK_ADDR(win) ? (win)->_clear : FALSE) #define is_idcok(win) (NCURSES_OK_ADDR(win) ? (win)->_idcok : FALSE) #define is_idlok(win) (NCURSES_OK_ADDR(win) ? (win)->_idlok : FALSE) #define is_immedok(win) (NCURSES_OK_ADDR(win) ? (win)->_immed : FALSE) #define is_keypad(win) (NCURSES_OK_ADDR(win) ? (win)->_use_keypad : FALSE) #define is_leaveok(win) (NCURSES_OK_ADDR(win) ? (win)->_leaveok : FALSE) #define is_nodelay(win) (NCURSES_OK_ADDR(win) ? ((win)->_delay == 0) : FALSE) #define is_notimeout(win) (NCURSES_OK_ADDR(win) ? (win)->_notimeout : FALSE) #define is_pad(win) (NCURSES_OK_ADDR(win) ? ((win)->_flags & _ISPAD) != 0 : FALSE) #define is_scrollok(win) (NCURSES_OK_ADDR(win) ? (win)->_scroll : FALSE) #define is_subwin(win) (NCURSES_OK_ADDR(win) ? ((win)->_flags & _SUBWIN) != 0 : FALSE) #define is_syncok(win) (NCURSES_OK_ADDR(win) ? (win)->_sync : FALSE) #define wgetdelay(win) (NCURSES_OK_ADDR(win) ? (win)->_delay : 0) #define wgetparent(win) (NCURSES_OK_ADDR(win) ? (win)->_parent : 0) #define wgetscrreg(win,t,b) (NCURSES_OK_ADDR(win) ? (*(t) = (win)->_regtop, *(b) = (win)->_regbottom, OK) : ERR) #endif #endif #endif /* NCURSES_NOMACROS */ /* * Public variables. * * Notes: * a. ESCDELAY was an undocumented feature under AIX curses. * It gives the ESC expire time in milliseconds. * b. ttytype is needed for backward compatibility */ #if NCURSES_REENTRANT NCURSES_WRAPPED_VAR(WINDOW *, curscr); NCURSES_WRAPPED_VAR(WINDOW *, newscr); NCURSES_WRAPPED_VAR(WINDOW *, stdscr); NCURSES_WRAPPED_VAR(char *, ttytype); NCURSES_WRAPPED_VAR(int, COLORS); NCURSES_WRAPPED_VAR(int, COLOR_PAIRS); NCURSES_WRAPPED_VAR(int, COLS); NCURSES_WRAPPED_VAR(int, ESCDELAY); NCURSES_WRAPPED_VAR(int, LINES); NCURSES_WRAPPED_VAR(int, TABSIZE); #define curscr NCURSES_PUBLIC_VAR(curscr()) #define newscr NCURSES_PUBLIC_VAR(newscr()) #define stdscr NCURSES_PUBLIC_VAR(stdscr()) #define ttytype NCURSES_PUBLIC_VAR(ttytype()) #define COLORS NCURSES_PUBLIC_VAR(COLORS()) #define COLOR_PAIRS NCURSES_PUBLIC_VAR(COLOR_PAIRS()) #define COLS NCURSES_PUBLIC_VAR(COLS()) #define ESCDELAY NCURSES_PUBLIC_VAR(ESCDELAY()) #define LINES NCURSES_PUBLIC_VAR(LINES()) #define TABSIZE NCURSES_PUBLIC_VAR(TABSIZE()) #else extern NCURSES_EXPORT_VAR(WINDOW *) curscr; extern NCURSES_EXPORT_VAR(WINDOW *) newscr; extern NCURSES_EXPORT_VAR(WINDOW *) stdscr; extern NCURSES_EXPORT_VAR(char) ttytype[]; extern NCURSES_EXPORT_VAR(int) COLORS; extern NCURSES_EXPORT_VAR(int) COLOR_PAIRS; extern NCURSES_EXPORT_VAR(int) COLS; extern NCURSES_EXPORT_VAR(int) ESCDELAY; extern NCURSES_EXPORT_VAR(int) LINES; extern NCURSES_EXPORT_VAR(int) TABSIZE; #endif /* * Pseudo-character tokens outside ASCII range. The curses wgetch() function * will return any given one of these only if the corresponding k- capability * is defined in your terminal's terminfo entry. * * Some keys (KEY_A1, etc) are arranged like this: * a1 up a3 * left b2 right * c1 down c3 * * A few key codes do not depend upon the terminfo entry. */ #define KEY_CODE_YES 0400 /* A wchar_t contains a key code */ #define KEY_MIN 0401 /* Minimum curses key */ #define KEY_BREAK 0401 /* Break key (unreliable) */ #define KEY_SRESET 0530 /* Soft (partial) reset (unreliable) */ #define KEY_RESET 0531 /* Reset or hard reset (unreliable) */ /* * These definitions were generated by ./MKkey_defs.sh ./Caps */ #define KEY_DOWN 0402 /* down-arrow key */ #define KEY_UP 0403 /* up-arrow key */ #define KEY_LEFT 0404 /* left-arrow key */ #define KEY_RIGHT 0405 /* right-arrow key */ #define KEY_HOME 0406 /* home key */ #define KEY_BACKSPACE 0407 /* backspace key */ #define KEY_F0 0410 /* Function keys. Space for 64 */ #define KEY_F(n) (KEY_F0+(n)) /* Value of function key n */ #define KEY_DL 0510 /* delete-line key */ #define KEY_IL 0511 /* insert-line key */ #define KEY_DC 0512 /* delete-character key */ #define KEY_IC 0513 /* insert-character key */ #define KEY_EIC 0514 /* sent by rmir or smir in insert mode */ #define KEY_CLEAR 0515 /* clear-screen or erase key */ #define KEY_EOS 0516 /* clear-to-end-of-screen key */ #define KEY_EOL 0517 /* clear-to-end-of-line key */ #define KEY_SF 0520 /* scroll-forward key */ #define KEY_SR 0521 /* scroll-backward key */ #define KEY_NPAGE 0522 /* next-page key */ #define KEY_PPAGE 0523 /* previous-page key */ #define KEY_STAB 0524 /* set-tab key */ #define KEY_CTAB 0525 /* clear-tab key */ #define KEY_CATAB 0526 /* clear-all-tabs key */ #define KEY_ENTER 0527 /* enter/send key */ #define KEY_PRINT 0532 /* print key */ #define KEY_LL 0533 /* lower-left key (home down) */ #define KEY_A1 0534 /* upper left of keypad */ #define KEY_A3 0535 /* upper right of keypad */ #define KEY_B2 0536 /* center of keypad */ #define KEY_C1 0537 /* lower left of keypad */ #define KEY_C3 0540 /* lower right of keypad */ #define KEY_BTAB 0541 /* back-tab key */ #define KEY_BEG 0542 /* begin key */ #define KEY_CANCEL 0543 /* cancel key */ #define KEY_CLOSE 0544 /* close key */ #define KEY_COMMAND 0545 /* command key */ #define KEY_COPY 0546 /* copy key */ #define KEY_CREATE 0547 /* create key */ #define KEY_END 0550 /* end key */ #define KEY_EXIT 0551 /* exit key */ #define KEY_FIND 0552 /* find key */ #define KEY_HELP 0553 /* help key */ #define KEY_MARK 0554 /* mark key */ #define KEY_MESSAGE 0555 /* message key */ #define KEY_MOVE 0556 /* move key */ #define KEY_NEXT 0557 /* next key */ #define KEY_OPEN 0560 /* open key */ #define KEY_OPTIONS 0561 /* options key */ #define KEY_PREVIOUS 0562 /* previous key */ #define KEY_REDO 0563 /* redo key */ #define KEY_REFERENCE 0564 /* reference key */ #define KEY_REFRESH 0565 /* refresh key */ #define KEY_REPLACE 0566 /* replace key */ #define KEY_RESTART 0567 /* restart key */ #define KEY_RESUME 0570 /* resume key */ #define KEY_SAVE 0571 /* save key */ #define KEY_SBEG 0572 /* shifted begin key */ #define KEY_SCANCEL 0573 /* shifted cancel key */ #define KEY_SCOMMAND 0574 /* shifted command key */ #define KEY_SCOPY 0575 /* shifted copy key */ #define KEY_SCREATE 0576 /* shifted create key */ #define KEY_SDC 0577 /* shifted delete-character key */ #define KEY_SDL 0600 /* shifted delete-line key */ #define KEY_SELECT 0601 /* select key */ #define KEY_SEND 0602 /* shifted end key */ #define KEY_SEOL 0603 /* shifted clear-to-end-of-line key */ #define KEY_SEXIT 0604 /* shifted exit key */ #define KEY_SFIND 0605 /* shifted find key */ #define KEY_SHELP 0606 /* shifted help key */ #define KEY_SHOME 0607 /* shifted home key */ #define KEY_SIC 0610 /* shifted insert-character key */ #define KEY_SLEFT 0611 /* shifted left-arrow key */ #define KEY_SMESSAGE 0612 /* shifted message key */ #define KEY_SMOVE 0613 /* shifted move key */ #define KEY_SNEXT 0614 /* shifted next key */ #define KEY_SOPTIONS 0615 /* shifted options key */ #define KEY_SPREVIOUS 0616 /* shifted previous key */ #define KEY_SPRINT 0617 /* shifted print key */ #define KEY_SREDO 0620 /* shifted redo key */ #define KEY_SREPLACE 0621 /* shifted replace key */ #define KEY_SRIGHT 0622 /* shifted right-arrow key */ #define KEY_SRSUME 0623 /* shifted resume key */ #define KEY_SSAVE 0624 /* shifted save key */ #define KEY_SSUSPEND 0625 /* shifted suspend key */ #define KEY_SUNDO 0626 /* shifted undo key */ #define KEY_SUSPEND 0627 /* suspend key */ #define KEY_UNDO 0630 /* undo key */ #define KEY_MOUSE 0631 /* Mouse event has occurred */ #define KEY_RESIZE 0632 /* Terminal resize event */ #define KEY_EVENT 0633 /* We were interrupted by an event */ #define KEY_MAX 0777 /* Maximum key value is 0633 */ /* $Id: curses.wide,v 1.50 2017/03/26 16:05:21 tom Exp $ */ /* * vile:cmode: * This file is part of ncurses, designed to be appended after curses.h.in * (see that file for the relevant copyright). */ #define _XOPEN_CURSES 1 #if NCURSES_WIDECHAR extern NCURSES_EXPORT_VAR(cchar_t *) _nc_wacs; #define NCURSES_WACS(c) (&_nc_wacs[NCURSES_CAST(unsigned char,(c))]) #define WACS_BSSB NCURSES_WACS('l') #define WACS_SSBB NCURSES_WACS('m') #define WACS_BBSS NCURSES_WACS('k') #define WACS_SBBS NCURSES_WACS('j') #define WACS_SBSS NCURSES_WACS('u') #define WACS_SSSB NCURSES_WACS('t') #define WACS_SSBS NCURSES_WACS('v') #define WACS_BSSS NCURSES_WACS('w') #define WACS_BSBS NCURSES_WACS('q') #define WACS_SBSB NCURSES_WACS('x') #define WACS_SSSS NCURSES_WACS('n') #define WACS_ULCORNER WACS_BSSB #define WACS_LLCORNER WACS_SSBB #define WACS_URCORNER WACS_BBSS #define WACS_LRCORNER WACS_SBBS #define WACS_RTEE WACS_SBSS #define WACS_LTEE WACS_SSSB #define WACS_BTEE WACS_SSBS #define WACS_TTEE WACS_BSSS #define WACS_HLINE WACS_BSBS #define WACS_VLINE WACS_SBSB #define WACS_PLUS WACS_SSSS #define WACS_S1 NCURSES_WACS('o') /* scan line 1 */ #define WACS_S9 NCURSES_WACS('s') /* scan line 9 */ #define WACS_DIAMOND NCURSES_WACS('`') /* diamond */ #define WACS_CKBOARD NCURSES_WACS('a') /* checker board */ #define WACS_DEGREE NCURSES_WACS('f') /* degree symbol */ #define WACS_PLMINUS NCURSES_WACS('g') /* plus/minus */ #define WACS_BULLET NCURSES_WACS('~') /* bullet */ /* Teletype 5410v1 symbols */ #define WACS_LARROW NCURSES_WACS(',') /* arrow left */ #define WACS_RARROW NCURSES_WACS('+') /* arrow right */ #define WACS_DARROW NCURSES_WACS('.') /* arrow down */ #define WACS_UARROW NCURSES_WACS('-') /* arrow up */ #define WACS_BOARD NCURSES_WACS('h') /* board of squares */ #define WACS_LANTERN NCURSES_WACS('i') /* lantern symbol */ #define WACS_BLOCK NCURSES_WACS('0') /* solid square block */ /* ncurses extensions */ #define WACS_S3 NCURSES_WACS('p') /* scan line 3 */ #define WACS_S7 NCURSES_WACS('r') /* scan line 7 */ #define WACS_LEQUAL NCURSES_WACS('y') /* less/equal */ #define WACS_GEQUAL NCURSES_WACS('z') /* greater/equal */ #define WACS_PI NCURSES_WACS('{') /* Pi */ #define WACS_NEQUAL NCURSES_WACS('|') /* not equal */ #define WACS_STERLING NCURSES_WACS('}') /* UK pound sign */ /* double lines */ #define WACS_BDDB NCURSES_WACS('C') #define WACS_DDBB NCURSES_WACS('D') #define WACS_BBDD NCURSES_WACS('B') #define WACS_DBBD NCURSES_WACS('A') #define WACS_DBDD NCURSES_WACS('G') #define WACS_DDDB NCURSES_WACS('F') #define WACS_DDBD NCURSES_WACS('H') #define WACS_BDDD NCURSES_WACS('I') #define WACS_BDBD NCURSES_WACS('R') #define WACS_DBDB NCURSES_WACS('Y') #define WACS_DDDD NCURSES_WACS('E') #define WACS_D_ULCORNER WACS_BDDB #define WACS_D_LLCORNER WACS_DDBB #define WACS_D_URCORNER WACS_BBDD #define WACS_D_LRCORNER WACS_DBBD #define WACS_D_RTEE WACS_DBDD #define WACS_D_LTEE WACS_DDDB #define WACS_D_BTEE WACS_DDBD #define WACS_D_TTEE WACS_BDDD #define WACS_D_HLINE WACS_BDBD #define WACS_D_VLINE WACS_DBDB #define WACS_D_PLUS WACS_DDDD /* thick lines */ #define WACS_BTTB NCURSES_WACS('L') #define WACS_TTBB NCURSES_WACS('M') #define WACS_BBTT NCURSES_WACS('K') #define WACS_TBBT NCURSES_WACS('J') #define WACS_TBTT NCURSES_WACS('U') #define WACS_TTTB NCURSES_WACS('T') #define WACS_TTBT NCURSES_WACS('V') #define WACS_BTTT NCURSES_WACS('W') #define WACS_BTBT NCURSES_WACS('Q') #define WACS_TBTB NCURSES_WACS('X') #define WACS_TTTT NCURSES_WACS('N') #define WACS_T_ULCORNER WACS_BTTB #define WACS_T_LLCORNER WACS_TTBB #define WACS_T_URCORNER WACS_BBTT #define WACS_T_LRCORNER WACS_TBBT #define WACS_T_RTEE WACS_TBTT #define WACS_T_LTEE WACS_TTTB #define WACS_T_BTEE WACS_TTBT #define WACS_T_TTEE WACS_BTTT #define WACS_T_HLINE WACS_BTBT #define WACS_T_VLINE WACS_TBTB #define WACS_T_PLUS WACS_TTTT /* * Function prototypes for wide-character operations. * * "generated" comments should include ":WIDEC" to make the corresponding * functions ifdef'd in lib_gen.c * * "implemented" comments do not need this marker. */ extern NCURSES_EXPORT(int) add_wch (const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) add_wchnstr (const cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) add_wchstr (const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) addnwstr (const wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) addwstr (const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) bkgrnd (const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(void) bkgrndset (const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) border_set (const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*); /* generated:WIDEC */ extern NCURSES_EXPORT(int) box_set (WINDOW *, const cchar_t *, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) echo_wchar (const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) erasewchar (wchar_t*); /* implemented */ extern NCURSES_EXPORT(int) get_wch (wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) get_wstr (wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) getbkgrnd (cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) getcchar (const cchar_t *, wchar_t*, attr_t*, NCURSES_PAIRS_T*, void*); /* implemented */ extern NCURSES_EXPORT(int) getn_wstr (wint_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) hline_set (const cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) in_wch (cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) in_wchnstr (cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) in_wchstr (cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) innwstr (wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) ins_nwstr (const wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) ins_wch (const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) ins_wstr (const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) inwstr (wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(NCURSES_CONST char*) key_name (wchar_t); /* implemented */ extern NCURSES_EXPORT(int) killwchar (wchar_t *); /* implemented */ extern NCURSES_EXPORT(int) mvadd_wch (int, int, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvadd_wchnstr (int, int, const cchar_t *, int);/* generated:WIDEC */ extern NCURSES_EXPORT(int) mvadd_wchstr (int, int, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvaddnwstr (int, int, const wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvaddwstr (int, int, const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvget_wch (int, int, wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvget_wstr (int, int, wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvgetn_wstr (int, int, wint_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvhline_set (int, int, const cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvin_wch (int, int, cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvin_wchnstr (int, int, cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvin_wchstr (int, int, cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvinnwstr (int, int, wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvins_nwstr (int, int, const wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvins_wch (int, int, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvins_wstr (int, int, const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvinwstr (int, int, wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvvline_set (int, int, const cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwadd_wch (WINDOW *, int, int, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwadd_wchnstr (WINDOW *, int, int, const cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwadd_wchstr (WINDOW *, int, int, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwaddnwstr (WINDOW *, int, int, const wchar_t *, int);/* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwaddwstr (WINDOW *, int, int, const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwget_wch (WINDOW *, int, int, wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwget_wstr (WINDOW *, int, int, wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwgetn_wstr (WINDOW *, int, int, wint_t *, int);/* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwhline_set (WINDOW *, int, int, const cchar_t *, int);/* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwin_wch (WINDOW *, int, int, cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwin_wchnstr (WINDOW *, int,int, cchar_t *,int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwin_wchstr (WINDOW *, int, int, cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwinnwstr (WINDOW *, int, int, wchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwins_nwstr (WINDOW *, int,int, const wchar_t *,int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwins_wch (WINDOW *, int, int, const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwins_wstr (WINDOW *, int, int, const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwinwstr (WINDOW *, int, int, wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) mvwvline_set (WINDOW *, int,int, const cchar_t *,int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) pecho_wchar (WINDOW *, const cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) setcchar (cchar_t *, const wchar_t *, const attr_t, NCURSES_PAIRS_T, const void *); /* implemented */ extern NCURSES_EXPORT(int) slk_wset (int, const wchar_t *, int); /* implemented */ extern NCURSES_EXPORT(attr_t) term_attrs (void); /* implemented */ extern NCURSES_EXPORT(int) unget_wch (const wchar_t); /* implemented */ extern NCURSES_EXPORT(int) vid_attr (attr_t, NCURSES_PAIRS_T, void *); /* implemented */ extern NCURSES_EXPORT(int) vid_puts (attr_t, NCURSES_PAIRS_T, void *, NCURSES_OUTC); /* implemented */ extern NCURSES_EXPORT(int) vline_set (const cchar_t *, int); /* generated:WIDEC */ extern NCURSES_EXPORT(int) wadd_wch (WINDOW *,const cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) wadd_wchnstr (WINDOW *,const cchar_t *,int); /* implemented */ extern NCURSES_EXPORT(int) wadd_wchstr (WINDOW *,const cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) waddnwstr (WINDOW *,const wchar_t *,int); /* implemented */ extern NCURSES_EXPORT(int) waddwstr (WINDOW *,const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) wbkgrnd (WINDOW *,const cchar_t *); /* implemented */ extern NCURSES_EXPORT(void) wbkgrndset (WINDOW *,const cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) wborder_set (WINDOW *,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*,const cchar_t*); /* implemented */ extern NCURSES_EXPORT(int) wecho_wchar (WINDOW *, const cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) wget_wch (WINDOW *, wint_t *); /* implemented */ extern NCURSES_EXPORT(int) wget_wstr (WINDOW *, wint_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) wgetbkgrnd (WINDOW *, cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) wgetn_wstr (WINDOW *, wint_t *, int); /* implemented */ extern NCURSES_EXPORT(int) whline_set (WINDOW *, const cchar_t *, int); /* implemented */ extern NCURSES_EXPORT(int) win_wch (WINDOW *, cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) win_wchnstr (WINDOW *, cchar_t *, int); /* implemented */ extern NCURSES_EXPORT(int) win_wchstr (WINDOW *, cchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) winnwstr (WINDOW *, wchar_t *, int); /* implemented */ extern NCURSES_EXPORT(int) wins_nwstr (WINDOW *, const wchar_t *, int); /* implemented */ extern NCURSES_EXPORT(int) wins_wch (WINDOW *, const cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) wins_wstr (WINDOW *, const wchar_t *); /* generated:WIDEC */ extern NCURSES_EXPORT(int) winwstr (WINDOW *, wchar_t *); /* implemented */ extern NCURSES_EXPORT(wchar_t*) wunctrl (cchar_t *); /* implemented */ extern NCURSES_EXPORT(int) wvline_set (WINDOW *, const cchar_t *, int); /* implemented */ #if NCURSES_SP_FUNCS extern NCURSES_EXPORT(attr_t) NCURSES_SP_NAME(term_attrs) (SCREEN*); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(unget_wch) (SCREEN*, const wchar_t); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(wchar_t*) NCURSES_SP_NAME(wunctrl) (SCREEN*, cchar_t *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vid_attr) (SCREEN*, attr_t, NCURSES_PAIRS_T, void *); /* implemented:SP_FUNC */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(vid_puts) (SCREEN*, attr_t, NCURSES_PAIRS_T, void *, NCURSES_SP_OUTC); /* implemented:SP_FUNC */ #endif #ifndef NCURSES_NOMACROS /* * XSI curses macros for XPG4 conformance. */ #define add_wch(c) wadd_wch(stdscr,(c)) #define add_wchnstr(str,n) wadd_wchnstr(stdscr,(str),(n)) #define add_wchstr(str) wadd_wchstr(stdscr,(str)) #define addnwstr(wstr,n) waddnwstr(stdscr,(wstr),(n)) #define addwstr(wstr) waddwstr(stdscr,(wstr)) #define bkgrnd(c) wbkgrnd(stdscr,(c)) #define bkgrndset(c) wbkgrndset(stdscr,(c)) #define border_set(l,r,t,b,tl,tr,bl,br) wborder_set(stdscr,(l),(r),(t),(b),tl,tr,bl,br) #define box_set(w,v,h) wborder_set((w),(v),(v),(h),(h),0,0,0,0) #define echo_wchar(c) wecho_wchar(stdscr,(c)) #define get_wch(c) wget_wch(stdscr,(c)) #define get_wstr(t) wget_wstr(stdscr,(t)) #define getbkgrnd(wch) wgetbkgrnd(stdscr,(wch)) #define getn_wstr(t,n) wgetn_wstr(stdscr,(t),(n)) #define hline_set(c,n) whline_set(stdscr,(c),(n)) #define in_wch(c) win_wch(stdscr,(c)) #define in_wchnstr(c,n) win_wchnstr(stdscr,(c),(n)) #define in_wchstr(c) win_wchstr(stdscr,(c)) #define innwstr(c,n) winnwstr(stdscr,(c),(n)) #define ins_nwstr(t,n) wins_nwstr(stdscr,(t),(n)) #define ins_wch(c) wins_wch(stdscr,(c)) #define ins_wstr(t) wins_wstr(stdscr,(t)) #define inwstr(c) winwstr(stdscr,(c)) #define vline_set(c,n) wvline_set(stdscr,(c),(n)) #define wadd_wchstr(win,str) wadd_wchnstr((win),(str),-1) #define waddwstr(win,wstr) waddnwstr((win),(wstr),-1) #define wget_wstr(w,t) wgetn_wstr((w),(t),-1) #define win_wchstr(w,c) win_wchnstr((w),(c),-1) #define wins_wstr(w,t) wins_nwstr((w),(t),-1) #if !NCURSES_OPAQUE #define wgetbkgrnd(win,wch) (NCURSES_OK_ADDR(wch) ? ((win) ? (*(wch) = (win)->_bkgrnd) : *(wch), OK) : ERR) #endif #define mvadd_wch(y,x,c) mvwadd_wch(stdscr,(y),(x),(c)) #define mvadd_wchnstr(y,x,s,n) mvwadd_wchnstr(stdscr,(y),(x),(s),(n)) #define mvadd_wchstr(y,x,s) mvwadd_wchstr(stdscr,(y),(x),(s)) #define mvaddnwstr(y,x,wstr,n) mvwaddnwstr(stdscr,(y),(x),(wstr),(n)) #define mvaddwstr(y,x,wstr) mvwaddwstr(stdscr,(y),(x),(wstr)) #define mvget_wch(y,x,c) mvwget_wch(stdscr,(y),(x),(c)) #define mvget_wstr(y,x,t) mvwget_wstr(stdscr,(y),(x),(t)) #define mvgetn_wstr(y,x,t,n) mvwgetn_wstr(stdscr,(y),(x),(t),(n)) #define mvhline_set(y,x,c,n) mvwhline_set(stdscr,(y),(x),(c),(n)) #define mvin_wch(y,x,c) mvwin_wch(stdscr,(y),(x),(c)) #define mvin_wchnstr(y,x,c,n) mvwin_wchnstr(stdscr,(y),(x),(c),(n)) #define mvin_wchstr(y,x,c) mvwin_wchstr(stdscr,(y),(x),(c)) #define mvinnwstr(y,x,c,n) mvwinnwstr(stdscr,(y),(x),(c),(n)) #define mvins_nwstr(y,x,t,n) mvwins_nwstr(stdscr,(y),(x),(t),(n)) #define mvins_wch(y,x,c) mvwins_wch(stdscr,(y),(x),(c)) #define mvins_wstr(y,x,t) mvwins_wstr(stdscr,(y),(x),(t)) #define mvinwstr(y,x,c) mvwinwstr(stdscr,(y),(x),(c)) #define mvvline_set(y,x,c,n) mvwvline_set(stdscr,(y),(x),(c),(n)) #define mvwadd_wch(win,y,x,c) (wmove(win,(y),(x)) == ERR ? ERR : wadd_wch((win),(c))) #define mvwadd_wchnstr(win,y,x,s,n) (wmove(win,(y),(x)) == ERR ? ERR : wadd_wchnstr((win),(s),(n))) #define mvwadd_wchstr(win,y,x,s) (wmove(win,(y),(x)) == ERR ? ERR : wadd_wchstr((win),(s))) #define mvwaddnwstr(win,y,x,wstr,n) (wmove(win,(y),(x)) == ERR ? ERR : waddnwstr((win),(wstr),(n))) #define mvwaddwstr(win,y,x,wstr) (wmove(win,(y),(x)) == ERR ? ERR : waddwstr((win),(wstr))) #define mvwget_wch(win,y,x,c) (wmove(win,(y),(x)) == ERR ? ERR : wget_wch((win),(c))) #define mvwget_wstr(win,y,x,t) (wmove(win,(y),(x)) == ERR ? ERR : wget_wstr((win),(t))) #define mvwgetn_wstr(win,y,x,t,n) (wmove(win,(y),(x)) == ERR ? ERR : wgetn_wstr((win),(t),(n))) #define mvwhline_set(win,y,x,c,n) (wmove(win,(y),(x)) == ERR ? ERR : whline_set((win),(c),(n))) #define mvwin_wch(win,y,x,c) (wmove(win,(y),(x)) == ERR ? ERR : win_wch((win),(c))) #define mvwin_wchnstr(win,y,x,c,n) (wmove(win,(y),(x)) == ERR ? ERR : win_wchnstr((win),(c),(n))) #define mvwin_wchstr(win,y,x,c) (wmove(win,(y),(x)) == ERR ? ERR : win_wchstr((win),(c))) #define mvwinnwstr(win,y,x,c,n) (wmove(win,(y),(x)) == ERR ? ERR : winnwstr((win),(c),(n))) #define mvwins_nwstr(win,y,x,t,n) (wmove(win,(y),(x)) == ERR ? ERR : wins_nwstr((win),(t),(n))) #define mvwins_wch(win,y,x,c) (wmove(win,(y),(x)) == ERR ? ERR : wins_wch((win),(c))) #define mvwins_wstr(win,y,x,t) (wmove(win,(y),(x)) == ERR ? ERR : wins_wstr((win),(t))) #define mvwinwstr(win,y,x,c) (wmove(win,(y),(x)) == ERR ? ERR : winwstr((win),(c))) #define mvwvline_set(win,y,x,c,n) (wmove(win,(y),(x)) == ERR ? ERR : wvline_set((win),(c),(n))) #endif /* NCURSES_NOMACROS */ #if defined(TRACE) || defined(NCURSES_TEST) extern NCURSES_EXPORT(const char *) _nc_viswbuf(const wchar_t *); extern NCURSES_EXPORT(const char *) _nc_viswibuf(const wint_t *); #endif #endif /* NCURSES_WIDECHAR */ /* $Id: curses.tail,v 1.23 2016/02/13 16:37:45 tom Exp $ */ /* * vile:cmode: * This file is part of ncurses, designed to be appended after curses.h.in * (see that file for the relevant copyright). */ /* mouse interface */ #if NCURSES_MOUSE_VERSION > 1 #define NCURSES_MOUSE_MASK(b,m) ((m) << (((b) - 1) * 5)) #else #define NCURSES_MOUSE_MASK(b,m) ((m) << (((b) - 1) * 6)) #endif #define NCURSES_BUTTON_RELEASED 001L #define NCURSES_BUTTON_PRESSED 002L #define NCURSES_BUTTON_CLICKED 004L #define NCURSES_DOUBLE_CLICKED 010L #define NCURSES_TRIPLE_CLICKED 020L #define NCURSES_RESERVED_EVENT 040L /* event masks */ #define BUTTON1_RELEASED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_RELEASED) #define BUTTON1_PRESSED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_PRESSED) #define BUTTON1_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_BUTTON_CLICKED) #define BUTTON1_DOUBLE_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_DOUBLE_CLICKED) #define BUTTON1_TRIPLE_CLICKED NCURSES_MOUSE_MASK(1, NCURSES_TRIPLE_CLICKED) #define BUTTON2_RELEASED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_RELEASED) #define BUTTON2_PRESSED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_PRESSED) #define BUTTON2_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_BUTTON_CLICKED) #define BUTTON2_DOUBLE_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_DOUBLE_CLICKED) #define BUTTON2_TRIPLE_CLICKED NCURSES_MOUSE_MASK(2, NCURSES_TRIPLE_CLICKED) #define BUTTON3_RELEASED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_RELEASED) #define BUTTON3_PRESSED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_PRESSED) #define BUTTON3_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_BUTTON_CLICKED) #define BUTTON3_DOUBLE_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_DOUBLE_CLICKED) #define BUTTON3_TRIPLE_CLICKED NCURSES_MOUSE_MASK(3, NCURSES_TRIPLE_CLICKED) #define BUTTON4_RELEASED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_RELEASED) #define BUTTON4_PRESSED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_PRESSED) #define BUTTON4_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_BUTTON_CLICKED) #define BUTTON4_DOUBLE_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_DOUBLE_CLICKED) #define BUTTON4_TRIPLE_CLICKED NCURSES_MOUSE_MASK(4, NCURSES_TRIPLE_CLICKED) /* * In 32 bits the version-1 scheme does not provide enough space for a 5th * button, unless we choose to change the ABI by omitting the reserved-events. */ #if NCURSES_MOUSE_VERSION > 1 #define BUTTON5_RELEASED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_RELEASED) #define BUTTON5_PRESSED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_PRESSED) #define BUTTON5_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_BUTTON_CLICKED) #define BUTTON5_DOUBLE_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_DOUBLE_CLICKED) #define BUTTON5_TRIPLE_CLICKED NCURSES_MOUSE_MASK(5, NCURSES_TRIPLE_CLICKED) #define BUTTON_CTRL NCURSES_MOUSE_MASK(6, 0001L) #define BUTTON_SHIFT NCURSES_MOUSE_MASK(6, 0002L) #define BUTTON_ALT NCURSES_MOUSE_MASK(6, 0004L) #define REPORT_MOUSE_POSITION NCURSES_MOUSE_MASK(6, 0010L) #else #define BUTTON1_RESERVED_EVENT NCURSES_MOUSE_MASK(1, NCURSES_RESERVED_EVENT) #define BUTTON2_RESERVED_EVENT NCURSES_MOUSE_MASK(2, NCURSES_RESERVED_EVENT) #define BUTTON3_RESERVED_EVENT NCURSES_MOUSE_MASK(3, NCURSES_RESERVED_EVENT) #define BUTTON4_RESERVED_EVENT NCURSES_MOUSE_MASK(4, NCURSES_RESERVED_EVENT) #define BUTTON_CTRL NCURSES_MOUSE_MASK(5, 0001L) #define BUTTON_SHIFT NCURSES_MOUSE_MASK(5, 0002L) #define BUTTON_ALT NCURSES_MOUSE_MASK(5, 0004L) #define REPORT_MOUSE_POSITION NCURSES_MOUSE_MASK(5, 0010L) #endif #define ALL_MOUSE_EVENTS (REPORT_MOUSE_POSITION - 1) /* macros to extract single event-bits from masks */ #define BUTTON_RELEASE(e, x) ((e) & NCURSES_MOUSE_MASK(x, 001)) #define BUTTON_PRESS(e, x) ((e) & NCURSES_MOUSE_MASK(x, 002)) #define BUTTON_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 004)) #define BUTTON_DOUBLE_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 010)) #define BUTTON_TRIPLE_CLICK(e, x) ((e) & NCURSES_MOUSE_MASK(x, 020)) #define BUTTON_RESERVED_EVENT(e, x) ((e) & NCURSES_MOUSE_MASK(x, 040)) typedef struct { short id; /* ID to distinguish multiple devices */ int x, y, z; /* event coordinates (character-cell) */ mmask_t bstate; /* button state bits */ } MEVENT; extern NCURSES_EXPORT(bool) has_mouse(void); extern NCURSES_EXPORT(int) getmouse (MEVENT *); extern NCURSES_EXPORT(int) ungetmouse (MEVENT *); extern NCURSES_EXPORT(mmask_t) mousemask (mmask_t, mmask_t *); extern NCURSES_EXPORT(bool) wenclose (const WINDOW *, int, int); extern NCURSES_EXPORT(int) mouseinterval (int); extern NCURSES_EXPORT(bool) wmouse_trafo (const WINDOW*, int*, int*, bool); extern NCURSES_EXPORT(bool) mouse_trafo (int*, int*, bool); /* generated */ #if NCURSES_SP_FUNCS extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(has_mouse) (SCREEN*); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(getmouse) (SCREEN*, MEVENT *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(ungetmouse) (SCREEN*,MEVENT *); extern NCURSES_EXPORT(mmask_t) NCURSES_SP_NAME(mousemask) (SCREEN*, mmask_t, mmask_t *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mouseinterval) (SCREEN*, int); #endif #ifndef NCURSES_NOMACROS #define mouse_trafo(y,x,to_screen) wmouse_trafo(stdscr,y,x,to_screen) #endif /* other non-XSI functions */ extern NCURSES_EXPORT(int) mcprint (char *, int); /* direct data to printer */ extern NCURSES_EXPORT(int) has_key (int); /* do we have given key? */ #if NCURSES_SP_FUNCS extern NCURSES_EXPORT(int) NCURSES_SP_NAME(has_key) (SCREEN*, int); /* do we have given key? */ extern NCURSES_EXPORT(int) NCURSES_SP_NAME(mcprint) (SCREEN*, char *, int); /* direct data to printer */ #endif /* Debugging : use with libncurses_g.a */ extern NCURSES_EXPORT(void) _tracef (const char *, ...) GCC_PRINTFLIKE(1,2); extern NCURSES_EXPORT(char *) _traceattr (attr_t); extern NCURSES_EXPORT(char *) _traceattr2 (int, chtype); extern NCURSES_EXPORT(char *) _tracechar (int); extern NCURSES_EXPORT(char *) _tracechtype (chtype); extern NCURSES_EXPORT(char *) _tracechtype2 (int, chtype); #if NCURSES_WIDECHAR #define _tracech_t _tracecchar_t extern NCURSES_EXPORT(char *) _tracecchar_t (const cchar_t *); #define _tracech_t2 _tracecchar_t2 extern NCURSES_EXPORT(char *) _tracecchar_t2 (int, const cchar_t *); #else #define _tracech_t _tracechtype #define _tracech_t2 _tracechtype2 #endif extern NCURSES_EXPORT(void) trace (const unsigned int); /* trace masks */ #define TRACE_DISABLE 0x0000 /* turn off tracing */ #define TRACE_TIMES 0x0001 /* trace user and system times of updates */ #define TRACE_TPUTS 0x0002 /* trace tputs calls */ #define TRACE_UPDATE 0x0004 /* trace update actions, old & new screens */ #define TRACE_MOVE 0x0008 /* trace cursor moves and scrolls */ #define TRACE_CHARPUT 0x0010 /* trace all character outputs */ #define TRACE_ORDINARY 0x001F /* trace all update actions */ #define TRACE_CALLS 0x0020 /* trace all curses calls */ #define TRACE_VIRTPUT 0x0040 /* trace virtual character puts */ #define TRACE_IEVENT 0x0080 /* trace low-level input processing */ #define TRACE_BITS 0x0100 /* trace state of TTY control bits */ #define TRACE_ICALLS 0x0200 /* trace internal/nested calls */ #define TRACE_CCALLS 0x0400 /* trace per-character calls */ #define TRACE_DATABASE 0x0800 /* trace read/write of terminfo/termcap data */ #define TRACE_ATTRS 0x1000 /* trace attribute updates */ #define TRACE_SHIFT 13 /* number of bits in the trace masks */ #define TRACE_MAXIMUM ((1 << TRACE_SHIFT) - 1) /* maximum trace level */ #if defined(TRACE) || defined(NCURSES_TEST) extern NCURSES_EXPORT_VAR(int) _nc_optimize_enable; /* enable optimizations */ extern NCURSES_EXPORT(const char *) _nc_visbuf (const char *); #define OPTIMIZE_MVCUR 0x01 /* cursor movement optimization */ #define OPTIMIZE_HASHMAP 0x02 /* diff hashing to detect scrolls */ #define OPTIMIZE_SCROLL 0x04 /* scroll optimization */ #define OPTIMIZE_ALL 0xff /* enable all optimizations (dflt) */ #endif #include #ifdef __cplusplus #ifndef NCURSES_NOMACROS /* these names conflict with STL */ #undef box #undef clear #undef erase #undef move #undef refresh #endif /* NCURSES_NOMACROS */ } #endif #endif /* __NCURSES_H */ evhttp.h000064400000003763151027430560006243 0ustar00/* * Copyright 2000-2007 Niels Provos * Copyright 2007-2012 Niels Provos and Nick Mathewson * * 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. */ #ifndef EVENT1_EVHTTP_H_INCLUDED_ #define EVENT1_EVHTTP_H_INCLUDED_ /** @file evhttp.h An http implementation subsystem for Libevent. The header is deprecated in Libevent 2.0 and later; please use instead. Depending on what functionality you need, you may also want to include more of the other headers. */ #include #include #include #include #endif /* EVENT1_EVHTTP_H_INCLUDED_ */ gconv.h000064400000010472151027430560006040 0ustar00/* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* This header provides no interface for a user to the internals of the gconv implementation in the libc. Therefore there is no use for these definitions beside for writing additional gconv modules. */ #ifndef _GCONV_H #define _GCONV_H 1 #include #include #include #define __need_size_t #define __need_wchar_t #include /* ISO 10646 value used to signal invalid value. */ #define __UNKNOWN_10646_CHAR ((wchar_t) 0xfffd) /* Error codes for gconv functions. */ enum { __GCONV_OK = 0, __GCONV_NOCONV, __GCONV_NODB, __GCONV_NOMEM, __GCONV_EMPTY_INPUT, __GCONV_FULL_OUTPUT, __GCONV_ILLEGAL_INPUT, __GCONV_INCOMPLETE_INPUT, __GCONV_ILLEGAL_DESCRIPTOR, __GCONV_INTERNAL_ERROR }; /* Flags the `__gconv_open' function can set. */ enum { __GCONV_IS_LAST = 0x0001, __GCONV_IGNORE_ERRORS = 0x0002, __GCONV_SWAP = 0x0004, __GCONV_TRANSLIT = 0x0008 }; /* Forward declarations. */ struct __gconv_step; struct __gconv_step_data; struct __gconv_loaded_object; /* Type of a conversion function. */ typedef int (*__gconv_fct) (struct __gconv_step *, struct __gconv_step_data *, const unsigned char **, const unsigned char *, unsigned char **, size_t *, int, int); /* Type of a specialized conversion function for a single byte to INTERNAL. */ typedef wint_t (*__gconv_btowc_fct) (struct __gconv_step *, unsigned char); /* Constructor and destructor for local data for conversion step. */ typedef int (*__gconv_init_fct) (struct __gconv_step *); typedef void (*__gconv_end_fct) (struct __gconv_step *); /* Description of a conversion step. */ struct __gconv_step { struct __gconv_loaded_object *__shlib_handle; const char *__modname; int __counter; char *__from_name; char *__to_name; __gconv_fct __fct; __gconv_btowc_fct __btowc_fct; __gconv_init_fct __init_fct; __gconv_end_fct __end_fct; /* Information about the number of bytes needed or produced in this step. This helps optimizing the buffer sizes. */ int __min_needed_from; int __max_needed_from; int __min_needed_to; int __max_needed_to; /* Flag whether this is a stateful encoding or not. */ int __stateful; void *__data; /* Pointer to step-local data. */ }; /* Additional data for steps in use of conversion descriptor. This is allocated by the `init' function. */ struct __gconv_step_data { unsigned char *__outbuf; /* Output buffer for this step. */ unsigned char *__outbufend; /* Address of first byte after the output buffer. */ /* Is this the last module in the chain. */ int __flags; /* Counter for number of invocations of the module function for this descriptor. */ int __invocation_counter; /* Flag whether this is an internal use of the module (in the mb*towc* and wc*tomb* functions) or regular with iconv(3). */ int __internal_use; __mbstate_t *__statep; __mbstate_t __state; /* This element must not be used directly by any module; always use STATEP! */ }; /* Combine conversion step description with data. */ typedef struct __gconv_info { size_t __nsteps; struct __gconv_step *__steps; __extension__ struct __gconv_step_data __data[0]; } *__gconv_t; /* Transliteration using the locale's data. */ extern int __gconv_transliterate (struct __gconv_step *step, struct __gconv_step_data *step_data, const unsigned char *inbufstart, const unsigned char **inbufp, const unsigned char *inbufend, unsigned char **outbufstart, size_t *irreversible); #endif /* gconv.h */ sgtty.h000064400000002477151027430560006104 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _SGTTY_H #define _SGTTY_H 1 #include #include /* On some systems this type is not defined by ; in that case, the functions are just stubs that return ENOSYS. */ struct sgttyb; __BEGIN_DECLS /* Fill in *PARAMS with terminal parameters associated with FD. */ extern int gtty (int __fd, struct sgttyb *__params) __THROW; /* Set the terminal parameters associated with FD to *PARAMS. */ extern int stty (int __fd, const struct sgttyb *__params) __THROW; __END_DECLS #endif /* sgtty.h */ krb5.h000064400000000622151027430560005563 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* The MIT Kerberos header file krb5.h used to live here. As of the 1.5 release, we're installing multiple Kerberos headers, so they're all moving to a krb5/ subdirectory. This file is present just to keep old software still compiling. Please update your code to use the new path for the header. */ #include idn-free.h000064400000004650151027430560006416 0ustar00/* idn-free.h --- Invoke the free function to release memory Copyright (C) 2004-2016 Simon Josefsson This file is part of GNU Libidn. GNU Libidn is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Libidn is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see . */ #ifndef IDN_FREE_H # define IDN_FREE_H # ifndef IDNAPI # if defined LIBIDN_BUILDING && defined HAVE_VISIBILITY && HAVE_VISIBILITY # define IDNAPI __attribute__((__visibility__("default"))) # elif defined LIBIDN_BUILDING && defined _MSC_VER && ! defined LIBIDN_STATIC # define IDNAPI __declspec(dllexport) # elif defined _MSC_VER && ! defined LIBIDN_STATIC # define IDNAPI __declspec(dllimport) # else # define IDNAPI # endif # endif # ifdef __cplusplus extern "C" { # endif /* I don't recommend using this interface in general. Use `free'. * * I'm told Microsoft Windows may use one set of `malloc' and `free' * in a library, and another incompatible set in a statically compiled * application that link to the library, thus creating problems if the * application would invoke `free' on a pointer pointing to memory * allocated by the library. This motivated adding this function. * * The theory of isolating all memory allocations and de-allocations * within a code package (library) sounds good, to simplify hunting * down memory allocation related problems, but I'm not sure if it is * worth enough to motivate recommending this interface over calling * `free' directly, though. * * See the manual section 'Memory handling under Windows' for more * information. */ extern void IDNAPI idn_free (void *ptr); # ifdef __cplusplus } # endif #endif /* IDN_FREE_H */ cursesm.h000064400000046335151027430560006414 0ustar00// * This makes emacs happy -*-Mode: C++;-*- /**************************************************************************** * Copyright (c) 1998-2012,2014 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1997 * ****************************************************************************/ // $Id: cursesm.h,v 1.30 2014/08/09 22:06:18 Adam.Jiang Exp $ #ifndef NCURSES_CURSESM_H_incl #define NCURSES_CURSESM_H_incl 1 #include extern "C" { # include } // // ------------------------------------------------------------------------- // This wraps the ITEM type of // ------------------------------------------------------------------------- // class NCURSES_IMPEXP NCursesMenuItem { friend class NCursesMenu; protected: ITEM *item; inline void OnError (int err) const THROW2(NCursesException const, NCursesMenuException) { if (err != E_OK) THROW(new NCursesMenuException (err)); } public: NCursesMenuItem (const char* p_name = NULL, const char* p_descript = NULL) : item(0) { item = p_name ? ::new_item (p_name, p_descript) : STATIC_CAST(ITEM*)(0); if (p_name && !item) OnError (E_SYSTEM_ERROR); } // Create an item. If you pass both parameters as NULL, a delimiting // item is constructed which can be used to terminate a list of // NCursesMenu objects. NCursesMenuItem& operator=(const NCursesMenuItem& rhs) { if (this != &rhs) { *this = rhs; } return *this; } NCursesMenuItem(const NCursesMenuItem& rhs) : item(0) { (void) rhs; } virtual ~NCursesMenuItem (); // Release the items memory inline const char* name () const { return ::item_name (item); } // Name of the item inline const char* description () const { return ::item_description (item); } // Description of the item inline int (index) (void) const { return ::item_index (item); } // Index of the item in an item array (or -1) inline void options_on (Item_Options opts) { OnError (::item_opts_on (item, opts)); } // Switch on the items options inline void options_off (Item_Options opts) { OnError (::item_opts_off (item, opts)); } // Switch off the item's option inline Item_Options options () const { return ::item_opts (item); } // Retrieve the items options inline void set_options (Item_Options opts) { OnError (::set_item_opts (item, opts)); } // Set the items options inline void set_value (bool f) { OnError (::set_item_value (item,f)); } // Set/Reset the items selection state inline bool value () const { return ::item_value (item); } // Retrieve the items selection state inline bool visible () const { return ::item_visible (item); } // Retrieve visibility of the item virtual bool action(); // Perform an action associated with this item; you may use this in an // user supplied driver for a menu; you may derive from this class and // overload action() to supply items with different actions. // If an action returns true, the menu will be exited. The default action // is to do nothing. }; // Prototype for an items callback function. typedef bool ITEMCALLBACK(NCursesMenuItem&); // If you don't like to create a child class for individual items to // overload action(), you may use this class and provide a callback // function pointer for items. class NCURSES_IMPEXP NCursesMenuCallbackItem : public NCursesMenuItem { private: ITEMCALLBACK* p_fct; public: NCursesMenuCallbackItem(ITEMCALLBACK* fct = NULL, const char* p_name = NULL, const char* p_descript = NULL ) : NCursesMenuItem (p_name, p_descript), p_fct (fct) { } NCursesMenuCallbackItem& operator=(const NCursesMenuCallbackItem& rhs) { if (this != &rhs) { *this = rhs; } return *this; } NCursesMenuCallbackItem(const NCursesMenuCallbackItem& rhs) : NCursesMenuItem(rhs), p_fct(0) { } virtual ~NCursesMenuCallbackItem(); bool action(); }; // This are the built-in hook functions in this C++ binding. In C++ we use // virtual member functions (see below On_..._Init and On_..._Termination) // to provide this functionality in an object oriented manner. extern "C" { void _nc_xx_mnu_init(MENU *); void _nc_xx_mnu_term(MENU *); void _nc_xx_itm_init(MENU *); void _nc_xx_itm_term(MENU *); } // // ------------------------------------------------------------------------- // This wraps the MENU type of // ------------------------------------------------------------------------- // class NCURSES_IMPEXP NCursesMenu : public NCursesPanel { protected: MENU *menu; private: NCursesWindow* sub; // the subwindow object bool b_sub_owner; // is this our own subwindow? bool b_framed; // has the menu a border? bool b_autoDelete; // Delete items when deleting menu? NCursesMenuItem** my_items; // The array of items for this menu // This structure is used for the menu's user data field to link the // MENU* to the C++ object and to provide extra space for a user pointer. typedef struct { void* m_user; // the pointer for the user's data const NCursesMenu* m_back; // backward pointer to C++ object const MENU* m_owner; } UserHook; // Get the backward pointer to the C++ object from a MENU static inline NCursesMenu* getHook(const MENU *m) { UserHook* hook = STATIC_CAST(UserHook*)(::menu_userptr(m)); assert(hook != 0 && hook->m_owner==m); return const_cast(hook->m_back); } friend void _nc_xx_mnu_init(MENU *); friend void _nc_xx_mnu_term(MENU *); friend void _nc_xx_itm_init(MENU *); friend void _nc_xx_itm_term(MENU *); // Calculate ITEM* array for the menu ITEM** mapItems(NCursesMenuItem* nitems[]); protected: // internal routines inline void set_user(void *user) { UserHook* uptr = STATIC_CAST(UserHook*)(::menu_userptr (menu)); assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==menu); uptr->m_user = user; } inline void *get_user() { UserHook* uptr = STATIC_CAST(UserHook*)(::menu_userptr (menu)); assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==menu); return uptr->m_user; } void InitMenu (NCursesMenuItem* menu[], bool with_frame, bool autoDeleteItems); inline void OnError (int err) const THROW2(NCursesException const, NCursesMenuException) { if (err != E_OK) THROW(new NCursesMenuException (this, err)); } // this wraps the menu_driver call. virtual int driver (int c) ; // 'Internal' constructor to create a menu without association to // an array of items. NCursesMenu( int nlines, int ncols, int begin_y = 0, int begin_x = 0) : NCursesPanel(nlines,ncols,begin_y,begin_x), menu (STATIC_CAST(MENU*)(0)), sub(0), b_sub_owner(0), b_framed(0), b_autoDelete(0), my_items(0) { } public: // Make a full window size menu NCursesMenu (NCursesMenuItem* Items[], bool with_frame=FALSE, // Reserve space for a frame? bool autoDelete_Items=FALSE) // Autocleanup of Items? : NCursesPanel(), menu(0), sub(0), b_sub_owner(0), b_framed(0), b_autoDelete(0), my_items(0) { InitMenu(Items, with_frame, autoDelete_Items); } // Make a menu with a window of this size. NCursesMenu (NCursesMenuItem* Items[], int nlines, int ncols, int begin_y = 0, int begin_x = 0, bool with_frame=FALSE, // Reserve space for a frame? bool autoDelete_Items=FALSE) // Autocleanup of Items? : NCursesPanel(nlines, ncols, begin_y, begin_x), menu(0), sub(0), b_sub_owner(0), b_framed(0), b_autoDelete(0), my_items(0) { InitMenu(Items, with_frame, autoDelete_Items); } NCursesMenu& operator=(const NCursesMenu& rhs) { if (this != &rhs) { *this = rhs; NCursesPanel::operator=(rhs); } return *this; } NCursesMenu(const NCursesMenu& rhs) : NCursesPanel(rhs), menu(rhs.menu), sub(rhs.sub), b_sub_owner(rhs.b_sub_owner), b_framed(rhs.b_framed), b_autoDelete(rhs.b_autoDelete), my_items(rhs.my_items) { } virtual ~NCursesMenu (); // Retrieve the menus subwindow inline NCursesWindow& subWindow() const { assert(sub!=NULL); return *sub; } // Set the menus subwindow void setSubWindow(NCursesWindow& sub); // Set these items for the menu inline void setItems(NCursesMenuItem* Items[]) { OnError(::set_menu_items(menu,mapItems(Items))); } // Remove the menu from the screen inline void unpost (void) { OnError (::unpost_menu (menu)); } // Post the menu to the screen if flag is true, unpost it otherwise inline void post(bool flag = TRUE) { flag ? OnError (::post_menu(menu)) : OnError (::unpost_menu (menu)); } // Get the numer of rows and columns for this menu inline void scale (int& mrows, int& mcols) const { OnError (::scale_menu (menu, &mrows, &mcols)); } // Set the format of this menu inline void set_format(int mrows, int mcols) { OnError (::set_menu_format(menu, mrows, mcols)); } // Get the format of this menu inline void menu_format(int& rows,int& ncols) { ::menu_format(menu,&rows,&ncols); } // Items of the menu inline NCursesMenuItem* items() const { return *my_items; } // Get the number of items in this menu inline int count() const { return ::item_count(menu); } // Get the current item (i.e. the one the cursor is located) inline NCursesMenuItem* current_item() const { return my_items[::item_index(::current_item(menu))]; } // Get the marker string inline const char* mark() const { return ::menu_mark(menu); } // Set the marker string inline void set_mark(const char *marker) { OnError (::set_menu_mark (menu, marker)); } // Get the name of the request code c inline static const char* request_name(int c) { return ::menu_request_name(c); } // Get the current pattern inline char* pattern() const { return ::menu_pattern(menu); } // true if there is a pattern match, false otherwise. bool set_pattern (const char *pat); // set the default attributes for the menu // i.e. set fore, back and grey attribute virtual void setDefaultAttributes(); // Get the menus background attributes inline chtype back() const { return ::menu_back(menu); } // Get the menus foreground attributes inline chtype fore() const { return ::menu_fore(menu); } // Get the menus grey attributes (used for unselectable items) inline chtype grey() const { return ::menu_grey(menu); } // Set the menus background attributes inline chtype set_background(chtype a) { return ::set_menu_back(menu,a); } // Set the menus foreground attributes inline chtype set_foreground(chtype a) { return ::set_menu_fore(menu,a); } // Set the menus grey attributes (used for unselectable items) inline chtype set_grey(chtype a) { return ::set_menu_grey(menu,a); } inline void options_on (Menu_Options opts) { OnError (::menu_opts_on (menu,opts)); } inline void options_off(Menu_Options opts) { OnError (::menu_opts_off(menu,opts)); } inline Menu_Options options() const { return ::menu_opts(menu); } inline void set_options (Menu_Options opts) { OnError (::set_menu_opts (menu,opts)); } inline int pad() const { return ::menu_pad(menu); } inline void set_pad (int padch) { OnError (::set_menu_pad (menu, padch)); } // Position the cursor to the current item inline void position_cursor () const { OnError (::pos_menu_cursor (menu)); } // Set the current item inline void set_current(NCursesMenuItem& I) { OnError (::set_current_item(menu, I.item)); } // Get the current top row of the menu inline int top_row (void) const { return ::top_row (menu); } // Set the current top row of the menu inline void set_top_row (int row) { OnError (::set_top_row (menu, row)); } // spacing control // Set the spacing for the menu inline void setSpacing(int spc_description, int spc_rows, int spc_columns) { OnError(::set_menu_spacing(menu, spc_description, spc_rows, spc_columns)); } // Get the spacing info for the menu inline void Spacing(int& spc_description, int& spc_rows, int& spc_columns) const { OnError(::menu_spacing(menu, &spc_description, &spc_rows, &spc_columns)); } // Decorations inline void frame(const char *title=NULL, const char* btitle=NULL) { if (b_framed) NCursesPanel::frame(title,btitle); else OnError(E_SYSTEM_ERROR); } inline void boldframe(const char *title=NULL, const char* btitle=NULL) { if (b_framed) NCursesPanel::boldframe(title,btitle); else OnError(E_SYSTEM_ERROR); } inline void label(const char *topLabel, const char *bottomLabel) { if (b_framed) NCursesPanel::label(topLabel,bottomLabel); else OnError(E_SYSTEM_ERROR); } // ----- // Hooks // ----- // Called after the menu gets repositioned in its window. // This is especially true if the menu is posted. virtual void On_Menu_Init(); // Called before the menu gets repositioned in its window. // This is especially true if the menu is unposted. virtual void On_Menu_Termination(); // Called after the item became the current item virtual void On_Item_Init(NCursesMenuItem& item); // Called before this item is left as current item. virtual void On_Item_Termination(NCursesMenuItem& item); // Provide a default key virtualization. Translate the keyboard // code c into a menu request code. // The default implementation provides a hopefully straightforward // mapping for the most common keystrokes and menu requests. virtual int virtualize(int c); // Operators inline NCursesMenuItem* operator[](int i) const { if ( (i < 0) || (i >= ::item_count (menu)) ) OnError (E_BAD_ARGUMENT); return (my_items[i]); } // Perform the menu's operation // Return the item where you left the selection mark for a single // selection menu, or NULL for a multivalued menu. virtual NCursesMenuItem* operator()(void); // -------------------- // Exception handlers // Called by operator() // -------------------- // Called if the request is denied virtual void On_Request_Denied(int c) const; // Called if the item is not selectable virtual void On_Not_Selectable(int c) const; // Called if pattern doesn't match virtual void On_No_Match(int c) const; // Called if the command is unknown virtual void On_Unknown_Command(int c) const; }; // // ------------------------------------------------------------------------- // This is the typical C++ typesafe way to allow to attach // user data to an item of a menu. Its assumed that the user // data belongs to some class T. Use T as template argument // to create a UserItem. // ------------------------------------------------------------------------- // template class NCURSES_IMPEXP NCursesUserItem : public NCursesMenuItem { public: NCursesUserItem (const char* p_name, const char* p_descript = NULL, const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesMenuItem (p_name, p_descript) { if (item) OnError (::set_item_userptr (item, const_cast(reinterpret_cast(p_UserData)))); } virtual ~NCursesUserItem() {} inline const T* UserData (void) const { return reinterpret_cast(::item_userptr (item)); }; inline virtual void setUserData(const T* p_UserData) { if (item) OnError (::set_item_userptr (item, const_cast(reinterpret_cast(p_UserData)))); } }; // // ------------------------------------------------------------------------- // The same mechanism is used to attach user data to a menu // ------------------------------------------------------------------------- // template class NCURSES_IMPEXP NCursesUserMenu : public NCursesMenu { protected: NCursesUserMenu( int nlines, int ncols, int begin_y = 0, int begin_x = 0, const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesMenu(nlines,ncols,begin_y,begin_x) { if (menu) set_user (const_cast(reinterpret_cast(p_UserData))); } public: NCursesUserMenu (NCursesMenuItem* Items[], const T* p_UserData = STATIC_CAST(T*)(0), bool with_frame=FALSE, bool autoDelete_Items=FALSE) : NCursesMenu (Items, with_frame, autoDelete_Items) { if (menu) set_user (const_cast(reinterpret_cast(p_UserData))); }; NCursesUserMenu (NCursesMenuItem* Items[], int nlines, int ncols, int begin_y = 0, int begin_x = 0, const T* p_UserData = STATIC_CAST(T*)(0), bool with_frame=FALSE) : NCursesMenu (Items, nlines, ncols, begin_y, begin_x, with_frame) { if (menu) set_user (const_cast(reinterpret_cast(p_UserData))); }; virtual ~NCursesUserMenu() { }; inline T* UserData (void) { return reinterpret_cast(get_user ()); }; inline virtual void setUserData (const T* p_UserData) { if (menu) set_user (const_cast(reinterpret_cast(p_UserData))); } }; #endif /* NCURSES_CURSESM_H_incl */ idna.h000064400000006754151027430560005647 0ustar00/* idna.h --- Prototypes for Internationalized Domain Name library. Copyright (C) 2002-2016 Simon Josefsson This file is part of GNU Libidn. GNU Libidn is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Libidn is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see . */ #ifndef IDNA_H # define IDNA_H # ifndef IDNAPI # if defined LIBIDN_BUILDING && defined HAVE_VISIBILITY && HAVE_VISIBILITY # define IDNAPI __attribute__((__visibility__("default"))) # elif defined LIBIDN_BUILDING && defined _MSC_VER && ! defined LIBIDN_STATIC # define IDNAPI __declspec(dllexport) # elif defined _MSC_VER && ! defined LIBIDN_STATIC # define IDNAPI __declspec(dllimport) # else # define IDNAPI # endif # endif # include /* size_t */ # include /* uint32_t */ # ifdef __cplusplus extern "C" { # endif /* Error codes. */ typedef enum { IDNA_SUCCESS = 0, IDNA_STRINGPREP_ERROR = 1, IDNA_PUNYCODE_ERROR = 2, IDNA_CONTAINS_NON_LDH = 3, /* Workaround typo in earlier versions. */ IDNA_CONTAINS_LDH = IDNA_CONTAINS_NON_LDH, IDNA_CONTAINS_MINUS = 4, IDNA_INVALID_LENGTH = 5, IDNA_NO_ACE_PREFIX = 6, IDNA_ROUNDTRIP_VERIFY_ERROR = 7, IDNA_CONTAINS_ACE_PREFIX = 8, IDNA_ICONV_ERROR = 9, /* Internal errors. */ IDNA_MALLOC_ERROR = 201, IDNA_DLOPEN_ERROR = 202 } Idna_rc; /* IDNA flags */ typedef enum { IDNA_ALLOW_UNASSIGNED = 0x0001, IDNA_USE_STD3_ASCII_RULES = 0x0002 } Idna_flags; # ifndef IDNA_ACE_PREFIX # define IDNA_ACE_PREFIX "xn--" # endif extern IDNAPI const char *idna_strerror (Idna_rc rc); /* Core functions */ extern IDNAPI int idna_to_ascii_4i (const uint32_t * in, size_t inlen, char *out, int flags); extern IDNAPI int idna_to_unicode_44i (const uint32_t * in, size_t inlen, uint32_t * out, size_t * outlen, int flags); /* Wrappers that handle several labels */ extern IDNAPI int idna_to_ascii_4z (const uint32_t * input, char **output, int flags); extern IDNAPI int idna_to_ascii_8z (const char *input, char **output, int flags); extern IDNAPI int idna_to_ascii_lz (const char *input, char **output, int flags); extern IDNAPI int idna_to_unicode_4z4z (const uint32_t * input, uint32_t ** output, int flags); extern IDNAPI int idna_to_unicode_8z4z (const char *input, uint32_t ** output, int flags); extern IDNAPI int idna_to_unicode_8z8z (const char *input, char **output, int flags); extern IDNAPI int idna_to_unicode_8zlz (const char *input, char **output, int flags); extern IDNAPI int idna_to_unicode_lzlz (const char *input, char **output, int flags); # ifdef __cplusplus } # endif #endif /* IDNA_H */ ar.h000064400000003302151027430560005320 0ustar00/* Header describing `ar' archive file format. Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _AR_H #define _AR_H 1 #include /* Archive files start with the ARMAG identifying string. Then follows a `struct ar_hdr', and as many bytes of member file data as its `ar_size' member indicates, for each member file. */ #define ARMAG "!\n" /* String that begins an archive file. */ #define SARMAG 8 /* Size of that string. */ #define ARFMAG "`\n" /* String in ar_fmag at end of each header. */ __BEGIN_DECLS struct ar_hdr { char ar_name[16]; /* Member file name, sometimes / terminated. */ char ar_date[12]; /* File date, decimal seconds since Epoch. */ char ar_uid[6], ar_gid[6]; /* User and group IDs, in ASCII decimal. */ char ar_mode[8]; /* File mode, in ASCII octal. */ char ar_size[10]; /* File size, in ASCII decimal. */ char ar_fmag[2]; /* Always contains ARFMAG. */ }; __END_DECLS #endif /* ar.h */ verto-module.h000064400000014760151027430560007352 0ustar00/* * Copyright 2011 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /*** THE FOLLOWING ARE FOR IMPLEMENTATION MODULES ONLY ***/ #ifndef VERTO_MODULE_H_ #define VERTO_MODULE_H_ #include #ifndef VERTO_MODULE_TYPES #define VERTO_MODULE_TYPES typedef void verto_mod_ctx; typedef void verto_mod_ev; #endif #define VERTO_MODULE_VERSION 3 #define VERTO_MODULE_TABLE(name) verto_module_table_ ## name #define VERTO_MODULE(name, symb, types) \ static verto_ctx_funcs name ## _funcs = { \ name ## _ctx_new, \ name ## _ctx_default, \ name ## _ctx_free, \ name ## _ctx_run, \ name ## _ctx_run_once, \ name ## _ctx_break, \ name ## _ctx_reinitialize, \ name ## _ctx_set_flags, \ name ## _ctx_add, \ name ## _ctx_del \ }; \ verto_module VERTO_MODULE_TABLE(name) = { \ VERTO_MODULE_VERSION, \ # name, \ # symb, \ types, \ &name ## _funcs, \ }; \ verto_ctx * \ verto_new_ ## name() \ { \ return verto_convert(name, 0, NULL); \ } \ verto_ctx * \ verto_default_ ## name() \ { \ return verto_convert(name, 1, NULL); \ } typedef struct { /* Required */ verto_mod_ctx *(*ctx_new)(); /* Optional */ verto_mod_ctx *(*ctx_default)(); /* Required */ void (*ctx_free)(verto_mod_ctx *ctx); /* Optional */ void (*ctx_run)(verto_mod_ctx *ctx); /* Required */ void (*ctx_run_once)(verto_mod_ctx *ctx); /* Optional */ void (*ctx_break)(verto_mod_ctx *ctx); /* Optional */ void (*ctx_reinitialize)(verto_mod_ctx *ctx); /* Optional */ void (*ctx_set_flags)(verto_mod_ctx *ctx, const verto_ev *ev, verto_mod_ev *modev); /* Required */ verto_mod_ev *(*ctx_add)(verto_mod_ctx *ctx, const verto_ev *ev, verto_ev_flag *flags); /* Required */ void (*ctx_del)(verto_mod_ctx *ctx, const verto_ev *ev, verto_mod_ev *modev); } verto_ctx_funcs; typedef struct { unsigned int vers; const char *name; const char *symb; verto_ev_type types; verto_ctx_funcs *funcs; } verto_module; /** * Converts an existing implementation specific loop to a verto_ctx. * * This function also sets the internal default implementation so that future * calls to verto_new(NULL) or verto_default(NULL) will use this specific * implementation if it was not already set. * * @param name The name of the module (unquoted) * @param deflt Whether the ctx is the default context or not * @param ctx The context to store * @return A new verto_ctx, or NULL on error. Call verto_free() when done. */ #define verto_convert(name, deflt, ctx) \ verto_convert_module(&VERTO_MODULE_TABLE(name), deflt, ctx) /** * Converts an existing implementation specific loop to a verto_ctx. * * If you are a module implementation, you probably want the macro above. This * function is generally used directly only when an application is attempting * to expose a home-grown event loop to verto. * * If deflt is non-zero and a default ctx was already defined for this module * and ctx is not NULL, than ctx will be free'd and the previously defined * default will be returned. * * If ctx is non-NULL, than the pre-existing verto_mod_ctx will be converted to * to a verto_ctx; if deflt is non-zero than this verto_mod_ctx will also be * marked as the default loop for this process. If ctx is NULL, than the * appropriate constructor will be called: either module->ctx_new() or * module->ctx_default() depending on the boolean value of deflt. If * module->ctx_default is NULL and deflt is non-zero, than module->ctx_new() * will be called and the resulting verto_mod_ctx will be utilized as the * default. * * This function also sets the internal default implementation so that future * calls to verto_new(NULL) or verto_default(NULL) will use this specific * implementation if it was not already set. * * @param name The name of the module (unquoted) * @param ctx The context private to store * @return A new verto_ctx, or NULL on error. Call verto_free() when done. */ verto_ctx * verto_convert_module(const verto_module *module, int deflt, verto_mod_ctx *ctx); /** * Calls the callback of the verto_ev and then frees it via verto_del(). * * The verto_ev is not freed (verto_del() is not called) if it is a signal event. * * @see verto_add_read() * @see verto_add_write() * @see verto_add_timeout() * @see verto_add_idle() * @see verto_add_signal() * @see verto_add_child() * @see verto_del() * @param ev The verto_ev */ void verto_fire(verto_ev *ev); /** * Sets the status of the pid/handle which caused this event to fire. * * This function does nothing if the verto_ev is not a child type. * * @see verto_add_child() * @param ev The verto_ev to set the status in. * @param status The pid/handle status. */ void verto_set_proc_status(verto_ev *ev, verto_proc_status status); /** * Sets the state of the fd which caused this event to fire. * * This function does nothing if the verto_ev is not a io type. * * Only the flags VERTO_EV_FLAG_IO_(READ|WRITE|ERROR) are supported. All other * flags are unset. * * @see verto_add_io() * @param ev The verto_ev to set the state in. * @param state The fd state. */ void verto_set_fd_state(verto_ev *ev, verto_ev_flag state); #endif /* VERTO_MODULE_H_ */ gd_errors.h000064400000002737151027430560006717 0ustar00#ifndef GD_ERRORS_H #define GD_ERRORS_H #ifndef _WIN32 # include #else /* * priorities/facilities are encoded into a single 32-bit quantity, where the * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility * (0-big number). Both the priorities and the facilities map roughly * one-to-one to strings in the syslogd(8) source code. This mapping is * included in this file. * * priorities (these are ordered) */ # define LOG_EMERG 0 /* system is unusable */ # define LOG_ALERT 1 /* action must be taken immediately */ # define LOG_CRIT 2 /* critical conditions */ # define LOG_ERR 3 /* error conditions */ # define LOG_WARNING 4 /* warning conditions */ # define LOG_NOTICE 5 /* normal but significant condition */ # define LOG_INFO 6 /* informational */ # define LOG_DEBUG 7 /* debug-level messages */ #endif /* LOG_EMERG system is unusable LOG_ALERT action must be taken immediately LOG_CRIT critical conditions LOG_ERR error conditions LOG_WARNING warning conditions LOG_NOTICE normal, but significant, condition LOG_INFO informational message LOG_DEBUG debug-level message */ #define GD_ERROR LOG_ERR #define GD_WARNING LOG_WARNING #define GD_NOTICE LOG_NOTICE #define GD_INFO LOG_INFO #define GD_DEBUG LOG_DEBUG void gd_error(const char *format, ...); void gd_error_ex(int priority, const char *format, ...); #endif termio.h000064400000000326151027430560006220 0ustar00/* Compatible for old `struct termio' ioctl interface. This is obsolete; use the POSIX.1 `struct termios' interface defined in instead. */ #include #include stdlib.h000064400000105505151027430560006207 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * ISO C99 Standard: 7.20 General utilities */ #ifndef _STDLIB_H #define __GLIBC_INTERNAL_STARTING_HEADER_IMPLEMENTATION #include /* Get size_t, wchar_t and NULL from . */ #define __need_size_t #define __need_wchar_t #define __need_NULL #include __BEGIN_DECLS #define _STDLIB_H 1 #if (defined __USE_XOPEN || defined __USE_XOPEN2K8) && !defined _SYS_WAIT_H /* XPG requires a few symbols from being defined. */ # include # include /* Define the macros also would define this way. */ # define WEXITSTATUS(status) __WEXITSTATUS (status) # define WTERMSIG(status) __WTERMSIG (status) # define WSTOPSIG(status) __WSTOPSIG (status) # define WIFEXITED(status) __WIFEXITED (status) # define WIFSIGNALED(status) __WIFSIGNALED (status) # define WIFSTOPPED(status) __WIFSTOPPED (status) # ifdef __WIFCONTINUED # define WIFCONTINUED(status) __WIFCONTINUED (status) # endif #endif /* X/Open or XPG7 and not included. */ /* _FloatN API tests for enablement. */ #include /* Returned by `div'. */ typedef struct { int quot; /* Quotient. */ int rem; /* Remainder. */ } div_t; /* Returned by `ldiv'. */ #ifndef __ldiv_t_defined typedef struct { long int quot; /* Quotient. */ long int rem; /* Remainder. */ } ldiv_t; # define __ldiv_t_defined 1 #endif #if defined __USE_ISOC99 && !defined __lldiv_t_defined /* Returned by `lldiv'. */ __extension__ typedef struct { long long int quot; /* Quotient. */ long long int rem; /* Remainder. */ } lldiv_t; # define __lldiv_t_defined 1 #endif /* The largest number rand will return (same as INT_MAX). */ #define RAND_MAX 2147483647 /* We define these the same for all machines. Changes from this to the outside world should be done in `_exit'. */ #define EXIT_FAILURE 1 /* Failing exit status. */ #define EXIT_SUCCESS 0 /* Successful exit status. */ /* Maximum length of a multibyte character in the current locale. */ #define MB_CUR_MAX (__ctype_get_mb_cur_max ()) extern size_t __ctype_get_mb_cur_max (void) __THROW __wur; /* Convert a string to a floating-point number. */ extern double atof (const char *__nptr) __THROW __attribute_pure__ __nonnull ((1)) __wur; /* Convert a string to an integer. */ extern int atoi (const char *__nptr) __THROW __attribute_pure__ __nonnull ((1)) __wur; /* Convert a string to a long integer. */ extern long int atol (const char *__nptr) __THROW __attribute_pure__ __nonnull ((1)) __wur; #ifdef __USE_ISOC99 /* Convert a string to a long long integer. */ __extension__ extern long long int atoll (const char *__nptr) __THROW __attribute_pure__ __nonnull ((1)) __wur; #endif /* Convert a string to a floating-point number. */ extern double strtod (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #ifdef __USE_ISOC99 /* Likewise for `float' and `long double' sizes of floating-point numbers. */ extern float strtof (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); extern long double strtold (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif /* Likewise for '_FloatN' and '_FloatNx'. */ #if __HAVE_FLOAT16 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float16 strtof16 (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif #if __HAVE_FLOAT32 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float32 strtof32 (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif #if __HAVE_FLOAT64 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float64 strtof64 (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif #if __HAVE_FLOAT128 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float128 strtof128 (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif #if __HAVE_FLOAT32X && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float32x strtof32x (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif #if __HAVE_FLOAT64X && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float64x strtof64x (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif #if __HAVE_FLOAT128X && __GLIBC_USE (IEC_60559_TYPES_EXT) extern _Float128x strtof128x (const char *__restrict __nptr, char **__restrict __endptr) __THROW __nonnull ((1)); #endif /* Convert a string to a long integer. */ extern long int strtol (const char *__restrict __nptr, char **__restrict __endptr, int __base) __THROW __nonnull ((1)); /* Convert a string to an unsigned long integer. */ extern unsigned long int strtoul (const char *__restrict __nptr, char **__restrict __endptr, int __base) __THROW __nonnull ((1)); #ifdef __USE_MISC /* Convert a string to a quadword integer. */ __extension__ extern long long int strtoq (const char *__restrict __nptr, char **__restrict __endptr, int __base) __THROW __nonnull ((1)); /* Convert a string to an unsigned quadword integer. */ __extension__ extern unsigned long long int strtouq (const char *__restrict __nptr, char **__restrict __endptr, int __base) __THROW __nonnull ((1)); #endif /* Use misc. */ #ifdef __USE_ISOC99 /* Convert a string to a quadword integer. */ __extension__ extern long long int strtoll (const char *__restrict __nptr, char **__restrict __endptr, int __base) __THROW __nonnull ((1)); /* Convert a string to an unsigned quadword integer. */ __extension__ extern unsigned long long int strtoull (const char *__restrict __nptr, char **__restrict __endptr, int __base) __THROW __nonnull ((1)); #endif /* ISO C99 or use MISC. */ /* Convert a floating-point number to a string. */ #if __GLIBC_USE (IEC_60559_BFP_EXT) extern int strfromd (char *__dest, size_t __size, const char *__format, double __f) __THROW __nonnull ((3)); extern int strfromf (char *__dest, size_t __size, const char *__format, float __f) __THROW __nonnull ((3)); extern int strfroml (char *__dest, size_t __size, const char *__format, long double __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT16 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf16 (char *__dest, size_t __size, const char * __format, _Float16 __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT32 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf32 (char *__dest, size_t __size, const char * __format, _Float32 __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT64 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf64 (char *__dest, size_t __size, const char * __format, _Float64 __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT128 && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf128 (char *__dest, size_t __size, const char * __format, _Float128 __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT32X && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf32x (char *__dest, size_t __size, const char * __format, _Float32x __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT64X && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf64x (char *__dest, size_t __size, const char * __format, _Float64x __f) __THROW __nonnull ((3)); #endif #if __HAVE_FLOAT128X && __GLIBC_USE (IEC_60559_TYPES_EXT) extern int strfromf128x (char *__dest, size_t __size, const char * __format, _Float128x __f) __THROW __nonnull ((3)); #endif #ifdef __USE_GNU /* Parallel versions of the functions above which take the locale to use as an additional parameter. These are GNU extensions inspired by the POSIX.1-2008 extended locale API. */ # include extern long int strtol_l (const char *__restrict __nptr, char **__restrict __endptr, int __base, locale_t __loc) __THROW __nonnull ((1, 4)); extern unsigned long int strtoul_l (const char *__restrict __nptr, char **__restrict __endptr, int __base, locale_t __loc) __THROW __nonnull ((1, 4)); __extension__ extern long long int strtoll_l (const char *__restrict __nptr, char **__restrict __endptr, int __base, locale_t __loc) __THROW __nonnull ((1, 4)); __extension__ extern unsigned long long int strtoull_l (const char *__restrict __nptr, char **__restrict __endptr, int __base, locale_t __loc) __THROW __nonnull ((1, 4)); extern double strtod_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); extern float strtof_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); extern long double strtold_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # if __HAVE_FLOAT16 extern _Float16 strtof16_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif # if __HAVE_FLOAT32 extern _Float32 strtof32_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif # if __HAVE_FLOAT64 extern _Float64 strtof64_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif # if __HAVE_FLOAT128 extern _Float128 strtof128_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif # if __HAVE_FLOAT32X extern _Float32x strtof32x_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif # if __HAVE_FLOAT64X extern _Float64x strtof64x_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif # if __HAVE_FLOAT128X extern _Float128x strtof128x_l (const char *__restrict __nptr, char **__restrict __endptr, locale_t __loc) __THROW __nonnull ((1, 3)); # endif #endif /* GNU */ #ifdef __USE_EXTERN_INLINES __extern_inline int __NTH (atoi (const char *__nptr)) { return (int) strtol (__nptr, (char **) NULL, 10); } __extern_inline long int __NTH (atol (const char *__nptr)) { return strtol (__nptr, (char **) NULL, 10); } # ifdef __USE_ISOC99 __extension__ __extern_inline long long int __NTH (atoll (const char *__nptr)) { return strtoll (__nptr, (char **) NULL, 10); } # endif #endif /* Optimizing and Inlining. */ #if defined __USE_MISC || defined __USE_XOPEN_EXTENDED /* Convert N to base 64 using the digits "./0-9A-Za-z", least-significant digit first. Returns a pointer to static storage overwritten by the next call. */ extern char *l64a (long int __n) __THROW __wur; /* Read a number from a string S in base 64 as above. */ extern long int a64l (const char *__s) __THROW __attribute_pure__ __nonnull ((1)) __wur; #endif /* Use misc || extended X/Open. */ #if defined __USE_MISC || defined __USE_XOPEN_EXTENDED # include /* we need int32_t... */ /* These are the functions that actually do things. The `random', `srandom', `initstate' and `setstate' functions are those from BSD Unices. The `rand' and `srand' functions are required by the ANSI standard. We provide both interfaces to the same random number generator. */ /* Return a random long integer between 0 and RAND_MAX inclusive. */ extern long int random (void) __THROW; /* Seed the random number generator with the given number. */ extern void srandom (unsigned int __seed) __THROW; /* Initialize the random number generator to use state buffer STATEBUF, of length STATELEN, and seed it with SEED. Optimal lengths are 8, 16, 32, 64, 128 and 256, the bigger the better; values less than 8 will cause an error and values greater than 256 will be rounded down. */ extern char *initstate (unsigned int __seed, char *__statebuf, size_t __statelen) __THROW __nonnull ((2)); /* Switch the random number generator to state buffer STATEBUF, which should have been previously initialized by `initstate'. */ extern char *setstate (char *__statebuf) __THROW __nonnull ((1)); # ifdef __USE_MISC /* Reentrant versions of the `random' family of functions. These functions all use the following data structure to contain state, rather than global state variables. */ struct random_data { int32_t *fptr; /* Front pointer. */ int32_t *rptr; /* Rear pointer. */ int32_t *state; /* Array of state values. */ int rand_type; /* Type of random number generator. */ int rand_deg; /* Degree of random number generator. */ int rand_sep; /* Distance between front and rear. */ int32_t *end_ptr; /* Pointer behind state table. */ }; extern int random_r (struct random_data *__restrict __buf, int32_t *__restrict __result) __THROW __nonnull ((1, 2)); extern int srandom_r (unsigned int __seed, struct random_data *__buf) __THROW __nonnull ((2)); extern int initstate_r (unsigned int __seed, char *__restrict __statebuf, size_t __statelen, struct random_data *__restrict __buf) __THROW __nonnull ((2, 4)); extern int setstate_r (char *__restrict __statebuf, struct random_data *__restrict __buf) __THROW __nonnull ((1, 2)); # endif /* Use misc. */ #endif /* Use extended X/Open || misc. */ /* Return a random integer between 0 and RAND_MAX inclusive. */ extern int rand (void) __THROW; /* Seed the random number generator with the given number. */ extern void srand (unsigned int __seed) __THROW; #ifdef __USE_POSIX199506 /* Reentrant interface according to POSIX.1. */ extern int rand_r (unsigned int *__seed) __THROW; #endif #if defined __USE_MISC || defined __USE_XOPEN /* System V style 48-bit random number generator functions. */ /* Return non-negative, double-precision floating-point value in [0.0,1.0). */ extern double drand48 (void) __THROW; extern double erand48 (unsigned short int __xsubi[3]) __THROW __nonnull ((1)); /* Return non-negative, long integer in [0,2^31). */ extern long int lrand48 (void) __THROW; extern long int nrand48 (unsigned short int __xsubi[3]) __THROW __nonnull ((1)); /* Return signed, long integers in [-2^31,2^31). */ extern long int mrand48 (void) __THROW; extern long int jrand48 (unsigned short int __xsubi[3]) __THROW __nonnull ((1)); /* Seed random number generator. */ extern void srand48 (long int __seedval) __THROW; extern unsigned short int *seed48 (unsigned short int __seed16v[3]) __THROW __nonnull ((1)); extern void lcong48 (unsigned short int __param[7]) __THROW __nonnull ((1)); # ifdef __USE_MISC /* Data structure for communication with thread safe versions. This type is to be regarded as opaque. It's only exported because users have to allocate objects of this type. */ struct drand48_data { unsigned short int __x[3]; /* Current state. */ unsigned short int __old_x[3]; /* Old state. */ unsigned short int __c; /* Additive const. in congruential formula. */ unsigned short int __init; /* Flag for initializing. */ __extension__ unsigned long long int __a; /* Factor in congruential formula. */ }; /* Return non-negative, double-precision floating-point value in [0.0,1.0). */ extern int drand48_r (struct drand48_data *__restrict __buffer, double *__restrict __result) __THROW __nonnull ((1, 2)); extern int erand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, double *__restrict __result) __THROW __nonnull ((1, 2)); /* Return non-negative, long integer in [0,2^31). */ extern int lrand48_r (struct drand48_data *__restrict __buffer, long int *__restrict __result) __THROW __nonnull ((1, 2)); extern int nrand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, long int *__restrict __result) __THROW __nonnull ((1, 2)); /* Return signed, long integers in [-2^31,2^31). */ extern int mrand48_r (struct drand48_data *__restrict __buffer, long int *__restrict __result) __THROW __nonnull ((1, 2)); extern int jrand48_r (unsigned short int __xsubi[3], struct drand48_data *__restrict __buffer, long int *__restrict __result) __THROW __nonnull ((1, 2)); /* Seed random number generator. */ extern int srand48_r (long int __seedval, struct drand48_data *__buffer) __THROW __nonnull ((2)); extern int seed48_r (unsigned short int __seed16v[3], struct drand48_data *__buffer) __THROW __nonnull ((1, 2)); extern int lcong48_r (unsigned short int __param[7], struct drand48_data *__buffer) __THROW __nonnull ((1, 2)); # endif /* Use misc. */ #endif /* Use misc or X/Open. */ /* Allocate SIZE bytes of memory. */ extern void *malloc (size_t __size) __THROW __attribute_malloc__ __wur; /* Allocate NMEMB elements of SIZE bytes each, all initialized to 0. */ extern void *calloc (size_t __nmemb, size_t __size) __THROW __attribute_malloc__ __wur; /* Re-allocate the previously allocated block in PTR, making the new block SIZE bytes long. */ /* __attribute_malloc__ is not used, because if realloc returns the same pointer that was passed to it, aliasing needs to be allowed between objects pointed by the old and new pointers. */ extern void *realloc (void *__ptr, size_t __size) __THROW __attribute_warn_unused_result__; #ifdef __USE_GNU /* Re-allocate the previously allocated block in PTR, making the new block large enough for NMEMB elements of SIZE bytes each. */ /* __attribute_malloc__ is not used, because if reallocarray returns the same pointer that was passed to it, aliasing needs to be allowed between objects pointed by the old and new pointers. */ extern void *reallocarray (void *__ptr, size_t __nmemb, size_t __size) __THROW __attribute_warn_unused_result__; #endif /* Free a block allocated by `malloc', `realloc' or `calloc'. */ extern void free (void *__ptr) __THROW; #ifdef __USE_MISC # include #endif /* Use misc. */ #if (defined __USE_XOPEN_EXTENDED && !defined __USE_XOPEN2K) \ || defined __USE_MISC /* Allocate SIZE bytes on a page boundary. The storage cannot be freed. */ extern void *valloc (size_t __size) __THROW __attribute_malloc__ __wur; #endif #ifdef __USE_XOPEN2K /* Allocate memory of SIZE bytes with an alignment of ALIGNMENT. */ extern int posix_memalign (void **__memptr, size_t __alignment, size_t __size) __THROW __nonnull ((1)) __wur; #endif #ifdef __USE_ISOC11 /* ISO C variant of aligned allocation. */ extern void *aligned_alloc (size_t __alignment, size_t __size) __THROW __attribute_malloc__ __attribute_alloc_size__ ((2)) __wur; #endif /* Abort execution and generate a core-dump. */ extern void abort (void) __THROW __attribute__ ((__noreturn__)); /* Register a function to be called when `exit' is called. */ extern int atexit (void (*__func) (void)) __THROW __nonnull ((1)); #if defined __USE_ISOC11 || defined __USE_ISOCXX11 /* Register a function to be called when `quick_exit' is called. */ # ifdef __cplusplus extern "C++" int at_quick_exit (void (*__func) (void)) __THROW __asm ("at_quick_exit") __nonnull ((1)); # else extern int at_quick_exit (void (*__func) (void)) __THROW __nonnull ((1)); # endif #endif #ifdef __USE_MISC /* Register a function to be called with the status given to `exit' and the given argument. */ extern int on_exit (void (*__func) (int __status, void *__arg), void *__arg) __THROW __nonnull ((1)); #endif /* Call all functions registered with `atexit' and `on_exit', in the reverse of the order in which they were registered, perform stdio cleanup, and terminate program execution with STATUS. */ extern void exit (int __status) __THROW __attribute__ ((__noreturn__)); #if defined __USE_ISOC11 || defined __USE_ISOCXX11 /* Call all functions registered with `at_quick_exit' in the reverse of the order in which they were registered and terminate program execution with STATUS. */ extern void quick_exit (int __status) __THROW __attribute__ ((__noreturn__)); #endif #ifdef __USE_ISOC99 /* Terminate the program with STATUS without calling any of the functions registered with `atexit' or `on_exit'. */ extern void _Exit (int __status) __THROW __attribute__ ((__noreturn__)); #endif /* Return the value of envariable NAME, or NULL if it doesn't exist. */ extern char *getenv (const char *__name) __THROW __nonnull ((1)) __wur; #ifdef __USE_GNU /* This function is similar to the above but returns NULL if the programs is running with SUID or SGID enabled. */ extern char *secure_getenv (const char *__name) __THROW __nonnull ((1)) __wur; #endif #if defined __USE_MISC || defined __USE_XOPEN /* The SVID says this is in , but this seems a better place. */ /* Put STRING, which is of the form "NAME=VALUE", in the environment. If there is no `=', remove NAME from the environment. */ extern int putenv (char *__string) __THROW __nonnull ((1)); #endif #ifdef __USE_XOPEN2K /* Set NAME to VALUE in the environment. If REPLACE is nonzero, overwrite an existing value. */ extern int setenv (const char *__name, const char *__value, int __replace) __THROW __nonnull ((2)); /* Remove the variable NAME from the environment. */ extern int unsetenv (const char *__name) __THROW __nonnull ((1)); #endif #ifdef __USE_MISC /* The `clearenv' was planned to be added to POSIX.1 but probably never made it. Nevertheless the POSIX.9 standard (POSIX bindings for Fortran 77) requires this function. */ extern int clearenv (void) __THROW; #endif #if defined __USE_MISC \ || (defined __USE_XOPEN_EXTENDED && !defined __USE_XOPEN2K8) /* Generate a unique temporary file name from TEMPLATE. The last six characters of TEMPLATE must be "XXXXXX"; they are replaced with a string that makes the file name unique. Always returns TEMPLATE, it's either a temporary file name or a null string if it cannot get a unique file name. */ extern char *mktemp (char *__template) __THROW __nonnull ((1)); #endif #if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K8 /* Generate a unique temporary file name from TEMPLATE. The last six characters of TEMPLATE must be "XXXXXX"; they are replaced with a string that makes the filename unique. Returns a file descriptor open on the file for reading and writing, or -1 if it cannot create a uniquely-named file. This function is a possible cancellation point and therefore not marked with __THROW. */ # ifndef __USE_FILE_OFFSET64 extern int mkstemp (char *__template) __nonnull ((1)) __wur; # else # ifdef __REDIRECT extern int __REDIRECT (mkstemp, (char *__template), mkstemp64) __nonnull ((1)) __wur; # else # define mkstemp mkstemp64 # endif # endif # ifdef __USE_LARGEFILE64 extern int mkstemp64 (char *__template) __nonnull ((1)) __wur; # endif #endif #ifdef __USE_MISC /* Similar to mkstemp, but the template can have a suffix after the XXXXXX. The length of the suffix is specified in the second parameter. This function is a possible cancellation point and therefore not marked with __THROW. */ # ifndef __USE_FILE_OFFSET64 extern int mkstemps (char *__template, int __suffixlen) __nonnull ((1)) __wur; # else # ifdef __REDIRECT extern int __REDIRECT (mkstemps, (char *__template, int __suffixlen), mkstemps64) __nonnull ((1)) __wur; # else # define mkstemps mkstemps64 # endif # endif # ifdef __USE_LARGEFILE64 extern int mkstemps64 (char *__template, int __suffixlen) __nonnull ((1)) __wur; # endif #endif #ifdef __USE_XOPEN2K8 /* Create a unique temporary directory from TEMPLATE. The last six characters of TEMPLATE must be "XXXXXX"; they are replaced with a string that makes the directory name unique. Returns TEMPLATE, or a null pointer if it cannot get a unique name. The directory is created mode 700. */ extern char *mkdtemp (char *__template) __THROW __nonnull ((1)) __wur; #endif #ifdef __USE_GNU /* Generate a unique temporary file name from TEMPLATE similar to mkstemp. But allow the caller to pass additional flags which are used in the open call to create the file.. This function is a possible cancellation point and therefore not marked with __THROW. */ # ifndef __USE_FILE_OFFSET64 extern int mkostemp (char *__template, int __flags) __nonnull ((1)) __wur; # else # ifdef __REDIRECT extern int __REDIRECT (mkostemp, (char *__template, int __flags), mkostemp64) __nonnull ((1)) __wur; # else # define mkostemp mkostemp64 # endif # endif # ifdef __USE_LARGEFILE64 extern int mkostemp64 (char *__template, int __flags) __nonnull ((1)) __wur; # endif /* Similar to mkostemp, but the template can have a suffix after the XXXXXX. The length of the suffix is specified in the second parameter. This function is a possible cancellation point and therefore not marked with __THROW. */ # ifndef __USE_FILE_OFFSET64 extern int mkostemps (char *__template, int __suffixlen, int __flags) __nonnull ((1)) __wur; # else # ifdef __REDIRECT extern int __REDIRECT (mkostemps, (char *__template, int __suffixlen, int __flags), mkostemps64) __nonnull ((1)) __wur; # else # define mkostemps mkostemps64 # endif # endif # ifdef __USE_LARGEFILE64 extern int mkostemps64 (char *__template, int __suffixlen, int __flags) __nonnull ((1)) __wur; # endif #endif /* Execute the given line as a shell command. This function is a cancellation point and therefore not marked with __THROW. */ extern int system (const char *__command) __wur; #ifdef __USE_GNU /* Return a malloc'd string containing the canonical absolute name of the existing named file. */ extern char *canonicalize_file_name (const char *__name) __THROW __nonnull ((1)) __wur; #endif #if defined __USE_MISC || defined __USE_XOPEN_EXTENDED /* Return the canonical absolute name of file NAME. If RESOLVED is null, the result is malloc'd; otherwise, if the canonical name is PATH_MAX chars or more, returns null with `errno' set to ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars, returns the name in RESOLVED. */ extern char *realpath (const char *__restrict __name, char *__restrict __resolved) __THROW __wur; #endif /* Shorthand for type of comparison functions. */ #ifndef __COMPAR_FN_T # define __COMPAR_FN_T typedef int (*__compar_fn_t) (const void *, const void *); # ifdef __USE_GNU typedef __compar_fn_t comparison_fn_t; # endif #endif #ifdef __USE_GNU typedef int (*__compar_d_fn_t) (const void *, const void *, void *); #endif /* Do a binary search for KEY in BASE, which consists of NMEMB elements of SIZE bytes each, using COMPAR to perform the comparisons. */ extern void *bsearch (const void *__key, const void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar) __nonnull ((1, 2, 5)) __wur; #ifdef __USE_EXTERN_INLINES # include #endif /* Sort NMEMB elements of BASE, of SIZE bytes each, using COMPAR to perform the comparisons. */ extern void qsort (void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar) __nonnull ((1, 4)); #ifdef __USE_GNU extern void qsort_r (void *__base, size_t __nmemb, size_t __size, __compar_d_fn_t __compar, void *__arg) __nonnull ((1, 4)); #endif /* Return the absolute value of X. */ extern int abs (int __x) __THROW __attribute__ ((__const__)) __wur; extern long int labs (long int __x) __THROW __attribute__ ((__const__)) __wur; #ifdef __USE_ISOC99 __extension__ extern long long int llabs (long long int __x) __THROW __attribute__ ((__const__)) __wur; #endif /* Return the `div_t', `ldiv_t' or `lldiv_t' representation of the value of NUMER over DENOM. */ /* GCC may have built-ins for these someday. */ extern div_t div (int __numer, int __denom) __THROW __attribute__ ((__const__)) __wur; extern ldiv_t ldiv (long int __numer, long int __denom) __THROW __attribute__ ((__const__)) __wur; #ifdef __USE_ISOC99 __extension__ extern lldiv_t lldiv (long long int __numer, long long int __denom) __THROW __attribute__ ((__const__)) __wur; #endif #if (defined __USE_XOPEN_EXTENDED && !defined __USE_XOPEN2K8) \ || defined __USE_MISC /* Convert floating point numbers to strings. The returned values are valid only until another call to the same function. */ /* Convert VALUE to a string with NDIGIT digits and return a pointer to this. Set *DECPT with the position of the decimal character and *SIGN with the sign of the number. */ extern char *ecvt (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __THROW __nonnull ((3, 4)) __wur; /* Convert VALUE to a string rounded to NDIGIT decimal digits. Set *DECPT with the position of the decimal character and *SIGN with the sign of the number. */ extern char *fcvt (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __THROW __nonnull ((3, 4)) __wur; /* If possible convert VALUE to a string with NDIGIT significant digits. Otherwise use exponential representation. The resulting string will be written to BUF. */ extern char *gcvt (double __value, int __ndigit, char *__buf) __THROW __nonnull ((3)) __wur; #endif #ifdef __USE_MISC /* Long double versions of above functions. */ extern char *qecvt (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __THROW __nonnull ((3, 4)) __wur; extern char *qfcvt (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign) __THROW __nonnull ((3, 4)) __wur; extern char *qgcvt (long double __value, int __ndigit, char *__buf) __THROW __nonnull ((3)) __wur; /* Reentrant version of the functions above which provide their own buffers. */ extern int ecvt_r (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __THROW __nonnull ((3, 4, 5)); extern int fcvt_r (double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __THROW __nonnull ((3, 4, 5)); extern int qecvt_r (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __THROW __nonnull ((3, 4, 5)); extern int qfcvt_r (long double __value, int __ndigit, int *__restrict __decpt, int *__restrict __sign, char *__restrict __buf, size_t __len) __THROW __nonnull ((3, 4, 5)); #endif /* misc */ /* Return the length of the multibyte character in S, which is no longer than N. */ extern int mblen (const char *__s, size_t __n) __THROW; /* Return the length of the given multibyte character, putting its `wchar_t' representation in *PWC. */ extern int mbtowc (wchar_t *__restrict __pwc, const char *__restrict __s, size_t __n) __THROW; /* Put the multibyte character represented by WCHAR in S, returning its length. */ extern int wctomb (char *__s, wchar_t __wchar) __THROW; /* Convert a multibyte string to a wide char string. */ extern size_t mbstowcs (wchar_t *__restrict __pwcs, const char *__restrict __s, size_t __n) __THROW; /* Convert a wide char string to multibyte string. */ extern size_t wcstombs (char *__restrict __s, const wchar_t *__restrict __pwcs, size_t __n) __THROW; #ifdef __USE_MISC /* Determine whether the string value of RESPONSE matches the affirmation or negative response expression as specified by the LC_MESSAGES category in the program's current locale. Returns 1 if affirmative, 0 if negative, and -1 if not matching. */ extern int rpmatch (const char *__response) __THROW __nonnull ((1)) __wur; #endif #if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K8 /* Parse comma separated suboption from *OPTIONP and match against strings in TOKENS. If found return index and set *VALUEP to optional value introduced by an equal sign. If the suboption is not part of TOKENS return in *VALUEP beginning of unknown suboption. On exit *OPTIONP is set to the beginning of the next token or at the terminating NUL character. */ extern int getsubopt (char **__restrict __optionp, char *const *__restrict __tokens, char **__restrict __valuep) __THROW __nonnull ((1, 2, 3)) __wur; #endif /* X/Open pseudo terminal handling. */ #ifdef __USE_XOPEN2KXSI /* Return a master pseudo-terminal handle. */ extern int posix_openpt (int __oflag) __wur; #endif #ifdef __USE_XOPEN_EXTENDED /* The next four functions all take a master pseudo-tty fd and perform an operation on the associated slave: */ /* Chown the slave to the calling user. */ extern int grantpt (int __fd) __THROW; /* Release an internal lock so the slave can be opened. Call after grantpt(). */ extern int unlockpt (int __fd) __THROW; /* Return the pathname of the pseudo terminal slave associated with the master FD is open on, or NULL on errors. The returned storage is good until the next call to this function. */ extern char *ptsname (int __fd) __THROW __wur; #endif #ifdef __USE_GNU /* Store at most BUFLEN characters of the pathname of the slave pseudo terminal associated with the master FD is open on in BUF. Return 0 on success, otherwise an error number. */ extern int ptsname_r (int __fd, char *__buf, size_t __buflen) __THROW __nonnull ((2)); /* Open a master pseudo terminal and return its file descriptor. */ extern int getpt (void); #endif #ifdef __USE_MISC /* Put the 1 minute, 5 minute and 15 minute load averages into the first NELEM elements of LOADAVG. Return the number written (never more than three, but may be less than NELEM), or -1 if an error occurred. */ extern int getloadavg (double __loadavg[], int __nelem) __THROW __nonnull ((1)); #endif #if defined __USE_XOPEN_EXTENDED && !defined __USE_XOPEN2K /* Return the index into the active-logins file (utmp) for the controlling terminal. */ extern int ttyslot (void) __THROW; #endif #include /* Define some macros helping to catch buffer overflows. */ #if __USE_FORTIFY_LEVEL > 0 && defined __fortify_function # include #endif #ifdef __LDBL_COMPAT # include #endif __END_DECLS #endif /* stdlib.h */ termcap.h000064400000006621151027430560006360 0ustar00/**************************************************************************** * Copyright (c) 1998-2000,2001 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim 1992,1995 * * and: Eric S. Raymond * ****************************************************************************/ /* $Id: termcap.h.in,v 1.17 2001/03/24 21:53:27 tom Exp $ */ #ifndef NCURSES_TERMCAP_H_incl #define NCURSES_TERMCAP_H_incl 1 #undef NCURSES_VERSION #define NCURSES_VERSION "6.1" #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include #undef NCURSES_CONST #define NCURSES_CONST const #undef NCURSES_OSPEED #define NCURSES_OSPEED unsigned extern NCURSES_EXPORT_VAR(char) PC; extern NCURSES_EXPORT_VAR(char *) UP; extern NCURSES_EXPORT_VAR(char *) BC; extern NCURSES_EXPORT_VAR(NCURSES_OSPEED) ospeed; #if !defined(NCURSES_TERM_H_incl) extern NCURSES_EXPORT(char *) tgetstr (NCURSES_CONST char *, char **); extern NCURSES_EXPORT(char *) tgoto (const char *, int, int); extern NCURSES_EXPORT(int) tgetent (char *, const char *); extern NCURSES_EXPORT(int) tgetflag (NCURSES_CONST char *); extern NCURSES_EXPORT(int) tgetnum (NCURSES_CONST char *); extern NCURSES_EXPORT(int) tputs (const char *, int, int (*)(int)); #endif #ifdef __cplusplus } #endif #endif /* NCURSES_TERMCAP_H_incl */ cursslk.h000064400000016210151027430560006406 0ustar00// * this is for making emacs happy: -*-Mode: C++;-*- /**************************************************************************** * Copyright (c) 1998-2003,2005 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1997 * ****************************************************************************/ // $Id: cursslk.h,v 1.13 2005/05/28 21:58:18 tom Exp $ #ifndef NCURSES_CURSSLK_H_incl #define NCURSES_CURSSLK_H_incl #include class NCURSES_IMPEXP Soft_Label_Key_Set { public: // This inner class represents the attributes of a Soft Label Key (SLK) class NCURSES_IMPEXP Soft_Label_Key { friend class Soft_Label_Key_Set; public: typedef enum { Left=0, Center=1, Right=2 } Justification; private: char *label; // The Text of the Label Justification format; // The Justification int num; // The number of the Label Soft_Label_Key() : label(NULL), format(Left), num(-1) { } virtual ~Soft_Label_Key() { delete[] label; }; public: // Set the text of the Label Soft_Label_Key& operator=(char *text); // Set the Justification of the Label Soft_Label_Key& operator=(Justification just) { format = just; return *this; } // Retrieve the text of the label inline char* operator()(void) const { return label; } Soft_Label_Key& operator=(const Soft_Label_Key& rhs) { if (this != &rhs) { *this = rhs; } return *this; } Soft_Label_Key(const Soft_Label_Key& rhs) : label(NULL), format(rhs.format), num(rhs.num) { *this = rhs.label; } }; public: typedef enum { None = -1, Three_Two_Three = 0, Four_Four = 1, PC_Style = 2, PC_Style_With_Index = 3 } Label_Layout; private: static long NCURSES_IMPEXP count; // Number of Key Sets static Label_Layout NCURSES_IMPEXP format; // Layout of the Key Sets static int NCURSES_IMPEXP num_labels; // Number Of Labels in Key Sets bool NCURSES_IMPEXP b_attrInit; // Are attributes initialized Soft_Label_Key *slk_array; // The array of SLK's // Init the Key Set void init(); // Activate or Deactivate Label# i, Label counting starts with 1! void activate_label(int i, bool bf=TRUE); // Activate of Deactivate all Labels void activate_labels(bool bf); protected: inline void Error (const char* msg) const THROWS(NCursesException) { THROW(new NCursesException (msg)); } // Remove SLK's from screen void clear() { if (ERR==::slk_clear()) Error("slk_clear"); } // Restore them void restore() { if (ERR==::slk_restore()) Error("slk_restore"); } public: // Construct a Key Set, use the most comfortable layout as default. // You must create a Soft_Label_Key_Set before you create any object of // the NCursesWindow, NCursesPanel or derived classes. (Actually before // ::initscr() is called). Soft_Label_Key_Set(Label_Layout fmt); // This constructor assumes, that you already constructed a Key Set // with a layout by the constructor above. This layout will be reused. NCURSES_IMPEXP Soft_Label_Key_Set(); Soft_Label_Key_Set& operator=(const Soft_Label_Key_Set& rhs) { if (this != &rhs) { *this = rhs; init(); // allocate a new slk_array[] } return *this; } Soft_Label_Key_Set(const Soft_Label_Key_Set& rhs) : b_attrInit(rhs.b_attrInit), slk_array(NULL) { init(); // allocate a new slk_array[] } virtual ~Soft_Label_Key_Set(); // Get Label# i. Label counting starts with 1! NCURSES_IMPEXP Soft_Label_Key& operator[](int i); // Retrieve number of Labels inline int labels() const { return num_labels; } // Refresh the SLK portion of the screen inline void refresh() { if (ERR==::slk_refresh()) Error("slk_refresh"); } // Mark the SLK portion of the screen for refresh, defer actual refresh // until next update call. inline void noutrefresh() { if (ERR==::slk_noutrefresh()) Error("slk_noutrefresh"); } // Mark the whole SLK portion of the screen as modified inline void touch() { if (ERR==::slk_touch()) Error("slk_touch"); } // Activate Label# i inline void show(int i) { activate_label(i,FALSE); activate_label(i,TRUE); } // Hide Label# i inline void hide(int i) { activate_label(i,FALSE); } // Show all Labels inline void show() { activate_labels(FALSE); activate_labels(TRUE); } // Hide all Labels inline void hide() { activate_labels(FALSE); } inline void attron(attr_t attrs) { if (ERR==::slk_attron(attrs)) Error("slk_attron"); } inline void attroff(attr_t attrs) { if (ERR==::slk_attroff(attrs)) Error("slk_attroff"); } inline void attrset(attr_t attrs) { if (ERR==::slk_attrset(attrs)) Error("slk_attrset"); } inline void color(short color_pair_number) { if (ERR==::slk_color(color_pair_number)) Error("slk_color"); } inline attr_t attr() const { return ::slk_attr(); } }; #endif /* NCURSES_CURSSLK_H_incl */ cursesp.h000064400000020631151027430560006406 0ustar00// * This makes emacs happy -*-Mode: C++;-*- /**************************************************************************** * Copyright (c) 1998-2012,2014 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1997 * ****************************************************************************/ #ifndef NCURSES_CURSESP_H_incl #define NCURSES_CURSESP_H_incl 1 // $Id: cursesp.h,v 1.31 2014/08/09 22:06:26 Adam.Jiang Exp $ #include extern "C" { # include } class NCURSES_IMPEXP NCursesPanel : public NCursesWindow { protected: PANEL *p; static NCursesPanel *dummy; private: // This structure is used for the panel's user data field to link the // PANEL* to the C++ object and to provide extra space for a user pointer. typedef struct { void* m_user; // the pointer for the user's data const NCursesPanel* m_back; // backward pointer to C++ object const PANEL* m_owner; // the panel itself } UserHook; inline UserHook *UserPointer() { UserHook* uptr = reinterpret_cast( const_cast(::panel_userptr (p))); return uptr; } void init(); // Initialize the panel object protected: void set_user(void *user) { UserHook* uptr = UserPointer(); if (uptr != 0 && uptr->m_back==this && uptr->m_owner==p) { uptr->m_user = user; } } // Set the user pointer of the panel. void *get_user() { UserHook* uptr = UserPointer(); void *result = 0; if (uptr != 0 && uptr->m_back==this && uptr->m_owner==p) result = uptr->m_user; return result; } void OnError (int err) const THROW2(NCursesException const, NCursesPanelException) { if (err==ERR) THROW(new NCursesPanelException (this, err)); } // If err is equal to the curses error indicator ERR, an error handler // is called. // Get a keystroke. Default implementation calls getch() virtual int getKey(void); public: NCursesPanel(int nlines, int ncols, int begin_y = 0, int begin_x = 0) : NCursesWindow(nlines,ncols,begin_y,begin_x), p(0) { init(); } // Create a panel with this size starting at the requested position. NCursesPanel() : NCursesWindow(::stdscr), p(0) { init(); } // This constructor creates the default Panel associated with the // ::stdscr window NCursesPanel& operator=(const NCursesPanel& rhs) { if (this != &rhs) { *this = rhs; NCursesWindow::operator=(rhs); } return *this; } NCursesPanel(const NCursesPanel& rhs) : NCursesWindow(rhs), p(rhs.p) { } virtual ~NCursesPanel(); // basic manipulation inline void hide() { OnError (::hide_panel(p)); } // Hide the panel. It stays in the stack but becomes invisible. inline void show() { OnError (::show_panel(p)); } // Show the panel, i.e. make it visible. inline void top() { OnError (::top_panel(p)); } // Make this panel the top panel in the stack. inline void bottom() { OnError (::bottom_panel(p)); } // Make this panel the bottom panel in the stack. // N.B.: The panel associated with ::stdscr is always on the bottom. So // actually bottom() makes the panel the first above ::stdscr. virtual int mvwin(int y, int x) { OnError(::move_panel(p, y, x)); return OK; } inline bool hidden() const { return (::panel_hidden (p) ? TRUE : FALSE); } // Return TRUE if the panel is hidden, FALSE otherwise. /* The functions panel_above() and panel_below() are not reflected in the NCursesPanel class. The reason for this is, that we cannot assume that a panel retrieved by those operations is one wrapped by a C++ class. Although this situation might be handled, we also need a reverse mapping from PANEL to NCursesPanel which needs some redesign of the low level stuff. At the moment, we define them in the interface but they will always produce an error. */ inline NCursesPanel& above() const { OnError(ERR); return *dummy; } inline NCursesPanel& below() const { OnError(ERR); return *dummy; } // Those two are rewrites of the corresponding virtual members of // NCursesWindow virtual int refresh(); // Propagate all panel changes to the virtual screen and update the // physical screen. virtual int noutrefresh(); // Propagate all panel changes to the virtual screen. static void redraw(); // Redraw all panels. // decorations virtual void frame(const char* title=NULL, const char* btitle=NULL); // Put a frame around the panel and put the title centered in the top line // and btitle in the bottom line. virtual void boldframe(const char* title=NULL, const char* btitle=NULL); // Same as frame(), but use highlighted attributes. virtual void label(const char* topLabel, const char* bottomLabel); // Put the title centered in the top line and btitle in the bottom line. virtual void centertext(int row,const char* label); // Put the label text centered in the specified row. }; /* We use templates to provide a typesafe mechanism to associate * user data with a panel. A NCursesUserPanel is a panel * associated with some user data of type T. */ template class NCursesUserPanel : public NCursesPanel { public: NCursesUserPanel (int nlines, int ncols, int begin_y = 0, int begin_x = 0, const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesPanel (nlines, ncols, begin_y, begin_x) { if (p) set_user (const_cast(reinterpret_cast (p_UserData))); }; // This creates an user panel of the requested size with associated // user data pointed to by p_UserData. NCursesUserPanel(const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesPanel() { if (p) set_user(const_cast(reinterpret_cast(p_UserData))); }; // This creates an user panel associated with the ::stdscr and user data // pointed to by p_UserData. virtual ~NCursesUserPanel() {}; T* UserData (void) { return reinterpret_cast(get_user ()); }; // Retrieve the user data associated with the panel. virtual void setUserData (const T* p_UserData) { if (p) set_user (const_cast(reinterpret_cast(p_UserData))); } // Associate the user panel with the user data pointed to by p_UserData. }; #endif /* NCURSES_CURSESP_H_incl */ nc_tparm.h000064400000010145151027430560006524 0ustar00/**************************************************************************** * Copyright (c) 2006-2012,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Thomas E. Dickey 2006 * ****************************************************************************/ /* $Id: nc_tparm.h,v 1.8 2017/07/22 17:09:46 tom Exp $ */ #ifndef NC_TPARM_included #define NC_TPARM_included 1 #include #include /* * Cast parameters past the formatting-string for tparm() to match the * assumption of the varargs code. */ #ifndef TPARM_ARG #ifdef NCURSES_TPARM_ARG #define TPARM_ARG NCURSES_TPARM_ARG #else #define TPARM_ARG long #endif #endif /* TPARAM_ARG */ #define TPARM_N(n) (TPARM_ARG)(n) #define TPARM_9(a,b,c,d,e,f,g,h,i,j) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g),TPARM_N(h),TPARM_N(i),TPARM_N(j)) #if NCURSES_TPARM_VARARGS #define TPARM_8(a,b,c,d,e,f,g,h,i) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g),TPARM_N(h),TPARM_N(i)) #define TPARM_7(a,b,c,d,e,f,g,h) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g),TPARM_N(h)) #define TPARM_6(a,b,c,d,e,f,g) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f),TPARM_N(g)) #define TPARM_5(a,b,c,d,e,f) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e),TPARM_N(f)) #define TPARM_4(a,b,c,d,e) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d),TPARM_N(e)) #define TPARM_3(a,b,c,d) tparm(a,TPARM_N(b),TPARM_N(c),TPARM_N(d)) #define TPARM_2(a,b,c) tparm(a,TPARM_N(b),TPARM_N(c)) #define TPARM_1(a,b) tparm(a,TPARM_N(b)) #define TPARM_0(a) tparm(a) #else #define TPARM_8(a,b,c,d,e,f,g,h,i) TPARM_9(a,b,c,d,e,f,g,h,i,0) #define TPARM_7(a,b,c,d,e,f,g,h) TPARM_8(a,b,c,d,e,f,g,h,0) #define TPARM_6(a,b,c,d,e,f,g) TPARM_7(a,b,c,d,e,f,g,0) #define TPARM_5(a,b,c,d,e,f) TPARM_6(a,b,c,d,e,f,0) #define TPARM_4(a,b,c,d,e) TPARM_5(a,b,c,d,e,0) #define TPARM_3(a,b,c,d) TPARM_4(a,b,c,d,0) #define TPARM_2(a,b,c) TPARM_3(a,b,c,0) #define TPARM_1(a,b) TPARM_2(a,b,0) #define TPARM_1(a,b) TPARM_2(a,b,0) #define TPARM_0(a) TPARM_1(a,0) #endif #endif /* NC_TPARM_included */ ncurses_dll.h000064400000010265151027430560007241 0ustar00/**************************************************************************** * Copyright (c) 1998-2009,2014 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /* $Id: ncurses_dll.h.in,v 1.9 2014/08/02 21:30:20 tom Exp $ */ #ifndef NCURSES_DLL_H_incl #define NCURSES_DLL_H_incl 1 /* 2014-08-02 workaround for broken MinGW compiler. * Oddly, only TRACE is mapped to trace - the other -D's are okay. * suggest TDM as an alternative. */ #if defined(__MINGW64__) #elif defined(__MINGW32__) #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 8) #ifdef trace #undef trace #define TRACE #endif #endif /* broken compiler */ #endif /* MingW */ /* * For reentrant code, we map the various global variables into SCREEN by * using functions to access them. */ #define NCURSES_PUBLIC_VAR(name) _nc_##name #define NCURSES_WRAPPED_VAR(type,name) extern type NCURSES_PUBLIC_VAR(name)(void) /* no longer needed on cygwin or mingw, thanks to auto-import */ /* but this structure may be useful at some point for an MSVC build */ /* so, for now unconditionally define the important flags */ /* "the right way" for proper static and dll+auto-import behavior */ #undef NCURSES_DLL #define NCURSES_STATIC #if defined(__CYGWIN__) || defined(__MINGW32__) # if defined(NCURSES_DLL) # if defined(NCURSES_STATIC) # undef NCURSES_STATIC # endif # endif # undef NCURSES_IMPEXP # undef NCURSES_API # undef NCURSES_EXPORT # undef NCURSES_EXPORT_VAR # if defined(NCURSES_DLL) /* building a DLL */ # define NCURSES_IMPEXP __declspec(dllexport) # elif defined(NCURSES_STATIC) /* building or linking to a static library */ # define NCURSES_IMPEXP /* nothing */ # else /* linking to the DLL */ # define NCURSES_IMPEXP __declspec(dllimport) # endif # define NCURSES_API __cdecl # define NCURSES_EXPORT(type) NCURSES_IMPEXP type NCURSES_API # define NCURSES_EXPORT_VAR(type) NCURSES_IMPEXP type #endif /* Take care of non-cygwin platforms */ #if !defined(NCURSES_IMPEXP) # define NCURSES_IMPEXP /* nothing */ #endif #if !defined(NCURSES_API) # define NCURSES_API /* nothing */ #endif #if !defined(NCURSES_EXPORT) # define NCURSES_EXPORT(type) NCURSES_IMPEXP type NCURSES_API #endif #if !defined(NCURSES_EXPORT_VAR) # define NCURSES_EXPORT_VAR(type) NCURSES_IMPEXP type #endif #endif /* NCURSES_DLL_H_incl */ term_entry.h000064400000021070151027430560007110 0ustar00/**************************************************************************** * Copyright (c) 1998-2015,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim 1992,1995 * * and: Eric S. Raymond * * and: Thomas E. Dickey 1998-on * ****************************************************************************/ /* $Id: term_entry.h,v 1.55 2017/04/06 22:45:34 tom Exp $ */ /* * term_entry.h -- interface to entry-manipulation code */ #ifndef NCURSES_TERM_ENTRY_H_incl #define NCURSES_TERM_ENTRY_H_incl 1 /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif #include /* * These macros may be used by programs that know about TERMTYPE: */ #if NCURSES_XNAMES #define NUM_BOOLEANS(tp) (tp)->num_Booleans #define NUM_NUMBERS(tp) (tp)->num_Numbers #define NUM_STRINGS(tp) (tp)->num_Strings #define EXT_NAMES(tp,i,limit,index,table) (i >= limit) ? tp->ext_Names[index] : table[i] #else #define NUM_BOOLEANS(tp) BOOLCOUNT #define NUM_NUMBERS(tp) NUMCOUNT #define NUM_STRINGS(tp) STRCOUNT #define EXT_NAMES(tp,i,limit,index,table) table[i] #endif #define NUM_EXT_NAMES(tp) (unsigned) ((tp)->ext_Booleans + (tp)->ext_Numbers + (tp)->ext_Strings) #define for_each_boolean(n,tp) for(n = 0; n < NUM_BOOLEANS(tp); n++) #define for_each_number(n,tp) for(n = 0; n < NUM_NUMBERS(tp); n++) #define for_each_string(n,tp) for(n = 0; n < NUM_STRINGS(tp); n++) #if NCURSES_XNAMES #define for_each_ext_boolean(n,tp) for(n = BOOLCOUNT; (int) n < (int) NUM_BOOLEANS(tp); n++) #define for_each_ext_number(n,tp) for(n = NUMCOUNT; (int) n < (int) NUM_NUMBERS(tp); n++) #define for_each_ext_string(n,tp) for(n = STRCOUNT; (int) n < (int) NUM_STRINGS(tp); n++) #endif #define ExtBoolname(tp,i,names) EXT_NAMES(tp, i, BOOLCOUNT, (i - (tp->num_Booleans - tp->ext_Booleans)), names) #define ExtNumname(tp,i,names) EXT_NAMES(tp, i, NUMCOUNT, (i - (tp->num_Numbers - tp->ext_Numbers)) + tp->ext_Booleans, names) #define ExtStrname(tp,i,names) EXT_NAMES(tp, i, STRCOUNT, (i - (tp->num_Strings - tp->ext_Strings)) + (tp->ext_Numbers + tp->ext_Booleans), names) /* * The remaining type-definitions and macros are used only internally by the * ncurses utilities. */ #ifdef NCURSES_INTERNALS /* * see db_iterator.c - this enumeration lists the places searched for a * terminal description and defines the order in which they are searched. */ typedef enum { dbdTIC = 0, /* special, used by tic when writing entry */ #if NCURSES_USE_DATABASE dbdEnvOnce, /* the $TERMINFO environment variable */ dbdHome, /* $HOME/.terminfo */ dbdEnvList, /* the $TERMINFO_DIRS environment variable */ dbdCfgList, /* the compiled-in TERMINFO_DIRS value */ dbdCfgOnce, /* the compiled-in TERMINFO value */ #endif #if NCURSES_USE_TERMCAP dbdEnvOnce2, /* the $TERMCAP environment variable */ dbdEnvList2, /* the $TERMPATH environment variable */ dbdCfgList2, /* the compiled-in TERMPATH */ #endif dbdLAST } DBDIRS; #define MAX_USES 32 #define MAX_CROSSLINKS 16 typedef struct entry ENTRY; typedef struct { char *name; ENTRY *link; long line; } ENTRY_USES; struct entry { TERMTYPE2 tterm; unsigned nuses; ENTRY_USES uses[MAX_USES]; int ncrosslinks; ENTRY *crosslinks[MAX_CROSSLINKS]; long cstart; long cend; long startline; ENTRY *next; ENTRY *last; }; extern NCURSES_EXPORT_VAR(ENTRY *) _nc_head; extern NCURSES_EXPORT_VAR(ENTRY *) _nc_tail; #define for_entry_list(qp) for (qp = _nc_head; qp; qp = qp->next) #define MAX_LINE 132 #define NULLHOOK (bool(*)(ENTRY *))0 /* * Note that WANTED and PRESENT are not simple inverses! If a capability * has been explicitly cancelled, it's not considered WANTED. */ #define WANTED(s) ((s) == ABSENT_STRING) #define PRESENT(s) (((s) != ABSENT_STRING) && ((s) != CANCELLED_STRING)) #define ANDMISSING(p,q) \ { \ if (PRESENT(p) && !PRESENT(q)) \ _nc_warning(#p " but no " #q); \ } #define PAIRED(p,q) \ { \ if (PRESENT(q) && !PRESENT(p)) \ _nc_warning(#q " but no " #p); \ if (PRESENT(p) && !PRESENT(q)) \ _nc_warning(#p " but no " #q); \ } /* * These entrypoints are used only by the ncurses utilities such as tic. */ /* alloc_entry.c: elementary allocation code */ extern NCURSES_EXPORT(ENTRY *) _nc_copy_entry (ENTRY *oldp); extern NCURSES_EXPORT(char *) _nc_save_str (const char *const); extern NCURSES_EXPORT(void) _nc_init_entry (ENTRY *const); extern NCURSES_EXPORT(void) _nc_merge_entry (ENTRY *const, ENTRY *const); extern NCURSES_EXPORT(void) _nc_wrap_entry (ENTRY *const, bool); /* alloc_ttype.c: elementary allocation code */ extern NCURSES_EXPORT(void) _nc_align_termtype (TERMTYPE2 *, TERMTYPE2 *); /* free_ttype.c: elementary allocation code */ extern NCURSES_EXPORT(void) _nc_free_termtype2 (TERMTYPE2 *); /* lib_termcap.c: trim sgr0 string for termcap users */ extern NCURSES_EXPORT(char *) _nc_trim_sgr0 (TERMTYPE2 *); /* parse_entry.c: entry-parsing code */ #if NCURSES_XNAMES extern NCURSES_EXPORT_VAR(bool) _nc_user_definable; extern NCURSES_EXPORT_VAR(bool) _nc_disable_period; #endif extern NCURSES_EXPORT(int) _nc_parse_entry (ENTRY *, int, bool); extern NCURSES_EXPORT(int) _nc_capcmp (const char *, const char *); /* write_entry.c: writing an entry to the file system */ extern NCURSES_EXPORT(void) _nc_set_writedir (const char *); extern NCURSES_EXPORT(void) _nc_write_entry (TERMTYPE2 *const); extern NCURSES_EXPORT(int) _nc_write_object (TERMTYPE2 *, char *, unsigned *, unsigned); /* comp_parse.c: entry list handling */ extern NCURSES_EXPORT(void) _nc_read_entry_source (FILE*, char*, int, bool, bool (*)(ENTRY*)); extern NCURSES_EXPORT(bool) _nc_entry_match (char *, char *); extern NCURSES_EXPORT(int) _nc_resolve_uses (bool); /* obs 20040705 */ extern NCURSES_EXPORT(int) _nc_resolve_uses2 (bool, bool); extern NCURSES_EXPORT(void) _nc_free_entries (ENTRY *); extern NCURSES_IMPEXP void NCURSES_API (*_nc_check_termtype)(TERMTYPE *); /* obs 20040705 */ extern NCURSES_IMPEXP void NCURSES_API (*_nc_check_termtype2)(TERMTYPE2 *, bool); /* trace_xnames.c */ extern NCURSES_EXPORT(void) _nc_trace_xnames (TERMTYPE *); #endif /* NCURSES_INTERNALS */ /* * These entrypoints are used by tack. */ /* alloc_ttype.c: elementary allocation code */ extern NCURSES_EXPORT(void) _nc_copy_termtype (TERMTYPE *, const TERMTYPE *); /* lib_acs.c */ extern NCURSES_EXPORT(void) _nc_init_acs (void); /* corresponds to traditional 'init_acs()' */ /* free_ttype.c: elementary allocation code */ extern NCURSES_EXPORT(void) _nc_free_termtype (TERMTYPE *); #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* NCURSES_TERM_ENTRY_H_incl */ term.h000064400000120346151027430560005675 0ustar00/**************************************************************************** * Copyright (c) 1998-2013,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /****************************************************************************/ /* Author: Zeyd M. Ben-Halim 1992,1995 */ /* and: Eric S. Raymond */ /* and: Thomas E. Dickey 1995-on */ /****************************************************************************/ /* $Id: MKterm.h.awk.in,v 1.67 2017/04/06 00:19:26 tom Exp $ */ /* ** term.h -- Definition of struct term */ #ifndef NCURSES_TERM_H_incl #define NCURSES_TERM_H_incl 1 #undef NCURSES_VERSION #define NCURSES_VERSION "6.1" #include #ifdef __cplusplus extern "C" { #endif /* Make this file self-contained by providing defaults for the HAVE_TERMIO[S]_H * definition (based on the system for which this was configured). */ #undef NCURSES_CONST #define NCURSES_CONST const #undef NCURSES_SBOOL #define NCURSES_SBOOL char #undef NCURSES_USE_DATABASE #define NCURSES_USE_DATABASE 1 #undef NCURSES_USE_TERMCAP #define NCURSES_USE_TERMCAP 0 #undef NCURSES_XNAMES #define NCURSES_XNAMES 1 /* We will use these symbols to hide differences between * termios/termio/sgttyb interfaces. */ #undef TTY #undef SET_TTY #undef GET_TTY /* Assume POSIX termio if we have the header and function */ /* #if HAVE_TERMIOS_H && HAVE_TCGETATTR */ #if 1 && 1 #undef TERMIOS #define TERMIOS 1 #include #define TTY struct termios #else /* !HAVE_TERMIOS_H */ /* #if HAVE_TERMIO_H */ #if 1 #undef TERMIOS #define TERMIOS 1 #include #define TTY struct termio #else /* !HAVE_TERMIO_H */ #if __MINGW32__ # include # define TTY struct termios #else #undef TERMIOS #include #include #define TTY struct sgttyb #endif /* MINGW32 */ #endif /* HAVE_TERMIO_H */ #endif /* HAVE_TERMIOS_H */ #ifdef TERMIOS #define GET_TTY(fd, buf) tcgetattr(fd, buf) #define SET_TTY(fd, buf) tcsetattr(fd, TCSADRAIN, buf) #else #define GET_TTY(fd, buf) gtty(fd, buf) #define SET_TTY(fd, buf) stty(fd, buf) #endif #define NAMESIZE 256 /* The cast works because TERMTYPE is the first data in TERMINAL */ #define CUR ((TERMTYPE *)(cur_term))-> #define auto_left_margin CUR Booleans[0] #define auto_right_margin CUR Booleans[1] #define no_esc_ctlc CUR Booleans[2] #define ceol_standout_glitch CUR Booleans[3] #define eat_newline_glitch CUR Booleans[4] #define erase_overstrike CUR Booleans[5] #define generic_type CUR Booleans[6] #define hard_copy CUR Booleans[7] #define has_meta_key CUR Booleans[8] #define has_status_line CUR Booleans[9] #define insert_null_glitch CUR Booleans[10] #define memory_above CUR Booleans[11] #define memory_below CUR Booleans[12] #define move_insert_mode CUR Booleans[13] #define move_standout_mode CUR Booleans[14] #define over_strike CUR Booleans[15] #define status_line_esc_ok CUR Booleans[16] #define dest_tabs_magic_smso CUR Booleans[17] #define tilde_glitch CUR Booleans[18] #define transparent_underline CUR Booleans[19] #define xon_xoff CUR Booleans[20] #define needs_xon_xoff CUR Booleans[21] #define prtr_silent CUR Booleans[22] #define hard_cursor CUR Booleans[23] #define non_rev_rmcup CUR Booleans[24] #define no_pad_char CUR Booleans[25] #define non_dest_scroll_region CUR Booleans[26] #define can_change CUR Booleans[27] #define back_color_erase CUR Booleans[28] #define hue_lightness_saturation CUR Booleans[29] #define col_addr_glitch CUR Booleans[30] #define cr_cancels_micro_mode CUR Booleans[31] #define has_print_wheel CUR Booleans[32] #define row_addr_glitch CUR Booleans[33] #define semi_auto_right_margin CUR Booleans[34] #define cpi_changes_res CUR Booleans[35] #define lpi_changes_res CUR Booleans[36] #define columns CUR Numbers[0] #define init_tabs CUR Numbers[1] #define lines CUR Numbers[2] #define lines_of_memory CUR Numbers[3] #define magic_cookie_glitch CUR Numbers[4] #define padding_baud_rate CUR Numbers[5] #define virtual_terminal CUR Numbers[6] #define width_status_line CUR Numbers[7] #define num_labels CUR Numbers[8] #define label_height CUR Numbers[9] #define label_width CUR Numbers[10] #define max_attributes CUR Numbers[11] #define maximum_windows CUR Numbers[12] #define max_colors CUR Numbers[13] #define max_pairs CUR Numbers[14] #define no_color_video CUR Numbers[15] #define buffer_capacity CUR Numbers[16] #define dot_vert_spacing CUR Numbers[17] #define dot_horz_spacing CUR Numbers[18] #define max_micro_address CUR Numbers[19] #define max_micro_jump CUR Numbers[20] #define micro_col_size CUR Numbers[21] #define micro_line_size CUR Numbers[22] #define number_of_pins CUR Numbers[23] #define output_res_char CUR Numbers[24] #define output_res_line CUR Numbers[25] #define output_res_horz_inch CUR Numbers[26] #define output_res_vert_inch CUR Numbers[27] #define print_rate CUR Numbers[28] #define wide_char_size CUR Numbers[29] #define buttons CUR Numbers[30] #define bit_image_entwining CUR Numbers[31] #define bit_image_type CUR Numbers[32] #define back_tab CUR Strings[0] #define bell CUR Strings[1] #define carriage_return CUR Strings[2] #define change_scroll_region CUR Strings[3] #define clear_all_tabs CUR Strings[4] #define clear_screen CUR Strings[5] #define clr_eol CUR Strings[6] #define clr_eos CUR Strings[7] #define column_address CUR Strings[8] #define command_character CUR Strings[9] #define cursor_address CUR Strings[10] #define cursor_down CUR Strings[11] #define cursor_home CUR Strings[12] #define cursor_invisible CUR Strings[13] #define cursor_left CUR Strings[14] #define cursor_mem_address CUR Strings[15] #define cursor_normal CUR Strings[16] #define cursor_right CUR Strings[17] #define cursor_to_ll CUR Strings[18] #define cursor_up CUR Strings[19] #define cursor_visible CUR Strings[20] #define delete_character CUR Strings[21] #define delete_line CUR Strings[22] #define dis_status_line CUR Strings[23] #define down_half_line CUR Strings[24] #define enter_alt_charset_mode CUR Strings[25] #define enter_blink_mode CUR Strings[26] #define enter_bold_mode CUR Strings[27] #define enter_ca_mode CUR Strings[28] #define enter_delete_mode CUR Strings[29] #define enter_dim_mode CUR Strings[30] #define enter_insert_mode CUR Strings[31] #define enter_secure_mode CUR Strings[32] #define enter_protected_mode CUR Strings[33] #define enter_reverse_mode CUR Strings[34] #define enter_standout_mode CUR Strings[35] #define enter_underline_mode CUR Strings[36] #define erase_chars CUR Strings[37] #define exit_alt_charset_mode CUR Strings[38] #define exit_attribute_mode CUR Strings[39] #define exit_ca_mode CUR Strings[40] #define exit_delete_mode CUR Strings[41] #define exit_insert_mode CUR Strings[42] #define exit_standout_mode CUR Strings[43] #define exit_underline_mode CUR Strings[44] #define flash_screen CUR Strings[45] #define form_feed CUR Strings[46] #define from_status_line CUR Strings[47] #define init_1string CUR Strings[48] #define init_2string CUR Strings[49] #define init_3string CUR Strings[50] #define init_file CUR Strings[51] #define insert_character CUR Strings[52] #define insert_line CUR Strings[53] #define insert_padding CUR Strings[54] #define key_backspace CUR Strings[55] #define key_catab CUR Strings[56] #define key_clear CUR Strings[57] #define key_ctab CUR Strings[58] #define key_dc CUR Strings[59] #define key_dl CUR Strings[60] #define key_down CUR Strings[61] #define key_eic CUR Strings[62] #define key_eol CUR Strings[63] #define key_eos CUR Strings[64] #define key_f0 CUR Strings[65] #define key_f1 CUR Strings[66] #define key_f10 CUR Strings[67] #define key_f2 CUR Strings[68] #define key_f3 CUR Strings[69] #define key_f4 CUR Strings[70] #define key_f5 CUR Strings[71] #define key_f6 CUR Strings[72] #define key_f7 CUR Strings[73] #define key_f8 CUR Strings[74] #define key_f9 CUR Strings[75] #define key_home CUR Strings[76] #define key_ic CUR Strings[77] #define key_il CUR Strings[78] #define key_left CUR Strings[79] #define key_ll CUR Strings[80] #define key_npage CUR Strings[81] #define key_ppage CUR Strings[82] #define key_right CUR Strings[83] #define key_sf CUR Strings[84] #define key_sr CUR Strings[85] #define key_stab CUR Strings[86] #define key_up CUR Strings[87] #define keypad_local CUR Strings[88] #define keypad_xmit CUR Strings[89] #define lab_f0 CUR Strings[90] #define lab_f1 CUR Strings[91] #define lab_f10 CUR Strings[92] #define lab_f2 CUR Strings[93] #define lab_f3 CUR Strings[94] #define lab_f4 CUR Strings[95] #define lab_f5 CUR Strings[96] #define lab_f6 CUR Strings[97] #define lab_f7 CUR Strings[98] #define lab_f8 CUR Strings[99] #define lab_f9 CUR Strings[100] #define meta_off CUR Strings[101] #define meta_on CUR Strings[102] #define newline CUR Strings[103] #define pad_char CUR Strings[104] #define parm_dch CUR Strings[105] #define parm_delete_line CUR Strings[106] #define parm_down_cursor CUR Strings[107] #define parm_ich CUR Strings[108] #define parm_index CUR Strings[109] #define parm_insert_line CUR Strings[110] #define parm_left_cursor CUR Strings[111] #define parm_right_cursor CUR Strings[112] #define parm_rindex CUR Strings[113] #define parm_up_cursor CUR Strings[114] #define pkey_key CUR Strings[115] #define pkey_local CUR Strings[116] #define pkey_xmit CUR Strings[117] #define print_screen CUR Strings[118] #define prtr_off CUR Strings[119] #define prtr_on CUR Strings[120] #define repeat_char CUR Strings[121] #define reset_1string CUR Strings[122] #define reset_2string CUR Strings[123] #define reset_3string CUR Strings[124] #define reset_file CUR Strings[125] #define restore_cursor CUR Strings[126] #define row_address CUR Strings[127] #define save_cursor CUR Strings[128] #define scroll_forward CUR Strings[129] #define scroll_reverse CUR Strings[130] #define set_attributes CUR Strings[131] #define set_tab CUR Strings[132] #define set_window CUR Strings[133] #define tab CUR Strings[134] #define to_status_line CUR Strings[135] #define underline_char CUR Strings[136] #define up_half_line CUR Strings[137] #define init_prog CUR Strings[138] #define key_a1 CUR Strings[139] #define key_a3 CUR Strings[140] #define key_b2 CUR Strings[141] #define key_c1 CUR Strings[142] #define key_c3 CUR Strings[143] #define prtr_non CUR Strings[144] #define char_padding CUR Strings[145] #define acs_chars CUR Strings[146] #define plab_norm CUR Strings[147] #define key_btab CUR Strings[148] #define enter_xon_mode CUR Strings[149] #define exit_xon_mode CUR Strings[150] #define enter_am_mode CUR Strings[151] #define exit_am_mode CUR Strings[152] #define xon_character CUR Strings[153] #define xoff_character CUR Strings[154] #define ena_acs CUR Strings[155] #define label_on CUR Strings[156] #define label_off CUR Strings[157] #define key_beg CUR Strings[158] #define key_cancel CUR Strings[159] #define key_close CUR Strings[160] #define key_command CUR Strings[161] #define key_copy CUR Strings[162] #define key_create CUR Strings[163] #define key_end CUR Strings[164] #define key_enter CUR Strings[165] #define key_exit CUR Strings[166] #define key_find CUR Strings[167] #define key_help CUR Strings[168] #define key_mark CUR Strings[169] #define key_message CUR Strings[170] #define key_move CUR Strings[171] #define key_next CUR Strings[172] #define key_open CUR Strings[173] #define key_options CUR Strings[174] #define key_previous CUR Strings[175] #define key_print CUR Strings[176] #define key_redo CUR Strings[177] #define key_reference CUR Strings[178] #define key_refresh CUR Strings[179] #define key_replace CUR Strings[180] #define key_restart CUR Strings[181] #define key_resume CUR Strings[182] #define key_save CUR Strings[183] #define key_suspend CUR Strings[184] #define key_undo CUR Strings[185] #define key_sbeg CUR Strings[186] #define key_scancel CUR Strings[187] #define key_scommand CUR Strings[188] #define key_scopy CUR Strings[189] #define key_screate CUR Strings[190] #define key_sdc CUR Strings[191] #define key_sdl CUR Strings[192] #define key_select CUR Strings[193] #define key_send CUR Strings[194] #define key_seol CUR Strings[195] #define key_sexit CUR Strings[196] #define key_sfind CUR Strings[197] #define key_shelp CUR Strings[198] #define key_shome CUR Strings[199] #define key_sic CUR Strings[200] #define key_sleft CUR Strings[201] #define key_smessage CUR Strings[202] #define key_smove CUR Strings[203] #define key_snext CUR Strings[204] #define key_soptions CUR Strings[205] #define key_sprevious CUR Strings[206] #define key_sprint CUR Strings[207] #define key_sredo CUR Strings[208] #define key_sreplace CUR Strings[209] #define key_sright CUR Strings[210] #define key_srsume CUR Strings[211] #define key_ssave CUR Strings[212] #define key_ssuspend CUR Strings[213] #define key_sundo CUR Strings[214] #define req_for_input CUR Strings[215] #define key_f11 CUR Strings[216] #define key_f12 CUR Strings[217] #define key_f13 CUR Strings[218] #define key_f14 CUR Strings[219] #define key_f15 CUR Strings[220] #define key_f16 CUR Strings[221] #define key_f17 CUR Strings[222] #define key_f18 CUR Strings[223] #define key_f19 CUR Strings[224] #define key_f20 CUR Strings[225] #define key_f21 CUR Strings[226] #define key_f22 CUR Strings[227] #define key_f23 CUR Strings[228] #define key_f24 CUR Strings[229] #define key_f25 CUR Strings[230] #define key_f26 CUR Strings[231] #define key_f27 CUR Strings[232] #define key_f28 CUR Strings[233] #define key_f29 CUR Strings[234] #define key_f30 CUR Strings[235] #define key_f31 CUR Strings[236] #define key_f32 CUR Strings[237] #define key_f33 CUR Strings[238] #define key_f34 CUR Strings[239] #define key_f35 CUR Strings[240] #define key_f36 CUR Strings[241] #define key_f37 CUR Strings[242] #define key_f38 CUR Strings[243] #define key_f39 CUR Strings[244] #define key_f40 CUR Strings[245] #define key_f41 CUR Strings[246] #define key_f42 CUR Strings[247] #define key_f43 CUR Strings[248] #define key_f44 CUR Strings[249] #define key_f45 CUR Strings[250] #define key_f46 CUR Strings[251] #define key_f47 CUR Strings[252] #define key_f48 CUR Strings[253] #define key_f49 CUR Strings[254] #define key_f50 CUR Strings[255] #define key_f51 CUR Strings[256] #define key_f52 CUR Strings[257] #define key_f53 CUR Strings[258] #define key_f54 CUR Strings[259] #define key_f55 CUR Strings[260] #define key_f56 CUR Strings[261] #define key_f57 CUR Strings[262] #define key_f58 CUR Strings[263] #define key_f59 CUR Strings[264] #define key_f60 CUR Strings[265] #define key_f61 CUR Strings[266] #define key_f62 CUR Strings[267] #define key_f63 CUR Strings[268] #define clr_bol CUR Strings[269] #define clear_margins CUR Strings[270] #define set_left_margin CUR Strings[271] #define set_right_margin CUR Strings[272] #define label_format CUR Strings[273] #define set_clock CUR Strings[274] #define display_clock CUR Strings[275] #define remove_clock CUR Strings[276] #define create_window CUR Strings[277] #define goto_window CUR Strings[278] #define hangup CUR Strings[279] #define dial_phone CUR Strings[280] #define quick_dial CUR Strings[281] #define tone CUR Strings[282] #define pulse CUR Strings[283] #define flash_hook CUR Strings[284] #define fixed_pause CUR Strings[285] #define wait_tone CUR Strings[286] #define user0 CUR Strings[287] #define user1 CUR Strings[288] #define user2 CUR Strings[289] #define user3 CUR Strings[290] #define user4 CUR Strings[291] #define user5 CUR Strings[292] #define user6 CUR Strings[293] #define user7 CUR Strings[294] #define user8 CUR Strings[295] #define user9 CUR Strings[296] #define orig_pair CUR Strings[297] #define orig_colors CUR Strings[298] #define initialize_color CUR Strings[299] #define initialize_pair CUR Strings[300] #define set_color_pair CUR Strings[301] #define set_foreground CUR Strings[302] #define set_background CUR Strings[303] #define change_char_pitch CUR Strings[304] #define change_line_pitch CUR Strings[305] #define change_res_horz CUR Strings[306] #define change_res_vert CUR Strings[307] #define define_char CUR Strings[308] #define enter_doublewide_mode CUR Strings[309] #define enter_draft_quality CUR Strings[310] #define enter_italics_mode CUR Strings[311] #define enter_leftward_mode CUR Strings[312] #define enter_micro_mode CUR Strings[313] #define enter_near_letter_quality CUR Strings[314] #define enter_normal_quality CUR Strings[315] #define enter_shadow_mode CUR Strings[316] #define enter_subscript_mode CUR Strings[317] #define enter_superscript_mode CUR Strings[318] #define enter_upward_mode CUR Strings[319] #define exit_doublewide_mode CUR Strings[320] #define exit_italics_mode CUR Strings[321] #define exit_leftward_mode CUR Strings[322] #define exit_micro_mode CUR Strings[323] #define exit_shadow_mode CUR Strings[324] #define exit_subscript_mode CUR Strings[325] #define exit_superscript_mode CUR Strings[326] #define exit_upward_mode CUR Strings[327] #define micro_column_address CUR Strings[328] #define micro_down CUR Strings[329] #define micro_left CUR Strings[330] #define micro_right CUR Strings[331] #define micro_row_address CUR Strings[332] #define micro_up CUR Strings[333] #define order_of_pins CUR Strings[334] #define parm_down_micro CUR Strings[335] #define parm_left_micro CUR Strings[336] #define parm_right_micro CUR Strings[337] #define parm_up_micro CUR Strings[338] #define select_char_set CUR Strings[339] #define set_bottom_margin CUR Strings[340] #define set_bottom_margin_parm CUR Strings[341] #define set_left_margin_parm CUR Strings[342] #define set_right_margin_parm CUR Strings[343] #define set_top_margin CUR Strings[344] #define set_top_margin_parm CUR Strings[345] #define start_bit_image CUR Strings[346] #define start_char_set_def CUR Strings[347] #define stop_bit_image CUR Strings[348] #define stop_char_set_def CUR Strings[349] #define subscript_characters CUR Strings[350] #define superscript_characters CUR Strings[351] #define these_cause_cr CUR Strings[352] #define zero_motion CUR Strings[353] #define char_set_names CUR Strings[354] #define key_mouse CUR Strings[355] #define mouse_info CUR Strings[356] #define req_mouse_pos CUR Strings[357] #define get_mouse CUR Strings[358] #define set_a_foreground CUR Strings[359] #define set_a_background CUR Strings[360] #define pkey_plab CUR Strings[361] #define device_type CUR Strings[362] #define code_set_init CUR Strings[363] #define set0_des_seq CUR Strings[364] #define set1_des_seq CUR Strings[365] #define set2_des_seq CUR Strings[366] #define set3_des_seq CUR Strings[367] #define set_lr_margin CUR Strings[368] #define set_tb_margin CUR Strings[369] #define bit_image_repeat CUR Strings[370] #define bit_image_newline CUR Strings[371] #define bit_image_carriage_return CUR Strings[372] #define color_names CUR Strings[373] #define define_bit_image_region CUR Strings[374] #define end_bit_image_region CUR Strings[375] #define set_color_band CUR Strings[376] #define set_page_length CUR Strings[377] #define display_pc_char CUR Strings[378] #define enter_pc_charset_mode CUR Strings[379] #define exit_pc_charset_mode CUR Strings[380] #define enter_scancode_mode CUR Strings[381] #define exit_scancode_mode CUR Strings[382] #define pc_term_options CUR Strings[383] #define scancode_escape CUR Strings[384] #define alt_scancode_esc CUR Strings[385] #define enter_horizontal_hl_mode CUR Strings[386] #define enter_left_hl_mode CUR Strings[387] #define enter_low_hl_mode CUR Strings[388] #define enter_right_hl_mode CUR Strings[389] #define enter_top_hl_mode CUR Strings[390] #define enter_vertical_hl_mode CUR Strings[391] #define set_a_attributes CUR Strings[392] #define set_pglen_inch CUR Strings[393] #define BOOLWRITE 37 #define NUMWRITE 33 #define STRWRITE 394 /* older synonyms for some capabilities */ #define beehive_glitch no_esc_ctlc #define teleray_glitch dest_tabs_magic_smso #define micro_char_size micro_col_size #ifdef __INTERNAL_CAPS_VISIBLE #define termcap_init2 CUR Strings[394] #define termcap_reset CUR Strings[395] #define magic_cookie_glitch_ul CUR Numbers[33] #define backspaces_with_bs CUR Booleans[37] #define crt_no_scrolling CUR Booleans[38] #define no_correctly_working_cr CUR Booleans[39] #define carriage_return_delay CUR Numbers[34] #define new_line_delay CUR Numbers[35] #define linefeed_if_not_lf CUR Strings[396] #define backspace_if_not_bs CUR Strings[397] #define gnu_has_meta_key CUR Booleans[40] #define linefeed_is_newline CUR Booleans[41] #define backspace_delay CUR Numbers[36] #define horizontal_tab_delay CUR Numbers[37] #define number_of_function_keys CUR Numbers[38] #define other_non_function_keys CUR Strings[398] #define arrow_key_map CUR Strings[399] #define has_hardware_tabs CUR Booleans[42] #define return_does_clr_eol CUR Booleans[43] #define acs_ulcorner CUR Strings[400] #define acs_llcorner CUR Strings[401] #define acs_urcorner CUR Strings[402] #define acs_lrcorner CUR Strings[403] #define acs_ltee CUR Strings[404] #define acs_rtee CUR Strings[405] #define acs_btee CUR Strings[406] #define acs_ttee CUR Strings[407] #define acs_hline CUR Strings[408] #define acs_vline CUR Strings[409] #define acs_plus CUR Strings[410] #define memory_lock CUR Strings[411] #define memory_unlock CUR Strings[412] #define box_chars_1 CUR Strings[413] #endif /* __INTERNAL_CAPS_VISIBLE */ /* * Predefined terminfo array sizes */ #define BOOLCOUNT 44 #define NUMCOUNT 39 #define STRCOUNT 414 /* used by code for comparing entries */ #define acs_chars_index 146 typedef struct termtype { /* in-core form of terminfo data */ char *term_names; /* str_table offset of term names */ char *str_table; /* pointer to string table */ NCURSES_SBOOL *Booleans; /* array of boolean values */ short *Numbers; /* array of integer values */ char **Strings; /* array of string offsets */ #if NCURSES_XNAMES char *ext_str_table; /* pointer to extended string table */ char **ext_Names; /* corresponding names */ unsigned short num_Booleans;/* count total Booleans */ unsigned short num_Numbers; /* count total Numbers */ unsigned short num_Strings; /* count total Strings */ unsigned short ext_Booleans;/* count extensions to Booleans */ unsigned short ext_Numbers; /* count extensions to Numbers */ unsigned short ext_Strings; /* count extensions to Strings */ #endif /* NCURSES_XNAMES */ } TERMTYPE; /* * The only reason these structures are visible is for read-only use. * Programs which modify the data are not, never were, portable across * curses implementations. */ #ifdef NCURSES_INTERNALS typedef struct termtype2 { /* in-core form of terminfo data */ char *term_names; /* str_table offset of term names */ char *str_table; /* pointer to string table */ NCURSES_SBOOL *Booleans; /* array of boolean values */ int *Numbers; /* array of integer values */ char **Strings; /* array of string offsets */ #if NCURSES_XNAMES char *ext_str_table; /* pointer to extended string table */ char **ext_Names; /* corresponding names */ unsigned short num_Booleans;/* count total Booleans */ unsigned short num_Numbers; /* count total Numbers */ unsigned short num_Strings; /* count total Strings */ unsigned short ext_Booleans;/* count extensions to Booleans */ unsigned short ext_Numbers; /* count extensions to Numbers */ unsigned short ext_Strings; /* count extensions to Strings */ #endif /* NCURSES_XNAMES */ } TERMTYPE2; typedef struct term { /* describe an actual terminal */ TERMTYPE type; /* terminal type description */ short Filedes; /* file description being written to */ TTY Ottyb; /* original state of the terminal */ TTY Nttyb; /* current state of the terminal */ int _baudrate; /* used to compute padding */ char * _termname; /* used for termname() */ TERMTYPE2 type2; /* extended terminal type description */ } TERMINAL; #else typedef struct term TERMINAL; #endif /* NCURSES_INTERNALS */ #if 0 && !0 extern NCURSES_EXPORT_VAR(TERMINAL *) cur_term; #elif 0 NCURSES_WRAPPED_VAR(TERMINAL *, cur_term); #define cur_term NCURSES_PUBLIC_VAR(cur_term()) #else extern NCURSES_EXPORT_VAR(TERMINAL *) cur_term; #endif #if 0 || 0 NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, boolnames); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, boolcodes); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, boolfnames); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, numnames); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, numcodes); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, numfnames); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, strnames); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, strcodes); NCURSES_WRAPPED_VAR(NCURSES_CONST char * const *, strfnames); #define boolnames NCURSES_PUBLIC_VAR(boolnames()) #define boolcodes NCURSES_PUBLIC_VAR(boolcodes()) #define boolfnames NCURSES_PUBLIC_VAR(boolfnames()) #define numnames NCURSES_PUBLIC_VAR(numnames()) #define numcodes NCURSES_PUBLIC_VAR(numcodes()) #define numfnames NCURSES_PUBLIC_VAR(numfnames()) #define strnames NCURSES_PUBLIC_VAR(strnames()) #define strcodes NCURSES_PUBLIC_VAR(strcodes()) #define strfnames NCURSES_PUBLIC_VAR(strfnames()) #else extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) boolnames[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) boolcodes[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) boolfnames[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) numnames[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) numcodes[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) numfnames[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) strnames[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) strcodes[]; extern NCURSES_EXPORT_VAR(NCURSES_CONST char * const ) strfnames[]; #endif /* * These entrypoints are used only by the ncurses utilities such as tic. */ #ifdef NCURSES_INTERNALS extern NCURSES_EXPORT(int) _nc_set_tty_mode (TTY *buf); extern NCURSES_EXPORT(int) _nc_read_entry2 (const char * const, char * const, TERMTYPE2 *const); extern NCURSES_EXPORT(int) _nc_read_file_entry (const char *const, TERMTYPE2 *); extern NCURSES_EXPORT(int) _nc_read_termtype (TERMTYPE2 *, char *, int); extern NCURSES_EXPORT(char *) _nc_first_name (const char *const); extern NCURSES_EXPORT(int) _nc_name_match (const char *const, const char *const, const char *const); #endif /* NCURSES_INTERNALS */ /* * These entrypoints are used by tack. */ extern NCURSES_EXPORT(const TERMTYPE *) _nc_fallback (const char *); extern NCURSES_EXPORT(int) _nc_read_entry (const char * const, char * const, TERMTYPE *const); /* Normal entry points */ extern NCURSES_EXPORT(TERMINAL *) set_curterm (TERMINAL *); extern NCURSES_EXPORT(int) del_curterm (TERMINAL *); /* miscellaneous entry points */ extern NCURSES_EXPORT(int) restartterm (NCURSES_CONST char *, int, int *); extern NCURSES_EXPORT(int) setupterm (NCURSES_CONST char *,int,int *); /* terminfo entry points, also declared in curses.h */ #if !defined(__NCURSES_H) extern NCURSES_EXPORT(char *) tigetstr (NCURSES_CONST char *); extern NCURSES_EXPORT_VAR(char) ttytype[]; extern NCURSES_EXPORT(int) putp (const char *); extern NCURSES_EXPORT(int) tigetflag (NCURSES_CONST char *); extern NCURSES_EXPORT(int) tigetnum (NCURSES_CONST char *); #if 1 /* NCURSES_TPARM_VARARGS */ extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, ...); /* special */ #else extern NCURSES_EXPORT(char *) tparm (NCURSES_CONST char *, long,long,long,long,long,long,long,long,long); /* special */ extern NCURSES_EXPORT(char *) tparm_varargs (NCURSES_CONST char *, ...); /* special */ #endif extern NCURSES_EXPORT(char *) tiparm (const char *, ...); /* special */ #endif /* __NCURSES_H */ /* termcap database emulation (XPG4 uses const only for 2nd param of tgetent) */ #if !defined(NCURSES_TERMCAP_H_incl) extern NCURSES_EXPORT(char *) tgetstr (NCURSES_CONST char *, char **); extern NCURSES_EXPORT(char *) tgoto (const char *, int, int); extern NCURSES_EXPORT(int) tgetent (char *, const char *); extern NCURSES_EXPORT(int) tgetflag (NCURSES_CONST char *); extern NCURSES_EXPORT(int) tgetnum (NCURSES_CONST char *); extern NCURSES_EXPORT(int) tputs (const char *, int, int (*)(int)); #endif /* NCURSES_TERMCAP_H_incl */ /* * Include curses.h before term.h to enable these extensions. */ #if defined(NCURSES_SP_FUNCS) && (NCURSES_SP_FUNCS != 0) extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tigetstr) (SCREEN*, NCURSES_CONST char *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(putp) (SCREEN*, const char *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tigetflag) (SCREEN*, NCURSES_CONST char *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tigetnum) (SCREEN*, NCURSES_CONST char *); #if 1 /* NCURSES_TPARM_VARARGS */ extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tparm) (SCREEN*, NCURSES_CONST char *, ...); /* special */ #else extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tparm) (SCREEN*, NCURSES_CONST char *, long,long,long,long,long,long,long,long,long); /* special */ extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tparm_varargs) (SCREEN*, NCURSES_CONST char *, ...); /* special */ #endif /* termcap database emulation (XPG4 uses const only for 2nd param of tgetent) */ extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tgetstr) (SCREEN*, NCURSES_CONST char *, char **); extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(tgoto) (SCREEN*, const char *, int, int); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tgetent) (SCREEN*, char *, const char *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tgetflag) (SCREEN*, NCURSES_CONST char *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tgetnum) (SCREEN*, NCURSES_CONST char *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(tputs) (SCREEN*, const char *, int, NCURSES_SP_OUTC); extern NCURSES_EXPORT(TERMINAL *) NCURSES_SP_NAME(set_curterm) (SCREEN*, TERMINAL *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(del_curterm) (SCREEN*, TERMINAL *); extern NCURSES_EXPORT(int) NCURSES_SP_NAME(restartterm) (SCREEN*, NCURSES_CONST char *, int, int *); #endif /* NCURSES_SP_FUNCS */ #ifdef __cplusplus } #endif #endif /* NCURSES_TERM_H_incl */ menu.h000064400000027645151027430560005702 0ustar00/**************************************************************************** * Copyright (c) 1998-2016,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1995,1997 * ****************************************************************************/ /* $Id: menu.h,v 1.23 2017/02/11 16:54:04 tom Exp $ */ #ifndef ETI_MENU #define ETI_MENU #ifdef AMIGA #define TEXT TEXT_ncurses #endif #include #include #ifdef __cplusplus extern "C" { #endif typedef int Menu_Options; typedef int Item_Options; /* Menu options: */ #define O_ONEVALUE (0x01) #define O_SHOWDESC (0x02) #define O_ROWMAJOR (0x04) #define O_IGNORECASE (0x08) #define O_SHOWMATCH (0x10) #define O_NONCYCLIC (0x20) #define O_MOUSE_MENU (0x40) /* Item options: */ #define O_SELECTABLE (0x01) #if !NCURSES_OPAQUE_MENU typedef struct { const char* str; unsigned short length; } TEXT; #endif /* !NCURSES_OPAQUE_MENU */ struct tagMENU; typedef struct tagITEM #if !NCURSES_OPAQUE_MENU { TEXT name; /* name of menu item */ TEXT description; /* description of item, optional in display */ struct tagMENU *imenu; /* Pointer to parent menu */ void *userptr; /* Pointer to user defined per item data */ Item_Options opt; /* Item options */ short index; /* Item number if connected to a menu */ short y; /* y and x location of item in menu */ short x; bool value; /* Selection value */ struct tagITEM *left; /* neighbor items */ struct tagITEM *right; struct tagITEM *up; struct tagITEM *down; } #endif /* !NCURSES_OPAQUE_MENU */ ITEM; typedef void (*Menu_Hook)(struct tagMENU *); typedef struct tagMENU #if 1 /* not yet: !NCURSES_OPAQUE_MENU */ { short height; /* Nr. of chars high */ short width; /* Nr. of chars wide */ short rows; /* Nr. of items high */ short cols; /* Nr. of items wide */ short frows; /* Nr. of formatted items high */ short fcols; /* Nr. of formatted items wide */ short arows; /* Nr. of items high (actual) */ short namelen; /* Max. name length */ short desclen; /* Max. description length */ short marklen; /* Length of mark, if any */ short itemlen; /* Length of one item */ short spc_desc; /* Spacing for descriptor */ short spc_cols; /* Spacing for columns */ short spc_rows; /* Spacing for rows */ char *pattern; /* Buffer to store match chars */ short pindex; /* Index into pattern buffer */ WINDOW *win; /* Window containing menu */ WINDOW *sub; /* Subwindow for menu display */ WINDOW *userwin; /* User's window */ WINDOW *usersub; /* User's subwindow */ ITEM **items; /* array of items */ short nitems; /* Nr. of items in menu */ ITEM *curitem; /* Current item */ short toprow; /* Top row of menu */ chtype fore; /* Selection attribute */ chtype back; /* Nonselection attribute */ chtype grey; /* Inactive attribute */ unsigned char pad; /* Pad character */ Menu_Hook menuinit; /* User hooks */ Menu_Hook menuterm; Menu_Hook iteminit; Menu_Hook itemterm; void *userptr; /* Pointer to menus user data */ char *mark; /* Pointer to marker string */ Menu_Options opt; /* Menu options */ unsigned short status; /* Internal state of menu */ } #endif /* !NCURSES_OPAQUE_MENU */ MENU; /* Define keys */ #define REQ_LEFT_ITEM (KEY_MAX + 1) #define REQ_RIGHT_ITEM (KEY_MAX + 2) #define REQ_UP_ITEM (KEY_MAX + 3) #define REQ_DOWN_ITEM (KEY_MAX + 4) #define REQ_SCR_ULINE (KEY_MAX + 5) #define REQ_SCR_DLINE (KEY_MAX + 6) #define REQ_SCR_DPAGE (KEY_MAX + 7) #define REQ_SCR_UPAGE (KEY_MAX + 8) #define REQ_FIRST_ITEM (KEY_MAX + 9) #define REQ_LAST_ITEM (KEY_MAX + 10) #define REQ_NEXT_ITEM (KEY_MAX + 11) #define REQ_PREV_ITEM (KEY_MAX + 12) #define REQ_TOGGLE_ITEM (KEY_MAX + 13) #define REQ_CLEAR_PATTERN (KEY_MAX + 14) #define REQ_BACK_PATTERN (KEY_MAX + 15) #define REQ_NEXT_MATCH (KEY_MAX + 16) #define REQ_PREV_MATCH (KEY_MAX + 17) #define MIN_MENU_COMMAND (KEY_MAX + 1) #define MAX_MENU_COMMAND (KEY_MAX + 17) /* * Some AT&T code expects MAX_COMMAND to be out-of-band not * just for menu commands but for forms ones as well. */ #if defined(MAX_COMMAND) # if (MAX_MENU_COMMAND > MAX_COMMAND) # error Something is wrong -- MAX_MENU_COMMAND is greater than MAX_COMMAND # elif (MAX_COMMAND != (KEY_MAX + 128)) # error Something is wrong -- MAX_COMMAND is already inconsistently defined. # endif #else # define MAX_COMMAND (KEY_MAX + 128) #endif /* --------- prototypes for libmenu functions ----------------------------- */ extern NCURSES_EXPORT(ITEM **) menu_items (const MENU *); extern NCURSES_EXPORT(ITEM *) current_item (const MENU *); extern NCURSES_EXPORT(ITEM *) new_item (const char *,const char *); extern NCURSES_EXPORT(MENU *) new_menu (ITEM **); extern NCURSES_EXPORT(Item_Options) item_opts (const ITEM *); extern NCURSES_EXPORT(Menu_Options) menu_opts (const MENU *); extern NCURSES_EXPORT(Menu_Hook) item_init (const MENU *); extern NCURSES_EXPORT(Menu_Hook) item_term (const MENU *); extern NCURSES_EXPORT(Menu_Hook) menu_init (const MENU *); extern NCURSES_EXPORT(Menu_Hook) menu_term (const MENU *); extern NCURSES_EXPORT(WINDOW *) menu_sub (const MENU *); extern NCURSES_EXPORT(WINDOW *) menu_win (const MENU *); extern NCURSES_EXPORT(const char *) item_description (const ITEM *); extern NCURSES_EXPORT(const char *) item_name (const ITEM *); extern NCURSES_EXPORT(const char *) menu_mark (const MENU *); extern NCURSES_EXPORT(const char *) menu_request_name (int); extern NCURSES_EXPORT(char *) menu_pattern (const MENU *); extern NCURSES_EXPORT(void *) menu_userptr (const MENU *); extern NCURSES_EXPORT(void *) item_userptr (const ITEM *); extern NCURSES_EXPORT(chtype) menu_back (const MENU *); extern NCURSES_EXPORT(chtype) menu_fore (const MENU *); extern NCURSES_EXPORT(chtype) menu_grey (const MENU *); extern NCURSES_EXPORT(int) free_item (ITEM *); extern NCURSES_EXPORT(int) free_menu (MENU *); extern NCURSES_EXPORT(int) item_count (const MENU *); extern NCURSES_EXPORT(int) item_index (const ITEM *); extern NCURSES_EXPORT(int) item_opts_off (ITEM *,Item_Options); extern NCURSES_EXPORT(int) item_opts_on (ITEM *,Item_Options); extern NCURSES_EXPORT(int) menu_driver (MENU *,int); extern NCURSES_EXPORT(int) menu_opts_off (MENU *,Menu_Options); extern NCURSES_EXPORT(int) menu_opts_on (MENU *,Menu_Options); extern NCURSES_EXPORT(int) menu_pad (const MENU *); extern NCURSES_EXPORT(int) pos_menu_cursor (const MENU *); extern NCURSES_EXPORT(int) post_menu (MENU *); extern NCURSES_EXPORT(int) scale_menu (const MENU *,int *,int *); extern NCURSES_EXPORT(int) set_current_item (MENU *menu,ITEM *item); extern NCURSES_EXPORT(int) set_item_init (MENU *, Menu_Hook); extern NCURSES_EXPORT(int) set_item_opts (ITEM *,Item_Options); extern NCURSES_EXPORT(int) set_item_term (MENU *, Menu_Hook); extern NCURSES_EXPORT(int) set_item_userptr (ITEM *, void *); extern NCURSES_EXPORT(int) set_item_value (ITEM *,bool); extern NCURSES_EXPORT(int) set_menu_back (MENU *,chtype); extern NCURSES_EXPORT(int) set_menu_fore (MENU *,chtype); extern NCURSES_EXPORT(int) set_menu_format (MENU *,int,int); extern NCURSES_EXPORT(int) set_menu_grey (MENU *,chtype); extern NCURSES_EXPORT(int) set_menu_init (MENU *, Menu_Hook); extern NCURSES_EXPORT(int) set_menu_items (MENU *,ITEM **); extern NCURSES_EXPORT(int) set_menu_mark (MENU *, const char *); extern NCURSES_EXPORT(int) set_menu_opts (MENU *,Menu_Options); extern NCURSES_EXPORT(int) set_menu_pad (MENU *,int); extern NCURSES_EXPORT(int) set_menu_pattern (MENU *,const char *); extern NCURSES_EXPORT(int) set_menu_sub (MENU *,WINDOW *); extern NCURSES_EXPORT(int) set_menu_term (MENU *, Menu_Hook); extern NCURSES_EXPORT(int) set_menu_userptr (MENU *,void *); extern NCURSES_EXPORT(int) set_menu_win (MENU *,WINDOW *); extern NCURSES_EXPORT(int) set_top_row (MENU *,int); extern NCURSES_EXPORT(int) top_row (const MENU *); extern NCURSES_EXPORT(int) unpost_menu (MENU *); extern NCURSES_EXPORT(int) menu_request_by_name (const char *); extern NCURSES_EXPORT(int) set_menu_spacing (MENU *,int,int,int); extern NCURSES_EXPORT(int) menu_spacing (const MENU *,int *,int *,int *); extern NCURSES_EXPORT(bool) item_value (const ITEM *); extern NCURSES_EXPORT(bool) item_visible (const ITEM *); extern NCURSES_EXPORT(void) menu_format (const MENU *,int *,int *); #if NCURSES_SP_FUNCS extern NCURSES_EXPORT(MENU *) NCURSES_SP_NAME(new_menu) (SCREEN*, ITEM **); #endif #ifdef __cplusplus } #endif #endif /* ETI_MENU */ cursesapp.h000064400000015167151027430560006737 0ustar00// * This makes emacs happy -*-Mode: C++;-*- /**************************************************************************** * Copyright (c) 1998-2005,2011 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1997 * ****************************************************************************/ // $Id: cursesapp.h,v 1.12 2011/09/17 22:12:10 tom Exp $ #ifndef NCURSES_CURSESAPP_H_incl #define NCURSES_CURSESAPP_H_incl #include class NCURSES_IMPEXP NCursesApplication { public: typedef struct _slk_link { // This structure is used to maintain struct _slk_link* prev; // a stack of SLKs Soft_Label_Key_Set* SLKs; } SLK_Link; private: static int rinit(NCursesWindow& w); // Internal Init function for title static NCursesApplication* theApp; // Global ref. to the application static SLK_Link* slk_stack; protected: static NCursesWindow* titleWindow; // The Title Window (if any) bool b_Colors; // Is this a color application? NCursesWindow* Root_Window; // This is the stdscr equiv. // Initialization of attributes; // Rewrite this in your derived class if you prefer other settings virtual void init(bool bColors); // The number of lines for the title window. Default is no title window // You may rewrite this in your derived class virtual int titlesize() const { return 0; } // This method is called to put something into the title window initially // You may rewrite this in your derived class virtual void title() { } // The layout used for the Soft Label Keys. Default is to have no SLKs. // You may rewrite this in your derived class virtual Soft_Label_Key_Set::Label_Layout useSLKs() const { return Soft_Label_Key_Set::None; } // This method is called to initialize the SLKs. Default is nothing. // You may rewrite this in your derived class virtual void init_labels(Soft_Label_Key_Set& S) const { (void) S; } // Your derived class must implement this method. The return value must // be the exit value of your application. virtual int run() = 0; // The constructor is protected, so you may use it in your derived // class constructor. The argument tells whether or not you want colors. NCursesApplication(bool wantColors = FALSE); NCursesApplication& operator=(const NCursesApplication& rhs) { if (this != &rhs) { *this = rhs; } return *this; } NCursesApplication(const NCursesApplication& rhs) : b_Colors(rhs.b_Colors), Root_Window(rhs.Root_Window) { } public: virtual ~NCursesApplication(); // Get a pointer to the current application object static NCursesApplication* getApplication() { return theApp; } // This method runs the application and returns its exit value int operator()(void); // Process the commandline arguments. The default implementation simply // ignores them. Your derived class may rewrite this. virtual void handleArgs(int argc, char* argv[]) { (void) argc; (void) argv; } // Does this application use colors? inline bool useColors() const { return b_Colors; } // Push the Key Set S onto the SLK Stack. S then becomes the current set // of Soft Labelled Keys. void push(Soft_Label_Key_Set& S); // Throw away the current set of SLKs and make the previous one the // new current set. bool pop(); // Retrieve the current set of Soft Labelled Keys. Soft_Label_Key_Set* top() const; // Attributes to use for menu and forms foregrounds virtual chtype foregrounds() const { return b_Colors ? static_cast(COLOR_PAIR(1)) : A_BOLD; } // Attributes to use for menu and forms backgrounds virtual chtype backgrounds() const { return b_Colors ? static_cast(COLOR_PAIR(2)) : A_NORMAL; } // Attributes to use for inactive (menu) elements virtual chtype inactives() const { return b_Colors ? static_cast(COLOR_PAIR(3)|A_DIM) : A_DIM; } // Attributes to use for (form) labels and SLKs virtual chtype labels() const { return b_Colors ? static_cast(COLOR_PAIR(4)) : A_NORMAL; } // Attributes to use for form backgrounds virtual chtype dialog_backgrounds() const { return b_Colors ? static_cast(COLOR_PAIR(4)) : A_NORMAL; } // Attributes to use as default for (form) window backgrounds virtual chtype window_backgrounds() const { return b_Colors ? static_cast(COLOR_PAIR(5)) : A_NORMAL; } // Attributes to use for the title window virtual chtype screen_titles() const { return b_Colors ? static_cast(COLOR_PAIR(6)) : A_BOLD; } }; #endif /* NCURSES_CURSESAPP_H_incl */ cursesw.h000064400000141067151027430560006424 0ustar00// * This makes emacs happy -*-Mode: C++;-*- // vile:cppmode /**************************************************************************** * Copyright (c) 1998-2014,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ #ifndef NCURSES_CURSESW_H_incl #define NCURSES_CURSESW_H_incl 1 // $Id: cursesw.h,v 1.53 2017/11/21 00:37:23 tom Exp $ extern "C" { # include } #include /* SCO 3.2v4 curses.h includes term.h, which defines lines as a macro. Undefine it here, because NCursesWindow uses lines as a method. */ #undef lines /* "Convert" macros to inlines. We'll define it as another symbol to avoid * conflict with library symbols. */ #undef UNDEF #define UNDEF(name) CUR_ ##name #ifdef addch inline int UNDEF(addch)(chtype ch) { return addch(ch); } #undef addch #define addch UNDEF(addch) #endif #ifdef addchstr inline int UNDEF(addchstr)(chtype *at) { return addchstr(at); } #undef addchstr #define addchstr UNDEF(addchstr) #endif #ifdef addnstr inline int UNDEF(addnstr)(const char *str, int n) { return addnstr(str, n); } #undef addnstr #define addnstr UNDEF(addnstr) #endif #ifdef addstr inline int UNDEF(addstr)(const char * str) { return addstr(str); } #undef addstr #define addstr UNDEF(addstr) #endif #ifdef attroff inline int UNDEF(attroff)(chtype at) { return attroff(at); } #undef attroff #define attroff UNDEF(attroff) #endif #ifdef attron inline int UNDEF(attron)(chtype at) { return attron(at); } #undef attron #define attron UNDEF(attron) #endif #ifdef attrset inline chtype UNDEF(attrset)(chtype at) { return attrset(at); } #undef attrset #define attrset UNDEF(attrset) #endif #ifdef bkgd inline int UNDEF(bkgd)(chtype ch) { return bkgd(ch); } #undef bkgd #define bkgd UNDEF(bkgd) #endif #ifdef bkgdset inline void UNDEF(bkgdset)(chtype ch) { bkgdset(ch); } #undef bkgdset #define bkgdset UNDEF(bkgdset) #endif #ifdef border inline int UNDEF(border)(chtype ls, chtype rs, chtype ts, chtype bs, chtype tl, chtype tr, chtype bl, chtype br) { return border(ls, rs, ts, bs, tl, tr, bl, br); } #undef border #define border UNDEF(border) #endif #ifdef box inline int UNDEF(box)(WINDOW *win, int v, int h) { return box(win, v, h); } #undef box #define box UNDEF(box) #endif #ifdef chgat inline int UNDEF(chgat)(int n, attr_t attr, NCURSES_PAIRS_T color, const void *opts) { return chgat(n, attr, color, opts); } #undef chgat #define chgat UNDEF(chgat) #endif #ifdef clear inline int UNDEF(clear)() { return clear(); } #undef clear #define clear UNDEF(clear) #endif #ifdef clearok inline int UNDEF(clearok)(WINDOW* win, bool bf) { return clearok(win, bf); } #undef clearok #define clearok UNDEF(clearok) #else extern "C" NCURSES_IMPEXP int NCURSES_API clearok(WINDOW*, bool); #endif #ifdef clrtobot inline int UNDEF(clrtobot)() { return clrtobot(); } #undef clrtobot #define clrtobot UNDEF(clrtobot) #endif #ifdef clrtoeol inline int UNDEF(clrtoeol)() { return clrtoeol(); } #undef clrtoeol #define clrtoeol UNDEF(clrtoeol) #endif #ifdef color_set inline chtype UNDEF(color_set)(NCURSES_PAIRS_T p, void* opts) { return color_set(p, opts); } #undef color_set #define color_set UNDEF(color_set) #endif #ifdef crmode inline int UNDEF(crmode)(void) { return crmode(); } #undef crmode #define crmode UNDEF(crmode) #endif #ifdef delch inline int UNDEF(delch)() { return delch(); } #undef delch #define delch UNDEF(delch) #endif #ifdef deleteln inline int UNDEF(deleteln)() { return deleteln(); } #undef deleteln #define deleteln UNDEF(deleteln) #endif #ifdef echochar inline int UNDEF(echochar)(chtype ch) { return echochar(ch); } #undef echochar #define echochar UNDEF(echochar) #endif #ifdef erase inline int UNDEF(erase)() { return erase(); } #undef erase #define erase UNDEF(erase) #endif #ifdef fixterm inline int UNDEF(fixterm)(void) { return fixterm(); } #undef fixterm #define fixterm UNDEF(fixterm) #endif #ifdef flushok inline int UNDEF(flushok)(WINDOW* _win, bool _bf) { return flushok(_win, _bf); } #undef flushok #define flushok UNDEF(flushok) #else #define _no_flushok #endif #ifdef getattrs inline int UNDEF(getattrs)(WINDOW *win) { return getattrs(win); } #undef getattrs #define getattrs UNDEF(getattrs) #endif #ifdef getbegyx inline void UNDEF(getbegyx)(WINDOW* win, int& y, int& x) { getbegyx(win, y, x); } #undef getbegyx #define getbegyx UNDEF(getbegyx) #endif #ifdef getbkgd inline chtype UNDEF(getbkgd)(const WINDOW *win) { return getbkgd(win); } #undef getbkgd #define getbkgd UNDEF(getbkgd) #endif #ifdef getch inline int UNDEF(getch)() { return getch(); } #undef getch #define getch UNDEF(getch) #endif #ifdef getmaxyx inline void UNDEF(getmaxyx)(WINDOW* win, int& y, int& x) { getmaxyx(win, y, x); } #undef getmaxyx #define getmaxyx UNDEF(getmaxyx) #endif #ifdef getnstr inline int UNDEF(getnstr)(char *_str, int n) { return getnstr(_str, n); } #undef getnstr #define getnstr UNDEF(getnstr) #endif #ifdef getparyx inline void UNDEF(getparyx)(WINDOW* win, int& y, int& x) { getparyx(win, y, x); } #undef getparyx #define getparyx UNDEF(getparyx) #endif #ifdef getstr inline int UNDEF(getstr)(char *_str) { return getstr(_str); } #undef getstr #define getstr UNDEF(getstr) #endif #ifdef getyx inline void UNDEF(getyx)(const WINDOW* win, int& y, int& x) { getyx(win, y, x); } #undef getyx #define getyx UNDEF(getyx) #endif #ifdef hline inline int UNDEF(hline)(chtype ch, int n) { return hline(ch, n); } #undef hline #define hline UNDEF(hline) #endif #ifdef inch inline chtype UNDEF(inch)() { return inch(); } #undef inch #define inch UNDEF(inch) #endif #ifdef inchstr inline int UNDEF(inchstr)(chtype *str) { return inchstr(str); } #undef inchstr #define inchstr UNDEF(inchstr) #endif #ifdef innstr inline int UNDEF(innstr)(char *_str, int n) { return innstr(_str, n); } #undef innstr #define innstr UNDEF(innstr) #endif #ifdef insch inline int UNDEF(insch)(chtype c) { return insch(c); } #undef insch #define insch UNDEF(insch) #endif #ifdef insdelln inline int UNDEF(insdelln)(int n) { return insdelln(n); } #undef insdelln #define insdelln UNDEF(insdelln) #endif #ifdef insertln inline int UNDEF(insertln)() { return insertln(); } #undef insertln #define insertln UNDEF(insertln) #endif #ifdef insnstr inline int UNDEF(insnstr)(const char *_str, int n) { return insnstr(_str, n); } #undef insnstr #define insnstr UNDEF(insnstr) #endif #ifdef insstr inline int UNDEF(insstr)(const char *_str) { return insstr(_str); } #undef insstr #define insstr UNDEF(insstr) #endif #ifdef instr inline int UNDEF(instr)(char *_str) { return instr(_str); } #undef instr #define instr UNDEF(instr) #endif #ifdef intrflush inline void UNDEF(intrflush)(WINDOW *win, bool bf) { intrflush(); } #undef intrflush #define intrflush UNDEF(intrflush) #endif #ifdef is_linetouched inline int UNDEF(is_linetouched)(WINDOW *w, int l) { return is_linetouched(w,l); } #undef is_linetouched #define is_linetouched UNDEF(is_linetouched) #endif #ifdef leaveok inline int UNDEF(leaveok)(WINDOW* win, bool bf) { return leaveok(win, bf); } #undef leaveok #define leaveok UNDEF(leaveok) #else extern "C" NCURSES_IMPEXP int NCURSES_API leaveok(WINDOW* win, bool bf); #endif #ifdef move inline int UNDEF(move)(int x, int y) { return move(x, y); } #undef move #define move UNDEF(move) #endif #ifdef mvaddch inline int UNDEF(mvaddch)(int y, int x, chtype ch) { return mvaddch(y, x, ch); } #undef mvaddch #define mvaddch UNDEF(mvaddch) #endif #ifdef mvaddnstr inline int UNDEF(mvaddnstr)(int y, int x, const char *str, int n) { return mvaddnstr(y, x, str, n); } #undef mvaddnstr #define mvaddnstr UNDEF(mvaddnstr) #endif #ifdef mvaddstr inline int UNDEF(mvaddstr)(int y, int x, const char * str) { return mvaddstr(y, x, str); } #undef mvaddstr #define mvaddstr UNDEF(mvaddstr) #endif #ifdef mvchgat inline int UNDEF(mvchgat)(int y, int x, int n, attr_t attr, NCURSES_PAIRS_T color, const void *opts) { return mvchgat(y, x, n, attr, color, opts); } #undef mvchgat #define mvchgat UNDEF(mvchgat) #endif #ifdef mvdelch inline int UNDEF(mvdelch)(int y, int x) { return mvdelch(y, x);} #undef mvdelch #define mvdelch UNDEF(mvdelch) #endif #ifdef mvgetch inline int UNDEF(mvgetch)(int y, int x) { return mvgetch(y, x);} #undef mvgetch #define mvgetch UNDEF(mvgetch) #endif #ifdef mvgetnstr inline int UNDEF(mvgetnstr)(int y, int x, char *str, int n) { return mvgetnstr(y, x, str, n);} #undef mvgetnstr #define mvgetnstr UNDEF(mvgetnstr) #endif #ifdef mvgetstr inline int UNDEF(mvgetstr)(int y, int x, char *str) {return mvgetstr(y, x, str);} #undef mvgetstr #define mvgetstr UNDEF(mvgetstr) #endif #ifdef mvinch inline chtype UNDEF(mvinch)(int y, int x) { return mvinch(y, x);} #undef mvinch #define mvinch UNDEF(mvinch) #endif #ifdef mvinnstr inline int UNDEF(mvinnstr)(int y, int x, char *_str, int n) { return mvinnstr(y, x, _str, n); } #undef mvinnstr #define mvinnstr UNDEF(mvinnstr) #endif #ifdef mvinsch inline int UNDEF(mvinsch)(int y, int x, chtype c) { return mvinsch(y, x, c); } #undef mvinsch #define mvinsch UNDEF(mvinsch) #endif #ifdef mvinsnstr inline int UNDEF(mvinsnstr)(int y, int x, const char *_str, int n) { return mvinsnstr(y, x, _str, n); } #undef mvinsnstr #define mvinsnstr UNDEF(mvinsnstr) #endif #ifdef mvinsstr inline int UNDEF(mvinsstr)(int y, int x, const char *_str) { return mvinsstr(y, x, _str); } #undef mvinsstr #define mvinsstr UNDEF(mvinsstr) #endif #ifdef mvwaddch inline int UNDEF(mvwaddch)(WINDOW *win, int y, int x, const chtype ch) { return mvwaddch(win, y, x, ch); } #undef mvwaddch #define mvwaddch UNDEF(mvwaddch) #endif #ifdef mvwaddchnstr inline int UNDEF(mvwaddchnstr)(WINDOW *win, int y, int x, const chtype *str, int n) { return mvwaddchnstr(win, y, x, str, n); } #undef mvwaddchnstr #define mvwaddchnstr UNDEF(mvwaddchnstr) #endif #ifdef mvwaddchstr inline int UNDEF(mvwaddchstr)(WINDOW *win, int y, int x, const chtype *str) { return mvwaddchstr(win, y, x, str); } #undef mvwaddchstr #define mvwaddchstr UNDEF(mvwaddchstr) #endif #ifdef mvwaddnstr inline int UNDEF(mvwaddnstr)(WINDOW *win, int y, int x, const char *str, int n) { return mvwaddnstr(win, y, x, str, n); } #undef mvwaddnstr #define mvwaddnstr UNDEF(mvwaddnstr) #endif #ifdef mvwaddstr inline int UNDEF(mvwaddstr)(WINDOW *win, int y, int x, const char * str) { return mvwaddstr(win, y, x, str); } #undef mvwaddstr #define mvwaddstr UNDEF(mvwaddstr) #endif #ifdef mvwchgat inline int UNDEF(mvwchgat)(WINDOW *win, int y, int x, int n, attr_t attr, NCURSES_PAIRS_T color, const void *opts) { return mvwchgat(win, y, x, n, attr, color, opts); } #undef mvwchgat #define mvwchgat UNDEF(mvwchgat) #endif #ifdef mvwdelch inline int UNDEF(mvwdelch)(WINDOW *win, int y, int x) { return mvwdelch(win, y, x); } #undef mvwdelch #define mvwdelch UNDEF(mvwdelch) #endif #ifdef mvwgetch inline int UNDEF(mvwgetch)(WINDOW *win, int y, int x) { return mvwgetch(win, y, x);} #undef mvwgetch #define mvwgetch UNDEF(mvwgetch) #endif #ifdef mvwgetnstr inline int UNDEF(mvwgetnstr)(WINDOW *win, int y, int x, char *str, int n) {return mvwgetnstr(win, y, x, str, n);} #undef mvwgetnstr #define mvwgetnstr UNDEF(mvwgetnstr) #endif #ifdef mvwgetstr inline int UNDEF(mvwgetstr)(WINDOW *win, int y, int x, char *str) {return mvwgetstr(win, y, x, str);} #undef mvwgetstr #define mvwgetstr UNDEF(mvwgetstr) #endif #ifdef mvwhline inline int UNDEF(mvwhline)(WINDOW *win, int y, int x, chtype c, int n) { return mvwhline(win, y, x, c, n); } #undef mvwhline #define mvwhline UNDEF(mvwhline) #endif #ifdef mvwinch inline chtype UNDEF(mvwinch)(WINDOW *win, int y, int x) { return mvwinch(win, y, x);} #undef mvwinch #define mvwinch UNDEF(mvwinch) #endif #ifdef mvwinchnstr inline int UNDEF(mvwinchnstr)(WINDOW *win, int y, int x, chtype *str, int n) { return mvwinchnstr(win, y, x, str, n); } #undef mvwinchnstr #define mvwinchnstr UNDEF(mvwinchnstr) #endif #ifdef mvwinchstr inline int UNDEF(mvwinchstr)(WINDOW *win, int y, int x, chtype *str) { return mvwinchstr(win, y, x, str); } #undef mvwinchstr #define mvwinchstr UNDEF(mvwinchstr) #endif #ifdef mvwinnstr inline int UNDEF(mvwinnstr)(WINDOW *win, int y, int x, char *_str, int n) { return mvwinnstr(win, y, x, _str, n); } #undef mvwinnstr #define mvwinnstr UNDEF(mvwinnstr) #endif #ifdef mvwinsch inline int UNDEF(mvwinsch)(WINDOW *win, int y, int x, chtype c) { return mvwinsch(win, y, x, c); } #undef mvwinsch #define mvwinsch UNDEF(mvwinsch) #endif #ifdef mvwinsnstr inline int UNDEF(mvwinsnstr)(WINDOW *w, int y, int x, const char *_str, int n) { return mvwinsnstr(w, y, x, _str, n); } #undef mvwinsnstr #define mvwinsnstr UNDEF(mvwinsnstr) #endif #ifdef mvwinsstr inline int UNDEF(mvwinsstr)(WINDOW *w, int y, int x, const char *_str) { return mvwinsstr(w, y, x, _str); } #undef mvwinsstr #define mvwinsstr UNDEF(mvwinsstr) #endif #ifdef mvwvline inline int UNDEF(mvwvline)(WINDOW *win, int y, int x, chtype c, int n) { return mvwvline(win, y, x, c, n); } #undef mvwvline #define mvwvline UNDEF(mvwvline) #endif #ifdef napms inline void UNDEF(napms)(unsigned long x) { napms(x); } #undef napms #define napms UNDEF(napms) #endif #ifdef nocrmode inline int UNDEF(nocrmode)(void) { return nocrmode(); } #undef nocrmode #define nocrmode UNDEF(nocrmode) #endif #ifdef nodelay inline void UNDEF(nodelay)() { nodelay(); } #undef nodelay #define nodelay UNDEF(nodelay) #endif #ifdef redrawwin inline int UNDEF(redrawwin)(WINDOW *win) { return redrawwin(win); } #undef redrawwin #define redrawwin UNDEF(redrawwin) #endif #ifdef refresh inline int UNDEF(refresh)() { return refresh(); } #undef refresh #define refresh UNDEF(refresh) #endif #ifdef resetterm inline int UNDEF(resetterm)(void) { return resetterm(); } #undef resetterm #define resetterm UNDEF(resetterm) #endif #ifdef saveterm inline int UNDEF(saveterm)(void) { return saveterm(); } #undef saveterm #define saveterm UNDEF(saveterm) #endif #ifdef scrl inline int UNDEF(scrl)(int l) { return scrl(l); } #undef scrl #define scrl UNDEF(scrl) #endif #ifdef scroll inline int UNDEF(scroll)(WINDOW *win) { return scroll(win); } #undef scroll #define scroll UNDEF(scroll) #endif #ifdef scrollok inline int UNDEF(scrollok)(WINDOW* win, bool bf) { return scrollok(win, bf); } #undef scrollok #define scrollok UNDEF(scrollok) #else #if defined(__NCURSES_H) extern "C" NCURSES_IMPEXP int NCURSES_API scrollok(WINDOW*, bool); #else extern "C" NCURSES_IMPEXP int NCURSES_API scrollok(WINDOW*, char); #endif #endif #ifdef setscrreg inline int UNDEF(setscrreg)(int t, int b) { return setscrreg(t, b); } #undef setscrreg #define setscrreg UNDEF(setscrreg) #endif #ifdef standend inline int UNDEF(standend)() { return standend(); } #undef standend #define standend UNDEF(standend) #endif #ifdef standout inline int UNDEF(standout)() { return standout(); } #undef standout #define standout UNDEF(standout) #endif #ifdef subpad inline WINDOW *UNDEF(subpad)(WINDOW *p, int l, int c, int y, int x) { return derwin(p, l, c, y, x); } #undef subpad #define subpad UNDEF(subpad) #endif #ifdef timeout inline void UNDEF(timeout)(int delay) { timeout(delay); } #undef timeout #define timeout UNDEF(timeout) #endif #ifdef touchline inline int UNDEF(touchline)(WINDOW *win, int s, int c) { return touchline(win, s, c); } #undef touchline #define touchline UNDEF(touchline) #endif #ifdef touchwin inline int UNDEF(touchwin)(WINDOW *win) { return touchwin(win); } #undef touchwin #define touchwin UNDEF(touchwin) #endif #ifdef untouchwin inline int UNDEF(untouchwin)(WINDOW *win) { return untouchwin(win); } #undef untouchwin #define untouchwin UNDEF(untouchwin) #endif #ifdef vline inline int UNDEF(vline)(chtype ch, int n) { return vline(ch, n); } #undef vline #define vline UNDEF(vline) #endif #ifdef waddchstr inline int UNDEF(waddchstr)(WINDOW *win, chtype *at) { return waddchstr(win, at); } #undef waddchstr #define waddchstr UNDEF(waddchstr) #endif #ifdef waddstr inline int UNDEF(waddstr)(WINDOW *win, char *str) { return waddstr(win, str); } #undef waddstr #define waddstr UNDEF(waddstr) #endif #ifdef wattroff inline int UNDEF(wattroff)(WINDOW *win, int att) { return wattroff(win, att); } #undef wattroff #define wattroff UNDEF(wattroff) #endif #ifdef wattrset inline int UNDEF(wattrset)(WINDOW *win, int att) { return wattrset(win, att); } #undef wattrset #define wattrset UNDEF(wattrset) #endif #ifdef winch inline chtype UNDEF(winch)(const WINDOW* win) { return winch(win); } #undef winch #define winch UNDEF(winch) #endif #ifdef winchnstr inline int UNDEF(winchnstr)(WINDOW *win, chtype *str, int n) { return winchnstr(win, str, n); } #undef winchnstr #define winchnstr UNDEF(winchnstr) #endif #ifdef winchstr inline int UNDEF(winchstr)(WINDOW *win, chtype *str) { return winchstr(win, str); } #undef winchstr #define winchstr UNDEF(winchstr) #endif #ifdef winsstr inline int UNDEF(winsstr)(WINDOW *w, const char *_str) { return winsstr(w, _str); } #undef winsstr #define winsstr UNDEF(winsstr) #endif #ifdef wstandend inline int UNDEF(wstandend)(WINDOW *win) { return wstandend(win); } #undef wstandend #define wstandend UNDEF(wstandend) #endif #ifdef wstandout inline int UNDEF(wstandout)(WINDOW *win) { return wstandout(win); } #undef wstandout #define wstandout UNDEF(wstandout) #endif /* * * C++ class for windows. * */ extern "C" int _nc_ripoffline(int, int (*init)(WINDOW*, int)); extern "C" int _nc_xx_ripoff_init(WINDOW *, int); extern "C" int _nc_has_mouse(void); class NCURSES_IMPEXP NCursesWindow { friend class NCursesMenu; friend class NCursesForm; private: static bool b_initialized; static void initialize(); void constructing(); friend int _nc_xx_ripoff_init(WINDOW *, int); void set_keyboard(); NCURSES_COLOR_T getcolor(int getback) const; NCURSES_PAIRS_T getPair() const; static int setpalette(NCURSES_COLOR_T fore, NCURSES_COLOR_T back, NCURSES_PAIRS_T pair); static int colorInitialized; // This private constructor is only used during the initialization // of windows generated by ripoffline() calls. NCursesWindow(WINDOW* win, int ncols); protected: virtual void err_handler(const char *) const THROWS(NCursesException); // Signal an error with the given message text. static long count; // count of all active windows: // We rely on the c++ promise that // all otherwise uninitialized // static class vars are set to 0 WINDOW* w; // the curses WINDOW bool alloced; // TRUE if we own the WINDOW NCursesWindow* par; // parent, if subwindow NCursesWindow* subwins; // head of subwindows list NCursesWindow* sib; // next subwindow of parent void kill_subwindows(); // disable all subwindows // Destroy all subwindows. /* Only for use by derived classes. They are then in charge to fill the member variables correctly. */ NCursesWindow(); public: NCursesWindow(WINDOW* window); // useful only for stdscr NCursesWindow(int nlines, // number of lines int ncols, // number of columns int begin_y, // line origin int begin_x); // col origin NCursesWindow(NCursesWindow& par,// parent window int nlines, // number of lines int ncols, // number of columns int begin_y, // absolute or relative int begin_x, // origins: char absrel = 'a');// if `a', begin_y & begin_x are // absolute screen pos, else if `r', they are relative to par origin NCursesWindow(NCursesWindow& par,// parent window bool do_box = TRUE); // this is the very common case that we want to create the subwindow that // is two lines and two columns smaller and begins at (1,1). // We may automatically request the box around it. NCursesWindow& operator=(const NCursesWindow& rhs) { if (this != &rhs) *this = rhs; return *this; } NCursesWindow(const NCursesWindow& rhs) : w(rhs.w), alloced(rhs.alloced), par(rhs.par), subwins(rhs.subwins), sib(rhs.sib) { } virtual ~NCursesWindow(); NCursesWindow Clone(); // Make an exact copy of the window. // Initialization. static void useColors(void); // Call this routine very early if you want to have colors. static int ripoffline(int ripoff_lines, int (*init)(NCursesWindow& win)); // This function is used to generate a window of ripped-of lines. // If the argument is positive, lines are removed from the top, if it // is negative lines are removed from the bottom. This enhances the // lowlevel ripoffline() function because it uses the internal // implementation that allows to remove more than just a single line. // This function must be called before any other ncurses function. The // creation of the window is deferred until ncurses gets initialized. // The initialization function is then called. // ------------------------------------------------------------------------- // terminal status // ------------------------------------------------------------------------- int lines() const { initialize(); return LINES; } // Number of lines on terminal, *not* window int cols() const { initialize(); return COLS; } // Number of cols on terminal, *not* window int tabsize() const { initialize(); return TABSIZE; } // Size of a tab on terminal, *not* window static int NumberOfColors(); // Number of available colors int colors() const { return NumberOfColors(); } // Number of available colors // ------------------------------------------------------------------------- // window status // ------------------------------------------------------------------------- int height() const { return maxy() + 1; } // Number of lines in this window int width() const { return maxx() + 1; } // Number of columns in this window int begx() const { return getbegx(w); } // Column of top left corner relative to stdscr int begy() const { return getbegy(w); } // Line of top left corner relative to stdscr int curx() const { return getcurx(w); } // Column of top left corner relative to stdscr int cury() const { return getcury(w); } // Line of top left corner relative to stdscr int maxx() const { return getmaxx(w) == ERR ? ERR : getmaxx(w)-1; } // Largest x coord in window int maxy() const { return getmaxy(w) == ERR ? ERR : getmaxy(w)-1; } // Largest y coord in window NCURSES_PAIRS_T getcolor() const; // Actual color pair NCURSES_COLOR_T foreground() const { return getcolor(0); } // Actual foreground color NCURSES_COLOR_T background() const { return getcolor(1); } // Actual background color int setpalette(NCURSES_COLOR_T fore, NCURSES_COLOR_T back); // Set color palette entry int setcolor(NCURSES_PAIRS_T pair); // Set actually used palette entry // ------------------------------------------------------------------------- // window positioning // ------------------------------------------------------------------------- virtual int mvwin(int begin_y, int begin_x) { return ::mvwin(w, begin_y, begin_x); } // Move window to new position with the new position as top left corner. // This is virtual because it is redefined in NCursesPanel. // ------------------------------------------------------------------------- // coordinate positioning // ------------------------------------------------------------------------- int move(int y, int x) { return ::wmove(w, y, x); } // Move cursor the this position void getyx(int& y, int& x) const { ::getyx(w, y, x); } // Get current position of the cursor void getbegyx(int& y, int& x) const { ::getbegyx(w, y, x); } // Get beginning of the window void getmaxyx(int& y, int& x) const { ::getmaxyx(w, y, x); } // Get size of the window void getparyx(int& y, int& x) const { ::getparyx(w, y, x); } // Get parent's beginning of the window int mvcur(int oldrow, int oldcol, int newrow, int newcol) const { return ::mvcur(oldrow, oldcol, newrow, newcol); } // Perform lowlevel cursor motion that takes effect immediately. // ------------------------------------------------------------------------- // input // ------------------------------------------------------------------------- int getch() { return ::wgetch(w); } // Get a keystroke from the window. int getch(int y, int x) { return ::mvwgetch(w, y, x); } // Move cursor to position and get a keystroke from the window int getstr(char* str, int n=-1) { return ::wgetnstr(w, str, n); } // Read a series of characters into str until a newline or carriage return // is received. Read at most n characters. If n is negative, the limit is // ignored. int getstr(int y, int x, char* str, int n=-1) { return ::mvwgetnstr(w, y, x, str, n); } // Move the cursor to the requested position and then perform the getstr() // as described above. int instr(char *s, int n=-1) { return ::winnstr(w, s, n); } // Get a string of characters from the window into the buffer s. Retrieve // at most n characters, if n is negative retrieve all characters up to the // end of the current line. Attributes are stripped from the characters. int instr(int y, int x, char *s, int n=-1) { return ::mvwinnstr(w, y, x, s, n); } // Move the cursor to the requested position and then perform the instr() // as described above. int scanw(const char* fmt, ...) // Perform a scanw function from the window. #if __GNUG__ >= 2 __attribute__ ((format (scanf, 2, 3))); #else ; #endif int scanw(const char*, va_list); // Perform a scanw function from the window. int scanw(int y, int x, const char* fmt, ...) // Move the cursor to the requested position and then perform a scanw // from the window. #if __GNUG__ >= 2 __attribute__ ((format (scanf, 4, 5))); #else ; #endif int scanw(int y, int x, const char* fmt, va_list); // Move the cursor to the requested position and then perform a scanw // from the window. // ------------------------------------------------------------------------- // output // ------------------------------------------------------------------------- int addch(const chtype ch) { return ::waddch(w, ch); } // Put attributed character to the window. int addch(int y, int x, const chtype ch) { return ::mvwaddch(w, y, x, ch); } // Move cursor to the requested position and then put attributed character // to the window. int echochar(const chtype ch) { return ::wechochar(w, ch); } // Put attributed character to the window and refresh it immediately. int addstr(const char* str, int n=-1) { return ::waddnstr(w, str, n); } // Write the string str to the window, stop writing if the terminating // NUL or the limit n is reached. If n is negative, it is ignored. int addstr(int y, int x, const char * str, int n=-1) { return ::mvwaddnstr(w, y, x, str, n); } // Move the cursor to the requested position and then perform the addchstr // as described above. int addchstr(const chtype* str, int n=-1) { return ::waddchnstr(w, str, n); } // Write the string str to the window, stop writing if the terminating // NUL or the limit n is reached. If n is negative, it is ignored. int addchstr(int y, int x, const chtype * str, int n=-1) { return ::mvwaddchnstr(w, y, x, str, n); } // Move the cursor to the requested position and then perform the addchstr // as described above. int printw(const char* fmt, ...) // Do a formatted print to the window. #if (__GNUG__ >= 2) && !defined(printf) __attribute__ ((format (printf, 2, 3))); #else ; #endif int printw(int y, int x, const char * fmt, ...) // Move the cursor and then do a formatted print to the window. #if (__GNUG__ >= 2) && !defined(printf) __attribute__ ((format (printf, 4, 5))); #else ; #endif int printw(const char* fmt, va_list args); // Do a formatted print to the window. int printw(int y, int x, const char * fmt, va_list args); // Move the cursor and then do a formatted print to the window. chtype inch() const { return ::winch(w); } // Retrieve attributed character under the current cursor position. chtype inch(int y, int x) { return ::mvwinch(w, y, x); } // Move cursor to requested position and then retrieve attributed character // at this position. int inchstr(chtype* str, int n=-1) { return ::winchnstr(w, str, n); } // Read the string str from the window, stop reading if the terminating // NUL or the limit n is reached. If n is negative, it is ignored. int inchstr(int y, int x, chtype * str, int n=-1) { return ::mvwinchnstr(w, y, x, str, n); } // Move the cursor to the requested position and then perform the inchstr // as described above. int insch(chtype ch) { return ::winsch(w, ch); } // Insert attributed character into the window before current cursor // position. int insch(int y, int x, chtype ch) { return ::mvwinsch(w, y, x, ch); } // Move cursor to requested position and then insert the attributed // character before that position. int insertln() { return ::winsdelln(w, 1); } // Insert an empty line above the current line. int insdelln(int n=1) { return ::winsdelln(w, n); } // If n>0 insert that many lines above the current line. If n<0 delete // that many lines beginning with the current line. int insstr(const char *s, int n=-1) { return ::winsnstr(w, s, n); } // Insert the string into the window before the current cursor position. // Insert stops at end of string or when the limit n is reached. If n is // negative, it is ignored. int insstr(int y, int x, const char *s, int n=-1) { return ::mvwinsnstr(w, y, x, s, n); } // Move the cursor to the requested position and then perform the insstr() // as described above. int attron (chtype at) { return ::wattron (w, at); } // Switch on the window attributes; int attroff(chtype at) { return ::wattroff(w, static_cast(at)); } // Switch off the window attributes; int attrset(chtype at) { return ::wattrset(w, static_cast(at)); } // Set the window attributes; chtype attrget() { return ::getattrs(w); } // Get the window attributes; int color_set(NCURSES_PAIRS_T color_pair_number, void* opts=NULL) { return ::wcolor_set(w, color_pair_number, opts); } // Set the window color attribute; int chgat(int n, attr_t attr, NCURSES_PAIRS_T color, const void *opts=NULL) { return ::wchgat(w, n, attr, color, opts); } // Change the attributes of the next n characters in the current line. If // n is negative or greater than the number of remaining characters in the // line, the attributes will be changed up to the end of the line. int chgat(int y, int x, int n, attr_t attr, NCURSES_PAIRS_T color, const void *opts=NULL) { return ::mvwchgat(w, y, x, n, attr, color, opts); } // Move the cursor to the requested position and then perform chgat() as // described above. // ------------------------------------------------------------------------- // background // ------------------------------------------------------------------------- chtype getbkgd() const { return ::getbkgd(w); } // Get current background setting. int bkgd(const chtype ch) { return ::wbkgd(w, ch); } // Set the background property and apply it to the window. void bkgdset(chtype ch) { ::wbkgdset(w, ch); } // Set the background property. // ------------------------------------------------------------------------- // borders // ------------------------------------------------------------------------- int box(chtype vert=0, chtype hor=0) { return ::wborder(w, vert, vert, hor, hor, 0, 0, 0, 0); } // Draw a box around the window with the given vertical and horizontal // drawing characters. If you specify a zero as character, curses will try // to find a "nice" character. int border(chtype left=0, chtype right=0, chtype top =0, chtype bottom=0, chtype top_left =0, chtype top_right=0, chtype bottom_left =0, chtype bottom_right=0) { return ::wborder(w, left, right, top, bottom, top_left, top_right, bottom_left, bottom_right); } // Draw a border around the window with the given characters for the // various parts of the border. If you pass zero for a character, curses // will try to find "nice" characters. // ------------------------------------------------------------------------- // lines and boxes // ------------------------------------------------------------------------- int hline(int len, chtype ch=0) { return ::whline(w, ch, len); } // Draw a horizontal line of len characters with the given character. If // you pass zero for the character, curses will try to find a "nice" one. int hline(int y, int x, int len, chtype ch=0) { return ::mvwhline(w, y, x, ch, len); } // Move the cursor to the requested position and then draw a horizontal line. int vline(int len, chtype ch=0) { return ::wvline(w, ch, len); } // Draw a vertical line of len characters with the given character. If // you pass zero for the character, curses will try to find a "nice" one. int vline(int y, int x, int len, chtype ch=0) { return ::mvwvline(w, y, x, ch, len); } // Move the cursor to the requested position and then draw a vertical line. // ------------------------------------------------------------------------- // erasure // ------------------------------------------------------------------------- int erase() { return ::werase(w); } // Erase the window. int clear() { return ::wclear(w); } // Clear the window. int clearok(bool bf) { return ::clearok(w, bf); } // Set/Reset the clear flag. If set, the next refresh() will clear the // screen. int clrtobot() { return ::wclrtobot(w); } // Clear to the end of the window. int clrtoeol() { return ::wclrtoeol(w); } // Clear to the end of the line. int delch() { return ::wdelch(w); } // Delete character under the cursor. int delch(int y, int x) { return ::mvwdelch(w, y, x); } // Move cursor to requested position and delete the character under the // cursor. int deleteln() { return ::winsdelln(w, -1); } // Delete the current line. // ------------------------------------------------------------------------- // screen control // ------------------------------------------------------------------------- int scroll(int amount=1) { return ::wscrl(w, amount); } // Scroll amount lines. If amount is positive, scroll up, otherwise // scroll down. int scrollok(bool bf) { return ::scrollok(w, bf); } // If bf is TRUE, window scrolls if cursor is moved off the bottom // edge of the window or a scrolling region, otherwise the cursor is left // at the bottom line. int setscrreg(int from, int to) { return ::wsetscrreg(w, from, to); } // Define a soft scrolling region. int idlok(bool bf) { return ::idlok(w, bf); } // If bf is TRUE, use insert/delete line hardware support if possible. // Otherwise do it in software. void idcok(bool bf) { ::idcok(w, bf); } // If bf is TRUE, use insert/delete character hardware support if possible. // Otherwise do it in software. int touchline(int s, int c) { return ::touchline(w, s, c); } // Mark the given lines as modified. int touchwin() { return ::wtouchln(w, 0, height(), 1); } // Mark the whole window as modified. int untouchwin() { return ::wtouchln(w, 0, height(), 0); } // Mark the whole window as unmodified. int touchln(int s, int cnt, bool changed=TRUE) { return ::wtouchln(w, s, cnt, static_cast(changed ? 1 : 0)); } // Mark cnt lines beginning from line s as changed or unchanged, depending // on the value of the changed flag. bool is_linetouched(int line) const { return (::is_linetouched(w, line) == TRUE ? TRUE:FALSE); } // Return TRUE if line is marked as changed, FALSE otherwise bool is_wintouched() const { return (::is_wintouched(w) ? TRUE:FALSE); } // Return TRUE if window is marked as changed, FALSE otherwise int leaveok(bool bf) { return ::leaveok(w, bf); } // If bf is TRUE, curses will leave the cursor after an update whereever // it is after the update. int redrawln(int from, int n) { return ::wredrawln(w, from, n); } // Redraw n lines starting from the requested line int redrawwin() { return ::wredrawln(w, 0, height()); } // Redraw the whole window int doupdate() { return ::doupdate(); } // Do all outputs to make the physical screen looking like the virtual one void syncdown() { ::wsyncdown(w); } // Propagate the changes down to all descendant windows void syncup() { ::wsyncup(w); } // Propagate the changes up in the hierarchy void cursyncup() { ::wcursyncup(w); } // Position the cursor in all ancestor windows corresponding to our setting int syncok(bool bf) { return ::syncok(w, bf); } // If called with bf=TRUE, syncup() is called whenever the window is changed #ifndef _no_flushok int flushok(bool bf) { return ::flushok(w, bf); } #endif void immedok(bool bf) { ::immedok(w, bf); } // If called with bf=TRUE, any change in the window will cause an // automatic immediate refresh() int intrflush(bool bf) { return ::intrflush(w, bf); } int keypad(bool bf) { return ::keypad(w, bf); } // If called with bf=TRUE, the application will interpret function keys. int nodelay(bool bf) { return ::nodelay(w, bf); } int meta(bool bf) { return ::meta(w, bf); } // If called with bf=TRUE, keys may generate 8-Bit characters. Otherwise // 7-Bit characters are generated. int standout() { return ::wstandout(w); } // Enable "standout" attributes int standend() { return ::wstandend(w); } // Disable "standout" attributes // ------------------------------------------------------------------------- // The next two are virtual, because we redefine them in the // NCursesPanel class. // ------------------------------------------------------------------------- virtual int refresh() { return ::wrefresh(w); } // Propagate the changes in this window to the virtual screen and call // doupdate(). This is redefined in NCursesPanel. virtual int noutrefresh() { return ::wnoutrefresh(w); } // Propagate the changes in this window to the virtual screen. This is // redefined in NCursesPanel. // ------------------------------------------------------------------------- // multiple window control // ------------------------------------------------------------------------- int overlay(NCursesWindow& win) { return ::overlay(w, win.w); } // Overlay this window over win. int overwrite(NCursesWindow& win) { return ::overwrite(w, win.w); } // Overwrite win with this window. int copywin(NCursesWindow& win, int sminrow, int smincol, int dminrow, int dmincol, int dmaxrow, int dmaxcol, bool overlaywin=TRUE) { return ::copywin(w, win.w, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol, static_cast(overlaywin ? 1 : 0)); } // Overlay or overwrite the rectangle in win given by dminrow,dmincol, // dmaxrow,dmaxcol with the rectangle in this window beginning at // sminrow,smincol. // ------------------------------------------------------------------------- // Extended functions // ------------------------------------------------------------------------- #if defined(NCURSES_EXT_FUNCS) && (NCURSES_EXT_FUNCS != 0) int wresize(int newLines, int newColumns) { return ::wresize(w, newLines, newColumns); } #endif // ------------------------------------------------------------------------- // Mouse related // ------------------------------------------------------------------------- bool has_mouse() const; // Return TRUE if terminal supports a mouse, FALSE otherwise // ------------------------------------------------------------------------- // traversal support // ------------------------------------------------------------------------- NCursesWindow* child() { return subwins; } // Get the first child window. NCursesWindow* sibling() { return sib; } // Get the next child of my parent. NCursesWindow* parent() { return par; } // Get my parent. bool isDescendant(NCursesWindow& win); // Return TRUE if win is a descendant of this. }; // ------------------------------------------------------------------------- // We leave this here for compatibility reasons. // ------------------------------------------------------------------------- class NCURSES_IMPEXP NCursesColorWindow : public NCursesWindow { public: NCursesColorWindow(WINDOW* &window) // useful only for stdscr : NCursesWindow(window) { useColors(); } NCursesColorWindow(int nlines, // number of lines int ncols, // number of columns int begin_y, // line origin int begin_x) // col origin : NCursesWindow(nlines, ncols, begin_y, begin_x) { useColors(); } NCursesColorWindow(NCursesWindow& parentWin,// parent window int nlines, // number of lines int ncols, // number of columns int begin_y, // absolute or relative int begin_x, // origins: char absrel = 'a') // if `a', by & bx are : NCursesWindow(parentWin, nlines, ncols, // absolute screen pos, begin_y, begin_x, // else if `r', they are absrel ) { // relative to par origin useColors(); } }; // These enum definitions really belong inside the NCursesPad class, but only // recent compilers support that feature. typedef enum { REQ_PAD_REFRESH = KEY_MAX + 1, REQ_PAD_UP, REQ_PAD_DOWN, REQ_PAD_LEFT, REQ_PAD_RIGHT, REQ_PAD_EXIT } Pad_Request; const Pad_Request PAD_LOW = REQ_PAD_REFRESH; // lowest op-code const Pad_Request PAD_HIGH = REQ_PAD_EXIT; // highest op-code // ------------------------------------------------------------------------- // Pad Support. We allow an association of a pad with a "real" window // through which the pad may be viewed. // ------------------------------------------------------------------------- class NCURSES_IMPEXP NCursesPad : public NCursesWindow { private: NCursesWindow* viewWin; // the "viewport" window NCursesWindow* viewSub; // the "viewport" subwindow int h_gridsize, v_gridsize; protected: int min_row, min_col; // top left row/col of the pads display area NCursesWindow* Win(void) const { // Get the window into which the pad should be copied (if any) return (viewSub?viewSub:(viewWin?viewWin:0)); } NCursesWindow* getWindow(void) const { return viewWin; } NCursesWindow* getSubWindow(void) const { return viewSub; } virtual int driver (int key); // Virtualize keystroke key // The driver translates the keystroke c into an Pad_Request virtual void OnUnknownOperation(int pad_req) { (void) pad_req; ::beep(); } // This is called if the driver returns an unknown op-code virtual void OnNavigationError(int pad_req) { (void) pad_req; ::beep(); } // This is called if a navigation request couldn't be satisfied virtual void OnOperation(int pad_req) { (void) pad_req; }; // OnOperation is called if a Pad_Operation was executed and just before // the refresh() operation is done. public: NCursesPad(int nlines, int ncols); // create a pad with the given size NCursesPad& operator=(const NCursesPad& rhs) { if (this != &rhs) { *this = rhs; NCursesWindow::operator=(rhs); } return *this; } NCursesPad(const NCursesPad& rhs) : NCursesWindow(rhs), viewWin(rhs.viewWin), viewSub(rhs.viewSub), h_gridsize(rhs.h_gridsize), v_gridsize(rhs.v_gridsize), min_row(rhs.min_row), min_col(rhs.min_col) { } virtual ~NCursesPad() {} int echochar(const chtype ch) { return ::pechochar(w, ch); } // Put the attributed character onto the pad and immediately do a // prefresh(). int refresh(); // If a viewport is defined the pad is displayed in this window, otherwise // this is a noop. int refresh(int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol) { return ::prefresh(w, pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol); } // The coordinates sminrow,smincol,smaxrow,smaxcol describe a rectangle // on the screen. refresh copies a rectangle of this size beginning // with top left corner pminrow,pmincol onto the screen and calls doupdate(). int noutrefresh(); // If a viewport is defined the pad is displayed in this window, otherwise // this is a noop. int noutrefresh(int pminrow, int pmincol, int sminrow, int smincol, int smaxrow, int smaxcol) { return ::pnoutrefresh(w, pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol); } // Does the same as refresh() but without calling doupdate(). virtual void setWindow(NCursesWindow& view, int v_grid = 1, int h_grid = 1); // Add the window "view" as viewing window to the pad. virtual void setSubWindow(NCursesWindow& sub); // Use the subwindow "sub" of the viewport window for the actual viewing. // The full viewport window is usually used to provide some decorations // like frames, titles etc. virtual void operator() (void); // Perform Pad's operation }; // A FramedPad is constructed always with a viewport window. This viewport // will be framed (by a box() command) and the interior of the box is the // viewport subwindow. On the frame we display scrollbar sliders. class NCURSES_IMPEXP NCursesFramedPad : public NCursesPad { protected: virtual void OnOperation(int pad_req); public: NCursesFramedPad(NCursesWindow& win, int nlines, int ncols, int v_grid = 1, int h_grid = 1) : NCursesPad(nlines, ncols) { NCursesPad::setWindow(win, v_grid, h_grid); NCursesPad::setSubWindow(*(new NCursesWindow(win))); } // Construct the FramedPad with the given Window win as viewport. virtual ~NCursesFramedPad() { delete getSubWindow(); } void setWindow(NCursesWindow& view, int v_grid = 1, int h_grid = 1) { (void) view; (void) v_grid; (void) h_grid; err_handler("Operation not allowed"); } // Disable this call; the viewport is already defined void setSubWindow(NCursesWindow& sub) { (void) sub; err_handler("Operation not allowed"); } // Disable this call; the viewport subwindow is already defined }; #endif /* NCURSES_CURSESW_H_incl */ etip.h000064400000022746151027430560005674 0ustar00// * This makes emacs happy -*-Mode: C++;-*- /**************************************************************************** * Copyright (c) 1998-2012,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1997 * ****************************************************************************/ // $Id: etip.h.in,v 1.41 2017/06/24 21:57:16 tom Exp $ #ifndef NCURSES_ETIP_H_incl #define NCURSES_ETIP_H_incl 1 // These are substituted at configure/build time #ifndef HAVE_BUILTIN_H #define HAVE_BUILTIN_H 0 #endif #ifndef HAVE_GXX_BUILTIN_H #define HAVE_GXX_BUILTIN_H 0 #endif #ifndef HAVE_GPP_BUILTIN_H #define HAVE_GPP_BUILTIN_H 0 #endif #ifndef HAVE_IOSTREAM #define HAVE_IOSTREAM 1 #endif #ifndef HAVE_TYPEINFO #define HAVE_TYPEINFO 1 #endif #ifndef HAVE_VALUES_H #define HAVE_VALUES_H 0 #endif #ifndef ETIP_NEEDS_MATH_H #define ETIP_NEEDS_MATH_H 0 #endif #ifndef ETIP_NEEDS_MATH_EXCEPTION #define ETIP_NEEDS_MATH_EXCEPTION 0 #endif #ifndef CPP_HAS_PARAM_INIT #define CPP_HAS_PARAM_INIT 0 #endif #ifndef CPP_HAS_STATIC_CAST #define CPP_HAS_STATIC_CAST 1 #endif #ifndef IOSTREAM_NAMESPACE #define IOSTREAM_NAMESPACE 1 #endif #ifdef __GNUG__ # if ((__GNUG__ <= 2) && (__GNUC_MINOR__ < 8)) # if HAVE_TYPEINFO # include # endif # endif #endif #if defined(__GNUG__) # if HAVE_BUILTIN_H || HAVE_GXX_BUILTIN_H || HAVE_GPP_BUILTIN_H # if ETIP_NEEDS_MATH_H # if ETIP_NEEDS_MATH_EXCEPTION # undef exception # define exception math_exception # endif # include # endif # undef exception # define exception builtin_exception # if HAVE_GPP_BUILTIN_H # include # elif HAVE_GXX_BUILTIN_H # include # else # include # endif # undef exception # endif #elif defined (__SUNPRO_CC) # include #endif #include extern "C" { #if HAVE_VALUES_H # include #endif #include #include #include } // Language features #if CPP_HAS_PARAM_INIT #define NCURSES_PARAM_INIT(value) = value #else #define NCURSES_PARAM_INIT(value) /*nothing*/ #endif #if CPP_HAS_STATIC_CAST #define STATIC_CAST(s) static_cast #else #define STATIC_CAST(s) (s) #endif // Forward Declarations class NCURSES_IMPEXP NCursesPanel; class NCURSES_IMPEXP NCursesMenu; class NCURSES_IMPEXP NCursesForm; class NCURSES_IMPEXP NCursesException { public: const char *message; int errorno; NCursesException (const char* msg, int err) : message(msg), errorno (err) {}; NCursesException (const char* msg) : message(msg), errorno (E_SYSTEM_ERROR) {}; NCursesException& operator=(const NCursesException& rhs) { errorno = rhs.errorno; return *this; } NCursesException(const NCursesException& rhs) : message(rhs.message), errorno(rhs.errorno) { } virtual const char *classname() const { return "NCursesWindow"; } virtual ~NCursesException() { } }; class NCURSES_IMPEXP NCursesPanelException : public NCursesException { public: const NCursesPanel* p; NCursesPanelException (const char *msg, int err) : NCursesException (msg, err), p (0) {}; NCursesPanelException (const NCursesPanel* panel, const char *msg, int err) : NCursesException (msg, err), p (panel) {}; NCursesPanelException (int err) : NCursesException ("panel library error", err), p (0) {}; NCursesPanelException (const NCursesPanel* panel, int err) : NCursesException ("panel library error", err), p (panel) {}; NCursesPanelException& operator=(const NCursesPanelException& rhs) { if (this != &rhs) { NCursesException::operator=(rhs); p = rhs.p; } return *this; } NCursesPanelException(const NCursesPanelException& rhs) : NCursesException(rhs), p(rhs.p) { } virtual const char *classname() const { return "NCursesPanel"; } virtual ~NCursesPanelException() { } }; class NCURSES_IMPEXP NCursesMenuException : public NCursesException { public: const NCursesMenu* m; NCursesMenuException (const char *msg, int err) : NCursesException (msg, err), m (0) {}; NCursesMenuException (const NCursesMenu* menu, const char *msg, int err) : NCursesException (msg, err), m (menu) {}; NCursesMenuException (int err) : NCursesException ("menu library error", err), m (0) {}; NCursesMenuException (const NCursesMenu* menu, int err) : NCursesException ("menu library error", err), m (menu) {}; NCursesMenuException& operator=(const NCursesMenuException& rhs) { if (this != &rhs) { NCursesException::operator=(rhs); m = rhs.m; } return *this; } NCursesMenuException(const NCursesMenuException& rhs) : NCursesException(rhs), m(rhs.m) { } virtual const char *classname() const { return "NCursesMenu"; } virtual ~NCursesMenuException() { } }; class NCURSES_IMPEXP NCursesFormException : public NCursesException { public: const NCursesForm* f; NCursesFormException (const char *msg, int err) : NCursesException (msg, err), f (0) {}; NCursesFormException (const NCursesForm* form, const char *msg, int err) : NCursesException (msg, err), f (form) {}; NCursesFormException (int err) : NCursesException ("form library error", err), f (0) {}; NCursesFormException (const NCursesForm* form, int err) : NCursesException ("form library error", err), f (form) {}; NCursesFormException& operator=(const NCursesFormException& rhs) { if (this != &rhs) { NCursesException::operator=(rhs); f = rhs.f; } return *this; } NCursesFormException(const NCursesFormException& rhs) : NCursesException(rhs), f(rhs.f) { } virtual const char *classname() const { return "NCursesForm"; } virtual ~NCursesFormException() { } }; #if !((defined(__GNUG__) && defined(__EXCEPTIONS) && (__GNUG__ < 7)) || defined(__SUNPRO_CC)) # if HAVE_IOSTREAM # include # if IOSTREAM_NAMESPACE using std::cerr; using std::endl; # endif # else # include # endif extern "C" void exit(int); #endif inline void THROW(const NCursesException *e) { #if defined(__GNUG__) && defined(__EXCEPTIONS) # if ((__GNUG__ <= 2) && (__GNUC_MINOR__ < 8)) (*lib_error_handler)(e ? e->classname() : "", e ? e->message : ""); # elif (__GNUG__ >= 7) // g++ 7.0 warns about deprecation, but lacks the predefined symbols ::endwin(); std::cerr << "Found a problem - goodbye" << std::endl; exit(EXIT_FAILURE); # else # define CPP_HAS_TRY_CATCH 1 # endif #elif defined(__SUNPRO_CC) # if !defined(__SUNPRO_CC_COMPAT) || (__SUNPRO_CC_COMPAT < 5) genericerror(1, ((e != 0) ? (char *)(e->message) : "")); # else # define CPP_HAS_TRY_CATCH 1 # endif #else if (e) cerr << e->message << endl; exit(0); #endif #ifndef CPP_HAS_TRY_CATCH #define CPP_HAS_TRY_CATCH 0 #define NCURSES_CPP_TRY /* nothing */ #define NCURSES_CPP_CATCH(e) if (false) #define THROWS(s) /* nothing */ #define THROW2(s,t) /* nothing */ #elif CPP_HAS_TRY_CATCH throw *e; #define NCURSES_CPP_TRY try #define NCURSES_CPP_CATCH(e) catch(e) #if defined(__cpp_noexcept_function_type) && (__cpp_noexcept_function_type >= 201510) // C++17 deprecates the usage of throw(). #define THROWS(s) /* nothing */ #define THROW2(s,t) /* nothing */ #else #define THROWS(s) throw(s) #define THROW2(s,t) throw(s,t) #endif #endif } #endif /* NCURSES_ETIP_H_incl */ eti.h000064400000005513151027430560005505 0ustar00/**************************************************************************** * Copyright (c) 1998-2002,2003 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1995,1997 * ****************************************************************************/ /* $Id: eti.h,v 1.8 2003/10/25 15:24:29 tom Exp $ */ #ifndef NCURSES_ETI_H_incl #define NCURSES_ETI_H_incl 1 #define E_OK (0) #define E_SYSTEM_ERROR (-1) #define E_BAD_ARGUMENT (-2) #define E_POSTED (-3) #define E_CONNECTED (-4) #define E_BAD_STATE (-5) #define E_NO_ROOM (-6) #define E_NOT_POSTED (-7) #define E_UNKNOWN_COMMAND (-8) #define E_NO_MATCH (-9) #define E_NOT_SELECTABLE (-10) #define E_NOT_CONNECTED (-11) #define E_REQUEST_DENIED (-12) #define E_INVALID_FIELD (-13) #define E_CURRENT (-14) #endif panel.h000064400000010033151027430560006014 0ustar00/**************************************************************************** * Copyright (c) 1998-2009,2017 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Zeyd M. Ben-Halim 1995 * * and: Eric S. Raymond * * and: Juergen Pfeifer 1996-1999,2008 * ****************************************************************************/ /* $Id: panel.h,v 1.12 2017/02/11 16:50:28 tom Exp $ */ /* panel.h -- interface file for panels library */ #ifndef NCURSES_PANEL_H_incl #define NCURSES_PANEL_H_incl 1 #include typedef struct panel #if !NCURSES_OPAQUE_PANEL { WINDOW *win; struct panel *below; struct panel *above; NCURSES_CONST void *user; } #endif /* !NCURSES_OPAQUE_PANEL */ PANEL; #if defined(__cplusplus) extern "C" { #endif extern NCURSES_EXPORT(WINDOW*) panel_window (const PANEL *); extern NCURSES_EXPORT(void) update_panels (void); extern NCURSES_EXPORT(int) hide_panel (PANEL *); extern NCURSES_EXPORT(int) show_panel (PANEL *); extern NCURSES_EXPORT(int) del_panel (PANEL *); extern NCURSES_EXPORT(int) top_panel (PANEL *); extern NCURSES_EXPORT(int) bottom_panel (PANEL *); extern NCURSES_EXPORT(PANEL*) new_panel (WINDOW *); extern NCURSES_EXPORT(PANEL*) panel_above (const PANEL *); extern NCURSES_EXPORT(PANEL*) panel_below (const PANEL *); extern NCURSES_EXPORT(int) set_panel_userptr (PANEL *, NCURSES_CONST void *); extern NCURSES_EXPORT(NCURSES_CONST void*) panel_userptr (const PANEL *); extern NCURSES_EXPORT(int) move_panel (PANEL *, int, int); extern NCURSES_EXPORT(int) replace_panel (PANEL *,WINDOW *); extern NCURSES_EXPORT(int) panel_hidden (const PANEL *); #if NCURSES_SP_FUNCS extern NCURSES_EXPORT(PANEL *) ground_panel(SCREEN *); extern NCURSES_EXPORT(PANEL *) ceiling_panel(SCREEN *); extern NCURSES_EXPORT(void) NCURSES_SP_NAME(update_panels) (SCREEN*); #endif #if defined(__cplusplus) } #endif #endif /* NCURSES_PANEL_H_incl */ /* end of panel.h */ cursesf.h000064400000066311151027430560006401 0ustar00// * This makes emacs happy -*-Mode: C++;-*- /**************************************************************************** * Copyright (c) 1998-2012,2014 Free Software Foundation, Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, distribute with modifications, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * * Except as contained in this notice, the name(s) of the above copyright * * holders shall not be used in advertising or otherwise to promote the * * sale, use or other dealings in this Software without prior written * * authorization. * ****************************************************************************/ /**************************************************************************** * Author: Juergen Pfeifer, 1997 * ****************************************************************************/ // $Id: cursesf.h,v 1.32 2014/08/09 22:06:11 Adam.Jiang Exp $ #ifndef NCURSES_CURSESF_H_incl #define NCURSES_CURSESF_H_incl 1 #include #ifndef __EXT_QNX #include #endif extern "C" { # include } // // ------------------------------------------------------------------------- // The abstract base class for buitin and user defined Fieldtypes. // ------------------------------------------------------------------------- // class NCURSES_IMPEXP NCursesFormField; // forward declaration // Class to represent builtin field types as well as C++ written new // fieldtypes (see classes UserDefineFieldType... class NCURSES_IMPEXP NCursesFieldType { friend class NCursesFormField; protected: FIELDTYPE* fieldtype; inline void OnError(int err) const THROW2(NCursesException const, NCursesFormException) { if (err!=E_OK) THROW(new NCursesFormException (err)); } NCursesFieldType(FIELDTYPE *f) : fieldtype(f) { } virtual ~NCursesFieldType() {} // Set the fields f fieldtype to this one. virtual void set(NCursesFormField& f) = 0; public: NCursesFieldType() : fieldtype(STATIC_CAST(FIELDTYPE*)(0)) { } NCursesFieldType& operator=(const NCursesFieldType& rhs) { if (this != &rhs) { *this = rhs; } return *this; } NCursesFieldType(const NCursesFieldType& rhs) : fieldtype(rhs.fieldtype) { } }; // // ------------------------------------------------------------------------- // The class representing a forms field, wrapping the lowlevel FIELD struct // ------------------------------------------------------------------------- // class NCURSES_IMPEXP NCursesFormField { friend class NCursesForm; protected: FIELD *field; // lowlevel structure NCursesFieldType* ftype; // Associated field type // Error handler inline void OnError (int err) const THROW2(NCursesException const, NCursesFormException) { if (err != E_OK) THROW(new NCursesFormException (err)); } public: // Create a 'Null' field. Can be used to delimit a field list NCursesFormField() : field(STATIC_CAST(FIELD*)(0)), ftype(STATIC_CAST(NCursesFieldType*)(0)) { } // Create a new field NCursesFormField (int rows, int ncols, int first_row = 0, int first_col = 0, int offscreen_rows = 0, int additional_buffers = 0) : field(0), ftype(STATIC_CAST(NCursesFieldType*)(0)) { field = ::new_field(rows, ncols, first_row, first_col, offscreen_rows, additional_buffers); if (!field) OnError(errno); } NCursesFormField& operator=(const NCursesFormField& rhs) { if (this != &rhs) { *this = rhs; } return *this; } NCursesFormField(const NCursesFormField& rhs) : field(rhs.field), ftype(rhs.ftype) { } virtual ~NCursesFormField (); // Duplicate the field at a new position inline NCursesFormField* dup(int first_row, int first_col) { NCursesFormField* f = new NCursesFormField(); if (!f) OnError(E_SYSTEM_ERROR); else { f->ftype = ftype; f->field = ::dup_field(field,first_row,first_col); if (!f->field) OnError(errno); } return f; } // Link the field to a new location inline NCursesFormField* link(int first_row, int first_col) { NCursesFormField* f = new NCursesFormField(); if (!f) OnError(E_SYSTEM_ERROR); else { f->ftype = ftype; f->field = ::link_field(field,first_row,first_col); if (!f->field) OnError(errno); } return f; } // Get the lowlevel field representation inline FIELD* get_field() const { return field; } // Retrieve info about the field inline void info(int& rows, int& ncols, int& first_row, int& first_col, int& offscreen_rows, int& additional_buffers) const { OnError(::field_info(field, &rows, &ncols, &first_row, &first_col, &offscreen_rows, &additional_buffers)); } // Retrieve info about the fields dynamic properties. inline void dynamic_info(int& dynamic_rows, int& dynamic_cols, int& max_growth) const { OnError(::dynamic_field_info(field, &dynamic_rows, &dynamic_cols, &max_growth)); } // For a dynamic field you may set the maximum growth limit. // A zero means unlimited growth. inline void set_maximum_growth(int growth = 0) { OnError(::set_max_field(field,growth)); } // Move the field to a new position inline void move(int row, int col) { OnError(::move_field(field,row,col)); } // Mark the field to start a new page inline void new_page(bool pageFlag = FALSE) { OnError(::set_new_page(field,pageFlag)); } // Retrieve whether or not the field starts a new page. inline bool is_new_page() const { return ::new_page(field); } // Set the justification for the field inline void set_justification(int just) { OnError(::set_field_just(field,just)); } // Retrieve the fields justification inline int justification() const { return ::field_just(field); } // Set the foreground attribute for the field inline void set_foreground(chtype foreground) { OnError(::set_field_fore(field,foreground)); } // Retrieve the fields foreground attribute inline chtype fore() const { return ::field_fore(field); } // Set the background attribute for the field inline void set_background(chtype background) { OnError(::set_field_back(field,background)); } // Retrieve the fields background attribute inline chtype back() const { return ::field_back(field); } // Set the padding character for the field inline void set_pad_character(int padding) { OnError(::set_field_pad(field, padding)); } // Retrieve the fields padding character inline int pad() const { return ::field_pad(field); } // Switch on the fields options inline void options_on (Field_Options opts) { OnError (::field_opts_on (field, opts)); } // Switch off the fields options inline void options_off (Field_Options opts) { OnError (::field_opts_off (field, opts)); } // Retrieve the fields options inline Field_Options options () const { return ::field_opts (field); } // Set the fields options inline void set_options (Field_Options opts) { OnError (::set_field_opts (field, opts)); } // Mark the field as changed inline void set_changed(bool changeFlag = TRUE) { OnError(::set_field_status(field,changeFlag)); } // Test whether or not the field is marked as changed inline bool changed() const { return ::field_status(field); } // Return the index of the field in the field array of a form // or -1 if the field is not associated to a form inline int (index)() const { return ::field_index(field); } // Store a value in a fields buffer. The default buffer is nr. 0 inline void set_value(const char *val, int buffer = 0) { OnError(::set_field_buffer(field,buffer,val)); } // Retrieve the value of a fields buffer. The default buffer is nr. 0 inline char* value(int buffer = 0) const { return ::field_buffer(field,buffer); } // Set the validation type of the field. inline void set_fieldtype(NCursesFieldType& f) { ftype = &f; f.set(*this); // A good friend may do that... } // Retrieve the validation type of the field. inline NCursesFieldType* fieldtype() const { return ftype; } }; // This are the built-in hook functions in this C++ binding. In C++ we use // virtual member functions (see below On_..._Init and On_..._Termination) // to provide this functionality in an object oriented manner. extern "C" { void _nc_xx_frm_init(FORM *); void _nc_xx_frm_term(FORM *); void _nc_xx_fld_init(FORM *); void _nc_xx_fld_term(FORM *); } // // ------------------------------------------------------------------------- // The class representing a form, wrapping the lowlevel FORM struct // ------------------------------------------------------------------------- // class NCURSES_IMPEXP NCursesForm : public NCursesPanel { protected: FORM* form; // the lowlevel structure private: NCursesWindow* sub; // the subwindow object bool b_sub_owner; // is this our own subwindow? bool b_framed; // has the form a border? bool b_autoDelete; // Delete fields when deleting form? NCursesFormField** my_fields; // The array of fields for this form // This structure is used for the form's user data field to link the // FORM* to the C++ object and to provide extra space for a user pointer. typedef struct { void* m_user; // the pointer for the user's data const NCursesForm* m_back; // backward pointer to C++ object const FORM* m_owner; } UserHook; // Get the backward pointer to the C++ object from a FORM static inline NCursesForm* getHook(const FORM *f) { UserHook* hook = reinterpret_cast(::form_userptr(f)); assert(hook != 0 && hook->m_owner==f); return const_cast(hook->m_back); } friend void _nc_xx_frm_init(FORM *); friend void _nc_xx_frm_term(FORM *); friend void _nc_xx_fld_init(FORM *); friend void _nc_xx_fld_term(FORM *); // Calculate FIELD* array for the menu FIELD** mapFields(NCursesFormField* nfields[]); protected: // internal routines inline void set_user(void *user) { UserHook* uptr = reinterpret_cast(::form_userptr (form)); assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==form); uptr->m_user = user; } inline void *get_user() { UserHook* uptr = reinterpret_cast(::form_userptr (form)); assert (uptr != 0 && uptr->m_back==this && uptr->m_owner==form); return uptr->m_user; } void InitForm (NCursesFormField* Fields[], bool with_frame, bool autoDeleteFields); inline void OnError (int err) const THROW2(NCursesException const, NCursesFormException) { if (err != E_OK) THROW(new NCursesFormException (err)); } // this wraps the form_driver call. virtual int driver (int c) ; // 'Internal' constructor, builds an object without association to a // field array. NCursesForm( int nlines, int ncols, int begin_y = 0, int begin_x = 0) : NCursesPanel(nlines, ncols, begin_y, begin_x), form (STATIC_CAST(FORM*)(0)), sub(0), b_sub_owner(0), b_framed(0), b_autoDelete(0), my_fields(0) { } public: // Create form for the default panel. NCursesForm (NCursesFormField* Fields[], bool with_frame=FALSE, // reserve space for a frame? bool autoDelete_Fields=FALSE) // do automatic cleanup? : NCursesPanel(), form(0), sub(0), b_sub_owner(0), b_framed(0), b_autoDelete(0), my_fields(0) { InitForm(Fields, with_frame, autoDelete_Fields); } // Create a form in a panel with the given position and size. NCursesForm (NCursesFormField* Fields[], int nlines, int ncols, int begin_y, int begin_x, bool with_frame=FALSE, // reserve space for a frame? bool autoDelete_Fields=FALSE) // do automatic cleanup? : NCursesPanel(nlines, ncols, begin_y, begin_x), form(0), sub(0), b_sub_owner(0), b_framed(0), b_autoDelete(0), my_fields(0) { InitForm(Fields, with_frame, autoDelete_Fields); } NCursesForm& operator=(const NCursesForm& rhs) { if (this != &rhs) { *this = rhs; NCursesPanel::operator=(rhs); } return *this; } NCursesForm(const NCursesForm& rhs) : NCursesPanel(rhs), form(rhs.form), sub(rhs.sub), b_sub_owner(rhs.b_sub_owner), b_framed(rhs.b_framed), b_autoDelete(rhs.b_autoDelete), my_fields(rhs.my_fields) { } virtual ~NCursesForm(); // Set the default attributes for the form virtual void setDefaultAttributes(); // Retrieve current field of the form. inline NCursesFormField* current_field() const { return my_fields[::field_index(::current_field(form))]; } // Set the forms subwindow void setSubWindow(NCursesWindow& sub); // Set these fields for the form inline void setFields(NCursesFormField* Fields[]) { OnError(::set_form_fields(form,mapFields(Fields))); } // Remove the form from the screen inline void unpost (void) { OnError (::unpost_form (form)); } // Post the form to the screen if flag is true, unpost it otherwise inline void post(bool flag = TRUE) { OnError (flag ? ::post_form(form) : ::unpost_form (form)); } // Decorations inline void frame(const char *title=NULL, const char* btitle=NULL) { if (b_framed) NCursesPanel::frame(title,btitle); else OnError(E_SYSTEM_ERROR); } inline void boldframe(const char *title=NULL, const char* btitle=NULL) { if (b_framed) NCursesPanel::boldframe(title,btitle); else OnError(E_SYSTEM_ERROR); } inline void label(const char *topLabel, const char *bottomLabel) { if (b_framed) NCursesPanel::label(topLabel,bottomLabel); else OnError(E_SYSTEM_ERROR); } // ----- // Hooks // ----- // Called after the form gets repositioned in its window. // This is especially true if the form is posted. virtual void On_Form_Init(); // Called before the form gets repositioned in its window. // This is especially true if the form is unposted. virtual void On_Form_Termination(); // Called after the field became the current field virtual void On_Field_Init(NCursesFormField& field); // Called before this field is left as current field. virtual void On_Field_Termination(NCursesFormField& field); // Calculate required window size for the form. void scale(int& rows, int& ncols) const { OnError(::scale_form(form,&rows,&ncols)); } // Retrieve number of fields in the form. int count() const { return ::field_count(form); } // Make the page the current page of the form. void set_page(int pageNum) { OnError(::set_form_page(form, pageNum)); } // Retrieve current page number int page() const { return ::form_page(form); } // Switch on the forms options inline void options_on (Form_Options opts) { OnError (::form_opts_on (form, opts)); } // Switch off the forms options inline void options_off (Form_Options opts) { OnError (::form_opts_off (form, opts)); } // Retrieve the forms options inline Form_Options options () const { return ::form_opts (form); } // Set the forms options inline void set_options (Form_Options opts) { OnError (::set_form_opts (form, opts)); } // Are there more data in the current field after the data shown inline bool data_ahead() const { return ::data_ahead(form); } // Are there more data in the current field before the data shown inline bool data_behind() const { return ::data_behind(form); } // Position the cursor to the current field inline void position_cursor () { OnError (::pos_form_cursor (form)); } // Set the current field inline void set_current(NCursesFormField& F) { OnError (::set_current_field(form, F.field)); } // Provide a default key virtualization. Translate the keyboard // code c into a form request code. // The default implementation provides a hopefully straightforward // mapping for the most common keystrokes and form requests. virtual int virtualize(int c); // Operators inline NCursesFormField* operator[](int i) const { if ( (i < 0) || (i >= ::field_count (form)) ) OnError (E_BAD_ARGUMENT); return my_fields[i]; } // Perform the menu's operation // Return the field where you left the form. virtual NCursesFormField* operator()(void); // Exception handlers. The default is a Beep. virtual void On_Request_Denied(int c) const; virtual void On_Invalid_Field(int c) const; virtual void On_Unknown_Command(int c) const; }; // // ------------------------------------------------------------------------- // This is the typical C++ typesafe way to allow to attach // user data to a field of a form. Its assumed that the user // data belongs to some class T. Use T as template argument // to create a UserField. // ------------------------------------------------------------------------- template class NCURSES_IMPEXP NCursesUserField : public NCursesFormField { public: NCursesUserField (int rows, int ncols, int first_row = 0, int first_col = 0, const T* p_UserData = STATIC_CAST(T*)(0), int offscreen_rows = 0, int additional_buffers = 0) : NCursesFormField (rows, ncols, first_row, first_col, offscreen_rows, additional_buffers) { if (field) OnError(::set_field_userptr(field, STATIC_CAST(void *)(p_UserData))); } virtual ~NCursesUserField() {}; inline const T* UserData (void) const { return reinterpret_cast(::field_userptr (field)); } inline virtual void setUserData(const T* p_UserData) { if (field) OnError (::set_field_userptr (field, STATIC_CAST(void *)(p_UserData))); } }; // // ------------------------------------------------------------------------- // The same mechanism is used to attach user data to a form // ------------------------------------------------------------------------- // template class NCURSES_IMPEXP NCursesUserForm : public NCursesForm { protected: // 'Internal' constructor, builds an object without association to a // field array. NCursesUserForm( int nlines, int ncols, int begin_y = 0, int begin_x = 0, const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesForm(nlines,ncols,begin_y,begin_x) { if (form) set_user (const_cast(reinterpret_cast (p_UserData))); } public: NCursesUserForm (NCursesFormField* Fields[], const T* p_UserData = STATIC_CAST(T*)(0), bool with_frame=FALSE, bool autoDelete_Fields=FALSE) : NCursesForm (Fields, with_frame, autoDelete_Fields) { if (form) set_user (const_cast(reinterpret_cast(p_UserData))); }; NCursesUserForm (NCursesFormField* Fields[], int nlines, int ncols, int begin_y = 0, int begin_x = 0, const T* p_UserData = STATIC_CAST(T*)(0), bool with_frame=FALSE, bool autoDelete_Fields=FALSE) : NCursesForm (Fields, nlines, ncols, begin_y, begin_x, with_frame, autoDelete_Fields) { if (form) set_user (const_cast(reinterpret_cast (p_UserData))); }; virtual ~NCursesUserForm() { }; inline T* UserData (void) { return reinterpret_cast(get_user ()); }; inline virtual void setUserData (const T* p_UserData) { if (form) set_user (const_cast(reinterpret_cast(p_UserData))); } }; // // ------------------------------------------------------------------------- // Builtin Fieldtypes // ------------------------------------------------------------------------- // class NCURSES_IMPEXP Alpha_Field : public NCursesFieldType { private: int min_field_width; void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype,min_field_width)); } public: Alpha_Field(int width) : NCursesFieldType(TYPE_ALPHA), min_field_width(width) { } }; class NCURSES_IMPEXP Alphanumeric_Field : public NCursesFieldType { private: int min_field_width; void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype,min_field_width)); } public: Alphanumeric_Field(int width) : NCursesFieldType(TYPE_ALNUM), min_field_width(width) { } }; class NCURSES_IMPEXP Integer_Field : public NCursesFieldType { private: int precision; long lower_limit, upper_limit; void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype, precision,lower_limit,upper_limit)); } public: Integer_Field(int prec, long low=0L, long high=0L) : NCursesFieldType(TYPE_INTEGER), precision(prec), lower_limit(low), upper_limit(high) { } }; class NCURSES_IMPEXP Numeric_Field : public NCursesFieldType { private: int precision; double lower_limit, upper_limit; void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype, precision,lower_limit,upper_limit)); } public: Numeric_Field(int prec, double low=0.0, double high=0.0) : NCursesFieldType(TYPE_NUMERIC), precision(prec), lower_limit(low), upper_limit(high) { } }; class NCURSES_IMPEXP Regular_Expression_Field : public NCursesFieldType { private: char* regex; void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype,regex)); } void copy_regex(const char *source) { regex = new char[1 + ::strlen(source)]; (::strcpy)(regex, source); } public: Regular_Expression_Field(const char *expr) : NCursesFieldType(TYPE_REGEXP), regex(NULL) { copy_regex(expr); } Regular_Expression_Field& operator=(const Regular_Expression_Field& rhs) { if (this != &rhs) { *this = rhs; copy_regex(rhs.regex); NCursesFieldType::operator=(rhs); } return *this; } Regular_Expression_Field(const Regular_Expression_Field& rhs) : NCursesFieldType(rhs), regex(NULL) { copy_regex(rhs.regex); } ~Regular_Expression_Field() { delete[] regex; } }; class NCURSES_IMPEXP Enumeration_Field : public NCursesFieldType { private: const char** list; int case_sensitive; int non_unique_matches; void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype, list,case_sensitive,non_unique_matches)); } public: Enumeration_Field(const char* enums[], bool case_sens=FALSE, bool non_unique=FALSE) : NCursesFieldType(TYPE_ENUM), list(enums), case_sensitive(case_sens ? -1 : 0), non_unique_matches(non_unique ? -1 : 0) { } Enumeration_Field& operator=(const Enumeration_Field& rhs) { if (this != &rhs) { *this = rhs; NCursesFieldType::operator=(rhs); } return *this; } Enumeration_Field(const Enumeration_Field& rhs) : NCursesFieldType(rhs), list(rhs.list), case_sensitive(rhs.case_sensitive), non_unique_matches(rhs.non_unique_matches) { } }; class NCURSES_IMPEXP IPV4_Address_Field : public NCursesFieldType { private: void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype)); } public: IPV4_Address_Field() : NCursesFieldType(TYPE_IPV4) { } }; extern "C" { bool _nc_xx_fld_fcheck(FIELD *, const void*); bool _nc_xx_fld_ccheck(int c, const void *); void* _nc_xx_fld_makearg(va_list*); } // // ------------------------------------------------------------------------- // Abstract base class for User-Defined Fieldtypes // ------------------------------------------------------------------------- // class NCURSES_IMPEXP UserDefinedFieldType : public NCursesFieldType { friend class UDF_Init; // Internal helper to set up statics private: // For all C++ defined fieldtypes we need only one generic lowlevel // FIELDTYPE* element. static FIELDTYPE* generic_fieldtype; protected: // This are the functions required by the low level libforms functions // to construct a fieldtype. friend bool _nc_xx_fld_fcheck(FIELD *, const void*); friend bool _nc_xx_fld_ccheck(int c, const void *); friend void* _nc_xx_fld_makearg(va_list*); void set(NCursesFormField& f) { OnError(::set_field_type(f.get_field(),fieldtype,&f)); } protected: // Redefine this function to do a field validation. The argument // is a reference to the field you should validate. virtual bool field_check(NCursesFormField& f) = 0; // Redefine this function to do a character validation. The argument // is the character to be validated. virtual bool char_check (int c) = 0; public: UserDefinedFieldType() : NCursesFieldType(generic_fieldtype) { } }; extern "C" { bool _nc_xx_next_choice(FIELD*, const void *); bool _nc_xx_prev_choice(FIELD*, const void *); } // // ------------------------------------------------------------------------- // Abstract base class for User-Defined Fieldtypes with Choice functions // ------------------------------------------------------------------------- // class NCURSES_IMPEXP UserDefinedFieldType_With_Choice : public UserDefinedFieldType { friend class UDF_Init; // Internal helper to set up statics private: // For all C++ defined fieldtypes with choice functions we need only one // generic lowlevel FIELDTYPE* element. static FIELDTYPE* generic_fieldtype_with_choice; // This are the functions required by the low level libforms functions // to construct a fieldtype with choice functions. friend bool _nc_xx_next_choice(FIELD*, const void *); friend bool _nc_xx_prev_choice(FIELD*, const void *); protected: // Redefine this function to do the retrieval of the next choice value. // The argument is a reference to the field tobe examined. virtual bool next (NCursesFormField& f) = 0; // Redefine this function to do the retrieval of the previous choice value. // The argument is a reference to the field tobe examined. virtual bool previous(NCursesFormField& f) = 0; public: UserDefinedFieldType_With_Choice() { fieldtype = generic_fieldtype_with_choice; } }; #endif /* NCURSES_CURSESF_H_incl */ tiffio.h000064400000055273151027430560006214 0ustar00/* $Id: tiffio.h,v 1.94 2017-01-11 19:02:49 erouault Exp $ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #ifndef _TIFFIO_ #define _TIFFIO_ /* * TIFF I/O Library Definitions. */ #include "tiff.h" #include "tiffvers.h" /* * TIFF is defined as an incomplete type to hide the * library's internal data structures from clients. */ typedef struct tiff TIFF; /* * The following typedefs define the intrinsic size of * data types used in the *exported* interfaces. These * definitions depend on the proper definition of types * in tiff.h. Note also that the varargs interface used * to pass tag types and values uses the types defined in * tiff.h directly. * * NB: ttag_t is unsigned int and not unsigned short because * ANSI C requires that the type before the ellipsis be a * promoted type (i.e. one of int, unsigned int, pointer, * or double) and because we defined pseudo-tags that are * outside the range of legal Aldus-assigned tags. * NB: tsize_t is int32 and not uint32 because some functions * return -1. * NB: toff_t is not off_t for many reasons; TIFFs max out at * 32-bit file offsets, and BigTIFF maxes out at 64-bit * offsets being the most important, and to ensure use of * a consistently unsigned type across architectures. * Prior to libtiff 4.0, this was an unsigned 32 bit type. */ /* * this is the machine addressing size type, only it's signed, so make it * int32 on 32bit machines, int64 on 64bit machines */ typedef TIFF_SSIZE_T tmsize_t; typedef uint64 toff_t; /* file offset */ /* the following are deprecated and should be replaced by their defining counterparts */ typedef uint32 ttag_t; /* directory tag */ typedef uint16 tdir_t; /* directory index */ typedef uint16 tsample_t; /* sample number */ typedef uint32 tstrile_t; /* strip or tile number */ typedef tstrile_t tstrip_t; /* strip number */ typedef tstrile_t ttile_t; /* tile number */ typedef tmsize_t tsize_t; /* i/o size in bytes */ typedef void* tdata_t; /* image data ref */ #if !defined(__WIN32__) && (defined(_WIN32) || defined(WIN32)) #define __WIN32__ #endif /* * On windows you should define USE_WIN32_FILEIO if you are using tif_win32.c * or AVOID_WIN32_FILEIO if you are using something else (like tif_unix.c). * * By default tif_unix.c is assumed. */ #if defined(_WINDOWS) || defined(__WIN32__) || defined(_Windows) # if !defined(__CYGWIN) && !defined(AVOID_WIN32_FILEIO) && !defined(USE_WIN32_FILEIO) # define AVOID_WIN32_FILEIO # endif #endif #if defined(USE_WIN32_FILEIO) # define VC_EXTRALEAN # include # ifdef __WIN32__ DECLARE_HANDLE(thandle_t); /* Win32 file handle */ # else typedef HFILE thandle_t; /* client data handle */ # endif /* __WIN32__ */ #else typedef void* thandle_t; /* client data handle */ #endif /* USE_WIN32_FILEIO */ /* * Flags to pass to TIFFPrintDirectory to control * printing of data structures that are potentially * very large. Bit-or these flags to enable printing * multiple items. */ #define TIFFPRINT_NONE 0x0 /* no extra info */ #define TIFFPRINT_STRIPS 0x1 /* strips/tiles info */ #define TIFFPRINT_CURVES 0x2 /* color/gray response curves */ #define TIFFPRINT_COLORMAP 0x4 /* colormap */ #define TIFFPRINT_JPEGQTABLES 0x100 /* JPEG Q matrices */ #define TIFFPRINT_JPEGACTABLES 0x200 /* JPEG AC tables */ #define TIFFPRINT_JPEGDCTABLES 0x200 /* JPEG DC tables */ /* * Colour conversion stuff */ /* reference white */ #define D65_X0 (95.0470F) #define D65_Y0 (100.0F) #define D65_Z0 (108.8827F) #define D50_X0 (96.4250F) #define D50_Y0 (100.0F) #define D50_Z0 (82.4680F) /* Structure for holding information about a display device. */ typedef unsigned char TIFFRGBValue; /* 8-bit samples */ typedef struct { float d_mat[3][3]; /* XYZ -> luminance matrix */ float d_YCR; /* Light o/p for reference white */ float d_YCG; float d_YCB; uint32 d_Vrwr; /* Pixel values for ref. white */ uint32 d_Vrwg; uint32 d_Vrwb; float d_Y0R; /* Residual light for black pixel */ float d_Y0G; float d_Y0B; float d_gammaR; /* Gamma values for the three guns */ float d_gammaG; float d_gammaB; } TIFFDisplay; typedef struct { /* YCbCr->RGB support */ TIFFRGBValue* clamptab; /* range clamping table */ int* Cr_r_tab; int* Cb_b_tab; int32* Cr_g_tab; int32* Cb_g_tab; int32* Y_tab; } TIFFYCbCrToRGB; typedef struct { /* CIE Lab 1976->RGB support */ int range; /* Size of conversion table */ #define CIELABTORGB_TABLE_RANGE 1500 float rstep, gstep, bstep; float X0, Y0, Z0; /* Reference white point */ TIFFDisplay display; float Yr2r[CIELABTORGB_TABLE_RANGE + 1]; /* Conversion of Yr to r */ float Yg2g[CIELABTORGB_TABLE_RANGE + 1]; /* Conversion of Yg to g */ float Yb2b[CIELABTORGB_TABLE_RANGE + 1]; /* Conversion of Yb to b */ } TIFFCIELabToRGB; /* * RGBA-style image support. */ typedef struct _TIFFRGBAImage TIFFRGBAImage; /* * The image reading and conversion routines invoke * ``put routines'' to copy/image/whatever tiles of * raw image data. A default set of routines are * provided to convert/copy raw image data to 8-bit * packed ABGR format rasters. Applications can supply * alternate routines that unpack the data into a * different format or, for example, unpack the data * and draw the unpacked raster on the display. */ typedef void (*tileContigRoutine) (TIFFRGBAImage*, uint32*, uint32, uint32, uint32, uint32, int32, int32, unsigned char*); typedef void (*tileSeparateRoutine) (TIFFRGBAImage*, uint32*, uint32, uint32, uint32, uint32, int32, int32, unsigned char*, unsigned char*, unsigned char*, unsigned char*); /* * RGBA-reader state. */ struct _TIFFRGBAImage { TIFF* tif; /* image handle */ int stoponerr; /* stop on read error */ int isContig; /* data is packed/separate */ int alpha; /* type of alpha data present */ uint32 width; /* image width */ uint32 height; /* image height */ uint16 bitspersample; /* image bits/sample */ uint16 samplesperpixel; /* image samples/pixel */ uint16 orientation; /* image orientation */ uint16 req_orientation; /* requested orientation */ uint16 photometric; /* image photometric interp */ uint16* redcmap; /* colormap palette */ uint16* greencmap; uint16* bluecmap; /* get image data routine */ int (*get)(TIFFRGBAImage*, uint32*, uint32, uint32); /* put decoded strip/tile */ union { void (*any)(TIFFRGBAImage*); tileContigRoutine contig; tileSeparateRoutine separate; } put; TIFFRGBValue* Map; /* sample mapping array */ uint32** BWmap; /* black&white map */ uint32** PALmap; /* palette image map */ TIFFYCbCrToRGB* ycbcr; /* YCbCr conversion state */ TIFFCIELabToRGB* cielab; /* CIE L*a*b conversion state */ uint8* UaToAa; /* Unassociated alpha to associated alpha conversion LUT */ uint8* Bitdepth16To8; /* LUT for conversion from 16bit to 8bit values */ int row_offset; int col_offset; }; /* * Macros for extracting components from the * packed ABGR form returned by TIFFReadRGBAImage. */ #define TIFFGetR(abgr) ((abgr) & 0xff) #define TIFFGetG(abgr) (((abgr) >> 8) & 0xff) #define TIFFGetB(abgr) (((abgr) >> 16) & 0xff) #define TIFFGetA(abgr) (((abgr) >> 24) & 0xff) /* * A CODEC is a software package that implements decoding, * encoding, or decoding+encoding of a compression algorithm. * The library provides a collection of builtin codecs. * More codecs may be registered through calls to the library * and/or the builtin implementations may be overridden. */ typedef int (*TIFFInitMethod)(TIFF*, int); typedef struct { char* name; uint16 scheme; TIFFInitMethod init; } TIFFCodec; #include #include /* share internal LogLuv conversion routines? */ #ifndef LOGLUV_PUBLIC #define LOGLUV_PUBLIC 1 #endif #if !defined(__GNUC__) && !defined(__attribute__) # define __attribute__(x) /*nothing*/ #endif #if defined(c_plusplus) || defined(__cplusplus) extern "C" { #endif typedef void (*TIFFErrorHandler)(const char*, const char*, va_list); typedef void (*TIFFErrorHandlerExt)(thandle_t, const char*, const char*, va_list); typedef tmsize_t (*TIFFReadWriteProc)(thandle_t, void*, tmsize_t); typedef toff_t (*TIFFSeekProc)(thandle_t, toff_t, int); typedef int (*TIFFCloseProc)(thandle_t); typedef toff_t (*TIFFSizeProc)(thandle_t); typedef int (*TIFFMapFileProc)(thandle_t, void** base, toff_t* size); typedef void (*TIFFUnmapFileProc)(thandle_t, void* base, toff_t size); typedef void (*TIFFExtendProc)(TIFF*); extern const char* TIFFGetVersion(void); extern const TIFFCodec* TIFFFindCODEC(uint16); extern TIFFCodec* TIFFRegisterCODEC(uint16, const char*, TIFFInitMethod); extern void TIFFUnRegisterCODEC(TIFFCodec*); extern int TIFFIsCODECConfigured(uint16); extern TIFFCodec* TIFFGetConfiguredCODECs(void); /* * Auxiliary functions. */ extern void* _TIFFmalloc(tmsize_t s); extern void* _TIFFcalloc(tmsize_t nmemb, tmsize_t siz); extern void* _TIFFrealloc(void* p, tmsize_t s); extern void _TIFFmemset(void* p, int v, tmsize_t c); extern void _TIFFmemcpy(void* d, const void* s, tmsize_t c); extern int _TIFFmemcmp(const void* p1, const void* p2, tmsize_t c); extern void _TIFFfree(void* p); /* ** Stuff, related to tag handling and creating custom tags. */ extern int TIFFGetTagListCount( TIFF * ); extern uint32 TIFFGetTagListEntry( TIFF *, int tag_index ); #define TIFF_ANY TIFF_NOTYPE /* for field descriptor searching */ #define TIFF_VARIABLE -1 /* marker for variable length tags */ #define TIFF_SPP -2 /* marker for SamplesPerPixel tags */ #define TIFF_VARIABLE2 -3 /* marker for uint32 var-length tags */ #define FIELD_CUSTOM 65 typedef struct _TIFFField TIFFField; typedef struct _TIFFFieldArray TIFFFieldArray; extern const TIFFField* TIFFFindField(TIFF *, uint32, TIFFDataType); extern const TIFFField* TIFFFieldWithTag(TIFF*, uint32); extern const TIFFField* TIFFFieldWithName(TIFF*, const char *); extern uint32 TIFFFieldTag(const TIFFField*); extern const char* TIFFFieldName(const TIFFField*); extern TIFFDataType TIFFFieldDataType(const TIFFField*); extern int TIFFFieldPassCount(const TIFFField*); extern int TIFFFieldReadCount(const TIFFField*); extern int TIFFFieldWriteCount(const TIFFField*); typedef int (*TIFFVSetMethod)(TIFF*, uint32, va_list); typedef int (*TIFFVGetMethod)(TIFF*, uint32, va_list); typedef void (*TIFFPrintMethod)(TIFF*, FILE*, long); typedef struct { TIFFVSetMethod vsetfield; /* tag set routine */ TIFFVGetMethod vgetfield; /* tag get routine */ TIFFPrintMethod printdir; /* directory print routine */ } TIFFTagMethods; extern TIFFTagMethods *TIFFAccessTagMethods(TIFF *); extern void *TIFFGetClientInfo(TIFF *, const char *); extern void TIFFSetClientInfo(TIFF *, void *, const char *); extern void TIFFCleanup(TIFF* tif); extern void TIFFClose(TIFF* tif); extern int TIFFFlush(TIFF* tif); extern int TIFFFlushData(TIFF* tif); extern int TIFFGetField(TIFF* tif, uint32 tag, ...); extern int TIFFVGetField(TIFF* tif, uint32 tag, va_list ap); extern int TIFFGetFieldDefaulted(TIFF* tif, uint32 tag, ...); extern int TIFFVGetFieldDefaulted(TIFF* tif, uint32 tag, va_list ap); extern int TIFFReadDirectory(TIFF* tif); extern int TIFFReadCustomDirectory(TIFF* tif, toff_t diroff, const TIFFFieldArray* infoarray); extern int TIFFReadEXIFDirectory(TIFF* tif, toff_t diroff); extern uint64 TIFFScanlineSize64(TIFF* tif); extern tmsize_t TIFFScanlineSize(TIFF* tif); extern uint64 TIFFRasterScanlineSize64(TIFF* tif); extern tmsize_t TIFFRasterScanlineSize(TIFF* tif); extern uint64 TIFFStripSize64(TIFF* tif); extern tmsize_t TIFFStripSize(TIFF* tif); extern uint64 TIFFRawStripSize64(TIFF* tif, uint32 strip); extern tmsize_t TIFFRawStripSize(TIFF* tif, uint32 strip); extern uint64 TIFFVStripSize64(TIFF* tif, uint32 nrows); extern tmsize_t TIFFVStripSize(TIFF* tif, uint32 nrows); extern uint64 TIFFTileRowSize64(TIFF* tif); extern tmsize_t TIFFTileRowSize(TIFF* tif); extern uint64 TIFFTileSize64(TIFF* tif); extern tmsize_t TIFFTileSize(TIFF* tif); extern uint64 TIFFVTileSize64(TIFF* tif, uint32 nrows); extern tmsize_t TIFFVTileSize(TIFF* tif, uint32 nrows); extern uint32 TIFFDefaultStripSize(TIFF* tif, uint32 request); extern void TIFFDefaultTileSize(TIFF*, uint32*, uint32*); extern int TIFFFileno(TIFF*); extern int TIFFSetFileno(TIFF*, int); extern thandle_t TIFFClientdata(TIFF*); extern thandle_t TIFFSetClientdata(TIFF*, thandle_t); extern int TIFFGetMode(TIFF*); extern int TIFFSetMode(TIFF*, int); extern int TIFFIsTiled(TIFF*); extern int TIFFIsByteSwapped(TIFF*); extern int TIFFIsUpSampled(TIFF*); extern int TIFFIsMSB2LSB(TIFF*); extern int TIFFIsBigEndian(TIFF*); extern TIFFReadWriteProc TIFFGetReadProc(TIFF*); extern TIFFReadWriteProc TIFFGetWriteProc(TIFF*); extern TIFFSeekProc TIFFGetSeekProc(TIFF*); extern TIFFCloseProc TIFFGetCloseProc(TIFF*); extern TIFFSizeProc TIFFGetSizeProc(TIFF*); extern TIFFMapFileProc TIFFGetMapFileProc(TIFF*); extern TIFFUnmapFileProc TIFFGetUnmapFileProc(TIFF*); extern uint32 TIFFCurrentRow(TIFF*); extern uint16 TIFFCurrentDirectory(TIFF*); extern uint16 TIFFNumberOfDirectories(TIFF*); extern uint64 TIFFCurrentDirOffset(TIFF*); extern uint32 TIFFCurrentStrip(TIFF*); extern uint32 TIFFCurrentTile(TIFF* tif); extern int TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size); extern int TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size); extern int TIFFSetupStrips(TIFF *); extern int TIFFWriteCheck(TIFF*, int, const char *); extern void TIFFFreeDirectory(TIFF*); extern int TIFFCreateDirectory(TIFF*); extern int TIFFCreateCustomDirectory(TIFF*,const TIFFFieldArray*); extern int TIFFCreateEXIFDirectory(TIFF*); extern int TIFFLastDirectory(TIFF*); extern int TIFFSetDirectory(TIFF*, uint16); extern int TIFFSetSubDirectory(TIFF*, uint64); extern int TIFFUnlinkDirectory(TIFF*, uint16); extern int TIFFSetField(TIFF*, uint32, ...); extern int TIFFVSetField(TIFF*, uint32, va_list); extern int TIFFUnsetField(TIFF*, uint32); extern int TIFFWriteDirectory(TIFF *); extern int TIFFWriteCustomDirectory(TIFF *, uint64 *); extern int TIFFCheckpointDirectory(TIFF *); extern int TIFFRewriteDirectory(TIFF *); #if defined(c_plusplus) || defined(__cplusplus) extern void TIFFPrintDirectory(TIFF*, FILE*, long = 0); extern int TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample = 0); extern int TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample = 0); extern int TIFFReadRGBAImage(TIFF*, uint32, uint32, uint32*, int = 0); extern int TIFFReadRGBAImageOriented(TIFF*, uint32, uint32, uint32*, int = ORIENTATION_BOTLEFT, int = 0); #else extern void TIFFPrintDirectory(TIFF*, FILE*, long); extern int TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample); extern int TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample); extern int TIFFReadRGBAImage(TIFF*, uint32, uint32, uint32*, int); extern int TIFFReadRGBAImageOriented(TIFF*, uint32, uint32, uint32*, int, int); #endif extern int TIFFReadRGBAStrip(TIFF*, uint32, uint32 * ); extern int TIFFReadRGBATile(TIFF*, uint32, uint32, uint32 * ); extern int TIFFReadRGBAStripExt(TIFF*, uint32, uint32 *, int stop_on_error ); extern int TIFFReadRGBATileExt(TIFF*, uint32, uint32, uint32 *, int stop_on_error ); extern int TIFFRGBAImageOK(TIFF*, char [1024]); extern int TIFFRGBAImageBegin(TIFFRGBAImage*, TIFF*, int, char [1024]); extern int TIFFRGBAImageGet(TIFFRGBAImage*, uint32*, uint32, uint32); extern void TIFFRGBAImageEnd(TIFFRGBAImage*); extern TIFF* TIFFOpen(const char*, const char*); # ifdef __WIN32__ extern TIFF* TIFFOpenW(const wchar_t*, const char*); # endif /* __WIN32__ */ extern TIFF* TIFFFdOpen(int, const char*, const char*); extern TIFF* TIFFClientOpen(const char*, const char*, thandle_t, TIFFReadWriteProc, TIFFReadWriteProc, TIFFSeekProc, TIFFCloseProc, TIFFSizeProc, TIFFMapFileProc, TIFFUnmapFileProc); extern const char* TIFFFileName(TIFF*); extern const char* TIFFSetFileName(TIFF*, const char *); extern void TIFFError(const char*, const char*, ...) __attribute__((__format__ (__printf__,2,3))); extern void TIFFErrorExt(thandle_t, const char*, const char*, ...) __attribute__((__format__ (__printf__,3,4))); extern void TIFFWarning(const char*, const char*, ...) __attribute__((__format__ (__printf__,2,3))); extern void TIFFWarningExt(thandle_t, const char*, const char*, ...) __attribute__((__format__ (__printf__,3,4))); extern TIFFErrorHandler TIFFSetErrorHandler(TIFFErrorHandler); extern TIFFErrorHandlerExt TIFFSetErrorHandlerExt(TIFFErrorHandlerExt); extern TIFFErrorHandler TIFFSetWarningHandler(TIFFErrorHandler); extern TIFFErrorHandlerExt TIFFSetWarningHandlerExt(TIFFErrorHandlerExt); extern TIFFExtendProc TIFFSetTagExtender(TIFFExtendProc); extern uint32 TIFFComputeTile(TIFF* tif, uint32 x, uint32 y, uint32 z, uint16 s); extern int TIFFCheckTile(TIFF* tif, uint32 x, uint32 y, uint32 z, uint16 s); extern uint32 TIFFNumberOfTiles(TIFF*); extern tmsize_t TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s); extern tmsize_t TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s); extern uint32 TIFFComputeStrip(TIFF*, uint32, uint16); extern uint32 TIFFNumberOfStrips(TIFF*); extern tmsize_t TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size); extern tmsize_t TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size); extern tmsize_t TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size); extern tmsize_t TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size); extern tmsize_t TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc); extern tmsize_t TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc); extern tmsize_t TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc); extern tmsize_t TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc); extern int TIFFDataWidth(TIFFDataType); /* table of tag datatype widths */ extern void TIFFSetWriteOffset(TIFF* tif, toff_t off); extern void TIFFSwabShort(uint16*); extern void TIFFSwabLong(uint32*); extern void TIFFSwabLong8(uint64*); extern void TIFFSwabFloat(float*); extern void TIFFSwabDouble(double*); extern void TIFFSwabArrayOfShort(uint16* wp, tmsize_t n); extern void TIFFSwabArrayOfTriples(uint8* tp, tmsize_t n); extern void TIFFSwabArrayOfLong(uint32* lp, tmsize_t n); extern void TIFFSwabArrayOfLong8(uint64* lp, tmsize_t n); extern void TIFFSwabArrayOfFloat(float* fp, tmsize_t n); extern void TIFFSwabArrayOfDouble(double* dp, tmsize_t n); extern void TIFFReverseBits(uint8* cp, tmsize_t n); extern const unsigned char* TIFFGetBitRevTable(int); #ifdef LOGLUV_PUBLIC #define U_NEU 0.210526316 #define V_NEU 0.473684211 #define UVSCALE 410. extern double LogL16toY(int); extern double LogL10toY(int); extern void XYZtoRGB24(float*, uint8*); extern int uv_decode(double*, double*, int); extern void LogLuv24toXYZ(uint32, float*); extern void LogLuv32toXYZ(uint32, float*); #if defined(c_plusplus) || defined(__cplusplus) extern int LogL16fromY(double, int = SGILOGENCODE_NODITHER); extern int LogL10fromY(double, int = SGILOGENCODE_NODITHER); extern int uv_encode(double, double, int = SGILOGENCODE_NODITHER); extern uint32 LogLuv24fromXYZ(float*, int = SGILOGENCODE_NODITHER); extern uint32 LogLuv32fromXYZ(float*, int = SGILOGENCODE_NODITHER); #else extern int LogL16fromY(double, int); extern int LogL10fromY(double, int); extern int uv_encode(double, double, int); extern uint32 LogLuv24fromXYZ(float*, int); extern uint32 LogLuv32fromXYZ(float*, int); #endif #endif /* LOGLUV_PUBLIC */ extern int TIFFCIELabToRGBInit(TIFFCIELabToRGB*, const TIFFDisplay *, float*); extern void TIFFCIELabToXYZ(TIFFCIELabToRGB *, uint32, int32, int32, float *, float *, float *); extern void TIFFXYZToRGB(TIFFCIELabToRGB *, float, float, float, uint32 *, uint32 *, uint32 *); extern int TIFFYCbCrToRGBInit(TIFFYCbCrToRGB*, float*, float*); extern void TIFFYCbCrtoRGB(TIFFYCbCrToRGB *, uint32, int32, int32, uint32 *, uint32 *, uint32 *); /**************************************************************************** * O B S O L E T E D I N T E R F A C E S * * Don't use this stuff in your applications, it may be removed in the future * libtiff versions. ****************************************************************************/ typedef struct { ttag_t field_tag; /* field's tag */ short field_readcount; /* read count/TIFF_VARIABLE/TIFF_SPP */ short field_writecount; /* write count/TIFF_VARIABLE */ TIFFDataType field_type; /* type of associated data */ unsigned short field_bit; /* bit in fieldsset bit vector */ unsigned char field_oktochange; /* if true, can change while writing */ unsigned char field_passcount; /* if true, pass dir count on set */ char *field_name; /* ASCII name */ } TIFFFieldInfo; extern int TIFFMergeFieldInfo(TIFF*, const TIFFFieldInfo[], uint32); #if defined(c_plusplus) || defined(__cplusplus) } #endif #endif /* _TIFFIO_ */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */ execinfo.h000064400000002762151027430560006527 0ustar00/* Copyright (C) 1998-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _EXECINFO_H #define _EXECINFO_H 1 #include __BEGIN_DECLS /* Store up to SIZE return address of the current program state in ARRAY and return the exact number of values stored. */ extern int backtrace (void **__array, int __size) __nonnull ((1)); /* Return names of functions from the backtrace list in ARRAY in a newly malloc()ed memory block. */ extern char **backtrace_symbols (void *const *__array, int __size) __THROW __nonnull ((1)); /* This function is similar to backtrace_symbols() but it writes the result immediately to a file. */ extern void backtrace_symbols_fd (void *const *__array, int __size, int __fd) __THROW __nonnull ((1)); __END_DECLS #endif /* execinfo.h */ aliases.h000064400000003757151027430560006355 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _ALIASES_H #define _ALIASES_H 1 #include #include __BEGIN_DECLS /* Structure to represent one entry of the alias data base. */ struct aliasent { char *alias_name; size_t alias_members_len; char **alias_members; int alias_local; }; /* Open alias data base files. */ extern void setaliasent (void) __THROW; /* Close alias data base files. */ extern void endaliasent (void) __THROW; /* Get the next entry from the alias data base. */ extern struct aliasent *getaliasent (void) __THROW; /* Get the next entry from the alias data base and put it in RESULT_BUF. */ extern int getaliasent_r (struct aliasent *__restrict __result_buf, char *__restrict __buffer, size_t __buflen, struct aliasent **__restrict __result) __THROW; /* Get alias entry corresponding to NAME. */ extern struct aliasent *getaliasbyname (const char *__name) __THROW; /* Get alias entry corresponding to NAME and put it in RESULT_BUF. */ extern int getaliasbyname_r (const char *__restrict __name, struct aliasent *__restrict __result_buf, char *__restrict __buffer, size_t __buflen, struct aliasent **__restrict __result) __THROW; __END_DECLS #endif /* aliases.h */ gdfontl.h000064400000001047151027430560006357 0ustar00#ifndef _GDFONTL_H_ #define _GDFONTL_H_ 1 #ifdef __cplusplus extern "C" { #endif /* This is a header file for gd font, generated using bdftogd version 0.5 by Jan Pazdziora, adelton@fi.muni.cz from bdf font -misc-fixed-medium-r-normal--16-140-75-75-c-80-iso8859-2 at Tue Jan 6 19:39:27 1998. The original bdf was holding following copyright: "Libor Skarvada, libor@informatics.muni.cz" */ #include "gd.h" extern BGD_EXPORT_DATA_PROT gdFontPtr gdFontLarge; BGD_DECLARE(gdFontPtr) gdFontGetLarge(void); #ifdef __cplusplus } #endif #endif netrom/netrom.h000064400000004261151027430560007533 0ustar00/* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _NETROM_NETROM_H #define _NETROM_NETROM_H 1 #include /* Setsockoptions(2) level. Thanks to BSD these must match IPPROTO_xxx. */ #define SOL_NETROM 259 /* NetRom control values: */ #define NETROM_T1 1 #define NETROM_T2 2 #define NETROM_N2 3 #define NETROM_PACLEN 5 #define NETROM_T4 6 #define NETROM_IDLE 7 #define NETROM_KILL 99 /* Type of route: */ #define NETROM_NEIGH 0 #define NETROM_NODE 1 struct nr_route_struct { int type; ax25_address callsign; char device[16]; unsigned int quality; char mnemonic[7]; ax25_address neighbour; unsigned int obs_count; unsigned int ndigis; ax25_address digipeaters[AX25_MAX_DIGIS]; }; /* NetRom socket ioctls: */ #define SIOCNRGETPARMS (SIOCPROTOPRIVATE+0) #define SIOCNRSETPARMS (SIOCPROTOPRIVATE+1) #define SIOCNRDECOBS (SIOCPROTOPRIVATE+2) #define SIOCNRRTCTL (SIOCPROTOPRIVATE+3) #define SIOCNRCTLCON (SIOCPROTOPRIVATE+4) /* NetRom parameter structure: */ struct nr_parms_struct { unsigned int quality; unsigned int obs_count; unsigned int ttl; unsigned int timeout; unsigned int ack_delay; unsigned int busy_delay; unsigned int tries; unsigned int window; unsigned int paclen; }; /* NetRom control structure: */ struct nr_ctl_struct { unsigned char index; unsigned char id; unsigned int cmd; unsigned long arg; }; #endif /* netrom/netrom.h */ mcheck.h000064400000004602151027430560006154 0ustar00/* Copyright (C) 1996-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ #ifndef _MCHECK_H #define _MCHECK_H 1 #include __BEGIN_DECLS /* Return values for `mprobe': these are the kinds of inconsistencies that `mcheck' enables detection of. */ enum mcheck_status { MCHECK_DISABLED = -1, /* Consistency checking is not turned on. */ MCHECK_OK, /* Block is fine. */ MCHECK_FREE, /* Block freed twice. */ MCHECK_HEAD, /* Memory before the block was clobbered. */ MCHECK_TAIL /* Memory after the block was clobbered. */ }; /* Activate a standard collection of debugging hooks. This must be called before `malloc' is ever called. ABORTFUNC is called with an error code (see enum above) when an inconsistency is detected. If ABORTFUNC is null, the standard function prints on stderr and then calls `abort'. */ extern int mcheck (void (*__abortfunc)(enum mcheck_status)) __THROW; /* Similar to `mcheck' but performs checks for all block whenever one of the memory handling functions is called. This can be very slow. */ extern int mcheck_pedantic (void (*__abortfunc)(enum mcheck_status)) __THROW; /* Force check of all blocks now. */ extern void mcheck_check_all (void); /* Check for aberrations in a particular malloc'd block. You must have called `mcheck' already. These are the same checks that `mcheck' does when you free or reallocate a block. */ extern enum mcheck_status mprobe (void *__ptr) __THROW; /* Activate a standard collection of tracing hooks. */ extern void mtrace (void) __THROW; extern void muntrace (void) __THROW; __END_DECLS #endif /* mcheck.h */ setjmp.h000064400000007125151027430560006227 0ustar00/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* * ISO C99 Standard: 7.13 Nonlocal jumps */ #ifndef _SETJMP_H #define _SETJMP_H 1 #include __BEGIN_DECLS #include /* Get `__jmp_buf'. */ #include /* Calling environment, plus possibly a saved signal mask. */ struct __jmp_buf_tag { /* NOTE: The machine-dependent definitions of `__sigsetjmp' assume that a `jmp_buf' begins with a `__jmp_buf' and that `__mask_was_saved' follows it. Do not move these members or add others before it. */ __jmp_buf __jmpbuf; /* Calling environment. */ int __mask_was_saved; /* Saved the signal mask? */ __sigset_t __saved_mask; /* Saved signal mask. */ }; typedef struct __jmp_buf_tag jmp_buf[1]; /* Store the calling environment in ENV, also saving the signal mask. Return 0. */ extern int setjmp (jmp_buf __env) __THROWNL; /* Store the calling environment in ENV, also saving the signal mask if SAVEMASK is nonzero. Return 0. This is the internal name for `sigsetjmp'. */ extern int __sigsetjmp (struct __jmp_buf_tag __env[1], int __savemask) __THROWNL; /* Store the calling environment in ENV, not saving the signal mask. Return 0. */ extern int _setjmp (struct __jmp_buf_tag __env[1]) __THROWNL; /* Do not save the signal mask. This is equivalent to the `_setjmp' BSD function. */ #define setjmp(env) _setjmp (env) /* Jump to the environment saved in ENV, making the `setjmp' call there return VAL, or 1 if VAL is 0. */ extern void longjmp (struct __jmp_buf_tag __env[1], int __val) __THROWNL __attribute__ ((__noreturn__)); #if defined __USE_MISC || defined __USE_XOPEN /* Same. Usually `_longjmp' is used with `_setjmp', which does not save the signal mask. But it is how ENV was saved that determines whether `longjmp' restores the mask; `_longjmp' is just an alias. */ extern void _longjmp (struct __jmp_buf_tag __env[1], int __val) __THROWNL __attribute__ ((__noreturn__)); #endif #ifdef __USE_POSIX /* Use the same type for `jmp_buf' and `sigjmp_buf'. The `__mask_was_saved' flag determines whether or not `longjmp' will restore the signal mask. */ typedef struct __jmp_buf_tag sigjmp_buf[1]; /* Store the calling environment in ENV, also saving the signal mask if SAVEMASK is nonzero. Return 0. */ # define sigsetjmp(env, savemask) __sigsetjmp (env, savemask) /* Jump to the environment saved in ENV, making the sigsetjmp call there return VAL, or 1 if VAL is 0. Restore the signal mask if that sigsetjmp call saved it. This is just an alias `longjmp'. */ extern void siglongjmp (sigjmp_buf __env, int __val) __THROWNL __attribute__ ((__noreturn__)); #endif /* Use POSIX. */ /* Define helper functions to catch unsafe code. */ #if __USE_FORTIFY_LEVEL > 0 # include #endif __END_DECLS #endif /* setjmp.h */ obstack.h000064400000051472151027430560006357 0ustar00/* obstack.h - object stack macros Copyright (C) 1988-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see . */ /* Summary: All the apparent functions defined here are macros. The idea is that you would use these pre-tested macros to solve a very specific set of problems, and they would run fast. Caution: no side-effects in arguments please!! They may be evaluated MANY times!! These macros operate a stack of objects. Each object starts life small, and may grow to maturity. (Consider building a word syllable by syllable.) An object can move while it is growing. Once it has been "finished" it never changes address again. So the "top of the stack" is typically an immature growing object, while the rest of the stack is of mature, fixed size and fixed address objects. These routines grab large chunks of memory, using a function you supply, called 'obstack_chunk_alloc'. On occasion, they free chunks, by calling 'obstack_chunk_free'. You must define them and declare them before using any obstack macros. Each independent stack is represented by a 'struct obstack'. Each of the obstack macros expects a pointer to such a structure as the first argument. One motivation for this package is the problem of growing char strings in symbol tables. Unless you are "fascist pig with a read-only mind" --Gosper's immortal quote from HAKMEM item 154, out of context--you would not like to put any arbitrary upper limit on the length of your symbols. In practice this often means you will build many short symbols and a few long symbols. At the time you are reading a symbol you don't know how long it is. One traditional method is to read a symbol into a buffer, realloc()ating the buffer every time you try to read a symbol that is longer than the buffer. This is beaut, but you still will want to copy the symbol from the buffer to a more permanent symbol-table entry say about half the time. With obstacks, you can work differently. Use one obstack for all symbol names. As you read a symbol, grow the name in the obstack gradually. When the name is complete, finalize it. Then, if the symbol exists already, free the newly read name. The way we do this is to take a large chunk, allocating memory from low addresses. When you want to build a symbol in the chunk you just add chars above the current "high water mark" in the chunk. When you have finished adding chars, because you got to the end of the symbol, you know how long the chars are, and you can create a new object. Mostly the chars will not burst over the highest address of the chunk, because you would typically expect a chunk to be (say) 100 times as long as an average object. In case that isn't clear, when we have enough chars to make up the object, THEY ARE ALREADY CONTIGUOUS IN THE CHUNK (guaranteed) so we just point to it where it lies. No moving of chars is needed and this is the second win: potentially long strings need never be explicitly shuffled. Once an object is formed, it does not change its address during its lifetime. When the chars burst over a chunk boundary, we allocate a larger chunk, and then copy the partly formed object from the end of the old chunk to the beginning of the new larger chunk. We then carry on accreting characters to the end of the object as we normally would. A special macro is provided to add a single char at a time to a growing object. This allows the use of register variables, which break the ordinary 'growth' macro. Summary: We allocate large chunks. We carve out one object at a time from the current chunk. Once carved, an object never moves. We are free to append data of any size to the currently growing object. Exactly one object is growing in an obstack at any one time. You can run one obstack per control block. You may have as many control blocks as you dare. Because of the way we do it, you can "unwind" an obstack back to a previous state. (You may remove objects much as you would with a stack.) */ /* Don't do the contents of this file more than once. */ #ifndef _OBSTACK_H #define _OBSTACK_H 1 /* We need the type of a pointer subtraction. If __PTRDIFF_TYPE__ is defined, as with GNU C, use that; that way we don't pollute the namespace with 's symbols. Otherwise, include and use ptrdiff_t. */ #ifdef __PTRDIFF_TYPE__ # define PTR_INT_TYPE __PTRDIFF_TYPE__ #else # include # define PTR_INT_TYPE ptrdiff_t #endif /* If B is the base of an object addressed by P, return the result of aligning P to the next multiple of A + 1. B and P must be of type char *. A + 1 must be a power of 2. */ #define __BPTR_ALIGN(B, P, A) ((B) + (((P) - (B) + (A)) & ~(A))) /* Similar to _BPTR_ALIGN (B, P, A), except optimize the common case where pointers can be converted to integers, aligned as integers, and converted back again. If PTR_INT_TYPE is narrower than a pointer (e.g., the AS/400), play it safe and compute the alignment relative to B. Otherwise, use the faster strategy of computing the alignment relative to 0. */ #define __PTR_ALIGN(B, P, A) \ __BPTR_ALIGN (sizeof (PTR_INT_TYPE) < sizeof (void *) ? (B) : (char *) 0, \ P, A) #include #ifndef __attribute_pure__ # define __attribute_pure__ _GL_ATTRIBUTE_PURE #endif #ifdef __cplusplus extern "C" { #endif struct _obstack_chunk /* Lives at front of each chunk. */ { char *limit; /* 1 past end of this chunk */ struct _obstack_chunk *prev; /* address of prior chunk or NULL */ char contents[4]; /* objects begin here */ }; struct obstack /* control current object in current chunk */ { long chunk_size; /* preferred size to allocate chunks in */ struct _obstack_chunk *chunk; /* address of current struct obstack_chunk */ char *object_base; /* address of object we are building */ char *next_free; /* where to add next char to current object */ char *chunk_limit; /* address of char after current chunk */ union { PTR_INT_TYPE tempint; void *tempptr; } temp; /* Temporary for some macros. */ int alignment_mask; /* Mask of alignment for each object. */ /* These prototypes vary based on 'use_extra_arg', and we use casts to the prototypeless function type in all assignments, but having prototypes here quiets -Wstrict-prototypes. */ struct _obstack_chunk *(*chunkfun) (void *, long); void (*freefun) (void *, struct _obstack_chunk *); void *extra_arg; /* first arg for chunk alloc/dealloc funcs */ unsigned use_extra_arg : 1; /* chunk alloc/dealloc funcs take extra arg */ unsigned maybe_empty_object : 1; /* There is a possibility that the current chunk contains a zero-length object. This prevents freeing the chunk if we allocate a bigger chunk to replace it. */ unsigned alloc_failed : 1; /* No longer used, as we now call the failed handler on error, but retained for binary compatibility. */ }; /* Declare the external functions we use; they are in obstack.c. */ extern void _obstack_newchunk (struct obstack *, int); extern int _obstack_begin (struct obstack *, int, int, void *(*)(long), void (*)(void *)); extern int _obstack_begin_1 (struct obstack *, int, int, void *(*)(void *, long), void (*)(void *, void *), void *); extern int _obstack_memory_used (struct obstack *) __attribute_pure__; /* The default name of the function for freeing a chunk is 'obstack_free', but gnulib users can override this by defining '__obstack_free'. */ #ifndef __obstack_free # define __obstack_free obstack_free #endif extern void __obstack_free (struct obstack *, void *); /* Error handler called when 'obstack_chunk_alloc' failed to allocate more memory. This can be set to a user defined function which should either abort gracefully or use longjump - but shouldn't return. The default action is to print a message and abort. */ extern void (*obstack_alloc_failed_handler) (void); /* Exit value used when 'print_and_abort' is used. */ extern int obstack_exit_failure; /* Pointer to beginning of object being allocated or to be allocated next. Note that this might not be the final address of the object because a new chunk might be needed to hold the final size. */ #define obstack_base(h) ((void *) (h)->object_base) /* Size for allocating ordinary chunks. */ #define obstack_chunk_size(h) ((h)->chunk_size) /* Pointer to next byte not yet allocated in current chunk. */ #define obstack_next_free(h) ((h)->next_free) /* Mask specifying low bits that should be clear in address of an object. */ #define obstack_alignment_mask(h) ((h)->alignment_mask) /* To prevent prototype warnings provide complete argument list. */ #define obstack_init(h) \ _obstack_begin ((h), 0, 0, \ (void *(*)(long))obstack_chunk_alloc, \ (void (*)(void *))obstack_chunk_free) #define obstack_begin(h, size) \ _obstack_begin ((h), (size), 0, \ (void *(*)(long))obstack_chunk_alloc, \ (void (*)(void *))obstack_chunk_free) #define obstack_specify_allocation(h, size, alignment, chunkfun, freefun) \ _obstack_begin ((h), (size), (alignment), \ (void *(*)(long))(chunkfun), \ (void (*)(void *))(freefun)) #define obstack_specify_allocation_with_arg(h, size, alignment, chunkfun, freefun, arg) \ _obstack_begin_1 ((h), (size), (alignment), \ (void *(*)(void *, long))(chunkfun), \ (void (*)(void *, void *))(freefun), (arg)) #define obstack_chunkfun(h, newchunkfun) \ ((h)->chunkfun = (struct _obstack_chunk *(*)(void *, long))(newchunkfun)) #define obstack_freefun(h, newfreefun) \ ((h)->freefun = (void (*)(void *, struct _obstack_chunk *))(newfreefun)) #define obstack_1grow_fast(h, achar) (*((h)->next_free)++ = (achar)) #define obstack_blank_fast(h, n) ((h)->next_free += (n)) #define obstack_memory_used(h) _obstack_memory_used (h) #if defined __GNUC__ # if ! (2 < __GNUC__ + (8 <= __GNUC_MINOR__)) # define __extension__ # endif /* For GNU C, if not -traditional, we can define these macros to compute all args only once without using a global variable. Also, we can avoid using the 'temp' slot, to make faster code. */ # define obstack_object_size(OBSTACK) \ __extension__ \ ({ struct obstack const *__o = (OBSTACK); \ (unsigned) (__o->next_free - __o->object_base); }) # define obstack_room(OBSTACK) \ __extension__ \ ({ struct obstack const *__o = (OBSTACK); \ (unsigned) (__o->chunk_limit - __o->next_free); }) # define obstack_make_room(OBSTACK, length) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ int __len = (length); \ if (__o->chunk_limit - __o->next_free < __len) \ _obstack_newchunk (__o, __len); \ (void) 0; }) # define obstack_empty_p(OBSTACK) \ __extension__ \ ({ struct obstack const *__o = (OBSTACK); \ (__o->chunk->prev == 0 \ && __o->next_free == __PTR_ALIGN ((char *) __o->chunk, \ __o->chunk->contents, \ __o->alignment_mask)); }) # define obstack_grow(OBSTACK, where, length) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ int __len = (length); \ if (__o->next_free + __len > __o->chunk_limit) \ _obstack_newchunk (__o, __len); \ memcpy (__o->next_free, where, __len); \ __o->next_free += __len; \ (void) 0; }) # define obstack_grow0(OBSTACK, where, length) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ int __len = (length); \ if (__o->next_free + __len + 1 > __o->chunk_limit) \ _obstack_newchunk (__o, __len + 1); \ memcpy (__o->next_free, where, __len); \ __o->next_free += __len; \ *(__o->next_free)++ = 0; \ (void) 0; }) # define obstack_1grow(OBSTACK, datum) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ if (__o->next_free + 1 > __o->chunk_limit) \ _obstack_newchunk (__o, 1); \ obstack_1grow_fast (__o, datum); \ (void) 0; }) /* These assume that the obstack alignment is good enough for pointers or ints, and that the data added so far to the current object shares that much alignment. */ # define obstack_ptr_grow(OBSTACK, datum) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ if (__o->next_free + sizeof (void *) > __o->chunk_limit) \ _obstack_newchunk (__o, sizeof (void *)); \ obstack_ptr_grow_fast (__o, datum); }) \ # define obstack_int_grow(OBSTACK, datum) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ if (__o->next_free + sizeof (int) > __o->chunk_limit) \ _obstack_newchunk (__o, sizeof (int)); \ obstack_int_grow_fast (__o, datum); }) # define obstack_ptr_grow_fast(OBSTACK, aptr) \ __extension__ \ ({ struct obstack *__o1 = (OBSTACK); \ void *__p1 = __o1->next_free; \ *(const void **) __p1 = (aptr); \ __o1->next_free += sizeof (const void *); \ (void) 0; }) # define obstack_int_grow_fast(OBSTACK, aint) \ __extension__ \ ({ struct obstack *__o1 = (OBSTACK); \ void *__p1 = __o1->next_free; \ *(int *) __p1 = (aint); \ __o1->next_free += sizeof (int); \ (void) 0; }) # define obstack_blank(OBSTACK, length) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ int __len = (length); \ if (__o->chunk_limit - __o->next_free < __len) \ _obstack_newchunk (__o, __len); \ obstack_blank_fast (__o, __len); \ (void) 0; }) # define obstack_alloc(OBSTACK, length) \ __extension__ \ ({ struct obstack *__h = (OBSTACK); \ obstack_blank (__h, (length)); \ obstack_finish (__h); }) # define obstack_copy(OBSTACK, where, length) \ __extension__ \ ({ struct obstack *__h = (OBSTACK); \ obstack_grow (__h, (where), (length)); \ obstack_finish (__h); }) # define obstack_copy0(OBSTACK, where, length) \ __extension__ \ ({ struct obstack *__h = (OBSTACK); \ obstack_grow0 (__h, (where), (length)); \ obstack_finish (__h); }) /* The local variable is named __o1 to avoid a name conflict when obstack_blank is called. */ # define obstack_finish(OBSTACK) \ __extension__ \ ({ struct obstack *__o1 = (OBSTACK); \ void *__value = (void *) __o1->object_base; \ if (__o1->next_free == __value) \ __o1->maybe_empty_object = 1; \ __o1->next_free \ = __PTR_ALIGN (__o1->object_base, __o1->next_free, \ __o1->alignment_mask); \ if (__o1->next_free - (char *) __o1->chunk \ > __o1->chunk_limit - (char *) __o1->chunk) \ __o1->next_free = __o1->chunk_limit; \ __o1->object_base = __o1->next_free; \ __value; }) # define obstack_free(OBSTACK, OBJ) \ __extension__ \ ({ struct obstack *__o = (OBSTACK); \ void *__obj = (OBJ); \ if (__obj > (void *) __o->chunk && __obj < (void *) __o->chunk_limit) \ __o->next_free = __o->object_base = (char *) __obj; \ else (__obstack_free) (__o, __obj); }) #else /* not __GNUC__ */ # define obstack_object_size(h) \ (unsigned) ((h)->next_free - (h)->object_base) # define obstack_room(h) \ (unsigned) ((h)->chunk_limit - (h)->next_free) # define obstack_empty_p(h) \ ((h)->chunk->prev == 0 \ && (h)->next_free == __PTR_ALIGN ((char *) (h)->chunk, \ (h)->chunk->contents, \ (h)->alignment_mask)) /* Note that the call to _obstack_newchunk is enclosed in (..., 0) so that we can avoid having void expressions in the arms of the conditional expression. Casting the third operand to void was tried before, but some compilers won't accept it. */ # define obstack_make_room(h, length) \ ((h)->temp.tempint = (length), \ (((h)->next_free + (h)->temp.tempint > (h)->chunk_limit) \ ? (_obstack_newchunk ((h), (h)->temp.tempint), 0) : 0)) # define obstack_grow(h, where, length) \ ((h)->temp.tempint = (length), \ (((h)->next_free + (h)->temp.tempint > (h)->chunk_limit) \ ? (_obstack_newchunk ((h), (h)->temp.tempint), 0) : 0), \ memcpy ((h)->next_free, where, (h)->temp.tempint), \ (h)->next_free += (h)->temp.tempint) # define obstack_grow0(h, where, length) \ ((h)->temp.tempint = (length), \ (((h)->next_free + (h)->temp.tempint + 1 > (h)->chunk_limit) \ ? (_obstack_newchunk ((h), (h)->temp.tempint + 1), 0) : 0), \ memcpy ((h)->next_free, where, (h)->temp.tempint), \ (h)->next_free += (h)->temp.tempint, \ *((h)->next_free)++ = 0) # define obstack_1grow(h, datum) \ ((((h)->next_free + 1 > (h)->chunk_limit) \ ? (_obstack_newchunk ((h), 1), 0) : 0), \ obstack_1grow_fast (h, datum)) # define obstack_ptr_grow(h, datum) \ ((((h)->next_free + sizeof (char *) > (h)->chunk_limit) \ ? (_obstack_newchunk ((h), sizeof (char *)), 0) : 0), \ obstack_ptr_grow_fast (h, datum)) # define obstack_int_grow(h, datum) \ ((((h)->next_free + sizeof (int) > (h)->chunk_limit) \ ? (_obstack_newchunk ((h), sizeof (int)), 0) : 0), \ obstack_int_grow_fast (h, datum)) # define obstack_ptr_grow_fast(h, aptr) \ (((const void **) ((h)->next_free += sizeof (void *)))[-1] = (aptr)) # define obstack_int_grow_fast(h, aint) \ (((int *) ((h)->next_free += sizeof (int)))[-1] = (aint)) # define obstack_blank(h, length) \ ((h)->temp.tempint = (length), \ (((h)->chunk_limit - (h)->next_free < (h)->temp.tempint) \ ? (_obstack_newchunk ((h), (h)->temp.tempint), 0) : 0), \ obstack_blank_fast (h, (h)->temp.tempint)) # define obstack_alloc(h, length) \ (obstack_blank ((h), (length)), obstack_finish ((h))) # define obstack_copy(h, where, length) \ (obstack_grow ((h), (where), (length)), obstack_finish ((h))) # define obstack_copy0(h, where, length) \ (obstack_grow0 ((h), (where), (length)), obstack_finish ((h))) # define obstack_finish(h) \ (((h)->next_free == (h)->object_base \ ? (((h)->maybe_empty_object = 1), 0) \ : 0), \ (h)->temp.tempptr = (h)->object_base, \ (h)->next_free \ = __PTR_ALIGN ((h)->object_base, (h)->next_free, \ (h)->alignment_mask), \ (((h)->next_free - (char *) (h)->chunk \ > (h)->chunk_limit - (char *) (h)->chunk) \ ? ((h)->next_free = (h)->chunk_limit) : 0), \ (h)->object_base = (h)->next_free, \ (h)->temp.tempptr) # define obstack_free(h, obj) \ ((h)->temp.tempint = (char *) (obj) - (char *) (h)->chunk, \ ((((h)->temp.tempint > 0 \ && (h)->temp.tempint < (h)->chunk_limit - (char *) (h)->chunk)) \ ? (void) ((h)->next_free = (h)->object_base \ = (h)->temp.tempint + (char *) (h)->chunk) \ : (__obstack_free) (h, (h)->temp.tempint + (char *) (h)->chunk))) #endif /* not __GNUC__ */ #ifdef __cplusplus } /* C++ */ #endif #endif /* obstack.h */ mysql/mysqld_error.h000064400000135573151027430560010625 0ustar00/* Autogenerated file, please don't edit */ #ifndef ER_ERROR_FIRST #define ER_ERROR_FIRST 1000 #define ER_HASHCHK 1000 #define ER_NISAMCHK 1001 #define ER_NO 1002 #define ER_YES 1003 #define ER_CANT_CREATE_FILE 1004 #define ER_CANT_CREATE_TABLE 1005 #define ER_CANT_CREATE_DB 1006 #define ER_DB_CREATE_EXISTS 1007 #define ER_DB_DROP_EXISTS 1008 #define ER_DB_DROP_DELETE 1009 #define ER_DB_DROP_RMDIR 1010 #define ER_CANT_DELETE_FILE 1011 #define ER_CANT_FIND_SYSTEM_REC 1012 #define ER_CANT_GET_STAT 1013 #define ER_CANT_GET_WD 1014 #define ER_CANT_LOCK 1015 #define ER_CANT_OPEN_FILE 1016 #define ER_FILE_NOT_FOUND 1017 #define ER_CANT_READ_DIR 1018 #define ER_CANT_SET_WD 1019 #define ER_CHECKREAD 1020 #define ER_DISK_FULL 1021 #define ER_DUP_KEY 1022 #define ER_ERROR_ON_CLOSE 1023 #define ER_ERROR_ON_READ 1024 #define ER_ERROR_ON_RENAME 1025 #define ER_ERROR_ON_WRITE 1026 #define ER_FILE_USED 1027 #define ER_FILSORT_ABORT 1028 #define ER_FORM_NOT_FOUND 1029 #define ER_GET_ERRNO 1030 #define ER_ILLEGAL_HA 1031 #define ER_KEY_NOT_FOUND 1032 #define ER_NOT_FORM_FILE 1033 #define ER_NOT_KEYFILE 1034 #define ER_OLD_KEYFILE 1035 #define ER_OPEN_AS_READONLY 1036 #define ER_OUTOFMEMORY 1037 #define ER_OUT_OF_SORTMEMORY 1038 #define ER_UNEXPECTED_EOF 1039 #define ER_CON_COUNT_ERROR 1040 #define ER_OUT_OF_RESOURCES 1041 #define ER_BAD_HOST_ERROR 1042 #define ER_HANDSHAKE_ERROR 1043 #define ER_DBACCESS_DENIED_ERROR 1044 #define ER_ACCESS_DENIED_ERROR 1045 #define ER_NO_DB_ERROR 1046 #define ER_UNKNOWN_COM_ERROR 1047 #define ER_BAD_NULL_ERROR 1048 #define ER_BAD_DB_ERROR 1049 #define ER_TABLE_EXISTS_ERROR 1050 #define ER_BAD_TABLE_ERROR 1051 #define ER_NON_UNIQ_ERROR 1052 #define ER_SERVER_SHUTDOWN 1053 #define ER_BAD_FIELD_ERROR 1054 #define ER_WRONG_FIELD_WITH_GROUP 1055 #define ER_WRONG_GROUP_FIELD 1056 #define ER_WRONG_SUM_SELECT 1057 #define ER_WRONG_VALUE_COUNT 1058 #define ER_TOO_LONG_IDENT 1059 #define ER_DUP_FIELDNAME 1060 #define ER_DUP_KEYNAME 1061 #define ER_DUP_ENTRY 1062 #define ER_WRONG_FIELD_SPEC 1063 #define ER_PARSE_ERROR 1064 #define ER_EMPTY_QUERY 1065 #define ER_NONUNIQ_TABLE 1066 #define ER_INVALID_DEFAULT 1067 #define ER_MULTIPLE_PRI_KEY 1068 #define ER_TOO_MANY_KEYS 1069 #define ER_TOO_MANY_KEY_PARTS 1070 #define ER_TOO_LONG_KEY 1071 #define ER_KEY_COLUMN_DOES_NOT_EXITS 1072 #define ER_BLOB_USED_AS_KEY 1073 #define ER_TOO_BIG_FIELDLENGTH 1074 #define ER_WRONG_AUTO_KEY 1075 #define ER_BINLOG_CANT_DELETE_GTID_DOMAIN 1076 #define ER_NORMAL_SHUTDOWN 1077 #define ER_GOT_SIGNAL 1078 #define ER_SHUTDOWN_COMPLETE 1079 #define ER_FORCING_CLOSE 1080 #define ER_IPSOCK_ERROR 1081 #define ER_NO_SUCH_INDEX 1082 #define ER_WRONG_FIELD_TERMINATORS 1083 #define ER_BLOBS_AND_NO_TERMINATED 1084 #define ER_TEXTFILE_NOT_READABLE 1085 #define ER_FILE_EXISTS_ERROR 1086 #define ER_LOAD_INFO 1087 #define ER_ALTER_INFO 1088 #define ER_WRONG_SUB_KEY 1089 #define ER_CANT_REMOVE_ALL_FIELDS 1090 #define ER_CANT_DROP_FIELD_OR_KEY 1091 #define ER_INSERT_INFO 1092 #define ER_UPDATE_TABLE_USED 1093 #define ER_NO_SUCH_THREAD 1094 #define ER_KILL_DENIED_ERROR 1095 #define ER_NO_TABLES_USED 1096 #define ER_TOO_BIG_SET 1097 #define ER_NO_UNIQUE_LOGFILE 1098 #define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099 #define ER_TABLE_NOT_LOCKED 1100 #define ER_UNUSED_17 1101 #define ER_WRONG_DB_NAME 1102 #define ER_WRONG_TABLE_NAME 1103 #define ER_TOO_BIG_SELECT 1104 #define ER_UNKNOWN_ERROR 1105 #define ER_UNKNOWN_PROCEDURE 1106 #define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107 #define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108 #define ER_UNKNOWN_TABLE 1109 #define ER_FIELD_SPECIFIED_TWICE 1110 #define ER_INVALID_GROUP_FUNC_USE 1111 #define ER_UNSUPPORTED_EXTENSION 1112 #define ER_TABLE_MUST_HAVE_COLUMNS 1113 #define ER_RECORD_FILE_FULL 1114 #define ER_UNKNOWN_CHARACTER_SET 1115 #define ER_TOO_MANY_TABLES 1116 #define ER_TOO_MANY_FIELDS 1117 #define ER_TOO_BIG_ROWSIZE 1118 #define ER_STACK_OVERRUN 1119 #define ER_WRONG_OUTER_JOIN 1120 #define ER_NULL_COLUMN_IN_INDEX 1121 #define ER_CANT_FIND_UDF 1122 #define ER_CANT_INITIALIZE_UDF 1123 #define ER_UDF_NO_PATHS 1124 #define ER_UDF_EXISTS 1125 #define ER_CANT_OPEN_LIBRARY 1126 #define ER_CANT_FIND_DL_ENTRY 1127 #define ER_FUNCTION_NOT_DEFINED 1128 #define ER_HOST_IS_BLOCKED 1129 #define ER_HOST_NOT_PRIVILEGED 1130 #define ER_PASSWORD_ANONYMOUS_USER 1131 #define ER_PASSWORD_NOT_ALLOWED 1132 #define ER_PASSWORD_NO_MATCH 1133 #define ER_UPDATE_INFO 1134 #define ER_CANT_CREATE_THREAD 1135 #define ER_WRONG_VALUE_COUNT_ON_ROW 1136 #define ER_CANT_REOPEN_TABLE 1137 #define ER_INVALID_USE_OF_NULL 1138 #define ER_REGEXP_ERROR 1139 #define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140 #define ER_NONEXISTING_GRANT 1141 #define ER_TABLEACCESS_DENIED_ERROR 1142 #define ER_COLUMNACCESS_DENIED_ERROR 1143 #define ER_ILLEGAL_GRANT_FOR_TABLE 1144 #define ER_GRANT_WRONG_HOST_OR_USER 1145 #define ER_NO_SUCH_TABLE 1146 #define ER_NONEXISTING_TABLE_GRANT 1147 #define ER_NOT_ALLOWED_COMMAND 1148 #define ER_SYNTAX_ERROR 1149 #define ER_DELAYED_CANT_CHANGE_LOCK 1150 #define ER_TOO_MANY_DELAYED_THREADS 1151 #define ER_ABORTING_CONNECTION 1152 #define ER_NET_PACKET_TOO_LARGE 1153 #define ER_NET_READ_ERROR_FROM_PIPE 1154 #define ER_NET_FCNTL_ERROR 1155 #define ER_NET_PACKETS_OUT_OF_ORDER 1156 #define ER_NET_UNCOMPRESS_ERROR 1157 #define ER_NET_READ_ERROR 1158 #define ER_NET_READ_INTERRUPTED 1159 #define ER_NET_ERROR_ON_WRITE 1160 #define ER_NET_WRITE_INTERRUPTED 1161 #define ER_TOO_LONG_STRING 1162 #define ER_TABLE_CANT_HANDLE_BLOB 1163 #define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164 #define ER_DELAYED_INSERT_TABLE_LOCKED 1165 #define ER_WRONG_COLUMN_NAME 1166 #define ER_WRONG_KEY_COLUMN 1167 #define ER_WRONG_MRG_TABLE 1168 #define ER_DUP_UNIQUE 1169 #define ER_BLOB_KEY_WITHOUT_LENGTH 1170 #define ER_PRIMARY_CANT_HAVE_NULL 1171 #define ER_TOO_MANY_ROWS 1172 #define ER_REQUIRES_PRIMARY_KEY 1173 #define ER_NO_RAID_COMPILED 1174 #define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175 #define ER_KEY_DOES_NOT_EXISTS 1176 #define ER_CHECK_NO_SUCH_TABLE 1177 #define ER_CHECK_NOT_IMPLEMENTED 1178 #define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179 #define ER_ERROR_DURING_COMMIT 1180 #define ER_ERROR_DURING_ROLLBACK 1181 #define ER_ERROR_DURING_FLUSH_LOGS 1182 #define ER_ERROR_DURING_CHECKPOINT 1183 #define ER_NEW_ABORTING_CONNECTION 1184 #define ER_UNUSED_10 1185 #define ER_FLUSH_MASTER_BINLOG_CLOSED 1186 #define ER_INDEX_REBUILD 1187 #define ER_MASTER 1188 #define ER_MASTER_NET_READ 1189 #define ER_MASTER_NET_WRITE 1190 #define ER_FT_MATCHING_KEY_NOT_FOUND 1191 #define ER_LOCK_OR_ACTIVE_TRANSACTION 1192 #define ER_UNKNOWN_SYSTEM_VARIABLE 1193 #define ER_CRASHED_ON_USAGE 1194 #define ER_CRASHED_ON_REPAIR 1195 #define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196 #define ER_TRANS_CACHE_FULL 1197 #define ER_SLAVE_MUST_STOP 1198 #define ER_SLAVE_NOT_RUNNING 1199 #define ER_BAD_SLAVE 1200 #define ER_MASTER_INFO 1201 #define ER_SLAVE_THREAD 1202 #define ER_TOO_MANY_USER_CONNECTIONS 1203 #define ER_SET_CONSTANTS_ONLY 1204 #define ER_LOCK_WAIT_TIMEOUT 1205 #define ER_LOCK_TABLE_FULL 1206 #define ER_READ_ONLY_TRANSACTION 1207 #define ER_DROP_DB_WITH_READ_LOCK 1208 #define ER_CREATE_DB_WITH_READ_LOCK 1209 #define ER_WRONG_ARGUMENTS 1210 #define ER_NO_PERMISSION_TO_CREATE_USER 1211 #define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212 #define ER_LOCK_DEADLOCK 1213 #define ER_TABLE_CANT_HANDLE_FT 1214 #define ER_CANNOT_ADD_FOREIGN 1215 #define ER_NO_REFERENCED_ROW 1216 #define ER_ROW_IS_REFERENCED 1217 #define ER_CONNECT_TO_MASTER 1218 #define ER_QUERY_ON_MASTER 1219 #define ER_ERROR_WHEN_EXECUTING_COMMAND 1220 #define ER_WRONG_USAGE 1221 #define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222 #define ER_CANT_UPDATE_WITH_READLOCK 1223 #define ER_MIXING_NOT_ALLOWED 1224 #define ER_DUP_ARGUMENT 1225 #define ER_USER_LIMIT_REACHED 1226 #define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227 #define ER_LOCAL_VARIABLE 1228 #define ER_GLOBAL_VARIABLE 1229 #define ER_NO_DEFAULT 1230 #define ER_WRONG_VALUE_FOR_VAR 1231 #define ER_WRONG_TYPE_FOR_VAR 1232 #define ER_VAR_CANT_BE_READ 1233 #define ER_CANT_USE_OPTION_HERE 1234 #define ER_NOT_SUPPORTED_YET 1235 #define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236 #define ER_SLAVE_IGNORED_TABLE 1237 #define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238 #define ER_WRONG_FK_DEF 1239 #define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240 #define ER_OPERAND_COLUMNS 1241 #define ER_SUBQUERY_NO_1_ROW 1242 #define ER_UNKNOWN_STMT_HANDLER 1243 #define ER_CORRUPT_HELP_DB 1244 #define ER_CYCLIC_REFERENCE 1245 #define ER_AUTO_CONVERT 1246 #define ER_ILLEGAL_REFERENCE 1247 #define ER_DERIVED_MUST_HAVE_ALIAS 1248 #define ER_SELECT_REDUCED 1249 #define ER_TABLENAME_NOT_ALLOWED_HERE 1250 #define ER_NOT_SUPPORTED_AUTH_MODE 1251 #define ER_SPATIAL_CANT_HAVE_NULL 1252 #define ER_COLLATION_CHARSET_MISMATCH 1253 #define ER_SLAVE_WAS_RUNNING 1254 #define ER_SLAVE_WAS_NOT_RUNNING 1255 #define ER_TOO_BIG_FOR_UNCOMPRESS 1256 #define ER_ZLIB_Z_MEM_ERROR 1257 #define ER_ZLIB_Z_BUF_ERROR 1258 #define ER_ZLIB_Z_DATA_ERROR 1259 #define ER_CUT_VALUE_GROUP_CONCAT 1260 #define ER_WARN_TOO_FEW_RECORDS 1261 #define ER_WARN_TOO_MANY_RECORDS 1262 #define ER_WARN_NULL_TO_NOTNULL 1263 #define ER_WARN_DATA_OUT_OF_RANGE 1264 #define WARN_DATA_TRUNCATED 1265 #define ER_WARN_USING_OTHER_HANDLER 1266 #define ER_CANT_AGGREGATE_2COLLATIONS 1267 #define ER_DROP_USER 1268 #define ER_REVOKE_GRANTS 1269 #define ER_CANT_AGGREGATE_3COLLATIONS 1270 #define ER_CANT_AGGREGATE_NCOLLATIONS 1271 #define ER_VARIABLE_IS_NOT_STRUCT 1272 #define ER_UNKNOWN_COLLATION 1273 #define ER_SLAVE_IGNORED_SSL_PARAMS 1274 #define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275 #define ER_WARN_FIELD_RESOLVED 1276 #define ER_BAD_SLAVE_UNTIL_COND 1277 #define ER_MISSING_SKIP_SLAVE 1278 #define ER_UNTIL_COND_IGNORED 1279 #define ER_WRONG_NAME_FOR_INDEX 1280 #define ER_WRONG_NAME_FOR_CATALOG 1281 #define ER_WARN_QC_RESIZE 1282 #define ER_BAD_FT_COLUMN 1283 #define ER_UNKNOWN_KEY_CACHE 1284 #define ER_WARN_HOSTNAME_WONT_WORK 1285 #define ER_UNKNOWN_STORAGE_ENGINE 1286 #define ER_WARN_DEPRECATED_SYNTAX 1287 #define ER_NON_UPDATABLE_TABLE 1288 #define ER_FEATURE_DISABLED 1289 #define ER_OPTION_PREVENTS_STATEMENT 1290 #define ER_DUPLICATED_VALUE_IN_TYPE 1291 #define ER_TRUNCATED_WRONG_VALUE 1292 #define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293 #define ER_INVALID_ON_UPDATE 1294 #define ER_UNSUPPORTED_PS 1295 #define ER_GET_ERRMSG 1296 #define ER_GET_TEMPORARY_ERRMSG 1297 #define ER_UNKNOWN_TIME_ZONE 1298 #define ER_WARN_INVALID_TIMESTAMP 1299 #define ER_INVALID_CHARACTER_STRING 1300 #define ER_WARN_ALLOWED_PACKET_OVERFLOWED 1301 #define ER_CONFLICTING_DECLARATIONS 1302 #define ER_SP_NO_RECURSIVE_CREATE 1303 #define ER_SP_ALREADY_EXISTS 1304 #define ER_SP_DOES_NOT_EXIST 1305 #define ER_SP_DROP_FAILED 1306 #define ER_SP_STORE_FAILED 1307 #define ER_SP_LILABEL_MISMATCH 1308 #define ER_SP_LABEL_REDEFINE 1309 #define ER_SP_LABEL_MISMATCH 1310 #define ER_SP_UNINIT_VAR 1311 #define ER_SP_BADSELECT 1312 #define ER_SP_BADRETURN 1313 #define ER_SP_BADSTATEMENT 1314 #define ER_UPDATE_LOG_DEPRECATED_IGNORED 1315 #define ER_UPDATE_LOG_DEPRECATED_TRANSLATED 1316 #define ER_QUERY_INTERRUPTED 1317 #define ER_SP_WRONG_NO_OF_ARGS 1318 #define ER_SP_COND_MISMATCH 1319 #define ER_SP_NORETURN 1320 #define ER_SP_NORETURNEND 1321 #define ER_SP_BAD_CURSOR_QUERY 1322 #define ER_SP_BAD_CURSOR_SELECT 1323 #define ER_SP_CURSOR_MISMATCH 1324 #define ER_SP_CURSOR_ALREADY_OPEN 1325 #define ER_SP_CURSOR_NOT_OPEN 1326 #define ER_SP_UNDECLARED_VAR 1327 #define ER_SP_WRONG_NO_OF_FETCH_ARGS 1328 #define ER_SP_FETCH_NO_DATA 1329 #define ER_SP_DUP_PARAM 1330 #define ER_SP_DUP_VAR 1331 #define ER_SP_DUP_COND 1332 #define ER_SP_DUP_CURS 1333 #define ER_SP_CANT_ALTER 1334 #define ER_SP_SUBSELECT_NYI 1335 #define ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG 1336 #define ER_SP_VARCOND_AFTER_CURSHNDLR 1337 #define ER_SP_CURSOR_AFTER_HANDLER 1338 #define ER_SP_CASE_NOT_FOUND 1339 #define ER_FPARSER_TOO_BIG_FILE 1340 #define ER_FPARSER_BAD_HEADER 1341 #define ER_FPARSER_EOF_IN_COMMENT 1342 #define ER_FPARSER_ERROR_IN_PARAMETER 1343 #define ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER 1344 #define ER_VIEW_NO_EXPLAIN 1345 #define ER_FRM_UNKNOWN_TYPE 1346 #define ER_WRONG_OBJECT 1347 #define ER_NONUPDATEABLE_COLUMN 1348 #define ER_VIEW_SELECT_DERIVED 1349 #define ER_VIEW_SELECT_CLAUSE 1350 #define ER_VIEW_SELECT_VARIABLE 1351 #define ER_VIEW_SELECT_TMPTABLE 1352 #define ER_VIEW_WRONG_LIST 1353 #define ER_WARN_VIEW_MERGE 1354 #define ER_WARN_VIEW_WITHOUT_KEY 1355 #define ER_VIEW_INVALID 1356 #define ER_SP_NO_DROP_SP 1357 #define ER_SP_GOTO_IN_HNDLR 1358 #define ER_TRG_ALREADY_EXISTS 1359 #define ER_TRG_DOES_NOT_EXIST 1360 #define ER_TRG_ON_VIEW_OR_TEMP_TABLE 1361 #define ER_TRG_CANT_CHANGE_ROW 1362 #define ER_TRG_NO_SUCH_ROW_IN_TRG 1363 #define ER_NO_DEFAULT_FOR_FIELD 1364 #define ER_DIVISION_BY_ZERO 1365 #define ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366 #define ER_ILLEGAL_VALUE_FOR_TYPE 1367 #define ER_VIEW_NONUPD_CHECK 1368 #define ER_VIEW_CHECK_FAILED 1369 #define ER_PROCACCESS_DENIED_ERROR 1370 #define ER_RELAY_LOG_FAIL 1371 #define ER_PASSWD_LENGTH 1372 #define ER_UNKNOWN_TARGET_BINLOG 1373 #define ER_IO_ERR_LOG_INDEX_READ 1374 #define ER_BINLOG_PURGE_PROHIBITED 1375 #define ER_FSEEK_FAIL 1376 #define ER_BINLOG_PURGE_FATAL_ERR 1377 #define ER_LOG_IN_USE 1378 #define ER_LOG_PURGE_UNKNOWN_ERR 1379 #define ER_RELAY_LOG_INIT 1380 #define ER_NO_BINARY_LOGGING 1381 #define ER_RESERVED_SYNTAX 1382 #define ER_WSAS_FAILED 1383 #define ER_DIFF_GROUPS_PROC 1384 #define ER_NO_GROUP_FOR_PROC 1385 #define ER_ORDER_WITH_PROC 1386 #define ER_LOGGING_PROHIBIT_CHANGING_OF 1387 #define ER_NO_FILE_MAPPING 1388 #define ER_WRONG_MAGIC 1389 #define ER_PS_MANY_PARAM 1390 #define ER_KEY_PART_0 1391 #define ER_VIEW_CHECKSUM 1392 #define ER_VIEW_MULTIUPDATE 1393 #define ER_VIEW_NO_INSERT_FIELD_LIST 1394 #define ER_VIEW_DELETE_MERGE_VIEW 1395 #define ER_CANNOT_USER 1396 #define ER_XAER_NOTA 1397 #define ER_XAER_INVAL 1398 #define ER_XAER_RMFAIL 1399 #define ER_XAER_OUTSIDE 1400 #define ER_XAER_RMERR 1401 #define ER_XA_RBROLLBACK 1402 #define ER_NONEXISTING_PROC_GRANT 1403 #define ER_PROC_AUTO_GRANT_FAIL 1404 #define ER_PROC_AUTO_REVOKE_FAIL 1405 #define ER_DATA_TOO_LONG 1406 #define ER_SP_BAD_SQLSTATE 1407 #define ER_STARTUP 1408 #define ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR 1409 #define ER_CANT_CREATE_USER_WITH_GRANT 1410 #define ER_WRONG_VALUE_FOR_TYPE 1411 #define ER_TABLE_DEF_CHANGED 1412 #define ER_SP_DUP_HANDLER 1413 #define ER_SP_NOT_VAR_ARG 1414 #define ER_SP_NO_RETSET 1415 #define ER_CANT_CREATE_GEOMETRY_OBJECT 1416 #define ER_FAILED_ROUTINE_BREAK_BINLOG 1417 #define ER_BINLOG_UNSAFE_ROUTINE 1418 #define ER_BINLOG_CREATE_ROUTINE_NEED_SUPER 1419 #define ER_EXEC_STMT_WITH_OPEN_CURSOR 1420 #define ER_STMT_HAS_NO_OPEN_CURSOR 1421 #define ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG 1422 #define ER_NO_DEFAULT_FOR_VIEW_FIELD 1423 #define ER_SP_NO_RECURSION 1424 #define ER_TOO_BIG_SCALE 1425 #define ER_TOO_BIG_PRECISION 1426 #define ER_M_BIGGER_THAN_D 1427 #define ER_WRONG_LOCK_OF_SYSTEM_TABLE 1428 #define ER_CONNECT_TO_FOREIGN_DATA_SOURCE 1429 #define ER_QUERY_ON_FOREIGN_DATA_SOURCE 1430 #define ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 1431 #define ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 1432 #define ER_FOREIGN_DATA_STRING_INVALID 1433 #define ER_CANT_CREATE_FEDERATED_TABLE 1434 #define ER_TRG_IN_WRONG_SCHEMA 1435 #define ER_STACK_OVERRUN_NEED_MORE 1436 #define ER_TOO_LONG_BODY 1437 #define ER_WARN_CANT_DROP_DEFAULT_KEYCACHE 1438 #define ER_TOO_BIG_DISPLAYWIDTH 1439 #define ER_XAER_DUPID 1440 #define ER_DATETIME_FUNCTION_OVERFLOW 1441 #define ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG 1442 #define ER_VIEW_PREVENT_UPDATE 1443 #define ER_PS_NO_RECURSION 1444 #define ER_SP_CANT_SET_AUTOCOMMIT 1445 #define ER_MALFORMED_DEFINER 1446 #define ER_VIEW_FRM_NO_USER 1447 #define ER_VIEW_OTHER_USER 1448 #define ER_NO_SUCH_USER 1449 #define ER_FORBID_SCHEMA_CHANGE 1450 #define ER_ROW_IS_REFERENCED_2 1451 #define ER_NO_REFERENCED_ROW_2 1452 #define ER_SP_BAD_VAR_SHADOW 1453 #define ER_TRG_NO_DEFINER 1454 #define ER_OLD_FILE_FORMAT 1455 #define ER_SP_RECURSION_LIMIT 1456 #define ER_SP_PROC_TABLE_CORRUPT 1457 #define ER_SP_WRONG_NAME 1458 #define ER_TABLE_NEEDS_UPGRADE 1459 #define ER_SP_NO_AGGREGATE 1460 #define ER_MAX_PREPARED_STMT_COUNT_REACHED 1461 #define ER_VIEW_RECURSIVE 1462 #define ER_NON_GROUPING_FIELD_USED 1463 #define ER_TABLE_CANT_HANDLE_SPKEYS 1464 #define ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA 1465 #define ER_REMOVED_SPACES 1466 #define ER_AUTOINC_READ_FAILED 1467 #define ER_USERNAME 1468 #define ER_HOSTNAME 1469 #define ER_WRONG_STRING_LENGTH 1470 #define ER_NON_INSERTABLE_TABLE 1471 #define ER_ADMIN_WRONG_MRG_TABLE 1472 #define ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT 1473 #define ER_NAME_BECOMES_EMPTY 1474 #define ER_AMBIGUOUS_FIELD_TERM 1475 #define ER_FOREIGN_SERVER_EXISTS 1476 #define ER_FOREIGN_SERVER_DOESNT_EXIST 1477 #define ER_ILLEGAL_HA_CREATE_OPTION 1478 #define ER_PARTITION_REQUIRES_VALUES_ERROR 1479 #define ER_PARTITION_WRONG_VALUES_ERROR 1480 #define ER_PARTITION_MAXVALUE_ERROR 1481 #define ER_PARTITION_SUBPARTITION_ERROR 1482 #define ER_PARTITION_SUBPART_MIX_ERROR 1483 #define ER_PARTITION_WRONG_NO_PART_ERROR 1484 #define ER_PARTITION_WRONG_NO_SUBPART_ERROR 1485 #define ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR 1486 #define ER_NOT_CONSTANT_EXPRESSION 1487 #define ER_FIELD_NOT_FOUND_PART_ERROR 1488 #define ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR 1489 #define ER_INCONSISTENT_PARTITION_INFO_ERROR 1490 #define ER_PARTITION_FUNC_NOT_ALLOWED_ERROR 1491 #define ER_PARTITIONS_MUST_BE_DEFINED_ERROR 1492 #define ER_RANGE_NOT_INCREASING_ERROR 1493 #define ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR 1494 #define ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR 1495 #define ER_PARTITION_ENTRY_ERROR 1496 #define ER_MIX_HANDLER_ERROR 1497 #define ER_PARTITION_NOT_DEFINED_ERROR 1498 #define ER_TOO_MANY_PARTITIONS_ERROR 1499 #define ER_SUBPARTITION_ERROR 1500 #define ER_CANT_CREATE_HANDLER_FILE 1501 #define ER_BLOB_FIELD_IN_PART_FUNC_ERROR 1502 #define ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF 1503 #define ER_NO_PARTS_ERROR 1504 #define ER_PARTITION_MGMT_ON_NONPARTITIONED 1505 #define ER_FEATURE_NOT_SUPPORTED_WITH_PARTITIONING 1506 #define ER_DROP_PARTITION_NON_EXISTENT 1507 #define ER_DROP_LAST_PARTITION 1508 #define ER_COALESCE_ONLY_ON_HASH_PARTITION 1509 #define ER_REORG_HASH_ONLY_ON_SAME_NO 1510 #define ER_REORG_NO_PARAM_ERROR 1511 #define ER_ONLY_ON_RANGE_LIST_PARTITION 1512 #define ER_ADD_PARTITION_SUBPART_ERROR 1513 #define ER_ADD_PARTITION_NO_NEW_PARTITION 1514 #define ER_COALESCE_PARTITION_NO_PARTITION 1515 #define ER_REORG_PARTITION_NOT_EXIST 1516 #define ER_SAME_NAME_PARTITION 1517 #define ER_NO_BINLOG_ERROR 1518 #define ER_CONSECUTIVE_REORG_PARTITIONS 1519 #define ER_REORG_OUTSIDE_RANGE 1520 #define ER_PARTITION_FUNCTION_FAILURE 1521 #define ER_PART_STATE_ERROR 1522 #define ER_LIMITED_PART_RANGE 1523 #define ER_PLUGIN_IS_NOT_LOADED 1524 #define ER_WRONG_VALUE 1525 #define ER_NO_PARTITION_FOR_GIVEN_VALUE 1526 #define ER_FILEGROUP_OPTION_ONLY_ONCE 1527 #define ER_CREATE_FILEGROUP_FAILED 1528 #define ER_DROP_FILEGROUP_FAILED 1529 #define ER_TABLESPACE_AUTO_EXTEND_ERROR 1530 #define ER_WRONG_SIZE_NUMBER 1531 #define ER_SIZE_OVERFLOW_ERROR 1532 #define ER_ALTER_FILEGROUP_FAILED 1533 #define ER_BINLOG_ROW_LOGGING_FAILED 1534 #define ER_BINLOG_ROW_WRONG_TABLE_DEF 1535 #define ER_BINLOG_ROW_RBR_TO_SBR 1536 #define ER_EVENT_ALREADY_EXISTS 1537 #define ER_EVENT_STORE_FAILED 1538 #define ER_EVENT_DOES_NOT_EXIST 1539 #define ER_EVENT_CANT_ALTER 1540 #define ER_EVENT_DROP_FAILED 1541 #define ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG 1542 #define ER_EVENT_ENDS_BEFORE_STARTS 1543 #define ER_EVENT_EXEC_TIME_IN_THE_PAST 1544 #define ER_EVENT_OPEN_TABLE_FAILED 1545 #define ER_EVENT_NEITHER_M_EXPR_NOR_M_AT 1546 #define ER_UNUSED_2 1547 #define ER_UNUSED_3 1548 #define ER_EVENT_CANNOT_DELETE 1549 #define ER_EVENT_COMPILE_ERROR 1550 #define ER_EVENT_SAME_NAME 1551 #define ER_EVENT_DATA_TOO_LONG 1552 #define ER_DROP_INDEX_FK 1553 #define ER_WARN_DEPRECATED_SYNTAX_WITH_VER 1554 #define ER_CANT_WRITE_LOCK_LOG_TABLE 1555 #define ER_CANT_LOCK_LOG_TABLE 1556 #define ER_UNUSED_4 1557 #define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE 1558 #define ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR 1559 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT 1560 #define ER_UNUSED_13 1561 #define ER_PARTITION_NO_TEMPORARY 1562 #define ER_PARTITION_CONST_DOMAIN_ERROR 1563 #define ER_PARTITION_FUNCTION_IS_NOT_ALLOWED 1564 #define ER_DDL_LOG_ERROR 1565 #define ER_NULL_IN_VALUES_LESS_THAN 1566 #define ER_WRONG_PARTITION_NAME 1567 #define ER_CANT_CHANGE_TX_CHARACTERISTICS 1568 #define ER_DUP_ENTRY_AUTOINCREMENT_CASE 1569 #define ER_EVENT_MODIFY_QUEUE_ERROR 1570 #define ER_EVENT_SET_VAR_ERROR 1571 #define ER_PARTITION_MERGE_ERROR 1572 #define ER_CANT_ACTIVATE_LOG 1573 #define ER_RBR_NOT_AVAILABLE 1574 #define ER_BASE64_DECODE_ERROR 1575 #define ER_EVENT_RECURSION_FORBIDDEN 1576 #define ER_EVENTS_DB_ERROR 1577 #define ER_ONLY_INTEGERS_ALLOWED 1578 #define ER_UNSUPORTED_LOG_ENGINE 1579 #define ER_BAD_LOG_STATEMENT 1580 #define ER_CANT_RENAME_LOG_TABLE 1581 #define ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT 1582 #define ER_WRONG_PARAMETERS_TO_NATIVE_FCT 1583 #define ER_WRONG_PARAMETERS_TO_STORED_FCT 1584 #define ER_NATIVE_FCT_NAME_COLLISION 1585 #define ER_DUP_ENTRY_WITH_KEY_NAME 1586 #define ER_BINLOG_PURGE_EMFILE 1587 #define ER_EVENT_CANNOT_CREATE_IN_THE_PAST 1588 #define ER_EVENT_CANNOT_ALTER_IN_THE_PAST 1589 #define ER_SLAVE_INCIDENT 1590 #define ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT 1591 #define ER_BINLOG_UNSAFE_STATEMENT 1592 #define ER_SLAVE_FATAL_ERROR 1593 #define ER_SLAVE_RELAY_LOG_READ_FAILURE 1594 #define ER_SLAVE_RELAY_LOG_WRITE_FAILURE 1595 #define ER_SLAVE_CREATE_EVENT_FAILURE 1596 #define ER_SLAVE_MASTER_COM_FAILURE 1597 #define ER_BINLOG_LOGGING_IMPOSSIBLE 1598 #define ER_VIEW_NO_CREATION_CTX 1599 #define ER_VIEW_INVALID_CREATION_CTX 1600 #define ER_SR_INVALID_CREATION_CTX 1601 #define ER_TRG_CORRUPTED_FILE 1602 #define ER_TRG_NO_CREATION_CTX 1603 #define ER_TRG_INVALID_CREATION_CTX 1604 #define ER_EVENT_INVALID_CREATION_CTX 1605 #define ER_TRG_CANT_OPEN_TABLE 1606 #define ER_CANT_CREATE_SROUTINE 1607 #define ER_UNUSED_11 1608 #define ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT 1609 #define ER_SLAVE_CORRUPT_EVENT 1610 #define ER_LOAD_DATA_INVALID_COLUMN 1611 #define ER_LOG_PURGE_NO_FILE 1612 #define ER_XA_RBTIMEOUT 1613 #define ER_XA_RBDEADLOCK 1614 #define ER_NEED_REPREPARE 1615 #define ER_DELAYED_NOT_SUPPORTED 1616 #define WARN_NO_MASTER_INFO 1617 #define WARN_OPTION_IGNORED 1618 #define ER_PLUGIN_DELETE_BUILTIN 1619 #define WARN_PLUGIN_BUSY 1620 #define ER_VARIABLE_IS_READONLY 1621 #define ER_WARN_ENGINE_TRANSACTION_ROLLBACK 1622 #define ER_SLAVE_HEARTBEAT_FAILURE 1623 #define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE 1624 #define ER_UNUSED_14 1625 #define ER_CONFLICT_FN_PARSE_ERROR 1626 #define ER_EXCEPTIONS_WRITE_ERROR 1627 #define ER_TOO_LONG_TABLE_COMMENT 1628 #define ER_TOO_LONG_FIELD_COMMENT 1629 #define ER_FUNC_INEXISTENT_NAME_COLLISION 1630 #define ER_DATABASE_NAME 1631 #define ER_TABLE_NAME 1632 #define ER_PARTITION_NAME 1633 #define ER_SUBPARTITION_NAME 1634 #define ER_TEMPORARY_NAME 1635 #define ER_RENAMED_NAME 1636 #define ER_TOO_MANY_CONCURRENT_TRXS 1637 #define WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED 1638 #define ER_DEBUG_SYNC_TIMEOUT 1639 #define ER_DEBUG_SYNC_HIT_LIMIT 1640 #define ER_DUP_SIGNAL_SET 1641 #define ER_SIGNAL_WARN 1642 #define ER_SIGNAL_NOT_FOUND 1643 #define ER_SIGNAL_EXCEPTION 1644 #define ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER 1645 #define ER_SIGNAL_BAD_CONDITION_TYPE 1646 #define WARN_COND_ITEM_TRUNCATED 1647 #define ER_COND_ITEM_TOO_LONG 1648 #define ER_UNKNOWN_LOCALE 1649 #define ER_SLAVE_IGNORE_SERVER_IDS 1650 #define ER_QUERY_CACHE_DISABLED 1651 #define ER_SAME_NAME_PARTITION_FIELD 1652 #define ER_PARTITION_COLUMN_LIST_ERROR 1653 #define ER_WRONG_TYPE_COLUMN_VALUE_ERROR 1654 #define ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR 1655 #define ER_MAXVALUE_IN_VALUES_IN 1656 #define ER_TOO_MANY_VALUES_ERROR 1657 #define ER_ROW_SINGLE_PARTITION_FIELD_ERROR 1658 #define ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD 1659 #define ER_PARTITION_FIELDS_TOO_LONG 1660 #define ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE 1661 #define ER_BINLOG_ROW_MODE_AND_STMT_ENGINE 1662 #define ER_BINLOG_UNSAFE_AND_STMT_ENGINE 1663 #define ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE 1664 #define ER_BINLOG_STMT_MODE_AND_ROW_ENGINE 1665 #define ER_BINLOG_ROW_INJECTION_AND_STMT_MODE 1666 #define ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1667 #define ER_BINLOG_UNSAFE_LIMIT 1668 #define ER_BINLOG_UNSAFE_INSERT_DELAYED 1669 #define ER_BINLOG_UNSAFE_SYSTEM_TABLE 1670 #define ER_BINLOG_UNSAFE_AUTOINC_COLUMNS 1671 #define ER_BINLOG_UNSAFE_UDF 1672 #define ER_BINLOG_UNSAFE_SYSTEM_VARIABLE 1673 #define ER_BINLOG_UNSAFE_SYSTEM_FUNCTION 1674 #define ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS 1675 #define ER_MESSAGE_AND_STATEMENT 1676 #define ER_SLAVE_CONVERSION_FAILED 1677 #define ER_SLAVE_CANT_CREATE_CONVERSION 1678 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT 1679 #define ER_PATH_LENGTH 1680 #define ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT 1681 #define ER_WRONG_NATIVE_TABLE_STRUCTURE 1682 #define ER_WRONG_PERFSCHEMA_USAGE 1683 #define ER_WARN_I_S_SKIPPED_TABLE 1684 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT 1685 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT 1686 #define ER_SPATIAL_MUST_HAVE_GEOM_COL 1687 #define ER_TOO_LONG_INDEX_COMMENT 1688 #define ER_LOCK_ABORTED 1689 #define ER_DATA_OUT_OF_RANGE 1690 #define ER_WRONG_SPVAR_TYPE_IN_LIMIT 1691 #define ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1692 #define ER_BINLOG_UNSAFE_MIXED_STATEMENT 1693 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN 1694 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN 1695 #define ER_FAILED_READ_FROM_PAR_FILE 1696 #define ER_VALUES_IS_NOT_INT_TYPE_ERROR 1697 #define ER_ACCESS_DENIED_NO_PASSWORD_ERROR 1698 #define ER_SET_PASSWORD_AUTH_PLUGIN 1699 #define ER_GRANT_PLUGIN_USER_EXISTS 1700 #define ER_TRUNCATE_ILLEGAL_FK 1701 #define ER_PLUGIN_IS_PERMANENT 1702 #define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN 1703 #define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX 1704 #define ER_STMT_CACHE_FULL 1705 #define ER_MULTI_UPDATE_KEY_CONFLICT 1706 #define ER_TABLE_NEEDS_REBUILD 1707 #define WARN_OPTION_BELOW_LIMIT 1708 #define ER_INDEX_COLUMN_TOO_LONG 1709 #define ER_ERROR_IN_TRIGGER_BODY 1710 #define ER_ERROR_IN_UNKNOWN_TRIGGER_BODY 1711 #define ER_INDEX_CORRUPT 1712 #define ER_UNDO_RECORD_TOO_BIG 1713 #define ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT 1714 #define ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE 1715 #define ER_BINLOG_UNSAFE_REPLACE_SELECT 1716 #define ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT 1717 #define ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT 1718 #define ER_BINLOG_UNSAFE_UPDATE_IGNORE 1719 #define ER_UNUSED_15 1720 #define ER_UNUSED_16 1721 #define ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT 1722 #define ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC 1723 #define ER_BINLOG_UNSAFE_INSERT_TWO_KEYS 1724 #define ER_UNUSED_28 1725 #define ER_VERS_NOT_ALLOWED 1726 #define ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST 1727 #define ER_CANNOT_LOAD_FROM_TABLE_V2 1728 #define ER_MASTER_DELAY_VALUE_OUT_OF_RANGE 1729 #define ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT 1730 #define ER_PARTITION_EXCHANGE_DIFFERENT_OPTION 1731 #define ER_PARTITION_EXCHANGE_PART_TABLE 1732 #define ER_PARTITION_EXCHANGE_TEMP_TABLE 1733 #define ER_PARTITION_INSTEAD_OF_SUBPARTITION 1734 #define ER_UNKNOWN_PARTITION 1735 #define ER_TABLES_DIFFERENT_METADATA 1736 #define ER_ROW_DOES_NOT_MATCH_PARTITION 1737 #define ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX 1738 #define ER_WARN_INDEX_NOT_APPLICABLE 1739 #define ER_PARTITION_EXCHANGE_FOREIGN_KEY 1740 #define ER_NO_SUCH_KEY_VALUE 1741 #define ER_VALUE_TOO_LONG 1742 #define ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE 1743 #define ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE 1744 #define ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX 1745 #define ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT 1746 #define ER_PARTITION_CLAUSE_ON_NONPARTITIONED 1747 #define ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET 1748 #define ER_UNUSED_5 1749 #define ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE 1750 #define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE 1751 #define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE 1752 #define ER_MTS_FEATURE_IS_NOT_SUPPORTED 1753 #define ER_MTS_UPDATED_DBS_GREATER_MAX 1754 #define ER_MTS_CANT_PARALLEL 1755 #define ER_MTS_INCONSISTENT_DATA 1756 #define ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING 1757 #define ER_DA_INVALID_CONDITION_NUMBER 1758 #define ER_INSECURE_PLAIN_TEXT 1759 #define ER_INSECURE_CHANGE_MASTER 1760 #define ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO 1761 #define ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO 1762 #define ER_SQLTHREAD_WITH_SECURE_SLAVE 1763 #define ER_TABLE_HAS_NO_FT 1764 #define ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER 1765 #define ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION 1766 #define ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST 1767 #define ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL 1768 #define ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION 1769 #define ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL 1770 #define ER_SKIPPING_LOGGED_TRANSACTION 1771 #define ER_MALFORMED_GTID_SET_SPECIFICATION 1772 #define ER_MALFORMED_GTID_SET_ENCODING 1773 #define ER_MALFORMED_GTID_SPECIFICATION 1774 #define ER_GNO_EXHAUSTED 1775 #define ER_BAD_SLAVE_AUTO_POSITION 1776 #define ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON 1777 #define ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET 1778 #define ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON 1779 #define ER_GTID_MODE_REQUIRES_BINLOG 1780 #define ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF 1781 #define ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON 1782 #define ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF 1783 #define ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF 1784 #define ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE 1785 #define ER_GTID_UNSAFE_CREATE_SELECT 1786 #define ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION 1787 #define ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME 1788 #define ER_MASTER_HAS_PURGED_REQUIRED_GTIDS 1789 #define ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID 1790 #define ER_UNKNOWN_EXPLAIN_FORMAT 1791 #define ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION 1792 #define ER_TOO_LONG_TABLE_PARTITION_COMMENT 1793 #define ER_SLAVE_CONFIGURATION 1794 #define ER_INNODB_FT_LIMIT 1795 #define ER_INNODB_NO_FT_TEMP_TABLE 1796 #define ER_INNODB_FT_WRONG_DOCID_COLUMN 1797 #define ER_INNODB_FT_WRONG_DOCID_INDEX 1798 #define ER_INNODB_ONLINE_LOG_TOO_BIG 1799 #define ER_UNKNOWN_ALTER_ALGORITHM 1800 #define ER_UNKNOWN_ALTER_LOCK 1801 #define ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS 1802 #define ER_MTS_RECOVERY_FAILURE 1803 #define ER_MTS_RESET_WORKERS 1804 #define ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 1805 #define ER_SLAVE_SILENT_RETRY_TRANSACTION 1806 #define ER_UNUSED_22 1807 #define ER_TABLE_SCHEMA_MISMATCH 1808 #define ER_TABLE_IN_SYSTEM_TABLESPACE 1809 #define ER_IO_READ_ERROR 1810 #define ER_IO_WRITE_ERROR 1811 #define ER_TABLESPACE_MISSING 1812 #define ER_TABLESPACE_EXISTS 1813 #define ER_TABLESPACE_DISCARDED 1814 #define ER_INTERNAL_ERROR 1815 #define ER_INNODB_IMPORT_ERROR 1816 #define ER_INNODB_INDEX_CORRUPT 1817 #define ER_INVALID_YEAR_COLUMN_LENGTH 1818 #define ER_NOT_VALID_PASSWORD 1819 #define ER_MUST_CHANGE_PASSWORD 1820 #define ER_FK_NO_INDEX_CHILD 1821 #define ER_FK_NO_INDEX_PARENT 1822 #define ER_FK_FAIL_ADD_SYSTEM 1823 #define ER_FK_CANNOT_OPEN_PARENT 1824 #define ER_FK_INCORRECT_OPTION 1825 #define ER_DUP_CONSTRAINT_NAME 1826 #define ER_PASSWORD_FORMAT 1827 #define ER_FK_COLUMN_CANNOT_DROP 1828 #define ER_FK_COLUMN_CANNOT_DROP_CHILD 1829 #define ER_FK_COLUMN_NOT_NULL 1830 #define ER_DUP_INDEX 1831 #define ER_FK_COLUMN_CANNOT_CHANGE 1832 #define ER_FK_COLUMN_CANNOT_CHANGE_CHILD 1833 #define ER_FK_CANNOT_DELETE_PARENT 1834 #define ER_MALFORMED_PACKET 1835 #define ER_READ_ONLY_MODE 1836 #define ER_GTID_NEXT_TYPE_UNDEFINED_GROUP 1837 #define ER_VARIABLE_NOT_SETTABLE_IN_SP 1838 #define ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF 1839 #define ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY 1840 #define ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY 1841 #define ER_GTID_PURGED_WAS_CHANGED 1842 #define ER_GTID_EXECUTED_WAS_CHANGED 1843 #define ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES 1844 #define ER_ALTER_OPERATION_NOT_SUPPORTED 1845 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON 1846 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY 1847 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION 1848 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME 1849 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE 1850 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK 1851 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE 1852 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK 1853 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC 1854 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS 1855 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS 1856 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS 1857 #define ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE 1858 #define ER_DUP_UNKNOWN_IN_INDEX 1859 #define ER_IDENT_CAUSES_TOO_LONG_PATH 1860 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL 1861 #define ER_MUST_CHANGE_PASSWORD_LOGIN 1862 #define ER_ROW_IN_WRONG_PARTITION 1863 #define ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX 1864 #define ER_INNODB_NO_FT_USES_PARSER 1865 #define ER_BINLOG_LOGICAL_CORRUPTION 1866 #define ER_WARN_PURGE_LOG_IN_USE 1867 #define ER_WARN_PURGE_LOG_IS_ACTIVE 1868 #define ER_AUTO_INCREMENT_CONFLICT 1869 #define WARN_ON_BLOCKHOLE_IN_RBR 1870 #define ER_SLAVE_MI_INIT_REPOSITORY 1871 #define ER_SLAVE_RLI_INIT_REPOSITORY 1872 #define ER_ACCESS_DENIED_CHANGE_USER_ERROR 1873 #define ER_INNODB_READ_ONLY 1874 #define ER_STOP_SLAVE_SQL_THREAD_TIMEOUT 1875 #define ER_STOP_SLAVE_IO_THREAD_TIMEOUT 1876 #define ER_TABLE_CORRUPT 1877 #define ER_TEMP_FILE_WRITE_FAILURE 1878 #define ER_INNODB_FT_AUX_NOT_HEX_ID 1879 #define ER_LAST_MYSQL_ERROR_MESSAGE 1880 #define ER_ERROR_LAST_SECTION_1 1880 /* New section */ #define ER_ERROR_FIRST_SECTION_2 1900 #define ER_UNUSED_18 1900 #define ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED 1901 #define ER_UNUSED_19 1902 #define ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN 1903 #define ER_KEY_BASED_ON_GENERATED_VIRTUAL_COLUMN 1904 #define ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN 1905 #define ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN 1906 #define ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN 1907 #define ER_UNUSED_20 1908 #define ER_UNUSED_21 1909 #define ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS 1910 #define ER_UNKNOWN_OPTION 1911 #define ER_BAD_OPTION_VALUE 1912 #define ER_UNUSED_6 1913 #define ER_UNUSED_7 1914 #define ER_UNUSED_8 1915 #define ER_DATA_OVERFLOW 1916 #define ER_DATA_TRUNCATED 1917 #define ER_BAD_DATA 1918 #define ER_DYN_COL_WRONG_FORMAT 1919 #define ER_DYN_COL_IMPLEMENTATION_LIMIT 1920 #define ER_DYN_COL_DATA 1921 #define ER_DYN_COL_WRONG_CHARSET 1922 #define ER_ILLEGAL_SUBQUERY_OPTIMIZER_SWITCHES 1923 #define ER_QUERY_CACHE_IS_DISABLED 1924 #define ER_QUERY_CACHE_IS_GLOBALY_DISABLED 1925 #define ER_VIEW_ORDERBY_IGNORED 1926 #define ER_CONNECTION_KILLED 1927 #define ER_UNUSED_12 1928 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SKIP_REPLICATION 1929 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_SKIP_REPLICATION 1930 #define ER_QUERY_RESULT_INCOMPLETE 1931 #define ER_NO_SUCH_TABLE_IN_ENGINE 1932 #define ER_TARGET_NOT_EXPLAINABLE 1933 #define ER_CONNECTION_ALREADY_EXISTS 1934 #define ER_MASTER_LOG_PREFIX 1935 #define ER_CANT_START_STOP_SLAVE 1936 #define ER_SLAVE_STARTED 1937 #define ER_SLAVE_STOPPED 1938 #define ER_SQL_DISCOVER_ERROR 1939 #define ER_FAILED_GTID_STATE_INIT 1940 #define ER_INCORRECT_GTID_STATE 1941 #define ER_CANNOT_UPDATE_GTID_STATE 1942 #define ER_DUPLICATE_GTID_DOMAIN 1943 #define ER_GTID_OPEN_TABLE_FAILED 1944 #define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG 1945 #define ER_CANNOT_LOAD_SLAVE_GTID_STATE 1946 #define ER_MASTER_GTID_POS_CONFLICTS_WITH_BINLOG 1947 #define ER_MASTER_GTID_POS_MISSING_DOMAIN 1948 #define ER_UNTIL_REQUIRES_USING_GTID 1949 #define ER_GTID_STRICT_OUT_OF_ORDER 1950 #define ER_GTID_START_FROM_BINLOG_HOLE 1951 #define ER_SLAVE_UNEXPECTED_MASTER_SWITCH 1952 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1953 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1954 #define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG2 1955 #define ER_BINLOG_MUST_BE_EMPTY 1956 #define ER_NO_SUCH_QUERY 1957 #define ER_BAD_BASE64_DATA 1958 #define ER_INVALID_ROLE 1959 #define ER_INVALID_CURRENT_USER 1960 #define ER_CANNOT_GRANT_ROLE 1961 #define ER_CANNOT_REVOKE_ROLE 1962 #define ER_CHANGE_SLAVE_PARALLEL_THREADS_ACTIVE 1963 #define ER_PRIOR_COMMIT_FAILED 1964 #define ER_IT_IS_A_VIEW 1965 #define ER_SLAVE_SKIP_NOT_IN_GTID 1966 #define ER_TABLE_DEFINITION_TOO_BIG 1967 #define ER_PLUGIN_INSTALLED 1968 #define ER_STATEMENT_TIMEOUT 1969 #define ER_SUBQUERIES_NOT_SUPPORTED 1970 #define ER_SET_STATEMENT_NOT_SUPPORTED 1971 #define ER_UNUSED_9 1972 #define ER_USER_CREATE_EXISTS 1973 #define ER_USER_DROP_EXISTS 1974 #define ER_ROLE_CREATE_EXISTS 1975 #define ER_ROLE_DROP_EXISTS 1976 #define ER_CANNOT_CONVERT_CHARACTER 1977 #define ER_INVALID_DEFAULT_VALUE_FOR_FIELD 1978 #define ER_KILL_QUERY_DENIED_ERROR 1979 #define ER_NO_EIS_FOR_FIELD 1980 #define ER_WARN_AGGFUNC_DEPENDENCE 1981 #define WARN_INNODB_PARTITION_OPTION_IGNORED 1982 #define ER_ERROR_LAST_SECTION_2 1982 /* New section */ #define ER_ERROR_FIRST_SECTION_3 2000 #define ER_ERROR_LAST_SECTION_3 2000 /* New section */ #define ER_ERROR_FIRST_SECTION_4 3000 #define ER_FILE_CORRUPT 3000 #define ER_ERROR_ON_MASTER 3001 #define ER_INCONSISTENT_ERROR 3002 #define ER_STORAGE_ENGINE_NOT_LOADED 3003 #define ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER 3004 #define ER_WARN_LEGACY_SYNTAX_CONVERTED 3005 #define ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN 3006 #define ER_CANNOT_DISCARD_TEMPORARY_TABLE 3007 #define ER_FK_DEPTH_EXCEEDED 3008 #define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 3009 #define ER_WARN_TRIGGER_DOESNT_HAVE_CREATED 3010 #define ER_REFERENCED_TRG_DOES_NOT_EXIST_MYSQL 3011 #define ER_EXPLAIN_NOT_SUPPORTED 3012 #define ER_INVALID_FIELD_SIZE 3013 #define ER_MISSING_HA_CREATE_OPTION 3014 #define ER_ENGINE_OUT_OF_MEMORY 3015 #define ER_PASSWORD_EXPIRE_ANONYMOUS_USER 3016 #define ER_SLAVE_SQL_THREAD_MUST_STOP 3017 #define ER_NO_FT_MATERIALIZED_SUBQUERY 3018 #define ER_INNODB_UNDO_LOG_FULL 3019 #define ER_INVALID_ARGUMENT_FOR_LOGARITHM 3020 #define ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP 3021 #define ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO 3022 #define ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS 3023 #define ER_UNUSED_1 3024 #define ER_NON_RO_SELECT_DISABLE_TIMER 3025 #define ER_DUP_LIST_ENTRY 3026 #define ER_SQL_MODE_NO_EFFECT 3027 #define ER_AGGREGATE_ORDER_FOR_UNION 3028 #define ER_AGGREGATE_ORDER_NON_AGG_QUERY 3029 #define ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR 3030 #define ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER 3031 #define ER_SERVER_OFFLINE_MODE 3032 #define ER_GIS_DIFFERENT_SRIDS 3033 #define ER_GIS_UNSUPPORTED_ARGUMENT 3034 #define ER_GIS_UNKNOWN_ERROR 3035 #define ER_GIS_UNKNOWN_EXCEPTION 3036 #define ER_GIS_INVALID_DATA 3037 #define ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION 3038 #define ER_BOOST_GEOMETRY_CENTROID_EXCEPTION 3039 #define ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION 3040 #define ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION 3041 #define ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION 3042 #define ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION 3043 #define ER_STD_BAD_ALLOC_ERROR 3044 #define ER_STD_DOMAIN_ERROR 3045 #define ER_STD_LENGTH_ERROR 3046 #define ER_STD_INVALID_ARGUMENT 3047 #define ER_STD_OUT_OF_RANGE_ERROR 3048 #define ER_STD_OVERFLOW_ERROR 3049 #define ER_STD_RANGE_ERROR 3050 #define ER_STD_UNDERFLOW_ERROR 3051 #define ER_STD_LOGIC_ERROR 3052 #define ER_STD_RUNTIME_ERROR 3053 #define ER_STD_UNKNOWN_EXCEPTION 3054 #define ER_GIS_DATA_WRONG_ENDIANESS 3055 #define ER_CHANGE_MASTER_PASSWORD_LENGTH 3056 #define ER_USER_LOCK_WRONG_NAME 3057 #define ER_USER_LOCK_DEADLOCK 3058 #define ER_REPLACE_INACCESSIBLE_ROWS 3059 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS 3060 #define ER_ERROR_LAST_SECTION_4 3060 /* New section */ #define ER_ERROR_FIRST_SECTION_5 4000 #define ER_UNUSED_26 4000 #define ER_UNUSED_27 4001 #define ER_WITH_COL_WRONG_LIST 4002 #define ER_TOO_MANY_DEFINITIONS_IN_WITH_CLAUSE 4003 #define ER_DUP_QUERY_NAME 4004 #define ER_RECURSIVE_WITHOUT_ANCHORS 4005 #define ER_UNACCEPTABLE_MUTUAL_RECURSION 4006 #define ER_REF_TO_RECURSIVE_WITH_TABLE_IN_DERIVED 4007 #define ER_NOT_STANDARD_COMPLIANT_RECURSIVE 4008 #define ER_WRONG_WINDOW_SPEC_NAME 4009 #define ER_DUP_WINDOW_NAME 4010 #define ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC 4011 #define ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC 4012 #define ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC 4013 #define ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS 4014 #define ER_WRONG_PLACEMENT_OF_WINDOW_FUNCTION 4015 #define ER_WINDOW_FUNCTION_IN_WINDOW_SPEC 4016 #define ER_NOT_ALLOWED_WINDOW_FRAME 4017 #define ER_NO_ORDER_LIST_IN_WINDOW_SPEC 4018 #define ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY 4019 #define ER_WRONG_TYPE_FOR_ROWS_FRAME 4020 #define ER_WRONG_TYPE_FOR_RANGE_FRAME 4021 #define ER_FRAME_EXCLUSION_NOT_SUPPORTED 4022 #define ER_WINDOW_FUNCTION_DONT_HAVE_FRAME 4023 #define ER_INVALID_NTILE_ARGUMENT 4024 #define ER_CONSTRAINT_FAILED 4025 #define ER_EXPRESSION_IS_TOO_BIG 4026 #define ER_ERROR_EVALUATING_EXPRESSION 4027 #define ER_CALCULATING_DEFAULT_VALUE 4028 #define ER_EXPRESSION_REFERS_TO_UNINIT_FIELD 4029 #define ER_PARTITION_DEFAULT_ERROR 4030 #define ER_REFERENCED_TRG_DOES_NOT_EXIST 4031 #define ER_INVALID_DEFAULT_PARAM 4032 #define ER_BINLOG_NON_SUPPORTED_BULK 4033 #define ER_BINLOG_UNCOMPRESS_ERROR 4034 #define ER_JSON_BAD_CHR 4035 #define ER_JSON_NOT_JSON_CHR 4036 #define ER_JSON_EOS 4037 #define ER_JSON_SYNTAX 4038 #define ER_JSON_ESCAPING 4039 #define ER_JSON_DEPTH 4040 #define ER_JSON_PATH_EOS 4041 #define ER_JSON_PATH_SYNTAX 4042 #define ER_JSON_PATH_DEPTH 4043 #define ER_JSON_PATH_NO_WILDCARD 4044 #define ER_JSON_PATH_ARRAY 4045 #define ER_JSON_ONE_OR_ALL 4046 #define ER_UNSUPPORTED_COMPRESSED_TABLE 4047 #define ER_GEOJSON_INCORRECT 4048 #define ER_GEOJSON_TOO_FEW_POINTS 4049 #define ER_GEOJSON_NOT_CLOSED 4050 #define ER_JSON_PATH_EMPTY 4051 #define ER_SLAVE_SAME_ID 4052 #define ER_FLASHBACK_NOT_SUPPORTED 4053 #define ER_KEYS_OUT_OF_ORDER 4054 #define ER_OVERLAPPING_KEYS 4055 #define ER_REQUIRE_ROW_BINLOG_FORMAT 4056 #define ER_ISOLATION_MODE_NOT_SUPPORTED 4057 #define ER_ON_DUPLICATE_DISABLED 4058 #define ER_UPDATES_WITH_CONSISTENT_SNAPSHOT 4059 #define ER_ROLLBACK_ONLY 4060 #define ER_ROLLBACK_TO_SAVEPOINT 4061 #define ER_ISOLATION_LEVEL_WITH_CONSISTENT_SNAPSHOT 4062 #define ER_UNSUPPORTED_COLLATION 4063 #define ER_METADATA_INCONSISTENCY 4064 #define ER_CF_DIFFERENT 4065 #define ER_RDB_TTL_DURATION_FORMAT 4066 #define ER_RDB_STATUS_GENERAL 4067 #define ER_RDB_STATUS_MSG 4068 #define ER_RDB_TTL_UNSUPPORTED 4069 #define ER_RDB_TTL_COL_FORMAT 4070 #define ER_PER_INDEX_CF_DEPRECATED 4071 #define ER_KEY_CREATE_DURING_ALTER 4072 #define ER_SK_POPULATE_DURING_ALTER 4073 #define ER_SUM_FUNC_WITH_WINDOW_FUNC_AS_ARG 4074 #define ER_NET_OK_PACKET_TOO_LARGE 4075 #define ER_GEOJSON_EMPTY_COORDINATES 4076 #define ER_MYROCKS_CANT_NOPAD_COLLATION 4077 #define ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION 4078 #define ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION 4079 #define ER_WRONG_PARAMCOUNT_TO_CURSOR 4080 #define ER_UNKNOWN_STRUCTURED_VARIABLE 4081 #define ER_ROW_VARIABLE_DOES_NOT_HAVE_FIELD 4082 #define ER_END_IDENTIFIER_DOES_NOT_MATCH 4083 #define ER_SEQUENCE_RUN_OUT 4084 #define ER_SEQUENCE_INVALID_DATA 4085 #define ER_SEQUENCE_INVALID_TABLE_STRUCTURE 4086 #define ER_SEQUENCE_ACCESS_ERROR 4087 #define ER_SEQUENCE_BINLOG_FORMAT 4088 #define ER_NOT_SEQUENCE 4089 #define ER_NOT_SEQUENCE2 4090 #define ER_UNKNOWN_SEQUENCES 4091 #define ER_UNKNOWN_VIEW 4092 #define ER_WRONG_INSERT_INTO_SEQUENCE 4093 #define ER_SP_STACK_TRACE 4094 #define ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY 4095 #define ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED 4096 #define ER_COMPRESSED_COLUMN_USED_AS_KEY 4097 #define ER_UNKNOWN_COMPRESSION_METHOD 4098 #define ER_WRONG_NUMBER_OF_VALUES_IN_TVC 4099 #define ER_FIELD_REFERENCE_IN_TVC 4100 #define ER_WRONG_TYPE_FOR_PERCENTILE_FUNC 4101 #define ER_ARGUMENT_NOT_CONSTANT 4102 #define ER_ARGUMENT_OUT_OF_RANGE 4103 #define ER_WRONG_TYPE_OF_ARGUMENT 4104 #define ER_NOT_AGGREGATE_FUNCTION 4105 #define ER_INVALID_AGGREGATE_FUNCTION 4106 #define ER_INVALID_VALUE_TO_LIMIT 4107 #define ER_INVISIBLE_NOT_NULL_WITHOUT_DEFAULT 4108 #define ER_UPDATE_INFO_WITH_SYSTEM_VERSIONING 4109 #define ER_VERS_FIELD_WRONG_TYPE 4110 #define ER_VERS_ENGINE_UNSUPPORTED 4111 #define ER_UNUSED_23 4112 #define ER_PARTITION_WRONG_TYPE 4113 #define WARN_VERS_PART_FULL 4114 #define WARN_VERS_PARAMETERS 4115 #define ER_VERS_DROP_PARTITION_INTERVAL 4116 #define ER_UNUSED_25 4117 #define WARN_VERS_PART_NON_HISTORICAL 4118 #define ER_VERS_ALTER_NOT_ALLOWED 4119 #define ER_VERS_ALTER_ENGINE_PROHIBITED 4120 #define ER_VERS_RANGE_PROHIBITED 4121 #define ER_CONFLICTING_FOR_SYSTEM_TIME 4122 #define ER_VERS_TABLE_MUST_HAVE_COLUMNS 4123 #define ER_VERS_NOT_VERSIONED 4124 #define ER_MISSING 4125 #define ER_VERS_PERIOD_COLUMNS 4126 #define ER_PART_WRONG_VALUE 4127 #define ER_VERS_WRONG_PARTS 4128 #define ER_VERS_NO_TRX_ID 4129 #define ER_VERS_ALTER_SYSTEM_FIELD 4130 #define ER_DROP_VERSIONING_SYSTEM_TIME_PARTITION 4131 #define ER_VERS_DB_NOT_SUPPORTED 4132 #define ER_VERS_TRT_IS_DISABLED 4133 #define ER_VERS_DUPLICATE_ROW_START_END 4134 #define ER_VERS_ALREADY_VERSIONED 4135 #define ER_UNUSED_24 4136 #define ER_VERS_NOT_SUPPORTED 4137 #define ER_VERS_TRX_PART_HISTORIC_ROW_NOT_SUPPORTED 4138 #define ER_INDEX_FILE_FULL 4139 #define ER_UPDATED_COLUMN_ONLY_ONCE 4140 #define ER_EMPTY_ROW_IN_TVC 4141 #define ER_VERS_QUERY_IN_PARTITION 4142 #define ER_KEY_DOESNT_SUPPORT 4143 #define ER_ALTER_OPERATION_TABLE_OPTIONS_NEED_REBUILD 4144 #define ER_BACKUP_LOCK_IS_ACTIVE 4145 #define ER_BACKUP_NOT_RUNNING 4146 #define ER_BACKUP_WRONG_STAGE 4147 #define ER_BACKUP_STAGE_FAILED 4148 #define ER_BACKUP_UNKNOWN_STAGE 4149 #define ER_USER_IS_BLOCKED 4150 #define ER_ACCOUNT_HAS_BEEN_LOCKED 4151 #define ER_PERIOD_TEMPORARY_NOT_ALLOWED 4152 #define ER_PERIOD_TYPES_MISMATCH 4153 #define ER_MORE_THAN_ONE_PERIOD 4154 #define ER_PERIOD_FIELD_WRONG_ATTRIBUTES 4155 #define ER_PERIOD_NOT_FOUND 4156 #define ER_PERIOD_COLUMNS_UPDATED 4157 #define ER_PERIOD_CONSTRAINT_DROP 4158 #define ER_TOO_LONG_KEYPART 4159 #define ER_TOO_LONG_DATABASE_COMMENT 4160 #define ER_UNKNOWN_DATA_TYPE 4161 #define ER_UNKNOWN_OPERATOR 4162 #define ER_WARN_HISTORY_ROW_START_TIME 4163 #define ER_PART_STARTS_BEYOND_INTERVAL 4164 #define ER_GALERA_REPLICATION_NOT_SUPPORTED 4165 #define ER_LOAD_INFILE_CAPABILITY_DISABLED 4166 #define ER_NO_SECURE_TRANSPORTS_CONFIGURED 4167 #define ER_SLAVE_IGNORED_SHARED_TABLE 4168 #define ER_NO_AUTOINCREMENT_WITH_UNIQUE 4169 #define ER_KEY_CONTAINS_PERIOD_FIELDS 4170 #define ER_KEY_CANT_HAVE_WITHOUT_OVERLAPS 4171 #define ER_NOT_ALLOWED_IN_THIS_CONTEXT 4172 #define ER_DATA_WAS_COMMITED_UNDER_ROLLBACK 4173 #define ER_PK_INDEX_CANT_BE_IGNORED 4174 #define ER_BINLOG_UNSAFE_SKIP_LOCKED 4175 #define ER_JSON_TABLE_ERROR_ON_FIELD 4176 #define ER_JSON_TABLE_ALIAS_REQUIRED 4177 #define ER_JSON_TABLE_SCALAR_EXPECTED 4178 #define ER_JSON_TABLE_MULTIPLE_MATCHES 4179 #define ER_WITH_TIES_NEEDS_ORDER 4180 #define ER_REMOVED_ORPHAN_TRIGGER 4181 #define ER_STORAGE_ENGINE_DISABLED 4182 #define ER_ERROR_LAST 4182 #endif /* ER_ERROR_FIRST */ mysql/mariadb/ma_io.h000064400000003126151027430560010552 0ustar00/* Copyright (C) 2015 MariaDB Corporation AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ #ifndef _ma_io_h_ #define _ma_io_h_ #ifdef HAVE_REMOTEIO #include #endif enum enum_file_type { MA_FILE_NONE=0, MA_FILE_LOCAL=1, MA_FILE_REMOTE=2 }; typedef struct { enum enum_file_type type; void *ptr; } MA_FILE; #ifdef HAVE_REMOTEIO struct st_rio_methods { MA_FILE *(*mopen)(const char *url, const char *mode); int (*mclose)(MA_FILE *ptr); int (*mfeof)(MA_FILE *file); size_t (*mread)(void *ptr, size_t size, size_t nmemb, MA_FILE *file); char * (*mgets)(char *ptr, size_t size, MA_FILE *file); }; #endif /* function prototypes */ MA_FILE *ma_open(const char *location, const char *mode, MYSQL *mysql); int ma_close(MA_FILE *file); int ma_feof(MA_FILE *file); size_t ma_read(void *ptr, size_t size, size_t nmemb, MA_FILE *file); char *ma_gets(char *ptr, size_t size, MA_FILE *file); #endif mysql/ma_pvio.h000064400000010744151027430560007525 0ustar00#ifndef _ma_pvio_h_ #define _ma_pvio_h_ #define cio_defined #ifdef HAVE_TLS #include #else #define MARIADB_TLS void #endif /* CONC-492: Allow to build plugins outside of MariaDB Connector/C source tree when ma_global.h was not included. */ #if !defined(_global_h) && !defined(MY_GLOBAL_INCLUDED) typedef unsigned char uchar; #endif #define PVIO_SET_ERROR if (pvio->set_error) \ pvio->set_error #define PVIO_READ_AHEAD_CACHE_SIZE 16384 #define PVIO_READ_AHEAD_CACHE_MIN_SIZE 2048 #define PVIO_EINTR_TRIES 2 struct st_ma_pvio_methods; typedef struct st_ma_pvio_methods PVIO_METHODS; #define IS_PVIO_ASYNC(a) \ ((a)->mysql && (a)->mysql->options.extension && (a)->mysql->options.extension->async_context) #define IS_PVIO_ASYNC_ACTIVE(a) \ (IS_PVIO_ASYNC(a)&& (a)->mysql->options.extension->async_context->active) #define IS_MYSQL_ASYNC(a) \ ((a)->options.extension && (a)->options.extension->async_context) #define IS_MYSQL_ASYNC_ACTIVE(a) \ (IS_MYSQL_ASYNC(a)&& (a)->options.extension->async_context->active) enum enum_pvio_timeout { PVIO_CONNECT_TIMEOUT= 0, PVIO_READ_TIMEOUT, PVIO_WRITE_TIMEOUT }; enum enum_pvio_io_event { VIO_IO_EVENT_READ, VIO_IO_EVENT_WRITE, VIO_IO_EVENT_CONNECT }; enum enum_pvio_type { PVIO_TYPE_UNIXSOCKET= 0, PVIO_TYPE_SOCKET, PVIO_TYPE_NAMEDPIPE, PVIO_TYPE_SHAREDMEM, }; enum enum_pvio_operation { PVIO_READ= 0, PVIO_WRITE=1 }; #define SHM_DEFAULT_NAME "MYSQL" struct st_pvio_callback; typedef struct st_pvio_callback { void (*callback)(MYSQL *mysql, uchar *buffer, size_t size); struct st_pvio_callback *next; } PVIO_CALLBACK; struct st_ma_pvio { void *data; /* read ahead cache */ uchar *cache; uchar *cache_pos; size_t cache_size; enum enum_pvio_type type; int timeout[3]; int ssl_type; /* todo: change to enum (ssl plugins) */ MARIADB_TLS *ctls; MYSQL *mysql; PVIO_METHODS *methods; void (*set_error)(MYSQL *mysql, unsigned int error_nr, const char *sqlstate, const char *format, ...); void (*callback)(MARIADB_PVIO *pvio, my_bool is_read, const uchar *buffer, size_t length); size_t bytes_read; size_t bytes_sent; }; typedef struct st_ma_pvio_cinfo { const char *host; const char *unix_socket; int port; enum enum_pvio_type type; MYSQL *mysql; } MA_PVIO_CINFO; struct st_ma_pvio_methods { my_bool (*set_timeout)(MARIADB_PVIO *pvio, enum enum_pvio_timeout type, int timeout); int (*get_timeout)(MARIADB_PVIO *pvio, enum enum_pvio_timeout type); ssize_t (*read)(MARIADB_PVIO *pvio, uchar *buffer, size_t length); ssize_t (*async_read)(MARIADB_PVIO *pvio, uchar *buffer, size_t length); ssize_t (*write)(MARIADB_PVIO *pvio, const uchar *buffer, size_t length); ssize_t (*async_write)(MARIADB_PVIO *pvio, const uchar *buffer, size_t length); int (*wait_io_or_timeout)(MARIADB_PVIO *pvio, my_bool is_read, int timeout); int (*blocking)(MARIADB_PVIO *pvio, my_bool value, my_bool *old_value); my_bool (*connect)(MARIADB_PVIO *pvio, MA_PVIO_CINFO *cinfo); my_bool (*close)(MARIADB_PVIO *pvio); int (*fast_send)(MARIADB_PVIO *pvio); int (*keepalive)(MARIADB_PVIO *pvio); my_bool (*get_handle)(MARIADB_PVIO *pvio, void *handle); my_bool (*is_blocking)(MARIADB_PVIO *pvio); my_bool (*is_alive)(MARIADB_PVIO *pvio); my_bool (*has_data)(MARIADB_PVIO *pvio, ssize_t *data_len); int(*shutdown)(MARIADB_PVIO *pvio); }; /* Function prototypes */ MARIADB_PVIO *ma_pvio_init(MA_PVIO_CINFO *cinfo); void ma_pvio_close(MARIADB_PVIO *pvio); ssize_t ma_pvio_cache_read(MARIADB_PVIO *pvio, uchar *buffer, size_t length); ssize_t ma_pvio_read(MARIADB_PVIO *pvio, uchar *buffer, size_t length); ssize_t ma_pvio_write(MARIADB_PVIO *pvio, const uchar *buffer, size_t length); int ma_pvio_get_timeout(MARIADB_PVIO *pvio, enum enum_pvio_timeout type); my_bool ma_pvio_set_timeout(MARIADB_PVIO *pvio, enum enum_pvio_timeout type, int timeout); int ma_pvio_fast_send(MARIADB_PVIO *pvio); int ma_pvio_keepalive(MARIADB_PVIO *pvio); my_socket ma_pvio_get_socket(MARIADB_PVIO *pvio); my_bool ma_pvio_is_blocking(MARIADB_PVIO *pvio); my_bool ma_pvio_blocking(MARIADB_PVIO *pvio, my_bool block, my_bool *previous_mode); my_bool ma_pvio_is_blocking(MARIADB_PVIO *pvio); int ma_pvio_wait_io_or_timeout(MARIADB_PVIO *pvio, my_bool is_read, int timeout); my_bool ma_pvio_connect(MARIADB_PVIO *pvio, MA_PVIO_CINFO *cinfo); my_bool ma_pvio_is_alive(MARIADB_PVIO *pvio); my_bool ma_pvio_get_handle(MARIADB_PVIO *pvio, void *handle); my_bool ma_pvio_has_data(MARIADB_PVIO *pvio, ssize_t *length); #endif /* _ma_pvio_h_ */ mysql/ma_list.h000064400000003123151027430560007514 0ustar00/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ #ifndef _list_h_ #define _list_h_ #ifdef __cplusplus extern "C" { #endif typedef struct st_list { struct st_list *prev,*next; void *data; } LIST; typedef int (*list_walk_action)(void *,void *); extern LIST *list_add(LIST *root,LIST *element); extern LIST *list_delete(LIST *root,LIST *element); extern LIST *list_cons(void *data,LIST *root); extern LIST *list_reverse(LIST *root); extern void list_free(LIST *root,unsigned int free_data); extern unsigned int list_length(LIST *list); extern int list_walk(LIST *list,list_walk_action action,char * argument); #define list_rest(a) ((a)->next) #define list_push(a,b) (a)=list_cons((b),(a)) #define list_pop(A) do {LIST *old=(A); (A)=list_delete(old,old) ; ma_free((char *) old,MYF(MY_FAE)); } while(0) #ifdef __cplusplus } #endif #endif mysql/errmsg.h000064400000011461151027430560007367 0ustar00/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB 2012-2016 SkySQL AB, MariaDB Corporation AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ /* Error messages for mysql clients */ /* error messages for the demon is in share/language/errmsg.sys */ #ifndef _errmsg_h_ #define _errmsg_h_ #ifdef __cplusplus extern "C" { #endif void init_client_errs(void); extern const char *client_errors[]; /* Error messages */ extern const char *mariadb_client_errors[]; /* Error messages */ #ifdef __cplusplus } #endif #define CR_MIN_ERROR 2000 /* For easier client code */ #define CR_MAX_ERROR 2999 #define CER_MIN_ERROR 5000 #define CER_MAX_ERROR 5999 #define CLIENT_ERRMAP 2 /* Errormap used by ma_error() */ #define ER_UNKNOWN_ERROR_CODE "Unknown or undefined error code (%d)" #define CR_UNKNOWN_ERROR 2000 #define CR_SOCKET_CREATE_ERROR 2001 #define CR_CONNECTION_ERROR 2002 #define CR_CONN_HOST_ERROR 2003 /* never sent to a client, message only */ #define CR_IPSOCK_ERROR 2004 #define CR_UNKNOWN_HOST 2005 #define CR_SERVER_GONE_ERROR 2006 /* disappeared _between_ queries */ #define CR_VERSION_ERROR 2007 #define CR_OUT_OF_MEMORY 2008 #define CR_WRONG_HOST_INFO 2009 #define CR_LOCALHOST_CONNECTION 2010 #define CR_TCP_CONNECTION 2011 #define CR_SERVER_HANDSHAKE_ERR 2012 #define CR_SERVER_LOST 2013 /* disappeared _during_ a query */ #define CR_COMMANDS_OUT_OF_SYNC 2014 #define CR_NAMEDPIPE_CONNECTION 2015 #define CR_NAMEDPIPEWAIT_ERROR 2016 #define CR_NAMEDPIPEOPEN_ERROR 2017 #define CR_NAMEDPIPESETSTATE_ERROR 2018 #define CR_CANT_READ_CHARSET 2019 #define CR_NET_PACKET_TOO_LARGE 2020 #define CR_SSL_CONNECTION_ERROR 2026 #define CR_MALFORMED_PACKET 2027 #define CR_NO_PREPARE_STMT 2030 #define CR_PARAMS_NOT_BOUND 2031 #define CR_INVALID_PARAMETER_NO 2034 #define CR_INVALID_BUFFER_USE 2035 #define CR_UNSUPPORTED_PARAM_TYPE 2036 #define CR_SHARED_MEMORY_CONNECTION 2037 #define CR_SHARED_MEMORY_CONNECT_ERROR 2038 #define CR_CONN_UNKNOWN_PROTOCOL 2047 #define CR_SECURE_AUTH 2049 #define CR_NO_DATA 2051 #define CR_NO_STMT_METADATA 2052 #define CR_NOT_IMPLEMENTED 2054 #define CR_SERVER_LOST_EXTENDED 2055 /* never sent to a client, message only */ #define CR_STMT_CLOSED 2056 #define CR_NEW_STMT_METADATA 2057 #define CR_ALREADY_CONNECTED 2058 #define CR_AUTH_PLUGIN_CANNOT_LOAD 2059 #define CR_DUPLICATE_CONNECTION_ATTR 2060 #define CR_AUTH_PLUGIN_ERR 2061 /* Always last, if you add new error codes please update the value for CR_MYSQL_LAST_ERROR */ #define CR_MYSQL_LAST_ERROR CR_AUTH_PLUGIN_ERR /* * MariaDB Connector/C errors: */ #define CR_EVENT_CREATE_FAILED 5000 #define CR_BIND_ADDR_FAILED 5001 #define CR_ASYNC_NOT_SUPPORTED 5002 #define CR_FUNCTION_NOT_SUPPORTED 5003 #define CR_FILE_NOT_FOUND 5004 #define CR_FILE_READ 5005 #define CR_BULK_WITHOUT_PARAMETERS 5006 #define CR_INVALID_STMT 5007 #define CR_VERSION_MISMATCH 5008 #define CR_INVALID_PARAMETER 5009 #define CR_PLUGIN_NOT_ALLOWED 5010 #define CR_CONNSTR_PARSE_ERROR 5011 #define CR_ERR_LOAD_PLUGIN 5012 #define CR_ERR_NET_READ 5013 #define CR_ERR_NET_WRITE 5014 #define CR_ERR_NET_UNCOMPRESS 5015 #define CR_ERR_STMT_PARAM_CALLBACK 5016 #define CR_ERR_BINLOG_UNCOMPRESS 5017 #define CR_ERR_CHECKSUM_VERIFICATION_ERROR 5018 #define CR_ERR_UNSUPPORTED_BINLOG_FORMAT 5019 #define CR_UNKNOWN_BINLOG_EVENT 5020 #define CR_BINLOG_ERROR 5021 #define CR_BINLOG_INVALID_FILE 5022 #define CR_BINLOG_SEMI_SYNC_ERROR 5023 #define CR_INVALID_CLIENT_FLAG 5024 #define CR_ERR_MISSING_ERROR_INFO 5026 /* Always last, if you add new error codes please update the value for CR_MARIADB_LAST_ERROR */ #define CR_MARIADB_LAST_ERROR CR_ERR_MISSING_ERROR_INFO #endif #define IS_MYSQL_ERROR(code) ((code) > CR_MIN_ERROR && (code) <= CR_MYSQL_LAST_ERROR) #define IS_MARIADB_ERROR(code) ((code) > CER_MIN_ERROR && (code) <= CR_MARIADB_LAST_ERROR) #define ER(code) IS_MYSQL_ERROR((code)) ? client_errors[(code) - CR_MIN_ERROR] : \ IS_MARIADB_ERROR((code)) ? mariadb_client_errors[(code) - CER_MIN_ERROR] : \ "Unknown or undefined error code" #define CER(code) ER((code)) mysql/mysql/client_plugin.h000064400000021746151027430560012100 0ustar00/* Copyright (C) 2010 - 2012 Sergei Golubchik and Monty Program Ab 2014, 2022 MariaDB Corporation AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not see or write to the Free Software Foundation, Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110, USA */ /** @file MySQL Client Plugin API This file defines the API for plugins that work on the client side */ #ifndef MYSQL_CLIENT_PLUGIN_INCLUDED #define MYSQL_CLIENT_PLUGIN_INCLUDED #ifndef MYSQL_ABI_CHECK #include #include #endif #ifndef PLUGINDIR #define PLUGINDIR "lib/plugin" #endif #define plugin_declarations_sym "_mysql_client_plugin_declaration_" /* known plugin types */ #define MYSQL_CLIENT_PLUGIN_RESERVED 0 #define MYSQL_CLIENT_PLUGIN_RESERVED2 1 #define MYSQL_CLIENT_AUTHENTICATION_PLUGIN 2 /* authentication */ #define MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION 0x0100 #define MYSQL_CLIENT_MAX_PLUGINS 3 /* Connector/C specific plugin types */ #define MARIADB_CLIENT_REMOTEIO_PLUGIN 100 /* communication IO */ #define MARIADB_CLIENT_PVIO_PLUGIN 101 #define MARIADB_CLIENT_TRACE_PLUGIN 102 #define MARIADB_CLIENT_CONNECTION_PLUGIN 103 #define MARIADB_CLIENT_COMPRESSION_PLUGIN 104 #define MARIADB_CLIENT_REMOTEIO_PLUGIN_INTERFACE_VERSION 0x0100 #define MARIADB_CLIENT_PVIO_PLUGIN_INTERFACE_VERSION 0x0100 #define MARIADB_CLIENT_TRACE_PLUGIN_INTERFACE_VERSION 0x0100 #define MARIADB_CLIENT_CONNECTION_PLUGIN_INTERFACE_VERSION 0x0100 #define MARIADB_CLIENT_COMPRESSION_PLUGIN_INTERFACE_VERSION 0x0100 #define MARIADB_CLIENT_MAX_PLUGINS 5 #define mysql_declare_client_plugin(X) \ struct st_mysql_client_plugin_ ## X \ _mysql_client_plugin_declaration_ = { \ MYSQL_CLIENT_ ## X ## _PLUGIN, \ MYSQL_CLIENT_ ## X ## _PLUGIN_INTERFACE_VERSION, #define mysql_end_client_plugin } /* generic plugin header structure */ #ifndef MYSQL_CLIENT_PLUGIN_HEADER #define MYSQL_CLIENT_PLUGIN_HEADER \ int type; \ unsigned int interface_version; \ const char *name; \ const char *author; \ const char *desc; \ unsigned int version[3]; \ const char *license; \ void *mysql_api; \ int (*init)(char *, size_t, int, va_list); \ int (*deinit)(void); \ int (*options)(const char *option, const void *); struct st_mysql_client_plugin { MYSQL_CLIENT_PLUGIN_HEADER }; #endif struct st_mysql; /********* connection handler plugin specific declarations **********/ typedef struct st_ma_connection_plugin { MYSQL_CLIENT_PLUGIN_HEADER /* functions */ MYSQL *(*connect)(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); void (*close)(MYSQL *mysql); int (*set_optionsv)(MYSQL *mysql, unsigned int option, ...); int (*set_connection)(MYSQL *mysql,enum enum_server_command command, const char *arg, size_t length, my_bool skipp_check, void *opt_arg); my_bool (*reconnect)(MYSQL *mysql); int (*reset)(MYSQL *mysql); } MARIADB_CONNECTION_PLUGIN; #define MARIADB_DB_DRIVER(a) ((a)->ext_db) /******************* Communication IO plugin *****************/ #include typedef struct st_mariadb_client_plugin_PVIO { MYSQL_CLIENT_PLUGIN_HEADER struct st_ma_pvio_methods *methods; } MARIADB_PVIO_PLUGIN; /******** authentication plugin specific declarations *********/ #include struct st_mysql_client_plugin_AUTHENTICATION { MYSQL_CLIENT_PLUGIN_HEADER int (*authenticate_user)(MYSQL_PLUGIN_VIO *vio, struct st_mysql *mysql); }; /******** trace plugin *******/ struct st_mysql_client_plugin_TRACE { MYSQL_CLIENT_PLUGIN_HEADER }; #include typedef struct st_mariadb_client_plugin_COMPRESS { MYSQL_CLIENT_PLUGIN_HEADER ma_compress_ctx *(*init_ctx)(int compression_level); void (*free_ctx)(ma_compress_ctx *ctx); my_bool (*compress)(ma_compress_ctx *ctx, void *dst, size_t *dst_len, void *source, size_t source_len); my_bool (*decompress)(ma_compress_ctx *ctx, void *dst, size_t *dst_len, void *source, size_t *source_len); } MARIADB_COMPRESSION_PLUGIN; /** type of the mysql_authentication_dialog_ask function @param mysql mysql @param type type of the input 1 - ordinary string input 2 - password string @param prompt prompt @param buf a buffer to store the use input @param buf_len the length of the buffer @retval a pointer to the user input string. It may be equal to 'buf' or to 'mysql->password'. In all other cases it is assumed to be an allocated string, and the "dialog" plugin will free() it. */ typedef char *(*mysql_authentication_dialog_ask_t)(struct st_mysql *mysql, int type, const char *prompt, char *buf, int buf_len); /********************** remote IO plugin **********************/ #ifdef HAVE_REMOTEIO #include /* Remote IO plugin */ typedef struct st_mysql_client_plugin_REMOTEIO { MYSQL_CLIENT_PLUGIN_HEADER struct st_rio_methods *methods; } MARIADB_REMOTEIO_PLUGIN; #endif /******** using plugins ************/ /** loads a plugin and initializes it @param mysql MYSQL structure. only MYSQL_PLUGIN_DIR option value is used, and last_errno/last_error, for error reporting @param name a name of the plugin to load @param type type of plugin that should be loaded, -1 to disable type check @param argc number of arguments to pass to the plugin initialization function @param ... arguments for the plugin initialization function @retval a pointer to the loaded plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * mysql_load_plugin(struct st_mysql *mysql, const char *name, int type, int argc, ...); /** loads a plugin and initializes it, taking va_list as an argument This is the same as mysql_load_plugin, but take va_list instead of a list of arguments. @param mysql MYSQL structure. only MYSQL_PLUGIN_DIR option value is used, and last_errno/last_error, for error reporting @param name a name of the plugin to load @param type type of plugin that should be loaded, -1 to disable type check @param argc number of arguments to pass to the plugin initialization function @param args arguments for the plugin initialization function @retval a pointer to the loaded plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * STDCALL mysql_load_plugin_v(struct st_mysql *mysql, const char *name, int type, int argc, va_list args); /** finds an already loaded plugin by name, or loads it, if necessary @param mysql MYSQL structure. only MYSQL_PLUGIN_DIR option value is used, and last_errno/last_error, for error reporting @param name a name of the plugin to load @param type type of plugin that should be loaded @retval a pointer to the plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * STDCALL mysql_client_find_plugin(struct st_mysql *mysql, const char *name, int type); /** adds a plugin structure to the list of loaded plugins This is useful if an application has the necessary functionality (for example, a special load data handler) statically linked into the application binary. It can use this function to register the plugin directly, avoiding the need to factor it out into a shared object. @param mysql MYSQL structure. It is only used for error reporting @param plugin an st_mysql_client_plugin structure to register @retval a pointer to the plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * STDCALL mysql_client_register_plugin(struct st_mysql *mysql, struct st_mysql_client_plugin *plugin); extern struct st_mysql_client_plugin *mysql_client_builtins[]; #endif mysql/mysql/plugin_auth.h000064400000007321151027430560011554 0ustar00#ifndef MYSQL_PLUGIN_AUTH_COMMON_INCLUDED /* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ /** @file This file defines constants and data structures that are the same for both client- and server-side authentication plugins. */ #define MYSQL_PLUGIN_AUTH_COMMON_INCLUDED /** the max allowed length for a user name */ #define MYSQL_USERNAME_LENGTH 512 /** return values of the plugin authenticate_user() method. */ /** Authentication failed. Additionally, all other CR_xxx values (libmariadb error code) can be used too. The client plugin may set the error code and the error message directly in the MYSQL structure and return CR_ERROR. If a CR_xxx specific error code was returned, an error message in the MYSQL structure will be overwritten. If CR_ERROR is returned without setting the error in MYSQL, CR_UNKNOWN_ERROR will be user. */ #define CR_ERROR 0 /** Authentication (client part) was successful. It does not mean that the authentication as a whole was successful, usually it only means that the client was able to send the user name and the password to the server. If CR_OK is returned, the libmariadb reads the next packet expecting it to be one of OK, ERROR, or CHANGE_PLUGIN packets. */ #define CR_OK -1 /** Authentication was successful. It means that the client has done its part successfully and also that a plugin has read the last packet (one of OK, ERROR, CHANGE_PLUGIN). In this case, libmariadb will not read a packet from the server, but it will use the data at mysql->net.read_pos. A plugin may return this value if the number of roundtrips in the authentication protocol is not known in advance, and the client plugin needs to read one packet more to determine if the authentication is finished or not. */ #define CR_OK_HANDSHAKE_COMPLETE -2 typedef struct st_plugin_vio_info { enum { MYSQL_VIO_INVALID, MYSQL_VIO_TCP, MYSQL_VIO_SOCKET, MYSQL_VIO_PIPE, MYSQL_VIO_MEMORY } protocol; int socket; /**< it's set, if the protocol is SOCKET or TCP */ #ifdef _WIN32 HANDLE handle; /**< it's set, if the protocol is PIPE or MEMORY */ #endif } MYSQL_PLUGIN_VIO_INFO; /** Provides plugin access to communication channel */ typedef struct st_plugin_vio { /** Plugin provides a pointer reference and this function sets it to the contents of any incoming packet. Returns the packet length, or -1 if the plugin should terminate. */ int (*read_packet)(struct st_plugin_vio *vio, unsigned char **buf); /** Plugin provides a buffer with data and the length and this function sends it as a packet. Returns 0 on success, 1 on failure. */ int (*write_packet)(struct st_plugin_vio *vio, const unsigned char *packet, int packet_len); /** Fills in a st_plugin_vio_info structure, providing the information about the connection. */ void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info); } MYSQL_PLUGIN_VIO; #endif mysql/my_config.h000064400000000224151027430560010035 0ustar00/* Do not edit this file directly, it was auto-generated by cmake */ #warning This file should not be included by clients, include only mysql/my_alloca.h000064400000000224151027430560010023 0ustar00/* Do not edit this file directly, it was auto-generated by cmake */ #warning This file should not be included by clients, include only mysql/mariadb_stmt.h000064400000022642151027430560010541 0ustar00/************************************************************************ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA Part of this code includes code from PHP's mysqlnd extension (written by Andrey Hristov, Georg Richter and Ulf Wendel), freely available from http://www.php.net/software *************************************************************************/ #define MYSQL_NO_DATA 100 #define MYSQL_DATA_TRUNCATED 101 #define MYSQL_DEFAULT_PREFETCH_ROWS (unsigned long) 1 /* Bind flags */ #define MADB_BIND_DUMMY 1 #define MARIADB_STMT_BULK_SUPPORTED(stmt)\ ((stmt)->mysql && \ (!((stmt)->mysql->server_capabilities & CLIENT_MYSQL) &&\ ((stmt)->mysql->extension->mariadb_server_capabilities & \ (MARIADB_CLIENT_STMT_BULK_OPERATIONS >> 32)))) #define CLEAR_CLIENT_STMT_ERROR(a) \ do { \ (a)->last_errno= 0;\ strcpy((a)->sqlstate, "00000");\ (a)->last_error[0]= 0;\ } while (0) #define MYSQL_PS_SKIP_RESULT_W_LEN -1 #define MYSQL_PS_SKIP_RESULT_STR -2 #define STMT_ID_LENGTH 4 typedef struct st_mysql_stmt MYSQL_STMT; typedef MYSQL_RES* (*mysql_stmt_use_or_store_func)(MYSQL_STMT *); enum enum_stmt_attr_type { STMT_ATTR_UPDATE_MAX_LENGTH, STMT_ATTR_CURSOR_TYPE, STMT_ATTR_PREFETCH_ROWS, /* MariaDB only */ STMT_ATTR_PREBIND_PARAMS=200, STMT_ATTR_ARRAY_SIZE, STMT_ATTR_ROW_SIZE, STMT_ATTR_STATE, STMT_ATTR_CB_USER_DATA, STMT_ATTR_CB_PARAM, STMT_ATTR_CB_RESULT }; enum enum_cursor_type { CURSOR_TYPE_NO_CURSOR= 0, CURSOR_TYPE_READ_ONLY= 1, CURSOR_TYPE_FOR_UPDATE= 2, CURSOR_TYPE_SCROLLABLE= 4 }; enum enum_indicator_type { STMT_INDICATOR_NTS=-1, STMT_INDICATOR_NONE=0, STMT_INDICATOR_NULL=1, STMT_INDICATOR_DEFAULT=2, STMT_INDICATOR_IGNORE=3, STMT_INDICATOR_IGNORE_ROW=4 }; /* bulk PS flags */ #define STMT_BULK_FLAG_CLIENT_SEND_TYPES 128 #define STMT_BULK_FLAG_INSERT_ID_REQUEST 64 typedef enum mysql_stmt_state { MYSQL_STMT_INITTED = 0, MYSQL_STMT_PREPARED, MYSQL_STMT_EXECUTED, MYSQL_STMT_WAITING_USE_OR_STORE, MYSQL_STMT_USE_OR_STORE_CALLED, MYSQL_STMT_USER_FETCHING, /* fetch_row_buff or fetch_row_unbuf */ MYSQL_STMT_FETCH_DONE } enum_mysqlnd_stmt_state; typedef struct st_mysql_bind { unsigned long *length; /* output length pointer */ my_bool *is_null; /* Pointer to null indicator */ void *buffer; /* buffer to get/put data */ /* set this if you want to track data truncations happened during fetch */ my_bool *error; union { unsigned char *row_ptr; /* for the current data position */ char *indicator; /* indicator variable */ } u; void (*store_param_func)(NET *net, struct st_mysql_bind *param); void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *, unsigned char **row); void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *, unsigned char **row); /* output buffer length, must be set when fetching str/binary */ unsigned long buffer_length; unsigned long offset; /* offset position for char/binary fetch */ unsigned long length_value; /* Used if length is 0 */ unsigned int flags; /* special flags, e.g. for dummy bind */ unsigned int pack_length; /* Internal length for packed data */ enum enum_field_types buffer_type; /* buffer type */ my_bool error_value; /* used if error is 0 */ my_bool is_unsigned; /* set if integer type is unsigned */ my_bool long_data_used; /* If used with mysql_send_long_data */ my_bool is_null_value; /* Used if is_null is 0 */ void *extension; } MYSQL_BIND; typedef struct st_mysqlnd_upsert_result { unsigned int warning_count; unsigned int server_status; unsigned long long affected_rows; unsigned long long last_insert_id; } mysql_upsert_status; typedef struct st_mysql_cmd_buffer { unsigned char *buffer; size_t length; } MYSQL_CMD_BUFFER; typedef struct st_mysql_error_info { unsigned int error_no; char error[MYSQL_ERRMSG_SIZE+1]; char sqlstate[SQLSTATE_LENGTH + 1]; } mysql_error_info; typedef int (*mysql_stmt_fetch_row_func)(MYSQL_STMT *stmt, unsigned char **row); typedef void (*ps_result_callback)(void *data, unsigned int column, unsigned char **row); typedef my_bool (*ps_param_callback)(void *data, MYSQL_BIND *bind, unsigned int row_nr); struct st_mysql_stmt { MA_MEM_ROOT mem_root; MYSQL *mysql; unsigned long stmt_id; unsigned long flags;/* cursor is set here */ enum_mysqlnd_stmt_state state; MYSQL_FIELD *fields; unsigned int field_count; unsigned int param_count; unsigned char send_types_to_server; MYSQL_BIND *params; MYSQL_BIND *bind; MYSQL_DATA result; /* we don't use mysqlnd's result set logic */ MYSQL_ROWS *result_cursor; my_bool bind_result_done; my_bool bind_param_done; mysql_upsert_status upsert_status; unsigned int last_errno; char last_error[MYSQL_ERRMSG_SIZE+1]; char sqlstate[SQLSTATE_LENGTH + 1]; my_bool update_max_length; unsigned long prefetch_rows; LIST list; my_bool cursor_exists; void *extension; mysql_stmt_fetch_row_func fetch_row_func; unsigned int execute_count;/* count how many times the stmt was executed */ mysql_stmt_use_or_store_func default_rset_handler; unsigned char *request_buffer; unsigned int array_size; size_t row_size; unsigned int prebind_params; void *user_data; ps_result_callback result_callback; ps_param_callback param_callback; size_t request_length; }; typedef void (*ps_field_fetch_func)(MYSQL_BIND *r_param, const MYSQL_FIELD * field, unsigned char **row); typedef struct st_mysql_perm_bind { ps_field_fetch_func func; /* should be signed int */ int pack_len; unsigned long max_len; } MYSQL_PS_CONVERSION; extern MYSQL_PS_CONVERSION mysql_ps_fetch_functions[MYSQL_TYPE_GEOMETRY + 1]; unsigned long ma_net_safe_read(MYSQL *mysql); void mysql_init_ps_subsystem(void); unsigned long net_field_length(unsigned char **packet); int ma_simple_command(MYSQL *mysql,enum enum_server_command command, const char *arg, size_t length, my_bool skipp_check, void *opt_arg); void stmt_set_error(MYSQL_STMT *stmt, unsigned int error_nr, const char *sqlstate, const char *format, ...); /* * function prototypes */ MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql); int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, unsigned long length); int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt); int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt); int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, unsigned int column, unsigned long offset); int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt); unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt); my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, const void *attr); my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, void *attr); my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd); my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd); my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt); my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt); my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt); my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long length); MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt); MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt); unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt); const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt); const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt); MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET offset); MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt); void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, unsigned long long offset); unsigned long long STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt); unsigned long long STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt); unsigned long long STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt); unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt); int STDCALL mysql_stmt_next_result(MYSQL_STMT *stmt); my_bool STDCALL mysql_stmt_more_results(MYSQL_STMT *stmt); int STDCALL mariadb_stmt_execute_direct(MYSQL_STMT *stmt, const char *stmt_str, size_t length); MYSQL_FIELD * STDCALL mariadb_stmt_fetch_fields(MYSQL_STMT *stmt); mysql/mysql_version.h000064400000000346151027430560011002 0ustar00/* Do not edit this file directly, it was auto-generated by cmake */ #warning This file should not be included by clients, include only #include #define LIBMYSQL_VERSION MARIADB_CLIENT_VERSION_STR mysql/mariadb_ctype.h000064400000005041151027430560010670 0ustar00/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ /* A better implementation of the UNIX ctype(3) library. Notes: my_global.h should be included before ctype.h */ #ifndef _mariadb_ctype_h #define _mariadb_ctype_h #include #ifdef __cplusplus extern "C" { #endif #define CHARSET_DIR "charsets/" #define MY_CS_NAME_SIZE 32 #define MADB_DEFAULT_CHARSET_NAME "latin1" #define MADB_DEFAULT_COLLATION_NAME "latin1_swedish_ci" #define MADB_AUTODETECT_CHARSET_NAME "auto" /* we use the mysqlnd implementation */ typedef struct ma_charset_info_st { unsigned int nr; /* so far only 1 byte for charset */ unsigned int state; const char *csname; const char *name; const char *dir; unsigned int codepage; const char *encoding; unsigned int char_minlen; unsigned int char_maxlen; unsigned int (*mb_charlen)(unsigned int c); unsigned int (*mb_valid)(const char *start, const char *end); } MARIADB_CHARSET_INFO; extern const MARIADB_CHARSET_INFO mariadb_compiled_charsets[]; extern MARIADB_CHARSET_INFO *ma_default_charset_info; extern MARIADB_CHARSET_INFO *ma_charset_bin; extern MARIADB_CHARSET_INFO *ma_charset_latin1; extern MARIADB_CHARSET_INFO *ma_charset_utf8_general_ci; extern MARIADB_CHARSET_INFO *ma_charset_utf16le_general_ci; MARIADB_CHARSET_INFO *find_compiled_charset(unsigned int cs_number); MARIADB_CHARSET_INFO *find_compiled_charset_by_name(const char *name); size_t mysql_cset_escape_quotes(const MARIADB_CHARSET_INFO *cset, char *newstr, const char *escapestr, size_t escapestr_len); size_t mysql_cset_escape_slashes(const MARIADB_CHARSET_INFO *cset, char *newstr, const char *escapestr, size_t escapestr_len); const char* madb_get_os_character_set(void); #ifdef _WIN32 int madb_get_windows_cp(const char *charset); #endif #ifdef __cplusplus } #endif #endif mysql/my_sys.h000064400000000224151027430560007406 0ustar00/* Do not edit this file directly, it was auto-generated by cmake */ #warning This file should not be included by clients, include only mysql/mariadb_com.h000064400000044522151027430560010331 0ustar00/************************************************************************************ Copyright (C) 2000, 2012 MySQL AB & MySQL Finland AB & TCX DataKonsult AB, Monty Program AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not see or write to the Free Software Foundation, Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110, USA Part of this code includes code from the PHP project which is freely available from http://www.php.net *************************************************************************************/ /* ** Common definition between mysql server & client */ #ifndef _mysql_com_h #define _mysql_com_h #define NAME_CHAR_LEN 64 #define NAME_LEN 256 /* Field/table name length */ #define HOSTNAME_LENGTH 255 #define SYSTEM_MB_MAX_CHAR_LENGTH 4 #define USERNAME_CHAR_LENGTH 128 #define USERNAME_LENGTH (USERNAME_CHAR_LENGTH * SYSTEM_MB_MAX_CHAR_LENGTH) #define SERVER_VERSION_LENGTH 60 #define SQLSTATE_LENGTH 5 #define SCRAMBLE_LENGTH 20 #define SCRAMBLE_LENGTH_323 8 #define LOCAL_HOST "localhost" #define LOCAL_HOST_NAMEDPIPE "." #if defined(_WIN32) && !defined( _CUSTOMCONFIG_) #define MARIADB_NAMEDPIPE "MySQL" #define MYSQL_SERVICENAME "MySql" #endif /* _WIN32 */ /* for use in mysql client tools only */ #define MYSQL_AUTODETECT_CHARSET_NAME "auto" #define BINCMP_FLAG 131072 enum Item_result {STRING_RESULT,REAL_RESULT,INT_RESULT,ROW_RESULT,DECIMAL_RESULT}; enum mysql_enum_shutdown_level { SHUTDOWN_DEFAULT = 0, KILL_QUERY= 254, KILL_CONNECTION= 255 }; enum enum_server_command { COM_SLEEP = 0, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME = 15, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, COM_TABLE_DUMP, COM_CONNECT_OUT = 20, COM_REGISTER_SLAVE, COM_STMT_PREPARE = 22, COM_STMT_EXECUTE = 23, COM_STMT_SEND_LONG_DATA = 24, COM_STMT_CLOSE = 25, COM_STMT_RESET = 26, COM_SET_OPTION = 27, COM_STMT_FETCH = 28, COM_DAEMON= 29, COM_UNSUPPORTED= 30, COM_RESET_CONNECTION = 31, COM_STMT_BULK_EXECUTE = 250, COM_RESERVED_1 = 254, /* former COM_MULTI, now removed */ COM_END }; #define NOT_NULL_FLAG 1 /* Field can't be NULL */ #define PRI_KEY_FLAG 2 /* Field is part of a primary key */ #define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */ #define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */ #define BLOB_FLAG 16 /* Field is a blob */ #define UNSIGNED_FLAG 32 /* Field is unsigned */ #define ZEROFILL_FLAG 64 /* Field is zerofill */ #define BINARY_FLAG 128 /* The following are only sent to new clients */ #define ENUM_FLAG 256 /* field is an enum */ #define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */ #define TIMESTAMP_FLAG 1024 /* Field is a timestamp */ #define SET_FLAG 2048 /* field is a set */ /* new since 3.23.58 */ #define NO_DEFAULT_VALUE_FLAG 4096 /* Field doesn't have default value */ #define ON_UPDATE_NOW_FLAG 8192 /* Field is set to NOW on UPDATE */ /* end new */ #define NUM_FLAG 32768 /* Field is num (for clients) */ #define PART_KEY_FLAG 16384 /* Intern; Part of some key */ #define GROUP_FLAG 32768 /* Intern: Group field */ #define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */ #define REFRESH_GRANT 1 /* Refresh grant tables */ #define REFRESH_LOG 2 /* Start on new log file */ #define REFRESH_TABLES 4 /* close all tables */ #define REFRESH_HOSTS 8 /* Flush host cache */ #define REFRESH_STATUS 16 /* Flush status variables */ #define REFRESH_THREADS 32 /* Flush thread cache */ #define REFRESH_SLAVE 64 /* Reset master info and restart slave thread */ #define REFRESH_MASTER 128 /* Remove all bin logs in the index and truncate the index */ /* The following can't be set with mysql_refresh() */ #define REFRESH_READ_LOCK 16384 /* Lock tables for read */ #define REFRESH_FAST 32768 /* Intern flag */ #define CLIENT_MYSQL 1 #define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */ #define CLIENT_LONG_FLAG 4 /* Get all column flags */ #define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */ #define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */ #define CLIENT_COMPRESS 32 /* Can use compression protocol */ #define CLIENT_ODBC 64 /* Odbc client */ #define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */ #define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */ #define CLIENT_INTERACTIVE 1024 /* This is an interactive client */ #define CLIENT_SSL 2048 /* Switch to SSL after handshake */ #define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */ #define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */ /* added in 4.x */ #define CLIENT_PROTOCOL_41 512 #define CLIENT_RESERVED 16384 #define CLIENT_SECURE_CONNECTION 32768 #define CLIENT_MULTI_STATEMENTS (1UL << 16) #define CLIENT_MULTI_RESULTS (1UL << 17) #define CLIENT_PS_MULTI_RESULTS (1UL << 18) #define CLIENT_PLUGIN_AUTH (1UL << 19) #define CLIENT_CONNECT_ATTRS (1UL << 20) #define CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA (1UL << 21) #define CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS (1UL << 22) #define CLIENT_SESSION_TRACKING (1UL << 23) #define CLIENT_ZSTD_COMPRESSION (1UL << 26) #define CLIENT_PROGRESS (1UL << 29) /* client supports progress indicator */ #define CLIENT_PROGRESS_OBSOLETE CLIENT_PROGRESS #define CLIENT_SSL_VERIFY_SERVER_CERT (1UL << 30) #define CLIENT_SSL_VERIFY_SERVER_CERT_OBSOLETE CLIENT_SSL_VERIFY_SERVER_CERT #define CLIENT_REMEMBER_OPTIONS (1UL << 31) /* MariaDB-specific capabilities */ #define MARIADB_CLIENT_FLAGS 0xFFFFFFFF00000000ULL #define MARIADB_CLIENT_PROGRESS (1ULL << 32) #define MARIADB_CLIENT_RESERVED_1 (1ULL << 33) /* Former COM_MULTI, don't use */ #define MARIADB_CLIENT_STMT_BULK_OPERATIONS (1ULL << 34) /* support of extended data type/format information, since 10.5.0 */ #define MARIADB_CLIENT_EXTENDED_METADATA (1ULL << 35) /* Do not resend metadata for prepared statements, since 10.6*/ #define MARIADB_CLIENT_CACHE_METADATA (1ULL << 36) #define IS_MARIADB_EXTENDED_SERVER(mysql)\ (!(mysql->server_capabilities & CLIENT_MYSQL)) #define MARIADB_CLIENT_SUPPORTED_FLAGS (MARIADB_CLIENT_PROGRESS |\ MARIADB_CLIENT_STMT_BULK_OPERATIONS|\ MARIADB_CLIENT_EXTENDED_METADATA|\ MARIADB_CLIENT_CACHE_METADATA) #define CLIENT_SUPPORTED_FLAGS (CLIENT_MYSQL |\ CLIENT_FOUND_ROWS |\ CLIENT_LONG_FLAG |\ CLIENT_CONNECT_WITH_DB |\ CLIENT_NO_SCHEMA |\ CLIENT_COMPRESS |\ CLIENT_ODBC |\ CLIENT_LOCAL_FILES |\ CLIENT_IGNORE_SPACE |\ CLIENT_INTERACTIVE |\ CLIENT_SSL |\ CLIENT_IGNORE_SIGPIPE |\ CLIENT_TRANSACTIONS |\ CLIENT_PROTOCOL_41 |\ CLIENT_RESERVED |\ CLIENT_SECURE_CONNECTION |\ CLIENT_MULTI_STATEMENTS |\ CLIENT_MULTI_RESULTS |\ CLIENT_PROGRESS |\ CLIENT_SSL_VERIFY_SERVER_CERT |\ CLIENT_REMEMBER_OPTIONS |\ CLIENT_PLUGIN_AUTH |\ CLIENT_SESSION_TRACKING |\ CLIENT_CONNECT_ATTRS) #define CLIENT_ALLOWED_FLAGS (CLIENT_SUPPORTED_FLAGS |\ CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA |\ CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS |\ CLIENT_ZSTD_COMPRESSION |\ CLIENT_PS_MULTI_RESULTS |\ CLIENT_REMEMBER_OPTIONS) #define CLIENT_CAPABILITIES (CLIENT_MYSQL | \ CLIENT_LONG_FLAG |\ CLIENT_TRANSACTIONS |\ CLIENT_SECURE_CONNECTION |\ CLIENT_MULTI_RESULTS | \ CLIENT_PS_MULTI_RESULTS |\ CLIENT_PROTOCOL_41 |\ CLIENT_PLUGIN_AUTH |\ CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | \ CLIENT_SESSION_TRACKING |\ CLIENT_CONNECT_ATTRS) #define CLIENT_DEFAULT_FLAGS ((CLIENT_SUPPORTED_FLAGS & ~CLIENT_COMPRESS)\ & ~CLIENT_SSL) #define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */ #define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */ #define SERVER_MORE_RESULTS_EXIST 8 #define SERVER_QUERY_NO_GOOD_INDEX_USED 16 #define SERVER_QUERY_NO_INDEX_USED 32 #define SERVER_STATUS_CURSOR_EXISTS 64 #define SERVER_STATUS_LAST_ROW_SENT 128 #define SERVER_STATUS_DB_DROPPED 256 #define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512 #define SERVER_STATUS_METADATA_CHANGED 1024 #define SERVER_QUERY_WAS_SLOW 2048 #define SERVER_PS_OUT_PARAMS 4096 #define SERVER_STATUS_IN_TRANS_READONLY 8192 #define SERVER_SESSION_STATE_CHANGED 16384 #define SERVER_STATUS_ANSI_QUOTES 32768 #define MYSQL_ERRMSG_SIZE 512 #define NET_READ_TIMEOUT 30 /* Timeout on read */ #define NET_WRITE_TIMEOUT 60 /* Timeout on write */ #define NET_WAIT_TIMEOUT (8*60*60) /* Wait for new query */ /* for server integration (mysqlbinlog) */ #define LIST_PROCESS_HOST_LEN 64 #define MYSQL50_TABLE_NAME_PREFIX "#mysql50#" #define MYSQL50_TABLE_NAME_PREFIX_LENGTH (sizeof(MYSQL50_TABLE_NAME_PREFIX)-1) #define SAFE_NAME_LEN (NAME_LEN + MYSQL50_TABLE_NAME_PREFIX_LENGTH) struct st_ma_pvio; typedef struct st_ma_pvio MARIADB_PVIO; #define MAX_CHAR_WIDTH 255 /* Max length for a CHAR column */ #define MAX_BLOB_WIDTH 8192 /* Default width for blob */ /* the following defines were added for PHP's mysqli and pdo extensions: see: CONC-56 */ #define MAX_TINYINT_WIDTH 3 #define MAX_SMALLINT_WIDTH 5 #define MAX_MEDIUMINT_WIDTH 8 #define MAX_INT_WIDTH 10 #define MAX_BIGINT_WIDTH 20 struct st_ma_connection_plugin; typedef struct st_net { MARIADB_PVIO *pvio; unsigned char *buff; unsigned char *buff_end,*write_pos,*read_pos; my_socket fd; /* For Perl DBI/dbd */ unsigned long remain_in_buf,length; unsigned long buf_length, where_b; unsigned long max_packet, max_packet_size; unsigned int pkt_nr, compress_pkt_nr; unsigned int write_timeout, read_timeout, retry_count; int fcntl; unsigned int *return_status; unsigned char reading_or_writing; char save_char; char unused_1; my_bool unused_2; my_bool compress; my_bool unused_3; void *unused_4; unsigned int last_errno; unsigned char error; my_bool unused_5; my_bool unused_6; char last_error[MYSQL_ERRMSG_SIZE]; char sqlstate[SQLSTATE_LENGTH+1]; struct st_mariadb_net_extension *extension; } NET; #define packet_error ((unsigned int) -1) /* used by mysql_set_server_option */ enum enum_mysql_set_option { MYSQL_OPTION_MULTI_STATEMENTS_ON, MYSQL_OPTION_MULTI_STATEMENTS_OFF }; /* for status callback function */ enum enum_mariadb_status_info { STATUS_TYPE= 0, SESSION_TRACK_TYPE }; enum enum_session_state_type { SESSION_TRACK_SYSTEM_VARIABLES= 0, SESSION_TRACK_SCHEMA, SESSION_TRACK_STATE_CHANGE, /* currently not supported by MariaDB Server */ SESSION_TRACK_GTIDS, SESSION_TRACK_TRANSACTION_CHARACTERISTICS, SESSION_TRACK_TRANSACTION_STATE /* make sure that SESSION_TRACK_END always points to last element of enum !! */ }; #define SESSION_TRACK_BEGIN 0 #define SESSION_TRACK_END SESSION_TRACK_TRANSACTION_STATE #define SESSION_TRACK_TYPES (SESSION_TRACK_END + 1) /* SESSION_TRACK_TRANSACTION_TYPE was renamed to SESSION_TRACK_TRANSACTION_STATE in 3e699a1738cdfb0a2c5b8eabfa8301b8d11cf711. This is a workaround to prevent breaking of travis and buildbot tests. TODO: Remove this after server fixes */ #define SESSION_TRACK_TRANSACTION_TYPE SESSION_TRACK_TRANSACTION_STATE enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY, MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE, MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24, MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR, MYSQL_TYPE_BIT, /* the following types are not used by client, only for mysqlbinlog!! */ MYSQL_TYPE_TIMESTAMP2, MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIME2, /* --------------------------------------------- */ MYSQL_TYPE_JSON=245, MYSQL_TYPE_NEWDECIMAL=246, MYSQL_TYPE_ENUM=247, MYSQL_TYPE_SET=248, MYSQL_TYPE_TINY_BLOB=249, MYSQL_TYPE_MEDIUM_BLOB=250, MYSQL_TYPE_LONG_BLOB=251, MYSQL_TYPE_BLOB=252, MYSQL_TYPE_VAR_STRING=253, MYSQL_TYPE_STRING=254, MYSQL_TYPE_GEOMETRY=255, MAX_NO_FIELD_TYPES }; #define FIELD_TYPE_CHAR FIELD_TYPE_TINY /* For compatibility */ #define FIELD_TYPE_INTERVAL FIELD_TYPE_ENUM /* For compatibility */ #define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL #define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL #define FIELD_TYPE_TINY MYSQL_TYPE_TINY #define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT #define FIELD_TYPE_LONG MYSQL_TYPE_LONG #define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT #define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE #define FIELD_TYPE_NULL MYSQL_TYPE_NULL #define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP #define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG #define FIELD_TYPE_INT24 MYSQL_TYPE_INT24 #define FIELD_TYPE_DATE MYSQL_TYPE_DATE #define FIELD_TYPE_TIME MYSQL_TYPE_TIME #define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME #define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR #define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE #define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM #define FIELD_TYPE_SET MYSQL_TYPE_SET #define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB #define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB #define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB #define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB #define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING #define FIELD_TYPE_STRING MYSQL_TYPE_STRING #define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY #define FIELD_TYPE_BIT MYSQL_TYPE_BIT extern unsigned long max_allowed_packet; extern unsigned long net_buffer_length; #define net_new_transaction(net) ((net)->pkt_nr=0) int ma_net_init(NET *net, MARIADB_PVIO *pvio); void ma_net_end(NET *net); void ma_net_clear(NET *net); int ma_net_flush(NET *net); int ma_net_write(NET *net,const unsigned char *packet, size_t len); int ma_net_write_command(NET *net,unsigned char command,const char *packet, size_t len, my_bool disable_flush); int ma_net_real_write(NET *net,const char *packet, size_t len); extern unsigned long ma_net_read(NET *net); struct rand_struct { unsigned long seed1,seed2,max_value; double max_value_dbl; }; /* The following is for user defined functions */ typedef struct st_udf_args { unsigned int arg_count; /* Number of arguments */ enum Item_result *arg_type; /* Pointer to item_results */ char **args; /* Pointer to argument */ unsigned long *lengths; /* Length of string arguments */ char *maybe_null; /* Set to 1 for all maybe_null args */ } UDF_ARGS; /* This holds information about the result */ typedef struct st_udf_init { my_bool maybe_null; /* 1 if function can return NULL */ unsigned int decimals; /* for real functions */ unsigned int max_length; /* For string functions */ char *ptr; /* free pointer for function data */ my_bool const_item; /* 0 if result is independent of arguments */ } UDF_INIT; /* Connection types */ #define MARIADB_CONNECTION_UNIXSOCKET 0 #define MARIADB_CONNECTION_TCP 1 #define MARIADB_CONNECTION_NAMEDPIPE 2 #define MARIADB_CONNECTION_SHAREDMEM 3 /* Constants when using compression */ #define NET_HEADER_SIZE 4 /* standard header size */ #define COMP_HEADER_SIZE 3 /* compression header extra size */ /* Prototypes to password functions */ #define native_password_plugin_name "mysql_native_password" #define old_password_plugin_name "mysql_old_password" #ifdef __cplusplus extern "C" { #endif char *ma_scramble_323(char *to,const char *message,const char *password); void ma_scramble_41(const unsigned char *buffer, const char *scramble, const char *password); void ma_hash_password(unsigned long *result, const char *password, size_t len); void ma_make_scrambled_password(char *to,const char *password); /* Some other useful functions */ void mariadb_load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv); my_bool ma_thread_init(void); void ma_thread_end(void); #ifdef __cplusplus } #endif #define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */ #endif mysql/mysql.h000064400000121625151027430560007241 0ustar00/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB 2012 by MontyProgram AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ /* defines for the libmariadb library */ #ifndef _mysql_h #define _mysql_h #ifdef __cplusplus extern "C" { #endif #ifndef LIBMARIADB #define LIBMARIADB #endif #ifndef MYSQL_CLIENT #define MYSQL_CLIENT #endif #include #if !defined (_global_h) && !defined (MY_GLOBAL_INCLUDED) /* If not standard header */ #include typedef char my_bool; typedef unsigned long long my_ulonglong; #if !defined(_WIN32) #define STDCALL #else #define STDCALL __stdcall #endif #ifndef my_socket_defined #define my_socket_defined #if defined(_WIN64) #define my_socket unsigned long long #elif defined(_WIN32) #define my_socket unsigned int #else typedef int my_socket; #endif #endif #endif #include "mariadb_com.h" #include "mariadb_version.h" #include "ma_list.h" #include "mariadb_ctype.h" typedef struct st_ma_const_string { const char *str; size_t length; } MARIADB_CONST_STRING; typedef struct st_ma_const_data { const unsigned char *data; size_t length; } MARIADB_CONST_DATA; #ifndef ST_MA_USED_MEM_DEFINED #define ST_MA_USED_MEM_DEFINED typedef struct st_ma_used_mem { /* struct for once_alloc */ struct st_ma_used_mem *next; /* Next block in use */ size_t left; /* memory left in block */ size_t size; /* Size of block */ } MA_USED_MEM; typedef struct st_ma_mem_root { MA_USED_MEM *free; MA_USED_MEM *used; MA_USED_MEM *pre_alloc; size_t min_malloc; size_t block_size; unsigned int block_num; unsigned int first_block_usage; void (*error_handler)(void); } MA_MEM_ROOT; #endif extern unsigned int mysql_port; extern char *mysql_unix_port; extern unsigned int mariadb_deinitialize_ssl; #define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG) #define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG) #define IS_BLOB(n) ((n) & BLOB_FLAG) #define IS_NUM(t) (((t) <= MYSQL_TYPE_INT24 && (t) != MYSQL_TYPE_TIMESTAMP) || (t) == MYSQL_TYPE_YEAR || (t) == MYSQL_TYPE_NEWDECIMAL) #define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG) #define INTERNAL_NUM_FIELD(f) (((f)->type <= MYSQL_TYPE_INT24 && ((f)->type != MYSQL_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == MYSQL_TYPE_YEAR || (f)->type == MYSQL_TYPE_NEWDECIMAL || (f)->type == MYSQL_TYPE_DECIMAL) typedef struct st_mysql_field { char *name; /* Name of column */ char *org_name; /* Name of original column (added after 3.23.58) */ char *table; /* Table of column if column was a field */ char *org_table; /* Name of original table (added after 3.23.58 */ char *db; /* table schema (added after 3.23.58) */ char *catalog; /* table catalog (added after 3.23.58) */ char *def; /* Default value (set by mysql_list_fields) */ unsigned long length; /* Width of column */ unsigned long max_length; /* Max width of selected set */ /* added after 3.23.58 */ unsigned int name_length; unsigned int org_name_length; unsigned int table_length; unsigned int org_table_length; unsigned int db_length; unsigned int catalog_length; unsigned int def_length; /***********************/ unsigned int flags; /* Div flags */ unsigned int decimals; /* Number of decimals in field */ unsigned int charsetnr; /* char set number (added in 4.1) */ enum enum_field_types type; /* Type of field. Se mysql_com.h for types */ void *extension; /* added in 4.1 */ } MYSQL_FIELD; typedef char **MYSQL_ROW; /* return data as array of strings */ typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */ #define SET_CLIENT_ERROR(a, b, c, d) \ do { \ (a)->net.last_errno= (b);\ strncpy((a)->net.sqlstate, (c), SQLSTATE_LENGTH);\ (a)->net.sqlstate[SQLSTATE_LENGTH]= 0;\ strncpy((a)->net.last_error, (d) ? (d) : ER((b)), MYSQL_ERRMSG_SIZE - 1);\ (a)->net.last_error[MYSQL_ERRMSG_SIZE - 1]= 0;\ } while(0) /* For mysql_async.c */ #define set_mariadb_error(A,B,C) SET_CLIENT_ERROR((A),(B),(C),0) extern const char *SQLSTATE_UNKNOWN; #define unknown_sqlstate SQLSTATE_UNKNOWN #define CLEAR_CLIENT_ERROR(a) \ do { \ (a)->net.last_errno= 0;\ strcpy((a)->net.sqlstate, "00000");\ (a)->net.last_error[0]= '\0';\ if ((a)->net.extension)\ (a)->net.extension->extended_errno= 0;\ } while (0) #define MYSQL_COUNT_ERROR (~(unsigned long long) 0) typedef struct st_mysql_rows { struct st_mysql_rows *next; /* list of rows */ MYSQL_ROW data; unsigned long length; } MYSQL_ROWS; typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */ typedef struct st_mysql_data { MYSQL_ROWS *data; void *embedded_info; MA_MEM_ROOT alloc; unsigned long long rows; unsigned int fields; void *extension; } MYSQL_DATA; enum mysql_option { MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE, MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP, MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT, MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION, MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH, MYSQL_OPT_BIND, MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH, MYSQL_OPT_SSL_CIPHER, MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH, /* Connection attribute options */ MYSQL_OPT_CONNECT_ATTR_RESET, MYSQL_OPT_CONNECT_ATTR_ADD, MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_SERVER_PUBLIC_KEY, MYSQL_ENABLE_CLEARTEXT_PLUGIN, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, MYSQL_OPT_SSL_ENFORCE, MYSQL_OPT_MAX_ALLOWED_PACKET, MYSQL_OPT_NET_BUFFER_LENGTH, MYSQL_OPT_TLS_VERSION, MYSQL_OPT_ZSTD_COMPRESSION_LEVEL, /* MariaDB-specific */ MYSQL_PROGRESS_CALLBACK=5999, MYSQL_OPT_NONBLOCK, /* MariaDB Connector/C specific */ MYSQL_DATABASE_DRIVER=7000, MARIADB_OPT_SSL_FP, /* deprecated, use MARIADB_OPT_TLS_PEER_FP instead */ MARIADB_OPT_SSL_FP_LIST, /* deprecated, use MARIADB_OPT_TLS_PEER_FP_LIST instead */ MARIADB_OPT_TLS_PASSPHRASE, /* passphrase for encrypted certificates */ MARIADB_OPT_TLS_CIPHER_STRENGTH, MARIADB_OPT_TLS_VERSION, MARIADB_OPT_TLS_PEER_FP, /* single finger print for server certificate verification */ MARIADB_OPT_TLS_PEER_FP_LIST, /* finger print white list for server certificate verification */ MARIADB_OPT_CONNECTION_READ_ONLY, MYSQL_OPT_CONNECT_ATTRS, /* for mysql_get_optionv */ MARIADB_OPT_USERDATA, MARIADB_OPT_CONNECTION_HANDLER, MARIADB_OPT_PORT, MARIADB_OPT_UNIXSOCKET, MARIADB_OPT_PASSWORD, MARIADB_OPT_HOST, MARIADB_OPT_USER, MARIADB_OPT_SCHEMA, MARIADB_OPT_DEBUG, MARIADB_OPT_FOUND_ROWS, MARIADB_OPT_MULTI_RESULTS, MARIADB_OPT_MULTI_STATEMENTS, MARIADB_OPT_INTERACTIVE, MARIADB_OPT_PROXY_HEADER, MARIADB_OPT_IO_WAIT, MARIADB_OPT_SKIP_READ_RESPONSE, MARIADB_OPT_RESTRICTED_AUTH, MARIADB_OPT_RPL_REGISTER_REPLICA, MARIADB_OPT_STATUS_CALLBACK, MARIADB_OPT_SERVER_PLUGINS }; enum mariadb_value { MARIADB_CHARSET_ID, MARIADB_CHARSET_NAME, MARIADB_CLIENT_ERRORS, MARIADB_CLIENT_VERSION, MARIADB_CLIENT_VERSION_ID, MARIADB_CONNECTION_ASYNC_TIMEOUT, MARIADB_CONNECTION_ASYNC_TIMEOUT_MS, MARIADB_CONNECTION_MARIADB_CHARSET_INFO, MARIADB_CONNECTION_ERROR, MARIADB_CONNECTION_ERROR_ID, MARIADB_CONNECTION_HOST, MARIADB_CONNECTION_INFO, MARIADB_CONNECTION_PORT, MARIADB_CONNECTION_PROTOCOL_VERSION_ID, MARIADB_CONNECTION_PVIO_TYPE, MARIADB_CONNECTION_SCHEMA, MARIADB_CONNECTION_SERVER_TYPE, MARIADB_CONNECTION_SERVER_VERSION, MARIADB_CONNECTION_SERVER_VERSION_ID, MARIADB_CONNECTION_SOCKET, MARIADB_CONNECTION_SQLSTATE, MARIADB_CONNECTION_SSL_CIPHER, MARIADB_TLS_LIBRARY, MARIADB_CONNECTION_TLS_VERSION, MARIADB_CONNECTION_TLS_VERSION_ID, MARIADB_CONNECTION_TYPE, MARIADB_CONNECTION_UNIX_SOCKET, MARIADB_CONNECTION_USER, MARIADB_MAX_ALLOWED_PACKET, MARIADB_NET_BUFFER_LENGTH, MARIADB_CONNECTION_SERVER_STATUS, MARIADB_CONNECTION_SERVER_CAPABILITIES, MARIADB_CONNECTION_EXTENDED_SERVER_CAPABILITIES, MARIADB_CONNECTION_CLIENT_CAPABILITIES, MARIADB_CONNECTION_BYTES_READ, MARIADB_CONNECTION_BYTES_SENT }; enum mysql_status { MYSQL_STATUS_READY, MYSQL_STATUS_GET_RESULT, MYSQL_STATUS_USE_RESULT, MYSQL_STATUS_QUERY_SENT, MYSQL_STATUS_SENDING_LOAD_DATA, MYSQL_STATUS_FETCHING_DATA, MYSQL_STATUS_NEXT_RESULT_PENDING, MYSQL_STATUS_QUIT_SENT, /* object is "destroyed" at this stage */ MYSQL_STATUS_STMT_RESULT }; enum mysql_protocol_type { MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET, MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY }; struct st_mysql_options { unsigned int connect_timeout, read_timeout, write_timeout; unsigned int port, protocol; unsigned long client_flag; char *host,*user,*password,*unix_socket,*db; struct st_dynamic_array *init_command; char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name; char *ssl_key; /* PEM key file */ char *ssl_cert; /* PEM cert file */ char *ssl_ca; /* PEM CA file */ char *ssl_capath; /* PEM directory of CA-s? */ char *ssl_cipher; char *shared_memory_base_name; unsigned long max_allowed_packet; my_bool use_ssl; /* if to use SSL or not */ my_bool compress,named_pipe; my_bool reconnect, unused_1, unused_2, unused_3; enum mysql_option methods_to_use; char *bind_address; my_bool secure_auth; my_bool report_data_truncation; /* function pointers for local infile support */ int (*local_infile_init)(void **, const char *, void *); int (*local_infile_read)(void *, char *, unsigned int); void (*local_infile_end)(void *); int (*local_infile_error)(void *, char *, unsigned int); void *local_infile_userdata; struct st_mysql_options_extension *extension; }; typedef struct st_mysql { NET net; /* Communication parameters */ void *unused_0; char *host,*user,*passwd,*unix_socket,*server_version,*host_info; char *info,*db; const struct ma_charset_info_st *charset; /* character set */ MYSQL_FIELD *fields; MA_MEM_ROOT field_alloc; unsigned long long affected_rows; unsigned long long insert_id; /* id if insert on table with NEXTNR */ unsigned long long extra_info; /* Used by mysqlshow */ unsigned long thread_id; /* Id for connection in server */ unsigned long packet_length; unsigned int port; unsigned long client_flag; unsigned long server_capabilities; unsigned int protocol_version; unsigned int field_count; unsigned int server_status; unsigned int server_language; unsigned int warning_count; /* warning count, added in 4.1 protocol */ struct st_mysql_options options; enum mysql_status status; my_bool free_me; /* If free in mysql_close */ my_bool unused_1; char scramble_buff[20+ 1]; /* madded after 3.23.58 */ my_bool unused_2; void *unused_3, *unused_4, *unused_5, *unused_6; LIST *stmts; const struct st_mariadb_methods *methods; void *thd; my_bool *unbuffered_fetch_owner; char *info_buffer; struct st_mariadb_extension *extension; } MYSQL; typedef struct st_mysql_res { unsigned long long row_count; unsigned int field_count, current_field; MYSQL_FIELD *fields; MYSQL_DATA *data; MYSQL_ROWS *data_cursor; MA_MEM_ROOT field_alloc; MYSQL_ROW row; /* If unbuffered read */ MYSQL_ROW current_row; /* buffer to current row */ unsigned long *lengths; /* column lengths of current row */ MYSQL *handle; /* for unbuffered reads */ my_bool eof; /* Used my mysql_fetch_row */ my_bool is_ps; } MYSQL_RES; typedef struct { unsigned long *p_max_allowed_packet; unsigned long *p_net_buffer_length; void *extension; } MYSQL_PARAMETERS; enum mariadb_field_attr_t { MARIADB_FIELD_ATTR_DATA_TYPE_NAME= 0, MARIADB_FIELD_ATTR_FORMAT_NAME= 1 }; #define MARIADB_FIELD_ATTR_LAST MARIADB_FIELD_ATTR_FORMAT_NAME int STDCALL mariadb_field_attr(MARIADB_CONST_STRING *attr, const MYSQL_FIELD *field, enum mariadb_field_attr_t type); #ifndef _mysql_time_h_ enum enum_mysql_timestamp_type { MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1, MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2 }; typedef struct st_mysql_time { unsigned int year, month, day, hour, minute, second; unsigned long second_part; my_bool neg; enum enum_mysql_timestamp_type time_type; } MYSQL_TIME; #define AUTO_SEC_PART_DIGITS 39 #endif #define SEC_PART_DIGITS 6 #define MARIADB_INVALID_SOCKET -1 /* Asynchronous API constants */ #define MYSQL_WAIT_READ 1 #define MYSQL_WAIT_WRITE 2 #define MYSQL_WAIT_EXCEPT 4 #define MYSQL_WAIT_TIMEOUT 8 typedef struct character_set { unsigned int number; /* character set number */ unsigned int state; /* character set state */ const char *csname; /* character set name */ const char *name; /* collation name */ const char *comment; /* comment */ const char *dir; /* character set directory */ unsigned int mbminlen; /* min. length for multibyte strings */ unsigned int mbmaxlen; /* max. length for multibyte strings */ } MY_CHARSET_INFO; /* Local infile support functions */ #define LOCAL_INFILE_ERROR_LEN 512 #include "mariadb_stmt.h" #ifndef MYSQL_CLIENT_PLUGIN_HEADER #define MYSQL_CLIENT_PLUGIN_HEADER \ int type; \ unsigned int interface_version; \ const char *name; \ const char *author; \ const char *desc; \ unsigned int version[3]; \ const char *license; \ void *mysql_api; \ int (*init)(char *, size_t, int, va_list); \ int (*deinit)(void); \ int (*options)(const char *option, const void *); struct st_mysql_client_plugin { MYSQL_CLIENT_PLUGIN_HEADER }; struct st_mysql_client_plugin * mysql_load_plugin(struct st_mysql *mysql, const char *name, int type, int argc, ...); struct st_mysql_client_plugin * STDCALL mysql_load_plugin_v(struct st_mysql *mysql, const char *name, int type, int argc, va_list args); struct st_mysql_client_plugin * STDCALL mysql_client_find_plugin(struct st_mysql *mysql, const char *name, int type); struct st_mysql_client_plugin * STDCALL mysql_client_register_plugin(struct st_mysql *mysql, struct st_mysql_client_plugin *plugin); #endif void STDCALL mysql_set_local_infile_handler(MYSQL *mysql, int (*local_infile_init)(void **, const char *, void *), int (*local_infile_read)(void *, char *, unsigned int), void (*local_infile_end)(void *), int (*local_infile_error)(void *, char*, unsigned int), void *); void mysql_set_local_infile_default(MYSQL *mysql); void my_set_error(MYSQL *mysql, unsigned int error_nr, const char *sqlstate, const char *format, ...); /* Functions to get information from the MYSQL and MYSQL_RES structures */ /* Should definitely be used if one uses shared libraries */ my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res); unsigned int STDCALL mysql_num_fields(MYSQL_RES *res); my_bool STDCALL mysql_eof(MYSQL_RES *res); MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res, unsigned int fieldnr); MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res); MYSQL_ROWS * STDCALL mysql_row_tell(MYSQL_RES *res); unsigned int STDCALL mysql_field_tell(MYSQL_RES *res); unsigned int STDCALL mysql_field_count(MYSQL *mysql); my_bool STDCALL mysql_more_results(MYSQL *mysql); int STDCALL mysql_next_result(MYSQL *mysql); my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql); my_bool STDCALL mysql_autocommit(MYSQL *mysql, my_bool mode); my_bool STDCALL mysql_commit(MYSQL *mysql); my_bool STDCALL mysql_rollback(MYSQL *mysql); my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql); unsigned int STDCALL mysql_errno(MYSQL *mysql); const char * STDCALL mysql_error(MYSQL *mysql); const char * STDCALL mysql_info(MYSQL *mysql); unsigned long STDCALL mysql_thread_id(MYSQL *mysql); const char * STDCALL mysql_character_set_name(MYSQL *mysql); void STDCALL mysql_get_character_set_info(MYSQL *mysql, MY_CHARSET_INFO *cs); int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname); my_bool mariadb_get_infov(MYSQL *mysql, enum mariadb_value value, void *arg, ...); my_bool STDCALL mariadb_get_info(MYSQL *mysql, enum mariadb_value value, void *arg); MYSQL * STDCALL mysql_init(MYSQL *mysql); int STDCALL mysql_ssl_set(MYSQL *mysql, const char *key, const char *cert, const char *ca, const char *capath, const char *cipher); const char * STDCALL mysql_get_ssl_cipher(MYSQL *mysql); my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user, const char *passwd, const char *db); MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); void STDCALL mysql_close(MYSQL *sock); int STDCALL mysql_select_db(MYSQL *mysql, const char *db); int STDCALL mysql_query(MYSQL *mysql, const char *q); int STDCALL mysql_send_query(MYSQL *mysql, const char *q, unsigned long length); my_bool STDCALL mysql_read_query_result(MYSQL *mysql); int STDCALL mysql_real_query(MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_shutdown(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); int STDCALL mysql_dump_debug_info(MYSQL *mysql); int STDCALL mysql_refresh(MYSQL *mysql, unsigned int refresh_options); int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid); int STDCALL mysql_ping(MYSQL *mysql); char * STDCALL mysql_stat(MYSQL *mysql); char * STDCALL mysql_get_server_info(MYSQL *mysql); unsigned long STDCALL mysql_get_server_version(MYSQL *mysql); char * STDCALL mysql_get_host_info(MYSQL *mysql); unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql); MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild); MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild); MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table, const char *wild); MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql); MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql); MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql); int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg); int STDCALL mysql_options4(MYSQL *mysql,enum mysql_option option, const void *arg1, const void *arg2); void STDCALL mysql_free_result(MYSQL_RES *result); void STDCALL mysql_data_seek(MYSQL_RES *result, unsigned long long offset); MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET); MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset); MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result); MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result); unsigned long STDCALL mysql_escape_string(char *to,const char *from, unsigned long from_length); unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql, char *to,const char *from, unsigned long length); unsigned int STDCALL mysql_thread_safe(void); unsigned int STDCALL mysql_warning_count(MYSQL *mysql); const char * STDCALL mysql_sqlstate(MYSQL *mysql); int STDCALL mysql_server_init(int argc, char **argv, char **groups); void STDCALL mysql_server_end(void); void STDCALL mysql_thread_end(void); my_bool STDCALL mysql_thread_init(void); int STDCALL mysql_set_server_option(MYSQL *mysql, enum enum_mysql_set_option option); const char * STDCALL mysql_get_client_info(void); unsigned long STDCALL mysql_get_client_version(void); my_bool STDCALL mariadb_connection(MYSQL *mysql); const char * STDCALL mysql_get_server_name(MYSQL *mysql); MARIADB_CHARSET_INFO * STDCALL mariadb_get_charset_by_name(const char *csname); MARIADB_CHARSET_INFO * STDCALL mariadb_get_charset_by_nr(unsigned int csnr); size_t STDCALL mariadb_convert_string(const char *from, size_t *from_len, MARIADB_CHARSET_INFO *from_cs, char *to, size_t *to_len, MARIADB_CHARSET_INFO *to_cs, int *errorcode); int mysql_optionsv(MYSQL *mysql,enum mysql_option option, ...); int mysql_get_optionv(MYSQL *mysql, enum mysql_option option, void *arg, ...); int STDCALL mysql_get_option(MYSQL *mysql, enum mysql_option option, void *arg); unsigned long STDCALL mysql_hex_string(char *to, const char *from, unsigned long len); my_socket STDCALL mysql_get_socket(MYSQL *mysql); unsigned int STDCALL mysql_get_timeout_value(const MYSQL *mysql); unsigned int STDCALL mysql_get_timeout_value_ms(const MYSQL *mysql); my_bool STDCALL mariadb_reconnect(MYSQL *mysql); int STDCALL mariadb_cancel(MYSQL *mysql); void STDCALL mysql_debug(const char *debug); unsigned long STDCALL mysql_net_read_packet(MYSQL *mysql); unsigned long STDCALL mysql_net_field_length(unsigned char **packet); my_bool STDCALL mysql_embedded(void); MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void); /* Async API */ int STDCALL mysql_close_start(MYSQL *sock); int STDCALL mysql_close_cont(MYSQL *sock, int status); int STDCALL mysql_commit_start(my_bool *ret, MYSQL * mysql); int STDCALL mysql_commit_cont(my_bool *ret, MYSQL * mysql, int status); int STDCALL mysql_dump_debug_info_cont(int *ret, MYSQL *mysql, int ready_status); int STDCALL mysql_dump_debug_info_start(int *ret, MYSQL *mysql); int STDCALL mysql_rollback_start(my_bool *ret, MYSQL * mysql); int STDCALL mysql_rollback_cont(my_bool *ret, MYSQL * mysql, int status); int STDCALL mysql_autocommit_start(my_bool *ret, MYSQL * mysql, my_bool auto_mode); int STDCALL mysql_list_fields_cont(MYSQL_RES **ret, MYSQL *mysql, int ready_status); int STDCALL mysql_list_fields_start(MYSQL_RES **ret, MYSQL *mysql, const char *table, const char *wild); int STDCALL mysql_autocommit_cont(my_bool *ret, MYSQL * mysql, int status); int STDCALL mysql_next_result_start(int *ret, MYSQL *mysql); int STDCALL mysql_next_result_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_select_db_start(int *ret, MYSQL *mysql, const char *db); int STDCALL mysql_select_db_cont(int *ret, MYSQL *mysql, int ready_status); int STDCALL mysql_stmt_warning_count(MYSQL_STMT *stmt); int STDCALL mysql_stmt_next_result_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_next_result_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_set_character_set_start(int *ret, MYSQL *mysql, const char *csname); int STDCALL mysql_set_character_set_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_change_user_start(my_bool *ret, MYSQL *mysql, const char *user, const char *passwd, const char *db); int STDCALL mysql_change_user_cont(my_bool *ret, MYSQL *mysql, int status); int STDCALL mysql_real_connect_start(MYSQL **ret, MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); int STDCALL mysql_real_connect_cont(MYSQL **ret, MYSQL *mysql, int status); int STDCALL mysql_query_start(int *ret, MYSQL *mysql, const char *q); int STDCALL mysql_query_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_send_query_start(int *ret, MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_send_query_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_real_query_start(int *ret, MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_real_query_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_store_result_start(MYSQL_RES **ret, MYSQL *mysql); int STDCALL mysql_store_result_cont(MYSQL_RES **ret, MYSQL *mysql, int status); int STDCALL mysql_shutdown_start(int *ret, MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); int STDCALL mysql_shutdown_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_refresh_start(int *ret, MYSQL *mysql, unsigned int refresh_options); int STDCALL mysql_refresh_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_kill_start(int *ret, MYSQL *mysql, unsigned long pid); int STDCALL mysql_kill_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_set_server_option_start(int *ret, MYSQL *mysql, enum enum_mysql_set_option option); int STDCALL mysql_set_server_option_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_ping_start(int *ret, MYSQL *mysql); int STDCALL mysql_ping_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_stat_start(const char **ret, MYSQL *mysql); int STDCALL mysql_stat_cont(const char **ret, MYSQL *mysql, int status); int STDCALL mysql_free_result_start(MYSQL_RES *result); int STDCALL mysql_free_result_cont(MYSQL_RES *result, int status); int STDCALL mysql_fetch_row_start(MYSQL_ROW *ret, MYSQL_RES *result); int STDCALL mysql_fetch_row_cont(MYSQL_ROW *ret, MYSQL_RES *result, int status); int STDCALL mysql_read_query_result_start(my_bool *ret, MYSQL *mysql); int STDCALL mysql_read_query_result_cont(my_bool *ret, MYSQL *mysql, int status); int STDCALL mysql_reset_connection_start(int *ret, MYSQL *mysql); int STDCALL mysql_reset_connection_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_session_track_get_next(MYSQL *mysql, enum enum_session_state_type type, const char **data, size_t *length); int STDCALL mysql_session_track_get_first(MYSQL *mysql, enum enum_session_state_type type, const char **data, size_t *length); int STDCALL mysql_stmt_prepare_start(int *ret, MYSQL_STMT *stmt,const char *query, unsigned long length); int STDCALL mysql_stmt_prepare_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_execute_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_execute_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_fetch_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_fetch_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_store_result_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_store_result_cont(int *ret, MYSQL_STMT *stmt,int status); int STDCALL mysql_stmt_close_start(my_bool *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_close_cont(my_bool *ret, MYSQL_STMT * stmt, int status); int STDCALL mysql_stmt_reset_start(my_bool *ret, MYSQL_STMT * stmt); int STDCALL mysql_stmt_reset_cont(my_bool *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_free_result_start(my_bool *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_free_result_cont(my_bool *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_send_long_data_start(my_bool *ret, MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long len); int STDCALL mysql_stmt_send_long_data_cont(my_bool *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_reset_connection(MYSQL *mysql); /* API function calls (used by dynamic plugins) */ struct st_mariadb_api { unsigned long long (STDCALL *mysql_num_rows)(MYSQL_RES *res); unsigned int (STDCALL *mysql_num_fields)(MYSQL_RES *res); my_bool (STDCALL *mysql_eof)(MYSQL_RES *res); MYSQL_FIELD *(STDCALL *mysql_fetch_field_direct)(MYSQL_RES *res, unsigned int fieldnr); MYSQL_FIELD * (STDCALL *mysql_fetch_fields)(MYSQL_RES *res); MYSQL_ROWS * (STDCALL *mysql_row_tell)(MYSQL_RES *res); unsigned int (STDCALL *mysql_field_tell)(MYSQL_RES *res); unsigned int (STDCALL *mysql_field_count)(MYSQL *mysql); my_bool (STDCALL *mysql_more_results)(MYSQL *mysql); int (STDCALL *mysql_next_result)(MYSQL *mysql); unsigned long long (STDCALL *mysql_affected_rows)(MYSQL *mysql); my_bool (STDCALL *mysql_autocommit)(MYSQL *mysql, my_bool mode); my_bool (STDCALL *mysql_commit)(MYSQL *mysql); my_bool (STDCALL *mysql_rollback)(MYSQL *mysql); unsigned long long (STDCALL *mysql_insert_id)(MYSQL *mysql); unsigned int (STDCALL *mysql_errno)(MYSQL *mysql); const char * (STDCALL *mysql_error)(MYSQL *mysql); const char * (STDCALL *mysql_info)(MYSQL *mysql); unsigned long (STDCALL *mysql_thread_id)(MYSQL *mysql); const char * (STDCALL *mysql_character_set_name)(MYSQL *mysql); void (STDCALL *mysql_get_character_set_info)(MYSQL *mysql, MY_CHARSET_INFO *cs); int (STDCALL *mysql_set_character_set)(MYSQL *mysql, const char *csname); my_bool (*mariadb_get_infov)(MYSQL *mysql, enum mariadb_value value, void *arg, ...); my_bool (STDCALL *mariadb_get_info)(MYSQL *mysql, enum mariadb_value value, void *arg); MYSQL * (STDCALL *mysql_init)(MYSQL *mysql); int (STDCALL *mysql_ssl_set)(MYSQL *mysql, const char *key, const char *cert, const char *ca, const char *capath, const char *cipher); const char * (STDCALL *mysql_get_ssl_cipher)(MYSQL *mysql); my_bool (STDCALL *mysql_change_user)(MYSQL *mysql, const char *user, const char *passwd, const char *db); MYSQL * (STDCALL *mysql_real_connect)(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); void (STDCALL *mysql_close)(MYSQL *sock); int (STDCALL *mysql_select_db)(MYSQL *mysql, const char *db); int (STDCALL *mysql_query)(MYSQL *mysql, const char *q); int (STDCALL *mysql_send_query)(MYSQL *mysql, const char *q, unsigned long length); my_bool (STDCALL *mysql_read_query_result)(MYSQL *mysql); int (STDCALL *mysql_real_query)(MYSQL *mysql, const char *q, unsigned long length); int (STDCALL *mysql_shutdown)(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); int (STDCALL *mysql_dump_debug_info)(MYSQL *mysql); int (STDCALL *mysql_refresh)(MYSQL *mysql, unsigned int refresh_options); int (STDCALL *mysql_kill)(MYSQL *mysql,unsigned long pid); int (STDCALL *mysql_ping)(MYSQL *mysql); char * (STDCALL *mysql_stat)(MYSQL *mysql); char * (STDCALL *mysql_get_server_info)(MYSQL *mysql); unsigned long (STDCALL *mysql_get_server_version)(MYSQL *mysql); char * (STDCALL *mysql_get_host_info)(MYSQL *mysql); unsigned int (STDCALL *mysql_get_proto_info)(MYSQL *mysql); MYSQL_RES * (STDCALL *mysql_list_dbs)(MYSQL *mysql,const char *wild); MYSQL_RES * (STDCALL *mysql_list_tables)(MYSQL *mysql,const char *wild); MYSQL_RES * (STDCALL *mysql_list_fields)(MYSQL *mysql, const char *table, const char *wild); MYSQL_RES * (STDCALL *mysql_list_processes)(MYSQL *mysql); MYSQL_RES * (STDCALL *mysql_store_result)(MYSQL *mysql); MYSQL_RES * (STDCALL *mysql_use_result)(MYSQL *mysql); int (STDCALL *mysql_options)(MYSQL *mysql,enum mysql_option option, const void *arg); void (STDCALL *mysql_free_result)(MYSQL_RES *result); void (STDCALL *mysql_data_seek)(MYSQL_RES *result, unsigned long long offset); MYSQL_ROW_OFFSET (STDCALL *mysql_row_seek)(MYSQL_RES *result, MYSQL_ROW_OFFSET); MYSQL_FIELD_OFFSET (STDCALL *mysql_field_seek)(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset); MYSQL_ROW (STDCALL *mysql_fetch_row)(MYSQL_RES *result); unsigned long * (STDCALL *mysql_fetch_lengths)(MYSQL_RES *result); MYSQL_FIELD * (STDCALL *mysql_fetch_field)(MYSQL_RES *result); unsigned long (STDCALL *mysql_escape_string)(char *to,const char *from, unsigned long from_length); unsigned long (STDCALL *mysql_real_escape_string)(MYSQL *mysql, char *to,const char *from, unsigned long length); unsigned int (STDCALL *mysql_thread_safe)(void); unsigned int (STDCALL *mysql_warning_count)(MYSQL *mysql); const char * (STDCALL *mysql_sqlstate)(MYSQL *mysql); int (STDCALL *mysql_server_init)(int argc, char **argv, char **groups); void (STDCALL *mysql_server_end)(void); void (STDCALL *mysql_thread_end)(void); my_bool (STDCALL *mysql_thread_init)(void); int (STDCALL *mysql_set_server_option)(MYSQL *mysql, enum enum_mysql_set_option option); const char * (STDCALL *mysql_get_client_info)(void); unsigned long (STDCALL *mysql_get_client_version)(void); my_bool (STDCALL *mariadb_connection)(MYSQL *mysql); const char * (STDCALL *mysql_get_server_name)(MYSQL *mysql); MARIADB_CHARSET_INFO * (STDCALL *mariadb_get_charset_by_name)(const char *csname); MARIADB_CHARSET_INFO * (STDCALL *mariadb_get_charset_by_nr)(unsigned int csnr); size_t (STDCALL *mariadb_convert_string)(const char *from, size_t *from_len, MARIADB_CHARSET_INFO *from_cs, char *to, size_t *to_len, MARIADB_CHARSET_INFO *to_cs, int *errorcode); int (*mysql_optionsv)(MYSQL *mysql,enum mysql_option option, ...); int (*mysql_get_optionv)(MYSQL *mysql, enum mysql_option option, void *arg, ...); int (STDCALL *mysql_get_option)(MYSQL *mysql, enum mysql_option option, void *arg); unsigned long (STDCALL *mysql_hex_string)(char *to, const char *from, unsigned long len); my_socket (STDCALL *mysql_get_socket)(MYSQL *mysql); unsigned int (STDCALL *mysql_get_timeout_value)(const MYSQL *mysql); unsigned int (STDCALL *mysql_get_timeout_value_ms)(const MYSQL *mysql); my_bool (STDCALL *mariadb_reconnect)(MYSQL *mysql); MYSQL_STMT * (STDCALL *mysql_stmt_init)(MYSQL *mysql); int (STDCALL *mysql_stmt_prepare)(MYSQL_STMT *stmt, const char *query, unsigned long length); int (STDCALL *mysql_stmt_execute)(MYSQL_STMT *stmt); int (STDCALL *mysql_stmt_fetch)(MYSQL_STMT *stmt); int (STDCALL *mysql_stmt_fetch_column)(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, unsigned int column, unsigned long offset); int (STDCALL *mysql_stmt_store_result)(MYSQL_STMT *stmt); unsigned long (STDCALL *mysql_stmt_param_count)(MYSQL_STMT * stmt); my_bool (STDCALL *mysql_stmt_attr_set)(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, const void *attr); my_bool (STDCALL *mysql_stmt_attr_get)(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, void *attr); my_bool (STDCALL *mysql_stmt_bind_param)(MYSQL_STMT * stmt, MYSQL_BIND * bnd); my_bool (STDCALL *mysql_stmt_bind_result)(MYSQL_STMT * stmt, MYSQL_BIND * bnd); my_bool (STDCALL *mysql_stmt_close)(MYSQL_STMT * stmt); my_bool (STDCALL *mysql_stmt_reset)(MYSQL_STMT * stmt); my_bool (STDCALL *mysql_stmt_free_result)(MYSQL_STMT *stmt); my_bool (STDCALL *mysql_stmt_send_long_data)(MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long length); MYSQL_RES *(STDCALL *mysql_stmt_result_metadata)(MYSQL_STMT *stmt); MYSQL_RES *(STDCALL *mysql_stmt_param_metadata)(MYSQL_STMT *stmt); unsigned int (STDCALL *mysql_stmt_errno)(MYSQL_STMT * stmt); const char *(STDCALL *mysql_stmt_error)(MYSQL_STMT * stmt); const char *(STDCALL *mysql_stmt_sqlstate)(MYSQL_STMT * stmt); MYSQL_ROW_OFFSET (STDCALL *mysql_stmt_row_seek)(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET offset); MYSQL_ROW_OFFSET (STDCALL *mysql_stmt_row_tell)(MYSQL_STMT *stmt); void (STDCALL *mysql_stmt_data_seek)(MYSQL_STMT *stmt, unsigned long long offset); unsigned long long (STDCALL *mysql_stmt_num_rows)(MYSQL_STMT *stmt); unsigned long long (STDCALL *mysql_stmt_affected_rows)(MYSQL_STMT *stmt); unsigned long long (STDCALL *mysql_stmt_insert_id)(MYSQL_STMT *stmt); unsigned int (STDCALL *mysql_stmt_field_count)(MYSQL_STMT *stmt); int (STDCALL *mysql_stmt_next_result)(MYSQL_STMT *stmt); my_bool (STDCALL *mysql_stmt_more_results)(MYSQL_STMT *stmt); int (STDCALL *mariadb_stmt_execute_direct)(MYSQL_STMT *stmt, const char *stmtstr, size_t length); int (STDCALL *mysql_reset_connection)(MYSQL *mysql); }; /* these methods can be overwritten by db plugins */ struct st_mariadb_methods { MYSQL *(*db_connect)(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); void (*db_close)(MYSQL *mysql); int (*db_command)(MYSQL *mysql,enum enum_server_command command, const char *arg, size_t length, my_bool skip_check, void *opt_arg); void (*db_skip_result)(MYSQL *mysql); int (*db_read_query_result)(MYSQL *mysql); MYSQL_DATA *(*db_read_rows)(MYSQL *mysql,MYSQL_FIELD *fields, unsigned int field_count); int (*db_read_one_row)(MYSQL *mysql,unsigned int fields,MYSQL_ROW row, unsigned long *lengths); /* prepared statements */ my_bool (*db_supported_buffer_type)(enum enum_field_types type); my_bool (*db_read_prepare_response)(MYSQL_STMT *stmt); int (*db_read_stmt_result)(MYSQL *mysql); my_bool (*db_stmt_get_result_metadata)(MYSQL_STMT *stmt); my_bool (*db_stmt_get_param_metadata)(MYSQL_STMT *stmt); int (*db_stmt_read_all_rows)(MYSQL_STMT *stmt); int (*db_stmt_fetch)(MYSQL_STMT *stmt, unsigned char **row); int (*db_stmt_fetch_to_bind)(MYSQL_STMT *stmt, unsigned char *row); void (*db_stmt_flush_unbuffered)(MYSQL_STMT *stmt); void (*set_error)(MYSQL *mysql, unsigned int error_nr, const char *sqlstate, const char *format, ...); void (*invalidate_stmts)(MYSQL *mysql, const char *function_name); struct st_mariadb_api *api; int (*db_read_execute_response)(MYSQL_STMT *stmt); unsigned char* (*db_execute_generate_request)(MYSQL_STMT *stmt, size_t *request_len, my_bool internal); }; /* synonyms/aliases functions */ #define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT) #define mysql_library_init mysql_server_init #define mysql_library_end mysql_server_end #define mariadb_connect(hdl, conn_str) mysql_real_connect((hdl),(conn_str), NULL, NULL, NULL, 0, NULL, 0) /* new api functions */ #define HAVE_MYSQL_REAL_CONNECT #ifdef __cplusplus } #endif #endif mysql/mysql_com.h000064400000000256151027430560010073 0ustar00/* Do not edit this file directly, it was auto-generated by cmake */ #warning This file should not be included by clients, include only #include mysql/mariadb_dyncol.h000064400000020116151027430560011034 0ustar00/* Copyright (c) 2011, Monty Program Ab Copyright (c) 2011, Oleksandr Byelkin Copyright (c) 2012, 2022 MariaDB Corporation AB 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 the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY ``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 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ma_dyncol_h #define ma_dyncol_h #ifdef __cplusplus extern "C" { #endif #ifndef LIBMARIADB #include #include #endif #include #ifndef longlong_defined #if defined(HAVE_LONG_LONG) && SIZEOF_LONG != 8 typedef unsigned long long int ulonglong; /* ulong or unsigned long long */ typedef long long int longlong; #else typedef unsigned long ulonglong; /* ulong or unsigned long long */ typedef long longlong; #endif #define longlong_defined #endif #ifndef _my_sys_h typedef struct st_dynamic_string { char *str; size_t length,max_length,alloc_increment; } DYNAMIC_STRING; #endif struct st_mysql_lex_string { char *str; size_t length; }; typedef struct st_mysql_lex_string MYSQL_LEX_STRING; typedef struct st_mysql_lex_string LEX_STRING; /* Limits of implementation */ #define MAX_TOTAL_NAME_LENGTH 65535 #define MAX_NAME_LENGTH (MAX_TOTAL_NAME_LENGTH/4) /* NO and OK is the same used just to show semantics */ #define ER_DYNCOL_NO ER_DYNCOL_OK enum enum_dyncol_func_result { ER_DYNCOL_OK= 0, ER_DYNCOL_YES= 1, /* For functions returning 0/1 */ ER_DYNCOL_FORMAT= -1, /* Wrong format of the encoded string */ ER_DYNCOL_LIMIT= -2, /* Some limit reached */ ER_DYNCOL_RESOURCE= -3, /* Out of resources */ ER_DYNCOL_DATA= -4, /* Incorrect input data */ ER_DYNCOL_UNKNOWN_CHARSET= -5, /* Unknown character set */ ER_DYNCOL_TRUNCATED= 2 /* OK, but data was truncated */ }; typedef DYNAMIC_STRING DYNAMIC_COLUMN; enum enum_dynamic_column_type { DYN_COL_NULL= 0, DYN_COL_INT, DYN_COL_UINT, DYN_COL_DOUBLE, DYN_COL_STRING, DYN_COL_DECIMAL, DYN_COL_DATETIME, DYN_COL_DATE, DYN_COL_TIME, DYN_COL_DYNCOL }; typedef enum enum_dynamic_column_type DYNAMIC_COLUMN_TYPE; struct st_dynamic_column_value { DYNAMIC_COLUMN_TYPE type; union { long long long_value; unsigned long long ulong_value; double double_value; struct { MYSQL_LEX_STRING value; MARIADB_CHARSET_INFO *charset; } string; #ifndef LIBMARIADB struct { decimal_digit_t buffer[DECIMAL_BUFF_LENGTH]; decimal_t value; } decimal; #endif MYSQL_TIME time_value; } x; }; typedef struct st_dynamic_column_value DYNAMIC_COLUMN_VALUE; #ifdef MADYNCOL_DEPRECATED enum enum_dyncol_func_result dynamic_column_create(DYNAMIC_COLUMN *str, uint column_nr, DYNAMIC_COLUMN_VALUE *value); enum enum_dyncol_func_result dynamic_column_create_many(DYNAMIC_COLUMN *str, uint column_count, uint *column_numbers, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result dynamic_column_update(DYNAMIC_COLUMN *org, uint column_nr, DYNAMIC_COLUMN_VALUE *value); enum enum_dyncol_func_result dynamic_column_update_many(DYNAMIC_COLUMN *str, uint add_column_count, uint *column_numbers, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result dynamic_column_exists(DYNAMIC_COLUMN *org, uint column_nr); enum enum_dyncol_func_result dynamic_column_list(DYNAMIC_COLUMN *org, DYNAMIC_ARRAY *array_of_uint); enum enum_dyncol_func_result dynamic_column_get(DYNAMIC_COLUMN *org, uint column_nr, DYNAMIC_COLUMN_VALUE *store_it_here); #endif /* new functions */ enum enum_dyncol_func_result mariadb_dyncol_create_many_num(DYNAMIC_COLUMN *str, uint column_count, uint *column_numbers, DYNAMIC_COLUMN_VALUE *values, my_bool new_string); enum enum_dyncol_func_result mariadb_dyncol_create_many_named(DYNAMIC_COLUMN *str, uint column_count, MYSQL_LEX_STRING *column_keys, DYNAMIC_COLUMN_VALUE *values, my_bool new_string); enum enum_dyncol_func_result mariadb_dyncol_update_many_num(DYNAMIC_COLUMN *str, uint add_column_count, uint *column_keys, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result mariadb_dyncol_update_many_named(DYNAMIC_COLUMN *str, uint add_column_count, MYSQL_LEX_STRING *column_keys, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result mariadb_dyncol_exists_num(DYNAMIC_COLUMN *org, uint column_nr); enum enum_dyncol_func_result mariadb_dyncol_exists_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name); /* List of not NULL columns */ enum enum_dyncol_func_result mariadb_dyncol_list_num(DYNAMIC_COLUMN *str, uint *count, uint **nums); enum enum_dyncol_func_result mariadb_dyncol_list_named(DYNAMIC_COLUMN *str, uint *count, MYSQL_LEX_STRING **names); /* if the column do not exists it is NULL */ enum enum_dyncol_func_result mariadb_dyncol_get_num(DYNAMIC_COLUMN *org, uint column_nr, DYNAMIC_COLUMN_VALUE *store_it_here); enum enum_dyncol_func_result mariadb_dyncol_get_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name, DYNAMIC_COLUMN_VALUE *store_it_here); my_bool mariadb_dyncol_has_names(DYNAMIC_COLUMN *str); enum enum_dyncol_func_result mariadb_dyncol_check(DYNAMIC_COLUMN *str); enum enum_dyncol_func_result mariadb_dyncol_json(DYNAMIC_COLUMN *str, DYNAMIC_STRING *json); void mariadb_dyncol_free(DYNAMIC_COLUMN *str); #define mariadb_dyncol_init(A) memset((A), 0, sizeof(DYNAMIC_COLUMN)) #define dynamic_column_initialize(A) mariadb_dyncol_init((A)) #define dynamic_column_column_free(A) mariadb_dyncol_free((A)) /* conversion of values to 3 base types */ enum enum_dyncol_func_result mariadb_dyncol_val_str(DYNAMIC_STRING *str, DYNAMIC_COLUMN_VALUE *val, MARIADB_CHARSET_INFO *cs, char quote); enum enum_dyncol_func_result mariadb_dyncol_val_long(longlong *ll, DYNAMIC_COLUMN_VALUE *val); enum enum_dyncol_func_result mariadb_dyncol_val_double(double *dbl, DYNAMIC_COLUMN_VALUE *val); enum enum_dyncol_func_result mariadb_dyncol_unpack(DYNAMIC_COLUMN *str, uint *count, MYSQL_LEX_STRING **names, DYNAMIC_COLUMN_VALUE **vals); int mariadb_dyncol_column_cmp_named(const MYSQL_LEX_STRING *s1, const MYSQL_LEX_STRING *s2); enum enum_dyncol_func_result mariadb_dyncol_column_count(DYNAMIC_COLUMN *str, uint *column_count); #define mariadb_dyncol_value_init(V) \ do {\ (V)->type= DYN_COL_NULL;\ } while(0) /* Prepare value for using as decimal */ void mariadb_dyncol_prepare_decimal(DYNAMIC_COLUMN_VALUE *value); #ifdef __cplusplus } #endif #endif mysql/my_global.h000064400000000224151027430560010030 0ustar00/* Do not edit this file directly, it was auto-generated by cmake */ #warning This file should not be included by clients, include only mysql/mariadb_version.h000064400000002275151027430560011237 0ustar00/* Copyright Abandoned 1996, 1999, 2001 MySQL AB This file is public domain and comes with NO WARRANTY of any kind */ /* Version numbers for protocol & mysqld */ #ifndef _mariadb_version_h_ #define _mariadb_version_h_ #ifdef _CUSTOMCONFIG_ #include #else #define PROTOCOL_VERSION 10 #define MARIADB_CLIENT_VERSION_STR "10.6.23" #define MARIADB_BASE_VERSION "mariadb-10.6" #define MARIADB_VERSION_ID 100623 #define MARIADB_PORT 3306 #define MARIADB_UNIX_ADDR "/var/lib/mysql/mysql.sock" #ifndef MYSQL_UNIX_ADDR #define MYSQL_UNIX_ADDR MARIADB_UNIX_ADDR #endif #ifndef MYSQL_PORT #define MYSQL_PORT MARIADB_PORT #endif #define MYSQL_CONFIG_NAME "my" #define MYSQL_VERSION_ID 100623 #define MYSQL_SERVER_VERSION "10.6.23-MariaDB" #define MARIADB_PACKAGE_VERSION "3.3.17" #define MARIADB_PACKAGE_VERSION_ID 30317 #define MARIADB_SYSTEM_TYPE "Linux" #define MARIADB_MACHINE_TYPE "x86_64" #define MARIADB_PLUGINDIR "/usr/lib64/mysql/plugin" /* mysqld compile time options */ #ifndef MYSQL_CHARSET #define MYSQL_CHARSET "" #endif #endif /* Source information */ #define CC_SOURCE_REVISION "" #endif /* _mariadb_version_h_ */ mysql/server/mysqld_error.h000064400000135573151027430560012133 0ustar00/* Autogenerated file, please don't edit */ #ifndef ER_ERROR_FIRST #define ER_ERROR_FIRST 1000 #define ER_HASHCHK 1000 #define ER_NISAMCHK 1001 #define ER_NO 1002 #define ER_YES 1003 #define ER_CANT_CREATE_FILE 1004 #define ER_CANT_CREATE_TABLE 1005 #define ER_CANT_CREATE_DB 1006 #define ER_DB_CREATE_EXISTS 1007 #define ER_DB_DROP_EXISTS 1008 #define ER_DB_DROP_DELETE 1009 #define ER_DB_DROP_RMDIR 1010 #define ER_CANT_DELETE_FILE 1011 #define ER_CANT_FIND_SYSTEM_REC 1012 #define ER_CANT_GET_STAT 1013 #define ER_CANT_GET_WD 1014 #define ER_CANT_LOCK 1015 #define ER_CANT_OPEN_FILE 1016 #define ER_FILE_NOT_FOUND 1017 #define ER_CANT_READ_DIR 1018 #define ER_CANT_SET_WD 1019 #define ER_CHECKREAD 1020 #define ER_DISK_FULL 1021 #define ER_DUP_KEY 1022 #define ER_ERROR_ON_CLOSE 1023 #define ER_ERROR_ON_READ 1024 #define ER_ERROR_ON_RENAME 1025 #define ER_ERROR_ON_WRITE 1026 #define ER_FILE_USED 1027 #define ER_FILSORT_ABORT 1028 #define ER_FORM_NOT_FOUND 1029 #define ER_GET_ERRNO 1030 #define ER_ILLEGAL_HA 1031 #define ER_KEY_NOT_FOUND 1032 #define ER_NOT_FORM_FILE 1033 #define ER_NOT_KEYFILE 1034 #define ER_OLD_KEYFILE 1035 #define ER_OPEN_AS_READONLY 1036 #define ER_OUTOFMEMORY 1037 #define ER_OUT_OF_SORTMEMORY 1038 #define ER_UNEXPECTED_EOF 1039 #define ER_CON_COUNT_ERROR 1040 #define ER_OUT_OF_RESOURCES 1041 #define ER_BAD_HOST_ERROR 1042 #define ER_HANDSHAKE_ERROR 1043 #define ER_DBACCESS_DENIED_ERROR 1044 #define ER_ACCESS_DENIED_ERROR 1045 #define ER_NO_DB_ERROR 1046 #define ER_UNKNOWN_COM_ERROR 1047 #define ER_BAD_NULL_ERROR 1048 #define ER_BAD_DB_ERROR 1049 #define ER_TABLE_EXISTS_ERROR 1050 #define ER_BAD_TABLE_ERROR 1051 #define ER_NON_UNIQ_ERROR 1052 #define ER_SERVER_SHUTDOWN 1053 #define ER_BAD_FIELD_ERROR 1054 #define ER_WRONG_FIELD_WITH_GROUP 1055 #define ER_WRONG_GROUP_FIELD 1056 #define ER_WRONG_SUM_SELECT 1057 #define ER_WRONG_VALUE_COUNT 1058 #define ER_TOO_LONG_IDENT 1059 #define ER_DUP_FIELDNAME 1060 #define ER_DUP_KEYNAME 1061 #define ER_DUP_ENTRY 1062 #define ER_WRONG_FIELD_SPEC 1063 #define ER_PARSE_ERROR 1064 #define ER_EMPTY_QUERY 1065 #define ER_NONUNIQ_TABLE 1066 #define ER_INVALID_DEFAULT 1067 #define ER_MULTIPLE_PRI_KEY 1068 #define ER_TOO_MANY_KEYS 1069 #define ER_TOO_MANY_KEY_PARTS 1070 #define ER_TOO_LONG_KEY 1071 #define ER_KEY_COLUMN_DOES_NOT_EXITS 1072 #define ER_BLOB_USED_AS_KEY 1073 #define ER_TOO_BIG_FIELDLENGTH 1074 #define ER_WRONG_AUTO_KEY 1075 #define ER_BINLOG_CANT_DELETE_GTID_DOMAIN 1076 #define ER_NORMAL_SHUTDOWN 1077 #define ER_GOT_SIGNAL 1078 #define ER_SHUTDOWN_COMPLETE 1079 #define ER_FORCING_CLOSE 1080 #define ER_IPSOCK_ERROR 1081 #define ER_NO_SUCH_INDEX 1082 #define ER_WRONG_FIELD_TERMINATORS 1083 #define ER_BLOBS_AND_NO_TERMINATED 1084 #define ER_TEXTFILE_NOT_READABLE 1085 #define ER_FILE_EXISTS_ERROR 1086 #define ER_LOAD_INFO 1087 #define ER_ALTER_INFO 1088 #define ER_WRONG_SUB_KEY 1089 #define ER_CANT_REMOVE_ALL_FIELDS 1090 #define ER_CANT_DROP_FIELD_OR_KEY 1091 #define ER_INSERT_INFO 1092 #define ER_UPDATE_TABLE_USED 1093 #define ER_NO_SUCH_THREAD 1094 #define ER_KILL_DENIED_ERROR 1095 #define ER_NO_TABLES_USED 1096 #define ER_TOO_BIG_SET 1097 #define ER_NO_UNIQUE_LOGFILE 1098 #define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099 #define ER_TABLE_NOT_LOCKED 1100 #define ER_UNUSED_17 1101 #define ER_WRONG_DB_NAME 1102 #define ER_WRONG_TABLE_NAME 1103 #define ER_TOO_BIG_SELECT 1104 #define ER_UNKNOWN_ERROR 1105 #define ER_UNKNOWN_PROCEDURE 1106 #define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107 #define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108 #define ER_UNKNOWN_TABLE 1109 #define ER_FIELD_SPECIFIED_TWICE 1110 #define ER_INVALID_GROUP_FUNC_USE 1111 #define ER_UNSUPPORTED_EXTENSION 1112 #define ER_TABLE_MUST_HAVE_COLUMNS 1113 #define ER_RECORD_FILE_FULL 1114 #define ER_UNKNOWN_CHARACTER_SET 1115 #define ER_TOO_MANY_TABLES 1116 #define ER_TOO_MANY_FIELDS 1117 #define ER_TOO_BIG_ROWSIZE 1118 #define ER_STACK_OVERRUN 1119 #define ER_WRONG_OUTER_JOIN 1120 #define ER_NULL_COLUMN_IN_INDEX 1121 #define ER_CANT_FIND_UDF 1122 #define ER_CANT_INITIALIZE_UDF 1123 #define ER_UDF_NO_PATHS 1124 #define ER_UDF_EXISTS 1125 #define ER_CANT_OPEN_LIBRARY 1126 #define ER_CANT_FIND_DL_ENTRY 1127 #define ER_FUNCTION_NOT_DEFINED 1128 #define ER_HOST_IS_BLOCKED 1129 #define ER_HOST_NOT_PRIVILEGED 1130 #define ER_PASSWORD_ANONYMOUS_USER 1131 #define ER_PASSWORD_NOT_ALLOWED 1132 #define ER_PASSWORD_NO_MATCH 1133 #define ER_UPDATE_INFO 1134 #define ER_CANT_CREATE_THREAD 1135 #define ER_WRONG_VALUE_COUNT_ON_ROW 1136 #define ER_CANT_REOPEN_TABLE 1137 #define ER_INVALID_USE_OF_NULL 1138 #define ER_REGEXP_ERROR 1139 #define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140 #define ER_NONEXISTING_GRANT 1141 #define ER_TABLEACCESS_DENIED_ERROR 1142 #define ER_COLUMNACCESS_DENIED_ERROR 1143 #define ER_ILLEGAL_GRANT_FOR_TABLE 1144 #define ER_GRANT_WRONG_HOST_OR_USER 1145 #define ER_NO_SUCH_TABLE 1146 #define ER_NONEXISTING_TABLE_GRANT 1147 #define ER_NOT_ALLOWED_COMMAND 1148 #define ER_SYNTAX_ERROR 1149 #define ER_DELAYED_CANT_CHANGE_LOCK 1150 #define ER_TOO_MANY_DELAYED_THREADS 1151 #define ER_ABORTING_CONNECTION 1152 #define ER_NET_PACKET_TOO_LARGE 1153 #define ER_NET_READ_ERROR_FROM_PIPE 1154 #define ER_NET_FCNTL_ERROR 1155 #define ER_NET_PACKETS_OUT_OF_ORDER 1156 #define ER_NET_UNCOMPRESS_ERROR 1157 #define ER_NET_READ_ERROR 1158 #define ER_NET_READ_INTERRUPTED 1159 #define ER_NET_ERROR_ON_WRITE 1160 #define ER_NET_WRITE_INTERRUPTED 1161 #define ER_TOO_LONG_STRING 1162 #define ER_TABLE_CANT_HANDLE_BLOB 1163 #define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164 #define ER_DELAYED_INSERT_TABLE_LOCKED 1165 #define ER_WRONG_COLUMN_NAME 1166 #define ER_WRONG_KEY_COLUMN 1167 #define ER_WRONG_MRG_TABLE 1168 #define ER_DUP_UNIQUE 1169 #define ER_BLOB_KEY_WITHOUT_LENGTH 1170 #define ER_PRIMARY_CANT_HAVE_NULL 1171 #define ER_TOO_MANY_ROWS 1172 #define ER_REQUIRES_PRIMARY_KEY 1173 #define ER_NO_RAID_COMPILED 1174 #define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175 #define ER_KEY_DOES_NOT_EXISTS 1176 #define ER_CHECK_NO_SUCH_TABLE 1177 #define ER_CHECK_NOT_IMPLEMENTED 1178 #define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179 #define ER_ERROR_DURING_COMMIT 1180 #define ER_ERROR_DURING_ROLLBACK 1181 #define ER_ERROR_DURING_FLUSH_LOGS 1182 #define ER_ERROR_DURING_CHECKPOINT 1183 #define ER_NEW_ABORTING_CONNECTION 1184 #define ER_UNUSED_10 1185 #define ER_FLUSH_MASTER_BINLOG_CLOSED 1186 #define ER_INDEX_REBUILD 1187 #define ER_MASTER 1188 #define ER_MASTER_NET_READ 1189 #define ER_MASTER_NET_WRITE 1190 #define ER_FT_MATCHING_KEY_NOT_FOUND 1191 #define ER_LOCK_OR_ACTIVE_TRANSACTION 1192 #define ER_UNKNOWN_SYSTEM_VARIABLE 1193 #define ER_CRASHED_ON_USAGE 1194 #define ER_CRASHED_ON_REPAIR 1195 #define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196 #define ER_TRANS_CACHE_FULL 1197 #define ER_SLAVE_MUST_STOP 1198 #define ER_SLAVE_NOT_RUNNING 1199 #define ER_BAD_SLAVE 1200 #define ER_MASTER_INFO 1201 #define ER_SLAVE_THREAD 1202 #define ER_TOO_MANY_USER_CONNECTIONS 1203 #define ER_SET_CONSTANTS_ONLY 1204 #define ER_LOCK_WAIT_TIMEOUT 1205 #define ER_LOCK_TABLE_FULL 1206 #define ER_READ_ONLY_TRANSACTION 1207 #define ER_DROP_DB_WITH_READ_LOCK 1208 #define ER_CREATE_DB_WITH_READ_LOCK 1209 #define ER_WRONG_ARGUMENTS 1210 #define ER_NO_PERMISSION_TO_CREATE_USER 1211 #define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212 #define ER_LOCK_DEADLOCK 1213 #define ER_TABLE_CANT_HANDLE_FT 1214 #define ER_CANNOT_ADD_FOREIGN 1215 #define ER_NO_REFERENCED_ROW 1216 #define ER_ROW_IS_REFERENCED 1217 #define ER_CONNECT_TO_MASTER 1218 #define ER_QUERY_ON_MASTER 1219 #define ER_ERROR_WHEN_EXECUTING_COMMAND 1220 #define ER_WRONG_USAGE 1221 #define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222 #define ER_CANT_UPDATE_WITH_READLOCK 1223 #define ER_MIXING_NOT_ALLOWED 1224 #define ER_DUP_ARGUMENT 1225 #define ER_USER_LIMIT_REACHED 1226 #define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227 #define ER_LOCAL_VARIABLE 1228 #define ER_GLOBAL_VARIABLE 1229 #define ER_NO_DEFAULT 1230 #define ER_WRONG_VALUE_FOR_VAR 1231 #define ER_WRONG_TYPE_FOR_VAR 1232 #define ER_VAR_CANT_BE_READ 1233 #define ER_CANT_USE_OPTION_HERE 1234 #define ER_NOT_SUPPORTED_YET 1235 #define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236 #define ER_SLAVE_IGNORED_TABLE 1237 #define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238 #define ER_WRONG_FK_DEF 1239 #define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240 #define ER_OPERAND_COLUMNS 1241 #define ER_SUBQUERY_NO_1_ROW 1242 #define ER_UNKNOWN_STMT_HANDLER 1243 #define ER_CORRUPT_HELP_DB 1244 #define ER_CYCLIC_REFERENCE 1245 #define ER_AUTO_CONVERT 1246 #define ER_ILLEGAL_REFERENCE 1247 #define ER_DERIVED_MUST_HAVE_ALIAS 1248 #define ER_SELECT_REDUCED 1249 #define ER_TABLENAME_NOT_ALLOWED_HERE 1250 #define ER_NOT_SUPPORTED_AUTH_MODE 1251 #define ER_SPATIAL_CANT_HAVE_NULL 1252 #define ER_COLLATION_CHARSET_MISMATCH 1253 #define ER_SLAVE_WAS_RUNNING 1254 #define ER_SLAVE_WAS_NOT_RUNNING 1255 #define ER_TOO_BIG_FOR_UNCOMPRESS 1256 #define ER_ZLIB_Z_MEM_ERROR 1257 #define ER_ZLIB_Z_BUF_ERROR 1258 #define ER_ZLIB_Z_DATA_ERROR 1259 #define ER_CUT_VALUE_GROUP_CONCAT 1260 #define ER_WARN_TOO_FEW_RECORDS 1261 #define ER_WARN_TOO_MANY_RECORDS 1262 #define ER_WARN_NULL_TO_NOTNULL 1263 #define ER_WARN_DATA_OUT_OF_RANGE 1264 #define WARN_DATA_TRUNCATED 1265 #define ER_WARN_USING_OTHER_HANDLER 1266 #define ER_CANT_AGGREGATE_2COLLATIONS 1267 #define ER_DROP_USER 1268 #define ER_REVOKE_GRANTS 1269 #define ER_CANT_AGGREGATE_3COLLATIONS 1270 #define ER_CANT_AGGREGATE_NCOLLATIONS 1271 #define ER_VARIABLE_IS_NOT_STRUCT 1272 #define ER_UNKNOWN_COLLATION 1273 #define ER_SLAVE_IGNORED_SSL_PARAMS 1274 #define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275 #define ER_WARN_FIELD_RESOLVED 1276 #define ER_BAD_SLAVE_UNTIL_COND 1277 #define ER_MISSING_SKIP_SLAVE 1278 #define ER_UNTIL_COND_IGNORED 1279 #define ER_WRONG_NAME_FOR_INDEX 1280 #define ER_WRONG_NAME_FOR_CATALOG 1281 #define ER_WARN_QC_RESIZE 1282 #define ER_BAD_FT_COLUMN 1283 #define ER_UNKNOWN_KEY_CACHE 1284 #define ER_WARN_HOSTNAME_WONT_WORK 1285 #define ER_UNKNOWN_STORAGE_ENGINE 1286 #define ER_WARN_DEPRECATED_SYNTAX 1287 #define ER_NON_UPDATABLE_TABLE 1288 #define ER_FEATURE_DISABLED 1289 #define ER_OPTION_PREVENTS_STATEMENT 1290 #define ER_DUPLICATED_VALUE_IN_TYPE 1291 #define ER_TRUNCATED_WRONG_VALUE 1292 #define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293 #define ER_INVALID_ON_UPDATE 1294 #define ER_UNSUPPORTED_PS 1295 #define ER_GET_ERRMSG 1296 #define ER_GET_TEMPORARY_ERRMSG 1297 #define ER_UNKNOWN_TIME_ZONE 1298 #define ER_WARN_INVALID_TIMESTAMP 1299 #define ER_INVALID_CHARACTER_STRING 1300 #define ER_WARN_ALLOWED_PACKET_OVERFLOWED 1301 #define ER_CONFLICTING_DECLARATIONS 1302 #define ER_SP_NO_RECURSIVE_CREATE 1303 #define ER_SP_ALREADY_EXISTS 1304 #define ER_SP_DOES_NOT_EXIST 1305 #define ER_SP_DROP_FAILED 1306 #define ER_SP_STORE_FAILED 1307 #define ER_SP_LILABEL_MISMATCH 1308 #define ER_SP_LABEL_REDEFINE 1309 #define ER_SP_LABEL_MISMATCH 1310 #define ER_SP_UNINIT_VAR 1311 #define ER_SP_BADSELECT 1312 #define ER_SP_BADRETURN 1313 #define ER_SP_BADSTATEMENT 1314 #define ER_UPDATE_LOG_DEPRECATED_IGNORED 1315 #define ER_UPDATE_LOG_DEPRECATED_TRANSLATED 1316 #define ER_QUERY_INTERRUPTED 1317 #define ER_SP_WRONG_NO_OF_ARGS 1318 #define ER_SP_COND_MISMATCH 1319 #define ER_SP_NORETURN 1320 #define ER_SP_NORETURNEND 1321 #define ER_SP_BAD_CURSOR_QUERY 1322 #define ER_SP_BAD_CURSOR_SELECT 1323 #define ER_SP_CURSOR_MISMATCH 1324 #define ER_SP_CURSOR_ALREADY_OPEN 1325 #define ER_SP_CURSOR_NOT_OPEN 1326 #define ER_SP_UNDECLARED_VAR 1327 #define ER_SP_WRONG_NO_OF_FETCH_ARGS 1328 #define ER_SP_FETCH_NO_DATA 1329 #define ER_SP_DUP_PARAM 1330 #define ER_SP_DUP_VAR 1331 #define ER_SP_DUP_COND 1332 #define ER_SP_DUP_CURS 1333 #define ER_SP_CANT_ALTER 1334 #define ER_SP_SUBSELECT_NYI 1335 #define ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG 1336 #define ER_SP_VARCOND_AFTER_CURSHNDLR 1337 #define ER_SP_CURSOR_AFTER_HANDLER 1338 #define ER_SP_CASE_NOT_FOUND 1339 #define ER_FPARSER_TOO_BIG_FILE 1340 #define ER_FPARSER_BAD_HEADER 1341 #define ER_FPARSER_EOF_IN_COMMENT 1342 #define ER_FPARSER_ERROR_IN_PARAMETER 1343 #define ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER 1344 #define ER_VIEW_NO_EXPLAIN 1345 #define ER_FRM_UNKNOWN_TYPE 1346 #define ER_WRONG_OBJECT 1347 #define ER_NONUPDATEABLE_COLUMN 1348 #define ER_VIEW_SELECT_DERIVED 1349 #define ER_VIEW_SELECT_CLAUSE 1350 #define ER_VIEW_SELECT_VARIABLE 1351 #define ER_VIEW_SELECT_TMPTABLE 1352 #define ER_VIEW_WRONG_LIST 1353 #define ER_WARN_VIEW_MERGE 1354 #define ER_WARN_VIEW_WITHOUT_KEY 1355 #define ER_VIEW_INVALID 1356 #define ER_SP_NO_DROP_SP 1357 #define ER_SP_GOTO_IN_HNDLR 1358 #define ER_TRG_ALREADY_EXISTS 1359 #define ER_TRG_DOES_NOT_EXIST 1360 #define ER_TRG_ON_VIEW_OR_TEMP_TABLE 1361 #define ER_TRG_CANT_CHANGE_ROW 1362 #define ER_TRG_NO_SUCH_ROW_IN_TRG 1363 #define ER_NO_DEFAULT_FOR_FIELD 1364 #define ER_DIVISION_BY_ZERO 1365 #define ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366 #define ER_ILLEGAL_VALUE_FOR_TYPE 1367 #define ER_VIEW_NONUPD_CHECK 1368 #define ER_VIEW_CHECK_FAILED 1369 #define ER_PROCACCESS_DENIED_ERROR 1370 #define ER_RELAY_LOG_FAIL 1371 #define ER_PASSWD_LENGTH 1372 #define ER_UNKNOWN_TARGET_BINLOG 1373 #define ER_IO_ERR_LOG_INDEX_READ 1374 #define ER_BINLOG_PURGE_PROHIBITED 1375 #define ER_FSEEK_FAIL 1376 #define ER_BINLOG_PURGE_FATAL_ERR 1377 #define ER_LOG_IN_USE 1378 #define ER_LOG_PURGE_UNKNOWN_ERR 1379 #define ER_RELAY_LOG_INIT 1380 #define ER_NO_BINARY_LOGGING 1381 #define ER_RESERVED_SYNTAX 1382 #define ER_WSAS_FAILED 1383 #define ER_DIFF_GROUPS_PROC 1384 #define ER_NO_GROUP_FOR_PROC 1385 #define ER_ORDER_WITH_PROC 1386 #define ER_LOGGING_PROHIBIT_CHANGING_OF 1387 #define ER_NO_FILE_MAPPING 1388 #define ER_WRONG_MAGIC 1389 #define ER_PS_MANY_PARAM 1390 #define ER_KEY_PART_0 1391 #define ER_VIEW_CHECKSUM 1392 #define ER_VIEW_MULTIUPDATE 1393 #define ER_VIEW_NO_INSERT_FIELD_LIST 1394 #define ER_VIEW_DELETE_MERGE_VIEW 1395 #define ER_CANNOT_USER 1396 #define ER_XAER_NOTA 1397 #define ER_XAER_INVAL 1398 #define ER_XAER_RMFAIL 1399 #define ER_XAER_OUTSIDE 1400 #define ER_XAER_RMERR 1401 #define ER_XA_RBROLLBACK 1402 #define ER_NONEXISTING_PROC_GRANT 1403 #define ER_PROC_AUTO_GRANT_FAIL 1404 #define ER_PROC_AUTO_REVOKE_FAIL 1405 #define ER_DATA_TOO_LONG 1406 #define ER_SP_BAD_SQLSTATE 1407 #define ER_STARTUP 1408 #define ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR 1409 #define ER_CANT_CREATE_USER_WITH_GRANT 1410 #define ER_WRONG_VALUE_FOR_TYPE 1411 #define ER_TABLE_DEF_CHANGED 1412 #define ER_SP_DUP_HANDLER 1413 #define ER_SP_NOT_VAR_ARG 1414 #define ER_SP_NO_RETSET 1415 #define ER_CANT_CREATE_GEOMETRY_OBJECT 1416 #define ER_FAILED_ROUTINE_BREAK_BINLOG 1417 #define ER_BINLOG_UNSAFE_ROUTINE 1418 #define ER_BINLOG_CREATE_ROUTINE_NEED_SUPER 1419 #define ER_EXEC_STMT_WITH_OPEN_CURSOR 1420 #define ER_STMT_HAS_NO_OPEN_CURSOR 1421 #define ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG 1422 #define ER_NO_DEFAULT_FOR_VIEW_FIELD 1423 #define ER_SP_NO_RECURSION 1424 #define ER_TOO_BIG_SCALE 1425 #define ER_TOO_BIG_PRECISION 1426 #define ER_M_BIGGER_THAN_D 1427 #define ER_WRONG_LOCK_OF_SYSTEM_TABLE 1428 #define ER_CONNECT_TO_FOREIGN_DATA_SOURCE 1429 #define ER_QUERY_ON_FOREIGN_DATA_SOURCE 1430 #define ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 1431 #define ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 1432 #define ER_FOREIGN_DATA_STRING_INVALID 1433 #define ER_CANT_CREATE_FEDERATED_TABLE 1434 #define ER_TRG_IN_WRONG_SCHEMA 1435 #define ER_STACK_OVERRUN_NEED_MORE 1436 #define ER_TOO_LONG_BODY 1437 #define ER_WARN_CANT_DROP_DEFAULT_KEYCACHE 1438 #define ER_TOO_BIG_DISPLAYWIDTH 1439 #define ER_XAER_DUPID 1440 #define ER_DATETIME_FUNCTION_OVERFLOW 1441 #define ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG 1442 #define ER_VIEW_PREVENT_UPDATE 1443 #define ER_PS_NO_RECURSION 1444 #define ER_SP_CANT_SET_AUTOCOMMIT 1445 #define ER_MALFORMED_DEFINER 1446 #define ER_VIEW_FRM_NO_USER 1447 #define ER_VIEW_OTHER_USER 1448 #define ER_NO_SUCH_USER 1449 #define ER_FORBID_SCHEMA_CHANGE 1450 #define ER_ROW_IS_REFERENCED_2 1451 #define ER_NO_REFERENCED_ROW_2 1452 #define ER_SP_BAD_VAR_SHADOW 1453 #define ER_TRG_NO_DEFINER 1454 #define ER_OLD_FILE_FORMAT 1455 #define ER_SP_RECURSION_LIMIT 1456 #define ER_SP_PROC_TABLE_CORRUPT 1457 #define ER_SP_WRONG_NAME 1458 #define ER_TABLE_NEEDS_UPGRADE 1459 #define ER_SP_NO_AGGREGATE 1460 #define ER_MAX_PREPARED_STMT_COUNT_REACHED 1461 #define ER_VIEW_RECURSIVE 1462 #define ER_NON_GROUPING_FIELD_USED 1463 #define ER_TABLE_CANT_HANDLE_SPKEYS 1464 #define ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA 1465 #define ER_REMOVED_SPACES 1466 #define ER_AUTOINC_READ_FAILED 1467 #define ER_USERNAME 1468 #define ER_HOSTNAME 1469 #define ER_WRONG_STRING_LENGTH 1470 #define ER_NON_INSERTABLE_TABLE 1471 #define ER_ADMIN_WRONG_MRG_TABLE 1472 #define ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT 1473 #define ER_NAME_BECOMES_EMPTY 1474 #define ER_AMBIGUOUS_FIELD_TERM 1475 #define ER_FOREIGN_SERVER_EXISTS 1476 #define ER_FOREIGN_SERVER_DOESNT_EXIST 1477 #define ER_ILLEGAL_HA_CREATE_OPTION 1478 #define ER_PARTITION_REQUIRES_VALUES_ERROR 1479 #define ER_PARTITION_WRONG_VALUES_ERROR 1480 #define ER_PARTITION_MAXVALUE_ERROR 1481 #define ER_PARTITION_SUBPARTITION_ERROR 1482 #define ER_PARTITION_SUBPART_MIX_ERROR 1483 #define ER_PARTITION_WRONG_NO_PART_ERROR 1484 #define ER_PARTITION_WRONG_NO_SUBPART_ERROR 1485 #define ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR 1486 #define ER_NOT_CONSTANT_EXPRESSION 1487 #define ER_FIELD_NOT_FOUND_PART_ERROR 1488 #define ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR 1489 #define ER_INCONSISTENT_PARTITION_INFO_ERROR 1490 #define ER_PARTITION_FUNC_NOT_ALLOWED_ERROR 1491 #define ER_PARTITIONS_MUST_BE_DEFINED_ERROR 1492 #define ER_RANGE_NOT_INCREASING_ERROR 1493 #define ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR 1494 #define ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR 1495 #define ER_PARTITION_ENTRY_ERROR 1496 #define ER_MIX_HANDLER_ERROR 1497 #define ER_PARTITION_NOT_DEFINED_ERROR 1498 #define ER_TOO_MANY_PARTITIONS_ERROR 1499 #define ER_SUBPARTITION_ERROR 1500 #define ER_CANT_CREATE_HANDLER_FILE 1501 #define ER_BLOB_FIELD_IN_PART_FUNC_ERROR 1502 #define ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF 1503 #define ER_NO_PARTS_ERROR 1504 #define ER_PARTITION_MGMT_ON_NONPARTITIONED 1505 #define ER_FEATURE_NOT_SUPPORTED_WITH_PARTITIONING 1506 #define ER_DROP_PARTITION_NON_EXISTENT 1507 #define ER_DROP_LAST_PARTITION 1508 #define ER_COALESCE_ONLY_ON_HASH_PARTITION 1509 #define ER_REORG_HASH_ONLY_ON_SAME_NO 1510 #define ER_REORG_NO_PARAM_ERROR 1511 #define ER_ONLY_ON_RANGE_LIST_PARTITION 1512 #define ER_ADD_PARTITION_SUBPART_ERROR 1513 #define ER_ADD_PARTITION_NO_NEW_PARTITION 1514 #define ER_COALESCE_PARTITION_NO_PARTITION 1515 #define ER_REORG_PARTITION_NOT_EXIST 1516 #define ER_SAME_NAME_PARTITION 1517 #define ER_NO_BINLOG_ERROR 1518 #define ER_CONSECUTIVE_REORG_PARTITIONS 1519 #define ER_REORG_OUTSIDE_RANGE 1520 #define ER_PARTITION_FUNCTION_FAILURE 1521 #define ER_PART_STATE_ERROR 1522 #define ER_LIMITED_PART_RANGE 1523 #define ER_PLUGIN_IS_NOT_LOADED 1524 #define ER_WRONG_VALUE 1525 #define ER_NO_PARTITION_FOR_GIVEN_VALUE 1526 #define ER_FILEGROUP_OPTION_ONLY_ONCE 1527 #define ER_CREATE_FILEGROUP_FAILED 1528 #define ER_DROP_FILEGROUP_FAILED 1529 #define ER_TABLESPACE_AUTO_EXTEND_ERROR 1530 #define ER_WRONG_SIZE_NUMBER 1531 #define ER_SIZE_OVERFLOW_ERROR 1532 #define ER_ALTER_FILEGROUP_FAILED 1533 #define ER_BINLOG_ROW_LOGGING_FAILED 1534 #define ER_BINLOG_ROW_WRONG_TABLE_DEF 1535 #define ER_BINLOG_ROW_RBR_TO_SBR 1536 #define ER_EVENT_ALREADY_EXISTS 1537 #define ER_EVENT_STORE_FAILED 1538 #define ER_EVENT_DOES_NOT_EXIST 1539 #define ER_EVENT_CANT_ALTER 1540 #define ER_EVENT_DROP_FAILED 1541 #define ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG 1542 #define ER_EVENT_ENDS_BEFORE_STARTS 1543 #define ER_EVENT_EXEC_TIME_IN_THE_PAST 1544 #define ER_EVENT_OPEN_TABLE_FAILED 1545 #define ER_EVENT_NEITHER_M_EXPR_NOR_M_AT 1546 #define ER_UNUSED_2 1547 #define ER_UNUSED_3 1548 #define ER_EVENT_CANNOT_DELETE 1549 #define ER_EVENT_COMPILE_ERROR 1550 #define ER_EVENT_SAME_NAME 1551 #define ER_EVENT_DATA_TOO_LONG 1552 #define ER_DROP_INDEX_FK 1553 #define ER_WARN_DEPRECATED_SYNTAX_WITH_VER 1554 #define ER_CANT_WRITE_LOCK_LOG_TABLE 1555 #define ER_CANT_LOCK_LOG_TABLE 1556 #define ER_UNUSED_4 1557 #define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE 1558 #define ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR 1559 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT 1560 #define ER_UNUSED_13 1561 #define ER_PARTITION_NO_TEMPORARY 1562 #define ER_PARTITION_CONST_DOMAIN_ERROR 1563 #define ER_PARTITION_FUNCTION_IS_NOT_ALLOWED 1564 #define ER_DDL_LOG_ERROR 1565 #define ER_NULL_IN_VALUES_LESS_THAN 1566 #define ER_WRONG_PARTITION_NAME 1567 #define ER_CANT_CHANGE_TX_CHARACTERISTICS 1568 #define ER_DUP_ENTRY_AUTOINCREMENT_CASE 1569 #define ER_EVENT_MODIFY_QUEUE_ERROR 1570 #define ER_EVENT_SET_VAR_ERROR 1571 #define ER_PARTITION_MERGE_ERROR 1572 #define ER_CANT_ACTIVATE_LOG 1573 #define ER_RBR_NOT_AVAILABLE 1574 #define ER_BASE64_DECODE_ERROR 1575 #define ER_EVENT_RECURSION_FORBIDDEN 1576 #define ER_EVENTS_DB_ERROR 1577 #define ER_ONLY_INTEGERS_ALLOWED 1578 #define ER_UNSUPORTED_LOG_ENGINE 1579 #define ER_BAD_LOG_STATEMENT 1580 #define ER_CANT_RENAME_LOG_TABLE 1581 #define ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT 1582 #define ER_WRONG_PARAMETERS_TO_NATIVE_FCT 1583 #define ER_WRONG_PARAMETERS_TO_STORED_FCT 1584 #define ER_NATIVE_FCT_NAME_COLLISION 1585 #define ER_DUP_ENTRY_WITH_KEY_NAME 1586 #define ER_BINLOG_PURGE_EMFILE 1587 #define ER_EVENT_CANNOT_CREATE_IN_THE_PAST 1588 #define ER_EVENT_CANNOT_ALTER_IN_THE_PAST 1589 #define ER_SLAVE_INCIDENT 1590 #define ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT 1591 #define ER_BINLOG_UNSAFE_STATEMENT 1592 #define ER_SLAVE_FATAL_ERROR 1593 #define ER_SLAVE_RELAY_LOG_READ_FAILURE 1594 #define ER_SLAVE_RELAY_LOG_WRITE_FAILURE 1595 #define ER_SLAVE_CREATE_EVENT_FAILURE 1596 #define ER_SLAVE_MASTER_COM_FAILURE 1597 #define ER_BINLOG_LOGGING_IMPOSSIBLE 1598 #define ER_VIEW_NO_CREATION_CTX 1599 #define ER_VIEW_INVALID_CREATION_CTX 1600 #define ER_SR_INVALID_CREATION_CTX 1601 #define ER_TRG_CORRUPTED_FILE 1602 #define ER_TRG_NO_CREATION_CTX 1603 #define ER_TRG_INVALID_CREATION_CTX 1604 #define ER_EVENT_INVALID_CREATION_CTX 1605 #define ER_TRG_CANT_OPEN_TABLE 1606 #define ER_CANT_CREATE_SROUTINE 1607 #define ER_UNUSED_11 1608 #define ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT 1609 #define ER_SLAVE_CORRUPT_EVENT 1610 #define ER_LOAD_DATA_INVALID_COLUMN 1611 #define ER_LOG_PURGE_NO_FILE 1612 #define ER_XA_RBTIMEOUT 1613 #define ER_XA_RBDEADLOCK 1614 #define ER_NEED_REPREPARE 1615 #define ER_DELAYED_NOT_SUPPORTED 1616 #define WARN_NO_MASTER_INFO 1617 #define WARN_OPTION_IGNORED 1618 #define ER_PLUGIN_DELETE_BUILTIN 1619 #define WARN_PLUGIN_BUSY 1620 #define ER_VARIABLE_IS_READONLY 1621 #define ER_WARN_ENGINE_TRANSACTION_ROLLBACK 1622 #define ER_SLAVE_HEARTBEAT_FAILURE 1623 #define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE 1624 #define ER_UNUSED_14 1625 #define ER_CONFLICT_FN_PARSE_ERROR 1626 #define ER_EXCEPTIONS_WRITE_ERROR 1627 #define ER_TOO_LONG_TABLE_COMMENT 1628 #define ER_TOO_LONG_FIELD_COMMENT 1629 #define ER_FUNC_INEXISTENT_NAME_COLLISION 1630 #define ER_DATABASE_NAME 1631 #define ER_TABLE_NAME 1632 #define ER_PARTITION_NAME 1633 #define ER_SUBPARTITION_NAME 1634 #define ER_TEMPORARY_NAME 1635 #define ER_RENAMED_NAME 1636 #define ER_TOO_MANY_CONCURRENT_TRXS 1637 #define WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED 1638 #define ER_DEBUG_SYNC_TIMEOUT 1639 #define ER_DEBUG_SYNC_HIT_LIMIT 1640 #define ER_DUP_SIGNAL_SET 1641 #define ER_SIGNAL_WARN 1642 #define ER_SIGNAL_NOT_FOUND 1643 #define ER_SIGNAL_EXCEPTION 1644 #define ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER 1645 #define ER_SIGNAL_BAD_CONDITION_TYPE 1646 #define WARN_COND_ITEM_TRUNCATED 1647 #define ER_COND_ITEM_TOO_LONG 1648 #define ER_UNKNOWN_LOCALE 1649 #define ER_SLAVE_IGNORE_SERVER_IDS 1650 #define ER_QUERY_CACHE_DISABLED 1651 #define ER_SAME_NAME_PARTITION_FIELD 1652 #define ER_PARTITION_COLUMN_LIST_ERROR 1653 #define ER_WRONG_TYPE_COLUMN_VALUE_ERROR 1654 #define ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR 1655 #define ER_MAXVALUE_IN_VALUES_IN 1656 #define ER_TOO_MANY_VALUES_ERROR 1657 #define ER_ROW_SINGLE_PARTITION_FIELD_ERROR 1658 #define ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD 1659 #define ER_PARTITION_FIELDS_TOO_LONG 1660 #define ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE 1661 #define ER_BINLOG_ROW_MODE_AND_STMT_ENGINE 1662 #define ER_BINLOG_UNSAFE_AND_STMT_ENGINE 1663 #define ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE 1664 #define ER_BINLOG_STMT_MODE_AND_ROW_ENGINE 1665 #define ER_BINLOG_ROW_INJECTION_AND_STMT_MODE 1666 #define ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1667 #define ER_BINLOG_UNSAFE_LIMIT 1668 #define ER_BINLOG_UNSAFE_INSERT_DELAYED 1669 #define ER_BINLOG_UNSAFE_SYSTEM_TABLE 1670 #define ER_BINLOG_UNSAFE_AUTOINC_COLUMNS 1671 #define ER_BINLOG_UNSAFE_UDF 1672 #define ER_BINLOG_UNSAFE_SYSTEM_VARIABLE 1673 #define ER_BINLOG_UNSAFE_SYSTEM_FUNCTION 1674 #define ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS 1675 #define ER_MESSAGE_AND_STATEMENT 1676 #define ER_SLAVE_CONVERSION_FAILED 1677 #define ER_SLAVE_CANT_CREATE_CONVERSION 1678 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT 1679 #define ER_PATH_LENGTH 1680 #define ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT 1681 #define ER_WRONG_NATIVE_TABLE_STRUCTURE 1682 #define ER_WRONG_PERFSCHEMA_USAGE 1683 #define ER_WARN_I_S_SKIPPED_TABLE 1684 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT 1685 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT 1686 #define ER_SPATIAL_MUST_HAVE_GEOM_COL 1687 #define ER_TOO_LONG_INDEX_COMMENT 1688 #define ER_LOCK_ABORTED 1689 #define ER_DATA_OUT_OF_RANGE 1690 #define ER_WRONG_SPVAR_TYPE_IN_LIMIT 1691 #define ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE 1692 #define ER_BINLOG_UNSAFE_MIXED_STATEMENT 1693 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN 1694 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN 1695 #define ER_FAILED_READ_FROM_PAR_FILE 1696 #define ER_VALUES_IS_NOT_INT_TYPE_ERROR 1697 #define ER_ACCESS_DENIED_NO_PASSWORD_ERROR 1698 #define ER_SET_PASSWORD_AUTH_PLUGIN 1699 #define ER_GRANT_PLUGIN_USER_EXISTS 1700 #define ER_TRUNCATE_ILLEGAL_FK 1701 #define ER_PLUGIN_IS_PERMANENT 1702 #define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN 1703 #define ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX 1704 #define ER_STMT_CACHE_FULL 1705 #define ER_MULTI_UPDATE_KEY_CONFLICT 1706 #define ER_TABLE_NEEDS_REBUILD 1707 #define WARN_OPTION_BELOW_LIMIT 1708 #define ER_INDEX_COLUMN_TOO_LONG 1709 #define ER_ERROR_IN_TRIGGER_BODY 1710 #define ER_ERROR_IN_UNKNOWN_TRIGGER_BODY 1711 #define ER_INDEX_CORRUPT 1712 #define ER_UNDO_RECORD_TOO_BIG 1713 #define ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT 1714 #define ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE 1715 #define ER_BINLOG_UNSAFE_REPLACE_SELECT 1716 #define ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT 1717 #define ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT 1718 #define ER_BINLOG_UNSAFE_UPDATE_IGNORE 1719 #define ER_UNUSED_15 1720 #define ER_UNUSED_16 1721 #define ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT 1722 #define ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC 1723 #define ER_BINLOG_UNSAFE_INSERT_TWO_KEYS 1724 #define ER_UNUSED_28 1725 #define ER_VERS_NOT_ALLOWED 1726 #define ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST 1727 #define ER_CANNOT_LOAD_FROM_TABLE_V2 1728 #define ER_MASTER_DELAY_VALUE_OUT_OF_RANGE 1729 #define ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT 1730 #define ER_PARTITION_EXCHANGE_DIFFERENT_OPTION 1731 #define ER_PARTITION_EXCHANGE_PART_TABLE 1732 #define ER_PARTITION_EXCHANGE_TEMP_TABLE 1733 #define ER_PARTITION_INSTEAD_OF_SUBPARTITION 1734 #define ER_UNKNOWN_PARTITION 1735 #define ER_TABLES_DIFFERENT_METADATA 1736 #define ER_ROW_DOES_NOT_MATCH_PARTITION 1737 #define ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX 1738 #define ER_WARN_INDEX_NOT_APPLICABLE 1739 #define ER_PARTITION_EXCHANGE_FOREIGN_KEY 1740 #define ER_NO_SUCH_KEY_VALUE 1741 #define ER_VALUE_TOO_LONG 1742 #define ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE 1743 #define ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE 1744 #define ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX 1745 #define ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT 1746 #define ER_PARTITION_CLAUSE_ON_NONPARTITIONED 1747 #define ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET 1748 #define ER_UNUSED_5 1749 #define ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE 1750 #define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE 1751 #define ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE 1752 #define ER_MTS_FEATURE_IS_NOT_SUPPORTED 1753 #define ER_MTS_UPDATED_DBS_GREATER_MAX 1754 #define ER_MTS_CANT_PARALLEL 1755 #define ER_MTS_INCONSISTENT_DATA 1756 #define ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING 1757 #define ER_DA_INVALID_CONDITION_NUMBER 1758 #define ER_INSECURE_PLAIN_TEXT 1759 #define ER_INSECURE_CHANGE_MASTER 1760 #define ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO 1761 #define ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO 1762 #define ER_SQLTHREAD_WITH_SECURE_SLAVE 1763 #define ER_TABLE_HAS_NO_FT 1764 #define ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER 1765 #define ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION 1766 #define ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST 1767 #define ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL 1768 #define ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION 1769 #define ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL 1770 #define ER_SKIPPING_LOGGED_TRANSACTION 1771 #define ER_MALFORMED_GTID_SET_SPECIFICATION 1772 #define ER_MALFORMED_GTID_SET_ENCODING 1773 #define ER_MALFORMED_GTID_SPECIFICATION 1774 #define ER_GNO_EXHAUSTED 1775 #define ER_BAD_SLAVE_AUTO_POSITION 1776 #define ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON 1777 #define ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET 1778 #define ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON 1779 #define ER_GTID_MODE_REQUIRES_BINLOG 1780 #define ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF 1781 #define ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON 1782 #define ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF 1783 #define ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF 1784 #define ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE 1785 #define ER_GTID_UNSAFE_CREATE_SELECT 1786 #define ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION 1787 #define ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME 1788 #define ER_MASTER_HAS_PURGED_REQUIRED_GTIDS 1789 #define ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID 1790 #define ER_UNKNOWN_EXPLAIN_FORMAT 1791 #define ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION 1792 #define ER_TOO_LONG_TABLE_PARTITION_COMMENT 1793 #define ER_SLAVE_CONFIGURATION 1794 #define ER_INNODB_FT_LIMIT 1795 #define ER_INNODB_NO_FT_TEMP_TABLE 1796 #define ER_INNODB_FT_WRONG_DOCID_COLUMN 1797 #define ER_INNODB_FT_WRONG_DOCID_INDEX 1798 #define ER_INNODB_ONLINE_LOG_TOO_BIG 1799 #define ER_UNKNOWN_ALTER_ALGORITHM 1800 #define ER_UNKNOWN_ALTER_LOCK 1801 #define ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS 1802 #define ER_MTS_RECOVERY_FAILURE 1803 #define ER_MTS_RESET_WORKERS 1804 #define ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 1805 #define ER_SLAVE_SILENT_RETRY_TRANSACTION 1806 #define ER_UNUSED_22 1807 #define ER_TABLE_SCHEMA_MISMATCH 1808 #define ER_TABLE_IN_SYSTEM_TABLESPACE 1809 #define ER_IO_READ_ERROR 1810 #define ER_IO_WRITE_ERROR 1811 #define ER_TABLESPACE_MISSING 1812 #define ER_TABLESPACE_EXISTS 1813 #define ER_TABLESPACE_DISCARDED 1814 #define ER_INTERNAL_ERROR 1815 #define ER_INNODB_IMPORT_ERROR 1816 #define ER_INNODB_INDEX_CORRUPT 1817 #define ER_INVALID_YEAR_COLUMN_LENGTH 1818 #define ER_NOT_VALID_PASSWORD 1819 #define ER_MUST_CHANGE_PASSWORD 1820 #define ER_FK_NO_INDEX_CHILD 1821 #define ER_FK_NO_INDEX_PARENT 1822 #define ER_FK_FAIL_ADD_SYSTEM 1823 #define ER_FK_CANNOT_OPEN_PARENT 1824 #define ER_FK_INCORRECT_OPTION 1825 #define ER_DUP_CONSTRAINT_NAME 1826 #define ER_PASSWORD_FORMAT 1827 #define ER_FK_COLUMN_CANNOT_DROP 1828 #define ER_FK_COLUMN_CANNOT_DROP_CHILD 1829 #define ER_FK_COLUMN_NOT_NULL 1830 #define ER_DUP_INDEX 1831 #define ER_FK_COLUMN_CANNOT_CHANGE 1832 #define ER_FK_COLUMN_CANNOT_CHANGE_CHILD 1833 #define ER_FK_CANNOT_DELETE_PARENT 1834 #define ER_MALFORMED_PACKET 1835 #define ER_READ_ONLY_MODE 1836 #define ER_GTID_NEXT_TYPE_UNDEFINED_GROUP 1837 #define ER_VARIABLE_NOT_SETTABLE_IN_SP 1838 #define ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF 1839 #define ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY 1840 #define ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY 1841 #define ER_GTID_PURGED_WAS_CHANGED 1842 #define ER_GTID_EXECUTED_WAS_CHANGED 1843 #define ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES 1844 #define ER_ALTER_OPERATION_NOT_SUPPORTED 1845 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON 1846 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY 1847 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION 1848 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME 1849 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE 1850 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK 1851 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE 1852 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK 1853 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC 1854 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS 1855 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS 1856 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS 1857 #define ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE 1858 #define ER_DUP_UNKNOWN_IN_INDEX 1859 #define ER_IDENT_CAUSES_TOO_LONG_PATH 1860 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL 1861 #define ER_MUST_CHANGE_PASSWORD_LOGIN 1862 #define ER_ROW_IN_WRONG_PARTITION 1863 #define ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX 1864 #define ER_INNODB_NO_FT_USES_PARSER 1865 #define ER_BINLOG_LOGICAL_CORRUPTION 1866 #define ER_WARN_PURGE_LOG_IN_USE 1867 #define ER_WARN_PURGE_LOG_IS_ACTIVE 1868 #define ER_AUTO_INCREMENT_CONFLICT 1869 #define WARN_ON_BLOCKHOLE_IN_RBR 1870 #define ER_SLAVE_MI_INIT_REPOSITORY 1871 #define ER_SLAVE_RLI_INIT_REPOSITORY 1872 #define ER_ACCESS_DENIED_CHANGE_USER_ERROR 1873 #define ER_INNODB_READ_ONLY 1874 #define ER_STOP_SLAVE_SQL_THREAD_TIMEOUT 1875 #define ER_STOP_SLAVE_IO_THREAD_TIMEOUT 1876 #define ER_TABLE_CORRUPT 1877 #define ER_TEMP_FILE_WRITE_FAILURE 1878 #define ER_INNODB_FT_AUX_NOT_HEX_ID 1879 #define ER_LAST_MYSQL_ERROR_MESSAGE 1880 #define ER_ERROR_LAST_SECTION_1 1880 /* New section */ #define ER_ERROR_FIRST_SECTION_2 1900 #define ER_UNUSED_18 1900 #define ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED 1901 #define ER_UNUSED_19 1902 #define ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN 1903 #define ER_KEY_BASED_ON_GENERATED_VIRTUAL_COLUMN 1904 #define ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN 1905 #define ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN 1906 #define ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN 1907 #define ER_UNUSED_20 1908 #define ER_UNUSED_21 1909 #define ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS 1910 #define ER_UNKNOWN_OPTION 1911 #define ER_BAD_OPTION_VALUE 1912 #define ER_UNUSED_6 1913 #define ER_UNUSED_7 1914 #define ER_UNUSED_8 1915 #define ER_DATA_OVERFLOW 1916 #define ER_DATA_TRUNCATED 1917 #define ER_BAD_DATA 1918 #define ER_DYN_COL_WRONG_FORMAT 1919 #define ER_DYN_COL_IMPLEMENTATION_LIMIT 1920 #define ER_DYN_COL_DATA 1921 #define ER_DYN_COL_WRONG_CHARSET 1922 #define ER_ILLEGAL_SUBQUERY_OPTIMIZER_SWITCHES 1923 #define ER_QUERY_CACHE_IS_DISABLED 1924 #define ER_QUERY_CACHE_IS_GLOBALY_DISABLED 1925 #define ER_VIEW_ORDERBY_IGNORED 1926 #define ER_CONNECTION_KILLED 1927 #define ER_UNUSED_12 1928 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SKIP_REPLICATION 1929 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_SKIP_REPLICATION 1930 #define ER_QUERY_RESULT_INCOMPLETE 1931 #define ER_NO_SUCH_TABLE_IN_ENGINE 1932 #define ER_TARGET_NOT_EXPLAINABLE 1933 #define ER_CONNECTION_ALREADY_EXISTS 1934 #define ER_MASTER_LOG_PREFIX 1935 #define ER_CANT_START_STOP_SLAVE 1936 #define ER_SLAVE_STARTED 1937 #define ER_SLAVE_STOPPED 1938 #define ER_SQL_DISCOVER_ERROR 1939 #define ER_FAILED_GTID_STATE_INIT 1940 #define ER_INCORRECT_GTID_STATE 1941 #define ER_CANNOT_UPDATE_GTID_STATE 1942 #define ER_DUPLICATE_GTID_DOMAIN 1943 #define ER_GTID_OPEN_TABLE_FAILED 1944 #define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG 1945 #define ER_CANNOT_LOAD_SLAVE_GTID_STATE 1946 #define ER_MASTER_GTID_POS_CONFLICTS_WITH_BINLOG 1947 #define ER_MASTER_GTID_POS_MISSING_DOMAIN 1948 #define ER_UNTIL_REQUIRES_USING_GTID 1949 #define ER_GTID_STRICT_OUT_OF_ORDER 1950 #define ER_GTID_START_FROM_BINLOG_HOLE 1951 #define ER_SLAVE_UNEXPECTED_MASTER_SWITCH 1952 #define ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1953 #define ER_STORED_FUNCTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO 1954 #define ER_GTID_POSITION_NOT_FOUND_IN_BINLOG2 1955 #define ER_BINLOG_MUST_BE_EMPTY 1956 #define ER_NO_SUCH_QUERY 1957 #define ER_BAD_BASE64_DATA 1958 #define ER_INVALID_ROLE 1959 #define ER_INVALID_CURRENT_USER 1960 #define ER_CANNOT_GRANT_ROLE 1961 #define ER_CANNOT_REVOKE_ROLE 1962 #define ER_CHANGE_SLAVE_PARALLEL_THREADS_ACTIVE 1963 #define ER_PRIOR_COMMIT_FAILED 1964 #define ER_IT_IS_A_VIEW 1965 #define ER_SLAVE_SKIP_NOT_IN_GTID 1966 #define ER_TABLE_DEFINITION_TOO_BIG 1967 #define ER_PLUGIN_INSTALLED 1968 #define ER_STATEMENT_TIMEOUT 1969 #define ER_SUBQUERIES_NOT_SUPPORTED 1970 #define ER_SET_STATEMENT_NOT_SUPPORTED 1971 #define ER_UNUSED_9 1972 #define ER_USER_CREATE_EXISTS 1973 #define ER_USER_DROP_EXISTS 1974 #define ER_ROLE_CREATE_EXISTS 1975 #define ER_ROLE_DROP_EXISTS 1976 #define ER_CANNOT_CONVERT_CHARACTER 1977 #define ER_INVALID_DEFAULT_VALUE_FOR_FIELD 1978 #define ER_KILL_QUERY_DENIED_ERROR 1979 #define ER_NO_EIS_FOR_FIELD 1980 #define ER_WARN_AGGFUNC_DEPENDENCE 1981 #define WARN_INNODB_PARTITION_OPTION_IGNORED 1982 #define ER_ERROR_LAST_SECTION_2 1982 /* New section */ #define ER_ERROR_FIRST_SECTION_3 2000 #define ER_ERROR_LAST_SECTION_3 2000 /* New section */ #define ER_ERROR_FIRST_SECTION_4 3000 #define ER_FILE_CORRUPT 3000 #define ER_ERROR_ON_MASTER 3001 #define ER_INCONSISTENT_ERROR 3002 #define ER_STORAGE_ENGINE_NOT_LOADED 3003 #define ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER 3004 #define ER_WARN_LEGACY_SYNTAX_CONVERTED 3005 #define ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN 3006 #define ER_CANNOT_DISCARD_TEMPORARY_TABLE 3007 #define ER_FK_DEPTH_EXCEEDED 3008 #define ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 3009 #define ER_WARN_TRIGGER_DOESNT_HAVE_CREATED 3010 #define ER_REFERENCED_TRG_DOES_NOT_EXIST_MYSQL 3011 #define ER_EXPLAIN_NOT_SUPPORTED 3012 #define ER_INVALID_FIELD_SIZE 3013 #define ER_MISSING_HA_CREATE_OPTION 3014 #define ER_ENGINE_OUT_OF_MEMORY 3015 #define ER_PASSWORD_EXPIRE_ANONYMOUS_USER 3016 #define ER_SLAVE_SQL_THREAD_MUST_STOP 3017 #define ER_NO_FT_MATERIALIZED_SUBQUERY 3018 #define ER_INNODB_UNDO_LOG_FULL 3019 #define ER_INVALID_ARGUMENT_FOR_LOGARITHM 3020 #define ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP 3021 #define ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO 3022 #define ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS 3023 #define ER_UNUSED_1 3024 #define ER_NON_RO_SELECT_DISABLE_TIMER 3025 #define ER_DUP_LIST_ENTRY 3026 #define ER_SQL_MODE_NO_EFFECT 3027 #define ER_AGGREGATE_ORDER_FOR_UNION 3028 #define ER_AGGREGATE_ORDER_NON_AGG_QUERY 3029 #define ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR 3030 #define ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER 3031 #define ER_SERVER_OFFLINE_MODE 3032 #define ER_GIS_DIFFERENT_SRIDS 3033 #define ER_GIS_UNSUPPORTED_ARGUMENT 3034 #define ER_GIS_UNKNOWN_ERROR 3035 #define ER_GIS_UNKNOWN_EXCEPTION 3036 #define ER_GIS_INVALID_DATA 3037 #define ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION 3038 #define ER_BOOST_GEOMETRY_CENTROID_EXCEPTION 3039 #define ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION 3040 #define ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION 3041 #define ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION 3042 #define ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION 3043 #define ER_STD_BAD_ALLOC_ERROR 3044 #define ER_STD_DOMAIN_ERROR 3045 #define ER_STD_LENGTH_ERROR 3046 #define ER_STD_INVALID_ARGUMENT 3047 #define ER_STD_OUT_OF_RANGE_ERROR 3048 #define ER_STD_OVERFLOW_ERROR 3049 #define ER_STD_RANGE_ERROR 3050 #define ER_STD_UNDERFLOW_ERROR 3051 #define ER_STD_LOGIC_ERROR 3052 #define ER_STD_RUNTIME_ERROR 3053 #define ER_STD_UNKNOWN_EXCEPTION 3054 #define ER_GIS_DATA_WRONG_ENDIANESS 3055 #define ER_CHANGE_MASTER_PASSWORD_LENGTH 3056 #define ER_USER_LOCK_WRONG_NAME 3057 #define ER_USER_LOCK_DEADLOCK 3058 #define ER_REPLACE_INACCESSIBLE_ROWS 3059 #define ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS 3060 #define ER_ERROR_LAST_SECTION_4 3060 /* New section */ #define ER_ERROR_FIRST_SECTION_5 4000 #define ER_UNUSED_26 4000 #define ER_UNUSED_27 4001 #define ER_WITH_COL_WRONG_LIST 4002 #define ER_TOO_MANY_DEFINITIONS_IN_WITH_CLAUSE 4003 #define ER_DUP_QUERY_NAME 4004 #define ER_RECURSIVE_WITHOUT_ANCHORS 4005 #define ER_UNACCEPTABLE_MUTUAL_RECURSION 4006 #define ER_REF_TO_RECURSIVE_WITH_TABLE_IN_DERIVED 4007 #define ER_NOT_STANDARD_COMPLIANT_RECURSIVE 4008 #define ER_WRONG_WINDOW_SPEC_NAME 4009 #define ER_DUP_WINDOW_NAME 4010 #define ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC 4011 #define ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC 4012 #define ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC 4013 #define ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS 4014 #define ER_WRONG_PLACEMENT_OF_WINDOW_FUNCTION 4015 #define ER_WINDOW_FUNCTION_IN_WINDOW_SPEC 4016 #define ER_NOT_ALLOWED_WINDOW_FRAME 4017 #define ER_NO_ORDER_LIST_IN_WINDOW_SPEC 4018 #define ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY 4019 #define ER_WRONG_TYPE_FOR_ROWS_FRAME 4020 #define ER_WRONG_TYPE_FOR_RANGE_FRAME 4021 #define ER_FRAME_EXCLUSION_NOT_SUPPORTED 4022 #define ER_WINDOW_FUNCTION_DONT_HAVE_FRAME 4023 #define ER_INVALID_NTILE_ARGUMENT 4024 #define ER_CONSTRAINT_FAILED 4025 #define ER_EXPRESSION_IS_TOO_BIG 4026 #define ER_ERROR_EVALUATING_EXPRESSION 4027 #define ER_CALCULATING_DEFAULT_VALUE 4028 #define ER_EXPRESSION_REFERS_TO_UNINIT_FIELD 4029 #define ER_PARTITION_DEFAULT_ERROR 4030 #define ER_REFERENCED_TRG_DOES_NOT_EXIST 4031 #define ER_INVALID_DEFAULT_PARAM 4032 #define ER_BINLOG_NON_SUPPORTED_BULK 4033 #define ER_BINLOG_UNCOMPRESS_ERROR 4034 #define ER_JSON_BAD_CHR 4035 #define ER_JSON_NOT_JSON_CHR 4036 #define ER_JSON_EOS 4037 #define ER_JSON_SYNTAX 4038 #define ER_JSON_ESCAPING 4039 #define ER_JSON_DEPTH 4040 #define ER_JSON_PATH_EOS 4041 #define ER_JSON_PATH_SYNTAX 4042 #define ER_JSON_PATH_DEPTH 4043 #define ER_JSON_PATH_NO_WILDCARD 4044 #define ER_JSON_PATH_ARRAY 4045 #define ER_JSON_ONE_OR_ALL 4046 #define ER_UNSUPPORTED_COMPRESSED_TABLE 4047 #define ER_GEOJSON_INCORRECT 4048 #define ER_GEOJSON_TOO_FEW_POINTS 4049 #define ER_GEOJSON_NOT_CLOSED 4050 #define ER_JSON_PATH_EMPTY 4051 #define ER_SLAVE_SAME_ID 4052 #define ER_FLASHBACK_NOT_SUPPORTED 4053 #define ER_KEYS_OUT_OF_ORDER 4054 #define ER_OVERLAPPING_KEYS 4055 #define ER_REQUIRE_ROW_BINLOG_FORMAT 4056 #define ER_ISOLATION_MODE_NOT_SUPPORTED 4057 #define ER_ON_DUPLICATE_DISABLED 4058 #define ER_UPDATES_WITH_CONSISTENT_SNAPSHOT 4059 #define ER_ROLLBACK_ONLY 4060 #define ER_ROLLBACK_TO_SAVEPOINT 4061 #define ER_ISOLATION_LEVEL_WITH_CONSISTENT_SNAPSHOT 4062 #define ER_UNSUPPORTED_COLLATION 4063 #define ER_METADATA_INCONSISTENCY 4064 #define ER_CF_DIFFERENT 4065 #define ER_RDB_TTL_DURATION_FORMAT 4066 #define ER_RDB_STATUS_GENERAL 4067 #define ER_RDB_STATUS_MSG 4068 #define ER_RDB_TTL_UNSUPPORTED 4069 #define ER_RDB_TTL_COL_FORMAT 4070 #define ER_PER_INDEX_CF_DEPRECATED 4071 #define ER_KEY_CREATE_DURING_ALTER 4072 #define ER_SK_POPULATE_DURING_ALTER 4073 #define ER_SUM_FUNC_WITH_WINDOW_FUNC_AS_ARG 4074 #define ER_NET_OK_PACKET_TOO_LARGE 4075 #define ER_GEOJSON_EMPTY_COORDINATES 4076 #define ER_MYROCKS_CANT_NOPAD_COLLATION 4077 #define ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION 4078 #define ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION 4079 #define ER_WRONG_PARAMCOUNT_TO_CURSOR 4080 #define ER_UNKNOWN_STRUCTURED_VARIABLE 4081 #define ER_ROW_VARIABLE_DOES_NOT_HAVE_FIELD 4082 #define ER_END_IDENTIFIER_DOES_NOT_MATCH 4083 #define ER_SEQUENCE_RUN_OUT 4084 #define ER_SEQUENCE_INVALID_DATA 4085 #define ER_SEQUENCE_INVALID_TABLE_STRUCTURE 4086 #define ER_SEQUENCE_ACCESS_ERROR 4087 #define ER_SEQUENCE_BINLOG_FORMAT 4088 #define ER_NOT_SEQUENCE 4089 #define ER_NOT_SEQUENCE2 4090 #define ER_UNKNOWN_SEQUENCES 4091 #define ER_UNKNOWN_VIEW 4092 #define ER_WRONG_INSERT_INTO_SEQUENCE 4093 #define ER_SP_STACK_TRACE 4094 #define ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY 4095 #define ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED 4096 #define ER_COMPRESSED_COLUMN_USED_AS_KEY 4097 #define ER_UNKNOWN_COMPRESSION_METHOD 4098 #define ER_WRONG_NUMBER_OF_VALUES_IN_TVC 4099 #define ER_FIELD_REFERENCE_IN_TVC 4100 #define ER_WRONG_TYPE_FOR_PERCENTILE_FUNC 4101 #define ER_ARGUMENT_NOT_CONSTANT 4102 #define ER_ARGUMENT_OUT_OF_RANGE 4103 #define ER_WRONG_TYPE_OF_ARGUMENT 4104 #define ER_NOT_AGGREGATE_FUNCTION 4105 #define ER_INVALID_AGGREGATE_FUNCTION 4106 #define ER_INVALID_VALUE_TO_LIMIT 4107 #define ER_INVISIBLE_NOT_NULL_WITHOUT_DEFAULT 4108 #define ER_UPDATE_INFO_WITH_SYSTEM_VERSIONING 4109 #define ER_VERS_FIELD_WRONG_TYPE 4110 #define ER_VERS_ENGINE_UNSUPPORTED 4111 #define ER_UNUSED_23 4112 #define ER_PARTITION_WRONG_TYPE 4113 #define WARN_VERS_PART_FULL 4114 #define WARN_VERS_PARAMETERS 4115 #define ER_VERS_DROP_PARTITION_INTERVAL 4116 #define ER_UNUSED_25 4117 #define WARN_VERS_PART_NON_HISTORICAL 4118 #define ER_VERS_ALTER_NOT_ALLOWED 4119 #define ER_VERS_ALTER_ENGINE_PROHIBITED 4120 #define ER_VERS_RANGE_PROHIBITED 4121 #define ER_CONFLICTING_FOR_SYSTEM_TIME 4122 #define ER_VERS_TABLE_MUST_HAVE_COLUMNS 4123 #define ER_VERS_NOT_VERSIONED 4124 #define ER_MISSING 4125 #define ER_VERS_PERIOD_COLUMNS 4126 #define ER_PART_WRONG_VALUE 4127 #define ER_VERS_WRONG_PARTS 4128 #define ER_VERS_NO_TRX_ID 4129 #define ER_VERS_ALTER_SYSTEM_FIELD 4130 #define ER_DROP_VERSIONING_SYSTEM_TIME_PARTITION 4131 #define ER_VERS_DB_NOT_SUPPORTED 4132 #define ER_VERS_TRT_IS_DISABLED 4133 #define ER_VERS_DUPLICATE_ROW_START_END 4134 #define ER_VERS_ALREADY_VERSIONED 4135 #define ER_UNUSED_24 4136 #define ER_VERS_NOT_SUPPORTED 4137 #define ER_VERS_TRX_PART_HISTORIC_ROW_NOT_SUPPORTED 4138 #define ER_INDEX_FILE_FULL 4139 #define ER_UPDATED_COLUMN_ONLY_ONCE 4140 #define ER_EMPTY_ROW_IN_TVC 4141 #define ER_VERS_QUERY_IN_PARTITION 4142 #define ER_KEY_DOESNT_SUPPORT 4143 #define ER_ALTER_OPERATION_TABLE_OPTIONS_NEED_REBUILD 4144 #define ER_BACKUP_LOCK_IS_ACTIVE 4145 #define ER_BACKUP_NOT_RUNNING 4146 #define ER_BACKUP_WRONG_STAGE 4147 #define ER_BACKUP_STAGE_FAILED 4148 #define ER_BACKUP_UNKNOWN_STAGE 4149 #define ER_USER_IS_BLOCKED 4150 #define ER_ACCOUNT_HAS_BEEN_LOCKED 4151 #define ER_PERIOD_TEMPORARY_NOT_ALLOWED 4152 #define ER_PERIOD_TYPES_MISMATCH 4153 #define ER_MORE_THAN_ONE_PERIOD 4154 #define ER_PERIOD_FIELD_WRONG_ATTRIBUTES 4155 #define ER_PERIOD_NOT_FOUND 4156 #define ER_PERIOD_COLUMNS_UPDATED 4157 #define ER_PERIOD_CONSTRAINT_DROP 4158 #define ER_TOO_LONG_KEYPART 4159 #define ER_TOO_LONG_DATABASE_COMMENT 4160 #define ER_UNKNOWN_DATA_TYPE 4161 #define ER_UNKNOWN_OPERATOR 4162 #define ER_WARN_HISTORY_ROW_START_TIME 4163 #define ER_PART_STARTS_BEYOND_INTERVAL 4164 #define ER_GALERA_REPLICATION_NOT_SUPPORTED 4165 #define ER_LOAD_INFILE_CAPABILITY_DISABLED 4166 #define ER_NO_SECURE_TRANSPORTS_CONFIGURED 4167 #define ER_SLAVE_IGNORED_SHARED_TABLE 4168 #define ER_NO_AUTOINCREMENT_WITH_UNIQUE 4169 #define ER_KEY_CONTAINS_PERIOD_FIELDS 4170 #define ER_KEY_CANT_HAVE_WITHOUT_OVERLAPS 4171 #define ER_NOT_ALLOWED_IN_THIS_CONTEXT 4172 #define ER_DATA_WAS_COMMITED_UNDER_ROLLBACK 4173 #define ER_PK_INDEX_CANT_BE_IGNORED 4174 #define ER_BINLOG_UNSAFE_SKIP_LOCKED 4175 #define ER_JSON_TABLE_ERROR_ON_FIELD 4176 #define ER_JSON_TABLE_ALIAS_REQUIRED 4177 #define ER_JSON_TABLE_SCALAR_EXPECTED 4178 #define ER_JSON_TABLE_MULTIPLE_MATCHES 4179 #define ER_WITH_TIES_NEEDS_ORDER 4180 #define ER_REMOVED_ORPHAN_TRIGGER 4181 #define ER_STORAGE_ENGINE_DISABLED 4182 #define ER_ERROR_LAST 4182 #endif /* ER_ERROR_FIRST */ mysql/server/json_lib.h000064400000032713151027430560011200 0ustar00#ifndef JSON_LIB_INCLUDED #define JSON_LIB_INCLUDED #ifdef __cplusplus extern "C" { #endif #define JSON_DEPTH_LIMIT 32 /* When error happens, the c_next of the JSON engine contains the character that caused the error, and the c_str is the position in string where the error occurs. */ enum json_errors { JE_BAD_CHR= -1, /* Invalid character, charset handler cannot read it. */ JE_NOT_JSON_CHR= -2, /* Character met not used in JSON. */ /* ASCII 00-08 for instance. */ JE_EOS= -3, /* Unexpected end of string. */ JE_SYN= -4, /* The next character breaks the JSON syntax. */ JE_STRING_CONST= -5, /* Character disallowed in string constant. */ JE_ESCAPING= -6, /* Error in the escaping. */ JE_DEPTH= -7, /* The limit on the JSON depth was overrun. */ }; typedef struct st_json_string_t { const uchar *c_str; /* Current position in JSON string */ const uchar *str_end; /* The end on the string. */ my_wc_t c_next; /* UNICODE of the last read character */ int c_next_len; /* character lenght of the last read character. */ int error; /* error code. */ CHARSET_INFO *cs; /* Character set of the JSON string. */ my_charset_conv_mb_wc wc; /* UNICODE conversion function. */ /* It's taken out of the cs just to speed calls. */ } json_string_t; void json_string_set_cs(json_string_t *s, CHARSET_INFO *i_cs); void json_string_set_str(json_string_t *s, const uchar *str, const uchar *end); #define json_next_char(j) \ ((j)->c_next_len= (j)->wc((j)->cs, &(j)->c_next, (j)->c_str, (j)->str_end)) #define json_eos(j) ((j)->c_str >= (j)->str_end) /* read_string_const_chr() reads the next character of the string constant and saves it to the js->c_next. It takes into account possible escapings, so if for instance the string is '\b', the read_string_const_chr() sets 8. */ int json_read_string_const_chr(json_string_t *js); /* Various JSON-related operations expect JSON path as a parameter. The path is a string like this "$.keyA[2].*" The path itself is a number of steps specifying either a key or a position in an array. Some of them can be wildcards. So the representation of the JSON path is the json_path_t class containing an array of json_path_step_t objects. */ /* Path step types - actually bitmasks to let '&' or '|' operations. */ enum json_path_step_types { JSON_PATH_KEY_NULL=0, JSON_PATH_KEY=1, /* Must be equal to JSON_VALUE_OBJECT. */ JSON_PATH_ARRAY=2, /* Must be equal to JSON_VALUE_ARRAY. */ JSON_PATH_KEY_OR_ARRAY=3, JSON_PATH_WILD=4, /* Step like .* or [*] */ JSON_PATH_DOUBLE_WILD=8, /* Step like **.k or **[1] */ JSON_PATH_KEY_WILD= 1+4, JSON_PATH_KEY_DOUBLEWILD= 1+8, JSON_PATH_ARRAY_WILD= 2+4, JSON_PATH_ARRAY_DOUBLEWILD= 2+8 }; typedef struct st_json_path_step_t { enum json_path_step_types type; /* The type of the step - */ /* see json_path_step_types */ const uchar *key; /* Pointer to the beginning of the key. */ const uchar *key_end; /* Pointer to the end of the key. */ uint n_item; /* Item number in an array. No meaning for the key step. */ } json_path_step_t; typedef struct st_json_path_t { json_string_t s; /* The string to be parsed. */ json_path_step_t steps[JSON_DEPTH_LIMIT]; /* Steps of the path. */ json_path_step_t *last_step; /* Points to the last step. */ int mode_strict; /* TRUE if the path specified as 'strict' */ enum json_path_step_types types_used; /* The '|' of all step's 'type'-s */ } json_path_t; int json_path_setup(json_path_t *p, CHARSET_INFO *i_cs, const uchar *str, const uchar *end); /* The set of functions and structures below provides interface to the JSON text parser. Running the parser normally goes like this: json_engine_t j_eng; // structure keeps parser's data json_scan_start(j_eng) // begin the parsing do { // The parser has read next piece of JSON // and set fields of j_eng structure accordingly. // So let's see what we have: switch (j_eng.state) { case JST_KEY: // Handle key name. See the json_read_keyname_chr() // Probably compare it with the keyname we're looking for case JST_VALUE: // Handle value. It is either value of the key or an array item. // see the json_read_value() case JST_OBJ_START: // parser found an object (the '{' in JSON) case JST_OBJ_END: // parser found the end of the object (the '}' in JSON) case JST_ARRAY_START: // parser found an array (the '[' in JSON) case JST_ARRAY_END: // parser found the end of the array (the ']' in JSON) }; } while (json_scan_next() == 0); // parse next structure if (j_eng.s.error) // we need to check why the loop ended. // Did we get to the end of JSON, or came upon error. { signal_error_in_JSON() } Parts of JSON can be quickly skipped. If we are not interested in a particular key, we can just skip it with json_skip_key() call. Similarly json_skip_level() goes right to the end of an object or an array. */ /* These are JSON parser states that user can expect and handle. */ enum json_states { JST_VALUE, /* value found */ JST_KEY, /* key found */ JST_OBJ_START, /* object */ JST_OBJ_END, /* object ended */ JST_ARRAY_START, /* array */ JST_ARRAY_END, /* array ended */ NR_JSON_USER_STATES }; enum json_value_types { JSON_VALUE_UNINITALIZED=0, JSON_VALUE_OBJECT=1, JSON_VALUE_ARRAY=2, JSON_VALUE_STRING=3, JSON_VALUE_NUMBER=4, JSON_VALUE_TRUE=5, JSON_VALUE_FALSE=6, JSON_VALUE_NULL=7 }; enum json_num_flags { JSON_NUM_NEG=1, /* Number is negative. */ JSON_NUM_FRAC_PART=2, /* The fractional part is not empty. */ JSON_NUM_EXP=4, /* The number has the 'e' part. */ }; typedef struct st_json_engine_t { json_string_t s; /* String to parse. */ int sav_c_len; /* Length of the current character. Can be more than 1 for multibyte charsets */ int state; /* The state of the parser. One of 'enum json_states'. It tells us what construction of JSON we've just read. */ /* These values are only set after the json_read_value() call. */ enum json_value_types value_type; /* type of the value.*/ const uchar *value; /* Points to the value. */ const uchar *value_begin;/* Points to where the value starts in the JSON. */ int value_escaped; /* Flag telling if the string value has escaping.*/ uint num_flags; /* the details of the JSON_VALUE_NUMBER, is it negative, or if it has the fractional part. See the enum json_num_flags. */ /* In most cases the 'value' and 'value_begin' are equal. They only differ if the value is a string constants. Then 'value_begin' points to the starting quotation mark, while the 'value' - to the first character of the string. */ const uchar *value_end; /* Points to the next character after the value. */ int value_len; /* The length of the value. Does not count quotations for */ /* string constants. */ int stack[JSON_DEPTH_LIMIT]; /* Keeps the stack of nested JSON structures. */ int stack_p; /* The 'stack' pointer. */ volatile uchar *killed_ptr; } json_engine_t; int json_scan_start(json_engine_t *je, CHARSET_INFO *i_cs, const uchar *str, const uchar *end); int json_scan_next(json_engine_t *j); /* json_read_keyname_chr() function assists parsing the name of an JSON key. It only can be called when the json_engine is in JST_KEY. The json_read_keyname_chr() reads one character of the name of the key, and puts it in j_eng.s.next_c. Typical usage is like this: if (j_eng.state == JST_KEY) { while (json_read_keyname_chr(&j) == 0) { //handle next character i.e. match it against the pattern } } */ int json_read_keyname_chr(json_engine_t *j); /* Check if the name of the current JSON key matches the step of the path. */ int json_key_matches(json_engine_t *je, json_string_t *k); /* json_read_value() function parses the JSON value syntax, so that we can handle the value of a key or an array item. It only returns meaningful result when the engine is in the JST_VALUE state. Typical usage is like this: if (j_eng.state == JST_VALUE) { json_read_value(&j_eng); switch(j_eng.value_type) { case JSON_VALUE_STRING: // get the string str= j_eng.value; str_length= j_eng.value_len; case JSON_VALUE_NUMBER: // get the number ... etc } */ int json_read_value(json_engine_t *j); /* json_skip_key() makes parser skip the content of the current JSON key quickly. It can be called only when the json_engine state is JST_KEY. Typical usage is: if (j_eng.state == JST_KEY) { if (key_does_not_match(j_eng)) json_skip_key(j_eng); } */ int json_skip_key(json_engine_t *j); typedef const int *json_level_t; /* json_skip_to_level() makes parser quickly get out of nested loops and arrays. It is used when we're not interested in what is there in the rest of these structures. The 'level' should be remembered in advance. json_level_t level= json_get_level(j); .... // getting into the nested JSON structures json_skip_to_level(j, level); */ #define json_get_level(j) (j->stack_p) int json_skip_to_level(json_engine_t *j, int level); /* json_skip_level() works as above with just current structure. So it gets to the end of the current JSON array or object. */ #define json_skip_level(json_engine) \ json_skip_to_level((json_engine), (json_engine)->stack_p) /* works as json_skip_level() but also counts items on the current level skipped. */ int json_skip_level_and_count(json_engine_t *j, int *n_items_skipped); #define json_skip_array_item json_skip_key /* Checks if the current value is of scalar type - not an OBJECT nor ARRAY. */ #define json_value_scalar(je) ((je)->value_type > JSON_VALUE_ARRAY) /* Look for the JSON PATH in the json string. Function can be called several times with same JSON/PATH to find multiple matches. On the first call, the json_engine_t parameter should be initialized with the JSON string, and the json_path_t with the JSON path appropriately. The 'p_cur_step' should point at the first step of the path. The 'array_counters' is the array of JSON_DEPTH_LIMIT size. It stores the array counters of the parsed JSON. If function returns 0, it means it found the match. The position of the match is je->s.c_str. Then we can call the json_find_path() with same engine/path/p_cur_step to get the next match. Non-zero return means no matches found. Check je->s.error to see if there was an error in JSON. */ int json_find_path(json_engine_t *je, json_path_t *p, json_path_step_t **p_cur_step, uint *array_counters); typedef struct st_json_find_paths_t { uint n_paths; json_path_t *paths; uint cur_depth; uint *path_depths; uint array_counters[JSON_DEPTH_LIMIT]; } json_find_paths_t; int json_find_paths_first(json_engine_t *je, json_find_paths_t *state, uint n_paths, json_path_t *paths, uint *path_depths); int json_find_paths_next(json_engine_t *je, json_find_paths_t *state); /* Convert JSON string constant into ordinary string constant which can involve unpacking json escapes and changing character set. Returns negative integer in the case of an error, the length of the result otherwise. */ int json_unescape(CHARSET_INFO *json_cs, const uchar *json_str, const uchar *json_end, CHARSET_INFO *res_cs, uchar *res, uchar *res_end); /* Convert ordinary string constant into JSON string constant. which can involve appropriate escaping and changing character set. Returns negative integer in the case of an error, the length of the result otherwise. */ int json_escape(CHARSET_INFO *str_cs, const uchar *str, const uchar *str_end, CHARSET_INFO *json_cs, uchar *json, uchar *json_end); /* Appends the ASCII string to the json with the charset conversion. */ int json_append_ascii(CHARSET_INFO *json_cs, uchar *json, uchar *json_end, const uchar *ascii, const uchar *ascii_end); /* Scan the JSON and return paths met one-by-one. json_get_path_start(&p) while (json_get_path_next(&p)) { handle_the_next_path(); } */ int json_get_path_start(json_engine_t *je, CHARSET_INFO *i_cs, const uchar *str, const uchar *end, json_path_t *p); int json_get_path_next(json_engine_t *je, json_path_t *p); int json_path_parts_compare( const json_path_step_t *a, const json_path_step_t *a_end, const json_path_step_t *b, const json_path_step_t *b_end, enum json_value_types vt); int json_path_compare(const json_path_t *a, const json_path_t *b, enum json_value_types vt); int json_valid(const char *js, size_t js_len, CHARSET_INFO *cs); int json_locate_key(const char *js, const char *js_end, const char *kname, const char **key_start, const char **key_end, int *comma_pos); #ifdef __cplusplus } #endif #endif /* JSON_LIB_INCLUDED */ mysql/server/m_string.h000064400000024112151027430560011215 0ustar00/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2019, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* There may be problems included in all of these. Try to test in configure which ones are needed? */ /* This is needed for the definitions of strchr... on solaris */ #ifndef _m_string_h #define _m_string_h #include "my_decimal_limits.h" #ifndef __USE_GNU #define __USE_GNU /* We want to use stpcpy */ #endif #if defined(HAVE_STRINGS_H) #include #endif #if defined(HAVE_STRING_H) #include #endif /* This is needed for the definitions of memcpy... on solaris */ #if defined(HAVE_MEMORY_H) && !defined(__cplusplus) #include #endif #if !defined(HAVE_MEMCPY) && !defined(HAVE_MEMMOVE) # define memcpy(d, s, n) bcopy ((s), (d), (n)) # define memset(A,C,B) bfill((A),(B),(C)) # define memmove(d, s, n) bmove ((d), (s), (n)) #elif defined(HAVE_MEMMOVE) # define bmove(d, s, n) memmove((d), (s), (n)) #endif /* Unixware 7 */ #if !defined(HAVE_BFILL) # define bfill(A,B,C) memset((A),(C),(B)) #endif # define bmove_align(A,B,C) memcpy((A),(B),(C)) # define bcmp(A,B,C) memcmp((A),(B),(C)) #if !defined(bzero) # define bzero(A,B) memset((A),0,(B)) #endif #if defined(__cplusplus) extern "C" { #endif #ifdef DBUG_OFF #if defined(HAVE_STPCPY) && defined(__GNUC__) && !defined(__INTEL_COMPILER) #define strmov(A,B) __builtin_stpcpy((A),(B)) #elif defined(HAVE_STPCPY) #define strmov(A,B) stpcpy((A),(B)) #endif #endif /* Declared in int2str() */ extern const char _dig_vec_upper[]; extern const char _dig_vec_lower[]; extern char *strmov_overlapp(char *dest, const char *src); #if defined(_lint) || defined(FORCE_INIT_OF_VARS) #define LINT_INIT_STRUCT(var) bzero(&var, sizeof(var)) /* No uninitialize-warning */ #else #define LINT_INIT_STRUCT(var) #endif /* Prototypes for string functions */ extern void bmove_upp(uchar *dst,const uchar *src,size_t len); extern void bchange(uchar *dst,size_t old_len,const uchar *src, size_t new_len,size_t tot_len); extern void strappend(char *s,size_t len,pchar fill); extern char *strend(const char *s); extern char *strcend(const char *, pchar); extern char *strfill(char * s,size_t len,pchar fill); extern char *strmake(char *dst,const char *src,size_t length); #if !defined(__GNUC__) || (__GNUC__ < 4) #define strmake_buf(D,S) strmake(D, S, sizeof(D) - 1) #else #define strmake_buf(D,S) ({ \ __typeof__ (D) __x __attribute__((unused)) = { 2 }; \ strmake(D, S, sizeof(D) - 1); \ }) #endif #ifndef strmov extern char *strmov(char *dst,const char *src); #endif extern char *strnmov(char *dst, const char *src, size_t n); extern char *strcont(const char *src, const char *set); extern char *strxmov(char *dst, const char *src, ...); extern char *strxnmov(char *dst, size_t len, const char *src, ...); /* Prototypes of normal stringfunctions (with may ours) */ #ifndef HAVE_STRNLEN extern size_t strnlen(const char *s, size_t n); #endif extern int is_prefix(const char *, const char *); /* Conversion routines */ typedef enum { MY_GCVT_ARG_FLOAT, MY_GCVT_ARG_DOUBLE } my_gcvt_arg_type; double my_strtod(const char *str, char **end, int *error); double my_atof(const char *nptr); size_t my_fcvt(double x, int precision, char *to, my_bool *error); size_t my_gcvt(double x, my_gcvt_arg_type type, int width, char *to, my_bool *error); /* The longest string my_fcvt can return is 311 + "precision" bytes. Here we assume that we never cal my_fcvt() with precision >= DECIMAL_NOT_SPECIFIED (+ 1 byte for the terminating '\0'). */ #define FLOATING_POINT_BUFFER (311 + DECIMAL_NOT_SPECIFIED) /* We want to use the 'e' format in some cases even if we have enough space for the 'f' one just to mimic sprintf("%.15g") behavior for large integers, and to improve it for numbers < 10^(-4). That is, for |x| < 1 we require |x| >= 10^(-15), and for |x| > 1 we require it to be integer and be <= 10^DBL_DIG for the 'f' format to be used. We don't lose precision, but make cases like "1e200" or "0.00001" look nicer. */ #define MAX_DECPT_FOR_F_FORMAT DBL_DIG /* The maximum possible field width for my_gcvt() conversion. (DBL_DIG + 2) significant digits + sign + "." + ("e-NNN" or MAX_DECPT_FOR_F_FORMAT zeros for cases when |x|<1 and the 'f' format is used). */ #define MY_GCVT_MAX_FIELD_WIDTH (DBL_DIG + 4 + MY_MAX(5, MAX_DECPT_FOR_F_FORMAT)) \ extern char *llstr(longlong value,char *buff); extern char *ullstr(longlong value,char *buff); #ifndef HAVE_STRTOUL extern long strtol(const char *str, char **ptr, int base); extern ulong strtoul(const char *str, char **ptr, int base); #endif extern char *int2str(long val, char *dst, int radix, int upcase); extern char *int10_to_str(long val,char *dst,int radix); extern char *str2int(const char *src,int radix,long lower,long upper, long *val); longlong my_strtoll10(const char *nptr, char **endptr, int *error); #if SIZEOF_LONG == SIZEOF_LONG_LONG #define ll2str(A,B,C,D) int2str((A),(B),(C),(D)) #define longlong10_to_str(A,B,C) int10_to_str((A),(B),(C)) #undef strtoll #define strtoll(A,B,C) strtol((A),(B),(C)) #define strtoull(A,B,C) strtoul((A),(B),(C)) #ifndef HAVE_STRTOULL #define HAVE_STRTOULL #endif #ifndef HAVE_STRTOLL #define HAVE_STRTOLL #endif #else #ifdef HAVE_LONG_LONG extern char *ll2str(longlong val,char *dst,int radix, int upcase); extern char *longlong10_to_str(longlong val,char *dst,int radix); #if (!defined(HAVE_STRTOULL) || defined(NO_STRTOLL_PROTO)) extern longlong strtoll(const char *str, char **ptr, int base); extern ulonglong strtoull(const char *str, char **ptr, int base); #endif #endif #endif #define longlong2str(A,B,C) ll2str((A),(B),(C),1) #if defined(__cplusplus) } #endif #include #ifdef __cplusplus #include template inline const char *_swl_check(T s) { static_assert(std::is_same::value || std::is_same::value, "Wrong argument for STRING_WITH_LEN()"); return s; } #define STRING_WITH_LEN(X) _swl_check(X), ((size_t) (sizeof(X) - 1)) #else #define STRING_WITH_LEN(X) (X ""), ((size_t) (sizeof(X) - 1)) #endif #define USTRING_WITH_LEN(X) (uchar*) STRING_WITH_LEN(X) #define C_STRING_WITH_LEN(X) (char *) STRING_WITH_LEN(X) #define LEX_STRING_WITH_LEN(X) (X).str, (X).length typedef struct st_mysql_const_lex_string LEX_CSTRING; /* A variant with const and unsigned */ struct st_mysql_const_unsigned_lex_string { const uchar *str; size_t length; }; typedef struct st_mysql_const_unsigned_lex_string LEX_CUSTRING; static inline void lex_string_set(LEX_CSTRING *lex_str, const char *c_str) { lex_str->str= c_str; lex_str->length= strlen(c_str); } static inline void lex_string_set3(LEX_CSTRING *lex_str, const char *c_str, size_t len) { lex_str->str= c_str; lex_str->length= len; } /** Copies a string. @param dst destination buffer, will be NUL padded. @param dst_size size of dst buffer, must be > 0 @param src NUL terminated source string */ static inline void safe_strcpy(char *dst, size_t dst_size, const char *src) { DBUG_ASSERT(dst_size > 0); /* 1) IF there is a 0 byte in the first dst_size bytes of src, strncpy will * 0-terminate dst, and pad dst with additional 0 bytes out to dst_size. * * 2) IF there is no 0 byte in the first dst_size bytes of src, strncpy will * copy dst_size bytes, and the final byte won't be 0. * * In GCC 8+, the `-Wstringop-truncation` warning may object to strncpy() * being used in this way, so we need to disable this warning for this * single statement. */ #if defined __GNUC__ && __GNUC__ >= 8 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstringop-truncation" #endif strncpy(dst, src, dst_size); #if defined __GNUC__ && __GNUC__ >= 8 #pragma GCC diagnostic pop #endif dst[dst_size - 1]= 0; } /** Copies a string, checking for truncation. @param dst destination buffer, will be NUL padded. @param dst_size size of dst buffer, must be > 0 @param src NUL terminated source string @retval 1 if the src string was truncated due to too small size of dst. @retval 0 if src completely fit within dst, */ static inline int safe_strcpy_truncated(char *dst, size_t dst_size, const char *src) { DBUG_ASSERT(dst_size > 0); if (dst_size == 0) return 1; /* We do not want to use strncpy() as we do not want to rely on strncpy() filling the unused dst with 0. We cannot use strmake() here as it in debug mode fills the buffers with 'Z'. */ if (strnmov(dst, src, dst_size) == dst+dst_size) { dst[dst_size-1]= 0; return 1; } return 0; } /** Appends src to dst and ensures dst is a NUL terminated C string. @retval 1 if the src string was truncated due to too small size of dst. @retval 0 if src completely fit within the remaining dst space, including NUL termination. */ static inline int safe_strcat(char *dst, size_t dst_size, const char *src) { size_t init_len= strlen(dst); if (init_len >= dst_size) return 1; return safe_strcpy_truncated(dst + init_len, dst_size - init_len, src); } #ifdef __cplusplus static inline char *safe_str(char *str) { return str ? str : const_cast(""); } #endif static inline const char *safe_str(const char *str) { return str ? str : ""; } static inline size_t safe_strlen(const char *str) { return str ? strlen(str) : 0; } #endif mysql/server/my_decimal_limits.h000064400000004032151027430560013056 0ustar00#ifndef MY_DECIMAL_LIMITS_INCLUDED #define MY_DECIMAL_LIMITS_INCLUDED /* Copyright (c) 2011 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #define DECIMAL_LONGLONG_DIGITS 22 #define DECIMAL_LONG_DIGITS 10 #define DECIMAL_LONG3_DIGITS 8 /** maximum length of buffer in our big digits (uint32). */ #define DECIMAL_BUFF_LENGTH 9 /* the number of digits that my_decimal can possibly contain */ #define DECIMAL_MAX_POSSIBLE_PRECISION (DECIMAL_BUFF_LENGTH * 9) /** maximum guaranteed precision of number in decimal digits (number of our digits * number of decimal digits in one our big digit - number of decimal digits in one our big digit decreased by 1 (because we always put decimal point on the border of our big digits)) With normal precision we can handle 65 digits. MariaDB can store in the .frm up to 63 digits. By default we use DECIMAL_NOT_SPECIFIED digits when converting strings to decimal, so we don't want to set this too high. To not use up all digits for the scale we limit the number of decimals to 38. */ #define DECIMAL_MAX_PRECISION (DECIMAL_MAX_POSSIBLE_PRECISION - 8*2) #define DECIMAL_MAX_SCALE 38 #define DECIMAL_NOT_SPECIFIED 39 /** maximum length of string representation (number of maximum decimal digits + 1 position for sign + 1 position for decimal point, no terminator) */ #define DECIMAL_MAX_STR_LENGTH (DECIMAL_MAX_POSSIBLE_PRECISION + 2) #endif /* MY_DECIMAL_LIMITS_INCLUDED */ mysql/server/pack.h000064400000002121151027430560010305 0ustar00/* Copyright (c) 2016, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef __cplusplus extern "C" { #endif ulong net_field_length(uchar **packet); my_ulonglong net_field_length_ll(uchar **packet); my_ulonglong safe_net_field_length_ll(uchar **packet, size_t packet_len); uchar *net_store_length(uchar *pkg, ulonglong length); uchar *safe_net_store_length(uchar *pkg, size_t pkg_len, ulonglong length); unsigned int net_length_size(ulonglong num); #ifdef __cplusplus } #endif mysql/server/mariadb_capi_rename.h000064400000006532151027430560013323 0ustar00/* Copyright (c) 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Renaming C API symbols inside server * client.c defines a number of functions from the C API, that are used in replication, in number of storage engine plugins, mariadb-backup. * That can cause a problem if a plugin loads libmariadb/libmysql or a library, that has dependency on them. The known case is ODBC driver. * Thus the header re-names those functions for internal use. */ #ifndef MARIADB_CAPI_RENAME_INCLUDED #define MARIADB_CAPI_RENAME_INCLUDED #if !defined(EMBEDDED_LIBRARY) && !defined(MYSQL_DYNAMIC_PLUGIN) #define MARIADB_ADD_PREFIX(_SYMBOL) server_##_SYMBOL #define mysql_real_connect MARIADB_ADD_PREFIX(mysql_real_connect) #define mysql_init MARIADB_ADD_PREFIX(mysql_init) #define mysql_close MARIADB_ADD_PREFIX(mysql_close) #define mysql_options MARIADB_ADD_PREFIX(mysql_options) #define mysql_load_plugin MARIADB_ADD_PREFIX(mysql_load_plugin) #define mysql_load_plugin_v MARIADB_ADD_PREFIX(mysql_load_plugin_v) #define mysql_client_find_plugin MARIADB_ADD_PREFIX(mysql_client_find_plugin) #define mysql_real_query MARIADB_ADD_PREFIX(mysql_real_query) #define mysql_send_query MARIADB_ADD_PREFIX(mysql_send_query) #define mysql_free_result MARIADB_ADD_PREFIX(mysql_free_result) #define mysql_get_socket MARIADB_ADD_PREFIX(mysql_get_socket) #define mysql_set_character_set MARIADB_ADD_PREFIX(mysql_set_character_set) #define mysql_real_escape_string MARIADB_ADD_PREFIX(mysql_real_escape_string) #define mysql_get_server_version MARIADB_ADD_PREFIX(mysql_get_server_version) #define mysql_error MARIADB_ADD_PREFIX(mysql_error) #define mysql_errno MARIADB_ADD_PREFIX(mysql_errno) #define mysql_num_fields MARIADB_ADD_PREFIX(mysql_num_fields) #define mysql_num_rows MARIADB_ADD_PREFIX(mysql_num_rows) #define mysql_options4 MARIADB_ADD_PREFIX(mysql_options4) #define mysql_fetch_fields MARIADB_ADD_PREFIX(mysql_fetch_fields) #define mysql_fetch_lengths MARIADB_ADD_PREFIX(mysql_fetch_lengths) #define mysql_fetch_row MARIADB_ADD_PREFIX(mysql_fetch_row) #define mysql_affected_rows MARIADB_ADD_PREFIX(mysql_affected_rows) #define mysql_store_result MARIADB_ADD_PREFIX(mysql_store_result) #define mysql_use_result MARIADB_ADD_PREFIX(mysql_use_result) #define mysql_select_db MARIADB_ADD_PREFIX(mysql_select_db) #define mysql_get_ssl_cipher MARIADB_ADD_PREFIX(mysql_get_ssl_cipher) #define mysql_ssl_set MARIADB_ADD_PREFIX(mysql_ssl_set) #define mysql_client_register_plugin MARIADB_ADD_PREFIX(mysql_client_register_plugin) #endif // !EMBEDDED_LIBRARY && !MYSQL_DYNAMIC_PLUGIN #endif // !MARIADB_CAPI_RENAME_INCLUDED mysql/server/my_attribute.h000064400000006772151027430560012117 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Helper macros used for setting different __attributes__ on functions in a portable fashion */ #ifndef _my_attribute_h #define _my_attribute_h #if defined(__GNUC__) # ifndef GCC_VERSION # define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) # endif #endif /* Disable __attribute__() on gcc < 2.7, g++ < 3.4, and non-gcc compilers. Some forms of __attribute__ are actually supported in earlier versions of g++, but we just disable them all because we only use them to generate compilation warnings. */ #ifndef __attribute__ # if !defined(__GNUC__) && !defined(__clang__) # define __attribute__(A) # elif defined(__GNUC__) # ifndef GCC_VERSION # define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) # endif # if GCC_VERSION < 2008 # define __attribute__(A) # elif defined(__cplusplus) && GCC_VERSION < 3004 # define __attribute__(A) # endif # endif #endif /* __attribute__((format(...))) is only supported in gcc >= 2.8 and g++ >= 3.4 But that's already covered by the __attribute__ tests above, so this is just a convenience macro. */ #ifndef ATTRIBUTE_FORMAT # define ATTRIBUTE_FORMAT(style, m, n) __attribute__((format(style, m, n))) #endif /* __attribute__((format(...))) on a function pointer is not supported until gcc 3.1 */ #ifndef ATTRIBUTE_FORMAT_FPTR # if (GCC_VERSION >= 3001) # define ATTRIBUTE_FORMAT_FPTR(style, m, n) ATTRIBUTE_FORMAT(style, m, n) # else # define ATTRIBUTE_FORMAT_FPTR(style, m, n) # endif /* GNUC >= 3.1 */ #endif /* gcc 7.5.0 does not support __attribute__((no_sanitize("undefined")) */ #ifndef ATTRIBUTE_NO_UBSAN # if (GCC_VERSION >= 8000) || defined(__clang__) # define ATTRIBUTE_NO_UBSAN __attribute__((no_sanitize("undefined"))) # elif (GCC_VERSION >= 6001) # define ATTRIBUTE_NO_UBSAN __attribute__((no_sanitize_undefined)) # else # define ATTRIBUTE_NO_UBSAN # endif #endif /* Define pragmas to disable warnings for stack frame checking */ #ifdef __GNUC__ #define PRAGMA_DISABLE_CHECK_STACK_FRAME \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wframe-larger-than=\"") #define PRAGMA_REENABLE_CHECK_STACK_FRAME \ _Pragma("GCC diagnostic pop") /* The following check is for older gcc version that allocates a lot of stack during startup that does not need to be checked */ #if !defined(__clang__) && __GNUC__ < 13 #define PRAGMA_DISABLE_CHECK_STACK_FRAME_EXTRA PRAGMA_DISABLE_CHECK_STACK_FRAME #else #define PRAGMA_DISABLE_CHECK_STACK_FRAME_EXTRA #endif /* !defined(__clang__) && __GNUC__ < 13 */ #else /*! __GNUC__ */ #define PRAGMA_DISABLE_CHECK_STACK_FRAME #define PRAGMA_REENABLE_CHECK_STACK_FRAME #define PRAGMA_DISABLE_CHECK_STACK_FRAME #define PRAGMA_DISABLE_CHECK_STACK_FRAME_EXTRA #endif /* __GNUC__ */ #endif /* _my_attribute_h */ mysql/server/sslopt-vars.h000064400000002575151027430560011701 0ustar00#ifndef SSLOPT_VARS_INCLUDED #define SSLOPT_VARS_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) #ifdef SSL_VARS_NOT_STATIC #define SSL_STATIC #else #define SSL_STATIC static #endif SSL_STATIC my_bool opt_use_ssl = 0; SSL_STATIC char *opt_ssl_ca = 0; SSL_STATIC char *opt_ssl_capath = 0; SSL_STATIC char *opt_ssl_cert = 0; SSL_STATIC char *opt_ssl_cipher = 0; SSL_STATIC char *opt_ssl_key = 0; SSL_STATIC char *opt_ssl_crl = 0; SSL_STATIC char *opt_ssl_crlpath = 0; SSL_STATIC char *opt_tls_version = 0; #ifdef MYSQL_CLIENT SSL_STATIC my_bool opt_ssl_verify_server_cert= 0; #endif #endif #endif /* SSLOPT_VARS_INCLUDED */ mysql/server/mysql_com_server.h000064400000002441151027430560012765 0ustar00/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Definitions private to the server, used in the networking layer to notify specific events. */ #ifndef _mysql_com_server_h #define _mysql_com_server_h struct st_net_server; typedef void (*before_header_callback_fn) (struct st_net *net, void *user_data, size_t count); typedef void (*after_header_callback_fn) (struct st_net *net, void *user_data, size_t count, my_bool rc); struct st_net_server { before_header_callback_fn m_before_header; after_header_callback_fn m_after_header; void *m_user_data; }; typedef struct st_net_server NET_SERVER; #endif mysql/server/my_net.h000064400000003755151027430560010700 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file is also used to make handling of sockets and ioctl() portable across systems. */ #ifndef _my_net_h #define _my_net_h C_MODE_START #include #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif #ifdef HAVE_ARPA_INET_H #include #endif #if defined(HAVE_POLL_H) #include #elif defined(HAVE_SYS_POLL_H) #include #endif /* defined(HAVE_POLL_H) */ #ifdef HAVE_SYS_IOCTL_H #include #endif #if !defined(_WIN32) #include #include #include #if !defined(alpha_linux_port) #include #endif #endif #if defined(_WIN32) #define O_NONBLOCK 1 /* For emulation of fcntl() */ /* SHUT_RDWR is called SD_BOTH in windows and is defined to 2 in winsock2.h #define SD_BOTH 0x02 */ #define SHUT_RDWR 0x02 #else #include /* getaddrinfo() & co */ #endif /* On OSes which don't have the in_addr_t, we guess that using uint32 is the best possible choice. We guess this from the fact that on HP-UX64bit & FreeBSD64bit & Solaris64bit, in_addr_t is equivalent to uint32. And on Linux32bit too. */ #ifndef HAVE_IN_ADDR_T #define in_addr_t uint32 #endif C_MODE_END #endif mysql/server/errmsg.h000064400000010471151027430560010675 0ustar00#ifndef ERRMSG_INCLUDED #define ERRMSG_INCLUDED /* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Error messages numbers for MySQL clients. The error messages itself are in libmysql/errmsg.c Error messages for the mysqld daemon are in sql/share/errmsg.txt */ #ifdef __cplusplus extern "C" { #endif void init_client_errs(void); void finish_client_errs(void); extern const char *client_errors[]; /* Error messages */ #ifdef __cplusplus } #endif #define CR_MIN_ERROR 2000 /* For easier client code */ #define CR_MAX_ERROR 2999 #if !defined(ER) #define ER(X) (((X) >= CR_ERROR_FIRST && (X) <= CR_ERROR_LAST) \ ? client_errors[(X)-CR_ERROR_FIRST] \ : client_errors[CR_UNKNOWN_ERROR-CR_ERROR_FIRST]) #endif #define CLIENT_ERRMAP 2 /* Errormap used by my_error() */ /* Do not add error numbers before CR_ERROR_FIRST. */ /* If necessary to add lower numbers, change CR_ERROR_FIRST accordingly. */ #define CR_ERROR_FIRST 2000 /*Copy first error nr.*/ #define CR_UNKNOWN_ERROR 2000 #define CR_SOCKET_CREATE_ERROR 2001 #define CR_CONNECTION_ERROR 2002 #define CR_CONN_HOST_ERROR 2003 #define CR_IPSOCK_ERROR 2004 #define CR_UNKNOWN_HOST 2005 #define CR_SERVER_GONE_ERROR 2006 #define CR_VERSION_ERROR 2007 #define CR_OUT_OF_MEMORY 2008 #define CR_WRONG_HOST_INFO 2009 #define CR_LOCALHOST_CONNECTION 2010 #define CR_TCP_CONNECTION 2011 #define CR_SERVER_HANDSHAKE_ERR 2012 #define CR_SERVER_LOST 2013 #define CR_COMMANDS_OUT_OF_SYNC 2014 #define CR_NAMEDPIPE_CONNECTION 2015 #define CR_NAMEDPIPEWAIT_ERROR 2016 #define CR_NAMEDPIPEOPEN_ERROR 2017 #define CR_NAMEDPIPESETSTATE_ERROR 2018 #define CR_CANT_READ_CHARSET 2019 #define CR_NET_PACKET_TOO_LARGE 2020 #define CR_EMBEDDED_CONNECTION 2021 #define CR_PROBE_SLAVE_STATUS 2022 #define CR_PROBE_SLAVE_HOSTS 2023 #define CR_PROBE_SLAVE_CONNECT 2024 #define CR_PROBE_MASTER_CONNECT 2025 #define CR_SSL_CONNECTION_ERROR 2026 #define CR_MALFORMED_PACKET 2027 #define CR_WRONG_LICENSE 2028 /* new 4.1 error codes */ #define CR_NULL_POINTER 2029 #define CR_NO_PREPARE_STMT 2030 #define CR_PARAMS_NOT_BOUND 2031 #define CR_DATA_TRUNCATED 2032 #define CR_NO_PARAMETERS_EXISTS 2033 #define CR_INVALID_PARAMETER_NO 2034 #define CR_INVALID_BUFFER_USE 2035 #define CR_UNSUPPORTED_PARAM_TYPE 2036 #define CR_SHARED_MEMORY_CONNECTION 2037 #define CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR 2038 #define CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR 2039 #define CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR 2040 #define CR_SHARED_MEMORY_CONNECT_MAP_ERROR 2041 #define CR_SHARED_MEMORY_FILE_MAP_ERROR 2042 #define CR_SHARED_MEMORY_MAP_ERROR 2043 #define CR_SHARED_MEMORY_EVENT_ERROR 2044 #define CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR 2045 #define CR_SHARED_MEMORY_CONNECT_SET_ERROR 2046 #define CR_CONN_UNKNOW_PROTOCOL 2047 #define CR_INVALID_CONN_HANDLE 2048 #define CR_SECURE_AUTH 2049 #define CR_FETCH_CANCELED 2050 #define CR_NO_DATA 2051 #define CR_NO_STMT_METADATA 2052 #define CR_NO_RESULT_SET 2053 #define CR_NOT_IMPLEMENTED 2054 #define CR_SERVER_LOST_EXTENDED 2055 #define CR_STMT_CLOSED 2056 #define CR_NEW_STMT_METADATA 2057 #define CR_ALREADY_CONNECTED 2058 #define CR_AUTH_PLUGIN_CANNOT_LOAD 2059 #define CR_DUPLICATE_CONNECTION_ATTR 2060 #define CR_AUTH_PLUGIN_ERR 2061 #define CR_ERROR_LAST /*Copy last error nr:*/ 2061 /* Add error numbers before CR_ERROR_LAST and change it accordingly. */ #endif /* ERRMSG_INCLUDED */ mysql/server/sql_state.h000064400000035061151027430560011377 0ustar00/* Autogenerated file, please don't edit */ { ER_DUP_KEY ,"23000", "" }, { ER_OUTOFMEMORY ,"HY001", "S1001" }, { ER_OUT_OF_SORTMEMORY ,"HY001", "S1001" }, { ER_CON_COUNT_ERROR ,"08004", "" }, { ER_BAD_HOST_ERROR ,"08S01", "" }, { ER_HANDSHAKE_ERROR ,"08S01", "" }, { ER_DBACCESS_DENIED_ERROR ,"42000", "" }, { ER_ACCESS_DENIED_ERROR ,"28000", "" }, { ER_NO_DB_ERROR ,"3D000", "" }, { ER_UNKNOWN_COM_ERROR ,"08S01", "" }, { ER_BAD_NULL_ERROR ,"23000", "" }, { ER_BAD_DB_ERROR ,"42000", "" }, { ER_TABLE_EXISTS_ERROR ,"42S01", "" }, { ER_BAD_TABLE_ERROR ,"42S02", "" }, { ER_NON_UNIQ_ERROR ,"23000", "" }, { ER_SERVER_SHUTDOWN ,"08S01", "" }, { ER_BAD_FIELD_ERROR ,"42S22", "S0022" }, { ER_WRONG_FIELD_WITH_GROUP ,"42000", "S1009" }, { ER_WRONG_GROUP_FIELD ,"42000", "S1009" }, { ER_WRONG_SUM_SELECT ,"42000", "S1009" }, { ER_WRONG_VALUE_COUNT ,"21S01", "" }, { ER_TOO_LONG_IDENT ,"42000", "S1009" }, { ER_DUP_FIELDNAME ,"42S21", "S1009" }, { ER_DUP_KEYNAME ,"42000", "S1009" }, { ER_DUP_ENTRY ,"23000", "S1009" }, { ER_WRONG_FIELD_SPEC ,"42000", "S1009" }, { ER_PARSE_ERROR ,"42000", "s1009" }, { ER_EMPTY_QUERY ,"42000", "" }, { ER_NONUNIQ_TABLE ,"42000", "S1009" }, { ER_INVALID_DEFAULT ,"42000", "S1009" }, { ER_MULTIPLE_PRI_KEY ,"42000", "S1009" }, { ER_TOO_MANY_KEYS ,"42000", "S1009" }, { ER_TOO_MANY_KEY_PARTS ,"42000", "S1009" }, { ER_TOO_LONG_KEY ,"42000", "S1009" }, { ER_KEY_COLUMN_DOES_NOT_EXITS ,"42000", "S1009" }, { ER_BLOB_USED_AS_KEY ,"42000", "S1009" }, { ER_TOO_BIG_FIELDLENGTH ,"42000", "S1009" }, { ER_WRONG_AUTO_KEY ,"42000", "S1009" }, { ER_FORCING_CLOSE ,"08S01", "" }, { ER_IPSOCK_ERROR ,"08S01", "" }, { ER_NO_SUCH_INDEX ,"42S12", "S1009" }, { ER_WRONG_FIELD_TERMINATORS ,"42000", "S1009" }, { ER_BLOBS_AND_NO_TERMINATED ,"42000", "S1009" }, { ER_CANT_REMOVE_ALL_FIELDS ,"42000", "" }, { ER_CANT_DROP_FIELD_OR_KEY ,"42000", "" }, { ER_WRONG_DB_NAME ,"42000", "" }, { ER_WRONG_TABLE_NAME ,"42000", "" }, { ER_TOO_BIG_SELECT ,"42000", "" }, { ER_UNKNOWN_PROCEDURE ,"42000", "" }, { ER_WRONG_PARAMCOUNT_TO_PROCEDURE ,"42000", "" }, { ER_UNKNOWN_TABLE ,"42S02", "" }, { ER_FIELD_SPECIFIED_TWICE ,"42000", "" }, { ER_UNSUPPORTED_EXTENSION ,"42000", "" }, { ER_TABLE_MUST_HAVE_COLUMNS ,"42000", "" }, { ER_UNKNOWN_CHARACTER_SET ,"42000", "" }, { ER_TOO_BIG_ROWSIZE ,"42000", "" }, { ER_WRONG_OUTER_JOIN ,"42000", "" }, { ER_NULL_COLUMN_IN_INDEX ,"42000", "" }, { ER_PASSWORD_ANONYMOUS_USER ,"42000", "" }, { ER_PASSWORD_NOT_ALLOWED ,"42000", "" }, { ER_PASSWORD_NO_MATCH ,"28000", "" }, { ER_WRONG_VALUE_COUNT_ON_ROW ,"21S01", "" }, { ER_INVALID_USE_OF_NULL ,"22004", "" }, { ER_REGEXP_ERROR ,"42000", "" }, { ER_MIX_OF_GROUP_FUNC_AND_FIELDS ,"42000", "" }, { ER_NONEXISTING_GRANT ,"42000", "" }, { ER_TABLEACCESS_DENIED_ERROR ,"42000", "" }, { ER_COLUMNACCESS_DENIED_ERROR ,"42000", "" }, { ER_ILLEGAL_GRANT_FOR_TABLE ,"42000", "" }, { ER_GRANT_WRONG_HOST_OR_USER ,"42000", "" }, { ER_NO_SUCH_TABLE ,"42S02", "" }, { ER_NONEXISTING_TABLE_GRANT ,"42000", "" }, { ER_NOT_ALLOWED_COMMAND ,"42000", "" }, { ER_SYNTAX_ERROR ,"42000", "" }, { ER_ABORTING_CONNECTION ,"08S01", "" }, { ER_NET_PACKET_TOO_LARGE ,"08S01", "" }, { ER_NET_READ_ERROR_FROM_PIPE ,"08S01", "" }, { ER_NET_FCNTL_ERROR ,"08S01", "" }, { ER_NET_PACKETS_OUT_OF_ORDER ,"08S01", "" }, { ER_NET_UNCOMPRESS_ERROR ,"08S01", "" }, { ER_NET_READ_ERROR ,"08S01", "" }, { ER_NET_READ_INTERRUPTED ,"08S01", "" }, { ER_NET_ERROR_ON_WRITE ,"08S01", "" }, { ER_NET_WRITE_INTERRUPTED ,"08S01", "" }, { ER_TOO_LONG_STRING ,"42000", "" }, { ER_TABLE_CANT_HANDLE_BLOB ,"42000", "" }, { ER_TABLE_CANT_HANDLE_AUTO_INCREMENT ,"42000", "" }, { ER_WRONG_COLUMN_NAME ,"42000", "" }, { ER_WRONG_KEY_COLUMN ,"42000", "" }, { ER_DUP_UNIQUE ,"23000", "" }, { ER_BLOB_KEY_WITHOUT_LENGTH ,"42000", "" }, { ER_PRIMARY_CANT_HAVE_NULL ,"42000", "" }, { ER_TOO_MANY_ROWS ,"42000", "" }, { ER_REQUIRES_PRIMARY_KEY ,"42000", "" }, { ER_KEY_DOES_NOT_EXISTS ,"42000", "S1009" }, { ER_CHECK_NO_SUCH_TABLE ,"42000", "" }, { ER_CHECK_NOT_IMPLEMENTED ,"42000", "" }, { ER_CANT_DO_THIS_DURING_AN_TRANSACTION ,"25000", "" }, { ER_NEW_ABORTING_CONNECTION ,"08S01", "" }, { ER_MASTER_NET_READ ,"08S01", "" }, { ER_MASTER_NET_WRITE ,"08S01", "" }, { ER_TOO_MANY_USER_CONNECTIONS ,"42000", "" }, { ER_READ_ONLY_TRANSACTION ,"25000", "" }, { ER_NO_PERMISSION_TO_CREATE_USER ,"42000", "" }, { ER_LOCK_DEADLOCK ,"40001", "" }, { ER_NO_REFERENCED_ROW ,"23000", "" }, { ER_ROW_IS_REFERENCED ,"23000", "" }, { ER_CONNECT_TO_MASTER ,"08S01", "" }, { ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT ,"21000", "" }, { ER_USER_LIMIT_REACHED ,"42000", "" }, { ER_SPECIFIC_ACCESS_DENIED_ERROR ,"42000", "" }, { ER_NO_DEFAULT ,"42000", "" }, { ER_WRONG_VALUE_FOR_VAR ,"42000", "" }, { ER_WRONG_TYPE_FOR_VAR ,"42000", "" }, { ER_CANT_USE_OPTION_HERE ,"42000", "" }, { ER_NOT_SUPPORTED_YET ,"42000", "" }, { ER_WRONG_FK_DEF ,"42000", "" }, { ER_OPERAND_COLUMNS ,"21000", "" }, { ER_SUBQUERY_NO_1_ROW ,"21000", "" }, { ER_ILLEGAL_REFERENCE ,"42S22", "" }, { ER_DERIVED_MUST_HAVE_ALIAS ,"42000", "" }, { ER_SELECT_REDUCED ,"01000", "" }, { ER_TABLENAME_NOT_ALLOWED_HERE ,"42000", "" }, { ER_NOT_SUPPORTED_AUTH_MODE ,"08004", "" }, { ER_SPATIAL_CANT_HAVE_NULL ,"42000", "" }, { ER_COLLATION_CHARSET_MISMATCH ,"42000", "" }, { ER_WARN_TOO_FEW_RECORDS ,"01000", "" }, { ER_WARN_TOO_MANY_RECORDS ,"01000", "" }, { ER_WARN_NULL_TO_NOTNULL ,"22004", "" }, { ER_WARN_DATA_OUT_OF_RANGE ,"22003", "" }, { WARN_DATA_TRUNCATED ,"01000", "" }, { ER_WRONG_NAME_FOR_INDEX ,"42000", "" }, { ER_WRONG_NAME_FOR_CATALOG ,"42000", "" }, { ER_UNKNOWN_STORAGE_ENGINE ,"42000", "" }, { ER_TRUNCATED_WRONG_VALUE ,"22007", "" }, { ER_SP_NO_RECURSIVE_CREATE ,"2F003", "" }, { ER_SP_ALREADY_EXISTS ,"42000", "" }, { ER_SP_DOES_NOT_EXIST ,"42000", "" }, { ER_SP_LILABEL_MISMATCH ,"42000", "" }, { ER_SP_LABEL_REDEFINE ,"42000", "" }, { ER_SP_LABEL_MISMATCH ,"42000", "" }, { ER_SP_UNINIT_VAR ,"01000", "" }, { ER_SP_BADSELECT ,"0A000", "" }, { ER_SP_BADRETURN ,"42000", "" }, { ER_SP_BADSTATEMENT ,"0A000", "" }, { ER_UPDATE_LOG_DEPRECATED_IGNORED ,"42000", "" }, { ER_UPDATE_LOG_DEPRECATED_TRANSLATED ,"42000", "" }, { ER_QUERY_INTERRUPTED ,"70100", "" }, { ER_SP_WRONG_NO_OF_ARGS ,"42000", "" }, { ER_SP_COND_MISMATCH ,"42000", "" }, { ER_SP_NORETURN ,"42000", "" }, { ER_SP_NORETURNEND ,"2F005", "" }, { ER_SP_BAD_CURSOR_QUERY ,"42000", "" }, { ER_SP_BAD_CURSOR_SELECT ,"42000", "" }, { ER_SP_CURSOR_MISMATCH ,"42000", "" }, { ER_SP_CURSOR_ALREADY_OPEN ,"24000", "" }, { ER_SP_CURSOR_NOT_OPEN ,"24000", "" }, { ER_SP_UNDECLARED_VAR ,"42000", "" }, { ER_SP_FETCH_NO_DATA ,"02000", "" }, { ER_SP_DUP_PARAM ,"42000", "" }, { ER_SP_DUP_VAR ,"42000", "" }, { ER_SP_DUP_COND ,"42000", "" }, { ER_SP_DUP_CURS ,"42000", "" }, { ER_SP_SUBSELECT_NYI ,"0A000", "" }, { ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG ,"0A000", "" }, { ER_SP_VARCOND_AFTER_CURSHNDLR ,"42000", "" }, { ER_SP_CURSOR_AFTER_HANDLER ,"42000", "" }, { ER_SP_CASE_NOT_FOUND ,"20000", "" }, { ER_DIVISION_BY_ZERO ,"22012", "" }, { ER_TRUNCATED_WRONG_VALUE_FOR_FIELD ,"22007", "" }, { ER_ILLEGAL_VALUE_FOR_TYPE ,"22007", "" }, { ER_VIEW_CHECK_FAILED ,"44000", "" }, { ER_PROCACCESS_DENIED_ERROR ,"42000", "" }, { ER_XAER_NOTA ,"XAE04", "" }, { ER_XAER_INVAL ,"XAE05", "" }, { ER_XAER_RMFAIL ,"XAE07", "" }, { ER_XAER_OUTSIDE ,"XAE09", "" }, { ER_XAER_RMERR ,"XAE03", "" }, { ER_XA_RBROLLBACK ,"XA100", "" }, { ER_NONEXISTING_PROC_GRANT ,"42000", "" }, { ER_DATA_TOO_LONG ,"22001", "" }, { ER_SP_BAD_SQLSTATE ,"42000", "" }, { ER_CANT_CREATE_USER_WITH_GRANT ,"42000", "" }, { ER_SP_DUP_HANDLER ,"42000", "" }, { ER_SP_NOT_VAR_ARG ,"42000", "" }, { ER_SP_NO_RETSET ,"0A000", "" }, { ER_CANT_CREATE_GEOMETRY_OBJECT ,"22003", "" }, { ER_TOO_BIG_SCALE ,"42000", "S1009" }, { ER_TOO_BIG_PRECISION ,"42000", "S1009" }, { ER_M_BIGGER_THAN_D ,"42000", "S1009" }, { ER_TOO_LONG_BODY ,"42000", "S1009" }, { ER_TOO_BIG_DISPLAYWIDTH ,"42000", "S1009" }, { ER_XAER_DUPID ,"XAE08", "" }, { ER_DATETIME_FUNCTION_OVERFLOW ,"22008", "" }, { ER_MALFORMED_DEFINER ,"0L000", "" }, { ER_ROW_IS_REFERENCED_2 ,"23000", "" }, { ER_NO_REFERENCED_ROW_2 ,"23000", "" }, { ER_SP_BAD_VAR_SHADOW ,"42000", "" }, { ER_SP_WRONG_NAME ,"42000", "" }, { ER_SP_NO_AGGREGATE ,"42000", "" }, { ER_MAX_PREPARED_STMT_COUNT_REACHED ,"42000", "" }, { ER_NON_GROUPING_FIELD_USED ,"42000", "" }, { ER_CANT_CHANGE_TX_CHARACTERISTICS ,"25001", "" }, { ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT ,"42000", "" }, { ER_WRONG_PARAMETERS_TO_NATIVE_FCT ,"42000", "" }, { ER_WRONG_PARAMETERS_TO_STORED_FCT ,"42000", "" }, { ER_DUP_ENTRY_WITH_KEY_NAME ,"23000", "S1009" }, { ER_XA_RBTIMEOUT ,"XA106", "" }, { ER_XA_RBDEADLOCK ,"XA102", "" }, { ER_FUNC_INEXISTENT_NAME_COLLISION ,"42000", "" }, { ER_DUP_SIGNAL_SET ,"42000", "" }, { ER_SIGNAL_WARN ,"01000", "" }, { ER_SIGNAL_NOT_FOUND ,"02000", "" }, { ER_SIGNAL_EXCEPTION ,"HY000", "" }, { ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER ,"0K000", "" }, { ER_SPATIAL_MUST_HAVE_GEOM_COL ,"42000", "" }, { ER_DATA_OUT_OF_RANGE ,"22003", "" }, { ER_ACCESS_DENIED_NO_PASSWORD_ERROR ,"28000", "" }, { ER_TRUNCATE_ILLEGAL_FK ,"42000", "" }, { ER_DA_INVALID_CONDITION_NUMBER ,"35000", "" }, { ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO,"23000", "S1009" }, { ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO,"23000", "S1009" }, { ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION,"25006", "" }, { ER_ALTER_OPERATION_NOT_SUPPORTED ,"0A000", "" }, { ER_ALTER_OPERATION_NOT_SUPPORTED_REASON ,"0A000", "" }, { ER_DUP_UNKNOWN_IN_INDEX ,"23000", "" }, { ER_ACCESS_DENIED_CHANGE_USER_ERROR ,"28000", "" }, { ER_DATA_OVERFLOW ,"22003", "" }, { ER_DATA_TRUNCATED ,"22003", "" }, { ER_BAD_DATA ,"22007", "" }, { ER_DYN_COL_DATA ,"22007", "" }, { ER_CONNECTION_KILLED ,"70100", "" }, { ER_NO_SUCH_TABLE_IN_ENGINE ,"42S02", "" }, { ER_INVALID_ROLE ,"OP000", "" }, { ER_INVALID_CURRENT_USER ,"0L000", "" }, { ER_IT_IS_A_VIEW ,"42S02", "" }, { ER_STATEMENT_TIMEOUT ,"70100", "" }, { ER_SUBQUERIES_NOT_SUPPORTED ,"42000", "" }, { ER_SET_STATEMENT_NOT_SUPPORTED ,"42000", "" }, { ER_INVALID_DEFAULT_VALUE_FOR_FIELD ,"22007", "" }, { ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER,"0Z002", "" }, { ER_INVALID_ARGUMENT_FOR_LOGARITHM ,"2201E", "" }, { ER_GIS_INVALID_DATA ,"22023", "" }, { ER_USER_LOCK_WRONG_NAME ,"42000", "" }, { ER_UNUSED_26 ,"0A000", "" }, { ER_CONSTRAINT_FAILED ,"23000", "" }, { ER_EXPRESSION_REFERS_TO_UNINIT_FIELD ,"01000", "" }, { ER_WRONG_PARAMCOUNT_TO_CURSOR ,"42000", "" }, { ER_NOT_SEQUENCE ,"42S02", "" }, { ER_NOT_SEQUENCE2 ,"42S02", "" }, { ER_UNKNOWN_SEQUENCES ,"42S02", "" }, { ER_UNKNOWN_VIEW ,"42S02", "" }, { ER_TOO_LONG_KEYPART ,"42000", "S1009" }, mysql/server/mysql/service_kill_statement.h000064400000004026151027430560015301 0ustar00/* Copyright (c) 2013, 2018, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_SERVICE_KILL_STATEMENT_INCLUDED #define MYSQL_SERVICE_KILL_STATEMENT_INCLUDED /** @file This service provides functions that allow plugins to support the KILL statement. In MySQL support for the KILL statement is cooperative. The KILL statement only sets a "killed" flag. This function returns the value of that flag. A thread should check it often, especially inside time-consuming loops, and gracefully abort the operation if it is non-zero. thd_killed(thd) @return 0 - no KILL statement was issued, continue normally @return 1 - there was a KILL statement, abort the execution. thd_kill_level(thd) @return thd_kill_levels_enum values */ #ifdef __cplusplus extern "C" { #endif enum thd_kill_levels { THD_IS_NOT_KILLED=0, THD_ABORT_SOFTLY=50, /**< abort when possible, don't leave tables corrupted */ THD_ABORT_ASAP=100, /**< abort asap */ }; extern struct kill_statement_service_st { enum thd_kill_levels (*thd_kill_level_func)(const MYSQL_THD); } *thd_kill_statement_service; /* backward compatibility helper */ #define thd_killed(THD) (thd_kill_level(THD) == THD_ABORT_ASAP) #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_kill_level(THD) \ thd_kill_statement_service->thd_kill_level_func(THD) #else enum thd_kill_levels thd_kill_level(const MYSQL_THD); #endif #ifdef __cplusplus } #endif #endif mysql/server/mysql/service_sha2.h000064400000012263151027430560013121 0ustar00#ifndef MYSQL_SERVICE_SHA2_INCLUDED /* Copyright (c) 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file my sha2 service Functions to calculate SHA2 hash from a memory buffer */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #endif extern struct my_sha2_service_st { void (*my_sha224_type)(unsigned char*, const char*, size_t); void (*my_sha224_multi_type)(unsigned char*, ...); size_t (*my_sha224_context_size_type)(); void (*my_sha224_init_type)(void *); void (*my_sha224_input_type)(void *, const unsigned char *, size_t); void (*my_sha224_result_type)(void *, unsigned char *); void (*my_sha256_type)(unsigned char*, const char*, size_t); void (*my_sha256_multi_type)(unsigned char*, ...); size_t (*my_sha256_context_size_type)(); void (*my_sha256_init_type)(void *); void (*my_sha256_input_type)(void *, const unsigned char *, size_t); void (*my_sha256_result_type)(void *, unsigned char *); void (*my_sha384_type)(unsigned char*, const char*, size_t); void (*my_sha384_multi_type)(unsigned char*, ...); size_t (*my_sha384_context_size_type)(); void (*my_sha384_init_type)(void *); void (*my_sha384_input_type)(void *, const unsigned char *, size_t); void (*my_sha384_result_type)(void *, unsigned char *); void (*my_sha512_type)(unsigned char*, const char*, size_t); void (*my_sha512_multi_type)(unsigned char*, ...); size_t (*my_sha512_context_size_type)(); void (*my_sha512_init_type)(void *); void (*my_sha512_input_type)(void *, const unsigned char *, size_t); void (*my_sha512_result_type)(void *, unsigned char *); } *my_sha2_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_sha224(A,B,C) my_sha2_service->my_sha224_type(A,B,C) #define my_sha224_multi my_sha2_service->my_sha224_multi_type #define my_sha224_context_size() my_sha2_service->my_sha224_context_size_type() #define my_sha224_init(A) my_sha2_service->my_sha224_init_type(A) #define my_sha224_input(A,B,C) my_sha2_service->my_sha224_input_type(A,B,C) #define my_sha224_result(A,B) my_sha2_service->my_sha224_result_type(A,B) #define my_sha256(A,B,C) my_sha2_service->my_sha256_type(A,B,C) #define my_sha256_multi my_sha2_service->my_sha256_multi_type #define my_sha256_context_size() my_sha2_service->my_sha256_context_size_type() #define my_sha256_init(A) my_sha2_service->my_sha256_init_type(A) #define my_sha256_input(A,B,C) my_sha2_service->my_sha256_input_type(A,B,C) #define my_sha256_result(A,B) my_sha2_service->my_sha256_result_type(A,B) #define my_sha384(A,B,C) my_sha2_service->my_sha384_type(A,B,C) #define my_sha384_multi my_sha2_service->my_sha384_multi_type #define my_sha384_context_size() my_sha2_service->my_sha384_context_size_type() #define my_sha384_init(A) my_sha2_service->my_sha384_init_type(A) #define my_sha384_input(A,B,C) my_sha2_service->my_sha384_input_type(A,B,C) #define my_sha384_result(A,B) my_sha2_service->my_sha384_result_type(A,B) #define my_sha512(A,B,C) my_sha2_service->my_sha512_type(A,B,C) #define my_sha512_multi my_sha2_service->my_sha512_multi_type #define my_sha512_context_size() my_sha2_service->my_sha512_context_size_type() #define my_sha512_init(A) my_sha2_service->my_sha512_init_type(A) #define my_sha512_input(A,B,C) my_sha2_service->my_sha512_input_type(A,B,C) #define my_sha512_result(A,B) my_sha2_service->my_sha512_result_type(A,B) #else void my_sha224(unsigned char*, const char*, size_t); void my_sha224_multi(unsigned char*, ...); size_t my_sha224_context_size(); void my_sha224_init(void *context); void my_sha224_input(void *context, const unsigned char *buf, size_t len); void my_sha224_result(void *context, unsigned char *digest); void my_sha256(unsigned char*, const char*, size_t); void my_sha256_multi(unsigned char*, ...); size_t my_sha256_context_size(); void my_sha256_init(void *context); void my_sha256_input(void *context, const unsigned char *buf, size_t len); void my_sha256_result(void *context, unsigned char *digest); void my_sha384(unsigned char*, const char*, size_t); void my_sha384_multi(unsigned char*, ...); size_t my_sha384_context_size(); void my_sha384_init(void *context); void my_sha384_input(void *context, const unsigned char *buf, size_t len); void my_sha384_result(void *context, unsigned char *digest); void my_sha512(unsigned char*, const char*, size_t); void my_sha512_multi(unsigned char*, ...); size_t my_sha512_context_size(); void my_sha512_init(void *context); void my_sha512_input(void *context, const unsigned char *buf, size_t len); void my_sha512_result(void *context, unsigned char *digest); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_SHA2_INCLUDED #endif mysql/server/mysql/plugin_password_validation.h000064400000003021151027430560016166 0ustar00#ifndef MYSQL_PLUGIN_PASSWORD_VALIDATION_INCLUDED /* Copyright (C) 2014 Sergei Golubchik and MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Password Validation Plugin API. This file defines the API for server password validation plugins. */ #define MYSQL_PLUGIN_PASSWORD_VALIDATION_INCLUDED #include #ifdef __cplusplus extern "C" { #endif #define MariaDB_PASSWORD_VALIDATION_INTERFACE_VERSION 0x0100 /** Password validation plugin descriptor */ struct st_mariadb_password_validation { int interface_version; /**< version plugin uses */ /** Function provided by the plugin which should perform password validation and return 0 if the password has passed the validation. */ int (*validate_password)(const MYSQL_CONST_LEX_STRING *username, const MYSQL_CONST_LEX_STRING *password); }; #ifdef __cplusplus } #endif #endif mysql/server/mysql/plugin_data_type.h000064400000002424151027430560014072 0ustar00#ifndef MARIADB_PLUGIN_DATA_TYPE_INCLUDED #define MARIADB_PLUGIN_DATA_TYPE_INCLUDED /* Copyright (C) 2019, Alexander Barkov and MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Data Type Plugin API. This file defines the API for server plugins that manage data types. */ #ifdef __cplusplus #include /* API for data type plugins. (MariaDB_DATA_TYPE_PLUGIN) */ #define MariaDB_DATA_TYPE_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) struct st_mariadb_data_type { int interface_version; class Type_handler *type_handler; }; /** Data type plugin descriptor */ #endif /* __cplusplus */ #endif /* MARIADB_PLUGIN_DATA_TYPE_INCLUDED */ mysql/server/mysql/service_thd_error_context.h000064400000006540151027430560016021 0ustar00#ifndef MYSQL_SERVICE_THD_STMT_DA_INCLUDED /* Copyright (C) 2013 MariaDB Foundation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This service provides access to the statement diagnostics area: - error message - error number - row for warning (e.g. for multi-row INSERT statements) */ #ifdef __cplusplus extern "C" { #endif extern struct thd_error_context_service_st { const char *(*thd_get_error_message_func)(const MYSQL_THD thd); unsigned int (*thd_get_error_number_func)(const MYSQL_THD thd); unsigned long (*thd_get_error_row_func)(const MYSQL_THD thd); void (*thd_inc_error_row_func)(MYSQL_THD thd); char *(*thd_get_error_context_description_func)(MYSQL_THD thd, char *buffer, unsigned int length, unsigned int max_query_length); } *thd_error_context_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_get_error_message(thd) \ (thd_error_context_service->thd_get_error_message_func((thd))) #define thd_get_error_number(thd) \ (thd_error_context_service->thd_get_error_number_func((thd))) #define thd_get_error_row(thd) \ (thd_error_context_service->thd_get_error_row_func((thd))) #define thd_inc_error_row(thd) \ (thd_error_context_service->thd_inc_error_row_func((thd))) #define thd_get_error_context_description(thd, buffer, length, max_query_len) \ (thd_error_context_service->thd_get_error_context_description_func((thd), \ (buffer), \ (length), \ (max_query_len))) #else /** Return error message @param thd user thread connection handle @return error text */ const char *thd_get_error_message(const MYSQL_THD thd); /** Return error number @param thd user thread connection handle @return error number */ unsigned int thd_get_error_number(const MYSQL_THD thd); /** Return the current row number (i.e. in a multiple INSERT statement) @param thd user thread connection handle @return row number */ unsigned long thd_get_error_row(const MYSQL_THD thd); /** Increment the current row number @param thd user thread connection handle */ void thd_inc_error_row(MYSQL_THD thd); /** Return a text description of a thread, its security context (user,host) and the current query. */ char *thd_get_error_context_description(MYSQL_THD thd, char *buffer, unsigned int length, unsigned int max_query_length); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_THD_STMT_DA_INCLUDED #endif mysql/server/mysql/service_thd_wait.h000064400000007157151027430560014075 0ustar00/* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_SERVICE_THD_WAIT_INCLUDED #define MYSQL_SERVICE_THD_WAIT_INCLUDED /** @file include/mysql/service_thd_wait.h This service provides functions for plugins and storage engines to report when they are going to sleep/stall. SYNOPSIS thd_wait_begin() - call just before a wait begins thd Thread object Use NULL if the thd is NOT known. wait_type Type of wait 1 -- short wait (e.g. for mutex) 2 -- medium wait (e.g. for disk io) 3 -- large wait (e.g. for locked row/table) NOTES This is used by the threadpool to have better knowledge of which threads that currently are actively running on CPUs. When a thread reports that it's going to sleep/stall, the threadpool scheduler is free to start another thread in the pool most likely. The expected wait time is simply an indication of how long the wait is expected to become, the real wait time could be very different. thd_wait_end() called immediately after the wait is complete thd_wait_end() MUST be called if thd_wait_begin() was called. Using thd_wait_...() service is optional but recommended. Using it will improve performance as the thread pool will be more active at managing the thread workload. */ #ifdef __cplusplus extern "C" { #endif /* One should only report wait events that could potentially block for a long time. A mutex wait is too short of an event to report. The reason is that an event which is reported leads to a new thread starts executing a query and this has a negative impact of usage of CPU caches and thus the expected gain of starting a new thread must be higher than the expected cost of lost performance due to starting a new thread. Good examples of events that should be reported are waiting for row locks that could easily be for many milliseconds or even seconds and the same holds true for global read locks, table locks and other meta data locks. Another event of interest is going to sleep for an extended time. */ typedef enum _thd_wait_type_e { THD_WAIT_SLEEP= 1, THD_WAIT_DISKIO= 2, THD_WAIT_ROW_LOCK= 3, THD_WAIT_GLOBAL_LOCK= 4, THD_WAIT_META_DATA_LOCK= 5, THD_WAIT_TABLE_LOCK= 6, THD_WAIT_USER_LOCK= 7, THD_WAIT_BINLOG= 8, THD_WAIT_GROUP_COMMIT= 9, THD_WAIT_SYNC= 10, THD_WAIT_NET= 11, THD_WAIT_LAST= 12 } thd_wait_type; extern struct thd_wait_service_st { void (*thd_wait_begin_func)(MYSQL_THD, int); void (*thd_wait_end_func)(MYSQL_THD); } *thd_wait_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_wait_begin(_THD, _WAIT_TYPE) \ thd_wait_service->thd_wait_begin_func(_THD, _WAIT_TYPE) #define thd_wait_end(_THD) thd_wait_service->thd_wait_end_func(_THD) #else void thd_wait_begin(MYSQL_THD thd, int wait_type); void thd_wait_end(MYSQL_THD thd); #endif #ifdef __cplusplus } #endif #endif mysql/server/mysql/service_debug_sync.h000064400000032414151027430560014406 0ustar00#ifndef MYSQL_SERVICE_DEBUG_SYNC_INCLUDED /* Copyright (c) 2009, 2010, Oracle and/or its affiliates. Copyright (c) 2012, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file == Debug Sync Facility == The Debug Sync Facility allows placement of synchronization points in the server code by using the DEBUG_SYNC macro: open_tables(...) DEBUG_SYNC(thd, "after_open_tables"); lock_tables(...) When activated, a sync point can - Emit a signal and/or - Wait for a signal Nomenclature: - signal: A value of a global variable that persists until overwritten by a new signal. The global variable can also be seen as a "signal post" or "flag mast". Then the signal is what is attached to the "signal post" or "flag mast". - emit a signal: Assign the value (the signal) to the global variable ("set a flag") and broadcast a global condition to wake those waiting for a signal. - wait for a signal: Loop over waiting for the global condition until the global value matches the wait-for signal. By default, all sync points are inactive. They do nothing (except to burn a couple of CPU cycles for checking if they are active). A sync point becomes active when an action is requested for it. To do so, put a line like this in the test case file: SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed'; This activates the sync point 'after_open_tables'. It requests it to emit the signal 'opened' and wait for another thread to emit the signal 'flushed' when the thread's execution runs through the sync point. For every sync point there can be one action per thread only. Every thread can request multiple actions, but only one per sync point. In other words, a thread can activate multiple sync points. Here is an example how to activate and use the sync points: --connection conn1 SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed'; send INSERT INTO t1 VALUES(1); --connection conn2 SET DEBUG_SYNC= 'now WAIT_FOR opened'; SET DEBUG_SYNC= 'after_abort_locks SIGNAL flushed'; FLUSH TABLE t1; When conn1 runs through the INSERT statement, it hits the sync point 'after_open_tables'. It notices that it is active and executes its action. It emits the signal 'opened' and waits for another thread to emit the signal 'flushed'. conn2 waits immediately at the special sync point 'now' for another thread to emit the 'opened' signal. A signal remains in effect until it is overwritten. If conn1 signals 'opened' before conn2 reaches 'now', conn2 will still find the 'opened' signal. It does not wait in this case. When conn2 reaches 'after_abort_locks', it signals 'flushed', which lets conn1 awake. Normally the activation of a sync point is cleared when it has been executed. Sometimes it is necessary to keep the sync point active for another execution. You can add an execute count to the action: SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 3'; This sets the signal point's activation counter to 3. Each execution decrements the counter. After the third execution the sync point becomes inactive. One of the primary goals of this facility is to eliminate sleeps from the test suite. In most cases it should be possible to rewrite test cases so that they do not need to sleep. (But this facility cannot synchronize multiple processes.) However, to support test development, and as a last resort, sync point waiting times out. There is a default timeout, but it can be overridden: SET DEBUG_SYNC= 'name WAIT_FOR sig TIMEOUT 10 EXECUTE 2'; TIMEOUT 0 is special: If the signal is not present, the wait times out immediately. When a wait timed out (even on TIMEOUT 0), a warning is generated so that it shows up in the test result. You can throw an error message and kill the query when a synchronization point is hit a certain number of times: SET DEBUG_SYNC= 'name HIT_LIMIT 3'; Or combine it with signal and/or wait: SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 2 HIT_LIMIT 3'; Here the first two hits emit the signal, the third hit returns the error message and kills the query. For cases where you are not sure that an action is taken and thus cleared in any case, you can force to clear (deactivate) a sync point: SET DEBUG_SYNC= 'name CLEAR'; If you want to clear all actions and clear the global signal, use: SET DEBUG_SYNC= 'RESET'; This is the only way to reset the global signal to an empty string. For testing of the facility itself you can execute a sync point just as if it had been hit: SET DEBUG_SYNC= 'name TEST'; === Formal Syntax === The string to "assign" to the DEBUG_SYNC variable can contain: {RESET | TEST | CLEAR | {{SIGNAL | WAIT_FOR [TIMEOUT ]} [EXECUTE ] &| HIT_LIMIT } Here '&|' means 'and/or'. This means that one of the sections separated by '&|' must be present or both of them. === Activation/Deactivation === The facility is an optional part of the MySQL server. It is enabled in a debug server by default. ./configure --enable-debug-sync The Debug Sync Facility, when compiled in, is disabled by default. It can be enabled by a mysqld command line option: --debug-sync-timeout[=default_wait_timeout_value_in_seconds] 'default_wait_timeout_value_in_seconds' is the default timeout for the WAIT_FOR action. If set to zero, the facility stays disabled. The facility is enabled by default in the test suite, but can be disabled with: mysql-test-run.pl ... --debug-sync-timeout=0 ... Likewise the default wait timeout can be set: mysql-test-run.pl ... --debug-sync-timeout=10 ... The command line option influences the readable value of the system variable 'debug_sync'. * If the facility is not compiled in, the system variable does not exist. * If --debug-sync-timeout=0 the value of the variable reads as "OFF". * Otherwise the value reads as "ON - current signal: " followed by the current signal string, which can be empty. The readable variable value is the same, regardless if read as global or session value. Setting the 'debug-sync' system variable requires 'SUPER' privilege. You can never read back the string that you assigned to the variable, unless you assign the value that the variable does already have. But that would give a parse error. A syntactically correct string is parsed into a debug sync action and stored apart from the variable value. === Implementation === Pseudo code for a sync point: #define DEBUG_SYNC(thd, sync_point_name) if (unlikely(opt_debug_sync_timeout)) debug_sync(thd, STRING_WITH_LEN(sync_point_name)) The sync point performs a binary search in a sorted array of actions for this thread. The SET DEBUG_SYNC statement adds a requested action to the array or overwrites an existing action for the same sync point. When it adds a new action, the array is sorted again. === A typical synchronization pattern === There are quite a few places in MySQL, where we use a synchronization pattern like this: mysql_mutex_lock(&mutex); thd->enter_cond(&condition_variable, &mutex, new_message); #if defined(ENABLE_DEBUG_SYNC) if (!thd->killed && !end_of_wait_condition) DEBUG_SYNC(thd, "sync_point_name"); #endif while (!thd->killed && !end_of_wait_condition) mysql_cond_wait(&condition_variable, &mutex); thd->exit_cond(old_message); Here some explanations: thd->enter_cond() is used to register the condition variable and the mutex in thd->mysys_var. This is done to allow the thread to be interrupted (killed) from its sleep. Another thread can find the condition variable to signal and mutex to use for synchronization in this thread's THD::mysys_var. thd->enter_cond() requires the mutex to be acquired in advance. thd->exit_cond() unregisters the condition variable and mutex and releases the mutex. If you want to have a Debug Sync point with the wait, please place it behind enter_cond(). Only then you can safely decide, if the wait will be taken. Also you will have THD::proc_info correct when the sync point emits a signal. DEBUG_SYNC sets its own proc_info, but restores the previous one before releasing its internal mutex. As soon as another thread sees the signal, it does also see the proc_info from before entering the sync point. In this case it will be "new_message", which is associated with the wait that is to be synchronized. In the example above, the wait condition is repeated before the sync point. This is done to skip the sync point, if no wait takes place. The sync point is before the loop (not inside the loop) to have it hit once only. It is possible that the condition variable is signaled multiple times without the wait condition to be true. A bit off-topic: At some places, the loop is taken around the whole synchronization pattern: while (!thd->killed && !end_of_wait_condition) { mysql_mutex_lock(&mutex); thd->enter_cond(&condition_variable, &mutex, new_message); if (!thd->killed [&& !end_of_wait_condition]) { [DEBUG_SYNC(thd, "sync_point_name");] mysql_cond_wait(&condition_variable, &mutex); } thd->exit_cond(old_message); } Note that it is important to repeat the test for thd->killed after enter_cond(). Otherwise the killing thread may kill this thread after it tested thd->killed in the loop condition and before it registered the condition variable and mutex in enter_cond(). In this case, the killing thread does not know that this thread is going to wait on a condition variable. It would just set THD::killed. But if we would not test it again, we would go asleep though we are killed. If the killing thread would kill us when we are after the second test, but still before sleeping, we hold the mutex, which is registered in mysys_var. The killing thread would try to acquire the mutex before signaling the condition variable. Since the mutex is only released implicitly in mysql_cond_wait(), the signaling happens at the right place. We have a safe synchronization. === Co-work with the DBUG facility === When running the MySQL test suite with the --debug-dbug command line option, the Debug Sync Facility writes trace messages to the DBUG trace. The following shell commands proved very useful in extracting relevant information: egrep 'query:|debug_sync_exec:' mysql-test/var/log/mysqld.1.trace It shows all executed SQL statements and all actions executed by synchronization points. Sometimes it is also useful to see, which synchronization points have been run through (hit) with or without executing actions. Then add "|debug_sync_point:" to the egrep pattern. === Further reading === For a discussion of other methods to synchronize threads see http://forge.mysql.com/wiki/MySQL_Internals_Test_Synchronization For complete syntax tests, functional tests, and examples see the test case debug_sync.test. See also http://forge.mysql.com/worklog/task.php?id=4259 */ #ifndef MYSQL_ABI_CHECK #include #endif #ifdef __cplusplus extern "C" { #endif #ifdef MYSQL_DYNAMIC_PLUGIN extern void (*debug_sync_service)(MYSQL_THD, const char *, size_t); #else #define debug_sync_service debug_sync_C_callback_ptr extern void (*debug_sync_C_callback_ptr)(MYSQL_THD, const char *, size_t); #endif #ifdef ENABLED_DEBUG_SYNC #define DEBUG_SYNC(thd, name) \ do { \ if (debug_sync_service) \ debug_sync_service(thd, STRING_WITH_LEN(name)); \ } while(0) #define DEBUG_SYNC_C_IF_THD(thd, name) \ do { \ if (debug_sync_service && thd) \ debug_sync_service((MYSQL_THD) thd, STRING_WITH_LEN(name)); \ } while(0) #else #define DEBUG_SYNC(thd,name) do { } while(0) #define DEBUG_SYNC_C_IF_THD(thd, _sync_point_name_) do { } while(0) #endif /* defined(ENABLED_DEBUG_SYNC) */ /* compatibility macro */ #ifdef __cplusplus #define DEBUG_SYNC_C(name) DEBUG_SYNC(nullptr, name) #else #define DEBUG_SYNC_C(name) DEBUG_SYNC(NULL, name) #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_DEBUG_SYNC_INCLUDED #endif mysql/server/mysql/service_my_crypt.h000064400000010107151027430560014125 0ustar00#ifndef MYSQL_SERVICE_MY_CRYPT_INCLUDED #define MYSQL_SERVICE_MY_CRYPT_INCLUDED /* Copyright (c) 2014 Google Inc. Copyright (c) 2014, 2015 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file my crypt service AES encryption functions, and a function to generate random bytes. Include my_config.h before this file to use CTR and GCM modes (they only work if server was compiled with openssl). */ #ifdef __cplusplus extern "C" { #endif /* return values from my_aes_encrypt/my_aes_decrypt functions */ #define MY_AES_OK 0 #define MY_AES_BAD_DATA -100 #define MY_AES_OPENSSL_ERROR -101 #define MY_AES_BAD_KEYSIZE -102 /* The block size for all supported algorithms */ #define MY_AES_BLOCK_SIZE 16 /* The max key length of all supported algorithms */ #define MY_AES_MAX_KEY_LENGTH 32 #define MY_AES_CTX_SIZE 1040 enum my_aes_mode { MY_AES_ECB, MY_AES_CBC #ifdef HAVE_EncryptAes128Ctr , MY_AES_CTR #endif #ifdef HAVE_EncryptAes128Gcm , MY_AES_GCM #endif }; extern struct my_crypt_service_st { int (*my_aes_crypt_init)(void *ctx, enum my_aes_mode mode, int flags, const unsigned char* key, unsigned int klen, const unsigned char* iv, unsigned int ivlen); int (*my_aes_crypt_update)(void *ctx, const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen); int (*my_aes_crypt_finish)(void *ctx, unsigned char *dst, unsigned int *dlen); int (*my_aes_crypt)(enum my_aes_mode mode, int flags, const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen, const unsigned char *key, unsigned int klen, const unsigned char *iv, unsigned int ivlen); unsigned int (*my_aes_get_size)(enum my_aes_mode mode, unsigned int source_length); unsigned int (*my_aes_ctx_size)(enum my_aes_mode mode); int (*my_random_bytes)(unsigned char* buf, int num); } *my_crypt_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_aes_crypt_init(A,B,C,D,E,F,G) \ my_crypt_service->my_aes_crypt_init(A,B,C,D,E,F,G) #define my_aes_crypt_update(A,B,C,D,E) \ my_crypt_service->my_aes_crypt_update(A,B,C,D,E) #define my_aes_crypt_finish(A,B,C) \ my_crypt_service->my_aes_crypt_finish(A,B,C) #define my_aes_crypt(A,B,C,D,E,F,G,H,I,J) \ my_crypt_service->my_aes_crypt(A,B,C,D,E,F,G,H,I,J) #define my_aes_get_size(A,B)\ my_crypt_service->my_aes_get_size(A,B) #define my_aes_ctx_size(A)\ my_crypt_service->my_aes_ctx_size(A) #define my_random_bytes(A,B)\ my_crypt_service->my_random_bytes(A,B) #else int my_aes_crypt_init(void *ctx, enum my_aes_mode mode, int flags, const unsigned char* key, unsigned int klen, const unsigned char* iv, unsigned int ivlen); int my_aes_crypt_update(void *ctx, const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen); int my_aes_crypt_finish(void *ctx, unsigned char *dst, unsigned int *dlen); int my_aes_crypt(enum my_aes_mode mode, int flags, const unsigned char *src, unsigned int slen, unsigned char *dst, unsigned int *dlen, const unsigned char *key, unsigned int klen, const unsigned char *iv, unsigned int ivlen); int my_random_bytes(unsigned char* buf, int num); unsigned int my_aes_get_size(enum my_aes_mode mode, unsigned int source_length); unsigned int my_aes_ctx_size(enum my_aes_mode mode); #endif #ifdef __cplusplus } #endif #endif /* MYSQL_SERVICE_MY_CRYPT_INCLUDED */ mysql/server/mysql/plugin_function.h000064400000002635151027430560013751 0ustar00#ifndef MARIADB_PLUGIN_FUNCTION_INCLUDED #define MARIADB_PLUGIN_FUNCTION_INCLUDED /* Copyright (C) 2019, Alexander Barkov and MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Function Plugin API. This file defines the API for server plugins that manage functions. */ #ifdef __cplusplus #include /* API for function plugins. (MariaDB_FUNCTION_PLUGIN) */ #define MariaDB_FUNCTION_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) class Plugin_function { int m_interface_version; Create_func *m_builder; public: Plugin_function(Create_func *builder) :m_interface_version(MariaDB_FUNCTION_INTERFACE_VERSION), m_builder(builder) { } Create_func *create_func() { return m_builder; } }; #endif /* __cplusplus */ #endif /* MARIADB_PLUGIN_FUNCTION_INCLUDED */ mysql/server/mysql/client_plugin.h000064400000014267151027430560013406 0ustar00#ifndef MYSQL_CLIENT_PLUGIN_INCLUDED /* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab Copyright (c) 2010, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file MySQL Client Plugin API This file defines the API for plugins that work on the client side */ #define MYSQL_CLIENT_PLUGIN_INCLUDED /* On Windows, exports from DLL need to be declared Also, plugin needs to be declared as extern "C" because MSVC unlike other compilers, uses C++ mangling for variables not only for functions. */ #undef MYSQL_PLUGIN_EXPORT #if defined(_MSC_VER) #define MYSQL_PLUGIN_EXPORT_C __declspec(dllexport) #else /*_MSC_VER */ #define MYSQL_PLUGIN_EXPORT_C #endif #ifdef __cplusplus #define MYSQL_PLUGIN_EXPORT extern "C" MYSQL_PLUGIN_EXPORT_C #define C_MODE_START extern "C" { #define C_MODE_END } #else #define MYSQL_PLUGIN_EXPORT MYSQL_PLUGIN_EXPORT_C #define C_MODE_START #define C_MODE_END #endif #ifndef MYSQL_ABI_CHECK #include #include #endif /* known plugin types */ #define MYSQL_CLIENT_reserved1 0 #define MYSQL_CLIENT_reserved2 1 #define MYSQL_CLIENT_AUTHENTICATION_PLUGIN 2 #define MYSQL_CLIENT_AUTHENTICATION_PLUGIN_INTERFACE_VERSION 0x0100 #define MYSQL_CLIENT_MAX_PLUGINS 3 #define mysql_declare_client_plugin(X) \ C_MODE_START MYSQL_PLUGIN_EXPORT_C \ struct st_mysql_client_plugin_ ## X \ _mysql_client_plugin_declaration_ = { \ MYSQL_CLIENT_ ## X ## _PLUGIN, \ MYSQL_CLIENT_ ## X ## _PLUGIN_INTERFACE_VERSION, #define mysql_end_client_plugin }; C_MODE_END /* generic plugin header structure */ #define MYSQL_CLIENT_PLUGIN_HEADER \ int type; \ unsigned int interface_version; \ const char *name; \ const char *author; \ const char *desc; \ unsigned int version[3]; \ const char *license; \ void *mysql_api; \ int (*init)(char *, size_t, int, va_list); \ int (*deinit)(); \ int (*options)(const char *option, const void *); struct st_mysql_client_plugin { MYSQL_CLIENT_PLUGIN_HEADER }; struct st_mysql; /******** authentication plugin specific declarations *********/ #include struct st_mysql_client_plugin_AUTHENTICATION { MYSQL_CLIENT_PLUGIN_HEADER int (*authenticate_user)(MYSQL_PLUGIN_VIO *vio, struct st_mysql *mysql); }; #include /******** using plugins ************/ /** loads a plugin and initializes it @param mysql MYSQL structure. @param name a name of the plugin to load @param type type of plugin that should be loaded, -1 to disable type check @param argc number of arguments to pass to the plugin initialization function @param ... arguments for the plugin initialization function @retval a pointer to the loaded plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * mysql_load_plugin(struct st_mysql *mysql, const char *name, int type, int argc, ...); /** loads a plugin and initializes it, taking va_list as an argument This is the same as mysql_load_plugin, but take va_list instead of a list of arguments. @param mysql MYSQL structure. @param name a name of the plugin to load @param type type of plugin that should be loaded, -1 to disable type check @param argc number of arguments to pass to the plugin initialization function @param args arguments for the plugin initialization function @retval a pointer to the loaded plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * mysql_load_plugin_v(struct st_mysql *mysql, const char *name, int type, int argc, va_list args); /** finds an already loaded plugin by name, or loads it, if necessary @param mysql MYSQL structure. @param name a name of the plugin to load @param type type of plugin that should be loaded @retval a pointer to the plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * mysql_client_find_plugin(struct st_mysql *mysql, const char *name, int type); /** adds a plugin structure to the list of loaded plugins This is useful if an application has the necessary functionality (for example, a special load data handler) statically linked into the application binary. It can use this function to register the plugin directly, avoiding the need to factor it out into a shared object. @param mysql MYSQL structure. It is only used for error reporting @param plugin an st_mysql_client_plugin structure to register @retval a pointer to the plugin, or NULL in case of a failure */ struct st_mysql_client_plugin * mysql_client_register_plugin(struct st_mysql *mysql, struct st_mysql_client_plugin *plugin); /** set plugin options Can be used to set extra options and affect behavior for a plugin. This function may be called multiple times to set several options @param plugin an st_mysql_client_plugin structure @param option a string which specifies the option to set @param value value for the option. @retval 0 on success, 1 in case of failure **/ int mysql_plugin_options(struct st_mysql_client_plugin *plugin, const char *option, const void *value); #endif mysql/server/mysql/plugin_auth.h000064400000012430151027430560013057 0ustar00#ifndef MYSQL_PLUGIN_AUTH_INCLUDED /* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab Copyright (c) 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Authentication Plugin API. This file defines the API for server authentication plugins. */ #define MYSQL_PLUGIN_AUTH_INCLUDED #include #define MYSQL_AUTHENTICATION_INTERFACE_VERSION 0x0202 #include #ifdef __cplusplus extern "C" { #endif /* defines for MYSQL_SERVER_AUTH_INFO.password_used */ #define PASSWORD_USED_NO 0 #define PASSWORD_USED_YES 1 #define PASSWORD_USED_NO_MENTION 2 /** Provides server plugin access to authentication information */ typedef struct st_mysql_server_auth_info { /** User name as sent by the client and shown in USER(). NULL if the client packet with the user name was not received yet. */ const char *user_name; /** Length of user_name */ unsigned int user_name_length; /** A corresponding column value from the mysql.user table for the matching account name or the preprocessed value, if preprocess_hash method is not NULL */ const char *auth_string; /** Length of auth_string */ unsigned long auth_string_length; /** Matching account name as found in the mysql.user table. A plugin can override it with another name that will be used by MySQL for authorization, and shown in CURRENT_USER() */ char authenticated_as[MYSQL_USERNAME_LENGTH+1]; /** The unique user name that was used by the plugin to authenticate. Not used by the server. Available through the @@EXTERNAL_USER variable. */ char external_user[MYSQL_USERNAME_LENGTH+1]; /** This only affects the "Authentication failed. Password used: %s" error message. has the following values : 0 : %s will be NO. 1 : %s will be YES. 2 : there will be no %s. Set it as appropriate or ignore at will. */ int password_used; /** Set to the name of the connected client host, if it can be resolved, or to its IP address otherwise. */ const char *host_or_ip; /** Length of host_or_ip */ unsigned int host_or_ip_length; /** Current THD pointer (to use with various services) */ MYSQL_THD thd; } MYSQL_SERVER_AUTH_INFO; /** Server authentication plugin descriptor */ struct st_mysql_auth { int interface_version; /**< version plugin uses */ /** A plugin that a client must use for authentication with this server plugin. Can be NULL to mean "any plugin". */ const char *client_auth_plugin; /** Function provided by the plugin which should perform authentication (using the vio functions if necessary) and return 0 if successful. The plugin can also fill the info.authenticated_as field if a different username should be used for authorization. */ int (*authenticate_user)(MYSQL_PLUGIN_VIO *vio, MYSQL_SERVER_AUTH_INFO *info); /** Create a password hash (or digest) out of a plain-text password Used in SET PASSWORD, GRANT, and CREATE USER to convert user specified plain-text password into a value that will be stored in mysql.user table. @see preprocess_hash @param password plain-text password @param password_length plain-text password length @param hash the digest will be stored there @param hash_length in: hash buffer size out: the actual length of the hash @return 0 for ok, 1 for error Can be NULL, in this case one will not be able to use SET PASSWORD or PASSWORD('...') in GRANT, CREATE USER, ALTER USER. */ int (*hash_password)(const char *password, size_t password_length, char *hash, size_t *hash_length); /** Prepare the password hash for authentication. Password hash is stored in the authentication_string column of the mysql.user table in a text form. If a plugin needs to preprocess the value somehow before the authentication (e.g. convert from hex or base64 to binary), it can do it in this method. This way the conversion will happen only once, not for every authentication attempt. The value written to the out buffer will be cached and later made available to the authenticate_user() method in the MYSQL_SERVER_AUTH_INFO::auth_string[] buffer. @return 0 for ok, 1 for error Can be NULL, in this case the mysql.user.authentication_string value will be given to the authenticate_user() method as is, unconverted. */ int (*preprocess_hash)(const char *hash, size_t hash_length, unsigned char *out, size_t *out_length); }; #ifdef __cplusplus } #endif #endif mysql/server/mysql/plugin.h000064400000072306151027430560012046 0ustar00/* Copyright (c) 2005, 2013, Oracle and/or its affiliates Copyright (C) 2009, 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_PLUGIN_INCLUDED #define MYSQL_PLUGIN_INCLUDED /* On Windows, exports from DLL need to be declared Also, plugin needs to be declared as extern "C" because MSVC unlike other compilers, uses C++ mangling for variables not only for functions. */ #ifdef MYSQL_DYNAMIC_PLUGIN #ifdef _MSC_VER #define MYSQL_DLLEXPORT _declspec(dllexport) #else #define MYSQL_DLLEXPORT #endif #else #define MYSQL_DLLEXPORT #endif #ifdef __cplusplus #define MYSQL_PLUGIN_EXPORT extern "C" MYSQL_DLLEXPORT #else #define MYSQL_PLUGIN_EXPORT MYSQL_DLLEXPORT #endif #ifdef __cplusplus class THD; class Item; #define MYSQL_THD THD* #else struct THD; typedef struct THD* MYSQL_THD; #endif typedef char my_bool; typedef void * MYSQL_PLUGIN; #include #define MYSQL_XIDDATASIZE 128 /** struct st_mysql_xid is binary compatible with the XID structure as in the X/Open CAE Specification, Distributed Transaction Processing: The XA Specification, X/Open Company Ltd., 1991. http://www.opengroup.org/bookstore/catalog/c193.htm @see XID in sql/handler.h */ struct st_mysql_xid { long formatID; long gtrid_length; long bqual_length; char data[MYSQL_XIDDATASIZE]; /* Not \0-terminated */ }; typedef struct st_mysql_xid MYSQL_XID; /************************************************************************* Plugin API. Common for all plugin types. */ /* MySQL plugin interface version */ #define MYSQL_PLUGIN_INTERFACE_VERSION 0x0104 /* MariaDB plugin interface version */ #define MARIA_PLUGIN_INTERFACE_VERSION 0x010e /* The allowable types of plugins */ #define MYSQL_UDF_PLUGIN 0 /* not implemented */ #define MYSQL_STORAGE_ENGINE_PLUGIN 1 #define MYSQL_FTPARSER_PLUGIN 2 /* Full-text parser plugin */ #define MYSQL_DAEMON_PLUGIN 3 #define MYSQL_INFORMATION_SCHEMA_PLUGIN 4 #define MYSQL_AUDIT_PLUGIN 5 #define MYSQL_REPLICATION_PLUGIN 6 #define MYSQL_AUTHENTICATION_PLUGIN 7 #define MYSQL_MAX_PLUGIN_TYPE_NUM 12 /* The number of plugin types */ /* MariaDB plugin types */ #define MariaDB_PASSWORD_VALIDATION_PLUGIN 8 #define MariaDB_ENCRYPTION_PLUGIN 9 #define MariaDB_DATA_TYPE_PLUGIN 10 #define MariaDB_FUNCTION_PLUGIN 11 /* We use the following strings to define licenses for plugins */ #define PLUGIN_LICENSE_PROPRIETARY 0 #define PLUGIN_LICENSE_GPL 1 #define PLUGIN_LICENSE_BSD 2 #define PLUGIN_LICENSE_PROPRIETARY_STRING "PROPRIETARY" #define PLUGIN_LICENSE_GPL_STRING "GPL" #define PLUGIN_LICENSE_BSD_STRING "BSD" /* definitions of code maturity for plugins */ #define MariaDB_PLUGIN_MATURITY_UNKNOWN 0 #define MariaDB_PLUGIN_MATURITY_EXPERIMENTAL 1 #define MariaDB_PLUGIN_MATURITY_ALPHA 2 #define MariaDB_PLUGIN_MATURITY_BETA 3 #define MariaDB_PLUGIN_MATURITY_GAMMA 4 #define MariaDB_PLUGIN_MATURITY_STABLE 5 /* Macros for beginning and ending plugin declarations. Between mysql_declare_plugin and mysql_declare_plugin_end there should be a st_mysql_plugin struct for each plugin to be declared. */ #ifndef MYSQL_DYNAMIC_PLUGIN #define __MYSQL_DECLARE_PLUGIN(NAME, VERSION, PSIZE, DECLS) \ int VERSION= MYSQL_PLUGIN_INTERFACE_VERSION; \ int PSIZE= sizeof(struct st_mysql_plugin); \ struct st_mysql_plugin DECLS[]= { #define MARIA_DECLARE_PLUGIN__(NAME, VERSION, PSIZE, DECLS) \ MYSQL_PLUGIN_EXPORT int VERSION; \ int VERSION= MARIA_PLUGIN_INTERFACE_VERSION; \ MYSQL_PLUGIN_EXPORT int PSIZE; \ int PSIZE= sizeof(struct st_maria_plugin); \ MYSQL_PLUGIN_EXPORT struct st_maria_plugin DECLS[]; \ struct st_maria_plugin DECLS[]= { #else #define __MYSQL_DECLARE_PLUGIN(NAME, VERSION, PSIZE, DECLS) \ MYSQL_PLUGIN_EXPORT int _mysql_plugin_interface_version_; \ int _mysql_plugin_interface_version_= MYSQL_PLUGIN_INTERFACE_VERSION; \ MYSQL_PLUGIN_EXPORT int _mysql_sizeof_struct_st_plugin_; \ int _mysql_sizeof_struct_st_plugin_= sizeof(struct st_mysql_plugin); \ MYSQL_PLUGIN_EXPORT struct st_mysql_plugin _mysql_plugin_declarations_[]; \ struct st_mysql_plugin _mysql_plugin_declarations_[]= { #define MARIA_DECLARE_PLUGIN__(NAME, VERSION, PSIZE, DECLS) \ MYSQL_PLUGIN_EXPORT int _maria_plugin_interface_version_; \ int _maria_plugin_interface_version_= MARIA_PLUGIN_INTERFACE_VERSION; \ MYSQL_PLUGIN_EXPORT int _maria_sizeof_struct_st_plugin_; \ int _maria_sizeof_struct_st_plugin_= sizeof(struct st_maria_plugin); \ MYSQL_PLUGIN_EXPORT struct st_maria_plugin _maria_plugin_declarations_[]; \ struct st_maria_plugin _maria_plugin_declarations_[]= { #endif #define mysql_declare_plugin(NAME) \ __MYSQL_DECLARE_PLUGIN(NAME, \ builtin_ ## NAME ## _plugin_interface_version, \ builtin_ ## NAME ## _sizeof_struct_st_plugin, \ builtin_ ## NAME ## _plugin) #define maria_declare_plugin(NAME) \ MARIA_DECLARE_PLUGIN__(NAME, \ builtin_maria_ ## NAME ## _plugin_interface_version, \ builtin_maria_ ## NAME ## _sizeof_struct_st_plugin, \ builtin_maria_ ## NAME ## _plugin) #define mysql_declare_plugin_end ,{0,0,0,0,0,0,0,0,0,0,0,0,0}} #define maria_declare_plugin_end ,{0,0,0,0,0,0,0,0,0,0,0,0,0}} /* declarations for SHOW STATUS support in plugins */ enum enum_mysql_show_type { SHOW_UNDEF, SHOW_BOOL, SHOW_UINT, SHOW_ULONG, SHOW_ULONGLONG, SHOW_CHAR, SHOW_CHAR_PTR, SHOW_ARRAY, SHOW_FUNC, SHOW_DOUBLE, SHOW_SINT, SHOW_SLONG, SHOW_SLONGLONG, SHOW_SIMPLE_FUNC, SHOW_SIZE_T, SHOW_always_last }; /* backward compatibility mapping. */ #define SHOW_INT SHOW_UINT #define SHOW_LONG SHOW_ULONG #define SHOW_LONGLONG SHOW_ULONGLONG enum enum_var_type { SHOW_OPT_DEFAULT= 0, SHOW_OPT_SESSION, SHOW_OPT_GLOBAL }; struct st_mysql_show_var { const char *name; void *value; enum enum_mysql_show_type type; }; struct system_status_var; #define SHOW_VAR_FUNC_BUFF_SIZE (256 * sizeof(void*)) typedef int (*mysql_show_var_func)(MYSQL_THD, struct st_mysql_show_var*, void *, struct system_status_var *status_var, enum enum_var_type); static inline struct st_mysql_show_var SHOW_FUNC_ENTRY(const char *name, mysql_show_var_func func_arg) { struct st_mysql_show_var tmp; tmp.name= name; tmp.value= (void*) func_arg; tmp.type= SHOW_FUNC; return tmp; }; /* Constants for plugin flags. */ #define PLUGIN_OPT_NO_INSTALL 1UL /* Not dynamically loadable */ #define PLUGIN_OPT_NO_UNINSTALL 2UL /* Not dynamically unloadable */ /* declarations for server variables and command line options */ #define PLUGIN_VAR_BOOL 0x0001 #define PLUGIN_VAR_INT 0x0002 #define PLUGIN_VAR_LONG 0x0003 #define PLUGIN_VAR_LONGLONG 0x0004 #define PLUGIN_VAR_STR 0x0005 #define PLUGIN_VAR_ENUM 0x0006 #define PLUGIN_VAR_SET 0x0007 #define PLUGIN_VAR_DOUBLE 0x0008 #define PLUGIN_VAR_UNSIGNED 0x0080 #define PLUGIN_VAR_THDLOCAL 0x0100 /* Variable is per-connection */ #define PLUGIN_VAR_READONLY 0x0200 /* Server variable is read only */ #define PLUGIN_VAR_NOSYSVAR 0x0400 /* Not a server variable */ #define PLUGIN_VAR_NOCMDOPT 0x0800 /* Not a command line option */ #define PLUGIN_VAR_NOCMDARG 0x1000 /* No argument for cmd line */ #define PLUGIN_VAR_RQCMDARG 0x0000 /* Argument required for cmd line */ #define PLUGIN_VAR_OPCMDARG 0x2000 /* Argument optional for cmd line */ #define PLUGIN_VAR_DEPRECATED 0x4000 /* Server variable is deprecated */ #define PLUGIN_VAR_MEMALLOC 0x8000 /* String needs memory allocated */ struct st_mysql_sys_var; struct st_mysql_value; /* SYNOPSIS (*mysql_var_check_func)() thd thread handle var dynamic variable being altered save pointer to temporary storage value user provided value RETURN 0 user provided value is OK and the update func may be called. any other value indicates error. This function should parse the user provided value and store in the provided temporary storage any data as required by the update func. There is sufficient space in the temporary storage to store a double. Note that the update func may not be called if any other error occurs so any memory allocated should be thread-local so that it may be freed automatically at the end of the statement. */ typedef int (*mysql_var_check_func)(MYSQL_THD thd, struct st_mysql_sys_var *var, void *save, struct st_mysql_value *value); /* SYNOPSIS (*mysql_var_update_func)() thd thread handle var dynamic variable being altered var_ptr pointer to dynamic variable save pointer to temporary storage RETURN NONE This function should use the validated value stored in the temporary store and persist it in the provided pointer to the dynamic variable. For example, strings may require memory to be allocated. */ typedef void (*mysql_var_update_func)(MYSQL_THD thd, struct st_mysql_sys_var *var, void *var_ptr, const void *save); /* the following declarations are for internal use only */ #define PLUGIN_VAR_MASK \ (PLUGIN_VAR_READONLY | PLUGIN_VAR_NOSYSVAR | \ PLUGIN_VAR_NOCMDOPT | PLUGIN_VAR_NOCMDARG | \ PLUGIN_VAR_OPCMDARG | PLUGIN_VAR_RQCMDARG | \ PLUGIN_VAR_DEPRECATED | PLUGIN_VAR_MEMALLOC) #define MYSQL_PLUGIN_VAR_HEADER \ int flags; \ const char *name; \ const char *comment; \ mysql_var_check_func check; \ mysql_var_update_func update #define MYSQL_SYSVAR_NAME(name) mysql_sysvar_ ## name #define MYSQL_SYSVAR(name) \ ((struct st_mysql_sys_var *)&(MYSQL_SYSVAR_NAME(name))) /* for global variables, the value pointer is the first element after the header, the default value is the second. for thread variables, the value offset is the first element after the header, the default value is the second. */ #define DECLARE_MYSQL_SYSVAR_BASIC(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ type *value; \ const type def_val; \ } MYSQL_SYSVAR_NAME(name) #define DECLARE_MYSQL_SYSVAR_CONST_BASIC(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ const type *value; \ const type def_val; \ } MYSQL_SYSVAR_NAME(name) #define DECLARE_MYSQL_SYSVAR_SIMPLE(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ type *value; type def_val; \ type min_val; type max_val; \ type blk_sz; \ } MYSQL_SYSVAR_NAME(name) #define DECLARE_MYSQL_SYSVAR_TYPELIB(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ type *value; type def_val; \ TYPELIB *typelib; \ } MYSQL_SYSVAR_NAME(name) #define DECLARE_THDVAR_FUNC(type) \ type *(*resolve)(MYSQL_THD thd, int offset) #define DECLARE_MYSQL_THDVAR_BASIC(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ int offset; \ const type def_val; \ DECLARE_THDVAR_FUNC(type); \ } MYSQL_SYSVAR_NAME(name) #define DECLARE_MYSQL_THDVAR_SIMPLE(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ int offset; \ type def_val; type min_val; \ type max_val; type blk_sz; \ DECLARE_THDVAR_FUNC(type); \ } MYSQL_SYSVAR_NAME(name) #define DECLARE_MYSQL_THDVAR_TYPELIB(name, type) struct { \ MYSQL_PLUGIN_VAR_HEADER; \ int offset; \ const type def_val; \ DECLARE_THDVAR_FUNC(type); \ TYPELIB *typelib; \ } MYSQL_SYSVAR_NAME(name) /* the following declarations are for use by plugin implementors */ #define MYSQL_SYSVAR_BOOL(name, varname, opt, comment, check, update, def) \ DECLARE_MYSQL_SYSVAR_BASIC(name, char) = { \ PLUGIN_VAR_BOOL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def} #define MYSQL_SYSVAR_STR(name, varname, opt, comment, check, update, def) \ DECLARE_MYSQL_SYSVAR_BASIC(name, char *) = { \ PLUGIN_VAR_STR | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def} #define MYSQL_SYSVAR_CONST_STR(name, varname, opt, comment, check, update, def) \ DECLARE_MYSQL_SYSVAR_CONST_BASIC(name, char *) = { \ PLUGIN_VAR_STR | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def} #define MYSQL_SYSVAR_INT(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, int) = { \ PLUGIN_VAR_INT | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_SYSVAR_UINT(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, unsigned int) = { \ PLUGIN_VAR_INT | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_SYSVAR_LONG(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, long) = { \ PLUGIN_VAR_LONG | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_SYSVAR_ULONG(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, unsigned long) = { \ PLUGIN_VAR_LONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_SYSVAR_LONGLONG(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, long long) = { \ PLUGIN_VAR_LONGLONG | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_SYSVAR_ULONGLONG(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, unsigned long long) = { \ PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_SYSVAR_UINT64_T(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, uint64_t) = { \ PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #ifdef _WIN64 #define MYSQL_SYSVAR_SIZE_T(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, size_t) = { \ PLUGIN_VAR_LONGLONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #else #define MYSQL_SYSVAR_SIZE_T(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, size_t) = { \ PLUGIN_VAR_LONG | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #endif #define MYSQL_SYSVAR_ENUM(name, varname, opt, comment, check, update, def, typelib) \ DECLARE_MYSQL_SYSVAR_TYPELIB(name, unsigned long) = { \ PLUGIN_VAR_ENUM | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, typelib } #define MYSQL_SYSVAR_SET(name, varname, opt, comment, check, update, def, typelib) \ DECLARE_MYSQL_SYSVAR_TYPELIB(name, unsigned long long) = { \ PLUGIN_VAR_SET | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, typelib } #define MYSQL_SYSVAR_DOUBLE(name, varname, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_SYSVAR_SIMPLE(name, double) = { \ PLUGIN_VAR_DOUBLE | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, &varname, def, min, max, blk } #define MYSQL_THDVAR_BOOL(name, opt, comment, check, update, def) \ DECLARE_MYSQL_THDVAR_BASIC(name, char) = { \ PLUGIN_VAR_BOOL | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, NULL} #define MYSQL_THDVAR_STR(name, opt, comment, check, update, def) \ DECLARE_MYSQL_THDVAR_BASIC(name, char *) = { \ PLUGIN_VAR_STR | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, NULL} #define MYSQL_THDVAR_INT(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, int) = { \ PLUGIN_VAR_INT | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } #define MYSQL_THDVAR_UINT(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, unsigned int) = { \ PLUGIN_VAR_INT | PLUGIN_VAR_THDLOCAL | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } #define MYSQL_THDVAR_LONG(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, long) = { \ PLUGIN_VAR_LONG | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } #define MYSQL_THDVAR_ULONG(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, unsigned long) = { \ PLUGIN_VAR_LONG | PLUGIN_VAR_THDLOCAL | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } #define MYSQL_THDVAR_LONGLONG(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, long long) = { \ PLUGIN_VAR_LONGLONG | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } #define MYSQL_THDVAR_ULONGLONG(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, unsigned long long) = { \ PLUGIN_VAR_LONGLONG | PLUGIN_VAR_THDLOCAL | PLUGIN_VAR_UNSIGNED | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } #define MYSQL_THDVAR_ENUM(name, opt, comment, check, update, def, typelib) \ DECLARE_MYSQL_THDVAR_TYPELIB(name, unsigned long) = { \ PLUGIN_VAR_ENUM | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, NULL, typelib } #define MYSQL_THDVAR_SET(name, opt, comment, check, update, def, typelib) \ DECLARE_MYSQL_THDVAR_TYPELIB(name, unsigned long long) = { \ PLUGIN_VAR_SET | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, NULL, typelib } #define MYSQL_THDVAR_DOUBLE(name, opt, comment, check, update, def, min, max, blk) \ DECLARE_MYSQL_THDVAR_SIMPLE(name, double) = { \ PLUGIN_VAR_DOUBLE | PLUGIN_VAR_THDLOCAL | ((opt) & PLUGIN_VAR_MASK), \ #name, comment, check, update, -1, def, min, max, blk, NULL } /* accessor macros */ #define SYSVAR(name) \ (*(MYSQL_SYSVAR_NAME(name).value)) /* when thd == null, result points to global value */ #define THDVAR(thd, name) \ (*(MYSQL_SYSVAR_NAME(name).resolve(thd, MYSQL_SYSVAR_NAME(name).offset))) /* Plugin description structure. */ struct st_mysql_plugin { int type; /* the plugin type (a MYSQL_XXX_PLUGIN value) */ void *info; /* pointer to type-specific plugin descriptor */ const char *name; /* plugin name */ const char *author; /* plugin author (for I_S.PLUGINS) */ const char *descr; /* general descriptive text (for I_S.PLUGINS) */ int license; /* the plugin license (PLUGIN_LICENSE_XXX) */ /* The function to invoke when plugin is loaded. Plugin initialisation done here should defer any ALTER TABLE queries to after the ddl recovery is done, in the signal_ddl_recovery_done() callback called by ha_signal_ddl_recovery_done(). */ int (*init)(void *); int (*deinit)(void *);/* the function to invoke when plugin is unloaded */ unsigned int version; /* plugin version (for I_S.PLUGINS) */ struct st_mysql_show_var *status_vars; struct st_mysql_sys_var **system_vars; void * __reserved1; /* reserved for dependency checking */ unsigned long flags; /* flags for plugin */ }; /* MariaDB extension for plugins declaration structure. It also copy current MySQL plugin fields to have more independency in plugins extension */ struct st_maria_plugin { int type; /* the plugin type (a MYSQL_XXX_PLUGIN value) */ void *info; /* pointer to type-specific plugin descriptor */ const char *name; /* plugin name */ const char *author; /* plugin author (for SHOW PLUGINS) */ const char *descr; /* general descriptive text (for SHOW PLUGINS ) */ int license; /* the plugin license (PLUGIN_LICENSE_XXX) */ /* The function to invoke when plugin is loaded. Plugin initialisation done here should defer any ALTER TABLE queries to after the ddl recovery is done, in the signal_ddl_recovery_done() callback called by ha_signal_ddl_recovery_done(). */ int (*init)(void *); int (*deinit)(void *);/* the function to invoke when plugin is unloaded */ unsigned int version; /* plugin version (for SHOW PLUGINS) */ struct st_mysql_show_var *status_vars; struct st_mysql_sys_var **system_vars; const char *version_info; /* plugin version string */ unsigned int maturity; /* MariaDB_PLUGIN_MATURITY_XXX */ }; /************************************************************************* API for Full-text parser plugin. (MYSQL_FTPARSER_PLUGIN) */ #include "plugin_ftparser.h" /************************************************************************* API for Storage Engine plugin. (MYSQL_DAEMON_PLUGIN) */ /* handlertons of different MySQL releases are incompatible */ #define MYSQL_DAEMON_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) /* Here we define only the descriptor structure, that is referred from st_mysql_plugin. */ struct st_mysql_daemon { int interface_version; }; /************************************************************************* API for I_S plugin. (MYSQL_INFORMATION_SCHEMA_PLUGIN) */ /* handlertons of different MySQL releases are incompatible */ #define MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) /* Here we define only the descriptor structure, that is referred from st_mysql_plugin. */ struct st_mysql_information_schema { int interface_version; }; /************************************************************************* API for Storage Engine plugin. (MYSQL_STORAGE_ENGINE_PLUGIN) */ /* handlertons of different MySQL releases are incompatible */ #define MYSQL_HANDLERTON_INTERFACE_VERSION (MYSQL_VERSION_ID << 8) /* The real API is in the sql/handler.h Here we define only the descriptor structure, that is referred from st_mysql_plugin. */ struct st_mysql_storage_engine { int interface_version; }; struct handlerton; /* API for Replication plugin. (MYSQL_REPLICATION_PLUGIN) */ #define MYSQL_REPLICATION_INTERFACE_VERSION 0x0200 /** Replication plugin descriptor */ struct Mysql_replication { int interface_version; }; /************************************************************************* st_mysql_value struct for reading values from mysqld. Used by server variables framework to parse user-provided values. Will be used for arguments when implementing UDFs. Note that val_str() returns a string in temporary memory that will be freed at the end of statement. Copy the string if you need it to persist. */ #define MYSQL_VALUE_TYPE_STRING 0 #define MYSQL_VALUE_TYPE_REAL 1 #define MYSQL_VALUE_TYPE_INT 2 struct st_mysql_value { int (*value_type)(struct st_mysql_value *); const char *(*val_str)(struct st_mysql_value *, char *buffer, int *length); int (*val_real)(struct st_mysql_value *, double *realbuf); int (*val_int)(struct st_mysql_value *, long long *intbuf); int (*is_unsigned)(struct st_mysql_value *); }; /************************************************************************* Miscellaneous functions for plugin implementors */ #ifdef __cplusplus extern "C" { #endif int thd_in_lock_tables(const MYSQL_THD thd); int thd_tablespace_op(const MYSQL_THD thd); long long thd_test_options(const MYSQL_THD thd, long long test_options); int thd_sql_command(const MYSQL_THD thd); struct DDL_options_st; struct DDL_options_st *thd_ddl_options(const MYSQL_THD thd); void thd_storage_lock_wait(MYSQL_THD thd, long long value); int thd_tx_isolation(const MYSQL_THD thd); int thd_tx_is_read_only(const MYSQL_THD thd); /** Create a temporary file. @details The temporary file is created in a location specified by the mysql server configuration (--tmpdir option). The caller does not need to delete the file, it will be deleted automatically. @param prefix prefix for temporary file name @retval -1 error @retval >= 0 a file handle that can be passed to dup or my_close */ int mysql_tmpfile(const char *prefix); /** Return the thread id of a user thread @param thd user thread connection handle @return thread id */ unsigned long thd_get_thread_id(const MYSQL_THD thd); /** Get the XID for this connection's transaction @param thd user thread connection handle @param xid location where identifier is stored */ void thd_get_xid(const MYSQL_THD thd, MYSQL_XID *xid); /** Invalidate the query cache for a given table. @param thd user thread connection handle @param key databasename\\0tablename\\0 @param key_length length of key in bytes, including the NUL bytes @param using_trx flag: TRUE if using transactions, FALSE otherwise */ void mysql_query_cache_invalidate4(MYSQL_THD thd, const char *key, unsigned int key_length, int using_trx); /** Provide a handler data getter to simplify coding */ void *thd_get_ha_data(const MYSQL_THD thd, const struct handlerton *hton); /** Provide a handler data setter to simplify coding @details Set ha_data pointer (storage engine per-connection information). To avoid unclean deactivation (uninstall) of storage engine plugin in the middle of transaction, additional storage engine plugin lock is acquired. If ha_data is not null and storage engine plugin was not locked by thd_set_ha_data() in this connection before, storage engine plugin gets locked. If ha_data is null and storage engine plugin was locked by thd_set_ha_data() in this connection before, storage engine plugin lock gets released. If handlerton::close_connection() didn't reset ha_data, server does it immediately after calling handlerton::close_connection(). */ void thd_set_ha_data(MYSQL_THD thd, const struct handlerton *hton, const void *ha_data); /** Signal that the first part of handler commit is finished, and that the committed transaction is now visible and has fixed commit ordering with respect to other transactions. The commit need _not_ be durable yet, and typically will not be when this call makes sense. This call is optional, if the storage engine does not call it the upper layer will after the handler commit() method is done. However, the storage engine may choose to call it itself to increase the possibility for group commit. In-order parallel replication uses this to apply different transaction in parallel, but delay the commits of later transactions until earlier transactions have committed first, thus achieving increased performance on multi-core systems while still preserving full transaction consistency. The storage engine can call this from within the commit() method, typically after the commit record has been written to the transaction log, but before the log has been fsync()'ed. This will allow the next replicated transaction to proceed to commit before the first one has done fsync() or similar. Thus, it becomes possible for multiple sequential replicated transactions to share a single fsync() inside the engine in group commit. Note that this method should _not_ be called from within the commit_ordered() method, or any other place in the storage engine. When commit_ordered() is used (typically when binlog is enabled), the transaction coordinator takes care of this and makes group commit in the storage engine possible without any other action needed on the part of the storage engine. This function thd_wakeup_subsequent_commits() is only needed when no transaction coordinator is used, meaning a single storage engine and no binary log. */ void thd_wakeup_subsequent_commits(MYSQL_THD thd, int wakeup_error); #ifdef __cplusplus } #endif #endif mysql/server/mysql/service_log_warnings.h000064400000002541151027430560014753 0ustar00/* Copyright (c) 2013, 2018, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_SERVICE_LOG_WARNINGS #define MYSQL_SERVICE_LOG_WARNINGS /** @file This service provides access to the log warning level for the current session. thd_log_warnings(thd) @return thd->log_warnings */ #ifdef __cplusplus extern "C" { #endif extern struct thd_log_warnings_service_st { void *(*thd_log_warnings)(MYSQL_THD); } *thd_log_warnings_service; #ifdef MYSQL_DYNAMIC_PLUGIN # define thd_log_warnings(THD) thd_log_warnings_service->thd_log_warnings(THD) #else /** MDL_context accessor @param thd the current session @return pointer to thd->mdl_context */ int thd_log_warnings(MYSQL_THD thd); #endif #ifdef __cplusplus } #endif #endif mysql/server/mysql/service_thd_timezone.h000064400000004363151027430560014757 0ustar00#ifndef MYSQL_SERVICE_THD_TIMEZONE_INCLUDED /* Copyright (C) 2013 MariaDB Foundation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This service provides functions to convert between my_time_t and MYSQL_TIME taking into account the current value of the time_zone session variable. The values of the my_time_t type are in Unix timestamp format, i.e. the number of seconds since "1970-01-01 00:00:00 UTC". The values of the MYSQL_TIME type are in the current time zone, according to thd->variables.time_zone. If the MYSQL_THD parameter is NULL, then global_system_variables.time_zone is used for conversion. */ #ifndef MYSQL_ABI_CHECK /* This service currently does not depend on any system headers. If it needs system headers in the future, make sure to put them inside this ifndef. */ #endif #include "mysql_time.h" #ifdef __cplusplus extern "C" { #endif extern struct thd_timezone_service_st { my_time_t (*thd_TIME_to_gmt_sec)(MYSQL_THD thd, const MYSQL_TIME *ltime, unsigned int *errcode); void (*thd_gmt_sec_to_TIME)(MYSQL_THD thd, MYSQL_TIME *ltime, my_time_t t); } *thd_timezone_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_TIME_to_gmt_sec(thd, ltime, errcode) \ (thd_timezone_service->thd_TIME_to_gmt_sec((thd), (ltime), (errcode))) #define thd_gmt_sec_to_TIME(thd, ltime, t) \ (thd_timezone_service->thd_gmt_sec_to_TIME((thd), (ltime), (t))) #else my_time_t thd_TIME_to_gmt_sec(MYSQL_THD thd, const MYSQL_TIME *ltime, unsigned int *errcode); void thd_gmt_sec_to_TIME(MYSQL_THD thd, MYSQL_TIME *ltime, my_time_t t); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_THD_TIMEZONE_INCLUDED #endif mysql/server/mysql/service_md5.h000064400000004107151027430560012747 0ustar00#ifndef MYSQL_SERVICE_MD5_INCLUDED /* Copyright (c) 2014, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file my md5 service Functions to calculate MD5 hash from a memory buffer */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #endif #define MY_MD5_HASH_SIZE 16 /* Hash size in bytes */ extern struct my_md5_service_st { void (*my_md5_type)(unsigned char*, const char*, size_t); void (*my_md5_multi_type)(unsigned char*, ...); size_t (*my_md5_context_size_type)(); void (*my_md5_init_type)(void *); void (*my_md5_input_type)(void *, const unsigned char *, size_t); void (*my_md5_result_type)(void *, unsigned char *); } *my_md5_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_md5(A,B,C) my_md5_service->my_md5_type(A,B,C) #define my_md5_multi my_md5_service->my_md5_multi_type #define my_md5_context_size() my_md5_service->my_md5_context_size_type() #define my_md5_init(A) my_md5_service->my_md5_init_type(A) #define my_md5_input(A,B,C) my_md5_service->my_md5_input_type(A,B,C) #define my_md5_result(A,B) my_md5_service->my_md5_result_type(A,B) #else void my_md5(unsigned char*, const char*, size_t); void my_md5_multi(unsigned char*, ...); size_t my_md5_context_size(); void my_md5_init(void *context); void my_md5_input(void *context, const unsigned char *buf, size_t len); void my_md5_result(void *context, unsigned char *digest); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_MD5_INCLUDED #endif mysql/server/mysql/service_wsrep.h000064400000033516151027430560013430 0ustar00#ifndef MYSQL_SERVICE_WSREP_INCLUDED #define MYSQL_SERVICE_WSREP_INCLUDED enum Wsrep_service_key_type { WSREP_SERVICE_KEY_SHARED, WSREP_SERVICE_KEY_REFERENCE, WSREP_SERVICE_KEY_UPDATE, WSREP_SERVICE_KEY_EXCLUSIVE }; #if (defined (MYSQL_DYNAMIC_PLUGIN) && defined(MYSQL_SERVICE_WSREP_DYNAMIC_INCLUDED)) || (!defined(MYSQL_DYNAMIC_PLUGIN) && defined(MYSQL_SERVICE_WSREP_STATIC_INCLUDED)) #else /* Copyright (c) 2015, 2020, MariaDB Corporation Ab 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file wsrep service Interface to WSREP functionality in the server. For engines that want to support galera. */ #include #ifdef __cplusplus #endif struct xid_t; struct wsrep_ws_handle; struct wsrep_buf; /* Must match to definition in sql/mysqld.h */ typedef int64 query_id_t; extern struct wsrep_service_st { my_bool (*get_wsrep_recovery_func)(); bool (*wsrep_consistency_check_func)(MYSQL_THD thd); int (*wsrep_is_wsrep_xid_func)(const void *xid); long long (*wsrep_xid_seqno_func)(const struct xid_t *xid); const unsigned char* (*wsrep_xid_uuid_func)(const struct xid_t *xid); my_bool (*wsrep_on_func)(const MYSQL_THD thd); bool (*wsrep_prepare_key_for_innodb_func)(MYSQL_THD thd, const unsigned char*, size_t, const unsigned char*, size_t, struct wsrep_buf*, size_t*); void (*wsrep_thd_LOCK_func)(const MYSQL_THD thd); int (*wsrep_thd_TRYLOCK_func)(const MYSQL_THD thd); void (*wsrep_thd_UNLOCK_func)(const MYSQL_THD thd); const char * (*wsrep_thd_query_func)(const MYSQL_THD thd); int (*wsrep_thd_retry_counter_func)(const MYSQL_THD thd); bool (*wsrep_thd_ignore_table_func)(MYSQL_THD thd); long long (*wsrep_thd_trx_seqno_func)(const MYSQL_THD thd); my_bool (*wsrep_thd_is_aborting_func)(const MYSQL_THD thd); void (*wsrep_set_data_home_dir_func)(const char *data_dir); my_bool (*wsrep_thd_is_BF_func)(const MYSQL_THD thd, my_bool sync); my_bool (*wsrep_thd_is_local_func)(const MYSQL_THD thd); void (*wsrep_thd_self_abort_func)(MYSQL_THD thd); int (*wsrep_thd_append_key_func)(MYSQL_THD thd, const struct wsrep_key* key, int n_keys, enum Wsrep_service_key_type); int (*wsrep_thd_append_table_key_func)(MYSQL_THD thd, const char* db, const char* table, enum Wsrep_service_key_type); my_bool (*wsrep_thd_is_local_transaction)(const MYSQL_THD thd); const char* (*wsrep_thd_client_state_str_func)(const MYSQL_THD thd); const char* (*wsrep_thd_client_mode_str_func)(const MYSQL_THD thd); const char* (*wsrep_thd_transaction_state_str_func)(const MYSQL_THD thd); query_id_t (*wsrep_thd_transaction_id_func)(const MYSQL_THD thd); my_bool (*wsrep_thd_bf_abort_func)(MYSQL_THD bf_thd, MYSQL_THD victim_thd, my_bool signal); my_bool (*wsrep_thd_order_before_func)(const MYSQL_THD left, const MYSQL_THD right); void (*wsrep_handle_SR_rollback_func)(MYSQL_THD BF_thd, MYSQL_THD victim_thd); my_bool (*wsrep_thd_skip_locking_func)(const MYSQL_THD thd); const char* (*wsrep_get_sr_table_name_func)(); my_bool (*wsrep_get_debug_func)(); void (*wsrep_commit_ordered_func)(MYSQL_THD thd); my_bool (*wsrep_thd_is_applying_func)(const MYSQL_THD thd); ulong (*wsrep_OSU_method_get_func)(const MYSQL_THD thd); my_bool (*wsrep_thd_has_ignored_error_func)(const MYSQL_THD thd); void (*wsrep_thd_set_ignored_error_func)(MYSQL_THD thd, my_bool val); void (*wsrep_report_bf_lock_wait_func)(const MYSQL_THD thd, unsigned long long trx_id); void (*wsrep_thd_kill_LOCK_func)(const MYSQL_THD thd); void (*wsrep_thd_kill_UNLOCK_func)(const MYSQL_THD thd); void (*wsrep_thd_set_wsrep_PA_unsafe_func)(MYSQL_THD thd); uint32 (*wsrep_get_domain_id_func)(); } *wsrep_service; #define MYSQL_SERVICE_WSREP_INCLUDED #endif #ifdef MYSQL_DYNAMIC_PLUGIN #define MYSQL_SERVICE_WSREP_DYNAMIC_INCLUDED #define get_wsrep_recovery() wsrep_service->get_wsrep_recovery_func() #define wsrep_consistency_check(T) wsrep_service->wsrep_consistency_check_func(T) #define wsrep_is_wsrep_xid(X) wsrep_service->wsrep_is_wsrep_xid_func(X) #define wsrep_xid_seqno(X) wsrep_service->wsrep_xid_seqno_func(X) #define wsrep_xid_uuid(X) wsrep_service->wsrep_xid_uuid_func(X) #define wsrep_on(thd) (thd) && WSREP_ON && wsrep_service->wsrep_on_func(thd) #define wsrep_prepare_key_for_innodb(A,B,C,D,E,F,G) wsrep_service->wsrep_prepare_key_for_innodb_func(A,B,C,D,E,F,G) #define wsrep_thd_LOCK(T) wsrep_service->wsrep_thd_LOCK_func(T) #define wsrep_thd_TRYLOCK(T) wsrep_service->wsrep_thd_TRYLOCK_func(T) #define wsrep_thd_UNLOCK(T) wsrep_service->wsrep_thd_UNLOCK_func(T) #define wsrep_thd_kill_LOCK(T) wsrep_service->wsrep_thd_kill_LOCK_func(T) #define wsrep_thd_kill_UNLOCK(T) wsrep_service->wsrep_thd_kill_UNLOCK_func(T) #define wsrep_thd_query(T) wsrep_service->wsrep_thd_query_func(T) #define wsrep_thd_retry_counter(T) wsrep_service->wsrep_thd_retry_counter_func(T) #define wsrep_thd_ignore_table(T) wsrep_service->wsrep_thd_ignore_table_func(T) #define wsrep_thd_trx_seqno(T) wsrep_service->wsrep_thd_trx_seqno_func(T) #define wsrep_set_data_home_dir(A) wsrep_service->wsrep_set_data_home_dir_func(A) #define wsrep_thd_is_BF(T,S) wsrep_service->wsrep_thd_is_BF_func(T,S) #define wsrep_thd_is_aborting(T) wsrep_service->wsrep_thd_is_aborting_func(T) #define wsrep_thd_is_local(T) wsrep_service->wsrep_thd_is_local_func(T) #define wsrep_thd_self_abort(T) wsrep_service->wsrep_thd_self_abort_func(T) #define wsrep_thd_append_key(T,W,N,K) wsrep_service->wsrep_thd_append_key_func(T,W,N,K) #define wsrep_thd_append_table_key(T,D,B,K) wsrep_service->wsrep_thd_append_table_key_func(T,D,B,K) #define wsrep_thd_is_local_transaction(T) wsrep_service->wsrep_thd_is_local_transaction_func(T) #define wsrep_thd_client_state_str(T) wsrep_service->wsrep_thd_client_state_str_func(T) #define wsrep_thd_client_mode_str(T) wsrep_service->wsrep_thd_client_mode_str_func(T) #define wsrep_thd_transaction_state_str(T) wsrep_service->wsrep_thd_transaction_state_str_func(T) #define wsrep_thd_transaction_id(T) wsrep_service->wsrep_thd_transaction_id_func(T) #define wsrep_thd_bf_abort(T,T2,S) wsrep_service->wsrep_thd_bf_abort_func(T,T2,S) #define wsrep_thd_order_before(L,R) wsrep_service->wsrep_thd_order_before_func(L,R) #define wsrep_handle_SR_rollback(B,V) wsrep_service->wsrep_handle_SR_rollback_func(B,V) #define wsrep_thd_skip_locking(T) wsrep_service->wsrep_thd_skip_locking_func(T) #define wsrep_get_sr_table_name() wsrep_service->wsrep_get_sr_table_name_func() #define wsrep_get_debug() wsrep_service->wsrep_get_debug_func() #define wsrep_commit_ordered(T) wsrep_service->wsrep_commit_ordered_func(T) #define wsrep_thd_is_applying(T) wsrep_service->wsrep_thd_is_applying_func(T) #define wsrep_OSU_method_get(T) wsrep_service->wsrep_OSU_method_get_func(T) #define wsrep_thd_has_ignored_error(T) wsrep_service->wsrep_thd_has_ignored_error_func(T) #define wsrep_thd_set_ignored_error(T,V) wsrep_service->wsrep_thd_set_ignored_error_func(T,V) #define wsrep_report_bf_lock_wait(T,I) wsrep_service->wsrep_report_bf_lock_wait(T,I) #define wsrep_thd_set_PA_unsafe(T) wsrep_service->wsrep_thd_set_PA_unsafe_func(T) #define wsrep_get_domain_id(T) wsrep_service->wsrep_get_domain_id_func(T) #else #define MYSQL_SERVICE_WSREP_STATIC_INCLUDED extern ulong wsrep_debug; extern my_bool wsrep_log_conflicts; extern my_bool wsrep_certify_nonPK; extern my_bool wsrep_load_data_splitting; extern my_bool wsrep_drupal_282555_workaround; extern my_bool wsrep_recovery; extern long wsrep_protocol_version; extern "C" bool wsrep_consistency_check(MYSQL_THD thd); bool wsrep_prepare_key_for_innodb(MYSQL_THD thd, const unsigned char* cache_key, size_t cache_key_len, const unsigned char* row_id, size_t row_id_len, struct wsrep_buf* key, size_t* key_len); extern "C" const char *wsrep_thd_query(const MYSQL_THD thd); extern "C" int wsrep_is_wsrep_xid(const void* xid); extern "C" long long wsrep_xid_seqno(const struct xid_t* xid); const unsigned char* wsrep_xid_uuid(const struct xid_t* xid); extern "C" long long wsrep_thd_trx_seqno(const MYSQL_THD thd); my_bool get_wsrep_recovery(); bool wsrep_thd_ignore_table(MYSQL_THD thd); void wsrep_set_data_home_dir(const char *data_dir); /* from mysql wsrep-lib */ #include "my_global.h" #include "my_pthread.h" /* Return true if wsrep is enabled for a thd. This means that wsrep is enabled globally and the thd has wsrep on */ extern "C" my_bool wsrep_on(const MYSQL_THD thd); /* Lock thd wsrep lock */ extern "C" void wsrep_thd_LOCK(const MYSQL_THD thd); /* Try thd wsrep lock. Return non-zero if lock could not be taken. */ extern "C" int wsrep_thd_TRYLOCK(const MYSQL_THD thd); /* Unlock thd wsrep lock */ extern "C" void wsrep_thd_UNLOCK(const MYSQL_THD thd); extern "C" void wsrep_thd_kill_LOCK(const MYSQL_THD thd); extern "C" void wsrep_thd_kill_UNLOCK(const MYSQL_THD thd); /* Return thd client state string */ extern "C" const char* wsrep_thd_client_state_str(const MYSQL_THD thd); /* Return thd client mode string */ extern "C" const char* wsrep_thd_client_mode_str(const MYSQL_THD thd); /* Return thd transaction state string */ extern "C" const char* wsrep_thd_transaction_state_str(const MYSQL_THD thd); /* Return current transaction id */ extern "C" query_id_t wsrep_thd_transaction_id(const MYSQL_THD thd); /* Mark thd own transaction as aborted */ extern "C" void wsrep_thd_self_abort(MYSQL_THD thd); /* Return true if thd is in replicating mode */ extern "C" my_bool wsrep_thd_is_local(const MYSQL_THD thd); /* Return true if thd is in high priority mode */ /* todo: rename to is_high_priority() */ extern "C" my_bool wsrep_thd_is_applying(const MYSQL_THD thd); /* Return true if thd is in TOI mode */ extern "C" my_bool wsrep_thd_is_toi(const MYSQL_THD thd); /* Return true if thd is in replicating TOI mode */ extern "C" my_bool wsrep_thd_is_local_toi(const MYSQL_THD thd); /* Return true if thd is in RSU mode */ extern "C" my_bool wsrep_thd_is_in_rsu(const MYSQL_THD thd); /* Return true if thd is in BF mode, either high_priority or TOI */ extern "C" my_bool wsrep_thd_is_BF(const MYSQL_THD thd, my_bool sync); /* Return true if thd is streaming in progress */ extern "C" my_bool wsrep_thd_is_SR(const MYSQL_THD thd); extern "C" void wsrep_handle_SR_rollback(MYSQL_THD BF_thd, MYSQL_THD victim_thd); /* Return thd retry counter */ extern "C" int wsrep_thd_retry_counter(const MYSQL_THD thd); /* BF abort victim_thd */ extern "C" my_bool wsrep_thd_bf_abort(MYSQL_THD bf_thd, MYSQL_THD victim_thd, my_bool signal); /* Return true if left thd is ordered before right thd */ extern "C" my_bool wsrep_thd_order_before(const MYSQL_THD left, const MYSQL_THD right); /* Return true if thd should skip locking. This means that the thd is operating on shared resource inside commit order critical section. */ extern "C" my_bool wsrep_thd_skip_locking(const MYSQL_THD thd); /* Return true if thd is aborting */ extern "C" my_bool wsrep_thd_is_aborting(const MYSQL_THD thd); struct wsrep_key; struct wsrep_key_array; extern "C" int wsrep_thd_append_key(MYSQL_THD thd, const struct wsrep_key* key, int n_keys, enum Wsrep_service_key_type); extern "C" int wsrep_thd_append_table_key(MYSQL_THD thd, const char* db, const char* table, enum Wsrep_service_key_type); extern "C" my_bool wsrep_thd_is_local_transaction(const MYSQL_THD thd); extern const char* wsrep_sr_table_name_full; extern "C" const char* wsrep_get_sr_table_name(); extern "C" my_bool wsrep_get_debug(); extern "C" void wsrep_commit_ordered(MYSQL_THD thd); extern "C" my_bool wsrep_thd_is_applying(const MYSQL_THD thd); extern "C" ulong wsrep_OSU_method_get(const MYSQL_THD thd); extern "C" my_bool wsrep_thd_has_ignored_error(const MYSQL_THD thd); extern "C" void wsrep_thd_set_ignored_error(MYSQL_THD thd, my_bool val); extern "C" void wsrep_report_bf_lock_wait(const THD *thd, unsigned long long trx_id); /* declare parallel applying unsafety for the THD */ extern "C" void wsrep_thd_set_PA_unsafe(MYSQL_THD thd); extern "C" uint32 wsrep_get_domain_id(); #endif #endif /* MYSQL_SERVICE_WSREP_INCLUDED */ mysql/server/mysql/service_thd_rnd.h000064400000003556151027430560013713 0ustar00#ifndef MYSQL_SERVICE_THD_RND_INCLUDED /* Copyright (C) 2017 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This service provides access to the thd-local random number generator. It's preferable over the global one, because concurrent threads can generate random numbers without fighting each other over the access to the shared rnd state. */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #endif extern struct thd_rnd_service_st { double (*thd_rnd_ptr)(MYSQL_THD thd); void (*thd_c_r_p_ptr)(MYSQL_THD thd, char *to, size_t length); } *thd_rnd_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_rnd(A) thd_rnd_service->thd_rnd_ptr(A) #define thd_create_random_password(A,B,C) thd_rnd_service->thd_c_r_p_ptr(A,B,C) #else double thd_rnd(MYSQL_THD thd); /** Generate string of printable random characters of requested length. @param to[out] Buffer for generation; must be at least length+1 bytes long; result string is always null-terminated @param length[in] How many random characters to put in buffer */ void thd_create_random_password(MYSQL_THD thd, char *to, size_t length); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_THD_RND_INCLUDED #endif mysql/server/mysql/service_logger.h000064400000006737151027430560013554 0ustar00/* Copyright (C) 2012 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_SERVICE_LOGGER_INCLUDED #define MYSQL_SERVICE_LOGGER_INCLUDED #ifndef MYSQL_ABI_CHECK #include #endif /** @file logger service Log file with rotation implementation. This service implements logging with possible rotation of the log files. Interface intentionally tries to be similar to FILE* related functions. So that one can open the log with logger_open(), specifying the limit on the logfile size and the rotations number. Then it's possible to write messages to the log with logger_printf or logger_vprintf functions. As the size of the logfile grows over the specified limit, it is renamed to 'logfile.1'. The former 'logfile.1' becomes 'logfile.2', etc. The file 'logfile.rotations' is removed. That's how the rotation works. The rotation can be forced with the logger_rotate() call. Finally the log should be closed with logger_close(). @notes: Implementation checks the size of the log file before it starts new printf into it. So the size of the file gets over the limit when it rotates. The access is secured with the mutex, so the log is threadsafe. */ #ifdef __cplusplus extern "C" { #endif typedef struct logger_handle_st LOGGER_HANDLE; extern struct logger_service_st { void (*logger_init_mutexes)(); LOGGER_HANDLE* (*open)(const char *path, unsigned long long size_limit, unsigned int rotations); int (*close)(LOGGER_HANDLE *log); int (*vprintf)(LOGGER_HANDLE *log, const char *fmt, va_list argptr); int (*printf)(LOGGER_HANDLE *log, const char *fmt, ...); int (*write)(LOGGER_HANDLE *log, const char *buffer, size_t size); int (*rotate)(LOGGER_HANDLE *log); } *logger_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define logger_init_mutexes logger_service->logger_init_mutexes #define logger_open(path, size_limit, rotations) \ (logger_service->open(path, size_limit, rotations)) #define logger_close(log) (logger_service->close(log)) #define logger_rotate(log) (logger_service->rotate(log)) #define logger_vprintf(log, fmt, argptr) (logger_service->\ vprintf(log, fmt, argptr)) #define logger_printf (*logger_service->printf) #define logger_write(log, buffer, size) \ (logger_service->write(log, buffer, size)) #else void logger_init_mutexes(); LOGGER_HANDLE *logger_open(const char *path, unsigned long long size_limit, unsigned int rotations); int logger_close(LOGGER_HANDLE *log); int logger_vprintf(LOGGER_HANDLE *log, const char *fmt, va_list argptr); int logger_printf(LOGGER_HANDLE *log, const char *fmt, ...); int logger_write(LOGGER_HANDLE *log, const char *buffer, size_t size); int logger_rotate(LOGGER_HANDLE *log); #endif #ifdef __cplusplus } #endif #endif /*MYSQL_SERVICE_LOGGER_INCLUDED*/ mysql/server/mysql/plugin_ftparser.h000064400000017230151027430560013747 0ustar00/* Copyright (c) 2005 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_plugin_ftparser_h #define _my_plugin_ftparser_h #include "plugin.h" #ifdef __cplusplus extern "C" { #endif /************************************************************************* API for Full-text parser plugin. (MYSQL_FTPARSER_PLUGIN) */ #define MYSQL_FTPARSER_INTERFACE_VERSION 0x0100 /* Parsing modes. Set in MYSQL_FTPARSER_PARAM::mode */ enum enum_ftparser_mode { /* Fast and simple mode. This mode is used for indexing, and natural language queries. The parser is expected to return only those words that go into the index. Stopwords or too short/long words should not be returned. The 'boolean_info' argument of mysql_add_word() does not have to be set. */ MYSQL_FTPARSER_SIMPLE_MODE= 0, /* Parse with stopwords mode. This mode is used in boolean searches for "phrase matching." The parser is not allowed to ignore words in this mode. Every word should be returned, including stopwords and words that are too short or long. The 'boolean_info' argument of mysql_add_word() does not have to be set. */ MYSQL_FTPARSER_WITH_STOPWORDS= 1, /* Parse in boolean mode. This mode is used to parse a boolean query string. The parser should provide a valid MYSQL_FTPARSER_BOOLEAN_INFO structure in the 'boolean_info' argument to mysql_add_word(). Usually that means that the parser should recognize boolean operators in the parsing stream and set appropriate fields in MYSQL_FTPARSER_BOOLEAN_INFO structure accordingly. As for MYSQL_FTPARSER_WITH_STOPWORDS mode, no word should be ignored. Instead, use FT_TOKEN_STOPWORD for the token type of such a word. */ MYSQL_FTPARSER_FULL_BOOLEAN_INFO= 2 }; /* Token types for boolean mode searching (used for the type member of MYSQL_FTPARSER_BOOLEAN_INFO struct) FT_TOKEN_EOF: End of data. FT_TOKEN_WORD: Regular word. FT_TOKEN_LEFT_PAREN: Left parenthesis (start of group/sub-expression). FT_TOKEN_RIGHT_PAREN: Right parenthesis (end of group/sub-expression). FT_TOKEN_STOPWORD: Stopword. */ enum enum_ft_token_type { FT_TOKEN_EOF= 0, FT_TOKEN_WORD= 1, FT_TOKEN_LEFT_PAREN= 2, FT_TOKEN_RIGHT_PAREN= 3, FT_TOKEN_STOPWORD= 4 }; /* This structure is used in boolean search mode only. It conveys boolean-mode metadata to the MySQL search engine for every word in the search query. A valid instance of this structure must be filled in by the plugin parser and passed as an argument in the call to mysql_add_word (the callback function in the MYSQL_FTPARSER_PARAM structure) when a query is parsed in boolean mode. type: The token type. Should be one of the enum_ft_token_type values. yesno: Whether the word must be present for a match to occur: >0 Must be present <0 Must not be present 0 Neither; the word is optional but its presence increases the relevance With the default settings of the ft_boolean_syntax system variable, >0 corresponds to the '+' operator, <0 corresponds to the '-' operator, and 0 means neither operator was used. weight_adjust: A weighting factor that determines how much a match for the word counts. Positive values increase, negative - decrease the relative word's importance in the query. wasign: The sign of the word's weight in the query. If it's non-negative the match for the word will increase document relevance, if it's negative - decrease (the word becomes a "noise word", the less of it the better). trunc: Corresponds to the '*' operator in the default setting of the ft_boolean_syntax system variable. */ typedef struct st_mysql_ftparser_boolean_info { enum enum_ft_token_type type; int yesno; int weight_adjust; char wasign; char trunc; /* These are parser state and must be removed. */ char prev; char *quot; } MYSQL_FTPARSER_BOOLEAN_INFO; /* The following flag means that buffer with a string (document, word) may be overwritten by the caller before the end of the parsing (that is before st_mysql_ftparser::deinit() call). If one needs the string to survive between two successive calls of the parsing function, she needs to save a copy of it. The flag may be set by MySQL before calling st_mysql_ftparser::parse(), or it may be set by a plugin before calling st_mysql_ftparser_param::mysql_parse() or st_mysql_ftparser_param::mysql_add_word(). */ #define MYSQL_FTFLAGS_NEED_COPY 1 /* An argument of the full-text parser plugin. This structure is filled in by MySQL server and passed to the parsing function of the plugin as an in/out parameter. mysql_parse: A pointer to the built-in parser implementation of the server. It's set by the server and can be used by the parser plugin to invoke the MySQL default parser. If plugin's role is to extract textual data from .doc, .pdf or .xml content, it might extract plaintext from the content, and then pass the text to the default MySQL parser to be parsed. mysql_add_word: A server callback to add a new word. When parsing a document, the server sets this to point at a function that adds the word to MySQL full-text index. When parsing a search query, this function will add the new word to the list of words to search for. The boolean_info argument can be NULL for all cases except when mode is MYSQL_FTPARSER_FULL_BOOLEAN_INFO. A plugin can replace this callback to post-process every parsed word before passing it to the original mysql_add_word function. ftparser_state: A generic pointer. The plugin can set it to point to information to be used internally for its own purposes. mysql_ftparam: This is set by the server. It is used by MySQL functions called via mysql_parse() and mysql_add_word() callback. The plugin should not modify it. cs: Information about the character set of the document or query string. doc: A pointer to the document or query string to be parsed. length: Length of the document or query string, in bytes. flags: See MYSQL_FTFLAGS_* constants above. mode: The parsing mode. With boolean operators, with stopwords, or nothing. See enum_ftparser_mode above. */ typedef struct st_mysql_ftparser_param { int (*mysql_parse)(struct st_mysql_ftparser_param *, const char *doc, int doc_len); int (*mysql_add_word)(struct st_mysql_ftparser_param *, const char *word, int word_len, MYSQL_FTPARSER_BOOLEAN_INFO *boolean_info); void *ftparser_state; void *mysql_ftparam; const struct charset_info_st *cs; const char *doc; int length; unsigned int flags; enum enum_ftparser_mode mode; } MYSQL_FTPARSER_PARAM; /* Full-text parser descriptor. interface_version is, e.g., MYSQL_FTPARSER_INTERFACE_VERSION. The parsing, initialization, and deinitialization functions are invoked per SQL statement for which the parser is used. */ struct st_mysql_ftparser { int interface_version; int (*parse)(MYSQL_FTPARSER_PARAM *param); int (*init)(MYSQL_FTPARSER_PARAM *param); int (*deinit)(MYSQL_FTPARSER_PARAM *param); }; #ifdef __cplusplus } #endif #endif mysql/server/mysql/service_sql.h000064400000012016151027430560013057 0ustar00/* Copyright (C) 2021 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #ifndef MYSQL_SERVICE_SQL #define MYSQL_SERVICE_SQL #ifndef MYSQL_ABI_CHECK #include #endif /** @file SQL service Interface for plugins to execute SQL queries on the local server. Functions of the service are the 'server-limited' client library: mysql_init mysql_real_connect_local mysql_real_connect mysql_errno mysql_error mysql_real_query mysql_affected_rows mysql_num_rows mysql_store_result mysql_free_result mysql_fetch_row mysql_close */ #ifdef __cplusplus extern "C" { #endif extern struct sql_service_st { MYSQL *(STDCALL *mysql_init_func)(MYSQL *mysql); MYSQL *(*mysql_real_connect_local_func)(MYSQL *mysql); MYSQL *(STDCALL *mysql_real_connect_func)(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); unsigned int(STDCALL *mysql_errno_func)(MYSQL *mysql); const char *(STDCALL *mysql_error_func)(MYSQL *mysql); int (STDCALL *mysql_real_query_func)(MYSQL *mysql, const char *q, unsigned long length); my_ulonglong (STDCALL *mysql_affected_rows_func)(MYSQL *mysql); my_ulonglong (STDCALL *mysql_num_rows_func)(MYSQL_RES *res); MYSQL_RES *(STDCALL *mysql_store_result_func)(MYSQL *mysql); void (STDCALL *mysql_free_result_func)(MYSQL_RES *result); MYSQL_ROW (STDCALL *mysql_fetch_row_func)(MYSQL_RES *result); void (STDCALL *mysql_close_func)(MYSQL *mysql); int (STDCALL *mysql_options_func)(MYSQL *mysql, enum mysql_option option, const void *arg); unsigned long *(STDCALL *mysql_fetch_lengths_func)(MYSQL_RES *res); int (STDCALL *mysql_set_character_set_func)(MYSQL *mysql, const char *cs_name); unsigned int (STDCALL *mysql_num_fields_func)(MYSQL_RES *res); int (STDCALL *mysql_select_db_func)(MYSQL *mysql, const char *db); MYSQL_RES *(STDCALL *mysql_use_result_func)(MYSQL *mysql); MYSQL_FIELD *(STDCALL *mysql_fetch_fields_func)(MYSQL_RES *res); unsigned long (STDCALL *mysql_real_escape_string_func)(MYSQL *mysql, char *to, const char *from, unsigned long length); my_bool (STDCALL *mysql_ssl_set_func)(MYSQL *mysql, const char *key, const char *cert, const char *ca, const char *capath, const char *cipher); } *sql_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define mysql_init(M) sql_service->mysql_init_func(M) #define mysql_real_connect_local(M) sql_service->mysql_real_connect_local_func(M) #define mysql_real_connect(M,H,U,PW,D,P,S,F) sql_service->mysql_real_connect_func(M,H,U,PW,D,P,S,F) #define mysql_errno(M) sql_service->mysql_errno_func(M) #define mysql_error(M) sql_service->mysql_error_func(M) #define mysql_real_query sql_service->mysql_real_query_func #define mysql_affected_rows(M) sql_service->mysql_affected_rows_func(M) #define mysql_num_rows(R) sql_service->mysql_num_rows_func(R) #define mysql_store_result(M) sql_service->mysql_store_result_func(M) #define mysql_free_result(R) sql_service->mysql_free_result_func(R) #define mysql_fetch_row(R) sql_service->mysql_fetch_row_func(R) #define mysql_close(M) sql_service->mysql_close_func(M) #define mysql_options(M,O,V) sql_service->mysql_options_func(M,O,V) #define mysql_fetch_lengths(R) sql_service->mysql_fetch_lengths_func(R) #define mysql_set_character_set(M,C) sql_service->mysql_set_character_set_func(M,C) #define mysql_num_fields(R) sql_service->mysql_num_fields_func(R) #define mysql_select_db(M,D) sql_service->mysql_select_db_func(M,D) #define mysql_use_result(M) sql_service->mysql_use_result_func(M) #define mysql_fetch_fields(R) sql_service->mysql_fetch_fields_func(R) #define mysql_real_escape_string(M,T,F,L) sql_service->mysql_real_escape_string_func(M,T,F,L) #define mysql_ssl_set(M,K,C1,C2,C3,C4) sql_service->mysql_ssl_set_func(M,K,C1,C2,C3,C4) #else /* Establishes the connection to the 'local' server that started the plugin. Like the mysql_real_connect() does for the remote server. The established connection has no user/host associated to it, neither it has the current db, so the queries should have database/table name specified. */ MYSQL *mysql_real_connect_local(MYSQL *mysql); /* The rest of the function declarations must be taken from the mysql.h */ #endif /*MYSQL_DYNAMIC_PLUGIN*/ #ifdef __cplusplus } #endif #endif /*MYSQL_SERVICE_SQL */ mysql/server/mysql/service_my_print_error.h000064400000004430151027430560015333 0ustar00/* Copyright (c) 2016, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_SERVICE_MY_PRINT_ERROR_INCLUDED #define MYSQL_SERVICE_MY_PRINT_ERROR_INCLUDED /** @file include/mysql/service_my_print_error.h This service provides functions for plugins to report errors to client (without client, the errors are written to the error log). */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #include #endif #define ME_ERROR_LOG 64 /* Write the message to the error log */ #define ME_ERROR_LOG_ONLY 128 /* Write the error message to error log only */ #define ME_NOTE 1024 /* Not an error, just a note */ #define ME_WARNING 2048 /* Not an error, just a warning */ #define ME_FATAL 4096 /* Fatal statement error */ extern struct my_print_error_service_st { void (*my_error_func)(unsigned int nr, unsigned long MyFlags, ...); void (*my_printf_error_func)(unsigned int nr, const char *fmt, unsigned long MyFlags,...); void (*my_printv_error_func)(unsigned int error, const char *format, unsigned long MyFlags, va_list ap); } *my_print_error_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_error my_print_error_service->my_error_func #define my_printf_error my_print_error_service->my_printf_error_func #define my_printv_error(A,B,C,D) my_print_error_service->my_printv_error_func(A,B,C,D) #else extern void my_error(unsigned int nr, unsigned long MyFlags, ...); extern void my_printf_error(unsigned int my_err, const char *format, unsigned long MyFlags, ...); extern void my_printv_error(unsigned int error, const char *format, unsigned long MyFlags,va_list ap); #endif /* MYSQL_DYNAMIC_PLUGIN */ #ifdef __cplusplus } #endif #endif mysql/server/mysql/services.h000064400000003342151027430560012365 0ustar00#ifndef MYSQL_SERVICES_INCLUDED /* Copyright (c) 2009, 2010, Oracle and/or its affiliates. Copyright (c) 2012, 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef __cplusplus extern "C" { #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /*#include */ #include #ifdef __cplusplus } #endif #define MYSQL_SERVICES_INCLUDED #endif mysql/server/mysql/service_thd_mdl.h000064400000002402151027430560013671 0ustar00/* Copyright (c) 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once /** @file include/mysql/service_thd_mdl.h This service provides functions for plugins and storage engines to access metadata locks. */ #ifdef __cplusplus extern "C" { #endif extern struct thd_mdl_service_st { void *(*thd_mdl_context)(MYSQL_THD); } *thd_mdl_service; #ifdef MYSQL_DYNAMIC_PLUGIN # define thd_mdl_context(_THD) thd_mdl_service->thd_mdl_context(_THD) #else /** MDL_context accessor @param thd the current session @return pointer to thd->mdl_context */ void *thd_mdl_context(MYSQL_THD thd); #endif #ifdef __cplusplus } #endif mysql/server/mysql/psi/mysql_socket.h000064400000106615151027430560014061 0ustar00/* Copyright (c) 2010, 2023, Oracle and/or its affiliates. Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_SOCKET_H #define MYSQL_SOCKET_H /* For MY_STAT */ #include /* For my_chsize */ #include /* For socket api */ #ifdef _WIN32 #include #include #include #define SOCKBUF_T char #else #include #define SOCKBUF_T void #endif /** @file mysql/psi/mysql_socket.h [...] */ #include "mysql/psi/psi.h" #ifndef PSI_SOCKET_CALL #define PSI_SOCKET_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Socket_instrumentation Socket Instrumentation @ingroup Instrumentation_interface @{ */ /** @def mysql_socket_register(P1, P2, P3) Socket registration. */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_register(P1, P2, P3) \ inline_mysql_socket_register(P1, P2, P3) #else #define mysql_socket_register(P1, P2, P3) \ do {} while (0) #endif /** An instrumented socket. */ struct st_mysql_socket { /** The real socket descriptor. */ my_socket fd; /** Is this a Unix-domain socket? */ char is_unix_domain_socket; /** Is this a socket opened for the extra port? */ char is_extra_port; /** Address family of the socket. (See sa_family from struct sockaddr). */ unsigned short address_family; /** The instrumentation hook. Note that this hook is not conditionally defined, for binary compatibility of the @c MYSQL_SOCKET interface. */ struct PSI_socket *m_psi; }; /** An instrumented socket. @c MYSQL_SOCKET is a replacement for @c my_socket. */ typedef struct st_mysql_socket MYSQL_SOCKET; /** @def MYSQL_INVALID_SOCKET MYSQL_SOCKET initial value. */ //MYSQL_SOCKET MYSQL_INVALID_SOCKET= {INVALID_SOCKET, NULL}; #define MYSQL_INVALID_SOCKET mysql_socket_invalid() /** MYSQL_SOCKET helper. Initialize instrumented socket. @sa mysql_socket_getfd @sa mysql_socket_setfd */ static inline MYSQL_SOCKET mysql_socket_invalid() { MYSQL_SOCKET mysql_socket= {INVALID_SOCKET, 0, 0, 0, NULL}; return mysql_socket; } /** Set socket descriptor and address. @param socket nstrumented socket @param addr unformatted socket address @param addr_len length of socket address */ static inline void mysql_socket_set_address( #ifdef HAVE_PSI_SOCKET_INTERFACE MYSQL_SOCKET socket, const struct sockaddr *addr, socklen_t addr_len #else MYSQL_SOCKET socket __attribute__ ((unused)), const struct sockaddr *addr __attribute__ ((unused)), socklen_t addr_len __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_SOCKET_INTERFACE if (socket.m_psi != NULL) PSI_SOCKET_CALL(set_socket_info)(socket.m_psi, NULL, addr, addr_len); #endif } /** Set socket descriptor and address. @param socket instrumented socket */ static inline void mysql_socket_set_thread_owner( #ifdef HAVE_PSI_SOCKET_INTERFACE MYSQL_SOCKET socket #else MYSQL_SOCKET socket __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_SOCKET_INTERFACE if (socket.m_psi != NULL) PSI_SOCKET_CALL(set_socket_thread_owner)(socket.m_psi); #endif } /** MYSQL_SOCKET helper. Get socket descriptor. @param mysql_socket Instrumented socket @sa mysql_socket_getfd */ static inline my_socket mysql_socket_getfd(MYSQL_SOCKET mysql_socket) { return mysql_socket.fd; } /** MYSQL_SOCKET helper. Set socket descriptor. @param mysql_socket Instrumented socket @param fd Socket descriptor @sa mysql_socket_setfd */ static inline void mysql_socket_setfd(MYSQL_SOCKET *mysql_socket, my_socket fd) { if (likely(mysql_socket != NULL)) mysql_socket->fd= fd; } /** @def MYSQL_SOCKET_WAIT_VARIABLES Instrumentation helper for socket waits. This instrumentation declares local variables. Do not use a ';' after this macro @param LOCKER locker @param STATE locker state @sa MYSQL_START_SOCKET_WAIT. @sa MYSQL_END_SOCKET_WAIT. */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define MYSQL_SOCKET_WAIT_VARIABLES(LOCKER, STATE) \ struct PSI_socket_locker* LOCKER; \ PSI_socket_locker_state STATE; #else #define MYSQL_SOCKET_WAIT_VARIABLES(LOCKER, STATE) #endif /** @def MYSQL_START_SOCKET_WAIT Instrumentation helper for socket waits. This instrumentation marks the start of a wait event. @param LOCKER locker @param STATE locker state @param SOCKET instrumented socket @param OP The socket operation to be performed @param COUNT bytes to be written/read @sa MYSQL_END_SOCKET_WAIT. */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define MYSQL_START_SOCKET_WAIT(LOCKER, STATE, SOCKET, OP, COUNT) \ LOCKER= inline_mysql_start_socket_wait(STATE, SOCKET, OP, COUNT,\ __FILE__, __LINE__) #else #define MYSQL_START_SOCKET_WAIT(LOCKER, STATE, SOCKET, OP, COUNT) \ do {} while (0) #endif /** @def MYSQL_END_SOCKET_WAIT Instrumentation helper for socket waits. This instrumentation marks the end of a wait event. @param LOCKER locker @param COUNT actual bytes written/read, or -1 @sa MYSQL_START_SOCKET_WAIT. */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define MYSQL_END_SOCKET_WAIT(LOCKER, COUNT) \ inline_mysql_end_socket_wait(LOCKER, COUNT) #else #define MYSQL_END_SOCKET_WAIT(LOCKER, COUNT) \ do {} while (0) #endif /** @def MYSQL_SOCKET_SET_STATE Set the state (IDLE, ACTIVE) of an instrumented socket. @param SOCKET the instrumented socket @param STATE the new state @sa PSI_socket_state */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define MYSQL_SOCKET_SET_STATE(SOCKET, STATE) \ inline_mysql_socket_set_state(SOCKET, STATE) #else #define MYSQL_SOCKET_SET_STATE(SOCKET, STATE) \ do {} while (0) #endif #ifdef HAVE_PSI_SOCKET_INTERFACE /** Instrumentation calls for MYSQL_START_SOCKET_WAIT. @sa MYSQL_START_SOCKET_WAIT. */ static inline struct PSI_socket_locker* inline_mysql_start_socket_wait(PSI_socket_locker_state *state, MYSQL_SOCKET mysql_socket, enum PSI_socket_operation op, size_t byte_count, const char *src_file, uint src_line) { struct PSI_socket_locker *locker; if (psi_likely(mysql_socket.m_psi != NULL)) { locker= PSI_SOCKET_CALL(start_socket_wait) (state, mysql_socket.m_psi, op, byte_count, src_file, src_line); } else locker= NULL; return locker; } /** Instrumentation calls for MYSQL_END_SOCKET_WAIT. @sa MYSQL_END_SOCKET_WAIT. */ static inline void inline_mysql_end_socket_wait(struct PSI_socket_locker *locker, size_t byte_count) { if (psi_likely(locker != NULL)) PSI_SOCKET_CALL(end_socket_wait)(locker, byte_count); } /** Set the state (IDLE, ACTIVE) of an instrumented socket. @param socket the instrumented socket @param state the new state @sa PSI_socket_state */ static inline void inline_mysql_socket_set_state(MYSQL_SOCKET socket, enum PSI_socket_state state) { if (socket.m_psi != NULL) PSI_SOCKET_CALL(set_socket_state)(socket.m_psi, state); } #endif /* HAVE_PSI_SOCKET_INTERFACE */ /** @def mysql_socket_fd(K, F) Create a socket. @c mysql_socket_fd is a replacement for @c socket. @param K PSI_socket_key for this instrumented socket @param F File descriptor */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_fd(K, F) \ inline_mysql_socket_fd(K, F) #else #define mysql_socket_fd(K, F) \ inline_mysql_socket_fd(F) #endif /** @def mysql_socket_socket(K, D, T, P) Create a socket. @c mysql_socket_socket is a replacement for @c socket. @param K PSI_socket_key for this instrumented socket @param D Socket domain @param T Protocol type @param P Transport protocol */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_socket(K, D, T, P) \ inline_mysql_socket_socket(K, D, T, P) #else #define mysql_socket_socket(K, D, T, P) \ inline_mysql_socket_socket(D, T, P) #endif /** @def mysql_socket_bind(FD, AP, L) Bind a socket to a local port number and IP address @c mysql_socket_bind is a replacement for @c bind. @param FD Instrumented socket descriptor returned by socket() @param AP Pointer to local port number and IP address in sockaddr structure @param L Length of sockaddr structure */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_bind(FD, AP, L) \ inline_mysql_socket_bind(__FILE__, __LINE__, FD, AP, L) #else #define mysql_socket_bind(FD, AP, L) \ inline_mysql_socket_bind(FD, AP, L) #endif /** @def mysql_socket_getsockname(FD, AP, LP) Return port number and IP address of the local host @c mysql_socket_getsockname is a replacement for @c getsockname. @param FD Instrumented socket descriptor returned by socket() @param AP Pointer to returned address of local host in @c sockaddr structure @param LP Pointer to length of @c sockaddr structure */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_getsockname(FD, AP, LP) \ inline_mysql_socket_getsockname(__FILE__, __LINE__, FD, AP, LP) #else #define mysql_socket_getsockname(FD, AP, LP) \ inline_mysql_socket_getsockname(FD, AP, LP) #endif /** @def mysql_socket_connect(FD, AP, L) Establish a connection to a remote host. @c mysql_socket_connect is a replacement for @c connect. @param FD Instrumented socket descriptor returned by socket() @param AP Pointer to target address in sockaddr structure @param L Length of sockaddr structure */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_connect(FD, AP, L) \ inline_mysql_socket_connect(__FILE__, __LINE__, FD, AP, L) #else #define mysql_socket_connect(FD, AP, L) \ inline_mysql_socket_connect(FD, AP, L) #endif /** @def mysql_socket_getpeername(FD, AP, LP) Get port number and IP address of remote host that a socket is connected to. @c mysql_socket_getpeername is a replacement for @c getpeername. @param FD Instrumented socket descriptor returned by socket() or accept() @param AP Pointer to returned address of remote host in sockaddr structure @param LP Pointer to length of sockaddr structure */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_getpeername(FD, AP, LP) \ inline_mysql_socket_getpeername(__FILE__, __LINE__, FD, AP, LP) #else #define mysql_socket_getpeername(FD, AP, LP) \ inline_mysql_socket_getpeername(FD, AP, LP) #endif /** @def mysql_socket_send(FD, B, N, FL) Send data from the buffer, B, to a connected socket. @c mysql_socket_send is a replacement for @c send. @param FD Instrumented socket descriptor returned by socket() or accept() @param B Buffer to send @param N Number of bytes to send @param FL Control flags */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_send(FD, B, N, FL) \ inline_mysql_socket_send(__FILE__, __LINE__, FD, B, N, FL) #else #define mysql_socket_send(FD, B, N, FL) \ inline_mysql_socket_send(FD, B, N, FL) #endif /** @def mysql_socket_recv(FD, B, N, FL) Receive data from a connected socket. @c mysql_socket_recv is a replacement for @c recv. @param FD Instrumented socket descriptor returned by socket() or accept() @param B Buffer to receive to @param N Maximum bytes to receive @param FL Control flags */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_recv(FD, B, N, FL) \ inline_mysql_socket_recv(__FILE__, __LINE__, FD, B, N, FL) #else #define mysql_socket_recv(FD, B, N, FL) \ inline_mysql_socket_recv(FD, B, N, FL) #endif /** @def mysql_socket_sendto(FD, B, N, FL, AP, L) Send data to a socket at the specified address. @c mysql_socket_sendto is a replacement for @c sendto. @param FD Instrumented socket descriptor returned by socket() @param B Buffer to send @param N Number of bytes to send @param FL Control flags @param AP Pointer to destination sockaddr structure @param L Size of sockaddr structure */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_sendto(FD, B, N, FL, AP, L) \ inline_mysql_socket_sendto(__FILE__, __LINE__, FD, B, N, FL, AP, L) #else #define mysql_socket_sendto(FD, B, N, FL, AP, L) \ inline_mysql_socket_sendto(FD, B, N, FL, AP, L) #endif /** @def mysql_socket_recvfrom(FD, B, N, FL, AP, L) Receive data from a socket and return source address information @c mysql_socket_recvfrom is a replacement for @c recvfrom. @param FD Instrumented socket descriptor returned by socket() @param B Buffer to receive to @param N Maximum bytes to receive @param FL Control flags @param AP Pointer to source address in sockaddr_storage structure @param LP Size of sockaddr_storage structure */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_recvfrom(FD, B, N, FL, AP, LP) \ inline_mysql_socket_recvfrom(__FILE__, __LINE__, FD, B, N, FL, AP, LP) #else #define mysql_socket_recvfrom(FD, B, N, FL, AP, LP) \ inline_mysql_socket_recvfrom(FD, B, N, FL, AP, LP) #endif /** @def mysql_socket_getsockopt(FD, LV, ON, OP, OL) Get a socket option for the specified socket. @c mysql_socket_getsockopt is a replacement for @c getsockopt. @param FD Instrumented socket descriptor returned by socket() @param LV Protocol level @param ON Option to query @param OP Buffer which will contain the value for the requested option @param OL Pointer to length of OP */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_getsockopt(FD, LV, ON, OP, OL) \ inline_mysql_socket_getsockopt(__FILE__, __LINE__, FD, LV, ON, OP, OL) #else #define mysql_socket_getsockopt(FD, LV, ON, OP, OL) \ inline_mysql_socket_getsockopt(FD, LV, ON, OP, OL) #endif /** @def mysql_socket_setsockopt(FD, LV, ON, OP, OL) Set a socket option for the specified socket. @c mysql_socket_setsockopt is a replacement for @c setsockopt. @param FD Instrumented socket descriptor returned by socket() @param LV Protocol level @param ON Option to modify @param OP Buffer containing the value for the specified option @param OL Pointer to length of OP */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_setsockopt(FD, LV, ON, OP, OL) \ inline_mysql_socket_setsockopt(__FILE__, __LINE__, FD, LV, ON, OP, OL) #else #define mysql_socket_setsockopt(FD, LV, ON, OP, OL) \ inline_mysql_socket_setsockopt(FD, LV, ON, OP, OL) #endif /** @def mysql_sock_set_nonblocking Set socket to non-blocking. @param FD instrumented socket descriptor */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_sock_set_nonblocking(FD) \ inline_mysql_sock_set_nonblocking(__FILE__, __LINE__, FD) #else #define mysql_sock_set_nonblocking(FD) \ inline_mysql_sock_set_nonblocking(FD) #endif /** @def mysql_socket_listen(FD, N) Set socket state to listen for an incoming connection. @c mysql_socket_listen is a replacement for @c listen. @param FD Instrumented socket descriptor, bound and connected @param N Maximum number of pending connections allowed. */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_listen(FD, N) \ inline_mysql_socket_listen(__FILE__, __LINE__, FD, N) #else #define mysql_socket_listen(FD, N) \ inline_mysql_socket_listen(FD, N) #endif /** @def mysql_socket_accept(K, FD, AP, LP) Accept a connection from any remote host; TCP only. @c mysql_socket_accept is a replacement for @c accept. @param K PSI_socket_key for this instrumented socket @param FD Instrumented socket descriptor, bound and placed in a listen state @param AP Pointer to sockaddr structure with returned IP address and port of connected host @param LP Pointer to length of valid information in AP */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_accept(K, FD, AP, LP) \ inline_mysql_socket_accept(__FILE__, __LINE__, K, FD, AP, LP) #else #define mysql_socket_accept(K, FD, AP, LP) \ inline_mysql_socket_accept(FD, AP, LP) #endif /** @def mysql_socket_close(FD) Close a socket and sever any connections. @c mysql_socket_close is a replacement for @c close. @param FD Instrumented socket descriptor returned by socket() or accept() */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_close(FD) \ inline_mysql_socket_close(__FILE__, __LINE__, FD) #else #define mysql_socket_close(FD) \ inline_mysql_socket_close(FD) #endif /** @def mysql_socket_shutdown(FD, H) Disable receives and/or sends on a socket. @c mysql_socket_shutdown is a replacement for @c shutdown. @param FD Instrumented socket descriptor returned by socket() or accept() @param H Specifies which operations to shutdown */ #ifdef HAVE_PSI_SOCKET_INTERFACE #define mysql_socket_shutdown(FD, H) \ inline_mysql_socket_shutdown(__FILE__, __LINE__, FD, H) #else #define mysql_socket_shutdown(FD, H) \ inline_mysql_socket_shutdown(FD, H) #endif #ifdef HAVE_PSI_SOCKET_INTERFACE static inline void inline_mysql_socket_register( const char *category, PSI_socket_info *info, int count) { PSI_SOCKET_CALL(register_socket)(category, info, count); } #endif /** mysql_socket_fd */ static inline MYSQL_SOCKET inline_mysql_socket_fd ( #ifdef HAVE_PSI_SOCKET_INTERFACE PSI_socket_key key, #endif int fd) { MYSQL_SOCKET mysql_socket= MYSQL_INVALID_SOCKET; mysql_socket.fd= fd; DBUG_ASSERT(mysql_socket.fd != INVALID_SOCKET); #ifdef HAVE_PSI_SOCKET_INTERFACE mysql_socket.m_psi= PSI_SOCKET_CALL(init_socket) (key, (const my_socket*)&mysql_socket.fd, NULL, 0); #endif /** Currently systemd socket activation is the user of this function. Its API (man sd_listen_fds) says FD_CLOSE_EXEC is already called. If there becomes another user, we can call it again without detriment. If needed later: #if defined(HAVE_FCNTL) && defined(FD_CLOEXEC) (void) fcntl(mysql_socket.fd, F_SETFD, FD_CLOEXEC); #endif */ return mysql_socket; } /** mysql_socket_socket */ static inline MYSQL_SOCKET inline_mysql_socket_socket ( #ifdef HAVE_PSI_SOCKET_INTERFACE PSI_socket_key key, #endif int domain, int type, int protocol) { MYSQL_SOCKET mysql_socket= MYSQL_INVALID_SOCKET; mysql_socket.fd= socket(domain, type | SOCK_CLOEXEC, protocol); #ifdef HAVE_PSI_SOCKET_INTERFACE if (likely(mysql_socket.fd != INVALID_SOCKET)) { mysql_socket.m_psi= PSI_SOCKET_CALL(init_socket) (key, (const my_socket*)&mysql_socket.fd, NULL, 0); } #endif /* SOCK_CLOEXEC isn't always a number - can't preprocessor compare */ #if defined(HAVE_FCNTL) && defined(FD_CLOEXEC) && !defined(HAVE_SOCK_CLOEXEC) (void) fcntl(mysql_socket.fd, F_SETFD, FD_CLOEXEC); #endif return mysql_socket; } /** mysql_socket_bind */ static inline int inline_mysql_socket_bind ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, const struct sockaddr *addr, size_t len) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker_state state; PSI_socket_locker *locker; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_BIND, (size_t)0, src_file, src_line); /* Instrumented code */ result= bind(mysql_socket.fd, addr, (int)len); /* Instrumentation end */ if (result == 0) PSI_SOCKET_CALL(set_socket_info)(mysql_socket.m_psi, NULL, addr, (socklen_t)len); if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= bind(mysql_socket.fd, addr, (int)len); return result; } /** mysql_socket_getsockname */ static inline int inline_mysql_socket_getsockname ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, struct sockaddr *addr, socklen_t *len) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_BIND, (size_t)0, src_file, src_line); /* Instrumented code */ result= getsockname(mysql_socket.fd, addr, len); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= getsockname(mysql_socket.fd, addr, len); return result; } /** mysql_socket_connect */ static inline int inline_mysql_socket_connect ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, const struct sockaddr *addr, socklen_t len) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_CONNECT, (size_t)0, src_file, src_line); /* Instrumented code */ result= connect(mysql_socket.fd, addr, len); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= connect(mysql_socket.fd, addr, len); return result; } /** mysql_socket_getpeername */ static inline int inline_mysql_socket_getpeername ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, struct sockaddr *addr, socklen_t *len) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_BIND, (size_t)0, src_file, src_line); /* Instrumented code */ result= getpeername(mysql_socket.fd, addr, len); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= getpeername(mysql_socket.fd, addr, len); return result; } /** mysql_socket_send */ static inline ssize_t inline_mysql_socket_send ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, const SOCKBUF_T *buf, size_t n, int flags) { ssize_t result; DBUG_ASSERT(mysql_socket.fd != INVALID_SOCKET); #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_SEND, n, src_file, src_line); /* Instrumented code */ result= send(mysql_socket.fd, buf, IF_WIN((int),) n, flags); /* Instrumentation end */ if (locker != NULL) { size_t bytes_written= (result > 0) ? (size_t) result : 0; PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_written); } return result; } #endif /* Non instrumented code */ result= send(mysql_socket.fd, buf, IF_WIN((int),) n, flags); return result; } /** mysql_socket_recv */ static inline ssize_t inline_mysql_socket_recv ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, SOCKBUF_T *buf, size_t n, int flags) { ssize_t result; DBUG_ASSERT(mysql_socket.fd != INVALID_SOCKET); #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_RECV, (size_t)0, src_file, src_line); /* Instrumented code */ result= recv(mysql_socket.fd, buf, IF_WIN((int),) n, flags); /* Instrumentation end */ if (locker != NULL) { size_t bytes_read= (result > 0) ? (size_t) result : 0; PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_read); } return result; } #endif /* Non instrumented code */ result= recv(mysql_socket.fd, buf, IF_WIN((int),) n, flags); return result; } /** mysql_socket_sendto */ static inline ssize_t inline_mysql_socket_sendto ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, const SOCKBUF_T *buf, size_t n, int flags, const struct sockaddr *addr, socklen_t addr_len) { ssize_t result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_SEND, n, src_file, src_line); /* Instrumented code */ result= sendto(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); /* Instrumentation end */ if (locker != NULL) { size_t bytes_written = (result > 0) ? (size_t) result : 0; PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_written); } return result; } #endif /* Non instrumented code */ result= sendto(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); return result; } /** mysql_socket_recvfrom */ static inline ssize_t inline_mysql_socket_recvfrom ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, SOCKBUF_T *buf, size_t n, int flags, struct sockaddr *addr, socklen_t *addr_len) { ssize_t result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_RECV, (size_t)0, src_file, src_line); /* Instrumented code */ result= recvfrom(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); /* Instrumentation end */ if (locker != NULL) { size_t bytes_read= (result > 0) ? (size_t) result : 0; PSI_SOCKET_CALL(end_socket_wait)(locker, bytes_read); } return result; } #endif /* Non instrumented code */ result= recvfrom(mysql_socket.fd, buf, IF_WIN((int),) n, flags, addr, addr_len); return result; } /** mysql_socket_getsockopt */ static inline int inline_mysql_socket_getsockopt ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, int level, int optname, SOCKBUF_T *optval, socklen_t *optlen) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_OPT, (size_t)0, src_file, src_line); /* Instrumented code */ result= getsockopt(mysql_socket.fd, level, optname, optval, optlen); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= getsockopt(mysql_socket.fd, level, optname, optval, optlen); return result; } /** mysql_socket_setsockopt */ static inline int inline_mysql_socket_setsockopt ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, int level, int optname, const SOCKBUF_T *optval, socklen_t optlen) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_OPT, (size_t)0, src_file, src_line); /* Instrumented code */ result= setsockopt(mysql_socket.fd, level, optname, optval, optlen); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= setsockopt(mysql_socket.fd, level, optname, optval, optlen); return result; } /** set_socket_nonblock */ static inline int set_socket_nonblock(my_socket fd) { int ret= 0; #ifdef _WIN32 { u_long nonblocking= 1; ret= ioctlsocket(fd, FIONBIO, &nonblocking); } #else { int fd_flags; fd_flags= fcntl(fd, F_GETFL, 0); if (fd_flags < 0) return errno; #if defined(O_NONBLOCK) fd_flags |= O_NONBLOCK; #elif defined(O_NDELAY) fd_flags |= O_NDELAY; #elif defined(O_FNDELAY) fd_flags |= O_FNDELAY; #else #error "No definition of non-blocking flag found." #endif /* O_NONBLOCK */ if (fcntl(fd, F_SETFL, fd_flags) == -1) ret= errno; } #endif /* _WIN32 */ return ret; } /** mysql_socket_set_nonblocking */ static inline int inline_mysql_sock_set_nonblocking ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket ) { int result= 0; #ifdef HAVE_PSI_SOCKET_INTERFACE if (mysql_socket.m_psi) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_OPT, (size_t)0, src_file, src_line); /* Instrumented code */ result= set_socket_nonblock(mysql_socket.fd); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= set_socket_nonblock(mysql_socket.fd); return result; } /** mysql_socket_listen */ static inline int inline_mysql_socket_listen ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, int backlog) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_CONNECT, (size_t)0, src_file, src_line); /* Instrumented code */ result= listen(mysql_socket.fd, backlog); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ result= listen(mysql_socket.fd, backlog); return result; } /** mysql_socket_accept */ static inline MYSQL_SOCKET inline_mysql_socket_accept ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, PSI_socket_key key, #endif MYSQL_SOCKET socket_listen, struct sockaddr *addr, socklen_t *addr_len) { #ifdef FD_CLOEXEC int flags __attribute__ ((unused)); #endif MYSQL_SOCKET socket_accept; #ifdef HAVE_PSI_SOCKET_INTERFACE if (socket_listen.m_psi != NULL) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, socket_listen.m_psi, PSI_SOCKET_CONNECT, (size_t)0, src_file, src_line); /* Instrumented code */ #ifdef HAVE_ACCEPT4 socket_accept.fd= accept4(socket_listen.fd, addr, addr_len, SOCK_CLOEXEC); #else socket_accept.fd= accept(socket_listen.fd, addr, addr_len); #ifdef FD_CLOEXEC if (socket_accept.fd != INVALID_SOCKET) { flags= fcntl(socket_accept.fd, F_GETFD); if (flags != -1) { flags |= FD_CLOEXEC; fcntl(socket_accept.fd, F_SETFD, flags); } } #endif #endif /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); } else #endif { /* Non instrumented code */ #ifdef HAVE_ACCEPT4 socket_accept.fd= accept4(socket_listen.fd, addr, addr_len, SOCK_CLOEXEC); #else socket_accept.fd= accept(socket_listen.fd, addr, addr_len); #ifdef FD_CLOEXEC if (socket_accept.fd != INVALID_SOCKET) { flags= fcntl(socket_accept.fd, F_GETFD); if (flags != -1) { flags |= FD_CLOEXEC; fcntl(socket_accept.fd, F_SETFD, flags); } } #endif #endif } #ifdef HAVE_PSI_SOCKET_INTERFACE if (likely(socket_accept.fd != INVALID_SOCKET)) { /* Initialize the instrument with the new socket descriptor and address */ socket_accept.m_psi= PSI_SOCKET_CALL(init_socket) (key, (const my_socket*)&socket_accept.fd, addr, *addr_len); } #endif return socket_accept; } /** mysql_socket_close */ static inline int inline_mysql_socket_close ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket) { int result; #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { /* Instrumentation start */ PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_CLOSE, (size_t)0, src_file, src_line); /* Instrumented code */ result= closesocket(mysql_socket.fd); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); /* Remove the instrumentation for this socket. */ if (mysql_socket.m_psi != NULL) PSI_SOCKET_CALL(destroy_socket)(mysql_socket.m_psi); return result; } #endif /* Non instrumented code */ result= closesocket(mysql_socket.fd); return result; } /** mysql_socket_shutdown */ static inline int inline_mysql_socket_shutdown ( #ifdef HAVE_PSI_SOCKET_INTERFACE const char *src_file, uint src_line, #endif MYSQL_SOCKET mysql_socket, int how) { int result; #ifdef _WIN32 static LPFN_DISCONNECTEX DisconnectEx = NULL; if (DisconnectEx == NULL) { DWORD dwBytesReturned; GUID guidDisconnectEx = WSAID_DISCONNECTEX; WSAIoctl(mysql_socket.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidDisconnectEx, sizeof(GUID), &DisconnectEx, sizeof(DisconnectEx), &dwBytesReturned, NULL, NULL); } #endif /* Instrumentation start */ #ifdef HAVE_PSI_SOCKET_INTERFACE if (psi_likely(mysql_socket.m_psi != NULL)) { PSI_socket_locker *locker; PSI_socket_locker_state state; locker= PSI_SOCKET_CALL(start_socket_wait) (&state, mysql_socket.m_psi, PSI_SOCKET_SHUTDOWN, (size_t)0, src_file, src_line); /* Instrumented code */ #ifdef _WIN32 if (DisconnectEx) result= (DisconnectEx(mysql_socket.fd, (LPOVERLAPPED) NULL, (DWORD) 0, (DWORD) 0) == TRUE) ? 0 : -1; else #endif result= shutdown(mysql_socket.fd, how); /* Instrumentation end */ if (locker != NULL) PSI_SOCKET_CALL(end_socket_wait)(locker, (size_t)0); return result; } #endif /* Non instrumented code */ #ifdef _WIN32 if (DisconnectEx) result= (DisconnectEx(mysql_socket.fd, (LPOVERLAPPED) NULL, (DWORD) 0, (DWORD) 0) == TRUE) ? 0 : -1; else #endif result= shutdown(mysql_socket.fd, how); return result; } /** @} (end of group Socket_instrumentation) */ #endif mysql/server/mysql/psi/mysql_mdl.h000064400000010624151027430560013337 0ustar00/* Copyright (c) 2012, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef MYSQL_MDL_H #define MYSQL_MDL_H /** @file mysql/psi/mysql_mdl.h Instrumentation helpers for metadata locks. */ #include "mysql/psi/psi.h" #ifdef HAVE_PSI_METADATA_INTERFACE #ifndef PSI_METADATA_CALL #define PSI_METADATA_CALL(M) PSI_DYNAMIC_CALL(M) #endif #define PSI_CALL_start_metadata_wait(A,B,C,D) PSI_METADATA_CALL(start_metadata_wait)(A,B,C,D) #define PSI_CALL_end_metadata_wait(A,B) PSI_METADATA_CALL(end_metadata_wait)(A,B) #define PSI_CALL_create_metadata_lock(A,B,C,D,E,F,G) PSI_METADATA_CALL(create_metadata_lock)(A,B,C,D,E,F,G) #define PSI_CALL_set_metadata_lock_status(A,B) PSI_METADATA_CALL(set_metadata_lock_status)(A,B) #define PSI_CALL_destroy_metadata_lock(A) PSI_METADATA_CALL(destroy_metadata_lock)(A) #else #define PSI_CALL_start_metadata_wait(A,B,C,D) 0 #define PSI_CALL_end_metadata_wait(A,B) do { } while(0) #define PSI_CALL_create_metadata_lock(A,B,C,D,E,F,G) 0 #define PSI_CALL_set_metadata_lock_status(A,B) do {} while(0) #define PSI_CALL_destroy_metadata_lock(A) do {} while(0) #endif /** @defgroup Thread_instrumentation Metadata Instrumentation @ingroup Instrumentation_interface @{ */ /** @def mysql_mdl_create(K, M, A) Instrumented metadata lock creation. @param I Metadata lock identity @param K Metadata key @param T Metadata lock type @param D Metadata lock duration @param S Metadata lock status @param F request source file @param L request source line */ #ifdef HAVE_PSI_METADATA_INTERFACE #define mysql_mdl_create(I, K, T, D, S, F, L) \ inline_mysql_mdl_create(I, K, T, D, S, F, L) #else #define mysql_mdl_create(I, K, T, D, S, F, L) NULL #endif #ifdef HAVE_PSI_METADATA_INTERFACE #define mysql_mdl_set_status(L, S) \ inline_mysql_mdl_set_status(L, S) #else #define mysql_mdl_set_status(L, S) \ do {} while (0) #endif /** @def mysql_mdl_destroy(M) Instrumented metadata lock destruction. @param M Metadata lock */ #ifdef HAVE_PSI_METADATA_INTERFACE #define mysql_mdl_destroy(M) \ inline_mysql_mdl_destroy(M, __FILE__, __LINE__) #else #define mysql_mdl_destroy(M) \ do {} while (0) #endif #ifdef HAVE_PSI_METADATA_INTERFACE static inline PSI_metadata_lock * inline_mysql_mdl_create(void *identity, const MDL_key *mdl_key, enum_mdl_type mdl_type, enum_mdl_duration mdl_duration, MDL_ticket::enum_psi_status mdl_status, const char *src_file, uint src_line) { PSI_metadata_lock *result; /* static_cast: Fit a round C++ enum peg into a square C int hole ... */ result= PSI_METADATA_CALL(create_metadata_lock) (identity, mdl_key, static_cast (mdl_type), static_cast (mdl_duration), static_cast (mdl_status), src_file, src_line); return result; } static inline void inline_mysql_mdl_set_status( PSI_metadata_lock *psi, MDL_ticket::enum_psi_status mdl_status) { if (psi != NULL) PSI_METADATA_CALL(set_metadata_lock_status)(psi, mdl_status); } static inline void inline_mysql_mdl_destroy( PSI_metadata_lock *psi, const char *src_file, uint src_line) { if (psi != NULL) PSI_METADATA_CALL(destroy_metadata_lock)(psi); } #endif /* HAVE_PSI_METADATA_INTERFACE */ /** @} (end of group Metadata_instrumentation) */ #endif mysql/server/mysql/psi/psi_abi_v2.h000064400000002667151027430560013363 0ustar00/* Copyright (c) 2008, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file mysql/psi/psi_abi_v1.h ABI check for mysql/psi/psi.h, when using PSI_VERSION_2. This file is only used to automate detection of changes between versions. Do not include this file, include mysql/psi/psi.h instead. */ #define USE_PSI_2 #define HAVE_PSI_INTERFACE #define MY_GLOBAL_INCLUDED #include "mysql/psi/psi.h" mysql/server/mysql/psi/psi_base.h000064400000011027151027430560013121 0ustar00/* Copyright (c) 2008, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. Without limiting anything contained in the foregoing, this file, which is part of C Driver for MySQL (Connector/C), is also subject to the Universal FOSS Exception, version 1.0, a copy of which can be found at http://oss.oracle.com/licenses/universal-foss-exception. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_PSI_BASE_H #define MYSQL_PSI_BASE_H #ifdef EMBEDDED_LIBRARY #define DISABLE_ALL_PSI #endif /* EMBEDDED_LIBRARY */ #ifdef __cplusplus extern "C" { #endif /** @file mysql/psi/psi_base.h Performance schema instrumentation interface. @defgroup Instrumentation_interface Instrumentation Interface @ingroup Performance_schema @{ */ #define PSI_INSTRUMENT_ME 0 #define PSI_INSTRUMENT_MEM ((PSI_memory_key)0) #define PSI_NOT_INSTRUMENTED 0 /** Global flag. This flag indicate that an instrumentation point is a global variable, or a singleton. */ #define PSI_FLAG_GLOBAL (1 << 0) /** Mutable flag. This flag indicate that an instrumentation point is a general placeholder, that can mutate into a more specific instrumentation point. */ #define PSI_FLAG_MUTABLE (1 << 1) #define PSI_FLAG_THREAD (1 << 2) /** Stage progress flag. This flag apply to the stage instruments only. It indicates the instrumentation provides progress data. */ #define PSI_FLAG_STAGE_PROGRESS (1 << 3) /** Shared Exclusive flag. Indicates that rwlock support the shared exclusive state. */ #define PSI_RWLOCK_FLAG_SX (1 << 4) /** Transferable flag. This flag indicate that an instrumented object can be created by a thread and destroyed by another thread. */ #define PSI_FLAG_TRANSFER (1 << 5) /** Volatility flag. This flag indicate that an instrumented object has a volatility (life cycle) comparable to the volatility of a session. */ #define PSI_FLAG_VOLATILITY_SESSION (1 << 6) /** System thread flag. Indicates that the instrumented object exists on a system thread. */ #define PSI_FLAG_THREAD_SYSTEM (1 << 9) #ifdef HAVE_PSI_INTERFACE /** @def PSI_VERSION_1 Performance Schema Interface number for version 1. This version is supported. */ #define PSI_VERSION_1 1 /** @def PSI_VERSION_2 Performance Schema Interface number for version 2. This version is not implemented, it's a placeholder. */ #define PSI_VERSION_2 2 /** @def PSI_CURRENT_VERSION Performance Schema Interface number for the most recent version. The most current version is @c PSI_VERSION_1 */ #define PSI_CURRENT_VERSION 1 /** @def USE_PSI_1 Define USE_PSI_1 to use the interface version 1. */ /** @def USE_PSI_2 Define USE_PSI_2 to use the interface version 2. */ /** @def HAVE_PSI_1 Define HAVE_PSI_1 if the interface version 1 needs to be compiled in. */ /** @def HAVE_PSI_2 Define HAVE_PSI_2 if the interface version 2 needs to be compiled in. */ #ifndef USE_PSI_2 #ifndef USE_PSI_1 #define USE_PSI_1 #endif #endif #ifdef USE_PSI_1 #define HAVE_PSI_1 #endif #ifdef USE_PSI_2 #define HAVE_PSI_2 #endif /* Allow to override PSI_XXX_CALL at compile time with more efficient implementations, if available. If nothing better is available, make a dynamic call using the PSI_server function pointer. */ #define PSI_DYNAMIC_CALL(M) PSI_server->M #endif /* HAVE_PSI_INTERFACE */ /** @} */ /** Instrumented memory key. To instrument memory, a memory key must be obtained using @c register_memory. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_memory_key; #ifdef __cplusplus } #endif #endif /* MYSQL_PSI_BASE_H */ mysql/server/mysql/psi/mysql_table.h000064400000013061151027430560013650 0ustar00/* Copyright (c) 2010, 2023, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_TABLE_H #define MYSQL_TABLE_H /** @file mysql/psi/mysql_table.h Instrumentation helpers for table io. */ #include "mysql/psi/psi.h" #ifndef PSI_TABLE_CALL #define PSI_TABLE_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Table_instrumentation Table Instrumentation @ingroup Instrumentation_interface @{ */ #ifdef HAVE_PSI_TABLE_INTERFACE #define MYSQL_UNBIND_TABLE(handler) (handler)->unbind_psi() #define PSI_CALL_unbind_table PSI_TABLE_CALL(unbind_table) #define PSI_CALL_rebind_table PSI_TABLE_CALL(rebind_table) #define PSI_CALL_open_table PSI_TABLE_CALL(open_table) #define PSI_CALL_close_table PSI_TABLE_CALL(close_table) #define PSI_CALL_get_table_share PSI_TABLE_CALL(get_table_share) #define PSI_CALL_release_table_share PSI_TABLE_CALL(release_table_share) #define PSI_CALL_drop_table_share PSI_TABLE_CALL(drop_table_share) #else #define MYSQL_UNBIND_TABLE(handler) do { } while(0) #define PSI_CALL_unbind_table(A1) do { } while(0) #define PSI_CALL_rebind_table(A1,A2,A3) NULL #define PSI_CALL_close_table(A1,A2) do { } while(0) #define PSI_CALL_open_table(A1,A2) NULL #define PSI_CALL_get_table_share(A1,A2) NULL #define PSI_CALL_release_table_share(A1) do { } while(0) #define PSI_CALL_drop_table_share(A1,A2,A3,A4,A5) do { } while(0) #endif /** @def MYSQL_TABLE_WAIT_VARIABLES Instrumentation helper for table waits. This instrumentation declares local variables. Do not use a ';' after this macro @param LOCKER the locker @param STATE the locker state @sa MYSQL_START_TABLE_IO_WAIT. @sa MYSQL_END_TABLE_IO_WAIT. @sa MYSQL_START_TABLE_LOCK_WAIT. @sa MYSQL_END_TABLE_LOCK_WAIT. */ #ifdef HAVE_PSI_TABLE_INTERFACE #define MYSQL_TABLE_WAIT_VARIABLES(LOCKER, STATE) \ struct PSI_table_locker* LOCKER; \ PSI_table_locker_state STATE; #else #define MYSQL_TABLE_WAIT_VARIABLES(LOCKER, STATE) #endif /** @def MYSQL_START_TABLE_LOCK_WAIT Instrumentation helper for table lock waits. This instrumentation marks the start of a wait event. @param LOCKER the locker @param STATE the locker state @param PSI the instrumented table @param OP the table operation to be performed @param FLAGS per table operation flags. @sa MYSQL_END_TABLE_LOCK_WAIT. */ #ifdef HAVE_PSI_TABLE_INTERFACE #define MYSQL_START_TABLE_LOCK_WAIT(LOCKER, STATE, PSI, OP, FLAGS) \ LOCKER= inline_mysql_start_table_lock_wait(STATE, PSI, \ OP, FLAGS, __FILE__, __LINE__) #else #define MYSQL_START_TABLE_LOCK_WAIT(LOCKER, STATE, PSI, OP, FLAGS) \ do {} while (0) #endif /** @def MYSQL_END_TABLE_LOCK_WAIT Instrumentation helper for table lock waits. This instrumentation marks the end of a wait event. @param LOCKER the locker @sa MYSQL_START_TABLE_LOCK_WAIT. */ #ifdef HAVE_PSI_TABLE_INTERFACE #define MYSQL_END_TABLE_LOCK_WAIT(LOCKER) \ inline_mysql_end_table_lock_wait(LOCKER) #else #define MYSQL_END_TABLE_LOCK_WAIT(LOCKER) \ do {} while (0) #endif #ifdef HAVE_PSI_TABLE_INTERFACE #define MYSQL_UNLOCK_TABLE(T) \ inline_mysql_unlock_table(T) #else #define MYSQL_UNLOCK_TABLE(T) \ do {} while (0) #endif #ifdef HAVE_PSI_TABLE_INTERFACE /** Instrumentation calls for MYSQL_START_TABLE_LOCK_WAIT. @sa MYSQL_END_TABLE_LOCK_WAIT. */ static inline struct PSI_table_locker * inline_mysql_start_table_lock_wait(PSI_table_locker_state *state, struct PSI_table *psi, enum PSI_table_lock_operation op, ulong flags, const char *src_file, uint src_line) { if (psi_likely(psi != NULL)) { struct PSI_table_locker *locker; locker= PSI_TABLE_CALL(start_table_lock_wait) (state, psi, op, flags, src_file, src_line); return locker; } return NULL; } /** Instrumentation calls for MYSQL_END_TABLE_LOCK_WAIT. @sa MYSQL_START_TABLE_LOCK_WAIT. */ static inline void inline_mysql_end_table_lock_wait(struct PSI_table_locker *locker) { if (psi_likely(locker != NULL)) PSI_TABLE_CALL(end_table_lock_wait)(locker); } static inline void inline_mysql_unlock_table(struct PSI_table *table) { if (table != NULL) PSI_TABLE_CALL(unlock_table)(table); } #endif /** @} (end of group Table_instrumentation) */ #endif mysql/server/mysql/psi/psi_abi_v0.h000064400000002630151027430560013347 0ustar00/* Copyright (c) 2011, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file mysql/psi/psi_abi_v0.h ABI check for mysql/psi/psi.h, when compiling without instrumentation. This file is only used to automate detection of changes between versions. Do not include this file, include mysql/psi/psi.h instead. */ #define MY_GLOBAL_INCLUDED #include "mysql/psi/psi.h" mysql/server/mysql/psi/mysql_thread.h000064400000077376151027430560014053 0ustar00/* Copyright (c) 2008, 2023, Oracle and/or its affiliates. Copyright (c) 2020, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_THREAD_H #define MYSQL_THREAD_H /** @file mysql/psi/mysql_thread.h Instrumentation helpers for mysys threads, mutexes, read write locks and conditions. This header file provides the necessary declarations to use the mysys thread API with the performance schema instrumentation. In some compilers (SunStudio), 'static inline' functions, when declared but not used, are not optimized away (because they are unused) by default, so that including a static inline function from a header file does create unwanted dependencies, causing unresolved symbols at link time. Other compilers, like gcc, optimize these dependencies by default. Since the instrumented APIs declared here are wrapper on top of my_pthread / safemutex / etc APIs, including mysql/psi/mysql_thread.h assumes that the dependency on my_pthread and safemutex already exists. */ /* Note: there are several orthogonal dimensions here. Dimension 1: Instrumentation HAVE_PSI_INTERFACE is defined when the instrumentation is compiled in. This may happen both in debug or production builds. Dimension 2: Debug SAFE_MUTEX is defined when debug is compiled in. This may happen both with and without instrumentation. Dimension 3: Platform Mutexes are implemented with one of: - the pthread library - fast mutexes - window apis This is implemented by various macro definitions in my_pthread.h This causes complexity with '#ifdef'-ery that can't be avoided. */ #include "mysql/psi/psi.h" #ifdef MYSQL_SERVER #ifndef MYSQL_DYNAMIC_PLUGIN #include "pfs_thread_provider.h" #endif #endif #ifndef PSI_MUTEX_CALL #define PSI_MUTEX_CALL(M) PSI_DYNAMIC_CALL(M) #endif #ifndef PSI_RWLOCK_CALL #define PSI_RWLOCK_CALL(M) PSI_DYNAMIC_CALL(M) #endif #ifndef PSI_COND_CALL #define PSI_COND_CALL(M) PSI_DYNAMIC_CALL(M) #endif #ifndef PSI_THREAD_CALL #define PSI_THREAD_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Thread_instrumentation Thread Instrumentation @ingroup Instrumentation_interface @{ */ #ifdef HAVE_PSI_THREAD_INTERFACE #define PSI_CALL_delete_current_thread PSI_THREAD_CALL(delete_current_thread) #define PSI_CALL_get_thread PSI_THREAD_CALL(get_thread) #define PSI_CALL_new_thread PSI_THREAD_CALL(new_thread) #define PSI_CALL_register_thread PSI_THREAD_CALL(register_thread) #define PSI_CALL_set_thread PSI_THREAD_CALL(set_thread) #define PSI_CALL_set_thread_THD PSI_THREAD_CALL(set_thread_THD) #define PSI_CALL_set_thread_connect_attrs PSI_THREAD_CALL(set_thread_connect_attrs) #define PSI_CALL_set_thread_db PSI_THREAD_CALL(set_thread_db) #define PSI_CALL_set_thread_id PSI_THREAD_CALL(set_thread_id) #define PSI_CALL_set_thread_os_id PSI_THREAD_CALL(set_thread_os_id) #define PSI_CALL_set_thread_info PSI_THREAD_CALL(set_thread_info) #define PSI_CALL_set_thread_start_time PSI_THREAD_CALL(set_thread_start_time) #define PSI_CALL_set_thread_account PSI_THREAD_CALL(set_thread_account) #define PSI_CALL_spawn_thread PSI_THREAD_CALL(spawn_thread) #define PSI_CALL_set_connection_type PSI_THREAD_CALL(set_connection_type) #else #define PSI_CALL_delete_current_thread() do { } while(0) #define PSI_CALL_get_thread() NULL #define PSI_CALL_new_thread(A1,A2,A3) NULL #define PSI_CALL_register_thread(A1,A2,A3) do { } while(0) #define PSI_CALL_set_thread(A1) do { } while(0) #define PSI_CALL_set_thread_THD(A1,A2) do { } while(0) #define PSI_CALL_set_thread_connect_attrs(A1,A2,A3) 0 #define PSI_CALL_set_thread_db(A1,A2) do { } while(0) #define PSI_CALL_set_thread_id(A1,A2) do { } while(0) #define PSI_CALL_set_thread_os_id(A1) do { } while(0) #define PSI_CALL_set_thread_info(A1, A2) do { } while(0) #define PSI_CALL_set_thread_start_time(A1) do { } while(0) #define PSI_CALL_set_thread_account(A1, A2, A3, A4) do { } while(0) #define PSI_CALL_spawn_thread(A1, A2, A3, A4, A5) 0 #define PSI_CALL_set_connection_type(A) do { } while(0) #endif /** An instrumented mutex structure. @sa mysql_mutex_t */ struct st_mysql_mutex { /** The real mutex. */ #ifdef SAFE_MUTEX safe_mutex_t m_mutex; #else pthread_mutex_t m_mutex; #endif /** The instrumentation hook. Note that this hook is not conditionally defined, for binary compatibility of the @c mysql_mutex_t interface. */ struct PSI_mutex *m_psi; }; /** Type of an instrumented mutex. @c mysql_mutex_t is a drop-in replacement for @c pthread_mutex_t. @sa mysql_mutex_assert_owner @sa mysql_mutex_assert_not_owner @sa mysql_mutex_init @sa mysql_mutex_lock @sa mysql_mutex_unlock @sa mysql_mutex_destroy */ typedef struct st_mysql_mutex mysql_mutex_t; /** An instrumented rwlock structure. @sa mysql_rwlock_t */ struct st_mysql_rwlock { /** The real rwlock */ rw_lock_t m_rwlock; /** The instrumentation hook. Note that this hook is not conditionally defined, for binary compatibility of the @c mysql_rwlock_t interface. */ struct PSI_rwlock *m_psi; }; /** An instrumented prlock structure. @sa mysql_prlock_t */ struct st_mysql_prlock { /** The real prlock */ rw_pr_lock_t m_prlock; /** The instrumentation hook. Note that this hook is not conditionally defined, for binary compatibility of the @c mysql_rwlock_t interface. */ struct PSI_rwlock *m_psi; }; /** Type of an instrumented rwlock. @c mysql_rwlock_t is a drop-in replacement for @c pthread_rwlock_t. @sa mysql_rwlock_init @sa mysql_rwlock_rdlock @sa mysql_rwlock_tryrdlock @sa mysql_rwlock_wrlock @sa mysql_rwlock_trywrlock @sa mysql_rwlock_unlock @sa mysql_rwlock_destroy */ typedef struct st_mysql_rwlock mysql_rwlock_t; /** Type of an instrumented prlock. A prlock is a read write lock that 'prefers readers' (pr). @c mysql_prlock_t is a drop-in replacement for @c rw_pr_lock_t. @sa mysql_prlock_init @sa mysql_prlock_rdlock @sa mysql_prlock_wrlock @sa mysql_prlock_unlock @sa mysql_prlock_destroy */ typedef struct st_mysql_prlock mysql_prlock_t; /** An instrumented cond structure. @sa mysql_cond_t */ struct st_mysql_cond { /** The real condition */ pthread_cond_t m_cond; /** The instrumentation hook. Note that this hook is not conditionally defined, for binary compatibility of the @c mysql_cond_t interface. */ struct PSI_cond *m_psi; }; /** Type of an instrumented condition. @c mysql_cond_t is a drop-in replacement for @c pthread_cond_t. @sa mysql_cond_init @sa mysql_cond_wait @sa mysql_cond_timedwait @sa mysql_cond_signal @sa mysql_cond_broadcast @sa mysql_cond_destroy */ typedef struct st_mysql_cond mysql_cond_t; /* Consider the following code: static inline void foo() { bar(); } when foo() is never called. With gcc, foo() is a local static function, so the dependencies are optimized away at compile time, and there is no dependency on bar(). With other compilers (HP, Sun Studio), the function foo() implementation is compiled, and bar() needs to be present to link. Due to the existing header dependencies in MySQL code, this header file is sometime used when it is not needed, which in turn cause link failures on some platforms. The proper fix would be to cut these extra dependencies in the calling code. DISABLE_MYSQL_THREAD_H is a work around to limit dependencies. DISABLE_MYSQL_PRLOCK_H is similar, and is used to disable specifically the prlock wrappers. */ #ifndef DISABLE_MYSQL_THREAD_H #define mysql_mutex_is_owner(M) safe_mutex_is_owner(&(M)->m_mutex) /** @def mysql_mutex_assert_owner(M) Wrapper, to use safe_mutex_assert_owner with instrumented mutexes. @c mysql_mutex_assert_owner is a drop-in replacement for @c safe_mutex_assert_owner. */ #define mysql_mutex_assert_owner(M) \ safe_mutex_assert_owner(&(M)->m_mutex) /** @def mysql_mutex_assert_not_owner(M) Wrapper, to use safe_mutex_assert_not_owner with instrumented mutexes. @c mysql_mutex_assert_not_owner is a drop-in replacement for @c safe_mutex_assert_not_owner. */ #define mysql_mutex_assert_not_owner(M) \ safe_mutex_assert_not_owner(&(M)->m_mutex) #define mysql_mutex_setflags(M, F) \ safe_mutex_setflags(&(M)->m_mutex, (F)) /** @def mysql_prlock_assert_write_owner(M) Drop-in replacement for @c rw_pr_lock_assert_write_owner. */ #define mysql_prlock_assert_write_owner(M) \ rw_pr_lock_assert_write_owner(&(M)->m_prlock) /** @def mysql_prlock_assert_not_write_owner(M) Drop-in replacement for @c rw_pr_lock_assert_not_write_owner. */ #define mysql_prlock_assert_not_write_owner(M) \ rw_pr_lock_assert_not_write_owner(&(M)->m_prlock) /** @def mysql_mutex_register(P1, P2, P3) Mutex registration. */ #define mysql_mutex_register(P1, P2, P3) \ inline_mysql_mutex_register(P1, P2, P3) /** @def mysql_mutex_init(K, M, A) Instrumented mutex_init. @c mysql_mutex_init is a replacement for @c pthread_mutex_init. @param K The PSI_mutex_key for this instrumented mutex @param M The mutex to initialize @param A Mutex attributes */ #ifdef HAVE_PSI_MUTEX_INTERFACE #ifdef SAFE_MUTEX #define mysql_mutex_init(K, M, A) \ inline_mysql_mutex_init(K, M, A, #M, __FILE__, __LINE__) #else #define mysql_mutex_init(K, M, A) \ inline_mysql_mutex_init(K, M, A) #endif #else #ifdef SAFE_MUTEX #define mysql_mutex_init(K, M, A) \ inline_mysql_mutex_init(M, A, #M, __FILE__, __LINE__) #else #define mysql_mutex_init(K, M, A) \ inline_mysql_mutex_init(M, A) #endif #endif /** @def mysql_mutex_destroy(M) Instrumented mutex_destroy. @c mysql_mutex_destroy is a drop-in replacement for @c pthread_mutex_destroy. */ #ifdef SAFE_MUTEX #define mysql_mutex_destroy(M) \ inline_mysql_mutex_destroy(M, __FILE__, __LINE__) #else #define mysql_mutex_destroy(M) \ inline_mysql_mutex_destroy(M) #endif /** @def mysql_mutex_lock(M) Instrumented mutex_lock. @c mysql_mutex_lock is a drop-in replacement for @c pthread_mutex_lock. @param M The mutex to lock */ #if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) #define mysql_mutex_lock(M) \ inline_mysql_mutex_lock(M, __FILE__, __LINE__) #else #define mysql_mutex_lock(M) \ inline_mysql_mutex_lock(M) #endif /** @def mysql_mutex_trylock(M) Instrumented mutex_lock. @c mysql_mutex_trylock is a drop-in replacement for @c pthread_mutex_trylock. */ #if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) #define mysql_mutex_trylock(M) \ inline_mysql_mutex_trylock(M, __FILE__, __LINE__) #else #define mysql_mutex_trylock(M) \ inline_mysql_mutex_trylock(M) #endif /** @def mysql_mutex_unlock(M) Instrumented mutex_unlock. @c mysql_mutex_unlock is a drop-in replacement for @c pthread_mutex_unlock. */ #ifdef SAFE_MUTEX #define mysql_mutex_unlock(M) \ inline_mysql_mutex_unlock(M, __FILE__, __LINE__) #else #define mysql_mutex_unlock(M) \ inline_mysql_mutex_unlock(M) #endif /** @def mysql_rwlock_register(P1, P2, P3) Rwlock registration. */ #define mysql_rwlock_register(P1, P2, P3) \ inline_mysql_rwlock_register(P1, P2, P3) /** @def mysql_rwlock_init(K, RW) Instrumented rwlock_init. @c mysql_rwlock_init is a replacement for @c pthread_rwlock_init. Note that pthread_rwlockattr_t is not supported in MySQL. @param K The PSI_rwlock_key for this instrumented rwlock @param RW The rwlock to initialize */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_rwlock_init(K, RW) inline_mysql_rwlock_init(K, RW) #else #define mysql_rwlock_init(K, RW) inline_mysql_rwlock_init(RW) #endif /** @def mysql_prlock_init(K, RW) Instrumented rw_pr_init. @c mysql_prlock_init is a replacement for @c rw_pr_init. @param K The PSI_rwlock_key for this instrumented prlock @param RW The prlock to initialize */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_prlock_init(K, RW) inline_mysql_prlock_init(K, RW) #else #define mysql_prlock_init(K, RW) inline_mysql_prlock_init(RW) #endif /** @def mysql_rwlock_destroy(RW) Instrumented rwlock_destroy. @c mysql_rwlock_destroy is a drop-in replacement for @c pthread_rwlock_destroy. */ #define mysql_rwlock_destroy(RW) inline_mysql_rwlock_destroy(RW) /** @def mysql_prlock_destroy(RW) Instrumented rw_pr_destroy. @c mysql_prlock_destroy is a drop-in replacement for @c rw_pr_destroy. */ #define mysql_prlock_destroy(RW) inline_mysql_prlock_destroy(RW) /** @def mysql_rwlock_rdlock(RW) Instrumented rwlock_rdlock. @c mysql_rwlock_rdlock is a drop-in replacement for @c pthread_rwlock_rdlock. */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_rwlock_rdlock(RW) \ inline_mysql_rwlock_rdlock(RW, __FILE__, __LINE__) #else #define mysql_rwlock_rdlock(RW) \ inline_mysql_rwlock_rdlock(RW) #endif /** @def mysql_prlock_rdlock(RW) Instrumented rw_pr_rdlock. @c mysql_prlock_rdlock is a drop-in replacement for @c rw_pr_rdlock. */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_prlock_rdlock(RW) \ inline_mysql_prlock_rdlock(RW, __FILE__, __LINE__) #else #define mysql_prlock_rdlock(RW) \ inline_mysql_prlock_rdlock(RW) #endif /** @def mysql_rwlock_wrlock(RW) Instrumented rwlock_wrlock. @c mysql_rwlock_wrlock is a drop-in replacement for @c pthread_rwlock_wrlock. */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_rwlock_wrlock(RW) \ inline_mysql_rwlock_wrlock(RW, __FILE__, __LINE__) #else #define mysql_rwlock_wrlock(RW) \ inline_mysql_rwlock_wrlock(RW) #endif /** @def mysql_prlock_wrlock(RW) Instrumented rw_pr_wrlock. @c mysql_prlock_wrlock is a drop-in replacement for @c rw_pr_wrlock. */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_prlock_wrlock(RW) \ inline_mysql_prlock_wrlock(RW, __FILE__, __LINE__) #else #define mysql_prlock_wrlock(RW) \ inline_mysql_prlock_wrlock(RW) #endif /** @def mysql_rwlock_tryrdlock(RW) Instrumented rwlock_tryrdlock. @c mysql_rwlock_tryrdlock is a drop-in replacement for @c pthread_rwlock_tryrdlock. */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_rwlock_tryrdlock(RW) \ inline_mysql_rwlock_tryrdlock(RW, __FILE__, __LINE__) #else #define mysql_rwlock_tryrdlock(RW) \ inline_mysql_rwlock_tryrdlock(RW) #endif /** @def mysql_rwlock_trywrlock(RW) Instrumented rwlock_trywrlock. @c mysql_rwlock_trywrlock is a drop-in replacement for @c pthread_rwlock_trywrlock. */ #ifdef HAVE_PSI_RWLOCK_INTERFACE #define mysql_rwlock_trywrlock(RW) \ inline_mysql_rwlock_trywrlock(RW, __FILE__, __LINE__) #else #define mysql_rwlock_trywrlock(RW) \ inline_mysql_rwlock_trywrlock(RW) #endif /** @def mysql_rwlock_unlock(RW) Instrumented rwlock_unlock. @c mysql_rwlock_unlock is a drop-in replacement for @c pthread_rwlock_unlock. */ #define mysql_rwlock_unlock(RW) inline_mysql_rwlock_unlock(RW) /** @def mysql_prlock_unlock(RW) Instrumented rw_pr_unlock. @c mysql_prlock_unlock is a drop-in replacement for @c rw_pr_unlock. */ #define mysql_prlock_unlock(RW) inline_mysql_prlock_unlock(RW) /** @def mysql_cond_register(P1, P2, P3) Cond registration. */ #define mysql_cond_register(P1, P2, P3) \ inline_mysql_cond_register(P1, P2, P3) /** @def mysql_cond_init(K, C, A) Instrumented cond_init. @c mysql_cond_init is a replacement for @c pthread_cond_init. @param C The cond to initialize @param K The PSI_cond_key for this instrumented cond @param A Condition attributes */ #ifdef HAVE_PSI_COND_INTERFACE #define mysql_cond_init(K, C, A) inline_mysql_cond_init(K, C, A) #else #define mysql_cond_init(K, C, A) inline_mysql_cond_init(C, A) #endif /** @def mysql_cond_destroy(C) Instrumented cond_destroy. @c mysql_cond_destroy is a drop-in replacement for @c pthread_cond_destroy. */ #define mysql_cond_destroy(C) inline_mysql_cond_destroy(C) /** @def mysql_cond_wait(C) Instrumented cond_wait. @c mysql_cond_wait is a drop-in replacement for @c pthread_cond_wait. */ #if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) #define mysql_cond_wait(C, M) \ inline_mysql_cond_wait(C, M, __FILE__, __LINE__) #else #define mysql_cond_wait(C, M) \ inline_mysql_cond_wait(C, M) #endif /** @def mysql_cond_timedwait(C, M, W) Instrumented cond_timedwait. @c mysql_cond_timedwait is a drop-in replacement for @c pthread_cond_timedwait. */ #if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) #define mysql_cond_timedwait(C, M, W) \ inline_mysql_cond_timedwait(C, M, W, __FILE__, __LINE__) #else #define mysql_cond_timedwait(C, M, W) \ inline_mysql_cond_timedwait(C, M, W) #endif /** @def mysql_cond_signal(C) Instrumented cond_signal. @c mysql_cond_signal is a drop-in replacement for @c pthread_cond_signal. */ #define mysql_cond_signal(C) inline_mysql_cond_signal(C) /** @def mysql_cond_broadcast(C) Instrumented cond_broadcast. @c mysql_cond_broadcast is a drop-in replacement for @c pthread_cond_broadcast. */ #define mysql_cond_broadcast(C) inline_mysql_cond_broadcast(C) /** @def mysql_thread_register(P1, P2, P3) Thread registration. */ #define mysql_thread_register(P1, P2, P3) \ inline_mysql_thread_register(P1, P2, P3) /** @def mysql_thread_create(K, P1, P2, P3, P4) Instrumented pthread_create. This function creates both the thread instrumentation and a thread. @c mysql_thread_create is a replacement for @c pthread_create. The parameter P4 (or, if it is NULL, P1) will be used as the instrumented thread "identity". Providing a P1 / P4 parameter with a different value for each call will on average improve performances, since this thread identity value is used internally to randomize access to data and prevent contention. This is optional, and the improvement is not guaranteed, only statistical. @param K The PSI_thread_key for this instrumented thread @param P1 pthread_create parameter 1 @param P2 pthread_create parameter 2 @param P3 pthread_create parameter 3 @param P4 pthread_create parameter 4 */ #ifdef HAVE_PSI_THREAD_INTERFACE #define mysql_thread_create(K, P1, P2, P3, P4) \ inline_mysql_thread_create(K, P1, P2, P3, P4) #else #define mysql_thread_create(K, P1, P2, P3, P4) \ pthread_create(P1, P2, P3, P4) #endif /** @def mysql_thread_set_psi_id(I) Set the thread identifier for the instrumentation. @param I The thread identifier */ #ifdef HAVE_PSI_THREAD_INTERFACE #define mysql_thread_set_psi_id(I) inline_mysql_thread_set_psi_id(I) #else #define mysql_thread_set_psi_id(I) do {} while (0) #endif /** @def mysql_thread_set_psi_THD(T) Set the thread sql session for the instrumentation. @param I The thread identifier */ #ifdef HAVE_PSI_THREAD_INTERFACE #define mysql_thread_set_psi_THD(T) inline_mysql_thread_set_psi_THD(T) #else #define mysql_thread_set_psi_THD(T) do {} while (0) #endif static inline void inline_mysql_mutex_register( #ifdef HAVE_PSI_MUTEX_INTERFACE const char *category, PSI_mutex_info *info, int count #else const char *category __attribute__ ((unused)), void *info __attribute__ ((unused)), int count __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_MUTEX_INTERFACE PSI_MUTEX_CALL(register_mutex)(category, info, count); #endif } static inline int inline_mysql_mutex_init( #ifdef HAVE_PSI_MUTEX_INTERFACE PSI_mutex_key key, #endif mysql_mutex_t *that, const pthread_mutexattr_t *attr #ifdef SAFE_MUTEX , const char *src_name, const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_MUTEX_INTERFACE that->m_psi= PSI_MUTEX_CALL(init_mutex)(key, &that->m_mutex); #else that->m_psi= NULL; #endif #ifdef SAFE_MUTEX return safe_mutex_init(&that->m_mutex, attr, src_name, src_file, src_line); #else return pthread_mutex_init(&that->m_mutex, attr); #endif } static inline int inline_mysql_mutex_destroy( mysql_mutex_t *that #ifdef SAFE_MUTEX , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_MUTEX_INTERFACE if (that->m_psi != NULL) { PSI_MUTEX_CALL(destroy_mutex)(that->m_psi); that->m_psi= NULL; } #endif #ifdef SAFE_MUTEX return safe_mutex_destroy(&that->m_mutex, src_file, src_line); #else return pthread_mutex_destroy(&that->m_mutex); #endif } #ifdef HAVE_PSI_MUTEX_INTERFACE ATTRIBUTE_COLD int psi_mutex_lock(mysql_mutex_t *that, const char *file, uint line); ATTRIBUTE_COLD int psi_mutex_trylock(mysql_mutex_t *that, const char *file, uint line); #endif static inline int inline_mysql_mutex_lock( mysql_mutex_t *that #if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_MUTEX_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_mutex_lock(that, src_file, src_line); #endif /* Non instrumented code */ #ifdef SAFE_MUTEX return safe_mutex_lock(&that->m_mutex, FALSE, src_file, src_line); #else return pthread_mutex_lock(&that->m_mutex); #endif } static inline int inline_mysql_mutex_trylock( mysql_mutex_t *that #if defined(SAFE_MUTEX) || defined (HAVE_PSI_MUTEX_INTERFACE) , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_MUTEX_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_mutex_trylock(that, src_file, src_line); #endif /* Non instrumented code */ #ifdef SAFE_MUTEX return safe_mutex_lock(&that->m_mutex, TRUE, src_file, src_line); #else return pthread_mutex_trylock(&that->m_mutex); #endif } static inline int inline_mysql_mutex_unlock( mysql_mutex_t *that #ifdef SAFE_MUTEX , const char *src_file, uint src_line #endif ) { int result; #ifdef HAVE_PSI_MUTEX_INTERFACE if (psi_likely(that->m_psi != NULL)) PSI_MUTEX_CALL(unlock_mutex)(that->m_psi); #endif #ifdef SAFE_MUTEX result= safe_mutex_unlock(&that->m_mutex, src_file, src_line); #else result= pthread_mutex_unlock(&that->m_mutex); #endif return result; } static inline void inline_mysql_rwlock_register( #ifdef HAVE_PSI_RWLOCK_INTERFACE const char *category, PSI_rwlock_info *info, int count #else const char *category __attribute__ ((unused)), void *info __attribute__ ((unused)), int count __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE PSI_RWLOCK_CALL(register_rwlock)(category, info, count); #endif } static inline int inline_mysql_rwlock_init( #ifdef HAVE_PSI_RWLOCK_INTERFACE PSI_rwlock_key key, #endif mysql_rwlock_t *that) { #ifdef HAVE_PSI_RWLOCK_INTERFACE that->m_psi= PSI_RWLOCK_CALL(init_rwlock)(key, &that->m_rwlock); #else that->m_psi= NULL; #endif /* pthread_rwlockattr_t is not used in MySQL. */ return my_rwlock_init(&that->m_rwlock, NULL); } #ifndef DISABLE_MYSQL_PRLOCK_H static inline int inline_mysql_prlock_init( #ifdef HAVE_PSI_RWLOCK_INTERFACE PSI_rwlock_key key, #endif mysql_prlock_t *that) { #ifdef HAVE_PSI_RWLOCK_INTERFACE that->m_psi= PSI_RWLOCK_CALL(init_rwlock)(key, &that->m_prlock); #else that->m_psi= NULL; #endif return rw_pr_init(&that->m_prlock); } #endif static inline int inline_mysql_rwlock_destroy( mysql_rwlock_t *that) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) { PSI_RWLOCK_CALL(destroy_rwlock)(that->m_psi); that->m_psi= NULL; } #endif return rwlock_destroy(&that->m_rwlock); } #ifndef DISABLE_MYSQL_PRLOCK_H static inline int inline_mysql_prlock_destroy( mysql_prlock_t *that) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) { PSI_RWLOCK_CALL(destroy_rwlock)(that->m_psi); that->m_psi= NULL; } #endif return rw_pr_destroy(&that->m_prlock); } #endif #ifdef HAVE_PSI_RWLOCK_INTERFACE ATTRIBUTE_COLD int psi_rwlock_rdlock(mysql_rwlock_t *that, const char *file, uint line); ATTRIBUTE_COLD int psi_rwlock_tryrdlock(mysql_rwlock_t *that, const char *file, uint line); ATTRIBUTE_COLD int psi_rwlock_wrlock(mysql_rwlock_t *that, const char *file, uint line); ATTRIBUTE_COLD int psi_rwlock_trywrlock(mysql_rwlock_t *that, const char *file, uint line); # ifndef DISABLE_MYSQL_PRLOCK_H ATTRIBUTE_COLD int psi_prlock_rdlock(mysql_prlock_t *that, const char *file, uint line); ATTRIBUTE_COLD int psi_prlock_wrlock(mysql_prlock_t *that, const char *file, uint line); # endif #endif static inline int inline_mysql_rwlock_rdlock( mysql_rwlock_t *that #ifdef HAVE_PSI_RWLOCK_INTERFACE , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_rwlock_rdlock(that, src_file, src_line); #endif return rw_rdlock(&that->m_rwlock); } #ifndef DISABLE_MYSQL_PRLOCK_H static inline int inline_mysql_prlock_rdlock( mysql_prlock_t *that #ifdef HAVE_PSI_RWLOCK_INTERFACE , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_prlock_rdlock(that, src_file, src_line); #endif return rw_pr_rdlock(&that->m_prlock); } #endif static inline int inline_mysql_rwlock_wrlock( mysql_rwlock_t *that #ifdef HAVE_PSI_RWLOCK_INTERFACE , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_rwlock_wrlock(that, src_file, src_line); #endif return rw_wrlock(&that->m_rwlock); } #ifndef DISABLE_MYSQL_PRLOCK_H static inline int inline_mysql_prlock_wrlock( mysql_prlock_t *that #ifdef HAVE_PSI_RWLOCK_INTERFACE , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_prlock_wrlock(that, src_file, src_line); #endif return rw_pr_wrlock(&that->m_prlock); } #endif static inline int inline_mysql_rwlock_tryrdlock( mysql_rwlock_t *that #ifdef HAVE_PSI_RWLOCK_INTERFACE , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_rwlock_tryrdlock(that, src_file, src_line); #endif return rw_tryrdlock(&that->m_rwlock); } static inline int inline_mysql_rwlock_trywrlock( mysql_rwlock_t *that #ifdef HAVE_PSI_RWLOCK_INTERFACE , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_rwlock_trywrlock(that, src_file, src_line); #endif return rw_trywrlock(&that->m_rwlock); } static inline int inline_mysql_rwlock_unlock( mysql_rwlock_t *that) { int result; #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) PSI_RWLOCK_CALL(unlock_rwlock)(that->m_psi); #endif result= rw_unlock(&that->m_rwlock); return result; } #ifndef DISABLE_MYSQL_PRLOCK_H static inline int inline_mysql_prlock_unlock( mysql_prlock_t *that) { int result; #ifdef HAVE_PSI_RWLOCK_INTERFACE if (psi_likely(that->m_psi != NULL)) PSI_RWLOCK_CALL(unlock_rwlock)(that->m_psi); #endif result= rw_pr_unlock(&that->m_prlock); return result; } #endif static inline void inline_mysql_cond_register( #ifdef HAVE_PSI_COND_INTERFACE const char *category, PSI_cond_info *info, int count #else const char *category __attribute__ ((unused)), void *info __attribute__ ((unused)), int count __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_COND_INTERFACE PSI_COND_CALL(register_cond)(category, info, count); #endif } static inline int inline_mysql_cond_init( #ifdef HAVE_PSI_COND_INTERFACE PSI_cond_key key, #endif mysql_cond_t *that, const pthread_condattr_t *attr) { #ifdef HAVE_PSI_COND_INTERFACE that->m_psi= PSI_COND_CALL(init_cond)(key, &that->m_cond); #else that->m_psi= NULL; #endif return pthread_cond_init(&that->m_cond, attr); } static inline int inline_mysql_cond_destroy( mysql_cond_t *that) { #ifdef HAVE_PSI_COND_INTERFACE if (psi_likely(that->m_psi != NULL)) { PSI_COND_CALL(destroy_cond)(that->m_psi); that->m_psi= NULL; } #endif return pthread_cond_destroy(&that->m_cond); } #ifdef HAVE_PSI_COND_INTERFACE ATTRIBUTE_COLD int psi_cond_wait(mysql_cond_t *that, mysql_mutex_t *mutex, const char *file, uint line); ATTRIBUTE_COLD int psi_cond_timedwait(mysql_cond_t *that, mysql_mutex_t *mutex, const struct timespec *abstime, const char *file, uint line); #endif static inline int inline_mysql_cond_wait( mysql_cond_t *that, mysql_mutex_t *mutex #if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_COND_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_cond_wait(that, mutex, src_file, src_line); #endif return my_cond_wait(&that->m_cond, &mutex->m_mutex); } static inline int inline_mysql_cond_timedwait( mysql_cond_t *that, mysql_mutex_t *mutex, const struct timespec *abstime #if defined(SAFE_MUTEX) || defined(HAVE_PSI_COND_INTERFACE) , const char *src_file, uint src_line #endif ) { #ifdef HAVE_PSI_COND_INTERFACE if (psi_likely(that->m_psi != NULL)) return psi_cond_timedwait(that, mutex, abstime, src_file, src_line); #endif return my_cond_timedwait(&that->m_cond, &mutex->m_mutex, abstime); } static inline int inline_mysql_cond_signal( mysql_cond_t *that) { int result; #ifdef HAVE_PSI_COND_INTERFACE if (psi_likely(that->m_psi != NULL)) PSI_COND_CALL(signal_cond)(that->m_psi); #endif result= pthread_cond_signal(&that->m_cond); return result; } static inline int inline_mysql_cond_broadcast( mysql_cond_t *that) { int result; #ifdef HAVE_PSI_COND_INTERFACE if (psi_likely(that->m_psi != NULL)) PSI_COND_CALL(broadcast_cond)(that->m_psi); #endif result= pthread_cond_broadcast(&that->m_cond); return result; } static inline void inline_mysql_thread_register( #ifdef HAVE_PSI_THREAD_INTERFACE const char *category, PSI_thread_info *info, int count #else const char *category __attribute__ ((unused)), void *info __attribute__ ((unused)), int count __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_THREAD_INTERFACE PSI_THREAD_CALL(register_thread)(category, info, count); #endif } #ifdef HAVE_PSI_THREAD_INTERFACE static inline int inline_mysql_thread_create( PSI_thread_key key, pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg) { int result; result= PSI_THREAD_CALL(spawn_thread)(key, thread, attr, start_routine, arg); return result; } static inline void inline_mysql_thread_set_psi_id(my_thread_id id) { struct PSI_thread *psi= PSI_THREAD_CALL(get_thread)(); PSI_THREAD_CALL(set_thread_id)(psi, id); } #ifdef __cplusplus class THD; static inline void inline_mysql_thread_set_psi_THD(THD *thd) { struct PSI_thread *psi= PSI_THREAD_CALL(get_thread)(); PSI_THREAD_CALL(set_thread_THD)(psi, thd); } #endif /* __cplusplus */ static inline void mysql_thread_set_peer_port(uint port __attribute__ ((unused))) { #ifdef HAVE_PSI_THREAD_INTERFACE struct PSI_thread *psi = PSI_THREAD_CALL(get_thread)(); PSI_THREAD_CALL(set_thread_peer_port)(psi, port); #endif } #endif #endif /* DISABLE_MYSQL_THREAD_H */ /** @} (end of group Thread_instrumentation) */ #endif mysql/server/mysql/psi/mysql_stage.h000064400000012112151027430560013660 0ustar00/* Copyright (c) 2010, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_STAGE_H #define MYSQL_STAGE_H /** @file mysql/psi/mysql_stage.h Instrumentation helpers for stages. */ #include "mysql/psi/psi.h" #ifndef PSI_STAGE_CALL #define PSI_STAGE_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Stage_instrumentation Stage Instrumentation @ingroup Instrumentation_interface @{ */ /** @def mysql_stage_register(P1, P2, P3) Stage registration. */ #ifdef HAVE_PSI_STAGE_INTERFACE #define mysql_stage_register(P1, P2, P3) \ inline_mysql_stage_register(P1, P2, P3) #else #define mysql_stage_register(P1, P2, P3) \ do {} while (0) #endif /** @def MYSQL_SET_STAGE Set the current stage. Use this API when the file and line is passed from the caller. @param K the stage key @param F the source file name @param L the source file line @return the current stage progress */ #ifdef HAVE_PSI_STAGE_INTERFACE #define MYSQL_SET_STAGE(K, F, L) \ inline_mysql_set_stage(K, F, L) #else #define MYSQL_SET_STAGE(K, F, L) \ NULL #endif /** @def mysql_set_stage Set the current stage. @param K the stage key @return the current stage progress */ #ifdef HAVE_PSI_STAGE_INTERFACE #define mysql_set_stage(K) \ inline_mysql_set_stage(K, __FILE__, __LINE__) #else #define mysql_set_stage(K) \ NULL #endif /** @def mysql_end_stage End the last stage */ #ifdef HAVE_PSI_STAGE_INTERFACE #define mysql_end_stage() \ inline_mysql_end_stage() #else #define mysql_end_stage() \ do {} while (0) #endif #ifdef HAVE_PSI_STAGE_INTERFACE static inline void inline_mysql_stage_register( const char *category, PSI_stage_info **info, int count) { PSI_STAGE_CALL(register_stage)(category, info, count); } #endif #ifdef HAVE_PSI_STAGE_INTERFACE static inline PSI_stage_progress* inline_mysql_set_stage(PSI_stage_key key, const char *src_file, int src_line) { return PSI_STAGE_CALL(start_stage)(key, src_file, src_line); } #endif #ifdef HAVE_PSI_STAGE_INTERFACE static inline void inline_mysql_end_stage() { PSI_STAGE_CALL(end_stage)(); } #endif #ifdef HAVE_PSI_STAGE_INTERFACE #define mysql_stage_set_work_completed(P1, P2) \ inline_mysql_stage_set_work_completed(P1, P2) #define mysql_stage_get_work_completed(P1) \ inline_mysql_stage_get_work_completed(P1) #else #define mysql_stage_set_work_completed(P1, P2) \ do {} while (0) #define mysql_stage_get_work_completed(P1) \ do {} while (0) #endif #ifdef HAVE_PSI_STAGE_INTERFACE #define mysql_stage_inc_work_completed(P1, P2) \ inline_mysql_stage_inc_work_completed(P1, P2) #else #define mysql_stage_inc_work_completed(P1, P2) \ do {} while (0) #endif #ifdef HAVE_PSI_STAGE_INTERFACE #define mysql_stage_set_work_estimated(P1, P2) \ inline_mysql_stage_set_work_estimated(P1, P2) #define mysql_stage_get_work_estimated(P1) \ inline_mysql_stage_get_work_estimated(P1) #else #define mysql_stage_set_work_estimated(P1, P2) \ do {} while (0) #define mysql_stage_get_work_estimated(P1) \ do {} while (0) #endif #ifdef HAVE_PSI_STAGE_INTERFACE static inline void inline_mysql_stage_set_work_completed(PSI_stage_progress *progress, ulonglong val) { if (progress != NULL) progress->m_work_completed= val; } static inline ulonglong inline_mysql_stage_get_work_completed(PSI_stage_progress *progress) { return progress->m_work_completed; } #endif #ifdef HAVE_PSI_STAGE_INTERFACE static inline void inline_mysql_stage_inc_work_completed(PSI_stage_progress *progress, ulonglong val) { if (progress != NULL) progress->m_work_completed+= val; } #endif #ifdef HAVE_PSI_STAGE_INTERFACE static inline void inline_mysql_stage_set_work_estimated(PSI_stage_progress *progress, ulonglong val) { if (progress != NULL) progress->m_work_estimated= val; } static inline ulonglong inline_mysql_stage_get_work_estimated(PSI_stage_progress *progress) { return progress->m_work_estimated; } #endif /** @} (end of group Stage_instrumentation) */ #endif mysql/server/mysql/psi/mysql_ps.h000064400000007447151027430560013216 0ustar00/* Copyright (c) 2014, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MYSQL_PS_H #define MYSQL_PS_H /** @file mysql/psi/mysql_ps.h Instrumentation helpers for prepared statements. */ #include "mysql/psi/psi.h" #ifndef PSI_PS_CALL #define PSI_PS_CALL(M) PSI_DYNAMIC_CALL(M) #endif #ifdef HAVE_PSI_PS_INTERFACE #define MYSQL_CREATE_PS(IDENTITY, ID, LOCKER, NAME, NAME_LENGTH) \ inline_mysql_create_prepared_stmt(IDENTITY, ID, LOCKER, NAME, NAME_LENGTH) #define MYSQL_EXECUTE_PS(LOCKER, PREPARED_STMT) \ inline_mysql_execute_prepared_stmt(LOCKER, PREPARED_STMT) #define MYSQL_DESTROY_PS(PREPARED_STMT) \ inline_mysql_destroy_prepared_stmt(PREPARED_STMT) #define MYSQL_REPREPARE_PS(PREPARED_STMT) \ inline_mysql_reprepare_prepared_stmt(PREPARED_STMT) #define MYSQL_SET_PS_TEXT(PREPARED_STMT, SQLTEXT, SQLTEXT_LENGTH) \ inline_mysql_set_prepared_stmt_text(PREPARED_STMT, SQLTEXT, SQLTEXT_LENGTH) #else #define MYSQL_CREATE_PS(IDENTITY, ID, LOCKER, NAME, NAME_LENGTH) \ NULL #define MYSQL_EXECUTE_PS(LOCKER, PREPARED_STMT) \ do {} while (0) #define MYSQL_DESTROY_PS(PREPARED_STMT) \ do {} while (0) #define MYSQL_REPREPARE_PS(PREPARED_STMT) \ do {} while (0) #define MYSQL_SET_PS_TEXT(PREPARED_STMT, SQLTEXT, SQLTEXT_LENGTH) \ do {} while (0) #endif #ifdef HAVE_PSI_PS_INTERFACE static inline struct PSI_prepared_stmt* inline_mysql_create_prepared_stmt(void *identity, uint stmt_id, PSI_statement_locker *locker, const char *stmt_name, size_t stmt_name_length) { if (locker == NULL) return NULL; return PSI_PS_CALL(create_prepared_stmt)(identity, stmt_id, locker, stmt_name, stmt_name_length); } static inline void inline_mysql_execute_prepared_stmt(PSI_statement_locker *locker, PSI_prepared_stmt* prepared_stmt) { if (prepared_stmt != NULL && locker != NULL) PSI_PS_CALL(execute_prepared_stmt)(locker, prepared_stmt); } static inline void inline_mysql_destroy_prepared_stmt(PSI_prepared_stmt *prepared_stmt) { if (prepared_stmt != NULL) PSI_PS_CALL(destroy_prepared_stmt)(prepared_stmt); } static inline void inline_mysql_reprepare_prepared_stmt(PSI_prepared_stmt *prepared_stmt) { if (prepared_stmt != NULL) PSI_PS_CALL(reprepare_prepared_stmt)(prepared_stmt); } static inline void inline_mysql_set_prepared_stmt_text(PSI_prepared_stmt *prepared_stmt, const char *text, uint text_len) { if (prepared_stmt != NULL) { PSI_PS_CALL(set_prepared_stmt_text)(prepared_stmt, text, text_len); } } #endif #endif mysql/server/mysql/psi/mysql_memory.h000064400000005067151027430560014100 0ustar00/* Copyright (c) 2012, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef MYSQL_MEMORY_H #define MYSQL_MEMORY_H /** @file mysql/psi/mysql_memory.h Instrumentation helpers for memory allocation. */ #include "mysql/psi/psi.h" #ifdef HAVE_PSI_MEMORY_INTERFACE #define PSI_CALL_memory_alloc(A1,A2,A3) PSI_MEMORY_CALL(memory_alloc)(A1,A2,A3) #define PSI_CALL_memory_free(A1,A2,A3) PSI_MEMORY_CALL(memory_free)(A1,A2,A3) #define PSI_CALL_memory_realloc(A1,A2,A3,A4) PSI_MEMORY_CALL(memory_realloc)(A1,A2,A3,A4) #define PSI_CALL_register_memory(A1,A2,A3) PSI_MEMORY_CALL(register_memory)(A1,A2,A3) #else #define PSI_CALL_memory_alloc(A1,A2,A3) 0 #define PSI_CALL_memory_free(A1,A2,A3) do { } while(0) #define PSI_CALL_memory_realloc(A1,A2,A3,A4) 0 #define PSI_CALL_register_memory(A1,A2,A3) do { } while(0) #endif #ifndef PSI_MEMORY_CALL #define PSI_MEMORY_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Memory_instrumentation Memory Instrumentation @ingroup Instrumentation_interface @{ */ /** @def mysql_memory_register(P1, P2, P3) Memory registration. */ #define mysql_memory_register(P1, P2, P3) \ inline_mysql_memory_register(P1, P2, P3) static inline void inline_mysql_memory_register( #ifdef HAVE_PSI_MEMORY_INTERFACE const char *category, PSI_memory_info *info, int count) #else const char *category __attribute__((unused)), void *info __attribute__((unused)), int count __attribute__((unused))) #endif { PSI_CALL_register_memory(category, info, count); } /** @} (end of group Memory_instrumentation) */ #endif mysql/server/mysql/psi/mysql_transaction.h000064400000016100151027430560015103 0ustar00/* Copyright (c) 2013, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MYSQL_TRANSACTION_H #define MYSQL_TRANSACTION_H /** @file mysql/psi/mysql_transaction.h Instrumentation helpers for transactions. */ #include "mysql/psi/psi.h" #ifndef PSI_TRANSACTION_CALL #define PSI_TRANSACTION_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Transaction_instrumentation Transaction Instrumentation @ingroup Instrumentation_interface @{ */ #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_START_TRANSACTION(STATE, XID, TRXID, ISO, RO, AC) \ inline_mysql_start_transaction(STATE, XID, TRXID, ISO, RO, AC, __FILE__, __LINE__) #else #define MYSQL_START_TRANSACTION(STATE, XID, TRXID, ISO, RO, AC) \ 0 #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_SET_TRANSACTION_GTID(LOCKER, P1, P2) \ inline_mysql_set_transaction_gtid(LOCKER, P1, P2) #else #define MYSQL_SET_TRANSACTION_GTID(LOCKER, P1, P2) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_SET_TRANSACTION_XID(LOCKER, P1, P2) \ inline_mysql_set_transaction_xid(LOCKER, P1, P2) #else #define MYSQL_SET_TRANSACTION_XID(LOCKER, P1, P2) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_SET_TRANSACTION_XA_STATE(LOCKER, P1) \ inline_mysql_set_transaction_xa_state(LOCKER, P1) #else #define MYSQL_SET_TRANSACTION_XA_STATE(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_SET_TRANSACTION_TRXID(LOCKER, P1) \ inline_mysql_set_transaction_trxid(LOCKER, P1) #else #define MYSQL_SET_TRANSACTION_TRXID(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_INC_TRANSACTION_SAVEPOINTS(LOCKER, P1) \ inline_mysql_inc_transaction_savepoints(LOCKER, P1) #else #define MYSQL_INC_TRANSACTION_SAVEPOINTS(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_INC_TRANSACTION_ROLLBACK_TO_SAVEPOINT(LOCKER, P1) \ inline_mysql_inc_transaction_rollback_to_savepoint(LOCKER, P1) #else #define MYSQL_INC_TRANSACTION_ROLLBACK_TO_SAVEPOINT(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_INC_TRANSACTION_RELEASE_SAVEPOINT(LOCKER, P1) \ inline_mysql_inc_transaction_release_savepoint(LOCKER, P1) #else #define MYSQL_INC_TRANSACTION_RELEASE_SAVEPOINT(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_ROLLBACK_TRANSACTION(LOCKER) \ inline_mysql_rollback_transaction(LOCKER) #else #define MYSQL_ROLLBACK_TRANSACTION(LOCKER) \ do { } while(0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE #define MYSQL_COMMIT_TRANSACTION(LOCKER) \ inline_mysql_commit_transaction(LOCKER) #else #define MYSQL_COMMIT_TRANSACTION(LOCKER) \ do { } while(0) #endif #ifdef HAVE_PSI_TRANSACTION_INTERFACE static inline struct PSI_transaction_locker * inline_mysql_start_transaction(PSI_transaction_locker_state *state, const void *xid, ulonglong trxid, int isolation_level, my_bool read_only, my_bool autocommit, const char *src_file, int src_line) { PSI_transaction_locker *locker; locker= PSI_TRANSACTION_CALL(get_thread_transaction_locker)(state, xid, trxid, isolation_level, read_only, autocommit); if (likely(locker != NULL)) PSI_TRANSACTION_CALL(start_transaction)(locker, src_file, src_line); return locker; } static inline void inline_mysql_set_transaction_gtid(PSI_transaction_locker *locker, const void *sid, const void *gtid_spec) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(set_transaction_gtid)(locker, sid, gtid_spec); } static inline void inline_mysql_set_transaction_xid(PSI_transaction_locker *locker, const void *xid, int xa_state) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(set_transaction_xid)(locker, xid, xa_state); } static inline void inline_mysql_set_transaction_xa_state(PSI_transaction_locker *locker, int xa_state) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(set_transaction_xa_state)(locker, xa_state); } static inline void inline_mysql_set_transaction_trxid(PSI_transaction_locker *locker, const ulonglong *trxid) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(set_transaction_trxid)(locker, trxid); } static inline void inline_mysql_inc_transaction_savepoints(PSI_transaction_locker *locker, ulong count) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(inc_transaction_savepoints)(locker, count); } static inline void inline_mysql_inc_transaction_rollback_to_savepoint(PSI_transaction_locker *locker, ulong count) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(inc_transaction_rollback_to_savepoint)(locker, count); } static inline void inline_mysql_inc_transaction_release_savepoint(PSI_transaction_locker *locker, ulong count) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(inc_transaction_release_savepoint)(locker, count); } static inline void inline_mysql_rollback_transaction(struct PSI_transaction_locker *locker) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(end_transaction)(locker, false); } static inline void inline_mysql_commit_transaction(struct PSI_transaction_locker *locker) { if (likely(locker != NULL)) PSI_TRANSACTION_CALL(end_transaction)(locker, true); } #endif /** @} (end of group Transaction_instrumentation) */ #endif mysql/server/mysql/psi/mysql_sp.h000064400000006250151027430560013205 0ustar00/* Copyright (c) 2013, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MYSQL_SP_H #define MYSQL_SP_H /** @file mysql/psi/mysql_sp.h Instrumentation helpers for stored programs. */ #include "mysql/psi/psi.h" #ifndef PSI_SP_CALL #define PSI_SP_CALL(M) PSI_DYNAMIC_CALL(M) #endif #ifdef HAVE_PSI_SP_INTERFACE #define MYSQL_START_SP(STATE, SP_SHARE) \ inline_mysql_start_sp(STATE, SP_SHARE) #else #define MYSQL_START_SP(STATE, SP_SHARE) \ NULL #endif #ifdef HAVE_PSI_SP_INTERFACE #define MYSQL_END_SP(LOCKER) \ inline_mysql_end_sp(LOCKER) #else #define MYSQL_END_SP(LOCKER) \ do {} while (0) #endif #ifdef HAVE_PSI_SP_INTERFACE #define MYSQL_DROP_SP(OT, SN, SNL, ON, ONL) \ inline_mysql_drop_sp(OT, SN, SNL, ON, ONL) #else #define MYSQL_DROP_SP(OT, SN, SNL, ON, ONL) \ do {} while (0) #endif #ifdef HAVE_PSI_SP_INTERFACE #define MYSQL_GET_SP_SHARE(OT, SN, SNL, ON, ONL) \ inline_mysql_get_sp_share(OT, SN, SNL, ON, ONL) #else #define MYSQL_GET_SP_SHARE(OT, SN, SNL, ON, ONL) \ NULL #endif #ifdef HAVE_PSI_SP_INTERFACE static inline struct PSI_sp_locker* inline_mysql_start_sp(PSI_sp_locker_state *state, PSI_sp_share *sp_share) { return PSI_SP_CALL(start_sp)(state, sp_share); } static inline void inline_mysql_end_sp(PSI_sp_locker *locker) { if (likely(locker != NULL)) PSI_SP_CALL(end_sp)(locker); } static inline void inline_mysql_drop_sp(uint sp_type, const char* schema_name, uint shcema_name_length, const char* object_name, uint object_name_length) { PSI_SP_CALL(drop_sp)(sp_type, schema_name, shcema_name_length, object_name, object_name_length); } static inline PSI_sp_share* inline_mysql_get_sp_share(uint sp_type, const char* schema_name, uint shcema_name_length, const char* object_name, uint object_name_length) { return PSI_SP_CALL(get_sp_share)(sp_type, schema_name, shcema_name_length, object_name, object_name_length); } #endif #endif mysql/server/mysql/psi/mysql_file.h000064400000117763151027430560013516 0ustar00/* Copyright (c) 2008, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_FILE_H #define MYSQL_FILE_H /* For strlen() */ #include /* For MY_STAT */ #include /* For my_chsize */ #include /** @file mysql/psi/mysql_file.h Instrumentation helpers for mysys file io. This header file provides the necessary declarations to use the mysys file API with the performance schema instrumentation. In some compilers (SunStudio), 'static inline' functions, when declared but not used, are not optimized away (because they are unused) by default, so that including a static inline function from a header file does create unwanted dependencies, causing unresolved symbols at link time. Other compilers, like gcc, optimize these dependencies by default. Since the instrumented APIs declared here are wrapper on top of mysys file io APIs, including mysql/psi/mysql_file.h assumes that the dependency on my_sys already exists. */ #include "mysql/psi/psi.h" #ifndef PSI_FILE_CALL #define PSI_FILE_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup File_instrumentation File Instrumentation @ingroup Instrumentation_interface @{ */ /** @def mysql_file_register(P1, P2, P3) File registration. */ #define mysql_file_register(P1, P2, P3) \ inline_mysql_file_register(P1, P2, P3) /** @def mysql_file_fgets(P1, P2, F) Instrumented fgets. @c mysql_file_fgets is a replacement for @c fgets. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fgets(P1, P2, F) \ inline_mysql_file_fgets(__FILE__, __LINE__, P1, P2, F) #else #define mysql_file_fgets(P1, P2, F) \ inline_mysql_file_fgets(P1, P2, F) #endif /** @def mysql_file_fgetc(F) Instrumented fgetc. @c mysql_file_fgetc is a replacement for @c fgetc. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fgetc(F) inline_mysql_file_fgetc(__FILE__, __LINE__, F) #else #define mysql_file_fgetc(F) inline_mysql_file_fgetc(F) #endif /** @def mysql_file_fputs(P1, F) Instrumented fputs. @c mysql_file_fputs is a replacement for @c fputs. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fputs(P1, F) \ inline_mysql_file_fputs(__FILE__, __LINE__, P1, F) #else #define mysql_file_fputs(P1, F)\ inline_mysql_file_fputs(P1, F) #endif /** @def mysql_file_fputc(P1, F) Instrumented fputc. @c mysql_file_fputc is a replacement for @c fputc. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fputc(P1, F) \ inline_mysql_file_fputc(__FILE__, __LINE__, P1, F) #else #define mysql_file_fputc(P1, F) \ inline_mysql_file_fputc(P1, F) #endif /** @def mysql_file_fprintf Instrumented fprintf. @c mysql_file_fprintf is a replacement for @c fprintf. */ #define mysql_file_fprintf inline_mysql_file_fprintf /** @def mysql_file_vfprintf(F, P1, P2) Instrumented vfprintf. @c mysql_file_vfprintf is a replacement for @c vfprintf. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_vfprintf(F, P1, P2) \ inline_mysql_file_vfprintf(__FILE__, __LINE__, F, P1, P2) #else #define mysql_file_vfprintf(F, P1, P2) \ inline_mysql_file_vfprintf(F, P1, P2) #endif /** @def mysql_file_fflush(F, P1, P2) Instrumented fflush. @c mysql_file_fflush is a replacement for @c fflush. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fflush(F) \ inline_mysql_file_fflush(__FILE__, __LINE__, F) #else #define mysql_file_fflush(F) \ inline_mysql_file_fflush(F) #endif /** @def mysql_file_feof(F) Instrumented feof. @c mysql_file_feof is a replacement for @c feof. */ #define mysql_file_feof(F) inline_mysql_file_feof(F) /** @def mysql_file_fstat(FN, S, FL) Instrumented fstat. @c mysql_file_fstat is a replacement for @c my_fstat. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fstat(FN, S, FL) \ inline_mysql_file_fstat(__FILE__, __LINE__, FN, S, FL) #else #define mysql_file_fstat(FN, S, FL) \ inline_mysql_file_fstat(FN, S, FL) #endif /** @def mysql_file_stat(K, FN, S, FL) Instrumented stat. @c mysql_file_stat is a replacement for @c my_stat. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_stat(K, FN, S, FL) \ inline_mysql_file_stat(K, __FILE__, __LINE__, FN, S, FL) #else #define mysql_file_stat(K, FN, S, FL) \ inline_mysql_file_stat(FN, S, FL) #endif /** @def mysql_file_chsize(F, P1, P2, P3) Instrumented chsize. @c mysql_file_chsize is a replacement for @c my_chsize. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_chsize(F, P1, P2, P3) \ inline_mysql_file_chsize(__FILE__, __LINE__, F, P1, P2, P3) #else #define mysql_file_chsize(F, P1, P2, P3) \ inline_mysql_file_chsize(F, P1, P2, P3) #endif /** @def mysql_file_fopen(K, N, F1, F2) Instrumented fopen. @c mysql_file_fopen is a replacement for @c my_fopen. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fopen(K, N, F1, F2) \ inline_mysql_file_fopen(K, __FILE__, __LINE__, N, F1, F2) #else #define mysql_file_fopen(K, N, F1, F2) \ inline_mysql_file_fopen(N, F1, F2) #endif /** @def mysql_file_fclose(FD, FL) Instrumented fclose. @c mysql_file_fclose is a replacement for @c my_fclose. Without the instrumentation, this call will have the same behavior as the undocumented and possibly platform specific my_fclose(NULL, ...) behavior. With the instrumentation, mysql_fclose(NULL, ...) will safely return 0, which is an extension compared to my_fclose and is therefore compliant. mysql_fclose is on purpose *not* implementing @code assert(file != NULL) @endcode, since doing so could introduce regressions. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fclose(FD, FL) \ inline_mysql_file_fclose(__FILE__, __LINE__, FD, FL) #else #define mysql_file_fclose(FD, FL) \ inline_mysql_file_fclose(FD, FL) #endif /** @def mysql_file_fread(FD, P1, P2, P3) Instrumented fread. @c mysql_file_fread is a replacement for @c my_fread. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fread(FD, P1, P2, P3) \ inline_mysql_file_fread(__FILE__, __LINE__, FD, P1, P2, P3) #else #define mysql_file_fread(FD, P1, P2, P3) \ inline_mysql_file_fread(FD, P1, P2, P3) #endif /** @def mysql_file_fwrite(FD, P1, P2, P3) Instrumented fwrite. @c mysql_file_fwrite is a replacement for @c my_fwrite. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fwrite(FD, P1, P2, P3) \ inline_mysql_file_fwrite(__FILE__, __LINE__, FD, P1, P2, P3) #else #define mysql_file_fwrite(FD, P1, P2, P3) \ inline_mysql_file_fwrite(FD, P1, P2, P3) #endif /** @def mysql_file_fseek(FD, P, W, F) Instrumented fseek. @c mysql_file_fseek is a replacement for @c my_fseek. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_fseek(FD, P, W, F) \ inline_mysql_file_fseek(__FILE__, __LINE__, FD, P, W, F) #else #define mysql_file_fseek(FD, P, W, F) \ inline_mysql_file_fseek(FD, P, W, F) #endif /** @def mysql_file_ftell(FD, F) Instrumented ftell. @c mysql_file_ftell is a replacement for @c my_ftell. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_ftell(FD, F) \ inline_mysql_file_ftell(__FILE__, __LINE__, FD, F) #else #define mysql_file_ftell(FD, F) \ inline_mysql_file_ftell(FD, F) #endif /** @def mysql_file_create(K, N, F1, F2, F3) Instrumented create. @c mysql_file_create is a replacement for @c my_create. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_create(K, N, F1, F2, F3) \ inline_mysql_file_create(K, __FILE__, __LINE__, N, F1, F2, F3) #else #define mysql_file_create(K, N, F1, F2, F3) \ inline_mysql_file_create(N, F1, F2, F3) #endif /** @def mysql_file_create_temp(K, T, D, P, M, F) Instrumented create_temp_file. @c mysql_file_create_temp is a replacement for @c create_temp_file. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_create_temp(K, T, D, P, M, F) \ inline_mysql_file_create_temp(K, __FILE__, __LINE__, T, D, P, M, F) #else #define mysql_file_create_temp(K, T, D, P, M, F) \ inline_mysql_file_create_temp(T, D, P, M, F) #endif /** @def mysql_file_open(K, N, F1, F2) Instrumented open. @c mysql_file_open is a replacement for @c my_open. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_open(K, N, F1, F2) \ inline_mysql_file_open(K, __FILE__, __LINE__, N, F1, F2) #else #define mysql_file_open(K, N, F1, F2) \ inline_mysql_file_open(N, F1, F2) #endif /** @def mysql_file_close(FD, F) Instrumented close. @c mysql_file_close is a replacement for @c my_close. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_close(FD, F) \ inline_mysql_file_close(__FILE__, __LINE__, FD, F) #else #define mysql_file_close(FD, F) \ inline_mysql_file_close(FD, F) #endif /** @def mysql_file_read(FD, B, S, F) Instrumented read. @c mysql_read is a replacement for @c my_read. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_read(FD, B, S, F) \ inline_mysql_file_read(__FILE__, __LINE__, FD, B, S, F) #else #define mysql_file_read(FD, B, S, F) \ inline_mysql_file_read(FD, B, S, F) #endif /** @def mysql_file_write(FD, B, S, F) Instrumented write. @c mysql_file_write is a replacement for @c my_write. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_write(FD, B, S, F) \ inline_mysql_file_write(__FILE__, __LINE__, FD, B, S, F) #else #define mysql_file_write(FD, B, S, F) \ inline_mysql_file_write(FD, B, S, F) #endif /** @def mysql_file_pread(FD, B, S, O, F) Instrumented pread. @c mysql_pread is a replacement for @c my_pread. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_pread(FD, B, S, O, F) \ inline_mysql_file_pread(__FILE__, __LINE__, FD, B, S, O, F) #else #define mysql_file_pread(FD, B, S, O, F) \ inline_mysql_file_pread(FD, B, S, O, F) #endif /** @def mysql_file_pwrite(FD, B, S, O, F) Instrumented pwrite. @c mysql_file_pwrite is a replacement for @c my_pwrite. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_pwrite(FD, B, S, O, F) \ inline_mysql_file_pwrite(__FILE__, __LINE__, FD, B, S, O, F) #else #define mysql_file_pwrite(FD, B, S, O, F) \ inline_mysql_file_pwrite(FD, B, S, O, F) #endif /** @def mysql_file_seek(FD, P, W, F) Instrumented seek. @c mysql_file_seek is a replacement for @c my_seek. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_seek(FD, P, W, F) \ inline_mysql_file_seek(__FILE__, __LINE__, FD, P, W, F) #else #define mysql_file_seek(FD, P, W, F) \ inline_mysql_file_seek(FD, P, W, F) #endif /** @def mysql_file_tell(FD, F) Instrumented tell. @c mysql_file_tell is a replacement for @c my_tell. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_tell(FD, F) \ inline_mysql_file_tell(__FILE__, __LINE__, FD, F) #else #define mysql_file_tell(FD, F) \ inline_mysql_file_tell(FD, F) #endif /** @def mysql_file_delete(K, P1, P2) Instrumented delete. @c mysql_file_delete is a replacement for @c my_delete. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_delete(K, P1, P2) \ inline_mysql_file_delete(K, __FILE__, __LINE__, P1, P2) #else #define mysql_file_delete(K, P1, P2) \ inline_mysql_file_delete(P1, P2) #endif /** @def mysql_file_rename(K, P1, P2, P3) Instrumented rename. @c mysql_file_rename is a replacement for @c my_rename. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_rename(K, P1, P2, P3) \ inline_mysql_file_rename(K, __FILE__, __LINE__, P1, P2, P3) #else #define mysql_file_rename(K, P1, P2, P3) \ inline_mysql_file_rename(P1, P2, P3) #endif /** @def mysql_file_create_with_symlink(K, P1, P2, P3, P4, P5) Instrumented create with symbolic link. @c mysql_file_create_with_symlink is a replacement for @c my_create_with_symlink. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_create_with_symlink(K, P1, P2, P3, P4, P5) \ inline_mysql_file_create_with_symlink(K, __FILE__, __LINE__, \ P1, P2, P3, P4, P5) #else #define mysql_file_create_with_symlink(K, P1, P2, P3, P4, P5) \ inline_mysql_file_create_with_symlink(P1, P2, P3, P4, P5) #endif /** @def mysql_file_delete_with_symlink(K, P1, P2, P3) Instrumented delete with symbolic link. @c mysql_file_delete_with_symlink is a replacement for @c my_handler_delete_with_symlink. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_delete_with_symlink(K, P1, P2, P3) \ inline_mysql_file_delete_with_symlink(K, __FILE__, __LINE__, P1, P2, P3) #else #define mysql_file_delete_with_symlink(K, P1, P2, P3) \ inline_mysql_file_delete_with_symlink(P1, P2, P3) #endif /** @def mysql_file_rename_with_symlink(K, P1, P2, P3) Instrumented rename with symbolic link. @c mysql_file_rename_with_symlink is a replacement for @c my_rename_with_symlink. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_rename_with_symlink(K, P1, P2, P3) \ inline_mysql_file_rename_with_symlink(K, __FILE__, __LINE__, P1, P2, P3) #else #define mysql_file_rename_with_symlink(K, P1, P2, P3) \ inline_mysql_file_rename_with_symlink(P1, P2, P3) #endif /** @def mysql_file_sync(P1, P2) Instrumented file sync. @c mysql_file_sync is a replacement for @c my_sync. */ #ifdef HAVE_PSI_FILE_INTERFACE #define mysql_file_sync(P1, P2) \ inline_mysql_file_sync(__FILE__, __LINE__, P1, P2) #else #define mysql_file_sync(P1, P2) \ inline_mysql_file_sync(P1, P2) #endif /** An instrumented FILE structure. @sa MYSQL_FILE */ struct st_mysql_file { /** The real file. */ FILE *m_file; /** The instrumentation hook. Note that this hook is not conditionally defined, for binary compatibility of the @c MYSQL_FILE interface. */ struct PSI_file *m_psi; }; /** Type of an instrumented file. @c MYSQL_FILE is a drop-in replacement for @c FILE. @sa mysql_file_open */ typedef struct st_mysql_file MYSQL_FILE; static inline void inline_mysql_file_register( #ifdef HAVE_PSI_FILE_INTERFACE const char *category, PSI_file_info *info, int count #else const char *category __attribute__ ((unused)), void *info __attribute__ ((unused)), int count __attribute__ ((unused)) #endif ) { #ifdef HAVE_PSI_FILE_INTERFACE PSI_FILE_CALL(register_file)(category, info, count); #endif } static inline char * inline_mysql_file_fgets( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif char *str, int size, MYSQL_FILE *file) { char *result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_READ); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) size, src_file, src_line); result= fgets(str, size, file->m_file); PSI_FILE_CALL(end_file_wait)(locker, result ? strlen(result) : 0); return result; } } #endif result= fgets(str, size, file->m_file); return result; } static inline int inline_mysql_file_fgetc( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file) { int result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_READ); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 1, src_file, src_line); result= fgetc(file->m_file); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 1); return result; } } #endif result= fgetc(file->m_file); return result; } static inline int inline_mysql_file_fputs( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif const char *str, MYSQL_FILE *file) { int result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes; locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); if (likely(locker != NULL)) { bytes= str ? strlen(str) : 0; PSI_FILE_CALL(start_file_wait)(locker, bytes, src_file, src_line); result= fputs(str, file->m_file); PSI_FILE_CALL(end_file_wait)(locker, bytes); return result; } } #endif result= fputs(str, file->m_file); return result; } static inline int inline_mysql_file_fputc( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif char c, MYSQL_FILE *file) { int result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 1, src_file, src_line); result= fputc(c, file->m_file); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 1); return result; } } #endif result= fputc(c, file->m_file); return result; } static inline int inline_mysql_file_fprintf(MYSQL_FILE *file, const char *format, ...) { /* TODO: figure out how to pass src_file and src_line from the caller. */ int result; va_list args; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, __FILE__, __LINE__); va_start(args, format); result= vfprintf(file->m_file, format, args); va_end(args); PSI_FILE_CALL(end_file_wait)(locker, (size_t) result); return result; } } #endif va_start(args, format); result= vfprintf(file->m_file, format, args); va_end(args); return result; } static inline int inline_mysql_file_vfprintf( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file, const char *format, va_list args) { int result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker) (&state, file->m_psi, PSI_FILE_WRITE); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= vfprintf(file->m_file, format, args); PSI_FILE_CALL(end_file_wait)(locker, (size_t) result); return result; } } #endif result= vfprintf(file->m_file, format, args); return result; } static inline int inline_mysql_file_fflush( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file) { int result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_FLUSH); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= fflush(file->m_file); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } } #endif result= fflush(file->m_file); return result; } static inline int inline_mysql_file_feof(MYSQL_FILE *file) { /* Not instrumented, there is no wait involved */ return feof(file->m_file); } static inline int inline_mysql_file_fstat( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif int filenr, MY_STAT *stat_area, myf flags) { int result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, filenr, PSI_FILE_FSTAT); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_fstat(filenr, stat_area, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } #endif result= my_fstat(filenr, stat_area, flags); return result; } static inline MY_STAT * inline_mysql_file_stat( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *path, MY_STAT *stat_area, myf flags) { MY_STAT *result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_STAT, path, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); result= my_stat(path, stat_area, flags); PSI_FILE_CALL(end_file_open_wait)(locker, result); return result; } #endif result= my_stat(path, stat_area, flags); return result; } static inline int inline_mysql_file_chsize( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, my_off_t newlength, int filler, myf flags) { int result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_CHSIZE); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) newlength, src_file, src_line); result= my_chsize(file, newlength, filler, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) newlength); return result; } #endif result= my_chsize(file, newlength, filler, flags); return result; } static inline MYSQL_FILE* inline_mysql_file_fopen( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *filename, int flags, myf myFlags) { MYSQL_FILE *that; that= (MYSQL_FILE*) my_malloc(PSI_NOT_INSTRUMENTED, sizeof(MYSQL_FILE), MYF(MY_WME)); if (likely(that != NULL)) { #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_STREAM_OPEN, filename, that); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); that->m_file= my_fopen(filename, flags, myFlags); that->m_psi= PSI_FILE_CALL(end_file_open_wait)(locker, that->m_file); if (unlikely(that->m_file == NULL)) { my_free(that); return NULL; } return that; } #endif that->m_psi= NULL; that->m_file= my_fopen(filename, flags, myFlags); if (unlikely(that->m_file == NULL)) { my_free(that); return NULL; } } return that; } static inline int inline_mysql_file_fclose( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file, myf flags) { int result= 0; if (likely(file != NULL)) { #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_STREAM_CLOSE); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); result= my_fclose(file->m_file, flags); PSI_FILE_CALL(end_file_close_wait)(locker, result); my_free(file); return result; } } #endif result= my_fclose(file->m_file, flags); my_free(file); } return result; } static inline size_t inline_mysql_file_fread( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file, uchar *buffer, size_t count, myf flags) { size_t result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes_read; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_READ); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); result= my_fread(file->m_file, buffer, count, flags); if (flags & (MY_NABP | MY_FNABP)) bytes_read= (result == 0) ? count : 0; else bytes_read= (result != MY_FILE_ERROR) ? result : 0; PSI_FILE_CALL(end_file_wait)(locker, bytes_read); return result; } } #endif result= my_fread(file->m_file, buffer, count, flags); return result; } static inline size_t inline_mysql_file_fwrite( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file, const uchar *buffer, size_t count, myf flags) { size_t result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes_written; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_WRITE); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); result= my_fwrite(file->m_file, buffer, count, flags); if (flags & (MY_NABP | MY_FNABP)) bytes_written= (result == 0) ? count : 0; else bytes_written= (result != MY_FILE_ERROR) ? result : 0; PSI_FILE_CALL(end_file_wait)(locker, bytes_written); return result; } } #endif result= my_fwrite(file->m_file, buffer, count, flags); return result; } static inline my_off_t inline_mysql_file_fseek( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file, my_off_t pos, int whence, myf flags) { my_off_t result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_SEEK); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_fseek(file->m_file, pos, whence, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } } #endif result= my_fseek(file->m_file, pos, whence, flags); return result; } static inline my_off_t inline_mysql_file_ftell( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif MYSQL_FILE *file, myf flags) { my_off_t result; #ifdef HAVE_PSI_FILE_INTERFACE if (psi_likely(file->m_psi)) { struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_stream_locker)(&state, file->m_psi, PSI_FILE_TELL); if (likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_ftell(file->m_file, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } } #endif result= my_ftell(file->m_file, flags); return result; } static inline File inline_mysql_file_create( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *filename, mode_t create_flags, int access_flags, myf myFlags) { File file; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_CREATE, filename, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); file= my_create(filename, create_flags, access_flags, myFlags); PSI_FILE_CALL(end_file_open_wait_and_bind_to_descriptor)(locker, file); return file; } #endif file= my_create(filename, create_flags, access_flags, myFlags); return file; } static inline File inline_mysql_file_create_temp( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif char *to, const char *dir, const char *pfx, int mode, myf myFlags) { File file; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker) (&state, key, PSI_FILE_CREATE, NULL, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); /* The file name is generated by create_temp_file(). */ file= create_temp_file(to, dir, pfx, mode, myFlags); PSI_FILE_CALL(end_temp_file_open_wait_and_bind_to_descriptor)(locker, file, (const char*)to); return file; } #endif file= create_temp_file(to, dir, pfx, mode, myFlags); return file; } static inline File inline_mysql_file_open( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *filename, int flags, myf myFlags) { File file; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_OPEN, filename, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); file= my_open(filename, flags, myFlags); PSI_FILE_CALL(end_file_open_wait_and_bind_to_descriptor)(locker, file); return file; } #endif file= my_open(filename, flags, myFlags); return file; } static inline int inline_mysql_file_close( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, myf flags) { int result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_CLOSE); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); result= my_close(file, flags); PSI_FILE_CALL(end_file_close_wait)(locker, result); return result; } #endif result= my_close(file, flags); return result; } static inline size_t inline_mysql_file_read( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, uchar *buffer, size_t count, myf flags) { size_t result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes_read; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_READ); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); result= my_read(file, buffer, count, flags); if (flags & (MY_NABP | MY_FNABP)) bytes_read= (result == 0) ? count : 0; else bytes_read= (result != MY_FILE_ERROR) ? result : 0; PSI_FILE_CALL(end_file_wait)(locker, bytes_read); return result; } #endif result= my_read(file, buffer, count, flags); return result; } static inline size_t inline_mysql_file_write( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, const uchar *buffer, size_t count, myf flags) { size_t result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes_written; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_WRITE); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); result= my_write(file, buffer, count, flags); if (flags & (MY_NABP | MY_FNABP)) bytes_written= (result == 0) ? count : 0; else bytes_written= (result != MY_FILE_ERROR) ? result : 0; PSI_FILE_CALL(end_file_wait)(locker, bytes_written); return result; } #endif result= my_write(file, buffer, count, flags); return result; } static inline size_t inline_mysql_file_pread( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, uchar *buffer, size_t count, my_off_t offset, myf flags) { size_t result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes_read; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_READ); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); result= my_pread(file, buffer, count, offset, flags); if (flags & (MY_NABP | MY_FNABP)) bytes_read= (result == 0) ? count : 0; else bytes_read= (result != MY_FILE_ERROR) ? result : 0; PSI_FILE_CALL(end_file_wait)(locker, bytes_read); return result; } #endif result= my_pread(file, buffer, count, offset, flags); return result; } static inline size_t inline_mysql_file_pwrite( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, const uchar *buffer, size_t count, my_off_t offset, myf flags) { size_t result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; size_t bytes_written; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_WRITE); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, count, src_file, src_line); result= my_pwrite(file, buffer, count, offset, flags); if (flags & (MY_NABP | MY_FNABP)) bytes_written= (result == 0) ? count : 0; else bytes_written= (result != MY_FILE_ERROR) ? result : 0; PSI_FILE_CALL(end_file_wait)(locker, bytes_written); return result; } #endif result= my_pwrite(file, buffer, count, offset, flags); return result; } static inline my_off_t inline_mysql_file_seek( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, my_off_t pos, int whence, myf flags) { my_off_t result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_SEEK); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_seek(file, pos, whence, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } #endif result= my_seek(file, pos, whence, flags); return result; } static inline my_off_t inline_mysql_file_tell( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File file, myf flags) { my_off_t result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, file, PSI_FILE_TELL); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_tell(file, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } #endif result= my_tell(file, flags); return result; } static inline int inline_mysql_file_delete( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *name, myf flags) { int result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_DELETE, name, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); result= my_delete(name, flags); PSI_FILE_CALL(end_file_close_wait)(locker, result); return result; } #endif result= my_delete(name, flags); return result; } static inline int inline_mysql_file_rename( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *from, const char *to, myf flags) { int result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker) (&state, key, PSI_FILE_RENAME, from, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_rename(from, to, flags); PSI_FILE_CALL(end_file_rename_wait)(locker, from, to, result); return result; } #endif result= my_rename(from, to, flags); return result; } static inline File inline_mysql_file_create_with_symlink( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *linkname, const char *filename, mode_t create_flags, int access_flags, myf flags) { File file; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_CREATE, filename, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_open_wait)(locker, src_file, src_line); file= my_create_with_symlink(linkname, filename, create_flags, access_flags, flags); PSI_FILE_CALL(end_file_open_wait_and_bind_to_descriptor)(locker, file); return file; } #endif file= my_create_with_symlink(linkname, filename, create_flags, access_flags, flags); return file; } static inline int inline_mysql_file_delete_with_symlink( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *name, const char *ext, myf flags) { int result; char buf[FN_REFLEN]; char *fullname= fn_format(buf, name, "", ext, MY_UNPACK_FILENAME | MY_APPEND_EXT); #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker)(&state, key, PSI_FILE_DELETE, fullname, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_close_wait)(locker, src_file, src_line); result= my_handler_delete_with_symlink(fullname, flags); PSI_FILE_CALL(end_file_close_wait)(locker, result); return result; } #endif result= my_handler_delete_with_symlink(fullname, flags); return result; } static inline int inline_mysql_file_rename_with_symlink( #ifdef HAVE_PSI_FILE_INTERFACE PSI_file_key key, const char *src_file, uint src_line, #endif const char *from, const char *to, myf flags) { int result; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_name_locker) (&state, key, PSI_FILE_RENAME, from, &locker); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_rename_with_symlink(from, to, flags); PSI_FILE_CALL(end_file_rename_wait)(locker, from, to, result); return result; } #endif result= my_rename_with_symlink(from, to, flags); return result; } static inline int inline_mysql_file_sync( #ifdef HAVE_PSI_FILE_INTERFACE const char *src_file, uint src_line, #endif File fd, myf flags) { int result= 0; #ifdef HAVE_PSI_FILE_INTERFACE struct PSI_file_locker *locker; PSI_file_locker_state state; locker= PSI_FILE_CALL(get_thread_file_descriptor_locker)(&state, fd, PSI_FILE_SYNC); if (psi_likely(locker != NULL)) { PSI_FILE_CALL(start_file_wait)(locker, (size_t) 0, src_file, src_line); result= my_sync(fd, flags); PSI_FILE_CALL(end_file_wait)(locker, (size_t) 0); return result; } #endif result= my_sync(fd, flags); return result; } /** @} (end of group File_instrumentation) */ #endif mysql/server/mysql/psi/mysql_idle.h000064400000005743151027430560013506 0ustar00/* Copyright (c) 2011, 2023, Oracle and/or its affiliates Copyright (c) 2017, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_IDLE_H #define MYSQL_IDLE_H /** @file mysql/psi/mysql_idle.h Instrumentation helpers for idle waits. */ #include "mysql/psi/psi.h" #ifndef PSI_IDLE_CALL #define PSI_IDLE_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Idle_instrumentation Idle Instrumentation @ingroup Instrumentation_interface @{ */ /** @def MYSQL_START_IDLE_WAIT Instrumentation helper for table io_waits. This instrumentation marks the start of a wait event. @param LOCKER the locker @param STATE the locker state @sa MYSQL_END_IDLE_WAIT. */ #ifdef HAVE_PSI_IDLE_INTERFACE #define MYSQL_START_IDLE_WAIT(LOCKER, STATE) \ LOCKER= inline_mysql_start_idle_wait(STATE, __FILE__, __LINE__) #else #define MYSQL_START_IDLE_WAIT(LOCKER, STATE) \ do {} while (0) #endif /** @def MYSQL_END_IDLE_WAIT Instrumentation helper for idle waits. This instrumentation marks the end of a wait event. @param LOCKER the locker @sa MYSQL_START_IDLE_WAIT. */ #ifdef HAVE_PSI_IDLE_INTERFACE #define MYSQL_END_IDLE_WAIT(LOCKER) \ inline_mysql_end_idle_wait(LOCKER) #else #define MYSQL_END_IDLE_WAIT(LOCKER) \ do {} while (0) #endif #ifdef HAVE_PSI_IDLE_INTERFACE /** Instrumentation calls for MYSQL_START_IDLE_WAIT. @sa MYSQL_END_IDLE_WAIT. */ static inline struct PSI_idle_locker * inline_mysql_start_idle_wait(PSI_idle_locker_state *state, const char *src_file, uint src_line) { struct PSI_idle_locker *locker; locker= PSI_IDLE_CALL(start_idle_wait)(state, src_file, src_line); return locker; } /** Instrumentation calls for MYSQL_END_IDLE_WAIT. @sa MYSQL_START_IDLE_WAIT. */ static inline void inline_mysql_end_idle_wait(struct PSI_idle_locker *locker) { if (psi_likely(locker != NULL)) PSI_IDLE_CALL(end_idle_wait)(locker); } #endif /** @} (end of group Idle_instrumentation) */ #endif mysql/server/mysql/psi/psi_abi_v1.h000064400000002667151027430560013362 0ustar00/* Copyright (c) 2008, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file mysql/psi/psi_abi_v1.h ABI check for mysql/psi/psi.h, when using PSI_VERSION_1. This file is only used to automate detection of changes between versions. Do not include this file, include mysql/psi/psi.h instead. */ #define USE_PSI_1 #define HAVE_PSI_INTERFACE #define MY_GLOBAL_INCLUDED #include "mysql/psi/psi.h" mysql/server/mysql/psi/psi_memory.h000064400000010771151027430560013524 0ustar00/* Copyright (c) 2013, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. Without limiting anything contained in the foregoing, this file, which is part of C Driver for MySQL (Connector/C), is also subject to the Universal FOSS Exception, version 1.0, a copy of which can be found at http://oss.oracle.com/licenses/universal-foss-exception. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_PSI_MEMORY_H #define MYSQL_PSI_MEMORY_H #include "psi_base.h" #ifdef __cplusplus extern "C" { #endif /** @file mysql/psi/psi_memory.h Performance schema instrumentation interface. @defgroup Instrumentation_interface Instrumentation Interface @ingroup Performance_schema @{ */ #ifdef HAVE_PSI_INTERFACE #ifndef DISABLE_ALL_PSI #ifndef DISABLE_PSI_MEMORY #define HAVE_PSI_MEMORY_INTERFACE #endif /* DISABLE_PSI_MEMORY */ #endif /* DISABLE_ALL_PSI */ #endif /* HAVE_PSI_INTERFACE */ struct PSI_thread; #ifdef HAVE_PSI_1 /** @defgroup Group_PSI_v1 Application Binary Interface, version 1 @ingroup Instrumentation_interface @{ */ /** Memory instrument information. @since PSI_VERSION_1 This structure is used to register instrumented memory. */ struct PSI_memory_info_v1 { /** Pointer to the key assigned to the registered memory. */ PSI_memory_key *m_key; /** The name of the memory instrument to register. */ const char *m_name; /** The flags of the socket instrument to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_memory_info_v1 PSI_memory_info_v1; /** Memory registration API. @param category a category name (typically a plugin name) @param info an array of memory info to register @param count the size of the info array */ typedef void (*register_memory_v1_t) (const char *category, struct PSI_memory_info_v1 *info, int count); /** Instrument memory allocation. @param key the memory instrument key @param size the size of memory allocated @param[out] owner the memory owner @return the effective memory instrument key */ typedef PSI_memory_key (*memory_alloc_v1_t) (PSI_memory_key key, size_t size, struct PSI_thread ** owner); /** Instrument memory re allocation. @param key the memory instrument key @param old_size the size of memory previously allocated @param new_size the size of memory re allocated @param[in, out] owner the memory owner @return the effective memory instrument key */ typedef PSI_memory_key (*memory_realloc_v1_t) (PSI_memory_key key, size_t old_size, size_t new_size, struct PSI_thread ** owner); /** Instrument memory claim. @param key the memory instrument key @param size the size of memory allocated @param[in, out] owner the memory owner @return the effective memory instrument key */ typedef PSI_memory_key (*memory_claim_v1_t) (PSI_memory_key key, size_t size, struct PSI_thread ** owner); /** Instrument memory free. @param key the memory instrument key @param size the size of memory allocated @param owner the memory owner */ typedef void (*memory_free_v1_t) (PSI_memory_key key, size_t size, struct PSI_thread * owner); /** @} (end of group Group_PSI_v1) */ #ifdef _AIX PSI_memory_key key_memory_log_event; #endif #endif /* HAVE_PSI_1 */ #ifdef HAVE_PSI_2 struct PSI_memory_info_v2 { int placeholder; }; #endif /* HAVE_PSI_2 */ #ifdef USE_PSI_1 typedef struct PSI_memory_info_v1 PSI_memory_info; #endif #ifdef USE_PSI_2 typedef struct PSI_memory_info_v2 PSI_memory_info; #endif /** @} (end of group Instrumentation_interface) */ #ifdef __cplusplus } #endif #endif /* MYSQL_PSI_MEMORY_H */ mysql/server/mysql/psi/psi.h000064400000253735151027430560012145 0ustar00/* Copyright (c) 2008, 2023, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H #define MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H #ifndef MY_GLOBAL_INCLUDED /* Make sure a .c or .cc file contains an include to my_global.h first. When this include is missing, all the #ifdef HAVE_XXX have no effect, and the resulting binary won't build, or won't link, or will crash at runtime since various structures will have different binary definitions. */ #error "You must include my_global.h in the code for the build to be correct." #endif /* If PSI_ON_BY_DFAULT is defined, assume PSI will be enabled by default and optimize jumps testing for PSI this case. If not, optimize the binary for that PSI is not enabled */ #ifdef PSI_ON_BY_DEFAULT #define psi_likely(A) likely(A) #define psi_unlikely(A) unlikely(A) #else #define psi_likely(A) unlikely(A) #define psi_unlikely(A) likely(A) #endif #include "psi_base.h" #include "psi_memory.h" #ifdef _WIN32 typedef struct thread_attr pthread_attr_t; typedef DWORD pthread_t; typedef DWORD pthread_key_t; #endif /* MAINTAINER: The following pattern: typedef struct XYZ XYZ; is not needed in C++, but required for C. */ C_MODE_START /** @sa MDL_key. */ struct MDL_key; typedef struct MDL_key MDL_key; /** @sa enum_mdl_type. */ typedef int opaque_mdl_type; /** @sa enum_mdl_duration. */ typedef int opaque_mdl_duration; /** @sa MDL_wait::enum_wait_status. */ typedef int opaque_mdl_status; /** @sa enum_vio_type. */ typedef int opaque_vio_type; struct TABLE_SHARE; struct sql_digest_storage; #ifdef __cplusplus class THD; #else /* Phony declaration when compiling C code. This is ok, because the C code will never have a THD anyway. */ struct opaque_THD { int dummy; }; typedef struct opaque_THD THD; #endif /** @file mysql/psi/psi.h Performance schema instrumentation interface. @defgroup Instrumentation_interface Instrumentation Interface @ingroup Performance_schema @{ */ /** Interface for an instrumented mutex. This is an opaque structure. */ struct PSI_mutex; typedef struct PSI_mutex PSI_mutex; /** Interface for an instrumented rwlock. This is an opaque structure. */ struct PSI_rwlock; typedef struct PSI_rwlock PSI_rwlock; /** Interface for an instrumented condition. This is an opaque structure. */ struct PSI_cond; typedef struct PSI_cond PSI_cond; /** Interface for an instrumented table share. This is an opaque structure. */ struct PSI_table_share; typedef struct PSI_table_share PSI_table_share; /** Interface for an instrumented table handle. This is an opaque structure. */ struct PSI_table; typedef struct PSI_table PSI_table; /** Interface for an instrumented thread. This is an opaque structure. */ struct PSI_thread; typedef struct PSI_thread PSI_thread; /** Interface for an instrumented file handle. This is an opaque structure. */ struct PSI_file; typedef struct PSI_file PSI_file; /** Interface for an instrumented socket descriptor. This is an opaque structure. */ struct PSI_socket; typedef struct PSI_socket PSI_socket; /** Interface for an instrumented prepared statement. This is an opaque structure. */ struct PSI_prepared_stmt; typedef struct PSI_prepared_stmt PSI_prepared_stmt; /** Interface for an instrumented table operation. This is an opaque structure. */ struct PSI_table_locker; typedef struct PSI_table_locker PSI_table_locker; /** Interface for an instrumented statement. This is an opaque structure. */ struct PSI_statement_locker; typedef struct PSI_statement_locker PSI_statement_locker; /** Interface for an instrumented transaction. This is an opaque structure. */ struct PSI_transaction_locker; typedef struct PSI_transaction_locker PSI_transaction_locker; /** Interface for an instrumented idle operation. This is an opaque structure. */ struct PSI_idle_locker; typedef struct PSI_idle_locker PSI_idle_locker; /** Interface for an instrumented statement digest operation. This is an opaque structure. */ struct PSI_digest_locker; typedef struct PSI_digest_locker PSI_digest_locker; /** Interface for an instrumented stored procedure share. This is an opaque structure. */ struct PSI_sp_share; typedef struct PSI_sp_share PSI_sp_share; /** Interface for an instrumented stored program. This is an opaque structure. */ struct PSI_sp_locker; typedef struct PSI_sp_locker PSI_sp_locker; /** Interface for an instrumented metadata lock. This is an opaque structure. */ struct PSI_metadata_lock; typedef struct PSI_metadata_lock PSI_metadata_lock; /** Interface for an instrumented stage progress. This is a public structure, for efficiency. */ struct PSI_stage_progress { ulonglong m_work_completed; ulonglong m_work_estimated; }; typedef struct PSI_stage_progress PSI_stage_progress; /** IO operation performed on an instrumented table. */ enum PSI_table_io_operation { /** Row fetch. */ PSI_TABLE_FETCH_ROW= 0, /** Row write. */ PSI_TABLE_WRITE_ROW= 1, /** Row update. */ PSI_TABLE_UPDATE_ROW= 2, /** Row delete. */ PSI_TABLE_DELETE_ROW= 3 }; typedef enum PSI_table_io_operation PSI_table_io_operation; /** State data storage for @c start_table_io_wait_v1_t, @c start_table_lock_wait_v1_t. This structure provide temporary storage to a table locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_table_io_wait_v1_t @sa start_table_lock_wait_v1_t */ struct PSI_table_locker_state { /** Internal state. */ uint m_flags; /** Current io operation. */ enum PSI_table_io_operation m_io_operation; /** Current table handle. */ struct PSI_table *m_table; /** Current table share. */ struct PSI_table_share *m_table_share; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; /** Implementation specific. For table io, the table io index. For table lock, the lock type. */ uint m_index; }; typedef struct PSI_table_locker_state PSI_table_locker_state; /** Entry point for the performance schema interface. */ struct PSI_bootstrap { /** ABI interface finder. Calling this method with an interface version number returns either an instance of the ABI for this version, or NULL. @param version the interface version number to find @return a versioned interface (PSI_v1, PSI_v2 or PSI) @sa PSI_VERSION_1 @sa PSI_v1 @sa PSI_VERSION_2 @sa PSI_v2 @sa PSI_CURRENT_VERSION @sa PSI */ void* (*get_interface)(int version); }; typedef struct PSI_bootstrap PSI_bootstrap; #ifdef HAVE_PSI_INTERFACE #ifdef DISABLE_ALL_PSI #ifndef DISABLE_PSI_THREAD #define DISABLE_PSI_THREAD #endif #ifndef DISABLE_PSI_MUTEX #define DISABLE_PSI_MUTEX #endif #ifndef DISABLE_PSI_RWLOCK #define DISABLE_PSI_RWLOCK #endif #ifndef DISABLE_PSI_COND #define DISABLE_PSI_COND #endif #ifndef DISABLE_PSI_FILE #define DISABLE_PSI_FILE #endif #ifndef DISABLE_PSI_TABLE #define DISABLE_PSI_TABLE #endif #ifndef DISABLE_PSI_SOCKET #define DISABLE_PSI_SOCKET #endif #ifndef DISABLE_PSI_STAGE #define DISABLE_PSI_STAGE #endif #ifndef DISABLE_PSI_STATEMENT #define DISABLE_PSI_STATEMENT #endif #ifndef DISABLE_PSI_SP #define DISABLE_PSI_SP #endif #ifndef DISABLE_PSI_IDLE #define DISABLE_PSI_IDLE #endif #ifndef DISABLE_PSI_STATEMENT_DIGEST #define DISABLE_PSI_STATEMENT_DIGEST #endif #ifndef DISABLE_PSI_METADATA #define DISABLE_PSI_METADATA #endif #ifndef DISABLE_PSI_MEMORY #define DISABLE_PSI_MEMORY #endif #ifndef DISABLE_PSI_TRANSACTION #define DISABLE_PSI_TRANSACTION #endif #ifndef DISABLE_PSI_SP #define DISABLE_PSI_SP #endif #ifndef DISABLE_PSI_PS #define DISABLE_PSI_PS #endif #endif /** @def DISABLE_PSI_MUTEX Compiling option to disable the mutex instrumentation. This option is mostly intended to be used during development, when doing special builds with only a subset of the performance schema instrumentation, for code analysis / profiling / performance tuning of a specific instrumentation alone. @sa DISABLE_PSI_RWLOCK @sa DISABLE_PSI_COND @sa DISABLE_PSI_FILE @sa DISABLE_PSI_THREAD @sa DISABLE_PSI_TABLE @sa DISABLE_PSI_STAGE @sa DISABLE_PSI_STATEMENT @sa DISABLE_PSI_SP @sa DISABLE_PSI_STATEMENT_DIGEST @sa DISABLE_PSI_SOCKET @sa DISABLE_PSI_MEMORY @sa DISABLE_PSI_IDLE @sa DISABLE_PSI_METADATA @sa DISABLE PSI_TRANSACTION */ #ifndef DISABLE_PSI_MUTEX #define HAVE_PSI_MUTEX_INTERFACE #endif /** @def DISABLE_PSI_RWLOCK Compiling option to disable the rwlock instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_RWLOCK #define HAVE_PSI_RWLOCK_INTERFACE #endif /** @def DISABLE_PSI_COND Compiling option to disable the cond instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_COND #define HAVE_PSI_COND_INTERFACE #endif /** @def DISABLE_PSI_FILE Compiling option to disable the file instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_FILE #define HAVE_PSI_FILE_INTERFACE #endif /** @def DISABLE_PSI_THREAD Compiling option to disable the thread instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_THREAD #define HAVE_PSI_THREAD_INTERFACE #endif /** @def DISABLE_PSI_TABLE Compiling option to disable the table instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_TABLE #define HAVE_PSI_TABLE_INTERFACE #endif /** @def DISABLE_PSI_STAGE Compiling option to disable the stage instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_STAGE #define HAVE_PSI_STAGE_INTERFACE #endif /** @def DISABLE_PSI_STATEMENT Compiling option to disable the statement instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_STATEMENT #define HAVE_PSI_STATEMENT_INTERFACE #endif /** @def DISABLE_PSI_SP Compiling option to disable the stored program instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_SP #define HAVE_PSI_SP_INTERFACE #endif /** @def DISABLE_PSI_PS Compiling option to disable the prepared statement instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_STATEMENT #ifndef DISABLE_PSI_PS #define HAVE_PSI_PS_INTERFACE #endif #endif /** @def DISABLE_PSI_STATEMENT_DIGEST Compiling option to disable the statement digest instrumentation. */ #ifndef DISABLE_PSI_STATEMENT #ifndef DISABLE_PSI_STATEMENT_DIGEST #define HAVE_PSI_STATEMENT_DIGEST_INTERFACE #endif #endif /** @def DISABLE_PSI_TRANSACTION Compiling option to disable the transaction instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_TRANSACTION #define HAVE_PSI_TRANSACTION_INTERFACE #endif /** @def DISABLE_PSI_SOCKET Compiling option to disable the statement instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_SOCKET #define HAVE_PSI_SOCKET_INTERFACE #endif /** @def DISABLE_PSI_MEMORY Compiling option to disable the memory instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_MEMORY #define HAVE_PSI_MEMORY_INTERFACE #endif /** @def DISABLE_PSI_IDLE Compiling option to disable the idle instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_IDLE #define HAVE_PSI_IDLE_INTERFACE #endif /** @def DISABLE_PSI_METADATA Compiling option to disable the metadata instrumentation. @sa DISABLE_PSI_MUTEX */ #ifndef DISABLE_PSI_METADATA #define HAVE_PSI_METADATA_INTERFACE #endif /** @def PSI_VERSION_1 Performance Schema Interface number for version 1. This version is supported. */ #define PSI_VERSION_1 1 /** @def PSI_VERSION_2 Performance Schema Interface number for version 2. This version is not implemented, it's a placeholder. */ #define PSI_VERSION_2 2 /** @def PSI_CURRENT_VERSION Performance Schema Interface number for the most recent version. The most current version is @c PSI_VERSION_1 */ #define PSI_CURRENT_VERSION 1 #ifndef USE_PSI_2 #ifndef USE_PSI_1 #define USE_PSI_1 #endif #endif /** Interface for an instrumented mutex operation. This is an opaque structure. */ struct PSI_mutex_locker; typedef struct PSI_mutex_locker PSI_mutex_locker; /** Interface for an instrumented rwlock operation. This is an opaque structure. */ struct PSI_rwlock_locker; typedef struct PSI_rwlock_locker PSI_rwlock_locker; /** Interface for an instrumented condition operation. This is an opaque structure. */ struct PSI_cond_locker; typedef struct PSI_cond_locker PSI_cond_locker; /** Interface for an instrumented file operation. This is an opaque structure. */ struct PSI_file_locker; typedef struct PSI_file_locker PSI_file_locker; /** Interface for an instrumented socket operation. This is an opaque structure. */ struct PSI_socket_locker; typedef struct PSI_socket_locker PSI_socket_locker; /** Interface for an instrumented MDL operation. This is an opaque structure. */ struct PSI_metadata_locker; typedef struct PSI_metadata_locker PSI_metadata_locker; /** Operation performed on an instrumented mutex. */ enum PSI_mutex_operation { /** Lock. */ PSI_MUTEX_LOCK= 0, /** Lock attempt. */ PSI_MUTEX_TRYLOCK= 1 }; typedef enum PSI_mutex_operation PSI_mutex_operation; /** Operation performed on an instrumented rwlock. For basic READ / WRITE lock, operations are "READ" or "WRITE". For SX-locks, operations are "SHARED", "SHARED-EXCLUSIVE" or "EXCLUSIVE". */ enum PSI_rwlock_operation { /** Read lock. */ PSI_RWLOCK_READLOCK= 0, /** Write lock. */ PSI_RWLOCK_WRITELOCK= 1, /** Read lock attempt. */ PSI_RWLOCK_TRYREADLOCK= 2, /** Write lock attempt. */ PSI_RWLOCK_TRYWRITELOCK= 3, /** Shared lock. */ PSI_RWLOCK_SHAREDLOCK= 4, /** Shared Exclusive lock. */ PSI_RWLOCK_SHAREDEXCLUSIVELOCK= 5, /** Exclusive lock. */ PSI_RWLOCK_EXCLUSIVELOCK= 6, /** Shared lock attempt. */ PSI_RWLOCK_TRYSHAREDLOCK= 7, /** Shared Exclusive lock attempt. */ PSI_RWLOCK_TRYSHAREDEXCLUSIVELOCK= 8, /** Exclusive lock attempt. */ PSI_RWLOCK_TRYEXCLUSIVELOCK= 9 }; typedef enum PSI_rwlock_operation PSI_rwlock_operation; /** Operation performed on an instrumented condition. */ enum PSI_cond_operation { /** Wait. */ PSI_COND_WAIT= 0, /** Wait, with timeout. */ PSI_COND_TIMEDWAIT= 1 }; typedef enum PSI_cond_operation PSI_cond_operation; /** Operation performed on an instrumented file. */ enum PSI_file_operation { /** File creation, as in @c create(). */ PSI_FILE_CREATE= 0, /** Temporary file creation, as in @c create_temp_file(). */ PSI_FILE_CREATE_TMP= 1, /** File open, as in @c open(). */ PSI_FILE_OPEN= 2, /** File open, as in @c fopen(). */ PSI_FILE_STREAM_OPEN= 3, /** File close, as in @c close(). */ PSI_FILE_CLOSE= 4, /** File close, as in @c fclose(). */ PSI_FILE_STREAM_CLOSE= 5, /** Generic file read, such as @c fgets(), @c fgetc(), @c fread(), @c read(), @c pread(). */ PSI_FILE_READ= 6, /** Generic file write, such as @c fputs(), @c fputc(), @c fprintf(), @c vfprintf(), @c fwrite(), @c write(), @c pwrite(). */ PSI_FILE_WRITE= 7, /** Generic file seek, such as @c fseek() or @c seek(). */ PSI_FILE_SEEK= 8, /** Generic file tell, such as @c ftell() or @c tell(). */ PSI_FILE_TELL= 9, /** File flush, as in @c fflush(). */ PSI_FILE_FLUSH= 10, /** File stat, as in @c stat(). */ PSI_FILE_STAT= 11, /** File stat, as in @c fstat(). */ PSI_FILE_FSTAT= 12, /** File chsize, as in @c my_chsize(). */ PSI_FILE_CHSIZE= 13, /** File delete, such as @c my_delete() or @c my_handler_delete_with_symlink(). */ PSI_FILE_DELETE= 14, /** File rename, such as @c my_rename() or @c my_rename_with_symlink(). */ PSI_FILE_RENAME= 15, /** File sync, as in @c fsync() or @c my_sync(). */ PSI_FILE_SYNC= 16 }; typedef enum PSI_file_operation PSI_file_operation; /** Lock operation performed on an instrumented table. */ enum PSI_table_lock_operation { /** Table lock, in the server layer. */ PSI_TABLE_LOCK= 0, /** Table lock, in the storage engine layer. */ PSI_TABLE_EXTERNAL_LOCK= 1 }; typedef enum PSI_table_lock_operation PSI_table_lock_operation; /** State of an instrumented socket. */ enum PSI_socket_state { /** Idle, waiting for the next command. */ PSI_SOCKET_STATE_IDLE= 1, /** Active, executing a command. */ PSI_SOCKET_STATE_ACTIVE= 2 }; typedef enum PSI_socket_state PSI_socket_state; /** Operation performed on an instrumented socket. */ enum PSI_socket_operation { /** Socket creation, as in @c socket() or @c socketpair(). */ PSI_SOCKET_CREATE= 0, /** Socket connection, as in @c connect(), @c listen() and @c accept(). */ PSI_SOCKET_CONNECT= 1, /** Socket bind, as in @c bind(), @c getsockname() and @c getpeername(). */ PSI_SOCKET_BIND= 2, /** Socket close, as in @c shutdown(). */ PSI_SOCKET_CLOSE= 3, /** Socket send, @c send(). */ PSI_SOCKET_SEND= 4, /** Socket receive, @c recv(). */ PSI_SOCKET_RECV= 5, /** Socket send, @c sendto(). */ PSI_SOCKET_SENDTO= 6, /** Socket receive, @c recvfrom). */ PSI_SOCKET_RECVFROM= 7, /** Socket send, @c sendmsg(). */ PSI_SOCKET_SENDMSG= 8, /** Socket receive, @c recvmsg(). */ PSI_SOCKET_RECVMSG= 9, /** Socket seek, such as @c fseek() or @c seek(). */ PSI_SOCKET_SEEK= 10, /** Socket options, as in @c getsockopt() and @c setsockopt(). */ PSI_SOCKET_OPT= 11, /** Socket status, as in @c sockatmark() and @c isfdtype(). */ PSI_SOCKET_STAT= 12, /** Socket shutdown, as in @c shutdown(). */ PSI_SOCKET_SHUTDOWN= 13, /** Socket select, as in @c select() and @c poll(). */ PSI_SOCKET_SELECT= 14 }; typedef enum PSI_socket_operation PSI_socket_operation; #endif /** Instrumented mutex key. To instrument a mutex, a mutex key must be obtained using @c register_mutex. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_mutex_key; /** Instrumented rwlock key. To instrument a rwlock, a rwlock key must be obtained using @c register_rwlock. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_rwlock_key; /** Instrumented cond key. To instrument a condition, a condition key must be obtained using @c register_cond. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_cond_key; /** Instrumented thread key. To instrument a thread, a thread key must be obtained using @c register_thread. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_thread_key; /** Instrumented file key. To instrument a file, a file key must be obtained using @c register_file. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_file_key; /** Instrumented stage key. To instrument a stage, a stage key must be obtained using @c register_stage. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_stage_key; /** Instrumented statement key. To instrument a statement, a statement key must be obtained using @c register_statement. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_statement_key; /** Instrumented socket key. To instrument a socket, a socket key must be obtained using @c register_socket. Using a zero key always disable the instrumentation. */ typedef unsigned int PSI_socket_key; #ifdef HAVE_PSI_1 /** @defgroup Group_PSI_v1 Application Binary Interface, version 1 @ingroup Instrumentation_interface @{ */ /** Mutex information. @since PSI_VERSION_1 This structure is used to register an instrumented mutex. */ struct PSI_mutex_info_v1 { /** Pointer to the key assigned to the registered mutex. */ PSI_mutex_key *m_key; /** The name of the mutex to register. */ const char *m_name; /** The flags of the mutex to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_mutex_info_v1 PSI_mutex_info_v1; /** Rwlock information. @since PSI_VERSION_1 This structure is used to register an instrumented rwlock. */ struct PSI_rwlock_info_v1 { /** Pointer to the key assigned to the registered rwlock. */ PSI_rwlock_key *m_key; /** The name of the rwlock to register. */ const char *m_name; /** The flags of the rwlock to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_rwlock_info_v1 PSI_rwlock_info_v1; /** Condition information. @since PSI_VERSION_1 This structure is used to register an instrumented cond. */ struct PSI_cond_info_v1 { /** Pointer to the key assigned to the registered cond. */ PSI_cond_key *m_key; /** The name of the cond to register. */ const char *m_name; /** The flags of the cond to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_cond_info_v1 PSI_cond_info_v1; /** Thread instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented thread. */ struct PSI_thread_info_v1 { /** Pointer to the key assigned to the registered thread. */ PSI_thread_key *m_key; /** The name of the thread instrument to register. */ const char *m_name; /** The flags of the thread to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_thread_info_v1 PSI_thread_info_v1; /** File instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented file. */ struct PSI_file_info_v1 { /** Pointer to the key assigned to the registered file. */ PSI_file_key *m_key; /** The name of the file instrument to register. */ const char *m_name; /** The flags of the file instrument to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_file_info_v1 PSI_file_info_v1; /** Stage instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented stage. */ struct PSI_stage_info_v1 { /** The registered stage key. */ PSI_stage_key m_key; /** The name of the stage instrument to register. */ const char *m_name; /** The flags of the stage instrument to register. */ int m_flags; }; typedef struct PSI_stage_info_v1 PSI_stage_info_v1; /** Statement instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented statement. */ struct PSI_statement_info_v1 { /** The registered statement key. */ PSI_statement_key m_key; /** The name of the statement instrument to register. */ const char *m_name; /** The flags of the statement instrument to register. */ int m_flags; }; typedef struct PSI_statement_info_v1 PSI_statement_info_v1; /** Socket instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented socket. */ struct PSI_socket_info_v1 { /** Pointer to the key assigned to the registered socket. */ PSI_socket_key *m_key; /** The name of the socket instrument to register. */ const char *m_name; /** The flags of the socket instrument to register. @sa PSI_FLAG_GLOBAL */ int m_flags; }; typedef struct PSI_socket_info_v1 PSI_socket_info_v1; /** State data storage for @c start_idle_wait_v1_t. This structure provide temporary storage to an idle locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_idle_wait_v1_t. */ struct PSI_idle_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_idle_locker_state_v1 PSI_idle_locker_state_v1; /** State data storage for @c start_mutex_wait_v1_t. This structure provide temporary storage to a mutex locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_mutex_wait_v1_t */ struct PSI_mutex_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_mutex_operation m_operation; /** Current mutex. */ struct PSI_mutex *m_mutex; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_mutex_locker_state_v1 PSI_mutex_locker_state_v1; /** State data storage for @c start_rwlock_rdwait_v1_t, @c start_rwlock_wrwait_v1_t. This structure provide temporary storage to a rwlock locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_rwlock_rdwait_v1_t @sa start_rwlock_wrwait_v1_t */ struct PSI_rwlock_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_rwlock_operation m_operation; /** Current rwlock. */ struct PSI_rwlock *m_rwlock; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_rwlock_locker_state_v1 PSI_rwlock_locker_state_v1; /** State data storage for @c start_cond_wait_v1_t. This structure provide temporary storage to a condition locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_cond_wait_v1_t */ struct PSI_cond_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_cond_operation m_operation; /** Current condition. */ struct PSI_cond *m_cond; /** Current mutex. */ struct PSI_mutex *m_mutex; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_cond_locker_state_v1 PSI_cond_locker_state_v1; /** State data storage for @c get_thread_file_name_locker_v1_t. This structure provide temporary storage to a file locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa get_thread_file_name_locker_v1_t @sa get_thread_file_stream_locker_v1_t @sa get_thread_file_descriptor_locker_v1_t */ struct PSI_file_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current operation. */ enum PSI_file_operation m_operation; /** Current file. */ struct PSI_file *m_file; /** Current file name. */ const char *m_name; /** Current file class. */ void *m_class; /** Current thread. */ struct PSI_thread *m_thread; /** Operation number of bytes. */ size_t m_number_of_bytes; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_file_locker_state_v1 PSI_file_locker_state_v1; /** State data storage for @c start_metadata_wait_v1_t. This structure provide temporary storage to a metadata locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_metadata_wait_v1_t */ struct PSI_metadata_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current metadata lock. */ struct PSI_metadata_lock *m_metadata_lock; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_wait; }; typedef struct PSI_metadata_locker_state_v1 PSI_metadata_locker_state_v1; /* Duplicate of NAME_LEN, to avoid dependency on mysql_com.h */ #define PSI_SCHEMA_NAME_LEN (64 * 3) /** State data storage for @c get_thread_statement_locker_v1_t, @c get_thread_statement_locker_v1_t. This structure provide temporary storage to a statement locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa get_thread_statement_locker_v1_t */ struct PSI_statement_locker_state_v1 { /** Discarded flag. */ my_bool m_discarded; /** In prepare flag. */ my_bool m_in_prepare; /** Metric, no index used flag. */ uchar m_no_index_used; /** Metric, no good index used flag. */ uchar m_no_good_index_used; /** Internal state. */ uint m_flags; /** Instrumentation class. */ void *m_class; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_statement; /** Locked time. */ ulonglong m_lock_time; /** Rows sent. */ ulonglong m_rows_sent; /** Rows examined. */ ulonglong m_rows_examined; /** Metric, temporary tables created on disk. */ ulong m_created_tmp_disk_tables; /** Metric, temporary tables created. */ ulong m_created_tmp_tables; /** Metric, number of select full join. */ ulong m_select_full_join; /** Metric, number of select full range join. */ ulong m_select_full_range_join; /** Metric, number of select range. */ ulong m_select_range; /** Metric, number of select range check. */ ulong m_select_range_check; /** Metric, number of select scan. */ ulong m_select_scan; /** Metric, number of sort merge passes. */ ulong m_sort_merge_passes; /** Metric, number of sort merge. */ ulong m_sort_range; /** Metric, number of sort rows. */ ulong m_sort_rows; /** Metric, number of sort scans. */ ulong m_sort_scan; /** Statement digest. */ const struct sql_digest_storage *m_digest; /** Current schema name. */ char m_schema_name[PSI_SCHEMA_NAME_LEN]; /** Length in bytes of @c m_schema_name. */ uint m_schema_name_length; /** Statement character set number. */ uint m_cs_number; PSI_sp_share *m_parent_sp_share; PSI_prepared_stmt *m_parent_prepared_stmt; }; typedef struct PSI_statement_locker_state_v1 PSI_statement_locker_state_v1; /** State data storage for @c get_thread_transaction_locker_v1_t, @c get_thread_transaction_locker_v1_t. This structure provide temporary storage to a transaction locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa get_thread_transaction_locker_v1_t */ struct PSI_transaction_locker_state_v1 { /** Internal state. */ uint m_flags; /** Instrumentation class. */ void *m_class; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Internal data. */ void *m_transaction; /** True if read-only transaction, false if read-write. */ my_bool m_read_only; /** True if transaction is autocommit. */ my_bool m_autocommit; /** Number of statements. */ ulong m_statement_count; /** Total number of savepoints. */ ulong m_savepoint_count; /** Number of rollback_to_savepoint. */ ulong m_rollback_to_savepoint_count; /** Number of release_savepoint. */ ulong m_release_savepoint_count; }; typedef struct PSI_transaction_locker_state_v1 PSI_transaction_locker_state_v1; /** State data storage for @c start_socket_wait_v1_t. This structure provide temporary storage to a socket locker. The content of this structure is considered opaque, the fields are only hints of what an implementation of the psi interface can use. This memory is provided by the instrumented code for performance reasons. @sa start_socket_wait_v1_t */ struct PSI_socket_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current socket. */ struct PSI_socket *m_socket; /** Current thread. */ struct PSI_thread *m_thread; /** Operation number of bytes. */ size_t m_number_of_bytes; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Current operation. */ enum PSI_socket_operation m_operation; /** Source file. */ const char* m_src_file; /** Source line number. */ int m_src_line; /** Internal data. */ void *m_wait; }; typedef struct PSI_socket_locker_state_v1 PSI_socket_locker_state_v1; struct PSI_sp_locker_state_v1 { /** Internal state. */ uint m_flags; /** Current thread. */ struct PSI_thread *m_thread; /** Timer start. */ ulonglong m_timer_start; /** Timer function. */ ulonglong (*m_timer)(void); /** Stored Procedure share. */ PSI_sp_share* m_sp_share; }; typedef struct PSI_sp_locker_state_v1 PSI_sp_locker_state_v1; /* Using typedef to make reuse between PSI_v1 and PSI_v2 easier later. */ /** Mutex registration API. @param category a category name (typically a plugin name) @param info an array of mutex info to register @param count the size of the info array */ typedef void (*register_mutex_v1_t) (const char *category, struct PSI_mutex_info_v1 *info, int count); /** Rwlock registration API. @param category a category name (typically a plugin name) @param info an array of rwlock info to register @param count the size of the info array */ typedef void (*register_rwlock_v1_t) (const char *category, struct PSI_rwlock_info_v1 *info, int count); /** Cond registration API. @param category a category name (typically a plugin name) @param info an array of cond info to register @param count the size of the info array */ typedef void (*register_cond_v1_t) (const char *category, struct PSI_cond_info_v1 *info, int count); /** Thread registration API. @param category a category name (typically a plugin name) @param info an array of thread info to register @param count the size of the info array */ typedef void (*register_thread_v1_t) (const char *category, struct PSI_thread_info_v1 *info, int count); /** File registration API. @param category a category name (typically a plugin name) @param info an array of file info to register @param count the size of the info array */ typedef void (*register_file_v1_t) (const char *category, struct PSI_file_info_v1 *info, int count); /** Stage registration API. @param category a category name @param info an array of stage info to register @param count the size of the info array */ typedef void (*register_stage_v1_t) (const char *category, struct PSI_stage_info_v1 **info, int count); /** Statement registration API. @param category a category name @param info an array of stage info to register @param count the size of the info array */ typedef void (*register_statement_v1_t) (const char *category, struct PSI_statement_info_v1 *info, int count); /** Socket registration API. @param category a category name (typically a plugin name) @param info an array of socket info to register @param count the size of the info array */ typedef void (*register_socket_v1_t) (const char *category, struct PSI_socket_info_v1 *info, int count); /** Mutex instrumentation initialisation API. @param key the registered mutex key @param identity the address of the mutex itself @return an instrumented mutex */ typedef struct PSI_mutex* (*init_mutex_v1_t) (PSI_mutex_key key, void *identity); /** Mutex instrumentation destruction API. @param mutex the mutex to destroy */ typedef void (*destroy_mutex_v1_t)(struct PSI_mutex *mutex); /** Rwlock instrumentation initialisation API. @param key the registered rwlock key @param identity the address of the rwlock itself @return an instrumented rwlock */ typedef struct PSI_rwlock* (*init_rwlock_v1_t) (PSI_rwlock_key key, void *identity); /** Rwlock instrumentation destruction API. @param rwlock the rwlock to destroy */ typedef void (*destroy_rwlock_v1_t)(struct PSI_rwlock *rwlock); /** Cond instrumentation initialisation API. @param key the registered key @param identity the address of the rwlock itself @return an instrumented cond */ typedef struct PSI_cond* (*init_cond_v1_t) (PSI_cond_key key, void *identity); /** Cond instrumentation destruction API. @param cond the rcond to destroy */ typedef void (*destroy_cond_v1_t)(struct PSI_cond *cond); /** Socket instrumentation initialisation API. @param key the registered mutex key @param socket descriptor @param addr the socket ip address @param addr_len length of socket ip address @return an instrumented socket */ typedef struct PSI_socket* (*init_socket_v1_t) (PSI_socket_key key, const my_socket *fd, const struct sockaddr *addr, socklen_t addr_len); /** socket instrumentation destruction API. @param socket the socket to destroy */ typedef void (*destroy_socket_v1_t)(struct PSI_socket *socket); /** Acquire a table share instrumentation. @param temporary True for temporary tables @param share The SQL layer table share @return a table share instrumentation, or NULL */ typedef struct PSI_table_share* (*get_table_share_v1_t) (my_bool temporary, struct TABLE_SHARE *share); /** Release a table share. @param info the table share to release */ typedef void (*release_table_share_v1_t)(struct PSI_table_share *share); /** Drop a table share. @param temporary True for temporary tables @param schema_name the table schema name @param schema_name_length the table schema name length @param table_name the table name @param table_name_length the table name length */ typedef void (*drop_table_share_v1_t) (my_bool temporary, const char *schema_name, int schema_name_length, const char *table_name, int table_name_length); /** Open an instrumentation table handle. @param share the table to open @param identity table handle identity @return a table handle, or NULL */ typedef struct PSI_table* (*open_table_v1_t) (struct PSI_table_share *share, const void *identity); /** Unbind a table handle from the current thread. This operation happens when an opened table is added to the open table cache. @param table the table to unbind */ typedef void (*unbind_table_v1_t) (struct PSI_table *table); /** Rebind a table handle to the current thread. This operation happens when a table from the open table cache is reused for a thread. @param table the table to unbind */ typedef PSI_table* (*rebind_table_v1_t) (PSI_table_share *share, const void *identity, PSI_table *table); /** Close an instrumentation table handle. Note that the table handle is invalid after this call. @param table the table handle to close */ typedef void (*close_table_v1_t)(struct TABLE_SHARE *server_share, struct PSI_table *table); /** Create a file instrumentation for a created file. This method does not create the file itself, but is used to notify the instrumentation interface that a file was just created. @param key the file instrumentation key for this file @param name the file name @param file the file handle */ typedef void (*create_file_v1_t)(PSI_file_key key, const char *name, File file); /** Spawn a thread. This method creates a new thread, with instrumentation. @param key the instrumentation key for this thread @param thread the resulting thread @param attr the thread attributes @param start_routine the thread start routine @param arg the thread start routine argument */ typedef int (*spawn_thread_v1_t)(PSI_thread_key key, pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); /** Create instrumentation for a thread. @param key the registered key @param identity an address typical of the thread @return an instrumented thread */ typedef struct PSI_thread* (*new_thread_v1_t) (PSI_thread_key key, const void *identity, ulonglong thread_id); /** Assign a THD to an instrumented thread. @param thread the instrumented thread @param THD the sql layer THD to assign */ typedef void (*set_thread_THD_v1_t)(struct PSI_thread *thread, THD *thd); /** Assign an id to an instrumented thread. @param thread the instrumented thread @param id the id to assign */ typedef void (*set_thread_id_v1_t)(struct PSI_thread *thread, ulonglong id); /** Assign the current operating system thread id to an instrumented thread. The operating system task id is obtained from @c gettid() @param thread the instrumented thread */ typedef void (*set_thread_os_id_v1_t)(struct PSI_thread *thread); /** Get the instrumentation for the running thread. For this function to return a result, the thread instrumentation must have been attached to the running thread using @c set_thread() @return the instrumentation for the running thread */ typedef struct PSI_thread* (*get_thread_v1_t)(void); /** Assign a user name to the instrumented thread. @param user the user name @param user_len the user name length */ typedef void (*set_thread_user_v1_t)(const char *user, int user_len); /** Assign a user name and host name to the instrumented thread. @param user the user name @param user_len the user name length @param host the host name @param host_len the host name length */ typedef void (*set_thread_account_v1_t)(const char *user, int user_len, const char *host, int host_len); /** Assign a current database to the instrumented thread. @param db the database name @param db_len the database name length */ typedef void (*set_thread_db_v1_t)(const char* db, int db_len); /** Assign a current command to the instrumented thread. @param command the current command */ typedef void (*set_thread_command_v1_t)(int command); /** Assign a connection type to the instrumented thread. @param conn_type the connection type */ typedef void (*set_connection_type_v1_t)(opaque_vio_type conn_type); /** Assign a start time to the instrumented thread. @param start_time the thread start time */ typedef void (*set_thread_start_time_v1_t)(time_t start_time); /** Assign a state to the instrumented thread. @param state the thread state */ typedef void (*set_thread_state_v1_t)(const char* state); /** Assign a process info to the instrumented thread. @param info the process into string @param info_len the process into string length */ typedef void (*set_thread_info_v1_t)(const char* info, uint info_len); /** Attach a thread instrumentation to the running thread. In case of thread pools, this method should be called when a worker thread picks a work item and runs it. Also, this method should be called if the instrumented code does not keep the pointer returned by @c new_thread() and relies on @c get_thread() instead. @param thread the thread instrumentation */ typedef void (*set_thread_v1_t)(struct PSI_thread *thread); /** Assign the remote (peer) port to the instrumented thread. @param thread pointer to the thread instrumentation @param port the remote port */ typedef void (*set_thread_peer_port_v1_t)(PSI_thread *thread, unsigned int port); /** Delete the current thread instrumentation. */ typedef void (*delete_current_thread_v1_t)(void); /** Delete a thread instrumentation. */ typedef void (*delete_thread_v1_t)(struct PSI_thread *thread); /** Get a file instrumentation locker, for opening or creating a file. @param state data storage for the locker @param key the file instrumentation key @param op the operation to perform @param name the file name @param identity a pointer representative of this file. @return a file locker, or NULL */ typedef struct PSI_file_locker* (*get_thread_file_name_locker_v1_t) (struct PSI_file_locker_state_v1 *state, PSI_file_key key, enum PSI_file_operation op, const char *name, const void *identity); /** Get a file stream instrumentation locker. @param state data storage for the locker @param file the file stream to access @param op the operation to perform @return a file locker, or NULL */ typedef struct PSI_file_locker* (*get_thread_file_stream_locker_v1_t) (struct PSI_file_locker_state_v1 *state, struct PSI_file *file, enum PSI_file_operation op); /** Get a file instrumentation locker. @param state data storage for the locker @param file the file descriptor to access @param op the operation to perform @return a file locker, or NULL */ typedef struct PSI_file_locker* (*get_thread_file_descriptor_locker_v1_t) (struct PSI_file_locker_state_v1 *state, File file, enum PSI_file_operation op); /** Record a mutex instrumentation unlock event. @param mutex the mutex instrumentation */ typedef void (*unlock_mutex_v1_t) (struct PSI_mutex *mutex); /** Record a rwlock instrumentation unlock event. @param rwlock the rwlock instrumentation */ typedef void (*unlock_rwlock_v1_t) (struct PSI_rwlock *rwlock); /** Record a condition instrumentation signal event. @param cond the cond instrumentation */ typedef void (*signal_cond_v1_t) (struct PSI_cond *cond); /** Record a condition instrumentation broadcast event. @param cond the cond instrumentation */ typedef void (*broadcast_cond_v1_t) (struct PSI_cond *cond); /** Record an idle instrumentation wait start event. @param state data storage for the locker @param file the source file name @param line the source line number @return an idle locker, or NULL */ typedef struct PSI_idle_locker* (*start_idle_wait_v1_t) (struct PSI_idle_locker_state_v1 *state, const char *src_file, uint src_line); /** Record an idle instrumentation wait end event. @param locker a thread locker for the running thread */ typedef void (*end_idle_wait_v1_t) (struct PSI_idle_locker *locker); /** Record a mutex instrumentation wait start event. @param state data storage for the locker @param mutex the instrumented mutex to lock @param op the operation to perform @param file the source file name @param line the source line number @return a mutex locker, or NULL */ typedef struct PSI_mutex_locker* (*start_mutex_wait_v1_t) (struct PSI_mutex_locker_state_v1 *state, struct PSI_mutex *mutex, enum PSI_mutex_operation op, const char *src_file, uint src_line); /** Record a mutex instrumentation wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_mutex_wait_v1_t) (struct PSI_mutex_locker *locker, int rc); /** Record a rwlock instrumentation read wait start event. @param locker a thread locker for the running thread @param must must block: 1 for lock, 0 for trylock */ typedef struct PSI_rwlock_locker* (*start_rwlock_rdwait_v1_t) (struct PSI_rwlock_locker_state_v1 *state, struct PSI_rwlock *rwlock, enum PSI_rwlock_operation op, const char *src_file, uint src_line); /** Record a rwlock instrumentation read wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_rwlock_rdwait_v1_t) (struct PSI_rwlock_locker *locker, int rc); /** Record a rwlock instrumentation write wait start event. @param locker a thread locker for the running thread @param must must block: 1 for lock, 0 for trylock */ typedef struct PSI_rwlock_locker* (*start_rwlock_wrwait_v1_t) (struct PSI_rwlock_locker_state_v1 *state, struct PSI_rwlock *rwlock, enum PSI_rwlock_operation op, const char *src_file, uint src_line); /** Record a rwlock instrumentation write wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_rwlock_wrwait_v1_t) (struct PSI_rwlock_locker *locker, int rc); /** Record a condition instrumentation wait start event. @param locker a thread locker for the running thread @param must must block: 1 for wait, 0 for timedwait */ typedef struct PSI_cond_locker* (*start_cond_wait_v1_t) (struct PSI_cond_locker_state_v1 *state, struct PSI_cond *cond, struct PSI_mutex *mutex, enum PSI_cond_operation op, const char *src_file, uint src_line); /** Record a condition instrumentation wait end event. @param locker a thread locker for the running thread @param rc the wait operation return code */ typedef void (*end_cond_wait_v1_t) (struct PSI_cond_locker *locker, int rc); /** Record a table instrumentation io wait start event. @param locker a table locker for the running thread @param file the source file name @param line the source line number */ typedef struct PSI_table_locker* (*start_table_io_wait_v1_t) (struct PSI_table_locker_state *state, struct PSI_table *table, enum PSI_table_io_operation op, uint index, const char *src_file, uint src_line); /** Record a table instrumentation io wait end event. @param locker a table locker for the running thread @param numrows the number of rows involved in io */ typedef void (*end_table_io_wait_v1_t) (struct PSI_table_locker *locker, ulonglong numrows); /** Record a table instrumentation lock wait start event. @param locker a table locker for the running thread @param file the source file name @param line the source line number */ typedef struct PSI_table_locker* (*start_table_lock_wait_v1_t) (struct PSI_table_locker_state *state, struct PSI_table *table, enum PSI_table_lock_operation op, ulong flags, const char *src_file, uint src_line); /** Record a table instrumentation lock wait end event. @param locker a table locker for the running thread */ typedef void (*end_table_lock_wait_v1_t)(struct PSI_table_locker *locker); typedef void (*unlock_table_v1_t)(struct PSI_table *table); /** Start a file instrumentation open operation. @param locker the file locker @param op the operation to perform @param src_file the source file name @param src_line the source line number */ typedef void (*start_file_open_wait_v1_t) (struct PSI_file_locker *locker, const char *src_file, uint src_line); /** End a file instrumentation open operation, for file streams. @param locker the file locker. @param result the opened file (NULL indicates failure, non NULL success). @return an instrumented file handle */ typedef struct PSI_file* (*end_file_open_wait_v1_t) (struct PSI_file_locker *locker, void *result); /** End a file instrumentation open operation, for non stream files. @param locker the file locker. @param file the file number assigned by open() or create() for this file. */ typedef void (*end_file_open_wait_and_bind_to_descriptor_v1_t) (struct PSI_file_locker *locker, File file); /** End a file instrumentation open operation, for non stream temporary files. @param locker the file locker. @param file the file number assigned by open() or create() for this file. @param filename the file name generated during temporary file creation. */ typedef void (*end_temp_file_open_wait_and_bind_to_descriptor_v1_t) (struct PSI_file_locker *locker, File file, const char *filename); /** Record a file instrumentation start event. @param locker a file locker for the running thread @param op file operation to be performed @param count the number of bytes requested, or 0 if not applicable @param src_file the source file name @param src_line the source line number */ typedef void (*start_file_wait_v1_t) (struct PSI_file_locker *locker, size_t count, const char *src_file, uint src_line); /** Record a file instrumentation end event. Note that for file close operations, the instrumented file handle associated with the file (which was provided to obtain a locker) is invalid after this call. @param locker a file locker for the running thread @param count the number of bytes actually used in the operation, or 0 if not applicable, or -1 if the operation failed @sa get_thread_file_name_locker @sa get_thread_file_stream_locker @sa get_thread_file_descriptor_locker */ typedef void (*end_file_wait_v1_t) (struct PSI_file_locker *locker, size_t count); /** Start a file instrumentation close operation. @param locker the file locker @param op the operation to perform @param src_file the source file name @param src_line the source line number */ typedef void (*start_file_close_wait_v1_t) (struct PSI_file_locker *locker, const char *src_file, uint src_line); /** End a file instrumentation close operation. @param locker the file locker. @param rc the close operation return code (0 for success). @return an instrumented file handle */ typedef void (*end_file_close_wait_v1_t) (struct PSI_file_locker *locker, int rc); /** Rename a file instrumentation close operation. @param locker the file locker. @param old_name name of the file to be renamed. @param new_name name of the file after rename. @param rc the rename operation return code (0 for success). */ typedef void (*end_file_rename_wait_v1_t) (struct PSI_file_locker *locker, const char *old_name, const char *new_name, int rc); /** Start a new stage, and implicitly end the previous stage. @param key the key of the new stage @param src_file the source file name @param src_line the source line number @return the new stage progress */ typedef PSI_stage_progress* (*start_stage_v1_t) (PSI_stage_key key, const char *src_file, int src_line); typedef PSI_stage_progress* (*get_current_stage_progress_v1_t)(void); /** End the current stage. */ typedef void (*end_stage_v1_t) (void); /** Get a statement instrumentation locker. @param state data storage for the locker @param key the statement instrumentation key @param charset client character set @return a statement locker, or NULL */ typedef struct PSI_statement_locker* (*get_thread_statement_locker_v1_t) (struct PSI_statement_locker_state_v1 *state, PSI_statement_key key, const void *charset, PSI_sp_share *sp_share); /** Refine a statement locker to a more specific key. Note that only events declared mutable can be refined. @param the statement locker for the current event @param key the new key for the event @sa PSI_FLAG_MUTABLE */ typedef struct PSI_statement_locker* (*refine_statement_v1_t) (struct PSI_statement_locker *locker, PSI_statement_key key); /** Start a new statement event. @param locker the statement locker for this event @param db the active database name for this statement @param db_length the active database name length for this statement @param src_file source file name @param src_line source line number */ typedef void (*start_statement_v1_t) (struct PSI_statement_locker *locker, const char *db, uint db_length, const char *src_file, uint src_line); /** Set the statement text for a statement event. @param locker the current statement locker @param text the statement text @param text_len the statement text length */ typedef void (*set_statement_text_v1_t) (struct PSI_statement_locker *locker, const char *text, uint text_len); /** Set a statement event lock time. @param locker the statement locker @param lock_time the locked time, in microseconds */ typedef void (*set_statement_lock_time_t) (struct PSI_statement_locker *locker, ulonglong lock_time); /** Set a statement event rows sent metric. @param locker the statement locker @param count the number of rows sent */ typedef void (*set_statement_rows_sent_t) (struct PSI_statement_locker *locker, ulonglong count); /** Set a statement event rows examined metric. @param locker the statement locker @param count the number of rows examined */ typedef void (*set_statement_rows_examined_t) (struct PSI_statement_locker *locker, ulonglong count); /** Increment a statement event "created tmp disk tables" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_created_tmp_disk_tables_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "created tmp tables" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_created_tmp_tables_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select full join" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_full_join_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select full range join" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_full_range_join_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select range join" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_range_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select range check" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_range_check_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "select scan" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_select_scan_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort merge passes" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_merge_passes_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort range" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_range_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort rows" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_rows_t) (struct PSI_statement_locker *locker, ulong count); /** Increment a statement event "sort scan" metric. @param locker the statement locker @param count the metric increment value */ typedef void (*inc_statement_sort_scan_t) (struct PSI_statement_locker *locker, ulong count); /** Set a statement event "no index used" metric. @param locker the statement locker @param count the metric value */ typedef void (*set_statement_no_index_used_t) (struct PSI_statement_locker *locker); /** Set a statement event "no good index used" metric. @param locker the statement locker @param count the metric value */ typedef void (*set_statement_no_good_index_used_t) (struct PSI_statement_locker *locker); /** End a statement event. @param locker the statement locker @param stmt_da the statement diagnostics area. @sa Diagnostics_area */ typedef void (*end_statement_v1_t) (struct PSI_statement_locker *locker, void *stmt_da); /** Get a transaction instrumentation locker. @param state data storage for the locker @param xid the xid for this transaction @param trxid the InnoDB transaction id @param iso_level isolation level for this transaction @param read_only true if transaction access mode is read-only @param autocommit true if transaction is autocommit @return a transaction locker, or NULL */ typedef struct PSI_transaction_locker* (*get_thread_transaction_locker_v1_t) (struct PSI_transaction_locker_state_v1 *state, const void *xid, ulonglong trxid, int isolation_level, my_bool read_only, my_bool autocommit); /** Start a new transaction event. @param locker the transaction locker for this event @param src_file source file name @param src_line source line number */ typedef void (*start_transaction_v1_t) (struct PSI_transaction_locker *locker, const char *src_file, uint src_line); /** Set the transaction xid. @param locker the transaction locker for this event @param xid the id of the XA transaction #param xa_state is the state of the XA transaction */ typedef void (*set_transaction_xid_v1_t) (struct PSI_transaction_locker *locker, const void *xid, int xa_state); /** Set the state of the XA transaction. @param locker the transaction locker for this event @param xa_state the new state of the xa transaction */ typedef void (*set_transaction_xa_state_v1_t) (struct PSI_transaction_locker *locker, int xa_state); /** Set the transaction gtid. @param locker the transaction locker for this event @param sid the source id for the transaction, mapped from sidno @param gtid_spec the gtid specifier for the transaction */ typedef void (*set_transaction_gtid_v1_t) (struct PSI_transaction_locker *locker, const void *sid, const void *gtid_spec); /** Set the transaction trx_id. @param locker the transaction locker for this event @param trxid the storage engine transaction ID */ typedef void (*set_transaction_trxid_v1_t) (struct PSI_transaction_locker *locker, const ulonglong *trxid); /** Increment a transaction event savepoint count. @param locker the transaction locker @param count the increment value */ typedef void (*inc_transaction_savepoints_v1_t) (struct PSI_transaction_locker *locker, ulong count); /** Increment a transaction event rollback to savepoint count. @param locker the transaction locker @param count the increment value */ typedef void (*inc_transaction_rollback_to_savepoint_v1_t) (struct PSI_transaction_locker *locker, ulong count); /** Increment a transaction event release savepoint count. @param locker the transaction locker @param count the increment value */ typedef void (*inc_transaction_release_savepoint_v1_t) (struct PSI_transaction_locker *locker, ulong count); /** Commit or rollback the transaction. @param locker the transaction locker for this event @param commit true if transaction was committed, false if rolled back */ typedef void (*end_transaction_v1_t) (struct PSI_transaction_locker *locker, my_bool commit); /** Record a socket instrumentation start event. @param locker a socket locker for the running thread @param op socket operation to be performed @param count the number of bytes requested, or 0 if not applicable @param src_file the source file name @param src_line the source line number */ typedef struct PSI_socket_locker* (*start_socket_wait_v1_t) (struct PSI_socket_locker_state_v1 *state, struct PSI_socket *socket, enum PSI_socket_operation op, size_t count, const char *src_file, uint src_line); /** Record a socket instrumentation end event. Note that for socket close operations, the instrumented socket handle associated with the socket (which was provided to obtain a locker) is invalid after this call. @param locker a socket locker for the running thread @param count the number of bytes actually used in the operation, or 0 if not applicable, or -1 if the operation failed @sa get_thread_socket_locker */ typedef void (*end_socket_wait_v1_t) (struct PSI_socket_locker *locker, size_t count); /** Set the socket state for an instrumented socket. @param socket the instrumented socket @param state socket state */ typedef void (*set_socket_state_v1_t)(struct PSI_socket *socket, enum PSI_socket_state state); /** Set the socket info for an instrumented socket. @param socket the instrumented socket @param fd the socket descriptor @param addr the socket ip address @param addr_len length of socket ip address @param thread_id associated thread id */ typedef void (*set_socket_info_v1_t)(struct PSI_socket *socket, const my_socket *fd, const struct sockaddr *addr, socklen_t addr_len); /** Bind a socket to the thread that owns it. @param socket instrumented socket */ typedef void (*set_socket_thread_owner_v1_t)(struct PSI_socket *socket); /** Get a prepare statement. @param locker a statement locker for the running thread. */ typedef PSI_prepared_stmt* (*create_prepared_stmt_v1_t) (void *identity, uint stmt_id, PSI_statement_locker *locker, const char *stmt_name, size_t stmt_name_length); /** destroy a prepare statement. @param prepared_stmt prepared statement. */ typedef void (*destroy_prepared_stmt_v1_t) (PSI_prepared_stmt *prepared_stmt); /** repreare a prepare statement. @param prepared_stmt prepared statement. */ typedef void (*reprepare_prepared_stmt_v1_t) (PSI_prepared_stmt *prepared_stmt); /** Record a prepare statement instrumentation execute event. @param locker a statement locker for the running thread. @param prepared_stmt prepared statement. */ typedef void (*execute_prepared_stmt_v1_t) (PSI_statement_locker *locker, PSI_prepared_stmt* prepared_stmt); /** Set the statement text for a prepared statement event. @param prepared_stmt prepared statement. @param text the prepared statement text @param text_len the prepared statement text length */ typedef void (*set_prepared_stmt_text_v1_t)(PSI_prepared_stmt *prepared_stmt, const char *text, uint text_len); /** Get a digest locker for the current statement. @param locker a statement locker for the running thread */ typedef struct PSI_digest_locker * (*digest_start_v1_t) (struct PSI_statement_locker *locker); /** Add a token to the current digest instrumentation. @param locker a digest locker for the current statement @param token the lexical token to add @param yylval the lexical token attributes */ typedef void (*digest_end_v1_t) (struct PSI_digest_locker *locker, const struct sql_digest_storage *digest); typedef PSI_sp_locker* (*start_sp_v1_t) (struct PSI_sp_locker_state_v1 *state, struct PSI_sp_share* sp_share); typedef void (*end_sp_v1_t) (struct PSI_sp_locker *locker); typedef void (*drop_sp_v1_t) (uint object_type, const char *schema_name, uint schema_name_length, const char *object_name, uint object_name_length); /** Acquire a sp share instrumentation. @param type of stored program @param schema name of stored program @param name of stored program @return a stored program share instrumentation, or NULL */ typedef struct PSI_sp_share* (*get_sp_share_v1_t) (uint object_type, const char *schema_name, uint schema_name_length, const char *object_name, uint object_name_length); /** Release a stored program share. @param info the stored program share to release */ typedef void (*release_sp_share_v1_t)(struct PSI_sp_share *share); typedef PSI_metadata_lock* (*create_metadata_lock_v1_t) (void *identity, const MDL_key *key, opaque_mdl_type mdl_type, opaque_mdl_duration mdl_duration, opaque_mdl_status mdl_status, const char *src_file, uint src_line); typedef void (*set_metadata_lock_status_v1_t)(PSI_metadata_lock *lock, opaque_mdl_status mdl_status); typedef void (*destroy_metadata_lock_v1_t)(PSI_metadata_lock *lock); typedef struct PSI_metadata_locker* (*start_metadata_wait_v1_t) (struct PSI_metadata_locker_state_v1 *state, struct PSI_metadata_lock *mdl, const char *src_file, uint src_line); typedef void (*end_metadata_wait_v1_t) (struct PSI_metadata_locker *locker, int rc); /** Stores an array of connection attributes @param buffer char array of length encoded connection attributes in network format @param length length of the data in buffer @param from_cs charset in which @c buffer is encoded @return state @retval non_0 attributes truncated @retval 0 stored the attribute */ typedef int (*set_thread_connect_attrs_v1_t)(const char *buffer, uint length, const void *from_cs); /** Performance Schema Interface, version 1. @since PSI_VERSION_1 */ struct PSI_v1 { /** @sa register_mutex_v1_t. */ register_mutex_v1_t register_mutex; /** @sa register_rwlock_v1_t. */ register_rwlock_v1_t register_rwlock; /** @sa register_cond_v1_t. */ register_cond_v1_t register_cond; /** @sa register_thread_v1_t. */ register_thread_v1_t register_thread; /** @sa register_file_v1_t. */ register_file_v1_t register_file; /** @sa register_stage_v1_t. */ register_stage_v1_t register_stage; /** @sa register_statement_v1_t. */ register_statement_v1_t register_statement; /** @sa register_socket_v1_t. */ register_socket_v1_t register_socket; /** @sa init_mutex_v1_t. */ init_mutex_v1_t init_mutex; /** @sa destroy_mutex_v1_t. */ destroy_mutex_v1_t destroy_mutex; /** @sa init_rwlock_v1_t. */ init_rwlock_v1_t init_rwlock; /** @sa destroy_rwlock_v1_t. */ destroy_rwlock_v1_t destroy_rwlock; /** @sa init_cond_v1_t. */ init_cond_v1_t init_cond; /** @sa destroy_cond_v1_t. */ destroy_cond_v1_t destroy_cond; /** @sa init_socket_v1_t. */ init_socket_v1_t init_socket; /** @sa destroy_socket_v1_t. */ destroy_socket_v1_t destroy_socket; /** @sa get_table_share_v1_t. */ get_table_share_v1_t get_table_share; /** @sa release_table_share_v1_t. */ release_table_share_v1_t release_table_share; /** @sa drop_table_share_v1_t. */ drop_table_share_v1_t drop_table_share; /** @sa open_table_v1_t. */ open_table_v1_t open_table; /** @sa unbind_table_v1_t. */ unbind_table_v1_t unbind_table; /** @sa rebind_table_v1_t. */ rebind_table_v1_t rebind_table; /** @sa close_table_v1_t. */ close_table_v1_t close_table; /** @sa create_file_v1_t. */ create_file_v1_t create_file; /** @sa spawn_thread_v1_t. */ spawn_thread_v1_t spawn_thread; /** @sa new_thread_v1_t. */ new_thread_v1_t new_thread; /** @sa set_thread_id_v1_t. */ set_thread_id_v1_t set_thread_id; /** @sa set_thread_THD_v1_t. */ set_thread_THD_v1_t set_thread_THD; /** @sa set_thread_os_id_v1_t. */ set_thread_os_id_v1_t set_thread_os_id; /** @sa get_thread_v1_t. */ get_thread_v1_t get_thread; /** @sa set_thread_user_v1_t. */ set_thread_user_v1_t set_thread_user; /** @sa set_thread_account_v1_t. */ set_thread_account_v1_t set_thread_account; /** @sa set_thread_db_v1_t. */ set_thread_db_v1_t set_thread_db; /** @sa set_thread_command_v1_t. */ set_thread_command_v1_t set_thread_command; /** @sa set_connection_type_v1_t. */ set_connection_type_v1_t set_connection_type; /** @sa set_thread_start_time_v1_t. */ set_thread_start_time_v1_t set_thread_start_time; /** @sa set_thread_state_v1_t. */ set_thread_state_v1_t set_thread_state; /** @sa set_thread_info_v1_t. */ set_thread_info_v1_t set_thread_info; /** @sa set_thread_v1_t. */ set_thread_v1_t set_thread; /** @sa delete_current_thread_v1_t. */ delete_current_thread_v1_t delete_current_thread; /** @sa delete_thread_v1_t. */ delete_thread_v1_t delete_thread; /** @sa get_thread_file_name_locker_v1_t. */ get_thread_file_name_locker_v1_t get_thread_file_name_locker; /** @sa get_thread_file_stream_locker_v1_t. */ get_thread_file_stream_locker_v1_t get_thread_file_stream_locker; /** @sa get_thread_file_descriptor_locker_v1_t. */ get_thread_file_descriptor_locker_v1_t get_thread_file_descriptor_locker; /** @sa unlock_mutex_v1_t. */ unlock_mutex_v1_t unlock_mutex; /** @sa unlock_rwlock_v1_t. */ unlock_rwlock_v1_t unlock_rwlock; /** @sa signal_cond_v1_t. */ signal_cond_v1_t signal_cond; /** @sa broadcast_cond_v1_t. */ broadcast_cond_v1_t broadcast_cond; /** @sa start_idle_wait_v1_t. */ start_idle_wait_v1_t start_idle_wait; /** @sa end_idle_wait_v1_t. */ end_idle_wait_v1_t end_idle_wait; /** @sa start_mutex_wait_v1_t. */ start_mutex_wait_v1_t start_mutex_wait; /** @sa end_mutex_wait_v1_t. */ end_mutex_wait_v1_t end_mutex_wait; /** @sa start_rwlock_rdwait_v1_t. */ start_rwlock_rdwait_v1_t start_rwlock_rdwait; /** @sa end_rwlock_rdwait_v1_t. */ end_rwlock_rdwait_v1_t end_rwlock_rdwait; /** @sa start_rwlock_wrwait_v1_t. */ start_rwlock_wrwait_v1_t start_rwlock_wrwait; /** @sa end_rwlock_wrwait_v1_t. */ end_rwlock_wrwait_v1_t end_rwlock_wrwait; /** @sa start_cond_wait_v1_t. */ start_cond_wait_v1_t start_cond_wait; /** @sa end_cond_wait_v1_t. */ end_cond_wait_v1_t end_cond_wait; /** @sa start_table_io_wait_v1_t. */ start_table_io_wait_v1_t start_table_io_wait; /** @sa end_table_io_wait_v1_t. */ end_table_io_wait_v1_t end_table_io_wait; /** @sa start_table_lock_wait_v1_t. */ start_table_lock_wait_v1_t start_table_lock_wait; /** @sa end_table_lock_wait_v1_t. */ end_table_lock_wait_v1_t end_table_lock_wait; /** @sa start_file_open_wait_v1_t. */ start_file_open_wait_v1_t start_file_open_wait; /** @sa end_file_open_wait_v1_t. */ end_file_open_wait_v1_t end_file_open_wait; /** @sa end_file_open_wait_and_bind_to_descriptor_v1_t. */ end_file_open_wait_and_bind_to_descriptor_v1_t end_file_open_wait_and_bind_to_descriptor; /** @sa end_temp_file_open_wait_and_bind_to_descriptor_v1_t. */ end_temp_file_open_wait_and_bind_to_descriptor_v1_t end_temp_file_open_wait_and_bind_to_descriptor; /** @sa start_file_wait_v1_t. */ start_file_wait_v1_t start_file_wait; /** @sa end_file_wait_v1_t. */ end_file_wait_v1_t end_file_wait; /** @sa start_file_close_wait_v1_t. */ start_file_close_wait_v1_t start_file_close_wait; /** @sa end_file_close_wait_v1_t. */ end_file_close_wait_v1_t end_file_close_wait; /** @sa rename_file_close_wait_v1_t. */ end_file_rename_wait_v1_t end_file_rename_wait; /** @sa start_stage_v1_t. */ start_stage_v1_t start_stage; /** @sa get_current_stage_progress_v1_t. */ get_current_stage_progress_v1_t get_current_stage_progress; /** @sa end_stage_v1_t. */ end_stage_v1_t end_stage; /** @sa get_thread_statement_locker_v1_t. */ get_thread_statement_locker_v1_t get_thread_statement_locker; /** @sa refine_statement_v1_t. */ refine_statement_v1_t refine_statement; /** @sa start_statement_v1_t. */ start_statement_v1_t start_statement; /** @sa set_statement_text_v1_t. */ set_statement_text_v1_t set_statement_text; /** @sa set_statement_lock_time_t. */ set_statement_lock_time_t set_statement_lock_time; /** @sa set_statement_rows_sent_t. */ set_statement_rows_sent_t set_statement_rows_sent; /** @sa set_statement_rows_examined_t. */ set_statement_rows_examined_t set_statement_rows_examined; /** @sa inc_statement_created_tmp_disk_tables. */ inc_statement_created_tmp_disk_tables_t inc_statement_created_tmp_disk_tables; /** @sa inc_statement_created_tmp_tables. */ inc_statement_created_tmp_tables_t inc_statement_created_tmp_tables; /** @sa inc_statement_select_full_join. */ inc_statement_select_full_join_t inc_statement_select_full_join; /** @sa inc_statement_select_full_range_join. */ inc_statement_select_full_range_join_t inc_statement_select_full_range_join; /** @sa inc_statement_select_range. */ inc_statement_select_range_t inc_statement_select_range; /** @sa inc_statement_select_range_check. */ inc_statement_select_range_check_t inc_statement_select_range_check; /** @sa inc_statement_select_scan. */ inc_statement_select_scan_t inc_statement_select_scan; /** @sa inc_statement_sort_merge_passes. */ inc_statement_sort_merge_passes_t inc_statement_sort_merge_passes; /** @sa inc_statement_sort_range. */ inc_statement_sort_range_t inc_statement_sort_range; /** @sa inc_statement_sort_rows. */ inc_statement_sort_rows_t inc_statement_sort_rows; /** @sa inc_statement_sort_scan. */ inc_statement_sort_scan_t inc_statement_sort_scan; /** @sa set_statement_no_index_used. */ set_statement_no_index_used_t set_statement_no_index_used; /** @sa set_statement_no_good_index_used. */ set_statement_no_good_index_used_t set_statement_no_good_index_used; /** @sa end_statement_v1_t. */ end_statement_v1_t end_statement; /** @sa get_thread_transaction_locker_v1_t. */ get_thread_transaction_locker_v1_t get_thread_transaction_locker; /** @sa start_transaction_v1_t. */ start_transaction_v1_t start_transaction; /** @sa set_transaction_xid_v1_t. */ set_transaction_xid_v1_t set_transaction_xid; /** @sa set_transaction_xa_state_v1_t. */ set_transaction_xa_state_v1_t set_transaction_xa_state; /** @sa set_transaction_gtid_v1_t. */ set_transaction_gtid_v1_t set_transaction_gtid; /** @sa set_transaction_trxid_v1_t. */ set_transaction_trxid_v1_t set_transaction_trxid; /** @sa inc_transaction_savepoints_v1_t. */ inc_transaction_savepoints_v1_t inc_transaction_savepoints; /** @sa inc_transaction_rollback_to_savepoint_v1_t. */ inc_transaction_rollback_to_savepoint_v1_t inc_transaction_rollback_to_savepoint; /** @sa inc_transaction_release_savepoint_v1_t. */ inc_transaction_release_savepoint_v1_t inc_transaction_release_savepoint; /** @sa end_transaction_v1_t. */ end_transaction_v1_t end_transaction; /** @sa start_socket_wait_v1_t. */ start_socket_wait_v1_t start_socket_wait; /** @sa end_socket_wait_v1_t. */ end_socket_wait_v1_t end_socket_wait; /** @sa set_socket_state_v1_t. */ set_socket_state_v1_t set_socket_state; /** @sa set_socket_info_v1_t. */ set_socket_info_v1_t set_socket_info; /** @sa set_socket_thread_owner_v1_t. */ set_socket_thread_owner_v1_t set_socket_thread_owner; /** @sa create_prepared_stmt_v1_t. */ create_prepared_stmt_v1_t create_prepared_stmt; /** @sa destroy_prepared_stmt_v1_t. */ destroy_prepared_stmt_v1_t destroy_prepared_stmt; /** @sa reprepare_prepared_stmt_v1_t. */ reprepare_prepared_stmt_v1_t reprepare_prepared_stmt; /** @sa execute_prepared_stmt_v1_t. */ execute_prepared_stmt_v1_t execute_prepared_stmt; /** @sa set_prepared_stmt_text_v1_t. */ set_prepared_stmt_text_v1_t set_prepared_stmt_text; /** @sa digest_start_v1_t. */ digest_start_v1_t digest_start; /** @sa digest_end_v1_t. */ digest_end_v1_t digest_end; /** @sa set_thread_connect_attrs_v1_t. */ set_thread_connect_attrs_v1_t set_thread_connect_attrs; /** @sa start_sp_v1_t. */ start_sp_v1_t start_sp; /** @sa start_sp_v1_t. */ end_sp_v1_t end_sp; /** @sa drop_sp_v1_t. */ drop_sp_v1_t drop_sp; /** @sa get_sp_share_v1_t. */ get_sp_share_v1_t get_sp_share; /** @sa release_sp_share_v1_t. */ release_sp_share_v1_t release_sp_share; /** @sa register_memory_v1_t. */ register_memory_v1_t register_memory; /** @sa memory_alloc_v1_t. */ memory_alloc_v1_t memory_alloc; /** @sa memory_realloc_v1_t. */ memory_realloc_v1_t memory_realloc; /** @sa memory_claim_v1_t. */ memory_claim_v1_t memory_claim; /** @sa memory_free_v1_t. */ memory_free_v1_t memory_free; unlock_table_v1_t unlock_table; create_metadata_lock_v1_t create_metadata_lock; set_metadata_lock_status_v1_t set_metadata_lock_status; destroy_metadata_lock_v1_t destroy_metadata_lock; start_metadata_wait_v1_t start_metadata_wait; end_metadata_wait_v1_t end_metadata_wait; set_thread_peer_port_v1_t set_thread_peer_port; }; /** @} (end of group Group_PSI_v1) */ #endif /* HAVE_PSI_1 */ #ifdef USE_PSI_2 #define HAVE_PSI_2 #endif #ifdef HAVE_PSI_2 /** @defgroup Group_PSI_v2 Application Binary Interface, version 2 @ingroup Instrumentation_interface @{ */ /** Performance Schema Interface, version 2. This is a placeholder, this interface is not defined yet. @since PSI_VERSION_2 */ struct PSI_v2 { /** Placeholder */ int placeholder; /* ... extended interface ... */ }; /** Placeholder */ struct PSI_mutex_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_rwlock_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_cond_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_thread_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_file_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_stage_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_statement_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_transaction_info_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_idle_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_mutex_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_rwlock_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_cond_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_file_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_statement_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_transaction_locker_state_v2 { /** Placeholder */ int placeholder; }; /** Placeholder */ struct PSI_socket_locker_state_v2 { /** Placeholder */ int placeholder; }; struct PSI_metadata_locker_state_v2 { int placeholder; }; /** @} (end of group Group_PSI_v2) */ #endif /* HAVE_PSI_2 */ /** @typedef PSI The instrumentation interface for the current version. @sa PSI_CURRENT_VERSION */ /** @typedef PSI_mutex_info The mutex information structure for the current version. */ /** @typedef PSI_rwlock_info The rwlock information structure for the current version. */ /** @typedef PSI_cond_info The cond information structure for the current version. */ /** @typedef PSI_thread_info The thread information structure for the current version. */ /** @typedef PSI_file_info The file information structure for the current version. */ /* Export the required version */ #ifdef USE_PSI_1 typedef struct PSI_v1 PSI; typedef struct PSI_mutex_info_v1 PSI_mutex_info; typedef struct PSI_rwlock_info_v1 PSI_rwlock_info; typedef struct PSI_cond_info_v1 PSI_cond_info; typedef struct PSI_thread_info_v1 PSI_thread_info; typedef struct PSI_file_info_v1 PSI_file_info; typedef struct PSI_stage_info_v1 PSI_stage_info; typedef struct PSI_statement_info_v1 PSI_statement_info; typedef struct PSI_transaction_info_v1 PSI_transaction_info; typedef struct PSI_socket_info_v1 PSI_socket_info; typedef struct PSI_idle_locker_state_v1 PSI_idle_locker_state; typedef struct PSI_mutex_locker_state_v1 PSI_mutex_locker_state; typedef struct PSI_rwlock_locker_state_v1 PSI_rwlock_locker_state; typedef struct PSI_cond_locker_state_v1 PSI_cond_locker_state; typedef struct PSI_file_locker_state_v1 PSI_file_locker_state; typedef struct PSI_statement_locker_state_v1 PSI_statement_locker_state; typedef struct PSI_transaction_locker_state_v1 PSI_transaction_locker_state; typedef struct PSI_socket_locker_state_v1 PSI_socket_locker_state; typedef struct PSI_sp_locker_state_v1 PSI_sp_locker_state; typedef struct PSI_metadata_locker_state_v1 PSI_metadata_locker_state; #endif #ifdef USE_PSI_2 typedef struct PSI_v2 PSI; typedef struct PSI_mutex_info_v2 PSI_mutex_info; typedef struct PSI_rwlock_info_v2 PSI_rwlock_info; typedef struct PSI_cond_info_v2 PSI_cond_info; typedef struct PSI_thread_info_v2 PSI_thread_info; typedef struct PSI_file_info_v2 PSI_file_info; typedef struct PSI_stage_info_v2 PSI_stage_info; typedef struct PSI_statement_info_v2 PSI_statement_info; typedef struct PSI_transaction_info_v2 PSI_transaction_info; typedef struct PSI_socket_info_v2 PSI_socket_info; typedef struct PSI_idle_locker_state_v2 PSI_idle_locker_state; typedef struct PSI_mutex_locker_state_v2 PSI_mutex_locker_state; typedef struct PSI_rwlock_locker_state_v2 PSI_rwlock_locker_state; typedef struct PSI_cond_locker_state_v2 PSI_cond_locker_state; typedef struct PSI_file_locker_state_v2 PSI_file_locker_state; typedef struct PSI_statement_locker_state_v2 PSI_statement_locker_state; typedef struct PSI_transaction_locker_state_v2 PSI_transaction_locker_state; typedef struct PSI_socket_locker_state_v2 PSI_socket_locker_state; typedef struct PSI_sp_locker_state_v2 PSI_sp_locker_state; typedef struct PSI_metadata_locker_state_v2 PSI_metadata_locker_state; #endif #ifndef HAVE_PSI_INTERFACE /** Dummy structure, used to declare PSI_server when no instrumentation is available. The content does not matter, since PSI_server will be NULL. */ struct PSI_none { int opaque; }; typedef struct PSI_none PSI; /** Stage instrument information. @since PSI_VERSION_1 This structure is used to register an instrumented stage. */ struct PSI_stage_info_none { /** Unused stage key. */ unsigned int m_key; /** The name of the stage instrument. */ const char *m_name; /** Unused stage flags. */ int m_flags; }; /** The stage instrumentation has to co exist with the legacy THD::set_proc_info instrumentation. To avoid duplication of the instrumentation in the server, the common PSI_stage_info structure is used, so we export it here, even when not building with HAVE_PSI_INTERFACE. */ typedef struct PSI_stage_info_none PSI_stage_info; typedef struct PSI_stage_info_none PSI_statement_info; typedef struct PSI_stage_info_none PSI_sp_locker_state; typedef struct PSI_stage_info_none PSI_metadata_locker_state; typedef struct PSI_stage_info_none PSI_metadata_locker; #endif /* HAVE_PSI_INTERFACE */ extern MYSQL_PLUGIN_IMPORT PSI *PSI_server; /* Allow to override PSI_XXX_CALL at compile time with more efficient implementations, if available. If nothing better is available, make a dynamic call using the PSI_server function pointer. */ #define PSI_DYNAMIC_CALL(M) PSI_server->M /** @} */ C_MODE_END #endif /* MYSQL_PERFORMANCE_SCHEMA_INTERFACE_H */ mysql/server/mysql/psi/mysql_statement.h000064400000015706151027430560014575 0ustar00/* Copyright (c) 2010, 2023, Oracle and/or its affiliates. Copyright (c) 2017, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQL_STATEMENT_H #define MYSQL_STATEMENT_H /** @file mysql/psi/mysql_statement.h Instrumentation helpers for statements. */ #include "mysql/psi/psi.h" class Diagnostics_area; typedef const struct charset_info_st CHARSET_INFO; #ifndef PSI_STATEMENT_CALL #define PSI_STATEMENT_CALL(M) PSI_DYNAMIC_CALL(M) #endif #ifndef PSI_DIGEST_CALL #define PSI_DIGEST_CALL(M) PSI_DYNAMIC_CALL(M) #endif /** @defgroup Statement_instrumentation Statement Instrumentation @ingroup Instrumentation_interface @{ */ /** @def mysql_statement_register(P1, P2, P3) Statement registration. */ #ifdef HAVE_PSI_STATEMENT_INTERFACE #define mysql_statement_register(P1, P2, P3) \ inline_mysql_statement_register(P1, P2, P3) #else #define mysql_statement_register(P1, P2, P3) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE #define MYSQL_DIGEST_START(LOCKER) \ inline_mysql_digest_start(LOCKER) #else #define MYSQL_DIGEST_START(LOCKER) \ NULL #endif #ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE #define MYSQL_DIGEST_END(LOCKER, DIGEST) \ inline_mysql_digest_end(LOCKER, DIGEST) #else #define MYSQL_DIGEST_END(LOCKER, DIGEST) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_START_STATEMENT(STATE, K, DB, DB_LEN, CS, SPS) \ inline_mysql_start_statement(STATE, K, DB, DB_LEN, CS, SPS, __FILE__, __LINE__) #else #define MYSQL_START_STATEMENT(STATE, K, DB, DB_LEN, CS, SPS) \ NULL #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_REFINE_STATEMENT(LOCKER, K) \ inline_mysql_refine_statement(LOCKER, K) #else #define MYSQL_REFINE_STATEMENT(LOCKER, K) \ NULL #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_SET_STATEMENT_TEXT(LOCKER, P1, P2) \ inline_mysql_set_statement_text(LOCKER, P1, P2) #else #define MYSQL_SET_STATEMENT_TEXT(LOCKER, P1, P2) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_SET_STATEMENT_LOCK_TIME(LOCKER, P1) \ inline_mysql_set_statement_lock_time(LOCKER, P1) #else #define MYSQL_SET_STATEMENT_LOCK_TIME(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_SET_STATEMENT_ROWS_SENT(LOCKER, P1) \ inline_mysql_set_statement_rows_sent(LOCKER, P1) #else #define MYSQL_SET_STATEMENT_ROWS_SENT(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_SET_STATEMENT_ROWS_EXAMINED(LOCKER, P1) \ inline_mysql_set_statement_rows_examined(LOCKER, P1) #else #define MYSQL_SET_STATEMENT_ROWS_EXAMINED(LOCKER, P1) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE #define MYSQL_END_STATEMENT(LOCKER, DA) \ inline_mysql_end_statement(LOCKER, DA) #else #define MYSQL_END_STATEMENT(LOCKER, DA) \ do {} while (0) #endif #ifdef HAVE_PSI_STATEMENT_INTERFACE static inline void inline_mysql_statement_register( const char *category, PSI_statement_info *info, int count) { PSI_STATEMENT_CALL(register_statement)(category, info, count); } #ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE static inline struct PSI_digest_locker * inline_mysql_digest_start(PSI_statement_locker *locker) { PSI_digest_locker* digest_locker= NULL; if (psi_likely(locker != NULL)) digest_locker= PSI_DIGEST_CALL(digest_start)(locker); return digest_locker; } #endif #ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE static inline void inline_mysql_digest_end(PSI_digest_locker *locker, const sql_digest_storage *digest) { if (psi_likely(locker != NULL)) PSI_DIGEST_CALL(digest_end)(locker, digest); } #endif static inline struct PSI_statement_locker * inline_mysql_start_statement(PSI_statement_locker_state *state, PSI_statement_key key, const char *db, size_t db_len, CHARSET_INFO *charset, PSI_sp_share *sp_share, const char *src_file, uint src_line) { PSI_statement_locker *locker; locker= PSI_STATEMENT_CALL(get_thread_statement_locker)(state, key, charset, sp_share); if (psi_likely(locker != NULL)) PSI_STATEMENT_CALL(start_statement)(locker, db, (uint)db_len, src_file, src_line); return locker; } static inline struct PSI_statement_locker * inline_mysql_refine_statement(PSI_statement_locker *locker, PSI_statement_key key) { if (psi_likely(locker != NULL)) { locker= PSI_STATEMENT_CALL(refine_statement)(locker, key); } return locker; } static inline void inline_mysql_set_statement_text(PSI_statement_locker *locker, const char *text, uint text_len) { if (psi_likely(locker != NULL)) { PSI_STATEMENT_CALL(set_statement_text)(locker, text, text_len); } } static inline void inline_mysql_set_statement_lock_time(PSI_statement_locker *locker, ulonglong count) { if (psi_likely(locker != NULL)) { PSI_STATEMENT_CALL(set_statement_lock_time)(locker, count); } } static inline void inline_mysql_set_statement_rows_sent(PSI_statement_locker *locker, ulonglong count) { if (psi_likely(locker != NULL)) { PSI_STATEMENT_CALL(set_statement_rows_sent)(locker, count); } } static inline void inline_mysql_set_statement_rows_examined(PSI_statement_locker *locker, ulonglong count) { if (psi_likely(locker != NULL)) { PSI_STATEMENT_CALL(set_statement_rows_examined)(locker, count); } } static inline void inline_mysql_end_statement(struct PSI_statement_locker *locker, Diagnostics_area *stmt_da) { PSI_STAGE_CALL(end_stage)(); if (psi_likely(locker != NULL)) PSI_STATEMENT_CALL(end_statement)(locker, stmt_da); } #endif /** @} (end of group Statement_instrumentation) */ #endif mysql/server/mysql/plugin_encryption.h000064400000010521151027430560014307 0ustar00#ifndef MYSQL_PLUGIN_ENCRYPTION_INCLUDED /* Copyright (C) 2014, 2015 Sergei Golubchik and MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Encryption Plugin API. This file defines the API for server plugins that manage encryption keys for MariaDB on-disk data encryption. */ #define MYSQL_PLUGIN_ENCRYPTION_INCLUDED #include #ifdef __cplusplus extern "C" { #endif #define MariaDB_ENCRYPTION_INTERFACE_VERSION 0x0300 /** Encryption plugin descriptor */ struct st_mariadb_encryption { int interface_version; /**< version plugin uses */ /*********** KEY MANAGEMENT ********************************************/ /** function returning latest key version for a given key id @return a version or ENCRYPTION_KEY_VERSION_INVALID to indicate an error. */ unsigned int (*get_latest_key_version)(unsigned int key_id); /** function returning a key for a key version @param version the requested key version @param key the key will be stored there. Can be NULL - in which case no key will be returned @param key_length in: key buffer size out: the actual length of the key This method can be used to query the key length - the required buffer size - by passing key==NULL. If the buffer size is less than the key length the content of the key buffer is undefined (the plugin is free to partially fill it with the key data or leave it untouched). @return 0 on success, or ENCRYPTION_KEY_VERSION_INVALID, ENCRYPTION_KEY_BUFFER_TOO_SMALL or any other non-zero number for errors */ unsigned int (*get_key)(unsigned int key_id, unsigned int version, unsigned char *key, unsigned int *key_length); /*********** ENCRYPTION ************************************************/ /* the caller uses encryption as follows: 1. create the encryption context object of the crypt_ctx_size() bytes. 2. initialize it with crypt_ctx_init(). 3. repeat crypt_ctx_update() until there are no more data to encrypt. 4. write the remaining output bytes and destroy the context object with crypt_ctx_finish(). */ /** returns the size of the encryption context object in bytes */ unsigned int (*crypt_ctx_size)(unsigned int key_id, unsigned int key_version); /** initializes the encryption context object. */ int (*crypt_ctx_init)(void *ctx, const unsigned char* key, unsigned int klen, const unsigned char* iv, unsigned int ivlen, int flags, unsigned int key_id, unsigned int key_version); /** processes (encrypts or decrypts) a chunk of data writes the output to th dst buffer. note that it might write more bytes that were in the input. or less. or none at all. */ int (*crypt_ctx_update)(void *ctx, const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen); /** writes the remaining output bytes and destroys the encryption context crypt_ctx_update might've cached part of the output in the context, this method will flush these data out. */ int (*crypt_ctx_finish)(void *ctx, unsigned char* dst, unsigned int* dlen); /** returns the length of the encrypted data it returns the exact length, given only the source length. which means, this API only supports encryption algorithms where the length of the encrypted data only depends on the length of the input (a.k.a. compression is not supported). */ unsigned int (*encrypted_length)(unsigned int slen, unsigned int key_id, unsigned int key_version); }; #ifdef __cplusplus } #endif #endif mysql/server/mysql/auth_dialog_client.h000064400000004015151027430560014356 0ustar00#ifndef MYSQL_AUTH_DIALOG_CLIENT_INCLUDED /* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Definitions needed to use Dialog client authentication plugin */ struct st_mysql; #define MYSQL_AUTH_DIALOG_CLIENT_INCLUDED /** type of the mysql_authentication_dialog_ask function @param mysql mysql @param type type of the input 1 - ordinary string input 2 - password string @param prompt prompt @param buf a buffer to store the use input @param buf_len the length of the buffer @retval a pointer to the user input string. It may be equal to 'buf' or to 'mysql->password'. In all other cases it is assumed to be an allocated string, and the "dialog" plugin will free() it. */ typedef char *(*mysql_authentication_dialog_ask_t)(struct st_mysql *mysql, int type, const char *prompt, char *buf, int buf_len); /** first byte of the question string is the question "type". It can be an "ordinary" or a "password" question. The last bit set marks a last question in the authentication exchange. */ #define ORDINARY_QUESTION "\2" #define LAST_QUESTION "\3" #define PASSWORD_QUESTION "\4" #define LAST_PASSWORD "\5" #endif mysql/server/mysql/service_progress_report.h000064400000006434151027430560015526 0ustar00#ifndef MYSQL_SERVICE_PROGRESS_REPORT_INCLUDED /* Copyright (C) 2011 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This service allows plugins to report progress of long running operations to the server. The progress report is visible in SHOW PROCESSLIST, INFORMATION_SCHEMA.PROCESSLIST, and is sent to the client if requested. The functions are documented at https://mariadb.com/kb/en/progress-reporting/#how-to-add-support-for-progress-reporting-to-a-storage-engine */ #ifdef __cplusplus extern "C" { #endif #define thd_proc_info(thd, msg) set_thd_proc_info(thd, msg, \ __func__, __FILE__, __LINE__) extern struct progress_report_service_st { void (*thd_progress_init_func)(MYSQL_THD thd, unsigned int max_stage); void (*thd_progress_report_func)(MYSQL_THD thd, unsigned long long progress, unsigned long long max_progress); void (*thd_progress_next_stage_func)(MYSQL_THD thd); void (*thd_progress_end_func)(MYSQL_THD thd); const char *(*set_thd_proc_info_func)(MYSQL_THD, const char *info, const char *func, const char *file, unsigned int line); } *progress_report_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_progress_init(thd,max_stage) (progress_report_service->thd_progress_init_func((thd),(max_stage))) #define thd_progress_report(thd, progress, max_progress) (progress_report_service->thd_progress_report_func((thd), (progress), (max_progress))) #define thd_progress_next_stage(thd) (progress_report_service->thd_progress_next_stage_func(thd)) #define thd_progress_end(thd) (progress_report_service->thd_progress_end_func(thd)) #define set_thd_proc_info(thd,info,func,file,line) (progress_report_service->set_thd_proc_info_func((thd),(info),(func),(file),(line))) #else /** Report progress for long running operations @param thd User thread connection handle @param progress Where we are now @param max_progress Progress will continue up to this */ void thd_progress_init(MYSQL_THD thd, unsigned int max_stage); void thd_progress_report(MYSQL_THD thd, unsigned long long progress, unsigned long long max_progress); void thd_progress_next_stage(MYSQL_THD thd); void thd_progress_end(MYSQL_THD thd); const char *set_thd_proc_info(MYSQL_THD, const char * info, const char *func, const char *file, unsigned int line); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_PROGRESS_REPORT_INCLUDED #endif mysql/server/mysql/service_thd_alloc.h000064400000010612151027430560014211 0ustar00#ifndef MYSQL_SERVICE_THD_ALLOC_INCLUDED /* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This service provides functions to allocate memory in a connection local memory pool. The memory allocated there will be automatically freed at the end of the statement, don't use it for allocations that should live longer than that. For short living allocations this is more efficient than using my_malloc and friends, and automatic "garbage collection" allows not to think about memory leaks. The pool is best for small to medium objects, don't use it for large allocations - they are better served with my_malloc. */ #ifndef MYSQL_ABI_CHECK #include #endif #ifdef __cplusplus extern "C" { #endif struct st_mysql_lex_string { char *str; size_t length; }; typedef struct st_mysql_lex_string MYSQL_LEX_STRING; struct st_mysql_const_lex_string { const char *str; size_t length; }; typedef struct st_mysql_const_lex_string MYSQL_CONST_LEX_STRING; extern struct thd_alloc_service_st { void *(*thd_alloc_func)(MYSQL_THD, size_t); void *(*thd_calloc_func)(MYSQL_THD, size_t); char *(*thd_strdup_func)(MYSQL_THD, const char *); char *(*thd_strmake_func)(MYSQL_THD, const char *, size_t); void *(*thd_memdup_func)(MYSQL_THD, const void*, size_t); MYSQL_CONST_LEX_STRING *(*thd_make_lex_string_func)(MYSQL_THD, MYSQL_CONST_LEX_STRING *, const char *, size_t, int); } *thd_alloc_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_alloc(thd,size) (thd_alloc_service->thd_alloc_func((thd), (size))) #define thd_calloc(thd,size) (thd_alloc_service->thd_calloc_func((thd), (size))) #define thd_strdup(thd,str) (thd_alloc_service->thd_strdup_func((thd), (str))) #define thd_strmake(thd,str,size) \ (thd_alloc_service->thd_strmake_func((thd), (str), (size))) #define thd_memdup(thd,str,size) \ (thd_alloc_service->thd_memdup_func((thd), (str), (size))) #define thd_make_lex_string(thd, lex_str, str, size, allocate_lex_string) \ (thd_alloc_service->thd_make_lex_string_func((thd), (lex_str), (str), \ (size), (allocate_lex_string))) #else /** Allocate memory in the connection's local memory pool @details When properly used in place of @c my_malloc(), this can significantly improve concurrency. Don't use this or related functions to allocate large chunks of memory. Use for temporary storage only. The memory will be freed automatically at the end of the statement; no explicit code is required to prevent memory leaks. @see alloc_root() */ void *thd_alloc(MYSQL_THD thd, size_t size); /** @see thd_alloc() */ void *thd_calloc(MYSQL_THD thd, size_t size); /** @see thd_alloc() */ char *thd_strdup(MYSQL_THD thd, const char *str); /** @see thd_alloc() */ char *thd_strmake(MYSQL_THD thd, const char *str, size_t size); /** @see thd_alloc() */ void *thd_memdup(MYSQL_THD thd, const void* str, size_t size); /** Create a LEX_STRING in this connection's local memory pool @param thd user thread connection handle @param lex_str pointer to LEX_STRING object to be initialized @param str initializer to be copied into lex_str @param size length of str, in bytes @param allocate_lex_string flag: if TRUE, allocate new LEX_STRING object, instead of using lex_str value @return NULL on failure, or pointer to the LEX_STRING object @see thd_alloc() */ MYSQL_CONST_LEX_STRING *thd_make_lex_string(MYSQL_THD thd, MYSQL_CONST_LEX_STRING *lex_str, const char *str, size_t size, int allocate_lex_string); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_THD_ALLOC_INCLUDED #endif mysql/server/mysql/service_encryption.h000064400000013031151027430560014450 0ustar00#ifndef MYSQL_SERVICE_ENCRYPTION_INCLUDED /* Copyright (c) 2015, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file encryption service Functions to support data encryption and encryption key management. They are normally implemented in an encryption plugin, so this service connects encryption *consumers* (e.g. storage engines) to the encryption *provider* (encryption plugin). */ #ifndef MYSQL_ABI_CHECK #include #ifdef _WIN32 #ifndef __cplusplus #define inline __inline #endif #endif #endif #ifdef __cplusplus extern "C" { #endif /* returned from encryption_key_get_latest_version() */ #define ENCRYPTION_KEY_VERSION_INVALID (~(unsigned int)0) #define ENCRYPTION_KEY_NOT_ENCRYPTED (0) #define ENCRYPTION_KEY_SYSTEM_DATA 1 #define ENCRYPTION_KEY_TEMPORARY_DATA 2 /* returned from encryption_key_get() */ #define ENCRYPTION_KEY_BUFFER_TOO_SMALL (100) #define ENCRYPTION_FLAG_DECRYPT 0 #define ENCRYPTION_FLAG_ENCRYPT 1 #define ENCRYPTION_FLAG_NOPAD 2 struct encryption_service_st { unsigned int (*encryption_key_get_latest_version_func)(unsigned int key_id); unsigned int (*encryption_key_get_func)(unsigned int key_id, unsigned int key_version, unsigned char* buffer, unsigned int* length); unsigned int (*encryption_ctx_size_func)(unsigned int key_id, unsigned int key_version); int (*encryption_ctx_init_func)(void *ctx, const unsigned char* key, unsigned int klen, const unsigned char* iv, unsigned int ivlen, int flags, unsigned int key_id, unsigned int key_version); int (*encryption_ctx_update_func)(void *ctx, const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen); int (*encryption_ctx_finish_func)(void *ctx, unsigned char* dst, unsigned int* dlen); unsigned int (*encryption_encrypted_length_func)(unsigned int slen, unsigned int key_id, unsigned int key_version); }; #ifdef MYSQL_DYNAMIC_PLUGIN extern struct encryption_service_st *encryption_service; #define encryption_key_get_latest_version(KI) encryption_service->encryption_key_get_latest_version_func(KI) #define encryption_key_get(KI,KV,K,S) encryption_service->encryption_key_get_func((KI),(KV),(K),(S)) #define encryption_ctx_size(KI,KV) encryption_service->encryption_ctx_size_func((KI),(KV)) #define encryption_ctx_init(CTX,K,KL,IV,IVL,F,KI,KV) encryption_service->encryption_ctx_init_func((CTX),(K),(KL),(IV),(IVL),(F),(KI),(KV)) #define encryption_ctx_update(CTX,S,SL,D,DL) encryption_service->encryption_ctx_update_func((CTX),(S),(SL),(D),(DL)) #define encryption_ctx_finish(CTX,D,DL) encryption_service->encryption_ctx_finish_func((CTX),(D),(DL)) #define encryption_encrypted_length(SL,KI,KV) encryption_service->encryption_encrypted_length_func((SL),(KI),(KV)) #else extern struct encryption_service_st encryption_handler; #define encryption_key_get_latest_version(KI) encryption_handler.encryption_key_get_latest_version_func(KI) #define encryption_key_get(KI,KV,K,S) encryption_handler.encryption_key_get_func((KI),(KV),(K),(S)) #define encryption_ctx_size(KI,KV) encryption_handler.encryption_ctx_size_func((KI),(KV)) #define encryption_ctx_init(CTX,K,KL,IV,IVL,F,KI,KV) encryption_handler.encryption_ctx_init_func((CTX),(K),(KL),(IV),(IVL),(F),(KI),(KV)) #define encryption_ctx_update(CTX,S,SL,D,DL) encryption_handler.encryption_ctx_update_func((CTX),(S),(SL),(D),(DL)) #define encryption_ctx_finish(CTX,D,DL) encryption_handler.encryption_ctx_finish_func((CTX),(D),(DL)) #define encryption_encrypted_length(SL,KI,KV) encryption_handler.encryption_encrypted_length_func((SL),(KI),(KV)) #endif static inline unsigned int encryption_key_id_exists(unsigned int id) { return encryption_key_get_latest_version(id) != ENCRYPTION_KEY_VERSION_INVALID; } static inline unsigned int encryption_key_version_exists(unsigned int id, unsigned int version) { unsigned int unused; return encryption_key_get(id, version, NULL, &unused) != ENCRYPTION_KEY_VERSION_INVALID; } static inline int encryption_crypt(const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen, const unsigned char* key, unsigned int klen, const unsigned char* iv, unsigned int ivlen, int flags, unsigned int key_id, unsigned int key_version) { void *ctx= alloca(encryption_ctx_size(key_id, key_version)); int res1, res2; unsigned int d1, d2; if ((res1= encryption_ctx_init(ctx, key, klen, iv, ivlen, flags, key_id, key_version))) return res1; res1= encryption_ctx_update(ctx, src, slen, dst, &d1); res2= encryption_ctx_finish(ctx, dst + d1, &d2); *dlen= d1 + d2; return res1 ? res1 : res2; } #ifdef __cplusplus } #endif #define MYSQL_SERVICE_ENCRYPTION_INCLUDED #endif mysql/server/mysql/plugin_audit.h000064400000012641151027430560013230 0ustar00/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_audit_h #define _my_audit_h /************************************************************************* API for Audit plugin. (MYSQL_AUDIT_PLUGIN) */ #include "plugin.h" #ifdef __cplusplus extern "C" { #endif #define MYSQL_AUDIT_CLASS_MASK_SIZE 1 #define MYSQL_AUDIT_INTERFACE_VERSION 0x0302 /************************************************************************* AUDIT CLASS : GENERAL LOG events occurs before emitting to the general query log. ERROR events occur before transmitting errors to the user. RESULT events occur after transmitting a resultset to the user. STATUS events occur after transmitting a resultset or errors to the user. */ #define MYSQL_AUDIT_GENERAL_CLASS 0 #define MYSQL_AUDIT_GENERAL_CLASSMASK (1 << MYSQL_AUDIT_GENERAL_CLASS) #define MYSQL_AUDIT_GENERAL_LOG 0 #define MYSQL_AUDIT_GENERAL_ERROR 1 #define MYSQL_AUDIT_GENERAL_RESULT 2 #define MYSQL_AUDIT_GENERAL_STATUS 3 struct mysql_event_general { unsigned int event_subclass; int general_error_code; unsigned long general_thread_id; const char *general_user; unsigned int general_user_length; const char *general_command; unsigned int general_command_length; const char *general_query; unsigned int general_query_length; const struct charset_info_st *general_charset; unsigned long long general_time; unsigned long long general_rows; /* Added in version 0x302 */ unsigned long long query_id; MYSQL_CONST_LEX_STRING database; }; /* AUDIT CLASS : CONNECTION CONNECT occurs after authentication phase is completed. DISCONNECT occurs after connection is terminated. CHANGE_USER occurs after COM_CHANGE_USER RPC is completed. */ #define MYSQL_AUDIT_CONNECTION_CLASS 1 #define MYSQL_AUDIT_CONNECTION_CLASSMASK (1 << MYSQL_AUDIT_CONNECTION_CLASS) #define MYSQL_AUDIT_CONNECTION_CONNECT 0 #define MYSQL_AUDIT_CONNECTION_DISCONNECT 1 #define MYSQL_AUDIT_CONNECTION_CHANGE_USER 2 struct mysql_event_connection { unsigned int event_subclass; int status; unsigned long thread_id; const char *user; unsigned int user_length; const char *priv_user; unsigned int priv_user_length; const char *external_user; unsigned int external_user_length; const char *proxy_user; unsigned int proxy_user_length; const char *host; unsigned int host_length; const char *ip; unsigned int ip_length; MYSQL_CONST_LEX_STRING database; }; /* AUDIT CLASS : TABLE LOCK occurs when a connection "locks" (this does not necessarily mean a table lock and also happens for row-locking engines) the table at the beginning of a statement. This event is generated at the beginning of every statement for every affected table, unless there's a LOCK TABLES statement in effect (in which case it is generated once for LOCK TABLES and then is suppressed until the tables are unlocked). CREATE/DROP/RENAME occur when a table is created, dropped, or renamed. */ #define MYSQL_AUDIT_TABLE_CLASS 15 #define MYSQL_AUDIT_TABLE_CLASSMASK (1 << MYSQL_AUDIT_TABLE_CLASS) #define MYSQL_AUDIT_TABLE_LOCK 0 #define MYSQL_AUDIT_TABLE_CREATE 1 #define MYSQL_AUDIT_TABLE_DROP 2 #define MYSQL_AUDIT_TABLE_RENAME 3 #define MYSQL_AUDIT_TABLE_ALTER 4 struct mysql_event_table { unsigned int event_subclass; unsigned long thread_id; const char *user; const char *priv_user; const char *priv_host; const char *external_user; const char *proxy_user; const char *host; const char *ip; MYSQL_CONST_LEX_STRING database; MYSQL_CONST_LEX_STRING table; /* for MYSQL_AUDIT_TABLE_RENAME */ MYSQL_CONST_LEX_STRING new_database; MYSQL_CONST_LEX_STRING new_table; /* for MYSQL_AUDIT_TABLE_LOCK, true if read-only, false if read/write */ int read_only; /* Added in version 0x302 */ unsigned long long query_id; }; /************************************************************************* Here we define the descriptor structure, that is referred from st_mysql_plugin. release_thd() event occurs when the event class consumer is to be disassociated from the specified THD. This would typically occur before some operation which may require sleeping - such as when waiting for the next query from the client. event_notify() is invoked whenever an event occurs which is of any class for which the plugin has interest. The second argument indicates the specific event class and the third argument is data as required for that class. class_mask is an array of bits used to indicate what event classes that this plugin wants to receive. */ struct st_mysql_audit { int interface_version; void (*release_thd)(MYSQL_THD); void (*event_notify)(MYSQL_THD, unsigned int, const void *); unsigned long class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; }; #ifdef __cplusplus } #endif #endif mysql/server/mysql/service_print_check_msg.h000064400000003020151027430560015412 0ustar00/* Copyright (c) 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once /** @file include/mysql/service_print_check_msg.h This service provides functions to write messages for check or repair */ #ifdef __cplusplus extern "C" { #endif extern struct print_check_msg_service_st { void (*print_check_msg)(MYSQL_THD, const char *db_name, const char *table_name, const char *op, const char *msg_type, const char *message, my_bool print_to_log); } *print_check_msg_service; #ifdef MYSQL_DYNAMIC_PLUGIN # define print_check_msg_context(_THD) print_check_msg_service->print_check_msg #else extern void print_check_msg(MYSQL_THD, const char *db_name, const char *table_name, const char *op, const char *msg_type, const char *message, my_bool print_to_log); #endif #ifdef __cplusplus } #endif mysql/server/mysql/plugin_auth_common.h000064400000010635151027430560014434 0ustar00#ifndef MYSQL_PLUGIN_AUTH_COMMON_INCLUDED /* Copyright (C) 2010 Sergei Golubchik and Monty Program Ab Copyright (c) 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef _WIN32 #include #endif /** @file This file defines constants and data structures that are the same for both client- and server-side authentication plugins. */ #define MYSQL_PLUGIN_AUTH_COMMON_INCLUDED /** the max allowed length for a user name */ #define MYSQL_USERNAME_LENGTH 512 /** return values of the plugin authenticate_user() method. */ /** Authentication failed, plugin internal error. An error occurred in the authentication plugin itself. These errors are reported in table performance_schema.host_cache, column COUNT_AUTH_PLUGIN_ERRORS. */ #define CR_AUTH_PLUGIN_ERROR 3 /** Authentication failed, client server handshake. An error occurred during the client server handshake. These errors are reported in table performance_schema.host_cache, column COUNT_HANDSHAKE_ERRORS. */ #define CR_AUTH_HANDSHAKE 2 /** Authentication failed, user credentials. For example, wrong passwords. These errors are reported in table performance_schema.host_cache, column COUNT_AUTHENTICATION_ERRORS. */ #define CR_AUTH_USER_CREDENTIALS 1 /** Authentication failed. Additionally, all other CR_xxx values (libmysql error code) can be used too. The client plugin may set the error code and the error message directly in the MYSQL structure and return CR_ERROR. If a CR_xxx specific error code was returned, an error message in the MYSQL structure will be overwritten. If CR_ERROR is returned without setting the error in MYSQL, CR_UNKNOWN_ERROR will be user. */ #define CR_ERROR 0 /** Authentication (client part) was successful. It does not mean that the authentication as a whole was successful, usually it only means that the client was able to send the user name and the password to the server. If CR_OK is returned, the libmysql reads the next packet expecting it to be one of OK, ERROR, or CHANGE_PLUGIN packets. */ #define CR_OK -1 /** Authentication was successful. It means that the client has done its part successfully and also that a plugin has read the last packet (one of OK, ERROR, CHANGE_PLUGIN). In this case, libmysql will not read a packet from the server, but it will use the data at mysql->net.read_pos. A plugin may return this value if the number of roundtrips in the authentication protocol is not known in advance, and the client plugin needs to read one packet more to determine if the authentication is finished or not. */ #define CR_OK_HANDSHAKE_COMPLETE -2 typedef struct st_plugin_vio_info { enum { MYSQL_VIO_INVALID, MYSQL_VIO_TCP, MYSQL_VIO_SOCKET, MYSQL_VIO_PIPE, MYSQL_VIO_MEMORY } protocol; int socket; /**< it's set, if the protocol is SOCKET or TCP */ #ifdef _WIN32 HANDLE handle; /**< it's set, if the protocol is PIPE or MEMORY */ #endif } MYSQL_PLUGIN_VIO_INFO; /** Provides plugin access to communication channel */ typedef struct st_plugin_vio { /** Plugin provides a pointer reference and this function sets it to the contents of any incoming packet. Returns the packet length, or -1 if the plugin should terminate. */ int (*read_packet)(struct st_plugin_vio *vio, unsigned char **buf); /** Plugin provides a buffer with data and the length and this function sends it as a packet. Returns 0 on success, 1 on failure. */ int (*write_packet)(struct st_plugin_vio *vio, const unsigned char *packet, int packet_len); /** Fills in a st_plugin_vio_info structure, providing the information about the connection. */ void (*info)(struct st_plugin_vio *vio, struct st_plugin_vio_info *info); } MYSQL_PLUGIN_VIO; #endif mysql/server/mysql/service_my_snprintf.h000064400000007212151027430560014632 0ustar00#ifndef MYSQL_SERVICE_MY_SNPRINTF_INCLUDED /* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file my_snprintf service Portable and limited vsnprintf() implementation. This is a portable, limited vsnprintf() implementation, with some extra features. "Portable" means that it'll produce identical result on all platforms (for example, on Windows and Linux system printf %e formats the exponent differently, on different systems %p either prints leading 0x or not, %s may accept null pointer or crash on it). "Limited" means that it does not support all the C89 features. But it supports few extensions, not in any standard. my_vsnprintf(to, n, fmt, ap) @param[out] to A buffer to store the result in @param[in] n Store up to n-1 characters, followed by an end 0 @param[in] fmt printf-like format string @param[in] ap Arguments @return a number of bytes written to a buffer *excluding* terminating '\0' @post The syntax of a format string is generally the same: % where everything but the format is optional. Three one-character flags are recognized: '0' has the standard zero-padding semantics; '-' is parsed, but silently ignored; '`' (backtick) is only supported for strings (%s) and means that the string will be quoted according to MySQL identifier quoting rules. Both and can be specified as numbers or '*'. If an asterisk is used, an argument of type int is consumed. can be 'l', 'll', or 'z'. Supported formats are 's' (null pointer is accepted, printed as "(null)"), 'b' (extension, see below), 'c', 'd', 'i', 'u', 'x', 'o', 'X', 'p' (works as 0x%x), 'f', 'g', 'M' (extension, see below), 'T' (extension, see below). Standard syntax for positional arguments $n is supported. Extensions: Flag '`' (backtick): see above. Format 'b': binary buffer, prints exactly bytes from the argument, without stopping at '\0'. Format 'M': takes one integer, prints this integer, space, double quote error message, double quote. In other words printf("%M", n) === printf("%d \"%s\"", n, strerror(n)) Format 'T': takes string and print it like s but if the strints should be truncated puts "..." at the end. */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #include #endif extern struct my_snprintf_service_st { size_t (*my_snprintf_type)(char*, size_t, const char*, ...); size_t (*my_vsnprintf_type)(char *, size_t, const char*, va_list); } *my_snprintf_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_vsnprintf my_snprintf_service->my_vsnprintf_type #define my_snprintf my_snprintf_service->my_snprintf_type #else size_t my_snprintf(char* to, size_t n, const char* fmt, ...); size_t my_vsnprintf(char *to, size_t n, const char* fmt, va_list ap); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_MY_SNPRINTF_INCLUDED #endif mysql/server/mysql/service_sha1.h000064400000004162151027430560013117 0ustar00#ifndef MYSQL_SERVICE_SHA1_INCLUDED /* Copyright (c) 2013, 2014, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file my sha1 service Functions to calculate SHA1 hash from a memory buffer */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #endif #define MY_SHA1_HASH_SIZE 20 /* Hash size in bytes */ extern struct my_sha1_service_st { void (*my_sha1_type)(unsigned char*, const char*, size_t); void (*my_sha1_multi_type)(unsigned char*, ...); size_t (*my_sha1_context_size_type)(); void (*my_sha1_init_type)(void *); void (*my_sha1_input_type)(void *, const unsigned char *, size_t); void (*my_sha1_result_type)(void *, unsigned char *); } *my_sha1_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_sha1(A,B,C) my_sha1_service->my_sha1_type(A,B,C) #define my_sha1_multi my_sha1_service->my_sha1_multi_type #define my_sha1_context_size() my_sha1_service->my_sha1_context_size_type() #define my_sha1_init(A) my_sha1_service->my_sha1_init_type(A) #define my_sha1_input(A,B,C) my_sha1_service->my_sha1_input_type(A,B,C) #define my_sha1_result(A,B) my_sha1_service->my_sha1_result_type(A,B) #else void my_sha1(unsigned char*, const char*, size_t); void my_sha1_multi(unsigned char*, ...); size_t my_sha1_context_size(); void my_sha1_init(void *context); void my_sha1_input(void *context, const unsigned char *buf, size_t len); void my_sha1_result(void *context, unsigned char *digest); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_SHA1_INCLUDED #endif mysql/server/mysql/service_encryption_scheme.h000064400000013016151027430560015777 0ustar00#ifndef MYSQL_SERVICE_ENCRYPTION_SCHEME_INCLUDED /* Copyright (c) 2015, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file encryption scheme service A higher-level access to encryption service. This is a helper service that storage engines use to encrypt tables on disk. It requests keys from the plugin, generates temporary or local keys from the global (as returned by the plugin) keys, etc. To use the service: * st_encryption_scheme object is created per space. A "space" can be a table space in XtraDB/InnoDB, a file in Aria, etc. The whole space is encrypted with the one key id. * The service does not take the key and the IV as parameters for encryption or decryption. Instead it takes two 32-bit integers and one 64-bit integer (and requests the key from an encryption plugin, if needed). * The service requests the global key from the encryption plugin automatically as needed. Three last keys are cached in the st_encryption_scheme. Number of key requests (number of cache misses) are counted in st_encryption_scheme::keyserver_requests * If an st_encryption_scheme can be used concurrently by different threads, it needs to be able to lock itself when accessing the key cache. Set the st_encryption_scheme::locker appropriately. If non-zero, it will be invoked by encrypt/decrypt functions to lock and unlock the scheme when needed. * Implementation details (in particular, key derivation) are defined by the scheme type. Currently only schema type 1 is supported. In the schema type 1, every "space" (table space in XtraDB/InnoDB, file in Aria) is encrypted with a different space-local key: * Every space has a 16-byte unique identifier (typically it's generated randomly and stored in the space). The caller should put it into st_encryption_scheme::iv. * Space-local key is generated by encrypting this identifier with the global encryption key (of the given id and version) using AES_ECB. * Encryption/decryption parameters for a page are typically the 4-byte space id, 4-byte page position (offset, page number, etc), and the 8-byte LSN. This guarantees that they'll be different for any two pages (of the same or different tablespaces) and also that they'll change for the same page when it's modified. They don't need to be secret (they create the IV, not the encryption key). */ #ifdef __cplusplus extern "C" { #endif #define ENCRYPTION_SCHEME_KEY_INVALID -1 #define ENCRYPTION_SCHEME_BLOCK_LENGTH 16 struct st_encryption_scheme_key { unsigned int version; unsigned char key[ENCRYPTION_SCHEME_BLOCK_LENGTH]; }; struct st_encryption_scheme { unsigned char iv[ENCRYPTION_SCHEME_BLOCK_LENGTH]; struct st_encryption_scheme_key key[3]; unsigned int keyserver_requests; unsigned int key_id; unsigned int type; void (*locker)(struct st_encryption_scheme *self, int release); }; extern struct encryption_scheme_service_st { int (*encryption_scheme_encrypt_func) (const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen, struct st_encryption_scheme *scheme, unsigned int key_version, unsigned int i32_1, unsigned int i32_2, unsigned long long i64); int (*encryption_scheme_decrypt_func) (const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen, struct st_encryption_scheme *scheme, unsigned int key_version, unsigned int i32_1, unsigned int i32_2, unsigned long long i64); } *encryption_scheme_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define encryption_scheme_encrypt(S,SL,D,DL,SCH,KV,I32,J32,I64) encryption_scheme_service->encryption_scheme_encrypt_func(S,SL,D,DL,SCH,KV,I32,J32,I64) #define encryption_scheme_decrypt(S,SL,D,DL,SCH,KV,I32,J32,I64) encryption_scheme_service->encryption_scheme_decrypt_func(S,SL,D,DL,SCH,KV,I32,J32,I64) #else int encryption_scheme_encrypt(const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen, struct st_encryption_scheme *scheme, unsigned int key_version, unsigned int i32_1, unsigned int i32_2, unsigned long long i64); int encryption_scheme_decrypt(const unsigned char* src, unsigned int slen, unsigned char* dst, unsigned int* dlen, struct st_encryption_scheme *scheme, unsigned int key_version, unsigned int i32_1, unsigned int i32_2, unsigned long long i64); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_ENCRYPTION_SCHEME_INCLUDED #endif mysql/server/mysql/service_json.h000064400000010707151027430560013236 0ustar00/* Copyright (C) 2018 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #ifndef MYSQL_SERVICE_JSON #define MYSQL_SERVICE_JSON /** @file json service Exports JSON parsing methods for plugins to use. Functions of the service: json_type - returns the type of the JSON argument, and the parsed value if it's scalar (not object or array) json_get_array_item - expects JSON array as an argument, and returns the type of the element at index `n_item`. Returns JSV_NOTHING type if the array is shorter than n_item and the actual length of the array in value_len. If successful, then `value` up till `value[value_len]` contains the array element at the desired index (n_item). json_get_object_key - expects JSON object as an argument, searches for a key in the object, return it's type and stores its value in `value`. JSV_NOTHING if no such key found, the number of keys in v_len. json_get_object_nkey - expects JSON object as an argument. finds n_key's key in the object, returns it's name, type and value. JSV_NOTHING if object has less keys than n_key. */ #ifdef __cplusplus extern "C" { #endif enum json_types { JSV_BAD_JSON=-1, JSV_NOTHING=0, JSV_OBJECT=1, JSV_ARRAY=2, JSV_STRING=3, JSV_NUMBER=4, JSV_TRUE=5, JSV_FALSE=6, JSV_NULL=7 }; extern struct json_service_st { enum json_types (*json_type)(const char *js, const char *js_end, const char **value, int *value_len); enum json_types (*json_get_array_item)(const char *js, const char *js_end, int n_item, const char **value, int *value_len); enum json_types (*json_get_object_key)(const char *js, const char *js_end, const char *key, const char **value, int *value_len); enum json_types (*json_get_object_nkey)(const char *js,const char *js_end, int nkey, const char **keyname, const char **keyname_end, const char **value, int *value_len); int (*json_escape_string)(const char *str,const char *str_end, char *json, char *json_end); int (*json_unescape_json)(const char *json_str, const char *json_end, char *res, char *res_end); } *json_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define json_type json_service->json_type #define json_get_array_item json_service->json_get_array_item #define json_get_object_key json_service->json_get_object_key #define json_get_object_nkey json_service->json_get_object_nkey #define json_escape_string json_service->json_escape_string #define json_unescape_json json_service->json_unescape_json #else enum json_types json_type(const char *js, const char *js_end, const char **value, int *value_len); enum json_types json_get_array_item(const char *js, const char *js_end, int n_item, const char **value, int *value_len); enum json_types json_get_object_key(const char *js, const char *js_end, const char *key, const char **value, int *value_len); enum json_types json_get_object_nkey(const char *js,const char *js_end, int nkey, const char **keyname, const char **keyname_end, const char **value, int *value_len); int json_escape_string(const char *str,const char *str_end, char *json, char *json_end); int json_unescape_json(const char *json_str, const char *json_end, char *res, char *res_end); #endif /*MYSQL_DYNAMIC_PLUGIN*/ #ifdef __cplusplus } #endif #endif /*MYSQL_SERVICE_JSON */ mysql/server/mysql/service_thd_specifics.h000064400000007146151027430560015077 0ustar00#ifndef MYSQL_SERVICE_THD_SPECIFICS_INCLUDED /* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file THD specific for plugin(s) This API provides pthread_getspecific like functionality to plugin authors. This is a functional alternative to the declarative MYSQL_THDVAR A plugin should at init call thd_key_create that create a key that will have storage in each THD. The key should be used by all threads and can be used concurrently from all threads. A plugin should at deinit call thd_key_delete. Alternatively, a plugin can use thd_key_create_from_var(K,V) to create a key that corresponds to a named MYSQL_THDVAR variable. This API is also safe when using pool-of-threads in which case pthread_getspecific is not, because the actual OS thread may change. @note Normally one should prefer MYSQL_THDVAR declarative API. The benefits are: - It supports typed variables (int, char*, enum, etc), not only void*. - The memory allocated for MYSQL_THDVAR is free'd automatically (if PLUGIN_VAR_MEMALLOC is specified). - Continuous loading and unloading of the same plugin does not allocate memory for same variables over and over again. An example of using MYSQL_THDVAR for a thd local storage: MYSQL_THDVAR_STR(my_tls, PLUGIN_VAR_MEMALLOC | PLUGIN_VAR_NOSYSVAR | PLUGIN_VAR_NOCMDOPT, "thd local storage example", 0, 0, 0); */ #ifdef __cplusplus extern "C" { #endif typedef int MYSQL_THD_KEY_T; extern struct thd_specifics_service_st { int (*thd_key_create_func)(MYSQL_THD_KEY_T *key); void (*thd_key_delete_func)(MYSQL_THD_KEY_T *key); void *(*thd_getspecific_func)(MYSQL_THD thd, MYSQL_THD_KEY_T key); int (*thd_setspecific_func)(MYSQL_THD thd, MYSQL_THD_KEY_T key, void *value); } *thd_specifics_service; #define thd_key_create_from_var(K, V) do { *(K)= MYSQL_SYSVAR_NAME(V).offset; } while(0) #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_key_create(K) (thd_specifics_service->thd_key_create_func(K)) #define thd_key_delete(K) (thd_specifics_service->thd_key_delete_func(K)) #define thd_getspecific(T, K) (thd_specifics_service->thd_getspecific_func(T, K)) #define thd_setspecific(T, K, V) (thd_specifics_service->thd_setspecific_func(T, K, V)) #else /** * create THD specific storage * @return 0 on success * else errno is returned */ int thd_key_create(MYSQL_THD_KEY_T *key); /** * delete THD specific storage */ void thd_key_delete(MYSQL_THD_KEY_T *key); /** * get/set thd specific storage * - first time this is called from a thread it will return 0 * - this call is thread-safe in that different threads may call this * simultaneously if operating on different THDs. * - this call acquires no mutexes and is implemented as an array lookup */ void* thd_getspecific(MYSQL_THD thd, MYSQL_THD_KEY_T key); int thd_setspecific(MYSQL_THD thd, MYSQL_THD_KEY_T key, void *value); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_THD_SPECIFICS_INCLUDED #endif mysql/server/mysql/service_base64.h000064400000005564151027430560013356 0ustar00#ifndef MYSQL_SERVICE_BASE64_INCLUDED /* Copyright (c) 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file my base64 service Functions for base64 en- and decoding */ #ifdef __cplusplus extern "C" { #endif #ifndef MYSQL_ABI_CHECK #include #endif /* Allow multiple chunks 'AAA= AA== AA==', binlog uses this */ #define MY_BASE64_DECODE_ALLOW_MULTIPLE_CHUNKS 1 extern struct base64_service_st { int (*base64_needed_encoded_length_ptr)(int length_of_data); int (*base64_encode_max_arg_length_ptr)(void); int (*base64_needed_decoded_length_ptr)(int length_of_encoded_data); int (*base64_decode_max_arg_length_ptr)(); int (*base64_encode_ptr)(const void *src, size_t src_len, char *dst); int (*base64_decode_ptr)(const char *src, size_t src_len, void *dst, const char **end_ptr, int flags); } *base64_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define my_base64_needed_encoded_length(A) base64_service->base64_needed_encoded_length_ptr(A) #define my_base64_encode_max_arg_length() base64_service->base64_encode_max_arg_length_ptr() #define my_base64_needed_decoded_length(A) base64_service->base64_needed_decoded_length_ptr(A) #define my_base64_decode_max_arg_length() base64_service->base64_decode_max_arg_length_ptr() #define my_base64_encode(A,B,C) base64_service->base64_encode_ptr(A,B,C) #define my_base64_decode(A,B,C,D,E) base64_service->base64_decode_ptr(A,B,C,D,E) #else /* Calculate how much memory needed for dst of my_base64_encode() */ int my_base64_needed_encoded_length(int length_of_data); /* Maximum length my_base64_encode_needed_length() can accept with no overflow. */ int my_base64_encode_max_arg_length(void); /* Calculate how much memory needed for dst of my_base64_decode() */ int my_base64_needed_decoded_length(int length_of_encoded_data); /* Maximum length my_base64_decode_needed_length() can accept with no overflow. */ int my_base64_decode_max_arg_length(); /* Encode data as a my_base64 string */ int my_base64_encode(const void *src, size_t src_len, char *dst); /* Decode a my_base64 string into data */ int my_base64_decode(const char *src, size_t src_len, void *dst, const char **end_ptr, int flags); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_BASE64_INCLUDED #endif mysql/server/mysql/service_thd_autoinc.h000064400000003234151027430560014563 0ustar00#ifndef MYSQL_SERVICE_THD_AUTOINC_INCLUDED /* Copyright (C) 2013 MariaDB Foundation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This service provides access to the auto_increment related system variables: @@auto_increment_offset @@auto_increment_increment */ #ifdef __cplusplus extern "C" { #endif extern struct thd_autoinc_service_st { void (*thd_get_autoinc_func)(const MYSQL_THD thd, unsigned long* off, unsigned long* inc); } *thd_autoinc_service; #ifdef MYSQL_DYNAMIC_PLUGIN #define thd_get_autoinc(thd, off, inc) \ (thd_autoinc_service->thd_get_autoinc_func((thd), (off), (inc))) #else /** Return autoincrement system variables @param IN thd user thread connection handle @param OUT off the value of @@SESSION.auto_increment_offset @param OUT inc the value of @@SESSION.auto_increment_increment */ void thd_get_autoinc(const MYSQL_THD thd, unsigned long* off, unsigned long* inc); #endif #ifdef __cplusplus } #endif #define MYSQL_SERVICE_THD_AUTOINC_INCLUDED #endif mysql/server/my_config.h000064400000034353151027430560011355 0ustar00/* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_CONFIG_H #define MY_CONFIG_H #define DOT_FRM_VERSION 6 /* Headers we may want to use. */ #define STDC_HEADERS 1 #define _GNU_SOURCE 1 #define HAVE_ALLOCA_H 1 #define HAVE_ARPA_INET_H 1 #define HAVE_ASM_TERMBITS_H 1 #define HAVE_CRYPT_H 1 #define HAVE_CURSES_H 1 /* #undef HAVE_BFD_H */ /* #undef HAVE_NDIR_H */ #define HAVE_DIRENT_H 1 #define HAVE_DLFCN_H 1 #define HAVE_EXECINFO_H 1 #define HAVE_FCNTL_H 1 #define HAVE_FCNTL_DIRECT 1 #define HAVE_FENV_H 1 #define HAVE_FLOAT_H 1 #define HAVE_FNMATCH_H 1 #define HAVE_FPU_CONTROL_H 1 #define HAVE_GETMNTENT 1 /* #undef HAVE_GETMNTENT_IN_SYS_MNTAB */ /* #undef HAVE_GETMNTINFO */ /* #undef HAVE_GETMNTINFO64 */ /* #undef HAVE_GETMNTINFO_TAKES_statvfs */ #define HAVE_GRP_H 1 /* #undef HAVE_IA64INTRIN_H */ /* #undef HAVE_IEEEFP_H */ #define HAVE_INTTYPES_H 1 /* #undef HAVE_KQUEUE */ #define HAVE_LIMITS_H 1 #define HAVE_LINK_H 1 #define HAVE_LINUX_UNISTD_H 1 #define HAVE_LINUX_MMAN_H 1 #define HAVE_LOCALE_H 1 #define HAVE_MALLOC_H 1 #define HAVE_MEMORY_H 1 #define HAVE_NETINET_IN_H 1 #define HAVE_PATHS_H 1 #define HAVE_POLL_H 1 #define HAVE_PWD_H 1 #define HAVE_SCHED_H 1 /* #undef HAVE_SELECT_H */ /* #undef HAVE_SOLARIS_LARGE_PAGES */ #define HAVE_STDDEF_H 1 #define HAVE_STDLIB_H 1 #define HAVE_STDARG_H 1 #define HAVE_STRINGS_H 1 #define HAVE_STRING_H 1 #define HAVE_STDINT_H 1 /* #undef HAVE_SYNCH_H */ /* #undef HAVE_SYSENT_H */ #define HAVE_SYS_DIR_H 1 #define HAVE_SYS_FILE_H 1 /* #undef HAVE_SYS_FPU_H */ #define HAVE_SYS_IOCTL_H 1 /* #undef HAVE_SYS_MALLOC_H */ #define HAVE_SYS_MMAN_H 1 /* #undef HAVE_SYS_MNTENT_H */ /* #undef HAVE_SYS_NDIR_H */ /* #undef HAVE_SYS_PTE_H */ /* #undef HAVE_SYS_PTEM_H */ #define HAVE_SYS_PRCTL_H 1 #define HAVE_SYS_RESOURCE_H 1 #define HAVE_SYS_SELECT_H 1 #define HAVE_SYS_SOCKET_H 1 /* #undef HAVE_SYS_SOCKIO_H */ #define HAVE_SYS_UTSNAME_H 1 #define HAVE_SYS_STAT_H 1 /* #undef HAVE_SYS_STREAM_H */ #define HAVE_SYS_SYSCALL_H 1 #define HAVE_SYS_TIMEB_H 1 #define HAVE_SYS_TIMES_H 1 #define HAVE_SYS_TIME_H 1 #define HAVE_SYS_TYPES_H 1 #define HAVE_SYS_UN_H 1 /* #undef HAVE_SYS_VADVISE_H */ #define HAVE_SYS_STATVFS_H 1 #define HAVE_UCONTEXT_H 1 #define HAVE_TERM_H 1 /* #undef HAVE_TERMBITS_H */ #define HAVE_TERMIOS_H 1 #define HAVE_TERMIO_H 1 #define HAVE_TERMCAP_H 1 #define HAVE_TIME_H 1 #define HAVE_UNISTD_H 1 #define HAVE_UTIME_H 1 /* #undef HAVE_VARARGS_H */ /* #undef HAVE_SYS_UTIME_H */ #define HAVE_SYS_WAIT_H 1 #define HAVE_SYS_PARAM_H 1 /* Libraries */ /* #undef HAVE_LIBWRAP */ #define HAVE_SYSTEMD 1 #define HAVE_SYSTEMD_SD_LISTEN_FDS_WITH_NAMES 1 /* Does "struct timespec" have a "sec" and "nsec" field? */ /* #undef HAVE_TIMESPEC_TS_SEC */ /* Readline */ /* #undef HAVE_HIST_ENTRY */ /* #undef USE_LIBEDIT_INTERFACE */ #define USE_NEW_READLINE_INTERFACE 1 #define FIONREAD_IN_SYS_IOCTL 1 #define GWINSZ_IN_SYS_IOCTL 1 /* #undef TIOCSTAT_IN_SYS_IOCTL */ /* #undef FIONREAD_IN_SYS_FILIO */ /* Functions we may want to use. */ #define HAVE_ACCEPT4 1 #define HAVE_ACCESS 1 #define HAVE_ALARM 1 #define HAVE_ALLOCA 1 /* #undef HAVE_BFILL */ #define HAVE_INDEX 1 #define HAVE_CLOCK_GETTIME 1 #define HAVE_CRYPT 1 #define HAVE_CUSERID 1 #define HAVE_DLADDR 1 #define HAVE_DLERROR 1 #define HAVE_DLOPEN 1 #define HAVE_FCHMOD 1 #define HAVE_FCNTL 1 #define HAVE_FDATASYNC 1 #define HAVE_DECL_FDATASYNC 1 #define HAVE_FEDISABLEEXCEPT 1 #define HAVE_FESETROUND 1 /* #undef HAVE_FP_EXCEPT */ #define HAVE_FSEEKO 1 #define HAVE_FSYNC 1 #define HAVE_FTIME 1 #define HAVE_GETIFADDRS 1 #define HAVE_GETCWD 1 #define HAVE_GETHOSTBYADDR_R 1 /* #undef HAVE_GETHRTIME */ #define HAVE_GETPAGESIZE 1 /* #undef HAVE_GETPAGESIZES */ #define HAVE_GETPASS 1 /* #undef HAVE_GETPASSPHRASE */ #define HAVE_GETPWNAM 1 #define HAVE_GETPWUID 1 #define HAVE_GETRLIMIT 1 #define HAVE_GETRUSAGE 1 #define HAVE_GETTIMEOFDAY 1 #define HAVE_GETWD 1 #define HAVE_GMTIME_R 1 /* #undef gmtime_r */ #define HAVE_IN_ADDR_T 1 #define HAVE_INITGROUPS 1 #define HAVE_LDIV 1 #define HAVE_LRAND48 1 #define HAVE_LOCALTIME_R 1 #define HAVE_LSTAT 1 /* #define HAVE_MLOCK 1 see Bug#54662 */ #define HAVE_NL_LANGINFO 1 #define HAVE_MADVISE 1 #define HAVE_DECL_MADVISE 1 /* #undef HAVE_DECL_MHA_MAPSIZE_VA */ #define HAVE_MALLINFO 1 /* #undef HAVE_MALLINFO2 */ /* #undef HAVE_MALLOC_ZONE */ #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MKSTEMP 1 #define HAVE_MKOSTEMP 1 #define HAVE_MLOCKALL 1 #define HAVE_MMAP 1 #define HAVE_MMAP64 1 #define HAVE_PERROR 1 #define HAVE_POLL 1 #define HAVE_POSIX_FALLOCATE 1 #define HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE 1 #define HAVE_PREAD 1 /* #undef HAVE_READ_REAL_TIME */ /* #undef HAVE_PTHREAD_ATTR_CREATE */ #define HAVE_PTHREAD_ATTR_GETGUARDSIZE 1 #define HAVE_PTHREAD_ATTR_GETSTACKSIZE 1 #define HAVE_PTHREAD_ATTR_SETSCOPE 1 #define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1 #define HAVE_PTHREAD_GETATTR_NP 1 /* #undef HAVE_PTHREAD_CONDATTR_CREATE */ #define HAVE_PTHREAD_GETAFFINITY_NP 1 #define HAVE_PTHREAD_KEY_DELETE 1 /* #undef HAVE_PTHREAD_KILL */ #define HAVE_PTHREAD_RWLOCK_RDLOCK 1 #define HAVE_PTHREAD_SIGMASK 1 /* #undef HAVE_PTHREAD_YIELD_NP */ #define HAVE_PTHREAD_YIELD_ZERO_ARG 1 #define PTHREAD_ONCE_INITIALIZER PTHREAD_ONCE_INIT #define HAVE_PUTENV 1 /* #undef HAVE_READDIR_R */ #define HAVE_READLINK 1 #define HAVE_REALPATH 1 #define HAVE_RENAME 1 /* #undef HAVE_RWLOCK_INIT */ #define HAVE_SCHED_YIELD 1 #define HAVE_SELECT 1 #define HAVE_SETENV 1 #define HAVE_SETLOCALE 1 #define HAVE_SETMNTENT 1 #define HAVE_SETUPTERM 1 #define HAVE_SIGSET 1 #define HAVE_SIGACTION 1 /* #undef HAVE_SIGTHREADMASK */ #define HAVE_SIGWAIT 1 #define HAVE_SIGWAITINFO 1 #define HAVE_SLEEP 1 #define HAVE_STPCPY 1 #define HAVE_STRERROR 1 #define HAVE_STRCOLL 1 #define HAVE_STRNLEN 1 #define HAVE_STRPBRK 1 #define HAVE_STRTOK_R 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOULL 1 /* #undef HAVE_TELL */ /* #undef HAVE_THR_YIELD */ #define HAVE_TIME 1 #define HAVE_TIMES 1 #define HAVE_VIDATTR 1 #define HAVE_VIO_READ_BUFF 1 #define HAVE_VASPRINTF 1 #define HAVE_VSNPRINTF 1 #define HAVE_FTRUNCATE 1 #define HAVE_TZNAME 1 /* Symbols we may use */ /* #undef HAVE_SYS_ERRLIST */ /* used by stacktrace functions */ #define HAVE_BACKTRACE 1 #define HAVE_BACKTRACE_SYMBOLS 1 #define HAVE_BACKTRACE_SYMBOLS_FD 1 /* #undef HAVE_PRINTSTACK */ #define HAVE_IPV6 1 /* #undef ss_family */ /* #undef HAVE_SOCKADDR_IN_SIN_LEN */ /* #undef HAVE_SOCKADDR_IN6_SIN6_LEN */ #define STRUCT_TIMESPEC_HAS_TV_SEC 1 #define STRUCT_TIMESPEC_HAS_TV_NSEC 1 /* this means that valgrind headers and macros are available */ #define HAVE_VALGRIND_MEMCHECK_H 1 /* this means WITH_VALGRIND - we change some code paths for valgrind */ /* #undef HAVE_valgrind */ /* Types we may use */ #ifdef __APPLE__ /* Special handling required for OSX to support universal binaries that mix 32 and 64 bit architectures. */ #if(__LP64__) #define SIZEOF_LONG 8 #else #define SIZEOF_LONG 4 #endif #define SIZEOF_VOIDP SIZEOF_LONG #define SIZEOF_CHARP SIZEOF_LONG #define SIZEOF_SIZE_T SIZEOF_LONG #else /* No indentation, to fetch the lines from verification scripts */ #define SIZEOF_LONG 8 #define SIZEOF_VOIDP 8 #define SIZEOF_CHARP 8 #define SIZEOF_SIZE_T 8 #endif #define HAVE_LONG 1 #define HAVE_CHARP 1 #define SIZEOF_INT 4 #define HAVE_INT 1 #define SIZEOF_LONG_LONG 8 #define HAVE_LONG_LONG 1 #define SIZEOF_OFF_T 8 #define HAVE_OFF_T 1 /* #undef SIZEOF_UCHAR */ /* #undef HAVE_UCHAR */ #define SIZEOF_UINT 4 #define HAVE_UINT 1 #define SIZEOF_ULONG 8 #define HAVE_ULONG 1 /* #undef SIZEOF_INT8 */ /* #undef HAVE_INT8 */ /* #undef SIZEOF_UINT8 */ /* #undef HAVE_UINT8 */ /* #undef SIZEOF_INT16 */ /* #undef HAVE_INT16 */ /* #undef SIZEOF_UINT16 */ /* #undef HAVE_UINT16 */ /* #undef SIZEOF_INT32 */ /* #undef HAVE_INT32 */ /* #undef SIZEOF_UINT32 */ /* #undef HAVE_UINT32 */ /* #undef SIZEOF_INT64 */ /* #undef HAVE_INT64 */ /* #undef SIZEOF_UINT64 */ /* #undef HAVE_UINT64 */ #define SOCKET_SIZE_TYPE socklen_t #define HAVE_MBSTATE_T 1 #define MAX_INDEXES 64 #define QSORT_TYPE_IS_VOID 1 #define RETQSORTTYPE void #define RETSIGTYPE void #define VOID_SIGHANDLER 1 #define HAVE_SIGHANDLER_T 1 #define STRUCT_RLIMIT struct rlimit #ifdef __APPLE__ #if __BIG_ENDIAN #define WORDS_BIGENDIAN 1 #endif #else /* #undef WORDS_BIGENDIAN */ #endif /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #define C_HAS_inline 1 #if !(C_HAS_inline) #ifndef __cplusplus # define inline #endif #endif #define TARGET_OS_LINUX 1 #define HAVE_WCTYPE_H 1 #define HAVE_WCHAR_H 1 #define HAVE_LANGINFO_H 1 #define HAVE_MBRLEN 1 #define HAVE_MBSRTOWCS 1 #define HAVE_MBRTOWC 1 #define HAVE_WCWIDTH 1 #define HAVE_ISWLOWER 1 #define HAVE_ISWUPPER 1 #define HAVE_TOWLOWER 1 #define HAVE_TOWUPPER 1 #define HAVE_ISWCTYPE 1 #define HAVE_WCHAR_T 1 #define HAVE_STRCASECMP 1 #define HAVE_TCGETATTR 1 #define HAVE_WEAK_SYMBOL 1 #define HAVE_ABI_CXA_DEMANGLE 1 #define HAVE_ATTRIBUTE_CLEANUP 1 #define HAVE_POSIX_SIGNALS 1 /* #undef HAVE_BSD_SIGNALS */ /* #undef HAVE_SVR3_SIGNALS */ /* #undef HAVE_V7_SIGNALS */ #define HAVE_ERR_remove_thread_state 1 #define HAVE_X509_check_host 1 /* #undef HAVE_SOLARIS_STYLE_GETHOST */ #define HAVE_GCC_C11_ATOMICS 1 /* #undef HAVE_SOLARIS_ATOMIC */ /* #undef NO_FCNTL_NONBLOCK */ #define NO_ALARM 1 /* #undef _LARGE_FILES */ #define _LARGEFILE_SOURCE 1 /* #undef _LARGEFILE64_SOURCE */ #define TIME_WITH_SYS_TIME 1 #define STACK_DIRECTION -1 #define SYSTEM_TYPE "Linux" #define MACHINE_TYPE "x86_64" #define DEFAULT_MACHINE "x86_64" #define HAVE_DTRACE 1 #define SIGNAL_WITH_VIO_CLOSE 1 /* Windows stuff, mostly functions, that have Posix analogs but named differently */ /* #undef S_IROTH */ /* #undef S_IFIFO */ /* #undef IPPROTO_IPV6 */ /* #undef IPV6_V6ONLY */ /* #undef sigset_t */ /* #undef mode_t */ /* #undef SIGQUIT */ /* #undef SIGPIPE */ /* #undef popen */ /* #undef pclose */ /* #undef ssize_t */ /* #undef strcasecmp */ /* #undef strncasecmp */ /* #undef snprintf */ /* #undef strtok_r */ /* #undef strtoll */ /* #undef strtoull */ /* #undef vsnprintf */ #if defined(_MSC_VER) && (_MSC_VER > 1800) #define tzname _tzname #define P_tmpdir "C:\\TEMP" #endif #if defined(_MSC_VER) && (_MSC_VER > 1310) # define HAVE_SETENV #define setenv(a,b,c) _putenv_s(a,b) #endif #define PSAPI_VERSION 1 /* for GetProcessMemoryInfo() */ /* We don't want the min/max macros */ #ifdef _WIN32 #define NOMINMAX 1 #endif /* MySQL features */ #define LOCAL_INFILE_MODE_OFF 0 #define LOCAL_INFILE_MODE_ON 1 #define LOCAL_INFILE_MODE_AUTO 2 #define ENABLED_LOCAL_INFILE LOCAL_INFILE_MODE_AUTO #define ENABLED_PROFILING 1 /* #undef EXTRA_DEBUG */ /* #undef USE_SYMDIR */ /* Character sets and collations */ #define MYSQL_DEFAULT_CHARSET_NAME "latin1" #define MYSQL_DEFAULT_COLLATION_NAME "latin1_swedish_ci" #define USE_MB #define USE_MB_IDENT /* This should mean case insensitive file system */ /* #undef FN_NO_CASE_SENSE */ #define HAVE_CHARSET_armscii8 1 #define HAVE_CHARSET_ascii 1 #define HAVE_CHARSET_big5 1 #define HAVE_CHARSET_cp1250 1 #define HAVE_CHARSET_cp1251 1 #define HAVE_CHARSET_cp1256 1 #define HAVE_CHARSET_cp1257 1 #define HAVE_CHARSET_cp850 1 #define HAVE_CHARSET_cp852 1 #define HAVE_CHARSET_cp866 1 #define HAVE_CHARSET_cp932 1 #define HAVE_CHARSET_dec8 1 #define HAVE_CHARSET_eucjpms 1 #define HAVE_CHARSET_euckr 1 #define HAVE_CHARSET_gb2312 1 #define HAVE_CHARSET_gbk 1 #define HAVE_CHARSET_geostd8 1 #define HAVE_CHARSET_greek 1 #define HAVE_CHARSET_hebrew 1 #define HAVE_CHARSET_hp8 1 #define HAVE_CHARSET_keybcs2 1 #define HAVE_CHARSET_koi8r 1 #define HAVE_CHARSET_koi8u 1 #define HAVE_CHARSET_latin1 1 #define HAVE_CHARSET_latin2 1 #define HAVE_CHARSET_latin5 1 #define HAVE_CHARSET_latin7 1 #define HAVE_CHARSET_macce 1 #define HAVE_CHARSET_macroman 1 #define HAVE_CHARSET_sjis 1 #define HAVE_CHARSET_swe7 1 #define HAVE_CHARSET_tis620 1 #define HAVE_CHARSET_ucs2 1 #define HAVE_CHARSET_ujis 1 #define HAVE_CHARSET_utf8mb4 1 #define HAVE_CHARSET_utf8mb3 1 #define HAVE_CHARSET_utf16 1 #define HAVE_CHARSET_utf32 1 #define HAVE_UCA_COLLATIONS 1 #define HAVE_COMPRESS 1 #define HAVE_EncryptAes128Ctr 1 #define HAVE_EncryptAes128Gcm 1 #define HAVE_des 1 /* Stuff that always need to be defined (compile breaks without it) */ #define HAVE_SPATIAL 1 #define HAVE_RTREE_KEYS 1 #define HAVE_QUERY_CACHE 1 #define BIG_TABLES 1 /* Important storage engines (those that really need define WITH__STORAGE_ENGINE for the whole server) */ #define WITH_INNOBASE_STORAGE_ENGINE 1 #define WITH_PARTITION_STORAGE_ENGINE 1 #define WITH_PERFSCHEMA_STORAGE_ENGINE 1 #define WITH_ARIA_STORAGE_ENGINE 1 #define USE_ARIA_FOR_TMP_TABLES 1 #define DEFAULT_MYSQL_HOME "/usr" #define SHAREDIR "/usr/share/mysql" #define DEFAULT_BASEDIR "/usr" #define MYSQL_DATADIR "/var/lib/mysql" #define DEFAULT_CHARSET_HOME "/usr" #define PLUGINDIR "/usr/lib64/mysql/plugin" #define DEFAULT_SYSCONFDIR "/etc" #define DEFAULT_TMPDIR P_tmpdir /* #undef SO_EXT */ #define MYSQL_VERSION_MAJOR 10 #define MYSQL_VERSION_MINOR 6 #define MYSQL_VERSION_PATCH 23 #define MYSQL_VERSION_EXTRA "" #define PACKAGE "mysql" #define PACKAGE_BUGREPORT "" #define PACKAGE_NAME "MySQL Server" #define PACKAGE_STRING "MySQL Server 10.6.23" #define PACKAGE_TARNAME "mysql" #define PACKAGE_VERSION "10.6.23" #define VERSION "10.6.23" #define PROTOCOL_VERSION 10 #define PCRE2_CODE_UNIT_WIDTH 8 #define MALLOC_LIBRARY "system" /* time_t related defines */ #define SIZEOF_TIME_T 8 /* #undef TIME_T_UNSIGNED */ #ifndef EMBEDDED_LIBRARY /* #undef WSREP_INTERFACE_VERSION */ #define WITH_WSREP 1 #define WSREP_PROC_INFO 1 #endif #if !defined(__STDC_FORMAT_MACROS) #define __STDC_FORMAT_MACROS #endif // !defined(__STDC_FORMAT_MACROS) #endif #define HAVE_VFORK 1 mysql/server/byte_order_generic_x86_64.h000064400000010041151027430560014237 0ustar00/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Optimized function-like macros for the x86 architecture (_WIN32 included). */ #define sint2korr(A) (int16) (*((int16 *) (A))) #define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ (((uint32) 255L << 24) | \ (((uint32) (uchar) (A)[2]) << 16) |\ (((uint32) (uchar) (A)[1]) << 8) | \ ((uint32) (uchar) (A)[0])) : \ (((uint32) (uchar) (A)[2]) << 16) |\ (((uint32) (uchar) (A)[1]) << 8) | \ ((uint32) (uchar) (A)[0]))) #define sint4korr(A) (int32) (*((int32 *) (A))) #define uint2korr(A) (uint16) (*((uint16 *) (A))) #define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16)) #define uint4korr(A) (uint32) (*((uint32 *) (A))) static inline ulonglong uint5korr(const void *p) { ulonglong a= *(uint32 *) p; ulonglong b= *(4 + (uchar *) p); return a | (b << 32); } static inline ulonglong uint6korr(const void *p) { ulonglong a= *(uint32 *) p; ulonglong b= *(uint16 *) (4 + (char *) p); return a | (b << 32); } #define uint8korr(A) (ulonglong) (*((ulonglong *) (A))) #define sint8korr(A) (longlong) (*((longlong *) (A))) #define int2store(T,A) do { uchar *pT= (uchar*)(T);\ *((uint16*)(pT))= (uint16) (A);\ } while (0) #define int3store(T,A) do { *(T)= (uchar) ((A));\ *(T+1)=(uchar) (((uint) (A) >> 8));\ *(T+2)=(uchar) (((A) >> 16));\ } while (0) #define int4store(T,A) do { uchar *pT= (uchar*)(T);\ *((uint32 *) (pT))= (uint32) (A); \ } while (0) #define int5store(T,A) do { uchar *pT= (uchar*)(T);\ *((uint32 *) (pT))= (uint32) (A); \ *((pT)+4)=(uchar) (((A) >> 32));\ } while (0) #define int6store(T,A) do { uchar *pT= (uchar*)(T);\ *((uint32 *) (pT))= (uint32) (A); \ *((uint16*)(pT+4))= (uint16) (A >> 32);\ } while (0) #define int8store(T,A) do { uchar *pT= (uchar*)(T);\ *((ulonglong *) (pT))= (ulonglong) (A);\ } while(0) #if defined(__GNUC__) #define HAVE_mi_uint5korr #define HAVE_mi_uint6korr #define HAVE_mi_uint7korr #define HAVE_mi_uint8korr /* Read numbers stored in high-bytes-first order */ static inline ulonglong mi_uint5korr(const void *p) { ulonglong a= *(uint32 *) p; ulonglong b= *(4 + (uchar *) p); ulonglong v= (a | (b << 32)) << 24; asm ("bswapq %0" : "=r" (v) : "0" (v)); return v; } static inline ulonglong mi_uint6korr(const void *p) { ulonglong a= *(uint32 *) p; ulonglong b= *(uint16 *) (4 + (char *) p); ulonglong v= (a | (b << 32)) << 16; asm ("bswapq %0" : "=r" (v) : "0" (v)); return v; } static inline ulonglong mi_uint7korr(const void *p) { ulonglong a= *(uint32 *) p; ulonglong b= *(uint16 *) (4 + (char *) p); ulonglong c= *(6 + (uchar *) p); ulonglong v= (a | (b << 32) | (c << 48)) << 8; asm ("bswapq %0" : "=r" (v) : "0" (v)); return v; } static inline ulonglong mi_uint8korr(const void *p) { ulonglong v= *(ulonglong *) p; asm ("bswapq %0" : "=r" (v) : "0" (v)); return v; } #endif mysql/server/my_alloc.h000064400000004025151027430560011173 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Data structures for mysys/my_alloc.c (root memory allocator) */ #ifndef _my_alloc_h #define _my_alloc_h #include "mysql/psi/psi_base.h" #define ALLOC_MAX_BLOCK_TO_DROP 4096 #define ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP 10 #define ROOT_FLAG_READ_ONLY 4 #ifdef __cplusplus extern "C" { #endif typedef struct st_used_mem { /* struct for once_alloc (block) */ struct st_used_mem *next; /* Next block in use */ size_t left; /* memory left in block */ size_t size; /* size of block */ } USED_MEM; typedef struct st_mem_root { USED_MEM *free; /* blocks with free memory in it */ USED_MEM *used; /* blocks almost without free memory */ USED_MEM *pre_alloc; /* preallocated block */ /* if block have less memory it will be put in 'used' list */ size_t min_malloc; size_t block_size; /* initial block size */ unsigned int block_num; /* allocated blocks counter */ /* first free block in queue test counter (if it exceed MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list) */ unsigned short first_block_usage; unsigned short flags; void (*error_handler)(void); PSI_memory_key m_psi_key; } MEM_ROOT; #ifdef __cplusplus } #endif #endif mysql/server/my_dir.h000064400000007457151027430560010673 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_DIR_H #define MY_DIR_H #include #ifdef __cplusplus extern "C" { #endif /* Defines for my_dir and my_stat */ #define MY_S_IFMT S_IFMT /* type of file */ #define MY_S_IFDIR S_IFDIR /* directory */ #define MY_S_IFCHR S_IFCHR /* character special */ #define MY_S_IFBLK S_IFBLK /* block special */ #define MY_S_IFREG S_IFREG /* regular */ #define MY_S_IFIFO S_IFIFO /* fifo */ #define MY_S_ISUID S_ISUID /* set user id on execution */ #define MY_S_ISGID S_ISGID /* set group id on execution */ #define MY_S_ISVTX S_ISVTX /* save swapped text even after use */ #ifndef S_IREAD #define MY_S_IREAD S_IRUSR /* read permission, owner */ #define MY_S_IWRITE S_IWUSR /* write permission, owner */ #define MY_S_IEXEC S_IXUSR /* execute/search permission, owner */ #else #define MY_S_IREAD S_IREAD /* read permission, owner */ #define MY_S_IWRITE S_IWRITE /* write permission, owner */ #define MY_S_IEXEC S_IEXEC /* execute/search permission, owner */ #endif #define MY_S_ISDIR(m) (((m) & MY_S_IFMT) == MY_S_IFDIR) #define MY_S_ISCHR(m) (((m) & MY_S_IFMT) == MY_S_IFCHR) #define MY_S_ISBLK(m) (((m) & MY_S_IFMT) == MY_S_IFBLK) #define MY_S_ISREG(m) (((m) & MY_S_IFMT) == MY_S_IFREG) #define MY_S_ISFIFO(m) (((m) & MY_S_IFMT) == MY_S_IFIFO) /* Ensure these doesn't clash with anything in my_sys.h */ #define MY_WANT_SORT 8192 /* my_lib; sort files */ #define MY_WANT_STAT 16384 /* my_lib; stat files */ #define MY_DONT_SORT 0 /* typedefs for my_dir & my_stat */ #ifdef USE_MY_STAT_STRUCT typedef struct my_stat { dev_t st_dev; /* major & minor device numbers */ ino_t st_ino; /* inode number */ ushort st_mode; /* file permissions (& suid sgid .. bits) */ short st_nlink; /* number of links to file */ ushort st_uid; /* user id */ ushort st_gid; /* group id */ dev_t st_rdev; /* more major & minor device numbers (???) */ off_t st_size; /* size of file */ time_t st_atime; /* time for last read */ time_t st_mtime; /* time for last contents modify */ time_t st_ctime; /* time for last inode or contents modify */ } MY_STAT; #else #if defined(_MSC_VER) #define MY_STAT struct _stati64 /* 64 bit file size */ #else #define MY_STAT struct stat /* Original struct has what we need */ #endif #endif /* USE_MY_STAT_STRUCT */ /* Struct describing one file returned from my_dir */ typedef struct fileinfo { char *name; MY_STAT *mystat; } FILEINFO; typedef struct st_my_dir /* Struct returned from my_dir */ { /* These members are just copies of parts of DYNAMIC_ARRAY structure, which is allocated right after the end of MY_DIR structure (MEM_ROOT for storing names is also resides there). We've left them here because we don't want to change code that uses my_dir. */ struct fileinfo *dir_entry; uint number_of_files; } MY_DIR; extern MY_DIR *my_dir(const char *path,myf MyFlags); extern void my_dirend(MY_DIR *buffer); extern MY_STAT *my_stat(const char *path, MY_STAT *stat_area, myf my_flags); extern int my_fstat(int filenr, MY_STAT *stat_area, myf MyFlags); #ifdef __cplusplus } #endif #endif /* MY_DIR_H */ mysql/server/my_valgrind.h000064400000010700151027430560011704 0ustar00/* Copyright (C) 2010, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_VALGRIND_INCLUDED #define MY_VALGRIND_INCLUDED /* clang -> gcc */ #ifndef __has_feature # define __has_feature(x) 0 #endif #if __has_feature(address_sanitizer) # define __SANITIZE_ADDRESS__ 1 #endif #if __has_feature(memory_sanitizer) # include # define HAVE_valgrind # define HAVE_MEM_CHECK # define MEM_UNDEFINED(a,len) __msan_allocated_memory(a,len) # define MEM_MAKE_ADDRESSABLE(a,len) MEM_UNDEFINED(a,len) # define MEM_MAKE_DEFINED(a,len) __msan_unpoison(a,len) # define MEM_NOACCESS(a,len) ((void) 0) # define MEM_CHECK_ADDRESSABLE(a,len) ((void) 0) # define MEM_CHECK_DEFINED(a,len) __msan_check_mem_is_initialized(a,len) # define MEM_GET_VBITS(a,b,len) __msan_copy_shadow(b,a,len) # define MEM_SET_VBITS(a,b,len) __msan_copy_shadow(a,b,len) # define REDZONE_SIZE 8 # ifdef __linux__ # define MSAN_STAT_WORKAROUND(st) MEM_MAKE_DEFINED(st, sizeof(*st)) # else # define MSAN_STAT_WORKAROUND(st) ((void) 0) # endif #elif defined(HAVE_VALGRIND_MEMCHECK_H) && defined(HAVE_valgrind) # include # define HAVE_MEM_CHECK # define MEM_UNDEFINED(a,len) VALGRIND_MAKE_MEM_UNDEFINED(a,len) # define MEM_MAKE_ADDRESSABLE(a,len) MEM_UNDEFINED(a,len) # define MEM_MAKE_DEFINED(a,len) VALGRIND_MAKE_MEM_DEFINED(a,len) # define MEM_NOACCESS(a,len) VALGRIND_MAKE_MEM_NOACCESS(a,len) # define MEM_CHECK_ADDRESSABLE(a,len) VALGRIND_CHECK_MEM_IS_ADDRESSABLE(a,len) # define MEM_CHECK_DEFINED(a,len) VALGRIND_CHECK_MEM_IS_DEFINED(a,len) # define MEM_GET_VBITS(a,b,len) VALGRIND_GET_VBITS(a,b,len) # define MEM_SET_VBITS(a,b,len) VALGRIND_SET_VBITS(a,b,len) # define REDZONE_SIZE 8 # define MSAN_STAT_WORKAROUND(st) ((void) 0) #elif defined(__SANITIZE_ADDRESS__) && (!defined(_MSC_VER) || defined (__clang__)) # include /* How to do manual poisoning: https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning */ # define MEM_UNDEFINED(a,len) ((void) 0) # define MEM_MAKE_ADDRESSABLE(a,len) ASAN_UNPOISON_MEMORY_REGION(a,len) # define MEM_MAKE_DEFINED(a,len) ((void) 0) # define MEM_NOACCESS(a,len) ASAN_POISON_MEMORY_REGION(a,len) # define MEM_CHECK_ADDRESSABLE(a,len) \ assert(!__asan_region_is_poisoned((void*) a,len)) # define MEM_CHECK_DEFINED(a,len) ((void) 0) # define MEM_GET_VBITS(a,b,len) ((void) 0) # define MEM_SET_VBITS(a,b,len) ((void) 0) # define MSAN_STAT_WORKAROUND(st) ((void) 0) # define REDZONE_SIZE 8 #else # define MEM_UNDEFINED(a,len) ((void) 0) # define MEM_MAKE_ADDRESSABLE(a,len) ((void) 0) # define MEM_MAKE_DEFINED(a,len) ((void) 0) # define MEM_NOACCESS(a,len) ((void) 0) # define MEM_CHECK_ADDRESSABLE(a,len) ((void) 0) # define MEM_CHECK_DEFINED(a,len) ((void) 0) # define MEM_GET_VBITS(a,b,len) ((void) 0) # define MEM_SET_VBITS(a,b,len) ((void) 0) # define REDZONE_SIZE 0 # define MSAN_STAT_WORKAROUND(st) ((void) 0) #endif /* __has_feature(memory_sanitizer) */ #ifdef TRASH_FREED_MEMORY /* _TRASH_FILL() has to call MEM_MAKE_ADDRESSABLE() to cancel any effect of TRASH_FREE(). This can happen in the case one does TRASH_ALLOC(A,B) ; TRASH_FREE(A,B) ; TRASH_ALLOC(A,B) to reuse the same memory in an internal memory allocator like MEM_ROOT. _TRASH_FILL() is an internal function and should not be used externally. */ #define _TRASH_FILL(A,B,C) do { const size_t trash_tmp= (B); MEM_MAKE_ADDRESSABLE(A, trash_tmp); memset(A, C, trash_tmp); } while (0) #else #define _TRASH_FILL(A,B,C) do { MEM_UNDEFINED((A), (B)); } while (0) #endif /** Note that some memory became allocated and/or uninitialized. */ #define TRASH_ALLOC(A,B) do { _TRASH_FILL(A,B,0xA5); MEM_MAKE_ADDRESSABLE(A,B); } while(0) /** Note that some memory became freed. (Prohibit further access to it.) */ #define TRASH_FREE(A,B) do { _TRASH_FILL(A,B,0x8F); MEM_NOACCESS(A,B); } while(0) #endif /* MY_VALGRIND_INCLUDED */ mysql/server/my_alloca.h000064400000002627151027430560011342 0ustar00/* Copyright (c) 2023, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_ALLOCA_INCLUDED #define MY_ALLOCA_INCLUDED #ifdef _WIN32 #include /*for alloca*/ /* MSVC may define "alloca" when compiling in /Ze mode (with extensions from Microsoft), but otherwise only the _alloca function is defined: */ #ifndef alloca #define alloca _alloca #endif #else #ifdef HAVE_ALLOCA_H #include #endif #endif #if defined(_AIX) && !defined(__GNUC__) && !defined(_AIX43) #pragma alloca #endif /* _AIX */ /* If the GCC/LLVM compiler from the MinGW is used, alloca may not be defined when using the MSVC CRT: */ #if defined(__GNUC__) && !defined(HAVE_ALLOCA_H) && !defined(alloca) #define alloca __builtin_alloca #endif /* GNUC */ #endif /* MY_ALLOCA_INCLUDED */ mysql/server/typelib.h000064400000004534151027430560011051 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _typelib_h #define _typelib_h #include "my_alloc.h" typedef struct st_typelib { /* Different types saved here */ unsigned int count; /* How many types */ const char *name; /* Name of typelib */ const char **type_names; unsigned int *type_lengths; } TYPELIB; extern my_ulonglong find_typeset(const char *x, TYPELIB *typelib, int *error_position); extern int find_type_with_warning(const char *x, TYPELIB *typelib, const char *option); #define FIND_TYPE_BASIC 0 /** makes @c find_type() require the whole name, no prefix */ #define FIND_TYPE_NO_PREFIX (1U << 0) /** always implicitly on, so unused, but old code may pass it */ #define FIND_TYPE_NO_OVERWRITE 0 /** makes @c find_type() accept a number. Not used either */ #define FIND_TYPE_ALLOW_NUMBER 0 /** makes @c find_type() treat ',' and '=' as terminators */ #define FIND_TYPE_COMMA_TERM (1U << 3) extern int find_type(const char *x, const TYPELIB *typelib, unsigned int flags); extern void make_type(char *to,unsigned int nr,TYPELIB *typelib); extern const char *get_type(TYPELIB *typelib,unsigned int nr); extern TYPELIB *copy_typelib(MEM_ROOT *root, const TYPELIB *from); extern TYPELIB sql_protocol_typelib; my_ulonglong find_set_from_flags(const TYPELIB *lib, unsigned int default_name, my_ulonglong cur_set, my_ulonglong default_set, const char *str, unsigned int length, char **err_pos, unsigned int *err_len); #endif /* _typelib_h */ mysql/server/my_pthread.h000064400000065737151027430560011551 0ustar00/* Copyright (c) 2000, 2014, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Defines to make different thread packages compatible */ #ifndef _my_pthread_h #define _my_pthread_h #ifndef ETIME #define ETIME ETIMEDOUT /* For FreeBSD */ #endif #ifdef __cplusplus #define EXTERNC extern "C" extern "C" { #else #define EXTERNC #endif /* __cplusplus */ #if defined(_WIN32) typedef CRITICAL_SECTION pthread_mutex_t; typedef DWORD pthread_t; typedef struct thread_attr { DWORD dwStackSize ; DWORD dwCreatingFlag ; } pthread_attr_t ; typedef struct { int dummy; } pthread_condattr_t; /* Implementation of posix conditions */ typedef struct st_pthread_link { DWORD thread_id; struct st_pthread_link *next; } pthread_link; /** Implementation of Windows condition variables. We use native conditions on Vista and later, and fallback to own implementation on earlier OS version. */ typedef CONDITION_VARIABLE pthread_cond_t; typedef int pthread_mutexattr_t; #define pthread_self() GetCurrentThreadId() #define pthread_handler_t EXTERNC void * __cdecl typedef void * (__cdecl *pthread_handler)(void *); typedef INIT_ONCE my_pthread_once_t; #define MY_PTHREAD_ONCE_INIT INIT_ONCE_STATIC_INIT; #if !STRUCT_TIMESPEC_HAS_TV_SEC || !STRUCT_TIMESPEC_HAS_TV_NSEC struct timespec { time_t tv_sec; long tv_nsec; }; #endif int win_pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_create(pthread_t *, const pthread_attr_t *, pthread_handler, void *); int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); int pthread_cond_signal(pthread_cond_t *cond); int pthread_cond_broadcast(pthread_cond_t *cond); int pthread_cond_destroy(pthread_cond_t *cond); int pthread_attr_init(pthread_attr_t *connect_att); int pthread_attr_setstacksize(pthread_attr_t *connect_att,size_t stack); int pthread_attr_destroy(pthread_attr_t *connect_att); int my_pthread_once(my_pthread_once_t *once_control,void (*init_routine)(void)); static inline struct tm *localtime_r(const time_t *timep, struct tm *tmp) { localtime_s(tmp, timep); return tmp; } static inline struct tm *gmtime_r(const time_t *clock, struct tm *res) { gmtime_s(res, clock); return res; } void pthread_exit(void *a); int pthread_join(pthread_t thread, void **value_ptr); int pthread_cancel(pthread_t thread); #ifndef ETIMEDOUT #define ETIMEDOUT 145 /* Win32 doesn't have this */ #endif #define HAVE_LOCALTIME_R 1 #define _REENTRANT 1 #define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1 #undef SAFE_MUTEX /* This will cause conflicts */ #define pthread_key(T,V) DWORD V #define pthread_key_create(A,B) ((*A=TlsAlloc())==0xFFFFFFFF) #define pthread_key_delete(A) TlsFree(A) #define my_pthread_setspecific_ptr(T,V) (!TlsSetValue((T),(V))) #define pthread_setspecific(A,B) (!TlsSetValue((A),(LPVOID)(B))) #define pthread_getspecific(A) (TlsGetValue(A)) #define my_pthread_getspecific(T,A) ((T) TlsGetValue(A)) #define my_pthread_getspecific_ptr(T,V) ((T) TlsGetValue(V)) #define pthread_equal(A,B) ((A) == (B)) #define pthread_mutex_init(A,B) (InitializeCriticalSection(A),0) #define pthread_mutex_lock(A) (EnterCriticalSection(A),0) #define pthread_mutex_trylock(A) win_pthread_mutex_trylock((A)) #define pthread_mutex_unlock(A) (LeaveCriticalSection(A), 0) #define pthread_mutex_destroy(A) (DeleteCriticalSection(A), 0) #define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH) /* Dummy defines for easier code */ #define pthread_attr_setdetachstate(A,B) pthread_dummy(0) #define pthread_attr_setscope(A,B) #define pthread_detach_this_thread() #define pthread_condattr_init(A) #define pthread_condattr_destroy(A) #define pthread_yield() SwitchToThread() #define my_sigset(A,B) signal(A,B) #else /* Normal threads */ #ifdef HAVE_rts_threads #define sigwait org_sigwait #include #undef sigwait #endif #include #ifndef _REENTRANT #define _REENTRANT #endif #ifdef HAVE_SCHED_H #include #endif #ifdef HAVE_SYNCH_H #include #endif #define pthread_key(T,V) pthread_key_t V #define my_pthread_getspecific_ptr(T,V) my_pthread_getspecific(T,(V)) #define my_pthread_setspecific_ptr(T,V) pthread_setspecific(T,(void*) (V)) #define pthread_detach_this_thread() #define pthread_handler_t EXTERNC void * typedef void *(* pthread_handler)(void *); #define my_pthread_once_t pthread_once_t #if defined(PTHREAD_ONCE_INITIALIZER) #define MY_PTHREAD_ONCE_INIT PTHREAD_ONCE_INITIALIZER #else #define MY_PTHREAD_ONCE_INIT PTHREAD_ONCE_INIT #endif #define my_pthread_once(C,F) pthread_once(C,F) /* Test first for RTS or FSU threads */ #if defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) #define HAVE_rts_threads extern int my_pthread_create_detached; #define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C)) #define PTHREAD_CREATE_DETACHED &my_pthread_create_detached #define PTHREAD_SCOPE_SYSTEM PTHREAD_SCOPE_GLOBAL #define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_LOCAL #define USE_ALARM_THREAD #endif /* defined(PTHREAD_SCOPE_GLOBAL) && !defined(PTHREAD_SCOPE_SYSTEM) */ #if defined(_BSDI_VERSION) && _BSDI_VERSION < 199910 int sigwait(sigset_t *set, int *sig); #endif static inline int my_sigwait(sigset_t *set, int *sig, int *code) { #ifdef HAVE_SIGWAITINFO siginfo_t siginfo; *sig= sigwaitinfo(set, &siginfo); *code= siginfo.si_code; return *sig < 0 ? errno : 0; #else *code= 0; return sigwait(set, sig); #endif } #if defined(HAVE_SIGTHREADMASK) && !defined(HAVE_PTHREAD_SIGMASK) #define pthread_sigmask(A,B,C) sigthreadmask((A),(B),(C)) #endif #if !defined(HAVE_SIGWAIT) && !defined(HAVE_rts_threads) && !defined(sigwait) && !defined(alpha_linux_port) && !defined(_AIX) int sigwait(sigset_t *setp, int *sigp); /* Use our implementation */ #endif /* We define my_sigset() and use that instead of the system sigset() so that we can favor an implementation based on sigaction(). On some systems, such as Mac OS X, sigset() results in flags such as SA_RESTART being set, and we want to make sure that no such flags are set. */ #if defined(HAVE_SIGACTION) && !defined(my_sigset) #define my_sigset(A,B) do { struct sigaction l_s; sigset_t l_set; \ DBUG_ASSERT((A) != 0); \ sigemptyset(&l_set); \ l_s.sa_handler = (B); \ l_s.sa_mask = l_set; \ l_s.sa_flags = 0; \ sigaction((A), &l_s, NULL); \ } while (0) #elif defined(HAVE_SIGSET) && !defined(my_sigset) #define my_sigset(A,B) sigset((A),(B)) #elif !defined(my_sigset) #define my_sigset(A,B) signal((A),(B)) #endif #if !defined(HAVE_PTHREAD_ATTR_SETSCOPE) #define pthread_attr_setscope(A,B) #undef HAVE_GETHOSTBYADDR_R /* No definition */ #endif #define my_pthread_getspecific(A,B) ((A) pthread_getspecific(B)) #ifndef HAVE_LOCALTIME_R struct tm *localtime_r(const time_t *clock, struct tm *res); #endif #ifndef HAVE_GMTIME_R struct tm *gmtime_r(const time_t *clock, struct tm *res); #endif #ifdef HAVE_PTHREAD_CONDATTR_CREATE /* DCE threads on HPUX 10.20 */ #define pthread_condattr_init pthread_condattr_create #define pthread_condattr_destroy pthread_condattr_delete #endif /* FSU THREADS */ #if !defined(HAVE_PTHREAD_KEY_DELETE) && !defined(pthread_key_delete) #define pthread_key_delete(A) pthread_dummy(0) #endif #if defined(HAVE_PTHREAD_ATTR_CREATE) && !defined(HAVE_SIGWAIT) /* This is set on AIX_3_2 and Siemens unix (and DEC OSF/1 3.2 too) */ #define pthread_key_create(A,B) \ pthread_keycreate(A,(B) ?\ (pthread_destructor_t) (B) :\ (pthread_destructor_t) pthread_dummy) #define pthread_attr_init(A) pthread_attr_create(A) #define pthread_attr_destroy(A) pthread_attr_delete(A) #define pthread_attr_setdetachstate(A,B) pthread_dummy(0) #define pthread_create(A,B,C,D) pthread_create((A),*(B),(C),(D)) #ifndef pthread_sigmask #define pthread_sigmask(A,B,C) sigprocmask((A),(B),(C)) #endif #define pthread_kill(A,B) pthread_dummy((A) ? 0 : ESRCH) #undef pthread_detach_this_thread #define pthread_detach_this_thread() { pthread_t tmp=pthread_self() ; pthread_detach(&tmp); } #else /* HAVE_PTHREAD_ATTR_CREATE && !HAVE_SIGWAIT */ #define HAVE_PTHREAD_KILL 1 #endif #endif /* defined(_WIN32) */ #if defined(HPUX10) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS) #undef pthread_cond_timedwait #define pthread_cond_timedwait(a,b,c) my_pthread_cond_timedwait((a),(b),(c)) int my_pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime); #endif #if defined(HPUX10) #define pthread_attr_getstacksize(A,B) my_pthread_attr_getstacksize(A,B) void my_pthread_attr_getstacksize(pthread_attr_t *attrib, size_t *size); #endif #if defined(HAVE_POSIX1003_4a_MUTEX) && !defined(DONT_REMAP_PTHREAD_FUNCTIONS) #undef pthread_mutex_trylock #define pthread_mutex_trylock(a) my_pthread_mutex_trylock((a)) int my_pthread_mutex_trylock(pthread_mutex_t *mutex); #endif #ifdef HAVE_SCHED_YIELD #define pthread_yield() sched_yield() #else #if !defined(HAVE_PTHREAD_YIELD_ZERO_ARG) /* no pthread_yield() available */ #if defined(HAVE_PTHREAD_YIELD_NP) /* can be Mac OS X */ #define pthread_yield() pthread_yield_np() #elif defined(HAVE_THR_YIELD) #define pthread_yield() thr_yield() #endif //defined(HAVE_PTHREAD_YIELD_NP) #endif //!defined(HAVE_PTHREAD_YIELD_ZERO_ARG) #endif //HAVE_SCHED_YIELD size_t my_setstacksize(pthread_attr_t *attr, size_t stacksize); /* The defines set_timespec and set_timespec_nsec should be used for calculating an absolute time at which pthread_cond_timedwait should timeout */ #define set_timespec(ABSTIME,SEC) set_timespec_nsec((ABSTIME),(SEC)*1000000000ULL) #ifndef set_timespec_nsec #define set_timespec_nsec(ABSTIME,NSEC) \ set_timespec_time_nsec((ABSTIME), my_hrtime_coarse().val*1000 + (NSEC)) #endif /* !set_timespec_nsec */ /* adapt for two different flavors of struct timespec */ #ifdef HAVE_TIMESPEC_TS_SEC #define MY_tv_sec ts_sec #define MY_tv_nsec ts_nsec #else #define MY_tv_sec tv_sec #define MY_tv_nsec tv_nsec #endif /* HAVE_TIMESPEC_TS_SEC */ /** Compare two timespec structs. @retval 1 If TS1 ends after TS2. @retval 0 If TS1 is equal to TS2. @retval -1 If TS1 ends before TS2. */ #ifndef cmp_timespec #define cmp_timespec(TS1, TS2) \ ((TS1.MY_tv_sec > TS2.MY_tv_sec || \ (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec > TS2.MY_tv_nsec)) ? 1 : \ ((TS1.MY_tv_sec < TS2.MY_tv_sec || \ (TS1.MY_tv_sec == TS2.MY_tv_sec && TS1.MY_tv_nsec < TS2.MY_tv_nsec)) ? -1 : 0)) #endif /* !cmp_timespec */ #ifndef set_timespec_time_nsec #define set_timespec_time_nsec(ABSTIME,NSEC) do { \ ulonglong _now_= (NSEC); \ (ABSTIME).MY_tv_sec= (time_t) (_now_ / 1000000000ULL); \ (ABSTIME).MY_tv_nsec= (ulong) (_now_ % 1000000000UL); \ } while(0) #endif /* !set_timespec_time_nsec */ #ifdef MYSQL_CLIENT #define _current_thd() NULL #else MYSQL_THD _current_thd(); #endif /* safe_mutex adds checking to mutex for easier debugging */ struct st_hash; typedef struct st_safe_mutex_t { pthread_mutex_t global,mutex; const char *file, *name; uint line,count; myf create_flags, active_flags; ulong id; pthread_t thread; struct st_hash *locked_mutex, *used_mutex; struct st_safe_mutex_t *prev, *next; #ifdef SAFE_MUTEX_DETECT_DESTROY struct st_safe_mutex_info_t *info; /* to track destroying of mutexes */ #endif } safe_mutex_t; typedef struct st_safe_mutex_deadlock_t { const char *file, *name; safe_mutex_t *mutex; uint line; ulong count; ulong id; my_bool warning_only; } safe_mutex_deadlock_t; #ifdef SAFE_MUTEX_DETECT_DESTROY /* Used to track the destroying of mutexes. This needs to be a separate structure because the safe_mutex_t structure could be freed before the mutexes are destroyed. */ typedef struct st_safe_mutex_info_t { struct st_safe_mutex_info_t *next; struct st_safe_mutex_info_t *prev; const char *init_file; uint32 init_line; } safe_mutex_info_t; #endif /* SAFE_MUTEX_DETECT_DESTROY */ int safe_mutex_init(safe_mutex_t *mp, const pthread_mutexattr_t *attr, const char *name, const char *file, uint line); int safe_mutex_lock(safe_mutex_t *mp, myf my_flags, const char *file, uint line); int safe_mutex_unlock(safe_mutex_t *mp,const char *file, uint line); int safe_mutex_destroy(safe_mutex_t *mp,const char *file, uint line); int safe_cond_wait(pthread_cond_t *cond, safe_mutex_t *mp,const char *file, uint line); int safe_cond_timedwait(pthread_cond_t *cond, safe_mutex_t *mp, const struct timespec *abstime, const char *file, uint line); void safe_mutex_global_init(void); void safe_mutex_end(FILE *file); void safe_mutex_free_deadlock_data(safe_mutex_t *mp); /* Wrappers if safe mutex is actually used */ #define MYF_TRY_LOCK 1 #define MYF_NO_DEADLOCK_DETECTION 2 #ifdef SAFE_MUTEX #define safe_mutex_is_owner(mp) ((mp)->count > 0 && \ pthread_equal(pthread_self(), (mp)->thread)) #define safe_mutex_assert_owner(mp) DBUG_ASSERT(safe_mutex_is_owner(mp)) #define safe_mutex_assert_not_owner(mp) DBUG_ASSERT(!safe_mutex_is_owner(mp)) #define safe_mutex_setflags(mp, F) do { (mp)->create_flags|= (F); } while (0) #define my_cond_timedwait(A,B,C) safe_cond_timedwait((A),(B),(C),__FILE__,__LINE__) #define my_cond_wait(A,B) safe_cond_wait((A), (B), __FILE__, __LINE__) #else #define safe_mutex_is_owner(mp) (1) #define safe_mutex_assert_owner(mp) do {} while (0) #define safe_mutex_assert_not_owner(mp) do {} while (0) #define safe_mutex_setflags(mp, F) do {} while (0) #define my_cond_timedwait(A,B,C) pthread_cond_timedwait((A),(B),(C)) #define my_cond_wait(A,B) pthread_cond_wait((A), (B)) #endif /* !SAFE_MUTEX */ /* READ-WRITE thread locking */ #if defined(USE_MUTEX_INSTEAD_OF_RW_LOCKS) /* use these defs for simple mutex locking */ #define rw_lock_t pthread_mutex_t #define my_rwlock_init(A,B) pthread_mutex_init((A),(B)) #define rw_rdlock(A) pthread_mutex_lock((A)) #define rw_wrlock(A) pthread_mutex_lock((A)) #define rw_tryrdlock(A) pthread_mutex_trylock((A)) #define rw_trywrlock(A) pthread_mutex_trylock((A)) #define rw_unlock(A) pthread_mutex_unlock((A)) #define rwlock_destroy(A) pthread_mutex_destroy((A)) #elif defined(HAVE_PTHREAD_RWLOCK_RDLOCK) #define rw_lock_t pthread_rwlock_t #define my_rwlock_init(A,B) pthread_rwlock_init((A),(B)) #define rw_rdlock(A) pthread_rwlock_rdlock(A) #define rw_wrlock(A) pthread_rwlock_wrlock(A) #define rw_tryrdlock(A) pthread_rwlock_tryrdlock((A)) #define rw_trywrlock(A) pthread_rwlock_trywrlock((A)) #define rw_unlock(A) pthread_rwlock_unlock(A) #define rwlock_destroy(A) pthread_rwlock_destroy(A) #elif defined(HAVE_RWLOCK_INIT) #ifdef HAVE_RWLOCK_T /* For example Solaris 2.6-> */ #define rw_lock_t rwlock_t #endif #define my_rwlock_init(A,B) rwlock_init((A),USYNC_THREAD,0) #else /* Use our own version of read/write locks */ #define NEED_MY_RW_LOCK 1 #define rw_lock_t my_rw_lock_t #define my_rwlock_init(A,B) my_rw_init((A)) #define rw_rdlock(A) my_rw_rdlock((A)) #define rw_wrlock(A) my_rw_wrlock((A)) #define rw_tryrdlock(A) my_rw_tryrdlock((A)) #define rw_trywrlock(A) my_rw_trywrlock((A)) #define rw_unlock(A) my_rw_unlock((A)) #define rwlock_destroy(A) my_rw_destroy((A)) #define rw_lock_assert_write_owner(A) my_rw_lock_assert_write_owner((A)) #define rw_lock_assert_not_write_owner(A) my_rw_lock_assert_not_write_owner((A)) #endif /* USE_MUTEX_INSTEAD_OF_RW_LOCKS */ /** Portable implementation of special type of read-write locks. These locks have two properties which are unusual for rwlocks: 1) They "prefer readers" in the sense that they do not allow situations in which rwlock is rd-locked and there is a pending rd-lock which is blocked (e.g. due to pending request for wr-lock). This is a stronger guarantee than one which is provided for PTHREAD_RWLOCK_PREFER_READER_NP rwlocks in Linux. MDL subsystem deadlock detector relies on this property for its correctness. 2) They are optimized for uncontended wr-lock/unlock case. This is a scenario in which they are most often used within MDL subsystem. Optimizing for it gives significant performance improvements in some of the tests involving many connections. Another important requirement imposed on this type of rwlock by the MDL subsystem is that it should be OK to destroy rwlock object which is in unlocked state even though some threads might have not yet fully left unlock operation for it (of course there is an external guarantee that no thread will try to lock rwlock which is destroyed). Putting it another way the unlock operation should not access rwlock data after changing its state to unlocked. TODO/FIXME: We should consider alleviating this requirement as it blocks us from doing certain performance optimizations. */ typedef struct st_rw_pr_lock_t { /** Lock which protects the structure. Also held for the duration of wr-lock. */ pthread_mutex_t lock; /** Condition variable which is used to wake-up writers waiting for readers to go away. */ pthread_cond_t no_active_readers; /** Number of active readers. */ uint active_readers; /** Number of writers waiting for readers to go away. */ uint writers_waiting_readers; /** Indicates whether there is an active writer. */ my_bool active_writer; #ifdef SAFE_MUTEX /** Thread holding wr-lock (for debug purposes only). */ pthread_t writer_thread; #endif } rw_pr_lock_t; extern int rw_pr_init(rw_pr_lock_t *); extern int rw_pr_rdlock(rw_pr_lock_t *); extern int rw_pr_wrlock(rw_pr_lock_t *); extern int rw_pr_unlock(rw_pr_lock_t *); extern int rw_pr_destroy(rw_pr_lock_t *); #ifdef SAFE_MUTEX #define rw_pr_lock_assert_write_owner(A) \ DBUG_ASSERT((A)->active_writer && pthread_equal(pthread_self(), \ (A)->writer_thread)) #define rw_pr_lock_assert_not_write_owner(A) \ DBUG_ASSERT(! (A)->active_writer || ! pthread_equal(pthread_self(), \ (A)->writer_thread)) #else #define rw_pr_lock_assert_write_owner(A) #define rw_pr_lock_assert_not_write_owner(A) #endif /* SAFE_MUTEX */ #ifdef NEED_MY_RW_LOCK #ifdef _WIN32 /** Implementation of Windows rwlock. We use native (slim) rwlocks on Windows, which requires Win7 or later. */ typedef struct _my_rwlock_t { SRWLOCK srwlock; /* native reader writer lock */ BOOL have_exclusive_srwlock; /* used for unlock */ } my_rw_lock_t; #else /* _WIN32 */ /* On systems which don't support native read/write locks we have to use own implementation. */ typedef struct st_my_rw_lock_t { pthread_mutex_t lock; /* lock for structure */ pthread_cond_t readers; /* waiting readers */ pthread_cond_t writers; /* waiting writers */ int state; /* -1:writer,0:free,>0:readers */ int waiters; /* number of waiting writers */ #ifdef SAFE_MUTEX pthread_t write_thread; #endif } my_rw_lock_t; #endif /*! _WIN32 */ extern int my_rw_init(my_rw_lock_t *); extern int my_rw_destroy(my_rw_lock_t *); extern int my_rw_rdlock(my_rw_lock_t *); extern int my_rw_wrlock(my_rw_lock_t *); extern int my_rw_unlock(my_rw_lock_t *); extern int my_rw_tryrdlock(my_rw_lock_t *); extern int my_rw_trywrlock(my_rw_lock_t *); #ifdef SAFE_MUTEX #define my_rw_lock_assert_write_owner(A) \ DBUG_ASSERT((A)->state == -1 && pthread_equal(pthread_self(), \ (A)->write_thread)) #define my_rw_lock_assert_not_write_owner(A) \ DBUG_ASSERT((A)->state >= 0 || ! pthread_equal(pthread_self(), \ (A)->write_thread)) #else #define my_rw_lock_assert_write_owner(A) #define my_rw_lock_assert_not_write_owner(A) #endif #endif /* NEED_MY_RW_LOCK */ #define GETHOSTBYADDR_BUFF_SIZE 2048 #if !defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && ! defined(pthread_attr_setstacksize) #define pthread_attr_setstacksize(A,B) pthread_dummy(0) #endif /* Define mutex types, see my_thr_init.c */ #define MY_MUTEX_INIT_SLOW NULL #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP extern pthread_mutexattr_t my_fast_mutexattr; #define MY_MUTEX_INIT_FAST &my_fast_mutexattr #else #define MY_MUTEX_INIT_FAST NULL #endif #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP extern pthread_mutexattr_t my_errorcheck_mutexattr; #define MY_MUTEX_INIT_ERRCHK &my_errorcheck_mutexattr #else #define MY_MUTEX_INIT_ERRCHK NULL #endif #ifndef ESRCH /* Define it to something */ #define ESRCH 1 #endif typedef uint64 my_thread_id; /** Long-standing formats (such as the client-server protocol and the binary log) hard-coded `my_thread_id` to 32 bits in practice. (Though not all `thread_id`s are typed as such, @ref my_thread_id itself among those.) @see MDEV-35706 */ #define MY_THREAD_ID_MAX UINT32_MAX extern void my_threadattr_global_init(void); extern my_bool my_thread_global_init(void); extern void my_thread_global_reinit(void); extern void my_thread_global_end(void); extern my_bool my_thread_init(void); extern void my_thread_end(void); extern const char *my_thread_name(void); extern my_thread_id my_thread_dbug_id(void); extern int pthread_dummy(int); extern void my_mutex_init(void); extern void my_mutex_end(void); /* All thread specific variables are in the following struct */ #define THREAD_NAME_SIZE 10 #ifndef DEFAULT_THREAD_STACK /* We need to have at least 256K stack to handle calls to myisamchk_init() with the current number of keys and key parts. */ #if !defined(__has_feature) #define __has_feature(x) 0 #endif #if defined(__clang__) && __has_feature(memory_sanitizer) && !defined(DBUG_OFF) /* MSAN in Debug with clang-20.1 required more memory to complete mtr begin/end checks. The result without increase was MSAN errors triggered on a call instruction. */ # define DEFAULT_THREAD_STACK (2L<<20) # elif defined(__SANITIZE_ADDRESS__) || defined(WITH_UBSAN) /* Optimized WITH_ASAN=ON executables produced by GCC 12.3.0, GCC 13.2.0, or clang 16.0.6 would fail ./mtr main.1st when the stack size is 5 MiB. The minimum is more than 6 MiB for CMAKE_BUILD_TYPE=RelWithDebInfo and more than 10 MiB for CMAKE_BUILD_TYPE=Debug. Let us add some safety margin. */ # define DEFAULT_THREAD_STACK (11L<<20) # else # define DEFAULT_THREAD_STACK (292*1024L) /* 299008 */ # endif #endif #define MY_PTHREAD_LOCK_READ 0 #define MY_PTHREAD_LOCK_WRITE 1 #include #define INSTRUMENT_ME 0 /* Thread specific variables Aria key cache is using the following variables for keeping track of state: suspend, next, prev, keycache_link, keycache_file, suspend, lock_type MariaDB uses the following to mutex, current_mutex, current_cond, abort */ struct st_my_thread_var { int thr_errno; mysql_cond_t suspend; mysql_mutex_t mutex; struct st_my_thread_var *next,**prev; mysql_mutex_t * volatile current_mutex; mysql_cond_t * volatile current_cond; void *keycache_link; void *keycache_file; void *stack_ends_here; safe_mutex_t *mutex_in_use; pthread_t pthread_self; my_thread_id id, dbug_id; int volatile abort; uint lock_type; /* used by conditional release the queue */ my_bool init; #ifndef DBUG_OFF void *dbug; char name[THREAD_NAME_SIZE+1]; #endif }; struct st_my_thread_var *_my_thread_var(void); extern void **my_thread_var_dbug(void); extern safe_mutex_t **my_thread_var_mutex_in_use(void); extern uint my_thread_end_wait_time; extern my_bool safe_mutex_deadlock_detector; #define my_thread_var (_my_thread_var()) #define my_errno my_thread_var->thr_errno int set_mysys_var(struct st_my_thread_var *mysys_var); /* thread_safe_xxx functions are for critical statistic or counters. The implementation is guaranteed to be thread safe, on all platforms. Note that the calling code should *not* assume the counter is protected by the mutex given, as the implementation of these helpers may change to use my_atomic operations instead. */ #ifndef thread_safe_increment #ifdef _WIN32 #define thread_safe_increment(V,L) InterlockedIncrement((long*) &(V)) #define thread_safe_decrement(V,L) InterlockedDecrement((long*) &(V)) #else #define thread_safe_increment(V,L) \ (mysql_mutex_lock((L)), (V)++, mysql_mutex_unlock((L))) #define thread_safe_decrement(V,L) \ (mysql_mutex_lock((L)), (V)--, mysql_mutex_unlock((L))) #endif #endif #ifndef thread_safe_add #ifdef _WIN32 #define thread_safe_add(V,C,L) InterlockedExchangeAdd((long*) &(V),(C)) #define thread_safe_sub(V,C,L) InterlockedExchangeAdd((long*) &(V),-(long) (C)) #else #define thread_safe_add(V,C,L) \ (mysql_mutex_lock((L)), (V)+=(C), mysql_mutex_unlock((L))) #define thread_safe_sub(V,C,L) \ (mysql_mutex_lock((L)), (V)-=(C), mysql_mutex_unlock((L))) #endif #endif /* statistics_xxx functions are for non critical statistic, maintained in global variables. When compiling with SAFE_STATISTICS: - race conditions can not occur. - some locking occurs, which may cause performance degradation. When compiling without SAFE_STATISTICS: - race conditions can occur, making the result slightly inaccurate. - the lock given is not honored. */ #ifdef SAFE_STATISTICS #define statistic_increment(V,L) thread_safe_increment((V),(L)) #define statistic_decrement(V,L) thread_safe_decrement((V),(L)) #define statistic_add(V,C,L) thread_safe_add((V),(C),(L)) #define statistic_sub(V,C,L) thread_safe_sub((V),(C),(L)) #else #define statistic_decrement(V,L) (V)-- #define statistic_increment(V,L) (V)++ #define statistic_add(V,C,L) (V)+=(C) #define statistic_sub(V,C,L) (V)-=(C) #endif /* SAFE_STATISTICS */ /* No locking needed, the counter is owned by the thread */ #define status_var_increment(V) (V)++ #define status_var_decrement(V) (V)-- #define status_var_add(V,C) (V)+=(C) #define status_var_sub(V,C) (V)-=(C) #ifdef SAFE_MUTEX #define mysql_mutex_record_order(A,B) \ do { \ mysql_mutex_lock(A); mysql_mutex_lock(B); \ mysql_mutex_unlock(B); mysql_mutex_unlock(A); \ } while(0) #else #define mysql_mutex_record_order(A,B) do { } while(0) #endif /* At least Windows and NetBSD do not have this definition */ #ifndef PTHREAD_STACK_MIN #define PTHREAD_STACK_MIN 65536 #endif #ifdef __cplusplus } #endif #endif /* _my_ptread_h */ mysql/server/byte_order_generic_x86.h000064400000010272151027430560013734 0ustar00/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Optimized function-like macros for the x86 architecture (_WIN32 included). */ #define sint2korr(A) (*((const int16 *) (A))) #define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ (((uint32) 255L << 24) | \ (((uint32) (uchar) (A)[2]) << 16) |\ (((uint32) (uchar) (A)[1]) << 8) | \ ((uint32) (uchar) (A)[0])) : \ (((uint32) (uchar) (A)[2]) << 16) |\ (((uint32) (uchar) (A)[1]) << 8) | \ ((uint32) (uchar) (A)[0]))) #define sint4korr(A) (*((const long *) (A))) #define uint2korr(A) (*((const uint16 *) (A))) #define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16)) #define uint4korr(A) (*((const uint32 *) (A))) #define uint5korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16) |\ (((uint32) ((uchar) (A)[3])) << 24)) |\ (((ulonglong) ((uchar) (A)[4])) << 32)) #define uint6korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) | \ (((uint32) ((uchar) (A)[1])) << 8) | \ (((uint32) ((uchar) (A)[2])) << 16) | \ (((uint32) ((uchar) (A)[3])) << 24)) | \ (((ulonglong) ((uchar) (A)[4])) << 32) | \ (((ulonglong) ((uchar) (A)[5])) << 40)) #define uint8korr(A) (*((const ulonglong *) (A))) #define sint8korr(A) (*((const longlong *) (A))) #define int2store(T,A) *((uint16*) (T))= (uint16) (A) #define int3store(T,A) do { *(T)= (uchar) ((A));\ *(T+1)=(uchar) (((uint) (A) >> 8));\ *(T+2)=(uchar) (((A) >> 16));\ } while (0) #define int4store(T,A) *((long *) (T))= (long) (A) #define int5store(T,A) do { *(T)= (uchar)((A));\ *((T)+1)=(uchar) (((A) >> 8));\ *((T)+2)=(uchar) (((A) >> 16));\ *((T)+3)=(uchar) (((A) >> 24));\ *((T)+4)=(uchar) (((A) >> 32));\ } while(0) #define int6store(T,A) do { *(T)= (uchar)((A)); \ *((T)+1)=(uchar) (((A) >> 8)); \ *((T)+2)=(uchar) (((A) >> 16)); \ *((T)+3)=(uchar) (((A) >> 24)); \ *((T)+4)=(uchar) (((A) >> 32)); \ *((T)+5)=(uchar) (((A) >> 40)); \ } while(0) #define int8store(T,A) *((ulonglong *) (T))= (ulonglong) (A) typedef union { double v; long m[2]; } doubleget_union; #define doubleget(V,M) \ do { doubleget_union _tmp; \ _tmp.m[0] = *((const long*)(M)); \ _tmp.m[1] = *(((const long*) (M))+1); \ (V) = _tmp.v; } while(0) #define doublestore(T,V) \ do { *((long *) T) = ((const doubleget_union *)&V)->m[0]; \ *(((long *) T)+1) = ((const doubleget_union *)&V)->m[1]; \ } while (0) #define float4get(V,M) \ do { *((float *) &(V)) = *((const float*) (M)); } while(0) #define float8get(V,M) doubleget((V),(M)) #define float4store(V,M) memcpy((uchar*)(V), (uchar*)(&M), sizeof(float)) #define floatstore(T,V) memcpy((uchar*)(T), (uchar*)(&V), sizeof(float)) #define floatget(V,M) memcpy((uchar*)(&V),(uchar*) (M), sizeof(float)) #define float8store(V,M) doublestore((V),(M)) mysql/server/private/my_md5.h000064400000002716151027430560012245 0ustar00#ifndef MY_MD5_INCLUDED #define MY_MD5_INCLUDED /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #include "m_string.h" #define MD5_HASH_SIZE 16 /* Hash size in bytes */ /* Wrapper function for MD5 implementation. */ #ifdef __cplusplus extern "C" { #endif #define compute_md5_hash(A,B,C) my_md5(A,B,C) /* Convert an array of bytes to a hexadecimal representation. Used to generate a hexadecimal representation of a message digest. */ static inline void array_to_hex(char *to, const unsigned char *str, uint len) { const unsigned char *str_end= str + len; for (; str != str_end; ++str) { *to++= _dig_vec_lower[((uchar) *str) >> 4]; *to++= _dig_vec_lower[((uchar) *str) & 0x0F]; } } #ifdef __cplusplus } #endif #endif /* MY_MD5_INCLUDED */ mysql/server/private/event_data_objects.h000064400000010133151027430560014666 0ustar00#ifndef _EVENT_DATA_OBJECTS_H_ #define _EVENT_DATA_OBJECTS_H_ /* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @addtogroup Event_Scheduler @{ @file event_data_objects.h */ #include "event_parse_data.h" #include "thr_lock.h" /* thr_lock_type */ class Field; class THD; class Time_zone; struct TABLE; void init_scheduler_psi_keys(void); class Event_queue_element_for_exec { public: Event_queue_element_for_exec() : dbname{nullptr, 0}, name{nullptr, 0} {} ~Event_queue_element_for_exec(); bool init(const LEX_CSTRING &dbname, const LEX_CSTRING &name); LEX_CSTRING dbname; LEX_CSTRING name; bool dropped; THD *thd; private: /* Prevent use of these */ Event_queue_element_for_exec(const Event_queue_element_for_exec &); void operator=(Event_queue_element_for_exec &); #ifdef HAVE_PSI_INTERFACE public: PSI_statement_info* get_psi_info() { return & psi_info; } static PSI_statement_info psi_info; #endif }; class Event_basic { protected: MEM_ROOT mem_root; public: LEX_CSTRING dbname; LEX_CSTRING name; LEX_CSTRING definer;// combination of user and host Time_zone *time_zone; Event_basic(); virtual ~Event_basic(); virtual bool load_from_row(THD *thd, TABLE *table) = 0; protected: bool load_string_fields(Field **fields, ...); bool load_time_zone(THD *thd, const LEX_CSTRING *tz_name); }; class Event_queue_element : public Event_basic { public: int on_completion; int status; uint32 originator; my_time_t last_executed; my_time_t execute_at; my_time_t starts; my_time_t ends; bool starts_null; bool ends_null; bool execute_at_null; longlong expression; interval_type interval; bool dropped; uint execution_count; Event_queue_element(); virtual ~Event_queue_element(); virtual bool load_from_row(THD *thd, TABLE *table) override; bool compute_next_execution_time(); void mark_last_executed(THD *thd); }; class Event_timed : public Event_queue_element { Event_timed(const Event_timed &); /* Prevent use of these */ void operator=(Event_timed &); public: LEX_CSTRING body; LEX_CSTRING definer_user; LEX_CSTRING definer_host; LEX_CSTRING comment; ulonglong created; ulonglong modified; sql_mode_t sql_mode; class Stored_program_creation_ctx *creation_ctx; LEX_CSTRING body_utf8; Event_timed(); virtual ~Event_timed(); void init(); virtual bool load_from_row(THD *thd, TABLE *table) override; int get_create_event(THD *thd, String *buf); }; class Event_job_data : public Event_basic { public: LEX_CSTRING body; LEX_CSTRING definer_user; LEX_CSTRING definer_host; sql_mode_t sql_mode; class Stored_program_creation_ctx *creation_ctx; Event_job_data(); virtual bool load_from_row(THD *thd, TABLE *table) override; bool execute(THD *thd, bool drop); private: bool construct_sp_sql(THD *thd, String *sp_sql); bool construct_drop_event_sql(THD *thd, String *sp_sql); Event_job_data(const Event_job_data &); /* Prevent use of these */ void operator=(Event_job_data &); }; /* Compares only the schema part of the identifier */ bool event_basic_db_equal(const LEX_CSTRING *db, Event_basic *et); /* Compares the whole identifier*/ bool event_basic_identifier_equal(const LEX_CSTRING *db, const LEX_CSTRING *name, Event_basic *b); /** @} (End of group Event_Scheduler) */ #endif /* _EVENT_DATA_OBJECTS_H_ */ mysql/server/private/thr_alarm.h000064400000005564151027430560013030 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Prototypes when using thr_alarm library functions */ #ifndef _thr_alarm_h #define _thr_alarm_h #ifdef __cplusplus extern "C" { #endif #ifndef USE_ALARM_THREAD #define USE_ONE_SIGNAL_HAND /* One must call process_alarm */ #endif #ifdef HAVE_rts_threads #undef USE_ONE_SIGNAL_HAND #define USE_ALARM_THREAD #define THR_SERVER_ALARM SIGUSR1 #else #define THR_SERVER_ALARM SIGALRM #endif typedef struct st_alarm_info { time_t next_alarm_time; uint active_alarms; uint max_used_alarms; } ALARM_INFO; void thr_alarm_info(ALARM_INFO *info); extern my_bool my_disable_thr_alarm; #ifdef _WIN32 #define DONT_USE_THR_ALARM #endif #if defined(DONT_USE_THR_ALARM) #define USE_ALARM_THREAD #undef USE_ONE_SIGNAL_HAND typedef my_bool thr_alarm_t; typedef my_bool ALARM; #define thr_alarm_init(A) (*(A))=0 #define thr_alarm_in_use(A) (*(A) != 0) #define thr_end_alarm(A) #define thr_alarm(A,B,C) ((*(A)=1)-1) /* The following should maybe be (*(A)) */ #define thr_got_alarm(A) 0 #define init_thr_alarm(A) #define thr_alarm_kill(A) #define resize_thr_alarm(N) #define end_thr_alarm(A) #else #if defined(_WIN32) typedef struct st_thr_alarm_entry { UINT_PTR crono; } thr_alarm_entry; #else /* System with posix threads */ typedef int thr_alarm_entry; #define thr_got_alarm(thr_alarm) (**(thr_alarm)) #endif /* _WIN32 */ typedef thr_alarm_entry* thr_alarm_t; typedef struct st_alarm { time_t expire_time; thr_alarm_entry alarmed; /* set when alarm is due */ pthread_t thread; my_thread_id thread_id; uint index_in_queue; my_bool malloced; } ALARM; extern uint thr_client_alarm; extern pthread_t alarm_thread; #define thr_alarm_init(A) (*(A))=0 #define thr_alarm_in_use(A) (*(A)!= 0) void init_thr_alarm(uint max_alarm); void resize_thr_alarm(uint max_alarms); my_bool thr_alarm(thr_alarm_t *alarmed, uint sec, ALARM *buff); void thr_alarm_kill(my_thread_id thread_id); void thr_end_alarm(thr_alarm_t *alarmed); void end_thr_alarm(my_bool free_structures); sig_handler process_alarm(int); #ifndef thr_got_alarm my_bool thr_got_alarm(thr_alarm_t *alrm); #endif #endif /* DONT_USE_THR_ALARM */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _thr_alarm_h */ mysql/server/private/thr_malloc.h000064400000002262151027430560013173 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef THR_MALLOC_INCLUDED #define THR_MALLOC_INCLUDED typedef struct st_mem_root MEM_ROOT; void init_sql_alloc(PSI_memory_key key, MEM_ROOT *root, uint block_size, uint pre_alloc_size, myf my_flags); char *sql_strmake_with_convert(THD *thd, const char *str, size_t arg_length, CHARSET_INFO *from_cs, size_t max_res_length, CHARSET_INFO *to_cs, size_t *result_length); #endif /* THR_MALLOC_INCLUDED */ mysql/server/private/my_apc.h000064400000011213151027430560012313 0ustar00#ifndef SQL_MY_APC_INCLUDED #define SQL_MY_APC_INCLUDED /* Copyright (c) 2011, 2013 Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Interface ~~~~~~~~~ ( - This is an APC request queue - We assume there is a particular owner thread which periodically calls process_apc_requests() to serve the call requests. - Other threads can post call requests, and block until they are exectued. ) Implementation ~~~~~~~~~~~~~~ - The target has a mutex-guarded request queue. - After the request has been put into queue, the requestor waits for request to be satisfied. The worker satisifes the request and signals the requestor. */ class THD; /* Target for asynchronous procedure calls (APCs). - A target is running in some particular thread, - One can make calls to it from other threads. */ class Apc_target { mysql_mutex_t *LOCK_thd_kill_ptr; public: Apc_target() : enabled(0), apc_calls(NULL) {} ~Apc_target() { DBUG_ASSERT(!enabled && !apc_calls);} void init(mysql_mutex_t *target_mutex); /* Destroy the target. The target must be disabled when this call is made. */ void destroy() { DBUG_ASSERT(!enabled); } /* Enter ther state where the target is available for serving APC requests */ void enable() { enabled++; } /* Make the target unavailable for serving APC requests. @note This call will serve all requests that were already enqueued */ void disable() { DBUG_ASSERT(enabled); mysql_mutex_lock(LOCK_thd_kill_ptr); bool process= !--enabled && have_apc_requests(); mysql_mutex_unlock(LOCK_thd_kill_ptr); if (unlikely(process)) process_apc_requests(true); } void process_apc_requests(bool force); /* A lightweight function, intended to be used in frequent checks like this: if (apc_target.have_requests()) apc_target.process_apc_requests() */ inline bool have_apc_requests() { return MY_TEST(apc_calls); } inline bool is_enabled() { return enabled; } /* Functor class for calls you can schedule */ class Apc_call { public: /* This function will be called in the target thread */ virtual void call_in_target_thread()= 0; virtual ~Apc_call() = default; }; /* Make a call in the target thread (see function definition for details) */ bool make_apc_call(THD *caller_thd, Apc_call *call, int timeout_sec, bool *timed_out); #ifndef DBUG_OFF int n_calls_processed; /* Number of calls served by this target */ #endif private: class Call_request; /* Non-zero value means we're enabled. It's an int, not bool, because one can call enable() N times (and then needs to call disable() N times before the target is really disabled) */ int enabled; /* Circular, double-linked list of all enqueued call requests. We use this structure, because we - process requests sequentially: requests are added at the end of the list and removed from the front. With circular list, we can keep one pointer, and access both front an back of the list with it. - a thread that has posted a request may time out (or be KILLed) and cancel the request, which means we need a fast request-removal operation. */ Call_request *apc_calls; class Call_request { public: Apc_call *call; /* Functor to be called */ /* The caller will actually wait for "processed==TRUE" */ bool processed; /* Condition that will be signalled when the request has been served */ mysql_cond_t COND_request; /* Double linked-list linkage */ Call_request *next; Call_request *prev; const char *what; /* (debug) state of the request */ }; void enqueue_request(Call_request *qe); void dequeue_request(Call_request *qe); /* return the first call request in queue, or NULL if there are none enqueued */ Call_request *get_first_in_queue() { return apc_calls; } }; #ifdef HAVE_PSI_INTERFACE void init_show_explain_psi_keys(void); #else #define init_show_explain_psi_keys() /* no-op */ #endif #endif //SQL_MY_APC_INCLUDED mysql/server/private/opt_range.h000064400000164307151027430560013036 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* classes to use when handling where clause */ #ifndef _opt_range_h #define _opt_range_h #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "records.h" /* READ_RECORD */ #include "queues.h" /* QUEUE */ #include "filesort.h" /* SORT_INFO */ /* It is necessary to include set_var.h instead of item.h because there are dependencies on include order for set_var.h and item.h. This will be resolved later. */ #include "sql_class.h" // set_var.h: THD #include "set_var.h" /* Item */ class JOIN; class Item_sum; struct KEY_PART { uint16 key,part; /* See KEY_PART_INFO for meaning of the next two: */ uint16 store_length, length; uint8 null_bit; /* Keypart flags (0 when this structure is used by partition pruning code for fake partitioning index description) */ uint8 flag; Field *field; Field::imagetype image_type; }; class RANGE_OPT_PARAM; /* A construction block of the SEL_ARG-graph. The following description only covers graphs of SEL_ARG objects with sel_arg->type==KEY_RANGE: One SEL_ARG object represents an "elementary interval" in form min_value <=? table.keypartX <=? max_value The interval is a non-empty interval of any kind: with[out] minimum/maximum bound, [half]open/closed, single-point interval, etc. 1. SEL_ARG GRAPH STRUCTURE SEL_ARG objects are linked together in a graph. The meaning of the graph is better demostrated by an example: tree->keys[i] | | $ $ | part=1 $ part=2 $ part=3 | $ $ | +-------+ $ +-------+ $ +--------+ | | kp1<1 |--$-->| kp2=5 |--$-->| kp3=10 | | +-------+ $ +-------+ $ +--------+ | | $ $ | | | $ $ +--------+ | | $ $ | kp3=12 | | | $ $ +--------+ | +-------+ $ $ \->| kp1=2 |--$--------------$-+ +-------+ $ $ | +--------+ | $ $ ==>| kp3=11 | +-------+ $ $ | +--------+ | kp1=3 |--$--------------$-+ | +-------+ $ $ +--------+ | $ $ | kp3=14 | ... $ $ +--------+ The entire graph is partitioned into "interval lists". An interval list is a sequence of ordered disjoint intervals over the same key part. SEL_ARG are linked via "next" and "prev" pointers. Additionally, all intervals in the list form an RB-tree, linked via left/right/parent pointers. The RB-tree root SEL_ARG object will be further called "root of the interval list". In the example pic, there are 4 interval lists: "kp<1 OR kp1=2 OR kp1=3", "kp2=5", "kp3=10 OR kp3=12", "kp3=11 OR kp3=13". The vertical lines represent SEL_ARG::next/prev pointers. In an interval list, each member X may have SEL_ARG::next_key_part pointer pointing to the root of another interval list Y. The pointed interval list must cover a key part with greater number (i.e. Y->part > X->part). In the example pic, the next_key_part pointers are represented by horisontal lines. 2. SEL_ARG GRAPH SEMANTICS It represents a condition in a special form (we don't have a name for it ATM) The SEL_ARG::next/prev is "OR", and next_key_part is "AND". For example, the picture represents the condition in form: (kp1 < 1 AND kp2=5 AND (kp3=10 OR kp3=12)) OR (kp1=2 AND (kp3=11 OR kp3=14)) OR (kp1=3 AND (kp3=11 OR kp3=14)) 3. SEL_ARG GRAPH USE Use get_mm_tree() to construct SEL_ARG graph from WHERE condition. Then walk the SEL_ARG graph and get a list of dijsoint ordered key intervals (i.e. intervals in form (constA1, .., const1_K) < (keypart1,.., keypartK) < (constB1, .., constB_K) Those intervals can be used to access the index. The uses are in: - check_quick_select() - Walk the SEL_ARG graph and find an estimate of how many table records are contained within all intervals. - get_quick_select() - Walk the SEL_ARG, materialize the key intervals, and create QUICK_RANGE_SELECT object that will read records within these intervals. 4. SPACE COMPLEXITY NOTES SEL_ARG graph is a representation of an ordered disjoint sequence of intervals over the ordered set of index tuple values. For multi-part keys, one can construct a WHERE expression such that its list of intervals will be of combinatorial size. Here is an example: (keypart1 IN (1,2, ..., n1)) AND (keypart2 IN (1,2, ..., n2)) AND (keypart3 IN (1,2, ..., n3)) For this WHERE clause the list of intervals will have n1*n2*n3 intervals of form (keypart1, keypart2, keypart3) = (k1, k2, k3), where 1 <= k{i} <= n{i} SEL_ARG graph structure aims to reduce the amount of required space by "sharing" the elementary intervals when possible (the pic at the beginning of this comment has examples of such sharing). The sharing may prevent combinatorial blowup: There are WHERE clauses that have combinatorial-size interval lists but will be represented by a compact SEL_ARG graph. Example: (keypartN IN (1,2, ..., n1)) AND ... (keypart2 IN (1,2, ..., n2)) AND (keypart1 IN (1,2, ..., n3)) but not in all cases: - There are WHERE clauses that do have a compact SEL_ARG-graph representation but get_mm_tree() and its callees will construct a graph of combinatorial size. Example: (keypart1 IN (1,2, ..., n1)) AND (keypart2 IN (1,2, ..., n2)) AND ... (keypartN IN (1,2, ..., n3)) - There are WHERE clauses for which the minimal possible SEL_ARG graph representation will have combinatorial size. Example: By induction: Let's take any interval on some keypart in the middle: kp15=c0 Then let's AND it with this interval 'structure' from preceding and following keyparts: (kp14=c1 AND kp16=c3) OR keypart14=c2) (*) We will obtain this SEL_ARG graph: kp14 $ kp15 $ kp16 $ $ +---------+ $ +---------+ $ +---------+ | kp14=c1 |--$-->| kp15=c0 |--$-->| kp16=c3 | +---------+ $ +---------+ $ +---------+ | $ $ +---------+ $ +---------+ $ | kp14=c2 |--$-->| kp15=c0 | $ +---------+ $ +---------+ $ $ $ Note that we had to duplicate "kp15=c0" and there was no way to avoid that. The induction step: AND the obtained expression with another "wrapping" expression like (*). When the process ends because of the limit on max. number of keyparts we'll have: WHERE clause length is O(3*#max_keyparts) SEL_ARG graph size is O(2^(#max_keyparts/2)) (it is also possible to construct a case where instead of 2 in 2^n we have a bigger constant, e.g. 4, and get a graph with 4^(31/2)= 2^31 nodes) We avoid consuming too much memory by setting a limit on the number of SEL_ARG object we can construct during one range analysis invocation. 5. SEL_ARG GRAPH WEIGHT A SEL_ARG graph has a property we call weight, and we define it as follows: If the SEL_ARG graph does not have any node with multiple incoming next_key_part edges, then its weight is the number of SEL_ARG objects used. If there is a node with multiple incoming next_key_part edges, clone that node, (and the nodes connected to it via prev/next links) and redirect one of the incoming next_key_part edges to the clone. Continue with cloning until we get a graph that has no nodes with multiple incoming next_key_part edges. Then, the number of SEL_ARG objects in the graph is the weight of the original graph. Example: kp1 $ kp2 $ kp3 $ $ | +-------+ $ $ \->| kp1=2 |--$--------------$-+ +-------+ $ $ | +--------+ | $ $ ==>| kp3=11 | +-------+ $ $ | +--------+ | kp1>3 |--$--------------$-+ | +-------+ $ $ +--------+ $ $ | kp3=14 | $ $ +--------+ $ $ | $ $ +--------+ $ $ | kp3=14 | $ $ +--------+ Here, the weight is 2 + 2*3=8. The rationale behind using this definition of weight is: - it has the same order-of-magnitude as the number of ranges that the SEL_ARG graph is describing, - it is a lot easier to compute than computing the number of ranges, - it can be updated incrementally when performing AND/OR operations on parts of the graph. */ class SEL_ARG :public Sql_alloc { static int sel_cmp(Field *field, uchar *a, uchar *b, uint8 a_flag, uint8 b_flag); public: uint8 min_flag,max_flag,maybe_flag; uint8 part; // Which key part uint8 maybe_null; /* The ordinal number the least significant component encountered in the ranges of the SEL_ARG tree (the first component has number 1) Note: this number is currently not precise, it is an upper bound. @seealso SEL_ARG::get_max_key_part() */ uint16 max_part_no; /* Number of children of this element in the RB-tree, plus 1 for this element itself. */ uint32 elements; /* Valid only for elements which are RB-tree roots: Number of times this RB-tree is referred to (it is referred by SEL_ARG::next_key_part or by SEL_TREE::keys[i] or by a temporary SEL_ARG* variable) */ ulong use_count; Field *field; uchar *min_value,*max_value; // Pointer to range /* eq_tree() requires that left == right == 0 if the type is MAYBE_KEY. */ SEL_ARG *left,*right; /* R-B tree children */ SEL_ARG *next,*prev; /* Links for bi-directional interval list */ SEL_ARG *parent; /* R-B tree parent */ SEL_ARG *next_key_part; enum leaf_color { BLACK,RED } color; enum Type { IMPOSSIBLE, MAYBE, MAYBE_KEY, KEY_RANGE } type; /* For R-B root nodes only: the graph weight, as defined above in the SEL_ARG GRAPH WEIGHT section. */ uint weight; enum { MAX_WEIGHT = 32000 }; #ifndef DBUG_OFF uint verify_weight(); #endif /* See RANGE_OPT_PARAM::alloced_sel_args */ enum { DEFAULT_MAX_SEL_ARGS = 16000 }; SEL_ARG() = default; SEL_ARG(SEL_ARG &); SEL_ARG(Field *,const uchar *, const uchar *); SEL_ARG(Field *field, uint8 part, uchar *min_value, uchar *max_value, uint8 min_flag, uint8 max_flag, uint8 maybe_flag); SEL_ARG(enum Type type_arg) :min_flag(0), max_part_no(0) /* first key part means 1. 0 mean 'no parts'*/, elements(1),use_count(1),left(0),right(0), next_key_part(0), color(BLACK), type(type_arg), weight(1) {} /** returns true if a range predicate is equal. Use all_same() to check for equality of all the predicates on this keypart. */ inline bool is_same(const SEL_ARG *arg) const { if (type != arg->type || part != arg->part) return false; if (type != KEY_RANGE) return true; return cmp_min_to_min(arg) == 0 && cmp_max_to_max(arg) == 0; } uint get_max_key_part() const; /** returns true if all the predicates in the keypart tree are equal */ bool all_same(const SEL_ARG *arg) const { if (type != arg->type || part != arg->part) return false; if (type != KEY_RANGE) return true; if (arg == this) return true; const SEL_ARG *cmp_arg= arg->first(); const SEL_ARG *cur_arg= first(); for (; cur_arg && cmp_arg && cur_arg->is_same(cmp_arg); cur_arg= cur_arg->next, cmp_arg= cmp_arg->next) ; if (cur_arg || cmp_arg) return false; return true; } inline void merge_flags(SEL_ARG *arg) { maybe_flag|=arg->maybe_flag; } inline void maybe_smaller() { maybe_flag=1; } /* Return true iff it's a single-point null interval */ inline bool is_null_interval() { return maybe_null && max_value[0] == 1; } inline int cmp_min_to_min(const SEL_ARG* arg) const { return sel_cmp(field,min_value, arg->min_value, min_flag, arg->min_flag); } inline int cmp_min_to_max(const SEL_ARG* arg) const { return sel_cmp(field,min_value, arg->max_value, min_flag, arg->max_flag); } inline int cmp_max_to_max(const SEL_ARG* arg) const { return sel_cmp(field,max_value, arg->max_value, max_flag, arg->max_flag); } inline int cmp_max_to_min(const SEL_ARG* arg) const { return sel_cmp(field,max_value, arg->min_value, max_flag, arg->min_flag); } SEL_ARG *clone_and(THD *thd, SEL_ARG* arg) { // Get overlapping range uchar *new_min,*new_max; uint8 flag_min,flag_max; if (cmp_min_to_min(arg) >= 0) { new_min=min_value; flag_min=min_flag; } else { new_min=arg->min_value; flag_min=arg->min_flag; /* purecov: deadcode */ } if (cmp_max_to_max(arg) <= 0) { new_max=max_value; flag_max=max_flag; } else { new_max=arg->max_value; flag_max=arg->max_flag; } return new (thd->mem_root) SEL_ARG(field, part, new_min, new_max, flag_min, flag_max, MY_TEST(maybe_flag && arg->maybe_flag)); } SEL_ARG *clone_first(SEL_ARG *arg) { // min <= X < arg->min return new SEL_ARG(field,part, min_value, arg->min_value, min_flag, arg->min_flag & NEAR_MIN ? 0 : NEAR_MAX, maybe_flag | arg->maybe_flag); } SEL_ARG *clone_last(SEL_ARG *arg) { // min <= X <= key_max return new SEL_ARG(field, part, min_value, arg->max_value, min_flag, arg->max_flag, maybe_flag | arg->maybe_flag); } SEL_ARG *clone(RANGE_OPT_PARAM *param, SEL_ARG *new_parent, SEL_ARG **next); bool copy_min(SEL_ARG* arg) { // Get overlapping range if (cmp_min_to_min(arg) > 0) { min_value=arg->min_value; min_flag=arg->min_flag; if ((max_flag & (NO_MAX_RANGE | NO_MIN_RANGE)) == (NO_MAX_RANGE | NO_MIN_RANGE)) return 1; // Full range } maybe_flag|=arg->maybe_flag; return 0; } bool copy_max(SEL_ARG* arg) { // Get overlapping range if (cmp_max_to_max(arg) <= 0) { max_value=arg->max_value; max_flag=arg->max_flag; if ((max_flag & (NO_MAX_RANGE | NO_MIN_RANGE)) == (NO_MAX_RANGE | NO_MIN_RANGE)) return 1; // Full range } maybe_flag|=arg->maybe_flag; return 0; } void copy_min_to_min(SEL_ARG *arg) { min_value=arg->min_value; min_flag=arg->min_flag; } void copy_min_to_max(SEL_ARG *arg) { max_value=arg->min_value; max_flag=arg->min_flag & NEAR_MIN ? 0 : NEAR_MAX; } void copy_max_to_min(SEL_ARG *arg) { min_value=arg->max_value; min_flag=arg->max_flag & NEAR_MAX ? 0 : NEAR_MIN; } /* returns a number of keypart values (0 or 1) appended to the key buffer */ int store_min(uint length, uchar **min_key,uint min_key_flag) { /* "(kp1 > c1) AND (kp2 OP c2) AND ..." -> (kp1 > c1) */ if ((min_flag & GEOM_FLAG) || (!(min_flag & NO_MIN_RANGE) && !(min_key_flag & (NO_MIN_RANGE | NEAR_MIN)))) { if (maybe_null && *min_value) { **min_key=1; bzero(*min_key+1,length-1); } else memcpy(*min_key,min_value,length); (*min_key)+= length; return 1; } return 0; } /* returns a number of keypart values (0 or 1) appended to the key buffer */ int store_max(uint length, uchar **max_key, uint max_key_flag) { if (!(max_flag & NO_MAX_RANGE) && !(max_key_flag & (NO_MAX_RANGE | NEAR_MAX))) { if (maybe_null && *max_value) { **max_key=1; bzero(*max_key+1,length-1); } else memcpy(*max_key,max_value,length); (*max_key)+= length; return 1; } return 0; } /* Returns a number of keypart values appended to the key buffer for min key and max key. This function is used by both Range Analysis and Partition pruning. For partition pruning we have to ensure that we don't store also subpartition fields. Thus we have to stop at the last partition part and not step into the subpartition fields. For Range Analysis we set last_part to MAX_KEY which we should never reach. */ int store_min_key(KEY_PART *key, uchar **range_key, uint *range_key_flag, uint last_part) { SEL_ARG *key_tree= first(); uint res= key_tree->store_min(key[key_tree->part].store_length, range_key, *range_key_flag); // add flags only if a key_part is written to the buffer if (!res) return 0; *range_key_flag|= key_tree->min_flag; if (key_tree->next_key_part && key_tree->next_key_part->type == SEL_ARG::KEY_RANGE && key_tree->part != last_part && key_tree->next_key_part->part == key_tree->part+1 && !(*range_key_flag & (NO_MIN_RANGE | NEAR_MIN))) res+= key_tree->next_key_part->store_min_key(key, range_key, range_key_flag, last_part); return res; } /* returns a number of keypart values appended to the key buffer */ int store_max_key(KEY_PART *key, uchar **range_key, uint *range_key_flag, uint last_part) { SEL_ARG *key_tree= last(); uint res=key_tree->store_max(key[key_tree->part].store_length, range_key, *range_key_flag); if (!res) return 0; *range_key_flag|= key_tree->max_flag; if (key_tree->next_key_part && key_tree->next_key_part->type == SEL_ARG::KEY_RANGE && key_tree->part != last_part && key_tree->next_key_part->part == key_tree->part+1 && !(*range_key_flag & (NO_MAX_RANGE | NEAR_MAX))) res+= key_tree->next_key_part->store_max_key(key, range_key, range_key_flag, last_part); return res; } SEL_ARG *insert(SEL_ARG *key); SEL_ARG *tree_delete(SEL_ARG *key); SEL_ARG *find_range(SEL_ARG *key); SEL_ARG *rb_insert(SEL_ARG *leaf); friend SEL_ARG *rb_delete_fixup(SEL_ARG *root,SEL_ARG *key, SEL_ARG *par); #ifdef EXTRA_DEBUG friend int test_rb_tree(SEL_ARG *element,SEL_ARG *parent); void test_use_count(SEL_ARG *root); #endif SEL_ARG *first(); const SEL_ARG *first() const; SEL_ARG *last(); void make_root(); inline bool simple_key() { return !next_key_part && elements == 1; } void increment_use_count(long count) { if (next_key_part) { next_key_part->use_count+=count; count*= (next_key_part->use_count-count); for (SEL_ARG *pos=next_key_part->first(); pos ; pos=pos->next) if (pos->next_key_part) pos->increment_use_count(count); } } void incr_refs() { increment_use_count(1); use_count++; } void incr_refs_all() { for (SEL_ARG *pos=first(); pos ; pos=pos->next) { pos->increment_use_count(1); } use_count++; } void free_tree() { for (SEL_ARG *pos=first(); pos ; pos=pos->next) if (pos->next_key_part) { pos->next_key_part->use_count--; pos->next_key_part->free_tree(); } } inline SEL_ARG **parent_ptr() { return parent->left == this ? &parent->left : &parent->right; } /* Check if this SEL_ARG object represents a single-point interval SYNOPSIS is_singlepoint() DESCRIPTION Check if this SEL_ARG object (not tree) represents a single-point interval, i.e. if it represents a "keypart = const" or "keypart IS NULL". RETURN TRUE This SEL_ARG object represents a singlepoint interval FALSE Otherwise */ bool is_singlepoint() const { /* Check for NEAR_MIN ("strictly less") and NO_MIN_RANGE (-inf < field) flags, and the same for right edge. */ if (min_flag || max_flag) return FALSE; uchar *min_val= min_value; uchar *max_val= max_value; if (maybe_null) { /* First byte is a NULL value indicator */ if (*min_val != *max_val) return FALSE; if (*min_val) return TRUE; /* This "x IS NULL" */ min_val++; max_val++; } return !field->key_cmp(min_val, max_val); } SEL_ARG *clone_tree(RANGE_OPT_PARAM *param); }; extern MYSQL_PLUGIN_IMPORT SEL_ARG null_element; class SEL_ARG_IMPOSSIBLE: public SEL_ARG { public: SEL_ARG_IMPOSSIBLE(Field *field) :SEL_ARG(field, 0, 0) { type= SEL_ARG::IMPOSSIBLE; } }; class RANGE_OPT_PARAM { public: THD *thd; /* Current thread handle */ TABLE *table; /* Table being analyzed */ table_map prev_tables; table_map read_tables; table_map current_table; /* Bit of the table being analyzed */ /* Array of parts of all keys for which range analysis is performed */ KEY_PART *key_parts; KEY_PART *key_parts_end; MEM_ROOT *mem_root; /* Memory that will be freed when range analysis completes */ MEM_ROOT *old_root; /* Memory that will last until the query end */ /* Number of indexes used in range analysis (In SEL_TREE::keys only first #keys elements are not empty) */ uint keys; /* If true, the index descriptions describe real indexes (and it is ok to call field->optimize_range(real_keynr[...], ...). Otherwise index description describes fake indexes. */ bool using_real_indexes; /* Aggressively remove "scans" that do not have conditions on first keyparts. Such scans are usable when doing partition pruning but not regular range optimization. */ bool remove_jump_scans; /* TRUE <=> Range analyzer should remove parts of condition that are found to be always FALSE. */ bool remove_false_where_parts; /* Which functions should give SQL notes for unusable keys. */ Item_func::Bitmap note_unusable_keys; /* used_key_no -> table_key_no translation table. Only makes sense if using_real_indexes==TRUE */ uint real_keynr[MAX_KEY]; /* Used to store 'current key tuples', in both range analysis and partitioning (list) analysis */ uchar *min_key; uchar *max_key; /* Number of SEL_ARG objects allocated by SEL_ARG::clone_tree operations */ uint alloced_sel_args; bool force_default_mrr; KEY_PART *key[MAX_KEY]; /* First key parts of keys used in the query */ bool statement_should_be_aborted() const { return thd->killed || thd->is_error() || alloced_sel_args > thd->variables.optimizer_max_sel_args; } }; class Explain_quick_select; /* A "MIN_TUPLE < tbl.key_tuple < MAX_TUPLE" interval. One of endpoints may be absent. 'flags' member has flags which tell whether the endpoints are '<' or '<='. */ class QUICK_RANGE :public Sql_alloc { public: uchar *min_key,*max_key; uint16 min_length,max_length,flag; key_part_map min_keypart_map, // bitmap of used keyparts in min_key max_keypart_map; // bitmap of used keyparts in max_key #ifdef HAVE_valgrind uint16 dummy; /* Avoid warnings on 'flag' */ #endif QUICK_RANGE(); /* Full range */ QUICK_RANGE(THD *thd, const uchar *min_key_arg, uint min_length_arg, key_part_map min_keypart_map_arg, const uchar *max_key_arg, uint max_length_arg, key_part_map max_keypart_map_arg, uint flag_arg) : min_key((uchar*) thd->memdup(min_key_arg, min_length_arg + 1)), max_key((uchar*) thd->memdup(max_key_arg, max_length_arg + 1)), min_length((uint16) min_length_arg), max_length((uint16) max_length_arg), flag((uint16) flag_arg), min_keypart_map(min_keypart_map_arg), max_keypart_map(max_keypart_map_arg) { #ifdef HAVE_valgrind dummy=0; #endif } /** Initializes a key_range object for communication with storage engine. This function facilitates communication with the Storage Engine API by translating the minimum endpoint of the interval represented by this QUICK_RANGE into an index range endpoint specifier for the engine. @param Pointer to an uninitialized key_range C struct. @param prefix_length The length of the search key prefix to be used for lookup. @param keypart_map A set (bitmap) of keyparts to be used. */ void make_min_endpoint(key_range *kr, uint prefix_length, key_part_map keypart_map) { make_min_endpoint(kr); kr->length= MY_MIN(kr->length, prefix_length); kr->keypart_map&= keypart_map; } /** Initializes a key_range object for communication with storage engine. This function facilitates communication with the Storage Engine API by translating the minimum endpoint of the interval represented by this QUICK_RANGE into an index range endpoint specifier for the engine. @param Pointer to an uninitialized key_range C struct. */ void make_min_endpoint(key_range *kr) { kr->key= (const uchar*)min_key; kr->length= min_length; kr->keypart_map= min_keypart_map; kr->flag= ((flag & NEAR_MIN) ? HA_READ_AFTER_KEY : (flag & EQ_RANGE) ? HA_READ_KEY_EXACT : HA_READ_KEY_OR_NEXT); } /** Initializes a key_range object for communication with storage engine. This function facilitates communication with the Storage Engine API by translating the maximum endpoint of the interval represented by this QUICK_RANGE into an index range endpoint specifier for the engine. @param Pointer to an uninitialized key_range C struct. @param prefix_length The length of the search key prefix to be used for lookup. @param keypart_map A set (bitmap) of keyparts to be used. */ void make_max_endpoint(key_range *kr, uint prefix_length, key_part_map keypart_map) { make_max_endpoint(kr); kr->length= MY_MIN(kr->length, prefix_length); kr->keypart_map&= keypart_map; } /** Initializes a key_range object for communication with storage engine. This function facilitates communication with the Storage Engine API by translating the maximum endpoint of the interval represented by this QUICK_RANGE into an index range endpoint specifier for the engine. @param Pointer to an uninitialized key_range C struct. */ void make_max_endpoint(key_range *kr) { kr->key= (const uchar*)max_key; kr->length= max_length; kr->keypart_map= max_keypart_map; /* We use READ_AFTER_KEY here because if we are reading on a key prefix we want to find all keys with this prefix */ kr->flag= (flag & NEAR_MAX ? HA_READ_BEFORE_KEY : HA_READ_AFTER_KEY); } }; /* Quick select interface. This class is a parent for all QUICK_*_SELECT and FT_SELECT classes. The usage scenario is as follows: 1. Create quick select quick= new QUICK_XXX_SELECT(...); 2. Perform lightweight initialization. This can be done in 2 ways: 2.a: Regular initialization if (quick->init()) { //the only valid action after failed init() call is delete delete quick; } 2.b: Special initialization for quick selects merged by QUICK_ROR_*_SELECT if (quick->init_ror_merged_scan()) delete quick; 3. Perform zero, one, or more scans. while (...) { // initialize quick select for scan. This may allocate // buffers and/or prefetch rows. if (quick->reset()) { //the only valid action after failed reset() call is delete delete quick; //abort query } // perform the scan do { res= quick->get_next(); } while (res && ...) } 4. Delete the select: delete quick; NOTE quick select doesn't use Sql_alloc/MEM_ROOT allocation because "range checked for each record" functionality may create/destroy O(#records_in_some_table) quick selects during query execution. */ class QUICK_SELECT_I { public: ha_rows records; /* estimate of # of records to be retrieved */ double read_time; /* time to perform this retrieval */ TABLE *head; /* Index this quick select uses, or MAX_KEY for quick selects that use several indexes */ uint index; /* Total length of first used_key_parts parts of the key. Applicable if index!= MAX_KEY. */ uint max_used_key_length; /* Max. number of (first) key parts this quick select uses for retrieval. eg. for "(key1p1=c1 AND key1p2=c2) OR key1p1=c2" used_key_parts == 2. Applicable if index!= MAX_KEY. For QUICK_GROUP_MIN_MAX_SELECT it includes MIN/MAX argument keyparts. */ uint used_key_parts; QUICK_SELECT_I(); virtual ~QUICK_SELECT_I() = default;; /* Do post-constructor initialization. SYNOPSIS init() init() performs initializations that should have been in constructor if it was possible to return errors from constructors. The join optimizer may create and then delete quick selects without retrieving any rows so init() must not contain any IO or CPU intensive code. If init() call fails the only valid action is to delete this quick select, reset() and get_next() must not be called. RETURN 0 OK other Error code */ virtual int init() = 0; /* Initialize quick select for row retrieval. SYNOPSIS reset() reset() should be called when it is certain that row retrieval will be necessary. This call may do heavyweight initialization like buffering first N records etc. If reset() call fails get_next() must not be called. Note that reset() may be called several times if * the quick select is executed in a subselect * a JOIN buffer is used RETURN 0 OK other Error code */ virtual int reset(void) = 0; virtual int get_next() = 0; /* get next record to retrieve */ /* Range end should be called when we have looped over the whole index */ virtual void range_end() {} virtual bool reverse_sorted() = 0; virtual bool unique_key_range() { return false; } /* Request that this quick select produces sorted output. Not all quick selects can do it, the caller is responsible for calling this function only for those quick selects that can. */ virtual void need_sorted_output() = 0; enum { QS_TYPE_RANGE = 0, QS_TYPE_INDEX_INTERSECT = 1, QS_TYPE_INDEX_MERGE = 2, QS_TYPE_RANGE_DESC = 3, QS_TYPE_FULLTEXT = 4, QS_TYPE_ROR_INTERSECT = 5, QS_TYPE_ROR_UNION = 6, QS_TYPE_GROUP_MIN_MAX = 7 }; /* Get type of this quick select - one of the QS_TYPE_* values */ virtual int get_type() = 0; /* Initialize this quick select as a merged scan inside a ROR-union or a ROR- intersection scan. The caller must not additionally call init() if this function is called. SYNOPSIS init_ror_merged_scan() reuse_handler If true, the quick select may use table->handler, otherwise it must create and use a separate handler object. RETURN 0 Ok other Error */ virtual int init_ror_merged_scan(bool reuse_handler, MEM_ROOT *alloc) { DBUG_ASSERT(0); return 1; } /* Save ROWID of last retrieved row in file->ref. This used in ROR-merging. */ virtual void save_last_pos(){}; void add_key_and_length(String *key_names, String *used_lengths, bool *first); /* Append comma-separated list of keys this quick select uses to key_names; append comma-separated list of corresponding used lengths to used_lengths. This is used by select_describe. */ virtual void add_keys_and_lengths(String *key_names, String *used_lengths)=0; void add_key_name(String *str, bool *first); /* Save information about quick select's query plan */ virtual Explain_quick_select* get_explain(MEM_ROOT *alloc)= 0; /* Return 1 if any index used by this quick select uses field which is marked in passed bitmap. */ virtual bool is_keys_used(const MY_BITMAP *fields); /** Simple sanity check that the quick select has been set up correctly. Function is overridden by quick selects that merge indices. */ virtual bool is_valid() { return index != MAX_KEY; }; /* rowid of last row retrieved by this quick select. This is used only when doing ROR-index_merge selects */ uchar *last_rowid; /* Table record buffer used by this quick select. */ uchar *record; virtual void replace_handler(handler *new_file) { DBUG_ASSERT(0); /* Only supported in QUICK_RANGE_SELECT */ } #ifndef DBUG_OFF /* Print quick select information to DBUG_FILE. Caller is responsible for locking DBUG_FILE before this call and unlocking it afterwards. */ virtual void dbug_dump(int indent, bool verbose)= 0; #endif /* Returns a QUICK_SELECT with reverse order of to the index. */ virtual QUICK_SELECT_I *make_reverse(uint used_key_parts_arg) { return NULL; } /* Add the key columns used by the quick select into table's read set. This is used by an optimization in filesort. */ virtual void add_used_key_part_to_set()=0; }; struct st_qsel_param; class PARAM; /* MRR range sequence, array implementation: sequence traversal context. */ typedef struct st_quick_range_seq_ctx { QUICK_RANGE **first; QUICK_RANGE **cur; QUICK_RANGE **last; } QUICK_RANGE_SEQ_CTX; range_seq_t quick_range_seq_init(void *init_param, uint n_ranges, uint flags); bool quick_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range); /* Quick select that does a range scan on a single key. The records are returned in key order. */ class QUICK_RANGE_SELECT : public QUICK_SELECT_I { protected: THD *thd; bool no_alloc; MEM_ROOT *parent_alloc; /* true if we enabled key only reads */ handler *file; /* Members to deal with case when this quick select is a ROR-merged scan */ bool in_ror_merged_scan; MY_BITMAP column_bitmap; bool free_file; /* TRUE <=> this->file is "owned" by this quick select */ /* Range pointers to be used when not using MRR interface */ /* Members needed to use the MRR interface */ QUICK_RANGE_SEQ_CTX qr_traversal_ctx; public: uint mrr_flags; /* Flags to be used with MRR interface */ protected: uint mrr_buf_size; /* copy from thd->variables.mrr_buff_size */ HANDLER_BUFFER *mrr_buf_desc; /* the handler buffer */ /* Info about index we're scanning */ DYNAMIC_ARRAY ranges; /* ordered array of range ptrs */ QUICK_RANGE **cur_range; /* current element in ranges */ QUICK_RANGE *last_range; KEY_PART *key_parts; KEY_PART_INFO *key_part_info; bool dont_free; /* Used by QUICK_SELECT_DESC */ int cmp_next(QUICK_RANGE *range); int cmp_prev(QUICK_RANGE *range); bool row_in_ranges(); public: MEM_ROOT alloc; QUICK_RANGE_SELECT(THD *thd, TABLE *table,uint index_arg,bool no_alloc, MEM_ROOT *parent_alloc, bool *create_err); ~QUICK_RANGE_SELECT(); virtual QUICK_RANGE_SELECT *clone(bool *create_error) { return new QUICK_RANGE_SELECT(thd, head, index, no_alloc, parent_alloc, create_error); } void need_sorted_output() override; int init() override; int reset(void) override; int get_next() override; void range_end() override; int get_next_prefix(uint prefix_length, uint group_key_parts, uchar *cur_prefix); bool reverse_sorted() override { return 0; } bool unique_key_range() override; int init_ror_merged_scan(bool reuse_handler, MEM_ROOT *alloc) override; void save_last_pos() override { file->position(record); } int get_type() override { return QS_TYPE_RANGE; } void add_keys_and_lengths(String *key_names, String *used_lengths) override; Explain_quick_select *get_explain(MEM_ROOT *alloc) override; #ifndef DBUG_OFF void dbug_dump(int indent, bool verbose) override; #endif void replace_handler(handler *new_file) override { file= new_file; } QUICK_SELECT_I *make_reverse(uint used_key_parts_arg) override; void add_used_key_part_to_set() override; private: /* Default copy ctor used by QUICK_SELECT_DESC */ friend class TRP_ROR_INTERSECT; friend QUICK_RANGE_SELECT *get_quick_select_for_ref(THD *thd, TABLE *table, struct st_table_ref *ref, ha_rows records); friend bool get_quick_keys(PARAM *param, QUICK_RANGE_SELECT *quick, KEY_PART *key, SEL_ARG *key_tree, uchar *min_key, uint min_key_flag, uchar *max_key, uint max_key_flag); friend QUICK_RANGE_SELECT *get_quick_select(PARAM*,uint idx, SEL_ARG *key_tree, uint mrr_flags, uint mrr_buf_size, MEM_ROOT *alloc); friend class QUICK_SELECT_DESC; friend class QUICK_INDEX_SORT_SELECT; friend class QUICK_INDEX_MERGE_SELECT; friend class QUICK_ROR_INTERSECT_SELECT; friend class QUICK_INDEX_INTERSECT_SELECT; friend class QUICK_GROUP_MIN_MAX_SELECT; friend bool quick_range_seq_next(range_seq_t rseq, KEY_MULTI_RANGE *range); friend range_seq_t quick_range_seq_init(void *init_param, uint n_ranges, uint flags); friend int read_keys_and_merge_scans(THD *thd, TABLE *head, List quick_selects, QUICK_RANGE_SELECT *pk_quick_select, READ_RECORD *read_record, bool intersection, key_map *filtered_scans, Unique **unique_ptr); }; class QUICK_RANGE_SELECT_GEOM: public QUICK_RANGE_SELECT { public: QUICK_RANGE_SELECT_GEOM(THD *thd, TABLE *table, uint index_arg, bool no_alloc, MEM_ROOT *parent_alloc, bool *create_err) :QUICK_RANGE_SELECT(thd, table, index_arg, no_alloc, parent_alloc, create_err) {}; QUICK_RANGE_SELECT *clone(bool *create_error) override { DBUG_ASSERT(0); return new QUICK_RANGE_SELECT_GEOM(thd, head, index, no_alloc, parent_alloc, create_error); } int get_next() override; }; /* QUICK_INDEX_SORT_SELECT is the base class for the common functionality of: - QUICK_INDEX_MERGE_SELECT, access based on multi-index merge/union - QUICK_INDEX_INTERSECT_SELECT, access based on multi-index intersection QUICK_INDEX_SORT_SELECT uses * QUICK_RANGE_SELECTs to get rows * Unique class - to remove duplicate rows for QUICK_INDEX_MERGE_SELECT - to intersect rows for QUICK_INDEX_INTERSECT_SELECT INDEX MERGE OPTIMIZER Current implementation doesn't detect all cases where index merge could be used, in particular: * index_merge+'using index' is not supported * If WHERE part contains complex nested AND and OR conditions, some ways to retrieve rows using index merge will not be considered. The choice of read plan may depend on the order of conjuncts/disjuncts in WHERE part of the query, see comments near imerge_list_or_list and SEL_IMERGE::or_sel_tree_with_checks functions for details. * There is no "index_merge_ref" method (but index merge on non-first table in join is possible with 'range checked for each record'). ROW RETRIEVAL ALGORITHM index merge/intersection uses Unique class for duplicates removal. index merge/intersection takes advantage of Clustered Primary Key (CPK) if the table has one. The index merge/intersection algorithm consists of two phases: Phase 1 (implemented by a QUICK_INDEX_MERGE_SELECT::read_keys_and_merge call): prepare() { activate 'index only'; while(retrieve next row for non-CPK scan) { if (there is a CPK scan and row will be retrieved by it) skip this row; else put its rowid into Unique; } deactivate 'index only'; } Phase 2 (implemented as sequence of QUICK_INDEX_MERGE_SELECT::get_next calls): fetch() { retrieve all rows from row pointers stored in Unique (merging/intersecting them); free Unique; if (! intersection) retrieve all rows for CPK scan; } */ class QUICK_INDEX_SORT_SELECT : public QUICK_SELECT_I { protected: Unique *unique; public: QUICK_INDEX_SORT_SELECT(THD *thd, TABLE *table); ~QUICK_INDEX_SORT_SELECT(); int init() override; void need_sorted_output() override { DBUG_ASSERT(0); /* Can't do it */ } int reset(void) override; bool reverse_sorted() override { return false; } bool unique_key_range() override { return false; } bool is_keys_used(const MY_BITMAP *fields) override; #ifndef DBUG_OFF void dbug_dump(int indent, bool verbose) override; #endif Explain_quick_select *get_explain(MEM_ROOT *alloc) override; bool push_quick_back(QUICK_RANGE_SELECT *quick_sel_range); /* range quick selects this index merge/intersect consists of */ List quick_selects; /* quick select that uses clustered primary key (NULL if none) */ QUICK_RANGE_SELECT* pk_quick_select; MEM_ROOT alloc; THD *thd; bool is_valid() override { List_iterator_fast it(quick_selects); QUICK_RANGE_SELECT *quick; bool valid= true; while ((quick= it++)) { if (!quick->is_valid()) { valid= false; break; } } return valid; } virtual int read_keys_and_merge()= 0; /* used to get rows collected in Unique */ READ_RECORD read_record; void add_used_key_part_to_set() override; }; class QUICK_INDEX_MERGE_SELECT : public QUICK_INDEX_SORT_SELECT { private: /* true if this select is currently doing a clustered PK scan */ bool doing_pk_scan; protected: int read_keys_and_merge() override; public: QUICK_INDEX_MERGE_SELECT(THD *thd_arg, TABLE *table) :QUICK_INDEX_SORT_SELECT(thd_arg, table) {} int get_next() override; int get_type() override { return QS_TYPE_INDEX_MERGE; } void add_keys_and_lengths(String *key_names, String *used_lengths) override; }; class QUICK_INDEX_INTERSECT_SELECT : public QUICK_INDEX_SORT_SELECT { protected: int read_keys_and_merge() override; public: QUICK_INDEX_INTERSECT_SELECT(THD *thd_arg, TABLE *table) :QUICK_INDEX_SORT_SELECT(thd_arg, table) {} key_map filtered_scans; int get_next() override; int get_type() override { return QS_TYPE_INDEX_INTERSECT; } void add_keys_and_lengths(String *key_names, String *used_lengths) override; Explain_quick_select *get_explain(MEM_ROOT *alloc) override; }; /* Rowid-Ordered Retrieval (ROR) index intersection quick select. This quick select produces intersection of row sequences returned by several QUICK_RANGE_SELECTs it "merges". All merged QUICK_RANGE_SELECTs must return rowids in rowid order. QUICK_ROR_INTERSECT_SELECT will return rows in rowid order, too. All merged quick selects retrieve {rowid, covered_fields} tuples (not full table records). QUICK_ROR_INTERSECT_SELECT retrieves full records if it is not being used by QUICK_ROR_INTERSECT_SELECT and all merged quick selects together don't cover needed all fields. If one of the merged quick selects is a Clustered PK range scan, it is used only to filter rowid sequence produced by other merged quick selects. */ class QUICK_ROR_INTERSECT_SELECT : public QUICK_SELECT_I { public: QUICK_ROR_INTERSECT_SELECT(THD *thd, TABLE *table, bool retrieve_full_rows, MEM_ROOT *parent_alloc); ~QUICK_ROR_INTERSECT_SELECT(); int init() override; void need_sorted_output() override { DBUG_ASSERT(0); /* Can't do it */ } int reset(void) override; int get_next() override; bool reverse_sorted() override { return false; } bool unique_key_range() override { return false; } int get_type() override { return QS_TYPE_ROR_INTERSECT; } void add_keys_and_lengths(String *key_names, String *used_lengths) override; Explain_quick_select *get_explain(MEM_ROOT *alloc) override; bool is_keys_used(const MY_BITMAP *fields) override; void add_used_key_part_to_set() override; #ifndef DBUG_OFF void dbug_dump(int indent, bool verbose) override; #endif int init_ror_merged_scan(bool reuse_handler, MEM_ROOT *alloc) override; bool push_quick_back(MEM_ROOT *alloc, QUICK_RANGE_SELECT *quick_sel_range); class QUICK_SELECT_WITH_RECORD : public Sql_alloc { public: QUICK_RANGE_SELECT *quick; uchar *key_tuple; ~QUICK_SELECT_WITH_RECORD() { delete quick; } }; /* Range quick selects this intersection consists of, not including cpk_quick. */ List quick_selects; bool is_valid() override { List_iterator_fast it(quick_selects); QUICK_SELECT_WITH_RECORD *quick; bool valid= true; while ((quick= it++)) { if (!quick->quick->is_valid()) { valid= false; break; } } return valid; } /* Merged quick select that uses Clustered PK, if there is one. This quick select is not used for row retrieval, it is used for row retrieval. */ QUICK_RANGE_SELECT *cpk_quick; MEM_ROOT alloc; /* Memory pool for this and merged quick selects data. */ THD *thd; /* current thread */ bool need_to_fetch_row; /* if true, do retrieve full table records. */ /* in top-level quick select, true if merged scans where initialized */ bool scans_inited; }; /* Rowid-Ordered Retrieval index union select. This quick select produces union of row sequences returned by several quick select it "merges". All merged quick selects must return rowids in rowid order. QUICK_ROR_UNION_SELECT will return rows in rowid order, too. All merged quick selects are set not to retrieve full table records. ROR-union quick select always retrieves full records. */ class QUICK_ROR_UNION_SELECT : public QUICK_SELECT_I { public: QUICK_ROR_UNION_SELECT(THD *thd, TABLE *table); ~QUICK_ROR_UNION_SELECT(); int init() override; void need_sorted_output() override { DBUG_ASSERT(0); /* Can't do it */ } int reset(void) override; int get_next() override; bool reverse_sorted() override { return false; } bool unique_key_range() override { return false; } int get_type() override { return QS_TYPE_ROR_UNION; } void add_keys_and_lengths(String *key_names, String *used_lengths) override; Explain_quick_select *get_explain(MEM_ROOT *alloc) override; bool is_keys_used(const MY_BITMAP *fields) override; void add_used_key_part_to_set() override; #ifndef DBUG_OFF void dbug_dump(int indent, bool verbose) override; #endif bool push_quick_back(QUICK_SELECT_I *quick_sel_range); List quick_selects; /* Merged quick selects */ bool is_valid() override { List_iterator_fast it(quick_selects); QUICK_SELECT_I *quick; bool valid= true; while ((quick= it++)) { if (!quick->is_valid()) { valid= false; break; } } return valid; } QUEUE queue; /* Priority queue for merge operation */ MEM_ROOT alloc; /* Memory pool for this and merged quick selects data. */ THD *thd; /* current thread */ uchar *cur_rowid; /* buffer used in get_next() */ uchar *prev_rowid; /* rowid of last row returned by get_next() */ bool have_prev_rowid; /* true if prev_rowid has valid data */ uint rowid_length; /* table rowid length */ private: bool scans_inited; }; /* Index scan for GROUP-BY queries with MIN/MAX aggregate functions. This class provides a specialized index access method for GROUP-BY queries of the forms: SELECT A_1,...,A_k, [B_1,...,B_m], [MIN(C)], [MAX(C)] FROM T WHERE [RNG(A_1,...,A_p ; where p <= k)] [AND EQ(B_1,...,B_m)] [AND PC(C)] [AND PA(A_i1,...,A_iq)] GROUP BY A_1,...,A_k; or SELECT DISTINCT A_i1,...,A_ik FROM T WHERE [RNG(A_1,...,A_p ; where p <= k)] [AND PA(A_i1,...,A_iq)]; where all selected fields are parts of the same index. The class of queries that can be processed by this quick select is fully specified in the description of get_best_trp_group_min_max() in opt_range.cc. The get_next() method directly produces result tuples, thus obviating the need to call end_send_group() because all grouping is already done inside get_next(). Since one of the requirements is that all select fields are part of the same index, this class produces only index keys, and not complete records. */ class QUICK_GROUP_MIN_MAX_SELECT : public QUICK_SELECT_I { private: handler * const file; /* The handler used to get data. */ JOIN *join; /* Descriptor of the current query */ KEY *index_info; /* The index chosen for data access */ uchar *record; /* Buffer where the next record is returned. */ uchar *tmp_record; /* Temporary storage for next_min(), next_max(). */ uchar *group_prefix; /* Key prefix consisting of the GROUP fields. */ const uint group_prefix_len; /* Length of the group prefix. */ uint group_key_parts; /* A number of keyparts in the group prefix */ bool have_min; /* Specify whether we are computing */ bool have_max; /* a MIN, a MAX, or both. */ bool have_agg_distinct;/* aggregate_function(DISTINCT ...). */ bool seen_first_key; /* Denotes whether the first key was retrieved.*/ bool doing_key_read; /* true if we enabled key only reads */ KEY_PART_INFO *min_max_arg_part; /* The keypart of the only argument field */ /* of all MIN/MAX functions. */ uint min_max_arg_len; /* The length of the MIN/MAX argument field */ uchar *key_infix; /* Infix of constants from equality predicates. */ uint key_infix_len; DYNAMIC_ARRAY min_max_ranges; /* Array of range ptrs for the MIN/MAX field. */ uint real_prefix_len; /* Length of key prefix extended with key_infix. */ uint real_key_parts; /* A number of keyparts in the above value. */ List *min_functions; List *max_functions; List_iterator *min_functions_it; List_iterator *max_functions_it; /* Use index scan to get the next different key instead of jumping into it through index read */ bool is_index_scan; public: /* The following two members are public to allow easy access from TRP_GROUP_MIN_MAX::make_quick() */ MEM_ROOT alloc; /* Memory pool for this and quick_prefix_select data. */ QUICK_RANGE_SELECT *quick_prefix_select;/* For retrieval of group prefixes. */ private: int next_prefix(); int next_min_in_range(); int next_max_in_range(); int next_min(); int next_max(); void update_min_result(); void update_max_result(); int cmp_min_max_key(const uchar *key, uint16 length); public: QUICK_GROUP_MIN_MAX_SELECT(TABLE *table, JOIN *join, bool have_min, bool have_max, bool have_agg_distinct, KEY_PART_INFO *min_max_arg_part, uint group_prefix_len, uint group_key_parts, uint used_key_parts, KEY *index_info, uint use_index, double read_cost, ha_rows records, uint key_infix_len, uchar *key_infix, MEM_ROOT *parent_alloc, bool is_index_scan); ~QUICK_GROUP_MIN_MAX_SELECT(); bool add_range(SEL_ARG *sel_range); void update_key_stat(); void adjust_prefix_ranges(); bool alloc_buffers(); int init() override; void need_sorted_output() override { /* always do it */ } int reset() override; int get_next() override; bool reverse_sorted() override { return false; } bool unique_key_range() override { return false; } int get_type() override { return QS_TYPE_GROUP_MIN_MAX; } void add_keys_and_lengths(String *key_names, String *used_lengths) override; void add_used_key_part_to_set() override; #ifndef DBUG_OFF void dbug_dump(int indent, bool verbose) override; #endif bool is_agg_distinct() { return have_agg_distinct; } bool loose_scan_is_scanning() { return is_index_scan; } Explain_quick_select *get_explain(MEM_ROOT *alloc) override; }; class QUICK_SELECT_DESC: public QUICK_RANGE_SELECT { public: QUICK_SELECT_DESC(QUICK_RANGE_SELECT *q, uint used_key_parts); QUICK_RANGE_SELECT *clone(bool *create_error) override { DBUG_ASSERT(0); return new QUICK_SELECT_DESC(this, used_key_parts); } int get_next() override; bool reverse_sorted() override { return 1; } int get_type() override { return QS_TYPE_RANGE_DESC; } QUICK_SELECT_I *make_reverse(uint used_key_parts_arg) override { return this; // is already reverse sorted } private: bool range_reads_after_key(QUICK_RANGE *range); int reset(void) override { rev_it.rewind(); return QUICK_RANGE_SELECT::reset(); } List rev_ranges; List_iterator rev_it; uint used_key_parts; }; class SQL_SELECT :public Sql_alloc { public: QUICK_SELECT_I *quick; // If quick-select used COND *cond; // where condition /* When using Index Condition Pushdown: condition that we've had before extracting and pushing index condition. In other cases, NULL. */ Item *pre_idx_push_select_cond; TABLE *head; IO_CACHE file; // Positions to used records ha_rows records; // Records in use if read from file double read_time; // Time to read rows key_map quick_keys; // Possible quick keys key_map needed_reg; // Possible quick keys after prev tables. table_map const_tables,read_tables; /* See PARAM::possible_keys */ key_map possible_keys; bool free_cond; /* Currently not used and always FALSE */ SQL_SELECT(); ~SQL_SELECT(); void cleanup(); void set_quick(QUICK_SELECT_I *new_quick) { delete quick; quick= new_quick; } /* @return true - for ERROR and IMPOSSIBLE_RANGE false - Ok */ bool check_quick(THD *thd, bool force_quick_range, ha_rows limit, Item_func::Bitmap note_unusable_keys) { key_map tmp; tmp.set_all(); return test_quick_select(thd, tmp, 0, limit, force_quick_range, FALSE, FALSE, FALSE, note_unusable_keys) != OK; } /* RETURN 0 if record must be skipped <-> (cond && cond->val_bool() == false) -1 if error 1 otherwise */ inline int skip_record(THD *thd) { int rc= MY_TEST(!cond || cond->val_bool()); if (thd->is_error()) rc= -1; return rc; } enum quick_select_return_type { IMPOSSIBLE_RANGE = -1, ERROR, OK }; enum quick_select_return_type test_quick_select(THD *thd, key_map keys, table_map prev_tables, ha_rows limit, bool force_quick_range, bool ordered_output, bool remove_false_parts_of_where, bool only_single_index_range_scan, Item_func::Bitmap note_unusable_keys); }; typedef enum SQL_SELECT::quick_select_return_type quick_select_return; class SQL_SELECT_auto { SQL_SELECT *select; public: SQL_SELECT_auto(): select(NULL) {} ~SQL_SELECT_auto() { delete select; } SQL_SELECT_auto& operator= (SQL_SELECT *_select) { select= _select; return *this; } operator SQL_SELECT * () const { return select; } SQL_SELECT * operator-> () const { return select; } operator bool () const { return select; } }; class FT_SELECT: public QUICK_RANGE_SELECT { public: FT_SELECT(THD *thd, TABLE *table, uint key, bool *create_err) : QUICK_RANGE_SELECT (thd, table, key, 1, NULL, create_err) { (void) init(); } ~FT_SELECT() { file->ft_end(); } QUICK_RANGE_SELECT *clone(bool *create_error) override { DBUG_ASSERT(0); return new FT_SELECT(thd, head, index, create_error); } int init() override { return file->ft_init(); } int reset() override { return 0; } int get_next() override { return file->ha_ft_read(record); } int get_type() override { return QS_TYPE_FULLTEXT; } }; FT_SELECT *get_ft_select(THD *thd, TABLE *table, uint key); QUICK_RANGE_SELECT *get_quick_select_for_ref(THD *thd, TABLE *table, struct st_table_ref *ref, ha_rows records); SQL_SELECT *make_select(TABLE *head, table_map const_tables, table_map read_tables, COND *conds, SORT_INFO* filesort, bool allow_null_cond, int *error); bool calculate_cond_selectivity_for_table(THD *thd, TABLE *table, Item **cond); bool eq_ranges_exceeds_limit(RANGE_SEQ_IF *seq, void *seq_init_param, uint limit); #ifdef WITH_PARTITION_STORAGE_ENGINE bool prune_partitions(THD *thd, TABLE *table, Item *pprune_cond); #endif void store_key_image_to_rec(Field *field, uchar *ptr, uint len); extern String null_string; /* check this number of rows (default value) */ #define SELECTIVITY_SAMPLING_LIMIT 100 /* but no more then this part of table (10%) */ #define SELECTIVITY_SAMPLING_SHARE 0.10 /* do not check if we are going check less then this number of records */ #define SELECTIVITY_SAMPLING_THRESHOLD 10 #endif mysql/server/private/my_bitmap.h000064400000013372151027430560013034 0ustar00/* Copyright (c) 2001, 2011, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_bitmap_h_ #define _my_bitmap_h_ #define MY_BIT_NONE (~(uint) 0) #include #include typedef ulonglong my_bitmap_map; typedef struct st_bitmap { my_bitmap_map *bitmap; my_bitmap_map *last_word_ptr; /* mutex will be acquired for the duration of each bitmap operation if thread_safe flag in bitmap_init was set. Otherwise, we optimize by not acquiring the mutex */ mysql_mutex_t *mutex; my_bitmap_map last_bit_mask; uint32 n_bits; /* number of bits occupied by the above */ my_bool bitmap_allocated; } MY_BITMAP; #ifdef __cplusplus extern "C" { #endif /* Reset memory. Faster then doing a full bzero */ #define my_bitmap_clear(A) ((A)->bitmap= 0) extern void create_last_bit_mask(MY_BITMAP *map); extern my_bool my_bitmap_init(MY_BITMAP *map, my_bitmap_map *buf, uint n_bits, my_bool thread_safe); extern my_bool bitmap_is_clear_all(const MY_BITMAP *map); extern my_bool bitmap_is_prefix(const MY_BITMAP *map, uint prefix_size); extern my_bool bitmap_is_set_all(const MY_BITMAP *map); extern my_bool bitmap_is_subset(const MY_BITMAP *map1, const MY_BITMAP *map2); extern my_bool bitmap_is_overlapping(const MY_BITMAP *map1, const MY_BITMAP *map2); extern my_bool bitmap_test_and_set(MY_BITMAP *map, uint bitmap_bit); extern my_bool bitmap_test_and_clear(MY_BITMAP *map, uint bitmap_bit); extern my_bool bitmap_fast_test_and_set(MY_BITMAP *map, uint bitmap_bit); extern my_bool bitmap_fast_test_and_clear(MY_BITMAP *map, uint bitmap_bit); extern my_bool bitmap_union_is_set_all(const MY_BITMAP *map1, const MY_BITMAP *map2); extern my_bool bitmap_exists_intersection(MY_BITMAP **bitmap_array, uint bitmap_count, uint start_bit, uint end_bit); extern uint bitmap_set_next(MY_BITMAP *map); extern uint bitmap_get_first_clear(const MY_BITMAP *map); extern uint bitmap_get_first_set(const MY_BITMAP *map); extern uint bitmap_bits_set(const MY_BITMAP *map); extern uint bitmap_get_next_set(const MY_BITMAP *map, uint bitmap_bit); extern void my_bitmap_free(MY_BITMAP *map); extern void bitmap_set_above(MY_BITMAP *map, uint from_byte, uint use_bit); extern void bitmap_set_prefix(MY_BITMAP *map, uint prefix_size); extern void bitmap_intersect(MY_BITMAP *map, const MY_BITMAP *map2); extern void bitmap_subtract(MY_BITMAP *map, const MY_BITMAP *map2); extern void bitmap_union(MY_BITMAP *map, const MY_BITMAP *map2); extern void bitmap_xor(MY_BITMAP *map, const MY_BITMAP *map2); extern void bitmap_invert(MY_BITMAP *map); extern void bitmap_copy(MY_BITMAP *map, const MY_BITMAP *map2); /* Functions to export/import bitmaps to an architecture independent format */ extern void bitmap_export(uchar *to, MY_BITMAP *map); extern void bitmap_import(MY_BITMAP *map, uchar *from); extern uint bitmap_lock_set_next(MY_BITMAP *map); extern void bitmap_lock_clear_bit(MY_BITMAP *map, uint bitmap_bit); #define my_bitmap_map_bytes sizeof(my_bitmap_map) #define my_bitmap_map_bits (my_bitmap_map_bytes*8) /* Size in bytes to store 'bits' number of bits */ #define bitmap_buffer_size(bits) (MY_ALIGN((bits), my_bitmap_map_bits)/8) #define my_bitmap_buffer_size(map) bitmap_buffer_size((map)->n_bits) #define no_bytes_in_export_map(map) (((map)->n_bits + 7)/8) #define no_words_in_map(map) (((map)->n_bits + (my_bitmap_map_bits-1))/my_bitmap_map_bits) /* Fast, not thread safe, bitmap functions */ /* The following functions must be compatible with create_last_bit_mask()! */ static inline void bitmap_set_bit(MY_BITMAP *map,uint bit) { DBUG_ASSERT(bit < map->n_bits); map->bitmap[bit/my_bitmap_map_bits]|= (1ULL << (bit & (my_bitmap_map_bits-1))); } static inline void bitmap_flip_bit(MY_BITMAP *map,uint bit) { DBUG_ASSERT(bit < map->n_bits); map->bitmap[bit/my_bitmap_map_bits]^= (1ULL << (bit & (my_bitmap_map_bits-1))); } static inline void bitmap_clear_bit(MY_BITMAP *map,uint bit) { DBUG_ASSERT(bit < map->n_bits); map->bitmap[bit/my_bitmap_map_bits]&= ~(1ULL << (bit & (my_bitmap_map_bits-1))); } static inline uint bitmap_is_set(const MY_BITMAP *map,uint bit) { DBUG_ASSERT(bit < map->n_bits); return (!!(map->bitmap[bit/my_bitmap_map_bits] & (1ULL << (bit & (my_bitmap_map_bits-1))))); } /* Return true if bitmaps are equal */ static inline my_bool bitmap_cmp(const MY_BITMAP *map1, const MY_BITMAP *map2) { DBUG_ASSERT(map1->n_bits == map2->n_bits); return (memcmp(map1->bitmap, map2->bitmap, my_bitmap_buffer_size(map1)) == 0); } #define bitmap_clear_all(MAP) \ { memset((MAP)->bitmap, 0, my_bitmap_buffer_size(MAP)); } static inline void bitmap_set_all(const MY_BITMAP *map) { if (map->n_bits) { memset(map->bitmap, 0xFF, my_bitmap_map_bytes * (no_words_in_map(map)-1)); DBUG_ASSERT(map->bitmap + no_words_in_map(map)-1 == map->last_word_ptr); *map->last_word_ptr= ~map->last_bit_mask; } } #ifdef __cplusplus } #endif #endif /* _my_bitmap_h_ */ mysql/server/private/ha_partition.h000064400000175541151027430560013543 0ustar00#ifndef HA_PARTITION_INCLUDED #define HA_PARTITION_INCLUDED /* Copyright (c) 2005, 2012, Oracle and/or its affiliates. Copyright (c) 2009, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_partition.h" /* part_id_range, partition_element */ #include "queues.h" /* QUEUE */ struct Ordered_blob_storage { String blob; bool set_read_value; Ordered_blob_storage() : set_read_value(false) {} }; #define PAR_EXT ".par" #define PARTITION_BYTES_IN_POS 2 #define ORDERED_PART_NUM_OFFSET sizeof(Ordered_blob_storage **) #define ORDERED_REC_OFFSET (ORDERED_PART_NUM_OFFSET + PARTITION_BYTES_IN_POS) /** Struct used for partition_name_hash */ typedef struct st_part_name_def { uchar *partition_name; uint length; uint32 part_id; my_bool is_subpart; } PART_NAME_DEF; /** class where to save partitions Handler_share's */ class Parts_share_refs { public: uint num_parts; /**< Size of ha_share array */ Handler_share **ha_shares; /**< Storage for each part */ Parts_share_refs() { num_parts= 0; ha_shares= NULL; } ~Parts_share_refs() { uint i; for (i= 0; i < num_parts; i++) delete ha_shares[i]; delete[] ha_shares; } bool init(uint arg_num_parts) { DBUG_ASSERT(!num_parts && !ha_shares); num_parts= arg_num_parts; /* Allocate an array of Handler_share pointers */ ha_shares= new Handler_share *[num_parts]; if (!ha_shares) { num_parts= 0; return true; } memset(ha_shares, 0, sizeof(Handler_share*) * num_parts); return false; } }; class ha_partition; /* Partition Full Text Search info */ struct st_partition_ft_info { struct _ft_vft *please; st_partition_ft_info *next; ha_partition *file; FT_INFO **part_ft_info; }; #ifdef HAVE_PSI_MUTEX_INTERFACE extern PSI_mutex_key key_partition_auto_inc_mutex; #endif /** Partition specific Handler_share. */ class Partition_share : public Handler_share { public: bool auto_inc_initialized; mysql_mutex_t auto_inc_mutex; /**< protecting auto_inc val */ ulonglong next_auto_inc_val; /**< first non reserved value */ /** Hash of partition names. Initialized in the first ha_partition::open() for the table_share. After that it is read-only, i.e. no locking required. */ bool partition_name_hash_initialized; HASH partition_name_hash; const char *partition_engine_name; /** Storage for each partitions Handler_share */ Parts_share_refs partitions_share_refs; Partition_share() : auto_inc_initialized(false), next_auto_inc_val(0), partition_name_hash_initialized(false), partition_engine_name(NULL), partition_names(NULL) { mysql_mutex_init(key_partition_auto_inc_mutex, &auto_inc_mutex, MY_MUTEX_INIT_FAST); } ~Partition_share() { mysql_mutex_destroy(&auto_inc_mutex); if (partition_names) { my_free(partition_names); } if (partition_name_hash_initialized) { my_hash_free(&partition_name_hash); } } bool init(uint num_parts); /** Release reserved auto increment values not used. @param thd Thread. @param table_share Table Share @param next_insert_id Next insert id (first non used auto inc value). @param max_reserved End of reserved auto inc range. */ void release_auto_inc_if_possible(THD *thd, TABLE_SHARE *table_share, const ulonglong next_insert_id, const ulonglong max_reserved); /** lock mutex protecting auto increment value next_auto_inc_val. */ inline void lock_auto_inc() { mysql_mutex_lock(&auto_inc_mutex); } /** unlock mutex protecting auto increment value next_auto_inc_val. */ inline void unlock_auto_inc() { mysql_mutex_unlock(&auto_inc_mutex); } /** Populate partition_name_hash with partition and subpartition names from part_info. @param part_info Partition info containing all partitions metadata. @return Operation status. @retval false Success. @retval true Failure. */ bool populate_partition_name_hash(partition_info *part_info); /** Get partition name. @param part_id Partition id (for subpartitioned table only subpartition names will be returned.) @return partition name or NULL if error. */ const char *get_partition_name(size_t part_id) const; private: const uchar **partition_names; /** Insert [sub]partition name into partition_name_hash @param name Partition name. @param part_id Partition id. @param is_subpart True if subpartition else partition. @return Operation status. @retval false Success. @retval true Failure. */ bool insert_partition_name_in_hash(const char *name, uint part_id, bool is_subpart); }; /* List of ranges to be scanned by ha_partition's MRR implementation This object is - A KEY_MULTI_RANGE structure (the MRR range) - Storage for the range endpoints that the KEY_MULTI_RANGE has pointers to - list of such ranges (connected through the "next" pointer). */ typedef struct st_partition_key_multi_range { /* Number of the range. The ranges are numbered in the order RANGE_SEQ_IF has emitted them, starting from 1. The numbering in used by ordered MRR scans. */ uint id; uchar *key[2]; /* Sizes of allocated memory in key[]. These may be larger then the actual values as this structure is reused across MRR scans */ uint length[2]; /* The range. key_multi_range.ptr is a pointer to the this PARTITION_KEY_MULTI_RANGE object */ KEY_MULTI_RANGE key_multi_range; // Range id from the SQL layer range_id_t ptr; // The next element in the list of MRR ranges. st_partition_key_multi_range *next; } PARTITION_KEY_MULTI_RANGE; /* List of ranges to be scanned in a certain [sub]partition The idea is that there's a list of ranges to be scanned in the table (formed by PARTITION_KEY_MULTI_RANGE structures), and for each [sub]partition, we only need to scan a subset of that list. PKMR1 --> PKMR2 --> PKMR3 -->... // list of PARTITION_KEY_MULTI_RANGE ^ ^ | | PPKMR1 ----------> PPKMR2 -->... // list of PARTITION_PART_KEY_MULTI_RANGE This way, per-partition lists of PARTITION_PART_KEY_MULTI_RANGE have pointers to the elements of the global list of PARTITION_KEY_MULTI_RANGE. */ typedef struct st_partition_part_key_multi_range { PARTITION_KEY_MULTI_RANGE *partition_key_multi_range; st_partition_part_key_multi_range *next; } PARTITION_PART_KEY_MULTI_RANGE; class ha_partition; /* The structure holding information about range sequence to be used with one partition. (pointer to this is used as seq_init_param for RANGE_SEQ_IF structure when invoking MRR for an individual partition) */ typedef struct st_partition_part_key_multi_range_hld { /* Owner object */ ha_partition *partition; /* id of the the partition this structure is for */ uint32 part_id; /* Current range we're iterating through */ PARTITION_PART_KEY_MULTI_RANGE *partition_part_key_multi_range; } PARTITION_PART_KEY_MULTI_RANGE_HLD; extern "C" int cmp_key_part_id(void *key_p, const void *ref1, const void *ref2); extern "C" int cmp_key_rowid_part_id(void *ptr, const void *ref1, const void *ref2); class ha_partition final :public handler { private: enum partition_index_scan_type { partition_index_read= 0, partition_index_first= 1, partition_index_last= 3, partition_index_read_last= 4, partition_read_range = 5, partition_no_index_scan= 6, partition_read_multi_range = 7, partition_ft_read= 8 }; /* Data for the partition handler */ int m_mode; // Open mode uint m_open_test_lock; // Open test_if_locked uchar *m_file_buffer; // Content of the .par file char *m_name_buffer_ptr; // Pointer to first partition name MEM_ROOT m_mem_root; plugin_ref *m_engine_array; // Array of types of the handlers handler **m_file; // Array of references to handler inst. uint m_file_tot_parts; // Debug handler **m_new_file; // Array of references to new handlers handler **m_reorged_file; // Reorganised partitions handler **m_added_file; // Added parts kept for errors LEX_CSTRING *m_connect_string; partition_info *m_part_info; // local reference to partition Field **m_part_field_array; // Part field array locally to save acc uchar *m_ordered_rec_buffer; // Row and key buffer for ord. idx scan st_partition_ft_info *ft_first; st_partition_ft_info *ft_current; /* Current index. When used in key_rec_cmp: If clustered pk, index compare must compare pk if given index is same for two rows. So normally m_curr_key_info[0]= current index and m_curr_key[1]= NULL, and if clustered pk, [0]= current index, [1]= pk, [2]= NULL */ KEY *m_curr_key_info[3]; // Current index const uchar *m_err_rec; // record which gave error QUEUE m_queue; // Prio queue used by sorted read /* Length of an element in m_ordered_rec_buffer. The elements are composed of [part_no] [table->record copy] [underlying_table_rowid] underlying_table_rowid is only stored when the table has no extended keys. */ size_t m_priority_queue_rec_len; /* If true, then sorting records by key value also sorts them by their underlying_table_rowid. */ bool m_using_extended_keys; /* Since the partition handler is a handler on top of other handlers, it is necessary to keep information about what the underlying handler characteristics is. It is not possible to keep any handler instances for this since the MySQL Server sometimes allocating the handler object without freeing them. */ enum enum_handler_status { handler_not_initialized= 0, handler_initialized, handler_opened, handler_closed }; enum_handler_status m_handler_status; uint m_reorged_parts; // Number of reorganised parts uint m_tot_parts; // Total number of partitions; uint m_num_locks; // For engines like ha_blackhole, which needs no locks uint m_last_part; // Last file that we update,write,read part_id_range m_part_spec; // Which parts to scan uint m_scan_value; // Value passed in rnd_init // call uint m_ref_length; // Length of position in this // handler object key_range m_start_key; // index read key range enum partition_index_scan_type m_index_scan_type;// What type of index // scan uint m_top_entry; // Which partition is to // deliver next result uint m_rec_length; // Local copy of record length bool m_ordered; // Ordered/Unordered index scan bool m_create_handler; // Handler used to create table bool m_is_sub_partitioned; // Is subpartitioned bool m_ordered_scan_ongoing; bool m_rnd_init_and_first; bool m_ft_init_and_first; /* If set, this object was created with ha_partition::clone and doesn't "own" the m_part_info structure. */ ha_partition *m_is_clone_of; MEM_ROOT *m_clone_mem_root; /* We keep track if all underlying handlers are MyISAM since MyISAM has a great number of extra flags not needed by other handlers. */ bool m_myisam; // Are all underlying handlers // MyISAM /* We keep track of InnoDB handlers below since it requires proper setting of query_id in fields at index_init and index_read calls. */ bool m_innodb; // Are all underlying handlers // InnoDB bool m_myisammrg; // Are any of the handlers of type MERGE /* When calling extra(HA_EXTRA_CACHE) we do not pass this to the underlying handlers immediately. Instead we cache it and call the underlying immediately before starting the scan on the partition. This is to prevent allocating a READ CACHE for each partition in parallel when performing a full table scan on MyISAM partitioned table. This state is cleared by extra(HA_EXTRA_NO_CACHE). */ bool m_extra_cache; uint m_extra_cache_size; /* The same goes for HA_EXTRA_PREPARE_FOR_UPDATE */ bool m_extra_prepare_for_update; /* Which partition has active cache */ uint m_extra_cache_part_id; void init_handler_variables(); /* Variables for lock structures. */ bool auto_increment_lock; /**< lock reading/updating auto_inc */ /** Flag to keep the auto_increment lock through out the statement. This to ensure it will work with statement based replication. */ bool auto_increment_safe_stmt_log_lock; /** For optimizing ha_start_bulk_insert calls */ MY_BITMAP m_bulk_insert_started; ha_rows m_bulk_inserted_rows; /** used for prediction of start_bulk_insert rows */ enum_monotonicity_info m_part_func_monotonicity_info; part_id_range m_direct_update_part_spec; bool m_pre_calling; bool m_pre_call_use_parallel; /* Keep track of bulk access requests */ bool bulk_access_executing; /** keep track of locked partitions */ MY_BITMAP m_locked_partitions; /** Stores shared auto_increment etc. */ Partition_share *part_share; void sum_copy_info(handler *file); void sum_copy_infos(); void reset_copy_info() override; /** Temporary storage for new partitions Handler_shares during ALTER */ List m_new_partitions_share_refs; /** Sorted array of partition ids in descending order of number of rows. */ uint32 *m_part_ids_sorted_by_num_of_records; /* Compare function for my_qsort2, for reversed order. */ static int compare_number_of_records(void *me, const void *a, const void *b); /** keep track of partitions to call ha_reset */ MY_BITMAP m_partitions_to_reset; /** partitions that returned HA_ERR_KEY_NOT_FOUND. */ MY_BITMAP m_key_not_found_partitions; bool m_key_not_found; List *m_partitions_to_open; MY_BITMAP m_opened_partitions; /** This is one of the m_file-s that it guaranteed to be opened. */ /** It is set in open_read_partitions() */ handler *m_file_sample; public: handler **get_child_handlers() { return m_file; } ha_partition *get_clone_source() { return m_is_clone_of; } virtual part_id_range *get_part_spec() { return &m_part_spec; } virtual uint get_no_current_part_id() { return NO_CURRENT_PART_ID; } Partition_share *get_part_share() { return part_share; } handler *clone(const char *name, MEM_ROOT *mem_root) override; void set_part_info(partition_info *part_info) override { m_part_info= part_info; m_is_sub_partitioned= part_info->is_sub_partitioned(); } Compare_keys compare_key_parts( const Field &old_field, const Column_definition &new_field, const KEY_PART_INFO &old_part, const KEY_PART_INFO &new_part) const override; void return_record_by_parent() override; bool vers_can_native(THD *thd) override { if (thd->lex->part_info) { // PARTITION BY SYSTEM_TIME is not supported for now return thd->lex->part_info->part_type != VERSIONING_PARTITION; } else { bool can= true; for (uint i= 0; i < m_tot_parts && can; i++) can= can && m_file[i]->vers_can_native(thd); return can; } } /* ------------------------------------------------------------------------- MODULE create/delete handler object ------------------------------------------------------------------------- Object create/delete method. Normally called when a table object exists. There is also a method to create the handler object with only partition information. This is used from mysql_create_table when the table is to be created and the engine type is deduced to be the partition handler. ------------------------------------------------------------------------- */ ha_partition(handlerton *hton, TABLE_SHARE * table); ha_partition(handlerton *hton, partition_info * part_info); ha_partition(handlerton *hton, TABLE_SHARE *share, partition_info *part_info_arg, ha_partition *clone_arg, MEM_ROOT *clone_mem_root_arg); ~ha_partition(); void ha_partition_init(); /* A partition handler has no characteristics in itself. It only inherits those from the underlying handlers. Here we set-up those constants to enable later calls of the methods to retrieve constants from the under- lying handlers. Returns false if not successful. */ bool initialize_partition(MEM_ROOT *mem_root); /* ------------------------------------------------------------------------- MODULE meta data changes ------------------------------------------------------------------------- Meta data routines to CREATE, DROP, RENAME table and often used at ALTER TABLE (update_create_info used from ALTER TABLE and SHOW ..). create_partitioning_metadata is called before opening a new handler object with openfrm to call create. It is used to create any local handler object needed in opening the object in openfrm ------------------------------------------------------------------------- */ int delete_table(const char *from) override; int rename_table(const char *from, const char *to) override; int create(const char *name, TABLE *form, HA_CREATE_INFO *create_info) override; int create_partitioning_metadata(const char *name, const char *old_name, chf_create_flags action_flag) override; bool check_if_updates_are_ignored(const char *op) const override; void update_create_info(HA_CREATE_INFO *create_info) override; int change_partitions(HA_CREATE_INFO *create_info, const char *path, ulonglong * const copied, ulonglong * const deleted, const uchar *pack_frm_data, size_t pack_frm_len) override; int drop_partitions(const char *path) override; int rename_partitions(const char *path) override; bool get_no_parts(const char *, uint *num_parts) override { DBUG_ENTER("ha_partition::get_no_parts"); *num_parts= m_tot_parts; DBUG_RETURN(0); } void change_table_ptr(TABLE *table_arg, TABLE_SHARE *share) override; bool check_if_incompatible_data(HA_CREATE_INFO *create_info, uint table_changes) override; void update_part_create_info(HA_CREATE_INFO *create_info, uint part_id) { m_file[part_id]->update_create_info(create_info); } private: int copy_partitions(ulonglong * const copied, ulonglong * const deleted); void cleanup_new_partition(uint part_count); int prepare_new_partition(TABLE *table, HA_CREATE_INFO *create_info, handler *file, const char *part_name, partition_element *p_elem); /* delete_table and rename_table uses very similar logic which is packed into this routine. */ uint del_ren_table(const char *from, const char *to); /* One method to create the table_name.par file containing the names of the underlying partitions, their engine and the number of partitions. And one method to read it in. */ bool create_handler_file(const char *name); bool setup_engine_array(MEM_ROOT *mem_root, handlerton *first_engine); int read_par_file(const char *name); handlerton *get_def_part_engine(const char *name); bool get_from_handler_file(const char *name, MEM_ROOT *mem_root, bool is_clone); bool re_create_par_file(const char *name); bool new_handlers_from_part_info(MEM_ROOT *mem_root); bool create_handlers(MEM_ROOT *mem_root); void clear_handler_file(); int set_up_table_before_create(TABLE *table_arg, const char *partition_name_with_path, HA_CREATE_INFO *info, partition_element *p_elem); partition_element *find_partition_element(uint part_id); bool insert_partition_name_in_hash(const char *name, uint part_id, bool is_subpart); bool populate_partition_name_hash(); Partition_share *get_share(); bool set_ha_share_ref(Handler_share **ha_share) override; void fix_data_dir(char* path); bool init_partition_bitmaps(); void free_partition_bitmaps(); public: /* ------------------------------------------------------------------------- MODULE open/close object ------------------------------------------------------------------------- Open and close handler object to ensure all underlying files and objects allocated and deallocated for query handling is handled properly. ------------------------------------------------------------------------- A handler object is opened as part of its initialisation and before being used for normal queries (not before meta-data changes always. If the object was opened it will also be closed before being deleted. */ int open(const char *name, int mode, uint test_if_locked) override; int close() override; /* ------------------------------------------------------------------------- MODULE start/end statement ------------------------------------------------------------------------- This module contains methods that are used to understand start/end of statements, transaction boundaries, and aid for proper concurrency control. The partition handler need not implement abort and commit since this will be handled by any underlying handlers implementing transactions. There is only one call to each handler type involved per transaction and these go directly to the handlers supporting transactions ------------------------------------------------------------------------- */ THR_LOCK_DATA **store_lock(THD * thd, THR_LOCK_DATA ** to, enum thr_lock_type lock_type) override; int external_lock(THD * thd, int lock_type) override; LEX_CSTRING *engine_name() override { return hton_name(partition_ht()); } /* When table is locked a statement is started by calling start_stmt instead of external_lock */ int start_stmt(THD * thd, thr_lock_type lock_type) override; /* Lock count is number of locked underlying handlers (I assume) */ uint lock_count() const override; /* Call to unlock rows not to be updated in transaction */ void unlock_row() override; /* Check if semi consistent read */ bool was_semi_consistent_read() override; /* Call to hint about semi consistent read */ void try_semi_consistent_read(bool) override; /* NOTE: due to performance and resource issues with many partitions, we only use the m_psi on the ha_partition handler, excluding all partitions m_psi. */ #ifdef HAVE_M_PSI_PER_PARTITION /* Bind the table/handler thread to track table i/o. */ virtual void unbind_psi(); virtual int rebind(); #endif int discover_check_version() override; /* ------------------------------------------------------------------------- MODULE change record ------------------------------------------------------------------------- This part of the handler interface is used to change the records after INSERT, DELETE, UPDATE, REPLACE method calls but also other special meta-data operations as ALTER TABLE, LOAD DATA, TRUNCATE. ------------------------------------------------------------------------- These methods are used for insert (write_row), update (update_row) and delete (delete_row). All methods to change data always work on one row at a time. update_row and delete_row also contains the old row. delete_all_rows will delete all rows in the table in one call as a special optimisation for DELETE from table; Bulk inserts are supported if all underlying handlers support it. start_bulk_insert and end_bulk_insert is called before and after a number of calls to write_row. */ int write_row(const uchar * buf) override; bool start_bulk_update() override; int exec_bulk_update(ha_rows *dup_key_found) override; int end_bulk_update() override; int bulk_update_row(const uchar *old_data, const uchar *new_data, ha_rows *dup_key_found) override; int update_row(const uchar * old_data, const uchar * new_data) override; int direct_update_rows_init(List *update_fields) override; int pre_direct_update_rows_init(List *update_fields) override; int direct_update_rows(ha_rows *update_rows, ha_rows *found_rows) override; int pre_direct_update_rows() override; bool start_bulk_delete() override; int end_bulk_delete() override; int delete_row(const uchar * buf) override; int direct_delete_rows_init() override; int pre_direct_delete_rows_init() override; int direct_delete_rows(ha_rows *delete_rows) override; int pre_direct_delete_rows() override; int delete_all_rows() override; int truncate() override; void start_bulk_insert(ha_rows rows, uint flags) override; int end_bulk_insert() override; private: ha_rows guess_bulk_insert_rows(); void start_part_bulk_insert(THD *thd, uint part_id); long estimate_read_buffer_size(long original_size); public: /* Method for truncating a specific partition. (i.e. ALTER TABLE t1 TRUNCATE PARTITION p). @remark This method is a partitioning-specific hook and thus not a member of the general SE API. */ int truncate_partition(Alter_info *, bool *binlog_stmt); bool is_fatal_error(int error, uint flags) override { if (!handler::is_fatal_error(error, flags) || error == HA_ERR_NO_PARTITION_FOUND || error == HA_ERR_NOT_IN_LOCK_PARTITIONS) return FALSE; return TRUE; } /* ------------------------------------------------------------------------- MODULE full table scan ------------------------------------------------------------------------- This module is used for the most basic access method for any table handler. This is to fetch all data through a full table scan. No indexes are needed to implement this part. It contains one method to start the scan (rnd_init) that can also be called multiple times (typical in a nested loop join). Then proceeding to the next record (rnd_next) and closing the scan (rnd_end). To remember a record for later access there is a method (position) and there is a method used to retrieve the record based on the stored position. The position can be a file position, a primary key, a ROWID dependent on the handler below. ------------------------------------------------------------------------- */ /* unlike index_init(), rnd_init() can be called two times without rnd_end() in between (it only makes sense if scan=1). then the second call should prepare for the new table scan (e.g if rnd_init allocates the cursor, second call should position it to the start of the table, no need to deallocate and allocate it again */ int rnd_init(bool scan) override; int rnd_end() override; int rnd_next(uchar * buf) override; int rnd_pos(uchar * buf, uchar * pos) override; int rnd_pos_by_record(uchar *record) override; void position(const uchar * record) override; /* ------------------------------------------------------------------------- MODULE index scan ------------------------------------------------------------------------- This part of the handler interface is used to perform access through indexes. The interface is defined as a scan interface but the handler can also use key lookup if the index is a unique index or a primary key index. Index scans are mostly useful for SELECT queries but are an important part also of UPDATE, DELETE, REPLACE and CREATE TABLE table AS SELECT and so forth. Naturally an index is needed for an index scan and indexes can either be ordered, hash based. Some ordered indexes can return data in order but not necessarily all of them. There are many flags that define the behavior of indexes in the various handlers. These methods are found in the optimizer module. ------------------------------------------------------------------------- index_read is called to start a scan of an index. The find_flag defines the semantics of the scan. These flags are defined in include/my_base.h index_read_idx is the same but also initializes index before calling doing the same thing as index_read. Thus it is similar to index_init followed by index_read. This is also how we implement it. index_read/index_read_idx does also return the first row. Thus for key lookups, the index_read will be the only call to the handler in the index scan. index_init initializes an index before using it and index_end does any end processing needed. */ int index_read_map(uchar * buf, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag) override; int index_init(uint idx, bool sorted) override; int index_end() override; /** @breif Positions an index cursor to the index specified in the handle. Fetches the row if available. If the key value is null, begin at first key of the index. */ int index_read_idx_map(uchar *buf, uint index, const uchar *key, key_part_map keypart_map, enum ha_rkey_function find_flag) override; /* These methods are used to jump to next or previous entry in the index scan. There are also methods to jump to first and last entry. */ int index_next(uchar * buf) override; int index_prev(uchar * buf) override; int index_first(uchar * buf) override; int index_last(uchar * buf) override; int index_next_same(uchar * buf, const uchar * key, uint keylen) override; int index_read_last_map(uchar *buf, const uchar *key, key_part_map keypart_map) override; /* read_first_row is virtual method but is only implemented by handler.cc, no storage engine has implemented it so neither will the partition handler. int read_first_row(uchar *buf, uint primary_key) override; */ int read_range_first(const key_range * start_key, const key_range * end_key, bool eq_range, bool sorted) override; int read_range_next() override; HANDLER_BUFFER *m_mrr_buffer; uint *m_mrr_buffer_size; uchar *m_mrr_full_buffer; uint m_mrr_full_buffer_size; uint m_mrr_new_full_buffer_size; MY_BITMAP m_mrr_used_partitions; uint *m_stock_range_seq; /* not used: uint m_current_range_seq; */ /* Value of mrr_mode passed to ha_partition::multi_range_read_init */ uint m_mrr_mode; /* Value of n_ranges passed to ha_partition::multi_range_read_init */ uint m_mrr_n_ranges; /* Ordered MRR mode: m_range_info[N] has the range_id of the last record that we've got from partition N */ range_id_t *m_range_info; /* TRUE <=> This ha_partition::multi_range_read_next() call is the first one */ bool m_multi_range_read_first; /* not used: uint m_mrr_range_init_flags; */ /* Number of elements in the list pointed by m_mrr_range_first. Not used */ uint m_mrr_range_length; /* Linked list of ranges to scan */ PARTITION_KEY_MULTI_RANGE *m_mrr_range_first; PARTITION_KEY_MULTI_RANGE *m_mrr_range_current; /* For each partition: number of ranges MRR scan will scan in the partition */ uint *m_part_mrr_range_length; /* For each partition: List of ranges to scan in this partition */ PARTITION_PART_KEY_MULTI_RANGE **m_part_mrr_range_first; PARTITION_PART_KEY_MULTI_RANGE **m_part_mrr_range_current; PARTITION_PART_KEY_MULTI_RANGE_HLD *m_partition_part_key_multi_range_hld; /* Sequence of ranges to be scanned (TODO: why not store this in handler::mrr_{iter,funcs}?) */ range_seq_t m_seq; RANGE_SEQ_IF *m_seq_if; /* Range iterator structure to be supplied to partitions */ RANGE_SEQ_IF m_part_seq_if; virtual int multi_range_key_create_key( RANGE_SEQ_IF *seq, range_seq_t seq_it ); ha_rows multi_range_read_info_const(uint keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges, uint *bufsz, uint *mrr_mode, Cost_estimate *cost) override; ha_rows multi_range_read_info(uint keyno, uint n_ranges, uint keys, uint key_parts, uint *bufsz, uint *mrr_mode, Cost_estimate *cost) override; int multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges, uint mrr_mode, HANDLER_BUFFER *buf) override; int multi_range_read_next(range_id_t *range_info) override; int multi_range_read_explain_info(uint mrr_mode, char *str, size_t size) override; uint last_part() { return m_last_part; } private: bool init_record_priority_queue(); void destroy_record_priority_queue(); int common_index_read(uchar * buf, bool have_start_key); int common_first_last(uchar * buf); int partition_scan_set_up(uchar * buf, bool idx_read_flag); bool check_parallel_search(); int handle_pre_scan(bool reverse_order, bool use_parallel); int handle_unordered_next(uchar * buf, bool next_same); int handle_unordered_scan_next_partition(uchar * buf); int handle_ordered_index_scan(uchar * buf, bool reverse_order); int handle_ordered_index_scan_key_not_found(); int handle_ordered_next(uchar * buf, bool next_same); int handle_ordered_prev(uchar * buf); void return_top_record(uchar * buf); void swap_blobs(uchar* rec_buf, Ordered_blob_storage ** storage, bool restore); public: /* ------------------------------------------------------------------------- MODULE information calls ------------------------------------------------------------------------- This calls are used to inform the handler of specifics of the ongoing scans and other actions. Most of these are used for optimisation purposes. ------------------------------------------------------------------------- */ int info(uint) override; void get_dynamic_partition_info(PARTITION_STATS *stat_info, uint part_id) override; void set_partitions_to_open(List *partition_names) override; int change_partitions_to_open(List *partition_names) override; int open_read_partitions(char *name_buff, size_t name_buff_size); int extra(enum ha_extra_function operation) override; int extra_opt(enum ha_extra_function operation, ulong arg) override; int reset() override; uint count_query_cache_dependant_tables(uint8 *tables_type) override; my_bool register_query_cache_dependant_tables(THD *thd, Query_cache *cache, Query_cache_block_table **block, uint *n) override; private: typedef int handler_callback(handler *, void *); my_bool reg_query_cache_dependant_table(THD *thd, char *engine_key, uint engine_key_len, char *query_key, uint query_key_len, uint8 type, Query_cache *cache, Query_cache_block_table **block_table, handler *file, uint *n); static const uint NO_CURRENT_PART_ID= NOT_A_PARTITION_ID; int loop_partitions(handler_callback callback, void *param); int loop_partitions_over_map(const MY_BITMAP *map, handler_callback callback, void *param); int loop_read_partitions(handler_callback callback, void *param); int loop_extra_alter(enum ha_extra_function operations); void late_extra_cache(uint partition_id); void late_extra_no_cache(uint partition_id); void prepare_extra_cache(uint cachesize); handler *get_open_file_sample() const { return m_file_sample; } public: /* ------------------------------------------------------------------------- MODULE optimiser support ------------------------------------------------------------------------- ------------------------------------------------------------------------- */ /* NOTE !!!!!! ------------------------------------------------------------------------- ------------------------------------------------------------------------- One important part of the public handler interface that is not depicted in the methods is the attribute records which is defined in the base class. This is looked upon directly and is set by calling info(HA_STATUS_INFO) ? ------------------------------------------------------------------------- */ private: /* Helper functions for optimizer hints. */ ha_rows min_rows_for_estimate(); uint get_biggest_used_partition(uint *part_index); public: /* keys_to_use_for_scanning can probably be implemented as the intersection of all underlying handlers if mixed handlers are used. This method is used to derive whether an index can be used for index-only scanning when performing an ORDER BY query. Only called from one place in sql_select.cc */ const key_map *keys_to_use_for_scanning() override; /* Called in test_quick_select to determine if indexes should be used. */ double scan_time() override; double key_scan_time(uint inx) override; double keyread_time(uint inx, uint ranges, ha_rows rows) override; /* The next method will never be called if you do not implement indexes. */ double read_time(uint index, uint ranges, ha_rows rows) override; /* For the given range how many records are estimated to be in this range. Used by optimiser to calculate cost of using a particular index. */ ha_rows records_in_range(uint inx, const key_range * min_key, const key_range * max_key, page_range *pages) override; /* Upper bound of number records returned in scan is sum of all underlying handlers. */ ha_rows estimate_rows_upper_bound() override; /* table_cache_type is implemented by the underlying handler but all underlying handlers must have the same implementation for it to work. */ uint8 table_cache_type() override; ha_rows records() override; /* Calculate hash value for PARTITION BY KEY tables. */ static uint32 calculate_key_hash_value(Field **field_array); /* ------------------------------------------------------------------------- MODULE print messages ------------------------------------------------------------------------- This module contains various methods that returns text messages for table types, index type and error messages. ------------------------------------------------------------------------- */ /* The name of the index type that will be used for display Here we must ensure that all handlers use the same index type for each index created. */ const char *index_type(uint inx) override; /* The name of the table type that will be used for display purposes */ const char *real_table_type() const override; /* The name of the row type used for the underlying tables. */ enum row_type get_row_type() const override; /* Handler specific error messages */ void print_error(int error, myf errflag) override; bool get_error_message(int error, String * buf) override; /* ------------------------------------------------------------------------- MODULE handler characteristics ------------------------------------------------------------------------- This module contains a number of methods defining limitations and characteristics of the handler. The partition handler will calculate this characteristics based on underlying handler characteristics. ------------------------------------------------------------------------- This is a list of flags that says what the storage engine implements. The current table flags are documented in handler.h The partition handler will support whatever the underlying handlers support except when specifically mentioned below about exceptions to this rule. NOTE: This cannot be cached since it can depend on TRANSACTION ISOLATION LEVEL which is dynamic, see bug#39084. HA_TABLE_SCAN_ON_INDEX: Used to avoid scanning full tables on an index. If this flag is set then the handler always has a primary key (hidden if not defined) and this index is used for scanning rather than a full table scan in all situations. (InnoDB, Federated) HA_REC_NOT_IN_SEQ: This flag is set for handlers that cannot guarantee that the rows are returned according to incremental positions (0, 1, 2, 3...). This also means that rnd_next() should return HA_ERR_RECORD_DELETED if it finds a deleted row. (MyISAM (not fixed length row), HEAP, InnoDB) HA_CAN_GEOMETRY: Can the storage engine handle spatial data. Used to check that no spatial attributes are declared unless the storage engine is capable of handling it. (MyISAM) HA_FAST_KEY_READ: Setting this flag indicates that the handler is equally fast in finding a row by key as by position. This flag is used in a very special situation in conjunction with filesort's. For further explanation see intro to init_read_record. (HEAP, InnoDB) HA_NULL_IN_KEY: Is NULL values allowed in indexes. If this is not allowed then it is not possible to use an index on a NULLable field. (HEAP, MyISAM, InnoDB) HA_DUPLICATE_POS: Tells that we can the position for the conflicting duplicate key record is stored in table->file->dupp_ref. (insert uses rnd_pos() on this to find the duplicated row) (MyISAM) HA_CAN_INDEX_BLOBS: Is the storage engine capable of defining an index of a prefix on a BLOB attribute. (Federated, MyISAM, InnoDB) HA_AUTO_PART_KEY: Auto increment fields can be part of a multi-part key. For second part auto-increment keys, the auto_incrementing is done in handler.cc (Federated, MyISAM) HA_REQUIRE_PRIMARY_KEY: Can't define a table without primary key (and cannot handle a table with hidden primary key) (No handler has this limitation currently) HA_STATS_RECORDS_IS_EXACT: Does the counter of records after the info call specify an exact value or not. If it does this flag is set. Only MyISAM and HEAP uses exact count. HA_CAN_INSERT_DELAYED: Can the storage engine support delayed inserts. To start with the partition handler will not support delayed inserts. Further investigation needed. (HEAP, MyISAM) HA_PRIMARY_KEY_IN_READ_INDEX: This parameter is set when the handler will also return the primary key when doing read-only-key on another index. HA_NOT_DELETE_WITH_CACHE: Seems to be an old MyISAM feature that is no longer used. No handler has it defined but it is checked in init_read_record. Further investigation needed. (No handler defines it) HA_NO_PREFIX_CHAR_KEYS: Indexes on prefixes of character fields is not allowed. (Federated) HA_CAN_FULLTEXT: Does the storage engine support fulltext indexes The partition handler will start by not supporting fulltext indexes. (MyISAM) HA_CAN_SQL_HANDLER: Can the HANDLER interface in the MySQL API be used towards this storage engine. (MyISAM, InnoDB) HA_NO_AUTO_INCREMENT: Set if the storage engine does not support auto increment fields. (Currently not set by any handler) HA_HAS_CHECKSUM: Special MyISAM feature. Has special SQL support in CREATE TABLE. No special handling needed by partition handler. (MyISAM) HA_FILE_BASED: Should file names always be in lower case (used by engines that map table names to file names. Since partition handler has a local file this flag is set. (Federated, MyISAM) HA_CAN_BIT_FIELD: Is the storage engine capable of handling bit fields? (MyISAM) HA_NEED_READ_RANGE_BUFFER: Is Read Multi-Range supported => need multi read range buffer This parameter specifies whether a buffer for read multi range is needed by the handler. Whether the handler supports this feature or not is dependent of whether the handler implements read_multi_range* calls or not. The only handler currently supporting this feature is NDB so the partition handler need not handle this call. There are methods in handler.cc that will transfer those calls into index_read and other calls in the index scan module. (No handler defines it) HA_PRIMARY_KEY_REQUIRED_FOR_POSITION: Does the storage engine need a PK for position? (InnoDB) HA_FILE_BASED is always set for partition handler since we use a special file for handling names of partitions, engine types. HA_REC_NOT_IN_SEQ is always set for partition handler since we cannot guarantee that the records will be returned in sequence. HA_DUPLICATE_POS, HA_CAN_INSERT_DELAYED, HA_PRIMARY_KEY_REQUIRED_FOR_POSITION is disabled until further investigated. */ Table_flags table_flags() const override; /* This is a bitmap of flags that says how the storage engine implements indexes. The current index flags are documented in handler.h. If you do not implement indexes, just return zero here. part is the key part to check. First key part is 0 If all_parts it's set, MySQL want to know the flags for the combined index up to and including 'part'. HA_READ_NEXT: Does the index support read next, this is assumed in the server code and never checked so all indexes must support this. Note that the handler can be used even if it doesn't have any index. (HEAP, MyISAM, Federated, InnoDB) HA_READ_PREV: Can the index be used to scan backwards. (HEAP, MyISAM, InnoDB) HA_READ_ORDER: Can the index deliver its record in index order. Typically true for all ordered indexes and not true for hash indexes. In first step this is not true for partition handler until a merge sort has been implemented in partition handler. Used to set keymap part_of_sortkey This keymap is only used to find indexes usable for resolving an ORDER BY in the query. Thus in most cases index_read will work just fine without order in result production. When this flag is set it is however safe to order all output started by index_read since most engines do this. With read_multi_range calls there is a specific flag setting order or not order so in those cases ordering of index output can be avoided. (InnoDB, HEAP, MyISAM) HA_READ_RANGE: Specify whether index can handle ranges, typically true for all ordered indexes and not true for hash indexes. Used by optimiser to check if ranges (as key >= 5) can be optimised by index. (InnoDB, MyISAM, HEAP) HA_ONLY_WHOLE_INDEX: Can't use part key searches. This is typically true for hash indexes and typically not true for ordered indexes. (Federated, HEAP) HA_KEYREAD_ONLY: Does the storage engine support index-only scans on this index. Enables use of HA_EXTRA_KEYREAD and HA_EXTRA_NO_KEYREAD Used to set key_map keys_for_keyread and to check in optimiser for index-only scans. When doing a read under HA_EXTRA_KEYREAD the handler only have to fill in the columns the key covers. If HA_PRIMARY_KEY_IN_READ_INDEX is set then also the PRIMARY KEY columns must be updated in the row. (InnoDB, MyISAM) */ ulong index_flags(uint inx, uint part, bool all_parts) const override { /* The following code is not safe if you are using different storage engines or different index types per partition. */ ulong part_flags= m_file[0]->index_flags(inx, part, all_parts); /* The underlying storage engine might support Rowid Filtering. But ha_partition does not forward the needed SE API calls, so the feature will not be used. Note: It's the same with IndexConditionPushdown, except for its variant of IndexConditionPushdown+BatchedKeyAccess (that one works). Because of that, we do not clear HA_DO_INDEX_COND_PUSHDOWN here. */ return part_flags & ~HA_DO_RANGE_FILTER_PUSHDOWN; } /** wrapper function for handlerton alter_table_flags, since the ha_partition_hton cannot know all its capabilities */ alter_table_operations alter_table_flags(alter_table_operations flags) override; /* unireg.cc will call the following to make sure that the storage engine can handle the data it is about to send. The maximum supported values is the minimum of all handlers in the table */ uint min_of_the_max_uint(uint (handler::*operator_func)(void) const) const; uint max_supported_record_length() const override; uint max_supported_keys() const override; uint max_supported_key_parts() const override; uint max_supported_key_length() const override; uint max_supported_key_part_length() const override; uint min_record_length(uint options) const override; /* ------------------------------------------------------------------------- MODULE compare records ------------------------------------------------------------------------- cmp_ref checks if two references are the same. For most handlers this is a simple memcmp of the reference. However some handlers use primary key as reference and this can be the same even if memcmp says they are different. This is due to character sets and end spaces and so forth. For the partition handler the reference is first two bytes providing the partition identity of the referred record and then the reference of the underlying handler. Thus cmp_ref for the partition handler always returns FALSE for records not in the same partition and uses cmp_ref on the underlying handler to check whether the rest of the reference part is also the same. ------------------------------------------------------------------------- */ int cmp_ref(const uchar * ref1, const uchar * ref2) override; /* ------------------------------------------------------------------------- MODULE auto increment ------------------------------------------------------------------------- This module is used to handle the support of auto increments. This variable in the handler is used as part of the handler interface It is maintained by the parent handler object and should not be touched by child handler objects (see handler.cc for its use). auto_increment_column_changed ------------------------------------------------------------------------- */ bool need_info_for_auto_inc() override; bool can_use_for_auto_inc_init() override; void get_auto_increment(ulonglong offset, ulonglong increment, ulonglong nb_desired_values, ulonglong *first_value, ulonglong *nb_reserved_values) override; void release_auto_increment() override; private: int reset_auto_increment(ulonglong value) override; int update_next_auto_inc_val(); virtual void lock_auto_increment() { /* lock already taken */ if (auto_increment_safe_stmt_log_lock) return; if (table_share->tmp_table == NO_TMP_TABLE) { part_share->lock_auto_inc(); DBUG_ASSERT(!auto_increment_lock); auto_increment_lock= TRUE; } } virtual void unlock_auto_increment() { /* If auto_increment_safe_stmt_log_lock is true, we have to keep the lock. It will be set to false and thus unlocked at the end of the statement by ha_partition::release_auto_increment. */ if (auto_increment_lock && !auto_increment_safe_stmt_log_lock) { auto_increment_lock= FALSE; part_share->unlock_auto_inc(); } } virtual void set_auto_increment_if_higher(Field *field) { ulonglong nr= (((Field_num*) field)->unsigned_flag || field->val_int() > 0) ? field->val_int() : 0; update_next_auto_inc_val(); lock_auto_increment(); /* must check when the mutex is taken */ if (nr >= part_share->next_auto_inc_val) part_share->next_auto_inc_val= nr + 1; unlock_auto_increment(); } void check_insert_or_replace_autoincrement() { /* If we INSERT or REPLACE into the table having the AUTO_INCREMENT column, we have to read all partitions for the next autoincrement value unless we already did it. */ if (!part_share->auto_inc_initialized && (ha_thd()->lex->sql_command == SQLCOM_INSERT || ha_thd()->lex->sql_command == SQLCOM_INSERT_SELECT || ha_thd()->lex->sql_command == SQLCOM_REPLACE || ha_thd()->lex->sql_command == SQLCOM_REPLACE_SELECT) && table->found_next_number_field) bitmap_set_all(&m_part_info->read_partitions); } public: /* ------------------------------------------------------------------------- MODULE initialize handler for HANDLER call ------------------------------------------------------------------------- This method is a special InnoDB method called before a HANDLER query. ------------------------------------------------------------------------- */ void init_table_handle_for_HANDLER() override; /* The remainder of this file defines the handler methods not implemented by the partition handler */ /* ------------------------------------------------------------------------- MODULE foreign key support ------------------------------------------------------------------------- The following methods are used to implement foreign keys as supported by InnoDB. Implement this ?? get_foreign_key_create_info is used by SHOW CREATE TABLE to get a textual description of how the CREATE TABLE part to define FOREIGN KEY's is done. free_foreign_key_create_info is used to free the memory area that provided this description. can_switch_engines checks if it is ok to switch to a new engine based on the foreign key info in the table. ------------------------------------------------------------------------- virtual char* get_foreign_key_create_info() virtual void free_foreign_key_create_info(char* str) virtual int get_foreign_key_list(THD *thd, List *f_key_list) bool referenced_by_foreign_key() const noexcept override */ bool can_switch_engines() override; /* ------------------------------------------------------------------------- MODULE fulltext index ------------------------------------------------------------------------- */ void ft_close_search(FT_INFO *handler); int ft_init() override; int pre_ft_init() override; void ft_end() override; int pre_ft_end() override; FT_INFO *ft_init_ext(uint flags, uint inx, String *key) override; int ft_read(uchar *buf) override; int pre_ft_read(bool use_parallel) override; /* ------------------------------------------------------------------------- MODULE restart full table scan at position (MyISAM) ------------------------------------------------------------------------- The following method is only used by MyISAM when used as temporary tables in a join. int restart_rnd_next(uchar *buf, uchar *pos) override; */ /* ------------------------------------------------------------------------- MODULE in-place ALTER TABLE ------------------------------------------------------------------------- These methods are in the handler interface. (used by innodb-plugin) They are used for in-place alter table: ------------------------------------------------------------------------- */ enum_alter_inplace_result check_if_supported_inplace_alter(TABLE *altered_table, Alter_inplace_info *ha_alter_info) override; bool prepare_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info) override; bool inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info) override; bool commit_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info, bool commit) override; /* ------------------------------------------------------------------------- MODULE tablespace support ------------------------------------------------------------------------- Admin of table spaces is not applicable to the partition handler (InnoDB) This means that the following method is not implemented: ------------------------------------------------------------------------- virtual int discard_or_import_tablespace(my_bool discard) */ /* ------------------------------------------------------------------------- MODULE admin MyISAM ------------------------------------------------------------------------- ------------------------------------------------------------------------- OPTIMIZE TABLE, CHECK TABLE, ANALYZE TABLE and REPAIR TABLE are mapped to a routine that handles looping over a given set of partitions and those routines send a flag indicating to execute on all partitions. ------------------------------------------------------------------------- */ int optimize(THD* thd, HA_CHECK_OPT *check_opt) override; int analyze(THD* thd, HA_CHECK_OPT *check_opt) override; int check(THD* thd, HA_CHECK_OPT *check_opt) override; int repair(THD* thd, HA_CHECK_OPT *check_opt) override; bool check_and_repair(THD *thd) override; bool auto_repair(int error) const override; bool is_crashed() const override; int check_for_upgrade(HA_CHECK_OPT *check_opt) override; /* ------------------------------------------------------------------------- MODULE condition pushdown ------------------------------------------------------------------------- */ const COND *cond_push(const COND *cond) override; void cond_pop() override; int info_push(uint info_type, void *info) override; private: int handle_opt_partitions(THD *thd, HA_CHECK_OPT *check_opt, uint flags); int handle_opt_part(THD *thd, HA_CHECK_OPT *check_opt, uint part_id, uint flag); /** Check if the rows are placed in the correct partition. If the given argument is true, then move the rows to the correct partition. */ int check_misplaced_rows(uint read_part_id, bool repair); void append_row_to_str(String &str); public: int pre_calculate_checksum() override; int calculate_checksum() override; /* Enabled keycache for performance reasons, WL#4571 */ int assign_to_keycache(THD* thd, HA_CHECK_OPT *check_opt) override; int preload_keys(THD* thd, HA_CHECK_OPT* check_opt) override; TABLE_LIST *get_next_global_for_child() override; /* ------------------------------------------------------------------------- MODULE enable/disable indexes ------------------------------------------------------------------------- Enable/Disable Indexes are only supported by HEAP and MyISAM. ------------------------------------------------------------------------- */ int disable_indexes(key_map map, bool persist) override; int enable_indexes(key_map map, bool persist) override; int indexes_are_disabled() override; /* ------------------------------------------------------------------------- MODULE append_create_info ------------------------------------------------------------------------- append_create_info is only used by MyISAM MERGE tables and the partition handler will not support this handler as underlying handler. Implement this?? ------------------------------------------------------------------------- virtual void append_create_info(String *packet) */ /* the following heavily relies on the fact that all partitions are in the same storage engine. When this limitation is lifted, the following hack should go away, and a proper interface for engines needs to be introduced: an PARTITION_SHARE structure that has a pointer to the TABLE_SHARE. is given to engines everywhere where TABLE_SHARE is used now has members like option_struct, ha_data perhaps TABLE needs to be split the same way too... this can also be done before partition will support a mix of engines, but preferably together with other incompatible API changes. */ handlerton *partition_ht() const override { handlerton *h= m_file[0]->ht; for (uint i=1; i < m_tot_parts; i++) DBUG_ASSERT(h == m_file[i]->ht); return h; } bool partition_engine() override { return 1;} ha_rows part_records(partition_element *part_elem) { DBUG_ASSERT(m_part_info); uint32 sub_factor= m_part_info->num_subparts ? m_part_info->num_subparts : 1; uint32 part_id= part_elem->id * sub_factor; uint32 part_id_end= part_id + sub_factor; DBUG_ASSERT(part_id_end <= m_tot_parts); ha_rows part_recs= 0; for (; part_id < part_id_end; ++part_id) { handler *file= m_file[part_id]; file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK | HA_STATUS_OPEN); part_recs+= file->stats.records; } return part_recs; } int notify_tabledef_changed(LEX_CSTRING *db, LEX_CSTRING *table, LEX_CUSTRING *frm, LEX_CUSTRING *version); friend int cmp_key_rowid_part_id(void *ptr, const void *ref1, const void *ref2); friend int cmp_key_part_id(void *key_p, const void *ref1, const void *ref2); bool can_convert_nocopy(const Field &field, const Column_definition &new_field) const override; void handler_stats_updated() override; }; #endif /* HA_PARTITION_INCLUDED */ mysql/server/private/rpl_utility.h000064400000022636151027430560013436 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_UTILITY_H #define RPL_UTILITY_H #ifndef __cplusplus #error "Don't include this C++ header file from a non-C++ file!" #endif #include "sql_priv.h" #include "m_string.h" /* bzero, memcpy */ #ifdef MYSQL_SERVER #include "table.h" /* TABLE_LIST */ #endif #include "mysql_com.h" class Relay_log_info; class Log_event; struct rpl_group_info; /** A table definition from the master. The responsibilities of this class is: - Extract and decode table definition data from the table map event - Check if table definition in table map is compatible with table definition on slave */ class table_def { public: /** Constructor. @param types Array of types, each stored as a byte @param size Number of elements in array 'types' @param field_metadata Array of extra information about fields @param metadata_size Size of the field_metadata array @param null_bitmap The bitmap of fields that can be null */ table_def(unsigned char *types, ulong size, uchar *field_metadata, int metadata_size, uchar *null_bitmap, uint16 flags); ~table_def(); /** Return the number of fields there is type data for. @return The number of fields that there is type data for. */ ulong size() const { return m_size; } /** Returns internal binlog type code for one field, without translation to real types. */ enum_field_types binlog_type(ulong index) const { return static_cast(m_type[index]); } /* Return a representation of the type data for one field. @param index Field index to return data for @return Will return a representation of the type data for field index. Currently, only the type identifier is returned. */ enum_field_types type(ulong index) const { DBUG_ASSERT(index < m_size); /* If the source type is MYSQL_TYPE_STRING, it can in reality be either MYSQL_TYPE_STRING, MYSQL_TYPE_ENUM, or MYSQL_TYPE_SET, so we might need to modify the type to get the real type. */ enum_field_types source_type= binlog_type(index); uint16 source_metadata= m_field_metadata[index]; switch (source_type) { case MYSQL_TYPE_STRING: { int real_type= source_metadata >> 8; if (real_type == MYSQL_TYPE_ENUM || real_type == MYSQL_TYPE_SET) source_type= static_cast(real_type); break; } /* This type has not been used since before row-based replication, so we can safely assume that it really is MYSQL_TYPE_NEWDATE. */ case MYSQL_TYPE_DATE: source_type= MYSQL_TYPE_NEWDATE; break; default: /* Do nothing */ break; } return source_type; } #ifdef MYSQL_SERVER const Type_handler *field_type_handler(uint index) const; #endif /* This function allows callers to get the extra field data from the table map for a given field. If there is no metadata for that field or there is no extra metadata at all, the function returns 0. The function returns the value for the field metadata for column at position indicated by index. As mentioned, if the field was a type that stores field metadata, that value is returned else zero (0) is returned. This method is used in the unpack() methods of the corresponding fields to properly extract the data from the binary log in the event that the master's field is smaller than the slave. */ uint16 field_metadata(uint index) const { DBUG_ASSERT(index < m_size); if (m_field_metadata_size) return m_field_metadata[index]; else return 0; } /* This function returns whether the field on the master can be null. This value is derived from field->maybe_null(). */ my_bool maybe_null(uint index) const { DBUG_ASSERT(index < m_size); return ((m_null_bits[(index / 8)] & (1 << (index % 8))) == (1 << (index %8))); } /* This function returns the field size in raw bytes based on the type and the encoded field data from the master's raw data. This method can be used for situations where the slave needs to skip a column (e.g., WL#3915) or needs to advance the pointer for the fields in the raw data from the master to a specific column. */ uint32 calc_field_size(uint col, uchar *master_data) const; /** Decide if the table definition is compatible with a table. Compare the definition with a table to see if it is compatible with it. A table definition is compatible with a table if: - The columns types of the table definition is a (not necessarily proper) prefix of the column type of the table. - The other way around. - Each column on the master that also exists on the slave can be converted according to the current settings of @c SLAVE_TYPE_CONVERSIONS. @param thd @param rli Pointer to relay log info @param table Pointer to table to compare with. @param[out] tmp_table_var Pointer to temporary table for holding conversion table. @retval 1 if the table definition is not compatible with @c table @retval 0 if the table definition is compatible with @c table */ #ifndef MYSQL_CLIENT bool compatible_with(THD *thd, rpl_group_info *rgi, TABLE *table, TABLE **conv_table_var) const; /** Create a virtual in-memory temporary table structure. The table structure has records and field array so that a row can be unpacked into the record for further processing. In the virtual table, each field that requires conversion will have a non-NULL value, while fields that do not require conversion will have a NULL value. Some information that is missing in the events, such as the character set for string types, are taken from the table that the field is going to be pushed into, so the target table that the data eventually need to be pushed into need to be supplied. @param thd Thread to allocate memory from. @param rli Relay log info structure, for error reporting. @param target_table Target table for fields. @return A pointer to a temporary table with memory allocated in the thread's memroot, NULL if the table could not be created */ TABLE *create_conversion_table(THD *thd, rpl_group_info *rgi, TABLE *target_table) const; #endif private: ulong m_size; // Number of elements in the types array unsigned char *m_type; // Array of type descriptors uint m_field_metadata_size; uint16 *m_field_metadata; uchar *m_null_bits; uint16 m_flags; // Table flags uchar *m_memory; }; #ifndef MYSQL_CLIENT /** Extend the normal table list with a few new fields needed by the slave thread, but nowhere else. */ struct RPL_TABLE_LIST : public TABLE_LIST { bool m_tabledef_valid; table_def m_tabledef; TABLE *m_conv_table; bool master_had_triggers; }; /* Anonymous namespace for template functions/classes */ CPP_UNNAMED_NS_START /* Smart pointer that will automatically call my_afree (a macro) when the pointer goes out of scope. This is used so that I do not have to remember to call my_afree() before each return. There is no overhead associated with this, since all functions are inline. I (Matz) would prefer to use the free function as a template parameter, but that is not possible when the "function" is a macro. */ template class auto_afree_ptr { Obj* m_ptr; public: auto_afree_ptr(Obj* ptr) : m_ptr(ptr) { } ~auto_afree_ptr() { if (m_ptr) my_afree(m_ptr); } void assign(Obj* ptr) { /* Only to be called if it hasn't been given a value before. */ DBUG_ASSERT(m_ptr == NULL); m_ptr= ptr; } Obj* get() { return m_ptr; } }; CPP_UNNAMED_NS_END class Deferred_log_events { private: DYNAMIC_ARRAY array; Log_event *last_added; public: Deferred_log_events(Relay_log_info *rli); ~Deferred_log_events(); /* queue for exection at Query-log-event time prior the Query */ int add(Log_event *ev); bool is_empty(); bool execute(struct rpl_group_info *rgi); void rewind(); bool is_last(Log_event *ev) { return ev == last_added; }; }; #endif // NB. number of printed bit values is limited to sizeof(buf) - 1 #define DBUG_PRINT_BITSET(N,FRM,BS) \ do { \ char buf[256]; \ uint i; \ for (i = 0 ; i < MY_MIN(sizeof(buf) - 1, (BS)->n_bits) ; i++) \ buf[i] = bitmap_is_set((BS), i) ? '1' : '0'; \ buf[i] = '\0'; \ DBUG_PRINT((N), ((FRM), buf)); \ } while (0) #endif /* RPL_UTILITY_H */ mysql/server/private/sql_signal.h000064400000006442151027430560013207 0ustar00/* Copyright (c) 2008 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_SIGNAL_H #define SQL_SIGNAL_H /** Sql_cmd_common_signal represents the common properties of the SIGNAL and RESIGNAL statements. */ class Sql_cmd_common_signal : public Sql_cmd { protected: /** Constructor. @param cond the condition signaled if any, or NULL. @param set collection of signal condition item assignments. */ Sql_cmd_common_signal(const sp_condition_value *cond, const Set_signal_information& set) : Sql_cmd(), m_cond(cond), m_set_signal_information(set) {} virtual ~Sql_cmd_common_signal() = default; /** Evaluate each signal condition items for this statement. @param thd the current thread. @param cond the condition to update. @return 0 on success. */ int eval_signal_informations(THD *thd, Sql_condition *cond); /** Raise a SQL condition. @param thd the current thread. @param cond the condition to raise. @return false on success. */ bool raise_condition(THD *thd, Sql_condition *cond); /** The condition to signal or resignal. This member is optional and can be NULL (RESIGNAL). */ const sp_condition_value *m_cond; /** Collection of 'SET item = value' assignments in the SIGNAL/RESIGNAL statement. */ Set_signal_information m_set_signal_information; }; /** Sql_cmd_signal represents a SIGNAL statement. */ class Sql_cmd_signal : public Sql_cmd_common_signal { public: /** Constructor, used to represent a SIGNAL statement. @param cond the SQL condition to signal (required). @param set the collection of signal information to signal. */ Sql_cmd_signal(const sp_condition_value *cond, const Set_signal_information& set) : Sql_cmd_common_signal(cond, set) {} virtual ~Sql_cmd_signal() = default; enum_sql_command sql_command_code() const override { return SQLCOM_SIGNAL; } bool execute(THD *thd) override; }; /** Sql_cmd_resignal represents a RESIGNAL statement. */ class Sql_cmd_resignal : public Sql_cmd_common_signal { public: /** Constructor, used to represent a RESIGNAL statement. @param cond the SQL condition to resignal (optional, may be NULL). @param set the collection of signal information to resignal. */ Sql_cmd_resignal(const sp_condition_value *cond, const Set_signal_information& set) : Sql_cmd_common_signal(cond, set) {} virtual ~Sql_cmd_resignal() = default; enum_sql_command sql_command_code() const override { return SQLCOM_RESIGNAL; } bool execute(THD *thd) override; }; #endif mysql/server/private/client_settings.h000064400000003617151027430560014252 0ustar00/* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef CLIENT_SETTINGS_INCLUDED #define CLIENT_SETTINGS_INCLUDED #else #error You have already included an client_settings.h and it should not be included twice #endif /* CLIENT_SETTINGS_INCLUDED */ #include #include /* Note: CLIENT_CAPABILITIES is also defined in libmysql/client_settings.h. When adding capabilities here, consider if they should be also added to the libmysql version. */ #define CLIENT_CAPABILITIES (CLIENT_MYSQL | \ CLIENT_LONG_FLAG | \ CLIENT_TRANSACTIONS | \ CLIENT_PROTOCOL_41 | \ CLIENT_SECURE_CONNECTION | \ CLIENT_PLUGIN_AUTH | \ CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | \ CLIENT_CONNECT_ATTRS) #define read_user_name(A) A[0]= 0 #undef _CUSTOMCONFIG_ #define mysql_server_init(a,b,c) mysql_client_plugin_init() #define mysql_server_end() mysql_client_plugin_deinit() #ifdef HAVE_REPLICATION C_MODE_START void slave_io_thread_detach_vio(); C_MODE_END #else #define slave_io_thread_detach_vio() #endif mysql/server/private/mem_root_array.h000064400000015702151027430560014071 0ustar00/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MEM_ROOT_ARRAY_INCLUDED #define MEM_ROOT_ARRAY_INCLUDED #include /** A typesafe replacement for DYNAMIC_ARRAY. We use MEM_ROOT for allocating storage, rather than the C++ heap. The interface is chosen to be similar to std::vector. @remark Unlike DYNAMIC_ARRAY, elements are properly copied (rather than memcpy()d) if the underlying array needs to be expanded. @remark Depending on has_trivial_destructor, we destroy objects which are removed from the array (including when the array object itself is destroyed). @remark Note that MEM_ROOT has no facility for reusing free space, so don't use this if multiple re-expansions are likely to happen. @param Element_type The type of the elements of the container. Elements must be copyable. @param has_trivial_destructor If true, we don't destroy elements. We could have used type traits to determine this. __has_trivial_destructor is supported by some (but not all) compilers we use. */ template class Mem_root_array { public: /// Convenience typedef, same typedef name as std::vector typedef Element_type value_type; Mem_root_array(MEM_ROOT *root) : m_root(root), m_array(NULL), m_size(0), m_capacity(0) { DBUG_ASSERT(m_root != NULL); } Mem_root_array(MEM_ROOT *root, size_t n, const value_type &val= value_type()) : m_root(root), m_array(NULL), m_size(0), m_capacity(0) { resize(n, val); } ~Mem_root_array() { clear(); } Element_type &at(size_t n) { DBUG_ASSERT(n < size()); return m_array[n]; } const Element_type &at(size_t n) const { DBUG_ASSERT(n < size()); return m_array[n]; } Element_type &operator[](size_t n) { return at(n); } const Element_type &operator[](size_t n) const { return at(n); } Element_type &back() { return at(size() - 1); } const Element_type &back() const { return at(size() - 1); } // Returns a pointer to the first element in the array. Element_type *begin() { return &m_array[0]; } const Element_type *begin() const { return &m_array[0]; } // Returns a pointer to the past-the-end element in the array. Element_type *end() { return &m_array[size()]; } const Element_type *end() const { return &m_array[size()]; } // Erases all of the elements. void clear() { if (!empty()) chop(0); } /* Chops the tail off the array, erasing all tail elements. @param pos Index of first element to erase. */ void chop(const size_t pos) { DBUG_ASSERT(pos < m_size); if (!has_trivial_destructor) { for (size_t ix= pos; ix < m_size; ++ix) { Element_type *p= &m_array[ix]; p->~Element_type(); // Destroy discarded element. } } m_size= pos; } /* Reserves space for array elements. Copies over existing elements, in case we are re-expanding the array. @param n number of elements. @retval true if out-of-memory, false otherwise. */ bool reserve(size_t n) { if (n <= m_capacity) return false; void *mem= alloc_root(m_root, n * element_size()); if (!mem) return true; Element_type *array= static_cast(mem); // Copy all the existing elements into the new array. for (size_t ix= 0; ix < m_size; ++ix) { Element_type *new_p= &array[ix]; Element_type *old_p= &m_array[ix]; new (new_p) Element_type(*old_p); // Copy into new location. if (!has_trivial_destructor) old_p->~Element_type(); // Destroy the old element. } // Forget the old array. m_array= array; m_capacity= n; return false; } /* Adds a new element at the end of the array, after its current last element. The content of this new element is initialized to a copy of the input argument. @param element Object to copy. @retval true if out-of-memory, false otherwise. */ bool push_back(const Element_type &element) { const size_t min_capacity= 20; const size_t expansion_factor= 2; if (0 == m_capacity && reserve(min_capacity)) return true; if (m_size == m_capacity && reserve(m_capacity * expansion_factor)) return true; Element_type *p= &m_array[m_size++]; new (p) Element_type(element); return false; } /** Removes the last element in the array, effectively reducing the container size by one. This destroys the removed element. */ void pop_back() { DBUG_ASSERT(!empty()); if (!has_trivial_destructor) back().~Element_type(); m_size-= 1; } /** Resizes the container so that it contains n elements. If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them). If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized. If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place. Notice that this function changes the actual content of the container by inserting or erasing elements from it. */ void resize(size_t n, const value_type &val= value_type()) { if (n == m_size) return; if (n > m_size) { if (!reserve(n)) { while (n != m_size) push_back(val); } return; } if (!has_trivial_destructor) { while (n != m_size) pop_back(); } m_size= n; } size_t capacity() const { return m_capacity; } size_t element_size() const { return sizeof(Element_type); } bool empty() const { return size() == 0; } size_t size() const { return m_size; } const MEM_ROOT *mem_root() const { return m_root; } private: MEM_ROOT *const m_root; Element_type *m_array; size_t m_size; size_t m_capacity; // Not (yet) implemented. Mem_root_array(const Mem_root_array&); Mem_root_array &operator=(const Mem_root_array&); }; #endif // MEM_ROOT_ARRAY_INCLUDED mysql/server/private/sql_udf.h000064400000011362151027430560012505 0ustar00#ifndef SQL_UDF_INCLUDED #define SQL_UDF_INCLUDED /* Copyright (c) 2000, 2003-2007 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file defines structures needed by udf functions */ #ifdef USE_PRAGMA_INTERFACE #pragma interface #endif enum Item_udftype {UDFTYPE_FUNCTION=1,UDFTYPE_AGGREGATE}; typedef void (*Udf_func_clear)(UDF_INIT *, uchar *, uchar *); typedef void (*Udf_func_add)(UDF_INIT *, UDF_ARGS *, uchar *, uchar *); typedef void (*Udf_func_deinit)(UDF_INIT*); typedef my_bool (*Udf_func_init)(UDF_INIT *, UDF_ARGS *, char *); typedef void *Udf_func_any; typedef double (*Udf_func_double)(UDF_INIT *, UDF_ARGS *, uchar *, uchar *); typedef longlong (*Udf_func_longlong)(UDF_INIT *, UDF_ARGS *, uchar *, uchar *); typedef struct st_udf_func { LEX_CSTRING name; Item_result returns; Item_udftype type; const char *dl; void *dlhandle; Udf_func_any func; Udf_func_init func_init; Udf_func_deinit func_deinit; Udf_func_clear func_clear; Udf_func_add func_add; Udf_func_add func_remove; ulong usage_count; } udf_func; class Item_result_field; class udf_handler :public Sql_alloc { protected: udf_func *u_d; String *buffers; UDF_ARGS f_args; UDF_INIT initid; char *num_buffer; uchar error, is_null; bool initialized; Item **args; public: bool not_original; udf_handler(udf_func *udf_arg) :u_d(udf_arg), buffers(0), error(0), is_null(0), initialized(0), not_original(0) {} ~udf_handler(); const char *name() const { return u_d ? u_d->name.str : "?"; } Item_result result_type () const { return u_d ? u_d->returns : STRING_RESULT;} bool get_arguments(); bool fix_fields(THD *thd, Item_func_or_sum *item, uint arg_count, Item **args); void cleanup(); double val(my_bool *null_value) { is_null= 0; if (get_arguments()) { *null_value=1; return 0.0; } Udf_func_double func= (Udf_func_double) u_d->func; double tmp=func(&initid, &f_args, &is_null, &error); if (is_null || error) { *null_value=1; return 0.0; } *null_value=0; return tmp; } longlong val_int(my_bool *null_value) { is_null= 0; if (get_arguments()) { *null_value=1; return 0; } Udf_func_longlong func= (Udf_func_longlong) u_d->func; longlong tmp=func(&initid, &f_args, &is_null, &error); if (is_null || error) { *null_value=1; return 0; } *null_value=0; return tmp; } my_decimal *val_decimal(my_bool *null_value, my_decimal *dec_buf); void clear() { is_null= 0; Udf_func_clear func= u_d->func_clear; func(&initid, &is_null, &error); } void add(my_bool *null_value) { if (get_arguments()) { *null_value=1; return; } Udf_func_add func= u_d->func_add; func(&initid, &f_args, &is_null, &error); *null_value= (my_bool) (is_null || error); } bool supports_removal() const { return MY_TEST(u_d->func_remove); } void remove(my_bool *null_value) { DBUG_ASSERT(u_d->func_remove); if (get_arguments()) { *null_value=1; return; } Udf_func_add func= u_d->func_remove; func(&initid, &f_args, &is_null, &error); *null_value= (my_bool) (is_null || error); } String *val_str(String *str,String *save_str); udf_handler(const udf_handler &orig) { u_d = orig.u_d; buffers = orig.buffers; f_args = orig.f_args; initid = orig.initid; num_buffer = orig.num_buffer; error = orig.error; is_null = orig.is_null; initialized = orig.initialized; args = orig.args; not_original = true; } }; #ifdef HAVE_DLOPEN void udf_init(void),udf_free(void); udf_func *find_udf(const char *name, size_t size, bool mark_used=0); void free_udf(udf_func *udf); int mysql_create_function(THD *thd,udf_func *udf); enum drop_udf_result { UDF_DEL_RESULT_ABSENT, UDF_DEL_RESULT_DELETED, UDF_DEL_RESULT_ERROR }; enum drop_udf_result mysql_drop_function(THD *thd, const LEX_CSTRING *name); #else static inline void udf_init(void) { } static inline void udf_free(void) { } #endif #endif /* SQL_UDF_INCLUDED */ mysql/server/private/message.h000064400000002253151027430560012473 0ustar00/* To change or add messages mysqld writes to the Windows error log, run mc.exe message.mc and checkin generated messages.h, messages.rc and msg000001.bin under the source control. mc.exe can be installed with Windows SDK, some Visual Studio distributions do not include it. */ // // Values are 32 bit values laid out as follows: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +---+-+-+-----------------------+-------------------------------+ // |Sev|C|R| Facility | Code | // +---+-+-+-----------------------+-------------------------------+ // // where // // Sev - is the severity code // // 00 - Success // 01 - Informational // 10 - Warning // 11 - Error // // C - is the Customer code flag // // R - is a reserved bit // // Facility - is the facility code // // Code - is the facility's status code // // // Define the facility codes // // // Define the severity codes // // // MessageId: MSG_DEFAULT // // MessageText: // // %1 // // #define MSG_DEFAULT 0xC0000064L mysql/server/private/sql_manager.h000064400000001700151027430560013334 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_MANAGER_INCLUDED #define SQL_MANAGER_INCLUDED void start_handle_manager(); void stop_handle_manager(); bool mysql_manager_submit(void (*action)(void *), void *data); #endif /* SQL_MANAGER_INCLUDED */ mysql/server/private/sql_tvc.h000064400000004562151027430560012527 0ustar00/* Copyright (c) 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SQL_TVC_INCLUDED #define SQL_TVC_INCLUDED #include "sql_type.h" typedef List List_item; typedef bool (Item::*Item_processor) (void *arg); class select_result; class Explain_select; class Explain_query; class Item_func_in; class st_select_lex_unit; typedef class st_select_lex SELECT_LEX; class Type_holder; /** @class table_value_constr @brief Definition of a Table Value Construction(TVC) It contains a list of lists of values which this TVC is defined by and reference on SELECT where this TVC is defined. */ class table_value_constr : public Sql_alloc { public: List lists_of_values; select_result *result; SELECT_LEX *select_lex; Type_holder *type_holders; enum { QEP_NOT_PRESENT_YET, QEP_AVAILABLE} have_query_plan; Explain_select *explain; ulonglong select_options; table_value_constr(List tvc_values, SELECT_LEX *sl, ulonglong select_options_arg) : lists_of_values(tvc_values), result(0), select_lex(sl), type_holders(0), have_query_plan(QEP_NOT_PRESENT_YET), explain(0), select_options(select_options_arg) { }; ha_rows get_records() { return lists_of_values.elements; } bool prepare(THD *thd_arg, SELECT_LEX *sl, select_result *tmp_result, st_select_lex_unit *unit_arg); bool to_be_wrapped_as_with_tail(); int save_explain_data_intern(THD *thd_arg, Explain_query *output); bool optimize(THD *thd_arg); bool exec(SELECT_LEX *sl); void print(THD *thd_arg, String *str, enum_query_type query_type); bool walk_values(Item_processor processor, bool walk_subquery, void *arg); }; st_select_lex *wrap_tvc_with_tail(THD *thd, st_select_lex *tvc_sl); #endif /* SQL_TVC_INCLUDED */ mysql/server/private/thread_cache.h000064400000013421151027430560013440 0ustar00/* Copyright (C) 2020 MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** MariaDB thread cache for "one thread per connection" scheduler. Thread cache allows to re-use threads (as well as THD objects) for subsequent connections. */ class Thread_cache { mutable mysql_cond_t COND_thread_cache; mutable mysql_cond_t COND_flush_thread_cache; mutable mysql_mutex_t LOCK_thread_cache; /** Queue of new connection requests. */ I_List list; /** Number of threads parked in the cache. */ ulong cached_thread_count; /** Number of active flush requests. */ uint32_t kill_cached_threads; /** PFS stuff, only used during initialization. Unfortunately needs to survive till destruction. */ PSI_cond_key key_COND_thread_cache, key_COND_flush_thread_cache; PSI_mutex_key key_LOCK_thread_cache; public: void init() { #ifdef HAVE_PSI_INTERFACE PSI_cond_info conds[]= { { &key_COND_thread_cache, "COND_thread_cache", PSI_FLAG_GLOBAL }, { &key_COND_flush_thread_cache, "COND_flush_thread_cache", PSI_FLAG_GLOBAL } }; PSI_mutex_info mutexes[]= { { &key_LOCK_thread_cache, "LOCK_thread_cache", PSI_FLAG_GLOBAL } }; mysql_mutex_register("sql", mutexes, array_elements(mutexes)); mysql_cond_register("sql", conds, array_elements(conds)); #endif mysql_mutex_init(key_LOCK_thread_cache, &LOCK_thread_cache, MY_MUTEX_INIT_FAST); mysql_cond_init(key_COND_thread_cache, &COND_thread_cache, 0); mysql_cond_init(key_COND_flush_thread_cache, &COND_flush_thread_cache, 0); list.empty(); kill_cached_threads= 0; cached_thread_count= 0; } void destroy() { DBUG_ASSERT(cached_thread_count == 0); DBUG_ASSERT(list.is_empty()); mysql_cond_destroy(&COND_flush_thread_cache); mysql_cond_destroy(&COND_thread_cache); mysql_mutex_destroy(&LOCK_thread_cache); } /** Flushes thread cache. Awakes parked threads and requests them to shutdown. Waits until last parked thread leaves the cache. */ void flush() { mysql_mutex_lock(&LOCK_thread_cache); kill_cached_threads++; while (cached_thread_count) { mysql_cond_broadcast(&COND_thread_cache); mysql_cond_wait(&COND_flush_thread_cache, &LOCK_thread_cache); } kill_cached_threads--; mysql_mutex_unlock(&LOCK_thread_cache); } /** Flushes thread cache and forbids threads parking in the cache. This is a pre-shutdown hook. */ void final_flush() { kill_cached_threads++; flush(); } /** Requests parked thread to serve new connection. @return @retval true connection is enqueued and parked thread is about to serve it @retval false thread cache is empty */ bool enqueue(CONNECT *connect) { mysql_mutex_lock(&LOCK_thread_cache); if (cached_thread_count) { list.push_back(connect); cached_thread_count--; mysql_mutex_unlock(&LOCK_thread_cache); mysql_cond_signal(&COND_thread_cache); return true; } mysql_mutex_unlock(&LOCK_thread_cache); return false; } /** Parks thread in the cache. Thread execution is suspended until either of the following occurs: - thread is requested to serve new connection; - thread cache is flushed; - THREAD_CACHE_TIMEOUT elapsed. @return @retval pointer to CONNECT if requested to serve new connection @retval 0 if thread cache is flushed or on timeout */ CONNECT *park() { struct timespec abstime; CONNECT *connect; bool flushed= false; DBUG_ENTER("Thread_cache::park"); set_timespec(abstime, THREAD_CACHE_TIMEOUT); /* Delete the instrumentation for the job that just completed, before parking this pthread in the cache (blocked on COND_thread_cache). */ PSI_CALL_delete_current_thread(); #ifndef DBUG_OFF while (_db_is_pushed_()) _db_pop_(); #endif mysql_mutex_lock(&LOCK_thread_cache); if ((connect= list.get())) cached_thread_count++; else if (cached_thread_count < thread_cache_size && !kill_cached_threads) { /* Don't kill the thread, just put it in cache for reuse */ DBUG_PRINT("info", ("Adding thread to cache")); cached_thread_count++; for (;;) { int error= mysql_cond_timedwait(&COND_thread_cache, &LOCK_thread_cache, &abstime); flushed= kill_cached_threads; if ((connect= list.get())) break; else if (flushed || error == ETIMEDOUT || error == ETIME) { /* If timeout, end thread. If a new thread is requested, we will handle the call, even if we got a timeout (as we are already awake and free) */ cached_thread_count--; break; } } } mysql_mutex_unlock(&LOCK_thread_cache); if (flushed) mysql_cond_signal(&COND_flush_thread_cache); DBUG_RETURN(connect); } /** Returns the number of parked threads. */ ulong size() const { mysql_mutex_lock(&LOCK_thread_cache); ulong r= cached_thread_count; mysql_mutex_unlock(&LOCK_thread_cache); return r; } }; extern Thread_cache thread_cache; mysql/server/private/group_by_handler.h000064400000006716151027430560014402 0ustar00/* Copyright (c) 2014, 2015 SkySQL Ab & MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef GROUP_BY_HANDLER_INCLUDED #define GROUP_BY_HANDLER_INCLUDED class Select_limit_counters; /* This file implements the group_by_handler interface. This interface can be used by storage handlers that can intercept summary or GROUP BY queries from MariaDB and itself return the result to the user or upper level. It is part of the Storage Engine API Both main and sub queries are supported. Here are some examples of what the storage engine could intersept: SELECT count(*) FROM t1; SELECT a,count(*) FROM t1 group by a; SELECT a,count(*) as sum FROM t1 where b > 10 group by a, order by sum; SELECT a,count(*) FROM t1,t2; SELECT a, (select sum(*) from t2 where t1.a=t2.a) from t2; */ /** The structure describing various parts of the query The engine is supposed to take out parts that it can do internally. For example, if the engine can return results sorted according to the specified order_by clause, it sets Query::order_by=NULL before returning. At the moment the engine must take group_by (or return an error), and optionally can take distinct, where, order_by, and having. The engine should not modify the select list. It is the extended SELECT clause (extended, because it has more items than the original user-specified SELECT clause) and it contains all aggregate functions, used in the query. */ struct Query { List *select; /* Number of auxiliary fields. */ int n_aux; bool distinct; TABLE_LIST *from; Item *where; ORDER *group_by; ORDER *order_by; Item *having; // LIMIT Select_limit_counters *limit; }; class group_by_handler { public: THD *thd; handlerton *ht; /* Temporary table where all results should be stored in record[0] The table has a field for every item from the Query::select list, except for const items and some other exceptions, see Create_tmp_table::add_fields() for which items are included and which are skipped. */ TABLE *table; group_by_handler(THD *thd_arg, handlerton *ht_arg) : thd(thd_arg), ht(ht_arg), table(0) {} virtual ~group_by_handler() = default; /* Functions to scan data. All these returns 0 if ok, error code in case of error */ /* Initialize group_by scan, prepare for next_row(). If this is a sub query with group by, this can be called many times for a query. */ virtual int init_scan()= 0; /* Return next group by result in table->record[0]. Return 0 if row found, HA_ERR_END_OF_FILE if last row and other error number in case of fatal error. */ virtual int next_row()= 0; /* End scanning */ virtual int end_scan()=0; /* Report errors */ virtual void print_error(int error, myf errflag); }; #endif //GROUP_BY_HANDLER_INCLUDED mysql/server/private/source_revision.h000064400000000103151027430560014255 0ustar00#define SOURCE_REVISION "fe8047caf26d20e98ea7f6ec1dce3924e696703f" mysql/server/private/partition_info.h000064400000045544151027430560014105 0ustar00#ifndef PARTITION_INFO_INCLUDED #define PARTITION_INFO_INCLUDED /* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_class.h" #include "partition_element.h" #include "sql_partition.h" class partition_info; struct TABLE_LIST; /* Some function typedefs */ typedef int (*get_part_id_func)(partition_info *part_info, uint32 *part_id, longlong *func_value); typedef int (*get_subpart_id_func)(partition_info *part_info, uint32 *part_id); typedef bool (*check_constants_func)(THD *thd, partition_info *part_info); struct st_ddl_log_memory_entry; #define MAX_PART_NAME_SIZE 8 struct Vers_part_info : public Sql_alloc { Vers_part_info() : limit(0), now_part(NULL), hist_part(NULL) { interval.type= INTERVAL_LAST; } Vers_part_info(Vers_part_info &src) : interval(src.interval), limit(src.limit), now_part(NULL), hist_part(NULL) { } bool initialized() { if (now_part) { DBUG_ASSERT(now_part->id != UINT_MAX32); DBUG_ASSERT(now_part->type == partition_element::CURRENT); if (hist_part) { DBUG_ASSERT(hist_part->id != UINT_MAX32); DBUG_ASSERT(hist_part->type == partition_element::HISTORY); } return true; } return false; } struct { my_time_t start; INTERVAL step; enum interval_type type; bool is_set() { return type < INTERVAL_LAST; } } interval; ulonglong limit; partition_element *now_part; partition_element *hist_part; }; /* See generate_partition_syntax() for details of how the data is used in partition expression. */ class partition_info : public Sql_alloc { public: /* * Here comes a set of definitions needed for partitioned table handlers. */ List partitions; List temp_partitions; /* These are mutually exclusive with part_expr/subpart_expr depending on what is specified in partitioning filter: expression or column list. */ List part_field_list; List subpart_field_list; /* If there is no subpartitioning, use only this func to get partition ids. If there is subpartitioning, use the this func to get partition id when you have both partition and subpartition fields. */ get_part_id_func get_partition_id; /* Get partition id when we don't have subpartition fields */ get_part_id_func get_part_partition_id; /* Get subpartition id when we have don't have partition fields by we do have subpartition ids. Mikael said that for given constant tuple {subpart_field1, ..., subpart_fieldN} the subpartition id will be the same in all subpartitions */ get_subpart_id_func get_subpartition_id; /* When we have various string fields we might need some preparation before and clean-up after calling the get_part_id_func's. We need one such method for get_part_partition_id and one for get_subpartition_id. */ get_part_id_func get_part_partition_id_charset; get_subpart_id_func get_subpartition_id_charset; check_constants_func check_constants; /* NULL-terminated array of fields used in partitioned expression */ Field **part_field_array; Field **subpart_field_array; Field **part_charset_field_array; Field **subpart_charset_field_array; /* Array of all fields used in partition and subpartition expression, without duplicates, NULL-terminated. */ Field **full_part_field_array; /* Set of all fields used in partition and subpartition expression. Required for testing of partition fields in write_set when updating. We need to set all bits in read_set because the row may need to be inserted in a different [sub]partition. */ MY_BITMAP full_part_field_set; /* When we have a field that requires transformation before calling the partition functions we must allocate field buffers for the field of the fields in the partition function. */ uchar **part_field_buffers; uchar **subpart_field_buffers; uchar **restore_part_field_ptrs; uchar **restore_subpart_field_ptrs; Item *part_expr; Item *subpart_expr; Item *item_free_list; struct st_ddl_log_memory_entry *first_log_entry; struct st_ddl_log_memory_entry *exec_log_entry; struct st_ddl_log_memory_entry *frm_log_entry; /* Bitmaps of partitions used by the current query. * read_partitions - partitions to be used for reading. * lock_partitions - partitions that must be locked (read or write). Usually read_partitions is the same set as lock_partitions, but in case of UPDATE the WHERE clause can limit the read_partitions set, but not neccesarily the lock_partitions set. Usage pattern: * Initialized in ha_partition::open(). * read+lock_partitions is set according to explicit PARTITION, WL#5217, in open_and_lock_tables(). * Bits in read_partitions can be cleared in prune_partitions() in the optimizing step. (WL#4443 is about allowing prune_partitions() to affect lock_partitions and be done before locking too). * When the partition enabled handler get an external_lock call it locks all partitions in lock_partitions (and remembers which partitions it locked, so that it can unlock them later). In case of LOCK TABLES it will lock all partitions, and keep them locked while lock_partitions can change for each statement under LOCK TABLES. * Freed at the same time item_free_list is freed. */ MY_BITMAP read_partitions; MY_BITMAP lock_partitions; bool bitmaps_are_initialized; union { longlong *range_int_array; LIST_PART_ENTRY *list_array; part_column_list_val *range_col_array; part_column_list_val *list_col_array; }; Vers_part_info *vers_info; /******************************************** * INTERVAL ANALYSIS ********************************************/ /* Partitioning interval analysis function for partitioning, or NULL if interval analysis is not supported for this kind of partitioning. */ get_partitions_in_range_iter get_part_iter_for_interval; /* Partitioning interval analysis function for subpartitioning, or NULL if interval analysis is not supported for this kind of partitioning. */ get_partitions_in_range_iter get_subpart_iter_for_interval; /******************************************** * INTERVAL ANALYSIS ENDS ********************************************/ longlong err_value; char* part_info_string; partition_element *curr_part_elem; // part or sub part partition_element *current_partition; // partition part_elem_value *curr_list_val; uint curr_list_object; uint num_columns; TABLE *table; /* These key_map's are used for Partitioning to enable quick decisions on whether we can derive more information about which partition to scan just by looking at what index is used. */ key_map all_fields_in_PF, all_fields_in_PPF, all_fields_in_SPF; key_map some_fields_in_PF; handlerton *default_engine_type; partition_type part_type; partition_type subpart_type; uint part_info_len; uint num_parts; uint num_subparts; uint count_curr_subparts; // used during parsing uint num_list_values; uint num_part_fields; uint num_subpart_fields; uint num_full_part_fields; uint has_null_part_id; uint32 default_partition_id; /* This variable is used to calculate the partition id when using LINEAR KEY/HASH. This functionality is kept in the MySQL Server but mainly of use to handlers supporting partitioning. */ uint16 linear_hash_mask; /* PARTITION BY KEY ALGORITHM=N Which algorithm to use for hashing the fields. N = 1 - Use 5.1 hashing (numeric fields are hashed as binary) N = 2 - Use 5.5 hashing (numeric fields are hashed like latin1 bytes) */ enum enum_key_algorithm { KEY_ALGORITHM_NONE= 0, KEY_ALGORITHM_51= 1, KEY_ALGORITHM_55= 2 }; enum_key_algorithm key_algorithm; /* Only the number of partitions defined (uses default names and options). */ bool use_default_partitions; bool use_default_num_partitions; /* Only the number of subpartitions defined (uses default names etc.). */ bool use_default_subpartitions; bool use_default_num_subpartitions; bool default_partitions_setup; bool defined_max_value; inline bool has_default_partititon() { return (part_type == LIST_PARTITION && defined_max_value); } bool list_of_part_fields; // KEY or COLUMNS PARTITIONING bool list_of_subpart_fields; // KEY SUBPARTITIONING bool linear_hash_ind; // LINEAR HASH/KEY bool fixed; bool is_auto_partitioned; bool has_null_value; bool column_list; // COLUMNS PARTITIONING, 5.5+ partition_info() : get_partition_id(NULL), get_part_partition_id(NULL), get_subpartition_id(NULL), part_field_array(NULL), subpart_field_array(NULL), part_charset_field_array(NULL), subpart_charset_field_array(NULL), full_part_field_array(NULL), part_field_buffers(NULL), subpart_field_buffers(NULL), restore_part_field_ptrs(NULL), restore_subpart_field_ptrs(NULL), part_expr(NULL), subpart_expr(NULL), item_free_list(NULL), first_log_entry(NULL), exec_log_entry(NULL), frm_log_entry(NULL), bitmaps_are_initialized(FALSE), list_array(NULL), vers_info(NULL), err_value(0), part_info_string(NULL), curr_part_elem(NULL), current_partition(NULL), curr_list_object(0), num_columns(0), table(NULL), default_engine_type(NULL), part_type(NOT_A_PARTITION), subpart_type(NOT_A_PARTITION), part_info_len(0), num_parts(0), num_subparts(0), count_curr_subparts(0), num_list_values(0), num_part_fields(0), num_subpart_fields(0), num_full_part_fields(0), has_null_part_id(0), linear_hash_mask(0), key_algorithm(KEY_ALGORITHM_NONE), use_default_partitions(TRUE), use_default_num_partitions(TRUE), use_default_subpartitions(TRUE), use_default_num_subpartitions(TRUE), default_partitions_setup(FALSE), defined_max_value(FALSE), list_of_part_fields(FALSE), list_of_subpart_fields(FALSE), linear_hash_ind(FALSE), fixed(FALSE), is_auto_partitioned(FALSE), has_null_value(FALSE), column_list(FALSE) { all_fields_in_PF.clear_all(); all_fields_in_PPF.clear_all(); all_fields_in_SPF.clear_all(); some_fields_in_PF.clear_all(); partitions.empty(); temp_partitions.empty(); part_field_list.empty(); subpart_field_list.empty(); } ~partition_info() = default; partition_info *get_clone(THD *thd, bool empty_data_and_index_file= FALSE); bool set_named_partition_bitmap(const char *part_name, size_t length); bool set_partition_bitmaps(List *partition_names); /* Answers the question if subpartitioning is used for a certain table */ bool is_sub_partitioned() { return (subpart_type == NOT_A_PARTITION ? FALSE : TRUE); } /* Returns the total number of partitions on the leaf level */ uint get_tot_partitions() { return num_parts * (is_sub_partitioned() ? num_subparts : 1); } bool set_up_defaults_for_partitioning(THD *thd, handler *file, HA_CREATE_INFO *info, uint start_no); const char *find_duplicate_field(); char *find_duplicate_name(); bool check_engine_mix(handlerton *engine_type, bool default_engine); bool check_partition_info(THD *thd, handlerton **eng_type, handler *file, HA_CREATE_INFO *info, partition_info *add_or_reorg_part= NULL); void print_no_partition_found(TABLE *table, myf errflag); void print_debug(const char *str, uint*); Item* get_column_item(Item *item, Field *field); int fix_partition_values(THD *thd, part_elem_value *val, partition_element *part_elem); bool fix_column_value_functions(THD *thd, part_elem_value *val, uint part_id); bool fix_parser_data(THD *thd); int add_max_value(THD *thd); void init_col_val(part_column_list_val *col_val, Item *item); int reorganize_into_single_field_col_val(THD *thd); part_column_list_val *add_column_value(THD *thd); bool set_part_expr(THD *thd, Item *item_ptr, bool is_subpart); bool set_up_charset_field_preps(THD *thd); bool check_partition_field_length(); bool init_column_part(THD *thd); bool add_column_list_value(THD *thd, Item *item); partition_element *get_part_elem(const char *partition_name, char *file_name, size_t file_name_size, uint32 *part_id); void report_part_expr_error(bool use_subpart_expr); bool has_same_partitioning(partition_info *new_part_info); bool error_if_requires_values() const; private: bool set_up_default_partitions(THD *thd, handler *file, HA_CREATE_INFO *info, uint start_no); bool set_up_default_subpartitions(THD *thd, handler *file, HA_CREATE_INFO *info); char *create_default_partition_names(THD *thd, uint part_no, uint num_parts, uint start_no); char *create_default_subpartition_name(THD *thd, uint subpart_no, const char *part_name); bool prune_partition_bitmaps(List *partition_names); // set_read_partitions() in 8.0 bool add_named_partition(const char *part_name, size_t length); public: bool has_unique_name(partition_element *element); bool field_in_partition_expr(Field *field) const; bool vers_init_info(THD *thd); bool vers_set_interval(THD *thd, Item *interval, interval_type int_type, Item *starts, const char *table_name); bool vers_set_limit(ulonglong limit) { DBUG_ASSERT(part_type == VERSIONING_PARTITION); vers_info->limit= limit; return !limit; } bool vers_require_hist_part(THD *thd) const { return part_type == VERSIONING_PARTITION && thd->lex->vers_history_generating(); } int vers_set_hist_part(THD *thd); void vers_check_limit(THD *thd); bool vers_fix_field_list(THD *thd); void vers_update_el_ids(); partition_element *get_partition(uint part_id) { List_iterator it(partitions); partition_element *el; while ((el= it++)) { if (el->id == part_id) return el; } return NULL; } uint next_part_no(uint new_parts) const; }; uint32 get_next_partition_id_range(struct st_partition_iter* part_iter); bool check_partition_dirs(partition_info *part_info); /* Initialize the iterator to return a single partition with given part_id */ static inline void init_single_partition_iterator(uint32 part_id, PARTITION_ITERATOR *part_iter) { part_iter->part_nums.start= part_iter->part_nums.cur= part_id; part_iter->part_nums.end= part_id+1; part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE; part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE; part_iter->get_next= get_next_partition_id_range; } /* Initialize the iterator to enumerate all partitions */ static inline void init_all_partitions_iterator(partition_info *part_info, PARTITION_ITERATOR *part_iter) { part_iter->part_nums.start= part_iter->part_nums.cur= 0; part_iter->part_nums.end= part_info->num_parts; part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE; part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE; part_iter->get_next= get_next_partition_id_range; } /** @brief Update part_field_list by row_end field name @returns true on error; false on success */ inline bool partition_info::vers_fix_field_list(THD * thd) { if (!table->versioned()) { // frm must be corrupted, normally CREATE/ALTER TABLE checks for that my_error(ER_FILE_CORRUPT, MYF(0), table->s->path.str); return true; } DBUG_ASSERT(part_type == VERSIONING_PARTITION); DBUG_ASSERT(table->versioned(VERS_TIMESTAMP)); Field *row_end= table->vers_end_field(); // needed in handle_list_of_fields() row_end->flags|= GET_FIXED_FIELDS_FLAG; Name_resolution_context *context= &thd->lex->current_select->context; Item *row_end_item= new (thd->mem_root) Item_field(thd, context, row_end); Item *row_end_ts= new (thd->mem_root) Item_func_unix_timestamp(thd, row_end_item); set_part_expr(thd, row_end_ts, false); return false; } /** @brief Update partition_element's id @returns true on error; false on success */ inline void partition_info::vers_update_el_ids() { DBUG_ASSERT(part_type == VERSIONING_PARTITION); DBUG_ASSERT(table->versioned(VERS_TIMESTAMP)); List_iterator it(partitions); partition_element *el; for(uint32 id= 0; ((el= it++)); id++) { DBUG_ASSERT(el->type != partition_element::CONVENTIONAL); /* Newly added element is inserted before AS_OF_NOW. */ if (el->id == UINT_MAX32 || el->type == partition_element::CURRENT) { el->id= id; if (el->type == partition_element::CURRENT) break; } } } inline bool make_partition_name(char *move_ptr, uint i) { int res= snprintf(move_ptr, MAX_PART_NAME_SIZE + 1, "p%u", i); return res < 0 || res > MAX_PART_NAME_SIZE; } #ifdef WITH_PARTITION_STORAGE_ENGINE inline uint partition_info::next_part_no(uint new_parts) const { if (part_type != VERSIONING_PARTITION) return num_parts; DBUG_ASSERT(new_parts > 0); /* Choose first non-occupied name suffix */ uint32 suffix= num_parts - 1; DBUG_ASSERT(suffix > 0); char part_name[MAX_PART_NAME_SIZE + 1]; List_iterator_fast it(table->part_info->partitions); for (uint cur_part= 0; cur_part < new_parts; ++cur_part, ++suffix) { uint32 cur_suffix= suffix; if (make_partition_name(part_name, suffix)) return 0; partition_element *el; it.rewind(); while ((el= it++)) { if (0 == my_strcasecmp(&my_charset_latin1, el->partition_name, part_name)) { if (make_partition_name(part_name, ++suffix)) return 0; it.rewind(); } } if (cur_part > 0 && suffix > cur_suffix) cur_part= 0; } return suffix - new_parts; } #endif #endif /* PARTITION_INFO_INCLUDED */ mysql/server/private/aria_backup.h000064400000003013151027430560013303 0ustar00/* Copyright (C) 2018,2020 MariaDB Corporation Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ /* Interfaces for doing backups of Aria tables */ C_MODE_START typedef struct st_aria_table_capabilities { my_off_t header_size; ulong bitmap_pages_covered; uint block_size; uint keypage_header; enum data_file_type data_file_type; my_bool checksum; my_bool transactional; my_bool encrypted; /* This is true if the table can be copied without any locks */ my_bool online_backup_safe; /* s3 capabilities */ ulong s3_block_size; uint8 compression; } ARIA_TABLE_CAPABILITIES; int aria_get_capabilities(File kfile, ARIA_TABLE_CAPABILITIES *cap); int aria_read_index(File kfile, ARIA_TABLE_CAPABILITIES *cap, ulonglong block, uchar *buffer); int aria_read_data(File dfile, ARIA_TABLE_CAPABILITIES *cap, ulonglong block, uchar *buffer, size_t *bytes_read); C_MODE_END mysql/server/private/sql_view.h000064400000004646151027430560012710 0ustar00#ifndef SQL_VIEW_INCLUDED #define SQL_VIEW_INCLUDED /* -*- C++ -*- */ /* Copyright (c) 2004, 2010, Oracle and/or its affiliates. Copyright (c) 2015, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_class.h" /* Required by sql_lex.h */ #include "sql_lex.h" /* enum_view_create_mode, enum_drop_mode */ /* Forward declarations */ class File_parser; /* Function declarations */ bool create_view_precheck(THD *thd, TABLE_LIST *tables, TABLE_LIST *view, enum_view_create_mode mode); bool mysql_create_view(THD *thd, TABLE_LIST *view, enum_view_create_mode mode); bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table, bool open_view_no_parse); bool mysql_drop_view(THD *thd, TABLE_LIST *view, enum_drop_mode drop_mode); bool check_key_in_view(THD *thd, TABLE_LIST * view); bool insert_view_fields(THD *thd, List *list, TABLE_LIST *view); int view_checksum(THD *thd, TABLE_LIST *view); int view_check(THD *thd, TABLE_LIST *view, HA_CHECK_OPT *check_opt); int view_repair(THD *thd, TABLE_LIST *view, HA_CHECK_OPT *check_opt); extern TYPELIB updatable_views_with_limit_typelib; bool check_duplicate_names(THD *thd, List& item_list, bool gen_unique_view_names); bool mysql_rename_view(THD *thd, const LEX_CSTRING *new_db, const LEX_CSTRING *new_name, const LEX_CSTRING *old_db, const LEX_CSTRING *old_name); void make_valid_column_names(THD *thd, List &item_list); #define VIEW_ANY_ACL (SELECT_ACL | UPDATE_ACL | INSERT_ACL | DELETE_ACL) extern const LEX_CSTRING view_type; void make_valid_column_names(List &item_list); bool mariadb_view_version_get(TABLE_SHARE *share); #endif /* SQL_VIEW_INCLUDED */ mysql/server/private/my_atomic.h000064400000016161151027430560013033 0ustar00#ifndef MY_ATOMIC_INCLUDED #define MY_ATOMIC_INCLUDED /* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2018, 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This header defines five atomic operations: my_atomic_add#(&var, what) my_atomic_add#_explicit(&var, what, memory_order) 'Fetch and Add' add 'what' to *var, and return the old value of *var All memory orders are valid. my_atomic_fas#(&var, what) my_atomic_fas#_explicit(&var, what, memory_order) 'Fetch And Store' store 'what' in *var, and return the old value of *var All memory orders are valid. my_atomic_cas#(&var, &old, new) my_atomic_cas#_weak_explicit(&var, &old, new, succ, fail) my_atomic_cas#_strong_explicit(&var, &old, new, succ, fail) 'Compare And Swap' if *var is equal to *old, then store 'new' in *var, and return TRUE otherwise store *var in *old, and return FALSE succ - the memory synchronization ordering for the read-modify-write operation if the comparison succeeds. All memory orders are valid. fail - the memory synchronization ordering for the load operation if the comparison fails. Cannot be MY_MEMORY_ORDER_RELEASE or MY_MEMORY_ORDER_ACQ_REL and cannot specify stronger ordering than succ. The weak form is allowed to fail spuriously, that is, act as if *var != *old even if they are equal. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable. my_atomic_load#(&var) my_atomic_load#_explicit(&var, memory_order) return *var Order must be one of MY_MEMORY_ORDER_RELAXED, MY_MEMORY_ORDER_CONSUME, MY_MEMORY_ORDER_ACQUIRE, MY_MEMORY_ORDER_SEQ_CST. my_atomic_store#(&var, what) my_atomic_store#_explicit(&var, what, memory_order) store 'what' in *var Order must be one of MY_MEMORY_ORDER_RELAXED, MY_MEMORY_ORDER_RELEASE, MY_MEMORY_ORDER_SEQ_CST. '#' is substituted by a size suffix - 8, 16, 32, 64, or ptr (e.g. my_atomic_add8, my_atomic_fas32, my_atomic_casptr). The first version orders memory accesses according to MY_MEMORY_ORDER_SEQ_CST, the second version (with _explicit suffix) orders memory accesses according to given memory order. memory_order specifies how non-atomic memory accesses are to be ordered around an atomic operation: MY_MEMORY_ORDER_RELAXED - there are no constraints on reordering of memory accesses around the atomic variable. MY_MEMORY_ORDER_CONSUME - no reads in the current thread dependent on the value currently loaded can be reordered before this load. This ensures that writes to dependent variables in other threads that release the same atomic variable are visible in the current thread. On most platforms, this affects compiler optimization only. MY_MEMORY_ORDER_ACQUIRE - no reads in the current thread can be reordered before this load. This ensures that all writes in other threads that release the same atomic variable are visible in the current thread. MY_MEMORY_ORDER_RELEASE - no writes in the current thread can be reordered after this store. This ensures that all writes in the current thread are visible in other threads that acquire the same atomic variable. MY_MEMORY_ORDER_ACQ_REL - no reads in the current thread can be reordered before this load as well as no writes in the current thread can be reordered after this store. The operation is read-modify-write operation. It is ensured that all writes in another threads that release the same atomic variable are visible before the modification and the modification is visible in other threads that acquire the same atomic variable. MY_MEMORY_ORDER_SEQ_CST - The operation has the same semantics as acquire-release operation, and additionally has sequentially-consistent operation ordering. We choose implementation as follows: on Windows using Visual C++ the native implementation should be preferable. When using gcc we prefer the Solaris implementation before the gcc because of stability preference, we choose gcc builtins if available. */ #if defined(_MSC_VER) #include "atomic/generic-msvc.h" #elif defined(HAVE_SOLARIS_ATOMIC) #include "atomic/solaris.h" #elif defined(HAVE_GCC_C11_ATOMICS) #include "atomic/gcc_builtins.h" #endif #ifndef MY_MEMORY_ORDER_SEQ_CST #define MY_MEMORY_ORDER_RELAXED #define MY_MEMORY_ORDER_CONSUME #define MY_MEMORY_ORDER_ACQUIRE #define MY_MEMORY_ORDER_RELEASE #define MY_MEMORY_ORDER_ACQ_REL #define MY_MEMORY_ORDER_SEQ_CST #define my_atomic_store32_explicit(P, D, O) my_atomic_store32((P), (D)) #define my_atomic_store64_explicit(P, D, O) my_atomic_store64((P), (D)) #define my_atomic_storeptr_explicit(P, D, O) my_atomic_storeptr((P), (D)) #define my_atomic_load32_explicit(P, O) my_atomic_load32((P)) #define my_atomic_load64_explicit(P, O) my_atomic_load64((P)) #define my_atomic_loadptr_explicit(P, O) my_atomic_loadptr((P)) #define my_atomic_fas32_explicit(P, D, O) my_atomic_fas32((P), (D)) #define my_atomic_fas64_explicit(P, D, O) my_atomic_fas64((P), (D)) #define my_atomic_fasptr_explicit(P, D, O) my_atomic_fasptr((P), (D)) #define my_atomic_add32_explicit(P, A, O) my_atomic_add32((P), (A)) #define my_atomic_add64_explicit(P, A, O) my_atomic_add64((P), (A)) #define my_atomic_addptr_explicit(P, A, O) my_atomic_addptr((P), (A)) #define my_atomic_cas32_weak_explicit(P, E, D, S, F) \ my_atomic_cas32((P), (E), (D)) #define my_atomic_cas64_weak_explicit(P, E, D, S, F) \ my_atomic_cas64((P), (E), (D)) #define my_atomic_casptr_weak_explicit(P, E, D, S, F) \ my_atomic_casptr((P), (E), (D)) #define my_atomic_cas32_strong_explicit(P, E, D, S, F) \ my_atomic_cas32((P), (E), (D)) #define my_atomic_cas64_strong_explicit(P, E, D, S, F) \ my_atomic_cas64((P), (E), (D)) #define my_atomic_casptr_strong_explicit(P, E, D, S, F) \ my_atomic_casptr((P), (E), (D)) #endif #endif /* MY_ATOMIC_INCLUDED */ mysql/server/private/win_tzname_data.h000064400000014552151027430560014220 0ustar00/* This file was generated using gen_win_tzname_data.ps1 */ {L"Dateline Standard Time","Etc/GMT+12"}, {L"UTC-11","Etc/GMT+11"}, {L"Aleutian Standard Time","America/Adak"}, {L"Hawaiian Standard Time","Pacific/Honolulu"}, {L"Marquesas Standard Time","Pacific/Marquesas"}, {L"Alaskan Standard Time","America/Anchorage"}, {L"UTC-09","Etc/GMT+9"}, {L"Pacific Standard Time (Mexico)","America/Tijuana"}, {L"UTC-08","Etc/GMT+8"}, {L"Pacific Standard Time","America/Los_Angeles"}, {L"US Mountain Standard Time","America/Phoenix"}, {L"Mountain Standard Time (Mexico)","America/Mazatlan"}, {L"Mountain Standard Time","America/Denver"}, {L"Yukon Standard Time","America/Whitehorse"}, {L"Central America Standard Time","America/Guatemala"}, {L"Central Standard Time","America/Chicago"}, {L"Easter Island Standard Time","Pacific/Easter"}, {L"Central Standard Time (Mexico)","America/Mexico_City"}, {L"Canada Central Standard Time","America/Regina"}, {L"SA Pacific Standard Time","America/Bogota"}, {L"Eastern Standard Time (Mexico)","America/Cancun"}, {L"Eastern Standard Time","America/New_York"}, {L"Haiti Standard Time","America/Port-au-Prince"}, {L"Cuba Standard Time","America/Havana"}, {L"US Eastern Standard Time","America/Indianapolis"}, {L"Turks And Caicos Standard Time","America/Grand_Turk"}, {L"Paraguay Standard Time","America/Asuncion"}, {L"Atlantic Standard Time","America/Halifax"}, {L"Venezuela Standard Time","America/Caracas"}, {L"Central Brazilian Standard Time","America/Cuiaba"}, {L"SA Western Standard Time","America/La_Paz"}, {L"Pacific SA Standard Time","America/Santiago"}, {L"Newfoundland Standard Time","America/St_Johns"}, {L"Tocantins Standard Time","America/Araguaina"}, {L"E. South America Standard Time","America/Sao_Paulo"}, {L"SA Eastern Standard Time","America/Cayenne"}, {L"Argentina Standard Time","America/Buenos_Aires"}, {L"Greenland Standard Time","America/Godthab"}, {L"Montevideo Standard Time","America/Montevideo"}, {L"Magallanes Standard Time","America/Punta_Arenas"}, {L"Saint Pierre Standard Time","America/Miquelon"}, {L"Bahia Standard Time","America/Bahia"}, {L"UTC-02","Etc/GMT+2"}, {L"Azores Standard Time","Atlantic/Azores"}, {L"Cape Verde Standard Time","Atlantic/Cape_Verde"}, {L"UTC","Etc/UTC"}, {L"GMT Standard Time","Europe/London"}, {L"Greenwich Standard Time","Atlantic/Reykjavik"}, {L"Sao Tome Standard Time","Africa/Sao_Tome"}, {L"Morocco Standard Time","Africa/Casablanca"}, {L"W. Europe Standard Time","Europe/Berlin"}, {L"Central Europe Standard Time","Europe/Budapest"}, {L"Romance Standard Time","Europe/Paris"}, {L"Central European Standard Time","Europe/Warsaw"}, {L"W. Central Africa Standard Time","Africa/Lagos"}, {L"Jordan Standard Time","Asia/Amman"}, {L"GTB Standard Time","Europe/Bucharest"}, {L"Middle East Standard Time","Asia/Beirut"}, {L"Egypt Standard Time","Africa/Cairo"}, {L"E. Europe Standard Time","Europe/Chisinau"}, {L"Syria Standard Time","Asia/Damascus"}, {L"West Bank Standard Time","Asia/Hebron"}, {L"South Africa Standard Time","Africa/Johannesburg"}, {L"FLE Standard Time","Europe/Kiev"}, {L"Israel Standard Time","Asia/Jerusalem"}, {L"South Sudan Standard Time","Africa/Juba"}, {L"Kaliningrad Standard Time","Europe/Kaliningrad"}, {L"Sudan Standard Time","Africa/Khartoum"}, {L"Libya Standard Time","Africa/Tripoli"}, {L"Namibia Standard Time","Africa/Windhoek"}, {L"Arabic Standard Time","Asia/Baghdad"}, {L"Turkey Standard Time","Europe/Istanbul"}, {L"Arab Standard Time","Asia/Riyadh"}, {L"Belarus Standard Time","Europe/Minsk"}, {L"Russian Standard Time","Europe/Moscow"}, {L"E. Africa Standard Time","Africa/Nairobi"}, {L"Iran Standard Time","Asia/Tehran"}, {L"Arabian Standard Time","Asia/Dubai"}, {L"Astrakhan Standard Time","Europe/Astrakhan"}, {L"Azerbaijan Standard Time","Asia/Baku"}, {L"Russia Time Zone 3","Europe/Samara"}, {L"Mauritius Standard Time","Indian/Mauritius"}, {L"Saratov Standard Time","Europe/Saratov"}, {L"Georgian Standard Time","Asia/Tbilisi"}, {L"Volgograd Standard Time","Europe/Volgograd"}, {L"Caucasus Standard Time","Asia/Yerevan"}, {L"Afghanistan Standard Time","Asia/Kabul"}, {L"West Asia Standard Time","Asia/Tashkent"}, {L"Ekaterinburg Standard Time","Asia/Yekaterinburg"}, {L"Pakistan Standard Time","Asia/Karachi"}, {L"Qyzylorda Standard Time","Asia/Qyzylorda"}, {L"India Standard Time","Asia/Calcutta"}, {L"Sri Lanka Standard Time","Asia/Colombo"}, {L"Nepal Standard Time","Asia/Katmandu"}, {L"Central Asia Standard Time","Asia/Bishkek"}, {L"Bangladesh Standard Time","Asia/Dhaka"}, {L"Omsk Standard Time","Asia/Omsk"}, {L"Myanmar Standard Time","Asia/Rangoon"}, {L"SE Asia Standard Time","Asia/Bangkok"}, {L"Altai Standard Time","Asia/Barnaul"}, {L"W. Mongolia Standard Time","Asia/Hovd"}, {L"North Asia Standard Time","Asia/Krasnoyarsk"}, {L"N. Central Asia Standard Time","Asia/Novosibirsk"}, {L"Tomsk Standard Time","Asia/Tomsk"}, {L"China Standard Time","Asia/Shanghai"}, {L"North Asia East Standard Time","Asia/Irkutsk"}, {L"Singapore Standard Time","Asia/Singapore"}, {L"W. Australia Standard Time","Australia/Perth"}, {L"Taipei Standard Time","Asia/Taipei"}, {L"Ulaanbaatar Standard Time","Asia/Ulaanbaatar"}, {L"Aus Central W. Standard Time","Australia/Eucla"}, {L"Transbaikal Standard Time","Asia/Chita"}, {L"Tokyo Standard Time","Asia/Tokyo"}, {L"North Korea Standard Time","Asia/Pyongyang"}, {L"Korea Standard Time","Asia/Seoul"}, {L"Yakutsk Standard Time","Asia/Yakutsk"}, {L"Cen. Australia Standard Time","Australia/Adelaide"}, {L"AUS Central Standard Time","Australia/Darwin"}, {L"E. Australia Standard Time","Australia/Brisbane"}, {L"AUS Eastern Standard Time","Australia/Sydney"}, {L"West Pacific Standard Time","Pacific/Port_Moresby"}, {L"Tasmania Standard Time","Australia/Hobart"}, {L"Vladivostok Standard Time","Asia/Vladivostok"}, {L"Lord Howe Standard Time","Australia/Lord_Howe"}, {L"Bougainville Standard Time","Pacific/Bougainville"}, {L"Russia Time Zone 10","Asia/Srednekolymsk"}, {L"Magadan Standard Time","Asia/Magadan"}, {L"Norfolk Standard Time","Pacific/Norfolk"}, {L"Sakhalin Standard Time","Asia/Sakhalin"}, {L"Central Pacific Standard Time","Pacific/Guadalcanal"}, {L"Russia Time Zone 11","Asia/Kamchatka"}, {L"New Zealand Standard Time","Pacific/Auckland"}, {L"UTC+12","Etc/GMT-12"}, {L"Fiji Standard Time","Pacific/Fiji"}, {L"Chatham Islands Standard Time","Pacific/Chatham"}, {L"UTC+13","Etc/GMT-13"}, {L"Tonga Standard Time","Pacific/Tongatapu"}, {L"Samoa Standard Time","Pacific/Apia"}, {L"Line Islands Standard Time","Pacific/Kiritimati"}, mysql/server/private/sql_digest_stream.h000064400000003037151027430560014561 0ustar00/* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_DIGEST_STREAM_H #define SQL_DIGEST_STREAM_H #include "sql_digest.h" /** State data storage for @c digest_start, @c digest_add_token. This structure extends the @c sql_digest_storage structure with temporary state used only during parsing. */ struct sql_digest_state { /** Index, in the digest token array, of the last identifier seen. Reduce rules used in the digest computation can not apply to tokens seen before an identifier. @sa digest_add_token */ int m_last_id_index; sql_digest_storage m_digest_storage; inline void reset(unsigned char *token_array, uint length) { m_last_id_index= 0; m_digest_storage.reset(token_array, length); } inline bool is_empty() { return m_digest_storage.is_empty(); } }; typedef struct sql_digest_state sql_digest_state; #endif mysql/server/private/password.h000064400000002222151027430560012705 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef PASSWORD_INCLUDED #define PASSWORD_INCLUDED C_MODE_START void my_make_scrambled_password_323(char *to, const char *password, size_t pass_len); void my_make_scrambled_password(char *to, const char *password, size_t pass_len); void hash_password(ulong *result, const char *password, uint password_len); C_MODE_END #endif /* PASSWORD_INCLUDED */ mysql/server/private/set_var.h000064400000040247151027430560012517 0ustar00#ifndef SET_VAR_INCLUDED #define SET_VAR_INCLUDED /* Copyright (c) 2002, 2013, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file "public" interface to sys_var - server configuration variables. */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include #include class sys_var; class set_var; class sys_var_pluginvar; class PolyLock; class Item_func_set_user_var; // This include needs to be here since item.h requires enum_var_type :-P #include "item.h" /* Item */ #include "sql_class.h" /* THD */ extern TYPELIB bool_typelib; struct sys_var_chain { sys_var *first; sys_var *last; }; int mysql_add_sys_var_chain(sys_var *chain); int mysql_del_sys_var_chain(sys_var *chain); /** A class representing one system variable - that is something that can be accessed as @@global.variable_name or @@session.variable_name, visible in SHOW xxx VARIABLES and in INFORMATION_SCHEMA.xxx_VARIABLES, optionally it can be assigned to, optionally it can have a command-line counterpart with the same name. */ class sys_var: protected Value_source // for double_from_string_with_check { public: sys_var *next; LEX_CSTRING name; bool *test_load; enum flag_enum { GLOBAL, SESSION, ONLY_SESSION, SCOPE_MASK=1023, READONLY=1024, ALLOCATED=2048, PARSE_EARLY=4096, NO_SET_STATEMENT=8192, AUTO_SET=16384}; enum { NO_GETOPT=-1, GETOPT_ONLY_HELP=-2 }; enum where { CONFIG, COMMAND_LINE, AUTO, SQL, COMPILE_TIME, ENV }; /** Enumeration type to indicate for a system variable whether it will be written to the binlog or not. */ enum binlog_status_enum { VARIABLE_NOT_IN_BINLOG, SESSION_VARIABLE_IN_BINLOG } binlog_status; my_option option; ///< min, max, default values are stored here enum where value_origin; const char *origin_filename; protected: typedef bool (*on_check_function)(sys_var *self, THD *thd, set_var *var); typedef bool (*on_update_function)(sys_var *self, THD *thd, enum_var_type type); int flags; ///< or'ed flag_enum values const SHOW_TYPE show_val_type; ///< what value_ptr() returns for sql_show.cc PolyLock *guard; ///< *second* lock that protects the variable ptrdiff_t offset; ///< offset to the value from global_system_variables on_check_function on_check; on_update_function on_update; const char *const deprecation_substitute; public: sys_var(sys_var_chain *chain, const char *name_arg, const char *comment, int flag_args, ptrdiff_t off, int getopt_id, enum get_opt_arg_type getopt_arg_type, SHOW_TYPE show_val_type_arg, longlong def_val, PolyLock *lock, enum binlog_status_enum binlog_status_arg, on_check_function on_check_func, on_update_function on_update_func, const char *substitute); virtual ~sys_var() = default; /** All the cleanup procedures should be performed here */ virtual void cleanup() {} /** downcast for sys_var_pluginvar. Returns this if it's an instance of sys_var_pluginvar, and 0 otherwise. */ virtual sys_var_pluginvar *cast_pluginvar() { return 0; } bool check(THD *thd, set_var *var); const uchar *value_ptr(THD *thd, enum_var_type type, const LEX_CSTRING *base) const; /** Update the system variable with the default value from either session or global scope. The default value is stored in the 'var' argument. Return false when successful. */ bool set_default(THD *thd, set_var *var); bool update(THD *thd, set_var *var); String *val_str_nolock(String *str, THD *thd, const uchar *value); longlong val_int(bool *is_null, THD *thd, enum_var_type type, const LEX_CSTRING *base); String *val_str(String *str, THD *thd, enum_var_type type, const LEX_CSTRING *base); double val_real(bool *is_null, THD *thd, enum_var_type type, const LEX_CSTRING *base); SHOW_TYPE show_type() const { return show_val_type; } int scope() const { return flags & SCOPE_MASK; } virtual CHARSET_INFO *charset(THD *thd) const { return system_charset_info; } bool is_readonly() const { return flags & READONLY; } /** the following is only true for keycache variables, that support the syntax @@keycache_name.variable_name */ bool is_struct() { return option.var_type & GET_ASK_ADDR; } bool is_set_stmt_ok() const { return !(flags & NO_SET_STATEMENT); } bool is_written_to_binlog(enum_var_type type) { return type != OPT_GLOBAL && binlog_status == SESSION_VARIABLE_IN_BINLOG; } bool check_update_type(const Item *item) { Item_result type= item->result_type(); switch (option.var_type & GET_TYPE_MASK) { case GET_INT: case GET_UINT: case GET_LONG: case GET_ULONG: case GET_LL: case GET_ULL: return type != INT_RESULT && (type != DECIMAL_RESULT || item->decimals != 0); case GET_STR: case GET_STR_ALLOC: return type != STRING_RESULT; case GET_ENUM: case GET_BOOL: case GET_SET: case GET_FLAGSET: case GET_BIT: return type != STRING_RESULT && type != INT_RESULT; case GET_DOUBLE: return type != INT_RESULT && type != REAL_RESULT && type != DECIMAL_RESULT; default: return true; } } bool check_type(enum_var_type type) { switch (scope()) { case GLOBAL: return type != OPT_GLOBAL; case SESSION: return false; // always ok case ONLY_SESSION: return type == OPT_GLOBAL; } return true; // keep gcc happy } bool register_option(DYNAMIC_ARRAY *array, int parse_flags) { DBUG_ASSERT(parse_flags == GETOPT_ONLY_HELP || parse_flags == PARSE_EARLY || parse_flags == 0); if (option.id == NO_GETOPT) return 0; if (parse_flags == GETOPT_ONLY_HELP) { if (option.id != GETOPT_ONLY_HELP) return 0; } else { if (option.id == GETOPT_ONLY_HELP) return 0; if ((flags & PARSE_EARLY) != parse_flags) return 0; } return insert_dynamic(array, (uchar*)&option); } void do_deprecated_warning(THD *thd); /** whether session value of a sysvar is a default one. in this simple implementation we don't distinguish between default and non-default values. for most variables it's ok, they don't treat default values specially. this method is overwritten in descendant classes as necessary. */ virtual bool session_is_default(THD *thd) { return false; } virtual const uchar *default_value_ptr(THD *thd) const { return (uchar*)&option.def_value; } virtual bool on_check_access_global(THD *thd) const; virtual bool on_check_access_session(THD *thd) const { return false; } private: virtual bool do_check(THD *thd, set_var *var) = 0; /** save the session default value of the variable in var */ virtual void session_save_default(THD *thd, set_var *var) = 0; /** save the global default value of the variable in var */ virtual void global_save_default(THD *thd, set_var *var) = 0; virtual bool session_update(THD *thd, set_var *var) = 0; virtual bool global_update(THD *thd, set_var *var) = 0; protected: /** A pointer to a value of the variable for SHOW. It must be of show_val_type type (my_bool for SHOW_MY_BOOL, int for SHOW_INT, longlong for SHOW_LONGLONG, etc). */ virtual const uchar *session_value_ptr(THD *thd, const LEX_CSTRING *base) const; virtual const uchar *global_value_ptr(THD *thd, const LEX_CSTRING *base) const; /** A pointer to a storage area of the variable, to the raw data. Typically it's the same as session_value_ptr(), but it's different, for example, for ENUM, that is printed as a string, but stored as a number. */ ATTRIBUTE_NO_UBSAN uchar *session_var_ptr(THD *thd) const { return ((uchar*)&(thd->variables)) + offset; } ATTRIBUTE_NO_UBSAN uchar *global_var_ptr() const { return ((uchar*)&global_system_variables) + offset; } void *max_var_ptr() { return scope() == SESSION ? (((uchar*)&max_system_variables) + offset) : 0; } friend class Session_sysvars_tracker; friend class Session_tracker; }; #include "sql_plugin.h" /* SHOW_HA_ROWS, SHOW_MY_BOOL */ /**************************************************************************** Classes for parsing of the SET command ****************************************************************************/ /** A base class for everything that can be set with SET command. It's similar to Items, an instance of this is created by the parser for every assigmnent in SET (or elsewhere, e.g. in SELECT). */ class set_var_base :public Sql_alloc { public: set_var_base() = default; virtual ~set_var_base() = default; virtual int check(THD *thd)=0; /* To check privileges etc. */ virtual int update(THD *thd)=0; /* To set the value */ virtual int light_check(THD *thd) { return check(thd); } /* for PS */ virtual bool is_system() { return FALSE; } /** @returns whether this variable is @@@@optimizer_trace. */ virtual bool is_var_optimizer_trace() const { return false; } }; /** Structure for holding unix timestamp and high precision second part. */ typedef struct my_time_t_hires { my_time_t unix_time; ulong second_part; } my_time_t_hires; /** set_var_base descendant for assignments to the system variables. */ class set_var :public set_var_base { public: sys_var *var; ///< system variable to be updated Item *value; ///< the expression that provides the new value of the variable enum_var_type type; union ///< temp storage to hold a value between sys_var::check and ::update { ulonglong ulonglong_value; ///< for unsigned integer, set, enum sysvars longlong longlong_value; ///< for signed integer double double_value; ///< for Sys_var_double plugin_ref plugin; ///< for Sys_var_plugin plugin_ref *plugins; ///< for Sys_var_pluginlist Time_zone *time_zone; ///< for Sys_var_tz LEX_STRING string_value; ///< for Sys_var_charptr and others my_time_t_hires timestamp; ///< for Sys_var_vers_asof const void *ptr; ///< for Sys_var_struct } save_result; LEX_CSTRING base; /**< for structured variables, like keycache_name.variable_name */ set_var(THD *thd, enum_var_type type_arg, sys_var *var_arg, const LEX_CSTRING *base_name_arg, Item *value_arg); bool is_system() override { return 1; } int check(THD *thd) override; int update(THD *thd) override; int light_check(THD *thd) override; bool is_var_optimizer_trace() const override { extern sys_var *Sys_optimizer_trace_ptr; return var == Sys_optimizer_trace_ptr; } }; /* User variables like @my_own_variable */ class set_var_user: public set_var_base { Item_func_set_user_var *user_var_item; public: set_var_user(Item_func_set_user_var *item) :user_var_item(item) {} int check(THD *thd) override; int update(THD *thd) override; int light_check(THD *thd) override; }; /* For SET PASSWORD */ class set_var_password: public set_var_base { LEX_USER *user; public: set_var_password(LEX_USER *user_arg) :user(user_arg) {} int check(THD *thd) override; int update(THD *thd) override; }; /* For SET ROLE */ class set_var_role: public set_var_base { LEX_CSTRING role; privilege_t access; public: set_var_role(LEX_CSTRING role_arg) : role(role_arg), access(NO_ACL) {} int check(THD *thd) override; int update(THD *thd) override; }; /* For SET DEFAULT ROLE */ class set_var_default_role: public set_var_base { LEX_USER *user, *real_user; LEX_CSTRING role; const char *real_role; public: set_var_default_role(LEX_USER *user_arg, LEX_CSTRING role_arg) : user(user_arg), role(role_arg) {} int check(THD *thd) override; int update(THD *thd) override; }; /* For SET NAMES and SET CHARACTER SET */ class set_var_collation_client: public set_var_base { CHARSET_INFO *character_set_client; CHARSET_INFO *character_set_results; CHARSET_INFO *collation_connection; public: set_var_collation_client(CHARSET_INFO *client_coll_arg, CHARSET_INFO *connection_coll_arg, CHARSET_INFO *result_coll_arg) :character_set_client(client_coll_arg), character_set_results(result_coll_arg), collation_connection(connection_coll_arg) {} int check(THD *thd) override; int update(THD *thd) override; }; /* optional things, have_* variables */ extern SHOW_COMP_OPTION have_csv, have_innodb; extern SHOW_COMP_OPTION have_ndbcluster, have_partitioning; extern SHOW_COMP_OPTION have_profiling; extern SHOW_COMP_OPTION have_ssl, have_symlink, have_dlopen; extern SHOW_COMP_OPTION have_query_cache; extern SHOW_COMP_OPTION have_geometry, have_rtree_keys; extern SHOW_COMP_OPTION have_crypt; extern SHOW_COMP_OPTION have_compress; extern SHOW_COMP_OPTION have_openssl; /* Prototypes for helper functions */ ulong get_system_variable_hash_records(void); ulonglong get_system_variable_hash_version(void); SHOW_VAR* enumerate_sys_vars(THD *thd, bool sorted, enum enum_var_type type); int fill_sysvars(THD *thd, TABLE_LIST *tables, COND *cond); sys_var *find_sys_var(THD *thd, const char *str, size_t length= 0, bool throw_error= false); int sql_set_variables(THD *thd, List *var_list, bool free); #define SYSVAR_AUTOSIZE(VAR,VAL) \ do { \ VAR= (VAL); \ set_sys_var_value_origin(&VAR, sys_var::AUTO); \ } while(0) #define SYSVAR_AUTOSIZE_IF_CHANGED(VAR,VAL,TYPE) \ do { \ TYPE tmp= (VAL); \ if (VAR != tmp) \ { \ VAR= (VAL); \ set_sys_var_value_origin(&VAR, sys_var::AUTO); \ } \ } while(0) void set_sys_var_value_origin(void *ptr, enum sys_var::where here, const char *filename= NULL); enum sys_var::where get_sys_var_value_origin(void *ptr); inline bool IS_SYSVAR_AUTOSIZE(void *ptr) { enum sys_var::where res= get_sys_var_value_origin(ptr); return (res == sys_var::AUTO || res == sys_var::COMPILE_TIME); } bool fix_delay_key_write(sys_var *self, THD *thd, enum_var_type type); sql_mode_t expand_sql_mode(sql_mode_t sql_mode); const char *sql_mode_string_representation(uint bit_number); bool sql_mode_string_representation(THD *thd, sql_mode_t sql_mode, LEX_CSTRING *ls); int default_regex_flags_pcre(THD *thd); extern sys_var *Sys_autocommit_ptr, *Sys_last_gtid_ptr, *Sys_character_set_client_ptr, *Sys_character_set_connection_ptr, *Sys_character_set_results_ptr; CHARSET_INFO *get_old_charset_by_name(const char *old_name); int sys_var_init(); uint sys_var_elements(); int sys_var_add_options(DYNAMIC_ARRAY *long_options, int parse_flags); void sys_var_end(void); bool check_has_super(sys_var *self, THD *thd, set_var *var); plugin_ref *resolve_engine_list(THD *thd, const char *str_arg, size_t str_arg_len, bool error_on_unknown_engine, bool temp_copy); void free_engine_list(plugin_ref *list); plugin_ref *copy_engine_list(plugin_ref *list); plugin_ref *temp_copy_engine_list(THD *thd, plugin_ref *list); char *pretty_print_engine_list(THD *thd, plugin_ref *list); #endif mysql/server/private/my_service_manager.h000064400000004002151027430560014700 0ustar00/* Copyright (c) 2015 Daniel Black. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_SERVICE_MANAGER_INCLUDED #define MY_SERVICE_MANAGER_INCLUDED #if defined(HAVE_SYSTEMD) && !defined(EMBEDDED_LIBRARY) /* sd-daemon.h may include inttypes.h. Explicitly request format macros before the first inclusion of inttypes.h. */ #if !defined(__STDC_FORMAT_MACROS) #define __STDC_FORMAT_MACROS #endif // !defined(__STDC_FORMAT_MACROS) #include /** INTERVAL in seconds followed by printf style status */ #define service_manager_extend_timeout(INTERVAL, FMTSTR, ...) \ sd_notifyf(0, "STATUS=" FMTSTR "\nEXTEND_TIMEOUT_USEC=%u\n", ##__VA_ARGS__, INTERVAL * 1000000) /* sd_listen_fds_with_names added v227 however RHEL/Centos7 has v219, fallback to sd_listen_fds */ #ifndef HAVE_SYSTEMD_SD_LISTEN_FDS_WITH_NAMES #define sd_listen_fds_with_names(FD, NAMES) sd_listen_fds(FD) #endif #else #define sd_listen_fds_with_names(FD, NAMES) (0) #define sd_is_socket_unix(FD, TYPE, LISTENING, PATH, SIZE) (0) #define sd_is_socket_inet(FD, FAMILY, TYPE, LISTENING, PORT) (0) #define SD_LISTEN_FDS_START (0) #define sd_notify(X, Y) #define sd_notifyf(E, F, ...) #ifdef _WIN32 #define service_manager_extend_timeout(I, F, ...) \ mysqld_win_extend_service_timeout(I) #else #define service_manager_extend_timeout(I, FMTSTR, ...) #endif #endif #endif /* MY_SERVICE_MANAGER_INCLUDED */ mysql/server/private/wsrep_server_service.h000064400000007057151027430560015324 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_SERVER_SERVICE_H #define WSREP_SERVER_SERVICE_H /* wsrep-lib */ #include "wsrep/server_service.hpp" #include "wsrep/exception.hpp" // not_impemented_error(), remove when finished #include "wsrep/storage_service.hpp" class Wsrep_server_state; /* wsrep::server_service interface implementation */ class Wsrep_server_service : public wsrep::server_service { public: Wsrep_server_service(Wsrep_server_state& server_state) : m_server_state(server_state) { } wsrep::storage_service* storage_service(wsrep::client_service&) override; wsrep::storage_service* storage_service(wsrep::high_priority_service&) override; void release_storage_service(wsrep::storage_service*) override; wsrep::high_priority_service* streaming_applier_service(wsrep::client_service&) override; wsrep::high_priority_service* streaming_applier_service(wsrep::high_priority_service&) override; void release_high_priority_service(wsrep::high_priority_service*) override; void background_rollback(wsrep::unique_lock &, wsrep::client_state &) override; void bootstrap() override; void log_message(enum wsrep::log::level, const char*) override; void log_dummy_write_set(wsrep::client_state&, const wsrep::ws_meta&) override { throw wsrep::not_implemented_error(); } void log_view(wsrep::high_priority_service*, const wsrep::view&) override; void recover_streaming_appliers(wsrep::client_service&) override; void recover_streaming_appliers(wsrep::high_priority_service&) override; wsrep::view get_view(wsrep::client_service&, const wsrep::id& own_id) override; wsrep::gtid get_position(wsrep::client_service&) override; void set_position(wsrep::client_service&, const wsrep::gtid&) override; void log_state_change(enum wsrep::server_state::state, enum wsrep::server_state::state) override; bool sst_before_init() const override; std::string sst_request() override; int start_sst(const std::string&, const wsrep::gtid&, bool) override; int wait_committing_transactions(int) override; void debug_sync(const char*) override; private: Wsrep_server_state& m_server_state; }; /** Helper method to create new streaming applier. @param orig_thd Original thd context to copy operation context from. @param ctx Context string for debug logging. */ class Wsrep_applier_service; Wsrep_applier_service* wsrep_create_streaming_applier(THD *orig_thd, const char *ctx); /** Helper method to create new storage service. @param orig_thd Original thd context to copy operation context from. @param ctx Context string for debug logging. */ class Wsrep_storage_service; Wsrep_storage_service* wsrep_create_storage_service(THD *orig_thd, const char *ctx); /** Suppress all error logging from wsrep/Galera library. */ void wsrep_suppress_error_logging(); #endif /* WSREP_SERVER_SERVICE */ mysql/server/private/aligned.h000064400000002160151027430560012447 0ustar00/* Copyright (c) 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #if defined __linux__ # include #endif inline void *aligned_malloc(size_t size, size_t alignment) { #ifdef _WIN32 return _aligned_malloc(size, alignment); #elif defined __linux__ return memalign(alignment, size); #else void *result; if (posix_memalign(&result, alignment, size)) result= NULL; return result; #endif } inline void aligned_free(void *ptr) { IF_WIN(_aligned_free,free)(ptr); } mysql/server/private/thr_lock.h000064400000016266151027430560012665 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* For use with thr_lock:s */ #ifndef _thr_lock_h #define _thr_lock_h #ifdef __cplusplus extern "C" { #endif #include #include struct st_thr_lock; extern ulong locks_immediate,locks_waited ; /* Important: if a new lock type is added, a matching lock description must be added to sql_test.cc's lock_descriptions array. */ enum thr_lock_type { TL_IGNORE=-1, TL_UNLOCK, /* UNLOCK ANY LOCK */ /* Parser only! At open_tables() becomes TL_READ or TL_READ_NO_INSERT depending on the binary log format (SBR/RBR) and on the table category (log table). Used for tables that are read by statements which modify tables. */ TL_READ_DEFAULT, TL_READ, /* Read lock */ TL_READ_WITH_SHARED_LOCKS, /* High prior. than TL_WRITE. Allow concurrent insert */ TL_READ_HIGH_PRIORITY, /* READ, Don't allow concurrent insert */ TL_READ_NO_INSERT, /* READ, but skip locks if found */ TL_READ_SKIP_LOCKED, /* Write lock, but allow other threads to read / write. Used by BDB tables in MySQL to mark that someone is reading/writing to the table. */ TL_WRITE_ALLOW_WRITE, /* WRITE lock used by concurrent insert. Will allow READ, if one could use concurrent insert on table. */ TL_WRITE_CONCURRENT_INSERT, /* Write used by INSERT DELAYED. Allows READ locks */ TL_WRITE_DELAYED, /* parser only! Late bound low_priority flag. At open_tables() becomes thd->update_lock_default. */ TL_WRITE_DEFAULT, /* WRITE lock that has lower priority than TL_READ */ TL_WRITE_LOW_PRIORITY, /* WRITE, but skip locks if found */ TL_WRITE_SKIP_LOCKED, /* Normal WRITE lock */ TL_WRITE, /* Abort new lock request with an error */ TL_WRITE_ONLY}; /* TL_FIRST_WRITE is here to impose some consistency in the sql layer on determining read/write transactions and to provide some API compatibility if additional transactions are added. Above or equal to TL_FIRST_WRITE is a write transaction while < TL_FIRST_WRITE is a read transaction. */ #define TL_FIRST_WRITE TL_WRITE_ALLOW_WRITE enum enum_thr_lock_result { THR_LOCK_SUCCESS= 0, THR_LOCK_ABORTED= 1, THR_LOCK_WAIT_TIMEOUT= 2, THR_LOCK_DEADLOCK= 3 }; /* Priority for locks */ #define THR_LOCK_LATE_PRIV 1U /* For locks to be merged with org lock */ #define THR_LOCK_MERGE_PRIV 2U /* For merge tables */ #define THR_UNLOCK_UPDATE_STATUS 1U extern ulong max_write_lock_count; extern my_bool thr_lock_inited; extern enum thr_lock_type thr_upgraded_concurrent_insert_lock; /* A description of the thread which owns the lock. The address of an instance of this structure is used to uniquely identify the thread. */ typedef struct st_thr_lock_info { pthread_t thread; my_thread_id thread_id; void *mysql_thd; // THD pointer } THR_LOCK_INFO; typedef struct st_thr_lock_data { THR_LOCK_INFO *owner; struct st_thr_lock_data *next,**prev; struct st_thr_lock *lock; mysql_cond_t *cond; void *status_param; /* Param to status functions */ void *debug_print_param; /* For error messages */ struct PSI_table *m_psi; enum thr_lock_type type; enum thr_lock_type org_type; /* Cache for MariaDB */ uint priority; } THR_LOCK_DATA; struct st_lock_list { THR_LOCK_DATA *data,**last; }; typedef struct st_thr_lock { LIST list; mysql_mutex_t mutex; struct st_lock_list read_wait; struct st_lock_list read; struct st_lock_list write_wait; struct st_lock_list write; /* write_lock_count is incremented for write locks and reset on read locks */ ulong write_lock_count; uint read_no_write_count; my_bool (*get_status)(void*, my_bool);/* Called when one gets a lock */ void (*copy_status)(void*,void*); void (*update_status)(void*); /* Before release of write */ void (*restore_status)(void*); /* Before release of read */ my_bool (*start_trans)(void*); /* When all locks are taken */ my_bool (*check_status)(void *); void (*fix_status)(void *, void *);/* For thr_merge_locks() */ const char *name; /* Used for error reporting */ my_bool allow_multiple_concurrent_insert; } THR_LOCK; extern LIST *thr_lock_thread_list; extern mysql_mutex_t THR_LOCK_lock; struct st_my_thread_var; my_bool init_thr_lock(void); /* Must be called once/thread */ void thr_lock_info_init(THR_LOCK_INFO *info, struct st_my_thread_var *tmp); void thr_lock_init(THR_LOCK *lock); void thr_lock_delete(THR_LOCK *lock); void thr_lock_data_init(THR_LOCK *lock,THR_LOCK_DATA *data, void *status_param); void thr_unlock(THR_LOCK_DATA *data, uint unlock_flags); enum enum_thr_lock_result thr_multi_lock(THR_LOCK_DATA **data, uint count, THR_LOCK_INFO *owner, ulong lock_wait_timeout); void thr_multi_unlock(THR_LOCK_DATA **data,uint count, uint unlock_flags); void thr_merge_locks(THR_LOCK_DATA **data, uint org_count, uint new_count); void thr_abort_locks(THR_LOCK *lock, my_bool upgrade_lock); my_bool thr_abort_locks_for_thread(THR_LOCK *lock, my_thread_id thread); void thr_print_locks(void); /* For debugging */ my_bool thr_upgrade_write_delay_lock(THR_LOCK_DATA *data, enum thr_lock_type new_lock_type, ulong lock_wait_timeout); void thr_downgrade_write_lock(THR_LOCK_DATA *data, enum thr_lock_type new_lock_type); my_bool thr_reschedule_write_lock(THR_LOCK_DATA *data, ulong lock_wait_timeout); void thr_set_lock_wait_callback(void (*before_wait)(void), void (*after_wait)(void)); #ifdef WITH_WSREP typedef my_bool (* wsrep_thd_is_brute_force_fun)(const MYSQL_THD, my_bool); typedef my_bool(* wsrep_abort_thd_fun)(MYSQL_THD, MYSQL_THD, my_bool); typedef my_bool (* wsrep_on_fun)(const MYSQL_THD); void wsrep_thr_lock_init( wsrep_thd_is_brute_force_fun bf_fun, wsrep_abort_thd_fun abort_fun, my_bool debug, my_bool convert_LOCK_to_trx, wsrep_on_fun on_fun); #endif #ifdef __cplusplus } #endif #endif /* _thr_lock_h */ mysql/server/private/socketpair.h000064400000001512151027430560013210 0ustar00/* Copyright (c) 2023, MariaDB Plc This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef _WIN32 C_MODE_START int create_socketpair(SOCKET socks[2]); void close_socketpair(SOCKET socks[2]); C_MODE_END #endif /* _WIN32 */ mysql/server/private/sql_reload.h000064400000002014151027430560013167 0ustar00#ifndef SQL_RELOAD_INCLUDED #define SQL_RELOAD_INCLUDED /* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ class THD; struct TABLE_LIST; bool reload_acl_and_cache(THD *thd, unsigned long long options, TABLE_LIST *tables, int *write_to_binlog); bool flush_tables_with_read_lock(THD *thd, TABLE_LIST *all_tables); #endif mysql/server/private/item_geofunc.h000064400000113770151027430560013522 0ustar00#ifndef ITEM_GEOFUNC_INCLUDED #define ITEM_GEOFUNC_INCLUDED /* Copyright (c) 2000, 2016 Oracle and/or its affiliates. Copyright (C) 2011, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file defines all spatial functions */ #ifdef HAVE_SPATIAL #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_type_geom.h" #include "item.h" #include "gstream.h" #include "spatial.h" #include "gcalc_slicescan.h" #include "gcalc_tools.h" class Item_geometry_func: public Item_str_func { public: Item_geometry_func(THD *thd): Item_str_func(thd) {} Item_geometry_func(THD *thd, Item *a): Item_str_func(thd, a) {} Item_geometry_func(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} Item_geometry_func(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c) {} Item_geometry_func(THD *thd, List &list): Item_str_func(thd, list) {} bool fix_length_and_dec() override; const Type_handler *type_handler() const override { return &type_handler_geometry; } }; /* Functions returning REAL measurements of a single GEOMETRY argument */ class Item_real_func_args_geometry: public Item_real_func { protected: String value; bool check_arguments() const override { DBUG_ASSERT(arg_count == 1); return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]); } public: Item_real_func_args_geometry(THD *thd, Item *a) :Item_real_func(thd, a) {} }; /* Functions returning INT measurements of a single GEOMETRY argument */ class Item_long_func_args_geometry: public Item_long_func { bool check_arguments() const override { DBUG_ASSERT(arg_count == 1); return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]); } protected: String value; public: Item_long_func_args_geometry(THD *thd, Item *a) :Item_long_func(thd, a) {} }; /* Functions returning BOOL measurements of a single GEOMETRY argument */ class Item_bool_func_args_geometry: public Item_bool_func { protected: String value; bool check_arguments() const override { DBUG_ASSERT(arg_count == 1); return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]); } public: Item_bool_func_args_geometry(THD *thd, Item *a) :Item_bool_func(thd, a) {} }; /* Functions returning ASCII string measurements of a single GEOMETRY argument */ class Item_str_ascii_func_args_geometry: public Item_str_ascii_func { protected: bool check_arguments() const override { DBUG_ASSERT(arg_count >= 1); return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]); } public: Item_str_ascii_func_args_geometry(THD *thd, Item *a) :Item_str_ascii_func(thd, a) {} Item_str_ascii_func_args_geometry(THD *thd, Item *a, Item *b) :Item_str_ascii_func(thd, a, b) {} Item_str_ascii_func_args_geometry(THD *thd, Item *a, Item *b, Item *c) :Item_str_ascii_func(thd, a, b, c) {} }; /* Functions returning binary string measurements of a single GEOMETRY argument */ class Item_binary_func_args_geometry: public Item_str_func { protected: bool check_arguments() const override { DBUG_ASSERT(arg_count >= 1); return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]); } public: Item_binary_func_args_geometry(THD *thd, Item *a) :Item_str_func(thd, a) {} }; /* Functions returning GEOMETRY measurements of a single GEOEMETRY argument */ class Item_geometry_func_args_geometry: public Item_geometry_func { protected: bool check_arguments() const override { DBUG_ASSERT(arg_count >= 1); return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]); } public: Item_geometry_func_args_geometry(THD *thd, Item *a) :Item_geometry_func(thd, a) {} Item_geometry_func_args_geometry(THD *thd, Item *a, Item *b) :Item_geometry_func(thd, a, b) {} }; /* Functions returning REAL result relationships between two GEOMETRY arguments */ class Item_real_func_args_geometry_geometry: public Item_real_func { protected: bool check_arguments() const override { DBUG_ASSERT(arg_count >= 2); return Type_handler_geometry::check_types_geom_or_binary(func_name_cstring(), args, 0, 2); } public: Item_real_func_args_geometry_geometry(THD *thd, Item *a, Item *b) :Item_real_func(thd, a, b) {} }; /* Functions returning BOOL result relationships between two GEOMETRY arguments */ class Item_bool_func_args_geometry_geometry: public Item_bool_func { protected: String value; bool check_arguments() const override { DBUG_ASSERT(arg_count >= 2); return Type_handler_geometry::check_types_geom_or_binary(func_name_cstring(), args, 0, 2); } public: Item_bool_func_args_geometry_geometry(THD *thd, Item *a, Item *b, Item *c) :Item_bool_func(thd, a, b, c) {} }; class Item_func_geometry_from_text: public Item_geometry_func { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()) || check_argument_types_can_return_int(1, MY_MIN(2, arg_count)); } public: Item_func_geometry_from_text(THD *thd, Item *a): Item_geometry_func(thd, a) {} Item_func_geometry_from_text(THD *thd, Item *a, Item *srid): Item_geometry_func(thd, a, srid) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_geometryfromtext") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_geometry_from_wkb: public Item_geometry_func { bool check_arguments() const override { return Type_handler_geometry::check_type_geom_or_binary(func_name_cstring(), args[0]) || check_argument_types_can_return_int(1, MY_MIN(2, arg_count)); } public: Item_func_geometry_from_wkb(THD *thd, Item *a): Item_geometry_func(thd, a) {} Item_func_geometry_from_wkb(THD *thd, Item *a, Item *srid): Item_geometry_func(thd, a, srid) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_geometryfromwkb") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_geometry_from_json: public Item_geometry_func { String tmp_js; bool check_arguments() const override { // TODO: check with Alexey, for better args[1] and args[2] type control return args[0]->check_type_general_purpose_string(func_name_cstring()) || check_argument_types_traditional_scalar(1, MY_MIN(3, arg_count)); } public: Item_func_geometry_from_json(THD *thd, Item *js): Item_geometry_func(thd, js) {} Item_func_geometry_from_json(THD *thd, Item *js, Item *opt): Item_geometry_func(thd, js, opt) {} Item_func_geometry_from_json(THD *thd, Item *js, Item *opt, Item *srid): Item_geometry_func(thd, js, opt, srid) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_geomfromgeojson") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_as_wkt: public Item_str_ascii_func_args_geometry { public: Item_func_as_wkt(THD *thd, Item *a) :Item_str_ascii_func_args_geometry(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_astext") }; return name; } String *val_str_ascii(String *) override; bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_as_wkb: public Item_binary_func_args_geometry { public: Item_func_as_wkb(THD *thd, Item *a) :Item_binary_func_args_geometry(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_aswkb") }; return name; } String *val_str(String *) override; const Type_handler *type_handler() const override { return &type_handler_long_blob; } bool fix_length_and_dec() override { collation.set(&my_charset_bin); decimals=0; max_length= (uint32) UINT_MAX32; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_as_geojson: public Item_str_ascii_func_args_geometry { bool check_arguments() const override { // TODO: check with Alexey, for better args[1] and args[2] type control return Item_str_ascii_func_args_geometry::check_arguments() || check_argument_types_traditional_scalar(1, MY_MIN(3, arg_count)); } public: Item_func_as_geojson(THD *thd, Item *js) :Item_str_ascii_func_args_geometry(thd, js) {} Item_func_as_geojson(THD *thd, Item *js, Item *max_dec_digits) :Item_str_ascii_func_args_geometry(thd, js, max_dec_digits) {} Item_func_as_geojson(THD *thd, Item *js, Item *max_dec_digits, Item *opt) :Item_str_ascii_func_args_geometry(thd, js, max_dec_digits, opt) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_asgeojson") }; return name; } bool fix_length_and_dec() override; String *val_str_ascii(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_geometry_type: public Item_str_ascii_func_args_geometry { public: Item_func_geometry_type(THD *thd, Item *a) :Item_str_ascii_func_args_geometry(thd, a) {} String *val_str_ascii(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_geometrytype") }; return name; } bool fix_length_and_dec() override { // "GeometryCollection" is the longest fix_length_and_charset(20, default_charset()); set_maybe_null(); return FALSE; }; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; // #define HEAVY_CONVEX_HULL class Item_func_convexhull: public Item_geometry_func_args_geometry { class ch_node: public Gcalc_dyn_list::Item { public: const Gcalc_heap::Info *pi; ch_node *prev; Gcalc_dyn_list::Item *next; ch_node *get_next() { return (ch_node *) next; } }; Gcalc_heap collector; Gcalc_function func; Gcalc_dyn_list res_heap; Gcalc_result_receiver res_receiver; String tmp_value; #ifdef HEAVY_CONVEX_HULL Gcalc_scan_iterator scan_it; #endif /*HEAVY_CONVEX_HULL*/ ch_node *new_ch_node() { return (ch_node *) res_heap.new_item(); } int add_node_to_line(ch_node **p_cur, int dir, const Gcalc_heap::Info *pi); public: Item_func_convexhull(THD *thd, Item *a) :Item_geometry_func_args_geometry(thd, a), res_heap(8192, sizeof(ch_node)) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_convexhull") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_centroid: public Item_geometry_func_args_geometry { public: Item_func_centroid(THD *thd, Item *a) :Item_geometry_func_args_geometry(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_centroid") }; return name; } String *val_str(String *) override; const Type_handler *type_handler() const override { return &type_handler_point; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_envelope: public Item_geometry_func_args_geometry { public: Item_func_envelope(THD *thd, Item *a) :Item_geometry_func_args_geometry(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_envelope") }; return name; } String *val_str(String *) override; const Type_handler *type_handler() const override { return &type_handler_polygon; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_boundary: public Item_geometry_func_args_geometry { class Transporter : public Gcalc_shape_transporter { Gcalc_result_receiver *m_receiver; uint n_points; Gcalc_function::shape_type current_type; double last_x, last_y; public: Transporter(Gcalc_result_receiver *receiver) : Gcalc_shape_transporter(NULL), m_receiver(receiver) {} int single_point(double x, double y) override; int start_line() override; int complete_line() override; int start_poly() override; int complete_poly() override; int start_ring() override; int complete_ring() override; int add_point(double x, double y) override; int start_collection(int n_objects) override; }; Gcalc_result_receiver res_receiver; public: Item_func_boundary(THD *thd, Item *a) :Item_geometry_func_args_geometry(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_boundary") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_point: public Item_geometry_func { bool check_arguments() const override { return check_argument_types_can_return_real(0, 2); } public: Item_func_point(THD *thd, Item *a, Item *b): Item_geometry_func(thd, a, b) {} Item_func_point(THD *thd, Item *a, Item *b, Item *srid): Item_geometry_func(thd, a, b, srid) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("point") }; return name; } String *val_str(String *) override; const Type_handler *type_handler() const override { return &type_handler_point; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_spatial_decomp: public Item_geometry_func_args_geometry { enum Functype decomp_func; public: Item_func_spatial_decomp(THD *thd, Item *a, Item_func::Functype ft): Item_geometry_func_args_geometry(thd, a) { decomp_func = ft; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING startpoint= {STRING_WITH_LEN("st_startpoint") }; static LEX_CSTRING endpoint= {STRING_WITH_LEN("st_endpoint") }; static LEX_CSTRING exteriorring= {STRING_WITH_LEN("st_exteriorring") }; static LEX_CSTRING unknown= {STRING_WITH_LEN("spatial_decomp_unknown") }; switch (decomp_func) { case SP_STARTPOINT: return startpoint; case SP_ENDPOINT: return endpoint; case SP_EXTERIORRING: return exteriorring; default: DBUG_ASSERT(0); // Should never happened return unknown; } } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_spatial_decomp_n: public Item_geometry_func_args_geometry { enum Functype decomp_func_n; bool check_arguments() const override { return Item_geometry_func_args_geometry::check_arguments() || args[1]->check_type_can_return_int(func_name_cstring()); } public: Item_func_spatial_decomp_n(THD *thd, Item *a, Item *b, Item_func::Functype ft) :Item_geometry_func_args_geometry(thd, a, b), decomp_func_n(ft) { } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING pointn= {STRING_WITH_LEN("st_pointn") }; static LEX_CSTRING geometryn= {STRING_WITH_LEN("st_geometryn") }; static LEX_CSTRING interiorringn= {STRING_WITH_LEN("st_interiorringn") }; static LEX_CSTRING unknown= {STRING_WITH_LEN("spatial_decomp_unknown") }; switch (decomp_func_n) { case SP_POINTN: return pointn; case SP_GEOMETRYN: return geometryn; case SP_INTERIORRINGN: return interiorringn; default: DBUG_ASSERT(0); // Should never happened return unknown; } } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_spatial_collection: public Item_geometry_func { bool check_arguments() const override { return Type_handler_geometry::check_types_geom_or_binary(func_name_cstring(), args, 0, arg_count); } enum Geometry::wkbType coll_type; enum Geometry::wkbType item_type; public: Item_func_spatial_collection(THD *thd, List &list, enum Geometry::wkbType ct, enum Geometry::wkbType it): Item_geometry_func(thd, list) { coll_type=ct; item_type=it; } String *val_str(String *) override; bool fix_length_and_dec() override { if (Item_geometry_func::fix_length_and_dec()) return TRUE; for (unsigned int i= 0; i < arg_count; ++i) { if (args[i]->fixed() && args[i]->field_type() != MYSQL_TYPE_GEOMETRY) { String str; args[i]->print(&str, QT_NO_DATA_EXPANSION); str.append('\0'); my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "non geometric", str.ptr()); return TRUE; } } return FALSE; } }; class Item_func_geometrycollection: public Item_func_spatial_collection { public: Item_func_geometrycollection(THD *thd, List &list) :Item_func_spatial_collection(thd, list, Geometry::wkb_geometrycollection, Geometry::wkb_point) { } const Type_handler *type_handler() const override { return &type_handler_geometrycollection; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("geometrycollection") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_linestring: public Item_func_spatial_collection { public: Item_func_linestring(THD *thd, List &list) :Item_func_spatial_collection(thd, list, Geometry::wkb_linestring, Geometry::wkb_point) { } const Type_handler *type_handler() const override { return &type_handler_linestring; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("linestring") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_polygon: public Item_func_spatial_collection { public: Item_func_polygon(THD *thd, List &list) :Item_func_spatial_collection(thd, list, Geometry::wkb_polygon, Geometry::wkb_linestring) { } const Type_handler *type_handler() const override { return &type_handler_polygon; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("polygon") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_multilinestring: public Item_func_spatial_collection { public: Item_func_multilinestring(THD *thd, List &list) :Item_func_spatial_collection(thd, list, Geometry::wkb_multilinestring, Geometry::wkb_linestring) { } const Type_handler *type_handler() const override { return &type_handler_multilinestring; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("multilinestring") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_multipoint: public Item_func_spatial_collection { public: Item_func_multipoint(THD *thd, List &list) :Item_func_spatial_collection(thd, list, Geometry::wkb_multipoint, Geometry::wkb_point) { } const Type_handler *type_handler() const override { return &type_handler_multipoint; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("multipoint") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_multipolygon: public Item_func_spatial_collection { public: Item_func_multipolygon(THD *thd, List &list) :Item_func_spatial_collection(thd, list, Geometry::wkb_multipolygon, Geometry::wkb_polygon) { } const Type_handler *type_handler() const override { return &type_handler_multipolygon; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("multipolygon") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Spatial relations */ class Item_func_spatial_rel: public Item_bool_func2_with_rev { protected: enum Functype spatial_rel; String tmp_value1, tmp_value2; SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, KEY_PART *key_part, Item_func::Functype type, Item *value) override; bool check_arguments() const override { DBUG_ASSERT(arg_count >= 2); return Type_handler_geometry::check_types_geom_or_binary(func_name_cstring(), args, 0, 2); } public: Item_func_spatial_rel(THD *thd, Item *a, Item *b, enum Functype sp_rel): Item_bool_func2_with_rev(thd, a, b), spatial_rel(sp_rel) { set_maybe_null(); } enum Functype functype() const override { return spatial_rel; } enum Functype rev_functype() const override { switch (spatial_rel) { case SP_CONTAINS_FUNC: return SP_WITHIN_FUNC; case SP_WITHIN_FUNC: return SP_CONTAINS_FUNC; default: return spatial_rel; } } bool is_null() override { (void) val_int(); return null_value; } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override { return add_key_fields_optimize_op(join, key_fields, and_level, usable_tables, sargables, false); } bool need_parentheses_in_default() override { return false; } Item *do_build_clone(THD *thd) const override { return nullptr; } }; class Item_func_spatial_mbr_rel: public Item_func_spatial_rel { public: Item_func_spatial_mbr_rel(THD *thd, Item *a, Item *b, enum Functype sp_rel): Item_func_spatial_rel(thd, a, b, sp_rel) { } bool val_bool() override; LEX_CSTRING func_name_cstring() const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_spatial_precise_rel: public Item_func_spatial_rel { Gcalc_heap collector; Gcalc_scan_iterator scan_it; Gcalc_function func; public: Item_func_spatial_precise_rel(THD *thd, Item *a, Item *b, enum Functype sp_rel): Item_func_spatial_rel(thd, a, b, sp_rel), collector() { } bool val_bool() override; LEX_CSTRING func_name_cstring() const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_spatial_relate: public Item_bool_func_args_geometry_geometry { Gcalc_heap collector; Gcalc_scan_iterator scan_it; Gcalc_function func; String tmp_value1, tmp_value2, tmp_matrix; bool check_arguments() const override { return Item_bool_func_args_geometry_geometry::check_arguments() || args[2]->check_type_general_purpose_string(func_name_cstring()); } public: Item_func_spatial_relate(THD *thd, Item *a, Item *b, Item *matrix): Item_bool_func_args_geometry_geometry(thd, a, b, matrix) { } bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_relate") }; return name; } bool need_parentheses_in_default() override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Spatial operations */ class Item_func_spatial_operation final: public Item_geometry_func { bool check_arguments() const override { DBUG_ASSERT(arg_count >= 2); return Type_handler_geometry::check_types_geom_or_binary(func_name_cstring(), args, 0, 2); } public: Gcalc_function::op_type spatial_op; Gcalc_heap collector; Gcalc_function func; Gcalc_result_receiver res_receiver; Gcalc_operation_reducer operation; String tmp_value1,tmp_value2; public: Item_func_spatial_operation(THD *thd, Item *a,Item *b, Gcalc_function::op_type sp_op): Item_geometry_func(thd, a, b), spatial_op(sp_op) {} virtual ~Item_func_spatial_operation(); String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override; void print(String *str, enum_query_type query_type) override { Item_func::print(str, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_buffer final : public Item_geometry_func_args_geometry { bool check_arguments() const override { return Item_geometry_func_args_geometry::check_arguments() || args[1]->check_type_can_return_real(func_name_cstring()); } protected: class Transporter : public Gcalc_operation_transporter { int m_npoints; double m_d; double x1,y1,x2,y2; double x00,y00,x01,y01; int add_edge_buffer(double x3, double y3, bool round_p1, bool round_p2); int add_last_edge_buffer(); int add_point_buffer(double x, double y); int complete(); int m_nshapes; Gcalc_function::op_type buffer_op; int last_shape_pos; bool skip_line; public: Transporter(Gcalc_function *fn, Gcalc_heap *heap, double d) : Gcalc_operation_transporter(fn, heap), m_npoints(0), m_d(d), m_nshapes(0), buffer_op((d > 0.0) ? Gcalc_function::op_union : Gcalc_function::op_difference), skip_line(FALSE) {} int single_point(double x, double y) override; int start_line() override; int complete_line() override; int start_poly() override; int complete_poly() override; int start_ring() override; int complete_ring() override; int add_point(double x, double y) override; int start_collection(int n_objects) override; }; Gcalc_heap collector; Gcalc_function func; Gcalc_result_receiver res_receiver; Gcalc_operation_reducer operation; public: Item_func_buffer(THD *thd, Item *obj, Item *distance) :Item_geometry_func_args_geometry(thd, obj, distance) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_buffer") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_isempty: public Item_bool_func_args_geometry { public: Item_func_isempty(THD *thd, Item *a) :Item_bool_func_args_geometry(thd, a) {} bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_isempty") }; return name; } bool fix_length_and_dec() override { set_maybe_null(); return FALSE; } bool need_parentheses_in_default() override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_issimple: public Item_long_func_args_geometry { Gcalc_heap collector; Gcalc_function func; Gcalc_scan_iterator scan_it; String tmp; public: Item_func_issimple(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_issimple") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2; return FALSE; } decimal_digits_t decimal_precision() const override { return 1; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_isclosed: public Item_long_func_args_geometry { public: Item_func_isclosed(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_isclosed") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2; return FALSE; } decimal_digits_t decimal_precision() const override { return 1; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_isring: public Item_func_issimple { public: Item_func_isring(THD *thd, Item *a): Item_func_issimple(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_isring") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dimension: public Item_long_func_args_geometry { public: Item_func_dimension(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_dimension") }; return name; } bool fix_length_and_dec() override { max_length= 10; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_x: public Item_real_func_args_geometry { public: Item_func_x(THD *thd, Item *a): Item_real_func_args_geometry(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_x") }; return name; } bool fix_length_and_dec() override { if (Item_real_func::fix_length_and_dec()) return TRUE; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_y: public Item_real_func_args_geometry { public: Item_func_y(THD *thd, Item *a): Item_real_func_args_geometry(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_y") }; return name; } bool fix_length_and_dec() override { if (Item_real_func::fix_length_and_dec()) return TRUE; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_numgeometries: public Item_long_func_args_geometry { public: Item_func_numgeometries(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_numgeometries") }; return name; } bool fix_length_and_dec() override { max_length= 10; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_numinteriorring: public Item_long_func_args_geometry { public: Item_func_numinteriorring(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_numinteriorrings") }; return name; } bool fix_length_and_dec() override { max_length= 10; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_numpoints: public Item_long_func_args_geometry { public: Item_func_numpoints(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_numpoints") }; return name; } bool fix_length_and_dec() override { max_length= 10; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_area: public Item_real_func_args_geometry { public: Item_func_area(THD *thd, Item *a): Item_real_func_args_geometry(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_area") }; return name; } bool fix_length_and_dec() override { if (Item_real_func::fix_length_and_dec()) return TRUE; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_glength: public Item_real_func_args_geometry { String value; public: Item_func_glength(THD *thd, Item *a) :Item_real_func_args_geometry(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_length") }; return name; } bool fix_length_and_dec() override { if (Item_real_func::fix_length_and_dec()) return TRUE; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_srid: public Item_long_func_args_geometry { public: Item_func_srid(THD *thd, Item *a) :Item_long_func_args_geometry(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("srid") }; return name; } bool fix_length_and_dec() override { max_length= 10; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_distance: public Item_real_func_args_geometry_geometry { String tmp_value1; String tmp_value2; Gcalc_heap collector; Gcalc_function func; Gcalc_scan_iterator scan_it; public: Item_func_distance(THD *thd, Item *a, Item *b) :Item_real_func_args_geometry_geometry(thd, a, b) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_distance") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sphere_distance: public Item_real_func { double spherical_distance_points(Geometry *g1, Geometry *g2, const double sphere_r); public: Item_func_sphere_distance(THD *thd, List &list): Item_real_func(thd, list) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_distance_sphere") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_pointonsurface: public Item_geometry_func_args_geometry { String tmp_value; Gcalc_heap collector; Gcalc_function func; Gcalc_scan_iterator scan_it; public: Item_func_pointonsurface(THD *thd, Item *a) :Item_geometry_func_args_geometry(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_pointonsurface") }; return name; } String *val_str(String *) override; const Type_handler *type_handler() const override { return &type_handler_point; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #ifndef DBUG_OFF class Item_func_gis_debug: public Item_long_func { public: Item_func_gis_debug(THD *thd, Item *a): Item_long_func(thd, a) { null_value= false; } bool fix_length_and_dec() override { fix_char_length(10); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("st_gis_debug") }; return name; } longlong val_int() override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #endif #define GEOM_NEW(thd, obj_constructor) new (thd->mem_root) obj_constructor #define GEOM_TYPE(x) (x) #else /*HAVE_SPATIAL*/ #define GEOM_NEW(thd, obj_constructor) NULL #define GEOM_TYPE(x) NULL #endif /*HAVE_SPATIAL*/ #endif /* ITEM_GEOFUNC_INCLUDED */ mysql/server/private/semisync_master_ack_receiver.h000064400000021005151027430560016752 0ustar00/* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SEMISYNC_MASTER_ACK_RECEIVER_DEFINED #define SEMISYNC_MASTER_ACK_RECEIVER_DEFINED #include "my_global.h" #include "my_pthread.h" #include "sql_class.h" #include "semisync.h" #include "socketpair.h" #include struct Slave :public ilink { THD *thd; Vio vio; #ifdef HAVE_POLL uint m_fds_index; #endif bool active; my_socket sock_fd() const { return vio.mysql_socket.fd; } uint server_id() const { return thd->variables.server_id; } }; typedef I_List Slave_ilist; typedef I_List_iterator Slave_ilist_iterator; /** Ack_receiver is responsible to control ack receive thread and maintain slave information used by ack receive thread. There are mainly four operations on ack receive thread: start: start ack receive thread stop: stop ack receive thread add_slave: maintain a new semisync slave's information remove_slave: remove a semisync slave's information */ class Ack_receiver : public Repl_semi_sync_base { public: Ack_receiver(); ~Ack_receiver() = default; void cleanup(); /** Notify ack receiver to receive acks on the dump session. It adds the given dump thread into the slave list and wakes up ack thread if it is waiting for any slave coming. @param[in] thd THD of a dump thread. @return it return false if succeeds, otherwise true is returned. */ bool add_slave(THD *thd); /** Notify ack receiver not to receive ack on the dump session. it removes the given dump thread from slave list. @param[in] thd THD of a dump thread. */ void remove_slave(THD *thd); /** Start ack receive thread @return it return false if succeeds, otherwise true is returned. */ bool start(); /** Stop ack receive thread */ void stop(); /** The core of ack receive thread. It monitors all slaves' sockets and receives acks when they come. */ void run(); void set_trace_level(unsigned long trace_level) { m_trace_level= trace_level; } bool running() { return m_status != ST_DOWN; } private: enum status {ST_UP, ST_DOWN, ST_STOPPING}; enum status m_status; /* Protect m_status, m_slaves_changed and m_slaves. ack thread and other session may access the variables at the same time. */ mysql_mutex_t m_mutex; mysql_cond_t m_cond, m_cond_reply; /* If slave list is updated(add or remove). */ bool m_slaves_changed; Slave_ilist m_slaves; pthread_t m_pid; /* Declare them private, so no one can copy the object. */ Ack_receiver(const Ack_receiver &ack_receiver); Ack_receiver& operator=(const Ack_receiver &ack_receiver); void set_stage_info(const PSI_stage_info &stage); void wait_for_slave_connection(THD *thd); }; extern my_socket global_ack_signal_fd; class Ack_listener { public: my_socket local_read_signal; const Slave_ilist &m_slaves; int error; Ack_listener(const Slave_ilist &slaves) :local_read_signal(-1), m_slaves(slaves), error(0) { my_socket pipes[2]; #ifdef _WIN32 error= create_socketpair(pipes); #else if (!pipe(pipes)) { fcntl(pipes[0], F_SETFL, O_NONBLOCK); fcntl(pipes[1], F_SETFL, O_NONBLOCK); } else { pipes[0]= pipes[1]= -1; } #endif /* _WIN32 */ local_read_signal= pipes[0]; global_ack_signal_fd= pipes[1]; } virtual ~Ack_listener() { #ifdef _WIN32 my_socket pipes[2]; pipes[0]= local_read_signal; pipes[1]= global_ack_signal_fd; close_socketpair(pipes); #else if (global_ack_signal_fd >= 0) close(global_ack_signal_fd); if (local_read_signal >= 0) close(local_read_signal); #endif /* _WIN32 */ global_ack_signal_fd= local_read_signal= -1; } int got_error() { return error; } virtual bool has_signal_data()= 0; /* Clear data sent by signal_listener() to abort read */ void clear_signal() { if (has_signal_data()) { char buff[100]; /* Clear the signal message */ #ifndef _WIN32 (void) !read(local_read_signal, buff, sizeof(buff)); #else recv(local_read_signal, buff, sizeof(buff), 0); #endif /* _WIN32 */ } } }; static inline void signal_listener() { #ifndef _WIN32 my_write(global_ack_signal_fd, (uchar*) "a", 1, MYF(0)); #else send(global_ack_signal_fd, "a", 1, 0); #endif /* _WIN32 */ } #ifdef HAVE_POLL #include class Poll_socket_listener final : public Ack_listener { private: std::vector m_fds; public: Poll_socket_listener(const Slave_ilist &slaves) :Ack_listener(slaves) {} virtual ~Poll_socket_listener() = default; bool listen_on_sockets() { return poll(m_fds.data(), m_fds.size(), -1); } bool is_socket_active(const Slave *slave) { return m_fds[slave->m_fds_index].revents & POLLIN; } bool is_socket_hangup(const Slave *slave) { return m_fds[slave->m_fds_index].revents & POLLHUP; } void clear_socket_info(const Slave *slave) { m_fds[slave->m_fds_index].fd= -1; m_fds[slave->m_fds_index].events= 0; } bool has_signal_data() override { /* The signal fd is always first */ return (m_fds[0].revents & POLLIN); } int init_slave_sockets() { Slave_ilist_iterator it(const_cast(m_slaves)); Slave *slave; uint fds_index= 0; pollfd poll_fd; m_fds.clear(); /* First put in the signal socket */ poll_fd.fd= local_read_signal; poll_fd.events= POLLIN; m_fds.push_back(poll_fd); fds_index++; while ((slave= it++)) { slave->active= 1; pollfd poll_fd; poll_fd.fd= slave->sock_fd(); poll_fd.events= POLLIN; m_fds.push_back(poll_fd); slave->m_fds_index= fds_index++; } return fds_index; } }; #else //NO POLL class Select_socket_listener final : public Ack_listener { private: my_socket m_max_fd; fd_set m_init_fds; fd_set m_fds; public: Select_socket_listener(const Slave_ilist &slaves) :Ack_listener(slaves), m_max_fd(INVALID_SOCKET) {} virtual ~Select_socket_listener() = default; bool listen_on_sockets() { /* Reinitialize the fds with active fds before calling select */ m_fds= m_init_fds; /* select requires max fd + 1 for the first argument */ return select((int) m_max_fd+1, &m_fds, NULL, NULL, NULL); } bool is_socket_active(const Slave *slave) { return FD_ISSET(slave->sock_fd(), &m_fds); } bool is_socket_hangup(const Slave *slave) { return 0; } bool has_signal_data() override { return FD_ISSET(local_read_signal, &m_fds); } void clear_socket_info(const Slave *slave) { FD_CLR(slave->sock_fd(), &m_init_fds); } int init_slave_sockets() { Slave_ilist_iterator it(const_cast(m_slaves)); Slave *slave; uint fds_index= 0; FD_ZERO(&m_init_fds); m_max_fd= -1; /* First put in the signal socket */ FD_SET(local_read_signal, &m_init_fds); fds_index++; set_if_bigger(m_max_fd, local_read_signal); #ifndef _WIN32 if (local_read_signal > FD_SETSIZE) { int socket_id= local_read_signal; sql_print_error("Semisync slave socket fd is %u. " "select() cannot handle if the socket fd is " "greater than %u (FD_SETSIZE).", socket_id, FD_SETSIZE); return -1; } #endif while ((slave= it++)) { my_socket socket_id= slave->sock_fd(); set_if_bigger(m_max_fd, socket_id); #ifndef _WIN32 if (socket_id > FD_SETSIZE) { sql_print_error("Semisync slave socket fd is %u. " "select() cannot handle if the socket fd is " "greater than %u (FD_SETSIZE).", socket_id, FD_SETSIZE); it.remove(); continue; } #endif //_WIN32 FD_SET(socket_id, &m_init_fds); fds_index++; slave->active= 1; } return fds_index; } my_socket get_max_fd() { return m_max_fd; } }; #endif //HAVE_POLL extern Ack_receiver ack_receiver; #endif mysql/server/private/sql_type_fixedbin.h000064400000175500151027430560014565 0ustar00#ifndef SQL_TYPE_FIXEDBIN_H #define SQL_TYPE_FIXEDBIN_H /* Copyright (c) 2019,2021 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This is a common code for plugin (?) types that are generally handled like strings, but have their own fixed size on-disk binary storage format and their own (variable size) canonical string representation. Examples are INET6 and UUID types. */ #define MYSQL_SERVER #include "sql_class.h" // THD, SORT_FIELD_ATTR #include "opt_range.h" // SEL_ARG, null_element #include "sql_type_fixedbin_storage.h" /***********************************************************************/ template class Type_collection_fbt; template > class Type_handler_fbt: public Type_handler { /* =[ internal helper classes ]=============================== */ public: class Fbt: public FbtImpl { protected: using FbtImpl::m_buffer; bool make_from_item(Item *item, bool warn) { if (item->type_handler() == singleton()) { Native tmp(m_buffer, sizeof(m_buffer)); bool rc= item->val_native(current_thd, &tmp); if (rc) return true; DBUG_ASSERT(tmp.length() == sizeof(m_buffer)); if (tmp.ptr() != m_buffer) memcpy(m_buffer, tmp.ptr(), sizeof(m_buffer)); return false; } StringBuffer tmp; String *str= item->val_str(&tmp); return str ? make_from_character_or_binary_string(str, warn) : true; } bool character_string_to_fbt(const char *str, size_t str_length, CHARSET_INFO *cs) { if (cs->state & MY_CS_NONASCII) { char tmp[FbtImpl::max_char_length()+1]; String_copier copier; uint length= copier.well_formed_copy(&my_charset_latin1, tmp, sizeof(tmp), cs, str, str_length); return FbtImpl::ascii_to_fbt(tmp, length); } return FbtImpl::ascii_to_fbt(str, str_length); } bool make_from_character_or_binary_string(const String *str, bool warn) { if (str->charset() != &my_charset_bin) { bool rc= character_string_to_fbt(str->ptr(), str->length(), str->charset()); if (rc && warn) current_thd->push_warning_wrong_value(Sql_condition::WARN_LEVEL_WARN, singleton()->name().ptr(), ErrConvString(str).ptr()); return rc; } if (str->length() != sizeof(m_buffer)) { if (warn) current_thd->push_warning_wrong_value(Sql_condition::WARN_LEVEL_WARN, singleton()->name().ptr(), ErrConvString(str).ptr()); return true; } DBUG_ASSERT(str->ptr() != m_buffer); memcpy(m_buffer, str->ptr(), sizeof(m_buffer)); return false; } bool binary_to_fbt(const char *str, size_t length) { if (length != sizeof(m_buffer)) return true; memcpy(m_buffer, str, length); return false; } Fbt() { } public: static Fbt zero() { Fbt fbt; fbt.set_zero(); return fbt; } static Fbt record_to_memory(const char *ptr) { Fbt fbt; FbtImpl::record_to_memory(fbt.m_buffer, ptr); return fbt; } /* Check at Item's fix_fields() time if "item" can return a nullable value on conversion to Fbt, or conversion produces a NOT NULL Fbt value. */ static bool fix_fields_maybe_null_on_conversion_to_fbt(Item *item) { if (item->maybe_null()) return true; if (item->type_handler() == singleton()) return false; if (!item->const_item() || item->is_expensive()) return true; return Fbt_null(item, false).is_null(); } /* Check at fix_fields() time if any of the items can return a nullable value on conversion to Fbt. */ static bool fix_fields_maybe_null_on_conversion_to_fbt(Item **items, uint count) { for (uint i= 0; i < count; i++) { if (Fbt::fix_fields_maybe_null_on_conversion_to_fbt(items[i])) return true; } return false; } public: Fbt(Item *item, bool *error, bool warn= true) { *error= make_from_item(item, warn); } void to_record(char *str, size_t str_size) const { DBUG_ASSERT(str_size >= sizeof(m_buffer)); FbtImpl::memory_to_record(str, m_buffer); } bool to_binary(String *to) const { return to->copy(m_buffer, sizeof(m_buffer), &my_charset_bin); } bool to_native(Native *to) const { return to->copy(m_buffer, sizeof(m_buffer)); } bool to_string(String *to) const { to->set_charset(&my_charset_latin1); if (to->alloc(FbtImpl::max_char_length()+1)) return true; to->length((uint32) FbtImpl::to_string(const_cast(to->ptr()), FbtImpl::max_char_length()+1)); return false; } int cmp(const Binary_string &other) const { return FbtImpl::cmp(FbtImpl::to_lex_cstring(), other.to_lex_cstring()); } int cmp(const Fbt &other) const { return FbtImpl::cmp(FbtImpl::to_lex_cstring(), other.to_lex_cstring()); } }; class Fbt_null: public Fbt, public Null_flag { public: // Initialize from a text representation Fbt_null(const char *str, size_t length, CHARSET_INFO *cs) :Null_flag(Fbt::character_string_to_fbt(str, length, cs)) { } Fbt_null(const String &str) :Fbt_null(str.ptr(), str.length(), str.charset()) { } // Initialize from a binary representation Fbt_null(const char *str, size_t length) :Null_flag(Fbt::binary_to_fbt(str, length)) { } Fbt_null(const Binary_string &str) :Fbt_null(str.ptr(), str.length()) { } // Initialize from an Item Fbt_null(Item *item, bool warn= true) :Null_flag(Fbt::make_from_item(item, warn)) { } public: const Fbt& to_fbt() const { DBUG_ASSERT(!is_null()); return *this; } void to_record(char *str, size_t str_size) const { to_fbt().to_record(str, str_size); } bool to_binary(String *to) const { return to_fbt().to_binary(to); } bool to_string(String *to) const { return to_fbt().to_string(to); } }; /* =[ API classes ]=========================================== */ class Type_std_attributes_fbt: public Type_std_attributes { public: Type_std_attributes_fbt() :Type_std_attributes( Type_numeric_attributes(FbtImpl::max_char_length(), 0, true), DTCollation_numeric()) { } }; class Item_literal_fbt: public Item_literal { Fbt m_value; public: Item_literal_fbt(THD *thd) :Item_literal(thd), m_value(Fbt::zero()) { } Item_literal_fbt(THD *thd, const Fbt &value) :Item_literal(thd), m_value(value) { } const Type_handler *type_handler() const override { return singleton(); } bool val_bool() override { return m_value.to_bool(); } longlong val_int() override { return 0; } double val_real() override { return 0; } String *val_str(String *to) override { return m_value.to_string(to) ? NULL : to; } my_decimal *val_decimal(my_decimal *to) override { my_decimal_set_zero(to); return to; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); return false; } bool val_native(THD *thd, Native *to) override { return m_value.to_native(to); } void print(String *str, enum_query_type query_type) override { StringBuffer tmp; tmp.append(singleton()->name().lex_cstring()); my_caseup_str(&my_charset_latin1, tmp.c_ptr()); str->append(tmp); str->append('\''); m_value.to_string(&tmp); str->append(tmp); str->append('\''); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } // Non-overriding methods void set_value(const Fbt &value) { m_value= value; } }; class Field_fbt: public Field { static void set_min_value(char *ptr) { memset(ptr, 0, FbtImpl::binary_length()); } static void set_max_value(char *ptr) { memset(ptr, 0xFF, FbtImpl::binary_length()); } void store_warning(const ErrConv &str, Sql_condition::enum_warning_level level) { if (get_thd()->count_cuted_fields <= CHECK_FIELD_EXPRESSION) return; const TABLE_SHARE *s= table->s; static const Name type_name= singleton()->name(); get_thd()->push_warning_truncated_value_for_field(level, type_name.ptr(), str.ptr(), s ? s->db.str : nullptr, s ? s->table_name.str : nullptr, field_name.str); } int set_null_with_warn(const ErrConv &str) { store_warning(str, Sql_condition::WARN_LEVEL_WARN); set_null(); return 1; } int set_min_value_with_warn(const ErrConv &str) { store_warning(str, Sql_condition::WARN_LEVEL_WARN); set_min_value((char*) ptr); return 1; } int set_max_value_with_warn(const ErrConv &str) { store_warning(str, Sql_condition::WARN_LEVEL_WARN); set_max_value((char*) ptr); return 1; } int store_fbt_null_with_warn(const Fbt_null &fbt, const ErrConvString &err) { DBUG_ASSERT(marked_for_write_or_computed()); if (fbt.is_null()) return maybe_null() ? set_null_with_warn(err) : set_min_value_with_warn(err); fbt.to_record((char *) ptr, FbtImpl::binary_length()); return 0; } public: Field_fbt(const LEX_CSTRING *field_name_arg, const Record_addr &rec) :Field(rec.ptr(), FbtImpl::max_char_length(), rec.null_ptr(), rec.null_bit(), Field::NONE, field_name_arg) { flags|= BINARY_FLAG | UNSIGNED_FLAG; } const Type_handler *type_handler() const override { return singleton(); } uint32 max_display_length() const override { return field_length; } bool str_needs_quotes() const override { return true; } const DTCollation &dtcollation() const override { static DTCollation_numeric c; return c; } CHARSET_INFO *charset(void) const override { return &my_charset_numeric; } const CHARSET_INFO *sort_charset(void) const override { return &my_charset_bin; } /** This makes client-server protocol convert the value according to @@character_set_client. */ bool binary() const override { return false; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } bool is_equal(const Column_definition &new_field) const override { return new_field.type_handler() == type_handler(); } bool eq_def(const Field *field) const override { return Field::eq_def(field); } double pos_in_interval(Field *min, Field *max) override { return pos_in_interval_val_str(min, max, 0); } int cmp(const uchar *a, const uchar *b) const override { return memcmp(a, b, pack_length()); } void sort_string(uchar *to, uint length) override { DBUG_ASSERT(length == pack_length()); memcpy(to, ptr, length); } uint32 pack_length() const override { return FbtImpl::binary_length(); } uint pack_length_from_metadata(uint field_metadata) const override { return FbtImpl::binary_length(); } void sql_type(String &str) const override { static Name name= singleton()->name(); str.set_ascii(name.ptr(), name.length()); } void make_send_field(Send_field *to) override { Field::make_send_field(to); to->set_data_type_name(singleton()->name().lex_cstring()); } bool validate_value_in_record(THD *thd, const uchar *record) const override { return false; } bool val_native(Native *to) override { DBUG_ASSERT(marked_for_read()); if (to->alloc(FbtImpl::binary_length())) return true; to->length(FbtImpl::binary_length()); FbtImpl::record_to_memory((char*) to->ptr(), (const char*) ptr); return false; } Fbt to_fbt() const { DBUG_ASSERT(marked_for_read()); return Fbt::record_to_memory((const char*) ptr); } String *val_str(String *val_buffer, String *) override { return to_fbt().to_string(val_buffer) ? NULL : val_buffer; } my_decimal *val_decimal(my_decimal *to) override { DBUG_ASSERT(marked_for_read()); my_decimal_set_zero(to); return to; } longlong val_int() override { DBUG_ASSERT(marked_for_read()); return 0; } double val_real() override { DBUG_ASSERT(marked_for_read()); return 0; } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { DBUG_ASSERT(marked_for_read()); set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); return false; } bool val_bool(void) override { DBUG_ASSERT(marked_for_read()); return !Fbt::only_zero_bytes((const char *) ptr, FbtImpl::binary_length()); } int store_native(const Native &value) override { DBUG_ASSERT(marked_for_write_or_computed()); DBUG_ASSERT(value.length() == FbtImpl::binary_length()); FbtImpl::memory_to_record((char*) ptr, value.ptr()); return 0; } int store(const char *str, size_t length, CHARSET_INFO *cs) override { return cs == &my_charset_bin ? store_binary(str, length) : store_text(str, length, cs); } int store_text(const char *str, size_t length, CHARSET_INFO *cs) override { return store_fbt_null_with_warn(Fbt_null(str, length, cs), ErrConvString(str, length, cs)); } int store_binary(const char *str, size_t length) override { return store_fbt_null_with_warn(Fbt_null(str, length), ErrConvString(str, length, &my_charset_bin)); } int store_hex_hybrid(const char *str, size_t length) override { return Field_fbt::store_binary(str, length); } int store_decimal(const my_decimal *num) override { DBUG_ASSERT(marked_for_write_or_computed()); return set_min_value_with_warn(ErrConvDecimal(num)); } int store(longlong nr, bool unsigned_flag) override { DBUG_ASSERT(marked_for_write_or_computed()); return set_min_value_with_warn( ErrConvInteger(Longlong_hybrid(nr, unsigned_flag))); } int store(double nr) override { DBUG_ASSERT(marked_for_write_or_computed()); return set_min_value_with_warn(ErrConvDouble(nr)); } int store_time_dec(const MYSQL_TIME *ltime, uint dec) override { DBUG_ASSERT(marked_for_write_or_computed()); return set_min_value_with_warn(ErrConvTime(ltime)); } /*** Field conversion routines ***/ int store_field(Field *from) override { // INSERT INTO t1 (fbt_field) SELECT different_field_type FROM t2; return from->save_in_field(this); } int save_in_field(Field *to) override { // INSERT INTO t2 (different_field_type) SELECT fbt_field FROM t1; if (to->charset() == &my_charset_bin && dynamic_cast (to->type_handler())) { NativeBuffer res; val_native(&res); return to->store(res.ptr(), res.length(), &my_charset_bin); } return save_in_field_str(to); } Copy_func *get_copy_func(const Field *from) const override { // ALTER to FBT from another field return do_field_string; } Copy_func *get_copy_func_to(const Field *to) const override { if (type_handler() == to->type_handler()) { // ALTER from FBT to FBT DBUG_ASSERT(pack_length() == to->pack_length()); DBUG_ASSERT(charset() == to->charset()); DBUG_ASSERT(sort_charset() == to->sort_charset()); return Field::do_field_eq; } // ALTER from FBT to another fbt type if (to->charset() == &my_charset_bin && dynamic_cast (to->type_handler())) { /* ALTER from FBT to a binary string type, e.g.: BINARY, TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB */ return do_field_fbt_native_to_binary; } return do_field_string; } static void do_field_fbt_native_to_binary(Copy_field *copy) { NativeBuffer res; copy->from_field->val_native(&res); copy->to_field->store(res.ptr(), res.length(), &my_charset_bin); } bool memcpy_field_possible(const Field *from) const override { // INSERT INTO t1 (fbt_field) SELECT field2 FROM t2; return type_handler() == from->type_handler(); } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override { if (type_handler() == source.type_handler() || (source.type_handler() == &type_handler_string && source.type_handler()->max_display_length_for_field(source) == FbtImpl::binary_length())) return rpl_conv_type_from_same_data_type(source.metadata(), rli, param); return CONV_TYPE_IMPOSSIBLE; } /*** Optimizer routines ***/ bool test_if_equality_guarantees_uniqueness(const Item *const_item) const override { /* This condition: WHERE fbt_field=const should return a single distinct value only, as comparison is done according to FBT. */ return true; } bool can_be_substituted_to_equal_item(const Context &ctx, const Item_equal *item_equal) override { switch (ctx.subst_constraint()) { case ANY_SUBST: return ctx.compare_type_handler() == item_equal->compare_type_handler(); case IDENTITY_SUBST: return true; } return false; } Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override { Fbt_null tmp(const_item); if (tmp.is_null()) return NULL; return new (thd->mem_root) Item_literal_fbt(thd, tmp); } Data_type_compatibility can_optimize_keypart_ref(const Item_bool_func *cond, const Item *item) const override { /* Mixing of two different non-traditional types is currently prevented. This may change in the future. */ DBUG_ASSERT(item->type_handler()->type_handler_base_or_self()-> is_traditional_scalar_type() || item->type_handler() == type_handler()); return Data_type_compatibility::OK; } /** Test if Field can use range optimizer for a standard comparison operation: <=, <, =, <=>, >, >= Note, this method does not cover spatial operations. */ Data_type_compatibility can_optimize_range(const Item_bool_func *cond, const Item *item, bool is_eq_func) const override { // See the DBUG_ASSERT comment in can_optimize_keypart_ref() DBUG_ASSERT(item->type_handler()->type_handler_base_or_self()-> is_traditional_scalar_type() || item->type_handler() == type_handler()); return Data_type_compatibility::OK; } void hash_not_null(Hasher *hasher) override { FbtImpl::hash_record(ptr, hasher); } SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *prm, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override { DBUG_ENTER("Field_fbt::get_mm_leaf"); if (can_optimize_scalar_range(prm, key_part, cond, op, value) != Data_type_compatibility::OK) DBUG_RETURN(0); int err= value->save_in_field_no_warnings(this, 1); if ((op != SCALAR_CMP_EQUAL && is_real_null()) || err < 0) DBUG_RETURN(&null_element); if (err > 0) { if (op == SCALAR_CMP_EQ || op == SCALAR_CMP_EQUAL) DBUG_RETURN(new (prm->mem_root) SEL_ARG_IMPOSSIBLE(this)); DBUG_RETURN(NULL); /* Cannot infer anything */ } DBUG_RETURN(stored_field_make_mm_leaf(prm, key_part, op, value)); } Data_type_compatibility can_optimize_hash_join(const Item_bool_func *cond, const Item *item) const override { return can_optimize_keypart_ref(cond, item); } Data_type_compatibility can_optimize_group_min_max( const Item_bool_func *cond, const Item *const_item) const override { return Data_type_compatibility::OK; } uint row_pack_length() const override { return pack_length(); } Binlog_type_info binlog_type_info() const override { DBUG_ASSERT(type() == binlog_type()); return Binlog_type_info_fixed_string(Field_fbt::binlog_type(), FbtImpl::binary_length(), &my_charset_bin); } uchar *pack(uchar *to, const uchar *from, uint max_length) override { DBUG_PRINT("debug", ("Packing field '%s'", field_name.str)); return FbtImpl::pack(to, from, max_length); } const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, uint param_data) override { return FbtImpl::unpack(to, from, from_end, param_data); } uint max_packed_col_length(uint max_length) override { return StringPack::max_packed_col_length(max_length); } uint packed_col_length(const uchar *fbt_ptr, uint length) override { return StringPack::packed_col_length(fbt_ptr, length); } uint size_of() const override { return sizeof(*this); } }; class cmp_item_fbt: public cmp_item_scalar { Fbt m_native; public: cmp_item_fbt() :cmp_item_scalar(), m_native(Fbt::zero()) { } void store_value(Item *item) override { m_native= Fbt(item, &m_null_value); } int cmp_not_null(const Value *val) override { DBUG_ASSERT(!val->is_null()); DBUG_ASSERT(val->is_string()); Fbt_null tmp(val->m_string); DBUG_ASSERT(!tmp.is_null()); return m_native.cmp(tmp); } int cmp(Item *arg) override { Fbt_null tmp(arg); return m_null_value || tmp.is_null() ? UNKNOWN : m_native.cmp(tmp) != 0; } int compare(const cmp_item *ci) const override { const cmp_item_fbt *tmp= static_cast(ci); DBUG_ASSERT(!m_null_value); DBUG_ASSERT(!tmp->m_null_value); return m_native.cmp(tmp->m_native); } cmp_item *make_same(THD *thd) override { return new (thd->mem_root) cmp_item_fbt(); } }; class in_fbt :public in_vector { Fbt m_value; static int cmp_fbt(void *cmp_arg, const void *a, const void *b) { return static_cast(a)->cmp(*static_cast(b)); } public: in_fbt(THD *thd, uint elements) :in_vector(thd, elements, sizeof(Fbt), cmp_fbt, 0), m_value(Fbt::zero()) { } const Type_handler *type_handler() const override { return singleton(); } bool set(uint pos, Item *item) override { Fbt *buff= &((Fbt *) base)[pos]; Fbt_null value(item); if (value.is_null()) { *buff= Fbt::zero(); return true; } *buff= value; return false; } uchar *get_value(Item *item) override { Fbt_null value(item); if (value.is_null()) return 0; m_value= value; return (uchar *) &m_value; } Item* create_item(THD *thd) override { return new (thd->mem_root) Item_literal_fbt(thd); } void value_to_item(uint pos, Item *item) override { const Fbt &buff= (((Fbt*) base)[pos]); static_cast(item)->set_value(buff); } }; class Item_copy_fbt: public Item_copy { NativeBuffer m_value; public: Item_copy_fbt(THD *thd, Item *item_arg): Item_copy(thd, item_arg) {} bool val_native(THD *thd, Native *to) override { if (null_value) return true; return to->copy(m_value.ptr(), m_value.length()); } String *val_str(String *to) override { if (null_value) return NULL; Fbt_null tmp(m_value.ptr(), m_value.length()); return tmp.is_null() || tmp.to_string(to) ? NULL : to; } my_decimal *val_decimal(my_decimal *to) override { my_decimal_set_zero(to); return to; } double val_real() override { return 0; } longlong val_int() override { return 0; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); return null_value; } void copy() override { null_value= item->val_native(current_thd, &m_value); DBUG_ASSERT(null_value == item->null_value); } int save_in_field(Field *field, bool no_conversions) override { return Item::save_in_field(field, no_conversions); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_char_typecast_func_handler_fbt_to_binary: public Item_handled_func::Handler_str { public: const Type_handler *return_type_handler(const Item_handled_func *item) const override { if (item->max_length > MAX_FIELD_VARCHARLENGTH) return Type_handler::blob_type_handler(item->max_length); if (item->max_length > 255) return &type_handler_varchar; return &type_handler_string; } bool fix_length_and_dec(Item_handled_func *xitem) const override { return false; } String *val_str(Item_handled_func *item, String *to) const override { DBUG_ASSERT(dynamic_cast(item)); return static_cast(item)-> val_str_binary_from_native(to); } }; class Item_typecast_fbt: public Item_func { public: Item_typecast_fbt(THD *thd, Item *a) :Item_func(thd, a) {} const Type_handler *type_handler() const override { return singleton(); } enum Functype functype() const override { return CHAR_TYPECAST_FUNC; } bool eq(const Item *item, bool binary_cmp) const override { if (this == item) return true; if (item->type() != FUNC_ITEM || functype() != ((Item_func*)item)->functype()) return false; if (type_handler() != item->type_handler()) return false; Item_typecast_fbt *cast= (Item_typecast_fbt*) item; return args[0]->eq(cast->args[0], binary_cmp); } LEX_CSTRING func_name_cstring() const override { static Name name= singleton()->name(); size_t len= 9+name.length()+1; char *buf= (char*)current_thd->alloc(len); strmov(strmov(buf, "cast_as_"), name.ptr()); return { buf, len }; } void print(String *str, enum_query_type query_type) override { str->append(STRING_WITH_LEN("cast(")); args[0]->print(str, query_type); str->append(STRING_WITH_LEN(" as ")); str->append(singleton()->name().lex_cstring()); str->append(')'); } bool fix_length_and_dec() override { Type_std_attributes::operator=(Type_std_attributes_fbt()); if (Fbt::fix_fields_maybe_null_on_conversion_to_fbt(args[0])) set_maybe_null(); return false; } String *val_str(String *to) override { Fbt_null tmp(args[0]); return (null_value= tmp.is_null() || tmp.to_string(to)) ? NULL : to; } longlong val_int() override { return 0; } double val_real() override { return 0; } my_decimal *val_decimal(my_decimal *to) override { my_decimal_set_zero(to); return to; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); return false; } bool val_native(THD *thd, Native *to) override { Fbt_null tmp(args[0]); return null_value= tmp.is_null() || tmp.to_native(to); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_cache_fbt: public Item_cache { NativeBuffer m_value; public: Item_cache_fbt(THD *thd) :Item_cache(thd, singleton()) { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } bool cache_value() override { if (!example) return false; value_cached= true; null_value_inside= null_value= example->val_native_with_conversion_result(current_thd, &m_value, type_handler()); return true; } String* val_str(String *to) override { if (!has_value()) return NULL; Fbt_null tmp(m_value.ptr(), m_value.length()); return tmp.is_null() || tmp.to_string(to) ? NULL : to; } my_decimal *val_decimal(my_decimal *to) override { if (!has_value()) return NULL; my_decimal_set_zero(to); return to; } longlong val_int() override { if (!has_value()) return 0; return 0; } double val_real() override { if (!has_value()) return 0; return 0; } longlong val_datetime_packed(THD *) override { DBUG_ASSERT(0); if (!has_value()) return 0; return 0; } longlong val_time_packed(THD *) override { DBUG_ASSERT(0); if (!has_value()) return 0; return 0; } bool get_date(THD *, MYSQL_TIME *ltime, date_mode_t) override { if (!has_value()) return true; set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); return false; } bool val_native(THD *, Native *to) override { if (!has_value()) return true; return to->copy(m_value.ptr(), m_value.length()); } }; /* =[ methods ]=============================================== */ private: bool character_or_binary_string_to_native(THD *thd, const String *str, Native *to) const { if (str->charset() == &my_charset_bin) { // Convert from a binary string if (str->length() != FbtImpl::binary_length() || to->copy(str->ptr(), str->length())) { thd->push_warning_wrong_value(Sql_condition::WARN_LEVEL_WARN, name().ptr(), ErrConvString(str).ptr()); return true; } return false; } // Convert from a character string Fbt_null tmp(*str); if (tmp.is_null()) thd->push_warning_wrong_value(Sql_condition::WARN_LEVEL_WARN, name().ptr(), ErrConvString(str).ptr()); return tmp.is_null() || tmp.to_native(to); } public: ~Type_handler_fbt() override {} const Type_collection *type_collection() const override { return TypeCollectionImpl::singleton(); } const Name &default_value() const override { return FbtImpl::default_value(); } ulong KEY_pack_flags(uint column_nr) const override { return FbtImpl::KEY_pack_flags(column_nr); } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_STRING; } bool Item_append_extended_type_info(Send_field_extended_metadata *to, const Item *item) const override { return to->set_data_type_name(name().lex_cstring()); } enum_field_types field_type() const override { return MYSQL_TYPE_STRING; } Item_result result_type() const override { return STRING_RESULT; } Item_result cmp_type() const override { return STRING_RESULT; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_STRING; } uint32 max_display_length_for_field(const Conv_source &src) const override { return FbtImpl::max_char_length(); } const Type_handler *type_handler_for_comparison() const override { return this; } int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override { DBUG_ASSERT(field->type_handler() == this); Fbt_null ni(item); // Convert Item to Fbt if (ni.is_null()) return 0; NativeBuffer tmp; if (field->val_native(&tmp)) { DBUG_ASSERT(0); return 0; } return -ni.cmp(tmp); } CHARSET_INFO *charset_for_protocol(const Item *item) const override { return item->collation.collation; } bool is_scalar_type() const override { return true; } bool is_val_native_ready() const override { return true; } bool can_return_int() const override { return false; } bool can_return_decimal() const override { return false; } bool can_return_real() const override { return false; } bool can_return_str() const override { return true; } bool can_return_text() const override { return true; } bool can_return_date() const override { return false; } bool can_return_time() const override { return false; } bool convert_to_binary_using_val_native() const override { return true; } decimal_digits_t Item_time_precision(THD *thd, Item *item) const override { return 0; } decimal_digits_t Item_datetime_precision(THD *thd, Item *item) const override { return 0; } decimal_digits_t Item_decimal_scale(const Item *item) const override { return 0; } decimal_digits_t Item_decimal_precision(const Item *item) const override { /* This will be needed if we ever allow cast from Fbt to DECIMAL. */ return (FbtImpl::binary_length()*8+7)/10*3; // = bytes to decimal digits } /* Returns how many digits a divisor adds into a division result. See Item::divisor_precision_increment() in item.h for more comments. */ decimal_digits_t Item_divisor_precision_increment(const Item *) const override { return 0; } /** Makes a temporary table Field to handle numeric aggregate functions, e.g. SUM(DISTINCT expr), AVG(DISTINCT expr), etc. */ Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override { DBUG_ASSERT(0); return 0; } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override { const Record_addr tmp(NULL, Bit_addr(true)); return new (table->in_use->mem_root) Field_fbt(&empty_clex_str, tmp); } // Fix attributes after the parser bool Column_definition_fix_attributes(Column_definition *c) const override { c->length= FbtImpl::max_char_length(); return false; } bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *def, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override { def->prepare_stage1_simple(&my_charset_numeric); return false; } bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const override { def->redefine_stage1_common(dup, file); def->set_compression_method(dup->compression_method()); def->create_length_to_internal_length_string(); return false; } bool Column_definition_prepare_stage2(Column_definition *def, handler *file, ulonglong table_flags) const override { def->pack_flag= FIELDFLAG_BINARY; return false; } bool partition_field_check(const LEX_CSTRING &field_name, Item *item_expr) const override { if (item_expr->cmp_type() != STRING_RESULT) { my_error(ER_WRONG_TYPE_COLUMN_VALUE_ERROR, MYF(0)); return true; } return false; } bool partition_field_append_value(String *to, Item *item_expr, CHARSET_INFO *field_cs, partition_value_print_mode_t mode) const override { StringBuffer fbtstr; Fbt_null fbt(item_expr); if (fbt.is_null()) { my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0)); return true; } return fbt.to_string(&fbtstr) || to->append('\'') || to->append(fbtstr) || to->append('\''); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *table) const override { return new (root) Field_fbt(name, addr); } Field * make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override { return new (mem_root) Field_fbt(name, addr); } void Column_definition_attributes_frm_pack(const Column_definition_attributes *def, uchar *buff) const override { def->frm_pack_basic(buff); def->frm_pack_charset(buff); } bool Column_definition_attributes_frm_unpack(Column_definition_attributes *def, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override { def->frm_unpack_basic(buffer); return def->frm_unpack_charset(share, buffer); } void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *) const override { DBUG_ASSERT(item->type_handler() == this); NativeBuffer tmp; item->val_native_result(current_thd, &tmp); if (item->maybe_null()) { if (item->null_value) { memset(to, 0, FbtImpl::binary_length() + 1); return; } *to++= 1; } DBUG_ASSERT(!item->null_value); DBUG_ASSERT(FbtImpl::binary_length() == tmp.length()); DBUG_ASSERT(FbtImpl::binary_length() == sort_field->length); FbtImpl::memory_to_record((char*) to, tmp.ptr()); } uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *) const override { DBUG_ASSERT(item->type_handler() == this); NativeBuffer tmp; item->val_native_result(current_thd, &tmp); if (item->maybe_null()) { if (item->null_value) { *to++=0; return 0; } *to++= 1; } DBUG_ASSERT(!item->null_value); DBUG_ASSERT(FbtImpl::binary_length() == tmp.length()); DBUG_ASSERT(FbtImpl::binary_length() == sort_field->length); FbtImpl::memory_to_record((char*) to, tmp.ptr()); return tmp.length(); } void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override { attr->original_length= attr->length= FbtImpl::binary_length(); attr->suffix_length= 0; } uint32 max_display_length(const Item *item) const override { return FbtImpl::max_char_length(); } uint32 calc_pack_length(uint32 length) const override { return FbtImpl::binary_length(); } void Item_update_null_value(Item *item) const override { NativeBuffer tmp; item->val_native(current_thd, &tmp); } bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override { value->m_type= DYN_COL_STRING; String *str= item->val_str(&value->m_string); if (str != &value->m_string && !item->null_value) { // "item" returned a non-NULL value if (Fbt_null(*str).is_null()) { /* The value was not-null, but conversion to FBT failed: SELECT a, DECODE_ORACLE(fbtcol, 'garbage', '', '::01', '01') FROM t1; */ thd->push_warning_wrong_value(Sql_condition::WARN_LEVEL_WARN, name().ptr(), ErrConvString(str).ptr()); value->m_type= DYN_COL_NULL; return true; } // "item" returned a non-NULL value, and it was a valid FBT value->m_string.set(str->ptr(), str->length(), str->charset()); } return check_null(item, value); } void Item_param_setup_conversion(THD *thd, Item_param *param) const override { param->setup_conversion_string(thd, thd->variables.character_set_client); } void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override { param->set_param_str(pos, len); } bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *val) const override { param->unsigned_flag= false; param->setup_conversion_string(thd, attr->collation.collation); /* Exact value of max_length is not known unless fbt is converted to charset of connection, so we have to set it later. */ return param->set_str(val->m_string.ptr(), val->m_string.length(), attr->collation.collation, attr->collation.collation); } bool Item_param_val_native(THD *thd, Item_param *item, Native *to) const override { StringBuffer buffer; String *str= item->val_str(&buffer); if (!str) return true; Fbt_null tmp(*str); return tmp.is_null() || tmp.to_native(to); } bool Item_send(Item *item, Protocol *p, st_value *buf) const override { return Item_send_str(item, p, buf); } int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override { if (field->type_handler() == this) { NativeBuffer tmp; bool rc= item->val_native(current_thd, &tmp); if (rc || item->null_value) return set_field_to_null_with_conversions(field, no_conversions); field->set_notnull(); return field->store_native(tmp); } return item->save_str_in_field(field, no_conversions); } String *print_item_value(THD *thd, Item *item, String *str) const override { StringBuffer buf; String *result= item->val_str(&buf); /* TODO: This should eventually use one of these notations: 1. CAST('xxx' AS Fbt) Problem: CAST is not supported as a NAME_CONST() argument. 2. Fbt'xxx' Problem: This syntax is not supported by the parser yet. */ return !result || str->realloc(result->length() + 2) || str->append(STRING_WITH_LEN("'")) || str->append(result->ptr(), result->length()) || str->append(STRING_WITH_LEN("'")) ? nullptr : str; } /** Check if WHERE expr=value AND expr=const can be rewritten as: WHERE const=value AND expr=const "this" is the comparison handler that is used by "target". @param target - the predicate expr=value, whose "expr" argument will be replaced to "const". @param target_expr - the target's "expr" which will be replaced to "const". @param target_value - the target's second argument, it will remain unchanged. @param source - the equality predicate expr=const (or expr<=>const) that can be used to rewrite the "target" part (under certain conditions, see the code). @param source_expr - the source's "expr". It should be exactly equal to the target's "expr" to make condition rewrite possible. @param source_const - the source's "const" argument, it will be inserted into "target" instead of "expr". */ bool can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const override { /* WHERE COALESCE(col)='xxx' AND COALESCE(col)=CONCAT(a); --> WHERE COALESCE(col)='xxx' AND 'xxx'=CONCAT(a); */ return target->compare_type_handler() == source->compare_type_handler(); } bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool) const override { /* Example: SELECT * FROM t1 WHERE a IN (SELECT col FROM t1 GROUP BY col); Allow materialization only if the outer column is also FBT. This can be changed for more relaxed rules in the future. */ DBUG_ASSERT(inner->type_handler() == this); return outer->type_handler() == this; } /** Make a simple constant replacement item for a constant "src", so the new item can futher be used for comparison with "cmp", e.g.: src = cmp -> replacement = cmp "this" is the type handler that is used to compare "src" and "cmp". @param thd - current thread, for mem_root @param src - The item that we want to replace. It's a const item, but it can be complex enough to calculate on every row. @param cmp - The src's comparand. @retval - a pointer to the created replacement Item @retval - NULL, if could not create a replacement (e.g. on EOM). NULL is also returned for ROWs, because instead of replacing a Item_row to a new Item_row, Type_handler_row just replaces its elements. */ Item *make_const_item_for_comparison(THD *thd, Item *src, const Item *cmp) const override { Fbt_null tmp(src); if (tmp.is_null()) return new (thd->mem_root) Item_null(thd, src->name.str); return new (thd->mem_root) Item_literal_fbt(thd, tmp); } Item_cache *Item_get_cache(THD *thd, const Item *item) const override { return new (thd->mem_root) Item_cache_fbt(thd); } Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override { return new (thd->mem_root) Item_typecast_fbt(thd, item); } Item_copy *create_item_copy(THD *thd, Item *item) const override { return new (thd->mem_root) Item_copy_fbt(thd, item); } int cmp_native(const Native &a, const Native &b) const override { return FbtImpl::cmp(a.to_lex_cstring(), b.to_lex_cstring()); } bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override { return cmp->set_cmp_func_native(thd); } bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override { return false; } bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override { Fbt_null na(a), nb(b); return !na.is_null() && !nb.is_null() && !na.cmp(nb); } bool Item_bool_rowready_func2_fix_length_and_dec(THD *thd, Item_bool_rowready_func2 *func) const override { if (Type_handler::Item_bool_rowready_func2_fix_length_and_dec(thd, func)) return true; if (!func->maybe_null() && Fbt::fix_fields_maybe_null_on_conversion_to_fbt(func->arguments(), 2)) func->set_maybe_null(); return false; } bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *h, Type_all_attributes *attr, Item **items, uint nitems) const override { attr->Type_std_attributes::operator=(Type_std_attributes_fbt()); h->set_handler(this); /* If some of the arguments cannot be safely converted to "FBT NOT NULL", then mark the entire function nullability as NULL-able. Otherwise, keep the generic nullability calculated by earlier stages: - either by the most generic way in Item_func::fix_fields() - or by Item_func_xxx::fix_length_and_dec() before the call of Item_hybrid_func_fix_attributes() IFNULL() is special. It does not need to test args[0]. */ uint first= dynamic_cast(attr) ? 1 : 0; for (uint i= first; i < nitems; i++) { if (Fbt::fix_fields_maybe_null_on_conversion_to_fbt(items[i])) { attr->set_type_maybe_null(true); break; } } return false; } bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const override { return Item_hybrid_func_fix_attributes(thd, func->func_name_cstring(), func, func, items, nitems); } bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override { func->Type_std_attributes::operator=(Type_std_attributes_fbt()); func->set_handler(this); return false; } bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_val_native_with_conversion(THD *thd, Item *item, Native *to) const override { if (item->type_handler() == this) return item->val_native(thd, to); // No conversion needed StringBuffer buffer; String *str= item->val_str(&buffer); return str ? character_or_binary_string_to_native(thd, str, to) : true; } bool Item_val_native_with_conversion_result(THD *thd, Item *item, Native *to) const override { if (item->type_handler() == this) return item->val_native_result(thd, to); // No conversion needed StringBuffer buffer; String *str= item->str_result(&buffer); return str ? character_or_binary_string_to_native(thd, str, to) : true; } bool Item_val_bool(Item *item) const override { NativeBuffer tmp; if (item->val_native(current_thd, &tmp)) return false; return !Fbt::only_zero_bytes(tmp.ptr(), tmp.length()); } void Item_get_date(THD *thd, Item *item, Temporal::Warn *buff, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override { set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); } longlong Item_val_int_signed_typecast(Item *item) const override { DBUG_ASSERT(0); return 0; } longlong Item_val_int_unsigned_typecast(Item *item) const override { DBUG_ASSERT(0); return 0; } String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const override { NativeBuffer tmp; if ((item->null_value= item->arguments()[0]->val_native(current_thd, &tmp))) return nullptr; DBUG_ASSERT(tmp.length() == FbtImpl::binary_length()); if (str->set_hex(tmp.ptr(), tmp.length())) { str->length(0); str->set_charset(item->collation.collation); } return str; } String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *item, String *str) const override { NativeBuffer native; if (item->val_native(current_thd, &native)) { DBUG_ASSERT(item->null_value); return nullptr; } DBUG_ASSERT(native.length() == FbtImpl::binary_length()); Fbt_null tmp(native.ptr(), native.length()); return tmp.is_null() || tmp.to_string(str) ? nullptr : str; } double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override { return 0; } longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override { return 0; } my_decimal * Item_func_hybrid_field_type_val_decimal(Item_func_hybrid_field_type *, my_decimal *to) const override { my_decimal_set_zero(to); return to; } void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *to, date_mode_t fuzzydate) const override { set_zero_time(to, MYSQL_TIMESTAMP_TIME); } // WHERE is Item_func_min_max_val_native??? String *Item_func_min_max_val_str(Item_func_min_max *func, String *str) const override { Fbt_null tmp(func); return tmp.is_null() || tmp.to_string(str) ? nullptr : str; } double Item_func_min_max_val_real(Item_func_min_max *) const override { return 0; } longlong Item_func_min_max_val_int(Item_func_min_max *) const override { return 0; } my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *to) const override { my_decimal_set_zero(to); return to; } bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *to, date_mode_t fuzzydate) const override { set_zero_time(to, MYSQL_TIMESTAMP_TIME); return false; } bool Item_func_between_fix_length_and_dec(Item_func_between *func) const override { if (!func->maybe_null() && Fbt::fix_fields_maybe_null_on_conversion_to_fbt(func->arguments(), 3)) func->set_maybe_null(); return false; } longlong Item_func_between_val_int(Item_func_between *func) const override { return func->val_int_cmp_native(); } cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override { return new (thd->mem_root) cmp_item_fbt; } in_vector *make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const override { return new (thd->mem_root) in_fbt(thd, nargs); } bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *func) const override { if (!func->maybe_null() && Fbt::fix_fields_maybe_null_on_conversion_to_fbt(func->arguments(), func->argument_count())) func->set_maybe_null(); if (func->compatible_types_scalar_bisection_possible()) { return func->value_list_convert_const_to_int(thd) || func->fix_for_scalar_comparison_using_bisection(thd); } return func->fix_for_scalar_comparison_using_cmp_items(thd, 1U << (uint) STRING_RESULT); } bool Item_func_round_fix_length_and_dec(Item_func_round *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_func_abs_fix_length_and_dec(Item_func_abs *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_func_neg_fix_length_and_dec(Item_func_neg *func) const override { return Item_func_or_sum_illegal_param(func); } bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_double_typecast_fix_length_and_dec(Item_double_typecast *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_float_typecast_fix_length_and_dec(Item_float_typecast *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const override { if (item->cast_charset() == &my_charset_bin) { static Item_char_typecast_func_handler_fbt_to_binary item_char_typecast_func_handler_fbt_to_binary; item->fix_length_and_dec_native_to_binary(FbtImpl::binary_length()); item->set_func_handler(&item_char_typecast_func_handler_fbt_to_binary); return false; } item->fix_length_and_dec_str(); return false; } bool Item_time_typecast_fix_length_and_dec(Item_time_typecast *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_date_typecast_fix_length_and_dec(Item_date_typecast *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_func_plus_fix_length_and_dec(Item_func_plus *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_func_minus_fix_length_and_dec(Item_func_minus *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_func_mul_fix_length_and_dec(Item_func_mul *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_func_div_fix_length_and_dec(Item_func_div *item) const override { return Item_func_or_sum_illegal_param(item); } bool Item_func_mod_fix_length_and_dec(Item_func_mod *item) const override { return Item_func_or_sum_illegal_param(item); } static Type_handler_fbt *singleton() { static Type_handler_fbt th; return &th; } }; template class Type_collection_fbt: public Type_collection { const Type_handler *aggregate_common(const Type_handler *a, const Type_handler *b) const { if (a == b) return a; return NULL; } const Type_handler *aggregate_if_string(const Type_handler *a, const Type_handler *b) const { static const Type_aggregator::Pair agg[]= { {Type_handler_fbt::singleton(), &type_handler_null, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_varchar, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_string, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_tiny_blob, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_blob, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_medium_blob, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_long_blob, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_hex_hybrid, Type_handler_fbt::singleton()}, {NULL,NULL,NULL} }; return Type_aggregator::find_handler_in_array(agg, a, b, true); } public: const Type_handler *aggregate_for_result(const Type_handler *a, const Type_handler *b) const override { const Type_handler *h; if ((h= aggregate_common(a, b)) || (h= aggregate_if_string(a, b))) return h; return NULL; } const Type_handler *aggregate_for_min_max(const Type_handler *a, const Type_handler *b) const override { return aggregate_for_result(a, b); } const Type_handler *aggregate_for_comparison(const Type_handler *a, const Type_handler *b) const override { if (const Type_handler *h= aggregate_common(a, b)) return h; static const Type_aggregator::Pair agg[]= { {Type_handler_fbt::singleton(), &type_handler_null, Type_handler_fbt::singleton()}, {Type_handler_fbt::singleton(), &type_handler_long_blob, Type_handler_fbt::singleton()}, {NULL,NULL,NULL} }; return Type_aggregator::find_handler_in_array(agg, a, b, true); } const Type_handler *aggregate_for_num_op(const Type_handler *a, const Type_handler *b) const override { return NULL; } static Type_collection_fbt *singleton() { static Type_collection_fbt tc; return &tc; } }; #endif /* SQL_TYPE_FIXEDBIN_H */ mysql/server/private/sql_priv.h000064400000044241151027430560012711 0ustar00/* Copyright (c) 2000, 2018, Oracle and/or its affiliates. Copyright (c) 2010, 2019, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file @details Mostly this file is used in the server. But a little part of it is used in mysqlbinlog too (definition of SELECT_DISTINCT and others). The consequence is that 90% of the file is wrapped in \#ifndef MYSQL_CLIENT, except the part which must be in the server and in the client. */ #ifndef SQL_PRIV_INCLUDED #define SQL_PRIV_INCLUDED #ifndef MYSQL_CLIENT /* Generates a warning that a feature is deprecated. After a specified version asserts that the feature is removed. Using it as WARN_DEPRECATED(thd, 6,2, "BAD", "'GOOD'"); Will result in a warning "The syntax 'BAD' is deprecated and will be removed in MySQL 6.2. Please use 'GOOD' instead" Note that in macro arguments BAD is not quoted, while 'GOOD' is. Note that the version is TWO numbers, separated with a comma (two macro arguments, that is) */ #define WARN_DEPRECATED(Thd,VerHi,VerLo,Old,New) \ do { \ compile_time_assert(MYSQL_VERSION_ID < VerHi * 10000 + VerLo * 100); \ if (((THD *) Thd) != NULL) \ push_warning_printf(((THD *) Thd), Sql_condition::WARN_LEVEL_WARN, \ ER_WARN_DEPRECATED_SYNTAX, \ ER_THD(((THD *) Thd), ER_WARN_DEPRECATED_SYNTAX), \ (Old), (New)); \ else \ sql_print_warning("The syntax '%s' is deprecated and will be removed " \ "in a future release. Please use %s instead.", \ (Old), (New)); \ } while(0) /* Generates a warning that a feature is deprecated and there is no replacement. Using it as WARN_DEPRECATED_NO_REPLACEMENT(thd, "BAD"); Will result in a warning "'BAD' is deprecated and will be removed in a future release." Note that in macro arguments BAD is not quoted. */ #define WARN_DEPRECATED_NO_REPLACEMENT(Thd,Old) \ do { \ THD *thd_= ((THD*) Thd); \ if (thd_ != NULL) \ push_warning_printf(thd_, Sql_condition::WARN_LEVEL_WARN, \ ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT, \ ER_THD(thd_, ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT), \ (Old)); \ else \ sql_print_warning("'%s' is deprecated and will be removed " \ "in a future release.", (Old)); \ } while(0) /*************************************************************************/ #endif /* This is included in the server and in the client. Options for select set by the yacc parser (stored in lex->options). NOTE log_event.h defines OPTIONS_WRITTEN_TO_BIN_LOG to specify what THD options list are written into binlog. These options can NOT change their values, or it will break replication between version. context is encoded as following: SELECT - SELECT_LEX_NODE::options THD - THD::options intern - neither. used only as func(..., select_node->options | thd->options | OPTION_XXX, ...) TODO: separate three contexts above, move them to separate bitfields. */ #define SELECT_DISTINCT (1ULL << 0) // SELECT, user #define SELECT_STRAIGHT_JOIN (1ULL << 1) // SELECT, user #define SELECT_DESCRIBE (1ULL << 2) // SELECT, user #define SELECT_SMALL_RESULT (1ULL << 3) // SELECT, user #define SELECT_BIG_RESULT (1ULL << 4) // SELECT, user #define OPTION_FOUND_ROWS (1ULL << 5) // SELECT, user #define OPTION_TO_QUERY_CACHE (1ULL << 6) // SELECT, user #define SELECT_NO_JOIN_CACHE (1ULL << 7) // intern /** always the opposite of OPTION_NOT_AUTOCOMMIT except when in fix_autocommit() */ #define OPTION_AUTOCOMMIT (1ULL << 8) // THD, user #define OPTION_BIG_SELECTS (1ULL << 9) // THD, user #define OPTION_LOG_OFF (1ULL << 10) // THD, user #define OPTION_QUOTE_SHOW_CREATE (1ULL << 11) // THD, user #define TMP_TABLE_ALL_COLUMNS (1ULL << 12) // SELECT, intern #define OPTION_WARNINGS (1ULL << 13) // THD, user #define OPTION_AUTO_IS_NULL (1ULL << 14) // THD, user, binlog #define OPTION_NO_CHECK_CONSTRAINT_CHECKS (1ULL << 15) #define OPTION_SAFE_UPDATES (1ULL << 16) // THD, user #define OPTION_BUFFER_RESULT (1ULL << 17) // SELECT, user #define OPTION_BIN_LOG (1ULL << 18) // THD, user #define OPTION_NOT_AUTOCOMMIT (1ULL << 19) // THD, user #define OPTION_BEGIN (1ULL << 20) // THD, intern #define OPTION_TABLE_LOCK (1ULL << 21) // THD, intern #define OPTION_QUICK (1ULL << 22) // SELECT (for DELETE) #define OPTION_KEEP_LOG (1ULL << 23) // THD, user #define OPTION_EXPLICIT_DEF_TIMESTAMP (1ULL << 24) // THD, user #define OPTION_GTID_BEGIN (1ULL << 25) // GTID BEGIN found in log /** The following can be set when importing tables in a 'wrong order' to suppress foreign key checks */ #define OPTION_NO_FOREIGN_KEY_CHECKS (1ULL << 26) // THD, user, binlog /** The following speeds up inserts to InnoDB tables by suppressing unique key checks in some cases */ #define OPTION_RELAXED_UNIQUE_CHECKS (1ULL << 27) // THD, user, binlog #define OPTION_IF_EXISTS (1ULL << 28) // binlog #define OPTION_SCHEMA_TABLE (1ULL << 29) // SELECT, intern /** Flag set if setup_tables already done */ #define OPTION_SETUP_TABLES_DONE (1ULL << 30) // intern /** If not set then the thread will ignore all warnings with level notes. */ #define OPTION_SQL_NOTES (1ULL << 31) // THD, user /** Force the used temporary table to be a MyISAM table (because we will use fulltext functions when reading from it. */ #define TMP_TABLE_FORCE_MYISAM (1ULL << 32) #define OPTION_PROFILING (1ULL << 33) /** Indicates that this is a HIGH_PRIORITY SELECT. Currently used only for printing of such selects. Type of locks to be acquired is specified directly. */ #define SELECT_HIGH_PRIORITY (1ULL << 34) // SELECT, user /** Is set in slave SQL thread when there was an error on master, which, when is not reproducible on slave (i.e. the query succeeds on slave), is not terminal to the state of repliation, and should be ignored. The slave SQL thread, however, needs to rollback the effects of the succeeded statement to keep replication consistent. */ #define OPTION_MASTER_SQL_ERROR (1ULL << 35) #define OPTION_SKIP_REPLICATION (1ULL << 37) // THD, user #define OPTION_RPL_SKIP_PARALLEL (1ULL << 38) #define OPTION_NO_QUERY_CACHE (1ULL << 39) // SELECT, user #define OPTION_PROCEDURE_CLAUSE (1ULL << 40) // Internal usage #define SELECT_NO_UNLOCK (1ULL << 41) // SELECT, intern #define OPTION_BIN_TMP_LOG_OFF (1ULL << 42) // disable binlog, intern /* Disable commit of binlog. Used to combine many DDL's and DML's as one */ #define OPTION_BIN_COMMIT_OFF (1ULL << 43) /* The following is used to detect a conflict with DISTINCT */ #define SELECT_ALL (1ULL << 44) // SELECT, user, parser #define OPTION_LEX_FOUND_COMMENT (1ULL << 0) // intern, parser /* The rest of the file is included in the server only */ #ifndef MYSQL_CLIENT /* @@optimizer_switch flags. These must be in sync with optimizer_switch_names */ #define OPTIMIZER_SWITCH_INDEX_MERGE (1ULL << 0) #define OPTIMIZER_SWITCH_INDEX_MERGE_UNION (1ULL << 1) #define OPTIMIZER_SWITCH_INDEX_MERGE_SORT_UNION (1ULL << 2) #define OPTIMIZER_SWITCH_INDEX_MERGE_INTERSECT (1ULL << 3) #define OPTIMIZER_SWITCH_INDEX_MERGE_SORT_INTERSECT (1ULL << 4) #define deprecated_ENGINE_CONDITION_PUSHDOWN (1ULL << 5) #define OPTIMIZER_SWITCH_INDEX_COND_PUSHDOWN (1ULL << 6) #define OPTIMIZER_SWITCH_DERIVED_MERGE (1ULL << 7) #define OPTIMIZER_SWITCH_DERIVED_WITH_KEYS (1ULL << 8) #define OPTIMIZER_SWITCH_FIRSTMATCH (1ULL << 9) #define OPTIMIZER_SWITCH_LOOSE_SCAN (1ULL << 10) #define OPTIMIZER_SWITCH_MATERIALIZATION (1ULL << 11) #define OPTIMIZER_SWITCH_IN_TO_EXISTS (1ULL << 12) #define OPTIMIZER_SWITCH_SEMIJOIN (1ULL << 13) #define OPTIMIZER_SWITCH_PARTIAL_MATCH_ROWID_MERGE (1ULL << 14) #define OPTIMIZER_SWITCH_PARTIAL_MATCH_TABLE_SCAN (1ULL << 15) #define OPTIMIZER_SWITCH_SUBQUERY_CACHE (1ULL << 16) /** If this is off, MRR is never used. */ #define OPTIMIZER_SWITCH_MRR (1ULL << 17) /** If OPTIMIZER_SWITCH_MRR is on and this is on, MRR is used depending on a cost-based choice ("automatic"). If OPTIMIZER_SWITCH_MRR is on and this is off, MRR is "forced" (i.e. used as long as the storage engine is capable of doing it). */ #define OPTIMIZER_SWITCH_MRR_COST_BASED (1ULL << 18) #define OPTIMIZER_SWITCH_MRR_SORT_KEYS (1ULL << 19) #define OPTIMIZER_SWITCH_OUTER_JOIN_WITH_CACHE (1ULL << 20) #define OPTIMIZER_SWITCH_SEMIJOIN_WITH_CACHE (1ULL << 21) #define OPTIMIZER_SWITCH_JOIN_CACHE_INCREMENTAL (1ULL << 22) #define OPTIMIZER_SWITCH_JOIN_CACHE_HASHED (1ULL << 23) #define OPTIMIZER_SWITCH_JOIN_CACHE_BKA (1ULL << 24) #define OPTIMIZER_SWITCH_OPTIMIZE_JOIN_BUFFER_SIZE (1ULL << 25) #define OPTIMIZER_SWITCH_TABLE_ELIMINATION (1ULL << 26) #define OPTIMIZER_SWITCH_EXTENDED_KEYS (1ULL << 27) #define OPTIMIZER_SWITCH_EXISTS_TO_IN (1ULL << 28) #define OPTIMIZER_SWITCH_ORDERBY_EQ_PROP (1ULL << 29) #define OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_DERIVED (1ULL << 30) #define OPTIMIZER_SWITCH_SPLIT_MATERIALIZED (1ULL << 31) #define OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_SUBQUERY (1ULL << 32) #define OPTIMIZER_SWITCH_USE_ROWID_FILTER (1ULL << 33) #define OPTIMIZER_SWITCH_COND_PUSHDOWN_FROM_HAVING (1ULL << 34) #define OPTIMIZER_SWITCH_NOT_NULL_RANGE_SCAN (1ULL << 35) #define OPTIMIZER_SWITCH_HASH_JOIN_CARDINALITY (1ULL << 36) #define OPTIMIZER_SWITCH_CSET_NARROWING (1ULL << 37) #define OPTIMIZER_SWITCH_DEFAULT (OPTIMIZER_SWITCH_INDEX_MERGE | \ OPTIMIZER_SWITCH_INDEX_MERGE_UNION | \ OPTIMIZER_SWITCH_INDEX_MERGE_SORT_UNION | \ OPTIMIZER_SWITCH_INDEX_MERGE_INTERSECT | \ OPTIMIZER_SWITCH_INDEX_COND_PUSHDOWN | \ OPTIMIZER_SWITCH_DERIVED_MERGE | \ OPTIMIZER_SWITCH_DERIVED_WITH_KEYS | \ OPTIMIZER_SWITCH_TABLE_ELIMINATION | \ OPTIMIZER_SWITCH_EXTENDED_KEYS | \ OPTIMIZER_SWITCH_IN_TO_EXISTS | \ OPTIMIZER_SWITCH_MATERIALIZATION | \ OPTIMIZER_SWITCH_PARTIAL_MATCH_ROWID_MERGE|\ OPTIMIZER_SWITCH_PARTIAL_MATCH_TABLE_SCAN|\ OPTIMIZER_SWITCH_OUTER_JOIN_WITH_CACHE | \ OPTIMIZER_SWITCH_SEMIJOIN_WITH_CACHE | \ OPTIMIZER_SWITCH_JOIN_CACHE_INCREMENTAL | \ OPTIMIZER_SWITCH_JOIN_CACHE_HASHED | \ OPTIMIZER_SWITCH_JOIN_CACHE_BKA | \ OPTIMIZER_SWITCH_SUBQUERY_CACHE | \ OPTIMIZER_SWITCH_SEMIJOIN | \ OPTIMIZER_SWITCH_FIRSTMATCH | \ OPTIMIZER_SWITCH_LOOSE_SCAN | \ OPTIMIZER_SWITCH_EXISTS_TO_IN | \ OPTIMIZER_SWITCH_ORDERBY_EQ_PROP | \ OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_DERIVED | \ OPTIMIZER_SWITCH_SPLIT_MATERIALIZED | \ OPTIMIZER_SWITCH_COND_PUSHDOWN_FOR_SUBQUERY | \ OPTIMIZER_SWITCH_USE_ROWID_FILTER | \ OPTIMIZER_SWITCH_COND_PUSHDOWN_FROM_HAVING | \ OPTIMIZER_SWITCH_OPTIMIZE_JOIN_BUFFER_SIZE) /* See adjust_secondary_key_cost in sys_vars.cc for symbolic names. */ #define OPTIMIZER_ADJ_SEC_KEY_COST (1) #define OPTIMIZER_ADJ_DISABLE_MAX_SEEKS (2) #define OPTIMIZER_ADJ_DISABLE_FORCE_INDEX_GROUP_BY (4) #define OPTIMIZER_FIX_INNODB_CARDINALITY (8) #define OPTIMIZER_ADJ_FIX_REUSE_RANGE_FOR_REF (16) #define OPTIMIZER_ADJ_FIX_CARD_MULT (32) #define OPTIMIZER_ADJ_DEFAULT (OPTIMIZER_ADJ_FIX_REUSE_RANGE_FOR_REF | \ OPTIMIZER_ADJ_FIX_CARD_MULT) /* Replication uses 8 bytes to store SQL_MODE in the binary log. The day you use strictly more than 64 bits by adding one more define above, you should contact the replication team because the replication code should then be updated (to store more bytes on disk). NOTE: When adding new SQL_MODE types, make sure to also add them to the scripts used for creating the MySQL system tables in scripts/mysql_system_tables.sql and scripts/mysql_system_tables_fix.sql */ /* Flags below are set when we perform context analysis of the statement and make subqueries non-const. It prevents subquery evaluation at context analysis stage. */ /* Don't evaluate this subquery during statement prepare even if it's a constant one. The flag is switched off in the end of mysqld_stmt_prepare. */ #define CONTEXT_ANALYSIS_ONLY_PREPARE 1 /* Special JOIN::prepare mode: changing of query is prohibited. When creating a view, we need to just check its syntax omitting any optimizations: afterwards definition of the view will be reconstructed by means of ::print() methods and written to to an .frm file. We need this definition to stay untouched. */ #define CONTEXT_ANALYSIS_ONLY_VIEW 2 /* Don't evaluate this subquery during derived table prepare even if it's a constant one. */ #define CONTEXT_ANALYSIS_ONLY_DERIVED 4 /* Don't evaluate constant sub-expressions of virtual column expressions when opening tables */ #define CONTEXT_ANALYSIS_ONLY_VCOL_EXPR 8 /* Uncachable causes: */ /* This subquery has fields from outer query (put by user) */ #define UNCACHEABLE_DEPENDENT_GENERATED 1 /* This subquery contains functions with random result. Something that is uncacheable is by default unmergeable. */ #define UNCACHEABLE_RAND 2 /* This subquery contains functions with side effect */ #define UNCACHEABLE_SIDEEFFECT 4 /* Forcing to save JOIN tables for explain */ #define UNCACHEABLE_EXPLAIN 8 /* For uncorrelated SELECT in an UNION with some correlated SELECTs */ #define UNCACHEABLE_UNITED 16 #define UNCACHEABLE_CHECKOPTION 32 /* This subquery has fields from outer query injected during transformation process */ #define UNCACHEABLE_DEPENDENT_INJECTED 64 /* This subquery has fields from outer query (any nature) */ #define UNCACHEABLE_DEPENDENT (UNCACHEABLE_DEPENDENT_GENERATED | \ UNCACHEABLE_DEPENDENT_INJECTED) /* Used to check GROUP BY list in the MODE_ONLY_FULL_GROUP_BY mode */ #define UNDEF_POS (-1) #define IN_SUBQUERY_CONVERSION_THRESHOLD 1000 #endif /* !MYSQL_CLIENT */ /* BINLOG_DUMP options */ #define BINLOG_DUMP_NON_BLOCK 1 #define BINLOG_SEND_ANNOTATE_ROWS_EVENT 2 #ifndef MYSQL_CLIENT /* Field::is_equal() return codes. */ #define IS_EQUAL_NO 0 #define IS_EQUAL_YES 1 /** new_field has compatible packed representation with old type, so it is theoretically possible to perform change by only updating data dictionary without changing table rows */ #define IS_EQUAL_PACK_LENGTH 2 enum enum_parsing_place { NO_MATTER, IN_HAVING, SELECT_LIST, IN_WHERE, IN_ON, IN_GROUP_BY, IN_ORDER_BY, IN_UPDATE_ON_DUP_KEY, IN_PART_FUNC, BEFORE_OPT_LIST, AFTER_LIST, FOR_LOOP_BOUND, IN_RETURNING, PARSING_PLACE_SIZE /* always should be the last */ }; class sys_var; enum enum_yes_no_unknown { TVL_YES, TVL_NO, TVL_UNKNOWN }; #ifdef MYSQL_SERVER /* External variables */ /* yy_*.cc */ #ifndef DBUG_OFF extern void turn_parser_debug_on_MYSQLparse(); extern void turn_parser_debug_on_ORAparse(); #endif /** convert a hex digit into number. */ inline int hexchar_to_int(char c) { if (c <= '9' && c >= '0') return c-'0'; c|=32; if (c <= 'f' && c >= 'a') return c-'a'+10; return -1; } /* This must match the path length limit in the ER_NOT_RW_DIR error msg. */ #define ER_NOT_RW_DIR_PATHSIZE 200 #define IS_TABLESPACES_TABLESPACE_NAME 0 #define IS_TABLESPACES_ENGINE 1 #define IS_TABLESPACES_TABLESPACE_TYPE 2 #define IS_TABLESPACES_LOGFILE_GROUP_NAME 3 #define IS_TABLESPACES_EXTENT_SIZE 4 #define IS_TABLESPACES_AUTOEXTEND_SIZE 5 #define IS_TABLESPACES_MAXIMUM_SIZE 6 #define IS_TABLESPACES_NODEGROUP_ID 7 #define IS_TABLESPACES_TABLESPACE_COMMENT 8 bool db_name_is_in_ignore_db_dirs_list(const char *dbase); #endif /* MYSQL_SERVER */ #endif /* MYSQL_CLIENT */ #endif /* SQL_PRIV_INCLUDED */ mysql/server/private/threadpool_generic.h000064400000007601151027430560014706 0ustar00/* Copyright(C) 2019, 2020, MariaDB * * This program is free software; you can redistribute itand /or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111 - 1301 USA*/ #if defined (HAVE_POOL_OF_THREADS) #include #include #include #include #include #include #ifdef _WIN32 #include #include "threadpool_winsockets.h" /* AIX may define this, too ?*/ #define HAVE_IOCP #endif #ifdef _WIN32 typedef HANDLE TP_file_handle; #else typedef int TP_file_handle; #define INVALID_HANDLE_VALUE -1 #endif #ifdef __linux__ #include typedef struct epoll_event native_event; #elif defined(HAVE_KQUEUE) #include typedef struct kevent native_event; #elif defined (__sun) #include typedef port_event_t native_event; #elif defined (HAVE_IOCP) typedef OVERLAPPED_ENTRY native_event; #else #error threadpool is not available on this platform #endif struct thread_group_t; /* Per-thread structure for workers */ struct worker_thread_t { ulonglong event_count; /* number of request handled by this thread */ thread_group_t* thread_group; worker_thread_t* next_in_list; worker_thread_t** prev_in_list; mysql_cond_t cond; bool woken; }; typedef I_P_List, I_P_List_counter > worker_list_t; struct TP_connection_generic :public TP_connection { TP_connection_generic(CONNECT* c); ~TP_connection_generic(); int init() override { return 0; } void set_io_timeout(int sec) override; int start_io() override; void wait_begin(int type) override; void wait_end() override; thread_group_t* thread_group; TP_connection_generic* next_in_queue; TP_connection_generic** prev_in_queue; ulonglong abs_wait_timeout; ulonglong enqueue_time; TP_file_handle fd; bool bound_to_poll_descriptor; int waiting; bool fix_group; #ifdef _WIN32 win_aiosocket win_sock{}; void init_vio(st_vio *vio) override { win_sock.init(vio);} #endif }; typedef I_P_List, I_P_List_counter, I_P_List_fast_push_back > connection_queue_t; const int NQUEUES = 2; /* We have high and low priority queues*/ enum class operation_origin { WORKER, LISTENER }; struct thread_group_counters_t { ulonglong thread_creations; ulonglong thread_creations_due_to_stall; ulonglong wakes; ulonglong wakes_due_to_stall; ulonglong throttles; ulonglong stalls; ulonglong dequeues[2]; ulonglong polls[2]; }; struct thread_group_t { mysql_mutex_t mutex; connection_queue_t queues[NQUEUES]; worker_list_t waiting_threads; worker_thread_t* listener; pthread_attr_t* pthread_attr; TP_file_handle pollfd; int thread_count; int active_thread_count; int connection_count; /* Stats for the deadlock detection timer routine.*/ int io_event_count; int queue_event_count; ulonglong last_thread_creation_time; int shutdown_pipe[2]; bool shutdown; bool stalled; thread_group_counters_t counters; char pad[CPU_LEVEL1_DCACHE_LINESIZE]; }; #define TP_INCREMENT_GROUP_COUNTER(group,var) do {group->counters.var++;}while(0) extern thread_group_t* all_groups; #endif mysql/server/private/my_crypt.h000064400000001610151027430560012711 0ustar00/* Copyright (c) 2014 Google Inc. Copyright (c) 2014, 2015 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_CRYPT_INCLUDED #define MY_CRYPT_INCLUDED #include /* HAVE_EncryptAes128{Ctr,Gcm} */ #include #endif /* MY_CRYPT_INCLUDED */ mysql/server/private/sql_window.h000064400000015236151027430560013242 0ustar00/* Copyright (c) 2016, 2022 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SQL_WINDOW_INCLUDED #define SQL_WINDOW_INCLUDED #include "filesort.h" class Item_window_func; /* Window functions module. Each instance of window function has its own element in SELECT_LEX::window_specs. */ class Window_frame_bound : public Sql_alloc { public: enum Bound_precedence_type { PRECEDING, CURRENT, // Used for CURRENT ROW window frame bounds FOLLOWING }; Bound_precedence_type precedence_type; /* For UNBOUNDED PRECEDING / UNBOUNDED FOLLOWING window frame bounds precedence type is seto to PRECEDING / FOLLOWING and offset is set to NULL. The offset is not meaningful with precedence type CURRENT */ Item *offset; Window_frame_bound(Bound_precedence_type prec_type, Item *offset_val) : precedence_type(prec_type), offset(offset_val) {} bool is_unbounded() { return offset == NULL; } void print(String *str, enum_query_type query_type); }; class Window_frame : public Sql_alloc { public: enum Frame_units { UNITS_ROWS, UNITS_RANGE }; enum Frame_exclusion { EXCL_NONE, EXCL_CURRENT_ROW, EXCL_GROUP, EXCL_TIES }; Frame_units units; Window_frame_bound *top_bound; Window_frame_bound *bottom_bound; Frame_exclusion exclusion; Window_frame(Frame_units win_frame_units, Window_frame_bound *win_frame_top_bound, Window_frame_bound *win_frame_bottom_bound, Frame_exclusion win_frame_exclusion) : units(win_frame_units), top_bound(win_frame_top_bound), bottom_bound(win_frame_bottom_bound), exclusion(win_frame_exclusion) {} bool check_frame_bounds(); void print(String *str, enum_query_type query_type); }; class Window_spec : public Sql_alloc { bool window_names_are_checked; public: virtual ~Window_spec() = default; LEX_CSTRING *window_ref; SQL_I_List *partition_list; SQL_I_List *save_partition_list; SQL_I_List *order_list; SQL_I_List *save_order_list; Window_frame *window_frame; Window_spec *referenced_win_spec; /* Window_spec objects are numbered by the number of their appearance in the query. This is used by compare_order_elements() to provide a predictable ordering of PARTITION/ORDER BY clauses. */ int win_spec_number; Window_spec(LEX_CSTRING *win_ref, SQL_I_List *part_list, SQL_I_List *ord_list, Window_frame *win_frame) : window_names_are_checked(false), window_ref(win_ref), partition_list(part_list), save_partition_list(NULL), order_list(ord_list), save_order_list(NULL), window_frame(win_frame), referenced_win_spec(NULL) {} virtual const char *name() { return NULL; } bool check_window_names(List_iterator_fast &it); const char *window_reference() { return window_ref ? window_ref->str : NULL; } void join_partition_and_order_lists() { *(partition_list->next)= order_list->first; } void disjoin_partition_and_order_lists() { *(partition_list->next)= NULL; } void print(String *str, enum_query_type query_type); void print_order(String *str, enum_query_type query_type); void print_partition(String *str, enum_query_type query_type); }; class Window_def : public Window_spec { public: LEX_CSTRING *window_name; Window_def(LEX_CSTRING *win_name, LEX_CSTRING *win_ref, SQL_I_List *part_list, SQL_I_List *ord_list, Window_frame *win_frame) : Window_spec(win_ref, part_list, ord_list, win_frame), window_name(win_name) {} const char *name() override { return window_name->str; } }; int setup_windows(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, List &fields, List &all_fields, List &win_specs, List &win_funcs); ////////////////////////////////////////////////////////////////////////////// // Classes that make window functions computation a part of SELECT's query plan ////////////////////////////////////////////////////////////////////////////// class Frame_cursor; /* This handles computation of one window function. Currently, we make a spearate filesort() call for each window function. */ class Window_func_runner : public Sql_alloc { public: /* Add the function to be computed during the execution pass */ bool add_function_to_run(Item_window_func *win_func); /* Compute and fill the fields in the table. */ bool exec(THD *thd, TABLE *tbl, SORT_INFO *filesort_result); private: /* A list of window functions for which this Window_func_runner will compute values during the execution phase. */ List window_functions; }; /* Represents a group of window functions that require the same sorting of rows and so share the filesort() call. */ class Window_funcs_sort : public Sql_alloc { public: bool setup(THD *thd, SQL_SELECT *sel, List_iterator &it, st_join_table *join_tab); bool exec(JOIN *join, bool keep_filesort_result); void cleanup() { delete filesort; } friend class Window_funcs_computation; private: Window_func_runner runner; /* Window functions can be computed over this sorting */ Filesort *filesort; }; struct st_join_table; class Explain_aggr_window_funcs; /* This is a "window function computation phase": a single object of this class takes care of computing all window functions in a SELECT. - JOIN optimizer is exected to call setup() during query optimization. - JOIN::exec() should call exec() once it has collected join output in a temporary table. */ class Window_funcs_computation : public Sql_alloc { List win_func_sorts; public: bool setup(THD *thd, List *window_funcs, st_join_table *tab); bool exec(JOIN *join, bool keep_last_filesort_result); Explain_aggr_window_funcs *save_explain_plan(MEM_ROOT *mem_root, bool is_analyze); void cleanup(); }; #endif /* SQL_WINDOW_INCLUDED */ mysql/server/private/wsrep_mysqld_c.h000064400000002313151027430560014077 0ustar00/* Copyright 2018-2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef WSREP_MYSQLD_C_H #define WSREP_MYSQLD_C_H enum enum_wsrep_certification_rules { WSREP_CERTIFICATION_RULES_STRICT, WSREP_CERTIFICATION_RULES_OPTIMIZED }; /* This is intentionally declared as a weak global symbol, so that the same ha_innodb.so can be used with the embedded server (which does not link to the definition of this variable) and with the regular server built WITH_WSREP. */ extern ulong wsrep_certification_rules __attribute__((weak)); #endif /* WSREP_MYSQLD_C_H */ mysql/server/private/my_rnd.h000064400000002050151027430560012332 0ustar00/* Copyright (C) 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 or later of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_rnd_h #define _my_rnd_h C_MODE_START struct my_rnd_struct { unsigned long seed1,seed2,max_value; double max_value_dbl; }; void my_rnd_init(struct my_rnd_struct *rand_st, ulong seed1, ulong seed2); double my_rnd(struct my_rnd_struct *rand_st); double my_rnd_ssl(struct my_rnd_struct *rand_st); C_MODE_END #endif /* _my_rnd_h */ mysql/server/private/opt_subselect.h000064400000034327151027430560013731 0ustar00/* Copyright (c) 2010, 2019, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Semi-join subquery optimization code definitions */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif int check_and_do_in_subquery_rewrites(JOIN *join); bool convert_join_subqueries_to_semijoins(JOIN *join); int pull_out_semijoin_tables(JOIN *join); bool optimize_semijoin_nests(JOIN *join, table_map all_table_map); bool setup_degenerate_jtbm_semi_joins(JOIN *join, List *join_list, List &eq_list); bool setup_jtbm_semi_joins(JOIN *join, List *join_list, List &eq_list); void cleanup_empty_jtbm_semi_joins(JOIN *join, List *join_list); // used by Loose_scan_opt ulonglong get_bound_sj_equalities(TABLE_LIST *sj_nest, table_map remaining_tables); /* This is a class for considering possible loose index scan optimizations. It's usage pattern is as follows: best_access_path() { Loose_scan_opt opt; opt.init() for each index we can do ref access with { opt.next_ref_key(); for each keyuse opt.add_keyuse(); opt.check_ref_access(); } if (some criteria for range scans) opt.check_range_access(); opt.get_best_option(); } */ class Loose_scan_opt { /* All methods must check this before doing anything else */ bool try_loosescan; /* If we consider (oe1, .. oeN) IN (SELECT ie1, .. ieN) then ieK=oeK is called sj-equality. If oeK depends only on preceding tables then such equality is called 'bound'. */ ulonglong bound_sj_equalities; /* Accumulated properties of ref access we're now considering: */ ulonglong handled_sj_equalities; key_part_map loose_scan_keyparts; uint max_loose_keypart; bool part1_conds_met; /* Use of quick select is a special case. Some of its properties: */ uint quick_uses_applicable_index; uint quick_max_loose_keypart; /* Best loose scan method so far */ uint best_loose_scan_key; double best_loose_scan_cost; double best_loose_scan_records; KEYUSE *best_loose_scan_start_key; uint best_max_loose_keypart; table_map best_ref_depend_map; public: Loose_scan_opt(): try_loosescan(false), bound_sj_equalities(0), quick_uses_applicable_index(0), quick_max_loose_keypart(0), best_loose_scan_key(0), best_loose_scan_cost(0), best_loose_scan_records(0), best_loose_scan_start_key(NULL), best_max_loose_keypart(0), best_ref_depend_map(0) { } void init(JOIN *join, JOIN_TAB *s, table_map remaining_tables) { /* Discover the bound equalities. We need to do this if 1. The next table is an SJ-inner table, and 2. It is the first table from that semijoin, and 3. We're not within a semi-join range (i.e. all semi-joins either have all or none of their tables in join_table_map), except s->emb_sj_nest (which we've just entered, see #2). 4. All non-IN-equality correlation references from this sj-nest are bound 5. But some of the IN-equalities aren't (so this can't be handled by FirstMatch strategy) */ best_loose_scan_cost= DBL_MAX; if (!join->emb_sjm_nest && s->emb_sj_nest && // (1) s->emb_sj_nest->sj_in_exprs < 64 && ((remaining_tables & s->emb_sj_nest->sj_inner_tables) == // (2) s->emb_sj_nest->sj_inner_tables) && // (2) join->cur_sj_inner_tables == 0 && // (3) !(remaining_tables & s->emb_sj_nest->nested_join->sj_corr_tables) && // (4) remaining_tables & s->emb_sj_nest->nested_join->sj_depends_on &&// (5) optimizer_flag(join->thd, OPTIMIZER_SWITCH_LOOSE_SCAN)) { /* This table is an LooseScan scan candidate */ bound_sj_equalities= get_bound_sj_equalities(s->emb_sj_nest, remaining_tables); try_loosescan= TRUE; DBUG_PRINT("info", ("Will try LooseScan scan, bound_map=%llx", (longlong)bound_sj_equalities)); } } void next_ref_key() { handled_sj_equalities=0; loose_scan_keyparts= 0; max_loose_keypart= 0; part1_conds_met= FALSE; } void add_keyuse(table_map remaining_tables, KEYUSE *keyuse) { if (try_loosescan && keyuse->sj_pred_no != UINT_MAX && (keyuse->table->file->index_flags(keyuse->key, 0, 1 ) & HA_READ_ORDER)) { if (!(remaining_tables & keyuse->used_tables)) { /* This allows to use equality propagation to infer that some sj-equalities are bound. */ bound_sj_equalities |= 1ULL << keyuse->sj_pred_no; } else { handled_sj_equalities |= 1ULL << keyuse->sj_pred_no; loose_scan_keyparts |= ((key_part_map)1) << keyuse->keypart; set_if_bigger(max_loose_keypart, keyuse->keypart); } } } bool have_a_case() { return MY_TEST(handled_sj_equalities); } void check_ref_access_part1(JOIN_TAB *s, uint key, KEYUSE *start_key, table_map found_part) { /* Check if we can use LooseScan semi-join strategy. We can if 1. This is the right table at right location 2. All IN-equalities are either - "bound", ie. the outer_expr part refers to the preceding tables - "handled", ie. covered by the index we're considering 3. Index order allows to enumerate subquery's duplicate groups in order. This happens when the index definition matches this pattern: (handled_col|bound_col)* (other_col|bound_col) */ if (try_loosescan && // (1) (handled_sj_equalities | bound_sj_equalities) == // (2) PREV_BITS(ulonglong, s->emb_sj_nest->sj_in_exprs) && // (2) (PREV_BITS(key_part_map, max_loose_keypart+1) & // (3) (found_part | loose_scan_keyparts)) == // (3) PREV_BITS(key_part_map, max_loose_keypart+1) && // (3) !key_uses_partial_cols(s->table->s, key)) { if (s->quick && s->quick->index == key && s->quick->get_type() == QUICK_SELECT_I::QS_TYPE_RANGE) { quick_uses_applicable_index= TRUE; quick_max_loose_keypart= max_loose_keypart; } DBUG_PRINT("info", ("Can use LooseScan scan")); if (found_part & 1) { /* Can use LooseScan on ref access if the first key part is bound */ part1_conds_met= TRUE; } /* Check if this is a special case where there are no usable bound IN-equalities, i.e. we have outer_expr IN (SELECT innertbl.key FROM ...) and outer_expr cannot be evaluated yet, so it's actually full index scan and not a ref access. We can do full index scan if it uses index-only. */ if (!(found_part & 1 ) && /* no usable ref access for 1st key part */ s->table->covering_keys.is_set(key)) { part1_conds_met= TRUE; DBUG_PRINT("info", ("Can use full index scan for LooseScan")); /* Calculate the cost of complete loose index scan. */ double records= rows2double(s->table->file->stats.records); /* The cost is entire index scan cost (divided by 2) */ double read_time= s->table->file->keyread_time(key, 1, (ha_rows) records); /* Now find out how many different keys we will get (for now we ignore the fact that we have "keypart_i=const" restriction for some key components, that may make us think think that loose scan will produce more distinct records than it actually will) */ ulong rpc; if ((rpc= s->table->key_info[key].rec_per_key[max_loose_keypart])) records= records / rpc; // TODO: previous version also did /2 if (read_time < best_loose_scan_cost) { best_loose_scan_key= key; best_loose_scan_cost= read_time; best_loose_scan_records= records; best_max_loose_keypart= max_loose_keypart; best_loose_scan_start_key= start_key; best_ref_depend_map= 0; } } } } void check_ref_access_part2(uint key, KEYUSE *start_key, double records, double read_time, table_map ref_depend_map_arg) { if (part1_conds_met && read_time < best_loose_scan_cost) { /* TODO use rec-per-key-based fanout calculations */ best_loose_scan_key= key; best_loose_scan_cost= read_time; best_loose_scan_records= records; best_max_loose_keypart= max_loose_keypart; best_loose_scan_start_key= start_key; best_ref_depend_map= ref_depend_map_arg; } } void check_range_access(JOIN *join, uint idx, QUICK_SELECT_I *quick) { /* TODO: this the right part restriction: */ if (quick_uses_applicable_index && idx == join->const_tables && quick->read_time < best_loose_scan_cost) { best_loose_scan_key= quick->index; best_loose_scan_cost= quick->read_time; /* this is ok because idx == join->const_tables */ best_loose_scan_records= rows2double(quick->records); best_max_loose_keypart= quick_max_loose_keypart; best_loose_scan_start_key= NULL; best_ref_depend_map= 0; } } void save_to_position(JOIN_TAB *tab, POSITION *pos) { pos->read_time= best_loose_scan_cost; if (best_loose_scan_cost != DBL_MAX) { pos->records_read= best_loose_scan_records; pos->key= best_loose_scan_start_key; pos->cond_selectivity= 1.0; pos->loosescan_picker.loosescan_key= best_loose_scan_key; pos->loosescan_picker.loosescan_parts= best_max_loose_keypart + 1; pos->use_join_buffer= FALSE; pos->table= tab; pos->range_rowid_filter_info= tab->range_rowid_filter_info; pos->ref_depend_map= best_ref_depend_map; DBUG_PRINT("info", ("Produced a LooseScan plan, key %s, %s", tab->table->key_info[best_loose_scan_key].name.str, best_loose_scan_start_key? "(ref access)": "(range/index access)")); } } }; void optimize_semi_joins(JOIN *join, table_map remaining_tables, uint idx, double *current_record_count, double *current_read_time, POSITION *loose_scan_pos); void update_sj_state(JOIN *join, const JOIN_TAB *new_tab, uint idx, table_map remaining_tables); void restore_prev_sj_state(const table_map remaining_tables, const JOIN_TAB *tab, uint idx); void fix_semijoin_strategies_for_picked_join_order(JOIN *join); bool setup_sj_materialization_part1(JOIN_TAB *sjm_tab); bool setup_sj_materialization_part2(JOIN_TAB *sjm_tab); uint get_number_of_tables_at_top_level(JOIN *join); /* Temporary table used by semi-join DuplicateElimination strategy This consists of the temptable itself and data needed to put records into it. The table's DDL is as follows: CREATE TABLE tmptable (col VARCHAR(n) BINARY, PRIMARY KEY(col)); where the primary key can be replaced with unique constraint if n exceeds the limit (as it is always done for query execution-time temptables). The record value is a concatenation of rowids of tables from the join we're executing. If a join table is on the inner side of the outer join, we assume that its rowid can be NULL and provide means to store this rowid in the tuple. */ class SJ_TMP_TABLE : public Sql_alloc { public: /* Array of pointers to tables whose rowids compose the temporary table record. */ class TAB { public: JOIN_TAB *join_tab; uint rowid_offset; ushort null_byte; uchar null_bit; }; TAB *tabs; TAB *tabs_end; /* is_degenerate==TRUE means this is a special case where the temptable record has zero length (and presence of a unique key means that the temptable can have either 0 or 1 records). In this case we don't create the physical temptable but instead record its state in SJ_TMP_TABLE::have_degenerate_row. */ bool is_degenerate; /* When is_degenerate==TRUE: the contents of the table (whether it has the record or not). */ bool have_degenerate_row; /* table record parameters */ uint null_bits; uint null_bytes; uint rowid_len; /* The temporary table itself (NULL means not created yet) */ TABLE *tmp_table; /* These are the members we got from temptable creation code. We'll need them if we'll need to convert table from HEAP to MyISAM/Maria. */ TMP_ENGINE_COLUMNDEF *start_recinfo; TMP_ENGINE_COLUMNDEF *recinfo; SJ_TMP_TABLE *next_flush_table; int sj_weedout_delete_rows(); int sj_weedout_check_row(THD *thd); bool create_sj_weedout_tmp_table(THD *thd); }; int setup_semijoin_loosescan(JOIN *join); int setup_semijoin_dups_elimination(JOIN *join, ulonglong options, uint no_jbuf_after); void destroy_sj_tmp_tables(JOIN *join); int clear_sj_tmp_tables(JOIN *join); int rewrite_to_index_subquery_engine(JOIN *join); void get_delayed_table_estimates(TABLE *table, ha_rows *out_rows, double *scan_time, double *startup_cost); enum_nested_loop_state join_tab_execution_startup(JOIN_TAB *tab); mysql/server/private/sql_array.h000064400000015333151027430560013047 0ustar00#ifndef SQL_ARRAY_INCLUDED #define SQL_ARRAY_INCLUDED /* Copyright (c) 2003, 2005-2007 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include /** A wrapper class which provides array bounds checking. We do *not* own the array, we simply have a pointer to the first element, and a length. @remark We want the compiler-generated versions of: - the copy CTOR (memberwise initialization) - the assignment operator (memberwise assignment) @param Element_type The type of the elements of the container. */ template class Bounds_checked_array { public: Bounds_checked_array()= default; Bounds_checked_array(Element_type *el, size_t size_arg) : m_array(el), m_size(size_arg) {} void reset() { m_array= NULL; m_size= 0; } void reset(Element_type *array_arg, size_t size_arg) { m_array= array_arg; m_size= size_arg; } /** Set a new bound on the array. Does not resize the underlying array, so the new size must be smaller than or equal to the current size. */ void resize(size_t new_size) { DBUG_ASSERT(new_size <= m_size); m_size= new_size; } Element_type &operator[](size_t n) { DBUG_ASSERT(n < m_size); return m_array[n]; } const Element_type &operator[](size_t n) const { DBUG_ASSERT(n < m_size); return m_array[n]; } size_t element_size() const { return sizeof(Element_type); } size_t size() const { return m_size; } bool is_null() const { return m_array == NULL; } void pop_front() { DBUG_ASSERT(m_size > 0); m_array+= 1; m_size-= 1; } Element_type *array() const { return m_array; } Element_type *begin() const { return array(); } Element_type *end() const { return array() + m_size; } bool operator==(const Bounds_checked_array&rhs) const { return m_array == rhs.m_array && m_size == rhs.m_size; } bool operator!=(const Bounds_checked_array&rhs) const { return m_array != rhs.m_array || m_size != rhs.m_size; } private: Element_type *m_array= nullptr; size_t m_size= 0; }; /* A typesafe wrapper around DYNAMIC_ARRAY TODO: Change creator to take a THREAD_SPECIFIC option. */ template class Dynamic_array { DYNAMIC_ARRAY array; public: Dynamic_array(PSI_memory_key psi_key, uint prealloc=16, uint increment=16) { init(psi_key, prealloc, increment); } Dynamic_array(MEM_ROOT *root, uint prealloc=16, uint increment=16) { void *init_buffer= alloc_root(root, sizeof(Elem) * prealloc); init_dynamic_array2(root->m_psi_key, &array, sizeof(Elem), init_buffer, prealloc, increment, MYF(0)); } void init(PSI_memory_key psi_key, uint prealloc=16, uint increment=16) { init_dynamic_array2(psi_key, &array, sizeof(Elem), 0, prealloc, increment, MYF(0)); } /** @note Though formally this could be declared "const" it would be misleading at it returns a non-const pointer to array's data. */ Elem& at(size_t idx) { DBUG_ASSERT(idx < array.elements); return *(((Elem*)array.buffer) + idx); } /// Const variant of at(), which cannot change data const Elem& at(size_t idx) const { return *(((Elem*)array.buffer) + idx); } Elem& operator[](size_t idx) { return at(idx); } /// Const variant of operator[] const Elem& operator[](size_t idx) const { return at(idx); } /// @returns pointer to first element Elem *front() { return (Elem*)array.buffer; } /// @returns pointer to first element const Elem *front() const { return (const Elem*)array.buffer; } /// @returns pointer to last element Elem *back() { return ((Elem*)array.buffer) + array.elements - 1; } /// @returns pointer to last element const Elem *back() const { return ((const Elem*)array.buffer) + array.elements - 1; } size_t size() const { return array.elements; } const Elem *end() const { return back() + 1; } /// @returns pointer to n-th element Elem *get_pos(size_t idx) { return ((Elem*)array.buffer) + idx; } /// @returns pointer to n-th element const Elem *get_pos(size_t idx) const { return ((const Elem*)array.buffer) + idx; } /** @retval false ok @retval true OOM, @c my_error() has been called. */ bool append(const Elem &el) { return insert_dynamic(&array, &el); } bool append_val(Elem el) { return (insert_dynamic(&array, (uchar*)&el)); } bool push(Elem &el) { return append(el); } /// Pops the last element. Does nothing if array is empty. Elem& pop() { return *((Elem*)pop_dynamic(&array)); } void del(size_t idx) { DBUG_ASSERT(idx <= array.max_element); delete_dynamic_element(&array, (uint)idx); } size_t elements() const { return array.elements; } void elements(size_t num_elements) { DBUG_ASSERT(num_elements <= array.max_element); array.elements= (uint)num_elements; } void clear() { elements(0); } void set(uint idx, const Elem &el) { set_dynamic(&array, &el, idx); } void freeze() { freeze_size(&array); } bool reserve(size_t new_size) { return allocate_dynamic(&array, (uint)new_size); } bool resize(size_t new_size, Elem default_val) { size_t old_size= elements(); if (reserve(new_size)) return true; if (new_size > old_size) { set_dynamic(&array, (uchar*)&default_val, (uint)(new_size - 1)); /*for (size_t i= old_size; i != new_size; i++) { at(i)= default_val; }*/ } return false; } ~Dynamic_array() { delete_dynamic(&array); } void free_memory() { delete_dynamic(&array); } void sort(int (*cmp_func)(const void *, const void *)) { my_qsort(array.buffer, array.elements, sizeof(Elem), cmp_func); } void sort(qsort_cmp2 cmp_func, void *data) { my_qsort2(array.buffer, array.elements, sizeof(Elem), cmp_func, data); } }; typedef Bounds_checked_array Ref_ptr_array; #endif /* SQL_ARRAY_INCLUDED */ mysql/server/private/my_bit.h000064400000014064151027430560012335 0ustar00/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_BIT_INCLUDED #define MY_BIT_INCLUDED /* Some useful bit functions */ C_MODE_START extern const uchar _my_bits_reverse_table[256]; /* my_bit_log2_xxx() In the given value, find the highest bit set, which is the smallest X that satisfies the condition: (2^X >= value). Can be used as a reverse operation for (1<> 4)) + 4: my_bit_log2_hex_digit(value); } static inline CONSTEXPR uint my_bit_log2_uint16(uint16 value) { return value & 0xFF00 ? my_bit_log2_uint8((uint8) (value >> 8)) + 8 : my_bit_log2_uint8((uint8) value); } static inline CONSTEXPR uint my_bit_log2_uint32(uint32 value) { return value & 0xFFFF0000UL ? my_bit_log2_uint16((uint16) (value >> 16)) + 16 : my_bit_log2_uint16((uint16) value); } static inline CONSTEXPR uint my_bit_log2_uint64(ulonglong value) { return value & 0xFFFFFFFF00000000ULL ? my_bit_log2_uint32((uint32) (value >> 32)) + 32 : my_bit_log2_uint32((uint32) value); } static inline CONSTEXPR uint my_bit_log2_size_t(size_t value) { #ifdef __cplusplus static_assert(sizeof(size_t) <= sizeof(ulonglong), "size_t <= ulonglong is an assumption that needs to be fixed " "for this architecture. Please create an issue on " "https://jira.mariadb.org"); #endif return my_bit_log2_uint64((ulonglong) value); } /* Count bits in 32bit integer Algorithm by Sean Anderson, according to: http://graphics.stanford.edu/~seander/bithacks.html under "Counting bits set, in parallel" (Original code public domain). */ static inline uint my_count_bits_uint32(uint32 v) { v = v - ((v >> 1) & 0x55555555); v = (v & 0x33333333) + ((v >> 2) & 0x33333333); return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; } static inline uint my_count_bits(ulonglong x) { return my_count_bits_uint32((uint32)x) + my_count_bits_uint32((uint32)(x >> 32)); } /* Next highest power of two SYNOPSIS my_round_up_to_next_power() v Value to check RETURN Next or equal power of 2 Note: 0 will return 0 NOTES Algorithm by Sean Anderson, according to: http://graphics.stanford.edu/~seander/bithacks.html (Original code public domain) Comments shows how this works with 01100000000000000000000000001011 */ static inline uint32 my_round_up_to_next_power(uint32 v) { v--; /* 01100000000000000000000000001010 */ v|= v >> 1; /* 01110000000000000000000000001111 */ v|= v >> 2; /* 01111100000000000000000000001111 */ v|= v >> 4; /* 01111111110000000000000000001111 */ v|= v >> 8; /* 01111111111111111100000000001111 */ v|= v >> 16; /* 01111111111111111111111111111111 */ return v+1; /* 10000000000000000000000000000000 */ } static inline uint32 my_clear_highest_bit(uint32 v) { uint32 w=v >> 1; w|= w >> 1; w|= w >> 2; w|= w >> 4; w|= w >> 8; w|= w >> 16; return v & w; } static inline uint32 my_reverse_bits(uint32 key) { return ((uint32)_my_bits_reverse_table[ key & 255] << 24) | ((uint32)_my_bits_reverse_table[(key>> 8) & 255] << 16) | ((uint32)_my_bits_reverse_table[(key>>16) & 255] << 8) | (uint32)_my_bits_reverse_table[(key>>24) ]; } /* a number with the n lowest bits set an overflow-safe version of (1 << n) - 1 */ static inline uint64 my_set_bits(int n) { return (((1ULL << (n - 1)) - 1) << 1) | 1; } /* Create a mask of the significant bits for the last byte (1,3,7,..255) */ static inline uchar last_byte_mask(uint bits) { /* Get the number of used bits-1 (0..7) in the last byte */ unsigned int const used = (bits - 1U) & 7U; /* Return bitmask for the significant bits */ return (uchar) ((2U << used) - 1); } static inline uint my_bits_in_bytes(uint n) { return ((n + 7) / 8); } #ifdef _MSC_VER #include #endif /* Find the position of the first(least significant) bit set in the argument. Returns 64 if the argument was 0. */ static inline uint my_find_first_bit(ulonglong n) { if(!n) return 64; #if defined(__GNUC__) return __builtin_ctzll(n); #elif defined(_MSC_VER) #if defined(_M_IX86) unsigned long bit; if( _BitScanForward(&bit, (uint)n)) return bit; _BitScanForward(&bit, (uint)(n>>32)); return bit + 32; #else unsigned long bit; _BitScanForward64(&bit, n); return bit; #endif #else /* Generic case */ uint shift= 0; static const uchar last_bit[16] = { 32, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0}; uint bit; while ((bit = last_bit[(n >> shift) & 0xF]) == 32) shift+= 4; return shift+bit; #endif } C_MODE_END #endif /* MY_BIT_INCLUDED */ mysql/server/private/my_check_opt.h000064400000005072151027430560013515 0ustar00/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_check_opt_h #define _my_check_opt_h #ifdef __cplusplus extern "C" { #endif /* All given definitions needed for MyISAM storage engine: myisamchk.c or/and ha_myisam.cc or/and micheck.c Some definitions are needed by the MySQL parser. */ #define T_AUTO_INC (1UL << 0) #define T_AUTO_REPAIR (1UL << 1) #define T_BACKUP_DATA (1UL << 2) #define T_CALC_CHECKSUM (1UL << 3) #define T_CHECK (1UL << 4) #define T_CHECK_ONLY_CHANGED (1UL << 5) #define T_CREATE_MISSING_KEYS (1UL << 6) #define T_DESCRIPT (1UL << 7) #define T_DONT_CHECK_CHECKSUM (1UL << 8) #define T_EXTEND (1UL << 9) #define T_FAST (1UL << 10) #define T_FORCE_CREATE (1UL << 11) #define T_FORCE_UNIQUENESS (1UL << 12) #define T_INFO (1UL << 13) /** CHECK TABLE...MEDIUM (the default) */ #define T_MEDIUM (1UL << 14) /** CHECK TABLE...QUICK */ #define T_QUICK (1UL << 15) #define T_READONLY (1UL << 16) #define T_REP (1UL << 17) #define T_REP_BY_SORT (1UL << 18) #define T_REP_PARALLEL (1UL << 19) #define T_RETRY_WITHOUT_QUICK (1UL << 20) #define T_SAFE_REPAIR (1UL << 21) #define T_SILENT (1UL << 22) #define T_SORT_INDEX (1UL << 23) #define T_SORT_RECORDS (1UL << 24) #define T_STATISTICS (1UL << 25) #define T_UNPACK (1UL << 26) #define T_UPDATE_STATE (1UL << 27) #define T_VERBOSE (1UL << 28) #define T_VERY_SILENT (1UL << 29) #define T_WAIT_FOREVER (1UL << 30) #define T_WRITE_LOOP (1UL << 31) #define T_ZEROFILL (1ULL << 32) #define T_ZEROFILL_KEEP_LSN (1ULL << 33) /** If repair should not bump create_rename_lsn */ #define T_NO_CREATE_RENAME_LSN (1ULL << 34) /** If repair shouldn't do any locks */ #define T_NO_LOCKS (1ULL << 35) #define T_CREATE_UNIQUE_BY_SORT (1ULL << 36) #define T_SUPPRESS_ERR_HANDLING (1ULL << 37) #define T_FORCE_SORT_MEMORY (1ULL << 38) #define T_REP_ANY (T_REP | T_REP_BY_SORT | T_REP_PARALLEL) #ifdef __cplusplus } #endif #endif mysql/server/private/sql_db.h000064400000004610151027430560012312 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_DB_INCLUDED #define SQL_DB_INCLUDED #include "hash.h" /* HASH */ class THD; int mysql_create_db(THD *thd, const LEX_CSTRING *db, DDL_options_st options, const Schema_specification_st *create); bool mysql_alter_db(THD *thd, const LEX_CSTRING *db, const Schema_specification_st *create); bool mysql_rm_db(THD *thd, const LEX_CSTRING *db, bool if_exists); bool mysql_upgrade_db(THD *thd, const LEX_CSTRING *old_db); uint mysql_change_db(THD *thd, const LEX_CSTRING *new_db_name, bool force_switch); bool mysql_opt_change_db(THD *thd, const LEX_CSTRING *new_db_name, LEX_STRING *saved_db_name, bool force_switch, bool *cur_db_changed); bool my_dboptions_cache_init(void); void my_dboptions_cache_free(void); bool check_db_dir_existence(const char *db_name); bool load_db_opt(THD *thd, const char *path, Schema_specification_st *create); bool load_db_opt_by_name(THD *thd, const char *db_name, Schema_specification_st *db_create_info); CHARSET_INFO *get_default_db_collation(THD *thd, const char *db_name); bool my_dbopt_init(void); void my_dbopt_cleanup(void); const char *normalize_db_name(const char *db, char *buffer, size_t buffer_size); void drop_database_objects(THD *thd, const LEX_CSTRING *path, const LEX_CSTRING *db, bool rm_mysql_schema); my_bool rm_dir_w_symlink(const char *org_path, my_bool send_error); #define MY_DB_OPT_FILE "db.opt" #endif /* SQL_DB_INCLUDED */ mysql/server/private/lex_token.h000064400000123006151027430560013037 0ustar00/* Copyright (c) 2011, 2018, Oracle, MariaDB Corporation Ab and others. */ /* This file is generated, do not edit. See file sql/gen_lex_token.cc. */ struct lex_token_string { const char *m_token_string; int m_token_length; bool m_append_space; bool m_start_expr; }; typedef struct lex_token_string lex_token_string; #ifdef LEX_TOKEN_WITH_DEFINITION lex_token_string lex_token_array[]= { /* PART 1: character tokens. */ /* 000 */ { "\x00", 1, true, false}, /* 001 */ { "\x01", 1, true, false}, /* 002 */ { "\x02", 1, true, false}, /* 003 */ { "\x03", 1, true, false}, /* 004 */ { "\x04", 1, true, false}, /* 005 */ { "\x05", 1, true, false}, /* 006 */ { "\x06", 1, true, false}, /* 007 */ { "\x07", 1, true, false}, /* 008 */ { "\x08", 1, true, false}, /* 009 */ { "\x09", 1, true, false}, /* 010 */ { "\x0a", 1, true, false}, /* 011 */ { "\x0b", 1, true, false}, /* 012 */ { "\x0c", 1, true, false}, /* 013 */ { "\x0d", 1, true, false}, /* 014 */ { "\x0e", 1, true, false}, /* 015 */ { "\x0f", 1, true, false}, /* 016 */ { "\x10", 1, true, false}, /* 017 */ { "\x11", 1, true, false}, /* 018 */ { "\x12", 1, true, false}, /* 019 */ { "\x13", 1, true, false}, /* 020 */ { "\x14", 1, true, false}, /* 021 */ { "\x15", 1, true, false}, /* 022 */ { "\x16", 1, true, false}, /* 023 */ { "\x17", 1, true, false}, /* 024 */ { "\x18", 1, true, false}, /* 025 */ { "\x19", 1, true, false}, /* 026 */ { "\x1a", 1, true, false}, /* 027 */ { "\x1b", 1, true, false}, /* 028 */ { "\x1c", 1, true, false}, /* 029 */ { "\x1d", 1, true, false}, /* 030 */ { "\x1e", 1, true, false}, /* 031 */ { "\x1f", 1, true, false}, /* 032 */ { "\x20", 1, true, false}, /* 033 */ { "\x21", 1, true, false}, /* 034 */ { "\x22", 1, true, false}, /* 035 */ { "\x23", 1, true, false}, /* 036 */ { "\x24", 1, true, false}, /* 037 */ { "\x25", 1, true, true}, /* 038 */ { "\x26", 1, true, true}, /* 039 */ { "\x27", 1, true, false}, /* 040 */ { "\x28", 1, true, true}, /* 041 */ { "\x29", 1, true, false}, /* 042 */ { "\x2a", 1, true, true}, /* 043 */ { "\x2b", 1, true, true}, /* 044 */ { "\x2c", 1, true, true}, /* 045 */ { "\x2d", 1, true, true}, /* 046 */ { "\x2e", 1, true, false}, /* 047 */ { "\x2f", 1, true, true}, /* 048 */ { "\x30", 1, true, false}, /* 049 */ { "\x31", 1, true, false}, /* 050 */ { "\x32", 1, true, false}, /* 051 */ { "\x33", 1, true, false}, /* 052 */ { "\x34", 1, true, false}, /* 053 */ { "\x35", 1, true, false}, /* 054 */ { "\x36", 1, true, false}, /* 055 */ { "\x37", 1, true, false}, /* 056 */ { "\x38", 1, true, false}, /* 057 */ { "\x39", 1, true, false}, /* 058 */ { "\x3a", 1, true, false}, /* 059 */ { "\x3b", 1, true, false}, /* 060 */ { "\x3c", 1, true, false}, /* 061 */ { "\x3d", 1, true, false}, /* 062 */ { "\x3e", 1, true, false}, /* 063 */ { "\x3f", 1, true, false}, /* 064 */ { "\x40", 1, false, false}, /* 065 */ { "\x41", 1, true, false}, /* 066 */ { "\x42", 1, true, false}, /* 067 */ { "\x43", 1, true, false}, /* 068 */ { "\x44", 1, true, false}, /* 069 */ { "\x45", 1, true, false}, /* 070 */ { "\x46", 1, true, false}, /* 071 */ { "\x47", 1, true, false}, /* 072 */ { "\x48", 1, true, false}, /* 073 */ { "\x49", 1, true, false}, /* 074 */ { "\x4a", 1, true, false}, /* 075 */ { "\x4b", 1, true, false}, /* 076 */ { "\x4c", 1, true, false}, /* 077 */ { "\x4d", 1, true, false}, /* 078 */ { "\x4e", 1, true, false}, /* 079 */ { "\x4f", 1, true, false}, /* 080 */ { "\x50", 1, true, false}, /* 081 */ { "\x51", 1, true, false}, /* 082 */ { "\x52", 1, true, false}, /* 083 */ { "\x53", 1, true, false}, /* 084 */ { "\x54", 1, true, false}, /* 085 */ { "\x55", 1, true, false}, /* 086 */ { "\x56", 1, true, false}, /* 087 */ { "\x57", 1, true, false}, /* 088 */ { "\x58", 1, true, false}, /* 089 */ { "\x59", 1, true, false}, /* 090 */ { "\x5a", 1, true, false}, /* 091 */ { "\x5b", 1, true, false}, /* 092 */ { "\x5c", 1, true, false}, /* 093 */ { "\x5d", 1, true, false}, /* 094 */ { "\x5e", 1, true, true}, /* 095 */ { "\x5f", 1, true, false}, /* 096 */ { "\x60", 1, true, false}, /* 097 */ { "\x61", 1, true, false}, /* 098 */ { "\x62", 1, true, false}, /* 099 */ { "\x63", 1, true, false}, /* 100 */ { "\x64", 1, true, false}, /* 101 */ { "\x65", 1, true, false}, /* 102 */ { "\x66", 1, true, false}, /* 103 */ { "\x67", 1, true, false}, /* 104 */ { "\x68", 1, true, false}, /* 105 */ { "\x69", 1, true, false}, /* 106 */ { "\x6a", 1, true, false}, /* 107 */ { "\x6b", 1, true, false}, /* 108 */ { "\x6c", 1, true, false}, /* 109 */ { "\x6d", 1, true, false}, /* 110 */ { "\x6e", 1, true, false}, /* 111 */ { "\x6f", 1, true, false}, /* 112 */ { "\x70", 1, true, false}, /* 113 */ { "\x71", 1, true, false}, /* 114 */ { "\x72", 1, true, false}, /* 115 */ { "\x73", 1, true, false}, /* 116 */ { "\x74", 1, true, false}, /* 117 */ { "\x75", 1, true, false}, /* 118 */ { "\x76", 1, true, false}, /* 119 */ { "\x77", 1, true, false}, /* 120 */ { "\x78", 1, true, false}, /* 121 */ { "\x79", 1, true, false}, /* 122 */ { "\x7a", 1, true, false}, /* 123 */ { "\x7b", 1, true, false}, /* 124 */ { "\x7c", 1, true, true}, /* 125 */ { "\x7d", 1, true, false}, /* 126 */ { "\x7e", 1, true, false}, /* 127 */ { "\x7f", 1, true, false}, /* 128 */ { "\x80", 1, true, false}, /* 129 */ { "\x81", 1, true, false}, /* 130 */ { "\x82", 1, true, false}, /* 131 */ { "\x83", 1, true, false}, /* 132 */ { "\x84", 1, true, false}, /* 133 */ { "\x85", 1, true, false}, /* 134 */ { "\x86", 1, true, false}, /* 135 */ { "\x87", 1, true, false}, /* 136 */ { "\x88", 1, true, false}, /* 137 */ { "\x89", 1, true, false}, /* 138 */ { "\x8a", 1, true, false}, /* 139 */ { "\x8b", 1, true, false}, /* 140 */ { "\x8c", 1, true, false}, /* 141 */ { "\x8d", 1, true, false}, /* 142 */ { "\x8e", 1, true, false}, /* 143 */ { "\x8f", 1, true, false}, /* 144 */ { "\x90", 1, true, false}, /* 145 */ { "\x91", 1, true, false}, /* 146 */ { "\x92", 1, true, false}, /* 147 */ { "\x93", 1, true, false}, /* 148 */ { "\x94", 1, true, false}, /* 149 */ { "\x95", 1, true, false}, /* 150 */ { "\x96", 1, true, false}, /* 151 */ { "\x97", 1, true, false}, /* 152 */ { "\x98", 1, true, false}, /* 153 */ { "\x99", 1, true, false}, /* 154 */ { "\x9a", 1, true, false}, /* 155 */ { "\x9b", 1, true, false}, /* 156 */ { "\x9c", 1, true, false}, /* 157 */ { "\x9d", 1, true, false}, /* 158 */ { "\x9e", 1, true, false}, /* 159 */ { "\x9f", 1, true, false}, /* 160 */ { "\xa0", 1, true, false}, /* 161 */ { "\xa1", 1, true, false}, /* 162 */ { "\xa2", 1, true, false}, /* 163 */ { "\xa3", 1, true, false}, /* 164 */ { "\xa4", 1, true, false}, /* 165 */ { "\xa5", 1, true, false}, /* 166 */ { "\xa6", 1, true, false}, /* 167 */ { "\xa7", 1, true, false}, /* 168 */ { "\xa8", 1, true, false}, /* 169 */ { "\xa9", 1, true, false}, /* 170 */ { "\xaa", 1, true, false}, /* 171 */ { "\xab", 1, true, false}, /* 172 */ { "\xac", 1, true, false}, /* 173 */ { "\xad", 1, true, false}, /* 174 */ { "\xae", 1, true, false}, /* 175 */ { "\xaf", 1, true, false}, /* 176 */ { "\xb0", 1, true, false}, /* 177 */ { "\xb1", 1, true, false}, /* 178 */ { "\xb2", 1, true, false}, /* 179 */ { "\xb3", 1, true, false}, /* 180 */ { "\xb4", 1, true, false}, /* 181 */ { "\xb5", 1, true, false}, /* 182 */ { "\xb6", 1, true, false}, /* 183 */ { "\xb7", 1, true, false}, /* 184 */ { "\xb8", 1, true, false}, /* 185 */ { "\xb9", 1, true, false}, /* 186 */ { "\xba", 1, true, false}, /* 187 */ { "\xbb", 1, true, false}, /* 188 */ { "\xbc", 1, true, false}, /* 189 */ { "\xbd", 1, true, false}, /* 190 */ { "\xbe", 1, true, false}, /* 191 */ { "\xbf", 1, true, false}, /* 192 */ { "\xc0", 1, true, false}, /* 193 */ { "\xc1", 1, true, false}, /* 194 */ { "\xc2", 1, true, false}, /* 195 */ { "\xc3", 1, true, false}, /* 196 */ { "\xc4", 1, true, false}, /* 197 */ { "\xc5", 1, true, false}, /* 198 */ { "\xc6", 1, true, false}, /* 199 */ { "\xc7", 1, true, false}, /* 200 */ { "\xc8", 1, true, false}, /* 201 */ { "\xc9", 1, true, false}, /* 202 */ { "\xca", 1, true, false}, /* 203 */ { "\xcb", 1, true, false}, /* 204 */ { "\xcc", 1, true, false}, /* 205 */ { "\xcd", 1, true, false}, /* 206 */ { "\xce", 1, true, false}, /* 207 */ { "\xcf", 1, true, false}, /* 208 */ { "\xd0", 1, true, false}, /* 209 */ { "\xd1", 1, true, false}, /* 210 */ { "\xd2", 1, true, false}, /* 211 */ { "\xd3", 1, true, false}, /* 212 */ { "\xd4", 1, true, false}, /* 213 */ { "\xd5", 1, true, false}, /* 214 */ { "\xd6", 1, true, false}, /* 215 */ { "\xd7", 1, true, false}, /* 216 */ { "\xd8", 1, true, false}, /* 217 */ { "\xd9", 1, true, false}, /* 218 */ { "\xda", 1, true, false}, /* 219 */ { "\xdb", 1, true, false}, /* 220 */ { "\xdc", 1, true, false}, /* 221 */ { "\xdd", 1, true, false}, /* 222 */ { "\xde", 1, true, false}, /* 223 */ { "\xdf", 1, true, false}, /* 224 */ { "\xe0", 1, true, false}, /* 225 */ { "\xe1", 1, true, false}, /* 226 */ { "\xe2", 1, true, false}, /* 227 */ { "\xe3", 1, true, false}, /* 228 */ { "\xe4", 1, true, false}, /* 229 */ { "\xe5", 1, true, false}, /* 230 */ { "\xe6", 1, true, false}, /* 231 */ { "\xe7", 1, true, false}, /* 232 */ { "\xe8", 1, true, false}, /* 233 */ { "\xe9", 1, true, false}, /* 234 */ { "\xea", 1, true, false}, /* 235 */ { "\xeb", 1, true, false}, /* 236 */ { "\xec", 1, true, false}, /* 237 */ { "\xed", 1, true, false}, /* 238 */ { "\xee", 1, true, false}, /* 239 */ { "\xef", 1, true, false}, /* 240 */ { "\xf0", 1, true, false}, /* 241 */ { "\xf1", 1, true, false}, /* 242 */ { "\xf2", 1, true, false}, /* 243 */ { "\xf3", 1, true, false}, /* 244 */ { "\xf4", 1, true, false}, /* 245 */ { "\xf5", 1, true, false}, /* 246 */ { "\xf6", 1, true, false}, /* 247 */ { "\xf7", 1, true, false}, /* 248 */ { "\xf8", 1, true, false}, /* 249 */ { "\xf9", 1, true, false}, /* 250 */ { "\xfa", 1, true, false}, /* 251 */ { "\xfb", 1, true, false}, /* 252 */ { "\xfc", 1, true, false}, /* 253 */ { "\xfd", 1, true, false}, /* 254 */ { "\xfe", 1, true, false}, /* 255 */ { "\xff", 1, true, false}, /* PART 2: named tokens. */ /* 256 */ { "(unknown)", 9, true, false}, /* 257 */ { "(unknown)", 9, true, false}, /* 258 */ { "(unknown)", 9, true, false}, /* 259 */ { "(unknown)", 9, true, false}, /* 260 */ { "(unknown)", 9, true, false}, /* 261 */ { "", 0, true, false}, /* 262 */ { "(unknown)", 9, true, false}, /* 263 */ { "?", 1, true, false}, /* 264 */ { "FOR SYSTEM_TIME", 15, true, false}, /* 265 */ { "(unknown)", 9, true, false}, /* 266 */ { "(unknown)", 9, true, false}, /* 267 */ { "(unknown)", 9, true, false}, /* 268 */ { "(unknown)", 9, true, false}, /* 269 */ { "(unknown)", 9, true, false}, /* 270 */ { "WITH CUBE", 9, true, false}, /* 271 */ { "WITH ROLLUP", 11, true, false}, /* 272 */ { "WITH SYSTEM", 11, true, false}, /* 273 */ { "(id)", 4, true, false}, /* 274 */ { "(id_quoted)", 11, true, false}, /* 275 */ { "(hostname)", 10, true, false}, /* 276 */ { "(_charset)", 10, true, false}, /* 277 */ { "(bin)", 5, true, false}, /* 278 */ { "(decimal)", 9, true, false}, /* 279 */ { "(float)", 7, true, false}, /* 280 */ { "(hex)", 5, true, false}, /* 281 */ { "(unknown)", 9, true, false}, /* 282 */ { "(long)", 6, true, false}, /* 283 */ { "(nchar)", 7, true, false}, /* 284 */ { "(num)", 5, true, false}, /* 285 */ { "(text)", 6, true, false}, /* 286 */ { "(ulonglong)", 11, true, false}, /* 287 */ { "&&", 2, true, true}, /* 288 */ { "(unknown)", 9, true, false}, /* 289 */ { "<=>", 3, true, false}, /* 290 */ { ">=", 2, true, false}, /* 291 */ { "<=", 2, true, false}, /* 292 */ { "(unknown)", 9, true, false}, /* 293 */ { "!=", 2, true, false}, /* 294 */ { "!", 1, true, false}, /* 295 */ { "||", 2, true, true}, /* 296 */ { ":=", 2, true, false}, /* 297 */ { "<<", 2, true, true}, /* 298 */ { ">>", 2, true, true}, /* 299 */ { "ACCESSIBLE", 10, true, false}, /* 300 */ { "ADD", 3, true, false}, /* 301 */ { "ALL", 3, true, false}, /* 302 */ { "ALTER", 5, true, false}, /* 303 */ { "ANALYZE", 7, true, false}, /* 304 */ { "AND", 3, true, true}, /* 305 */ { "ASC", 3, true, false}, /* 306 */ { "ASENSITIVE", 10, true, false}, /* 307 */ { "AS", 2, true, false}, /* 308 */ { "BEFORE", 6, true, false}, /* 309 */ { "BETWEEN", 7, true, true}, /* 310 */ { "INT8", 4, true, false}, /* 311 */ { "BINARY", 6, true, false}, /* 312 */ { "BIT_AND", 7, true, false}, /* 313 */ { "BIT_OR", 6, true, false}, /* 314 */ { "BIT_XOR", 7, true, false}, /* 315 */ { "BLOB", 4, true, false}, /* 316 */ { "(unknown)", 9, true, false}, /* 317 */ { "(unknown)", 9, true, false}, /* 318 */ { "BOTH", 4, true, false}, /* 319 */ { "BY", 2, true, false}, /* 320 */ { "CALL", 4, true, false}, /* 321 */ { "CASCADE", 7, true, false}, /* 322 */ { "CASE", 4, true, true}, /* 323 */ { "CAST", 4, true, false}, /* 324 */ { "CHANGE", 6, true, false}, /* 325 */ { "CHARACTER", 9, true, false}, /* 326 */ { "CHECK", 5, true, false}, /* 327 */ { "COLLATE", 7, true, false}, /* 328 */ { "CONDITION", 9, true, false}, /* 329 */ { "CONSTRAINT", 10, true, false}, /* 330 */ { "CONTINUE", 8, true, false}, /* 331 */ { "(unknown)", 9, true, false}, /* 332 */ { "CONVERT", 7, true, false}, /* 333 */ { "COUNT", 5, true, false}, /* 334 */ { "CREATE", 6, true, false}, /* 335 */ { "CROSS", 5, true, false}, /* 336 */ { "CUME_DIST", 9, true, false}, /* 337 */ { "CURDATE", 7, true, false}, /* 338 */ { "CURRENT_ROLE", 12, true, false}, /* 339 */ { "CURRENT_USER", 12, true, false}, /* 340 */ { "CURSOR", 6, true, false}, /* 341 */ { "CURTIME", 7, true, false}, /* 342 */ { "SCHEMA", 6, true, false}, /* 343 */ { "SCHEMAS", 7, true, false}, /* 344 */ { "DATE_ADD", 8, true, false}, /* 345 */ { "DATE_SUB", 8, true, false}, /* 346 */ { "DAY_HOUR", 8, true, false}, /* 347 */ { "DAY_MICROSECOND", 15, true, false}, /* 348 */ { "DAY_MINUTE", 10, true, false}, /* 349 */ { "DAY_SECOND", 10, true, false}, /* 350 */ { "DECIMAL", 7, true, false}, /* 351 */ { "DECLARE", 7, true, false}, /* 352 */ { "(unknown)", 9, true, false}, /* 353 */ { "DEFAULT", 7, true, true}, /* 354 */ { "DELETE_DOMAIN_ID", 16, true, false}, /* 355 */ { "DELETE", 6, true, false}, /* 356 */ { "DENSE_RANK", 10, true, false}, /* 357 */ { "EXPLAIN", 7, true, false}, /* 358 */ { "DESC", 4, true, false}, /* 359 */ { "DETERMINISTIC", 13, true, false}, /* 360 */ { "DISTINCTROW", 11, true, false}, /* 361 */ { "DIV", 3, true, true}, /* 362 */ { "DO_DOMAIN_IDS", 13, true, false}, /* 363 */ { "FLOAT8", 6, true, false}, /* 364 */ { "DROP", 4, true, false}, /* 365 */ { "DUAL", 4, true, false}, /* 366 */ { "EACH", 4, true, false}, /* 367 */ { "ELSEIF", 6, true, true}, /* 368 */ { "ELSE", 4, true, false}, /* 369 */ { "(unknown)", 9, true, false}, /* 370 */ { "EMPTY", 5, true, false}, /* 371 */ { "ENCLOSED", 8, true, false}, /* 372 */ { "ESCAPED", 7, true, false}, /* 373 */ { "EXCEPT", 6, true, false}, /* 374 */ { "EXISTS", 6, true, false}, /* 375 */ { "EXTRACT", 7, true, false}, /* 376 */ { "FALSE", 5, true, false}, /* 377 */ { "FETCH", 5, true, false}, /* 378 */ { "FIRST_VALUE", 11, true, false}, /* 379 */ { "FLOAT4", 6, true, false}, /* 380 */ { "FOREIGN", 7, true, false}, /* 381 */ { "FOR", 3, true, false}, /* 382 */ { "FROM", 4, true, false}, /* 383 */ { "FULLTEXT", 8, true, false}, /* 384 */ { "(unknown)", 9, true, false}, /* 385 */ { "GRANT", 5, true, false}, /* 386 */ { "GROUP_CONCAT", 12, true, false}, /* 387 */ { "JSON_ARRAYAGG", 13, true, false}, /* 388 */ { "JSON_OBJECTAGG", 14, true, false}, /* 389 */ { "JSON_TABLE", 10, true, false}, /* 390 */ { "GROUP", 5, true, false}, /* 391 */ { "HAVING", 6, true, false}, /* 392 */ { "HOUR_MICROSECOND", 16, true, false}, /* 393 */ { "HOUR_MINUTE", 11, true, false}, /* 394 */ { "HOUR_SECOND", 11, true, false}, /* 395 */ { "IF", 2, true, true}, /* 396 */ { "IGNORE_DOMAIN_IDS", 17, true, false}, /* 397 */ { "IGNORE", 6, true, false}, /* 398 */ { "IGNORED", 7, true, false}, /* 399 */ { "INDEX", 5, true, false}, /* 400 */ { "INFILE", 6, true, false}, /* 401 */ { "INNER", 5, true, false}, /* 402 */ { "INOUT", 5, true, false}, /* 403 */ { "INSENSITIVE", 11, true, false}, /* 404 */ { "INSERT", 6, true, false}, /* 405 */ { "IN", 2, true, false}, /* 406 */ { "INTERSECT", 9, true, false}, /* 407 */ { "INTERVAL", 8, true, true}, /* 408 */ { "INTO", 4, true, false}, /* 409 */ { "INTEGER", 7, true, false}, /* 410 */ { "IS", 2, true, false}, /* 411 */ { "ITERATE", 7, true, false}, /* 412 */ { "JOIN", 4, true, false}, /* 413 */ { "KEYS", 4, true, false}, /* 414 */ { "KEY", 3, true, false}, /* 415 */ { "KILL", 4, true, false}, /* 416 */ { "LAG", 3, true, false}, /* 417 */ { "LEADING", 7, true, false}, /* 418 */ { "LEAD", 4, true, false}, /* 419 */ { "LEAVE", 5, true, false}, /* 420 */ { "LEFT", 4, true, false}, /* 421 */ { "LIKE", 4, true, true}, /* 422 */ { "LIMIT", 5, true, false}, /* 423 */ { "LINEAR", 6, true, false}, /* 424 */ { "LINES", 5, true, false}, /* 425 */ { "LOAD", 4, true, false}, /* 426 */ { "LOCATOR", 7, true, false}, /* 427 */ { "LOCK", 4, true, false}, /* 428 */ { "LONGBLOB", 8, true, false}, /* 429 */ { "LONG", 4, true, false}, /* 430 */ { "LONGTEXT", 8, true, false}, /* 431 */ { "LOOP", 4, true, false}, /* 432 */ { "LOW_PRIORITY", 12, true, false}, /* 433 */ { "MASTER_SSL_VERIFY_SERVER_CERT", 29, true, false}, /* 434 */ { "MATCH", 5, true, false}, /* 435 */ { "MAX", 3, true, false}, /* 436 */ { "MAXVALUE", 8, true, false}, /* 437 */ { "MEDIAN", 6, true, false}, /* 438 */ { "MEDIUMBLOB", 10, true, false}, /* 439 */ { "MIDDLEINT", 9, true, false}, /* 440 */ { "MEDIUMTEXT", 10, true, false}, /* 441 */ { "MIN", 3, true, false}, /* 442 */ { "MINUS", 5, true, false}, /* 443 */ { "MINUTE_MICROSECOND", 18, true, false}, /* 444 */ { "MINUTE_SECOND", 13, true, false}, /* 445 */ { "MODIFIES", 8, true, false}, /* 446 */ { "MOD", 3, true, true}, /* 447 */ { "NATURAL", 7, true, false}, /* 448 */ { "~", 1, true, false}, /* 449 */ { "NESTED", 6, true, false}, /* 450 */ { "NOT", 3, true, true}, /* 451 */ { "NO_WRITE_TO_BINLOG", 18, true, false}, /* 452 */ { "NOW", 3, true, false}, /* 453 */ { "NTH_VALUE", 9, true, false}, /* 454 */ { "NTILE", 5, true, false}, /* 455 */ { "NULL", 4, true, false}, /* 456 */ { "NUMERIC", 7, true, false}, /* 457 */ { "ON", 2, true, false}, /* 458 */ { "OPTIMIZE", 8, true, false}, /* 459 */ { "OPTIONALLY", 10, true, false}, /* 460 */ { "ORDER", 5, true, false}, /* 461 */ { "ORDINALITY", 10, true, false}, /* 462 */ { "OR", 2, true, true}, /* 463 */ { "(unknown)", 9, true, false}, /* 464 */ { "OUTER", 5, true, false}, /* 465 */ { "OUTFILE", 7, true, false}, /* 466 */ { "OUT", 3, true, false}, /* 467 */ { "OVER", 4, true, false}, /* 468 */ { "(unknown)", 9, true, false}, /* 469 */ { "PAGE_CHECKSUM", 13, true, false}, /* 470 */ { "PARSE_VCOL_EXPR", 15, true, false}, /* 471 */ { "PARTITION", 9, true, false}, /* 472 */ { "PATH", 4, true, false}, /* 473 */ { "PERCENTILE_CONT", 15, true, false}, /* 474 */ { "PERCENTILE_DISC", 15, true, false}, /* 475 */ { "PERCENT_RANK", 12, true, false}, /* 476 */ { "PORTION", 7, true, false}, /* 477 */ { "POSITION", 8, true, false}, /* 478 */ { "PRECISION", 9, true, false}, /* 479 */ { "PRIMARY", 7, true, false}, /* 480 */ { "PROCEDURE", 9, true, false}, /* 481 */ { "PURGE", 5, true, false}, /* 482 */ { "(unknown)", 9, true, false}, /* 483 */ { "RANGE", 5, true, false}, /* 484 */ { "RANK", 4, true, false}, /* 485 */ { "READS", 5, true, false}, /* 486 */ { "READ", 4, true, false}, /* 487 */ { "READ_WRITE", 10, true, false}, /* 488 */ { "REAL", 4, true, false}, /* 489 */ { "RECURSIVE", 9, true, false}, /* 490 */ { "REFERENCES", 10, true, false}, /* 491 */ { "REF_SYSTEM_ID", 13, true, false}, /* 492 */ { "RLIKE", 5, true, true}, /* 493 */ { "RELEASE", 7, true, false}, /* 494 */ { "RENAME", 6, true, false}, /* 495 */ { "REPEAT", 6, true, false}, /* 496 */ { "REQUIRE", 7, true, false}, /* 497 */ { "RESIGNAL", 8, true, false}, /* 498 */ { "RESTRICT", 8, true, false}, /* 499 */ { "RETURNING", 9, true, false}, /* 500 */ { "RETURN", 6, true, true}, /* 501 */ { "(unknown)", 9, true, true}, /* 502 */ { "REVOKE", 6, true, false}, /* 503 */ { "RIGHT", 5, true, false}, /* 504 */ { "ROW_NUMBER", 10, true, false}, /* 505 */ { "ROWS", 4, true, false}, /* 506 */ { "(unknown)", 9, true, false}, /* 507 */ { "SECOND_MICROSECOND", 18, true, false}, /* 508 */ { "SELECT", 6, true, true}, /* 509 */ { "SENSITIVE", 9, true, false}, /* 510 */ { "SEPARATOR", 9, true, false}, /* 511 */ { "SERVER_OPTIONS", 14, true, false}, /* 512 */ { "SET", 3, true, false}, /* 513 */ { "SHOW", 4, true, false}, /* 514 */ { "SIGNAL", 6, true, false}, /* 515 */ { "SMALLINT", 8, true, false}, /* 516 */ { "SPATIAL", 7, true, false}, /* 517 */ { "SPECIFIC", 8, true, false}, /* 518 */ { "SQL_BIG_RESULT", 14, true, false}, /* 519 */ { "SQLEXCEPTION", 12, true, false}, /* 520 */ { "SQL_SMALL_RESULT", 16, true, false}, /* 521 */ { "SQLSTATE", 8, true, false}, /* 522 */ { "SQL", 3, true, false}, /* 523 */ { "SQLWARNING", 10, true, false}, /* 524 */ { "SSL", 3, true, false}, /* 525 */ { "STARTING", 8, true, false}, /* 526 */ { "STATS_AUTO_RECALC", 17, true, false}, /* 527 */ { "STATS_PERSISTENT", 16, true, false}, /* 528 */ { "STATS_SAMPLE_PAGES", 18, true, false}, /* 529 */ { "STDDEV_SAMP", 11, true, false}, /* 530 */ { "STDDEV_POP", 10, true, false}, /* 531 */ { "STRAIGHT_JOIN", 13, true, false}, /* 532 */ { "SUM", 3, true, false}, /* 533 */ { "SYSDATE", 7, true, false}, /* 534 */ { "TABLE_REF_PRIORITY", 18, true, false}, /* 535 */ { "TABLE", 5, true, false}, /* 536 */ { "TERMINATED", 10, true, false}, /* 537 */ { "THEN", 4, true, false}, /* 538 */ { "TINYBLOB", 8, true, false}, /* 539 */ { "TINYINT", 7, true, false}, /* 540 */ { "TINYTEXT", 8, true, false}, /* 541 */ { "TO", 2, true, false}, /* 542 */ { "TRAILING", 8, true, false}, /* 543 */ { "TRIGGER", 7, true, false}, /* 544 */ { "TRUE", 4, true, false}, /* 545 */ { "UNDO", 4, true, false}, /* 546 */ { "UNION", 5, true, false}, /* 547 */ { "UNIQUE", 6, true, false}, /* 548 */ { "UNLOCK", 6, true, false}, /* 549 */ { "UNSIGNED", 8, true, false}, /* 550 */ { "UPDATE", 6, true, false}, /* 551 */ { "USAGE", 5, true, false}, /* 552 */ { "USE", 3, true, false}, /* 553 */ { "USING", 5, true, false}, /* 554 */ { "UTC_DATE", 8, true, false}, /* 555 */ { "UTC_TIMESTAMP", 13, true, false}, /* 556 */ { "UTC_TIME", 8, true, false}, /* 557 */ { "VALUES IN", 9, true, false}, /* 558 */ { "VALUES LESS", 11, true, false}, /* 559 */ { "VALUES", 6, true, false}, /* 560 */ { "VARBINARY", 9, true, false}, /* 561 */ { "VARCHARACTER", 12, true, false}, /* 562 */ { "VAR_POP", 7, true, false}, /* 563 */ { "VAR_SAMP", 8, true, false}, /* 564 */ { "VARYING", 7, true, false}, /* 565 */ { "WHEN", 4, true, true}, /* 566 */ { "WHERE", 5, true, false}, /* 567 */ { "WHILE", 5, true, true}, /* 568 */ { "WITH", 4, true, false}, /* 569 */ { "XOR", 3, true, true}, /* 570 */ { "YEAR_MONTH", 10, true, false}, /* 571 */ { "ZEROFILL", 8, true, false}, /* 572 */ { "BODY", 4, true, false}, /* 573 */ { "(unknown)", 9, true, true}, /* 574 */ { "ELSIF", 5, true, false}, /* 575 */ { "(unknown)", 9, true, false}, /* 576 */ { "GOTO", 4, true, false}, /* 577 */ { "OTHERS", 6, true, false}, /* 578 */ { "PACKAGE", 7, true, false}, /* 579 */ { "RAISE", 5, true, false}, /* 580 */ { "ROWTYPE", 7, true, false}, /* 581 */ { "ROWNUM", 6, true, false}, /* 582 */ { "REPLACE", 7, true, false}, /* 583 */ { "SUBSTRING", 9, true, false}, /* 584 */ { "TRIM", 4, true, false}, /* 585 */ { "ACCOUNT", 7, true, false}, /* 586 */ { "ACTION", 6, true, false}, /* 587 */ { "ADMIN", 5, true, false}, /* 588 */ { "ADDDATE", 7, true, false}, /* 589 */ { "AFTER", 5, true, false}, /* 590 */ { "AGAINST", 7, true, false}, /* 591 */ { "AGGREGATE", 9, true, false}, /* 592 */ { "ALGORITHM", 9, true, false}, /* 593 */ { "ALWAYS", 6, true, false}, /* 594 */ { "SOME", 4, true, false}, /* 595 */ { "ASCII", 5, true, false}, /* 596 */ { "AT", 2, true, true}, /* 597 */ { "ATOMIC", 6, true, false}, /* 598 */ { "AUTHORS", 7, true, false}, /* 599 */ { "AUTOEXTEND_SIZE", 15, true, false}, /* 600 */ { "AUTO_INCREMENT", 14, true, false}, /* 601 */ { "AVG_ROW_LENGTH", 14, true, false}, /* 602 */ { "AVG", 3, true, false}, /* 603 */ { "BACKUP", 6, true, false}, /* 604 */ { "BEGIN", 5, true, false}, /* 605 */ { "(unknown)", 9, true, false}, /* 606 */ { "BINLOG", 6, true, false}, /* 607 */ { "BIT", 3, true, false}, /* 608 */ { "BLOCK", 5, true, false}, /* 609 */ { "BOOL", 4, true, false}, /* 610 */ { "BOOLEAN", 7, true, false}, /* 611 */ { "BTREE", 5, true, false}, /* 612 */ { "BYTE", 4, true, false}, /* 613 */ { "CACHE", 5, true, false}, /* 614 */ { "CASCADED", 8, true, false}, /* 615 */ { "CATALOG_NAME", 12, true, false}, /* 616 */ { "CHAIN", 5, true, false}, /* 617 */ { "CHANGED", 7, true, false}, /* 618 */ { "CHARSET", 7, true, false}, /* 619 */ { "CHECKPOINT", 10, true, false}, /* 620 */ { "CHECKSUM", 8, true, false}, /* 621 */ { "CIPHER", 6, true, false}, /* 622 */ { "CLASS_ORIGIN", 12, true, false}, /* 623 */ { "CLIENT", 6, true, false}, /* 624 */ { "CLOB", 4, true, false}, /* 625 */ { "(unknown)", 9, true, false}, /* 626 */ { "CLOSE", 5, true, false}, /* 627 */ { "COALESCE", 8, true, false}, /* 628 */ { "CODE", 4, true, false}, /* 629 */ { "COLLATION", 9, true, false}, /* 630 */ { "FIELDS", 6, true, false}, /* 631 */ { "COLUMN_ADD", 10, true, false}, /* 632 */ { "COLUMN_CHECK", 12, true, false}, /* 633 */ { "COLUMN_CREATE", 13, true, false}, /* 634 */ { "COLUMN_DELETE", 13, true, false}, /* 635 */ { "COLUMN_GET", 10, true, false}, /* 636 */ { "COLUMN", 6, true, false}, /* 637 */ { "COLUMN_NAME", 11, true, false}, /* 638 */ { "COMMENT", 7, true, false}, /* 639 */ { "COMMITTED", 9, true, false}, /* 640 */ { "COMMIT", 6, true, false}, /* 641 */ { "COMPACT", 7, true, false}, /* 642 */ { "COMPLETION", 10, true, false}, /* 643 */ { "COMPRESSED", 10, true, false}, /* 644 */ { "CONCURRENT", 10, true, false}, /* 645 */ { "CONNECTION", 10, true, false}, /* 646 */ { "CONSISTENT", 10, true, false}, /* 647 */ { "CONSTRAINT_CATALOG", 18, true, false}, /* 648 */ { "CONSTRAINT_NAME", 15, true, false}, /* 649 */ { "CONSTRAINT_SCHEMA", 17, true, false}, /* 650 */ { "CONTAINS", 8, true, false}, /* 651 */ { "CONTEXT", 7, true, false}, /* 652 */ { "CONTRIBUTORS", 12, true, false}, /* 653 */ { "CPU", 3, true, false}, /* 654 */ { "CUBE", 4, true, false}, /* 655 */ { "CURRENT", 7, true, false}, /* 656 */ { "CURRENT_POS", 11, true, false}, /* 657 */ { "CURSOR_NAME", 11, true, false}, /* 658 */ { "CYCLE", 5, true, false}, /* 659 */ { "DATAFILE", 8, true, false}, /* 660 */ { "DATA", 4, true, false}, /* 661 */ { "DATETIME", 8, true, false}, /* 662 */ { "DATE", 4, true, false}, /* 663 */ { "SQL_TSI_DAY", 11, true, false}, /* 664 */ { "DEALLOCATE", 10, true, false}, /* 665 */ { "DEFINER", 7, true, false}, /* 666 */ { "DELAYED", 7, true, false}, /* 667 */ { "DELAY_KEY_WRITE", 15, true, false}, /* 668 */ { "DES_KEY_FILE", 12, true, false}, /* 669 */ { "DIAGNOSTICS", 11, true, false}, /* 670 */ { "DIRECTORY", 9, true, false}, /* 671 */ { "DISABLE", 7, true, false}, /* 672 */ { "DISCARD", 7, true, false}, /* 673 */ { "DISK", 4, true, false}, /* 674 */ { "DO", 2, true, false}, /* 675 */ { "DUMPFILE", 8, true, false}, /* 676 */ { "DUPLICATE", 9, true, false}, /* 677 */ { "DYNAMIC", 7, true, false}, /* 678 */ { "ENABLE", 6, true, false}, /* 679 */ { "END", 3, true, false}, /* 680 */ { "ENDS", 4, true, true}, /* 681 */ { "ENGINES", 7, true, false}, /* 682 */ { "ENGINE", 6, true, false}, /* 683 */ { "ENUM", 4, true, false}, /* 684 */ { "ERROR", 5, true, false}, /* 685 */ { "ERRORS", 6, true, false}, /* 686 */ { "ESCAPE", 6, true, false}, /* 687 */ { "EVENTS", 6, true, false}, /* 688 */ { "EVENT", 5, true, false}, /* 689 */ { "EVERY", 5, true, true}, /* 690 */ { "EXCHANGE", 8, true, false}, /* 691 */ { "EXAMINED", 8, true, false}, /* 692 */ { "EXCLUDE", 7, true, false}, /* 693 */ { "EXECUTE", 7, true, false}, /* 694 */ { "EXCEPTION", 9, true, false}, /* 695 */ { "EXIT", 4, true, false}, /* 696 */ { "(unknown)", 9, true, false}, /* 697 */ { "EXPANSION", 9, true, false}, /* 698 */ { "EXPIRE", 6, true, false}, /* 699 */ { "EXPORT", 6, true, false}, /* 700 */ { "EXTENDED", 8, true, false}, /* 701 */ { "EXTENT_SIZE", 11, true, false}, /* 702 */ { "FAST", 4, true, false}, /* 703 */ { "FAULTS", 6, true, false}, /* 704 */ { "FEDERATED", 9, true, false}, /* 705 */ { "FILE", 4, true, false}, /* 706 */ { "FIRST", 5, true, false}, /* 707 */ { "FIXED", 5, true, false}, /* 708 */ { "FLUSH", 5, true, false}, /* 709 */ { "FOLLOWS", 7, true, false}, /* 710 */ { "FOLLOWING", 9, true, false}, /* 711 */ { "FORCE", 5, true, false}, /* 712 */ { "FORMAT", 6, true, false}, /* 713 */ { "FOUND", 5, true, false}, /* 714 */ { "FULL", 4, true, false}, /* 715 */ { "FUNCTION", 8, true, false}, /* 716 */ { "GENERAL", 7, true, false}, /* 717 */ { "GENERATED", 9, true, false}, /* 718 */ { "GET_FORMAT", 10, true, false}, /* 719 */ { "GET", 3, true, false}, /* 720 */ { "GLOBAL", 6, true, false}, /* 721 */ { "GRANTS", 6, true, false}, /* 722 */ { "HANDLER", 7, true, false}, /* 723 */ { "HARD", 4, true, false}, /* 724 */ { "HASH", 4, true, false}, /* 725 */ { "HELP", 4, true, false}, /* 726 */ { "HIGH_PRIORITY", 13, true, false}, /* 727 */ { "HISTORY", 7, true, false}, /* 728 */ { "HOST", 4, true, false}, /* 729 */ { "HOSTS", 5, true, false}, /* 730 */ { "SQL_TSI_HOUR", 12, true, false}, /* 731 */ { "ID", 2, true, false}, /* 732 */ { "IDENTIFIED", 10, true, false}, /* 733 */ { "IGNORE_SERVER_IDS", 17, true, false}, /* 734 */ { "IMMEDIATE", 9, true, false}, /* 735 */ { "IMPORT", 6, true, false}, /* 736 */ { "INCREMENT", 9, true, false}, /* 737 */ { "INDEXES", 7, true, false}, /* 738 */ { "INITIAL_SIZE", 12, true, false}, /* 739 */ { "INSERT_METHOD", 13, true, false}, /* 740 */ { "INSTALL", 7, true, false}, /* 741 */ { "INVOKER", 7, true, false}, /* 742 */ { "IO", 2, true, false}, /* 743 */ { "IPC", 3, true, false}, /* 744 */ { "ISOLATION", 9, true, false}, /* 745 */ { "ISOPEN", 6, true, false}, /* 746 */ { "ISSUER", 6, true, false}, /* 747 */ { "INVISIBLE", 9, true, false}, /* 748 */ { "JSON", 4, true, false}, /* 749 */ { "KEY_BLOCK_SIZE", 14, true, false}, /* 750 */ { "LANGUAGE", 8, true, false}, /* 751 */ { "LAST", 4, true, false}, /* 752 */ { "LAST_VALUE", 10, true, false}, /* 753 */ { "LASTVAL", 7, true, false}, /* 754 */ { "LEAVES", 6, true, false}, /* 755 */ { "LESS", 4, true, false}, /* 756 */ { "LEVEL", 5, true, false}, /* 757 */ { "LIST", 4, true, false}, /* 758 */ { "LOCAL", 5, true, false}, /* 759 */ { "LOCKED", 6, true, false}, /* 760 */ { "LOCKS", 5, true, false}, /* 761 */ { "LOGFILE", 7, true, false}, /* 762 */ { "LOGS", 4, true, false}, /* 763 */ { "MASTER_CONNECT_RETRY", 20, true, false}, /* 764 */ { "MASTER_DELAY", 12, true, false}, /* 765 */ { "MASTER_GTID_POS", 15, true, false}, /* 766 */ { "MASTER_HOST", 11, true, false}, /* 767 */ { "MASTER_LOG_FILE", 15, true, false}, /* 768 */ { "MASTER_LOG_POS", 14, true, false}, /* 769 */ { "MASTER_PASSWORD", 15, true, false}, /* 770 */ { "MASTER_PORT", 11, true, false}, /* 771 */ { "MASTER_SERVER_ID", 16, true, false}, /* 772 */ { "MASTER_SSL_CAPATH", 17, true, false}, /* 773 */ { "MASTER_SSL_CA", 13, true, false}, /* 774 */ { "MASTER_SSL_CERT", 15, true, false}, /* 775 */ { "MASTER_SSL_CIPHER", 17, true, false}, /* 776 */ { "MASTER_SSL_CRL", 14, true, false}, /* 777 */ { "MASTER_SSL_CRLPATH", 18, true, false}, /* 778 */ { "MASTER_SSL_KEY", 14, true, false}, /* 779 */ { "MASTER_SSL", 10, true, false}, /* 780 */ { "MASTER", 6, true, false}, /* 781 */ { "MASTER_USER", 11, true, false}, /* 782 */ { "MASTER_USE_GTID", 15, true, false}, /* 783 */ { "MASTER_HEARTBEAT_PERIOD", 23, true, false}, /* 784 */ { "MAX_CONNECTIONS_PER_HOUR", 24, true, false}, /* 785 */ { "MAX_QUERIES_PER_HOUR", 20, true, false}, /* 786 */ { "MAX_ROWS", 8, true, false}, /* 787 */ { "MAX_SIZE", 8, true, false}, /* 788 */ { "MAX_UPDATES_PER_HOUR", 20, true, false}, /* 789 */ { "MAX_STATEMENT_TIME", 18, true, false}, /* 790 */ { "MAX_USER_CONNECTIONS", 20, true, false}, /* 791 */ { "MEDIUM", 6, true, false}, /* 792 */ { "MEMORY", 6, true, false}, /* 793 */ { "MERGE", 5, true, false}, /* 794 */ { "MESSAGE_TEXT", 12, true, false}, /* 795 */ { "MICROSECOND", 11, true, false}, /* 796 */ { "MIGRATE", 7, true, false}, /* 797 */ { "SQL_TSI_MINUTE", 14, true, false}, /* 798 */ { "MINVALUE", 8, true, false}, /* 799 */ { "MIN_ROWS", 8, true, false}, /* 800 */ { "MODE", 4, true, false}, /* 801 */ { "MODIFY", 6, true, false}, /* 802 */ { "MONITOR", 7, true, false}, /* 803 */ { "SQL_TSI_MONTH", 13, true, false}, /* 804 */ { "MUTEX", 5, true, false}, /* 805 */ { "MYSQL", 5, true, false}, /* 806 */ { "MYSQL_ERRNO", 11, true, false}, /* 807 */ { "NAMES", 5, true, false}, /* 808 */ { "NAME", 4, true, false}, /* 809 */ { "NATIONAL", 8, true, false}, /* 810 */ { "NCHAR", 5, true, false}, /* 811 */ { "NEVER", 5, true, false}, /* 812 */ { "NEXT", 4, true, false}, /* 813 */ { "NEXTVAL", 7, true, false}, /* 814 */ { "NOCACHE", 7, true, false}, /* 815 */ { "NOCYCLE", 7, true, false}, /* 816 */ { "NODEGROUP", 9, true, false}, /* 817 */ { "NONE", 4, true, false}, /* 818 */ { "NOTFOUND", 8, true, false}, /* 819 */ { "NO", 2, true, false}, /* 820 */ { "NOMAXVALUE", 10, true, false}, /* 821 */ { "NOMINVALUE", 10, true, false}, /* 822 */ { "NO_WAIT", 7, true, false}, /* 823 */ { "NOWAIT", 6, true, false}, /* 824 */ { "NUMBER", 6, true, false}, /* 825 */ { "(unknown)", 9, true, false}, /* 826 */ { "NVARCHAR", 8, true, false}, /* 827 */ { "OF", 2, true, false}, /* 828 */ { "OFFSET", 6, true, false}, /* 829 */ { "OLD_PASSWORD", 12, true, false}, /* 830 */ { "ONE", 3, true, false}, /* 831 */ { "ONLY", 4, true, false}, /* 832 */ { "ONLINE", 6, true, false}, /* 833 */ { "OPEN", 4, true, false}, /* 834 */ { "OPTIONS", 7, true, false}, /* 835 */ { "OPTION", 6, true, false}, /* 836 */ { "OVERLAPS", 8, true, false}, /* 837 */ { "OWNER", 5, true, false}, /* 838 */ { "PACK_KEYS", 9, true, false}, /* 839 */ { "PAGE", 4, true, false}, /* 840 */ { "PARSER", 6, true, false}, /* 841 */ { "PARTIAL", 7, true, false}, /* 842 */ { "PARTITIONS", 10, true, false}, /* 843 */ { "PARTITIONING", 12, true, false}, /* 844 */ { "PASSWORD", 8, true, false}, /* 845 */ { "PERIOD", 6, true, false}, /* 846 */ { "PERSISTENT", 10, true, false}, /* 847 */ { "PHASE", 5, true, false}, /* 848 */ { "PLUGINS", 7, true, false}, /* 849 */ { "PLUGIN", 6, true, false}, /* 850 */ { "PORT", 4, true, false}, /* 851 */ { "PRECEDES", 8, true, false}, /* 852 */ { "PRECEDING", 9, true, false}, /* 853 */ { "PREPARE", 7, true, false}, /* 854 */ { "PRESERVE", 8, true, false}, /* 855 */ { "PREV", 4, true, false}, /* 856 */ { "PREVIOUS", 8, true, false}, /* 857 */ { "PRIVILEGES", 10, true, false}, /* 858 */ { "PROCESS", 7, true, false}, /* 859 */ { "PROCESSLIST", 11, true, false}, /* 860 */ { "PROFILE", 7, true, false}, /* 861 */ { "PROFILES", 8, true, false}, /* 862 */ { "PROXY", 5, true, false}, /* 863 */ { "SQL_TSI_QUARTER", 15, true, false}, /* 864 */ { "QUERY", 5, true, false}, /* 865 */ { "QUICK", 5, true, false}, /* 866 */ { "RAW", 3, true, false}, /* 867 */ { "(unknown)", 9, true, false}, /* 868 */ { "READ_ONLY", 9, true, false}, /* 869 */ { "REBUILD", 7, true, false}, /* 870 */ { "RECOVER", 7, true, false}, /* 871 */ { "REDOFILE", 8, true, false}, /* 872 */ { "REDO_BUFFER_SIZE", 16, true, false}, /* 873 */ { "REDUNDANT", 9, true, false}, /* 874 */ { "RELAY", 5, true, false}, /* 875 */ { "RELAYLOG", 8, true, false}, /* 876 */ { "RELAY_LOG_FILE", 14, true, false}, /* 877 */ { "RELAY_LOG_POS", 13, true, false}, /* 878 */ { "RELAY_THREAD", 12, true, false}, /* 879 */ { "RELOAD", 6, true, false}, /* 880 */ { "REMOVE", 6, true, false}, /* 881 */ { "REORGANIZE", 10, true, false}, /* 882 */ { "REPAIR", 6, true, false}, /* 883 */ { "REPEATABLE", 10, true, false}, /* 884 */ { "REPLAY", 6, true, false}, /* 885 */ { "REPLICATION", 11, true, false}, /* 886 */ { "RESET", 5, true, false}, /* 887 */ { "RESTART", 7, true, false}, /* 888 */ { "USER_RESOURCES", 14, true, false}, /* 889 */ { "RESTORE", 7, true, false}, /* 890 */ { "RESUME", 6, true, false}, /* 891 */ { "RETURNED_SQLSTATE", 17, true, false}, /* 892 */ { "RETURNS", 7, true, false}, /* 893 */ { "REUSE", 5, true, false}, /* 894 */ { "REVERSE", 7, true, false}, /* 895 */ { "ROLE", 4, true, false}, /* 896 */ { "ROLLBACK", 8, true, false}, /* 897 */ { "ROLLUP", 6, true, false}, /* 898 */ { "ROUTINE", 7, true, false}, /* 899 */ { "ROWCOUNT", 8, true, false}, /* 900 */ { "ROW", 3, true, false}, /* 901 */ { "ROW_COUNT", 9, true, false}, /* 902 */ { "ROW_FORMAT", 10, true, false}, /* 903 */ { "RTREE", 5, true, false}, /* 904 */ { "SAVEPOINT", 9, true, false}, /* 905 */ { "SCHEDULE", 8, true, false}, /* 906 */ { "SCHEMA_NAME", 11, true, false}, /* 907 */ { "SQL_TSI_SECOND", 14, true, false}, /* 908 */ { "SECURITY", 8, true, false}, /* 909 */ { "SEQUENCE", 8, true, false}, /* 910 */ { "SERIALIZABLE", 12, true, false}, /* 911 */ { "SERIAL", 6, true, false}, /* 912 */ { "SESSION", 7, true, false}, /* 913 */ { "SERVER", 6, true, false}, /* 914 */ { "SETVAL", 6, true, false}, /* 915 */ { "SHARE", 5, true, false}, /* 916 */ { "SHUTDOWN", 8, true, false}, /* 917 */ { "SIGNED", 6, true, false}, /* 918 */ { "SIMPLE", 6, true, false}, /* 919 */ { "SKIP", 4, true, false}, /* 920 */ { "SLAVE", 5, true, false}, /* 921 */ { "SLAVES", 6, true, false}, /* 922 */ { "SLAVE_POS", 9, true, false}, /* 923 */ { "SLOW", 4, true, false}, /* 924 */ { "SNAPSHOT", 8, true, false}, /* 925 */ { "SOCKET", 6, true, false}, /* 926 */ { "SOFT", 4, true, false}, /* 927 */ { "SONAME", 6, true, false}, /* 928 */ { "SOUNDS", 6, true, false}, /* 929 */ { "SOURCE", 6, true, false}, /* 930 */ { "SQL_BUFFER_RESULT", 17, true, false}, /* 931 */ { "SQL_CACHE", 9, true, false}, /* 932 */ { "SQL_CALC_FOUND_ROWS", 19, true, false}, /* 933 */ { "SQL_NO_CACHE", 12, true, false}, /* 934 */ { "SQL_THREAD", 10, true, false}, /* 935 */ { "STAGE", 5, true, false}, /* 936 */ { "STARTS", 6, true, true}, /* 937 */ { "START", 5, true, false}, /* 938 */ { "STATEMENT", 9, true, false}, /* 939 */ { "STATUS", 6, true, false}, /* 940 */ { "STOP", 4, true, false}, /* 941 */ { "STORAGE", 7, true, false}, /* 942 */ { "STORED", 6, true, false}, /* 943 */ { "STRING", 6, true, false}, /* 944 */ { "SUBCLASS_ORIGIN", 15, true, false}, /* 945 */ { "SUBDATE", 7, true, false}, /* 946 */ { "SUBJECT", 7, true, false}, /* 947 */ { "SUBPARTITIONS", 13, true, false}, /* 948 */ { "SUBPARTITION", 12, true, false}, /* 949 */ { "SUPER", 5, true, false}, /* 950 */ { "SUSPEND", 7, true, false}, /* 951 */ { "SWAPS", 5, true, false}, /* 952 */ { "SWITCHES", 8, true, false}, /* 953 */ { "SYSTEM", 6, true, false}, /* 954 */ { "SYSTEM_TIME", 11, true, false}, /* 955 */ { "TABLES", 6, true, false}, /* 956 */ { "TABLESPACE", 10, true, false}, /* 957 */ { "TABLE_CHECKSUM", 14, true, false}, /* 958 */ { "TABLE_NAME", 10, true, false}, /* 959 */ { "TEMPORARY", 9, true, false}, /* 960 */ { "TEMPTABLE", 9, true, false}, /* 961 */ { "TEXT", 4, true, false}, /* 962 */ { "THAN", 4, true, false}, /* 963 */ { "TIES", 4, true, false}, /* 964 */ { "TIMESTAMP", 9, true, false}, /* 965 */ { "TIMESTAMPADD", 12, true, false}, /* 966 */ { "TIMESTAMPDIFF", 13, true, false}, /* 967 */ { "TIME", 4, true, false}, /* 968 */ { "TRANSACTION", 11, true, false}, /* 969 */ { "TRANSACTIONAL", 13, true, false}, /* 970 */ { "THREADS", 7, true, false}, /* 971 */ { "TRIGGERS", 8, true, false}, /* 972 */ { "TRIM_ORACLE", 11, true, false}, /* 973 */ { "TRUNCATE", 8, true, false}, /* 974 */ { "TYPE", 4, true, false}, /* 975 */ { "UDF_RETURNS", 11, true, false}, /* 976 */ { "UNBOUNDED", 9, true, false}, /* 977 */ { "UNCOMMITTED", 11, true, false}, /* 978 */ { "UNDEFINED", 9, true, false}, /* 979 */ { "UNDOFILE", 8, true, false}, /* 980 */ { "UNDO_BUFFER_SIZE", 16, true, false}, /* 981 */ { "UNICODE", 7, true, false}, /* 982 */ { "UNINSTALL", 9, true, false}, /* 983 */ { "UNKNOWN", 7, true, false}, /* 984 */ { "UNTIL", 5, true, true}, /* 985 */ { "UPGRADE", 7, true, false}, /* 986 */ { "SYSTEM_USER", 11, true, false}, /* 987 */ { "USE_FRM", 7, true, false}, /* 988 */ { "VALUE", 5, true, false}, /* 989 */ { "VARCHAR2", 8, true, false}, /* 990 */ { "(unknown)", 9, true, false}, /* 991 */ { "VARIABLES", 9, true, false}, /* 992 */ { "VERSIONING", 10, true, false}, /* 993 */ { "VIA", 3, true, false}, /* 994 */ { "VIEW", 4, true, false}, /* 995 */ { "VISIBLE", 7, true, false}, /* 996 */ { "VIRTUAL", 7, true, false}, /* 997 */ { "WAIT", 4, true, false}, /* 998 */ { "WARNINGS", 8, true, false}, /* 999 */ { "WEEK", 4, true, false}, /* 1000 */ { "WEIGHT_STRING", 13, true, false}, /* 1001 */ { "WINDOW", 6, true, false}, /* 1002 */ { "WITHIN", 6, true, false}, /* 1003 */ { "WITHOUT", 7, true, false}, /* 1004 */ { "WORK", 4, true, false}, /* 1005 */ { "WRAPPER", 7, true, false}, /* 1006 */ { "WRITE", 5, true, false}, /* 1007 */ { "X509", 4, true, false}, /* 1008 */ { "XA", 2, true, false}, /* 1009 */ { "XML", 3, true, false}, /* 1010 */ { "YEAR", 4, true, false}, /* 1011 */ { "?", 1, true, false}, /* 1012 */ { "?, ...", 6, true, false}, /* 1013 */ { "(?)", 3, true, false}, /* 1014 */ { "(?) /* , ... */", 15, true, false}, /* 1015 */ { "(...)", 5, true, false}, /* 1016 */ { "(...) /* , ... */", 17, true, false}, /* 1017 */ { "(tok_id)", 8, true, false}, /* 1018 */ { "UNUSED", 6, true, false}, /* DUMMY */ { "", 0, false, false} }; #endif /* LEX_TOKEN_WITH_DEFINITION */ /* DIGEST specific tokens. */ #define TOK_GENERIC_VALUE 1011 #define TOK_GENERIC_VALUE_LIST 1012 #define TOK_ROW_SINGLE_VALUE 1013 #define TOK_ROW_SINGLE_VALUE_LIST 1014 #define TOK_ROW_MULTIPLE_VALUE 1015 #define TOK_ROW_MULTIPLE_VALUE_LIST 1016 #define TOK_IDENT 1017 #define TOK_UNUSED 1018 mysql/server/private/cset_narrowing.h000064400000007600151027430560014074 0ustar00/* Copyright (c) 2023, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef CSET_NARROWING_H_INCLUDED #define CSET_NARROWING_H_INCLUDED /* A singleton class to provide "utf8mb3_from_mb4.charset()". This is a variant of utf8mb3_general_ci that one can use when they have data in MB4 and want to make index lookup keys in MB3. */ extern class Charset_utf8narrow { struct my_charset_handler_st cset_handler; struct charset_info_st cset; public: Charset_utf8narrow() : cset_handler(*my_charset_utf8mb3_general_ci.cset), cset(my_charset_utf8mb3_general_ci) /* Copy the CHARSET_INFO structure */ { /* Insert our function wc_mb */ cset_handler.wc_mb= my_wc_mb_utf8mb4_bmp_only; cset.cset=&cset_handler; /* Charsets are compared by their name, so assign a different name */ LEX_CSTRING tmp= {STRING_WITH_LEN("utf8_mb4_to_mb3")}; cset.cs_name= tmp; } CHARSET_INFO *charset() { return &cset; } } utf8mb3_from_mb4; /* A class to temporary change a field that uses utf8mb3_general_ci to enable correct lookup key construction from string value in utf8mb4_general_ci Intended usage: // can do this in advance: bool do_narrowing= Utf8_narrow::should_do_narrowing(field, value_cset); ... // This sets the field to do narrowing if necessary: Utf8_narrow narrow(field, do_narrowing); // write to 'field' here // item->save_in_field(field) or something else // Stop doing narrowing narrow.stop(); */ class Utf8_narrow { Field *field; DTCollation save_collation; public: static bool should_do_narrowing(const THD *thd, CHARSET_INFO *field_cset, CHARSET_INFO *value_cset); static bool should_do_narrowing(const Field *field, CHARSET_INFO *value_cset) { CHARSET_INFO *field_cset= field->charset(); THD *thd= field->table->in_use; return should_do_narrowing(thd, field_cset, value_cset); } Utf8_narrow(Field *field_arg, bool is_applicable) { field= NULL; if (is_applicable) { DTCollation mb3_from_mb4= utf8mb3_from_mb4.charset(); field= field_arg; save_collation= field->dtcollation(); field->change_charset(mb3_from_mb4); } } void stop() { if (field) field->change_charset(save_collation); #ifndef NDEBUG field= NULL; #endif } ~Utf8_narrow() { DBUG_ASSERT(!field); } }; /* @brief Check if two fields can participate in a multiple equality using charset narrowing. @detail Normally, check_simple_equality() checks this by calling: left_field->eq_def(right_field) This function does the same but takes into account we might use charset narrowing: - collations are not the same but rather an utf8mb{3,4}_general_ci pair - for field lengths, should compare # characters, not #bytes. */ inline bool fields_equal_using_narrowing(const THD *thd, const Field *left, const Field *right) { return dynamic_cast(left) && dynamic_cast(right) && left->real_type() == right->real_type() && (Utf8_narrow::should_do_narrowing(left, right->charset()) || Utf8_narrow::should_do_narrowing(right, left->charset())) && left->char_length() == right->char_length(); }; #endif /* CSET_NARROWING_H_INCLUDED */ mysql/server/private/sql_prepare.h000064400000026221151027430560013365 0ustar00#ifndef SQL_PREPARE_H #define SQL_PREPARE_H /* Copyright (c) 1995-2008 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_error.h" #define LAST_STMT_ID 0xFFFFFFFF #define STMT_ID_MASK 0x7FFFFFFF class THD; struct LEX; /** An interface that is used to take an action when the locking module notices that a table version has changed since the last execution. "Table" here may refer to any kind of table -- a base table, a temporary table, a view or an information schema table. When we open and lock tables for execution of a prepared statement, we must verify that they did not change since statement prepare. If some table did change, the statement parse tree *may* be no longer valid, e.g. in case it contains optimizations that depend on table metadata. This class provides an interface (a method) that is invoked when such a situation takes place. The implementation of the method simply reports an error, but the exact details depend on the nature of the SQL statement. At most 1 instance of this class is active at a time, in which case THD::m_reprepare_observer is not NULL. @sa check_and_update_table_version() for details of the version tracking algorithm @sa Open_tables_state::m_reprepare_observer for the life cycle of metadata observers. */ class Reprepare_observer { public: /** Check if a change of metadata is OK. In future the signature of this method may be extended to accept the old and the new versions, but since currently the check is very simple, we only need the THD to report an error. */ bool report_error(THD *thd); bool is_invalidated() const { return m_invalidated; } void reset_reprepare_observer() { m_invalidated= FALSE; } private: bool m_invalidated; }; void mysqld_stmt_prepare(THD *thd, const char *packet, uint packet_length); void mysqld_stmt_execute(THD *thd, char *packet, uint packet_length); void mysqld_stmt_execute_bulk(THD *thd, char *packet, uint packet_length); void mysqld_stmt_bulk_execute(THD *thd, char *packet, uint packet_length); void mysqld_stmt_close(THD *thd, char *packet); void mysql_sql_stmt_prepare(THD *thd); void mysql_sql_stmt_execute(THD *thd); void mysql_sql_stmt_execute_immediate(THD *thd); void mysql_sql_stmt_close(THD *thd); void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length); void mysqld_stmt_reset(THD *thd, char *packet); void mysql_stmt_get_longdata(THD *thd, char *pos, ulong packet_length); void reinit_stmt_before_use(THD *thd, LEX *lex); my_bool bulk_parameters_iterations(THD *thd); my_bool bulk_parameters_set(THD *thd); /** Execute a fragment of server code in an isolated context, so that it doesn't leave any effect on THD. THD must have no open tables. The code must not leave any open tables around. The result of execution (if any) is stored in Ed_result. */ class Server_runnable { public: virtual bool execute_server_code(THD *thd)= 0; virtual ~Server_runnable(); }; /** Execute direct interface. @todo Implement support for prelocked mode. */ class Ed_row; /** Ed_result_set -- a container with result set rows. @todo Implement support for result set metadata and automatic type conversion. */ class Ed_result_set { public: operator List&() { return *m_rows; } unsigned int size() const { return m_rows->elements; } Ed_result_set(List *rows_arg, size_t column_count, MEM_ROOT *mem_root_arg); /** We don't call member destructors, they all are POD types. */ ~Ed_result_set() = default; size_t get_field_count() const { return m_column_count; } static void *operator new(size_t size, MEM_ROOT *mem_root) { return alloc_root(mem_root, size); } static void operator delete(void *ptr, size_t size) throw (); static void operator delete(void *, MEM_ROOT *){} private: Ed_result_set(const Ed_result_set &); /* not implemented */ Ed_result_set &operator=(Ed_result_set &); /* not implemented */ private: MEM_ROOT m_mem_root; size_t m_column_count; List *m_rows; Ed_result_set *m_next_rset; friend class Ed_connection; }; class Ed_connection { public: /** Construct a new "execute direct" connection. The connection can be used to execute SQL statements. If the connection failed to initialize, the error will be returned on the attempt to execute a statement. @pre thd must have no open tables while the connection is used. However, Ed_connection works okay in LOCK TABLES mode. Other properties of THD, such as the current warning information, errors, etc. do not matter and are preserved by Ed_connection. One thread may have many Ed_connections created for it. */ Ed_connection(THD *thd); /** Execute one SQL statement. Until this method is executed, no other methods of Ed_connection can be used. Life cycle of Ed_connection is: Initialized -> a statement has been executed -> look at result, move to next result -> look at result, move to next result -> ... moved beyond the last result == Initialized. This method can be called repeatedly. Once it's invoked, results of the previous execution are lost. A result of execute_direct() can be either: - success, no result set rows. In this case get_field_count() returns 0. This happens after execution of INSERT, UPDATE, DELETE, DROP and similar statements. Some other methods, such as get_affected_rows() can be used to retrieve additional result information. - success, there are some result set rows (maybe 0). E.g. happens after SELECT. In this case get_field_count() returns the number of columns in a result set and store_result() can be used to retrieve a result set.. - an error, methods to retrieve error information can be used. @return execution status @retval FALSE success, use get_field_count() to determine what to do next. @retval TRUE error, use get_last_error() to see the error number. */ bool execute_direct(Protocol *p, LEX_STRING sql_text); /** Same as the previous, but takes an instance of Server_runnable instead of SQL statement text. @return execution status @retval FALSE success, use get_field_count() if your code fragment is supposed to return a result set @retval TRUE failure */ bool execute_direct(Protocol *p, Server_runnable *server_runnable); /** Get the number of affected (deleted, updated) rows for the current statement. Can be used for statements with get_field_count() == 0. @sa Documentation for C API function mysql_affected_rows(). */ ulonglong get_affected_rows() const { return m_diagnostics_area.affected_rows(); } /** Get the last insert id, if any. @sa Documentation for mysql_insert_id(). */ ulonglong get_last_insert_id() const { return m_diagnostics_area.last_insert_id(); } /** Get the total number of warnings for the last executed statement. Note, that there is only one warning list even if a statement returns multiple results. @sa Documentation for C API function mysql_num_warnings(). */ ulong get_warn_count() const { return m_diagnostics_area.warn_count(); } /** The following members are only valid if execute_direct() or move_to_next_result() returned an error. They never fail, but if they are called when there is no result, or no error, the result is not defined. */ const char *get_last_error() const { return m_diagnostics_area.message(); } unsigned int get_last_errno() const { return m_diagnostics_area.sql_errno(); } const char *get_last_sqlstate() const { return m_diagnostics_area.get_sqlstate(); } /** Provided get_field_count() is not 0, this never fails. You don't need to free the result set, this is done automatically when you advance to the next result set or destroy the connection. Not returning const because of List iterator not accepting Should be used when you would like Ed_connection to manage result set memory for you. */ Ed_result_set *use_result_set() { return m_current_rset; } /** Provided get_field_count() is not 0, this never fails. You must free the returned result set. This can be called only once after execute_direct(). Should be used when you would like to get the results and destroy the connection. */ Ed_result_set *store_result_set(); /** If the query returns multiple results, this method can be checked if there is another result beyond the next one. Never fails. */ bool has_next_result() const { return MY_TEST(m_current_rset->m_next_rset); } /** Only valid to call if has_next_result() returned true. Otherwise the result is undefined. */ bool move_to_next_result() { m_current_rset= m_current_rset->m_next_rset; return MY_TEST(m_current_rset); } ~Ed_connection() { free_old_result(); } private: Diagnostics_area m_diagnostics_area; /** Execute direct interface does not support multi-statements, only multi-results. So we never have a situation when we have a mix of result sets and OK or error packets. We either have a single result set, a single error, or a single OK, or we have a series of result sets, followed by an OK or error. */ THD *m_thd; Ed_result_set *m_rsets; Ed_result_set *m_current_rset; private: void free_old_result(); void add_result_set(Ed_result_set *ed_result_set); private: Ed_connection(const Ed_connection &); /* not implemented */ Ed_connection &operator=(Ed_connection &); /* not implemented */ }; /** One result set column. */ struct Ed_column: public LEX_STRING { /** Implementation note: destructor for this class is never called. */ }; /** One result set record. */ class Ed_row: public Sql_alloc { public: const Ed_column &operator[](const unsigned int column_index) const { return *get_column(column_index); } const Ed_column *get_column(const unsigned int column_index) const { DBUG_ASSERT(column_index < size()); return m_column_array + column_index; } size_t size() const { return m_column_count; } Ed_row(Ed_column *column_array_arg, size_t column_count_arg) :m_column_array(column_array_arg), m_column_count(column_count_arg) {} private: Ed_column *m_column_array; size_t m_column_count; /* TODO: change to point to metadata */ }; extern Atomic_counter local_connection_thread_count; #endif // SQL_PREPARE_H mysql/server/private/sql_trigger.h000064400000030054151027430560013371 0ustar00#ifndef SQL_TRIGGER_INCLUDED #define SQL_TRIGGER_INCLUDED /* Copyright (c) 2004, 2011, Oracle and/or its affiliates. Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include /* Forward declarations */ class Item_trigger_field; class sp_head; class sp_name; class Query_tables_list; struct TABLE_LIST; class Query_tables_list; typedef struct st_ddl_log_state DDL_LOG_STATE; /** Event on which trigger is invoked. */ enum trg_event_type { TRG_EVENT_INSERT= 0, TRG_EVENT_UPDATE= 1, TRG_EVENT_DELETE= 2, TRG_EVENT_MAX }; static inline uint8 trg2bit(enum trg_event_type trg) { return static_cast(1 << static_cast(trg)); } #include "table.h" /* GRANT_INFO */ /* We need this two enums here instead of sql_lex.h because at least one of them is used by Item_trigger_field interface. Time when trigger is invoked (i.e. before or after row actually inserted/updated/deleted). */ enum trg_action_time_type { TRG_ACTION_BEFORE= 0, TRG_ACTION_AFTER= 1, TRG_ACTION_MAX }; enum trigger_order_type { TRG_ORDER_NONE= 0, TRG_ORDER_FOLLOWS= 1, TRG_ORDER_PRECEDES= 2 }; struct st_trg_execution_order { /** FOLLOWS or PRECEDES as specified in the CREATE TRIGGER statement. */ enum trigger_order_type ordering_clause; /** Trigger name referenced in the FOLLOWS/PRECEDES clause of the CREATE TRIGGER statement. */ LEX_CSTRING anchor_trigger_name; }; /* Parameter to change_table_name_in_triggers() */ class TRIGGER_RENAME_PARAM { public: TABLE table; bool upgrading50to51; bool got_error; TRIGGER_RENAME_PARAM() { upgrading50to51= got_error= 0; table.reset(); } ~TRIGGER_RENAME_PARAM() { reset(); } void reset(); }; class Table_triggers_list; /** The trigger object */ class Trigger :public Sql_alloc { public: Trigger(Table_triggers_list *base_arg, sp_head *code): base(base_arg), body(code), next(0), trigger_fields(0), action_order(0) { bzero((char *)&subject_table_grants, sizeof(subject_table_grants)); } ~Trigger(); Table_triggers_list *base; sp_head *body; Trigger *next; /* Next trigger of same type */ /** Heads of the lists linking items for all fields used in triggers grouped by event and action_time. */ Item_trigger_field *trigger_fields; LEX_CSTRING name; LEX_CSTRING on_table_name; /* Raw table name */ LEX_CSTRING definition; LEX_CSTRING definer; /* Character sets used */ LEX_CSTRING client_cs_name; LEX_CSTRING connection_cl_name; LEX_CSTRING db_cl_name; GRANT_INFO subject_table_grants; sql_mode_t sql_mode; /* Store create time. Can't be mysql_time_t as this holds also sub seconds */ my_hrtime_t hr_create_time; // Create time timestamp in microseconds trg_event_type event; trg_action_time_type action_time; uint action_order; bool is_fields_updated_in_trigger(MY_BITMAP *used_fields); void get_trigger_info(LEX_CSTRING *stmt, LEX_CSTRING *body, LEX_STRING *definer); /* Functions executed over each active trigger */ bool change_on_table_name(void* param_arg); bool change_table_name(void* param_arg); bool add_to_file_list(void* param_arg); }; typedef bool (Trigger::*Triggers_processor)(void *arg); /** This class holds all information about triggers of table. */ class Table_triggers_list: public Sql_alloc { friend class Trigger; /* Points to first trigger for a certain type */ Trigger *triggers[TRG_EVENT_MAX][TRG_ACTION_MAX]; /** Copy of TABLE::Field array which all fields made nullable (using extra_null_bitmap, if needed). Used for NEW values in BEFORE INSERT/UPDATE triggers. */ Field **record0_field; uchar *extra_null_bitmap, *extra_null_bitmap_init; /** Copy of TABLE::Field array with field pointers set to TABLE::record[1] buffer instead of TABLE::record[0] (used for OLD values in on UPDATE trigger and DELETE trigger when it is called for REPLACE). */ Field **record1_field; /** During execution of trigger new_field and old_field should point to the array of fields representing new or old version of row correspondingly (so it can point to TABLE::field or to Tale_triggers_list::record1_field) */ Field **new_field; Field **old_field; /* TABLE instance for which this triggers list object was created */ TABLE *trigger_table; /** This flag indicates that one of the triggers was not parsed successfully, and as a precaution the object has entered a state where all trigger access results in errors until all such triggers are dropped. It is not safe to add triggers since we don't know if the broken trigger has the same name or event type. Nor is it safe to invoke any trigger for the aforementioned reasons. The only safe operations are drop_trigger and drop_all_triggers. @see Table_triggers_list::set_parse_error */ bool m_has_unparseable_trigger; /** This error will be displayed when the user tries to manipulate or invoke triggers on a table that has broken triggers. It will get set only once per statement and thus will contain the first parse error encountered in the trigger file. */ char m_parse_error_message[MYSQL_ERRMSG_SIZE]; uint count; /* Number of triggers */ public: /** Field responsible for storing triggers definitions in file. It have to be public because we are using it directly from parser. */ List definitions_list; /** List of sql modes for triggers */ List definition_modes_list; /** Create times for triggers */ List hr_create_times; List definers_list; /* Character set context, used for parsing and executing triggers. */ List client_cs_names; List connection_cl_names; List db_cl_names; /* End of character ser context. */ Table_triggers_list(TABLE *table_arg) :record0_field(0), extra_null_bitmap(0), extra_null_bitmap_init(0), record1_field(0), trigger_table(table_arg), m_has_unparseable_trigger(false), count(0) { bzero((char *) triggers, sizeof(triggers)); } ~Table_triggers_list(); bool create_trigger(THD *thd, TABLE_LIST *table, String *stmt_query, DDL_LOG_STATE *ddl_log_state, DDL_LOG_STATE *ddl_log_state_tmp_file); bool drop_trigger(THD *thd, TABLE_LIST *table, LEX_CSTRING *sp_name, String *stmt_query, DDL_LOG_STATE *ddl_log_state); bool process_triggers(THD *thd, trg_event_type event, trg_action_time_type time_type, bool old_row_is_record1); void empty_lists(); bool create_lists_needed_for_files(MEM_ROOT *root); bool save_trigger_file(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table_name); static bool check_n_load(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table_name, TABLE *table, bool names_only); static bool drop_all_triggers(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table_name, myf MyFlags); static bool prepare_for_rename(THD *thd, TRIGGER_RENAME_PARAM *param, const LEX_CSTRING *db, const LEX_CSTRING *old_alias, const LEX_CSTRING *old_table, const LEX_CSTRING *new_db, const LEX_CSTRING *new_table); static bool change_table_name(THD *thd, TRIGGER_RENAME_PARAM *param, const LEX_CSTRING *db, const LEX_CSTRING *old_alias, const LEX_CSTRING *old_table, const LEX_CSTRING *new_db, const LEX_CSTRING *new_table); void add_trigger(trg_event_type event_type, trg_action_time_type action_time, trigger_order_type ordering_clause, LEX_CSTRING *anchor_trigger_name, Trigger *trigger); Trigger *get_trigger(trg_event_type event_type, trg_action_time_type action_time) { return triggers[event_type][action_time]; } /* Simpler version of the above, to avoid casts in the code */ Trigger *get_trigger(uint event_type, uint action_time) { return get_trigger((trg_event_type) event_type, (trg_action_time_type) action_time); } bool has_triggers(trg_event_type event_type, trg_action_time_type action_time) { return get_trigger(event_type,action_time) != 0; } bool has_delete_triggers() { return (has_triggers(TRG_EVENT_DELETE,TRG_ACTION_BEFORE) || has_triggers(TRG_EVENT_DELETE,TRG_ACTION_AFTER)); } void mark_fields_used(trg_event_type event); void set_parse_error_message(char *error_message); friend class Item_trigger_field; bool add_tables_and_routines_for_triggers(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list); Field **nullable_fields() { return record0_field; } void clear_extra_null_bitmap() { if (size_t null_bytes= extra_null_bitmap_init - extra_null_bitmap) bzero(extra_null_bitmap, null_bytes); } void default_extra_null_bitmap() { if (size_t null_bytes= extra_null_bitmap_init - extra_null_bitmap) memcpy(extra_null_bitmap, extra_null_bitmap_init, null_bytes); } Trigger *find_trigger(const LEX_CSTRING *name, bool remove_from_list); Trigger* for_all_triggers(Triggers_processor func, void *arg); private: bool prepare_record_accessors(TABLE *table); Trigger *change_table_name_in_trignames(const LEX_CSTRING *old_db_name, const LEX_CSTRING *new_db_name, const LEX_CSTRING *new_table_name, Trigger *trigger); bool change_table_name_in_triggers(THD *thd, const LEX_CSTRING *old_db_name, const LEX_CSTRING *new_db_name, const LEX_CSTRING *old_table_name, const LEX_CSTRING *new_table_name); bool check_for_broken_triggers() { if (m_has_unparseable_trigger) { my_message(ER_PARSE_ERROR, m_parse_error_message, MYF(0)); return true; } return false; } }; bool add_table_for_trigger(THD *thd, const sp_name *trg_name, bool continue_if_not_exist, TABLE_LIST **table); void build_trn_path(THD *thd, const sp_name *trg_name, LEX_STRING *trn_path); bool check_trn_exists(const LEX_CSTRING *trn_path); bool load_table_name_for_trigger(THD *thd, const sp_name *trg_name, const LEX_CSTRING *trn_path, LEX_CSTRING *tbl_name); bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create); bool rm_trigname_file(char *path, const LEX_CSTRING *db, const LEX_CSTRING *trigger_name, myf MyFlags); extern const char * const TRG_EXT; extern const char * const TRN_EXT; #endif /* SQL_TRIGGER_INCLUDED */ mysql/server/private/create_tmp_table.h000064400000005370151027430560014344 0ustar00#ifndef CREATE_TMP_TABLE_INCLUDED #define CREATE_TMP_TABLE_INCLUDED /* Copyright (c) 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Class for creating internal tempory tables in sql_select.cc */ class Create_tmp_table: public Data_type_statistics { protected: // The following members are initialized only in start() Field **m_from_field, **m_default_field; KEY_PART_INFO *m_key_part_info; uchar *m_group_buff, *m_bitmaps; // The following members are initialized in ctor uint m_alloced_field_count; bool m_using_unique_constraint; uint m_temp_pool_slot; ORDER *m_group; bool m_distinct; bool m_save_sum_fields; bool m_with_cycle; ulonglong m_select_options; ha_rows m_rows_limit; uint m_group_null_items; // counter for distinct/other fields uint m_field_count[2]; // counter for distinct/other fields which can be NULL uint m_null_count[2]; // counter for distinct/other blob fields uint m_blobs_count[2]; // counter for "tails" of bit fields which do not fit in a byte uint m_uneven_bit[2]; public: enum counter {distinct, other}; /* shows which field we are processing: distinct/other (set in processing cycles) */ counter current_counter; Create_tmp_table(ORDER *group, bool distinct, bool save_sum_fields, ulonglong select_options, ha_rows rows_limit); virtual ~Create_tmp_table() {} virtual bool choose_engine(THD *thd, TABLE *table, TMP_TABLE_PARAM *param); void add_field(TABLE *table, Field *field, uint fieldnr, bool force_not_null_cols); TABLE *start(THD *thd, TMP_TABLE_PARAM *param, const LEX_CSTRING *table_alias); bool add_fields(THD *thd, TABLE *table, TMP_TABLE_PARAM *param, List &fields); bool add_schema_fields(THD *thd, TABLE *table, TMP_TABLE_PARAM *param, const ST_SCHEMA_TABLE &schema_table); bool finalize(THD *thd, TABLE *table, TMP_TABLE_PARAM *param, bool do_not_open, bool keep_row_order); void cleanup_on_failure(THD *thd, TABLE *table); }; #endif /* CREATE_TMP_TABLE_INCLUDED */ mysql/server/private/wsrep_utils.h000064400000022112151027430560013423 0ustar00/* Copyright (C) 2013-2015 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #ifndef WSREP_UTILS_H #define WSREP_UTILS_H #include "wsrep_priv.h" #include "wsrep_mysqld.h" unsigned int wsrep_check_ip (const char* const addr, bool *is_ipv6); size_t wsrep_guess_ip (char* buf, size_t buf_len); /* returns the length of the host part of the address string */ size_t wsrep_host_len(const char* addr, size_t addr_len); namespace wsp { class Address { public: Address() : m_address_len(0), m_family(UNSPEC), m_port(0), m_valid(false) { memset(m_address, 0, sizeof(m_address)); } Address(const char *addr_in) : m_address_len(0), m_family(UNSPEC), m_port(0), m_valid(false) { memset(m_address, 0, sizeof(m_address)); parse_addr(addr_in); } bool is_valid() { return m_valid; } bool is_ipv6() { return (m_family == INET6); } const char* get_address() { return m_address; } size_t get_address_len() { return m_address_len; } int get_port() { return m_port; } void set_port(int port) { m_port= port; } private: enum family { UNSPEC= 0, INET, /* IPv4 */ INET6, /* IPv6 */ }; char m_address[256]; size_t m_address_len; family m_family; int m_port; bool m_valid; void parse_addr(const char *addr_in) { const char *start; const char *end; const char *port; const char* open_bracket= strchr(const_cast(addr_in), '['); const char* close_bracket= strchr(const_cast(addr_in), ']'); const char* colon= strchr(const_cast(addr_in), ':'); const char* dot= strchr(const_cast(addr_in), '.'); int cc= colon_count(addr_in); if (open_bracket != NULL || dot == NULL || (colon != NULL && (dot == NULL || colon < dot))) { // This could be an IPv6 address or a hostname if (open_bracket != NULL) { /* Sanity check: Address with '[' must include ']' */ if (close_bracket == NULL && open_bracket < close_bracket) /* Error: malformed address */ { m_valid= false; return; } start= open_bracket + 1; end= close_bracket; /* Check for port */ port= strchr(close_bracket, ':'); if ((port != NULL) && parse_port(port + 1)) { return; /* Error: invalid port */ } m_family= INET6; } else { switch (cc) { case 0: /* Hostname with no port */ start= addr_in; end= addr_in + strlen(addr_in); break; case 1: /* Hostname with port (host:port) */ start= addr_in; end= colon; if (parse_port(colon + 1)) return; /* Error: invalid port */ break; default: /* IPv6 address */ start= addr_in; end= addr_in + strlen(addr_in); m_family= INET6; break; } } } else { /* IPv4 address or hostname */ start= addr_in; if (colon != NULL) { /* Port */ end= colon; if (parse_port(colon + 1)) return; /* Error: invalid port */ } else { end= addr_in + strlen(addr_in); } } size_t len= end - start; /* Safety */ if (len >= sizeof(m_address)) { // The supplied address is too large to fit into the internal buffer. m_valid= false; return; } memcpy(m_address, start, len); m_address[len]= '\0'; m_address_len= ++ len; m_valid= true; return; } int colon_count(const char *addr) { int count= 0, i= 0; while(addr[i] != '\0') { if (addr[i] == ':') ++count; ++ i; } return count; } bool parse_port(const char *port) { errno= 0; /* Reset the errno */ m_port= strtol(port, NULL, 10); if (errno == EINVAL || errno == ERANGE) { m_port= 0; /* Error: invalid port */ m_valid= false; return true; } return false; } }; class Config_state { public: Config_state() : view_(), status_(wsrep::server_state::s_disconnected) {} void set(const wsrep::view& view) { wsrep_notify_status(status_, &view); lock(); view_= view; unlock(); } void set(enum wsrep::server_state::state status) { if (status == wsrep::server_state::s_donor || status == wsrep::server_state::s_synced) wsrep_notify_status(status, &view_); else wsrep_notify_status(status); lock(); status_= status; unlock(); } const wsrep::view& get_view_info() const { return view_; } enum wsrep::server_state::state get_status() const { return status_; } int lock() { return mysql_mutex_lock(&LOCK_wsrep_config_state); } int unlock() { return mysql_mutex_unlock(&LOCK_wsrep_config_state); } private: wsrep::view view_; enum wsrep::server_state::state status_; }; } /* namespace wsp */ extern wsp::Config_state *wsrep_config_state; namespace wsp { /* a class to manage env vars array */ class env { private: size_t len_; char** env_; int errno_; bool ctor_common(char** e); void dtor(); env& operator =(env); public: explicit env(char** env); explicit env(const env&); ~env(); int append(const char* var); /* add a new env. var */ int error() const { return errno_; } char** operator()() { return env_; } }; /* A small class to run external programs. */ class process { private: const char* const str_; FILE* io_; int err_; pid_t pid_; public: /*! @arg type is a pointer to a null-terminated string which must contain either the letter 'r' for reading or the letter 'w' for writing. @arg env optional null-terminated vector of environment variables */ process (const char* cmd, const char* type, char** env); ~process (); FILE* pipe () { return io_; } int error() { return err_; } int wait (); const char* cmd() { return str_; } }; class thd { class thd_init { public: thd_init() { my_thread_init(); } ~thd_init() { my_thread_end(); } } init; thd (const thd&); thd& operator= (const thd&); public: thd(my_bool wsrep_on, bool system_thread=false); ~thd(); THD* const ptr; }; class string { public: string() : string_(0) {} explicit string(size_t s) : string_(static_cast(malloc(s))) {} char* operator()() { return string_; } void set(char* str) { if (string_) free (string_); string_= str; } ~string() { set (0); } private: char* string_; }; /* scope level lock */ class auto_lock { public: auto_lock(mysql_mutex_t* m) : m_(m) { mysql_mutex_lock(m_); } ~auto_lock() { mysql_mutex_unlock(m_); } private: mysql_mutex_t& operator =(mysql_mutex_t&); mysql_mutex_t* const m_; }; #ifdef REMOVED class lock { pthread_mutex_t* const mtx_; public: lock (pthread_mutex_t* mtx) : mtx_(mtx) { int err= pthread_mutex_lock (mtx_); if (err) { WSREP_ERROR("Mutex lock failed: %s", strerror(err)); abort(); } } virtual ~lock () { int err= pthread_mutex_unlock (mtx_); if (err) { WSREP_ERROR("Mutex unlock failed: %s", strerror(err)); abort(); } } inline void wait (pthread_cond_t* cond) { pthread_cond_wait (cond, mtx_); } private: lock (const lock&); lock& operator=(const lock&); }; class monitor { int mutable refcnt; pthread_mutex_t mutable mtx; pthread_cond_t mutable cond; public: monitor() : refcnt(0) { pthread_mutex_init (&mtx, NULL); pthread_cond_init (&cond, NULL); } ~monitor() { pthread_mutex_destroy (&mtx); pthread_cond_destroy (&cond); } void enter() const { lock l(&mtx); while (refcnt) { l.wait(&cond); } refcnt++; } void leave() const { lock l(&mtx); refcnt--; if (refcnt == 0) { pthread_cond_signal (&cond); } } private: monitor (const monitor&); monitor& operator= (const monitor&); }; class critical { const monitor& mon; public: critical(const monitor& m) : mon(m) { mon.enter(); } ~critical() { mon.leave(); } private: critical (const critical&); critical& operator= (const critical&); }; #endif } // namespace wsrep #endif /* WSREP_UTILS_H */ mysql/server/private/item_windowfunc.h000064400000103013151027430560014244 0ustar00/* Copyright (c) 2016, 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ITEM_WINDOWFUNC_INCLUDED #define ITEM_WINDOWFUNC_INCLUDED #include "item.h" class Window_spec; int test_if_group_changed(List &list); /* A wrapper around test_if_group_changed */ class Group_bound_tracker { public: Group_bound_tracker(THD *thd, SQL_I_List *list) { for (ORDER *curr = list->first; curr; curr=curr->next) { Cached_item *tmp= new_Cached_item(thd, curr->item[0], TRUE); group_fields.push_back(tmp); } } void init() { first_check= true; } /* Check if the current row is in a different group than the previous row this function was called for. XXX: Side-effect: The new row's group becomes the current row's group. Returns true if there is a change between the current_group and the cached value, or if it is the first check after a call to init. */ bool check_if_next_group() { if (test_if_group_changed(group_fields) > -1 || first_check) { first_check= false; return true; } return false; } /* Check if the current row is in a different group than the previous row check_if_next_group was called for. Compares the groups without the additional side effect of updating the current cached values. */ int compare_with_cache() { List_iterator li(group_fields); Cached_item *ptr; int res; while ((ptr= li++)) { if ((res= ptr->cmp_read_only())) return res; } return 0; } ~Group_bound_tracker() { group_fields.delete_elements(); } private: List group_fields; /* During the first check_if_next_group, the list of cached_items is not initialized. The compare function will return that the items match if the field's value is the same as the Cached_item's default value (0). This flag makes sure that we always return true during the first check. XXX This is better to be implemented within test_if_group_changed, but since it is used in other parts of the codebase, we keep it here for now. */ bool first_check; }; /* ROW_NUMBER() OVER (...) @detail - This is a Window function (not just an aggregate) - It can be computed by doing one pass over select output, provided the output is sorted according to the window definition. */ class Item_sum_row_number: public Item_sum_int { longlong count; public: Item_sum_row_number(THD *thd) : Item_sum_int(thd), count(0) {} const Type_handler *type_handler() const override { return &type_handler_slonglong; } void clear() override { count= 0; } bool add() override { count++; return false; } void reset_field() override { DBUG_ASSERT(0); } void update_field() override {} enum Sumfunctype sum_func() const override { return ROW_NUMBER_FUNC; } longlong val_int() override { return count; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("row_number") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* RANK() OVER (...) Windowing function @detail - This is a Window function (not just an aggregate) - It can be computed by doing one pass over select output, provided the output is sorted according to the window definition. The function is defined as: "The rank of row R is defined as 1 (one) plus the number of rows that precede R and are not peers of R" "This implies that if two or more rows are not distinct with respect to the window ordering, then there will be one or more" */ class Item_sum_rank: public Item_sum_int { protected: longlong row_number; // just ROW_NUMBER() longlong cur_rank; // current value Group_bound_tracker *peer_tracker; public: Item_sum_rank(THD *thd) : Item_sum_int(thd), peer_tracker(NULL) {} const Type_handler *type_handler() const override { return &type_handler_slonglong; } void clear() override { /* This is called on partition start */ cur_rank= 1; row_number= 0; } bool add() override; longlong val_int() override { return cur_rank; } void reset_field() override { DBUG_ASSERT(0); } void update_field() override {} enum Sumfunctype sum_func () const override { return RANK_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("rank") }; return name; } void setup_window_func(THD *thd, Window_spec *window_spec) override; void cleanup() override { if (peer_tracker) { delete peer_tracker; peer_tracker= NULL; } Item_sum_int::cleanup(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* DENSE_RANK() OVER (...) Windowing function @detail - This is a Window function (not just an aggregate) - It can be computed by doing one pass over select output, provided the output is sorted according to the window definition. The function is defined as: "If DENSE_RANK is specified, then the rank of row R is defined as the number of rows preceding and including R that are distinct with respect to the window ordering" "This implies that there are no gaps in the sequential rank numbering of rows in each window partition." */ class Item_sum_dense_rank: public Item_sum_int { longlong dense_rank; bool first_add; Group_bound_tracker *peer_tracker; public: /* XXX(cvicentiu) This class could potentially be implemented in the rank class, with a switch for the DENSE case. */ void clear() override { dense_rank= 0; first_add= true; } bool add() override; void reset_field() override { DBUG_ASSERT(0); } void update_field() override {} longlong val_int() override { return dense_rank; } Item_sum_dense_rank(THD *thd) : Item_sum_int(thd), dense_rank(0), first_add(true), peer_tracker(NULL) {} const Type_handler *type_handler() const override { return &type_handler_slonglong; } enum Sumfunctype sum_func () const override { return DENSE_RANK_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("dense_rank") }; return name; } void setup_window_func(THD *thd, Window_spec *window_spec) override; void cleanup() override { if (peer_tracker) { delete peer_tracker; peer_tracker= NULL; } Item_sum_int::cleanup(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_hybrid_simple : public Item_sum_hybrid { public: Item_sum_hybrid_simple(THD *thd, Item *arg): Item_sum_hybrid(thd, arg), value(NULL) { } Item_sum_hybrid_simple(THD *thd, Item *arg1, Item *arg2): Item_sum_hybrid(thd, arg1, arg2), value(NULL) { } bool add() override; bool fix_fields(THD *, Item **) override; bool fix_length_and_dec() override; void setup_hybrid(THD *thd, Item *item); double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; void reset_field() override; String *val_str(String *) override; bool val_native(THD *thd, Native *to) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } void update_field() override; Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) override; void clear() override { value->clear(); null_value= 1; } private: Item_cache *value; }; /* This item will remember the first value added to it. It will not update the value unless it is cleared. */ class Item_sum_first_value : public Item_sum_hybrid_simple { public: Item_sum_first_value(THD* thd, Item* arg_expr) : Item_sum_hybrid_simple(thd, arg_expr) {} enum Sumfunctype sum_func () const override { return FIRST_VALUE_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("first_value") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* This item will remember the last value added to it. This item does not support removal, and can be cleared only by calling clear(). */ class Item_sum_last_value : public Item_sum_hybrid_simple { public: Item_sum_last_value(THD* thd, Item* arg_expr) : Item_sum_hybrid_simple(thd, arg_expr) {} enum Sumfunctype sum_func() const override { return LAST_VALUE_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("last_value") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_nth_value : public Item_sum_hybrid_simple { public: Item_sum_nth_value(THD *thd, Item *arg_expr, Item* offset_expr) : Item_sum_hybrid_simple(thd, arg_expr, offset_expr) {} enum Sumfunctype sum_func() const override { return NTH_VALUE_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("nth_value") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_lead : public Item_sum_hybrid_simple { public: Item_sum_lead(THD *thd, Item *arg_expr, Item* offset_expr) : Item_sum_hybrid_simple(thd, arg_expr, offset_expr) {} enum Sumfunctype sum_func() const override { return LEAD_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("lead") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_lag : public Item_sum_hybrid_simple { public: Item_sum_lag(THD *thd, Item *arg_expr, Item* offset_expr) : Item_sum_hybrid_simple(thd, arg_expr, offset_expr) {} enum Sumfunctype sum_func() const override { return LAG_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("lag") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Partition_row_count { public: Partition_row_count() :partition_row_count_(0) { } void set_partition_row_count(ulonglong count) { partition_row_count_ = count; } double calc_val_real(bool *null_value, ulonglong current_row_count) { if ((*null_value= (partition_row_count_ == 0))) return 0; return static_cast(current_row_count) / partition_row_count_; } protected: longlong get_row_count() { return partition_row_count_; } ulonglong partition_row_count_; }; class Current_row_count { public: Current_row_count() :current_row_count_(0) { } protected: ulonglong get_row_number() { return current_row_count_ ; } ulonglong current_row_count_; }; /* @detail "The relative rank of a row R is defined as (RK-1)/(NR-1), where RK is defined to be the RANK of R and NR is defined to be the number of rows in the window partition of R." Computation of this function requires two passes: - First pass to find #rows in the partition This is held within the row_count context. - Second pass to compute rank of current row and the value of the function */ class Item_sum_percent_rank: public Item_sum_double, public Partition_row_count { public: Item_sum_percent_rank(THD *thd) : Item_sum_double(thd), cur_rank(1), peer_tracker(NULL) {} longlong val_int() override { /* Percent rank is a real value so calling the integer value should never happen. It makes no sense as it gets truncated to either 0 or 1. */ DBUG_ASSERT(0); return 0; } double val_real() override { /* We can not get the real value without knowing the number of rows in the partition. Don't divide by 0. */ ulonglong partition_rows = get_row_count(); null_value= partition_rows > 0 ? false : true; return partition_rows > 1 ? static_cast(cur_rank - 1) / (partition_rows - 1) : 0; } enum Sumfunctype sum_func () const override { return PERCENT_RANK_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("percent_rank") }; return name; } void update_field() override {} void clear() override { cur_rank= 1; row_number= 0; } bool add() override; const Type_handler *type_handler() const override { return &type_handler_double; } bool fix_length_and_dec() override { decimals = 10; // TODO-cvicentiu find out how many decimals the standard // requires. return FALSE; } void setup_window_func(THD *thd, Window_spec *window_spec) override; void reset_field() override { DBUG_ASSERT(0); } void set_partition_row_count(ulonglong count) override { Partition_row_count::set_partition_row_count(count); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: longlong cur_rank; // Current rank of the current row. longlong row_number; // Value if this were ROW_NUMBER() function. Group_bound_tracker *peer_tracker; void cleanup() override { if (peer_tracker) { delete peer_tracker; peer_tracker= NULL; } Item_sum_num::cleanup(); } }; /* @detail "The relative rank of a row R is defined as NP/NR, where - NP is defined to be the number of rows preceding or peer with R in the window ordering of the window partition of R - NR is defined to be the number of rows in the window partition of R. Just like with Item_sum_percent_rank, computation of this function requires two passes. */ class Item_sum_cume_dist: public Item_sum_double, public Partition_row_count, public Current_row_count { public: Item_sum_cume_dist(THD *thd) :Item_sum_double(thd) { } Item_sum_cume_dist(THD *thd, Item *arg) :Item_sum_double(thd, arg) { } double val_real() override { return calc_val_real(&null_value, current_row_count_); } bool add() override { current_row_count_++; return false; } enum Sumfunctype sum_func() const override { return CUME_DIST_FUNC; } void clear() override { current_row_count_= 0; partition_row_count_= 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cume_dist") }; return name; } void update_field() override {} const Type_handler *type_handler() const override { return &type_handler_double; } bool fix_length_and_dec() override { decimals = 10; // TODO-cvicentiu find out how many decimals the standard // requires. return FALSE; } void reset_field() override { DBUG_ASSERT(0); } void set_partition_row_count(ulonglong count) override { Partition_row_count::set_partition_row_count(count); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_ntile : public Item_sum_int, public Partition_row_count, public Current_row_count { public: Item_sum_ntile(THD* thd, Item* num_quantiles_expr) : Item_sum_int(thd, num_quantiles_expr), n_old_val_(0) { } longlong val_int() override { if (get_row_count() == 0) { null_value= true; return 0; } longlong num_quantiles= get_num_quantiles(); if (num_quantiles <= 0 || (static_cast(num_quantiles) != n_old_val_ && n_old_val_ > 0)) { my_error(ER_INVALID_NTILE_ARGUMENT, MYF(0)); return true; } n_old_val_= static_cast(num_quantiles); null_value= false; ulonglong quantile_size = get_row_count() / num_quantiles; ulonglong extra_rows = get_row_count() - quantile_size * num_quantiles; if (current_row_count_ <= extra_rows * (quantile_size + 1)) return (current_row_count_ - 1) / (quantile_size + 1) + 1; return (current_row_count_ - 1 - extra_rows) / quantile_size + 1; } bool add() override { current_row_count_++; return false; } enum Sumfunctype sum_func() const override { return NTILE_FUNC; } void clear() override { current_row_count_= 0; partition_row_count_= 0; n_old_val_= 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ntile") }; return name; } void update_field() override {} const Type_handler *type_handler() const override { return &type_handler_slonglong; } void reset_field() override { DBUG_ASSERT(0); } void set_partition_row_count(ulonglong count) override { Partition_row_count::set_partition_row_count(count); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: longlong get_num_quantiles() { return args[0]->val_int(); } ulonglong n_old_val_; }; class Item_sum_percentile_disc : public Item_sum_num, public Type_handler_hybrid_field_type, public Partition_row_count, public Current_row_count { public: Item_sum_percentile_disc(THD *thd, Item* arg) : Item_sum_num(thd, arg), Type_handler_hybrid_field_type(&type_handler_slonglong), value(NULL), val_calculated(FALSE), first_call(TRUE), prev_value(0), order_item(NULL){} double val_real() override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return 0; } null_value= false; return value->val_real(); } longlong val_int() override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return 0; } null_value= false; return value->val_int(); } my_decimal* val_decimal(my_decimal* dec) override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return 0; } null_value= false; return value->val_decimal(dec); } String* val_str(String *str) override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return 0; } null_value= false; return value->val_str(str); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return true; } null_value= false; return value->get_date(thd, ltime, fuzzydate); } bool val_native(THD *thd, Native *to) override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return true; } null_value= false; return value->val_native(thd, to); } bool add() override { Item *arg= get_arg(0); if (arg->is_null()) return false; if (first_call) { prev_value= arg->val_real(); if (prev_value > 1 || prev_value < 0) { my_error(ER_ARGUMENT_OUT_OF_RANGE, MYF(0), func_name()); return true; } first_call= false; } double arg_val= arg->val_real(); if (prev_value != arg_val) { my_error(ER_ARGUMENT_NOT_CONSTANT, MYF(0), func_name()); return true; } if (val_calculated) return false; value->store(order_item); value->cache_value(); if (value->null_value) return false; current_row_count_++; double val= calc_val_real(&null_value, current_row_count_); if (val >= prev_value && !val_calculated) val_calculated= true; return false; } enum Sumfunctype sum_func() const override { return PERCENTILE_DISC_FUNC; } void clear() override { val_calculated= false; first_call= true; value->clear(); partition_row_count_= 0; current_row_count_= 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("percentile_disc") }; return name; } void update_field() override {} const Type_handler *type_handler() const override {return Type_handler_hybrid_field_type::type_handler();} bool fix_length_and_dec() override { decimals = 10; // TODO-cvicentiu find out how many decimals the standard // requires. return FALSE; } void reset_field() override { DBUG_ASSERT(0); } void set_partition_row_count(ulonglong count) override { Partition_row_count::set_partition_row_count(count); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } void setup_window_func(THD *thd, Window_spec *window_spec) override; void setup_hybrid(THD *thd, Item *item); bool fix_fields(THD *thd, Item **ref) override; private: Item_cache *value; bool val_calculated; bool first_call; double prev_value; Item *order_item; }; class Item_sum_percentile_cont : public Item_sum_double, public Partition_row_count, public Current_row_count { public: Item_sum_percentile_cont(THD *thd, Item* arg) : Item_sum_double(thd, arg), floor_value(NULL), ceil_value(NULL), first_call(TRUE),prev_value(0), ceil_val_calculated(FALSE), floor_val_calculated(FALSE), order_item(NULL){} double val_real() override { if (get_row_count() == 0 || get_arg(0)->is_null()) { null_value= true; return 0; } null_value= false; double val= 1 + prev_value * (get_row_count()-1); /* Applying the formula to get the value If (CRN = FRN = RN) then the result is (value of expression from row at RN) Otherwise the result is (CRN - RN) * (value of expression for row at FRN) + (RN - FRN) * (value of expression for row at CRN) */ if(ceil(val) == floor(val)) return floor_value->val_real(); double ret_val= ((val - floor(val)) * ceil_value->val_real()) + ((ceil(val) - val) * floor_value->val_real()); return ret_val; } bool add() override { Item *arg= get_arg(0); if (arg->is_null()) return false; if (first_call) { first_call= false; prev_value= arg->val_real(); if (prev_value > 1 || prev_value < 0) { my_error(ER_ARGUMENT_OUT_OF_RANGE, MYF(0), func_name()); return true; } } double arg_val= arg->val_real(); if (prev_value != arg_val) { my_error(ER_ARGUMENT_NOT_CONSTANT, MYF(0), func_name()); return true; } if (!floor_val_calculated) { floor_value->store(order_item); floor_value->cache_value(); if (floor_value->null_value) return false; } if (floor_val_calculated && !ceil_val_calculated) { ceil_value->store(order_item); ceil_value->cache_value(); if (ceil_value->null_value) return false; } current_row_count_++; double val= 1 + prev_value * (get_row_count()-1); if (!floor_val_calculated && get_row_number() == floor(val)) floor_val_calculated= true; if (!ceil_val_calculated && get_row_number() == ceil(val)) ceil_val_calculated= true; return false; } enum Sumfunctype sum_func() const override { return PERCENTILE_CONT_FUNC; } void clear() override { first_call= true; floor_value->clear(); ceil_value->clear(); floor_val_calculated= false; ceil_val_calculated= false; partition_row_count_= 0; current_row_count_= 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("percentile_cont") }; return name; } void update_field() override {} bool fix_length_and_dec() override { decimals = 10; // TODO-cvicentiu find out how many decimals the standard // requires. return FALSE; } void reset_field() override { DBUG_ASSERT(0); } void set_partition_row_count(ulonglong count) override { Partition_row_count::set_partition_row_count(count); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } void setup_window_func(THD *thd, Window_spec *window_spec) override; void setup_hybrid(THD *thd, Item *item); bool fix_fields(THD *thd, Item **ref) override; private: Item_cache *floor_value; Item_cache *ceil_value; bool first_call; double prev_value; bool ceil_val_calculated; bool floor_val_calculated; Item *order_item; }; class Item_window_func : public Item_func_or_sum { /* Window function parameters as we've got them from the parser */ public: LEX_CSTRING *window_name; public: Window_spec *window_spec; public: Item_window_func(THD *thd, Item_sum *win_func, LEX_CSTRING *win_name) : Item_func_or_sum(thd, (Item *) win_func), window_name(win_name), window_spec(NULL), force_return_blank(true), read_value_from_result_field(false) {} Item_window_func(THD *thd, Item_sum *win_func, Window_spec *win_spec) : Item_func_or_sum(thd, (Item *) win_func), window_name(NULL), window_spec(win_spec), force_return_blank(true), read_value_from_result_field(false) {} Item_sum *window_func() const { return (Item_sum *) args[0]; } void update_used_tables() override; /* This is used by filesort to mark the columns it needs to read (because they participate in the sort criteria and/or row retrieval. Window functions can only be used in sort criteria). Sorting by window function value is only done after the window functions have been computed. In that case, window function will need to read its temp.table field. In order to allow that, mark that field in the read_set. */ bool register_field_in_read_map(void *arg) override { TABLE *table= (TABLE*) arg; if (result_field && (result_field->table == table || !table)) { bitmap_set_bit(result_field->table->read_set, result_field->field_index); } return 0; } bool is_frame_prohibited() const { switch (window_func()->sum_func()) { case Item_sum::ROW_NUMBER_FUNC: case Item_sum::RANK_FUNC: case Item_sum::DENSE_RANK_FUNC: case Item_sum::PERCENT_RANK_FUNC: case Item_sum::CUME_DIST_FUNC: case Item_sum::NTILE_FUNC: case Item_sum::PERCENTILE_CONT_FUNC: case Item_sum::PERCENTILE_DISC_FUNC: return true; default: return false; } } bool requires_special_cursors() const { switch (window_func()->sum_func()) { case Item_sum::FIRST_VALUE_FUNC: case Item_sum::LAST_VALUE_FUNC: case Item_sum::NTH_VALUE_FUNC: case Item_sum::LAG_FUNC: case Item_sum::LEAD_FUNC: return true; default: return false; } } bool requires_partition_size() const { switch (window_func()->sum_func()) { case Item_sum::PERCENT_RANK_FUNC: case Item_sum::CUME_DIST_FUNC: case Item_sum::NTILE_FUNC: case Item_sum::PERCENTILE_CONT_FUNC: case Item_sum::PERCENTILE_DISC_FUNC: return true; default: return false; } } bool requires_peer_size() const { switch (window_func()->sum_func()) { case Item_sum::CUME_DIST_FUNC: return true; default: return false; } } bool is_order_list_mandatory() const { switch (window_func()->sum_func()) { case Item_sum::RANK_FUNC: case Item_sum::DENSE_RANK_FUNC: case Item_sum::PERCENT_RANK_FUNC: case Item_sum::CUME_DIST_FUNC: case Item_sum::LAG_FUNC: case Item_sum::LEAD_FUNC: case Item_sum::PERCENTILE_CONT_FUNC: case Item_sum::PERCENTILE_DISC_FUNC: return true; default: return false; } } bool only_single_element_order_list() const { switch (window_func()->sum_func()){ case Item_sum::PERCENTILE_CONT_FUNC: case Item_sum::PERCENTILE_DISC_FUNC: return true; default: return false; } } bool check_result_type_of_order_item(); /* Computation functions. TODO: consoder merging these with class Group_bound_tracker. */ void setup_partition_border_check(THD *thd); const Type_handler *type_handler() const override { return ((Item_sum *) args[0])->type_handler(); } enum Item::Type type() const override { return Item::WINDOW_FUNC_ITEM; } private: /* Window functions are very special functions, so val_() methods have special meaning for them: - Phase#1, "Initial" we run the join and put its result into temporary table. For window functions, we write the default value (NULL?) as a placeholder. - Phase#2: "Computation": executor does the scan in {PARTITION, ORDER BY} order of this window function. It calls appropriate methods to inform the window function about rows entering/leaving the window. It calls window_func()->val_int() so that current window function value can be saved and stored in the temp.table. - Phase#3: "Retrieval" the temporary table is read and passed to query output. However, Item_window_func still remains in the select list, so item_windowfunc->val_int() will be called. During Phase#3, read_value_from_result_field= true. */ bool force_return_blank; bool read_value_from_result_field; void print_for_percentile_functions(String *str, enum_query_type query_type); public: void set_phase_to_initial() { force_return_blank= true; read_value_from_result_field= false; } void set_phase_to_computation() { force_return_blank= false; read_value_from_result_field= false; } void set_phase_to_retrieval() { force_return_blank= false; read_value_from_result_field= true; } bool is_null() override { if (force_return_blank) return true; if (read_value_from_result_field) return result_field->is_null(); return window_func()->is_null(); } double val_real() override { double res; if (force_return_blank) { res= 0.0; null_value= true; } else if (read_value_from_result_field) { res= result_field->val_real(); null_value= result_field->is_null(); } else { res= window_func()->val_real(); null_value= window_func()->null_value; } return res; } longlong val_int() override { longlong res; if (force_return_blank) { res= 0; null_value= true; } else if (read_value_from_result_field) { res= result_field->val_int(); null_value= result_field->is_null(); } else { res= window_func()->val_int(); null_value= window_func()->null_value; } return res; } String* val_str(String* str) override { String *res; if (force_return_blank) { null_value= true; res= NULL; } else if (read_value_from_result_field) { if ((null_value= result_field->is_null())) res= NULL; else res= result_field->val_str(str); } else { res= window_func()->val_str(str); null_value= window_func()->null_value; } return res; } bool val_native(THD *thd, Native *to) override { if (force_return_blank) return null_value= true; if (read_value_from_result_field) return val_native_from_field(result_field, to); return val_native_from_item(thd, window_func(), to); } my_decimal* val_decimal(my_decimal* dec) override { my_decimal *res; if (force_return_blank) { null_value= true; res= NULL; } else if (read_value_from_result_field) { if ((null_value= result_field->is_null())) res= NULL; else res= result_field->val_decimal(dec); } else { res= window_func()->val_decimal(dec); null_value= window_func()->null_value; } return res; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { bool res; if (force_return_blank) { null_value= true; res= true; } else if (read_value_from_result_field) { if ((null_value= result_field->is_null())) res= true; else res= result_field->get_date(ltime, fuzzydate); } else { res= window_func()->get_date(thd, ltime, fuzzydate); null_value= window_func()->null_value; } return res; } void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) override; bool fix_length_and_dec() override { Type_std_attributes::set(window_func()); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("WF") }; return name; } bool fix_fields(THD *thd, Item **ref) override; bool resolve_window_name(THD *thd); void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return 0; } }; #endif /* ITEM_WINDOWFUNC_INCLUDED */ mysql/server/private/authors.h000064400000023635151027430560012543 0ustar00#ifndef AUTHORS_INCLUDED #define AUTHORS_INCLUDED /* Copyright (c) 2005, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Structure of the name list */ struct show_table_authors_st { const char *name; const char *location; const char *comment; }; /* Output from "SHOW AUTHORS" If you can update it, you get to be in it :) Don't be offended if your name is not in here, just add it! Active people in the MariaDB are listed first, active people in MySQL then, not active last. Names should be encoded using UTF-8. See also https://mariadb.com/kb/en/log-of-mariadb-contributions/ */ struct show_table_authors_st show_table_authors[]= { /* Active people on MariaDB */ { "Michael (Monty) Widenius", "Tusby, Finland", "Lead developer and main author" }, { "Sergei Golubchik", "Kerpen, Germany", "Architect, Full-text search, precision math, plugin framework, merges etc" }, { "Igor Babaev", "Bellevue, USA", "Optimizer, keycache, core work"}, { "Sergey Petrunia", "St. Petersburg, Russia", "Optimizer"}, { "Oleksandr Byelkin", "Lugansk, Ukraine", "Query Cache (4.0), Subqueries (4.1), Views (5.0)" }, { "Timour Katchaounov", "Sofia , Bulgaria", "Optimizer"}, { "Kristian Nielsen", "Copenhagen, Denmark", "Replication, Async client prototocol, General buildbot stuff" }, { "Alexander (Bar) Barkov", "Izhevsk, Russia", "Unicode and character sets" }, { "Alexey Botchkov (Holyfoot)", "Izhevsk, Russia", "GIS extensions, embedded server, precision math"}, { "Daniel Bartholomew", "Raleigh, USA", "MariaDB documentation, Buildbot, releases"}, { "Colin Charles", "Selangor, Malesia", "MariaDB documentation, talks at a LOT of conferences"}, { "Sergey Vojtovich", "Izhevsk, Russia", "initial implementation of plugin architecture, maintained native storage engines (MyISAM, MEMORY, ARCHIVE, etc), rewrite of table cache"}, { "Vladislav Vaintroub", "Mannheim, Germany", "MariaDB Java connector, new thread pool, Windows optimizations"}, { "Elena Stepanova", "Sankt Petersburg, Russia", "QA, test cases"}, { "Georg Richter", "Heidelberg, Germany", "New LGPL C connector, PHP connector"}, { "Jan Lindström", "Ylämylly, Finland", "Working on InnoDB"}, { "Lixun Peng", "Hangzhou, China", "Multi Source replication" }, { "Olivier Bertrand", "Paris, France", "CONNECT storage engine"}, { "Kentoku Shiba", "Tokyo, Japan", "Spider storage engine, metadata_lock_info Information schema"}, { "Percona", "CA, USA", "XtraDB, microslow patches, extensions to slow log"}, { "Vicentiu Ciorbaru", "Bucharest, Romania", "Roles"}, { "Sudheera Palihakkara", "", "PCRE Regular Expressions" }, { "Pavel Ivanov", "USA", "Some patches and bug fixes"}, { "Konstantin Osipov", "Moscow, Russia", "Prepared statements (4.1), Cursors (5.0), GET_LOCK (10.0)" }, { "Ian Gilfillan", "South Africa", "MariaDB documentation"}, { "Federico Razolli", "Italy", "MariaDB documentation Italian translation"}, { "Vinchen", "Shenzhen, China", "Instant ADD Column for InnoDB, Spider engine optimization, from Tencent Game DBA Team" }, { "Willhan", "Shenzhen, China", "Big Column Compression, Spider engine optimization, from Tencent Game DBA Team" }, { "Anders Karlsson", "Ystad, Sweden", "Replication patch for enforcing triggers on slave"}, { "Otto Kekäläinen", "Tampere, Finland", "Debian packaging, install/upgrade engineering, QA pipelines, documentation"}, { "Daniel Black", "Canberra, Australia", "Modernising large page support, systemd, and bug fixes"}, /* People working on MySQL code base (not NDB) */ { "Guilhem Bichot", "Bordeaux, France", "Replication (since 4.0)" }, { "Andrei Elkin", "Espoo, Finland", "Replication" }, { "Dmitri Lenev", "Moscow, Russia", "Time zones support (4.1), Triggers (5.0)" }, { "Marc Alff", "Denver, CO, USA", "Signal, Resignal, Performance schema" }, { "Mikael Ronström", "Stockholm, Sweden", "NDB Cluster, Partitioning, online alter table" }, { "Ingo Strüwing", "Berlin, Germany", "Bug fixing in MyISAM, Merge tables etc" }, {"Marko Mäkelä", "Helsinki, Finland", "InnoDB core developer"}, /* People not active anymore */ { "David Axmark", "London, England", "MySQL founder; Small stuff long time ago, Monty ripped it out!" }, { "Brian (Krow) Aker", "Seattle, WA, USA", "Architecture, archive, blackhole, federated, bunch of little stuff :)" }, { "Venu Anuganti", "", "Client/server protocol (4.1)" }, { "Omer BarNir", "Sunnyvale, CA, USA", "Testing (sometimes) and general QA stuff" }, { "John Birrell", "", "Emulation of pthread_mutex() for OS/2" }, { "Andreas F. Bobak", "", "AGGREGATE extension to user-defined functions" }, { "Reggie Burnett", "Nashville, TN, USA", "Windows development, Connectors" }, { "Kent Boortz", "Orebro, Sweden", "Test platform, and general build stuff" }, { "Tim Bunce", "", "mysqlhotcopy" }, { "Yves Carlier", "", "mysqlaccess" }, { "Joshua Chamas", "Cupertino, CA, USA", "Concurrent insert, extended date syntax" }, { "Petr Chardin", "Moscow, Russia", "Instance Manager (5.0), Server log tables (5.1)" }, { "Wei-Jou Chen", "", "Chinese (Big5) character set" }, { "Albert Chin-A-Young", "", "Tru64 port, large file support, better TCP wrappers support" }, { "Jorge del Conde", "Mexico City, Mexico", "Windows development" }, { "Antony T. Curtis", "Norwalk, CA, USA", "Parser, port to OS/2, storage engines and some random stuff" }, { "Yuri Dario", "", "OS/2 port" }, { "Patrick Galbraith", "Sharon, NH", "Federated Engine, mysqlslap" }, { "Lenz Grimmer", "Hamburg, Germany", "Production (build and release) engineering" }, { "Nikolay Grishakin", "Austin, TX, USA", "Testing - Server" }, { "Wei He", "", "Chinese (GBK) character set" }, { "Eric Herman", "Amsterdam, Netherlands", "Bug fixing - federated" }, { "Andrey Hristov", "Walldorf, Germany", "Event scheduler (5.1)" }, { "Alexander (Alexi) Ivanov", "St. Petersburg, Russia", "Replication" }, { "Mattias Jonsson", "Uppsala, Sweden", "Partitioning" }, { "Alexander (Salle) Keremidarski", "Sofia, Bulgaria", "Bug fixing" }, { "Mats Kindahl", "Storvreta, Sweden", "Replication" }, { "Serge Kozlov", "Velikie Luki, Russia", "Testing - Cluster" }, { "Hakan Küçükyılmaz", "Walldorf, Germany", "Testing - Server" }, { "Matthias Leich", "Berlin, Germany", "Testing - Server" }, { "Arjen Lentz", "Brisbane, Australia", "Documentation (2001-2004), Dutch error messages, LOG2()" }, { "Marc Liyanage", "", "Created Mac OS X packages" }, { "Kelly Long", "Denver, CO, USA", "Pool Of Threads" }, { "Zarko Mocnik", "", "Sorting for Slovenian language" }, { "Per-Erik Martin", "Uppsala, Sweden", "Stored Procedures (5.0)" }, { "Alexis Mikhailov", "", "User-defined functions" }, { "Sinisa Milivojevic", "Larnaca, Cyprus", "UNION (4.0), Subqueries in FROM clause (4.1), many other features" }, { "Jonathan (Jeb) Miller", "Kyle, TX, USA", "Testing - Cluster, Replication" }, { "Elliot Murphy", "Cocoa, FL, USA", "Replication and backup" }, { "Pekka Nouisiainen", "Stockholm, Sweden", "NDB Cluster: BLOB support, character set support, ordered indexes" }, { "Alexander Nozdrin", "Moscow, Russia", "Bug fixing (Stored Procedures, 5.0)" }, { "Per Eric Olsson", "", "Testing of dynamic record format" }, { "Jonas Oreland", "Stockholm, Sweden", "NDB Cluster, Online Backup, lots of other things" }, { "Alexander (Sasha) Pachev", "Provo, UT, USA", "Statement-based replication, SHOW CREATE TABLE, mysql-bench" }, { "Irena Pancirov", "", "Port to Windows with Borland compiler" }, { "Jan Pazdziora", "", "Czech sorting order" }, { "Benjamin Pflugmann", "", "Extended MERGE storage engine to handle INSERT" }, { "Igor Romanenko", "", "mysqldump" }, { "Tõnu Samuel", "Estonia", "VIO interface, other miscellaneous features" }, { "Carsten Segieth (Pino)", "Fredersdorf, Germany", "Testing - Server"}, { "Martin Sköld", "Stockholm, Sweden", "NDB Cluster: Unique indexes, integration into MySQL" }, { "Timothy Smith", "Auckland, New Zealand", "Dynamic character sets, parts of the build system, libmysqld"}, { "Miguel Solorzano", "Florianopolis, Santa Catarina, Brazil", "Windows development, Windows NT service"}, { "Punita Srivastava", "Austin, TX, USA", "Testing - Merlin"}, { "Alexey Stroganov (Ranger)", "Lugansk, Ukraine", "Testing - Benchmarks"}, { "Magnus Svensson", "Öregrund, Sweden", "NDB Cluster: Integration into MySQL, test framework" }, { "Zeev Suraski", "", "FROM_UNIXTIME(), ENCRYPT()" }, { "TAMITO", "", "The _MB character set macros and UJIS and SJIS character sets" }, { "Jani Tolonen", "Helsinki, Finland", "mysqlimport, extensions to command-line clients, PROCEDURE ANALYSE()" }, { "Lars Thalmann", "Stockholm, Sweden", "Replication and cluster development" }, { "Tomas Ulin", "Stockholm, Sweden", "NDB Cluster: Configuration, installation" }, { "Gianmassimo Vigazzola", "", "Initial Windows port" }, { "Sergey Vojtovich", "Izhevsk, Russia", "Plugins infrastructure (5.1)" }, { "Matt Wagner", "Northfield, MN, USA", "Bug fixing" }, { "Jim Winstead Jr.", "Los Angeles, CA, USA", "Bug fixing" }, { "Peter Zaitsev", "Tacoma, WA, USA", "SHA1(), AES_ENCRYPT(), AES_DECRYPT(), bug fixing" }, {"Mark Mark Callaghan", "Texas, USA", "Statistics patches"}, {NULL, NULL, NULL} }; #endif /* AUTHORS_INCLUDED */ mysql/server/private/sql_show.h000064400000022620151027430560012706 0ustar00/* Copyright (c) 2005, 2010, Oracle and/or its affiliates. Copyright (c) 2012, 2016, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_SHOW_H #define SQL_SHOW_H #include "sql_list.h" /* List */ #include "handler.h" /* enum_schema_tables */ #include "table.h" /* enum_schema_table_state */ #include "my_apc.h" /* Forward declarations */ class JOIN; class String; class THD; class sp_name; struct TABLE_LIST; typedef class st_select_lex SELECT_LEX; struct LEX; typedef struct st_mysql_show_var SHOW_VAR; typedef struct st_schema_table ST_SCHEMA_TABLE; struct TABLE; typedef struct system_status_var STATUS_VAR; /* Used by handlers to store things in schema tables */ #define IS_FILES_FILE_ID 0 #define IS_FILES_FILE_NAME 1 #define IS_FILES_FILE_TYPE 2 #define IS_FILES_TABLESPACE_NAME 3 #define IS_FILES_TABLE_CATALOG 4 #define IS_FILES_TABLE_SCHEMA 5 #define IS_FILES_TABLE_NAME 6 #define IS_FILES_LOGFILE_GROUP_NAME 7 #define IS_FILES_LOGFILE_GROUP_NUMBER 8 #define IS_FILES_ENGINE 9 #define IS_FILES_FULLTEXT_KEYS 10 #define IS_FILES_DELETED_ROWS 11 #define IS_FILES_UPDATE_COUNT 12 #define IS_FILES_FREE_EXTENTS 13 #define IS_FILES_TOTAL_EXTENTS 14 #define IS_FILES_EXTENT_SIZE 15 #define IS_FILES_INITIAL_SIZE 16 #define IS_FILES_MAXIMUM_SIZE 17 #define IS_FILES_AUTOEXTEND_SIZE 18 #define IS_FILES_CREATION_TIME 19 #define IS_FILES_LAST_UPDATE_TIME 20 #define IS_FILES_LAST_ACCESS_TIME 21 #define IS_FILES_RECOVER_TIME 22 #define IS_FILES_TRANSACTION_COUNTER 23 #define IS_FILES_VERSION 24 #define IS_FILES_ROW_FORMAT 25 #define IS_FILES_TABLE_ROWS 26 #define IS_FILES_AVG_ROW_LENGTH 27 #define IS_FILES_DATA_LENGTH 28 #define IS_FILES_MAX_DATA_LENGTH 29 #define IS_FILES_INDEX_LENGTH 30 #define IS_FILES_DATA_FREE 31 #define IS_FILES_CREATE_TIME 32 #define IS_FILES_UPDATE_TIME 33 #define IS_FILES_CHECK_TIME 34 #define IS_FILES_CHECKSUM 35 #define IS_FILES_STATUS 36 #define IS_FILES_EXTRA 37 typedef enum { WITHOUT_DB_NAME, WITH_DB_NAME } enum_with_db_name; int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond); int show_create_table(THD *thd, TABLE_LIST *table_list, String *packet, Table_specification_st *create_info_arg, enum_with_db_name with_db_name); int show_create_table_ex(THD *thd, TABLE_LIST *table_list, const char * forced_db, const char *forced_name, String *packet, Table_specification_st *create_info_arg, enum_with_db_name with_db_name); int copy_event_to_schema_table(THD *thd, TABLE *sch_table, TABLE *event_table); bool append_identifier(THD *thd, String *packet, const char *name, size_t length); static inline bool append_identifier(THD *thd, String *packet, const LEX_CSTRING *name) { return append_identifier(thd, packet, name->str, name->length); } void mysqld_list_fields(THD *thd,TABLE_LIST *table, const char *wild); int mysqld_dump_create_info(THD *thd, TABLE_LIST *table_list, int fd); bool mysqld_show_create_get_fields(THD *thd, TABLE_LIST *table_list, List *field_list, String *buffer); bool mysqld_show_create(THD *thd, TABLE_LIST *table_list); void mysqld_show_create_db_get_fields(THD *thd, List *field_list); bool mysqld_show_create_db(THD *thd, LEX_CSTRING *db_name, LEX_CSTRING *orig_db_name, const DDL_options_st &options); void mysqld_list_processes(THD *thd,const char *user,bool verbose); int mysqld_show_status(THD *thd); int mysqld_show_variables(THD *thd,const char *wild); bool mysqld_show_storage_engines(THD *thd); bool mysqld_show_authors(THD *thd); bool mysqld_show_contributors(THD *thd); bool mysqld_show_privileges(THD *thd); char *make_backup_log_name(char *buff, const char *name, const char* log_ext); uint calc_sum_of_all_status(STATUS_VAR *to); bool append_definer(THD *thd, String *buffer, const LEX_CSTRING *definer_user, const LEX_CSTRING *definer_host); int add_status_vars(SHOW_VAR *list); void remove_status_vars(SHOW_VAR *list); ulonglong get_status_vars_version(void); void init_status_vars(); void free_status_vars(); void reset_status_vars(); bool show_create_trigger(THD *thd, const sp_name *trg_name); void view_store_options(THD *thd, TABLE_LIST *table, String *buff); void init_fill_schema_files_row(TABLE* table); void initialize_information_schema_acl(); ST_SCHEMA_TABLE *find_schema_table(THD *thd, const LEX_CSTRING *table_name, bool *in_plugin); static inline ST_SCHEMA_TABLE *find_schema_table(THD *thd, const LEX_CSTRING *table_name) { bool unused; return find_schema_table(thd, table_name, &unused); } ST_SCHEMA_TABLE *get_schema_table(enum enum_schema_tables schema_table_idx); int make_schema_select(THD *thd, SELECT_LEX *sel, ST_SCHEMA_TABLE *schema_table); int mysql_schema_table(THD *thd, LEX *lex, TABLE_LIST *table_list); bool get_schema_tables_result(JOIN *join, enum enum_schema_table_state executed_place); enum enum_schema_tables get_schema_table_idx(ST_SCHEMA_TABLE *schema_table); TABLE *create_schema_table(THD *thd, TABLE_LIST *table_list); const char* get_one_variable(THD *thd, const SHOW_VAR *variable, enum_var_type value_type, SHOW_TYPE show_type, system_status_var *status_var, const CHARSET_INFO **charset, char *buff, size_t *length); /* These functions were under INNODB_COMPATIBILITY_HOOKS */ int get_quote_char_for_identifier(THD *thd, const char *name, size_t length); THD *find_thread_by_id(longlong id, bool query_id= false); class select_result_explain_buffer; /* SHOW EXPLAIN request object. */ class Show_explain_request : public Apc_target::Apc_call { public: THD *target_thd; /* thd that we're running SHOW EXPLAIN for */ THD *request_thd; /* thd that run SHOW EXPLAIN command */ /* If true, there was some error when producing EXPLAIN output. */ bool failed_to_produce; /* SHOW EXPLAIN will be stored here */ select_result_explain_buffer *explain_buf; /* Query that we've got SHOW EXPLAIN for */ String query_str; /* Overloaded virtual function */ void call_in_target_thread() override; }; /** Condition pushdown used for INFORMATION_SCHEMA / SHOW queries. This structure is to implement an optimization when accessing data dictionary data in the INFORMATION_SCHEMA or SHOW commands. When the query contain a TABLE_SCHEMA or TABLE_NAME clause, narrow the search for data based on the constraints given. */ typedef struct st_lookup_field_values { /** Value of a TABLE_SCHEMA clause. Note that this value length may exceed @c NAME_LEN. @sa wild_db_value */ LEX_CSTRING db_value; /** Value of a TABLE_NAME clause. Note that this value length may exceed @c NAME_LEN. @sa wild_table_value */ LEX_CSTRING table_value; /** True when @c db_value is a LIKE clause, false when @c db_value is an '=' clause. */ bool wild_db_value; /** True when @c table_value is a LIKE clause, false when @c table_value is an '=' clause. */ bool wild_table_value; } LOOKUP_FIELD_VALUES; /* INFORMATION_SCHEMA: Execution plan for get_all_tables() call */ class IS_table_read_plan : public Sql_alloc { public: IS_table_read_plan() : no_rows(false), trivial_show_command(FALSE) {} bool no_rows; /* For EXPLAIN only: For SHOW KEYS and SHOW COLUMNS, we know which db_name.table_name will be read, however for some reason we don't set the fields in this->lookup_field_vals. In order to not have JOIN::save_explain_data() walking over uninitialized data, we set trivial_show_command=true. */ bool trivial_show_command; LOOKUP_FIELD_VALUES lookup_field_vals; Item *partial_cond; bool has_db_lookup_value() { return (lookup_field_vals.db_value.length && !lookup_field_vals.wild_db_value); } bool has_table_lookup_value() { return (lookup_field_vals.table_value.length && !lookup_field_vals.wild_table_value); } }; bool optimize_schema_tables_reads(JOIN *join); bool optimize_schema_tables_memory_usage(List &tables); /* Handle the ignored database directories list for SHOW/I_S. */ bool ignore_db_dirs_init(); void ignore_db_dirs_free(); void ignore_db_dirs_reset(); bool ignore_db_dirs_process_additions(); bool push_ignored_db_dir(const char *path); extern char *opt_ignore_db_dirs; #endif /* SQL_SHOW_H */ mysql/server/private/grant.h000064400000005306151027430560012164 0ustar00/* Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_GRANT_INCLUDED #define SQL_GRANT_INCLUDED #include "lex_string.h" #include "privilege.h" class LEX_COLUMN; class Lex_ident_sys; class Table_ident; /* Represents the object name in this standard SQL grammar: GRANT ON */ class Grant_object_name { public: enum Type { STAR, // ON * IDENT_STAR, // ON db.* STAR_STAR, // ON *.* TABLE_IDENT // ON db.name }; Lex_cstring m_db; Table_ident *m_table_ident; Type m_type; public: Grant_object_name(Table_ident *table_ident) :m_table_ident(table_ident), m_type(TABLE_IDENT) { } Grant_object_name(const LEX_CSTRING &db, Type type) :m_db(db), m_table_ident(NULL), m_type(type) { } privilege_t all_privileges_by_type() const; }; /* Represents standard SQL statements described by: - - */ class Grant_privilege { protected: List m_columns; Lex_cstring m_db; privilege_t m_object_privilege; privilege_t m_column_privilege_total; bool m_all_privileges; public: Grant_privilege() :m_object_privilege(NO_ACL), m_column_privilege_total(NO_ACL), m_all_privileges(false) { } Grant_privilege(privilege_t privilege, bool all_privileges) :m_object_privilege(privilege), m_column_privilege_total(NO_ACL), m_all_privileges(all_privileges) { } void add_object_privilege(privilege_t privilege) { m_object_privilege|= privilege; } bool add_column_privilege(THD *thd, const Lex_ident_sys &col, privilege_t privilege); bool add_column_list_privilege(THD *thd, List &list, privilege_t privilege); bool set_object_name(THD *thd, const Grant_object_name &ident, SELECT_LEX *sel, privilege_t with_grant_option); const List & columns() const { return m_columns; } }; #endif // SQL_GRANT_INCLUDED mysql/server/private/compat56.h000064400000004350151027430560012505 0ustar00#ifndef COMPAT56_H_INCLUDED #define COMPAT56_H_INCLUDED /* Copyright (c) 2004, 2012, Oracle and/or its affiliates. Copyright (c) 2013 MariaDB Foundation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** MySQL56 routines and macros **/ /* Buffer size for a native TIMESTAMP representation, for use with NativBuffer. 4 bytes for seconds 3 bytes for microseconds 1 byte for the trailing '\0' (class Native reserves extra 1 byte for '\0') */ #define STRING_BUFFER_TIMESTAMP_BINARY_SIZE 8 /* 4 + 3 + 1 */ #define MY_PACKED_TIME_GET_INT_PART(x) ((x) >> 24) #define MY_PACKED_TIME_GET_FRAC_PART(x) ((x) % (1LL << 24)) #define MY_PACKED_TIME_MAKE(i, f) ((((ulonglong) (i)) << 24) + (f)) #define MY_PACKED_TIME_MAKE_INT(i) ((((ulonglong) (i)) << 24)) longlong TIME_to_longlong_datetime_packed(const MYSQL_TIME *); longlong TIME_to_longlong_time_packed(const MYSQL_TIME *); void TIME_from_longlong_datetime_packed(MYSQL_TIME *ltime, longlong nr); void TIME_from_longlong_time_packed(MYSQL_TIME *ltime, longlong nr); void my_datetime_packed_to_binary(longlong nr, uchar *ptr, uint dec); longlong my_datetime_packed_from_binary(const uchar *ptr, uint dec); uint my_datetime_binary_length(uint dec); void my_time_packed_to_binary(longlong nr, uchar *ptr, uint dec); longlong my_time_packed_from_binary(const uchar *ptr, uint dec); uint my_time_binary_length(uint dec); void my_timestamp_to_binary(const struct timeval *tm, uchar *ptr, uint dec); void my_timestamp_from_binary(struct timeval *tm, const uchar *ptr, uint dec); uint my_timestamp_binary_length(uint dec); /** End of MySQL routines and macros **/ #endif /* COMPAT56_H_INCLUDED */ mysql/server/private/sql_truncate.h000064400000004037151027430560013555 0ustar00#ifndef SQL_TRUNCATE_INCLUDED #define SQL_TRUNCATE_INCLUDED /* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ class THD; struct TABLE_LIST; /** Sql_cmd_truncate_table represents the TRUNCATE statement. */ class Sql_cmd_truncate_table : public Sql_cmd { private: /* Set if a lock must be downgraded after truncate is done. */ MDL_ticket *m_ticket_downgrade; public: /** Constructor, used to represent a TRUNCATE statement. */ Sql_cmd_truncate_table() = default; virtual ~Sql_cmd_truncate_table() = default; /** Execute a TRUNCATE statement at runtime. @param thd the current thread. @return false on success. */ bool execute(THD *thd) override; enum_sql_command sql_command_code() const override { return SQLCOM_TRUNCATE; } protected: enum truncate_result{ TRUNCATE_OK=0, TRUNCATE_FAILED_BUT_BINLOG, TRUNCATE_FAILED_SKIP_BINLOG }; /** Handle locking a base table for truncate. */ bool lock_table(THD *, TABLE_LIST *, bool *); /** Truncate table via the handler method. */ enum truncate_result handler_truncate(THD *, TABLE_LIST *, bool); /** Optimized delete of all rows by doing a full regenerate of the table. Depending on the storage engine, it can be accomplished through a drop and recreate or via the handler truncate method. */ bool truncate_table(THD *, TABLE_LIST *); }; #endif mysql/server/private/mdl.h000064400000113104151027430560011621 0ustar00#ifndef MDL_H #define MDL_H /* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2020, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_plist.h" #include "ilist.h" #include #include #include #include class THD; class MDL_context; class MDL_lock; class MDL_ticket; bool ok_for_lower_case_names(const char *name); typedef unsigned short mdl_bitmap_t; #define MDL_BIT(A) static_cast(1U << A) /** @def ENTER_COND(C, M, S, O) Start a wait on a condition. @param C the condition to wait on @param M the associated mutex @param S the new stage to enter @param O the previous stage @sa EXIT_COND(). */ #define ENTER_COND(C, M, S, O) enter_cond(C, M, S, O, __func__, __FILE__, __LINE__) /** @def EXIT_COND(S) End a wait on a condition @param S the new stage to enter */ #define EXIT_COND(S) exit_cond(S, __func__, __FILE__, __LINE__) /** An interface to separate the MDL module from the THD, and the rest of the server code. */ class MDL_context_owner { public: virtual ~MDL_context_owner() = default; /** Enter a condition wait. For @c enter_cond() / @c exit_cond() to work the mutex must be held before @c enter_cond(); this mutex is then released by @c exit_cond(). Usage must be: lock mutex; enter_cond(); your code; exit_cond(). @param cond the condition to wait on @param mutex the associated mutex @param [in] stage the stage to enter, or NULL @param [out] old_stage the previous stage, or NULL @param src_function function name of the caller @param src_file file name of the caller @param src_line line number of the caller @sa ENTER_COND(), THD::enter_cond() @sa EXIT_COND(), THD::exit_cond() */ virtual void enter_cond(mysql_cond_t *cond, mysql_mutex_t *mutex, const PSI_stage_info *stage, PSI_stage_info *old_stage, const char *src_function, const char *src_file, int src_line) = 0; /** @def EXIT_COND(S) End a wait on a condition @param [in] stage the new stage to enter @param src_function function name of the caller @param src_file file name of the caller @param src_line line number of the caller @sa ENTER_COND(), THD::enter_cond() @sa EXIT_COND(), THD::exit_cond() */ virtual void exit_cond(const PSI_stage_info *stage, const char *src_function, const char *src_file, int src_line) = 0; /** Has the owner thread been killed? */ virtual int is_killed() = 0; /** This one is only used for DEBUG_SYNC. (Do not use it to peek/poke into other parts of THD.) */ virtual THD* get_thd() = 0; /** @see THD::notify_shared_lock() */ virtual bool notify_shared_lock(MDL_context_owner *in_use, bool needs_thr_lock_abort) = 0; }; /** Type of metadata lock request. @sa Comments for MDL_object_lock::can_grant_lock() and MDL_scoped_lock::can_grant_lock() for details. Scoped locks are database (or schema) locks. The object locks are for tables, triggers etc. */ enum enum_mdl_type { /* This means that the MDL_request is not initialized */ MDL_NOT_INITIALIZED= -1, /* An intention exclusive metadata lock (IX). Used only for scoped locks. Owner of this type of lock can acquire upgradable exclusive locks on individual objects. Compatible with other IX locks, but is incompatible with scoped S and X locks. IX lock is taken in SCHEMA namespace when we intend to modify object metadata. Object may refer table, stored procedure, trigger, view/etc. */ MDL_INTENTION_EXCLUSIVE= 0, /* A shared metadata lock (S). To be used in cases when we are interested in object metadata only and there is no intention to access object data (e.g. for stored routines or during preparing prepared statements). We also mis-use this type of lock for open HANDLERs, since lock acquired by this statement has to be compatible with lock acquired by LOCK TABLES ... WRITE statement, i.e. SNRW (We can't get by by acquiring S lock at HANDLER ... OPEN time and upgrading it to SR lock for HANDLER ... READ as it doesn't solve problem with need to abort DML statements which wait on table level lock while having open HANDLER in the same connection). To avoid deadlock which may occur when SNRW lock is being upgraded to X lock for table on which there is an active S lock which is owned by thread which waits in its turn for table-level lock owned by thread performing upgrade we have to use thr_abort_locks_for_thread() facility in such situation. This problem does not arise for locks on stored routines as we don't use SNRW locks for them. It also does not arise when S locks are used during PREPARE calls as table-level locks are not acquired in this case. This lock is taken for global read lock, when caching a stored procedure in memory for the duration of the transaction and for tables used by prepared statements. */ MDL_SHARED, /* A high priority shared metadata lock. Used for cases when there is no intention to access object data (i.e. data in the table). "High priority" means that, unlike other shared locks, it is granted ignoring pending requests for exclusive locks. Intended for use in cases when we only need to access metadata and not data, e.g. when filling an INFORMATION_SCHEMA table. Since SH lock is compatible with SNRW lock, the connection that holds SH lock lock should not try to acquire any kind of table-level or row-level lock, as this can lead to a deadlock. Moreover, after acquiring SH lock, the connection should not wait for any other resource, as it might cause starvation for X locks and a potential deadlock during upgrade of SNW or SNRW to X lock (e.g. if the upgrading connection holds the resource that is being waited for). */ MDL_SHARED_HIGH_PRIO, /* A shared metadata lock (SR) for cases when there is an intention to read data from table. A connection holding this kind of lock can read table metadata and read table data (after acquiring appropriate table and row-level locks). This means that one can only acquire TL_READ, TL_READ_NO_INSERT, and similar table-level locks on table if one holds SR MDL lock on it. To be used for tables in SELECTs, subqueries, and LOCK TABLE ... READ statements. */ MDL_SHARED_READ, /* A shared metadata lock (SW) for cases when there is an intention to modify (and not just read) data in the table. A connection holding SW lock can read table metadata and modify or read table data (after acquiring appropriate table and row-level locks). To be used for tables to be modified by INSERT, UPDATE, DELETE statements, but not LOCK TABLE ... WRITE or DDL). Also taken by SELECT ... FOR UPDATE. */ MDL_SHARED_WRITE, /* An upgradable shared metadata lock for cases when there is an intention to modify (and not just read) data in the table. Can be upgraded to MDL_SHARED_NO_WRITE and MDL_EXCLUSIVE. A connection holding SU lock can read table metadata and modify or read table data (after acquiring appropriate table and row-level locks). To be used for the first phase of ALTER TABLE. */ MDL_SHARED_UPGRADABLE, /* A shared metadata lock for cases when we need to read data from table and block all concurrent modifications to it (for both data and metadata). Used by LOCK TABLES READ statement. */ MDL_SHARED_READ_ONLY, /* An upgradable shared metadata lock which blocks all attempts to update table data, allowing reads. A connection holding this kind of lock can read table metadata and read table data. Can be upgraded to X metadata lock. Note, that since this type of lock is not compatible with SNRW or SW lock types, acquiring appropriate engine-level locks for reading (TL_READ* for MyISAM, shared row locks in InnoDB) should be contention-free. To be used for the first phase of ALTER TABLE, when copying data between tables, to allow concurrent SELECTs from the table, but not UPDATEs. */ MDL_SHARED_NO_WRITE, /* An upgradable shared metadata lock which allows other connections to access table metadata, but not data. It blocks all attempts to read or update table data, while allowing INFORMATION_SCHEMA and SHOW queries. A connection holding this kind of lock can read table metadata modify and read table data. Can be upgraded to X metadata lock. To be used for LOCK TABLES WRITE statement. Not compatible with any other lock type except S and SH. */ MDL_SHARED_NO_READ_WRITE, /* An exclusive metadata lock (X). A connection holding this lock can modify both table's metadata and data. No other type of metadata lock can be granted while this lock is held. To be used for CREATE/DROP/RENAME TABLE statements and for execution of certain phases of other DDL statements. */ MDL_EXCLUSIVE, /* This should be the last !!! */ MDL_TYPE_END }; /** Backup locks */ /** Block concurrent backup */ #define MDL_BACKUP_START enum_mdl_type(0) /** Block new write requests to non transactional tables */ #define MDL_BACKUP_FLUSH enum_mdl_type(1) /** In addition to previous locks, blocks running requests to non trans tables Used to wait until all DML usage of on trans tables are finished */ #define MDL_BACKUP_WAIT_FLUSH enum_mdl_type(2) /** In addition to previous locks, blocks new DDL's from starting */ #define MDL_BACKUP_WAIT_DDL enum_mdl_type(3) /** In addition to previous locks, blocks commits */ #define MDL_BACKUP_WAIT_COMMIT enum_mdl_type(4) /** Blocks (or is blocked by) statements that intend to modify data. Acquired before commit lock by FLUSH TABLES WITH READ LOCK. */ #define MDL_BACKUP_FTWRL1 enum_mdl_type(5) /** Blocks (or is blocked by) commits. Acquired after global read lock by FLUSH TABLES WITH READ LOCK. */ #define MDL_BACKUP_FTWRL2 enum_mdl_type(6) #define MDL_BACKUP_DML enum_mdl_type(7) #define MDL_BACKUP_TRANS_DML enum_mdl_type(8) #define MDL_BACKUP_SYS_DML enum_mdl_type(9) /** Must be acquired by DDL statements that intend to modify data. Currently it's also used for LOCK TABLES. */ #define MDL_BACKUP_DDL enum_mdl_type(10) /** Blocks new DDL's. Used by backup code to enable DDL logging */ #define MDL_BACKUP_BLOCK_DDL enum_mdl_type(11) /* Statement is modifying data, but will not block MDL_BACKUP_DDL or earlier BACKUP stages. ALTER TABLE is started with MDL_BACKUP_DDL, but changed to MDL_BACKUP_ALTER_COPY while alter table is copying or modifing data. */ #define MDL_BACKUP_ALTER_COPY enum_mdl_type(12) /** Must be acquired during commit. */ #define MDL_BACKUP_COMMIT enum_mdl_type(13) #define MDL_BACKUP_END enum_mdl_type(14) /** Duration of metadata lock. */ enum enum_mdl_duration { /** Locks with statement duration are automatically released at the end of statement or transaction. */ MDL_STATEMENT= 0, /** Locks with transaction duration are automatically released at the end of transaction. */ MDL_TRANSACTION, /** Locks with explicit duration survive the end of statement and transaction. They have to be released explicitly by calling MDL_context::release_lock(). */ MDL_EXPLICIT, /* This should be the last ! */ MDL_DURATION_END }; /** Maximal length of key for metadata locking subsystem. */ #define MAX_MDLKEY_LENGTH (1 + NAME_LEN + 1 + NAME_LEN + 1) /** Metadata lock object key. A lock is requested or granted based on a fully qualified name and type. E.g. They key for a table consists of <0 (=table)>++. Elsewhere in the comments this triple will be referred to simply as "key" or "name". */ struct MDL_key { public: #ifdef HAVE_PSI_INTERFACE static void init_psi_keys(); #endif /** Object namespaces. Sic: when adding a new member to this enum make sure to update m_namespace_to_wait_state_name array in mdl.cc and metadata_lock_info_lock_name in metadata_lock_info.cc! Different types of objects exist in different namespaces - SCHEMA is for databases (to protect against DROP DATABASE) - TABLE is for tables and views. - BACKUP is for locking DML, DDL and COMMIT's during BACKUP STAGES - FUNCTION is for stored functions. - PROCEDURE is for stored procedures. - TRIGGER is for triggers. - EVENT is for event scheduler events Note that although there isn't metadata locking on triggers, it's necessary to have a separate namespace for them since MDL_key is also used outside of the MDL subsystem. */ enum enum_mdl_namespace { BACKUP=0, SCHEMA, TABLE, FUNCTION, PROCEDURE, PACKAGE_BODY, TRIGGER, EVENT, USER_LOCK, /* user level locks. */ /* This should be the last ! */ NAMESPACE_END }; const uchar *ptr() const { return (uchar*) m_ptr; } uint length() const { return m_length; } const char *db_name() const { return m_ptr + 1; } uint db_name_length() const { return m_db_name_length; } const char *name() const { return m_ptr + m_db_name_length + 2; } uint name_length() const { return m_length - m_db_name_length - 3; } enum_mdl_namespace mdl_namespace() const { return (enum_mdl_namespace)(m_ptr[0]); } /** Construct a metadata lock key from a triplet (mdl_namespace, database and name). @remark The key for a table is ++
@param mdl_namespace Id of namespace of object to be locked @param db Name of database to which the object belongs @param name Name of of the object @param key Where to store the the MDL key. */ void mdl_key_init(enum_mdl_namespace mdl_namespace_arg, const char *db, const char *name_arg) { m_ptr[0]= (char) mdl_namespace_arg; /* It is responsibility of caller to ensure that db and object names are not longer than NAME_LEN. Still we play safe and try to avoid buffer overruns. */ DBUG_ASSERT(strlen(db) <= NAME_LEN); DBUG_ASSERT(strlen(name_arg) <= NAME_LEN); m_db_name_length= static_cast(strmake(m_ptr + 1, db, NAME_LEN) - m_ptr - 1); m_length= static_cast(strmake(m_ptr + m_db_name_length + 2, name_arg, NAME_LEN) - m_ptr + 1); m_hash_value= my_hash_sort(&my_charset_bin, (uchar*) m_ptr + 1, m_length - 1); DBUG_SLOW_ASSERT(mdl_namespace_arg == USER_LOCK || ok_for_lower_case_names(db)); } void mdl_key_init(const MDL_key *rhs) { memcpy(m_ptr, rhs->m_ptr, rhs->m_length); m_length= rhs->m_length; m_db_name_length= rhs->m_db_name_length; m_hash_value= rhs->m_hash_value; } bool is_equal(const MDL_key *rhs) const { return (m_length == rhs->m_length && memcmp(m_ptr, rhs->m_ptr, m_length) == 0); } /** Compare two MDL keys lexicographically. */ int cmp(const MDL_key *rhs) const { /* The key buffer is always '\0'-terminated. Since key character set is utf-8, we can safely assume that no character starts with a zero byte. */ return memcmp(m_ptr, rhs->m_ptr, MY_MIN(m_length, rhs->m_length)); } MDL_key(const MDL_key *rhs) { mdl_key_init(rhs); } MDL_key(enum_mdl_namespace namespace_arg, const char *db_arg, const char *name_arg) { mdl_key_init(namespace_arg, db_arg, name_arg); } MDL_key() = default; /* To use when part of MDL_request. */ /** Get thread state name to be used in case when we have to wait on resource identified by key. */ const PSI_stage_info * get_wait_state_name() const { return & m_namespace_to_wait_state_name[(int)mdl_namespace()]; } my_hash_value_type hash_value() const { return m_hash_value + mdl_namespace(); } my_hash_value_type tc_hash_value() const { return m_hash_value; } private: uint16 m_length; uint16 m_db_name_length; my_hash_value_type m_hash_value; char m_ptr[MAX_MDLKEY_LENGTH]; static PSI_stage_info m_namespace_to_wait_state_name[NAMESPACE_END]; private: MDL_key(const MDL_key &); /* not implemented */ MDL_key &operator=(const MDL_key &); /* not implemented */ friend my_hash_value_type mdl_hash_function(CHARSET_INFO *, const uchar *, size_t); }; /** A pending metadata lock request. A lock request and a granted metadata lock are represented by different classes because they have different allocation sites and hence different lifetimes. The allocation of lock requests is controlled from outside of the MDL subsystem, while allocation of granted locks (tickets) is controlled within the MDL subsystem. MDL_request is a C structure, you don't need to call a constructor or destructor for it. */ class MDL_request { public: /** Type of metadata lock. */ enum enum_mdl_type type; /** Duration for requested lock. */ enum enum_mdl_duration duration; /** Pointers for participating in the list of lock requests for this context. */ MDL_request *next_in_list; MDL_request **prev_in_list; /** Pointer to the lock ticket object for this lock request. Valid only if this lock request is satisfied. */ MDL_ticket *ticket; /** A lock is requested based on a fully qualified name and type. */ MDL_key key; const char *m_src_file; uint m_src_line; public: static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } static void operator delete(void *, MEM_ROOT *) {} void init_with_source(MDL_key::enum_mdl_namespace namespace_arg, const char *db_arg, const char *name_arg, enum_mdl_type mdl_type_arg, enum_mdl_duration mdl_duration_arg, const char *src_file, uint src_line); void init_by_key_with_source(const MDL_key *key_arg, enum_mdl_type mdl_type_arg, enum_mdl_duration mdl_duration_arg, const char *src_file, uint src_line); /** Set type of lock request. Can be only applied to pending locks. */ inline void set_type(enum_mdl_type type_arg) { DBUG_ASSERT(ticket == NULL); type= type_arg; } void move_from(MDL_request &from) { type= from.type; duration= from.duration; ticket= from.ticket; next_in_list= from.next_in_list; prev_in_list= from.prev_in_list; key.mdl_key_init(&from.key); from.ticket= NULL; // that's what "move" means } /** Is this a request for a lock which allow data to be updated? @note This method returns true for MDL_SHARED_UPGRADABLE type of lock. Even though this type of lock doesn't allow updates it will always be upgraded to one that does. */ bool is_write_lock_request() const { return (type >= MDL_SHARED_WRITE && type != MDL_SHARED_READ_ONLY); } /* This is to work around the ugliness of TABLE_LIST compiler-generated assignment operator. It is currently used in several places to quickly copy "most" of the members of the table list. These places currently never assume that the mdl request is carried over to the new TABLE_LIST, or shared between lists. This method does not initialize the instance being assigned! Use of init() for initialization after this assignment operator is mandatory. Can only be used before the request has been granted. */ MDL_request& operator=(const MDL_request &) { type= MDL_NOT_INITIALIZED; ticket= NULL; /* Do nothing, in particular, don't try to copy the key. */ return *this; } /* Another piece of ugliness for TABLE_LIST constructor */ MDL_request(): type(MDL_NOT_INITIALIZED), ticket(NULL) {} MDL_request(const MDL_request *rhs) :type(rhs->type), duration(rhs->duration), ticket(NULL), key(&rhs->key) {} }; typedef void (*mdl_cached_object_release_hook)(void *); #define MDL_REQUEST_INIT(R, P1, P2, P3, P4, P5) \ (*R).init_with_source(P1, P2, P3, P4, P5, __FILE__, __LINE__) #define MDL_REQUEST_INIT_BY_KEY(R, P1, P2, P3) \ (*R).init_by_key_with_source(P1, P2, P3, __FILE__, __LINE__) /** An abstract class for inspection of a connected subgraph of the wait-for graph. */ class MDL_wait_for_graph_visitor { public: virtual bool enter_node(MDL_context *node) = 0; virtual void leave_node(MDL_context *node) = 0; virtual bool inspect_edge(MDL_context *dest) = 0; virtual ~MDL_wait_for_graph_visitor(); MDL_wait_for_graph_visitor() = default; }; /** Abstract class representing an edge in the waiters graph to be traversed by deadlock detection algorithm. */ class MDL_wait_for_subgraph { public: virtual ~MDL_wait_for_subgraph(); /** Accept a wait-for graph visitor to inspect the node this edge is leading to. */ virtual bool accept_visitor(MDL_wait_for_graph_visitor *gvisitor) = 0; enum enum_deadlock_weight { DEADLOCK_WEIGHT_FTWRL1= 0, DEADLOCK_WEIGHT_DML= 1, DEADLOCK_WEIGHT_DDL= 100 }; /* A helper used to determine which lock request should be aborted. */ virtual uint get_deadlock_weight() const = 0; }; /** A granted metadata lock. @warning MDL_ticket members are private to the MDL subsystem. @note Multiple shared locks on a same object are represented by a single ticket. The same does not apply for other lock types. @note There are two groups of MDL_ticket members: - "Externally accessible". These members can be accessed from threads/contexts different than ticket owner in cases when ticket participates in some list of granted or waiting tickets for a lock. Therefore one should change these members before including then to waiting/granted lists or while holding lock protecting those lists. - "Context private". Such members are private to thread/context owning this ticket. I.e. they should not be accessed from other threads/contexts. */ class MDL_ticket : public MDL_wait_for_subgraph, public ilist_node<> { public: /** Pointers for participating in the list of lock requests for this context. Context private. */ MDL_ticket *next_in_context; MDL_ticket **prev_in_context; public: #ifdef WITH_WSREP void wsrep_report(bool debug) const; #endif /* WITH_WSREP */ bool has_pending_conflicting_lock() const; MDL_context *get_ctx() const { return m_ctx; } bool is_upgradable_or_exclusive() const { return m_type == MDL_SHARED_UPGRADABLE || m_type == MDL_SHARED_NO_WRITE || m_type == MDL_SHARED_NO_READ_WRITE || m_type == MDL_EXCLUSIVE; } enum_mdl_type get_type() const { return m_type; } const LEX_STRING *get_type_name() const; const LEX_STRING *get_type_name(enum_mdl_type type) const; MDL_lock *get_lock() const { return m_lock; } MDL_key *get_key() const; void downgrade_lock(enum_mdl_type type); bool has_stronger_or_equal_type(enum_mdl_type type) const; bool is_incompatible_when_granted(enum_mdl_type type) const; bool is_incompatible_when_waiting(enum_mdl_type type) const; /** Implement MDL_wait_for_subgraph interface. */ bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor) override; uint get_deadlock_weight() const override; /** Status of lock request represented by the ticket as reflected in P_S. */ enum enum_psi_status { PENDING = 0, GRANTED, PRE_ACQUIRE_NOTIFY, POST_RELEASE_NOTIFY }; private: friend class MDL_context; MDL_ticket(MDL_context *ctx_arg, enum_mdl_type type_arg #ifndef DBUG_OFF , enum_mdl_duration duration_arg #endif ) : m_type(type_arg), #ifndef DBUG_OFF m_duration(duration_arg), #endif m_ctx(ctx_arg), m_lock(NULL), m_psi(NULL) {} virtual ~MDL_ticket() { DBUG_ASSERT(m_psi == NULL); } static MDL_ticket *create(MDL_context *ctx_arg, enum_mdl_type type_arg #ifndef DBUG_OFF , enum_mdl_duration duration_arg #endif ); static void destroy(MDL_ticket *ticket); private: /** Type of metadata lock. Externally accessible. */ enum enum_mdl_type m_type; #ifndef DBUG_OFF /** Duration of lock represented by this ticket. Context private. Debug-only. */ enum_mdl_duration m_duration; #endif /** Context of the owner of the metadata lock ticket. Externally accessible. */ MDL_context *m_ctx; /** Pointer to the lock object for this lock ticket. Externally accessible. */ MDL_lock *m_lock; PSI_metadata_lock *m_psi; private: MDL_ticket(const MDL_ticket &); /* not implemented */ MDL_ticket &operator=(const MDL_ticket &); /* not implemented */ }; /** Savepoint for MDL context. Doesn't include metadata locks with explicit duration as they are not released during rollback to savepoint. */ class MDL_savepoint { public: MDL_savepoint() = default;; private: MDL_savepoint(MDL_ticket *stmt_ticket, MDL_ticket *trans_ticket) : m_stmt_ticket(stmt_ticket), m_trans_ticket(trans_ticket) {} friend class MDL_context; private: /** Pointer to last lock with statement duration which was taken before creation of savepoint. */ MDL_ticket *m_stmt_ticket; /** Pointer to last lock with transaction duration which was taken before creation of savepoint. */ MDL_ticket *m_trans_ticket; }; /** A reliable way to wait on an MDL lock. */ class MDL_wait { public: MDL_wait(); ~MDL_wait(); enum enum_wait_status { EMPTY = 0, GRANTED, VICTIM, TIMEOUT, KILLED }; bool set_status(enum_wait_status result_arg); enum_wait_status get_status(); void reset_status(); enum_wait_status timed_wait(MDL_context_owner *owner, struct timespec *abs_timeout, bool signal_timeout, const PSI_stage_info *wait_state_name); private: /** Condvar which is used for waiting until this context's pending request can be satisfied or this thread has to perform actions to resolve a potential deadlock (we subscribe to such notification by adding a ticket corresponding to the request to an appropriate queue of waiters). */ mysql_mutex_t m_LOCK_wait_status; mysql_cond_t m_COND_wait_status; enum_wait_status m_wait_status; }; typedef I_P_List, I_P_List_counter> MDL_request_list; /** Context of the owner of metadata locks. I.e. each server connection has such a context. */ class MDL_context { public: typedef I_P_List > Ticket_list; typedef Ticket_list::Iterator Ticket_iterator; MDL_context(); void destroy(); bool try_acquire_lock(MDL_request *mdl_request); bool acquire_lock(MDL_request *mdl_request, double lock_wait_timeout); bool acquire_locks(MDL_request_list *requests, double lock_wait_timeout); bool upgrade_shared_lock(MDL_ticket *mdl_ticket, enum_mdl_type new_type, double lock_wait_timeout); bool clone_ticket(MDL_request *mdl_request); void release_all_locks_for_name(MDL_ticket *ticket); void release_lock(MDL_ticket *ticket); bool is_lock_owner(MDL_key::enum_mdl_namespace mdl_namespace, const char *db, const char *name, enum_mdl_type mdl_type); unsigned long get_lock_owner(MDL_key *mdl_key); bool has_lock(const MDL_savepoint &mdl_savepoint, MDL_ticket *mdl_ticket); inline bool has_locks() const { return !(m_tickets[MDL_STATEMENT].is_empty() && m_tickets[MDL_TRANSACTION].is_empty() && m_tickets[MDL_EXPLICIT].is_empty()); } bool has_explicit_locks() const { return !m_tickets[MDL_EXPLICIT].is_empty(); } inline bool has_transactional_locks() const { return !m_tickets[MDL_TRANSACTION].is_empty(); } MDL_savepoint mdl_savepoint() { return MDL_savepoint(m_tickets[MDL_STATEMENT].front(), m_tickets[MDL_TRANSACTION].front()); } void set_explicit_duration_for_all_locks(); void set_transaction_duration_for_all_locks(); void set_lock_duration(MDL_ticket *mdl_ticket, enum_mdl_duration duration); void release_statement_locks(); void release_transactional_locks(THD *thd); void release_explicit_locks(); void rollback_to_savepoint(const MDL_savepoint &mdl_savepoint); MDL_context_owner *get_owner() { return m_owner; } /** @pre Only valid if we started waiting for lock. */ inline uint get_deadlock_weight() const { return m_waiting_for->get_deadlock_weight() + m_deadlock_overweight; } void inc_deadlock_overweight() { m_deadlock_overweight++; } /** Post signal to the context (and wake it up if necessary). @retval FALSE - Success, signal was posted. @retval TRUE - Failure, signal was not posted since context already has received some signal or closed signal slot. */ void init(MDL_context_owner *arg) { m_owner= arg; reset(); } void reset() { m_deadlock_overweight= 0; } void set_needs_thr_lock_abort(bool needs_thr_lock_abort) { /* @note In theory, this member should be modified under protection of some lock since it can be accessed from different threads. In practice, this is not necessary as code which reads this value and so might miss the fact that value was changed will always re-try reading it after small timeout and therefore will see the new value eventually. */ m_needs_thr_lock_abort= needs_thr_lock_abort; } bool get_needs_thr_lock_abort() const { return m_needs_thr_lock_abort; } public: /** If our request for a lock is scheduled, or aborted by the deadlock detector, the result is recorded in this class. */ MDL_wait m_wait; private: /** Lists of all MDL tickets acquired by this connection. Lists of MDL tickets: --------------------- The entire set of locks acquired by a connection can be separated in three subsets according to their duration: locks released at the end of statement, at the end of transaction and locks are released explicitly. Statement and transactional locks are locks with automatic scope. They are accumulated in the course of a transaction, and released either at the end of uppermost statement (for statement locks) or on COMMIT, ROLLBACK or ROLLBACK TO SAVEPOINT (for transactional locks). They must not be (and never are) released manually, i.e. with release_lock() call. Tickets with explicit duration are taken for locks that span multiple transactions or savepoints. These are: HANDLER SQL locks (HANDLER SQL is transaction-agnostic), LOCK TABLES locks (you can COMMIT/etc under LOCK TABLES, and the locked tables stay locked), user level locks (GET_LOCK()/RELEASE_LOCK() functions) and locks implementing "global read lock". Statement/transactional locks are always prepended to the beginning of the appropriate list. In other words, they are stored in reverse temporal order. Thus, when we rollback to a savepoint, we start popping and releasing tickets from the front until we reach the last ticket acquired after the savepoint. Locks with explicit duration are not stored in any particular order, and among each other can be split into four sets: [LOCK TABLES locks] [USER locks] [HANDLER locks] [GLOBAL READ LOCK locks] The following is known about these sets: * GLOBAL READ LOCK locks are always stored last. This is because one can't say SET GLOBAL read_only=1 or FLUSH TABLES WITH READ LOCK if one has locked tables. One can, however, LOCK TABLES after having entered the read only mode. Note, that subsequent LOCK TABLES statement will unlock the previous set of tables, but not the GRL! There are no HANDLER locks after GRL locks because SET GLOBAL read_only performs a FLUSH TABLES WITH READ LOCK internally, and FLUSH TABLES, in turn, implicitly closes all open HANDLERs. However, one can open a few HANDLERs after entering the read only mode. * LOCK TABLES locks include intention exclusive locks on involved schemas and global intention exclusive lock. */ Ticket_list m_tickets[MDL_DURATION_END]; MDL_context_owner *m_owner; /** TRUE - if for this context we will break protocol and try to acquire table-level locks while having only S lock on some table. To avoid deadlocks which might occur during concurrent upgrade of SNRW lock on such object to X lock we have to abort waits for table-level locks for such connections. FALSE - Otherwise. */ bool m_needs_thr_lock_abort; /** Read-write lock protecting m_waiting_for member. @note The fact that this read-write lock prefers readers is important as deadlock detector won't work correctly otherwise. @sa Comment for MDL_lock::m_rwlock. */ mysql_prlock_t m_LOCK_waiting_for; /** Tell the deadlock detector what metadata lock or table definition cache entry this session is waiting for. In principle, this is redundant, as information can be found by inspecting waiting queues, but we'd very much like it to be readily available to the wait-for graph iterator. */ MDL_wait_for_subgraph *m_waiting_for; LF_PINS *m_pins; uint m_deadlock_overweight; private: MDL_ticket *find_ticket(MDL_request *mdl_req, enum_mdl_duration *duration); void release_locks_stored_before(enum_mdl_duration duration, MDL_ticket *sentinel); void release_lock(enum_mdl_duration duration, MDL_ticket *ticket); bool try_acquire_lock_impl(MDL_request *mdl_request, MDL_ticket **out_ticket); bool fix_pins(); public: THD *get_thd() const { return m_owner->get_thd(); } bool has_explicit_locks(); void find_deadlock(); ulong get_thread_id() const { return thd_get_thread_id(get_thd()); } bool visit_subgraph(MDL_wait_for_graph_visitor *dvisitor); /** Inform the deadlock detector there is an edge in the wait-for graph. */ void will_wait_for(MDL_wait_for_subgraph *waiting_for_arg) { mysql_prlock_wrlock(&m_LOCK_waiting_for); m_waiting_for= waiting_for_arg; mysql_prlock_unlock(&m_LOCK_waiting_for); } /** Remove the wait-for edge from the graph after we're done waiting. */ void done_waiting_for() { mysql_prlock_wrlock(&m_LOCK_waiting_for); m_waiting_for= NULL; mysql_prlock_unlock(&m_LOCK_waiting_for); } void lock_deadlock_victim() { mysql_prlock_rdlock(&m_LOCK_waiting_for); } void unlock_deadlock_victim() { mysql_prlock_unlock(&m_LOCK_waiting_for); } private: MDL_context(const MDL_context &rhs); /* not implemented */ MDL_context &operator=(MDL_context &rhs); /* not implemented */ /* metadata_lock_info plugin */ friend int i_s_metadata_lock_info_fill_row(MDL_ticket*, void*); #ifndef DBUG_OFF public: /** This is for the case when the thread opening the table does not acquire the lock itself, but utilizes a lock guarantee from another MDL context. For example, in InnoDB, MDL is acquired by the purge_coordinator_task, but the table may be opened and used in a purge_worker_task. The coordinator thread holds the lock for the duration of worker's purge job, or longer, possibly reusing shared MDL for different workers and jobs. */ MDL_context *lock_warrant= NULL; inline bool is_lock_warrantee(MDL_key::enum_mdl_namespace ns, const char *db, const char *name, enum_mdl_type mdl_type) const { return lock_warrant && lock_warrant->is_lock_owner(ns, db, name, mdl_type); } #endif }; void mdl_init(); void mdl_destroy(); extern "C" unsigned long thd_get_thread_id(const MYSQL_THD thd); /** Check if a connection in question is no longer connected. @details Replication apply thread is always connected. Otherwise, does a poll on the associated socket to check if the client is gone. */ extern "C" int thd_is_connected(MYSQL_THD thd); /* Metadata locking subsystem tries not to grant more than max_write_lock_count high-prio, strong locks successively, to avoid starving out weak, low-prio locks. */ extern "C" ulong max_write_lock_count; typedef int (*mdl_iterator_callback)(MDL_ticket *ticket, void *arg, bool granted); extern MYSQL_PLUGIN_IMPORT int mdl_iterate(mdl_iterator_callback callback, void *arg); #endif /* MDL_H */ mysql/server/private/sql_time.h000064400000020266151027430560012670 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. Copyright (c) 2011, 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_TIME_INCLUDED #define SQL_TIME_INCLUDED #include "sql_basic_types.h" #include "my_time.h" #include "mysql_time.h" /* timestamp_type */ #include "sql_error.h" /* Sql_condition */ #include "structs.h" /* INTERVAL */ typedef enum enum_mysql_timestamp_type timestamp_type; typedef struct st_date_time_format DATE_TIME_FORMAT; typedef struct st_known_date_time_format KNOWN_DATE_TIME_FORMAT; /* Flags for calc_week() function. */ #define WEEK_MONDAY_FIRST 1 #define WEEK_YEAR 2 #define WEEK_FIRST_WEEKDAY 4 ulong convert_period_to_month(ulong period); ulong convert_month_to_period(ulong month); void set_current_date(THD *thd, MYSQL_TIME *to); bool time_to_datetime(MYSQL_TIME *ltime); bool get_date_from_daynr(long daynr,uint *year, uint *month, uint *day); my_time_t TIME_to_timestamp(THD *thd, const MYSQL_TIME *t, uint *error_code); bool str_to_datetime_with_warn(THD *thd, CHARSET_INFO *cs, const char *str, size_t length, MYSQL_TIME *l_time, date_mode_t flags); bool double_to_datetime_with_warn(THD *thd, double value, MYSQL_TIME *ltime, date_mode_t fuzzydate, const TABLE_SHARE *s, const char *name); bool decimal_to_datetime_with_warn(THD *thd, const my_decimal *value, MYSQL_TIME *ltime, date_mode_t fuzzydate, const TABLE_SHARE *s, const char *name); bool int_to_datetime_with_warn(THD *thd, const Longlong_hybrid &nr, MYSQL_TIME *ltime, date_mode_t fuzzydate, const TABLE_SHARE *s, const char *name); bool time_to_datetime(THD *thd, const MYSQL_TIME *tm, MYSQL_TIME *dt); bool time_to_datetime_with_warn(THD *thd, const MYSQL_TIME *tm, MYSQL_TIME *dt, date_conv_mode_t fuzzydate); inline void datetime_to_date(MYSQL_TIME *ltime) { DBUG_ASSERT(ltime->time_type == MYSQL_TIMESTAMP_DATE || ltime->time_type == MYSQL_TIMESTAMP_DATETIME); DBUG_ASSERT(ltime->neg == 0); ltime->second_part= ltime->hour= ltime->minute= ltime->second= 0; ltime->time_type= MYSQL_TIMESTAMP_DATE; } inline void date_to_datetime(MYSQL_TIME *ltime) { DBUG_ASSERT(ltime->time_type == MYSQL_TIMESTAMP_DATE || ltime->time_type == MYSQL_TIMESTAMP_DATETIME); DBUG_ASSERT(ltime->neg == 0); ltime->time_type= MYSQL_TIMESTAMP_DATETIME; } void make_truncated_value_warning(THD *thd, Sql_condition::enum_warning_level level, const ErrConv *str_val, timestamp_type time_type, const char *db_name, const char *table_name, const char *field_name); extern DATE_TIME_FORMAT *date_time_format_make(timestamp_type format_type, const char *format_str, uint format_length); extern DATE_TIME_FORMAT *date_time_format_copy(THD *thd, DATE_TIME_FORMAT *format); const char *get_date_time_format_str(KNOWN_DATE_TIME_FORMAT *format, timestamp_type type); bool my_TIME_to_str(const MYSQL_TIME *ltime, String *str, uint dec); /* MYSQL_TIME operations */ bool date_add_interval(THD *thd, MYSQL_TIME *ltime, interval_type int_type, const INTERVAL &interval, bool push_warn= true); bool calc_time_diff(const MYSQL_TIME *l_time1, const MYSQL_TIME *l_time2, int l_sign, ulonglong *seconds_out, ulong *microseconds_out); int append_interval(String *str, interval_type int_type, const INTERVAL &interval); /** Calculate time difference between two MYSQL_TIME values and store the result as an out MYSQL_TIME value in MYSQL_TIMESTAMP_TIME format. The result can be outside of the supported TIME range. For example, calc_time_diff('2002-01-01 00:00:00', '2001-01-01 00:00:00') returns '8760:00:00'. So the caller might want to do check_time_range() or adjust_time_range_with_warn() on the result of a calc_time_diff() call. @param l_time1 - the minuend (TIME/DATE/DATETIME value) @param l_time2 - the subtrahend TIME/DATE/DATETIME value @param l_sign - +1 if absolute values are to be subtracted, or -1 if absolute values are to be added. @param[out] l_time3 - the result @param fuzzydate - flags @return true - if TIME_NO_ZERO_DATE was passed in flags and the result appeared to be '00:00:00.000000'. This is important when calc_time_diff() is called when calculating DATE_ADD(TIMEDIFF(...),...) @return false - otherwise */ bool calc_time_diff(const MYSQL_TIME *l_time1, const MYSQL_TIME *l_time2, int lsign, MYSQL_TIME *l_time3, date_mode_t fuzzydate); int my_time_compare(const MYSQL_TIME *a, const MYSQL_TIME *b); void localtime_to_TIME(MYSQL_TIME *to, struct tm *from); void calc_time_from_sec(MYSQL_TIME *to, ulong seconds, ulong microseconds); uint calc_week(const MYSQL_TIME *l_time, uint week_behaviour, uint *year); int calc_weekday(long daynr,bool sunday_first_day_of_week); bool parse_date_time_format(timestamp_type format_type, const char *format, uint format_length, DATE_TIME_FORMAT *date_time_format); /* convenience wrapper */ inline bool parse_date_time_format(timestamp_type format_type, DATE_TIME_FORMAT *date_time_format) { return parse_date_time_format(format_type, date_time_format->format.str, (uint) date_time_format->format.length, date_time_format); } extern DATE_TIME_FORMAT global_date_format; extern DATE_TIME_FORMAT global_datetime_format; extern DATE_TIME_FORMAT global_time_format; extern KNOWN_DATE_TIME_FORMAT known_date_time_formats[]; extern LEX_CSTRING interval_type_to_name[]; static inline bool non_zero_hhmmssuu(const MYSQL_TIME *ltime) { return ltime->hour || ltime->minute || ltime->second || ltime->second_part; } static inline bool non_zero_YYMMDD(const MYSQL_TIME *ltime) { return ltime->year || ltime->month || ltime->day; } static inline bool non_zero_date(const MYSQL_TIME *ltime) { return non_zero_YYMMDD(ltime) || (ltime->time_type == MYSQL_TIMESTAMP_DATETIME && non_zero_hhmmssuu(ltime)); } static inline bool check_date(const MYSQL_TIME *ltime, date_conv_mode_t flags, int *was_cut) { return check_date(ltime, non_zero_date(ltime), ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), was_cut); } bool check_date_with_warn(THD *thd, const MYSQL_TIME *ltime, date_conv_mode_t fuzzy_date, timestamp_type ts_type); static inline bool check_date_with_warn(THD *thd, const MYSQL_TIME *ltime, date_mode_t fuzzydate, timestamp_type ts_type) { return check_date_with_warn(thd, ltime, date_conv_mode_t(fuzzydate), ts_type); } bool adjust_time_range_with_warn(THD *thd, MYSQL_TIME *ltime, uint dec); longlong pack_time(const MYSQL_TIME *my_time); void unpack_time(longlong packed, MYSQL_TIME *my_time, enum_mysql_timestamp_type ts_type); #endif /* SQL_TIME_INCLUDED */ mysql/server/private/handle_connections_win.h000064400000001564151027430560015565 0ustar00/* Copyright (c) 2018 MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /** Handles incoming socket and pipe connections, on Windows. Creates new (THD) connections.. */ extern void handle_connections_win(); extern void network_init_win(); mysql/server/private/mysqld_suffix.h000064400000002261151027430560013743 0ustar00#ifndef MYSQLD_SUFFIX_INCLUDED #define MYSQLD_SUFFIX_INCLUDED /* Copyright (c) 2000-2004, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Set MYSQL_SERVER_SUFFIX_STR. The following code is quite ugly as there is no portable way to easily set a string to the value of a macro */ #ifdef MYSQL_SERVER_SUFFIX #define MYSQL_SERVER_SUFFIX_STR STRINGIFY_ARG(MYSQL_SERVER_SUFFIX) #else #define MYSQL_SERVER_SUFFIX_STR MYSQL_SERVER_SUFFIX_DEF #endif #endif /* MYSQLD_SUFFIX_INCLUDED */ mysql/server/private/gcalc_slicescan.h000064400000041570151027430560014151 0ustar00/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved. Copyright (C) 2011 Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef GCALC_SLICESCAN_INCLUDED #define GCALC_SLICESCAN_INCLUDED #ifndef DBUG_OFF // #define GCALC_CHECK_WITH_FLOAT #else #define GCALC_DBUG_OFF #endif /*DBUG_OFF*/ #ifndef GCALC_DBUG_OFF #define GCALC_DBUG_PRINT(b) DBUG_PRINT("Gcalc", b) #define GCALC_DBUG_ENTER(a) DBUG_ENTER("Gcalc " a) #define GCALC_DBUG_RETURN(r) DBUG_RETURN(r) #define GCALC_DBUG_VOID_RETURN DBUG_VOID_RETURN #define GCALC_DBUG_ASSERT(r) DBUG_ASSERT(r) #else #define GCALC_DBUG_PRINT(b) do {} while(0) #define GCALC_DBUG_ENTER(a) do {} while(0) #define GCALC_DBUG_RETURN(r) return (r) #define GCALC_DBUG_VOID_RETURN do {} while(0) #define GCALC_DBUG_ASSERT(r) do {} while(0) #endif /*GCALC_DBUG_OFF*/ #define GCALC_TERMINATED(state_var) (state_var && (*state_var)) #define GCALC_SET_TERMINATED(state_var, val) state_var= val #define GCALC_DECL_TERMINATED_STATE(varname) \ volatile int *varname; /* Gcalc_dyn_list class designed to manage long lists of same-size objects with the possible efficiency. It allocates fixed-size blocks of memory (blk_size specified at the time of creation). When new object is added to the list, it occupies part of this block until it's full. Then the new block is allocated. Freed objects are chained to the m_free list, and if it's not empty, the newly added object is taken from this list instead the block. */ class Gcalc_dyn_list { public: class Item { public: Item *next; }; Gcalc_dyn_list(size_t blk_size, size_t sizeof_item); Gcalc_dyn_list(const Gcalc_dyn_list &dl); ~Gcalc_dyn_list(); Item *new_item() { Item *result; if (m_free) { result= m_free; m_free= m_free->next; } else result= alloc_new_blk(); return result; } inline void free_item(Item *item) { item->next= m_free; m_free= item; } inline void free_list(Item **list, Item **hook) { *hook= m_free; m_free= *list; } void free_list(Item *list) { Item **hook= &list; while (*hook) hook= &(*hook)->next; free_list(&list, hook); } void reset(); void cleanup(); protected: size_t m_blk_size; size_t m_sizeof_item; unsigned int m_points_per_blk; void *m_first_blk; void **m_blk_hook; Item *m_free; Item *m_keep; Item *alloc_new_blk(); void format_blk(void* block); inline Item *ptr_add(Item *ptr, int n_items) { return (Item *)(((char*)ptr) + n_items * m_sizeof_item); } }; /* Internal Gcalc coordinates to provide the precise calculations */ #define GCALC_DIG_BASE 1000000000 typedef uint32 gcalc_digit_t; typedef unsigned long long gcalc_coord2; typedef gcalc_digit_t Gcalc_internal_coord; #define GCALC_COORD_BASE 2 #define GCALC_COORD_BASE2 4 #define GCALC_COORD_BASE3 6 #define GCALC_COORD_BASE4 8 #define GCALC_COORD_BASE5 10 typedef gcalc_digit_t Gcalc_coord1[GCALC_COORD_BASE]; typedef gcalc_digit_t Gcalc_coord2[GCALC_COORD_BASE*2]; typedef gcalc_digit_t Gcalc_coord3[GCALC_COORD_BASE*3]; void gcalc_mul_coord(Gcalc_internal_coord *result, int result_len, const Gcalc_internal_coord *a, int a_len, const Gcalc_internal_coord *b, int b_len); void gcalc_add_coord(Gcalc_internal_coord *result, int result_len, const Gcalc_internal_coord *a, const Gcalc_internal_coord *b); void gcalc_sub_coord(Gcalc_internal_coord *result, int result_len, const Gcalc_internal_coord *a, const Gcalc_internal_coord *b); int gcalc_cmp_coord(const Gcalc_internal_coord *a, const Gcalc_internal_coord *b, int len); /* Internal coordinates declarations end. */ typedef uint gcalc_shape_info; /* Gcalc_heap represents the 'dynamic list' of Info objects, that contain information about vertexes of all the shapes that take part in some spatial calculation. Can become quite long. After filled, the list is usually sorted and then walked through in the slicescan algorithm. The Gcalc_heap and the algorithm can only operate with two kinds of shapes - polygon and polyline. So all the spatial objects should be represented as sets of these two. */ class Gcalc_heap : public Gcalc_dyn_list { public: enum node_type { nt_shape_node, nt_intersection, nt_eq_node }; class Info : public Gcalc_dyn_list::Item { public: node_type type; union { struct { /* nt_shape_node */ gcalc_shape_info shape; Info *left; Info *right; double x,y; Gcalc_coord1 ix, iy; int top_node; } shape; struct { /* nt_intersection */ /* Line p1-p2 supposed to intersect line p3-p4 */ const Info *p1; const Info *p2; const Info *p3; const Info *p4; void *data; int equal; } intersection; struct { /* nt_eq_node */ const Info *node; void *data; } eq; } node; bool is_bottom() const { GCALC_DBUG_ASSERT(type == nt_shape_node); return !node.shape.left; } bool is_top() const { GCALC_DBUG_ASSERT(type == nt_shape_node); return node.shape.top_node; } bool is_single_node() const { return is_bottom() && is_top(); } void calc_xy(double *x, double *y) const; int equal_pi(const Info *pi) const; #ifdef GCALC_CHECK_WITH_FLOAT void calc_xy_ld(long double *x, long double *y) const; #endif /*GCALC_CHECK_WITH_FLOAT*/ Info *get_next() { return (Info *)next; } const Info *get_next() const { return (const Info *)next; } }; Gcalc_heap(size_t blk_size=8192) : Gcalc_dyn_list(blk_size, sizeof(Info)), m_hook(&m_first), m_n_points(0) {} Gcalc_heap(const Gcalc_heap &gh) : Gcalc_dyn_list(gh), m_hook(&m_first), m_n_points(0) {} void set_extent(double xmin, double xmax, double ymin, double ymax); Info *new_point_info(double x, double y, gcalc_shape_info shape); void free_point_info(Info *i, Gcalc_dyn_list::Item **i_hook); Info *new_intersection(const Info *p1, const Info *p2, const Info *p3, const Info *p4); void prepare_operation(); inline bool ready() const { return m_hook == NULL; } Info *get_first() { return (Info *)m_first; } const Info *get_first() const { return (const Info *)m_first; } Gcalc_dyn_list::Item **get_last_hook() { return m_hook; } void reset(); #ifdef GCALC_CHECK_WITH_FLOAT long double get_double(const Gcalc_internal_coord *c) const; #endif /*GCALC_CHECK_WITH_FLOAT*/ double coord_extent; Gcalc_dyn_list::Item **get_cur_hook() { return m_hook; } private: Gcalc_dyn_list::Item *m_first; Gcalc_dyn_list::Item **m_hook; int m_n_points; }; /* the spatial object has to be represented as a set of simple polygones and polylines to be sent to the slicescan. Gcalc_shape_transporter class and his descendants are used to simplify storing the information about the shape into necessary structures. This base class only fills the Gcalc_heap with the information about shapes and vertices. Normally the Gcalc_shape_transporter family object is sent as a parameter to the 'get_shapes' method of an 'spatial' object so it can pass the spatial information about itself. The virtual methods are treating this data in a way the caller needs. */ class Gcalc_shape_transporter { private: Gcalc_heap::Info *m_first; Gcalc_heap::Info *m_prev; Gcalc_dyn_list::Item **m_prev_hook; int m_shape_started; void int_complete(); protected: Gcalc_heap *m_heap; int int_single_point(gcalc_shape_info Info, double x, double y); int int_add_point(gcalc_shape_info Info, double x, double y); void int_start_line() { DBUG_ASSERT(!m_shape_started); m_shape_started= 1; m_first= m_prev= NULL; } void int_complete_line() { DBUG_ASSERT(m_shape_started== 1); int_complete(); m_shape_started= 0; } void int_start_ring() { DBUG_ASSERT(m_shape_started== 2); m_shape_started= 3; m_first= m_prev= NULL; } void int_complete_ring() { DBUG_ASSERT(m_shape_started== 3); int_complete(); m_shape_started= 2; } void int_start_poly() { DBUG_ASSERT(!m_shape_started); m_shape_started= 2; } void int_complete_poly() { DBUG_ASSERT(m_shape_started== 2); m_shape_started= 0; } bool line_started() { return m_shape_started == 1; }; public: Gcalc_shape_transporter(Gcalc_heap *heap) : m_shape_started(0), m_heap(heap) {} virtual int single_point(double x, double y)=0; virtual int start_line()=0; virtual int complete_line()=0; virtual int start_poly()=0; virtual int complete_poly()=0; virtual int start_ring()=0; virtual int complete_ring()=0; virtual int add_point(double x, double y)=0; virtual int start_collection(int n_objects) { return 0; } virtual int empty_shape() { return 0; } int start_simple_poly() { return start_poly() || start_ring(); } int complete_simple_poly() { return complete_ring() || complete_poly(); } virtual ~Gcalc_shape_transporter() = default; }; enum Gcalc_scan_events { scev_none= 0, scev_point= 1, /* Just a new point in thread */ scev_thread= 2, /* Start of the new thread */ scev_two_threads= 4, /* A couple of new threads started */ scev_intersection= 8, /* Intersection happened */ scev_end= 16, /* Single thread finished */ scev_two_ends= 32, /* A couple of threads finished */ scev_single_point= 64 /* Got single point */ }; /* Gcalc_scan_iterator incapsulates the slicescan algorithm. It takes filled Gcalc_heap as a datasource. Then can be iterated through the vertexes and intersection points with the step() method. After the 'step()' one usually observes the current 'slice' to do the necessary calculations, like looking for intersections, calculating the area, whatever. */ class Gcalc_scan_iterator : public Gcalc_dyn_list { public: class point : public Gcalc_dyn_list::Item { public: Gcalc_coord1 dx; Gcalc_coord1 dy; Gcalc_heap::Info *pi; Gcalc_heap::Info *next_pi; Gcalc_heap::Info *ev_pi; const Gcalc_coord1 *l_border; const Gcalc_coord1 *r_border; point *ev_next; Gcalc_scan_events event; inline const point *c_get_next() const { return (const point *)next; } inline bool is_bottom() const { return !next_pi; } gcalc_shape_info get_shape() const { return pi->node.shape.shape; } inline point *get_next() { return (point *)next; } inline const point *get_next() const { return (const point *)next; } /* Compare the dx_dy parameters regarding the horiz_dir */ /* returns -1 if less, 0 if equal, 1 if bigger */ static int cmp_dx_dy(const Gcalc_coord1 dx_a, const Gcalc_coord1 dy_a, const Gcalc_coord1 dx_b, const Gcalc_coord1 dy_b); static int cmp_dx_dy(const Gcalc_heap::Info *p1, const Gcalc_heap::Info *p2, const Gcalc_heap::Info *p3, const Gcalc_heap::Info *p4); int cmp_dx_dy(const point *p) const; point **next_ptr() { return (point **) &next; } #ifndef GCALC_DBUG_OFF unsigned int thread; #endif /*GCALC_DBUG_OFF*/ #ifdef GCALC_CHECK_WITH_FLOAT void calc_x(long double *x, long double y, long double ix) const; #endif /*GCALC_CHECK_WITH_FLOAT*/ }; /* That class introduced mostly for the 'typecontrol' reason. */ /* only difference from the point classis the get_next() function. */ class event_point : public point { public: inline const event_point *get_next() const { return (const event_point*) ev_next; } int simple_event() const { return !ev_next ? (event & (scev_point | scev_end)) : (!ev_next->ev_next && event == scev_two_ends); } }; class intersection_info : public Gcalc_dyn_list::Item { public: point *edge_a; point *edge_b; Gcalc_coord2 t_a; Gcalc_coord2 t_b; int t_calculated; Gcalc_coord3 x_exp; int x_calculated; Gcalc_coord3 y_exp; int y_calculated; void calc_t() {if (!t_calculated) do_calc_t(); } void calc_y_exp() { if (!y_calculated) do_calc_y(); } void calc_x_exp() { if (!x_calculated) do_calc_x(); } void do_calc_t(); void do_calc_x(); void do_calc_y(); }; class slice_state { public: point *slice; point **event_position_hook; point *event_end; const Gcalc_heap::Info *pi; }; public: Gcalc_scan_iterator(size_t blk_size= 8192); GCALC_DECL_TERMINATED_STATE(killed) void init(Gcalc_heap *points); /* Iterator can be reused */ void reset(); int step(); Gcalc_heap::Info *more_points() { return m_cur_pi; } bool more_trapezoids() { return m_cur_pi && m_cur_pi->next; } const point *get_bottom_points() const { return m_bottom_points; } const point *get_event_position() const { return *state.event_position_hook; } const point *get_event_end() const { return state.event_end; } const event_point *get_events() const { return (const event_point *) (*state.event_position_hook == state.event_end ? m_bottom_points : *state.event_position_hook); } const point *get_b_slice() const { return state.slice; } double get_h() const; double get_y() const; double get_event_x() const; double get_sp_x(const point *sp) const; int intersection_step() const { return state.pi->type == Gcalc_heap::nt_intersection; } const Gcalc_heap::Info *get_cur_pi() const { return state.pi; } private: Gcalc_heap *m_heap; Gcalc_heap::Info *m_cur_pi; slice_state state; #ifndef GCALC_DBUG_OFF unsigned int m_cur_thread; #endif /*GCALC_DBUG_OFF*/ point *m_bottom_points; point **m_bottom_hook; int node_scan(); void eq_scan(); void intersection_scan(); void remove_bottom_node(); int insert_top_node(); int add_intersection(point *sp_a, point *sp_b, Gcalc_heap::Info *pi_from); int add_eq_node(Gcalc_heap::Info *node, point *sp); int add_events_for_node(point *sp_node); point *new_slice_point() { point *new_point= (point *)new_item(); return new_point; } intersection_info *new_intersection_info(point *a, point *b) { intersection_info *ii= (intersection_info *)new_item(); ii->edge_a= a; ii->edge_b= b; ii->t_calculated= ii->x_calculated= ii->y_calculated= 0; return ii; } int arrange_event(int do_sorting, int n_intersections); static double get_pure_double(const Gcalc_internal_coord *d, int d_len); }; /* Gcalc_trapezoid_iterator simplifies the calculations on the current slice of the Gcalc_scan_iterator. One can walk through the trapezoids formed between previous and current slices. */ #ifdef TMP_BLOCK class Gcalc_trapezoid_iterator { protected: const Gcalc_scan_iterator::point *sp0; const Gcalc_scan_iterator::point *sp1; public: Gcalc_trapezoid_iterator(const Gcalc_scan_iterator *scan_i) : sp0(scan_i->get_b_slice()), sp1(scan_i->get_t_slice()) {} inline bool more() const { return sp1 && sp1->next; } const Gcalc_scan_iterator::point *lt() const { return sp1; } const Gcalc_scan_iterator::point *lb() const { return sp0; } const Gcalc_scan_iterator::point *rb() const { const Gcalc_scan_iterator::point *result= sp0; while ((result= result->c_get_next())->is_bottom()) {} return result; } const Gcalc_scan_iterator::point *rt() const { return sp1->c_get_next(); } void operator++() { sp0= rb(); sp1= rt(); } }; #endif /*TMP_BLOCK*/ /* Gcalc_point_iterator simplifies the calculations on the current slice of the Gcalc_scan_iterator. One can walk through the points on the current slice. */ class Gcalc_point_iterator { protected: const Gcalc_scan_iterator::point *sp; public: Gcalc_point_iterator(const Gcalc_scan_iterator *scan_i): sp(scan_i->get_b_slice()) {} inline bool more() const { return sp != NULL; } inline void operator++() { sp= sp->c_get_next(); } inline const Gcalc_scan_iterator::point *point() const { return sp; } inline const Gcalc_heap::Info *get_pi() const { return sp->pi; } inline gcalc_shape_info get_shape() const { return sp->get_shape(); } inline void restart(const Gcalc_scan_iterator *scan_i) { sp= scan_i->get_b_slice(); } }; #endif /*GCALC_SLICESCAN_INCLUDED*/ mysql/server/private/records.h000064400000006113151027430560012507 0ustar00#ifndef SQL_RECORDS_H #define SQL_RECORDS_H /* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "table.h" struct st_join_table; class handler; class THD; class SQL_SELECT; class Copy_field; class SORT_INFO; struct READ_RECORD; void end_read_record(READ_RECORD *info); void free_cache(READ_RECORD *info); /** A context for reading through a single table using a chosen access method: index read, scan, etc, use of cache, etc. Use by: READ_RECORD read_record; init_read_record(&read_record, ...); while (read_record.read_record()) { ... } end_read_record(); */ struct READ_RECORD { typedef int (*Read_func)(READ_RECORD*); typedef void (*Unlock_row_func)(st_join_table *); typedef int (*Setup_func)(struct st_join_table*); TABLE *table; /* Head-form */ Unlock_row_func unlock_row; Read_func read_record_func; Read_func read_record_func_and_unpack_calls; THD *thd; SQL_SELECT *select; uint ref_length, reclength, rec_cache_size, error_offset; /** Counting records when reading result from filesort(). Used when filesort leaves the result in the filesort buffer. */ ha_rows unpack_counter; uchar *ref_pos; /* pointer to form->refpos */ uchar *rec_buf; /* to read field values after filesort */ uchar *cache,*cache_pos,*cache_end,*read_positions; /* Structure storing information about sorting */ SORT_INFO *sort_info; struct st_io_cache *io_cache; bool print_error; int read_record() { return read_record_func(this); } uchar *record() const { return table->record[0]; } /* SJ-Materialization runtime may need to read fields from the materialized table and unpack them into original table fields: */ Copy_field *copy_field; Copy_field *copy_field_end; public: READ_RECORD() : table(NULL), cache(NULL) {} ~READ_RECORD() { end_read_record(this); } }; bool init_read_record(READ_RECORD *info, THD *thd, TABLE *reg_form, SQL_SELECT *select, SORT_INFO *sort, int use_record_cache, bool print_errors, bool disable_rr_cache); bool init_read_record_idx(READ_RECORD *info, THD *thd, TABLE *table, bool print_error, uint idx, bool reverse); void rr_unlock_row(st_join_table *tab); #endif /* SQL_RECORDS_H */ mysql/server/private/uniques.h000064400000010171151027430560012536 0ustar00/* Copyright (c) 2016 MariaDB corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef UNIQUE_INCLUDED #define UNIQUE_INCLUDED #include "filesort.h" /* Unique -- class for unique (removing of duplicates). Puts all values to the TREE. If the tree becomes too big, it's dumped to the file. User can request sorted values, or just iterate through them. In the last case tree merging is performed in memory simultaneously with iteration, so it should be ~2-3x faster. */ class Unique :public Sql_alloc { DYNAMIC_ARRAY file_ptrs; ulong max_elements; /* Total number of elements that will be stored in-memory */ size_t max_in_memory_size; IO_CACHE file; TREE tree; /* Number of elements filtered out due to min_dupl_count when storing results to table. See Unique::get */ ulong filtered_out_elems; uint size; uint full_size; /* Size of element + space needed to store the number of duplicates found for the element. */ uint min_dupl_count; /* Minimum number of occurences of element required for it to be written to record_pointers. always 0 for unions, > 0 for intersections */ bool with_counters; bool merge(TABLE *table, uchar *buff, size_t size, bool without_last_merge); bool flush(); public: ulong elements; SORT_INFO sort; Unique(qsort_cmp2 comp_func, void *comp_func_fixed_arg, uint size_arg, size_t max_in_memory_size_arg, uint min_dupl_count_arg= 0); ~Unique(); ulong elements_in_tree() { return tree.elements_in_tree; } inline bool unique_add(void *ptr) { DBUG_ENTER("unique_add"); DBUG_PRINT("info", ("tree %u - %lu", tree.elements_in_tree, max_elements)); if (!(tree.flag & TREE_ONLY_DUPS) && tree.elements_in_tree >= max_elements && flush()) DBUG_RETURN(1); DBUG_RETURN(!tree_insert(&tree, ptr, 0, tree.custom_arg)); } bool is_in_memory() { return (my_b_tell(&file) == 0); } void close_for_expansion() { tree.flag= TREE_ONLY_DUPS; } bool get(TABLE *table); /* Cost of searching for an element in the tree */ inline static double get_search_cost(ulonglong tree_elems, double compare_factor) { return log((double) tree_elems) / (compare_factor * M_LN2); } static double get_use_cost(uint *buffer, size_t nkeys, uint key_size, size_t max_in_memory_size, double compare_factor, bool intersect_fl, bool *in_memory); inline static int get_cost_calc_buff_size(size_t nkeys, uint key_size, size_t max_in_memory_size) { size_t max_elems_in_tree= max_in_memory_size / ALIGN_SIZE(sizeof(TREE_ELEMENT)+key_size); if (max_elems_in_tree == 0) max_elems_in_tree= 1; return (int) (sizeof(uint)*(1 + nkeys/max_elems_in_tree)); } void reset(); bool walk(TABLE *table, tree_walk_action action, void *walk_action_arg); uint get_size() const { return size; } size_t get_max_in_memory_size() const { return max_in_memory_size; } friend int unique_write_to_file(void* key, element_count count, void *unique); friend int unique_write_to_ptrs(void* key, element_count count, void *unique); friend int unique_write_to_file_with_count(void *key, element_count count, void *unique); friend int unique_intersect_write_to_ptrs(void *key, element_count count, void *unique); }; #endif /* UNIQUE_INCLUDED */ mysql/server/private/strfunc.h000064400000004343151027430560012535 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef STRFUNC_INCLUDED #define STRFUNC_INCLUDED typedef struct st_typelib TYPELIB; ulonglong find_set(const TYPELIB *lib, const char *x, size_t length, CHARSET_INFO *cs, char **err_pos, uint *err_len, bool *set_warning); ulonglong find_set_from_flags(TYPELIB *lib, uint default_name, ulonglong cur_set, ulonglong default_set, const char *str, uint length, CHARSET_INFO *cs, char **err_pos, uint *err_len, bool *set_warning); uint find_type(const TYPELIB *lib, const char *find, size_t length, bool part_match); uint find_type2(const TYPELIB *lib, const char *find, size_t length, CHARSET_INFO *cs); void unhex_type2(TYPELIB *lib); uint check_word(TYPELIB *lib, const char *val, const char *end, const char **end_of_word); int find_string_in_array(LEX_CSTRING * const haystack, LEX_CSTRING * const needle, CHARSET_INFO * const cs); const char *flagset_to_string(THD *thd, LEX_CSTRING *result, ulonglong set, const char *lib[]); const char *set_to_string(THD *thd, LEX_CSTRING *result, ulonglong set, const char *lib[]); /* These functions were protected by INNODB_COMPATIBILITY_HOOKS */ uint strconvert(CHARSET_INFO *from_cs, const char *from, size_t from_length, CHARSET_INFO *to_cs, char *to, size_t to_length, uint *errors); #endif /* STRFUNC_INCLUDED */ mysql/server/private/mysqld.h000064400000117011151027430560012357 0ustar00/* Copyright (c) 2006, 2016, Oracle and/or its affiliates. Copyright (c) 2010, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MYSQLD_INCLUDED #define MYSQLD_INCLUDED #include "sql_basic_types.h" /* query_id_t */ #include "sql_mode.h" /* Sql_mode_dependency */ #include "sql_plugin.h" #include "sql_bitmap.h" /* Bitmap */ #include "my_decimal.h" /* my_decimal */ #include "mysql_com.h" /* SERVER_VERSION_LENGTH */ #include "my_counter.h" #include "mysql/psi/mysql_file.h" /* MYSQL_FILE */ #include "mysql/psi/mysql_socket.h" /* MYSQL_SOCKET */ #include "sql_list.h" /* I_List */ #include "sql_cmd.h" #include #include "my_pthread.h" #include "my_rdtsc.h" class THD; class CONNECT; struct handlerton; class Time_zone; struct scheduler_functions; typedef struct st_mysql_show_var SHOW_VAR; /* Bits from testflag */ #define TEST_PRINT_CACHED_TABLES 1U #define TEST_NO_KEY_GROUP 2U #define TEST_MIT_THREAD 4U #define TEST_BLOCKING 8U #define TEST_KEEP_TMP_TABLES 16U #define TEST_READCHECK 64U /**< Force use of readcheck */ #define TEST_NO_EXTRA 128U #define TEST_CORE_ON_SIGNAL 256U /**< Give core if signal */ #define TEST_SIGINT 1024U /**< Allow sigint on threads */ #define TEST_SYNCHRONIZATION 2048U /**< get server to do sleep in some places */ /* Keep things compatible */ #define OPT_DEFAULT SHOW_OPT_DEFAULT #define OPT_SESSION SHOW_OPT_SESSION #define OPT_GLOBAL SHOW_OPT_GLOBAL extern MYSQL_PLUGIN_IMPORT MY_TIMER_INFO sys_timer_info; /* Values for --slave-parallel-mode Must match order in slave_parallel_mode_typelib in sys_vars.cc. */ enum enum_slave_parallel_mode { SLAVE_PARALLEL_NONE, SLAVE_PARALLEL_MINIMAL, SLAVE_PARALLEL_CONSERVATIVE, SLAVE_PARALLEL_OPTIMISTIC, SLAVE_PARALLEL_AGGRESSIVE }; /* Function prototypes */ void kill_mysql(THD *thd); void close_connection(THD *thd, uint sql_errno= 0); void handle_connection_in_main_thread(CONNECT *thd); void create_thread_to_handle_connection(CONNECT *connect); void unlink_thd(THD *thd); void refresh_status(THD *thd); bool is_secure_file_path(char *path); extern void init_net_server_extension(THD *thd); extern void handle_accepted_socket(MYSQL_SOCKET new_sock, MYSQL_SOCKET sock); extern void create_new_thread(CONNECT *connect); extern void ssl_acceptor_stats_update(int sslaccept_ret); extern int reinit_ssl(); extern "C" MYSQL_PLUGIN_IMPORT CHARSET_INFO *system_charset_info; extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *files_charset_info ; extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *national_charset_info; extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *table_alias_charset; /** Character set of the buildin error messages loaded from errmsg.sys. */ extern CHARSET_INFO *error_message_charset_info; extern CHARSET_INFO *character_set_filesystem; extern MY_BITMAP temp_pool; extern bool opt_large_files; extern bool opt_update_log, opt_bin_log, opt_error_log, opt_bin_log_compress; extern uint opt_bin_log_compress_min_len; extern my_bool opt_log, opt_bootstrap; extern my_bool opt_backup_history_log; extern my_bool opt_backup_progress_log; extern my_bool opt_support_flashback; extern ulonglong log_output_options; extern ulong log_backup_output_options; extern bool opt_disable_networking, opt_skip_show_db; extern bool opt_skip_name_resolve; extern bool opt_ignore_builtin_innodb; extern my_bool opt_character_set_client_handshake; extern my_bool debug_assert_on_not_freed_memory; extern MYSQL_PLUGIN_IMPORT bool volatile abort_loop; extern my_bool opt_safe_user_create; extern my_bool opt_safe_show_db, opt_local_infile, opt_myisam_use_mmap; extern my_bool opt_slave_compressed_protocol, use_temp_pool; extern ulong slave_exec_mode_options, slave_ddl_exec_mode_options; extern ulong slave_retried_transactions; extern ulong transactions_multi_engine; extern ulong rpl_transactions_multi_engine; extern ulong transactions_gtid_foreign_engine; extern ulong slave_run_triggers_for_rbr; extern ulonglong slave_type_conversions_options; extern my_bool read_only, opt_readonly; extern MYSQL_PLUGIN_IMPORT my_bool lower_case_file_system; extern my_bool opt_enable_named_pipe, opt_sync_frm, opt_allow_suspicious_udfs; extern my_bool opt_secure_auth; extern my_bool opt_require_secure_transport; extern const char *current_dbug_option; extern char* opt_secure_file_priv; extern char* opt_secure_backup_file_priv; extern size_t opt_secure_backup_file_priv_len; extern my_bool sp_automatic_privileges, opt_noacl; extern ulong use_stat_tables; extern my_bool opt_old_style_user_limits, trust_function_creators; extern uint opt_crash_binlog_innodb; extern const char *shared_memory_base_name; extern MYSQL_PLUGIN_IMPORT char *mysqld_unix_port; extern my_bool opt_enable_shared_memory; extern ulong opt_replicate_events_marked_for_skip; extern char *default_tz_name; extern Time_zone *default_tz; extern char *my_bind_addr_str; extern char *default_storage_engine, *default_tmp_storage_engine; extern char *enforced_storage_engine; extern char *gtid_pos_auto_engines; extern plugin_ref *opt_gtid_pos_auto_plugins; extern bool opt_endinfo, using_udf_functions; extern my_bool locked_in_memory; extern bool opt_using_transactions; extern ulong current_pid; extern double expire_logs_days; extern ulong binlog_expire_logs_seconds; extern my_bool relay_log_recovery; extern uint sync_binlog_period, sync_relaylog_period, sync_relayloginfo_period, sync_masterinfo_period; extern ulong opt_tc_log_size, tc_log_max_pages_used, tc_log_page_size; extern ulong tc_log_page_waits; extern my_bool relay_log_purge, opt_innodb_safe_binlog, opt_innodb; extern my_bool relay_log_recovery; extern uint select_errors,ha_open_options; extern ulonglong test_flags; extern uint protocol_version, dropping_tables; extern MYSQL_PLUGIN_IMPORT uint mysqld_port; extern ulong delay_key_write_options; extern char *opt_logname, *opt_slow_logname, *opt_bin_logname, *opt_relay_logname; extern char *opt_binlog_index_name; extern char *opt_backup_history_logname, *opt_backup_progress_logname, *opt_backup_settings_name; extern const char *log_output_str; extern const char *log_backup_output_str; /* System Versioning begin */ enum vers_system_time_t { SYSTEM_TIME_UNSPECIFIED = 0, SYSTEM_TIME_AS_OF, SYSTEM_TIME_FROM_TO, SYSTEM_TIME_BETWEEN, SYSTEM_TIME_BEFORE, // used for DELETE HISTORY ... BEFORE SYSTEM_TIME_HISTORY, // used for DELETE HISTORY SYSTEM_TIME_ALL }; struct vers_asof_timestamp_t { ulong type; my_time_t unix_time; ulong second_part; }; enum vers_alter_history_enum { VERS_ALTER_HISTORY_ERROR= 0, VERS_ALTER_HISTORY_KEEP }; /* System Versioning end */ extern char *mysql_home_ptr, *pidfile_name_ptr; extern MYSQL_PLUGIN_IMPORT char glob_hostname[FN_REFLEN]; extern char mysql_home[FN_REFLEN]; extern char pidfile_name[FN_REFLEN], system_time_zone[30], *opt_init_file; extern char default_logfile_name[FN_REFLEN]; extern char log_error_file[FN_REFLEN], *opt_tc_log_file, *opt_ddl_recovery_file; extern const double log_10[309]; extern ulonglong keybuff_size; extern ulonglong thd_startup_options; extern my_thread_id global_thread_id; extern ulong binlog_cache_use, binlog_cache_disk_use; extern ulong binlog_stmt_cache_use, binlog_stmt_cache_disk_use; extern ulong aborted_threads, aborted_connects, aborted_connects_preauth; extern ulong delayed_insert_timeout; extern ulong delayed_insert_limit, delayed_queue_size; extern ulong delayed_insert_threads, delayed_insert_writes; extern ulong delayed_rows_in_use,delayed_insert_errors; extern Atomic_counter slave_open_temp_tables; extern ulonglong query_cache_size; extern ulong query_cache_limit; extern ulong query_cache_min_res_unit; extern ulong slow_launch_threads, slow_launch_time; extern MYSQL_PLUGIN_IMPORT ulong max_connections; extern uint max_digest_length; extern ulong max_connect_errors, connect_timeout; extern uint max_password_errors; extern my_bool slave_allow_batching; extern my_bool allow_slave_start; extern LEX_CSTRING reason_slave_blocked; extern ulong slave_trans_retries; extern ulong slave_trans_retry_interval; extern uint slave_net_timeout; extern int max_user_connections; extern ulong what_to_log,flush_time; extern uint max_prepared_stmt_count, prepared_stmt_count; extern MYSQL_PLUGIN_IMPORT ulong open_files_limit; extern ulonglong binlog_cache_size, binlog_stmt_cache_size, binlog_file_cache_size; extern ulonglong max_binlog_cache_size, max_binlog_stmt_cache_size; extern ulong max_binlog_size; extern ulong slave_max_allowed_packet; extern ulong opt_binlog_rows_event_max_size; extern ulong binlog_row_metadata; extern ulong thread_cache_size; extern ulong stored_program_cache_size; extern ulong opt_slave_parallel_threads; extern ulong opt_slave_domain_parallel_threads; extern ulong opt_slave_parallel_max_queued; extern ulong opt_slave_parallel_mode; extern ulong opt_binlog_commit_wait_count; extern ulong opt_binlog_commit_wait_usec; extern my_bool opt_gtid_ignore_duplicates; extern uint opt_gtid_cleanup_batch_size; extern ulong back_log; extern ulong executed_events; extern char language[FN_REFLEN]; extern "C" MYSQL_PLUGIN_IMPORT ulong server_id; extern ulong concurrency; extern time_t server_start_time, flush_status_time; extern char *opt_mysql_tmpdir, mysql_charsets_dir[]; extern size_t mysql_unpacked_real_data_home_len; extern MYSQL_PLUGIN_IMPORT MY_TMPDIR mysql_tmpdir_list; extern const char *first_keyword, *delayed_user, *slave_user; extern MYSQL_PLUGIN_IMPORT const char *my_localhost; extern MYSQL_PLUGIN_IMPORT const char **errmesg; /* Error messages */ extern const char *myisam_recover_options_str; extern const LEX_CSTRING in_left_expr_name, in_additional_cond, in_having_cond; extern const LEX_CSTRING NULL_clex_str; extern const LEX_CSTRING error_clex_str; extern SHOW_VAR status_vars[]; extern struct system_variables max_system_variables; extern struct system_status_var global_status_var; extern struct my_rnd_struct sql_rand; extern const char *opt_date_time_formats[]; extern handlerton *partition_hton; extern handlerton *myisam_hton; extern handlerton *heap_hton; extern const char *load_default_groups[]; extern struct my_option my_long_options[]; int handle_early_options(); extern int MYSQL_PLUGIN_IMPORT mysqld_server_started; extern int mysqld_server_initialized; extern "C" MYSQL_PLUGIN_IMPORT int orig_argc; extern "C" MYSQL_PLUGIN_IMPORT char **orig_argv; extern pthread_attr_t connection_attrib; extern my_bool old_mode; extern LEX_STRING opt_init_connect, opt_init_slave; extern char err_shared_dir[]; extern ulong connection_errors_select; extern ulong connection_errors_accept; extern ulong connection_errors_tcpwrap; extern ulong connection_errors_internal; extern ulong connection_errors_max_connection; extern ulong connection_errors_peer_addr; extern ulong log_warnings; extern my_bool encrypt_binlog; extern my_bool encrypt_tmp_disk_tables, encrypt_tmp_files; extern ulong encryption_algorithm; extern const char *encryption_algorithm_names[]; extern long opt_secure_timestamp; extern uint default_password_lifetime; extern my_bool disconnect_on_expired_password; enum secure_timestamp { SECTIME_NO, SECTIME_SUPER, SECTIME_REPL, SECTIME_YES }; #ifdef HAVE_MMAP extern PSI_mutex_key key_PAGE_lock, key_LOCK_sync, key_LOCK_active, key_LOCK_pool, key_LOCK_pending_checkpoint; #endif /* HAVE_MMAP */ extern PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_xid_list, key_BINLOG_LOCK_binlog_background_thread, key_LOCK_binlog_end_pos, key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi, key_LOCK_crypt, key_LOCK_delayed_create, key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log, key_LOCK_gdl, key_LOCK_global_system_variables, key_LOCK_logger, key_LOCK_manager, key_LOCK_prepared_stmt_count, key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status, key_LOCK_thd_data, key_LOCK_thd_kill, key_LOCK_user_conn, key_LOG_LOCK_log, key_master_info_data_lock, key_master_info_run_lock, key_master_info_sleep_lock, key_master_info_start_stop_lock, key_mutex_slave_reporting_capability_err_lock, key_relay_log_info_data_lock, key_relay_log_info_log_space_lock, key_relay_log_info_run_lock, key_rpl_group_info_sleep_lock, key_structure_guard_mutex, key_TABLE_SHARE_LOCK_ha_data, key_TABLE_SHARE_LOCK_statistics, key_LOCK_start_thread, key_LOCK_error_messages, key_PARTITION_LOCK_auto_inc; extern PSI_mutex_key key_RELAYLOG_LOCK_index; extern PSI_mutex_key key_LOCK_relaylog_end_pos; extern PSI_mutex_key key_LOCK_slave_state, key_LOCK_binlog_state, key_LOCK_rpl_thread, key_LOCK_rpl_thread_pool, key_LOCK_parallel_entry; extern PSI_mutex_key key_TABLE_SHARE_LOCK_share, key_LOCK_stats, key_LOCK_global_user_client_stats, key_LOCK_global_table_stats, key_LOCK_global_index_stats, key_LOCK_wakeup_ready, key_LOCK_wait_commit, key_TABLE_SHARE_LOCK_rotation; extern PSI_mutex_key key_LOCK_gtid_waiting; extern PSI_rwlock_key key_rwlock_LOCK_grant, key_rwlock_LOCK_logger, key_rwlock_LOCK_sys_init_connect, key_rwlock_LOCK_sys_init_slave, key_rwlock_LOCK_system_variables_hash, key_rwlock_query_cache_query_lock, key_LOCK_SEQUENCE, key_rwlock_LOCK_vers_stats, key_rwlock_LOCK_stat_serial, key_rwlock_THD_list; #ifdef HAVE_MMAP extern PSI_cond_key key_PAGE_cond, key_COND_active, key_COND_pool; #endif /* HAVE_MMAP */ extern PSI_cond_key key_BINLOG_COND_xid_list, key_BINLOG_update_cond, key_BINLOG_COND_binlog_background_thread, key_BINLOG_COND_binlog_background_thread_end, key_COND_cache_status_changed, key_COND_manager, key_COND_rpl_status, key_COND_server_started, key_delayed_insert_cond, key_delayed_insert_cond_client, key_item_func_sleep_cond, key_master_info_data_cond, key_master_info_start_cond, key_master_info_stop_cond, key_master_info_sleep_cond, key_relay_log_info_data_cond, key_relay_log_info_log_space_cond, key_relay_log_info_start_cond, key_relay_log_info_stop_cond, key_rpl_group_info_sleep_cond, key_TABLE_SHARE_cond, key_user_level_lock_cond, key_COND_start_thread; extern PSI_cond_key key_RELAYLOG_COND_relay_log_updated, key_RELAYLOG_COND_bin_log_updated, key_COND_wakeup_ready, key_COND_wait_commit; extern PSI_cond_key key_RELAYLOG_COND_queue_busy; extern PSI_cond_key key_TC_LOG_MMAP_COND_queue_busy; extern PSI_cond_key key_COND_rpl_thread, key_COND_rpl_thread_queue, key_COND_rpl_thread_stop, key_COND_rpl_thread_pool, key_COND_parallel_entry, key_COND_group_commit_orderer; extern PSI_cond_key key_COND_wait_gtid, key_COND_gtid_ignore_duplicates; extern PSI_cond_key key_TABLE_SHARE_COND_rotation; extern PSI_thread_key key_thread_delayed_insert, key_thread_handle_manager, key_thread_kill_server, key_thread_main, key_thread_one_connection, key_thread_signal_hand, key_thread_slave_background, key_rpl_parallel_thread; extern PSI_file_key key_file_binlog, key_file_binlog_cache, key_file_binlog_index, key_file_binlog_index_cache, key_file_casetest, key_file_dbopt, key_file_ERRMSG, key_select_to_file, key_file_fileparser, key_file_frm, key_file_global_ddl_log, key_file_load, key_file_loadfile, key_file_log_event_data, key_file_log_event_info, key_file_master_info, key_file_misc, key_file_partition_ddl_log, key_file_pid, key_file_relay_log_info, key_file_send_file, key_file_tclog, key_file_trg, key_file_trn, key_file_init, key_file_log_ddl; extern PSI_file_key key_file_query_log, key_file_slow_log; extern PSI_file_key key_file_relaylog, key_file_relaylog_index, key_file_relaylog_cache, key_file_relaylog_index_cache; extern PSI_socket_key key_socket_tcpip, key_socket_unix, key_socket_client_connection; extern PSI_file_key key_file_binlog_state; #ifdef HAVE_des extern char* des_key_file; extern PSI_file_key key_file_des_key_file; extern PSI_mutex_key key_LOCK_des_key_file; extern mysql_mutex_t LOCK_des_key_file; #endif #ifdef HAVE_PSI_INTERFACE void init_server_psi_keys(); #endif /* HAVE_PSI_INTERFACE */ extern PSI_memory_key key_memory_locked_table_list; extern PSI_memory_key key_memory_locked_thread_list; extern PSI_memory_key key_memory_thd_transactions; extern PSI_memory_key key_memory_delegate; extern PSI_memory_key key_memory_acl_mem; extern PSI_memory_key key_memory_acl_memex; extern PSI_memory_key key_memory_acl_cache; extern PSI_memory_key key_memory_thd_main_mem_root; extern PSI_memory_key key_memory_help; extern PSI_memory_key key_memory_frm; extern PSI_memory_key key_memory_table_share; extern PSI_memory_key key_memory_gdl; extern PSI_memory_key key_memory_table_triggers_list; extern PSI_memory_key key_memory_prepared_statement_map; extern PSI_memory_key key_memory_prepared_statement_main_mem_root; extern PSI_memory_key key_memory_protocol_rset_root; extern PSI_memory_key key_memory_warning_info_warn_root; extern PSI_memory_key key_memory_sp_cache; extern PSI_memory_key key_memory_sp_head_main_root; extern PSI_memory_key key_memory_sp_head_execute_root; extern PSI_memory_key key_memory_sp_head_call_root; extern PSI_memory_key key_memory_table_mapping_root; extern PSI_memory_key key_memory_quick_range_select_root; extern PSI_memory_key key_memory_quick_index_merge_root; extern PSI_memory_key key_memory_quick_ror_intersect_select_root; extern PSI_memory_key key_memory_quick_ror_union_select_root; extern PSI_memory_key key_memory_quick_group_min_max_select_root; extern PSI_memory_key key_memory_test_quick_select_exec; extern PSI_memory_key key_memory_prune_partitions_exec; extern PSI_memory_key key_memory_binlog_recover_exec; extern PSI_memory_key key_memory_blob_mem_storage; extern PSI_memory_key key_memory_Sys_var_charptr_value; extern PSI_memory_key key_memory_THD_db; extern PSI_memory_key key_memory_user_var_entry; extern PSI_memory_key key_memory_user_var_entry_value; extern PSI_memory_key key_memory_Slave_job_group_group_relay_log_name; extern PSI_memory_key key_memory_Relay_log_info_group_relay_log_name; extern PSI_memory_key key_memory_binlog_cache_mngr; extern PSI_memory_key key_memory_Row_data_memory_memory; extern PSI_memory_key key_memory_errmsgs; extern PSI_memory_key key_memory_Event_queue_element_for_exec_names; extern PSI_memory_key key_memory_Event_scheduler_scheduler_param; extern PSI_memory_key key_memory_Gis_read_stream_err_msg; extern PSI_memory_key key_memory_Geometry_objects_data; extern PSI_memory_key key_memory_host_cache_hostname; extern PSI_memory_key key_memory_User_level_lock; extern PSI_memory_key key_memory_Filesort_info_record_pointers; extern PSI_memory_key key_memory_Sort_param_tmp_buffer; extern PSI_memory_key key_memory_Filesort_info_merge; extern PSI_memory_key key_memory_Filesort_buffer_sort_keys; extern PSI_memory_key key_memory_handler_errmsgs; extern PSI_memory_key key_memory_handlerton; extern PSI_memory_key key_memory_XID; extern PSI_memory_key key_memory_MYSQL_LOCK; extern PSI_memory_key key_memory_MYSQL_LOG_name; extern PSI_memory_key key_memory_TC_LOG_MMAP_pages; extern PSI_memory_key key_memory_my_str_malloc; extern PSI_memory_key key_memory_MYSQL_BIN_LOG_basename; extern PSI_memory_key key_memory_MYSQL_BIN_LOG_index; extern PSI_memory_key key_memory_MYSQL_RELAY_LOG_basename; extern PSI_memory_key key_memory_MYSQL_RELAY_LOG_index; extern PSI_memory_key key_memory_rpl_filter; extern PSI_memory_key key_memory_Security_context; extern PSI_memory_key key_memory_NET_buff; extern PSI_memory_key key_memory_NET_compress_packet; extern PSI_memory_key key_memory_my_bitmap_map; extern PSI_memory_key key_memory_QUICK_RANGE_SELECT_mrr_buf_desc; extern PSI_memory_key key_memory_TABLE_RULE_ENT; extern PSI_memory_key key_memory_Mutex_cond_array_Mutex_cond; extern PSI_memory_key key_memory_Owned_gtids_sidno_to_hash; extern PSI_memory_key key_memory_Sid_map_Node; extern PSI_memory_key key_memory_bison_stack; extern PSI_memory_key key_memory_TABLE_sort_io_cache; extern PSI_memory_key key_memory_DATE_TIME_FORMAT; extern PSI_memory_key key_memory_DDL_LOG_MEMORY_ENTRY; extern PSI_memory_key key_memory_ST_SCHEMA_TABLE; extern PSI_memory_key key_memory_ignored_db; extern PSI_memory_key key_memory_SLAVE_INFO; extern PSI_memory_key key_memory_log_event_old; extern PSI_memory_key key_memory_HASH_ROW_ENTRY; extern PSI_memory_key key_memory_table_def_memory; extern PSI_memory_key key_memory_MPVIO_EXT_auth_info; extern PSI_memory_key key_memory_LOG_POS_COORD; extern PSI_memory_key key_memory_XID_STATE; extern PSI_memory_key key_memory_Rpl_info_file_buffer; extern PSI_memory_key key_memory_Rpl_info_table; extern PSI_memory_key key_memory_binlog_pos; extern PSI_memory_key key_memory_db_worker_hash_entry; extern PSI_memory_key key_memory_rpl_slave_command_buffer; extern PSI_memory_key key_memory_binlog_ver_1_event; extern PSI_memory_key key_memory_rpl_slave_check_temp_dir; extern PSI_memory_key key_memory_TABLE; extern PSI_memory_key key_memory_binlog_statement_buffer; extern PSI_memory_key key_memory_user_conn; extern PSI_memory_key key_memory_dboptions_hash; extern PSI_memory_key key_memory_dbnames_cache; extern PSI_memory_key key_memory_hash_index_key_buffer; extern PSI_memory_key key_memory_THD_handler_tables_hash; extern PSI_memory_key key_memory_JOIN_CACHE; extern PSI_memory_key key_memory_READ_INFO; extern PSI_memory_key key_memory_partition_syntax_buffer; extern PSI_memory_key key_memory_global_system_variables; extern PSI_memory_key key_memory_THD_variables; extern PSI_memory_key key_memory_PROFILE; extern PSI_memory_key key_memory_LOG_name; extern PSI_memory_key key_memory_string_iterator; extern PSI_memory_key key_memory_frm_extra_segment_buff; extern PSI_memory_key key_memory_frm_form_pos; extern PSI_memory_key key_memory_frm_string; extern PSI_memory_key key_memory_Unique_sort_buffer; extern PSI_memory_key key_memory_Unique_merge_buffer; extern PSI_memory_key key_memory_shared_memory_name; extern PSI_memory_key key_memory_opt_bin_logname; extern PSI_memory_key key_memory_Query_cache; extern PSI_memory_key key_memory_READ_RECORD_cache; extern PSI_memory_key key_memory_Quick_ranges; extern PSI_memory_key key_memory_File_query_log_name; extern PSI_memory_key key_memory_Table_trigger_dispatcher; extern PSI_memory_key key_memory_show_slave_status_io_gtid_set; extern PSI_memory_key key_memory_write_set_extraction; extern PSI_memory_key key_memory_thd_timer; extern PSI_memory_key key_memory_THD_Session_tracker; extern PSI_memory_key key_memory_THD_Session_sysvar_resource_manager; extern PSI_memory_key key_memory_get_all_tables; extern PSI_memory_key key_memory_fill_schema_schemata; extern PSI_memory_key key_memory_native_functions; extern PSI_memory_key key_memory_JSON; extern PSI_memory_key key_memory_WSREP; /* MAINTAINER: Please keep this list in order, to limit merge collisions. Hint: grep PSI_stage_info | sort -u */ extern PSI_stage_info stage_apply_event; extern PSI_stage_info stage_after_create; extern PSI_stage_info stage_after_opening_tables; extern PSI_stage_info stage_after_table_lock; extern PSI_stage_info stage_allocating_local_table; extern PSI_stage_info stage_alter_inplace_prepare; extern PSI_stage_info stage_alter_inplace; extern PSI_stage_info stage_alter_inplace_commit; extern PSI_stage_info stage_after_apply_event; extern PSI_stage_info stage_changing_master; extern PSI_stage_info stage_checking_master_version; extern PSI_stage_info stage_checking_permissions; extern PSI_stage_info stage_checking_privileges_on_cached_query; extern PSI_stage_info stage_checking_query_cache_for_query; extern PSI_stage_info stage_cleaning_up; extern PSI_stage_info stage_closing_tables; extern PSI_stage_info stage_connecting_to_master; extern PSI_stage_info stage_converting_heap_to_myisam; extern PSI_stage_info stage_copying_to_group_table; extern PSI_stage_info stage_copying_to_tmp_table; extern PSI_stage_info stage_copy_to_tmp_table; extern PSI_stage_info stage_creating_delayed_handler; extern PSI_stage_info stage_creating_sort_index; extern PSI_stage_info stage_creating_table; extern PSI_stage_info stage_creating_tmp_table; extern PSI_stage_info stage_deleting_from_main_table; extern PSI_stage_info stage_deleting_from_reference_tables; extern PSI_stage_info stage_discard_or_import_tablespace; extern PSI_stage_info stage_end; extern PSI_stage_info stage_enabling_keys; extern PSI_stage_info stage_executing; extern PSI_stage_info stage_execution_of_init_command; extern PSI_stage_info stage_explaining; extern PSI_stage_info stage_finding_key_cache; extern PSI_stage_info stage_finished_reading_one_binlog_switching_to_next_binlog; extern PSI_stage_info stage_flushing_relay_log_and_master_info_repository; extern PSI_stage_info stage_flushing_relay_log_info_file; extern PSI_stage_info stage_freeing_items; extern PSI_stage_info stage_fulltext_initialization; extern PSI_stage_info stage_got_handler_lock; extern PSI_stage_info stage_got_old_table; extern PSI_stage_info stage_init; extern PSI_stage_info stage_init_update; extern PSI_stage_info stage_insert; extern PSI_stage_info stage_invalidating_query_cache_entries_table; extern PSI_stage_info stage_invalidating_query_cache_entries_table_list; extern PSI_stage_info stage_killing_slave; extern PSI_stage_info stage_logging_slow_query; extern PSI_stage_info stage_making_temp_file_append_before_load_data; extern PSI_stage_info stage_making_temp_file_create_before_load_data; extern PSI_stage_info stage_manage_keys; extern PSI_stage_info stage_master_has_sent_all_binlog_to_slave; extern PSI_stage_info stage_opening_tables; extern PSI_stage_info stage_optimizing; extern PSI_stage_info stage_preparing; extern PSI_stage_info stage_purging_old_relay_logs; extern PSI_stage_info stage_query_end; extern PSI_stage_info stage_starting_cleanup; extern PSI_stage_info stage_slave_sql_cleanup; extern PSI_stage_info stage_rollback; extern PSI_stage_info stage_rollback_implicit; extern PSI_stage_info stage_commit; extern PSI_stage_info stage_commit_implicit; extern PSI_stage_info stage_queueing_master_event_to_the_relay_log; extern PSI_stage_info stage_reading_event_from_the_relay_log; extern PSI_stage_info stage_recreating_table; extern PSI_stage_info stage_registering_slave_on_master; extern PSI_stage_info stage_removing_duplicates; extern PSI_stage_info stage_removing_tmp_table; extern PSI_stage_info stage_rename; extern PSI_stage_info stage_rename_result_table; extern PSI_stage_info stage_requesting_binlog_dump; extern PSI_stage_info stage_reschedule; extern PSI_stage_info stage_searching_rows_for_update; extern PSI_stage_info stage_sending_binlog_event_to_slave; extern PSI_stage_info stage_sending_cached_result_to_client; extern PSI_stage_info stage_sending_data; extern PSI_stage_info stage_setup; extern PSI_stage_info stage_slave_has_read_all_relay_log; extern PSI_stage_info stage_show_explain; extern PSI_stage_info stage_sorting; extern PSI_stage_info stage_sorting_for_group; extern PSI_stage_info stage_sorting_for_order; extern PSI_stage_info stage_sorting_result; extern PSI_stage_info stage_sql_thd_waiting_until_delay; extern PSI_stage_info stage_statistics; extern PSI_stage_info stage_storing_result_in_query_cache; extern PSI_stage_info stage_storing_row_into_queue; extern PSI_stage_info stage_system_lock; extern PSI_stage_info stage_unlocking_tables; extern PSI_stage_info stage_table_lock; extern PSI_stage_info stage_filling_schema_table; extern PSI_stage_info stage_update; extern PSI_stage_info stage_updating; extern PSI_stage_info stage_updating_main_table; extern PSI_stage_info stage_updating_reference_tables; extern PSI_stage_info stage_upgrading_lock; extern PSI_stage_info stage_user_lock; extern PSI_stage_info stage_user_sleep; extern PSI_stage_info stage_verifying_table; extern PSI_stage_info stage_waiting_for_ddl; extern PSI_stage_info stage_waiting_for_delay_list; extern PSI_stage_info stage_waiting_for_disk_space; extern PSI_stage_info stage_waiting_for_flush; extern PSI_stage_info stage_waiting_for_gtid_to_be_written_to_binary_log; extern PSI_stage_info stage_waiting_for_handler_insert; extern PSI_stage_info stage_waiting_for_handler_lock; extern PSI_stage_info stage_waiting_for_handler_open; extern PSI_stage_info stage_waiting_for_insert; extern PSI_stage_info stage_waiting_for_master_to_send_event; extern PSI_stage_info stage_waiting_for_master_update; extern PSI_stage_info stage_waiting_for_relay_log_space; extern PSI_stage_info stage_waiting_for_slave_mutex_on_exit; extern PSI_stage_info stage_waiting_for_slave_thread_to_start; extern PSI_stage_info stage_waiting_for_query_cache_lock; extern PSI_stage_info stage_waiting_for_table_flush; extern PSI_stage_info stage_waiting_for_the_next_event_in_relay_log; extern PSI_stage_info stage_waiting_for_the_slave_thread_to_advance_position; extern PSI_stage_info stage_waiting_to_finalize_termination; extern PSI_stage_info stage_binlog_waiting_background_tasks; extern PSI_stage_info stage_binlog_write; extern PSI_stage_info stage_binlog_processing_checkpoint_notify; extern PSI_stage_info stage_binlog_stopping_background_thread; extern PSI_stage_info stage_waiting_for_work_from_sql_thread; extern PSI_stage_info stage_waiting_for_prior_transaction_to_commit; extern PSI_stage_info stage_waiting_for_prior_transaction_to_start_commit; extern PSI_stage_info stage_waiting_for_room_in_worker_thread; extern PSI_stage_info stage_waiting_for_workers_idle; extern PSI_stage_info stage_waiting_for_ftwrl; extern PSI_stage_info stage_waiting_for_ftwrl_threads_to_pause; extern PSI_stage_info stage_waiting_for_rpl_thread_pool; extern PSI_stage_info stage_master_gtid_wait_primary; extern PSI_stage_info stage_master_gtid_wait; extern PSI_stage_info stage_gtid_wait_other_connection; extern PSI_stage_info stage_slave_background_process_request; extern PSI_stage_info stage_slave_background_wait_request; extern PSI_stage_info stage_waiting_for_deadlock_kill; extern PSI_stage_info stage_starting; #ifdef HAVE_PSI_STATEMENT_INTERFACE /** Statement instrumentation keys (sql). The last entry, at [SQLCOM_END], is for parsing errors. */ extern PSI_statement_info sql_statement_info[(uint) SQLCOM_END + 1]; /** Statement instrumentation keys (com). The last entry, at [COM_END], is for packet errors. */ extern PSI_statement_info com_statement_info[(uint) COM_END + 1]; /** Statement instrumentation key for replication. */ extern PSI_statement_info stmt_info_rpl; void init_sql_statement_info(); void init_com_statement_info(); #endif /* HAVE_PSI_STATEMENT_INTERFACE */ #ifndef _WIN32 extern pthread_t signal_thread; #endif #ifdef HAVE_OPENSSL extern struct st_VioSSLFd * ssl_acceptor_fd; #endif /* HAVE_OPENSSL */ /* The following variables were under INNODB_COMPABILITY_HOOKS */ extern my_bool opt_large_pages; extern uint opt_large_page_size; extern MYSQL_PLUGIN_IMPORT char lc_messages_dir[FN_REFLEN]; extern char *lc_messages_dir_ptr, *log_error_file_ptr; extern MYSQL_PLUGIN_IMPORT char reg_ext[FN_EXTLEN]; extern MYSQL_PLUGIN_IMPORT uint reg_ext_length; extern MYSQL_PLUGIN_IMPORT uint lower_case_table_names; extern MYSQL_PLUGIN_IMPORT bool mysqld_embedded; extern ulong specialflag; extern uint mysql_data_home_len; extern uint mysql_real_data_home_len; extern const char *mysql_real_data_home_ptr; extern ulong thread_handling; extern "C" MYSQL_PLUGIN_IMPORT char server_version[SERVER_VERSION_LENGTH]; extern char *server_version_ptr; extern bool using_custom_server_version; extern MYSQL_PLUGIN_IMPORT char mysql_real_data_home[]; extern char mysql_unpacked_real_data_home[]; extern MYSQL_PLUGIN_IMPORT struct system_variables global_system_variables; extern char default_logfile_name[FN_REFLEN]; extern char *my_proxy_protocol_networks; #define mysql_tmpdir (my_tmpdir(&mysql_tmpdir_list)) extern MYSQL_PLUGIN_IMPORT const key_map key_map_empty; extern MYSQL_PLUGIN_IMPORT key_map key_map_full; /* Should be threaded as const */ /* Server mutex locks and condition variables. */ extern mysql_mutex_t LOCK_item_func_sleep, LOCK_status, LOCK_error_log, LOCK_delayed_insert, LOCK_short_uuid_generator, LOCK_delayed_status, LOCK_delayed_create, LOCK_crypt, LOCK_timezone, LOCK_active_mi, LOCK_manager, LOCK_user_conn, LOCK_prepared_stmt_count, LOCK_error_messages, LOCK_backup_log; extern MYSQL_PLUGIN_IMPORT mysql_mutex_t LOCK_global_system_variables; extern mysql_rwlock_t LOCK_all_status_vars; extern mysql_mutex_t LOCK_start_thread; extern MYSQL_PLUGIN_IMPORT mysql_mutex_t LOCK_server_started; extern MYSQL_PLUGIN_IMPORT mysql_cond_t COND_server_started; extern mysql_rwlock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave; extern mysql_rwlock_t LOCK_ssl_refresh; extern mysql_prlock_t LOCK_system_variables_hash; extern mysql_cond_t COND_start_thread; extern mysql_cond_t COND_manager; extern my_bool opt_use_ssl; extern char *opt_ssl_ca, *opt_ssl_capath, *opt_ssl_cert, *opt_ssl_cipher, *opt_ssl_key, *opt_ssl_crl, *opt_ssl_crlpath; extern ulonglong tls_version; #ifdef MYSQL_SERVER /** only options that need special treatment in get_one_option() deserve to be listed below */ enum options_mysqld { OPT_to_set_the_start_number=256, OPT_BINLOG_DO_DB, OPT_BINLOG_FORMAT, OPT_BINLOG_IGNORE_DB, OPT_BIN_LOG, OPT_BOOTSTRAP, OPT_EXPIRE_LOGS_DAYS, OPT_BINLOG_EXPIRE_LOGS_SECONDS, OPT_CONSOLE, OPT_DEBUG_SYNC_TIMEOUT, OPT_REMOVED_OPTION, OPT_IGNORE_DB_DIRECTORY, OPT_ISAM_LOG, OPT_KEY_BUFFER_SIZE, OPT_KEY_CACHE_AGE_THRESHOLD, OPT_KEY_CACHE_BLOCK_SIZE, OPT_KEY_CACHE_DIVISION_LIMIT, OPT_KEY_CACHE_PARTITIONS, OPT_KEY_CACHE_CHANGED_BLOCKS_HASH_SIZE, OPT_LOG_BASENAME, OPT_LOG_ERROR, OPT_LOG_SLOW_FILTER, OPT_LOWER_CASE_TABLE_NAMES, OPT_PLUGIN_LOAD, OPT_PLUGIN_LOAD_ADD, OPT_PFS_INSTRUMENT, OPT_REPLICATE_DO_DB, OPT_REPLICATE_DO_TABLE, OPT_REPLICATE_IGNORE_DB, OPT_REPLICATE_IGNORE_TABLE, OPT_REPLICATE_REWRITE_DB, OPT_REPLICATE_WILD_DO_TABLE, OPT_REPLICATE_WILD_IGNORE_TABLE, OPT_SAFE, OPT_SERVER_ID, OPT_SILENT, OPT_SKIP_HOST_CACHE, OPT_SLAVE_PARALLEL_MODE, OPT_SSL_CA, OPT_SSL_CAPATH, OPT_SSL_CERT, OPT_SSL_CIPHER, OPT_SSL_CRL, OPT_SSL_CRLPATH, OPT_SSL_KEY, OPT_THREAD_CONCURRENCY, OPT_WANT_CORE, #ifdef WITH_WSREP OPT_WSREP_CAUSAL_READS, OPT_WSREP_SYNC_WAIT, #endif /* WITH_WSREP */ OPT_MYSQL_COMPATIBILITY, OPT_TLS_VERSION, OPT_SECURE_AUTH, OPT_MYSQL_TO_BE_IMPLEMENTED, OPT_which_is_always_the_last }; #endif /** Query type constants (usable as bitmap flags). */ enum enum_query_type { /// Nothing specific, ordinary SQL query. QT_ORDINARY= 0, /// In utf8. QT_TO_SYSTEM_CHARSET= (1 << 0), /// Without character set introducers. QT_WITHOUT_INTRODUCERS= (1 << 1), /// view internal representation (like QT_ORDINARY except ORDER BY clause) QT_VIEW_INTERNAL= (1 << 2), /// If identifiers should not include database names, where unambiguous QT_ITEM_IDENT_SKIP_DB_NAMES= (1 << 3), /// If identifiers should not include table names, where unambiguous QT_ITEM_IDENT_SKIP_TABLE_NAMES= (1 << 4), /// If Item_cache_wrapper should not print QT_ITEM_CACHE_WRAPPER_SKIP_DETAILS= (1 << 5), /// If Item_subselect should print as just "(subquery#1)" /// rather than display the subquery body QT_ITEM_SUBSELECT_ID_ONLY= (1 << 6), /// If NULLIF(a,b) should print itself as /// CASE WHEN a_for_comparison=b THEN NULL ELSE a_for_return_value END /// when "a" was replaced to two different items /// (e.g. by equal fields propagation in optimize_cond()) /// or always as NULLIF(a, b). /// The default behaviour is to use CASE syntax when /// a_for_return_value is not the same as a_for_comparison. /// SHOW CREATE {VIEW|PROCEDURE|FUNCTION} and other cases where the /// original representation is required, should set this flag. QT_ITEM_ORIGINAL_FUNC_NULLIF= (1 << 7), /// good for parsing QT_PARSABLE= (1 << 8), // If an expression is constant, print the expression, not the value // it evaluates to. Should be used for error messages, so that they // don't reveal values. QT_NO_DATA_EXPANSION= (1 << 9), /// This value means focus on readability, not on ability to parse back, etc. QT_EXPLAIN= QT_TO_SYSTEM_CHARSET | QT_ITEM_IDENT_SKIP_DB_NAMES | QT_ITEM_CACHE_WRAPPER_SKIP_DETAILS | QT_ITEM_SUBSELECT_ID_ONLY, QT_SHOW_SELECT_NUMBER= (1<<10), /// Do not print database name or table name in the identifiers (even if /// this means the printout will be ambigous). It is assumed that the caller /// passing this flag knows what they are doing. QT_ITEM_IDENT_DISABLE_DB_TABLE_NAMES= (1 <<11), /// This is used for EXPLAIN EXTENDED extra warnings / Be more detailed /// Be more detailed than QT_EXPLAIN. /// Perhaps we should eventually include QT_ITEM_IDENT_SKIP_CURRENT_DATABASE /// here, as it would give better readable results QT_EXPLAIN_EXTENDED= QT_TO_SYSTEM_CHARSET| QT_SHOW_SELECT_NUMBER, // Remove wrappers added for TVC when creating or showing view QT_NO_WRAPPERS_FOR_TVC_IN_VIEW= (1 << 12), /// Print for FRM file. Focus on parse-back. /// e.g. VIEW expressions and virtual column expressions QT_FOR_FRM= (1 << 13) }; /* query_id */ extern Atomic_counter global_query_id; /* increment query_id and return it. */ inline __attribute__((warn_unused_result)) query_id_t next_query_id() { return global_query_id++; } inline query_id_t get_query_id() { return global_query_id; } /* increment global_thread_id and return it. */ extern __attribute__((warn_unused_result)) my_thread_id next_thread_id(void); /* TODO: Replace this with an inline function. */ #ifndef EMBEDDED_LIBRARY extern "C" void unireg_abort(int exit_code) __attribute__((noreturn)); #else extern "C" void unireg_clear(int exit_code); #define unireg_abort(exit_code) do { unireg_clear(exit_code); DBUG_RETURN(exit_code); } while(0) #endif inline void table_case_convert(char * name, uint length) { if (lower_case_table_names) files_charset_info->casedn(name, length, name, length); } extern char *set_server_version(char *buf, size_t size); #define current_thd _current_thd() void set_current_thd(THD *thd); /* @todo remove, make it static in ha_maria.cc currently it's needed for sql_select.cc */ extern handlerton *maria_hton; extern uint64 global_gtid_counter; extern my_bool opt_gtid_strict_mode; extern my_bool opt_userstat_running, debug_assert_if_crashed_table; extern uint mysqld_extra_port; extern ulong opt_progress_report_time; extern ulong extra_max_connections; extern ulonglong denied_connections; extern ulong thread_created; extern scheduler_functions *thread_scheduler, *extra_thread_scheduler; extern char *opt_log_basename; extern my_bool opt_master_verify_checksum; extern my_bool opt_stack_trace, disable_log_notes; extern my_bool opt_expect_abort; extern my_bool opt_slave_sql_verify_checksum; extern my_bool opt_mysql56_temporal_format, strict_password_validation; extern ulong binlog_checksum_options; extern bool max_user_connections_checking; extern ulong opt_binlog_dbug_fsync_sleep; static const int SERVER_UID_SIZE= 29; extern char server_uid[SERVER_UID_SIZE+1]; extern uint volatile global_disable_checkpoint; extern my_bool opt_help; extern int mysqld_main(int argc, char **argv); #ifdef _WIN32 extern HANDLE hEventShutdown; extern void mysqld_win_initiate_shutdown(); extern void mysqld_win_set_startup_complete(); extern void mysqld_win_extend_service_timeout(DWORD sec); extern void mysqld_set_service_status_callback(void (*)(DWORD, DWORD, DWORD)); extern void mysqld_win_set_service_name(const char *name); #endif #endif /* MYSQLD_INCLUDED */ mysql/server/private/log_slow.h000064400000004612151027430560012675 0ustar00/* Copyright (C) 2009, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 or later of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Defining what to log to slow log */ #ifndef LOG_SLOW_INCLUDED #define LOG_SLOW_INCLUDED #define LOG_SLOW_VERBOSITY_INIT 0 #define LOG_SLOW_VERBOSITY_INNODB (1U << 0) /* Old option */ #define LOG_SLOW_VERBOSITY_QUERY_PLAN (1U << 1) #define LOG_SLOW_VERBOSITY_EXPLAIN (1U << 2) #define LOG_SLOW_VERBOSITY_STORAGE_ENGINE (1U << 3) /* Replaces InnoDB */ #define LOG_SLOW_VERBOSITY_WARNINGS (1U << 4) #define LOG_SLOW_VERBOSITY_FULL (1U << 5) #define LOG_SLOW_VERBOSITY_ENGINE (LOG_SLOW_VERBOSITY_FULL | \ LOG_SLOW_VERBOSITY_INNODB | \ LOG_SLOW_VERBOSITY_STORAGE_ENGINE) #define QPLAN_INIT QPLAN_QC_NO #define QPLAN_ADMIN (1U << 0) #define QPLAN_FILESORT (1U << 1) #define QPLAN_FILESORT_DISK (1U << 2) #define QPLAN_FILESORT_PRIORITY_QUEUE (1U << 3) #define QPLAN_FULL_JOIN (1U << 4) #define QPLAN_FULL_SCAN (1U << 5) #define QPLAN_NOT_USING_INDEX (1U << 6) #define QPLAN_QC (1U << 7) #define QPLAN_QC_NO (1U << 8) #define QPLAN_TMP_TABLE (1U << 9) #define QPLAN_TMP_DISK (1U << 10) /* ... */ #define QPLAN_STATUS (1UL << 31) /* not in the slow_log_filter */ #define QPLAN_MAX (1UL << 31) /* reserved as placeholder */ /* Bits for log_slow_disabled_statements */ #define LOG_SLOW_DISABLE_ADMIN (1 << 0) #define LOG_SLOW_DISABLE_CALL (1 << 1) #define LOG_SLOW_DISABLE_SLAVE (1 << 2) #define LOG_SLOW_DISABLE_SP (1 << 3) /* Bits for log_disabled_statements */ #define LOG_DISABLE_SLAVE (1 << 0) #define LOG_DISABLE_SP (1 << 1) #endif /* LOG_SLOW_INCLUDED */ mysql/server/private/keycaches.h000064400000003713151027430560013010 0ustar00#ifndef KEYCACHES_INCLUDED #define KEYCACHES_INCLUDED /* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_list.h" #include #include extern "C" { typedef int (*process_key_cache_t) (const char *, KEY_CACHE *, void *); } class NAMED_ILINK; class NAMED_ILIST: public I_List { public: void delete_elements(void (*free_element)(const char*, void*)); bool delete_element(const char *name, size_t length, void (*free_element)(const char*, void*)); }; /* For key cache */ extern LEX_CSTRING default_key_cache_base; extern KEY_CACHE zero_key_cache; extern NAMED_ILIST key_caches; KEY_CACHE *create_key_cache(const char *name, size_t length); KEY_CACHE *get_key_cache(const LEX_CSTRING *cache_name); KEY_CACHE *get_or_create_key_cache(const char *name, size_t length); void free_key_cache(const char *name, void *key_cache); bool process_key_caches(process_key_cache_t func, void *param); /* For Rpl_filter */ extern LEX_CSTRING default_rpl_filter_base; extern NAMED_ILIST rpl_filters; Rpl_filter *create_rpl_filter(const char *name, size_t length); Rpl_filter *get_rpl_filter(LEX_CSTRING *filter_name); Rpl_filter *get_or_create_rpl_filter(const char *name, size_t length); void free_all_rpl_filters(void); #endif /* KEYCACHES_INCLUDED */ mysql/server/private/pfs_socket_provider.h000064400000004322151027430560015120 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_SOCKET_PROVIDER_H #define PFS_SOCKET_PROVIDER_H /** @file include/pfs_socket_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_SOCKET_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_SOCKET_CALL(M) pfs_ ## M ## _v1 C_MODE_START void pfs_register_socket_v1(const char *category, PSI_socket_info_v1 *info, int count); PSI_socket* pfs_init_socket_v1(PSI_socket_key key, const my_socket *fd, const struct sockaddr *addr, socklen_t addr_len); void pfs_destroy_socket_v1(PSI_socket *socket); PSI_socket_locker* pfs_start_socket_wait_v1(PSI_socket_locker_state *state, PSI_socket *socket, PSI_socket_operation op, size_t count, const char *src_file, uint src_line); void pfs_end_socket_wait_v1(PSI_socket_locker *locker, size_t byte_count); void pfs_set_socket_state_v1(PSI_socket *socket, PSI_socket_state state); void pfs_set_socket_info_v1(PSI_socket *socket, const my_socket *fd, const struct sockaddr *addr, socklen_t addr_len); void pfs_set_socket_thread_owner_v1(PSI_socket *socket); C_MODE_END #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_SOCKET_INTERFACE */ #endif mysql/server/private/sql_derived.h000064400000002411151027430560013344 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_DERIVED_INCLUDED #define SQL_DERIVED_INCLUDED struct TABLE_LIST; class THD; struct LEX; bool mysql_handle_derived(LEX *lex, uint phases); bool mysql_handle_single_derived(LEX *lex, TABLE_LIST *derived, uint phases); Item *transform_condition_or_part(THD *thd, Item *cond, Item_transformer transformer, uchar *arg); bool pushdown_cond_for_derived(THD *thd, Item *cond, TABLE_LIST *derived); #endif /* SQL_DERIVED_INCLUDED */ mysql/server/private/replication.h000064400000037352151027430560013370 0ustar00/* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef REPLICATION_H #define REPLICATION_H /*************************************************************************** NOTE: plugin locking. The plugin is locked on Binlog_transmit_observer::transmit_start and is unlocked after Binlog_transmit_observer::transmit_stop. All other master observable events happen between these two and don't lock the plugin at all. Also a plugin is locked on Binlog_relay_IO_observer::thread_start and unlocked after Binlog_relay_IO_observer::thread_stop. ***************************************************************************/ #include typedef struct st_mysql MYSQL; #ifdef __cplusplus extern "C" { #endif /** Transaction observer flags. */ enum Trans_flags { /** Transaction is a real transaction */ TRANS_IS_REAL_TRANS = 1 }; /** Transaction observer parameter */ typedef struct Trans_param { uint32 server_id; uint32 flags; /* The latest binary log file name and position written by current transaction, if binary log is disabled or no log event has been written into binary log file by current transaction (events written into transaction log cache are not counted), these two member will be zero. */ const char *log_file; my_off_t log_pos; } Trans_param; /** Observes and extends transaction execution */ typedef struct Trans_observer { uint32 len; /** This callback is called after transaction commit This callback is called right after commit to storage engines for transactional tables. For non-transactional tables, this is called at the end of the statement, before sending statement status, if the statement succeeded. @note The return value is currently ignored by the server. @note This hook is called wo/ any global mutex held @param param The parameter for transaction observers @retval 0 Sucess @retval 1 Failure */ int (*after_commit)(Trans_param *param); /** This callback is called after transaction rollback This callback is called right after rollback to storage engines for transactional tables. For non-transactional tables, this is called at the end of the statement, before sending statement status, if the statement failed. @note The return value is currently ignored by the server. @param param The parameter for transaction observers @note This hook is called wo/ any global mutex held @retval 0 Sucess @retval 1 Failure */ int (*after_rollback)(Trans_param *param); } Trans_observer; /** Binlog storage flags */ enum Binlog_storage_flags { /** Binary log was sync:ed */ BINLOG_STORAGE_IS_SYNCED = 1, /** First(or alone) in a group commit */ BINLOG_GROUP_COMMIT_LEADER = 2, /** Last(or alone) in a group commit */ BINLOG_GROUP_COMMIT_TRAILER = 4 }; /** Binlog storage observer parameters */ typedef struct Binlog_storage_param { uint32 server_id; } Binlog_storage_param; /** Observe binlog logging storage */ typedef struct Binlog_storage_observer { uint32 len; /** This callback is called after binlog has been flushed This callback is called after cached events have been flushed to binary log file. Whether the binary log file is synchronized to disk is indicated by the bit BINLOG_STORAGE_IS_SYNCED in @a flags. @note: this hook is called with LOCK_log mutex held @param param Observer common parameter @param log_file Binlog file name been updated @param log_pos Binlog position after update @param flags flags for binlog storage @retval 0 Sucess @retval 1 Failure */ int (*after_flush)(Binlog_storage_param *param, const char *log_file, my_off_t log_pos, uint32 flags); /** This callback is called after binlog has been synced This callback is called after events flushed to disk has been sync:ed ("group committed"). @note: this hook is called with LOCK_after_binlog_sync mutex held @param param Observer common parameter @param log_file Binlog file name been updated @param log_pos Binlog position after update @param flags flags for binlog storage @retval 0 Sucess @retval 1 Failure */ int (*after_sync)(Binlog_storage_param *param, const char *log_file, my_off_t log_pos, uint32 flags); } Binlog_storage_observer; /** Replication binlog transmitter (binlog dump) observer parameter. */ typedef struct Binlog_transmit_param { uint32 server_id; uint32 flags; } Binlog_transmit_param; /** Observe and extends the binlog dumping thread. */ typedef struct Binlog_transmit_observer { uint32 len; /** This callback is called when binlog dumping starts @param param Observer common parameter @param log_file Binlog file name to transmit from @param log_pos Binlog position to transmit from @retval 0 Sucess @retval 1 Failure */ int (*transmit_start)(Binlog_transmit_param *param, const char *log_file, my_off_t log_pos); /** This callback is called when binlog dumping stops @param param Observer common parameter @retval 0 Sucess @retval 1 Failure */ int (*transmit_stop)(Binlog_transmit_param *param); /** This callback is called to reserve bytes in packet header for event transmission This callback is called when resetting transmit packet header to reserve bytes for this observer in packet header. The @a header buffer is allocated by the server code, and @a size is the size of the header buffer. Each observer can only reserve a maximum size of @a size in the header. @param param Observer common parameter @param header Pointer of the header buffer @param size Size of the header buffer @param len Header length reserved by this observer @retval 0 Sucess @retval 1 Failure */ int (*reserve_header)(Binlog_transmit_param *param, unsigned char *header, unsigned long size, unsigned long *len); /** This callback is called before sending an event packet to slave @param param Observer common parameter @param packet Binlog event packet to send @param len Length of the event packet @param log_file Binlog file name of the event packet to send @param log_pos Binlog position of the event packet to send @retval 0 Sucess @retval 1 Failure */ int (*before_send_event)(Binlog_transmit_param *param, unsigned char *packet, unsigned long len, const char *log_file, my_off_t log_pos ); /** This callback is called after sending an event packet to slave @param param Observer common parameter @param event_buf Binlog event packet buffer sent @param len length of the event packet buffer @retval 0 Sucess @retval 1 Failure */ int (*after_send_event)(Binlog_transmit_param *param, const char *event_buf, unsigned long len); /** This callback is called after resetting master status This is called when executing the command RESET MASTER, and is used to reset status variables added by observers. @param param Observer common parameter @retval 0 Sucess @retval 1 Failure */ int (*after_reset_master)(Binlog_transmit_param *param); } Binlog_transmit_observer; /** Binlog relay IO flags */ enum Binlog_relay_IO_flags { /** Binary relay log was sync:ed */ BINLOG_RELAY_IS_SYNCED = 1 }; /** Replication binlog relay IO observer parameter */ typedef struct Binlog_relay_IO_param { uint32 server_id; /* Master host, user and port */ char *host; char *user; unsigned int port; char *master_log_name; my_off_t master_log_pos; MYSQL *mysql; /* the connection to master */ } Binlog_relay_IO_param; /** Observes and extends the service of slave IO thread. */ typedef struct Binlog_relay_IO_observer { uint32 len; /** This callback is called when slave IO thread starts @param param Observer common parameter @retval 0 Sucess @retval 1 Failure */ int (*thread_start)(Binlog_relay_IO_param *param); /** This callback is called when slave IO thread stops @param param Observer common parameter @retval 0 Sucess @retval 1 Failure */ int (*thread_stop)(Binlog_relay_IO_param *param); /** This callback is called before slave requesting binlog transmission from master This is called before slave issuing BINLOG_DUMP command to master to request binlog. @param param Observer common parameter @param flags binlog dump flags @retval 0 Sucess @retval 1 Failure */ int (*before_request_transmit)(Binlog_relay_IO_param *param, uint32 flags); /** This callback is called after read an event packet from master @param param Observer common parameter @param packet The event packet read from master @param len Length of the event packet read from master @param event_buf The event packet return after process @param event_len The length of event packet return after process @retval 0 Sucess @retval 1 Failure */ int (*after_read_event)(Binlog_relay_IO_param *param, const char *packet, unsigned long len, const char **event_buf, unsigned long *event_len); /** This callback is called after written an event packet to relay log @param param Observer common parameter @param event_buf Event packet written to relay log @param event_len Length of the event packet written to relay log @param flags flags for relay log @retval 0 Sucess @retval 1 Failure */ int (*after_queue_event)(Binlog_relay_IO_param *param, const char *event_buf, unsigned long event_len, uint32 flags); /** This callback is called after reset slave relay log IO status @param param Observer common parameter @retval 0 Sucess @retval 1 Failure */ int (*after_reset_slave)(Binlog_relay_IO_param *param); } Binlog_relay_IO_observer; /** Register a transaction observer @param observer The transaction observer to register @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer already exists */ int register_trans_observer(Trans_observer *observer, void *p); /** Unregister a transaction observer @param observer The transaction observer to unregister @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer not exists */ int unregister_trans_observer(Trans_observer *observer, void *p); /** Register a binlog storage observer @param observer The binlog storage observer to register @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer already exists */ int register_binlog_storage_observer(Binlog_storage_observer *observer, void *p); /** Unregister a binlog storage observer @param observer The binlog storage observer to unregister @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer not exists */ int unregister_binlog_storage_observer(Binlog_storage_observer *observer, void *p); /** Register a binlog transmit observer @param observer The binlog transmit observer to register @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer already exists */ int register_binlog_transmit_observer(Binlog_transmit_observer *observer, void *p); /** Unregister a binlog transmit observer @param observer The binlog transmit observer to unregister @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer not exists */ int unregister_binlog_transmit_observer(Binlog_transmit_observer *observer, void *p); /** Register a binlog relay IO (slave IO thread) observer @param observer The binlog relay IO observer to register @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer already exists */ int register_binlog_relay_io_observer(Binlog_relay_IO_observer *observer, void *p); /** Unregister a binlog relay IO (slave IO thread) observer @param observer The binlog relay IO observer to unregister @param p pointer to the internal plugin structure @retval 0 Sucess @retval 1 Observer not exists */ int unregister_binlog_relay_io_observer(Binlog_relay_IO_observer *observer, void *p); /** Connect to master This function can only used in the slave I/O thread context, and will use the same master information to do the connection. @code MYSQL *mysql = mysql_init(NULL); if (rpl_connect_master(mysql)) { // do stuff with the connection } mysql_close(mysql); // close the connection @endcode @param mysql address of MYSQL structure to use, pass NULL will create a new one @return address of MYSQL structure on success, NULL on failure */ MYSQL *rpl_connect_master(MYSQL *mysql); /** Get the value of user variable as an integer. This function will return the value of variable @a name as an integer. If the original value of the variable is not an integer, the value will be converted into an integer. @param name user variable name @param value pointer to return the value @param null_value if not NULL, the function will set it to true if the value of variable is null, set to false if not @retval 0 Success @retval 1 Variable not found */ int get_user_var_int(const char *name, long long int *value, int *null_value); /** Get the value of user variable as a double precision float number. This function will return the value of variable @a name as real number. If the original value of the variable is not a real number, the value will be converted into a real number. @param name user variable name @param value pointer to return the value @param null_value if not NULL, the function will set it to true if the value of variable is null, set to false if not @retval 0 Success @retval 1 Variable not found */ int get_user_var_real(const char *name, double *value, int *null_value); /** Get the value of user variable as a string. This function will return the value of variable @a name as string. If the original value of the variable is not a string, the value will be converted into a string. @param name user variable name @param value pointer to the value buffer @param len length of the value buffer @param precision precision of the value if it is a float number @param null_value if not NULL, the function will set it to true if the value of variable is null, set to false if not @retval 0 Success @retval 1 Variable not found */ int get_user_var_str(const char *name, char *value, unsigned long len, unsigned int precision, int *null_value); #ifdef __cplusplus } #endif #endif /* REPLICATION_H */ mysql/server/private/my_json_writer.h000064400000043716151027430560014132 0ustar00/* Copyright (C) 2014 SkySQL Ab, MariaDB Corporation Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef JSON_WRITER_INCLUDED #define JSON_WRITER_INCLUDED #include "my_base.h" #if !defined(NDEBUG) || defined(JSON_WRITER_UNIT_TEST) || defined ENABLED_JSON_WRITER_CONSISTENCY_CHECKS #include #include #include #include #endif #ifdef JSON_WRITER_UNIT_TEST #include "sql_string.h" constexpr uint FAKE_SELECT_LEX_ID= UINT_MAX; // Also, mock objects are defined in my_json_writer-t.cc #define VALIDITY_ASSERT(x) if (!(x)) this->invalid_json= true; #else #include "sql_select.h" #define VALIDITY_ASSERT(x) DBUG_ASSERT(x) #endif #include class Opt_trace_stmt; class Opt_trace_context; class Json_writer; struct TABLE_LIST; /* Single_line_formatting_helper is used by Json_writer to do better formatting of JSON documents. The idea is to catch arrays that can be printed on one line: arrayName : [ "boo", 123, 456 ] and actually print them on one line. Arrrays that occupy too much space on the line, or have nested members cannot be printed on one line. We hook into JSON printing functions and try to detect the pattern. While detecting the pattern, we will accumulate "boo", 123, 456 as strings. Then, - either the pattern is broken, and we print the elements out, - or the pattern lasts till the end of the array, and we print the array on one line. */ class Single_line_formatting_helper { enum enum_state { INACTIVE, ADD_MEMBER, IN_ARRAY, DISABLED }; /* This works like a finite automaton. state=DISABLED means the helper is disabled - all on_XXX functions will return false (which means "not handled") and do nothing. +->-+ | v INACTIVE ---> ADD_MEMBER ---> IN_ARRAY--->-+ ^ | +------------------<--------------------+ For other states: INACTIVE - initial state, we have nothing. ADD_MEMBER - add_member() was called, the buffer has "member_name\0". IN_ARRAY - start_array() was called. */ enum enum_state state; enum { MAX_LINE_LEN= 80 }; char buffer[80]; /* The data in the buffer is located between buffer[0] and buf_ptr */ char *buf_ptr; uint line_len; Json_writer *owner; public: Single_line_formatting_helper() : state(INACTIVE), buf_ptr(buffer) {} void init(Json_writer *owner_arg) { owner= owner_arg; } bool on_add_member(const char *name, size_t len); bool on_start_array(); bool on_end_array(); void on_start_object(); // on_end_object() is not needed. bool on_add_str(const char *str, size_t num_bytes); /* Returns true if the helper is flushing its buffer and is probably making calls back to its Json_writer. (The Json_writer uses this function to avoid re-doing the processing that it has already done before making a call to fmt_helper) */ bool is_making_writer_calls() const { return state == DISABLED; } private: void flush_on_one_line(); void disable_and_flush(); }; /* Something that looks like class String, but has an internal limit of how many bytes one can append to it. Bytes that were truncated due to the size limitation are counted. */ class String_with_limit { public: String_with_limit() : size_limit(SIZE_T_MAX), truncated_len(0) { str.length(0); } size_t get_truncated_bytes() const { return truncated_len; } size_t get_size_limit() { return size_limit; } void set_size_limit(size_t limit_arg) { // Setting size limit to be shorter than length will not have the desired // effect DBUG_ASSERT(str.length() < size_limit); size_limit= limit_arg; } void append(const char *s, size_t size) { if (str.length() + size <= size_limit) { // Whole string can be added, just do it str.append(s, size); } else { // We cannot add the whole string if (str.length() < size_limit) { // But we can still add something size_t bytes_to_add = size_limit - str.length(); str.append(s, bytes_to_add); truncated_len += size - bytes_to_add; } else truncated_len += size; } } void append(const char *s) { append(s, strlen(s)); } void append(char c) { if (str.length() + 1 > size_limit) truncated_len++; else str.append(c); } const String *get_string() { return &str; } size_t length() { return str.length(); } private: String str; // str must not get longer than this many bytes. size_t size_limit; // How many bytes were truncated from the string size_t truncated_len; }; /* A class to write well-formed JSON documents. The documents are also formatted for human readability. */ class Json_writer { #if !defined(NDEBUG) || defined(JSON_WRITER_UNIT_TEST) /* In debug mode, Json_writer will fail and assertion if one attempts to produce an invalid JSON document (e.g. JSON array having named elements). */ std::vector named_items_expectation; bool named_item_expected() const; bool got_name; #ifdef JSON_WRITER_UNIT_TEST public: // When compiled for unit test, creating invalid JSON will set this to true // instead of an assertion. bool invalid_json= false; #endif #endif public: /* Add a member. We must be in an object. */ Json_writer& add_member(const char *name); Json_writer& add_member(const char *name, size_t len); /* Add atomic values */ void add_str(const char* val); void add_str(const char* val, size_t num_bytes); void add_str(const String &str); void add_str(Item *item); void add_table_name(const JOIN_TAB *tab); void add_table_name(const TABLE* table); void add_ll(longlong val); void add_ull(ulonglong val); void add_size(longlong val); void add_double(double val); void add_bool(bool val); void add_null(); private: void add_unquoted_str(const char* val); void add_unquoted_str(const char* val, size_t len); bool on_add_str(const char *str, size_t num_bytes); void on_start_object(); public: /* Start a child object */ void start_object(); void start_array(); void end_object(); void end_array(); /* One can set a limit of how large a JSON document should be. Writes beyond that size will be counted, but will not be collected. */ void set_size_limit(size_t mem_size) { output.set_size_limit(mem_size); } size_t get_truncated_bytes() { return output.get_truncated_bytes(); } Json_writer() : #if !defined(NDEBUG) || defined(JSON_WRITER_UNIT_TEST) got_name(false), #endif indent_level(0), document_start(true), element_started(false), first_child(true) { fmt_helper.init(this); } private: // TODO: a stack of (name, bool is_object_or_array) elements. int indent_level; enum { INDENT_SIZE = 2 }; friend class Single_line_formatting_helper; friend class Json_writer_nesting_guard; bool document_start; bool element_started; bool first_child; Single_line_formatting_helper fmt_helper; void append_indent(); void start_element(); void start_sub_element(); public: String_with_limit output; }; /* A class to add values to Json_writer_object and Json_writer_array */ class Json_value_helper { Json_writer* writer; public: void init(Json_writer *my_writer) { writer= my_writer; } void add_str(const char* val) { writer->add_str(val); } void add_str(const char* val, size_t length) { writer->add_str(val, length); } void add_str(const String &str) { writer->add_str(str.ptr(), str.length()); } void add_str(const LEX_CSTRING &str) { writer->add_str(str.str, str.length); } void add_str(Item *item) { writer->add_str(item); } void add_ll(longlong val) { writer->add_ll(val); } void add_size(longlong val) { writer->add_size(val); } void add_double(double val) { writer->add_double(val); } void add_bool(bool val) { writer->add_bool(val); } void add_null() { writer->add_null(); } void add_table_name(const JOIN_TAB *tab) { writer->add_table_name(tab); } void add_table_name(const TABLE* table) { writer->add_table_name(table); } }; /* A common base for Json_writer_object and Json_writer_array */ class Json_writer_struct { Json_writer_struct(const Json_writer_struct&)= delete; Json_writer_struct& operator=(const Json_writer_struct&)= delete; #ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS static thread_local std::vector named_items_expectation; #endif protected: Json_writer* my_writer; Json_value_helper context; /* Tells when a json_writer_struct has been closed or not */ bool closed; explicit Json_writer_struct(Json_writer *writer) : my_writer(writer) { context.init(my_writer); closed= false; #ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS named_items_expectation.push_back(expect_named_children); #endif } explicit Json_writer_struct(THD *thd) : Json_writer_struct(thd->opt_trace.get_current_json()) { } public: #ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS virtual ~Json_writer_struct() { named_items_expectation.pop_back(); } #else virtual ~Json_writer_struct() = default; #endif bool trace_started() const { return my_writer != 0; } #ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS bool named_item_expected() const { return named_items_expectation.size() > 1 && *(named_items_expectation.rbegin() + 1); } #endif }; /* RAII-based class to start/end writing a JSON object into the JSON document There is "ignore mode": one can initialize Json_writer_object with a NULL Json_writer argument, and then all its calls will do nothing. This is used by optimizer trace which can be enabled or disabled. */ class Json_writer_object : public Json_writer_struct { private: void add_member(const char *name) { my_writer->add_member(name); } public: explicit Json_writer_object(Json_writer* writer, const char *str= nullptr) : Json_writer_struct(writer) { #ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS DBUG_ASSERT(named_item_expected()); #endif if (unlikely(my_writer)) { if (str) my_writer->add_member(str); my_writer->start_object(); } } explicit Json_writer_object(THD* thd, const char *str= nullptr) : Json_writer_object(thd->opt_trace.get_current_json(), str) { } ~Json_writer_object() { if (my_writer && !closed) my_writer->end_object(); closed= TRUE; } Json_writer_object& add(const char *name, bool value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_bool(value); } return *this; } Json_writer_object& add(const char *name, ulonglong value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); my_writer->add_ull(value); } return *this; } template::value>::type > Json_writer_object& add(const char *name, IntT value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_ll(value); } return *this; } Json_writer_object& add(const char *name, double value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_double(value); } return *this; } Json_writer_object& add(const char *name, const char *value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_str(value); } return *this; } Json_writer_object& add(const char *name, const char *value, size_t num_bytes) { add_member(name); context.add_str(value, num_bytes); return *this; } Json_writer_object& add(const char *name, const LEX_CSTRING &value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_str(value.str, value.length); } return *this; } Json_writer_object& add(const char *name, Item *value) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_str(value); } return *this; } Json_writer_object& add_null(const char*name) { DBUG_ASSERT(!closed); if (my_writer) { add_member(name); context.add_null(); } return *this; } Json_writer_object& add_table_name(const JOIN_TAB *tab) { DBUG_ASSERT(!closed); if (my_writer) { add_member("table"); context.add_table_name(tab); } return *this; } Json_writer_object& add_table_name(const TABLE *table) { DBUG_ASSERT(!closed); if (my_writer) { add_member("table"); context.add_table_name(table); } return *this; } Json_writer_object& add_select_number(uint select_number) { DBUG_ASSERT(!closed); if (my_writer) { add_member("select_id"); if (unlikely(select_number == FAKE_SELECT_LEX_ID)) context.add_str("fake"); else context.add_ll(static_cast(select_number)); } return *this; } void end() { DBUG_ASSERT(!closed); if (unlikely(my_writer)) my_writer->end_object(); closed= TRUE; } }; /* RAII-based class to start/end writing a JSON array into the JSON document There is "ignore mode": one can initialize Json_writer_array with a NULL Json_writer argument, and then all its calls will do nothing. This is used by optimizer trace which can be enabled or disabled. */ class Json_writer_array : public Json_writer_struct { public: explicit Json_writer_array(Json_writer *writer, const char *str= nullptr) : Json_writer_struct(writer) { #ifdef ENABLED_JSON_WRITER_CONSISTENCY_CHECKS DBUG_ASSERT(!named_item_expected()); #endif if (unlikely(my_writer)) { if (str) my_writer->add_member(str); my_writer->start_array(); } } explicit Json_writer_array(THD *thd, const char *str= nullptr) : Json_writer_array(thd->opt_trace.get_current_json(), str) { } ~Json_writer_array() { if (unlikely(my_writer && !closed)) { my_writer->end_array(); closed= TRUE; } } void end() { DBUG_ASSERT(!closed); if (unlikely(my_writer)) my_writer->end_array(); closed= TRUE; } Json_writer_array& add(bool value) { DBUG_ASSERT(!closed); if (my_writer) context.add_bool(value); return *this; } Json_writer_array& add(ulonglong value) { DBUG_ASSERT(!closed); if (my_writer) context.add_ll(static_cast(value)); return *this; } Json_writer_array& add(longlong value) { DBUG_ASSERT(!closed); if (my_writer) context.add_ll(value); return *this; } Json_writer_array& add(double value) { DBUG_ASSERT(!closed); if (my_writer) context.add_double(value); return *this; } #ifndef _WIN64 Json_writer_array& add(size_t value) { DBUG_ASSERT(!closed); if (my_writer) context.add_ll(static_cast(value)); return *this; } #endif Json_writer_array& add(const char *value) { DBUG_ASSERT(!closed); if (my_writer) context.add_str(value); return *this; } Json_writer_array& add(const char *value, size_t num_bytes) { DBUG_ASSERT(!closed); if (my_writer) context.add_str(value, num_bytes); return *this; } Json_writer_array& add(const LEX_CSTRING &value) { DBUG_ASSERT(!closed); if (my_writer) context.add_str(value.str, value.length); return *this; } Json_writer_array& add(Item *value) { DBUG_ASSERT(!closed); if (my_writer) context.add_str(value); return *this; } Json_writer_array& add_null() { DBUG_ASSERT(!closed); if (my_writer) context.add_null(); return *this; } Json_writer_array& add_table_name(const JOIN_TAB *tab) { DBUG_ASSERT(!closed); if (my_writer) context.add_table_name(tab); return *this; } Json_writer_array& add_table_name(const TABLE *table) { DBUG_ASSERT(!closed); if (my_writer) context.add_table_name(table); return *this; } }; /* RAII-based class to disable writing into the JSON document The tracing is disabled as soon as the object is created. The destuctor is called as soon as we exit the scope of the object and the tracing is enabled back. */ class Json_writer_temp_disable { public: Json_writer_temp_disable(THD *thd_arg); ~Json_writer_temp_disable(); THD *thd; }; /* RAII-based helper class to detect incorrect use of Json_writer. The idea is that a function typically must leave Json_writer at the same identation level as it was when it was invoked. Leaving it at a different level typically means we forgot to close an object or an array So, here is a way to guard void foo(Json_writer *writer) { Json_writer_nesting_guard(writer); .. do something with writer // at the end of the function, ~Json_writer_nesting_guard() is called // and it makes sure that the nesting is the same as when the function was // entered. } */ class Json_writer_nesting_guard { #ifdef DBUG_OFF public: Json_writer_nesting_guard(Json_writer *) {} #else Json_writer* writer; int indent_level; public: Json_writer_nesting_guard(Json_writer *writer_arg) : writer(writer_arg), indent_level(writer->indent_level) {} ~Json_writer_nesting_guard() { DBUG_ASSERT(indent_level == writer->indent_level); } #endif }; #endif mysql/server/private/structs.h000064400000063413151027430560012563 0ustar00#ifndef STRUCTS_INCLUDED #define STRUCTS_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. Copyright (c) 2009, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* The old structures from unireg */ #include "sql_plugin.h" /* plugin_ref */ #include "sql_const.h" /* MAX_REFLENGTH */ #include "my_time.h" /* enum_mysql_timestamp_type */ #include "thr_lock.h" /* thr_lock_type */ #include "my_base.h" /* ha_rows, ha_key_alg */ #include /* USERNAME_LENGTH */ #include "sql_bitmap.h" struct TABLE; class Type_handler; class Field; class Index_statistics; struct Lex_ident_cli_st; class THD; /* Array index type for table.field[] */ typedef uint16 field_index_t; typedef struct st_date_time_format { uchar positions[8]; char time_separator; /* Separator between hour and minute */ uint flag; /* For future */ LEX_CSTRING format; } DATE_TIME_FORMAT; typedef struct st_keyfile_info { /* used with ha_info() */ uchar ref[MAX_REFLENGTH]; /* Pointer to current row */ uchar dupp_ref[MAX_REFLENGTH]; /* Pointer to dupp row */ uint ref_length; /* Length of ref (1-8) */ uint block_size; /* index block size */ File filenr; /* (uniq) filenr for table */ ha_rows records; /* Records i datafilen */ ha_rows deleted; /* Deleted records */ ulonglong data_file_length; /* Length off data file */ ulonglong max_data_file_length; /* Length off data file */ ulonglong index_file_length; ulonglong max_index_file_length; ulonglong delete_length; /* Free bytes */ ulonglong auto_increment_value; int errkey,sortkey; /* Last errorkey and sorted by */ time_t create_time; /* When table was created */ time_t check_time; time_t update_time; ulong mean_rec_length; /* physical reclength */ } KEYFILE_INFO; typedef struct st_key_part_info { /* Info about a key part */ Field *field; /* the Field object for the indexed prefix of the original table Field. NOT necessarily the original Field */ uint offset; /* Offset in record (from 0) */ uint null_offset; /* Offset to null_bit in record */ /* Length of key part in bytes, excluding NULL flag and length bytes */ uint length; /* Number of bytes required to store the keypart value. This may be different from the "length" field as it also counts - possible NULL-flag byte (see HA_KEY_NULL_LENGTH) - possible HA_KEY_BLOB_LENGTH bytes needed to store actual value length. */ uint store_length; uint16 key_type; field_index_t fieldnr; /* Fieldnr begins counting from 1 */ uint16 key_part_flag; /* 0 or HA_REVERSE_SORT */ uint8 type; uint8 null_bit; /* Position to null_bit */ } KEY_PART_INFO ; class engine_option_value; struct ha_index_option_struct; typedef struct st_key { uint key_length; /* total length of user defined key parts */ ulong flags; /* dupp key and pack flags */ uint user_defined_key_parts; /* How many key_parts */ uint usable_key_parts; /* Should normally be = user_defined_key_parts */ uint ext_key_parts; /* Number of key parts in extended key */ ulong ext_key_flags; /* Flags for extended key */ /* Parts of primary key that are in the extension of this index. Example: if this structure describes idx1, which is defined as INDEX idx1 (pk2, col2) and pk is defined as: PRIMARY KEY (pk1, pk2) then pk1 is in the extension idx1, ext_key_part_map.is_set(0) == true pk2 is explicitly present in idx1, it is not in the extension, so ext_key_part_map.is_set(1) == false */ key_part_map ext_key_part_map; /* Bitmap of indexes having common parts with this index (only key parts from key definitions are taken into account) */ key_map overlapped; /* Set of keys constraint correlated with this key */ key_map constraint_correlated; LEX_CSTRING name; uint block_size; enum ha_key_alg algorithm; /* The flag is on if statistical data for the index prefixes has to be taken from the system statistical tables. */ bool is_statistics_from_stat_tables; /* Note that parser is used when the table is opened for use, and parser_name is used when the table is being created. */ union { plugin_ref parser; /* Fulltext [pre]parser */ LEX_CSTRING *parser_name; /* Fulltext [pre]parser name */ }; KEY_PART_INFO *key_part; /* Unique name for cache; db + \0 + table_name + \0 + key_name + \0 */ uchar *cache_name; /* Array of AVG(#records with the same field value) for 1st ... Nth key part. 0 means 'not known'. For temporary heap tables this member is NULL. */ ulong *rec_per_key; /* This structure is used for statistical data on the index that has been read from the statistical table index_stat */ Index_statistics *read_stats; /* This structure is used for statistical data on the index that is collected by the function collect_statistics_for_table */ Index_statistics *collected_stats; TABLE *table; LEX_CSTRING comment; /** reference to the list of options or NULL */ engine_option_value *option_list; ha_index_option_struct *option_struct; /* structure with parsed options */ double actual_rec_per_key(uint i) const; bool without_overlaps; /* TRUE if index needs to be ignored */ bool is_ignored; } KEY; struct st_join_table; typedef struct st_reginfo { /* Extra info about reg */ struct st_join_table *join_tab; /* Used by SELECT() */ enum thr_lock_type lock_type; /* How database is used */ bool skip_locked; bool not_exists_optimize; /* TRUE <=> range optimizer found that there is no rows satisfying table conditions. */ bool impossible_range; } REGINFO; /* Originally MySQL used MYSQL_TIME structure inside server only, but since 4.1 it's exported to user in the new client API. Define aliases for new names to keep existing code simple. */ typedef enum enum_mysql_timestamp_type timestamp_type; typedef struct { ulong year,month,day,hour; ulonglong minute,second,second_part; bool neg; } INTERVAL; typedef struct st_known_date_time_format { const char *format_name; const char *date_format; const char *datetime_format; const char *time_format; } KNOWN_DATE_TIME_FORMAT; extern const char *show_comp_option_name[]; typedef int *(*update_var)(THD *, struct st_mysql_show_var *); struct USER_AUTH : public Sql_alloc { LEX_CSTRING plugin, auth_str, pwtext; USER_AUTH *next; USER_AUTH() : next(NULL) { plugin.str= auth_str.str= ""; pwtext.str= NULL; plugin.length= auth_str.length= pwtext.length= 0; } }; struct AUTHID { LEX_CSTRING user, host; void init() { memset(this, 0, sizeof(*this)); } void copy(MEM_ROOT *root, const LEX_CSTRING *usr, const LEX_CSTRING *host); bool is_role() const { return user.str[0] && (!host.str || !host.str[0]); } void set_lex_string(LEX_CSTRING *l, char *buf) { if (is_role()) *l= user; else { l->str= buf; l->length= strxmov(buf, user.str, "@", host.str, NullS) - buf; } } void parse(const char *str, size_t length); bool read_from_mysql_proc_row(THD *thd, TABLE *table); }; struct LEX_USER: public AUTHID { USER_AUTH *auth; bool has_auth() { return auth && (auth->plugin.length || auth->auth_str.length || auth->pwtext.length); } }; /* This structure specifies the maximum amount of resources which can be consumed by each account. Zero value of a member means there is no limit. */ typedef struct user_resources { /* Maximum number of queries/statements per hour. */ uint questions; /* Maximum number of updating statements per hour (which statements are updating is defined by sql_command_flags array). */ uint updates; /* Maximum number of connections established per hour. */ uint conn_per_hour; /* Maximum number of concurrent connections. If -1 then no new connections allowed */ int user_conn; /* Max query timeout */ double max_statement_time; /* Values of this enum and specified_limits member are used by the parser to store which user limits were specified in GRANT statement. */ enum {QUERIES_PER_HOUR= 1, UPDATES_PER_HOUR= 2, CONNECTIONS_PER_HOUR= 4, USER_CONNECTIONS= 8, MAX_STATEMENT_TIME= 16}; uint specified_limits; } USER_RESOURCES; /* This structure is used for counting resources consumed and for checking them against specified user limits. */ typedef struct user_conn { /* Pointer to user+host key (pair separated by '\0') defining the entity for which resources are counted (By default it is user account thus priv_user/priv_host pair is used. If --old-style-user-limits option is enabled, resources are counted for each user+host separately). */ char *user; /* Pointer to host part of the key. */ char *host; /** The moment of time when per hour counters were reset last time (i.e. start of "hour" for conn_per_hour, updates, questions counters). */ ulonglong reset_utime; /* Total length of the key. */ uint len; /* Current amount of concurrent connections for this account. */ int connections; /* Current number of connections per hour, number of updating statements per hour and total number of statements per hour for this account. */ uint conn_per_hour, updates, questions; /* Maximum amount of resources which account is allowed to consume. */ USER_RESOURCES user_resources; } USER_CONN; typedef struct st_user_stats { char user[MY_MAX(USERNAME_LENGTH, LIST_PROCESS_HOST_LEN) + 1]; // Account name the user is mapped to when this is a user from mapped_user. // Otherwise, the same value as user. char priv_user[MY_MAX(USERNAME_LENGTH, LIST_PROCESS_HOST_LEN) + 1]; uint user_name_length; uint total_connections; uint total_ssl_connections; uint concurrent_connections; time_t connected_time; // in seconds ha_rows rows_read, rows_sent; ha_rows rows_updated, rows_deleted, rows_inserted; ulonglong bytes_received; ulonglong bytes_sent; ulonglong binlog_bytes_written; ulonglong select_commands, update_commands, other_commands; ulonglong commit_trans, rollback_trans; ulonglong denied_connections, lost_connections, max_statement_time_exceeded; ulonglong access_denied_errors; ulonglong empty_queries; double busy_time; // in seconds double cpu_time; // in seconds } USER_STATS; typedef struct st_table_stats { char table[NAME_LEN * 2 + 2]; // [db] + '\0' + [table] + '\0' size_t table_name_length; ulonglong rows_read, rows_changed; ulonglong rows_changed_x_indexes; /* Stores enum db_type, but forward declarations cannot be done */ int engine_type; } TABLE_STATS; typedef struct st_index_stats { // [db] + '\0' + [table] + '\0' + [index] + '\0' char index[NAME_LEN * 3 + 3]; size_t index_name_length; /* Length of 'index' */ ulonglong rows_read; } INDEX_STATS; /* Bits in form->update */ #define REG_MAKE_DUPP 1U /* Make a copy of record when read */ #define REG_NEW_RECORD 2U /* Write a new record if not found */ #define REG_UPDATE 4U /* Uppdate record */ #define REG_DELETE 8U /* Delete found record */ #define REG_PROG 16U /* User is updating database */ #define REG_CLEAR_AFTER_WRITE 32U #define REG_MAY_BE_UPDATED 64U #define REG_AUTO_UPDATE 64U /* Used in D-forms for scroll-tables */ #define REG_OVERWRITE 128U #define REG_SKIP_DUP 256U /* Bits in form->status */ #define STATUS_NO_RECORD (1U+2U) /* Record isn't usable */ #define STATUS_GARBAGE 1U #define STATUS_NOT_FOUND 2U /* No record in database when needed */ #define STATUS_NO_PARENT 4U /* Parent record wasn't found */ #define STATUS_NOT_READ 8U /* Record isn't read */ #define STATUS_UPDATED 16U /* Record is updated by formula */ #define STATUS_NULL_ROW 32U /* table->null_row is set */ #define STATUS_DELETED 64U /* Such interval is "discrete": it is the set of { auto_inc_interval_min + k * increment, 0 <= k <= (auto_inc_interval_values-1) } Where "increment" is maintained separately by the user of this class (and is currently only thd->variables.auto_increment_increment). It mustn't derive from Sql_alloc, because SET INSERT_ID needs to allocate memory which must stay allocated for use by the next statement. */ class Discrete_interval { private: ulonglong interval_min; ulonglong interval_values; ulonglong interval_max; // excluded bound. Redundant. public: Discrete_interval *next; // used when linked into Discrete_intervals_list void replace(ulonglong start, ulonglong val, ulonglong incr) { interval_min= start; interval_values= val; interval_max= (val == ULONGLONG_MAX) ? val : start + val * incr; } Discrete_interval(ulonglong start, ulonglong val, ulonglong incr) : next(NULL) { replace(start, val, incr); }; Discrete_interval() : next(NULL) { replace(0, 0, 0); }; ulonglong minimum() const { return interval_min; }; ulonglong values() const { return interval_values; }; ulonglong maximum() const { return interval_max; }; /* If appending [3,5] to [1,2], we merge both in [1,5] (they should have the same increment for that, user of the class has to ensure that). That is just a space optimization. Returns 0 if merge succeeded. */ bool merge_if_contiguous(ulonglong start, ulonglong val, ulonglong incr) { if (interval_max == start) { if (val == ULONGLONG_MAX) { interval_values= interval_max= val; } else { interval_values+= val; interval_max= start + val * incr; } return 0; } return 1; }; }; /* List of Discrete_interval objects */ class Discrete_intervals_list { private: Discrete_interval *head; Discrete_interval *tail; /* When many intervals are provided at the beginning of the execution of a statement (in a replication slave or SET INSERT_ID), "current" points to the interval being consumed by the thread now (so "current" goes from "head" to "tail" then to NULL). */ Discrete_interval *current; uint elements; // number of elements void set_members(Discrete_interval *h, Discrete_interval *t, Discrete_interval *c, uint el) { head= h; tail= t; current= c; elements= el; } void operator=(Discrete_intervals_list &); /* prevent use of these */ Discrete_intervals_list(const Discrete_intervals_list &); public: Discrete_intervals_list() : head(NULL), current(NULL), elements(0) {}; void empty_no_free() { set_members(NULL, NULL, NULL, 0); } void empty() { for (Discrete_interval *i= head; i;) { Discrete_interval *next= i->next; delete i; i= next; } empty_no_free(); } void copy_shallow(const Discrete_intervals_list * dli) { head= dli->get_head(); tail= dli->get_tail(); current= dli->get_current(); elements= dli->nb_elements(); } void swap (Discrete_intervals_list * dli) { Discrete_interval *h, *t, *c; uint el; h= dli->get_head(); t= dli->get_tail(); c= dli->get_current(); el= dli->nb_elements(); dli->copy_shallow(this); set_members(h, t, c, el); } const Discrete_interval* get_next() { Discrete_interval *tmp= current; if (current != NULL) current= current->next; return tmp; } ~Discrete_intervals_list() { empty(); }; bool append(ulonglong start, ulonglong val, ulonglong incr); bool append(Discrete_interval *interval); ulonglong minimum() const { return (head ? head->minimum() : 0); }; ulonglong maximum() const { return (head ? tail->maximum() : 0); }; uint nb_elements() const { return elements; } Discrete_interval* get_head() const { return head; }; Discrete_interval* get_tail() const { return tail; }; Discrete_interval* get_current() const { return current; }; }; /* DDL options: - CREATE IF NOT EXISTS - DROP IF EXISTS - CREATE LIKE - REPLACE */ struct DDL_options_st { public: enum Options { OPT_NONE= 0, OPT_IF_NOT_EXISTS= 2, // CREATE TABLE IF NOT EXISTS OPT_LIKE= 4, // CREATE TABLE LIKE OPT_OR_REPLACE= 16, // CREATE OR REPLACE TABLE OPT_OR_REPLACE_SLAVE_GENERATED= 32,// REPLACE was added on slave, it was // not in the original query on master. OPT_IF_EXISTS= 64, OPT_CREATE_SELECT= 128 // CREATE ... SELECT }; private: Options m_options; public: Options create_like_options() const { return (DDL_options_st::Options) (((uint) m_options) & (OPT_IF_NOT_EXISTS | OPT_OR_REPLACE)); } void init() { m_options= OPT_NONE; } void init(Options options) { m_options= options; } void set(Options other) { m_options= other; } void set(const DDL_options_st other) { m_options= other.m_options; } bool if_not_exists() const { return m_options & OPT_IF_NOT_EXISTS; } bool or_replace() const { return m_options & OPT_OR_REPLACE; } bool or_replace_slave_generated() const { return m_options & OPT_OR_REPLACE_SLAVE_GENERATED; } bool like() const { return m_options & OPT_LIKE; } bool if_exists() const { return m_options & OPT_IF_EXISTS; } bool is_create_select() const { return m_options & OPT_CREATE_SELECT; } void add(const DDL_options_st::Options other) { m_options= (Options) ((uint) m_options | (uint) other); } void add(const DDL_options_st &other) { add(other.m_options); } DDL_options_st operator|(const DDL_options_st &other) { add(other.m_options); return *this; } DDL_options_st operator|=(DDL_options_st::Options other) { add(other); return *this; } }; class DDL_options: public DDL_options_st { public: DDL_options() { init(); } DDL_options(Options options) { init(options); } DDL_options(const DDL_options_st &options) { DDL_options_st::operator=(options); } }; struct Lex_length_and_dec_st { private: const char *m_length; const char *m_dec; public: void set(const char *length, const char *dec) { m_length= length; m_dec= dec; } const char *length() const { return m_length; } const char *dec() const { return m_dec; } }; struct Lex_field_type_st: public Lex_length_and_dec_st { private: const Type_handler *m_handler; void set(const Type_handler *handler, const char *length, const char *dec) { m_handler= handler; Lex_length_and_dec_st::set(length, dec); } public: void set(const Type_handler *handler, Lex_length_and_dec_st length_and_dec) { m_handler= handler; Lex_length_and_dec_st::operator=(length_and_dec); } void set_handler_length_flags(const Type_handler *handler, const char *length, uint32 flags); void set(const Type_handler *handler, const char *length) { set(handler, length, 0); } void set(const Type_handler *handler) { set(handler, 0, 0); } void set_handler(const Type_handler *handler) { m_handler= handler; } const Type_handler *type_handler() const { return m_handler; } }; struct Lex_dyncol_type_st: public Lex_length_and_dec_st { private: int m_type; // enum_dynamic_column_type is not visible here, so use int public: void set(int type, const char *length, const char *dec) { m_type= type; Lex_length_and_dec_st::set(length, dec); } void set(int type, Lex_length_and_dec_st length_and_dec) { m_type= type; Lex_length_and_dec_st::operator=(length_and_dec); } void set(int type, const char *length) { set(type, length, 0); } void set(int type) { set(type, 0, 0); } int dyncol_type() const { return m_type; } }; struct Lex_spblock_handlers_st { public: int hndlrs; void init(int count) { hndlrs= count; } }; struct Lex_spblock_st: public Lex_spblock_handlers_st { public: int vars; int conds; int curs; void init() { vars= conds= hndlrs= curs= 0; } void init_using_vars(uint nvars) { vars= nvars; conds= hndlrs= curs= 0; } void join(const Lex_spblock_st &b1, const Lex_spblock_st &b2) { vars= b1.vars + b2.vars; conds= b1.conds + b2.conds; hndlrs= b1.hndlrs + b2.hndlrs; curs= b1.curs + b2.curs; } }; class Lex_spblock: public Lex_spblock_st { public: Lex_spblock() { init(); } Lex_spblock(const Lex_spblock_handlers_st &other) { vars= conds= curs= 0; hndlrs= other.hndlrs; } }; struct Lex_for_loop_bounds_st { public: class sp_assignment_lex *m_index; // The first iteration value (or cursor) class sp_assignment_lex *m_target_bound; // The last iteration value int8 m_direction; bool m_implicit_cursor; bool is_for_loop_cursor() const { return m_target_bound == NULL; } }; class Lex_for_loop_bounds_intrange: public Lex_for_loop_bounds_st { public: Lex_for_loop_bounds_intrange(int8 direction, class sp_assignment_lex *left_expr, class sp_assignment_lex *right_expr) { m_direction= direction; m_index= direction > 0 ? left_expr : right_expr; m_target_bound= direction > 0 ? right_expr : left_expr; m_implicit_cursor= false; } }; struct Lex_for_loop_st { public: class sp_variable *m_index; // The first iteration value (or cursor) class sp_variable *m_target_bound; // The last iteration value int m_cursor_offset; int8 m_direction; bool m_implicit_cursor; void init() { m_index= 0; m_target_bound= 0; m_cursor_offset= 0; m_direction= 0; m_implicit_cursor= false; } bool is_for_loop_cursor() const { return m_target_bound == NULL; } bool is_for_loop_explicit_cursor() const { return is_for_loop_cursor() && !m_implicit_cursor; } }; enum trim_spec { TRIM_LEADING, TRIM_TRAILING, TRIM_BOTH }; struct Lex_trim_st { Item *m_remove; Item *m_source; trim_spec m_spec; public: void set(trim_spec spec, Item *remove, Item *source) { m_spec= spec; m_remove= remove; m_source= source; } void set(trim_spec spec, Item *source) { set(spec, NULL, source); } Item *make_item_func_trim_std(THD *thd) const; Item *make_item_func_trim_oracle(THD *thd) const; }; class Lex_trim: public Lex_trim_st { public: Lex_trim(trim_spec spec, Item *source) { set(spec, source); } }; class Lex_substring_spec_st { public: Item *m_subject; Item *m_from; Item *m_for; static Lex_substring_spec_st init(Item *subject, Item *from, Item *xfor= NULL) { Lex_substring_spec_st res; res.m_subject= subject; res.m_from= from; res.m_for= xfor; return res; } }; class st_select_lex; class Lex_select_lock { public: struct { uint defined_lock:1; uint update_lock:1; uint defined_timeout:1; uint skip_locked:1; }; ulong timeout; void empty() { defined_lock= update_lock= defined_timeout= skip_locked= FALSE; timeout= 0; } void set_to(st_select_lex *sel); }; class Lex_select_limit { public: /* explicit LIMIT clause was used */ bool explicit_limit; bool with_ties; Item *select_limit, *offset_limit; void clear() { explicit_limit= FALSE; // No explicit limit given by user with_ties= FALSE; // No use of WITH TIES operator select_limit= NULL; // denotes the default limit = HA_POS_ERROR offset_limit= NULL; // denotes the default offset = 0 } }; struct st_order; class Load_data_param { protected: CHARSET_INFO *m_charset; // Character set of the file ulonglong m_fixed_length; // Sum of target field lengths for fixed format bool m_is_fixed_length; bool m_use_blobs; public: Load_data_param(CHARSET_INFO *cs, bool is_fixed_length): m_charset(cs), m_fixed_length(0), m_is_fixed_length(is_fixed_length), m_use_blobs(false) { } bool add_outvar_field(THD *thd, const Field *field); bool add_outvar_user_var(THD *thd); CHARSET_INFO *charset() const { return m_charset; } bool is_fixed_length() const { return m_is_fixed_length; } bool use_blobs() const { return m_use_blobs; } }; class Load_data_outvar { public: virtual ~Load_data_outvar() = default; virtual bool load_data_set_null(THD *thd, const Load_data_param *param)= 0; virtual bool load_data_set_value(THD *thd, const char *pos, uint length, const Load_data_param *param)= 0; virtual bool load_data_set_no_data(THD *thd, const Load_data_param *param)= 0; virtual void load_data_print_for_log_event(THD *thd, class String *to) const= 0; virtual bool load_data_add_outvar(THD *thd, Load_data_param *param) const= 0; virtual uint load_data_fixed_length() const= 0; }; class Timeval: public timeval { protected: Timeval() = default; public: Timeval(my_time_t sec, ulong usec) { tv_sec= sec; /* Since tv_usec is not always of type ulong, cast usec parameter explicitly to uint to avoid compiler warnings about losing integer precision. */ DBUG_ASSERT(usec < 1000000); tv_usec= (uint)usec; } explicit Timeval(const timeval &tv) :timeval(tv) { } }; #endif /* STRUCTS_INCLUDED */ mysql/server/private/sql_type_fixedbin_storage.h000064400000012533151027430560016305 0ustar00#ifndef SQL_TYPE_FIXEDBIN_STORAGE #define SQL_TYPE_FIXEDBIN_STORAGE /* Copyright (c) 2019,2021 MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This is a common code for plugin (?) types that are generally handled like strings, but have their own fixed size on-disk binary storage format and their own (variable size) canonical string representation. Examples are INET6 and UUID types. The MariaDB server uses three binary representations of a data type: 1. In-memory binary representation (user visible) This representation: - can be used in INSERT..VALUES (X'AABBCC') - can be used in WHERE conditions: WHERE c1=X'AABBCC' - is returned by CAST(x AS BINARY(N)) - is returned by Field::val_native() and Item::val_native() 2. In-record binary representation (user invisible) This representation: - is used in records (is pointed by Field::ptr) - must be comparable by memcmp() 3. Binlog binary (row) representation Usually, for string data types the binlog representation is based on the in-record representation with trailing byte compression: - trailing space compression for text string data types - trailing zero compression for binary string data types We have to have separate in-memory and in-record representations because we use HA_KEYTYPE_BINARY for indexing. The engine API does not have a way to pass a comparison function as a parameter. The default implementation below assumes that: - the in-memory and in-record representations are equal - the binlog representation is compatible with BINARY(N) This is OK for simple data types, like INET6. Data type implementations that need different representations can override the default implementation (like e.g. UUID does). */ /***********************************************************************/ template class FixedBinTypeStorage { protected: // The buffer that stores the in-memory binary representation char m_buffer[NATIVE_LEN]; FixedBinTypeStorage() = default; FixedBinTypeStorage & set_zero() { bzero(&m_buffer, sizeof(m_buffer)); return *this; } public: // Initialize from the in-memory binary representation FixedBinTypeStorage(const char *str, size_t length) { if (length != binary_length()) set_zero(); else memcpy(&m_buffer, str, sizeof(m_buffer)); } // Return the buffer with the in-memory representation Lex_cstring to_lex_cstring() const { return Lex_cstring(m_buffer, sizeof(m_buffer)); } static constexpr uint binary_length() { return NATIVE_LEN; } static constexpr uint max_char_length() { return MAX_CHAR_LEN; } // Compare the in-memory binary representations of two values static int cmp(const LEX_CSTRING &a, const LEX_CSTRING &b) { DBUG_ASSERT(a.length == binary_length()); DBUG_ASSERT(b.length == binary_length()); return memcmp(a.str, b.str, b.length); } /* Convert from the in-memory to the in-record representation. Used in Field::store_native(). */ static void memory_to_record(char *to, const char *from) { memcpy(to, from, NATIVE_LEN); } /* Convert from the in-record to the in-memory representation Used in Field::val_native(). */ static void record_to_memory(char *to, const char *from) { memcpy(to, from, NATIVE_LEN); } /* Hash the in-record representation Used in Field::hash(). */ static void hash_record(uchar *ptr, Hasher *hasher) { hasher->add(&my_charset_bin, ptr, binary_length()); } static bool only_zero_bytes(const char *ptr, size_t length) { for (uint i= 0 ; i < length; i++) { if (ptr[i] != 0) return false; } return true; } static ulong KEY_pack_flags(uint column_nr) { /* Return zero by default. A particular data type can override this method return some flags, e.g. HA_PACK_KEY to enable key prefix compression. */ return 0; } /* Convert from the in-record to the binlog representation. Used in Field::pack(), and in filesort to store the addon fields. By default, do what BINARY(N) does. */ static uchar *pack(uchar *to, const uchar *from, uint max_length) { return StringPack(&my_charset_bin, binary_length()).pack(to, from, max_length); } /* Convert from the in-binary-log to the in-record representation. Used in Field::unpack(). By default, do what BINARY(N) does. */ static const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, uint param_data) { return StringPack(&my_charset_bin, binary_length()).unpack(to, from, from_end, param_data); } }; #endif /* SQL_TYPE_FIXEDBIN_STORAGE */ mysql/server/private/tztime.h000064400000006505151027430560012367 0ustar00#ifndef TZTIME_INCLUDED #define TZTIME_INCLUDED /* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class interface */ #endif #include "my_time.h" /* my_time_t */ #include "mysql_time.h" /* MYSQL_TIME */ #include "sql_list.h" /* Sql_alloc */ #include "sql_string.h" /* String */ class THD; #if !defined(TESTTIME) && !defined(TZINFO2SQL) class THD; /** This class represents abstract time zone and provides basic interface for MYSQL_TIME <-> my_time_t conversion. Actual time zones which are specified by DB, or via offset or use system functions are its descendants. */ class Time_zone: public Sql_alloc { public: Time_zone() = default; /* Remove gcc warning */ /** Converts local time in broken down MYSQL_TIME representation to my_time_t (UTC seconds since Epoch) represenation. Returns 0 in case of error. May set error_code to ER_WARN_DATA_OUT_OF_RANGE or ER_WARN_INVALID_TIMESTAMP, see TIME_to_timestamp()) */ virtual my_time_t TIME_to_gmt_sec(const MYSQL_TIME *t, uint *error_code) const = 0; /** Converts time in my_time_t representation to local time in broken down MYSQL_TIME representation. */ virtual void gmt_sec_to_TIME(MYSQL_TIME *tmp, my_time_t t) const = 0; /** Because of constness of String returned by get_name() time zone name have to be already zeroended to be able to use String::ptr() instead of c_ptr(). */ virtual const String * get_name() const = 0; /** We need this only for surpressing warnings, objects of this type are allocated on MEM_ROOT and should not require destruction. */ virtual ~Time_zone() = default; protected: static inline void adjust_leap_second(MYSQL_TIME *t); }; extern Time_zone * my_tz_UTC; extern MYSQL_PLUGIN_IMPORT Time_zone * my_tz_SYSTEM; extern Time_zone * my_tz_OFFSET0; extern Time_zone * my_tz_find(THD *thd, const String *name); extern my_bool my_tz_init(THD *org_thd, const char *default_tzname, my_bool bootstrap); extern void my_tz_free(); extern my_time_t sec_since_epoch_TIME(MYSQL_TIME *t); /** Number of elements in table list produced by my_tz_get_table_list() (this table list contains tables which are needed for dynamical loading of time zone descriptions). Actually it is imlementation detail that should not be used anywhere outside of tztime.h and tztime.cc. */ static const int MY_TZ_TABLES_COUNT= 4; #endif /* !defined(TESTTIME) && !defined(TZINFO2SQL) */ #endif /* TZTIME_INCLUDED */ mysql/server/private/rowid_filter.h000064400000036165151027430560013551 0ustar00/* Copyright (c) 2018, 2019 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ROWID_FILTER_INCLUDED #define ROWID_FILTER_INCLUDED #include "mariadb.h" #include "sql_array.h" /* What rowid / primary filters are -------------------------------- Consider a join query Q of the form SELECT * FROM T1, ... , Tk WHERE P. For any of the table reference Ti(Q) from the from clause of Q different rowid / primary key filters (pk-filters for short) can be built. A pk-filter F built for Ti(Q) is a set of rowids / primary keys of Ti F= {pk1,...,pkN} such that for any row r=r1||...||rk from the result set of Q ri's rowid / primary key pk(ri) is contained in F. When pk-filters are useful -------------------------- If building a pk-filter F for Ti(Q )is not too costly and its cardinality #F is much less than the cardinality of T - #T then using the pk-filter when executing Q might be quite beneficial. Let r be a random row from Ti. Let s(F) be the probability that pk(r) belongs to F. Let BC(F) be the cost of building F. Suppose that the optimizer has chosen for Q a plan with this join order T1 => ... Tk and that the table Ti is accessed by a ref access using index I. Let K = {k1,...,kM} be the set of all rowid/primary keys values used to access rows of Ti when looking for matches in this table.to join Ti by index I. Let's assume that two set sets K and F are uncorrelated. With this assumption if before accessing data from Ti by the rowid / primary key k we first check whether k is in F then we can expect saving on M*(1-s(S)) accesses of data rows from Ti. If we can guarantee that test whether k is in F is relatively cheap then we can gain a lot assuming that BC(F) is much less then the cost of fetching M*(1-s(S)) records from Ti and following evaluation of conditions pushed into Ti. Making pk-filter test cheap --------------------------- If the search structure to test whether an element is in F can be fully placed in RAM then this test is expected to be be much cheaper than a random access of a record from Ti. We'll consider two search structures for pk-filters: ordered array and bloom filter. Ordered array is easy to implement, but it's space consuming. If a filter contains primary keys then at least space for each primary key from the filter must be allocated in the search structure. On a the opposite a bloom filter requires a fixed number of bits and this number does not depend on the cardinality of the pk-filter (10 bits per element will serve pk-filter of any size). */ /* How and when the optimizer builds and uses range rowid filters -------------------------------------------------------------- 1. In make_join_statistics() for each join table s after the call of get_quick_record_count() the TABLE::method init_cost_info_for_usable_range_rowid_filters() is called The method build an array of Range_rowid_filter_cost_info elements containing the cost info on possible range filters for s->table. The array is optimized for further usage. 2. For each partial join order when the optimizer considers joining table s to this partial join In the function best_access_path() a. When evaluating a ref access r by index idx to join s the optimizer estimates the effect of usage of each possible range filter f and chooses one with the best gain. The gain is taken into account when the cost of thr ref access r is calculated. If it turns out that this is the best ref access to join s then the info about the chosen filter together with the info on r is remembered in the corresponding element of the array of POSITION structures. [We evaluate every pair (ref access, range_filter) rather then every pair (best ref access, range filter) because if the index ref_idx used for ref access r correlates with the index rf_idx used by the filter f then the pair (r,f) is not evaluated at all as we don't know how to estimate the effect of correlation between ref_idx and rf_idx.] b. When evaluating the best range access to join table s the optimizer estimates the effect of usage of each possible range filter f and chooses one with the best gain. [Here we should have evaluated every pair (range access, range filter) as well, but it's not done yet.] 3. When the cheapest execution plan has been chosen and after the call of JOIN::get_best_combination() The method JOIN::make_range_rowid_filters() is called For each range rowid filter used in the chosen execution plan the method creates a quick select object to be able to perform index range scan to fill the filter at the execution stage. The method also creates Range_rowid_filter objects that are used at the execution stage. 4. Just before the execution stage The method JOIN::init_range_rowid_filters() is called. For each join table s that is to be accessed with usage of a range filter the method allocates containers for the range filter and it lets the engine know that the filter will be used when accessing s. 5. At the execution stage In the function sub_select() just before the first access of a join table s employing a range filter The method JOIN_TAB::build_range_rowid_filter_if_needed() is called The method fills the filter using the quick select created by JOIN::make_range_rowid_filters(). 6. The accessed key tuples are checked against the filter within the engine using the info pushed into it. */ struct TABLE; class SQL_SELECT; class Rowid_filter_container; class Range_rowid_filter_cost_info; /* Cost to write rowid into array */ #define ARRAY_WRITE_COST 0.005 /* Factor used to calculate cost of sorting rowids in array */ #define ARRAY_SORT_C 0.01 /* Cost to evaluate condition */ #define COST_COND_EVAL 0.2 typedef enum { SORTED_ARRAY_CONTAINER, BLOOM_FILTER_CONTAINER // Not used yet } Rowid_filter_container_type; /** @class Rowid_filter_container The interface for different types of containers to store info on the set of rowids / primary keys that defines a pk-filter. There will be two implementations of this abstract class. - sorted array - bloom filter */ class Rowid_filter_container : public Sql_alloc { public: virtual Rowid_filter_container_type get_type() = 0; /* Allocate memory for the container */ virtual bool alloc() = 0; /* @brief Add info on a rowid / primary to the container @param ctxt The context info (opaque) @param elem The rowid / primary key to be added to the container @retval true if elem is successfully added */ virtual bool add(void *ctxt, char *elem) = 0; /* @brief Check whether a rowid / primary key is in container @param ctxt The context info (opaque) @param elem The rowid / primary key to be checked against the container @retval False if elem is definitely not in the container */ virtual bool check(void *ctxt, char *elem) = 0; /* True if the container does not contain any element */ virtual bool is_empty() = 0; virtual ~Rowid_filter_container() = default; }; /** @class Rowid_filter The interface for different types of pk-filters Currently we support only range pk filters. */ class Rowid_filter : public Sql_alloc { protected: /* The container to store info the set of elements in the filter */ Rowid_filter_container *container; Rowid_filter_tracker *tracker; public: enum build_return_code { SUCCESS, NON_FATAL_ERROR, FATAL_ERROR, }; Rowid_filter(Rowid_filter_container *container_arg) : container(container_arg) {} /* Build the filter : fill it with info on the set of elements placed there */ virtual build_return_code build() = 0; /* Check whether an element is in the filter. Returns false is the elements is definitely not in the filter. */ virtual bool check(char *elem) = 0; virtual ~Rowid_filter() = default; bool is_empty() { return container->is_empty(); } Rowid_filter_container *get_container() { return container; } void set_tracker(Rowid_filter_tracker *track_arg) { tracker= track_arg; } Rowid_filter_tracker *get_tracker() { return tracker; } }; /** @class Rowid_filter_container The implementation of the Rowid_interface used for pk-filters that are filled when performing range index scans. */ class Range_rowid_filter: public Rowid_filter { /* The table for which the rowid filter is built */ TABLE *table; /* The select to perform the range scan to fill the filter */ SQL_SELECT *select; /* The cost info on the filter (used for EXPLAIN/ANALYZE) */ Range_rowid_filter_cost_info *cost_info; public: Range_rowid_filter(TABLE *tab, Range_rowid_filter_cost_info *cost_arg, Rowid_filter_container *container_arg, SQL_SELECT *sel) : Rowid_filter(container_arg), table(tab), select(sel), cost_info(cost_arg) {} ~Range_rowid_filter(); build_return_code build() override; bool check(char *elem) override { if (container->is_empty()) return false; bool was_checked= container->check(table, elem); tracker->increment_checked_elements_count(was_checked); return was_checked; } SQL_SELECT *get_select() { return select; } }; /** @class Refpos_container_sorted_array The wrapper class over Dynamic_array to facilitate operations over array of elements of the type char[N] where N is the same for all elements */ class Refpos_container_sorted_array : public Sql_alloc { /* Maximum number of elements in the array (Now is used only at the initialization of the dynamic array) */ uint max_elements; /* Number of bytes allocated for an element */ uint elem_size; /* The dynamic array over which the wrapper is built */ Dynamic_array *array; public: Refpos_container_sorted_array(uint max_elems, uint elem_sz) : max_elements(max_elems), elem_size(elem_sz), array(0) {} ~Refpos_container_sorted_array() { delete array; array= 0; } bool alloc() { array= new Dynamic_array (PSI_INSTRUMENT_MEM, elem_size * max_elements, elem_size * max_elements/sizeof(char) + 1); return array == NULL; } bool add(char *elem) { for (uint i= 0; i < elem_size; i++) { if (array->append(elem[i])) return true; } return false; } char *get_pos(uint n) { return array->get_pos(n * elem_size); } uint elements() { return (uint) (array->elements() / elem_size); } void sort(qsort_cmp2 cmp, void *cmp_arg) { my_qsort2(array->front(), array->elements() / elem_size, elem_size, cmp, cmp_arg); } bool is_empty() { return elements() == 0; } }; /** @class Rowid_filter_sorted_array The implementation of the Rowid_filter_container interface as a sorted array container of rowids / primary keys */ class Rowid_filter_sorted_array: public Rowid_filter_container { /* The dynamic array to store rowids / primary keys */ Refpos_container_sorted_array refpos_container; /* Initially false, becomes true after the first call of (check() */ bool is_checked; public: Rowid_filter_sorted_array(uint elems, uint elem_size) : refpos_container(elems, elem_size), is_checked(false) {} Rowid_filter_container_type get_type() override { return SORTED_ARRAY_CONTAINER; } bool alloc() override { return refpos_container.alloc(); } bool add(void *ctxt, char *elem) override { return refpos_container.add(elem); } bool check(void *ctxt, char *elem) override; bool is_empty() override { return refpos_container.is_empty(); } }; /** @class Range_rowid_filter_cost_info An objects of this class is created for each potentially usable range filter. It contains the info that allows to figure out whether usage of the range filter promises some gain. */ class Range_rowid_filter_cost_info : public Sql_alloc { /* The table for which the range filter is to be built (if needed) */ TABLE *table; /* Estimated number of elements in the filter */ ulonglong est_elements; /* The cost of building the range filter */ double b; /* a*N-b yields the gain of the filter for N key tuples of the index key_no */ double a; /* The value of N where the gain is 0 */ double cross_x; /* Used for pruning of the potential range filters */ key_map abs_independent; /* These two parameters are used to choose the best range filter in the function TABLE::best_range_rowid_filter_for_partial_join */ double a_adj; double cross_x_adj; public: /* The type of the container of the range filter */ Rowid_filter_container_type container_type; /* The index whose range scan would be used to build the range filter */ uint key_no; /* The selectivity of the range filter */ double selectivity; Range_rowid_filter_cost_info() : table(0), key_no(0) {} void init(Rowid_filter_container_type cont_type, TABLE *tab, uint key_no); double build_cost(Rowid_filter_container_type container_type); inline double lookup_cost(Rowid_filter_container_type cont_type); inline double avg_access_and_eval_gain_per_row(Rowid_filter_container_type cont_type); inline double avg_adjusted_gain_per_row(double access_cost_factor); inline void set_adjusted_gain_param(double access_cost_factor); /* Get the gain that usage of filter promises for r key tuples */ inline double get_gain(double r) { return r * a - b; } /* Get the adjusted gain that usage of filter promises for r key tuples */ inline double get_adjusted_gain(double r) { return r * a_adj - b; } /* The gain promised by usage of the filter for r key tuples due to less condition evaluations */ inline double get_cmp_gain(double r) { return r * (1 - selectivity) / TIME_FOR_COMPARE; } Rowid_filter_container *create_container(); double get_a() const { return a; } void trace_info(THD *thd); friend void TABLE::prune_range_rowid_filters(); friend void TABLE::init_cost_info_for_usable_range_rowid_filters(THD *thd); friend Range_rowid_filter_cost_info * TABLE::best_range_rowid_filter_for_partial_join(uint access_key_no, double records, double access_cost_factor); }; #endif /* ROWID_FILTER_INCLUDED */ mysql/server/private/my_rdtsc.h000064400000020351151027430560012672 0ustar00/* Copyright (c) 2008 MySQL AB, 2009 Sun Microsystems, Inc. Copyright (c) 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* rdtsc3 -- multi-platform timer code pgulutzan@mysql.com, 2005-08-29 modified 2008-11-02 */ #ifndef MY_RDTSC_H #define MY_RDTSC_H # ifndef __has_builtin # define __has_builtin(x) 0 /* Compatibility with non-clang compilers */ # endif # if __has_builtin(__builtin_readcyclecounter) # elif defined _WIN32 # include # elif defined __i386__ || defined __x86_64__ # include # elif defined(__INTEL_COMPILER) && defined(__ia64__) && defined(HAVE_IA64INTRIN_H) # include # elif defined(HAVE_SYS_TIMES_H) && defined(HAVE_GETHRTIME) # include # endif /** Characteristics of a timer. */ struct my_timer_unit_info { /** Routine used for the timer. */ ulonglong routine; /** Overhead of the timer. */ ulonglong overhead; /** Frequency of the timer. */ ulonglong frequency; /** Resolution of the timer. */ ulonglong resolution; }; /** Characteristics of all the supported timers. @sa my_timer_init(). */ struct my_timer_info { /** Characteristics of the cycle timer. */ struct my_timer_unit_info cycles; /** Characteristics of the nanosecond timer. */ struct my_timer_unit_info nanoseconds; /** Characteristics of the microsecond timer. */ struct my_timer_unit_info microseconds; /** Characteristics of the millisecond timer. */ struct my_timer_unit_info milliseconds; /** Characteristics of the tick timer. */ struct my_timer_unit_info ticks; }; typedef struct my_timer_info MY_TIMER_INFO; C_MODE_START /** A cycle timer. On clang we use __builtin_readcyclecounter(), except for AARCH64. On other compilers: On IA-32 and AMD64, we use the RDTSC instruction. On IA-64, we read the ar.itc register. On SPARC, we read the tick register. On POWER, we read the Time Base Register (which is not really a cycle count but a separate counter with less than nanosecond resolution). On IBM S/390 System z we use the STCK instruction. On ARM, we probably should use the Generic Timer, but should figure out how to ensure that it can be accessed. On AARCH64, we use the generic timer base register. We override clang implementation for aarch64 as it access a PMU register which is not guaranteed to be active. Sadly, we have nothing for the Digital Alpha, MIPS, Motorola m68k, HP PA-RISC or other non-mainstream (or obsolete) processors. TODO: consider C++11 std::chrono::high_resolution_clock. We fall back to gethrtime() where available. On the platforms that do not have a CYCLE timer, "wait" events are initialized to use NANOSECOND instead of CYCLE during performance_schema initialization (at the server startup). Linux performance monitor (see "man perf_event_open") can provide cycle counter on the platforms that do not have other kinds of cycle counters. But we don't use it so far. ARM notes --------- During tests on ARMv7 Debian, perf_even_open() based cycle counter provided too low frequency with too high overhead: MariaDB [performance_schema]> SELECT * FROM performance_timers; +-------------+-----------------+------------------+----------------+ | TIMER_NAME | TIMER_FREQUENCY | TIMER_RESOLUTION | TIMER_OVERHEAD | +-------------+-----------------+------------------+----------------+ | CYCLE | 689368159 | 1 | 970 | | NANOSECOND | 1000000000 | 1 | 308 | | MICROSECOND | 1000000 | 1 | 417 | | MILLISECOND | 1000 | 1000 | 407 | | TICK | 127 | 1 | 612 | +-------------+-----------------+------------------+----------------+ Therefore, it was decided not to use perf_even_open() on ARM (i.e. go without CYCLE and have "wait" events use NANOSECOND by default). @return the current timer value, in cycles. */ static inline ulonglong my_timer_cycles(void) { # if __has_builtin(__builtin_readcyclecounter) && !defined (__aarch64__) return __builtin_readcyclecounter(); # elif defined _M_IX86 || defined _M_X64 || defined __i386__ || defined __x86_64__ return __rdtsc(); #elif defined _M_ARM64 return _ReadStatusReg(ARM64_CNTVCT); # elif defined(__INTEL_COMPILER) && defined(__ia64__) && defined(HAVE_IA64INTRIN_H) return (ulonglong) __getReg(_IA64_REG_AR_ITC); /* (3116) */ #elif defined(__GNUC__) && defined(__ia64__) { ulonglong result; __asm __volatile__ ("mov %0=ar.itc" : "=r" (result)); return result; } #elif defined __GNUC__ && defined __powerpc__ return __builtin_ppc_get_timebase(); #elif defined(__GNUC__) && defined(__sparcv9) && defined(_LP64) { ulonglong result; __asm __volatile__ ("rd %%tick,%0" : "=r" (result)); return result; } #elif defined(__GNUC__) && defined(__sparc__) && !defined(_LP64) { union { ulonglong wholeresult; struct { ulong high; ulong low; } splitresult; } result; __asm __volatile__ ("rd %%tick,%1; srlx %1,32,%0" : "=r" (result.splitresult.high), "=r" (result.splitresult.low)); return result.wholeresult; } #elif defined(__GNUC__) && defined(__s390__) /* covers both s390 and s390x */ { ulonglong result; __asm__ __volatile__ ("stck %0" : "=Q" (result) : : "cc"); return result; } #elif defined(__GNUC__) && defined (__aarch64__) { ulonglong result; __asm __volatile("mrs %0, CNTVCT_EL0" : "=&r" (result)); return result; } #elif defined(HAVE_SYS_TIMES_H) && defined(HAVE_GETHRTIME) /* gethrtime may appear as either cycle or nanosecond counter */ return (ulonglong) gethrtime(); #else # define MY_TIMER_CYCLES_IS_ZERO return 0; #endif } #ifdef MY_TIMER_CYCLES_IS_ZERO static inline size_t my_pseudo_random(void) { /* In some platforms, pthread_self() might return a structure that cannot be converted to a number like this. Possible alternatives could include gettid() or sched_getcpu(). */ return ((size_t) pthread_self()) / 16; } #else # define my_pseudo_random my_timer_cycles #endif /** A nanosecond timer. @return the current timer value, in nanoseconds. */ ulonglong my_timer_nanoseconds(void); /** A microseconds timer. @return the current timer value, in microseconds. */ ulonglong my_timer_microseconds(void); /** A millisecond timer. @return the current timer value, in milliseconds. */ ulonglong my_timer_milliseconds(void); /** A ticks timer. @return the current timer value, in ticks. */ ulonglong my_timer_ticks(void); /** Timer initialization function. @param [out] mti the timer characteristics. */ void my_timer_init(MY_TIMER_INFO *mti); C_MODE_END #define MY_TIMER_ROUTINE_RDTSC 5 #define MY_TIMER_ROUTINE_ASM_IA64 6 #define MY_TIMER_ROUTINE_PPC_GET_TIMEBASE 7 #define MY_TIMER_ROUTINE_GETHRTIME 9 #define MY_TIMER_ROUTINE_READ_REAL_TIME 10 #define MY_TIMER_ROUTINE_CLOCK_GETTIME 11 #define MY_TIMER_ROUTINE_GETTIMEOFDAY 13 #define MY_TIMER_ROUTINE_QUERYPERFORMANCECOUNTER 14 #define MY_TIMER_ROUTINE_GETTICKCOUNT 15 #define MY_TIMER_ROUTINE_TIME 16 #define MY_TIMER_ROUTINE_TIMES 17 #define MY_TIMER_ROUTINE_FTIME 18 #define MY_TIMER_ROUTINE_ASM_GCC_SPARC64 23 #define MY_TIMER_ROUTINE_ASM_GCC_SPARC32 24 #define MY_TIMER_ROUTINE_MACH_ABSOLUTE_TIME 25 #define MY_TIMER_ROUTINE_GETSYSTEMTIMEASFILETIME 26 #define MY_TIMER_ROUTINE_ASM_S390 28 #define MY_TIMER_ROUTINE_AARCH64 29 #endif mysql/server/private/dur_prop.h000064400000002072151027430560012700 0ustar00/* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _my_dur_prop_h #define _my_dur_prop_h enum durability_properties { /* Preserves the durability properties defined by the engine */ HA_REGULAR_DURABILITY= 0, /* Ignore the durability properties defined by the engine and write only in-memory entries. */ HA_IGNORE_DURABILITY= 1 }; #endif /* _my_dur_prop_h */ mysql/server/private/ha_handler_stats.h000064400000004437151027430560014360 0ustar00#ifndef HA_HANDLER_STATS_INCLUDED #define HA_HANDLER_STATS_INCLUDED /* Copyright (c) 2023, MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Definitions for parameters to do with handler-routines */ class ha_handler_stats { public: ulonglong pages_accessed; /* Pages accessed from page cache */ ulonglong pages_updated; /* Pages changed in page cache */ ulonglong pages_read_count; /* Pages read from disk */ /* Time spent reading pages, in timer_tracker_frequency() units */ ulonglong pages_read_time; /* Number of pages that we've requested to prefetch while running the query. Note that we don't know: - how much time was spent reading these pages (and how to count the time if reading was done in parallel) - whether the pages were read by "us" or somebody else... */ ulonglong pages_prefetched; ulonglong undo_records_read; /* Time spent in engine, in timer_tracker_frequency() units */ ulonglong engine_time; uint active; /* <> 0 if status has to be updated */ ha_handler_stats() { active= 0; } #define first_stat pages_accessed #define last_stat engine_time inline void reset() { bzero((void*) this, sizeof(*this)); } inline void add(ha_handler_stats *stats) { ulonglong *to= &first_stat; ulonglong *from= &stats->first_stat; do { (*to)+= *from++; } while (to++ != &last_stat); } inline bool has_stats() { if (!active) return 0; ulonglong *to= &first_stat; do { if (*to) return 1; } while (to++ != &last_stat); return 0; } }; #endif /* HA_HANDLER_STATS_INCLUDED */ mysql/server/private/wsrep_condition_variable.h000064400000002714151027430560016124 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_CONDITION_VARIABLE_H #define WSREP_CONDITION_VARIABLE_H /* wsrep-lib */ #include "wsrep/condition_variable.hpp" /* implementation */ #include "my_pthread.h" class Wsrep_condition_variable : public wsrep::condition_variable { public: Wsrep_condition_variable(mysql_cond_t* cond) : m_cond(cond) { } ~Wsrep_condition_variable() = default; void notify_one() override { mysql_cond_signal(m_cond); } void notify_all() override { mysql_cond_broadcast(m_cond); } void wait(wsrep::unique_lock& lock) override { mysql_mutex_t* mutex= static_cast(lock.mutex()->native()); mysql_cond_wait(m_cond, mutex); } private: mysql_cond_t* m_cond; }; #endif /* WSREP_CONDITION_VARIABLE_H */ mysql/server/private/contributors.h000064400000011416151027430560013605 0ustar00#ifndef CONTRIBUTORS_INCLUDED #define CONTRIBUTORS_INCLUDED /* Copyright (c) 2006 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Structure of the name list */ struct show_table_contributors_st { const char *name; const char *location; const char *comment; }; /* Output from "SHOW CONTRIBUTORS" Get permission before editing. Names should be encoded using UTF-8. See also https://mariadb.com/kb/en/log-of-mariadb-contributions/ */ struct show_table_contributors_st show_table_contributors[]= { /* MariaDB Foundation sponsors, alphabetical by tier */ {"Amazon", "https://www.amazon.com/", "Diamond Sponsor of the MariaDB Foundation"}, {"Acronis", "https://www.acronis.com/", "Platinum Sponsor of the MariaDB Foundation"}, {"Alibaba Cloud", "https://www.alibabacloud.com/", "Platinum Sponsor of the MariaDB Foundation"}, {"Cstrnncoll(name.str, name.length, str->str, str->length) == 0; } }; /////////////////////////////////////////////////////////////////////////// /** class sp_pcursor. Stores information about a cursor: - Cursor's name in LEX_STRING. - Cursor's formal parameter descriptions. Formal parameter descriptions reside in a separate context block, pointed by the "m_param_context" member. m_param_context can be NULL. This means a cursor with no parameters. Otherwise, the number of variables in m_param_context means the number of cursor's formal parameters. Note, m_param_context can be not NULL, but have no variables. This is also means a cursor with no parameters (similar to NULL). */ class sp_pcursor: public LEX_CSTRING { class sp_pcontext *m_param_context; // Formal parameters class sp_lex_cursor *m_lex; // The cursor statement LEX public: sp_pcursor(const LEX_CSTRING *name, class sp_pcontext *param_ctx, class sp_lex_cursor *lex) :LEX_CSTRING(*name), m_param_context(param_ctx), m_lex(lex) { } class sp_pcontext *param_context() const { return m_param_context; } class sp_lex_cursor *lex() const { return m_lex; } bool check_param_count_with_error(uint param_count) const; }; /////////////////////////////////////////////////////////////////////////// /// This class represents 'DECLARE HANDLER' statement. class sp_handler : public Sql_alloc { public: /// Enumeration of possible handler types. /// Note: UNDO handlers are not (and have never been) supported. enum enum_type { EXIT, CONTINUE }; /// Handler type. enum_type type; /// Conditions caught by this handler. List condition_values; public: /// The constructor. /// /// @param _type SQL-handler type. sp_handler(enum_type _type) :Sql_alloc(), type(_type) { } }; /////////////////////////////////////////////////////////////////////////// /// The class represents parse-time context, which keeps track of declared /// variables/parameters, conditions, handlers, cursors and labels. /// /// sp_pcontext objects are organized in a tree according to the following /// rules: /// - one sp_pcontext object corresponds for for each BEGIN..END block; /// - one sp_pcontext object corresponds for each exception handler; /// - one additional sp_pcontext object is created to contain /// Stored Program parameters. /// /// sp_pcontext objects are used both at parse-time and at runtime. /// /// During the parsing stage sp_pcontext objects are used: /// - to look up defined names (e.g. declared variables and visible /// labels); /// - to check for duplicates; /// - for error checking; /// - to calculate offsets to be used at runtime. /// /// During the runtime phase, a tree of sp_pcontext objects is used: /// - for error checking (e.g. to check correct number of parameters); /// - to resolve SQL-handlers. class sp_pcontext : public Sql_alloc { public: enum enum_scope { /// REGULAR_SCOPE designates regular BEGIN ... END blocks. REGULAR_SCOPE, /// HANDLER_SCOPE designates SQL-handler blocks. HANDLER_SCOPE }; class Lex_for_loop: public Lex_for_loop_st { public: /* The label poiting to the body start, either explicit or automatically generated. Used during generation of "ITERATE loop_label" to check if "loop_label" is a FOR loop label. - In case of a FOR loop, some additional code (cursor fetch or iteger increment) is generated before the backward jump to the beginning of the loop body. - In case of other loop types (WHILE, REPEAT) only the jump is generated. */ const sp_label *m_start_label; Lex_for_loop() :m_start_label(NULL) { Lex_for_loop_st::init(); } Lex_for_loop(const Lex_for_loop_st &for_loop, const sp_label *start) :m_start_label(start) { Lex_for_loop_st::operator=(for_loop); } }; public: sp_pcontext(); ~sp_pcontext(); /// Create and push a new context in the tree. /// @param thd thread context. /// @param scope scope of the new parsing context. /// @return the node created. sp_pcontext *push_context(THD *thd, enum_scope scope); /// Pop a node from the parsing context tree. /// @return the parent node. sp_pcontext *pop_context(); sp_pcontext *parent_context() const { return m_parent; } sp_pcontext *child_context(uint i) const { return i < m_children.elements() ? m_children.at(i) : NULL; } /// Calculate and return the number of handlers to pop between the given /// context and this one. /// /// @param ctx the other parsing context. /// @param exclusive specifies if the last scope should be excluded. /// /// @return the number of handlers to pop between the given context and /// this one. If 'exclusive' is true, don't count the last scope we are /// leaving; this is used for LEAVE where we will jump to the hpop /// instructions. uint diff_handlers(const sp_pcontext *ctx, bool exclusive) const; /// Calculate and return the number of cursors to pop between the given /// context and this one. /// /// @param ctx the other parsing context. /// @param exclusive specifies if the last scope should be excluded. /// /// @return the number of cursors to pop between the given context and /// this one. If 'exclusive' is true, don't count the last scope we are /// leaving; this is used for LEAVE where we will jump to the cpop /// instructions. uint diff_cursors(const sp_pcontext *ctx, bool exclusive) const; ///////////////////////////////////////////////////////////////////////// // SP-variables (parameters and variables). ///////////////////////////////////////////////////////////////////////// /// @return the maximum number of variables used in this and all child /// contexts. For the root parsing context, this gives us the number of /// slots needed for variables during the runtime phase. uint max_var_index() const { return m_max_var_index; } /// @return the current number of variables used in the parent contexts /// (from the root), including this context. uint current_var_count() const { return m_var_offset + (uint)m_vars.elements(); } /// @return the number of variables in this context alone. uint context_var_count() const { return (uint)m_vars.elements(); } /// return the i-th variable on the current context sp_variable *get_context_variable(uint i) const { DBUG_ASSERT(i < m_vars.elements()); return m_vars.at(i); } /* Return the i-th last context variable. If i is 0, then return the very last variable in m_vars. */ sp_variable *get_last_context_variable(uint i= 0) const { DBUG_ASSERT(i < m_vars.elements()); return m_vars.at(m_vars.elements() - i - 1); } /// Add SP-variable to the parsing context. /// /// @param thd Thread context. /// @param name Name of the SP-variable. /// /// @return instance of newly added SP-variable. sp_variable *add_variable(THD *thd, const LEX_CSTRING *name); /// Retrieve full type information about SP-variables in this parsing /// context and its children. /// /// @param field_def_lst[out] Container to store type information. void retrieve_field_definitions(List *field_def_lst) const; /// Find SP-variable by name. /// /// The function does a linear search (from newer to older variables, /// in case we have shadowed names). /// /// The function is called only at parsing time. /// /// @param name Variable name. /// @param current_scope_only A flag if we search only in current scope. /// /// @return instance of found SP-variable, or NULL if not found. sp_variable *find_variable(const LEX_CSTRING *name, bool current_scope_only) const; /// Find SP-variable by the offset in the root parsing context. /// /// The function is used for two things: /// - When evaluating parameters at the beginning, and setting out parameters /// at the end, of invocation. (Top frame only, so no recursion then.) /// - For printing of sp_instr_set. (Debug mode only.) /// /// @param offset Variable offset in the root parsing context. /// /// @return instance of found SP-variable, or NULL if not found. sp_variable *find_variable(uint offset) const; /// Set the current scope boundary (for default values). /// /// @param n The number of variables to skip. void declare_var_boundary(uint n) { m_pboundary= n; } ///////////////////////////////////////////////////////////////////////// // CASE expressions. ///////////////////////////////////////////////////////////////////////// int register_case_expr() { return m_num_case_exprs++; } int get_num_case_exprs() const { return m_num_case_exprs; } bool push_case_expr_id(int case_expr_id) { return m_case_expr_ids.append(case_expr_id); } void pop_case_expr_id() { m_case_expr_ids.pop(); } int get_current_case_expr_id() const { return *m_case_expr_ids.back(); } ///////////////////////////////////////////////////////////////////////// // Labels. ///////////////////////////////////////////////////////////////////////// sp_label *push_label(THD *thd, const LEX_CSTRING *name, uint ip, sp_label::enum_type type, List * list); sp_label *push_label(THD *thd, const LEX_CSTRING *name, uint ip, sp_label::enum_type type) { return push_label(thd, name, ip, type, &m_labels); } sp_label *push_goto_label(THD *thd, const LEX_CSTRING *name, uint ip, sp_label::enum_type type) { return push_label(thd, name, ip, type, &m_goto_labels); } sp_label *push_label(THD *thd, const LEX_CSTRING *name, uint ip) { return push_label(thd, name, ip, sp_label::IMPLICIT); } sp_label *push_goto_label(THD *thd, const LEX_CSTRING *name, uint ip) { return push_goto_label(thd, name, ip, sp_label::GOTO); } sp_label *find_label(const LEX_CSTRING *name); sp_label *find_goto_label(const LEX_CSTRING *name, bool recusive); sp_label *find_goto_label(const LEX_CSTRING *name) { return find_goto_label(name, true); } sp_label *find_label_current_loop_start(); sp_label *last_label() { sp_label *label= m_labels.head(); if (!label && m_parent) label= m_parent->last_label(); return label; } sp_label *last_goto_label() { return m_goto_labels.head(); } sp_label *pop_label() { return m_labels.pop(); } bool block_label_declare(LEX_CSTRING *label) { sp_label *lab= find_label(label); if (lab) { my_error(ER_SP_LABEL_REDEFINE, MYF(0), label->str); return true; } return false; } ///////////////////////////////////////////////////////////////////////// // Conditions. ///////////////////////////////////////////////////////////////////////// bool add_condition(THD *thd, const LEX_CSTRING *name, sp_condition_value *value); /// See comment for find_variable() above. sp_condition_value *find_condition(const LEX_CSTRING *name, bool current_scope_only) const; sp_condition_value * find_declared_or_predefined_condition(THD *thd, const LEX_CSTRING *name) const; bool declare_condition(THD *thd, const LEX_CSTRING *name, sp_condition_value *val) { if (find_condition(name, true)) { my_error(ER_SP_DUP_COND, MYF(0), name->str); return true; } return add_condition(thd, name, val); } ///////////////////////////////////////////////////////////////////////// // Handlers. ///////////////////////////////////////////////////////////////////////// sp_handler *add_handler(THD* thd, sp_handler::enum_type type); /// This is an auxilary parsing-time function to check if an SQL-handler /// exists in the current parsing context (current scope) for the given /// SQL-condition. This function is used to check for duplicates during /// the parsing phase. /// /// This function can not be used during the runtime phase to check /// SQL-handler existence because it searches for the SQL-handler in the /// current scope only (during runtime, current and parent scopes /// should be checked according to the SQL-handler resolution rules). /// /// @param condition_value the handler condition value /// (not SQL-condition!). /// /// @retval true if such SQL-handler exists. /// @retval false otherwise. bool check_duplicate_handler(const sp_condition_value *cond_value) const; /// Find an SQL handler for the given SQL condition according to the /// SQL-handler resolution rules. This function is used at runtime. /// /// @param value The error code and the SQL state /// @param level The SQL condition level /// /// @return a pointer to the found SQL-handler or NULL. sp_handler *find_handler(const Sql_condition_identity &identity) const; ///////////////////////////////////////////////////////////////////////// // Cursors. ///////////////////////////////////////////////////////////////////////// bool add_cursor(const LEX_CSTRING *name, sp_pcontext *param_ctx, class sp_lex_cursor *lex); /// See comment for find_variable() above. const sp_pcursor *find_cursor(const LEX_CSTRING *name, uint *poff, bool current_scope_only) const; const sp_pcursor *find_cursor_with_error(const LEX_CSTRING *name, uint *poff, bool current_scope_only) const { const sp_pcursor *pcursor= find_cursor(name, poff, current_scope_only); if (!pcursor) { my_error(ER_SP_CURSOR_MISMATCH, MYF(0), name->str); return NULL; } return pcursor; } /// Find cursor by offset (for SHOW {PROCEDURE|FUNCTION} CODE only). const sp_pcursor *find_cursor(uint offset) const; const sp_pcursor *get_cursor_by_local_frame_offset(uint offset) const { return &m_cursors.at(offset); } uint cursor_offset() const { return m_cursor_offset; } uint frame_cursor_count() const { return (uint)m_cursors.elements(); } uint max_cursor_index() const { return m_max_cursor_index + (uint)m_cursors.elements(); } uint current_cursor_count() const { return m_cursor_offset + (uint)m_cursors.elements(); } void set_for_loop(const Lex_for_loop_st &for_loop) { m_for_loop= Lex_for_loop(for_loop, last_label()); } const Lex_for_loop &for_loop() { return m_for_loop; } private: /// Constructor for a tree node. /// @param prev the parent parsing context /// @param scope scope of this parsing context sp_pcontext(sp_pcontext *prev, enum_scope scope); void init(uint var_offset, uint cursor_offset, int num_case_expressions); /* Prevent use of these */ sp_pcontext(const sp_pcontext &); void operator=(sp_pcontext &); sp_condition_value *find_predefined_condition(const LEX_CSTRING *name) const; private: /// m_max_var_index -- number of variables (including all types of arguments) /// in this context including all children contexts. /// /// m_max_var_index >= m_vars.elements(). /// /// m_max_var_index of the root parsing context contains number of all /// variables (including arguments) in all enclosed contexts. uint m_max_var_index; /// The maximum sub context's framesizes. uint m_max_cursor_index; /// Parent context. sp_pcontext *m_parent; /// An index of the first SP-variable in this parsing context. The index /// belongs to a runtime table of SP-variables. /// /// Note: /// - m_var_offset is 0 for root parsing context; /// - m_var_offset is different for all nested parsing contexts. uint m_var_offset; /// Cursor offset for this context. uint m_cursor_offset; /// Boundary for finding variables in this context. This is the number of /// variables currently "invisible" to default clauses. This is normally 0, /// but will be larger during parsing of DECLARE ... DEFAULT, to get the /// scope right for DEFAULT values. uint m_pboundary; int m_num_case_exprs; /// SP parameters/variables. Dynamic_array m_vars; /// Stack of CASE expression ids. Dynamic_array m_case_expr_ids; /// Stack of SQL-conditions. Dynamic_array m_conditions; /// Stack of cursors. Dynamic_array m_cursors; /// Stack of SQL-handlers. Dynamic_array m_handlers; /* In the below example the label <> has two meanings: - GOTO lab : must go before the beginning of the loop - CONTINUE lab : must go to the beginning of the loop We solve this by storing block labels and goto labels into separate lists. BEGIN <> FOR i IN a..10 LOOP ... GOTO lab; ... CONTINUE lab; ... END LOOP; END; */ /// List of block labels List m_labels; /// List of goto labels List m_goto_labels; /// Children contexts, used for destruction. Dynamic_array m_children; /// Scope of this parsing context. enum_scope m_scope; /// FOR LOOP characteristics Lex_for_loop m_for_loop; }; // class sp_pcontext : public Sql_alloc #endif /* _SP_PCONTEXT_H_ */ mysql/server/private/unireg.h000064400000017044151027430560012344 0ustar00#ifndef UNIREG_INCLUDED #define UNIREG_INCLUDED /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #include /* FRM_VER */ /* Extra functions used by unireg library */ #ifndef NO_ALARM_LOOP #define NO_ALARM_LOOP /* lib5 and popen can't use alarm */ #endif /* These paths are converted to other systems (WIN95) before use */ #define LANGUAGE "english/" #define ERRMSG_FILE "errmsg.sys" #define TEMP_PREFIX "MY" #define LOG_PREFIX "ML" #define PROGDIR "bin/" #ifndef MYSQL_DATADIR #define MYSQL_DATADIR "data/" #endif #ifndef SHAREDIR #define SHAREDIR "share/" #endif #ifndef PLUGINDIR #define PLUGINDIR "lib/plugin" #endif #define MAX_ERROR_RANGES 4 /* 1000-2000, 2000-3000, 3000-4000, 4000-5000 */ #define ERRORS_PER_RANGE 1000 #define DEFAULT_ERRMSGS my_default_lc_messages->errmsgs->errmsgs #define CURRENT_THD_ERRMSGS (current_thd)->variables.errmsgs #ifndef mysqld_error_find_printf_error_used #define ER_DEFAULT(X) DEFAULT_ERRMSGS[((X)-ER_ERROR_FIRST) / ERRORS_PER_RANGE][(X)% ERRORS_PER_RANGE] #define ER_THD(thd,X) ((thd)->variables.errmsgs[((X)-ER_ERROR_FIRST) / ERRORS_PER_RANGE][(X) % ERRORS_PER_RANGE]) #define ER(X) ER_THD(current_thd, (X)) #endif #define ER_THD_OR_DEFAULT(thd,X) ((thd) ? ER_THD(thd, (X)) : ER_DEFAULT(X)) #define SPECIAL_USE_LOCKS 1 /* Lock used databases */ #define SPECIAL_NO_NEW_FUNC 2 /* Skip new functions */ #define SPECIAL_SKIP_SHOW_DB 4 /* Don't allow 'show db' */ #define SPECIAL_WAIT_IF_LOCKED 8 /* Wait if locked database */ #define SPECIAL_SAME_DB_NAME 16 /* form name = file name */ #define SPECIAL_ENGLISH 32 /* English error messages */ #define SPECIAL_NO_RESOLVE 64 /* Obsolete */ #define SPECIAL_NO_PRIOR 128 /* Obsolete */ #define SPECIAL_BIG_SELECTS 256 /* Don't use heap tables */ #define SPECIAL_NO_HOST_CACHE 512 /* Don't cache hosts */ #define SPECIAL_SHORT_LOG_FORMAT 1024 #define SPECIAL_SAFE_MODE 2048 #define SPECIAL_LOG_QUERIES_NOT_USING_INDEXES 4096 /* Obsolete */ /* Extern defines */ #define store_record(A,B) memcpy((A)->B,(A)->record[0],(size_t) (A)->s->reclength) #define restore_record(A,B) memcpy((A)->record[0],(A)->B,(size_t) (A)->s->reclength) #define cmp_record(A,B) memcmp((A)->record[0],(A)->B,(size_t) (A)->s->reclength) #define empty_record(A) { \ restore_record((A),s->default_values); \ if ((A)->s->null_bytes) \ bfill((A)->null_flags,(A)->s->null_bytes,255); \ } /* Defines for use with openfrm, openprt and openfrd */ #define READ_ALL (1 << 0) /* openfrm: Read all parameters */ #define EXTRA_RECORD (1 << 3) /* Reserve space for an extra record */ #define DELAYED_OPEN (1 << 12) /* Open table later */ #define OPEN_VIEW_NO_PARSE (1 << 14) /* Open frm only if it's a view, but do not parse view itself */ /** This flag is used in function get_all_tables() which fills I_S tables with data which are retrieved from frm files and storage engine The flag means that we need to open FRM file only to get necessary data. */ #define OPEN_FRM_FILE_ONLY (1 << 15) /** This flag is used in function get_all_tables() which fills I_S tables with data which are retrieved from frm files and storage engine The flag means that we need to process tables only to get necessary data. Views are not processed. */ #define OPEN_TABLE_ONLY (1 << 16) /** This flag is used in function get_all_tables() which fills I_S tables with data which are retrieved from frm files and storage engine The flag means that we need to process views only to get necessary data. Tables are not processed. */ #define OPEN_VIEW_ONLY (1 << 17) /** This flag is used in function get_all_tables() which fills I_S tables with data which are retrieved from frm files and storage engine. The flag means that we need to open a view using open_normal_and_derived_tables() function. */ #define OPEN_VIEW_FULL (1 << 18) /** This flag is used in function get_all_tables() which fills I_S tables with data which are retrieved from frm files and storage engine. The flag means that I_S table uses optimization algorithm. */ #define OPTIMIZE_I_S_TABLE (1 << 19) /** This flag is used to instruct tdc_open_view() to check metadata version. */ #define CHECK_METADATA_VERSION (1 << 20) /* The flag means that we need to process trigger files only. */ #define OPEN_TRIGGER_ONLY (1 << 21) /* Minimum length pattern before Turbo Boyer-Moore is used for SELECT "text" LIKE "%pattern%", excluding the two wildcards in class Item_func_like. */ #define MIN_TURBOBM_PATTERN_LEN 3 /* Defines for binary logging. Do not decrease the value of BIN_LOG_HEADER_SIZE. Do not even increase it before checking code. */ #define BIN_LOG_HEADER_SIZE 4 #define DEFAULT_KEY_CACHE_NAME "default" /* Include prototypes for unireg */ #include "mysqld_error.h" #include "structs.h" /* All structs we need */ #include "sql_list.h" /* List<> */ #include "field.h" /* Create_field */ /* Types of values in the MariaDB extra2 frm segment. Each value is written as type: 1 byte length: 1 byte (1..255) or \0 and 2 bytes. binary value of the 'length' bytes. Older MariaDB servers can ignore values of unknown types if the type code is less than 128 (EXTRA2_ENGINE_IMPORTANT). Otherwise older (but newer than 10.0.1) servers are required to report an error. */ enum extra2_frm_value_type { EXTRA2_TABLEDEF_VERSION=0, EXTRA2_DEFAULT_PART_ENGINE=1, EXTRA2_GIS=2, EXTRA2_APPLICATION_TIME_PERIOD=3, EXTRA2_PERIOD_FOR_SYSTEM_TIME=4, EXTRA2_INDEX_FLAGS=5, #define EXTRA2_ENGINE_IMPORTANT 128 EXTRA2_ENGINE_TABLEOPTS=128, EXTRA2_FIELD_FLAGS=129, EXTRA2_FIELD_DATA_TYPE_INFO=130, EXTRA2_PERIOD_WITHOUT_OVERLAPS=131, }; enum extra2_field_flags { VERS_OPTIMIZED_UPDATE= 1 << INVISIBLE_MAX_BITS, }; enum extra2_index_flags { EXTRA2_DEFAULT_INDEX_FLAGS, EXTRA2_IGNORED_KEY }; static inline size_t extra2_read_len(const uchar **extra2, const uchar *end) { size_t length= *(*extra2)++; if (length) return length; if ((*extra2) + 2 >= end) return 0; length= uint2korr(*extra2); (*extra2)+= 2; if (length < 256 || *extra2 + length > end) return 0; return length; } LEX_CUSTRING build_frm_image(THD *thd, const LEX_CSTRING &table, HA_CREATE_INFO *create_info, List &create_fields, uint keys, KEY *key_info, handler *db_file); #define FRM_HEADER_SIZE 64 #define FRM_FORMINFO_SIZE 288 #define FRM_MAX_SIZE (1024*1024) static inline bool is_binary_frm_header(uchar *head) { return head[0] == 254 && head[1] == 1 && head[2] >= FRM_VER && head[2] <= FRM_VER_CURRENT; } #endif mysql/server/private/sql_sequence.h000064400000012074151027430560013540 0ustar00/* Copyright (c) 2017, MariaDB corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SQL_SEQUENCE_INCLUDED #define SQL_SEQUENCE_INCLUDED #define seq_field_used_min_value 1 #define seq_field_used_max_value 2 #define seq_field_used_start 4 #define seq_field_used_increment 8 #define seq_field_used_cache 16 #define seq_field_used_cycle 32 #define seq_field_used_restart 64 #define seq_field_used_restart_value 128 /* Field position in sequence table for some fields we refer to directly */ #define NEXT_FIELD_NO 0 #define MIN_VALUE_FIELD_NO 1 #define ROUND_FIELD_NO 7 /** sequence_definition is used when defining a sequence as part of create */ class sequence_definition :public Sql_alloc { public: sequence_definition(): min_value(1), max_value(LONGLONG_MAX-1), start(1), increment(1), cache(1000), round(0), restart(0), cycle(0), used_fields(0) {} longlong reserved_until; longlong min_value; longlong max_value; longlong start; longlong increment; longlong cache; ulonglong round; longlong restart; // alter sequence restart value bool cycle; uint used_fields; // Which fields where used in CREATE bool check_and_adjust(bool set_reserved_until); void store_fields(TABLE *table); void read_fields(TABLE *table); int write_initial_sequence(TABLE *table); int write(TABLE *table, bool all_fields); /* This must be called after sequence data has been updated */ void adjust_values(longlong next_value); inline void print_dbug() { DBUG_PRINT("sequence", ("reserved: %lld start: %lld increment: %lld min_value: %lld max_value: %lld cache: %lld round: %lld", reserved_until, start, increment, min_value, max_value, cache, round)); } protected: /* The following values are the values from sequence_definition merged with global auto_increment_offset and auto_increment_increment */ longlong real_increment; longlong next_free_value; }; /** SEQUENCE is in charge of managing the sequence values. It's also responsible to generate new values and updating the sequence table (engine=SQL_SEQUENCE) trough it's specialized handler interface. If increment is 0 then the sequence will be be using auto_increment_increment and auto_increment_offset variables, just like AUTO_INCREMENT is using. */ class SEQUENCE :public sequence_definition { public: enum seq_init { SEQ_UNINTIALIZED, SEQ_IN_PREPARE, SEQ_IN_ALTER, SEQ_READY_TO_USE }; SEQUENCE(); ~SEQUENCE(); int read_initial_values(TABLE *table); int read_stored_values(TABLE *table); void write_lock(TABLE *table); void write_unlock(TABLE *table); void read_lock(TABLE *table); void read_unlock(TABLE *table); void copy(sequence_definition *seq) { sequence_definition::operator= (*seq); adjust_values(reserved_until); all_values_used= 0; } longlong next_value(TABLE *table, bool second_round, int *error); int set_value(TABLE *table, longlong next_value, ulonglong round_arg, bool is_used); longlong increment_value(longlong value) { if (real_increment > 0) { if (value > max_value - real_increment || value + real_increment > max_value) value= max_value + 1; else value+= real_increment; } else { if (value + real_increment < min_value || value < min_value - real_increment) value= min_value - 1; else value+= real_increment; } return value; } bool all_values_used; seq_init initialized; private: mysql_rwlock_t mutex; }; /** Class to cache last value of NEXT VALUE from the sequence */ class SEQUENCE_LAST_VALUE { public: SEQUENCE_LAST_VALUE(uchar *key_arg, uint length_arg) :key(key_arg), length(length_arg) {} ~SEQUENCE_LAST_VALUE() { my_free((void*) key); } /* Returns 1 if table hasn't been dropped or re-created */ bool check_version(TABLE *table); void set_version(TABLE *table); const uchar *key; uint length; bool null_value; longlong value; uchar table_version[MY_UUID_SIZE]; }; class Create_field; extern bool prepare_sequence_fields(THD *thd, List *fields); extern bool check_sequence_fields(LEX *lex, List *fields, const LEX_CSTRING db, const LEX_CSTRING table_name); extern bool sequence_insert(THD *thd, LEX *lex, TABLE_LIST *table_list); #endif /* SQL_SEQUENCE_INCLUDED */ mysql/server/private/wsrep_mutex.h000064400000002300151027430560013422 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_MUTEX_H #define WSREP_MUTEX_H /* wsrep-lib */ #include "wsrep/mutex.hpp" /* implementation */ #include "my_pthread.h" class Wsrep_mutex : public wsrep::mutex { public: Wsrep_mutex(mysql_mutex_t* mutex) : m_mutex(mutex) { } void lock() override { mysql_mutex_lock(m_mutex); } void unlock() override { mysql_mutex_unlock(m_mutex); } void* native() override { return m_mutex; } private: mysql_mutex_t* m_mutex; }; #endif /* WSREP_MUTEX_H */ mysql/server/private/rpl_constants.h000064400000006435151027430560013746 0ustar00/* Copyright (c) 2007 MySQL AB, 2008 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_CONSTANTS_H #define RPL_CONSTANTS_H #include #include /** Enumeration of the incidents that can occur for the server. */ enum Incident { /** No incident */ INCIDENT_NONE = 0, /** There are possibly lost events in the replication stream */ INCIDENT_LOST_EVENTS = 1, /** Shall be last event of the enumeration */ INCIDENT_COUNT }; /** Enumeration of the reserved formats of Binlog extra row information */ enum ExtraRowInfoFormat { /** Reserved formats 0 -> 63 inclusive */ ERIF_LASTRESERVED = 63, /** Available / uncontrolled formats 64 -> 254 inclusive */ ERIF_OPEN1 = 64, ERIF_OPEN2 = 65, ERIF_LASTOPEN = 254, /** Multi-payload format 255 Length is total length, payload is sequence of sub-payloads with their own headers containing length + format. */ ERIF_MULTI = 255 }; /* 1 byte length, 1 byte format Length is total length in bytes, including 2 byte header Length values 0 and 1 are currently invalid and reserved. */ #define EXTRA_ROW_INFO_LEN_OFFSET 0 #define EXTRA_ROW_INFO_FORMAT_OFFSET 1 #define EXTRA_ROW_INFO_HDR_BYTES 2 #define EXTRA_ROW_INFO_MAX_PAYLOAD (255 - EXTRA_ROW_INFO_HDR_BYTES) enum enum_binlog_checksum_alg { BINLOG_CHECKSUM_ALG_OFF= 0, // Events are without checksum though its generator // is checksum-capable New Master (NM). BINLOG_CHECKSUM_ALG_CRC32= 1, // CRC32 of zlib algorithm. BINLOG_CHECKSUM_ALG_ENUM_END, // the cut line: valid alg range is [1, 0x7f]. BINLOG_CHECKSUM_ALG_UNDEF= 255 // special value to tag undetermined yet checksum // or events from checksum-unaware servers }; #define BINLOG_CRYPTO_SCHEME_LENGTH 1 #define BINLOG_KEY_VERSION_LENGTH 4 #define BINLOG_IV_LENGTH MY_AES_BLOCK_SIZE #define BINLOG_IV_OFFS_LENGTH 4 #define BINLOG_NONCE_LENGTH (BINLOG_IV_LENGTH - BINLOG_IV_OFFS_LENGTH) struct Binlog_crypt_data { uint scheme; uint key_version, key_length, ctx_size; uchar key[MY_AES_MAX_KEY_LENGTH]; uchar nonce[BINLOG_NONCE_LENGTH]; int init(uint sch, uint kv) { scheme= sch; ctx_size= encryption_ctx_size(ENCRYPTION_KEY_SYSTEM_DATA, kv); key_version= kv; key_length= sizeof(key); return encryption_key_get(ENCRYPTION_KEY_SYSTEM_DATA, kv, key, &key_length); } void set_iv(uchar* iv, uint32 offs) const { memcpy(iv, nonce, BINLOG_NONCE_LENGTH); int4store(iv + BINLOG_NONCE_LENGTH, offs); } }; #endif /* RPL_CONSTANTS_H */ mysql/server/private/sql_const.h000064400000025734151027430560013065 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file File containing constants that can be used throughout the server. @note This file shall not contain or include any declarations of any kinds. */ #ifndef SQL_CONST_INCLUDED #define SQL_CONST_INCLUDED #include #define LIBLEN FN_REFLEN-FN_LEN /* Max l{ngd p} dev */ /* extra 4+4 bytes for slave tmp tables */ #define MAX_DBKEY_LENGTH (NAME_LEN*2+1+1+4+4) #define MAX_ALIAS_NAME 256 #define MAX_FIELD_NAME (NAME_LEN+1) /* Max colum name length +1 */ #define MAX_SYS_VAR_LENGTH 32 #define MAX_KEY MAX_INDEXES /* Max used keys */ #define MAX_REF_PARTS 32 /* Max parts used as ref */ /* Maximum length of the data part of an index lookup key. The "data part" is defined as the value itself, not including the NULL-indicator bytes or varchar length bytes ("the Extras"). We need this value because there was a bug where length of the Extras were not counted. You probably need MAX_KEY_LENGTH, not this constant. */ #define MAX_DATA_LENGTH_FOR_KEY 3072 #if SIZEOF_OFF_T > 4 #define MAX_REFLENGTH 8 /* Max length for record ref */ #else #define MAX_REFLENGTH 4 /* Max length for record ref */ #endif #define MAX_HOSTNAME (HOSTNAME_LENGTH + 1) /* len+1 in mysql.user */ #define MAX_CONNECTION_NAME NAME_LEN #define MAX_MBWIDTH 3 /* Max multibyte sequence */ #define MAX_FILENAME_MBWIDTH 5 #define MAX_FIELD_CHARLENGTH 255 /* In MAX_FIELD_VARCHARLENGTH we reserve extra bytes for the overhead: - 2 bytes for the length - 1 byte for NULL bits to avoid the "Row size too large" error for these three corner definitions: CREATE TABLE t1 (c VARBINARY(65533)); CREATE TABLE t1 (c VARBINARY(65534)); CREATE TABLE t1 (c VARBINARY(65535)); Like VARCHAR(65536), they will be converted to BLOB automatically in non-strict mode. */ #define MAX_FIELD_VARCHARLENGTH (65535-2-1) #define MAX_FIELD_BLOBLENGTH UINT_MAX32 /* cf field_blob::get_length() */ #define CONVERT_IF_BIGGER_TO_BLOB 512 /* Threshold *in characters* */ /* Max column width +1 */ #define MAX_FIELD_WIDTH (MAX_FIELD_CHARLENGTH*MAX_MBWIDTH+1) #define MAX_BIT_FIELD_LENGTH 64 /* Max length in bits for bit fields */ #define MAX_DATE_WIDTH 10 /* YYYY-MM-DD */ #define MIN_TIME_WIDTH 10 /* -HHH:MM:SS */ #define MAX_TIME_WIDTH 16 /* -DDDDDD HH:MM:SS */ #define MAX_TIME_FULL_WIDTH 23 /* -DDDDDD HH:MM:SS.###### */ #define MAX_DATETIME_FULL_WIDTH 26 /* YYYY-MM-DD HH:MM:SS.###### */ #define MAX_DATETIME_WIDTH 19 /* YYYY-MM-DD HH:MM:SS */ #define MAX_DATETIME_COMPRESSED_WIDTH 14 /* YYYYMMDDHHMMSS */ #define MAX_DATETIME_PRECISION 6 #define MAX_TABLES (sizeof(table_map)*8-3) /* Max tables in join */ #define PARAM_TABLE_BIT (((table_map) 1) << (sizeof(table_map)*8-3)) #define OUTER_REF_TABLE_BIT (((table_map) 1) << (sizeof(table_map)*8-2)) #define RAND_TABLE_BIT (((table_map) 1) << (sizeof(table_map)*8-1)) #define PSEUDO_TABLE_BITS (PARAM_TABLE_BIT | OUTER_REF_TABLE_BIT | \ RAND_TABLE_BIT) #define CONNECT_STRING_MAXLEN 65535 /* stored in 2 bytes in .frm */ #define MAX_FIELDS 4096 /* Limit in the .frm file */ #define MAX_PARTITIONS 8192 #define MAX_SELECT_NESTING (SELECT_NESTING_MAP_SIZE - 1) #define MAX_SORT_MEMORY 2048*1024 #define MIN_SORT_MEMORY 1024 /* Some portable defines */ #define STRING_BUFFER_USUAL_SIZE 80 /* Memory allocated when parsing a statement / saving a statement */ #define MEM_ROOT_BLOCK_SIZE 8192 #define MEM_ROOT_PREALLOC 8192 #define TRANS_MEM_ROOT_BLOCK_SIZE 4096 #define TRANS_MEM_ROOT_PREALLOC 4096 #define DEFAULT_ERROR_COUNT 64 #define EXTRA_RECORDS 10 /* Extra records in sort */ #define SCROLL_EXTRA 5 /* Extra scroll-rows. */ #define FIELD_NAME_USED ((uint) 32768) /* Bit set if fieldname used */ #define FORM_NAME_USED ((uint) 16384) /* Bit set if formname used */ #define FIELD_NR_MASK 16383 /* To get fieldnumber */ #define FERR -1 /* Error from my_functions */ #define CREATE_MODE 0 /* Default mode on new files */ #define NAMES_SEP_CHAR 255 /* Char to sep. names */ #define READ_RECORD_BUFFER (uint) (IO_SIZE*8) /* Pointer_buffer_size */ #define DISK_BUFFER_SIZE (uint) (IO_SIZE*16) /* Size of diskbuffer */ #define FRM_VER_TRUE_VARCHAR (FRM_VER+4) /* 10 */ #define FRM_VER_EXPRESSSIONS (FRM_VER+5) /* 11 */ #define FRM_VER_CURRENT FRM_VER_EXPRESSSIONS /*************************************************************************** Configuration parameters ****************************************************************************/ #define ACL_CACHE_SIZE 256 #define MAX_PASSWORD_LENGTH 32 #define HOST_CACHE_SIZE 128 #define MAX_ACCEPT_RETRY 10 // Test accept this many times #define MAX_FIELDS_BEFORE_HASH 32 #define USER_VARS_HASH_SIZE 16 #define SEQUENCES_HASH_SIZE 16 #define TABLE_OPEN_CACHE_MIN 200 #define TABLE_OPEN_CACHE_DEFAULT 2000 #define TABLE_DEF_CACHE_DEFAULT 400 /** We must have room for at least 400 table definitions in the table cache, since otherwise there is no chance prepared statements that use these many tables can work. Prepared statements use table definition cache ids (table_map_id) as table version identifiers. If the table definition cache size is less than the number of tables used in a statement, the contents of the table definition cache is guaranteed to rotate between a prepare and execute. This leads to stable validation errors. In future we shall use more stable version identifiers, for now the only solution is to ensure that the table definition cache can contain at least all tables of a given statement. */ #define TABLE_DEF_CACHE_MIN 400 /** Maximum number of connections default value. 151 is larger than Apache's default max children, to avoid "too many connections" error in a common setup. */ #define MAX_CONNECTIONS_DEFAULT 151 /* Stack reservation. Feel free to raise this by the smallest amount you can to get the "execution_constants" test to pass. */ #define STACK_MIN_SIZE 16000 // Abort if less stack during eval. #define STACK_MIN_SIZE_FOR_OPEN (1024*80) #define STACK_BUFF_ALLOC 352 ///< For stack overrun checks #ifndef MYSQLD_NET_RETRY_COUNT #define MYSQLD_NET_RETRY_COUNT 10 ///< Abort read after this many int. #endif /* Allocations with MEM_ROOT. We should try to keep these as powers of 2 and not higher than 32768 to get full benefit of allocators like tcmalloc that will for these use a local heap without locks. */ #define QUERY_ALLOC_BLOCK_SIZE 32768 #define QUERY_ALLOC_PREALLOC_SIZE 32768 /* 65536 could be better */ #define TRANS_ALLOC_BLOCK_SIZE 8192 #define TRANS_ALLOC_PREALLOC_SIZE 4096 #define RANGE_ALLOC_BLOCK_SIZE 4096 #define ACL_ALLOC_BLOCK_SIZE 1024 #define UDF_ALLOC_BLOCK_SIZE 1024 #define TABLE_PREALLOC_BLOCK_SIZE 8192 #define TABLE_ALLOC_BLOCK_SIZE 4096 #define WARN_ALLOC_BLOCK_SIZE 2048 #define WARN_ALLOC_PREALLOC_SIZE 1024 #define TMP_TABLE_BLOCK_SIZE 16384 #define TMP_TABLE_PREALLOC_SIZE 32768 #define SHOW_ALLOC_BLOCK_SIZE 32768 /* The following parameters is to decide when to use an extra cache to optimise seeks when reading a big table in sorted order */ #define MIN_FILE_LENGTH_TO_USE_ROW_CACHE (10L*1024*1024) #define MIN_ROWS_TO_USE_TABLE_CACHE 100 #define MIN_ROWS_TO_USE_BULK_INSERT 100 /** The following is used to decide if MySQL should use table scanning instead of reading with keys. The number says how many evaluation of the WHERE clause is comparable to reading one extra row from a table. */ #define TIME_FOR_COMPARE 5.0 // 5 WHERE compares == one read #define TIME_FOR_COMPARE_IDX 20.0 #define IDX_BLOCK_COPY_COST ((double) 1 / TIME_FOR_COMPARE) #define IDX_LOOKUP_COST ((double) 1 / 8) #define MULTI_RANGE_READ_SETUP_COST (IDX_BLOCK_COPY_COST/10) /** Number of comparisons of table rowids equivalent to reading one row from a table. */ #define TIME_FOR_COMPARE_ROWID (TIME_FOR_COMPARE*100) /* cost1 is better that cost2 only if cost1 + COST_EPS < cost2 */ #define COST_EPS 0.001 /* For sequential disk seeks the cost formula is: DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST * #blocks_to_skip The cost of average seek DISK_SEEK_BASE_COST + DISK_SEEK_PROP_COST*BLOCKS_IN_AVG_SEEK =1.0. */ #define DISK_SEEK_BASE_COST ((double)0.9) #define BLOCKS_IN_AVG_SEEK 128 #define DISK_SEEK_PROP_COST ((double)0.1/BLOCKS_IN_AVG_SEEK) /** Number of rows in a reference table when refereed through a not unique key. This value is only used when we don't know anything about the key distribution. */ #define MATCHING_ROWS_IN_OTHER_TABLE 10 /* Subquery materialization-related constants */ #define HEAP_TEMPTABLE_LOOKUP_COST 0.05 #define DISK_TEMPTABLE_LOOKUP_COST 1.0 #define SORT_INDEX_CMP_COST 0.02 #define COST_MAX (DBL_MAX * (1.0 - DBL_EPSILON)) #define COST_ADD(c,d) (COST_MAX - (d) > (c) ? (c) + (d) : COST_MAX) #define COST_MULT(c,f) (COST_MAX / (f) > (c) ? (c) * (f) : COST_MAX) #define MY_CHARSET_BIN_MB_MAXLEN 1 /** Don't pack string keys shorter than this (if PACK_KEYS=1 isn't used). */ #define KEY_DEFAULT_PACK_LENGTH 8 /** Characters shown for the command in 'show processlist'. */ #define PROCESS_LIST_WIDTH 100 /* Characters shown for the command in 'information_schema.processlist' */ #define PROCESS_LIST_INFO_WIDTH 65535 #define PRECISION_FOR_DOUBLE 53 #define PRECISION_FOR_FLOAT 24 /* -[digits].E+## */ #define MAX_FLOAT_STR_LENGTH (FLT_DIG + 6) /* -[digits].E+### */ #define MAX_DOUBLE_STR_LENGTH (DBL_DIG + 7) /* Default time to wait before aborting a new client connection that does not respond to "initial server greeting" timely */ #define CONNECT_TIMEOUT 10 /* Wait 5 minutes before removing thread from thread cache */ #define THREAD_CACHE_TIMEOUT 5*60 /* The following can also be changed from the command line */ #define DEFAULT_CONCURRENCY 10 #define DELAYED_LIMIT 100 /**< pause after xxx inserts */ #define DELAYED_QUEUE_SIZE 1000 #define DELAYED_WAIT_TIMEOUT (5*60) /**< Wait for delayed insert */ #define MAX_CONNECT_ERRORS 100 ///< errors before disabling host #define LONG_TIMEOUT ((ulong) 3600L*24L*365L) /** Maximum length of time zone name that we support (Time zone name is char(64) in db). mysqlbinlog needs it. */ #define MAX_TIME_ZONE_NAME_LENGTH (NAME_LEN + 1) #define SP_PSI_STATEMENT_INFO_COUNT 19 #endif /* SQL_CONST_INCLUDED */ mysql/server/private/repl_failsafe.h000064400000003061151027430560013641 0ustar00#ifndef REPL_FAILSAFE_INCLUDED #define REPL_FAILSAFE_INCLUDED /* Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef HAVE_REPLICATION #include "mysql.h" #include #include "slave.h" extern Atomic_counter binlog_dump_thread_count; typedef enum {RPL_AUTH_MASTER=0,RPL_IDLE_SLAVE,RPL_ACTIVE_SLAVE, RPL_LOST_SOLDIER,RPL_TROOP_SOLDIER, RPL_RECOVERY_CAPTAIN,RPL_NULL /* inactive */, RPL_ANY /* wild card used by change_rpl_status */ } RPL_STATUS; extern ulong rpl_status; extern mysql_mutex_t LOCK_rpl_status; extern mysql_cond_t COND_rpl_status; extern TYPELIB rpl_role_typelib; extern const char* rpl_role_type[], *rpl_status_type[]; void change_rpl_status(ulong from_status, ulong to_status); int find_recovery_captain(THD* thd, MYSQL* mysql); bool show_slave_hosts(THD* thd); #endif /* HAVE_REPLICATION */ #endif /* REPL_FAILSAFE_INCLUDED */ mysql/server/private/sql_servers.h000064400000003361151027430560013420 0ustar00#ifndef SQL_SERVERS_INCLUDED #define SQL_SERVERS_INCLUDED /* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "slave.h" // for tables_ok(), rpl_filter class THD; typedef struct st_lex_server_options LEX_SERVER_OPTIONS; typedef struct st_mem_root MEM_ROOT; /* structs */ typedef struct st_federated_server { const char *server_name; long port; size_t server_name_length; const char *db, *scheme, *username, *password, *socket, *owner, *host, *sport; } FOREIGN_SERVER; /* cache handlers */ bool servers_init(bool dont_read_server_table); bool servers_reload(THD *thd); void servers_free(bool end=0); /* insert functions */ int create_server(THD *thd, LEX_SERVER_OPTIONS *server_options); /* drop functions */ int drop_server(THD *thd, LEX_SERVER_OPTIONS *server_options); /* update functions */ int alter_server(THD *thd, LEX_SERVER_OPTIONS *server_options); /* lookup functions */ FOREIGN_SERVER *get_server_by_name(MEM_ROOT *mem, const char *server_name, FOREIGN_SERVER *server_buffer); #endif /* SQL_SERVERS_INCLUDED */ mysql/server/private/sql_list.h000064400000053672151027430560012714 0ustar00#ifndef INCLUDES_MYSQL_SQL_LIST_H #define INCLUDES_MYSQL_SQL_LIST_H /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_alloc.h" #include /** Simple intrusive linked list. @remark Similar in nature to base_list, but intrusive. It keeps a a pointer to the first element in the list and a indirect reference to the last element. */ template class SQL_I_List :public Sql_alloc { public: uint elements; /** The first element in the list. */ T *first; /** A reference to the next element in the list. */ T **next; SQL_I_List() { empty(); } SQL_I_List(const SQL_I_List &tmp) : Sql_alloc() { elements= tmp.elements; first= tmp.first; next= elements ? tmp.next : &first; } SQL_I_List& operator=(const SQL_I_List &tmp) { elements= tmp.elements; first= tmp.first; next= elements ? tmp.next : &first;; return *this; } inline void empty() { elements= 0; first= NULL; next= &first; } inline void link_in_list(T *element, T **next_ptr) { elements++; (*next)= element; next= next_ptr; *next= NULL; } inline void save_and_clear(SQL_I_List *save) { *save= *this; empty(); } inline void push_front(SQL_I_List *save) { /* link current list last */ *save->next= first; first= save->first; elements+= save->elements; } inline void push_back(SQL_I_List *save) { if (save->first) { *next= save->first; next= save->next; elements+= save->elements; } } }; /* Basic single linked list Used for item and item_buffs. All list ends with a pointer to the 'end_of_list' element, which data pointer is a null pointer and the next pointer points to itself. This makes it very fast to traverse lists as we don't have to test for a specialend condition for list that can't contain a null pointer. */ /** list_node - a node of a single-linked list. @note We never call a destructor for instances of this class. */ struct list_node :public Sql_alloc { list_node *next; void *info; list_node(const void *info_par, list_node *next_par) :next(next_par), info(const_cast(info_par)) {} list_node() /* For end_of_list */ { info= 0; next= this; } }; extern MYSQL_PLUGIN_IMPORT list_node end_of_list; class base_list :public Sql_alloc { protected: list_node *first,**last; public: uint elements; bool operator==(const base_list &rhs) const { return elements == rhs.elements && first == rhs.first && last == rhs.last; } base_list& operator=(const base_list &rhs) { elements= rhs.elements; first= rhs.first; last= elements ? rhs.last : &first; return *this; } inline void empty() { elements=0; first= &end_of_list; last=&first;} inline base_list() { empty(); } /** This is a shallow copy constructor that implicitly passes the ownership from the source list to the new instance. The old instance is not updated, so both objects end up sharing the same nodes. If one of the instances then adds or removes a node, the other becomes out of sync ('last' pointer), while still operational. Some old code uses and relies on this behaviour. This logic is quite tricky: please do not use it in any new code. */ inline base_list(const base_list &tmp) :Sql_alloc() { *this= tmp; } /** Construct a deep copy of the argument in memory root mem_root. The elements themselves are copied by pointer. If you also need to copy elements by value, you should employ list_copy_and_replace_each_value after creating a copy. */ bool copy(const base_list *rhs, MEM_ROOT *mem_root); base_list(const base_list &rhs, MEM_ROOT *mem_root) { copy(&rhs, mem_root); } inline base_list(bool) {} inline bool push_back(void *info) { if (((*last)=new list_node(info, &end_of_list))) { last= &(*last)->next; elements++; return 0; } return 1; } inline bool push_back(void *info, MEM_ROOT *mem_root) { if (((*last)=new (mem_root) list_node(info, &end_of_list))) { last= &(*last)->next; elements++; return 0; } return 1; } bool push_front_impl(list_node *node) { if (node) { if (last == &first) last= &node->next; first=node; elements++; return 0; } return 1; } inline bool push_front(void *info) { return push_front_impl(new list_node(info, first)); } inline bool push_front(void *info, MEM_ROOT *mem_root) { return push_front_impl(new (mem_root) list_node(info,first)); } void remove(list_node **prev) { list_node *node=(*prev)->next; if (!--elements) last= &first; else if (last == &(*prev)->next) last= prev; delete *prev; *prev=node; } inline void append(base_list *list) { if (!list->is_empty()) { if (is_empty()) { *this= *list; return; } *last= list->first; last= list->last; elements+= list->elements; } } inline void *pop(void) { if (first == &end_of_list) return 0; list_node *tmp=first; first=first->next; if (!--elements) last= &first; return tmp->info; } /* Remove from this list elements that are contained in the passed list. We assume that the passed list is a tail of this list (that is, the whole list_node* elements are shared). */ inline void disjoin(const base_list *list) { list_node **prev= &first; list_node *node= first; list_node *list_first= list->first; elements=0; while (node != &end_of_list && node != list_first) { prev= &node->next; node= node->next; elements++; if (node == &end_of_list) return; } *prev= &end_of_list; last= prev; } inline void prepend(base_list *list) { if (!list->is_empty()) { if (is_empty()) last= list->last; *list->last= first; first= list->first; elements+= list->elements; } } /** Swap two lists. */ inline void swap(base_list &rhs) { list_node **rhs_last=rhs.last; swap_variables(list_node *, first, rhs.first); swap_variables(uint, elements, rhs.elements); rhs.last= last == &first ? &rhs.first : last; last = rhs_last == &rhs.first ? &first : rhs_last; } inline list_node* last_node() { return *last; } inline list_node* first_node() { return first;} inline void *head() { return first->info; } inline void **head_ref() { return first != &end_of_list ? &first->info : 0; } inline bool is_empty() { return first == &end_of_list ; } inline list_node *last_ref() { return &end_of_list; } template inline bool add_unique(T *info, bool (*eq)(T *a, T *b)) { list_node *node= first; for (; node != &end_of_list && (!(*eq)(static_cast(node->info), info)); node= node->next) ; if (node == &end_of_list) return push_back(info); return 1; } friend class base_list_iterator; friend class error_list; friend class error_list_iterator; /* Return N-th element in the list, or NULL if the list has less than N elements. */ void *elem(uint n) { list_node *node= first; void *data= NULL; for (uint i= 0; i <= n; i++) { if (node == &end_of_list) { data= NULL; break; } data= node->info; node= node->next; } return data; } #ifdef LIST_EXTRA_DEBUG /* Check list invariants and print results into trace. Invariants are: - (*last) points to end_of_list - There are no NULLs in the list. - base_list::elements is the number of elements in the list. SYNOPSIS check_list() name Name to print to trace file RETURN 1 The list is Ok. 0 List invariants are not met. */ bool check_list(const char *name) { base_list *list= this; list_node *node= first; uint cnt= 0; while (node->next != &end_of_list) { if (!node->info) { DBUG_PRINT("list_invariants",("%s: error: NULL element in the list", name)); return FALSE; } node= node->next; cnt++; } if (last != &(node->next)) { DBUG_PRINT("list_invariants", ("%s: error: wrong last pointer", name)); return FALSE; } if (cnt+1 != elements) { DBUG_PRINT("list_invariants", ("%s: error: wrong element count", name)); return FALSE; } DBUG_PRINT("list_invariants", ("%s: list is ok", name)); return TRUE; } #endif // LIST_EXTRA_DEBUG protected: void after(const void *info, list_node *node) { list_node *new_node=new list_node(info,node->next); node->next=new_node; elements++; if (last == &(node->next)) last= &new_node->next; } }; class base_list_iterator { protected: base_list *list; list_node **el,**prev,*current; void sublist(base_list &ls, uint elm) { ls.first= *el; ls.last= list->last; ls.elements= elm; } public: base_list_iterator() :list(0), el(0), prev(0), current(0) {} base_list_iterator(base_list &list_par) { init(list_par); } inline void init(base_list &list_par) { list= &list_par; el= &list_par.first; prev= 0; current= 0; } inline void *next(void) { prev=el; current= *el; el= ¤t->next; return current->info; } /* Get what calling next() would return, without moving the iterator */ inline void *peek() { return (*el)->info; } inline void *next_fast(void) { list_node *tmp; tmp= *el; el= &tmp->next; return tmp->info; } inline void rewind(void) { el= &list->first; } inline void *replace(const void *element) { // Return old element void *tmp=current->info; DBUG_ASSERT(current->info != 0); current->info= const_cast(element); return tmp; } void *replace(base_list &new_list) { void *ret_value=current->info; if (!new_list.is_empty()) { *new_list.last=current->next; current->info=new_list.first->info; current->next=new_list.first->next; if ((list->last == ¤t->next) && (new_list.elements > 1)) list->last= new_list.last; list->elements+=new_list.elements-1; } return ret_value; // return old element } inline void remove(void) // Remove current { list->remove(prev); el=prev; current=0; // Safeguard } void after(const void *element) // Insert element after current { list->after(element,current); current=current->next; el= ¤t->next; } inline void **ref(void) // Get reference pointer { return ¤t->info; } inline bool is_last(void) { return el == &list->last_ref()->next; } inline bool at_end() { return current == &end_of_list; } friend class error_list_iterator; }; template class List :public base_list { public: inline List() :base_list() {} inline List(const List &tmp, MEM_ROOT *mem_root) : base_list(tmp, mem_root) {} inline bool push_back(T *a) { return base_list::push_back(a); } inline bool push_back(T *a, MEM_ROOT *mem_root) { return base_list::push_back((void*) a, mem_root); } inline bool push_front(T *a) { return base_list::push_front(a); } inline bool push_front(T *a, MEM_ROOT *mem_root) { return base_list::push_front((void*) a, mem_root); } inline T* head() {return (T*) base_list::head(); } inline T** head_ref() {return (T**) base_list::head_ref(); } inline T* pop() {return (T*) base_list::pop(); } inline void append(List *list) { base_list::append(list); } inline void prepend(List *list) { base_list::prepend(list); } inline void disjoin(List *list) { base_list::disjoin(list); } inline bool add_unique(T *a, bool (*eq)(T *a, T *b)) { return base_list::add_unique(a, eq); } inline bool copy(const List *list, MEM_ROOT *root) { return base_list::copy(list, root); } void delete_elements(void) { list_node *element,*next; for (element=first; element != &end_of_list; element=next) { next=element->next; delete (T*) element->info; } empty(); } T *elem(uint n) { return (T*) base_list::elem(n); } // Create a new list with one element static List *make(MEM_ROOT *mem_root, T *first) { List *res= new (mem_root) List; return res == NULL || res->push_back(first, mem_root) ? NULL : res; } class Iterator; using value_type= T; using iterator= Iterator; iterator begin() const { return iterator(first); } iterator end() const { return iterator(); } class Iterator { public: using iterator_category= std::forward_iterator_tag; using value_type= T; using difference_type= std::ptrdiff_t; using pointer= T *; using reference= T &; Iterator(list_node *p= &end_of_list) : node{p} {} Iterator &operator++() { DBUG_ASSERT(node != &end_of_list); node= node->next; return *this; } Iterator operator++(int) { Iterator tmp(*this); operator++(); return tmp; } T &operator*() { return *static_cast(node->info); } T *operator->() { return static_cast(node->info); } bool operator==(const typename List::iterator &rhs) { return node == rhs.node; } bool operator!=(const typename List::iterator &rhs) { return node != rhs.node; } private: list_node *node{&end_of_list}; }; }; template class List_iterator :public base_list_iterator { public: List_iterator(List &a) : base_list_iterator(a) {} List_iterator() : base_list_iterator() {} inline void init(List &a) { base_list_iterator::init(a); } inline T* operator++(int) { return (T*) base_list_iterator::next(); } inline T* peek() { return (T*) base_list_iterator::peek(); } inline T *replace(T *a) { return (T*) base_list_iterator::replace(a); } inline T *replace(List &a) { return (T*) base_list_iterator::replace(a); } inline void rewind(void) { base_list_iterator::rewind(); } inline void remove() { base_list_iterator::remove(); } inline void after(T *a) { base_list_iterator::after(a); } inline T** ref(void) { return (T**) base_list_iterator::ref(); } }; template class List_iterator_fast :public base_list_iterator { protected: inline T *replace(T *) { return (T*) 0; } inline T *replace(List &) { return (T*) 0; } inline void remove(void) {} inline void after(T *) {} inline T** ref(void) { return (T**) 0; } public: inline List_iterator_fast(List &a) : base_list_iterator(a) {} inline List_iterator_fast() : base_list_iterator() {} inline void init(List &a) { base_list_iterator::init(a); } inline T* operator++(int) { return (T*) base_list_iterator::next_fast(); } inline void rewind(void) { base_list_iterator::rewind(); } void sublist(List &list_arg, uint el_arg) { base_list_iterator::sublist(list_arg, el_arg); } }; /* Bubble sort algorithm for List. This sort function is supposed to be used only for very short list. Currently it is used for the lists of Item_equal objects and for some lists in the table elimination algorithms. In both cases the sorted lists are very short. */ template inline void bubble_sort(List *list_to_sort, int (*sort_func)(T *a, T *b, void *arg), void *arg) { bool swap; T **ref1= 0; T **ref2= 0; List_iterator it(*list_to_sort); do { T **last_ref= ref1; T *item1= it++; ref1= it.ref(); T *item2; swap= FALSE; while ((item2= it++) && (ref2= it.ref()) != last_ref) { if (sort_func(item1, item2, arg) > 0) { *ref1= item2; *ref2= item1; swap= TRUE; } else item1= item2; ref1= ref2; } it.rewind(); } while (swap); } /* A simple intrusive list which automaticly removes element from list on delete (for THD element) */ struct ilink { struct ilink **prev,*next; static void *operator new(size_t size) throw () { return (void*)my_malloc(PSI_INSTRUMENT_ME, (uint)size, MYF(MY_WME | MY_FAE | ME_FATAL)); } static void operator delete(void* ptr_arg, size_t) { my_free(ptr_arg); } inline ilink() { prev=0; next=0; } inline void unlink() { /* Extra tests because element doesn't have to be linked */ if (prev) *prev= next; if (next) next->prev=prev; prev=0 ; next=0; } inline void assert_linked() { DBUG_ASSERT(prev != 0 && next != 0); } inline void assert_not_linked() { DBUG_ASSERT(prev == 0 && next == 0); } virtual ~ilink() { unlink(); } /*lint -e1740 */ }; /* Needed to be able to have an I_List of char* strings in mysqld.cc. */ class i_string: public ilink { public: const char* ptr; i_string():ptr(0) { } i_string(const char* s) : ptr(s) {} }; /* needed for linked list of two strings for replicate-rewrite-db */ class i_string_pair: public ilink { public: const char* key; const char* val; i_string_pair():key(0),val(0) { } i_string_pair(const char* key_arg, const char* val_arg) : key(key_arg),val(val_arg) {} }; template class I_List_iterator; class base_ilist { struct ilink *first; struct ilink last; public: inline void empty() { first= &last; last.prev= &first; } base_ilist() { empty(); } inline bool is_empty() { return first == &last; } // Returns true if p is the last "real" object in the list, // i.e. p->next points to the sentinel. inline bool is_last(ilink *p) { return p->next == NULL || p->next == &last; } inline void append(ilink *a) { first->prev= &a->next; a->next=first; a->prev= &first; first=a; } inline void push_back(ilink *a) { *last.prev= a; a->next= &last; a->prev= last.prev; last.prev= &a->next; } inline struct ilink *get() { struct ilink *first_link=first; if (first_link == &last) return 0; first_link->unlink(); // Unlink from list return first_link; } inline struct ilink *head() { return (first != &last) ? first : 0; } /** Moves list elements to new owner, and empties current owner (i.e. this). @param[in,out] new_owner The new owner of the list elements. Should be empty in input. */ void move_elements_to(base_ilist *new_owner) { DBUG_ASSERT(new_owner->is_empty()); new_owner->first= first; new_owner->last= last; empty(); } friend class base_ilist_iterator; private: /* We don't want to allow copying of this class, as that would give us two list heads containing the same elements. So we declare, but don't define copy CTOR and assignment operator. */ base_ilist(const base_ilist&); void operator=(const base_ilist&); }; class base_ilist_iterator { base_ilist *list; struct ilink **el; protected: struct ilink *current; public: base_ilist_iterator(base_ilist &list_par) :list(&list_par), el(&list_par.first),current(0) {} void *next(void) { /* This is coded to allow push_back() while iterating */ current= *el; if (current == &list->last) return 0; el= ¤t->next; return current; } /* Unlink element returned by last next() call */ inline void unlink(void) { struct ilink **tmp= current->prev; current->unlink(); el= tmp; } }; template class I_List :private base_ilist { public: I_List() :base_ilist() {} inline bool is_last(T *p) { return base_ilist::is_last(p); } inline void empty() { base_ilist::empty(); } inline bool is_empty() { return base_ilist::is_empty(); } inline void append(T* a) { base_ilist::append(a); } inline void push_back(T* a) { base_ilist::push_back(a); } inline T* get() { return (T*) base_ilist::get(); } inline T* head() { return (T*) base_ilist::head(); } inline void move_elements_to(I_List* new_owner) { base_ilist::move_elements_to(new_owner); } #ifndef _lint friend class I_List_iterator; #endif }; template class I_List_iterator :public base_ilist_iterator { public: I_List_iterator(I_List &a) : base_ilist_iterator(a) {} inline T* operator++(int) { return (T*) base_ilist_iterator::next(); } /* Remove element returned by last next() call */ inline void remove(void) { unlink(); delete (T*) current; current= 0; // Safety } }; /** Make a deep copy of each list element. @note A template function and not a template method of class List is employed because of explicit template instantiation: in server code there are explicit instantiations of List and an explicit instantiation of a template requires that any method of the instantiated class used in the template can be resolved. Evidently not all template arguments have clone() method with the right signature. @return You must query the error state in THD for out-of-memory situation after calling this function. */ template inline void list_copy_and_replace_each_value(List &list, MEM_ROOT *mem_root) { /* Make a deep copy of each element */ List_iterator it(list); T *el; while ((el= it++)) it.replace(el->clone(mem_root)); } void free_list(I_List *list); void free_list(I_List *list); #endif // INCLUDES_MYSQL_SQL_LIST_H mysql/server/private/sql_audit.h000064400000033167151027430560013044 0ustar00#ifndef SQL_AUDIT_INCLUDED #define SQL_AUDIT_INCLUDED /* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include #include "sql_class.h" extern unsigned long mysql_global_audit_mask[]; extern void mysql_audit_initialize(); extern void mysql_audit_finalize(); extern void mysql_audit_init_thd(THD *thd); extern void mysql_audit_free_thd(THD *thd); extern void mysql_audit_acquire_plugins(THD *thd, ulong *event_class_mask); #ifndef EMBEDDED_LIBRARY extern void mysql_audit_notify(THD *thd, uint event_class, const void *event); static inline bool mysql_audit_general_enabled() { return mysql_global_audit_mask[0] & MYSQL_AUDIT_GENERAL_CLASSMASK; } static inline bool mysql_audit_connection_enabled() { return mysql_global_audit_mask[0] & MYSQL_AUDIT_CONNECTION_CLASSMASK; } static inline bool mysql_audit_table_enabled() { return mysql_global_audit_mask[0] & MYSQL_AUDIT_TABLE_CLASSMASK; } #else static inline void mysql_audit_notify(THD *thd, uint event_class, const void *event) {} #define mysql_audit_general_enabled() 0 #define mysql_audit_connection_enabled() 0 #define mysql_audit_table_enabled() 0 #endif extern my_bool mysql_audit_release_required(THD *thd); extern void mysql_audit_release(THD *thd); static inline unsigned int strlen_uint(const char *s) { return (uint)strlen(s); } static inline unsigned int safe_strlen_uint(const char *s) { return (uint)safe_strlen(s); } #define MAX_USER_HOST_SIZE 512 static inline uint make_user_name(THD *thd, char *buf) { const Security_context *sctx= thd->security_ctx; char *end= strxnmov(buf, MAX_USER_HOST_SIZE, sctx->priv_user[0] ? sctx->priv_user : "", "[", sctx->user ? sctx->user : "", "] @ ", sctx->host ? sctx->host : "", " [", sctx->ip ? sctx->ip : "", "]", NullS); return (uint)(end-buf); } /** Call audit plugins of GENERAL audit class, MYSQL_AUDIT_GENERAL_LOG subtype. @param[in] thd @param[in] time time that event occurred @param[in] user User name @param[in] userlen User name length @param[in] cmd Command name @param[in] cmdlen Command name length @param[in] query Query string @param[in] querylen Query string length */ static inline void mysql_audit_general_log(THD *thd, time_t time, const char *user, uint userlen, const char *cmd, uint cmdlen, const char *query, uint querylen) { if (mysql_audit_general_enabled()) { mysql_event_general event; event.event_subclass= MYSQL_AUDIT_GENERAL_LOG; event.general_error_code= 0; event.general_time= time; event.general_user= user; event.general_user_length= userlen; event.general_command= cmd; event.general_command_length= cmdlen; event.general_query= query; event.general_query_length= querylen; event.general_rows= 0; if (thd) { event.general_thread_id= (unsigned long)thd->thread_id; event.general_charset= thd->variables.character_set_client; event.database= thd->db; event.query_id= thd->query_id; } else { event.general_thread_id= 0; event.general_charset= global_system_variables.character_set_client; event.database= null_clex_str; event.query_id= 0; } mysql_audit_notify(thd, MYSQL_AUDIT_GENERAL_CLASS, &event); } } /** Call audit plugins of GENERAL audit class. event_subtype should be set to one of: MYSQL_AUDIT_GENERAL_ERROR MYSQL_AUDIT_GENERAL_RESULT MYSQL_AUDIT_GENERAL_STATUS @param[in] thd @param[in] event_subtype Type of general audit event. @param[in] error_code Error code @param[in] msg Message */ static inline void mysql_audit_general(THD *thd, uint event_subtype, int error_code, const char *msg) { DBUG_ENTER("mysql_audit_general"); if (mysql_audit_general_enabled()) { char user_buff[MAX_USER_HOST_SIZE+1]; mysql_event_general event; event.event_subclass= event_subtype; event.general_error_code= error_code; event.general_time= my_time(0); event.general_command= msg; event.general_command_length= safe_strlen_uint(msg); if (thd) { event.general_user= user_buff; event.general_user_length= make_user_name(thd, user_buff); event.general_thread_id= (unsigned long)thd->thread_id; event.general_query= thd->query_string.str(); event.general_query_length= (unsigned) thd->query_string.length(); event.general_charset= thd->query_string.charset(); event.general_rows= thd->get_stmt_da()->current_row_for_warning(); event.database= thd->db; event.query_id= thd->query_id; } else { event.general_user= NULL; event.general_user_length= 0; event.general_thread_id= 0; event.general_query= NULL; event.general_query_length= 0; event.general_charset= &my_charset_bin; event.general_rows= 0; event.database= null_clex_str; event.query_id= 0; } mysql_audit_notify(thd, MYSQL_AUDIT_GENERAL_CLASS, &event); } DBUG_VOID_RETURN; } static inline void mysql_audit_notify_connection_connect(THD *thd) { if (mysql_audit_connection_enabled()) { const Security_context *sctx= thd->security_ctx; mysql_event_connection event; event.event_subclass= MYSQL_AUDIT_CONNECTION_CONNECT; event.status= thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0; event.thread_id= (unsigned long)thd->thread_id; event.user= sctx->user; event.user_length= safe_strlen_uint(sctx->user); event.priv_user= sctx->priv_user; event.priv_user_length= strlen_uint(sctx->priv_user); event.external_user= sctx->external_user; event.external_user_length= safe_strlen_uint(sctx->external_user); event.proxy_user= sctx->proxy_user; event.proxy_user_length= strlen_uint(sctx->proxy_user); event.host= sctx->host; event.host_length= safe_strlen_uint(sctx->host); event.ip= sctx->ip; event.ip_length= safe_strlen_uint(sctx->ip); event.database= thd->db; mysql_audit_notify(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event); } } static inline void mysql_audit_notify_connection_disconnect(THD *thd, int errcode) { if (mysql_audit_connection_enabled()) { const Security_context *sctx= thd->security_ctx; mysql_event_connection event; event.event_subclass= MYSQL_AUDIT_CONNECTION_DISCONNECT; event.status= errcode; event.thread_id= (unsigned long)thd->thread_id; event.user= sctx->user; event.user_length= safe_strlen_uint(sctx->user); event.priv_user= sctx->priv_user; event.priv_user_length= strlen_uint(sctx->priv_user); event.external_user= sctx->external_user; event.external_user_length= safe_strlen_uint(sctx->external_user); event.proxy_user= sctx->proxy_user; event.proxy_user_length= strlen_uint(sctx->proxy_user); event.host= sctx->host; event.host_length= safe_strlen_uint(sctx->host); event.ip= sctx->ip; event.ip_length= safe_strlen_uint(sctx->ip) ; event.database= thd->db; mysql_audit_notify(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event); } } static inline void mysql_audit_notify_connection_change_user(THD *thd, const Security_context *old_ctx) { if (mysql_audit_connection_enabled()) { mysql_event_connection event; event.event_subclass= MYSQL_AUDIT_CONNECTION_CHANGE_USER; event.status= thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0; event.thread_id= (unsigned long)thd->thread_id; event.user= old_ctx->user; event.user_length= safe_strlen_uint(old_ctx->user); event.priv_user= old_ctx->priv_user; event.priv_user_length= strlen_uint(old_ctx->priv_user); event.external_user= old_ctx->external_user; event.external_user_length= safe_strlen_uint(old_ctx->external_user); event.proxy_user= old_ctx->proxy_user; event.proxy_user_length= strlen_uint(old_ctx->proxy_user); event.host= old_ctx->host; event.host_length= safe_strlen_uint(old_ctx->host); event.ip= old_ctx->ip; event.ip_length= safe_strlen_uint(old_ctx->ip); event.database= thd->db; mysql_audit_notify(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event); } } static inline void mysql_audit_external_lock_ex(THD *thd, my_thread_id thread_id, const char *user, const char *host, const char *ip, query_id_t query_id, TABLE_SHARE *share, int lock) { if (lock != F_UNLCK && mysql_audit_table_enabled()) { const Security_context *sctx= thd->security_ctx; mysql_event_table event; event.event_subclass= MYSQL_AUDIT_TABLE_LOCK; event.read_only= lock == F_RDLCK; event.thread_id= (unsigned long)thread_id; event.user= user; event.priv_user= sctx->priv_user; event.priv_host= sctx->priv_host; event.external_user= sctx->external_user; event.proxy_user= sctx->proxy_user; event.host= host; event.ip= ip; event.database= share->db; event.table= share->table_name; event.new_database= null_clex_str; event.new_table= null_clex_str; event.query_id= query_id; mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); } } static inline void mysql_audit_external_lock(THD *thd, TABLE_SHARE *share, int lock) { mysql_audit_external_lock_ex(thd, thd->thread_id, thd->security_ctx->user, thd->security_ctx->host, thd->security_ctx->ip, thd->query_id, share, lock); } static inline void mysql_audit_create_table(TABLE *table) { if (mysql_audit_table_enabled()) { THD *thd= table->in_use; const TABLE_SHARE *share= table->s; const Security_context *sctx= thd->security_ctx; mysql_event_table event; event.event_subclass= MYSQL_AUDIT_TABLE_CREATE; event.read_only= 0; event.thread_id= (unsigned long)thd->thread_id; event.user= sctx->user; event.priv_user= sctx->priv_user; event.priv_host= sctx->priv_host; event.external_user= sctx->external_user; event.proxy_user= sctx->proxy_user; event.host= sctx->host; event.ip= sctx->ip; event.database= share->db; event.table= share->table_name; event.new_database= null_clex_str; event.new_table= null_clex_str; event.query_id= thd->query_id; mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); } } static inline void mysql_audit_drop_table(THD *thd, TABLE_LIST *table) { if (mysql_audit_table_enabled()) { const Security_context *sctx= thd->security_ctx; mysql_event_table event; event.event_subclass= MYSQL_AUDIT_TABLE_DROP; event.read_only= 0; event.thread_id= (unsigned long)thd->thread_id; event.user= sctx->user; event.priv_user= sctx->priv_user; event.priv_host= sctx->priv_host; event.external_user= sctx->external_user; event.proxy_user= sctx->proxy_user; event.host= sctx->host; event.ip= sctx->ip; event.database= table->db; event.table= table->table_name; event.new_database= null_clex_str; event.new_table= null_clex_str; event.query_id= thd->query_id; mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); } } static inline void mysql_audit_rename_table(THD *thd, const LEX_CSTRING *old_db, const LEX_CSTRING *old_tb, const LEX_CSTRING *new_db, const LEX_CSTRING *new_tb) { if (mysql_audit_table_enabled()) { const Security_context *sctx= thd->security_ctx; mysql_event_table event; event.event_subclass= MYSQL_AUDIT_TABLE_RENAME; event.read_only= 0; event.thread_id= (unsigned long)thd->thread_id; event.user= sctx->user; event.priv_user= sctx->priv_user; event.priv_host= sctx->priv_host; event.external_user= sctx->external_user; event.proxy_user= sctx->proxy_user; event.host= sctx->host; event.ip= sctx->ip; event.database= *old_db; event.table= *old_tb; event.new_database= *new_db; event.new_table= *new_tb; event.query_id= thd->query_id; mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); } } static inline void mysql_audit_alter_table(THD *thd, TABLE_LIST *table) { if (mysql_audit_table_enabled()) { const Security_context *sctx= thd->security_ctx; mysql_event_table event; event.event_subclass= MYSQL_AUDIT_TABLE_ALTER; event.read_only= 0; event.thread_id= (unsigned long)thd->thread_id; event.user= sctx->user; event.priv_user= sctx->priv_user; event.priv_host= sctx->priv_host; event.external_user= sctx->external_user; event.proxy_user= sctx->proxy_user; event.host= sctx->host; event.ip= sctx->ip; event.database= table->db; event.table= table->table_name; event.new_database= null_clex_str; event.new_table= null_clex_str; event.query_id= thd->query_id; mysql_audit_notify(thd, MYSQL_AUDIT_TABLE_CLASS, &event); } } #endif /* SQL_AUDIT_INCLUDED */ mysql/server/private/filesort.h000064400000016163151027430560012703 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef FILESORT_INCLUDED #define FILESORT_INCLUDED #include "my_base.h" /* ha_rows */ #include "sql_alloc.h" #include "filesort_utils.h" class SQL_SELECT; class THD; struct TABLE; class Filesort_tracker; struct SORT_FIELD; struct SORT_FIELD_ATTR; typedef struct st_order ORDER; class JOIN; class Addon_fields; class Sort_keys; /** Sorting related info. To be extended by another WL to include complete filesort implementation. */ class Filesort: public Sql_alloc { public: /** List of expressions to order the table by */ ORDER *order; /** Number of records to return */ ha_rows limit; /** ORDER BY list with some precalculated info for filesort */ SORT_FIELD *sortorder; /* Used with ROWNUM. Contains the number of rows filesort has found so far */ ha_rows *accepted_rows; /** select to use for getting records */ SQL_SELECT *select; /** TRUE <=> free select on destruction */ bool own_select; /** TRUE means we are using Priority Queue for order by with limit. */ bool using_pq; /* TRUE means sort operation must produce table rowids. FALSE means that it also has an option of producing {sort_key, addon_fields} pairs. Usually initialized with value of join_tab->keep_current_rowid to allow for a call to table->file->position() using these table rowids. */ bool sort_positions; /* TRUE means all the fields of table of whose bitmap read_set is set need to be read while reading records in the sort buffer. FALSE otherwise */ bool set_all_read_bits; Filesort_tracker *tracker; Sort_keys *sort_keys; /* Unpack temp table columns to base table columns*/ void (*unpack)(TABLE *); Filesort(ORDER *order_arg, ha_rows limit_arg, bool sort_positions_arg, SQL_SELECT *select_arg): order(order_arg), limit(limit_arg), sortorder(NULL), accepted_rows(0), select(select_arg), own_select(false), using_pq(false), sort_positions(sort_positions_arg), set_all_read_bits(false), sort_keys(NULL), unpack(NULL) { DBUG_ASSERT(order); }; ~Filesort() { cleanup(); } /* Prepare ORDER BY list for sorting. */ Sort_keys* make_sortorder(THD *thd, JOIN *join, table_map first_table_bit); private: void cleanup(); }; class SORT_INFO { /// Buffer for sorting keys. Filesort_buffer filesort_buffer; public: SORT_INFO() :addon_fields(NULL), record_pointers(0), sort_keys(NULL), sorted_result_in_fsbuf(FALSE) { buffpek.str= 0; my_b_clear(&io_cache); } ~SORT_INFO(); void free_data() { close_cached_file(&io_cache); free_addon_buff(); my_free(record_pointers); my_free(buffpek.str); my_free(addon_fields); free_sort_buffer(); } void reset() { free_data(); record_pointers= 0; buffpek.str= 0; addon_fields= 0; sorted_result_in_fsbuf= false; } void free_addon_buff(); IO_CACHE io_cache; /* If sorted through filesort */ LEX_STRING buffpek; /* Buffer for buffpek structures */ Addon_fields *addon_fields; /* Addon field descriptors */ uchar *record_pointers; /* If sorted in memory */ Sort_keys *sort_keys; /* Sort key descriptors*/ /** If the entire result of filesort fits in memory, we skip the merge phase. We may leave the result in filesort_buffer (indicated by sorted_result_in_fsbuf), or we may strip away the sort keys, and copy the sorted result into a new buffer. @see save_index() */ bool sorted_result_in_fsbuf; /* How many rows in final result. Also how many rows in record_pointers, if used */ ha_rows return_rows; ha_rows examined_rows; /* How many rows read */ ha_rows found_rows; /* How many rows was accepted */ /** Sort filesort_buffer */ void sort_buffer(Sort_param *param, uint count) { filesort_buffer.sort_buffer(param, count); } uchar **get_sort_keys() { return filesort_buffer.get_sort_keys(); } uchar *get_sorted_record(uint ix) { return filesort_buffer.get_sorted_record(ix); } uchar *alloc_sort_buffer(uint num_records, uint record_length) { return filesort_buffer.alloc_sort_buffer(num_records, record_length); } void free_sort_buffer() { filesort_buffer.free_sort_buffer(); } bool isfull() const { return filesort_buffer.isfull(); } void init_record_pointers() { filesort_buffer.init_record_pointers(); } void init_next_record_pointer() { filesort_buffer.init_next_record_pointer(); } uchar *get_next_record_pointer() { return filesort_buffer.get_next_record_pointer(); } void adjust_next_record_pointer(uint val) { filesort_buffer.adjust_next_record_pointer(val); } Bounds_checked_array get_raw_buf() { return filesort_buffer.get_raw_buf(); } size_t sort_buffer_size() const { return filesort_buffer.sort_buffer_size(); } bool is_allocated() const { return filesort_buffer.is_allocated(); } void set_sort_length(uint val) { filesort_buffer.set_sort_length(val); } uint get_sort_length() const { return filesort_buffer.get_sort_length(); } bool has_filesort_result_in_memory() const { return record_pointers || sorted_result_in_fsbuf; } /// Are we using "addon fields"? bool using_addon_fields() const { return addon_fields != NULL; } /// Are we using "packed addon fields"? bool using_packed_addons(); /** Copies (unpacks) values appended to sorted fields from a buffer back to their regular positions specified by the Field::ptr pointers. @param buff Buffer which to unpack the value from */ template inline void unpack_addon_fields(uchar *buff); bool using_packed_sortkeys(); friend SORT_INFO *filesort(THD *thd, TABLE *table, Filesort *filesort, Filesort_tracker* tracker, JOIN *join, table_map first_table_bit); }; SORT_INFO *filesort(THD *thd, TABLE *table, Filesort *filesort, Filesort_tracker* tracker, JOIN *join=NULL, table_map first_table_bit=0); bool filesort_use_addons(TABLE *table, uint sortlength, uint *length, uint *fields, uint *null_fields, uint *m_packable_length); void change_double_for_sort(double nr,uchar *to); void store_length(uchar *to, uint length, uint pack_length); void reverse_key(uchar *to, const SORT_FIELD_ATTR *sort_field); #endif /* FILESORT_INCLUDED */ mysql/server/private/wsrep_high_priority_service.h000064400000011460151027430560016667 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_HIGH_PRIORITY_SERVICE_H #define WSREP_HIGH_PRIORITY_SERVICE_H #include "wsrep/high_priority_service.hpp" #include "my_global.h" #include "sql_error.h" /* Diagnostics area */ #include "sql_class.h" /* rpl_group_info */ class THD; class Relay_log_info; class Wsrep_server_service; class Wsrep_high_priority_service : public wsrep::high_priority_service, public wsrep::high_priority_context { public: Wsrep_high_priority_service(THD*); ~Wsrep_high_priority_service(); int start_transaction(const wsrep::ws_handle&, const wsrep::ws_meta&) override; int next_fragment(const wsrep::ws_meta&) override; const wsrep::transaction& transaction() const override; int adopt_transaction(const wsrep::transaction&) override; int apply_write_set(const wsrep::ws_meta&, const wsrep::const_buffer&, wsrep::mutable_buffer&) override = 0; int append_fragment_and_commit(const wsrep::ws_handle&, const wsrep::ws_meta&, const wsrep::const_buffer&, const wsrep::xid&) override; int remove_fragments(const wsrep::ws_meta&) override; int commit(const wsrep::ws_handle&, const wsrep::ws_meta&) override; int rollback(const wsrep::ws_handle&, const wsrep::ws_meta&) override; int apply_toi(const wsrep::ws_meta&, const wsrep::const_buffer&, wsrep::mutable_buffer&) override; void store_globals() override; void reset_globals() override; void switch_execution_context(wsrep::high_priority_service&) override; int log_dummy_write_set(const wsrep::ws_handle&, const wsrep::ws_meta&, wsrep::mutable_buffer&) override; void adopt_apply_error(wsrep::mutable_buffer&) override; virtual bool check_exit_status() const = 0; void debug_crash(const char*) override; protected: friend Wsrep_server_service; THD* m_thd; Relay_log_info* m_rli; rpl_group_info* m_rgi; struct shadow { ulonglong option_bits; uint server_status; struct st_vio* vio; ulong tx_isolation; char* db; size_t db_length; //struct timeval user_time; my_hrtime_t user_time; longlong row_count_func; bool wsrep_applier; } m_shadow; }; class Wsrep_applier_service : public Wsrep_high_priority_service { public: Wsrep_applier_service(THD*); ~Wsrep_applier_service(); int apply_write_set(const wsrep::ws_meta&, const wsrep::const_buffer&, wsrep::mutable_buffer&) override; int apply_nbo_begin(const wsrep::ws_meta&, const wsrep::const_buffer& data, wsrep::mutable_buffer& err) override; void after_apply() override; bool is_replaying() const override { return false; } bool check_exit_status() const override; }; class Wsrep_replayer_service : public Wsrep_high_priority_service { public: Wsrep_replayer_service(THD* replayer_thd, THD* orig_thd); ~Wsrep_replayer_service(); int apply_write_set(const wsrep::ws_meta&, const wsrep::const_buffer&, wsrep::mutable_buffer&) override; int apply_nbo_begin(const wsrep::ws_meta&, const wsrep::const_buffer& data, wsrep::mutable_buffer& err) override { DBUG_ASSERT(0); /* DDL should never cause replaying */ return 0; } void after_apply() override { } bool is_replaying() const override { return true; } void replay_status(enum wsrep::provider::status status) { m_replay_status = status; } enum wsrep::provider::status replay_status() const { return m_replay_status; } /* Replayer should never be forced to exit */ bool check_exit_status() const override { return false; } private: THD* m_orig_thd; struct da_shadow { enum Diagnostics_area::enum_diagnostics_status status; ulonglong affected_rows; ulonglong last_insert_id; char message[MYSQL_ERRMSG_SIZE]; da_shadow() : status() , affected_rows() , last_insert_id() , message() { } } m_da_shadow; enum wsrep::provider::status m_replay_status; }; #endif /* WSREP_HIGH_PRIORITY_SERVICE_H */ mysql/server/private/lf.h000064400000014476151027430560011462 0ustar00/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef INCLUDE_LF_INCLUDED #define INCLUDE_LF_INCLUDED #include C_MODE_START /* wait-free dynamic array, see lf_dynarray.c 4 levels of 256 elements each mean 4311810304 elements in an array - it should be enough for a while */ #define LF_DYNARRAY_LEVEL_LENGTH 256 #define LF_DYNARRAY_LEVELS 4 typedef struct { void * volatile level[LF_DYNARRAY_LEVELS]; uint size_of_element; } LF_DYNARRAY; typedef int (*lf_dynarray_func)(void *, void *); void lf_dynarray_init(LF_DYNARRAY *array, uint element_size); void lf_dynarray_destroy(LF_DYNARRAY *array); void *lf_dynarray_value(LF_DYNARRAY *array, uint idx); void *lf_dynarray_lvalue(LF_DYNARRAY *array, uint idx); int lf_dynarray_iterate(LF_DYNARRAY *array, lf_dynarray_func func, void *arg); /* pin manager for memory allocator, lf_alloc-pin.c */ #define LF_PINBOX_PINS 4 #define LF_PURGATORY_SIZE 100 typedef void lf_pinbox_free_func(void *, void *, void*); typedef struct { LF_DYNARRAY pinarray; lf_pinbox_free_func *free_func; void *free_func_arg; uint free_ptr_offset; uint32 volatile pinstack_top_ver; /* this is a versioned pointer */ uint32 volatile pins_in_array; /* number of elements in array */ } LF_PINBOX; typedef struct { void * volatile pin[LF_PINBOX_PINS]; LF_PINBOX *pinbox; void *purgatory; uint32 purgatory_count; uint32 volatile link; /* avoid false sharing */ char pad[CPU_LEVEL1_DCACHE_LINESIZE]; } LF_PINS; /* compile-time assert to make sure we have enough pins. */ #define lf_pin(PINS, PIN, ADDR) \ do { \ compile_time_assert(PIN < LF_PINBOX_PINS); \ my_atomic_storeptr(&(PINS)->pin[PIN], (ADDR)); \ } while(0) #define lf_unpin(PINS, PIN) lf_pin(PINS, PIN, NULL) #define lf_assert_pin(PINS, PIN) assert((PINS)->pin[PIN] != 0) #define lf_assert_unpin(PINS, PIN) assert((PINS)->pin[PIN] == 0) void lf_pinbox_init(LF_PINBOX *pinbox, uint free_ptr_offset, lf_pinbox_free_func *free_func, void * free_func_arg); void lf_pinbox_destroy(LF_PINBOX *pinbox); LF_PINS *lf_pinbox_get_pins(LF_PINBOX *pinbox); void lf_pinbox_put_pins(LF_PINS *pins); void lf_pinbox_free(LF_PINS *pins, void *addr); /* memory allocator, lf_alloc-pin.c */ typedef struct st_lf_allocator { LF_PINBOX pinbox; uchar * volatile top; uint element_size; uint32 volatile mallocs; void (*constructor)(uchar *); /* called, when an object is malloc()'ed */ void (*destructor)(uchar *); /* called, when an object is free()'d */ } LF_ALLOCATOR; void lf_alloc_init(LF_ALLOCATOR *allocator, uint size, uint free_ptr_offset); void lf_alloc_destroy(LF_ALLOCATOR *allocator); uint lf_alloc_pool_count(LF_ALLOCATOR *allocator); /* shortcut macros to access underlying pinbox functions from an LF_ALLOCATOR see lf_pinbox_get_pins() and lf_pinbox_put_pins() */ #define lf_alloc_free(PINS, PTR) lf_pinbox_free((PINS), (PTR)) #define lf_alloc_get_pins(A) lf_pinbox_get_pins(&(A)->pinbox) #define lf_alloc_put_pins(PINS) lf_pinbox_put_pins(PINS) #define lf_alloc_direct_free(ALLOC, ADDR) \ do { \ if ((ALLOC)->destructor) \ (ALLOC)->destructor((uchar*) ADDR); \ my_free(ADDR); \ } while(0) void *lf_alloc_new(LF_PINS *pins); C_MODE_END /* extendible hash, lf_hash.cc */ #include C_MODE_START typedef struct st_lf_hash LF_HASH; typedef void (*lf_hash_initializer)(LF_HASH *hash, void *dst, const void *src); #define LF_HASH_UNIQUE 1 /* lf_hash overhead per element (that is, sizeof(LF_SLIST) */ extern const int LF_HASH_OVERHEAD; struct st_lf_hash { LF_DYNARRAY array; /* hash itself */ LF_ALLOCATOR alloc; /* allocator for elements */ my_hash_get_key get_key; /* see HASH */ lf_hash_initializer initializer; /* called when an element is inserted */ my_hash_function hash_function; /* see HASH */ CHARSET_INFO *charset; /* see HASH */ uint key_offset, key_length; /* see HASH */ uint element_size; /* size of memcpy'ed area on insert */ uint flags; /* LF_HASH_UNIQUE, etc */ int32 volatile size; /* size of array */ int32 volatile count; /* number of elements in the hash */ }; void lf_hash_init(LF_HASH *hash, uint element_size, uint flags, uint key_offset, uint key_length, my_hash_get_key get_key, CHARSET_INFO *charset); void lf_hash_destroy(LF_HASH *hash); int lf_hash_insert(LF_HASH *hash, LF_PINS *pins, const void *data); void *lf_hash_search(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen); void *lf_hash_search_using_hash_value(LF_HASH *hash, LF_PINS *pins, my_hash_value_type hash_value, const void *key, uint keylen); int lf_hash_delete(LF_HASH *hash, LF_PINS *pins, const void *key, uint keylen); int lf_hash_iterate(LF_HASH *hash, LF_PINS *pins, my_hash_walk_action action, void *argument); #define lf_hash_size(hash) \ my_atomic_load32_explicit(&(hash)->count, MY_MEMORY_ORDER_RELAXED) /* shortcut macros to access underlying pinbox functions from an LF_HASH see lf_pinbox_get_pins() and lf_pinbox_put_pins() */ #define lf_hash_get_pins(HASH) lf_alloc_get_pins(&(HASH)->alloc) #define lf_hash_put_pins(PINS) lf_pinbox_put_pins(PINS) #define lf_hash_search_unpin(PINS) lf_unpin((PINS), 2) /* cleanup */ C_MODE_END #endif mysql/server/private/derror.h000064400000001724151027430560012346 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef DERROR_INCLUDED #define DERROR_INCLUDED bool init_errmessage(void); void free_error_messages(); bool read_texts(const char *file_name, const char *language, const char ****data); #endif /* DERROR_INCLUDED */ mysql/server/private/sql_partition_admin.h000064400000013464151027430560015115 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_PARTITION_ADMIN_H #define SQL_PARTITION_ADMIN_H #ifndef WITH_PARTITION_STORAGE_ENGINE /** Stub class that returns a error if the partition storage engine is not supported. */ class Sql_cmd_partition_unsupported : public Sql_cmd { public: Sql_cmd_partition_unsupported() {} ~Sql_cmd_partition_unsupported() {} /* Override SQLCOM_*, since it is an ALTER command */ virtual enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } bool execute(THD *thd) override; }; class Sql_cmd_alter_table_exchange_partition : public Sql_cmd_partition_unsupported { public: Sql_cmd_alter_table_exchange_partition() {} ~Sql_cmd_alter_table_exchange_partition() {} }; class Sql_cmd_alter_table_analyze_partition : public Sql_cmd_partition_unsupported { public: Sql_cmd_alter_table_analyze_partition() {} ~Sql_cmd_alter_table_analyze_partition() {} }; class Sql_cmd_alter_table_check_partition : public Sql_cmd_partition_unsupported { public: Sql_cmd_alter_table_check_partition() {} ~Sql_cmd_alter_table_check_partition() {} }; class Sql_cmd_alter_table_optimize_partition : public Sql_cmd_partition_unsupported { public: Sql_cmd_alter_table_optimize_partition() {} ~Sql_cmd_alter_table_optimize_partition() {} }; class Sql_cmd_alter_table_repair_partition : public Sql_cmd_partition_unsupported { public: Sql_cmd_alter_table_repair_partition() {} ~Sql_cmd_alter_table_repair_partition() {} }; class Sql_cmd_alter_table_truncate_partition : public Sql_cmd_partition_unsupported { public: Sql_cmd_alter_table_truncate_partition() {} ~Sql_cmd_alter_table_truncate_partition() {} }; #else /** Class that represents the ALTER TABLE t1 ANALYZE PARTITION p statement. */ class Sql_cmd_alter_table_exchange_partition : public Sql_cmd_common_alter_table { public: /** Constructor, used to represent a ALTER TABLE EXCHANGE PARTITION statement. */ Sql_cmd_alter_table_exchange_partition() : Sql_cmd_common_alter_table() {} ~Sql_cmd_alter_table_exchange_partition() = default; bool execute(THD *thd) override; private: bool exchange_partition(THD *thd, TABLE_LIST *, Alter_info *); }; /** Class that represents the ALTER TABLE t1 ANALYZE PARTITION p statement. */ class Sql_cmd_alter_table_analyze_partition : public Sql_cmd_analyze_table { public: /** Constructor, used to represent a ALTER TABLE ANALYZE PARTITION statement. */ Sql_cmd_alter_table_analyze_partition() : Sql_cmd_analyze_table() {} ~Sql_cmd_alter_table_analyze_partition() = default; bool execute(THD *thd) override; /* Override SQLCOM_ANALYZE, since it is an ALTER command */ enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } }; /** Class that represents the ALTER TABLE t1 CHECK PARTITION p statement. */ class Sql_cmd_alter_table_check_partition : public Sql_cmd_check_table { public: /** Constructor, used to represent a ALTER TABLE CHECK PARTITION statement. */ Sql_cmd_alter_table_check_partition() : Sql_cmd_check_table() {} ~Sql_cmd_alter_table_check_partition() = default; bool execute(THD *thd) override; /* Override SQLCOM_CHECK, since it is an ALTER command */ enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } }; /** Class that represents the ALTER TABLE t1 OPTIMIZE PARTITION p statement. */ class Sql_cmd_alter_table_optimize_partition : public Sql_cmd_optimize_table { public: /** Constructor, used to represent a ALTER TABLE OPTIMIZE PARTITION statement. */ Sql_cmd_alter_table_optimize_partition() : Sql_cmd_optimize_table() {} ~Sql_cmd_alter_table_optimize_partition() = default; bool execute(THD *thd) override; /* Override SQLCOM_OPTIMIZE, since it is an ALTER command */ enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } }; /** Class that represents the ALTER TABLE t1 REPAIR PARTITION p statement. */ class Sql_cmd_alter_table_repair_partition : public Sql_cmd_repair_table { public: /** Constructor, used to represent a ALTER TABLE REPAIR PARTITION statement. */ Sql_cmd_alter_table_repair_partition() : Sql_cmd_repair_table() {} ~Sql_cmd_alter_table_repair_partition() = default; bool execute(THD *thd) override; /* Override SQLCOM_REPAIR, since it is an ALTER command */ enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } }; /** Class that represents the ALTER TABLE t1 TRUNCATE PARTITION p statement. */ class Sql_cmd_alter_table_truncate_partition : public Sql_cmd_truncate_table { public: /** Constructor, used to represent a ALTER TABLE TRUNCATE PARTITION statement. */ Sql_cmd_alter_table_truncate_partition() = default; virtual ~Sql_cmd_alter_table_truncate_partition() = default; bool execute(THD *thd) override; /* Override SQLCOM_TRUNCATE, since it is an ALTER command */ enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } }; #endif /* WITH_PARTITION_STORAGE_ENGINE */ #endif /* SQL_PARTITION_ADMIN_H */ mysql/server/private/lex.h000064400000071601151027430560011642 0ustar00#ifndef LEX_INCLUDED #define LEX_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. Copyright (c) 2009, 2015, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file includes all reserved words and functions */ #include "lex_symbol.h" SYM_GROUP sym_group_common= {"", ""}; SYM_GROUP sym_group_geom= {"Spatial extensions", "HAVE_SPATIAL"}; SYM_GROUP sym_group_rtree= {"RTree keys", "HAVE_RTREE_KEYS"}; /* We don't want to include sql_yacc.h into gen_lex_hash */ #ifdef NO_YACC_SYMBOLS #define SYM_OR_NULL(A) 0 #else #define SYM_OR_NULL(A) A #endif #define SYM(A) SYM_OR_NULL(A),0,&sym_group_common /* Symbols are broken into separated arrays to allow field names with same name as functions. These are kept sorted for human lookup (the symbols are hashed). NOTE! The symbol tables should be the same regardless of what features are compiled into the server. Don't add ifdef'ed symbols to the lists NOTE!! If you add or delete symbols from this file, you must also update results for the perfschema.start_server_low_digest_sql_length test! */ SYMBOL symbols[] = { { "&&", SYM(AND_AND_SYM)}, { "<=", SYM(LE)}, { "<>", SYM(NE)}, { "!=", SYM(NE)}, { ">=", SYM(GE)}, { "<<", SYM(SHIFT_LEFT)}, { ">>", SYM(SHIFT_RIGHT)}, { "<=>", SYM(EQUAL_SYM)}, { "ACCESSIBLE", SYM(ACCESSIBLE_SYM)}, { "ACCOUNT", SYM(ACCOUNT_SYM)}, { "ACTION", SYM(ACTION)}, { "ADD", SYM(ADD)}, { "ADMIN", SYM(ADMIN_SYM)}, { "AFTER", SYM(AFTER_SYM)}, { "AGAINST", SYM(AGAINST)}, { "AGGREGATE", SYM(AGGREGATE_SYM)}, { "ALL", SYM(ALL)}, { "ALGORITHM", SYM(ALGORITHM_SYM)}, { "ALTER", SYM(ALTER)}, { "ALWAYS", SYM(ALWAYS_SYM)}, { "ANALYZE", SYM(ANALYZE_SYM)}, { "AND", SYM(AND_SYM)}, { "ANY", SYM(ANY_SYM)}, { "AS", SYM(AS)}, { "ASC", SYM(ASC)}, { "ASCII", SYM(ASCII_SYM)}, { "ASENSITIVE", SYM(ASENSITIVE_SYM)}, { "AT", SYM(AT_SYM)}, { "ATOMIC", SYM(ATOMIC_SYM)}, { "AUTHORS", SYM(AUTHORS_SYM)}, { "AUTO_INCREMENT", SYM(AUTO_INC)}, { "AUTOEXTEND_SIZE", SYM(AUTOEXTEND_SIZE_SYM)}, { "AVG", SYM(AVG_SYM)}, { "AVG_ROW_LENGTH", SYM(AVG_ROW_LENGTH)}, { "BACKUP", SYM(BACKUP_SYM)}, { "BEFORE", SYM(BEFORE_SYM)}, { "BEGIN", SYM(BEGIN_MARIADB_SYM)}, { "BETWEEN", SYM(BETWEEN_SYM)}, { "BIGINT", SYM(BIGINT)}, { "BINARY", SYM(BINARY)}, { "BINLOG", SYM(BINLOG_SYM)}, { "BIT", SYM(BIT_SYM)}, { "BLOB", SYM(BLOB_MARIADB_SYM)}, { "BLOCK", SYM(BLOCK_SYM)}, { "BODY", SYM(BODY_MARIADB_SYM)}, { "BOOL", SYM(BOOL_SYM)}, { "BOOLEAN", SYM(BOOLEAN_SYM)}, { "BOTH", SYM(BOTH)}, { "BTREE", SYM(BTREE_SYM)}, { "BY", SYM(BY)}, { "BYTE", SYM(BYTE_SYM)}, { "CACHE", SYM(CACHE_SYM)}, { "CALL", SYM(CALL_SYM)}, { "CASCADE", SYM(CASCADE)}, { "CASCADED", SYM(CASCADED)}, { "CASE", SYM(CASE_SYM)}, { "CATALOG_NAME", SYM(CATALOG_NAME_SYM)}, { "CHAIN", SYM(CHAIN_SYM)}, { "CHANGE", SYM(CHANGE)}, { "CHANGED", SYM(CHANGED)}, { "CHAR", SYM(CHAR_SYM)}, { "CHARACTER", SYM(CHAR_SYM)}, { "CHARSET", SYM(CHARSET)}, { "CHECK", SYM(CHECK_SYM)}, { "CHECKPOINT", SYM(CHECKPOINT_SYM)}, { "CHECKSUM", SYM(CHECKSUM_SYM)}, { "CIPHER", SYM(CIPHER_SYM)}, { "CLASS_ORIGIN", SYM(CLASS_ORIGIN_SYM)}, { "CLIENT", SYM(CLIENT_SYM)}, { "CLOB", SYM(CLOB_MARIADB_SYM)}, { "CLOSE", SYM(CLOSE_SYM)}, { "COALESCE", SYM(COALESCE)}, { "CODE", SYM(CODE_SYM)}, { "COLLATE", SYM(COLLATE_SYM)}, { "COLLATION", SYM(COLLATION_SYM)}, { "COLUMN", SYM(COLUMN_SYM)}, { "COLUMN_NAME", SYM(COLUMN_NAME_SYM)}, { "COLUMNS", SYM(COLUMNS)}, { "COLUMN_ADD", SYM(COLUMN_ADD_SYM)}, { "COLUMN_CHECK", SYM(COLUMN_CHECK_SYM)}, { "COLUMN_CREATE", SYM(COLUMN_CREATE_SYM)}, { "COLUMN_DELETE", SYM(COLUMN_DELETE_SYM)}, { "COLUMN_GET", SYM(COLUMN_GET_SYM)}, { "COMMENT", SYM(COMMENT_SYM)}, { "COMMIT", SYM(COMMIT_SYM)}, { "COMMITTED", SYM(COMMITTED_SYM)}, { "COMPACT", SYM(COMPACT_SYM)}, { "COMPLETION", SYM(COMPLETION_SYM)}, { "COMPRESSED", SYM(COMPRESSED_SYM)}, { "CONCURRENT", SYM(CONCURRENT)}, { "CONDITION", SYM(CONDITION_SYM)}, { "CONNECTION", SYM(CONNECTION_SYM)}, { "CONSISTENT", SYM(CONSISTENT_SYM)}, { "CONSTRAINT", SYM(CONSTRAINT)}, { "CONSTRAINT_CATALOG", SYM(CONSTRAINT_CATALOG_SYM)}, { "CONSTRAINT_NAME", SYM(CONSTRAINT_NAME_SYM)}, { "CONSTRAINT_SCHEMA", SYM(CONSTRAINT_SCHEMA_SYM)}, { "CONTAINS", SYM(CONTAINS_SYM)}, { "CONTEXT", SYM(CONTEXT_SYM)}, { "CONTINUE", SYM(CONTINUE_MARIADB_SYM)}, { "CONTRIBUTORS", SYM(CONTRIBUTORS_SYM)}, { "CONVERT", SYM(CONVERT_SYM)}, { "CPU", SYM(CPU_SYM)}, { "CREATE", SYM(CREATE)}, { "CROSS", SYM(CROSS)}, { "CUBE", SYM(CUBE_SYM)}, { "CURRENT", SYM(CURRENT_SYM)}, { "CURRENT_DATE", SYM(CURDATE)}, { "CURRENT_POS", SYM(CURRENT_POS_SYM)}, { "CURRENT_ROLE", SYM(CURRENT_ROLE)}, { "CURRENT_TIME", SYM(CURTIME)}, { "CURRENT_TIMESTAMP", SYM(NOW_SYM)}, { "CURRENT_USER", SYM(CURRENT_USER)}, { "CURSOR", SYM(CURSOR_SYM)}, { "CURSOR_NAME", SYM(CURSOR_NAME_SYM)}, { "CYCLE", SYM(CYCLE_SYM)}, { "DATA", SYM(DATA_SYM)}, { "DATABASE", SYM(DATABASE)}, { "DATABASES", SYM(DATABASES)}, { "DATAFILE", SYM(DATAFILE_SYM)}, { "DATE", SYM(DATE_SYM)}, { "DATETIME", SYM(DATETIME)}, { "DAY", SYM(DAY_SYM)}, { "DAY_HOUR", SYM(DAY_HOUR_SYM)}, { "DAY_MICROSECOND", SYM(DAY_MICROSECOND_SYM)}, { "DAY_MINUTE", SYM(DAY_MINUTE_SYM)}, { "DAY_SECOND", SYM(DAY_SECOND_SYM)}, { "DEALLOCATE", SYM(DEALLOCATE_SYM)}, { "DEC", SYM(DECIMAL_SYM)}, { "DECIMAL", SYM(DECIMAL_SYM)}, { "DECLARE", SYM(DECLARE_MARIADB_SYM)}, { "DEFAULT", SYM(DEFAULT)}, { "DEFINER", SYM(DEFINER_SYM)}, { "DELAYED", SYM(DELAYED_SYM)}, { "DELAY_KEY_WRITE", SYM(DELAY_KEY_WRITE_SYM)}, { "DELETE", SYM(DELETE_SYM)}, { "DELETE_DOMAIN_ID", SYM(DELETE_DOMAIN_ID_SYM)}, { "DESC", SYM(DESC)}, { "DESCRIBE", SYM(DESCRIBE)}, { "DES_KEY_FILE", SYM(DES_KEY_FILE)}, { "DETERMINISTIC", SYM(DETERMINISTIC_SYM)}, { "DIAGNOSTICS", SYM(DIAGNOSTICS_SYM)}, { "DIRECTORY", SYM(DIRECTORY_SYM)}, { "DISABLE", SYM(DISABLE_SYM)}, { "DISCARD", SYM(DISCARD)}, { "DISK", SYM(DISK_SYM)}, { "DISTINCT", SYM(DISTINCT)}, { "DISTINCTROW", SYM(DISTINCT)}, /* Access likes this */ { "DIV", SYM(DIV_SYM)}, { "DO", SYM(DO_SYM)}, { "DOUBLE", SYM(DOUBLE_SYM)}, { "DO_DOMAIN_IDS", SYM(DO_DOMAIN_IDS_SYM)}, { "DROP", SYM(DROP)}, { "DUAL", SYM(DUAL_SYM)}, { "DUMPFILE", SYM(DUMPFILE)}, { "DUPLICATE", SYM(DUPLICATE_SYM)}, { "DYNAMIC", SYM(DYNAMIC_SYM)}, { "EACH", SYM(EACH_SYM)}, { "ELSE", SYM(ELSE)}, { "ELSEIF", SYM(ELSEIF_MARIADB_SYM)}, { "ELSIF", SYM(ELSIF_MARIADB_SYM)}, { "EMPTY", SYM(EMPTY_SYM)}, { "ENABLE", SYM(ENABLE_SYM)}, { "ENCLOSED", SYM(ENCLOSED)}, { "END", SYM(END)}, { "ENDS", SYM(ENDS_SYM)}, { "ENGINE", SYM(ENGINE_SYM)}, { "ENGINES", SYM(ENGINES_SYM)}, { "ENUM", SYM(ENUM)}, { "ERROR", SYM(ERROR_SYM)}, { "ERRORS", SYM(ERRORS)}, { "ESCAPE", SYM(ESCAPE_SYM)}, { "ESCAPED", SYM(ESCAPED)}, { "EVENT", SYM(EVENT_SYM)}, { "EVENTS", SYM(EVENTS_SYM)}, { "EVERY", SYM(EVERY_SYM)}, { "EXAMINED", SYM(EXAMINED_SYM)}, { "EXCEPT", SYM(EXCEPT_SYM)}, { "EXCHANGE", SYM(EXCHANGE_SYM)}, { "EXCLUDE", SYM(EXCLUDE_SYM)}, { "EXECUTE", SYM(EXECUTE_SYM)}, { "EXCEPTION", SYM(EXCEPTION_MARIADB_SYM)}, { "EXISTS", SYM(EXISTS)}, { "EXIT", SYM(EXIT_MARIADB_SYM)}, { "EXPANSION", SYM(EXPANSION_SYM)}, { "EXPIRE", SYM(EXPIRE_SYM)}, { "EXPORT", SYM(EXPORT_SYM)}, { "EXPLAIN", SYM(DESCRIBE)}, { "EXTENDED", SYM(EXTENDED_SYM)}, { "EXTENT_SIZE", SYM(EXTENT_SIZE_SYM)}, { "FALSE", SYM(FALSE_SYM)}, { "FAST", SYM(FAST_SYM)}, { "FAULTS", SYM(FAULTS_SYM)}, { "FEDERATED", SYM(FEDERATED_SYM)}, { "FETCH", SYM(FETCH_SYM)}, { "FIELDS", SYM(COLUMNS)}, { "FILE", SYM(FILE_SYM)}, { "FIRST", SYM(FIRST_SYM)}, { "FIXED", SYM(FIXED_SYM)}, { "FLOAT", SYM(FLOAT_SYM)}, { "FLOAT4", SYM(FLOAT_SYM)}, { "FLOAT8", SYM(DOUBLE_SYM)}, { "FLUSH", SYM(FLUSH_SYM)}, { "FOLLOWING", SYM(FOLLOWING_SYM)}, { "FOLLOWS", SYM(FOLLOWS_SYM)}, { "FOR", SYM(FOR_SYM)}, { "FORCE", SYM(FORCE_SYM)}, { "FOREIGN", SYM(FOREIGN)}, { "FORMAT", SYM(FORMAT_SYM)}, { "FOUND", SYM(FOUND_SYM)}, { "FROM", SYM(FROM)}, { "FULL", SYM(FULL)}, { "FULLTEXT", SYM(FULLTEXT_SYM)}, { "FUNCTION", SYM(FUNCTION_SYM)}, { "GENERAL", SYM(GENERAL)}, { "GENERATED", SYM(GENERATED_SYM)}, { "GET_FORMAT", SYM(GET_FORMAT)}, { "GET", SYM(GET_SYM)}, { "GLOBAL", SYM(GLOBAL_SYM)}, { "GOTO", SYM(GOTO_MARIADB_SYM)}, { "GRANT", SYM(GRANT)}, { "GRANTS", SYM(GRANTS)}, { "GROUP", SYM(GROUP_SYM)}, { "HANDLER", SYM(HANDLER_SYM)}, { "HARD", SYM(HARD_SYM)}, { "HASH", SYM(HASH_SYM)}, { "HAVING", SYM(HAVING)}, { "HELP", SYM(HELP_SYM)}, { "HIGH_PRIORITY", SYM(HIGH_PRIORITY)}, { "HISTORY", SYM(HISTORY_SYM)}, { "HOST", SYM(HOST_SYM)}, { "HOSTS", SYM(HOSTS_SYM)}, { "HOUR", SYM(HOUR_SYM)}, { "HOUR_MICROSECOND", SYM(HOUR_MICROSECOND_SYM)}, { "HOUR_MINUTE", SYM(HOUR_MINUTE_SYM)}, { "HOUR_SECOND", SYM(HOUR_SECOND_SYM)}, { "ID", SYM(ID_SYM)}, { "IDENTIFIED", SYM(IDENTIFIED_SYM)}, { "IF", SYM(IF_SYM)}, { "IGNORE", SYM(IGNORE_SYM)}, { "IGNORED", SYM(IGNORED_SYM)}, { "IGNORE_DOMAIN_IDS", SYM(IGNORE_DOMAIN_IDS_SYM)}, { "IGNORE_SERVER_IDS", SYM(IGNORE_SERVER_IDS_SYM)}, { "IMMEDIATE", SYM(IMMEDIATE_SYM)}, { "IMPORT", SYM(IMPORT)}, { "INTERSECT", SYM(INTERSECT_SYM)}, { "IN", SYM(IN_SYM)}, { "INCREMENT", SYM(INCREMENT_SYM)}, { "INDEX", SYM(INDEX_SYM)}, { "INDEXES", SYM(INDEXES)}, { "INFILE", SYM(INFILE)}, { "INITIAL_SIZE", SYM(INITIAL_SIZE_SYM)}, { "INNER", SYM(INNER_SYM)}, { "INOUT", SYM(INOUT_SYM)}, { "INSENSITIVE", SYM(INSENSITIVE_SYM)}, { "INSERT", SYM(INSERT)}, { "INSERT_METHOD", SYM(INSERT_METHOD)}, { "INSTALL", SYM(INSTALL_SYM)}, { "INT", SYM(INT_SYM)}, { "INT1", SYM(TINYINT)}, { "INT2", SYM(SMALLINT)}, { "INT3", SYM(MEDIUMINT)}, { "INT4", SYM(INT_SYM)}, { "INT8", SYM(BIGINT)}, { "INTEGER", SYM(INT_SYM)}, { "INTERVAL", SYM(INTERVAL_SYM)}, { "INVISIBLE", SYM(INVISIBLE_SYM)}, { "INTO", SYM(INTO)}, { "IO", SYM(IO_SYM)}, { "IO_THREAD", SYM(RELAY_THREAD)}, { "IPC", SYM(IPC_SYM)}, { "IS", SYM(IS)}, { "ISOLATION", SYM(ISOLATION)}, { "ISOPEN", SYM(ISOPEN_SYM)}, { "ISSUER", SYM(ISSUER_SYM)}, { "ITERATE", SYM(ITERATE_SYM)}, { "INVOKER", SYM(INVOKER_SYM)}, { "JOIN", SYM(JOIN_SYM)}, { "JSON", SYM(JSON_SYM)}, { "JSON_TABLE", SYM(JSON_TABLE_SYM)}, { "KEY", SYM(KEY_SYM)}, { "KEYS", SYM(KEYS)}, { "KEY_BLOCK_SIZE", SYM(KEY_BLOCK_SIZE)}, { "KILL", SYM(KILL_SYM)}, { "LANGUAGE", SYM(LANGUAGE_SYM)}, { "LAST", SYM(LAST_SYM)}, { "LAST_VALUE", SYM(LAST_VALUE)}, { "LASTVAL", SYM(LASTVAL_SYM)}, { "LEADING", SYM(LEADING)}, { "LEAVE", SYM(LEAVE_SYM)}, { "LEAVES", SYM(LEAVES)}, { "LEFT", SYM(LEFT)}, { "LESS", SYM(LESS_SYM)}, { "LEVEL", SYM(LEVEL_SYM)}, { "LIKE", SYM(LIKE)}, { "LIMIT", SYM(LIMIT)}, { "LINEAR", SYM(LINEAR_SYM)}, { "LINES", SYM(LINES)}, { "LIST", SYM(LIST_SYM)}, { "LOAD", SYM(LOAD)}, { "LOCAL", SYM(LOCAL_SYM)}, { "LOCALTIME", SYM(NOW_SYM)}, { "LOCALTIMESTAMP", SYM(NOW_SYM)}, { "LOCK", SYM(LOCK_SYM)}, { "LOCKED", SYM(LOCKED_SYM)}, { "LOCKS", SYM(LOCKS_SYM)}, { "LOGFILE", SYM(LOGFILE_SYM)}, { "LOGS", SYM(LOGS_SYM)}, { "LONG", SYM(LONG_SYM)}, { "LONGBLOB", SYM(LONGBLOB)}, { "LONGTEXT", SYM(LONGTEXT)}, { "LOOP", SYM(LOOP_SYM)}, { "LOW_PRIORITY", SYM(LOW_PRIORITY)}, { "MASTER", SYM(MASTER_SYM)}, { "MASTER_CONNECT_RETRY", SYM(MASTER_CONNECT_RETRY_SYM)}, { "MASTER_DELAY", SYM(MASTER_DELAY_SYM)}, { "MASTER_GTID_POS", SYM(MASTER_GTID_POS_SYM)}, { "MASTER_HOST", SYM(MASTER_HOST_SYM)}, { "MASTER_LOG_FILE", SYM(MASTER_LOG_FILE_SYM)}, { "MASTER_LOG_POS", SYM(MASTER_LOG_POS_SYM)}, { "MASTER_PASSWORD", SYM(MASTER_PASSWORD_SYM)}, { "MASTER_PORT", SYM(MASTER_PORT_SYM)}, { "MASTER_SERVER_ID", SYM(MASTER_SERVER_ID_SYM)}, { "MASTER_SSL", SYM(MASTER_SSL_SYM)}, { "MASTER_SSL_CA", SYM(MASTER_SSL_CA_SYM)}, { "MASTER_SSL_CAPATH",SYM(MASTER_SSL_CAPATH_SYM)}, { "MASTER_SSL_CERT", SYM(MASTER_SSL_CERT_SYM)}, { "MASTER_SSL_CIPHER",SYM(MASTER_SSL_CIPHER_SYM)}, { "MASTER_SSL_CRL", SYM(MASTER_SSL_CRL_SYM)}, { "MASTER_SSL_CRLPATH",SYM(MASTER_SSL_CRLPATH_SYM)}, { "MASTER_SSL_KEY", SYM(MASTER_SSL_KEY_SYM)}, { "MASTER_SSL_VERIFY_SERVER_CERT", SYM(MASTER_SSL_VERIFY_SERVER_CERT_SYM)}, { "MASTER_USER", SYM(MASTER_USER_SYM)}, { "MASTER_USE_GTID", SYM(MASTER_USE_GTID_SYM)}, { "MASTER_HEARTBEAT_PERIOD", SYM(MASTER_HEARTBEAT_PERIOD_SYM)}, { "MATCH", SYM(MATCH)}, { "MAX_CONNECTIONS_PER_HOUR", SYM(MAX_CONNECTIONS_PER_HOUR)}, { "MAX_QUERIES_PER_HOUR", SYM(MAX_QUERIES_PER_HOUR)}, { "MAX_ROWS", SYM(MAX_ROWS)}, { "MAX_SIZE", SYM(MAX_SIZE_SYM)}, { "MAX_STATEMENT_TIME", SYM(MAX_STATEMENT_TIME_SYM)}, { "MAX_UPDATES_PER_HOUR", SYM(MAX_UPDATES_PER_HOUR)}, { "MAX_USER_CONNECTIONS", SYM(MAX_USER_CONNECTIONS_SYM)}, { "MAXVALUE", SYM(MAXVALUE_SYM)}, { "MEDIUM", SYM(MEDIUM_SYM)}, { "MEDIUMBLOB", SYM(MEDIUMBLOB)}, { "MEDIUMINT", SYM(MEDIUMINT)}, { "MEDIUMTEXT", SYM(MEDIUMTEXT)}, { "MEMORY", SYM(MEMORY_SYM)}, { "MERGE", SYM(MERGE_SYM)}, { "MESSAGE_TEXT", SYM(MESSAGE_TEXT_SYM)}, { "MICROSECOND", SYM(MICROSECOND_SYM)}, { "MIDDLEINT", SYM(MEDIUMINT)}, /* For powerbuilder */ { "MIGRATE", SYM(MIGRATE_SYM)}, { "MINUS", SYM(MINUS_ORACLE_SYM)}, { "MINUTE", SYM(MINUTE_SYM)}, { "MINUTE_MICROSECOND", SYM(MINUTE_MICROSECOND_SYM)}, { "MINUTE_SECOND", SYM(MINUTE_SECOND_SYM)}, { "MINVALUE", SYM(MINVALUE_SYM)}, { "MIN_ROWS", SYM(MIN_ROWS)}, { "MOD", SYM(MOD_SYM)}, { "MODE", SYM(MODE_SYM)}, { "MODIFIES", SYM(MODIFIES_SYM)}, { "MODIFY", SYM(MODIFY_SYM)}, { "MONITOR", SYM(MONITOR_SYM)}, { "MONTH", SYM(MONTH_SYM)}, { "MUTEX", SYM(MUTEX_SYM)}, { "MYSQL", SYM(MYSQL_SYM)}, { "MYSQL_ERRNO", SYM(MYSQL_ERRNO_SYM)}, { "NAME", SYM(NAME_SYM)}, { "NAMES", SYM(NAMES_SYM)}, { "NATIONAL", SYM(NATIONAL_SYM)}, { "NATURAL", SYM(NATURAL)}, { "NCHAR", SYM(NCHAR_SYM)}, { "NESTED", SYM(NESTED_SYM)}, { "NEVER", SYM(NEVER_SYM)}, { "NEXT", SYM(NEXT_SYM)}, { "NEXTVAL", SYM(NEXTVAL_SYM)}, { "NO", SYM(NO_SYM)}, { "NOMAXVALUE", SYM(NOMAXVALUE_SYM)}, { "NOMINVALUE", SYM(NOMINVALUE_SYM)}, { "NOCACHE", SYM(NOCACHE_SYM)}, { "NOCYCLE", SYM(NOCYCLE_SYM)}, { "NO_WAIT", SYM(NO_WAIT_SYM)}, { "NOWAIT", SYM(NOWAIT_SYM)}, { "NODEGROUP", SYM(NODEGROUP_SYM)}, { "NONE", SYM(NONE_SYM)}, { "NOT", SYM(NOT_SYM)}, { "NOTFOUND", SYM(NOTFOUND_SYM)}, { "NO_WRITE_TO_BINLOG", SYM(NO_WRITE_TO_BINLOG)}, { "NULL", SYM(NULL_SYM)}, { "NUMBER", SYM(NUMBER_MARIADB_SYM)}, { "NUMERIC", SYM(NUMERIC_SYM)}, { "NVARCHAR", SYM(NVARCHAR_SYM)}, { "OF", SYM(OF_SYM)}, { "OFFSET", SYM(OFFSET_SYM)}, { "OLD_PASSWORD", SYM(OLD_PASSWORD_SYM)}, { "ON", SYM(ON)}, { "ONE", SYM(ONE_SYM)}, { "ONLINE", SYM(ONLINE_SYM)}, { "ONLY", SYM(ONLY_SYM)}, { "OPEN", SYM(OPEN_SYM)}, { "OPTIMIZE", SYM(OPTIMIZE)}, { "OPTIONS", SYM(OPTIONS_SYM)}, { "OPTION", SYM(OPTION)}, { "OPTIONALLY", SYM(OPTIONALLY)}, { "OR", SYM(OR_SYM)}, { "ORDER", SYM(ORDER_SYM)}, { "ORDINALITY", SYM(ORDINALITY_SYM)}, { "OTHERS", SYM(OTHERS_MARIADB_SYM)}, { "OUT", SYM(OUT_SYM)}, { "OUTER", SYM(OUTER)}, { "OUTFILE", SYM(OUTFILE)}, { "OVER", SYM(OVER_SYM)}, { "OVERLAPS", SYM(OVERLAPS_SYM)}, { "OWNER", SYM(OWNER_SYM)}, { "PACKAGE", SYM(PACKAGE_MARIADB_SYM)}, { "PACK_KEYS", SYM(PACK_KEYS_SYM)}, { "PAGE", SYM(PAGE_SYM)}, { "PAGE_CHECKSUM", SYM(PAGE_CHECKSUM_SYM)}, { "PARSER", SYM(PARSER_SYM)}, { "PARSE_VCOL_EXPR", SYM(PARSE_VCOL_EXPR_SYM)}, { "PATH", SYM(PATH_SYM)}, { "PERIOD", SYM(PERIOD_SYM)}, { "PARTIAL", SYM(PARTIAL)}, { "PARTITION", SYM(PARTITION_SYM)}, { "PARTITIONING", SYM(PARTITIONING_SYM)}, { "PARTITIONS", SYM(PARTITIONS_SYM)}, { "PASSWORD", SYM(PASSWORD_SYM)}, { "PERSISTENT", SYM(PERSISTENT_SYM)}, { "PHASE", SYM(PHASE_SYM)}, { "PLUGIN", SYM(PLUGIN_SYM)}, { "PLUGINS", SYM(PLUGINS_SYM)}, { "PORT", SYM(PORT_SYM)}, { "PORTION", SYM(PORTION_SYM)}, { "PRECEDES", SYM(PRECEDES_SYM)}, { "PRECEDING", SYM(PRECEDING_SYM)}, { "PRECISION", SYM(PRECISION)}, { "PREPARE", SYM(PREPARE_SYM)}, { "PRESERVE", SYM(PRESERVE_SYM)}, { "PREV", SYM(PREV_SYM)}, { "PREVIOUS", SYM(PREVIOUS_SYM)}, { "PRIMARY", SYM(PRIMARY_SYM)}, { "PRIVILEGES", SYM(PRIVILEGES)}, { "PROCEDURE", SYM(PROCEDURE_SYM)}, { "PROCESS" , SYM(PROCESS)}, { "PROCESSLIST", SYM(PROCESSLIST_SYM)}, { "PROFILE", SYM(PROFILE_SYM)}, { "PROFILES", SYM(PROFILES_SYM)}, { "PROXY", SYM(PROXY_SYM)}, { "PURGE", SYM(PURGE)}, { "QUARTER", SYM(QUARTER_SYM)}, { "QUERY", SYM(QUERY_SYM)}, { "QUICK", SYM(QUICK)}, { "RAISE", SYM(RAISE_MARIADB_SYM)}, { "RANGE", SYM(RANGE_SYM)}, { "RAW", SYM(RAW_MARIADB_SYM)}, { "READ", SYM(READ_SYM)}, { "READ_ONLY", SYM(READ_ONLY_SYM)}, { "READ_WRITE", SYM(READ_WRITE_SYM)}, { "READS", SYM(READS_SYM)}, { "REAL", SYM(REAL)}, { "REBUILD", SYM(REBUILD_SYM)}, { "RECOVER", SYM(RECOVER_SYM)}, { "RECURSIVE", SYM(RECURSIVE_SYM)}, { "REDO_BUFFER_SIZE", SYM(REDO_BUFFER_SIZE_SYM)}, { "REDOFILE", SYM(REDOFILE_SYM)}, { "REDUNDANT", SYM(REDUNDANT_SYM)}, { "REFERENCES", SYM(REFERENCES)}, { "REGEXP", SYM(REGEXP)}, { "RELAY", SYM(RELAY)}, { "RELAYLOG", SYM(RELAYLOG_SYM)}, { "RELAY_LOG_FILE", SYM(RELAY_LOG_FILE_SYM)}, { "RELAY_LOG_POS", SYM(RELAY_LOG_POS_SYM)}, { "RELAY_THREAD", SYM(RELAY_THREAD)}, { "RELEASE", SYM(RELEASE_SYM)}, { "RELOAD", SYM(RELOAD)}, { "REMOVE", SYM(REMOVE_SYM)}, { "RENAME", SYM(RENAME)}, { "REORGANIZE", SYM(REORGANIZE_SYM)}, { "REPAIR", SYM(REPAIR)}, { "REPEATABLE", SYM(REPEATABLE_SYM)}, { "REPLACE", SYM(REPLACE)}, { "REPLAY", SYM(REPLAY_SYM)}, { "REPLICA", SYM(SLAVE)}, { "REPLICAS", SYM(SLAVES)}, { "REPLICA_POS", SYM(SLAVE_POS_SYM)}, { "REPLICATION", SYM(REPLICATION)}, { "REPEAT", SYM(REPEAT_SYM)}, { "REQUIRE", SYM(REQUIRE_SYM)}, { "RESET", SYM(RESET_SYM)}, { "RESIGNAL", SYM(RESIGNAL_SYM)}, { "RESTART", SYM(RESTART_SYM)}, { "RESTORE", SYM(RESTORE_SYM)}, { "RESTRICT", SYM(RESTRICT)}, { "RESUME", SYM(RESUME_SYM)}, { "RETURNED_SQLSTATE",SYM(RETURNED_SQLSTATE_SYM)}, { "RETURN", SYM(RETURN_MARIADB_SYM)}, { "RETURNING", SYM(RETURNING_SYM)}, { "RETURNS", SYM(RETURNS_SYM)}, { "REUSE", SYM(REUSE_SYM)}, { "REVERSE", SYM(REVERSE_SYM)}, { "REVOKE", SYM(REVOKE)}, { "RIGHT", SYM(RIGHT)}, { "RLIKE", SYM(REGEXP)}, /* Like in mSQL2 */ { "ROLE", SYM(ROLE_SYM)}, { "ROLLBACK", SYM(ROLLBACK_SYM)}, { "ROLLUP", SYM(ROLLUP_SYM)}, { "ROUTINE", SYM(ROUTINE_SYM)}, { "ROW", SYM(ROW_SYM)}, { "ROWCOUNT", SYM(ROWCOUNT_SYM)}, /* Oracle-N */ { "ROWNUM", SYM(ROWNUM_SYM)}, /* Oracle-R */ { "ROWS", SYM(ROWS_SYM)}, { "ROWTYPE", SYM(ROWTYPE_MARIADB_SYM)}, { "ROW_COUNT", SYM(ROW_COUNT_SYM)}, { "ROW_FORMAT", SYM(ROW_FORMAT_SYM)}, { "RTREE", SYM(RTREE_SYM)}, { "SAVEPOINT", SYM(SAVEPOINT_SYM)}, { "SCHEDULE", SYM(SCHEDULE_SYM)}, { "SCHEMA", SYM(DATABASE)}, { "SCHEMA_NAME", SYM(SCHEMA_NAME_SYM)}, { "SCHEMAS", SYM(DATABASES)}, { "SECOND", SYM(SECOND_SYM)}, { "SECOND_MICROSECOND", SYM(SECOND_MICROSECOND_SYM)}, { "SECURITY", SYM(SECURITY_SYM)}, { "SELECT", SYM(SELECT_SYM)}, { "SENSITIVE", SYM(SENSITIVE_SYM)}, { "SEPARATOR", SYM(SEPARATOR_SYM)}, { "SEQUENCE", SYM(SEQUENCE_SYM)}, { "SERIAL", SYM(SERIAL_SYM)}, { "SERIALIZABLE", SYM(SERIALIZABLE_SYM)}, { "SESSION", SYM(SESSION_SYM)}, { "SERVER", SYM(SERVER_SYM)}, { "SET", SYM(SET)}, { "SETVAL", SYM(SETVAL_SYM)}, { "SHARE", SYM(SHARE_SYM)}, { "SHOW", SYM(SHOW)}, { "SHUTDOWN", SYM(SHUTDOWN)}, { "SIGNAL", SYM(SIGNAL_SYM)}, { "SIGNED", SYM(SIGNED_SYM)}, { "SIMPLE", SYM(SIMPLE_SYM)}, { "SKIP", SYM(SKIP_SYM)}, { "SLAVE", SYM(SLAVE)}, { "SLAVES", SYM(SLAVES)}, { "SLAVE_POS", SYM(SLAVE_POS_SYM)}, { "SLOW", SYM(SLOW)}, { "SNAPSHOT", SYM(SNAPSHOT_SYM)}, { "SMALLINT", SYM(SMALLINT)}, { "SOCKET", SYM(SOCKET_SYM)}, { "SOFT", SYM(SOFT_SYM)}, { "SOME", SYM(ANY_SYM)}, { "SONAME", SYM(SONAME_SYM)}, { "SOUNDS", SYM(SOUNDS_SYM)}, { "SOURCE", SYM(SOURCE_SYM)}, { "STAGE", SYM(STAGE_SYM)}, { "STORED", SYM(STORED_SYM)}, { "SPATIAL", SYM(SPATIAL_SYM)}, { "SPECIFIC", SYM(SPECIFIC_SYM)}, { "REF_SYSTEM_ID", SYM(REF_SYSTEM_ID_SYM)}, { "SQL", SYM(SQL_SYM)}, { "SQLEXCEPTION", SYM(SQLEXCEPTION_SYM)}, { "SQLSTATE", SYM(SQLSTATE_SYM)}, { "SQLWARNING", SYM(SQLWARNING_SYM)}, { "SQL_BIG_RESULT", SYM(SQL_BIG_RESULT)}, { "SQL_BUFFER_RESULT", SYM(SQL_BUFFER_RESULT)}, { "SQL_CACHE", SYM(SQL_CACHE_SYM)}, { "SQL_CALC_FOUND_ROWS", SYM(SQL_CALC_FOUND_ROWS)}, { "SQL_NO_CACHE", SYM(SQL_NO_CACHE_SYM)}, { "SQL_SMALL_RESULT", SYM(SQL_SMALL_RESULT)}, { "SQL_THREAD", SYM(SQL_THREAD)}, { "SQL_TSI_SECOND", SYM(SECOND_SYM)}, { "SQL_TSI_MINUTE", SYM(MINUTE_SYM)}, { "SQL_TSI_HOUR", SYM(HOUR_SYM)}, { "SQL_TSI_DAY", SYM(DAY_SYM)}, { "SQL_TSI_WEEK", SYM(WEEK_SYM)}, { "SQL_TSI_MONTH", SYM(MONTH_SYM)}, { "SQL_TSI_QUARTER", SYM(QUARTER_SYM)}, { "SQL_TSI_YEAR", SYM(YEAR_SYM)}, { "SSL", SYM(SSL_SYM)}, { "START", SYM(START_SYM)}, { "STARTING", SYM(STARTING)}, { "STARTS", SYM(STARTS_SYM)}, { "STATEMENT", SYM(STATEMENT_SYM)}, { "STATS_AUTO_RECALC",SYM(STATS_AUTO_RECALC_SYM)}, { "STATS_PERSISTENT", SYM(STATS_PERSISTENT_SYM)}, { "STATS_SAMPLE_PAGES",SYM(STATS_SAMPLE_PAGES_SYM)}, { "STATUS", SYM(STATUS_SYM)}, { "STOP", SYM(STOP_SYM)}, { "STORAGE", SYM(STORAGE_SYM)}, { "STRAIGHT_JOIN", SYM(STRAIGHT_JOIN)}, { "STRING", SYM(STRING_SYM)}, { "SUBCLASS_ORIGIN", SYM(SUBCLASS_ORIGIN_SYM)}, { "SUBJECT", SYM(SUBJECT_SYM)}, { "SUBPARTITION", SYM(SUBPARTITION_SYM)}, { "SUBPARTITIONS", SYM(SUBPARTITIONS_SYM)}, { "SUPER", SYM(SUPER_SYM)}, { "SUSPEND", SYM(SUSPEND_SYM)}, { "SWAPS", SYM(SWAPS_SYM)}, { "SWITCHES", SYM(SWITCHES_SYM)}, { "SYSDATE", SYM(SYSDATE)}, { "SYSTEM", SYM(SYSTEM)}, { "SYSTEM_TIME", SYM(SYSTEM_TIME_SYM)}, { "TABLE", SYM(TABLE_SYM)}, { "TABLE_NAME", SYM(TABLE_NAME_SYM)}, { "TABLES", SYM(TABLES)}, { "TABLESPACE", SYM(TABLESPACE)}, { "TABLE_CHECKSUM", SYM(TABLE_CHECKSUM_SYM)}, { "TEMPORARY", SYM(TEMPORARY)}, { "TEMPTABLE", SYM(TEMPTABLE_SYM)}, { "TERMINATED", SYM(TERMINATED)}, { "TEXT", SYM(TEXT_SYM)}, { "THAN", SYM(THAN_SYM)}, { "THEN", SYM(THEN_SYM)}, { "TIES", SYM(TIES_SYM)}, { "TIME", SYM(TIME_SYM)}, { "TIMESTAMP", SYM(TIMESTAMP)}, { "TIMESTAMPADD", SYM(TIMESTAMP_ADD)}, { "TIMESTAMPDIFF", SYM(TIMESTAMP_DIFF)}, { "TINYBLOB", SYM(TINYBLOB)}, { "TINYINT", SYM(TINYINT)}, { "TINYTEXT", SYM(TINYTEXT)}, { "TO", SYM(TO_SYM)}, { "TRAILING", SYM(TRAILING)}, { "TRANSACTION", SYM(TRANSACTION_SYM)}, { "TRANSACTIONAL", SYM(TRANSACTIONAL_SYM)}, { "THREADS", SYM(THREADS_SYM)}, { "TRIGGER", SYM(TRIGGER_SYM)}, { "TRIGGERS", SYM(TRIGGERS_SYM)}, { "TRUE", SYM(TRUE_SYM)}, { "TRUNCATE", SYM(TRUNCATE_SYM)}, { "TYPE", SYM(TYPE_SYM)}, { "UNBOUNDED", SYM(UNBOUNDED_SYM)}, { "UNCOMMITTED", SYM(UNCOMMITTED_SYM)}, { "UNDEFINED", SYM(UNDEFINED_SYM)}, { "UNDO_BUFFER_SIZE", SYM(UNDO_BUFFER_SIZE_SYM)}, { "UNDOFILE", SYM(UNDOFILE_SYM)}, { "UNDO", SYM(UNDO_SYM)}, { "UNICODE", SYM(UNICODE_SYM)}, { "UNION", SYM(UNION_SYM)}, { "UNIQUE", SYM(UNIQUE_SYM)}, { "UNKNOWN", SYM(UNKNOWN_SYM)}, { "UNLOCK", SYM(UNLOCK_SYM)}, { "UNINSTALL", SYM(UNINSTALL_SYM)}, { "UNSIGNED", SYM(UNSIGNED)}, { "UNTIL", SYM(UNTIL_SYM)}, { "UPDATE", SYM(UPDATE_SYM)}, { "UPGRADE", SYM(UPGRADE_SYM)}, { "USAGE", SYM(USAGE)}, { "USE", SYM(USE_SYM)}, { "USER", SYM(USER_SYM)}, { "USER_RESOURCES", SYM(RESOURCES)}, { "USE_FRM", SYM(USE_FRM)}, { "USING", SYM(USING)}, { "UTC_DATE", SYM(UTC_DATE_SYM)}, { "UTC_TIME", SYM(UTC_TIME_SYM)}, { "UTC_TIMESTAMP", SYM(UTC_TIMESTAMP_SYM)}, { "VALUE", SYM(VALUE_SYM)}, { "VALUES", SYM(VALUES)}, { "VARBINARY", SYM(VARBINARY)}, { "VARCHAR", SYM(VARCHAR)}, { "VARCHARACTER", SYM(VARCHAR)}, { "VARCHAR2", SYM(VARCHAR2_MARIADB_SYM)}, { "VARIABLES", SYM(VARIABLES)}, { "VARYING", SYM(VARYING)}, { "VIA", SYM(VIA_SYM)}, { "VIEW", SYM(VIEW_SYM)}, { "VIRTUAL", SYM(VIRTUAL_SYM)}, { "VISIBLE", SYM(VISIBLE_SYM)}, { "VERSIONING", SYM(VERSIONING_SYM)}, { "WAIT", SYM(WAIT_SYM)}, { "WARNINGS", SYM(WARNINGS)}, { "WEEK", SYM(WEEK_SYM)}, { "WEIGHT_STRING", SYM(WEIGHT_STRING_SYM)}, { "WHEN", SYM(WHEN_SYM)}, { "WHERE", SYM(WHERE)}, { "WHILE", SYM(WHILE_SYM)}, { "WINDOW", SYM(WINDOW_SYM)}, { "WITH", SYM(WITH)}, { "WITHIN", SYM(WITHIN)}, { "WITHOUT", SYM(WITHOUT)}, { "WORK", SYM(WORK_SYM)}, { "WRAPPER", SYM(WRAPPER_SYM)}, { "WRITE", SYM(WRITE_SYM)}, { "X509", SYM(X509_SYM)}, { "XOR", SYM(XOR)}, { "XA", SYM(XA_SYM)}, { "XML", SYM(XML_SYM)}, /* LOAD XML Arnold/Erik */ { "YEAR", SYM(YEAR_SYM)}, { "YEAR_MONTH", SYM(YEAR_MONTH_SYM)}, { "ZEROFILL", SYM(ZEROFILL)}, { "||", SYM(OR2_SYM)} }; SYMBOL sql_functions[] = { { "ADDDATE", SYM(ADDDATE_SYM)}, { "BIT_AND", SYM(BIT_AND)}, { "BIT_OR", SYM(BIT_OR)}, { "BIT_XOR", SYM(BIT_XOR)}, { "CAST", SYM(CAST_SYM)}, { "COUNT", SYM(COUNT_SYM)}, { "CUME_DIST", SYM(CUME_DIST_SYM)}, { "CURDATE", SYM(CURDATE)}, { "CURTIME", SYM(CURTIME)}, { "DATE_ADD", SYM(DATE_ADD_INTERVAL)}, { "DATE_SUB", SYM(DATE_SUB_INTERVAL)}, { "DENSE_RANK", SYM(DENSE_RANK_SYM)}, { "EXTRACT", SYM(EXTRACT_SYM)}, { "FIRST_VALUE", SYM(FIRST_VALUE_SYM)}, { "GROUP_CONCAT", SYM(GROUP_CONCAT_SYM)}, { "JSON_ARRAYAGG", SYM(JSON_ARRAYAGG_SYM)}, { "JSON_OBJECTAGG", SYM(JSON_OBJECTAGG_SYM)}, { "LAG", SYM(LAG_SYM)}, { "LEAD", SYM(LEAD_SYM)}, { "MAX", SYM(MAX_SYM)}, { "MEDIAN", SYM(MEDIAN_SYM)}, { "MID", SYM(SUBSTRING)}, /* unireg function */ { "MIN", SYM(MIN_SYM)}, { "NOW", SYM(NOW_SYM)}, { "NTH_VALUE", SYM(NTH_VALUE_SYM)}, { "NTILE", SYM(NTILE_SYM)}, { "POSITION", SYM(POSITION_SYM)}, { "PERCENT_RANK", SYM(PERCENT_RANK_SYM)}, { "PERCENTILE_CONT", SYM(PERCENTILE_CONT_SYM)}, { "PERCENTILE_DISC", SYM(PERCENTILE_DISC_SYM)}, { "RANK", SYM(RANK_SYM)}, { "ROW_NUMBER", SYM(ROW_NUMBER_SYM)}, { "SESSION_USER", SYM(USER_SYM)}, { "STD", SYM(STD_SYM)}, { "STDDEV", SYM(STD_SYM)}, { "STDDEV_POP", SYM(STD_SYM)}, { "STDDEV_SAMP", SYM(STDDEV_SAMP_SYM)}, { "SUBDATE", SYM(SUBDATE_SYM)}, { "SUBSTR", SYM(SUBSTRING)}, { "SUBSTRING", SYM(SUBSTRING)}, { "SUM", SYM(SUM_SYM)}, { "SYSTEM_USER", SYM(USER_SYM)}, { "TRIM", SYM(TRIM)}, { "TRIM_ORACLE", SYM(TRIM_ORACLE)}, { "VARIANCE", SYM(VARIANCE_SYM)}, { "VAR_POP", SYM(VARIANCE_SYM)}, { "VAR_SAMP", SYM(VAR_SAMP_SYM)}, }; size_t symbols_length= sizeof(symbols) / sizeof(SYMBOL); size_t sql_functions_length= sizeof(sql_functions) / sizeof(SYMBOL); #endif /* LEX_INCLUDED */ mysql/server/private/sql_base.h000064400000062430151027430560012643 0ustar00/* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2011, 2018, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_BASE_INCLUDED #define SQL_BASE_INCLUDED #include "sql_class.h" /* enum_column_usage */ #include "sql_trigger.h" /* trg_event_type */ #include "mysqld.h" /* key_map */ #include "table_cache.h" class Item_ident; struct Name_resolution_context; class Open_table_context; class Open_tables_state; class Prelocking_strategy; struct TABLE_LIST; class THD; struct handlerton; struct TABLE; typedef class st_select_lex SELECT_LEX; typedef struct st_lock_param_type ALTER_PARTITION_PARAM_TYPE; /* This enumeration type is used only by the function find_item_in_list to return the info on how an item has been resolved against a list of possibly aliased items. The item can be resolved: - against an alias name of the list's element (RESOLVED_AGAINST_ALIAS) - against non-aliased field name of the list (RESOLVED_WITH_NO_ALIAS) - against an aliased field name of the list (RESOLVED_BEHIND_ALIAS) - ignoring the alias name in cases when SQL requires to ignore aliases (e.g. when the resolved field reference contains a table name or when the resolved item is an expression) (RESOLVED_IGNORING_ALIAS) */ enum enum_resolution_type { NOT_RESOLVED=0, RESOLVED_IGNORING_ALIAS, RESOLVED_BEHIND_ALIAS, RESOLVED_WITH_NO_ALIAS, RESOLVED_AGAINST_ALIAS }; /* Argument to flush_tables() of what to flush */ enum flush_tables_type { FLUSH_ALL, FLUSH_NON_TRANS_TABLES, FLUSH_SYS_TABLES }; enum find_item_error_report_type {REPORT_ALL_ERRORS, REPORT_EXCEPT_NOT_FOUND, IGNORE_ERRORS, REPORT_EXCEPT_NON_UNIQUE, IGNORE_EXCEPT_NON_UNIQUE}; /* Flag bits for unique_table() */ #define CHECK_DUP_ALLOW_DIFFERENT_ALIAS 1 #define CHECK_DUP_FOR_CREATE 2 #define CHECK_DUP_SKIP_TEMP_TABLE 4 uint get_table_def_key(const TABLE_LIST *table_list, const char **key); TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type update, uint lock_flags); /* mysql_lock_tables() and open_table() flags bits */ #define MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK 0x0001 #define MYSQL_OPEN_IGNORE_FLUSH 0x0002 /* MYSQL_OPEN_TEMPORARY_ONLY (0x0004) is not used anymore. */ #define MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY 0x0008 #define MYSQL_LOCK_LOG_TABLE 0x0010 /** Do not try to acquire a metadata lock on the table: we already have one. */ #define MYSQL_OPEN_HAS_MDL_LOCK 0x0020 /** If in locked tables mode, ignore the locked tables and get a new instance of the table. */ #define MYSQL_OPEN_GET_NEW_TABLE 0x0040 /* 0x0080 used to be MYSQL_OPEN_SKIP_TEMPORARY */ /** Fail instead of waiting when conficting metadata lock is discovered. */ #define MYSQL_OPEN_FAIL_ON_MDL_CONFLICT 0x0100 /** Open tables using MDL_SHARED lock instead of one specified in parser. */ #define MYSQL_OPEN_FORCE_SHARED_MDL 0x0200 /** Open tables using MDL_SHARED_HIGH_PRIO lock instead of one specified in parser. */ #define MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL 0x0400 /** When opening or locking the table, use the maximum timeout (LONG_TIMEOUT = 1 year) rather than the user-supplied timeout value. */ #define MYSQL_LOCK_IGNORE_TIMEOUT 0x0800 /** When acquiring "strong" (SNW, SNRW, X) metadata locks on tables to be open do not acquire global and schema-scope IX locks. */ #define MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK 0x1000 #define MYSQL_LOCK_NOT_TEMPORARY 0x2000 #define MYSQL_LOCK_USE_MALLOC 0x4000 /** Only check THD::killed if waits happen (e.g. wait on MDL, wait on table flush, wait on thr_lock.c locks) while opening and locking table. */ #define MYSQL_OPEN_IGNORE_KILLED 0x8000 /** Don't try to auto-repair table */ #define MYSQL_OPEN_IGNORE_REPAIR 0x10000 /** Don't call decide_logging_format. Used for statistic tables etc */ #define MYSQL_OPEN_IGNORE_LOGGING_FORMAT 0x20000 /* Don't use statistics tables */ #define MYSQL_OPEN_IGNORE_ENGINE_STATS 0x40000 /** Please refer to the internals manual. */ #define MYSQL_OPEN_REOPEN (MYSQL_OPEN_IGNORE_FLUSH |\ MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |\ MYSQL_LOCK_IGNORE_GLOBAL_READ_ONLY |\ MYSQL_LOCK_IGNORE_TIMEOUT |\ MYSQL_OPEN_GET_NEW_TABLE |\ MYSQL_OPEN_HAS_MDL_LOCK) bool is_locked_view(THD *thd, TABLE_LIST *t); bool open_table(THD *thd, TABLE_LIST *table_list, Open_table_context *ot_ctx); bool get_key_map_from_key_list(key_map *map, TABLE *table, List *index_list); TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name); TABLE *find_write_locked_table(TABLE *list, const char *db, const char *table_name); thr_lock_type read_lock_type_for_table(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool routine_modifies_data); my_bool mysql_rm_tmp_tables(void); void close_tables_for_reopen(THD *thd, TABLE_LIST **tables, const MDL_savepoint &start_of_statement_svp); bool table_already_fk_prelocked(TABLE_LIST *tl, LEX_CSTRING *db, LEX_CSTRING *table, thr_lock_type lock_type); TABLE_LIST *find_table_in_list(TABLE_LIST *table, TABLE_LIST *TABLE_LIST::*link, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name); int close_thread_tables(THD *thd); void switch_to_nullable_trigger_fields(List &items, TABLE *); void switch_defaults_to_nullable_trigger_fields(TABLE *table); bool fill_record_n_invoke_before_triggers(THD *thd, TABLE *table, List &fields, List &values, bool ignore_errors, enum trg_event_type event); bool fill_record_n_invoke_before_triggers(THD *thd, TABLE *table, Field **field, List &values, bool ignore_errors, enum trg_event_type event); bool insert_fields(THD *thd, Name_resolution_context *context, const char *db_name, const char *table_name, List_iterator *it, bool any_privileges, uint *hidden_bit_fields, bool returning_field); void make_leaves_list(THD *thd, List &list, TABLE_LIST *tables, bool full_table_list, TABLE_LIST *boundary); int setup_wild(THD *thd, TABLE_LIST *tables, List &fields, List *sum_func_list, SELECT_LEX *sl, bool returning_field); int setup_returning_fields(THD* thd, TABLE_LIST* table_list); bool setup_fields(THD *thd, Ref_ptr_array ref_pointer_array, List &item, enum_column_usage column_usage, List *sum_func_list, List *pre_fix, bool allow_sum_func, THD_WHERE where= THD_WHERE::DEFAULT_WHERE); void unfix_fields(List &items); bool fill_record(THD * thd, TABLE *table_arg, List &fields, List &values, bool ignore_errors, bool update); bool fill_record(THD *thd, TABLE *table, Field **field, List &values, bool ignore_errors, bool use_value, bool check_for_evaluability); Field * find_field_in_tables(THD *thd, Item_ident *item, TABLE_LIST *first_table, TABLE_LIST *last_table, ignored_tables_list_t ignored_tables, Item **ref, find_item_error_report_type report_error, bool check_privileges, bool register_tree_change); Field * find_field_in_table_ref(THD *thd, TABLE_LIST *table_list, const char *name, size_t length, const char *item_name, const char *db_name, const char *table_name, ignored_tables_list_t ignored_tables, Item **ref, bool check_privileges, bool allow_rowid, field_index_t *cached_field_index_ptr, bool register_tree_change, TABLE_LIST **actual_table); Field * find_field_in_table(THD *thd, TABLE *table, const char *name, size_t length, bool allow_rowid, field_index_t *cached_field_index_ptr); Field * find_field_in_table_sef(TABLE *table, const char *name); Item ** find_item_in_list(Item *item, List &items, uint *counter, find_item_error_report_type report_error, enum_resolution_type *resolution, uint limit= 0); bool setup_tables(THD *thd, Name_resolution_context *context, List *from_clause, TABLE_LIST *tables, List &leaves, bool select_insert, bool full_table_list); bool setup_tables_and_check_access(THD *thd, Name_resolution_context *context, List *from_clause, TABLE_LIST *tables, List &leaves, bool select_insert, privilege_t want_access_first, privilege_t want_access, bool full_table_list); bool wait_while_table_is_used(THD *thd, TABLE *table, enum ha_extra_function function); void drop_open_table(THD *thd, TABLE *table, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name); void update_non_unique_table_error(TABLE_LIST *update, const char *operation, TABLE_LIST *duplicate); int setup_conds(THD *thd, TABLE_LIST *tables, List &leaves, COND **conds); void wrap_ident(THD *thd, Item **conds); int setup_ftfuncs(SELECT_LEX* select); void cleanup_ftfuncs(SELECT_LEX *select_lex); int init_ftfuncs(THD *thd, SELECT_LEX* select, bool no_order); bool lock_table_names(THD *thd, const DDL_options_st &options, TABLE_LIST *table_list, TABLE_LIST *table_list_end, ulong lock_wait_timeout, uint flags); static inline bool lock_table_names(THD *thd, TABLE_LIST *table_list, TABLE_LIST *table_list_end, ulong lock_wait_timeout, uint flags) { return lock_table_names(thd, thd->lex->create_info, table_list, table_list_end, lock_wait_timeout, flags); } bool open_tables(THD *thd, const DDL_options_st &options, TABLE_LIST **tables, uint *counter, uint flags, Prelocking_strategy *prelocking_strategy); static inline bool open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags, Prelocking_strategy *prelocking_strategy) { return open_tables(thd, thd->lex->create_info, tables, counter, flags, prelocking_strategy); } /* open_and_lock_tables with optional derived handling */ bool open_and_lock_tables(THD *thd, const DDL_options_st &options, TABLE_LIST *tables, bool derived, uint flags, Prelocking_strategy *prelocking_strategy); static inline bool open_and_lock_tables(THD *thd, TABLE_LIST *tables, bool derived, uint flags, Prelocking_strategy *prelocking_strategy) { return open_and_lock_tables(thd, thd->lex->create_info, tables, derived, flags, prelocking_strategy); } /* simple open_and_lock_tables without derived handling for single table */ TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l, thr_lock_type lock_type, uint flags, Prelocking_strategy *prelocking_strategy); bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags, uint dt_phases); bool open_tables_only_view_structure(THD *thd, TABLE_LIST *tables, bool can_deadlock); bool open_and_lock_internal_tables(TABLE *table, bool lock); bool lock_tables(THD *thd, TABLE_LIST *tables, uint counter, uint flags); int decide_logging_format(THD *thd, TABLE_LIST *tables); void close_thread_table(THD *thd, TABLE **table_ptr); TABLE_LIST* unique_table_in_insert_returning_subselect(THD *thd, TABLE_LIST *table, SELECT_LEX *sel); TABLE_LIST *unique_table(THD *thd, TABLE_LIST *table, TABLE_LIST *table_list, uint check_flag); bool is_equal(const LEX_CSTRING *a, const LEX_CSTRING *b); class Open_tables_backup; /* Functions to work with system tables. */ bool open_system_tables_for_read(THD *thd, TABLE_LIST *table_list); void close_system_tables(THD *thd); void close_mysql_tables(THD *thd); TABLE *open_system_table_for_update(THD *thd, TABLE_LIST *one_table); TABLE *open_log_table(THD *thd, TABLE_LIST *one_table, Open_tables_backup *backup); void close_log_table(THD *thd, Open_tables_backup *backup); bool close_cached_tables(THD *thd, TABLE_LIST *tables, bool wait_for_refresh, ulong timeout); void purge_tables(); bool flush_tables(THD *thd, flush_tables_type flag); void close_all_tables_for_name(THD *thd, TABLE_SHARE *share, ha_extra_function extra, TABLE *skip_table); OPEN_TABLE_LIST *list_open_tables(THD *thd, const LEX_CSTRING &db, const char *wild); bool tdc_open_view(THD *thd, TABLE_LIST *table_list, uint flags); TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db, const char *table_name, int *p_error); void mark_tmp_table_for_reuse(TABLE *table); int dynamic_column_error_message(enum_dyncol_func_result rc); /* open_and_lock_tables with optional derived handling */ int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived); extern "C" qsort_cmp2 simple_raw_key_cmp; extern "C" int count_distinct_walk(void *elem, element_count count, void *arg); int simple_str_key_cmp(void *arg, const void *key1, const void *key2); extern Item **not_found_item; extern Field *not_found_field; extern Field *view_ref_found; /** clean/setup table fields and map. @param table TABLE structure pointer (which should be setup) @param table_list TABLE_LIST structure pointer (owner of TABLE) @param tablenr table number */ inline void setup_table_map(TABLE *table, TABLE_LIST *table_list, uint tablenr) { table->used_fields= 0; table_list->reset_const_table(); table->null_row= 0; table->status= STATUS_NO_RECORD; table->maybe_null= table_list->outer_join; TABLE_LIST *embedding= table_list->embedding; while (!table->maybe_null && embedding) { table->maybe_null= embedding->outer_join; embedding= embedding->embedding; } DBUG_ASSERT(tablenr <= MAX_TABLES); table->tablenr= tablenr; table->map= (table_map) 1 << tablenr; table->force_index= table_list->force_index; table->force_index_order= table->force_index_group= 0; table->covering_keys= table->s->keys_for_keyread; } inline TABLE_LIST *find_table_in_global_list(TABLE_LIST *table, LEX_CSTRING *db_name, LEX_CSTRING *table_name) { return find_table_in_list(table, &TABLE_LIST::next_global, db_name, table_name); } inline bool setup_fields_with_no_wrap(THD *thd, Ref_ptr_array ref_pointer_array, List &item, enum_column_usage column_usage, List *sum_func_list, bool allow_sum_func, THD_WHERE where= THD_WHERE::DEFAULT_WHERE) { bool res; SELECT_LEX *first= thd->lex->first_select_lex(); DBUG_ASSERT(thd->lex->current_select == first); first->no_wrap_view_item= TRUE; res= setup_fields(thd, ref_pointer_array, item, column_usage, sum_func_list, NULL, allow_sum_func, where); first->no_wrap_view_item= FALSE; return res; } /** An abstract class for a strategy specifying how the prelocking algorithm should extend the prelocking set while processing already existing elements in the set. */ class Prelocking_strategy { public: virtual ~Prelocking_strategy() = default; virtual void reset(THD *thd) { }; virtual bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx, Sroutine_hash_entry *rt, sp_head *sp, bool *need_prelocking) = 0; virtual bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking) = 0; virtual bool handle_view(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking)= 0; virtual bool handle_end(THD *thd) { return 0; }; }; /** A Strategy for prelocking algorithm suitable for DML statements. Ensures that all tables used by all statement's SF/SP/triggers and required for foreign key checks are prelocked and SF/SPs used are cached. */ class DML_prelocking_strategy : public Prelocking_strategy { public: bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx, Sroutine_hash_entry *rt, sp_head *sp, bool *need_prelocking) override; bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking) override; bool handle_view(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking) override; }; /** A strategy for prelocking algorithm to be used for LOCK TABLES statement. */ class Lock_tables_prelocking_strategy : public DML_prelocking_strategy { bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking) override; }; /** Strategy for prelocking algorithm to be used for ALTER TABLE statements. Unlike DML or LOCK TABLES strategy, it doesn't prelock triggers, views or stored routines, since they are not used during ALTER. */ class Alter_table_prelocking_strategy : public Prelocking_strategy { public: bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx, Sroutine_hash_entry *rt, sp_head *sp, bool *need_prelocking) override; bool handle_table(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking) override; bool handle_view(THD *thd, Query_tables_list *prelocking_ctx, TABLE_LIST *table_list, bool *need_prelocking) override; }; inline bool open_tables(THD *thd, const DDL_options_st &options, TABLE_LIST **tables, uint *counter, uint flags) { DML_prelocking_strategy prelocking_strategy; return open_tables(thd, options, tables, counter, flags, &prelocking_strategy); } inline bool open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags) { DML_prelocking_strategy prelocking_strategy; return open_tables(thd, thd->lex->create_info, tables, counter, flags, &prelocking_strategy); } inline TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l, thr_lock_type lock_type, uint flags) { DML_prelocking_strategy prelocking_strategy; return open_n_lock_single_table(thd, table_l, lock_type, flags, &prelocking_strategy); } /* open_and_lock_tables with derived handling */ inline bool open_and_lock_tables(THD *thd, const DDL_options_st &options, TABLE_LIST *tables, bool derived, uint flags) { DML_prelocking_strategy prelocking_strategy; return open_and_lock_tables(thd, options, tables, derived, flags, &prelocking_strategy); } inline bool open_and_lock_tables(THD *thd, TABLE_LIST *tables, bool derived, uint flags) { DML_prelocking_strategy prelocking_strategy; return open_and_lock_tables(thd, thd->lex->create_info, tables, derived, flags, &prelocking_strategy); } bool restart_trans_for_tables(THD *thd, TABLE_LIST *table); bool extend_table_list(THD *thd, TABLE_LIST *tables, Prelocking_strategy *prelocking_strategy, bool has_prelocking_list); /** A context of open_tables() function, used to recover from a failed open_table() or open_routine() attempt. */ class Open_table_context { public: enum enum_open_table_action { OT_NO_ACTION= 0, OT_BACKOFF_AND_RETRY, OT_REOPEN_TABLES, OT_DISCOVER, OT_REPAIR }; Open_table_context(THD *thd, uint flags); bool recover_from_failed_open(); bool request_backoff_action(enum_open_table_action action_arg, TABLE_LIST *table); bool can_recover_from_failed_open() const { return m_action != OT_NO_ACTION; } /** When doing a back-off, we close all tables acquired by this statement. Return an MDL savepoint taken at the beginning of the statement, so that we can rollback to it before waiting on locks. */ const MDL_savepoint &start_of_statement_svp() const { return m_start_of_statement_svp; } inline ulong get_timeout() const { return m_timeout; } uint get_flags() const { return m_flags; } /** Set flag indicating that we have already acquired metadata lock protecting this statement against GRL while opening tables. */ void set_has_protection_against_grl(enum_mdl_type mdl_type) { m_has_protection_against_grl|= MDL_BIT(mdl_type); } bool has_protection_against_grl(enum_mdl_type mdl_type) const { return (bool) (m_has_protection_against_grl & MDL_BIT(mdl_type)); } private: /* THD for which tables are opened. */ THD *m_thd; /** For OT_DISCOVER and OT_REPAIR actions, the table list element for the table which definition should be re-discovered or which should be repaired. */ TABLE_LIST *m_failed_table; MDL_savepoint m_start_of_statement_svp; /** Lock timeout in seconds. Initialized to LONG_TIMEOUT when opening system tables or to the "lock_wait_timeout" system variable for regular tables. */ ulong m_timeout; /* open_table() flags. */ uint m_flags; /** Back off action. */ enum enum_open_table_action m_action; /** Whether we had any locks when this context was created. If we did, they are from the previous statement of a transaction, and we can't safely do back-off (and release them). */ bool m_has_locks; /** Indicates that in the process of opening tables we have acquired protection against global read lock. */ mdl_bitmap_t m_has_protection_against_grl; }; /** Check if a TABLE_LIST instance represents a pre-opened temporary table. */ inline bool is_temporary_table(TABLE_LIST *tl) { if (tl->view || tl->schema_table) return FALSE; if (!tl->table) return FALSE; /* NOTE: 'table->s' might be NULL for specially constructed TABLE instances. See SHOW TRIGGERS for example. */ if (!tl->table->s) return FALSE; return tl->table->s->tmp_table != NO_TMP_TABLE; } /** This internal handler is used to trap ER_NO_SUCH_TABLE. */ class No_such_table_error_handler : public Internal_error_handler { public: No_such_table_error_handler() : m_handled_errors(0), m_unhandled_errors(0), first_error(0) {} bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition ** cond_hdl) override; /** Returns TRUE if one or more ER_NO_SUCH_TABLE errors have been trapped and no other errors have been seen. FALSE otherwise. */ bool safely_trapped_errors(); uint got_error() { return first_error; } private: int m_handled_errors; int m_unhandled_errors; uint first_error; }; #endif /* SQL_BASE_INCLUDED */ mysql/server/private/procedure.h000064400000015200151027430560013033 0ustar00#ifndef PROCEDURE_INCLUDED #define PROCEDURE_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* When using sql procedures */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif /* It is necessary to include set_var.h instead of item.h because there are dependencies on include order for set_var.h and item.h. This will be resolved later. */ #include "sql_class.h" /* select_result, set_var.h: THD */ #include "set_var.h" /* Item */ #define PROC_NO_SORT 1 /**< Bits in flags */ #define PROC_GROUP 2 /**< proc must have group */ /* Procedure items used by procedures to store values for send_result_set_metadata */ class Item_proc :public Item { public: Item_proc(THD *thd, const char *name_par): Item(thd) { this->name.str= name_par; this->name.length= strlen(name_par); } enum Type type() const override { return Item::PROC_ITEM; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { /* We can get to here when using a CURSOR for a query with PROCEDURE: DECLARE c CURSOR FOR SELECT * FROM t1 PROCEDURE analyse(); OPEN c; */ return create_tmp_field_ex_simple(root, table, src, param); } virtual void set(double nr)=0; virtual void set(const char *str,uint length,CHARSET_INFO *cs)=0; virtual void set(longlong nr)=0; const Type_handler *type_handler() const override=0; void set(const char *str) { set(str,(uint) strlen(str), default_charset()); } unsigned int size_of() { return sizeof(*this);} bool check_vcol_func_processor(void *arg) override { DBUG_ASSERT(0); // impossible return mark_unsupported_function("proc", arg, VCOL_IMPOSSIBLE); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } Item* do_get_copy(THD *thd) const override { return 0; } }; class Item_proc_real :public Item_proc { double value; public: Item_proc_real(THD *thd, const char *name_par, uint dec): Item_proc(thd, name_par) { decimals=dec; max_length=float_length(dec); } const Type_handler *type_handler() const override { return &type_handler_double; } void set(double nr) override { value=nr; } void set(longlong nr) override { value=(double) nr; } void set(const char *str,uint length,CHARSET_INFO *cs) override { int err_not_used; char *end_not_used; value= cs->strntod((char*) str,length, &end_not_used, &err_not_used); } double val_real() override { return value; } longlong val_int() override { return (longlong) value; } String *val_str(String *s) override { s->set_real(value,decimals,default_charset()); return s; } my_decimal *val_decimal(my_decimal *) override; unsigned int size_of() { return sizeof(*this);} }; class Item_proc_int :public Item_proc { longlong value; public: Item_proc_int(THD *thd, const char *name_par): Item_proc(thd, name_par) { max_length=11; } const Type_handler *type_handler() const override { if (unsigned_flag) return &type_handler_ulonglong; return &type_handler_slonglong; } void set(double nr) override { value=(longlong) nr; } void set(longlong nr) override { value=nr; } void set(const char *str,uint length, CHARSET_INFO *cs) override { int err; value= cs->strntoll(str,length,10,NULL,&err); } double val_real() override { return (double) value; } longlong val_int() override { return value; } String *val_str(String *s) override { s->set(value, default_charset()); return s; } my_decimal *val_decimal(my_decimal *) override; unsigned int size_of() { return sizeof(*this);} Item *do_get_copy(THD *thd) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } }; class Item_proc_string :public Item_proc { String value; public: Item_proc_string(THD *thd, const char *name_par, uint length): Item_proc(thd, name_par) { this->max_length=length; value.set_thread_specific(); } const Type_handler *type_handler() const override { return &type_handler_varchar; } void set(double nr) override { value.set_real(nr, 2, default_charset()); } void set(longlong nr) override { value.set(nr, default_charset()); } void set(const char *str, uint length, CHARSET_INFO *cs) override { value.copy(str,length,cs); } double val_real() override { int err_not_used; char *end_not_used; CHARSET_INFO *cs= value.charset(); return cs->strntod((char*) value.ptr(), value.length(), &end_not_used, &err_not_used); } longlong val_int() override { int err; CHARSET_INFO *cs=value.charset(); return cs->strntoll(value.ptr(), value.length(), 10, NULL, &err); } String *val_str(String*) override { return null_value ? (String*) 0 : &value; } my_decimal *val_decimal(my_decimal *) override; void cleanup() override { value.free(); } unsigned int size_of() { return sizeof(*this);} Item *do_get_copy(THD *thd) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } }; /* The procedure class definitions */ class Procedure { protected: List *fields; select_result *result; public: const uint flags; ORDER *group,*param_fields; Procedure(select_result *res,uint flags_par) :result(res),flags(flags_par), group(0),param_fields(0) {} virtual ~Procedure() {group=param_fields=0; fields=0; } virtual void add(void)=0; virtual void end_group(void)=0; virtual int send_row(List &fields)=0; virtual bool change_columns(THD *thd, List &fields)= 0; virtual void update_refs(void) {} virtual int end_of_records() { return 0; } }; Procedure *setup_procedure(THD *thd,ORDER *proc_param,select_result *result, List &field_list,int *error); #endif /* PROCEDURE_INCLUDED */ mysql/server/private/sql_partition.h000064400000027450151027430560013745 0ustar00#ifndef SQL_PARTITION_INCLUDED #define SQL_PARTITION_INCLUDED /* Copyright (c) 2006, 2017, Oracle and/or its affiliates. Copyright (c) 2011, 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_list.h" /* List */ #include "table.h" /* TABLE_LIST */ class Alter_info; class Alter_table_ctx; class Field; class String; class handler; class partition_info; struct TABLE; struct TABLE_LIST; typedef struct st_bitmap MY_BITMAP; typedef struct st_key KEY; typedef struct st_key_range key_range; /* Flags for partition handlers */ #define HA_CAN_PARTITION (1 << 0) /* Partition support */ #define HA_CAN_UPDATE_PARTITION_KEY (1 << 1) #define HA_CAN_PARTITION_UNIQUE (1 << 2) #define HA_USE_AUTO_PARTITION (1 << 3) #define HA_ONLY_VERS_PARTITION (1 << 4) #define NORMAL_PART_NAME 0 #define TEMP_PART_NAME 1 #define RENAMED_PART_NAME 2 typedef struct st_lock_param_type { TABLE_LIST *table_list; ulonglong copied; ulonglong deleted; THD *thd; HA_CREATE_INFO *create_info; Alter_info *alter_info; TABLE *table; KEY *key_info_buffer; LEX_CUSTRING org_tabledef_version; uchar *pack_frm_data; uint key_count; uint db_options; size_t pack_frm_len; partition_info *part_info; } ALTER_PARTITION_PARAM_TYPE; typedef struct { longlong list_value; uint32 partition_id; } LIST_PART_ENTRY; typedef struct { uint32 start_part; uint32 end_part; } part_id_range; class String_list; struct st_partition_iter; #define NOT_A_PARTITION_ID UINT_MAX32 bool is_partition_in_list(char *part_name, List list_part_names); char *are_partitions_in_table(partition_info *new_part_info, partition_info *old_part_info); bool check_reorganise_list(partition_info *new_part_info, partition_info *old_part_info, List list_part_names); handler *get_ha_partition(partition_info *part_info); int get_part_for_buf(const uchar *buf, const uchar *rec0, partition_info *part_info, uint32 *part_id); void prune_partition_set(const TABLE *table, part_id_range *part_spec); bool check_partition_info(partition_info *part_info,handlerton **eng_type, TABLE *table, handler *file, HA_CREATE_INFO *info); void set_linear_hash_mask(partition_info *part_info, uint num_parts); bool fix_partition_func(THD *thd, TABLE *table, bool create_table_ind); void get_partition_set(const TABLE *table, uchar *buf, const uint index, const key_range *key_spec, part_id_range *part_spec); uint get_partition_field_store_length(Field *field); void get_full_part_id_from_key(const TABLE *table, uchar *buf, KEY *key_info, const key_range *key_spec, part_id_range *part_spec); bool mysql_unpack_partition(THD *thd, char *part_buf, uint part_info_len, TABLE *table, bool is_create_table_ind, handlerton *default_db_type, bool *work_part_info_used); void make_used_partitions_str(MEM_ROOT *mem_root, partition_info *part_info, String *parts_str, String_list &used_partitions_list); uint32 get_list_array_idx_for_endpoint(partition_info *part_info, bool left_endpoint, bool include_endpoint); uint32 get_partition_id_range_for_endpoint(partition_info *part_info, bool left_endpoint, bool include_endpoint); bool check_part_func_fields(Field **ptr, bool ok_with_charsets); bool field_is_partition_charset(Field *field); Item* convert_charset_partition_constant(Item *item, CHARSET_INFO *cs); /** Append all fields in read_set to string @param[in,out] str String to append to. @param[in] row Row to append. @param[in] table Table containing read_set and fields for the row. */ void append_row_to_str(String &str, const uchar *row, TABLE *table); void truncate_partition_filename(char *path); /* A "Get next" function for partition iterator. SYNOPSIS partition_iter_func() part_iter Partition iterator, you call only "iter.get_next(&iter)" DESCRIPTION Depending on whether partitions or sub-partitions are iterated, the function returns next subpartition id/partition number. The sequence of returned numbers is not ordered and may contain duplicates. When the end of sequence is reached, NOT_A_PARTITION_ID is returned, and the iterator resets itself (so next get_next() call will start to enumerate the set all over again). RETURN NOT_A_PARTITION_ID if there are no more partitions. [sub]partition_id of the next partition */ typedef uint32 (*partition_iter_func)(st_partition_iter* part_iter); /* Partition set iterator. Used to enumerate a set of [sub]partitions obtained in partition interval analysis (see get_partitions_in_range_iter). For the user, the only meaningful field is get_next, which may be used as follows: part_iterator.get_next(&part_iterator); Initialization is done by any of the following calls: - get_partitions_in_range_iter-type function call - init_single_partition_iterator() - init_all_partitions_iterator() Cleanup is not needed. */ typedef struct st_partition_iter { partition_iter_func get_next; /* Valid for "Interval mapping" in LIST partitioning: if true, let the iterator also produce id of the partition that contains NULL value. */ bool ret_null_part, ret_null_part_orig; /* We should return DEFAULT partition. */ bool ret_default_part, ret_default_part_orig; struct st_part_num_range { uint32 start; uint32 cur; uint32 end; }; struct st_field_value_range { longlong start; longlong cur; longlong end; }; union { struct st_part_num_range part_nums; struct st_field_value_range field_vals; }; partition_info *part_info; } PARTITION_ITERATOR; /* Get an iterator for set of partitions that match given field-space interval SYNOPSIS get_partitions_in_range_iter() part_info Partitioning info is_subpart store_length_array Length of fields packed in opt_range_key format min_val Left edge, field value in opt_range_key format max_val Right edge, field value in opt_range_key format min_len Length of minimum value max_len Length of maximum value flags Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE, NO_MAX_RANGE part_iter Iterator structure to be initialized DESCRIPTION Functions with this signature are used to perform "Partitioning Interval Analysis". This analysis is applicable for any type of [sub]partitioning by some function of a single fieldX. The idea is as follows: Given an interval "const1 <=? fieldX <=? const2", find a set of partitions that may contain records with value of fieldX within the given interval. The min_val, max_val and flags parameters specify the interval. The set of partitions is returned by initializing an iterator in *part_iter NOTES There are currently three functions of this type: - get_part_iter_for_interval_via_walking - get_part_iter_for_interval_cols_via_map - get_part_iter_for_interval_via_mapping RETURN 0 - No matching partitions, iterator not initialized 1 - Some partitions would match, iterator intialized for traversing them -1 - All partitions would match, iterator not initialized */ typedef int (*get_partitions_in_range_iter)(partition_info *part_info, bool is_subpart, uint32 *store_length_array, uchar *min_val, uchar *max_val, uint min_len, uint max_len, uint flags, PARTITION_ITERATOR *part_iter); #include "partition_info.h" #ifdef WITH_PARTITION_STORAGE_ENGINE uint fast_alter_partition_table(THD *thd, TABLE *table, Alter_info *alter_info, HA_CREATE_INFO *create_info, TABLE_LIST *table_list); bool set_part_state(Alter_info *alter_info, partition_info *tab_part_info, enum partition_state part_state); uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info, HA_CREATE_INFO *create_info, bool *partition_changed, bool *fast_alter_table); char *generate_partition_syntax(THD *thd, partition_info *part_info, uint *buf_length, bool show_partition_options, HA_CREATE_INFO *create_info, Alter_info *alter_info); char *generate_partition_syntax_for_frm(THD *thd, partition_info *part_info, uint *buf_length, HA_CREATE_INFO *create_info, Alter_info *alter_info); bool verify_data_with_partition(TABLE *table, TABLE *part_table, uint32 part_id); bool compare_partition_options(HA_CREATE_INFO *table_create_info, partition_element *part_elem); bool partition_key_modified(TABLE *table, const MY_BITMAP *fields); #else #define partition_key_modified(X,Y) 0 #endif int __attribute__((warn_unused_result)) create_partition_name(char *out, size_t outlen, const char *in1, const char *in2, uint name_variant, bool translate); int __attribute__((warn_unused_result)) create_subpartition_name(char *out, size_t outlen, const char *in1, const char *in2, const char *in3, uint name_variant); void set_key_field_ptr(KEY *key_info, const uchar *new_buf, const uchar *old_buf); /** Set up table for creating a partition. Copy info from partition to the table share so the created partition has the correct info. @param thd THD object @param share Table share to be updated. @param info Create info to be updated. @param part_elem partition_element containing the info. @return status @retval TRUE Error @retval FALSE Success @details Set up 1) Comment on partition 2) MAX_ROWS, MIN_ROWS on partition 3) Index file name on partition 4) Data file name on partition */ bool set_up_table_before_create(THD *thd, TABLE_SHARE *share, const char *partition_name_with_path, HA_CREATE_INFO *info, partition_element *part_elem); #endif /* SQL_PARTITION_INCLUDED */ mysql/server/private/sql_error.h000064400000115244151027430560013064 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_ERROR_H #define SQL_ERROR_H #include "sql_list.h" /* Sql_alloc, MEM_ROOT, list */ #include "sql_type_int.h" // Longlong_hybrid #include "sql_string.h" /* String */ #include "sql_plist.h" /* I_P_List */ #include "mysql_com.h" /* MYSQL_ERRMSG_SIZE */ #include "my_time.h" /* MYSQL_TIME */ #include "decimal.h" class THD; class my_decimal; class sp_condition_value; /* Types of LOG warnings, used by note_verbosity */ #define NOTE_VERBOSITY_NORMAL (1U << 0) /* Show warnings about keys parts that cannot be used */ #define NOTE_VERBOSITY_UNUSABLE_KEYS (1U << 1) /* Show warnings in explain for key parts that cannot be used */ #define NOTE_VERBOSITY_EXPLAIN (1U << 2) /////////////////////////////////////////////////////////////////////////// class Sql_state { protected: /** This member is always NUL terminated. */ char m_sqlstate[SQLSTATE_LENGTH + 1]; public: Sql_state() { memset(m_sqlstate, 0, sizeof(m_sqlstate)); } Sql_state(const char *sqlstate) { set_sqlstate(sqlstate); } const char* get_sqlstate() const { return m_sqlstate; } void set_sqlstate(const Sql_state *other) { *this= *other; } void set_sqlstate(const char *sqlstate) { memcpy(m_sqlstate, sqlstate, SQLSTATE_LENGTH); m_sqlstate[SQLSTATE_LENGTH]= '\0'; } bool eq(const Sql_state *other) const { return strcmp(m_sqlstate, other->m_sqlstate) == 0; } bool has_sql_state() const { return m_sqlstate[0] != '\0'; } /** Checks if this SQL state defines a WARNING condition. Note: m_sqlstate must contain a valid SQL-state. @retval true if this SQL state defines a WARNING condition. @retval false otherwise. */ inline bool is_warning() const { return m_sqlstate[0] == '0' && m_sqlstate[1] == '1'; } /** Checks if this SQL state defines a NOT FOUND condition. Note: m_sqlstate must contain a valid SQL-state. @retval true if this SQL state defines a NOT FOUND condition. @retval false otherwise. */ inline bool is_not_found() const { return m_sqlstate[0] == '0' && m_sqlstate[1] == '2'; } /** Checks if this SQL state defines an EXCEPTION condition. Note: m_sqlstate must contain a valid SQL-state. @retval true if this SQL state defines an EXCEPTION condition. @retval false otherwise. */ inline bool is_exception() const { return m_sqlstate[0] != '0' || m_sqlstate[1] > '2'; } }; class Sql_state_errno: public Sql_state { protected: /** MySQL extension, MYSQL_ERRNO condition item. SQL error number. One of ER_ codes from share/errmsg.txt. Set by set_error_status. */ uint m_sql_errno; public: Sql_state_errno() :m_sql_errno(0) { } Sql_state_errno(uint sql_errno) :m_sql_errno(sql_errno) { } Sql_state_errno(uint sql_errno, const char *sql_state) :Sql_state(sql_state), m_sql_errno(sql_errno) { } /** Get the SQL_ERRNO of this condition. @return the sql error number condition item. */ uint get_sql_errno() const { return m_sql_errno; } void set(uint sql_errno, const char *sqlstate) { m_sql_errno= sql_errno; set_sqlstate(sqlstate); } void clear() { m_sql_errno= 0; } }; class Sql_state_errno_level: public Sql_state_errno { public: /* Enumeration value describing the severity of the error. Note that these enumeration values must correspond to the indices of the sql_print_message_handlers array. */ enum enum_warning_level { WARN_LEVEL_NOTE, WARN_LEVEL_WARN, WARN_LEVEL_ERROR, WARN_LEVEL_END}; protected: /** Severity (error, warning, note) of this condition. */ enum_warning_level m_level; void assign_defaults(const Sql_state_errno *value); public: /** Get the error level of this condition. @return the error level condition item. */ enum_warning_level get_level() const { return m_level; } Sql_state_errno_level() :m_level(WARN_LEVEL_ERROR) { } Sql_state_errno_level(uint sqlerrno, const char* sqlstate, enum_warning_level level) :Sql_state_errno(sqlerrno, sqlstate), m_level(level) { } Sql_state_errno_level(const Sql_state_errno &state_errno, enum_warning_level level) :Sql_state_errno(state_errno), m_level(level) { } void clear() { m_level= WARN_LEVEL_ERROR; Sql_state_errno::clear(); } }; /* class Sql_user_condition_identity. Instances of this class uniquely idetify user defined conditions (EXCEPTION). SET sql_mode=ORACLE; CREATE PROCEDURE p1 AS a EXCEPTION; BEGIN RAISE a; EXCEPTION WHEN a THEN NULL; END; Currently a user defined condition is identified by a pointer to its parse time sp_condition_value instance. This can change when we add packages. See MDEV-10591. */ class Sql_user_condition_identity { protected: const sp_condition_value *m_user_condition_value; public: Sql_user_condition_identity() :m_user_condition_value(NULL) { } Sql_user_condition_identity(const sp_condition_value *value) :m_user_condition_value(value) { } const sp_condition_value *get_user_condition_value() const { return m_user_condition_value; } void set(const Sql_user_condition_identity &identity) { *this= identity; } void clear() { m_user_condition_value= NULL; } }; /** class Sql_condition_identity. Instances of this class uniquely identify conditions (including user-defined exceptions for sql_mode=ORACLE) and store everything that is needed for handler search purposes in sp_pcontext::find_handler(). */ class Sql_condition_identity: public Sql_state_errno_level, public Sql_user_condition_identity { public: Sql_condition_identity() = default; Sql_condition_identity(const Sql_state_errno_level &st, const Sql_user_condition_identity &ucid) :Sql_state_errno_level(st), Sql_user_condition_identity(ucid) { } Sql_condition_identity(const Sql_state_errno &st, enum_warning_level level, const Sql_user_condition_identity &ucid) :Sql_state_errno_level(st, level), Sql_user_condition_identity(ucid) { } Sql_condition_identity(uint sqlerrno, const char* sqlstate, enum_warning_level level, const Sql_user_condition_identity &ucid) :Sql_state_errno_level(sqlerrno, sqlstate, level), Sql_user_condition_identity(ucid) { } void clear() { Sql_state_errno_level::clear(); Sql_user_condition_identity::clear(); } }; class Sql_condition_items { protected: /** SQL CLASS_ORIGIN condition item. */ String m_class_origin; /** SQL SUBCLASS_ORIGIN condition item. */ String m_subclass_origin; /** SQL CONSTRAINT_CATALOG condition item. */ String m_constraint_catalog; /** SQL CONSTRAINT_SCHEMA condition item. */ String m_constraint_schema; /** SQL CONSTRAINT_NAME condition item. */ String m_constraint_name; /** SQL CATALOG_NAME condition item. */ String m_catalog_name; /** SQL SCHEMA_NAME condition item. */ String m_schema_name; /** SQL TABLE_NAME condition item. */ String m_table_name; /** SQL COLUMN_NAME condition item. */ String m_column_name; /** SQL CURSOR_NAME condition item. */ String m_cursor_name; Sql_condition_items() :m_class_origin((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_subclass_origin((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_constraint_catalog((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_constraint_schema((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_constraint_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_catalog_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_schema_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_table_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_column_name((const char*) NULL, 0, & my_charset_utf8mb3_bin), m_cursor_name((const char*) NULL, 0, & my_charset_utf8mb3_bin) { } void clear() { m_class_origin.length(0); m_subclass_origin.length(0); m_constraint_catalog.length(0); m_constraint_schema.length(0); m_constraint_name.length(0); m_catalog_name.length(0); m_schema_name.length(0); m_table_name.length(0); m_column_name.length(0); m_cursor_name.length(0); } }; /** Representation of a SQL condition. A SQL condition can be a completion condition (note, warning), or an exception condition (error, not found). */ class Sql_condition : public Sql_alloc, public Sql_condition_identity, public Sql_condition_items { public: /** Convert a bitmask consisting of MYSQL_TIME_{NOTE|WARN}_XXX bits to WARN_LEVEL_XXX */ static enum_warning_level time_warn_level(uint warnings) { return MYSQL_TIME_WARN_HAVE_WARNINGS(warnings) ? WARN_LEVEL_WARN : WARN_LEVEL_NOTE; } /** Get the MESSAGE_TEXT of this condition. @return the message text. */ const char* get_message_text() const; /** Get the MESSAGE_OCTET_LENGTH of this condition. @return the length in bytes of the message text. */ int get_message_octet_length() const; private: /* The interface of Sql_condition is mostly private, by design, so that only the following code: - various raise_error() or raise_warning() methods in class THD, - the implementation of SIGNAL / RESIGNAL / GET DIAGNOSTICS - catch / re-throw of SQL conditions in stored procedures (sp_rcontext) is allowed to create / modify a SQL condition. Enforcing this policy prevents confusion, since the only public interface available to the rest of the server implementation is the interface offered by the THD methods (THD::raise_error()), which should be used. */ friend class THD; friend class Warning_info; friend class Sql_cmd_common_signal; friend class Sql_cmd_signal; friend class Sql_cmd_resignal; friend class sp_rcontext; friend class Condition_information_item; /** Default constructor. This constructor is usefull when allocating arrays. Note that the init() method should be called to complete the Sql_condition. */ Sql_condition() :m_mem_root(NULL) { } /** Complete the Sql_condition initialisation. @param mem_root The memory root to use for the condition items of this condition */ void init(MEM_ROOT *mem_root) { DBUG_ASSERT(mem_root != NULL); DBUG_ASSERT(m_mem_root == NULL); m_mem_root= mem_root; } /** Constructor. @param mem_root The memory root to use for the condition items of this condition */ Sql_condition(MEM_ROOT *mem_root) :m_mem_root(mem_root) { DBUG_ASSERT(mem_root != NULL); } Sql_condition(MEM_ROOT *mem_root, const Sql_user_condition_identity &ucid) :Sql_condition_identity(Sql_state_errno_level(), ucid), m_mem_root(mem_root) { DBUG_ASSERT(mem_root != NULL); } /** Constructor for a fixed message text. @param mem_root - memory root @param value - the error number and the sql state for this condition @param level - the error level for this condition @param msg - the message text for this condition */ Sql_condition(MEM_ROOT *mem_root, const Sql_condition_identity &value, const char *msg) :Sql_condition_identity(value), m_mem_root(mem_root) { DBUG_ASSERT(mem_root != NULL); DBUG_ASSERT(value.get_sql_errno() != 0); DBUG_ASSERT(msg != NULL); set_builtin_message_text(msg); } /** Destructor. */ ~Sql_condition() = default; /** Copy optional condition items attributes. @param cond the condition to copy. */ void copy_opt_attributes(const Sql_condition *cond); /** Set the condition message test. @param str Message text, expressed in the character set derived from the server --language option */ void set_builtin_message_text(const char* str); /** Set the CLASS_ORIGIN of this condition. */ void set_class_origin(); /** Set the SUBCLASS_ORIGIN of this condition. */ void set_subclass_origin(); /** Assign the condition items 'MYSQL_ERRNO', 'level' and 'MESSAGE_TEXT' default values of a condition. @param thd - current thread, to access to localized error messages @param from - copy condition items from here (can be NULL) */ void assign_defaults(THD *thd, const Sql_state_errno *from); /** Clear this SQL condition. */ void clear() { Sql_condition_identity::clear(); Sql_condition_items::clear(); m_message_text.length(0); } private: /** Message text, expressed in the character set implied by --language. */ String m_message_text; /** Pointers for participating in the list of conditions. */ Sql_condition *next_in_wi; Sql_condition **prev_in_wi; /** Memory root to use to hold condition item values. */ MEM_ROOT *m_mem_root; }; /////////////////////////////////////////////////////////////////////////// /** Information about warnings of the current connection. */ class Warning_info { /** The type of the counted and doubly linked list of conditions. */ typedef I_P_List, I_P_List_counter, I_P_List_fast_push_back > Sql_condition_list; /** A memory root to allocate warnings and errors */ MEM_ROOT m_warn_root; /** List of warnings of all severities (levels). */ Sql_condition_list m_warn_list; /** A break down of the number of warnings per severity (level). */ uint m_warn_count[(uint) Sql_condition::WARN_LEVEL_END]; /** The number of warnings of the current statement. Warning_info life cycle differs from statement life cycle -- it may span multiple statements. In that case we get m_current_statement_warn_count 0, whereas m_warn_list is not empty. */ uint m_current_statement_warn_count; /* Row counter, to print in errors and warnings. Not increased in create_sort_index(); may differ from examined_row_count. */ ulong m_current_row_for_warning; /** Used to optionally clear warnings only once per statement. */ ulonglong m_warn_id; /** A pointer to an element of m_warn_list. It determines SQL-condition instance which corresponds to the error state in Diagnostics_area. This is needed for properly processing SQL-conditions in SQL-handlers. When an SQL-handler is found for the current error state in Diagnostics_area, this pointer is needed to remove the corresponding SQL-condition from the Warning_info list. @note m_error_condition might be NULL in the following cases: - Diagnostics_area set to fatal error state (like OOM); - Max number of Warning_info elements has been reached (thus, there is no corresponding SQL-condition object in Warning_info). */ const Sql_condition *m_error_condition; /** Indicates if push_warning() allows unlimited number of warnings. */ bool m_allow_unlimited_warnings; bool initialized; /* Set to 1 if init() has been called */ /** Read only status. */ bool m_read_only; /** Pointers for participating in the stack of Warning_info objects. */ Warning_info *m_next_in_da; Warning_info **m_prev_in_da; List m_marked_sql_conditions; public: Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings, bool initialized); ~Warning_info(); /* Allocate memory for structures */ void init(); void free_memory(); private: Warning_info(const Warning_info &rhs); /* Not implemented */ Warning_info& operator=(const Warning_info &rhs); /* Not implemented */ /** Checks if Warning_info contains SQL-condition with the given message. @param message_str Message string. @param message_length Length of message string. @return true if the Warning_info contains an SQL-condition with the given message. */ bool has_sql_condition(const char *message_str, size_t message_length) const; /** Checks if Warning_info contains SQL-condition with the given error id @param sql_errno SQL-condition error number @return true if the Warning_info contains an SQL-condition with the given error id. */ bool has_sql_condition(uint sql_errno) const; /** Reset the warning information. Clear all warnings, the number of warnings, reset current row counter to point to the first row. @param new_id new Warning_info id. */ void clear(ulonglong new_id); /** Only clear warning info if haven't yet done that already for the current query. Allows to be issued at any time during the query, without risk of clearing some warnings that have been generated by the current statement. @todo: This is a sign of sloppy coding. Instead we need to designate one place in a statement life cycle where we call Warning_info::clear(). @param query_id Current query id. */ void opt_clear(ulonglong query_id) { if (query_id != m_warn_id) clear(query_id); } /** Concatenate the list of warnings. It's considered tolerable to lose an SQL-condition in case of OOM-error, or if the number of SQL-conditions in the Warning_info reached top limit. @param thd Thread context. @param source Warning_info object to copy SQL-conditions from. */ void append_warning_info(THD *thd, const Warning_info *source); /** Reset between two COM_ commands. Warnings are preserved between commands, but statement_warn_count indicates the number of warnings of this particular statement only. */ void reset_for_next_command() { m_current_statement_warn_count= 0; } /** Mark active SQL-conditions for later removal. This is done to simulate stacked DAs for HANDLER statements. */ void mark_sql_conditions_for_removal(); /** Unmark SQL-conditions, which were marked for later removal. This is done to simulate stacked DAs for HANDLER statements. */ void unmark_sql_conditions_from_removal() { m_marked_sql_conditions.empty(); } /** Remove SQL-conditions that are marked for deletion. This is done to simulate stacked DAs for HANDLER statements. */ void remove_marked_sql_conditions(); /** Check if the given SQL-condition is marked for removal in this Warning_info instance. @param cond the SQL-condition. @retval true if the given SQL-condition is marked for removal in this Warning_info instance. @retval false otherwise. */ bool is_marked_for_removal(const Sql_condition *cond) const; /** Mark a single SQL-condition for removal (add the given SQL-condition to the removal list of this Warning_info instance). */ void mark_condition_for_removal(Sql_condition *cond) { m_marked_sql_conditions.push_back(cond, &m_warn_root); } /** Used for @@warning_count system variable, which prints the number of rows returned by SHOW WARNINGS. */ ulong warn_count() const { /* This may be higher than warn_list.elements() if we have had more warnings than thd->variables.max_error_count. */ return (m_warn_count[(uint) Sql_condition::WARN_LEVEL_NOTE] + m_warn_count[(uint) Sql_condition::WARN_LEVEL_ERROR] + m_warn_count[(uint) Sql_condition::WARN_LEVEL_WARN]); } /** The number of errors, or number of rows returned by SHOW ERRORS, also the value of session variable @@error_count. */ ulong error_count() const { return m_warn_count[(uint) Sql_condition::WARN_LEVEL_ERROR]; } /** The number of conditions (errors, warnings and notes) in the list. */ uint cond_count() const { return m_warn_list.elements(); } /** Id of the warning information area. */ ulonglong id() const { return m_warn_id; } /** Set id of the warning information area. */ void id(ulonglong id_arg) { m_warn_id= id_arg; } /** Do we have any errors and warnings that we can *show*? */ bool is_empty() const { return m_warn_list.is_empty(); } /** Increment the current row counter to point at the next row. */ void inc_current_row_for_warning() { m_current_row_for_warning++; } /** Reset the current row counter. Start counting from the first row. */ void reset_current_row_for_warning() { m_current_row_for_warning= 1; } ulong set_current_row_for_warning(ulong row) { ulong old_row= m_current_row_for_warning; m_current_row_for_warning= row; return old_row; } /** Return the current counter value. */ ulong current_row_for_warning() const { return m_current_row_for_warning; } /** Return the number of warnings thrown by the current statement. */ ulong current_statement_warn_count() const { return m_current_statement_warn_count; } /** Make sure there is room for the given number of conditions. */ void reserve_space(THD *thd, uint count); /** Add a new SQL-condition to the current list and increment the respective counters. @param thd Thread context. @param identity SQL-condition identity @param msg SQL-condition message. @return a pointer to the added SQL-condition. */ Sql_condition *push_warning(THD *thd, const Sql_condition_identity *identity, const char* msg); /** Add a new SQL-condition to the current list and increment the respective counters. @param thd Thread context. @param sql_condition SQL-condition to copy values from. @return a pointer to the added SQL-condition. */ Sql_condition *push_warning(THD *thd, const Sql_condition *sql_condition); /** Set the read only status for this statement area. This is a privileged operation, reserved for the implementation of diagnostics related statements, to enforce that the statement area is left untouched during execution. The diagnostics statements are: - SHOW WARNINGS - SHOW ERRORS - GET DIAGNOSTICS @param read_only the read only property to set. */ void set_read_only(bool read_only_arg) { m_read_only= read_only_arg; } /** Read only status. @return the read only property. */ bool is_read_only() const { return m_read_only; } /** @return SQL-condition, which corresponds to the error state in Diagnostics_area. @see m_error_condition. */ const Sql_condition *get_error_condition() const { return m_error_condition; } /** Set SQL-condition, which corresponds to the error state in Diagnostics_area. @see m_error_condition. */ void set_error_condition(const Sql_condition *error_condition) { m_error_condition= error_condition; } /** Reset SQL-condition, which corresponds to the error state in Diagnostics_area. @see m_error_condition. */ void clear_error_condition() { m_error_condition= NULL; } // for: // - m_next_in_da / m_prev_in_da // - is_marked_for_removal() friend class Diagnostics_area; }; extern size_t err_conv(char *buff, uint to_length, const char *from, uint from_length, CHARSET_INFO *from_cs); class ErrBuff { protected: mutable char err_buffer[MYSQL_ERRMSG_SIZE]; public: ErrBuff() { err_buffer[0]= '\0'; } const char *ptr() const { return err_buffer; } LEX_CSTRING set_longlong(const Longlong_hybrid &nr) const { int radix= nr.is_unsigned() ? 10 : -10; const char *end= longlong10_to_str(nr.value(), err_buffer, radix); DBUG_ASSERT(end >= err_buffer); return {err_buffer, (size_t) (end - err_buffer)}; } LEX_CSTRING set_double(double nr) const { size_t length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, sizeof(err_buffer), err_buffer, 0); return {err_buffer, length}; } LEX_CSTRING set_decimal(const decimal_t *d) const { int length= sizeof(err_buffer); decimal2string(d, err_buffer, &length, 0, 0, ' '); DBUG_ASSERT(length >= 0); return {err_buffer, (size_t) length}; } LEX_CSTRING set_str(const char *str, size_t len, CHARSET_INFO *cs) const { DBUG_ASSERT(len < UINT_MAX32); len= err_conv(err_buffer, (uint) sizeof(err_buffer), str, (uint) len, cs); return {err_buffer, len}; } LEX_CSTRING set_mysql_time(const MYSQL_TIME *ltime) const { int length= my_TIME_to_str(ltime, err_buffer, AUTO_SEC_PART_DIGITS); DBUG_ASSERT(length >= 0); return {err_buffer, (size_t) length}; } }; class ErrConv: public ErrBuff { public: ErrConv() = default; virtual ~ErrConv() = default; virtual LEX_CSTRING lex_cstring() const= 0; inline const char *ptr() const { return lex_cstring().str; } }; class ErrConvString : public ErrConv { const char *str; size_t len; CHARSET_INFO *cs; public: ErrConvString(const char *str_arg, size_t len_arg, CHARSET_INFO *cs_arg) : ErrConv(), str(str_arg), len(len_arg), cs(cs_arg) {} ErrConvString(const char *str_arg, CHARSET_INFO *cs_arg) : ErrConv(), str(str_arg), len(strlen(str_arg)), cs(cs_arg) {} ErrConvString(const String *s) : ErrConv(), str(s->ptr()), len(s->length()), cs(s->charset()) {} LEX_CSTRING lex_cstring() const override { return set_str(str, len, cs); } }; class ErrConvInteger : public ErrConv, public Longlong_hybrid { public: ErrConvInteger(const Longlong_hybrid &nr) : ErrConv(), Longlong_hybrid(nr) { } LEX_CSTRING lex_cstring() const override { return set_longlong(static_cast(*this)); } }; class ErrConvDouble: public ErrConv { double num; public: ErrConvDouble(double num_arg) : ErrConv(), num(num_arg) {} LEX_CSTRING lex_cstring() const override { return set_double(num); } }; class ErrConvTime : public ErrConv { const MYSQL_TIME *ltime; public: ErrConvTime(const MYSQL_TIME *ltime_arg) : ErrConv(), ltime(ltime_arg) {} LEX_CSTRING lex_cstring() const override { return set_mysql_time(ltime); } }; class ErrConvDecimal : public ErrConv { const decimal_t *d; public: ErrConvDecimal(const decimal_t *d_arg) : ErrConv(), d(d_arg) {} LEX_CSTRING lex_cstring() const override { return set_decimal(d); } }; /////////////////////////////////////////////////////////////////////////// /** Stores status of the currently executed statement. Cleared at the beginning of the statement, and then can hold either OK, ERROR, or EOF status. Can not be assigned twice per statement. */ class Diagnostics_area: public Sql_state_errno, public Sql_user_condition_identity { private: /** The type of the counted and doubly linked list of conditions. */ typedef I_P_List, I_P_List_counter, I_P_List_fast_push_back > Warning_info_list; public: /** Const iterator used to iterate through the warning list. */ typedef Warning_info::Sql_condition_list::Const_Iterator Sql_condition_iterator; enum enum_diagnostics_status { /** The area is cleared at start of a statement. */ DA_EMPTY= 0, /** Set whenever one calls my_ok(). */ DA_OK, /** Set whenever one calls my_eof(). */ DA_EOF, /** Set whenever one calls my_ok() in PS bulk mode. */ DA_OK_BULK, /** Set whenever one calls my_eof() in PS bulk mode. */ DA_EOF_BULK, /** Set whenever one calls my_error() or my_message(). */ DA_ERROR, /** Set in case of a custom response, such as one from COM_STMT_PREPARE. */ DA_DISABLED }; void set_overwrite_status(bool can_overwrite_status) { m_can_overwrite_status= can_overwrite_status; } /** True if status information is sent to the client. */ bool is_sent() const { return m_is_sent; } void set_is_sent(bool is_sent_arg) { m_is_sent= is_sent_arg; } void set_ok_status(ulonglong affected_rows, ulonglong last_insert_id, const char *message); void set_eof_status(THD *thd); void set_error_status(uint sql_errno); void set_error_status(uint sql_errno, const char *message, const char *sqlstate, const Sql_user_condition_identity &ucid, const Sql_condition *error_condition); void set_error_status(uint sql_errno, const char *message, const char *sqlstate, const Sql_condition *error_condition) { set_error_status(sql_errno, message, sqlstate, Sql_user_condition_identity(), error_condition); } void disable_status(); void reset_diagnostics_area(); bool is_set() const { return m_status != DA_EMPTY; } bool is_error() const { return m_status == DA_ERROR; } bool is_eof() const { return m_status == DA_EOF; } bool is_ok() const { return m_status == DA_OK; } bool is_disabled() const { return m_status == DA_DISABLED; } void set_bulk_execution(bool bulk) { is_bulk_execution= bulk; } bool is_bulk_op() const { return is_bulk_execution; } enum_diagnostics_status status() const { return m_status; } const char *message() const { DBUG_ASSERT(m_status == DA_ERROR || m_status == DA_OK || m_status == DA_OK_BULK || m_status == DA_EOF_BULK); return m_message; } uint sql_errno() const { DBUG_ASSERT(m_status == DA_ERROR); return Sql_state_errno::get_sql_errno(); } const char* get_sqlstate() const { DBUG_ASSERT(m_status == DA_ERROR); return Sql_state::get_sqlstate(); } ulonglong affected_rows() const { DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK); return m_affected_rows; } void set_message(const char *msg) { strmake_buf(m_message, msg); } ulonglong last_insert_id() const { DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK); return m_last_insert_id; } uint statement_warn_count() const { DBUG_ASSERT(m_status == DA_OK || m_status == DA_OK_BULK || m_status == DA_EOF ||m_status == DA_EOF_BULK ); return m_statement_warn_count; } uint unsafe_statement_warn_count() const { return m_statement_warn_count; } /** Get the current errno, state and id of the user defined condition and return them as Sql_condition_identity. */ Sql_condition_identity get_error_condition_identity() const { DBUG_ASSERT(m_status == DA_ERROR); return Sql_condition_identity(*this /*Sql_state_errno*/, Sql_condition::WARN_LEVEL_ERROR, *this /*Sql_user_condition_identity*/); } /* Used to count any warnings pushed after calling set_ok_status(). */ void increment_warning() { if (m_status != DA_EMPTY) m_statement_warn_count++; } Diagnostics_area(bool initialize); Diagnostics_area(ulonglong warning_info_id, bool allow_unlimited_warnings, bool initialize); void init() { m_main_wi.init() ; } void free_memory() { m_main_wi.free_memory() ; } void push_warning_info(Warning_info *wi) { m_wi_stack.push_front(wi); } void pop_warning_info() { DBUG_ASSERT(m_wi_stack.elements() > 0); m_wi_stack.remove(m_wi_stack.front()); } void set_warning_info_id(ulonglong id) { get_warning_info()->id(id); } ulonglong warning_info_id() const { return get_warning_info()->id(); } /** Compare given current warning info and current warning info and see if they are different. They will be different if warnings have been generated or statements that use tables have been executed. This is checked by comparing m_warn_id. @param wi Warning info to compare with current Warning info. @return false if they are equal, true if they are not. */ bool warning_info_changed(const Warning_info *wi) const { return get_warning_info()->id() != wi->id(); } bool is_warning_info_empty() const { return get_warning_info()->is_empty(); } ulong current_statement_warn_count() const { return get_warning_info()->current_statement_warn_count(); } bool has_sql_condition(const char *message_str, size_t message_length) const { return get_warning_info()->has_sql_condition(message_str, message_length); } bool has_sql_condition(uint sql_errno) const { return get_warning_info()->has_sql_condition(sql_errno); } void reset_for_next_command() { get_warning_info()->reset_for_next_command(); } void clear_warning_info(ulonglong id) { get_warning_info()->clear(id); } void opt_clear_warning_info(ulonglong query_id) { get_warning_info()->opt_clear(query_id); } long set_current_row_for_warning(long row) { return get_warning_info()->set_current_row_for_warning(row); } ulong current_row_for_warning() const { return get_warning_info()->current_row_for_warning(); } void inc_current_row_for_warning() { get_warning_info()->inc_current_row_for_warning(); } void reset_current_row_for_warning() { get_warning_info()->reset_current_row_for_warning(); } bool is_warning_info_read_only() const { return get_warning_info()->is_read_only(); } void set_warning_info_read_only(bool read_only_arg) { get_warning_info()->set_read_only(read_only_arg); } ulong error_count() const { return get_warning_info()->error_count(); } ulong warn_count() const { return get_warning_info()->warn_count(); } uint cond_count() const { return get_warning_info()->cond_count(); } Sql_condition_iterator sql_conditions() const { return get_warning_info()->m_warn_list; } void reserve_space(THD *thd, uint count) { get_warning_info()->reserve_space(thd, count); } Sql_condition *push_warning(THD *thd, const Sql_condition *sql_condition) { return get_warning_info()->push_warning(thd, sql_condition); } Sql_condition *push_warning(THD *thd, uint sql_errno_arg, const char* sqlstate, Sql_condition::enum_warning_level level, const Sql_user_condition_identity &ucid, const char* msg) { Sql_condition_identity tmp(sql_errno_arg, sqlstate, level, ucid); return get_warning_info()->push_warning(thd, &tmp, msg); } Sql_condition *push_warning(THD *thd, uint sqlerrno, const char* sqlstate, Sql_condition::enum_warning_level level, const char* msg) { return push_warning(thd, sqlerrno, sqlstate, level, Sql_user_condition_identity(), msg); } void mark_sql_conditions_for_removal() { get_warning_info()->mark_sql_conditions_for_removal(); } void unmark_sql_conditions_from_removal() { get_warning_info()->unmark_sql_conditions_from_removal(); } void remove_marked_sql_conditions() { get_warning_info()->remove_marked_sql_conditions(); } const Sql_condition *get_error_condition() const { return get_warning_info()->get_error_condition(); } void copy_sql_conditions_to_wi(THD *thd, Warning_info *dst_wi) const { dst_wi->append_warning_info(thd, get_warning_info()); } void copy_sql_conditions_from_wi(THD *thd, const Warning_info *src_wi) { get_warning_info()->append_warning_info(thd, src_wi); } void copy_non_errors_from_wi(THD *thd, const Warning_info *src_wi); private: Warning_info *get_warning_info() { return m_wi_stack.front(); } const Warning_info *get_warning_info() const { return m_wi_stack.front(); } private: /** True if status information is sent to the client. */ bool m_is_sent; /** Set to make set_error_status after set_{ok,eof}_status possible. */ bool m_can_overwrite_status; /** Message buffer. Can be used by OK or ERROR status. */ char m_message[MYSQL_ERRMSG_SIZE]; /** The number of rows affected by the last statement. This is semantically close to thd->m_row_count_func, but has a different life cycle. thd->m_row_count_func stores the value returned by function ROW_COUNT() and is cleared only by statements that update its value, such as INSERT, UPDATE, DELETE and few others. This member is cleared at the beginning of the next statement. We could possibly merge the two, but life cycle of thd->m_row_count_func can not be changed. */ ulonglong m_affected_rows; /** Similarly to the previous member, this is a replacement of thd->first_successful_insert_id_in_prev_stmt, which is used to implement LAST_INSERT_ID(). */ ulonglong m_last_insert_id; /** Number of warnings of this last statement. May differ from the number of warnings returned by SHOW WARNINGS e.g. in case the statement doesn't clear the warnings, and doesn't generate them. */ uint m_statement_warn_count; enum_diagnostics_status m_status; my_bool is_bulk_execution; Warning_info m_main_wi; Warning_info_list m_wi_stack; }; /////////////////////////////////////////////////////////////////////////// void convert_error_to_warning(THD *thd); void push_warning(THD *thd, Sql_condition::enum_warning_level level, uint code, const char *msg); void push_warning_printf(THD *thd, Sql_condition::enum_warning_level level, uint code, const char *format, ...); bool mysqld_show_warnings(THD *thd, ulong levels_to_show); size_t convert_error_message(char *to, size_t to_length, CHARSET_INFO *to_cs, const char *from, size_t from_length, CHARSET_INFO *from_cs, uint *errors); extern const LEX_CSTRING warning_level_names[]; bool is_sqlstate_valid(const LEX_CSTRING *sqlstate); /** Checks if the specified SQL-state-string defines COMPLETION condition. This function assumes that the given string contains a valid SQL-state. @param s the condition SQLSTATE. @retval true if the given string defines COMPLETION condition. @retval false otherwise. */ inline bool is_sqlstate_completion(const char *s) { return s[0] == '0' && s[1] == '0'; } #endif // SQL_ERROR_H mysql/server/private/tzfile.h000064400000011626151027430560012350 0ustar00#ifndef TZFILE_INCLUDED #define TZFILE_INCLUDED /* Copyright (c) 2004, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file is based on public domain code from ftp://elsie.ncih.nist.gov/ Initial source code is in the public domain, so clarified as of 1996-06-05 by Arthur David Olson (arthur_david_olson@nih.gov). */ /* Information about time zone files. */ #ifndef TZDIR #define TZDIR "/usr/share/zoneinfo" /* Time zone object file directory */ #endif /* !defined TZDIR */ /* Each file begins with. . . */ #define TZ_MAGIC "TZif" struct tzhead { uchar tzh_magic[4]; /* TZ_MAGIC */ uchar tzh_reserved[16]; /* reserved for future use */ uchar tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */ uchar tzh_ttisstdcnt[4]; /* coded number of trans. time flags */ uchar tzh_leapcnt[4]; /* coded number of leap seconds */ uchar tzh_timecnt[4]; /* coded number of transition times */ uchar tzh_typecnt[4]; /* coded number of local time types */ uchar tzh_charcnt[4]; /* coded number of abbr. chars */ }; /* . . .followed by. . . tzh_timecnt (char [4])s coded transition times a la time(2) tzh_timecnt (unsigned char)s types of local time starting at above tzh_typecnt repetitions of one (char [4]) coded UTC offset in seconds one (unsigned char) used to set tm_isdst one (unsigned char) that's an abbreviation list index tzh_charcnt (char)s '\0'-terminated zone abbreviations tzh_leapcnt repetitions of one (char [4]) coded leap second transition times one (char [4]) total correction after above tzh_ttisstdcnt (char)s indexed by type; if TRUE, transition time is standard time, if FALSE, transition time is wall clock time if absent, transition times are assumed to be wall clock time tzh_ttisgmtcnt (char)s indexed by type; if TRUE, transition time is UTC, if FALSE, transition time is local time if absent, transition times are assumed to be local time */ /* In the current implementation, we refuse to deal with files that exceed any of the limits below. */ #ifndef TZ_MAX_TIMES /* The TZ_MAX_TIMES value below is enough to handle a bit more than a year's worth of solar time (corrected daily to the nearest second) or 138 years of Pacific Presidential Election time (where there are three time zone transitions every fourth year). */ #define TZ_MAX_TIMES 370 #endif /* !defined TZ_MAX_TIMES */ #ifndef TZ_MAX_TYPES #ifdef SOLAR #define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */ #else /* Must be at least 14 for Europe/Riga as of Jan 12 1995, as noted by Earl Chew . */ #define TZ_MAX_TYPES 20 /* Maximum number of local time types */ #endif /* defined SOLAR */ #endif /* !defined TZ_MAX_TYPES */ #ifndef TZ_MAX_CHARS #define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */ /* (limited by what unsigned chars can hold) */ #endif /* !defined TZ_MAX_CHARS */ #ifndef TZ_MAX_LEAPS #define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ #endif /* !defined TZ_MAX_LEAPS */ #ifndef TZ_MAX_REV_RANGES #ifdef SOLAR /* Solar (Asia/RiyadhXX) zones need significantly bigger TZ_MAX_REV_RANGES */ #define TZ_MAX_REV_RANGES (TZ_MAX_TIMES*2+TZ_MAX_LEAPS*2+2) #else #define TZ_MAX_REV_RANGES (TZ_MAX_TIMES+TZ_MAX_LEAPS+2) #endif #endif #define SECS_PER_MIN 60 #define MINS_PER_HOUR 60 #define HOURS_PER_DAY 24 #define DAYS_PER_WEEK 7 #define DAYS_PER_NYEAR 365 #define DAYS_PER_LYEAR 366 #define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR) #define SECS_PER_DAY ((long) SECS_PER_HOUR * HOURS_PER_DAY) #define MONS_PER_YEAR 12 #define TM_YEAR_BASE 1900 #define EPOCH_YEAR 1970 /* Accurate only for the past couple of centuries, that will probably do. */ #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) #endif mysql/server/private/parse_file.h000064400000010443151027430560013160 0ustar00/* -*- C++ -*- */ /* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _PARSE_FILE_H_ #define _PARSE_FILE_H_ #include "sql_string.h" // LEX_STRING #include "sql_alloc.h" // Sql_alloc class THD; typedef struct st_mem_root MEM_ROOT; #define PARSE_FILE_TIMESTAMPLENGTH 19 enum file_opt_type { FILE_OPTIONS_STRING, /**< String (LEX_STRING) */ FILE_OPTIONS_ESTRING, /**< Escaped string (LEX_STRING) */ FILE_OPTIONS_ULONGLONG, /**< ulonglong parameter (ulonglong) */ FILE_OPTIONS_VIEW_ALGO, /**< Similar to longlong, but needs conversion */ FILE_OPTIONS_TIMESTAMP, /**< timestamp (LEX_STRING have to be allocated with length 20 (19+1) */ FILE_OPTIONS_STRLIST, /**< list of escaped strings (List) */ FILE_OPTIONS_ULLLIST /**< list of ulonglong values (List) */ }; struct File_option { LEX_CSTRING name; /**< Name of the option */ my_ptrdiff_t offset; /**< offset to base address of value */ file_opt_type type; /**< Option type */ }; /** This hook used to catch no longer supported keys and process them for backward compatibility. */ class Unknown_key_hook { public: Unknown_key_hook() = default; /* Remove gcc warning */ virtual ~Unknown_key_hook() = default; /* Remove gcc warning */ virtual bool process_unknown_string(const char *&unknown_key, uchar* base, MEM_ROOT *mem_root, const char *end)= 0; }; /** Dummy hook for parsers which do not need hook for unknown keys. */ class File_parser_dummy_hook: public Unknown_key_hook { public: File_parser_dummy_hook() = default; /* Remove gcc warning */ bool process_unknown_string(const char *&unknown_key, uchar* base, MEM_ROOT *mem_root, const char *end) override; }; extern File_parser_dummy_hook file_parser_dummy_hook; bool get_file_options_ulllist(const char *&ptr, const char *end, const char *line, uchar* base, File_option *parameter, MEM_ROOT *mem_root); const char * parse_escaped_string(const char *ptr, const char *end, MEM_ROOT *mem_root, LEX_CSTRING *str); class File_parser; File_parser *sql_parse_prepare(const LEX_CSTRING *file_name, MEM_ROOT *mem_root, bool bad_format_errors); my_bool sql_create_definition_file(const LEX_CSTRING *dir, const LEX_CSTRING *file_name, const LEX_CSTRING *type, uchar* base, File_option *parameters); my_bool rename_in_schema_file(THD *thd, const char *schema, const char *old_name, const char *new_db, const char *new_name); int sql_backup_definition_file(const LEX_CSTRING *org_name, LEX_CSTRING *new_name); int sql_restore_definition_file(const LEX_CSTRING *name); class File_parser: public Sql_alloc { char *start, *end; LEX_CSTRING file_type; bool content_ok; public: File_parser() :start(0), end(0), content_ok(0) { file_type.str= 0; file_type.length= 0; } bool ok() { return content_ok; } const LEX_CSTRING *type() const { return &file_type; } my_bool parse(uchar* base, MEM_ROOT *mem_root, struct File_option *parameters, uint required, Unknown_key_hook *hook) const; friend File_parser *sql_parse_prepare(const LEX_CSTRING *file_name, MEM_ROOT *mem_root, bool bad_format_errors); }; #endif /* _PARSE_FILE_H_ */ mysql/server/private/semisync.h000064400000004357151027430560012710 0ustar00/* Copyright (C) 2007 Google Inc. Copyright (C) 2008 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SEMISYNC_H #define SEMISYNC_H #include "mysqld.h" #include "log_event.h" #include "replication.h" /** This class is used to trace function calls and other process information */ class Trace { public: static const unsigned long k_trace_function; static const unsigned long k_trace_general; static const unsigned long k_trace_detail; static const unsigned long k_trace_net_wait; unsigned long m_trace_level; /* the level for tracing */ Trace() :m_trace_level(0L) {} Trace(unsigned long trace_level) :m_trace_level(trace_level) {} }; /** Base class for semi-sync master and slave classes */ class Repl_semi_sync_base :public Trace { public: static const unsigned char k_sync_header[2]; /* three byte packet header */ /* Constants in network packet header. */ static const unsigned char k_packet_magic_num; static const unsigned char k_packet_flag_sync; }; /* The layout of a semisync slave reply packet: 1 byte for the magic num 8 bytes for the binlog positon n bytes for the binlog filename, terminated with a '\0' */ #define REPLY_MAGIC_NUM_LEN 1 #define REPLY_BINLOG_POS_LEN 8 #define REPLY_BINLOG_NAME_LEN (FN_REFLEN + 1) #define REPLY_MAGIC_NUM_OFFSET 0 #define REPLY_BINLOG_POS_OFFSET (REPLY_MAGIC_NUM_OFFSET + REPLY_MAGIC_NUM_LEN) #define REPLY_BINLOG_NAME_OFFSET (REPLY_BINLOG_POS_OFFSET + REPLY_BINLOG_POS_LEN) #define REPLY_MESSAGE_MAX_LENGTH \ (REPLY_MAGIC_NUM_LEN + REPLY_BINLOG_POS_LEN + REPLY_BINLOG_NAME_LEN) #endif /* SEMISYNC_H */ mysql/server/private/sql_select.h000064400000255502151027430560013214 0ustar00#ifndef SQL_SELECT_INCLUDED #define SQL_SELECT_INCLUDED /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. Copyright (c) 2008, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file @brief classes to use when handling where clause */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "procedure.h" #include "sql_array.h" /* Array */ #include "records.h" /* READ_RECORD */ #include "opt_range.h" /* SQL_SELECT, QUICK_SELECT_I */ #include "filesort.h" #include "cset_narrowing.h" typedef struct st_join_table JOIN_TAB; /* Values in optimize */ #define KEY_OPTIMIZE_EXISTS 1U #define KEY_OPTIMIZE_REF_OR_NULL 2U #define KEY_OPTIMIZE_EQ 4U inline uint get_hash_join_key_no() { return MAX_KEY; } inline bool is_hash_join_key_no(uint key) { return key == MAX_KEY; } typedef struct keyuse_t { TABLE *table; Item *val; /**< or value if no field */ table_map used_tables; uint key, keypart, optimize; key_part_map keypart_map; ha_rows ref_table_rows; /** If true, the comparison this value was created from will not be satisfied if val has NULL 'value'. */ bool null_rejecting; /* !NULL - This KEYUSE was created from an equality that was wrapped into an Item_func_trig_cond. This means the equality (and validity of this KEYUSE element) can be turned on and off. The on/off state is indicted by the pointed value: *cond_guard == TRUE <=> equality condition is on *cond_guard == FALSE <=> equality condition is off NULL - Otherwise (the source equality can't be turned off) */ bool *cond_guard; /* 0..64 <=> This was created from semi-join IN-equality # sj_pred_no. MAX_UINT Otherwise */ uint sj_pred_no; /* If this is NULL than KEYUSE is always enabled. Otherwise it points to the enabling flag for this keyuse (true <=> enabled) */ bool *validity_ref; bool is_for_hash_join() { return is_hash_join_key_no(key); } } KEYUSE; struct KEYUSE_EXT: public KEYUSE { /* This keyuse can be used only when the partial join being extended contains the tables from this table map */ table_map needed_in_prefix; /* The enabling flag for keyuses usable for splitting */ bool validity_var; }; /// Used when finding key fields struct KEY_FIELD { Field *field; Item_bool_func *cond; Item *val; ///< May be empty if diff constant uint level; uint optimize; bool eq_func; /** If true, the condition this struct represents will not be satisfied when val IS NULL. */ bool null_rejecting; bool *cond_guard; /* See KEYUSE::cond_guard */ uint sj_pred_no; /* See KEYUSE::sj_pred_no */ }; #define NO_KEYPART ((uint)(-1)) class store_key; const int NO_REF_PART= uint(-1); typedef struct st_table_ref { bool key_err; /** True if something was read into buffer in join_read_key. */ bool has_record; uint key_parts; ///< num of ... uint key_length; ///< length of key_buff int key; ///< key no uchar *key_buff; ///< value to look for with key uchar *key_buff2; ///< key_buff+key_length store_key **key_copy; // /* Bitmap of key parts which refer to constants. key_copy only has copiers for non-const key parts. */ key_part_map const_ref_part_map; Item **items; ///< val()'s for each keypart /* Array of pointers to trigger variables. Some/all of the pointers may be NULL. The ref access can be used iff for each used key part i, (!cond_guards[i] || *cond_guards[i]) This array is used by subquery code. The subquery code may inject triggered conditions, i.e. conditions that can be 'switched off'. A ref access created from such condition is not valid when at least one of the underlying conditions is switched off (see subquery code for more details) */ bool **cond_guards; /** (null_rejecting & (1< disable the "cache" as doing lookup with the same key value may produce different results (because of Index Condition Pushdown) */ bool disable_cache; /* If true, this ref access was constructed from equalities generated by LATERAL DERIVED (aka GROUP BY splitting) optimization */ bool uses_splitting; bool tmp_table_index_lookup_init(THD *thd, KEY *tmp_key, Item_iterator &it, bool value, uint skip= 0); bool is_access_triggered(); } TABLE_REF; /* The structs which holds the join connections and join states */ enum join_type { JT_UNKNOWN,JT_SYSTEM,JT_CONST,JT_EQ_REF,JT_REF,JT_MAYBE_REF, JT_ALL, JT_RANGE, JT_NEXT, JT_FT, JT_REF_OR_NULL, JT_UNIQUE_SUBQUERY, JT_INDEX_SUBQUERY, JT_INDEX_MERGE, JT_HASH, JT_HASH_RANGE, JT_HASH_NEXT, JT_HASH_INDEX_MERGE}; class JOIN; enum enum_nested_loop_state { NESTED_LOOP_KILLED= -2, NESTED_LOOP_ERROR= -1, NESTED_LOOP_OK= 0, NESTED_LOOP_NO_MORE_ROWS= 1, NESTED_LOOP_QUERY_LIMIT= 3, NESTED_LOOP_CURSOR_LIMIT= 4 }; /* Possible sj_strategy values */ enum sj_strategy_enum { SJ_OPT_NONE=0, SJ_OPT_DUPS_WEEDOUT=1, SJ_OPT_LOOSE_SCAN =2, SJ_OPT_FIRST_MATCH =3, SJ_OPT_MATERIALIZE =4, SJ_OPT_MATERIALIZE_SCAN=5 }; /* Values for JOIN_TAB::packed_info */ #define TAB_INFO_HAVE_VALUE 1U #define TAB_INFO_USING_INDEX 2U #define TAB_INFO_USING_WHERE 4U #define TAB_INFO_FULL_SCAN_ON_NULL 8U typedef enum_nested_loop_state (*Next_select_func)(JOIN *, struct st_join_table *, bool); Next_select_func setup_end_select_func(JOIN *join); int rr_sequential(READ_RECORD *info); int read_record_func_for_rr_and_unpack(READ_RECORD *info); Item *remove_pushed_top_conjuncts(THD *thd, Item *cond); Item *and_new_conditions_to_optimized_cond(THD *thd, Item *cond, COND_EQUAL **cond_eq, List &new_conds, Item::cond_result *cond_value); #include "sql_explain.h" /************************************************************************************** * New EXPLAIN structures END *************************************************************************************/ class JOIN_CACHE; class SJ_TMP_TABLE; class JOIN_TAB_RANGE; class AGGR_OP; class Filesort; struct SplM_plan_info; class SplM_opt_info; typedef struct st_join_table { TABLE *table; TABLE_LIST *tab_list; KEYUSE *keyuse; /**< pointer to first used key */ KEY *hj_key; /**< descriptor of the used best hash join key not supported by any index */ SQL_SELECT *select; COND *select_cond; COND *on_precond; /**< part of on condition to check before accessing the first inner table */ QUICK_SELECT_I *quick; /* The value of select_cond before we've attempted to do Index Condition Pushdown. We may need to restore everything back if we first choose one index but then reconsider (see test_if_skip_sort_order() for such scenarios). NULL means no index condition pushdown was performed. */ Item *pre_idx_push_select_cond; /* Pointer to the associated ON expression. on_expr_ref=!NULL except for degenerate joins. Optimization phase: *on_expr_ref!=NULL for tables that are the single tables on the inner side of the outer join (t1 LEFT JOIN t2 ON...) Execution phase: *on_expr_ref!=NULL for tables that are first inner tables within an outer join (which may have multiple tables) */ Item **on_expr_ref; COND_EQUAL *cond_equal; /**< multiple equalities for the on expression */ st_join_table *first_inner; /**< first inner table for including outerjoin */ bool found; /**< true after all matches or null complement */ bool not_null_compl;/**< true before null complement is added */ st_join_table *last_inner; /**< last table table for embedding outer join */ st_join_table *first_upper; /**< first inner table for embedding outer join */ st_join_table *first_unmatched; /**< used for optimization purposes only */ /* For join tabs that are inside an SJM bush: root of the bush */ st_join_table *bush_root_tab; /* TRUE <=> This join_tab is inside an SJM bush and is the last leaf tab here */ bool last_leaf_in_bush; /* ptr - this is a bush, and ptr points to description of child join_tab range NULL - this join tab has no bush children */ JOIN_TAB_RANGE *bush_children; /* Special content for EXPLAIN 'Extra' column or NULL if none */ enum explain_extra_tag info; Table_access_tracker *tracker; Table_access_tracker *jbuf_tracker; Time_and_counter_tracker *jbuf_unpack_tracker; Counter_tracker *jbuf_loops_tracker; /* Bitmap of TAB_INFO_* bits that encodes special line for EXPLAIN 'Extra' column, or 0 if there is no info. */ uint packed_info; // READ_RECORD::Setup_func materialize_table; READ_RECORD::Setup_func read_first_record; Next_select_func next_select; READ_RECORD read_record; /* Currently the following two fields are used only for a [NOT] IN subquery if it is executed by an alternative full table scan when the left operand of the subquery predicate is evaluated to NULL. */ READ_RECORD::Setup_func save_read_first_record;/* to save read_first_record */ READ_RECORD::Read_func save_read_record;/* to save read_record.read_record */ double worst_seeks; key_map const_keys; /**< Keys with constant part */ key_map checked_keys; /**< Keys checked in find_best */ key_map needed_reg; key_map keys; /**< all keys with can be used */ /* Either #rows in the table or 1 for const table. */ ha_rows records; /* Number of records that will be scanned (yes scanned, not returned) by the best 'independent' access method, i.e. table scan or QUICK_*_SELECT) */ ha_rows found_records; /* Cost of accessing the table using "ALL" or range/index_merge access method (but not 'index' for some reason), i.e. this matches method which E(#records) is in found_records. */ double read_time; /* Copy of POSITION::records_read, set by get_best_combination() */ double records_read; /* The selectivity of the conditions that can be pushed to the table */ double cond_selectivity; /* Startup cost for execution */ double startup_cost; double partial_join_cardinality; table_map dependent,key_dependent; /* 1 - use quick select 2 - use "Range checked for each record" */ uint use_quick; /* Index to use. Note: this is valid only for 'index' access, but not range or ref access. */ uint index; uint status; ///< Save status for cache uint used_fields; ulong used_fieldlength; ulong max_used_fieldlength; uint used_blobs; uint used_null_fields; uint used_uneven_bit_fields; enum join_type type; /* If first key part is used for any key in 'key_dependent' */ bool key_start_dependent; bool cached_eq_ref_table,eq_ref_table; bool shortcut_for_distinct; bool sorted; /* If it's not 0 the number stored this field indicates that the index scan has been chosen to access the table data and we expect to scan this number of rows for the table. */ ha_rows limit; TABLE_REF ref; /* TRUE <=> condition pushdown supports other tables presence */ bool icp_other_tables_ok; /* TRUE <=> condition pushed to the index has to be factored out of the condition pushed to the table */ bool idx_cond_fact_out; bool use_join_cache; /* TRUE <=> it is prohibited to join this table using join buffer */ bool no_forced_join_cache; uint used_join_cache_level; JOIN_CACHE *cache; /* Index condition for BKA access join */ Item *cache_idx_cond; SQL_SELECT *cache_select; AGGR_OP *aggr; JOIN *join; /* Embedding SJ-nest (may be not the direct parent), or NULL if none. This variable holds the result of table pullout. */ TABLE_LIST *emb_sj_nest; /* FirstMatch variables (final QEP) */ struct st_join_table *first_sj_inner_tab; struct st_join_table *last_sj_inner_tab; /* Variables for semi-join duplicate elimination */ SJ_TMP_TABLE *flush_weedout_table; SJ_TMP_TABLE *check_weed_out_table; /* for EXPLAIN only: */ SJ_TMP_TABLE *first_weedout_table; /** reference to saved plan and execution statistics */ Explain_table_access *explain_plan; /* If set, means we should stop join enumeration after we've got the first match and return to the specified join tab. May point to join->join_tab[-1] which means stop join execution after the first match. */ struct st_join_table *do_firstmatch; /* ptr - We're doing a LooseScan, this join tab is the first (i.e. "driving") join tab), and ptr points to the last join tab handled by the strategy. loosescan_match_tab->found_match should be checked to see if the current value group had a match. NULL - Not doing a loose scan on this join tab. */ struct st_join_table *loosescan_match_tab; /* TRUE <=> we are inside LooseScan range */ bool inside_loosescan_range; /* Buffer to save index tuple to be able to skip duplicates */ uchar *loosescan_buf; /* Index used by LooseScan (we store it here separately because ref access stores it in tab->ref.key, while range scan stores it in tab->index, etc) */ uint loosescan_key; /* Length of key tuple (depends on #keyparts used) to store in the above */ uint loosescan_key_len; /* Used by LooseScan. TRUE<=> there has been a matching record combination */ bool found_match; /* Used by DuplicateElimination. tab->table->ref must have the rowid whenever we have a current record. */ int keep_current_rowid; /* NestedOuterJoins: Bitmap of nested joins this table is part of */ nested_join_map embedding_map; /* Tmp table info */ TMP_TABLE_PARAM *tmp_table_param; /* Sorting related info */ Filesort *filesort; SORT_INFO *filesort_result; /* Non-NULL value means this join_tab must do window function computation before reading. */ Window_funcs_computation* window_funcs_step; /** List of topmost expressions in the select list. The *next* JOIN_TAB in the plan should use it to obtain correct values. Same applicable to all_fields. These lists are needed because after tmp tables functions will be turned to fields. These variables are pointing to tmp_fields_list[123]. Valid only for tmp tables and the last non-tmp table in the query plan. @see JOIN::make_aggr_tables_info() */ List *fields; /** List of all expressions in the select list */ List *all_fields; /* Pointer to the ref array slice which to switch to before sending records. Valid only for tmp tables. */ Ref_ptr_array *ref_array; /** Number of records saved in tmp table */ ha_rows send_records; /** HAVING condition for checking prior saving a record into tmp table*/ Item *having; /** TRUE <=> remove duplicates on this table. */ bool distinct; /* Semi-join strategy to be used for this join table. This is a copy of POSITION::sj_strategy field. This field is set up by the fix_semijoin_strategies_for_picked_join_order. */ enum sj_strategy_enum sj_strategy; uint n_sj_tables; bool preread_init_done; /* true <=> split optimization has been applied to this materialized table */ bool is_split_derived; /* Bitmap of split materialized derived tables that can be filled just before this join table is to be joined. All parameters of the split derived tables belong to tables preceding this join table. */ table_map split_derived_to_update; /* Cost info to the range filter used when joining this join table (Defined when the best join order has been already chosen) */ Range_rowid_filter_cost_info *range_rowid_filter_info; /* Rowid filter to be used when joining this join table */ Rowid_filter *rowid_filter; /* Becomes true just after the used range filter has been built / filled */ bool is_rowid_filter_built; bool build_range_rowid_filter_if_needed(); void cleanup(); inline bool is_using_loose_index_scan() { const SQL_SELECT *sel= get_sql_select(); return (sel && sel->quick && (sel->quick->get_type() == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)); } bool is_using_agg_loose_index_scan () { const SQL_SELECT *sel= get_sql_select(); return (is_using_loose_index_scan() && ((QUICK_GROUP_MIN_MAX_SELECT *)sel->quick)->is_agg_distinct()); } const SQL_SELECT *get_sql_select() { return filesort ? filesort->select : select; } bool is_inner_table_of_semi_join_with_first_match() { return first_sj_inner_tab != NULL; } bool is_inner_table_of_semijoin() { return emb_sj_nest != NULL; } bool is_inner_table_of_outer_join() { return first_inner != NULL; } bool is_single_inner_of_semi_join_with_first_match() { return first_sj_inner_tab == this && last_sj_inner_tab == this; } bool is_single_inner_of_outer_join() { return first_inner == this && first_inner->last_inner == this; } bool is_first_inner_for_outer_join() { return first_inner == this; } bool use_match_flag() { return is_first_inner_for_outer_join() || first_sj_inner_tab == this ; } bool check_only_first_match() { return is_inner_table_of_semi_join_with_first_match() || (is_inner_table_of_outer_join() && table->reginfo.not_exists_optimize); } bool is_last_inner_table() { return (first_inner && first_inner->last_inner == this) || last_sj_inner_tab == this; } /* Check whether the table belongs to a nest of inner tables of an outer join or to a nest of inner tables of a semi-join */ bool is_nested_inner() { if (first_inner && (first_inner != first_inner->last_inner || first_inner->first_upper)) return TRUE; if (first_sj_inner_tab && first_sj_inner_tab != last_sj_inner_tab) return TRUE; return FALSE; } struct st_join_table *get_first_inner_table() { if (first_inner) return first_inner; return first_sj_inner_tab; } void set_select_cond(COND *to, uint line) { DBUG_PRINT("info", ("select_cond changes %p -> %p at line %u tab %p", select_cond, to, line, this)); select_cond= to; } COND *set_cond(COND *new_cond) { COND *tmp_select_cond= select_cond; set_select_cond(new_cond, __LINE__); if (select) select->cond= new_cond; return tmp_select_cond; } void calc_used_field_length(bool max_fl); ulong get_used_fieldlength() { if (!used_fieldlength) calc_used_field_length(FALSE); return used_fieldlength; } ulong get_max_used_fieldlength() { if (!max_used_fieldlength) calc_used_field_length(TRUE); return max_used_fieldlength; } double get_partial_join_cardinality() { return partial_join_cardinality; } bool hash_join_is_possible(); int make_scan_filter(); bool is_ref_for_hash_join() { return is_hash_join_key_no(ref.key); } KEY *get_keyinfo_by_key_no(uint key) { return (is_hash_join_key_no(key) ? hj_key : table->key_info+key); } double scan_time(); ha_rows get_examined_rows(); bool preread_init(); bool pfs_batch_update(JOIN *join); bool is_sjm_nest() { return MY_TEST(bush_children); } /* If this join_tab reads a non-merged semi-join (also called jtbm), return the select's number. Otherwise, return 0. */ int get_non_merged_semijoin_select() const { Item_in_subselect *subq; if (table->pos_in_table_list && (subq= table->pos_in_table_list->jtbm_subselect)) { return subq->unit->first_select()->select_number; } return 0; /* Not a merged semi-join */ } bool access_from_tables_is_allowed(table_map used_tables, table_map sjm_lookup_tables) { table_map used_sjm_lookup_tables= used_tables & sjm_lookup_tables; return !used_sjm_lookup_tables || (emb_sj_nest && !(used_sjm_lookup_tables & ~emb_sj_nest->sj_inner_tables)); } bool keyuse_is_valid_for_access_in_chosen_plan(JOIN *join, KEYUSE *keyuse); void remove_redundant_bnl_scan_conds(); bool save_explain_data(Explain_table_access *eta, table_map prefix_tables, bool distinct, struct st_join_table *first_top_tab); bool use_order() const; ///< Use ordering provided by chosen index? bool sort_table(); bool remove_duplicates(); void partial_cleanup(); void add_keyuses_for_splitting(); SplM_plan_info *choose_best_splitting(uint idx, table_map remaining_tables, const POSITION *join_positions, table_map *spl_pd_boundary); bool fix_splitting(SplM_plan_info *spl_plan, table_map excluded_tables, bool is_const_table); } JOIN_TAB; #include "sql_join_cache.h" enum_nested_loop_state sub_select_cache(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); enum_nested_loop_state sub_select(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); enum_nested_loop_state sub_select_postjoin_aggr(JOIN *join, JOIN_TAB *join_tab, bool end_of_records); enum_nested_loop_state end_send_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), bool end_of_records); enum_nested_loop_state end_write_group(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)), bool end_of_records); class Semi_join_strategy_picker { public: /* Called when starting to build a new join prefix */ virtual void set_empty() = 0; /* Update internal state after another table has been added to the join prefix */ virtual void set_from_prev(POSITION *prev) = 0; virtual bool check_qep(JOIN *join, uint idx, table_map remaining_tables, const JOIN_TAB *new_join_tab, double *record_count, double *read_time, table_map *handled_fanout, sj_strategy_enum *strategy, POSITION *loose_scan_pos) = 0; virtual void mark_used() = 0; virtual ~Semi_join_strategy_picker() = default; }; /* Duplicate Weedout strategy optimization state */ class Duplicate_weedout_picker : public Semi_join_strategy_picker { /* The first table that the strategy will need to handle */ uint first_dupsweedout_table; /* Tables that we will need to have in the prefix to do the weedout step (all inner and all outer that the involved semi-joins are correlated with) */ table_map dupsweedout_tables; bool is_used; public: void set_empty() override { dupsweedout_tables= 0; first_dupsweedout_table= MAX_TABLES; is_used= FALSE; } void set_from_prev(POSITION *prev) override; bool check_qep(JOIN *join, uint idx, table_map remaining_tables, const JOIN_TAB *new_join_tab, double *record_count, double *read_time, table_map *handled_fanout, sj_strategy_enum *stratey, POSITION *loose_scan_pos) override; void mark_used() override { is_used= TRUE; } friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); }; class Firstmatch_picker : public Semi_join_strategy_picker { /* Index of the first inner table that we intend to handle with this strategy */ uint first_firstmatch_table; /* Tables that were not in the join prefix when we've started considering FirstMatch strategy. */ table_map first_firstmatch_rtbl; /* Tables that need to be in the prefix before we can calculate the cost of using FirstMatch strategy. */ table_map firstmatch_need_tables; bool is_used; bool in_firstmatch_prefix() { return (first_firstmatch_table != MAX_TABLES); } void invalidate_firstmatch_prefix() { first_firstmatch_table= MAX_TABLES; } public: void set_empty() override { invalidate_firstmatch_prefix(); is_used= FALSE; } void set_from_prev(POSITION *prev) override; bool check_qep(JOIN *join, uint idx, table_map remaining_tables, const JOIN_TAB *new_join_tab, double *record_count, double *read_time, table_map *handled_fanout, sj_strategy_enum *strategy, POSITION *loose_scan_pos) override; void mark_used() override { is_used= TRUE; } friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); }; class LooseScan_picker : public Semi_join_strategy_picker { public: /* The first (i.e. driving) table we're doing loose scan for */ uint first_loosescan_table; /* Tables that need to be in the prefix before we can calculate the cost of using LooseScan strategy. */ table_map loosescan_need_tables; /* keyno - Planning to do LooseScan on this key. If keyuse is NULL then this is a full index scan, otherwise this is a ref+loosescan scan (and keyno matches the KEUSE's) MAX_KEY - Not doing a LooseScan */ uint loosescan_key; // final (one for strategy instance ) uint loosescan_parts; /* Number of keyparts to be kept distinct */ bool is_used; void set_empty() override { first_loosescan_table= MAX_TABLES; is_used= FALSE; } void set_from_prev(POSITION *prev) override; bool check_qep(JOIN *join, uint idx, table_map remaining_tables, const JOIN_TAB *new_join_tab, double *record_count, double *read_time, table_map *handled_fanout, sj_strategy_enum *strategy, POSITION *loose_scan_pos) override; void mark_used() override { is_used= TRUE; } friend class Loose_scan_opt; friend void best_access_path(JOIN *join, JOIN_TAB *s, table_map remaining_tables, const POSITION *join_positions, uint idx, bool disable_jbuf, double record_count, POSITION *pos, POSITION *loose_scan_pos); friend bool get_best_combination(JOIN *join); friend int setup_semijoin_loosescan(JOIN *join); friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); }; class Sj_materialization_picker : public Semi_join_strategy_picker { bool is_used; /* The last inner table (valid once we're after it) */ uint sjm_scan_last_inner; /* Tables that we need to have in the prefix to calculate the correct cost. Basically, we need all inner tables and outer tables mentioned in the semi-join's ON expression so we can correctly account for fanout. */ table_map sjm_scan_need_tables; public: void set_empty() override { sjm_scan_need_tables= 0; sjm_scan_last_inner= 0; is_used= FALSE; } void set_from_prev(POSITION *prev) override; bool check_qep(JOIN *join, uint idx, table_map remaining_tables, const JOIN_TAB *new_join_tab, double *record_count, double *read_time, table_map *handled_fanout, sj_strategy_enum *strategy, POSITION *loose_scan_pos) override; void mark_used() override { is_used= TRUE; } friend void fix_semijoin_strategies_for_picked_join_order(JOIN *join); }; class Range_rowid_filter_cost_info; class Rowid_filter; /** Information about a position of table within a join order. Used in join optimization. */ class POSITION { public: /* The table that's put into join order */ JOIN_TAB *table; /* The "fanout": number of output rows that will be produced (after pushed down selection condition is applied) per each row combination of previous tables. */ double records_read; /* The selectivity of the pushed down conditions */ double cond_selectivity; /* Cost accessing the table in course of the entire complete join execution, i.e. cost of one access method use (e.g. 'range' or 'ref' scan ) times number the access method will be invoked. */ double read_time; double prefix_record_count; /* NULL - 'index' or 'range' or 'index_merge' or 'ALL' access is used. Other - [eq_]ref[_or_null] access is used. Pointer to {t.keypart1 = expr} */ KEYUSE *key; /* Cardinality of current partial join ending with this position */ double partial_join_cardinality; /* Info on splitting plan used at this position */ SplM_plan_info *spl_plan; /* If spl_plan is NULL the value of spl_pd_boundary is 0. Otherwise spl_pd_boundary contains the bitmap of the table from the current partial join ending at this position that starts the sub-sequence of tables S from which no conditions are allowed to be used in the plan spl_plan for the split table joined at this position. */ table_map spl_pd_boundary; /* Cost info for the range filter used at this position */ Range_rowid_filter_cost_info *range_rowid_filter_info; /* If ref-based access is used: bitmap of tables this table depends on */ table_map ref_depend_map; /* tables that may help best_access_path() to find a better key */ table_map key_dependent; /* Bitmap of semi-join inner tables that are in the join prefix and for which there's no provision for how to eliminate semi-join duplicates they produce. */ table_map dups_producing_tables; table_map inner_tables_handled_with_other_sjs; Duplicate_weedout_picker dups_weedout_picker; Firstmatch_picker firstmatch_picker; LooseScan_picker loosescan_picker; Sj_materialization_picker sjmat_picker; /* Cumulative cost and record count for the join prefix */ Cost_estimate prefix_cost; /* Current optimization state: Semi-join strategy to be used for this and preceding join tables. Join optimizer sets this for the *last* join_tab in the duplicate-generating range. That is, in order to interpret this field, one needs to traverse join->[best_]positions array from right to left. When you see a join table with sj_strategy!= SJ_OPT_NONE, some other field (depending on the strategy) tells how many preceding positions this applies to. The values of covered_preceding_positions->sj_strategy must be ignored. */ enum sj_strategy_enum sj_strategy; /* Type of join (EQ_REF, REF etc) */ enum join_type type; /* Valid only after fix_semijoin_strategies_for_picked_join_order() call: if sj_strategy!=SJ_OPT_NONE, this is the number of subsequent tables that are covered by the specified semi-join strategy */ uint n_sj_tables; /* TRUE <=> join buffering will be used. At the moment this is based on *very* imprecise guesses made in best_access_path(). */ bool use_join_buffer; POSITION(); }; typedef Bounds_checked_array Item_null_array; typedef struct st_rollup { enum State { STATE_NONE, STATE_INITED, STATE_READY }; State state; Item_null_array null_items; Ref_ptr_array *ref_pointer_arrays; List *fields; } ROLLUP; class JOIN_TAB_RANGE: public Sql_alloc { public: JOIN_TAB *start; JOIN_TAB *end; }; class Pushdown_query; /** @brief Class to perform postjoin aggregation operations @details The result records are obtained on the put_record() call. The aggrgation process is determined by the write_func, it could be: end_write Simply store all records in tmp table. end_write_group Perform grouping using join->group_fields, records are expected to be sorted. end_update Perform grouping using the key generated on tmp table. Input records aren't expected to be sorted. Tmp table uses the heap engine end_update_unique Same as above, but the engine is myisam. Lazy table initialization is used - the table will be instantiated and rnd/index scan started on the first put_record() call. */ class AGGR_OP :public Sql_alloc { public: JOIN_TAB *join_tab; AGGR_OP(JOIN_TAB *tab) : join_tab(tab), write_func(NULL) {}; enum_nested_loop_state put_record() { return put_record(false); }; /* Send the result of operation further (to a next operation/client) This function is called after all records were put into tmp table. @return return one of enum_nested_loop_state values. */ enum_nested_loop_state end_send(); /** write_func setter */ void set_write_func(Next_select_func new_write_func) { write_func= new_write_func; } private: /** Write function that would be used for saving records in tmp table. */ Next_select_func write_func; enum_nested_loop_state put_record(bool end_of_records); bool prepare_tmp_table(); }; class JOIN :public Sql_alloc { private: JOIN(const JOIN &rhs); /**< not implemented */ JOIN& operator=(const JOIN &rhs); /**< not implemented */ protected: /** The subset of the state of a JOIN that represents an optimized query execution plan. Allows saving/restoring different JOIN plans for the same query. */ class Join_plan_state { public: DYNAMIC_ARRAY keyuse; /* Copy of the JOIN::keyuse array. */ POSITION *best_positions; /* Copy of JOIN::best_positions */ /* Copies of the JOIN_TAB::keyuse pointers for each JOIN_TAB. */ KEYUSE **join_tab_keyuse; /* Copies of JOIN_TAB::checked_keys for each JOIN_TAB. */ key_map *join_tab_checked_keys; SJ_MATERIALIZATION_INFO **sj_mat_info; my_bool error; public: Join_plan_state(uint tables) : error(0) { keyuse.elements= 0; keyuse.buffer= NULL; keyuse.malloc_flags= 0; best_positions= 0; /* To detect errors */ error= my_multi_malloc(PSI_INSTRUMENT_ME, MYF(MY_WME), &best_positions, sizeof(*best_positions) * (tables + 1), &join_tab_keyuse, sizeof(*join_tab_keyuse) * tables, &join_tab_checked_keys, sizeof(*join_tab_checked_keys) * tables, &sj_mat_info, sizeof(sj_mat_info) * tables, NullS) == 0; } Join_plan_state(JOIN *join); ~Join_plan_state() { delete_dynamic(&keyuse); my_free(best_positions); } }; /* Results of reoptimizing a JOIN via JOIN::reoptimize(). */ enum enum_reopt_result { REOPT_NEW_PLAN, /* there is a new reoptimized plan */ REOPT_OLD_PLAN, /* no new improved plan can be found, use the old one */ REOPT_ERROR, /* an irrecovarable error occurred during reoptimization */ REOPT_NONE /* not yet reoptimized */ }; /* Support for plan reoptimization with rewritten conditions. */ enum_reopt_result reoptimize(Item *added_where, table_map join_tables, Join_plan_state *save_to); /* Choose a subquery plan for a table-less subquery. */ bool choose_tableless_subquery_plan(); void handle_implicit_grouping_with_window_funcs(); public: void save_query_plan(Join_plan_state *save_to); void reset_query_plan(); void restore_query_plan(Join_plan_state *restore_from); public: JOIN_TAB *join_tab, **best_ref; /* List of fields that aren't under an aggregate function */ List non_agg_fields; JOIN_TAB **map2table; ///< mapping between table indexes and JOIN_TABs List join_tab_ranges; /* Base tables participating in the join. After join optimization is done, the tables are stored in the join order (but the only really important part is that const tables are first). */ TABLE **table; /** The table which has an index that allows to produce the requried ordering. A special value of 0x1 means that the ordering will be produced by passing 1st non-const table to filesort(). NULL means no such table exists. */ TABLE *sort_by_table; /* If true, there is ORDER BY x LIMIT n clause and for certain join orders, it is possible to short-cut the join execution, i.e. stop it as soon as n output rows were produced. See join_limit_shortcut_is_applicable(). */ bool limit_shortcut_applicable; /* Used during join optimization: if true, we're building a join order that will short-cut join execution as soon as #LIMIT rows are produced. */ bool limit_optimization_mode; /* Number of tables in the join. (In MySQL, it is named 'tables' and is also the number of elements in join->join_tab array. In MariaDB, the latter is not true, so we've renamed the variable) */ uint table_count; uint outer_tables; /**< Number of tables that are not inside semijoin */ uint const_tables; /* Number of tables in the top join_tab array. Normally this matches (join_tab_ranges.head()->end - join_tab_ranges.head()->start). We keep it here so that it is saved/restored with JOIN::restore_tmp. */ uint top_join_tab_count; uint aggr_tables; ///< Number of post-join tmp tables uint send_group_parts; /* This represents the number of items in ORDER BY *after* removing all const items. This is computed before other optimizations take place, such as removal of ORDER BY when it is a prefix of GROUP BY, for example: GROUP BY a, b ORDER BY a This is used when deciding to send rows, by examining the correct number of items in the group_fields list when ORDER BY was previously eliminated. */ uint with_ties_order_count; /* True if the query has GROUP BY. (that is, if group_by != NULL. when DISTINCT is converted into GROUP BY, it will set this, too. It is not clear why we need a separate var from group_list) */ bool group; bool need_distinct; /** Indicates that grouping will be performed on the result set during query execution. This field belongs to query execution. If 'sort_and_group' is set, then the optimizer is going to use on of the following algorithms to resolve GROUP BY. - If one table, sort the table and then calculate groups on the fly. - If more than one table, create a temporary table to hold the join, sort it and then resolve group by on the fly. The 'on the fly' calculation is done in end_send_group() @see make_group_fields, alloc_group_fields, JOIN::exec, setup_end_select_func */ bool sort_and_group; bool first_record,full_join, no_field_update; bool hash_join; bool do_send_rows; table_map const_table_map; /** Bitmap of semijoin tables that the current partial plan decided to materialize and access by lookups */ table_map sjm_lookup_tables; /** Bitmap of semijoin tables that the chosen plan decided to materialize to scan the results of materialization */ table_map sjm_scan_tables; /* Constant tables for which we have found a row (as opposed to those for which we didn't). */ table_map found_const_table_map; /* Tables removed by table elimination. Set to 0 before the elimination. */ table_map eliminated_tables; /* Bitmap of all inner tables from outer joins (set at start of make_join_statistics) */ table_map outer_join; /* Bitmap of tables used in the select list items */ table_map select_list_used_tables; /* Tables that has HA_NON_COMPARABLE_ROWID (does not support rowid) set */ table_map not_usable_rowid_map; ha_rows send_records,found_records,join_examined_rows, accepted_rows; /* LIMIT for the JOIN operation. When not using aggregation or DISITNCT, this is the same as select's LIMIT clause specifies. Note that this doesn't take sql_calc_found_rows into account. */ ha_rows row_limit; /* How many output rows should be produced after GROUP BY. (if sql_calc_found_rows is used, LIMIT is ignored) */ ha_rows select_limit; /* Number of duplicate rows found in UNION. */ ha_rows duplicate_rows; /** Used to fetch no more than given amount of rows per one fetch operation of server side cursor. The value is checked in end_send and end_send_group in fashion, similar to offset_limit_cnt: - fetch_limit= HA_POS_ERROR if there is no cursor. - when we open a cursor, we set fetch_limit to 0, - on each fetch iteration we add num_rows to fetch to fetch_limit NOTE: currently always HA_POS_ERROR. */ ha_rows fetch_limit; /* Finally picked QEP. This is result of join optimization */ POSITION *best_positions; Pushdown_query *pushdown_query; JOIN_TAB *original_join_tab; uint original_table_count; /******* Join optimization state members start *******/ /* pointer - we're doing optimization for a semi-join materialization nest. NULL - otherwise */ TABLE_LIST *emb_sjm_nest; /* Current join optimization state */ POSITION *positions; /* Bitmap of nested joins embedding the position at the end of the current partial join (valid only during join optimizer run). */ nested_join_map cur_embedding_map; /* Bitmap of inner tables of semi-join nests that have a proper subset of their tables in the current join prefix. That is, of those semi-join nests that have their tables both in and outside of the join prefix. (Note: tables that are constants but have not been pulled out of semi-join nests are not considered part of semi-join nests) */ table_map cur_sj_inner_tables; #ifndef DBUG_OFF void dbug_verify_sj_inner_tables(uint n_positions) const; int dbug_join_tab_array_size; #endif /* We also maintain a stack of join optimization states in * join->positions[] */ /******* Join optimization state members end *******/ /* Tables within complex firstmatch ranges (i.e. those where inner tables are interleaved with outer tables). Join buffering cannot be used for these. */ table_map complex_firstmatch_tables; Next_select_func first_select; /* The cost of best complete join plan found so far during optimization, after optimization phase - cost of picked join order (not taking into account the changes made by test_if_skip_sort_order()). */ double best_read; /* Estimated result rows (fanout) of the join operation. If this is a subquery that is reexecuted multiple times, this value includes the estiamted # of reexecutions. This value is equal to the multiplication of all join->positions[i].records_read of a JOIN. */ double join_record_count; List *fields; /* Used only for FETCH ... WITH TIES to identify peers. */ List order_fields; /* Used during GROUP BY operations to identify when a group has changed. */ List group_fields, group_fields_cache; THD *thd; Item_sum **sum_funcs, ***sum_funcs_end; /** second copy of sumfuncs (for queries with 2 temporary tables */ Item_sum **sum_funcs2, ***sum_funcs_end2; Procedure *procedure; Item *having; Item *tmp_having; ///< To store having when processed temporary table Item *having_history; ///< Store having for explain ORDER *group_list_for_estimates; bool having_is_correlated; ulonglong select_options; /* Bitmap of allowed types of the join caches that can be used for join operations */ uint allowed_join_cache_types; bool allowed_semijoin_with_cache; bool allowed_outer_join_with_cache; /* Maximum level of the join caches that can be used for join operations */ uint max_allowed_join_cache_level; select_result *result; TMP_TABLE_PARAM tmp_table_param; MYSQL_LOCK *lock; /// unit structure (with global parameters) for this select SELECT_LEX_UNIT *unit; /// select that processed SELECT_LEX *select_lex; /** TRUE <=> optimizer must not mark any table as a constant table. This is needed for subqueries in form "a IN (SELECT .. UNION SELECT ..): when we optimize the select that reads the results of the union from a temporary table, we must not mark the temp. table as constant because the number of rows in it may vary from one subquery execution to another. */ bool no_const_tables; /* This flag is set if we call no_rows_in_result() as par of end_group(). This is used as a simple speed optimization to avoiding calling restore_no_rows_in_result() in ::reinit() */ bool no_rows_in_result_called; /** This is set if SQL_CALC_ROWS was calculated by filesort() and should be taken from the appropriate JOIN_TAB */ bool filesort_found_rows; bool subq_exit_fl; ROLLUP rollup; ///< Used with rollup bool mixed_implicit_grouping; bool select_distinct; ///< Set if SELECT DISTINCT /** If we have the GROUP BY statement in the query, but the group_list was emptied by optimizer, this flag is TRUE. It happens when fields in the GROUP BY are from constant table */ bool group_optimized_away; /* simple_xxxxx is set if ORDER/GROUP BY doesn't include any references to other tables than the first non-constant table in the JOIN. It's also set if ORDER/GROUP BY is empty. Used for deciding for or against using a temporary table to compute GROUP/ORDER BY. */ bool simple_order, simple_group; /* ordered_index_usage is set if an ordered index access should be used instead of a filesort when computing ORDER/GROUP BY. */ enum { ordered_index_void, // No ordered index avail. ordered_index_group_by, // Use index for GROUP BY ordered_index_order_by // Use index for ORDER BY } ordered_index_usage; /** Is set only in case if we have a GROUP BY clause and no ORDER BY after constant elimination of 'order'. */ bool no_order; /** Is set if we have a GROUP BY and we have ORDER BY on a constant. */ bool skip_sort_order; bool need_tmp; bool hidden_group_fields; /* TRUE if there was full cleunap of the JOIN */ bool cleaned; DYNAMIC_ARRAY keyuse; Item::cond_result cond_value, having_value; /** Impossible where after reading const tables (set in make_join_statistics()) */ bool impossible_where; /* All fields used in the query processing. Initially this is a list of fields from the query's SQL text. Then, ORDER/GROUP BY and Window Function code add columns that need to be saved to be available in the post-group-by context. These extra columns are added to the front, because this->fields_list points to the suffix of this list. */ List all_fields; ///Above list changed to use temporary table List tmp_all_fields1, tmp_all_fields2, tmp_all_fields3; ///Part, shared with list above, emulate following list List tmp_fields_list1, tmp_fields_list2, tmp_fields_list3; /* The original field list as it was passed to mysql_select(). This refers to select_lex->item_list. CAUTION: this list is a suffix of this->all_fields list, that is, it shares elements with that list! */ List &fields_list; List procedure_fields_list; int error; ORDER *order, *group_list, *proc_param; //hold parameters of mysql_select COND *conds; // ---"--- Item *conds_history; // store WHERE for explain COND *outer_ref_cond; /// *join_list; ///< list of joined tables in reverse order COND_EQUAL *cond_equal; COND_EQUAL *having_equal; /* Constant codition computed during optimization, but evaluated during join execution. Typically expensive conditions that should not be evaluated at optimization time. */ Item *exec_const_cond; /* Constant ORDER and/or GROUP expressions that contain subqueries. Such expressions need to evaluated to verify that the subquery indeed returns a single row. The evaluation of such expressions is delayed until query execution. */ List exec_const_order_group_cond; SQL_SELECT *select; ///ref_pointer_array contains five "slices" of the same length: |========|========|========|========|========| ref_ptrs items0 items1 items2 items3 */ Ref_ptr_array ref_ptrs; // Copy of the initial slice above, to be used with different lists Ref_ptr_array items0, items1, items2, items3; // Used by rollup, to restore ref_ptrs after overwriting it. Ref_ptr_array current_ref_ptrs; const char *zero_result_cause; ///< not 0 if exec must return zero result bool union_part; ///< this subselect is part of union enum join_optimization_state { NOT_OPTIMIZED=0, OPTIMIZATION_IN_PROGRESS=1, OPTIMIZATION_PHASE_1_DONE=2, OPTIMIZATION_DONE=3}; // state of JOIN optimization enum join_optimization_state optimization_state; bool initialized; ///< flag to avoid double init_execution calls Explain_select *explain; enum { QEP_NOT_PRESENT_YET, QEP_AVAILABLE, QEP_DELETED} have_query_plan; // if keep_current_rowid=true, whether they should be saved in temporary table bool tmp_table_keep_current_rowid; /* Additional WHERE and HAVING predicates to be considered for IN=>EXISTS subquery transformation of a JOIN object. */ Item *in_to_exists_where; Item *in_to_exists_having; /* Temporary tables used to weed-out semi-join duplicates */ List
sj_tmp_tables; /* SJM nests that are executed with SJ-Materialization strategy */ List sjm_info_list; /** TRUE <=> ref_pointer_array is set to items3. */ bool set_group_rpa; /** Exec time only: TRUE <=> current group has been sent */ bool group_sent; /** TRUE if the query contains an aggregate function but has no GROUP BY clause. */ bool implicit_grouping; bool with_two_phase_optimization; /* Saved execution plan for this join */ Join_plan_state *save_qep; /* Info on splittability of the table materialized by this plan*/ SplM_opt_info *spl_opt_info; /* Contains info on keyuses usable for splitting */ Dynamic_array *ext_keyuses_for_splitting; JOIN_TAB *sort_and_group_aggr_tab; /* Flag is set to true if select_lex was found to be degenerated before the optimize_cond() call in JOIN::optimize_inner() method. */ bool is_orig_degenerated; JOIN(THD *thd_arg, List &fields_arg, ulonglong select_options_arg, select_result *result_arg) :fields_list(fields_arg) { init(thd_arg, fields_arg, select_options_arg, result_arg); } void init(THD *thd_arg, List &fields_arg, ulonglong select_options_arg, select_result *result_arg); /* True if the plan guarantees that it will be returned zero or one row */ bool only_const_tables() { return const_tables == table_count; } /* Number of tables actually joined at the top level */ uint exec_join_tab_cnt() { return tables_list ? top_join_tab_count : 0; } /* Number of tables in the join which also includes the temporary tables created for GROUP BY, DISTINCT , WINDOW FUNCTION etc. */ uint total_join_tab_cnt() { return exec_join_tab_cnt() + aggr_tables - 1; } int prepare(TABLE_LIST *tables, COND *conds, uint og_num, ORDER *order, bool skip_order_by, ORDER *group, Item *having, ORDER *proc_param, SELECT_LEX *select, SELECT_LEX_UNIT *unit); bool prepare_stage2(); int optimize(); int optimize_inner(); int optimize_stage2(); bool build_explain(); int reinit(); int init_execution(); void exec(); void exec_inner(); bool prepare_result(List **columns_list); int destroy(); void restore_tmp(); bool alloc_func_list(); bool flatten_subqueries(); bool optimize_unflattened_subqueries(); bool optimize_constant_subqueries(); bool make_range_rowid_filters(); bool init_range_rowid_filters(); bool make_sum_func_list(List &all_fields, List &send_fields, bool before_group_by); /// Initialzes a slice, see comments for ref_ptrs above. Ref_ptr_array ref_ptr_array_slice(size_t slice_num) { size_t slice_sz= select_lex->ref_pointer_array.size() / 5U; DBUG_ASSERT(select_lex->ref_pointer_array.size() % 5 == 0); DBUG_ASSERT(slice_num < 5U); return Ref_ptr_array(&select_lex->ref_pointer_array[slice_num * slice_sz], slice_sz); } /** Overwrites one slice with the contents of another slice. In the normal case, dst and src have the same size(). However: the rollup slices may have smaller size than slice_sz. */ void copy_ref_ptr_array(Ref_ptr_array dst_arr, Ref_ptr_array src_arr) { DBUG_ASSERT(dst_arr.size() >= src_arr.size()); if (src_arr.size() == 0) return; void *dest= dst_arr.array(); const void *src= src_arr.array(); memcpy(dest, src, src_arr.size() * src_arr.element_size()); } /// Overwrites 'ref_ptrs' and remembers the the source as 'current'. void set_items_ref_array(Ref_ptr_array src_arr) { copy_ref_ptr_array(ref_ptrs, src_arr); current_ref_ptrs= src_arr; } /// Initializes 'items0' and remembers that it is 'current'. void init_items_ref_array() { items0= ref_ptr_array_slice(1); copy_ref_ptr_array(items0, ref_ptrs); current_ref_ptrs= items0; } bool rollup_init(); bool rollup_process_const_fields(); bool rollup_make_fields(List &all_fields, List &fields, Item_sum ***func); int rollup_send_data(uint idx); int rollup_write_data(uint idx, TMP_TABLE_PARAM *tmp_table_param, TABLE *table); void join_free(); /** Cleanup this JOIN, possibly for reuse */ void cleanup(bool full); void clear(table_map *cleared_tables); void inline clear_sum_funcs(); bool send_row_on_empty_set() { return (do_send_rows && implicit_grouping && !group_optimized_away && having_value != Item::COND_FALSE); } bool empty_result() { return (zero_result_cause && !implicit_grouping); } bool change_result(select_result *new_result, select_result *old_result); bool is_top_level_join() const { return (unit == &thd->lex->unit && (unit->fake_select_lex == 0 || select_lex == unit->fake_select_lex)); } void cache_const_exprs(); inline table_map all_tables_map() { return (table_map(1) << table_count) - 1; } void drop_unused_derived_keys(); bool get_best_combination(); bool add_sorting_to_table(JOIN_TAB *tab, ORDER *order); inline void eval_select_list_used_tables(); /* Return the table for which an index scan can be used to satisfy the sort order needed by the ORDER BY/(implicit) GROUP BY clause */ JOIN_TAB *get_sort_by_join_tab() { return (need_tmp || !sort_by_table || skip_sort_order || ((group || tmp_table_param.sum_func_count) && !group_list)) ? NULL : join_tab+const_tables; } bool setup_subquery_caches(); bool shrink_join_buffers(JOIN_TAB *jt, ulonglong curr_space, ulonglong needed_space); void set_allowed_join_cache_types(); bool is_allowed_hash_join_access() { return MY_TEST(allowed_join_cache_types & JOIN_CACHE_HASHED_BIT) && max_allowed_join_cache_level > JOIN_CACHE_HASHED_BIT; } /* Check if we need to create a temporary table. This has to be done if all tables are not already read (const tables) and one of the following conditions holds: - We are using DISTINCT (simple distinct's are already optimized away) - We are using an ORDER BY or GROUP BY on fields not in the first table - We are using different ORDER BY and GROUP BY orders - The user wants us to buffer the result. - We are using WINDOW functions. When the WITH ROLLUP modifier is present, we cannot skip temporary table creation for the DISTINCT clause just because there are only const tables. */ bool test_if_need_tmp_table() { return ((const_tables != table_count && ((select_distinct || !simple_order || !simple_group) || (group_list && order) || MY_TEST(select_options & OPTION_BUFFER_RESULT))) || (rollup.state != ROLLUP::STATE_NONE && select_distinct) || select_lex->have_window_funcs()); } bool choose_subquery_plan(table_map join_tables); void get_partial_cost_and_fanout(int end_tab_idx, table_map filter_map, double *read_time_arg, double *record_count_arg); void get_prefix_cost_and_fanout(uint n_tables, double *read_time_arg, double *record_count_arg); double get_examined_rows(); /* defined in opt_subselect.cc */ bool transform_max_min_subquery(); /* True if this JOIN is a subquery under an IN predicate. */ bool is_in_subquery() { return (unit->item && unit->item->is_in_predicate()); } bool save_explain_data(Explain_query *output, bool can_overwrite, bool need_tmp_table, bool need_order, bool distinct); int save_explain_data_intern(Explain_query *output, bool need_tmp_table, bool need_order, bool distinct, const char *message); JOIN_TAB *first_breadth_first_tab() { return join_tab; } bool check_two_phase_optimization(THD *thd); bool inject_cond_into_where(Item *injected_cond); bool check_for_splittable_materialized(); void add_keyuses_for_splitting(); bool inject_best_splitting_cond(table_map remaining_tables); bool fix_all_splittings_in_plan(); bool inject_splitting_cond_for_all_tables_with_split_opt(); void make_notnull_conds_for_range_scans(); bool transform_in_predicates_into_in_subq(THD *thd); bool optimize_upper_rownum_func(); private: /** Create a temporary table to be used for processing DISTINCT/ORDER BY/GROUP BY. @note Will modify JOIN object wrt sort/group attributes @param tab the JOIN_TAB object to attach created table to @param tmp_table_fields List of items that will be used to define column types of the table. @param tmp_table_group Group key to use for temporary table, NULL if none. @param save_sum_fields If true, do not replace Item_sum items in @c tmp_fields list with Item_field items referring to fields in temporary table. @returns false on success, true on failure */ bool create_postjoin_aggr_table(JOIN_TAB *tab, List *tmp_table_fields, ORDER *tmp_table_group, bool save_sum_fields, bool distinct, bool keep_row_ordermake); /** Optimize distinct when used on a subset of the tables. E.g.,: SELECT DISTINCT t1.a FROM t1,t2 WHERE t1.b=t2.b In this case we can stop scanning t2 when we have found one t1.a */ void optimize_distinct(); void cleanup_item_list(List &items) const; bool add_having_as_table_cond(JOIN_TAB *tab); bool make_aggr_tables_info(); bool add_fields_for_current_rowid(JOIN_TAB *cur, List *fields); void free_pushdown_handlers(List& join_list); void init_join_cache_and_keyread(); bool prepare_sum_aggregators(THD *thd,Item_sum **func_ptr, bool need_distinct); bool transform_in_predicates_into_equalities(THD *thd); bool transform_all_conds_and_on_exprs(THD *thd, Item_transformer transformer); bool transform_all_conds_and_on_exprs_in_join_list(THD *thd, List *join_list, Item_transformer transformer); }; enum enum_with_bush_roots { WITH_BUSH_ROOTS, WITHOUT_BUSH_ROOTS}; enum enum_with_const_tables { WITH_CONST_TABLES, WITHOUT_CONST_TABLES}; JOIN_TAB *first_linear_tab(JOIN *join, enum enum_with_bush_roots include_bush_roots, enum enum_with_const_tables const_tbls); JOIN_TAB *next_linear_tab(JOIN* join, JOIN_TAB* tab, enum enum_with_bush_roots include_bush_roots); JOIN_TAB *first_top_level_tab(JOIN *join, enum enum_with_const_tables with_const); JOIN_TAB *next_top_level_tab(JOIN *join, JOIN_TAB *tab); typedef struct st_select_check { uint const_ref,reg_ref; } SELECT_CHECK; extern const char *join_type_str[]; /* Extern functions in sql_select.cc */ void count_field_types(SELECT_LEX *select_lex, TMP_TABLE_PARAM *param, List &fields, bool reset_with_sum_func); bool setup_copy_fields(THD *thd, TMP_TABLE_PARAM *param, Ref_ptr_array ref_pointer_array, List &new_list1, List &new_list2, uint elements, List &fields); void copy_fields(TMP_TABLE_PARAM *param); bool copy_funcs(Item **func_ptr, const THD *thd); uint find_shortest_key(TABLE *table, const key_map *usable_keys); bool is_indexed_agg_distinct(JOIN *join, List *out_args); /* functions from opt_sum.cc */ bool simple_pred(Item_func *func_item, Item **args, bool *inv_order); int opt_sum_query(THD* thd, List &tables, List &all_fields, COND *conds); /* from sql_delete.cc, used by opt_range.cc */ extern "C" int refpos_order_cmp(void *arg, const void *a,const void *b); /** class to copying an field/item to a key struct */ class store_key :public Sql_alloc { public: bool null_key; /* TRUE <=> the value of the key has a null part */ enum store_key_result { STORE_KEY_OK, STORE_KEY_FATAL, STORE_KEY_CONV }; enum Type { FIELD_STORE_KEY, ITEM_STORE_KEY, CONST_ITEM_STORE_KEY }; store_key(THD *thd, Field *field_arg, uchar *ptr, uchar *null, uint length) :null_key(0), null_ptr(null), err(0) { to_field=field_arg->new_key_field(thd->mem_root, field_arg->table, ptr, length, null, 1); } store_key(store_key &arg) :Sql_alloc(), null_key(arg.null_key), to_field(arg.to_field), null_ptr(arg.null_ptr), err(arg.err) {} virtual ~store_key() = default; /** Not actually needed */ virtual enum Type type() const=0; virtual const char *name() const=0; virtual bool store_key_is_const() { return false; } /** @brief sets ignore truncation warnings mode and calls the real copy method @details this function makes sure truncation warnings when preparing the key buffers don't end up as errors (because of an enclosing INSERT/UPDATE). */ enum store_key_result copy(THD *thd) { enum_check_fields org_count_cuted_fields= thd->count_cuted_fields; Use_relaxed_field_copy urfc(to_field->table->in_use); /* If needed, perform CharsetNarrowing for making ref access lookup keys. */ Utf8_narrow do_narrow(to_field, do_cset_narrowing); store_key_result result= copy_inner(); do_narrow.stop(); thd->count_cuted_fields= org_count_cuted_fields; return result; } protected: Field *to_field; // Store data here uchar *null_ptr; uchar err; /* This is set to true if we need to do Charset Narrowing when making a lookup key. */ bool do_cset_narrowing= false; virtual enum store_key_result copy_inner()=0; }; class store_key_field: public store_key { Copy_field copy_field; const char *field_name; public: store_key_field(THD *thd, Field *to_field_arg, uchar *ptr, uchar *null_ptr_arg, uint length, Field *from_field, const char *name_arg) :store_key(thd, to_field_arg,ptr, null_ptr_arg ? null_ptr_arg : from_field->maybe_null() ? &err : (uchar*) 0, length), field_name(name_arg) { if (to_field) { copy_field.set(to_field,from_field,0); setup_charset_narrowing(); } } enum Type type() const override { return FIELD_STORE_KEY; } const char *name() const override { return field_name; } void change_source_field(Item_field *fld_item) { copy_field.set(to_field, fld_item->field, 0); field_name= fld_item->full_name(); setup_charset_narrowing(); } /* Setup CharsetNarrowing if necessary */ void setup_charset_narrowing() { do_cset_narrowing= Utf8_narrow::should_do_narrowing(copy_field.to_field, copy_field.from_field->charset()); } protected: enum store_key_result copy_inner() override { TABLE *table= copy_field.to_field->table; MY_BITMAP *old_map= dbug_tmp_use_all_columns(table, &table->write_set); /* It looks like the next statement is needed only for a simplified hash function over key values used now in BNLH join. When the implementation of this function will be replaced for a proper full version this statement probably should be removed. */ bzero(copy_field.to_ptr,copy_field.to_length); copy_field.do_copy(©_field); dbug_tmp_restore_column_map(&table->write_set, old_map); null_key= to_field->is_null(); return err != 0 ? STORE_KEY_FATAL : STORE_KEY_OK; } }; class store_key_item :public store_key { protected: Item *item; /* Flag that forces usage of save_val() method which save value of the item instead of save_in_field() method which saves result. */ bool use_value; public: store_key_item(THD *thd, Field *to_field_arg, uchar *ptr, uchar *null_ptr_arg, uint length, Item *item_arg, bool val) :store_key(thd, to_field_arg, ptr, null_ptr_arg ? null_ptr_arg : item_arg->maybe_null() ? &err : (uchar*) 0, length), item(item_arg), use_value(val) { /* Setup CharsetNarrowing to be done if necessary */ do_cset_narrowing= Utf8_narrow::should_do_narrowing(to_field, item->collation.collation); } store_key_item(store_key &arg, Item *new_item, bool val) :store_key(arg), item(new_item), use_value(val) {} enum Type type() const override { return ITEM_STORE_KEY; } const char *name() const override { return "func"; } protected: enum store_key_result copy_inner() override { TABLE *table= to_field->table; MY_BITMAP *old_map= dbug_tmp_use_all_columns(table, &table->write_set); int res= FALSE; /* It looks like the next statement is needed only for a simplified hash function over key values used now in BNLH join. When the implementation of this function will be replaced for a proper full version this statement probably should be removed. */ to_field->reset(); if (use_value) item->save_val(to_field); else res= item->save_in_field(to_field, 1); /* Item::save_in_field() may call Item::val_xxx(). And if this is a subquery we need to check for errors executing it and react accordingly */ if (!res && table->in_use->is_error()) res= 1; /* STORE_KEY_FATAL */ dbug_tmp_restore_column_map(&table->write_set, old_map); null_key= to_field->is_null() || item->null_value; return ((err != 0 || res < 0 || res > 2) ? STORE_KEY_FATAL : (store_key_result) res); } }; class store_key_const_item :public store_key_item { bool inited; public: store_key_const_item(THD *thd, Field *to_field_arg, uchar *ptr, uchar *null_ptr_arg, uint length, Item *item_arg) :store_key_item(thd, to_field_arg, ptr, null_ptr_arg ? null_ptr_arg : item_arg->maybe_null() ? &err : (uchar*) 0, length, item_arg, FALSE), inited(0) { } store_key_const_item(store_key &arg, Item *new_item) :store_key_item(arg, new_item, FALSE), inited(0) {} enum Type type() const override { return CONST_ITEM_STORE_KEY; } const char *name() const override { return "const"; } bool store_key_is_const() override { return true; } protected: enum store_key_result copy_inner() override { int res; if (!inited) { inited=1; TABLE *table= to_field->table; MY_BITMAP *old_map= dbug_tmp_use_all_columns(table, &table->write_set); if ((res= item->save_in_field(to_field, 1))) { if (!err) err= res < 0 ? 1 : res; /* 1=STORE_KEY_FATAL */ } /* Item::save_in_field() may call Item::val_xxx(). And if this is a subquery we need to check for errors executing it and react accordingly */ if (!err && to_field->table->in_use->is_error()) err= 1; /* STORE_KEY_FATAL */ dbug_tmp_restore_column_map(&table->write_set, old_map); } null_key= to_field->is_null() || item->null_value; return (err > 2 ? STORE_KEY_FATAL : (store_key_result) err); } }; void best_access_path(JOIN *join, JOIN_TAB *s, table_map remaining_tables, const POSITION *join_positions, uint idx, bool disable_jbuf, double record_count, POSITION *pos, POSITION *loose_scan_pos); bool cp_buffer_from_ref(THD *thd, TABLE *table, TABLE_REF *ref); bool error_if_full_join(JOIN *join); int report_error(TABLE *table, int error); int safe_index_read(JOIN_TAB *tab); int get_quick_record(SQL_SELECT *select); int setup_order(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, List &fields, List &all_fields, ORDER *order, bool from_window_spec= false); int setup_group(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, List &fields, List &all_fields, ORDER *order, bool *hidden_group_fields, bool from_window_spec= false); bool fix_inner_refs(THD *thd, List &all_fields, SELECT_LEX *select, Ref_ptr_array ref_pointer_array); int join_read_key2(THD *thd, struct st_join_table *tab, TABLE *table, struct st_table_ref *table_ref); bool handle_select(THD *thd, LEX *lex, select_result *result, ulong setup_tables_done_option); bool mysql_select(THD *thd, TABLE_LIST *tables, List &list, COND *conds, uint og_num, ORDER *order, ORDER *group, Item *having, ORDER *proc_param, ulonglong select_type, select_result *result, SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex); void free_underlaid_joins(THD *thd, SELECT_LEX *select); bool mysql_explain_union(THD *thd, SELECT_LEX_UNIT *unit, select_result *result); /* General routine to change field->ptr of a NULL-terminated array of Field objects. Useful when needed to call val_int, val_str or similar and the field data is not in table->record[0] but in some other structure. set_key_field_ptr changes all fields of an index using a key_info object. All methods presume that there is at least one field to change. */ class Virtual_tmp_table: public TABLE { /** Destruct collected fields. This method can be called on errors, when we could not make the virtual temporary table completely, e.g. when some of the fields could not be created or added. This is needed to avoid memory leaks, as some fields can be BLOB variants and thus can have String onboard. Strings must be destructed as they store data on the heap (not on MEM_ROOT). */ void destruct_fields() { for (uint i= 0; i < s->fields; i++) { field[i]->free(); delete field[i]; // to invoke the field destructor } s->fields= 0; // safety } protected: /** The number of the fields that are going to be in the table. We remember the number of the fields at init() time, and at open() we check that all of the fields were really added. */ uint m_alloced_field_count; /** Setup field pointers and null-bit pointers. */ void setup_field_pointers(); public: /** Create a new empty virtual temporary table on the thread mem_root. After creation, the caller must: - call init() - populate the table with new fields using add(). - call open(). @param thd - Current thread. */ static void *operator new(size_t size, THD *thd) throw(); static void operator delete(void *ptr, size_t size) { TRASH_FREE(ptr, size); } static void operator delete(void *, THD *) throw(){} Virtual_tmp_table(THD *thd) : m_alloced_field_count(0) { reset(); temp_pool_slot= MY_BIT_NONE; in_use= thd; copy_blobs= true; alias.set("", 0, &my_charset_bin); } ~Virtual_tmp_table() { if (s) destruct_fields(); } /** Allocate components for the given number of fields. - fields[] - s->blob_fields[], - bitmaps: def_read_set, def_write_set, tmp_set, eq_join_set, cond_set. @param field_count - The number of fields we plan to add to the table. @returns false - on success. @returns true - on error. */ bool init(uint field_count); /** Add one Field to the end of the field array, update members: s->reclength, s->fields, s->blob_fields, s->null_fuelds. */ bool add(Field *new_field) { DBUG_ASSERT(s->fields < m_alloced_field_count); new_field->init(this); field[s->fields]= new_field; s->reclength+= new_field->pack_length(); if (!(new_field->flags & NOT_NULL_FLAG)) s->null_fields++; if (new_field->flags & BLOB_FLAG) { // Note, s->blob_fields was incremented in Field_blob::Field_blob DBUG_ASSERT(s->blob_fields); DBUG_ASSERT(s->blob_fields <= m_alloced_field_count); s->blob_field[s->blob_fields - 1]= s->fields; } new_field->field_index= s->fields++; return false; } /** Add fields from a Spvar_definition list @returns false - on success. @returns true - on error. */ bool add(List &field_list); /** Open a virtual table for read/write: - Setup end markers in TABLE::field and TABLE_SHARE::blob_fields, - Allocate a buffer in TABLE::record[0]. - Set field pointers (Field::ptr, Field::null_pos, Field::null_bit) to the allocated record. This method is called when all of the fields have been added to the table. After calling this method the table is ready for read and write operations. @return false - on success @return true - on error (e.g. could not allocate the record buffer). */ bool open(); void set_all_fields_to_null() { for (uint i= 0; i < s->fields; i++) field[i]->set_null(); } /** Set all fields from a compatible item list. The number of fields in "this" must be equal to the number of elements in "value". */ bool sp_set_all_fields_from_item_list(THD *thd, List &items); /** Set all fields from a compatible item. The number of fields in "this" must be the same with the number of elements in "value". */ bool sp_set_all_fields_from_item(THD *thd, Item *value); /** Find a ROW element index by its name Assumes that "this" is used as a storage for a ROW-type SP variable. @param [OUT] idx - the index of the found field is returned here @param [IN] field_name - find a field with this name @return true - on error (the field was not found) @return false - on success (idx[0] was set to the field index) */ bool sp_find_field_by_name(uint *idx, const LEX_CSTRING &name) const; /** Find a ROW element index by its name. If the element is not found, and error is issued. @param [OUT] idx - the index of the found field is returned here @param [IN] var_name - the name of the ROW variable (for error reporting) @param [IN] field_name - find a field with this name @return true - on error (the field was not found) @return false - on success (idx[0] was set to the field index) */ bool sp_find_field_by_name_or_error(uint *idx, const LEX_CSTRING &var_name, const LEX_CSTRING &field_name) const; }; /** Create a reduced TABLE object with properly set up Field list from a list of field definitions. The created table doesn't have a table handler associated with it, has no keys, no group/distinct, no copy_funcs array. The sole purpose of this TABLE object is to use the power of Field class to read/write data to/from table->record[0]. Then one can store the record in any container (RB tree, hash, etc). The table is created in THD mem_root, so are the table's fields. Consequently, if you don't BLOB fields, you don't need to free it. @param thd connection handle @param field_list list of column definitions @return 0 if out of memory, or a TABLE object ready for read and write in case of success */ inline Virtual_tmp_table * create_virtual_tmp_table(THD *thd, List &field_list) { Virtual_tmp_table *table; if (!(table= new(thd) Virtual_tmp_table(thd))) return NULL; /* If "simulate_create_virtual_tmp_table_out_of_memory" debug option is enabled, we now enable "simulate_out_of_memory". This effectively makes table->init() fail on OOM inside multi_alloc_root(). This is done to test that ~Virtual_tmp_table() called from the "delete" below correcly handles OOM. */ DBUG_EXECUTE_IF("simulate_create_virtual_tmp_table_out_of_memory", DBUG_SET("+d,simulate_out_of_memory");); if (table->init(field_list.elements) || table->add(field_list) || table->open()) { delete table; return NULL; } return table; } /** Create a new virtual temporary table consisting of a single field. SUM(DISTINCT expr) and similar numeric aggregate functions use this. @param thd - Current thread @param field - The field that will be added into the table. @return NULL - On error. @return !NULL - A pointer to the created table that is ready for read and write. */ inline TABLE * create_virtual_tmp_table(THD *thd, Field *field) { Virtual_tmp_table *table; DBUG_ASSERT(field); if (!(table= new(thd) Virtual_tmp_table(thd))) return NULL; if (table->init(1) || table->add(field) || table->open()) { delete table; return NULL; } return table; } int test_if_item_cache_changed(List &list); int join_init_read_record(JOIN_TAB *tab); void set_position(JOIN *join,uint idx,JOIN_TAB *table,KEYUSE *key); inline Item * and_items(THD *thd, Item* cond, Item *item) { return (cond ? (new (thd->mem_root) Item_cond_and(thd, cond, item)) : item); } inline Item * or_items(THD *thd, Item* cond, Item *item) { return (cond ? (new (thd->mem_root) Item_cond_or(thd, cond, item)) : item); } bool choose_plan(JOIN *join, table_map join_tables); void optimize_wo_join_buffering(JOIN *join, uint first_tab, uint last_tab, table_map last_remaining_tables, bool first_alt, uint no_jbuf_before, double *outer_rec_count, double *reopt_cost); Item_equal *find_item_equal(COND_EQUAL *cond_equal, Field *field, bool *inherited_fl); extern bool test_if_ref(Item *, Item_field *left_item,Item *right_item); inline bool optimizer_flag(const THD *thd, ulonglong flag) { return (thd->variables.optimizer_switch & flag); } /* int print_fake_select_lex_join(select_result_sink *result, bool on_the_fly, SELECT_LEX *select_lex, uint8 select_options); */ uint get_index_for_order(ORDER *order, TABLE *table, SQL_SELECT *select, ha_rows limit, ha_rows *scanned_limit, bool *need_sort, bool *reverse); ORDER *simple_remove_const(ORDER *order, COND *where); bool const_expression_in_where(COND *cond, Item *comp_item, Field *comp_field= NULL, Item **const_item= NULL); bool cond_is_datetime_is_null(Item *cond); bool cond_has_datetime_is_null(Item *cond); /* Table elimination entry point function */ void eliminate_tables(JOIN *join); /* Index Condition Pushdown entry point function */ void push_index_cond(JOIN_TAB *tab, uint keyno); #define OPT_LINK_EQUAL_FIELDS 1 /* EXPLAIN-related utility functions */ int print_explain_message_line(select_result_sink *result, uint8 options, bool is_analyze, uint select_number, const char *select_type, ha_rows *rows, const char *message); void explain_append_mrr_info(QUICK_RANGE_SELECT *quick, String *res); int append_possible_keys(MEM_ROOT *alloc, String_list &list, TABLE *table, key_map possible_keys); void unpack_to_base_table_fields(TABLE *table); /**************************************************************************** Temporary table support for SQL Runtime ***************************************************************************/ #define STRING_TOTAL_LENGTH_TO_PACK_ROWS 128 #define AVG_STRING_LENGTH_TO_PACK_ROWS 64 #define RATIO_TO_PACK_ROWS 2 #define MIN_STRING_LENGTH_TO_PACK_ROWS 10 void calc_group_buffer(TMP_TABLE_PARAM *param, ORDER *group); TABLE *create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List &fields, ORDER *group, bool distinct, bool save_sum_fields, ulonglong select_options, ha_rows rows_limit, const LEX_CSTRING *alias, bool do_not_open=FALSE, bool keep_row_order= FALSE); TABLE *create_tmp_table_for_schema(THD *thd, TMP_TABLE_PARAM *param, const ST_SCHEMA_TABLE &schema_table, longlong select_options, const LEX_CSTRING &alias, bool do_not_open, bool keep_row_order); void free_tmp_table(THD *thd, TABLE *entry); bool create_internal_tmp_table_from_heap(THD *thd, TABLE *table, TMP_ENGINE_COLUMNDEF *start_recinfo, TMP_ENGINE_COLUMNDEF **recinfo, int error, bool ignore_last_dupp_key_error, bool *is_duplicate); bool create_internal_tmp_table(TABLE *table, KEY *keyinfo, TMP_ENGINE_COLUMNDEF *start_recinfo, TMP_ENGINE_COLUMNDEF **recinfo, ulonglong options); bool instantiate_tmp_table(TABLE *table, KEY *keyinfo, TMP_ENGINE_COLUMNDEF *start_recinfo, TMP_ENGINE_COLUMNDEF **recinfo, ulonglong options); bool open_tmp_table(TABLE *table); double prev_record_reads(const POSITION *positions, uint idx, table_map found_ref); void fix_list_after_tbl_changes(SELECT_LEX *new_parent, List *tlist); double get_tmp_table_lookup_cost(THD *thd, double row_count, uint row_size); double get_tmp_table_write_cost(THD *thd, double row_count, uint row_size); void optimize_keyuse(JOIN *join, DYNAMIC_ARRAY *keyuse_array); bool sort_and_filter_keyuse(THD *thd, DYNAMIC_ARRAY *keyuse, bool skip_unprefixed_keyparts); struct st_cond_statistic { Item *cond; Field *field_arg; ulong positive; }; typedef struct st_cond_statistic COND_STATISTIC; ulong check_selectivity(THD *thd, ulong rows_to_read, TABLE *table, List *conds); class Pushdown_query: public Sql_alloc { public: SELECT_LEX *select_lex; bool store_data_in_temp_table; group_by_handler *handler; Item *having; Pushdown_query(SELECT_LEX *select_lex_arg, group_by_handler *handler_arg) : select_lex(select_lex_arg), store_data_in_temp_table(0), handler(handler_arg), having(0) {} ~Pushdown_query() { delete handler; } /* Function that calls the above scan functions */ int execute(JOIN *); }; class derived_handler; class Pushdown_derived: public Sql_alloc { public: TABLE_LIST *derived; derived_handler *handler; Pushdown_derived(TABLE_LIST *tbl, derived_handler *h); int execute(); }; class select_handler; bool test_if_order_compatible(SQL_I_List &a, SQL_I_List &b); int test_if_group_changed(List &list); int create_sort_index(THD *thd, JOIN *join, JOIN_TAB *tab, Filesort *fsort); JOIN_TAB *first_explain_order_tab(JOIN* join); JOIN_TAB *next_explain_order_tab(JOIN* join, JOIN_TAB* tab); bool is_eliminated_table(table_map eliminated_tables, TABLE_LIST *tbl); bool check_simple_equality(THD *thd, const Item::Context &ctx, Item *left_item, Item *right_item, COND_EQUAL *cond_equal); void propagate_new_equalities(THD *thd, Item *cond, List *new_equalities, COND_EQUAL *inherited, bool *is_simplifiable_cond); #define PREV_BITS(type, N_BITS) ((type)my_set_bits(N_BITS)) #endif /* SQL_SELECT_INCLUDED */ mysql/server/private/ft_global.h000064400000006051151027430560013000 0ustar00/* Copyright (c) 2000-2005, 2007 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Written by Sergei A. Golubchik, who has a shared copyright to this code */ /* some definitions for full-text indices */ /* #include "myisam.h" */ #ifndef _ft_global_h #define _ft_global_h #ifdef __cplusplus extern "C" { #endif #include #define HA_FT_MAXBYTELEN 254 #define HA_FT_MAXCHARLEN (HA_FT_MAXBYTELEN/3) #define DEFAULT_FTB_SYNTAX "+ -><()~*:\"\"&|" typedef struct st_ft_info FT_INFO; struct _ft_vft { int (*read_next)(FT_INFO *, char *); float (*find_relevance)(FT_INFO *, uchar *, uint); void (*close_search)(FT_INFO *); float (*get_relevance)(FT_INFO *); void (*reinit_search)(FT_INFO *); }; typedef struct st_ft_info_ext FT_INFO_EXT; struct _ft_vft_ext { uint (*get_version)(); // Extended API version ulonglong (*get_flags)(); ulonglong (*get_docid)(FT_INFO_EXT *); ulonglong (*count_matches)(FT_INFO_EXT *); }; /* Flags for extended FT API */ #define FTS_ORDERED_RESULT (1LL << 1) #define FTS_DOCID_IN_RESULT (1LL << 2) #define FTS_DOC_ID_COL_NAME "FTS_DOC_ID" #ifndef FT_CORE struct st_ft_info { struct _ft_vft *please; /* INTERCAL style :-) */ }; struct st_ft_info_ext { struct _ft_vft *please; /* INTERCAL style :-) */ struct _ft_vft_ext *could_you; }; #endif extern const char *ft_stopword_file; extern const char *ft_precompiled_stopwords[]; extern ulong ft_min_word_len; extern ulong ft_max_word_len; extern ulong ft_query_expansion_limit; extern const char *ft_boolean_syntax; extern struct st_mysql_ftparser ft_default_parser; int ft_init_stopwords(void); void ft_free_stopwords(void); #define FT_NL 0 #define FT_BOOL 1 #define FT_SORTED 2 #define FT_EXPAND 4 /* query expansion */ FT_INFO *ft_init_search(uint,void *, uint, uchar *, size_t, CHARSET_INFO *, uchar *); my_bool ft_boolean_check_syntax_string(const uchar *, size_t length, CHARSET_INFO *cs); /* Internal symbols for fulltext between maria and MyISAM */ #define HA_FT_WTYPE HA_KEYTYPE_FLOAT #define HA_FT_WLEN 4 #define FT_SEGS 2 #define ft_sintXkorr(A) mi_sint4korr(A) #define ft_intXstore(T,A) mi_int4store(T,A) extern const HA_KEYSEG ft_keysegs[FT_SEGS]; typedef union {int32 i; float f;} FT_WEIGTH; #ifdef __cplusplus } #endif #endif mysql/server/private/item_subselect.h000064400000163421151027430560014063 0ustar00#ifndef ITEM_SUBSELECT_INCLUDED #define ITEM_SUBSELECT_INCLUDED /* Copyright (c) 2002, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* subselect Item */ #include "item.h" #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include class st_select_lex; class st_select_lex_unit; class JOIN; class select_result_interceptor; class subselect_engine; class subselect_hash_sj_engine; class Item_bool_func2; class Comp_creator; class With_element; class Field_pair; typedef class st_select_lex SELECT_LEX; /** Convenience typedef used in this file, and further used by any files including this file. */ typedef Comp_creator* (*chooser_compare_func_creator)(bool invert); class Cached_item; class Subq_materialization_tracker; class Explain_subq_materialization; /* base class for subselects */ class Item_subselect :public Item_result_field, protected Used_tables_and_const_cache { /* Set to TRUE if the value is assigned for the subselect FALSE: subquery not executed or the subquery returns an empty result */ bool value_assigned; bool own_engine; /* the engine was not taken from other Item_subselect */ protected: /* thread handler, will be assigned in fix_fields only */ THD *thd; /* old engine if engine was changed */ subselect_engine *old_engine; /* allowed number of columns (1 for single value subqueries) */ uint max_columns; /* where subquery is placed */ enum_parsing_place parsing_place; /* work with 'substitution' */ bool have_to_be_excluded; bool inside_first_fix_fields; bool done_first_fix_fields; Item *expr_cache; /* Set to TRUE if at optimization or execution time we determine that this item's value is a constant. We need this member because it is not possible to substitute 'this' with a constant item. */ bool forced_const; /* Set to the result of the last call of is_expensive() */ bool expensive_fl; #ifndef DBUG_OFF /* Count the number of times this subquery predicate has been executed. */ uint exec_counter; #endif public: /* Used inside Item_subselect::fix_fields() according to this scenario: > Item_subselect::fix_fields > engine->prepare > child_join->prepare (Here we realize we need to do the rewrite and set substitution= some new Item, eg. Item_in_optimizer ) < child_join->prepare < engine->prepare *ref= substitution; substitution= NULL; < Item_subselect::fix_fields */ /* TODO make this protected member again. */ Item *substitution; /* engine that perform execution of subselect (single select or union) */ /* TODO make this protected member again. */ subselect_engine *engine; /* unit of subquery */ st_select_lex_unit *unit; /* Cached buffers used when calling filesort in sub queries */ Filesort_buffer filesort_buffer; LEX_STRING sortbuffer; /* A reference from inside subquery predicate to somewhere outside of it */ class Ref_to_outside : public Sql_alloc { public: st_select_lex *select; /* Select where the reference is pointing to */ /* What is being referred. This may be NULL when we're referring to an aggregate function. */ Item *item; }; /* References from within this subquery to somewhere outside of it (i.e. to parent select, grandparent select, etc) */ List upper_refs; st_select_lex *parent_select; /* TRUE<=>Table Elimination has made it redundant to evaluate this select (and so it is not part of QEP, etc) */ bool eliminated; /* subquery is transformed */ bool changed; /* TRUE <=> The underlying SELECT is correlated w.r.t some ancestor select */ bool is_correlated; /* TRUE <=> the subquery contains a recursive reference in the FROM list of one of its selects. In this case some of subquery optimization strategies cannot be applied for the subquery; */ bool with_recursive_reference; /* To link Item_subselects containing references to the same recursive CTE */ Item_subselect *next_with_rec_ref; enum subs_type {UNKNOWN_SUBS, SINGLEROW_SUBS, EXISTS_SUBS, IN_SUBS, ALL_SUBS, ANY_SUBS}; Item_subselect(THD *thd); virtual subs_type substype() { return UNKNOWN_SUBS; } bool is_exists_predicate() { return substype() == Item_subselect::EXISTS_SUBS; } bool is_in_predicate() { return get_IN_subquery() != NULL; } /* We need this method, because some compilers do not allow 'this' pointer in constructor initialization list, but we need to pass a pointer to subselect Item class to select_result_interceptor's constructor. */ virtual void init (st_select_lex *select_lex, select_result_interceptor *result); ~Item_subselect(); void cleanup() override; virtual void reset() { eliminated= FALSE; null_value= 1; } /** Set the subquery result to a default value consistent with the semantics of the result row produced for queries with implicit grouping. */ void no_rows_in_result() override= 0; virtual bool select_transformer(JOIN *join); bool assigned() { return value_assigned; } void assigned(bool a) { value_assigned= a; } enum Type type() const override; bool is_null() override { update_null_value(); return null_value; } bool fix_fields(THD *thd, Item **ref) override; bool mark_as_dependent(THD *thd, st_select_lex *select, Item *item); void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; void recalc_used_tables(st_select_lex *new_parent, bool after_pullout); virtual bool exec(); /* If subquery optimization or execution determines that the subquery has an empty result, mark the subquery predicate as a constant value. */ void make_const() { used_tables_cache= 0; const_item_cache= 0; forced_const= TRUE; } virtual bool fix_length_and_dec(); table_map used_tables() const override; table_map not_null_tables() const override { return 0; } bool const_item() const override; inline table_map get_used_tables_cache() { return used_tables_cache; } Item *get_tmp_table_item(THD *thd) override; void update_used_tables() override; void print(String *str, enum_query_type query_type) override; virtual bool have_guarded_conds() { return FALSE; } bool change_engine(subselect_engine *eng) { old_engine= engine; engine= eng; return eng == 0; } bool engine_changed(subselect_engine *eng) { return engine != eng; } /* True if this subquery has been already evaluated. Implemented only for single select and union subqueries only. */ bool is_evaluated() const; bool is_uncacheable() const; bool is_expensive() override; /* Used by max/min subquery to initialize value presence registration mechanism. Engine call this method before rexecution query. */ virtual void reset_value_registration() {} enum_parsing_place place() { return parsing_place; } bool walk(Item_processor processor, bool walk_subquery, void *arg) override; bool unknown_splocal_processor(void *arg) override; bool mark_as_eliminated_processor(void *arg) override; bool eliminate_subselect_processor(void *arg) override; bool enumerate_field_refs_processor(void *arg) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("select ...", arg, VCOL_IMPOSSIBLE); } /** Callback to test if an IN predicate is expensive. @notes The return value affects the behavior of make_cond_for_table(). @retval TRUE if the predicate is expensive @retval FALSE otherwise */ bool is_expensive_processor(void *arg) override { return is_expensive(); } bool update_table_bitmaps_processor(void *arg) override; /** Get the SELECT_LEX structure associated with this Item. @return the SELECT_LEX structure associated with this Item */ st_select_lex* get_select_lex(); bool expr_cache_is_needed(THD *) override; void get_cache_parameters(List ¶meters) override; bool is_subquery_processor (void *opt_arg) override { return 1; } bool exists2in_processor(void *opt_arg) override { return 0; } bool limit_index_condition_pushdown_processor(void *opt_arg) override { return TRUE; } bool subselect_table_finder_processor(void *arg) override; void register_as_with_rec_ref(With_element *with_elem); void init_expr_cache_tracker(THD *thd); Item* do_build_clone(THD *thd) const override { return nullptr; } Item *do_get_copy(THD *thd) const override { return 0; } st_select_lex *wrap_tvc_into_select(THD *thd, st_select_lex *tvc_sl); friend class select_result_interceptor; friend class Item_in_optimizer; friend bool Item_field::fix_fields(THD *, Item **); friend int Item_field::fix_outer_field(THD *, Field **, Item **); friend bool Item_ref::fix_fields(THD *, Item **); friend void mark_select_range_as_dependent(THD*, st_select_lex*, st_select_lex*, Field*, Item*, Item_ident*, bool); friend bool convert_join_subqueries_to_semijoins(JOIN *join); }; /* single value subselect */ class Item_cache; class Item_singlerow_subselect :public Item_subselect { protected: Item_cache *value, **row; public: Item_singlerow_subselect(THD *thd_arg, st_select_lex *select_lex); Item_singlerow_subselect(THD *thd_arg): Item_subselect(thd_arg), value(0), row (0) {} void cleanup() override; subs_type substype() override { return SINGLEROW_SUBS; } void reset() override; void no_rows_in_result() override; bool select_transformer(JOIN *join) override; void store(uint i, Item* item); double val_real() override; longlong val_int() override; String *val_str(String *) override; bool val_native(THD *thd, Native *) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; const Type_handler *type_handler() const override; bool fix_length_and_dec() override; uint cols() const override; Item* element_index(uint i) override { return reinterpret_cast(row[i]); } Item** addr(uint i) override { return (Item**)row + i; } bool check_cols(uint c) override; bool null_inside() override; void bring_value() override; /** This method is used to implement a special case of semantic tree rewriting, mandated by a SQL:2003 exception in the specification. The only caller of this method is handle_sql2003_note184_exception(), see the code there for more details. Note that this method breaks the object internal integrity, by removing it's association with the corresponding SELECT_LEX, making this object orphan from the parse tree. No other method, beside the destructor, should be called on this object, as it is now invalid. @return the SELECT_LEX structure that was given in the constructor. */ st_select_lex* invalidate_and_restore_select_lex(); Item* expr_cache_insert_transformer(THD *thd, uchar *unused) override; friend class select_singlerow_subselect; }; /* used in static ALL/ANY optimization */ class select_max_min_finder_subselect; class Item_maxmin_subselect :public Item_singlerow_subselect { protected: bool max; bool was_values; // Set if we have found at least one row public: Item_maxmin_subselect(THD *thd, Item_subselect *parent, st_select_lex *select_lex, bool max); void print(String *str, enum_query_type query_type) override; void cleanup() override; bool any_value() { return was_values; } void register_value() { was_values= TRUE; } void reset_value_registration() override { was_values= FALSE; } void no_rows_in_result() override; }; /* exists subselect */ class Item_exists_subselect :public Item_subselect { protected: Item_func_not *upper_not; bool value; /* value of this item (boolean: exists/not-exists) */ bool abort_on_null; void init_length_and_dec(); bool select_prepare_to_be_in(); public: /* Used by subquery optimizations to keep track about in which clause this subquery predicate is located: NO_JOIN_NEST - the predicate is an AND-part of the WHERE join nest pointer - the predicate is an AND-part of ON expression of a join nest NULL - for all other locations */ TABLE_LIST *emb_on_expr_nest; /** Reference on the Item_in_optimizer wrapper of this subquery */ Item_in_optimizer *optimizer; /* true if we got this from EXISTS or to IN */ bool exists_transformed; Item_exists_subselect(THD *thd_arg, st_select_lex *select_lex); Item_exists_subselect(THD *thd_arg): Item_subselect(thd_arg), upper_not(NULL), abort_on_null(0), emb_on_expr_nest(NULL), optimizer(0), exists_transformed(0) {} subs_type substype() override { return EXISTS_SUBS; } void reset() override { eliminated= FALSE; value= 0; } void no_rows_in_result() override; const Type_handler *type_handler() const override { return &type_handler_bool; } longlong val_int() override; double val_real() override; String *val_str(String*) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_int(thd, ltime, fuzzydate); } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; void print(String *str, enum_query_type query_type) override; bool select_transformer(JOIN *join) override; void top_level_item() override { abort_on_null=1; } bool is_top_level_item() const override { return abort_on_null; } bool exists2in_processor(void *opt_arg) override; Item* expr_cache_insert_transformer(THD *thd, uchar *unused) override; void mark_as_condition_AND_part(TABLE_LIST *embedding) override { emb_on_expr_nest= embedding; } void under_not(Item_func_not *upper) override { upper_not= upper; }; void set_exists_transformed() { exists_transformed= TRUE; } friend class select_exists_subselect; friend class subselect_uniquesubquery_engine; friend class subselect_indexsubquery_engine; }; TABLE_LIST * const NO_JOIN_NEST=(TABLE_LIST*)0x1; /* Possible methods to execute an IN predicate. These are set by the optimizer based on user-set optimizer switches, semantic analysis and cost comparison. */ #define SUBS_NOT_TRANSFORMED 0 /* No execution method was chosen for this IN. */ /* The Final decision about the strategy is made. */ #define SUBS_STRATEGY_CHOSEN 1 #define SUBS_SEMI_JOIN 2 /* IN was converted to semi-join. */ #define SUBS_IN_TO_EXISTS 4 /* IN was converted to correlated EXISTS. */ #define SUBS_MATERIALIZATION 8 /* Execute IN via subquery materialization. */ /* Partial matching substrategies of MATERIALIZATION. */ #define SUBS_PARTIAL_MATCH_ROWID_MERGE 16 #define SUBS_PARTIAL_MATCH_TABLE_SCAN 32 /* ALL/ANY will be transformed with max/min optimization */ /* The subquery has not aggregates, transform it into a MAX/MIN query. */ #define SUBS_MAXMIN_INJECTED 64 /* The subquery has aggregates, use a special max/min subselect engine. */ #define SUBS_MAXMIN_ENGINE 128 /** Representation of IN subquery predicates of the form "left_expr IN (SELECT ...)". @details This class has: - A "subquery execution engine" (as a subclass of Item_subselect) that allows it to evaluate subqueries. (and this class participates in execution by having was_null variable where part of execution result is stored. - Transformation methods (todo: more on this). This class is not used directly, it is "wrapped" into Item_in_optimizer which provides some small bits of subquery evaluation. */ class Item_in_subselect :public Item_exists_subselect { protected: /* Cache of the left operand of the subquery predicate. Allocated in the runtime memory root, for each execution, thus need not be freed. */ List *left_expr_cache; bool first_execution; /* expr & optimizer used in subselect rewriting to store Item for all JOIN in UNION */ Item *expr; bool was_null; /* A bitmap of possible execution strategies for an IN predicate. */ uchar in_strategy; /* Tracker collecting execution parameters of a materialized subquery */ Subq_materialization_tracker *materialization_tracker; protected: /* Used to trigger on/off conditions that were pushed down to subselect */ bool *pushed_cond_guards; Comp_creator *func; protected: bool init_cond_guards(); bool select_in_like_transformer(JOIN *join); bool single_value_transformer(JOIN *join); bool row_value_transformer(JOIN * join); bool fix_having(Item *having, st_select_lex *select_lex); bool create_single_in_to_exists_cond(JOIN * join, Item **where_item, Item **having_item); bool create_row_in_to_exists_cond(JOIN * join, Item **where_item, Item **having_item); Item *left_expr; /* Important for PS/SP: left_expr_orig is the item that left_expr originally pointed at. That item is allocated on the statement arena, while left_expr could later be changed to something on the execution arena. */ Item *left_expr_orig; public: /* Priority of this predicate in the convert-to-semi-join-nest process. */ int sj_convert_priority; /* May be TRUE only for the candidates to semi-join conversion */ bool do_not_convert_to_sj; /* Types of left_expr and subquery's select list allow to perform subquery materialization. Currently, we set this to FALSE when it as well could be TRUE. This is to be properly addressed with fix for BUG#36752. */ bool types_allow_materialization; /* Same as above, but they also allow to scan the materialized table. */ bool sjm_scan_allowed; /* JoinTaB Materialization (JTBM) members */ /* TRUE <=> This subselect has been converted into non-mergeable semi-join table. */ bool is_jtbm_merged; /* (Applicable if is_jtbm_merged==TRUE) Time required to run the materialized join */ double jtbm_read_time; /* (Applicable if is_jtbm_merged==TRUE) Number of output rows in materialized join */ double jtbm_record_count; /* (Applicable if is_jtbm_merged==TRUE) TRUE <=> The materialized subselect is a degenerate subselect which produces 0 or 1 rows, which we know at optimization phase. Examples: 1. subquery has "Impossible WHERE": SELECT * FROM ot WHERE ot.column IN (SELECT it.col FROM it WHERE 2 > 3) 2. Subquery produces one row which opt_sum.cc is able to get with one lookup: SELECT * FROM ot WHERE ot.column IN (SELECT MAX(it.key_col) FROM it) */ bool is_jtbm_const_tab; /* (Applicable if is_jtbm_const_tab==TRUE) Whether the subquery has produced the row (or not) */ bool jtbm_const_row_found; /* TRUE<=>this is a flattenable semi-join, false otherwise. */ bool is_flattenable_semijoin; /* TRUE<=>registered in the list of semijoins in outer select */ bool is_registered_semijoin; List corresponding_fields; /* Used to determine how this subselect item is represented in the item tree, in case there is a need to locate it there and replace with something else. Two options are possible: 1. This item is there 'as-is'. 1. This item is wrapped within Item_in_optimizer. */ Item *original_item() { return (is_flattenable_semijoin && !exists_transformed ? (Item*)this : (Item*)optimizer); } bool *get_cond_guard(int i) { return pushed_cond_guards ? pushed_cond_guards + i : NULL; } void set_cond_guard_var(int i, bool v) { if ( pushed_cond_guards) pushed_cond_guards[i]= v; } bool have_guarded_conds() override { return MY_TEST(pushed_cond_guards); } Item_func_not_all *upper_item; // point on NOT/NOP before ALL/SOME subquery /* SET to TRUE if IN subquery is converted from an IN predicate */ bool converted_from_in_predicate; Item_in_subselect(THD *thd_arg, Item * left_expr, st_select_lex *select_lex); Item_in_subselect(THD *thd_arg): Item_exists_subselect(thd_arg), left_expr_cache(0), first_execution(TRUE), in_strategy(SUBS_NOT_TRANSFORMED), materialization_tracker(NULL), pushed_cond_guards(NULL), func(NULL), do_not_convert_to_sj(FALSE), is_jtbm_merged(FALSE), is_jtbm_const_tab(FALSE), upper_item(0), converted_from_in_predicate(FALSE) {} void cleanup() override; subs_type substype() override { return IN_SUBS; } void reset() override { eliminated= FALSE; value= 0; null_value= 0; was_null= 0; } bool select_transformer(JOIN *join) override; bool create_in_to_exists_cond(JOIN *join_arg); bool inject_in_to_exists_cond(JOIN *join_arg); bool exec() override; longlong val_int() override; double val_real() override; String *val_str(String*) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; bool test_limit(st_select_lex_unit *unit); void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return IN_PRECEDENCE; } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; bool const_item() const override { return Item_subselect::const_item() && left_expr->const_item(); } void update_used_tables() override; bool setup_mat_engine(); bool init_left_expr_cache(); /* Inform 'this' that it was computed, and contains a valid result. */ void set_first_execution() { if (first_execution) first_execution= FALSE; } bool expr_cache_is_needed(THD *thd) override; inline bool left_expr_has_null(); void disable_cond_guard_for_const_null_left_expr(int i) { if (left_expr->can_eval_in_optimize()) { if (left_expr->element_index(i)->is_null()) set_cond_guard_var(i,FALSE); } } int optimize(double *out_rows, double *cost); /* Return the identifier that we could use to identify the subquery for the user. */ int get_identifier(); void block_conversion_to_sj () { do_not_convert_to_sj= TRUE; } bool test_strategy(uchar strategy) { return MY_TEST(in_strategy & strategy); } /** Test that the IN strategy was chosen for execution. This is so when the CHOSEN flag is ON, and there is no other strategy. */ bool test_set_strategy(uchar strategy) { DBUG_ASSERT(strategy == SUBS_SEMI_JOIN || strategy == SUBS_IN_TO_EXISTS || strategy == SUBS_MATERIALIZATION || strategy == SUBS_PARTIAL_MATCH_ROWID_MERGE || strategy == SUBS_PARTIAL_MATCH_TABLE_SCAN || strategy == SUBS_MAXMIN_INJECTED || strategy == SUBS_MAXMIN_ENGINE); return ((in_strategy & SUBS_STRATEGY_CHOSEN) && (in_strategy & ~SUBS_STRATEGY_CHOSEN) == strategy); } bool is_set_strategy() { return MY_TEST(in_strategy & SUBS_STRATEGY_CHOSEN); } bool has_strategy() { return in_strategy != SUBS_NOT_TRANSFORMED; } void add_strategy (uchar strategy) { DBUG_ENTER("Item_in_subselect::add_strategy"); DBUG_PRINT("enter", ("current: %u add: %u", (uint) in_strategy, (uint) strategy)); DBUG_ASSERT(strategy != SUBS_NOT_TRANSFORMED); DBUG_ASSERT(!(strategy & SUBS_STRATEGY_CHOSEN)); /* TODO: PS re-execution breaks this condition, because check_and_do_in_subquery_rewrites() is called for each reexecution and re-adds the same strategies. DBUG_ASSERT(!(in_strategy & SUBS_STRATEGY_CHOSEN)); */ in_strategy|= strategy; DBUG_VOID_RETURN; } void reset_strategy(uchar strategy) { DBUG_ENTER("Item_in_subselect::reset_strategy"); DBUG_PRINT("enter", ("current: %u new: %u", (uint) in_strategy, (uint) strategy)); DBUG_ASSERT(strategy != SUBS_NOT_TRANSFORMED); in_strategy= strategy; DBUG_VOID_RETURN; } void set_strategy(uchar strategy) { DBUG_ENTER("Item_in_subselect::set_strategy"); DBUG_PRINT("enter", ("current: %u set: %u", (uint) in_strategy, (uint) (SUBS_STRATEGY_CHOSEN | strategy))); /* Check that only one strategy is set for execution. */ DBUG_ASSERT(strategy == SUBS_SEMI_JOIN || strategy == SUBS_IN_TO_EXISTS || strategy == SUBS_MATERIALIZATION || strategy == SUBS_PARTIAL_MATCH_ROWID_MERGE || strategy == SUBS_PARTIAL_MATCH_TABLE_SCAN || strategy == SUBS_MAXMIN_INJECTED || strategy == SUBS_MAXMIN_ENGINE); in_strategy= (SUBS_STRATEGY_CHOSEN | strategy); DBUG_VOID_RETURN; } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { return left_expr->walk(processor, walk_subquery, arg) || Item_subselect::walk(processor, walk_subquery, arg); } bool exists2in_processor(void *opt_arg __attribute__((unused))) override { return 0; }; bool pushdown_cond_for_in_subquery(THD *thd, Item *cond); Item_in_subselect *get_IN_subquery() override { return this; } inline Item** left_exp_ptr() { return &left_expr; } inline Item* left_exp() const { return left_expr; } inline Item* left_exp_orig() const { return left_expr_orig; } void init_subq_materialization_tracker(THD *thd); Subq_materialization_tracker *get_materialization_tracker() const { return materialization_tracker; } friend class Item_ref_null_helper; friend class Item_is_not_null_test; friend class Item_in_optimizer; friend class subselect_indexsubquery_engine; friend class subselect_hash_sj_engine; friend class subselect_partial_match_engine; friend class Item_exists_subselect; }; /* ALL/ANY/SOME subselect */ class Item_allany_subselect :public Item_in_subselect { public: chooser_compare_func_creator func_creator; bool all; Item_allany_subselect(THD *thd_arg, Item * left_expr, chooser_compare_func_creator fc, st_select_lex *select_lex, bool all); void cleanup() override; // only ALL subquery has upper not subs_type substype() override { return all?ALL_SUBS:ANY_SUBS; } bool select_transformer(JOIN *join) override; void create_comp_func(bool invert) { func= func_creator(invert); } void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return CMP_PRECEDENCE; } bool is_maxmin_applicable(JOIN *join); bool transform_into_max_min(JOIN *join); void no_rows_in_result() override; }; class subselect_engine: public Sql_alloc, public Type_handler_hybrid_field_type { protected: select_result_interceptor *result; /* results storage class */ THD *thd; /* pointer to current THD */ Item_subselect *item; /* item, that use this engine */ bool maybe_null; /* may be null (first item in select) */ public: enum enum_engine_type {ABSTRACT_ENGINE, SINGLE_SELECT_ENGINE, UNION_ENGINE, UNIQUESUBQUERY_ENGINE, INDEXSUBQUERY_ENGINE, HASH_SJ_ENGINE, ROWID_MERGE_ENGINE, TABLE_SCAN_ENGINE, SINGLE_COLUMN_ENGINE}; subselect_engine(Item_subselect *si, select_result_interceptor *res): Type_handler_hybrid_field_type(&type_handler_varchar), thd(NULL) { result= res; item= si; maybe_null= 0; } virtual ~subselect_engine() = default;; // to satisfy compiler virtual void cleanup()= 0; /* Also sets "thd" for subselect_engine::result. Should be called before prepare(). */ void set_thd(THD *thd_arg); THD * get_thd() { return thd ? thd : current_thd; } virtual int prepare(THD *)= 0; virtual bool fix_length_and_dec(Item_cache** row)= 0; /* Execute the engine SYNOPSIS exec() DESCRIPTION Execute the engine. The result of execution is subquery value that is either captured by previously set up select_result-based 'sink' or stored somewhere by the exec() method itself. A required side effect: If at least one pushed-down predicate is disabled, subselect_engine->no_rows() must return correct result after the exec() call. RETURN 0 - OK 1 - Either an execution error, or the engine was "changed", and the caller should call exec() again for the new engine. */ virtual int exec()= 0; virtual uint cols() const= 0; /* return number of columns in select */ virtual uint8 uncacheable()= 0; /* query is uncacheable */ virtual void exclude()= 0; virtual bool may_be_null() { return maybe_null; }; virtual table_map upper_select_const_tables()= 0; static table_map calc_const_tables(TABLE_LIST *); static table_map calc_const_tables(List &list); virtual void print(String *str, enum_query_type query_type)= 0; virtual bool change_result(Item_subselect *si, select_result_interceptor *result, bool temp= FALSE)= 0; virtual bool no_tables() const = 0; /* Return true we can guarantee that the subquery will always return one row. */ virtual bool always_returns_one_row() const { return false; } virtual bool is_executed() const { return FALSE; } /* Check if subquery produced any rows during last query execution */ virtual bool no_rows() = 0; virtual enum_engine_type engine_type() { return ABSTRACT_ENGINE; } virtual int get_identifier() { DBUG_ASSERT(0); return 0; } virtual void force_reexecution() {} protected: bool set_row(List &item_list, Item_cache **row); }; class subselect_single_select_engine: public subselect_engine { bool prepared; /* simple subselect is prepared */ bool executed; /* simple subselect is executed */ st_select_lex *select_lex; /* corresponding select_lex */ JOIN * join; /* corresponding JOIN structure */ public: subselect_single_select_engine(st_select_lex *select, select_result_interceptor *result, Item_subselect *item); void cleanup() override; int prepare(THD *thd) override; bool fix_length_and_dec(Item_cache** row) override; int exec() override; uint cols() const override; uint8 uncacheable() override; void exclude() override; table_map upper_select_const_tables() override; void print(String *str, enum_query_type query_type) override; bool change_result(Item_subselect *si, select_result_interceptor *result, bool temp) override; bool no_tables() const override; bool always_returns_one_row() const override; bool may_be_null() override; bool is_executed() const override { return executed; } bool no_rows() override; enum_engine_type engine_type() override { return SINGLE_SELECT_ENGINE; } int get_identifier() override; void force_reexecution() override; void change_select(st_select_lex *new_select) { select_lex= new_select; } friend class subselect_hash_sj_engine; friend class Item_in_subselect; friend bool execute_degenerate_jtbm_semi_join(THD *thd, TABLE_LIST *tbl, Item_in_subselect *subq_pred, List &eq_list); }; class subselect_union_engine: public subselect_engine { st_select_lex_unit *unit; /* corresponding unit structure */ public: subselect_union_engine(st_select_lex_unit *u, select_result_interceptor *result, Item_subselect *item); void cleanup() override; int prepare(THD *) override; bool fix_length_and_dec(Item_cache** row) override; int exec() override; uint cols() const override; uint8 uncacheable() override; void exclude() override; table_map upper_select_const_tables() override; void print(String *str, enum_query_type query_type) override; bool change_result(Item_subselect *si, select_result_interceptor *result, bool temp= FALSE) override; bool no_tables() const override; bool is_executed() const override; void force_reexecution() override; bool no_rows() override; enum_engine_type engine_type() override { return UNION_ENGINE; } }; struct st_join_table; /* A subquery execution engine that evaluates the subquery by doing one index lookup in a unique index. This engine is used to resolve subqueries in forms outer_expr IN (SELECT tbl.unique_key FROM tbl WHERE subq_where) or, tuple-based: (oe1, .. oeN) IN (SELECT uniq_key_part1, ... uniq_key_partK FROM tbl WHERE subqwhere) i.e. the subquery is a single table SELECT without GROUP BY, aggregate functions, etc. */ class subselect_uniquesubquery_engine: public subselect_engine { protected: st_join_table *tab; Item *cond; /* The WHERE condition of subselect */ /* TRUE<=> last execution produced empty set. Valid only when left expression is NULL. */ bool empty_result_set; public: // constructor can assign THD because it will be called after JOIN::prepare subselect_uniquesubquery_engine(THD *thd_arg, st_join_table *tab_arg, Item_in_subselect *subs, Item *where) :subselect_engine(subs, 0), tab(tab_arg), cond(where) { thd= thd_arg; DBUG_ASSERT(subs); } ~subselect_uniquesubquery_engine(); void cleanup() override; int prepare(THD *) override; bool fix_length_and_dec(Item_cache** row) override; int exec() override; uint cols() const override { return 1; } uint8 uncacheable() override { return UNCACHEABLE_DEPENDENT_INJECTED; } void exclude() override; table_map upper_select_const_tables() override { return 0; } void print(String *str, enum_query_type query_type) override; bool change_result(Item_subselect *si, select_result_interceptor *result, bool temp= FALSE) override; bool no_tables() const override; int index_lookup(); /* TIMOUR: this method needs refactoring. */ int scan_table(); bool copy_ref_key(bool skip_constants); bool no_rows() override { return empty_result_set; } enum_engine_type engine_type() override { return UNIQUESUBQUERY_ENGINE; } }; class subselect_indexsubquery_engine: public subselect_uniquesubquery_engine { /* FALSE for 'ref', TRUE for 'ref-or-null'. */ bool check_null; /* The "having" clause. This clause (further referred to as "artificial having") was inserted by subquery transformation code. It contains Item(s) that have a side-effect: they record whether the subquery has produced a row with NULL certain components. We need to use it for cases like (oe1, oe2) IN (SELECT t.key, t.no_key FROM t1) where we do index lookup on t.key=oe1 but need also to check if there was a row such that t.no_key IS NULL. NOTE: This is currently here and not in the uniquesubquery_engine. Ideally it should have been in uniquesubquery_engine in order to allow execution of subqueries like (oe1, oe2) IN (SELECT primary_key, non_key_maybe_null_field FROM tbl) We could use uniquesubquery_engine for the first component and let Item_is_not_null_test( non_key_maybe_null_field) to handle the second. However, subqueries like the above are currently not handled by index lookup-based subquery engines, the engine applicability check misses them: it doesn't switch the engine for case of artificial having and [eq_]ref access (only for artificial having + ref_or_null or no having). The above example subquery is handled as a full-blown SELECT with eq_ref access to one table. Due to this limitation, the "artificial having" currently needs to be checked by only in indexsubquery_engine. */ Item *having; public: // constructor can assign THD because it will be called after JOIN::prepare subselect_indexsubquery_engine(THD *thd_arg, st_join_table *tab_arg, Item_in_subselect *subs, Item *where, Item *having_arg, bool chk_null) :subselect_uniquesubquery_engine(thd_arg, tab_arg, subs, where), check_null(chk_null), having(having_arg) { DBUG_ASSERT(subs); } int exec() override; void print (String *str, enum_query_type query_type) override; enum_engine_type engine_type() override { return INDEXSUBQUERY_ENGINE; } }; /* This function is actually defined in sql_parse.cc, but it depends on chooser_compare_func_creator defined in this file. */ Item * all_any_subquery_creator(THD *thd, Item *left_expr, chooser_compare_func_creator cmp, bool all, SELECT_LEX *select_lex); inline bool Item_subselect::is_evaluated() const { return engine->is_executed(); } inline bool Item_subselect::is_uncacheable() const { return engine->uncacheable(); } /** Compute an IN predicate via a hash semi-join. This class is responsible for the materialization of the subquery, and the selection of the correct and optimal execution method (e.g. direct index lookup, or partial matching) for the IN predicate. */ class subselect_hash_sj_engine : public subselect_engine { public: /* The table into which the subquery is materialized. */ TABLE *tmp_table; /* TRUE if the subquery was materialized into a temp table. */ bool is_materialized; /* The old engine already chosen at parse time and stored in permanent memory. Through this member we can re-create and re-prepare materialize_join for each execution of a prepared statement. We also reuse the functionality of subselect_single_select_engine::[prepare | cols]. */ subselect_single_select_engine *materialize_engine; /* QEP to execute the subquery and materialize its result into a temporary table. Created during the first call to exec(). */ JOIN *materialize_join; /* A conjunction of all the equality conditions between all pairs of expressions that are arguments of an IN predicate. We need these to post-filter some IN results because index lookups sometimes match values that are actually not equal to the search key in SQL terms. */ Item_cond_and *semi_join_conds; Name_resolution_context *semi_join_conds_context; subselect_hash_sj_engine(THD *thd_arg, Item_in_subselect *in_predicate, subselect_single_select_engine *old_engine) : subselect_engine(in_predicate, NULL), tmp_table(NULL), is_materialized(FALSE), materialize_engine(old_engine), materialize_join(NULL), semi_join_conds(NULL), lookup_engine(NULL), count_partial_match_columns(0), count_null_only_columns(0), count_columns_with_nulls(0), strategy(UNDEFINED) { DBUG_ASSERT(in_predicate); } ~subselect_hash_sj_engine(); bool init(List *tmp_columns, uint subquery_id); void cleanup() override; int prepare(THD *) override; int exec() override; void print(String *str, enum_query_type query_type) override; uint cols() const override { return materialize_engine->cols(); } uint8 uncacheable() override { return materialize_engine->uncacheable(); } table_map upper_select_const_tables() override { return 0; } bool no_rows() override { return !tmp_table->file->stats.records; } enum_engine_type engine_type() override { return HASH_SJ_ENGINE; } /* TODO: factor out all these methods in a base subselect_index_engine class because all of them have dummy implementations and should never be called. */ bool fix_length_and_dec(Item_cache** row) override;//=>base class void exclude() override; //=>base class //=>base class bool change_result(Item_subselect *si, select_result_interceptor *result, bool temp= FALSE) override; bool no_tables() const override;//=>base class /* Possible execution strategies that can be used to compute hash semi-join.*/ enum exec_strategy { UNDEFINED= 0, COMPLETE_MATCH, /* Use regular index lookups. */ PARTIAL_MATCH, /* Use some partial matching strategy. */ PARTIAL_MATCH_MERGE, /* Use partial matching through index merging. */ PARTIAL_MATCH_SCAN, /* Use partial matching through table scan. */ SINGLE_COLUMN_MATCH, /* Use simplified matching when there is only one field involved. */ CONST_RETURN_NULL, /* The result of IN predicate is constant NULL */ IMPOSSIBLE /* Subquery materialization is not applicable. */ }; protected: /* The engine used to compute the IN predicate. */ subselect_engine *lookup_engine; /* Keyparts of the only non-NULL composite index in a rowid merge. */ MY_BITMAP non_null_key_parts; /* Keyparts of the single column indexes with NULL, one keypart per index. */ MY_BITMAP partial_match_key_parts; uint count_partial_match_columns; uint count_null_only_columns; uint count_columns_with_nulls; /* The chosen execution strategy. Computed after materialization. */ exec_strategy strategy; exec_strategy get_strategy_using_schema(); exec_strategy get_strategy_using_data(); ulonglong rowid_merge_buff_size(bool has_non_null_key, bool has_covering_null_row, MY_BITMAP *partial_match_key_parts); void choose_partial_match_strategy(uint field_count, bool has_non_null_key, bool has_covering_null_row, MY_BITMAP *partial_match_key_parts); bool make_semi_join_conds(); subselect_uniquesubquery_engine* make_unique_engine(); }; /* Distinguish the type of (0-based) row numbers from the type of the index into an array of row numbers. */ typedef ha_rows rownum_t; /* An Ordered_key is an in-memory table index that allows O(log(N)) time lookups of a multi-part key. If the index is over a single column, then this column may contain NULLs, and the NULLs are stored and tested separately for NULL in O(1) via is_null(). Multi-part indexes assume that the indexed columns do not contain NULLs. TODO: = Due to the unnatural assymetry between single and multi-part indexes, it makes sense to somehow refactor or extend the class. = This class can be refactored into a base abstract interface, and two subclasses: - one to represent single-column indexes, and - another to represent multi-column indexes. Such separation would allow slightly more efficient implementation of the single-column indexes. = The current design requires such indexes to be fully recreated for each PS (re)execution, however most of the comprising objects can be reused. */ class Ordered_key : public Sql_alloc { protected: /* Index of the key in an array of keys. This index allows to construct (sub)sets of keys represented by bitmaps. */ uint keyid; /* The table being indexed. */ TABLE *tbl; /* The columns being indexed. */ Item_field **key_columns; /* Number of elements in 'key_columns' (number of key parts). */ uint key_column_count; /* An expression, or sequence of expressions that forms the search key. The search key is a sequence when it is Item_row. Each element of the sequence is accessible via Item::element_index(int i). */ Item *search_key; /* Value index related members. */ /* The actual value index, consists of a sorted sequence of row numbers. */ rownum_t *key_buff; /* Number of elements in key_buff. */ ha_rows key_buff_elements; /* Current element in 'key_buff'. */ ha_rows cur_key_idx; /* Mapping from row numbers to row ids. The element row_num_to_rowid[i] contains a buffer with the rowid for the row numbered 'i'. The memory for this member is not maintanined by this class because all Ordered_key indexes of the same table share the same mapping. */ uchar *row_num_to_rowid; /* A sequence of predicates to compare the search key with the corresponding columns of a table row from the index. */ Item_func_lt **compare_pred; /* Null index related members. */ MY_BITMAP null_key; /* Count of NULLs per column. */ ha_rows null_count; /* The row number that contains the first NULL in a column. */ rownum_t min_null_row; /* The row number that contains the last NULL in a column. */ rownum_t max_null_row; protected: bool alloc_keys_buffers(); /* Quick sort comparison function that compares two rows of the same table indentfied with their row numbers. */ int cmp_keys_by_row_data(const rownum_t a, const rownum_t b) const; static int cmp_keys_by_row_data_and_rownum(void *key, const void *a, const void *b); int cmp_key_with_search_key(rownum_t row_num); public: Ordered_key(uint keyid_arg, TABLE *tbl_arg, Item *search_key_arg, ha_rows null_count_arg, ha_rows min_null_row_arg, ha_rows max_null_row_arg, uchar *row_num_to_rowid_arg); ~Ordered_key(); void cleanup(); /* Initialize a multi-column index. */ bool init(MY_BITMAP *columns_to_index); /* Initialize a single-column index. */ bool init(int col_idx); uint get_column_count() const { return key_column_count; } uint get_keyid() const { return keyid; } Field *get_field(uint i) const { DBUG_ASSERT(i < key_column_count); return key_columns[i]->field; } rownum_t get_min_null_row() const { return min_null_row; } rownum_t get_max_null_row() const { return max_null_row; } MY_BITMAP * get_null_key() { return &null_key; } ha_rows get_null_count() const { return null_count; } ha_rows get_key_buff_elements() const { return key_buff_elements; } /* Get the search key element that corresponds to the i-th key part of this index. */ Item *get_search_key(uint i) const { return search_key->element_index(key_columns[i]->field->field_index); } void add_key(rownum_t row_num) { /* The caller must know how many elements to add. */ DBUG_ASSERT(key_buff_elements && cur_key_idx < key_buff_elements); key_buff[cur_key_idx]= row_num; ++cur_key_idx; } bool sort_keys(); inline double null_selectivity() const; /* Position the current element at the first row that matches the key. The key itself is propagated by evaluating the current value(s) of this->search_key. */ bool lookup(); /* Move the current index cursor to the first key. */ void first() { DBUG_ASSERT(key_buff_elements); cur_key_idx= 0; } /* TODO */ bool next_same(); /* Move the current index cursor to the next key. */ bool next() { DBUG_ASSERT(key_buff_elements); if (cur_key_idx < key_buff_elements - 1) { ++cur_key_idx; return TRUE; } return FALSE; }; /* Return the current index element. */ rownum_t current() const { DBUG_ASSERT(key_buff_elements && cur_key_idx < key_buff_elements); return key_buff[cur_key_idx]; } void set_null(rownum_t row_num) { bitmap_set_bit(&null_key, (uint)row_num); } bool is_null(rownum_t row_num) const { /* Indexes consisting of only NULLs do not have a bitmap buffer at all. Their only initialized member is 'n_bits', which is equal to the number of temp table rows. */ if (null_count == tbl->file->stats.records) { DBUG_ASSERT(tbl->file->stats.records == null_key.n_bits); return TRUE; } if (row_num > max_null_row || row_num < min_null_row) return FALSE; return bitmap_is_set(&null_key, (uint)row_num); } void print(String *str) const; }; class subselect_partial_match_engine : public subselect_engine { protected: /* The temporary table that contains a materialized subquery. */ TABLE *tmp_table; /* The engine used to check whether an IN predicate is TRUE or not. If not TRUE, then subselect_rowid_merge_engine further distinguishes between FALSE and UNKNOWN. */ subselect_uniquesubquery_engine *lookup_engine; /* A list of equalities between each pair of IN operands. */ List *equi_join_conds; /* True if there is an all NULL row in tmp_table. If so, then if there is no complete match, there is a guaranteed partial match. */ bool has_covering_null_row; /* True if all nullable columns of tmp_table consist of only NULL values. If so, then if there is a match in the non-null columns, there is a guaranteed partial match. */ bool has_covering_null_columns; uint count_columns_with_nulls; protected: virtual bool partial_match()= 0; public: subselect_partial_match_engine(THD *thd, subselect_uniquesubquery_engine *engine_arg, TABLE *tmp_table_arg, Item_subselect *item_arg, select_result_interceptor *result_arg, List *equi_join_conds_arg, bool has_covering_null_row_arg, bool has_covering_null_columns_arg, uint count_columns_with_nulls_arg); int prepare(THD *thd_arg) override { set_thd(thd_arg); return 0; } int exec() override; bool fix_length_and_dec(Item_cache**) override { return FALSE; } uint cols() const override { /* TODO: what is the correct value? */ return 1; } uint8 uncacheable() override { return UNCACHEABLE_DEPENDENT; } void exclude() override {} table_map upper_select_const_tables() override { return 0; } bool change_result(Item_subselect*, select_result_interceptor*, bool temp= FALSE) override { DBUG_ASSERT(FALSE); return false; } bool no_tables() const override { return false; } bool no_rows() override { /* TODO: It is completely unclear what is the semantics of this method. The current result is computed so that the call to no_rows() from Item_in_optimizer::val_int() sets Item_in_optimizer::null_value correctly. */ return !(item->get_IN_subquery()->null_value); } void print(String*, enum_query_type) override; friend void subselect_hash_sj_engine::cleanup(); }; class subselect_rowid_merge_engine: public subselect_partial_match_engine { protected: /* Mapping from row numbers to row ids. The rowids are stored sequentially in the array - rowid[i] is located in row_num_to_rowid + i * rowid_length. */ uchar *row_num_to_rowid; /* A subset of all the keys for which there is a match for the same row. Used during execution. Computed for each outer reference */ MY_BITMAP matching_keys; /* The columns of the outer reference that are NULL. Computed for each outer reference. */ MY_BITMAP matching_outer_cols; /* Indexes of row numbers, sorted by . If an index may contain NULLs, the NULLs are stored efficiently in a bitmap. The indexes are sorted by the selectivity of their NULL sub-indexes, the one with the fewer NULLs is first. Thus, if there is any index on non-NULL columns, it is contained in keys[0]. */ Ordered_key **merge_keys; /* The number of elements in merge_keys. */ uint merge_keys_count; /* The NULL bitmaps of merge keys.*/ MY_BITMAP **null_bitmaps; /* An index on all non-NULL columns of 'tmp_table'. The index has the logical form: <[v_i1 | ... | v_ik], rownum>. It allows to find the row number where the columns c_i1,...,c1_k contain the values v_i1,...,v_ik. If such an index exists, it is always the first element of 'merge_keys'. */ Ordered_key *non_null_key; /* Priority queue of Ordered_key indexes, one per NULLable column. This queue is used by the partial match algorithm in method exec(). */ QUEUE pq; protected: /* Comparison function to compare keys in order of decreasing bitmap selectivity. */ static int cmp_keys_by_null_selectivity(const void *k1, const void *k2); /* Comparison function used by the priority queue pq, the 'smaller' key is the one with the smaller current row number. */ static int cmp_keys_by_cur_rownum(void *, const void *k1, const void *k2); bool test_null_row(rownum_t row_num); bool exists_complementing_null_row(MY_BITMAP *keys_to_complement); bool partial_match() override; public: subselect_rowid_merge_engine(THD *thd, subselect_uniquesubquery_engine *engine_arg, TABLE *tmp_table_arg, uint merge_keys_count_arg, bool has_covering_null_row_arg, bool has_covering_null_columns_arg, uint count_columns_with_nulls_arg, Item_subselect *item_arg, select_result_interceptor *result_arg, List *equi_join_conds_arg) :subselect_partial_match_engine(thd, engine_arg, tmp_table_arg, item_arg, result_arg, equi_join_conds_arg, has_covering_null_row_arg, has_covering_null_columns_arg, count_columns_with_nulls_arg), merge_keys_count(merge_keys_count_arg), non_null_key(NULL) {} ~subselect_rowid_merge_engine(); bool init(MY_BITMAP *non_null_key_parts, MY_BITMAP *partial_match_key_parts); void cleanup() override; enum_engine_type engine_type() override { return ROWID_MERGE_ENGINE; } }; class subselect_table_scan_engine: public subselect_partial_match_engine { protected: bool partial_match() override; public: subselect_table_scan_engine(THD *thd, subselect_uniquesubquery_engine *engine_arg, TABLE *tmp_table_arg, Item_subselect *item_arg, select_result_interceptor *result_arg, List *equi_join_conds_arg, bool has_covering_null_row_arg, bool has_covering_null_columns_arg, uint count_columns_with_nulls_arg); void cleanup() override; enum_engine_type engine_type() override { return TABLE_SCAN_ENGINE; } }; /* An engine to handle NULL-aware Materialization for subqueries that compare one column: col1 IN (SELECT t2.col2 FROM t2 ...) When only one column is used, we need to handle NULL values of col1 and col2 but don't need to perform "partial" matches when only a subset of compared columns is NULL. This allows to save on some data structures. */ class subselect_single_column_match_engine: public subselect_partial_match_engine { protected: bool partial_match() override; public: subselect_single_column_match_engine(THD *thd, subselect_uniquesubquery_engine *engine_arg, TABLE *tmp_table_arg, Item_subselect *item_arg, select_result_interceptor *result_arg, List *equi_join_conds_arg, bool has_covering_null_row_arg, bool has_covering_null_columns_arg, uint count_columns_with_nulls_arg); void cleanup() override {} enum_engine_type engine_type() override { return SINGLE_COLUMN_ENGINE; } }; /** @brief Subquery materialization tracker @details Used to track various parameters of the materialized subquery execution, such as the execution strategy, sizes of buffers employed, etc */ class Subq_materialization_tracker { public: using Strategy = subselect_hash_sj_engine::exec_strategy; Subq_materialization_tracker(MEM_ROOT *mem_root) : exec_strategy(Strategy::UNDEFINED), partial_match_buffer_size(0), partial_match_array_sizes(mem_root), loops_count(0), index_lookups_count(0), partial_matches_count(0) {} void report_partial_merge_keys(Ordered_key **merge_keys, uint merge_keys_count); void report_exec_strategy(Strategy es) { exec_strategy= es; } void report_partial_match_buffer_size(longlong sz) { partial_match_buffer_size= sz; } void increment_loops_count() { loops_count++; } void increment_index_lookups() { index_lookups_count++; } void increment_partial_matches() { partial_matches_count++; } void print_json_members(Json_writer *writer) const; private: Strategy exec_strategy; ulonglong partial_match_buffer_size; Dynamic_array partial_match_array_sizes; /* Number of times subquery predicate was evaluated */ ulonglong loops_count; /* Number of times we made a lookup in the materialized temptable (we do this when all parts of left_expr are not NULLs) */ ulonglong index_lookups_count; /* Number of times we had to check for a partial match (either by scanning the materialized subquery or by doing a merge) */ ulonglong partial_matches_count; const char *get_exec_strategy() const { switch (exec_strategy) { case Strategy::UNDEFINED: return "undefined"; case Strategy::COMPLETE_MATCH: return "index_lookup"; case Strategy::PARTIAL_MATCH_MERGE: return "index_lookup;array merge for partial match"; case Strategy::PARTIAL_MATCH_SCAN: return "index_lookup;full scan for partial match"; case Strategy::SINGLE_COLUMN_MATCH: return "null-aware index_lookup"; case Strategy::CONST_RETURN_NULL: return "return NULL"; default: return "unsupported"; } } }; #endif /* ITEM_SUBSELECT_INCLUDED */ mysql/server/private/sql_cursor.h000064400000004414151027430560013244 0ustar00/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _sql_cursor_h_ #define _sql_cursor_h_ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class interface */ #endif #include "sql_class.h" /* Query_arena */ class JOIN; /** @file Declarations for implementation of server side cursors. Only read-only non-scrollable cursors are currently implemented. */ /** Server_side_cursor -- an interface for materialized implementation of cursors. All cursors are self-contained (created in their own memory root). For that reason they must be deleted only using a pointer to Server_side_cursor, not to its base class. */ class Server_side_cursor: protected Query_arena { protected: /** Row destination used for fetch */ select_result *result; public: Server_side_cursor(MEM_ROOT *mem_root_arg, select_result *result_arg) :Query_arena(mem_root_arg, STMT_INITIALIZED), result(result_arg) {} virtual bool is_open() const= 0; virtual int open(JOIN *top_level_join)= 0; virtual void fetch(ulong num_rows)= 0; virtual void close()= 0; virtual bool export_structure(THD *thd, Row_definition_list *defs) { DBUG_ASSERT(0); return true; } virtual ~Server_side_cursor(); static void *operator new(size_t size, MEM_ROOT *mem_root) { return alloc_root(mem_root, size); } static void operator delete(void *ptr, size_t size); static void operator delete(void *, MEM_ROOT *){} }; int mysql_open_cursor(THD *thd, select_result *result, Server_side_cursor **res); #endif /* _sql_cusor_h_ */ mysql/server/private/opt_trace.h000064400000020456151027430560013034 0ustar00#ifndef OPT_TRACE_INCLUDED #define OPT_TRACE_INCLUDED /* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "opt_trace_context.h" // Opt_trace_context #include "sql_lex.h" #include "my_json_writer.h" #include "sql_select.h" class Item; class THD; struct TABLE_LIST; /* User-visible information about a trace. */ struct Opt_trace_info { /** String containing trace. If trace has been end()ed, this is 0-terminated, which is only to aid debugging or unit testing; this property is not relied upon in normal server usage. If trace has not been ended, this is not 0-terminated. That rare case can happen when a substatement reads OPTIMIZER_TRACE (at that stage, the top statement is still executing so its trace is not ended yet, but may still be read by the sub-statement). */ const char *trace_ptr; size_t trace_length; //// String containing original query. const char *query_ptr; size_t query_length; const CHARSET_INFO *query_charset; ///< charset of query string /** How many bytes this trace is missing (for traces which were truncated because of @@@@optimizer-trace-max-mem-size). The trace is not extended beyond trace-max-mem-size. */ size_t missing_bytes; /* Whether user lacks privilege to see this trace. If this is set to TRUE, then we return an empty trace */ bool missing_priv; }; /** Instantiate this class to start tracing a THD's actions (generally at a statement's start), and to set the "original" query (not transformed, as sent by client) for the new trace. Destructor will end the trace. @param thd the THD @param tbl list of tables read/written by the statement. @param sql_command SQL command being prepared or executed @param set_vars what variables are set by this command (only used if sql_command is SQLCOM_SET_OPTION) @param query query @param length query's length @param charset charset which was used to encode this query */ class Opt_trace_start { public: Opt_trace_start(THD *thd_arg): ctx(&thd_arg->opt_trace), traceable(false) {} void init(THD *thd, TABLE_LIST *tbl, enum enum_sql_command sql_command, List *set_vars, const char *query, size_t query_length, const CHARSET_INFO *query_charset); ~Opt_trace_start(); private: Opt_trace_context *const ctx; /* True: the query will be traced False: otherwise */ bool traceable; }; /** Prints SELECT query to optimizer trace. It is not the original query (as in @c Opt_trace_context::set_query()) but a printout of the parse tree (Item-s). @param thd the THD @param select_lex query's parse tree @param trace_object Json_writer object to which the query will be added */ void opt_trace_print_expanded_query(THD *thd, SELECT_LEX *select_lex, Json_writer_object *trace_object); void add_table_scan_values_to_trace(THD *thd, JOIN_TAB *tab); void trace_plan_prefix(JOIN *join, uint idx, table_map join_tables); void print_final_join_order(JOIN *join); void print_best_access_for_table(THD *thd, POSITION *pos, enum join_type type); void trace_condition(THD * thd, const char *name, const char *transform_type, Item *item, const char *table_name= nullptr); /* Security related (need to add a proper comment here) */ /** If the security context is not that of the connected user, inform the trace system that a privilege is missing. With one exception: see below. @param thd This serves to eliminate the following issue. Any information readable by a SELECT may theoretically end up in the trace. And a SELECT may read information from other places than tables: - from views (reading their bodies) - from stored routines (reading their bodies) - from files (reading their content), with LOAD_FILE() - from the list of connections (reading their queries...), with I_S.PROCESSLIST. If the connected user has EXECUTE privilege on a routine which does a security context change, the routine can retrieve information internally (if allowed by the SUID context's privileges), and present only a portion of it to the connected user. But with tracing on, all information is possibly in the trace. So the connected user receives more information than the routine's definer intended to provide. Fixing this issue would require adding, near many privilege checks in the server, a new optimizer-trace-specific check done against the connected user's context, to verify that the connected user has the right to see the retrieved information. Instead, our chosen simpler solution is that if we see a security context change where SUID user is not the connected user, we disable tracing. With only one safe exception: if the connected user has all global privileges (because then she/he can find any information anyway). By "all global privileges" we mean everything but WITH GRANT OPTION (that latter one isn't related to information gathering). Read access to I_S.OPTIMIZER_TRACE by another user than the connected user is restricted: @see fill_optimizer_trace_info(). */ void opt_trace_disable_if_no_security_context_access(THD *thd); void opt_trace_disable_if_no_tables_access(THD *thd, TABLE_LIST *tbl); /** If tracing is on, checks additional privileges for a view, to make sure that the user has the right to do SHOW CREATE VIEW. For that: - this function checks SHOW VIEW - SELECT is tested in opt_trace_disable_if_no_tables_access() - SELECT + SHOW VIEW is sufficient for SHOW CREATE VIEW. We also check underlying tables. If a privilege is missing, notifies the trace system. This function should be called when the view's underlying tables have not yet been merged. @param thd THD context @param view view to check @param underlying_tables underlying tables/views of 'view' */ void opt_trace_disable_if_no_view_access(THD *thd, TABLE_LIST *view, TABLE_LIST *underlying_tables); /** If tracing is on, checks additional privileges on a stored routine, to make sure that the user has the right to do SHOW CREATE PROCEDURE/FUNCTION. For that, we use the same checks as in those SHOW commands. If a privilege is missing, notifies the trace system. This function is not redundant with opt_trace_disable_if_no_security_context_access(). Indeed, for a SQL SECURITY INVOKER routine, there is no context change, but we must still verify that the invoker can do SHOW CREATE. For triggers, see note in sp_head::execute_trigger(). @param thd @param sp routine to check */ void opt_trace_disable_if_no_stored_proc_func_access(THD *thd, sp_head *sp); /** Fills information_schema.OPTIMIZER_TRACE with rows (one per trace) @retval 0 ok @retval 1 error */ int fill_optimizer_trace_info(THD *thd, TABLE_LIST *tables, Item *); #define OPT_TRACE_TRANSFORM(thd, object_level0, object_level1, \ select_number, from, to) \ Json_writer_object object_level0(thd); \ Json_writer_object object_level1(thd, "transformation"); \ object_level1.add_select_number(select_number).add("from", from).add("to", to); #define OPT_TRACE_VIEWS_TRANSFORM(thd, object_level0, object_level1, \ derived, name, select_number, algorithm) \ Json_writer_object trace_wrapper(thd); \ Json_writer_object trace_derived(thd, derived); \ trace_derived.add("table", name).add_select_number(select_number) \ .add("algorithm", algorithm); #endif mysql/server/private/wsrep_mysqld.h000064400000051572151027430560013610 0ustar00/* Copyright 2008-2023 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef WSREP_MYSQLD_H #define WSREP_MYSQLD_H #include #ifdef WITH_WSREP #include #include "mysql/service_wsrep.h" #include #include #include "log.h" #include "mysqld.h" typedef struct st_mysql_show_var SHOW_VAR; #include #include "mdl.h" #include "sql_table.h" #include "wsrep_mysqld_c.h" #include "wsrep/provider.hpp" #include "wsrep/streaming_context.hpp" #include "wsrep_api.h" #include #define WSREP_UNDEFINED_TRX_ID ULONGLONG_MAX class THD; // Global wsrep parameters // MySQL wsrep options extern const char* wsrep_provider; extern const char* wsrep_provider_options; extern const char* wsrep_cluster_name; extern const char* wsrep_cluster_address; extern const char* wsrep_node_name; extern const char* wsrep_node_address; extern const char* wsrep_node_incoming_address; extern const char* wsrep_data_home_dir; extern const char* wsrep_dbug_option; extern long wsrep_slave_threads; extern int wsrep_slave_count_change; extern ulong wsrep_debug; extern my_bool wsrep_convert_LOCK_to_trx; extern ulong wsrep_retry_autocommit; extern my_bool wsrep_auto_increment_control; extern my_bool wsrep_drupal_282555_workaround; extern my_bool wsrep_incremental_data_collection; extern const char* wsrep_start_position; extern ulong wsrep_max_ws_size; extern ulong wsrep_max_ws_rows; extern const char* wsrep_notify_cmd; extern my_bool wsrep_certify_nonPK; extern long int wsrep_protocol_version; extern my_bool wsrep_desync; extern ulong wsrep_reject_queries; extern my_bool wsrep_recovery; extern my_bool wsrep_replicate_myisam; extern my_bool wsrep_log_conflicts; extern ulong wsrep_mysql_replication_bundle; extern my_bool wsrep_load_data_splitting; extern my_bool wsrep_restart_slave; extern my_bool wsrep_restart_slave_activated; extern my_bool wsrep_slave_FK_checks; extern my_bool wsrep_slave_UK_checks; extern ulong wsrep_trx_fragment_unit; extern ulong wsrep_SR_store_type; extern uint wsrep_ignore_apply_errors; extern ulong wsrep_running_threads; extern ulong wsrep_running_applier_threads; extern ulong wsrep_running_rollbacker_threads; extern bool wsrep_new_cluster; extern bool wsrep_gtid_mode; extern uint32 wsrep_gtid_domain_id; extern std::atomic wsrep_thread_create_failed; extern ulonglong wsrep_mode; extern my_bool wsrep_strict_ddl; enum enum_wsrep_reject_types { WSREP_REJECT_NONE, /* nothing rejected */ WSREP_REJECT_ALL, /* reject all queries, with UNKNOWN_COMMAND error */ WSREP_REJECT_ALL_KILL /* kill existing connections and reject all queries*/ }; enum enum_wsrep_OSU_method { WSREP_OSU_TOI, WSREP_OSU_RSU, WSREP_OSU_NONE, }; enum enum_wsrep_sync_wait { WSREP_SYNC_WAIT_NONE= 0x0, // select, begin WSREP_SYNC_WAIT_BEFORE_READ= 0x1, WSREP_SYNC_WAIT_BEFORE_UPDATE_DELETE= 0x2, WSREP_SYNC_WAIT_BEFORE_INSERT_REPLACE= 0x4, WSREP_SYNC_WAIT_BEFORE_SHOW= 0x8, WSREP_SYNC_WAIT_MAX= 0xF }; enum enum_wsrep_ignore_apply_error { WSREP_IGNORE_ERRORS_NONE= 0x0, WSREP_IGNORE_ERRORS_ON_RECONCILING_DDL= 0x1, WSREP_IGNORE_ERRORS_ON_RECONCILING_DML= 0x2, WSREP_IGNORE_ERRORS_ON_DDL= 0x4, WSREP_IGNORE_ERRORS_MAX= 0x7 }; /* wsrep_mode features */ enum enum_wsrep_mode { WSREP_MODE_STRICT_REPLICATION= (1ULL << 0), WSREP_MODE_BINLOG_ROW_FORMAT_ONLY= (1ULL << 1), WSREP_MODE_REQUIRED_PRIMARY_KEY= (1ULL << 2), WSREP_MODE_REPLICATE_MYISAM= (1ULL << 3), WSREP_MODE_REPLICATE_ARIA= (1ULL << 4), WSREP_MODE_DISALLOW_LOCAL_GTID= (1ULL << 5), WSREP_MODE_BF_MARIABACKUP= (1ULL << 6) }; // Streaming Replication #define WSREP_FRAG_BYTES 0 #define WSREP_FRAG_ROWS 1 #define WSREP_FRAG_STATEMENTS 2 #define WSREP_SR_STORE_NONE 0 #define WSREP_SR_STORE_TABLE 1 extern const char *wsrep_fragment_units[]; extern const char *wsrep_SR_store_types[]; // MySQL status variables extern my_bool wsrep_connected; extern const char* wsrep_cluster_state_uuid; extern long long wsrep_cluster_conf_id; extern const char* wsrep_cluster_status; extern long wsrep_cluster_size; extern long wsrep_local_index; extern long long wsrep_local_bf_aborts; extern const char* wsrep_provider_name; extern const char* wsrep_provider_version; extern const char* wsrep_provider_vendor; extern char* wsrep_provider_capabilities; extern char* wsrep_cluster_capabilities; int wsrep_show_status(THD *thd, SHOW_VAR *var, void *buff, system_status_var *status_var, enum_var_type scope); int wsrep_show_ready(THD *thd, SHOW_VAR *var, void *buff, system_status_var *, enum_var_type); void wsrep_free_status(THD *thd); void wsrep_update_cluster_state_uuid(const char* str); /* Filters out --wsrep-new-cluster oprtion from argv[] * should be called in the very beginning of main() */ void wsrep_filter_new_cluster (int* argc, char* argv[]); int wsrep_init(); void wsrep_deinit(bool free_options); /* Initialize wsrep thread LOCKs and CONDs */ void wsrep_thr_init(); /* Destroy wsrep thread LOCKs and CONDs */ void wsrep_thr_deinit(); void wsrep_recover(); bool wsrep_before_SE(); // initialize wsrep before storage // engines (true) or after (false) /* wsrep initialization sequence at startup * @param before wsrep_before_SE() value */ void wsrep_init_startup(bool before); /* Recover streaming transactions from fragment storage */ void wsrep_recover_sr_from_storage(THD *); // Other wsrep global variables extern my_bool wsrep_inited; // whether wsrep is initialized ? extern bool wsrep_service_started; extern "C" void wsrep_fire_rollbacker(THD *thd); extern "C" uint32 wsrep_thd_wsrep_rand(THD *thd); extern "C" time_t wsrep_thd_query_start(THD *thd); extern void wsrep_close_client_connections(my_bool wait_to_end, THD *except_caller_thd= NULL); extern "C" query_id_t wsrep_thd_wsrep_last_query_id(THD *thd); extern "C" void wsrep_thd_set_wsrep_last_query_id(THD *thd, query_id_t id); extern int wsrep_wait_committing_connections_close(int wait_time); extern void wsrep_close_applier(THD *thd); extern void wsrep_wait_appliers_close(THD *thd); extern void wsrep_close_applier_threads(int count); /* new defines */ extern void wsrep_stop_replication(THD *thd); extern bool wsrep_start_replication(const char *wsrep_cluster_address); extern void wsrep_shutdown_replication(); extern bool wsrep_check_mode (enum_wsrep_mode mask); extern bool wsrep_check_mode_after_open_table (THD *thd, const handlerton *hton, TABLE_LIST *tables); extern bool wsrep_check_mode_before_cmd_execute (THD *thd); extern bool wsrep_must_sync_wait (THD* thd, uint mask= WSREP_SYNC_WAIT_BEFORE_READ); extern bool wsrep_sync_wait (THD* thd, uint mask= WSREP_SYNC_WAIT_BEFORE_READ); extern bool wsrep_sync_wait (THD* thd, enum enum_sql_command command); extern enum wsrep::provider::status wsrep_sync_wait_upto (THD* thd, wsrep_gtid_t* upto, int timeout); extern int wsrep_check_opts(); extern void wsrep_prepend_PATH (const char* path); extern bool wsrep_append_fk_parent_table(THD* thd, TABLE_LIST* table, wsrep::key_array* keys); extern bool wsrep_reload_ssl(); /* Other global variables */ extern wsrep_seqno_t wsrep_locked_seqno; /* A wrapper function for MySQL log functions. The call will prefix the log message with WSREP and forward the result buffer to fun. */ void WSREP_LOG(void (*fun)(const char* fmt, ...), const char* fmt, ...); #define WSREP_SYNC_WAIT(thd_, before_) \ { if (WSREP_CLIENT(thd_) && \ wsrep_sync_wait(thd_, before_)) goto wsrep_error_label; } #define WSREP_MYSQL_DB (char *)"mysql" #define WSREP_TO_ISOLATION_BEGIN(db_, table_, table_list_) \ if (WSREP_ON && WSREP(thd) && wsrep_to_isolation_begin(thd, db_, table_, table_list_)) \ goto wsrep_error_label; #define WSREP_TO_ISOLATION_BEGIN_CREATE(db_, table_, table_list_, create_info_) \ if (WSREP_ON && WSREP(thd) && \ wsrep_to_isolation_begin(thd, db_, table_, \ table_list_, nullptr, nullptr, create_info_))\ goto wsrep_error_label; #define WSREP_TO_ISOLATION_BEGIN_ALTER(db_, table_, table_list_, alter_info_, fk_tables_, create_info_) \ if (WSREP(thd) && wsrep_thd_is_local(thd) && \ wsrep_to_isolation_begin(thd, db_, table_, \ table_list_, alter_info_, fk_tables_, create_info_)) #define WSREP_TO_ISOLATION_END \ if ((WSREP(thd) && wsrep_thd_is_local_toi(thd)) || \ wsrep_thd_is_in_rsu(thd)) \ wsrep_to_isolation_end(thd); /* Checks if lex->no_write_to_binlog is set for statements that use LOCAL or NO_WRITE_TO_BINLOG. */ #define WSREP_TO_ISOLATION_BEGIN_WRTCHK(db_, table_, table_list_) \ if (WSREP(thd) && !thd->lex->no_write_to_binlog \ && wsrep_to_isolation_begin(thd, db_, table_, table_list_)) \ goto wsrep_error_label; #define WSREP_PROVIDER_EXISTS (WSREP_PROVIDER_EXISTS_) static inline bool wsrep_cluster_address_exists() { if (mysqld_server_started) mysql_mutex_assert_owner(&LOCK_global_system_variables); return wsrep_cluster_address && wsrep_cluster_address[0]; } extern my_bool wsrep_ready_get(); extern void wsrep_ready_wait(); extern mysql_mutex_t LOCK_wsrep_ready; extern mysql_cond_t COND_wsrep_ready; extern mysql_mutex_t LOCK_wsrep_sst; extern mysql_cond_t COND_wsrep_sst; extern mysql_mutex_t LOCK_wsrep_sst_init; extern mysql_cond_t COND_wsrep_sst_init; extern int wsrep_replaying; extern mysql_mutex_t LOCK_wsrep_replaying; extern mysql_cond_t COND_wsrep_replaying; extern mysql_mutex_t LOCK_wsrep_slave_threads; extern mysql_cond_t COND_wsrep_slave_threads; extern mysql_mutex_t LOCK_wsrep_gtid_wait_upto; extern mysql_mutex_t LOCK_wsrep_cluster_config; extern mysql_mutex_t LOCK_wsrep_desync; extern mysql_mutex_t LOCK_wsrep_SR_pool; extern mysql_mutex_t LOCK_wsrep_SR_store; extern mysql_mutex_t LOCK_wsrep_config_state; extern mysql_mutex_t LOCK_wsrep_group_commit; extern mysql_mutex_t LOCK_wsrep_joiner_monitor; extern mysql_mutex_t LOCK_wsrep_donor_monitor; extern mysql_cond_t COND_wsrep_joiner_monitor; extern mysql_cond_t COND_wsrep_donor_monitor; extern int wsrep_to_isolation; #ifdef GTID_SUPPORT extern rpl_sidno wsrep_sidno; #endif /* GTID_SUPPORT */ extern my_bool wsrep_preordered_opt; #ifdef HAVE_PSI_INTERFACE extern PSI_cond_key key_COND_wsrep_thd; extern PSI_mutex_key key_LOCK_wsrep_ready; extern PSI_mutex_key key_COND_wsrep_ready; extern PSI_mutex_key key_LOCK_wsrep_sst; extern PSI_cond_key key_COND_wsrep_sst; extern PSI_mutex_key key_LOCK_wsrep_sst_init; extern PSI_cond_key key_COND_wsrep_sst_init; extern PSI_mutex_key key_LOCK_wsrep_sst_thread; extern PSI_cond_key key_COND_wsrep_sst_thread; extern PSI_mutex_key key_LOCK_wsrep_replaying; extern PSI_cond_key key_COND_wsrep_replaying; extern PSI_mutex_key key_LOCK_wsrep_slave_threads; extern PSI_cond_key key_COND_wsrep_slave_threads; extern PSI_mutex_key key_LOCK_wsrep_gtid_wait_upto; extern PSI_cond_key key_COND_wsrep_gtid_wait_upto; extern PSI_mutex_key key_LOCK_wsrep_cluster_config; extern PSI_mutex_key key_LOCK_wsrep_desync; extern PSI_mutex_key key_LOCK_wsrep_SR_pool; extern PSI_mutex_key key_LOCK_wsrep_SR_store; extern PSI_mutex_key key_LOCK_wsrep_global_seqno; extern PSI_mutex_key key_LOCK_wsrep_thd_queue; extern PSI_cond_key key_COND_wsrep_thd_queue; extern PSI_mutex_key key_LOCK_wsrep_joiner_monitor; extern PSI_mutex_key key_LOCK_wsrep_donor_monitor; extern PSI_file_key key_file_wsrep_gra_log; extern PSI_thread_key key_wsrep_sst_joiner; extern PSI_thread_key key_wsrep_sst_donor; extern PSI_thread_key key_wsrep_rollbacker; extern PSI_thread_key key_wsrep_applier; extern PSI_thread_key key_wsrep_sst_joiner_monitor; extern PSI_thread_key key_wsrep_sst_donor_monitor; #endif /* HAVE_PSI_INTERFACE */ struct TABLE_LIST; class Alter_info; int wsrep_to_isolation_begin(THD *thd, const char *db_, const char *table_, const TABLE_LIST* table_list, const Alter_info* alter_info= nullptr, const wsrep::key_array *fk_tables= nullptr, const HA_CREATE_INFO* create_info= nullptr); bool wsrep_should_replicate_ddl(THD* thd, const handlerton *hton); bool wsrep_should_replicate_ddl_iterate(THD* thd, const TABLE_LIST* table_list); void wsrep_to_isolation_end(THD *thd); bool wsrep_append_SR_keys(THD *thd); int wsrep_to_buf_helper( THD* thd, const char *query, uint query_len, uchar** buf, size_t* buf_len); int wsrep_create_trigger_query(THD *thd, uchar** buf, size_t* buf_len); int wsrep_create_event_query(THD *thd, uchar** buf, size_t* buf_len); void wsrep_init_sidno(const wsrep_uuid_t&); bool wsrep_node_is_donor(); bool wsrep_node_is_synced(); void wsrep_init_SR(); void wsrep_verify_SE_checkpoint(const wsrep_uuid_t& uuid, wsrep_seqno_t seqno); int wsrep_replay_from_SR_store(THD*, const wsrep_trx_meta_t&); class Log_event; int wsrep_ignored_error_code(Log_event* ev, int error); int wsrep_must_ignore_error(THD* thd); struct wsrep_server_gtid_t { uint32 domain_id; uint32 server_id; uint64 seqno; }; class Wsrep_gtid_server { public: uint32 domain_id; uint32 server_id; Wsrep_gtid_server() : m_force_signal(false) , m_seqno(0) , m_committed_seqno(0) { } void gtid(const wsrep_server_gtid_t& gtid) { domain_id= gtid.domain_id; server_id= gtid.server_id; m_seqno= gtid.seqno; } wsrep_server_gtid_t gtid() { wsrep_server_gtid_t gtid; gtid.domain_id= domain_id; gtid.server_id= server_id; gtid.seqno= m_seqno; return gtid; } void seqno(const uint64 seqno) { m_seqno= seqno; } uint64 seqno() const { return m_seqno; } uint64 seqno_committed() const { return m_committed_seqno; } uint64 seqno_inc() { m_seqno++; return m_seqno; } const wsrep_server_gtid_t& undefined() { return m_undefined; } int wait_gtid_upto(const uint64_t seqno, uint timeout) { int wait_result= 0; struct timespec wait_time; int ret= 0; mysql_cond_t wait_cond; mysql_cond_init(key_COND_wsrep_gtid_wait_upto, &wait_cond, NULL); set_timespec(wait_time, timeout); mysql_mutex_lock(&LOCK_wsrep_gtid_wait_upto); std::multimap::iterator it; if (seqno > m_seqno) { try { it= m_wait_map.insert(std::make_pair(seqno, &wait_cond)); } catch (std::bad_alloc& e) { ret= ENOMEM; } while (!ret && (m_committed_seqno < seqno) && !m_force_signal) { wait_result= mysql_cond_timedwait(&wait_cond, &LOCK_wsrep_gtid_wait_upto, &wait_time); if (wait_result == ETIMEDOUT || wait_result == ETIME) { ret= wait_result; break; } } if (ret != ENOMEM) { m_wait_map.erase(it); } } mysql_mutex_unlock(&LOCK_wsrep_gtid_wait_upto); mysql_cond_destroy(&wait_cond); return ret; } void signal_waiters(uint64 seqno, bool signal_all) { mysql_mutex_lock(&LOCK_wsrep_gtid_wait_upto); if (!signal_all && (m_committed_seqno >= seqno)) { mysql_mutex_unlock(&LOCK_wsrep_gtid_wait_upto); return; } m_force_signal= true; std::multimap::iterator it_end; std::multimap::iterator it_begin; if (signal_all) { it_end= m_wait_map.end(); } else { it_end= m_wait_map.upper_bound(seqno); } if (m_committed_seqno < seqno) { m_committed_seqno= seqno; } for (it_begin = m_wait_map.begin(); it_begin != it_end; ++it_begin) { mysql_cond_signal(it_begin->second); } m_force_signal= false; mysql_mutex_unlock(&LOCK_wsrep_gtid_wait_upto); } private: const wsrep_server_gtid_t m_undefined= {0,0,0}; std::multimap m_wait_map; bool m_force_signal; Atomic_counter m_seqno; Atomic_counter m_committed_seqno; }; extern Wsrep_gtid_server wsrep_gtid_server; void wsrep_init_gtid(); bool wsrep_check_gtid_seqno(const uint32&, const uint32&, uint64&); bool wsrep_get_binlog_gtid_seqno(wsrep_server_gtid_t&); int wsrep_append_table_keys(THD* thd, TABLE_LIST* first_table, TABLE_LIST* table_list, Wsrep_service_key_type key_type); extern void wsrep_handle_mdl_conflict(MDL_context *requestor_ctx, const MDL_ticket *ticket, const MDL_key *key); enum wsrep_thread_type { WSREP_APPLIER_THREAD=1, WSREP_ROLLBACKER_THREAD=2 }; typedef void (*wsrep_thd_processor_fun)(THD*, void *); class Wsrep_thd_args { public: Wsrep_thd_args(wsrep_thd_processor_fun fun, wsrep_thread_type thread_type, pthread_t thread_id) : fun_ (fun), thread_type_ (thread_type), thread_id_ (thread_id) { } wsrep_thd_processor_fun fun() { return fun_; } pthread_t* thread_id() {return &thread_id_; } enum wsrep_thread_type thread_type() {return thread_type_;} private: Wsrep_thd_args(const Wsrep_thd_args&); Wsrep_thd_args& operator=(const Wsrep_thd_args&); wsrep_thd_processor_fun fun_; enum wsrep_thread_type thread_type_; pthread_t thread_id_; }; void* start_wsrep_THD(void*); void wsrep_close_threads(THD *thd); bool wsrep_is_show_query(enum enum_sql_command command); void wsrep_replay_transaction(THD *thd); bool wsrep_create_like_table(THD* thd, TABLE_LIST* table, TABLE_LIST* src_table, HA_CREATE_INFO *create_info); bool wsrep_node_is_donor(); bool wsrep_node_is_synced(); /** * Check if the wsrep provider (ie the Galera library) is capable of * doing streaming replication. * @return true if SR capable */ bool wsrep_provider_is_SR_capable(); /** * Initialize WSREP server instance. * * @return Zero on success, non-zero on error. */ int wsrep_init_server(); /** * Initialize WSREP globals. This should be done after server initialization * is complete and the server has joined to the cluster. * */ void wsrep_init_globals(); /** * Deinit and release WSREP resources. */ void wsrep_deinit_server(); /** * Convert streaming fragment unit (WSREP_FRAG_BYTES, WSREP_FRAG_ROWS...) * to corresponding wsrep-lib fragment_unit */ enum wsrep::streaming_context::fragment_unit wsrep_fragment_unit(ulong unit); wsrep::key wsrep_prepare_key_for_toi(const char* db, const char* table, enum wsrep::key::type type); void wsrep_wait_ready(THD *thd); void wsrep_ready_set(bool ready_value); /** * Returns true if the given list of tables contains at least one * non-temporary table. */ bool wsrep_table_list_has_non_temp_tables(THD *thd, TABLE_LIST *tables); /** * Append foreign key to wsrep. * * @param thd Thread object * @param fk Foreign Key Info * * @return true if error, otherwise false. */ bool wsrep_foreign_key_append(THD *thd, FOREIGN_KEY_INFO *fk); #else /* !WITH_WSREP */ /* These macros are needed to compile MariaDB without WSREP support * (e.g. embedded) */ #define WSREP_PROVIDER_EXISTS (0) #define wsrep_emulate_bin_log (0) #define wsrep_to_isolation (0) #define wsrep_before_SE() (0) #define wsrep_init_startup(X) #define wsrep_check_opts() (0) #define wsrep_thr_init() do {} while(0) #define wsrep_thr_deinit() do {} while(0) #define wsrep_init_globals() do {} while(0) #define wsrep_create_appliers(X) do {} while(0) #define wsrep_cluster_address_exists() (false) #define WSREP_MYSQL_DB (0) #define WSREP_TO_ISOLATION_BEGIN(db_, table_, table_list_) do { } while(0) #define WSREP_TO_ISOLATION_BEGIN_ALTER(db_, table_, table_list_, alter_info_, fk_tables_) #define WSREP_TO_ISOLATION_END #define WSREP_TO_ISOLATION_BEGIN_WRTCHK(db_, table_, table_list_) #define WSREP_SYNC_WAIT(thd_, before_) #endif /* WITH_WSREP */ #endif /* WSREP_MYSQLD_H */ mysql/server/private/sql_type.h000064400001101015151027430560012704 0ustar00#ifndef SQL_TYPE_H_INCLUDED #define SQL_TYPE_H_INCLUDED /* Copyright (c) 2015 MariaDB Foundation. Copyright (c) 2015, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "mysqld.h" #include "lex_string.h" #include "sql_array.h" #include "sql_const.h" #include "sql_time.h" #include "sql_type_string.h" #include "sql_type_real.h" #include "compat56.h" #include "log_event_data_type.h" C_MODE_START #include C_MODE_END class Field; class Column_definition; class Column_definition_attributes; class Key_part_spec; class Item; class Item_const; class Item_literal; class Item_param; class Item_cache; class Item_copy; class Item_func_or_sum; class Item_sum; class Item_sum_hybrid; class Item_sum_sum; class Item_sum_avg; class Item_sum_variance; class Item_func_hex; class Item_hybrid_func; class Item_func_min_max; class Item_func_hybrid_field_type; class Item_bool_func2; class Item_bool_rowready_func2; class Item_func_between; class Item_func_in; class Item_func_round; class Item_func_int_val; class Item_func_abs; class Item_func_neg; class Item_func_signed; class Item_func_unsigned; class Item_double_typecast; class Item_float_typecast; class Item_decimal_typecast; class Item_char_typecast; class Item_time_typecast; class Item_date_typecast; class Item_datetime_typecast; class Item_func_plus; class Item_func_minus; class Item_func_mul; class Item_func_div; class Item_func_mod; class Item_type_holder; class cmp_item; class in_vector; class Type_handler_data; class Type_handler_hybrid_field_type; class Sort_param; class Arg_comparator; class Spvar_definition; class st_value; class Protocol; class handler; struct TABLE; struct SORT_FIELD_ATTR; struct SORT_FIELD; class Vers_history_point; class Virtual_column_info; class Conv_source; class ST_FIELD_INFO; class Type_collection; class Create_func; #define my_charset_numeric my_charset_latin1 enum protocol_send_type_t { PROTOCOL_SEND_STRING, PROTOCOL_SEND_FLOAT, PROTOCOL_SEND_DOUBLE, PROTOCOL_SEND_TINY, PROTOCOL_SEND_SHORT, PROTOCOL_SEND_LONG, PROTOCOL_SEND_LONGLONG, PROTOCOL_SEND_DATETIME, PROTOCOL_SEND_DATE, PROTOCOL_SEND_TIME }; enum scalar_comparison_op { SCALAR_CMP_EQ, SCALAR_CMP_EQUAL, SCALAR_CMP_LT, SCALAR_CMP_LE, SCALAR_CMP_GE, SCALAR_CMP_GT }; /* This enum is intentionally defined as "class" to disallow its implicit cast as "bool". This is needed to avoid pre-MDEV-32203 constructs like: if (field->can_optimize_range(...)) do_optimization(); to merge automatically as such - that would change the meaning to the opposite. The pre-MDEV-32203 code must to be changed to: if (field->can_optimize_range(...) == Data_type_compatibility::OK) do_optimization(); */ enum class Data_type_compatibility { OK, INCOMPATIBLE_DATA_TYPE, INCOMPATIBLE_COLLATION }; static inline const LEX_CSTRING scalar_comparison_op_to_lex_cstring(scalar_comparison_op op) { switch (op) { case SCALAR_CMP_EQ: return LEX_CSTRING{STRING_WITH_LEN("=")}; case SCALAR_CMP_EQUAL: return LEX_CSTRING{STRING_WITH_LEN("<=>")}; case SCALAR_CMP_LT: return LEX_CSTRING{STRING_WITH_LEN("<")}; case SCALAR_CMP_LE: return LEX_CSTRING{STRING_WITH_LEN("<=")}; case SCALAR_CMP_GE: return LEX_CSTRING{STRING_WITH_LEN(">=")}; case SCALAR_CMP_GT: return LEX_CSTRING{STRING_WITH_LEN(">")}; } DBUG_ASSERT(0); return LEX_CSTRING{STRING_WITH_LEN("")}; } class Hasher { ulong m_nr1; ulong m_nr2; public: Hasher(): m_nr1(1), m_nr2(4) { } void add_null() { m_nr1^= (m_nr1 << 1) | 1; } void add(CHARSET_INFO *cs, const uchar *str, size_t length) { cs->coll->hash_sort(cs, str, length, &m_nr1, &m_nr2); } void add(CHARSET_INFO *cs, const char *str, size_t length) { add(cs, (const uchar *) str, length); } uint32 finalize() const { return (uint32) m_nr1; } }; enum partition_value_print_mode_t { PARTITION_VALUE_PRINT_MODE_SHOW= 0, PARTITION_VALUE_PRINT_MODE_FRM= 1 }; enum column_definition_type_t { COLUMN_DEFINITION_TABLE_FIELD, COLUMN_DEFINITION_ROUTINE_PARAM, COLUMN_DEFINITION_ROUTINE_LOCAL, COLUMN_DEFINITION_FUNCTION_RETURN }; class Send_field_extended_metadata { LEX_CSTRING m_attr[MARIADB_FIELD_ATTR_LAST+1]; public: Send_field_extended_metadata() { bzero(this, sizeof(*this)); } bool set_data_type_name(const LEX_CSTRING &str) { m_attr[MARIADB_FIELD_ATTR_DATA_TYPE_NAME]= str; return false; } bool set_format_name(const LEX_CSTRING &str) { m_attr[MARIADB_FIELD_ATTR_FORMAT_NAME]= str; return false; } bool has_extended_metadata() const { for (uint i= 0; i <= MARIADB_FIELD_ATTR_LAST; i++) { if (m_attr[i].str) return true; } return false; } const LEX_CSTRING &attr(uint i) const { DBUG_ASSERT(i <= MARIADB_FIELD_ATTR_LAST); return m_attr[i]; } }; class Data_type_statistics { public: uint m_uneven_bit_length; uint m_fixed_string_total_length; uint m_fixed_string_count; uint m_variable_string_total_length; uint m_variable_string_count; uint m_blob_count; Data_type_statistics() :m_uneven_bit_length(0), m_fixed_string_total_length(0), m_fixed_string_count(0), m_variable_string_total_length(0), m_variable_string_count(0), m_blob_count(0) { } uint string_count() const { return m_fixed_string_count + m_variable_string_count; } uint string_total_length() const { return m_fixed_string_total_length + m_variable_string_total_length; } }; class Typelib: public TYPELIB { public: Typelib(uint count, const char **type_names, unsigned int *type_lengths) { TYPELIB::count= count; TYPELIB::name= ""; TYPELIB::type_names= type_names; TYPELIB::type_lengths= type_lengths; } uint max_octet_length() const { uint max_length= 0; for (uint i= 0; i < TYPELIB::count; i++) { const uint length= TYPELIB::type_lengths[i]; set_if_bigger(max_length, length); } return max_length; } }; template class TypelibBuffer: public Typelib { const char *m_type_names[sz + 1]; uint m_type_lengths[sz + 1]; public: TypelibBuffer(uint count, const LEX_CSTRING *values) :Typelib(count, m_type_names, m_type_lengths) { DBUG_ASSERT(sz >= count); for (uint i= 0; i < count; i++) { DBUG_ASSERT(values[i].str != NULL); m_type_names[i]= values[i].str; m_type_lengths[i]= (uint) values[i].length; } m_type_names[sz]= NullS; // End marker m_type_lengths[sz]= 0; // End marker } TypelibBuffer(const LEX_CSTRING *values) :TypelibBuffer(sz, values) { } }; /* A helper class to store column attributes that are inherited by columns (from the table level) when not specified explicitly. */ class Column_derived_attributes { /* Table level CHARACTER SET and COLLATE value: CREATE TABLE t1 (a VARCHAR(1), b CHAR(2)) CHARACTER SET latin1; All character string columns (CHAR, VARCHAR, TEXT) inherit CHARACTER SET from the table level. */ CHARSET_INFO *m_charset; public: explicit Column_derived_attributes(CHARSET_INFO *cs) :m_charset(cs) { } CHARSET_INFO *charset() const { return m_charset; } }; /* A helper class to store requests for changes in multiple column data types during ALTER. */ class Column_bulk_alter_attributes { /* Target CHARACTER SET specification in ALTER .. CONVERT, e.g. ALTER TABLE t1 CONVERT TO CHARACTER SET utf8; All character string columns (CHAR, VARCHAR, TEXT) get converted to the "CONVERT TO CHARACTER SET". */ CHARSET_INFO *m_alter_table_convert_to_charset; public: explicit Column_bulk_alter_attributes(CHARSET_INFO *convert) :m_alter_table_convert_to_charset(convert) { } CHARSET_INFO *alter_table_convert_to_charset() const { return m_alter_table_convert_to_charset; } }; class Native: public Binary_string { public: Native(char *str, size_t len) :Binary_string(str, len) { } }; template class NativeBuffer: public Native { char buff[buff_sz]; public: NativeBuffer() : Native(buff, buff_sz) { length(0); } }; class String_ptr { protected: String *m_string_ptr; public: String_ptr(String *str) :m_string_ptr(str) { } String_ptr(Item *item, String *buffer); const String *string() const { DBUG_ASSERT(m_string_ptr); return m_string_ptr; } bool is_null() const { return m_string_ptr == NULL; } }; class Ascii_ptr: public String_ptr { public: Ascii_ptr(Item *item, String *buffer); }; template class String_ptr_and_buffer: public StringBuffer, public String_ptr { public: String_ptr_and_buffer(Item *item) :String_ptr(item, this) { } }; template class Ascii_ptr_and_buffer: public StringBuffer, public Ascii_ptr { public: Ascii_ptr_and_buffer(Item *item) :Ascii_ptr(item, this) { } }; class Dec_ptr { protected: my_decimal *m_ptr; Dec_ptr() = default; public: Dec_ptr(my_decimal *ptr) :m_ptr(ptr) { } bool is_null() const { return m_ptr == NULL; } const my_decimal *ptr() const { return m_ptr; } const my_decimal *ptr_or(const my_decimal *def) const { return m_ptr ? m_ptr : def; } my_decimal *to_decimal(my_decimal *to) const { if (!m_ptr) return NULL; *to= *m_ptr; return to; } double to_double() const { return m_ptr ? m_ptr->to_double() : 0.0; } longlong to_longlong(bool unsigned_flag) { return m_ptr ? m_ptr->to_longlong(unsigned_flag) : 0; } Longlong_null to_xlonglong_null() { return m_ptr ? Longlong_null(m_ptr->to_xlonglong()) : Longlong_null(); } bool to_bool() const { return m_ptr ? m_ptr->to_bool() : false; } String *to_string(String *to) const { return m_ptr ? m_ptr->to_string(to) : NULL; } String *to_string(String *to, uint prec, uint dec, char filler) { return m_ptr ? m_ptr->to_string(to, prec, dec, filler) : NULL; } int to_binary(uchar *bin, int prec, decimal_digits_t scale) const { return (m_ptr ? m_ptr : &decimal_zero)->to_binary(bin, prec, scale); } int cmp(const my_decimal *dec) const { DBUG_ASSERT(m_ptr); DBUG_ASSERT(dec); return m_ptr->cmp(dec); } int cmp(const Dec_ptr &other) const { return cmp(other.m_ptr); } }; // A helper class to handle results of val_decimal(), date_op(), etc. class Dec_ptr_and_buffer: public Dec_ptr { protected: my_decimal m_buffer; public: /* scale is int as it can be negative here */ int round_to(my_decimal *to, int scale, decimal_round_mode mode) { DBUG_ASSERT(m_ptr); return m_ptr->round_to(to, scale, mode); } int round_self(decimal_digits_t scale, decimal_round_mode mode) { return round_to(&m_buffer, scale, mode); } int round_self_if_needed(int scale, decimal_round_mode mode) { if (scale >= m_ptr->frac) return E_DEC_OK; int res= m_ptr->round_to(&m_buffer, scale, mode); m_ptr= &m_buffer; return res; } String *to_string_round(String *to, decimal_digits_t dec) { /* decimal_round() allows from==to So it's save even if m_ptr points to m_buffer before this call: */ return m_ptr ? m_ptr->to_string_round(to, dec, &m_buffer) : NULL; } }; // A helper class to handle val_decimal() results. class VDec: public Dec_ptr_and_buffer { public: VDec(): Dec_ptr_and_buffer() { } VDec(Item *item); void set(Item *a); }; // A helper class to handler decimal_op() results. class VDec_op: public Dec_ptr_and_buffer { public: VDec_op(Item_func_hybrid_field_type *item); }; /* Get and cache val_decimal() values for two items. If the first value appears to be NULL, the second value is not evaluated. */ class VDec2_lazy { public: VDec m_a; VDec m_b; VDec2_lazy(Item *a, Item *b) :m_a(a) { if (!m_a.is_null()) m_b.set(b); } bool has_null() const { return m_a.is_null() || m_b.is_null(); } }; /** Class Sec6 represents a fixed point value with 6 fractional digits. Used e.g. to convert double and my_decimal values to TIME/DATETIME. */ class Sec6 { protected: ulonglong m_sec; // The integer part, between 0 and LONGLONG_MAX ulong m_usec; // The fractional part, between 0 and 999999 bool m_neg; // false if positive, true of negative bool m_truncated; // Indicates if the constructor truncated the value void make_from_decimal(const my_decimal *d, ulong *nanoseconds); void make_from_double(double d, ulong *nanoseconds); void make_from_int(const Longlong_hybrid &nr) { m_neg= nr.neg(); m_sec= nr.abs(); m_usec= 0; m_truncated= false; } void reset() { m_sec= m_usec= m_neg= m_truncated= 0; } Sec6() = default; bool add_nanoseconds(uint nanoseconds) { DBUG_ASSERT(nanoseconds <= 1000000000); if (nanoseconds < 500) return false; m_usec+= (nanoseconds + 500) / 1000; if (m_usec < 1000000) return false; m_usec%= 1000000; return true; } public: explicit Sec6(double nr) { ulong nanoseconds; make_from_double(nr, &nanoseconds); } explicit Sec6(const my_decimal *d) { ulong nanoseconds; make_from_decimal(d, &nanoseconds); } explicit Sec6(const Longlong_hybrid &nr) { make_from_int(nr); } explicit Sec6(longlong nr, bool unsigned_val) { make_from_int(Longlong_hybrid(nr, unsigned_val)); } bool neg() const { return m_neg; } bool truncated() const { return m_truncated; } ulonglong sec() const { return m_sec; } long usec() const { return m_usec; } /** Converts Sec6 to MYSQL_TIME @param thd current thd @param [out] warn conversion warnings will be written here @param [out] ltime converted value will be written here @param fuzzydate conversion flags (TIME_INVALID_DATE, etc) @returns false for success, true for a failure */ bool convert_to_mysql_time(THD *thd, int *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const; protected: bool to_interval_hhmmssff_only(MYSQL_TIME *to, int *warn) const { return number_to_time_only(m_neg, m_sec, m_usec, TIME_MAX_INTERVAL_HOUR, to, warn); } bool to_datetime_or_to_interval_hhmmssff(MYSQL_TIME *to, int *warn) const { /* Convert a number to a time interval. The following formats are understood: - 0 <= x <= 999999995959 - parse as hhhhmmss - 999999995959 < x <= 99991231235959 - parse as YYYYMMDDhhmmss (YYMMDDhhmmss) (YYYYMMDDhhmmss) Note, these formats are NOT understood: - YYMMDD - overlaps with INTERVAL range - YYYYMMDD - overlaps with INTERVAL range - YYMMDDhhmmss - overlaps with INTERVAL range, partially (see TIME_MAX_INTERVAL_HOUR) If we ever need wider intervals, this code switching between full datetime and interval-only should be rewised. */ DBUG_ASSERT(TIME_MAX_INTERVAL_HOUR <= 999999995959); /* (YYMMDDhhmmss) */ if (m_sec > 999999995959ULL && m_sec <= 99991231235959ULL && m_neg == 0) return to_datetime_or_date(to, warn, TIME_INVALID_DATES); if (m_sec / 10000 > TIME_MAX_INTERVAL_HOUR) { *warn= MYSQL_TIME_WARN_OUT_OF_RANGE; return true; } return to_interval_hhmmssff_only(to, warn); } public: // [-][DD]hhhmmss.ff, YYMMDDhhmmss.ff, YYYYMMDDhhmmss.ff bool to_datetime_or_time(MYSQL_TIME *to, int *warn, date_conv_mode_t mode) const { bool rc= m_sec > 9999999 && m_sec <= 99991231235959ULL && !m_neg ? ::number_to_datetime_or_date(m_sec, m_usec, to, ulonglong(mode & TIME_MODE_FOR_XXX_TO_DATE), warn) < 0 : ::number_to_time_only(m_neg, m_sec, m_usec, TIME_MAX_HOUR, to, warn); DBUG_ASSERT(*warn || !rc); return rc; } /* Convert a number in formats YYYYMMDDhhmmss.ff or YYMMDDhhmmss.ff to TIMESTAMP'YYYY-MM-DD hh:mm:ss.ff' */ bool to_datetime_or_date(MYSQL_TIME *to, int *warn, date_conv_mode_t flags) const { if (m_neg) { *warn= MYSQL_TIME_WARN_OUT_OF_RANGE; return true; } bool rc= number_to_datetime_or_date(m_sec, m_usec, to, ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), warn) == -1; DBUG_ASSERT(*warn || !rc); return rc; } // Convert elapsed seconds to TIME bool sec_to_time(MYSQL_TIME *ltime, uint dec) const { set_zero_time(ltime, MYSQL_TIMESTAMP_TIME); ltime->neg= m_neg; if (m_sec > TIME_MAX_VALUE_SECONDS) { // use check_time_range() to set ltime to the max value depending on dec int unused; ltime->hour= TIME_MAX_HOUR + 1; check_time_range(ltime, dec, &unused); return true; } DBUG_ASSERT(usec() <= TIME_MAX_SECOND_PART); ltime->hour= (uint) (m_sec / 3600); ltime->minute= (uint) (m_sec % 3600) / 60; ltime->second= (uint) m_sec % 60; ltime->second_part= m_usec; return false; } Sec6 &trunc(uint dec) { m_usec-= my_time_fraction_remainder(m_usec, dec); return *this; } size_t to_string(char *to, size_t nbytes) const { return m_usec ? my_snprintf(to, nbytes, "%s%llu.%06lu", m_neg ? "-" : "", m_sec, m_usec) : my_snprintf(to, nbytes, "%s%llu", m_neg ? "-" : "", m_sec); } void make_truncated_warning(THD *thd, const char *type_str) const; }; class Sec9: public Sec6 { protected: ulong m_nsec; // Nanoseconds 0..999 void make_from_int(const Longlong_hybrid &nr) { Sec6::make_from_int(nr); m_nsec= 0; } Sec9() = default; public: Sec9(const my_decimal *d) { Sec6::make_from_decimal(d, &m_nsec); } Sec9(double d) { Sec6::make_from_double(d, &m_nsec); } ulong nsec() const { return m_nsec; } Sec9 &trunc(uint dec) { m_nsec= 0; Sec6::trunc(dec); return *this; } Sec9 &round(uint dec); Sec9 &round(uint dec, time_round_mode_t mode) { return mode == TIME_FRAC_TRUNCATE ? trunc(dec) : round(dec); } }; class VSec9: protected Sec9 { bool m_is_null; Sec9& to_sec9() { DBUG_ASSERT(!is_null()); return *this; } public: VSec9(THD *thd, Item *item, const char *type_str, ulonglong limit); bool is_null() const { return m_is_null; } const Sec9& to_const_sec9() const { DBUG_ASSERT(!is_null()); return *this; } bool neg() const { return to_const_sec9().neg(); } bool truncated() const { return to_const_sec9().truncated(); } ulonglong sec() const { return to_const_sec9().sec(); } long usec() const { return to_const_sec9().usec(); } bool sec_to_time(MYSQL_TIME *ltime, uint dec) const { return to_const_sec9().sec_to_time(ltime, dec); } void make_truncated_warning(THD *thd, const char *type_str) const { return to_const_sec9().make_truncated_warning(thd, type_str); } Sec9 &round(uint dec) { return to_sec9().round(dec); } Sec9 &round(uint dec, time_round_mode_t mode) { return to_sec9().round(dec, mode); } }; /* A heler class to perform additive operations between two MYSQL_TIME structures and return the result as a combination of seconds, microseconds and sign. */ class Sec6_add { ulonglong m_sec; // number of seconds ulong m_usec; // number of microseconds bool m_neg; // false if positive, true if negative bool m_error; // false if the value is OK, true otherwise void to_hh24mmssff(MYSQL_TIME *ltime, timestamp_type tstype) const { bzero(ltime, sizeof(*ltime)); ltime->neg= m_neg; calc_time_from_sec(ltime, (ulong) (m_sec % SECONDS_IN_24H), m_usec); ltime->time_type= tstype; } public: /* @param ltime1 - the first value to add (must be a valid DATE,TIME,DATETIME) @param ltime2 - the second value to add (must be a valid TIME) @param sign - the sign of the operation (+1 for addition, -1 for subtraction) */ Sec6_add(const MYSQL_TIME *ltime1, const MYSQL_TIME *ltime2, int sign) { DBUG_ASSERT(sign == -1 || sign == 1); DBUG_ASSERT(!ltime1->neg || ltime1->time_type == MYSQL_TIMESTAMP_TIME); if (!(m_error= (ltime2->time_type != MYSQL_TIMESTAMP_TIME))) { if (ltime1->neg != ltime2->neg) sign= -sign; m_neg= calc_time_diff(ltime1, ltime2, -sign, &m_sec, &m_usec); if (ltime1->neg && (m_sec || m_usec)) m_neg= !m_neg; // Swap sign } } bool to_time(THD *thd, MYSQL_TIME *ltime, uint decimals) const { if (m_error) return true; to_hh24mmssff(ltime, MYSQL_TIMESTAMP_TIME); ltime->hour+= static_cast(to_days_abs() * 24); return adjust_time_range_with_warn(thd, ltime, decimals); } bool to_datetime(MYSQL_TIME *ltime) const { if (m_error || m_neg) return true; to_hh24mmssff(ltime, MYSQL_TIMESTAMP_DATETIME); return get_date_from_daynr(to_days_abs(), <ime->year, <ime->month, <ime->day) || !ltime->day; } long to_days_abs() const { return (long) (m_sec / SECONDS_IN_24H); } }; class Year { protected: uint m_year; bool m_truncated; uint year_precision(const Item *item) const; public: Year(): m_year(0), m_truncated(false) { } Year(longlong value, bool unsigned_flag, uint length); uint year() const { return m_year; } uint to_YYYYMMDD() const { return m_year * 10000; } bool truncated() const { return m_truncated; } }; class Year_null: public Year, public Null_flag { public: Year_null(const Longlong_null &nr, bool unsigned_flag, uint length) :Year(nr.is_null() ? 0 : nr.value(), unsigned_flag, length), Null_flag(nr.is_null()) { } }; class VYear: public Year_null { public: VYear(Item *item); }; class VYear_op: public Year_null { public: VYear_op(Item_func_hybrid_field_type *item); }; class Double_null: public Null_flag { protected: double m_value; public: Double_null(double value, bool is_null) :Null_flag(is_null), m_value(value) { } double value() const { return m_value; } }; class Temporal: protected MYSQL_TIME { public: class Status: public MYSQL_TIME_STATUS { public: Status() { my_time_status_init(this); } }; class Warn: public ErrBuff, public Status { public: void push_conversion_warnings(THD *thd, bool totally_useless_value, date_mode_t mode, timestamp_type tstype, const char *db_name, const char *table_name, const char *name) { const char *typestr= tstype >= 0 ? type_name_by_timestamp_type(tstype) : mode & (TIME_INTERVAL_hhmmssff | TIME_INTERVAL_DAY) ? "interval" : mode & TIME_TIME_ONLY ? "time" : "datetime"; Temporal::push_conversion_warnings(thd, totally_useless_value, warnings, typestr, db_name, table_name, name, ptr()); } }; class Warn_push: public Warn { THD * const m_thd; const char * const m_db_name; const char * const m_table_name; const char * const m_name; const MYSQL_TIME * const m_ltime; const date_mode_t m_mode; public: Warn_push(THD *thd, const char *db_name, const char *table_name, const char *name, const MYSQL_TIME *ltime, date_mode_t mode) : m_thd(thd), m_db_name(db_name), m_table_name(table_name), m_name(name), m_ltime(ltime), m_mode(mode) { } ~Warn_push() { if (warnings) push_conversion_warnings(m_thd, m_ltime->time_type < 0, m_mode, m_ltime->time_type, m_db_name, m_table_name, m_name); } }; public: static date_conv_mode_t sql_mode_for_dates(THD *thd); static time_round_mode_t default_round_mode(THD *thd); class Options: public date_mode_t { public: explicit Options(date_mode_t flags) :date_mode_t(flags) { } Options(date_conv_mode_t flags, time_round_mode_t round_mode) :date_mode_t(flags | round_mode) { DBUG_ASSERT(ulonglong(flags) <= UINT_MAX32); } Options(date_conv_mode_t flags, THD *thd) :Options(flags, default_round_mode(thd)) { } }; bool is_valid_temporal() const { DBUG_ASSERT(time_type != MYSQL_TIMESTAMP_ERROR); return time_type != MYSQL_TIMESTAMP_NONE; } static const char *type_name_by_timestamp_type(timestamp_type time_type) { switch (time_type) { case MYSQL_TIMESTAMP_DATE: return "date"; case MYSQL_TIMESTAMP_TIME: return "time"; case MYSQL_TIMESTAMP_DATETIME: // FALLTHROUGH default: break; } return "datetime"; } static void push_conversion_warnings(THD *thd, bool totally_useless_value, int warn, const char *type_name, const char *db_name, const char *table_name, const char *field_name, const char *value); /* This method is used if the item was not null but convertion to TIME/DATE/DATETIME failed. We return a zero date if allowed, otherwise - null. */ void make_fuzzy_date(int *warn, date_conv_mode_t fuzzydate) { /* In the following scenario: - The caller expected to get a TIME value - Item returned a not NULL string or numeric value - But then conversion from string or number to TIME failed we need to change the default time_type from MYSQL_TIMESTAMP_DATE (which was set in bzero) to MYSQL_TIMESTAMP_TIME and therefore return TIME'00:00:00' rather than DATE'0000-00-00'. If we don't do this, methods like Item::get_time_with_conversion() will erroneously subtract CURRENT_DATE from '0000-00-00 00:00:00' and return TIME'-838:59:59' instead of TIME'00:00:00' as a result. */ timestamp_type tstype= !(fuzzydate & TIME_FUZZY_DATES) ? MYSQL_TIMESTAMP_NONE : fuzzydate & TIME_TIME_ONLY ? MYSQL_TIMESTAMP_TIME : MYSQL_TIMESTAMP_DATETIME; set_zero_time(this, tstype); } protected: my_decimal *bad_to_decimal(my_decimal *to) const; my_decimal *to_decimal(my_decimal *to) const; static double to_double(bool negate, ulonglong num, ulong frac) { double d= static_cast(num) + static_cast(frac) / TIME_SECOND_PART_FACTOR; return negate ? -d : d; } longlong to_packed() const { return ::pack_time(this); } void make_from_out_of_range(int *warn) { *warn= MYSQL_TIME_WARN_OUT_OF_RANGE; time_type= MYSQL_TIMESTAMP_NONE; } void make_from_sec6(THD *thd, MYSQL_TIME_STATUS *st, const Sec6 &nr, date_mode_t mode) { if (nr.convert_to_mysql_time(thd, &st->warnings, this, mode)) make_fuzzy_date(&st->warnings, date_conv_mode_t(mode)); } void make_from_sec9(THD *thd, MYSQL_TIME_STATUS *st, const Sec9 &nr, date_mode_t mode) { if (nr.convert_to_mysql_time(thd, &st->warnings, this, mode) || add_nanoseconds(thd, &st->warnings, mode, nr.nsec())) make_fuzzy_date(&st->warnings, date_conv_mode_t(mode)); } void make_from_str(THD *thd, Warn *warn, const char *str, size_t length, CHARSET_INFO *cs, date_mode_t fuzzydate); void make_from_double(THD *thd, Warn *warn, double nr, date_mode_t mode) { make_from_sec9(thd, warn, Sec9(nr), mode); if (warn->warnings) warn->set_double(nr); } void make_from_longlong_hybrid(THD *thd, Warn *warn, const Longlong_hybrid &nr, date_mode_t mode) { /* Note: conversion from an integer to TIME can overflow to '838:59:59.999999', so the conversion result can have fractional digits. */ make_from_sec6(thd, warn, Sec6(nr), mode); if (warn->warnings) warn->set_longlong(nr); } void make_from_decimal(THD *thd, Warn *warn, const my_decimal *nr, date_mode_t mode) { make_from_sec9(thd, warn, Sec9(nr), mode); if (warn->warnings) warn->set_decimal(nr); } bool ascii_to_temporal(MYSQL_TIME_STATUS *st, const char *str, size_t length, date_mode_t mode) { if (mode & (TIME_INTERVAL_hhmmssff | TIME_INTERVAL_DAY)) return ascii_to_datetime_or_date_or_interval_DDhhmmssff(st, str, length, mode); if (mode & TIME_TIME_ONLY) return ascii_to_datetime_or_date_or_time(st, str, length, mode); return ascii_to_datetime_or_date(st, str, length, mode); } bool ascii_to_datetime_or_date_or_interval_DDhhmmssff(MYSQL_TIME_STATUS *st, const char *str, size_t length, date_mode_t mode) { longlong cflags= ulonglong(mode & TIME_MODE_FOR_XXX_TO_DATE); bool rc= mode & TIME_INTERVAL_DAY ? ::str_to_datetime_or_date_or_interval_day(str, length, this, cflags, st, TIME_MAX_INTERVAL_HOUR, TIME_MAX_INTERVAL_HOUR) : ::str_to_datetime_or_date_or_interval_hhmmssff(str, length, this, cflags, st, TIME_MAX_INTERVAL_HOUR, TIME_MAX_INTERVAL_HOUR); DBUG_ASSERT(!rc || st->warnings); return rc; } bool ascii_to_datetime_or_date_or_time(MYSQL_TIME_STATUS *status, const char *str, size_t length, date_mode_t fuzzydate) { ulonglong cflags= ulonglong(fuzzydate & TIME_MODE_FOR_XXX_TO_DATE); bool rc= ::str_to_datetime_or_date_or_time(str, length, this, cflags, status, TIME_MAX_HOUR, UINT_MAX32); DBUG_ASSERT(!rc || status->warnings); return rc; } bool ascii_to_datetime_or_date(MYSQL_TIME_STATUS *status, const char *str, size_t length, date_mode_t fuzzydate) { DBUG_ASSERT(bool(fuzzydate & TIME_TIME_ONLY) == false); bool rc= ::str_to_datetime_or_date(str, length, this, ulonglong(fuzzydate & TIME_MODE_FOR_XXX_TO_DATE), status); DBUG_ASSERT(!rc || status->warnings); return rc; } // Character set aware versions for string conversion routines bool str_to_temporal(THD *thd, MYSQL_TIME_STATUS *st, const char *str, size_t length, CHARSET_INFO *cs, date_mode_t fuzzydate); bool str_to_datetime_or_date_or_time(THD *thd, MYSQL_TIME_STATUS *st, const char *str, size_t length, CHARSET_INFO *cs, date_mode_t mode); bool str_to_datetime_or_date(THD *thd, MYSQL_TIME_STATUS *st, const char *str, size_t length, CHARSET_INFO *cs, date_mode_t mode); bool has_valid_mmssff() const { return minute <= TIME_MAX_MINUTE && second <= TIME_MAX_SECOND && second_part <= TIME_MAX_SECOND_PART; } bool has_zero_YYYYMM() const { return year == 0 && month == 0; } bool has_zero_YYYYMMDD() const { return year == 0 && month == 0 && day == 0; } bool check_date(date_conv_mode_t flags, int *warn) const { return ::check_date(this, flags, warn); } void time_hhmmssff_set_max(uint max_hour) { hour= max_hour; minute= TIME_MAX_MINUTE; second= TIME_MAX_SECOND; second_part= TIME_MAX_SECOND_PART; } /* Add nanoseconds to ssff retval true if seconds overflowed (the caller should increment minutes) false if no overflow happened */ bool add_nanoseconds_ssff(uint nanoseconds) { DBUG_ASSERT(nanoseconds <= 1000000000); if (nanoseconds < 500) return false; second_part+= (nanoseconds + 500) / 1000; if (second_part < 1000000) return false; second_part%= 1000000; if (second < 59) { second++; return false; } second= 0; return true; } /* Add nanoseconds to mmssff retval true if hours overflowed (the caller should increment hours) false if no overflow happened */ bool add_nanoseconds_mmssff(uint nanoseconds) { if (!add_nanoseconds_ssff(nanoseconds)) return false; if (minute < 59) { minute++; return false; } minute= 0; return true; } void time_round_or_set_max(uint dec, int *warn, ulong max_hour, ulong nsec); bool datetime_add_nanoseconds_or_invalidate(THD *thd, int *warn, ulong nsec); bool datetime_round_or_invalidate(THD *thd, uint dec, int *warn, ulong nsec); bool add_nanoseconds_with_round(THD *thd, int *warn, date_conv_mode_t mode, ulong nsec); bool add_nanoseconds(THD *thd, int *warn, date_mode_t mode, ulong nsec) { date_conv_mode_t cmode= date_conv_mode_t(mode); return time_round_mode_t(mode) == TIME_FRAC_ROUND ? add_nanoseconds_with_round(thd, warn, cmode, nsec) : false; } public: static void *operator new(size_t size, MYSQL_TIME *ltime) throw() { DBUG_ASSERT(size == sizeof(MYSQL_TIME)); return ltime; } static void operator delete(void *ptr, MYSQL_TIME *ltime) { } long fraction_remainder(uint dec) const { return my_time_fraction_remainder(second_part, dec); } }; /* Use this class when you need to get a MYSQL_TIME from an Item using Item's native timestamp type, without automatic timestamp type conversion. */ class Temporal_hybrid: public Temporal { public: class Options: public Temporal::Options { public: Options(THD *thd) :Temporal::Options(sql_mode_for_dates(thd), default_round_mode(thd)) { } Options(date_conv_mode_t flags, time_round_mode_t round_mode) :Temporal::Options(flags, round_mode) { } explicit Options(const Temporal::Options &opt) :Temporal::Options(opt) { } explicit Options(date_mode_t fuzzydate) :Temporal::Options(fuzzydate) { } }; public: // Contructors for Item Temporal_hybrid(THD *thd, Item *item, date_mode_t fuzzydate); Temporal_hybrid(THD *thd, Item *item) :Temporal_hybrid(thd, item, Options(thd)) { } Temporal_hybrid(Item *item) :Temporal_hybrid(current_thd, item) { } // Constructors for non-NULL values Temporal_hybrid(THD *thd, Warn *warn, const char *str, size_t length, CHARSET_INFO *cs, date_mode_t fuzzydate) { make_from_str(thd, warn, str, length, cs, fuzzydate); } Temporal_hybrid(THD *thd, Warn *warn, const Longlong_hybrid &nr, date_mode_t fuzzydate) { make_from_longlong_hybrid(thd, warn, nr, fuzzydate); } Temporal_hybrid(THD *thd, Warn *warn, double nr, date_mode_t fuzzydate) { make_from_double(thd, warn, nr, fuzzydate); } // Constructors for nullable values Temporal_hybrid(THD *thd, Warn *warn, const String *str, date_mode_t mode) { if (!str) time_type= MYSQL_TIMESTAMP_NONE; else make_from_str(thd, warn, str->ptr(), str->length(), str->charset(), mode); } Temporal_hybrid(THD *thd, Warn *warn, const Longlong_hybrid_null &nr, date_mode_t fuzzydate) { if (nr.is_null()) time_type= MYSQL_TIMESTAMP_NONE; else make_from_longlong_hybrid(thd, warn, nr, fuzzydate); } Temporal_hybrid(THD *thd, Warn *warn, const Double_null &nr, date_mode_t mode) { if (nr.is_null()) time_type= MYSQL_TIMESTAMP_NONE; else make_from_double(thd, warn, nr.value(), mode); } Temporal_hybrid(THD *thd, Warn *warn, const my_decimal *nr, date_mode_t mode) { if (!nr) time_type= MYSQL_TIMESTAMP_NONE; else make_from_decimal(thd, warn, nr, mode); } // End of constuctors bool copy_valid_value_to_mysql_time(MYSQL_TIME *ltime) const { DBUG_ASSERT(is_valid_temporal()); *ltime= *this; return false; } longlong to_longlong() const { if (!is_valid_temporal()) return 0; ulonglong v= TIME_to_ulonglong(this); return neg ? -(longlong) v : (longlong) v; } double to_double() const { return is_valid_temporal() ? TIME_to_double(this) : 0; } my_decimal *to_decimal(my_decimal *to) { return is_valid_temporal() ? Temporal::to_decimal(to) : bad_to_decimal(to); } String *to_string(String *str, uint dec) const { if (!is_valid_temporal()) return NULL; str->set_charset(&my_charset_numeric); if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) str->length(my_TIME_to_str(this, const_cast(str->ptr()), dec)); return str; } const MYSQL_TIME *get_mysql_time() const { DBUG_ASSERT(is_valid_temporal()); return this; } }; /* This class resembles the SQL standard , used in extract expressions, e.g: EXTRACT(DAY FROM dt) ::= EXTRACT FROM ::= | */ class Extract_source: public Temporal_hybrid { /* Convert a TIME value to DAY-TIME interval, e.g. for extraction: EXTRACT(DAY FROM x), EXTRACT(HOUR FROM x), etc. Moves full days from ltime->hour to ltime->day. */ void time_to_daytime_interval() { DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_TIME); DBUG_ASSERT(has_zero_YYYYMMDD()); MYSQL_TIME::day= MYSQL_TIME::hour / 24; MYSQL_TIME::hour%= 24; } bool is_valid_extract_source_slow() const { return is_valid_temporal() && MYSQL_TIME::hour < 24 && (has_zero_YYYYMM() || time_type != MYSQL_TIMESTAMP_TIME); } bool is_valid_value_slow() const { return time_type == MYSQL_TIMESTAMP_NONE || is_valid_extract_source_slow(); } public: Extract_source(THD *thd, Item *item, date_mode_t mode) :Temporal_hybrid(thd, item, mode) { if (MYSQL_TIME::time_type == MYSQL_TIMESTAMP_TIME) time_to_daytime_interval(); DBUG_ASSERT(is_valid_value_slow()); } inline const MYSQL_TIME *get_mysql_time() const { DBUG_ASSERT(is_valid_extract_source_slow()); return this; } bool is_valid_extract_source() const { return is_valid_temporal(); } int sign() const { return get_mysql_time()->neg ? -1 : 1; } uint year() const { return get_mysql_time()->year; } uint month() const { return get_mysql_time()->month; } int day() const { return (int) get_mysql_time()->day * sign(); } int hour() const { return (int) get_mysql_time()->hour * sign(); } int minute() const { return (int) get_mysql_time()->minute * sign(); } int second() const { return (int) get_mysql_time()->second * sign(); } int microsecond() const { return (int) get_mysql_time()->second_part * sign(); } uint year_month() const { return year() * 100 + month(); } uint quarter() const { return (month() + 2)/3; } uint week(THD *thd) const; longlong second_microsecond() const { return (second() * 1000000LL + microsecond()); } // DAY TO XXX longlong day_hour() const { return (longlong) day() * 100LL + hour(); } longlong day_minute() const { return day_hour() * 100LL + minute(); } longlong day_second() const { return day_minute() * 100LL + second(); } longlong day_microsecond() const { return day_second() * 1000000LL + microsecond(); } // HOUR TO XXX int hour_minute() const { return hour() * 100 + minute(); } int hour_second() const { return hour_minute() * 100 + second(); } longlong hour_microsecond() const { return hour_second() * 1000000LL + microsecond(); } // MINUTE TO XXX int minute_second() const { return minute() * 100 + second(); } longlong minute_microsecond() const { return minute_second() * 1000000LL + microsecond(); } }; /* This class is used for the "time_interval" argument of these SQL functions: TIMESTAMP(tm,time_interval) ADDTIME(tm,time_interval) Features: - DATE and DATETIME formats are treated as errors - Preserves hours for TIME format as is, without limiting to TIME_MAX_HOUR */ class Interval_DDhhmmssff: public Temporal { static const LEX_CSTRING m_type_name; bool str_to_DDhhmmssff(MYSQL_TIME_STATUS *status, const char *str, size_t length, CHARSET_INFO *cs, ulong max_hour); void push_warning_wrong_or_truncated_value(THD *thd, const ErrConv &str, int warnings); bool is_valid_interval_DDhhmmssff_slow() const { return time_type == MYSQL_TIMESTAMP_TIME && has_zero_YYYYMMDD() && has_valid_mmssff(); } bool is_valid_value_slow() const { return time_type == MYSQL_TIMESTAMP_NONE || is_valid_interval_DDhhmmssff_slow(); } public: // Get fractional second precision from an Item static uint fsp(THD *thd, Item *item); /* Maximum useful HOUR value: TIMESTAMP'0001-01-01 00:00:00' + '87649415:59:59' = '9999-12-31 23:59:59' This gives maximum possible interval values: - '87649415:59:59.999999' (in 'hh:mm:ss.ff' format) - '3652058 23:59:59.999999' (in 'DD hh:mm:ss.ff' format) */ static uint max_useful_hour() { return TIME_MAX_INTERVAL_HOUR; } static uint max_int_part_char_length() { // e.g. '+3652058 23:59:59' return 1/*sign*/ + TIME_MAX_INTERVAL_DAY_CHAR_LENGTH + 1 + 8/*hh:mm:ss*/; } static uint max_char_length(uint fsp) { DBUG_ASSERT(fsp <= TIME_SECOND_PART_DIGITS); return max_int_part_char_length() + (fsp ? 1 : 0) + fsp; } public: Interval_DDhhmmssff(THD *thd, Status *st, bool push_warnings, Item *item, ulong max_hour, time_round_mode_t mode, uint dec); Interval_DDhhmmssff(THD *thd, Item *item, uint dec) { Status st; new(this) Interval_DDhhmmssff(thd, &st, true, item, max_useful_hour(), default_round_mode(thd), dec); } Interval_DDhhmmssff(THD *thd, Item *item) :Interval_DDhhmmssff(thd, item, TIME_SECOND_PART_DIGITS) { } const MYSQL_TIME *get_mysql_time() const { DBUG_ASSERT(is_valid_interval_DDhhmmssff_slow()); return this; } bool is_valid_interval_DDhhmmssff() const { return time_type == MYSQL_TIMESTAMP_TIME; } bool is_valid_value() const { return time_type == MYSQL_TIMESTAMP_NONE || is_valid_interval_DDhhmmssff(); } String *to_string(String *str, uint dec) const { if (!is_valid_interval_DDhhmmssff()) return NULL; str->set_charset(&my_charset_numeric); if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) str->length(my_interval_DDhhmmssff_to_str(this, const_cast(str->ptr()), dec)); return str; } }; class Schema; /** Class Time is designed to store valid TIME values. 1. Valid value: a. MYSQL_TIMESTAMP_TIME - a valid TIME within the supported TIME range b. MYSQL_TIMESTAMP_NONE - an undefined value 2. Invalid value (internally only): a. MYSQL_TIMESTAMP_TIME outside of the supported TIME range a. MYSQL_TIMESTAMP_{DATE|DATETIME|ERROR} Temporarily Time is allowed to have an invalid value, but only internally, during initialization time. All constructors and modification methods must leave the Time value as described above (see "Valid values"). Time derives from MYSQL_TIME privately to make sure it is accessed externally only in the valid state. */ class Time: public Temporal { static uint binary_length_to_precision(uint length); public: enum datetime_to_time_mode_t { DATETIME_TO_TIME_DISALLOW, DATETIME_TO_TIME_YYYYMMDD_000000DD_MIX_TO_HOURS, DATETIME_TO_TIME_YYYYMMDD_TRUNCATE, DATETIME_TO_TIME_YYYYMMDD_00000000_ONLY, DATETIME_TO_TIME_MINUS_CURRENT_DATE }; class Options: public Temporal::Options { datetime_to_time_mode_t m_datetime_to_time_mode; public: Options(THD *thd) :Temporal::Options(default_flags_for_get_date(), default_round_mode(thd)), m_datetime_to_time_mode(default_datetime_to_time_mode()) { } Options(date_conv_mode_t flags, THD *thd) :Temporal::Options(flags, default_round_mode(thd)), m_datetime_to_time_mode(default_datetime_to_time_mode()) { } Options(date_conv_mode_t flags, THD *thd, datetime_to_time_mode_t dtmode) :Temporal::Options(flags, default_round_mode(thd)), m_datetime_to_time_mode(dtmode) { } Options(date_conv_mode_t fuzzydate, time_round_mode_t round_mode, datetime_to_time_mode_t datetime_to_time_mode) :Temporal::Options(fuzzydate, round_mode), m_datetime_to_time_mode(datetime_to_time_mode) { } datetime_to_time_mode_t datetime_to_time_mode() const { return m_datetime_to_time_mode; } static datetime_to_time_mode_t default_datetime_to_time_mode() { return DATETIME_TO_TIME_YYYYMMDD_000000DD_MIX_TO_HOURS; } }; /* CAST(AS TIME) historically does not mix days to hours. This is different comparing to how implicit conversion in Field::store_time_dec() works (e.g. on INSERT). */ class Options_for_cast: public Options { public: Options_for_cast(THD *thd) :Options(default_flags_for_get_date(), default_round_mode(thd), DATETIME_TO_TIME_YYYYMMDD_TRUNCATE) { } Options_for_cast(date_mode_t mode, THD *thd) :Options(default_flags_for_get_date() | (mode & TIME_FUZZY_DATES), default_round_mode(thd), DATETIME_TO_TIME_YYYYMMDD_TRUNCATE) { } }; class Options_for_round: public Options { public: Options_for_round(time_round_mode_t round_mode= TIME_FRAC_TRUNCATE) :Options(Time::default_flags_for_get_date(), round_mode, Time::DATETIME_TO_TIME_DISALLOW) { } }; class Options_cmp: public Options { public: Options_cmp(THD *thd) :Options(comparison_flags_for_get_date(), thd) { } Options_cmp(THD *thd, datetime_to_time_mode_t dtmode) :Options(comparison_flags_for_get_date(), default_round_mode(thd), dtmode) { } }; private: bool is_valid_value_slow() const { return time_type == MYSQL_TIMESTAMP_NONE || is_valid_time_slow(); } bool is_valid_time_slow() const { return time_type == MYSQL_TIMESTAMP_TIME && has_zero_YYYYMMDD() && has_valid_mmssff(); } void hhmmssff_copy(const MYSQL_TIME *from) { hour= from->hour; minute= from->minute; second= from->second; second_part= from->second_part; } void datetime_to_time_YYYYMMDD_000000DD_mix_to_hours(int *warn, uint from_year, uint from_month, uint from_day) { if (from_year != 0 || from_month != 0) *warn|= MYSQL_TIME_NOTE_TRUNCATED; else hour+= from_day * 24; } /* The result is calculated effectively similar to: TIMEDIFF(dt, CAST(CURRENT_DATE AS DATETIME)) If the difference does not fit to the supported TIME range, it's truncated. */ void datetime_to_time_minus_current_date(THD *thd) { MYSQL_TIME current_date, tmp; set_current_date(thd, ¤t_date); calc_time_diff(this, ¤t_date, 1, &tmp, date_mode_t(0)); static_cast(this)[0]= tmp; int warnings= 0; (void) check_time_range(this, TIME_SECOND_PART_DIGITS, &warnings); DBUG_ASSERT(is_valid_time()); } /* Convert a valid DATE or DATETIME to TIME. Before this call, "this" must be a valid DATE or DATETIME value, e.g. returned from Item::get_date(), str_to_xxx(), number_to_xxx(). After this call, "this" is a valid TIME value. */ void valid_datetime_to_valid_time(THD *thd, int *warn, const Options opt) { DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_DATE || time_type == MYSQL_TIMESTAMP_DATETIME); /* We're dealing with a DATE or DATETIME returned from str_to_xxx(), number_to_xxx() or unpack_time(). Do some asserts to make sure the result hour value after mixing days to hours does not go out of the valid TIME range. The maximum hour value after mixing days will be 31*24+23=767, which is within the supported TIME range. Thus no adjust_time_range_or_invalidate() is needed here. */ DBUG_ASSERT(day < 32); DBUG_ASSERT(hour < 24); if (opt.datetime_to_time_mode() == DATETIME_TO_TIME_MINUS_CURRENT_DATE) { datetime_to_time_minus_current_date(thd); } else { if (opt.datetime_to_time_mode() == DATETIME_TO_TIME_YYYYMMDD_000000DD_MIX_TO_HOURS) datetime_to_time_YYYYMMDD_000000DD_mix_to_hours(warn, year, month, day); year= month= day= 0; time_type= MYSQL_TIMESTAMP_TIME; } DBUG_ASSERT(is_valid_time_slow()); } /** Convert valid DATE/DATETIME to valid TIME if needed. This method is called after Item::get_date(), str_to_xxx(), number_to_xxx(). which can return only valid TIME/DATE/DATETIME values. Before this call, "this" is: - either a valid TIME/DATE/DATETIME value (within the supported range for the corresponding type), - or MYSQL_TIMESTAMP_NONE After this call, "this" is: - either a valid TIME (within the supported TIME range), - or MYSQL_TIMESTAMP_NONE */ void valid_MYSQL_TIME_to_valid_value(THD *thd, int *warn, const Options opt) { switch (time_type) { case MYSQL_TIMESTAMP_DATE: case MYSQL_TIMESTAMP_DATETIME: if (opt.datetime_to_time_mode() == DATETIME_TO_TIME_YYYYMMDD_00000000_ONLY && (year || month || day)) make_from_out_of_range(warn); else if (opt.datetime_to_time_mode() == DATETIME_TO_TIME_DISALLOW) make_from_out_of_range(warn); else valid_datetime_to_valid_time(thd, warn, opt); break; case MYSQL_TIMESTAMP_NONE: break; case MYSQL_TIMESTAMP_ERROR: set_zero_time(this, MYSQL_TIMESTAMP_TIME); break; case MYSQL_TIMESTAMP_TIME: DBUG_ASSERT(is_valid_time_slow()); break; } } /* This method is called after number_to_xxx() and str_to_xxx(), which can return DATE or DATETIME values. Convert to TIME if needed. We trust that xxx_to_time() returns a valid TIME/DATE/DATETIME value, so here we need to do only simple validation. */ void xxx_to_time_result_to_valid_value(THD *thd, int *warn, const Options opt) { // str_to_xxx(), number_to_xxx() never return MYSQL_TIMESTAMP_ERROR DBUG_ASSERT(time_type != MYSQL_TIMESTAMP_ERROR); valid_MYSQL_TIME_to_valid_value(thd, warn, opt); } void adjust_time_range_or_invalidate(int *warn) { if (check_time_range(this, TIME_SECOND_PART_DIGITS, warn)) time_type= MYSQL_TIMESTAMP_NONE; DBUG_ASSERT(is_valid_value_slow()); } public: void round_or_set_max(uint dec, int *warn, ulong nsec); private: void round_or_set_max(uint dec, int *warn); /* All make_from_xxx() methods initialize *warn. The old value gets lost. */ void make_from_datetime_move_day_to_hour(int *warn, const MYSQL_TIME *from); void make_from_datetime_with_days_diff(int *warn, const MYSQL_TIME *from, long curdays); void make_from_time(int *warn, const MYSQL_TIME *from); void make_from_datetime(int *warn, const MYSQL_TIME *from, long curdays); void make_from_item(THD *thd, int *warn, Item *item, const Options opt); public: /* All constructors that accept an "int *warn" parameter initialize *warn. The old value gets lost. */ Time(int *warn, bool neg, ulonglong hour, uint minute, const Sec6 &second); Time() { time_type= MYSQL_TIMESTAMP_NONE; } Time(const Native &native); Time(THD *thd, const MYSQL_TIME *ltime, const Options opt) { *(static_cast(this))= *ltime; DBUG_ASSERT(is_valid_temporal()); int warn= 0; valid_MYSQL_TIME_to_valid_value(thd, &warn, opt); } Time(Item *item) :Time(current_thd, item) { } Time(THD *thd, Item *item, const Options opt) { int warn; make_from_item(thd, &warn, item, opt); } Time(THD *thd, Item *item) :Time(thd, item, Options(thd)) { } Time(int *warn, const MYSQL_TIME *from, long curdays); Time(THD *thd, MYSQL_TIME_STATUS *status, const char *str, size_t len, CHARSET_INFO *cs, const Options opt) { if (str_to_datetime_or_date_or_time(thd, status, str, len, cs, opt)) time_type= MYSQL_TIMESTAMP_NONE; // The below call will optionally add notes to already collected warnings: else xxx_to_time_result_to_valid_value(thd, &status->warnings, opt); } protected: Time(THD *thd, int *warn, const Sec6 &nr, const Options opt) { if (nr.to_datetime_or_time(this, warn, TIME_INVALID_DATES)) time_type= MYSQL_TIMESTAMP_NONE; xxx_to_time_result_to_valid_value(thd, warn, opt); } Time(THD *thd, int *warn, const Sec9 &nr, const Options &opt) :Time(thd, warn, static_cast(nr), opt) { if (is_valid_time() && time_round_mode_t(opt) == TIME_FRAC_ROUND) round_or_set_max(6, warn, nr.nsec()); } public: Time(THD *thd, int *warn, const Longlong_hybrid &nr, const Options &opt) :Time(thd, warn, Sec6(nr), opt) { } Time(THD *thd, int *warn, double nr, const Options &opt) :Time(thd, warn, Sec9(nr), opt) { } Time(THD *thd, int *warn, const my_decimal *d, const Options &opt) :Time(thd, warn, Sec9(d), opt) { } Time(THD *thd, Item *item, const Options opt, uint dec) :Time(thd, item, opt) { round(dec, time_round_mode_t(opt)); } Time(int *warn, const MYSQL_TIME *from, long curdays, const Time::Options &opt, uint dec) :Time(warn, from, curdays) { round(dec, time_round_mode_t(opt), warn); } Time(int *warn, bool neg, ulonglong hour, uint minute, const Sec9 &second, time_round_mode_t mode, uint dec) :Time(warn, neg, hour, minute, second) { DBUG_ASSERT(is_valid_time()); if ((ulonglong) mode == (ulonglong) TIME_FRAC_ROUND) round_or_set_max(6, warn, second.nsec()); round(dec, mode, warn); } Time(THD *thd, MYSQL_TIME_STATUS *status, const char *str, size_t len, CHARSET_INFO *cs, const Options &opt, uint dec) :Time(thd, status, str, len, cs, opt) { round(dec, time_round_mode_t(opt), &status->warnings); } Time(THD *thd, int *warn, const Longlong_hybrid &nr, const Options &opt, uint dec) :Time(thd, warn, nr, opt) { /* Decimal digit truncation is needed here in case if nr was out of the supported TIME range, so "this" was set to '838:59:59.999999'. We always do truncation (not rounding) here, independently from "opt". */ trunc(dec); } Time(THD *thd, int *warn, double nr, const Options &opt, uint dec) :Time(thd, warn, nr, opt) { round(dec, time_round_mode_t(opt), warn); } Time(THD *thd, int *warn, const my_decimal *d, const Options &opt, uint dec) :Time(thd, warn, d, opt) { round(dec, time_round_mode_t(opt), warn); } static date_conv_mode_t default_flags_for_get_date() { return TIME_TIME_ONLY | TIME_INVALID_DATES; } static date_conv_mode_t comparison_flags_for_get_date() { return TIME_TIME_ONLY | TIME_INVALID_DATES | TIME_FUZZY_DATES; } bool is_valid_time() const { DBUG_ASSERT(is_valid_value_slow()); return time_type == MYSQL_TIMESTAMP_TIME; } const MYSQL_TIME *get_mysql_time() const { DBUG_ASSERT(is_valid_time_slow()); return this; } bool copy_to_mysql_time(MYSQL_TIME *ltime) const { if (time_type == MYSQL_TIMESTAMP_NONE) { ltime->time_type= MYSQL_TIMESTAMP_NONE; return true; } DBUG_ASSERT(is_valid_time_slow()); *ltime= *this; return false; } int cmp(const Time *other) const { DBUG_ASSERT(is_valid_time_slow()); DBUG_ASSERT(other->is_valid_time_slow()); longlong p0= to_packed(); longlong p1= other->to_packed(); if (p0 < p1) return -1; if (p0 > p1) return 1; return 0; } longlong to_seconds_abs() const { DBUG_ASSERT(is_valid_time_slow()); return hour * 3600L + minute * 60 + second; } longlong to_seconds() const { return neg ? -to_seconds_abs() : to_seconds_abs(); } bool to_bool() const { return is_valid_time() && (TIME_to_ulonglong_time(this) != 0 || second_part != 0); } longlong to_longlong() const { if (!is_valid_time()) return 0; ulonglong v= TIME_to_ulonglong_time(this); return neg ? -(longlong) v : (longlong) v; } double to_double() const { return !is_valid_time() ? 0 : Temporal::to_double(neg, TIME_to_ulonglong_time(this), second_part); } bool to_native(Native *to, uint decimals) const; String *to_string(String *str, uint dec) const { if (!is_valid_time()) return NULL; str->set_charset(&my_charset_numeric); if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) str->length(my_time_to_str(this, const_cast(str->ptr()), dec)); return str; } my_decimal *to_decimal(my_decimal *to) { return is_valid_time() ? Temporal::to_decimal(to) : bad_to_decimal(to); } longlong to_packed() const { return is_valid_time() ? Temporal::to_packed() : 0; } longlong valid_time_to_packed() const { DBUG_ASSERT(is_valid_time_slow()); return Temporal::to_packed(); } long fraction_remainder(uint dec) const { DBUG_ASSERT(is_valid_time()); return Temporal::fraction_remainder(dec); } Time &trunc(uint dec) { if (is_valid_time()) my_time_trunc(this, dec); DBUG_ASSERT(is_valid_value_slow()); return *this; } Time &ceiling(int *warn) { if (is_valid_time()) { if (neg) my_time_trunc(this, 0); else if (second_part) round_or_set_max(0, warn, 999999999); } DBUG_ASSERT(is_valid_value_slow()); return *this; } Time &ceiling() { int warn= 0; return ceiling(&warn); } Time &floor(int *warn) { if (is_valid_time()) { if (!neg) my_time_trunc(this, 0); else if (second_part) round_or_set_max(0, warn, 999999999); } DBUG_ASSERT(is_valid_value_slow()); return *this; } Time &floor() { int warn= 0; return floor(&warn); } Time &round(uint dec, int *warn) { if (is_valid_time()) round_or_set_max(dec, warn); DBUG_ASSERT(is_valid_value_slow()); return *this; } Time &round(uint dec, time_round_mode_t mode, int *warn) { switch (mode.mode()) { case time_round_mode_t::FRAC_NONE: DBUG_ASSERT(fraction_remainder(dec) == 0); return trunc(dec); case time_round_mode_t::FRAC_TRUNCATE: return trunc(dec); case time_round_mode_t::FRAC_ROUND: return round(dec, warn); } return *this; } Time &round(uint dec, time_round_mode_t mode) { int warn= 0; return round(dec, mode, &warn); } }; /** Class Temporal_with_date is designed to store valid DATE or DATETIME values. See also class Time. 1. Valid value: a. MYSQL_TIMESTAMP_{DATE|DATETIME} - a valid DATE or DATETIME value b. MYSQL_TIMESTAMP_NONE - an undefined value 2. Invalid value (internally only): a. MYSQL_TIMESTAMP_{DATE|DATETIME} - a DATE or DATETIME value, but with MYSQL_TIME members outside of the valid/supported range b. MYSQL_TIMESTAMP_TIME - a TIME value c. MYSQL_TIMESTAMP_ERROR - error Temporarily is allowed to have an invalid value, but only internally, during initialization time. All constructors and modification methods must leave the value as described above (see "Valid value"). Derives from MYSQL_TIME using "protected" inheritance to make sure it is accessed externally only in the valid state. */ class Temporal_with_date: public Temporal { public: class Options: public Temporal::Options { public: Options(date_conv_mode_t fuzzydate, time_round_mode_t mode): Temporal::Options(fuzzydate, mode) {} explicit Options(const Temporal::Options &opt) :Temporal::Options(opt) { } explicit Options(date_mode_t mode) :Temporal::Options(mode) { } }; protected: void check_date_or_invalidate(int *warn, date_conv_mode_t flags); void make_from_item(THD *thd, Item *item, date_mode_t flags); ulong daynr() const { return (ulong) ::calc_daynr((uint) year, (uint) month, (uint) day); } int weekday(bool sunday_first_day_of_week) const { return ::calc_weekday(daynr(), sunday_first_day_of_week); } ulong dayofyear() const { return (ulong) (daynr() - ::calc_daynr(year, 1, 1) + 1); } uint quarter() const { return (month + 2) / 3; } uint week(uint week_behaviour) const { uint year; return calc_week(this, week_behaviour, &year); } uint yearweek(uint week_behaviour) const { uint year; uint week= calc_week(this, week_behaviour, &year); return week + year * 100; } public: Temporal_with_date() { time_type= MYSQL_TIMESTAMP_NONE; } Temporal_with_date(THD *thd, Item *item, date_mode_t fuzzydate) { make_from_item(thd, item, fuzzydate); } Temporal_with_date(int *warn, const Sec6 &nr, date_mode_t flags) { DBUG_ASSERT(bool(flags & TIME_TIME_ONLY) == false); if (nr.to_datetime_or_date(this, warn, date_conv_mode_t(flags))) time_type= MYSQL_TIMESTAMP_NONE; } Temporal_with_date(THD *thd, MYSQL_TIME_STATUS *status, const char *str, size_t len, CHARSET_INFO *cs, date_mode_t flags) { DBUG_ASSERT(bool(flags & TIME_TIME_ONLY) == false); if (str_to_datetime_or_date(thd, status, str, len, cs, flags)) time_type= MYSQL_TIMESTAMP_NONE; } public: bool check_date_with_warn(THD *thd, date_conv_mode_t flags) { return ::check_date_with_warn(thd, this, flags, MYSQL_TIMESTAMP_ERROR); } bool check_date_with_warn(THD *thd) { return ::check_date_with_warn(thd, this, Temporal::sql_mode_for_dates(thd), MYSQL_TIMESTAMP_ERROR); } static date_conv_mode_t comparison_flags_for_get_date() { return TIME_INVALID_DATES | TIME_FUZZY_DATES; } }; /** Class Date is designed to store valid DATE values. All constructors and modification methods leave instances of this class in one of the following valid states: a. MYSQL_TIMESTAMP_DATE - a DATE with all MYSQL_TIME members properly set b. MYSQL_TIMESTAMP_NONE - an undefined value. Other MYSQL_TIMESTAMP_XXX are not possible. MYSQL_TIMESTAMP_DATE with MYSQL_TIME members improperly set is not possible. */ class Date: public Temporal_with_date { bool is_valid_value_slow() const { return time_type == MYSQL_TIMESTAMP_NONE || is_valid_date_slow(); } bool is_valid_date_slow() const { DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_DATE); return !check_datetime_range(this); } public: class Options: public Temporal_with_date::Options { public: explicit Options(date_conv_mode_t fuzzydate) :Temporal_with_date::Options(fuzzydate, TIME_FRAC_TRUNCATE) { } Options(THD *thd, time_round_mode_t mode) :Temporal_with_date::Options(sql_mode_for_dates(thd), mode) { } explicit Options(THD *thd) :Temporal_with_date::Options(sql_mode_for_dates(thd), TIME_FRAC_TRUNCATE) { } explicit Options(date_mode_t fuzzydate) :Temporal_with_date::Options(fuzzydate) { } }; public: Date(Item *item, date_mode_t fuzzydate) :Date(current_thd, item, fuzzydate) { } Date(THD *thd, Item *item, date_mode_t fuzzydate) :Temporal_with_date(thd, item, fuzzydate) { if (time_type == MYSQL_TIMESTAMP_DATETIME) datetime_to_date(this); DBUG_ASSERT(is_valid_value_slow()); } Date(THD *thd, Item *item, date_conv_mode_t fuzzydate) :Date(thd, item, Options(fuzzydate)) { } Date(THD *thd, Item *item) :Temporal_with_date(Date(thd, item, Options(thd, TIME_FRAC_TRUNCATE))) { } Date(Item *item) :Temporal_with_date(Date(current_thd, item)) { } Date(const Temporal_with_date *d) :Temporal_with_date(*d) { datetime_to_date(this); DBUG_ASSERT(is_valid_date_slow()); } explicit Date(const Temporal_hybrid *from) { from->copy_valid_value_to_mysql_time(this); DBUG_ASSERT(is_valid_date_slow()); } bool is_valid_date() const { DBUG_ASSERT(is_valid_value_slow()); return time_type == MYSQL_TIMESTAMP_DATE; } bool check_date(date_conv_mode_t flags, int *warnings) const { DBUG_ASSERT(is_valid_date_slow()); return ::check_date(this, (year || month || day), ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), warnings); } bool check_date(THD *thd, int *warnings) const { return check_date(Temporal::sql_mode_for_dates(thd), warnings); } bool check_date(date_conv_mode_t flags) const { int dummy; /* unused */ return check_date(flags, &dummy); } bool check_date(THD *thd) const { int dummy; return check_date(Temporal::sql_mode_for_dates(thd), &dummy); } const MYSQL_TIME *get_mysql_time() const { DBUG_ASSERT(is_valid_date_slow()); return this; } bool copy_to_mysql_time(MYSQL_TIME *ltime) const { if (time_type == MYSQL_TIMESTAMP_NONE) { ltime->time_type= MYSQL_TIMESTAMP_NONE; return true; } DBUG_ASSERT(is_valid_date_slow()); *ltime= *this; return false; } ulong daynr() const { DBUG_ASSERT(is_valid_date_slow()); return Temporal_with_date::daynr(); } ulong dayofyear() const { DBUG_ASSERT(is_valid_date_slow()); return Temporal_with_date::dayofyear(); } uint quarter() const { DBUG_ASSERT(is_valid_date_slow()); return Temporal_with_date::quarter(); } uint week(uint week_behaviour) const { DBUG_ASSERT(is_valid_date_slow()); return Temporal_with_date::week(week_behaviour); } uint yearweek(uint week_behaviour) const { DBUG_ASSERT(is_valid_date_slow()); return Temporal_with_date::yearweek(week_behaviour); } longlong valid_date_to_packed() const { DBUG_ASSERT(is_valid_date_slow()); return Temporal::to_packed(); } bool to_bool() const { return to_longlong() != 0; } longlong to_longlong() const { return is_valid_date() ? (longlong) TIME_to_ulonglong_date(this) : 0LL; } double to_double() const { return (double) to_longlong(); } String *to_string(String *str) const { if (!is_valid_date()) return NULL; str->set_charset(&my_charset_numeric); if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) str->length(my_date_to_str(this, const_cast(str->ptr()))); return str; } my_decimal *to_decimal(my_decimal *to) { return is_valid_date() ? Temporal::to_decimal(to) : bad_to_decimal(to); } }; /** Class Datetime is designed to store valid DATETIME values. All constructors and modification methods leave instances of this class in one of the following valid states: a. MYSQL_TIMESTAMP_DATETIME - a DATETIME with all members properly set b. MYSQL_TIMESTAMP_NONE - an undefined value. Other MYSQL_TIMESTAMP_XXX are not possible. MYSQL_TIMESTAMP_DATETIME with MYSQL_TIME members improperly set is not possible. */ class Datetime: public Temporal_with_date { bool is_valid_value_slow() const { return time_type == MYSQL_TIMESTAMP_NONE || is_valid_datetime_slow(); } bool is_valid_datetime_slow() const { DBUG_ASSERT(time_type == MYSQL_TIMESTAMP_DATETIME); return !check_datetime_range(this); } bool add_nanoseconds_or_invalidate(THD *thd, int *warn, ulong nsec) { DBUG_ASSERT(is_valid_datetime_slow()); bool rc= Temporal::datetime_add_nanoseconds_or_invalidate(thd, warn, nsec); DBUG_ASSERT(is_valid_value_slow()); return rc; } void date_to_datetime_if_needed() { if (time_type == MYSQL_TIMESTAMP_DATE) date_to_datetime(this); } void make_from_time(THD *thd, int *warn, const MYSQL_TIME *from, date_conv_mode_t flags); void make_from_datetime(THD *thd, int *warn, const MYSQL_TIME *from, date_conv_mode_t flags); bool round_or_invalidate(THD *thd, uint dec, int *warn); bool round_or_invalidate(THD *thd, uint dec, int *warn, ulong nsec) { DBUG_ASSERT(is_valid_datetime_slow()); bool rc= Temporal::datetime_round_or_invalidate(thd, dec, warn, nsec); DBUG_ASSERT(is_valid_value_slow()); return rc; } public: class Options: public Temporal_with_date::Options { public: Options(date_conv_mode_t fuzzydate, time_round_mode_t nanosecond_rounding) :Temporal_with_date::Options(fuzzydate, nanosecond_rounding) { } Options(THD *thd) :Temporal_with_date::Options(sql_mode_for_dates(thd), default_round_mode(thd)) { } Options(THD *thd, time_round_mode_t rounding_mode) :Temporal_with_date::Options(sql_mode_for_dates(thd), rounding_mode) { } Options(date_conv_mode_t fuzzydate, THD *thd) :Temporal_with_date::Options(fuzzydate, default_round_mode(thd)) { } }; class Options_cmp: public Options { public: Options_cmp(THD *thd) :Options(comparison_flags_for_get_date(), thd) { } }; static Datetime zero() { int warn; static Longlong_hybrid nr(0, false); return Datetime(&warn, nr, date_mode_t(0)); } public: Datetime() // NULL value :Temporal_with_date() { } Datetime(THD *thd, Item *item, date_mode_t fuzzydate) :Temporal_with_date(thd, item, fuzzydate) { date_to_datetime_if_needed(); DBUG_ASSERT(is_valid_value_slow()); } Datetime(THD *thd, Item *item) :Temporal_with_date(Datetime(thd, item, Options(thd))) { } Datetime(Item *item) :Datetime(current_thd, item) { } Datetime(THD *thd, int *warn, const MYSQL_TIME *from, date_conv_mode_t flags); Datetime(THD *thd, MYSQL_TIME_STATUS *status, const char *str, size_t len, CHARSET_INFO *cs, const date_mode_t fuzzydate) :Temporal_with_date(thd, status, str, len, cs, fuzzydate) { date_to_datetime_if_needed(); DBUG_ASSERT(is_valid_value_slow()); } protected: Datetime(int *warn, const Sec6 &nr, date_mode_t flags) :Temporal_with_date(warn, nr, flags) { date_to_datetime_if_needed(); DBUG_ASSERT(is_valid_value_slow()); } Datetime(THD *thd, int *warn, const Sec9 &nr, date_mode_t fuzzydate) :Datetime(warn, static_cast(nr), fuzzydate) { if (is_valid_datetime() && time_round_mode_t(fuzzydate) == TIME_FRAC_ROUND) round_or_invalidate(thd, 6, warn, nr.nsec()); DBUG_ASSERT(is_valid_value_slow()); } public: Datetime(int *warn, const Longlong_hybrid &nr, date_mode_t mode) :Datetime(warn, Sec6(nr), mode) { } Datetime(THD *thd, int *warn, double nr, date_mode_t fuzzydate) :Datetime(thd, warn, Sec9(nr), fuzzydate) { } Datetime(THD *thd, int *warn, const my_decimal *d, date_mode_t fuzzydate) :Datetime(thd, warn, Sec9(d), fuzzydate) { } Datetime(THD *thd, const timeval &tv); Datetime(THD *thd, Item *item, date_mode_t fuzzydate, uint dec) :Datetime(thd, item, fuzzydate) { int warn= 0; round(thd, dec, time_round_mode_t(fuzzydate), &warn); } Datetime(THD *thd, MYSQL_TIME_STATUS *status, const char *str, size_t len, CHARSET_INFO *cs, date_mode_t fuzzydate, uint dec) :Datetime(thd, status, str, len, cs, fuzzydate) { round(thd, dec, time_round_mode_t(fuzzydate), &status->warnings); } Datetime(THD *thd, int *warn, double nr, date_mode_t fuzzydate, uint dec) :Datetime(thd, warn, nr, fuzzydate) { round(thd, dec, time_round_mode_t(fuzzydate), warn); } Datetime(THD *thd, int *warn, const my_decimal *d, date_mode_t fuzzydate, uint dec) :Datetime(thd, warn, d, fuzzydate) { round(thd, dec, time_round_mode_t(fuzzydate), warn); } Datetime(THD *thd, int *warn, const MYSQL_TIME *from, date_mode_t fuzzydate, uint dec) :Datetime(thd, warn, from, date_conv_mode_t(fuzzydate) & ~TIME_TIME_ONLY) { round(thd, dec, time_round_mode_t(fuzzydate), warn); } explicit Datetime(const Temporal_hybrid *from) { from->copy_valid_value_to_mysql_time(this); DBUG_ASSERT(is_valid_datetime_slow()); } explicit Datetime(const MYSQL_TIME *from) { *(static_cast(this))= *from; DBUG_ASSERT(is_valid_datetime_slow()); } Datetime(my_time_t unix_time, ulong second_part, const Time_zone* time_zone); bool is_valid_datetime() const { /* Here we quickly check for the type only. If the type is valid, the rest of value must also be valid. */ DBUG_ASSERT(is_valid_value_slow()); return time_type == MYSQL_TIMESTAMP_DATETIME; } bool check_date(date_conv_mode_t flags, int *warnings) const { DBUG_ASSERT(is_valid_datetime_slow()); return ::check_date(this, (year || month || day), ulonglong(flags & TIME_MODE_FOR_XXX_TO_DATE), warnings); } bool check_date(date_conv_mode_t flags) const { int dummy; /* unused */ return check_date(flags, &dummy); } bool check_date(THD *thd) const { return check_date(Temporal::sql_mode_for_dates(thd)); } bool hhmmssff_is_zero() const { DBUG_ASSERT(is_valid_datetime_slow()); return hour == 0 && minute == 0 && second == 0 && second_part == 0; } ulong daynr() const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal_with_date::daynr(); } int weekday(bool sunday_first_day_of_week) const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal_with_date::weekday(sunday_first_day_of_week); } ulong dayofyear() const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal_with_date::dayofyear(); } uint quarter() const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal_with_date::quarter(); } uint week(uint week_behaviour) const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal_with_date::week(week_behaviour); } uint yearweek(uint week_behaviour) const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal_with_date::yearweek(week_behaviour); } longlong hhmmss_to_seconds_abs() const { DBUG_ASSERT(is_valid_datetime_slow()); return hour * 3600L + minute * 60 + second; } longlong hhmmss_to_seconds() const { return neg ? -hhmmss_to_seconds_abs() : hhmmss_to_seconds_abs(); } longlong to_seconds() const { return hhmmss_to_seconds() + (longlong) daynr() * 24L * 3600L; } const MYSQL_TIME *get_mysql_time() const { DBUG_ASSERT(is_valid_datetime_slow()); return this; } bool copy_to_mysql_time(MYSQL_TIME *ltime) const { if (time_type == MYSQL_TIMESTAMP_NONE) { ltime->time_type= MYSQL_TIMESTAMP_NONE; return true; } DBUG_ASSERT(is_valid_datetime_slow()); *ltime= *this; return false; } /** Copy without data loss, with an optional DATETIME to DATE conversion. If the value of the "type" argument is MYSQL_TIMESTAMP_DATE, then "this" must be a datetime with a zero hhmmssff part. */ bool copy_to_mysql_time(MYSQL_TIME *ltime, timestamp_type type) { DBUG_ASSERT(type == MYSQL_TIMESTAMP_DATE || type == MYSQL_TIMESTAMP_DATETIME); if (copy_to_mysql_time(ltime)) return true; DBUG_ASSERT(type != MYSQL_TIMESTAMP_DATE || hhmmssff_is_zero()); ltime->time_type= type; return false; } bool to_bool() const { return is_valid_datetime() && (TIME_to_ulonglong_datetime(this) != 0 || second_part != 0); } longlong to_longlong() const { return is_valid_datetime() ? (longlong) TIME_to_ulonglong_datetime(this) : 0LL; } double to_double() const { return !is_valid_datetime() ? 0 : Temporal::to_double(neg, TIME_to_ulonglong_datetime(this), second_part); } String *to_string(String *str, uint dec) const { if (!is_valid_datetime()) return NULL; str->set_charset(&my_charset_numeric); if (!str->alloc(MAX_DATE_STRING_REP_LENGTH)) str->length(my_datetime_to_str(this, const_cast(str->ptr()), dec)); return str; } my_decimal *to_decimal(my_decimal *to) { return is_valid_datetime() ? Temporal::to_decimal(to) : bad_to_decimal(to); } longlong to_packed() const { return is_valid_datetime() ? Temporal::to_packed() : 0; } longlong valid_datetime_to_packed() const { DBUG_ASSERT(is_valid_datetime_slow()); return Temporal::to_packed(); } long fraction_remainder(uint dec) const { DBUG_ASSERT(is_valid_datetime()); return Temporal::fraction_remainder(dec); } Datetime &trunc(uint dec) { if (is_valid_datetime()) my_datetime_trunc(this, dec); DBUG_ASSERT(is_valid_value_slow()); return *this; } Datetime &ceiling(THD *thd, int *warn) { if (is_valid_datetime() && second_part) round_or_invalidate(thd, 0, warn, 999999999); DBUG_ASSERT(is_valid_value_slow()); return *this; } Datetime &ceiling(THD *thd) { int warn= 0; return ceiling(thd, &warn); } Datetime &round(THD *thd, uint dec, int *warn) { if (is_valid_datetime()) round_or_invalidate(thd, dec, warn); DBUG_ASSERT(is_valid_value_slow()); return *this; } Datetime &round(THD *thd, uint dec, time_round_mode_t mode, int *warn) { switch (mode.mode()) { case time_round_mode_t::FRAC_NONE: DBUG_ASSERT(fraction_remainder(dec) == 0); return trunc(dec); case time_round_mode_t::FRAC_TRUNCATE: return trunc(dec); case time_round_mode_t::FRAC_ROUND: return round(thd, dec, warn); } return *this; } Datetime &round(THD *thd, uint dec, time_round_mode_t mode) { int warn= 0; return round(thd, dec, mode, &warn); } }; /* Datetime to be created from an Item who is known to be of a temporal data type. For temporal data types we don't need nanosecond rounding or truncation, as their precision is limited. */ class Datetime_from_temporal: public Datetime { public: // The constructor DBUG_ASSERTs on a proper Item data type. Datetime_from_temporal(THD *thd, Item *temporal, date_conv_mode_t flags); }; /* Datetime to be created from an Item who is known not to have digits outside of the specified scale. So it's not important which rounding method to use. TRUNCATE should work. Typically, Item is of a temporal data type, but this is not strictly required. */ class Datetime_truncation_not_needed: public Datetime { public: Datetime_truncation_not_needed(THD *thd, Item *item, date_conv_mode_t mode); Datetime_truncation_not_needed(THD *thd, Item *item, date_mode_t mode) :Datetime_truncation_not_needed(thd, item, date_conv_mode_t(mode)) { } }; class Timestamp: protected Timeval { static uint binary_length_to_precision(uint length); protected: void round_or_set_max(uint dec, int *warn); bool add_nanoseconds_usec(uint nanoseconds) { DBUG_ASSERT(nanoseconds <= 1000000000); if (nanoseconds < 500) return false; tv_usec+= (nanoseconds + 500) / 1000; if (tv_usec < 1000000) return false; tv_usec%= 1000000; return true; } public: static date_conv_mode_t sql_mode_for_timestamp(THD *thd); static time_round_mode_t default_round_mode(THD *thd); class DatetimeOptions: public date_mode_t { public: DatetimeOptions(date_conv_mode_t fuzzydate, time_round_mode_t round_mode) :date_mode_t(fuzzydate | round_mode) { } DatetimeOptions(THD *thd) :DatetimeOptions(sql_mode_for_timestamp(thd), default_round_mode(thd)) { } }; public: Timestamp(my_time_t timestamp, ulong sec_part) :Timeval(timestamp, sec_part) { } explicit Timestamp(const timeval &tv) :Timeval(tv) { } explicit Timestamp(const Native &native); Timestamp(THD *thd, const MYSQL_TIME *ltime, uint *error_code); const struct timeval &tv() const { return *this; } int cmp(const Timestamp &other) const { return tv_sec < other.tv_sec ? -1 : tv_sec > other.tv_sec ? +1 : tv_usec < other.tv_usec ? -1 : tv_usec > other.tv_usec ? +1 : 0; } bool to_TIME(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) const; bool to_native(Native *to, uint decimals) const; Datetime to_datetime(THD *thd) const { return Datetime(thd, *this); } long fraction_remainder(uint dec) const { return my_time_fraction_remainder(tv_usec, dec); } Timestamp &trunc(uint dec) { my_timeval_trunc(this, dec); return *this; } Timestamp &round(uint dec, int *warn) { round_or_set_max(dec, warn); return *this; } Timestamp &round(uint dec, time_round_mode_t mode, int *warn) { switch (mode.mode()) { case time_round_mode_t::FRAC_NONE: DBUG_ASSERT(fraction_remainder(dec) == 0); return trunc(dec); case time_round_mode_t::FRAC_TRUNCATE: return trunc(dec); case time_round_mode_t::FRAC_ROUND: return round(dec, warn); } return *this; } Timestamp &round(uint dec, time_round_mode_t mode) { int warn= 0; return round(dec, mode, &warn); } }; /** A helper class to store MariaDB TIMESTAMP values, which can be: - real TIMESTAMP (seconds and microseconds since epoch), or - zero datetime '0000-00-00 00:00:00.000000' */ class Timestamp_or_zero_datetime: protected Timestamp { bool m_is_zero_datetime; public: Timestamp_or_zero_datetime() :Timestamp(0,0), m_is_zero_datetime(true) { } Timestamp_or_zero_datetime(const Native &native) :Timestamp(native.length() ? Timestamp(native) : Timestamp(0,0)), m_is_zero_datetime(native.length() == 0) { } Timestamp_or_zero_datetime(const Timestamp &tm, bool is_zero_datetime) :Timestamp(tm), m_is_zero_datetime(is_zero_datetime) { } Timestamp_or_zero_datetime(THD *thd, const MYSQL_TIME *ltime, uint *err_code); Datetime to_datetime(THD *thd) const { if (is_zero_datetime()) return Datetime::zero(); return Timestamp::to_datetime(thd); } bool to_bool() const { return !m_is_zero_datetime; } bool is_zero_datetime() const { return m_is_zero_datetime; } void trunc(uint decimals) { if (!is_zero_datetime()) Timestamp::trunc(decimals); } int cmp(const Timestamp_or_zero_datetime &other) const { if (is_zero_datetime()) return other.is_zero_datetime() ? 0 : -1; if (other.is_zero_datetime()) return 1; return Timestamp::cmp(other); } bool to_TIME(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) const; /* Convert to native format: - Real timestamps are encoded in the same way how Field_timestamp2 stores values (big endian seconds followed by big endian microseconds) - Zero datetime '0000-00-00 00:00:00.000000' is encoded as empty string. Two native values are binary comparable. */ bool to_native(Native *to, uint decimals) const; }; /** A helper class to store non-null MariaDB TIMESTAMP values in the native binary encoded representation. */ class Timestamp_or_zero_datetime_native: public NativeBuffer { public: Timestamp_or_zero_datetime_native() = default; Timestamp_or_zero_datetime_native(const Timestamp_or_zero_datetime &ts, uint decimals) { if (ts.to_native(this, decimals)) length(0); // safety } int save_in_field(Field *field, uint decimals) const; Datetime to_datetime(THD *thd) const { return is_zero_datetime() ? Datetime::zero() : Datetime(thd, Timestamp(*this).tv()); } bool is_zero_datetime() const { return length() == 0; } }; /** A helper class to store nullable MariaDB TIMESTAMP values in the native binary encoded representation. */ class Timestamp_or_zero_datetime_native_null: public Timestamp_or_zero_datetime_native, public Null_flag { public: // With optional data type conversion Timestamp_or_zero_datetime_native_null(THD *thd, Item *item, bool conv); // Without data type conversion: item is known to be of the TIMESTAMP type Timestamp_or_zero_datetime_native_null(THD *thd, Item *item) :Timestamp_or_zero_datetime_native_null(thd, item, false) { } Datetime to_datetime(THD *thd) const { return is_null() ? Datetime() : Timestamp_or_zero_datetime_native::to_datetime(thd); } void to_TIME(THD *thd, MYSQL_TIME *to) { DBUG_ASSERT(!is_null()); Datetime::Options opt(TIME_CONV_NONE, TIME_FRAC_NONE); Timestamp_or_zero_datetime(*this).to_TIME(thd, to, opt); } bool is_zero_datetime() const { DBUG_ASSERT(!is_null()); return Timestamp_or_zero_datetime_native::is_zero_datetime(); } }; /* Flags for collation aggregation modes, used in TDCollation::agg(): MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value (i.e. constant). MY_COLL_ALLOW_CONV - allow any kind of conversion (combination of the above two) MY_COLL_ALLOW_NUMERIC_CONV - if all items were numbers, convert to @@character_set_connection MY_COLL_DISALLOW_NONE - don't allow return DERIVATION_NONE (e.g. when aggregating for comparison) MY_COLL_CMP_CONV - combination of MY_COLL_ALLOW_CONV and MY_COLL_DISALLOW_NONE */ #define MY_COLL_ALLOW_SUPERSET_CONV 1 #define MY_COLL_ALLOW_COERCIBLE_CONV 2 #define MY_COLL_DISALLOW_NONE 4 #define MY_COLL_ALLOW_NUMERIC_CONV 8 #define MY_COLL_ALLOW_CONV (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV) #define MY_COLL_CMP_CONV (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE) #define MY_REPERTOIRE_NUMERIC MY_REPERTOIRE_ASCII static inline my_repertoire_t operator|(const my_repertoire_t a, const my_repertoire_t b) { return (my_repertoire_t) ((uint) a | (uint) b); } static inline my_repertoire_t &operator|=(my_repertoire_t &a, const my_repertoire_t b) { return a= (my_repertoire_t) ((uint) a | (uint) b); } enum Derivation { DERIVATION_IGNORABLE= 6, DERIVATION_NUMERIC= 5, DERIVATION_COERCIBLE= 4, DERIVATION_SYSCONST= 3, DERIVATION_IMPLICIT= 2, DERIVATION_NONE= 1, DERIVATION_EXPLICIT= 0 }; /** "Declared Type Collation" A combination of collation and its derivation. */ class DTCollation { public: CHARSET_INFO *collation; enum Derivation derivation; my_repertoire_t repertoire; void set_repertoire_from_charset(CHARSET_INFO *cs) { repertoire= cs->state & MY_CS_PUREASCII ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; } DTCollation() { collation= &my_charset_bin; derivation= DERIVATION_NONE; repertoire= MY_REPERTOIRE_UNICODE30; } DTCollation(CHARSET_INFO *collation_arg) { /* This constructor version is used in combination with Field constructors, to pass "CHARSET_INFO" instead of the full DTCollation. Therefore, derivation is set to DERIVATION_IMPLICIT, which is the proper derivation for table fields. We should eventually remove all code pieces that pass "CHARSET_INFO" (e.g. in storage engine sources) and fix to pass the full DTCollation instead. Then, this constructor can be removed. */ collation= collation_arg; derivation= DERIVATION_IMPLICIT; repertoire= my_charset_repertoire(collation_arg); } DTCollation(CHARSET_INFO *collation_arg, Derivation derivation_arg) { collation= collation_arg; derivation= derivation_arg; set_repertoire_from_charset(collation_arg); } DTCollation(CHARSET_INFO *collation_arg, Derivation derivation_arg, my_repertoire_t repertoire_arg) :collation(collation_arg), derivation(derivation_arg), repertoire(repertoire_arg) { } void set(const DTCollation &dt) { *this= dt; } void set(CHARSET_INFO *collation_arg, Derivation derivation_arg) { collation= collation_arg; derivation= derivation_arg; set_repertoire_from_charset(collation_arg); } void set(CHARSET_INFO *collation_arg, Derivation derivation_arg, my_repertoire_t repertoire_arg) { collation= collation_arg; derivation= derivation_arg; repertoire= repertoire_arg; } void set(CHARSET_INFO *collation_arg) { collation= collation_arg; set_repertoire_from_charset(collation_arg); } void set(Derivation derivation_arg) { derivation= derivation_arg; } bool aggregate(const DTCollation &dt, uint flags= 0); bool set(DTCollation &dt1, DTCollation &dt2, uint flags= 0) { set(dt1); return aggregate(dt2, flags); } const char *derivation_name() const { switch(derivation) { case DERIVATION_NUMERIC: return "NUMERIC"; case DERIVATION_IGNORABLE: return "IGNORABLE"; case DERIVATION_COERCIBLE: return "COERCIBLE"; case DERIVATION_IMPLICIT: return "IMPLICIT"; case DERIVATION_SYSCONST: return "SYSCONST"; case DERIVATION_EXPLICIT: return "EXPLICIT"; case DERIVATION_NONE: return "NONE"; default: return "UNKNOWN"; } } int sortcmp(const Binary_string *s, const Binary_string *t) const { return collation->strnncollsp(s->ptr(), s->length(), t->ptr(), t->length()); } }; class DTCollation_numeric: public DTCollation { public: DTCollation_numeric() :DTCollation(charset_info(), DERIVATION_NUMERIC, MY_REPERTOIRE_NUMERIC) { } static const CHARSET_INFO *charset_info() { return &my_charset_numeric; } static const DTCollation & singleton(); }; static inline uint32 char_to_byte_length_safe(size_t char_length_arg, uint32 mbmaxlen_arg) { ulonglong tmp= ((ulonglong) char_length_arg) * mbmaxlen_arg; return tmp > UINT_MAX32 ? (uint32) UINT_MAX32 : static_cast(tmp); } class Type_numeric_attributes { public: static uint count_unsigned(Item **item, uint nitems); static uint32 find_max_char_length(Item **item, uint nitems); static uint32 find_max_octet_length(Item **item, uint nitems); static decimal_digits_t find_max_decimal_int_part(Item **item, uint nitems); static decimal_digits_t find_max_decimals(Item **item, uint nitems); public: /* The maximum value length in characters multiplied by collation->mbmaxlen. Almost always it's the maximum value length in bytes. */ uint32 max_length; decimal_digits_t decimals; bool unsigned_flag; public: Type_numeric_attributes() :max_length(0), decimals(0), unsigned_flag(false) { } Type_numeric_attributes(uint32 max_length_arg, decimal_digits_t decimals_arg, bool unsigned_flag_arg) :max_length(max_length_arg), decimals(decimals_arg), unsigned_flag(unsigned_flag_arg) { } protected: void aggregate_numeric_attributes_real(Item **item, uint nitems); void aggregate_numeric_attributes_decimal(Item **item, uint nitems, bool unsigned_arg); }; class Type_temporal_attributes: public Type_numeric_attributes { public: Type_temporal_attributes(uint32 int_part_length, decimal_digits_t dec, bool unsigned_arg) :Type_numeric_attributes(int_part_length + (dec ? 1 : 0), MY_MIN(dec, (decimal_digits_t) TIME_SECOND_PART_DIGITS), unsigned_arg) { max_length+= decimals; } }; class Type_temporal_attributes_not_fixed_dec: public Type_numeric_attributes { public: Type_temporal_attributes_not_fixed_dec(uint32 int_part_length, decimal_digits_t dec, bool unsigned_flag) :Type_numeric_attributes(int_part_length, dec, unsigned_flag) { if (decimals == NOT_FIXED_DEC) max_length+= TIME_SECOND_PART_DIGITS + 1; else if (decimals) { set_if_smaller(decimals, TIME_SECOND_PART_DIGITS); max_length+= decimals + 1; } } }; /** A class to store type attributes for the standard data types. Does not include attributes for the extended data types such as ENUM, SET, GEOMETRY. */ class Type_std_attributes: public Type_numeric_attributes { public: DTCollation collation; Type_std_attributes() :collation(&my_charset_bin, DERIVATION_COERCIBLE) { } Type_std_attributes(const Type_numeric_attributes &nattr, const DTCollation &dtc) :Type_numeric_attributes(nattr), collation(dtc) { } void set(const Type_std_attributes *other) { *this= *other; } void set(const Type_std_attributes &other) { *this= other; } void set(const Type_numeric_attributes &nattr, const DTCollation &dtc) { *this= Type_std_attributes(nattr, dtc); } uint32 max_char_length() const { return max_length / collation.collation->mbmaxlen; } void fix_length_and_charset(uint32 max_char_length_arg, CHARSET_INFO *cs) { max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen); collation.collation= cs; } void fix_char_length(uint32 max_char_length_arg) { max_length= char_to_byte_length_safe(max_char_length_arg, collation.collation->mbmaxlen); } void fix_attributes_temporal(uint32 int_part_length, decimal_digits_t dec) { *this= Type_std_attributes( Type_temporal_attributes(int_part_length, dec, false), DTCollation_numeric()); } void fix_attributes_date() { fix_attributes_temporal(MAX_DATE_WIDTH, 0); } void fix_attributes_time(decimal_digits_t dec) { fix_attributes_temporal(MIN_TIME_WIDTH, dec); } void fix_attributes_datetime(decimal_digits_t dec) { fix_attributes_temporal(MAX_DATETIME_WIDTH, dec); } void aggregate_attributes_int(Item **items, uint nitems) { collation= DTCollation_numeric(); fix_char_length(find_max_char_length(items, nitems)); unsigned_flag= count_unsigned(items, nitems) > 0; decimals= 0; } void aggregate_attributes_real(Item **items, uint nitems) { collation= DTCollation_numeric(); aggregate_numeric_attributes_real(items, nitems); } void aggregate_attributes_decimal(Item **items, uint nitems, bool unsigned_arg) { collation= DTCollation_numeric(); aggregate_numeric_attributes_decimal(items, nitems, (unsigned_flag= unsigned_arg)); } bool aggregate_attributes_string(const LEX_CSTRING &func_name, Item **item, uint nitems); void aggregate_attributes_temporal(uint int_part_length, Item **item, uint nitems) { fix_attributes_temporal(int_part_length, find_max_decimals(item, nitems)); } bool agg_item_collations(DTCollation &c, const LEX_CSTRING &name, Item **items, uint nitems, uint flags, int item_sep); struct Single_coll_err { const DTCollation& coll; bool first; }; bool agg_item_set_converter(const DTCollation &coll, const LEX_CSTRING &name, Item **args, uint nargs, uint flags, int item_sep, const Single_coll_err *single_item_err= NULL); /* Collect arguments' character sets together. We allow to apply automatic character set conversion in some cases. The conditions when conversion is possible are: - arguments A and B have different charsets - A wins according to coercibility rules (i.e. a column is stronger than a string constant, an explicit COLLATE clause is stronger than a column) - character set of A is either superset for character set of B, or B is a string constant which can be converted into the character set of A without data loss. If all of the above is true, then it's possible to convert B into the character set of A, and then compare according to the collation of A. For functions with more than two arguments: collect(A,B,C) ::= collect(collect(A,B),C) Since this function calls THD::change_item_tree() on the passed Item ** pointers, it is necessary to pass the original Item **'s, not copies. Otherwise their values will not be properly restored (see BUG#20769). If the items are not consecutive (eg. args[2] and args[5]), use the item_sep argument, ie. agg_item_charsets(coll, fname, &args[2], 2, flags, 3) */ bool agg_arg_charsets(DTCollation &c, const LEX_CSTRING &func_name, Item **items, uint nitems, uint flags, int item_sep) { if (agg_item_collations(c, func_name, items, nitems, flags, item_sep)) return true; return agg_item_set_converter(c, func_name, items, nitems, flags, item_sep); } /* Aggregate arguments for string result, e.g: CONCAT(a,b) - convert to @@character_set_connection if all arguments are numbers - allow DERIVATION_NONE */ bool agg_arg_charsets_for_string_result(DTCollation &c, const LEX_CSTRING &func_name, Item **items, uint nitems, int item_sep) { uint flags= MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV | MY_COLL_ALLOW_NUMERIC_CONV; return agg_arg_charsets(c, func_name, items, nitems, flags, item_sep); } /* Aggregate arguments for string result, when some comparison is involved internally, e.g: REPLACE(a,b,c) - convert to @@character_set_connection if all arguments are numbers - disallow DERIVATION_NONE */ bool agg_arg_charsets_for_string_result_with_comparison(DTCollation &c, const LEX_CSTRING &func_name, Item **items, uint nitems, int item_sep) { uint flags= MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV | MY_COLL_ALLOW_NUMERIC_CONV | MY_COLL_DISALLOW_NONE; return agg_arg_charsets(c, func_name, items, nitems, flags, item_sep); } /* Aggregate arguments for comparison, e.g: a=b, a LIKE b, a RLIKE b - don't convert to @@character_set_connection if all arguments are numbers - don't allow DERIVATION_NONE */ bool agg_arg_charsets_for_comparison(DTCollation &c, const LEX_CSTRING &func_name, Item **items, uint nitems, int item_sep) { uint flags= MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV | MY_COLL_DISALLOW_NONE; return agg_arg_charsets(c, func_name, items, nitems, flags, item_sep); } }; class Type_all_attributes: public Type_std_attributes { public: Type_all_attributes() = default; Type_all_attributes(const Type_all_attributes &) = default; virtual ~Type_all_attributes() = default; virtual void set_type_maybe_null(bool maybe_null_arg)= 0; virtual uint32 character_octet_length() const { return max_length; } // Returns total number of decimal digits virtual decimal_digits_t decimal_precision() const= 0; virtual const TYPELIB *get_typelib() const= 0; virtual void set_typelib(const TYPELIB *typelib)= 0; }; class Type_cmp_attributes { public: virtual ~Type_cmp_attributes() = default; virtual CHARSET_INFO *compare_collation() const= 0; }; class Type_cast_attributes { CHARSET_INFO *m_charset; ulonglong m_length; ulonglong m_decimals; bool m_length_specified; bool m_decimals_specified; public: Type_cast_attributes(const char *c_len, const char *c_dec, CHARSET_INFO *cs) :m_charset(cs), m_length(0), m_decimals(0), m_length_specified(false), m_decimals_specified(false) { set_length_and_dec(c_len, c_dec); } Type_cast_attributes(CHARSET_INFO *cs) :m_charset(cs), m_length(0), m_decimals(0), m_length_specified(false), m_decimals_specified(false) { } void set_length_and_dec(const char *c_len, const char *c_dec) { int error; /* We don't have to check for error here as sql_yacc.yy has guaranteed that the values are in range of ulonglong */ if ((m_length_specified= (c_len != NULL))) m_length= (ulonglong) my_strtoll10(c_len, NULL, &error); if ((m_decimals_specified= (c_dec != NULL))) m_decimals= (ulonglong) my_strtoll10(c_dec, NULL, &error); } CHARSET_INFO *charset() const { return m_charset; } bool length_specified() const { return m_length_specified; } bool decimals_specified() const { return m_decimals_specified; } ulonglong length() const { return m_length; } ulonglong decimals() const { return m_decimals; } }; class Name: private LEX_CSTRING { public: Name(const char *str_arg, uint length_arg) { DBUG_ASSERT(length_arg < UINT_MAX32); LEX_CSTRING::str= str_arg; LEX_CSTRING::length= length_arg; } Name(const LEX_CSTRING &lcs) { LEX_CSTRING::str= lcs.str; LEX_CSTRING::length= lcs.length; } const char *ptr() const { return LEX_CSTRING::str; } uint length() const { return (uint) LEX_CSTRING::length; } const LEX_CSTRING &lex_cstring() const { return *this; } bool eq(const LEX_CSTRING &other) const { return !system_charset_info->strnncoll(LEX_CSTRING::str, LEX_CSTRING::length, other.str, other.length); } }; class Bit_addr { /** Byte where the bit is stored inside a record. If the corresponding Field is a NOT NULL field, this member is NULL. */ uchar *m_ptr; /** Offset of the bit inside m_ptr[0], in the range 0..7. */ uchar m_offs; public: Bit_addr() :m_ptr(NULL), m_offs(0) { } Bit_addr(uchar *ptr, uchar offs) :m_ptr(ptr), m_offs(offs) { DBUG_ASSERT(ptr || offs == 0); DBUG_ASSERT(offs < 8); } Bit_addr(bool maybe_null) :m_ptr(maybe_null ? (uchar *) "" : NULL), m_offs(0) { } uchar *ptr() const { return m_ptr; } uchar offs() const { return m_offs; } uchar bit() const { return static_cast(m_ptr ? 1U << m_offs : 0); } void inc() { DBUG_ASSERT(m_ptr); m_ptr+= (m_offs == 7); m_offs= (m_offs + 1) & 7; } }; class Record_addr { uchar *m_ptr; // Position of the field in the record Bit_addr m_null; // Position and offset of the null bit public: Record_addr(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg) :m_ptr(ptr_arg), m_null(null_ptr_arg, null_bit_arg) { } Record_addr(uchar *ptr, const Bit_addr &null) :m_ptr(ptr), m_null(null) { } Record_addr(bool maybe_null) :m_ptr(NULL), m_null(maybe_null) { } uchar *ptr() const { return m_ptr; } const Bit_addr &null() const { return m_null; } uchar *null_ptr() const { return m_null.ptr(); } uchar null_bit() const { return m_null.bit(); } }; class Information_schema_numeric_attributes { enum enum_attr { ATTR_NONE= 0, ATTR_PRECISION= 1, ATTR_SCALE= 2, ATTR_PRECISION_AND_SCALE= (ATTR_PRECISION|ATTR_SCALE) }; uint m_precision; decimal_digits_t m_scale; enum_attr m_available_attributes; public: Information_schema_numeric_attributes() :m_precision(0), m_scale(0), m_available_attributes(ATTR_NONE) { } Information_schema_numeric_attributes(uint precision) :m_precision(precision), m_scale(0), m_available_attributes(ATTR_PRECISION) { } Information_schema_numeric_attributes(uint precision, decimal_digits_t scale) :m_precision(precision), m_scale(scale), m_available_attributes(ATTR_PRECISION_AND_SCALE) { } bool has_precision() const { return m_available_attributes & ATTR_PRECISION; } bool has_scale() const { return m_available_attributes & ATTR_SCALE; } uint precision() const { DBUG_ASSERT(has_precision()); return (uint) m_precision; } decimal_digits_t scale() const { DBUG_ASSERT(has_scale()); return m_scale; } }; class Information_schema_character_attributes { uint32 m_octet_length; uint32 m_char_length; bool m_is_set; public: Information_schema_character_attributes() :m_octet_length(0), m_char_length(0), m_is_set(false) { } Information_schema_character_attributes(uint32 octet_length, uint32 char_length) :m_octet_length(octet_length), m_char_length(char_length), m_is_set(true) { } bool has_octet_length() const { return m_is_set; } bool has_char_length() const { return m_is_set; } uint32 octet_length() const { DBUG_ASSERT(has_octet_length()); return m_octet_length; } uint char_length() const { DBUG_ASSERT(has_char_length()); return m_char_length; } }; enum vers_kind_t { VERS_UNDEFINED= 0, VERS_TIMESTAMP, VERS_TRX_ID }; class Vers_type_handler { protected: Vers_type_handler() = default; public: virtual ~Vers_type_handler() = default; virtual vers_kind_t kind() const { DBUG_ASSERT(0); return VERS_UNDEFINED; } virtual bool check_sys_fields(const LEX_CSTRING &table_name, const Column_definition *row_start, const Column_definition *row_end) const= 0; }; class Vers_type_timestamp: public Vers_type_handler { public: vers_kind_t kind() const override { return VERS_TIMESTAMP; } bool check_sys_fields(const LEX_CSTRING &table_name, const Column_definition *row_start, const Column_definition *row_end) const override; }; extern Vers_type_timestamp vers_type_timestamp; class Vers_type_trx: public Vers_type_handler { public: vers_kind_t kind() const override { return VERS_TRX_ID; } bool check_sys_fields(const LEX_CSTRING &table_name, const Column_definition *row_start, const Column_definition *row_end) const override; }; extern MYSQL_PLUGIN_IMPORT Vers_type_trx vers_type_trx; class Type_handler { Name m_name; protected: String *print_item_value_csstr(THD *thd, Item *item, String *str) const; String *print_item_value_temporal(THD *thd, Item *item, String *str, const Name &type_name, String *buf) const; void make_sort_key_longlong(uchar *to, bool maybe_null, bool null_value, bool unsigned_flag, longlong value) const; void store_sort_key_longlong(uchar *to, bool unsigned_flag, longlong value) const; uint make_packed_sort_key_longlong(uchar *to, bool maybe_null, bool null_value, bool unsigned_flag, longlong value, const SORT_FIELD_ATTR *sort_field) const; bool Item_func_or_sum_illegal_param(const LEX_CSTRING &name) const; bool Item_func_or_sum_illegal_param(const Item_func_or_sum *) const; bool check_null(const Item *item, st_value *value) const; bool Item_send_str(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_tiny(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_short(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_long(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_longlong(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_float(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_double(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_time(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_date(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_timestamp(Item *item, Protocol *protocol, st_value *buf) const; bool Item_send_datetime(Item *item, Protocol *protocol, st_value *buf) const; bool Column_definition_prepare_stage2_legacy(Column_definition *c, enum_field_types type) const; bool Column_definition_prepare_stage2_legacy_num(Column_definition *c, enum_field_types type) const; bool Column_definition_prepare_stage2_legacy_real(Column_definition *c, enum_field_types type) const; public: static const Type_handler *handler_by_name(THD *thd, const LEX_CSTRING &name); static const Type_handler *handler_by_name_or_error(THD *thd, const LEX_CSTRING &name); static const Type_handler *handler_by_log_event_data_type( THD *thd, const Log_event_data_type &type); static const Type_handler *odbc_literal_type_handler(const LEX_CSTRING *str); static const Type_handler *blob_type_handler(uint max_octet_length); static const Type_handler *string_type_handler(uint max_octet_length); static const Type_handler *bit_and_int_mixture_handler(uint max_char_len); static const Type_handler *type_handler_long_or_longlong(uint max_char_len, bool unsigned_flag); /** Return a string type handler for Item If too_big_for_varchar() returns a BLOB variant, according to length. If max_length > 0 create a VARCHAR(n) If max_length == 0 create a CHAR(0) @param item - the Item to get the handler to. */ static const Type_handler *varstring_type_handler(const Item *item); static const Type_handler *blob_type_handler(const Item *item); static const Type_handler *get_handler_by_field_type(enum_field_types type); static const Type_handler *get_handler_by_real_type(enum_field_types type); static const Type_collection * type_collection_for_aggregation(const Type_handler *h1, const Type_handler *h2); virtual const Type_collection *type_collection() const; static const Type_handler *aggregate_for_result_traditional(const Type_handler *h1, const Type_handler *h2); virtual Schema *schema() const; static void partition_field_type_not_allowed(const LEX_CSTRING &field_name); static bool partition_field_check_result_type(Item *item, Item_result expected_type); static const Name & version_mysql56(); static const Name & version_mariadb53(); void set_name(Name n) { DBUG_ASSERT(!m_name.ptr()); m_name= n; } const Name name() const { return m_name; } virtual const Name version() const; virtual const Name &default_value() const= 0; virtual uint32 flags() const { return 0; } virtual ulong KEY_pack_flags(uint column_nr) const { return 0; } bool is_unsigned() const { return flags() & UNSIGNED_FLAG; } virtual enum_field_types field_type() const= 0; virtual enum_field_types real_field_type() const { return field_type(); } /** Type code which is used for merging of traditional data types for result (for UNION and for hybrid functions such as COALESCE). Mapping can be done both ways: old->new, new->old, depending on the particular data type implementation: - type_handler_var_string (MySQL-4.1 old VARCHAR) is converted to new VARCHAR before merging. field_type_merge_rules[][] returns new VARCHAR. - type_handler_newdate is converted to old DATE before merging. field_type_merge_rules[][] returns NEWDATE. - Temporal type_handler_xxx2 (new MySQL-5.6 types) are converted to corresponding old type codes before merging (e.g. TIME2->TIME). field_type_merge_rules[][] returns old type codes (e.g. TIME). Then old types codes are supposed to convert to new type codes somehow, but they do not. So UNION and COALESCE create old columns. This is a bug and should be fixed eventually. */ virtual enum_field_types traditional_merge_field_type() const { DBUG_ASSERT(is_traditional_scalar_type()); return field_type(); } virtual enum_field_types type_code_for_protocol() const { return field_type(); } virtual protocol_send_type_t protocol_send_type() const= 0; virtual bool Item_append_extended_type_info(Send_field_extended_metadata *to, const Item *item) const { return false; } virtual Item_result result_type() const= 0; virtual Item_result cmp_type() const= 0; virtual enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const= 0; virtual enum_mysql_timestamp_type mysql_timestamp_type() const { return MYSQL_TIMESTAMP_ERROR; } /* Return true if the native format is fully implemented for a data type: - Field_xxx::val_native() - Item_xxx::val_native() for all classes supporting this data type - Type_handler_xxx::cmp_native() */ virtual bool is_val_native_ready() const { return false; } /* If operations such as: UPDATE t1 SET binary_string_field=this_type_field; should store this_type_field->val_native() rather than this_type_field->val_str(). */ virtual bool convert_to_binary_using_val_native() const { return false; } virtual bool is_timestamp_type() const { return false; } virtual bool is_order_clause_position_type() const { return false; } virtual bool is_limit_clause_valid_type() const { return false; } /* Returns true if this data type supports a hack that WHERE notnull_column IS NULL finds zero values, e.g.: WHERE date_notnull_column IS NULL -> WHERE date_notnull_column = '0000-00-00' */ virtual bool cond_notnull_field_isnull_to_field_eq_zero() const { return false; } /** Check whether a field type can be partially indexed by a key. @param type field type @retval true Type can have a prefixed key @retval false Type can not have a prefixed key */ virtual bool type_can_have_key_part() const { return false; } virtual bool type_can_have_auto_increment_attribute() const { return false; } virtual uint max_octet_length() const { return 0; } /** Prepared statement long data: Check whether this parameter data type is compatible with long data. Used to detect whether a long data stream has been supplied to a incompatible data type. */ virtual bool is_param_long_data_type() const { return false; } /* The base type handler "this" is derived from. "This" inherits aggregation rules from the base type handler. */ virtual const Type_handler *type_handler_base() const { return NULL; } const Type_handler *type_handler_base_or_self() const { const Type_handler *res= type_handler_base(); return res ? res : this; } virtual const Type_handler *type_handler_for_comparison() const= 0; virtual const Type_handler *type_handler_for_native_format() const { return this; } virtual const Type_handler *type_handler_for_item_field() const { return this; } virtual const Type_handler *type_handler_for_tmp_table(const Item *) const { return this; } virtual const Type_handler *type_handler_for_union(const Item *) const { return this; } virtual const Type_handler *cast_to_int_type_handler() const { return this; } virtual const Type_handler *type_handler_unsigned() const { return this; } virtual const Type_handler *type_handler_signed() const { return this; } virtual bool partition_field_check(const LEX_CSTRING &field_name, Item *) const { partition_field_type_not_allowed(field_name); return true; } virtual bool partition_field_append_value(String *str, Item *item_expr, CHARSET_INFO *field_cs, partition_value_print_mode_t mode) const; virtual int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const= 0; virtual CHARSET_INFO *charset_for_protocol(const Item *item) const; virtual const Type_handler* type_handler_adjusted_to_max_octet_length(uint max_octet_length, CHARSET_INFO *cs) const { return this; } virtual bool adjust_spparam_type(Spvar_definition *def, Item *from) const { return false; } Type_handler() : m_name(0,0) {} virtual ~Type_handler() = default; /** Determines MariaDB traditional scalar data types that always present in the server. */ bool is_traditional_scalar_type() const; virtual bool is_scalar_type() const { return true; } virtual bool can_return_int() const { return true; } virtual bool can_return_decimal() const { return true; } virtual bool can_return_real() const { return true; } virtual bool can_return_str() const { return true; } virtual bool can_return_text() const { return true; } virtual bool can_return_date() const { return true; } virtual bool can_return_time() const { return true; } virtual bool can_return_extract_source(interval_type type) const; virtual bool is_bool_type() const { return false; } virtual bool is_general_purpose_string_type() const { return false; } virtual decimal_digits_t Item_time_precision(THD *thd, Item *item) const; virtual decimal_digits_t Item_datetime_precision(THD *thd, Item *item) const; virtual decimal_digits_t Item_decimal_scale(const Item *item) const; virtual decimal_digits_t Item_decimal_precision(const Item *item) const= 0; /* Returns how many digits a divisor adds into a division result. See Item::divisor_precision_increment() in item.h for more comments. */ virtual decimal_digits_t Item_divisor_precision_increment(const Item *) const; /** Makes a temporary table Field to handle numeric aggregate functions, e.g. SUM(DISTINCT expr), AVG(DISTINCT expr), etc. */ virtual Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const; /** Makes a temporary table Field to handle RBR replication type conversion. @param TABLE - The conversion table the field is going to be added to. It's used to access to table->in_use->mem_root, to create the new field on the table memory root, as well as to increment statistics in table->share (e.g. table->s->blob_count). @param metadata - Metadata from the binary log. @param target - The field in the target table on the slave. Note, the data types of "target" and of "this" are not necessarily always the same, in general case it's possible that: this->field_type() != target->field_type() and/or this->real_type( ) != target->real_type() This method decodes metadata according to this->real_type() and creates a new field also according to this->real_type(). In some cases it lurks into "target", to get some extra information, e.g.: - unsigned_flag for numeric fields - charset() for string fields - typelib and field_length for SET and ENUM - geom_type and srid for GEOMETRY This information is not available in the binary log, so we assume that these fields are the same on the master and on the slave. */ virtual Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const= 0; virtual void show_binlog_type(const Conv_source &src, const Field &dst, String *str) const; virtual uint32 max_display_length_for_field(const Conv_source &src) const= 0; /* Performs the final data type validation for a UNION element, after the regular "aggregation for result" was done. */ virtual bool union_element_finalize(Item_type_holder* item) const { return false; } virtual Log_event_data_type user_var_log_event_data_type(uint charset_nr) const { return Log_event_data_type({NULL,0}/*data type name*/, result_type(), charset_nr, is_unsigned()); } virtual uint Column_definition_gis_options_image(uchar *buff, const Column_definition &def) const { return 0; } virtual bool Column_definition_data_type_info_image(Binary_string *to, const Column_definition &def) const; // Check if the implicit default value is Ok in the current sql_mode virtual bool validate_implicit_default_value(THD *thd, const Column_definition &def) const; // Automatic upgrade, e.g. for ALTER TABLE t1 FORCE virtual void Column_definition_implicit_upgrade(Column_definition *c) const { } // Validate CHECK constraint after the parser virtual bool Column_definition_validate_check_constraint(THD *thd, Column_definition *c) const; // Set attributes in the parser virtual bool Column_definition_set_attributes(THD *thd, Column_definition *def, const Lex_field_type_st &attr, CHARSET_INFO *cs, column_definition_type_t type) const; // Fix attributes after the parser virtual bool Column_definition_fix_attributes(Column_definition *c) const= 0; /* Fix attributes from an existing field. Used for: - ALTER TABLE (for columns that do not change) - DECLARE var TYPE OF t1.col1; (anchored SP variables) */ virtual void Column_definition_reuse_fix_attributes(THD *thd, Column_definition *c, const Field *field) const { } virtual bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const; virtual bool Column_definition_bulk_alter(Column_definition *c, const Column_derived_attributes *derived_attr, const Column_bulk_alter_attributes *bulk_alter_attr) const { return false; } /* This method is called on queries like: CREATE TABLE t2 (a INT) AS SELECT a FROM t1; I.e. column "a" is queried from another table, but its data type is redefined. @param OUT def - The column definition to be redefined @param IN dup - The column definition to take the data type from (i.e. "a INT" in the above example). @param IN file - Table owner handler. If it does not support certain data types, some conversion can be applied. I.g. true BIT to BIT-AS-CHAR. @param IN schema - the owner schema definition, e.g. for the default character set and collation. @retval true - on error @retval false - on success */ virtual bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const; virtual bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const= 0; virtual bool Key_part_spec_init_primary(Key_part_spec *part, const Column_definition &def, const handler *file) const; virtual bool Key_part_spec_init_unique(Key_part_spec *part, const Column_definition &def, const handler *file, bool *has_key_needed) const; virtual bool Key_part_spec_init_multiple(Key_part_spec *part, const Column_definition &def, const handler *file) const; virtual bool Key_part_spec_init_foreign(Key_part_spec *part, const Column_definition &def, const handler *file) const; virtual bool Key_part_spec_init_spatial(Key_part_spec *part, const Column_definition &def) const; virtual bool Key_part_spec_init_ft(Key_part_spec *part, const Column_definition &def) const { return true; // Error } virtual Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const= 0; Field *make_and_init_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE *table) const; virtual Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const { DBUG_ASSERT(0); return NULL; } virtual Field * make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const= 0; virtual void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const; virtual const Type_handler *type_handler_frm_unpack(const uchar *buffer) const { return this; } virtual bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const; /* Create a fixed size key part for a sort key */ virtual void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const= 0; /* create a compact size key part for a sort key */ virtual uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const=0; virtual void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const= 0; virtual bool is_packable() const { return false; } virtual uint32 max_display_length(const Item *item) const= 0; virtual uint32 Item_decimal_notation_int_digits(const Item *item) const { return 0; } virtual uint32 calc_pack_length(uint32 length) const= 0; virtual uint calc_key_length(const Column_definition &def) const; virtual void Item_update_null_value(Item *item) const= 0; virtual bool Item_save_in_value(THD *thd, Item *item, st_value *value) const= 0; virtual void Item_param_setup_conversion(THD *thd, Item_param *) const {} virtual void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const; virtual bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const= 0; virtual bool Item_param_val_native(THD *thd, Item_param *item, Native *to) const; virtual bool Item_send(Item *item, Protocol *p, st_value *buf) const= 0; virtual int Item_save_in_field(Item *item, Field *field, bool no_conversions) const= 0; /** Return a string representation of the Item value. @param thd thread handle @param str string buffer for representation of the value @note If the item has a string result type, the string is escaped according to its character set. @retval NULL on error @retval non-NULL a pointer to a a valid string on success */ virtual String *print_item_value(THD *thd, Item *item, String *str) const= 0; /** Check if WHERE expr=value AND expr=const can be rewritten as: WHERE const=value AND expr=const "this" is the comparison handler that is used by "target". @param target - the predicate expr=value, whose "expr" argument will be replaced to "const". @param target_expr - the target's "expr" which will be replaced to "const". @param target_value - the target's second argument, it will remain unchanged. @param source - the equality predicate expr=const (or expr<=>const) that can be used to rewrite the "target" part (under certain conditions, see the code). @param source_expr - the source's "expr". It should be exactly equal to the target's "expr" to make condition rewrite possible. @param source_const - the source's "const" argument, it will be inserted into "target" instead of "expr". */ virtual bool can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const= 0; /* @brief Check if an IN subquery allows materialization or not @param inner expression on the inner side of the IN subquery outer expression on the outer side of the IN subquery is_in_predicate SET to true if IN subquery was converted from an IN predicate or we are checking if materialization strategy can be used for an IN predicate */ virtual bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool is_in_predicate) const= 0; /** Make a simple constant replacement item for a constant "src", so the new item can futher be used for comparison with "cmp", e.g.: src = cmp -> replacement = cmp "this" is the type handler that is used to compare "src" and "cmp". @param thd - current thread, for mem_root @param src - The item that we want to replace. It's a const item, but it can be complex enough to calculate on every row. @param cmp - The src's comparand. @retval - a pointer to the created replacement Item @retval - NULL, if could not create a replacement (e.g. on EOM). NULL is also returned for ROWs, because instead of replacing a Item_row to a new Item_row, Type_handler_row just replaces its elements. */ virtual Item *make_const_item_for_comparison(THD *thd, Item *src, const Item *cmp) const= 0; virtual Item_cache *Item_get_cache(THD *thd, const Item *item) const= 0; virtual Item *make_constructor_item(THD *thd, List *args) const { return NULL; } /** A builder for literals with data type name prefix, e.g.: TIME'00:00:00', DATE'2001-01-01', TIMESTAMP'2001-01-01 00:00:00'. @param thd The current thread @param str Character literal @param length Length of str @param cs Character set of the string @param send_error Whether to generate an error on failure @retval A pointer to a new Item on success NULL on error (wrong literal value, EOM) */ virtual Item_literal *create_literal_item(THD *thd, const char *str, size_t length, CHARSET_INFO *cs, bool send_error) const { MY_ASSERT_UNREACHABLE(); return nullptr; } Item_literal *create_literal_item(THD *thd, const String *str, bool send_error) const { return create_literal_item(thd, str->ptr(), str->length(), str->charset(), send_error); } virtual Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const { MY_ASSERT_UNREACHABLE(); return nullptr; } virtual Item_copy *create_item_copy(THD *thd, Item *item) const; virtual int cmp_native(const Native &a, const Native &b) const { MY_ASSERT_UNREACHABLE(); return 0; } virtual bool set_comparator_func(THD *thd, Arg_comparator *cmp) const= 0; virtual bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const { return false; } virtual bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const= 0; virtual bool Item_bool_rowready_func2_fix_length_and_dec(THD *thd, Item_bool_rowready_func2 *func) const; virtual bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const= 0; virtual bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const; virtual bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const= 0; virtual bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const= 0; virtual bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const= 0; virtual bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const= 0; virtual bool Item_val_native_with_conversion(THD *thd, Item *item, Native *to) const { return true; } virtual bool Item_val_native_with_conversion_result(THD *thd, Item *item, Native *to) const { return true; } virtual bool Item_val_bool(Item *item) const= 0; virtual void Item_get_date(THD *thd, Item *item, Temporal::Warn *buff, MYSQL_TIME *ltime, date_mode_t fuzzydate) const= 0; bool Item_get_date_with_warn(THD *thd, Item *item, MYSQL_TIME *ltime, date_mode_t fuzzydate) const; virtual longlong Item_val_int_signed_typecast(Item *item) const= 0; virtual longlong Item_val_int_unsigned_typecast(Item *item) const= 0; virtual String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const= 0; virtual String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const= 0; virtual double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const= 0; virtual longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const= 0; virtual my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const= 0; virtual void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t fuzzydate) const= 0; bool Item_func_hybrid_field_type_get_date_with_warn(THD *thd, Item_func_hybrid_field_type *, MYSQL_TIME *, date_mode_t) const; virtual String *Item_func_min_max_val_str(Item_func_min_max *, String *) const= 0; virtual double Item_func_min_max_val_real(Item_func_min_max *) const= 0; virtual longlong Item_func_min_max_val_int(Item_func_min_max *) const= 0; virtual my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const= 0; virtual bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *, date_mode_t fuzzydate) const= 0; virtual bool Item_func_between_fix_length_and_dec(Item_func_between *func) const= 0; virtual longlong Item_func_between_val_int(Item_func_between *func) const= 0; virtual cmp_item * make_cmp_item(THD *thd, CHARSET_INFO *cs) const= 0; virtual in_vector * make_in_vector(THD *thd, const Item_func_in *func, uint nargs) const= 0; virtual bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) const= 0; virtual bool Item_func_round_fix_length_and_dec(Item_func_round *round) const= 0; virtual bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *func) const= 0; virtual bool Item_func_abs_fix_length_and_dec(Item_func_abs *func) const= 0; virtual bool Item_func_neg_fix_length_and_dec(Item_func_neg *func) const= 0; virtual bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) const; virtual bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const; virtual bool Item_double_typecast_fix_length_and_dec(Item_double_typecast *item) const; virtual bool Item_float_typecast_fix_length_and_dec(Item_float_typecast *item) const; virtual bool Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *item) const; virtual bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *item) const; virtual bool Item_time_typecast_fix_length_and_dec(Item_time_typecast *item) const; virtual bool Item_date_typecast_fix_length_and_dec(Item_date_typecast *item) const; virtual bool Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *item) const; virtual bool Item_func_plus_fix_length_and_dec(Item_func_plus *func) const= 0; virtual bool Item_func_minus_fix_length_and_dec(Item_func_minus *func) const= 0; virtual bool Item_func_mul_fix_length_and_dec(Item_func_mul *func) const= 0; virtual bool Item_func_div_fix_length_and_dec(Item_func_div *func) const= 0; virtual bool Item_func_mod_fix_length_and_dec(Item_func_mod *func) const= 0; virtual const Vers_type_handler *vers() const { return NULL; } }; /* Special handler for ROW */ class Type_handler_row: public Type_handler { public: virtual ~Type_handler_row() = default; const Name &default_value() const override; bool validate_implicit_default_value(THD *, const Column_definition &) const override { MY_ASSERT_UNREACHABLE(); return true; } const Type_collection *type_collection() const override; bool is_scalar_type() const override { return false; } bool can_return_int() const override { return false; } bool can_return_decimal() const override { return false; } bool can_return_real() const override { return false; } bool can_return_str() const override { return false; } bool can_return_text() const override { return false; } bool can_return_date() const override { return false; } bool can_return_time() const override { return false; } enum_field_types field_type() const override { MY_ASSERT_UNREACHABLE(); return MYSQL_TYPE_NULL; }; protocol_send_type_t protocol_send_type() const override { MY_ASSERT_UNREACHABLE(); return PROTOCOL_SEND_STRING; } Item_result result_type() const override { return ROW_RESULT; } Item_result cmp_type() const override { return ROW_RESULT; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *) const override { MY_ASSERT_UNREACHABLE(); return DYN_COL_NULL; } const Type_handler *type_handler_for_comparison() const override; int stored_field_cmp_to_item(THD *, Field *, Item *) const override { MY_ASSERT_UNREACHABLE(); return 0; } bool subquery_type_allows_materialization(const Item *, const Item *, bool) const override { MY_ASSERT_UNREACHABLE(); return false; } Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } Field *make_conversion_table_field(MEM_ROOT *, TABLE *, uint, const Field *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } bool Column_definition_fix_attributes(Column_definition *) const override { return false; } void Column_definition_reuse_fix_attributes(THD *, Column_definition *, const Field *) const override { MY_ASSERT_UNREACHABLE(); } bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_redefine_stage1(Column_definition *, const Column_definition *, const handler *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Column_definition_prepare_stage2(Column_definition *, handler *, ulonglong) const override { return false; } Field *make_table_field(MEM_ROOT *, const LEX_CSTRING *, const Record_addr &, const Type_all_attributes &, TABLE_SHARE *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override { MY_ASSERT_UNREACHABLE(); } uint make_packed_sort_key_part(uchar *, Item *, const SORT_FIELD_ATTR *, String *) const override { MY_ASSERT_UNREACHABLE(); return 0; } void sort_length(THD *, const Type_std_attributes *, SORT_FIELD_ATTR *) const override { MY_ASSERT_UNREACHABLE(); } uint32 max_display_length(const Item *) const override { MY_ASSERT_UNREACHABLE(); return 0; } uint32 max_display_length_for_field(const Conv_source &) const override { MY_ASSERT_UNREACHABLE(); return 0; } uint32 calc_pack_length(uint32) const override { MY_ASSERT_UNREACHABLE(); return 0; } bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; decimal_digits_t Item_decimal_precision(const Item *) const override { MY_ASSERT_UNREACHABLE(); return DECIMAL_MAX_PRECISION; } bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; bool Item_send(Item *, Protocol *, st_value *) const override { MY_ASSERT_UNREACHABLE(); return true; } void Item_update_null_value(Item *item) const override; int Item_save_in_field(Item *, Field *, bool) const override { MY_ASSERT_UNREACHABLE(); return 1; } String *print_item_value(THD *thd, Item *item, String *str) const override; bool can_change_cond_ref_to_const(Item_bool_func2 *, Item *, Item *, Item_bool_func2 *, Item *, Item *) const override { MY_ASSERT_UNREACHABLE(); return false; } Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; Item_copy *create_item_copy(THD *, Item *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_val_bool(Item *item) const override { MY_ASSERT_UNREACHABLE(); return false; } void Item_get_date(THD *, Item *, Temporal::Warn *, MYSQL_TIME *ltime, date_mode_t) const override { MY_ASSERT_UNREACHABLE(); set_zero_time(ltime, MYSQL_TIMESTAMP_NONE); } longlong Item_val_int_signed_typecast(Item *) const override { MY_ASSERT_UNREACHABLE(); return 0; } longlong Item_val_int_unsigned_typecast(Item *) const override { MY_ASSERT_UNREACHABLE(); return 0; } String *Item_func_hex_val_str_ascii(Item_func_hex *, String *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override { MY_ASSERT_UNREACHABLE(); return 0.0; } longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override { MY_ASSERT_UNREACHABLE(); return 0; } my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *ltime, date_mode_t) const override { MY_ASSERT_UNREACHABLE(); set_zero_time(ltime, MYSQL_TIMESTAMP_NONE); } String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } double Item_func_min_max_val_real(Item_func_min_max *) const override { MY_ASSERT_UNREACHABLE(); return 0; } longlong Item_func_min_max_val_int(Item_func_min_max *) const override { MY_ASSERT_UNREACHABLE(); return 0; } my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override { MY_ASSERT_UNREACHABLE(); return nullptr; } bool Item_func_min_max_get_date(THD *, Item_func_min_max*, MYSQL_TIME *, date_mode_t) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_func_between_fix_length_and_dec(Item_func_between *) const override { MY_ASSERT_UNREACHABLE(); return true; } longlong Item_func_between_val_int(Item_func_between *func) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *thd, const Item_func_in *f, uint nargs) const override; bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_func_signed_fix_length_and_dec(Item_func_signed *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_double_typecast_fix_length_and_dec(Item_double_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_float_typecast_fix_length_and_dec(Item_float_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_time_typecast_fix_length_and_dec(Item_time_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_date_typecast_fix_length_and_dec(Item_date_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *) const override { MY_ASSERT_UNREACHABLE(); return true; } bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; }; /* A common parent class for numeric data type handlers */ class Type_handler_numeric: public Type_handler { public: const Name &default_value() const override; String *print_item_value(THD *thd, Item *item, String *str) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; double Item_func_min_max_val_real(Item_func_min_max *) const override; longlong Item_func_min_max_val_int(Item_func_min_max *) const override; my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override; bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *, date_mode_t fuzzydate) const override; virtual ~Type_handler_numeric() = default; bool can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const override; bool Item_func_between_fix_length_and_dec(Item_func_between *func) const override; bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const override; }; /*** Abstract classes for every XXX_RESULT */ class Type_handler_real_result: public Type_handler_numeric { public: Item_result result_type() const override{ return REAL_RESULT; } Item_result cmp_type() const override { return REAL_RESULT; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_DOUBLE; } virtual ~Type_handler_real_result() = default; const Type_handler *type_handler_for_comparison() const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; void Column_definition_reuse_fix_attributes(THD *thd, Column_definition *c, const Field *field) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override; int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override; bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool is_in_predicate) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override; bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; decimal_digits_t Item_decimal_precision(const Item *item) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; void Item_update_null_value(Item *item) const override; int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) const override; bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const override; bool Item_val_bool(Item *item) const override; void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; longlong Item_val_int_signed_typecast(Item *item) const override; longlong Item_val_int_unsigned_typecast(Item *item) const override; String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const override; double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override; longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override; my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t fuzzydate) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; }; class Type_handler_decimal_result: public Type_handler_numeric { public: protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_STRING; } Item_result result_type() const override { return DECIMAL_RESULT; } Item_result cmp_type() const override { return DECIMAL_RESULT; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *) const override { return DYN_COL_DECIMAL; } virtual ~Type_handler_decimal_result() = default; const Type_handler *type_handler_for_comparison() const override; int stored_field_cmp_to_item(THD *, Field *field, Item *item) const override { VDec item_val(item); return item_val.is_null() ? 0 : my_decimal(field).cmp(item_val.ptr()); } bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool is_in_predicate) const override; Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override; void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override; uint32 max_display_length(const Item *item) const override; uint32 Item_decimal_notation_int_digits(const Item *item) const override; Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override { VDec va(a), vb(b); return va.ptr() && vb.ptr() && !va.cmp(vb); } decimal_digits_t Item_decimal_precision(const Item *item) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_str(item, protocol, buf); } void Item_update_null_value(Item *item) const override; int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override; bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; bool Item_sum_variance_fix_length_and_dec(Item_sum_variance*) const override; bool Item_val_bool(Item *item) const override { return VDec(item).to_bool(); } void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; longlong Item_val_int_signed_typecast(Item *item) const override; longlong Item_val_int_unsigned_typecast(Item *item) const override { return VDec(item).to_longlong(true); } String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override; longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override; my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t fuzzydate) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; }; class Type_limits_int { private: uint32 m_precision; uint32 m_char_length; public: Type_limits_int(uint32 prec, uint32 nchars) :m_precision(prec), m_char_length(nchars) { } uint32 precision() const { return m_precision; } uint32 char_length() const { return m_char_length; } }; /* UNDIGNED TINYINT: 0..255 digits=3 nchars=3 SIGNED TINYINT : -128..127 digits=3 nchars=4 */ class Type_limits_uint8: public Type_limits_int { public: Type_limits_uint8() :Type_limits_int(MAX_TINYINT_WIDTH, MAX_TINYINT_WIDTH) { } }; class Type_limits_sint8: public Type_limits_int { public: Type_limits_sint8() :Type_limits_int(MAX_TINYINT_WIDTH, MAX_TINYINT_WIDTH + 1) { } }; /* UNDIGNED SMALLINT: 0..65535 digits=5 nchars=5 SIGNED SMALLINT: -32768..32767 digits=5 nchars=6 */ class Type_limits_uint16: public Type_limits_int { public: Type_limits_uint16() :Type_limits_int(MAX_SMALLINT_WIDTH, MAX_SMALLINT_WIDTH) { } }; class Type_limits_sint16: public Type_limits_int { public: Type_limits_sint16() :Type_limits_int(MAX_SMALLINT_WIDTH, MAX_SMALLINT_WIDTH + 1) { } }; /* MEDIUMINT UNSIGNED 0 .. 16777215 digits=8 char_length=8 MEDIUMINT SIGNED: -8388608 .. 8388607 digits=7 char_length=8 */ class Type_limits_uint24: public Type_limits_int { public: Type_limits_uint24() :Type_limits_int(MAX_MEDIUMINT_WIDTH, MAX_MEDIUMINT_WIDTH) { } }; class Type_limits_sint24: public Type_limits_int { public: Type_limits_sint24() :Type_limits_int(MAX_MEDIUMINT_WIDTH - 1, MAX_MEDIUMINT_WIDTH) { } }; /* UNSIGNED INT: 0..4294967295 digits=10 nchars=10 SIGNED INT: -2147483648..2147483647 digits=10 nchars=11 */ class Type_limits_uint32: public Type_limits_int { public: Type_limits_uint32() :Type_limits_int(MAX_INT_WIDTH, MAX_INT_WIDTH) { } }; class Type_limits_sint32: public Type_limits_int { public: Type_limits_sint32() :Type_limits_int(MAX_INT_WIDTH, MAX_INT_WIDTH + 1) { } }; /* UNSIGNED BIGINT: 0..18446744073709551615 digits=20 nchars=20 SIGNED BIGINT: -9223372036854775808..9223372036854775807 digits=19 nchars=20 */ class Type_limits_uint64: public Type_limits_int { public: Type_limits_uint64(): Type_limits_int(MAX_BIGINT_WIDTH, MAX_BIGINT_WIDTH) { } }; class Type_limits_sint64: public Type_limits_int { public: Type_limits_sint64() :Type_limits_int(MAX_BIGINT_WIDTH - 1, MAX_BIGINT_WIDTH) { } }; class Type_handler_int_result: public Type_handler_numeric { public: Item_result result_type() const override { return INT_RESULT; } Item_result cmp_type() const override { return INT_RESULT; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return attr->unsigned_flag ? DYN_COL_UINT : DYN_COL_INT; } bool is_order_clause_position_type() const override { return true; } bool is_limit_clause_valid_type() const override { return true; } virtual ~Type_handler_int_result() = default; const Type_handler *type_handler_for_comparison() const override; int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override; bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool is_in_predicate) const override; Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override; bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; decimal_digits_t Item_decimal_precision(const Item *item) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; void Item_update_null_value(Item *item) const override; int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; bool Item_val_bool(Item *item) const override; void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; longlong Item_val_int_signed_typecast(Item *item) const override; longlong Item_val_int_unsigned_typecast(Item *item) const override; String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override; longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override; my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t fuzzydate) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; const Vers_type_handler *vers() const override { return &vers_type_trx; } }; class Type_handler_general_purpose_int: public Type_handler_int_result { public: bool type_can_have_auto_increment_attribute() const override { return true; } virtual const Type_limits_int *type_limits_int() const= 0; uint32 max_display_length(const Item *item) const override { return type_limits_int()->char_length(); } uint32 Item_decimal_notation_int_digits(const Item *item) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; bool partition_field_check(const LEX_CSTRING &, Item *item_expr) const override { return partition_field_check_result_type(item_expr, INT_RESULT); } bool partition_field_append_value(String *str, Item *item_expr, CHARSET_INFO *field_cs, partition_value_print_mode_t) const override; const Vers_type_handler *vers() const override { return &vers_type_trx; } }; class Type_handler_temporal_result: public Type_handler { protected: decimal_digits_t Item_decimal_scale_with_seconds(const Item *item) const; decimal_digits_t Item_divisor_precision_increment_with_seconds(const Item *) const; public: Item_result result_type() const override { return STRING_RESULT; } Item_result cmp_type() const override { return TIME_RESULT; } virtual ~Type_handler_temporal_result() = default; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; uint32 max_display_length(const Item *item) const override; uint32 Item_decimal_notation_int_digits(const Item *item) const override; bool can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const override; bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool is_in_predicate) const override; bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override; bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *)const override; bool Item_val_bool(Item *item) const override; void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; longlong Item_val_int_signed_typecast(Item *item) const override; longlong Item_val_int_unsigned_typecast(Item *item) const override; String *Item_func_hex_val_str_ascii(Item_func_hex *, String *)const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override; longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override; my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t) const override; bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *, date_mode_t) const override; bool Item_func_between_fix_length_and_dec(Item_func_between *)const override; bool Item_func_in_fix_comparator_compatible_types(THD *, Item_func_in *) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; const Vers_type_handler *vers() const override; }; class Type_handler_string_result: public Type_handler { decimal_digits_t Item_temporal_precision(THD *thd, Item *item, bool is_time) const; public: const Name &default_value() const override; protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_STRING; } Item_result result_type() const override { return STRING_RESULT; } Item_result cmp_type() const override { return STRING_RESULT; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *) const override { return DYN_COL_STRING; } CHARSET_INFO *charset_for_protocol(const Item *item) const override; virtual ~Type_handler_string_result() = default; const Type_handler *type_handler_for_comparison() const override; int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override; const Type_handler * type_handler_adjusted_to_max_octet_length(uint max_octet_length, CHARSET_INFO *cs) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override; bool is_packable() const override { return true; } bool union_element_finalize(Item_type_holder* item) const override; uint calc_key_length(const Column_definition &def) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; uint32 max_display_length(const Item *item) const override; /* The next method returns 309 for long stringified doubles in scientific notation, e.g. FORMAT('1e308', 2). */ uint32 Item_decimal_notation_int_digits(const Item *item) const override { return 309; } bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; decimal_digits_t Item_time_precision(THD *thd, Item *item) const override { return Item_temporal_precision(thd, item, true); } decimal_digits_t Item_datetime_precision(THD *thd, Item *item) const override { return Item_temporal_precision(thd, item, false); } decimal_digits_t Item_decimal_precision(const Item *item) const override; void Item_update_null_value(Item *item) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; void Item_param_setup_conversion(THD *thd, Item_param *) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_str(item, protocol, buf); } int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; String *print_item_value(THD *thd, Item *item, String *str) const override { return print_item_value_csstr(thd, item, str); } bool can_change_cond_ref_to_const(Item_bool_func2 *target, Item *target_expr, Item *target_value, Item_bool_func2 *source, Item *source_expr, Item *source_const) const override; bool subquery_type_allows_materialization(const Item *inner, const Item *outer, bool is_in_predicate) const override; Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) const override; bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const override; bool Item_val_bool(Item *item) const override; void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; longlong Item_val_int_signed_typecast(Item *item) const override; longlong Item_val_int_unsigned_typecast(Item *item) const override; String *Item_func_hex_val_str_ascii(Item_func_hex *item, String *str) const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override; longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override; my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t fuzzydate) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; double Item_func_min_max_val_real(Item_func_min_max *) const override; longlong Item_func_min_max_val_int(Item_func_min_max *) const override; my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override; bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *, date_mode_t fuzzydate) const override; bool Item_func_between_fix_length_and_dec(Item_func_between *func) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; bool Item_func_in_fix_comparator_compatible_types(THD *thd, Item_func_in *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_func_plus_fix_length_and_dec(Item_func_plus *) const override; bool Item_func_minus_fix_length_and_dec(Item_func_minus *) const override; bool Item_func_mul_fix_length_and_dec(Item_func_mul *) const override; bool Item_func_div_fix_length_and_dec(Item_func_div *) const override; bool Item_func_mod_fix_length_and_dec(Item_func_mod *) const override; const Vers_type_handler *vers() const override; }; class Type_handler_general_purpose_string: public Type_handler_string_result { public: bool is_general_purpose_string_type() const override { return true; } bool Column_definition_bulk_alter(Column_definition *c, const Column_derived_attributes *derived_attr, const Column_bulk_alter_attributes *bulk_alter_attr) const override; }; /*** Instantiable classes for every MYSQL_TYPE_XXX There are no Type_handler_xxx for the following types: - MYSQL_TYPE_VAR_STRING (old VARCHAR) - mapped to MYSQL_TYPE_VARSTRING - MYSQL_TYPE_ENUM - mapped to MYSQL_TYPE_VARSTRING - MYSQL_TYPE_SET: - mapped to MYSQL_TYPE_VARSTRING because the functionality that currently uses Type_handler (e.g. hybrid type functions) does not need to distinguish between these types and VARCHAR. For example: CREATE TABLE t2 AS SELECT COALESCE(enum_column) FROM t1; creates a VARCHAR column. There most likely be Type_handler_enum and Type_handler_set later, when the Type_handler infrastructure gets used in more pieces of the code. */ class Type_handler_tiny: public Type_handler_general_purpose_int { public: virtual ~Type_handler_tiny() = default; enum_field_types field_type() const override { return MYSQL_TYPE_TINY; } const Type_handler *type_handler_unsigned() const override; const Type_handler *type_handler_signed() const override; protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_TINY; } const Type_limits_int *type_limits_int() const override; uint32 calc_pack_length(uint32 length) const override { return 1; } uint32 max_display_length_for_field(const Conv_source &src) const override { return 4; } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_tiny(item, protocol, buf); } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_TINY); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; class Type_handler_utiny: public Type_handler_tiny { public: uint flags() const override { return UNSIGNED_FLAG; } const Type_limits_int *type_limits_int() const override; }; class Type_handler_short: public Type_handler_general_purpose_int { public: virtual ~Type_handler_short() = default; enum_field_types field_type() const override { return MYSQL_TYPE_SHORT; } const Type_handler *type_handler_unsigned() const override; const Type_handler *type_handler_signed() const override; protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_SHORT; } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_short(item, protocol, buf); } const Type_limits_int *type_limits_int() const override; uint32 max_display_length_for_field(const Conv_source &src) const override { return 6; } uint32 calc_pack_length(uint32 length) const override{ return 2; } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_SHORT); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; class Type_handler_ushort: public Type_handler_short { public: uint flags() const override { return UNSIGNED_FLAG; } const Type_limits_int *type_limits_int() const override; }; class Type_handler_long: public Type_handler_general_purpose_int { public: virtual ~Type_handler_long() = default; enum_field_types field_type() const override { return MYSQL_TYPE_LONG; } const Type_handler *type_handler_unsigned() const override; const Type_handler *type_handler_signed() const override; protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_LONG; } const Type_limits_int *type_limits_int() const override; uint32 max_display_length_for_field(const Conv_source &src) const override { return 11; } uint32 calc_pack_length(uint32 length) const override { return 4; } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_long(item, protocol, buf); } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_LONG); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; /* The expression of this type reports itself as signed, however it's known not to return negative values. Items of this data type count only digits in Item::max_length, without adding +1 for the sign. This allows expressions of this type convert nicely to VARCHAR and DECIMAL. For example, YEAR(now()) is: - VARCHAR(4) in a string context - DECIMAL(4,0) in a decimal context - but INT(5) in an integer context */ class Type_handler_long_ge0: public Type_handler_long { public: decimal_digits_t Item_decimal_precision(const Item *item) const override; bool Item_func_signed_fix_length_and_dec(Item_func_signed *item) const override; bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *item) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *func) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_ulong: public Type_handler_long { public: uint flags() const override { return UNSIGNED_FLAG; } const Type_limits_int *type_limits_int() const override; }; class Type_handler_bool: public Type_handler_long { public: bool is_bool_type() const override { return true; } const Type_handler *type_handler_unsigned() const override; const Type_handler *type_handler_signed() const override; void Item_update_null_value(Item *item) const override; bool Item_sum_hybrid_fix_length_and_dec(Item_sum_hybrid *) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; }; class Type_handler_longlong: public Type_handler_general_purpose_int { public: virtual ~Type_handler_longlong() = default; enum_field_types field_type() const override{ return MYSQL_TYPE_LONGLONG; } const Type_handler *type_handler_unsigned() const override; const Type_handler *type_handler_signed() const override; protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_LONGLONG; } const Type_limits_int *type_limits_int() const override; uint32 max_display_length_for_field(const Conv_source &src) const override { return 20; } uint32 calc_pack_length(uint32 length) const override { return 8; } Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_longlong(item, protocol, buf); } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_LONGLONG); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; class Type_handler_ulonglong: public Type_handler_longlong { public: uint flags() const override { return UNSIGNED_FLAG; } const Type_limits_int *type_limits_int() const override; }; class Type_handler_vers_trx_id: public Type_handler_ulonglong { public: virtual ~Type_handler_vers_trx_id() = default; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; }; class Type_handler_int24: public Type_handler_general_purpose_int { public: virtual ~Type_handler_int24() = default; enum_field_types field_type() const override { return MYSQL_TYPE_INT24; } const Type_handler *type_handler_unsigned() const override; const Type_handler *type_handler_signed() const override; protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_LONG; } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_long(item, protocol, buf); } const Type_limits_int *type_limits_int() const override; uint32 max_display_length_for_field(const Conv_source &src) const override { return 9; } uint32 calc_pack_length(uint32 length) const override { return 3; } Field *make_conversion_table_field(MEM_ROOT *mem_root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_INT24); } Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_uint24: public Type_handler_int24 { public: uint flags() const override { return UNSIGNED_FLAG; } const Type_limits_int *type_limits_int() const override; }; class Type_handler_year: public Type_handler_int_result { public: virtual ~Type_handler_year() = default; enum_field_types field_type() const override { return MYSQL_TYPE_YEAR; } uint flags() const override { return UNSIGNED_FLAG; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_SHORT; } uint32 max_display_length(const Item *item) const override; uint32 Item_decimal_notation_int_digits(const Item *item) const override { return 4; }; uint32 max_display_length_for_field(const Conv_source &src) const override { return 4; } uint32 calc_pack_length(uint32 length) const override { return 1; } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_short(item, protocol, buf); } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; void Column_definition_reuse_fix_attributes(THD *thd, Column_definition *c, const Field *field) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_YEAR); } Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *)const override; void Item_get_date(THD *thd, Item *item, Temporal::Warn *warn, MYSQL_TIME *ltime, date_mode_t fuzzydate) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *item, Temporal::Warn *, MYSQL_TIME *to, date_mode_t fuzzydate) const override; const Vers_type_handler *vers() const override { return NULL; } }; class Type_handler_bit: public Type_handler_int_result { public: virtual ~Type_handler_bit() = default; enum_field_types field_type() const override { return MYSQL_TYPE_BIT; } uint flags() const override { return UNSIGNED_FLAG; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_STRING; } uint32 max_display_length(const Item *item) const override; uint32 Item_decimal_notation_int_digits(const Item *item) const override; static uint32 Bit_decimal_notation_int_digits_by_nbits(uint nbits); uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override { return length / 8; } uint calc_key_length(const Column_definition &def) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_str(item, protocol, buf); } String *print_item_value(THD *thd, Item *item, String *str) const override { return print_item_value_csstr(thd, item, str); } void show_binlog_type(const Conv_source &src, const Field &, String *str) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_float: public Type_handler_real_result { public: virtual ~Type_handler_float() = default; enum_field_types field_type() const override { return MYSQL_TYPE_FLOAT; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_FLOAT; } bool type_can_have_auto_increment_attribute() const override { return true; } uint32 max_display_length(const Item *item) const override { return 25; } uint32 max_display_length_for_field(const Conv_source &src) const override { return 12; } uint32 Item_decimal_notation_int_digits(const Item *item) const override { return 39; } uint32 calc_pack_length(uint32 length) const override { return sizeof(float); } Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_float(item, protocol, buf); } Field *make_num_distinct_aggregator_field(MEM_ROOT *, const Item *) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_real(c, MYSQL_TYPE_FLOAT); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; }; class Type_handler_double: public Type_handler_real_result { public: virtual ~Type_handler_double() = default; enum_field_types field_type() const override { return MYSQL_TYPE_DOUBLE; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_DOUBLE; } bool type_can_have_auto_increment_attribute() const override { return true; } uint32 max_display_length(const Item *item) const override { return 53; } uint32 Item_decimal_notation_int_digits(const Item *item) const override { return 309; } uint32 max_display_length_for_field(const Conv_source &src) const override { return 22; } uint32 calc_pack_length(uint32 length) const override { return sizeof(double); } Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_double(item, protocol, buf); } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_real(c, MYSQL_TYPE_DOUBLE); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; }; class Type_handler_time_common: public Type_handler_temporal_result { public: virtual ~Type_handler_time_common() = default; const Name &default_value() const override; enum_field_types field_type() const override { return MYSQL_TYPE_TIME; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_TIME; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_TIME; } enum_mysql_timestamp_type mysql_timestamp_type() const override { return MYSQL_TIMESTAMP_TIME; } bool is_val_native_ready() const override { return true; } const Type_handler *type_handler_for_native_format() const override; int cmp_native(const Native &a, const Native &b) const override; bool Item_val_native_with_conversion(THD *thd, Item *, Native *to) const override; bool Item_val_native_with_conversion_result(THD *thd, Item *, Native *to) const override; bool Item_param_val_native(THD *thd, Item_param *item, Native *to) const override; bool partition_field_check(const LEX_CSTRING &, Item *item_expr) const override { return partition_field_check_result_type(item_expr, STRING_RESULT); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Item_literal *create_literal_item(THD *thd, const char *str, size_t length, CHARSET_INFO *cs, bool send_error) const override; Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; decimal_digits_t Item_decimal_scale(const Item *item) const override { return Item_decimal_scale_with_seconds(item); } decimal_digits_t Item_decimal_precision(const Item *item) const override; decimal_digits_t Item_divisor_precision_increment(const Item *item) const override { return Item_divisor_precision_increment_with_seconds(item); } const Type_handler *type_handler_for_comparison() const override; int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override; void Column_definition_implicit_upgrade(Column_definition *c) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_time(item, protocol, buf); } void Item_update_null_value(Item *item) const override; int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; String *print_item_value(THD *thd, Item *item, String *str) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; longlong Item_val_int_unsigned_typecast(Item *item) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; String *Item_func_hybrid_field_type_val_str(Item_func_hybrid_field_type *, String *) const override; double Item_func_hybrid_field_type_val_real(Item_func_hybrid_field_type *) const override; longlong Item_func_hybrid_field_type_val_int(Item_func_hybrid_field_type *) const override; my_decimal *Item_func_hybrid_field_type_val_decimal( Item_func_hybrid_field_type *, my_decimal *) const override; void Item_func_hybrid_field_type_get_date(THD *, Item_func_hybrid_field_type *, Temporal::Warn *, MYSQL_TIME *, date_mode_t fuzzydate) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; double Item_func_min_max_val_real(Item_func_min_max *) const override; longlong Item_func_min_max_val_int(Item_func_min_max *) const override; my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override; bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *, date_mode_t fuzzydate) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; class Type_handler_time: public Type_handler_time_common { /* number of bytes to store TIME(N) */ static uint m_hires_bytes[MAX_DATETIME_PRECISION+1]; public: static uint hires_bytes(uint dec) { return m_hires_bytes[dec]; } virtual ~Type_handler_time() = default; const Name version() const override { return version_mariadb53(); } uint32 max_display_length_for_field(const Conv_source &src) const override { return MIN_TIME_WIDTH; } uint32 calc_pack_length(uint32 length) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_TIME); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_time2: public Type_handler_time_common { public: virtual ~Type_handler_time2() = default; const Name version() const override { return version_mysql56(); } enum_field_types real_field_type() const override { return MYSQL_TYPE_TIME2; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_TIME2); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_temporal_with_date: public Type_handler_temporal_result { public: virtual ~Type_handler_temporal_with_date() = default; Item_literal *create_literal_item(THD *thd, const char *str, size_t length, CHARSET_INFO *cs, bool send_error) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; int stored_field_cmp_to_item(THD *thd, Field *field, Item *item) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_date(item, protocol, buf); } void Item_update_null_value(Item *item) const override; int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; Item *make_const_item_for_comparison(THD *, Item *src, const Item *cmp) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *, const Item_func_in *, uint nargs) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; }; class Type_handler_date_common: public Type_handler_temporal_with_date { public: virtual ~Type_handler_date_common() = default; const Name &default_value() const override; const Type_handler *type_handler_for_comparison() const override; enum_field_types field_type() const override { return MYSQL_TYPE_DATE; } uint32 max_display_length_for_field(const Conv_source &src) const override { return 3; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_DATE; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_DATE; } enum_mysql_timestamp_type mysql_timestamp_type() const override { return MYSQL_TIMESTAMP_DATE; } bool cond_notnull_field_isnull_to_field_eq_zero() const override { return true; } bool partition_field_check(const LEX_CSTRING &, Item *item_expr) const override { return partition_field_check_result_type(item_expr, STRING_RESULT); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Item_literal *create_literal_item(THD *thd, const char *str, size_t length, CHARSET_INFO *cs, bool send_error) const override; Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool validate_implicit_default_value(THD *thd, const Column_definition &def) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; decimal_digits_t Item_decimal_precision(const Item *item) const override; String *print_item_value(THD *thd, Item *item, String *str) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; double Item_func_min_max_val_real(Item_func_min_max *) const override; longlong Item_func_min_max_val_int(Item_func_min_max *) const override; my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; bool Item_func_min_max_fix_attributes(THD *thd, Item_func_min_max *func, Item **items, uint nitems) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; class Type_handler_date: public Type_handler_date_common { public: virtual ~Type_handler_date() = default; uint32 calc_pack_length(uint32 length) const override { return 4; } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_DATE); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_newdate: public Type_handler_date_common { public: virtual ~Type_handler_newdate() = default; enum_field_types real_field_type() const override { return MYSQL_TYPE_NEWDATE; } uint32 calc_pack_length(uint32 length) const override { return 3; } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_NEWDATE); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_datetime_common: public Type_handler_temporal_with_date { public: virtual ~Type_handler_datetime_common() = default; const Name &default_value() const override; const Type_handler *type_handler_for_comparison() const override; enum_field_types field_type() const override { return MYSQL_TYPE_DATETIME; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_DATETIME; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_DATETIME; } enum_mysql_timestamp_type mysql_timestamp_type() const override { return MYSQL_TIMESTAMP_DATETIME; } bool cond_notnull_field_isnull_to_field_eq_zero() const override { return true; } bool partition_field_check(const LEX_CSTRING &, Item *item_expr) const override { return partition_field_check_result_type(item_expr, STRING_RESULT); } Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; bool validate_implicit_default_value(THD *thd, const Column_definition &def) const override; void Column_definition_implicit_upgrade(Column_definition *c) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override; decimal_digits_t Item_decimal_scale(const Item *item) const override { return Item_decimal_scale_with_seconds(item); } decimal_digits_t Item_decimal_precision(const Item *item) const override; decimal_digits_t Item_divisor_precision_increment(const Item *item) const override { return Item_divisor_precision_increment_with_seconds(item); } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_datetime(item, protocol, buf); } String *print_item_value(THD *thd, Item *item, String *str) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; double Item_func_min_max_val_real(Item_func_min_max *) const override; longlong Item_func_min_max_val_int(Item_func_min_max *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; }; class Type_handler_datetime: public Type_handler_datetime_common { /* number of bytes to store DATETIME(N) */ static uint m_hires_bytes[MAX_DATETIME_PRECISION + 1]; public: static uint hires_bytes(uint dec) { return m_hires_bytes[dec]; } virtual ~Type_handler_datetime() = default; const Name version() const override { return version_mariadb53(); } uint32 max_display_length_for_field(const Conv_source &src) const override { return MAX_DATETIME_WIDTH; } uint32 calc_pack_length(uint32 length) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_DATETIME); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_datetime2: public Type_handler_datetime_common { public: virtual ~Type_handler_datetime2() = default; const Name version() const override { return version_mysql56(); } enum_field_types real_field_type() const override { return MYSQL_TYPE_DATETIME2; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_DATETIME2); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_timestamp_common: public Type_handler_temporal_with_date { protected: bool TIME_to_native(THD *, const MYSQL_TIME *from, Native *to, uint dec) const; public: virtual ~Type_handler_timestamp_common() = default; const Name &default_value() const override; const Type_handler *type_handler_for_comparison() const override; const Type_handler *type_handler_for_native_format() const override; enum_field_types field_type() const override { return MYSQL_TYPE_TIMESTAMP; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_DATETIME; } protocol_send_type_t protocol_send_type() const override { return PROTOCOL_SEND_DATETIME; } enum_mysql_timestamp_type mysql_timestamp_type() const override { return MYSQL_TIMESTAMP_DATETIME; } bool is_val_native_ready() const override { return true; } bool is_timestamp_type() const override { return true; } void Column_definition_implicit_upgrade(Column_definition *c) const override; bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override; bool Item_eq_value(THD *thd, const Type_cmp_attributes *attr, Item *a, Item *b) const override; bool Item_val_native_with_conversion(THD *thd, Item *, Native *to) const override; bool Item_val_native_with_conversion_result(THD *thd, Item *, Native *to) const override; bool Item_param_val_native(THD *thd, Item_param *item, Native *to) const override; int cmp_native(const Native &a, const Native &b) const override; longlong Item_func_between_val_int(Item_func_between *func) const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; cmp_item *make_cmp_item(THD *thd, CHARSET_INFO *cs) const override; in_vector *make_in_vector(THD *thd, const Item_func_in *f, uint nargs) const override; void make_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; uint make_packed_sort_key_part(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, String *tmp) const override; void sort_length(THD *thd, const Type_std_attributes *item, SORT_FIELD_ATTR *attr) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; decimal_digits_t Item_decimal_scale(const Item *item) const override { return Item_decimal_scale_with_seconds(item); } decimal_digits_t Item_decimal_precision(const Item *item) const override; decimal_digits_t Item_divisor_precision_increment(const Item *item) const override { return Item_divisor_precision_increment_with_seconds(item); } bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override { return Item_send_timestamp(item, protocol, buf); } int Item_save_in_field(Item *item, Field *field, bool no_conversions) const override; String *print_item_value(THD *thd, Item *item, String *str) const override; Item_cache *Item_get_cache(THD *thd, const Item *item) const override; Item_copy *create_item_copy(THD *thd, Item *item) const override; String *Item_func_min_max_val_str(Item_func_min_max *, String *) const override; double Item_func_min_max_val_real(Item_func_min_max *) const override; longlong Item_func_min_max_val_int(Item_func_min_max *) const override; my_decimal *Item_func_min_max_val_decimal(Item_func_min_max *, my_decimal *) const override; bool set_comparator_func(THD *thd, Arg_comparator *cmp) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; bool Item_func_min_max_get_date(THD *thd, Item_func_min_max*, MYSQL_TIME *, date_mode_t fuzzydate) const override; }; class Type_handler_timestamp: public Type_handler_timestamp_common { /* number of bytes to store second_part part of the TIMESTAMP(N) */ static uint m_sec_part_bytes[MAX_DATETIME_PRECISION + 1]; public: static uint sec_part_bytes(uint dec) { return m_sec_part_bytes[dec]; } virtual ~Type_handler_timestamp() = default; const Name version() const override { return version_mariadb53(); } uint32 max_display_length_for_field(const Conv_source &src) const override { return MAX_DATETIME_WIDTH; } uint32 calc_pack_length(uint32 length) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_TIMESTAMP); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_timestamp2: public Type_handler_timestamp_common { public: virtual ~Type_handler_timestamp2() = default; const Name version() const override { return version_mysql56(); } enum_field_types real_field_type() const override { return MYSQL_TYPE_TIMESTAMP2; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_TIMESTAMP2); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_olddecimal: public Type_handler_decimal_result { public: virtual ~Type_handler_olddecimal() = default; enum_field_types field_type() const override { return MYSQL_TYPE_DECIMAL; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override { return length; } const Type_handler *type_handler_for_tmp_table(const Item *item) const override; const Type_handler *type_handler_for_union(const Item *item) const override; void show_binlog_type(const Conv_source &src, const Field &, String *str) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_DECIMAL); } Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_newdecimal: public Type_handler_decimal_result { public: virtual ~Type_handler_newdecimal() = default; enum_field_types field_type() const override { return MYSQL_TYPE_NEWDECIMAL; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; uint calc_key_length(const Column_definition &def) const override; void show_binlog_type(const Conv_source &src, const Field &, String *str) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_null: public Type_handler_general_purpose_string { public: virtual ~Type_handler_null() = default; enum_field_types field_type() const override { return MYSQL_TYPE_NULL; } enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { return DYN_COL_NULL; } const Type_handler *type_handler_for_comparison() const override; const Type_handler *type_handler_for_tmp_table(const Item *item) const override; const Type_handler *type_handler_for_union(const Item *) const override; uint32 max_display_length(const Item *item) const override { return 0; } uint32 max_display_length_for_field(const Conv_source &src) const override { return 0; } uint32 calc_pack_length(uint32 length) const override { return 0; } bool Item_const_eq(const Item_const *a, const Item_const *b, bool binary_cmp) const override; bool Item_save_in_value(THD *thd, Item *item, st_value *value) const override; bool Item_send(Item *item, Protocol *protocol, st_value *buf) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool union_element_finalize(Item_type_holder* item) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy(c, MYSQL_TYPE_NULL); } void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; class Type_handler_longstr: public Type_handler_general_purpose_string { public: bool type_can_have_key_part() const override { return true; } }; class Type_handler_string: public Type_handler_longstr { public: virtual ~Type_handler_string() = default; enum_field_types field_type() const override { return MYSQL_TYPE_STRING; } ulong KEY_pack_flags(uint column_nr) const override { return HA_PACK_KEY; } bool is_param_long_data_type() const override { return true; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override { return length; } const Type_handler *type_handler_for_tmp_table(const Item *item) const override { return varstring_type_handler(item); } bool partition_field_check(const LEX_CSTRING &, Item *item_expr) const override { return partition_field_check_result_type(item_expr, STRING_RESULT); } void show_binlog_type(const Conv_source &src, const Field &dst, String *str) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_set_attributes(THD *thd, Column_definition *def, const Lex_field_type_st &attr, CHARSET_INFO *cs, column_definition_type_t type) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; bool Key_part_spec_init_ft(Key_part_spec *part, const Column_definition &def) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; /* Old varchar */ class Type_handler_var_string: public Type_handler_string { public: virtual ~Type_handler_var_string() = default; enum_field_types field_type() const override { return MYSQL_TYPE_VAR_STRING; } enum_field_types real_field_type() const override { return MYSQL_TYPE_STRING; } enum_field_types traditional_merge_field_type() const override { return MYSQL_TYPE_VARCHAR; } const Type_handler *type_handler_for_tmp_table(const Item *item) const override { return varstring_type_handler(item); } uint32 max_display_length_for_field(const Conv_source &src) const override; void show_binlog_type(const Conv_source &src, const Field &dst, String *str) const override; void Column_definition_implicit_upgrade(Column_definition *c) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override { return Column_definition_prepare_stage2_legacy_num(c, MYSQL_TYPE_STRING); } const Type_handler *type_handler_for_union(const Item *item) const override { return varstring_type_handler(item); } }; class Type_handler_varchar: public Type_handler_longstr { public: virtual ~Type_handler_varchar() = default; enum_field_types field_type() const override { return MYSQL_TYPE_VARCHAR; } ulong KEY_pack_flags(uint column_nr) const override { if (column_nr == 0) return HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; return HA_PACK_KEY; } enum_field_types type_code_for_protocol() const override { return MYSQL_TYPE_VAR_STRING; // Keep things compatible for old clients } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override { return (length + (length < 256 ? 1: 2)); } const Type_handler *type_handler_for_tmp_table(const Item *item) const override { return varstring_type_handler(item); } const Type_handler *type_handler_for_union(const Item *item) const override { return varstring_type_handler(item); } bool is_param_long_data_type() const override { return true; } bool partition_field_check(const LEX_CSTRING &, Item *item_expr) const override { return partition_field_check_result_type(item_expr, STRING_RESULT); } void show_binlog_type(const Conv_source &src, const Field &dst, String *str) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_set_attributes(THD *thd, Column_definition *def, const Lex_field_type_st &attr, CHARSET_INFO *cs, column_definition_type_t type) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; bool Key_part_spec_init_ft(Key_part_spec *part, const Column_definition &def) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; bool adjust_spparam_type(Spvar_definition *def, Item *from) const override; }; class Type_handler_hex_hybrid: public Type_handler_varchar { public: virtual ~Type_handler_hex_hybrid() = default; const Type_handler *cast_to_int_type_handler() const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; }; class Type_handler_varchar_compressed: public Type_handler_varchar { public: enum_field_types real_field_type() const override { return MYSQL_TYPE_VARCHAR_COMPRESSED; } ulong KEY_pack_flags(uint column_nr) const override { MY_ASSERT_UNREACHABLE(); return 0; } uint32 max_display_length_for_field(const Conv_source &src) const override; bool partition_field_check(const LEX_CSTRING &field_name, Item *) const override { partition_field_type_not_allowed(field_name); return true; } void show_binlog_type(const Conv_source &src, const Field &dst, String *str) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; enum_dynamic_column_type dyncol_type(const Type_all_attributes *attr) const override { DBUG_ASSERT(0); return DYN_COL_STRING; } }; class Type_handler_blob_common: public Type_handler_longstr { public: virtual ~Type_handler_blob_common() = default; virtual uint length_bytes() const= 0; ulong KEY_pack_flags(uint column_nr) const override { if (column_nr == 0) return HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; return HA_PACK_KEY; } Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; const Type_handler *type_handler_for_tmp_table(const Item *item) const override { return blob_type_handler(item); } const Type_handler *type_handler_for_union(const Item *item) const override { return blob_type_handler(item); } bool subquery_type_allows_materialization(const Item *, const Item *, bool) const override { return false; // Materialization does not work with BLOB columns } bool is_param_long_data_type() const override { return true; } uint calc_key_length(const Column_definition &def) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; bool Key_part_spec_init_ft(Key_part_spec *part, const Column_definition &def) const override; bool Key_part_spec_init_primary(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_unique(Key_part_spec *part, const Column_definition &def, const handler *file, bool *has_key_needed) const override; bool Key_part_spec_init_multiple(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_foreign(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; void Item_param_setup_conversion(THD *thd, Item_param *) const override; bool partition_field_check(const LEX_CSTRING &field_name, Item *item_expr) const override; Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; const Vers_type_handler *vers() const override; }; class Type_handler_tiny_blob: public Type_handler_blob_common { public: virtual ~Type_handler_tiny_blob() = default; uint length_bytes() const override { return 1; } enum_field_types field_type() const override { return MYSQL_TYPE_TINY_BLOB; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; uint max_octet_length() const override { return UINT_MAX8; } }; class Type_handler_medium_blob: public Type_handler_blob_common { public: virtual ~Type_handler_medium_blob() = default; uint length_bytes() const override { return 3; } enum_field_types field_type() const override { return MYSQL_TYPE_MEDIUM_BLOB; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; uint max_octet_length() const override { return UINT_MAX24; } }; class Type_handler_long_blob: public Type_handler_blob_common { public: virtual ~Type_handler_long_blob() = default; uint length_bytes() const override { return 4; } enum_field_types field_type() const override { return MYSQL_TYPE_LONG_BLOB; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; uint max_octet_length() const override { return UINT_MAX32; } }; class Type_handler_blob: public Type_handler_blob_common { public: virtual ~Type_handler_blob() = default; uint length_bytes() const override { return 2; } enum_field_types field_type() const override { return MYSQL_TYPE_BLOB; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; uint max_octet_length() const override { return UINT_MAX16; } }; class Type_handler_blob_compressed: public Type_handler_blob { public: enum_field_types real_field_type() const override { return MYSQL_TYPE_BLOB_COMPRESSED; } ulong KEY_pack_flags(uint) const override { MY_ASSERT_UNREACHABLE(); return 0; } uint32 max_display_length_for_field(const Conv_source &src) const override; void show_binlog_type(const Conv_source &src, const Field &, String *str) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; enum_dynamic_column_type dyncol_type(const Type_all_attributes *) const override { DBUG_ASSERT(0); return DYN_COL_STRING; } }; class Type_handler_typelib: public Type_handler_general_purpose_string { public: virtual ~Type_handler_typelib() = default; enum_field_types field_type() const override { return MYSQL_TYPE_STRING; } const Type_handler *type_handler_for_item_field() const override; const Type_handler *cast_to_int_type_handler() const override; bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val*) const override; uint32 max_display_length_for_field(const Conv_source &src) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *, Type_all_attributes *atrr, Item **items, uint nitems) const override; void Column_definition_reuse_fix_attributes(THD *thd, Column_definition *c, const Field *field) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_redefine_stage1(Column_definition *def, const Column_definition *dup, const handler *file) const override; void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; const Vers_type_handler *vers() const override { return NULL; } }; class Type_handler_enum: public Type_handler_typelib { public: virtual ~Type_handler_enum() = default; enum_field_types real_field_type() const override { return MYSQL_TYPE_ENUM; } enum_field_types traditional_merge_field_type() const override { return MYSQL_TYPE_ENUM; } uint32 calc_pack_length(uint32 length) const override; uint calc_key_length(const Column_definition &def) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; Field *make_schema_field(MEM_ROOT *root, TABLE *table, const Record_addr &addr, const ST_FIELD_INFO &def) const override; }; class Type_handler_set: public Type_handler_typelib { public: virtual ~Type_handler_set() = default; enum_field_types real_field_type() const override { return MYSQL_TYPE_SET; } enum_field_types traditional_merge_field_type() const override { return MYSQL_TYPE_SET; } uint32 calc_pack_length(uint32 length) const override; uint calc_key_length(const Column_definition &def) const override; void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; }; // A pseudo type handler, mostly for test purposes for now class Type_handler_interval_DDhhmmssff: public Type_handler_long_blob { public: Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; }; class Function_collection { public: virtual ~Function_collection() = default; virtual bool init()= 0; virtual void cleanup()= 0; virtual Create_func *find_native_function_builder(THD *thd, const LEX_CSTRING &name) const= 0; }; class Type_collection { public: virtual ~Type_collection() = default; virtual bool init(Type_handler_data *) { return false; } virtual const Type_handler *aggregate_for_result(const Type_handler *h1, const Type_handler *h2) const= 0; virtual const Type_handler *aggregate_for_comparison(const Type_handler *h1, const Type_handler *h2) const= 0; virtual const Type_handler *aggregate_for_min_max(const Type_handler *h1, const Type_handler *h2) const= 0; virtual const Type_handler *aggregate_for_num_op(const Type_handler *h1, const Type_handler *h2) const= 0; }; /** A handler for hybrid type functions, e.g. COALESCE(), IF(), IFNULL(), NULLIF(), CASE, numeric operators, UNIX_TIMESTAMP(), TIME_TO_SEC(). Makes sure that field_type(), cmp_type() and result_type() are always in sync to each other for hybrid functions. */ class Type_handler_hybrid_field_type { const Type_handler *m_type_handler; bool aggregate_for_min_max(const Type_handler *other); public: Type_handler_hybrid_field_type(); Type_handler_hybrid_field_type(const Type_handler *handler) :m_type_handler(handler) { } Type_handler_hybrid_field_type(const Type_handler_hybrid_field_type *other) :m_type_handler(other->m_type_handler) { } void swap(Type_handler_hybrid_field_type &other) { swap_variables(const Type_handler *, m_type_handler, other.m_type_handler); } const Type_handler *type_handler() const { return m_type_handler; } enum_field_types real_field_type() const { return m_type_handler->real_field_type(); } Item_result cmp_type() const { return m_type_handler->cmp_type(); } enum_mysql_timestamp_type mysql_timestamp_type() const { return m_type_handler->mysql_timestamp_type(); } bool is_timestamp_type() const { return m_type_handler->is_timestamp_type(); } void set_handler(const Type_handler *other) { m_type_handler= other; } const Type_handler *set_handler_by_field_type(enum_field_types type) { return (m_type_handler= Type_handler::get_handler_by_field_type(type)); } const Type_handler *set_handler_by_real_type(enum_field_types type) { return (m_type_handler= Type_handler::get_handler_by_real_type(type)); } bool aggregate_for_comparison(const Type_handler *other); bool aggregate_for_comparison(const LEX_CSTRING &funcname, Item **items, uint nitems, bool treat_int_to_uint_as_decimal); bool aggregate_for_result(const Type_handler *other); bool aggregate_for_result(const LEX_CSTRING &funcname, Item **item, uint nitems, bool treat_bit_as_number); bool aggregate_for_min_max(const LEX_CSTRING &funcname, Item **item, uint nitems); bool aggregate_for_num_op(const class Type_aggregator *aggregator, const Type_handler *h0, const Type_handler *h1); }; class Type_handler_pair { const Type_handler *m_a; const Type_handler *m_b; public: Type_handler_pair(const Type_handler *a, const Type_handler *b) :m_a(a), m_b(b) { } const Type_handler *a() const { return m_a; } const Type_handler *b() const { return m_b; } /* Change both handlers to their parent data type handlers, if available. For example, VARCHAR/JSON -> VARCHAR. @returns The number of handlers changed (0,1 or 2). */ bool to_base() { bool rc= false; const Type_handler *na= m_a->type_handler_base(); const Type_handler *nb= m_b->type_handler_base(); if (na) { m_a= na; rc= true; } if (nb) { m_b= nb; rc= true; } return rc; } }; /* Helper template to simplify creating builtin types with names. Plugin types inherit from Type_handler_xxx types that do not set the name in the constructor, as sql_plugin.cc sets the type name from the plugin name. */ template class Named_type_handler : public TypeHandler { public: Named_type_handler(const char *n) : TypeHandler() { Type_handler::set_name(Name(n, static_cast(strlen(n)))); } }; extern Named_type_handler type_handler_row; extern Named_type_handler type_handler_null; extern Named_type_handler type_handler_float; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_double; extern Named_type_handler type_handler_bit; extern Named_type_handler type_handler_enum; extern Named_type_handler type_handler_set; extern Named_type_handler type_handler_string; extern Named_type_handler type_handler_var_string; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_varchar; extern Named_type_handler type_handler_varchar_compressed; extern Named_type_handler type_handler_hex_hybrid; extern Named_type_handler type_handler_tiny_blob; extern Named_type_handler type_handler_medium_blob; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_long_blob; extern Named_type_handler type_handler_blob; extern Named_type_handler type_handler_blob_compressed; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_bool; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_stiny; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_sshort; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_sint24; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_slong; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_slong_ge0; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_slonglong; extern Named_type_handler type_handler_utiny; extern Named_type_handler type_handler_ushort; extern Named_type_handler type_handler_uint24; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_ulong; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_ulonglong; extern Named_type_handler type_handler_vers_trx_id; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_newdecimal; extern Named_type_handler type_handler_olddecimal; extern Named_type_handler type_handler_year; extern Named_type_handler type_handler_year2; extern Named_type_handler type_handler_newdate; extern Named_type_handler type_handler_date; extern Named_type_handler type_handler_time; extern Named_type_handler type_handler_time2; extern Named_type_handler type_handler_datetime; extern Named_type_handler type_handler_datetime2; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_timestamp; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_timestamp2; extern Type_handler_interval_DDhhmmssff type_handler_interval_DDhhmmssff; class Type_aggregator { bool m_is_commutative; public: class Pair { public: const Type_handler *m_handler1; const Type_handler *m_handler2; const Type_handler *m_result; Pair() = default; Pair(const Type_handler *handler1, const Type_handler *handler2, const Type_handler *result) :m_handler1(handler1), m_handler2(handler2), m_result(result) { } bool eq(const Type_handler *handler1, const Type_handler *handler2) const { return m_handler1 == handler1 && m_handler2 == handler2; } }; static const Type_handler * find_handler_in_array(const Type_aggregator::Pair *pairs, const Type_handler *h1, const Type_handler *h2, bool commutative) { for (const Type_aggregator::Pair *p= pairs; p->m_result; p++) { if (p->eq(h1, h2)) return p->m_result; if (commutative && p->eq(h2, h1)) return p->m_result; } return NULL; } private: Dynamic_array m_array; const Pair* find_pair(const Type_handler *handler1, const Type_handler *handler2) const; public: Type_aggregator(bool is_commutative= false) :m_is_commutative(is_commutative), m_array(PSI_INSTRUMENT_MEM) { } bool add(const Type_handler *handler1, const Type_handler *handler2, const Type_handler *result) { return m_array.append(Pair(handler1, handler2, result)); } const Type_handler *find_handler(const Type_handler *handler1, const Type_handler *handler2) const { const Pair* el= find_pair(handler1, handler2); return el ? el->m_result : NULL; } bool is_commutative() const { return m_is_commutative; } }; class Type_aggregator_commutative: public Type_aggregator { public: Type_aggregator_commutative() :Type_aggregator(true) { } }; class Type_handler_data { public: Type_aggregator_commutative m_type_aggregator_for_result; Type_aggregator_commutative m_type_aggregator_for_comparison; Type_aggregator_commutative m_type_aggregator_for_plus; Type_aggregator_commutative m_type_aggregator_for_mul; Type_aggregator m_type_aggregator_for_minus; Type_aggregator m_type_aggregator_for_div; Type_aggregator m_type_aggregator_for_mod; #ifndef DBUG_OFF // This is used for mtr purposes in debug builds Type_aggregator m_type_aggregator_non_commutative_test; #endif bool init(); }; extern Type_handler_data *type_handler_data; #endif /* SQL_TYPE_H_INCLUDED */ mysql/server/private/wsrep_var.h000064400000010777151027430560013071 0ustar00/* Copyright (C) 2013-2023 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #ifndef WSREP_VAR_H #define WSREP_VAR_H #include #ifdef WITH_WSREP #define WSREP_CLUSTER_NAME "my_wsrep_cluster" #define WSREP_NODE_INCOMING_AUTO "AUTO" #define WSREP_START_POSITION_ZERO "00000000-0000-0000-0000-000000000000:-1" #define WSREP_START_POSITION_ZERO_GTID "00000000-0000-0000-0000-000000000000:-1,0-0-0" // MySQL variables funcs #include "sql_priv.h" #include #include class sys_var; class set_var; class THD; int wsrep_init_vars(); void wsrep_set_wsrep_on(THD *thd); void wsrep_free_status_vars(); #define CHECK_ARGS (sys_var *self, THD* thd, set_var *var) #define UPDATE_ARGS (sys_var *self, THD* thd, enum_var_type type) #define DEFAULT_ARGS (THD* thd, enum_var_type var_type) #define INIT_ARGS (const char* opt) extern bool wsrep_causal_reads_update UPDATE_ARGS; extern bool wsrep_on_check CHECK_ARGS; extern bool wsrep_on_update UPDATE_ARGS; extern bool wsrep_sync_wait_update UPDATE_ARGS; extern bool wsrep_start_position_check CHECK_ARGS; extern bool wsrep_start_position_update UPDATE_ARGS; extern bool wsrep_start_position_init INIT_ARGS; extern bool wsrep_provider_check CHECK_ARGS; extern bool wsrep_provider_update UPDATE_ARGS; extern void wsrep_provider_init INIT_ARGS; extern bool wsrep_provider_options_check CHECK_ARGS; extern bool wsrep_provider_options_update UPDATE_ARGS; extern void wsrep_provider_options_init INIT_ARGS; extern bool wsrep_cluster_address_check CHECK_ARGS; extern bool wsrep_cluster_address_update UPDATE_ARGS; extern void wsrep_cluster_address_init INIT_ARGS; extern bool wsrep_cluster_name_check CHECK_ARGS; extern bool wsrep_cluster_name_update UPDATE_ARGS; extern bool wsrep_node_name_check CHECK_ARGS; extern bool wsrep_node_name_update UPDATE_ARGS; extern bool wsrep_node_address_check CHECK_ARGS; extern bool wsrep_node_address_update UPDATE_ARGS; extern void wsrep_node_address_init INIT_ARGS; extern bool wsrep_sst_method_check CHECK_ARGS; extern bool wsrep_sst_method_update UPDATE_ARGS; extern void wsrep_sst_method_init INIT_ARGS; extern bool wsrep_sst_receive_address_check CHECK_ARGS; extern bool wsrep_sst_receive_address_update UPDATE_ARGS; extern bool wsrep_sst_auth_check CHECK_ARGS; extern bool wsrep_sst_auth_update UPDATE_ARGS; extern bool wsrep_sst_donor_check CHECK_ARGS; extern bool wsrep_sst_donor_update UPDATE_ARGS; extern bool wsrep_slave_threads_check CHECK_ARGS; extern bool wsrep_slave_threads_update UPDATE_ARGS; extern bool wsrep_desync_check CHECK_ARGS; extern bool wsrep_desync_update UPDATE_ARGS; extern bool wsrep_trx_fragment_size_check CHECK_ARGS; extern bool wsrep_trx_fragment_size_update UPDATE_ARGS; extern bool wsrep_trx_fragment_unit_update UPDATE_ARGS; extern bool wsrep_max_ws_size_check CHECK_ARGS; extern bool wsrep_max_ws_size_update UPDATE_ARGS; extern bool wsrep_reject_queries_update UPDATE_ARGS; extern bool wsrep_debug_update UPDATE_ARGS; extern bool wsrep_gtid_seq_no_check CHECK_ARGS; extern bool wsrep_gtid_domain_id_update UPDATE_ARGS; extern bool wsrep_mode_check CHECK_ARGS; extern bool wsrep_strict_ddl_update UPDATE_ARGS; extern bool wsrep_replicate_myisam_update UPDATE_ARGS; extern bool wsrep_replicate_myisam_check CHECK_ARGS; extern bool wsrep_forced_binlog_format_check CHECK_ARGS; #else /* WITH_WSREP */ #define wsrep_provider_init(X) #define wsrep_init_vars() (0) #define wsrep_start_position_init(X) #endif /* WITH_WSREP */ #endif /* WSREP_VAR_H */ mysql/server/private/transaction.h000064400000002672151027430560013401 0ustar00/* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef TRANSACTION_H #define TRANSACTION_H #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include class THD; void trans_track_end_trx(THD *thd); bool trans_begin(THD *thd, uint flags= 0); bool trans_commit(THD *thd); bool trans_commit_implicit(THD *thd); bool trans_rollback(THD *thd); bool trans_rollback_implicit(THD *thd); bool trans_commit_stmt(THD *thd); bool trans_rollback_stmt(THD *thd); bool trans_savepoint(THD *thd, LEX_CSTRING name); bool trans_rollback_to_savepoint(THD *thd, LEX_CSTRING name); bool trans_release_savepoint(THD *thd, LEX_CSTRING name); void trans_reset_one_shot_chistics(THD *thd); #endif /* TRANSACTION_H */ mysql/server/private/multi_range_read.h000064400000055213151027430560014354 0ustar00/* Copyright (c) 2009, 2011, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @defgroup DS-MRR declarations @{ */ /** A Disk-Sweep implementation of MRR Interface (DS-MRR for short) This is a "plugin"(*) for storage engines that allows to 1. When doing index scans, read table rows in rowid order; 2. when making many index lookups, do them in key order and don't lookup the same key value multiple times; 3. Do both #1 and #2, when applicable. These changes are expected to speed up query execution for disk-based storage engines running io-bound loads and "big" queries (ie. queries that do joins and enumerate lots of records). (*) - only conceptually. No dynamic loading or binary compatibility of any kind. General scheme of things: SQL Layer code | | | v v v -|---|---|---- handler->multi_range_read_XXX() function calls | | | _____________________________________ / DS-MRR module \ | (order/de-duplicate lookup keys, | | scan indexes in key order, | | order/de-duplicate rowids, | | retrieve full record reads in rowid | | order) | \_____________________________________/ | | | -|---|---|----- handler->read_range_first()/read_range_next(), | | | handler->index_read(), handler->rnd_pos() calls. | | | v v v Storage engine internals Currently DS-MRR is used by MyISAM, InnoDB and Maria storage engines. Potentially it can be used with any table handler that has disk-based data storage and has better performance when reading data in rowid order. */ #include "sql_lifo_buffer.h" class DsMrr_impl; class Mrr_ordered_index_reader; /* A structure with key parameters that's shared among several classes */ class Key_parameters { public: uint key_tuple_length; /* Length of index lookup tuple, in bytes */ key_part_map key_tuple_map; /* keyparts used in index lookup tuples */ /* This is = key_tuple_length if we copy keys to buffer = sizeof(void*) if we're using pointers to materialized keys. */ uint key_size_in_keybuf; /* TRUE <=> don't copy key values, use pointers to them instead. */ bool use_key_pointers; /* TRUE <=> We can get at most one index tuple for a lookup key */ bool index_ranges_unique; }; /** A class to enumerate (record, range_id) pairs that match given key value. @note The idea is that we have a Lifo_buffer which holds (key, range_id) pairs ordered by key value. From the front of the buffer we see (key_val1, range_id1), (key_val1, range_id2) ... (key_val2, range_idN) we take the first elements that have the same key value (key_val1 in the example above), and make lookup into the table. The table will have multiple matches for key_val1: == Table Index == ... key_val1 -> key_val1, index_tuple1 key_val1, index_tuple2 ... key_val1, index_tupleN ... Our goal is to produce all possible combinations, i.e. we need: {(key_val1, index_tuple1), range_id1} {(key_val1, index_tuple1), range_id2} ... ... | {(key_val1, index_tuple1), range_idN}, {(key_val1, index_tuple2), range_id1} {(key_val1, index_tuple2), range_id2} ... ... | {(key_val1, index_tuple2), range_idN}, ... ... ... {(key_val1, index_tupleK), range_idN} */ class Key_value_records_iterator { /* Use this to get table handler, key buffer and other parameters */ Mrr_ordered_index_reader *owner; /* Iterator to get (key, range_id) pairs from */ Lifo_buffer_iterator identical_key_it; /* Last of the identical key values (when we get this pointer from identical_key_it, it will be time to stop). */ uchar *last_identical_key_ptr; /* FALSE <=> we're right after the init() call, the record has been already read with owner->file->index_read_map() call */ bool get_next_row; public: int init(Mrr_ordered_index_reader *owner_arg); int get_next(range_id_t *range_info); void move_to_next_key_value(); }; /* Buffer manager interface. Mrr_reader objects use it to inqure DsMrr_impl to manage buffer space for them. */ typedef struct st_buffer_manager { public: /* Opaque value to be passed as the first argument to all member functions */ void *arg; /* This is called when we've freed more space from the rowid buffer. The callee will get the unused space from the rowid buffer and give it to the key buffer. */ void (*redistribute_buffer_space)(void *arg); /* This is called when both key and rowid buffers are empty, and so it's time to reset them to their original size (They've lost their original size, because we were dynamically growing rowid buffer and shrinking key buffer). */ void (*reset_buffer_sizes)(void *arg); } Buffer_manager; /* Mrr_reader - DS-MRR execution strategy abstraction A reader produces ([index]_record, range_info) pairs, and requires periodic refill operations. - one starts using the reader by calling reader->get_next(), - when a get_next() call returns HA_ERR_END_OF_FILE, one must call refill_buffer() before they can make more get_next() calls. - when refill_buffer() returns HA_ERR_END_OF_FILE, this means the real end of stream and get_next() should not be called anymore. Both functions can return other error codes, these mean unrecoverable errors after which one cannot continue. */ class Mrr_reader { public: virtual int get_next(range_id_t *range_info) = 0; virtual int refill_buffer(bool initial) = 0; virtual ~Mrr_reader() = default; /* just to remove compiler warning */ }; /* A common base for readers that do index scans and produce index tuples */ class Mrr_index_reader : public Mrr_reader { protected: handler *file; /* Handler object to use */ public: virtual int init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, Key_parameters *key_par, Lifo_buffer *key_buffer, Buffer_manager *buf_manager_arg) = 0; /* Get pointer to place where every get_next() call will put rowid */ virtual uchar *get_rowid_ptr() = 0; /* Get the rowid (call this after get_next() call) */ virtual void position(); virtual bool skip_record(range_id_t range_id, uchar *rowid) = 0; virtual void interrupt_read() {} virtual void resume_read() {} }; /* A "bypass" index reader that just does and index scan. The index scan is done by calling default MRR implementation (i.e. handler::multi_range_read_XXX()) functions. */ class Mrr_simple_index_reader : public Mrr_index_reader { public: int init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, Key_parameters *key_par, Lifo_buffer *key_buffer, Buffer_manager *buf_manager_arg) override; int get_next(range_id_t *range_info) override; int refill_buffer(bool initial) override { return initial? 0: HA_ERR_END_OF_FILE; } uchar *get_rowid_ptr() override { return file->ref; } bool skip_record(range_id_t range_id, uchar *rowid) override { return (file->mrr_funcs.skip_record && file->mrr_funcs.skip_record(file->mrr_iter, range_id, rowid)); } }; /* A reader that sorts the key values before it makes the index lookups. */ class Mrr_ordered_index_reader : public Mrr_index_reader { public: int init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, Key_parameters *key_par, Lifo_buffer *key_buffer, Buffer_manager *buf_manager_arg) override; int get_next(range_id_t *range_info) override; int refill_buffer(bool initial) override; uchar *get_rowid_ptr() override { return file->ref; } bool skip_record(range_id_t range_info, uchar *rowid) override { return (mrr_funcs.skip_record && mrr_funcs.skip_record(mrr_iter, range_info, rowid)); } bool skip_index_tuple(range_id_t range_info) { return (mrr_funcs.skip_index_tuple && mrr_funcs.skip_index_tuple(mrr_iter, range_info)); } bool set_interruption_temp_buffer(uint rowid_length, uint key_len, uint saved_pk_len, uchar **space_start, uchar *space_end); void set_no_interruption_temp_buffer(); void interrupt_read() override; void resume_read() override; void position() override; private: Key_value_records_iterator kv_it; bool scanning_key_val_iter; /* Buffer to store (key, range_id) pairs */ Lifo_buffer *key_buffer; /* This manages key buffer allocation and sizing for us */ Buffer_manager *buf_manager; Key_parameters keypar; /* index scan and lookup tuple parameters */ /* TRUE <=> need range association, buffers hold {rowid, range_id} pairs */ bool is_mrr_assoc; /* Range sequence iteration members */ RANGE_SEQ_IF mrr_funcs; range_seq_t mrr_iter; /* TRUE == reached eof when enumerating ranges */ bool source_exhausted; /* Following members are for interrupt_read()/resume_read(). The idea is that in some cases index scan that is done by this object is interrupted by rnd_pos() calls made by Mrr_ordered_rndpos_reader. The problem is that we're sharing handler->record[0] with that object, and it destroys its contents. We need to save/restore our current - index tuple (for pushed index condition checks) - clustered primary key values (again, for pushed index condition checks) - rowid of the last record we've retrieved (in case this rowid matches multiple ranges and we'll need to return it again) */ bool support_scan_interruptions; /* Space where we save the rowid of the last record we've returned */ uchar *saved_rowid; /* TRUE <=> saved_rowid has the last saved rowid */ bool have_saved_rowid; uchar *saved_key_tuple; /* Saved current key tuple */ uchar *saved_primary_key; /* Saved current primary key tuple */ /* TRUE<=> saved_key_tuple (and saved_primary_key when applicable) have valid values. */ bool read_was_interrupted; static int compare_keys(void *arg, const void *key1, const void *key2); static int compare_keys_reverse(void *arg, const void *key1, const void *key2); friend class Key_value_records_iterator; friend class DsMrr_impl; friend class Mrr_ordered_rndpos_reader; }; /* A reader that gets rowids from an Mrr_index_reader, and then sorts them before getting full records with handler->rndpos() calls. */ class Mrr_ordered_rndpos_reader : public Mrr_reader { public: int init(handler *file, Mrr_index_reader *index_reader, uint mode, Lifo_buffer *buf, Rowid_filter *filter); int get_next(range_id_t *range_info) override; int refill_buffer(bool initial) override; private: handler *file; /* Handler to use */ /* This what we get (rowid, range_info) pairs from */ Mrr_index_reader *index_reader; /* index_reader->get_next() puts rowid here */ uchar *index_rowid; /* TRUE <=> index_reader->refill_buffer() call has returned EOF */ bool index_reader_exhausted; /* TRUE <=> We should call index_reader->refill_buffer(). This happens if 1. we've made index_reader->get_next() call which returned EOF 2. we haven't made any index_reader calls (and our first call should be index_reader->refill_buffer(initial=TRUE) */ bool index_reader_needs_refill; /* TRUE <=> need range association, buffers hold {rowid, range_id} pairs */ bool is_mrr_assoc; /* When reading from ordered rowid buffer: the rowid element of the last buffer element that has rowid identical to this one. */ uchar *last_identical_rowid; /* Buffer to store (rowid, range_id) pairs */ Lifo_buffer *rowid_buffer; /* Rowid filter to be checked against (if any) */ Rowid_filter *rowid_filter; int refill_from_index_reader(); }; /* A primitive "factory" of various Mrr_*_reader classes (the point is to get various kinds of readers without having to allocate them on the heap) */ class Mrr_reader_factory { public: Mrr_ordered_rndpos_reader ordered_rndpos_reader; Mrr_ordered_index_reader ordered_index_reader; Mrr_simple_index_reader simple_index_reader; }; #define DSMRR_IMPL_SORT_KEYS HA_MRR_IMPLEMENTATION_FLAG1 #define DSMRR_IMPL_SORT_ROWIDS HA_MRR_IMPLEMENTATION_FLAG2 /* DS-MRR implementation for one table. Create/use one object of this class for each ha_{myisam/innobase/etc} object. That object will be further referred to as "the handler" DsMrr_impl supports has the following execution strategies: - Bypass DS-MRR, pass all calls to default MRR implementation, which is an MRR-to-non-MRR call converter. - Key-Ordered Retrieval - Rowid-Ordered Retrieval DsMrr_impl will use one of the above strategies, or a combination of them, according to the following diagram: (mrr function calls) | +----------------->-----------------+ | | ___________v______________ _______________v________________ / default: use lookup keys \ / KEY-ORDERED RETRIEVAL: \ | (or ranges) in whatever | | sort lookup keys and then make | | order they are supplied | | index lookups in index order | \__________________________/ \________________________________/ | | | | | +---<---+ | +--------------->-----------|----+ | | | | | | +---------------+ | | ______v___ ______ | _______________v_______________ | / default: read \ | / ROWID-ORDERED RETRIEVAL: \ | | table records | | | Before reading table records, | v | in random order | v | sort their rowids and then | | \_________________/ | | read them in rowid order | | | | \_______________________________/ | | | | | | | | +-->---+ | +----<------+-----------<--------+ | | | v v v (table records and range_ids) The choice of strategy depends on MRR scan properties, table properties (whether we're scanning clustered primary key), and @@optimizer_switch settings. Key-Ordered Retrieval --------------------- The idea is: if MRR scan is essentially a series of lookups on tbl.key=value1 OR tbl.key=value2 OR ... OR tbl.key=valueN then it makes sense to collect and order the set of lookup values, i.e. sort(value1, value2, .. valueN) and then do index lookups in index order. This results in fewer index page fetch operations, and we also can avoid making multiple index lookups for the same value. That is, if value1=valueN we can easily discover that after sorting and make one index lookup for them instead of two. Rowid-Ordered Retrieval ----------------------- If we do a regular index scan or a series of index lookups, we'll be hitting table records at random. For disk-based engines, this is much slower than reading the same records in disk order. We assume that disk ordering of rows is the same as ordering of their rowids (which is provided by handler::cmp_ref()) In order to retrieve records in different order, we must separate index scanning and record fetching, that is, MRR scan uses the following steps: 1. Scan the index (and only index, that is, with HA_EXTRA_KEYREAD on) and fill a buffer with {rowid, range_id} pairs 2. Sort the buffer by rowid value 3. for each {rowid, range_id} pair in the buffer get record by rowid and return the {record, range_id} pair 4. Repeat the above steps until we've exhausted the list of ranges we're scanning. Buffer space management considerations -------------------------------------- With regards to buffer/memory management, MRR interface specifies that - SQL layer provides multi_range_read_init() with buffer of certain size. - MRR implementation may use (i.e. have at its disposal till the end of the MRR scan) all of the buffer, or return the unused end of the buffer to SQL layer. DS-MRR needs buffer in order to accumulate and sort rowids and/or keys. When we need to accumulate/sort only keys (or only rowids), it is fairly trivial. When we need to accumulate/sort both keys and rowids, efficient buffer use gets complicated. We need to: - First, accumulate keys and sort them - Then use the keys (smaller values go first) to obtain rowids. A key is not needed after we've got matching rowids for it. - Make sure that rowids are accumulated at the front of the buffer, so that we can return the end part of the buffer to SQL layer, should there be too few rowid values to occupy the buffer. All of these goals are achieved by using the following scheme: | | We get an empty buffer from SQL layer. | *-| | *----| First, we fill the buffer with keys. Key_buffer | *-------| part grows from end of the buffer space to start | *----------| (In this picture, the buffer is big enough to | *-------------| accomodate all keys and even have some space left) | *=============| We want to do key-ordered index scan, so we sort the keys |-x *===========| Then we use the keys get rowids. Rowids are |----x *========| stored from start of buffer space towards the end. |--------x *=====| The part of the buffer occupied with keys |------------x *===| gradually frees up space for rowids. In this |--------------x *=| picture we run out of keys before we've ran out |----------------x | of buffer space (it can be other way as well). |================x | Then we sort the rowids. | |~~~| The unused part of the buffer is at the end, so we can return it to the SQL layer. |================* Sorted rowids are then used to read table records in disk order */ class DsMrr_impl { public: typedef void (handler::*range_check_toggle_func_t)(bool on); void init(handler *h_arg, TABLE *table_arg) { primary_file= h_arg; table= table_arg; } int dsmrr_init(handler *h_arg, RANGE_SEQ_IF *seq_funcs, void *seq_init_param, uint n_ranges, uint mode, HANDLER_BUFFER *buf); void dsmrr_close(); int dsmrr_next(range_id_t *range_info); ha_rows dsmrr_info(uint keyno, uint n_ranges, uint keys, uint key_parts, uint *bufsz, uint *flags, Cost_estimate *cost); ha_rows dsmrr_info_const(uint keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges, uint *bufsz, uint *flags, Cost_estimate *cost); int dsmrr_explain_info(uint mrr_mode, char *str, size_t size); private: /* Buffer to store (key, range_id) pairs */ Lifo_buffer *key_buffer= nullptr; /* The "owner" handler object (the one that is expected to "own" this object and call its functions). */ handler *primary_file; TABLE *table; /* Always equal to primary_file->table */ /* Secondary handler object. (created when needed, we need it when we need to run both index scan and rnd_pos() scan at the same time) */ handler *secondary_file= nullptr; /* The rowid filter that DS-MRR has "unpushed" from the storage engine. If it's present, DS-MRR will use it. */ Rowid_filter *rowid_filter= nullptr; uint keyno; /* index we're running the scan on */ /* TRUE <=> need range association, buffers hold {rowid, range_id} pairs */ bool is_mrr_assoc; Mrr_reader_factory reader_factory; Mrr_reader *strategy; bool strategy_exhausted; Mrr_index_reader *index_strategy; /* The whole buffer space that we're using */ uchar *full_buf; uchar *full_buf_end; /* When using both rowid and key buffers: the boundary between key and rowid parts of the buffer. This is the "original" value, actual memory ranges used by key and rowid parts may be different because of dynamic space reallocation between them. */ uchar *rowid_buffer_end; /* One of the following two is used for key buffer: forward is used when we only need key buffer, backward is used when we need both key and rowid buffers. */ Forward_lifo_buffer forward_key_buf; Backward_lifo_buffer backward_key_buf; /* Buffer to store (rowid, range_id) pairs, or just rowids if is_mrr_assoc==FALSE */ Forward_lifo_buffer rowid_buffer; bool choose_mrr_impl(uint keyno, ha_rows rows, uint *flags, uint *bufsz, Cost_estimate *cost); bool get_disk_sweep_mrr_cost(uint keynr, ha_rows rows, uint flags, uint *buffer_size, uint extra_mem_overhead, Cost_estimate *cost); bool check_cpk_scan(THD *thd, TABLE_SHARE *share, uint keyno, uint mrr_flags); bool setup_buffer_sharing(uint key_size_in_keybuf, key_part_map key_tuple_map); /* Buffer_manager and its member functions */ Buffer_manager buf_manager; static void redistribute_buffer_space(void *dsmrr_arg); static void reset_buffer_sizes(void *dsmrr_arg); static void do_nothing(void *dsmrr_arg); Lifo_buffer* get_key_buffer() { return key_buffer; } friend class Key_value_records_iterator; friend class Mrr_ordered_index_reader; friend class Mrr_ordered_rndpos_reader; int setup_two_handlers(); void close_second_handler(); }; /** @} (end of group DS-MRR declarations) */ mysql/server/private/my_uctype.h000064400000207630151027430560013073 0ustar00#ifndef MY_UCTYPE_INCLUDED #define MY_UCTYPE_INCLUDED /* Copyright (c) 2006 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Unicode ctype data Generated from UnicodeData-5.0.0d9.txt */ static unsigned char uctype_page00[256]= { 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, 16, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 16, 16, 16, 16, 16, 16, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 16, 16, 16, 16, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 16, 16, 32, 16, 16, 16, 16, 20, 20, 16, 2, 16, 16, 16, 20, 2, 16, 20, 20, 20, 16, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 16, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, 2, 2 }; static unsigned char uctype_page01[256]= { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2 }; static unsigned char uctype_page02[256]= { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; static unsigned char uctype_page03[256]= { 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 2, 2, 2, 2, 16, 0, 0, 0, 0, 0, 16, 16, 1, 16, 1, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 1, 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, 16, 1, 2, 1, 1, 2, 2, 1, 1, 1 }; static unsigned char uctype_page04[256]= { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 16, 18, 18, 18, 18, 0, 18, 18, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 }; static unsigned char uctype_page05[256]= { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 16, 16, 16, 16, 16, 16, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 16, 16, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 18, 16, 18, 18, 16, 18, 18, 16, 18, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page06[256]= { 32, 32, 32, 32, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 16, 0, 0, 16, 16, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 2, 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 18, 18, 18, 18, 18, 18, 18, 32, 18, 18, 18, 18, 18, 18, 18, 2, 2, 18, 18, 16, 18, 18, 18, 18, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 16, 16, 2 }; static unsigned char uctype_page07[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 32, 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 2, 2, 16, 16, 16, 16, 2, 0, 0, 0, 0, 0 }; static unsigned char uctype_page09[256]= { 0, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 2, 18, 18, 18, 18, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, 18, 18, 18, 18, 18, 0, 0, 18, 18, 0, 0, 18, 18, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 16, 16, 20, 20, 20, 20, 20, 20, 16, 0, 0, 0, 0, 0 }; static unsigned char uctype_page0A[256]= { 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0, 18, 0, 18, 18, 18, 18, 18, 0, 0, 0, 0, 18, 18, 0, 0, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 18, 18, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page0B[256]= { 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, 18, 18, 18, 18, 0, 0, 0, 18, 18, 0, 0, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 2, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 0, 0, 0, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, 18, 18, 18, 0, 0, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0 }; static unsigned char uctype_page0C[256]= { 0, 18, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 18, 2, 18, 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page0D[256]= { 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 0, 0, 18, 18, 18, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 18, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 0, 18, 0, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page0E[256]= { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 2, 2, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 16, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 2, 2, 18, 2, 2, 18, 18, 18, 18, 18, 18, 0, 18, 18, 2, 0, 0, 2, 2, 2, 2, 2, 0, 2, 0, 18, 18, 18, 18, 18, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page0F[256]= { 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 16, 16, 16, 16, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 18, 16, 18, 16, 18, 16, 16, 16, 16, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 18, 18, 2, 2, 2, 2, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 16, 16, 16, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 16, 16, 0, 0, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page10[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 2, 0, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 0, 0, 0 }; static unsigned char uctype_page11[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page12[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; static unsigned char uctype_page13[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page14[256]= { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; static unsigned char uctype_page16[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page17[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 32, 32, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 16, 16, 2, 16, 16, 16, 16, 2, 18, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page18[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 8, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page19[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 16, 0, 0, 0, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 18, 18, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; static unsigned char uctype_page1A[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 0, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page1B[256]= { 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page1D[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18 }; static unsigned char uctype_page1E[256]= { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page1F[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 2, 16, 16, 16, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 16, 16, 2, 2, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 0, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 16, 16, 16, 0, 0, 2, 2, 2, 0, 2, 2, 1, 1, 1, 1, 1, 16, 16, 0 }; static unsigned char uctype_page20[256]= { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 32, 32, 32, 32, 32, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 8, 8, 32, 32, 32, 32, 32, 8, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 8, 32, 32, 32, 32, 0, 0, 0, 0, 0, 0, 32, 32, 32, 32, 32, 32, 20, 2, 0, 0, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 2, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page21[256]= { 16, 16, 1, 16, 16, 16, 16, 1, 16, 16, 2, 1, 1, 1, 2, 2, 1, 1, 1, 2, 16, 1, 16, 16, 16, 1, 1, 1, 1, 1, 16, 16, 16, 16, 16, 16, 1, 16, 1, 16, 1, 16, 1, 1, 1, 1, 16, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 16, 16, 2, 2, 1, 1, 16, 16, 16, 16, 16, 1, 2, 2, 2, 2, 16, 16, 16, 16, 2, 0, 0, 0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; static unsigned char uctype_page23[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page24[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 }; static unsigned char uctype_page26[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page27[256]= { 0, 16, 16, 16, 16, 0, 16, 16, 16, 16, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 0, 16, 16, 16, 16, 0, 0, 0, 16, 0, 16, 16, 16, 16, 16, 16, 16, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; static unsigned char uctype_page2B[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page2C[256]= { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 20, 16, 16 }; static unsigned char uctype_page2D[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page2E[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_page2F[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0 }; static unsigned char uctype_page30[256]= { 8, 16, 16, 16, 16, 2, 2, 7, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 7, 7, 7, 7, 7, 7, 7, 7, 7, 18, 18, 18, 18, 18, 18, 16, 2, 2, 2, 2, 2, 16, 16, 7, 7, 7, 2, 2, 16, 16, 16, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 18, 18, 16, 16, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2 }; static unsigned char uctype_page31[256]= { 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 16, 16, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; static unsigned char uctype_page32[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0 }; static unsigned char uctype_page4D[256]= { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; static unsigned char uctype_page9F[256]= { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageA4[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageA7[256]= { 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageA8[256]= { 2, 2, 18, 2, 2, 2, 18, 2, 2, 2, 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 18, 18, 18, 18, 18, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageD7[256]= { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageD8[256]= { 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageDB[256]= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 }; static unsigned char uctype_pageDC[256]= { 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageDF[256]= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 }; static unsigned char uctype_pageE0[256]= { 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageF8[256]= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 }; static unsigned char uctype_pageFA[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static unsigned char uctype_pageFB[256]= { 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; static unsigned char uctype_pageFD[256]= { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 0, 0 }; static unsigned char uctype_pageFE[256]= { 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 32 }; static unsigned char uctype_pageFF[256]= { 0, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 16, 16, 16, 16, 16, 16, 16, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16, 0, 16, 16, 16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 32, 32, 16, 16, 0, 0 }; MY_UNI_CTYPE my_uni_ctype[256]={ {0,uctype_page00}, {0,uctype_page01}, {0,uctype_page02}, {0,uctype_page03}, {0,uctype_page04}, {0,uctype_page05}, {0,uctype_page06}, {0,uctype_page07}, {0,NULL}, {0,uctype_page09}, {0,uctype_page0A}, {0,uctype_page0B}, {0,uctype_page0C}, {0,uctype_page0D}, {0,uctype_page0E}, {0,uctype_page0F}, {0,uctype_page10}, {0,uctype_page11}, {0,uctype_page12}, {0,uctype_page13}, {0,uctype_page14}, {2,NULL}, {0,uctype_page16}, {0,uctype_page17}, {0,uctype_page18}, {0,uctype_page19}, {0,uctype_page1A}, {0,uctype_page1B}, {0,NULL}, {0,uctype_page1D}, {0,uctype_page1E}, {0,uctype_page1F}, {0,uctype_page20}, {0,uctype_page21}, {16,NULL}, {0,uctype_page23}, {0,uctype_page24}, {16,NULL}, {0,uctype_page26}, {0,uctype_page27}, {16,NULL}, {16,NULL}, {16,NULL}, {0,uctype_page2B}, {0,uctype_page2C}, {0,uctype_page2D}, {0,uctype_page2E}, {0,uctype_page2F}, {0,uctype_page30}, {0,uctype_page31}, {0,uctype_page32}, {16,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {0,uctype_page4D}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {0,uctype_page9F}, {2,NULL}, {2,NULL}, {2,NULL}, {2,NULL}, {0,uctype_pageA4}, {0,NULL}, {0,NULL}, {0,uctype_pageA7}, {0,uctype_pageA8}, {0,NULL}, {0,NULL}, {0,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {3,NULL}, {0,uctype_pageD7}, {0,uctype_pageD8}, {0,NULL}, {0,NULL}, {0,uctype_pageDB}, {0,uctype_pageDC}, {0,NULL}, {0,NULL}, {0,uctype_pageDF}, {0,uctype_pageE0}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,NULL}, {0,uctype_pageF8}, {2,NULL}, {0,uctype_pageFA}, {0,uctype_pageFB}, {2,NULL}, {0,uctype_pageFD}, {0,uctype_pageFE}, {0,uctype_pageFF} }; #endif /* MY_UCTYPE_INCLUDED */ mysql/server/private/myisam.h000064400000042142151027430560012347 0ustar00/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. Copyright (c) 2009, 2013, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file should be included when using myisam_functions */ #ifndef _myisam_h #define _myisam_h #ifdef __cplusplus extern "C" { #endif #include #include #include "keycache.h" #include "my_compare.h" #include #include #include /* Limit max keys according to HA_MAX_POSSIBLE_KEY; See myisamchk.h for details */ #if MAX_INDEXES > HA_MAX_POSSIBLE_KEY #define MI_MAX_KEY HA_MAX_POSSIBLE_KEY /* Max allowed keys */ #else #define MI_MAX_KEY MAX_INDEXES /* Max allowed keys */ #endif #define MI_MAX_POSSIBLE_KEY_BUFF HA_MAX_POSSIBLE_KEY_BUFF /* The following defines can be increased if necessary. But beware the dependency of MI_MAX_POSSIBLE_KEY_BUFF and MI_MAX_KEY_LENGTH. */ #define MI_MAX_KEY_LENGTH 1000 /* Max length in bytes */ #define MI_MAX_KEY_SEG 16 /* Max segments for key */ #define MI_NAME_IEXT ".MYI" #define MI_NAME_DEXT ".MYD" /* Possible values for myisam_block_size (must be power of 2) */ #define MI_KEY_BLOCK_LENGTH 1024 /* default key block length */ #define MI_MIN_KEY_BLOCK_LENGTH 1024 /* Min key block length */ #define MI_MAX_KEY_BLOCK_LENGTH 16384 /* In the following macros '_keyno_' is 0 .. keys-1. If there can be more keys than bits in the key_map, the highest bit is for all upper keys. They cannot be switched individually. This means that clearing of high keys is ignored, setting one high key sets all high keys. */ #define MI_KEYMAP_BITS (8 * SIZEOF_LONG_LONG) #define MI_KEYMAP_HIGH_MASK (1ULL << (MI_KEYMAP_BITS - 1)) #define mi_get_mask_all_keys_active(_keys_) \ (((_keys_) < MI_KEYMAP_BITS) ? \ ((1ULL << (_keys_)) - 1ULL) : \ (~ 0ULL)) #if MI_MAX_KEY > MI_KEYMAP_BITS #define mi_is_key_active(_keymap_,_keyno_) \ (((_keyno_) < MI_KEYMAP_BITS) ? \ MY_TEST((_keymap_) & (1ULL << (_keyno_))) : \ MY_TEST((_keymap_) & MI_KEYMAP_HIGH_MASK)) #define mi_set_key_active(_keymap_,_keyno_) \ (_keymap_)|= (((_keyno_) < MI_KEYMAP_BITS) ? \ (1ULL << (_keyno_)) : \ MI_KEYMAP_HIGH_MASK) #define mi_clear_key_active(_keymap_,_keyno_) \ (_keymap_)&= (((_keyno_) < MI_KEYMAP_BITS) ? \ (~ (1ULL << (_keyno_))) : \ (~ (0ULL)) /*ignore*/ ) #else #define mi_is_key_active(_keymap_,_keyno_) \ MY_TEST((_keymap_) & (1ULL << (_keyno_))) #define mi_set_key_active(_keymap_,_keyno_) \ (_keymap_)|= (1ULL << (_keyno_)) #define mi_clear_key_active(_keymap_,_keyno_) \ (_keymap_)&= (~ (1ULL << (_keyno_))) #endif #define mi_is_any_key_active(_keymap_) \ MY_TEST((_keymap_)) #define mi_is_all_keys_active(_keymap_,_keys_) \ ((_keymap_) == mi_get_mask_all_keys_active(_keys_)) #define mi_set_all_keys_active(_keymap_,_keys_) \ (_keymap_)= mi_get_mask_all_keys_active(_keys_) #define mi_clear_all_keys_active(_keymap_) \ (_keymap_)= 0 #define mi_intersect_keys_active(_to_,_from_) \ (_to_)&= (_from_) #define mi_is_any_intersect_keys_active(_keymap1_,_keys_,_keymap2_) \ ((_keymap1_) & (_keymap2_) & \ mi_get_mask_all_keys_active(_keys_)) #define mi_copy_keys_active(_to_,_maxkeys_,_from_) \ (_to_)= (mi_get_mask_all_keys_active(_maxkeys_) & \ (_from_)) /* Param to/from mi_info */ typedef struct st_mi_isaminfo /* Struct from h_info */ { ha_rows records; /* Records in database */ ha_rows deleted; /* Deleted records in database */ my_off_t recpos; /* Pos for last used record */ my_off_t newrecpos; /* Pos if we write new record */ my_off_t dupp_key_pos; /* Position to record with dupp key */ my_off_t data_file_length, /* Length of data file */ max_data_file_length, index_file_length, max_index_file_length, delete_length; ulong reclength; /* Recordlength */ ulong mean_reclength; /* Mean recordlength (if packed) */ ulonglong auto_increment; ulonglong key_map; /* Which keys are used */ char *data_file_name, *index_file_name; uint keys; /* Number of keys in use */ uint options; /* HA_OPTION_... used */ int errkey, /* With key was dupplicated on err */ sortkey; /* clustered by this key */ File filenr; /* (uniq) filenr for datafile */ time_t create_time; /* When table was created */ time_t check_time; time_t update_time; uint reflength; ulong record_offset; ulong *rec_per_key; /* for sql optimizing */ } MI_ISAMINFO; typedef struct st_mi_create_info { const char *index_file_name, *data_file_name; /* If using symlinks */ ha_rows max_rows; ha_rows reloc_rows; ulonglong auto_increment; ulonglong data_file_length; ulonglong key_file_length; uint old_options; uint16 language; my_bool with_auto_increment; } MI_CREATE_INFO; struct st_myisam_info; /* For reference */ struct st_mi_isam_share; typedef struct st_myisam_info MI_INFO; struct st_mi_s_param; typedef struct st_mi_keydef /* Key definition with open & info */ { struct st_mi_isam_share *share; /* Pointer to base (set in mi_open) */ uint16 keysegs; /* Number of key-segment */ uint16 flag; /* NOSAME, PACK_USED */ uint8 key_alg; /* BTREE, RTREE */ uint16 block_length; /* Length of keyblock (auto) */ uint16 underflow_block_length; /* When to execute underflow */ uint16 keylength; /* Tot length of keyparts (auto) */ uint16 minlength; /* min length of (packed) key (auto) */ uint16 maxlength; /* max length of (packed) key (auto) */ uint16 block_size_index; /* block_size (auto) */ uint32 version; /* For concurrent read/write */ uint32 ftkey_nr; /* full-text index number */ HA_KEYSEG *seg,*end; struct st_mysql_ftparser *parser; /* Fulltext [pre]parser */ int (*bin_search)(struct st_myisam_info *info,struct st_mi_keydef *keyinfo, uchar *page,uchar *key, uint key_len,uint comp_flag,uchar * *ret_pos, uchar *buff, my_bool *was_last_key); uint (*get_key)(struct st_mi_keydef *keyinfo,uint nod_flag,uchar * *page, uchar *key); int (*pack_key)(struct st_mi_keydef *keyinfo,uint nod_flag,uchar *next_key, uchar *org_key, uchar *prev_key, uchar *key, struct st_mi_s_param *s_temp); void (*store_key)(struct st_mi_keydef *keyinfo, uchar *key_pos, struct st_mi_s_param *s_temp); int (*ck_insert)(struct st_myisam_info *inf, uint k_nr, uchar *k, uint klen); int (*ck_delete)(struct st_myisam_info *inf, uint k_nr, uchar *k, uint klen); } MI_KEYDEF; #define MI_UNIQUE_HASH_LENGTH 4 typedef struct st_unique_def /* Segment definition of unique */ { uint16 keysegs; /* Number of key-segment */ uchar key; /* Mapped to which key */ uint8 null_are_equal; HA_KEYSEG *seg,*end; } MI_UNIQUEDEF; typedef struct st_mi_decode_tree /* Decode huff-table */ { uint16 *table; uint quick_table_bits; uchar *intervalls; } MI_DECODE_TREE; struct st_mi_bit_buff; /* Note that null markers should always be first in a row ! When creating a column, one should only specify: type, length, null_bit and null_pos */ typedef struct st_columndef /* column information */ { enum en_fieldtype type; uint16 length; /* length of field */ uint32 offset; /* Offset to position in row */ uint8 null_bit; /* If column may be 0 */ uint16 null_pos; /* position for null marker */ #ifndef NOT_PACKED_DATABASES void (*unpack)(struct st_columndef *rec,struct st_mi_bit_buff *buff, uchar *start,uchar *end); enum en_fieldtype base_type; uint space_length_bits,pack_type; MI_DECODE_TREE *huff_tree; #endif } MI_COLUMNDEF; extern char * myisam_log_filename; /* Name of logfile */ extern ulong myisam_block_size; extern ulong myisam_concurrent_insert; extern my_bool myisam_flush,myisam_delay_key_write,myisam_single_user; extern my_off_t myisam_max_temp_length; extern ulong myisam_data_pointer_size; /* usually used to check if a symlink points into the mysql data home */ /* which is normally forbidden */ extern int (*myisam_test_invalid_symlink)(const char *filename); extern ulonglong myisam_mmap_size, myisam_mmap_used; extern mysql_mutex_t THR_LOCK_myisam_mmap; /* Prototypes for myisam-functions */ extern int mi_close(struct st_myisam_info *file); extern int mi_delete(struct st_myisam_info *file,const uchar *buff); extern struct st_myisam_info *mi_open(const char *name,int mode, uint wait_if_locked); extern int mi_panic(enum ha_panic_function function); extern int mi_rfirst(struct st_myisam_info *file,uchar *buf,int inx); extern int mi_rkey(MI_INFO *info, uchar *buf, int inx, const uchar *key, key_part_map keypart_map, enum ha_rkey_function search_flag); extern int mi_rlast(struct st_myisam_info *file,uchar *buf,int inx); extern int mi_rnext(struct st_myisam_info *file,uchar *buf,int inx); extern int mi_rnext_same(struct st_myisam_info *info, uchar *buf); extern int mi_rprev(struct st_myisam_info *file,uchar *buf,int inx); extern int mi_rrnd(struct st_myisam_info *file,uchar *buf, my_off_t pos); extern int mi_scan_init(struct st_myisam_info *file); extern int mi_scan(struct st_myisam_info *file,uchar *buf); extern int mi_rsame(struct st_myisam_info *file,uchar *record,int inx); extern int mi_rsame_with_pos(struct st_myisam_info *file,uchar *record, int inx, my_off_t pos); extern int mi_update(struct st_myisam_info *file,const uchar *old, const uchar *new_record); extern int mi_write(struct st_myisam_info *file,const uchar *buff); extern my_off_t mi_position(struct st_myisam_info *file); extern int mi_status(struct st_myisam_info *info, MI_ISAMINFO *x, uint flag); extern int mi_lock_database(struct st_myisam_info *file,int lock_type); extern int mi_create(const char *name,uint keys,MI_KEYDEF *keydef, uint columns, MI_COLUMNDEF *columndef, uint uniques, MI_UNIQUEDEF *uniquedef, MI_CREATE_INFO *create_info, uint flags); extern int mi_delete_table(const char *name); extern int mi_rename(const char *from, const char *to); extern int mi_extra(struct st_myisam_info *file, enum ha_extra_function function, void *extra_arg); extern int mi_reset(struct st_myisam_info *file); extern ha_rows mi_records_in_range(MI_INFO *info,int inx, const key_range *min_key, const key_range *max_key, page_range *pages); extern int mi_log(int activate_log); extern int mi_is_changed(struct st_myisam_info *info); extern int mi_delete_all_rows(struct st_myisam_info *info); extern ulong _mi_calc_blob_length(uint length , const uchar *pos); extern uint mi_get_pointer_length(ulonglong file_length, uint def); extern int mi_make_backup_of_index(struct st_myisam_info *info, time_t backup_time, myf flags); #define myisam_max_key_length() HA_MAX_KEY_LENGTH #define myisam_max_key_segments() HA_MAX_KEY_SEG #define MEMMAP_EXTRA_MARGIN 7 /* Write this as a suffix for mmap file */ /* this is used to pass to mysql_myisamchk_table */ #define MYISAMCHK_REPAIR 1 /* equivalent to myisamchk -r */ #define MYISAMCHK_VERIFY 2 /* Verify, run repair if failure */ typedef uint mi_bit_type; typedef struct st_sort_key_blocks SORT_KEY_BLOCKS; typedef struct st_sort_ftbuf SORT_FT_BUF; typedef struct st_mi_bit_buff { /* Used for packing of record */ mi_bit_type current_byte; uint bits; uchar *pos, *end, *blob_pos, *blob_end; uint error; } MI_BIT_BUFF; typedef struct st_sort_info { /* sync things */ mysql_mutex_t mutex; mysql_cond_t cond; MI_INFO *info; HA_CHECK *param; uchar *buff; SORT_KEY_BLOCKS *key_block, *key_block_end; SORT_FT_BUF *ft_buf; my_off_t filelength, dupp, buff_length; ha_rows max_records; uint current_key, total_keys; volatile uint got_error; uint threads_running; myf myf_rw; enum data_file_type new_data_file_type; } MI_SORT_INFO; typedef struct st_mi_sort_param { pthread_t thr; IO_CACHE read_cache, tempfile, tempfile_for_exceptions; DYNAMIC_ARRAY buffpek; MI_BIT_BUFF bit_buff; /* For parallel repair of packrec. */ MI_KEYDEF *keyinfo; MI_SORT_INFO *sort_info; HA_KEYSEG *seg; uchar **sort_keys; uchar *rec_buff; void *wordlist, *wordptr; MEM_ROOT wordroot; uchar *record; MY_TMPDIR *tmpdir; /* The next two are used to collect statistics, see update_key_parts for description. */ ulonglong unique[HA_MAX_KEY_SEG+1]; ulonglong notnull[HA_MAX_KEY_SEG+1]; my_off_t pos,max_pos,filepos,start_recpos; uint key, key_length,real_key_length; uint maxbuffers, find_length; ulonglong sortbuff_size; ha_rows keys; my_bool fix_datafile, master; my_bool calc_checksum; /* calculate table checksum */ int (*key_cmp)(void *, const void *, const void *); int (*key_read)(struct st_mi_sort_param *,void *); int (*key_write)(struct st_mi_sort_param *, const void *); void (*lock_in_memory)(HA_CHECK *); int (*write_keys)(struct st_mi_sort_param *, uchar **, ulonglong , struct st_buffpek *, IO_CACHE *); my_off_t (*read_to_buffer)(IO_CACHE *,struct st_buffpek *, uint); int (*write_key)(struct st_mi_sort_param *, IO_CACHE *,uchar *, uint, ulonglong); } MI_SORT_PARAM; /* functions in mi_check */ void myisamchk_init(HA_CHECK *param); int chk_status(HA_CHECK *param, MI_INFO *info); int chk_del(HA_CHECK *param, MI_INFO *info, ulonglong test_flag); int chk_size(HA_CHECK *param, MI_INFO *info); int chk_key(HA_CHECK *param, MI_INFO *info); int chk_data_link(HA_CHECK *param, MI_INFO *info, my_bool extend); int mi_repair(HA_CHECK *param, MI_INFO *info, char * name, int rep_quick); int mi_sort_index(HA_CHECK *param, MI_INFO *info, char * name); int mi_repair_by_sort(HA_CHECK *param, MI_INFO *info, const char * name, int rep_quick); int mi_repair_parallel(HA_CHECK *param, MI_INFO *info, const char * name, int rep_quick); int change_to_newfile(const char * filename, const char * old_ext, const char * new_ext, time_t backup_time, myf myflags); int lock_file(HA_CHECK *param, File file, my_off_t start, int lock_type, const char *filetype, const char *filename); void lock_memory(HA_CHECK *param); void update_auto_increment_key(HA_CHECK *param, MI_INFO *info, my_bool repair); int update_state_info(HA_CHECK *param, MI_INFO *info,uint update); void update_key_parts(MI_KEYDEF *keyinfo, ulong *rec_per_key_part, ulonglong *unique, ulonglong *notnull, ulonglong records); int filecopy(HA_CHECK *param, File to,File from,my_off_t start, my_off_t length, const char *type); int movepoint(MI_INFO *info,uchar *record,my_off_t oldpos, my_off_t newpos, uint prot_key); int write_data_suffix(MI_SORT_INFO *sort_info, my_bool fix_datafile); int test_if_almost_full(MI_INFO *info); int recreate_table(HA_CHECK *param, MI_INFO **org_info, char *filename); void mi_disable_non_unique_index(MI_INFO *info, ha_rows rows); my_bool mi_test_if_sort_rep(MI_INFO *info, ha_rows rows, ulonglong key_map, my_bool force); int mi_init_bulk_insert(MI_INFO *info, size_t cache_size, ha_rows rows); void mi_flush_bulk_insert(MI_INFO *info, uint inx); int mi_end_bulk_insert(MI_INFO *info, my_bool abort); int mi_assign_to_key_cache(MI_INFO *info, ulonglong key_map, KEY_CACHE *key_cache); void mi_change_key_cache(KEY_CACHE *old_key_cache, KEY_CACHE *new_key_cache); int mi_preload(MI_INFO *info, ulonglong key_map, my_bool ignore_leaves); int write_data_suffix(MI_SORT_INFO *sort_info, my_bool fix_datafile); int flush_pending_blocks(MI_SORT_PARAM *param); int sort_ft_buf_flush(MI_SORT_PARAM *sort_param); int thr_write_keys(MI_SORT_PARAM *sort_param); int sort_write_record(MI_SORT_PARAM *sort_param); int _create_index_by_sort(MI_SORT_PARAM *info,my_bool no_messages, ulonglong); my_bool mi_too_big_key_for_sort(MI_KEYDEF *key, ha_rows rows); #ifdef __cplusplus } #endif #endif mysql/server/private/item_vers.h000064400000010356151027430560013047 0ustar00#ifndef ITEM_VERS_INCLUDED #define ITEM_VERS_INCLUDED /* Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /* System Versioning items */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif class Item_func_history: public Item_bool_func { public: /* @param a Item_field for row_end system field */ Item_func_history(THD *thd, Item *a): Item_bool_func(thd, a) { DBUG_ASSERT(a->type() == Item::FIELD_ITEM); } bool val_bool() override; bool fix_length_and_dec() override { set_maybe_null(); null_value= 0; decimals= 0; max_length= 1; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("is_history") }; return name; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_trt_ts: public Item_datetimefunc { TR_table::field_id_t trt_field; public: Item_func_trt_ts(THD *thd, Item* a, TR_table::field_id_t _trt_field); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING begin_name= {STRING_WITH_LEN("trt_begin_ts") }; static LEX_CSTRING commit_name= {STRING_WITH_LEN("trt_commit_ts") }; return (trt_field == TR_table::FLD_BEGIN_TS) ? begin_name : commit_name; } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool fix_length_and_dec() override { fix_attributes_datetime(decimals); return FALSE; } }; class Item_func_trt_id : public Item_longlong_func { TR_table::field_id_t trt_field; bool backwards; longlong get_by_trx_id(ulonglong trx_id); longlong get_by_commit_ts(MYSQL_TIME &commit_ts, bool backwards); public: Item_func_trt_id(THD *thd, Item* a, TR_table::field_id_t _trt_field, bool _backwards= false); Item_func_trt_id(THD *thd, Item* a, Item* b, TR_table::field_id_t _trt_field); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING trx_name= {STRING_WITH_LEN("trt_trx_id") }; static LEX_CSTRING commit_name= {STRING_WITH_LEN("trt_commit_id") }; static LEX_CSTRING iso_name= {STRING_WITH_LEN("trt_iso_level") }; switch (trt_field) { case TR_table::FLD_TRX_ID: return trx_name; case TR_table::FLD_COMMIT_ID: return commit_name; case TR_table::FLD_ISO_LEVEL: return iso_name; default: DBUG_ASSERT(0); } return NULL_clex_str; } bool fix_length_and_dec() override { bool res= Item_int_func::fix_length_and_dec(); max_length= 20; return res; } longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_trt_trx_sees : public Item_bool_func { protected: bool accept_eq; public: Item_func_trt_trx_sees(THD *thd, Item* a, Item* b); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("trt_trx_sees") }; return name; } bool val_bool() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_trt_trx_sees_eq : public Item_func_trt_trx_sees { public: Item_func_trt_trx_sees_eq(THD *thd, Item* a, Item* b) : Item_func_trt_trx_sees(thd, a, b) { accept_eq= true; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("trt_trx_sees_eq") }; return name; } }; #endif /* ITEM_VERS_INCLUDED */ mysql/server/private/rijndael.h000064400000003257151027430560012644 0ustar00#ifndef RIJNDAEL_INCLUDED #define RIJNDAEL_INCLUDED /* Copyright (c) 2002, 2006 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* rijndael-alg-fst.h @version 3.0 (December 2000) Optimised ANSI C code for the Rijndael cipher (now AES) @author Vincent Rijmen @author Antoon Bosselaers @author Paulo Barreto This code is hereby placed in the public domain. Modified by Peter Zaitsev to fit MySQL coding style. */ #define AES_MAXKC (256/32) #define AES_MAXKB (256/8) #define AES_MAXNR 14 int rijndaelKeySetupEnc(uint32 rk[/*4*(Nr + 1)*/], const uint8 cipherKey[], int keyBits); int rijndaelKeySetupDec(uint32 rk[/*4*(Nr + 1)*/], const uint8 cipherKey[], int keyBits); void rijndaelEncrypt(const uint32 rk[/*4*(Nr + 1)*/], int Nr, const uint8 pt[16], uint8 ct[16]); void rijndaelDecrypt(const uint32 rk[/*4*(Nr + 1)*/], int Nr, const uint8 ct[16], uint8 pt[16]); #endif /* RIJNDAEL_INCLUDED */ mysql/server/private/sql_schema.h000064400000006347151027430560013176 0ustar00#ifndef SQL_SCHEMA_H_INCLUDED #define SQL_SCHEMA_H_INCLUDED /* Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "mysqld.h" #include "lex_string.h" class Lex_ident_sys; class Create_func; class Schema { LEX_CSTRING m_name; public: Schema(const LEX_CSTRING &name) :m_name(name) { } virtual ~Schema() = default; const LEX_CSTRING &name() const { return m_name; } virtual const Type_handler *map_data_type(THD *thd, const Type_handler *src) const { return src; } /** Find a native function builder, return an error if not found, build an Item otherwise. */ Item *make_item_func_call_native(THD *thd, const Lex_ident_sys &name, List *args) const; /** Find the native function builder associated with a given function name. @param thd The current thread @param name The native function name @return The native function builder associated with the name, or NULL */ virtual Create_func *find_native_function_builder(THD *thd, const LEX_CSTRING &name) const; // Builders for native SQL function with a special syntax in sql_yacc.yy virtual Item *make_item_func_replace(THD *thd, Item *subj, Item *find, Item *replace) const; virtual Item *make_item_func_substr(THD *thd, const Lex_substring_spec_st &spec) const; virtual Item *make_item_func_trim(THD *thd, const Lex_trim_st &spec) const; /* For now we have *hard-coded* compatibility schemas: schema_mariadb, schema_oracle, schema_maxdb. But eventually we'll turn then into real databases on disk. So the code below compares names according to the filesystem case sensitivity, like it is done for regular databases. Note, this is different to information_schema, whose name is always case insensitive. This is intentional! The assymetry will be gone when we'll implement SQL standard regular and delimited identifiers. */ bool eq_name(const LEX_CSTRING &name) const { return !table_alias_charset->strnncoll(m_name.str, m_name.length, name.str, name.length); } static Schema *find_by_name(const LEX_CSTRING &name); static Schema *find_implied(THD *thd); }; extern Schema mariadb_schema; extern const Schema &oracle_schema_ref; #endif // SQL_SCHEMA_H_INCLUDED mysql/server/private/item_jsonfunc.h000064400000053764151027430560013727 0ustar00#ifndef ITEM_JSONFUNC_INCLUDED #define ITEM_JSONFUNC_INCLUDED /* Copyright (c) 2016, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* This file defines all JSON functions */ #include #include "item_cmpfunc.h" // Item_bool_func #include "item_strfunc.h" // Item_str_func #include "item_sum.h" #include "sql_type_json.h" class json_path_with_flags { public: json_path_t p; bool constant; bool parsed; json_path_step_t *cur_step; void set_constant_flag(bool s_constant) { constant= s_constant; parsed= FALSE; } }; void report_path_error_ex(const char *ps, json_path_t *p, const char *fname, int n_param, Sql_condition::enum_warning_level lv); void report_json_error_ex(const char *js, json_engine_t *je, const char *fname, int n_param, Sql_condition::enum_warning_level lv); class Json_engine_scan: public json_engine_t { public: Json_engine_scan(CHARSET_INFO *i_cs, const uchar *str, const uchar *end) { json_scan_start(this, i_cs, str, end); } Json_engine_scan(const String &str) :Json_engine_scan(str.charset(), (const uchar *) str.ptr(), (const uchar *) str.end()) { } bool check_and_get_value_scalar(String *res, int *error); bool check_and_get_value_complex(String *res, int *error); }; class Json_path_extractor: public json_path_with_flags { protected: String tmp_js, tmp_path; virtual ~Json_path_extractor() { } virtual bool check_and_get_value(Json_engine_scan *je, String *to, int *error)=0; bool extract(String *to, Item *js, Item *jp, CHARSET_INFO *cs); }; class Item_func_json_valid: public Item_bool_func { protected: String tmp_value; public: Item_func_json_valid(THD *thd, Item *json) : Item_bool_func(thd, json) {} bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_valid") }; return name; } bool fix_length_and_dec() override { if (Item_bool_func::fix_length_and_dec()) return TRUE; set_maybe_null(); return FALSE; } bool set_format_by_check_constraint(Send_field_extended_metadata *to) const override { static const Lex_cstring fmt(STRING_WITH_LEN("json")); return to->set_format_name(fmt); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } enum Functype functype() const override { return JSON_VALID_FUNC; } }; class Item_func_json_exists: public Item_bool_func { protected: json_path_with_flags path; String tmp_js, tmp_path; public: Item_func_json_exists(THD *thd, Item *js, Item *i_path): Item_bool_func(thd, js, i_path) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_exists") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool val_bool() override; }; class Item_json_func: public Item_str_func { public: Item_json_func(THD *thd) :Item_str_func(thd) { } Item_json_func(THD *thd, Item *a) :Item_str_func(thd, a) { } Item_json_func(THD *thd, Item *a, Item *b) :Item_str_func(thd, a, b) { } Item_json_func(THD *thd, List &list) :Item_str_func(thd, list) { } const Type_handler *type_handler() const override { return Type_handler_json_common::json_type_handler(max_length); } }; class Item_func_json_value: public Item_str_func, public Json_path_extractor { public: Item_func_json_value(THD *thd, Item *js, Item *i_path): Item_str_func(thd, js, i_path) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_value") }; return name; } bool fix_length_and_dec() override ; String *val_str(String *to) override { null_value= Json_path_extractor::extract(to, args[0], args[1], collation.collation); return null_value ? NULL : to; } bool check_and_get_value(Json_engine_scan *je, String *res, int *error) override { return je->check_and_get_value_scalar(res, error); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_query: public Item_json_func, public Json_path_extractor { public: Item_func_json_query(THD *thd, Item *js, Item *i_path): Item_json_func(thd, js, i_path) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_query") }; return name; } bool fix_length_and_dec() override; String *val_str(String *to) override { null_value= Json_path_extractor::extract(to, args[0], args[1], collation.collation); return null_value ? NULL : to; } bool check_and_get_value(Json_engine_scan *je, String *res, int *error) override { return je->check_and_get_value_complex(res, error); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_quote: public Item_str_func { protected: String tmp_s; public: Item_func_json_quote(THD *thd, Item *s): Item_str_func(thd, s) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_quote") }; return name; } bool fix_length_and_dec() override; String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_unquote: public Item_str_func { protected: String tmp_s; String *read_json(json_engine_t *je); public: Item_func_json_unquote(THD *thd, Item *s): Item_str_func(thd, s) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_unquote") }; return name; } bool fix_length_and_dec() override; String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_json_str_multipath: public Item_json_func { protected: json_path_with_flags *paths; String *tmp_paths; private: /** Number of paths returned by calling virtual method get_n_paths() and remembered inside fix_fields(). It is used by the virtual destructor ~Item_json_str_multipath() to iterate along allocated memory chunks stored in the array tmp_paths and free every of them. The virtual method get_n_paths() can't be used for this goal from within virtual destructor. We could get rid of the virtual method get_n_paths() and store the number of paths directly in the constructor of classes derived from the class Item_json_str_multipath but presence of the method get_n_paths() allows to check invariant that the number of arguments not changed between sequential runs of the same prepared statement that seems to be useful. */ uint n_paths; public: Item_json_str_multipath(THD *thd, List &list): Item_json_func(thd, list), paths(NULL), tmp_paths(0), n_paths(0) {} virtual ~Item_json_str_multipath(); bool fix_fields(THD *thd, Item **ref) override; virtual uint get_n_paths() const = 0; }; class Item_func_json_extract: public Item_json_str_multipath { protected: String tmp_js; public: String *read_json(String *str, json_value_types *type, char **out_val, int *value_len); Item_func_json_extract(THD *thd, List &list): Item_json_str_multipath(thd, list) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_extract") }; return name; } enum Functype functype() const override { return JSON_EXTRACT_FUNC; } bool fix_length_and_dec() override; String *val_str(String *) override; longlong val_int() override; double val_real() override; my_decimal *val_decimal(my_decimal *) override; uint get_n_paths() const override { return arg_count - 1; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_contains: public Item_bool_func { protected: String tmp_js; json_path_with_flags path; String tmp_path; bool a2_constant, a2_parsed; String tmp_val, *val; public: Item_func_json_contains(THD *thd, List &list): Item_bool_func(thd, list) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_contains") }; return name; } bool fix_length_and_dec() override; bool val_bool() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_contains_path: public Item_bool_func { protected: String tmp_js; json_path_with_flags *paths; String *tmp_paths; bool mode_one; bool ooa_constant, ooa_parsed; bool *p_found; public: Item_func_json_contains_path(THD *thd, List &list): Item_bool_func(thd, list), tmp_paths(0) {} virtual ~Item_func_json_contains_path(); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_contains_path") }; return name; } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; bool val_bool() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_array: public Item_json_func { protected: String tmp_val; ulong result_limit; public: Item_func_json_array(THD *thd): Item_json_func(thd) {} Item_func_json_array(THD *thd, List &list): Item_json_func(thd, list) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_array") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_array_append: public Item_json_str_multipath { protected: String tmp_js; String tmp_val; public: Item_func_json_array_append(THD *thd, List &list): Item_json_str_multipath(thd, list) {} bool fix_length_and_dec() override; String *val_str(String *) override; uint get_n_paths() const override { return arg_count/2; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_array_append") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_array_insert: public Item_func_json_array_append { public: Item_func_json_array_insert(THD *thd, List &list): Item_func_json_array_append(thd, list) {} String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_array_insert") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_object: public Item_func_json_array { public: Item_func_json_object(THD *thd): Item_func_json_array(thd) {} Item_func_json_object(THD *thd, List &list): Item_func_json_array(thd, list) {} String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_object") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_merge: public Item_func_json_array { protected: String tmp_js1, tmp_js2; public: Item_func_json_merge(THD *thd, List &list): Item_func_json_array(thd, list) {} String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_merge_preserve") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_merge_patch: public Item_func_json_merge { public: Item_func_json_merge_patch(THD *thd, List &list): Item_func_json_merge(thd, list) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_merge_patch") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_length: public Item_long_func { bool check_arguments() const override { const LEX_CSTRING name= func_name_cstring(); if (arg_count == 0 || arg_count > 2) { my_error(ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT, MYF(0), name.str); return true; } return args[0]->check_type_can_return_text(name) || (arg_count > 1 && args[1]->check_type_general_purpose_string(name)); } protected: json_path_with_flags path; String tmp_js; String tmp_path; public: Item_func_json_length(THD *thd, List &list): Item_long_func(thd, list) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_length") }; return name; } bool fix_length_and_dec() override; longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_depth: public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_text(func_name_cstring()); } protected: String tmp_js; public: Item_func_json_depth(THD *thd, Item *js): Item_long_func(thd, js) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_depth") }; return name; } bool fix_length_and_dec() override { max_length= 10; return FALSE; } longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_type: public Item_str_func { protected: String tmp_js; public: Item_func_json_type(THD *thd, Item *js): Item_str_func(thd, js) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_type") }; return name; } bool fix_length_and_dec() override; String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_insert: public Item_json_str_multipath { protected: String tmp_js; String tmp_val; bool mode_insert, mode_replace; public: Item_func_json_insert(bool i_mode, bool r_mode, THD *thd, List &list): Item_json_str_multipath(thd, list), mode_insert(i_mode), mode_replace(r_mode) {} bool fix_length_and_dec() override; String *val_str(String *) override; uint get_n_paths() const override { return arg_count/2; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING json_set= {STRING_WITH_LEN("json_set") }; static LEX_CSTRING json_insert= {STRING_WITH_LEN("json_insert") }; static LEX_CSTRING json_replace= {STRING_WITH_LEN("json_replace") }; return (mode_insert ? (mode_replace ? json_set : json_insert) : json_replace); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_remove: public Item_json_str_multipath { protected: String tmp_js; public: Item_func_json_remove(THD *thd, List &list): Item_json_str_multipath(thd, list) {} bool fix_length_and_dec() override; String *val_str(String *) override; uint get_n_paths() const override { return arg_count - 1; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_remove") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_keys: public Item_str_func { protected: json_path_with_flags path; String tmp_js, tmp_path; public: Item_func_json_keys(THD *thd, List &list): Item_str_func(thd, list) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_keys") }; return name; } bool fix_length_and_dec() override; String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_search: public Item_json_str_multipath { protected: String tmp_js, tmp_path, esc_value; bool mode_one; bool ooa_constant, ooa_parsed; int escape; int n_path_found; json_path_t sav_path; int compare_json_value_wild(json_engine_t *je, const String *cmp_str); public: Item_func_json_search(THD *thd, List &list): Item_json_str_multipath(thd, list) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_search") }; return name; } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; String *val_str(String *) override; uint get_n_paths() const override { return arg_count > 4 ? arg_count - 4 : 0; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_format: public Item_json_func { public: enum formats { NONE, COMPACT, LOOSE, DETAILED }; protected: formats fmt; String tmp_js; public: Item_func_json_format(THD *thd, Item *js, formats format): Item_json_func(thd, js), fmt(format) {} Item_func_json_format(THD *thd, List &list): Item_json_func(thd, list), fmt(DETAILED) {} LEX_CSTRING func_name_cstring() const override; bool fix_length_and_dec() override; String *val_str(String *str) override; String *val_json(String *str) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_arrayagg : public Item_func_group_concat { protected: /* Overrides Item_func_group_concat::skip_nulls() NULL-s should be added to the result as JSON null value. */ bool skip_nulls() const override { return false; } String *get_str_from_item(Item *i, String *tmp) override; String *get_str_from_field(Item *i, Field *f, String *tmp, const uchar *key, size_t offset) override; void cut_max_length(String *result, uint old_length, uint max_length) const override; public: String m_tmp_json; /* Used in get_str_from_*.. */ Item_func_json_arrayagg(THD *thd, Name_resolution_context *context_arg, bool is_distinct, List *is_select, const SQL_I_List &is_order, String *is_separator, bool limit_clause, Item *row_limit, Item *offset_limit): Item_func_group_concat(thd, context_arg, is_distinct, is_select, is_order, is_separator, limit_clause, row_limit, offset_limit) { } Item_func_json_arrayagg(THD *thd, Item_func_json_arrayagg *item) : Item_func_group_concat(thd, item) {} const Type_handler *type_handler() const override { return Type_handler_json_common::json_type_handler_sum(this); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_arrayagg(") }; return name; } bool fix_fields(THD *thd, Item **ref) override; enum Sumfunctype sum_func() const override { return JSON_ARRAYAGG_FUNC; } String* val_str(String *str) override; Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_json_objectagg : public Item_sum { String result; public: Item_func_json_objectagg(THD *thd, Item *key, Item *value) : Item_sum(thd, key, value) { quick_group= FALSE; result.append('{'); } Item_func_json_objectagg(THD *thd, Item_func_json_objectagg *item); void cleanup() override; enum Sumfunctype sum_func () const override { return JSON_OBJECTAGG_FUNC;} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("json_objectagg") }; return name; } const Type_handler *type_handler() const override { return Type_handler_json_common::json_type_handler_sum(this); } void clear() override; bool add() override; void reset_field() override { DBUG_ASSERT(0); } // not used void update_field() override { DBUG_ASSERT(0); } // not used bool fix_fields(THD *,Item **) override; double val_real() override { return 0.0; } longlong val_int() override { return 0; } my_decimal *val_decimal(my_decimal *decimal_value) override { my_decimal_set_zero(decimal_value); return decimal_value; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_string(thd, ltime, fuzzydate); } String* val_str(String* str) override; Item *copy_or_same(THD* thd) override; void no_rows_in_result() override {} Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; extern bool is_json_type(const Item *item); #endif /* ITEM_JSONFUNC_INCLUDED */ mysql/server/private/backup.h000064400000003247151027430560012320 0ustar00#ifndef BACKUP_INCLUDED #define BACKUP_INCLUDED /* Copyright (c) 2018, MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ enum backup_stages { BACKUP_START, BACKUP_FLUSH, BACKUP_WAIT_FOR_FLUSH, BACKUP_LOCK_COMMIT, BACKUP_END, BACKUP_FINISHED }; extern TYPELIB backup_stage_names; struct backup_log_info { LEX_CSTRING query; LEX_CUSTRING org_table_id; /* Unique id from frm */ LEX_CSTRING org_database, org_table; LEX_CSTRING org_storage_engine_name; LEX_CSTRING new_database, new_table; LEX_CSTRING new_storage_engine_name; LEX_CUSTRING new_table_id; /* Unique id from frm */ bool org_partitioned; bool new_partitioned; }; void backup_init(); bool run_backup_stage(THD *thd, backup_stages stage); bool backup_end(THD *thd); void backup_set_alter_copy_lock(THD *thd, TABLE *altered_table); bool backup_reset_alter_copy_lock(THD *thd); bool backup_lock(THD *thd, TABLE_LIST *table); void backup_unlock(THD *thd); void backup_log_ddl(const backup_log_info *info); #endif /* BACKUP_INCLUDED */ mysql/server/private/lock.h000064400000004233151027430560011777 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef LOCK_INCLUDED #define LOCK_INCLUDED #include "thr_lock.h" /* thr_lock_type */ #include "mdl.h" // Forward declarations struct TABLE; struct TABLE_LIST; class THD; typedef struct st_mysql_lock MYSQL_LOCK; MYSQL_LOCK *mysql_lock_tables(THD *thd, TABLE **table, uint count, uint flags); bool mysql_lock_tables(THD *thd, MYSQL_LOCK *sql_lock, uint flags); int mysql_unlock_tables(THD *thd, MYSQL_LOCK *sql_lock, bool free_lock); int mysql_unlock_tables(THD *thd, MYSQL_LOCK *sql_lock); int mysql_unlock_read_tables(THD *thd, MYSQL_LOCK *sql_lock); int mysql_unlock_some_tables(THD *thd, TABLE **table,uint count, uint flag); int mysql_lock_remove(THD *thd, MYSQL_LOCK *locked,TABLE *table); bool mysql_lock_abort_for_thread(THD *thd, TABLE *table); MYSQL_LOCK *mysql_lock_merge(MYSQL_LOCK *a,MYSQL_LOCK *b); /* Lock based on name */ bool lock_schema_name(THD *thd, const char *db); /* Lock based on stored routine name */ bool lock_object_name(THD *thd, MDL_key::enum_mdl_namespace mdl_type, const char *db, const char *name); /* flags for get_lock_data */ #define GET_LOCK_UNLOCK 0 #define GET_LOCK_STORE_LOCKS 1 #define GET_LOCK_ACTION_MASK 1 #define GET_LOCK_ON_THD (1 << 1) #define GET_LOCK_SKIP_SEQUENCES (1 << 2) MYSQL_LOCK *get_lock_data(THD *thd, TABLE **table_ptr, uint count, uint flags); void reset_lock_data(MYSQL_LOCK *sql_lock, bool unlock); #endif /* LOCK_INCLUDED */ mysql/server/private/sql_test.h000064400000003065151027430560012707 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_TEST_INCLUDED #define SQL_TEST_INCLUDED #include "mysqld.h" #include "opt_trace_context.h" class JOIN; struct TABLE_LIST; typedef class Item COND; typedef class st_select_lex SELECT_LEX; struct SORT_FIELD; #ifndef DBUG_OFF void print_where(COND *cond,const char *info, enum_query_type query_type); void TEST_filesort(SORT_FIELD *sortorder,uint s_length); void TEST_join(JOIN *join); void print_plan(JOIN* join,uint idx, double record_count, double read_time, double current_read_time, const char *info); void print_keyuse_array(DYNAMIC_ARRAY *keyuse_array); void print_sjm(SJ_MATERIALIZATION_INFO *sjm); void dump_TABLE_LIST_graph(SELECT_LEX *select_lex, TABLE_LIST* tl); #endif void print_keyuse_array_for_trace(THD *thd, DYNAMIC_ARRAY *keyuse_array); void mysql_print_status(); #endif /* SQL_TEST_INCLUDED */ mysql/server/private/sql_cmd.h000064400000022037151027430560012473 0ustar00/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Representation of an SQL command. */ #ifndef SQL_CMD_INCLUDED #define SQL_CMD_INCLUDED /* When a command is added here, be sure it's also added in mysqld.cc in "struct show_var_st status_vars[]= {" ... If the command returns a result set or is not allowed in stored functions or triggers, please also make sure that sp_get_flags_for_command (sp_head.cc) returns proper flags for the added SQLCOM_. */ enum enum_sql_command { SQLCOM_SELECT, SQLCOM_CREATE_TABLE, SQLCOM_CREATE_INDEX, SQLCOM_ALTER_TABLE, SQLCOM_UPDATE, SQLCOM_INSERT, SQLCOM_INSERT_SELECT, SQLCOM_DELETE, SQLCOM_TRUNCATE, SQLCOM_DROP_TABLE, SQLCOM_DROP_INDEX, SQLCOM_SHOW_DATABASES, SQLCOM_SHOW_TABLES, SQLCOM_SHOW_FIELDS, SQLCOM_SHOW_KEYS, SQLCOM_SHOW_VARIABLES, SQLCOM_SHOW_STATUS, SQLCOM_SHOW_ENGINE_LOGS, SQLCOM_SHOW_ENGINE_STATUS, SQLCOM_SHOW_ENGINE_MUTEX, SQLCOM_SHOW_PROCESSLIST, SQLCOM_SHOW_BINLOG_STAT, SQLCOM_SHOW_SLAVE_STAT, SQLCOM_SHOW_GRANTS, SQLCOM_SHOW_CREATE, SQLCOM_SHOW_CHARSETS, SQLCOM_SHOW_COLLATIONS, SQLCOM_SHOW_CREATE_DB, SQLCOM_SHOW_TABLE_STATUS, SQLCOM_SHOW_TRIGGERS, SQLCOM_LOAD,SQLCOM_SET_OPTION,SQLCOM_LOCK_TABLES,SQLCOM_UNLOCK_TABLES, SQLCOM_GRANT, SQLCOM_CHANGE_DB, SQLCOM_CREATE_DB, SQLCOM_DROP_DB, SQLCOM_ALTER_DB, SQLCOM_REPAIR, SQLCOM_REPLACE, SQLCOM_REPLACE_SELECT, SQLCOM_CREATE_FUNCTION, SQLCOM_DROP_FUNCTION, SQLCOM_REVOKE,SQLCOM_OPTIMIZE, SQLCOM_CHECK, SQLCOM_ASSIGN_TO_KEYCACHE, SQLCOM_PRELOAD_KEYS, SQLCOM_FLUSH, SQLCOM_KILL, SQLCOM_ANALYZE, SQLCOM_ROLLBACK, SQLCOM_ROLLBACK_TO_SAVEPOINT, SQLCOM_COMMIT, SQLCOM_SAVEPOINT, SQLCOM_RELEASE_SAVEPOINT, SQLCOM_SLAVE_START, SQLCOM_SLAVE_STOP, SQLCOM_BEGIN, SQLCOM_CHANGE_MASTER, SQLCOM_RENAME_TABLE, SQLCOM_RESET, SQLCOM_PURGE, SQLCOM_PURGE_BEFORE, SQLCOM_SHOW_BINLOGS, SQLCOM_SHOW_OPEN_TABLES, SQLCOM_HA_OPEN, SQLCOM_HA_CLOSE, SQLCOM_HA_READ, SQLCOM_SHOW_SLAVE_HOSTS, SQLCOM_DELETE_MULTI, SQLCOM_UPDATE_MULTI, SQLCOM_SHOW_BINLOG_EVENTS, SQLCOM_DO, SQLCOM_SHOW_WARNS, SQLCOM_EMPTY_QUERY, SQLCOM_SHOW_ERRORS, SQLCOM_SHOW_STORAGE_ENGINES, SQLCOM_SHOW_PRIVILEGES, SQLCOM_HELP, SQLCOM_CREATE_USER, SQLCOM_DROP_USER, SQLCOM_RENAME_USER, SQLCOM_REVOKE_ALL, SQLCOM_CHECKSUM, SQLCOM_CREATE_PROCEDURE, SQLCOM_CREATE_SPFUNCTION, SQLCOM_CALL, SQLCOM_DROP_PROCEDURE, SQLCOM_ALTER_PROCEDURE,SQLCOM_ALTER_FUNCTION, SQLCOM_SHOW_CREATE_PROC, SQLCOM_SHOW_CREATE_FUNC, SQLCOM_SHOW_STATUS_PROC, SQLCOM_SHOW_STATUS_FUNC, SQLCOM_PREPARE, SQLCOM_EXECUTE, SQLCOM_DEALLOCATE_PREPARE, SQLCOM_CREATE_VIEW, SQLCOM_DROP_VIEW, SQLCOM_CREATE_TRIGGER, SQLCOM_DROP_TRIGGER, SQLCOM_XA_START, SQLCOM_XA_END, SQLCOM_XA_PREPARE, SQLCOM_XA_COMMIT, SQLCOM_XA_ROLLBACK, SQLCOM_XA_RECOVER, SQLCOM_SHOW_PROC_CODE, SQLCOM_SHOW_FUNC_CODE, SQLCOM_ALTER_TABLESPACE, SQLCOM_INSTALL_PLUGIN, SQLCOM_UNINSTALL_PLUGIN, SQLCOM_SHOW_AUTHORS, SQLCOM_BINLOG_BASE64_EVENT, SQLCOM_SHOW_PLUGINS, SQLCOM_SHOW_CONTRIBUTORS, SQLCOM_CREATE_SERVER, SQLCOM_DROP_SERVER, SQLCOM_ALTER_SERVER, SQLCOM_CREATE_EVENT, SQLCOM_ALTER_EVENT, SQLCOM_DROP_EVENT, SQLCOM_SHOW_CREATE_EVENT, SQLCOM_SHOW_EVENTS, SQLCOM_SHOW_CREATE_TRIGGER, SQLCOM_ALTER_DB_UPGRADE, SQLCOM_SHOW_PROFILE, SQLCOM_SHOW_PROFILES, SQLCOM_SIGNAL, SQLCOM_RESIGNAL, SQLCOM_SHOW_RELAYLOG_EVENTS, SQLCOM_GET_DIAGNOSTICS, SQLCOM_SLAVE_ALL_START, SQLCOM_SLAVE_ALL_STOP, SQLCOM_SHOW_EXPLAIN, SQLCOM_SHUTDOWN, SQLCOM_CREATE_ROLE, SQLCOM_DROP_ROLE, SQLCOM_GRANT_ROLE, SQLCOM_REVOKE_ROLE, SQLCOM_COMPOUND, SQLCOM_SHOW_GENERIC, SQLCOM_ALTER_USER, SQLCOM_SHOW_CREATE_USER, SQLCOM_EXECUTE_IMMEDIATE, SQLCOM_CREATE_SEQUENCE, SQLCOM_DROP_SEQUENCE, SQLCOM_ALTER_SEQUENCE, SQLCOM_CREATE_PACKAGE, SQLCOM_DROP_PACKAGE, SQLCOM_CREATE_PACKAGE_BODY, SQLCOM_DROP_PACKAGE_BODY, SQLCOM_SHOW_CREATE_PACKAGE, SQLCOM_SHOW_CREATE_PACKAGE_BODY, SQLCOM_SHOW_STATUS_PACKAGE, SQLCOM_SHOW_STATUS_PACKAGE_BODY, SQLCOM_SHOW_PACKAGE_BODY_CODE, SQLCOM_BACKUP, SQLCOM_BACKUP_LOCK, /* When a command is added here, be sure it's also added in mysqld.cc in "struct show_var_st com_status_vars[]= {" ... */ /* This should be the last !!! */ SQLCOM_END }; class Storage_engine_name { protected: LEX_CSTRING m_storage_engine_name; public: Storage_engine_name() { m_storage_engine_name.str= NULL; m_storage_engine_name.length= 0; } Storage_engine_name(const LEX_CSTRING &name) :m_storage_engine_name(name) { } Storage_engine_name(const LEX_STRING &name) { m_storage_engine_name.str= name.str; m_storage_engine_name.length= name.length; } bool resolve_storage_engine_with_error(THD *thd, handlerton **ha, bool tmp_table); bool is_set() { return m_storage_engine_name.str != NULL; } const LEX_CSTRING *name() const { return &m_storage_engine_name; } }; /** @class Sql_cmd - Representation of an SQL command. This class is an interface between the parser and the runtime. The parser builds the appropriate derived classes of Sql_cmd to represent a SQL statement in the parsed tree. The execute() method in the derived classes of Sql_cmd contain the runtime implementation. Note that this interface is used for SQL statements recently implemented, the code for older statements tend to load the LEX structure with more attributes instead. Implement new statements by sub-classing Sql_cmd, as this improves code modularity (see the 'big switch' in dispatch_command()), and decreases the total size of the LEX structure (therefore saving memory in stored programs). The recommended name of a derived class of Sql_cmd is Sql_cmd_. Notice that the Sql_cmd class should not be confused with the Statement class. Statement is a class that is used to manage an SQL command or a set of SQL commands. When the SQL statement text is analyzed, the parser will create one or more Sql_cmd objects to represent the actual SQL commands. */ class Sql_cmd : public Sql_alloc { private: Sql_cmd(const Sql_cmd &); // No copy constructor wanted void operator=(Sql_cmd &); // No assignment operator wanted public: /** @brief Return the command code for this statement */ virtual enum_sql_command sql_command_code() const = 0; /** Execute this SQL statement. @param thd the current thread. @retval false on success. @retval true on error */ virtual bool execute(THD *thd) = 0; virtual Storage_engine_name *option_storage_engine_name() { return NULL; } protected: Sql_cmd() = default; virtual ~Sql_cmd() { /* Sql_cmd objects are allocated in thd->mem_root. In MySQL, the C++ destructor is never called, the underlying MEM_ROOT is simply destroyed instead. Do not rely on the destructor for any cleanup. */ DBUG_ASSERT(FALSE); } }; class Sql_cmd_show_slave_status: public Sql_cmd { protected: bool show_all_slaves_status; public: Sql_cmd_show_slave_status() :show_all_slaves_status(false) {} Sql_cmd_show_slave_status(bool status_all) :show_all_slaves_status(status_all) {} enum_sql_command sql_command_code() const override { return SQLCOM_SHOW_SLAVE_STAT; } bool execute(THD *thd) override; bool is_show_all_slaves_stat() { return show_all_slaves_status; } }; class Sql_cmd_create_table_like: public Sql_cmd, public Storage_engine_name { public: Storage_engine_name *option_storage_engine_name() override { return this; } bool execute(THD *thd) override; }; class Sql_cmd_create_table: public Sql_cmd_create_table_like { public: enum_sql_command sql_command_code() const override { return SQLCOM_CREATE_TABLE; } }; class Sql_cmd_create_sequence: public Sql_cmd_create_table_like { public: enum_sql_command sql_command_code() const override { return SQLCOM_CREATE_SEQUENCE; } }; /** Sql_cmd_call represents the CALL statement. */ class Sql_cmd_call : public Sql_cmd { public: class sp_name *m_name; const class Sp_handler *m_handler; Sql_cmd_call(class sp_name *name, const class Sp_handler *handler) :m_name(name), m_handler(handler) {} virtual ~Sql_cmd_call() = default; /** Execute a CALL statement at runtime. @param thd the current thread. @return false on success. */ bool execute(THD *thd) override; enum_sql_command sql_command_code() const override { return SQLCOM_CALL; } }; #endif // SQL_CMD_INCLUDED mysql/server/private/sql_table.h000064400000022614151027430560013020 0ustar00/* Copyright (c) 2006, 2014, Oracle and/or its affiliates. Copyright (c) 2011, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_TABLE_INCLUDED #define SQL_TABLE_INCLUDED #include // pthread_mutex_t #include "m_string.h" // LEX_CUSTRING class Alter_info; class Alter_table_ctx; class Column_definition; class Create_field; struct TABLE_LIST; class THD; struct TABLE; struct handlerton; class handler; class String; typedef struct st_ha_check_opt HA_CHECK_OPT; struct HA_CREATE_INFO; struct Table_specification_st; typedef struct st_key KEY; typedef struct st_key_cache KEY_CACHE; typedef struct st_lock_param_type ALTER_PARTITION_PARAM_TYPE; typedef struct st_order ORDER; typedef struct st_ddl_log_state DDL_LOG_STATE; enum enum_explain_filename_mode { EXPLAIN_ALL_VERBOSE= 0, EXPLAIN_PARTITIONS_VERBOSE, EXPLAIN_PARTITIONS_AS_COMMENT }; /* depends on errmsg.txt Database `db`, Table `t` ... */ #define EXPLAIN_FILENAME_MAX_EXTRA_LENGTH 63 #define WFRM_WRITE_SHADOW 1 #define WFRM_INSTALL_SHADOW 2 #define WFRM_KEEP_SHARE 4 /* Flags for conversion functions. */ static const uint FN_FROM_IS_TMP= 1 << 0; static const uint FN_TO_IS_TMP= 1 << 1; static const uint FN_IS_TMP= FN_FROM_IS_TMP | FN_TO_IS_TMP; static const uint NO_FRM_RENAME= 1 << 2; static const uint FRM_ONLY= 1 << 3; /** Don't remove table in engine. Remove only .FRM and maybe .PAR files. */ static const uint NO_HA_TABLE= 1 << 4; /** Don't resolve MySQL's fake "foo.sym" symbolic directory names. */ static const uint SKIP_SYMDIR_ACCESS= 1 << 5; /** Don't check foreign key constraints while renaming table */ static const uint NO_FK_CHECKS= 1 << 6; /* Don't delete .par table in quick_rm_table() */ static const uint NO_PAR_TABLE= 1 << 7; uint filename_to_tablename(const char *from, char *to, size_t to_length, bool stay_quiet = false); uint tablename_to_filename(const char *from, char *to, size_t to_length); uint check_n_cut_mysql50_prefix(const char *from, char *to, size_t to_length); bool check_mysql50_prefix(const char *name); uint build_table_filename(char *buff, size_t bufflen, const char *db, const char *table, const char *ext, uint flags); uint build_table_shadow_filename(char *buff, size_t bufflen, ALTER_PARTITION_PARAM_TYPE *lpt); void build_lower_case_table_filename(char *buff, size_t bufflen, const LEX_CSTRING *db, const LEX_CSTRING *table, uint flags); uint build_tmptable_filename(THD* thd, char *buff, size_t bufflen); bool mysql_create_table(THD *thd, TABLE_LIST *create_table, Table_specification_st *create_info, Alter_info *alter_info); bool add_keyword_to_query(THD *thd, String *result, const LEX_CSTRING *keyword, const LEX_CSTRING *add); /* mysql_create_table_no_lock can be called in one of the following mutually exclusive situations: - Just a normal ordinary CREATE TABLE statement that explicitly defines the table structure. - CREATE TABLE ... SELECT. It is special, because only in this case, the list of fields is allowed to have duplicates, as long as one of the duplicates comes from the select list, and the other doesn't. For example in CREATE TABLE t1 (a int(5) NOT NUL) SELECT b+10 as a FROM t2; the list in alter_info->create_list will have two fields `a`. - ALTER TABLE, that creates a temporary table #sql-xxx, which will be later renamed to replace the original table. - ALTER TABLE as above, but which only modifies the frm file, it only creates an frm file for the #sql-xxx, the table in the engine is not created. - Assisted discovery, CREATE TABLE statement without the table structure. These situations are distinguished by the following "create table mode" values, where a CREATE ... SELECT is denoted by any non-negative number (which should be the number of fields in the SELECT ... part), and other cases use constants as defined below. */ #define C_CREATE_SELECT(X) ((X) > 0 ? (X) : 0) #define C_ORDINARY_CREATE 0 #define C_ASSISTED_DISCOVERY -1 #define C_ALTER_TABLE -2 #define C_ALTER_TABLE_FRM_ONLY -3 int mysql_create_table_no_lock(THD *thd, DDL_LOG_STATE *ddl_log_state, DDL_LOG_STATE *ddl_log_state_rm, Table_specification_st *create_info, Alter_info *alter_info, bool *is_trans, int create_table_mode, TABLE_LIST *table); handler *mysql_create_frm_image(THD *thd, HA_CREATE_INFO *create_info, Alter_info *alter_info, int create_table_mode, KEY **key_info, uint *key_count, LEX_CUSTRING *frm); int mysql_discard_or_import_tablespace(THD *thd, TABLE_LIST *table_list, bool discard); bool mysql_prepare_alter_table(THD *thd, TABLE *table, HA_CREATE_INFO *create_info, Alter_info *alter_info, Alter_table_ctx *alter_ctx); bool mysql_trans_prepare_alter_copy_data(THD *thd); bool mysql_trans_commit_alter_copy_data(THD *thd); bool mysql_alter_table(THD *thd, const LEX_CSTRING *new_db, const LEX_CSTRING *new_name, HA_CREATE_INFO *create_info, TABLE_LIST *table_list, class Recreate_info *recreate_info, Alter_info *alter_info, uint order_num, ORDER *order, bool ignore, bool if_exists); bool mysql_compare_tables(TABLE *table, Alter_info *alter_info, HA_CREATE_INFO *create_info, bool *metadata_equal); bool mysql_recreate_table(THD *thd, TABLE_LIST *table_list, class Recreate_info *recreate_info, bool table_copy); bool mysql_create_like_table(THD *thd, TABLE_LIST *table, TABLE_LIST *src_table, Table_specification_st *create_info); bool mysql_rename_table(handlerton *base, const LEX_CSTRING *old_db, const LEX_CSTRING *old_name, const LEX_CSTRING *new_db, const LEX_CSTRING *new_name, LEX_CUSTRING *id, uint flags); bool mysql_backup_table(THD* thd, TABLE_LIST* table_list); bool mysql_restore_table(THD* thd, TABLE_LIST* table_list); template class List; void fill_checksum_table_metadata_fields(THD *thd, List *fields); bool mysql_checksum_table(THD* thd, TABLE_LIST* table_list, HA_CHECK_OPT* check_opt); bool mysql_rm_table(THD *thd,TABLE_LIST *tables, bool if_exists, bool drop_temporary, bool drop_sequence, bool dont_log_query); int mysql_rm_table_no_locks(THD *thd, TABLE_LIST *tables, const LEX_CSTRING *db, DDL_LOG_STATE *ddl_log_state, bool if_exists, bool drop_temporary, bool drop_view, bool drop_sequence, bool dont_log_query, bool dont_free_locks); bool log_drop_table(THD *thd, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name, const LEX_CSTRING *handler, bool partitioned, const LEX_CUSTRING *id, bool temporary_table); bool quick_rm_table(THD *thd, handlerton *base, const LEX_CSTRING *db, const LEX_CSTRING *table_name, uint flags, const char *table_path=0); void close_cached_table(THD *thd, TABLE *table); void sp_prepare_create_field(THD *thd, Column_definition *sql_field); bool mysql_write_frm(ALTER_PARTITION_PARAM_TYPE *lpt, uint flags); int write_bin_log(THD *thd, bool clear_error, char const *query, ulong query_length, bool is_trans= FALSE); int write_bin_log_with_if_exists(THD *thd, bool clear_error, bool is_trans, bool add_if_exists); void promote_first_timestamp_column(List *column_definitions); /* These prototypes where under INNODB_COMPATIBILITY_HOOKS. */ uint explain_filename(THD* thd, const char *from, char *to, uint to_length, enum_explain_filename_mode explain_mode); extern MYSQL_PLUGIN_IMPORT const LEX_CSTRING primary_key_name; bool check_engine(THD *, const char *, const char *, HA_CREATE_INFO *); #endif /* SQL_TABLE_INCLUDED */ mysql/server/private/handler.h000064400000611465151027430560012477 0ustar00#ifndef HANDLER_INCLUDED #define HANDLER_INCLUDED /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. Copyright (c) 2009, 2023, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Definitions for parameters to do with handler-routines */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_const.h" #include "sql_basic_types.h" #include "mysqld.h" /* server_id */ #include "sql_plugin.h" /* plugin_ref, st_plugin_int, plugin */ #include "thr_lock.h" /* thr_lock_type, THR_LOCK_DATA */ #include "sql_cache.h" #include "structs.h" /* SHOW_COMP_OPTION */ #include "sql_array.h" /* Dynamic_array<> */ #include "mdl.h" #include "vers_string.h" #include "ha_handler_stats.h" #include "sql_analyze_stmt.h" // for Exec_time_tracker #include #include #include #include #include "sql_sequence.h" #include "mem_root_array.h" #include // pair #include /* __attribute__ */ class Alter_info; class Virtual_column_info; class sequence_definition; class Rowid_filter; class Field_string; class Field_varstring; class Field_blob; class Column_definition; // the following is for checking tables #define HA_ADMIN_ALREADY_DONE 1 #define HA_ADMIN_OK 0 #define HA_ADMIN_NOT_IMPLEMENTED -1 #define HA_ADMIN_FAILED -2 #define HA_ADMIN_CORRUPT -3 #define HA_ADMIN_INTERNAL_ERROR -4 #define HA_ADMIN_INVALID -5 #define HA_ADMIN_REJECT -6 #define HA_ADMIN_TRY_ALTER -7 #define HA_ADMIN_WRONG_CHECKSUM -8 #define HA_ADMIN_NOT_BASE_TABLE -9 #define HA_ADMIN_NEEDS_UPGRADE -10 #define HA_ADMIN_NEEDS_ALTER -11 #define HA_ADMIN_NEEDS_CHECK -12 #define HA_ADMIN_COMMIT_ERROR -13 /** Return values for check_if_supported_inplace_alter(). @see check_if_supported_inplace_alter() for description of the individual values. */ enum enum_alter_inplace_result { HA_ALTER_ERROR, HA_ALTER_INPLACE_COPY_NO_LOCK, HA_ALTER_INPLACE_COPY_LOCK, HA_ALTER_INPLACE_NOCOPY_LOCK, HA_ALTER_INPLACE_NOCOPY_NO_LOCK, HA_ALTER_INPLACE_INSTANT, HA_ALTER_INPLACE_NOT_SUPPORTED, HA_ALTER_INPLACE_EXCLUSIVE_LOCK, HA_ALTER_INPLACE_SHARED_LOCK, HA_ALTER_INPLACE_NO_LOCK }; /* Flags for create_partitioning_metadata() */ enum chf_create_flags { CHF_CREATE_FLAG, CHF_DELETE_FLAG, CHF_RENAME_FLAG, CHF_INDEX_FLAG }; /* Bits in table_flags() to show what database can do */ #define HA_NO_TRANSACTIONS (1ULL << 0) /* Doesn't support transactions */ #define HA_PARTIAL_COLUMN_READ (1ULL << 1) /* read may not return all columns */ #define HA_TABLE_SCAN_ON_INDEX (1ULL << 2) /* No separate data/index file */ /* The following should be set if the following is not true when scanning a table with rnd_next() - We will see all rows (including deleted ones) - Row positions are 'table->s->db_record_offset' apart If this flag is not set, filesort will do a position() call for each matched row to be able to find the row later. */ #define HA_REC_NOT_IN_SEQ (1ULL << 3) #define HA_CAN_GEOMETRY (1ULL << 4) /* Reading keys in random order is as fast as reading keys in sort order (Used in records.cc to decide if we should use a record cache and by filesort to decide if we should sort key + data or key + pointer-to-row */ #define HA_FAST_KEY_READ (1ULL << 5) /* Set the following flag if we on delete should force all key to be read and on update read all keys that changes */ #define HA_REQUIRES_KEY_COLUMNS_FOR_DELETE (1ULL << 6) #define HA_NULL_IN_KEY (1ULL << 7) /* One can have keys with NULL */ #define HA_DUPLICATE_POS (1ULL << 8) /* ha_position() gives dup row */ #define HA_NO_BLOBS (1ULL << 9) /* Doesn't support blobs */ #define HA_CAN_INDEX_BLOBS (1ULL << 10) #define HA_AUTO_PART_KEY (1ULL << 11) /* auto-increment in multi-part key */ /* The engine requires every table to have a user-specified PRIMARY KEY. Do not set the flag if the engine can generate a hidden primary key internally. This flag is ignored if a SEQUENCE is created (which, in turn, needs HA_CAN_TABLES_WITHOUT_ROLLBACK flag) */ #define HA_REQUIRE_PRIMARY_KEY (1ULL << 12) #define HA_STATS_RECORDS_IS_EXACT (1ULL << 13) /* stats.records is exact */ /* INSERT_DELAYED only works with handlers that uses MySQL internal table level locks */ #define HA_CAN_INSERT_DELAYED (1ULL << 14) /* If we get the primary key columns for free when we do an index read (usually, it also implies that HA_PRIMARY_KEY_REQUIRED_FOR_POSITION flag is set). */ #define HA_PRIMARY_KEY_IN_READ_INDEX (1ULL << 15) /* If HA_PRIMARY_KEY_REQUIRED_FOR_POSITION is set, it means that to position() uses a primary key given by the record argument. Without primary key, we can't call position(). If not set, the position is returned as the current rows position regardless of what argument is given. */ #define HA_PRIMARY_KEY_REQUIRED_FOR_POSITION (1ULL << 16) #define HA_CAN_RTREEKEYS (1ULL << 17) #define HA_NOT_DELETE_WITH_CACHE (1ULL << 18) /* unused */ /* The following is we need to a primary key to delete (and update) a row. If there is no primary key, all columns needs to be read on update and delete */ #define HA_PRIMARY_KEY_REQUIRED_FOR_DELETE (1ULL << 19) #define HA_NO_PREFIX_CHAR_KEYS (1ULL << 20) #define HA_CAN_FULLTEXT (1ULL << 21) #define HA_CAN_SQL_HANDLER (1ULL << 22) #define HA_NO_AUTO_INCREMENT (1ULL << 23) /* Has automatic checksums and uses the old checksum format */ #define HA_HAS_OLD_CHECKSUM (1ULL << 24) /* Table data are stored in separate files (for lower_case_table_names) */ #define HA_FILE_BASED (1ULL << 26) #define HA_CAN_BIT_FIELD (1ULL << 28) /* supports bit fields */ #define HA_NEED_READ_RANGE_BUFFER (1ULL << 29) /* for read_multi_range */ #define HA_ANY_INDEX_MAY_BE_UNIQUE (1ULL << 30) #define HA_NO_COPY_ON_ALTER (1ULL << 31) #define HA_HAS_RECORDS (1ULL << 32) /* records() gives exact count*/ /* Has it's own method of binlog logging */ #define HA_HAS_OWN_BINLOGGING (1ULL << 33) /* Engine is capable of row-format and statement-format logging, respectively */ #define HA_BINLOG_ROW_CAPABLE (1ULL << 34) #define HA_BINLOG_STMT_CAPABLE (1ULL << 35) /* When a multiple key conflict happens in a REPLACE command mysql expects the conflicts to be reported in the ascending order of key names. For e.g. CREATE TABLE t1 (a INT, UNIQUE (a), b INT NOT NULL, UNIQUE (b), c INT NOT NULL, INDEX(c)); REPLACE INTO t1 VALUES (1,1,1),(2,2,2),(2,1,3); MySQL expects the conflict with 'a' to be reported before the conflict with 'b'. If the underlying storage engine does not report the conflicting keys in ascending order, it causes unexpected errors when the REPLACE command is executed. This flag helps the underlying SE to inform the server that the keys are not ordered. */ #define HA_DUPLICATE_KEY_NOT_IN_ORDER (1ULL << 36) /* Engine supports REPAIR TABLE. Used by CHECK TABLE FOR UPGRADE if an incompatible table is detected. If this flag is set, CHECK TABLE FOR UPGRADE will report ER_TABLE_NEEDS_UPGRADE, otherwise ER_TABLE_NEED_REBUILD. */ #define HA_CAN_REPAIR (1ULL << 37) /* Has automatic checksums and uses the new checksum format */ #define HA_HAS_NEW_CHECKSUM (1ULL << 38) #define HA_CAN_VIRTUAL_COLUMNS (1ULL << 39) #define HA_MRR_CANT_SORT (1ULL << 40) /* All of VARCHAR is stored, including bytes after real varchar data */ #define HA_RECORD_MUST_BE_CLEAN_ON_WRITE (1ULL << 41) /* This storage engine supports condition pushdown */ #define HA_CAN_TABLE_CONDITION_PUSHDOWN (1ULL << 42) /* old name for the same flag */ #define HA_MUST_USE_TABLE_CONDITION_PUSHDOWN HA_CAN_TABLE_CONDITION_PUSHDOWN /** The handler supports read before write removal optimization Read before write removal may be used for storage engines which support write without previous read of the row to be updated. Handler returning this flag must implement start_read_removal() and end_read_removal(). The handler may return "fake" rows constructed from the key of the row asked for. This is used to optimize UPDATE and DELETE by reducing the number of roundtrips between handler and storage engine. Example: UPDATE a=1 WHERE pk IN () mysql_update() { if () start_read_removal() -> handler returns true if read removal supported for this table/query while(read_record("pk=")) -> handler returns fake row with column "pk" set to ha_update_row() -> handler sends write "a=1" for row with "pk=" end_read_removal() -> handler returns the number of rows actually written } @note This optimization in combination with batching may be used to remove even more roundtrips. */ #define HA_READ_BEFORE_WRITE_REMOVAL (1ULL << 43) /* Engine supports extended fulltext API */ #define HA_CAN_FULLTEXT_EXT (1ULL << 44) /* Storage engine supports table export using the FLUSH TABLE FOR EXPORT statement (meaning, after this statement one can copy table files out of the datadir and later "import" (somehow) in another MariaDB instance) */ #define HA_CAN_EXPORT (1ULL << 45) /* Storage engine does not require an exclusive metadata lock on the table during optimize. (TODO and repair?). It can allow other connections to open the table. (it does not necessarily mean that other connections can read or modify the table - this is defined by THR locks and the ::store_lock() method). */ #define HA_CONCURRENT_OPTIMIZE (1ULL << 46) /* If the storage engine support tables that will not roll back on commit In addition the table should not lock rows and support READ and WRITE UNCOMMITTED. This is useful for implementing things like SEQUENCE but can also in the future be useful to do logging that should never roll back. */ #define HA_CAN_TABLES_WITHOUT_ROLLBACK (1ULL << 47) /* Mainly for usage by SEQUENCE engine. Setting this flag means that the table will never roll back and that all operations for this table should stored in the non transactional log space that will always be written, even on rollback. */ #define HA_PERSISTENT_TABLE (1ULL << 48) /* If storage engine uses another engine as a base This flag is also needed if the table tries to open the .frm file as part of drop table. */ #define HA_REUSES_FILE_NAMES (1ULL << 49) /* Set of all binlog flags. Currently only contain the capabilities flags. */ #define HA_BINLOG_FLAGS (HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE) /* The following are used by Spider */ #define HA_CAN_FORCE_BULK_UPDATE (1ULL << 50) #define HA_CAN_FORCE_BULK_DELETE (1ULL << 51) #define HA_CAN_DIRECT_UPDATE_AND_DELETE (1ULL << 52) /* The following is for partition handler */ #define HA_CAN_MULTISTEP_MERGE (1LL << 53) /* calling cmp_ref() on the engine is expensive */ #define HA_SLOW_CMP_REF (1ULL << 54) #define HA_CMP_REF_IS_EXPENSIVE HA_SLOW_CMP_REF /** Some engines are unable to provide an efficient implementation for rnd_pos(). Server will try to avoid it, if possible TODO better to do it with cost estimates, not with an explicit flag */ #define HA_SLOW_RND_POS (1ULL << 55) /* Safe for online backup */ #define HA_CAN_ONLINE_BACKUPS (1ULL << 56) /* Support native hash index */ #define HA_CAN_HASH_KEYS (1ULL << 57) #define HA_CRASH_SAFE (1ULL << 58) /* There is no need to evict the table from the table definition cache having run ANALYZE TABLE on it */ #define HA_ONLINE_ANALYZE (1ULL << 59) /* Rowid's are not comparable. This is set if the rowid is unique to the current open handler, like it is with federated where the rowid is a pointer to a local result set buffer. The effect of having this set is that the optimizer will not consider the following optimizations for the table: ror scans, filtering or duplicate weedout */ #define HA_NON_COMPARABLE_ROWID (1ULL << 60) /* Implements SELECT ... FOR UPDATE SKIP LOCKED */ #define HA_CAN_SKIP_LOCKED (1ULL << 61) #define HA_CHECK_UNIQUE_AFTER_WRITE (1ULL << 62) #define HA_LAST_TABLE_FLAG HA_CHECK_UNIQUE_AFTER_WRITE /* bits in index_flags(index_number) for what you can do with index */ #define HA_READ_NEXT 1 /* TODO really use this flag */ #define HA_READ_PREV 2 /* supports ::index_prev */ #define HA_READ_ORDER 4 /* index_next/prev follow sort order */ #define HA_READ_RANGE 8 /* can find all records in a range */ #define HA_ONLY_WHOLE_INDEX 16 /* Can't use part key searches */ #define HA_KEYREAD_ONLY 64 /* Support HA_EXTRA_KEYREAD */ /* Index scan will not return records in rowid order. Not guaranteed to be set for unordered (e.g. HASH) indexes. */ #define HA_KEY_SCAN_NOT_ROR 128 #define HA_DO_INDEX_COND_PUSHDOWN 256 /* Supports Index Condition Pushdown */ /* Data is clustered on this key. This means that when you read the key you also get the row data without any additional disk reads. */ #define HA_CLUSTERED_INDEX 512 #define HA_DO_RANGE_FILTER_PUSHDOWN 1024 /* bits in alter_table_flags: */ /* These bits are set if different kinds of indexes can be created or dropped in-place without re-creating the table using a temporary table. NO_READ_WRITE indicates that the handler needs concurrent reads and writes of table data to be blocked. Partitioning needs both ADD and DROP to be supported by its underlying handlers, due to error handling, see bug#57778. */ #define HA_INPLACE_ADD_INDEX_NO_READ_WRITE (1UL << 0) #define HA_INPLACE_DROP_INDEX_NO_READ_WRITE (1UL << 1) #define HA_INPLACE_ADD_UNIQUE_INDEX_NO_READ_WRITE (1UL << 2) #define HA_INPLACE_DROP_UNIQUE_INDEX_NO_READ_WRITE (1UL << 3) #define HA_INPLACE_ADD_PK_INDEX_NO_READ_WRITE (1UL << 4) #define HA_INPLACE_DROP_PK_INDEX_NO_READ_WRITE (1UL << 5) /* These are set if different kinds of indexes can be created or dropped in-place while still allowing concurrent reads (but not writes) of table data. If a handler is capable of one or more of these, it should also set the corresponding *_NO_READ_WRITE bit(s). */ #define HA_INPLACE_ADD_INDEX_NO_WRITE (1UL << 6) #define HA_INPLACE_DROP_INDEX_NO_WRITE (1UL << 7) #define HA_INPLACE_ADD_UNIQUE_INDEX_NO_WRITE (1UL << 8) #define HA_INPLACE_DROP_UNIQUE_INDEX_NO_WRITE (1UL << 9) #define HA_INPLACE_ADD_PK_INDEX_NO_WRITE (1UL << 10) #define HA_INPLACE_DROP_PK_INDEX_NO_WRITE (1UL << 11) /* HA_PARTITION_FUNCTION_SUPPORTED indicates that the function is supported at all. HA_FAST_CHANGE_PARTITION means that optimised variants of the changes exists but they are not necessarily done online. HA_ONLINE_DOUBLE_WRITE means that the handler supports writing to both the new partition and to the old partitions when updating through the old partitioning schema while performing a change of the partitioning. This means that we can support updating of the table while performing the copy phase of the change. For no lock at all also a double write from new to old must exist and this is not required when this flag is set. This is actually removed even before it was introduced the first time. The new idea is that handlers will handle the lock level already in store_lock for ALTER TABLE partitions. HA_PARTITION_ONE_PHASE is a flag that can be set by handlers that take care of changing the partitions online and in one phase. Thus all phases needed to handle the change are implemented inside the storage engine. The storage engine must also support auto-discovery since the frm file is changed as part of the change and this change must be controlled by the storage engine. A typical engine to support this is NDB (through WL #2498). */ #define HA_PARTITION_FUNCTION_SUPPORTED (1UL << 12) #define HA_FAST_CHANGE_PARTITION (1UL << 13) #define HA_PARTITION_ONE_PHASE (1UL << 14) /* Note: the following includes binlog and closing 0. TODO remove the limit, use dynarrays */ #define MAX_HA 64 /* Use this instead of 0 as the initial value for the slot number of handlerton, so that we can distinguish uninitialized slot number from slot 0. */ #define HA_SLOT_UNDEF ((uint)-1) /* Parameters for open() (in register form->filestat) HA_GET_INFO does an implicit HA_ABORT_IF_LOCKED */ #define HA_OPEN_KEYFILE 1U #define HA_READ_ONLY 16U /* File opened as readonly */ /* Try readonly if can't open with read and write */ #define HA_TRY_READ_ONLY 32U /* Some key definitions */ #define HA_KEY_NULL_LENGTH 1 #define HA_KEY_BLOB_LENGTH 2 /* Maximum length of any index lookup key, in bytes */ #define MAX_KEY_LENGTH (MAX_DATA_LENGTH_FOR_KEY \ +(MAX_REF_PARTS \ *(HA_KEY_NULL_LENGTH + HA_KEY_BLOB_LENGTH))) #define HA_LEX_CREATE_TMP_TABLE 1U #define HA_CREATE_TMP_ALTER 8U #define HA_LEX_CREATE_SEQUENCE 16U #define HA_VERSIONED_TABLE 32U #define HA_SKIP_KEY_SORT 64U /* A temporary table that can be used by different threads, eg. replication threads. This flag ensure that memory is not allocated with THREAD_SPECIFIC, as we do for other temporary tables. */ #define HA_LEX_CREATE_GLOBAL_TMP_TABLE 128U #define HA_MAX_REC_LENGTH 65535 /* Table caching type */ #define HA_CACHE_TBL_NONTRANSACT 0 #define HA_CACHE_TBL_NOCACHE 1U #define HA_CACHE_TBL_ASKTRANSACT 2U #define HA_CACHE_TBL_TRANSACT 4U /** Options for the START TRANSACTION statement. Note that READ ONLY and READ WRITE are logically mutually exclusive. This is enforced by the parser and depended upon by trans_begin(). We need two flags instead of one in order to differentiate between situation when no READ WRITE/ONLY clause were given and thus transaction is implicitly READ WRITE and the case when READ WRITE clause was used explicitly. */ // WITH CONSISTENT SNAPSHOT option static const uint MYSQL_START_TRANS_OPT_WITH_CONS_SNAPSHOT = 1; // READ ONLY option static const uint MYSQL_START_TRANS_OPT_READ_ONLY = 2; // READ WRITE option static const uint MYSQL_START_TRANS_OPT_READ_WRITE = 4; /* Flags for method is_fatal_error */ #define HA_CHECK_DUP_KEY 1U #define HA_CHECK_DUP_UNIQUE 2U #define HA_CHECK_FK_ERROR 4U #define HA_CHECK_DUP (HA_CHECK_DUP_KEY + HA_CHECK_DUP_UNIQUE) #define HA_CHECK_ALL (~0U) /* Options for info_push() */ #define INFO_KIND_UPDATE_FIELDS 101 #define INFO_KIND_UPDATE_VALUES 102 #define INFO_KIND_FORCE_LIMIT_BEGIN 103 #define INFO_KIND_FORCE_LIMIT_END 104 enum legacy_db_type { /* note these numerical values are fixed and can *not* be changed */ DB_TYPE_UNKNOWN=0, DB_TYPE_HEAP=6, DB_TYPE_MYISAM=9, DB_TYPE_MRG_MYISAM=10, DB_TYPE_INNODB=12, DB_TYPE_EXAMPLE_DB=15, DB_TYPE_ARCHIVE_DB=16, DB_TYPE_CSV_DB=17, DB_TYPE_FEDERATED_DB=18, DB_TYPE_BLACKHOLE_DB=19, DB_TYPE_PARTITION_DB=20, DB_TYPE_BINLOG=21, DB_TYPE_PBXT=23, DB_TYPE_PERFORMANCE_SCHEMA=28, DB_TYPE_S3=41, DB_TYPE_ARIA=42, DB_TYPE_TOKUDB=43, /* disabled in MariaDB Server 10.5, removed in 10.6 */ DB_TYPE_SEQUENCE=44, DB_TYPE_FIRST_DYNAMIC=45, DB_TYPE_DEFAULT=127 // Must be last }; /* Better name for DB_TYPE_UNKNOWN. Should be used for engines that do not have a hard-coded type value here. */ #define DB_TYPE_AUTOASSIGN DB_TYPE_UNKNOWN enum row_type { ROW_TYPE_NOT_USED=-1, ROW_TYPE_DEFAULT, ROW_TYPE_FIXED, ROW_TYPE_DYNAMIC, ROW_TYPE_COMPRESSED, ROW_TYPE_REDUNDANT, ROW_TYPE_COMPACT, ROW_TYPE_PAGE }; /* not part of the enum, so that it shouldn't be in switch(row_type) */ #define ROW_TYPE_MAX ((uint)ROW_TYPE_PAGE + 1) /* Specifies data storage format for individual columns */ enum column_format_type { COLUMN_FORMAT_TYPE_DEFAULT= 0, /* Not specified (use engine default) */ COLUMN_FORMAT_TYPE_FIXED= 1, /* FIXED format */ COLUMN_FORMAT_TYPE_DYNAMIC= 2 /* DYNAMIC format */ }; enum enum_binlog_func { BFN_RESET_LOGS= 1, BFN_RESET_SLAVE= 2, BFN_BINLOG_WAIT= 3, BFN_BINLOG_END= 4, BFN_BINLOG_PURGE_FILE= 5 }; enum enum_binlog_command { LOGCOM_CREATE_TABLE, LOGCOM_ALTER_TABLE, LOGCOM_RENAME_TABLE, LOGCOM_DROP_TABLE, LOGCOM_CREATE_DB, LOGCOM_ALTER_DB, LOGCOM_DROP_DB }; /* struct to hold information about the table that should be created */ /* Bits in used_fields */ #define HA_CREATE_USED_AUTO (1UL << 0) #define HA_CREATE_USED_RAID (1UL << 1) //RAID is no longer available #define HA_CREATE_USED_UNION (1UL << 2) #define HA_CREATE_USED_INSERT_METHOD (1UL << 3) #define HA_CREATE_USED_MIN_ROWS (1UL << 4) #define HA_CREATE_USED_MAX_ROWS (1UL << 5) #define HA_CREATE_USED_AVG_ROW_LENGTH (1UL << 6) #define HA_CREATE_USED_PACK_KEYS (1UL << 7) #define HA_CREATE_USED_CHARSET (1UL << 8) #define HA_CREATE_USED_DEFAULT_CHARSET (1UL << 9) #define HA_CREATE_USED_DATADIR (1UL << 10) #define HA_CREATE_USED_INDEXDIR (1UL << 11) #define HA_CREATE_USED_ENGINE (1UL << 12) #define HA_CREATE_USED_CHECKSUM (1UL << 13) #define HA_CREATE_USED_DELAY_KEY_WRITE (1UL << 14) #define HA_CREATE_USED_ROW_FORMAT (1UL << 15) #define HA_CREATE_USED_COMMENT (1UL << 16) #define HA_CREATE_USED_PASSWORD (1UL << 17) #define HA_CREATE_USED_CONNECTION (1UL << 18) #define HA_CREATE_USED_KEY_BLOCK_SIZE (1UL << 19) /* The following two are used by Maria engine: */ #define HA_CREATE_USED_TRANSACTIONAL (1UL << 20) #define HA_CREATE_USED_PAGE_CHECKSUM (1UL << 21) /** This is set whenever STATS_PERSISTENT=0|1|default has been specified in CREATE/ALTER TABLE. See also HA_OPTION_STATS_PERSISTENT in include/my_base.h. It is possible to distinguish whether STATS_PERSISTENT=default has been specified or no STATS_PERSISTENT= is given at all. */ #define HA_CREATE_USED_STATS_PERSISTENT (1UL << 22) /** This is set whenever STATS_AUTO_RECALC=0|1|default has been specified in CREATE/ALTER TABLE. See enum_stats_auto_recalc. It is possible to distinguish whether STATS_AUTO_RECALC=default has been specified or no STATS_AUTO_RECALC= is given at all. */ #define HA_CREATE_USED_STATS_AUTO_RECALC (1UL << 23) /** This is set whenever STATS_SAMPLE_PAGES=N|default has been specified in CREATE/ALTER TABLE. It is possible to distinguish whether STATS_SAMPLE_PAGES=default has been specified or no STATS_SAMPLE_PAGES= is given at all. */ #define HA_CREATE_USED_STATS_SAMPLE_PAGES (1UL << 24) /* Create a sequence */ #define HA_CREATE_USED_SEQUENCE (1UL << 25) /* Tell binlog_show_create_table to print all engine options */ #define HA_CREATE_PRINT_ALL_OPTIONS (1UL << 26) typedef ulonglong alter_table_operations; typedef bool Log_func(THD*, TABLE*, bool, const uchar*, const uchar*); /* These flags are set by the parser and describes the type of operation(s) specified by the ALTER TABLE statement. */ // Set by parser for ADD [COLUMN] #define ALTER_PARSER_ADD_COLUMN (1ULL << 0) // Set by parser for DROP [COLUMN] #define ALTER_PARSER_DROP_COLUMN (1ULL << 1) // Set for CHANGE [COLUMN] | MODIFY [CHANGE] & mysql_recreate_table #define ALTER_CHANGE_COLUMN (1ULL << 2) // Set for ADD INDEX | ADD KEY | ADD PRIMARY KEY | ADD UNIQUE KEY | // ADD UNIQUE INDEX | ALTER ADD [COLUMN] #define ALTER_ADD_INDEX (1ULL << 3) // Set for DROP PRIMARY KEY | DROP FOREIGN KEY | DROP KEY | DROP INDEX #define ALTER_DROP_INDEX (1ULL << 4) // Set for RENAME [TO] #define ALTER_RENAME (1ULL << 5) // Set for ORDER BY #define ALTER_ORDER (1ULL << 6) // Set for table_options, like table comment #define ALTER_OPTIONS (1ULL << 7) // Set for ALTER [COLUMN] ... SET DEFAULT ... | DROP DEFAULT #define ALTER_CHANGE_COLUMN_DEFAULT (1ULL << 8) // Set for DISABLE KEYS | ENABLE KEYS #define ALTER_KEYS_ONOFF (1ULL << 9) // Set for FORCE, ENGINE(same engine), by mysql_recreate_table() #define ALTER_RECREATE (1ULL << 10) // Set for CONVERT TO #define ALTER_CONVERT_TO (1ULL << 11) // Set for DROP ... ADD some_index #define ALTER_RENAME_INDEX (1ULL << 12) // Set for ADD FOREIGN KEY #define ALTER_ADD_FOREIGN_KEY (1ULL << 21) // Set for DROP FOREIGN KEY #define ALTER_DROP_FOREIGN_KEY (1ULL << 22) #define ALTER_CHANGE_INDEX_COMMENT (1ULL << 23) // Set for ADD [COLUMN] FIRST | AFTER #define ALTER_COLUMN_ORDER (1ULL << 25) #define ALTER_ADD_CHECK_CONSTRAINT (1ULL << 27) #define ALTER_DROP_CHECK_CONSTRAINT (1ULL << 28) #define ALTER_RENAME_COLUMN (1ULL << 29) #define ALTER_COLUMN_UNVERSIONED (1ULL << 30) #define ALTER_ADD_SYSTEM_VERSIONING (1ULL << 31) #define ALTER_DROP_SYSTEM_VERSIONING (1ULL << 32) #define ALTER_ADD_PERIOD (1ULL << 33) #define ALTER_DROP_PERIOD (1ULL << 34) /* Following defines are used by ALTER_INPLACE_TABLE They do describe in more detail the type operation(s) to be executed by the storage engine. For example, which type of type of index to be added/dropped. These are set by fill_alter_inplace_info(). */ #define ALTER_RECREATE_TABLE ALTER_RECREATE #define ALTER_CHANGE_CREATE_OPTION ALTER_OPTIONS #define ALTER_ADD_COLUMN (ALTER_ADD_VIRTUAL_COLUMN | \ ALTER_ADD_STORED_BASE_COLUMN | \ ALTER_ADD_STORED_GENERATED_COLUMN) #define ALTER_DROP_COLUMN (ALTER_DROP_VIRTUAL_COLUMN | \ ALTER_DROP_STORED_COLUMN) #define ALTER_COLUMN_DEFAULT ALTER_CHANGE_COLUMN_DEFAULT // Add non-unique, non-primary index #define ALTER_ADD_NON_UNIQUE_NON_PRIM_INDEX (1ULL << 35) // Drop non-unique, non-primary index #define ALTER_DROP_NON_UNIQUE_NON_PRIM_INDEX (1ULL << 36) // Add unique, non-primary index #define ALTER_ADD_UNIQUE_INDEX (1ULL << 37) // Drop unique, non-primary index #define ALTER_DROP_UNIQUE_INDEX (1ULL << 38) // Add primary index #define ALTER_ADD_PK_INDEX (1ULL << 39) // Drop primary index #define ALTER_DROP_PK_INDEX (1ULL << 40) // Virtual generated column #define ALTER_ADD_VIRTUAL_COLUMN (1ULL << 41) // Stored base (non-generated) column #define ALTER_ADD_STORED_BASE_COLUMN (1ULL << 42) // Stored generated column #define ALTER_ADD_STORED_GENERATED_COLUMN (1ULL << 43) // Drop column #define ALTER_DROP_VIRTUAL_COLUMN (1ULL << 44) #define ALTER_DROP_STORED_COLUMN (1ULL << 45) // Rename column (verified; ALTER_RENAME_COLUMN may use original name) #define ALTER_COLUMN_NAME (1ULL << 46) // Change column datatype #define ALTER_VIRTUAL_COLUMN_TYPE (1ULL << 47) #define ALTER_STORED_COLUMN_TYPE (1ULL << 48) // Engine can handle type change by itself in ALGORITHM=INPLACE #define ALTER_COLUMN_TYPE_CHANGE_BY_ENGINE (1ULL << 49) // Reorder column #define ALTER_STORED_COLUMN_ORDER (1ULL << 50) // Reorder column #define ALTER_VIRTUAL_COLUMN_ORDER (1ULL << 51) // Change column from NOT NULL to NULL #define ALTER_COLUMN_NULLABLE (1ULL << 52) // Change column from NULL to NOT NULL #define ALTER_COLUMN_NOT_NULLABLE (1ULL << 53) // Change column generation expression #define ALTER_VIRTUAL_GCOL_EXPR (1ULL << 54) #define ALTER_STORED_GCOL_EXPR (1ULL << 55) // column's engine options changed, something in field->option_struct #define ALTER_COLUMN_OPTION (1ULL << 56) // MySQL alias for the same thing: #define ALTER_COLUMN_STORAGE_TYPE ALTER_COLUMN_OPTION // Change the column format of column #define ALTER_COLUMN_COLUMN_FORMAT (1ULL << 57) /** Changes in generated columns that affect storage, for example, when a vcol type or expression changes and this vcol is indexed or used in a partitioning expression */ #define ALTER_COLUMN_VCOL (1ULL << 58) /** ALTER TABLE for a partitioned table. The engine needs to commit online alter of all partitions atomically (using group_commit_ctx) */ #define ALTER_PARTITIONED (1ULL << 59) /** Change in index length such that it doesn't require index rebuild. */ #define ALTER_COLUMN_INDEX_LENGTH (1ULL << 60) /** Indicate that index order might have been changed. Disables inplace algorithm by default (not for InnoDB). */ #define ALTER_INDEX_ORDER (1ULL << 61) /** Means that the ignorability of an index is changed. */ #define ALTER_INDEX_IGNORABILITY (1ULL << 62) /* Flags set in partition_flags when altering partitions */ // Set for ADD PARTITION #define ALTER_PARTITION_ADD (1ULL << 1) // Set for DROP PARTITION #define ALTER_PARTITION_DROP (1ULL << 2) // Set for COALESCE PARTITION #define ALTER_PARTITION_COALESCE (1ULL << 3) // Set for REORGANIZE PARTITION ... INTO #define ALTER_PARTITION_REORGANIZE (1ULL << 4) // Set for partition_options #define ALTER_PARTITION_INFO (1ULL << 5) // Set for LOAD INDEX INTO CACHE ... PARTITION // Set for CACHE INDEX ... PARTITION #define ALTER_PARTITION_ADMIN (1ULL << 6) // Set for REBUILD PARTITION #define ALTER_PARTITION_REBUILD (1ULL << 7) // Set for partitioning operations specifying ALL keyword #define ALTER_PARTITION_ALL (1ULL << 8) // Set for REMOVE PARTITIONING #define ALTER_PARTITION_REMOVE (1ULL << 9) // Set for EXCHANGE PARITION #define ALTER_PARTITION_EXCHANGE (1ULL << 10) // Set by Sql_cmd_alter_table_truncate_partition::execute() #define ALTER_PARTITION_TRUNCATE (1ULL << 11) // Set for REORGANIZE PARTITION #define ALTER_PARTITION_TABLE_REORG (1ULL << 12) /* This is master database for most of system tables. However there can be other databases which can hold system tables. Respective storage engines define their own system database names. */ extern const char *mysqld_system_database; /* Structure to hold list of system_database.system_table. This is used at both mysqld and storage engine layer. */ struct st_system_tablename { const char *db; const char *tablename; }; typedef ulonglong my_xid; // this line is the same as in log_event.h #define MYSQL_XID_PREFIX "MySQLXid" #define MYSQL_XID_PREFIX_LEN 8 // must be a multiple of 8 #define MYSQL_XID_OFFSET (MYSQL_XID_PREFIX_LEN+sizeof(server_id)) #define MYSQL_XID_GTRID_LEN (MYSQL_XID_OFFSET+sizeof(my_xid)) #define XIDDATASIZE MYSQL_XIDDATASIZE #define MAXGTRIDSIZE 64 #define MAXBQUALSIZE 64 #define COMPATIBLE_DATA_YES 0 #define COMPATIBLE_DATA_NO 1 /** struct xid_t is binary compatible with the XID structure as in the X/Open CAE Specification, Distributed Transaction Processing: The XA Specification, X/Open Company Ltd., 1991. http://www.opengroup.org/bookstore/catalog/c193.htm @see MYSQL_XID in mysql/plugin.h */ struct xid_t { long formatID; long gtrid_length; long bqual_length; char data[XIDDATASIZE]; // not \0-terminated ! xid_t() = default; /* Remove gcc warning */ bool eq(struct xid_t *xid) const { return !xid->is_null() && eq(xid->gtrid_length, xid->bqual_length, xid->data); } bool eq(long g, long b, const char *d) const { return !is_null() && g == gtrid_length && b == bqual_length && !memcmp(d, data, g+b); } void set(struct xid_t *xid) { memcpy(this, xid, xid->length()); } void set(long f, const char *g, long gl, const char *b, long bl) { formatID= f; if ((gtrid_length= gl)) memcpy(data, g, gl); if ((bqual_length= bl)) memcpy(data+gl, b, bl); } // Populate server_id if it's specified, otherwise use the current server_id void set(ulonglong xid, decltype(::server_id) trx_server_id= server_id) { my_xid tmp; formatID= 1; set(MYSQL_XID_PREFIX_LEN, 0, MYSQL_XID_PREFIX); memcpy(data+MYSQL_XID_PREFIX_LEN, &trx_server_id, sizeof(trx_server_id)); tmp= xid; memcpy(data+MYSQL_XID_OFFSET, &tmp, sizeof(tmp)); gtrid_length=MYSQL_XID_GTRID_LEN; } void set(long g, long b, const char *d) { formatID= 1; gtrid_length= g; bqual_length= b; memcpy(data, d, g+b); } bool is_null() const { return formatID == -1; } void null() { formatID= -1; } my_xid quick_get_my_xid() { my_xid tmp; memcpy(&tmp, data+MYSQL_XID_OFFSET, sizeof(tmp)); return tmp; } my_xid get_my_xid() { return gtrid_length == MYSQL_XID_GTRID_LEN && bqual_length == 0 && !memcmp(data, MYSQL_XID_PREFIX, MYSQL_XID_PREFIX_LEN) ? quick_get_my_xid() : 0; } decltype(::server_id) get_trx_server_id() { decltype(::server_id) trx_server_id; memcpy(&trx_server_id, data+MYSQL_XID_PREFIX_LEN, sizeof(trx_server_id)); return trx_server_id; } uint length() { return static_cast(sizeof(formatID)) + key_length(); } uchar *key() const { return (uchar *)>rid_length; } uint key_length() const { return static_cast(sizeof(gtrid_length)+sizeof(bqual_length)+ gtrid_length+bqual_length); } }; typedef struct xid_t XID; /* Enumerates a sequence in the order of their creation that is in the top-down order of the index file. Ranges from zero through MAX_binlog_id. Not confuse the value with the binlog file numerical suffix, neither with the binlog file line in the binlog index file. */ typedef uint Binlog_file_id; const Binlog_file_id MAX_binlog_id= UINT_MAX; const my_off_t MAX_off_t = (~(my_off_t) 0); /* Compound binlog-id and byte offset of transaction's first event in a sequence (e.g the recovery sequence) of binlog files. Binlog_offset(0,0) is the minimum value to mean the first byte of the first binlog file. */ typedef std::pair Binlog_offset; /* binlog-based recovery transaction descriptor */ struct xid_recovery_member { my_xid xid; uint in_engine_prepare; // number of engines that have xid prepared bool decided_to_commit; /* Semisync recovery binlog offset. It's initialized with the maximum unreachable offset. The max value will remain for any transaction not found in binlog to yield its rollback decision as it's guaranteed to be within a truncated tail part of the binlog. */ Binlog_offset binlog_coord; XID *full_xid; // needed by wsrep or past it recovery decltype(::server_id) server_id; // server id of orginal server xid_recovery_member(my_xid xid_arg, uint prepare_arg, bool decided_arg, XID *full_xid_arg, decltype(::server_id) server_id_arg) : xid(xid_arg), in_engine_prepare(prepare_arg), decided_to_commit(decided_arg), binlog_coord(Binlog_offset(MAX_binlog_id, MAX_off_t)), full_xid(full_xid_arg), server_id(server_id_arg) {}; }; /* for recover() handlerton call */ #define MIN_XID_LIST_SIZE 128 #define MAX_XID_LIST_SIZE (1024*128) /* These structures are used to pass information from a set of SQL commands on add/drop/change tablespace definitions to the proper hton. */ #define UNDEF_NODEGROUP 65535 enum ts_command_type { TS_CMD_NOT_DEFINED = -1, CREATE_TABLESPACE = 0, ALTER_TABLESPACE = 1, CREATE_LOGFILE_GROUP = 2, ALTER_LOGFILE_GROUP = 3, DROP_TABLESPACE = 4, DROP_LOGFILE_GROUP = 5, CHANGE_FILE_TABLESPACE = 6, ALTER_ACCESS_MODE_TABLESPACE = 7 }; enum ts_alter_tablespace_type { TS_ALTER_TABLESPACE_TYPE_NOT_DEFINED = -1, ALTER_TABLESPACE_ADD_FILE = 1, ALTER_TABLESPACE_DROP_FILE = 2 }; enum tablespace_access_mode { TS_NOT_DEFINED= -1, TS_READ_ONLY = 0, TS_READ_WRITE = 1, TS_NOT_ACCESSIBLE = 2 }; /* Statistics about batch operations like bulk_insert */ struct ha_copy_info { ha_rows records; /* Used to check if rest of variables can be used */ ha_rows touched; ha_rows copied; ha_rows deleted; ha_rows updated; }; struct handlerton; class st_alter_tablespace : public Sql_alloc { public: const char *tablespace_name; const char *logfile_group_name; enum ts_command_type ts_cmd_type; enum ts_alter_tablespace_type ts_alter_tablespace_type; const char *data_file_name; const char *undo_file_name; const char *redo_file_name; ulonglong extent_size; ulonglong undo_buffer_size; ulonglong redo_buffer_size; ulonglong initial_size; ulonglong autoextend_size; ulonglong max_size; uint nodegroup_id; handlerton *storage_engine; bool wait_until_completed; const char *ts_comment; enum tablespace_access_mode ts_access_mode; st_alter_tablespace() { tablespace_name= NULL; logfile_group_name= "DEFAULT_LG"; //Default log file group ts_cmd_type= TS_CMD_NOT_DEFINED; data_file_name= NULL; undo_file_name= NULL; redo_file_name= NULL; extent_size= 1024*1024; //Default 1 MByte undo_buffer_size= 8*1024*1024; //Default 8 MByte redo_buffer_size= 8*1024*1024; //Default 8 MByte initial_size= 128*1024*1024; //Default 128 MByte autoextend_size= 0; //No autoextension as default max_size= 0; //Max size == initial size => no extension storage_engine= NULL; nodegroup_id= UNDEF_NODEGROUP; wait_until_completed= TRUE; ts_comment= NULL; ts_access_mode= TS_NOT_DEFINED; } }; /* The handler for a table type. Will be included in the TABLE structure */ struct TABLE; /* Make sure that the order of schema_tables and enum_schema_tables are the same. */ enum enum_schema_tables { SCH_ALL_PLUGINS, SCH_APPLICABLE_ROLES, SCH_CHARSETS, SCH_CHECK_CONSTRAINTS, SCH_COLLATIONS, SCH_COLLATION_CHARACTER_SET_APPLICABILITY, SCH_COLUMNS, SCH_COLUMN_PRIVILEGES, SCH_ENABLED_ROLES, SCH_ENGINES, SCH_EVENTS, SCH_EXPLAIN, SCH_FILES, SCH_GLOBAL_STATUS, SCH_GLOBAL_VARIABLES, SCH_KEYWORDS, SCH_KEY_CACHES, SCH_KEY_COLUMN_USAGE, SCH_OPEN_TABLES, SCH_OPT_TRACE, SCH_PARAMETERS, SCH_PARTITIONS, SCH_PLUGINS, SCH_PROCESSLIST, SCH_PROFILES, SCH_REFERENTIAL_CONSTRAINTS, SCH_PROCEDURES, SCH_SCHEMATA, SCH_SCHEMA_PRIVILEGES, SCH_SESSION_STATUS, SCH_SESSION_VARIABLES, SCH_STATISTICS, SCH_SQL_FUNCTIONS, SCH_SYSTEM_VARIABLES, SCH_TABLES, SCH_TABLESPACES, SCH_TABLE_CONSTRAINTS, SCH_TABLE_NAMES, SCH_TABLE_PRIVILEGES, SCH_TRIGGERS, SCH_USER_PRIVILEGES, SCH_VIEWS }; struct TABLE_SHARE; struct HA_CREATE_INFO; struct st_foreign_key_info; typedef struct st_foreign_key_info FOREIGN_KEY_INFO; typedef bool (stat_print_fn)(THD *thd, const char *type, size_t type_len, const char *file, size_t file_len, const char *status, size_t status_len); enum ha_stat_type { HA_ENGINE_STATUS, HA_ENGINE_LOGS, HA_ENGINE_MUTEX }; extern MYSQL_PLUGIN_IMPORT st_plugin_int *hton2plugin[MAX_HA]; #define view_pseudo_hton ((handlerton *)1) /* Definitions for engine-specific table/field/index options in the CREATE TABLE. Options are declared with HA_*OPTION_* macros (HA_TOPTION_NUMBER, HA_FOPTION_ENUM, HA_IOPTION_STRING, etc). Every macros takes the option name, and the name of the underlying field of the appropriate C structure. The "appropriate C structure" is ha_table_option_struct for table level options, ha_field_option_struct for field level options, ha_index_option_struct for key level options. The engine either defines a structure of this name, or uses #define's to map these "appropriate" names to the actual structure type name. ULL options use a ulonglong as the backing store. HA_*OPTION_NUMBER() takes the option name, the structure field name, the default value for the option, min, max, and blk_siz values. STRING options use a char* as a backing store. HA_*OPTION_STRING takes the option name and the structure field name. The default value will be 0. ENUM options use a uint as a backing store (not enum!!!). HA_*OPTION_ENUM takes the option name, the structure field name, the default value for the option as a number, and a string with the permitted values for this enum - one string with comma separated values, for example: "gzip,bzip2,lzma" BOOL options use a bool as a backing store. HA_*OPTION_BOOL takes the option name, the structure field name, and the default value for the option. From the SQL, BOOL options accept YES/NO, ON/OFF, and 1/0. The name of the option is limited to 255 bytes, the value (for string options) - to the 32767 bytes. See ha_example.cc for an example. */ struct ha_table_option_struct; struct ha_field_option_struct; struct ha_index_option_struct; enum ha_option_type { HA_OPTION_TYPE_ULL, /* unsigned long long */ HA_OPTION_TYPE_STRING, /* char * */ HA_OPTION_TYPE_ENUM, /* uint */ HA_OPTION_TYPE_BOOL, /* bool */ HA_OPTION_TYPE_SYSVAR};/* type of the sysval */ #define HA_xOPTION_NUMBER(name, struc, field, def, min, max, blk_siz) \ { HA_OPTION_TYPE_ULL, name, sizeof(name)-1, \ offsetof(struc, field), def, min, max, blk_siz, 0, 0 } #define HA_xOPTION_STRING(name, struc, field) \ { HA_OPTION_TYPE_STRING, name, sizeof(name)-1, \ offsetof(struc, field), 0, 0, 0, 0, 0, 0} #define HA_xOPTION_ENUM(name, struc, field, values, def) \ { HA_OPTION_TYPE_ENUM, name, sizeof(name)-1, \ offsetof(struc, field), def, 0, \ sizeof(values)-1, 0, values, 0 } #define HA_xOPTION_BOOL(name, struc, field, def) \ { HA_OPTION_TYPE_BOOL, name, sizeof(name)-1, \ offsetof(struc, field), def, 0, 1, 0, 0, 0 } #define HA_xOPTION_SYSVAR(name, struc, field, sysvar) \ { HA_OPTION_TYPE_SYSVAR, name, sizeof(name)-1, \ offsetof(struc, field), 0, 0, 0, 0, 0, MYSQL_SYSVAR(sysvar) } #define HA_xOPTION_END { HA_OPTION_TYPE_ULL, 0, 0, 0, 0, 0, 0, 0, 0, 0 } #define HA_TOPTION_NUMBER(name, field, def, min, max, blk_siz) \ HA_xOPTION_NUMBER(name, ha_table_option_struct, field, def, min, max, blk_siz) #define HA_TOPTION_STRING(name, field) \ HA_xOPTION_STRING(name, ha_table_option_struct, field) #define HA_TOPTION_ENUM(name, field, values, def) \ HA_xOPTION_ENUM(name, ha_table_option_struct, field, values, def) #define HA_TOPTION_BOOL(name, field, def) \ HA_xOPTION_BOOL(name, ha_table_option_struct, field, def) #define HA_TOPTION_SYSVAR(name, field, sysvar) \ HA_xOPTION_SYSVAR(name, ha_table_option_struct, field, sysvar) #define HA_TOPTION_END HA_xOPTION_END #define HA_FOPTION_NUMBER(name, field, def, min, max, blk_siz) \ HA_xOPTION_NUMBER(name, ha_field_option_struct, field, def, min, max, blk_siz) #define HA_FOPTION_STRING(name, field) \ HA_xOPTION_STRING(name, ha_field_option_struct, field) #define HA_FOPTION_ENUM(name, field, values, def) \ HA_xOPTION_ENUM(name, ha_field_option_struct, field, values, def) #define HA_FOPTION_BOOL(name, field, def) \ HA_xOPTION_BOOL(name, ha_field_option_struct, field, def) #define HA_FOPTION_SYSVAR(name, field, sysvar) \ HA_xOPTION_SYSVAR(name, ha_field_option_struct, field, sysvar) #define HA_FOPTION_END HA_xOPTION_END #define HA_IOPTION_NUMBER(name, field, def, min, max, blk_siz) \ HA_xOPTION_NUMBER(name, ha_index_option_struct, field, def, min, max, blk_siz) #define HA_IOPTION_STRING(name, field) \ HA_xOPTION_STRING(name, ha_index_option_struct, field) #define HA_IOPTION_ENUM(name, field, values, def) \ HA_xOPTION_ENUM(name, ha_index_option_struct, field, values, def) #define HA_IOPTION_BOOL(name, field, def) \ HA_xOPTION_BOOL(name, ha_index_option_struct, field, def) #define HA_IOPTION_SYSVAR(name, field, sysvar) \ HA_xOPTION_SYSVAR(name, ha_index_option_struct, field, sysvar) #define HA_IOPTION_END HA_xOPTION_END typedef struct st_ha_create_table_option { enum ha_option_type type; const char *name; size_t name_length; ptrdiff_t offset; ulonglong def_value; ulonglong min_value, max_value, block_size; const char *values; struct st_mysql_sys_var *var; } ha_create_table_option; class handler; class group_by_handler; class derived_handler; class select_handler; struct Query; typedef class st_select_lex SELECT_LEX; typedef struct st_order ORDER; /* handlerton is a singleton structure - one instance per storage engine - to provide access to storage engine functionality that works on the "global" level (unlike handler class that works on a per-table basis) usually handlerton instance is defined statically in ha_xxx.cc as static handlerton { ... } xxx_hton; savepoint_*, prepare, recover, and *_by_xid pointers can be 0. */ struct handlerton { /* Historical number used for frm file to determine the correct storage engine. This is going away and new engines will just use "name" for this. */ enum legacy_db_type db_type; /* each storage engine has it's own memory area (actually a pointer) in the thd, for storing per-connection information. It is accessed as thd->ha_data[xxx_hton.slot] slot number is initialized by MySQL after xxx_init() is called. */ uint slot; /* to store per-savepoint data storage engine is provided with an area of a requested size (0 is ok here). savepoint_offset must be initialized statically to the size of the needed memory to store per-savepoint information. After xxx_init it is changed to be an offset to savepoint storage area and need not be used by storage engine. see binlog_hton and binlog_savepoint_set/rollback for an example. */ uint savepoint_offset; /* handlerton methods: close_connection is only called if thd->ha_data[xxx_hton.slot] is non-zero, so even if you don't need this storage area - set it to something, so that MySQL would know this storage engine was accessed in this connection */ int (*close_connection)(handlerton *hton, THD *thd); /* Tell handler that query has been killed. */ void (*kill_query)(handlerton *hton, THD *thd, enum thd_kill_levels level); /* sv points to an uninitialized storage area of requested size (see savepoint_offset description) */ int (*savepoint_set)(handlerton *hton, THD *thd, void *sv); /* sv points to a storage area, that was earlier passed to the savepoint_set call */ int (*savepoint_rollback)(handlerton *hton, THD *thd, void *sv); /** Check if storage engine allows to release metadata locks which were acquired after the savepoint if rollback to savepoint is done. @return true - If it is safe to release MDL locks. false - If it is not. */ bool (*savepoint_rollback_can_release_mdl)(handlerton *hton, THD *thd); int (*savepoint_release)(handlerton *hton, THD *thd, void *sv); /* 'all' is true if it's a real commit, that makes persistent changes 'all' is false if it's not in fact a commit but an end of the statement that is part of the transaction. NOTE 'all' is also false in auto-commit mode where 'end of statement' and 'real commit' mean the same event. */ int (*commit)(handlerton *hton, THD *thd, bool all); /* The commit_ordered() method is called prior to the commit() method, after the transaction manager has decided to commit (not rollback) the transaction. Unlike commit(), commit_ordered() is called only when the full transaction is committed, not for each commit of statement transaction in a multi-statement transaction. Not that like prepare(), commit_ordered() is only called when 2-phase commit takes place. Ie. when no binary log and only a single engine participates in a transaction, one commit() is called, no commit_ordered(). So engines must be prepared for this. The calls to commit_ordered() in multiple parallel transactions is guaranteed to happen in the same order in every participating handler. This can be used to ensure the same commit order among multiple handlers (eg. in table handler and binlog). So if transaction T1 calls into commit_ordered() of handler A before T2, then T1 will also call commit_ordered() of handler B before T2. Engines that implement this method should during this call make the transaction visible to other transactions, thereby making the order of transaction commits be defined by the order of commit_ordered() calls. The intention is that commit_ordered() should do the minimal amount of work that needs to happen in consistent commit order among handlers. To preserve ordering, calls need to be serialised on a global mutex, so doing any time-consuming or blocking operations in commit_ordered() will limit scalability. Handlers can rely on commit_ordered() calls to be serialised (no two calls can run in parallel, so no extra locking on the handler part is required to ensure this). Note that commit_ordered() can be called from a different thread than the one handling the transaction! So it can not do anything that depends on thread local storage, in particular it can not call my_error() and friends (instead it can store the error code and delay the call of my_error() to the commit() method). Similarly, since commit_ordered() returns void, any return error code must be saved and returned from the commit() method instead. The commit_ordered method is optional, and can be left unset if not needed in a particular handler (then there will be no ordering guarantees wrt. other engines and binary log). */ void (*commit_ordered)(handlerton *hton, THD *thd, bool all); int (*rollback)(handlerton *hton, THD *thd, bool all); int (*prepare)(handlerton *hton, THD *thd, bool all); /* The prepare_ordered method is optional. If set, it will be called after successful prepare() in all handlers participating in 2-phase commit. Like commit_ordered(), it is called only when the full transaction is committed, not for each commit of statement transaction. The calls to prepare_ordered() among multiple parallel transactions are ordered consistently with calls to commit_ordered(). This means that calls to prepare_ordered() effectively define the commit order, and that each handler will see the same sequence of transactions calling into prepare_ordered() and commit_ordered(). Thus, prepare_ordered() can be used to define commit order for handlers that need to do this in the prepare step (like binlog). It can also be used to release transaction's locks early in an order consistent with the order transactions will be eventually committed. Like commit_ordered(), prepare_ordered() calls are serialised to maintain ordering, so the intention is that they should execute fast, with only the minimal amount of work needed to define commit order. Handlers can rely on this serialisation, and do not need to do any extra locking to avoid two prepare_ordered() calls running in parallel. Like commit_ordered(), prepare_ordered() is not guaranteed to be called in the context of the thread handling the rest of the transaction. So it cannot invoke code that relies on thread local storage, in particular it cannot call my_error(). prepare_ordered() cannot cause a rollback by returning an error, all possible errors must be handled in prepare() (the prepare_ordered() method returns void). In case of some fatal error, a record of the error must be made internally by the engine and returned from commit() later. Note that for user-level XA SQL commands, no consistent ordering among prepare_ordered() and commit_ordered() is guaranteed (as that would require blocking all other commits for an indefinite time). When 2-phase commit is not used (eg. only one engine (and no binlog) in transaction), neither prepare() nor prepare_ordered() is called. */ void (*prepare_ordered)(handlerton *hton, THD *thd, bool all); int (*recover)(handlerton *hton, XID *xid_list, uint len); int (*commit_by_xid)(handlerton *hton, XID *xid); int (*rollback_by_xid)(handlerton *hton, XID *xid); /* The commit_checkpoint_request() handlerton method is used to checkpoint the XA recovery process for storage engines that support two-phase commit. The method is optional - an engine that does not implemented is expected to work the traditional way, where every commit() durably flushes the transaction to disk in the engine before completion, so XA recovery will no longer be needed for that transaction. An engine that does implement commit_checkpoint_request() is also expected to implement commit_ordered(), so that ordering of commits is consistent between 2pc participants. Such engine is no longer required to durably flush to disk transactions in commit(), provided that the transaction has been successfully prepare()d and commit_ordered(); thus potentionally saving one fsync() call. (Engine must still durably flush to disk in commit() when no prepare()/commit_ordered() steps took place, at least if durable commits are wanted; this happens eg. if binlog is disabled). The TC will periodically (eg. once per binlog rotation) call commit_checkpoint_request(). When this happens, the engine must arrange for all transaction that have completed commit_ordered() to be durably flushed to disk (this does not include transactions that might be in the middle of executing commit_ordered()). When such flush has completed, the engine must call commit_checkpoint_notify_ha(), passing back the opaque "cookie". The flush and call of commit_checkpoint_notify_ha() need not happen immediately - it can be scheduled and performed asynchronously (ie. as part of next prepare(), or sync every second, or whatever), but should not be postponed indefinitely. It is however also permissible to do it immediately, before returning from commit_checkpoint_request(). When commit_checkpoint_notify_ha() is called, the TC will know that the transactions are durably committed, and thus no longer require XA recovery. It uses that to reduce the work needed for any subsequent XA recovery process. */ void (*commit_checkpoint_request)(void *cookie); /* "Disable or enable checkpointing internal to the storage engine. This is used for FLUSH TABLES WITH READ LOCK AND DISABLE CHECKPOINT to ensure that the engine will never start any recovery from a time between FLUSH TABLES ... ; UNLOCK TABLES. While checkpointing is disabled, the engine should pause any background write activity (such as tablespace checkpointing) that require consistency between different files (such as transaction log and tablespace files) for crash recovery to succeed. The idea is to use this to make safe multi-volume LVM snapshot backups. */ int (*checkpoint_state)(handlerton *hton, bool disabled); void *(*create_cursor_read_view)(handlerton *hton, THD *thd); void (*set_cursor_read_view)(handlerton *hton, THD *thd, void *read_view); void (*close_cursor_read_view)(handlerton *hton, THD *thd, void *read_view); handler *(*create)(handlerton *hton, TABLE_SHARE *table, MEM_ROOT *mem_root); void (*drop_database)(handlerton *hton, char* path); /* return 0 if dropped successfully, -1 if nothing was done by design (as in e.g. blackhole) an error code (e.g. HA_ERR_NO_SUCH_TABLE) otherwise */ int (*drop_table)(handlerton *hton, const char* path); int (*panic)(handlerton *hton, enum ha_panic_function flag); int (*start_consistent_snapshot)(handlerton *hton, THD *thd); bool (*flush_logs)(handlerton *hton); bool (*show_status)(handlerton *hton, THD *thd, stat_print_fn *print, enum ha_stat_type stat); uint (*partition_flags)(); alter_table_operations (*alter_table_flags)(alter_table_operations flags); int (*alter_tablespace)(handlerton *hton, THD *thd, st_alter_tablespace *ts_info); int (*fill_is_table)(handlerton *hton, THD *thd, TABLE_LIST *tables, class Item *cond, enum enum_schema_tables); uint32 flags; /* global handler flags */ /* Those handlerton functions below are properly initialized at handler init. */ int (*binlog_func)(handlerton *hton, THD *thd, enum_binlog_func fn, void *arg); void (*binlog_log_query)(handlerton *hton, THD *thd, enum_binlog_command binlog_command, const char *query, uint query_length, const char *db, const char *table_name); void (*abort_transaction)(handlerton *hton, THD *bf_thd, THD *victim_thd, my_bool signal) __attribute__((nonnull)); int (*set_checkpoint)(handlerton *hton, const XID *xid); int (*get_checkpoint)(handlerton *hton, XID* xid); /** Check if the version of the table matches the version in the .frm file. This is mainly used to verify in recovery to check if an inplace ALTER TABLE succeded. Storage engines that does not support inplace alter table does not have to implement this function. @param hton handlerton @param path Path for table @param version The unique id that is stored in the .frm file for CREATE and updated for each ALTER TABLE (but not for simple renames). This is the ID used for the final table. @param create_id The value returned from handler->table_version() for the original table (before ALTER TABLE). @retval 0 If id matches or table is newer than create_id (depending on what version check the engine supports. This means that The (inplace) alter table did succeed. @retval # > 0 Alter table did not succeed. Related to handler::discover_check_version(). */ int (*check_version)(handlerton *hton, const char *path, const LEX_CUSTRING *version, ulonglong create_id); /* Called for all storage handlers after ddl recovery is done */ int (*signal_ddl_recovery_done)(handlerton *hton); /* Optional clauses in the CREATE/ALTER TABLE */ ha_create_table_option *table_options; // table level options ha_create_table_option *field_options; // these are specified per field ha_create_table_option *index_options; // these are specified per index /** The list of extensions of files created for a single table in the database directory (datadir/db_name/). Used by open_table_error(), by the default rename_table and delete_table handler methods, and by the default discovery implementation. For engines that have more than one file name extensions (separate metadata, index, and/or data files), the order of elements is relevant. First element of engine file name extensions array should be metadata file extention. This is implied by the open_table_error() and the default discovery implementation. Second element - data file extension. This is implied assumed by REPAIR TABLE ... USE_FRM implementation. */ const char **tablefile_extensions; // by default - empty list /********************************************************************** Functions to intercept queries **********************************************************************/ /* Create and return a group_by_handler, if the storage engine can execute the summary / group by query. If the storage engine can't do that, return NULL. The server guaranteeds that all tables in the list belong to this storage engine. */ group_by_handler *(*create_group_by)(THD *thd, Query *query); /* Create and return a derived_handler if the storage engine can execute the derived table 'derived', otherwise return NULL. In a general case 'derived' may contain tables not from the engine. If the engine cannot handle or does not want to handle such pushed derived the function create_group_by has to return NULL. */ derived_handler *(*create_derived)(THD *thd, TABLE_LIST *derived); /* Create and return a select_handler if the storage engine can execute the select statement 'select, otherwise return NULL */ select_handler *(*create_select) (THD *thd, SELECT_LEX *select); /********************************************************************* Table discovery API. It allows the server to "discover" tables that exist in the storage engine, without user issuing an explicit CREATE TABLE statement. **********************************************************************/ /* This method is required for any engine that supports automatic table discovery, there is no default implementation. Given a TABLE_SHARE discover_table() fills it in with a correct table structure using one of the TABLE_SHARE::init_from_* methods. Returns HA_ERR_NO_SUCH_TABLE if the table did not exist in the engine, zero if the table was discovered successfully, or any other HA_ERR_* error code as appropriate if the table existed, but the discovery failed. */ int (*discover_table)(handlerton *hton, THD* thd, TABLE_SHARE *share); /* The discover_table_names method tells the server about all tables in the specified database that the engine knows about. Tables (or file names of tables) are added to the provided discovered_list collector object using add_table() or add_file() methods. */ class discovered_list { public: virtual bool add_table(const char *tname, size_t tlen) = 0; virtual bool add_file(const char *fname) = 0; protected: virtual ~discovered_list() = default; }; /* By default (if not implemented by the engine, but the discover_table() is implemented) it will perform a file-based discovery: - if tablefile_extensions[0] is not null, this will discovers all tables with the tablefile_extensions[0] extension. Returns 0 on success and 1 on error. */ int (*discover_table_names)(handlerton *hton, LEX_CSTRING *db, MY_DIR *dir, discovered_list *result); /* This is a method that allows to server to check if a table exists without an overhead of the complete discovery. By default (if not implemented by the engine, but the discovery_table() is implemented) it will try to perform a file-based discovery: - if tablefile_extensions[0] is not null this will look for a file name with the tablefile_extensions[0] extension. - if tablefile_extensions[0] is null, this will resort to discover_table(). Note that resorting to discover_table() is slow and the engine should probably implement its own discover_table_existence() method, if its tablefile_extensions[0] is null. Returns 1 if the table exists and 0 if it does not. */ int (*discover_table_existence)(handlerton *hton, const char *db, const char *table_name); /* This is the assisted table discovery method. Unlike the fully automatic discovery as above, here a user is expected to issue an explicit CREATE TABLE with the appropriate table attributes to "assist" the discovery of a table. But this "discovering" CREATE TABLE statement will not specify the table structure - the engine discovers it using this method. For example, FederatedX uses it in CREATE TABLE t1 ENGINE=FEDERATED CONNECTION="mysql://foo/bar/t1"; Given a TABLE_SHARE discover_table_structure() fills it in with a correct table structure using one of the TABLE_SHARE::init_from_* methods. Assisted discovery works independently from the automatic discover. An engine is allowed to support only assisted discovery and not support automatic one. Or vice versa. */ int (*discover_table_structure)(handlerton *hton, THD* thd, TABLE_SHARE *share, HA_CREATE_INFO *info); /* Notify the storage engine that the definition of the table (and the .frm file) has changed. Returns 0 if ok. */ int (*notify_tabledef_changed)(handlerton *hton, LEX_CSTRING *db, LEX_CSTRING *table_name, LEX_CUSTRING *frm, LEX_CUSTRING *org_tabledef_version, handler *file); /* System Versioning */ /** Determine if system-versioned data was modified by the transaction. @param[in,out] thd current session @param[out] trx_id transaction start ID @return transaction commit ID @retval 0 if no system-versioned data was affected by the transaction */ ulonglong (*prepare_commit_versioned)(THD *thd, ulonglong *trx_id); /** Disable or enable the internal writes of a storage engine */ void (*disable_internal_writes)(bool disable); /* backup */ void (*prepare_for_backup)(void); void (*end_backup)(void); /* Server shutdown early notification.*/ void (*pre_shutdown)(void); /* Inform handler that partitioning engine has changed the .frm and the .par files */ int (*create_partitioning_metadata)(const char *path, const char *old_path, chf_create_flags action_flag); }; extern const char *hton_no_exts[]; static inline LEX_CSTRING *hton_name(const handlerton *hton) { return &(hton2plugin[hton->slot]->name); } static inline handlerton *plugin_hton(plugin_ref plugin) { return plugin_data(plugin, handlerton *); } static inline sys_var *find_hton_sysvar(handlerton *hton, st_mysql_sys_var *var) { return find_plugin_sysvar(hton2plugin[hton->slot], var); } handlerton *ha_default_handlerton(THD *thd); handlerton *ha_default_tmp_handlerton(THD *thd); /* Possible flags of a handlerton (there can be 32 of them) */ #define HTON_NO_FLAGS 0 #define HTON_CLOSE_CURSORS_AT_COMMIT (1 << 0) #define HTON_ALTER_NOT_SUPPORTED (1 << 1) //Engine does not support alter #define HTON_CAN_RECREATE (1 << 2) //Delete all is used for truncate #define HTON_HIDDEN (1 << 3) //Engine does not appear in lists #define HTON_NOT_USER_SELECTABLE (1 << 5) #define HTON_TEMPORARY_NOT_SUPPORTED (1 << 6) //Having temporary tables not supported #define HTON_SUPPORT_LOG_TABLES (1 << 7) //Engine supports log tables #define HTON_NO_PARTITION (1 << 8) //Not partition of these tables /* This flag should be set when deciding that the engine does not allow row based binary logging (RBL) optimizations. Currently, setting this flag, means that table's read/write_set will be left untouched when logging changes to tables in this engine. In practice this means that the server will not mess around with table->write_set and/or table->read_set when using RBL and deciding whether to log full or minimal rows. It's valuable for instance for virtual tables, eg: Performance Schema which have no meaning for replication. */ #define HTON_NO_BINLOG_ROW_OPT (1 << 9) #define HTON_SUPPORTS_EXTENDED_KEYS (1 <<10) //supports extended keys #define HTON_NATIVE_SYS_VERSIONING (1 << 11) //Engine supports System Versioning // MySQL compatibility. Unused. #define HTON_SUPPORTS_FOREIGN_KEYS (1 << 0) //Foreign key constraint supported. #define HTON_CAN_MERGE (1 <<11) //Merge type table // Engine needs to access the main connect string in partitions #define HTON_CAN_READ_CONNECT_STRING_IN_PARTITION (1 <<12) /* can be replicated by wsrep replication provider plugin */ #define HTON_WSREP_REPLICATION (1 << 13) /* Set this on the *slave* that's connected to a shared with a master storage. The slave will ignore any CREATE TABLE, DROP or updates for this engine. */ #define HTON_IGNORE_UPDATES (1 << 14) /* Set this on the *master* that's connected to a shared with a slave storage. The table may not exists on the slave. The effects of having this flag are: - ALTER TABLE that changes engine from this table to another engine will be replicated as CREATE + INSERT - CREATE ... LIKE shared_table will be replicated as a full CREATE TABLE - ALTER TABLE for this engine will have "IF EXISTS" added. - RENAME TABLE for this engine will have "IF EXISTS" added. - DROP TABLE for this engine will have "IF EXISTS" added. */ #define HTON_TABLE_MAY_NOT_EXIST_ON_SLAVE (1 << 15) /* True if handler cannot rollback transactions. If not true, the transaction will be put in the transactional binlog cache. For some engines, like Aria, the rollback can happen in case of crash, but not trough a handler rollback call. */ #define HTON_NO_ROLLBACK (1 << 16) /* This storage engine can support both transactional and non transactional tables */ #define HTON_TRANSACTIONAL_AND_NON_TRANSACTIONAL (1 << 17) /* Table requires and close and reopen after truncate If the handler has HTON_CAN_RECREATE, this flag is not used */ #define HTON_REQUIRES_CLOSE_AFTER_TRUNCATE (1 << 18) /* Truncate requires that all other handlers are closed */ #define HTON_TRUNCATE_REQUIRES_EXCLUSIVE_USE (1 << 19) /* Used by mysql_inplace_alter_table() to decide if we should call hton->notify_tabledef_changed() before commit (MyRocks) or after (InnoDB). */ #define HTON_REQUIRES_NOTIFY_TABLEDEF_CHANGED_AFTER_COMMIT (1 << 20) class Ha_trx_info; struct THD_TRANS { /* true is not all entries in the ht[] support 2pc */ bool no_2pc; /* storage engines that registered in this transaction */ Ha_trx_info *ha_list; /* The purpose of this flag is to keep track of non-transactional tables that were modified in scope of: - transaction, when the variable is a member of THD::transaction.all - top-level statement or sub-statement, when the variable is a member of THD::transaction.stmt This member has the following life cycle: * stmt.modified_non_trans_table is used to keep track of modified non-transactional tables of top-level statements. At the end of the previous statement and at the beginning of the session, it is reset to FALSE. If such functions as mysql_insert, mysql_update, mysql_delete etc modify a non-transactional table, they set this flag to TRUE. At the end of the statement, the value of stmt.modified_non_trans_table is merged with all.modified_non_trans_table and gets reset. * all.modified_non_trans_table is reset at the end of transaction * Since we do not have a dedicated context for execution of a sub-statement, to keep track of non-transactional changes in a sub-statement, we re-use stmt.modified_non_trans_table. At entrance into a sub-statement, a copy of the value of stmt.modified_non_trans_table (containing the changes of the outer statement) is saved on stack. Then stmt.modified_non_trans_table is reset to FALSE and the substatement is executed. Then the new value is merged with the saved value. */ bool modified_non_trans_table; void reset() { no_2pc= FALSE; modified_non_trans_table= FALSE; m_unsafe_rollback_flags= 0; } bool is_empty() const { return ha_list == NULL; } THD_TRANS() = default; /* Remove gcc warning */ unsigned int m_unsafe_rollback_flags; /* Define the type of statements which cannot be rolled back safely. Each type occupies one bit in m_unsafe_rollback_flags. MODIFIED_NON_TRANS_TABLE is limited to mark only the temporary non-transactional table *when* it's cached along with the transactional events; the regular table is covered by the "namesake" bool var. */ enum unsafe_statement_types { MODIFIED_NON_TRANS_TABLE= 1, CREATED_TEMP_TABLE= 2, DROPPED_TEMP_TABLE= 4, DID_WAIT= 8, DID_DDL= 0x10, EXECUTED_TABLE_ADMIN_CMD= 0x20 }; void mark_modified_non_trans_temp_table() { m_unsafe_rollback_flags|= MODIFIED_NON_TRANS_TABLE; } bool has_modified_non_trans_temp_table() const { return (m_unsafe_rollback_flags & MODIFIED_NON_TRANS_TABLE) != 0; } void mark_executed_table_admin_cmd() { DBUG_PRINT("debug", ("mark_executed_table_admin_cmd")); m_unsafe_rollback_flags|= EXECUTED_TABLE_ADMIN_CMD; } bool trans_executed_admin_cmd() { return (m_unsafe_rollback_flags & EXECUTED_TABLE_ADMIN_CMD) != 0; } void mark_created_temp_table() { DBUG_PRINT("debug", ("mark_created_temp_table")); m_unsafe_rollback_flags|= CREATED_TEMP_TABLE; } void mark_dropped_temp_table() { DBUG_PRINT("debug", ("mark_dropped_temp_table")); m_unsafe_rollback_flags|= DROPPED_TEMP_TABLE; } bool has_created_dropped_temp_table() const { return (m_unsafe_rollback_flags & (CREATED_TEMP_TABLE|DROPPED_TEMP_TABLE)) != 0; } void mark_trans_did_wait() { m_unsafe_rollback_flags|= DID_WAIT; } bool trans_did_wait() const { return (m_unsafe_rollback_flags & DID_WAIT) != 0; } bool is_trx_read_write() const; void mark_trans_did_ddl() { m_unsafe_rollback_flags|= DID_DDL; } bool trans_did_ddl() const { return (m_unsafe_rollback_flags & DID_DDL) != 0; } }; /** Either statement transaction or normal transaction - related thread-specific storage engine data. If a storage engine participates in a statement/transaction, an instance of this class is present in thd->transaction.{stmt|all}.ha_list. The addition to {stmt|all}.ha_list is made by trans_register_ha(). When it's time to commit or rollback, each element of ha_list is used to access storage engine's prepare()/commit()/rollback() methods, and also to evaluate if a full two phase commit is necessary. @sa General description of transaction handling in handler.cc. */ class Ha_trx_info { public: /** Register this storage engine in the given transaction context. */ void register_ha(THD_TRANS *trans, handlerton *ht_arg) { DBUG_ASSERT(m_flags == 0); DBUG_ASSERT(m_ht == NULL); DBUG_ASSERT(m_next == NULL); m_ht= ht_arg; m_flags= (int) TRX_READ_ONLY; /* Assume read-only at start. */ m_next= trans->ha_list; trans->ha_list= this; } /** Clear, prepare for reuse. */ void reset() { m_next= NULL; m_ht= NULL; m_flags= 0; } Ha_trx_info() { reset(); } void set_trx_read_write() { DBUG_ASSERT(is_started()); m_flags|= (int) TRX_READ_WRITE; } bool is_trx_read_write() const { DBUG_ASSERT(is_started()); return m_flags & (int) TRX_READ_WRITE; } void set_trx_no_rollback() { DBUG_ASSERT(is_started()); m_flags|= (int) TRX_NO_ROLLBACK; } bool is_trx_no_rollback() const { DBUG_ASSERT(is_started()); return m_flags & (int) TRX_NO_ROLLBACK; } bool is_started() const { return m_ht != NULL; } /** Mark this transaction read-write if the argument is read-write. */ void coalesce_trx_with(const Ha_trx_info *stmt_trx) { /* Must be called only after the transaction has been started. Can be called many times, e.g. when we have many read-write statements in a transaction. */ DBUG_ASSERT(is_started()); if (stmt_trx->is_trx_read_write()) set_trx_read_write(); } Ha_trx_info *next() const { DBUG_ASSERT(is_started()); return m_next; } handlerton *ht() const { DBUG_ASSERT(is_started()); return m_ht; } private: enum { TRX_READ_ONLY= 0, TRX_READ_WRITE= 1, TRX_NO_ROLLBACK= 2 }; /** Auxiliary, used for ha_list management */ Ha_trx_info *m_next; /** Although a given Ha_trx_info instance is currently always used for the same storage engine, 'ht' is not-NULL only when the corresponding storage is a part of a transaction. */ handlerton *m_ht; /** Transaction flags related to this engine. Not-null only if this instance is a part of transaction. May assume a combination of enum values above. */ uchar m_flags; }; inline bool THD_TRANS::is_trx_read_write() const { Ha_trx_info *ha_info; for (ha_info= ha_list; ha_info; ha_info= ha_info->next()) if (ha_info->is_trx_read_write()) return TRUE; return FALSE; } enum enum_tx_isolation { ISO_READ_UNCOMMITTED, ISO_READ_COMMITTED, ISO_REPEATABLE_READ, ISO_SERIALIZABLE}; typedef struct { ulonglong data_file_length; ulonglong max_data_file_length; ulonglong index_file_length; ulonglong max_index_file_length; ulonglong delete_length; ha_rows records; ulong mean_rec_length; time_t create_time; time_t check_time; time_t update_time; ulonglong check_sum; bool check_sum_null; } PARTITION_STATS; #define UNDEF_NODEGROUP 65535 class Item; struct st_table_log_memory_entry; class partition_info; struct st_partition_iter; enum ha_choice { HA_CHOICE_UNDEF, HA_CHOICE_NO, HA_CHOICE_YES, HA_CHOICE_MAX }; enum enum_stats_auto_recalc { HA_STATS_AUTO_RECALC_DEFAULT= 0, HA_STATS_AUTO_RECALC_ON, HA_STATS_AUTO_RECALC_OFF }; /** A helper struct for schema DDL statements: CREATE SCHEMA [IF NOT EXISTS] name [ schema_specification... ] ALTER SCHEMA name [ schema_specification... ] It stores the "schema_specification" part of the CREATE/ALTER statements and is passed to mysql_create_db() and mysql_alter_db(). Currently consists of the schema default character set, collation and schema_comment. */ struct Schema_specification_st { CHARSET_INFO *default_table_charset; LEX_CSTRING *schema_comment; void init() { bzero(this, sizeof(*this)); } }; class Create_field; struct Table_period_info: Sql_alloc { Table_period_info() : create_if_not_exists(false), constr(NULL), unique_keys(0) {} Table_period_info(const char *name_arg, size_t size) : name(name_arg, size), create_if_not_exists(false), constr(NULL), unique_keys(0){} Lex_ident name; struct start_end_t { start_end_t() = default; start_end_t(const LEX_CSTRING& _start, const LEX_CSTRING& _end) : start(_start), end(_end) {} Lex_ident start; Lex_ident end; }; start_end_t period; bool create_if_not_exists; Virtual_column_info *constr; uint unique_keys; bool is_set() const { DBUG_ASSERT(bool(period.start) == bool(period.end)); return period.start; } void set_period(const Lex_ident& start, const Lex_ident& end) { period.start= start; period.end= end; } bool check_field(const Create_field* f, const Lex_ident& f_name) const; }; struct Vers_parse_info: public Table_period_info { Vers_parse_info() : Table_period_info(STRING_WITH_LEN("SYSTEM_TIME")), versioned_fields(false), unversioned_fields(false), can_native(-1) {} Table_period_info::start_end_t as_row; protected: friend struct Table_scope_and_contents_source_st; void set_start(const LEX_CSTRING field_name) { as_row.start= field_name; period.start= field_name; } void set_end(const LEX_CSTRING field_name) { as_row.end= field_name; period.end= field_name; } bool is_start(const char *name) const; bool is_end(const char *name) const; bool is_start(const Create_field &f) const; bool is_end(const Create_field &f) const; bool fix_implicit(THD *thd, Alter_info *alter_info); operator bool() const { return as_row.start || as_row.end || period.start || period.end; } bool need_check(const Alter_info *alter_info) const; bool check_conditions(const Lex_table_name &table_name, const Lex_table_name &db) const; bool create_sys_field(THD *thd, const char *field_name, Alter_info *alter_info, int flags); public: static const Lex_ident default_start; static const Lex_ident default_end; bool fix_alter_info(THD *thd, Alter_info *alter_info, HA_CREATE_INFO *create_info, TABLE *table); bool fix_create_like(Alter_info &alter_info, HA_CREATE_INFO &create_info, TABLE_LIST &src_table, TABLE_LIST &table); bool check_sys_fields(const Lex_table_name &table_name, const Lex_table_name &db, Alter_info *alter_info) const; /** At least one field was specified 'WITH/WITHOUT SYSTEM VERSIONING'. Useful for error handling. */ bool versioned_fields : 1; bool unversioned_fields : 1; int can_native; }; /** A helper struct for table DDL statements, e.g.: CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name table_contents_source; Represents a combinations of: 1. The scope, i.e. TEMPORARY or not TEMPORARY 2. The "table_contents_source" part of the table DDL statements, which can be initialized from either of these: - table_element_list ... // Explicit definition (column and key list) - LIKE another_table_name ... // Copy structure from another table - [AS] SELECT ... // Copy structure from a subquery */ struct Table_scope_and_contents_source_pod_st // For trivial members { CHARSET_INFO *alter_table_convert_to_charset; LEX_CUSTRING tabledef_version; LEX_CUSTRING org_tabledef_version; /* version of dropped table */ LEX_CSTRING connect_string; LEX_CSTRING comment; LEX_CSTRING alias; LEX_CSTRING org_storage_engine_name, new_storage_engine_name; const char *password, *tablespace; const char *data_file_name, *index_file_name; ulonglong max_rows,min_rows; ulonglong auto_increment_value; ulong table_options; ///< HA_OPTION_ values ulong avg_row_length; ulong used_fields; ulong key_block_size; ulong expression_length; ulong field_check_constraints; /* number of pages to sample during stats estimation, if used, otherwise 0. */ uint stats_sample_pages; uint null_bits; /* NULL bits at start of record */ uint options; /* OR of HA_CREATE_ options */ uint merge_insert_method; uint extra_size; /* length of extra data segment */ handlerton *db_type; /** Row type of the table definition. Defaults to ROW_TYPE_DEFAULT for all non-ALTER statements. For ALTER TABLE defaults to ROW_TYPE_NOT_USED (means "keep the current"). Can be changed either explicitly by the parser. If nothing specified inherits the value of the original table (if present). */ enum row_type row_type; enum ha_choice transactional; enum ha_storage_media storage_media; ///< DEFAULT, DISK or MEMORY enum ha_choice page_checksum; ///< If we have page_checksums engine_option_value *option_list; ///< list of table create options enum_stats_auto_recalc stats_auto_recalc; bool varchar; ///< 1 if table has a VARCHAR bool sequence; // If SEQUENCE=1 was used List *check_constraint_list; /* the following three are only for ALTER TABLE, check_if_incompatible_data() */ ha_table_option_struct *option_struct; ///< structure with parsed table options ha_field_option_struct **fields_option_struct; ///< array of field option structures ha_index_option_struct **indexes_option_struct; ///< array of index option structures /* The following is used to remember the old state for CREATE OR REPLACE */ TABLE *table; TABLE_LIST *pos_in_locked_tables; TABLE_LIST *merge_list; MDL_ticket *mdl_ticket; bool table_was_deleted; sequence_definition *seq_create_info; void init() { bzero(this, sizeof(*this)); } bool tmp_table() const { return options & HA_LEX_CREATE_TMP_TABLE; } void use_default_db_type(THD *thd) { db_type= tmp_table() ? ha_default_tmp_handlerton(thd) : ha_default_handlerton(thd); } bool versioned() const { return options & HA_VERSIONED_TABLE; } }; struct Table_scope_and_contents_source_st: public Table_scope_and_contents_source_pod_st { Vers_parse_info vers_info; Table_period_info period_info; void init() { Table_scope_and_contents_source_pod_st::init(); vers_info= {}; period_info= {}; } bool fix_create_fields(THD *thd, Alter_info *alter_info, const TABLE_LIST &create_table); bool fix_period_fields(THD *thd, Alter_info *alter_info); bool check_fields(THD *thd, Alter_info *alter_info, const Lex_table_name &table_name, const Lex_table_name &db, int select_count= 0); bool check_period_fields(THD *thd, Alter_info *alter_info); void vers_check_native(); bool vers_fix_system_fields(THD *thd, Alter_info *alter_info, const TABLE_LIST &create_table); bool vers_check_system_fields(THD *thd, Alter_info *alter_info, const Lex_table_name &table_name, const Lex_table_name &db, int select_count= 0); }; /** This struct is passed to handler table routines, e.g. ha_create(). It does not include the "OR REPLACE" and "IF NOT EXISTS" parts, as these parts are handled on the SQL level and are not needed on the handler level. */ struct HA_CREATE_INFO: public Table_scope_and_contents_source_st, public Schema_specification_st { /* TODO: remove after MDEV-20865 */ Alter_info *alter_info; void init() { Table_scope_and_contents_source_st::init(); Schema_specification_st::init(); alter_info= NULL; } bool check_conflicting_charset_declarations(CHARSET_INFO *cs); bool add_table_option_default_charset(CHARSET_INFO *cs) { // cs can be NULL, e.g.: CREATE TABLE t1 (..) CHARACTER SET DEFAULT; if (check_conflicting_charset_declarations(cs)) return true; default_table_charset= cs; used_fields|= HA_CREATE_USED_DEFAULT_CHARSET; return false; } bool add_alter_list_item_convert_to_charset(CHARSET_INFO *cs) { /* cs cannot be NULL, as sql_yacc.yy translates CONVERT TO CHARACTER SET DEFAULT to CONVERT TO CHARACTER SET TODO: Shouldn't we postpone resolution of DEFAULT until the character set of the table owner database is loaded from its db.opt? */ DBUG_ASSERT(cs); if (check_conflicting_charset_declarations(cs)) return true; alter_table_convert_to_charset= default_table_charset= cs; used_fields|= (HA_CREATE_USED_CHARSET | HA_CREATE_USED_DEFAULT_CHARSET); return false; } ulong table_options_with_row_type() { if (row_type == ROW_TYPE_DYNAMIC || row_type == ROW_TYPE_PAGE) return table_options | HA_OPTION_PACK_RECORD; else return table_options; } }; /** This struct is passed to mysql_create_table() and similar creation functions, as well as to show_create_table(). */ struct Table_specification_st: public HA_CREATE_INFO, public DDL_options_st { // Deep initialization void init() { HA_CREATE_INFO::init(); DDL_options_st::init(); } void init(DDL_options_st::Options options_arg) { HA_CREATE_INFO::init(); DDL_options_st::init(options_arg); } /* Quick initialization, for parser. Most of the HA_CREATE_INFO is left uninitialized. It gets fully initialized in sql_yacc.yy, only when the parser scans a related keyword (e.g. CREATE, ALTER). */ void lex_start() { HA_CREATE_INFO::options= 0; DDL_options_st::init(); } }; /** Structure describing changes to an index to be caused by ALTER TABLE. */ struct KEY_PAIR { /** Pointer to KEY object describing old version of index in TABLE::key_info array for TABLE instance representing old version of table. */ KEY *old_key; /** Pointer to KEY object describing new version of index in Alter_inplace_info::key_info_buffer array. */ KEY *new_key; }; /** In-place alter handler context. This is a superclass intended to be subclassed by individual handlers in order to store handler unique context between in-place alter API calls. The handler is responsible for creating the object. This can be done as early as during check_if_supported_inplace_alter(). The SQL layer is responsible for destroying the object. The class extends Sql_alloc so the memory will be mem root allocated. @see Alter_inplace_info */ class inplace_alter_handler_ctx : public Sql_alloc { public: inplace_alter_handler_ctx() = default; virtual ~inplace_alter_handler_ctx() = default; virtual void set_shared_data(const inplace_alter_handler_ctx& ctx) {} }; /** Class describing changes to be done by ALTER TABLE. Instance of this class is passed to storage engine in order to determine if this ALTER TABLE can be done using in-place algorithm. It is also used for executing the ALTER TABLE using in-place algorithm. */ class Alter_inplace_info { public: /** Create options (like MAX_ROWS) for the new version of table. @note The referenced instance of HA_CREATE_INFO object was already used to create new .FRM file for table being altered. So it has been processed by mysql_prepare_create_table() already. For example, this means that it has HA_OPTION_PACK_RECORD flag in HA_CREATE_INFO::table_options member correctly set. */ HA_CREATE_INFO *create_info; /** Alter options, fields and keys for the new version of table. @note The referenced instance of Alter_info object was already used to create new .FRM file for table being altered. So it has been processed by mysql_prepare_create_table() already. In particular, this means that in Create_field objects for fields which were present in some form in the old version of table, Create_field::field member points to corresponding Field instance for old version of table. */ Alter_info *alter_info; /** Array of KEYs for new version of table - including KEYs to be added. @note Currently this array is produced as result of mysql_prepare_create_table() call. This means that it follows different convention for KEY_PART_INFO::fieldnr values than objects in TABLE::key_info array. @todo This is mainly due to the fact that we need to keep compatibility with removed handler::add_index() call. We plan to switch to TABLE::key_info numbering later. KEYs are sorted - see sort_keys(). */ KEY *key_info_buffer; /** Size of key_info_buffer array. */ uint key_count; /** Size of index_drop_buffer array. */ uint index_drop_count= 0; /** Array of pointers to KEYs to be dropped belonging to the TABLE instance for the old version of the table. */ KEY **index_drop_buffer= nullptr; /** Size of index_add_buffer array. */ uint index_add_count= 0; /** Array of indexes into key_info_buffer for KEYs to be added, sorted in increasing order. */ uint *index_add_buffer= nullptr; KEY_PAIR *index_altered_ignorability_buffer= nullptr; /** Size of index_altered_ignorability_buffer array. */ uint index_altered_ignorability_count= 0; /** Old and new index names. Used for index rename. */ struct Rename_key_pair { Rename_key_pair(const KEY *old_key, const KEY *new_key) : old_key(old_key), new_key(new_key) { } const KEY *old_key; const KEY *new_key; }; /** Vector of key pairs from DROP/ADD index which can be renamed. */ typedef Mem_root_array Rename_keys_vector; /** A list of indexes which should be renamed. Index definitions stays the same. */ Rename_keys_vector rename_keys; /** Context information to allow handlers to keep context between in-place alter API calls. @see inplace_alter_handler_ctx for information about object lifecycle. */ inplace_alter_handler_ctx *handler_ctx= nullptr; /** If the table uses several handlers, like ha_partition uses one handler per partition, this contains a Null terminated array of ctx pointers that should all be committed together. Or NULL if only handler_ctx should be committed. Set to NULL if the low level handler::commit_inplace_alter_table uses it, to signal to the main handler that everything was committed as atomically. @see inplace_alter_handler_ctx for information about object lifecycle. */ inplace_alter_handler_ctx **group_commit_ctx= nullptr; /** Flags describing in detail which operations the storage engine is to execute. Flags are defined in sql_alter.h */ alter_table_operations handler_flags= 0; /* Alter operations involving parititons are strored here */ ulong partition_flags; /** Partition_info taking into account the partition changes to be performed. Contains all partitions which are present in the old version of the table with partitions to be dropped or changed marked as such + all partitions to be added in the new version of table marked as such. */ partition_info * const modified_part_info; /** true for ALTER IGNORE TABLE ... */ const bool ignore; /** true for online operation (LOCK=NONE) */ bool online= false; /** When ha_commit_inplace_alter_table() is called the the engine can set this to a function to be called after the ddl log is committed. */ typedef void (inplace_alter_table_commit_callback)(void *); inplace_alter_table_commit_callback *inplace_alter_table_committed= nullptr; /* This will be used as the argument to the above function when called */ void *inplace_alter_table_committed_argument= nullptr; /** which ALGORITHM and LOCK are supported by the storage engine */ enum_alter_inplace_result inplace_supported; /** Can be set by handler to describe why a given operation cannot be done in-place (HA_ALTER_INPLACE_NOT_SUPPORTED) or why it cannot be done online (HA_ALTER_INPLACE_NO_LOCK or HA_ALTER_INPLACE_COPY_NO_LOCK) If set, it will be used with ER_ALTER_OPERATION_NOT_SUPPORTED_REASON if results from handler::check_if_supported_inplace_alter() doesn't match requirements set by user. If not set, the more generic ER_ALTER_OPERATION_NOT_SUPPORTED will be used. Please set to a properly localized string, for example using my_get_err_msg(), so that the error message as a whole is localized. */ const char *unsupported_reason= nullptr; /** true when InnoDB should abort the alter when table is not empty */ const bool error_if_not_empty; /** True when DDL should avoid downgrading the MDL */ bool mdl_exclusive_after_prepare= false; Alter_inplace_info(HA_CREATE_INFO *create_info_arg, Alter_info *alter_info_arg, KEY *key_info_arg, uint key_count_arg, partition_info *modified_part_info_arg, bool ignore_arg, bool error_non_empty); ~Alter_inplace_info() { delete handler_ctx; } /** Used after check_if_supported_inplace_alter() to report error if the result does not match the LOCK/ALGORITHM requirements set by the user. @param not_supported Part of statement that was not supported. @param try_instead Suggestion as to what the user should replace not_supported with. */ void report_unsupported_error(const char *not_supported, const char *try_instead) const; void add_altered_index_ignorability(KEY *old_key, KEY *new_key) { KEY_PAIR *key_pair= index_altered_ignorability_buffer + index_altered_ignorability_count++; key_pair->old_key= old_key; key_pair->new_key= new_key; DBUG_PRINT("info", ("index had ignorability altered: %i to %i", old_key->is_ignored, new_key->is_ignored)); } }; typedef struct st_key_create_information { enum ha_key_alg algorithm; ulong block_size; uint flags; /* HA_USE.. flags */ LEX_CSTRING parser_name; LEX_CSTRING comment; bool is_ignored; } KEY_CREATE_INFO; /* Class for maintaining hooks used inside operations on tables such as: create table functions, delete table functions, and alter table functions. Class is using the Template Method pattern to separate the public usage interface from the private inheritance interface. This imposes no overhead, since the public non-virtual function is small enough to be inlined. The hooks are usually used for functions that does several things, e.g., create_table_from_items(), which both create a table and lock it. */ class TABLEOP_HOOKS { public: TABLEOP_HOOKS() = default; virtual ~TABLEOP_HOOKS() = default; inline void prelock(TABLE **tables, uint count) { do_prelock(tables, count); } inline int postlock(TABLE **tables, uint count) { return do_postlock(tables, count); } private: /* Function primitive that is called prior to locking tables */ virtual void do_prelock(TABLE **tables, uint count) { /* Default is to do nothing */ } /** Primitive called after tables are locked. If an error is returned, the tables will be unlocked and error handling start. @return Error code or zero. */ virtual int do_postlock(TABLE **tables, uint count) { return 0; /* Default is to do nothing */ } }; typedef struct st_savepoint SAVEPOINT; extern ulong savepoint_alloc_size; extern KEY_CREATE_INFO default_key_create_info; /* Forward declaration for condition pushdown to storage engine */ typedef class Item COND; typedef struct st_ha_check_opt { st_ha_check_opt() = default; /* Remove gcc warning */ uint flags; /* isam layer flags (e.g. for myisamchk) */ uint sql_flags; /* sql layer flags - for something myisamchk cannot do */ uint handler_flags; /* Reserved for handler usage */ time_t start_time; /* When check/repair starts */ KEY_CACHE *key_cache; /* new key cache when changing key cache */ void init(); } HA_CHECK_OPT; /******************************************************************************** * MRR ********************************************************************************/ typedef void *range_seq_t; typedef struct st_range_seq_if { /* Get key information SYNOPSIS get_key_info() init_params The seq_init_param parameter length OUT length of the keys in this range sequence map OUT key_part_map of the keys in this range sequence DESCRIPTION This function is set only when using HA_MRR_FIXED_KEY mode. In that mode, all ranges are single-point equality ranges that use the same set of key parts. This function allows the MRR implementation to get the length of a key, and which keyparts it uses. */ void (*get_key_info)(void *init_params, uint *length, key_part_map *map); /* Initialize the traversal of range sequence SYNOPSIS init() init_params The seq_init_param parameter n_ranges The number of ranges obtained flags A combination of HA_MRR_SINGLE_POINT, HA_MRR_FIXED_KEY RETURN An opaque value to be used as RANGE_SEQ_IF::next() parameter */ range_seq_t (*init)(void *init_params, uint n_ranges, uint flags); /* Get the next range in the range sequence SYNOPSIS next() seq The value returned by RANGE_SEQ_IF::init() range OUT Information about the next range RETURN FALSE - Ok, the range structure filled with info about the next range TRUE - No more ranges */ bool (*next) (range_seq_t seq, KEY_MULTI_RANGE *range); /* Check whether range_info orders to skip the next record SYNOPSIS skip_record() seq The value returned by RANGE_SEQ_IF::init() range_info Information about the next range (Ignored if MRR_NO_ASSOCIATION is set) rowid Rowid of the record to be checked (ignored if set to 0) RETURN 1 - Record with this range_info and/or this rowid shall be filtered out from the stream of records returned by multi_range_read_next() 0 - The record shall be left in the stream */ bool (*skip_record) (range_seq_t seq, range_id_t range_info, uchar *rowid); /* Check if the record combination matches the index condition SYNOPSIS skip_index_tuple() seq The value returned by RANGE_SEQ_IF::init() range_info Information about the next range RETURN 0 - The record combination satisfies the index condition 1 - Otherwise */ bool (*skip_index_tuple) (range_seq_t seq, range_id_t range_info); } RANGE_SEQ_IF; typedef bool (*SKIP_INDEX_TUPLE_FUNC) (range_seq_t seq, range_id_t range_info); class Cost_estimate { public: double io_count; /* number of I/O to fetch records */ double avg_io_cost; /* cost of an average I/O oper. to fetch records */ double idx_io_count; /* number of I/O to read keys */ double idx_avg_io_cost; /* cost of an average I/O oper. to fetch records */ double cpu_cost; /* total cost of operations in CPU */ double idx_cpu_cost; /* cost of operations in CPU for index */ double import_cost; /* cost of remote operations */ double mem_cost; /* cost of used memory */ static constexpr double IO_COEFF= 1; static constexpr double CPU_COEFF= 1; static constexpr double MEM_COEFF= 1; static constexpr double IMPORT_COEFF= 1; Cost_estimate() { reset(); } double total_cost() const { return IO_COEFF*io_count*avg_io_cost + IO_COEFF*idx_io_count*idx_avg_io_cost + CPU_COEFF*(cpu_cost + idx_cpu_cost) + MEM_COEFF*mem_cost + IMPORT_COEFF*import_cost; } double index_only_cost() { return IO_COEFF*idx_io_count*idx_avg_io_cost + CPU_COEFF*idx_cpu_cost; } /** Whether or not all costs in the object are zero @return true if all costs are zero, false otherwise */ bool is_zero() const { return io_count == 0.0 && idx_io_count == 0.0 && cpu_cost == 0.0 && import_cost == 0.0 && mem_cost == 0.0; } void reset() { avg_io_cost= 1.0; idx_avg_io_cost= 1.0; io_count= idx_io_count= cpu_cost= idx_cpu_cost= mem_cost= import_cost= 0.0; } void multiply(double m) { io_count *= m; cpu_cost *= m; idx_io_count *= m; idx_cpu_cost *= m; import_cost *= m; /* Don't multiply mem_cost */ } void add(const Cost_estimate* cost) { if (cost->io_count != 0.0) { double io_count_sum= io_count + cost->io_count; avg_io_cost= (io_count * avg_io_cost + cost->io_count * cost->avg_io_cost) /io_count_sum; io_count= io_count_sum; } if (cost->idx_io_count != 0.0) { double idx_io_count_sum= idx_io_count + cost->idx_io_count; idx_avg_io_cost= (idx_io_count * idx_avg_io_cost + cost->idx_io_count * cost->idx_avg_io_cost) /idx_io_count_sum; idx_io_count= idx_io_count_sum; } cpu_cost += cost->cpu_cost; idx_cpu_cost += cost->idx_cpu_cost; import_cost += cost->import_cost; } void add_io(double add_io_cnt, double add_avg_cost) { /* In edge cases add_io_cnt may be zero */ if (add_io_cnt > 0) { double io_count_sum= io_count + add_io_cnt; avg_io_cost= (io_count * avg_io_cost + add_io_cnt * add_avg_cost) / io_count_sum; io_count= io_count_sum; } } /// Add to CPU cost void add_cpu(double add_cpu_cost) { cpu_cost+= add_cpu_cost; } /// Add to import cost void add_import(double add_import_cost) { import_cost+= add_import_cost; } /// Add to memory cost void add_mem(double add_mem_cost) { mem_cost+= add_mem_cost; } /* To be used when we go from old single value-based cost calculations to the new Cost_estimate-based. */ void convert_from_cost(double cost) { reset(); io_count= cost; } }; void get_sweep_read_cost(TABLE *table, ha_rows nrows, bool interrupted, Cost_estimate *cost); /* Indicates that all scanned ranges will be singlepoint (aka equality) ranges. The ranges may not use the full key but all of them will use the same number of key parts. */ #define HA_MRR_SINGLE_POINT 1U #define HA_MRR_FIXED_KEY 2U /* Indicates that RANGE_SEQ_IF::next(&range) doesn't need to fill in the 'range' parameter. */ #define HA_MRR_NO_ASSOCIATION 4U /* The MRR user will provide ranges in key order, and MRR implementation must return rows in key order. */ #define HA_MRR_SORTED 8U /* MRR implementation doesn't have to retrieve full records */ #define HA_MRR_INDEX_ONLY 16U /* The passed memory buffer is of maximum possible size, the caller can't assume larger buffer. */ #define HA_MRR_LIMITS 32U /* Flag set <=> default MRR implementation is used (The choice is made by **_info[_const]() function which may set this flag. SQL layer remembers the flag value and then passes it to multi_read_range_init(). */ #define HA_MRR_USE_DEFAULT_IMPL 64U /* Used only as parameter to multi_range_read_info(): Flag set <=> the caller guarantees that the bounds of the scanned ranges will not have NULL values. */ #define HA_MRR_NO_NULL_ENDPOINTS 128U /* The MRR user has materialized range keys somewhere in the user's buffer. This can be used for optimization of the procedure that sorts these keys since in this case key values don't have to be copied into the MRR buffer. In other words, it is guaranteed that after RANGE_SEQ_IF::next() call the pointer in range->start_key.key will point to a key value that will remain there until the end of the MRR scan. */ #define HA_MRR_MATERIALIZED_KEYS 256U /* The following bits are reserved for use by MRR implementation. The intended use scenario: * sql layer calls handler->multi_range_read_info[_const]() - MRR implementation figures out what kind of scan it will perform, saves the result in *mrr_mode parameter. * sql layer remembers what was returned in *mrr_mode * the optimizer picks the query plan (which may or may not include the MRR scan that was estimated by the multi_range_read_info[_const] call) * if the query is an EXPLAIN statement, sql layer will call handler->multi_range_read_explain_info(mrr_mode) to get a text description of the picked MRR scan; the description will be a part of EXPLAIN output. */ #define HA_MRR_IMPLEMENTATION_FLAG1 512U #define HA_MRR_IMPLEMENTATION_FLAG2 1024U #define HA_MRR_IMPLEMENTATION_FLAG3 2048U #define HA_MRR_IMPLEMENTATION_FLAG4 4096U #define HA_MRR_IMPLEMENTATION_FLAG5 8192U #define HA_MRR_IMPLEMENTATION_FLAG6 16384U #define HA_MRR_IMPLEMENTATION_FLAGS \ (512U | 1024U | 2048U | 4096U | 8192U | 16384U) /* This is a buffer area that the handler can use to store rows. 'end_of_used_area' should be kept updated after calls to read-functions so that other parts of the code can use the remaining area (until next read calls is issued). */ typedef struct st_handler_buffer { /* const? */uchar *buffer; /* Buffer one can start using */ /* const? */uchar *buffer_end; /* End of buffer */ uchar *end_of_used_area; /* End of area that was used by handler */ } HANDLER_BUFFER; typedef struct system_status_var SSV; class ha_statistics { public: ulonglong data_file_length; /* Length off data file */ ulonglong max_data_file_length; /* Length off data file */ ulonglong index_file_length; ulonglong max_index_file_length; ulonglong delete_length; /* Free bytes */ ulonglong auto_increment_value; /* The number of records in the table. 0 - means the table has exactly 0 rows other - if (table_flags() & HA_STATS_RECORDS_IS_EXACT) the value is the exact number of records in the table else it is an estimate */ ha_rows records; ha_rows deleted; /* Deleted records */ ulong mean_rec_length; /* physical reclength */ time_t create_time; /* When table was created */ time_t check_time; time_t update_time; uint block_size; /* index block size */ ha_checksum checksum; bool checksum_null; /* number of buffer bytes that native mrr implementation needs, */ uint mrr_length_per_rec; ha_statistics(): data_file_length(0), max_data_file_length(0), index_file_length(0), max_index_file_length(0), delete_length(0), auto_increment_value(0), records(0), deleted(0), mean_rec_length(0), create_time(0), check_time(0), update_time(0), block_size(8192), checksum(0), checksum_null(FALSE), mrr_length_per_rec(0) {} }; extern "C" check_result_t handler_index_cond_check(void* h_arg); extern "C" check_result_t handler_rowid_filter_check(void* h_arg); extern "C" int handler_rowid_filter_is_active(void* h_arg); uint calculate_key_len(TABLE *, uint, const uchar *, key_part_map); /* bitmap with first N+1 bits set (keypart_map for a key prefix of [0..N] keyparts) */ inline key_part_map make_keypart_map(uint N) { return ((key_part_map)2 << (N)) - 1; } /* bitmap with first N bits set (keypart_map for a key prefix of [0..N-1] keyparts) */ inline key_part_map make_prev_keypart_map(uint N) { return ((key_part_map)1 << (N)) - 1; } /** Base class to be used by handlers different shares */ class Handler_share { public: Handler_share() = default; virtual ~Handler_share() = default; }; enum class Compare_keys : uint32_t { Equal= 0, EqualButKeyPartLength, EqualButComment, NotEqual }; /** The handler class is the interface for dynamically loadable storage engines. Do not add ifdefs and take care when adding or changing virtual functions to avoid vtable confusion Functions in this class accept and return table columns data. Two data representation formats are used: 1. TableRecordFormat - Used to pass [partial] table records to/from storage engine 2. KeyTupleFormat - used to pass index search tuples (aka "keys") to storage engine. See opt_range.cc for description of this format. TableRecordFormat ================= [Warning: this description is work in progress and may be incomplete] The table record is stored in a fixed-size buffer: record: null_bytes, column1_data, column2_data, ... The offsets of the parts of the buffer are also fixed: every column has an offset to its column{i}_data, and if it is nullable it also has its own bit in null_bytes. The record buffer only includes data about columns that are marked in the relevant column set (table->read_set and/or table->write_set, depending on the situation). It could be that it is required that null bits of non-present columns are set to 1 VARIOUS EXCEPTIONS AND SPECIAL CASES If the table has no nullable columns, then null_bytes is still present, its length is one byte which must be set to 0xFF at all times. If the table has columns of type BIT, then certain bits from those columns may be stored in null_bytes as well. Grep around for Field_bit for details. For blob columns (see Field_blob), the record buffer stores length of the data, following by memory pointer to the blob data. The pointer is owned by the storage engine and is valid until the next operation. If a blob column has NULL value, then its length and blob data pointer must be set to 0. */ class handler :public Sql_alloc { public: typedef ulonglong Table_flags; protected: TABLE_SHARE *table_share; /* The table definition */ TABLE *table; /* The current open table */ Table_flags cached_table_flags; /* Set on init() and open() */ ha_rows estimation_rows_to_insert; handler *lookup_handler; /* Statistics for the query. Updated if handler_stats.active is set */ ha_handler_stats active_handler_stats; void set_handler_stats(); public: handlerton *ht; /* storage engine of this handler */ uchar *ref; /* Pointer to current row */ uchar *dup_ref; /* Pointer to duplicate row */ uchar *lookup_buffer; /* General statistics for the table like number of row, file sizes etc */ ha_statistics stats; /* Collect query stats here if pointer is != NULL. This is a pointer because if we do a clone of the handler, we want to use the original handler for collecting statistics. */ ha_handler_stats *handler_stats; /** MultiRangeRead-related members: */ range_seq_t mrr_iter; /* Iterator to traverse the range sequence */ RANGE_SEQ_IF mrr_funcs; /* Range sequence traversal functions */ HANDLER_BUFFER *multi_range_buffer; /* MRR buffer info */ uint ranges_in_seq; /* Total number of ranges in the traversed sequence */ /** Current range (the one we're now returning rows from) */ KEY_MULTI_RANGE mrr_cur_range; /** The following are for read_range() */ key_range save_end_range, *end_range; KEY_PART_INFO *range_key_part; int key_compare_result_on_equal; /* TRUE <=> source MRR ranges and the output are ordered */ bool mrr_is_output_sorted; /** TRUE <=> we're currently traversing a range in mrr_cur_range. */ bool mrr_have_range; bool eq_range; bool internal_tmp_table; /* If internal tmp table */ bool implicit_emptied; /* Can be !=0 only if HEAP */ bool mark_trx_read_write_done; /* mark_trx_read_write was called */ bool check_table_binlog_row_based_done; /* check_table_binlog.. was called */ bool check_table_binlog_row_based_result; /* cached check_table_binlog... */ /* TRUE <=> the engine guarantees that returned records are within the range being scanned. */ bool in_range_check_pushed_down; uint lookup_errkey; uint errkey; /* Last dup key */ uint key_used_on_scan; uint active_index, keyread; /** Length of ref (1-8 or the clustered key length) */ uint ref_length; FT_INFO *ft_handler; enum init_stat { NONE=0, INDEX, RND }; init_stat inited, pre_inited; const COND *pushed_cond; /** next_insert_id is the next value which should be inserted into the auto_increment column: in a inserting-multi-row statement (like INSERT SELECT), for the first row where the autoinc value is not specified by the statement, get_auto_increment() called and asked to generate a value, next_insert_id is set to the next value, then for all other rows next_insert_id is used (and increased each time) without calling get_auto_increment(). */ ulonglong next_insert_id; /** insert id for the current row (*autogenerated*; if not autogenerated, it's 0). At first successful insertion, this variable is stored into THD::first_successful_insert_id_in_cur_stmt. */ ulonglong insert_id_for_cur_row; /** Interval returned by get_auto_increment() and being consumed by the inserter. */ /* Statistics variables */ ulonglong rows_read; ulonglong rows_tmp_read; ulonglong rows_changed; /* One bigger than needed to avoid to test if key == MAX_KEY */ ulonglong index_rows_read[MAX_KEY+1]; ha_copy_info copy_info; private: /* ANALYZE time tracker, if present */ Exec_time_tracker *tracker; public: void set_time_tracker(Exec_time_tracker *tracker_arg) { tracker=tracker_arg;} Exec_time_tracker *get_time_tracker() { return tracker; } Item *pushed_idx_cond; uint pushed_idx_cond_keyno; /* The index which the above condition is for */ /* Rowid filter pushed into the engine */ Rowid_filter *pushed_rowid_filter; /* true when the pushed rowid filter has been already filled */ bool rowid_filter_is_active; /* Used for disabling/enabling pushed_rowid_filter */ Rowid_filter *save_pushed_rowid_filter; bool save_rowid_filter_is_active; Discrete_interval auto_inc_interval_for_cur_row; /** Number of reserved auto-increment intervals. Serves as a heuristic when we have no estimation of how many records the statement will insert: the more intervals we have reserved, the bigger the next one. Reset in handler::ha_release_auto_increment(). */ uint auto_inc_intervals_count; /** Instrumented table associated with this handler. This member should be set to NULL when no instrumentation is in place, so that linking an instrumented/non instrumented server/plugin works. For example: - the server is compiled with the instrumentation. The server expects either NULL or valid pointers in m_psi. - an engine plugin is compiled without instrumentation. The plugin can not leave this pointer uninitialized, or can not leave a trash value on purpose in this pointer, as this would crash the server. */ PSI_table *m_psi; private: /** Internal state of the batch instrumentation. */ enum batch_mode_t { /** Batch mode not used. */ PSI_BATCH_MODE_NONE, /** Batch mode used, before first table io. */ PSI_BATCH_MODE_STARTING, /** Batch mode used, after first table io. */ PSI_BATCH_MODE_STARTED }; /** Batch mode state. @sa start_psi_batch_mode. @sa end_psi_batch_mode. */ batch_mode_t m_psi_batch_mode; /** The number of rows in the batch. @sa start_psi_batch_mode. @sa end_psi_batch_mode. */ ulonglong m_psi_numrows; /** The current event in a batch. @sa start_psi_batch_mode. @sa end_psi_batch_mode. */ PSI_table_locker *m_psi_locker; /** Storage for the event in a batch. @sa start_psi_batch_mode. @sa end_psi_batch_mode. */ PSI_table_locker_state m_psi_locker_state; public: virtual void unbind_psi(); virtual void rebind_psi(); /* Return error if definition doesn't match for already opened table */ virtual int discover_check_version() { return 0; } /** Put the handler in 'batch' mode when collecting table io instrumented events. When operating in batch mode: - a single start event is generated in the performance schema. - all table io performed between @c start_psi_batch_mode and @c end_psi_batch_mode is not instrumented: the number of rows affected is counted instead in @c m_psi_numrows. - a single end event is generated in the performance schema when the batch mode ends with @c end_psi_batch_mode. */ void start_psi_batch_mode(); /** End a batch started with @c start_psi_batch_mode. */ void end_psi_batch_mode(); /* If we have row logging enabled for this table */ bool row_logging, row_logging_init; /* If the row logging should be done in transaction cache */ bool row_logging_has_trans; private: /** The lock type set by when calling::ha_external_lock(). This is propagated down to the storage engine. The reason for also storing it here, is that when doing MRR we need to create/clone a second handler object. This cloned handler object needs to know about the lock_type used. */ int m_lock_type; /** Pointer where to store/retrieve the Handler_share pointer. For non partitioned handlers this is &TABLE_SHARE::ha_share. */ Handler_share **ha_share; public: handler(handlerton *ht_arg, TABLE_SHARE *share_arg) :table_share(share_arg), table(0), estimation_rows_to_insert(0), lookup_handler(this), ht(ht_arg), ref(0), lookup_buffer(NULL), handler_stats(NULL), end_range(NULL), implicit_emptied(0), mark_trx_read_write_done(0), check_table_binlog_row_based_done(0), check_table_binlog_row_based_result(0), in_range_check_pushed_down(FALSE), lookup_errkey(-1), errkey(-1), key_used_on_scan(MAX_KEY), active_index(MAX_KEY), keyread(MAX_KEY), ref_length(sizeof(my_off_t)), ft_handler(0), inited(NONE), pre_inited(NONE), pushed_cond(0), next_insert_id(0), insert_id_for_cur_row(0), tracker(NULL), pushed_idx_cond(NULL), pushed_idx_cond_keyno(MAX_KEY), pushed_rowid_filter(NULL), rowid_filter_is_active(0), save_pushed_rowid_filter(NULL), save_rowid_filter_is_active(false), auto_inc_intervals_count(0), m_psi(NULL), m_psi_batch_mode(PSI_BATCH_MODE_NONE), m_psi_numrows(0), m_psi_locker(NULL), row_logging(0), row_logging_init(0), m_lock_type(F_UNLCK), ha_share(NULL) { DBUG_PRINT("info", ("handler created F_UNLCK %d F_RDLCK %d F_WRLCK %d", F_UNLCK, F_RDLCK, F_WRLCK)); reset_statistics(); } virtual ~handler(void) { DBUG_ASSERT(m_lock_type == F_UNLCK); DBUG_ASSERT(inited == NONE); } /* To check if table has been properely opened */ bool is_open() { return ref != 0; } virtual handler *clone(const char *name, MEM_ROOT *mem_root); /** This is called after create to allow us to set up cached variables */ void init() { cached_table_flags= table_flags(); } /* ha_ methods: public wrappers for private virtual API */ int ha_open(TABLE *table, const char *name, int mode, uint test_if_locked, MEM_ROOT *mem_root= 0, List *partitions_to_open=NULL); int ha_index_init(uint idx, bool sorted) { DBUG_EXECUTE_IF("ha_index_init_fail", return HA_ERR_TABLE_DEF_CHANGED;); int result; DBUG_ENTER("ha_index_init"); DBUG_ASSERT(inited==NONE); if (!(result= index_init(idx, sorted))) { inited= INDEX; active_index= idx; end_range= NULL; } DBUG_RETURN(result); } int ha_index_end() { DBUG_ENTER("ha_index_end"); DBUG_ASSERT(inited==INDEX); inited= NONE; active_index= MAX_KEY; end_range= NULL; DBUG_RETURN(index_end()); } /* This is called after index_init() if we need to do a index scan */ virtual int prepare_index_scan() { return 0; } virtual int prepare_index_key_scan_map(const uchar * key, key_part_map keypart_map) { uint key_len= calculate_key_len(table, active_index, key, keypart_map); return prepare_index_key_scan(key, key_len); } virtual int prepare_index_key_scan( const uchar * key, uint key_len ) { return 0; } virtual int prepare_range_scan(const key_range *start_key, const key_range *end_key) { return 0; } int ha_rnd_init(bool scan) __attribute__ ((warn_unused_result)) { DBUG_EXECUTE_IF("ha_rnd_init_fail", return HA_ERR_TABLE_DEF_CHANGED;); int result; DBUG_ENTER("ha_rnd_init"); DBUG_ASSERT(inited==NONE || (inited==RND && scan)); inited= (result= rnd_init(scan)) ? NONE: RND; end_range= NULL; DBUG_RETURN(result); } int ha_rnd_end() { DBUG_ENTER("ha_rnd_end"); DBUG_ASSERT(inited==RND); inited=NONE; end_range= NULL; DBUG_RETURN(rnd_end()); } int ha_rnd_init_with_error(bool scan) __attribute__ ((warn_unused_result)); int ha_reset(); /* this is necessary in many places, e.g. in HANDLER command */ int ha_index_or_rnd_end() { return inited == INDEX ? ha_index_end() : inited == RND ? ha_rnd_end() : 0; } /** The cached_table_flags is set at ha_open and ha_external_lock */ Table_flags ha_table_flags() const { DBUG_ASSERT(cached_table_flags < (HA_LAST_TABLE_FLAG << 1)); return cached_table_flags; } /** These functions represent the public interface to *users* of the handler class, hence they are *not* virtual. For the inheritance interface, see the (private) functions write_row(), update_row(), and delete_row() below. */ int ha_external_lock(THD *thd, int lock_type); int ha_external_unlock(THD *thd) { return ha_external_lock(thd, F_UNLCK); } int ha_write_row(const uchar * buf); int ha_update_row(const uchar * old_data, const uchar * new_data); int ha_delete_row(const uchar * buf); void ha_release_auto_increment(); bool keyread_enabled() { return keyread < MAX_KEY; } int ha_start_keyread(uint idx) { int res= keyread_enabled() ? 0 : extra_opt(HA_EXTRA_KEYREAD, idx); keyread= idx; return res; } int ha_end_keyread() { if (!keyread_enabled()) return 0; keyread= MAX_KEY; return extra(HA_EXTRA_NO_KEYREAD); } int check_collation_compatibility(); int check_long_hash_compatibility() const; int ha_check_for_upgrade(HA_CHECK_OPT *check_opt); /** to be actually called to get 'check()' functionality*/ int ha_check(THD *thd, HA_CHECK_OPT *check_opt); int ha_repair(THD* thd, HA_CHECK_OPT* check_opt); void ha_start_bulk_insert(ha_rows rows, uint flags= 0) { DBUG_ENTER("handler::ha_start_bulk_insert"); estimation_rows_to_insert= rows; bzero(©_info,sizeof(copy_info)); start_bulk_insert(rows, flags); DBUG_VOID_RETURN; } int ha_end_bulk_insert(); int ha_bulk_update_row(const uchar *old_data, const uchar *new_data, ha_rows *dup_key_found); int ha_delete_all_rows(); int ha_truncate(); int ha_reset_auto_increment(ulonglong value); int ha_optimize(THD* thd, HA_CHECK_OPT* check_opt); int ha_analyze(THD* thd, HA_CHECK_OPT* check_opt); bool ha_check_and_repair(THD *thd); int ha_disable_indexes(key_map map, bool persist); int ha_enable_indexes(key_map map, bool persist); int ha_discard_or_import_tablespace(my_bool discard); int ha_rename_table(const char *from, const char *to); int ha_create(const char *name, TABLE *form, HA_CREATE_INFO *info); int ha_create_partitioning_metadata(const char *name, const char *old_name, chf_create_flags action_flag); int ha_change_partitions(HA_CREATE_INFO *create_info, const char *path, ulonglong * const copied, ulonglong * const deleted, const uchar *pack_frm_data, size_t pack_frm_len); int ha_drop_partitions(const char *path); int ha_rename_partitions(const char *path); void adjust_next_insert_id_after_explicit_value(ulonglong nr); int update_auto_increment(); virtual void print_error(int error, myf errflag); virtual bool get_error_message(int error, String *buf); uint get_dup_key(int error); bool has_dup_ref() const; /** Retrieves the names of the table and the key for which there was a duplicate entry in the case of HA_ERR_FOREIGN_DUPLICATE_KEY. If any of the table or key name is not available this method will return false and will not change any of child_table_name or child_key_name. @param child_table_name[out] Table name @param child_table_name_len[in] Table name buffer size @param child_key_name[out] Key name @param child_key_name_len[in] Key name buffer size @retval true table and key names were available and were written into the corresponding out parameters. @retval false table and key names were not available, the out parameters were not touched. */ virtual bool get_foreign_dup_key(char *child_table_name, uint child_table_name_len, char *child_key_name, uint child_key_name_len) { DBUG_ASSERT(false); return(false); } void reset_statistics() { rows_read= rows_changed= rows_tmp_read= 0; bzero(index_rows_read, sizeof(index_rows_read)); bzero(©_info, sizeof(copy_info)); } virtual void reset_copy_info() {} void ha_reset_copy_info() { bzero(©_info, sizeof(copy_info)); reset_copy_info(); } virtual void change_table_ptr(TABLE *table_arg, TABLE_SHARE *share) { table= table_arg; table_share= share; reset_statistics(); } virtual double scan_time() { return ((ulonglong2double(stats.data_file_length) / stats.block_size + 2) * avg_io_cost()); } virtual double key_scan_time(uint index) { return keyread_time(index, 1, records()); } virtual double avg_io_cost() { return 1.0; } /** The cost of reading a set of ranges from the table using an index to access it. @param index The index number. @param ranges The number of ranges to be read. If 0, it means that we calculate separately the cost of reading the key. @param rows Total number of rows to be read. This method can be used to calculate the total cost of scanning a table using an index by calling it using read_time(index, 1, table_size). */ virtual double read_time(uint index, uint ranges, ha_rows rows) { return rows2double(ranges+rows); } /** Calculate cost of 'keyread' scan for given index and number of records. @param index index to read @param ranges #of ranges to read @param rows #of records to read */ virtual double keyread_time(uint index, uint ranges, ha_rows rows); virtual const key_map *keys_to_use_for_scanning() { return &key_map_empty; } /* True if changes to the table is persistent (if there are no rollback) This is used to decide: - If the table is stored in the transaction or non transactional binary log - How things are tracked in trx and in add_changed_table(). - If we can combine several statements under one commit in the binary log. */ bool has_transactions() const { return ((ha_table_flags() & (HA_NO_TRANSACTIONS | HA_PERSISTENT_TABLE)) == 0); } /* True if table has both transactions and rollback. This is used to decide if we should write the changes to the binary log. If this is true, we don't have to write failed statements to the log as they can be rolled back. */ bool has_transactions_and_rollback() const { return has_transactions() && has_rollback(); } /* True if the underlaying table support transactions and rollback */ bool has_transaction_manager() const { return ((ha_table_flags() & HA_NO_TRANSACTIONS) == 0 && has_rollback()); } /* True if the underlaying table support TRANSACTIONAL table option */ bool has_transactional_option() const { extern handlerton *maria_hton; return partition_ht() == maria_hton || has_transaction_manager(); } /* True if table has rollback. Used to check if an update on the table can be killed fast. */ bool has_rollback() const { return ((ht->flags & HTON_NO_ROLLBACK) == 0); } /** This method is used to analyse the error to see whether the error is ignorable or not, certain handlers can have more error that are ignorable than others. E.g. the partition handler can get inserts into a range where there is no partition and this is an ignorable error. HA_ERR_FOUND_DUP_UNIQUE is a special case in MyISAM that means the same thing as HA_ERR_FOUND_DUP_KEY but can in some cases lead to a slightly different error message. */ virtual bool is_fatal_error(int error, uint flags) { if (!error || ((flags & HA_CHECK_DUP_KEY) && (error == HA_ERR_FOUND_DUPP_KEY || error == HA_ERR_FOUND_DUPP_UNIQUE)) || error == HA_ERR_AUTOINC_ERANGE || ((flags & HA_CHECK_FK_ERROR) && (error == HA_ERR_ROW_IS_REFERENCED || error == HA_ERR_NO_REFERENCED_ROW))) return FALSE; return TRUE; } /** Number of rows in table. It will only be called if (table_flags() & (HA_HAS_RECORDS | HA_STATS_RECORDS_IS_EXACT)) != 0 */ virtual int pre_records() { return 0; } virtual ha_rows records() { return stats.records; } /** Return upper bound of current number of records in the table (max. of how many records one will retrieve when doing a full table scan) If upper bound is not known, HA_POS_ERROR should be returned as a max possible upper bound. */ virtual ha_rows estimate_rows_upper_bound() { return stats.records+EXTRA_RECORDS; } /** Get the row type from the storage engine. If this method returns ROW_TYPE_NOT_USED, the information in HA_CREATE_INFO should be used. */ virtual enum row_type get_row_type() const { return ROW_TYPE_NOT_USED; } virtual const char *index_type(uint key_number) { DBUG_ASSERT(0); return "";} /** Signal that the table->read_set and table->write_set table maps changed The handler is allowed to set additional bits in the above map in this call. Normally the handler should ignore all calls until we have done a ha_rnd_init() or ha_index_init(), write_row(), update_row or delete_row() as there may be several calls to this routine. */ virtual void column_bitmaps_signal(); /* We have to check for inited as some engines, like innodb, sets active_index during table scan. */ uint get_index(void) const { return inited == INDEX ? active_index : MAX_KEY; } int ha_close(void); /** @retval 0 Bulk update used by handler @retval 1 Bulk update not used, normal operation used */ virtual bool start_bulk_update() { return 1; } /** @retval 0 Bulk delete used by handler @retval 1 Bulk delete not used, normal operation used */ virtual bool start_bulk_delete() { return 1; } /** After this call all outstanding updates must be performed. The number of duplicate key errors are reported in the duplicate key parameter. It is allowed to continue to the batched update after this call, the handler has to wait until end_bulk_update with changing state. @param dup_key_found Number of duplicate keys found @retval 0 Success @retval >0 Error code */ virtual int exec_bulk_update(ha_rows *dup_key_found) { DBUG_ASSERT(FALSE); return HA_ERR_WRONG_COMMAND; } /** Perform any needed clean-up, no outstanding updates are there at the moment. */ virtual int end_bulk_update() { return 0; } /** Execute all outstanding deletes and close down the bulk delete. @retval 0 Success @retval >0 Error code */ virtual int end_bulk_delete() { DBUG_ASSERT(FALSE); return HA_ERR_WRONG_COMMAND; } virtual int pre_index_read_map(const uchar *key, key_part_map keypart_map, enum ha_rkey_function find_flag, bool use_parallel) { return 0; } virtual int pre_index_first(bool use_parallel) { return 0; } virtual int pre_index_last(bool use_parallel) { return 0; } virtual int pre_index_read_last_map(const uchar *key, key_part_map keypart_map, bool use_parallel) { return 0; } /* virtual int pre_read_multi_range_first(KEY_MULTI_RANGE **found_range_p, KEY_MULTI_RANGE *ranges, uint range_count, bool sorted, HANDLER_BUFFER *buffer, bool use_parallel); */ virtual int pre_multi_range_read_next(bool use_parallel) { return 0; } virtual int pre_read_range_first(const key_range *start_key, const key_range *end_key, bool eq_range, bool sorted, bool use_parallel) { return 0; } virtual int pre_ft_read(bool use_parallel) { return 0; } virtual int pre_rnd_next(bool use_parallel) { return 0; } int ha_pre_rnd_init(bool scan) { int result; DBUG_ENTER("ha_pre_rnd_init"); DBUG_ASSERT(pre_inited==NONE || (pre_inited==RND && scan)); pre_inited= (result= pre_rnd_init(scan)) ? NONE: RND; DBUG_RETURN(result); } int ha_pre_rnd_end() { DBUG_ENTER("ha_pre_rnd_end"); DBUG_ASSERT(pre_inited==RND); pre_inited=NONE; DBUG_RETURN(pre_rnd_end()); } virtual int pre_rnd_init(bool scan) { return 0; } virtual int pre_rnd_end() { return 0; } virtual int pre_index_init(uint idx, bool sorted) { return 0; } virtual int pre_index_end() { return 0; } int ha_pre_index_init(uint idx, bool sorted) { int result; DBUG_ENTER("ha_pre_index_init"); DBUG_ASSERT(pre_inited==NONE); if (!(result= pre_index_init(idx, sorted))) pre_inited=INDEX; DBUG_RETURN(result); } int ha_pre_index_end() { DBUG_ENTER("ha_pre_index_end"); DBUG_ASSERT(pre_inited==INDEX); pre_inited=NONE; DBUG_RETURN(pre_index_end()); } int ha_pre_index_or_rnd_end() { return (pre_inited == INDEX ? ha_pre_index_end() : pre_inited == RND ? ha_pre_rnd_end() : 0 ); } virtual bool vers_can_native(THD *thd) { return ht->flags & HTON_NATIVE_SYS_VERSIONING; } /** @brief Positions an index cursor to the index specified in the handle. Fetches the row if available. If the key value is null, begin at the first key of the index. */ protected: virtual int index_read_map(uchar * buf, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag) { uint key_len= calculate_key_len(table, active_index, key, keypart_map); return index_read(buf, key, key_len, find_flag); } /** @brief Positions an index cursor to the index specified in the handle. Fetches the row if available. If the key value is null, begin at the first key of the index. */ virtual int index_read_idx_map(uchar * buf, uint index, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag); virtual int index_next(uchar * buf) { return HA_ERR_WRONG_COMMAND; } virtual int index_prev(uchar * buf) { return HA_ERR_WRONG_COMMAND; } virtual int index_first(uchar * buf) { return HA_ERR_WRONG_COMMAND; } virtual int index_last(uchar * buf) { return HA_ERR_WRONG_COMMAND; } virtual int index_next_same(uchar *buf, const uchar *key, uint keylen); /** @brief The following functions works like index_read, but it find the last row with the current key value or prefix. @returns @see index_read_map(). */ virtual int index_read_last_map(uchar * buf, const uchar * key, key_part_map keypart_map) { uint key_len= calculate_key_len(table, active_index, key, keypart_map); return index_read_last(buf, key, key_len); } virtual int close(void)=0; inline void update_rows_read() { if (likely(!internal_tmp_table)) rows_read++; else rows_tmp_read++; } inline void update_index_statistics() { index_rows_read[active_index]++; update_rows_read(); } public: int ha_index_read_map(uchar * buf, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag); int ha_index_read_idx_map(uchar * buf, uint index, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag); int ha_index_next(uchar * buf); int ha_index_prev(uchar * buf); int ha_index_first(uchar * buf); int ha_index_last(uchar * buf); int ha_index_next_same(uchar *buf, const uchar *key, uint keylen); /* TODO: should we make for those functions non-virtual ha_func_name wrappers, too? */ virtual ha_rows multi_range_read_info_const(uint keyno, RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges, uint *bufsz, uint *mrr_mode, Cost_estimate *cost); virtual ha_rows multi_range_read_info(uint keyno, uint n_ranges, uint keys, uint key_parts, uint *bufsz, uint *mrr_mode, Cost_estimate *cost); virtual int multi_range_read_init(RANGE_SEQ_IF *seq, void *seq_init_param, uint n_ranges, uint mrr_mode, HANDLER_BUFFER *buf); virtual int multi_range_read_next(range_id_t *range_info); /* Return string representation of the MRR plan. This is intended to be used for EXPLAIN, via the following scenario: 1. SQL layer calls handler->multi_range_read_info(). 1.1. Storage engine figures out whether it will use some non-default MRR strategy, sets appropritate bits in *mrr_mode, and returns control to SQL layer 2. SQL layer remembers the returned mrr_mode 3. SQL layer compares various options and choses the final query plan. As a part of that, it makes a choice of whether to use the MRR strategy picked in 1.1 4. EXPLAIN code converts the query plan to its text representation. If MRR strategy is part of the plan, it calls multi_range_read_explain_info(mrr_mode) to get a text representation of the picked MRR strategy. @param mrr_mode Mode which was returned by multi_range_read_info[_const] @param str INOUT string to be printed for EXPLAIN @param str_end End of the string buffer. The function is free to put the string into [str..str_end] memory range. */ virtual int multi_range_read_explain_info(uint mrr_mode, char *str, size_t size) { return 0; } virtual int read_range_first(const key_range *start_key, const key_range *end_key, bool eq_range, bool sorted); virtual int read_range_next(); void set_end_range(const key_range *end_key); int compare_key(key_range *range); int compare_key2(key_range *range) const; virtual int ft_init() { return HA_ERR_WRONG_COMMAND; } virtual int pre_ft_init() { return HA_ERR_WRONG_COMMAND; } virtual void ft_end() {} virtual int pre_ft_end() { return 0; } virtual FT_INFO *ft_init_ext(uint flags, uint inx,String *key) { return NULL; } public: virtual int ft_read(uchar *buf) { return HA_ERR_WRONG_COMMAND; } virtual int rnd_next(uchar *buf)=0; virtual int rnd_pos(uchar * buf, uchar *pos)=0; /** This function only works for handlers having HA_PRIMARY_KEY_REQUIRED_FOR_POSITION set. It will return the row with the PK given in the record argument. */ virtual int rnd_pos_by_record(uchar *record) { int error; DBUG_ASSERT(table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_POSITION); error = ha_rnd_init(false); if (error != 0) return error; position(record); error = ha_rnd_pos(record, ref); ha_rnd_end(); return error; } virtual int read_first_row(uchar *buf, uint primary_key); public: /* Same as above, but with statistics */ inline int ha_ft_read(uchar *buf); inline void ha_ft_end() { ft_end(); ft_handler=NULL; } int ha_rnd_next(uchar *buf); int ha_rnd_pos(uchar *buf, uchar *pos); inline int ha_rnd_pos_by_record(uchar *buf); inline int ha_read_first_row(uchar *buf, uint primary_key); /** The following 2 function is only needed for tables that may be internal temporary tables during joins. */ virtual int remember_rnd_pos() { return HA_ERR_WRONG_COMMAND; } virtual int restart_rnd_next(uchar *buf) { return HA_ERR_WRONG_COMMAND; } virtual ha_rows records_in_range(uint inx, const key_range *min_key, const key_range *max_key, page_range *res) { return (ha_rows) 10; } /* If HA_PRIMARY_KEY_REQUIRED_FOR_POSITION is set, then it sets ref (reference to the row, aka position, with the primary key given in the record). Otherwise it set ref to the current row. */ virtual void position(const uchar *record)=0; virtual int info(uint)=0; // see my_base.h for full description virtual void get_dynamic_partition_info(PARTITION_STATS *stat_info, uint part_id); virtual void set_partitions_to_open(List *partition_names) {} virtual bool check_if_updates_are_ignored(const char *op) const; virtual int change_partitions_to_open(List *partition_names) { return 0; } virtual int extra(enum ha_extra_function operation) { return 0; } virtual int extra_opt(enum ha_extra_function operation, ulong arg) { return extra(operation); } /* Table version id for the the table. This should change for each sucessfull ALTER TABLE. This is used by the handlerton->check_version() to ask the engine if the table definition has been updated. Storage engines that does not support inplace alter table does not have to support this call. */ virtual ulonglong table_version() const { return 0; } /** In an UPDATE or DELETE, if the row under the cursor was locked by another transaction, and the engine used an optimistic read of the last committed row value under the cursor, then the engine returns 1 from this function. MySQL must NOT try to update this optimistic value. If the optimistic value does not match the WHERE condition, MySQL can decide to skip over this row. Currently only works for InnoDB. This can be used to avoid unnecessary lock waits. If this method returns nonzero, it will also signal the storage engine that the next read will be a locking re-read of the row. */ bool ha_was_semi_consistent_read(); virtual bool was_semi_consistent_read() { return 0; } /** Tell the engine whether it should avoid unnecessary lock waits. If yes, in an UPDATE or DELETE, if the row under the cursor was locked by another transaction, the engine may try an optimistic read of the last committed row value under the cursor. */ virtual void try_semi_consistent_read(bool) {} virtual void unlock_row() {} virtual int start_stmt(THD *thd, thr_lock_type lock_type) {return 0;} virtual bool need_info_for_auto_inc() { return 0; } virtual bool can_use_for_auto_inc_init() { return 1; } virtual void get_auto_increment(ulonglong offset, ulonglong increment, ulonglong nb_desired_values, ulonglong *first_value, ulonglong *nb_reserved_values); void set_next_insert_id(ulonglong id) { DBUG_PRINT("info",("auto_increment: next value %lu", (ulong)id)); next_insert_id= id; } virtual void restore_auto_increment(ulonglong prev_insert_id) { /* Insertion of a row failed, re-use the lastly generated auto_increment id, for the next row. This is achieved by resetting next_insert_id to what it was before the failed insertion (that old value is provided by the caller). If that value was 0, it was the first row of the INSERT; then if insert_id_for_cur_row contains 0 it means no id was generated for this first row, so no id was generated since the INSERT started, so we should set next_insert_id to 0; if insert_id_for_cur_row is not 0, it is the generated id of the first and failed row, so we use it. */ next_insert_id= (prev_insert_id > 0) ? prev_insert_id : insert_id_for_cur_row; } virtual void update_create_info(HA_CREATE_INFO *create_info) {} int check_old_types(); virtual int assign_to_keycache(THD* thd, HA_CHECK_OPT* check_opt) { return HA_ADMIN_NOT_IMPLEMENTED; } virtual int preload_keys(THD* thd, HA_CHECK_OPT* check_opt) { return HA_ADMIN_NOT_IMPLEMENTED; } /* end of the list of admin commands */ virtual int indexes_are_disabled(void) {return 0;} virtual void append_create_info(String *packet) {} /** If index == MAX_KEY then a check for table is made and if index < MAX_KEY then a check is made if the table has foreign keys and if a foreign key uses this index (and thus the index cannot be dropped). @param index Index to check if foreign key uses it @retval TRUE Foreign key defined on table or index @retval FALSE No foreign key defined */ virtual bool is_fk_defined_on_table_or_index(uint index) { return FALSE; } virtual char* get_foreign_key_create_info() { return(NULL);} /* gets foreign key create string from InnoDB */ /** Used in ALTER TABLE to check if changing storage engine is allowed. @note Called without holding thr_lock.c lock. @retval true Changing storage engine is allowed. @retval false Changing storage engine not allowed. */ virtual bool can_switch_engines() { return true; } virtual int can_continue_handler_scan() { return 0; } /** Get the list of foreign keys in this table. @remark Returns the set of foreign keys where this table is the dependent or child table. @param thd The thread handle. @param f_key_list[out] The list of foreign keys. @return The handler error code or zero for success. */ virtual int get_foreign_key_list(THD *thd, List *f_key_list) { return 0; } /** Get the list of foreign keys referencing this table. @remark Returns the set of foreign keys where this table is the referenced or parent table. @param thd The thread handle. @param f_key_list[out] The list of foreign keys. @return The handler error code or zero for success. */ virtual int get_parent_foreign_key_list(THD *thd, List *f_key_list) { return 0; } virtual bool referenced_by_foreign_key() const noexcept { return false;} virtual void init_table_handle_for_HANDLER() { return; } /* prepare InnoDB for HANDLER */ virtual void free_foreign_key_create_info(char* str) {} /** The following can be called without an open handler */ virtual const char *table_type() const { return hton_name(ht)->str; } /* The following is same as table_table(), except for partition engine */ virtual const char *real_table_type() const { return hton_name(ht)->str; } const char **bas_ext() const { return ht->tablefile_extensions; } virtual int get_default_no_partitions(HA_CREATE_INFO *create_info) { return 1;} virtual void set_auto_partitions(partition_info *part_info) { return; } virtual bool get_no_parts(const char *name, uint *no_parts) { *no_parts= 0; return 0; } virtual void set_part_info(partition_info *part_info) {return;} virtual void return_record_by_parent() { return; } /* Information about index. Both index and part starts from 0 */ virtual ulong index_flags(uint idx, uint part, bool all_parts) const =0; uint max_record_length() const { return MY_MIN(HA_MAX_REC_LENGTH, max_supported_record_length()); } uint max_keys() const { return MY_MIN(MAX_KEY, max_supported_keys()); } uint max_key_parts() const { return MY_MIN(MAX_REF_PARTS, max_supported_key_parts()); } uint max_key_length() const { return MY_MIN(MAX_DATA_LENGTH_FOR_KEY, max_supported_key_length()); } uint max_key_part_length() const { return MY_MIN(MAX_DATA_LENGTH_FOR_KEY, max_supported_key_part_length()); } virtual uint max_supported_record_length() const { return HA_MAX_REC_LENGTH; } virtual uint max_supported_keys() const { return 0; } virtual uint max_supported_key_parts() const { return MAX_REF_PARTS; } virtual uint max_supported_key_length() const { return MAX_DATA_LENGTH_FOR_KEY; } virtual uint max_supported_key_part_length() const { return 255; } virtual uint min_record_length(uint options) const { return 1; } virtual int pre_calculate_checksum() { return 0; } virtual int calculate_checksum(); virtual bool is_crashed() const { return 0; } virtual bool auto_repair(int error) const { return 0; } void update_global_table_stats(); void update_global_index_stats(); /** @note lock_count() can return > 1 if the table is MERGE or partitioned. */ virtual uint lock_count(void) const { return 1; } /** Is not invoked for non-transactional temporary tables. @note store_lock() can return more than one lock if the table is MERGE or partitioned. @note that one can NOT rely on table->in_use in store_lock(). It may refer to a different thread if called from mysql_lock_abort_for_thread(). @note If the table is MERGE, store_lock() can return less locks than lock_count() claimed. This can happen when the MERGE children are not attached when this is called from another thread. */ virtual THR_LOCK_DATA **store_lock(THD *thd, THR_LOCK_DATA **to, enum thr_lock_type lock_type)=0; /** Type of table for caching query */ virtual uint8 table_cache_type() { return HA_CACHE_TBL_NONTRANSACT; } /** @brief Register a named table with a call back function to the query cache. @param thd The thread handle @param table_key A pointer to the table name in the table cache @param key_length The length of the table name @param[out] engine_callback The pointer to the storage engine call back function @param[out] engine_data Storage engine specific data which could be anything This method offers the storage engine, the possibility to store a reference to a table name which is going to be used with query cache. The method is called each time a statement is written to the cache and can be used to verify if a specific statement is cacheable. It also offers the possibility to register a generic (but static) call back function which is called each time a statement is matched against the query cache. @note If engine_data supplied with this function is different from engine_data supplied with the callback function, and the callback returns FALSE, a table invalidation on the current table will occur. @return Upon success the engine_callback will point to the storage engine call back function, if any, and engine_data will point to any storage engine data used in the specific implementation. @retval TRUE Success @retval FALSE The specified table or current statement should not be cached */ virtual my_bool register_query_cache_table(THD *thd, const char *table_key, uint key_length, qc_engine_callback *callback, ulonglong *engine_data) { *callback= 0; return TRUE; } /* Count tables invisible from all tables list on which current one built (like myisammrg and partitioned tables) tables_type mask for the tables should be added herdde returns number of such tables */ virtual uint count_query_cache_dependant_tables(uint8 *tables_type __attribute__((unused))) { return 0; } /* register tables invisible from all tables list on which current one built (like myisammrg and partitioned tables). @note they should be counted by method above cache Query cache pointer block Query cache block to write the table n Number of the table @retval FALSE - OK @retval TRUE - Error */ virtual my_bool register_query_cache_dependant_tables(THD *thd __attribute__((unused)), Query_cache *cache __attribute__((unused)), Query_cache_block_table **block __attribute__((unused)), uint *n __attribute__((unused))) { return FALSE; } /* Check if the key is a clustering key - Data is stored together with the primary key (no secondary lookup needed to find the row data). The optimizer uses this to find out the cost of fetching data. Note that in many cases a clustered key is also a reference key. This means that: - The key is part of each secondary key and is used to find the row data in the primary index when reading trough secondary indexes. - When doing a HA_KEYREAD_ONLY we get also all the primary key parts into the row. This is critical property used by index_merge. All the above is usually true for engines that store the row data in the primary key index (e.g. in a b-tree), and use the key key value as a position(). InnoDB is an example of such an engine. For a clustered (primary) key, the following should also hold: index_flags() should contain HA_CLUSTERED_INDEX table_flags() should contain HA_TABLE_SCAN_ON_INDEX For a reference key the following should also hold: table_flags() should contain HA_PRIMARY_KEY_IS_READ_INDEX. @retval TRUE yes @retval FALSE No. */ /* The following code is for primary keys */ bool pk_is_clustering_key(uint index) const { /* We have to check for MAX_INDEX as table->s->primary_key can be MAX_KEY in the case where there is no primary key. */ return index != MAX_KEY && is_clustering_key(index); } /* Same as before but for other keys, in which case we can skip the check */ bool is_clustering_key(uint index) const { DBUG_ASSERT(index != MAX_KEY); return (index_flags(index, 0, 1) & HA_CLUSTERED_INDEX); } virtual int cmp_ref(const uchar *ref1, const uchar *ref2) { return memcmp(ref1, ref2, ref_length); } /* Condition pushdown to storage engines */ /** Push condition down to the table handler. @param cond Condition to be pushed. The condition tree must not be modified by the by the caller. @return The 'remainder' condition that caller must use to filter out records. NULL means the handler will not return rows that do not match the passed condition. @note The pushed conditions form a stack (from which one can remove the last pushed condition using cond_pop). The table handler filters out rows using (pushed_cond1 AND pushed_cond2 AND ... AND pushed_condN) or less restrictive condition, depending on handler's capabilities. handler->ha_reset() call empties the condition stack. Calls to rnd_init/rnd_end, index_init/index_end etc do not affect the condition stack. */ virtual const COND *cond_push(const COND *cond) { return cond; }; /** Pop the top condition from the condition stack of the handler instance. Pops the top if condition stack, if stack is not empty. */ virtual void cond_pop() { return; }; /** Push metadata for the current operation down to the table handler. */ virtual int info_push(uint info_type, void *info) { return 0; }; /** Push down an index condition to the handler. The server will use this method to push down a condition it wants the handler to evaluate when retrieving records using a specified index. The pushed index condition will only refer to fields from this handler that is contained in the index (but it may also refer to fields in other handlers). Before the handler evaluates the condition it must read the content of the index entry into the record buffer. The handler is free to decide if and how much of the condition it will take responsibility for evaluating. Based on this evaluation it should return the part of the condition it will not evaluate. If it decides to evaluate the entire condition it should return NULL. If it decides not to evaluate any part of the condition it should return a pointer to the same condition as given as argument. @param keyno the index number to evaluate the condition on @param idx_cond the condition to be evaluated by the handler @return The part of the pushed condition that the handler decides not to evaluate */ virtual Item *idx_cond_push(uint keyno, Item* idx_cond) { return idx_cond; } /** Reset information about pushed index conditions */ virtual void cancel_pushed_idx_cond() { pushed_idx_cond= NULL; pushed_idx_cond_keyno= MAX_KEY; in_range_check_pushed_down= false; } virtual void cancel_pushed_rowid_filter() { pushed_rowid_filter= NULL; rowid_filter_is_active= false; } virtual void disable_pushed_rowid_filter() { DBUG_ASSERT(pushed_rowid_filter != NULL && save_pushed_rowid_filter == NULL); save_pushed_rowid_filter= pushed_rowid_filter; if (rowid_filter_is_active) save_rowid_filter_is_active= rowid_filter_is_active; pushed_rowid_filter= NULL; rowid_filter_is_active= false; } virtual void enable_pushed_rowid_filter() { DBUG_ASSERT(save_pushed_rowid_filter != NULL && pushed_rowid_filter == NULL); pushed_rowid_filter= save_pushed_rowid_filter; if (save_rowid_filter_is_active) rowid_filter_is_active= true; save_pushed_rowid_filter= NULL; } virtual bool rowid_filter_push(Rowid_filter *rowid_filter) { return true; } /* Needed for partition / spider */ virtual TABLE_LIST *get_next_global_for_child() { return NULL; } /** Part of old, deprecated in-place ALTER API. */ virtual bool check_if_incompatible_data(HA_CREATE_INFO *create_info, uint table_changes) { return COMPATIBLE_DATA_NO; } /* On-line/in-place ALTER TABLE interface. */ /* Here is an outline of on-line/in-place ALTER TABLE execution through this interface. Phase 1 : Initialization ======================== During this phase we determine which algorithm should be used for execution of ALTER TABLE and what level concurrency it will require. *) This phase starts by opening the table and preparing description of the new version of the table. *) Then we check if it is impossible even in theory to carry out this ALTER TABLE using the in-place algorithm. For example, because we need to change storage engine or the user has explicitly requested usage of the "copy" algorithm. *) If in-place ALTER TABLE is theoretically possible, we continue by compiling differences between old and new versions of the table in the form of HA_ALTER_FLAGS bitmap. We also build a few auxiliary structures describing requested changes and store all these data in the Alter_inplace_info object. *) Then the handler::check_if_supported_inplace_alter() method is called in order to find if the storage engine can carry out changes requested by this ALTER TABLE using the in-place algorithm. To determine this, the engine can rely on data in HA_ALTER_FLAGS/Alter_inplace_info passed to it as well as on its own checks. If the in-place algorithm can be used for this ALTER TABLE, the level of required concurrency for its execution is also returned. If any errors occur during the handler call, ALTER TABLE is aborted and no further handler functions are called. *) Locking requirements of the in-place algorithm are compared to any concurrency requirements specified by user. If there is a conflict between them, we either switch to the copy algorithm or emit an error. Phase 2 : Execution =================== In this phase the operations are executed. *) As the first step, we acquire a lock corresponding to the concurrency level which was returned by handler::check_if_supported_inplace_alter() and requested by the user. This lock is held for most of the duration of in-place ALTER (if HA_ALTER_INPLACE_COPY_LOCK or HA_ALTER_INPLACE_COPY_NO_LOCK were returned we acquire an exclusive lock for duration of the next step only). *) After that we call handler::ha_prepare_inplace_alter_table() to give the storage engine a chance to update its internal structures with a higher lock level than the one that will be used for the main step of algorithm. After that we downgrade the lock if it is necessary. *) After that, the main step of this phase and algorithm is executed. We call the handler::ha_inplace_alter_table() method, which carries out the changes requested by ALTER TABLE but does not makes them visible to other connections yet. *) We ensure that no other connection uses the table by upgrading our lock on it to exclusive. *) a) If the previous step succeeds, handler::ha_commit_inplace_alter_table() is called to allow the storage engine to do any final updates to its structures, to make all earlier changes durable and visible to other connections. b) If we have failed to upgrade lock or any errors have occurred during the handler functions calls (including commit), we call handler::ha_commit_inplace_alter_table() to rollback all changes which were done during previous steps. Phase 3 : Final =============== In this phase we: *) Update SQL-layer data-dictionary by installing .FRM file for the new version of the table. *) Inform the storage engine about this change by calling the hton::notify_table_changed() *) Destroy the Alter_inplace_info and handler_ctx objects. */ /** Check if a storage engine supports a particular alter table in-place @param altered_table TABLE object for new version of table. @param ha_alter_info Structure describing changes to be done by ALTER TABLE and holding data used during in-place alter. @retval HA_ALTER_ERROR Unexpected error. @retval HA_ALTER_INPLACE_NOT_SUPPORTED Not supported, must use copy. @retval HA_ALTER_INPLACE_EXCLUSIVE_LOCK Supported, but requires X lock. @retval HA_ALTER_INPLACE_COPY_LOCK Supported, but requires SNW lock during main phase. Prepare phase requires X lock. @retval HA_ALTER_INPLACE_SHARED_LOCK Supported, but requires SNW lock. @retval HA_ALTER_INPLACE_COPY_NO_LOCK Supported, concurrent reads/writes allowed. However, prepare phase requires X lock. @retval HA_ALTER_INPLACE_NO_LOCK Supported, concurrent reads/writes allowed. @note The default implementation uses the old in-place ALTER API to determine if the storage engine supports in-place ALTER or not. @note Called without holding thr_lock.c lock. */ virtual enum_alter_inplace_result check_if_supported_inplace_alter(TABLE *altered_table, Alter_inplace_info *ha_alter_info); /** Public functions wrapping the actual handler call. @see prepare_inplace_alter_table() */ bool ha_prepare_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info); /** Public function wrapping the actual handler call. @see inplace_alter_table() */ bool ha_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info) { return inplace_alter_table(altered_table, ha_alter_info); } /** Public function wrapping the actual handler call. Allows us to enforce asserts regardless of handler implementation. @see commit_inplace_alter_table() */ bool ha_commit_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info, bool commit); protected: /** Allows the storage engine to update internal structures with concurrent writes blocked. If check_if_supported_inplace_alter() returns HA_ALTER_INPLACE_COPY_NO_LOCK or HA_ALTER_INPLACE_COPY_LOCK, this function is called with exclusive lock otherwise the same level of locking as for inplace_alter_table() will be used. @note Storage engines are responsible for reporting any errors by calling my_error()/print_error() @note If this function reports error, commit_inplace_alter_table() will be called with commit= false. @note For partitioning, failing to prepare one partition, means that commit_inplace_alter_table() will be called to roll back changes for all partitions. This means that commit_inplace_alter_table() might be called without prepare_inplace_alter_table() having been called first for a given partition. @param altered_table TABLE object for new version of table. @param ha_alter_info Structure describing changes to be done by ALTER TABLE and holding data used during in-place alter. @retval true Error @retval false Success */ virtual bool prepare_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info) { return false; } /** Alter the table structure in-place with operations specified using HA_ALTER_FLAGS and Alter_inplace_info. The level of concurrency allowed during this operation depends on the return value from check_if_supported_inplace_alter(). @note Storage engines are responsible for reporting any errors by calling my_error()/print_error() @note If this function reports error, commit_inplace_alter_table() will be called with commit= false. @param altered_table TABLE object for new version of table. @param ha_alter_info Structure describing changes to be done by ALTER TABLE and holding data used during in-place alter. @retval true Error @retval false Success */ virtual bool inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info) { return false; } /** Commit or rollback the changes made during prepare_inplace_alter_table() and inplace_alter_table() inside the storage engine. Note that in case of rollback the allowed level of concurrency during this operation will be the same as for inplace_alter_table() and thus might be higher than during prepare_inplace_alter_table(). (For example, concurrent writes were blocked during prepare, but might not be during rollback). @note Storage engines are responsible for reporting any errors by calling my_error()/print_error() @note If this function with commit= true reports error, it will be called again with commit= false. @note In case of partitioning, this function might be called for rollback without prepare_inplace_alter_table() having been called first. Also partitioned tables sets ha_alter_info->group_commit_ctx to a NULL terminated array of the partitions handlers and if all of them are committed as one, then group_commit_ctx should be set to NULL to indicate to the partitioning handler that all partitions handlers are committed. @see prepare_inplace_alter_table(). @param altered_table TABLE object for new version of table. @param ha_alter_info Structure describing changes to be done by ALTER TABLE and holding data used during in-place alter. @param commit True => Commit, False => Rollback. @retval true Error @retval false Success */ virtual bool commit_inplace_alter_table(TABLE *altered_table, Alter_inplace_info *ha_alter_info, bool commit) { /* Nothing to commit/rollback, mark all handlers committed! */ ha_alter_info->group_commit_ctx= NULL; return false; } public: /* End of On-line/in-place ALTER TABLE interface. */ /** use_hidden_primary_key() is called in case of an update/delete when (table_flags() and HA_PRIMARY_KEY_REQUIRED_FOR_DELETE) is defined but we don't have a primary key */ virtual void use_hidden_primary_key(); virtual alter_table_operations alter_table_flags(alter_table_operations flags) { if (ht->alter_table_flags) return ht->alter_table_flags(flags); return 0; } virtual LEX_CSTRING *engine_name(); TABLE* get_table() { return table; } TABLE_SHARE* get_table_share() { return table_share; } protected: /* Service methods for use by storage engines. */ THD *ha_thd(void) const; /** Acquire the instrumented table information from a table share. @return an instrumented table share, or NULL. */ PSI_table_share *ha_table_share_psi() const; /** Default rename_table() and delete_table() rename/delete files with a given name and extensions from bas_ext(). These methods can be overridden, but their default implementation provide useful functionality. */ virtual int rename_table(const char *from, const char *to); public: /** Delete a table in the engine. Called for base as well as temporary tables. */ virtual int delete_table(const char *name); bool check_table_binlog_row_based(); bool prepare_for_row_logging(); int prepare_for_insert(bool do_create); int binlog_log_row(TABLE *table, const uchar *before_record, const uchar *after_record, Log_func *log_func); inline void clear_cached_table_binlog_row_based_flag() { check_table_binlog_row_based_done= 0; } virtual void handler_stats_updated() {} inline void ha_handler_stats_reset() { handler_stats= &active_handler_stats; active_handler_stats.reset(); active_handler_stats.active= 1; handler_stats_updated(); } inline void ha_handler_stats_disable() { if (handler_stats) { handler_stats= 0; active_handler_stats.active= 0; handler_stats_updated(); } } private: /* Cache result to avoid extra calls */ inline void mark_trx_read_write() { if (unlikely(!mark_trx_read_write_done)) { mark_trx_read_write_done= 1; mark_trx_read_write_internal(); } } private: void mark_trx_read_write_internal(); bool check_table_binlog_row_based_internal(); int create_lookup_handler(); void alloc_lookup_buffer(); int check_duplicate_long_entry_key(const uchar *new_rec, uint key_no); /** PRIMARY KEY/UNIQUE WITHOUT OVERLAPS check */ int ha_check_overlaps(const uchar *old_data, const uchar* new_data); int ha_check_long_uniques(const uchar *old_rec, const uchar *new_rec); int ha_check_inserver_constraints(const uchar *old_data, const uchar* new_data); protected: /* These are intended to be used only by handler::ha_xxxx() functions However, engines that implement read_range_XXX() (like MariaRocks) or embed other engines (like ha_partition) may need to call these also */ inline void increment_statistics(ulong SSV::*offset) const; inline void decrement_statistics(ulong SSV::*offset) const; private: /* Low-level primitives for storage engines. These should be overridden by the storage engine class. To call these methods, use the corresponding 'ha_*' method above. */ virtual int open(const char *name, int mode, uint test_if_locked)=0; /* Note: ha_index_read_idx_map() may bypass index_init() */ virtual int index_init(uint idx, bool sorted) { return 0; } virtual int index_end() { return 0; } /** rnd_init() can be called two times without rnd_end() in between (it only makes sense if scan=1). then the second call should prepare for the new table scan (e.g if rnd_init allocates the cursor, second call should position it to the start of the table, no need to deallocate and allocate it again */ virtual int rnd_init(bool scan)= 0; virtual int rnd_end() { return 0; } virtual int write_row(const uchar *buf __attribute__((unused))) { return HA_ERR_WRONG_COMMAND; } /** Update a single row. Note: If HA_ERR_FOUND_DUPP_KEY is returned, the handler must read all columns of the row so MySQL can create an error message. If the columns required for the error message are not read, the error message will contain garbage. */ virtual int update_row(const uchar *old_data __attribute__((unused)), const uchar *new_data __attribute__((unused))) { return HA_ERR_WRONG_COMMAND; } /* Optimized function for updating the first row. Only used by sequence tables */ virtual int update_first_row(const uchar *new_data); virtual int delete_row(const uchar *buf __attribute__((unused))) { return HA_ERR_WRONG_COMMAND; } /* Perform initialization for a direct update request */ public: int ha_direct_update_rows(ha_rows *update_rows, ha_rows *found_rows); virtual int direct_update_rows_init(List *update_fields) { return HA_ERR_WRONG_COMMAND; } private: virtual int pre_direct_update_rows_init(List *update_fields) { return HA_ERR_WRONG_COMMAND; } virtual int direct_update_rows(ha_rows *update_rows __attribute__((unused)), ha_rows *found_rows __attribute__((unused))) { return HA_ERR_WRONG_COMMAND; } virtual int pre_direct_update_rows() { return HA_ERR_WRONG_COMMAND; } /* Perform initialization for a direct delete request */ public: int ha_direct_delete_rows(ha_rows *delete_rows); virtual int direct_delete_rows_init() { return HA_ERR_WRONG_COMMAND; } private: virtual int pre_direct_delete_rows_init() { return HA_ERR_WRONG_COMMAND; } virtual int direct_delete_rows(ha_rows *delete_rows __attribute__((unused))) { return HA_ERR_WRONG_COMMAND; } virtual int pre_direct_delete_rows() { return HA_ERR_WRONG_COMMAND; } /** Reset state of file to after 'open'. This function is called after every statement for all tables used by that statement. */ virtual int reset() { return 0; } virtual Table_flags table_flags(void) const= 0; /** Is not invoked for non-transactional temporary tables. Tells the storage engine that we intend to read or write data from the table. This call is prefixed with a call to handler::store_lock() and is invoked only for those handler instances that stored the lock. Calls to rnd_init/index_init are prefixed with this call. When table IO is complete, we call external_lock(F_UNLCK). A storage engine writer should expect that each call to ::external_lock(F_[RD|WR]LOCK is followed by a call to ::external_lock(F_UNLCK). If it is not, it is a bug in MySQL. The name and signature originate from the first implementation in MyISAM, which would call fcntl to set/clear an advisory lock on the data file in this method. @param lock_type F_RDLCK, F_WRLCK, F_UNLCK @return non-0 in case of failure, 0 in case of success. When lock_type is F_UNLCK, the return value is ignored. */ virtual int external_lock(THD *thd __attribute__((unused)), int lock_type __attribute__((unused))) { return 0; } virtual void release_auto_increment() { return; }; /** admin commands - called from mysql_admin_table */ virtual int check_for_upgrade(HA_CHECK_OPT *check_opt) { return 0; } virtual int check(THD* thd, HA_CHECK_OPT* check_opt) { return HA_ADMIN_NOT_IMPLEMENTED; } /** In this method check_opt can be modified to specify CHECK option to use to call check() upon the table. */ virtual int repair(THD* thd, HA_CHECK_OPT* check_opt) { DBUG_ASSERT(!(ha_table_flags() & HA_CAN_REPAIR)); return HA_ADMIN_NOT_IMPLEMENTED; } protected: virtual void start_bulk_insert(ha_rows rows, uint flags) {} virtual int end_bulk_insert() { return 0; } virtual int index_read(uchar * buf, const uchar * key, uint key_len, enum ha_rkey_function find_flag) { return HA_ERR_WRONG_COMMAND; } virtual int index_read_last(uchar * buf, const uchar * key, uint key_len) { my_errno= HA_ERR_WRONG_COMMAND; return HA_ERR_WRONG_COMMAND; } friend class ha_partition; friend class ha_sequence; public: /** This method is similar to update_row, however the handler doesn't need to execute the updates at this point in time. The handler can be certain that another call to bulk_update_row will occur OR a call to exec_bulk_update before the set of updates in this query is concluded. @param old_data Old record @param new_data New record @param dup_key_found Number of duplicate keys found @retval 0 Bulk delete used by handler @retval 1 Bulk delete not used, normal operation used */ virtual int bulk_update_row(const uchar *old_data, const uchar *new_data, ha_rows *dup_key_found) { DBUG_ASSERT(FALSE); return HA_ERR_WRONG_COMMAND; } /** This is called to delete all rows in a table If the handler don't support this, then this function will return HA_ERR_WRONG_COMMAND and MySQL will delete the rows one by one. */ virtual int delete_all_rows() { return (my_errno=HA_ERR_WRONG_COMMAND); } /** Quickly remove all rows from a table. @remark This method is responsible for implementing MySQL's TRUNCATE TABLE statement, which is a DDL operation. As such, a engine can bypass certain integrity checks and in some cases avoid fine-grained locking (e.g. row locks) which would normally be required for a DELETE statement. @remark Typically, truncate is not used if it can result in integrity violation. For example, truncate is not used when a foreign key references the table, but it might be used if foreign key checks are disabled. @remark Engine is responsible for resetting the auto-increment counter. @remark The table is locked in exclusive mode. */ virtual int truncate() { int error= delete_all_rows(); return error ? error : reset_auto_increment(0); } /** Reset the auto-increment counter to the given value, i.e. the next row inserted will get the given value. */ virtual int reset_auto_increment(ulonglong value) { return 0; } virtual int optimize(THD* thd, HA_CHECK_OPT* check_opt) { return HA_ADMIN_NOT_IMPLEMENTED; } virtual int analyze(THD* thd, HA_CHECK_OPT* check_opt) { return HA_ADMIN_NOT_IMPLEMENTED; } virtual bool check_and_repair(THD *thd) { return TRUE; } virtual int disable_indexes(key_map map, bool persist) { return HA_ERR_WRONG_COMMAND; } virtual int enable_indexes(key_map map, bool persist) { return HA_ERR_WRONG_COMMAND; } virtual int discard_or_import_tablespace(my_bool discard) { return (my_errno=HA_ERR_WRONG_COMMAND); } virtual void drop_table(const char *name); virtual int create(const char *name, TABLE *form, HA_CREATE_INFO *info)=0; virtual int create_partitioning_metadata(const char *name, const char *old_name, chf_create_flags action_flag) { return FALSE; } virtual int change_partitions(HA_CREATE_INFO *create_info, const char *path, ulonglong * const copied, ulonglong * const deleted, const uchar *pack_frm_data, size_t pack_frm_len) { return HA_ERR_WRONG_COMMAND; } /* @return true if it's necessary to switch current statement log format from STATEMENT to ROW if binary log format is MIXED and autoincrement values are changed in the statement */ virtual bool autoinc_lock_mode_stmt_unsafe() const { return false; } virtual int drop_partitions(const char *path) { return HA_ERR_WRONG_COMMAND; } virtual int rename_partitions(const char *path) { return HA_ERR_WRONG_COMMAND; } virtual bool set_ha_share_ref(Handler_share **arg_ha_share) { DBUG_ASSERT(!ha_share); DBUG_ASSERT(arg_ha_share); if (ha_share || !arg_ha_share) return true; ha_share= arg_ha_share; return false; } void set_table(TABLE* table_arg) { table= table_arg; } int get_lock_type() const { return m_lock_type; } public: /* XXX to be removed, see ha_partition::partition_ht() */ virtual handlerton *partition_ht() const { return ht; } virtual bool partition_engine() { return 0;} /* Used with 'wrapper' engines, like SEQUENCE, to access to the underlaying engine used for storage. */ virtual handlerton *storage_ht() const { return ht; } inline int ha_write_tmp_row(uchar *buf); inline int ha_delete_tmp_row(uchar *buf); inline int ha_update_tmp_row(const uchar * old_data, uchar * new_data); virtual void set_lock_type(enum thr_lock_type lock); friend check_result_t handler_index_cond_check(void* h_arg); friend check_result_t handler_rowid_filter_check(void *h_arg); /** Find unique record by index or unique constrain @param record record to find (also will be fillded with actual record fields) @param unique_ref index or unique constraiun number (depends on what used in the engine @retval -1 Error @retval 1 Not found @retval 0 Found */ virtual int find_unique_row(uchar *record, uint unique_ref) { return -1; /*unsupported */} bool native_versioned() const { DBUG_ASSERT(ht); return partition_ht()->flags & HTON_NATIVE_SYS_VERSIONING; } virtual void update_partition(uint part_id) {} /** Some engines can perform column type conversion with ALGORITHM=INPLACE. These functions check for such possibility. Implementation could be based on Field_xxx::is_equal() */ virtual bool can_convert_nocopy(const Field &, const Column_definition &) const { return false; } /* If the table is using sql level unique constraints on some column */ inline bool has_long_unique(); /* Used for ALTER TABLE. Some engines can handle some differences in indexes by themself. */ virtual Compare_keys compare_key_parts(const Field &old_field, const Column_definition &new_field, const KEY_PART_INFO &old_part, const KEY_PART_INFO &new_part) const; /* If lower_case_table_names == 2 (case-preserving but case-insensitive file system) and the storage is not HA_FILE_BASED, we need to provide a lowercase file name for the engine. */ inline bool needs_lower_case_filenames() { return (lower_case_table_names == 2 && !(ha_table_flags() & HA_FILE_BASED)); } bool log_not_redoable_operation(const char *operation); protected: Handler_share *get_ha_share_ptr(); void set_ha_share_ptr(Handler_share *arg_ha_share); void lock_shared_ha_data(); void unlock_shared_ha_data(); }; #include "multi_range_read.h" #include "group_by_handler.h" bool key_uses_partial_cols(TABLE_SHARE *table, uint keyno); /* Some extern variables used with handlers */ extern const LEX_CSTRING ha_row_type[]; extern MYSQL_PLUGIN_IMPORT const char *tx_isolation_names[]; extern MYSQL_PLUGIN_IMPORT const char *binlog_format_names[]; extern TYPELIB tx_isolation_typelib; extern const char *myisam_stats_method_names[]; extern ulong total_ha, total_ha_2pc; /* lookups */ plugin_ref ha_resolve_by_name(THD *thd, const LEX_CSTRING *name, bool tmp_table); plugin_ref ha_lock_engine(THD *thd, const handlerton *hton); handlerton *ha_resolve_by_legacy_type(THD *thd, enum legacy_db_type db_type); handler *get_new_handler(TABLE_SHARE *share, MEM_ROOT *alloc, handlerton *db_type); handlerton *ha_checktype(THD *thd, handlerton *hton, bool no_substitute); static inline handlerton *ha_checktype(THD *thd, enum legacy_db_type type, bool no_substitute = 0) { return ha_checktype(thd, ha_resolve_by_legacy_type(thd, type), no_substitute); } static inline enum legacy_db_type ha_legacy_type(const handlerton *db_type) { return (db_type == NULL) ? DB_TYPE_UNKNOWN : db_type->db_type; } static inline const char *ha_resolve_storage_engine_name(const handlerton *db_type) { return (db_type == NULL ? "UNKNOWN" : db_type == view_pseudo_hton ? "VIEW" : hton_name(db_type)->str); } static inline bool ha_check_storage_engine_flag(const handlerton *db_type, uint32 flag) { return db_type && (db_type->flags & flag); } static inline bool ha_storage_engine_is_enabled(const handlerton *db_type) { return db_type && db_type->create; } /* basic stuff */ int ha_init_errors(void); int ha_init(void); int ha_end(void); int ha_initialize_handlerton(void *plugin); int ha_finalize_handlerton(void *plugin); TYPELIB *ha_known_exts(void); int ha_panic(enum ha_panic_function flag); void ha_close_connection(THD* thd); void ha_kill_query(THD* thd, enum thd_kill_levels level); void ha_signal_ddl_recovery_done(); bool ha_flush_logs(); void ha_drop_database(const char* path); void ha_checkpoint_state(bool disable); void ha_commit_checkpoint_request(void *cookie, void (*pre_hook)(void *)); int ha_create_table(THD *thd, const char *path, const char *db, const char *table_name, HA_CREATE_INFO *create_info, LEX_CUSTRING *frm, bool skip_frm_file); int ha_delete_table(THD *thd, handlerton *db_type, const char *path, const LEX_CSTRING *db, const LEX_CSTRING *alias, bool generate_warning); int ha_delete_table_force(THD *thd, const char *path, const LEX_CSTRING *db, const LEX_CSTRING *alias); void ha_prepare_for_backup(); void ha_end_backup(); void ha_pre_shutdown(); void ha_disable_internal_writes(bool disable); /* statistics and info */ bool ha_show_status(THD *thd, handlerton *db_type, enum ha_stat_type stat); /* discovery */ #ifdef MYSQL_SERVER class Discovered_table_list: public handlerton::discovered_list { THD *thd; const char *wild, *wend; bool with_temps; // whether to include temp tables in the result public: Dynamic_array *tables; Discovered_table_list(THD *thd_arg, Dynamic_array *tables_arg, const LEX_CSTRING *wild_arg); Discovered_table_list(THD *thd_arg, Dynamic_array *tables_arg) : thd(thd_arg), wild(NULL), with_temps(true), tables(tables_arg) {} ~Discovered_table_list() = default; bool add_table(const char *tname, size_t tlen) override; bool add_file(const char *fname) override; void sort(); void remove_duplicates(); // assumes that the list is sorted #ifndef DBUG_OFF /* Used to find unstable mtr tests querying INFORMATION_SCHEMA.TABLES without ORDER BY. */ void sort_desc(); #endif /* DBUG_OFF */ }; int ha_discover_table(THD *thd, TABLE_SHARE *share); int ha_discover_table_names(THD *thd, LEX_CSTRING *db, MY_DIR *dirp, Discovered_table_list *result, bool reusable); bool ha_table_exists(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table_name, LEX_CUSTRING *table_version= 0, LEX_CSTRING *partition_engine_name= 0, handlerton **hton= 0, bool *is_sequence= 0); bool ha_check_if_updates_are_ignored(THD *thd, handlerton *hton, const char *op); #endif /* MYSQL_SERVER */ /* key cache */ extern "C" int ha_init_key_cache(const char *name, KEY_CACHE *key_cache, void *); int ha_resize_key_cache(KEY_CACHE *key_cache); int ha_change_key_cache_param(KEY_CACHE *key_cache); int ha_repartition_key_cache(KEY_CACHE *key_cache); int ha_change_key_cache(KEY_CACHE *old_key_cache, KEY_CACHE *new_key_cache); /* transactions: interface to handlerton functions */ int ha_start_consistent_snapshot(THD *thd); int ha_commit_or_rollback_by_xid(XID *xid, bool commit); int ha_commit_one_phase(THD *thd, bool all); int ha_commit_trans(THD *thd, bool all); int ha_rollback_trans(THD *thd, bool all); int ha_prepare(THD *thd); int ha_recover(HASH *commit_list, MEM_ROOT *mem_root= NULL); uint ha_recover_complete(HASH *commit_list, Binlog_offset *coord= NULL); /* transactions: these functions never call handlerton functions directly */ int ha_enable_transaction(THD *thd, bool on); /* savepoints */ int ha_rollback_to_savepoint(THD *thd, SAVEPOINT *sv); bool ha_rollback_to_savepoint_can_release_mdl(THD *thd); int ha_savepoint(THD *thd, SAVEPOINT *sv); int ha_release_savepoint(THD *thd, SAVEPOINT *sv); #ifdef WITH_WSREP int ha_abort_transaction(THD *bf_thd, THD *victim_thd, my_bool signal); #endif /* these are called by storage engines */ void trans_register_ha(THD *thd, bool all, handlerton *ht, ulonglong trxid); /* Storage engine has to assume the transaction will end up with 2pc if - there is more than one 2pc-capable storage engine available - in the current transaction 2pc was not disabled yet */ #define trans_need_2pc(thd, all) ((total_ha_2pc > 1) && \ !((all ? &thd->transaction.all : &thd->transaction.stmt)->no_2pc)) const char *get_canonical_filename(handler *file, const char *path, char *tmp_path); void commit_checkpoint_notify_ha(void *cookie); inline const LEX_CSTRING *table_case_name(HA_CREATE_INFO *info, const LEX_CSTRING *name) { return ((lower_case_table_names == 2 && info->alias.str) ? &info->alias : name); } typedef bool Log_func(THD*, TABLE*, bool, const uchar*, const uchar*); int binlog_log_row(TABLE* table, const uchar *before_record, const uchar *after_record, Log_func *log_func); /** @def MYSQL_TABLE_IO_WAIT Instrumentation helper for table io_waits. Note that this helper is intended to be used from within the handler class only, as it uses members from @c handler Performance schema events are instrumented as follows: - in non batch mode, one event is generated per call - in batch mode, the number of rows affected is saved in @c m_psi_numrows, so that @c end_psi_batch_mode() generates a single event for the batch. @param OP the table operation to be performed @param INDEX the table index used if any, or MAX_KEY. @param PAYLOAD instrumented code to execute @sa handler::end_psi_batch_mode. */ #ifdef HAVE_PSI_TABLE_INTERFACE #define MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD) \ { \ if (m_psi != NULL) \ { \ switch (m_psi_batch_mode) \ { \ case PSI_BATCH_MODE_NONE: \ { \ PSI_table_locker *sub_locker= NULL; \ PSI_table_locker_state reentrant_safe_state; \ sub_locker= PSI_TABLE_CALL(start_table_io_wait) \ (& reentrant_safe_state, m_psi, OP, INDEX, \ __FILE__, __LINE__); \ PAYLOAD \ if (sub_locker != NULL) \ PSI_TABLE_CALL(end_table_io_wait) \ (sub_locker, 1); \ break; \ } \ case PSI_BATCH_MODE_STARTING: \ { \ m_psi_locker= PSI_TABLE_CALL(start_table_io_wait) \ (& m_psi_locker_state, m_psi, OP, INDEX, \ __FILE__, __LINE__); \ PAYLOAD \ if (!RESULT) \ m_psi_numrows++; \ m_psi_batch_mode= PSI_BATCH_MODE_STARTED; \ break; \ } \ case PSI_BATCH_MODE_STARTED: \ default: \ { \ DBUG_ASSERT(m_psi_batch_mode \ == PSI_BATCH_MODE_STARTED); \ PAYLOAD \ if (!RESULT) \ m_psi_numrows++; \ break; \ } \ } \ } \ else \ { \ PAYLOAD \ } \ } #else #define MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD) \ PAYLOAD #endif #define TABLE_IO_WAIT(TRACKER, OP, INDEX, RESULT, PAYLOAD) \ { \ Exec_time_tracker *this_tracker; \ if (unlikely((this_tracker= tracker))) \ tracker->start_tracking(table->in_use); \ \ MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD); \ \ if (unlikely(this_tracker)) \ tracker->stop_tracking(table->in_use); \ } void print_keydup_error(TABLE *table, KEY *key, const char *msg, myf errflag); void print_keydup_error(TABLE *table, KEY *key, myf errflag); int del_global_index_stat(THD *thd, TABLE* table, KEY* key_info); int del_global_table_stat(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table); uint ha_count_rw_all(THD *thd, Ha_trx_info **ptr_ha_info); bool non_existing_table_error(int error); uint ha_count_rw_2pc(THD *thd, bool all); uint ha_check_and_coalesce_trx_read_only(THD *thd, Ha_trx_info *ha_list, bool all, bool *no_rollback); int get_select_field_pos(Alter_info *alter_info, int select_field_count, bool versioned); #ifndef DBUG_OFF String dbug_format_row(TABLE *table, const uchar *rec, bool print_names= true); #endif /* DBUG_OFF */ #endif /* HANDLER_INCLUDED */ mysql/server/private/rpl_record.h000064400000003061151027430560013200 0ustar00/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. Copyright (c) 2008, 2013, SkySQL Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_RECORD_H #define RPL_RECORD_H #include struct rpl_group_info; struct TABLE; typedef struct st_bitmap MY_BITMAP; #if !defined(MYSQL_CLIENT) size_t pack_row(TABLE* table, MY_BITMAP const* cols, uchar *row_data, const uchar *data); #endif #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) int unpack_row(rpl_group_info *rgi, TABLE *table, uint const colcnt, uchar const *const row_data, MY_BITMAP const *cols, uchar const **const curr_row_end, ulong *const master_reclength, uchar const *const row_end); // Fill table's record[0] with default values. int prepare_record(TABLE *const table, const uint skip, const bool check); int fill_extra_persistent_columns(TABLE *table, int master_cols); #endif #endif mysql/server/private/create_options.h000064400000010654151027430560014071 0ustar00/* Copyright (C) 2010 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Engine defined options of tables/fields/keys in CREATE/ALTER TABLE. */ #ifndef SQL_CREATE_OPTIONS_INCLUDED #define SQL_CREATE_OPTIONS_INCLUDED #include "sql_class.h" enum { ENGINE_OPTION_MAX_LENGTH=32767 }; class engine_option_value: public Sql_alloc { public: LEX_CSTRING name; LEX_CSTRING value; engine_option_value *next; ///< parser puts them in a FIFO linked list bool parsed; ///< to detect unrecognized options bool quoted_value; ///< option=VAL vs. option='VAL' engine_option_value(engine_option_value *src, engine_option_value **start, engine_option_value **end) : name(src->name), value(src->value), next(NULL), parsed(src->parsed), quoted_value(src->quoted_value) { link(start, end); } engine_option_value(LEX_CSTRING &name_arg, LEX_CSTRING &value_arg, bool quoted, engine_option_value **start, engine_option_value **end) : name(name_arg), value(value_arg), next(NULL), parsed(false), quoted_value(quoted) { link(start, end); } engine_option_value(LEX_CSTRING &name_arg, engine_option_value **start, engine_option_value **end) : name(name_arg), value(null_clex_str), next(NULL), parsed(false), quoted_value(false) { link(start, end); } engine_option_value(LEX_CSTRING &name_arg, ulonglong value_arg, engine_option_value **start, engine_option_value **end, MEM_ROOT *root) : name(name_arg), next(NULL), parsed(false), quoted_value(false) { char *str; if (likely((value.str= str= (char *)alloc_root(root, 22)))) { value.length= longlong10_to_str(value_arg, str, 10) - str; link(start, end); } } static uchar *frm_read(const uchar *buff, const uchar *buff_end, engine_option_value **start, engine_option_value **end, MEM_ROOT *root); void link(engine_option_value **start, engine_option_value **end); uint frm_length(); uchar *frm_image(uchar *buff); }; typedef struct st_key KEY; class Create_field; bool resolve_sysvar_table_options(handlerton *hton); void free_sysvar_table_options(handlerton *hton); bool parse_engine_table_options(THD *thd, handlerton *ht, TABLE_SHARE *share); bool parse_option_list(THD* thd, void *option_struct, engine_option_value **option_list, ha_create_table_option *rules, bool suppress_warning, MEM_ROOT *root); bool extend_option_list(THD* thd, handlerton *hton, bool create, engine_option_value **option_list, ha_create_table_option *rules); bool engine_table_options_frm_read(const uchar *buff, size_t length, TABLE_SHARE *share); engine_option_value *merge_engine_table_options(engine_option_value *source, engine_option_value *changes, MEM_ROOT *root); uint engine_table_options_frm_length(engine_option_value *table_option_list, List &create_fields, uint keys, KEY *key_info); uchar *engine_table_options_frm_image(uchar *buff, engine_option_value *table_option_list, List &create_fields, uint keys, KEY *key_info); bool engine_options_differ(void *old_struct, void *new_struct, ha_create_table_option *rules); bool is_engine_option_known(engine_option_value *opt, ha_create_table_option *rules); #endif mysql/server/private/sql_bitmap.h000064400000017245151027430560013211 0ustar00/* Copyright (c) 2003, 2013, Oracle and/or its affiliates Copyright (c) 2009, 2013, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Implementation of a bitmap type. The idea with this is to be able to handle any constant number of bits but also be able to use 32 or 64 bits bitmaps very efficiently */ #ifndef SQL_BITMAP_INCLUDED #define SQL_BITMAP_INCLUDED #include #include #include /* An iterator to quickly walk over bits in ulonglong bitmap. */ class Table_map_iterator { ulonglong bmp; public: Table_map_iterator(ulonglong t): bmp(t){} uint next_bit() { if (!bmp) return BITMAP_END; uint bit= my_find_first_bit(bmp); bmp &= ~(1ULL << bit); return bit; } int operator++(int) { return next_bit(); } enum { BITMAP_END= 64 }; }; template class Bitmap { /* Workaround GCC optimizer bug (generating SSE instuctions on unaligned data) */ #if defined (__GNUC__) && defined(__x86_64__) && (__GNUC__ < 6) && !defined(__clang__) #define NEED_GCC_NO_SSE_WORKAROUND #endif #ifdef NEED_GCC_NO_SSE_WORKAROUND #pragma GCC push_options #pragma GCC target ("no-sse") #endif private: static const int BITS_PER_ELEMENT= sizeof(ulonglong) * 8; static const int ARRAY_ELEMENTS= (width + BITS_PER_ELEMENT - 1) / BITS_PER_ELEMENT; static const ulonglong ALL_BITS_SET= ULLONG_MAX; ulonglong buffer[ARRAY_ELEMENTS]; uint bit_index(uint n) const { DBUG_ASSERT(n < width); return ARRAY_ELEMENTS == 1 ? 0 : n / BITS_PER_ELEMENT; } ulonglong bit_mask(uint n) const { DBUG_ASSERT(n < width); return ARRAY_ELEMENTS == 1 ? 1ULL << n : 1ULL << (n % BITS_PER_ELEMENT); } ulonglong last_element_mask(int n) const { DBUG_ASSERT(n % BITS_PER_ELEMENT != 0); return bit_mask(n) - 1; } public: /* The default constructor does nothing. The caller is supposed to either zero the memory or to call set_all()/clear_all()/set_prefix() to initialize bitmap. */ Bitmap() = default; explicit Bitmap(uint prefix) { set_prefix(prefix); } void init(uint prefix) { set_prefix(prefix); } uint length() const { return width; } void set_bit(uint n) { buffer[bit_index(n)] |= bit_mask(n); } void clear_bit(uint n) { buffer[bit_index(n)] &= ~bit_mask(n); } bool is_set(uint n) const { return buffer[bit_index(n)] & bit_mask(n); } void set_prefix(uint prefix_size) { set_if_smaller(prefix_size, width); size_t idx= prefix_size / BITS_PER_ELEMENT; for (size_t i= 0; i < idx; i++) buffer[i]= ALL_BITS_SET; if (prefix_size % BITS_PER_ELEMENT) buffer[idx++]= last_element_mask(prefix_size); for (size_t i= idx; i < ARRAY_ELEMENTS; i++) buffer[i]= 0; } bool is_prefix(uint prefix_size) const { DBUG_ASSERT(prefix_size <= width); size_t idx= prefix_size / BITS_PER_ELEMENT; for (size_t i= 0; i < idx; i++) if (buffer[i] != ALL_BITS_SET) return false; if (prefix_size % BITS_PER_ELEMENT) if (buffer[idx++] != last_element_mask(prefix_size)) return false; for (size_t i= idx; i < ARRAY_ELEMENTS; i++) if (buffer[i] != 0) return false; return true; } void set_all() { if (width % BITS_PER_ELEMENT) set_prefix(width); else if (ARRAY_ELEMENTS > 1) memset(buffer, 0xff, sizeof(buffer)); else buffer[0] = ALL_BITS_SET; } void clear_all() { if (ARRAY_ELEMENTS > 1) memset(buffer, 0, sizeof(buffer)); else buffer[0]= 0; } void intersect(const Bitmap& map2) { for (size_t i= 0; i < ARRAY_ELEMENTS; i++) buffer[i] &= map2.buffer[i]; } private: /* Intersect with a bitmap represented as as longlong. In addition, pad the rest of the bitmap with 0 or 1 bits depending on pad_with_ones parameter. */ void intersect_and_pad(ulonglong map2buff, bool pad_with_ones) { buffer[0] &= map2buff; for (size_t i= 1; i < ARRAY_ELEMENTS; i++) buffer[i]= pad_with_ones ? ALL_BITS_SET : 0; if (ARRAY_ELEMENTS > 1 && (width % BITS_PER_ELEMENT) && pad_with_ones) buffer[ARRAY_ELEMENTS - 1]= last_element_mask(width); } public: void intersect(ulonglong map2buff) { intersect_and_pad(map2buff, 0); } /* Use highest bit for all bits above first element. */ void intersect_extended(ulonglong map2buff) { intersect_and_pad(map2buff, (map2buff & (1ULL << 63))); } void subtract(const Bitmap& map2) { for (size_t i= 0; i < ARRAY_ELEMENTS; i++) buffer[i] &= ~(map2.buffer[i]); } void merge(const Bitmap& map2) { for (size_t i= 0; i < ARRAY_ELEMENTS; i++) buffer[i] |= map2.buffer[i]; } bool is_clear_all() const { for (size_t i= 0; i < ARRAY_ELEMENTS; i++) if (buffer[i]) return false; return true; } bool is_subset(const Bitmap& map2) const { for (size_t i= 0; i < ARRAY_ELEMENTS; i++) if (buffer[i] & ~(map2.buffer[i])) return false; return true; } bool is_overlapping(const Bitmap& map2) const { for (size_t i= 0; i < ARRAY_ELEMENTS; i++) if (buffer[i] & map2.buffer[i]) return true; return false; } bool operator==(const Bitmap& map2) const { if (ARRAY_ELEMENTS > 1) return !memcmp(buffer,map2.buffer,sizeof(buffer)); return buffer[0] == map2.buffer[0]; } bool operator!=(const Bitmap& map2) const { return !(*this == map2); } /* Print hexadecimal representation of bitmap. Truncate trailing zeros. */ char *print(char *buf) const { size_t last; /*index of the last non-zero element, or 0. */ for (last= ARRAY_ELEMENTS - 1; last && !buffer[last]; last--){} const int HEX_DIGITS_PER_ELEMENT= BITS_PER_ELEMENT / 4; for (size_t i= 0; i < last; i++) { ulonglong num = buffer[i]; uint shift = BITS_PER_ELEMENT - 4; size_t pos= i * HEX_DIGITS_PER_ELEMENT; for (size_t j= 0; j < HEX_DIGITS_PER_ELEMENT; j++) { buf[pos + j]= _dig_vec_upper[(num >> shift) & 0xf]; shift += 4; } } longlong2str(buffer[last], buf, 16); return buf; } ulonglong to_ulonglong() const { return buffer[0]; } uint bits_set() { uint res= 0; for (size_t i= 0; i < ARRAY_ELEMENTS; i++) res += my_count_bits(buffer[i]); return res; } class Iterator { const Bitmap& map; uint offset; Table_map_iterator tmi; public: Iterator(const Bitmap& map2) : map(map2), offset(0), tmi(map2.buffer[0]) {} int operator++(int) { for (;;) { int nextbit= tmi++; if (nextbit != Table_map_iterator::BITMAP_END) return offset + nextbit; if (offset + BITS_PER_ELEMENT >= map.length()) return BITMAP_END; offset += BITS_PER_ELEMENT; tmi= Table_map_iterator(map.buffer[offset / BITS_PER_ELEMENT]); } } enum { BITMAP_END = width }; }; #ifdef NEED_GCC_NO_SSE_WORKAROUND #pragma GCC pop_options #undef NEED_GCC_NO_SSE_WORKAROUND #endif }; typedef Bitmap key_map; /* Used for finding keys */ #endif /* SQL_BITMAP_INCLUDED */ mysql/server/private/semisync_slave.h000064400000007225151027430560014077 0ustar00/* Copyright (c) 2006 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SEMISYNC_SLAVE_H #define SEMISYNC_SLAVE_H #include "semisync.h" #include "my_global.h" #include "sql_priv.h" #include "rpl_mi.h" #include "mysql.h" #include class Master_info; /** The extension class for the slave of semi-synchronous replication */ class Repl_semi_sync_slave :public Repl_semi_sync_base { public: Repl_semi_sync_slave() :m_slave_enabled(false) {} ~Repl_semi_sync_slave() = default; void set_trace_level(unsigned long trace_level) { m_trace_level = trace_level; } /* Initialize this class after MySQL parameters are initialized. this * function should be called once at bootstrap time. */ int init_object(); inline bool get_slave_enabled() { return m_slave_enabled; } void set_slave_enabled(bool enabled) { m_slave_enabled = enabled; } inline bool is_delay_master(){ return m_delay_master; } void set_delay_master(bool enabled) { m_delay_master = enabled; } void set_kill_conn_timeout(unsigned int timeout) { m_kill_conn_timeout = timeout; } /* A slave reads the semi-sync packet header and separate the metadata * from the payload data. * * Input: * header - (IN) packet header pointer * total_len - (IN) total packet length: metadata + payload * semi_flags - (IN) store flags: SEMI_SYNC_SLAVE_DELAY_SYNC and SEMI_SYNC_NEED_ACK * payload - (IN) payload: the replication event * payload_len - (IN) payload length * * Return: * 0: success; non-zero: error */ int slave_read_sync_header(const uchar *header, unsigned long total_len, int *semi_flags, const uchar **payload, unsigned long *payload_len); /* A slave replies to the master indicating its replication process. It * indicates that the slave has received all events before the specified * binlog position. */ int slave_reply(Master_info* mi); void slave_start(Master_info *mi); void slave_stop(Master_info *mi); void slave_reconnect(Master_info *mi); int request_transmit(Master_info *mi); void kill_connection(MYSQL *mysql); private: /* True when init_object has been called */ bool m_init_done; bool m_slave_enabled; /* semi-sync is enabled on the slave */ bool m_delay_master; unsigned int m_kill_conn_timeout; }; /* System and status variables for the slave component */ extern my_bool global_rpl_semi_sync_slave_enabled; extern ulong rpl_semi_sync_slave_trace_level; extern Repl_semi_sync_slave repl_semisync_slave; extern char rpl_semi_sync_slave_delay_master; extern unsigned int rpl_semi_sync_slave_kill_conn_timeout; extern unsigned long long rpl_semi_sync_slave_send_ack; extern int rpl_semi_sync_enabled(THD *thd, SHOW_VAR *var, void *buff, system_status_var *status_var, enum_var_type scope); #endif /* SEMISYNC_SLAVE_H */ mysql/server/private/sql_do.h000064400000001672151027430560012334 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_DO_INCLUDED #define SQL_DO_INCLUDED #include "sql_list.h" /* List */ class THD; class Item; bool mysql_do(THD *thd, List &values); #endif /* SQL_DO_INCLUDED */ mysql/server/private/opt_trace_context.h000064400000006333151027430560014576 0ustar00#ifndef OPT_TRACE_CONTEXT_INCLUDED #define OPT_TRACE_CONTEXT_INCLUDED #include "sql_array.h" class Opt_trace_context; struct Opt_trace_info; class Json_writer; class Opt_trace_stmt { public: /** Constructor, starts a trace for information_schema and dbug. @param ctx_arg context */ Opt_trace_stmt(Opt_trace_context *ctx_arg); ~Opt_trace_stmt(); void set_query(const char *query_ptr, size_t length, const CHARSET_INFO *charset); void open_struct(const char *key, char opening_bracket); void close_struct(const char *saved_key, char closing_bracket); void fill_info(Opt_trace_info* info); void add(const char *key, char *opening_bracket, size_t val_length); Json_writer* get_current_json() {return current_json;} void missing_privilege(); void disable_tracing_for_children(); void enable_tracing_for_children(); bool is_enabled() { return I_S_disabled == 0; } void set_allowed_mem_size(size_t mem_size); size_t get_length(); size_t get_truncated_bytes(); bool get_missing_priv() { return missing_priv; } private: Opt_trace_context *ctx; String query; // store the query sent by the user Json_writer *current_json; // stores the trace bool missing_priv; ///< whether user lacks privilege to see this trace /* 0 <=> this trace should be in information_schema. !=0 tracing is disabled, this currently happens when we want to trace a sub-statement. For now traces are only collect for the top statement not for the sub-statments. */ uint I_S_disabled; }; class Opt_trace_context { public: Opt_trace_context(); ~Opt_trace_context(); void start(THD *thd, TABLE_LIST *tbl, enum enum_sql_command sql_command, const char *query, size_t query_length, const CHARSET_INFO *query_charset, ulong max_mem_size_arg); void end(); void set_query(const char *query, size_t length, const CHARSET_INFO *charset); void delete_traces(); void set_allowed_mem_size(size_t mem_size); size_t remaining_mem_size(); private: Opt_trace_stmt* top_trace() { return *(traces.front()); } public: /* This returns the top trace from the list of traces. This function is used when we want to see the contents of the INFORMATION_SCHEMA.OPTIMIZER_TRACE table. */ Opt_trace_stmt* get_top_trace() { if (!traces.elements()) return NULL; return top_trace(); } /* This returns the current trace, to which we are still writing and has not been finished */ Json_writer* get_current_json() { if (!is_started()) return NULL; return current_trace->get_current_json(); } bool empty() { return static_cast(traces.elements()) == 0; } bool is_started() { return current_trace && current_trace->is_enabled(); } bool disable_tracing_if_required(); bool enable_tracing_if_required(); bool is_enabled(); void missing_privilege(); static const char *flag_names[]; enum { FLAG_DEFAULT = 0, FLAG_ENABLED = 1 << 0 }; private: /* List of traces (currently it stores only 1 trace) */ Dynamic_array traces; Opt_trace_stmt *current_trace; size_t max_mem_size; }; #endif /* OPT_TRACE_CONTEXT_INCLUDED */ mysql/server/private/field.h000064400000657137151027430560012153 0ustar00#ifndef FIELD_INCLUDED #define FIELD_INCLUDED /* Copyright (c) 2000, 2015, Oracle and/or its affiliates. Copyright (c) 2008, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Because of the function make_new_field() all field classes that have static variables must declare the size_of() member function. */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "mysqld.h" /* system_charset_info */ #include "table.h" /* TABLE */ #include "sql_string.h" /* String */ #include "my_decimal.h" /* my_decimal */ #include "sql_error.h" /* Sql_condition */ #include "compat56.h" #include "sql_type.h" /* Type_std_attributes */ #include "field_comp.h" class Send_field; class Copy_field; class Protocol; class Protocol_text; class Create_field; class Relay_log_info; class Field; class Column_statistics; class Column_statistics_collected; class Item_func; class Item_bool_func; class Item_equal; class Virtual_tmp_table; class Qualified_column_ident; class Table_ident; class SEL_ARG; class RANGE_OPT_PARAM; struct KEY_PART; struct SORT_FIELD; struct SORT_FIELD_ATTR; enum enum_check_fields { CHECK_FIELD_IGNORE, CHECK_FIELD_EXPRESSION, CHECK_FIELD_WARN, CHECK_FIELD_ERROR_FOR_NULL, }; enum ignore_value_reaction { IGNORE_MEANS_ERROR, IGNORE_MEANS_DEFAULT, IGNORE_MEANS_FIELD_VALUE }; ignore_value_reaction find_ignore_reaction(THD *thd); enum enum_conv_type { CONV_TYPE_PRECISE, CONV_TYPE_VARIANT, CONV_TYPE_SUBSET_TO_SUPERSET, CONV_TYPE_SUPERSET_TO_SUBSET, CONV_TYPE_IMPOSSIBLE }; class Conv_param { uint16 m_table_def_flags; public: Conv_param(uint16 table_def_flags) :m_table_def_flags(table_def_flags) { } uint16 table_def_flags() const { return m_table_def_flags; } }; class Conv_source: public Type_handler_hybrid_field_type { uint16 m_metadata; CHARSET_INFO *m_cs; public: Conv_source(const Type_handler *h, uint16 metadata, CHARSET_INFO *cs) :Type_handler_hybrid_field_type(h), m_metadata(metadata), m_cs(cs) { DBUG_ASSERT(cs); } uint16 metadata() const { return m_metadata; } uint mbmaxlen() const { return m_cs->mbmaxlen; } }; /* Common declarations for Field and Item */ class Value_source { protected: // Parameters for warning and note generation class Warn_filter { bool m_want_warning_edom; bool m_want_note_truncated_spaces; public: Warn_filter(bool want_warning_edom, bool want_note_truncated_spaces) : m_want_warning_edom(want_warning_edom), m_want_note_truncated_spaces(want_note_truncated_spaces) { } Warn_filter(const THD *thd); bool want_warning_edom() const { return m_want_warning_edom; } bool want_note_truncated_spaces() const { return m_want_note_truncated_spaces; } }; class Warn_filter_all: public Warn_filter { public: Warn_filter_all() :Warn_filter(true, true) { } }; class Converter_double_to_longlong { protected: bool m_error; longlong m_result; public: Converter_double_to_longlong(double nr, bool unsigned_flag); longlong result() const { return m_result; } bool error() const { return m_error; } void push_warning(THD *thd, double nr, bool unsigned_flag); }; class Converter_double_to_longlong_with_warn: public Converter_double_to_longlong { public: Converter_double_to_longlong_with_warn(THD *thd, double nr, bool unsigned_flag) :Converter_double_to_longlong(nr, unsigned_flag) { if (m_error) push_warning(thd, nr, unsigned_flag); } Converter_double_to_longlong_with_warn(double nr, bool unsigned_flag) :Converter_double_to_longlong(nr, unsigned_flag) { if (m_error) push_warning(current_thd, nr, unsigned_flag); } }; // String-to-number converters class Converter_string_to_number { protected: char *m_end_of_num; // Where the low-level conversion routine stopped int m_error; // The error code returned by the low-level routine bool m_edom; // If EDOM-alike error happened during conversion /** Check string-to-number conversion and produce a warning if - could not convert any digits (EDOM-alike error) - found garbage at the end of the string - found extra spaces at the end (a note) See also Field_num::check_edom_and_truncation() for a similar function. @param thd - the thread that will be used to generate warnings. Can be NULL (which means current_thd will be used if a warning is really necessary). @param type - name of the data type (e.g. "INTEGER", "DECIMAL", "DOUBLE") @param cs - character set of the original string @param str - the original string @param end - the end of the string @param allow_notes - tells if trailing space notes should be displayed or suppressed. Unlike Field_num::check_edom_and_truncation(), this function does not distinguish between EDOM and truncation and reports the same warning for both cases. Perhaps we should eventually print different warnings, to make the explicit CAST work closer to the implicit cast in Field_xxx::store(). */ void check_edom_and_truncation(THD *thd, Warn_filter filter, const char *type, CHARSET_INFO *cs, const char *str, size_t length) const; public: int error() const { return m_error; } }; class Converter_strntod: public Converter_string_to_number { double m_result; public: Converter_strntod(CHARSET_INFO *cs, const char *str, size_t length) { m_result= cs->strntod((char *) str, length, &m_end_of_num, &m_error); // strntod() does not set an error if the input string was empty m_edom= m_error !=0 || str == m_end_of_num; } double result() const { return m_result; } }; class Converter_string_to_longlong: public Converter_string_to_number { protected: longlong m_result; public: longlong result() const { return m_result; } }; class Converter_strntoll: public Converter_string_to_longlong { public: Converter_strntoll(CHARSET_INFO *cs, const char *str, size_t length) { m_result= cs->strntoll(str, length, 10, &m_end_of_num, &m_error); /* All non-zero errors means EDOM error. strntoll() does not set an error if the input string was empty. Check it here. Notice the different with the same condition in Converter_strntoll10. */ m_edom= m_error != 0 || str == m_end_of_num; } }; class Converter_strtoll10: public Converter_string_to_longlong { public: Converter_strtoll10(CHARSET_INFO *cs, const char *str, size_t length) { m_end_of_num= (char *) str + length; m_result= cs->strtoll10(str, &m_end_of_num, &m_error); /* Negative error means "good negative number". Only a positive m_error value means a real error. strtoll10() sets error to MY_ERRNO_EDOM in case of an empty string, so we don't have to additionally catch empty strings here. */ m_edom= m_error > 0; } }; class Converter_str2my_decimal: public Converter_string_to_number { public: Converter_str2my_decimal(uint mask, CHARSET_INFO *cs, const char *str, size_t length, my_decimal *buf) { DBUG_ASSERT(length < UINT_MAX32); m_error= str2my_decimal(mask, str, length, cs, buf, (const char **) &m_end_of_num); // E_DEC_TRUNCATED means a very minor truncation: '1e-100' -> 0 m_edom= m_error && m_error != E_DEC_TRUNCATED; } }; // String-to-number converters with automatic warning generation class Converter_strntod_with_warn: public Converter_strntod { public: Converter_strntod_with_warn(THD *thd, Warn_filter filter, CHARSET_INFO *cs, const char *str, size_t length) :Converter_strntod(cs, str, length) { check_edom_and_truncation(thd, filter, "DOUBLE", cs, str, length); } }; class Converter_strntoll_with_warn: public Converter_strntoll { public: Converter_strntoll_with_warn(THD *thd, Warn_filter filter, CHARSET_INFO *cs, const char *str, size_t length) :Converter_strntoll(cs, str, length) { check_edom_and_truncation(thd, filter, "INTEGER", cs, str, length); } }; class Converter_strtoll10_with_warn: public Converter_strtoll10 { public: Converter_strtoll10_with_warn(THD *thd, Warn_filter filter, CHARSET_INFO *cs, const char *str, size_t length) :Converter_strtoll10(cs, str, length) { check_edom_and_truncation(thd, filter, "INTEGER", cs, str, length); } }; class Converter_str2my_decimal_with_warn: public Converter_str2my_decimal { public: Converter_str2my_decimal_with_warn(THD *thd, Warn_filter filter, uint mask, CHARSET_INFO *cs, const char *str, size_t length, my_decimal *buf) :Converter_str2my_decimal(mask, cs, str, length, buf) { check_edom_and_truncation(thd, filter, "DECIMAL", cs, str, length); } }; // String-to-number conversion methods for the old code compatibility longlong longlong_from_string_with_check(CHARSET_INFO *cs, const char *cptr, const char *end) const { /* TODO: Give error if we wanted a signed integer and we got an unsigned one Notice, longlong_from_string_with_check() honors thd->no_error, because it's used to handle queries like this: SELECT COUNT(@@basedir); and is called when Item_func_get_system_var::update_null_value() suppresses warnings and then calls val_int(). The other methods {double|decimal}_from_string_with_check() ignore thd->no_errors, because they are not used for update_null_value() and they always allow all kind of warnings. */ THD *thd= current_thd; return Converter_strtoll10_with_warn(thd, Warn_filter(thd), cs, cptr, end - cptr).result(); } double double_from_string_with_check(CHARSET_INFO *cs, const char *cptr, const char *end) const { return Converter_strntod_with_warn(NULL, Warn_filter_all(), cs, cptr, end - cptr).result(); } my_decimal *decimal_from_string_with_check(my_decimal *decimal_value, CHARSET_INFO *cs, const char *cptr, const char *end) { Converter_str2my_decimal_with_warn(NULL, Warn_filter_all(), E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM, cs, cptr, end - cptr, decimal_value); return decimal_value; } longlong longlong_from_hex_hybrid(const char *str, size_t length) { const char *end= str + length; const char *ptr= end - MY_MIN(length, sizeof(longlong)); ulonglong value= 0; for ( ; ptr != end ; ptr++) value= (value << 8) + (ulonglong) (uchar) *ptr; return (longlong) value; } longlong longlong_from_string_with_check(const String *str) const { return longlong_from_string_with_check(str->charset(), str->ptr(), str->end()); } double double_from_string_with_check(const String *str) const { return double_from_string_with_check(str->charset(), str->ptr(), str->end()); } my_decimal *decimal_from_string_with_check(my_decimal *decimal_value, const String *str) { return decimal_from_string_with_check(decimal_value, str->charset(), str->ptr(), str->end()); } // End of String-to-number conversion methods public: /* The enumeration Subst_constraint is currently used only in implementations of the virtual function subst_argument_checker. */ enum Subst_constraint { ANY_SUBST, /* Any substitution for a field is allowed */ IDENTITY_SUBST /* Substitution for a field is allowed if any two different values of the field type are not equal */ }; /* Item context attributes. Comparison functions pass their attributes to propagate_equal_fields(). For example, for string comparison, the collation of the comparison operation is important inside propagate_equal_fields(). */ class Context { /* Which type of propagation is allowed: - ANY_SUBST (loose equality, according to the collation), or - IDENTITY_SUBST (strict binary equality). */ Subst_constraint m_subst_constraint; /* Comparison type. Important only when ANY_SUBSTS. */ const Type_handler *m_compare_handler; /* Collation of the comparison operation. Important only when ANY_SUBST. */ CHARSET_INFO *m_compare_collation; public: Context(Subst_constraint subst, const Type_handler *h, CHARSET_INFO *cs) :m_subst_constraint(subst), m_compare_handler(h), m_compare_collation(cs) { DBUG_ASSERT(h == h->type_handler_for_comparison()); } Subst_constraint subst_constraint() const { return m_subst_constraint; } const Type_handler *compare_type_handler() const { DBUG_ASSERT(m_subst_constraint == ANY_SUBST); return m_compare_handler; } CHARSET_INFO *compare_collation() const { DBUG_ASSERT(m_subst_constraint == ANY_SUBST); return m_compare_collation; } }; class Context_identity: public Context { // Use this to request only exact value, no invariants. public: Context_identity() :Context(IDENTITY_SUBST, &type_handler_long_blob, &my_charset_bin) { } }; class Context_boolean: public Context { // Use this when an item is [a part of] a boolean expression public: Context_boolean() :Context(ANY_SUBST, &type_handler_slonglong, &my_charset_bin) { } }; }; #define STORAGE_TYPE_MASK 7 #define COLUMN_FORMAT_MASK 7 #define COLUMN_FORMAT_SHIFT 3 /* The length of the header part for each virtual column in the .frm file */ #define FRM_VCOL_OLD_HEADER_SIZE(b) (3 + MY_TEST(b)) #define FRM_VCOL_NEW_BASE_SIZE 16 #define FRM_VCOL_NEW_HEADER_SIZE 6 class Count_distinct_field; struct ha_field_option_struct; struct st_cache_field; int field_conv(Field *to,Field *from); int truncate_double(double *nr, uint field_length, decimal_digits_t dec, bool unsigned_flag, double max_value); inline uint get_enum_pack_length(int elements) { return elements < 256 ? 1 : 2; } inline uint get_set_pack_length(int elements) { uint len= (elements + 7) / 8; return len > 4 ? 8 : len; } /** Tests if field type is temporal and has date part, i.e. represents DATE, DATETIME or TIMESTAMP types in SQL. @param type Field type, as returned by field->type(). @retval true If field type is temporal type with date part. @retval false If field type is not temporal type with date part. */ inline bool is_temporal_type_with_date(enum_field_types type) { switch (type) { case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIMESTAMP: return true; case MYSQL_TYPE_DATETIME2: case MYSQL_TYPE_TIMESTAMP2: DBUG_ASSERT(0); // field->real_type() should not get to here. return false; default: return false; } } enum enum_vcol_info_type { VCOL_GENERATED_VIRTUAL, VCOL_GENERATED_STORED, VCOL_DEFAULT, VCOL_CHECK_FIELD, VCOL_CHECK_TABLE, VCOL_USING_HASH, /* Additional types should be added here */ VCOL_GENERATED_VIRTUAL_INDEXED, // this is never written in .frm /* Following is the highest value last */ VCOL_TYPE_NONE = 127 // Since the 0 value is already in use }; static inline const char *vcol_type_name(enum_vcol_info_type type) { switch (type) { case VCOL_GENERATED_VIRTUAL: case VCOL_GENERATED_VIRTUAL_INDEXED: case VCOL_GENERATED_STORED: return "GENERATED ALWAYS AS"; case VCOL_DEFAULT: return "DEFAULT"; case VCOL_CHECK_FIELD: case VCOL_CHECK_TABLE: return "CHECK"; case VCOL_USING_HASH: return "USING HASH"; case VCOL_TYPE_NONE: return "UNTYPED"; } return 0; } /* Flags for Virtual_column_info. If none is set, the expression must be a constant with no side-effects, so it's calculated at CREATE TABLE time, stored in table->record[2], and not recalculated for every statement. */ #define VCOL_FIELD_REF 1 #define VCOL_NON_DETERMINISTIC 2 #define VCOL_SESSION_FUNC 4 /* uses session data, e.g. USER or DAYNAME */ #define VCOL_TIME_FUNC 8 /* safe for SBR */ #define VCOL_AUTO_INC 16 #define VCOL_IMPOSSIBLE 32 #define VCOL_NEXTVAL 64 /* NEXTVAL is not implemented for vcols */ #define VCOL_NOT_STRICTLY_DETERMINISTIC \ (VCOL_NON_DETERMINISTIC | VCOL_TIME_FUNC | VCOL_SESSION_FUNC) /* Virtual_column_info is the class to contain additional characteristics that is specific for a virtual/computed field such as: - the defining expression that is evaluated to compute the value of the field - whether the field is to be stored in the database - whether the field is used in a partitioning expression */ class Virtual_column_info: public Sql_alloc, private Type_handler_hybrid_field_type { private: enum_vcol_info_type vcol_type; /* Virtual column expression type */ /* The following data is only updated by the parser and read when a Create_field object is created/initialized. */ /* Flag indicating that the field used in a partitioning expression */ bool in_partitioning_expr; public: /* Flag indicating that the field is physically stored in the database */ bool stored_in_db; bool utf8; /* Already in utf8 */ bool automatic_name; bool if_not_exists; Item *expr; Lex_ident name; /* Name of constraint */ /* see VCOL_* (VCOL_FIELD_REF, ...) */ uint flags; Virtual_column_info() :Type_handler_hybrid_field_type(&type_handler_null), vcol_type((enum_vcol_info_type)VCOL_TYPE_NONE), in_partitioning_expr(FALSE), stored_in_db(FALSE), utf8(TRUE), automatic_name(FALSE), expr(NULL), flags(0) { name.str= NULL; name.length= 0; }; Virtual_column_info* clone(THD *thd); ~Virtual_column_info() = default; enum_vcol_info_type get_vcol_type() const { return vcol_type; } void set_vcol_type(enum_vcol_info_type v_type) { vcol_type= v_type; } const char *get_vcol_type_name() const { DBUG_ASSERT(vcol_type != VCOL_TYPE_NONE); return vcol_type_name(vcol_type); } void set_handler(const Type_handler *handler) { /* Calling this function can only be done once. */ DBUG_ASSERT(type_handler() == &type_handler_null); Type_handler_hybrid_field_type::set_handler(handler); } bool is_stored() const { return stored_in_db; } void set_stored_in_db_flag(bool stored) { stored_in_db= stored; } bool is_in_partitioning_expr() const { return in_partitioning_expr; } void mark_as_in_partitioning_expr() { in_partitioning_expr= TRUE; } bool need_refix() const { return flags & VCOL_SESSION_FUNC; } bool fix_expr(THD *thd); bool fix_session_expr(THD *thd); bool cleanup_session_expr(); bool fix_and_check_expr(THD *thd, TABLE *table); bool check_access(THD *thd); inline bool is_equal(const Virtual_column_info* vcol) const; /* Same as is_equal() but for comparing with different table */ bool is_equivalent(THD *thd, TABLE_SHARE *share, TABLE_SHARE *vcol_share, const Virtual_column_info* vcol, bool &error) const; inline void print(String*); }; class Binlog_type_info { public: enum binlog_sign_t { SIGN_SIGNED, SIGN_UNSIGNED, SIGN_NOT_APPLICABLE // for non-numeric types }; /** Retrieve the field metadata for fields. */ CHARSET_INFO *m_cs; // NULL if not relevant TYPELIB *m_enum_typelib; // NULL if not relevant TYPELIB *m_set_typelib; // NULL if not relevant binlog_sign_t m_signedness; uint16 m_metadata; uint8 m_metadata_size; uchar m_type_code; // according to Field::binlog_type() uchar m_geom_type; // Non-geometry fields can return 0 Binlog_type_info(uchar type_code, uint16 metadata, uint8 metadata_size) :m_cs(NULL), m_enum_typelib(NULL), m_set_typelib(NULL), m_signedness(SIGN_NOT_APPLICABLE), m_metadata(metadata), m_metadata_size(metadata_size), m_type_code(type_code), m_geom_type(0) {}; Binlog_type_info(uchar type_code, uint16 metadata, uint8 metadata_size, binlog_sign_t signedness) : m_cs(NULL), m_enum_typelib(NULL), m_set_typelib(NULL), m_signedness(signedness), m_metadata(metadata), m_metadata_size(metadata_size), m_type_code(type_code), m_geom_type(0) {}; Binlog_type_info(uchar type_code, uint16 metadata, uint8 metadata_size, CHARSET_INFO *cs) :m_cs(cs), m_enum_typelib(NULL), m_set_typelib(NULL), m_signedness(SIGN_NOT_APPLICABLE), m_metadata(metadata), m_metadata_size(metadata_size), m_type_code(type_code), m_geom_type(0) {}; Binlog_type_info(uchar type_code, uint16 metadata, uint8 metadata_size, CHARSET_INFO *cs, TYPELIB *t_enum, TYPELIB *t_set) :m_cs(cs), m_enum_typelib(t_enum), m_set_typelib(t_set), m_signedness(SIGN_NOT_APPLICABLE), m_metadata(metadata), m_metadata_size(metadata_size), m_type_code(type_code), m_geom_type(0) {}; Binlog_type_info(uchar type_code, uint16 metadata, uint8 metadata_size, CHARSET_INFO *cs, uchar geom_type) :m_cs(cs), m_enum_typelib(NULL), m_set_typelib(NULL), m_signedness(SIGN_NOT_APPLICABLE), m_metadata(metadata), m_metadata_size(metadata_size), m_type_code(type_code), m_geom_type(geom_type) {}; static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } }; class Binlog_type_info_fixed_string: public Binlog_type_info { public: Binlog_type_info_fixed_string(uchar type_code, uint32 octet_length, CHARSET_INFO *cs); }; class Field: public Value_source { Field(const Item &); /* Prevent use of these */ void operator=(Field &); protected: int save_in_field_str(Field *to) { StringBuffer result(charset()); val_str(&result); return to->store(result.ptr(), result.length(), charset()); } void error_generated_column_function_is_not_allowed(THD *thd, bool error) const; static void do_field_eq(Copy_field *copy); static void do_field_int(Copy_field *copy); static void do_field_real(Copy_field *copy); static void do_field_string(Copy_field *copy); static void do_field_date(Copy_field *copy); static void do_field_temporal(Copy_field *copy, date_mode_t fuzzydate); static void do_field_datetime(Copy_field *copy); static void do_field_timestamp(Copy_field *copy); static void do_field_decimal(Copy_field *copy); public: static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } static void *operator new(size_t size) throw () { DBUG_ASSERT(size < UINT_MAX32); return thd_alloc(current_thd, (uint) size); } static void operator delete(void *ptr_arg, size_t size) { TRASH_FREE(ptr_arg, size); } static void operator delete(void *ptr, MEM_ROOT *mem_root) { DBUG_ASSERT(0); } bool marked_for_read() const; bool marked_for_write_or_computed() const; /** Used by System Versioning. */ virtual void set_max() { DBUG_ASSERT(0); } virtual bool is_max() { DBUG_ASSERT(0); return false; } uchar *ptr; // Position to field in record /** Byte where the @c NULL bit is stored inside a record. If this Field is a @c NOT @c NULL field, this member is @c NULL. */ uchar *null_ptr; /* Note that you can use table->in_use as replacement for current_thd member only inside of val_*() and store() members (e.g. you can't use it in cons) */ TABLE *table; // Pointer for table TABLE *orig_table; // Pointer to original table const char * const *table_name; // Pointer to alias in TABLE LEX_CSTRING field_name; LEX_CSTRING comment; /** reference to the list of options or NULL */ engine_option_value *option_list; ha_field_option_struct *option_struct; /* structure with parsed options */ /* Field is part of the following keys */ key_map key_start, part_of_key, part_of_key_not_clustered; /* Bitmap of indexes that have records ordered by col1, ... this_field, ... For example, INDEX (col(prefix_n)) is not present in col.part_of_sortkey. */ key_map part_of_sortkey; /* We use three additional unireg types for TIMESTAMP to overcome limitation of current binary format of .frm file. We'd like to be able to support NOW() as default and on update value for such fields but unable to hold this info anywhere except unireg_check field. This issue will be resolved in more clean way with transition to new text based .frm format. See also comment for Field_timestamp::Field_timestamp(). */ enum __attribute__((packed)) utype { NONE=0, NEXT_NUMBER=15, // AUTO_INCREMENT TIMESTAMP_OLD_FIELD=18, // TIMESTAMP created before 4.1.3 TIMESTAMP_DN_FIELD=21, // TIMESTAMP DEFAULT NOW() TIMESTAMP_UN_FIELD=22, // TIMESTAMP ON UPDATE NOW() TIMESTAMP_DNUN_FIELD=23, // TIMESTAMP DEFAULT NOW() ON UPDATE NOW() TMYSQL_COMPRESSED= 24, // Compatibility with TMySQL }; enum imagetype { itRAW, itMBR}; utype unireg_check; field_visibility_t invisible; uint32 field_length; // Length of field uint32 flags; field_index_t field_index; // field number in fields array uchar null_bit; // Bit used to test null bit /** If true, this field was created in create_tmp_field_from_item from a NULL value. This means that the type of the field is just a guess, and the type may be freely coerced to another type. @see create_tmp_field_from_item @see Item_type_holder::get_real_type */ bool is_created_from_null_item; /* Selectivity of the range condition over this field. When calculating this selectivity a range predicate is taken into account only if: - it is extracted from the WHERE clause - it depends only on the table the field belongs to */ double cond_selectivity; /* The next field in the class of equal fields at the top AND level of the WHERE clause */ Field *next_equal_field; /* This structure is used for statistical data on the column that has been read from the statistical table column_stat */ Column_statistics *read_stats; /* This structure is used for statistical data on the column that is collected by the function collect_statistics_for_table */ Column_statistics_collected *collected_stats; /* This is additional data provided for any computed(virtual) field, default function or check constraint. In particular it includes a pointer to the item by which this field can be computed from other fields. */ Virtual_column_info *vcol_info, *check_constraint, *default_value; Field(uchar *ptr_arg,uint32 length_arg,uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg); virtual ~Field() = default; virtual Type_numeric_attributes type_numeric_attributes() const { return Type_numeric_attributes(field_length, decimals(), is_unsigned()); } Type_std_attributes type_std_attributes() const { return Type_std_attributes(type_numeric_attributes(), dtcollation()); } bool is_unsigned() const { return flags & UNSIGNED_FLAG; } /** Convenience definition of a copy function returned by Field::get_copy_func() */ typedef void Copy_func(Copy_field*); virtual Copy_func *get_copy_func(const Field *from) const= 0; virtual Copy_func *get_copy_func_to(const Field *to) const { return to->get_copy_func(this); } /* Store functions returns 1 on overflow and -1 on fatal error */ virtual int store_field(Field *from) { return from->save_in_field(this); } virtual int save_in_field(Field *to)= 0; /** Check if it is possible just copy the value of the field 'from' to the field 'this', e.g. for INSERT INTO t1 (field1) SELECT field2 FROM t2; @param from - The field to copy from @retval true - it is possible to just copy value of 'from' to 'this' @retval false - conversion is needed */ virtual bool memcpy_field_possible(const Field *from) const= 0; virtual bool make_empty_rec_store_default_value(THD *thd, Item *item); virtual void make_empty_rec_reset(THD *thd) { reset(); } virtual int store(const char *to, size_t length,CHARSET_INFO *cs)=0; /* This is used by engines like CSV and Federated to signal the field that the data is going to be in text (rather than binary) representation, even if cs points to &my_charset_bin. If a Field distinguishes between text and binary formats (e.g. INET6), we cannot call store(str,length,&my_charset_bin), to avoid "field" mis-interpreting the data format as binary. */ virtual int store_text(const char *to, size_t length, CHARSET_INFO *cs) { return store(to, length, cs); } virtual int store_binary(const char *to, size_t length) { return store(to, length, &my_charset_bin); } virtual int store_hex_hybrid(const char *str, size_t length); virtual int store(double nr)=0; virtual int store(longlong nr, bool unsigned_val)=0; virtual int store_decimal(const my_decimal *d)=0; virtual int store_time_dec(const MYSQL_TIME *ltime, uint dec); virtual int store_timestamp_dec(const timeval &ts, uint dec); int store_timestamp(my_time_t timestamp, ulong sec_part) { return store_timestamp_dec(Timeval(timestamp, sec_part), TIME_SECOND_PART_DIGITS); } /** Store a value represented in native format */ virtual int store_native(const Native &value) { DBUG_ASSERT(0); reset(); return 0; } int store_time(const MYSQL_TIME *ltime) { return store_time_dec(ltime, TIME_SECOND_PART_DIGITS); } int store(const char *to, size_t length, CHARSET_INFO *cs, enum_check_fields check_level); int store_text(const char *to, size_t length, CHARSET_INFO *cs, enum_check_fields check_level); int store(const LEX_STRING *ls, CHARSET_INFO *cs) { DBUG_ASSERT(ls->length < UINT_MAX32); return store(ls->str, (uint) ls->length, cs); } int store(const LEX_CSTRING *ls, CHARSET_INFO *cs) { DBUG_ASSERT(ls->length < UINT_MAX32); return store(ls->str, (uint) ls->length, cs); } int store(const LEX_CSTRING &ls, CHARSET_INFO *cs) { DBUG_ASSERT(ls.length < UINT_MAX32); return store(ls.str, (uint) ls.length, cs); } /* @brief Store minimum/maximum value of a column in the statistics table. @param field statistical table field str value buffer */ virtual int store_to_statistical_minmax_field(Field *field, String *str); /* @brief Store minimum/maximum value of a column from the statistical table. @param field statistical table field str value buffer */ virtual int store_from_statistical_minmax_field(Field *field, String *str, MEM_ROOT *mem); #ifdef HAVE_MEM_CHECK /** Mark unused memory in the field as defined. Mainly used to ensure that if we write full field to disk (for example in Count_distinct_field::add(), we don't write unitalized data to disk which would confuse valgrind or MSAN. */ virtual void mark_unused_memory_as_defined() {} #else void mark_unused_memory_as_defined() {} #endif virtual double val_real()=0; virtual longlong val_int()=0; /* Get ulonglong representation. Negative values are truncated to 0. */ virtual ulonglong val_uint(void) { longlong nr= val_int(); return nr < 0 ? 0 : (ulonglong) nr; } virtual bool val_bool()= 0; virtual my_decimal *val_decimal(my_decimal *)=0; inline String *val_str(String *str) { return val_str(str, str); } /* val_str(buf1, buf2) gets two buffers and should use them as follows: if it needs a temp buffer to convert result to string - use buf1 example Field_tiny::val_str() if the value exists as a string already - use buf2 example Field_string::val_str() consequently, buf2 may be created as 'String buf;' - no memory will be allocated for it. buf1 will be allocated to hold a value if it's too small. Using allocated buffer for buf2 may result in an unnecessary free (and later, may be an alloc). This trickery is used to decrease a number of malloc calls. */ virtual String *val_str(String*,String *)=0; virtual bool val_native(Native *to) { DBUG_ASSERT(!is_null()); return to->copy((const char *) ptr, pack_length()); } String *val_int_as_str(String *val_buffer, bool unsigned_flag); /* Return the field value as a LEX_CSTRING, without padding to full length (MODE_PAD_CHAR_TO_FULL_LENGTH is temporarily suppressed during the call). In case of an empty value, to[0] is assigned to empty_clex_string, memory is not allocated. In case of a non-empty value, the memory is allocated on mem_root. In case of a memory allocation failure, to[0] is assigned to {NULL,0}. @param [IN] mem_root store non-empty values here @param [OUT to return the string here @retval false (success) @retval true (EOM) */ bool val_str_nopad(MEM_ROOT *mem_root, LEX_CSTRING *to); fast_field_copier get_fast_field_copier(const Field *from); /* str_needs_quotes() returns TRUE if the value returned by val_str() needs to be quoted when used in constructing an SQL query. */ virtual bool str_needs_quotes() const { return false; } const Type_handler *type_handler_for_comparison() const { return type_handler()->type_handler_for_comparison(); } Item_result result_type () const { return type_handler()->result_type(); } Item_result cmp_type () const { return type_handler()->cmp_type(); } virtual bool eq(Field *field) { return (ptr == field->ptr && null_ptr == field->null_ptr && null_bit == field->null_bit && field->type() == type()); } virtual bool eq_def(const Field *field) const; /* pack_length() returns size (in bytes) used to store field data in memory (i.e. it returns the maximum size of the field in a row of the table, which is located in RAM). */ virtual uint32 pack_length() const { return (uint32) field_length; } /* pack_length_in_rec() returns size (in bytes) used to store field data on storage (i.e. it returns the maximal size of the field in a row of the table, which is located on disk). */ virtual uint32 pack_length_in_rec() const { return pack_length(); } virtual bool compatible_field_size(uint metadata, const Relay_log_info *rli, uint16 mflags, int *order) const; virtual uint pack_length_from_metadata(uint field_metadata) const { DBUG_ENTER("Field::pack_length_from_metadata"); DBUG_RETURN(field_metadata); } virtual uint row_pack_length() const { return 0; } /* data_length() return the "real size" of the data in memory. */ virtual uint32 data_length() { return pack_length(); } virtual uint32 sort_length() const { return pack_length(); } /* sort_suffix_length() return the length bytes needed to store the length for binary charset */ virtual uint32 sort_suffix_length() const { return 0; } /* Get the number bytes occupied by the value in the field. CHAR values are stripped of trailing spaces. Flexible values are stripped of their length. */ virtual uint32 value_length() { uint len; if (!zero_pack() && (type() == MYSQL_TYPE_STRING && (len= pack_length()) >= 4 && len < 256)) { uchar *str, *end; for (str= ptr, end= str+len; end > str && end[-1] == ' '; end--) {} len=(uint) (end-str); return len; } return data_length(); } /** Get the maximum size of the data in packed format. @return Maximum data length of the field when packed using the Field::pack() function. */ virtual uint32 max_data_length() const { return pack_length(); }; virtual int reset() { bzero(ptr,pack_length()); return 0; } virtual void reset_fields() {} const uchar *ptr_in_record(const uchar *record) const { my_ptrdiff_t l_offset= (my_ptrdiff_t) (ptr - table->record[0]); DBUG_ASSERT(l_offset >= 0 && table->s->rec_buff_length - l_offset > 0); return record + l_offset; } virtual int set_default(); bool has_update_default_function() const { return flags & ON_UPDATE_NOW_FLAG; } bool has_default_now_unireg_check() const { return unireg_check == TIMESTAMP_DN_FIELD || unireg_check == TIMESTAMP_DNUN_FIELD; } /* Mark the field as having a value supplied by the client, thus it should not be auto-updated. */ void set_has_explicit_value() { bitmap_set_bit(&table->has_value_set, field_index); } bool has_explicit_value() { return bitmap_is_set(&table->has_value_set, field_index); } void clear_has_explicit_value() { bitmap_clear_bit(&table->has_value_set, field_index); } virtual my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const { DBUG_ASSERT(0); return 0; } my_time_t get_timestamp(ulong *sec_part) const { return get_timestamp(ptr, sec_part); } virtual bool binary() const { return 1; } virtual bool zero_pack() const { return 1; } virtual enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; } virtual uint16 key_part_flag() const { return 0; } virtual uint16 key_part_length_bytes() const { return 0; } virtual uint32 key_length() const { return pack_length(); } virtual const Type_handler *type_handler() const = 0; virtual enum_field_types type() const { return type_handler()->field_type(); } virtual enum_field_types real_type() const { return type_handler()->real_field_type(); } virtual enum_field_types binlog_type() const { /* Binlog stores field->type() as type code by default. For example, it puts MYSQL_TYPE_STRING in case of CHAR, VARCHAR, SET and ENUM, with extra data type details put into metadata. Binlog behaviour slightly differs between various MySQL and MariaDB versions for the temporal data types TIME, DATETIME and TIMESTAMP. MySQL prior to 5.6 uses MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP type codes in binlog and stores no additional metadata. MariaDB-5.3 implements new versions for TIME, DATATIME, TIMESTAMP with fractional second precision, but uses the old format for the types TIME(0), DATETIME(0), TIMESTAMP(0), and it still stores MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP in binlog, with no additional metadata. So row-based replication between temporal data types of different precision is not possible in MariaDB. MySQL-5.6 also implements a new version of TIME, DATETIME, TIMESTAMP which support fractional second precision 0..6, and use the new format even for the types TIME(0), DATETIME(0), TIMESTAMP(0). For these new data types, MySQL-5.6 stores new type codes MYSQL_TYPE_TIME2, MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIMESTAMP2 in binlog, with fractional precision 0..6 put into metadata. This makes it in theory possible to do row-based replication between columns of different fractional precision (e.g. from TIME(1) on master to TIME(6) on slave). However, it's not currently fully implemented yet. MySQL-5.6 can only do row-based replication from the old types TIME, DATETIME, TIMESTAMP (represented by MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME and MYSQL_TYPE_TIMESTAMP type codes in binlog) to the new corresponding types TIME(0), DATETIME(0), TIMESTAMP(0). Note: MariaDB starting from the version 10.0 understands the new MySQL-5.6 type codes MYSQL_TYPE_TIME2, MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIMESTAMP2. When started over MySQL-5.6 tables both on master and on slave, MariaDB-10.0 can also do row-based replication from the old types TIME, DATETIME, TIMESTAMP to the new MySQL-5.6 types TIME(0), DATETIME(0), TIMESTAMP(0). Note: perhaps binlog should eventually be modified to store real_type() instead of type() for all column types. */ return type(); } virtual Binlog_type_info binlog_type_info() const { DBUG_ASSERT(Field::type() == binlog_type()); return Binlog_type_info(Field::type(), 0, 0); } virtual en_fieldtype tmp_engine_column_type(bool use_packed_rows) const { return FIELD_NORMAL; } /* Conversion type for from the source to the current field. */ virtual enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const= 0; enum_conv_type rpl_conv_type_from_same_data_type(uint16 metadata, const Relay_log_info *rli, const Conv_param ¶m) const; inline int cmp(const uchar *str) const { return cmp(ptr,str); } /* The following method is used for comparing prefix keys. Currently it's only used in partitioning. */ virtual int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_char_len) const { return cmp(a, b); } virtual int cmp(const uchar *,const uchar *) const=0; virtual int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const { return memcmp(a,b,pack_length()); } virtual int cmp_offset(my_ptrdiff_t row_offset) { return cmp(ptr,ptr+row_offset); } virtual int cmp_binary_offset(uint row_offset) { return cmp_binary(ptr, ptr+row_offset); }; virtual int key_cmp(const uchar *a,const uchar *b) const { return cmp(a, b); } virtual int key_cmp(const uchar *str, uint length) const { return cmp(ptr,str); } /* Update the value m of the 'min_val' field with the current value v of this field if force_update is set to TRUE or if v < m. Return TRUE if the value has been updated. */ virtual bool update_min(Field *min_val, bool force_update) { bool update_fl= force_update || cmp(ptr, min_val->ptr) < 0; if (update_fl) { min_val->set_notnull(); memcpy(min_val->ptr, ptr, pack_length()); } return update_fl; } /* Update the value m of the 'max_val' field with the current value v of this field if force_update is set to TRUE or if v > m. Return TRUE if the value has been updated. */ virtual bool update_max(Field *max_val, bool force_update) { bool update_fl= force_update || cmp(ptr, max_val->ptr) > 0; if (update_fl) { max_val->set_notnull(); memcpy(max_val->ptr, ptr, pack_length()); } return update_fl; } virtual void store_field_value(uchar *val, uint len) { memcpy(ptr, val, len); } virtual decimal_digits_t decimals() const { return 0; } virtual Information_schema_numeric_attributes information_schema_numeric_attributes() const { return Information_schema_numeric_attributes(); } virtual Information_schema_character_attributes information_schema_character_attributes() const { return Information_schema_character_attributes(); } virtual void update_data_type_statistics(Data_type_statistics *st) const { } /* Caller beware: sql_type can change str.Ptr, so check ptr() to see if it changed if you are using your own buffer in str and restore it with set() if needed */ virtual void sql_type(String &str) const =0; virtual void sql_rpl_type(String *str) const { sql_type(*str); } virtual uint size_of() const =0; // For new field inline bool is_null(my_ptrdiff_t row_offset= 0) const { /* The table may have been marked as containing only NULL values for all fields if it is a NULL-complemented row of an OUTER JOIN or if the query is an implicitly grouped query (has aggregate functions but no GROUP BY clause) with no qualifying rows. If this is the case (in which TABLE::null_row is true), the field is considered to be NULL. Note that if a table->null_row is set then also all null_bits are set for the row. In the case of the 'result_field' for GROUP BY, table->null_row might refer to the *next* row in the table (when the algorithm is: read the next row, see if any of group column values have changed, send the result - grouped - row to the client if yes). So, table->null_row might be wrong, but such a result_field is always nullable (that's defined by original_field->maybe_null()) and we trust its null bit. */ return null_ptr ? null_ptr[row_offset] & null_bit : table->null_row; } inline bool is_real_null(my_ptrdiff_t row_offset= 0) const { return null_ptr && (null_ptr[row_offset] & null_bit); } inline bool is_null_in_record(const uchar *record) const { if (maybe_null_in_table()) return record[(uint) (null_ptr - table->record[0])] & null_bit; return 0; } inline void set_null(my_ptrdiff_t row_offset= 0) { if (null_ptr) null_ptr[row_offset]|= null_bit; } inline void set_notnull(my_ptrdiff_t row_offset= 0) { if (null_ptr) null_ptr[row_offset]&= (uchar) ~null_bit; } inline bool maybe_null(void) const { return null_ptr != 0 || table->maybe_null; } // Set to NULL on LOAD DATA or LOAD XML virtual bool load_data_set_null(THD *thd); // Reset when a LOAD DATA file ended unexpectedly virtual bool load_data_set_no_data(THD *thd, bool fixed_format); void load_data_set_value(const char *pos, uint length, CHARSET_INFO *cs); /* @return true if this field is NULL-able (even if temporarily) */ inline bool real_maybe_null() const { return null_ptr != 0; } uint null_offset(const uchar *record) const { return (uint) (null_ptr - record); } /* For a NULL-able field (that can actually store a NULL value in a table) null_ptr points to the "null bitmap" in the table->record[0] header. For NOT NULL fields it is either 0 or points outside table->record[0] into the table->triggers->extra_null_bitmap (so that the field can store a NULL value temporarily, only in memory) */ bool maybe_null_in_table() const { return null_ptr >= table->record[0] && null_ptr <= ptr; } uint null_offset() const { return null_offset(table->record[0]); } void set_null_ptr(uchar *p_null_ptr, uint p_null_bit) { null_ptr= p_null_ptr; null_bit= static_cast(p_null_bit); } bool stored_in_db() const { return !vcol_info || vcol_info->stored_in_db; } bool check_vcol_sql_mode_dependency(THD *, vcol_init_mode mode) const; virtual sql_mode_t value_depends_on_sql_mode() const { return 0; } virtual sql_mode_t conversion_depends_on_sql_mode(THD *thd, Item *expr) const { return (sql_mode_t) 0; } virtual sql_mode_t can_handle_sql_mode_dependency_on_store() const { return 0; } inline THD *get_thd() const { return likely(table) ? table->in_use : current_thd; } enum { LAST_NULL_BYTE_UNDEF= 0 }; /* Find the position of the last null byte for the field. SYNOPSIS last_null_byte() DESCRIPTION Return a pointer to the last byte of the null bytes where the field conceptually is placed. RETURN VALUE The position of the last null byte relative to the beginning of the record. If the field does not use any bits of the null bytes, the value 0 (LAST_NULL_BYTE_UNDEF) is returned. */ size_t last_null_byte() const { size_t bytes= do_last_null_byte(); DBUG_PRINT("debug", ("last_null_byte() ==> %ld", (long) bytes)); DBUG_ASSERT(bytes <= table->s->null_bytes); return bytes; } /* Create mem-comparable sort key part for a sort key */ void make_sort_key_part(uchar *buff, uint length); /* create a compact sort key which can be compared with a comparison function. They are called packed sort keys */ virtual uint make_packed_sort_key_part(uchar *buff, const SORT_FIELD_ATTR *sort_field); virtual void make_send_field(Send_field *); /* Some implementations actually may write up to 8 bytes regardless of what size was requested. This is due to the minimum value of the system variable max_sort_length. */ virtual void sort_string(uchar *buff,uint length)=0; virtual bool optimize_range(uint idx, uint part) const; virtual void free() {} virtual Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type); virtual Field *new_key_field(MEM_ROOT *root, TABLE *new_table, uchar *new_ptr, uint32 length, uchar *new_null_ptr, uint new_null_bit); Field *create_tmp_field(MEM_ROOT *root, TABLE *new_table, bool maybe_null_arg); Field *create_tmp_field(MEM_ROOT *root, TABLE *new_table) { return create_tmp_field(root, new_table, maybe_null()); } Field *clone(MEM_ROOT *mem_root, TABLE *new_table); Field *clone(MEM_ROOT *mem_root, TABLE *new_table, my_ptrdiff_t diff); inline void move_field(uchar *ptr_arg,uchar *null_ptr_arg,uchar null_bit_arg) { ptr=ptr_arg; null_ptr=null_ptr_arg; null_bit=null_bit_arg; } inline void move_field(uchar *ptr_arg) { ptr=ptr_arg; } inline uchar *record_ptr() // record[0] or wherever the field was moved to { my_ptrdiff_t offset= table->s->field[field_index]->ptr - table->s->default_values; return ptr - offset; } virtual void move_field_offset(my_ptrdiff_t ptr_diff) { ptr=ADD_TO_PTR(ptr,ptr_diff, uchar*); if (null_ptr) { null_ptr=ADD_TO_PTR(null_ptr,ptr_diff,uchar*); if (table) { DBUG_ASSERT(null_ptr < ptr); DBUG_ASSERT(ptr - null_ptr <= (int)table->s->rec_buff_length); } } } void get_image(uchar *buff, uint length, CHARSET_INFO *cs) const { get_image(buff, length, ptr, cs); } virtual void get_image(uchar *buff, uint length, const uchar *ptr_arg, CHARSET_INFO *cs) const { memcpy(buff,ptr_arg,length); } virtual void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) { memcpy(ptr,buff,length); } /* Copy a field part into an output buffer. SYNOPSIS Field::get_key_image() buff [out] output buffer length output buffer size type itMBR for geometry blobs, otherwise itRAW DESCRIPTION This function makes a copy of field part of size equal to or less than "length" parameter value. For fields of string types (CHAR, VARCHAR, TEXT) the rest of buffer is padded by zero byte. NOTES For variable length character fields (i.e. UTF-8) the "length" parameter means a number of output buffer bytes as if all field characters have maximal possible size (mbmaxlen). In the other words, "length" parameter is a number of characters multiplied by field_charset->mbmaxlen. RETURN Number of copied bytes (excluding padded zero bytes -- see above). */ uint get_key_image(uchar *buff, uint length, imagetype type_arg) const { return get_key_image(buff, length, ptr, type_arg); } virtual uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type_arg) const { get_image(buff, length, ptr_arg, &my_charset_bin); return length; } virtual void set_key_image(const uchar *buff,uint length) { set_image(buff,length, &my_charset_bin); } inline longlong val_int_offset(uint row_offset) { ptr+=row_offset; longlong tmp=val_int(); ptr-=row_offset; return tmp; } inline longlong val_int(const uchar *new_ptr) { uchar *old_ptr= ptr; longlong return_value; ptr= (uchar*) new_ptr; return_value= val_int(); ptr= old_ptr; return return_value; } inline String *val_str(String *str, const uchar *new_ptr) { uchar *old_ptr= ptr; ptr= (uchar*) new_ptr; val_str(str); ptr= old_ptr; return str; } virtual bool send(Protocol *protocol); virtual uchar *pack(uchar *to, const uchar *from, uint max_length); /** @overload Field::pack(uchar*, const uchar*, uint, bool) */ uchar *pack(uchar *to, const uchar *from) { DBUG_ENTER("Field::pack"); uchar *result= this->pack(to, from, UINT_MAX); DBUG_RETURN(result); } virtual const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data=0); virtual uint packed_col_length(const uchar *to, uint length) { return length;} virtual uint max_packed_col_length(uint max_length) { return max_length;} virtual bool is_packable() const { return false; } uint offset(const uchar *record) const { return (uint) (ptr - record); } void copy_from_tmp(int offset); uint fill_cache_field(struct st_cache_field *copy); virtual bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate); virtual longlong val_datetime_packed(THD *thd); virtual longlong val_time_packed(THD *thd); virtual const TYPELIB *get_typelib() const { return NULL; } virtual CHARSET_INFO *charset() const= 0; /* returns TRUE if the new charset differs. */ virtual void change_charset(const DTCollation &new_cs) {} virtual const DTCollation &dtcollation() const= 0; virtual CHARSET_INFO *charset_for_protocol(void) const { return binary() ? &my_charset_bin : charset(); } virtual CHARSET_INFO *sort_charset(void) const { return charset(); } virtual bool has_charset(void) const { return FALSE; } virtual int set_time() { return 1; } bool set_warning(Sql_condition::enum_warning_level, unsigned int code, int cuted_increment, ulong current_row=0) const; virtual void print_key_value(String *out, uint32 length); void print_key_part_value(String *out, const uchar *key, uint32 length); void print_key_value_binary(String *out, const uchar* key, uint32 length); void raise_note_cannot_use_key_part(THD *thd, uint keynr, uint part, const LEX_CSTRING &op, CHARSET_INFO *op_collation, Item *value, const Data_type_compatibility reason) const; void raise_note_key_become_unused(THD *thd, const String &expr) const; protected: bool set_warning(unsigned int code, int cuted_increment) const { return set_warning(Sql_condition::WARN_LEVEL_WARN, code, cuted_increment); } bool set_note(unsigned int code, int cuted_increment) const { return set_warning(Sql_condition::WARN_LEVEL_NOTE, code, cuted_increment); } void set_datetime_warning(Sql_condition::enum_warning_level, uint code, const ErrConv *str, const char *typestr, int cuted_increment) const; void set_datetime_warning(uint code, const ErrConv *str, const char *typestr, int cuted_increment) const { set_datetime_warning(Sql_condition::WARN_LEVEL_WARN, code, str, typestr, cuted_increment); } void set_warning_truncated_wrong_value(const char *type, const char *value); inline bool check_overflow(int op_result) { return (op_result == E_DEC_OVERFLOW); } int warn_if_overflow(int op_result); Copy_func *get_identical_copy_func() const; bool cmp_is_done_using_type_handler_of_this(const Item_bool_func *cond, const Item *item) const; Data_type_compatibility can_optimize_scalar_range( const RANGE_OPT_PARAM *param, const KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) const; uchar *make_key_image(MEM_ROOT *mem_root, const KEY_PART *key_part); SEL_ARG *get_mm_leaf_int(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value, bool unsigned_field); /* Make a leaf tree for the cases when the value was stored to the field exactly, without any truncation, rounding or adjustments. For example, if we stored an INT value into an INT column, and value->save_in_field_no_warnings() returned 0, we know that the value was stored exactly. */ SEL_ARG *stored_field_make_mm_leaf_exact(RANGE_OPT_PARAM *param, KEY_PART *key_part, scalar_comparison_op op, Item *value); /* Make a leaf tree for the cases when we don't know if the value was stored to the field without any data loss, or was modified to a smaller or a greater value. Used for the data types whose methods Field::store*() silently adjust the value. This is the most typical case. */ SEL_ARG *stored_field_make_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, scalar_comparison_op op, Item *value); /* Make a leaf tree when an INT value was stored into a field of INT type, and some truncation happened. Tries to adjust the range search condition when possible, e.g. "tinytint < 300" -> "tinyint <= 127". Can also return SEL_ARG_IMPOSSIBLE(), and NULL (not sargable). */ SEL_ARG *stored_field_make_mm_leaf_bounded_int(RANGE_OPT_PARAM *param, KEY_PART *key_part, scalar_comparison_op op, Item *value, bool unsigned_field); /* Make a leaf tree when some truncation happened during value->save_in_field_no_warning(this), and we cannot yet adjust the range search condition for the current combination of the field and the value data types. Returns SEL_ARG_IMPOSSIBLE() for "=" and "<=>". Returns NULL (not sargable) for other comparison operations. */ SEL_ARG *stored_field_make_mm_leaf_truncated(RANGE_OPT_PARAM *prm, scalar_comparison_op, Item *value); public: void set_table_name(String *alias) { table_name= &alias->Ptr; } void init(TABLE *table_arg) { orig_table= table= table_arg; set_table_name(&table_arg->alias); } virtual void init_for_tmp_table(Field *org_field, TABLE *new_table) { init(new_table); orig_table= org_field->orig_table; vcol_info= 0; cond_selectivity= 1.0; next_equal_field= NULL; option_list= NULL; option_struct= NULL; if (org_field->type() == MYSQL_TYPE_VAR_STRING || org_field->type() == MYSQL_TYPE_VARCHAR) new_table->s->db_create_options|= HA_OPTION_PACK_RECORD; } void init_for_make_new_field(TABLE *new_table_arg, TABLE *orig_table_arg) { init(new_table_arg); /* Normally orig_table is different from table only if field was created via ::make_new_field. Here we alter the type of field, so ::make_new_field is not applicable. But we still need to preserve the original field metadata for the client-server protocol. */ orig_table= orig_table_arg; } /* maximum possible display length */ virtual uint32 max_display_length() const= 0; /** Whether a field being created has the samle type. Used by the ALTER TABLE */ virtual bool is_equal(const Column_definition &new_field) const= 0; /* convert decimal to longlong with overflow check */ longlong convert_decimal2longlong(const my_decimal *val, bool unsigned_flag, int *err); /* Maximum number of bytes in character representation. - For string types it is equal to the field capacity, in bytes. - For non-string types it represents the longest possible string length after conversion to string. */ virtual uint32 character_octet_length() const { return field_length; } /* The max. number of characters */ virtual uint32 char_length() const { return field_length / charset()->mbmaxlen; } ha_storage_media field_storage_type() const { return (ha_storage_media) ((flags >> FIELD_FLAGS_STORAGE_MEDIA) & 3); } void set_storage_type(ha_storage_media storage_type_arg) { DBUG_ASSERT(field_storage_type() == HA_SM_DEFAULT); flags |= static_cast(storage_type_arg) << FIELD_FLAGS_STORAGE_MEDIA; } column_format_type column_format() const { return (column_format_type) ((flags >> FIELD_FLAGS_COLUMN_FORMAT) & 3); } void set_column_format(column_format_type column_format_arg) { DBUG_ASSERT(column_format() == COLUMN_FORMAT_TYPE_DEFAULT); flags |= static_cast(column_format_arg) << FIELD_FLAGS_COLUMN_FORMAT; } bool vers_sys_field() const { return flags & (VERS_ROW_START | VERS_ROW_END); } bool vers_sys_start() const { return flags & VERS_ROW_START; } bool vers_sys_end() const { return flags & VERS_ROW_END; } bool vers_update_unversioned() const { return flags & VERS_UPDATE_UNVERSIONED_FLAG; } /* Validate a non-null field value stored in the given record according to the current thread settings, e.g. sql_mode. @param thd - the thread @param record - the record to check in */ virtual bool validate_value_in_record(THD *thd, const uchar *record) const { return false; } bool validate_value_in_record_with_warn(THD *thd, const uchar *record); key_map get_possible_keys(); /* Hash value */ void hash(Hasher *hasher) { if (is_null()) hasher->add_null(); else hash_not_null(hasher); } virtual void hash_not_null(Hasher *hasher); /** Get the upper limit of the MySQL integral and floating-point type. @return maximum allowed value for the field */ virtual ulonglong get_max_int_value() const { DBUG_ASSERT(false); return 0ULL; } /** Checks whether a string field is part of write_set. @return FALSE - If field is not char/varchar/.... - If field is char/varchar/.. and is not part of write set. TRUE - If field is char/varchar/.. and is part of write set. */ virtual bool is_varchar_and_in_write_set() const { return FALSE; } /* Check whether the field can be used as a join attribute in hash join */ virtual bool hash_join_is_possible() { return TRUE; } virtual bool eq_cmp_as_binary() { return TRUE; } /* Position of the field value within the interval of [min, max] */ virtual double pos_in_interval(Field *min, Field *max) { return (double) 0.5; } /* Check if comparison between the field and an item unambiguously identifies a distinct field value. Example1: SELECT * FROM t1 WHERE int_column=10; This example returns distinct integer value of 10. Example2: SELECT * FROM t1 WHERE varchar_column=DATE'2001-01-01' This example returns non-distinct values. Comparison as DATE will return '2001-01-01' and '2001-01-01x', but these two values are not equal to each other as VARCHARs. See also the function with the same name in sql_select.cc. */ virtual bool test_if_equality_guarantees_uniqueness(const Item *const_item) const; virtual bool can_be_substituted_to_equal_item(const Context &ctx, const Item_equal *item); virtual Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) { return const_item; } virtual Data_type_compatibility can_optimize_keypart_ref( const Item_bool_func *cond, const Item *item) const; virtual Data_type_compatibility can_optimize_hash_join( const Item_bool_func *cond, const Item *item) const { return can_optimize_keypart_ref(cond, item); } virtual Data_type_compatibility can_optimize_group_min_max( const Item_bool_func *cond, const Item *const_item) const; /** Test if Field can use range optimizer for a standard comparison operation: <=, <, =, <=>, >, >= Note, this method does not cover spatial operations. */ virtual Data_type_compatibility can_optimize_range(const Item_bool_func *cond, const Item *item, bool is_eq_func) const; virtual SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value)= 0; Data_type_compatibility can_optimize_outer_join_table_elimination( const Item_bool_func *cond, const Item *item) const { // Exactly the same rules with REF access return can_optimize_keypart_ref(cond, item); } bool save_in_field_default_value(bool view_eror_processing); bool save_in_field_ignore_value(bool view_error_processing); /* Mark field in read map. Updates also virtual fields */ void register_field_in_read_map(); virtual Compression_method *compression_method() const { return 0; } virtual Virtual_tmp_table **virtual_tmp_table_addr() { return NULL; } virtual bool sp_prepare_and_store_item(THD *thd, Item **value); friend int cre_myisam(char * name, TABLE *form, uint options, ulonglong auto_increment_value); friend class Copy_field; friend class Item_avg_field; friend class Item_std_field; friend class Item_sum_num; friend class Item_sum_sum; friend class Item_sum_count; friend class Item_sum_avg; friend class Item_sum_std; friend class Item_sum_min; friend class Item_sum_max; friend class Item_func_group_concat; private: /* Primitive for implementing last_null_byte(). SYNOPSIS do_last_null_byte() DESCRIPTION Primitive for the implementation of the last_null_byte() function. This represents the inheritance interface and can be overridden by subclasses. */ virtual size_t do_last_null_byte() const; protected: uchar *pack_int(uchar *to, const uchar *from, size_t size) { memcpy(to, from, size); return to + size; } const uchar *unpack_int(uchar* to, const uchar *from, const uchar *from_end, size_t size) { if (from + size > from_end) return 0; memcpy(to, from, size); return from + size; } uchar *pack_int16(uchar *to, const uchar *from) { return pack_int(to, from, 2); } const uchar *unpack_int16(uchar* to, const uchar *from, const uchar *from_end) { return unpack_int(to, from, from_end, 2); } uchar *pack_int24(uchar *to, const uchar *from) { return pack_int(to, from, 3); } const uchar *unpack_int24(uchar* to, const uchar *from, const uchar *from_end) { return unpack_int(to, from, from_end, 3); } uchar *pack_int32(uchar *to, const uchar *from) { return pack_int(to, from, 4); } const uchar *unpack_int32(uchar* to, const uchar *from, const uchar *from_end) { return unpack_int(to, from, from_end, 4); } uchar *pack_int64(uchar* to, const uchar *from) { return pack_int(to, from, 8); } const uchar *unpack_int64(uchar* to, const uchar *from, const uchar *from_end) { return unpack_int(to, from, from_end, 8); } double pos_in_interval_val_real(Field *min, Field *max); double pos_in_interval_val_str(Field *min, Field *max, uint data_offset); }; class Field_num :public Field { protected: int check_edom_and_important_data_truncation(const char *type, bool edom, CHARSET_INFO *cs, const char *str, size_t length, const char *end_of_num); int check_edom_and_truncation(const char *type, bool edom, CHARSET_INFO *cs, const char *str, size_t length, const char *end_of_num); int check_int(CHARSET_INFO *cs, const char *str, size_t length, const char *int_end, int error) { return check_edom_and_truncation("integer", error == MY_ERRNO_EDOM || str == int_end, cs, str, length, int_end); } bool get_int(CHARSET_INFO *cs, const char *from, size_t len, longlong *rnd, ulonglong unsigned_max, longlong signed_min, longlong signed_max); void prepend_zeros(String *value) const; Item *get_equal_zerofill_const_item(THD *thd, const Context &ctx, Item *const_item); Binlog_type_info::binlog_sign_t binlog_signedness() const { return (flags & UNSIGNED_FLAG) ? Binlog_type_info::SIGN_UNSIGNED : Binlog_type_info::SIGN_SIGNED; } bool send_numeric_zerofill_str(Protocol_text *protocol, protocol_send_type_t send_type); public: const decimal_digits_t dec; bool zerofill,unsigned_flag; // Purify cannot handle bit fields Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg, bool zero_arg, bool unsigned_arg); CHARSET_INFO *charset() const override { return DTCollation_numeric::singleton().collation; } const DTCollation &dtcollation() const override { return DTCollation_numeric::singleton(); } sql_mode_t can_handle_sql_mode_dependency_on_store() const override; Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override { return (flags & ZEROFILL_FLAG) ? get_equal_zerofill_const_item(thd, ctx, const_item) : const_item; } void add_zerofill_and_unsigned(String &res) const; friend class Create_field; void make_send_field(Send_field *) override; decimal_digits_t decimals() const override { return dec; } uint size_of() const override { return sizeof(*this); } bool eq_def(const Field *field) const override; Copy_func *get_copy_func(const Field *from) const override { if (unsigned_flag && from->cmp_type() == DECIMAL_RESULT) return do_field_decimal; return do_field_int; } int save_in_field(Field *to) override { return to->store(val_int(), MY_TEST(flags & UNSIGNED_FLAG)); } bool is_equal(const Column_definition &new_field) const override; uint row_pack_length() const override { return pack_length(); } uint32 pack_length_from_metadata(uint field_metadata) const override { uint32 length= pack_length(); DBUG_PRINT("result", ("pack_length_from_metadata(%d): %u", field_metadata, length)); return length; } double pos_in_interval(Field *min, Field *max) override { return pos_in_interval_val_real(min, max); } SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override; Binlog_type_info binlog_type_info() const override { DBUG_ASSERT(Field_num::type() == binlog_type()); return Binlog_type_info(Field_num::type(), 0, 0, binlog_signedness()); } }; class Field_str :public Field { protected: DTCollation m_collation; // A short alias for m_collation.collation with non-virtual linkage const CHARSET_INFO *field_charset() const { return m_collation.collation; } uint mbmaxlen() const { return m_collation.collation->mbmaxlen; } public: bool can_be_substituted_to_equal_item(const Context &ctx, const Item_equal *item_equal) override; Field_str(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation); decimal_digits_t decimals() const override { return is_created_from_null_item ? 0 : DECIMAL_NOT_SPECIFIED; } int save_in_field(Field *to) override { return save_in_field_str(to); } bool memcpy_field_possible(const Field *from) const override { return real_type() == from->real_type() && pack_length() == from->pack_length() && charset() == from->charset(); } int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_decimal(const my_decimal *) override; int store(const char *to,size_t length,CHARSET_INFO *cs) override=0; int store_hex_hybrid(const char *str, size_t length) override { return store(str, length, &my_charset_bin); } CHARSET_INFO *charset() const override { return m_collation.collation; } const DTCollation &dtcollation() const override { return m_collation; } void change_charset(const DTCollation &new_cs) override; bool binary() const override { return field_charset() == &my_charset_bin; } uint32 max_display_length() const override { return field_length; } uint32 character_octet_length() const override { return field_length; } uint32 char_length() const override { return field_length / mbmaxlen(); } Information_schema_character_attributes information_schema_character_attributes() const override { return Information_schema_character_attributes(max_display_length(), char_length()); } friend class Create_field; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override { return val_real() != 0e0; } bool str_needs_quotes() const override { return true; } bool eq_cmp_as_binary() override { return MY_TEST(flags & BINARY_FLAG); } virtual uint length_size() const { return 0; } double pos_in_interval(Field *min, Field *max) override { return pos_in_interval_val_str(min, max, length_size()); } bool test_if_equality_guarantees_uniqueness(const Item *const_item) const override; SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override; Binlog_type_info binlog_type_info() const override { DBUG_ASSERT(Field_str::type() == binlog_type()); return Binlog_type_info(Field_str::type(), 0, 0, charset()); } }; /* base class for Field_string, Field_varstring and Field_blob */ class Field_longstr :public Field_str { protected: int report_if_important_data(const char *ptr, const char *end, bool count_spaces); bool check_string_copy_error(const String_copier *copier, const char *end, CHARSET_INFO *cs); int check_conversion_status(const String_copier *copier, const char *end, CHARSET_INFO *cs, bool count_spaces) { if (check_string_copy_error(copier, end, cs)) return 2; return report_if_important_data(copier->source_end_pos(), end, count_spaces); } int well_formed_copy_with_check(char *to, size_t to_length, CHARSET_INFO *from_cs, const char *from, size_t from_length, size_t nchars, bool count_spaces, uint *copy_length) { String_copier copier; *copy_length= copier.well_formed_copy(field_charset(), to, to_length, from_cs, from, from_length, nchars); return check_conversion_status(&copier, from + from_length, from_cs, count_spaces); } Data_type_compatibility cmp_to_string_with_same_collation( const Item_bool_func *cond, const Item *item) const; Data_type_compatibility cmp_to_string_with_stricter_collation( const Item_bool_func *cond, const Item *item) const; int compress(char *to, uint to_length, const char *from, uint length, uint max_length, uint *out_length, CHARSET_INFO *cs, size_t nchars); String *uncompress(String *val_buffer, String *val_ptr, const uchar *from, uint from_length) const; public: Field_longstr(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation) :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, collation) {} enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; int store_decimal(const my_decimal *d) override; uint32 max_data_length() const override; void make_send_field(Send_field *) override; bool send(Protocol *protocol) override; bool is_varchar_and_in_write_set() const override { DBUG_ASSERT(table && table->write_set); return bitmap_is_set(table->write_set, field_index); } bool match_collation_to_optimize_range() const { return true; } Data_type_compatibility can_optimize_keypart_ref(const Item_bool_func *cond, const Item *item) const override; Data_type_compatibility can_optimize_hash_join(const Item_bool_func *cond, const Item *item) const override; Data_type_compatibility can_optimize_group_min_max(const Item_bool_func *cond, const Item *const_item) const override; Data_type_compatibility can_optimize_range(const Item_bool_func *cond, const Item *item, bool is_eq_func) const override; bool is_packable() const override { return true; } uint make_packed_sort_key_part(uchar *buff, const SORT_FIELD_ATTR *sort_field)override; uchar* pack_sort_string(uchar *to, const SORT_FIELD_ATTR *sort_field); }; /* base class for float and double and decimal (old one) */ class Field_real :public Field_num { protected: double get_double(const char *str, size_t length, CHARSET_INFO *cs, int *err); public: bool not_fixed; Field_real(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg, bool zero_arg, bool unsigned_arg) :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg), not_fixed(dec_arg >= FLOATING_POINT_DECIMALS) {} Copy_func *get_copy_func(const Field *from) const override { return do_field_real; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; Information_schema_numeric_attributes information_schema_numeric_attributes() const override { return dec == DECIMAL_NOT_SPECIFIED ? Information_schema_numeric_attributes(field_length) : Information_schema_numeric_attributes(field_length, dec); } void sql_type(String &str) const override; int save_in_field(Field *to) override { return to->store(val_real()); } bool memcpy_field_possible(const Field *from) const override { /* Cannot do memcpy from a longer field to a shorter field, e.g. a DOUBLE(53,10) into a DOUBLE(10,10). But it should be OK the other way around. */ return real_type() == from->real_type() && pack_length() == from->pack_length() && is_unsigned() <= from->is_unsigned() && decimals() == from->decimals() && field_length >= from->field_length; } int store_decimal(const my_decimal *dec) override { return store(dec->to_double()); } int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override { return val_real() != 0e0; } uint32 max_display_length() const override { return field_length; } uint size_of() const override { return sizeof *this; } Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override; }; class Field_decimal final :public Field_real { public: Field_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg, bool zero_arg,bool unsigned_arg) :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg) {} Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) override; const Type_handler *type_handler() const override { return &type_handler_olddecimal; } enum ha_base_keytype key_type() const override { return zerofill ? HA_KEYTYPE_BINARY : HA_KEYTYPE_NUM; } Information_schema_numeric_attributes information_schema_numeric_attributes() const override { uint tmp= dec ? 2 : 1; // The sign and the decimal point return Information_schema_numeric_attributes(field_length - tmp, dec); } Copy_func *get_copy_func(const Field *from) const override { return eq_def(from) ? get_identical_copy_func() : do_field_string; } int reset() override; int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; void overflow(bool negative); bool zero_pack() const override { return false; } void sql_type(String &str) const override; uchar *pack(uchar* to, const uchar *from, uint max_length) override { return Field::pack(to, from, max_length); } }; /* New decimal/numeric field which use fixed point arithmetic */ class Field_new_decimal final :public Field_num { public: /* The maximum number of decimal digits can be stored */ decimal_digits_t precision; uint32 bin_size; /* Constructors take max_length of the field as a parameter - not the precision as the number of decimal digits allowed. So for example we need to count length from precision handling CREATE TABLE ( DECIMAL(x,y)) */ Field_new_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg, bool zero_arg, bool unsigned_arg); const Type_handler *type_handler() const override { return &type_handler_newdecimal; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } Copy_func *get_copy_func(const Field *from) const override { // if (from->real_type() == MYSQL_TYPE_BIT) // QQ: why? // return do_field_int; return do_field_decimal; } int save_in_field(Field *to) override { my_decimal tmp(ptr, precision, dec); return to->store_decimal(&tmp); } bool memcpy_field_possible(const Field *from) const override { return real_type() == from->real_type() && pack_length() == from->pack_length() && is_unsigned() <= from->is_unsigned() && decimals() == from->decimals() && field_length == from->field_length; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; int reset() override; bool store_value(const my_decimal *decimal_value); bool store_value(const my_decimal *decimal_value, int *native_error); void set_value_on_overflow(my_decimal *decimal_value, bool sign); int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; int store_decimal(const my_decimal *) override; double val_real() override { return my_decimal(ptr, precision, dec).to_double(); } longlong val_int() override { return my_decimal(ptr, precision, dec).to_longlong(unsigned_flag); } ulonglong val_uint() override { return (ulonglong) my_decimal(ptr, precision, dec).to_longlong(true); } my_decimal *val_decimal(my_decimal *) override; String *val_str(String *val_buffer, String *) override { uint fixed_precision= zerofill ? precision : 0; return my_decimal(ptr, precision, dec). to_string(val_buffer, fixed_precision, dec, '0'); } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { my_decimal nr(ptr, precision, dec); return decimal_to_datetime_with_warn(get_thd(), &nr, ltime, fuzzydate, table->s, field_name.str); } bool val_bool() override { return my_decimal(ptr, precision, dec).to_bool(); } int cmp(const uchar *, const uchar *) const override; void sort_string(uchar *buff, uint length) override; bool zero_pack() const override { return false; } void sql_type(String &str) const override; uint32 max_display_length() const override { return field_length; } Information_schema_numeric_attributes information_schema_numeric_attributes() const override { return Information_schema_numeric_attributes(precision, dec); } uint size_of() const override { return sizeof *this; } uint32 pack_length() const override { return bin_size; } uint pack_length_from_metadata(uint field_metadata) const override; uint row_pack_length() const override { return pack_length(); } bool compatible_field_size(uint field_metadata, const Relay_log_info *rli, uint16 mflags, int *order_var) const override; bool is_equal(const Column_definition &new_field) const override; const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data) override; Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override; Binlog_type_info binlog_type_info() const override; }; class Field_int :public Field_num { protected: String *val_str_from_long(String *val_buffer, uint max_char_length, int radix, long nr); public: Field_int(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, 0, zero_arg, unsigned_arg) {} enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; bool memcpy_field_possible(const Field *from) const override { return real_type() == from->real_type() && pack_length() == from->pack_length() && is_unsigned() == from->is_unsigned(); } int store_decimal(const my_decimal *) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override { return val_int() != 0; } ulonglong val_uint() override { longlong nr= val_int(); return nr < 0 && !unsigned_flag ? 0 : (ulonglong) nr; } int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; virtual const Type_limits_int *type_limits_int() const= 0; uint32 max_display_length() const override { return type_limits_int()->char_length(); } Type_numeric_attributes type_numeric_attributes() const override { /* For integer data types, the user-specified length does not constrain the supported range, so e.g. a column of the INT(1) data type supports the full integer range anyway. Choose the maximum from the user-specified length and the maximum possible length determined by the data type capacity: INT(1) -> 11 INT(10) -> 11 INT(40) -> 40 */ uint32 length1= max_display_length(); uint32 length2= field_length; return Type_numeric_attributes(MY_MAX(length1, length2), decimals(), is_unsigned()); } Information_schema_numeric_attributes information_schema_numeric_attributes() const override { uint32 prec= type_limits_int()->precision(); return Information_schema_numeric_attributes(prec, 0); } void sql_type(String &str) const override; SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override { return get_mm_leaf_int(param, key_part, cond, op, value, unsigned_flag); } }; class Field_tiny :public Field_int { const Type_handler_general_purpose_int *type_handler_priv() const { if (is_unsigned()) return &type_handler_utiny; return &type_handler_stiny; } public: Field_tiny(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) {} const Type_handler *type_handler() const override { return type_handler_priv(); } enum ha_base_keytype key_type() const override { return unsigned_flag ? HA_KEYTYPE_BINARY : HA_KEYTYPE_INT8; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int reset() override { ptr[0]=0; return 0; } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 1; } const Type_limits_int *type_limits_int() const override { return type_handler_priv()->type_limits_int(); } uchar *pack(uchar* to, const uchar *from, uint max_length) override { *to= *from; return to + 1; } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data) override { if (from == from_end) return 0; *to= *from; return from + 1; } ulonglong get_max_int_value() const override { return unsigned_flag ? 0xFFULL : 0x7FULL; } }; class Field_short final :public Field_int { const Type_handler_general_purpose_int *type_handler_priv() const { if (is_unsigned()) return &type_handler_ushort; return &type_handler_sshort; } public: Field_short(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) {} Field_short(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, bool unsigned_arg) :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, NONE, field_name_arg, 0, unsigned_arg) {} const Type_handler *type_handler() const override { return type_handler_priv(); } enum ha_base_keytype key_type() const override { return unsigned_flag ? HA_KEYTYPE_USHORT_INT : HA_KEYTYPE_SHORT_INT;} int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int reset() override { ptr[0]=ptr[1]=0; return 0; } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 2; } const Type_limits_int *type_limits_int() const override { return type_handler_priv()->type_limits_int(); } uchar *pack(uchar* to, const uchar *from, uint) override { return pack_int16(to, from); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint) override { return unpack_int16(to, from, from_end); } ulonglong get_max_int_value() const override { return unsigned_flag ? 0xFFFFULL : 0x7FFFULL; } }; class Field_medium final :public Field_int { const Type_handler_general_purpose_int *type_handler_priv() const { if (is_unsigned()) return &type_handler_uint24; return &type_handler_sint24; } public: Field_medium(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) {} const Type_handler *type_handler() const override { return type_handler_priv(); } enum ha_base_keytype key_type() const override { return unsigned_flag ? HA_KEYTYPE_UINT24 : HA_KEYTYPE_INT24; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int reset() override { ptr[0]=ptr[1]=ptr[2]=0; return 0; } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 3; } const Type_limits_int *type_limits_int() const override { return type_handler_priv()->type_limits_int(); } uchar *pack(uchar* to, const uchar *from, uint max_length) override { return Field::pack(to, from, max_length); } ulonglong get_max_int_value() const override { return unsigned_flag ? 0xFFFFFFULL : 0x7FFFFFULL; } }; class Field_long final :public Field_int { const Type_handler_general_purpose_int *type_handler_priv() const { if (is_unsigned()) return &type_handler_ulong; return &type_handler_slong; } public: Field_long(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) {} Field_long(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, bool unsigned_arg) :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, NONE, field_name_arg, 0, unsigned_arg) {} const Type_handler *type_handler() const override { return type_handler_priv(); } enum ha_base_keytype key_type() const override { return unsigned_flag ? HA_KEYTYPE_ULONG_INT : HA_KEYTYPE_LONG_INT; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } double val_real() override; longlong val_int() override; bool send(Protocol *protocol) override; String *val_str(String *, String *) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 4; } const Type_limits_int *type_limits_int() const override { return type_handler_priv()->type_limits_int(); } uchar *pack(uchar* to, const uchar *from, uint) override { return pack_int32(to, from); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint) override { return unpack_int32(to, from, from_end); } ulonglong get_max_int_value() const override { return unsigned_flag ? 0xFFFFFFFFULL : 0x7FFFFFFFULL; } }; class Field_longlong :public Field_int { const Type_handler_general_purpose_int *type_handler_priv() const { if (is_unsigned()) return &type_handler_ulonglong; return &type_handler_slonglong; } public: Field_longlong(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) :Field_int(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, zero_arg, unsigned_arg) {} Field_longlong(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, bool unsigned_arg) :Field_int((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0,0, NONE, field_name_arg, 0, unsigned_arg) {} const Type_handler *type_handler() const override { return type_handler_priv(); } enum ha_base_keytype key_type() const override { return unsigned_flag ? HA_KEYTYPE_ULONGLONG : HA_KEYTYPE_LONGLONG; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=ptr[4]=ptr[5]=ptr[6]=ptr[7]=0; return 0; } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 8; } const Type_limits_int *type_limits_int() const override { return type_handler_priv()->type_limits_int(); } uchar *pack(uchar* to, const uchar *from, uint) override { return pack_int64(to, from); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint) override { return unpack_int64(to, from, from_end); } void set_max() override; bool is_max() override; ulonglong get_max_int_value() const override { return unsigned_flag ? 0xFFFFFFFFFFFFFFFFULL : 0x7FFFFFFFFFFFFFFFULL; } }; class Field_vers_trx_id :public Field_longlong { MYSQL_TIME cache; ulonglong cached; public: Field_vers_trx_id(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, bool zero_arg, bool unsigned_arg) : Field_longlong(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, zero_arg, unsigned_arg), cached(0) {} const Type_handler *type_handler() const override { return &type_handler_vers_trx_id; } uint size_of() const override { return sizeof *this; } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate, ulonglong trx_id); bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date(ltime, fuzzydate, (ulonglong) val_int()); } bool test_if_equality_guarantees_uniqueness(const Item *item) const override; Data_type_compatibility can_optimize_keypart_ref(const Item_bool_func *, const Item *) const override { return Data_type_compatibility::OK; } Data_type_compatibility can_optimize_group_min_max(const Item_bool_func *, const Item *) const override { return Data_type_compatibility::OK; } Data_type_compatibility can_optimize_range(const Item_bool_func *, const Item *, bool is_eq_func) const override { return Data_type_compatibility::OK; } /* cmp_type() cannot be TIME_RESULT, because we want to compare this field against integers. But in all other cases we treat it as TIME_RESULT! */ }; static inline decimal_digits_t fix_dec_arg(decimal_digits_t dec_arg) { return dec_arg >= FLOATING_POINT_DECIMALS ? DECIMAL_NOT_SPECIFIED : dec_arg; } class Field_float final :public Field_real { public: Field_float(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg,bool zero_arg,bool unsigned_arg) :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, fix_dec_arg(dec_arg), zero_arg, unsigned_arg) { } Field_float(uint32 len_arg, bool maybe_null_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, (uint) 0, NONE, field_name_arg, fix_dec_arg(dec_arg), 0, 0) { } const Type_handler *type_handler() const override { return &type_handler_float; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_FLOAT; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int reset() override { bzero(ptr,sizeof(float)); return 0; } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff, uint length) override; uint32 pack_length() const override { return sizeof(float); } uint row_pack_length() const override { return pack_length(); } ulonglong get_max_int_value() const override { /* We use the maximum as per IEEE754-2008 standard, 2^24 */ return 0x1000000ULL; } Binlog_type_info binlog_type_info() const override; }; class Field_double :public Field_real { longlong val_int_from_real(bool want_unsigned_result); public: Field_double(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg,bool zero_arg,bool unsigned_arg) :Field_real(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, fix_dec_arg(dec_arg), zero_arg, unsigned_arg) { } Field_double(uint32 len_arg, bool maybe_null_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0, NONE, field_name_arg, fix_dec_arg(dec_arg), 0, 0) { } Field_double(uint32 len_arg, bool maybe_null_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg, bool not_fixed_arg) :Field_real((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "" : 0, (uint) 0, NONE, field_name_arg, fix_dec_arg(dec_arg), 0, 0) { not_fixed= not_fixed_arg; } void init_for_tmp_table(Field *org_field, TABLE *new_table) override { Field::init_for_tmp_table(org_field, new_table); not_fixed= true; } const Type_handler *type_handler() const override { return &type_handler_double; } enum ha_base_keytype key_type() const override final { return HA_KEYTYPE_DOUBLE; } int store(const char *to,size_t length,CHARSET_INFO *charset) override final; int store(double nr) override final; int store(longlong nr, bool unsigned_val) override final; int reset() override final { bzero(ptr,sizeof(double)); return 0; } double val_real() override final; longlong val_int() override final { return val_int_from_real(false); } ulonglong val_uint() override final { return (ulonglong) val_int_from_real(true); } String *val_str(String *, String *) override final; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override final; void sort_string(uchar *buff, uint length) override final; uint32 pack_length() const override final { return sizeof(double); } uint row_pack_length() const override final { return pack_length(); } ulonglong get_max_int_value() const override final { /* We use the maximum as per IEEE754-2008 standard, 2^53 */ return 0x20000000000000ULL; } Binlog_type_info binlog_type_info() const override final; }; /* Everything saved in this will disappear. It will always return NULL */ class Field_null :public Field_str { static uchar null[1]; public: Field_null(uchar *ptr_arg, uint32 len_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation) :Field_str(ptr_arg, len_arg, null, 1, unireg_check_arg, field_name_arg, collation) {} const Type_handler *type_handler() const override { return &type_handler_null; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; Information_schema_character_attributes information_schema_character_attributes() const override { return Information_schema_character_attributes(); } Copy_func *get_copy_func(const Field *from) const override { return do_field_string; } int store(const char *to, size_t length, CHARSET_INFO *cs) override final { null[0]=1; return 0; } int store(double nr) override final { null[0]=1; return 0; } int store(longlong nr, bool unsigned_val) override final { null[0]=1; return 0; } int store_decimal(const my_decimal *d) override final { null[0]=1; return 0; } int reset() override final { return 0; } double val_real() override final { return 0.0;} longlong val_int() override final { return 0;} bool val_bool() override final { return false; } my_decimal *val_decimal(my_decimal *) override final { return 0; } String *val_str(String *value,String *value2) override final { value2->length(0); return value2;} bool is_equal(const Column_definition &new_field) const override final; int cmp(const uchar *a, const uchar *b) const override final { return 0;} void sort_string(uchar *buff, uint length) override final {} uint32 pack_length() const override final { return 0; } void sql_type(String &str) const override final; uint size_of() const override final { return sizeof *this; } uint32 max_display_length() const override final { return 4; } void move_field_offset(my_ptrdiff_t ptr_diff) override final {} Data_type_compatibility can_optimize_keypart_ref(const Item_bool_func *cond, const Item *item) const override final { return Data_type_compatibility::INCOMPATIBLE_DATA_TYPE; } Data_type_compatibility can_optimize_group_min_max(const Item_bool_func *cond, const Item *const_item) const override final { return Data_type_compatibility::INCOMPATIBLE_DATA_TYPE; } }; class Field_temporal :public Field { protected: Item *get_equal_const_item_datetime(THD *thd, const Context &ctx, Item *const_item); void set_warnings(Sql_condition::enum_warning_level trunc_level, const ErrConv *str, int was_cut, const char *typestr); int store_TIME_return_code_with_warnings(int warn, const ErrConv *str, const char *typestr) { if (!MYSQL_TIME_WARN_HAVE_WARNINGS(warn) && MYSQL_TIME_WARN_HAVE_NOTES(warn)) { set_warnings(Sql_condition::WARN_LEVEL_NOTE, str, warn | MYSQL_TIME_WARN_TRUNCATED, typestr); return 3; } set_warnings(Sql_condition::WARN_LEVEL_WARN, str, warn, typestr); return warn ? 2 : 0; } int store_invalid_with_warning(const ErrConv *str, int was_cut, const char *typestr) { DBUG_ASSERT(was_cut); reset(); Sql_condition::enum_warning_level level= Sql_condition::WARN_LEVEL_WARN; if (was_cut & MYSQL_TIME_WARN_ZERO_DATE) { set_warnings(level, str, MYSQL_TIME_WARN_OUT_OF_RANGE, typestr); return 2; } set_warnings(level, str, MYSQL_TIME_WARN_TRUNCATED, typestr); return 1; } void sql_type_comment(String &str, const Name &name, const Name &comment) const; void sql_type_dec_comment(String &str, const Name &name, uint dec, const Name &comment) const; void sql_type_opt_dec_comment(String &str, const Name &name, uint dec, const Name &comment) const { if (dec) sql_type_dec_comment(str, name, dec, comment); else sql_type_comment(str, name, comment); } static const Name &type_version_mysql56(); public: Field_temporal(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) { flags|= BINARY_FLAG; } int store_hex_hybrid(const char *str, size_t length) override { return store(str, length, &my_charset_bin); } sql_mode_t can_handle_sql_mode_dependency_on_store() const override; Copy_func *get_copy_func(const Field *from) const override; int save_in_field(Field *to) override { MYSQL_TIME ltime; // For temporal types no truncation needed. Rounding mode is not important. if (get_date(<ime, TIME_CONV_NONE | TIME_FRAC_NONE)) return to->reset(); return to->store_time_dec(<ime, decimals()); } bool memcpy_field_possible(const Field *from) const override; uint32 max_display_length() const override { return field_length; } bool str_needs_quotes() const override { return true; } CHARSET_INFO *charset() const override { return DTCollation_numeric::singleton().collation; } const DTCollation &dtcollation() const override { return DTCollation_numeric::singleton(); } CHARSET_INFO *sort_charset() const override { return &my_charset_bin; } bool binary() const override { return true; } bool val_bool() override { return val_real() != 0e0; } bool is_equal(const Column_definition &new_field) const override; bool eq_def(const Field *field) const override { return (Field::eq_def(field) && decimals() == field->decimals()); } my_decimal *val_decimal(my_decimal*) override; double pos_in_interval(Field *min, Field *max) override { return pos_in_interval_val_real(min, max); } Data_type_compatibility can_optimize_keypart_ref(const Item_bool_func *cond, const Item *item) const override; Data_type_compatibility can_optimize_group_min_max(const Item_bool_func *cond, const Item *const_item) const override; Data_type_compatibility can_optimize_range(const Item_bool_func *cond, const Item *item, bool is_eq_func) const override { return Data_type_compatibility::OK; } SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override; }; /** Abstract class for: - DATE - DATETIME - DATETIME(1..6) - DATETIME(0..6) - MySQL56 version */ class Field_temporal_with_date :public Field_temporal { protected: virtual void store_TIME(const MYSQL_TIME *ltime) = 0; void store_datetime(const Datetime &dt) { return store_TIME(dt.get_mysql_time()); } virtual bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) const = 0; bool validate_MMDD(bool not_zero_date, uint month, uint day, date_mode_t fuzzydate) const { if (!not_zero_date) return bool(fuzzydate & TIME_NO_ZERO_DATE); if (!month || !day) return bool(fuzzydate & TIME_NO_ZERO_IN_DATE); return false; } public: Field_temporal_with_date(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_temporal(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) {} bool validate_value_in_record(THD *thd, const uchar *record) const override; }; class Field_timestamp :public Field_temporal { protected: int store_TIME_with_warning(THD *, const Datetime *, const ErrConv *, int warn); virtual void store_TIMEVAL(const timeval &tv)= 0; void store_TIMESTAMP(const Timestamp &ts) { store_TIMEVAL(ts.tv()); } int zero_time_stored_return_code_with_warning(); public: Field_timestamp(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share); const Type_handler *type_handler() const override { return &type_handler_timestamp; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; Copy_func *get_copy_func(const Field *from) const override; sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override; int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; int store_decimal(const my_decimal *) override; int store_timestamp_dec(const timeval &ts, uint dec) override; int save_in_field(Field *to) override; longlong val_int() override; String *val_str(String *, String *) override; bool zero_pack() const override { return false; } /* This method is used by storage/perfschema and Item_func_now_local::save_in_field(). */ void store_TIME(my_time_t ts, ulong sec_part) { int warn; time_round_mode_t mode= Datetime::default_round_mode(get_thd()); store_TIMESTAMP(Timestamp(ts, sec_part).round(decimals(), mode, &warn)); } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; int store_native(const Native &value) override; bool validate_value_in_record(THD *thd, const uchar *record) const override; Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override { return get_equal_const_item_datetime(thd, ctx, const_item); } bool load_data_set_null(THD *thd) override; bool load_data_set_no_data(THD *thd, bool fixed_format) override; }; class Field_timestamp0 :public Field_timestamp { void store_TIMEVAL(const timeval &tv) override { int4store(ptr, tv.tv_sec); } public: Field_timestamp0(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share) :Field_timestamp(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share) { } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_ULONG_INT; } void sql_type(String &str) const override { sql_type_comment(str, Field_timestamp0::type_handler()->name(), Type_handler::version_mariadb53()); } double val_real() override { return (double) Field_timestamp0::val_int(); } bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 4; } int set_time() override; /* Get TIMESTAMP field value as seconds since begging of Unix Epoch */ my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override; bool val_native(Native *to) override; uchar *pack(uchar *to, const uchar *from, uint) override { return pack_int32(to, from); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint) override { return unpack_int32(to, from, from_end); } uint size_of() const override { return sizeof *this; } }; /** Abstract class for: - TIMESTAMP(1..6) - TIMESTAMP(0..6) - MySQL56 version */ class Field_timestamp_with_dec :public Field_timestamp { protected: decimal_digits_t dec; public: Field_timestamp_with_dec(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, decimal_digits_t dec_arg) : Field_timestamp(ptr_arg, MAX_DATETIME_WIDTH + dec_arg + MY_TEST(dec_arg), null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share), dec(dec_arg) { DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); } decimal_digits_t decimals() const override { return dec; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } uchar *pack(uchar *to, const uchar *from, uint max_length) override { return Field::pack(to, from, max_length); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data) override { return Field::unpack(to, from, from_end, param_data); } void make_send_field(Send_field *field) override; void sort_string(uchar *to, uint length) override { DBUG_ASSERT(length == pack_length()); memcpy(to, ptr, length); } bool send(Protocol *protocol) override; double val_real() override; my_decimal* val_decimal(my_decimal*) override; int set_time() override; }; class Field_timestamp_hires :public Field_timestamp_with_dec { uint sec_part_bytes(uint dec) const { return Type_handler_timestamp::sec_part_bytes(dec); } void store_TIMEVAL(const timeval &tv) override; public: Field_timestamp_hires(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, decimal_digits_t dec_arg) : Field_timestamp_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share, dec_arg) { DBUG_ASSERT(dec); } void sql_type(String &str) const override { sql_type_dec_comment(str, Field_timestamp_hires::type_handler()->name(), dec, Type_handler::version_mariadb53()); } bool val_native(Native *to) override; my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override; int cmp(const uchar *,const uchar *) const override; uint32 pack_length() const override { return 4 + sec_part_bytes(dec); } uint size_of() const override { return sizeof *this; } }; /** TIMESTAMP(0..6) - MySQL56 version */ class Field_timestampf :public Field_timestamp_with_dec { void store_TIMEVAL(const timeval &tv) override; public: Field_timestampf(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, decimal_digits_t dec_arg) : Field_timestamp_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share, dec_arg) {} const Type_handler *type_handler() const override { return &type_handler_timestamp2; } enum_field_types binlog_type() const override { return MYSQL_TYPE_TIMESTAMP2; } void sql_type(String &str) const override { sql_type_opt_dec_comment(str, Field_timestampf::type_handler()->name(), dec, type_version_mysql56()); } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; uint32 pack_length() const override { return my_timestamp_binary_length(dec); } uint row_pack_length() const override { return pack_length(); } uint pack_length_from_metadata(uint field_metadata) const override { DBUG_ENTER("Field_timestampf::pack_length_from_metadata"); uint tmp= my_timestamp_binary_length(field_metadata); DBUG_RETURN(tmp); } int cmp(const uchar *a_ptr,const uchar *b_ptr) const override { return memcmp(a_ptr, b_ptr, pack_length()); } void set_max() override; bool is_max() override; my_time_t get_timestamp(const uchar *pos, ulong *sec_part) const override; bool val_native(Native *to) override; uint size_of() const override { return sizeof *this; } Binlog_type_info binlog_type_info() const override; }; class Field_year final :public Field_tiny { public: Field_year(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_tiny(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, 1, 1) {} const Type_handler *type_handler() const override { return field_length == 2 ? &type_handler_year2 : &type_handler_year; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; Copy_func *get_copy_func(const Field *from) const override { if (eq_def(from)) return get_identical_copy_func(); switch (from->cmp_type()) { case STRING_RESULT: { const Type_handler *handler= from->type_handler(); if (handler == &type_handler_enum || handler == &type_handler_set) return do_field_int; return do_field_string; } case TIME_RESULT: return do_field_date; case DECIMAL_RESULT: return do_field_decimal; case REAL_RESULT: return do_field_real; case INT_RESULT: break; case ROW_RESULT: default: DBUG_ASSERT(0); break; } return do_field_int; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool send(Protocol *protocol) override; Information_schema_numeric_attributes information_schema_numeric_attributes() const override { return Information_schema_numeric_attributes(); } uint32 max_display_length() const override { return field_length; } void sql_type(String &str) const override; }; class Field_date_common :public Field_temporal_with_date { protected: int store_TIME_with_warning(const Datetime *ltime, const ErrConv *str, int was_cut); public: Field_date_common(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_temporal_with_date(ptr_arg, MAX_DATE_WIDTH, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) {} Copy_func *get_copy_func(const Field *from) const override; SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override; int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; int store_decimal(const my_decimal *) override; }; class Field_date final :public Field_date_common { void store_TIME(const MYSQL_TIME *ltime) override; bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) const override; public: Field_date(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_date_common(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) {} const Type_handler *type_handler() const override { return &type_handler_date; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_ULONG_INT; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; int reset() override { ptr[0]=ptr[1]=ptr[2]=ptr[3]=0; return 0; } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return Field_date::get_TIME(ltime, ptr, fuzzydate); } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 4; } void sql_type(String &str) const override; uchar *pack(uchar* to, const uchar *from, uint) override { return pack_int32(to, from); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint) override { return unpack_int32(to, from, from_end); } uint size_of() const override { return sizeof *this; } }; class Field_newdate final :public Field_date_common { void store_TIME(const MYSQL_TIME *ltime) override; bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) const override; public: Field_newdate(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_date_common(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) {} const Type_handler *type_handler() const override { return &type_handler_newdate; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_UINT24; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; int reset() override { ptr[0]=ptr[1]=ptr[2]=0; return 0; } double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 3; } void sql_type(String &str) const override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return Field_newdate::get_TIME(ltime, ptr, fuzzydate); } longlong val_datetime_packed(THD *thd) override; uint size_of() const override { return sizeof *this; } Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override; }; class Field_time :public Field_temporal { /* when this Field_time instance is used for storing values for index lookups (see class store_key, Field::new_key_field(), etc), the following might be set to TO_DAYS(CURDATE()). See also Field_time::store_time_dec() */ long curdays; protected: virtual void store_TIME(const MYSQL_TIME *ltime)= 0; void store_TIME(const Time &t) { return store_TIME(t.get_mysql_time()); } int store_TIME_with_warning(const Time *ltime, const ErrConv *str, int warn); bool check_zero_in_date_with_warn(date_mode_t fuzzydate); static void do_field_time(Copy_field *copy); public: Field_time(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_temporal(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg), curdays(0) {} bool can_be_substituted_to_equal_item(const Context &ctx, const Item_equal *item_equal) override; const Type_handler *type_handler() const override { return &type_handler_time; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; Copy_func *get_copy_func(const Field *from) const override { return from->cmp_type() == REAL_RESULT ? do_field_string : // MDEV-9344 from->type() == MYSQL_TYPE_YEAR ? do_field_int : from->type() == MYSQL_TYPE_BIT ? do_field_int : eq_def(from) ? get_identical_copy_func() : do_field_time; } bool memcpy_field_possible(const Field *from) const override { return real_type() == from->real_type() && decimals() == from->decimals(); } sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override; int store_native(const Native &value) override; bool val_native(Native *to) override; int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_decimal(const my_decimal *) override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; void set_curdays(THD *thd); Field *new_key_field(MEM_ROOT *root, TABLE *new_table, uchar *new_ptr, uint32 length, uchar *new_null_ptr, uint new_null_bit) override; Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override; }; class Field_time0 final :public Field_time { protected: void store_TIME(const MYSQL_TIME *ltime) override; public: Field_time0(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_time(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) { } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_INT24; } void sql_type(String &str) const override { sql_type_comment(str, Field_time0::type_handler()->name(), Type_handler::version_mariadb53()); } double val_real() override; longlong val_int() override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 3; } uint size_of() const override { return sizeof *this; } }; /** Abstract class for: - TIME(1..6) - TIME(0..6) - MySQL56 version */ class Field_time_with_dec :public Field_time { protected: decimal_digits_t dec; public: Field_time_with_dec(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_time(ptr_arg, MIN_TIME_WIDTH + dec_arg + MY_TEST(dec_arg), null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg), dec(dec_arg) { DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); } decimal_digits_t decimals() const override { return dec; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } longlong val_int() override; double val_real() override; void make_send_field(Send_field *) override; }; /** TIME(1..6) */ class Field_time_hires final :public Field_time_with_dec { longlong zero_point; void store_TIME(const MYSQL_TIME *) override; public: Field_time_hires(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_time_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg) { DBUG_ASSERT(dec); zero_point= sec_part_shift( ((TIME_MAX_VALUE_SECONDS+1LL)*TIME_SECOND_PART_FACTOR), dec); } void sql_type(String &str) const override { sql_type_dec_comment(str, Field_time_hires::type_handler()->name(), dec, Type_handler::version_mariadb53()); } int reset() override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return Type_handler_time::hires_bytes(dec); } uint size_of() const override { return sizeof *this; } }; /** TIME(0..6) - MySQL56 version */ class Field_timef final :public Field_time_with_dec { void store_TIME(const MYSQL_TIME *ltime) override; public: Field_timef(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_time_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg) { DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); } const Type_handler *type_handler() const override { return &type_handler_time2; } enum_field_types binlog_type() const override { return MYSQL_TYPE_TIME2; } void sql_type(String &str) const override { sql_type_opt_dec_comment(str, Field_timef::type_handler()->name(), dec, type_version_mysql56()); } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; uint32 pack_length() const override { return my_time_binary_length(dec); } uint row_pack_length() const override { return pack_length(); } uint pack_length_from_metadata(uint field_metadata) const override { DBUG_ENTER("Field_timef::pack_length_from_metadata"); uint tmp= my_time_binary_length(field_metadata); DBUG_RETURN(tmp); } void sort_string(uchar *to, uint length) override { DBUG_ASSERT(length == Field_timef::pack_length()); memcpy(to, ptr, length); } int cmp(const uchar *a_ptr, const uchar *b_ptr) const override { return memcmp(a_ptr, b_ptr, pack_length()); } int reset() override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override; longlong val_time_packed(THD *thd) override; int store_native(const Native &value) override; bool val_native(Native *to) override; uint size_of() const override { return sizeof *this; } Binlog_type_info binlog_type_info() const override; }; class Field_datetime :public Field_temporal_with_date { protected: int store_TIME_with_warning(const Datetime *ltime, const ErrConv *str, int was_cut); public: Field_datetime(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_temporal_with_date(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) { if (unireg_check == TIMESTAMP_UN_FIELD || unireg_check == TIMESTAMP_DNUN_FIELD) flags|= ON_UPDATE_NOW_FLAG; } const Type_handler *type_handler() const override { return &type_handler_datetime; } sql_mode_t conversion_depends_on_sql_mode(THD *, Item *) const override; enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_time_dec(const MYSQL_TIME *ltime, uint dec) override; int store_decimal(const my_decimal *) override; int set_time() override; Item *get_equal_const_item(THD *thd, const Context &ctx, Item *const_item) override { return get_equal_const_item_datetime(thd, ctx, const_item); } }; /* Stored as a 8 byte unsigned int. Should sometimes be change to a 6 byte */ class Field_datetime0 final :public Field_datetime { void store_TIME(const MYSQL_TIME *ltime) override; bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) const override; public: Field_datetime0(uchar *ptr_arg, uint length_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg) :Field_datetime(ptr_arg, length_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg) {} enum ha_base_keytype key_type() const override { return HA_KEYTYPE_ULONGLONG; } void sql_type(String &str) const override { sql_type_comment(str, Field_datetime0::type_handler()->name(), Type_handler::version_mariadb53()); } double val_real() override { return (double) Field_datetime0::val_int(); } longlong val_int() override; String *val_str(String *, String *) override; bool send(Protocol *protocol) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return 8; } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return Field_datetime0::get_TIME(ltime, ptr, fuzzydate); } uchar *pack(uchar* to, const uchar *from, uint) override { return pack_int64(to, from); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint) override { return unpack_int64(to, from, from_end); } uint size_of() const override { return sizeof *this; } }; /** Abstract class for: - DATETIME(1..6) - DATETIME(0..6) - MySQL56 version */ class Field_datetime_with_dec :public Field_datetime { protected: decimal_digits_t dec; public: Field_datetime_with_dec(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_datetime(ptr_arg, MAX_DATETIME_WIDTH + dec_arg + MY_TEST(dec_arg), null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg), dec(dec_arg) { DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); } decimal_digits_t decimals() const override final { return dec; } enum ha_base_keytype key_type() const override final { return HA_KEYTYPE_BINARY; } void make_send_field(Send_field *field) override final; bool send(Protocol *protocol) override final; uchar *pack(uchar *to, const uchar *from, uint max_length) override final { return Field::pack(to, from, max_length); } const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data) override final { return Field::unpack(to, from, from_end, param_data); } void sort_string(uchar *to, uint length) override final { DBUG_ASSERT(length == pack_length()); memcpy(to, ptr, length); } double val_real() override final; longlong val_int() override final; String *val_str(String *, String *) override final; }; /** DATETIME(1..6) */ class Field_datetime_hires final :public Field_datetime_with_dec { void store_TIME(const MYSQL_TIME *ltime) override; bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) const override; public: Field_datetime_hires(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_datetime_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg) { DBUG_ASSERT(dec); } void sql_type(String &str) const override { sql_type_dec_comment(str, Field_datetime_hires::type_handler()->name(), dec, Type_handler::version_mariadb53()); } int cmp(const uchar *,const uchar *) const override; uint32 pack_length() const override { return Type_handler_datetime::hires_bytes(dec); } bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return Field_datetime_hires::get_TIME(ltime, ptr, fuzzydate); } uint size_of() const override { return sizeof *this; } }; /** DATETIME(0..6) - MySQL56 version */ class Field_datetimef final :public Field_datetime_with_dec { void store_TIME(const MYSQL_TIME *ltime) override; bool get_TIME(MYSQL_TIME *ltime, const uchar *pos, date_mode_t fuzzydate) const override; public: Field_datetimef(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, decimal_digits_t dec_arg) :Field_datetime_with_dec(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg) {} const Type_handler *type_handler() const override { return &type_handler_datetime2; } enum_field_types binlog_type() const override { return MYSQL_TYPE_DATETIME2; } void sql_type(String &str) const override { sql_type_opt_dec_comment(str, Field_datetimef::type_handler()->name(), dec, type_version_mysql56()); } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; uint32 pack_length() const override { return my_datetime_binary_length(dec); } uint row_pack_length() const override { return pack_length(); } uint pack_length_from_metadata(uint field_metadata) const override { DBUG_ENTER("Field_datetimef::pack_length_from_metadata"); uint tmp= my_datetime_binary_length(field_metadata); DBUG_RETURN(tmp); } int cmp(const uchar *a_ptr, const uchar *b_ptr) const override { return memcmp(a_ptr, b_ptr, pack_length()); } int reset() override; bool get_date(MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return Field_datetimef::get_TIME(ltime, ptr, fuzzydate); } longlong val_datetime_packed(THD *thd) override; uint size_of() const override { return sizeof *this; } Binlog_type_info binlog_type_info() const override; }; static inline Field_timestamp * new_Field_timestamp(MEM_ROOT *root,uchar *ptr, uchar *null_ptr, uchar null_bit, enum Field::utype unireg_check, const LEX_CSTRING *field_name, TABLE_SHARE *share, decimal_digits_t dec) { if (dec==0) return new (root) Field_timestamp0(ptr, MAX_DATETIME_WIDTH, null_ptr, null_bit, unireg_check, field_name, share); if (dec >= FLOATING_POINT_DECIMALS) dec= MAX_DATETIME_PRECISION; return new (root) Field_timestamp_hires(ptr, null_ptr, null_bit, unireg_check, field_name, share, dec); } static inline Field_time * new_Field_time(MEM_ROOT *root, uchar *ptr, uchar *null_ptr, uchar null_bit, enum Field::utype unireg_check, const LEX_CSTRING *field_name, decimal_digits_t dec) { if (dec == 0) return new (root) Field_time0(ptr, MIN_TIME_WIDTH, null_ptr, null_bit, unireg_check, field_name); if (dec >= FLOATING_POINT_DECIMALS) dec= MAX_DATETIME_PRECISION; return new (root) Field_time_hires(ptr, null_ptr, null_bit, unireg_check, field_name, dec); } static inline Field_datetime * new_Field_datetime(MEM_ROOT *root, uchar *ptr, uchar *null_ptr, uchar null_bit, enum Field::utype unireg_check, const LEX_CSTRING *field_name, decimal_digits_t dec) { if (dec == 0) return new (root) Field_datetime0(ptr, MAX_DATETIME_WIDTH, null_ptr, null_bit, unireg_check, field_name); if (dec >= FLOATING_POINT_DECIMALS) dec= MAX_DATETIME_PRECISION; return new (root) Field_datetime_hires(ptr, null_ptr, null_bit, unireg_check, field_name, dec); } class Field_string final :public Field_longstr { class Warn_filter_string: public Warn_filter { public: Warn_filter_string(const THD *thd, const Field_string *field); }; bool is_var_string() const { return can_alter_field_type && orig_table && (orig_table->s->db_create_options & HA_OPTION_PACK_RECORD) && field_length >= 4 && orig_table->s->frm_version < FRM_VER_TRUE_VARCHAR; } LEX_CSTRING to_lex_cstring() const; public: bool can_alter_field_type; Field_string(uchar *ptr_arg, uint32 len_arg,uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation) :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, collation), can_alter_field_type(1) {}; Field_string(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation) :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0, NONE, field_name_arg, collation), can_alter_field_type(1) {}; const Type_handler *type_handler() const override; enum ha_base_keytype key_type() const override { return binary() ? HA_KEYTYPE_BINARY : HA_KEYTYPE_TEXT; } en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override; bool zero_pack() const override { return false; } Copy_func *get_copy_func(const Field *from) const override; int reset() override { charset()->fill((char*) ptr, field_length, (has_charset() ? ' ' : 0)); return 0; } int store(const char *to,size_t length,CHARSET_INFO *charset) override; using Field_str::store; double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; my_decimal *val_decimal(my_decimal *) override; int cmp(const uchar *,const uchar *) const override; int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_char_len) const override; void sort_string(uchar *buff,uint length) override; void update_data_type_statistics(Data_type_statistics *st) const override { st->m_fixed_string_count++; st->m_fixed_string_total_length+= pack_length(); } void sql_type(String &str) const override; void sql_rpl_type(String*) const override; bool is_equal(const Column_definition &new_field) const override; uchar *pack(uchar *to, const uchar *from, uint max_length) override; const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data) override; uint pack_length_from_metadata(uint field_metadata) const override { DBUG_PRINT("debug", ("field_metadata: 0x%04x", field_metadata)); if (field_metadata == 0) return row_pack_length(); return (((field_metadata >> 4) & 0x300) ^ 0x300) + (field_metadata & 0x00ff); } bool compatible_field_size(uint field_metadata, const Relay_log_info *rli, uint16 mflags, int *order_var) const override; uint row_pack_length() const override { return field_length; } uint packed_col_length(const uchar *to, uint length) override; uint max_packed_col_length(uint max_length) override; uint size_of() const override { return sizeof *this; } bool has_charset() const override { return charset() != &my_charset_bin; } Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) override; uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type) const override; sql_mode_t value_depends_on_sql_mode() const override; sql_mode_t can_handle_sql_mode_dependency_on_store() const override; void print_key_value(String *out, uint32 length) override; Binlog_type_info binlog_type_info() const override; }; class Field_varstring :public Field_longstr { public: const uchar *get_data() const { return get_data(ptr); } const uchar *get_data(const uchar *ptr_arg) const { return ptr_arg + length_bytes; } uint get_length() const { return get_length(ptr); } uint get_length(const uchar *ptr_arg) const { return length_bytes == 1 ? (uint) *ptr_arg : uint2korr(ptr_arg); } protected: void store_length(uint32 number) { if (length_bytes == 1) *ptr= (uchar) number; else int2store(ptr, number); } virtual void val_str_from_ptr(String *val, const uchar *ptr) const; public: /* The maximum space available in a Field_varstring, in bytes. See length_bytes. */ static const uint MAX_SIZE; /* Store number of bytes used to store length (1 or 2) */ uint32 length_bytes; Field_varstring(uchar *ptr_arg, uint32 len_arg, uint length_bytes_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, const DTCollation &collation) :Field_longstr(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, collation), length_bytes(length_bytes_arg) { share->varchar_fields++; } Field_varstring(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, const DTCollation &collation) :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0, NONE, field_name_arg, collation), length_bytes(len_arg < 256 ? 1 :2) { share->varchar_fields++; } const Type_handler *type_handler() const override; en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override { return FIELD_VARCHAR; } enum ha_base_keytype key_type() const override; uint16 key_part_flag() const override { return HA_VAR_LENGTH_PART; } uint16 key_part_length_bytes() const override { return HA_KEY_BLOB_LENGTH; } uint row_pack_length() const override { return field_length; } bool zero_pack() const override { return false; } int reset() override { bzero(ptr,field_length+length_bytes); return 0; } uint32 pack_length() const override { return (uint32) field_length+length_bytes; } uint32 key_length() const override { return (uint32) field_length; } uint32 sort_length() const override { return (uint32) field_length + sort_suffix_length(); } uint32 sort_suffix_length() const override { return (field_charset() == &my_charset_bin ? length_bytes : 0); } Copy_func *get_copy_func(const Field *from) const override; bool memcpy_field_possible(const Field *from) const override; void update_data_type_statistics(Data_type_statistics *st) const override { st->m_variable_string_count++; st->m_variable_string_total_length+= pack_length(); } int store(const char *to,size_t length,CHARSET_INFO *charset) override; using Field_str::store; #ifdef HAVE_MEM_CHECK void mark_unused_memory_as_defined() override; #endif double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; my_decimal *val_decimal(my_decimal *) override; bool send(Protocol *protocol) override; int cmp(const uchar *a,const uchar *b) const override; int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_char_len) const override; void sort_string(uchar *buff,uint length) override; uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type) const override; void set_key_image(const uchar *buff,uint length) override; void sql_type(String &str) const override; void sql_rpl_type(String*) const override; uchar *pack(uchar *to, const uchar *from, uint max_length) override; const uchar *unpack(uchar* to, const uchar *from, const uchar *from_end, uint param_data) override; int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const override; int key_cmp(const uchar *,const uchar*) const override; int key_cmp(const uchar *str, uint length) const override; uint packed_col_length(const uchar *to, uint length) override; uint max_packed_col_length(uint max_length) override; uint32 data_length() override; uint size_of() const override { return sizeof *this; } bool has_charset() const override { return charset() == &my_charset_bin ? FALSE : TRUE; } Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) override; Field *new_key_field(MEM_ROOT *root, TABLE *new_table, uchar *new_ptr, uint32 length, uchar *new_null_ptr, uint new_null_bit) override; bool is_equal(const Column_definition &new_field) const override; void hash_not_null(Hasher *hasher) override; uint length_size() const override { return length_bytes; } void print_key_value(String *out, uint32 length) override; Binlog_type_info binlog_type_info() const override; }; class Field_varstring_compressed final :public Field_varstring { public: Field_varstring_compressed(uchar *ptr_arg, uint32 len_arg, uint length_bytes_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, const DTCollation &collation, Compression_method *compression_method_arg): Field_varstring(ptr_arg, len_arg, length_bytes_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share, collation), compression_method_ptr(compression_method_arg) { DBUG_ASSERT(len_arg > 0); } Compression_method *compression_method() const override { return compression_method_ptr; } private: Compression_method *compression_method_ptr; void val_str_from_ptr(String *val, const uchar *ptr) const override; int store(const char *to, size_t length, CHARSET_INFO *charset) override; using Field_str::store; String *val_str(String *, String *) override; double val_real() override; longlong val_int() override; uint size_of() const override { return sizeof *this; } /* We use the default Field::send() implementation, because the derived optimized version (from Field_longstr) is not suitable for compressed fields. */ bool send(Protocol *protocol) override { return Field::send(protocol); } enum_field_types binlog_type() const override { return MYSQL_TYPE_VARCHAR_COMPRESSED; } void sql_type(String &str) const override { Field_varstring::sql_type(str); str.append(STRING_WITH_LEN(" /*M!100301 COMPRESSED*/")); } uint32 max_display_length() const override { return field_length - 1; } uint32 character_octet_length() const override { return field_length - 1; } uint32 char_length() const override { return (field_length - 1) / mbmaxlen(); } int cmp(const uchar *a_ptr, const uchar *b_ptr) const override; /* Compressed fields can't have keys as two rows may have different compression methods or compression levels. */ int key_cmp(const uchar *str, uint length) const override { DBUG_ASSERT(0); return 0; } using Field_varstring::key_cmp; Binlog_type_info binlog_type_info() const override; Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) override; }; static inline uint8 number_storage_requirement(uint32 n) { return n < 256 ? 1 : n < 65536 ? 2 : n < 16777216 ? 3 : 4; } static inline void store_bigendian(ulonglong num, uchar *to, uint bytes) { switch(bytes) { case 1: mi_int1store(to, num); break; case 2: mi_int2store(to, num); break; case 3: mi_int3store(to, num); break; case 4: mi_int4store(to, num); break; case 5: mi_int5store(to, num); break; case 6: mi_int6store(to, num); break; case 7: mi_int7store(to, num); break; case 8: mi_int8store(to, num); break; default: DBUG_ASSERT(0); } } static inline longlong read_bigendian(const uchar *from, uint bytes) { switch(bytes) { case 1: return mi_uint1korr(from); case 2: return mi_uint2korr(from); case 3: return mi_uint3korr(from); case 4: return mi_uint4korr(from); case 5: return mi_uint5korr(from); case 6: return mi_uint6korr(from); case 7: return mi_uint7korr(from); case 8: return mi_sint8korr(from); default: DBUG_ASSERT(0); return 0; } } static inline void store_lowendian(ulonglong num, uchar *to, uint bytes) { switch(bytes) { case 1: *to= (uchar)num; break; case 2: int2store(to, num); break; case 3: int3store(to, num); break; case 4: int4store(to, num); break; case 8: int8store(to, num); break; default: DBUG_ASSERT(0); } } static inline longlong read_lowendian(const uchar *from, uint bytes) { switch(bytes) { case 1: return from[0]; case 2: return uint2korr(from); case 3: return uint3korr(from); case 4: return uint4korr(from); case 8: return sint8korr(from); default: DBUG_ASSERT(0); return 0; } } extern LEX_CSTRING temp_lex_str; class Field_blob :public Field_longstr { protected: /** The number of bytes used to represent the length of the blob. */ uint packlength; /** The 'value'-object is a cache fronting the storage engine. */ String value; /** Cache for blob values when reading a row with a virtual blob field. This is needed to not destroy the old cached value when updating the blob with a new value when creating the new row. */ String read_value; static void do_copy_blob(Copy_field *copy); static void do_conv_blob(Copy_field *copy); uint get_key_image_itRAW(const uchar *ptr_arg, uchar *buff, uint length) const; public: Field_blob(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, uint blob_pack_length, const DTCollation &collation); Field_blob(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation) :Field_longstr((uchar*) 0, len_arg, maybe_null_arg ? (uchar*) "": 0, 0, NONE, field_name_arg, collation), packlength(4) { flags|= BLOB_FLAG; } Field_blob(uint32 len_arg,bool maybe_null_arg, const LEX_CSTRING *field_name_arg, const DTCollation &collation, bool set_packlength) :Field_longstr((uchar*) 0,len_arg, maybe_null_arg ? (uchar*) "": 0, 0, NONE, field_name_arg, collation) { flags|= BLOB_FLAG; packlength= set_packlength ? number_storage_requirement(len_arg) : 4; } Field_blob(uint32 packlength_arg) :Field_longstr((uchar*) 0, 0, (uchar*) "", 0, NONE, &temp_lex_str, system_charset_info), packlength(packlength_arg) {} const Type_handler *type_handler() const override; /* Note that the default copy constructor is used, in clone() */ enum_field_types type() const override { /* We cannot return type_handler()->field_type() here. Some pieces of the code (e.g. in engines) rely on the fact that Field::type(), Field::real_type() and Item_field::field_type() return MYSQL_TYPE_BLOB for all blob variants. We should eventually fix all such code pieces to expect all BLOB type codes. */ return MYSQL_TYPE_BLOB; } enum_field_types real_type() const override { return MYSQL_TYPE_BLOB; } enum ha_base_keytype key_type() const override { return binary() ? HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2; } uint16 key_part_flag() const override { return HA_BLOB_PART; } uint16 key_part_length_bytes() const override { return HA_KEY_BLOB_LENGTH; } en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override { return FIELD_BLOB; } Type_numeric_attributes type_numeric_attributes() const override { return Type_numeric_attributes(Field_blob::max_display_length(), decimals(), is_unsigned()); } Information_schema_character_attributes information_schema_character_attributes() const override { uint32 octets= Field_blob::character_octet_length(); uint32 chars= octets / field_charset()->mbminlen; return Information_schema_character_attributes(octets, chars); } void update_data_type_statistics(Data_type_statistics *st) const override { st->m_blob_count++; } void make_send_field(Send_field *) override; Copy_func *get_copy_func(const Field *from) const override { /* TODO: MDEV-9331 if (from->type() == MYSQL_TYPE_BIT) return do_field_int; */ if (!(from->flags & BLOB_FLAG) || from->charset() != charset() || !from->compression_method() != !compression_method()) return do_conv_blob; if (from->pack_length() != Field_blob::pack_length()) return do_copy_blob; return get_identical_copy_func(); } int store_field(Field *from) override { // Be sure the value is stored if (field_charset() == &my_charset_bin && from->type_handler()->convert_to_binary_using_val_native()) { NativeBuffer<64> tmp; from->val_native(&tmp); value.copy(tmp.ptr(), tmp.length(), &my_charset_bin); return store(value.ptr(), value.length(), &my_charset_bin); } from->val_str(&value); if (table->copy_blobs || (!value.is_alloced() && from->is_varchar_and_in_write_set())) value.copy(); return store(value.ptr(), value.length(), from->charset()); } bool memcpy_field_possible(const Field *from) const override { return Field_str::memcpy_field_possible(from) && !compression_method() == !from->compression_method() && !table->copy_blobs; } bool make_empty_rec_store_default_value(THD *thd, Item *item) override; int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store_from_statistical_minmax_field(Field *stat_field, String *str, MEM_ROOT *mem) override; using Field_str::store; void hash_not_null(Hasher *hasher) override; double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; my_decimal *val_decimal(my_decimal *) override; int cmp(const uchar *a, const uchar *b) const override; int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_char_len) const override; int cmp(const uchar *a, uint32 a_length, const uchar *b, uint32 b_length) const; int cmp_binary(const uchar *a,const uchar *b, uint32 max_length=~0U) const override; int key_cmp(const uchar *,const uchar*) const override; int key_cmp(const uchar *str, uint length) const override; /* Never update the value of min_val for a blob field */ bool update_min(Field *min_val, bool force_update) override { return false; } /* Never update the value of max_val for a blob field */ bool update_max(Field *max_val, bool force_update) override { return false; } uint32 key_length() const override { return 0; } void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return (uint32) (packlength + portable_sizeof_char_ptr); } /** Return the packed length without the pointer size added. This is used to determine the size of the actual data in the row buffer. @returns The length of the raw data itself without the pointer. */ uint32 pack_length_no_ptr() const { return (uint32) (packlength); } uint row_pack_length() const override { return pack_length_no_ptr(); } uint32 sort_length() const override; uint32 sort_suffix_length() const override; uint32 value_length() override { return get_length(); } uint32 max_data_length() const override { return (uint32) (((ulonglong) 1 << (packlength*8)) -1); } int reset() override { bzero(ptr, packlength+sizeof(uchar*)); return 0; } void reset_fields() override { bzero((uchar*) &value, sizeof value); bzero((uchar*) &read_value, sizeof read_value); } uint32 get_field_buffer_size() { return value.alloced_length(); } void store_length(uchar *i_ptr, uint i_packlength, uint32 i_number); void store_length(size_t number) { DBUG_ASSERT(number < UINT_MAX32); store_length(ptr, packlength, (uint32)number); } inline uint32 get_length(my_ptrdiff_t row_offset= 0) const { return get_length(ptr+row_offset, this->packlength); } uint32 get_length(const uchar *ptr, uint packlength) const; uint32 get_length(const uchar *ptr_arg) const { return get_length(ptr_arg, this->packlength); } inline uchar *get_ptr() const { return get_ptr(ptr); } inline uchar *get_ptr(const uchar *ptr_arg) const { uchar *s; memcpy(&s, ptr_arg + packlength, sizeof(uchar*)); return s; } inline void set_ptr(uchar *length, uchar *data) { memcpy(ptr,length,packlength); memcpy(ptr+packlength, &data,sizeof(char*)); } void set_ptr_offset(my_ptrdiff_t ptr_diff, uint32 length, const uchar *data) { uchar *ptr_ofs= ADD_TO_PTR(ptr,ptr_diff,uchar*); store_length(ptr_ofs, packlength, length); memcpy(ptr_ofs+packlength, &data, sizeof(char*)); } inline void set_ptr(uint32 length, uchar *data) { set_ptr_offset(0, length, data); } int copy_value(Field_blob *from); uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type) const override { DBUG_ASSERT(type == itRAW); return get_key_image_itRAW(ptr_arg, buff, length); } void set_key_image(const uchar *buff,uint length) override; Field *make_new_field(MEM_ROOT *, TABLE *new_table, bool keep_type) override; Field *new_key_field(MEM_ROOT *root, TABLE *new_table, uchar *new_ptr, uint32 length, uchar *new_null_ptr, uint new_null_bit) override; void sql_type(String &str) const override; /** Copy blob buffer into internal storage "value" and update record pointer. @retval true Memory allocation error @retval false Success */ bool copy() { uchar *tmp= get_ptr(); if (value.copy((char*) tmp, get_length(), charset())) { Field_blob::reset(); return 1; } tmp=(uchar*) value.ptr(); memcpy(ptr+packlength, &tmp, sizeof(char*)); return 0; } void swap(String &inout, bool set_read_value) { if (set_read_value) read_value.swap(inout); else value.swap(inout); } /** Return pointer to blob cache or NULL if not cached. */ String * cached(bool *set_read_value) { char *tmp= (char *) get_ptr(); if (!value.is_empty() && tmp == value.ptr()) { *set_read_value= false; return &value; } if (!read_value.is_empty() && tmp == read_value.ptr()) { *set_read_value= true; return &read_value; } return NULL; } /* store value for the duration of the current read record */ inline void swap_value_and_read_value() { read_value.swap(value); } inline void set_value(uchar *data) { /* Set value pointer. Lengths are not important */ value.reset((char*) data, 1, 1, &my_charset_bin); } uchar *pack(uchar *to, const uchar *from, uint max_length) override; const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, uint param_data) override; uint packed_col_length(const uchar *col_ptr, uint length) override; uint max_packed_col_length(uint max_length) override; void free() override { value.free(); read_value.free(); } inline void clear_temporary() { uchar *tmp= get_ptr(); if (likely(value.ptr() == (char*) tmp)) bzero((uchar*) &value, sizeof(value)); else { /* Currently read_value should never point to tmp, the following code is mainly here to make things future proof. */ if (unlikely(read_value.ptr() == (char*) tmp)) bzero((uchar*) &read_value, sizeof(read_value)); } } uint size_of() const override { return sizeof *this; } bool has_charset() const override { return charset() != &my_charset_bin; } uint32 max_display_length() const override; uint32 char_length() const override; uint32 character_octet_length() const override; bool is_equal(const Column_definition &new_field) const override; void print_key_value(String *out, uint32 length) override; Binlog_type_info binlog_type_info() const override; friend void TABLE::remember_blob_values(String *blob_storage); friend void TABLE::restore_blob_values(String *blob_storage); }; class Field_blob_compressed final :public Field_blob { public: Field_blob_compressed(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, uint blob_pack_length, const DTCollation &collation, Compression_method *compression_method_arg): Field_blob(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share, blob_pack_length, collation), compression_method_ptr(compression_method_arg) {} Compression_method *compression_method() const override { return compression_method_ptr; } private: Compression_method *compression_method_ptr; int store(const char *to, size_t length, CHARSET_INFO *charset) override; using Field_str::store; String *val_str(String *, String *) override; double val_real() override; longlong val_int() override; /* We use the default Field::send() implementation, because the derived optimized version (from Field_longstr) is not suitable for compressed fields. */ bool send(Protocol *protocol) override { return Field::send(protocol); } uint size_of() const override { return sizeof *this; } enum_field_types binlog_type() const override { return MYSQL_TYPE_BLOB_COMPRESSED; } void sql_type(String &str) const override { Field_blob::sql_type(str); str.append(STRING_WITH_LEN(" /*M!100301 COMPRESSED*/")); } /* Compressed fields can't have keys as two rows may have different compression methods or compression levels. */ uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type_arg) const override { DBUG_ASSERT(0); return 0; } void set_key_image(const uchar *, uint) override { DBUG_ASSERT(0); } int key_cmp(const uchar *, const uchar *) const override { DBUG_ASSERT(0); return 0; } int key_cmp(const uchar *, uint) const override { DBUG_ASSERT(0); return 0; } Field *new_key_field(MEM_ROOT *, TABLE *, uchar *, uint32, uchar *, uint) override { DBUG_ASSERT(0); return 0; } Binlog_type_info binlog_type_info() const override; Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) override; }; class Field_enum :public Field_str { static void do_field_enum(Copy_field *copy_field); longlong val_int(const uchar *) const; Data_type_compatibility can_optimize_range_or_keypart_ref( const Item_bool_func *cond, const Item *item) const; protected: uint packlength; public: const TYPELIB *typelib; Field_enum(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, uint packlength_arg, const TYPELIB *typelib_arg, const DTCollation &collation) :Field_str(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, collation), packlength(packlength_arg),typelib(typelib_arg) { flags|=ENUM_FLAG; } Field *make_new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type) override; const Type_handler *type_handler() const override { return &type_handler_enum; } enum ha_base_keytype key_type() const override; sql_mode_t can_handle_sql_mode_dependency_on_store() const override; enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; Copy_func *get_copy_func(const Field *from) const override { if (eq_def(from)) return get_identical_copy_func(); if (real_type() == MYSQL_TYPE_ENUM && from->real_type() == MYSQL_TYPE_ENUM) return do_field_enum; if (from->result_type() == STRING_RESULT) return do_field_string; return do_field_int; } int store_field(Field *from) override { if (from->real_type() == MYSQL_TYPE_ENUM && from->val_int() == 0) { store_type(0); return 0; } return from->save_in_field(this); } int save_in_field(Field *to) override { if (to->result_type() != STRING_RESULT) return to->store(val_int(), 0); return save_in_field_str(to); } bool memcpy_field_possible(const Field *from) const override { return false; } void make_empty_rec_reset(THD *) override { if (flags & NOT_NULL_FLAG) { set_notnull(); store((longlong) 1, true); } else reset(); } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; double val_real() override; longlong val_int() override; String *val_str(String *, String *) override; int cmp(const uchar *,const uchar *) const override; void sort_string(uchar *buff,uint length) override; uint32 pack_length() const override { return (uint32) packlength; } void store_type(ulonglong value); void sql_type(String &str) const override; uint size_of() const override { return sizeof *this; } uint pack_length_from_metadata(uint field_metadata) const override { return (field_metadata & 0x00ff); } uint row_pack_length() const override { return pack_length(); } bool zero_pack() const override { return false; } bool optimize_range(uint, uint) const override { return false; } bool eq_def(const Field *field) const override; bool has_charset() const override { return true; } /* enum and set are sorted as integers */ CHARSET_INFO *sort_charset() const override { return &my_charset_bin; } decimal_digits_t decimals() const override { return 0; } const TYPELIB *get_typelib() const override { return typelib; } uchar *pack(uchar *to, const uchar *from, uint max_length) override; const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, uint param_data) override; Data_type_compatibility can_optimize_keypart_ref(const Item_bool_func *cond, const Item *item) const override { return can_optimize_range_or_keypart_ref(cond, item); } Data_type_compatibility can_optimize_group_min_max(const Item_bool_func *cond, const Item *const_item) const override { /* Can't use GROUP_MIN_MAX optimization for ENUM and SET, because the values are stored as numbers in index, while MIN() and MAX() work as strings. It would return the records with min and max enum numeric indexes. "Bug#45300 MAX() and ENUM type" should be fixed first. */ return Data_type_compatibility::INCOMPATIBLE_DATA_TYPE; } Data_type_compatibility can_optimize_range(const Item_bool_func *cond, const Item *item, bool is_eq_func) const override { return can_optimize_range_or_keypart_ref(cond, item); } Binlog_type_info binlog_type_info() const override; private: bool is_equal(const Column_definition &new_field) const override; }; class Field_set final :public Field_enum { public: Field_set(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, uint32 packlength_arg, const TYPELIB *typelib_arg, const DTCollation &collation) :Field_enum(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, packlength_arg, typelib_arg, collation) { flags=(flags & ~ENUM_FLAG) | SET_FLAG; } void make_empty_rec_reset(THD *thd) override { Field::make_empty_rec_reset(thd); } int store_field(Field *from) override { return from->save_in_field(this); } int store(const char *to,size_t length,CHARSET_INFO *charset) override; int store(double nr) override { return Field_set::store((longlong) nr, FALSE); } int store(longlong nr, bool unsigned_val) override; bool zero_pack() const override { return true; } String *val_str(String *, String *) override; void sql_type(String &str) const override; uint size_of() const override { return sizeof *this; } const Type_handler *type_handler() const override { return &type_handler_set; } bool has_charset() const override { return true; } Binlog_type_info binlog_type_info() const override; }; /* Note: To use Field_bit::cmp_binary() you need to copy the bits stored in the beginning of the record (the NULL bytes) to each memory you want to compare (where the arguments point). This is the reason: - Field_bit::cmp_binary() is only implemented in the base class (Field::cmp_binary()). - Field::cmp_binary() currently uses pack_length() to calculate how long the data is. - pack_length() includes size of the bits stored in the NULL bytes of the record. */ class Field_bit :public Field { public: uchar *bit_ptr; // position in record where 'uneven' bits store uchar bit_ofs; // offset to 'uneven' high bits uint bit_len; // number of 'uneven' high bits uint bytes_in_rec; Field_bit(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, uchar *bit_ptr_arg, uchar bit_ofs_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg); const Type_handler *type_handler() const override { return &type_handler_bit; } enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BIT; } uint16 key_part_flag() const override { return HA_BIT_PART; } uint32 key_length() const override { return (uint32) (field_length + 7) / 8; } uint32 max_data_length() const override { return key_length(); } uint32 max_display_length() const override { return field_length; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; CHARSET_INFO *charset() const override { return &my_charset_bin; } const DTCollation & dtcollation() const override; Information_schema_numeric_attributes information_schema_numeric_attributes() const override { return Information_schema_numeric_attributes(field_length); } void update_data_type_statistics(Data_type_statistics *st) const override { st->m_uneven_bit_length+= field_length & 7; } uint size_of() const override { return sizeof *this; } int reset() override { bzero(ptr, bytes_in_rec); if (bit_ptr && (bit_len > 0)) // reset odd bits among null bits clr_rec_bits(bit_ptr, bit_ofs, bit_len); return 0; } Copy_func *get_copy_func(const Field *from) const override { if (from->cmp_type() == DECIMAL_RESULT) return do_field_decimal; return do_field_int; } int save_in_field(Field *to) override { return to->store(val_int(), true); } bool memcpy_field_possible(const Field *from) const override{ return false; } int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_decimal(const my_decimal *) override; double val_real() override; longlong val_int() override; String *val_str(String*, String *) override; bool str_needs_quotes() const override { return true; } my_decimal *val_decimal(my_decimal *) override; bool val_bool() override { return val_int() != 0; } int cmp(const uchar *a, const uchar *b) const override { DBUG_ASSERT(ptr == a || ptr == b); if (ptr == a) return Field_bit::key_cmp(b, bytes_in_rec + MY_TEST(bit_len)); else return Field_bit::key_cmp(a, bytes_in_rec + MY_TEST(bit_len)) * -1; } int cmp_binary_offset(uint row_offset) override { return cmp_offset(row_offset); } int cmp_prefix(const uchar *a, const uchar *b, size_t prefix_char_length) const override; int key_cmp(const uchar *a, const uchar *b) const override { return cmp_binary((uchar *) a, (uchar *) b); } int key_cmp(const uchar *str, uint length) const override; int cmp_offset(my_ptrdiff_t row_offset) override; bool update_min(Field *min_val, bool force_update) override { longlong val= val_int(); bool update_fl= force_update || val < min_val->val_int(); if (update_fl) { min_val->set_notnull(); min_val->store(val, FALSE); } return update_fl; } bool update_max(Field *max_val, bool force_update) override { longlong val= val_int(); bool update_fl= force_update || val > max_val->val_int(); if (update_fl) { max_val->set_notnull(); max_val->store(val, FALSE); } return update_fl; } void store_field_value(uchar *val, uint) override { store(*((longlong *)val), TRUE); } double pos_in_interval(Field *min, Field *max) override { return pos_in_interval_val_real(min, max); } void get_image(uchar *buff, uint length, const uchar *ptr_arg, CHARSET_INFO *cs) const override { get_key_image(buff, length, ptr_arg, itRAW); } void set_image(const uchar *buff,uint length, CHARSET_INFO *cs) override { Field_bit::store((char *) buff, length, cs); } uint get_key_image(uchar *buff, uint length, const uchar *ptr_arg, imagetype type) const override; void set_key_image(const uchar *buff, uint length) override { Field_bit::store((char*) buff, length, &my_charset_bin); } void sort_string(uchar *buff, uint length) override { get_key_image(buff, length, ptr, itRAW); } uint32 pack_length() const override { return (uint32) (field_length + 7) / 8; } uint32 pack_length_in_rec() const override { return bytes_in_rec; } uint pack_length_from_metadata(uint field_metadata) const override; uint row_pack_length() const override { return (bytes_in_rec + ((bit_len > 0) ? 1 : 0)); } bool compatible_field_size(uint metadata, const Relay_log_info *rli, uint16 mflags, int *order_var) const override; void sql_type(String &str) const override; uchar *pack(uchar *to, const uchar *from, uint max_length) override; const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, uint param_data) override; int set_default() override; Field *new_key_field(MEM_ROOT *root, TABLE *new_table, uchar *new_ptr, uint32 length, uchar *new_null_ptr, uint new_null_bit) override; void set_bit_ptr(uchar *bit_ptr_arg, uchar bit_ofs_arg) { bit_ptr= bit_ptr_arg; bit_ofs= bit_ofs_arg; } bool eq(Field *field) override { return (Field::eq(field) && bit_ptr == ((Field_bit *)field)->bit_ptr && bit_ofs == ((Field_bit *)field)->bit_ofs); } bool is_equal(const Column_definition &new_field) const override; void move_field_offset(my_ptrdiff_t ptr_diff) override { Field::move_field_offset(ptr_diff); /* clang does not like when things are added to a null pointer, even if it is never referenced. */ if (bit_ptr) bit_ptr= ADD_TO_PTR(bit_ptr, ptr_diff, uchar*); } void hash_not_null(Hasher *hasher) override; SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, KEY_PART *key_part, const Item_bool_func *cond, scalar_comparison_op op, Item *value) override { return get_mm_leaf_int(param, key_part, cond, op, value, true); } void print_key_value(String *out, uint32 length) override { val_int_as_str(out, 1); } /** Save the field metadata for bit fields. Saves the bit length in the first byte and bytes in record in the second byte of the field metadata array at index of *metadata_ptr and *(metadata_ptr + 1). @param metadata_ptr First byte of field metadata @returns number of bytes written to metadata_ptr */ Binlog_type_info binlog_type_info() const override { DBUG_PRINT("debug", ("bit_len: %d, bytes_in_rec: %d", bit_len, bytes_in_rec)); /* Since this class and Field_bit_as_char have different ideas of what should be stored here, we compute the values of the metadata explicitly using the field_length. */ return Binlog_type_info(type(), static_cast((field_length & 7) | ((field_length / 8) << 8)), 2); } private: size_t do_last_null_byte() const override; }; /** BIT field represented as chars for non-MyISAM tables. @todo The inheritance relationship is backwards since Field_bit is an extended version of Field_bit_as_char and not the other way around. Hence, we should refactor it to fix the hierarchy order. */ class Field_bit_as_char final :public Field_bit { public: Field_bit_as_char(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg); enum ha_base_keytype key_type() const override { return HA_KEYTYPE_BINARY; } uint size_of() const override { return sizeof *this; } int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store(double nr) override { return Field_bit::store(nr); } int store(longlong nr, bool unsigned_val) override { return Field_bit::store(nr, unsigned_val); } void sql_type(String &str) const override; }; class Field_row final :public Field_null { class Virtual_tmp_table *m_table; public: Field_row(uchar *ptr_arg, const LEX_CSTRING *field_name_arg) :Field_null(ptr_arg, 0, Field::NONE, field_name_arg, &my_charset_bin), m_table(NULL) {} ~Field_row(); en_fieldtype tmp_engine_column_type(bool use_packed_rows) const override { DBUG_ASSERT(0); return Field::tmp_engine_column_type(use_packed_rows); } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override { DBUG_ASSERT(0); return CONV_TYPE_IMPOSSIBLE; } Virtual_tmp_table **virtual_tmp_table_addr() override { return &m_table; } bool sp_prepare_and_store_item(THD *thd, Item **value) override; }; extern const LEX_CSTRING null_clex_str; class Column_definition_attributes { public: /* At various stages in execution this can be length of field in bytes or max number of characters. */ ulonglong length; const TYPELIB *interval; CHARSET_INFO *charset; uint32 srid; uint32 pack_flag; decimal_digits_t decimals; Field::utype unireg_check; Column_definition_attributes() :length(0), interval(NULL), charset(&my_charset_bin), srid(0), pack_flag(0), decimals(0), unireg_check(Field::NONE) { } Column_definition_attributes(const Field *field); Column_definition_attributes(const Type_all_attributes &attr); Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root, const Record_addr *rec, const Type_handler *handler, const LEX_CSTRING *field_name, uint32 flags) const; uint temporal_dec(uint intlen) const { return (uint) (length > intlen ? length - intlen - 1 : 0); } uint pack_flag_to_pack_length() const; void frm_pack_basic(uchar *buff) const; void frm_pack_charset(uchar *buff) const; void frm_pack_numeric_with_dec(uchar *buff) const; void frm_unpack_basic(const uchar *buff); bool frm_unpack_charset(TABLE_SHARE *share, const uchar *buff); bool frm_unpack_numeric_with_dec(TABLE_SHARE *share, const uchar *buff); bool frm_unpack_temporal_with_dec(TABLE_SHARE *share, uint intlen, const uchar *buff); void set_length_and_dec(const Lex_length_and_dec_st &attr); CHARSET_INFO *explicit_or_derived_charset(const Column_derived_attributes *derived_attr) const { return charset ? charset : derived_attr->charset(); } }; /* Create field class for CREATE TABLE */ class Column_definition: public Sql_alloc, public Type_handler_hybrid_field_type, public Column_definition_attributes { /** Create "interval" from "interval_list". @param mem_root - memory root to create the TYPELIB instance and its values on @param reuse_interval_list_values - determines if TYPELIB can reuse strings from interval_list, or should always allocate a copy on mem_root, even if character set conversion is not needed @retval false on success @retval true on error (bad values, or EOM) */ bool create_interval_from_interval_list(MEM_ROOT *mem_root, bool reuse_interval_list_values); /* Calculate TYPELIB (set or enum) max and total lengths @param cs charset+collation pair of the interval @param max_length length of the longest item @param tot_length sum of the item lengths After this method call: - ENUM uses max_length - SET uses tot_length. */ void calculate_interval_lengths(uint32 *max_length, uint32 *tot_length) { const char **pos; uint *len; *max_length= *tot_length= 0; for (pos= interval->type_names, len= interval->type_lengths; *pos ; pos++, len++) { size_t length= charset->numchars(*pos, *pos + *len); DBUG_ASSERT(length < UINT_MAX32); *tot_length+= (uint) length; set_if_bigger(*max_length, (uint32)length); } } bool prepare_stage1_check_typelib_default(); bool prepare_stage1_convert_default(THD *, MEM_ROOT *, CHARSET_INFO *to); const Type_handler *field_type() const; // Prevent using this Compression_method *compression_method_ptr; public: Lex_ident field_name; LEX_CSTRING comment; // Comment for field enum enum_column_versioning { VERSIONING_NOT_SET, WITH_VERSIONING, WITHOUT_VERSIONING }; Item *on_update; // ON UPDATE NOW() field_visibility_t invisible; /* The value of `length' as set by parser: is the number of characters for most of the types, or of bytes for BLOBs or numeric types. */ uint32 char_length; uint flags, pack_length; List interval_list; engine_option_value *option_list; bool explicitly_nullable; /* This is additinal data provided for any computed(virtual) field. In particular it includes a pointer to the item by which this field can be computed from other fields. */ Virtual_column_info *vcol_info, // Virtual field *default_value, // Default value *check_constraint; // Check constraint enum_column_versioning versioning; Table_period_info *period; Column_definition() :Type_handler_hybrid_field_type(&type_handler_null), compression_method_ptr(0), comment(null_clex_str), on_update(NULL), invisible(VISIBLE), char_length(0), flags(0), pack_length(0), option_list(NULL), explicitly_nullable(false), vcol_info(0), default_value(0), check_constraint(0), versioning(VERSIONING_NOT_SET), period(NULL) { interval_list.empty(); } Column_definition(THD *thd, Field *field, Field *orig_field); bool set_attributes(THD *thd, const Lex_field_type_st &attr, CHARSET_INFO *cs, column_definition_type_t type); void create_length_to_internal_length_null() { DBUG_ASSERT(length == 0); pack_length= 0; } void create_length_to_internal_length_simple() { pack_length= type_handler()->calc_pack_length((uint32) length); } void create_length_to_internal_length_string() { length*= charset->mbmaxlen; if (real_field_type() == MYSQL_TYPE_VARCHAR && compression_method()) length++; set_if_smaller(length, UINT_MAX32); pack_length= type_handler()->calc_pack_length((uint32) length); } void create_length_to_internal_length_typelib() { /* Pack_length already calculated in sql_parse.cc */ length*= charset->mbmaxlen; } bool vers_sys_field() const { return flags & (VERS_ROW_START | VERS_ROW_END); } void create_length_to_internal_length_bit(); void create_length_to_internal_length_newdecimal(); /* Prepare the "charset" member for string data types, such as CHAR, VARCHAR, TEXT, ENUM, SET: - derive the charset if not specified explicitly - find a _bin collation if the BINARY comparison style was specified, e.g.: CREATE TABLE t1 (a VARCHAR(10) BINARY) CHARSET utf8; */ bool prepare_charset_for_string(const Column_derived_attributes *dattr); /** Prepare a SET/ENUM field. Create "interval" from "interval_list" if needed, and adjust "length". @param mem_root - Memory root to allocate TYPELIB and its values on @param reuse_interval_list_values - determines if TYPELIB can reuse value buffers from interval_list, or should always allocate a copy on mem_root, even if character set conversion is not needed */ bool prepare_interval_field(MEM_ROOT *mem_root, bool reuse_interval_list_values); void prepare_interval_field_calc_length() { uint32 field_length, dummy; if (real_field_type() == MYSQL_TYPE_SET) { calculate_interval_lengths(&dummy, &field_length); length= field_length + (interval->count - 1); } else /* MYSQL_TYPE_ENUM */ { calculate_interval_lengths(&field_length, &dummy); length= field_length; } set_if_smaller(length, MAX_FIELD_WIDTH - 1); } bool prepare_blob_field(THD *thd); bool sp_prepare_create_field(THD *thd, MEM_ROOT *mem_root); bool prepare_stage1(THD *thd, MEM_ROOT *mem_root, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr); void prepare_stage1_simple(CHARSET_INFO *cs) { charset= cs; create_length_to_internal_length_simple(); } bool prepare_stage1_typelib(THD *thd, MEM_ROOT *mem_root, handler *file, ulonglong table_flags); bool prepare_stage1_string(THD *thd, MEM_ROOT *mem_root, handler *file, ulonglong table_flags); bool prepare_stage1_bit(THD *thd, MEM_ROOT *mem_root, handler *file, ulonglong table_flags); bool bulk_alter(const Column_derived_attributes *derived_attr, const Column_bulk_alter_attributes *bulk_attr) { return type_handler()->Column_definition_bulk_alter(this, derived_attr, bulk_attr); } void redefine_stage1_common(const Column_definition *dup_field, const handler *file); bool redefine_stage1(const Column_definition *dup_field, const handler *file) { const Type_handler *handler= dup_field->type_handler(); return handler->Column_definition_redefine_stage1(this, dup_field, file); } bool prepare_stage2(handler *handler, ulonglong table_flags); bool prepare_stage2_blob(handler *handler, ulonglong table_flags, uint field_flags); bool prepare_stage2_varchar(ulonglong table_flags); bool prepare_stage2_typelib(const char *type_name, uint field_flags, uint *dup_val_count); uint pack_flag_numeric() const; uint sign_length() const { return flags & UNSIGNED_FLAG ? 0 : 1; } bool check_length(uint mysql_errno, uint max_allowed_length) const; bool fix_attributes_real(uint default_length); bool fix_attributes_int(uint default_length); bool fix_attributes_decimal(); bool fix_attributes_temporal_with_time(uint int_part_length); bool fix_attributes_bit(); bool check(THD *thd); bool validate_check_constraint(THD *thd); bool stored_in_db() const { return !vcol_info || vcol_info->stored_in_db; } ha_storage_media field_storage_type() const { return (ha_storage_media) ((flags >> FIELD_FLAGS_STORAGE_MEDIA) & 3); } column_format_type column_format() const { return (column_format_type) ((flags >> FIELD_FLAGS_COLUMN_FORMAT) & 3); } bool has_default_function() const { return unireg_check != Field::NONE; } Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root, const Record_addr *addr, const LEX_CSTRING *field_name_arg) const { return Column_definition_attributes::make_field(share, mem_root, addr, type_handler(), field_name_arg, flags); } Field *make_field(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *field_name_arg) const { Record_addr addr(true); return make_field(share, mem_root, &addr, field_name_arg); } /* Return true if default is an expression that must be saved explicitly */ bool has_default_expression(); bool has_default_now_unireg_check() const { return unireg_check == Field::TIMESTAMP_DN_FIELD || unireg_check == Field::TIMESTAMP_DNUN_FIELD; } void set_type(const Column_definition &other) { set_handler(other.type_handler()); length= other.length; char_length= other.char_length; decimals= other.decimals; flags= other.flags; pack_length= other.pack_length; unireg_check= other.unireg_check; interval= other.interval; charset= other.charset; srid= other.srid; pack_flag= other.pack_flag; } // Replace the entire value by another definition void set_column_definition(const Column_definition *def) { *this= *def; } bool set_compressed(const char *method); bool set_compressed_deprecated(THD *thd, const char *method); bool set_compressed_deprecated_column_attribute(THD *thd, const char *pos, const char *method); void set_compression_method(Compression_method *compression_method_arg) { compression_method_ptr= compression_method_arg; } Compression_method *compression_method() const { return compression_method_ptr; } bool check_vcol_for_key(THD *thd) const; }; /** List of ROW element definitions, e.g.: DECLARE a ROW(a INT,b VARCHAR(10)) */ class Row_definition_list: public List { public: inline bool eq_name(const Spvar_definition *def, const LEX_CSTRING *name) const; /** Find a ROW field by name. @param [IN] name - the name @param [OUT] offset - if the ROW field found, its offset it returned here @retval NULL - the ROW field was not found @retval !NULL - the pointer to the found ROW field */ Spvar_definition *find_row_field_by_name(const LEX_CSTRING *name, uint *offset) const { // Cast-off the "const" qualifier List_iterator it(*((List*)this)); Spvar_definition *def; for (*offset= 0; (def= it++); (*offset)++) { if (eq_name(def, name)) return def; } return 0; } static Row_definition_list *make(MEM_ROOT *mem_root, Spvar_definition *var) { Row_definition_list *list; if (!(list= new (mem_root) Row_definition_list())) return NULL; return list->push_back(var, mem_root) ? NULL : list; } bool append_uniq(MEM_ROOT *thd, Spvar_definition *var); bool adjust_formal_params_to_actual_params(THD *thd, List *args); bool adjust_formal_params_to_actual_params(THD *thd, Item **args, uint arg_count); bool resolve_type_refs(THD *); }; /** This class is used during a stored routine or a trigger execution, at sp_rcontext::create() time. Currently it can represent: - variables with explicit data types: DECLARE a INT; - variables with data type references: DECLARE a t1.a%TYPE; - ROW type variables Notes: - Scalar variables have m_field_definitions==NULL. - ROW variables are defined as having MYSQL_TYPE_NULL, with a non-empty m_field_definitions. Data type references to other object types will be added soon, e.g.: - DECLARE a table_name%ROWTYPE; - DECLARE a cursor_name%ROWTYPE; - DECLARE a record_name%TYPE; - DECLARE a variable_name%TYPE; */ class Spvar_definition: public Column_definition { Qualified_column_ident *m_column_type_ref; // for %TYPE Table_ident *m_table_rowtype_ref; // for table%ROWTYPE bool m_cursor_rowtype_ref; // for cursor%ROWTYPE uint m_cursor_rowtype_offset; // for cursor%ROWTYPE Row_definition_list *m_row_field_definitions; // for ROW public: Spvar_definition() :m_column_type_ref(NULL), m_table_rowtype_ref(NULL), m_cursor_rowtype_ref(false), m_cursor_rowtype_offset(0), m_row_field_definitions(NULL) { } Spvar_definition(THD *thd, Field *field) :Column_definition(thd, field, NULL), m_column_type_ref(NULL), m_table_rowtype_ref(NULL), m_cursor_rowtype_ref(false), m_cursor_rowtype_offset(0), m_row_field_definitions(NULL) { } const Type_handler *type_handler() const { return Type_handler_hybrid_field_type::type_handler(); } bool is_column_type_ref() const { return m_column_type_ref != 0; } bool is_table_rowtype_ref() const { return m_table_rowtype_ref != 0; } bool is_cursor_rowtype_ref() const { return m_cursor_rowtype_ref; } bool is_explicit_data_type() const { return !is_column_type_ref() && !is_table_rowtype_ref() && !is_cursor_rowtype_ref(); } Qualified_column_ident *column_type_ref() const { return m_column_type_ref; } void set_column_type_ref(Qualified_column_ident *ref) { m_column_type_ref= ref; } Table_ident *table_rowtype_ref() const { return m_table_rowtype_ref; } void set_table_rowtype_ref(Table_ident *ref) { DBUG_ASSERT(ref); set_handler(&type_handler_row); m_table_rowtype_ref= ref; } uint cursor_rowtype_offset() const { return m_cursor_rowtype_offset; } void set_cursor_rowtype_ref(uint offset) { set_handler(&type_handler_row); m_cursor_rowtype_ref= true; m_cursor_rowtype_offset= offset; } /* Find a ROW field by name. See Row_field_list::find_row_field_by_name() for details. */ Spvar_definition *find_row_field_by_name(const LEX_CSTRING *name, uint *offset) const { DBUG_ASSERT(m_row_field_definitions); return m_row_field_definitions->find_row_field_by_name(name, offset); } uint is_row() const { return m_row_field_definitions != NULL; } // Check if "this" defines a ROW variable with n elements uint is_row(uint n) const { return m_row_field_definitions != NULL && m_row_field_definitions->elements == n; } Row_definition_list *row_field_definitions() const { return m_row_field_definitions; } void set_row_field_definitions(Row_definition_list *list) { DBUG_ASSERT(list); set_handler(&type_handler_row); m_row_field_definitions= list; } }; inline bool Row_definition_list::eq_name(const Spvar_definition *def, const LEX_CSTRING *name) const { return def->field_name.length == name->length && my_strcasecmp(system_charset_info, def->field_name.str, name->str) == 0; } class Create_field :public Column_definition { public: LEX_CSTRING change; // Old column name if column is renamed by ALTER LEX_CSTRING after; // Put column after this one Field *field; // For alter table const TYPELIB *save_interval; // Temporary copy for the above // Used only for UCS2 intervals /** structure with parsed options (for comparing fields in ALTER TABLE) */ ha_field_option_struct *option_struct; uint offset; uint8 interval_id; bool create_if_not_exists; // Used in ALTER TABLE IF NOT EXISTS Create_field(): Column_definition(), field(0), option_struct(NULL), create_if_not_exists(false) { change= after= null_clex_str; } Create_field(THD *thd, Field *old_field, Field *orig_field): Column_definition(thd, old_field, orig_field), change(old_field->field_name), field(old_field), option_struct(old_field->option_struct), create_if_not_exists(false) { after= null_clex_str; } /* Used to make a clone of this object for ALTER/CREATE TABLE */ Create_field *clone(MEM_ROOT *mem_root) const; static void upgrade_data_types(List &list) { List_iterator it(list); while (Create_field *f= it++) f->type_handler()->Column_definition_implicit_upgrade(f); } }; /* A class for sending info to the client */ class Send_field :public Sql_alloc, public Type_handler_hybrid_field_type, public Send_field_extended_metadata { public: LEX_CSTRING db_name; LEX_CSTRING table_name, org_table_name; LEX_CSTRING col_name, org_col_name; ulong length; uint flags; decimal_digits_t decimals; Send_field(Field *field) { field->make_send_field(this); DBUG_ASSERT(table_name.str != 0); normalize(); } Send_field(THD *thd, Item *item); Send_field(Field *field, const LEX_CSTRING &db_name_arg, const LEX_CSTRING &table_name_arg) :Type_handler_hybrid_field_type(field->type_handler()), db_name(db_name_arg), table_name(table_name_arg), org_table_name(table_name_arg), col_name(field->field_name), org_col_name(field->field_name), length(field->field_length), flags(field->table->maybe_null ? (field->flags & ~NOT_NULL_FLAG) : field->flags), decimals(field->decimals()) { normalize(); } private: void normalize() { /* limit number of decimals for float and double */ if (type_handler()->field_type() == MYSQL_TYPE_FLOAT || type_handler()->field_type() == MYSQL_TYPE_DOUBLE) set_if_smaller(decimals, FLOATING_POINT_DECIMALS); } public: // This should move to Type_handler eventually uint32 max_char_length(CHARSET_INFO *cs) const { return type_handler()->field_type() >= MYSQL_TYPE_TINY_BLOB && type_handler()->field_type() <= MYSQL_TYPE_BLOB ? static_cast(length / cs->mbminlen) : static_cast(length / cs->mbmaxlen); } uint32 max_octet_length(CHARSET_INFO *from, CHARSET_INFO *to) const { /* For TEXT/BLOB columns, field_length describes the maximum data length in bytes. There is no limit to the number of characters that a TEXT column can store, as long as the data fits into the designated space. For the rest of textual columns, field_length is evaluated as char_count * mbmaxlen, where character count is taken from the definition of the column. In other words, the maximum number of characters here is limited by the column definition. When one has a LONG TEXT column with a single-byte character set, and the connection character set is multi-byte, the client may get fields longer than UINT_MAX32, due to -> conversion. In that case column max length would not fit into the 4 bytes reserved for it in the protocol. So we cut it here to UINT_MAX32. */ return char_to_byte_length_safe(max_char_length(from), to->mbmaxlen); } // This should move to Type_handler eventually bool is_sane_float() const { return (decimals <= FLOATING_POINT_DECIMALS || (type_handler()->field_type() != MYSQL_TYPE_FLOAT && type_handler()->field_type() != MYSQL_TYPE_DOUBLE)); } bool is_sane_signess() const { if (type_handler() == type_handler()->type_handler_signed() && type_handler() == type_handler()->type_handler_unsigned()) return true; // Any signess is allowed, e.g. DOUBLE, DECIMAL /* We are here e.g. in case of INT data type. The UNSIGNED_FLAG bit must match in flags and in the type handler. */ return ((bool) (flags & UNSIGNED_FLAG)) == type_handler()->is_unsigned(); } bool is_sane() const { return is_sane_float() && is_sane_signess(); } }; /* A class for quick copying data to fields */ class Copy_field :public Sql_alloc { public: uchar *from_ptr,*to_ptr; uchar *from_null_ptr,*to_null_ptr; bool *null_row; uint from_bit,to_bit; /** Number of bytes in the fields pointed to by 'from_ptr' and 'to_ptr'. Usually this is the number of bytes that are copied from 'from_ptr' to 'to_ptr'. For variable-length fields (VARCHAR), the first byte(s) describe the actual length of the text. For VARCHARs with length < 256 there is 1 length byte >= 256 there is 2 length bytes Thus, if from_field is VARCHAR(10), from_length (and in most cases to_length) is 11. For VARCHAR(1024), the length is 1026. @see Field_varstring::length_bytes Note that for VARCHARs, do_copy() will be do_varstring*() which only copies the length-bytes (1 or 2) + the actual length of the text instead of from/to_length bytes. */ uint from_length,to_length; Field *from_field,*to_field; String tmp; // For items Copy_field() = default; ~Copy_field() = default; void set(Field *to,Field *from,bool save); // Field to field void set(uchar *to,Field *from); // Field to string void (*do_copy)(Copy_field *); void (*do_copy2)(Copy_field *); // Used to handle null values }; uint pack_length_to_packflag(uint type); enum_field_types get_blob_type_from_length(ulong length); int set_field_to_null(Field *field); int set_field_to_null_with_conversions(Field *field, bool no_conversions); int convert_null_to_field_value_or_error(Field *field, uint err); bool check_expression(Virtual_column_info *vcol, const LEX_CSTRING *name, enum_vcol_info_type type, Alter_info *alter_info= NULL); /* The following are for the interface with the .frm file */ #define FIELDFLAG_DECIMAL 1U #define FIELDFLAG_BINARY 1U // Shares same flag #define FIELDFLAG_NUMBER 2U #define FIELDFLAG_ZEROFILL 4U #define FIELDFLAG_PACK 120U // Bits used for packing #define FIELDFLAG_INTERVAL 256U // mangled with decimals! #define FIELDFLAG_BITFIELD 512U // mangled with decimals! #define FIELDFLAG_BLOB 1024U // mangled with decimals! #define FIELDFLAG_GEOM 2048U // mangled with decimals! #define FIELDFLAG_TREAT_BIT_AS_CHAR 4096U /* use Field_bit_as_char */ #define FIELDFLAG_LONG_DECIMAL 8192U #define FIELDFLAG_NO_DEFAULT 16384U /* sql */ #define FIELDFLAG_MAYBE_NULL 32768U // sql #define FIELDFLAG_HEX_ESCAPE 0x10000U #define FIELDFLAG_PACK_SHIFT 3 #define FIELDFLAG_DEC_SHIFT 8 #define FIELDFLAG_MAX_DEC 63U #define FIELDFLAG_DEC_MASK 0x3F00U #define MTYP_TYPENR(type) ((type) & 127U) // Remove bits from type #define f_is_dec(x) ((x) & FIELDFLAG_DECIMAL) #define f_is_num(x) ((x) & FIELDFLAG_NUMBER) #define f_is_zerofill(x) ((x) & FIELDFLAG_ZEROFILL) #define f_is_packed(x) ((x) & FIELDFLAG_PACK) #define f_packtype(x) (((x) >> FIELDFLAG_PACK_SHIFT) & 15) #define f_decimals(x) ((uint8) (((x) >> FIELDFLAG_DEC_SHIFT) & FIELDFLAG_MAX_DEC)) #define f_is_alpha(x) (!f_is_num(x)) #define f_is_binary(x) ((x) & FIELDFLAG_BINARY) // 4.0- compatibility #define f_is_enum(x) (((x) & (FIELDFLAG_INTERVAL | FIELDFLAG_NUMBER)) == FIELDFLAG_INTERVAL) #define f_is_bitfield(x) (((x) & (FIELDFLAG_BITFIELD | FIELDFLAG_NUMBER)) == FIELDFLAG_BITFIELD) #define f_is_blob(x) (((x) & (FIELDFLAG_BLOB | FIELDFLAG_NUMBER)) == FIELDFLAG_BLOB) #define f_is_geom(x) (((x) & (FIELDFLAG_GEOM | FIELDFLAG_NUMBER)) == FIELDFLAG_GEOM) #define f_settype(x) (((uint) (x)) << FIELDFLAG_PACK_SHIFT) #define f_maybe_null(x) ((x) & FIELDFLAG_MAYBE_NULL) #define f_no_default(x) ((x) & FIELDFLAG_NO_DEFAULT) #define f_bit_as_char(x) ((x) & FIELDFLAG_TREAT_BIT_AS_CHAR) #define f_is_hex_escape(x) ((x) & FIELDFLAG_HEX_ESCAPE) #define f_visibility(x) (static_cast ((x) & INVISIBLE_MAX_BITS)) inline ulonglong TABLE::vers_end_id() const { DBUG_ASSERT(versioned(VERS_TRX_ID)); return static_cast(vers_end_field()->val_int()); } inline ulonglong TABLE::vers_start_id() const { DBUG_ASSERT(versioned(VERS_TRX_ID)); return static_cast(vers_start_field()->val_int()); } #endif /* FIELD_INCLUDED */ mysql/server/private/rpl_tblmap.h000064400000006151151027430560013204 0ustar00/* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef TABLE_MAPPING_H #define TABLE_MAPPING_H /* Forward declarations */ #ifndef MYSQL_CLIENT struct TABLE; #else class Table_map_log_event; typedef Table_map_log_event TABLE; void free_table_map_log_event(TABLE *table); #endif /* CLASS table_mapping RESPONSIBILITIES The table mapping is used to map table id's to table pointers COLLABORATION RELAY_LOG For mapping table id:s to tables when receiving events. */ /* Guilhem to Mats: in the table_mapping class, the memory is allocated and never freed (until destruction). So this is a good candidate for allocating inside a MEM_ROOT: it gives the efficient allocation in chunks (like in expand()). So I have introduced a MEM_ROOT. Note that inheriting from Sql_alloc had no effect: it has effects only when "ptr= new table_mapping" is called, and this is never called. And it would then allocate from thd->mem_root which is a highly volatile object (reset from example after executing each query, see dispatch_command(), it has a free_root() at end); as the table_mapping object is supposed to live longer than a query, it was dangerous. A dedicated MEM_ROOT needs to be used, see below. */ #include "hash.h" /* HASH */ class table_mapping { private: MEM_ROOT m_mem_root; public: enum enum_error { ERR_NO_ERROR = 0, ERR_LIMIT_EXCEEDED, ERR_MEMORY_ALLOCATION }; table_mapping(); ~table_mapping(); TABLE* get_table(ulonglong table_id); int set_table(ulonglong table_id, TABLE* table); int remove_table(ulonglong table_id); void clear_tables(); ulong count() const { return m_table_ids.records; } private: /* This is a POD (Plain Old Data). Keep it that way (we apply offsetof() to it, which only works for PODs) */ struct entry { ulonglong table_id; union { TABLE *table; entry *next; }; }; entry *find_entry(ulonglong table_id) { return (entry *) my_hash_search(&m_table_ids, (uchar*)&table_id, sizeof(table_id)); } int expand(); /* Head of the list of free entries; "free" in the sense that it's an allocated entry free for use, NOT in the sense that it's freed memory. */ entry *m_free; /* Correspondance between an id (a number) and a TABLE object */ HASH m_table_ids; }; #endif mysql/server/private/sql_statistics.h000064400000030246151027430560014123 0ustar00/* Copyright 2006-2008 MySQL AB, 2008 Sun Microsystems, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_STATISTICS_H #define SQL_STATISTICS_H /* For COMPLEMENTARY_FOR_QUERIES and PREFERABLY_FOR_QUERIES they are similar to the COMPLEMENTARY and PREFERABLY respectively except that with these values we would not be collecting EITS for queries like ANALYZE TABLE t1; To collect EITS with these values, we have to use PERSISITENT FOR analyze table t1 persistent for columns (col1,col2...) index (idx1, idx2...) or analyze table t1 persistent for all */ typedef enum enum_use_stat_tables_mode { NEVER, COMPLEMENTARY, PREFERABLY, COMPLEMENTARY_FOR_QUERIES, PREFERABLY_FOR_QUERIES } Use_stat_tables_mode; typedef enum enum_histogram_type { SINGLE_PREC_HB, DOUBLE_PREC_HB } Histogram_type; enum enum_stat_tables { TABLE_STAT, COLUMN_STAT, INDEX_STAT, }; /* These enumeration types comprise the dictionary of three statistical tables table_stat, column_stat and index_stat as they defined in ../scripts/mysql_system_tables.sql. It would be nice if the declarations of these types were generated automatically by the table definitions. */ enum enum_table_stat_col { TABLE_STAT_DB_NAME, TABLE_STAT_TABLE_NAME, TABLE_STAT_CARDINALITY, TABLE_STAT_N_FIELDS }; enum enum_column_stat_col { COLUMN_STAT_DB_NAME, COLUMN_STAT_TABLE_NAME, COLUMN_STAT_COLUMN_NAME, COLUMN_STAT_MIN_VALUE, COLUMN_STAT_MAX_VALUE, COLUMN_STAT_NULLS_RATIO, COLUMN_STAT_AVG_LENGTH, COLUMN_STAT_AVG_FREQUENCY, COLUMN_STAT_HIST_SIZE, COLUMN_STAT_HIST_TYPE, COLUMN_STAT_HISTOGRAM, COLUMN_STAT_N_FIELDS }; enum enum_index_stat_col { INDEX_STAT_DB_NAME, INDEX_STAT_TABLE_NAME, INDEX_STAT_INDEX_NAME, INDEX_STAT_PREFIX_ARITY, INDEX_STAT_AVG_FREQUENCY, INDEX_STAT_N_FIELDS }; inline Use_stat_tables_mode get_use_stat_tables_mode(THD *thd) { return (Use_stat_tables_mode) (thd->variables.use_stat_tables); } inline bool check_eits_collection_allowed(THD *thd) { return (get_use_stat_tables_mode(thd) == COMPLEMENTARY || get_use_stat_tables_mode(thd) == PREFERABLY); } inline bool check_eits_preferred(THD *thd) { return (get_use_stat_tables_mode(thd) == PREFERABLY || get_use_stat_tables_mode(thd) == PREFERABLY_FOR_QUERIES); } int read_statistics_for_tables_if_needed(THD *thd, TABLE_LIST *tables); int read_statistics_for_tables(THD *thd, TABLE_LIST *tables, bool force_reload); int collect_statistics_for_table(THD *thd, TABLE *table); int alloc_statistics_for_table(THD *thd, TABLE *table, MY_BITMAP *stat_fields); int update_statistics_for_table(THD *thd, TABLE *table); int delete_statistics_for_table(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *tab); int delete_statistics_for_column(THD *thd, TABLE *tab, Field *col); int delete_statistics_for_index(THD *thd, TABLE *tab, KEY *key_info, bool ext_prefixes_only); int rename_table_in_stat_tables(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *tab, const LEX_CSTRING *new_db, const LEX_CSTRING *new_tab); int rename_columns_in_stat_table(THD *thd, TABLE *tab, List *fields); int rename_indexes_in_stat_table(THD *thd, TABLE *tab, List *indexes); void set_statistics_for_table(THD *thd, TABLE *table); double get_column_avg_frequency(Field * field); double get_column_range_cardinality(Field *field, key_range *min_endp, key_range *max_endp, uint range_flag); bool is_stat_table(const LEX_CSTRING *db, LEX_CSTRING *table); bool is_eits_usable(Field* field); class Histogram { private: Histogram_type type; uint8 size; /* Size of values array, in bytes */ uchar *values; uint prec_factor() { switch (type) { case SINGLE_PREC_HB: return ((uint) (1 << 8) - 1); case DOUBLE_PREC_HB: return ((uint) (1 << 16) - 1); } return 1; } public: uint get_width() { switch (type) { case SINGLE_PREC_HB: return size; case DOUBLE_PREC_HB: return size / 2; } return 0; } private: uint get_value(uint i) { DBUG_ASSERT(i < get_width()); switch (type) { case SINGLE_PREC_HB: return (uint) (((uint8 *) values)[i]); case DOUBLE_PREC_HB: return (uint) uint2korr(values + i * 2); } return 0; } /* Find the bucket which value 'pos' falls into. */ uint find_bucket(double pos, bool first) { uint val= (uint) (pos * prec_factor()); int lp= 0; int rp= get_width() - 1; int d= get_width() / 2; uint i= lp + d; for ( ; d; d= (rp - lp) / 2, i= lp + d) { if (val == get_value(i)) break; if (val < get_value(i)) rp= i; else if (val > get_value(i + 1)) lp= i + 1; else break; } if (val > get_value(i) && i < (get_width() - 1)) i++; if (val == get_value(i)) { if (first) { while(i && val == get_value(i - 1)) i--; } else { while(i + 1 < get_width() && val == get_value(i + 1)) i++; } } return i; } public: uint get_size() { return (uint) size; } Histogram_type get_type() { return type; } uchar *get_values() { return (uchar *) values; } void set_size (ulonglong sz) { size= (uint8) sz; } void set_type (Histogram_type t) { type= t; } void set_values (uchar *vals) { values= (uchar *) vals; } bool is_available() { return get_size() > 0 && get_values(); } /* This function checks that histograms should be usable only when 1) the level of optimizer_use_condition_selectivity > 3 2) histograms have been collected */ bool is_usable(THD *thd) { return thd->variables.optimizer_use_condition_selectivity > 3 && is_available(); } void set_value(uint i, double val) { switch (type) { case SINGLE_PREC_HB: ((uint8 *) values)[i]= (uint8) (val * prec_factor()); return; case DOUBLE_PREC_HB: int2store(values + i * 2, val * prec_factor()); return; } } void set_prev_value(uint i) { switch (type) { case SINGLE_PREC_HB: ((uint8 *) values)[i]= ((uint8 *) values)[i-1]; return; case DOUBLE_PREC_HB: int2store(values + i * 2, uint2korr(values + i * 2 - 2)); return; } } double range_selectivity(double min_pos, double max_pos) { double sel; double bucket_sel= 1.0/(get_width() + 1); uint min= find_bucket(min_pos, TRUE); uint max= find_bucket(max_pos, FALSE); sel= bucket_sel * (max - min + 1); return sel; } /* Estimate selectivity of "col=const" using a histogram */ double point_selectivity(double pos, double avg_sel); }; class Columns_statistics; class Index_statistics; /* Statistical data on a table */ class Table_statistics { public: my_bool cardinality_is_null; /* TRUE if the cardinality is unknown */ ha_rows cardinality; /* Number of rows in the table */ uchar *min_max_record_buffers; /* Record buffers for min/max values */ Column_statistics *column_stats; /* Array of statistical data for columns */ Index_statistics *index_stats; /* Array of statistical data for indexes */ /* Array of records per key for index prefixes */ ulonglong *idx_avg_frequency; uchar *histograms; /* Sequence of histograms */ }; /* Statistical data on a column Note: objects of this class may be "empty", where they have almost all fields as zeros, for example, get_avg_frequency() will return 0. objects are allocated in alloc_statistics_for_table[_share]. */ class Column_statistics { private: static const uint Scale_factor_nulls_ratio= 100000; static const uint Scale_factor_avg_length= 100000; static const uint Scale_factor_avg_frequency= 100000; public: /* Bitmap indicating what statistical characteristics are available for the column */ uint32 column_stat_nulls; /* For the below two, see comments in get_column_range_cardinality() */ /* Minimum value for the column */ Field *min_value; /* Maximum value for the column */ Field *max_value; private: /* The ratio Z/N multiplied by the scale factor Scale_factor_nulls_ratio, where N is the total number of rows, Z is the number of nulls in the column */ ulong nulls_ratio; /* Average number of bytes occupied by the representation of a value of the column in memory buffers such as join buffer multiplied by the scale factor Scale_factor_avg_length. CHAR values are stripped of trailing spaces. Flexible values are stripped of their length prefixes. */ ulonglong avg_length; /* The ratio N/D multiplied by the scale factor Scale_factor_avg_frequency, where N is the number of rows with not null value in the column, D the number of distinct values among them */ ulonglong avg_frequency; public: Histogram histogram; uint32 no_values_provided_bitmap() { return ((1 << (COLUMN_STAT_HISTOGRAM-COLUMN_STAT_COLUMN_NAME))-1) << (COLUMN_STAT_COLUMN_NAME+1); } void set_all_nulls() { column_stat_nulls= no_values_provided_bitmap(); } void set_not_null(uint stat_field_no) { column_stat_nulls&= ~(1 << stat_field_no); } bool is_null(uint stat_field_no) { return MY_TEST(column_stat_nulls & (1 << stat_field_no)); } double get_nulls_ratio() { return (double) nulls_ratio / Scale_factor_nulls_ratio; } double get_avg_length() { return (double) avg_length / Scale_factor_avg_length; } double get_avg_frequency() { return (double) avg_frequency / Scale_factor_avg_frequency; } void set_nulls_ratio (double val) { nulls_ratio= (ulong) (val * Scale_factor_nulls_ratio); } void set_avg_length (double val) { avg_length= (ulonglong) (val * Scale_factor_avg_length); } void set_avg_frequency (double val) { avg_frequency= (ulonglong) (val * Scale_factor_avg_frequency); } bool min_max_values_are_provided() { return !is_null(COLUMN_STAT_MIN_VALUE) && !is_null(COLUMN_STAT_MAX_VALUE); } /* This function checks whether the values for the fields of the statistical tables that were NULL by DEFAULT for a column have changed or not. @retval TRUE: Statistics are not present for a column FALSE: Statisitics are present for a column */ bool no_stat_values_provided() { return (column_stat_nulls == no_values_provided_bitmap()); } }; /* Statistical data on an index prefixes */ class Index_statistics { private: static const uint Scale_factor_avg_frequency= 100000; /* The k-th element of this array contains the ratio N/D multiplied by the scale factor Scale_factor_avg_frequency, where N is the number of index entries without nulls in the first k components, and D is the number of distinct k-component prefixes among them */ ulonglong *avg_frequency; public: void init_avg_frequency(ulonglong *ptr) { avg_frequency= ptr; } bool avg_frequency_is_inited() { return avg_frequency != NULL; } double get_avg_frequency(uint i) const { return (double) avg_frequency[i] / Scale_factor_avg_frequency; } void set_avg_frequency(uint i, double val) { avg_frequency[i]= (ulonglong) (val * Scale_factor_avg_frequency); } }; #endif /* SQL_STATISTICS_H */ mysql/server/private/my_compare.h000064400000025672151027430560013214 0ustar00/* Copyright (c) 2011, Oracle and/or its affiliates. Copyright (c) 1991, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_compare_h #define _my_compare_h #include "myisampack.h" #ifdef __cplusplus extern "C" { #endif #include "m_ctype.h" /* CHARSET_INFO */ /* There is a hard limit for the maximum number of keys as there are only 8 bits in the index file header for the number of keys in a table. This means that 0..255 keys can exist for a table. The idea of HA_MAX_POSSIBLE_KEY is to ensure that one can use myisamchk & tools on a MyISAM table for which one has more keys than MyISAM is normally compiled for. If you don't have this, you will get a core dump when running myisamchk compiled for 128 keys on a table with 255 keys. */ #define HA_MAX_POSSIBLE_KEY 255 /* For myisamchk */ /* The following defines can be increased if necessary. But beware the dependency of MI_MAX_POSSIBLE_KEY_BUFF and HA_MAX_KEY_LENGTH. */ #define HA_MAX_KEY_LENGTH 1000 /* Max length in bytes */ #define HA_MAX_KEY_SEG 32 /* Max segments for key */ #define HA_MAX_POSSIBLE_KEY_BUFF (HA_MAX_KEY_LENGTH + 24+ 6+6) #define HA_MAX_KEY_BUFF (HA_MAX_KEY_LENGTH+HA_MAX_KEY_SEG*6+8+8) typedef struct st_HA_KEYSEG /* Key-portion */ { CHARSET_INFO *charset; uint32 start; /* Start of key in record */ uint32 null_pos; /* position to NULL indicator */ uint16 bit_pos; /* Position to bit part */ uint16 flag; uint16 length; /* Keylength */ uint16 language; uint8 type; /* Type of key (for sort) */ uint8 null_bit; /* bitmask to test for NULL */ uint8 bit_start; uint8 bit_length; /* Length of bit part */ } HA_KEYSEG; #define get_key_length(length,key) \ { if (*(const uchar*) (key) != 255) \ length= (uint) *(const uchar*) ((key)++); \ else \ { length= mi_uint2korr((key)+1); (key)+=3; } \ } #define get_key_length_rdonly(length,key) \ { if (*(const uchar*) (key) != 255) \ length= ((uint) *(const uchar*) ((key))); \ else \ { length= mi_uint2korr((key)+1); } \ } #define get_key_pack_length(length,length_pack,key) \ { if (*(const uchar*) (key) != 255) \ { length= (uint) *(const uchar*) ((key)++); length_pack= 1; }\ else \ { length=mi_uint2korr((key)+1); (key)+= 3; length_pack= 3; } \ } #define store_key_length_inc(key,length) \ { if ((length) < 255) \ { *(key)++= (uchar)(length); } \ else \ { *(key)=255; mi_int2store((key)+1,(length)); (key)+=3; } \ } #define size_to_store_key_length(length) ((length) < 255 ? 1 : 3) static inline uchar get_rec_bits(const uchar *ptr, uchar ofs, uint len) { uint16 val= ptr[0]; if (ofs + len > 8) val|= (uint16)(((uint) ptr[1]) << 8); return (uchar) ((val >> ofs) & ((1 << len) - 1)); } static inline void set_rec_bits(uint16 bits, uchar *ptr, uchar ofs, uint len) { ptr[0]= (uchar) ((ptr[0] & ~(((1 << len) - 1) << ofs)) | (bits << ofs)); if (ofs + len > 8) ptr[1]= (uchar) ((ptr[1] & ~((1 << (len - 8 + ofs)) - 1)) | bits >> (8 - ofs)); } #define clr_rec_bits(bit_ptr, bit_ofs, bit_len) \ set_rec_bits(0, bit_ptr, bit_ofs, bit_len) /* Compare two VARCHAR values. @param charset_info - The character set and collation @param a - The pointer to the first string @param a_length - The length of the first string @param b - The pointer to the second string @param b_length - The length of the second string @param b_is_prefix - Whether "b" is a prefix of "a", e.g. in a prefix key (partial length key). @returns - The result of comparison - If "b_is_prefix" is FALSE, then the two strings are compared taking into account the PAD SPACE/NO PAD attribute of the collation. - If "b_is_prefix" is TRUE, then trailing spaces are compared in NO PAD style. This is done e.g. when we compare a column value to its prefix key value (the value of "a" to the value of "key_a"): CREATE TABLE t1 (a VARCHAR(10), KEY(key_a(5)); */ static inline int ha_compare_char_varying(CHARSET_INFO *charset_info, const uchar *a, size_t a_length, const uchar *b, size_t b_length, my_bool b_is_prefix) { if (!b_is_prefix) return charset_info->coll->strnncollsp(charset_info, a, a_length, b, b_length); return charset_info->coll->strnncoll(charset_info, a, a_length, b, b_length, TRUE/*prefix*/); } /* Compare two CHAR values of the same declared character length, e.g. CHAR(5) to CHAR(5). @param charset_info - The character set and collation @param a - The pointer to the first string @param a_length - The length of the first string @param b - The pointer to the second string @param b_length - The length of the second string @param nchars - The declared length (in characters) @param b_is_prefix - Whether "b" is a prefix of "a", e.g. in a prefix key (partial length key). @returns - The result of comparison - If "b_is_prefix" is FALSE, then the two strings are compared taking into account the PAD SPACE/NO PAD attribute of the collation. Additionally, this function assumes that the underlying storage could optionally apply trailing space compression, so values can come into this comparison function in different states: - all trailing spaces removed - some trailing spaced removed - no trailing spaces removed (exactly "nchars" characters on the two sides) This function virtually reconstructs trailing spaces up to the defined length specified in "nchars". If either of the sides have more than "nchar" characters, then only leftmost "nchar" characters are compared. - If "b_is_prefix" is TRUE, then trailing spaces are compared in NO PAD style. This is done e.g. when we compare a column value to its prefix key value (the value of "a" to the value of "key_a"): CREATE TABLE t1 (a CHAR(10), KEY(key_a(5)); */ static inline int ha_compare_char_fixed(CHARSET_INFO *charset_info, const uchar *a, size_t a_length, const uchar *b, size_t b_length, size_t nchars, my_bool b_is_prefix) { if (!b_is_prefix) return charset_info->coll->strnncollsp_nchars(charset_info, a, a_length, b, b_length, nchars, MY_STRNNCOLLSP_NCHARS_EMULATE_TRIMMED_TRAILING_SPACES); return charset_info->coll->strnncoll(charset_info, a, a_length, b, b_length, TRUE/*prefix*/); } /* A function to compare words of a text. This is a common operation in full-text search: SELECT MATCH (title) AGAINST ('word') FROM t1; */ static inline int ha_compare_word(CHARSET_INFO *charset_info, const uchar *a, size_t a_length, const uchar *b, size_t b_length) { return charset_info->coll->strnncollsp(charset_info, a, a_length, b, b_length); } /* A function to compare a word of a text to a word prefix. This is a common operation in full-text search: SELECT MATCH (title) AGAINST ('wor*' IN BOOLEAN MODE) FROM t1; */ static inline int ha_compare_word_prefix(CHARSET_INFO *charset_info, const uchar *a, size_t a_length, const uchar *b, size_t b_length) { return charset_info->coll->strnncoll(charset_info, a, a_length, b, b_length, TRUE/*b_is_prefix*/); } /* Compare words (full match or prefix match), e.g. for full-text search. */ static inline int ha_compare_word_or_prefix(CHARSET_INFO *charset_info, const uchar *a, size_t a_length, const uchar *b, size_t b_length, my_bool b_is_prefix) { if (!b_is_prefix) return ha_compare_word(charset_info, a, a_length, b, b_length); return ha_compare_word_prefix(charset_info, a, a_length, b, b_length); } extern int ha_key_cmp(HA_KEYSEG *keyseg, const uchar *a, const uchar *b, uint key_length, uint nextflag, uint *diff_pos); extern HA_KEYSEG *ha_find_null(HA_KEYSEG *keyseg, const uchar *a); /* Inside an in-memory data record, memory pointers to pieces of the record (like BLOBs) are stored in their native byte order and in this amount of bytes. */ #define portable_sizeof_char_ptr 8 #ifdef __cplusplus } #endif /** Return values for pushed index condition or rowid filter check functions. 0=CHECK_NEG - The filter is not satisfied. The engine should discard this index tuple and continue the scan. 1=CHECK_POS - The filter is satisfied. Current index tuple should be returned to the SQL layer. 2=CHECK_OUT_OF_RANGE - the index tuple is outside of the range that we're scanning. (Example: if we're scanning "t.key BETWEEN 10 AND 20" and got a "t.key=21" tuple) Tthe engine should stop scanning and return HA_ERR_END_OF_FILE right away). 3=CHECK_ABORTED_BY_USER - the engine must stop scanning and should return HA_ERR_ABORTED_BY_USER right away -1=CHECK_ERROR - Reserved for internal errors in engines. Should not be returned by ICP or rowid filter check functions. */ typedef enum check_result { CHECK_ERROR=-1, CHECK_NEG=0, CHECK_POS=1, CHECK_OUT_OF_RANGE=2, CHECK_ABORTED_BY_USER=3 } check_result_t; typedef check_result_t (*index_cond_func_t)(void *param); typedef check_result_t (*rowid_filter_func_t)(void *param); typedef int (*rowid_filter_is_active_func_t)(void *param); #endif /* _my_compare_h */ mysql/server/private/sql_crypt.h000064400000002635151027430560013073 0ustar00#ifndef SQL_CRYPT_INCLUDED #define SQL_CRYPT_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_alloc.h" /* Sql_alloc */ #include "my_rnd.h" /* rand_struct */ class SQL_CRYPT :public Sql_alloc { struct my_rnd_struct rand,org_rand; char decode_buff[256],encode_buff[256]; uint shift; public: SQL_CRYPT() = default; SQL_CRYPT(ulong *seed) { init(seed); } ~SQL_CRYPT() = default; void init(ulong *seed); void reinit() { shift=0; rand=org_rand; } void encode(char *str, uint length); void decode(char *str, uint length); }; #endif /* SQL_CRYPT_INCLUDED */ mysql/server/private/sp_cache.h000064400000003775151027430560012626 0ustar00/* -*- C++ -*- */ /* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _SP_CACHE_H_ #define _SP_CACHE_H_ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif /* Stored procedures/functions cache. This is used as follows: * Each thread has its own cache. * Each sp_head object is put into its thread cache before it is used, and then remains in the cache until deleted. */ class sp_head; class sp_cache; class Database_qualified_name; /* Cache usage scenarios: 1. Application-wide init: sp_cache_init(); 2. SP execution in thread: 2.1 While holding sp_head* pointers: // look up a routine in the cache (no checks if it is up to date or not) sp_cache_lookup(); sp_cache_insert(); sp_cache_invalidate(); 2.2 When not holding any sp_head* pointers: sp_cache_flush_obsolete(); 3. Before thread exit: sp_cache_clear(); */ void sp_cache_init(); void sp_cache_end(); void sp_cache_clear(sp_cache **cp); void sp_cache_insert(sp_cache **cp, sp_head *sp); sp_head *sp_cache_lookup(sp_cache **cp, const Database_qualified_name *name); void sp_cache_invalidate(); void sp_cache_flush_obsolete(sp_cache **cp, sp_head **sp); ulong sp_cache_version(); void sp_cache_enforce_limit(sp_cache *cp, ulong upper_limit_for_elements); #endif /* _SP_CACHE_H_ */ mysql/server/private/privilege.h000064400000067742151027430560013053 0ustar00#ifndef PRIVILEGE_H_INCLUDED #define PRIVILEGE_H_INCLUDED /* Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "my_global.h" // ulonglong /* A strict enum to store privilege bits. We should eventually make if even stricter using "enum class privilege_t" and: - Replace all code pieces like `if (priv)` to `if (priv != NO_ACL)` - Remove "delete" comparison operators below */ enum privilege_t: unsigned long long { NO_ACL = (0), SELECT_ACL = (1UL << 0), INSERT_ACL = (1UL << 1), UPDATE_ACL = (1UL << 2), DELETE_ACL = (1UL << 3), CREATE_ACL = (1UL << 4), DROP_ACL = (1UL << 5), RELOAD_ACL = (1UL << 6), SHUTDOWN_ACL = (1UL << 7), PROCESS_ACL = (1UL << 8), FILE_ACL = (1UL << 9), GRANT_ACL = (1UL << 10), REFERENCES_ACL = (1UL << 11), INDEX_ACL = (1UL << 12), ALTER_ACL = (1UL << 13), SHOW_DB_ACL = (1UL << 14), SUPER_ACL = (1UL << 15), CREATE_TMP_ACL = (1UL << 16), LOCK_TABLES_ACL = (1UL << 17), EXECUTE_ACL = (1UL << 18), REPL_SLAVE_ACL = (1UL << 19), BINLOG_MONITOR_ACL = (1UL << 20), // Was REPL_CLIENT_ACL prior to 10.5.2 CREATE_VIEW_ACL = (1UL << 21), SHOW_VIEW_ACL = (1UL << 22), CREATE_PROC_ACL = (1UL << 23), ALTER_PROC_ACL = (1UL << 24), CREATE_USER_ACL = (1UL << 25), EVENT_ACL = (1UL << 26), TRIGGER_ACL = (1UL << 27), CREATE_TABLESPACE_ACL = (1UL << 28), DELETE_HISTORY_ACL = (1UL << 29), // Added in 10.3.4 SET_USER_ACL = (1UL << 30), // Added in 10.5.2 FEDERATED_ADMIN_ACL = (1UL << 31), // Added in 10.5.2 CONNECTION_ADMIN_ACL = (1ULL << 32), // Added in 10.5.2 READ_ONLY_ADMIN_ACL = (1ULL << 33), // Added in 10.5.2 REPL_SLAVE_ADMIN_ACL = (1ULL << 34), // Added in 10.5.2 REPL_MASTER_ADMIN_ACL = (1ULL << 35), // Added in 10.5.2 BINLOG_ADMIN_ACL = (1ULL << 36), // Added in 10.5.2 BINLOG_REPLAY_ACL = (1ULL << 37), // Added in 10.5.2 SLAVE_MONITOR_ACL = (1ULL << 38) // Added in 10.5.8 /* When adding new privilege bits, don't forget to update: In this file: - Add a new LAST_version_ACL - Add a new ALL_KNOWN_ACL_version - Change ALL_KNOWN_ACL to ALL_KNOWN_ACL_version - Change GLOBAL_ACLS if needed - Change SUPER_ADDED_SINCE_USER_TABLE_ACL if needed In other files: - static struct show_privileges_st sys_privileges[] - static const char *command_array[] and static uint command_lengths[] - mysql_system_tables.sql and mysql_system_tables_fix.sql - acl_init() or whatever - to define behaviour for old privilege tables - Update User_table_json::get_access() - sql_yacc.yy - for GRANT/REVOKE to work Important: the enum should contain only single-bit values. In this case, debuggers print bit combinations in the readable form: (gdb) p (privilege_t) (15) $8 = (SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL) Bit-OR combinations of the above values should be declared outside! */ }; constexpr static inline privilege_t ALL_KNOWN_BITS(privilege_t x) { return (privilege_t)(x | (x-1)); } // Version markers constexpr privilege_t LAST_100304_ACL= DELETE_HISTORY_ACL; constexpr privilege_t LAST_100502_ACL= BINLOG_REPLAY_ACL; constexpr privilege_t LAST_100508_ACL= SLAVE_MONITOR_ACL; // Current version markers constexpr privilege_t LAST_CURRENT_ACL= LAST_100508_ACL; constexpr uint PRIVILEGE_T_MAX_BIT= my_bit_log2_uint64((ulonglong) LAST_CURRENT_ACL); static_assert((privilege_t)(1ULL << PRIVILEGE_T_MAX_BIT) == LAST_CURRENT_ACL, "Something went fatally badly: " "LAST_CURRENT_ACL and PRIVILEGE_T_MAX_BIT do not match"); // A combination of all bits defined in 10.3.4 (and earlier) constexpr privilege_t ALL_KNOWN_ACL_100304 = ALL_KNOWN_BITS(LAST_100304_ACL); // A combination of all bits defined in 10.5.2 constexpr privilege_t ALL_KNOWN_ACL_100502= ALL_KNOWN_BITS(LAST_100502_ACL); // A combination of all bits defined in 10.5.8 constexpr privilege_t ALL_KNOWN_ACL_100508= ALL_KNOWN_BITS(LAST_100508_ACL); // unfortunately, SLAVE_MONITOR_ACL was added in 10.5.9, but also in 10.5.8-5 // let's stay compatible with that branch too. constexpr privilege_t ALL_KNOWN_ACL_100509= ALL_KNOWN_ACL_100508; // A combination of all bits defined as of the current version constexpr privilege_t ALL_KNOWN_ACL= ALL_KNOWN_BITS(LAST_CURRENT_ACL); // Unary operators static inline constexpr ulonglong operator~(privilege_t access) { return ~static_cast(access); } /* Comparison operators. Delete automatic conversion between to/from integer types as much as possible. This forces to use `(priv == NO_ACL)` instead of `(priv == 0)`. Note: these operators will be gone when we change privilege_t to "enum class privilege_t". See comments above. */ static inline bool operator==(privilege_t, ulonglong)= delete; static inline bool operator==(privilege_t, ulong)= delete; static inline bool operator==(privilege_t, uint)= delete; static inline bool operator==(privilege_t, uchar)= delete; static inline bool operator==(privilege_t, longlong)= delete; static inline bool operator==(privilege_t, long)= delete; static inline bool operator==(privilege_t, int)= delete; static inline bool operator==(privilege_t, char)= delete; static inline bool operator==(privilege_t, bool)= delete; static inline bool operator==(ulonglong, privilege_t)= delete; static inline bool operator==(ulong, privilege_t)= delete; static inline bool operator==(uint, privilege_t)= delete; static inline bool operator==(uchar, privilege_t)= delete; static inline bool operator==(longlong, privilege_t)= delete; static inline bool operator==(long, privilege_t)= delete; static inline bool operator==(int, privilege_t)= delete; static inline bool operator==(char, privilege_t)= delete; static inline bool operator==(bool, privilege_t)= delete; static inline bool operator!=(privilege_t, ulonglong)= delete; static inline bool operator!=(privilege_t, ulong)= delete; static inline bool operator!=(privilege_t, uint)= delete; static inline bool operator!=(privilege_t, uchar)= delete; static inline bool operator!=(privilege_t, longlong)= delete; static inline bool operator!=(privilege_t, long)= delete; static inline bool operator!=(privilege_t, int)= delete; static inline bool operator!=(privilege_t, char)= delete; static inline bool operator!=(privilege_t, bool)= delete; static inline bool operator!=(ulonglong, privilege_t)= delete; static inline bool operator!=(ulong, privilege_t)= delete; static inline bool operator!=(uint, privilege_t)= delete; static inline bool operator!=(uchar, privilege_t)= delete; static inline bool operator!=(longlong, privilege_t)= delete; static inline bool operator!=(long, privilege_t)= delete; static inline bool operator!=(int, privilege_t)= delete; static inline bool operator!=(char, privilege_t)= delete; static inline bool operator!=(bool, privilege_t)= delete; // Dyadic bitwise operators static inline constexpr privilege_t operator&(privilege_t a, privilege_t b) { return static_cast(static_cast(a) & static_cast(b)); } static inline constexpr privilege_t operator&(ulonglong a, privilege_t b) { return static_cast(a & static_cast(b)); } static inline constexpr privilege_t operator&(privilege_t a, ulonglong b) { return static_cast(static_cast(a) & b); } static inline constexpr privilege_t operator|(privilege_t a, privilege_t b) { return static_cast(static_cast(a) | static_cast(b)); } // Dyadyc bitwise assignment operators static inline privilege_t& operator&=(privilege_t &a, privilege_t b) { return a= a & b; } static inline privilege_t& operator&=(privilege_t &a, ulonglong b) { return a= a & b; } static inline privilege_t& operator|=(privilege_t &a, privilege_t b) { return a= a | b; } /* A combination of all SUPER privileges added since the old user table format. These privileges are automatically added when upgrading from the old format mysql.user table if a user has the SUPER privilege. */ constexpr privilege_t GLOBAL_SUPER_ADDED_SINCE_USER_TABLE_ACLS= SET_USER_ACL | FEDERATED_ADMIN_ACL | CONNECTION_ADMIN_ACL | READ_ONLY_ADMIN_ACL | REPL_SLAVE_ADMIN_ACL | BINLOG_ADMIN_ACL | BINLOG_REPLAY_ACL; constexpr privilege_t COL_DML_ACLS= SELECT_ACL | INSERT_ACL | UPDATE_ACL | DELETE_ACL; constexpr privilege_t VIEW_ACLS= CREATE_VIEW_ACL | SHOW_VIEW_ACL; constexpr privilege_t STD_TABLE_DDL_ACLS= CREATE_ACL | DROP_ACL | ALTER_ACL; constexpr privilege_t ALL_TABLE_DDL_ACLS= STD_TABLE_DDL_ACLS | INDEX_ACL; constexpr privilege_t COL_ACLS= SELECT_ACL | INSERT_ACL | UPDATE_ACL | REFERENCES_ACL; constexpr privilege_t PROC_DDL_ACLS= CREATE_PROC_ACL | ALTER_PROC_ACL; constexpr privilege_t SHOW_PROC_ACLS= PROC_DDL_ACLS | EXECUTE_ACL; constexpr privilege_t TABLE_ACLS= COL_DML_ACLS | ALL_TABLE_DDL_ACLS | VIEW_ACLS | GRANT_ACL | REFERENCES_ACL | TRIGGER_ACL | DELETE_HISTORY_ACL; constexpr privilege_t DB_ACLS= TABLE_ACLS | PROC_DDL_ACLS | EXECUTE_ACL | CREATE_TMP_ACL | LOCK_TABLES_ACL | EVENT_ACL; constexpr privilege_t PROC_ACLS= ALTER_PROC_ACL | EXECUTE_ACL | GRANT_ACL; constexpr privilege_t GLOBAL_ACLS= DB_ACLS | SHOW_DB_ACL | CREATE_USER_ACL | CREATE_TABLESPACE_ACL | SUPER_ACL | RELOAD_ACL | SHUTDOWN_ACL | PROCESS_ACL | FILE_ACL | REPL_SLAVE_ACL | BINLOG_MONITOR_ACL | GLOBAL_SUPER_ADDED_SINCE_USER_TABLE_ACLS | REPL_MASTER_ADMIN_ACL | SLAVE_MONITOR_ACL; constexpr privilege_t DEFAULT_CREATE_PROC_ACLS= ALTER_PROC_ACL | EXECUTE_ACL; constexpr privilege_t SHOW_CREATE_TABLE_ACLS= COL_DML_ACLS | ALL_TABLE_DDL_ACLS | TRIGGER_ACL | REFERENCES_ACL | GRANT_ACL | VIEW_ACLS; /** Table-level privileges which are automatically "granted" to everyone on existing temporary tables (CREATE_ACL is necessary for ALTER ... RENAME). */ constexpr privilege_t TMP_TABLE_ACLS= COL_DML_ACLS | ALL_TABLE_DDL_ACLS | REFERENCES_ACL; constexpr privilege_t PRIV_LOCK_TABLES= SELECT_ACL | LOCK_TABLES_ACL; /* Allow to set an object definer: CREATE DEFINER=xxx {TRIGGER|VIEW|FUNCTION|PROCEDURE} Was SUPER prior to 10.5.2 */ constexpr privilege_t PRIV_DEFINER_CLAUSE= SET_USER_ACL | SUPER_ACL; /* If a VIEW has a `definer=invoker@host` clause and the specified definer does not exists, then - The invoker with REVEAL_MISSING_DEFINER_ACL gets: ERROR: The user specified as a definer ('definer1'@'localhost') doesn't exist - The invoker without MISSING_DEFINER_ACL gets a generic access error, without revealing details that the definer does not exists. TODO: we should eventually test the same privilege when processing other objects that have the DEFINER clause (e.g. routines, triggers). Currently the missing definer is revealed for non-privileged invokers in case of routines, triggers, etc. Was SUPER prior to 10.5.2 */ constexpr privilege_t PRIV_REVEAL_MISSING_DEFINER= SET_USER_ACL | SUPER_ACL; /* Actions that require only the SUPER privilege */ constexpr privilege_t PRIV_DES_DECRYPT_ONE_ARG= SUPER_ACL; constexpr privilege_t PRIV_LOG_BIN_TRUSTED_SP_CREATOR= SUPER_ACL; constexpr privilege_t PRIV_DEBUG= SUPER_ACL; constexpr privilege_t PRIV_SET_GLOBAL_SYSTEM_VARIABLE= SUPER_ACL; constexpr privilege_t PRIV_SET_RESTRICTED_SESSION_SYSTEM_VARIABLE= SUPER_ACL; /* The following variables respected only SUPER_ACL prior to 10.5.2 */ constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_FORMAT= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_DIRECT_NON_TRANSACTIONAL_UPDATES= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_ANNOTATE_ROW_EVENTS= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_VAR_BINLOG_ROW_IMAGE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_VAR_SQL_LOG_BIN= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_CACHE_SIZE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_FILE_CACHE_SIZE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_STMT_CACHE_SIZE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_COMMIT_WAIT_COUNT= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_COMMIT_WAIT_USEC= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_BINLOG_ROW_METADATA= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_EXPIRE_LOGS_DAYS= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_LOG_BIN_COMPRESS= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_LOG_BIN_COMPRESS_MIN_LEN= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_LOG_BIN_TRUST_FUNCTION_CREATORS= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_BINLOG_CACHE_SIZE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_BINLOG_STMT_CACHE_SIZE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_BINLOG_SIZE= SUPER_ACL | BINLOG_ADMIN_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_BINLOG= SUPER_ACL | BINLOG_ADMIN_ACL; /* Privileges related to --read-only */ // Was super prior to 10.5.2 constexpr privilege_t PRIV_IGNORE_READ_ONLY= READ_ONLY_ADMIN_ACL | SUPER_ACL; // Was super prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_READ_ONLY= READ_ONLY_ADMIN_ACL | SUPER_ACL; /* Privileges related to connection handling. */ // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_IGNORE_INIT_CONNECT= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_IGNORE_MAX_USER_CONNECTIONS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_IGNORE_MAX_CONNECTIONS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_IGNORE_MAX_PASSWORD_ERRORS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_KILL_OTHER_USER_PROCESS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_CONNECT_TIMEOUT= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_DISCONNECT_ON_EXPIRED_PASSWORD= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_EXTRA_MAX_CONNECTIONS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_INIT_CONNECT= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_CONNECTIONS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_CONNECT_ERRORS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MAX_PASSWORD_ERRORS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_PROXY_PROTOCOL_NETWORKS= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SECURE_AUTH= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLOW_LAUNCH_TIME= CONNECTION_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_THREAD_POOL= CONNECTION_ADMIN_ACL | SUPER_ACL; /* Binary log related privileges that are checked regardless of active replication running. */ /* This command was renamed from "SHOW MASTER STATUS" to "SHOW BINLOG STATUS" in 10.5.2. Was SUPER_ACL | REPL_CLIENT_ACL prior to 10.5.2 REPL_CLIENT_ACL was renamed to BINLOG_MONITOR_ACL. */ constexpr privilege_t PRIV_STMT_SHOW_BINLOG_STATUS= BINLOG_MONITOR_ACL | SUPER_ACL; /* Was SUPER_ACL | REPL_CLIENT_ACL prior to 10.5.2 REPL_CLIENT_ACL was renamed to BINLOG_MONITOR_ACL. */ constexpr privilege_t PRIV_STMT_SHOW_BINARY_LOGS= BINLOG_MONITOR_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_PURGE_BINLOG= BINLOG_ADMIN_ACL | SUPER_ACL; // Was REPL_SLAVE_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_SHOW_BINLOG_EVENTS= BINLOG_MONITOR_ACL; /* Privileges for replication related statements and commands that are executed on the master. */ constexpr privilege_t PRIV_COM_REGISTER_SLAVE= REPL_SLAVE_ACL; constexpr privilege_t PRIV_COM_BINLOG_DUMP= REPL_SLAVE_ACL; // Was REPL_SLAVE_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_SHOW_SLAVE_HOSTS= REPL_MASTER_ADMIN_ACL; /* Replication master related variable privileges. Where SUPER prior to 10.5.2 */ constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_ENABLED= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_TIMEOUT= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_WAIT_NO_SLAVE= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_TRACE_LEVEL= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_MASTER_WAIT_POINT= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_MASTER_VERIFY_CHECKSUM= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_BINLOG_STATE= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SERVER_ID= REPL_MASTER_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_DOMAIN_ID= REPL_MASTER_ADMIN_ACL | SUPER_ACL; /* Privileges for statements that are executed on the slave */ // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_START_SLAVE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_STOP_SLAVE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_CHANGE_MASTER= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; // Was (SUPER_ACL | REPL_CLIENT_ACL) prior to 10.5.2 // Was (SUPER_ACL | REPL_SLAVE_ADMIN_ACL) from 10.5.2 to 10.5.7 constexpr privilege_t PRIV_STMT_SHOW_SLAVE_STATUS= SLAVE_MONITOR_ACL | SUPER_ACL; // Was REPL_SLAVE_ACL prior to 10.5.2 // Was REPL_SLAVE_ADMIN_ACL from 10.5.2 to 10.5.7 constexpr privilege_t PRIV_STMT_SHOW_RELAYLOG_EVENTS= SLAVE_MONITOR_ACL; /* Privileges related to binlog replying. Were SUPER_ACL prior to 10.5.2 */ constexpr privilege_t PRIV_STMT_BINLOG= BINLOG_REPLAY_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_GTID_SEQ_NO= BINLOG_REPLAY_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_PSEUDO_THREAD_ID= BINLOG_REPLAY_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_SERVER_ID= BINLOG_REPLAY_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_SESSION_VAR_GTID_DOMAIN_ID= BINLOG_REPLAY_ACL | SUPER_ACL; /* Privileges for slave related global variables. Were SUPER prior to 10.5.2. */ constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_EVENTS_MARKED_FOR_SKIP= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_DO_DB= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_DO_TABLE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_IGNORE_DB= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_IGNORE_TABLE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_WILD_DO_TABLE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_REPLICATE_WILD_IGNORE_TABLE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_READ_BINLOG_SPEED_LIMIT= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_COMPRESSED_PROTOCOL= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_DDL_EXEC_MODE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_DOMAIN_PARALLEL_THREADS= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_EXEC_MODE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_MAX_ALLOWED_PACKET= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_NET_TIMEOUT= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_MAX_QUEUED= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_MODE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_THREADS= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_PARALLEL_WORKERS= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_RUN_TRIGGERS_FOR_RBR= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_SQL_VERIFY_CHECKSUM= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_TRANSACTION_RETRY_INTERVAL= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SLAVE_TYPE_CONVERSIONS= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_INIT_SLAVE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_ENABLED= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_TRACE_LEVEL= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_DELAY_MASTER= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RPL_SEMI_SYNC_SLAVE_KILL_CONN_TIMEOUT= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RELAY_LOG_PURGE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_RELAY_LOG_RECOVERY= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_MASTER_INFO= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_RELAY_LOG= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_SYNC_RELAY_LOG_INFO= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_CLEANUP_BATCH_SIZE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_IGNORE_DUPLICATES= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_POS_AUTO_ENGINES= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_SLAVE_POS= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; constexpr privilege_t PRIV_SET_SYSTEM_GLOBAL_VAR_GTID_STRICT_MODE= REPL_SLAVE_ADMIN_ACL | SUPER_ACL; /* Privileges for federated database related statements */ // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_CREATE_SERVER= FEDERATED_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_ALTER_SERVER= FEDERATED_ADMIN_ACL | SUPER_ACL; // Was SUPER_ACL prior to 10.5.2 constexpr privilege_t PRIV_STMT_DROP_SERVER= FEDERATED_ADMIN_ACL | SUPER_ACL; /* Privileges related to processes */ constexpr privilege_t PRIV_COM_PROCESS_INFO= PROCESS_ACL; constexpr privilege_t PRIV_STMT_SHOW_EXPLAIN= PROCESS_ACL; constexpr privilege_t PRIV_STMT_SHOW_ENGINE_STATUS= PROCESS_ACL; constexpr privilege_t PRIV_STMT_SHOW_ENGINE_MUTEX= PROCESS_ACL; constexpr privilege_t PRIV_STMT_SHOW_PROCESSLIST= PROCESS_ACL; /* Defines to change the above bits to how things are stored in tables This is needed as the 'host' and 'db' table is missing a few privileges */ /* Privileges that need to be reallocated (in continous chunks) */ constexpr privilege_t DB_CHUNK0 (COL_DML_ACLS | CREATE_ACL | DROP_ACL); constexpr privilege_t DB_CHUNK1 (GRANT_ACL | REFERENCES_ACL | INDEX_ACL | ALTER_ACL); constexpr privilege_t DB_CHUNK2 (CREATE_TMP_ACL | LOCK_TABLES_ACL); constexpr privilege_t DB_CHUNK3 (VIEW_ACLS | PROC_DDL_ACLS); constexpr privilege_t DB_CHUNK4 (EXECUTE_ACL); constexpr privilege_t DB_CHUNK5 (EVENT_ACL | TRIGGER_ACL); constexpr privilege_t DB_CHUNK6 (DELETE_HISTORY_ACL); static inline privilege_t fix_rights_for_db(privilege_t access) { ulonglong A(access); return static_cast (((A) & DB_CHUNK0) | ((A << 4) & DB_CHUNK1) | ((A << 6) & DB_CHUNK2) | ((A << 9) & DB_CHUNK3) | ((A << 2) & DB_CHUNK4) | ((A << 9) & DB_CHUNK5) | ((A << 10) & DB_CHUNK6)); } static inline privilege_t get_rights_for_db(privilege_t access) { ulonglong A(access); return static_cast ((A & DB_CHUNK0) | ((A & DB_CHUNK1) >> 4) | ((A & DB_CHUNK2) >> 6) | ((A & DB_CHUNK3) >> 9) | ((A & DB_CHUNK4) >> 2) | ((A & DB_CHUNK5) >> 9) | ((A & DB_CHUNK6) >> 10)); } #define TBL_CHUNK0 DB_CHUNK0 #define TBL_CHUNK1 DB_CHUNK1 #define TBL_CHUNK2 (CREATE_VIEW_ACL | SHOW_VIEW_ACL) #define TBL_CHUNK3 TRIGGER_ACL #define TBL_CHUNK4 (DELETE_HISTORY_ACL) static inline privilege_t fix_rights_for_table(privilege_t access) { ulonglong A(access); return static_cast ((A & TBL_CHUNK0) | ((A << 4) & TBL_CHUNK1) | ((A << 11) & TBL_CHUNK2) | ((A << 15) & TBL_CHUNK3) | ((A << 16) & TBL_CHUNK4)); } static inline privilege_t get_rights_for_table(privilege_t access) { ulonglong A(access); return static_cast ((A & TBL_CHUNK0) | ((A & TBL_CHUNK1) >> 4) | ((A & TBL_CHUNK2) >> 11) | ((A & TBL_CHUNK3) >> 15) | ((A & TBL_CHUNK4) >> 16)); } static inline privilege_t fix_rights_for_column(privilege_t A) { const ulonglong mask(SELECT_ACL | INSERT_ACL | UPDATE_ACL); return (A & mask) | static_cast((A & ~mask) << 8); } static inline privilege_t get_rights_for_column(privilege_t A) { const ulonglong mask(SELECT_ACL | INSERT_ACL | UPDATE_ACL); return static_cast((static_cast(A) & mask) | (static_cast(A) >> 8)); } static inline privilege_t fix_rights_for_procedure(privilege_t access) { ulonglong A(access); return static_cast (((A << 18) & EXECUTE_ACL) | ((A << 23) & ALTER_PROC_ACL) | ((A << 8) & GRANT_ACL)); } static inline privilege_t get_rights_for_procedure(privilege_t access) { ulonglong A(access); return static_cast (((A & EXECUTE_ACL) >> 18) | ((A & ALTER_PROC_ACL) >> 23) | ((A & GRANT_ACL) >> 8)); } #endif /* PRIVILEGE_H_INCLUDED */ mysql/server/private/config.h000064400000034353151027430560012322 0ustar00/* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef MY_CONFIG_H #define MY_CONFIG_H #define DOT_FRM_VERSION 6 /* Headers we may want to use. */ #define STDC_HEADERS 1 #define _GNU_SOURCE 1 #define HAVE_ALLOCA_H 1 #define HAVE_ARPA_INET_H 1 #define HAVE_ASM_TERMBITS_H 1 #define HAVE_CRYPT_H 1 #define HAVE_CURSES_H 1 /* #undef HAVE_BFD_H */ /* #undef HAVE_NDIR_H */ #define HAVE_DIRENT_H 1 #define HAVE_DLFCN_H 1 #define HAVE_EXECINFO_H 1 #define HAVE_FCNTL_H 1 #define HAVE_FCNTL_DIRECT 1 #define HAVE_FENV_H 1 #define HAVE_FLOAT_H 1 #define HAVE_FNMATCH_H 1 #define HAVE_FPU_CONTROL_H 1 #define HAVE_GETMNTENT 1 /* #undef HAVE_GETMNTENT_IN_SYS_MNTAB */ /* #undef HAVE_GETMNTINFO */ /* #undef HAVE_GETMNTINFO64 */ /* #undef HAVE_GETMNTINFO_TAKES_statvfs */ #define HAVE_GRP_H 1 /* #undef HAVE_IA64INTRIN_H */ /* #undef HAVE_IEEEFP_H */ #define HAVE_INTTYPES_H 1 /* #undef HAVE_KQUEUE */ #define HAVE_LIMITS_H 1 #define HAVE_LINK_H 1 #define HAVE_LINUX_UNISTD_H 1 #define HAVE_LINUX_MMAN_H 1 #define HAVE_LOCALE_H 1 #define HAVE_MALLOC_H 1 #define HAVE_MEMORY_H 1 #define HAVE_NETINET_IN_H 1 #define HAVE_PATHS_H 1 #define HAVE_POLL_H 1 #define HAVE_PWD_H 1 #define HAVE_SCHED_H 1 /* #undef HAVE_SELECT_H */ /* #undef HAVE_SOLARIS_LARGE_PAGES */ #define HAVE_STDDEF_H 1 #define HAVE_STDLIB_H 1 #define HAVE_STDARG_H 1 #define HAVE_STRINGS_H 1 #define HAVE_STRING_H 1 #define HAVE_STDINT_H 1 /* #undef HAVE_SYNCH_H */ /* #undef HAVE_SYSENT_H */ #define HAVE_SYS_DIR_H 1 #define HAVE_SYS_FILE_H 1 /* #undef HAVE_SYS_FPU_H */ #define HAVE_SYS_IOCTL_H 1 /* #undef HAVE_SYS_MALLOC_H */ #define HAVE_SYS_MMAN_H 1 /* #undef HAVE_SYS_MNTENT_H */ /* #undef HAVE_SYS_NDIR_H */ /* #undef HAVE_SYS_PTE_H */ /* #undef HAVE_SYS_PTEM_H */ #define HAVE_SYS_PRCTL_H 1 #define HAVE_SYS_RESOURCE_H 1 #define HAVE_SYS_SELECT_H 1 #define HAVE_SYS_SOCKET_H 1 /* #undef HAVE_SYS_SOCKIO_H */ #define HAVE_SYS_UTSNAME_H 1 #define HAVE_SYS_STAT_H 1 /* #undef HAVE_SYS_STREAM_H */ #define HAVE_SYS_SYSCALL_H 1 #define HAVE_SYS_TIMEB_H 1 #define HAVE_SYS_TIMES_H 1 #define HAVE_SYS_TIME_H 1 #define HAVE_SYS_TYPES_H 1 #define HAVE_SYS_UN_H 1 /* #undef HAVE_SYS_VADVISE_H */ #define HAVE_SYS_STATVFS_H 1 #define HAVE_UCONTEXT_H 1 #define HAVE_TERM_H 1 /* #undef HAVE_TERMBITS_H */ #define HAVE_TERMIOS_H 1 #define HAVE_TERMIO_H 1 #define HAVE_TERMCAP_H 1 #define HAVE_TIME_H 1 #define HAVE_UNISTD_H 1 #define HAVE_UTIME_H 1 /* #undef HAVE_VARARGS_H */ /* #undef HAVE_SYS_UTIME_H */ #define HAVE_SYS_WAIT_H 1 #define HAVE_SYS_PARAM_H 1 /* Libraries */ /* #undef HAVE_LIBWRAP */ #define HAVE_SYSTEMD 1 #define HAVE_SYSTEMD_SD_LISTEN_FDS_WITH_NAMES 1 /* Does "struct timespec" have a "sec" and "nsec" field? */ /* #undef HAVE_TIMESPEC_TS_SEC */ /* Readline */ /* #undef HAVE_HIST_ENTRY */ /* #undef USE_LIBEDIT_INTERFACE */ #define USE_NEW_READLINE_INTERFACE 1 #define FIONREAD_IN_SYS_IOCTL 1 #define GWINSZ_IN_SYS_IOCTL 1 /* #undef TIOCSTAT_IN_SYS_IOCTL */ /* #undef FIONREAD_IN_SYS_FILIO */ /* Functions we may want to use. */ #define HAVE_ACCEPT4 1 #define HAVE_ACCESS 1 #define HAVE_ALARM 1 #define HAVE_ALLOCA 1 /* #undef HAVE_BFILL */ #define HAVE_INDEX 1 #define HAVE_CLOCK_GETTIME 1 #define HAVE_CRYPT 1 #define HAVE_CUSERID 1 #define HAVE_DLADDR 1 #define HAVE_DLERROR 1 #define HAVE_DLOPEN 1 #define HAVE_FCHMOD 1 #define HAVE_FCNTL 1 #define HAVE_FDATASYNC 1 #define HAVE_DECL_FDATASYNC 1 #define HAVE_FEDISABLEEXCEPT 1 #define HAVE_FESETROUND 1 /* #undef HAVE_FP_EXCEPT */ #define HAVE_FSEEKO 1 #define HAVE_FSYNC 1 #define HAVE_FTIME 1 #define HAVE_GETIFADDRS 1 #define HAVE_GETCWD 1 #define HAVE_GETHOSTBYADDR_R 1 /* #undef HAVE_GETHRTIME */ #define HAVE_GETPAGESIZE 1 /* #undef HAVE_GETPAGESIZES */ #define HAVE_GETPASS 1 /* #undef HAVE_GETPASSPHRASE */ #define HAVE_GETPWNAM 1 #define HAVE_GETPWUID 1 #define HAVE_GETRLIMIT 1 #define HAVE_GETRUSAGE 1 #define HAVE_GETTIMEOFDAY 1 #define HAVE_GETWD 1 #define HAVE_GMTIME_R 1 /* #undef gmtime_r */ #define HAVE_IN_ADDR_T 1 #define HAVE_INITGROUPS 1 #define HAVE_LDIV 1 #define HAVE_LRAND48 1 #define HAVE_LOCALTIME_R 1 #define HAVE_LSTAT 1 /* #define HAVE_MLOCK 1 see Bug#54662 */ #define HAVE_NL_LANGINFO 1 #define HAVE_MADVISE 1 #define HAVE_DECL_MADVISE 1 /* #undef HAVE_DECL_MHA_MAPSIZE_VA */ #define HAVE_MALLINFO 1 /* #undef HAVE_MALLINFO2 */ /* #undef HAVE_MALLOC_ZONE */ #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MKSTEMP 1 #define HAVE_MKOSTEMP 1 #define HAVE_MLOCKALL 1 #define HAVE_MMAP 1 #define HAVE_MMAP64 1 #define HAVE_PERROR 1 #define HAVE_POLL 1 #define HAVE_POSIX_FALLOCATE 1 #define HAVE_FALLOC_PUNCH_HOLE_AND_KEEP_SIZE 1 #define HAVE_PREAD 1 /* #undef HAVE_READ_REAL_TIME */ /* #undef HAVE_PTHREAD_ATTR_CREATE */ #define HAVE_PTHREAD_ATTR_GETGUARDSIZE 1 #define HAVE_PTHREAD_ATTR_GETSTACKSIZE 1 #define HAVE_PTHREAD_ATTR_SETSCOPE 1 #define HAVE_PTHREAD_ATTR_SETSTACKSIZE 1 #define HAVE_PTHREAD_GETATTR_NP 1 /* #undef HAVE_PTHREAD_CONDATTR_CREATE */ #define HAVE_PTHREAD_GETAFFINITY_NP 1 #define HAVE_PTHREAD_KEY_DELETE 1 /* #undef HAVE_PTHREAD_KILL */ #define HAVE_PTHREAD_RWLOCK_RDLOCK 1 #define HAVE_PTHREAD_SIGMASK 1 /* #undef HAVE_PTHREAD_YIELD_NP */ #define HAVE_PTHREAD_YIELD_ZERO_ARG 1 #define PTHREAD_ONCE_INITIALIZER PTHREAD_ONCE_INIT #define HAVE_PUTENV 1 /* #undef HAVE_READDIR_R */ #define HAVE_READLINK 1 #define HAVE_REALPATH 1 #define HAVE_RENAME 1 /* #undef HAVE_RWLOCK_INIT */ #define HAVE_SCHED_YIELD 1 #define HAVE_SELECT 1 #define HAVE_SETENV 1 #define HAVE_SETLOCALE 1 #define HAVE_SETMNTENT 1 #define HAVE_SETUPTERM 1 #define HAVE_SIGSET 1 #define HAVE_SIGACTION 1 /* #undef HAVE_SIGTHREADMASK */ #define HAVE_SIGWAIT 1 #define HAVE_SIGWAITINFO 1 #define HAVE_SLEEP 1 #define HAVE_STPCPY 1 #define HAVE_STRERROR 1 #define HAVE_STRCOLL 1 #define HAVE_STRNLEN 1 #define HAVE_STRPBRK 1 #define HAVE_STRTOK_R 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOULL 1 /* #undef HAVE_TELL */ /* #undef HAVE_THR_YIELD */ #define HAVE_TIME 1 #define HAVE_TIMES 1 #define HAVE_VIDATTR 1 #define HAVE_VIO_READ_BUFF 1 #define HAVE_VASPRINTF 1 #define HAVE_VSNPRINTF 1 #define HAVE_FTRUNCATE 1 #define HAVE_TZNAME 1 /* Symbols we may use */ /* #undef HAVE_SYS_ERRLIST */ /* used by stacktrace functions */ #define HAVE_BACKTRACE 1 #define HAVE_BACKTRACE_SYMBOLS 1 #define HAVE_BACKTRACE_SYMBOLS_FD 1 /* #undef HAVE_PRINTSTACK */ #define HAVE_IPV6 1 /* #undef ss_family */ /* #undef HAVE_SOCKADDR_IN_SIN_LEN */ /* #undef HAVE_SOCKADDR_IN6_SIN6_LEN */ #define STRUCT_TIMESPEC_HAS_TV_SEC 1 #define STRUCT_TIMESPEC_HAS_TV_NSEC 1 /* this means that valgrind headers and macros are available */ #define HAVE_VALGRIND_MEMCHECK_H 1 /* this means WITH_VALGRIND - we change some code paths for valgrind */ /* #undef HAVE_valgrind */ /* Types we may use */ #ifdef __APPLE__ /* Special handling required for OSX to support universal binaries that mix 32 and 64 bit architectures. */ #if(__LP64__) #define SIZEOF_LONG 8 #else #define SIZEOF_LONG 4 #endif #define SIZEOF_VOIDP SIZEOF_LONG #define SIZEOF_CHARP SIZEOF_LONG #define SIZEOF_SIZE_T SIZEOF_LONG #else /* No indentation, to fetch the lines from verification scripts */ #define SIZEOF_LONG 8 #define SIZEOF_VOIDP 8 #define SIZEOF_CHARP 8 #define SIZEOF_SIZE_T 8 #endif #define HAVE_LONG 1 #define HAVE_CHARP 1 #define SIZEOF_INT 4 #define HAVE_INT 1 #define SIZEOF_LONG_LONG 8 #define HAVE_LONG_LONG 1 #define SIZEOF_OFF_T 8 #define HAVE_OFF_T 1 /* #undef SIZEOF_UCHAR */ /* #undef HAVE_UCHAR */ #define SIZEOF_UINT 4 #define HAVE_UINT 1 #define SIZEOF_ULONG 8 #define HAVE_ULONG 1 /* #undef SIZEOF_INT8 */ /* #undef HAVE_INT8 */ /* #undef SIZEOF_UINT8 */ /* #undef HAVE_UINT8 */ /* #undef SIZEOF_INT16 */ /* #undef HAVE_INT16 */ /* #undef SIZEOF_UINT16 */ /* #undef HAVE_UINT16 */ /* #undef SIZEOF_INT32 */ /* #undef HAVE_INT32 */ /* #undef SIZEOF_UINT32 */ /* #undef HAVE_UINT32 */ /* #undef SIZEOF_INT64 */ /* #undef HAVE_INT64 */ /* #undef SIZEOF_UINT64 */ /* #undef HAVE_UINT64 */ #define SOCKET_SIZE_TYPE socklen_t #define HAVE_MBSTATE_T 1 #define MAX_INDEXES 64 #define QSORT_TYPE_IS_VOID 1 #define RETQSORTTYPE void #define RETSIGTYPE void #define VOID_SIGHANDLER 1 #define HAVE_SIGHANDLER_T 1 #define STRUCT_RLIMIT struct rlimit #ifdef __APPLE__ #if __BIG_ENDIAN #define WORDS_BIGENDIAN 1 #endif #else /* #undef WORDS_BIGENDIAN */ #endif /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #define C_HAS_inline 1 #if !(C_HAS_inline) #ifndef __cplusplus # define inline #endif #endif #define TARGET_OS_LINUX 1 #define HAVE_WCTYPE_H 1 #define HAVE_WCHAR_H 1 #define HAVE_LANGINFO_H 1 #define HAVE_MBRLEN 1 #define HAVE_MBSRTOWCS 1 #define HAVE_MBRTOWC 1 #define HAVE_WCWIDTH 1 #define HAVE_ISWLOWER 1 #define HAVE_ISWUPPER 1 #define HAVE_TOWLOWER 1 #define HAVE_TOWUPPER 1 #define HAVE_ISWCTYPE 1 #define HAVE_WCHAR_T 1 #define HAVE_STRCASECMP 1 #define HAVE_TCGETATTR 1 #define HAVE_WEAK_SYMBOL 1 #define HAVE_ABI_CXA_DEMANGLE 1 #define HAVE_ATTRIBUTE_CLEANUP 1 #define HAVE_POSIX_SIGNALS 1 /* #undef HAVE_BSD_SIGNALS */ /* #undef HAVE_SVR3_SIGNALS */ /* #undef HAVE_V7_SIGNALS */ #define HAVE_ERR_remove_thread_state 1 #define HAVE_X509_check_host 1 /* #undef HAVE_SOLARIS_STYLE_GETHOST */ #define HAVE_GCC_C11_ATOMICS 1 /* #undef HAVE_SOLARIS_ATOMIC */ /* #undef NO_FCNTL_NONBLOCK */ #define NO_ALARM 1 /* #undef _LARGE_FILES */ #define _LARGEFILE_SOURCE 1 /* #undef _LARGEFILE64_SOURCE */ #define TIME_WITH_SYS_TIME 1 #define STACK_DIRECTION -1 #define SYSTEM_TYPE "Linux" #define MACHINE_TYPE "x86_64" #define DEFAULT_MACHINE "x86_64" #define HAVE_DTRACE 1 #define SIGNAL_WITH_VIO_CLOSE 1 /* Windows stuff, mostly functions, that have Posix analogs but named differently */ /* #undef S_IROTH */ /* #undef S_IFIFO */ /* #undef IPPROTO_IPV6 */ /* #undef IPV6_V6ONLY */ /* #undef sigset_t */ /* #undef mode_t */ /* #undef SIGQUIT */ /* #undef SIGPIPE */ /* #undef popen */ /* #undef pclose */ /* #undef ssize_t */ /* #undef strcasecmp */ /* #undef strncasecmp */ /* #undef snprintf */ /* #undef strtok_r */ /* #undef strtoll */ /* #undef strtoull */ /* #undef vsnprintf */ #if defined(_MSC_VER) && (_MSC_VER > 1800) #define tzname _tzname #define P_tmpdir "C:\\TEMP" #endif #if defined(_MSC_VER) && (_MSC_VER > 1310) # define HAVE_SETENV #define setenv(a,b,c) _putenv_s(a,b) #endif #define PSAPI_VERSION 1 /* for GetProcessMemoryInfo() */ /* We don't want the min/max macros */ #ifdef _WIN32 #define NOMINMAX 1 #endif /* MySQL features */ #define LOCAL_INFILE_MODE_OFF 0 #define LOCAL_INFILE_MODE_ON 1 #define LOCAL_INFILE_MODE_AUTO 2 #define ENABLED_LOCAL_INFILE LOCAL_INFILE_MODE_AUTO #define ENABLED_PROFILING 1 /* #undef EXTRA_DEBUG */ /* #undef USE_SYMDIR */ /* Character sets and collations */ #define MYSQL_DEFAULT_CHARSET_NAME "latin1" #define MYSQL_DEFAULT_COLLATION_NAME "latin1_swedish_ci" #define USE_MB #define USE_MB_IDENT /* This should mean case insensitive file system */ /* #undef FN_NO_CASE_SENSE */ #define HAVE_CHARSET_armscii8 1 #define HAVE_CHARSET_ascii 1 #define HAVE_CHARSET_big5 1 #define HAVE_CHARSET_cp1250 1 #define HAVE_CHARSET_cp1251 1 #define HAVE_CHARSET_cp1256 1 #define HAVE_CHARSET_cp1257 1 #define HAVE_CHARSET_cp850 1 #define HAVE_CHARSET_cp852 1 #define HAVE_CHARSET_cp866 1 #define HAVE_CHARSET_cp932 1 #define HAVE_CHARSET_dec8 1 #define HAVE_CHARSET_eucjpms 1 #define HAVE_CHARSET_euckr 1 #define HAVE_CHARSET_gb2312 1 #define HAVE_CHARSET_gbk 1 #define HAVE_CHARSET_geostd8 1 #define HAVE_CHARSET_greek 1 #define HAVE_CHARSET_hebrew 1 #define HAVE_CHARSET_hp8 1 #define HAVE_CHARSET_keybcs2 1 #define HAVE_CHARSET_koi8r 1 #define HAVE_CHARSET_koi8u 1 #define HAVE_CHARSET_latin1 1 #define HAVE_CHARSET_latin2 1 #define HAVE_CHARSET_latin5 1 #define HAVE_CHARSET_latin7 1 #define HAVE_CHARSET_macce 1 #define HAVE_CHARSET_macroman 1 #define HAVE_CHARSET_sjis 1 #define HAVE_CHARSET_swe7 1 #define HAVE_CHARSET_tis620 1 #define HAVE_CHARSET_ucs2 1 #define HAVE_CHARSET_ujis 1 #define HAVE_CHARSET_utf8mb4 1 #define HAVE_CHARSET_utf8mb3 1 #define HAVE_CHARSET_utf16 1 #define HAVE_CHARSET_utf32 1 #define HAVE_UCA_COLLATIONS 1 #define HAVE_COMPRESS 1 #define HAVE_EncryptAes128Ctr 1 #define HAVE_EncryptAes128Gcm 1 #define HAVE_des 1 /* Stuff that always need to be defined (compile breaks without it) */ #define HAVE_SPATIAL 1 #define HAVE_RTREE_KEYS 1 #define HAVE_QUERY_CACHE 1 #define BIG_TABLES 1 /* Important storage engines (those that really need define WITH__STORAGE_ENGINE for the whole server) */ #define WITH_INNOBASE_STORAGE_ENGINE 1 #define WITH_PARTITION_STORAGE_ENGINE 1 #define WITH_PERFSCHEMA_STORAGE_ENGINE 1 #define WITH_ARIA_STORAGE_ENGINE 1 #define USE_ARIA_FOR_TMP_TABLES 1 #define DEFAULT_MYSQL_HOME "/usr" #define SHAREDIR "/usr/share/mysql" #define DEFAULT_BASEDIR "/usr" #define MYSQL_DATADIR "/var/lib/mysql" #define DEFAULT_CHARSET_HOME "/usr" #define PLUGINDIR "/usr/lib64/mysql/plugin" #define DEFAULT_SYSCONFDIR "/etc" #define DEFAULT_TMPDIR P_tmpdir /* #undef SO_EXT */ #define MYSQL_VERSION_MAJOR 10 #define MYSQL_VERSION_MINOR 6 #define MYSQL_VERSION_PATCH 23 #define MYSQL_VERSION_EXTRA "" #define PACKAGE "mysql" #define PACKAGE_BUGREPORT "" #define PACKAGE_NAME "MySQL Server" #define PACKAGE_STRING "MySQL Server 10.6.23" #define PACKAGE_TARNAME "mysql" #define PACKAGE_VERSION "10.6.23" #define VERSION "10.6.23" #define PROTOCOL_VERSION 10 #define PCRE2_CODE_UNIT_WIDTH 8 #define MALLOC_LIBRARY "system" /* time_t related defines */ #define SIZEOF_TIME_T 8 /* #undef TIME_T_UNSIGNED */ #ifndef EMBEDDED_LIBRARY /* #undef WSREP_INTERFACE_VERSION */ #define WITH_WSREP 1 #define WSREP_PROC_INFO 1 #endif #if !defined(__STDC_FORMAT_MACROS) #define __STDC_FORMAT_MACROS #endif // !defined(__STDC_FORMAT_MACROS) #endif #define HAVE_VFORK 1 mysql/server/private/span.h000064400000007533151027430560012016 0ustar00/***************************************************************************** Copyright (c) 2019, 2020 MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA *****************************************************************************/ #pragma once #include #include namespace st_ { namespace detail { template struct remove_cv { typedef T type; }; template struct remove_cv { typedef T type; }; template struct remove_cv { typedef T type; }; template struct remove_cv { typedef T type; }; } // namespace detail template class span { public: typedef ElementType element_type; typedef typename detail::remove_cv::type value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef element_type *pointer; typedef const element_type *const_pointer; typedef element_type &reference; typedef const element_type &const_reference; typedef pointer iterator; typedef const_pointer const_iterator; typedef std::reverse_iterator reverse_iterator; span() : data_(NULL), size_(0) {} span(pointer ptr, size_type count) : data_(ptr), size_(count) {} span(pointer first, pointer last) : data_(first), size_(last - first) {} template span(element_type (&arr)[N]) : data_(arr), size_(N) {} template span(Container &cont) : data_(cont.data()), size_(cont.size()) { } template span(const Container &cont) : data_(cont.data()), size_(cont.size()) { } span(const span &other) : data_(other.data_), size_(other.size_) {} ~span() = default; span &operator=(const span &other) { data_= other.data(); size_= other.size(); return *this; } template span first() const { assert(!empty()); return span(data(), 1); } template span last() const { assert(!empty()); return span(data() + size() - 1, 1); } span first(size_type count) const { assert(!empty()); return span(data(), 1); } span last(size_type count) const { assert(!empty()); return span(data() + size() - 1, 1); } span subspan(size_type offset, size_type count) const { assert(!empty()); assert(size() >= offset + count); return span(data() + offset, count); } size_type size() const { return size_; } size_type size_bytes() const { return size() * sizeof(ElementType); } bool empty() const __attribute__((warn_unused_result)) { return size() == 0; } reference operator[](size_type idx) const { assert(size() > idx); return data()[idx]; } reference front() const { assert(!empty()); return data()[0]; } reference back() const { assert(!empty()); return data()[size() - 1]; } pointer data() const { return data_; } iterator begin() const { return data_; } iterator end() const { return data_ + size_; } reverse_iterator rbegin() const { return std::reverse_iterator(end()); } reverse_iterator rend() const { return std::reverse_iterator(begin()); } private: pointer data_; size_type size_; }; } // namespace st_ mysql/server/private/pfs_file_provider.h000064400000006121151027430560014546 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_FILE_PROVIDER_H #define PFS_FILE_PROVIDER_H /** @file include/pfs_file_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_FILE_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_FILE_CALL(M) pfs_ ## M ## _v1 C_MODE_START void pfs_register_file_v1(const char *category, PSI_file_info_v1 *info, int count); void pfs_create_file_v1(PSI_file_key key, const char *name, File file); PSI_file_locker* pfs_get_thread_file_name_locker_v1(PSI_file_locker_state *state, PSI_file_key key, PSI_file_operation op, const char *name, const void *identity); PSI_file_locker* pfs_get_thread_file_stream_locker_v1(PSI_file_locker_state *state, PSI_file *file, PSI_file_operation op); PSI_file_locker* pfs_get_thread_file_descriptor_locker_v1(PSI_file_locker_state *state, File file, PSI_file_operation op); void pfs_start_file_open_wait_v1(PSI_file_locker *locker, const char *src_file, uint src_line); PSI_file* pfs_end_file_open_wait_v1(PSI_file_locker *locker, void *result); void pfs_end_file_open_wait_and_bind_to_descriptor_v1 (PSI_file_locker *locker, File file); void pfs_end_temp_file_open_wait_and_bind_to_descriptor_v1 (PSI_file_locker *locker, File file, const char *filename); void pfs_start_file_wait_v1(PSI_file_locker *locker, size_t count, const char *src_file, uint src_line); void pfs_end_file_wait_v1(PSI_file_locker *locker, size_t byte_count); void pfs_start_file_close_wait_v1(PSI_file_locker *locker, const char *src_file, uint src_line); void pfs_end_file_close_wait_v1(PSI_file_locker *locker, int rc); void pfs_end_file_rename_wait_v1(PSI_file_locker *locker, const char *old_name, const char *new_name, int rc); C_MODE_END #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_FILE_INTERFACE */ #endif mysql/server/private/sql_insert.h000064400000005133151027430560013232 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_INSERT_INCLUDED #define SQL_INSERT_INCLUDED #include "sql_class.h" /* enum_duplicates */ #include "sql_list.h" /* Instead of including sql_lex.h we add this typedef here */ typedef List List_item; typedef struct st_copy_info COPY_INFO; int mysql_prepare_insert(THD *thd, TABLE_LIST *table_list, List &fields, List_item *values, List &update_fields, List &update_values, enum_duplicates duplic, COND **where, bool select_insert, bool * const cache_results); bool mysql_insert(THD *thd,TABLE_LIST *table,List &fields, List &values, List &update_fields, List &update_values, enum_duplicates flag, bool ignore, select_result* result); void upgrade_lock_type_for_insert(THD *thd, thr_lock_type *lock_type, enum_duplicates duplic, bool is_multi_insert); int check_that_all_fields_are_given_values(THD *thd, TABLE *entry, TABLE_LIST *table_list); int vers_insert_history_row(TABLE *table); int check_duplic_insert_without_overlaps(THD *thd, TABLE *table, enum_duplicates duplic); int write_record(THD *thd, TABLE *table, COPY_INFO *info, select_result *returning= NULL); void kill_delayed_threads(void); bool binlog_create_table(THD *thd, TABLE *table, bool replace); bool binlog_drop_table(THD *thd, TABLE *table); static inline void restore_default_record_for_insert(TABLE *t) { restore_record(t,s->default_values); if (t->triggers) t->triggers->default_extra_null_bitmap(); } #ifdef EMBEDDED_LIBRARY inline void kill_delayed_threads(void) {} #endif #endif /* SQL_INSERT_INCLUDED */ mysql/server/private/pfs_thread_provider.h000064400000012670151027430560015104 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_THREAD_PROVIDER_H #define PFS_THREAD_PROVIDER_H /** @file include/pfs_thread_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_THREAD_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_MUTEX_CALL(M) pfs_ ## M ## _v1 #define PSI_RWLOCK_CALL(M) pfs_ ## M ## _v1 #define PSI_COND_CALL(M) pfs_ ## M ## _v1 #define PSI_THREAD_CALL(M) pfs_ ## M ## _v1 C_MODE_START void pfs_register_mutex_v1(const char *category, PSI_mutex_info_v1 *info, int count); void pfs_register_rwlock_v1(const char *category, PSI_rwlock_info_v1 *info, int count); void pfs_register_cond_v1(const char *category, PSI_cond_info_v1 *info, int count); void pfs_register_thread_v1(const char *category, PSI_thread_info_v1 *info, int count); PSI_mutex* pfs_init_mutex_v1(PSI_mutex_key key, void *identity); void pfs_destroy_mutex_v1(PSI_mutex* mutex); PSI_rwlock* pfs_init_rwlock_v1(PSI_rwlock_key key, void *identity); void pfs_destroy_rwlock_v1(PSI_rwlock* rwlock); PSI_cond* pfs_init_cond_v1(PSI_cond_key key, void *identity); void pfs_destroy_cond_v1(PSI_cond* cond); int pfs_spawn_thread_v1(PSI_thread_key key, pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); PSI_thread* pfs_new_thread_v1(PSI_thread_key key, const void *identity, ulonglong processlist_id); void pfs_set_thread_id_v1(PSI_thread *thread, ulonglong processlist_id); void pfs_set_thread_THD_v1(PSI_thread *thread, THD *thd); void pfs_set_thread_os_id_v1(PSI_thread *thread); PSI_thread* pfs_get_thread_v1(void); void pfs_set_thread_user_v1(const char *user, int user_len); void pfs_set_thread_account_v1(const char *user, int user_len, const char *host, int host_len); void pfs_set_thread_db_v1(const char* db, int db_len); void pfs_set_thread_command_v1(int command); void pfs_set_thread_start_time_v1(time_t start_time); void pfs_set_thread_state_v1(const char* state); void pfs_set_connection_type_v1(opaque_vio_type conn_type); void pfs_set_thread_info_v1(const char* info, uint info_len); void pfs_set_thread_v1(PSI_thread* thread); void pfs_set_thread_peer_port_v1(PSI_thread *thread, uint port); void pfs_delete_current_thread_v1(void); void pfs_delete_thread_v1(PSI_thread *thread); PSI_mutex_locker* pfs_start_mutex_wait_v1(PSI_mutex_locker_state *state, PSI_mutex *mutex, PSI_mutex_operation op, const char *src_file, uint src_line); PSI_rwlock_locker* pfs_start_rwlock_rdwait_v1(PSI_rwlock_locker_state *state, PSI_rwlock *rwlock, PSI_rwlock_operation op, const char *src_file, uint src_line); PSI_rwlock_locker* pfs_start_rwlock_wrwait_v1(PSI_rwlock_locker_state *state, PSI_rwlock *rwlock, PSI_rwlock_operation op, const char *src_file, uint src_line); PSI_cond_locker* pfs_start_cond_wait_v1(PSI_cond_locker_state *state, PSI_cond *cond, PSI_mutex *mutex, PSI_cond_operation op, const char *src_file, uint src_line); PSI_table_locker* pfs_start_table_io_wait_v1(PSI_table_locker_state *state, PSI_table *table, PSI_table_io_operation op, uint index, const char *src_file, uint src_line); PSI_table_locker* pfs_start_table_lock_wait_v1(PSI_table_locker_state *state, PSI_table *table, PSI_table_lock_operation op, ulong op_flags, const char *src_file, uint src_line); void pfs_unlock_mutex_v1(PSI_mutex *mutex); void pfs_unlock_rwlock_v1(PSI_rwlock *rwlock); void pfs_signal_cond_v1(PSI_cond* cond); void pfs_broadcast_cond_v1(PSI_cond* cond); void pfs_end_mutex_wait_v1(PSI_mutex_locker* locker, int rc); void pfs_end_rwlock_rdwait_v1(PSI_rwlock_locker* locker, int rc); void pfs_end_rwlock_wrwait_v1(PSI_rwlock_locker* locker, int rc); void pfs_end_cond_wait_v1(PSI_cond_locker* locker, int rc); int pfs_set_thread_connect_attrs_v1(const char *buffer, uint length, const void *from_cs); C_MODE_END #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_THREAD_INTERFACE */ #endif mysql/server/private/t_ctype.h000064400000013007151027430560012515 0ustar00/* Copyright (C) 2000 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Copyright (C) 1998, 1999 by Pruet Boonma, all rights reserved. Copyright (C) 1998 by Theppitak Karoonboonyanan, all rights reserved. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies. Smaphan Raruenrom and Pruet Boonma makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. */ /* LC_COLLATE category + Level information */ #ifndef _t_ctype_h #define _t_ctype_h #define TOT_LEVELS 5 #define LAST_LEVEL 4 /* TOT_LEVELS - 1 */ #define IGNORE 0 /* level 1 symbols & order */ enum l1_symbols { L1_08 = TOT_LEVELS, L1_18, L1_28, L1_38, L1_48, L1_58, L1_68, L1_78, L1_88, L1_98, L1_A8, L1_B8, L1_C8, L1_D8, L1_E8, L1_F8, L1_G8, L1_H8, L1_I8, L1_J8, L1_K8, L1_L8, L1_M8, L1_N8, L1_O8, L1_P8, L1_Q8, L1_R8, L1_S8, L1_T8, L1_U8, L1_V8, L1_W8, L1_X8, L1_Y8, L1_Z8, L1_KO_KAI, L1_KHO_KHAI, L1_KHO_KHUAT, L1_KHO_KHWAI, L1_KHO_KHON, L1_KHO_RAKHANG, L1_NGO_NGU, L1_CHO_CHAN, L1_CHO_CHING, L1_CHO_CHANG, L1_SO_SO, L1_CHO_CHOE, L1_YO_YING, L1_DO_CHADA, L1_TO_PATAK, L1_THO_THAN, L1_THO_NANGMONTHO, L1_THO_PHUTHAO, L1_NO_NEN, L1_DO_DEK, L1_TO_TAO, L1_THO_THUNG, L1_THO_THAHAN, L1_THO_THONG, L1_NO_NU, L1_BO_BAIMAI, L1_PO_PLA, L1_PHO_PHUNG, L1_FO_FA, L1_PHO_PHAN, L1_FO_FAN, L1_PHO_SAMPHAO, L1_MO_MA, L1_YO_YAK, L1_RO_RUA, L1_RU, L1_LO_LING, L1_LU, L1_WO_WAEN, L1_SO_SALA, L1_SO_RUSI, L1_SO_SUA, L1_HO_HIP, L1_LO_CHULA, L1_O_ANG, L1_HO_NOKHUK, L1_NKHIT, L1_SARA_A, L1_MAI_HAN_AKAT, L1_SARA_AA, L1_SARA_AM, L1_SARA_I, L1_SARA_II, L1_SARA_UE, L1_SARA_UEE, L1_SARA_U, L1_SARA_UU, L1_SARA_E, L1_SARA_AE, L1_SARA_O, L1_SARA_AI_MAIMUAN, L1_SARA_AI_MAIMALAI }; /* level 2 symbols & order */ enum l2_symbols { L2_BLANK = TOT_LEVELS, L2_THAII, L2_YAMAK, L2_PINTHU, L2_GARAN, L2_TYKHU, L2_TONE1, L2_TONE2, L2_TONE3, L2_TONE4 }; /* level 3 symbols & order */ enum l3_symbols { L3_BLANK = TOT_LEVELS, L3_SPACE, L3_NB_SACE, L3_LOW_LINE, L3_HYPHEN, L3_COMMA, L3_SEMICOLON, L3_COLON, L3_EXCLAMATION, L3_QUESTION, L3_SOLIDUS, L3_FULL_STOP, L3_PAIYAN_NOI, L3_MAI_YAMOK, L3_GRAVE, L3_CIRCUMFLEX, L3_TILDE, L3_APOSTROPHE, L3_QUOTATION, L3_L_PARANTHESIS, L3_L_BRACKET, L3_L_BRACE, L3_R_BRACE, L3_R_BRACKET, L3_R_PARENTHESIS, L3_AT, L3_BAHT, L3_DOLLAR, L3_FONGMAN, L3_ANGKHANKHU, L3_KHOMUT, L3_ASTERISK, L3_BK_SOLIDUS, L3_AMPERSAND, L3_NUMBER, L3_PERCENT, L3_PLUS, L3_LESS_THAN, L3_EQUAL, L3_GREATER_THAN, L3_V_LINE }; /* level 4 symbols & order */ enum l4_symbols { L4_BLANK = TOT_LEVELS, L4_MIN, L4_CAP, L4_EXT }; enum level_symbols { L_UPRUPR = TOT_LEVELS, L_UPPER, L_MIDDLE, L_LOWER }; #define _is(c) (t_ctype[(c)][LAST_LEVEL]) #define _level 8 #define _consnt 16 #define _ldvowel 32 #define _fllwvowel 64 #define _uprvowel 128 #define _lwrvowel 256 #define _tone 512 #define _diacrt1 1024 #define _diacrt2 2048 #define _combine 4096 #define _stone 8192 #define _tdig 16384 #define _rearvowel (_fllwvowel | _uprvowel | _lwrvowel) #define _diacrt (_diacrt1 | _diacrt2) #define levelof(c) ( _is(c) & _level ) #define isthai(c) ( (c) >= 128 ) #define istalpha(c) ( _is(c) & (_consnt|_ldvowel|_rearvowel|\ _tone|_diacrt1|_diacrt2) ) #define isconsnt(c) ( _is(c) & _consnt ) #define isldvowel(c) ( _is(c) & _ldvowel ) #define isfllwvowel(c) ( _is(c) & _fllwvowel ) #define ismidvowel(c) ( _is(c) & (_ldvowel|_fllwvowel) ) #define isuprvowel(c) ( _is(c) & _uprvowel ) #define islwrvowel(c) ( _is(c) & _lwrvowel ) #define isuprlwrvowel(c) ( _is(c) & (_lwrvowel | _uprvowel)) #define isrearvowel(c) ( _is(c) & _rearvowel ) #define isvowel(c) ( _is(c) & (_ldvowel|_rearvowel) ) #define istone(c) ( _is(c) & _tone ) #define isunldable(c) ( _is(c) & (_rearvowel|_tone|_diacrt1|_diacrt2) ) #define iscombinable(c) ( _is(c) & _combine ) #define istdigit(c) ( _is(c) & _tdig ) #define isstone(c) ( _is(c) & _stone ) #define isdiacrt1(c) ( _is(c) & _diacrt1) #define isdiacrt2(c) ( _is(c) & _diacrt2) #define isdiacrt(c) ( _is(c) & _diacrt) /* Function prototype called by sql/field.cc */ void ThNormalize(uchar* ptr, uint field_length, const uchar* from, uint length); #endif mysql/server/private/sql_alloc.h000064400000003304151027430560013016 0ustar00#ifndef SQL_ALLOC_INCLUDED #define SQL_ALLOC_INCLUDED /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2017, 2018, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include /* alloc_root, MEM_ROOT, TRASH */ /* MariaDB standard class memory allocator */ class Sql_alloc { public: static void *operator new(size_t size) throw () { return thd_alloc(_current_thd(), size); } static void *operator new[](size_t size) throw () { return thd_alloc(_current_thd(), size); } static void *operator new[](size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } static void *operator new(size_t size, MEM_ROOT *mem_root) throw() { return alloc_root(mem_root, size); } static void operator delete(void *ptr, size_t size) { TRASH_FREE(ptr, size); } static void operator delete(void *, MEM_ROOT *){} static void operator delete[](void *, MEM_ROOT *) { /* never called */ } static void operator delete[](void *ptr, size_t size) { TRASH_FREE(ptr, size); } }; #endif /* SQL_ALLOC_INCLUDED */ mysql/server/private/wsrep_types.h000064400000001745151027430560013440 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Wsrep typedefs to better conform to coding style. */ #ifndef WSREP_TYPES_H #define WSREP_TYPES_H #include "wsrep/seqno.hpp" #include "wsrep/view.hpp" typedef wsrep::id Wsrep_id; typedef wsrep::seqno Wsrep_seqno; typedef wsrep::view Wsrep_view; #endif /* WSREP_TYPES_H */ mysql/server/private/sql_bootstrap.h000064400000003424151027430560013744 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_BOOTSTRAP_H #define SQL_BOOTSTRAP_H /** The maximum size of a bootstrap query. Increase this size if parsing a longer query during bootstrap is necessary. The longest query in use depends on the documentation content, see the file fill_help_tables.sql */ #define MAX_BOOTSTRAP_QUERY_SIZE 60000 /** The maximum size of a bootstrap query, expressed in a single line. Do not increase this size, use the multiline syntax instead. */ #define MAX_BOOTSTRAP_LINE_SIZE 20000 #define MAX_BOOTSTRAP_ERROR_LEN 256 #define READ_BOOTSTRAP_SUCCESS 0 #define READ_BOOTSTRAP_EOF 1 #define READ_BOOTSTRAP_ERROR 2 #define READ_BOOTSTRAP_QUERY_SIZE 3 typedef void *fgets_input_t; typedef char * (*fgets_fn_t)(char *, size_t, fgets_input_t, int *error); #ifdef __cplusplus extern "C" { #endif int read_bootstrap_query(char *query, int *query_length, fgets_input_t input, fgets_fn_t fgets_fn, int preserve_delimiter, int *error); #ifdef __cplusplus } #endif #endif mysql/server/private/threadpool_winsockets.h000064400000004362151027430560015464 0ustar00/* Copyright (C) 2020 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once #include #include struct st_vio; struct win_aiosocket { /** OVERLAPPED is needed by all Windows AIO*/ OVERLAPPED m_overlapped{}; /** Handle to pipe, or socket */ HANDLE m_handle{}; /** Whether the m_handle refers to pipe*/ bool m_is_pipe{}; /* Read buffer handling */ /** Pointer to buffer of size READ_BUFSIZ. Can be NULL.*/ char *m_buf_ptr{}; /** Offset to current buffer position*/ size_t m_buf_off{}; /** Size of valid data in the buffer*/ size_t m_buf_datalen{}; /* Vio handling */ /** Pointer to original vio->vio_read/vio->has_data function */ size_t (*m_orig_vio_read)(st_vio *, unsigned char *, size_t){}; char (*m_orig_vio_has_data)(st_vio *){}; /** Begins asynchronnous reading from socket/pipe. On IO completion, pre-read some bytes into internal buffer */ DWORD begin_read(); /** Update number of bytes returned, and IO error status Should be called right after IO is completed GetQueuedCompletionStatus() , or threadpool IO completion callback would return nbytes and the error. Sets the valid data length in the read buffer. */ void end_read(ULONG nbytes, DWORD err); /** Override VIO routines with ours, accounting for one-shot buffering. */ void init(st_vio *vio); /** Return number of unread bytes.*/ size_t buffer_remaining(); /* Frees the read buffer.*/ ~win_aiosocket(); }; /* Functions related to IO buffers caches.*/ extern void init_win_aio_buffers(unsigned int n_buffers); extern void destroy_win_aio_buffers(); mysql/server/private/my_tree.h000064400000007627151027430560012525 0ustar00/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _tree_h #define _tree_h #ifdef __cplusplus extern "C" { #endif #include "my_base.h" /* get 'enum ha_rkey_function' */ #include "my_alloc.h" /* MEM_ROOT */ /* Worst case tree is half full. This gives use 2^(MAX_TREE_HEIGHT/2) leafs */ #define MAX_TREE_HEIGHT 64 #define ELEMENT_KEY(tree,element)\ (tree->offset_to_key ? (void*)((uchar*) element+tree->offset_to_key) :\ *((void**) (element+1))) #define tree_set_pointer(element,ptr) *((uchar **) (element+1))=((uchar*) (ptr)) /* A tree with its flag set to TREE_ONLY_DUPS behaves differently on inserting an element that is not in the tree: the element is not added at all, but instead tree_insert() returns a special address TREE_ELEMENT_UNIQUE as an indication that the function has not failed due to lack of memory. */ #define TREE_ELEMENT_UNIQUE ((TREE_ELEMENT *) 1) #define TREE_NO_DUPS 1 #define TREE_ONLY_DUPS 2 typedef enum { left_root_right, right_root_left } TREE_WALK; typedef uint32 element_count; typedef int (*tree_walk_action)(void *,element_count,void *); typedef enum { free_init, free_free, free_end } TREE_FREE; typedef int (*tree_element_free)(void*, TREE_FREE, void *); typedef struct st_tree_element { struct st_tree_element *left,*right; uint32 count:31, colour:1; /* black is marked as 1 */ } TREE_ELEMENT; #define ELEMENT_CHILD(element, offs) (*(TREE_ELEMENT**)((char*)element + offs)) typedef struct st_tree { TREE_ELEMENT *root; TREE_ELEMENT **parents[MAX_TREE_HEIGHT]; uint offset_to_key,elements_in_tree,size_of_element; size_t memory_limit, allocated; qsort_cmp2 compare; void *custom_arg; MEM_ROOT mem_root; my_bool with_delete; tree_element_free free; myf my_flags; uint flag; } TREE; /* Functions on whole tree */ void init_tree(TREE *tree, size_t default_alloc_size, size_t memory_limit, int size, qsort_cmp2 compare, tree_element_free free_element, void *custom_arg, myf my_flags); int delete_tree(TREE*, my_bool abort); int reset_tree(TREE*); /* similar to delete tree, except we do not my_free() blocks in mem_root */ #define is_tree_inited(tree) ((tree)->root != 0) /* Functions on leafs */ TREE_ELEMENT *tree_insert(TREE *tree,void *key, uint key_size, void *custom_arg); void *tree_search(TREE *tree, void *key, void *custom_arg); int tree_walk(TREE *tree,tree_walk_action action, void *argument, TREE_WALK visit); int tree_delete(TREE *tree, void *key, uint key_size, void *custom_arg); void *tree_search_key(TREE *tree, const void *key, TREE_ELEMENT **parents, TREE_ELEMENT ***last_pos, enum ha_rkey_function flag, void *custom_arg); void *tree_search_edge(TREE *tree, TREE_ELEMENT **parents, TREE_ELEMENT ***last_pos, int child_offs); void *tree_search_next(TREE *tree, TREE_ELEMENT ***last_pos, int l_offs, int r_offs); ha_rows tree_record_pos(TREE *tree, const void *key, enum ha_rkey_function search_flag, void *custom_arg); #define reset_free_element(tree) (tree)->free= 0 #define TREE_ELEMENT_EXTRA_SIZE (sizeof(TREE_ELEMENT) + sizeof(void*)) #ifdef __cplusplus } #endif #endif mysql/server/private/sql_explain.h000064400000070534151027430560013375 0ustar00/* Copyright (c) 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* == EXPLAIN/ANALYZE architecture == === [SHOW] EXPLAIN data === Query optimization produces two data structures: 1. execution data structures themselves (eg. JOINs, JOIN_TAB, etc, etc) 2. Explain data structures. #2 are self contained set of data structures that has sufficient info to produce output of SHOW EXPLAIN, EXPLAIN [FORMAT=JSON], or ANALYZE [FORMAT=JSON], without accessing the execution data structures. (the only exception is that Explain data structures keep Item* pointers, and we require that one might call item->print(QT_EXPLAIN) when printing FORMAT=JSON output) === ANALYZE data === EXPLAIN data structures have embedded ANALYZE data structures. These are objects that are used to track how the parts of query plan were executed: how many times each part of query plan was invoked, how many rows were read/returned, etc. Each execution data structure keeps a direct pointer to its ANALYZE data structure. It is needed so that execution code can quickly increment the counters. (note that this increases the set of data that is frequently accessed during the execution. What is the impact of this?) Since ANALYZE/EXPLAIN data structures are separated from execution data structures, it is easy to have them survive until the end of the query, where we can return ANALYZE [FORMAT=JSON] output to the user, or print it into the slow query log. */ #ifndef SQL_EXPLAIN_INCLUDED #define SQL_EXPLAIN_INCLUDED class String_list: public List { public: const char *append_str(MEM_ROOT *mem_root, const char *str); }; class Json_writer; /************************************************************************************** Data structures for producing EXPLAIN outputs. These structures - Can be produced inexpensively from query plan. - Store sufficient information to produce tabular EXPLAIN output (the goal is to be able to produce JSON also) *************************************************************************************/ const uint FAKE_SELECT_LEX_ID= UINT_MAX; class Explain_query; /* A node can be either a SELECT, or a UNION. */ class Explain_node : public Sql_alloc { public: Explain_node(MEM_ROOT *root) : cache_tracker(NULL), subq_materialization(NULL), connection_type(EXPLAIN_NODE_OTHER), children(root) {} /* A type specifying what kind of node this is */ enum explain_node_type { EXPLAIN_UNION, EXPLAIN_SELECT, EXPLAIN_BASIC_JOIN, EXPLAIN_UPDATE, EXPLAIN_DELETE, EXPLAIN_INSERT }; /* How this node is connected */ enum explain_connection_type { EXPLAIN_NODE_OTHER, EXPLAIN_NODE_DERIVED, /* Materialized derived table */ EXPLAIN_NODE_NON_MERGED_SJ /* aka JTBM semi-join */ }; virtual enum explain_node_type get_type()= 0; virtual uint get_select_id()= 0; /** expression cache statistics */ Expression_cache_tracker* cache_tracker; /** If not NULL, this node is a SELECT (or UNION) in a materialized IN-subquery. */ Explain_subq_materialization* subq_materialization; /* How this node is connected to its parent. (NOTE: EXPLAIN_NODE_NON_MERGED_SJ is set very late currently) */ enum explain_connection_type connection_type; protected: /* A node may have children nodes. When a node's explain structure is created, children nodes may not yet have QPFs. This is why we store ids. */ Dynamic_array children; public: void add_child(int select_no) { children.append(select_no); } virtual int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze)=0; virtual void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze)= 0; int print_explain_for_children(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze); void print_explain_json_for_children(Explain_query *query, Json_writer *writer, bool is_analyze); bool print_explain_json_cache(Json_writer *writer, bool is_analyze); bool print_explain_json_subq_materialization(Json_writer *writer, bool is_analyze); virtual ~Explain_node() = default; }; class Explain_table_access; /* A basic join. This is only used for SJ-Materialization nests. Basic join doesn't have ORDER/GROUP/DISTINCT operations. It also cannot be degenerate. It has its own select_id. */ class Explain_basic_join : public Explain_node { public: enum explain_node_type get_type() override { return EXPLAIN_BASIC_JOIN; } Explain_basic_join(MEM_ROOT *root) : Explain_node(root), join_tabs(NULL) {} ~Explain_basic_join(); bool add_table(Explain_table_access *tab, Explain_query *query); uint get_select_id() override { return select_id; } uint select_id; int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze) override; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze) override; void print_explain_json_interns(Explain_query *query, Json_writer *writer, bool is_analyze); /* A flat array of Explain structs for tables. */ Explain_table_access** join_tabs; uint n_join_tabs; }; class Explain_aggr_node; /* EXPLAIN structure for a SELECT. A select can be: 1. A degenerate case. In this case, message!=NULL, and it contains a description of what kind of degenerate case it is (e.g. "Impossible WHERE"). 2. a non-degenrate join. In this case, join_tabs describes the join. In the non-degenerate case, a SELECT may have a GROUP BY/ORDER BY operation. In both cases, the select may have children nodes. class Explain_node provides a way get node's children. */ class Explain_select : public Explain_basic_join { public: enum explain_node_type get_type() override { return EXPLAIN_SELECT; } Explain_select(MEM_ROOT *root, bool is_analyze) : Explain_basic_join(root), #ifndef DBUG_OFF select_lex(NULL), #endif linkage(UNSPECIFIED_TYPE), is_lateral(false), message(NULL), having(NULL), having_value(Item::COND_UNDEF), using_temporary(false), using_filesort(false), time_tracker(is_analyze), aggr_tree(NULL) {} void add_linkage(Json_writer *writer); public: #ifndef DBUG_OFF SELECT_LEX *select_lex; #endif const char *select_type; enum sub_select_type linkage; bool is_lateral; /* If message != NULL, this is a degenerate join plan, and all subsequent members have no info */ const char *message; /* Expensive constant condition */ Item *exec_const_cond; Item *outer_ref_cond; Item *pseudo_bits_cond; /* HAVING condition */ Item *having; Item::cond_result having_value; /* Global join attributes. In tabular form, they are printed on the first row */ bool using_temporary; bool using_filesort; /* ANALYZE members */ Time_and_counter_tracker time_tracker; /* Part of query plan describing sorting, temp.table usage, and duplicate removal */ Explain_aggr_node* aggr_tree; int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze) override; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze) override; Table_access_tracker *get_using_temporary_read_tracker() { return &using_temporary_read_tracker; } private: Table_access_tracker using_temporary_read_tracker; }; ///////////////////////////////////////////////////////////////////////////// // EXPLAIN structures for ORDER/GROUP operations. ///////////////////////////////////////////////////////////////////////////// typedef enum { AGGR_OP_TEMP_TABLE, AGGR_OP_FILESORT, //AGGR_OP_READ_SORTED_FILE, // need this? AGGR_OP_REMOVE_DUPLICATES, AGGR_OP_WINDOW_FUNCS //AGGR_OP_JOIN // Need this? } enum_explain_aggr_node_type; class Explain_aggr_node : public Sql_alloc { public: virtual enum_explain_aggr_node_type get_type()= 0; virtual ~Explain_aggr_node() = default; Explain_aggr_node *child; }; class Explain_aggr_filesort : public Explain_aggr_node { List sort_items; List sort_directions; public: enum_explain_aggr_node_type get_type() override { return AGGR_OP_FILESORT; } Filesort_tracker tracker; Explain_aggr_filesort(MEM_ROOT *mem_root, bool is_analyze, Filesort *filesort); void print_json_members(Json_writer *writer, bool is_analyze); }; class Explain_aggr_tmp_table : public Explain_aggr_node { public: enum_explain_aggr_node_type get_type() override { return AGGR_OP_TEMP_TABLE; } }; class Explain_aggr_remove_dups : public Explain_aggr_node { public: enum_explain_aggr_node_type get_type() override { return AGGR_OP_REMOVE_DUPLICATES; } }; class Explain_aggr_window_funcs : public Explain_aggr_node { List sorts; public: enum_explain_aggr_node_type get_type() override { return AGGR_OP_WINDOW_FUNCS; } void print_json_members(Json_writer *writer, bool is_analyze); friend class Window_funcs_computation; }; ///////////////////////////////////////////////////////////////////////////// extern const char *unit_operation_text[4]; extern const char *pushed_derived_text; extern const char *pushed_select_text; /* Explain structure for a UNION. A UNION may or may not have "Using filesort". */ class Explain_union : public Explain_node { public: Explain_union(MEM_ROOT *root, bool is_analyze) : Explain_node(root), union_members(PSI_INSTRUMENT_MEM), is_recursive_cte(false), fake_select_lex_explain(root, is_analyze) {} enum explain_node_type get_type() override { return EXPLAIN_UNION; } unit_common_op operation; uint get_select_id() override { DBUG_ASSERT(union_members.elements() > 0); return union_members.at(0); } /* Members of the UNION. Note: these are different from UNION's "children". Example: (select * from t1) union (select * from t2) order by (select col1 from t3 ...) here - select-from-t1 and select-from-t2 are "union members", - select-from-t3 is the only "child". */ Dynamic_array union_members; void add_select(int select_no) { union_members.append(select_no); } int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze) override; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze) override; const char *fake_select_type; bool using_filesort; bool using_tmp; bool is_recursive_cte; /* Explain data structure for "fake_select_lex" (i.e. for the degenerate SELECT that reads UNION result). It doesn't have a query plan, but we still need execution tracker, etc. */ Explain_select fake_select_lex_explain; Table_access_tracker *get_fake_select_lex_tracker() { return &fake_select_lex_tracker; } Table_access_tracker *get_tmptable_read_tracker() { return &tmptable_read_tracker; } private: uint make_union_table_name(char *buf); Table_access_tracker fake_select_lex_tracker; /* This one is for reading after ORDER BY */ Table_access_tracker tmptable_read_tracker; }; class Explain_update; class Explain_delete; class Explain_insert; /* Explain structure for a query (i.e. a statement). This should be able to survive when the query plan was deleted. Currently, we do not intend for it survive until after query's MEM_ROOT is freed. It does surivive freeing of query's items. For reference, the process of post-query cleanup is as follows: >dispatch_command | >mysql_parse | | ... | | lex_end() | | ... | | >THD::cleanup_after_query | | | ... | | | free_items() | | | ... | | dispatch_command That is, the order of actions is: - free query's Items - write to slow query log - free query's MEM_ROOT */ class Explain_query : public Sql_alloc { public: Explain_query(THD *thd, MEM_ROOT *root); ~Explain_query(); /* Add a new node */ void add_node(Explain_node *node); void add_insert_plan(Explain_insert *insert_plan_arg); void add_upd_del_plan(Explain_update *upd_del_plan_arg); /* This will return a select, or a union */ Explain_node *get_node(uint select_id); /* This will return a select (even if there is a union with this id) */ Explain_select *get_select(uint select_id); Explain_union *get_union(uint select_id); /* Produce a tabular EXPLAIN output */ int print_explain(select_result_sink *output, uint8 explain_flags, bool is_analyze); /* Send tabular EXPLAIN to the client */ int send_explain(THD *thd, bool extended); /* Return tabular EXPLAIN output as a text string */ bool print_explain_str(THD *thd, String *out_str, bool is_analyze); void print_explain_json(select_result_sink *output, bool is_analyze); /* If true, at least part of EXPLAIN can be printed */ bool have_query_plan() { return insert_plan || upd_del_plan|| get_node(1) != NULL; } void query_plan_ready(); MEM_ROOT *mem_root; Explain_update *get_upd_del_plan() { return upd_del_plan; } private: /* Explain_delete inherits from Explain_update */ Explain_update *upd_del_plan; /* Query "plan" for INSERTs */ Explain_insert *insert_plan; Dynamic_array unions; Dynamic_array selects; THD *thd; // for APC start/stop bool apc_enabled; /* Debugging aid: count how many times add_node() was called. Ideally, it should be one, we currently allow O(1) query plan saves for each select or union. The goal is not to have O(#rows_in_some_table), which is unacceptable. */ longlong operations; }; /* Some of the tags have matching text. See extra_tag_text for text names, and Explain_table_access::append_tag_name() for code to convert from tag form to text form. */ enum explain_extra_tag { ET_none= 0, /* not-a-tag */ ET_USING_INDEX_CONDITION, ET_USING_INDEX_CONDITION_BKA, ET_USING, /* For quick selects of various kinds */ ET_RANGE_CHECKED_FOR_EACH_RECORD, ET_USING_WHERE_WITH_PUSHED_CONDITION, ET_USING_WHERE, ET_NOT_EXISTS, ET_USING_INDEX, ET_FULL_SCAN_ON_NULL_KEY, ET_SKIP_OPEN_TABLE, ET_OPEN_FRM_ONLY, ET_OPEN_FULL_TABLE, ET_SCANNED_0_DATABASES, ET_SCANNED_1_DATABASE, ET_SCANNED_ALL_DATABASES, ET_USING_INDEX_FOR_GROUP_BY, ET_USING_MRR, // does not print "Using mrr". ET_DISTINCT, ET_LOOSESCAN, ET_START_TEMPORARY, ET_END_TEMPORARY, ET_FIRST_MATCH, ET_USING_JOIN_BUFFER, ET_CONST_ROW_NOT_FOUND, ET_UNIQUE_ROW_NOT_FOUND, ET_IMPOSSIBLE_ON_CONDITION, ET_TABLE_FUNCTION, ET_total }; /* Explain data structure describing join buffering use. */ class EXPLAIN_BKA_TYPE { public: EXPLAIN_BKA_TYPE() : join_alg(NULL) {} size_t join_buffer_size; bool incremental; /* NULL if no join buferring used. Other values: BNL, BNLH, BKA, BKAH. */ const char *join_alg; /* Information about MRR usage. */ StringBuffer<64> mrr_type; bool is_using_jbuf() { return (join_alg != NULL); } }; /* Data about how an index is used by some access method */ class Explain_index_use : public Sql_alloc { char *key_name; uint key_len; char *filter_name; uint filter_len; public: String_list key_parts_list; Explain_index_use() { clear(); } void clear() { key_name= NULL; key_len= (uint)-1; filter_name= NULL; filter_len= (uint)-1; } bool set(MEM_ROOT *root, KEY *key_name, uint key_len_arg); bool set_pseudo_key(MEM_ROOT *root, const char *key_name); inline const char *get_key_name() const { return key_name; } inline uint get_key_len() const { return key_len; } //inline const char *get_filter_name() const { return filter_name; } }; /* Query Plan data structure for Rowid filter. */ class Explain_rowid_filter : public Sql_alloc { public: /* Quick select used to collect the rowids into filter */ Explain_quick_select *quick; /* How many rows the above quick select is expected to return */ ha_rows rows; /* Expected selectivity for the filter */ double selectivity; /* Tracker with the information about how rowid filter is executed */ Rowid_filter_tracker *tracker; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze); /* TODO: Here should be ANALYZE members: - r_rows for the quick select - An object that tracked the table access time - real selectivity of the filter. */ }; /* QPF for quick range selects, as well as index_merge select */ class Explain_quick_select : public Sql_alloc { public: Explain_quick_select(int quick_type_arg) : quick_type(quick_type_arg) {} const int quick_type; bool is_basic() { return (quick_type == QUICK_SELECT_I::QS_TYPE_RANGE || quick_type == QUICK_SELECT_I::QS_TYPE_RANGE_DESC || quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX); } /* This is used when quick_type == QUICK_SELECT_I::QS_TYPE_RANGE */ Explain_index_use range; /* Used in all other cases */ List children; void print_extra(String *str); void print_key(String *str); void print_key_len(String *str); void print_json(Json_writer *writer); void print_extra_recursive(String *str); private: const char *get_name_by_type(); }; /* Data structure for "range checked for each record". It's a set of keys, tabular explain prints hex bitmap, json prints key names. */ typedef const char* NAME; class Explain_range_checked_fer : public Sql_alloc { public: String_list key_set; key_map keys_map; private: ha_rows full_scan, index_merge; ha_rows *keys_stat; NAME *keys_stat_names; uint keys; public: Explain_range_checked_fer() :Sql_alloc(), full_scan(0), index_merge(0), keys_stat(0), keys_stat_names(0), keys(0) {} int append_possible_keys_stat(MEM_ROOT *alloc, TABLE *table, key_map possible_keys); void collect_data(QUICK_SELECT_I *quick); void print_json(Json_writer *writer, bool is_analyze); }; /* EXPLAIN data structure for a single JOIN_TAB. */ class Explain_table_access : public Sql_alloc { public: Explain_table_access(MEM_ROOT *root, bool timed) : derived_select_number(0), non_merged_sjm_number(0), extra_tags(root), range_checked_fer(NULL), full_scan_on_null_key(false), start_dups_weedout(false), end_dups_weedout(false), where_cond(NULL), cache_cond(NULL), pushed_index_cond(NULL), sjm_nest(NULL), pre_join_sort(NULL), handler_for_stats(NULL), jbuf_unpack_tracker(timed), rowid_filter(NULL) {} ~Explain_table_access() { delete sjm_nest; } void push_extra(enum explain_extra_tag extra_tag); /* Internals */ /* id and 'select_type' are cared-of by the parent Explain_select */ StringBuffer<32> table_name; StringBuffer<32> used_partitions; String_list used_partitions_list; // valid with ET_USING_MRR StringBuffer<32> mrr_type; StringBuffer<32> firstmatch_table_name; /* Non-zero number means this is a derived table. The number can be used to find the query plan for the derived table */ int derived_select_number; /* TODO: join with the previous member. */ int non_merged_sjm_number; enum join_type type; bool used_partitions_set; /* Empty means "NULL" will be printed */ String_list possible_keys; bool rows_set; /* not set means 'NULL' should be printed */ bool filtered_set; /* not set means 'NULL' should be printed */ // Valid if ET_USING_INDEX_FOR_GROUP_BY is present bool loose_scan_is_scanning; /* Index use: key name and length. Note: that when one is accessing I_S tables, those may show use of non-existant indexes. key.key_name == NULL means 'NULL' will be shown in tabular output. key.key_len == (uint)-1 means 'NULL' will be shown in tabular output. */ Explain_index_use key; /* when type==JT_HASH_NEXT, 'key' stores the hash join pseudo-key. hash_next_key stores the table's key. */ Explain_index_use hash_next_key; String_list ref_list; ha_rows rows; double filtered; /* Contents of the 'Extra' column. Some are converted into strings, some have parameters, values for which are stored below. */ Dynamic_array extra_tags; // Valid if ET_USING tag is present Explain_quick_select *quick_info; /* Non-NULL value means this tab uses "range checked for each record" */ Explain_range_checked_fer *range_checked_fer; bool full_scan_on_null_key; // valid with ET_USING_JOIN_BUFFER EXPLAIN_BKA_TYPE bka_type; bool start_dups_weedout; bool end_dups_weedout; /* Note: lifespan of WHERE condition is less than lifespan of this object. The below two are valid if tags include "ET_USING_WHERE". (TODO: indexsubquery may put ET_USING_WHERE without setting where_cond?) */ Item *where_cond; Item *cache_cond; /* This is either pushed index condition, or BKA's index condition. (the latter refers to columns of other tables and so can only be checked by BKA code). Examine extra_tags to tell which one it is. */ Item *pushed_index_cond; Explain_basic_join *sjm_nest; /* This describes a possible filesort() call that is done before doing the join operation. */ Explain_aggr_filesort *pre_join_sort; /* ANALYZE members */ /* Tracker for reading the table */ Table_access_tracker tracker; Exec_time_tracker op_tracker; Gap_time_tracker extra_time_tracker; /* Handler object to get the handler_stats from. Notes: This pointer is only valid until notify_tables_are_closed() is called. After that, the tables may be freed or reused, together with their handler_stats objects. notify_tables_are_closed() disables printing of FORMAT=JSON output. r_engine_stats is only printed in FORMAT=JSON output, so we're fine. We do not store pointers to temporary (aka "work") tables here. Temporary tables may be freed (e.g. by JOIN::cleanup()) or re-created during query execution (when HEAP table is converted into Aria). */ handler *handler_for_stats; /* When using join buffer: Track the reads from join buffer */ Table_access_tracker jbuf_tracker; /* When using join buffer: time spent unpacking rows from the join buffer */ Time_and_counter_tracker jbuf_unpack_tracker; /* When using join buffer: time spent after unpacking rows from the join buffer. This will capture the time spent checking the Join Condition: the condition that depends on this table and preceding tables. */ Gap_time_tracker jbuf_extra_time_tracker; /* When using join buffer: Track the number of incoming record combinations */ Counter_tracker jbuf_loops_tracker; Explain_rowid_filter *rowid_filter; int print_explain(select_result_sink *output, uint8 explain_flags, bool is_analyze, uint select_id, const char *select_type, bool using_temporary, bool using_filesort); void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze); private: void append_tag_name(String *str, enum explain_extra_tag tag); void fill_key_str(String *key_str, bool is_json) const; void fill_key_len_str(String *key_len_str, bool is_json) const; double get_r_filtered(); void tag_to_json(Json_writer *writer, enum explain_extra_tag tag); }; /* EXPLAIN structure for single-table UPDATE. This is similar to Explain_table_access, except that it is more restrictive. Also, it can have UPDATE operation options, but currently there aren't any. Explain_delete inherits from this. */ class Explain_update : public Explain_node { public: Explain_update(MEM_ROOT *root, bool is_analyze) : Explain_node(root), filesort_tracker(NULL), command_tracker(is_analyze), handler_for_stats(NULL) {} enum explain_node_type get_type() override { return EXPLAIN_UPDATE; } uint get_select_id() override { return 1; /* always root */ } const char *select_type; StringBuffer<32> used_partitions; String_list used_partitions_list; bool used_partitions_set; bool impossible_where; bool no_partitions; StringBuffer<64> table_name; enum join_type jtype; String_list possible_keys; /* Used key when doing a full index scan (possibly with limit) */ Explain_index_use key; /* MRR that's used with quick select. This should probably belong to the quick select */ StringBuffer<64> mrr_type; Explain_quick_select *quick_info; bool using_where; Item *where_cond; ha_rows rows; bool using_io_buffer; /* Tracker for doing reads when filling the buffer */ Table_access_tracker buf_tracker; bool is_using_filesort() { return filesort_tracker? true: false; } /* Non-null value of filesort_tracker means "using filesort" if we are using filesort, then table_tracker is for the io done inside filesort. 'tracker' is for tracking post-filesort reads. */ Filesort_tracker *filesort_tracker; /* ANALYZE members and methods */ Table_access_tracker tracker; /* This tracks execution of the whole command */ Time_and_counter_tracker command_tracker; /* TODO: This tracks time to read rows from the table */ Exec_time_tracker table_tracker; /* The same as Explain_table_access::handler_for_stats */ handler *handler_for_stats; int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze) override; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze) override; }; /* EXPLAIN data structure for an INSERT. At the moment this doesn't do much as we don't really have any query plans for INSERT statements. */ class Explain_insert : public Explain_node { public: Explain_insert(MEM_ROOT *root) : Explain_node(root) {} StringBuffer<64> table_name; enum explain_node_type get_type() override { return EXPLAIN_INSERT; } uint get_select_id() override { return 1; /* always root */ } int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze) override; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze) override; }; /* EXPLAIN data of a single-table DELETE. */ class Explain_delete: public Explain_update { public: Explain_delete(MEM_ROOT *root, bool is_analyze) : Explain_update(root, is_analyze) {} /* TRUE means we're going to call handler->delete_all_rows() and not read any rows. */ bool deleting_all_rows; enum explain_node_type get_type() override { return EXPLAIN_DELETE; } uint get_select_id() override { return 1; /* always root */ } int print_explain(Explain_query *query, select_result_sink *output, uint8 explain_flags, bool is_analyze) override; void print_explain_json(Explain_query *query, Json_writer *writer, bool is_analyze) override; }; /* EXPLAIN data structure for subquery materialization. All decisions are made at execution time so here we just store the tracker that has all the info. */ class Explain_subq_materialization : public Sql_alloc { public: Explain_subq_materialization(MEM_ROOT *mem_root) : tracker(mem_root) {} Subq_materialization_tracker *get_tracker() { return &tracker; } void print_explain_json(Json_writer *writer, bool is_analyze); private: Subq_materialization_tracker tracker; }; #endif //SQL_EXPLAIN_INCLUDED mysql/server/private/wsrep_client_service.h000064400000005000151027430560015256 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file wsrep_client_service.h This file provides declaratios for client service implementation. See wsrep/client_service.hpp for interface documentation. */ #ifndef WSREP_CLIENT_SERVICE_H #define WSREP_CLIENT_SERVICE_H /* wsrep-lib */ #include "wsrep/client_service.hpp" #include "wsrep/client_state.hpp" #include "wsrep/exception.hpp" /* not_implemented_error, remove when finished */ class THD; class Wsrep_client_state; class Wsrep_high_priority_context; class Wsrep_client_service : public wsrep::client_service { public: Wsrep_client_service(THD*, Wsrep_client_state&); bool interrupted(wsrep::unique_lock&) const override; void reset_globals() override; void store_globals() override; int prepare_data_for_replication() override; void cleanup_transaction() override; bool statement_allowed_for_streaming() const override; size_t bytes_generated() const override; int prepare_fragment_for_replication(wsrep::mutable_buffer&, size_t&) override; int remove_fragments() override; void emergency_shutdown() override { throw wsrep::not_implemented_error(); } void will_replay() override; void signal_replayed() override; enum wsrep::provider::status replay() override; enum wsrep::provider::status replay_unordered() override; void wait_for_replayers(wsrep::unique_lock&) override; enum wsrep::provider::status commit_by_xid() override; bool is_explicit_xa() override { return false; } bool is_prepared_xa() override { return false; } bool is_xa_rollback() override { return false; } void debug_sync(const char*) override; void debug_crash(const char*) override; int bf_rollback() override; private: friend class Wsrep_server_service; THD* m_thd; Wsrep_client_state& m_client_state; }; #endif /* WSREP_CLIENT_SERVICE_H */ mysql/server/private/ddl_log.h000064400000030615151027430560012456 0ustar00/* Copyright (c) 2000, 2019, Oracle and/or its affiliates. Copyright (c) 2010, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* External interfaces to ddl log functions */ #ifndef DDL_LOG_INCLUDED #define DDL_LOG_INCLUDED enum ddl_log_entry_code { /* DDL_LOG_UNKOWN Here mainly to detect blocks that are all zero DDL_LOG_EXECUTE_CODE: This is a code that indicates that this is a log entry to be executed, from this entry a linked list of log entries can be found and executed. DDL_LOG_ENTRY_CODE: An entry to be executed in a linked list from an execute log entry. DDL_LOG_IGNORE_ENTRY_CODE: An entry that is to be ignored */ DDL_LOG_UNKNOWN= 0, DDL_LOG_EXECUTE_CODE= 1, DDL_LOG_ENTRY_CODE= 2, DDL_LOG_IGNORE_ENTRY_CODE= 3, DDL_LOG_ENTRY_CODE_LAST= 4 }; /* When adding things below, also add an entry to ddl_log_action_names and ddl_log_entry_phases in ddl_log.cc */ enum ddl_log_action_code { /* The type of action that a DDL_LOG_ENTRY_CODE entry is to perform. */ DDL_LOG_UNKNOWN_ACTION= 0, /* Delete a .frm file or a table in the partition engine */ DDL_LOG_DELETE_ACTION= 1, /* Rename a .frm fire a table in the partition engine */ DDL_LOG_RENAME_ACTION= 2, /* Rename an entity after removing the previous entry with the new name, that is replace this entry. */ DDL_LOG_REPLACE_ACTION= 3, /* Exchange two entities by renaming them a -> tmp, b -> a, tmp -> b */ DDL_LOG_EXCHANGE_ACTION= 4, /* log do_rename(): Rename of .frm file, table, stat_tables and triggers */ DDL_LOG_RENAME_TABLE_ACTION= 5, DDL_LOG_RENAME_VIEW_ACTION= 6, DDL_LOG_DROP_INIT_ACTION= 7, DDL_LOG_DROP_TABLE_ACTION= 8, DDL_LOG_DROP_VIEW_ACTION= 9, DDL_LOG_DROP_TRIGGER_ACTION= 10, DDL_LOG_DROP_DB_ACTION=11, DDL_LOG_CREATE_TABLE_ACTION=12, DDL_LOG_CREATE_VIEW_ACTION=13, DDL_LOG_DELETE_TMP_FILE_ACTION=14, DDL_LOG_CREATE_TRIGGER_ACTION=15, DDL_LOG_ALTER_TABLE_ACTION=16, DDL_LOG_STORE_QUERY_ACTION=17, DDL_LOG_LAST_ACTION /* End marker */ }; /* Number of phases for each ddl_log_action_code */ extern const uchar ddl_log_entry_phases[DDL_LOG_LAST_ACTION]; enum enum_ddl_log_exchange_phase { EXCH_PHASE_NAME_TO_TEMP= 0, EXCH_PHASE_FROM_TO_NAME= 1, EXCH_PHASE_TEMP_TO_FROM= 2, EXCH_PHASE_END }; enum enum_ddl_log_rename_table_phase { DDL_RENAME_PHASE_TRIGGER= 0, DDL_RENAME_PHASE_STAT, DDL_RENAME_PHASE_TABLE, DDL_RENAME_PHASE_END }; enum enum_ddl_log_drop_table_phase { DDL_DROP_PHASE_TABLE=0, DDL_DROP_PHASE_TRIGGER, DDL_DROP_PHASE_BINLOG, DDL_DROP_PHASE_RESET, /* Reset found list of dropped tables */ DDL_DROP_PHASE_END }; enum enum_ddl_log_drop_db_phase { DDL_DROP_DB_PHASE_INIT=0, DDL_DROP_DB_PHASE_LOG, DDL_DROP_DB_PHASE_END }; enum enum_ddl_log_create_table_phase { DDL_CREATE_TABLE_PHASE_INIT=0, DDL_CREATE_TABLE_PHASE_LOG, DDL_CREATE_TABLE_PHASE_END }; enum enum_ddl_log_create_view_phase { DDL_CREATE_VIEW_PHASE_NO_OLD_VIEW, DDL_CREATE_VIEW_PHASE_DELETE_VIEW_COPY, DDL_CREATE_VIEW_PHASE_OLD_VIEW_COPIED, DDL_CREATE_VIEW_PHASE_END }; enum enum_ddl_log_create_trigger_phase { DDL_CREATE_TRIGGER_PHASE_NO_OLD_TRIGGER, DDL_CREATE_TRIGGER_PHASE_DELETE_COPY, DDL_CREATE_TRIGGER_PHASE_OLD_COPIED, DDL_CREATE_TRIGGER_PHASE_END }; enum enum_ddl_log_alter_table_phase { DDL_ALTER_TABLE_PHASE_INIT, DDL_ALTER_TABLE_PHASE_RENAME_FAILED, DDL_ALTER_TABLE_PHASE_INPLACE_COPIED, DDL_ALTER_TABLE_PHASE_INPLACE, DDL_ALTER_TABLE_PHASE_PREPARE_INPLACE, DDL_ALTER_TABLE_PHASE_CREATED, DDL_ALTER_TABLE_PHASE_COPIED, DDL_ALTER_TABLE_PHASE_OLD_RENAMED, DDL_ALTER_TABLE_PHASE_UPDATE_TRIGGERS, DDL_ALTER_TABLE_PHASE_UPDATE_STATS, DDL_ALTER_TABLE_PHASE_UPDATE_BINARY_LOG, DDL_ALTER_TABLE_PHASE_END }; /* Flags stored in DDL_LOG_ENTRY.flags The flag values can be reused for different commands */ #define DDL_LOG_FLAG_ALTER_RENAME (1 << 0) #define DDL_LOG_FLAG_ALTER_ENGINE_CHANGED (1 << 1) #define DDL_LOG_FLAG_ONLY_FRM (1 << 2) #define DDL_LOG_FLAG_UPDATE_STAT (1 << 3) /* Set when using ALTER TABLE on a partitioned table and the table engine is not changed */ #define DDL_LOG_FLAG_ALTER_PARTITION (1 << 4) /* Setting ddl_log_entry.phase to this has the same effect as setting the phase to the maximum phase (..PHASE_END) for an entry. */ #define DDL_LOG_FINAL_PHASE ((uchar) 0xff) typedef struct st_ddl_log_entry { LEX_CSTRING name; LEX_CSTRING from_name; LEX_CSTRING handler_name; LEX_CSTRING db; LEX_CSTRING from_db; LEX_CSTRING from_handler_name; LEX_CSTRING tmp_name; /* frm file or temporary file name */ LEX_CSTRING extra_name; /* Backup table name */ uchar uuid[MY_UUID_SIZE]; // UUID for new frm file ulonglong xid; // Xid stored in the binary log /* unique_id can be used to store a unique number to check current state. Currently it is used to store new size of frm file, link to another ddl log entry or store an a uniq version for a storage engine in alter table. For execute entries this is reused as an execute counter to ensure we don't repeat an entry too many times if executing the entry fails. */ ulonglong unique_id; uint next_entry; uint entry_pos; // Set by write_dll_log_entry() uint16 flags; // Flags unique for each command enum ddl_log_entry_code entry_type; // Set automatically enum ddl_log_action_code action_type; /* Most actions have only one phase. REPLACE does however have two phases. The first phase removes the file with the new name if there was one there before and the second phase renames the old name to the new name. */ uchar phase; // set automatically } DDL_LOG_ENTRY; typedef struct st_ddl_log_memory_entry { uint entry_pos; struct st_ddl_log_memory_entry *next_log_entry; struct st_ddl_log_memory_entry *prev_log_entry; struct st_ddl_log_memory_entry *next_active_log_entry; } DDL_LOG_MEMORY_ENTRY; /* State of the ddl log during execution of a DDL. A ddl log state has one execute entry (main entry pointing to the first action entry) and many 'action entries' linked in a list in the order they should be executed. One recovery the log is parsed and all execute entries will be executed. All entries are stored as separate blocks in the ddl recovery file. */ typedef struct st_ddl_log_state { /* List of ddl log entries */ DDL_LOG_MEMORY_ENTRY *list; /* One execute entry per list */ DDL_LOG_MEMORY_ENTRY *execute_entry; /* Entry used for PHASE updates. Normally same as first in 'list', but in case of a query log event, this points to the main event. */ DDL_LOG_MEMORY_ENTRY *main_entry; uint16 flags; /* Cache for flags */ bool is_active() { return list != 0; } } DDL_LOG_STATE; /* These functions are for recovery */ bool ddl_log_initialize(); void ddl_log_release(); bool ddl_log_close_binlogged_events(HASH *xids); int ddl_log_execute_recovery(); /* functions for updating the ddl log */ bool ddl_log_write_entry(DDL_LOG_ENTRY *ddl_log_entry, DDL_LOG_MEMORY_ENTRY **active_entry); bool ddl_log_write_execute_entry(uint first_entry, DDL_LOG_MEMORY_ENTRY **active_entry); bool ddl_log_disable_execute_entry(DDL_LOG_MEMORY_ENTRY **active_entry); void ddl_log_complete(DDL_LOG_STATE *ddl_log_state); bool ddl_log_revert(THD *thd, DDL_LOG_STATE *ddl_log_state); bool ddl_log_update_phase(DDL_LOG_STATE *entry, uchar phase); bool ddl_log_add_flag(DDL_LOG_STATE *entry, uint16 flag); bool ddl_log_update_unique_id(DDL_LOG_STATE *state, ulonglong id); bool ddl_log_update_xid(DDL_LOG_STATE *state, ulonglong xid); bool ddl_log_disable_entry(DDL_LOG_STATE *state); bool ddl_log_increment_phase(uint entry_pos); void ddl_log_release_memory_entry(DDL_LOG_MEMORY_ENTRY *log_entry); bool ddl_log_sync(); bool ddl_log_execute_entry(THD *thd, uint first_entry); void ddl_log_release_entries(DDL_LOG_STATE *ddl_log_state); bool ddl_log_rename_table(THD *thd, DDL_LOG_STATE *ddl_state, handlerton *hton, const LEX_CSTRING *org_db, const LEX_CSTRING *org_alias, const LEX_CSTRING *new_db, const LEX_CSTRING *new_alias); bool ddl_log_rename_view(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *org_db, const LEX_CSTRING *org_alias, const LEX_CSTRING *new_db, const LEX_CSTRING *new_alias); bool ddl_log_drop_table_init(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *db, const LEX_CSTRING *comment); bool ddl_log_drop_view_init(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *db); bool ddl_log_drop_table(THD *thd, DDL_LOG_STATE *ddl_state, handlerton *hton, const LEX_CSTRING *path, const LEX_CSTRING *db, const LEX_CSTRING *table); bool ddl_log_drop_view(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *path, const LEX_CSTRING *db, const LEX_CSTRING *table); bool ddl_log_drop_trigger(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *db, const LEX_CSTRING *table, const LEX_CSTRING *trigger_name, const LEX_CSTRING *query); bool ddl_log_drop_view(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *path, const LEX_CSTRING *db, const LEX_CSTRING *table); bool ddl_log_drop_view(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *db); bool ddl_log_drop_db(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *db, const LEX_CSTRING *path); bool ddl_log_create_table(THD *thd, DDL_LOG_STATE *ddl_state, handlerton *hton, const LEX_CSTRING *path, const LEX_CSTRING *db, const LEX_CSTRING *table, bool only_frm); bool ddl_log_create_view(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *path, enum_ddl_log_create_view_phase phase); bool ddl_log_delete_tmp_file(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *path, DDL_LOG_STATE *depending_state); bool ddl_log_create_trigger(THD *thd, DDL_LOG_STATE *ddl_state, const LEX_CSTRING *db, const LEX_CSTRING *table, const LEX_CSTRING *trigger_name, enum_ddl_log_create_trigger_phase phase); bool ddl_log_alter_table(THD *thd, DDL_LOG_STATE *ddl_state, handlerton *org_hton, const LEX_CSTRING *db, const LEX_CSTRING *table, handlerton *new_hton, handlerton *partition_underlying_hton, const LEX_CSTRING *new_db, const LEX_CSTRING *new_table, const LEX_CSTRING *frm_path, const LEX_CSTRING *backup_table_name, const LEX_CUSTRING *version, ulonglong table_version, bool is_renamed); bool ddl_log_store_query(THD *thd, DDL_LOG_STATE *ddl_log_state, const char *query, size_t length); extern mysql_mutex_t LOCK_gdl; #endif /* DDL_LOG_INCLUDED */ mysql/server/private/pfs_memory_provider.h000064400000003132151027430560015136 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_MEMORY_PROVIDER_H #define PFS_MEMORY_PROVIDER_H /** @file include/pfs_memory_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_MEMORY_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_MEMORY_CALL(M) pfs_ ## M ## _v1 C_MODE_START void pfs_register_memory_v1 (const char *category, struct PSI_memory_info_v1 *info, int count); PSI_memory_key pfs_memory_alloc_v1 (PSI_memory_key key, size_t size, PSI_thread **owner); PSI_memory_key pfs_memory_realloc_v1 (PSI_memory_key key, size_t old_size, size_t new_size, PSI_thread **owner); void pfs_memory_free_v1 (PSI_memory_key key, size_t size, PSI_thread *owner); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_MEMORY_INTERFACE */ #endif mysql/server/private/sql_connect.h000064400000007767151027430560013376 0ustar00/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_CONNECT_INCLUDED #define SQL_CONNECT_INCLUDED #include /* pthread_handler_t */ #include "mysql_com.h" /* enum_server_command */ #include "structs.h" #include #include #include "violite.h" /* Object to hold connect information to be given to the newly created thread */ struct scheduler_functions; class CONNECT : public ilink { public: MYSQL_SOCKET sock; #ifdef _WIN32 HANDLE pipe; CONNECT(HANDLE pipe_arg): pipe(pipe_arg), vio_type(VIO_TYPE_NAMEDPIPE), scheduler(thread_scheduler), thread_id(0), prior_thr_create_utime(0) { count++; } #endif enum enum_vio_type vio_type; scheduler_functions *scheduler; my_thread_id thread_id; /* Own variables */ ulonglong prior_thr_create_utime; static Atomic_counter count; CONNECT(MYSQL_SOCKET sock_arg, enum enum_vio_type vio_type_arg, scheduler_functions *scheduler_arg): sock(sock_arg), vio_type(vio_type_arg), scheduler(scheduler_arg), thread_id(0), prior_thr_create_utime(0) { count++; } ~CONNECT() { count--; DBUG_ASSERT(vio_type == VIO_CLOSED); } void close_and_delete(uint err); void close_with_error(uint sql_errno, const char *message, uint close_error); THD *create_thd(THD *thd); }; class THD; typedef struct user_conn USER_CONN; void init_max_user_conn(void); void init_global_user_stats(void); void init_global_table_stats(void); void init_global_index_stats(void); void init_global_client_stats(void); void free_max_user_conn(void); void free_global_user_stats(void); void free_global_table_stats(void); void free_global_index_stats(void); void free_global_client_stats(void); pthread_handler_t handle_one_connection(void *arg); void do_handle_one_connection(CONNECT *connect, bool put_in_cache); bool init_new_connection_handler_thread(); void reset_mqh(LEX_USER *lu, bool get_them); bool check_mqh(THD *thd, uint check_command); void time_out_user_resource_limits(THD *thd, USER_CONN *uc); #ifndef NO_EMBEDDED_ACCESS_CHECKS void decrease_user_connections(USER_CONN *uc); #else #define decrease_user_connections(X) do { } while(0) /* nothing */ #endif bool thd_init_client_charset(THD *thd, uint cs_number); void setup_connection_thread_globals(THD *thd); bool thd_prepare_connection(THD *thd); bool thd_is_connection_alive(THD *thd); int thd_set_peer_addr(THD *thd, sockaddr_storage *addr, const char *ip, uint port, bool check_proxy_networks, uint *host_errors); bool login_connection(THD *thd); void prepare_new_connection_state(THD* thd); void end_connection(THD *thd); void update_global_user_stats(THD* thd, bool create_user, time_t now); int get_or_create_user_conn(THD *thd, const char *user, const char *host, const USER_RESOURCES *mqh); int check_for_max_user_connections(THD *thd, USER_CONN *uc); extern HASH global_user_stats; extern HASH global_client_stats; extern HASH global_table_stats; extern HASH global_index_stats; extern mysql_mutex_t LOCK_global_user_client_stats; extern mysql_mutex_t LOCK_global_table_stats; extern mysql_mutex_t LOCK_global_index_stats; extern mysql_mutex_t LOCK_stats; #endif /* SQL_CONNECT_INCLUDED */ mysql/server/private/protocol.h000064400000030312151027430560012705 0ustar00#ifndef PROTOCOL_INCLUDED #define PROTOCOL_INCLUDED /* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_error.h" #include "my_decimal.h" /* my_decimal */ #include "sql_type.h" class i_string; class Field; class Send_field; class THD; class Item_param; struct TABLE_LIST; typedef struct st_mysql_field MYSQL_FIELD; typedef struct st_mysql_rows MYSQL_ROWS; class Protocol { protected: String *packet; /* Used by net_store_data() for charset conversions */ String *convert; uint field_pos; #ifndef DBUG_OFF const Type_handler **field_handlers; bool valid_handler(uint pos, protocol_send_type_t type) const { return field_handlers == 0 || field_handlers[field_pos]->protocol_send_type() == type; } #endif uint field_count; virtual bool net_store_data(const uchar *from, size_t length); virtual bool net_store_data_cs(const uchar *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs); virtual bool net_send_ok(THD *, uint, uint, ulonglong, ulonglong, const char *, bool); virtual bool net_send_error_packet(THD *, uint, const char *, const char *); #ifdef EMBEDDED_LIBRARY char **next_field; MYSQL_FIELD *next_mysql_field; MEM_ROOT *alloc; #endif bool needs_conversion(CHARSET_INFO *fromcs, CHARSET_INFO *tocs) const { // 'tocs' is set 0 when client issues SET character_set_results=NULL return tocs && !my_charset_same(fromcs, tocs) && fromcs != &my_charset_bin && tocs != &my_charset_bin; } /* The following two are low-level functions that are invoked from higher-level store_xxx() funcs. The data is stored into this->packet. */ bool store_string_aux(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs); virtual bool send_ok(uint server_status, uint statement_warn_count, ulonglong affected_rows, ulonglong last_insert_id, const char *message); virtual bool send_eof(uint server_status, uint statement_warn_count); virtual bool send_error(uint sql_errno, const char *err_msg, const char *sql_state); CHARSET_INFO *character_set_results() const; public: THD *thd; Protocol(THD *thd_arg) { init(thd_arg); } virtual ~Protocol() = default; void init(THD* thd_arg); enum { SEND_NUM_ROWS= 1, SEND_EOF= 2, SEND_FORCE_COLUMN_INFO= 4 }; virtual bool send_result_set_metadata(List *list, uint flags); bool send_list_fields(List *list, const TABLE_LIST *table_list); bool send_result_set_row(List *row_items); bool store(I_List *str_list); bool store_string_or_null(const char *from, CHARSET_INFO *cs); bool store_warning(const char *from, size_t length); String *storage_packet() { return packet; } inline void free() { packet->free(); } virtual bool write(); inline bool store(int from) { return store_long((longlong) from); } inline bool store(uint32 from) { return store_long((longlong) from); } inline bool store(longlong from) { return store_longlong((longlong) from, 0); } inline bool store(ulonglong from) { return store_longlong((longlong) from, 1); } inline bool store(String *str) { return store((char*) str->ptr(), str->length(), str->charset()); } inline bool store(const LEX_CSTRING *from, CHARSET_INFO *cs) { return store(from->str, from->length, cs); } virtual bool prepare_for_send(uint num_columns) { field_count= num_columns; return 0; } virtual bool flush(); virtual void end_partial_result_set(THD *thd); virtual void prepare_for_resend()=0; virtual bool store_null()=0; virtual bool store_tiny(longlong from)=0; virtual bool store_short(longlong from)=0; virtual bool store_long(longlong from)=0; virtual bool store_longlong(longlong from, bool unsigned_flag)=0; virtual bool store_decimal(const my_decimal *)=0; virtual bool store_str(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs)=0; virtual bool store_float(float from, uint32 decimals)=0; virtual bool store_double(double from, uint32 decimals)=0; virtual bool store_datetime(MYSQL_TIME *time, int decimals)=0; virtual bool store_date(MYSQL_TIME *time)=0; virtual bool store_time(MYSQL_TIME *time, int decimals)=0; virtual bool store(Field *field)=0; // Various useful wrappers for the virtual store*() methods. // Backward wrapper for store_str() bool store(const char *from, size_t length, CHARSET_INFO *cs) { return store_str(from, length, cs, character_set_results()); } bool store_lex_cstring(const LEX_CSTRING &s, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) { return store_str(s.str, (uint) s.length, fromcs, tocs); } bool store_binary_string(const char *str, size_t length) { return store_str(str, (uint) length, &my_charset_bin, &my_charset_bin); } bool store_ident(const LEX_CSTRING &s) { return store_lex_cstring(s, system_charset_info, character_set_results()); } // End of wrappers virtual bool send_out_parameters(List *sp_params)=0; #ifdef EMBEDDED_LIBRARY bool begin_dataset(); bool begin_dataset(THD *thd, uint numfields); virtual void remove_last_row() {} #else void remove_last_row() {} #endif enum enum_protocol_type { /* Before adding a new type, please make sure there is enough storage for it in Query_cache_query_flags. */ PROTOCOL_TEXT= 0, PROTOCOL_BINARY= 1, PROTOCOL_LOCAL= 2, PROTOCOL_DISCARD= 3 /* Should be last, not used by Query_cache */ }; virtual enum enum_protocol_type type()= 0; virtual bool net_send_eof(THD *thd, uint server_status, uint statement_warn_count); bool net_send_error(THD *thd, uint sql_errno, const char *err, const char* sqlstate); void end_statement(); }; /** Class used for the old (MySQL 4.0 protocol). */ class Protocol_text :public Protocol { StringBuffer buffer; bool store_numeric_string_aux(const char *from, size_t length); public: Protocol_text(THD *thd_arg, ulong prealloc= 0) :Protocol(thd_arg) { if (prealloc) packet->alloc(prealloc); } void prepare_for_resend() override; bool store_null() override; bool store_tiny(longlong from) override; bool store_short(longlong from) override; bool store_long(longlong from) override; bool store_longlong(longlong from, bool unsigned_flag) override; bool store_decimal(const my_decimal *) override; bool store_str(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) override; bool store_datetime(MYSQL_TIME *time, int decimals) override; bool store_date(MYSQL_TIME *time) override; bool store_time(MYSQL_TIME *time, int decimals) override; bool store_float(float nr, uint32 decimals) override; bool store_double(double from, uint32 decimals) override; bool store(Field *field) override; bool send_out_parameters(List *sp_params) override; bool store_numeric_zerofill_str(const char *from, size_t length, protocol_send_type_t send_type); #ifdef EMBEDDED_LIBRARY void remove_last_row() override; #endif bool store_field_metadata(const THD *thd, const Send_field &field, CHARSET_INFO *charset_for_protocol, uint pos); bool store_item_metadata(THD *thd, Item *item, uint pos); bool store_field_metadata_for_list_fields(const THD *thd, Field *field, const TABLE_LIST *table_list, uint pos); enum enum_protocol_type type() override { return PROTOCOL_TEXT; }; }; class Protocol_binary final :public Protocol { private: uint bit_fields; public: Protocol_binary(THD *thd_arg) :Protocol(thd_arg) {} bool prepare_for_send(uint num_columns) override; void prepare_for_resend() override; #ifdef EMBEDDED_LIBRARY bool write() override; bool net_store_data(const uchar *from, size_t length) override; bool net_store_data_cs(const uchar *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) override; #endif bool store_null() override; bool store_tiny(longlong from) override; bool store_short(longlong from) override; bool store_long(longlong from) override; bool store_longlong(longlong from, bool unsigned_flag) override; bool store_decimal(const my_decimal *) override; bool store_str(const char *from, size_t length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs) override; bool store_datetime(MYSQL_TIME *time, int decimals) override; bool store_date(MYSQL_TIME *time) override; bool store_time(MYSQL_TIME *time, int decimals) override; bool store_float(float nr, uint32 decimals) override; bool store_double(double from, uint32 decimals) override; bool store(Field *field) override; bool send_out_parameters(List *sp_params) override; enum enum_protocol_type type() override { return PROTOCOL_BINARY; }; }; /* A helper for "ANALYZE $stmt" which looks a real network procotol but doesn't write results to the network. At first glance, class select_send looks like a more appropriate place to implement the "write nothing" hook. This is not true, because - we need to evaluate the value of every item, and do it the way select_send does it (i.e. call item->val_int() or val_real() or...) - select_send::send_data() has some other code, like telling the storage engine that the row can be unlocked. We want to keep that also. as a result, "ANALYZE $stmt" uses a select_send_analyze which still uses select_send::send_data() & co., and also uses Protocol_discard object. */ class Protocol_discard final : public Protocol { public: Protocol_discard(THD *thd_arg) : Protocol(thd_arg) {} bool write() override { return 0; } bool send_result_set_metadata(List *, uint) override { return 0; } bool send_eof(uint, uint) override { return 0; } void prepare_for_resend() override { IF_DBUG(field_pos= 0,); } bool send_out_parameters(List *sp_params) override { return false; } /* Provide dummy overrides for any storage methods so that we avoid allocating and copying of data */ bool store_null() override { return false; } bool store_tiny(longlong) override { return false; } bool store_short(longlong) override { return false; } bool store_long(longlong) override { return false; } bool store_longlong(longlong, bool) override { return false; } bool store_decimal(const my_decimal *) override { return false; } bool store_str(const char *, size_t, CHARSET_INFO *, CHARSET_INFO *) override { return false; } bool store_datetime(MYSQL_TIME *, int) override { return false; } bool store_date(MYSQL_TIME *) override { return false; } bool store_time(MYSQL_TIME *, int) override { return false; } bool store_float(float, uint32) override { return false; } bool store_double(double, uint32) override { return false; } bool store(Field *) override { return false; } enum enum_protocol_type type() override { return PROTOCOL_DISCARD; }; }; void send_warning(THD *thd, uint sql_errno, const char *err=0); void net_send_progress_packet(THD *thd); uchar *net_store_data(uchar *to,const uchar *from, size_t length); uchar *net_store_data(uchar *to,int32 from); uchar *net_store_data(uchar *to,longlong from); #endif /* PROTOCOL_INCLUDED */ mysql/server/private/field_comp.h000064400000002226151027430560013150 0ustar00#ifndef FIELD_COMP_H_INCLUDED #define FIELD_COMP_H_INCLUDED /* Copyright (C) 2017 MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define MAX_COMPRESSION_METHODS 16 struct Compression_method { const char *name; uint (*compress)(THD *thd, char *to, const char *from, uint length); int (*uncompress)(String *to, const uchar *from, uint from_length, uint field_length); }; extern Compression_method compression_methods[MAX_COMPRESSION_METHODS]; #define zlib_compression_method (&compression_methods[8]) #endif mysql/server/private/rpl_record_old.h000064400000002577151027430560014051 0ustar00/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_RECORD_OLD_H #define RPL_RECORD_OLD_H #include "log_event.h" /* Log_event_type */ #ifndef MYSQL_CLIENT size_t pack_row_old(TABLE *table, MY_BITMAP const* cols, uchar *row_data, const uchar *record); #ifdef HAVE_REPLICATION int unpack_row_old(rpl_group_info *rgi, TABLE *table, uint const colcnt, uchar *record, uchar const *row, uchar const *row_buffer_end, MY_BITMAP const *cols, uchar const **row_end, ulong *master_reclength, MY_BITMAP* const rw_set, Log_event_type const event_type); #endif #endif #endif mysql/server/private/sql_cache.h000064400000052254151027430560012777 0ustar00/* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _SQL_CACHE_H #define _SQL_CACHE_H #include "hash.h" #include "my_base.h" /* ha_rows */ class MY_LOCALE; struct TABLE_LIST; class Time_zone; struct LEX; struct TABLE; typedef struct st_changed_table_list CHANGED_TABLE_LIST; /* Query cache */ /* Can't create new free memory block if unused memory in block less then QUERY_CACHE_MIN_ALLOCATION_UNIT. if QUERY_CACHE_MIN_ALLOCATION_UNIT == 0 then QUERY_CACHE_MIN_ALLOCATION_UNIT choosed automatically */ #define QUERY_CACHE_MIN_ALLOCATION_UNIT 512 /* inittial size of hashes */ #define QUERY_CACHE_DEF_QUERY_HASH_SIZE 1024 #define QUERY_CACHE_DEF_TABLE_HASH_SIZE 1024 /* minimal result data size when data allocated */ #define QUERY_CACHE_MIN_RESULT_DATA_SIZE (1024*4) /* start estimation of first result block size only when number of queries bigger then: */ #define QUERY_CACHE_MIN_ESTIMATED_QUERIES_NUMBER 3 /* memory bins size spacing (see at Query_cache::init_cache (sql_cache.cc)) */ #define QUERY_CACHE_MEM_BIN_FIRST_STEP_PWR2 4 #define QUERY_CACHE_MEM_BIN_STEP_PWR2 2 #define QUERY_CACHE_MEM_BIN_PARTS_INC 1 #define QUERY_CACHE_MEM_BIN_PARTS_MUL 1.2 #define QUERY_CACHE_MEM_BIN_SPC_LIM_PWR2 3 /* how many free blocks check when finding most suitable before other 'end' of list of free blocks */ #define QUERY_CACHE_MEM_BIN_TRY 5 /* packing parameters */ #define QUERY_CACHE_PACK_ITERATION 2 #define QUERY_CACHE_PACK_LIMIT (512*1024L) #define TABLE_COUNTER_TYPE uint struct Query_cache_block; struct Query_cache_block_table; struct Query_cache_table; struct Query_cache_query; struct Query_cache_result; class Query_cache; struct Query_cache_tls; struct LEX; class THD; typedef my_bool (*qc_engine_callback)(THD *thd, const char *table_key, uint key_length, ulonglong *engine_data); /** This class represents a node in the linked chain of queries belonging to one table. @note The root of this linked list is not a query-type block, but the table- type block which all queries has in common. */ struct Query_cache_block_table { Query_cache_block_table() = default; /* Remove gcc warning */ /** This node holds a position in a static table list belonging to the associated query (base 0). */ TABLE_COUNTER_TYPE n; /** Pointers to the next and previous node, linking all queries with a common table. */ Query_cache_block_table *next, *prev; /** A pointer to the table-type block which all linked queries has in common. */ Query_cache_table *parent; /** A method to calculate the address of the query cache block owning this node. The purpose of this calculation is to make it easier to move the query cache block without having to modify all the pointer addresses. */ inline Query_cache_block *block(); }; struct Query_cache_block { Query_cache_block() = default; /* Remove gcc warning */ enum block_type {FREE, QUERY, RESULT, RES_CONT, RES_BEG, RES_INCOMPLETE, TABLE, INCOMPLETE}; size_t length; // length of all block size_t used; // length of data /* Not used **pprev, **prev because really needed access to pervious block: *pprev to join free blocks *prev to access to opposite side of list in cyclic sorted list */ Query_cache_block *pnext,*pprev, // physical next/previous block *next,*prev; // logical next/previous block block_type type; TABLE_COUNTER_TYPE n_tables; // number of tables in query inline bool is_free(void) { return type == FREE; } void init(size_t length); void destroy(); uint headers_len() const; uchar* data(void) const; Query_cache_query *query(); Query_cache_table *table(); Query_cache_result *result(); Query_cache_block_table *table(TABLE_COUNTER_TYPE n); }; struct Query_cache_query { ulonglong limit_found_rows; mysql_rwlock_t lock; Query_cache_block *res; Query_cache_tls *wri; size_t len; unsigned int last_pkt_nr; uint8 tbls_type; uint8 ready; ulonglong hit_count; Query_cache_query() = default; /* Remove gcc warning */ inline void init_n_lock(); void unlock_n_destroy(); inline ulonglong found_rows() { return limit_found_rows; } inline void found_rows(ulonglong rows) { limit_found_rows= rows; } inline Query_cache_block *result() { return res; } inline void result(Query_cache_block *p) { res= p; } inline Query_cache_tls *writer() { return wri; } inline void writer(Query_cache_tls *p) { wri= p; } inline uint8 tables_type() { return tbls_type; } inline void tables_type(uint8 type) { tbls_type= type; } inline size_t length() { return len; } inline size_t add(size_t packet_len) { return(len+= packet_len); } inline void length(size_t length_arg) { len= length_arg; } inline uchar* query() { return (((uchar*)this) + ALIGN_SIZE(sizeof(Query_cache_query))); } /** following used to check if result ready in plugin without locking rw_lock of the query. */ inline void set_results_ready() { ready= 1; } inline bool is_results_ready() { return ready; } inline void increment_hits() { hit_count++; } inline ulonglong hits() { return hit_count; } void lock_writing(); void lock_reading(); bool try_lock_writing(); void unlock_writing(); void unlock_reading(); }; struct Query_cache_table { Query_cache_table() = default; /* Remove gcc warning */ char *tbl; uint32 key_len; uint8 suffix_len; /* For partitioned tables */ uint8 table_type; /* unique for every engine reference */ qc_engine_callback callback_func; /* data need by some engines */ ulonglong engine_data_buff; /** The number of queries depending of this table. */ int32 m_cached_query_count; /** If table included in the table hash to be found by other queries */ my_bool hashed; inline char *db() { return (char *) data(); } inline char *table() { return tbl; } inline void table(char *table_arg) { tbl= table_arg; } inline uint32 key_length() { return key_len; } inline void key_length(uint32 len) { key_len= len; } inline uint8 suffix_length() { return suffix_len; } inline void suffix_length(uint8 len) { suffix_len= len; } inline uint8 type() { return table_type; } inline void type(uint8 t) { table_type= t; } inline qc_engine_callback callback() { return callback_func; } inline void callback(qc_engine_callback fn){ callback_func= fn; } inline ulonglong engine_data() { return engine_data_buff; } inline void engine_data(ulonglong data_arg){ engine_data_buff= data_arg; } inline my_bool is_hashed() { return hashed; } inline void set_hashed(my_bool hash) { hashed= hash; } inline uchar* data() { return (uchar*)(((uchar*)this)+ ALIGN_SIZE(sizeof(Query_cache_table))); } }; struct Query_cache_result { Query_cache_result() = default; /* Remove gcc warning */ Query_cache_block *query; inline uchar* data() { return (uchar*)(((uchar*) this)+ ALIGN_SIZE(sizeof(Query_cache_result))); } /* data_continue (if not whole packet contained by this block) */ inline Query_cache_block *parent() { return query; } inline void parent (Query_cache_block *p) { query=p; } }; extern "C" { const uchar *query_cache_query_get_key(const void *record, size_t *length, my_bool); const uchar *query_cache_table_get_key(const void *record, size_t *length, my_bool); } extern "C" void query_cache_invalidate_by_MyISAM_filename(const char* filename); struct Query_cache_memory_bin { Query_cache_memory_bin() = default; /* Remove gcc warning */ #ifndef DBUG_OFF size_t size; #endif uint number; Query_cache_block *free_blocks; inline void init(size_t size_arg) { #ifndef DBUG_OFF size = size_arg; #endif number = 0; free_blocks = 0; } }; struct Query_cache_memory_bin_step { Query_cache_memory_bin_step() = default; /* Remove gcc warning */ size_t size; size_t increment; size_t idx; inline void init(size_t size_arg, size_t idx_arg, size_t increment_arg) { size = size_arg; idx = idx_arg; increment = increment_arg; } }; class Query_cache { public: /* Info */ size_t query_cache_size, query_cache_limit; /* statistics */ size_t free_memory, queries_in_cache, hits, inserts, refused, free_memory_blocks, total_blocks, lowmem_prunes; private: #ifndef DBUG_OFF my_thread_id m_cache_lock_thread_id; #endif mysql_cond_t COND_cache_status_changed; uint m_requests_in_progress; enum Cache_lock_status { UNLOCKED, LOCKED_NO_WAIT, LOCKED }; Cache_lock_status m_cache_lock_status; enum Cache_staus {OK, DISABLE_REQUEST, DISABLED}; Cache_staus m_cache_status; void free_query_internal(Query_cache_block *point); void invalidate_table_internal(uchar *key, size_t key_length); protected: /* The following mutex is locked when searching or changing global query, tables lists or hashes. When we are operating inside the query structure we locked an internal query block mutex. LOCK SEQUENCE (to prevent deadlocks): 1. structure_guard_mutex 2. query block (for operation inside query (query block/results)) Thread doing cache flush releases the mutex once it sets m_cache_lock_status flag, so other threads may bypass the cache as if it is disabled, not waiting for reset to finish. The exception is other threads that were going to do cache flush---they'll wait till the end of a flush operation. */ mysql_mutex_t structure_guard_mutex; size_t additional_data_size; uchar *cache; // cache memory Query_cache_block *first_block; // physical location block list Query_cache_block *queries_blocks; // query list (LIFO) Query_cache_block *tables_blocks; Query_cache_memory_bin *bins; // free block lists Query_cache_memory_bin_step *steps; // bins spacing info HASH queries, tables; /* options */ size_t min_allocation_unit, min_result_data_size; uint def_query_hash_size, def_table_hash_size; size_t mem_bin_num, mem_bin_steps; // See at init_cache & find_bin bool initialized; /* Exclude/include from cyclic double linked list */ static void double_linked_list_exclude(Query_cache_block *point, Query_cache_block **list_pointer); static void double_linked_list_simple_include(Query_cache_block *point, Query_cache_block ** list_pointer); static void double_linked_list_join(Query_cache_block *head_tail, Query_cache_block *tail_head); /* The following functions require that structure_guard_mutex is locked */ void flush_cache(); my_bool free_old_query(); void free_query(Query_cache_block *point); my_bool allocate_data_chain(Query_cache_block **result_block, size_t data_len, Query_cache_block *query_block, my_bool first_block); void invalidate_table(THD *thd, TABLE_LIST *table); void invalidate_table(THD *thd, TABLE *table); void invalidate_table(THD *thd, uchar *key, size_t key_length); void invalidate_table(THD *thd, Query_cache_block *table_block); void invalidate_query_block_list(Query_cache_block_table *list_root); TABLE_COUNTER_TYPE register_tables_from_list(THD *thd, TABLE_LIST *tables_used, TABLE_COUNTER_TYPE counter, Query_cache_block_table **block_table); my_bool register_all_tables(THD *thd, Query_cache_block *block, TABLE_LIST *tables_used, TABLE_COUNTER_TYPE tables); void unlink_table(Query_cache_block_table *node); Query_cache_block *get_free_block (size_t len, my_bool not_less, size_t min); void free_memory_block(Query_cache_block *point); void split_block(Query_cache_block *block, size_t len); Query_cache_block *join_free_blocks(Query_cache_block *first_block, Query_cache_block *block_in_list); my_bool append_next_free_block(Query_cache_block *block, size_t add_size); void exclude_from_free_memory_list(Query_cache_block *free_block); void insert_into_free_memory_list(Query_cache_block *new_block); my_bool move_by_type(uchar **border, Query_cache_block **before, size_t *gap, Query_cache_block *i); uint find_bin(size_t size); void move_to_query_list_end(Query_cache_block *block); void insert_into_free_memory_sorted_list(Query_cache_block *new_block, Query_cache_block **list); void pack_cache(); void relink(Query_cache_block *oblock, Query_cache_block *nblock, Query_cache_block *next, Query_cache_block *prev, Query_cache_block *pnext, Query_cache_block *pprev); my_bool join_results(size_t join_limit); /* Following function control structure_guard_mutex by themself or don't need structure_guard_mutex */ size_t init_cache(); void make_disabled(); void free_cache(); Query_cache_block *write_block_data(size_t data_len, uchar* data, size_t header_len, Query_cache_block::block_type type, TABLE_COUNTER_TYPE ntab = 0); my_bool append_result_data(Query_cache_block **result, size_t data_len, uchar* data, Query_cache_block *parent); my_bool write_result_data(Query_cache_block **result, size_t data_len, uchar* data, Query_cache_block *parent, Query_cache_block::block_type type=Query_cache_block::RESULT); inline size_t get_min_first_result_data_size(); inline size_t get_min_append_result_data_size(); Query_cache_block *allocate_block(size_t len, my_bool not_less, size_t min); /* If query is cacheable return number tables in query (query without tables not cached) */ TABLE_COUNTER_TYPE is_cacheable(THD *thd, LEX *lex, TABLE_LIST *tables_used, uint8 *tables_type); TABLE_COUNTER_TYPE process_and_count_tables(THD *thd, TABLE_LIST *tables_used, uint8 *tables_type); static my_bool ask_handler_allowance(THD *thd, TABLE_LIST *tables_used); public: Query_cache(size_t query_cache_limit = ULONG_MAX, size_t min_allocation_unit = QUERY_CACHE_MIN_ALLOCATION_UNIT, size_t min_result_data_size = QUERY_CACHE_MIN_RESULT_DATA_SIZE, uint def_query_hash_size = QUERY_CACHE_DEF_QUERY_HASH_SIZE, uint def_table_hash_size = QUERY_CACHE_DEF_TABLE_HASH_SIZE); inline bool is_disabled(void) { return m_cache_status != OK; } inline bool is_disable_in_progress(void) { return m_cache_status == DISABLE_REQUEST; } /* initialize cache (mutex) */ void init(); /* resize query cache (return real query size, 0 if disabled) */ size_t resize(size_t query_cache_size); /* set limit on result size */ inline void result_size_limit(size_t limit){query_cache_limit=limit;} /* set minimal result data allocation unit size */ size_t set_min_res_unit(size_t size); /* register query in cache */ void store_query(THD *thd, TABLE_LIST *used_tables); /* Check if the query is in the cache and if this is true send the data to client. */ int send_result_to_client(THD *thd, char *query, uint query_length); /* Remove all queries that uses any of the listed following tables */ void invalidate(THD *thd, TABLE_LIST *tables_used, my_bool using_transactions); void invalidate(THD *thd, CHANGED_TABLE_LIST *tables_used); void invalidate_locked_for_write(THD *thd, TABLE_LIST *tables_used); void invalidate(THD *thd, TABLE *table, my_bool using_transactions); void invalidate(THD *thd, const char *key, size_t key_length, my_bool using_transactions); /* Remove all queries that uses any of the tables in following database */ void invalidate(THD *thd, const char *db); /* Remove all queries that uses any of the listed following table */ void invalidate_by_MyISAM_filename(const char *filename); void flush(); void pack(THD *thd, size_t join_limit = QUERY_CACHE_PACK_LIMIT, uint iteration_limit = QUERY_CACHE_PACK_ITERATION); void destroy(); void insert(THD *thd, Query_cache_tls *query_cache_tls, const char *packet, size_t length, unsigned pkt_nr); my_bool insert_table(THD *thd, size_t key_len, const char *key, Query_cache_block_table *node, size_t db_length, uint8 suffix_length_arg, uint8 cache_type, qc_engine_callback callback, ulonglong engine_data, my_bool hash); void end_of_result(THD *thd); void abort(THD *thd, Query_cache_tls *query_cache_tls); /* The following functions are only used when debugging We don't protect these with ifndef DBUG_OFF to not have to recompile everything if we want to add checks of the cache at some places. */ void wreck(uint line, const char *message); void bins_dump(); void cache_dump(); void queries_dump(); void tables_dump(); my_bool check_integrity(bool not_locked); my_bool in_list(Query_cache_block * root, Query_cache_block * point, const char *name); my_bool in_table_list(Query_cache_block_table * root, Query_cache_block_table * point, const char *name); my_bool in_blocks(Query_cache_block * point); /* Table key generation */ static uint filename_2_table_key (char *key, const char *filename, uint32 *db_langth); enum Cache_try_lock_mode {WAIT, TIMEOUT, TRY}; bool try_lock(THD *thd, Cache_try_lock_mode mode= WAIT); void lock(THD *thd); void lock_and_suspend(void); void unlock(void); void disable_query_cache(THD *thd); }; #ifdef HAVE_QUERY_CACHE struct Query_cache_query_flags { unsigned int client_long_flag:1; unsigned int client_protocol_41:1; unsigned int client_extended_metadata:1; unsigned int client_depr_eof:1; unsigned int protocol_type:2; unsigned int more_results_exists:1; unsigned int in_trans:1; unsigned int autocommit:1; unsigned int pkt_nr; uint character_set_client_num; uint character_set_results_num; uint collation_connection_num; uint group_concat_max_len; ha_rows limit; Time_zone *time_zone; sql_mode_t sql_mode; ulonglong max_sort_length; size_t default_week_format; size_t div_precision_increment; MY_LOCALE *lc_time_names; }; #define QUERY_CACHE_FLAGS_SIZE sizeof(Query_cache_query_flags) #define QUERY_CACHE_DB_LENGTH_SIZE 2 #include "sql_cache.h" #define query_cache_abort(A,B) query_cache.abort(A,B) #define query_cache_end_of_result(A) query_cache.end_of_result(A) #define query_cache_store_query(A, B) query_cache.store_query(A, B) #define query_cache_destroy() query_cache.destroy() #define query_cache_result_size_limit(A) query_cache.result_size_limit(A) #define query_cache_init() query_cache.init() #define query_cache_resize(A) query_cache.resize(A) #define query_cache_set_min_res_unit(A) query_cache.set_min_res_unit(A) #define query_cache_invalidate3(A, B, C) query_cache.invalidate(A, B, C) #define query_cache_invalidate1(A, B) query_cache.invalidate(A, B) #define query_cache_send_result_to_client(A, B, C) \ query_cache.send_result_to_client(A, B, C) #define query_cache_invalidate_by_MyISAM_filename_ref \ &query_cache_invalidate_by_MyISAM_filename /* note the "maybe": it's a read without mutex */ #define query_cache_maybe_disabled(T) \ (T->variables.query_cache_type == 0 || query_cache.query_cache_size == 0) #define query_cache_is_cacheable_query(L) \ (((L)->sql_command == SQLCOM_SELECT) && (L)->safe_to_cache_query) #else #define QUERY_CACHE_FLAGS_SIZE 0 #define query_cache_store_query(A, B) do { } while(0) #define query_cache_destroy() do { } while(0) #define query_cache_result_size_limit(A) do { } while(0) #define query_cache_init() do { } while(0) #define query_cache_resize(A) do { } while(0) #define query_cache_set_min_res_unit(A) do { } while(0) #define query_cache_invalidate3(A, B, C) do { } while(0) #define query_cache_invalidate1(A,B) do { } while(0) #define query_cache_send_result_to_client(A, B, C) 0 #define query_cache_invalidate_by_MyISAM_filename_ref NULL #define query_cache_abort(A,B) do { } while(0) #define query_cache_end_of_result(A) do { } while(0) #define query_cache_maybe_disabled(T) 1 #define query_cache_is_cacheable_query(L) 0 #endif /*HAVE_QUERY_CACHE*/ extern MYSQL_PLUGIN_IMPORT Query_cache query_cache; #endif mysql/server/private/sql_parse.h000064400000020674151027430560013047 0ustar00/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_PARSE_INCLUDED #define SQL_PARSE_INCLUDED #include "sql_acl.h" /* GLOBAL_ACLS */ class Comp_creator; class Item; class Object_creation_ctx; class Parser_state; struct TABLE_LIST; class THD; class Table_ident; struct LEX; enum enum_mysql_completiontype { ROLLBACK_RELEASE=-2, ROLLBACK=1, ROLLBACK_AND_CHAIN=7, COMMIT_RELEASE=-1, COMMIT=0, COMMIT_AND_CHAIN=6 }; extern "C" int path_starts_from_data_home_dir(const char *dir); int test_if_data_home_dir(const char *dir); int error_if_data_home_dir(const char *path, const char *what); my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags); bool multi_update_precheck(THD *thd, TABLE_LIST *tables); bool multi_delete_precheck(THD *thd, TABLE_LIST *tables); int mysql_multi_update_prepare(THD *thd); int mysql_multi_delete_prepare(THD *thd); int mysql_insert_select_prepare(THD *thd,select_result *sel_res); bool update_precheck(THD *thd, TABLE_LIST *tables); bool delete_precheck(THD *thd, TABLE_LIST *tables); bool insert_precheck(THD *thd, TABLE_LIST *tables); bool create_table_precheck(THD *thd, TABLE_LIST *tables, TABLE_LIST *create_table); bool check_fk_parent_table_access(THD *thd, HA_CREATE_INFO *create_info, Alter_info *alter_info, const char* create_db); bool parse_sql(THD *thd, Parser_state *parser_state, Object_creation_ctx *creation_ctx, bool do_pfs_digest=false); void free_items(Item *item); void cleanup_items(Item *item); Comp_creator *comp_eq_creator(bool invert); Comp_creator *comp_ge_creator(bool invert); Comp_creator *comp_gt_creator(bool invert); Comp_creator *comp_le_creator(bool invert); Comp_creator *comp_lt_creator(bool invert); Comp_creator *comp_ne_creator(bool invert); int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident, enum enum_schema_tables schema_table_idx); void get_default_definer(THD *thd, LEX_USER *definer, bool role); LEX_USER *create_default_definer(THD *thd, bool role); LEX_USER *create_definer(THD *thd, LEX_CSTRING *user_name, LEX_CSTRING *host_name); LEX_USER *get_current_user(THD *thd, LEX_USER *user, bool lock=true); bool sp_process_definer(THD *thd); bool check_string_byte_length(const LEX_CSTRING *str, uint err_msg, size_t max_byte_length); bool check_string_char_length(const LEX_CSTRING *str, uint err_msg, size_t max_char_length, CHARSET_INFO *cs, bool no_error); bool check_ident_length(const LEX_CSTRING *ident); CHARSET_INFO* merge_charset_and_collation(CHARSET_INFO *cs, CHARSET_INFO *cl); CHARSET_INFO *find_bin_collation(CHARSET_INFO *cs); bool check_host_name(LEX_CSTRING *str); bool check_identifier_name(LEX_CSTRING *str, uint max_char_length, uint err_code, const char *param_for_err_msg); bool mysql_test_parse_for_slave(THD *thd,char *inBuf,uint length); bool sqlcom_can_generate_row_events(const THD *thd); bool stmt_causes_implicit_commit(THD *thd, uint mask); bool is_update_query(enum enum_sql_command command); bool is_log_table_write_query(enum enum_sql_command command); bool alloc_query(THD *thd, const char *packet, size_t packet_length); void mysql_init_select(LEX *lex); void mysql_parse(THD *thd, char *rawbuf, uint length, Parser_state *parser_state); bool mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *sel); void create_select_for_variable(THD *thd, LEX_CSTRING *var_name); void create_table_set_open_action_and_adjust_tables(LEX *lex); void mysql_init_multi_delete(LEX *lex); bool multi_delete_set_locks_and_link_aux_tables(LEX *lex); void create_table_set_open_action_and_adjust_tables(LEX *lex); int bootstrap(MYSQL_FILE *file); bool run_set_statement_if_requested(THD *thd, LEX *lex); int mysql_execute_command(THD *thd, bool is_called_from_prepared_stmt=false); enum dispatch_command_return { DISPATCH_COMMAND_SUCCESS=0, DISPATCH_COMMAND_CLOSE_CONNECTION= 1, DISPATCH_COMMAND_WOULDBLOCK= 2 }; dispatch_command_return do_command(THD *thd, bool blocking = true); dispatch_command_return dispatch_command(enum enum_server_command command, THD *thd, char* packet, uint packet_length, bool blocking = true); void log_slow_statement(THD *thd); bool append_file_to_dir(THD *thd, const char **filename_ptr, const LEX_CSTRING *table_name); void execute_init_command(THD *thd, LEX_STRING *init_command, mysql_rwlock_t *var_lock); bool add_to_list(THD *thd, SQL_I_List &list, Item *group, bool asc); void add_join_on(THD *thd, TABLE_LIST *b, Item *expr); void add_join_natural(TABLE_LIST *a,TABLE_LIST *b,List *using_fields, SELECT_LEX *lex); bool add_proc_to_list(THD *thd, Item *item); bool push_new_name_resolution_context(THD *thd, TABLE_LIST *left_op, TABLE_LIST *right_op); void init_update_queries(void); Item *normalize_cond(THD *thd, Item *cond); Item *negate_expression(THD *thd, Item *expr); bool check_stack_overrun(THD *thd, long margin, uchar *dummy); /* Variables */ extern const LEX_CSTRING any_db; extern uint sql_command_flags[]; extern uint server_command_flags[]; extern const LEX_CSTRING command_name[]; extern uint server_command_flags[]; /* Inline functions */ inline bool check_identifier_name(LEX_CSTRING *str, uint err_code) { return check_identifier_name(str, NAME_CHAR_LEN, err_code, ""); } inline bool check_identifier_name(LEX_CSTRING *str) { return check_identifier_name(str, NAME_CHAR_LEN, 0, ""); } #ifndef NO_EMBEDDED_ACCESS_CHECKS bool check_one_table_access(THD *thd, privilege_t privilege, TABLE_LIST *tables); bool check_single_table_access(THD *thd, privilege_t privilege, TABLE_LIST *tables, bool no_errors); bool check_routine_access(THD *thd, privilege_t want_access, const LEX_CSTRING *db, const LEX_CSTRING *name, const Sp_handler *sph, bool no_errors); bool check_some_access(THD *thd, privilege_t want_access, TABLE_LIST *table); bool check_some_routine_access(THD *thd, const char *db, const char *name, const Sp_handler *sph); bool check_table_access(THD *thd, privilege_t requirements,TABLE_LIST *tables, bool any_combination_of_privileges_will_do, uint number, bool no_errors); #else inline bool check_one_table_access(THD *thd, privilege_t privilege, TABLE_LIST *tables) { return false; } inline bool check_single_table_access(THD *thd, privilege_t privilege, TABLE_LIST *tables, bool no_errors) { return false; } inline bool check_routine_access(THD *thd, privilege_t want_access, const LEX_CSTRING *db, const LEX_CSTRING *name, const Sp_handler *sph, bool no_errors) { return false; } inline bool check_some_access(THD *thd, privilege_t want_access, TABLE_LIST *table) { table->grant.privilege= want_access; return false; } inline bool check_some_routine_access(THD *thd, const char *db, const char *name, const Sp_handler *sph) { return false; } inline bool check_table_access(THD *thd, privilege_t requirements,TABLE_LIST *tables, bool any_combination_of_privileges_will_do, uint number, bool no_errors) { return false; } #endif /*NO_EMBEDDED_ACCESS_CHECKS*/ #endif /* SQL_PARSE_INCLUDED */ mysql/server/private/lex_ident.h000064400000004112151027430560013016 0ustar00#ifndef LEX_IDENT_INCLUDED #define LEX_IDENT_INCLUDED /* Copyright (c) 2023, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *table_alias_charset; /* Identifiers for the database objects stored on disk, e.g. databases, tables, triggers. */ class Lex_ident_fs: public LEX_CSTRING { public: static CHARSET_INFO *charset_info() { return table_alias_charset; } public: Lex_ident_fs() :LEX_CSTRING({0,0}) { } Lex_ident_fs(const char *str, size_t length) :LEX_CSTRING({str, length}) { } explicit Lex_ident_fs(const LEX_CSTRING &str) :LEX_CSTRING(str) { } #if MYSQL_VERSION_ID<=110501 private: static bool is_valid_ident(const LEX_CSTRING &str) { // NULL identifier, or 0-terminated identifier return (str.str == NULL && str.length == 0) || str.str[str.length] == 0; } public: bool streq(const LEX_CSTRING &rhs) const { DBUG_ASSERT(is_valid_ident(*this)); DBUG_ASSERT(is_valid_ident(rhs)); return length == rhs.length && my_strcasecmp(charset_info(), str, rhs.str) == 0; } #else /* Starting from 11.5.1 streq() is inherited from the base. The above implementations of streq() and is_valid_ident() should be removed. */ #error Remove streq() above. #endif }; class Lex_ident_db: public Lex_ident_fs { public: using Lex_ident_fs::Lex_ident_fs; }; class Lex_ident_table: public Lex_ident_fs { public: using Lex_ident_fs::Lex_ident_fs; }; #endif // LEX_IDENT_INCLUDED mysql/server/private/sql_alter.h000064400000035655151027430560013051 0ustar00/* Copyright (c) 2010, 2014, Oracle and/or its affiliates. Copyright (c) 2013, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_ALTER_TABLE_H #define SQL_ALTER_TABLE_H class Alter_drop; class Alter_column; class Alter_rename_key; class Alter_index_ignorability; class Key; /** Data describing the table being created by CREATE TABLE or altered by ALTER TABLE. */ class Alter_info { public: enum enum_enable_or_disable { LEAVE_AS_IS, ENABLE, DISABLE }; bool vers_prohibited(THD *thd) const; /** The different values of the ALGORITHM clause. Describes which algorithm to use when altering the table. */ enum enum_alter_table_algorithm { /* Use thd->variables.alter_algorithm for alter method. If this is also default then use the fastest possible ALTER TABLE method (INSTANT, NOCOPY, INPLACE, COPY) */ ALTER_TABLE_ALGORITHM_DEFAULT, // Copy if supported, error otherwise. ALTER_TABLE_ALGORITHM_COPY, // In-place if supported, error otherwise. ALTER_TABLE_ALGORITHM_INPLACE, // No Copy will refuse any operation which does rebuild. ALTER_TABLE_ALGORITHM_NOCOPY, // Instant should allow any operation that changes metadata only. ALTER_TABLE_ALGORITHM_INSTANT, // When there is no specification of algorithm during alter table. ALTER_TABLE_ALGORITHM_NONE }; /** The different values of the LOCK clause. Describes the level of concurrency during ALTER TABLE. */ enum enum_alter_table_lock { // Maximum supported level of concurency for the given operation. ALTER_TABLE_LOCK_DEFAULT, // Allow concurrent reads & writes. If not supported, give error. ALTER_TABLE_LOCK_NONE, // Allow concurrent reads only. If not supported, give error. ALTER_TABLE_LOCK_SHARED, // Block reads and writes. ALTER_TABLE_LOCK_EXCLUSIVE }; Lex_table_name db, table_name; // Columns and keys to be dropped. List drop_list; // Columns for ALTER_CHANGE_COLUMN_DEFAULT. List alter_list; // List of keys, used by both CREATE and ALTER TABLE. List key_list; // List of keys to be renamed. List alter_rename_key_list; // List of columns, used by both CREATE and ALTER TABLE. List create_list; // Indexes whose ignorability needs to be changed. List alter_index_ignorability_list; List check_constraint_list; // Type of ALTER TABLE operation. alter_table_operations flags; ulong partition_flags; // Enable or disable keys. enum_enable_or_disable keys_onoff; // Used only in add_stat_drop_index() TABLE *original_table; // List of partitions. List partition_names; // Number of partitions. uint num_parts; /* List of fields that we should delete statistics from */ List drop_stat_fields; struct DROP_INDEX_STAT_PARAMS { KEY *key; bool ext_prefixes_only; }; struct RENAME_COLUMN_STAT_PARAMS { Field *field; LEX_CSTRING *name; uint duplicate_counter; // For temporary names }; struct RENAME_INDEX_STAT_PARAMS { const KEY *key; const LEX_CSTRING *name; uint duplicate_counter; // For temporary names uint usage_count; // How many rename entries }; /* List of index that we should delete statistics from */ List drop_stat_indexes; List rename_stat_fields; List rename_stat_indexes; bool add_stat_drop_index(KEY *key, bool ext_prefixes_only, MEM_ROOT *mem_root) { DROP_INDEX_STAT_PARAMS *param; if (!(param= (DROP_INDEX_STAT_PARAMS*) alloc_root(mem_root, sizeof(*param)))) return true; param->key= key; param->ext_prefixes_only= ext_prefixes_only; return drop_stat_indexes.push_back(param, mem_root); } bool add_stat_drop_index(THD *thd, const LEX_CSTRING *key_name); bool add_stat_rename_index(const KEY *key, const LEX_CSTRING *name, MEM_ROOT *mem_root) { RENAME_INDEX_STAT_PARAMS *param; if (!(param= (RENAME_INDEX_STAT_PARAMS*) alloc_root(mem_root, sizeof(*param)))) return true; param->key= key; param->name= name; param->usage_count= 0; return rename_stat_indexes.push_back(param, mem_root); } bool add_stat_rename_field(Field *field, LEX_CSTRING *name, MEM_ROOT *mem_root) { RENAME_COLUMN_STAT_PARAMS *param; if (!(param= (RENAME_COLUMN_STAT_PARAMS*) alloc_root(mem_root, sizeof(*param)))) return true; param->field= field; param->name= name; param->duplicate_counter= 0; return rename_stat_fields.push_back(param, mem_root); } bool collect_renamed_fields(THD *thd); /* Delete/update statistics in EITS tables */ void apply_statistics_deletes_renames(THD *thd, TABLE *table); private: // Type of ALTER TABLE algorithm. enum_alter_table_algorithm requested_algorithm; public: // Type of ALTER TABLE lock. enum_alter_table_lock requested_lock; Alter_info() : flags(0), partition_flags(0), keys_onoff(LEAVE_AS_IS), original_table(0), num_parts(0), requested_algorithm(ALTER_TABLE_ALGORITHM_NONE), requested_lock(ALTER_TABLE_LOCK_DEFAULT) {} void reset() { drop_list.empty(); alter_list.empty(); key_list.empty(); alter_rename_key_list.empty(); create_list.empty(); alter_index_ignorability_list.empty(); check_constraint_list.empty(); drop_stat_fields.empty(); drop_stat_indexes.empty(); rename_stat_fields.empty(); rename_stat_indexes.empty(); flags= 0; partition_flags= 0; keys_onoff= LEAVE_AS_IS; num_parts= 0; partition_names.empty(); requested_algorithm= ALTER_TABLE_ALGORITHM_NONE; requested_lock= ALTER_TABLE_LOCK_DEFAULT; } /** Construct a copy of this object to be used for mysql_alter_table and mysql_create_table. Historically, these two functions modify their Alter_info arguments. This behaviour breaks re-execution of prepared statements and stored procedures and is compensated by always supplying a copy of Alter_info to these functions. @param rhs Alter_info to make copy of @param mem_root Mem_root for new Alter_info @note You need to use check the error in THD for out of memory condition after calling this function. */ Alter_info(const Alter_info &rhs, MEM_ROOT *mem_root); /** Parses the given string and sets requested_algorithm if the string value matches a supported value. Supported values: INPLACE, COPY, DEFAULT @param str String containing the supplied value @retval false Supported value found, state updated @retval true Not supported value, no changes made */ bool set_requested_algorithm(const LEX_CSTRING *str); /** Parses the given string and sets requested_lock if the string value matches a supported value. Supported values: NONE, SHARED, EXCLUSIVE, DEFAULT @param str String containing the supplied value @retval false Supported value found, state updated @retval true Not supported value, no changes made */ bool set_requested_lock(const LEX_CSTRING *str); /** Set the requested algorithm to the given algorithm value @param algo_value algorithm to be set */ void set_requested_algorithm(enum_alter_table_algorithm algo_value); /** Returns the algorithm value in the format "algorithm=value" */ const char* algorithm_clause(THD *thd) const; /** Returns the lock value in the format "lock=value" */ const char* lock() const; /** Check whether the given result can be supported with the specified user alter algorithm. @param thd Thread handle @param ha_alter_info Structure describing changes to be done by ALTER TABLE and holding data during in-place alter @retval false Supported operation @retval true Not supported value */ bool supports_algorithm(THD *thd, const Alter_inplace_info *ha_alter_info); /** Check whether the given result can be supported with the specified user lock type. @param ha_alter_info Structure describing changes to be done by ALTER TABLE and holding data during in-place alter @retval false Supported lock type @retval true Not supported value */ bool supports_lock(THD *thd, const Alter_inplace_info *ha_alter_info); /** Return user requested algorithm. If user does not specify algorithm then return alter_algorithm variable value. */ enum_alter_table_algorithm algorithm(const THD *thd) const; uint check_vcol_field(Item_field *f) const; private: Alter_info &operator=(const Alter_info &rhs); // not implemented Alter_info(const Alter_info &rhs); // not implemented }; /** Runtime context for ALTER TABLE. */ class Alter_table_ctx { public: Alter_table_ctx(); Alter_table_ctx(THD *thd, TABLE_LIST *table_list, uint tables_opened_arg, const LEX_CSTRING *new_db_arg, const LEX_CSTRING *new_name_arg); /** @return true if the table is moved to another database, false otherwise. */ bool is_database_changed() const { return (new_db.str != db.str); }; /** @return true if the table is renamed, false otherwise. */ bool is_table_renamed() const { return (is_database_changed() || new_name.str != table_name.str); }; /** @return filename (including .frm) for the new table. */ const char *get_new_filename() const { DBUG_ASSERT(!tmp_table); return new_filename; } /** @return path to the original table. */ const char *get_path() const { DBUG_ASSERT(!tmp_table); return path; } /** @return path to the new table. */ const char *get_new_path() const { DBUG_ASSERT(!tmp_table); return new_path; } /** @return path to the temporary table created during ALTER TABLE. */ const char *get_tmp_path() const { return tmp_path; } const LEX_CSTRING get_tmp_cstring_path() const { LEX_CSTRING tmp= { tmp_path, strlen(tmp_path) }; return tmp; }; /** Mark ALTER TABLE as needing to produce foreign key error if it deletes a row from the table being changed. */ void set_fk_error_if_delete_row(FOREIGN_KEY_INFO *fk) { fk_error_if_delete_row= true; fk_error_id= fk->foreign_id->str; fk_error_table= fk->foreign_table->str; } void report_implicit_default_value_error(THD *thd, const TABLE_SHARE *) const; public: Create_field *implicit_default_value_error_field= nullptr; bool error_if_not_empty= false; uint tables_opened= 0; LEX_CSTRING db; LEX_CSTRING table_name; LEX_CSTRING storage_engine_name; LEX_CSTRING alias; LEX_CSTRING new_db; LEX_CSTRING new_name; LEX_CSTRING new_alias; LEX_CSTRING tmp_name; LEX_CSTRING tmp_storage_engine_name; LEX_CUSTRING tmp_id, id; char tmp_buff[80]; uchar id_buff[MY_UUID_SIZE]; char storage_engine_buff[NAME_LEN], tmp_storage_engine_buff[NAME_LEN]; bool storage_engine_partitioned; bool tmp_storage_engine_name_partitioned; /** Indicates that if a row is deleted during copying of data from old version of table to the new version ER_FK_CANNOT_DELETE_PARENT error should be emitted. */ bool fk_error_if_delete_row= false; /** Name of foreign key for the above error. */ const char *fk_error_id= nullptr; /** Name of table for the above error. */ const char *fk_error_table= nullptr; bool modified_primary_key= false; bool fast_alter_partition= false; /** Indicates that we are altering temporary table */ bool tmp_table= false; private: char new_filename[FN_REFLEN + 1]; char new_alias_buff[NAME_LEN + 1]; char tmp_name_buff[NAME_LEN + 1]; char path[FN_REFLEN + 1]; char new_path[FN_REFLEN + 1]; char tmp_path[FN_REFLEN + 1]; Alter_table_ctx &operator=(const Alter_table_ctx &rhs); // not implemented Alter_table_ctx(const Alter_table_ctx &rhs); // not implemented }; /** Sql_cmd_common_alter_table represents the common properties of the ALTER TABLE statements. @todo move Alter_info and other ALTER generic structures from Lex here. */ class Sql_cmd_common_alter_table : public Sql_cmd { protected: /** Constructor. */ Sql_cmd_common_alter_table() = default; virtual ~Sql_cmd_common_alter_table() = default; enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_TABLE; } }; /** Sql_cmd_alter_table represents the generic ALTER TABLE statement. @todo move Alter_info and other ALTER specific structures from Lex here. */ class Sql_cmd_alter_table : public Sql_cmd_common_alter_table, public Storage_engine_name { public: /** Constructor, used to represent a ALTER TABLE statement. */ Sql_cmd_alter_table() = default; ~Sql_cmd_alter_table() = default; Storage_engine_name *option_storage_engine_name() override { return this; } bool execute(THD *thd) override; }; /** Sql_cmd_alter_sequence represents the ALTER SEQUENCE statement. */ class Sql_cmd_alter_sequence : public Sql_cmd, public DDL_options { public: /** Constructor, used to represent a ALTER TABLE statement. */ Sql_cmd_alter_sequence(const DDL_options &options) :DDL_options(options) {} ~Sql_cmd_alter_sequence() = default; enum_sql_command sql_command_code() const override { return SQLCOM_ALTER_SEQUENCE; } bool execute(THD *thd) override; }; /** Sql_cmd_alter_table_tablespace represents ALTER TABLE IMPORT/DISCARD TABLESPACE statements. */ class Sql_cmd_discard_import_tablespace : public Sql_cmd_common_alter_table { public: enum enum_tablespace_op_type { DISCARD_TABLESPACE, IMPORT_TABLESPACE }; Sql_cmd_discard_import_tablespace(enum_tablespace_op_type tablespace_op_arg) : m_tablespace_op(tablespace_op_arg) {} bool execute(THD *thd) override; private: const enum_tablespace_op_type m_tablespace_op; }; #endif mysql/server/private/sql_join_cache.h000064400000137035151027430560014017 0ustar00/* Copyright (c) 2011, 2012, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file contains declarations for implementations of block based join algorithms */ #define JOIN_CACHE_INCREMENTAL_BIT 1 #define JOIN_CACHE_HASHED_BIT 2 #define JOIN_CACHE_BKA_BIT 4 /* Categories of data fields of variable length written into join cache buffers. The value of any of these fields is written into cache together with the prepended length of the value. */ #define CACHE_BLOB 1 /* blob field */ #define CACHE_STRIPPED 2 /* field stripped of trailing spaces */ #define CACHE_VARSTR1 3 /* short string value (length takes 1 byte) */ #define CACHE_VARSTR2 4 /* long string value (length takes 2 bytes) */ #define CACHE_ROWID 5 /* ROWID field */ /* The CACHE_FIELD structure used to describe fields of records that are written into a join cache buffer from record buffers and backward. */ typedef struct st_cache_field { uchar *str; /**< buffer from/to where the field is to be copied */ uint length; /**< maximal number of bytes to be copied from/to str */ /* Field object for the moved field (0 - for a flag field, see JOIN_CACHE::create_flag_fields). */ Field *field; uint type; /**< category of the of the copied field (CACHE_BLOB et al.) */ /* The number of the record offset value for the field in the sequence of offsets placed after the last field of the record. These offset values are used to access fields referred to from other caches. If the value is 0 then no offset for the field is saved in the trailing sequence of offsets. */ uint referenced_field_no; /* The remaining structure fields are used as containers for temp values */ uint blob_length; /**< length of the blob to be copied */ uint offset; /**< field offset to be saved in cache buffer */ } CACHE_FIELD; class JOIN_TAB_SCAN; class EXPLAIN_BKA_TYPE; /* JOIN_CACHE is the base class to support the implementations of - Block Nested Loop (BNL) Join Algorithm, - Block Nested Loop Hash (BNLH) Join Algorithm, - Batched Key Access (BKA) Join Algorithm. The first algorithm is supported by the derived class JOIN_CACHE_BNL, the second algorithm is supported by the derived class JOIN_CACHE_BNLH, while the third algorithm is implemented in two variant supported by the classes JOIN_CACHE_BKA and JOIN_CACHE_BKAH. These three algorithms have a lot in common. Each of them first accumulates the records of the left join operand in a join buffer and then searches for matching rows of the second operand for all accumulated records. For the first two algorithms this strategy saves on logical I/O operations: the entire set of records from the join buffer requires only one look-through of the records provided by the second operand. For the third algorithm the accumulation of records allows to optimize fetching rows of the second operand from disk for some engines (MyISAM, InnoDB), or to minimize the number of round-trips between the Server and the engine nodes. */ class JOIN_CACHE :public Sql_alloc { private: /* Size of the offset of a record from the cache */ uint size_of_rec_ofs; /* Size of the length of a record in the cache */ uint size_of_rec_len; /* Size of the offset of a field within a record in the cache */ uint size_of_fld_ofs; /* This structure is used only for explain, not for execution */ bool for_explain_only; protected: /* 3 functions below actually do not use the hidden parameter 'this' */ /* Calculate the number of bytes used to store an offset value */ uint offset_size(size_t len) { return (len < 256 ? 1 : len < 256*256 ? 2 : 4); } /* Get the offset value that takes ofs_sz bytes at the position ptr */ ulong get_offset(uint ofs_sz, uchar *ptr) { switch (ofs_sz) { case 1: return uint(*ptr); case 2: return uint2korr(ptr); case 4: return uint4korr(ptr); } return 0; } /* Set the offset value ofs that takes ofs_sz bytes at the position ptr */ void store_offset(uint ofs_sz, uchar *ptr, ulong ofs) { switch (ofs_sz) { case 1: *ptr= (uchar) ofs; return; case 2: int2store(ptr, (uint16) ofs); return; case 4: int4store(ptr, (uint32) ofs); return; } } size_t calc_avg_record_length(); /* The maximum total length of the fields stored for a record in the cache. For blob fields only the sizes of the blob lengths are taken into account. */ uint length; /* Representation of the executed multi-way join through which all needed context can be accessed. */ JOIN *join; /* JOIN_TAB of the first table that can have it's fields in the join cache. That is, tables in the [start_tab, tab) range can have their fields in the join cache. If a join tab in the range represents an SJM-nest, then all tables from the nest can have their fields in the join cache, too. */ JOIN_TAB *start_tab; /* The total number of flag and data fields that can appear in a record written into the cache. Fields with null values are always skipped to save space. */ uint fields; /* The total number of flag fields in a record put into the cache. They are used for table null bitmaps, table null row flags, and an optional match flag. Flag fields go before other fields in a cache record with the match flag field placed always at the very beginning of the record. */ uint flag_fields; /* The total number of blob fields that are written into the cache */ uint blobs; /* The total number of fields referenced from field descriptors for other join caches. These fields are used to construct key values. When BKA join algorithm is employed the constructed key values serve to access matching rows with index lookups. The key values are put into a hash table when the BNLH join algorithm is employed and when BKAH is used for the join operation. */ uint referenced_fields; /* The current number of already created data field descriptors. This number can be useful for implementations of the init methods. */ uint data_field_count; /* The current number of already created pointers to the data field descriptors. This number can be useful for implementations of the init methods. */ uint data_field_ptr_count; /* Array of the descriptors of fields containing 'fields' elements. These are all fields that are stored for a record in the cache. */ CACHE_FIELD *field_descr; /* Array of pointers to the blob descriptors that contains 'blobs' elements. */ CACHE_FIELD **blob_ptr; /* This flag indicates that records written into the join buffer contain a match flag field. This is set to true for the first inner table of an outer join or a semi-join. The flag must be set by the init method. Currently any implementation of the virtial init method calls the function JOIN_CACHE::calc_record_fields() to set this flag. */ bool with_match_flag; /* This flag indicates that any record is prepended with the length of the record which allows us to skip the record or part of it without reading. */ bool with_length; /* The maximal number of bytes used for a record representation in the cache excluding the space for blob data. For future derived classes this representation may contains some redundant info such as a key value associated with the record. */ uint pack_length; /* The value of pack_length incremented by the total size of all pointers of a record in the cache to the blob data. */ uint pack_length_with_blob_ptrs; /* The total size of the record base prefix. The base prefix of record may include the following components: - the length of the record - the link to a record in a previous buffer. Each record in the buffer are supplied with the same set of the components. */ uint base_prefix_length; /* The expected length of a record in the join buffer together with all prefixes and postfixes */ size_t avg_record_length; /* The expected size of the space per record in the auxiliary buffer */ size_t avg_aux_buffer_incr; /* Pointer to the beginning of the join buffer */ uchar *buff; /* Size of the entire memory allocated for the join buffer. Part of this memory may be reserved for the auxiliary buffer. */ size_t buff_size; /* The minimal join buffer size when join buffer still makes sense to use */ size_t min_buff_size; /* The maximum expected size if the join buffer to be used */ size_t max_buff_size; /* Size of the auxiliary buffer */ size_t aux_buff_size; /* The number of records put into the join buffer */ size_t records; /* The number of records in the fully refilled join buffer of the minimal size equal to min_buff_size */ size_t min_records; /* Pointer to the current position in the join buffer. This member is used both when writing to buffer and when reading from it. */ uchar *pos; /* Pointer to the first free position in the join buffer, right after the last record into it. */ uchar *end_pos; /* Pointer to the beginning of the first field of the current read/write record from the join buffer. The value is adjusted by the get_record/put_record functions. */ uchar *curr_rec_pos; /* Pointer to the beginning of the first field of the last record from the join buffer. */ uchar *last_rec_pos; /* Flag is set if the blob data for the last record in the join buffer is in record buffers rather than in the join cache. */ bool last_rec_blob_data_is_in_rec_buff; /* Pointer to the position to the current record link. Record links are used only with linked caches. Record links allow to set connections between parts of one join record that are stored in different join buffers. In the simplest case a record link is just a pointer to the beginning of the record stored in the buffer. In a more general case a link could be a reference to an array of pointers to records in the buffer. */ uchar *curr_rec_link; /* This flag is set to TRUE if join_tab is the first inner table of an outer join and the latest record written to the join buffer is detected to be null complemented after checking on conditions over the outer tables for this outer join operation */ bool last_written_is_null_compl; /* The number of fields put in the join buffer of the join cache that are used in building keys to access the table join_tab */ uint local_key_arg_fields; /* The total number of the fields in the previous caches that are used in building keys to access the table join_tab */ uint external_key_arg_fields; /* This flag indicates that the key values will be read directly from the join buffer. It will save us building key values in the key buffer. */ bool use_emb_key; /* The length of an embedded key value */ uint emb_key_length; /* This flag is used only when 'not exists' optimization can be applied */ bool not_exists_opt_is_applicable; /* This object provides the methods to iterate over records of the joined table join_tab when looking for join matches between records from join buffer and records from join_tab. BNL and BNLH join algorithms retrieve all records from join_tab, while BKA/BKAH algorithm iterates only over those records from join_tab that can be accessed by look-ups with join keys built from records in join buffer. */ JOIN_TAB_SCAN *join_tab_scan; void calc_record_fields(); void collect_info_on_key_args(); int alloc_fields(); void create_flag_fields(); void create_key_arg_fields(); void create_remaining_fields(); void set_constants(); int alloc_buffer(); /* Shall reallocate the join buffer */ virtual int realloc_buffer(); /* Check the possibility to read the access keys directly from join buffer */ bool check_emb_key_usage(); uint get_size_of_rec_offset() { return size_of_rec_ofs; } uint get_size_of_rec_length() { return size_of_rec_len; } uint get_size_of_fld_offset() { return size_of_fld_ofs; } uchar *get_rec_ref(uchar *ptr) { return buff+get_offset(size_of_rec_ofs, ptr-size_of_rec_ofs); } ulong get_rec_length(uchar *ptr) { return (ulong) get_offset(size_of_rec_len, ptr); } ulong get_fld_offset(uchar *ptr) { return (ulong) get_offset(size_of_fld_ofs, ptr); } void store_rec_ref(uchar *ptr, uchar* ref) { store_offset(size_of_rec_ofs, ptr-size_of_rec_ofs, (ulong) (ref-buff)); } void store_rec_length(uchar *ptr, ulong len) { store_offset(size_of_rec_len, ptr, len); } void store_fld_offset(uchar *ptr, ulong ofs) { store_offset(size_of_fld_ofs, ptr, ofs); } /* Write record fields and their required offsets into the join buffer */ uint write_record_data(uchar *link, bool *is_full); /* Get the total length of all prefixes of a record in the join buffer */ virtual uint get_prefix_length() { return base_prefix_length; } /* Get maximum total length of all affixes of a record in the join buffer */ virtual uint get_record_max_affix_length(); /* Shall get maximum size of the additional space per record used for record keys */ virtual uint get_max_key_addon_space_per_record() { return 0; } /* This method must determine for how much the auxiliary buffer should be incremented when a new record is added to the join buffer. If no auxiliary buffer is needed the function should return 0. */ virtual uint aux_buffer_incr(size_t recno); /* Shall calculate how much space is remaining in the join buffer */ virtual size_t rem_space() { return MY_MAX(buff_size-(end_pos-buff)-aux_buff_size,0); } /* Shall calculate how much space is taken by allocation of the key for a record in the join buffer */ virtual uint extra_key_length() { return 0; } /* Read all flag and data fields of a record from the join buffer */ uint read_all_record_fields(); /* Read all flag fields of a record from the join buffer */ uint read_flag_fields(); /* Read a data record field from the join buffer */ uint read_record_field(CACHE_FIELD *copy, bool last_record); /* Read a referenced field from the join buffer */ bool read_referenced_field(CACHE_FIELD *copy, uchar *rec_ptr, uint *len); /* Shall skip record from the join buffer if its match flag is set to MATCH_FOUND */ virtual bool skip_if_matched(); /* Shall skip record from the join buffer if its match flag commands to do so */ virtual bool skip_if_not_needed_match(); /* True if rec_ptr points to the record whose blob data stay in record buffers */ bool blob_data_is_in_rec_buff(uchar *rec_ptr) { return rec_ptr == last_rec_pos && last_rec_blob_data_is_in_rec_buff; } /* Find matches from the next table for records from the join buffer */ virtual enum_nested_loop_state join_matching_records(bool skip_last); /* Shall set an auxiliary buffer up (currently used only by BKA joins) */ virtual int setup_aux_buffer(HANDLER_BUFFER &aux_buff) { DBUG_ASSERT(0); return 0; } /* Shall get the number of ranges in the cache buffer passed to the MRR interface */ virtual uint get_number_of_ranges_for_mrr() { return 0; }; /* Shall prepare to look for records from the join cache buffer that would match the record of the joined table read into the record buffer */ virtual bool prepare_look_for_matches(bool skip_last)= 0; /* Shall return a pointer to the record from join buffer that is checked as the next candidate for a match with the current record from join_tab. Each implementation of this virtual function should bare in mind that the record position it returns shall be exactly the position passed as the parameter to the implementations of the virtual functions skip_next_candidate_for_match and read_next_candidate_for_match. */ virtual uchar *get_next_candidate_for_match()= 0; /* Shall check whether the given record from the join buffer has its match flag settings commands to skip the record in the buffer. */ virtual bool skip_next_candidate_for_match(uchar *rec_ptr)= 0; /* Shall read the given record from the join buffer into the the corresponding record buffer */ virtual void read_next_candidate_for_match(uchar *rec_ptr)= 0; /* Shall return the location of the association label returned by the multi_read_range_next function for the current record loaded into join_tab's record buffer */ virtual uchar **get_curr_association_ptr() { return 0; }; /* Add null complements for unmatched outer records from the join buffer */ virtual enum_nested_loop_state join_null_complements(bool skip_last); /* Restore the fields of the last record from the join buffer */ virtual void restore_last_record(); /* Set match flag for a record in join buffer if it has not been set yet */ bool set_match_flag_if_none(JOIN_TAB *first_inner, uchar *rec_ptr); enum_nested_loop_state generate_full_extensions(uchar *rec_ptr); /* Check matching to a partial join record from the join buffer */ bool check_match(uchar *rec_ptr); /* This constructor creates an unlinked join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. */ JOIN_CACHE(JOIN *j, JOIN_TAB *tab) { join= j; join_tab= tab; prev_cache= next_cache= 0; buff= 0; min_buff_size= max_buff_size= 0; // Caches not_exists_opt_is_applicable= false; } /* This constructor creates a linked join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The parameter 'prev' specifies the previous cache object to which this cache is linked. */ JOIN_CACHE(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) { join= j; join_tab= tab; next_cache= 0; prev_cache= prev; buff= 0; min_buff_size= max_buff_size= 0; // Caches if (prev) prev->next_cache= this; } public: /* The enumeration type Join_algorithm includes a mnemonic constant for each join algorithm that employs join buffers */ enum Join_algorithm { BNL_JOIN_ALG, /* Block Nested Loop Join algorithm */ BNLH_JOIN_ALG, /* Block Nested Loop Hash Join algorithm */ BKA_JOIN_ALG, /* Batched Key Access Join algorithm */ BKAH_JOIN_ALG /* Batched Key Access with Hash Table Join Algorithm */ }; /* The enumeration type Match_flag describes possible states of the match flag field stored for the records of the first inner tables of outer joins and semi-joins in the cases when the first match strategy is used for them. When a record with match flag field is written into the join buffer the state of the field usually is MATCH_NOT_FOUND unless this is a record of the first inner table of the outer join for which the on precondition (the condition from on expression over outer tables) has turned out not to be true. In the last case the state of the match flag is MATCH_IMPOSSIBLE. The state of the match flag field is changed to MATCH_FOUND as soon as the first full matching combination of inner tables of the outer join or the semi-join is discovered. */ enum Match_flag { MATCH_NOT_FOUND, MATCH_FOUND, MATCH_IMPOSSIBLE }; /* Table to be joined with the partial join records from the cache */ JOIN_TAB *join_tab; /* Pointer to the previous join cache if there is any */ JOIN_CACHE *prev_cache; /* Pointer to the next join cache if there is any */ JOIN_CACHE *next_cache; /* Shall initialize the join cache structure */ virtual int init(bool for_explain); /* Get the current size of the cache join buffer */ size_t get_join_buffer_size() { return buff_size; } /* Set the size of the cache join buffer to a new value */ void set_join_buffer_size(size_t sz) { buff_size= sz; } /* Get the minimum possible size of the cache join buffer */ size_t get_min_join_buffer_size(); /* Get the maximum possible size of the cache join buffer */ size_t get_max_join_buffer_size(bool optimize_buff_size, size_t min_buffer_size_arg); /* Shrink the size if the cache join buffer in a given ratio */ bool shrink_join_buffer_in_ratio(ulonglong n, ulonglong d); /* Shall return the type of the employed join algorithm */ virtual enum Join_algorithm get_join_alg()= 0; /* The function shall return TRUE only when there is a key access to the join table */ virtual bool is_key_access()= 0; /* Shall reset the join buffer for reading/writing */ virtual void reset(bool for_writing); /* This function shall add a record into the join buffer and return TRUE if it has been decided that it should be the last record in the buffer. */ virtual bool put_record(); /* This function shall read the next record into the join buffer and return TRUE if there is no more next records. */ virtual bool get_record(); /* This function shall read the record at the position rec_ptr in the join buffer */ virtual void get_record_by_pos(uchar *rec_ptr); /* Shall return the value of the match flag for the positioned record */ virtual enum Match_flag get_match_flag_by_pos(uchar *rec_ptr); /* Shall return the value of the match flag for the positioned record from the join buffer attached to the specified table */ virtual enum Match_flag get_match_flag_by_pos_from_join_buffer(uchar *rec_ptr, JOIN_TAB *tab); /* Shall return the position of the current record */ virtual uchar *get_curr_rec() { return curr_rec_pos; } /* Shall set the current record link */ virtual void set_curr_rec_link(uchar *link) { curr_rec_link= link; } /* Shall return the current record link */ virtual uchar *get_curr_rec_link() { return (curr_rec_link ? curr_rec_link : get_curr_rec()); } /* Join records from the join buffer with records from the next join table */ enum_nested_loop_state join_records(bool skip_last); /* Add a comment on the join algorithm employed by the join cache */ virtual bool save_explain_data(EXPLAIN_BKA_TYPE *explain); THD *thd(); virtual ~JOIN_CACHE() = default; void reset_join(JOIN *j) { join= j; } void free() { my_free(buff); buff= 0; } friend class JOIN_CACHE_HASHED; friend class JOIN_CACHE_BNL; friend class JOIN_CACHE_BKA; friend class JOIN_TAB_SCAN; friend class JOIN_TAB_SCAN_MRR; }; /* The class JOIN_CACHE_HASHED is the base class for the classes JOIN_CACHE_HASHED_BNL and JOIN_CACHE_HASHED_BKA. The first of them supports an implementation of Block Nested Loop Hash (BNLH) Join Algorithm, while the second is used for a variant of the BKA Join algorithm that performs only one lookup for any records from join buffer with the same key value. For a join cache of this class the records from the join buffer that have the same access key are linked into a chain attached to a key entry structure that either itself contains the key value, or, in the case when the keys are embedded, refers to its occurrence in one of the records from the chain. To build the chains with the same keys a hash table is employed. It is placed at the very end of the join buffer. The array of hash entries is allocated first at the very bottom of the join buffer, while key entries are placed before this array. A hash entry contains a header of the list of the key entries with the same hash value. Each key entry is a structure of the following type: struct st_join_cache_key_entry { union { uchar[] value; cache_ref *value_ref; // offset from the beginning of the buffer } hash_table_key; key_ref next_key; // offset backward from the beginning of hash table cache_ref *last_rec // offset from the beginning of the buffer } The references linking the records in a chain are always placed at the very beginning of the record info stored in the join buffer. The records are linked in a circular list. A new record is always added to the end of this list. The following picture represents a typical layout for the info stored in the join buffer of a join cache object of the JOIN_CACHE_HASHED class. buff V +----------------------------------------------------------------------------+ | |[*]record_1_1| | | ^ | | | | +--------------------------------------------------+ | | | |[*]record_2_1| | | | | ^ | V | | | | +------------------+ |[*]record_1_2| | | | +--------------------+-+ | | |+--+ +---------------------+ | | +-------------+ | || | | V | | | |||[*]record_3_1| |[*]record_1_3| |[*]record_2_2| | | ||^ ^ ^ | | ||+----------+ | | | | ||^ | |<---------------------------+-------------------+ | |++ | | ... mrr | buffer ... ... | | | | | | | | | +-----+--------+ | +-----|-------+ | | V | | | V | | | ||key_3|[/]|[*]| | | |key_2|[/]|[*]| | | | +-+---|-----------------------+ | | | V | | | | | | |key_1|[*]|[*]| | | ... |[*]| ... |[*]| ... | | +----------------------------------------------------------------------------+ ^ ^ ^ | i-th entry j-th entry hash table i-th hash entry: circular record chain for key_1: record_1_1 record_1_2 record_1_3 (points to record_1_1) circular record chain for key_3: record_3_1 (points to itself) j-th hash entry: circular record chain for key_2: record_2_1 record_2_2 (points to record_2_1) */ class JOIN_CACHE_HASHED: public JOIN_CACHE { typedef uint (JOIN_CACHE_HASHED::*Hash_func) (uchar *key, uint key_len); typedef bool (JOIN_CACHE_HASHED::*Hash_cmp_func) (uchar *key1, uchar *key2, uint key_len); private: /* Size of the offset of a key entry in the hash table */ uint size_of_key_ofs; /* Length of the key entry in the hash table. A key entry either contains the key value, or it contains a reference to the key value if use_emb_key flag is set for the cache. */ uint key_entry_length; /* The beginning of the hash table in the join buffer */ uchar *hash_table; /* Number of hash entries in the hash table */ uint hash_entries; /* The position of the currently retrieved key entry in the hash table */ uchar *curr_key_entry; /* The offset of the data fields from the beginning of the record fields */ uint data_fields_offset; inline uint get_hash_idx_simple(uchar *key, uint key_len); inline uint get_hash_idx_complex(uchar *key, uint key_len); inline bool equal_keys_simple(uchar *key1, uchar *key2, uint key_len); inline bool equal_keys_complex(uchar *key1, uchar *key2, uint key_len); int init_hash_table(); void cleanup_hash_table(); protected: /* Index info on the TABLE_REF object used by the hash join to look for matching records */ KEY *ref_key_info; /* Number of the key parts the TABLE_REF object used by the hash join to look for matching records */ uint ref_used_key_parts; /* The hash function used in the hash table, usually set by the init() method */ Hash_func hash_func; /* The function to check whether two key entries in the hash table are equal or not, usually set by the init() method */ Hash_cmp_func hash_cmp_func; /* Length of a key value. It is assumed that all key values have the same length. */ uint key_length; /* Buffer to store key values for probing */ uchar *key_buff; /* Number of key entries in the hash table (number of distinct keys) */ uint key_entries; /* The position of the last key entry in the hash table */ uchar *last_key_entry; /* The offset of the record fields from the beginning of the record representation. The record representation starts with a reference to the next record in the key record chain followed by the length of the trailing record data followed by a reference to the record segment in the previous cache, if any, followed by the record fields. */ uint rec_fields_offset; uint get_size_of_key_offset() { return size_of_key_ofs; } /* Get the position of the next_key_ptr field pointed to by a linking reference stored at the position key_ref_ptr. This reference is actually the offset backward from the beginning of hash table. */ uchar *get_next_key_ref(uchar *key_ref_ptr) { return hash_table-get_offset(size_of_key_ofs, key_ref_ptr); } /* Store the linking reference to the next_key_ptr field at the position key_ref_ptr. The position of the next_key_ptr field is pointed to by ref. The stored reference is actually the offset backward from the beginning of the hash table. */ void store_next_key_ref(uchar *key_ref_ptr, uchar *ref) { store_offset(size_of_key_ofs, key_ref_ptr, (ulong) (hash_table-ref)); } /* Check whether the reference to the next_key_ptr field at the position key_ref_ptr contains a nil value. */ bool is_null_key_ref(uchar *key_ref_ptr) { ulong nil= 0; return memcmp(key_ref_ptr, &nil, size_of_key_ofs ) == 0; } /* Set the reference to the next_key_ptr field at the position key_ref_ptr equal to nil. */ void store_null_key_ref(uchar *key_ref_ptr) { ulong nil= 0; store_offset(size_of_key_ofs, key_ref_ptr, nil); } uchar *get_next_rec_ref(uchar *ref_ptr) { return buff+get_offset(get_size_of_rec_offset(), ref_ptr); } void store_next_rec_ref(uchar *ref_ptr, uchar *ref) { store_offset(get_size_of_rec_offset(), ref_ptr, (ulong) (ref-buff)); } /* Get the position of the embedded key value for the current record pointed to by get_curr_rec(). */ uchar *get_curr_emb_key() { return get_curr_rec()+data_fields_offset; } /* Get the position of the embedded key value pointed to by a reference stored at ref_ptr. The stored reference is actually the offset from the beginning of the join buffer. */ uchar *get_emb_key(uchar *ref_ptr) { return buff+get_offset(get_size_of_rec_offset(), ref_ptr); } /* Store the reference to an embedded key at the position key_ref_ptr. The position of the embedded key is pointed to by ref. The stored reference is actually the offset from the beginning of the join buffer. */ void store_emb_key_ref(uchar *ref_ptr, uchar *ref) { store_offset(get_size_of_rec_offset(), ref_ptr, (ulong) (ref-buff)); } /* Get the total length of all prefixes of a record in hashed join buffer */ uint get_prefix_length() override { return base_prefix_length + get_size_of_rec_offset(); } /* Get maximum size of the additional space per record used for the hash table with record keys */ uint get_max_key_addon_space_per_record() override; /* Calculate how much space in the buffer would not be occupied by records, key entries and additional memory for the MMR buffer. */ size_t rem_space() override { return MY_MAX(last_key_entry-end_pos-aux_buff_size,0); } /* Calculate how much space is taken by allocation of the key entry for a record in the join buffer */ uint extra_key_length() override { return key_entry_length; } /* Skip record from a hashed join buffer if its match flag is set to MATCH_FOUND */ bool skip_if_matched() override; /* Skip record from a hashed join buffer if its match flag setting commands to do so */ bool skip_if_not_needed_match() override; /* Search for a key in the hash table of the join buffer */ bool key_search(uchar *key, uint key_len, uchar **key_ref_ptr); /* Reallocate the join buffer of a hashed join cache */ int realloc_buffer() override; /* This constructor creates an unlinked hashed join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. */ JOIN_CACHE_HASHED(JOIN *j, JOIN_TAB *tab) :JOIN_CACHE(j, tab) {} /* This constructor creates a linked hashed join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The parameter 'prev' specifies the previous cache object to which this cache is linked. */ JOIN_CACHE_HASHED(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) :JOIN_CACHE(j, tab, prev) {} public: /* Initialize a hashed join cache */ int init(bool for_explain) override; /* Reset the buffer of a hashed join cache for reading/writing */ void reset(bool for_writing) override; /* Add a record into the buffer of a hashed join cache */ bool put_record() override; /* Read the next record from the buffer of a hashed join cache */ bool get_record() override; /* Shall check whether all records in a key chain have their match flags set on */ virtual bool check_all_match_flags_for_key(uchar *key_chain_ptr); uint get_next_key(uchar **key); /* Get the head of the record chain attached to the current key entry */ uchar *get_curr_key_chain() { return get_next_rec_ref(curr_key_entry+key_entry_length- get_size_of_rec_offset()); } }; /* The class JOIN_TAB_SCAN is a companion class for the classes JOIN_CACHE_BNL and JOIN_CACHE_BNLH. Actually the class implements the iterator over the table joinded by BNL/BNLH join algorithm. The virtual functions open, next and close are called for any iteration over the table. The function open is called to initiate the process of the iteration. The function next shall read the next record from the joined table. The record is read into the record buffer of the joined table. The record is to be matched with records from the join cache buffer. The function close shall perform the finalizing actions for the iteration. */ class JOIN_TAB_SCAN: public Sql_alloc { private: /* TRUE if this is the first record from the joined table to iterate over */ bool is_first_record; protected: /* The joined table to be iterated over */ JOIN_TAB *join_tab; /* The join cache used to join the table join_tab */ JOIN_CACHE *cache; /* Representation of the executed multi-way join through which all needed context can be accessed. */ JOIN *join; public: JOIN_TAB_SCAN(JOIN *j, JOIN_TAB *tab) { join= j; join_tab= tab; cache= join_tab->cache; } virtual ~JOIN_TAB_SCAN() = default; /* Shall calculate the increment of the auxiliary buffer for a record write if such a buffer is used by the table scan object */ virtual uint aux_buffer_incr(size_t recno) { return 0; } /* Initiate the process of iteration over the joined table */ virtual int open(); /* Shall read the next candidate for matches with records from the join buffer. */ virtual int next(); /* Perform the finalizing actions for the process of iteration over the joined_table. */ virtual void close(); }; /* The class JOIN_CACHE_BNL is used when the BNL join algorithm is employed to perform a join operation */ class JOIN_CACHE_BNL :public JOIN_CACHE { private: /* The number of the records in the join buffer that have to be checked yet for a match with the current record of join_tab read into the record buffer. */ uint rem_records; protected: bool prepare_look_for_matches(bool skip_last) override; uchar *get_next_candidate_for_match() override; bool skip_next_candidate_for_match(uchar *rec_ptr) override; void read_next_candidate_for_match(uchar *rec_ptr) override; public: /* This constructor creates an unlinked BNL join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. */ JOIN_CACHE_BNL(JOIN *j, JOIN_TAB *tab) :JOIN_CACHE(j, tab) {} /* This constructor creates a linked BNL join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The parameter 'prev' specifies the previous cache object to which this cache is linked. */ JOIN_CACHE_BNL(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) :JOIN_CACHE(j, tab, prev) {} /* Initialize the BNL cache */ int init(bool for_explain) override; enum Join_algorithm get_join_alg() override { return BNL_JOIN_ALG; } bool is_key_access() override { return FALSE; } }; /* The class JOIN_CACHE_BNLH is used when the BNLH join algorithm is employed to perform a join operation */ class JOIN_CACHE_BNLH :public JOIN_CACHE_HASHED { protected: /* The pointer to the last record from the circular list of the records that match the join key built out of the record in the join buffer for the join_tab table */ uchar *last_matching_rec_ref_ptr; /* The pointer to the next current record from the circular list of the records that match the join key built out of the record in the join buffer for the join_tab table. This pointer is used by the class method get_next_candidate_for_match to iterate over records from the circular list. */ uchar *next_matching_rec_ref_ptr; /* Get the chain of records from buffer matching the current candidate record for join */ uchar *get_matching_chain_by_join_key(); bool prepare_look_for_matches(bool skip_last) override; uchar *get_next_candidate_for_match() override; bool skip_next_candidate_for_match(uchar *rec_ptr) override; void read_next_candidate_for_match(uchar *rec_ptr) override; public: /* This constructor creates an unlinked BNLH join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. */ JOIN_CACHE_BNLH(JOIN *j, JOIN_TAB *tab) : JOIN_CACHE_HASHED(j, tab) {} /* This constructor creates a linked BNLH join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The parameter 'prev' specifies the previous cache object to which this cache is linked. */ JOIN_CACHE_BNLH(JOIN *j, JOIN_TAB *tab, JOIN_CACHE *prev) : JOIN_CACHE_HASHED(j, tab, prev) {} /* Initialize the BNLH cache */ int init(bool for_explain) override; enum Join_algorithm get_join_alg() override { return BNLH_JOIN_ALG; } bool is_key_access() override { return TRUE; } }; /* The class JOIN_TAB_SCAN_MRR is a companion class for the classes JOIN_CACHE_BKA and JOIN_CACHE_BKAH. Actually the class implements the iterator over the records from join_tab selected by BKA/BKAH join algorithm as the candidates to be joined. The virtual functions open, next and close are called for any iteration over join_tab record candidates. The function open is called to initiate the process of the iteration. The function next shall read the next record from the set of the record candidates. The record is read into the record buffer of the joined table. The function close shall perform the finalizing actions for the iteration. */ class JOIN_TAB_SCAN_MRR: public JOIN_TAB_SCAN { /* Interface object to generate key ranges for MRR */ RANGE_SEQ_IF range_seq_funcs; /* Number of ranges to be processed by the MRR interface */ uint ranges; /* Flag to to be passed to the MRR interface */ uint mrr_mode; /* MRR buffer assotiated with this join cache */ HANDLER_BUFFER mrr_buff; /* Shall initialize the MRR buffer */ virtual void init_mrr_buff() { cache->setup_aux_buffer(mrr_buff); } public: JOIN_TAB_SCAN_MRR(JOIN *j, JOIN_TAB *tab, uint flags, RANGE_SEQ_IF rs_funcs) :JOIN_TAB_SCAN(j, tab), range_seq_funcs(rs_funcs), mrr_mode(flags) {} uint aux_buffer_incr(size_t recno) override; int open() override; int next() override; friend class JOIN_CACHE_BKA; /* it needs to add an mrr_mode flag after JOIN_CACHE::init() call */ }; /* The class JOIN_CACHE_BKA is used when the BKA join algorithm is employed to perform a join operation */ class JOIN_CACHE_BKA :public JOIN_CACHE { private: /* Flag to to be passed to the companion JOIN_TAB_SCAN_MRR object */ uint mrr_mode; /* This value is set to 1 by the class prepare_look_for_matches method and back to 0 by the class get_next_candidate_for_match method */ uint rem_records; /* This field contains the current association label set by a call of the multi_range_read_next handler function. See the function JOIN_CACHE_BKA::get_curr_key_association() */ uchar *curr_association; protected: /* Get the number of ranges in the cache buffer passed to the MRR interface. For each record its own range is passed. */ uint get_number_of_ranges_for_mrr() override { return (uint)records; } /* Setup the MRR buffer as the space between the last record put into the join buffer and the very end of the join buffer */ int setup_aux_buffer(HANDLER_BUFFER &aux_buff) override { aux_buff.buffer= end_pos; aux_buff.buffer_end= buff+buff_size; return 0; } bool prepare_look_for_matches(bool skip_last) override; uchar *get_next_candidate_for_match() override; bool skip_next_candidate_for_match(uchar *rec_ptr) override; void read_next_candidate_for_match(uchar *rec_ptr) override; public: /* This constructor creates an unlinked BKA join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The MRR mode initially is set to 'flags'. */ JOIN_CACHE_BKA(JOIN *j, JOIN_TAB *tab, uint flags) :JOIN_CACHE(j, tab), mrr_mode(flags) {} /* This constructor creates a linked BKA join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The parameter 'prev' specifies the previous cache object to which this cache is linked. The MRR mode initially is set to 'flags'. */ JOIN_CACHE_BKA(JOIN *j, JOIN_TAB *tab, uint flags, JOIN_CACHE *prev) :JOIN_CACHE(j, tab, prev), mrr_mode(flags) {} JOIN_CACHE_BKA(JOIN_CACHE_BKA *bka) :JOIN_CACHE(bka->join, bka->join_tab, bka->prev_cache), mrr_mode(bka->mrr_mode) {} uchar **get_curr_association_ptr() override { return &curr_association; } /* Initialize the BKA cache */ int init(bool for_explain) override; enum Join_algorithm get_join_alg() override { return BKA_JOIN_ALG; } bool is_key_access() override { return TRUE; } /* Get the key built over the next record from the join buffer */ uint get_next_key(uchar **key); /* Check index condition of the joined table for a record from BKA cache */ bool skip_index_tuple(range_id_t range_info); bool save_explain_data(EXPLAIN_BKA_TYPE *explain) override; }; /* The class JOIN_CACHE_BKAH is used when the BKAH join algorithm is employed to perform a join operation */ class JOIN_CACHE_BKAH :public JOIN_CACHE_BNLH { private: /* Flag to to be passed to the companion JOIN_TAB_SCAN_MRR object */ uint mrr_mode; /* This flag is set to TRUE if the implementation of the MRR interface cannot handle range association labels and does not return them to the caller of the multi_range_read_next handler function. E.g. the implementation of the MRR inteface for the Falcon engine could not return association labels to the caller of multi_range_read_next. The flag is set by JOIN_CACHE_BKA::init() and is not ever changed. */ bool no_association; /* This field contains the association label returned by the multi_range_read_next function. See the function JOIN_CACHE_BKAH::get_curr_key_association() */ uchar *curr_matching_chain; protected: uint get_number_of_ranges_for_mrr() override { return key_entries; } /* Initialize the MRR buffer allocating some space within the join buffer. The entire space between the last record put into the join buffer and the last key entry added to the hash table is used for the MRR buffer. */ int setup_aux_buffer(HANDLER_BUFFER &aux_buff) override { aux_buff.buffer= end_pos; aux_buff.buffer_end= last_key_entry; return 0; } bool prepare_look_for_matches(bool skip_last) override; /* The implementations of the methods - get_next_candidate_for_match - skip_recurrent_candidate_for_match - read_next_candidate_for_match are inherited from the JOIN_CACHE_BNLH class */ public: /* This constructor creates an unlinked BKAH join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The MRR mode initially is set to 'flags'. */ JOIN_CACHE_BKAH(JOIN *j, JOIN_TAB *tab, uint flags) :JOIN_CACHE_BNLH(j, tab), mrr_mode(flags) {} /* This constructor creates a linked BKAH join cache. The cache is to be used to join table 'tab' to the result of joining the previous tables specified by the 'j' parameter. The parameter 'prev' specifies the previous cache object to which this cache is linked. The MRR mode initially is set to 'flags'. */ JOIN_CACHE_BKAH(JOIN *j, JOIN_TAB *tab, uint flags, JOIN_CACHE *prev) :JOIN_CACHE_BNLH(j, tab, prev), mrr_mode(flags) {} JOIN_CACHE_BKAH(JOIN_CACHE_BKAH *bkah) :JOIN_CACHE_BNLH(bkah->join, bkah->join_tab, bkah->prev_cache), mrr_mode(bkah->mrr_mode) {} uchar **get_curr_association_ptr() override { return &curr_matching_chain; } /* Initialize the BKAH cache */ int init(bool for_explain) override; enum Join_algorithm get_join_alg() override { return BKAH_JOIN_ALG; } /* Check index condition of the joined table for a record from BKAH cache */ bool skip_index_tuple(range_id_t range_info); bool save_explain_data(EXPLAIN_BKA_TYPE *explain) override; }; mysql/server/private/sql_load.h000064400000002374151027430560012651 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_LOAD_INCLUDED #define SQL_LOAD_INCLUDED #include "sql_list.h" /* List */ class Item; #include "sql_class.h" /* enum_duplicates */ class sql_exchange; int mysql_load(THD *thd, const sql_exchange *ex, TABLE_LIST *table_list, List &fields_vars, List &set_fields, List &set_values_list, enum enum_duplicates handle_duplicates, bool ignore, bool local_file); #endif /* SQL_LOAD_INCLUDED */ mysql/server/private/sql_profile.h000064400000017210151027430560013365 0ustar00/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _SQL_PROFILE_H #define _SQL_PROFILE_H class Item; struct TABLE_LIST; class THD; class ST_FIELD_INFO; typedef struct st_schema_table ST_SCHEMA_TABLE; namespace Show { extern ST_FIELD_INFO query_profile_statistics_info[]; } // namespace Show int fill_query_profile_statistics_info(THD *thd, TABLE_LIST *tables, Item *cond); int make_profile_table_for_show(THD *thd, ST_SCHEMA_TABLE *schema_table); #define PROFILE_NONE (uint)0 #define PROFILE_CPU (uint)(1<<0) #define PROFILE_MEMORY (uint)(1<<1) #define PROFILE_BLOCK_IO (uint)(1<<2) #define PROFILE_CONTEXT (uint)(1<<3) #define PROFILE_PAGE_FAULTS (uint)(1<<4) #define PROFILE_IPC (uint)(1<<5) #define PROFILE_SWAPS (uint)(1<<6) #define PROFILE_SOURCE (uint)(1<<16) #define PROFILE_ALL (uint)(~0) #if defined(ENABLED_PROFILING) #include "sql_priv.h" #include "unireg.h" #ifdef _WIN32 #include #endif #ifdef HAVE_SYS_RESOURCE_H #include #endif extern PSI_memory_key key_memory_queue_item; class PROF_MEASUREMENT; class QUERY_PROFILE; class PROFILING; /** Implements a persistent FIFO using server List method names. Not thread-safe. Intended to be used on thread-local data only. */ template class Queue { private: struct queue_item { T *payload; struct queue_item *next, *previous; }; struct queue_item *first, *last; public: Queue() { elements= 0; first= last= NULL; } void empty() { struct queue_item *i, *after_i; for (i= first; i != NULL; i= after_i) { after_i= i->next; my_free(i); } elements= 0; } ulong elements; /* The count of items in the Queue */ void push_back(T *payload) { struct queue_item *new_item; new_item= (struct queue_item *) my_malloc(key_memory_queue_item, sizeof(struct queue_item), MYF(0)); if (!new_item) return; new_item->payload= payload; if (first == NULL) first= new_item; if (last != NULL) { DBUG_ASSERT(last->next == NULL); last->next= new_item; } new_item->previous= last; new_item->next= NULL; last= new_item; elements++; } T *pop() { struct queue_item *old_item= first; T *ret= NULL; if (first == NULL) { DBUG_PRINT("warning", ("tried to pop nonexistent item from Queue")); return NULL; } ret= old_item->payload; if (first->next != NULL) first->next->previous= NULL; else last= NULL; first= first->next; my_free(old_item); elements--; return ret; } bool is_empty() { DBUG_ASSERT(((elements > 0) && (first != NULL)) || ((elements == 0) || (first == NULL))); return (elements == 0); } void *new_iterator() { return first; } void *iterator_next(void *current) { return ((struct queue_item *) current)->next; } T *iterator_value(void *current) { return ((struct queue_item *) current)->payload; } }; /** A single entry in a single profile. */ class PROF_MEASUREMENT { private: friend class QUERY_PROFILE; friend class PROFILING; QUERY_PROFILE *profile; char *status; #ifdef HAVE_GETRUSAGE struct rusage rusage; #elif defined(_WIN32) FILETIME ftKernel, ftUser; IO_COUNTERS io_count; PROCESS_MEMORY_COUNTERS mem_count; #endif char *function; char *file; unsigned int line; ulong m_seq; double time_usecs; char *allocated_status_memory; void set_label(const char *status_arg, const char *function_arg, const char *file_arg, unsigned int line_arg); void clean_up(); PROF_MEASUREMENT(); PROF_MEASUREMENT(QUERY_PROFILE *profile_arg, const char *status_arg); PROF_MEASUREMENT(QUERY_PROFILE *profile_arg, const char *status_arg, const char *function_arg, const char *file_arg, unsigned int line_arg); ~PROF_MEASUREMENT(); void collect(); }; /** The full profile for a single query, and includes multiple PROF_MEASUREMENT objects. */ class QUERY_PROFILE { private: friend class PROFILING; PROFILING *profiling; query_id_t profiling_query_id; /* Session-specific id. */ char *query_source; double m_start_time_usecs; double m_end_time_usecs; ulong m_seq_counter; Queue entries; QUERY_PROFILE(PROFILING *profiling_arg, const char *status_arg); ~QUERY_PROFILE(); void set_query_source(char *query_source_arg, size_t query_length_arg); /* Add a profile status change to the current profile. */ void new_status(const char *status_arg, const char *function_arg, const char *file_arg, unsigned int line_arg); /* Reset the contents of this profile entry. */ void reset(); /* Show this profile. This is called by PROFILING. */ bool show(uint options); }; /** Profiling state for a single THD; contains multiple QUERY_PROFILE objects. */ class PROFILING { private: friend class PROF_MEASUREMENT; friend class QUERY_PROFILE; /* Not the system query_id, but a counter unique to profiling. */ query_id_t profile_id_counter; THD *thd; bool keeping; bool enabled; QUERY_PROFILE *current; QUERY_PROFILE *last; Queue history; query_id_t next_profile_id() { return(profile_id_counter++); } public: PROFILING(); ~PROFILING(); /** At a point in execution where we know the query source, save the text of it in the query profile. This must be called exactly once per descrete statement. */ void set_query_source(char *query_source_arg, size_t query_length_arg) { if (unlikely(current)) current->set_query_source(query_source_arg, query_length_arg); } /** Prepare to start processing a new query. It is an error to do this if there's a query already in process; nesting is not supported. @param initial_state (optional) name of period before first state change */ void start_new_query(const char *initial_state= "Starting") { DBUG_ASSERT(!current); if (unlikely(enabled)) { QUERY_PROFILE *new_profile= new QUERY_PROFILE(this, initial_state); if (new_profile) current= new_profile; } } void discard_current_query(); void finish_current_query() { if (unlikely(current)) finish_current_query_impl(); } void finish_current_query_impl(); void status_change(const char *status_arg, const char *function_arg, const char *file_arg, unsigned int line_arg) { if (unlikely(current)) current->new_status(status_arg, function_arg, file_arg, line_arg); } inline void set_thd(THD *thd_arg) { thd= thd_arg; reset(); } /* SHOW PROFILES */ bool show_profiles(); /* ... from INFORMATION_SCHEMA.PROFILING ... */ int fill_statistics_info(THD *thd, TABLE_LIST *tables, Item *cond); void reset(); void restart(); }; # endif /* ENABLED_PROFILING */ #endif /* _SQL_PROFILE_H */ mysql/server/private/innodb_priv.h000064400000002447151027430560013365 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef INNODB_PRIV_INCLUDED #define INNODB_PRIV_INCLUDED /** @file Declaring server-internal functions that are used by InnoDB. */ #include #include /* strconvert */ class THD; int get_quote_char_for_identifier(THD *thd, const char *name, size_t length); bool schema_table_store_record(THD *thd, TABLE *table); void localtime_to_TIME(MYSQL_TIME *to, struct tm *from); void sql_print_error(const char *format, ...); #define thd_binlog_pos(X, Y, Z) mysql_bin_log_commit_pos(X, Z, Y) #endif /* INNODB_PRIV_INCLUDED */ mysql/server/private/sql_type_int.h000064400000023421151027430560013561 0ustar00/* Copyright (c) 2018, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_TYPE_INT_INCLUDED #define SQL_TYPE_INT_INCLUDED #include "my_bit.h" // my_count_bits() class Null_flag { protected: bool m_is_null; public: bool is_null() const { return m_is_null; } Null_flag(bool is_null) :m_is_null(is_null) { } }; class Longlong { protected: longlong m_value; public: longlong value() const { return m_value; } Longlong(longlong nr) :m_value(nr) { } ulonglong abs() { if (m_value == LONGLONG_MIN) // avoid undefined behavior return ((ulonglong) LONGLONG_MAX) + 1; return m_value < 0 ? -m_value : m_value; } }; class Longlong_null: public Longlong, public Null_flag { public: Longlong_null(longlong nr, bool is_null) :Longlong(nr), Null_flag(is_null) { } explicit Longlong_null() :Longlong(0), Null_flag(true) { } explicit Longlong_null(longlong nr) :Longlong(nr), Null_flag(false) { } Longlong_null operator|(const Longlong_null &other) const { if (is_null() || other.is_null()) return Longlong_null(); return Longlong_null(value() | other.value()); } Longlong_null operator&(const Longlong_null &other) const { if (is_null() || other.is_null()) return Longlong_null(); return Longlong_null(value() & other.value()); } Longlong_null operator^(const Longlong_null &other) const { if (is_null() || other.is_null()) return Longlong_null(); return Longlong_null((longlong) (value() ^ other.value())); } Longlong_null operator~() const { if (is_null()) return *this; return Longlong_null((longlong) ~ (ulonglong) value()); } Longlong_null operator<<(const Longlong_null &llshift) const { ulonglong res; uint shift; if (is_null() || llshift.is_null()) return Longlong_null(); shift= (uint) llshift.value(); res= 0; if (shift < sizeof(longlong) * 8) res= ((ulonglong) value()) << shift; return Longlong_null((longlong) res); } Longlong_null operator>>(const Longlong_null &llshift) const { ulonglong res; uint shift; if (is_null() || llshift.is_null()) return Longlong_null(); shift= (uint) llshift.value(); res= 0; if (shift < sizeof(longlong) * 8) res= ((ulonglong) value()) >> shift; return Longlong_null(res); } Longlong_null bit_count() const { if (is_null()) return *this; return Longlong_null((longlong) my_count_bits((ulonglong) value())); } }; class ULonglong { protected: ulonglong m_value; public: ulonglong value() const { return m_value; } explicit ULonglong(ulonglong nr) :m_value(nr) { } static bool test_if_sum_overflows_ull(ulonglong arg1, ulonglong arg2) { return ULONGLONG_MAX - arg1 < arg2; } Longlong_null operator-() const { if (m_value > (ulonglong) LONGLONG_MAX) // Avoid undefined behaviour { return m_value == (ulonglong) LONGLONG_MAX + 1 ? Longlong_null(LONGLONG_MIN, false) : Longlong_null(0, true); } return Longlong_null(-(longlong) m_value, false); } // Convert to Longlong_null with the range check Longlong_null to_longlong_null() const { if (m_value > (ulonglong) LONGLONG_MAX) return Longlong_null(0, true); return Longlong_null((longlong) m_value, false); } }; class ULonglong_null: public ULonglong, public Null_flag { public: ULonglong_null(ulonglong nr, bool is_null) :ULonglong(nr), Null_flag(is_null) { } /* Multiply two ulonglong values. Let a = a1 * 2^32 + a0 and b = b1 * 2^32 + b0. Then a * b = (a1 * 2^32 + a0) * (b1 * 2^32 + b0) = a1 * b1 * 2^64 + + (a1 * b0 + a0 * b1) * 2^32 + a0 * b0; We can determine if the above sum overflows the ulonglong range by sequentially checking the following conditions: 1. If both a1 and b1 are non-zero. 2. Otherwise, if (a1 * b0 + a0 * b1) is greater than ULONG_MAX. 3. Otherwise, if (a1 * b0 + a0 * b1) * 2^32 + a0 * b0 is greater than ULONGLONG_MAX. */ static ULonglong_null ullmul(ulonglong a, ulonglong b) { ulong a1= (ulong)(a >> 32); ulong b1= (ulong)(b >> 32); if (a1 && b1) return ULonglong_null(0, true); ulong a0= (ulong)(0xFFFFFFFFUL & a); ulong b0= (ulong)(0xFFFFFFFFUL & b); ulonglong res1= (ulonglong) a1 * b0 + (ulonglong) a0 * b1; if (res1 > 0xFFFFFFFFUL) return ULonglong_null(0, true); res1= res1 << 32; ulonglong res0= (ulonglong) a0 * b0; if (test_if_sum_overflows_ull(res1, res0)) return ULonglong_null(0, true); return ULonglong_null(res1 + res0, false); } }; // A longlong/ulonglong hybrid. Good to store results of val_int(). class Longlong_hybrid: public Longlong { protected: bool m_unsigned; int cmp_signed(const Longlong_hybrid& other) const { return m_value < other.m_value ? -1 : m_value == other.m_value ? 0 : 1; } int cmp_unsigned(const Longlong_hybrid& other) const { return (ulonglong) m_value < (ulonglong) other.m_value ? -1 : m_value == other.m_value ? 0 : 1; } public: Longlong_hybrid(longlong nr, bool unsigned_flag) :Longlong(nr), m_unsigned(unsigned_flag) { } bool is_unsigned() const { return m_unsigned; } bool is_unsigned_outside_of_signed_range() const { return m_unsigned && ((ulonglong) m_value) > (ulonglong) LONGLONG_MAX; } bool neg() const { return m_value < 0 && !m_unsigned; } ulonglong abs() const { if (m_unsigned) return (ulonglong) m_value; return Longlong(m_value).abs(); } /* Convert to an unsigned number: - Negative numbers are converted to 0. - Positive numbers bigger than upper_bound are converted to upper_bound. - Other numbers are returned as is. */ ulonglong to_ulonglong(ulonglong upper_bound) const { return neg() ? 0 : (ulonglong) m_value > upper_bound ? upper_bound : (ulonglong) m_value; } uint to_uint(uint upper_bound) const { return (uint) to_ulonglong(upper_bound); } Longlong_null val_int_signed() const { if (m_unsigned) return ULonglong((ulonglong) m_value).to_longlong_null(); return Longlong_null(m_value, false); } Longlong_null val_int_unsigned() const { if (!m_unsigned && m_value < 0) return Longlong_null(0, true); return Longlong_null(m_value, false); } /* Return in Item compatible val_int() format: - signed numbers as a straight longlong value - unsigned numbers as a ulonglong value reinterpreted to longlong */ Longlong_null val_int(bool want_unsigned_value) const { return want_unsigned_value ? val_int_unsigned() : val_int_signed(); } int cmp(const Longlong_hybrid& other) const { if (m_unsigned == other.m_unsigned) return m_unsigned ? cmp_unsigned(other) : cmp_signed(other); if (is_unsigned_outside_of_signed_range()) return 1; if (other.is_unsigned_outside_of_signed_range()) return -1; /* The unsigned argument is in the range 0..LONGLONG_MAX. The signed argument is in the range LONGLONG_MIN..LONGLONG_MAX. Safe to compare as signed. */ return cmp_signed(other); } bool operator==(const Longlong_hybrid &nr) const { return cmp(nr) == 0; } bool operator==(ulonglong nr) const { return cmp(Longlong_hybrid((longlong) nr, true)) == 0; } bool operator==(uint nr) const { return cmp(Longlong_hybrid((longlong) nr, true)) == 0; } bool operator==(longlong nr) const { return cmp(Longlong_hybrid(nr, false)) == 0; } bool operator==(int nr) const { return cmp(Longlong_hybrid(nr, false)) == 0; } }; class Longlong_hybrid_null: public Longlong_hybrid, public Null_flag { public: Longlong_hybrid_null(const Longlong_null &nr, bool unsigned_flag) :Longlong_hybrid(nr.value(), unsigned_flag), Null_flag(nr.is_null()) { } }; /* Stores the absolute value of a number, and the sign. Value range: -ULONGLONG_MAX .. +ULONGLONG_MAX. Provides a wider range for negative numbers than Longlong_hybrid does. Usefull to store intermediate results of an expression whose value is further needed to be negated. For example, these methods: - Item_func_mul::int_op() - Item_func_int_div::val_int() - Item_func_mod::int_op() calculate the result of absolute values of the arguments, then optionally negate the result. */ class ULonglong_hybrid: public ULonglong { bool m_neg; public: ULonglong_hybrid(ulonglong value, bool neg) :ULonglong(value), m_neg(neg) { if (m_neg && !m_value) m_neg= false; // convert -0 to +0 } Longlong_null val_int_unsigned() const { return m_neg ? Longlong_null(0, true) : Longlong_null((longlong) m_value, false); } Longlong_null val_int_signed() const { return m_neg ? -ULonglong(m_value) : ULonglong::to_longlong_null(); } /* Return in Item compatible val_int() format: - signed numbers as a straight longlong value - unsigned numbers as a ulonglong value reinterpreted to longlong */ Longlong_null val_int(bool want_unsigned_value) const { return want_unsigned_value ? val_int_unsigned() : val_int_signed(); } }; #endif // SQL_TYPE_INT_INCLUDED mysql/server/private/sql_sort.h000064400000052717151027430560012727 0ustar00#ifndef SQL_SORT_INCLUDED #define SQL_SORT_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "my_base.h" /* ha_rows */ #include #include "queues.h" #include "sql_string.h" #include "sql_class.h" class Field; struct TABLE; /* Defines used by filesort and uniques */ #define MERGEBUFF 7 #define MERGEBUFF2 15 /* The structure SORT_ADDON_FIELD describes a fixed layout for field values appended to sorted values in records to be sorted in the sort buffer. Only fixed layout is supported now. Null bit maps for the appended values is placed before the values themselves. Offsets are from the last sorted field, that is from the record referefence, which is still last component of sorted records. It is preserved for backward compatiblility. The structure is used tp store values of the additional fields in the sort buffer. It is used also when these values are read from a temporary file/buffer. As the reading procedures are beyond the scope of the 'filesort' code the values have to be retrieved via the callback function 'unpack_addon_fields'. */ typedef struct st_sort_addon_field { /* Sort addon packed field */ Field *field; /* Original field */ uint offset; /* Offset from the last sorted field */ uint null_offset; /* Offset to to null bit from the last sorted field */ uint length; /* Length in the sort buffer */ uint8 null_bit; /* Null bit mask for the field */ } SORT_ADDON_FIELD; struct BUFFPEK_COMPARE_CONTEXT { qsort_cmp2 key_compare; void *key_compare_arg; }; /** Descriptor for a merge chunk to be sort-merged. A merge chunk is a sequence of pre-sorted records, written to a temporary file. A Merge_chunk instance describes where this chunk is stored in the file, and where it is located when it is in memory. It is a POD because - we read/write them from/to files. We have accessors (getters/setters) for all struct members. */ struct Merge_chunk { public: my_off_t file_position() const { return m_file_position; } void set_file_position(my_off_t val) { m_file_position= val; } void advance_file_position(my_off_t val) { m_file_position+= val; } uchar *buffer_start() { return m_buffer_start; } const uchar *buffer_end() const { return m_buffer_end; } void set_buffer(uchar *start, uchar *end) { m_buffer_start= start; m_buffer_end= end; } void set_buffer_start(uchar *start) { m_buffer_start= start; } void set_buffer_end(uchar *end) { DBUG_ASSERT(m_buffer_end == NULL || end <= m_buffer_end); m_buffer_end= end; } void init_current_key() { m_current_key= m_buffer_start; } uchar *current_key() { return m_current_key; } void advance_current_key(uint val) { m_current_key+= val; } void decrement_rowcount(ha_rows val) { m_rowcount-= val; } void set_rowcount(ha_rows val) { m_rowcount= val; } ha_rows rowcount() const { return m_rowcount; } ha_rows mem_count() const { return m_mem_count; } void set_mem_count(ha_rows val) { m_mem_count= val; } ha_rows decrement_mem_count() { return --m_mem_count; } ha_rows max_keys() const { return m_max_keys; } void set_max_keys(ha_rows val) { m_max_keys= val; } size_t buffer_size() const { return m_buffer_end - m_buffer_start; } /** Tries to merge *this with *mc, returns true if successful. The assumption is that *this is no longer in use, and the space it has been allocated can be handed over to a buffer which is adjacent to it. */ bool merge_freed_buff(Merge_chunk *mc) const { if (mc->m_buffer_end == m_buffer_start) { mc->m_buffer_end= m_buffer_end; mc->m_max_keys+= m_max_keys; return true; } else if (mc->m_buffer_start == m_buffer_end) { mc->m_buffer_start= m_buffer_start; mc->m_max_keys+= m_max_keys; return true; } return false; } /// The current key for this chunk uchar *m_current_key= nullptr; /// Current position in the file to be sorted. my_off_t m_file_position= 0; /// Start of main-memory buffer for this chunk. uchar *m_buffer_start= nullptr; /// End of main-memory buffer for this chunk. uchar *m_buffer_end= nullptr; /// Number of unread rows in this chunk. ha_rows m_rowcount= 0; /// Number of rows in the main-memory buffer. ha_rows m_mem_count= 0; /// If we have fixed-size rows: max number of rows in buffer. ha_rows m_max_keys= 0; }; typedef Bounds_checked_array Addon_fields_array; typedef Bounds_checked_array Sort_keys_array; /** This class wraps information about usage of addon fields. An Addon_fields object is used both during packing of data in the filesort buffer, and later during unpacking in 'Filesort_info::unpack_addon_fields'. @see documentation for the Sort_addon_field struct. @see documentation for get_addon_fields() */ class Addon_fields { public: Addon_fields(Addon_fields_array arr) : m_field_descriptors(arr), m_addon_buf(), m_addon_buf_length(), m_using_packed_addons(false) { DBUG_ASSERT(!arr.is_null()); } SORT_ADDON_FIELD *begin() { return m_field_descriptors.begin(); } SORT_ADDON_FIELD *end() { return m_field_descriptors.end(); } /// rr_unpack_from_tempfile needs an extra buffer when unpacking. uchar *allocate_addon_buf(uint sz) { m_addon_buf= (uchar *)my_malloc(PSI_INSTRUMENT_ME, sz, MYF(MY_WME | MY_THREAD_SPECIFIC)); if (m_addon_buf) m_addon_buf_length= sz; return m_addon_buf; } void free_addon_buff() { my_free(m_addon_buf); m_addon_buf= NULL; m_addon_buf_length= 0; } uchar *get_addon_buf() { return m_addon_buf; } uint get_addon_buf_length() const { return m_addon_buf_length; } void set_using_packed_addons(bool val) { m_using_packed_addons= val; } bool using_packed_addons() const { return m_using_packed_addons; } static bool can_pack_addon_fields(uint record_length) { return (record_length <= (0xFFFF)); } /** @returns Total number of bytes used for packed addon fields. the size of the length field + size of null bits + sum of field sizes. */ static uint read_addon_length(uchar *p) { return size_of_length_field + uint2korr(p); } /** Stores the number of bytes used for packed addon fields. */ static void store_addon_length(uchar *p, uint sz) { // We actually store the length of everything *after* the length field. int2store(p, sz - size_of_length_field); } static const uint size_of_length_field= 2; private: Addon_fields_array m_field_descriptors; uchar *m_addon_buf; ///< Buffer for unpacking addon fields. uint m_addon_buf_length; ///< Length of the buffer. bool m_using_packed_addons; ///< Are we packing the addon fields? }; /** This class wraps information about usage of sort keys. A Sort_keys object is used both during packing of data in the filesort buffer, and later during unpacking in 'Filesort_info::unpack_addon_fields'. @see SORT_FIELD struct. */ class Sort_keys :public Sql_alloc, public Sort_keys_array { public: Sort_keys(SORT_FIELD* arr, size_t count): Sort_keys_array(arr, count), m_using_packed_sortkeys(false), size_of_packable_fields(0), sort_length_with_original_values(0), sort_length_with_memcmp_values(0), parameters_computed(false) { DBUG_ASSERT(!is_null()); } bool using_packed_sortkeys() const { return m_using_packed_sortkeys; } void set_using_packed_sortkeys(bool val) { m_using_packed_sortkeys= val; } void set_size_of_packable_fields(uint len) { size_of_packable_fields= len; } uint get_size_of_packable_fields() { return size_of_packable_fields; } void set_sort_length_with_original_values(uint len) { sort_length_with_original_values= len; } uint get_sort_length_with_original_values() { return sort_length_with_original_values; } void set_sort_length_with_memcmp_values(uint len) { sort_length_with_memcmp_values= len; } uint get_sort_length_with_memcmp_values() { return sort_length_with_memcmp_values; } static void store_sortkey_length(uchar *p, uint sz) { int4store(p, sz - size_of_length_field); } static uint read_sortkey_length(uchar *p) { return size_of_length_field + uint4korr(p); } void increment_size_of_packable_fields(uint len) { size_of_packable_fields+= len; } void increment_original_sort_length(uint len) { sort_length_with_original_values+= len; } bool is_parameters_computed() { return parameters_computed; } void set_parameters_computed(bool val) { parameters_computed= val; } static const uint size_of_length_field= 4; private: bool m_using_packed_sortkeys; // Are we packing sort keys uint size_of_packable_fields; // Total length bytes for packable columns /* The sort length for all the keyparts storing the original values */ uint sort_length_with_original_values; /* The sort length for all the keyparts storing the mem-comparable images */ uint sort_length_with_memcmp_values; /* TRUE parameters(like sort_length_* , size_of_packable_field) are computed FALSE otherwise. */ bool parameters_computed; }; /** PACKED SORT KEYS Description In this optimization where we would like the pack the values of the sort key inside the sort buffer for each record. Contents: 1. Background 1.1 Implementation details 2. Solution : Packed Sort Keys 2.1 Packed key format 2.2 Which format to use 3. Special cases 3.1 Handling very long strings 3.2 Handling for long binary strings 3.3 Handling very long strings with Packed sort keys 4. Sort key columns in addon_fields 1. Background Before this optimization of using packed sort keys, filesort() sorted the data using mem-comparable keys. That is, if we wanted to sort by ORDER BY col1, col2, ... colN then the filesort code would for each row generate one "Sort Key" and then sort the rows by their Sort Keys. The Sort Keys are mem-comparable (that is, are compared by memcmp()) and they are of FIXED SIZE. The sort key has the same length regardless of what value it represents. This causes INEFFICIENT MEMORY USAGE. 1.1 Implementation details make_sortkey() is the function that produces a sort key from a record. The function treats Field and Item objects differently. class Field has: a) void make_sort_key(uchar *buff, uint length); make_sort_key is a non-virtual function which handles encoding of SQL null values. b) virtual void sort_string(uchar *buff,uint length)=0; sort_string produces mem-comparable image of the field value for each datatype. For Items, Type_handler has a virtual function: virtual void make_sort_key(uchar *to, Item *item, const SORT_FIELD_ATTR *sort_field, Sort_param *param) const= 0; which various datatypes overload. 2. SOLUTION: PACKED SORT KEYS Note that one can have mem-comparable keys are that are not fixed-size. MyRocks uses such encoding for example. However for this optimization it was decided to store the original (non-mem-comparable) values instead and use a datatype-aware key comparison function. 2.1 Packed key format The keys are stored in a new variable-size data format called "packed". The format is as follows: ....... format for a n-part sort key is the length of the whole key. Each packed value is encoded as follows: // This is a an SQL NULL [] // this a non-NULL value null_byte is present if the field/item is NULLable. SQL NULL is encoded as just one NULL-indicator byte. The value itself is omitted. The format of the packed_value depends on the datatype. For "non-packable" datatypes it is just their mem-comparable form, as before. The "packable" datatypes are currently variable-length strings and the packed format for them is (for binary blobs, see a note below): 2.2 Which format to use The advantage of Packed Key Format is potential space savings for variable-length fields. The disadvantages are: a) It may actually take more space, because of sort_key_length and length fields. b) The comparison function is more expensive. Currently the logic is: use Packed Key Format if we would save 128 or more bytes when constructing a sort key from values that have empty string for each packable component. 3. SPECIAL CASES 3.1 HANDLING VERY LONG STRINGS the size of sort key part was limited by @@max_sort_length variable. It is defined as: The number of bytes to use when sorting data values. The server uses only the first max_sort_length bytes of each value and ignores the rest. 3.2 HANDLING VERY LONG BINARY STRINGS Long binary strings receive special treatment. A sort key for the long binary string is truncated at max_sort_length bytes like described above, but then a "suffix" is appended which contains the total length of the value before the truncation. 3.3 HANDLING VERY LONG STRINGS WITH PACKED SORT KEY Truncating multi-byte string at N bytes is not safe because one can cut in the middle of a character. One is tempted to solve this by discarding the partial character but that's also not a good idea as in some collations multiple characters may produce one weight (this is called "contraction"). This combination of circumstances: The string value is very long, so truncation is necessary The collation is "complex", so truncation is dangerous is deemed to be relatively rare so it was decided to just use the non-packed sort keys in this case. 4. SORT KEY COLUMNS IN ADDON FIELDS Currently, each sort key column is actually stored twice 1. as part of the sort key 2. in the addon_fields This made total sense when sort key stored the mem-comparable image (from which one cannot restore the original value in general case). But since we now store the original value, we could also remove it from the addon_fields and further save space. This is still a limitation and needs to be fixed later @see Sort_keys **/ /** The sort record format may use one of two formats for the non-sorted part of the record: 1. Use the rowid || | / / ref_length / 2. Use "addon fields" |||...| / / addon_length / The packed format for "addon fields" ||||...| / / addon_length / The key may use one of the two formats: A. fixed-size mem-comparable form. The record is always sort_length bytes long. B. "PackedKeyFormat" - the records are variable-size. Fields are fixed-size, specially encoded with Field::make_sort_key() so we can do byte-by-byte compare. Contains the *actual* packed length (after packing) of everything after the sort keys. The size of the length field is 2 bytes, which should cover most use cases: addon data <= 65535 bytes. This is the same as max record size in MySQL. One bit for each nullable field, indicating whether the field is null or not. May have size zero if no fields are nullable. Are stored with field->pack(), and retrieved with field->unpack(). Addon fields within a record are stored consecutively, with no "holes" or padding. They will have zero size for NULL values. */ class Sort_param { public: uint rec_length; // Length of sorted records. uint sort_length; // Length of sorted columns. uint ref_length; // Length of record ref. uint addon_length; // Length of addon_fields uint res_length; // Length of records in final sorted file/buffer. uint max_keys_per_buffer; // Max keys / buffer. uint min_dupl_count; ha_rows max_rows; // Select limit, or HA_POS_ERROR if unlimited. ha_rows examined_rows; // Number of examined rows. TABLE *sort_form; // For quicker make_sortkey. /** ORDER BY list with some precalculated info for filesort. Array is created and owned by a Filesort instance. */ Bounds_checked_array local_sortorder; Addon_fields *addon_fields; // Descriptors for companion fields. Sort_keys *sort_keys; ha_rows *accepted_rows; /* For ROWNUM */ bool using_pq; bool set_all_read_bits; uchar *unique_buff; bool not_killable; String tmp_buffer; // The fields below are used only by Unique class. qsort_cmp2 compare; BUFFPEK_COMPARE_CONTEXT cmp_context; Sort_param() { memset(reinterpret_cast(this), 0, sizeof(*this)); tmp_buffer.set_thread_specific(); /* Fix memset() clearing the charset. TODO: The constructor should be eventually rewritten not to use memset(). */ tmp_buffer.set_charset(&my_charset_bin); } void init_for_filesort(uint sortlen, TABLE *table, ha_rows maxrows, Filesort *filesort); void (*unpack)(TABLE *); /// Enables the packing of addons if possible. void try_to_pack_addons(ulong max_length_for_sort_data); /// Are we packing the "addon fields"? bool using_packed_addons() const { DBUG_ASSERT(m_using_packed_addons == (addon_fields != NULL && addon_fields->using_packed_addons())); return m_using_packed_addons; } bool using_packed_sortkeys() const { DBUG_ASSERT(m_using_packed_sortkeys == (sort_keys != NULL && sort_keys->using_packed_sortkeys())); return m_using_packed_sortkeys; } /// Are we using "addon fields"? bool using_addon_fields() const { return addon_fields != NULL; } uint32 get_result_length(uchar *plen) { if (!m_using_packed_addons) return res_length; return Addon_fields::read_addon_length(plen); } uint32 get_addon_length(uchar *plen) { if (using_packed_addons()) return Addon_fields::read_addon_length(plen); else return addon_length; } uint32 get_sort_length(uchar *plen) { if (using_packed_sortkeys()) return Sort_keys::read_sortkey_length(plen) + /* when addon fields are not present, then the sort_length also includes the res_length. For packed keys here we add the res_length */ (using_addon_fields() ? 0: res_length); else return sort_length; } uint get_record_length(uchar *plen) { if (m_packed_format) { uint sort_len= get_sort_length(plen); return sort_len + get_addon_length(plen + sort_len); } else return rec_length; } /** Getter for record length and result length. @param record_start Pointer to record. @param [out] recl Store record length here. @param [out] resl Store result length here. */ void get_rec_and_res_len(uchar *record_start, uint *recl, uint *resl) { if (m_packed_format) { uint sort_len= get_sort_length(record_start); uint addon_len= get_addon_length(record_start + sort_len); *recl= sort_len + addon_len; *resl= using_addon_fields() ? addon_len : res_length; } else { *recl= rec_length; *resl= res_length; } } void try_to_pack_sortkeys(); qsort_cmp2 get_compare_function() const { return using_packed_sortkeys() ? get_packed_keys_compare_ptr() : get_ptr_compare(sort_length); } void* get_compare_argument(size_t *sort_len) const { return using_packed_sortkeys() ? (void*) this : (void*) sort_len; } bool is_packed_format() const { return m_packed_format; } private: uint m_packable_length; bool m_using_packed_addons; ///< caches the value of using_packed_addons() /* caches the value of using_packed_sortkeys() */ bool m_using_packed_sortkeys; bool m_packed_format; }; typedef Bounds_checked_array Sort_buffer; int merge_many_buff(Sort_param *param, Sort_buffer sort_buffer, Merge_chunk *buffpek, uint *maxbuffer, IO_CACHE *t_file); ulong read_to_buffer(IO_CACHE *fromfile, Merge_chunk *buffpek, Sort_param *param, bool packing_format); bool merge_buffers(Sort_param *param,IO_CACHE *from_file, IO_CACHE *to_file, Sort_buffer sort_buffer, Merge_chunk *lastbuff, Merge_chunk *Fb, Merge_chunk *Tb, int flag); int merge_index(Sort_param *param, Sort_buffer sort_buffer, Merge_chunk *buffpek, uint maxbuffer, IO_CACHE *tempfile, IO_CACHE *outfile); void reuse_freed_buff(QUEUE *queue, Merge_chunk *reuse, uint key_length); #endif /* SQL_SORT_INCLUDED */ mysql/server/private/datadict.h000064400000003244151027430560012625 0ustar00#ifndef DATADICT_INCLUDED #define DATADICT_INCLUDED /* Copyright (c) 2010, Oracle and/or its affiliates. Copyright (c) 2017 MariaDB corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "handler.h" /* Data dictionary API. */ enum Table_type { TABLE_TYPE_UNKNOWN, TABLE_TYPE_NORMAL, /* Normal table */ TABLE_TYPE_SEQUENCE, TABLE_TYPE_VIEW }; /* Take extra care when using dd_frm_type() - it only checks the .frm file, and it won't work for any engine that supports discovery. Prefer to use ha_table_exists() instead. To check whether it's an frm of a view, use dd_frm_is_view(). */ enum Table_type dd_frm_type(THD *thd, char *path, LEX_CSTRING *engine_name, LEX_CSTRING *partition_engine_name, LEX_CUSTRING *table_version); static inline bool dd_frm_is_view(THD *thd, char *path) { return dd_frm_type(thd, path, NULL, NULL, NULL) == TABLE_TYPE_VIEW; } bool dd_recreate_table(THD *thd, const char *db, const char *table_name); #endif // DATADICT_INCLUDED mysql/server/private/vers_string.h000064400000004746151027430560013425 0ustar00/* Copyright (c) 2018, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef VERS_STRING_INCLUDED #define VERS_STRING_INCLUDED #include "lex_string.h" /* LEX_CSTRING with comparison semantics. */ // db and table names: case sensitive (or insensitive) in table_alias_charset struct Compare_table_names { int operator()(const LEX_CSTRING& a, const LEX_CSTRING& b) const { DBUG_ASSERT(a.str[a.length] == 0); DBUG_ASSERT(b.str[b.length] == 0); return table_alias_charset->strnncoll(a.str, a.length, b.str, b.length); } }; // column names and other identifiers: case insensitive in system_charset_info struct Compare_identifiers { int operator()(const LEX_CSTRING& a, const LEX_CSTRING& b) const { DBUG_ASSERT(a.str != NULL); DBUG_ASSERT(b.str != NULL); DBUG_ASSERT(a.str[a.length] == 0); DBUG_ASSERT(b.str[b.length] == 0); return my_strcasecmp(system_charset_info, a.str, b.str); } }; template struct Lex_cstring_with_compare : public Lex_cstring { public: Lex_cstring_with_compare() = default; Lex_cstring_with_compare(const char *_str, size_t _len) : Lex_cstring(_str, _len) { } Lex_cstring_with_compare(const LEX_STRING src) : Lex_cstring(src.str, src.length) { } Lex_cstring_with_compare(const LEX_CSTRING src) : Lex_cstring(src.str, src.length) { } Lex_cstring_with_compare(const char *_str) : Lex_cstring(_str, strlen(_str)) { } bool streq(const Lex_cstring_with_compare& b) const { return Lex_cstring::length == b.length && 0 == Compare()(*this, b); } operator const char* () const { return str; } operator bool () const { return str != NULL; } }; typedef Lex_cstring_with_compare Lex_ident; typedef Lex_cstring_with_compare Lex_table_name; #endif // VERS_STRING_INCLUDED mysql/server/private/wsrep_thd.h000064400000025630151027430560013052 0ustar00/* Copyright (C) 2013-2023 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #ifndef WSREP_THD_H #define WSREP_THD_H #include #include "mysql/service_wsrep.h" #include "wsrep/client_state.hpp" #include "sql_class.h" #include "wsrep_utils.h" #include class Wsrep_thd_queue { public: Wsrep_thd_queue(THD* t) : thd(t) { mysql_mutex_init(key_LOCK_wsrep_thd_queue, &LOCK_wsrep_thd_queue, MY_MUTEX_INIT_FAST); mysql_cond_init(key_COND_wsrep_thd_queue, &COND_wsrep_thd_queue, NULL); } ~Wsrep_thd_queue() { mysql_mutex_destroy(&LOCK_wsrep_thd_queue); mysql_cond_destroy(&COND_wsrep_thd_queue); } bool push_back(THD* thd) { DBUG_ASSERT(thd); wsp::auto_lock lock(&LOCK_wsrep_thd_queue); std::deque::iterator it = queue.begin(); while (it != queue.end()) { if (*it == thd) { return true; } it++; } queue.push_back(thd); mysql_cond_signal(&COND_wsrep_thd_queue); return false; } THD* pop_front() { wsp::auto_lock lock(&LOCK_wsrep_thd_queue); while (queue.empty()) { if (thd->killed != NOT_KILLED) return NULL; thd->mysys_var->current_mutex= &LOCK_wsrep_thd_queue; thd->mysys_var->current_cond= &COND_wsrep_thd_queue; mysql_cond_wait(&COND_wsrep_thd_queue, &LOCK_wsrep_thd_queue); thd->mysys_var->current_mutex= 0; thd->mysys_var->current_cond= 0; } THD* ret= queue.front(); queue.pop_front(); return ret; } private: THD* thd; std::deque queue; mysql_mutex_t LOCK_wsrep_thd_queue; mysql_cond_t COND_wsrep_thd_queue; }; int wsrep_show_bf_aborts (THD *thd, SHOW_VAR *var, void *, system_status_var *, enum enum_var_type scope); bool wsrep_create_appliers(long threads, bool mutex_protected=false); void wsrep_create_rollbacker(); bool wsrep_bf_abort(THD* bf_thd, THD* victim_thd); /* Abort transaction for victim_thd. This function is called from MDL BF abort codepath. */ void wsrep_abort_thd(THD *bf_thd, THD *victim_thd, my_bool signal) __attribute__((nonnull(1,2))); /** Kill wsrep connection with kill_signal. Object thd is not guaranteed to exist anymore when this function returns. Asserts that the caller holds victim_thd->LOCK_thd_kill, victim_thd->LOCK_thd_data. @param thd THD object for connection that executes the KILL. @param victim_thd THD object for connection to be killed. @param kill_signal Kill signal. @return Zero if the kill was successful, otherwise non-zero error code. */ uint wsrep_kill_thd(THD *thd, THD *victim_thd, killed_state kill_signal); /* Backup kill status for commit. */ void wsrep_backup_kill_for_commit(THD *); /* Restore KILL status after commit. */ void wsrep_restore_kill_after_commit(THD *); /* Helper methods to deal with thread local storage. The purpose of these methods is to hide the details of thread local storage handling when operating with wsrep storage access and streaming applier THDs With one-thread-per-connection thread handling thread specific variables are allocated when the thread is started and deallocated before thread exits (my_thread_init(), my_thread_end()). However, with pool-of-threads thread handling new thread specific variables are allocated for each THD separately (see threadpool_add_connection()), and the variables in thread local storage are assigned from currently active thread (see thread_attach()). This must be taken into account when storing/resetting thread local storage and when creating streaming applier THDs. */ /** Create new variables for thread local storage. With one-thread-per-connection thread handling this is a no op, with pool-of-threads new variables are created via my_thread_init(). It is assumed that the caller has called wsrep_reset_threadvars() to clear the thread local storage before this call. @return Zero in case of success, non-zero otherwise. */ int wsrep_create_threadvars(); /** Delete variables which were created by wsrep_create_threadvars(). The caller must store variables into thread local storage before this call via wsrep_store_threadvars(). */ void wsrep_delete_threadvars(); /** Assign variables from current thread local storage into THD. This should be called for THDs whose lifetime is limited to single thread execution or which may share the operation context with some parent THD (e.g. storage access) and thus don't require separately allocated globals. With one-thread-per-connection thread handling this is a no-op, with pool-of-threads the variables which are currently stored into thread local storage are assigned to THD. */ void wsrep_assign_from_threadvars(THD *); /** Helper struct to save variables from thread local storage. */ struct Wsrep_threadvars { THD* cur_thd; st_my_thread_var* mysys_var; }; /** Save variables from thread local storage into Wsrep_threadvars struct. */ Wsrep_threadvars wsrep_save_threadvars(); /** Restore variables into thread local storage from Wsrep_threadvars struct. */ void wsrep_restore_threadvars(const Wsrep_threadvars&); /** Store variables into thread local storage. */ void wsrep_store_threadvars(THD *); /** Reset thread local storage. */ void wsrep_reset_threadvars(THD *); /** Helper functions to override error status In many contexts it is desirable to mask the original error status set for THD or it is necessary to change OK status to error. This function implements the common logic for the most of the cases. Rules: * If the diagnostics are has OK or EOF status, override it unconditionally * If the error is either ER_ERROR_DURING_COMMIT or ER_LOCK_DEADLOCK it is usually the correct error status to be returned to client, so don't override those by default */ static inline void wsrep_override_error(THD *thd, uint error, const char *format= 0, ...) { Diagnostics_area *da= thd->get_stmt_da(); if (da->is_ok() || da->is_eof() || !da->is_set() || (da->is_error() && da->sql_errno() != error && da->sql_errno() != ER_ERROR_DURING_COMMIT && da->sql_errno() != ER_LOCK_DEADLOCK)) { da->reset_diagnostics_area(); va_list args; va_start(args, format); if (!format) format= ER_THD(thd, error); my_printv_error(error, format, MYF(0), args); va_end(args); } } static inline void wsrep_override_error(THD* thd, wsrep::client_error ce, enum wsrep::provider::status status) { DBUG_ASSERT(ce != wsrep::e_success); switch (ce) { case wsrep::e_error_during_commit: if (status == wsrep::provider::error_size_exceeded) wsrep_override_error(thd, ER_UNKNOWN_ERROR, "Maximum writeset size exceeded"); else /* TODO: Figure out better error number */ if (status) wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, "Error while appending streaming replication fragment" "(provider status: %s)", wsrep::provider::to_string(status).c_str()); else wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, "Error while appending streaming replication fragment"); break; case wsrep::e_deadlock_error: switch (thd->lex->sql_command) { case SQLCOM_XA_END: case SQLCOM_XA_PREPARE: wsrep_override_error(thd, ER_XA_RBDEADLOCK); break; default: wsrep_override_error(thd, ER_LOCK_DEADLOCK); break; } break; case wsrep::e_interrupted_error: wsrep_override_error(thd, ER_QUERY_INTERRUPTED); break; case wsrep::e_size_exceeded_error: wsrep_override_error(thd, ER_UNKNOWN_ERROR, "Maximum writeset size exceeded"); break; case wsrep::e_append_fragment_error: /* TODO: Figure out better error number */ if (status) wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, "Error while appending streaming replication fragment" "(provider status: %s)", wsrep::provider::to_string(status).c_str()); else wsrep_override_error(thd, ER_ERROR_DURING_COMMIT, "Error while appending streaming replication fragment"); break; case wsrep::e_not_supported_error: wsrep_override_error(thd, ER_NOT_SUPPORTED_YET); break; case wsrep::e_timeout_error: wsrep_override_error(thd, ER_LOCK_WAIT_TIMEOUT); break; default: wsrep_override_error(thd, ER_UNKNOWN_ERROR); } } /** Helper function to log THD wsrep context. @param thd Pointer to THD @param message Optional message @param function Function where the call was made from */ static inline void wsrep_log_thd(const THD *thd, const char *message, const char *function) { WSREP_DEBUG("%s %s\n" " thd: %llu thd_ptr: %p client_mode: %s client_state: %s trx_state: %s\n" " next_trx_id: %lld trx_id: %lld seqno: %lld\n" " is_streaming: %d fragments: %zu\n" " sql_errno: %u message: %s\n" #define WSREP_THD_LOG_QUERIES #ifdef WSREP_THD_LOG_QUERIES " command: %d query: %.72s" #endif /* WSREP_OBSERVER_LOG_QUERIES */ , function, message ? message : "", thd->thread_id, thd, wsrep_thd_client_mode_str(thd), wsrep_thd_client_state_str(thd), wsrep_thd_transaction_state_str(thd), (long long)thd->wsrep_next_trx_id(), (long long)thd->wsrep_trx_id(), (long long)wsrep_thd_trx_seqno(thd), thd->wsrep_trx().is_streaming(), thd->wsrep_sr().fragments().size(), (thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0), (thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->message() : "") #ifdef WSREP_THD_LOG_QUERIES , thd->lex->sql_command, wsrep_thd_query(thd) #endif /* WSREP_OBSERVER_LOG_QUERIES */ ); } #define WSREP_LOG_THD(thd_, message_) wsrep_log_thd(thd_, message_, __FUNCTION__) #endif /* WSREP_THD_H */ mysql/server/private/maria.h000064400000013360151027430560012141 0ustar00/* Copyright (C) 2006-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. Copyright (c) 2009, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file should be included when using maria functions */ #ifndef _maria_h #define _maria_h #include #include #include "my_compare.h" #include "ft_global.h" #include #ifdef __cplusplus extern "C" { #endif #define MARIA_UNIQUE_HASH_LENGTH 4 extern my_bool maria_delay_key_write; uint maria_max_key_length(void); #define maria_max_key_segments() HA_MAX_KEY_SEG struct st_maria_bit_buff; struct st_maria_page; struct st_maria_s_param; struct st_maria_share; typedef struct st_maria_decode_tree MARIA_DECODE_TREE; typedef struct st_maria_handler MARIA_HA; typedef struct st_maria_key MARIA_KEY; typedef ulonglong MARIA_RECORD_POS; typedef struct st_maria_keydef /* Key definition with open & info */ { struct st_maria_share *share; /* Pointer to base (set in open) */ mysql_rwlock_t root_lock; /* locking of tree */ uint16 keysegs; /* Number of key-segment */ uint16 flag; /* NOSAME, PACK_USED */ uint8 key_alg; /* BTREE, RTREE */ uint8 key_nr; /* key number (auto) */ uint16 block_length; /* Length of keyblock (auto) */ uint16 underflow_block_length; /* When to execute underflow */ uint16 keylength; /* Tot length of keyparts (auto) */ uint16 minlength; /* min length of (packed) key (auto) */ uint16 maxlength; /* max length of (packed) key (auto) */ uint16 max_store_length; /* Size to store key + overhead */ uint32 write_comp_flag; /* compare flag for write key (auto) */ uint32 version; /* For concurrent read/write */ uint32 ftkey_nr; /* full-text index number */ HA_KEYSEG *seg, *end; struct st_mysql_ftparser *parser; /* Fulltext [pre]parser */ int (*bin_search)(const MARIA_KEY *key, const struct st_maria_page *page, uint32 comp_flag, uchar **ret_pos, uchar *buff, my_bool *was_last_key); uint (*get_key)(MARIA_KEY *key, uint page_flag, uint nod_flag, uchar **page); uchar *(*skip_key)(MARIA_KEY *key, uint page_flag, uint nod_flag, uchar *page); int (*pack_key)(const MARIA_KEY *key, uint nod_flag, uchar *next_key, uchar *org_key, uchar *prev_key, struct st_maria_s_param *s_temp); void (*store_key)(struct st_maria_keydef *keyinfo, uchar *key_pos, struct st_maria_s_param *s_temp); my_bool (*ck_insert)(MARIA_HA *inf, MARIA_KEY *key); my_bool (*ck_delete)(MARIA_HA *inf, MARIA_KEY *klen); MARIA_KEY *(*make_key)(MARIA_HA *info, MARIA_KEY *int_key, uint keynr, uchar *key, const uchar *record, MARIA_RECORD_POS filepos, ulonglong trid); } MARIA_KEYDEF; typedef struct st_maria_unique_def /* Segment definition of unique */ { uint16 keysegs; /* Number of key-segment */ uint8 key; /* Mapped to which key */ uint8 null_are_equal; HA_KEYSEG *seg, *end; } MARIA_UNIQUEDEF; /* Note that null markers should always be first in a row ! When creating a column, one should only specify: type, length, null_bit and null_pos */ typedef struct st_maria_columndef /* column information */ { enum en_fieldtype type; uint32 offset; /* Offset to position in row */ uint16 length; /* length of field */ uint16 column_nr; /* Intern variable (size of total storage area for the row) */ uint16 fill_length; uint16 null_pos; /* Position for null marker */ uint16 empty_pos; /* Position for empty marker */ uint8 null_bit; /* If column may be NULL */ /* Intern. Set if column should be zero packed (part of empty_bits) */ uint8 empty_bit; #ifndef NOT_PACKED_DATABASES void(*unpack)(struct st_maria_columndef *rec, struct st_maria_bit_buff *buff, uchar *start, uchar *end); enum en_fieldtype base_type; uint space_length_bits, pack_type; MARIA_DECODE_TREE *huff_tree; #endif } MARIA_COLUMNDEF; typedef struct st_maria_create_info { const char *index_file_name, *data_file_name; /* If using symlinks */ ha_rows max_rows; ha_rows reloc_rows; ulonglong auto_increment; ulonglong data_file_length; ulonglong key_file_length; ulong s3_block_size; /* Size of null bitmap at start of row */ uint null_bytes; uint old_options; uint compression_algorithm; enum data_file_type org_data_file_type; uint16 language; my_bool with_auto_increment, transactional, encrypted; } MARIA_CREATE_INFO; extern int maria_create(const char *name, enum data_file_type record_type, uint keys, MARIA_KEYDEF *keydef, uint columns, MARIA_COLUMNDEF *columndef, uint uniques, MARIA_UNIQUEDEF *uniquedef, MARIA_CREATE_INFO *create_info, uint flags); #ifdef __cplusplus } #endif #endif mysql/server/private/item_sum.h000064400000215137151027430560012700 0ustar00#ifndef ITEM_SUM_INCLUDED #define ITEM_SUM_INCLUDED /* Copyright (c) 2000, 2013 Oracle and/or its affiliates. Copyright (c) 2008, 2023, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* classes for sum functions */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include #include "sql_udf.h" /* udf_handler */ class Item_sum; class Aggregator_distinct; class Aggregator_simple; /** The abstract base class for the Aggregator_* classes. It implements the data collection functions (setup/add/clear) as either pass-through to the real functionality or as collectors into an Unique (for distinct) structure. Note that update_field/reset_field are not in that class, because they're simply not called when GROUP BY/DISTINCT can be handled with help of index on grouped fields (quick_group = 0); */ class Aggregator : public Sql_alloc { friend class Item_sum; friend class Item_sum_sum; friend class Item_sum_count; friend class Item_sum_avg; /* All members are protected as this class is not usable outside of an Item_sum descendant. */ protected: /* the aggregate function class to act on */ Item_sum *item_sum; public: Aggregator (Item_sum *arg): item_sum(arg) {} virtual ~Aggregator () = default; /* Keep gcc happy */ enum Aggregator_type { SIMPLE_AGGREGATOR, DISTINCT_AGGREGATOR }; virtual Aggregator_type Aggrtype() = 0; /** Called before adding the first row. Allocates and sets up the internal aggregation structures used, e.g. the Unique instance used to calculate distinct. */ virtual bool setup(THD *) = 0; /** Called when we need to wipe out all the data from the aggregator : all the values acumulated and all the state. Cleans up the internal structures and resets them to their initial state. */ virtual void clear() = 0; /** Called when there's a new value to be aggregated. Updates the internal state of the aggregator to reflect the new value. */ virtual bool add() = 0; /** Called when there are no more data and the final value is to be retrieved. Finalises the state of the aggregator, so the final result can be retrieved. */ virtual void endup() = 0; /** Decimal value of being-aggregated argument */ virtual my_decimal *arg_val_decimal(my_decimal * value) = 0; /** Floating point value of being-aggregated argument */ virtual double arg_val_real() = 0; /** NULLness of being-aggregated argument. @param use_null_value Optimization: to determine if the argument is NULL we must, in the general case, call is_null() on it, which itself might call val_*() on it, which might be costly. If you just have called arg_val*(), you can pass use_null_value=true; this way, arg_is_null() might avoid is_null() and instead do a cheap read of the Item's null_value (updated by arg_val*()). */ virtual bool arg_is_null(bool use_null_value) = 0; }; class st_select_lex; class Window_spec; /** Class Item_sum is the base class used for special expressions that SQL calls 'set functions'. These expressions are formed with the help of aggregate functions such as SUM, MAX, GROUP_CONCAT etc. GENERAL NOTES A set function cannot be used in certain positions where expressions are accepted. There are some quite explicable restrictions for the usage of set functions. In the query: SELECT AVG(b) FROM t1 WHERE SUM(b) > 20 GROUP by a the usage of the set function AVG(b) is legal, while the usage of SUM(b) is illegal. A WHERE condition must contain expressions that can be evaluated for each row of the table. Yet the expression SUM(b) can be evaluated only for each group of rows with the same value of column a. In the query: SELECT AVG(b) FROM t1 WHERE c > 30 GROUP BY a HAVING SUM(b) > 20 both set function expressions AVG(b) and SUM(b) are legal. We can say that in a query without nested selects an occurrence of a set function in an expression of the SELECT list or/and in the HAVING clause is legal, while in the WHERE clause it's illegal. The general rule to detect whether a set function is legal in a query with nested subqueries is much more complicated. Consider the the following query: SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a > ALL (SELECT t2.c FROM t2 WHERE SUM(t1.b) < t2.c). The set function SUM(b) is used here in the WHERE clause of the subquery. Nevertheless it is legal since it is under the HAVING clause of the query to which this function relates. The expression SUM(t1.b) is evaluated for each group defined in the main query, not for groups of the subquery. The problem of finding the query where to aggregate a particular set function is not so simple as it seems to be. In the query: SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a > ALL(SELECT t2.c FROM t2 GROUP BY t2.c HAVING SUM(t1.a) < t2.c) the set function can be evaluated for both outer and inner selects. If we evaluate SUM(t1.a) for the outer query then we get the value of t1.a multiplied by the cardinality of a group in table t1. In this case in each correlated subquery SUM(t1.a) is used as a constant. But we also can evaluate SUM(t1.a) for the inner query. In this case t1.a will be a constant for each correlated subquery and summation is performed for each group of table t2. (Here it makes sense to remind that the query SELECT c FROM t GROUP BY a HAVING SUM(1) < a is quite legal in our SQL). So depending on what query we assign the set function to we can get different result sets. The general rule to detect the query where a set function is to be evaluated can be formulated as follows. Consider a set function S(E) where E is an expression with occurrences of column references C1, ..., CN. Resolve these column references against subqueries that contain the set function S(E). Let Q be the innermost subquery of those subqueries. (It should be noted here that S(E) in no way can be evaluated in the subquery embedding the subquery Q, otherwise S(E) would refer to at least one unbound column reference) If S(E) is used in a construct of Q where set functions are allowed then we evaluate S(E) in Q. Otherwise we look for a innermost subquery containing S(E) of those where usage of S(E) is allowed. Let's demonstrate how this rule is applied to the following queries. 1. SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c HAVING SUM(t1.a+t2.b) < t3.c)) For this query the set function SUM(t1.a+t2.b) depends on t1.a and t2.b with t1.a defined in the outermost query, and t2.b defined for its subquery. The set function is in the HAVING clause of the subquery and can be evaluated in this subquery. 2. SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a > ALL(SELECT t2.b FROM t2 WHERE t2.b > ALL (SELECT t3.c FROM t3 GROUP BY t3.c HAVING SUM(t1.a+t2.b) < t3.c)) Here the set function SUM(t1.a+t2.b)is in the WHERE clause of the second subquery - the most upper subquery where t1.a and t2.b are defined. If we evaluate the function in this subquery we violate the context rules. So we evaluate the function in the third subquery (over table t3) where it is used under the HAVING clause. 3. SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a > ALL(SELECT t2.b FROM t2 WHERE t2.b > ALL (SELECT t3.c FROM t3 WHERE SUM(t1.a+t2.b) < t3.c)) In this query evaluation of SUM(t1.a+t2.b) is not legal neither in the second nor in the third subqueries. So this query is invalid. Mostly set functions cannot be nested. In the query SELECT t1.a from t1 GROUP BY t1.a HAVING AVG(SUM(t1.b)) > 20 the expression SUM(b) is not acceptable, though it is under a HAVING clause. Yet it is acceptable in the query: SELECT t.1 FROM t1 GROUP BY t1.a HAVING SUM(t1.b) > 20. An argument of a set function does not have to be a reference to a table column as we saw it in examples above. This can be a more complex expression SELECT t1.a FROM t1 GROUP BY t1.a HAVING SUM(t1.b+1) > 20. The expression SUM(t1.b+1) has a very clear semantics in this context: we sum up the values of t1.b+1 where t1.b varies for all values within a group of rows that contain the same t1.a value. A set function for an outer query yields a constant within a subquery. So the semantics of the query SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c HAVING AVG(t2.c+SUM(t1.b)) > 20) is still clear. For a group of the rows with the same t1.a values we calculate the value of SUM(t1.b). This value 's' is substituted in the the subquery: SELECT t2.c FROM t2 GROUP BY t2.c HAVING AVG(t2.c+s) than returns some result set. By the same reason the following query with a subquery SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a IN (SELECT t2.c FROM t2 GROUP BY t2.c HAVING AVG(SUM(t1.b)) > 20) is also acceptable. IMPLEMENTATION NOTES Three methods were added to the class to check the constraints specified in the previous section. These methods utilize several new members. The field 'nest_level' contains the number of the level for the subquery containing the set function. The main SELECT is of level 0, its subqueries are of levels 1, the subqueries of the latter are of level 2 and so on. The field 'aggr_level' is to contain the nest level of the subquery where the set function is aggregated. The field 'max_arg_level' is for the maximum of the nest levels of the unbound column references occurred in the set function. A column reference is unbound within a set function if it is not bound by any subquery used as a subexpression in this function. A column reference is bound by a subquery if it is a reference to the column by which the aggregation of some set function that is used in the subquery is calculated. For the set function used in the query SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a > ALL(SELECT t2.b FROM t2 GROUP BY t2.b HAVING t2.b > ALL(SELECT t3.c FROM t3 GROUP BY t3.c HAVING SUM(t1.a+t2.b) < t3.c)) the value of max_arg_level is equal to 1 since t1.a is bound in the main query, and t2.b is bound by the first subquery whose nest level is 1. Obviously a set function cannot be aggregated in the subquery whose nest level is less than max_arg_level. (Yet it can be aggregated in the subqueries whose nest level is greater than max_arg_level.) In the query SELECT t.a FROM t1 HAVING AVG(t1.a+(SELECT MIN(t2.c) FROM t2)) the value of the max_arg_level for the AVG set function is 0 since the reference t2.c is bound in the subquery. The field 'max_sum_func_level' is to contain the maximum of the nest levels of the set functions that are used as subexpressions of the arguments of the given set function, but not aggregated in any subquery within this set function. A nested set function s1 can be used within set function s0 only if s1.max_sum_func_level < s0.max_sum_func_level. Set function s1 is considered as nested for set function s0 if s1 is not calculated in any subquery within s0. A set function that is used as a subexpression in an argument of another set function refers to the latter via the field 'in_sum_func'. The condition imposed on the usage of set functions are checked when we traverse query subexpressions with the help of the recursive method fix_fields. When we apply this method to an object of the class Item_sum, first, on the descent, we call the method init_sum_func_check that initialize members used at checking. Then, on the ascent, we call the method check_sum_func that validates the set function usage and reports an error if it is illegal. The method register_sum_func serves to link the items for the set functions that are aggregated in the embedding (sub)queries. Circular chains of such functions are attached to the corresponding st_select_lex structures through the field inner_sum_func_list. Exploiting the fact that the members mentioned above are used in one recursive function we could have allocated them on the thread stack. Yet we don't do it now. We assume that the nesting level of subquries does not exceed 127. TODO: to catch queries where the limit is exceeded to make the code clean here. @note The implementation takes into account the used strategy: - Items resolved at optimization phase return 0 from Item_sum::used_tables(). - Items that depend on the number of join output records, but not columns of any particular table (like COUNT(*)), returm 0 from Item_sum::used_tables(), but still return false from Item_sum::const_item(). */ class Item_sum :public Item_func_or_sum { friend class Aggregator_distinct; friend class Aggregator_simple; protected: /** Aggregator class instance. Not set initially. Allocated only after it is determined if the incoming data are already distinct. */ Aggregator *aggr; private: /** Used in making ROLLUP. Set for the ROLLUP copies of the original Item_sum and passed to create_tmp_field() to cause it to work over the temp table buffer that is referenced by Item_result_field::result_field. */ bool force_copy_fields; /** Indicates how the aggregate function was specified by the parser : 1 if it was written as AGGREGATE(DISTINCT), 0 if it was AGGREGATE() */ bool with_distinct; /* TRUE if this is aggregate function of a window function */ bool window_func_sum_expr_flag; public: bool has_force_copy_fields() const { return force_copy_fields; } bool has_with_distinct() const { return with_distinct; } enum Sumfunctype { COUNT_FUNC, COUNT_DISTINCT_FUNC, SUM_FUNC, SUM_DISTINCT_FUNC, AVG_FUNC, AVG_DISTINCT_FUNC, MIN_FUNC, MAX_FUNC, STD_FUNC, VARIANCE_FUNC, SUM_BIT_FUNC, UDF_SUM_FUNC, GROUP_CONCAT_FUNC, ROW_NUMBER_FUNC, RANK_FUNC, DENSE_RANK_FUNC, PERCENT_RANK_FUNC, CUME_DIST_FUNC, NTILE_FUNC, FIRST_VALUE_FUNC, LAST_VALUE_FUNC, NTH_VALUE_FUNC, LEAD_FUNC, LAG_FUNC, PERCENTILE_CONT_FUNC, PERCENTILE_DISC_FUNC, SP_AGGREGATE_FUNC, JSON_ARRAYAGG_FUNC, JSON_OBJECTAGG_FUNC }; Item **ref_by; /* pointer to a ref to the object used to register it */ Item_sum *next; /* next in the circular chain of registered objects */ Item_sum *in_sum_func; /* embedding set function if any */ st_select_lex * aggr_sel; /* select where the function is aggregated */ int8 nest_level; /* number of the nesting level of the set function */ int8 aggr_level; /* nesting level of the aggregating subquery */ int8 max_arg_level; /* max level of unbound column references */ int8 max_sum_func_level;/* max level of aggregation for embedded functions */ /* true (the default value) means this aggregate function can be computed with TemporaryTableWithPartialSums algorithm (see end_update()). false means this aggregate function needs OrderedGroupBy algorithm (see end_write_group()). */ bool quick_group; /* This list is used by the check for mixing non aggregated fields and sum functions in the ONLY_FULL_GROUP_BY_MODE. We save all outer fields directly or indirectly used under this function it as it's unclear at the moment of fixing outer field whether it's aggregated or not. */ List outer_fields; protected: /* Copy of the arguments list to hold the original set of arguments. Used in EXPLAIN EXTENDED instead of the current argument list because the current argument list can be altered by usage of temporary tables. */ Item **orig_args, *tmp_orig_args[2]; static size_t ram_limitation(THD *thd); public: // Methods used by ColumnStore Item **get_orig_args() const { return orig_args; } public: void mark_as_sum_func(); Item_sum(THD *thd): Item_func_or_sum(thd), quick_group(1) { mark_as_sum_func(); init_aggregator(); } Item_sum(THD *thd, Item *a): Item_func_or_sum(thd, a), quick_group(1), orig_args(tmp_orig_args) { mark_as_sum_func(); init_aggregator(); } Item_sum(THD *thd, Item *a, Item *b): Item_func_or_sum(thd, a, b), quick_group(1), orig_args(tmp_orig_args) { mark_as_sum_func(); init_aggregator(); } Item_sum(THD *thd, List &list); //Copy constructor, need to perform subselects with temporary tables Item_sum(THD *thd, Item_sum *item); enum Type type() const override { return SUM_FUNC_ITEM; } virtual enum Sumfunctype sum_func () const=0; bool is_aggr_sum_func() { switch (sum_func()) { case COUNT_FUNC: case COUNT_DISTINCT_FUNC: case SUM_FUNC: case SUM_DISTINCT_FUNC: case AVG_FUNC: case AVG_DISTINCT_FUNC: case MIN_FUNC: case MAX_FUNC: case STD_FUNC: case VARIANCE_FUNC: case SUM_BIT_FUNC: case UDF_SUM_FUNC: case GROUP_CONCAT_FUNC: case JSON_ARRAYAGG_FUNC: return true; default: return false; } } /** Resets the aggregate value to its default and aggregates the current value of its attribute(s). */ inline bool reset_and_add() { aggregator_clear(); return aggregator_add(); }; /* Called when new group is started and results are being saved in a temporary table. Similarly to reset_and_add() it resets the value to its default and aggregates the value of its attribute(s), but must also store it in result_field. This set of methods (result_item(), reset_field, update_field()) of Item_sum is used only if quick_group is not null. Otherwise copy_or_same() is used to obtain a copy of this item. */ virtual void reset_field()=0; /* Called for each new value in the group, when temporary table is in use. Similar to add(), but uses temporary table field to obtain current value, Updated value is then saved in the field. */ virtual void update_field()=0; bool fix_length_and_dec() override { set_maybe_null(); null_value=1; return FALSE; } virtual Item *result_item(THD *thd, Field *field); void update_used_tables() override; COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override { /* Item_sum (and derivants) of the original WHERE/HAVING clauses should already be replaced to Item_aggregate_ref by the time when build_equal_items() is called. See Item::split_sum_func2(). */ DBUG_ASSERT(0); return Item::build_equal_items(thd, inherited, link_item_fields, cond_equal_ref); } bool is_null() override { return null_value; } /** make_const() Called if we've managed to calculate the value of this Item in opt_sum_query(), hence it can be considered constant at all subsequent steps. */ void make_const () { used_tables_cache= 0; const_item_cache= true; } void reset_forced_const() { const_item_cache= false; } bool const_during_execution() const override { return false; } void print(String *str, enum_query_type query_type) override; void fix_num_length_and_dec(); /** Mark an aggregate as having no rows. This function is called by the execution engine to assign 'NO ROWS FOUND' value to an aggregate item, when the underlying result set has no rows. Such value, in a general case, may be different from the default value of the item after 'clear()': e.g. a numeric item may be initialized to 0 by clear() and to NULL by no_rows_in_result(). */ void no_rows_in_result() override { set_aggregator(current_thd, with_distinct ? Aggregator::DISTINCT_AGGREGATOR : Aggregator::SIMPLE_AGGREGATOR); aggregator_clear(); } virtual void make_unique() { force_copy_fields= TRUE; } virtual Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table); Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { return create_tmp_field(root, param->group(), table); } bool collect_outer_ref_processor(void *param) override; bool init_sum_func_check(THD *thd); bool check_sum_func(THD *thd, Item **ref); bool register_sum_func(THD *thd, Item **ref); st_select_lex *depended_from() { return (nest_level == aggr_level ? 0 : aggr_sel); } Item *get_arg(uint i) const { return args[i]; } Item *set_arg(uint i, THD *thd, Item *new_val); uint get_arg_count() const { return arg_count; } virtual Item **get_args() { return fixed() ? orig_args : args; } /* Initialization of distinct related members */ void init_aggregator() { aggr= NULL; with_distinct= FALSE; force_copy_fields= FALSE; } /** Called to initialize the aggregator. */ inline bool aggregator_setup(THD *thd) { return aggr->setup(thd); }; /** Called to cleanup the aggregator. */ inline void aggregator_clear() { aggr->clear(); } /** Called to add value to the aggregator. */ inline bool aggregator_add() { return aggr->add(); }; /* stores the declared DISTINCT flag (from the parser) */ void set_distinct(bool distinct) { with_distinct= distinct; quick_group= with_distinct ? 0 : 1; } /* Set the type of aggregation : DISTINCT or not. May be called multiple times. */ int set_aggregator(THD *thd, Aggregator::Aggregator_type aggregator); virtual void clear()= 0; virtual bool add()= 0; virtual bool setup(THD *thd) { return false; } virtual bool supports_removal() const { return false; } virtual void remove() { DBUG_ASSERT(0); } void cleanup() override; bool check_vcol_func_processor(void *arg) override; virtual void setup_window_func(THD *thd, Window_spec *window_spec) {} void mark_as_window_func_sum_expr() { window_func_sum_expr_flag= true; } bool is_window_func_sum_expr() { return window_func_sum_expr_flag; } virtual void setup_caches(THD *thd) {}; virtual void set_partition_row_count(ulonglong count) { DBUG_ASSERT(0); } /* While most Item_sum descendants employ standard aggregators configured through Item_sum::set_aggregator() call, there are exceptions like Item_func_group_concat, which implements its own custom aggregators for deduplication values. This function distinguishes between the use of standard and custom aggregators by the object */ virtual bool uses_non_standard_aggregator_for_distinct() const { return false; } }; class Unique; /** The distinct aggregator. Implements AGGFN (DISTINCT ..) Collects all the data into an Unique (similarly to what Item_sum does currently when with_distinct=true) and then (if applicable) iterates over the list of unique values and pumps them back into its object */ class Aggregator_distinct : public Aggregator { friend class Item_sum_sum; /* flag to prevent consecutive runs of endup(). Normally in endup there are expensive calculations (like walking the distinct tree for example) which we must do only once if there are no data changes. We can re-use the data for the second and subsequent val_xxx() calls. endup_done set to TRUE also means that the calculated values for the aggregate functions are correct and don't need recalculation. */ bool endup_done; /* Used depending on the type of the aggregate function and the presence of blob columns in it: - For COUNT(DISTINCT) and no blob fields this points to a real temporary table. It's used as a hash table. - For AVG/SUM(DISTINCT) or COUNT(DISTINCT) with blob fields only the in-memory data structure of a temporary table is constructed. It's used by the Field classes to transform data into row format. */ TABLE *table; /* An array of field lengths on row allocated and used only for COUNT(DISTINCT) with multiple columns and no blobs. Used in Aggregator_distinct::composite_key_cmp (called from Unique to compare nodes */ uint32 *field_lengths; /* Used in conjunction with 'table' to support the access to Field classes for COUNT(DISTINCT). Needed by copy_fields()/copy_funcs(). */ TMP_TABLE_PARAM *tmp_table_param; /* If there are no blobs in the COUNT(DISTINCT) arguments, we can use a tree, which is faster than heap table. In that case, we still use the table to help get things set up, but we insert nothing in it. For AVG/SUM(DISTINCT) we always use this tree (as it takes a single argument) to get the distinct rows. */ Unique *tree; /* The length of the temp table row. Must be a member of the class as it gets passed down to simple_raw_key_cmp () as a compare function argument to Unique. simple_raw_key_cmp () is used as a fast comparison function when the entire row can be binary compared. */ uint tree_key_length; /* Set to true if the result is known to be always NULL. If set deactivates creation and usage of the temporary table (in the 'table' member) and the Unique instance (in the 'tree' member) as well as the calculation of the final value on the first call to Item_[sum|avg|count]::val_xxx(). */ bool always_null; /** When feeding back the data in endup() from Unique/temp table back to Item_sum::add() methods we must read the data from Unique (and not recalculate the functions that are given as arguments to the aggregate function. This flag is to tell the arg_*() methods to take the data from the Unique instead of calling the relevant val_..() method. */ bool use_distinct_values; public: Aggregator_distinct (Item_sum *sum) : Aggregator(sum), table(NULL), tmp_table_param(NULL), tree(NULL), always_null(false), use_distinct_values(false) {} virtual ~Aggregator_distinct (); Aggregator_type Aggrtype() override { return DISTINCT_AGGREGATOR; } bool setup(THD *) override; void clear() override; bool add() override; void endup() override; my_decimal *arg_val_decimal(my_decimal * value) override; double arg_val_real() override; bool arg_is_null(bool use_null_value) override; bool unique_walk_function(void *element); bool unique_walk_function_for_count(void *element); static int composite_key_cmp(void *arg, const void *key1, const void *key2); }; /** The pass-through aggregator. Implements AGGFN (DISTINCT ..) by knowing it gets distinct data on input. So it just pumps them back to the Item_sum descendant class. */ class Aggregator_simple : public Aggregator { public: Aggregator_simple (Item_sum *sum) : Aggregator(sum) {} Aggregator_type Aggrtype() override { return Aggregator::SIMPLE_AGGREGATOR; } bool setup(THD * thd) override { return item_sum->setup(thd); } void clear() override { item_sum->clear(); } bool add() override { return item_sum->add(); } void endup() override {}; my_decimal *arg_val_decimal(my_decimal * value) override; double arg_val_real() override; bool arg_is_null(bool use_null_value) override; }; class Item_sum_num :public Item_sum { public: Item_sum_num(THD *thd): Item_sum(thd) {} Item_sum_num(THD *thd, Item *item_par): Item_sum(thd, item_par) {} Item_sum_num(THD *thd, Item *a, Item* b): Item_sum(thd, a, b) {} Item_sum_num(THD *thd, List &list): Item_sum(thd, list) {} Item_sum_num(THD *thd, Item_sum_num *item): Item_sum(thd, item) {} bool fix_fields(THD *, Item **) override; }; class Item_sum_double :public Item_sum_num { public: Item_sum_double(THD *thd): Item_sum_num(thd) {} Item_sum_double(THD *thd, Item *item_par): Item_sum_num(thd, item_par) {} Item_sum_double(THD *thd, List &list): Item_sum_num(thd, list) {} Item_sum_double(THD *thd, Item_sum_double *item) :Item_sum_num(thd, item) {} longlong val_int() override { return val_int_from_real(); } String *val_str(String*str) override { return val_string_from_real(str); } my_decimal *val_decimal(my_decimal *to) override { return val_decimal_from_real(to); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_real(thd, ltime, fuzzydate); } const Type_handler *type_handler() const override { return &type_handler_double; } }; class Item_sum_int :public Item_sum_num { public: Item_sum_int(THD *thd): Item_sum_num(thd) {} Item_sum_int(THD *thd, Item *item_par): Item_sum_num(thd, item_par) {} Item_sum_int(THD *thd, List &list): Item_sum_num(thd, list) {} Item_sum_int(THD *thd, Item_sum_int *item) :Item_sum_num(thd, item) {} double val_real() override { DBUG_ASSERT(fixed()); return (double) val_int(); } String *val_str(String*str) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_int(thd, ltime, fuzzydate); } bool fix_length_and_dec() override { decimals=0; max_length=21; base_flags&= ~item_base_t::MAYBE_NULL; null_value=0; return false; } }; class Item_sum_sum :public Item_sum_num, public Type_handler_hybrid_field_type { protected: bool direct_added; bool direct_reseted_field; bool direct_sum_is_null; double direct_sum_real; double sum; my_decimal direct_sum_decimal; my_decimal dec_buffs[2]; uint curr_dec_buff; bool fix_length_and_dec() override; public: Item_sum_sum(THD *thd, Item *item_par, bool distinct): Item_sum_num(thd, item_par), direct_added(FALSE), direct_reseted_field(FALSE) { set_distinct(distinct); } Item_sum_sum(THD *thd, Item_sum_sum *item); enum Sumfunctype sum_func() const override { return has_with_distinct() ? SUM_DISTINCT_FUNC : SUM_FUNC; } void cleanup() override; void direct_add(my_decimal *add_sum_decimal); void direct_add(double add_sum_real, bool add_sum_is_null); void clear() override; bool add() override; double val_real() override; longlong val_int() override; String *val_str(String*str) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } void fix_length_and_dec_double(); void fix_length_and_dec_decimal(); void reset_field() override; void update_field() override; void no_rows_in_result() override {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name_distinct= { STRING_WITH_LEN("sum(distinct ")}; static LEX_CSTRING name_normal= { STRING_WITH_LEN("sum(") }; return has_with_distinct() ? name_distinct : name_normal; } Item *copy_or_same(THD* thd) override; void remove() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool supports_removal() const override { return true; } private: void add_helper(bool perform_removal); ulonglong count; }; class Item_sum_count :public Item_sum_int { bool direct_counted; bool direct_reseted_field; longlong direct_count; longlong count; friend class Aggregator_distinct; void clear() override; bool add() override; void cleanup() override; void remove() override; public: Item_sum_count(THD *thd, Item *item_par): Item_sum_int(thd, item_par), direct_counted(FALSE), direct_reseted_field(FALSE), count(0) {} /** Constructs an instance for COUNT(DISTINCT) @param list a list of the arguments to the aggregate function This constructor is called by the parser only for COUNT (DISTINCT). */ Item_sum_count(THD *thd, List &list): Item_sum_int(thd, list), direct_counted(FALSE), direct_reseted_field(FALSE), count(0) { set_distinct(TRUE); } Item_sum_count(THD *thd, Item_sum_count *item): Item_sum_int(thd, item), direct_counted(FALSE), direct_reseted_field(FALSE), count(item->count) {} enum Sumfunctype sum_func () const override { return has_with_distinct() ? COUNT_DISTINCT_FUNC : COUNT_FUNC; } void no_rows_in_result() override { count=0; } void make_const(longlong count_arg) { count=count_arg; Item_sum::make_const(); } const Type_handler *type_handler() const override { return &type_handler_slonglong; } longlong val_int() override; void reset_field() override; void update_field() override; void direct_add(longlong add_count); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name_distinct= { STRING_WITH_LEN("count(distinct ")}; static LEX_CSTRING name_normal= { STRING_WITH_LEN("count(") }; return has_with_distinct() ? name_distinct : name_normal; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool supports_removal() const override { return true; } }; class Item_sum_avg :public Item_sum_sum { public: // TODO-cvicentiu given that Item_sum_sum now uses a counter of its own, in // order to implement remove(), it is possible to remove this member. ulonglong count; uint prec_increment; uint f_precision, f_scale, dec_bin_size; Item_sum_avg(THD *thd, Item *item_par, bool distinct): Item_sum_sum(thd, item_par, distinct), count(0) {} Item_sum_avg(THD *thd, Item_sum_avg *item) :Item_sum_sum(thd, item), count(item->count), prec_increment(item->prec_increment) {} void fix_length_and_dec_double(); void fix_length_and_dec_decimal(); bool fix_length_and_dec() override; enum Sumfunctype sum_func () const override { return has_with_distinct() ? AVG_DISTINCT_FUNC : AVG_FUNC; } void clear() override; bool add() override; void remove() override; double val_real() override; // In SPs we might force the "wrong" type with select into a declare variable longlong val_int() override { return val_int_from_real(); } my_decimal *val_decimal(my_decimal *) override; String *val_str(String *str) override; void reset_field() override; void update_field() override; Item *result_item(THD *thd, Field *field) override; void no_rows_in_result() override {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name_distinct= { STRING_WITH_LEN("avg(distinct ")}; static LEX_CSTRING name_normal= { STRING_WITH_LEN("avg(") }; return has_with_distinct() ? name_distinct : name_normal; } Item *copy_or_same(THD* thd) override; Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) override; void cleanup() override { count= 0; Item_sum_sum::cleanup(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool supports_removal() const override { return true; } }; /* variance(a) = = sum (ai - avg(a))^2 / count(a) ) = sum (ai^2 - 2*ai*avg(a) + avg(a)^2) / count(a) = (sum(ai^2) - sum(2*ai*avg(a)) + sum(avg(a)^2))/count(a) = = (sum(ai^2) - 2*avg(a)*sum(a) + count(a)*avg(a)^2)/count(a) = = (sum(ai^2) - 2*sum(a)*sum(a)/count(a) + count(a)*sum(a)^2/count(a)^2 )/count(a) = = (sum(ai^2) - 2*sum(a)^2/count(a) + sum(a)^2/count(a) )/count(a) = = (sum(ai^2) - sum(a)^2/count(a))/count(a) But, this falls prey to catastrophic cancellation. Instead, use the recurrence formulas M_{1} = x_{1}, ~ M_{k} = M_{k-1} + (x_{k} - M_{k-1}) / k newline S_{1} = 0, ~ S_{k} = S_{k-1} + (x_{k} - M_{k-1}) times (x_{k} - M_{k}) newline for 2 <= k <= n newline ital variance = S_{n} / (n-1) */ class Stddev { double m_m; double m_s; ulonglong m_count; public: Stddev() :m_m(0), m_s(0), m_count(0) { } Stddev(double nr) :m_m(nr), m_s(0.0), m_count(1) { } Stddev(const uchar *); void to_binary(uchar *) const; void recurrence_next(double nr); double result(bool is_simple_variance); ulonglong count() const { return m_count; } static uint32 binary_size() { return (uint32) (sizeof(double) * 2 + sizeof(ulonglong)); }; }; class Item_sum_variance :public Item_sum_double { Stddev m_stddev; bool fix_length_and_dec() override; public: uint sample; uint prec_increment; Item_sum_variance(THD *thd, Item *item_par, uint sample_arg): Item_sum_double(thd, item_par), sample(sample_arg) {} Item_sum_variance(THD *thd, Item_sum_variance *item); Sumfunctype sum_func () const override { return VARIANCE_FUNC; } void fix_length_and_dec_double(); void fix_length_and_dec_decimal(); void clear() override final; bool add() override final; double val_real() override; void reset_field() override final; void update_field() override final; Item *result_item(THD *thd, Field *field) override; void no_rows_in_result() override final {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name_sample= { STRING_WITH_LEN("var_samp(")}; static LEX_CSTRING name_normal= { STRING_WITH_LEN("variance(") }; return sample ? name_sample : name_normal; } Item *copy_or_same(THD* thd) override; Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) override final; void cleanup() override final { m_stddev= Stddev(); Item_sum_double::cleanup(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* standard_deviation(a) = sqrt(variance(a)) */ class Item_sum_std final :public Item_sum_variance { public: Item_sum_std(THD *thd, Item *item_par, uint sample_arg): Item_sum_variance(thd, item_par, sample_arg) {} Item_sum_std(THD *thd, Item_sum_std *item) :Item_sum_variance(thd, item) {} enum Sumfunctype sum_func () const override final { return STD_FUNC; } double val_real() override final; Item *result_item(THD *thd, Field *field) override final; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING std_name= {STRING_WITH_LEN("std(") }; static LEX_CSTRING stddev_samp_name= {STRING_WITH_LEN("stddev_samp(") }; return sample ? stddev_samp_name : std_name; } Item *copy_or_same(THD* thd) override final; Item *do_get_copy(THD *thd) const override final { return get_item_copy(thd, this); } }; class Item_sum_hybrid : public Item_sum, public Type_handler_hybrid_field_type { public: Item_sum_hybrid(THD *thd, Item *item_par): Item_sum(thd, item_par), Type_handler_hybrid_field_type(&type_handler_slonglong) { collation.set(&my_charset_bin); } Item_sum_hybrid(THD *thd, Item *a, Item *b): Item_sum(thd, a, b), Type_handler_hybrid_field_type(&type_handler_slonglong) { collation.set(&my_charset_bin); } Item_sum_hybrid(THD *thd, Item_sum_hybrid *item) :Item_sum(thd, item), Type_handler_hybrid_field_type(item) { } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } bool fix_length_and_dec_generic(); bool fix_length_and_dec_numeric(const Type_handler *h); bool fix_length_and_dec_sint_ge0(); bool fix_length_and_dec_string(); }; // This class is a string or number function depending on num_func class Arg_comparator; class Item_cache; class Item_sum_min_max :public Item_sum_hybrid { protected: bool direct_added; Item *direct_item; Item_cache *value, *arg_cache; Arg_comparator *cmp; int cmp_sign; bool was_values; // Set if we have found at least one row (for max/min only) bool was_null_value; public: Item_sum_min_max(THD *thd, Item *item_par,int sign): Item_sum_hybrid(thd, item_par), direct_added(FALSE), value(0), arg_cache(0), cmp(0), cmp_sign(sign), was_values(TRUE) { collation.set(&my_charset_bin); } Item_sum_min_max(THD *thd, Item_sum_min_max *item) :Item_sum_hybrid(thd, item), direct_added(FALSE), value(item->value), arg_cache(0), cmp_sign(item->cmp_sign), was_values(item->was_values) { } bool fix_fields(THD *, Item **) override; bool fix_length_and_dec() override; void setup_hybrid(THD *thd, Item *item, Item *value_arg); void clear() override; void direct_add(Item *item); double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; void reset_field() override; String *val_str(String *) override; bool val_native(THD *thd, Native *) override; const Type_handler *real_type_handler() const override { return get_arg(0)->real_type_handler(); } const TYPELIB *get_typelib() const override { return args[0]->get_typelib(); } void update_field() override; void min_max_update_str_field(); void min_max_update_real_field(); void min_max_update_int_field(); void min_max_update_decimal_field(); void min_max_update_native_field(); void cleanup() override; bool any_value() { return was_values; } void no_rows_in_result() override; void restore_to_before_no_rows_in_result() override; Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) override; void setup_caches(THD *thd) override { setup_hybrid(thd, arguments()[0], NULL); } }; class Item_sum_min final :public Item_sum_min_max { public: Item_sum_min(THD *thd, Item *item_par): Item_sum_min_max(thd, item_par, 1) {} Item_sum_min(THD *thd, Item_sum_min *item) :Item_sum_min_max(thd, item) {} enum Sumfunctype sum_func () const override {return MIN_FUNC;} bool add() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING sum_name= {STRING_WITH_LEN("min(") }; return sum_name; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_max final :public Item_sum_min_max { public: Item_sum_max(THD *thd, Item *item_par): Item_sum_min_max(thd, item_par, -1) {} Item_sum_max(THD *thd, Item_sum_max *item) :Item_sum_min_max(thd, item) {} enum Sumfunctype sum_func() const override {return MAX_FUNC;} bool add() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING sum_name= {STRING_WITH_LEN("max(") }; return sum_name; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_bit :public Item_sum_int { public: Item_sum_bit(THD *thd, Item *item_par, ulonglong reset_arg): Item_sum_int(thd, item_par), reset_bits(reset_arg), bits(reset_arg), as_window_function(FALSE), num_values_added(0) {} Item_sum_bit(THD *thd, Item_sum_bit *item): Item_sum_int(thd, item), reset_bits(item->reset_bits), bits(item->bits), as_window_function(item->as_window_function), num_values_added(item->num_values_added) { if (as_window_function) memcpy(bit_counters, item->bit_counters, sizeof(bit_counters)); } enum Sumfunctype sum_func () const override { return SUM_BIT_FUNC;} void clear() override; longlong val_int() override; void reset_field() override; void update_field() override; const Type_handler *type_handler() const override { return &type_handler_ulonglong; } bool fix_length_and_dec() override { if (args[0]->check_type_can_return_int(func_name_cstring())) return true; decimals= 0; max_length=21; unsigned_flag= 1; base_flags&= ~item_base_t::MAYBE_NULL; null_value= 0; return FALSE; } void cleanup() override { bits= reset_bits; if (as_window_function) clear_as_window(); Item_sum_int::cleanup(); } void setup_window_func(THD *, Window_spec *) override { as_window_function= TRUE; clear_as_window(); } void remove() override { if (as_window_function) { remove_as_window(args[0]->val_int()); return; } // Unless we're counting bits, we can not remove anything. DBUG_ASSERT(0); } bool supports_removal() const override { return true; } protected: enum bit_counters { NUM_BIT_COUNTERS= 64 }; ulonglong reset_bits,bits; /* Marks whether the function is to be computed as a window function. */ bool as_window_function; // When used as an aggregate window function, we need to store // this additional information. ulonglong num_values_added; ulonglong bit_counters[NUM_BIT_COUNTERS]; bool add_as_window(ulonglong value); bool remove_as_window(ulonglong value); bool clear_as_window(); virtual void set_bits_from_counters()= 0; }; class Item_sum_or final :public Item_sum_bit { public: Item_sum_or(THD *thd, Item *item_par): Item_sum_bit(thd, item_par, 0) {} Item_sum_or(THD *thd, Item_sum_or *item) :Item_sum_bit(thd, item) {} bool add() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING sum_name= {STRING_WITH_LEN("bit_or(") }; return sum_name; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: void set_bits_from_counters() override; }; class Item_sum_and final :public Item_sum_bit { public: Item_sum_and(THD *thd, Item *item_par): Item_sum_bit(thd, item_par, ULONGLONG_MAX) {} Item_sum_and(THD *thd, Item_sum_and *item) :Item_sum_bit(thd, item) {} bool add() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING sum_min_name= {STRING_WITH_LEN("bit_and(") }; return sum_min_name; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: void set_bits_from_counters() override; }; class Item_sum_xor final :public Item_sum_bit { public: Item_sum_xor(THD *thd, Item *item_par): Item_sum_bit(thd, item_par, 0) {} Item_sum_xor(THD *thd, Item_sum_xor *item) :Item_sum_bit(thd, item) {} bool add() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING sum_min_name= {STRING_WITH_LEN("bit_xor(") }; return sum_min_name; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: void set_bits_from_counters() override; }; class sp_head; class sp_name; class Query_arena; struct st_sp_security_context; /* Item_sum_sp handles STORED AGGREGATE FUNCTIONS Each Item_sum_sp represents a custom aggregate function. Inside the function's body, we require at least one occurrence of FETCH GROUP NEXT ROW instruction. This cursor is what makes custom stored aggregates possible. During computation the function's add method is called. This in turn performs an execution of the function. The function will execute from the current function context (and instruction), if one exists, or from the start if not. See Item_sp for more details. Upon encounter of FETCH GROUP NEXT ROW instruction, the function will pause execution. We assume that the user has performed the necessary additions for a row, between two encounters of FETCH GROUP NEXT ROW. Example: create aggregate function f1(x INT) returns int begin declare continue handler for not found return s; declare s int default 0 loop fetch group next row; set s = s + x; end loop; end The function will always stop after an encounter of FETCH GROUP NEXT ROW, except (!) on first encounter, as the value for the first row in the group is already set in the argument x. This behaviour is done so when a user writes a function, he should "logically" include FETCH GROUP NEXT ROW before any "add" instructions in the stored function. This means however that internally, the first occurrence doesn't stop the function. See the implementation of FETCH GROUP NEXT ROW for details as to how it happens. Either way, one should assume that after calling "Item_sum_sp::add()" that the values for that particular row have been added to the aggregation. To produce values for val_xxx methods we need an extra syntactic construct. We require a continue handler when "no more rows are available". val_xxx methods force a function return by executing the function again, while setting a server flag that no more rows have been found. This implies that val_xxx methods should only be called once per group however. Example: DECLARE CONTINUE HANDLER FOR NOT FOUND RETURN ret_val; */ class Item_sum_sp :public Item_sum, public Item_sp { private: bool execute(); public: Item_sum_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name, sp_head *sp); Item_sum_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name, sp_head *sp, List &list); Item_sum_sp(THD *thd, Item_sum_sp *item); enum Sumfunctype sum_func () const override { return SP_AGGREGATE_FUNC; } Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { return create_table_field_from_handler(root, table); } bool fix_length_and_dec() override; bool fix_fields(THD *thd, Item **ref) override; LEX_CSTRING func_name_cstring() const override; const Type_handler *type_handler() const override; bool add() override; /* val_xx functions */ longlong val_int() override { if(execute()) return 0; return sp_result_field->val_int(); } double val_real() override { if(execute()) return 0.0; return sp_result_field->val_real(); } my_decimal *val_decimal(my_decimal *dec_buf) override { if(execute()) return NULL; return sp_result_field->val_decimal(dec_buf); } bool val_native(THD *thd, Native *to) override { return (null_value= execute()) || sp_result_field->val_native(to); } String *val_str(String *str) override { String buf; char buff[20]; buf.set(buff, 20, str->charset()); buf.length(0); if (execute()) return NULL; /* result_field will set buf pointing to internal buffer of the resul_field. Due to this it will change any time when SP is executed. In order to prevent occasional corruption of returned value, we make here a copy. */ sp_result_field->val_str(&buf); str->copy(buf); return str; } void reset_field() override{DBUG_ASSERT(0);} void update_field() override{DBUG_ASSERT(0);} void clear() override; void cleanup() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return execute() || sp_result_field->get_date(ltime, fuzzydate); } inline Field *get_sp_result_field() { return sp_result_field; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *copy_or_same(THD *thd) override; }; /* Items to get the value of a stored sum function */ class Item_sum_field :public Item { protected: Field *field; public: Item_sum_field(THD *thd, Item_sum *item) :Item(thd), field(item->result_field) { name= item->name; set_maybe_null(); decimals= item->decimals; max_length= item->max_length; unsigned_flag= item->unsigned_flag; } table_map used_tables() const override { return (table_map) 1L; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { return create_tmp_field_ex_simple(root, table, src, param); } void save_in_result_field(bool no_conversions) override { DBUG_ASSERT(0); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(name.str, arg, VCOL_IMPOSSIBLE); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } }; class Item_avg_field :public Item_sum_field { protected: uint prec_increment; public: Item_avg_field(THD *thd, Item_sum_avg *item) :Item_sum_field(thd, item), prec_increment(item->prec_increment) { } enum Type type() const override { return FIELD_AVG_ITEM; } bool is_null() override { update_null_value(); return null_value; } }; class Item_avg_field_double :public Item_avg_field { public: Item_avg_field_double(THD *thd, Item_sum_avg *item) :Item_avg_field(thd, item) { } const Type_handler *type_handler() const override { return &type_handler_double; } longlong val_int() override { return val_int_from_real(); } my_decimal *val_decimal(my_decimal *dec) override { return val_decimal_from_real(dec); } String *val_str(String *str) override { return val_string_from_real(str); } double val_real() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_avg_field_decimal :public Item_avg_field { uint f_precision, f_scale, dec_bin_size; public: Item_avg_field_decimal(THD *thd, Item_sum_avg *item) :Item_avg_field(thd, item), f_precision(item->f_precision), f_scale(item->f_scale), dec_bin_size(item->dec_bin_size) { } const Type_handler *type_handler() const override { return &type_handler_newdecimal; } double val_real() override { return VDec(this).to_double(); } longlong val_int() override { return VDec(this).to_longlong(unsigned_flag); } String *val_str(String *str) override { return VDec(this).to_string_round(str, decimals); } my_decimal *val_decimal(my_decimal *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_variance_field :public Item_sum_field { uint sample; public: Item_variance_field(THD *thd, Item_sum_variance *item) :Item_sum_field(thd, item), sample(item->sample) { } enum Type type() const override {return FIELD_VARIANCE_ITEM; } double val_real() override; longlong val_int() override { return val_int_from_real(); } String *val_str(String *str) override { return val_string_from_real(str); } my_decimal *val_decimal(my_decimal *dec_buf) override { return val_decimal_from_real(dec_buf); } bool is_null() override { update_null_value(); return null_value; } const Type_handler *type_handler() const override { return &type_handler_double; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_std_field :public Item_variance_field { public: Item_std_field(THD *thd, Item_sum_std *item) :Item_variance_field(thd, item) { } enum Type type() const override { return FIELD_STD_ITEM; } double val_real() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /* User defined aggregates */ #ifdef HAVE_DLOPEN class Item_udf_sum : public Item_sum { protected: udf_handler udf; public: Item_udf_sum(THD *thd, udf_func *udf_arg): Item_sum(thd), udf(udf_arg) { quick_group=0; } Item_udf_sum(THD *thd, udf_func *udf_arg, List &list): Item_sum(thd, list), udf(udf_arg) { quick_group=0;} Item_udf_sum(THD *thd, Item_udf_sum *item) :Item_sum(thd, item), udf(item->udf) { udf.not_original= TRUE; } LEX_CSTRING func_name_cstring() const override { const char *tmp= udf.name(); return {tmp, strlen(tmp) }; } bool fix_fields(THD *thd, Item **ref) override { DBUG_ASSERT(fixed() == 0); if (init_sum_func_check(thd)) return TRUE; base_flags|= item_base_t::FIXED; /* We set const_item_cache to false in constructors. It can be later changed to "true", in a Item_sum::make_const() call. No make_const() calls should have happened so far. */ DBUG_ASSERT(!const_item_cache); if (udf.fix_fields(thd, this, this->arg_count, this->args)) return TRUE; /** The above call for udf.fix_fields() updates the Used_tables_and_const_cache part of "this" as if it was a regular non-aggregate UDF function and can change both const_item_cache and used_tables_cache members. - The used_tables_cache will be re-calculated in update_used_tables() which is called from check_sum_func() below. So we don't care about its current value. - The const_item_cache must stay "false" until a Item_sum::make_const() call happens, if ever. So we need to reset const_item_cache back to "false" here. */ const_item_cache= false; memcpy (orig_args, args, sizeof (Item *) * arg_count); return check_sum_func(thd, ref); } enum Sumfunctype sum_func () const override { return UDF_SUM_FUNC; } virtual bool have_field_update(void) const { return 0; } void clear() override; bool add() override; bool supports_removal() const override; void remove() override; void reset_field() override {}; void update_field() override {} void cleanup() override; void print(String *str, enum_query_type query_type) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } }; class Item_sum_udf_float :public Item_udf_sum { public: Item_sum_udf_float(THD *thd, udf_func *udf_arg): Item_udf_sum(thd, udf_arg) {} Item_sum_udf_float(THD *thd, udf_func *udf_arg, List &list): Item_udf_sum(thd, udf_arg, list) {} Item_sum_udf_float(THD *thd, Item_sum_udf_float *item) :Item_udf_sum(thd, item) {} longlong val_int() override { return val_int_from_real(); } double val_real() override; String *val_str(String*str) override; my_decimal *val_decimal(my_decimal *) override; const Type_handler *type_handler() const override { return &type_handler_double; } bool fix_length_and_dec() override { fix_num_length_and_dec(); return FALSE; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_udf_int :public Item_udf_sum { public: Item_sum_udf_int(THD *thd, udf_func *udf_arg): Item_udf_sum(thd, udf_arg) {} Item_sum_udf_int(THD *thd, udf_func *udf_arg, List &list): Item_udf_sum(thd, udf_arg, list) {} Item_sum_udf_int(THD *thd, Item_sum_udf_int *item) :Item_udf_sum(thd, item) {} longlong val_int() override; double val_real() override { DBUG_ASSERT(fixed()); return (double) Item_sum_udf_int::val_int(); } String *val_str(String*str) override; my_decimal *val_decimal(my_decimal *) override; const Type_handler *type_handler() const override { if (unsigned_flag) return &type_handler_ulonglong; return &type_handler_slonglong; } bool fix_length_and_dec() override { decimals=0; max_length=21; return FALSE; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_udf_str :public Item_udf_sum { public: Item_sum_udf_str(THD *thd, udf_func *udf_arg): Item_udf_sum(thd, udf_arg) {} Item_sum_udf_str(THD *thd, udf_func *udf_arg, List &list): Item_udf_sum(thd, udf_arg, list) {} Item_sum_udf_str(THD *thd, Item_sum_udf_str *item) :Item_udf_sum(thd, item) {} String *val_str(String *) override; double val_real() override { int err_not_used; char *end_not_used; String *res; res=val_str(&str_value); return res ? res->charset()->strntod((char*) res->ptr(),res->length(), &end_not_used, &err_not_used) : 0.0; } longlong val_int() override { int err_not_used; char *end; String *res; CHARSET_INFO *cs; if (!(res= val_str(&str_value))) return 0; /* Null value */ cs= res->charset(); end= (char*) res->ptr()+res->length(); return cs->strtoll10(res->ptr(), &end, &err_not_used); } my_decimal *val_decimal(my_decimal *dec) override; const Type_handler *type_handler() const override { return string_type_handler(); } bool fix_length_and_dec() override; Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_sum_udf_decimal :public Item_udf_sum { public: Item_sum_udf_decimal(THD *thd, udf_func *udf_arg): Item_udf_sum(thd, udf_arg) {} Item_sum_udf_decimal(THD *thd, udf_func *udf_arg, List &list): Item_udf_sum(thd, udf_arg, list) {} Item_sum_udf_decimal(THD *thd, Item_sum_udf_decimal *item) :Item_udf_sum(thd, item) {} String *val_str(String *str) override { return VDec(this).to_string_round(str, decimals); } double val_real() override { return VDec(this).to_double(); } longlong val_int() override { return VDec(this).to_longlong(unsigned_flag); } my_decimal *val_decimal(my_decimal *) override; const Type_handler *type_handler() const override { return &type_handler_newdecimal; } bool fix_length_and_dec() override { fix_num_length_and_dec(); return FALSE; } Item *copy_or_same(THD* thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #else /* Dummy functions to get yy_*.cc files compiled */ class Item_sum_udf_float :public Item_sum_double { public: Item_sum_udf_float(THD *thd, udf_func *udf_arg): Item_sum_double(thd) {} Item_sum_udf_float(THD *thd, udf_func *udf_arg, List &list): Item_sum_double(thd) {} Item_sum_udf_float(THD *thd, Item_sum_udf_float *item) :Item_sum_double(thd, item) {} enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } double val_real() { DBUG_ASSERT(fixed()); return 0.0; } void clear() {} bool add() { return 0; } void reset_field() { DBUG_ASSERT(0); }; void update_field() {} }; class Item_sum_udf_int :public Item_sum_double { public: Item_sum_udf_int(THD *thd, udf_func *udf_arg): Item_sum_double(thd) {} Item_sum_udf_int(THD *thd, udf_func *udf_arg, List &list): Item_sum_double(thd) {} Item_sum_udf_int(THD *thd, Item_sum_udf_int *item) :Item_sum_double(thd, item) {} enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } longlong val_int() { DBUG_ASSERT(fixed()); return 0; } double val_real() { DBUG_ASSERT(fixed()); return 0; } void clear() {} bool add() { return 0; } void reset_field() { DBUG_ASSERT(0); }; void update_field() {} }; class Item_sum_udf_decimal :public Item_sum_double { public: Item_sum_udf_decimal(THD *thd, udf_func *udf_arg): Item_sum_double(thd) {} Item_sum_udf_decimal(THD *thd, udf_func *udf_arg, List &list): Item_sum_double(thd) {} Item_sum_udf_decimal(THD *thd, Item_sum_udf_float *item) :Item_sum_double(thd, item) {} enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } double val_real() { DBUG_ASSERT(fixed()); return 0.0; } my_decimal *val_decimal(my_decimal *) { DBUG_ASSERT(fixed()); return 0; } void clear() {} bool add() { return 0; } void reset_field() { DBUG_ASSERT(0); }; void update_field() {} }; class Item_sum_udf_str :public Item_sum_double { public: Item_sum_udf_str(THD *thd, udf_func *udf_arg): Item_sum_double(thd) {} Item_sum_udf_str(THD *thd, udf_func *udf_arg, List &list): Item_sum_double(thd) {} Item_sum_udf_str(THD *thd, Item_sum_udf_str *item) :Item_sum_double(thd, item) {} String *val_str(String *) { DBUG_ASSERT(fixed()); null_value=1; return 0; } double val_real() { DBUG_ASSERT(fixed()); null_value=1; return 0.0; } longlong val_int() { DBUG_ASSERT(fixed()); null_value=1; return 0; } bool fix_length_and_dec() override { base_flags|= item_base_t::MAYBE_NULL; max_length=0; return FALSE; } enum Sumfunctype sum_func () const { return UDF_SUM_FUNC; } void clear() {} bool add() { return 0; } void reset_field() { DBUG_ASSERT(0); }; void update_field() {} }; #endif /* HAVE_DLOPEN */ C_MODE_START int group_concat_key_cmp_with_distinct(void *arg, const void *key1, const void *key2); int group_concat_key_cmp_with_distinct_with_nulls(void *arg, const void *key1, const void *key2); int group_concat_key_cmp_with_order(void *arg, const void *key1, const void *key2); int group_concat_key_cmp_with_order_with_nulls(void *arg, const void *key1, const void *key2); int dump_leaf_key(void* key_arg, element_count count __attribute__((unused)), void* item_arg); C_MODE_END class Item_func_group_concat : public Item_sum { protected: TMP_TABLE_PARAM *tmp_table_param; String result; String *separator; TREE tree_base; TREE *tree; size_t tree_len; Item **ref_pointer_array; /** If DISTINCT is used with this GROUP_CONCAT, this member is used to filter out duplicates. @see Item_func_group_concat::setup @see Item_func_group_concat::add @see Item_func_group_concat::clear */ Unique *unique_filter; TABLE *table; ORDER **order; Name_resolution_context *context; /** The number of ORDER BY items. */ uint arg_count_order; /** The number of selected items, aka the expr list. */ uint arg_count_field; uint row_count; bool distinct; bool warning_for_row; bool always_null; bool force_copy_fields; /** True if entire result of GROUP_CONCAT has been written to output buffer. */ bool result_finalized; /** Limits the rows in the result */ Item *row_limit; /** Skips a particular number of rows in from the result*/ Item *offset_limit; bool limit_clause; /* copy of the offset limit */ ulonglong copy_offset_limit; /*copy of the row limit */ ulonglong copy_row_limit; /* Following is 0 normal object and pointer to original one for copy (to correctly free resources) */ Item_func_group_concat *original; /* Used by Item_func_group_concat and Item_func_json_arrayagg. The latter needs null values but the former doesn't. */ bool add(bool exclude_nulls); friend int group_concat_key_cmp_with_distinct(void *arg, const void *key1, const void *key2); friend int group_concat_key_cmp_with_distinct_with_nulls(void *arg, const void *key1, const void *key2); friend int group_concat_key_cmp_with_order(void *arg, const void *key1, const void *key2); friend int group_concat_key_cmp_with_order_with_nulls(void *arg, const void *key1, const void *key2); friend int dump_leaf_key(void* key_arg, element_count count __attribute__((unused)), void* item_arg); bool repack_tree(THD *thd); /* Says whether the function should skip NULL arguments or add them to the result. Redefined in JSON_ARRAYAGG. */ virtual bool skip_nulls() const { return true; } virtual String *get_str_from_item(Item *i, String *tmp) { return i->val_str(tmp); } virtual String *get_str_from_field(Item *i, Field *f, String *tmp, const uchar *key, size_t offset) { return f->val_str(tmp, key + offset); } virtual void cut_max_length(String *result, uint old_length, uint max_length) const; bool uses_non_standard_aggregator_for_distinct() const override { return distinct; } public: // Methods used by ColumnStore bool get_distinct() const { return distinct; } uint get_count_field() const { return arg_count_field; } uint get_order_field() const { return arg_count_order; } const String* get_separator() const { return separator; } ORDER** get_order() const { return order; } public: Item_func_group_concat(THD *thd, Name_resolution_context *context_arg, bool is_distinct, List *is_select, const SQL_I_List &is_order, String *is_separator, bool limit_clause, Item *row_limit, Item *offset_limit); Item_func_group_concat(THD *thd, Item_func_group_concat *item); ~Item_func_group_concat(); void cleanup() override; enum Sumfunctype sum_func () const override {return GROUP_CONCAT_FUNC;} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING sum_name= {STRING_WITH_LEN("group_concat(") }; return sum_name; } const Type_handler *type_handler() const override { if (too_big_for_varchar()) return &type_handler_blob; return &type_handler_varchar; } void clear() override; bool add() override { return add(skip_nulls()); } void reset_field() override { DBUG_ASSERT(0); } // not used void update_field() override { DBUG_ASSERT(0); } // not used bool fix_fields(THD *,Item **) override; bool setup(THD *thd) override; void make_unique() override; double val_real() override { int error; const char *end; String *res; if (!(res= val_str(&str_value))) return 0.0; end= res->ptr() + res->length(); return (my_strtod(res->ptr(), (char**) &end, &error)); } longlong val_int() override { String *res; char *end_ptr; int error; if (!(res= val_str(&str_value))) return (longlong) 0; end_ptr= (char*) res->ptr()+ res->length(); return my_strtoll10(res->ptr(), &end_ptr, &error); } my_decimal *val_decimal(my_decimal *decimal_value) override { return val_decimal_from_string(decimal_value); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_string(thd, ltime, fuzzydate); } String *val_str(String *str) override; Item *copy_or_same(THD* thd) override; void no_rows_in_result() override {} void print(String *str, enum_query_type query_type) override; bool change_context_processor(void *cntx) override { context= (Name_resolution_context *)cntx; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } qsort_cmp2 get_comparator_function_for_distinct(); qsort_cmp2 get_comparator_function_for_order_by(); uchar* get_record_pointer(); uint get_null_bytes(); }; #endif /* ITEM_SUM_INCLUDED */ mysql/server/private/des_key_file.h000064400000002324151027430560013470 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef DES_KEY_FILE_INCLUDED #define DES_KEY_FILE_INCLUDED #ifdef HAVE_des #include #include "violite.h" /* DES_cblock, DES_key_schedule */ struct st_des_keyblock { DES_cblock key1, key2, key3; }; struct st_des_keyschedule { DES_key_schedule ks1, ks2, ks3; }; extern struct st_des_keyschedule des_keyschedule[10]; extern uint des_default_key; bool load_des_key_file(const char *file_name); #endif /* HAVE_des */ #endif /* DES_KEY_FILE_INCLUDED */ mysql/server/private/sp.h000064400000054074151027430560011501 0ustar00/* -*- C++ -*- */ /* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _SP_H_ #define _SP_H_ #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_string.h" // LEX_STRING #include "sql_cmd.h" #include "mdl.h" class Field; class Open_tables_backup; class Open_tables_state; class Query_arena; class Query_tables_list; class Sroutine_hash_entry; class THD; class sp_cache; class sp_head; class sp_package; class sp_pcontext; class sp_name; class Database_qualified_name; struct st_sp_chistics; class Stored_program_creation_ctx; struct LEX; struct TABLE; struct TABLE_LIST; typedef struct st_hash HASH; template class SQL_I_List; /* Values for the type enum. This reflects the order of the enum declaration in the CREATE TABLE command. See also storage/perfschema/my_thread.h */ enum enum_sp_type { SP_TYPE_FUNCTION=1, SP_TYPE_PROCEDURE=2, SP_TYPE_PACKAGE=3, SP_TYPE_PACKAGE_BODY=4, SP_TYPE_TRIGGER=5, SP_TYPE_EVENT=6, }; class Sp_handler { bool sp_resolve_package_routine_explicit(THD *thd, sp_head *caller, sp_name *name, const Sp_handler **pkg_routine_hndlr, Database_qualified_name *pkgname) const; bool sp_resolve_package_routine_implicit(THD *thd, sp_head *caller, sp_name *name, const Sp_handler **pkg_routine_hndlr, Database_qualified_name *pkgname) const; protected: int db_find_routine_aux(THD *thd, const Database_qualified_name *name, TABLE *table) const; int db_find_routine(THD *thd, const Database_qualified_name *name, sp_head **sphp) const; int db_find_and_cache_routine(THD *thd, const Database_qualified_name *name, sp_head **sp) const; int db_load_routine(THD *thd, const Database_qualified_name *name, sp_head **sphp, sql_mode_t sql_mode, const LEX_CSTRING ¶ms, const LEX_CSTRING &returns, const LEX_CSTRING &body, const st_sp_chistics &chistics, const AUTHID &definer, longlong created, longlong modified, sp_package *parent, Stored_program_creation_ctx *creation_ctx) const; int sp_drop_routine_internal(THD *thd, const Database_qualified_name *name, TABLE *table) const; sp_head *sp_clone_and_link_routine(THD *thd, const Database_qualified_name *name, sp_head *sp) const; int sp_cache_package_routine(THD *thd, const LEX_CSTRING &pkgname_cstr, const Database_qualified_name *name, sp_head **sp) const; int sp_cache_package_routine(THD *thd, const Database_qualified_name *name, sp_head **sp) const; sp_head *sp_find_package_routine(THD *thd, const LEX_CSTRING pkgname_str, const Database_qualified_name *name, bool cache_only) const; sp_head *sp_find_package_routine(THD *thd, const Database_qualified_name *name, bool cache_only) const; public: // TODO: make it private or protected virtual int sp_find_and_drop_routine(THD *thd, TABLE *table, const Database_qualified_name *name) const; public: virtual ~Sp_handler() = default; static const Sp_handler *handler(enum enum_sql_command cmd); static const Sp_handler *handler(enum_sp_type type); static const Sp_handler *handler(MDL_key::enum_mdl_namespace ns); /* Return a handler only those SP objects that store definitions in the mysql.proc system table */ static const Sp_handler *handler_mysql_proc(enum_sp_type type) { const Sp_handler *sph= handler(type); return sph ? sph->sp_handler_mysql_proc() : NULL; } static bool eq_routine_name(const LEX_CSTRING &name1, const LEX_CSTRING &name2) { return system_charset_info->strnncoll(name1.str, name1.length, name2.str, name2.length) == 0; } const char *type_str() const { return type_lex_cstring().str; } virtual const char *show_create_routine_col1_caption() const { DBUG_ASSERT(0); return ""; } virtual const char *show_create_routine_col3_caption() const { DBUG_ASSERT(0); return ""; } virtual const Sp_handler *package_routine_handler() const { return this; } virtual enum_sp_type type() const= 0; virtual LEX_CSTRING type_lex_cstring() const= 0; virtual LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const { static LEX_CSTRING m_empty_body= {STRING_WITH_LEN("???")}; DBUG_ASSERT(0); return m_empty_body; } virtual MDL_key::enum_mdl_namespace get_mdl_type() const= 0; virtual const Sp_handler *sp_handler_mysql_proc() const { return this; } virtual sp_cache **get_cache(THD *) const { return NULL; } #ifndef NO_EMBEDDED_ACCESS_CHECKS virtual HASH *get_priv_hash() const { return NULL; } #endif virtual ulong recursion_depth(THD *thd) const { return 0; } /** Return appropriate error about recursion limit reaching @param thd Thread handle @param sp SP routine @remark For functions and triggers we return error about prohibited recursion. For stored procedures we return about reaching recursion limit. */ virtual void recursion_level_error(THD *thd, const sp_head *sp) const { my_error(ER_SP_NO_RECURSION, MYF(0)); } virtual bool add_instr_freturn(THD *thd, sp_head *sp, sp_pcontext *spcont, Item *item, LEX *lex) const; virtual bool add_instr_preturn(THD *thd, sp_head *sp, sp_pcontext *spcont) const; void add_used_routine(Query_tables_list *prelocking_ctx, Query_arena *arena, const Database_qualified_name *name) const; bool sp_resolve_package_routine(THD *thd, sp_head *caller, sp_name *name, const Sp_handler **pkg_routine_handler, Database_qualified_name *pkgname) const; virtual sp_head *sp_find_routine(THD *thd, const Database_qualified_name *name, bool cache_only) const; virtual int sp_cache_routine(THD *thd, const Database_qualified_name *name, sp_head **sp) const; int sp_cache_routine_reentrant(THD *thd, const Database_qualified_name *nm, sp_head **sp) const; bool sp_exist_routines(THD *thd, TABLE_LIST *procs) const; bool sp_show_create_routine(THD *thd, const Database_qualified_name *name) const; bool sp_create_routine(THD *thd, const sp_head *sp) const; int sp_update_routine(THD *thd, const Database_qualified_name *name, const st_sp_chistics *chistics) const; int sp_drop_routine(THD *thd, const Database_qualified_name *name) const; sp_head *sp_load_for_information_schema(THD *thd, TABLE *proc_table, const LEX_CSTRING &db, const LEX_CSTRING &name, const LEX_CSTRING ¶ms, const LEX_CSTRING &returns, sql_mode_t sql_mode, bool *free_sp_head) const; /* Make a SHOW CREATE statement. @retval true on error @retval false on success */ virtual bool show_create_sp(THD *thd, String *buf, const LEX_CSTRING &db, const LEX_CSTRING &name, const LEX_CSTRING ¶ms, const LEX_CSTRING &returns, const LEX_CSTRING &body, const st_sp_chistics &chistics, const AUTHID &definer, const DDL_options_st ddl_options, sql_mode_t sql_mode) const; }; class Sp_handler_procedure: public Sp_handler { public: enum_sp_type type() const override { return SP_TYPE_PROCEDURE; } LEX_CSTRING type_lex_cstring() const override { static LEX_CSTRING m_type_str= { STRING_WITH_LEN("PROCEDURE")}; return m_type_str; } LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const override; const char *show_create_routine_col1_caption() const override { return "Procedure"; } const char *show_create_routine_col3_caption() const override { return "Create Procedure"; } MDL_key::enum_mdl_namespace get_mdl_type() const override { return MDL_key::PROCEDURE; } const Sp_handler *package_routine_handler() const override; sp_cache **get_cache(THD *) const override; #ifndef NO_EMBEDDED_ACCESS_CHECKS HASH *get_priv_hash() const override; #endif ulong recursion_depth(THD *thd) const override; void recursion_level_error(THD *thd, const sp_head *sp) const override; bool add_instr_preturn(THD *thd, sp_head *sp, sp_pcontext *spcont) const override; }; class Sp_handler_package_procedure: public Sp_handler_procedure { public: int sp_cache_routine(THD *thd, const Database_qualified_name *name, sp_head **sp) const override { return sp_cache_package_routine(thd, name, sp); } sp_head *sp_find_routine(THD *thd, const Database_qualified_name *name, bool cache_only) const override { return sp_find_package_routine(thd, name, cache_only); } }; class Sp_handler_function: public Sp_handler { public: enum_sp_type type() const override { return SP_TYPE_FUNCTION; } LEX_CSTRING type_lex_cstring() const override { static LEX_CSTRING m_type_str= { STRING_WITH_LEN("FUNCTION")}; return m_type_str; } LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const override; const char *show_create_routine_col1_caption() const override { return "Function"; } const char *show_create_routine_col3_caption() const override { return "Create Function"; } MDL_key::enum_mdl_namespace get_mdl_type() const override { return MDL_key::FUNCTION; } const Sp_handler *package_routine_handler() const override; sp_cache **get_cache(THD *) const override; #ifndef NO_EMBEDDED_ACCESS_CHECKS HASH *get_priv_hash() const override; #endif bool add_instr_freturn(THD *thd, sp_head *sp, sp_pcontext *spcont, Item *item, LEX *lex) const override; }; class Sp_handler_package_function: public Sp_handler_function { public: int sp_cache_routine(THD *thd, const Database_qualified_name *name, sp_head **sp) const override { return sp_cache_package_routine(thd, name, sp); } sp_head *sp_find_routine(THD *thd, const Database_qualified_name *name, bool cache_only) const override { return sp_find_package_routine(thd, name, cache_only); } }; class Sp_handler_package: public Sp_handler { public: bool show_create_sp(THD *thd, String *buf, const LEX_CSTRING &db, const LEX_CSTRING &name, const LEX_CSTRING ¶ms, const LEX_CSTRING &returns, const LEX_CSTRING &body, const st_sp_chistics &chistics, const AUTHID &definer, const DDL_options_st ddl_options, sql_mode_t sql_mode) const override; }; class Sp_handler_package_spec: public Sp_handler_package { public: // TODO: make it private or protected int sp_find_and_drop_routine(THD *thd, TABLE *table, const Database_qualified_name *name) const override; public: enum_sp_type type() const override { return SP_TYPE_PACKAGE; } LEX_CSTRING type_lex_cstring() const override { static LEX_CSTRING m_type_str= {STRING_WITH_LEN("PACKAGE")}; return m_type_str; } LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const override { static LEX_CSTRING m_empty_body= {STRING_WITH_LEN("BEGIN END")}; return m_empty_body; } const char *show_create_routine_col1_caption() const override { return "Package"; } const char *show_create_routine_col3_caption() const override { return "Create Package"; } MDL_key::enum_mdl_namespace get_mdl_type() const override { return MDL_key::PACKAGE_BODY; } sp_cache **get_cache(THD *) const override; #ifndef NO_EMBEDDED_ACCESS_CHECKS HASH *get_priv_hash() const override; #endif }; class Sp_handler_package_body: public Sp_handler_package { public: enum_sp_type type() const override { return SP_TYPE_PACKAGE_BODY; } LEX_CSTRING type_lex_cstring() const override { static LEX_CSTRING m_type_str= {STRING_WITH_LEN("PACKAGE BODY")}; return m_type_str; } LEX_CSTRING empty_body_lex_cstring(sql_mode_t mode) const override { static LEX_CSTRING m_empty_body= {STRING_WITH_LEN("BEGIN END")}; return m_empty_body; } const char *show_create_routine_col1_caption() const override { return "Package body"; } const char *show_create_routine_col3_caption() const override { return "Create Package Body"; } MDL_key::enum_mdl_namespace get_mdl_type() const override { return MDL_key::PACKAGE_BODY; } sp_cache **get_cache(THD *) const override; #ifndef NO_EMBEDDED_ACCESS_CHECKS HASH *get_priv_hash() const override; #endif }; class Sp_handler_trigger: public Sp_handler { public: enum_sp_type type() const override { return SP_TYPE_TRIGGER; } LEX_CSTRING type_lex_cstring() const override { static LEX_CSTRING m_type_str= { STRING_WITH_LEN("TRIGGER")}; return m_type_str; } MDL_key::enum_mdl_namespace get_mdl_type() const override { DBUG_ASSERT(0); return MDL_key::TRIGGER; } const Sp_handler *sp_handler_mysql_proc() const override { return NULL; } }; extern MYSQL_PLUGIN_IMPORT Sp_handler_function sp_handler_function; extern MYSQL_PLUGIN_IMPORT Sp_handler_procedure sp_handler_procedure; extern MYSQL_PLUGIN_IMPORT Sp_handler_package_spec sp_handler_package_spec; extern MYSQL_PLUGIN_IMPORT Sp_handler_package_body sp_handler_package_body; extern MYSQL_PLUGIN_IMPORT Sp_handler_package_function sp_handler_package_function; extern MYSQL_PLUGIN_IMPORT Sp_handler_package_procedure sp_handler_package_procedure; extern MYSQL_PLUGIN_IMPORT Sp_handler_trigger sp_handler_trigger; inline const Sp_handler *Sp_handler::handler(enum_sql_command cmd) { switch (cmd) { case SQLCOM_CREATE_PROCEDURE: case SQLCOM_ALTER_PROCEDURE: case SQLCOM_DROP_PROCEDURE: case SQLCOM_SHOW_PROC_CODE: case SQLCOM_SHOW_CREATE_PROC: case SQLCOM_SHOW_STATUS_PROC: return &sp_handler_procedure; case SQLCOM_CREATE_SPFUNCTION: case SQLCOM_ALTER_FUNCTION: case SQLCOM_DROP_FUNCTION: case SQLCOM_SHOW_FUNC_CODE: case SQLCOM_SHOW_CREATE_FUNC: case SQLCOM_SHOW_STATUS_FUNC: return &sp_handler_function; case SQLCOM_CREATE_PACKAGE: case SQLCOM_DROP_PACKAGE: case SQLCOM_SHOW_CREATE_PACKAGE: case SQLCOM_SHOW_STATUS_PACKAGE: return &sp_handler_package_spec; case SQLCOM_CREATE_PACKAGE_BODY: case SQLCOM_DROP_PACKAGE_BODY: case SQLCOM_SHOW_CREATE_PACKAGE_BODY: case SQLCOM_SHOW_STATUS_PACKAGE_BODY: case SQLCOM_SHOW_PACKAGE_BODY_CODE: return &sp_handler_package_body; default: break; } return NULL; } inline const Sp_handler *Sp_handler::handler(enum_sp_type type) { switch (type) { case SP_TYPE_PROCEDURE: return &sp_handler_procedure; case SP_TYPE_FUNCTION: return &sp_handler_function; case SP_TYPE_PACKAGE: return &sp_handler_package_spec; case SP_TYPE_PACKAGE_BODY: return &sp_handler_package_body; case SP_TYPE_TRIGGER: return &sp_handler_trigger; case SP_TYPE_EVENT: break; } return NULL; } inline const Sp_handler *Sp_handler::handler(MDL_key::enum_mdl_namespace type) { switch (type) { case MDL_key::FUNCTION: return &sp_handler_function; case MDL_key::PROCEDURE: return &sp_handler_procedure; case MDL_key::PACKAGE_BODY: return &sp_handler_package_body; case MDL_key::BACKUP: case MDL_key::SCHEMA: case MDL_key::TABLE: case MDL_key::TRIGGER: case MDL_key::EVENT: case MDL_key::USER_LOCK: case MDL_key::NAMESPACE_END: break; } return NULL; } /* Tells what SP_DEFAULT_ACCESS should be mapped to */ #define SP_DEFAULT_ACCESS_MAPPING SP_CONTAINS_SQL // Return codes from sp_create_*, sp_drop_*, and sp_show_*: #define SP_OK 0 #define SP_KEY_NOT_FOUND -1 #define SP_OPEN_TABLE_FAILED -2 #define SP_WRITE_ROW_FAILED -3 #define SP_DELETE_ROW_FAILED -4 #define SP_GET_FIELD_FAILED -5 #define SP_PARSE_ERROR -6 #define SP_INTERNAL_ERROR -7 #define SP_NO_DB_ERROR -8 #define SP_BAD_IDENTIFIER -9 #define SP_BODY_TOO_LONG -10 #define SP_FLD_STORE_FAILED -11 /* DB storage of Stored PROCEDUREs and FUNCTIONs */ enum { MYSQL_PROC_FIELD_DB = 0, MYSQL_PROC_FIELD_NAME, MYSQL_PROC_MYSQL_TYPE, MYSQL_PROC_FIELD_SPECIFIC_NAME, MYSQL_PROC_FIELD_LANGUAGE, MYSQL_PROC_FIELD_ACCESS, MYSQL_PROC_FIELD_DETERMINISTIC, MYSQL_PROC_FIELD_SECURITY_TYPE, MYSQL_PROC_FIELD_PARAM_LIST, MYSQL_PROC_FIELD_RETURNS, MYSQL_PROC_FIELD_BODY, MYSQL_PROC_FIELD_DEFINER, MYSQL_PROC_FIELD_CREATED, MYSQL_PROC_FIELD_MODIFIED, MYSQL_PROC_FIELD_SQL_MODE, MYSQL_PROC_FIELD_COMMENT, MYSQL_PROC_FIELD_CHARACTER_SET_CLIENT, MYSQL_PROC_FIELD_COLLATION_CONNECTION, MYSQL_PROC_FIELD_DB_COLLATION, MYSQL_PROC_FIELD_BODY_UTF8, MYSQL_PROC_FIELD_AGGREGATE, MYSQL_PROC_FIELD_COUNT }; /* Drop all routines in database 'db' */ int sp_drop_db_routines(THD *thd, const char *db); /** Acquires exclusive metadata lock on all stored routines in the given database. @param thd Thread handler @param db Database name @retval false Success @retval true Failure */ bool lock_db_routines(THD *thd, const char *db); /** Structure that represents element in the set of stored routines used by statement or routine. */ class Sroutine_hash_entry { public: /** Metadata lock request for routine. MDL_key in this request is also used as a key for set. */ MDL_request mdl_request; /** Next element in list linking all routines in set. See also comments for LEX::sroutine/sroutine_list and sp_head::m_sroutines. */ Sroutine_hash_entry *next; /** Uppermost view which directly or indirectly uses this routine. 0 if routine is not used in view. Note that it also can be 0 if statement uses routine both via view and directly. */ TABLE_LIST *belong_to_view; /** This is for prepared statement validation purposes. A statement looks up and pre-loads all its stored functions at prepare. Later on, if a function is gone from the cache, execute may fail. Remember the version of sp_head at prepare to be able to invalidate the prepared statement at execute if it changes. */ ulong m_sp_cache_version; const Sp_handler *m_handler; int sp_cache_routine(THD *thd, sp_head **sp) const; }; bool sp_add_used_routine(Query_tables_list *prelocking_ctx, Query_arena *arena, const MDL_key *key, const Sp_handler *handler, TABLE_LIST *belong_to_view); void sp_remove_not_own_routines(Query_tables_list *prelocking_ctx); bool sp_update_sp_used_routines(HASH *dst, HASH *src); void sp_update_stmt_used_routines(THD *thd, Query_tables_list *prelocking_ctx, HASH *src, TABLE_LIST *belong_to_view); void sp_update_stmt_used_routines(THD *thd, Query_tables_list *prelocking_ctx, SQL_I_List *src, TABLE_LIST *belong_to_view); extern "C" const uchar *sp_sroutine_key(const void *ptr, size_t *plen, my_bool); /* Routines which allow open/lock and close mysql.proc table even when we already have some tables open and locked. */ TABLE *open_proc_table_for_read(THD *thd); bool load_charset(THD *thd, MEM_ROOT *mem_root, Field *field, CHARSET_INFO *dflt_cs, CHARSET_INFO **cs); bool load_collation(THD *thd,MEM_ROOT *mem_root, Field *field, CHARSET_INFO *dflt_cl, CHARSET_INFO **cl); void sp_returns_type(THD *thd, String &result, const sp_head *sp); #endif /* _SP_H_ */ mysql/server/private/my_handler_errors.h000064400000011422151027430560014563 0ustar00#ifndef MYSYS_MY_HANDLER_ERRORS_INCLUDED #define MYSYS_MY_HANDLER_ERRORS_INCLUDED /* Copyright (c) 2008, 2013, Oracle and/or its affiliates. Copyright (c) 2011, 2013, SkySQL Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Errors a handler can give you */ static const char *handler_error_messages[]= { /* 120 */ "Didn't find the key on read or update", "Duplicate key on write or update", "Internal (unspecified) error in handler", "Someone has changed the row since it was read (even though the table was locked to prevent it)", "Wrong index given to a function", "Undefined handler error 125", "Index is corrupted", "Table file is corrupted", "Out of memory in engine", "Undefined handler error 129", /* 130 */ "Incorrect file format", "Command not supported by the engine", "Old database file", "No record read before update", "Record was already deleted (or record file crashed)", "No more room in record file", "No more room in index file", "No more records (read after end of file)", "Unsupported extension used for table", "Too big row", /* 140 */ "Wrong create options", "Duplicate unique key on write or update", "Unknown character set used in table", "Conflicting table definitions in sub-tables of MERGE table", "Table is crashed and last repair failed", "Table was marked as crashed and should be repaired", "Lock timed out; Retry transaction", "Lock table is full; Restart program with a larger lock table", "Updates are not allowed under a read only transactions", "Lock deadlock; Retry transaction", /* 150 */ "Foreign key constraint is incorrectly formed", "Cannot add a child row", "Cannot delete a parent row", "No savepoint with that name", "Non unique key block size", "The table does not exist in the storage engine", "The table already existed in the storage engine", "Could not connect to the storage engine", "Unexpected null pointer found when using spatial index", "The table changed in the storage engine", /* 160 */ "There's no partition in the table for the given value", "Row-based binary logging of row failed", "Index needed in foreign key constraint", "Upholding foreign key constraints would lead to a duplicate key error in some other table", "Table needs to be upgraded before it can be used", "Table is read only", "Failed to get next auto increment value", "Failed to set row auto increment value", "Unknown (generic) error from engine", "Record was not updated. New values were the same as original values", /* 170 */ "It is not possible to log this statement", "The event was corrupt, leading to illegal data being read", "The table is of a new format not supported by this version", "The event could not be processed. No other handler error happened", "Fatal error during initialization of handler", "File too short; Expected more data in file", "Read page with wrong checksum", "Too many active concurrent transactions", "Record not matching the given partition set", "Index column length exceeds limit", /* 180 */ "Index corrupted", "Undo record too big", "Invalid InnoDB FTS Doc ID", "Table is being used in foreign key check", "Tablespace already exists", "Too many columns", "Row in wrong partition", "Row is not visible by the current transaction", "Operation was interrupted by end user (probably kill command?)", "Disk full", /* 190 */ "Incompatible key or row definition between the MariaDB .frm file and the information in the storage engine. You may have retry or dump and restore the table to fix this", "Too many words in a FTS phrase or proximity search", "Table encrypted but decryption failed. This could be because correct encryption management plugin is not loaded, used encryption key is not available or encryption method does not match.", "Foreign key cascade delete/update exceeds max depth", "Tablespace is missing for a table", "Sequence has been run out", "Sequence values are conflicting", "Error during commit", "Cannot select partitions", "Cannot initialize encryption. Check that all encryption parameters have been set", "Transaction was aborted", }; #endif /* MYSYS_MY_HANDLER_ERRORS_INCLUDED */ mysql/server/private/log_event_data_type.h000064400000003542151027430560015065 0ustar00/* Copyright (c) 2024, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef LOG_EVENT_DATA_TYPE_H #define LOG_EVENT_DATA_TYPE_H class Log_event_data_type { public: enum { CHUNK_SIGNED= 0, CHUNK_UNSIGNED= 1, CHUNK_DATA_TYPE_NAME= 2 }; protected: LEX_CSTRING m_data_type_name; Item_result m_type; uint m_charset_number; bool m_is_unsigned; public: Log_event_data_type() :m_data_type_name({NULL,0}), m_type(STRING_RESULT), m_charset_number(my_charset_bin.number), m_is_unsigned(false) { } Log_event_data_type(const LEX_CSTRING &data_type_name_arg, Item_result type_arg, uint charset_number_arg, bool is_unsigned_arg) :m_data_type_name(data_type_name_arg), m_type(type_arg), m_charset_number(charset_number_arg), m_is_unsigned(is_unsigned_arg) { } const LEX_CSTRING & data_type_name() const { return m_data_type_name; } Item_result type() const { return m_type; } uint charset_number() const { return m_charset_number; } bool is_unsigned() const { return m_is_unsigned; } bool unpack_optional_attributes(const char *str, const char *end); }; #endif // LOG_EVENT_DATA_TYPE_H mysql/server/private/log_event_old.h000064400000046566151027430560013706 0ustar00/* Copyright (c) 2007, 2013, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef LOG_EVENT_OLD_H #define LOG_EVENT_OLD_H /* Need to include this file at the proper position of log_event.h */ /** @file @brief This file contains classes handling old formats of row-based binlog events. */ /* Around 2007-10-31, I made these classes completely separated from the new classes (before, there was a complex class hierarchy involving multiple inheritance; see BUG#31581), by simply copying and pasting the entire contents of Rows_log_event into Old_rows_log_event and the entire contents of {Write|Update|Delete}_rows_log_event into {Write|Update|Delete}_rows_log_event_old. For clarity, I will keep the comments marking which code was cut-and-pasted for some time. With the classes collapsed into one, there is probably some redundancy (maybe some methods can be simplified and/or removed), but we keep them this way for now. /Sven */ /* These classes are based on the v1 RowsHeaderLen */ #undef ROWS_HEADER_LEN #define ROWS_HEADER_LEN ROWS_HEADER_LEN_V1 /** @class Old_rows_log_event Base class for the three types of row-based events {Write|Update|Delete}_row_log_event_old, with event type codes PRE_GA_{WRITE|UPDATE|DELETE}_ROWS_EVENT. These events are never created any more, except when reading a relay log created by an old server. */ class Old_rows_log_event : public Log_event { /********** BEGIN CUT & PASTE FROM Rows_log_event **********/ public: /** Enumeration of the errors that can be returned. */ enum enum_error { ERR_OPEN_FAILURE = -1, /**< Failure to open table */ ERR_OK = 0, /**< No error */ ERR_TABLE_LIMIT_EXCEEDED = 1, /**< No more room for tables */ ERR_OUT_OF_MEM = 2, /**< Out of memory */ ERR_BAD_TABLE_DEF = 3, /**< Table definition does not match */ ERR_RBR_TO_SBR = 4 /**< daisy-chanining RBR to SBR not allowed */ }; /* These definitions allow you to combine the flags into an appropriate flag set using the normal bitwise operators. The implicit conversion from an enum-constant to an integer is accepted by the compiler, which is then used to set the real set of flags. */ enum enum_flag { /* Last event of a statement */ STMT_END_F = (1U << 0), /* Value of the OPTION_NO_FOREIGN_KEY_CHECKS flag in thd->options */ NO_FOREIGN_KEY_CHECKS_F = (1U << 1), /* Value of the OPTION_RELAXED_UNIQUE_CHECKS flag in thd->options */ RELAXED_UNIQUE_CHECKS_F = (1U << 2), /** Indicates that rows in this event are complete, that is contain values for all columns of the table. */ COMPLETE_ROWS_F = (1U << 3) }; typedef uint16 flag_set; /* Special constants representing sets of flags */ enum { RLE_NO_FLAGS = 0U }; virtual ~Old_rows_log_event(); void set_flags(flag_set flags_arg) { m_flags |= flags_arg; } void clear_flags(flag_set flags_arg) { m_flags &= ~flags_arg; } flag_set get_flags(flag_set flags_arg) const { return m_flags & flags_arg; } #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) void pack_info(Protocol *protocol) override; #endif #ifdef MYSQL_CLIENT /* not for direct call, each derived has its own ::print() */ bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override= 0; #endif #ifndef MYSQL_CLIENT int add_row_data(uchar *data, size_t length) { return do_add_row_data(data,length); } #endif /* Member functions to implement superclass interface */ int get_data_size() override; MY_BITMAP const *get_cols() const { return &m_cols; } size_t get_width() const { return m_width; } ulonglong get_table_id() const { return m_table_id; } #ifndef MYSQL_CLIENT bool write_data_header() override; bool write_data_body() override; const char *get_db() override { return m_table->s->db.str; } #ifdef HAVE_REPLICATION bool is_part_of_group() override { return 1; } #endif #endif /* Check that malloc() succeeded in allocating memory for the rows buffer and the COLS vector. Checking that an Update_rows_log_event_old is valid is done in the Update_rows_log_event_old::is_valid() function. */ bool is_valid() const override { return m_rows_buf && m_cols.bitmap; } uint m_row_count; /* The number of rows added to the event */ protected: /* The constructors are protected since you're supposed to inherit this class, not create instances of this class. */ #ifndef MYSQL_CLIENT Old_rows_log_event(THD*, TABLE*, ulonglong table_id, MY_BITMAP const *cols, bool is_transactional); #endif Old_rows_log_event(const uchar *row_data, uint event_len, Log_event_type event_type, const Format_description_log_event *description_event); #ifdef MYSQL_CLIENT bool print_helper(FILE *, PRINT_EVENT_INFO *, char const *const name); #endif #ifndef MYSQL_CLIENT virtual int do_add_row_data(uchar *data, size_t length); #endif #ifndef MYSQL_CLIENT TABLE *m_table; /* The table the rows belong to */ #endif ulonglong m_table_id; /* Table ID */ MY_BITMAP m_cols; /* Bitmap denoting columns available */ ulong m_width; /* The width of the columns bitmap */ ulong m_master_reclength; /* Length of record on master side */ /* Bit buffers in the same memory as the class */ my_bitmap_map m_bitbuf[128/(sizeof(my_bitmap_map)*8)]; my_bitmap_map m_bitbuf_ai[128/(sizeof(my_bitmap_map)*8)]; uchar *m_rows_buf; /* The rows in packed format */ uchar *m_rows_cur; /* One-after the end of the data */ uchar *m_rows_end; /* One-after the end of the allocated space */ flag_set m_flags; /* Flags for row-level events */ /* helper functions */ #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) const uchar *m_curr_row; /* Start of the row being processed */ const uchar *m_curr_row_end; /* One-after the end of the current row */ uchar *m_key; /* Buffer to keep key value during searches */ int find_row(rpl_group_info *); int write_row(rpl_group_info *, const bool); // Unpack the current row into m_table->record[0] int unpack_current_row(rpl_group_info *rgi) { DBUG_ASSERT(m_table); ASSERT_OR_RETURN_ERROR(m_curr_row < m_rows_end, HA_ERR_CORRUPT_EVENT); return ::unpack_row(rgi, m_table, m_width, m_curr_row, &m_cols, &m_curr_row_end, &m_master_reclength, m_rows_end); } #endif private: #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; /* Primitive to prepare for a sequence of row executions. DESCRIPTION Before doing a sequence of do_prepare_row() and do_exec_row() calls, this member function should be called to prepare for the entire sequence. Typically, this member function will allocate space for any buffers that are needed for the two member functions mentioned above. RETURN VALUE The member function will return 0 if all went OK, or a non-zero error code otherwise. */ virtual int do_before_row_operations(const Slave_reporting_capability *const log) = 0; /* Primitive to clean up after a sequence of row executions. DESCRIPTION After doing a sequence of do_prepare_row() and do_exec_row(), this member function should be called to clean up and release any allocated buffers. The error argument, if non-zero, indicates an error which happened during row processing before this function was called. In this case, even if function is successful, it should return the error code given in the argument. */ virtual int do_after_row_operations(const Slave_reporting_capability *const log, int error) = 0; /* Primitive to do the actual execution necessary for a row. DESCRIPTION The member function will do the actual execution needed to handle a row. The row is located at m_curr_row. When the function returns, m_curr_row_end should point at the next row (one byte after the end of the current row). RETURN VALUE 0 if execution succeeded, 1 if execution failed. */ virtual int do_exec_row(rpl_group_info *rgi) = 0; #endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ /********** END OF CUT & PASTE FROM Rows_log_event **********/ protected: #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) int do_apply_event(Old_rows_log_event*, rpl_group_info *rgi); /* Primitive to prepare for a sequence of row executions. DESCRIPTION Before doing a sequence of do_prepare_row() and do_exec_row() calls, this member function should be called to prepare for the entire sequence. Typically, this member function will allocate space for any buffers that are needed for the two member functions mentioned above. RETURN VALUE The member function will return 0 if all went OK, or a non-zero error code otherwise. */ virtual int do_before_row_operations(TABLE *table) = 0; /* Primitive to clean up after a sequence of row executions. DESCRIPTION After doing a sequence of do_prepare_row() and do_exec_row(), this member function should be called to clean up and release any allocated buffers. */ virtual int do_after_row_operations(TABLE *table, int error) = 0; /* Primitive to prepare for handling one row in a row-level event. DESCRIPTION The member function prepares for execution of operations needed for one row in a row-level event by reading up data from the buffer containing the row. No specific interpretation of the data is normally done here, since SQL thread specific data is not available: that data is made available for the do_exec function. A pointer to the start of the next row, or NULL if the preparation failed. Currently, preparation cannot fail, but don't rely on this behavior. RETURN VALUE Error code, if something went wrong, 0 otherwise. */ virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, uchar const *row_start, uchar const **row_end) = 0; /* Primitive to do the actual execution necessary for a row. DESCRIPTION The member function will do the actual execution needed to handle a row. RETURN VALUE 0 if execution succeeded, 1 if execution failed. */ virtual int do_exec_row(TABLE *table) = 0; #endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ }; /** @class Write_rows_log_event_old Old class for binlog events that write new rows to a table (event type code PRE_GA_WRITE_ROWS_EVENT). Such events are never produced by this version of the server, but they may be read from a relay log created by an old server. New servers create events of class Write_rows_log_event (event type code WRITE_ROWS_EVENT) instead. */ class Write_rows_log_event_old : public Old_rows_log_event { /********** BEGIN CUT & PASTE FROM Write_rows_log_event **********/ public: #if !defined(MYSQL_CLIENT) Write_rows_log_event_old(THD*, TABLE*, ulonglong table_id, MY_BITMAP const *cols, bool is_transactional); #endif #ifdef HAVE_REPLICATION Write_rows_log_event_old(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif #if !defined(MYSQL_CLIENT) static bool binlog_row_logging_function(THD *thd, TABLE *table, bool is_transactional, const uchar *before_record __attribute__((unused)), const uchar *after_record) { return thd->binlog_write_row(table, is_transactional, after_record); } #endif private: #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) int do_before_row_operations(const Slave_reporting_capability *const) override; int do_after_row_operations(const Slave_reporting_capability *const,int) override; int do_exec_row(rpl_group_info *) override; #endif /********** END OF CUT & PASTE FROM Write_rows_log_event **********/ public: enum { /* Support interface to THD::binlog_prepare_pending_rows_event */ TYPE_CODE = PRE_GA_WRITE_ROWS_EVENT }; private: Log_event_type get_type_code() override { return (Log_event_type)TYPE_CODE; } #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) // use old definition of do_apply_event() int do_apply_event(rpl_group_info *rgi) override { return Old_rows_log_event::do_apply_event(this, rgi); } // primitives for old version of do_apply_event() int do_before_row_operations(TABLE *table) override; int do_after_row_operations(TABLE *table, int error) override; virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, uchar const *row_start, uchar const **row_end) override; int do_exec_row(TABLE *table) override; #endif }; /** @class Update_rows_log_event_old Old class for binlog events that modify existing rows to a table (event type code PRE_GA_UPDATE_ROWS_EVENT). Such events are never produced by this version of the server, but they may be read from a relay log created by an old server. New servers create events of class Update_rows_log_event (event type code UPDATE_ROWS_EVENT) instead. */ class Update_rows_log_event_old : public Old_rows_log_event { /********** BEGIN CUT & PASTE FROM Update_rows_log_event **********/ public: #ifndef MYSQL_CLIENT Update_rows_log_event_old(THD*, TABLE*, ulonglong table_id, MY_BITMAP const *cols, bool is_transactional); #endif #ifdef HAVE_REPLICATION Update_rows_log_event_old(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif #if !defined(MYSQL_CLIENT) static bool binlog_row_logging_function(THD *thd, TABLE *table, bool is_transactional, MY_BITMAP *cols, uint fields, const uchar *before_record, const uchar *after_record) { return thd->binlog_update_row(table, is_transactional, before_record, after_record); } #endif protected: #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) int do_before_row_operations(const Slave_reporting_capability *const) override; int do_after_row_operations(const Slave_reporting_capability *const,int) override; int do_exec_row(rpl_group_info *) override; #endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ /********** END OF CUT & PASTE FROM Update_rows_log_event **********/ uchar *m_after_image, *m_memory; public: enum { /* Support interface to THD::binlog_prepare_pending_rows_event */ TYPE_CODE = PRE_GA_UPDATE_ROWS_EVENT }; private: Log_event_type get_type_code() override { return (Log_event_type)TYPE_CODE; } #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) // use old definition of do_apply_event() int do_apply_event(rpl_group_info *rgi) override { return Old_rows_log_event::do_apply_event(this, rgi); } // primitives for old version of do_apply_event() int do_before_row_operations(TABLE *table) override; int do_after_row_operations(TABLE *table, int error) override; virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, uchar const *row_start, uchar const **row_end) override; int do_exec_row(TABLE *table) override; #endif /* !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) */ }; /** @class Delete_rows_log_event_old Old class for binlog events that delete existing rows from a table (event type code PRE_GA_DELETE_ROWS_EVENT). Such events are never produced by this version of the server, but they may be read from a relay log created by an old server. New servers create events of class Delete_rows_log_event (event type code DELETE_ROWS_EVENT) instead. */ class Delete_rows_log_event_old : public Old_rows_log_event { /********** BEGIN CUT & PASTE FROM Update_rows_log_event **********/ public: #ifndef MYSQL_CLIENT Delete_rows_log_event_old(THD*, TABLE*, ulonglong, MY_BITMAP const *cols, bool is_transactional); #endif #ifdef HAVE_REPLICATION Delete_rows_log_event_old(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif #if !defined(MYSQL_CLIENT) static bool binlog_row_logging_function(THD *thd, TABLE *table, bool is_transactional, MY_BITMAP *cols, uint fields, const uchar *before_record, const uchar *after_record __attribute__((unused))) { return thd->binlog_delete_row(table, is_transactional, before_record); } #endif protected: #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) int do_before_row_operations(const Slave_reporting_capability *const) override; int do_after_row_operations(const Slave_reporting_capability *const,int) override; int do_exec_row(rpl_group_info *) override; #endif /********** END CUT & PASTE FROM Delete_rows_log_event **********/ uchar *m_after_image, *m_memory; public: enum { /* Support interface to THD::binlog_prepare_pending_rows_event */ TYPE_CODE = PRE_GA_DELETE_ROWS_EVENT }; private: Log_event_type get_type_code() override { return (Log_event_type)TYPE_CODE; } #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) // use old definition of do_apply_event() int do_apply_event(rpl_group_info *rgi) override { return Old_rows_log_event::do_apply_event(this, rgi); } // primitives for old version of do_apply_event() int do_before_row_operations(TABLE *table) override; int do_after_row_operations(TABLE *table, int error) override; virtual int do_prepare_row(THD*, rpl_group_info*, TABLE*, uchar const *row_start, uchar const **row_end) override; int do_exec_row(TABLE *table) override; #endif }; #endif mysql/server/private/gcalc_tools.h000064400000027174151027430560013351 0ustar00/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved. Copyright (C) 2011 Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef GCALC_TOOLS_INCLUDED #define GCALC_TOOLS_INCLUDED #include "gcalc_slicescan.h" #include "sql_string.h" /* The Gcalc_function class objects are used to check for a binary relation. The relation can be constructed with the prefix notation using predicates as op_not (as !A) op_union ( A || B || C... ) op_intersection ( A && B && C ... ) op_symdifference ( A+B+C+... == 1 ) op_difference ( A && !(B||C||..)) with the calls of the add_operation(operation, n_operands) method. The relation is calculated over a set of shapes, that in turn have to be added with the add_new_shape() method. All the 'shapes' can be set to 0 with clear_shapes() method and single value can be changed with the invert_state() method. Then the value of the relation can be calculated with the count() method. Frequently used method is find_function(Gcalc_scan_iterator it) that iterates through the 'it' until the relation becomes TRUE. */ class Gcalc_function { private: String shapes_buffer; String function_buffer; int *i_states; int *b_states; uint32 cur_object_id; uint n_shapes; int count_internal(const char *cur_func, uint set_type, const char **end); public: enum op_type { v_empty= 0x00000000, v_find_t= 0x01000000, v_find_f= 0x02000000, v_t_found= 0x03000000, v_f_found= 0x04000000, v_mask= 0x07000000, op_not= 0x80000000, op_shape= 0x00000000, op_union= 0x10000000, op_intersection= 0x20000000, op_symdifference= 0x30000000, op_difference= 0x40000000, op_repeat= 0x50000000, op_border= 0x60000000, op_internals= 0x70000000, op_false= 0x08000000, op_any= 0x78000000 /* The mask to get any of the operations */ }; enum shape_type { shape_point= 0, shape_line= 1, shape_polygon= 2, shape_hole= 3 }; enum count_result { result_false= 0, result_true= 1, result_unknown= 2 }; Gcalc_function() : n_shapes(0) {} gcalc_shape_info add_new_shape(uint32 shape_id, shape_type shape_kind); /* Adds the leaf operation that returns the shape value. Also adds the shape to the list of operands. */ int single_shape_op(shape_type shape_kind, gcalc_shape_info *si); void add_operation(uint operation, uint32 n_operands); void add_not_operation(op_type operation, uint32 n_operands); uint32 get_next_expression_pos() { return function_buffer.length(); } void add_operands_to_op(uint32 operation_pos, uint32 n_operands); int repeat_expression(uint32 exp_pos); void set_cur_obj(uint32 cur_obj) { cur_object_id= cur_obj; } int reserve_shape_buffer(uint n_shapes); int reserve_op_buffer(uint n_ops); uint get_nshapes() const { return n_shapes; } shape_type get_shape_kind(gcalc_shape_info si) const { return (shape_type) uint4korr(shapes_buffer.ptr() + (si*4)); } void set_states(int *shape_states) { i_states= shape_states; } int alloc_states(); void invert_i_state(gcalc_shape_info shape) { i_states[shape]^= 1; } void set_i_state(gcalc_shape_info shape) { i_states[shape]= 1; } void clear_i_state(gcalc_shape_info shape) { i_states[shape]= 0; } void set_b_state(gcalc_shape_info shape) { b_states[shape]= 1; } void clear_b_state(gcalc_shape_info shape) { b_states[shape]= 0; } int get_state(gcalc_shape_info shape) { return i_states[shape] | b_states[shape]; } int get_i_state(gcalc_shape_info shape) { return i_states[shape]; } int get_b_state(gcalc_shape_info shape) { return b_states[shape]; } int count() { return count_internal(function_buffer.ptr(), 0, 0); } int count_last() { return count_internal(function_buffer.ptr(), 1, 0); } void clear_i_states(); void clear_b_states(); void reset(); int check_function(Gcalc_scan_iterator &scan_it); }; /* Gcalc_operation_transporter class extends the Gcalc_shape_transporter. In addition to the parent's functionality, it fills the Gcalc_function object so it has the function that determines the proper shape. For example Multipolyline will be represented as an union of polylines. */ class Gcalc_operation_transporter : public Gcalc_shape_transporter { protected: Gcalc_function *m_fn; gcalc_shape_info m_si; public: Gcalc_operation_transporter(Gcalc_function *fn, Gcalc_heap *heap) : Gcalc_shape_transporter(heap), m_fn(fn) {} int single_point(double x, double y) override; int start_line() override; int complete_line() override; int start_poly() override; int complete_poly() override; int start_ring() override; int complete_ring() override; int add_point(double x, double y) override; int start_collection(int n_objects) override; int empty_shape() override; }; /* When we calculate the result of an spatial operation like Union or Intersection, we receive vertexes of the result one-by-one, and probably need to treat them in variative ways. So, the Gcalc_result_receiver class designed to get these vertexes and construct shapes/objects out of them. and to store the result in an appropriate format */ class Gcalc_result_receiver { String buffer; uint32 n_points; Gcalc_function::shape_type common_shapetype; bool collection_result; uint32 n_shapes; uint32 n_holes; Gcalc_function::shape_type cur_shape; uint32 shape_pos; double first_x, first_y, prev_x, prev_y; double shape_area; public: Gcalc_result_receiver() : n_points(0), common_shapetype(Gcalc_function::shape_point), collection_result(FALSE), n_shapes(0), n_holes(0), cur_shape(Gcalc_function::shape_point), shape_pos(0) {} int start_shape(Gcalc_function::shape_type shape); int add_point(double x, double y); int complete_shape(); int single_point(double x, double y); int done(); void reset(); const char *result() { return buffer.ptr(); } uint length() { return buffer.length(); } int get_nshapes() { return n_shapes; } int get_nholes() { return n_holes; } int get_result_typeid(); uint32 position() { return buffer.length(); } int move_hole(uint32 dest_position, uint32 source_position, uint32 *position_shift); }; /* Gcalc_operation_reducer class incapsulates the spatial operation functionality. It analyses the slices generated by the slicescan and calculates the shape of the result defined by some Gcalc_function. */ class Gcalc_operation_reducer : public Gcalc_dyn_list { public: enum modes { /* Numeric values important here - careful with changing */ default_mode= 0, prefer_big_with_holes= 1, polygon_selfintersections_allowed= 2, /* allowed in the result */ line_selfintersections_allowed= 4 /* allowed in the result */ }; Gcalc_operation_reducer(size_t blk_size=8192); Gcalc_operation_reducer(const Gcalc_operation_reducer &gor); void init(Gcalc_function *fn, modes mode= default_mode); Gcalc_operation_reducer(Gcalc_function *fn, modes mode= default_mode, size_t blk_size=8192); GCALC_DECL_TERMINATED_STATE(killed) int count_slice(Gcalc_scan_iterator *si); int count_all(Gcalc_heap *hp); int get_result(Gcalc_result_receiver *storage); void reset(); #ifndef GCALC_DBUG_OFF int n_res_points; #endif /*GCALC_DBUG_OFF*/ class res_point : public Gcalc_dyn_list::Item { public: int intersection_point; union { const Gcalc_heap::Info *pi; res_point *first_poly_node; }; union { res_point *outer_poly; uint32 poly_position; }; res_point *up; res_point *down; res_point *glue; Gcalc_function::shape_type type; Gcalc_dyn_list::Item **prev_hook; #ifndef GCALC_DBUG_OFF int point_n; #endif /*GCALC_DBUG_OFF*/ void set(const Gcalc_scan_iterator *si); res_point *get_next() { return (res_point *)next; } }; class active_thread : public Gcalc_dyn_list::Item { public: res_point *rp; res_point *thread_start; const Gcalc_heap::Info *p1, *p2; res_point *enabled() { return rp; } active_thread *get_next() { return (active_thread *)next; } }; class poly_instance : public Gcalc_dyn_list::Item { public: uint32 *after_poly_position; poly_instance *get_next() { return (poly_instance *)next; } }; class line : public Gcalc_dyn_list::Item { public: active_thread *t; int incoming; const Gcalc_scan_iterator::point *p; line *get_next() { return (line *)next; } }; class poly_border : public Gcalc_dyn_list::Item { public: active_thread *t; int incoming; int prev_state; const Gcalc_scan_iterator::point *p; poly_border *get_next() { return (poly_border *)next; } }; line *m_lines; Gcalc_dyn_list::Item **m_lines_hook; poly_border *m_poly_borders; Gcalc_dyn_list::Item **m_poly_borders_hook; line *new_line() { return (line *) new_item(); } poly_border *new_poly_border() { return (poly_border *) new_item(); } int add_line(int incoming, active_thread *t, const Gcalc_scan_iterator::point *p); int add_poly_border(int incoming, active_thread *t, int prev_state, const Gcalc_scan_iterator::point *p); protected: Gcalc_function *m_fn; Gcalc_dyn_list::Item **m_res_hook; res_point *m_result; int m_mode; res_point *result_heap; active_thread *m_first_active_thread; res_point *add_res_point(Gcalc_function::shape_type type); active_thread *new_active_thread() { return (active_thread *)new_item(); } poly_instance *new_poly() { return (poly_instance *) new_item(); } private: int start_line(active_thread *t, const Gcalc_scan_iterator::point *p, const Gcalc_scan_iterator *si); int end_line(active_thread *t, const Gcalc_scan_iterator *si); int connect_threads(int incoming_a, int incoming_b, active_thread *ta, active_thread *tb, const Gcalc_scan_iterator::point *pa, const Gcalc_scan_iterator::point *pb, active_thread *prev_range, const Gcalc_scan_iterator *si, Gcalc_function::shape_type s_t); int add_single_point(const Gcalc_scan_iterator *si); poly_border *get_pair_border(poly_border *b1); int continue_range(active_thread *t, const Gcalc_heap::Info *p, const Gcalc_heap::Info *p_next); int continue_i_range(active_thread *t, const Gcalc_heap::Info *ii); int end_couple(active_thread *t0, active_thread *t1, const Gcalc_heap::Info *p); int get_single_result(res_point *res, Gcalc_result_receiver *storage); int get_result_thread(res_point *cur, Gcalc_result_receiver *storage, int move_upward, res_point *first_poly_node); int get_polygon_result(res_point *cur, Gcalc_result_receiver *storage, res_point *first_poly_node); int get_line_result(res_point *cur, Gcalc_result_receiver *storage); void free_result(res_point *res); }; #endif /*GCALC_TOOLS_INCLUDED*/ mysql/server/private/my_user.h000064400000002146151027430560012533 0ustar00/* Copyright (c) 2005-2007 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This is a header for libraries containing functions used in both server and only some of clients (but not in libmysql)... */ #ifndef _my_user_h_ #define _my_user_h_ C_MODE_START int parse_user(const char *user_id_str, size_t user_id_len, char *user_name_str, size_t *user_name_len, char *host_name_str, size_t *host_name_len); C_MODE_END #endif /* _my_user_h_ */ mysql/server/private/my_default.h000064400000003530151027430560013177 0ustar00/* Copyright (C) 2013 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Definitions for mysys/my_default.c */ #ifndef MY_DEFAULT_INCLUDED #define MY_DEFAULT_INCLUDED C_MODE_START extern MYSQL_PLUGIN_IMPORT const char *my_defaults_extra_file; extern const char *my_defaults_group_suffix; extern MYSQL_PLUGIN_IMPORT const char *my_defaults_file; extern my_bool my_defaults_mark_files; extern int get_defaults_options(char **argv); extern int my_load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv, const char ***); extern int load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv); extern void free_defaults(char **argv); extern void my_print_default_files(const char *conf_file); extern void print_defaults(const char *conf_file, const char **groups); /** Simplify load_defaults() common use */ #define load_defaults_or_exit(A, B, C, D) switch (load_defaults(A, B, C, D)) { \ case 0: break; \ case 4: my_end(0); exit(0); \ default: my_end(0); exit(1); } C_MODE_END #endif /* MY_DEFAULT_INCLUDED */ mysql/server/private/sql_lifo_buffer.h000064400000022714151027430560014214 0ustar00/* Copyright (c) 2010, 2011, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @defgroup Bi-directional LIFO buffers used by DS-MRR implementation @{ */ class Forward_lifo_buffer; class Backward_lifo_buffer; /* A base class for in-memory buffer used by DS-MRR implementation. Common properties: - The buffer is last-in-first-out, i.e. elements that are written last are read first. - The buffer contains fixed-size elements. The elements are either atomic byte sequences or pairs of them. - The buffer resides in the memory provided by the user. It is possible to = dynamically (ie. between write operations) add ajacent memory space to the buffer = dynamically remove unused space from the buffer. The intent of this is to allow to have two buffers on adjacent memory space, one is being read from (and so its space shrinks), while the other is being written to (and so it needs more and more space). There are two concrete classes, Forward_lifo_buffer and Backward_lifo_buffer. */ class Lifo_buffer { protected: size_t size1; size_t size2; public: /** write() will put into buffer size1 bytes pointed by write_ptr1. If size2!=0, then they will be accompanied by size2 bytes pointed by write_ptr2. */ uchar *write_ptr1; uchar *write_ptr2; /** read() will do reading by storing pointers to read data into read_ptr1 or into (read_ptr1, read_ptr2), depending on whether the buffer was set to store single objects or pairs. */ uchar *read_ptr1; uchar *read_ptr2; protected: uchar *start; /**< points to start of buffer space */ uchar *end; /**< points to just beyond the end of buffer space */ public: enum enum_direction { BACKWARD=-1, /**< buffer is filled/read from bigger to smaller memory addresses */ FORWARD=1 /**< buffer is filled/read from smaller to bigger memory addresses */ }; virtual enum_direction type() = 0; /* Buffer space control functions */ /** Let the buffer store data in the given space. */ void set_buffer_space(uchar *start_arg, uchar *end_arg) { start= start_arg; end= end_arg; if (end != start) TRASH_ALLOC(start, size_t(end - start)); reset(); } /** Specify where write() should get the source data from, as well as source data size. */ void setup_writing(size_t len1, size_t len2) { size1= len1; size2= len2; } /** Specify where read() should store pointers to read data, as well as read data size. The sizes must match those passed to setup_writing(). */ void setup_reading(size_t len1, size_t len2) { DBUG_ASSERT(len1 == size1); DBUG_ASSERT(len2 == size2); } bool can_write() { return have_space_for(size1 + size2); } virtual void write() = 0; bool is_empty() { return used_size() == 0; } virtual bool read() = 0; void sort(qsort_cmp2 cmp_func, void *cmp_func_arg) { size_t elem_size= size1 + size2; size_t n_elements= used_size() / elem_size; my_qsort2(used_area(), n_elements, elem_size, cmp_func, cmp_func_arg); } virtual void reset() = 0; virtual uchar *end_of_space() = 0; protected: virtual size_t used_size() = 0; /* To be used only by iterator class: */ virtual uchar *get_pos()= 0; virtual bool read(uchar **position, uchar **ptr1, uchar **ptr2)= 0; friend class Lifo_buffer_iterator; public: virtual bool have_space_for(size_t bytes) = 0; virtual void remove_unused_space(uchar **unused_start, uchar **unused_end)=0; virtual uchar *used_area() = 0; virtual ~Lifo_buffer() = default; }; /** Forward LIFO buffer The buffer that is being written to from start to end and read in the reverse. 'pos' points to just beyond the end of used space. It is possible to grow/shink the buffer at the end bound used space unused space *==============*-----------------* ^ ^ ^ | | +--- end | +---- pos +--- start */ class Forward_lifo_buffer: public Lifo_buffer { uchar *pos; public: enum_direction type() override { return FORWARD; } size_t used_size() override { return (size_t)(pos - start); } void reset() override { pos= start; } uchar *end_of_space() override { return pos; } bool have_space_for(size_t bytes) override { return (pos + bytes < end); } void write() override { write_bytes(write_ptr1, size1); if (size2) write_bytes(write_ptr2, size2); } void write_bytes(const uchar *data, size_t bytes) { DBUG_ASSERT(have_space_for(bytes)); memcpy(pos, data, bytes); pos += bytes; } bool have_data(uchar *position, size_t bytes) { return ((position - start) >= (ptrdiff_t)bytes); } uchar *read_bytes(uchar **position, size_t bytes) { DBUG_ASSERT(have_data(*position, bytes)); *position= (*position) - bytes; return *position; } bool read() override { return read(&pos, &read_ptr1, &read_ptr2); } bool read(uchar **position, uchar **ptr1, uchar **ptr2) override { if (!have_data(*position, size1 + size2)) return TRUE; if (size2) *ptr2= read_bytes(position, size2); *ptr1= read_bytes(position, size1); return FALSE; } void remove_unused_space(uchar **unused_start, uchar **unused_end) override { DBUG_ASSERT(0); /* Don't need this yet */ } /** Add more space to the buffer. The caller is responsible that the space being added is adjacent to the end of the buffer. @param unused_start Start of space @param unused_end End of space */ void grow(uchar *unused_start, uchar *unused_end) { DBUG_ASSERT(unused_end >= unused_start); DBUG_ASSERT(end == unused_start); TRASH_ALLOC(unused_start, size_t(unused_end - unused_start)); end= unused_end; } /* Return pointer to start of the memory area that is occupied by the data */ uchar *used_area() override { return start; } friend class Lifo_buffer_iterator; uchar *get_pos() override { return pos; } }; /** Backward LIFO buffer The buffer that is being written to from start to end and read in the reverse. 'pos' points to the start of used space. It is possible to grow/shink the buffer at the start. unused space used space *--------------*=================* ^ ^ ^ | | +--- end | +---- pos +--- start */ class Backward_lifo_buffer: public Lifo_buffer { uchar *pos; public: enum_direction type() override { return BACKWARD; } size_t used_size() override { return (size_t)(end - pos); } void reset() override { pos= end; } uchar *end_of_space() override { return end; } bool have_space_for(size_t bytes) override { return (pos - bytes >= start); } void write() override { if (write_ptr2) write_bytes(write_ptr2, size2); write_bytes(write_ptr1, size1); } void write_bytes(const uchar *data, size_t bytes) { DBUG_ASSERT(have_space_for(bytes)); pos -= bytes; memcpy(pos, data, bytes); } bool read() override { return read(&pos, &read_ptr1, &read_ptr2); } bool read(uchar **position, uchar **ptr1, uchar **ptr2) override { if (!have_data(*position, size1 + size2)) return TRUE; *ptr1= read_bytes(position, size1); if (size2) *ptr2= read_bytes(position, size2); return FALSE; } bool have_data(uchar *position, size_t bytes) { return ((end - position) >= (ptrdiff_t)bytes); } uchar *read_bytes(uchar **position, size_t bytes) { DBUG_ASSERT(have_data(*position, bytes)); uchar *ret= *position; *position= *position + bytes; return ret; } /** Stop using/return the unused part of the space @param unused_start OUT Start of the unused space @param unused_end OUT End of the unused space */ void remove_unused_space(uchar **unused_start, uchar **unused_end) override { *unused_start= start; *unused_end= pos; start= pos; } void grow(uchar *unused_start, uchar *unused_end) { DBUG_ASSERT(0); /* Not used for backward buffers */ } /* Return pointer to start of the memory area that is occupied by the data */ uchar *used_area() override { return pos; } friend class Lifo_buffer_iterator; uchar *get_pos() override { return pos; } }; /** Iterator to walk over contents of the buffer without reading from it */ class Lifo_buffer_iterator { uchar *pos; Lifo_buffer *buf; public: /* The data is read to here */ uchar *read_ptr1; uchar *read_ptr2; void init(Lifo_buffer *buf_arg) { buf= buf_arg; pos= buf->get_pos(); } /* Read the next value. The calling convention is the same as buf->read() has. @retval FALSE - ok @retval TRUE - EOF, reached the end of the buffer */ bool read() { return buf->read(&pos, &read_ptr1, &read_ptr2); } }; mysql/server/private/sql_locale.h000064400000005215151027430560013166 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_LOCALE_INCLUDED #define SQL_LOCALE_INCLUDED typedef struct my_locale_errmsgs { const char *language; const char ***errmsgs; } MY_LOCALE_ERRMSGS; typedef struct st_typelib TYPELIB; class MY_LOCALE { public: uint number; const char *name; const char *description; const bool is_ascii; TYPELIB *month_names; TYPELIB *ab_month_names; TYPELIB *day_names; TYPELIB *ab_day_names; uint max_month_name_length; uint max_day_name_length; uint decimal_point; uint thousand_sep; const char *grouping; MY_LOCALE_ERRMSGS *errmsgs; MY_LOCALE(uint number_par, const char *name_par, const char *descr_par, bool is_ascii_par, TYPELIB *month_names_par, TYPELIB *ab_month_names_par, TYPELIB *day_names_par, TYPELIB *ab_day_names_par, uint max_month_name_length_par, uint max_day_name_length_par, uint decimal_point_par, uint thousand_sep_par, const char *grouping_par, MY_LOCALE_ERRMSGS *errmsgs_par) : number(number_par), name(name_par), description(descr_par), is_ascii(is_ascii_par), month_names(month_names_par), ab_month_names(ab_month_names_par), day_names(day_names_par), ab_day_names(ab_day_names_par), max_month_name_length(max_month_name_length_par), max_day_name_length(max_day_name_length_par), decimal_point(decimal_point_par), thousand_sep(thousand_sep_par), grouping(grouping_par), errmsgs(errmsgs_par) {} my_repertoire_t repertoire() const { return is_ascii ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_EXTENDED; } }; /* Exported variables */ extern MY_LOCALE my_locale_en_US; extern MYSQL_PLUGIN_IMPORT MY_LOCALE *my_locales[]; extern MY_LOCALE *my_default_lc_messages; extern MY_LOCALE *my_default_lc_time_names; /* Exported functions */ MY_LOCALE *my_locale_by_name(const char *name); MY_LOCALE *my_locale_by_number(uint number); void cleanup_errmsgs(void); #endif /* SQL_LOCALE_INCLUDED */ mysql/server/private/sql_type_real.h000064400000002351151027430560013711 0ustar00/* Copyright (c) 2019 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SQL_TYPE_REAL_INCLUDED #define SQL_TYPE_REAL_INCLUDED #include class Float { float m_value; public: Float(float nr) :m_value(nr) { DBUG_ASSERT(!std::isnan(nr)); DBUG_ASSERT(!std::isinf(nr)); } Float(double nr) :m_value((float) nr) { DBUG_ASSERT(!std::isnan(nr)); DBUG_ASSERT(!std::isinf(nr)); DBUG_ASSERT(nr <= FLT_MAX); DBUG_ASSERT(nr >= -FLT_MAX); } Float(const uchar *ptr) { float4get(m_value, ptr); } bool to_string(String *to, uint dec) const; }; #endif // SQL_TYPE_REAL_INCLUDED mysql/server/private/my_counter.h000064400000003271151027430560013234 0ustar00#ifndef MY_COUNTER_H_INCLUDED #define MY_COUNTER_H_INCLUDED /* Copyright (C) 2018 MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include template class Atomic_counter { std::atomic m_counter; Type add(Type i) { return m_counter.fetch_add(i, std::memory_order_relaxed); } Type sub(Type i) { return m_counter.fetch_sub(i, std::memory_order_relaxed); } public: Atomic_counter(const Atomic_counter &rhs) { m_counter.store(rhs, std::memory_order_relaxed); } Atomic_counter(Type val): m_counter(val) {} Atomic_counter() = default; Type operator++(int) { return add(1); } Type operator--(int) { return sub(1); } Type operator++() { return add(1) + 1; } Type operator--() { return sub(1) - 1; } Type operator+=(const Type i) { return add(i) + i; } Type operator-=(const Type i) { return sub(i) - i; } operator Type() const { return m_counter.load(std::memory_order_relaxed); } Type operator=(const Type val) { m_counter.store(val, std::memory_order_relaxed); return val; } }; #endif /* MY_COUNTER_H_INCLUDED */ mysql/server/private/sql_plist.h000064400000017064151027430560013067 0ustar00#ifndef SQL_PLIST_H #define SQL_PLIST_H /* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ template class I_P_List_iterator; class I_P_List_null_counter; template class I_P_List_no_push_back; /** Intrusive parameterized list. Unlike I_List does not require its elements to be descendant of ilink class and therefore allows them to participate in several such lists simultaneously. Unlike List is doubly-linked list and thus supports efficient deletion of element without iterator. @param T Type of elements which will belong to list. @param B Class which via its methods specifies which members of T should be used for participating in this list. Here is typical layout of such class: struct B { static inline T **next_ptr(T *el) { return &el->next; } static inline T ***prev_ptr(T *el) { return &el->prev; } }; @param C Policy class specifying how counting of elements in the list should be done. Instance of this class is also used as a place where information about number of list elements is stored. @sa I_P_List_null_counter, I_P_List_counter @param I Policy class specifying whether I_P_List should support efficient push_back() operation. Instance of this class is used as place where we store information to support this operation. @sa I_P_List_no_push_back, I_P_List_fast_push_back. */ template > class I_P_List : public C, public I { T *m_first; /* Do not prohibit copying of I_P_List object to simplify their usage in backup/restore scenarios. Note that performing any operations on such is a bad idea. */ public: I_P_List() : I(&m_first), m_first(NULL) {}; /* empty() is used in many places in the code instead of a constructor, to initialize a bzero-ed I_P_List instance. */ inline void empty() { m_first= NULL; C::reset(); I::set_last(&m_first); } inline bool is_empty() const { return (m_first == NULL); } inline void push_front(T* a) { *B::next_ptr(a)= m_first; if (m_first) *B::prev_ptr(m_first)= B::next_ptr(a); else I::set_last(B::next_ptr(a)); m_first= a; *B::prev_ptr(a)= &m_first; C::inc(); } inline void push_back(T *a) { T **last= I::get_last(); *B::next_ptr(a)= *last; *last= a; *B::prev_ptr(a)= last; I::set_last(B::next_ptr(a)); C::inc(); } inline void insert_after(T *pos, T *a) { if (pos == NULL) push_front(a); else { *B::next_ptr(a)= *B::next_ptr(pos); *B::prev_ptr(a)= B::next_ptr(pos); *B::next_ptr(pos)= a; if (*B::next_ptr(a)) { T *old_next= *B::next_ptr(a); *B::prev_ptr(old_next)= B::next_ptr(a); } else I::set_last(B::next_ptr(a)); C::inc(); } } inline void remove(T *a) { T *next= *B::next_ptr(a); if (next) *B::prev_ptr(next)= *B::prev_ptr(a); else I::set_last(*B::prev_ptr(a)); **B::prev_ptr(a)= next; C::dec(); } inline T* front() { return m_first; } inline const T *front() const { return m_first; } inline T* pop_front() { T *result= front(); if (result) remove(result); return result; } void swap(I_P_List &rhs) { swap_variables(T *, m_first, rhs.m_first); I::swap(rhs); if (m_first) *B::prev_ptr(m_first)= &m_first; else I::set_last(&m_first); if (rhs.m_first) *B::prev_ptr(rhs.m_first)= &rhs.m_first; else I::set_last(&rhs.m_first); C::swap(rhs); } typedef B Adapter; typedef I_P_List Base; typedef I_P_List_iterator Iterator; typedef I_P_List_iterator Const_Iterator; #ifndef _lint friend class I_P_List_iterator; friend class I_P_List_iterator; #endif }; /** Iterator for I_P_List. */ template class I_P_List_iterator { const L *list; T *current; public: I_P_List_iterator(const L &a) : list(&a), current(a.m_first) {} I_P_List_iterator(const L &a, T* current_arg) : list(&a), current(current_arg) {} inline void init(const L &a) { list= &a; current= a.m_first; } /** Operator for it++ @note since we save next element pointer, caller may remove current element. Such modification doesn't invalidate iterator. */ inline T* operator++(int) { T *result= current; if (result) current= *L::Adapter::next_ptr(current); return result; } /* Operator for ++it */ inline T* operator++() { current= *L::Adapter::next_ptr(current); return current; } inline void rewind() { current= list->m_first; } }; /** Hook class which via its methods specifies which members of T should be used for participating in a intrusive list. */ template struct I_P_List_adapter { static inline T **next_ptr(T *el) { return &(el->*next); } static inline const T* const* next_ptr(const T *el) { return &(el->*next); } static inline T ***prev_ptr(T *el) { return &(el->*prev); } }; /** Element counting policy class for I_P_List to be used in cases when no element counting should be done. */ class I_P_List_null_counter { protected: void reset() {} void inc() {} void dec() {} void swap(I_P_List_null_counter &) {} }; /** Element counting policy class for I_P_List which provides basic element counting. */ class I_P_List_counter { uint m_counter; protected: I_P_List_counter() : m_counter (0) {} void reset() {m_counter= 0;} void inc() {m_counter++;} void dec() {m_counter--;} void swap(I_P_List_counter &rhs) { swap_variables(uint, m_counter, rhs.m_counter); } public: uint elements() const { return m_counter; } }; /** A null insertion policy class for I_P_List to be used in cases when push_back() operation is not necessary. */ template class I_P_List_no_push_back { protected: I_P_List_no_push_back(T **) {} void set_last(T **) {} /* T** get_last() const method is intentionally left unimplemented in order to prohibit usage of push_back() method in lists which use this policy. */ void swap(I_P_List_no_push_back &) {} }; /** An insertion policy class for I_P_List which can be used when fast push_back() operation is required. */ template class I_P_List_fast_push_back { T **m_last; protected: I_P_List_fast_push_back(T **a) : m_last(a) { }; void set_last(T **a) { m_last= a; } T** get_last() const { return m_last; } void swap(I_P_List_fast_push_back &rhs) { swap_variables(T**, m_last, rhs.m_last); } }; #endif mysql/server/private/sql_binlog.h000064400000001577151027430560013210 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_BINLOG_INCLUDED #define SQL_BINLOG_INCLUDED class THD; void mysql_client_binlog_statement(THD *thd); #endif /* SQL_BINLOG_INCLUDED */ mysql/server/private/my_alarm.h000064400000004575151027430560012661 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* File to include when we want to use alarm or a loop_counter to display some information when a program is running */ #ifndef _my_alarm_h #define _my_alarm_h #ifdef __cplusplus extern "C" { #endif extern int volatile my_have_got_alarm; extern ulong my_time_to_wait_for_lock; #if defined(HAVE_ALARM) && !defined(NO_ALARM_LOOP) #include #ifdef HAVE_SIGHANDLER_T #define sig_return sighandler_t #elif defined(SOLARIS) || defined(__sun) || defined(__APPLE__) || \ defined(_AIX) || \ defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ defined(__DragonFly__) typedef void (*sig_return)(int); /* Returns type from signal */ #else typedef void (*sig_return)(void); /* Returns type from signal */ #endif #define ALARM_VARIABLES uint alarm_old=0; \ sig_return alarm_signal=0 #define ALARM_INIT my_have_got_alarm=0 ; \ alarm_old=(uint) alarm(MY_HOW_OFTEN_TO_ALARM); \ alarm_signal=signal(SIGALRM,my_set_alarm_variable); #define ALARM_END (void) signal(SIGALRM,alarm_signal); \ (void) alarm(alarm_old); #define ALARM_TEST my_have_got_alarm #ifdef SIGNAL_HANDLER_RESET_ON_DELIVERY #define ALARM_REINIT (void) alarm(MY_HOW_OFTEN_TO_ALARM); \ (void) signal(SIGALRM,my_set_alarm_variable);\ my_have_got_alarm=0; #else #define ALARM_REINIT (void) alarm((uint) MY_HOW_OFTEN_TO_ALARM); \ my_have_got_alarm=0; #endif /* SIGNAL_HANDLER_RESET_ON_DELIVERY */ #else #define ALARM_VARIABLES long alarm_pos=0,alarm_end_pos=MY_HOW_OFTEN_TO_WRITE-1 #define ALARM_INIT #define ALARM_END #define ALARM_TEST (alarm_pos++ >= alarm_end_pos) #define ALARM_REINIT (alarm_end_pos+=MY_HOW_OFTEN_TO_WRITE) #endif /* HAVE_ALARM */ #ifdef __cplusplus } #endif #endif mysql/server/private/key.h000064400000004124151027430560011636 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef KEY_INCLUDED #define KEY_INCLUDED class Field; class String; struct TABLE; typedef struct st_bitmap MY_BITMAP; typedef struct st_key KEY; typedef struct st_key_part_info KEY_PART_INFO; int find_ref_key(KEY *key, uint key_count, uchar *record, Field *field, uint *key_length, uint *keypart); void key_copy(uchar *to_key, const uchar *from_record, const KEY *key_info, uint key_length, bool with_zerofill= FALSE); void key_restore(uchar *to_record, const uchar *from_key, KEY *key_info, uint key_length); bool key_cmp_if_same(TABLE *form,const uchar *key,uint index,uint key_length); void key_unpack(String *to, TABLE *table, KEY *key); void field_unpack(String *to, Field *field, const uchar *rec, uint max_length, bool prefix_key); bool is_key_used(TABLE *table, uint idx, const MY_BITMAP *fields); int key_cmp(KEY_PART_INFO *key_part, const uchar *key, uint key_length); ulong key_hashnr(KEY *key_info, uint used_key_parts, const uchar *key); bool key_buf_cmp(KEY *key_info, uint used_key_parts, const uchar *key1, const uchar *key2); extern "C" int key_rec_cmp(const KEY *const *key_info, const uchar *a, const uchar *b); int key_tuple_cmp(KEY_PART_INFO *part, const uchar *key1, const uchar *key2, uint tuple_length); #endif /* KEY_INCLUDED */ mysql/server/private/sql_acl.h000064400000033464151027430560012475 0ustar00#ifndef SQL_ACL_INCLUDED #define SQL_ACL_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "violite.h" /* SSL_type */ #include "sql_class.h" /* LEX_COLUMN */ #include "grant.h" #include "sql_cmd.h" /* Sql_cmd */ enum mysql_db_table_field { MYSQL_DB_FIELD_HOST = 0, MYSQL_DB_FIELD_DB, MYSQL_DB_FIELD_USER, MYSQL_DB_FIELD_SELECT_PRIV, MYSQL_DB_FIELD_INSERT_PRIV, MYSQL_DB_FIELD_UPDATE_PRIV, MYSQL_DB_FIELD_DELETE_PRIV, MYSQL_DB_FIELD_CREATE_PRIV, MYSQL_DB_FIELD_DROP_PRIV, MYSQL_DB_FIELD_GRANT_PRIV, MYSQL_DB_FIELD_REFERENCES_PRIV, MYSQL_DB_FIELD_INDEX_PRIV, MYSQL_DB_FIELD_ALTER_PRIV, MYSQL_DB_FIELD_CREATE_TMP_TABLE_PRIV, MYSQL_DB_FIELD_LOCK_TABLES_PRIV, MYSQL_DB_FIELD_CREATE_VIEW_PRIV, MYSQL_DB_FIELD_SHOW_VIEW_PRIV, MYSQL_DB_FIELD_CREATE_ROUTINE_PRIV, MYSQL_DB_FIELD_ALTER_ROUTINE_PRIV, MYSQL_DB_FIELD_EXECUTE_PRIV, MYSQL_DB_FIELD_EVENT_PRIV, MYSQL_DB_FIELD_TRIGGER_PRIV, MYSQL_DB_FIELD_DELETE_VERSIONING_ROWS_PRIV, MYSQL_DB_FIELD_COUNT }; extern const TABLE_FIELD_DEF mysql_db_table_def; extern bool mysql_user_table_is_in_short_password_format; extern LEX_CSTRING host_not_specified; extern LEX_CSTRING current_user; extern LEX_CSTRING current_role; extern LEX_CSTRING current_user_and_current_role; static inline int access_denied_error_code(int passwd_used) { #ifdef mysqld_error_find_printf_error_used return 0; #else return passwd_used == 2 ? ER_ACCESS_DENIED_NO_PASSWORD_ERROR : ER_ACCESS_DENIED_ERROR; #endif } /* prototypes */ bool hostname_requires_resolving(const char *hostname); bool acl_init(bool dont_read_acl_tables); bool acl_reload(THD *thd); void acl_free(bool end=0); privilege_t acl_get(const char *host, const char *ip, const char *user, const char *db, my_bool db_is_pattern); bool acl_authenticate(THD *thd, uint com_change_user_pkt_len); bool acl_getroot(Security_context *sctx, const char *user, const char *host, const char *ip, const char *db); bool acl_check_host(const char *host, const char *ip); bool check_change_password(THD *thd, LEX_USER *user); bool change_password(THD *thd, LEX_USER *user); bool mysql_grant_role(THD *thd, List &user_list, bool revoke); bool mysql_grant(THD *thd, const char *db, List &user_list, privilege_t rights, bool revoke, bool is_proxy); int mysql_table_grant(THD *thd, TABLE_LIST *table, List &user_list, List &column_list, privilege_t rights, bool revoke); bool mysql_routine_grant(THD *thd, TABLE_LIST *table, const Sp_handler *sph, List &user_list, privilege_t rights, bool revoke, bool write_to_binlog); bool grant_init(); void grant_free(void); bool grant_reload(THD *thd); bool check_grant(THD *thd, privilege_t want_access, TABLE_LIST *tables, bool any_combination_will_do, uint number, bool no_errors); bool check_grant_column (THD *thd, GRANT_INFO *grant, const char *db_name, const char *table_name, const char *name, size_t length, Security_context *sctx); bool check_column_grant_in_table_ref(THD *thd, TABLE_LIST * table_ref, const char *name, size_t length, Field *fld); bool check_grant_all_columns(THD *thd, privilege_t want_access, Field_iterator_table_ref *fields); bool check_grant_routine(THD *thd, privilege_t want_access, TABLE_LIST *procs, const Sp_handler *sph, bool no_error); bool check_grant_db(THD *thd,const char *db); bool check_global_access(THD *thd, const privilege_t want_access, bool no_errors= false); bool check_access(THD *thd, privilege_t want_access, const char *db, privilege_t *save_priv, GRANT_INTERNAL_INFO *grant_internal_info, bool dont_check_global_grants, bool no_errors); privilege_t get_table_grant(THD *thd, TABLE_LIST *table); privilege_t get_column_grant(THD *thd, GRANT_INFO *grant, const char *db_name, const char *table_name, const char *field_name); bool get_show_user(THD *thd, LEX_USER *lex_user, const char **username, const char **hostname, const char **rolename); void mysql_show_grants_get_fields(THD *thd, List *fields, const char *name, size_t length); bool mysql_show_grants(THD *thd, LEX_USER *user); bool mysql_show_create_user(THD *thd, LEX_USER *user); int fill_schema_enabled_roles(THD *thd, TABLE_LIST *tables, COND *cond); int fill_schema_applicable_roles(THD *thd, TABLE_LIST *tables, COND *cond); void get_privilege_desc(char *to, uint max_length, privilege_t access); void get_mqh(const char *user, const char *host, USER_CONN *uc); bool mysql_create_user(THD *thd, List &list, bool handle_as_role); bool mysql_drop_user(THD *thd, List &list, bool handle_as_role); bool mysql_rename_user(THD *thd, List &list); int mysql_alter_user(THD *thd, List &list); bool mysql_revoke_all(THD *thd, List &list); void fill_effective_table_privileges(THD *thd, GRANT_INFO *grant, const char *db, const char *table); bool sp_revoke_privileges(THD *thd, const char *sp_db, const char *sp_name, const Sp_handler *sph); bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name, const Sp_handler *sph); bool check_routine_level_acl(THD *thd, const char *db, const char *name, const Sp_handler *sph); bool is_acl_user(const char *host, const char *user); int fill_schema_user_privileges(THD *thd, TABLE_LIST *tables, COND *cond); int fill_schema_schema_privileges(THD *thd, TABLE_LIST *tables, COND *cond); int fill_schema_table_privileges(THD *thd, TABLE_LIST *tables, COND *cond); int fill_schema_column_privileges(THD *thd, TABLE_LIST *tables, COND *cond); int wild_case_compare(CHARSET_INFO *cs, const char *str,const char *wildstr); /** Result of an access check for an internal schema or table. Internal ACL checks are always performed *before* using the grant tables. This mechanism enforces that the server implementation has full control on its internal tables. Depending on the internal check result, the server implementation can choose to: - always allow access, - always deny access, - delegate the decision to the database administrator, by using the grant tables. */ enum ACL_internal_access_result { /** Access granted for all the requested privileges, do not use the grant tables. */ ACL_INTERNAL_ACCESS_GRANTED, /** Access denied, do not use the grant tables. */ ACL_INTERNAL_ACCESS_DENIED, /** No decision yet, use the grant tables. */ ACL_INTERNAL_ACCESS_CHECK_GRANT }; /** Per internal table ACL access rules. This class is an interface. Per table(s) specific access rule should be implemented in a subclass. @sa ACL_internal_schema_access */ class ACL_internal_table_access { public: ACL_internal_table_access() = default; virtual ~ACL_internal_table_access() = default; /** Check access to an internal table. When a privilege is granted, this method add the requested privilege to save_priv. @param want_access the privileges requested @param [in, out] save_priv the privileges granted @return @retval ACL_INTERNAL_ACCESS_GRANTED All the requested privileges are granted, and saved in save_priv. @retval ACL_INTERNAL_ACCESS_DENIED At least one of the requested privileges was denied. @retval ACL_INTERNAL_ACCESS_CHECK_GRANT No requested privilege was denied, and grant should be checked for at least one privilege. Requested privileges that are granted, if any, are saved in save_priv. */ virtual ACL_internal_access_result check(privilege_t want_access, privilege_t *save_priv, bool any_combination_will_do) const= 0; }; /** Per internal schema ACL access rules. This class is an interface. Each per schema specific access rule should be implemented in a different subclass, and registered. Per schema access rules can control: - every schema privileges on schema.* - every table privileges on schema.table @sa ACL_internal_schema_registry */ class ACL_internal_schema_access { public: ACL_internal_schema_access() = default; virtual ~ACL_internal_schema_access() = default; /** Check access to an internal schema. @param want_access the privileges requested @param [in, out] save_priv the privileges granted @return @retval ACL_INTERNAL_ACCESS_GRANTED All the requested privileges are granted, and saved in save_priv. @retval ACL_INTERNAL_ACCESS_DENIED At least one of the requested privileges was denied. @retval ACL_INTERNAL_ACCESS_CHECK_GRANT No requested privilege was denied, and grant should be checked for at least one privilege. Requested privileges that are granted, if any, are saved in save_priv. */ virtual ACL_internal_access_result check(privilege_t want_access, privilege_t *save_priv) const= 0; /** Search for per table ACL access rules by table name. @param name the table name @return per table access rules, or NULL */ virtual const ACL_internal_table_access *lookup(const char *name) const= 0; }; /** A registry for per internal schema ACL. An 'internal schema' is a database schema maintained by the server implementation, such as 'performance_schema' and 'INFORMATION_SCHEMA'. */ class ACL_internal_schema_registry { public: static void register_schema(const LEX_CSTRING *name, const ACL_internal_schema_access *access); static const ACL_internal_schema_access *lookup(const char *name); }; const ACL_internal_schema_access * get_cached_schema_access(GRANT_INTERNAL_INFO *grant_internal_info, const char *schema_name); const ACL_internal_table_access * get_cached_table_access(GRANT_INTERNAL_INFO *grant_internal_info, const char *schema_name, const char *table_name); bool acl_check_proxy_grant_access (THD *thd, const char *host, const char *user, bool with_grant); int acl_setrole(THD *thd, const char *rolename, privilege_t access); int acl_check_setrole(THD *thd, const char *rolename, privilege_t *access); int acl_check_set_default_role(THD *thd, const char *host, const char *user, const char *role); int acl_set_default_role(THD *thd, const char *host, const char *user, const char *rolename); extern SHOW_VAR acl_statistics[]; /* Check if a role is granted to a user/role. If hostname == NULL, search for a role as the starting grantee. */ bool check_role_is_granted(const char *username, const char *hostname, const char *rolename); #ifndef DBUG_OFF extern ulong role_global_merges, role_db_merges, role_table_merges, role_column_merges, role_routine_merges; #endif class Sql_cmd_grant: public Sql_cmd { protected: enum_sql_command m_command; #ifndef NO_EMBEDDED_ACCESS_CHECKS void warn_hostname_requires_resolving(THD *thd, List &list); bool user_list_reset_mqh(THD *thd, List &list); void grant_stage0(THD *thd); #endif public: Sql_cmd_grant(enum_sql_command command) :m_command(command) { } bool is_revoke() const { return m_command == SQLCOM_REVOKE; } enum_sql_command sql_command_code() const override { return m_command; } }; class Sql_cmd_grant_proxy: public Sql_cmd_grant { privilege_t m_grant_option; #ifndef NO_EMBEDDED_ACCESS_CHECKS bool check_access_proxy(THD *thd, List &list); #endif public: Sql_cmd_grant_proxy(enum_sql_command command, privilege_t grant_option) :Sql_cmd_grant(command), m_grant_option(grant_option) { } bool execute(THD *thd) override; }; class Sql_cmd_grant_object: public Sql_cmd_grant, public Grant_privilege { protected: #ifndef NO_EMBEDDED_ACCESS_CHECKS bool grant_stage0_exact_object(THD *thd, TABLE_LIST *table); #endif public: Sql_cmd_grant_object(enum_sql_command command, const Grant_privilege &grant) :Sql_cmd_grant(command), Grant_privilege(grant) { } }; class Sql_cmd_grant_table: public Sql_cmd_grant_object { #ifndef NO_EMBEDDED_ACCESS_CHECKS bool execute_table_mask(THD *thd); bool execute_exact_table(THD *thd, TABLE_LIST *table); #endif public: Sql_cmd_grant_table(enum_sql_command command, const Grant_privilege &grant) :Sql_cmd_grant_object(command, grant) { } bool execute(THD *thd) override; }; class Sql_cmd_grant_sp: public Sql_cmd_grant_object { const Sp_handler &m_sph; public: Sql_cmd_grant_sp(enum_sql_command command, const Grant_privilege &grant, const Sp_handler &sph) :Sql_cmd_grant_object(command, grant), m_sph(sph) { } bool execute(THD *thd) override; }; #endif /* SQL_ACL_INCLUDED */ mysql/server/private/wsrep_storage_service.h000064400000003421151027430560015451 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_STORAGE_SERVICE_H #define WSREP_STORAGE_SERVICE_H #include "wsrep/storage_service.hpp" #include "wsrep/client_state.hpp" class THD; class Wsrep_server_service; class Wsrep_storage_service : public wsrep::storage_service, public wsrep::high_priority_context { public: Wsrep_storage_service(THD*); ~Wsrep_storage_service(); int start_transaction(const wsrep::ws_handle&) override; void adopt_transaction(const wsrep::transaction&) override; int append_fragment(const wsrep::id&, wsrep::transaction_id, int flags, const wsrep::const_buffer&, const wsrep::xid&) override; int update_fragment_meta(const wsrep::ws_meta&) override; int remove_fragments() override; int commit(const wsrep::ws_handle&, const wsrep::ws_meta&) override; int rollback(const wsrep::ws_handle&, const wsrep::ws_meta&) override; void store_globals() override; void reset_globals() override; private: friend class Wsrep_server_service; THD* m_thd; }; #endif /* WSREP_STORAGE_SERVICE_H */ mysql/server/private/derived_handler.h000064400000004513151027430560014167 0ustar00/* Copyright (c) 2016, 2017 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DERIVED_HANDLER_INCLUDED #define DERIVED_HANDLER_INCLUDED #include "mariadb.h" #include "sql_priv.h" class TMP_TABLE_PARAM; typedef class st_select_lex_unit SELECT_LEX_UNIT; /** @class derived_handler This interface class is to be used for execution of queries that specify derived table by foreign engines */ class derived_handler { public: THD *thd; handlerton *ht; TABLE_LIST *derived; /* Temporary table where all results should be stored in record[0] The table has a field for every item from the select list of the specification of derived. */ TABLE *table; /* The parameters if the temporary table used at its creation */ TMP_TABLE_PARAM *tmp_table_param; SELECT_LEX_UNIT *unit; // Specifies the derived table SELECT_LEX *select; // The first select of the specification derived_handler(THD *thd_arg, handlerton *ht_arg) : thd(thd_arg), ht(ht_arg), derived(0),table(0), tmp_table_param(0), unit(0), select(0) {} virtual ~derived_handler() = default; /* Functions to scan data. All these returns 0 if ok, error code in case of error */ /* Initialize the process of producing rows of the derived table */ virtual int init_scan()= 0; /* Put the next produced row of the derived in table->record[0] and return 0. Return HA_ERR_END_OF_FILE if there are no more rows, return other error number in case of fatal error. */ virtual int next_row()= 0; /* End prodicing rows */ virtual int end_scan()=0; /* Report errors */ virtual void print_error(int error, myf errflag); void set_derived(TABLE_LIST *tbl); }; #endif /* DERIVED_HANDLER_INCLUDED */ mysql/server/private/event_db_repository.h000064400000007100151027430560015130 0ustar00#ifndef _EVENT_DB_REPOSITORY_H_ #define _EVENT_DB_REPOSITORY_H_ /* Copyright (c) 2006, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @addtogroup Event_Scheduler @{ @file event_db_repository.h Data Dictionary related operations of Event Scheduler. This is a private header file of Events module. Please do not include it directly. All public declarations of Events module should be stored in events.h and event_data_objects.h. */ enum enum_events_table_field { ET_FIELD_DB = 0, ET_FIELD_NAME, ET_FIELD_BODY, ET_FIELD_DEFINER, ET_FIELD_EXECUTE_AT, ET_FIELD_INTERVAL_EXPR, ET_FIELD_TRANSIENT_INTERVAL, ET_FIELD_CREATED, ET_FIELD_MODIFIED, ET_FIELD_LAST_EXECUTED, ET_FIELD_STARTS, ET_FIELD_ENDS, ET_FIELD_STATUS, ET_FIELD_ON_COMPLETION, ET_FIELD_SQL_MODE, ET_FIELD_COMMENT, ET_FIELD_ORIGINATOR, ET_FIELD_TIME_ZONE, ET_FIELD_CHARACTER_SET_CLIENT, ET_FIELD_COLLATION_CONNECTION, ET_FIELD_DB_COLLATION, ET_FIELD_BODY_UTF8, ET_FIELD_COUNT /* a cool trick to count the number of fields :) */ }; int events_table_index_read_for_db(THD *thd, TABLE *schema_table, TABLE *event_table); int events_table_scan_all(THD *thd, TABLE *schema_table, TABLE *event_table); class Event_basic; class Event_parse_data; class Event_db_repository { public: Event_db_repository() = default; bool create_event(THD *thd, Event_parse_data *parse_data, bool *event_already_exists); bool update_event(THD *thd, Event_parse_data *parse_data, LEX_CSTRING *new_dbname, LEX_CSTRING *new_name); bool drop_event(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *name, bool drop_if_exists); void drop_schema_events(THD *thd, const LEX_CSTRING *schema); bool find_named_event(const LEX_CSTRING *db, const LEX_CSTRING *name, TABLE *table); bool load_named_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name, Event_basic *et); static bool open_event_table(THD *thd, enum thr_lock_type lock_type, TABLE **table); bool fill_schema_events(THD *thd, TABLE_LIST *tables, const char *db); bool update_timing_fields_for_event(THD *thd, const LEX_CSTRING *event_db_name, const LEX_CSTRING *event_name, my_time_t last_executed, ulonglong status); public: static bool check_system_tables(THD *thd); private: bool index_read_for_db_for_i_s(THD *thd, TABLE *schema_table, TABLE *event_table, const char *db); bool table_scan_all_for_i_s(THD *thd, TABLE *schema_table, TABLE *event_table); private: /* Prevent use of these */ Event_db_repository(const Event_db_repository &); void operator=(Event_db_repository &); }; /** @} (End of group Event_Scheduler) */ #endif /* _EVENT_DB_REPOSITORY_H_ */ mysql/server/private/rpl_rli.h000064400000077752151027430560012532 0ustar00/* Copyright (c) 2005, 2017, Oracle and/or its affiliates. Copyright (c) 2009, 2017, MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_RLI_H #define RPL_RLI_H #include "rpl_tblmap.h" #include "rpl_reporting.h" #include "rpl_utility.h" #include "log.h" /* LOG_INFO, MYSQL_BIN_LOG */ #include "sql_class.h" /* THD */ #include "log_event.h" #include "rpl_parallel.h" struct RPL_TABLE_LIST; class Master_info; class Rpl_filter; /**************************************************************************** Replication SQL Thread Relay_log_info contains: - the current relay log - the current relay log offset - master log name - master log sequence corresponding to the last update - misc information specific to the SQL thread Relay_log_info is initialized from the slave.info file if such exists. Otherwise, data members are intialized with defaults. The initialization is done with Relay_log_info::init() call. The format of slave.info file: relay_log_name relay_log_pos master_log_name master_log_pos To clean up, call end_relay_log_info() *****************************************************************************/ struct rpl_group_info; struct inuse_relaylog; class Relay_log_info : public Slave_reporting_capability { public: /** Flags for the state of reading the relay log. Note that these are bit masks. */ enum enum_state_flag { /** We are inside a group of events forming a statement */ IN_STMT=1, /** We have inside a transaction */ IN_TRANSACTION=2 }; /* The SQL thread owns one Relay_log_info, and each client that has executed a BINLOG statement owns one Relay_log_info. This function returns zero for the Relay_log_info object that belongs to the SQL thread and nonzero for Relay_log_info objects that belong to clients. */ inline bool belongs_to_client() { DBUG_ASSERT(sql_driver_thd); return !sql_driver_thd->slave_thread; } /* If true, events with the same server id should be replicated. This field is set on creation of a relay log info structure by copying the value of ::replicate_same_server_id and can be overridden if necessary. For example of when this is done, check sql_binlog.cc, where the BINLOG statement can be used to execute "raw" events. */ bool replicate_same_server_id; /*** The following variables can only be read when protect by data lock ****/ /* info_fd - file descriptor of the info file. set only during initialization or clean up - safe to read anytime cur_log_fd - file descriptor of the current read relay log */ File info_fd,cur_log_fd; /* Protected with internal locks. Must get data_lock when resetting the logs. */ MYSQL_BIN_LOG relay_log; LOG_INFO linfo; /* cur_log Pointer that either points at relay_log.get_log_file() or &rli->cache_buf, depending on whether the log is hot or there was the need to open a cold relay_log. cache_buf IO_CACHE used when opening cold relay logs. */ IO_CACHE cache_buf,*cur_log; /* Keeps track of the number of transactions that commits before fsyncing. The option --sync-relay-log-info determines how many transactions should commit before fsyncing. */ uint sync_counter; /* Identifies when the recovery process is going on. See sql/slave.cc:init_recovery for further details. */ bool is_relay_log_recovery; /* The following variables are safe to read any time */ /* IO_CACHE of the info file - set only during init or end */ IO_CACHE info_file; /* List of temporary tables used by this connection. This is updated when a temporary table is created or dropped by a replication thread. Not reset when replication ends, to allow one to access the tables when replication restarts. Protected by data_lock. */ All_tmp_tables_list *save_temporary_tables; /* standard lock acquisition order to avoid deadlocks: run_lock, data_lock, relay_log.LOCK_log, relay_log.LOCK_index */ mysql_mutex_t data_lock, run_lock; /* start_cond is broadcast when SQL thread is started stop_cond - when stopped data_cond - when data protected by data_lock changes */ mysql_cond_t start_cond, stop_cond, data_cond; /* parent Master_info structure */ Master_info *mi; /* List of active relay log files. (This can be more than one in case of parallel replication). */ inuse_relaylog *inuse_relaylog_list; inuse_relaylog *last_inuse_relaylog; /* Needed to deal properly with cur_log getting closed and re-opened with a different log under our feet */ uint32 cur_log_old_open_count; /* If on init_info() call error_on_rli_init_info is true that means that previous call to init_info() terminated with an error, RESET SLAVE must be executed and the problem fixed manually. */ bool error_on_rli_init_info; /* Let's call a group (of events) : - a transaction or - an autocommiting query + its associated events (INSERT_ID, TIMESTAMP...) We need these rli coordinates : - relay log name and position of the beginning of the group we currently are executing. Needed to know where we have to restart when replication has stopped in the middle of a group (which has been rolled back by the slave). - relay log name and position just after the event we have just executed. This event is part of the current group. Formerly we only had the immediately above coordinates, plus a 'pending' variable, but this dealt wrong with the case of a transaction starting on a relay log and finishing (commiting) on another relay log. Case which can happen when, for example, the relay log gets rotated because of max_binlog_size. Note: group_relay_log_name, group_relay_log_pos must only be written from the thread owning the Relay_log_info (SQL thread if !belongs_to_client(); client thread executing BINLOG statement if belongs_to_client()). */ char group_relay_log_name[FN_REFLEN]; ulonglong group_relay_log_pos; char event_relay_log_name[FN_REFLEN]; ulonglong event_relay_log_pos; ulonglong future_event_relay_log_pos; /* The master log name for current event. Only used in parallel replication. */ char future_event_master_log_name[FN_REFLEN]; /* Original log name and position of the group we're currently executing (whose coordinates are group_relay_log_name/pos in the relay log) in the master's binlog. These concern the *group*, because in the master's binlog the log_pos that comes with each event is the position of the beginning of the group. Note: group_master_log_name, group_master_log_pos must only be written from the thread owning the Relay_log_info (SQL thread if !belongs_to_client(); client thread executing BINLOG statement if belongs_to_client()). */ char group_master_log_name[FN_REFLEN]; volatile my_off_t group_master_log_pos; /* Handling of the relay_log_space_limit optional constraint. ignore_log_space_limit is used to resolve a deadlock between I/O and SQL threads, the SQL thread sets it to unblock the I/O thread and make it temporarily forget about the constraint. */ ulonglong log_space_limit; Atomic_counter log_space_total; bool ignore_log_space_limit; /* Used by the SQL thread to instructs the IO thread to rotate the logs when the SQL thread needs to purge to release some disk space. */ bool sql_force_rotate_relay; time_t last_master_timestamp; /* The SQL driver thread sets this true while it is waiting at the end of the relay log for more events to arrive. SHOW SLAVE STATUS uses this to report Seconds_Behind_Master as zero while the SQL thread is so waiting. */ bool sql_thread_caught_up; void clear_until_condition(); /** Reset the delay. This is used by RESET SLAVE to clear the delay. */ void clear_sql_delay() { sql_delay= 0; } /* Needed for problems when slave stops and we want to restart it skipping one or more events in the master log that have caused errors, and have been manually applied by DBA already. Must be ulong as it's referred to from set_var.cc */ volatile ulonglong slave_skip_counter; ulonglong max_relay_log_size; volatile ulong abort_pos_wait; /* Incremented on change master */ volatile ulong slave_run_id; /* Incremented on slave start */ mysql_mutex_t log_space_lock; mysql_cond_t log_space_cond; /* THD for the main sql thread, the one that starts threads to process slave requests. If there is only one thread, then this THD is also used for SQL processing. A kill sent to this THD will kill the replication. */ THD *sql_driver_thd; #ifndef DBUG_OFF int events_till_abort; #endif enum_gtid_skip_type gtid_skip_flag; /* inited changes its value within LOCK_active_mi-guarded critical sections at times of start_slave_threads() (0->1) and end_slave() (1->0). Readers may not acquire the mutex while they realize potential concurrency issue. If not set, the value of other members of the structure are undefined. */ volatile bool inited; volatile bool abort_slave; volatile bool stop_for_until; volatile uint slave_running; /* Condition and its parameters from START SLAVE UNTIL clause. UNTIL condition is tested with is_until_satisfied() method that is called by exec_relay_log_event(). is_until_satisfied() caches the result of the comparison of log names because log names don't change very often; this cache is invalidated by parts of code which change log names with notify_*_log_name_updated() methods. (They need to be called only if SQL thread is running). */ enum { UNTIL_NONE= 0, UNTIL_MASTER_POS, UNTIL_RELAY_POS, UNTIL_GTID } until_condition; char until_log_name[FN_REFLEN]; ulonglong until_log_pos; /* extension extracted from log_name and converted to int */ ulong until_log_name_extension; /* Cached result of comparison of until_log_name and current log name -2 means unitialised, -1,0,1 are comarison results */ enum { UNTIL_LOG_NAMES_CMP_UNKNOWN= -2, UNTIL_LOG_NAMES_CMP_LESS= -1, UNTIL_LOG_NAMES_CMP_EQUAL= 0, UNTIL_LOG_NAMES_CMP_GREATER= 1 } until_log_names_cmp_result; /* Condition for UNTIL master_gtid_pos. */ slave_connection_state until_gtid_pos; /* retried_trans is a cumulative counter: how many times the slave has retried a transaction (any) since slave started. Protected by data_lock. */ ulong retried_trans; /* Number of executed events for SLAVE STATUS. Protected by slave_executed_entries_lock */ Atomic_counter executed_entries; /* If the end of the hot relay log is made of master's events ignored by the slave I/O thread, these two keep track of the coords (in the master's binlog) of the last of these events seen by the slave I/O thread. If not, ign_master_log_name_end[0] == 0. As they are like a Rotate event read/written from/to the relay log, they are both protected by rli->relay_log.LOCK_log. */ char ign_master_log_name_end[FN_REFLEN]; ulonglong ign_master_log_pos_end; /* Similar for ignored GTID events. */ slave_connection_state ign_gtids; /* Indentifies where the SQL Thread should create temporary files for the LOAD DATA INFILE. This is used for security reasons. */ char slave_patternload_file[FN_REFLEN]; size_t slave_patternload_file_size; rpl_parallel parallel; /* The relay_log_state keeps track of the current binlog state of the execution of the relay log. This is used to know where to resume current GTID position if the slave thread is stopped and restarted. It is only accessed from the SQL thread, so it does not need any locking. */ rpl_binlog_state relay_log_state; /* The restart_gtid_state is used when the SQL thread restarts on a relay log in GTID mode. In multi-domain parallel replication, each domain may have a separat position, so some events in more progressed domains may need to be skipped. This keeps track of the domains that have not yet reached their starting event. */ slave_connection_state restart_gtid_pos; Relay_log_info(bool is_slave_recovery, const char* thread_name= "SQL"); ~Relay_log_info(); /* Invalidate cached until_log_name and group_relay_log_name comparison result. Should be called after any update of group_realy_log_name if there chances that sql_thread is running. */ inline void notify_group_relay_log_name_update() { if (until_condition==UNTIL_RELAY_POS) until_log_names_cmp_result= UNTIL_LOG_NAMES_CMP_UNKNOWN; } /* The same as previous but for group_master_log_name. */ inline void notify_group_master_log_name_update() { if (until_condition==UNTIL_MASTER_POS) until_log_names_cmp_result= UNTIL_LOG_NAMES_CMP_UNKNOWN; } void inc_group_relay_log_pos(ulonglong log_pos, rpl_group_info *rgi, bool skip_lock=0); int wait_for_pos(THD* thd, String* log_name, longlong log_pos, longlong timeout); void close_temporary_tables(); /* Check if UNTIL condition is satisfied. See slave.cc for more. */ bool is_until_satisfied(Log_event *ev); inline ulonglong until_pos() { DBUG_ASSERT(until_condition == UNTIL_MASTER_POS || until_condition == UNTIL_RELAY_POS); return ((until_condition == UNTIL_MASTER_POS) ? group_master_log_pos : group_relay_log_pos); } inline char *until_name() { DBUG_ASSERT(until_condition == UNTIL_MASTER_POS || until_condition == UNTIL_RELAY_POS); return ((until_condition == UNTIL_MASTER_POS) ? group_master_log_name : group_relay_log_name); } /** Helper function to do after statement completion. This function is called from an event to complete the group by either stepping the group position, if the "statement" is not inside a transaction; or increase the event position, if the "statement" is inside a transaction. @param event_log_pos Master log position of the event. The position is recorded in the relay log info and used to produce information for SHOW SLAVE STATUS. */ bool stmt_done(my_off_t event_log_pos, THD *thd, rpl_group_info *rgi); int alloc_inuse_relaylog(const char *name); void free_inuse_relaylog(inuse_relaylog *ir); void reset_inuse_relaylog(); int update_relay_log_state(rpl_gtid *gtid_list, uint32 count); /** Is the replication inside a group? The reader of the relay log is inside a group if either: - The IN_TRANSACTION flag is set, meaning we're inside a transaction - The IN_STMT flag is set, meaning we have read at least one row from a multi-event entry. This flag reflects the state of the log 'just now', ie after the last read event would be executed. This allow us to test if we can stop replication before reading the next entry. @retval true Replication thread is currently inside a group @retval false Replication thread is currently not inside a group */ bool is_in_group() const { return (m_flags & (IN_STMT | IN_TRANSACTION)); } /** Set the value of a replication state flag. @param flag Flag to set */ void set_flag(enum_state_flag flag) { m_flags|= flag; } /** Get the value of a replication state flag. @param flag Flag to get value of @return @c true if the flag was set, @c false otherwise. */ bool get_flag(enum_state_flag flag) { return m_flags & flag; } /** Clear the value of a replication state flag. @param flag Flag to clear */ void clear_flag(enum_state_flag flag) { m_flags&= ~flag; } bool flush(); /** Reads the relay_log.info file. */ int init(const char* info_filename); /** Indicate that a delay starts. This does not actually sleep; it only sets the state of this Relay_log_info object to delaying so that the correct state can be reported by SHOW SLAVE STATUS and SHOW PROCESSLIST. Requires rli->data_lock. @param delay_end The time when the delay shall end. */ void start_sql_delay(time_t delay_end) { mysql_mutex_assert_owner(&data_lock); sql_delay_end= delay_end; THD_STAGE_INFO(sql_driver_thd, stage_sql_thd_waiting_until_delay); } int32 get_sql_delay() { return sql_delay; } void set_sql_delay(int32 _sql_delay) { sql_delay= _sql_delay; } time_t get_sql_delay_end() { return sql_delay_end; } rpl_gtid last_seen_gtid; ulong last_trans_retry_count; private: /** Delay slave SQL thread by this amount, compared to master (in seconds). This is set with CHANGE MASTER TO MASTER_DELAY=X. Guarded by data_lock. Initialized by the client thread executing START SLAVE. Written by client threads executing CHANGE MASTER TO MASTER_DELAY=X. Read by SQL thread and by client threads executing SHOW SLAVE STATUS. Note: must not be written while the slave SQL thread is running, since the SQL thread reads it without a lock when executing Relay_log_info::flush(). */ int sql_delay; /** During a delay, specifies the point in time when the delay ends. This is used for the SQL_Remaining_Delay column in SHOW SLAVE STATUS. Guarded by data_lock. Written by the sql thread. Read by client threads executing SHOW SLAVE STATUS. This is calculated as: clock_time_for_event_on_master + clock_difference_between_master_and_slave + SQL_DELAY. */ time_t sql_delay_end; /* Before the MASTER_DELAY parameter was added (WL#344), relay_log.info had 4 lines. Now it has 5 lines. */ static const int LINES_IN_RELAY_LOG_INFO_WITH_DELAY= 5; /* Hint for when to stop event distribution by sql driver thread. The flag is set ON by a non-group event when this event is in the middle of a group (e.g a transaction group) so it's too early to refresh the current-relay-log vs until-log cached comparison result. And it is checked and to decide whether it's a right time to do so when the being processed group has been fully scheduled. */ bool until_relay_log_names_defer; /* Holds the state of the data in the relay log. We need this to ensure that we are not in the middle of a statement or inside BEGIN ... COMMIT when should rotate the relay log. */ uint32 m_flags; }; /* In parallel replication, if we need to re-try a transaction due to a deadlock or other temporary error, we may need to go back and re-read events out of an earlier relay log. This structure keeps track of the relaylogs that are potentially in use. Each rpl_group_info has a pointer to one of those, corresponding to the first GTID event. A pair of reference count keeps track of how long a relay log is potentially in use. When the `completed' flag is set, all events have been read out of the relay log, but the log might still be needed for retry in worker threads. As worker threads complete an event group, they increment atomically the `dequeued_count' with number of events queued. Thus, when completed is set and dequeued_count equals queued_count, the relay log file is finally done with and can be purged. By separating the queued and dequeued count, only the dequeued_count needs multi-thread synchronisation; the completed flag and queued_count fields are only accessed by the SQL driver thread and need no synchronisation. */ struct inuse_relaylog { inuse_relaylog *next; Relay_log_info *rli; /* relay_log_state holds the binlog state corresponding to the start of this relay log file. It is an array with relay_log_state_count elements. */ rpl_gtid *relay_log_state; uint32 relay_log_state_count; /* Number of events in this relay log queued for worker threads. */ Atomic_counter queued_count; /* Number of events completed by worker threads. */ Atomic_counter dequeued_count; /* Set when all events have been read from a relaylog. */ bool completed; char name[FN_REFLEN]; inuse_relaylog(Relay_log_info *rli_arg, rpl_gtid *relay_log_state_arg, uint32 relay_log_state_count_arg, const char *name_arg): next(0), rli(rli_arg), relay_log_state(relay_log_state_arg), relay_log_state_count(relay_log_state_count_arg), queued_count(0), dequeued_count(0), completed(false) { strmake_buf(name, name_arg); } }; /* This is data for various state needed to be kept for the processing of one event group (transaction) during replication. In single-threaded replication, there will be one global rpl_group_info and one global Relay_log_info per master connection. They will be linked together. In parallel replication, there will be one rpl_group_info object for each running sql thread, each having their own thd. All rpl_group_info will share the same Relay_log_info. */ struct rpl_group_info { rpl_group_info *next; /* For free list in rpl_parallel_thread */ Relay_log_info *rli; THD *thd; /* Current GTID being processed. The sub_id gives the binlog order within one domain_id. A zero sub_id means that there is no active GTID. */ uint64 gtid_sub_id; rpl_gtid current_gtid; uint64 commit_id; /* This is used to keep transaction commit order. We will signal this when we commit, and can register it to wait for the commit_orderer of the previous commit to signal us. */ wait_for_commit commit_orderer; /* If non-zero, the sub_id of a prior event group whose commit we have to wait for before committing ourselves. Then wait_commit_group_info points to the event group to wait for. Before using this, rpl_parallel_entry::last_committed_sub_id should be compared against wait_commit_sub_id. Only if last_committed_sub_id is smaller than wait_commit_sub_id must the wait be done (otherwise the waited-for transaction is already committed, so we would otherwise wait for the wrong commit). */ uint64 wait_commit_sub_id; rpl_group_info *wait_commit_group_info; /* This holds a pointer to a struct that keeps track of the need to wait for the previous batch of event groups to reach the commit stage, before this batch can start to execute. (When we execute in parallel the transactions that group committed together on the master, we still need to wait for any prior transactions to have reached the commit stage). The pointed-to gco is only valid for as long as gtid_sub_id < parallel_entry->last_committed_sub_id. After that, it can be freed by another thread. */ group_commit_orderer *gco; struct rpl_parallel_entry *parallel_entry; /* A container to hold on Intvar-, Rand-, Uservar- log-events in case the slave is configured with table filtering rules. The withhold events are executed when their parent Query destiny is determined for execution as well. */ Deferred_log_events *deferred_events; /* State of the container: true stands for IRU events gathering, false does for execution, either deferred or direct. */ bool deferred_events_collecting; Annotate_rows_log_event *m_annotate_event; RPL_TABLE_LIST *tables_to_lock; /* RBR: Tables to lock */ uint tables_to_lock_count; /* RBR: Count of tables to lock */ table_mapping m_table_map; /* RBR: Mapping table-id to table */ mysql_mutex_t sleep_lock; mysql_cond_t sleep_cond; /* trans_retries varies between 0 to slave_transaction_retries and counts how many times the slave has retried the present transaction; gets reset to 0 when the transaction finally succeeds. */ ulong trans_retries; /* Used to defer stopping the SQL thread to give it a chance to finish up the current group of events. The timestamp is set and reset in @c sql_slave_killed(). */ time_t last_event_start_time; char *event_relay_log_name; char event_relay_log_name_buf[FN_REFLEN]; ulonglong event_relay_log_pos; ulonglong future_event_relay_log_pos; /* The master log name for current event. Only used in parallel replication. */ char future_event_master_log_name[FN_REFLEN]; bool is_parallel_exec; /* When gtid_pending is true, we have not yet done record_gtid(). */ bool gtid_pending; int worker_error; /* Set true when we signalled that we reach the commit phase. Used to avoid counting one event group twice. */ bool did_mark_start_commit; /* Copy of flags2 from GTID event. */ uchar gtid_ev_flags2; enum { GTID_DUPLICATE_NULL=0, GTID_DUPLICATE_IGNORE=1, GTID_DUPLICATE_OWNER=2 }; /* When --gtid-ignore-duplicates, this is set to one of the above three values: GTID_DUPLICATE_NULL - Not using --gtid-ignore-duplicates. GTID_DUPLICATE_IGNORE - This gtid already applied, skip the event group. GTID_DUPLICATE_OWNER - We are the current owner of the domain, and must apply the event group and then release the domain. */ uint8 gtid_ignore_duplicate_state; /* Runtime state for printing a note when slave is taking too long while processing a row event. */ longlong row_stmt_start_timestamp; bool long_find_row_note_printed; /* Needs room for "Gtid D-S-N\x00". */ char gtid_info_buf[5+10+1+10+1+20+1]; /* The timestamp, from the master, of the commit event. Used to do delayed update of rli->last_master_timestamp, for getting reasonable values out of Seconds_Behind_Master in SHOW SLAVE STATUS. */ time_t last_master_timestamp; /* Information to be able to re-try an event group in case of a deadlock or other temporary error. */ inuse_relaylog *relay_log; uint64 retry_start_offset; uint64 retry_event_count; /* If `speculation' is != SPECULATE_NO, then we are optimistically running this transaction in parallel, even though it might not be safe (there may be a conflict with a prior event group). In this case, a conflict can cause other errors than deadlocks (like duplicate key for example). So in case of _any_ error, we need to roll back and retry the event group. */ enum enum_speculation { /* This transaction was group-committed together on the master with the other transactions with which it is replicated in parallel. */ SPECULATE_NO, /* We will optimistically try to run this transaction in parallel with other transactions, even though it is not known to be conflict free. If we get a conflict, we will detect it as a deadlock, roll back and retry. */ SPECULATE_OPTIMISTIC, /* This transaction got a conflict during speculative parallel apply, or it was marked on the master as likely to cause a conflict or unsafe to speculate. So it will wait for the prior transaction to commit before starting to replicate. */ SPECULATE_WAIT } speculation; enum enum_retry_killed { RETRY_KILL_NONE = 0, RETRY_KILL_PENDING, RETRY_KILL_KILLED }; uchar killed_for_retry; rpl_group_info(Relay_log_info *rli_); ~rpl_group_info(); void reinit(Relay_log_info *rli); /* Returns true if the argument event resides in the containter; more specifically, the checking is done against the last added event. */ bool is_deferred_event(Log_event * ev) { return deferred_events_collecting ? deferred_events->is_last(ev) : false; }; /* The general cleanup that slave applier may need at the end of query. */ inline void cleanup_after_query() { if (deferred_events) deferred_events->rewind(); }; /* The general cleanup that slave applier may need at the end of session. */ void cleanup_after_session() { if (deferred_events) { delete deferred_events; deferred_events= NULL; } }; /** Save pointer to Annotate_rows event and switch on the binlog_annotate_row_events for this sql thread. To be called when sql thread receives an Annotate_rows event. */ inline void set_annotate_event(Annotate_rows_log_event *event) { DBUG_ASSERT(m_annotate_event == NULL); m_annotate_event= event; this->thd->variables.binlog_annotate_row_events= 1; } /** Returns pointer to the saved Annotate_rows event or NULL if there is no saved event. */ inline Annotate_rows_log_event* get_annotate_event() { return m_annotate_event; } /** Delete saved Annotate_rows event (if any) and switch off the binlog_annotate_row_events for this sql thread. To be called when sql thread has applied the last (i.e. with STMT_END_F flag) rbr event. */ inline void free_annotate_event() { if (m_annotate_event) { this->thd->variables.binlog_annotate_row_events= 0; delete m_annotate_event; m_annotate_event= 0; } } bool get_table_data(TABLE *table_arg, table_def **tabledef_var, TABLE **conv_table_var) const { DBUG_ASSERT(tabledef_var && conv_table_var); for (TABLE_LIST *ptr= tables_to_lock ; ptr != NULL ; ptr= ptr->next_global) if (ptr->table == table_arg) { *tabledef_var= &static_cast(ptr)->m_tabledef; *conv_table_var= static_cast(ptr)->m_conv_table; DBUG_PRINT("debug", ("Fetching table data for table %s.%s:" " tabledef: %p, conv_table: %p", table_arg->s->db.str, table_arg->s->table_name.str, *tabledef_var, *conv_table_var)); return true; } return false; } void clear_tables_to_lock(); void cleanup_context(THD *, bool, bool keep_domain_owner= false); void slave_close_thread_tables(THD *); void mark_start_commit_no_lock(); void mark_start_commit(); char *gtid_info(); void unmark_start_commit(); longlong get_row_stmt_start_timestamp() { return row_stmt_start_timestamp; } void set_row_stmt_start_timestamp() { if (row_stmt_start_timestamp == 0) row_stmt_start_timestamp= microsecond_interval_timer(); } void reset_row_stmt_start_timestamp() { row_stmt_start_timestamp= 0; } void set_long_find_row_note_printed() { long_find_row_note_printed= true; } void unset_long_find_row_note_printed() { long_find_row_note_printed= false; } bool is_long_find_row_note_printed() { return long_find_row_note_printed; } inline void inc_event_relay_log_pos() { if (!is_parallel_exec) rli->event_relay_log_pos= future_event_relay_log_pos; } }; /* The class rpl_sql_thread_info is the THD::system_thread_info for an SQL thread; this is either the driver SQL thread or a worker thread for parallel replication. */ class rpl_sql_thread_info { public: char cached_charset[6]; Rpl_filter* rpl_filter; rpl_sql_thread_info(Rpl_filter *filter); /* Last charset (6 bytes) seen by slave SQL thread is cached here; it helps the thread save 3 get_charset() per Query_log_event if the charset is not changing from event to event (common situation). When the 6 bytes are equal to 0 is used to mean "cache is invalidated". */ void cached_charset_invalidate(); bool cached_charset_compare(char *charset) const; }; extern struct rpl_slave_state *rpl_global_gtid_slave_state; extern gtid_waiting rpl_global_gtid_waiting; int rpl_load_gtid_slave_state(THD *thd); int find_gtid_slave_pos_tables(THD *thd); int event_group_new_gtid(rpl_group_info *rgi, Gtid_log_event *gev); void delete_or_keep_event_post_apply(rpl_group_info *rgi, Log_event_type typ, Log_event *ev); #endif /* RPL_RLI_H */ mysql/server/private/sql_cte.h000064400000040225151027430560012502 0ustar00/* Copyright (c) 2016, 2017 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SQL_CTE_INCLUDED #define SQL_CTE_INCLUDED #include "sql_list.h" #include "sql_lex.h" #include "sql_select.h" class select_unit; struct st_unit_ctxt_elem; /** @class With_element_head @brief Head of the definition of a CTE table It contains the name of the CTE and it contains the position of the subchain of table references used in the definition in the global chain of table references used in the query where this definition is encountered. */ class With_element_head : public Sql_alloc { /* The name of the defined CTE */ LEX_CSTRING *query_name; public: /* The structure describing the subchain of the table references used in the specification of the defined CTE in the global chain of table references used in the query. The structure is fully defined only after the CTE definition has been parsed. */ TABLE_CHAIN tables_pos; With_element_head(LEX_CSTRING *name) : query_name(name) { tables_pos.set_start_pos(0); tables_pos.set_end_pos(0); } friend class With_element; }; /** @class With_element @brief Definition of a CTE table It contains a reference to the name of the table introduced by this with element, and a reference to the unit that specificies this table. Also it contains a reference to the with clause to which this element belongs to. */ class With_element : public Sql_alloc { private: With_clause *owner; // with clause this object belongs to With_element *next; // next element in the with clause uint number; // number of the element in the with clause (starting from 0) table_map elem_map; // The map where with only one 1 set in this->number /* The map base_dep_map has 1 in the i-th position if the query that specifies this with element contains a reference to the with element number i in the query FROM list. (In this case this with element depends directly on the i-th with element.) */ table_map base_dep_map; /* The map derived_dep_map has 1 in i-th position if this with element depends directly or indirectly from the i-th with element. */ table_map derived_dep_map; /* The map sq_dep_map has 1 in i-th position if there is a reference to this with element somewhere in subqueries of the specifications of the tables defined in the with clause containing this element; */ table_map sq_dep_map; table_map work_dep_map; // dependency map used for work /* Dependency map of with elements mutually recursive with this with element */ table_map mutually_recursive; /* Dependency map built only for the top level references i.e. for those that are encountered in from lists of the selects of the specification unit */ table_map top_level_dep_map; /* Points to a recursive reference in subqueries. Used only for specifications without recursive references on the top level. */ TABLE_LIST *sq_rec_ref; /* The next with element from the circular chain of the with elements mutually recursive with this with element. (If This element is simply recursive than next_mutually_recursive contains the pointer to itself. If it's not recursive than next_mutually_recursive is set to NULL.) */ With_element *next_mutually_recursive; /* Total number of references to this element in the FROM lists of the queries that are in the scope of the element (including subqueries and specifications of other with elements). */ uint references; /* true <=> this With_element is referred in the query in which the element is defined */ bool referenced; /* true <=> this With_element is needed for the execution of the query in which the element is defined */ bool is_used_in_query; /* Unparsed specification of the query that specifies this element. It's used to build clones of the specification if they are needed. */ LEX_CSTRING unparsed_spec; /* Offset of the specification in the input string */ my_ptrdiff_t unparsed_spec_offset; /* True if the with element is used a prepared statement */ bool stmt_prepare_mode; /* Return the map where 1 is set only in the position for this element */ table_map get_elem_map() { return (table_map) 1 << number; } public: /* Contains the name of the defined With element and the position of the subchain of the tables references used by its definition in the global chain of TABLE_LIST objects created for the whole query. */ With_element_head *head; /* Optional list of column names to name the columns of the table introduced by this with element. It is used in the case when the names are not inherited from the query that specified the table. Otherwise the list is always empty. */ List column_list; List *cycle_list; /* The query that specifies the table introduced by this with element */ st_select_lex_unit *spec; /* Set to true is recursion is used (directly or indirectly) for the definition of this element */ bool is_recursive; /* For a simple recursive CTE: the number of references to the CTE from outside of the CTE specification. For a CTE mutually recursive with other CTEs : the total number of references to all these CTEs outside of their specification. Each of these mutually recursive CTEs has the same value in this field. */ uint rec_outer_references; /* Any non-recursive select in the specification of a recursive with element is a called anchor. In the case mutually recursive elements the specification of some them may be without any anchor. Yet at least one of them must contain an anchor. All anchors of any recursivespecification are moved ahead before the prepare stage. */ /* Set to true if this is a recursive element with an anchor */ bool with_anchor; /* Set to the first recursive select of the unit specifying the element after all anchor have been moved to the head of the unit. */ st_select_lex *first_recursive; /* The number of the last performed iteration for recursive table (the number of the initial non-recursive step is 0, the number of the first iteration is 1). */ uint level; /* The pointer to the object used to materialize this with element if it's recursive. This object is built at the end of prepare stage and is used at the execution stage. */ select_union_recursive *rec_result; /* List of Item_subselects containing recursive references to this CTE */ SQL_I_List sq_with_rec_ref; /* List of derived tables containing recursive references to this CTE */ SQL_I_List derived_with_rec_ref; With_element(With_element_head *h, List list, st_select_lex_unit *unit) : next(NULL), base_dep_map(0), derived_dep_map(0), sq_dep_map(0), work_dep_map(0), mutually_recursive(0), top_level_dep_map(0), sq_rec_ref(NULL), next_mutually_recursive(NULL), references(0), referenced(false), is_used_in_query(false), head(h), column_list(list), cycle_list(0), spec(unit), is_recursive(false), rec_outer_references(0), with_anchor(false), level(0), rec_result(NULL) { unit->with_element= this; } LEX_CSTRING *get_name() { return head->query_name; } const char *get_name_str() { return get_name()->str; } void set_tables_start_pos(TABLE_LIST **pos) { head->tables_pos.set_start_pos(pos); } void set_tables_end_pos(TABLE_LIST **pos) { head->tables_pos.set_end_pos(pos); } bool check_dependencies_in_spec(); void check_dependencies_in_select(st_select_lex *sl, st_unit_ctxt_elem *ctxt, bool in_subq, table_map *dep_map); void check_dependencies_in_unit(st_select_lex_unit *unit, st_unit_ctxt_elem *ctxt, bool in_subq, table_map *dep_map); void check_dependencies_in_with_clause(With_clause *with_clause, st_unit_ctxt_elem *ctxt, bool in_subq, table_map *dep_map); void set_dependency_on(With_element *with_elem) { base_dep_map|= with_elem->get_elem_map(); } bool check_dependency_on(With_element *with_elem) { return base_dep_map & with_elem->get_elem_map(); } TABLE_LIST *find_first_sq_rec_ref_in_select(st_select_lex *sel); bool set_unparsed_spec(THD *thd, const char *spec_start, const char *spec_end, my_ptrdiff_t spec_offset); st_select_lex_unit *clone_parsed_spec(LEX *old_lex, TABLE_LIST *with_table); bool is_referenced() { return referenced; } bool is_hanging_recursive() { return is_recursive && !rec_outer_references; } void inc_references() { references++; } bool process_columns_of_derived_unit(THD *thd, st_select_lex_unit *unit); bool prepare_unreferenced(THD *thd); bool check_unrestricted_recursive(st_select_lex *sel, table_map &unrestricted, table_map &encountered); void print(THD *thd, String *str, enum_query_type query_type); With_clause *get_owner() { return owner; } bool contains_sq_with_recursive_reference() { return sq_dep_map & mutually_recursive; } bool no_rec_ref_on_top_level() { return !(top_level_dep_map & mutually_recursive); } table_map get_mutually_recursive() { return mutually_recursive; } With_element *get_next_mutually_recursive() { return next_mutually_recursive; } TABLE_LIST *get_sq_rec_ref() { return sq_rec_ref; } bool is_anchor(st_select_lex *sel); void move_anchors_ahead(); bool is_unrestricted(); bool is_with_prepared_anchor(); void mark_as_with_prepared_anchor(); bool is_cleaned(); void mark_as_cleaned(); void reset_recursive_for_exec(); void cleanup_stabilized(); void set_as_stabilized(); bool is_stabilized(); bool all_are_stabilized(); bool instantiate_tmp_tables(); void prepare_for_next_iteration(); void set_cycle_list(List *cycle_list_arg); friend class With_clause; friend bool LEX::resolve_references_to_cte(TABLE_LIST *tables, TABLE_LIST **tables_last, st_select_lex_unit *excl_spec); }; const uint max_number_of_elements_in_with_clause= sizeof(table_map)*8; /** @class With_clause @brief Set of with_elements It has a reference to the first with element from this with clause. This reference allows to navigate through all the elements of the with clause. It contains a reference to the unit to which this with clause is attached. It also contains a flag saying whether this with clause was specified as recursive. */ class With_clause : public Sql_alloc { private: st_select_lex_unit *owner; // the unit this with clause attached to /* The list of all with elements from this with clause */ SQL_I_List with_list; /* The with clause immediately containing this with clause if there is any, otherwise NULL. Now used only at parsing. */ With_clause *embedding_with_clause; /* The next with the clause of the chain of with clauses encountered in the current statement */ With_clause *next_with_clause; /* Set to true if dependencies between with elements have been checked */ bool dependencies_are_checked; /* The bitmap of all recursive with elements whose specifications are not complied with restrictions imposed by the SQL standards on recursive specifications. */ table_map unrestricted; /* The bitmap of all recursive with elements whose anchors has been already prepared. */ table_map with_prepared_anchor; table_map cleaned; /* The bitmap of all recursive with elements that has been already materialized */ table_map stabilized; public: /* If true the specifier RECURSIVE is present in the with clause */ bool with_recursive; With_clause(bool recursive_fl, With_clause *emb_with_clause) : owner(NULL), embedding_with_clause(emb_with_clause), next_with_clause(NULL), dependencies_are_checked(false), unrestricted(0), with_prepared_anchor(0), cleaned(0), stabilized(0), with_recursive(recursive_fl) { } bool add_with_element(With_element *elem); /* Add this with clause to the list of with clauses used in the statement */ void add_to_list(With_clause **ptr, With_clause ** &last_next) { if (embedding_with_clause) { /* An embedded with clause is always placed before the embedding one in the list of with clauses used in the query. */ while (*ptr != embedding_with_clause) ptr= &(*ptr)->next_with_clause; *ptr= this; next_with_clause= embedding_with_clause; } else { *last_next= this; last_next= &this->next_with_clause; } } st_select_lex_unit *get_owner() { return owner; } void set_owner(st_select_lex_unit *unit) { owner= unit; } void attach_to(st_select_lex *select_lex); With_clause *pop() { return embedding_with_clause; } bool check_dependencies(); bool check_anchors(); void move_anchors_ahead(); With_element *find_table_def(TABLE_LIST *table, With_element *barrier, st_select_lex_unit *excl_spec); With_element *find_table_def_in_with_clauses(TABLE_LIST *table); bool prepare_unreferenced_elements(THD *thd); void add_unrestricted(table_map map) { unrestricted|= map; } void print(THD *thd, String *str, enum_query_type query_type); friend class With_element; friend bool LEX::check_dependencies_in_with_clauses(); }; inline bool With_element::is_unrestricted() { return owner->unrestricted & get_elem_map(); } inline bool With_element::is_with_prepared_anchor() { return owner->with_prepared_anchor & get_elem_map(); } inline void With_element::mark_as_with_prepared_anchor() { owner->with_prepared_anchor|= mutually_recursive; } inline bool With_element::is_cleaned() { return owner->cleaned & get_elem_map(); } inline void With_element::mark_as_cleaned() { owner->cleaned|= get_elem_map(); } inline void With_element::reset_recursive_for_exec() { DBUG_ASSERT(is_recursive); level= 0; owner->with_prepared_anchor&= ~mutually_recursive; owner->cleaned&= ~get_elem_map(); cleanup_stabilized(); spec->columns_are_renamed= false; } inline void With_element::cleanup_stabilized() { owner->stabilized&= ~mutually_recursive; } inline void With_element::set_as_stabilized() { owner->stabilized|= get_elem_map(); } inline bool With_element::is_stabilized() { return owner->stabilized & get_elem_map(); } inline bool With_element::all_are_stabilized() { return (owner->stabilized & mutually_recursive) == mutually_recursive; } inline void With_element::prepare_for_next_iteration() { With_element *with_elem= this; while ((with_elem= with_elem->get_next_mutually_recursive()) != this) { TABLE *rec_table= with_elem->rec_result->first_rec_table_to_update; if (rec_table) rec_table->reginfo.join_tab->preread_init_done= false; } } inline void With_clause::attach_to(st_select_lex *select_lex) { for (With_element *with_elem= with_list.first; with_elem; with_elem= with_elem->next) { select_lex->register_unit(with_elem->spec, NULL); } } inline void st_select_lex::set_with_clause(With_clause *with_clause) { master_unit()->with_clause= with_clause; if (with_clause) with_clause->set_owner(master_unit()); } #endif /* SQL_CTE_INCLUDED */ mysql/server/private/filesort_utils.h000064400000020003151027430560014107 0ustar00/* Copyright (c) 2010, 2012 Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef FILESORT_UTILS_INCLUDED #define FILESORT_UTILS_INCLUDED #include "my_base.h" #include "sql_array.h" class Sort_param; /* Calculate cost of merge sort @param num_rows Total number of rows. @param num_keys_per_buffer Number of keys per buffer. @param elem_size Size of each element. Calculates cost of merge sort by simulating call to merge_many_buff(). @retval Computed cost of merge sort in disk seeks. @note Declared here in order to be able to unit test it, since library dependencies have not been sorted out yet. See also comments get_merge_many_buffs_cost(). */ double get_merge_many_buffs_cost_fast(ha_rows num_rows, ha_rows num_keys_per_buffer, uint elem_size); /** A wrapper class around the buffer used by filesort(). The sort buffer is a contiguous chunk of memory, containing both records to be sorted, and pointers to said records: |rec 0|record 1 |rec 2| ............ |ptr to rec2|ptr to rec1|ptr to rec0| Records will be inserted "left-to-right". Records are not necessarily fixed-size, they can be packed and stored without any "gaps". Record pointers will be inserted "right-to-left", as a side-effect of inserting the actual records. We wrap the buffer in order to be able to do lazy initialization of the pointers: the buffer is often much larger than what we actually need. With this allocation scheme, and lazy initialization of the pointers, we are able to pack variable-sized records in the buffer, and thus possibly have space for more records than we initially estimated. The buffer must be kept available for multiple executions of the same sort operation, so we have explicit allocate and free functions, rather than doing alloc/free in CTOR/DTOR. */ class Filesort_buffer { public: Filesort_buffer() : m_next_rec_ptr(NULL), m_rawmem(NULL), m_record_pointers(NULL), m_sort_keys(NULL), m_num_records(0), m_record_length(0), m_sort_length(0), m_size_in_bytes(0), m_idx(0) {} /** Sort me... */ void sort_buffer(const Sort_param *param, uint count); /** Reverses the record pointer array, to avoid recording new results for non-deterministic mtr tests. */ void reverse_record_pointers() { if (m_idx < 2) // There is nothing to swap. return; uchar **keys= get_sort_keys(); const longlong count= m_idx - 1; for (longlong ix= 0; ix <= count/2; ++ix) { uchar *tmp= keys[count - ix]; keys[count - ix] = keys[ix]; keys[ix]= tmp; } } /** Initializes all the record pointers. */ void init_record_pointers() { init_next_record_pointer(); while (m_idx < m_num_records) (void) get_next_record_pointer(); reverse_record_pointers(); } /** Prepares the buffer for the next batch of records to process. */ void init_next_record_pointer() { m_idx= 0; m_next_rec_ptr= m_rawmem; m_sort_keys= NULL; } /** @returns the number of bytes currently in use for data. */ size_t space_used_for_data() const { return m_next_rec_ptr ? m_next_rec_ptr - m_rawmem : 0; } /** @returns the number of bytes left in the buffer. */ size_t spaceleft() const { DBUG_ASSERT(m_next_rec_ptr >= m_rawmem); const size_t spaceused= (m_next_rec_ptr - m_rawmem) + (static_cast(m_idx) * sizeof(uchar*)); return m_size_in_bytes - spaceused; } /** Is the buffer full? */ bool isfull() const { if (m_idx < m_num_records) return false; return spaceleft() < (m_record_length + sizeof(uchar*)); } /** Where should the next record be stored? */ uchar *get_next_record_pointer() { uchar *retval= m_next_rec_ptr; // Save the return value in the record pointer array. m_record_pointers[-m_idx]= m_next_rec_ptr; // Prepare for the subsequent request. m_idx++; m_next_rec_ptr+= m_record_length; return retval; } /** Adjusts for actual record length. get_next_record_pointer() above was pessimistic, and assumed that the record could not be packed. */ void adjust_next_record_pointer(uint val) { m_next_rec_ptr-= (m_record_length - val); } /// Returns total size: pointer array + record buffers. size_t sort_buffer_size() const { return m_size_in_bytes; } bool is_allocated() const { return m_rawmem; } /** Allocates the buffer, but does *not* initialize pointers. Total size = (num_records * record_length) + (num_records * sizeof(pointer)) space for records space for pointer to records Caller is responsible for raising an error if allocation fails. @param num_records Number of records. @param record_length (maximum) size of each record. @returns Pointer to allocated area, or NULL in case of out-of-memory. */ uchar *alloc_sort_buffer(uint num_records, uint record_length); /// Frees the buffer. void free_sort_buffer(); void reset() { m_rawmem= NULL; } /** Used to access the "right-to-left" array of record pointers as an ordinary "left-to-right" array, so that we can pass it directly on to std::sort(). */ uchar **get_sort_keys() { if (m_idx == 0) return NULL; return &m_record_pointers[1 - m_idx]; } /** Gets sorted record number ix. @see get_sort_keys() Only valid after buffer has been sorted! */ uchar *get_sorted_record(uint ix) { return m_sort_keys[ix]; } /** @returns The entire buffer, as a character array. This is for reusing the memory for merge buffers. */ Bounds_checked_array get_raw_buf() { return Bounds_checked_array(m_rawmem, m_size_in_bytes); } /** We need an assignment operator, see filesort(). This happens to have the same semantics as the one that would be generated by the compiler. Note that this is a shallow copy. We have two objects sharing the same array. */ Filesort_buffer &operator=(const Filesort_buffer &rhs) = default; uint get_sort_length() const { return m_sort_length; } void set_sort_length(uint val) { m_sort_length= val; } private: uchar *m_next_rec_ptr; /// The next record will be inserted here. uchar *m_rawmem; /// The raw memory buffer. uchar **m_record_pointers; /// The "right-to-left" array of record pointers. uchar **m_sort_keys; /// Caches the value of get_sort_keys() uint m_num_records; /// Saved value from alloc_sort_buffer() uint m_record_length; /// Saved value from alloc_sort_buffer() uint m_sort_length; /// The length of the sort key. size_t m_size_in_bytes; /// Size of raw buffer, in bytes. /** This is the index in the "right-to-left" array of the next record to be inserted into the buffer. It is signed, because we use it in signed expressions like: m_record_pointers[-m_idx]; It is longlong rather than int, to ensure that it covers UINT_MAX32 without any casting/warning. */ longlong m_idx; }; int compare_packed_sort_keys(void *sort_param, const void *a_ptr, const void *b_ptr); qsort_cmp2 get_packed_keys_compare_ptr(); #endif // FILESORT_UTILS_INCLUDED mysql/server/private/item_create.h000064400000026355151027430560013341 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. Copyright (c) 2008, 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Functions to create an item. Used by sql/sql_yacc.yy */ #ifndef ITEM_CREATE_H #define ITEM_CREATE_H #include "item_func.h" // Cast_target typedef struct st_udf_func udf_func; /** Public function builder interface. The parser (sql/sql_yacc.yy) uses a factory / builder pattern to construct an Item object for each function call. All the concrete function builders implements this interface, either directly or indirectly with some adapter helpers. Keeping the function creation separated from the bison grammar allows to simplify the parser, and avoid the need to introduce a new token for each function, which has undesirable side effects in the grammar. */ class Create_func { public: /** The builder create method. Given the function name and list or arguments, this method creates an Item that represents the function call. In case or errors, a NULL item is returned, and an error is reported. Note that the thd object may be modified by the builder. In particular, the following members/methods can be set/called, depending on the function called and the function possible side effects.
  • thd->lex->binlog_row_based_if_mixed
  • thd->lex->current_context()
  • thd->lex->safe_to_cache_query
  • thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT)
  • thd->lex->uncacheable(UNCACHEABLE_RAND)
  • thd->lex->add_time_zone_tables_to_query_tables(thd)
@param thd The current thread @param name The function name @param item_list The list of arguments to the function, can be NULL @return An item representing the parsed function call, or NULL */ virtual Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) = 0; protected: /** Constructor */ Create_func() = default; /** Destructor */ virtual ~Create_func() = default; }; /** Adapter for functions that takes exactly zero arguments. */ class Create_func_arg0 : public Create_func { public: Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** Builder method, with no arguments. @param thd The current thread @return An item representing the function call */ virtual Item *create_builder(THD *thd) = 0; protected: /** Constructor. */ Create_func_arg0() = default; /** Destructor. */ virtual ~Create_func_arg0() = default; }; /** Adapter for functions that takes exactly one argument. */ class Create_func_arg1 : public Create_func { public: Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** Builder method, with one argument. @param thd The current thread @param arg1 The first argument of the function @return An item representing the function call */ virtual Item *create_1_arg(THD *thd, Item *arg1) = 0; protected: /** Constructor. */ Create_func_arg1() = default; /** Destructor. */ virtual ~Create_func_arg1() = default; }; /** Adapter for functions that takes exactly two arguments. */ class Create_func_arg2 : public Create_func { public: Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** Builder method, with two arguments. @param thd The current thread @param arg1 The first argument of the function @param arg2 The second argument of the function @return An item representing the function call */ virtual Item *create_2_arg(THD *thd, Item *arg1, Item *arg2) = 0; protected: /** Constructor. */ Create_func_arg2() = default; /** Destructor. */ virtual ~Create_func_arg2() = default; }; /** Adapter for functions that takes exactly three arguments. */ class Create_func_arg3 : public Create_func { public: Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** Builder method, with three arguments. @param thd The current thread @param arg1 The first argument of the function @param arg2 The second argument of the function @param arg3 The third argument of the function @return An item representing the function call */ virtual Item *create_3_arg(THD *thd, Item *arg1, Item *arg2, Item *arg3) = 0; protected: /** Constructor. */ Create_func_arg3() = default; /** Destructor. */ virtual ~Create_func_arg3() = default; }; /** Adapter for native functions with a variable number of arguments. The main use of this class is to discard the following calls: foo(expr1 AS name1, expr2 AS name2, ...) which are syntactically correct (the syntax can refer to a UDF), but semantically invalid for native functions. */ class Create_native_func : public Create_func { public: Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** Builder method, with no arguments. @param thd The current thread @param name The native function name @param item_list The function parameters, none of which are named @return An item representing the function call */ virtual Item *create_native(THD *thd, const LEX_CSTRING *name, List *item_list) = 0; protected: /** Constructor. */ Create_native_func() = default; /** Destructor. */ virtual ~Create_native_func() = default; }; /** Function builder for qualified functions. This builder is used with functions call using a qualified function name syntax, as in db.func(expr, expr, ...). */ class Create_qfunc : public Create_func { public: /** The builder create method, for unqualified functions. This builder will use the current database for the database name. @param thd The current thread @param name The function name @param item_list The list of arguments to the function, can be NULL @return An item representing the parsed function call */ Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** The builder create method, for qualified functions. @param thd The current thread @param db The database name @param name The function name @param use_explicit_name Should the function be represented as 'db.name'? @param item_list The list of arguments to the function, can be NULL @return An item representing the parsed function call */ virtual Item *create_with_db(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *name, bool use_explicit_name, List *item_list) = 0; protected: /** Constructor. */ Create_qfunc() = default; /** Destructor. */ virtual ~Create_qfunc() = default; }; /** Find the function builder for qualified functions. @param thd The current thread @return A function builder for qualified functions */ extern Create_qfunc * find_qualified_function_builder(THD *thd); #ifdef HAVE_DLOPEN /** Function builder for User Defined Functions. */ class Create_udf_func : public Create_func { public: Item *create_func(THD *thd, const LEX_CSTRING *name, List *item_list) override; /** The builder create method, for User Defined Functions. @param thd The current thread @param fct The User Defined Function metadata @param item_list The list of arguments to the function, can be NULL @return An item representing the parsed function call */ Item *create(THD *thd, udf_func *fct, List *item_list); /** Singleton. */ static Create_udf_func s_singleton; protected: /** Constructor. */ Create_udf_func() = default; /** Destructor. */ virtual ~Create_udf_func() = default; }; #endif struct Native_func_registry { LEX_CSTRING name; Create_func *builder; }; class Native_functions_hash: public HASH { public: Native_functions_hash() { bzero((void*) this, sizeof(*this)); } ~Native_functions_hash() { /* No automatic free because objects of this type are expected to be declared statically. The code in cleanup() calls my_hash_free() which may not work correctly at the very end of mariadbd shutdown. The the upper level code should call cleanup() explicitly. Unfortunatelly, it's not possible to use DBUG_ASSERT(!records) here, because the server terminates using exit() in some cases, e.g. in the test main.named_pipe with the "Create named pipe failed" error. */ } bool init(size_t count); bool append(const Native_func_registry array[], size_t count); bool remove(const Native_func_registry array[], size_t count); bool replace(const Native_func_registry array[], size_t count) { DBUG_ENTER("Native_functions_hash::replace"); remove(array, count); DBUG_RETURN(append(array, count)); } void cleanup(); /** Find the native function builder associated with a given function name. @param thd The current thread @param name The native function name @return The native function builder associated with the name, or NULL */ Create_func *find(THD *thd, const LEX_CSTRING &name) const; }; extern MYSQL_PLUGIN_IMPORT Native_functions_hash native_functions_hash; extern MYSQL_PLUGIN_IMPORT Native_functions_hash native_functions_hash_oracle; extern const Native_func_registry func_array[]; extern const size_t func_array_length; int item_create_init(); void item_create_cleanup(); Item *create_func_dyncol_create(THD *thd, List &list); Item *create_func_dyncol_add(THD *thd, Item *str, List &list); Item *create_func_dyncol_delete(THD *thd, Item *str, List &nums); Item *create_func_dyncol_get(THD *thd, Item *num, Item *str, const Type_handler *handler, const char *c_len, const char *c_dec, CHARSET_INFO *cs); Item *create_func_dyncol_json(THD *thd, Item *str); class Native_func_registry_array { const Native_func_registry *m_elements; size_t m_count; public: Native_func_registry_array() :m_elements(NULL), m_count(0) { } Native_func_registry_array(const Native_func_registry *elements, size_t count) :m_elements(elements), m_count(count) { } const Native_func_registry& element(size_t i) const { DBUG_ASSERT(i < m_count); return m_elements[i]; } const Native_func_registry *elements() const { return m_elements; } size_t count() const { return m_count; } }; #endif mysql/server/private/sql_help.h000064400000001743151027430560012661 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_HELP_INCLUDED #define SQL_HELP_INCLUDED class THD; /* Function prototypes */ bool mysqld_help (THD *thd, const char *text); bool mysqld_help_prepare(THD *thd, const char *text, List *fields); #endif /* SQL_HELP_INCLUDED */ mysql/server/private/welcome_copyright_notice.h000064400000002302151027430560016126 0ustar00/* Copyright (c) 2011, 2017, Oracle and/or its affiliates. Copyright (c) 2011, 2017, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _welcome_copyright_notice_h_ #define _welcome_copyright_notice_h_ #define COPYRIGHT_NOTICE_CURRENT_YEAR "2018" /* This define specifies copyright notice which is displayed by every MySQL program on start, or on help screen. */ #define ORACLE_WELCOME_COPYRIGHT_NOTICE(first_year) \ "Copyright (c) " first_year ", " COPYRIGHT_NOTICE_CURRENT_YEAR \ ", Oracle, MariaDB Corporation Ab and others.\n" #endif /* _welcome_copyright_notice_h_ */ mysql/server/private/select_handler.h000064400000004264151027430560014027 0ustar00/* Copyright (c) 2018, 2019 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SELECT_HANDLER_INCLUDED #define SELECT_HANDLER_INCLUDED #include "mariadb.h" #include "sql_priv.h" /** @class select_handler This interface class is to be used for execution of select queries by foreign engines */ class select_handler { public: THD *thd; handlerton *ht; SELECT_LEX *select; // Select to be excuted /* Temporary table where all results should be stored in record[0] The table has a field for every item from the select_lex::item_list. The table is actually never filled. Only its record buffer is used. */ TABLE *table; List result_columns; bool is_analyze; bool send_result_set_metadata(); bool send_data(); select_handler(THD *thd_arg, handlerton *ht_arg); virtual ~select_handler(); int execute(); virtual bool prepare(); static TABLE *create_tmp_table(THD *thd, SELECT_LEX *sel); protected: /* Functions to scan the select result set. All these returns 0 if ok, error code in case of error. */ /* Initialize the process of producing rows of result set */ virtual int init_scan() = 0; /* Put the next produced row of the result set in table->record[0] and return 0. Return HA_ERR_END_OF_FILE if there are no more rows, return other error number in case of fatal error. */ virtual int next_row() = 0; /* Finish scanning */ virtual int end_scan() = 0; /* Report errors */ virtual void print_error(int error, myf errflag); bool send_eof(); }; #endif /* SELECT_HANDLER_INCLUDED */ mysql/server/private/gstream.h000064400000004605151027430560012514 0ustar00#ifndef GSTREAM_INCLUDED #define GSTREAM_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include /* MY_ALLOW_ZERO_PTR */ #include "m_ctype.h" /* my_charset_latin1, my_charset_bin */ class Gis_read_stream { public: enum enum_tok_types { unknown, eostream, word, numeric, l_bra, r_bra, comma }; Gis_read_stream(CHARSET_INFO *charset, const char *buffer, int size) :m_cur(buffer), m_limit(buffer + size), m_err_msg(NULL), m_charset(charset) {} Gis_read_stream(): m_cur(NullS), m_limit(NullS), m_err_msg(NullS) {} ~Gis_read_stream() { my_free(m_err_msg); } enum enum_tok_types get_next_toc_type(); bool lookup_next_word(LEX_STRING *res); bool get_next_word(LEX_STRING *); bool get_next_number(double *); bool check_next_symbol(char); inline void skip_space() { while ((m_cur < m_limit) && my_isspace(&my_charset_latin1, *m_cur)) m_cur++; } /* Skip next character, if match. Return 1 if no match */ inline bool skip_char(char skip) { skip_space(); if ((m_cur >= m_limit) || *m_cur != skip) return 1; /* Didn't find char */ m_cur++; return 0; } /* Returns the next notempty character. */ char next_symbol() { skip_space(); if (m_cur >= m_limit) return 0; /* EOL meet. */ return *m_cur; } void set_error_msg(const char *msg); // caller should free this pointer char *get_error_msg() { char *err_msg = m_err_msg; m_err_msg= NullS; return err_msg; } protected: const char *m_cur; const char *m_limit; char *m_err_msg; CHARSET_INFO *m_charset; }; #endif /* GSTREAM_INCLUDED */ mysql/server/private/wqueue.h000064400000003035151027430560012361 0ustar00/* Copyright (c) 2007, 2008, Sun Microsystems, Inc, Copyright (c) 2011, 2012, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef WQUEUE_INCLUDED #define WQUEUE_INCLUDED #include /* info about requests in a waiting queue */ typedef struct st_pagecache_wqueue { struct st_my_thread_var *last_thread; /* circular list of waiting threads */ } WQUEUE; void wqueue_link_into_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); void wqueue_unlink_from_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); void wqueue_add_to_queue(WQUEUE *wqueue, struct st_my_thread_var *thread); void wqueue_add_and_wait(WQUEUE *wqueue, struct st_my_thread_var *thread, mysql_mutex_t *lock); void wqueue_release_queue(WQUEUE *wqueue); void wqueue_release_one_locktype_from_queue(WQUEUE *wqueue); #endif mysql/server/private/sql_handler.h000064400000005536151027430560013352 0ustar00#ifndef SQL_HANDLER_INCLUDED #define SQL_HANDLER_INCLUDED /* Copyright (c) 2006, 2015, Oracle and/or its affiliates. Copyright (C) 2010, 2015, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_class.h" /* enum_ha_read_mode */ #include "my_base.h" /* ha_rkey_function, ha_rows */ #include "sql_list.h" /* List */ /* Open handlers are stored here */ class SQL_HANDLER { public: TABLE *table; List fields; /* Fields, set on open */ THD *thd; LEX_CSTRING handler_name; LEX_CSTRING db; LEX_CSTRING table_name; MEM_ROOT mem_root; MYSQL_LOCK *lock; MDL_request mdl_request; key_part_map keypart_map; int keyno; /* Used key */ uint key_len; enum enum_ha_read_modes mode; /* This is only used when deleting many handler objects */ SQL_HANDLER *next; Query_arena arena; char *base_data; SQL_HANDLER(THD *thd_arg) : thd(thd_arg), arena(&mem_root, Query_arena::STMT_INITIALIZED) { init(); clear_alloc_root(&mem_root); base_data= 0; } void init() { keyno= -1; table= 0; lock= 0; mdl_request.ticket= 0; } void reset(); ~SQL_HANDLER(); }; class THD; struct TABLE_LIST; bool mysql_ha_open(THD *thd, TABLE_LIST *tables, SQL_HANDLER *reopen); bool mysql_ha_close(THD *thd, TABLE_LIST *tables); bool mysql_ha_read(THD *, TABLE_LIST *,enum enum_ha_read_modes, const char *, List *,enum ha_rkey_function,Item *,ha_rows,ha_rows); void mysql_ha_flush(THD *thd); void mysql_ha_flush_tables(THD *thd, TABLE_LIST *all_tables); void mysql_ha_rm_tables(THD *thd, TABLE_LIST *tables); void mysql_ha_cleanup_no_free(THD *thd); void mysql_ha_cleanup(THD *thd); void mysql_ha_set_explicit_lock_duration(THD *thd); void mysql_ha_rm_temporary_tables(THD *thd); SQL_HANDLER *mysql_ha_read_prepare(THD *thd, TABLE_LIST *tables, enum enum_ha_read_modes mode, const char *keyname, List *key_expr, enum ha_rkey_function ha_rkey_mode, Item *cond); #endif mysql/server/private/pfs_table_provider.h000064400000005101151027430560014713 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_TABLE_PROVIDER_H #define PFS_TABLE_PROVIDER_H /** @file include/pfs_table_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_TABLE_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_TABLE_CALL(M) pfs_ ## M ## _v1 C_MODE_START PSI_table_share* pfs_get_table_share_v1(my_bool temporary, struct TABLE_SHARE *share); void pfs_release_table_share_v1(PSI_table_share* share); void pfs_drop_table_share_v1(my_bool temporary, const char *schema_name, int schema_name_length, const char *table_name, int table_name_length); PSI_table* pfs_open_table_v1(PSI_table_share *share, const void *identity); void pfs_unbind_table_v1(PSI_table *table); PSI_table * pfs_rebind_table_v1(PSI_table_share *share, const void *identity, PSI_table *table); void pfs_close_table_v1(struct TABLE_SHARE *server_share, PSI_table *table); PSI_table_locker* pfs_start_table_io_wait_v1(PSI_table_locker_state *state, PSI_table *table, PSI_table_io_operation op, uint index, const char *src_file, uint src_line); PSI_table_locker* pfs_start_table_lock_wait_v1(PSI_table_locker_state *state, PSI_table *table, PSI_table_lock_operation op, ulong op_flags, const char *src_file, uint src_line); void pfs_end_table_io_wait_v1(PSI_table_locker* locker, ulonglong numrows); void pfs_end_table_lock_wait_v1(PSI_table_locker* locker); void pfs_unlock_table_v1(PSI_table *table); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_TABLE_INTERFACE */ #endif mysql/server/private/sql_union.h000064400000002050151027430560013051 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_UNION_INCLUDED #define SQL_UNION_INCLUDED class THD; class select_result; struct LEX; typedef class st_select_lex_unit SELECT_LEX_UNIT; bool mysql_union(THD *thd, LEX *lex, select_result *result, SELECT_LEX_UNIT *unit, ulong setup_tables_done_option); #endif /* SQL_UNION_INCLUDED */ mysql/server/private/violite.h000064400000023546151027430560012532 0ustar00/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2012, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* * Vio Lite. * Purpose: include file for Vio that will work with C and C++ */ #ifndef vio_violite_h_ #define vio_violite_h_ #include "my_net.h" /* needed because of struct in_addr */ #include /* Simple vio interface in C; The functions are implemented in violite.c */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef __cplusplus typedef struct st_vio Vio; #endif /* __cplusplus */ enum enum_vio_type { VIO_CLOSED, VIO_TYPE_TCPIP, VIO_TYPE_SOCKET, VIO_TYPE_NAMEDPIPE, VIO_TYPE_SSL /* see also vio_type_names[] */ }; enum enum_vio_state { VIO_STATE_NOT_INITIALIZED, VIO_STATE_ACTIVE, VIO_STATE_SHUTDOWN, VIO_STATE_CLOSED }; #define FIRST_VIO_TYPE VIO_CLOSED #define LAST_VIO_TYPE VIO_TYPE_SSL /** VIO I/O events. */ enum enum_vio_io_event { VIO_IO_EVENT_READ, VIO_IO_EVENT_WRITE, VIO_IO_EVENT_CONNECT }; struct vio_keepalive_opts { int interval; int idle; int probes; }; #define VIO_TLSv1_0 1 #define VIO_TLSv1_1 2 #define VIO_TLSv1_2 4 #define VIO_TLSv1_3 8 #define VIO_LOCALHOST 1U /* a localhost connection */ #define VIO_BUFFERED_READ 2U /* use buffered read */ #define VIO_READ_BUFFER_SIZE 16384U /* size of read buffer */ #define VIO_DESCRIPTION_SIZE 30 /* size of description */ Vio* vio_new(my_socket sd, enum enum_vio_type type, uint flags); Vio* mysql_socket_vio_new(MYSQL_SOCKET mysql_socket, enum enum_vio_type type, uint flags); #ifdef _WIN32 Vio* vio_new_win32pipe(HANDLE hPipe); #else #define HANDLE void * #endif /* _WIN32 */ void vio_delete(Vio* vio); int vio_close(Vio* vio); my_bool vio_reset(Vio* vio, enum enum_vio_type type, my_socket sd, void *ssl, uint flags); size_t vio_read(Vio *vio, uchar * buf, size_t size); size_t vio_read_buff(Vio *vio, uchar * buf, size_t size); size_t vio_write(Vio *vio, const uchar * buf, size_t size); int vio_blocking(Vio *vio, my_bool onoff, my_bool *old_mode); my_bool vio_is_blocking(Vio *vio); /* setsockopt TCP_NODELAY at IPPROTO_TCP level, when possible */ int vio_nodelay(Vio *vio, my_bool on); int vio_fastsend(Vio *vio); /* setsockopt SO_KEEPALIVE at SOL_SOCKET level, when possible */ int vio_keepalive(Vio *vio, my_bool onoff); int vio_set_keepalive_options(Vio * vio, const struct vio_keepalive_opts *opts); /* Whenever we should retry the last read/write operation. */ my_bool vio_should_retry(Vio *vio); /* Check that operation was timed out */ my_bool vio_was_timeout(Vio *vio); /* Short text description of the socket for those, who are curious.. */ const char* vio_description(Vio *vio); /* Return the type of the connection */ enum enum_vio_type vio_type(Vio* vio); /* Return last error number */ int vio_errno(Vio*vio); /* Get socket number */ my_socket vio_fd(Vio*vio); /* Remote peer's address and name in text form */ my_bool vio_peer_addr(Vio *vio, char *buf, uint16 *port, size_t buflen); /* Wait for an I/O event notification. */ int vio_io_wait(Vio *vio, enum enum_vio_io_event event, int timeout); my_bool vio_is_connected(Vio *vio); ssize_t vio_pending(Vio *vio); /* Set timeout for a network operation. */ extern int vio_timeout(Vio *vio, uint which, int timeout_sec); extern void vio_set_wait_callback(void (*before_wait)(void), void (*after_wait)(void)); /* Connect to a peer. */ my_bool vio_socket_connect(Vio *vio, struct sockaddr *addr, socklen_t len, int timeout); void vio_get_normalized_ip(const struct sockaddr *src, size_t src_length, struct sockaddr *dst); my_bool vio_get_normalized_ip_string(const struct sockaddr *addr, size_t addr_length, char *ip_string, size_t ip_string_size); my_bool vio_is_no_name_error(int err_code); int vio_getnameinfo(const struct sockaddr *sa, char *hostname, size_t hostname_size, char *port, size_t port_size, int flags); #ifdef HAVE_OPENSSL /* apple deprecated openssl in MacOSX Lion */ #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #define HEADER_DES_LOCL_H dummy_something #define YASSL_MYSQL_COMPATIBLE #ifndef YASSL_PREFIX #define YASSL_PREFIX #endif /* Set yaSSL to use same type as MySQL do for socket handles */ typedef my_socket YASSL_SOCKET_T; #define YASSL_SOCKET_T_DEFINED #define template _template /* bug in WolfSSL 4.4.0, see also my_crypt.cc */ #include #undef template #include #ifdef DEPRECATED #undef DEPRECATED #endif enum enum_ssl_init_error { SSL_INITERR_NOERROR= 0, SSL_INITERR_CERT, SSL_INITERR_KEY, SSL_INITERR_NOMATCH, SSL_INITERR_BAD_PATHS, SSL_INITERR_CIPHERS, SSL_INITERR_MEMFAIL, SSL_INITERR_DH, SSL_INITERR_PROTOCOL, SSL_INITERR_LASTERR }; const char* sslGetErrString(enum enum_ssl_init_error err); struct st_VioSSLFd { SSL_CTX *ssl_context; }; int sslaccept(struct st_VioSSLFd*, Vio *, long timeout, unsigned long *errptr); int sslconnect(struct st_VioSSLFd*, Vio *, long timeout, unsigned long *errptr); void vio_check_ssl_init(); struct st_VioSSLFd *new_VioSSLConnectorFd(const char *key_file, const char *cert_file, const char *ca_file, const char *ca_path, const char *cipher, enum enum_ssl_init_error *error, const char *crl_file, const char *crl_path); struct st_VioSSLFd *new_VioSSLAcceptorFd(const char *key_file, const char *cert_file, const char *ca_file,const char *ca_path, const char *cipher, enum enum_ssl_init_error *error, const char *crl_file, const char *crl_path, ulonglong tls_version); void free_vio_ssl_acceptor_fd(struct st_VioSSLFd *fd); #endif /* HAVE_OPENSSL */ void vio_end(void); const char *vio_type_name(enum enum_vio_type vio_type, size_t *len); #ifdef __cplusplus } #endif #if !defined(DONT_MAP_VIO) #define vio_delete(vio) (vio)->viodelete(vio) #define vio_errno(vio) (vio)->vioerrno(vio) #define vio_read(vio, buf, size) ((vio)->read)(vio,buf,size) #define vio_write(vio, buf, size) ((vio)->write)(vio, buf, size) #define vio_blocking(vio, set_blocking_mode, old_mode)\ (vio)->vioblocking(vio, set_blocking_mode, old_mode) #define vio_is_blocking(vio) (vio)->is_blocking(vio) #define vio_fastsend(vio) (vio)->fastsend(vio) #define vio_keepalive(vio, set_keep_alive) (vio)->viokeepalive(vio, set_keep_alive) #define vio_should_retry(vio) (vio)->should_retry(vio) #define vio_was_timeout(vio) (vio)->was_timeout(vio) #define vio_close(vio) ((vio)->vioclose)(vio) #define vio_shutdown(vio,how) ((vio)->shutdown)(vio,how) #define vio_peer_addr(vio, buf, prt, buflen) (vio)->peer_addr(vio, buf, prt, buflen) #define vio_io_wait(vio, event, timeout) (vio)->io_wait(vio, event, timeout) #define vio_is_connected(vio) (vio)->is_connected(vio) #endif /* !defined(DONT_MAP_VIO) */ #ifdef _WIN32 /* shutdown(2) flags */ #ifndef SHUT_RD #define SHUT_RD SD_RECEIVE #endif #endif /* This enumerator is used in parser - should be always visible */ enum SSL_type { SSL_TYPE_NOT_SPECIFIED= -1, SSL_TYPE_NONE, SSL_TYPE_ANY, SSL_TYPE_X509, SSL_TYPE_SPECIFIED }; /* HFTODO - hide this if we don't want client in embedded server */ /* This structure is for every connection on both sides */ struct st_vio { MYSQL_SOCKET mysql_socket; /* Instrumented socket */ my_bool localhost; /* Are we from localhost? */ int fcntl_mode; /* Buffered fcntl(sd,F_GETFL) */ struct sockaddr_storage local; /* Local internet address */ struct sockaddr_storage remote; /* Remote internet address */ enum enum_vio_type type; /* Type of connection */ enum enum_vio_state state; /* State of the connection */ const char *desc; /* String description */ char *read_buffer; /* buffer for vio_read_buff */ char *read_pos; /* start of unfetched data in the read buffer */ char *read_end; /* end of unfetched data */ int read_timeout; /* Timeout value (ms) for read ops. */ int write_timeout; /* Timeout value (ms) for write ops. */ /* function pointers. They are similar for socket/SSL/whatever */ void (*viodelete)(Vio*); int (*vioerrno)(Vio*); size_t (*read)(Vio*, uchar *, size_t); size_t (*write)(Vio*, const uchar *, size_t); int (*timeout)(Vio*, uint, my_bool); int (*vioblocking)(Vio*, my_bool, my_bool *); my_bool (*is_blocking)(Vio*); int (*viokeepalive)(Vio*, my_bool); int (*fastsend)(Vio*); my_bool (*peer_addr)(Vio*, char *, uint16*, size_t); void (*in_addr)(Vio*, struct sockaddr_storage*); my_bool (*should_retry)(Vio*); my_bool (*was_timeout)(Vio*); int (*vioclose)(Vio*); my_bool (*is_connected)(Vio*); int (*shutdown)(Vio *, int); my_bool (*has_data) (Vio*); int (*io_wait)(Vio*, enum enum_vio_io_event, int); my_bool (*connect)(Vio*, struct sockaddr *, socklen_t, int); #ifdef HAVE_OPENSSL void *ssl_arg; #endif #ifdef _WIN32 HANDLE hPipe; OVERLAPPED overlapped; int shutdown_flag; void *tp_ctx; /* threadpool context */ #endif }; #endif /* vio_violite_h_ */ mysql/server/private/sql_update.h000064400000003603151027430560013210 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_UPDATE_INCLUDED #define SQL_UPDATE_INCLUDED #include "sql_class.h" /* enum_duplicates */ class Item; struct TABLE_LIST; class THD; typedef class st_select_lex SELECT_LEX; typedef class st_select_lex_unit SELECT_LEX_UNIT; bool mysql_prepare_update(THD *thd, TABLE_LIST *table_list, Item **conds, uint order_num, ORDER *order); bool check_unique_table(THD *thd, TABLE_LIST *table_list); int mysql_update(THD *thd,TABLE_LIST *tables,List &fields, List &values,COND *conds, uint order_num, ORDER *order, ha_rows limit, bool ignore, ha_rows *found_return, ha_rows *updated_return); bool mysql_multi_update(THD *thd, TABLE_LIST *table_list, List *fields, List *values, COND *conds, ulonglong options, enum enum_duplicates handle_duplicates, bool ignore, SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex, multi_update **result); bool records_are_comparable(const TABLE *table); bool compare_record(const TABLE *table); #endif /* SQL_UPDATE_INCLUDED */ mysql/server/private/sql_get_diagnostics.h000064400000017273151027430560015104 0ustar00/* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_GET_DIAGNOSTICS_H #define SQL_GET_DIAGNOSTICS_H /** Diagnostics information forward reference. */ class Diagnostics_information; /** Sql_cmd_get_diagnostics represents a GET DIAGNOSTICS statement. The GET DIAGNOSTICS statement retrieves exception or completion condition information from a diagnostics area, usually pertaining to the last non-diagnostic SQL statement that was executed. */ class Sql_cmd_get_diagnostics : public Sql_cmd { public: /** Constructor, used to represent a GET DIAGNOSTICS statement. @param info Diagnostics information to be obtained. */ Sql_cmd_get_diagnostics(Diagnostics_information *info) : m_info(info) {} enum_sql_command sql_command_code() const override { return SQLCOM_GET_DIAGNOSTICS; } bool execute(THD *thd) override; private: /** The information to be obtained. */ Diagnostics_information *m_info; }; /** Represents the diagnostics information to be obtained. Diagnostic information is made available through statement information and condition information items. */ class Diagnostics_information : public Sql_alloc { public: /** Which diagnostics area to access. Only CURRENT is supported for now. */ enum Which_area { /** Access the first diagnostics area. */ CURRENT_AREA }; /** Set which diagnostics area to access. */ void set_which_da(Which_area area) { m_area= area; } /** Get which diagnostics area to access. */ Which_area get_which_da(void) const { return m_area; } /** Aggregate diagnostics information. @param thd The current thread. @param da The diagnostics area. @retval false on success. @retval true on error */ virtual bool aggregate(THD *thd, const Diagnostics_area *da) = 0; protected: /** Diagnostics_information objects are allocated in thd->mem_root. Do not rely on the destructor for any cleanup. */ virtual ~Diagnostics_information() { DBUG_ASSERT(false); } /** Evaluate a diagnostics information item in a specific context. @param thd The current thread. @param diag_item The diagnostics information item. @param ctx The context to evaluate the item. @retval false on success. @retval true on error. */ template bool evaluate(THD *thd, Diag_item *diag_item, Context ctx) { Item *value; /* Get this item's value. */ if (! (value= diag_item->get_value(thd, ctx))) return true; /* Set variable/parameter value. */ return diag_item->set_value(thd, &value); } private: /** Which diagnostics area to access. */ Which_area m_area; }; /** A diagnostics information item. Used to associate a specific diagnostics information item to a target variable. */ class Diagnostics_information_item : public Sql_alloc { public: /** Set a value for this item. @param thd The current thread. @param value The obtained value. @retval false on success. @retval true on error. */ bool set_value(THD *thd, Item **value); protected: /** Constructor, used to represent a diagnostics information item. @param target A target that gets the value of this item. */ Diagnostics_information_item(Item *target) : m_target(target) {} /** Diagnostics_information_item objects are allocated in thd->mem_root. Do not rely on the destructor for any cleanup. */ virtual ~Diagnostics_information_item() { DBUG_ASSERT(false); } private: /** The target variable that will receive the value of this item. */ Item *m_target; }; /** A statement information item. */ class Statement_information_item : public Diagnostics_information_item { public: /** The name of a statement information item. */ enum Name { NUMBER, ROW_COUNT }; /** Constructor, used to represent a statement information item. @param name The name of this item. @param target A target that gets the value of this item. */ Statement_information_item(Name name, Item *target) : Diagnostics_information_item(target), m_name(name) {} /** Obtain value of this statement information item. */ Item *get_value(THD *thd, const Diagnostics_area *da); private: /** The name of this statement information item. */ Name m_name; }; /** Statement information. @remark Provides information about the execution of a statement. */ class Statement_information : public Diagnostics_information { public: /** Constructor, used to represent the statement information of a GET DIAGNOSTICS statement. @param items List of requested statement information items. */ Statement_information(List *items) : m_items(items) {} /** Obtain statement information in the context of a diagnostics area. */ bool aggregate(THD *thd, const Diagnostics_area *da) override; private: /* List of statement information items. */ List *m_items; }; /** A condition information item. */ class Condition_information_item : public Diagnostics_information_item { public: /** The name of a condition information item. */ enum Name { CLASS_ORIGIN, SUBCLASS_ORIGIN, CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME, CATALOG_NAME, SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, CURSOR_NAME, MESSAGE_TEXT, MYSQL_ERRNO, RETURNED_SQLSTATE }; /** Constructor, used to represent a condition information item. @param name The name of this item. @param target A target that gets the value of this item. */ Condition_information_item(Name name, Item *target) : Diagnostics_information_item(target), m_name(name) {} /** Obtain value of this condition information item. */ Item *get_value(THD *thd, const Sql_condition *cond); private: /** The name of this condition information item. */ Name m_name; /** Create an string item to represent a condition item string. */ Item *make_utf8_string_item(THD *thd, const String *str); }; /** Condition information. @remark Provides information about conditions raised during the execution of a statement. */ class Condition_information : public Diagnostics_information { public: /** Constructor, used to represent the condition information of a GET DIAGNOSTICS statement. @param cond_number_expr Number that identifies the diagnostic condition. @param items List of requested condition information items. */ Condition_information(Item *cond_number_expr, List *items) : m_cond_number_expr(cond_number_expr), m_items(items) {} /** Obtain condition information in the context of a diagnostics area. */ bool aggregate(THD *thd, const Diagnostics_area *da) override; private: /** Number that identifies the diagnostic condition for which information is to be obtained. */ Item *m_cond_number_expr; /** List of condition information items. */ List *m_items; }; #endif mysql/server/private/sql_tablespace.h000064400000001674151027430560014037 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_TABLESPACE_INCLUDED #define SQL_TABLESPACE_INCLUDED class THD; class st_alter_tablespace; int mysql_alter_tablespace(THD* thd, st_alter_tablespace *ts_info); #endif /* SQL_TABLESPACE_INCLUDED */ mysql/server/private/myisammrg.h000064400000011441151027430560013053 0ustar00/* Copyright (c) 2000-2002, 2004, 2006-2008 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file should be included when using merge_isam_functions */ #ifndef _myisammrg_h #define _myisammrg_h #ifdef __cplusplus extern "C" { #endif #ifndef _my_base_h #include #endif #ifndef _myisam_h #include #endif #include #define MYRG_NAME_EXT ".MRG" #define MYRG_NAME_TMPEXT ".MRG_TMP" /* In which table to INSERT rows */ #define MERGE_INSERT_DISABLED 0 #define MERGE_INSERT_TO_FIRST 1 #define MERGE_INSERT_TO_LAST 2 extern TYPELIB merge_insert_method; /* Param to/from myrg_info */ typedef struct st_mymerge_info /* Struct from h_info */ { ulonglong records; /* Records in database */ ulonglong deleted; /* Deleted records in database */ ulonglong recpos; /* Pos for last used record */ ulonglong data_file_length; ulonglong dupp_key_pos; /* Offset of the Duplicate key in the merge table */ uint reclength; /* Recordlength */ int errkey; /* With key was duplicated on err */ uint options; /* HA_OPTION_... used */ ulong *rec_per_key; /* for sql optimizing */ } MYMERGE_INFO; typedef struct st_myrg_table_info { struct st_myisam_info *table; ulonglong file_offset; } MYRG_TABLE; typedef struct st_myrg_info { MYRG_TABLE *open_tables,*current_table,*end_table,*last_used_table; ulonglong records; /* records in tables */ ulonglong del; /* Removed records */ ulonglong data_file_length; ulong cache_size; uint merge_insert_method; uint tables,options,reclength,keys; uint key_parts; my_bool cache_in_use; /* If MERGE children attached to parent. See top comment in ha_myisammrg.cc */ my_bool children_attached; LIST open_list; QUEUE by_key; ulong *rec_per_key_part; /* for sql optimizing */ mysql_mutex_t mutex; } MYRG_INFO; /* Prototypes for merge-functions */ extern int myrg_close(MYRG_INFO *file); extern int myrg_delete(MYRG_INFO *file,const uchar *buff); extern MYRG_INFO *myrg_open(const char *name,int mode,int wait_if_locked); extern MYRG_INFO *myrg_parent_open(const char *parent_name, int (*callback)(void*, const char*), void *callback_param); extern int myrg_attach_children(MYRG_INFO *m_info, int handle_locking, MI_INFO *(*callback)(void*), void *callback_param, my_bool *need_compat_check); extern int myrg_detach_children(MYRG_INFO *m_info); extern int myrg_panic(enum ha_panic_function function); extern int myrg_rfirst(MYRG_INFO *file,uchar *buf,int inx); extern int myrg_rlast(MYRG_INFO *file,uchar *buf,int inx); extern int myrg_rnext(MYRG_INFO *file,uchar *buf,int inx); extern int myrg_rprev(MYRG_INFO *file,uchar *buf,int inx); extern int myrg_rnext_same(MYRG_INFO *file,uchar *buf); extern int myrg_rkey(MYRG_INFO *info,uchar *buf,int inx, const uchar *key, key_part_map keypart_map, enum ha_rkey_function search_flag); extern int myrg_rrnd(MYRG_INFO *file,uchar *buf,ulonglong pos); extern int myrg_rsame(MYRG_INFO *file,uchar *record,int inx); extern int myrg_update(MYRG_INFO *file,const uchar *old, const uchar *new_rec); extern int myrg_write(MYRG_INFO *info,const uchar *rec); extern int myrg_status(MYRG_INFO *file,MYMERGE_INFO *x,int flag); extern int myrg_lock_database(MYRG_INFO *file,int lock_type); extern int myrg_create(const char *name, const char **table_names, uint insert_method, my_bool fix_names); extern int myrg_extra(MYRG_INFO *file,enum ha_extra_function function, void *extra_arg); extern int myrg_reset(MYRG_INFO *info); extern void myrg_extrafunc(MYRG_INFO *info,invalidator_by_filename inv); extern ha_rows myrg_records_in_range(MYRG_INFO *info, int inx, const key_range *min_key, const key_range *max_key, page_range *pages); extern ha_rows myrg_records(MYRG_INFO *info); extern ulonglong myrg_position(MYRG_INFO *info); #ifdef __cplusplus } #endif #endif mysql/server/private/my_time.h000064400000024256151027430560012521 0ustar00/* Copyright (c) 2004, 2011, Oracle and/or its affiliates. Copyright (c) 2017, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This is a private header of sql-common library, containing declarations for my_time.c */ #ifndef _my_time_h_ #define _my_time_h_ #include "mysql_time.h" #include "my_decimal_limits.h" C_MODE_START extern MYSQL_PLUGIN_IMPORT ulonglong log_10_int[20]; extern uchar days_in_month[]; #define MY_TIME_T_MAX LONG_MAX #define MY_TIME_T_MIN LONG_MIN /* Time handling defaults */ #define TIMESTAMP_MAX_YEAR 2038 #define TIMESTAMP_MIN_YEAR (1900 + YY_PART_YEAR - 1) #define TIMESTAMP_MAX_VALUE INT_MAX32 #define TIMESTAMP_MIN_VALUE 0 /* two-digit years < this are 20..; >= this are 19.. */ #define YY_PART_YEAR 70 /* check for valid times only if the range of time_t is greater than the range of my_time_t */ #if SIZEOF_TIME_T > 4 || defined(TIME_T_UNSIGNED) # define IS_TIME_T_VALID_FOR_TIMESTAMP(x) \ ((x) <= TIMESTAMP_MAX_VALUE && \ (x) >= TIMESTAMP_MIN_VALUE) #else # define IS_TIME_T_VALID_FOR_TIMESTAMP(x) \ ((x) >= TIMESTAMP_MIN_VALUE) #endif /* Flags to str_to_datetime */ #define C_TIME_NO_ZERO_IN_DATE (1UL << 23) /* == MODE_NO_ZERO_IN_DATE */ #define C_TIME_NO_ZERO_DATE (1UL << 24) /* == MODE_NO_ZERO_DATE */ #define C_TIME_INVALID_DATES (1UL << 25) /* == MODE_INVALID_DATES */ #define MYSQL_TIME_WARN_TRUNCATED 1U #define MYSQL_TIME_WARN_OUT_OF_RANGE 2U #define MYSQL_TIME_WARN_EDOM 4U #define MYSQL_TIME_WARN_ZERO_DATE 8U #define MYSQL_TIME_NOTE_TRUNCATED 16U #define MYSQL_TIME_WARN_WARNINGS (MYSQL_TIME_WARN_TRUNCATED|\ MYSQL_TIME_WARN_OUT_OF_RANGE|\ MYSQL_TIME_WARN_EDOM|\ MYSQL_TIME_WARN_ZERO_DATE) #define MYSQL_TIME_WARN_NOTES (MYSQL_TIME_NOTE_TRUNCATED) #define MYSQL_TIME_WARN_HAVE_WARNINGS(x) MY_TEST((x) & MYSQL_TIME_WARN_WARNINGS) #define MYSQL_TIME_WARN_HAVE_NOTES(x) MY_TEST((x) & MYSQL_TIME_WARN_NOTES) /* Useful constants */ #define SECONDS_IN_24H 86400L /* Limits for the INTERVAL data type */ /* Number of hours between '0001-01-01 00h' and '9999-12-31 23h' */ #define TIME_MAX_INTERVAL_HOUR 87649415 #define TIME_MAX_INTERVAL_HOUR_CHAR_LENGTH 8 /* Number of full days between '0001-01-01' and '9999-12-31'*/ #define TIME_MAX_INTERVAL_DAY 3652058 /*87649415/24*/ #define TIME_MAX_INTERVAL_DAY_CHAR_LENGTH 7 /* Limits for the TIME data type */ #define TIME_MAX_HOUR 838 #define TIME_MAX_MINUTE 59 #define TIME_MAX_SECOND 59 #define TIME_MAX_SECOND_PART 999999 #define TIME_SECOND_PART_FACTOR (TIME_MAX_SECOND_PART+1) #define TIME_SECOND_PART_DIGITS 6 #define TIME_MAX_VALUE (TIME_MAX_HOUR*10000 + TIME_MAX_MINUTE*100 + TIME_MAX_SECOND) #define TIME_MAX_VALUE_SECONDS (TIME_MAX_HOUR * 3600L + \ TIME_MAX_MINUTE * 60L + TIME_MAX_SECOND) /* Structure to return status from str_to_datetime(), str_to_time(). */ typedef struct st_mysql_time_status { int warnings; uint precision; uint nanoseconds; } MYSQL_TIME_STATUS; static inline void my_time_status_init(MYSQL_TIME_STATUS *status) { status->warnings= 0; status->precision= 0; status->nanoseconds= 0; } my_bool check_date(const MYSQL_TIME *ltime, my_bool not_zero_date, ulonglong flags, int *was_cut); my_bool str_to_DDhhmmssff(const char *str, size_t length, MYSQL_TIME *l_time, ulong max_hour, MYSQL_TIME_STATUS *status); my_bool str_to_datetime_or_date_or_time(const char *str, size_t length, MYSQL_TIME *to, ulonglong flag, MYSQL_TIME_STATUS *status, ulong time_max_hour, ulong time_err_hour); my_bool str_to_datetime_or_date_or_interval_hhmmssff(const char *str, size_t length, MYSQL_TIME *to, ulonglong flag, MYSQL_TIME_STATUS *status, ulong time_max_hour, ulong time_err_hour); my_bool str_to_datetime_or_date_or_interval_day(const char *str, size_t length, MYSQL_TIME *to, ulonglong flag, MYSQL_TIME_STATUS *status, ulong time_max_hour, ulong time_err_hour); my_bool str_to_datetime_or_date(const char *str, size_t length, MYSQL_TIME *to, ulonglong flags, MYSQL_TIME_STATUS *status); longlong number_to_datetime_or_date(longlong nr, ulong sec_part, MYSQL_TIME *time_res, ulonglong flags, int *was_cut); int number_to_time_only(my_bool neg, ulonglong nr, ulong sec_part, ulong max_hour, MYSQL_TIME *to, int *was_cut); ulonglong TIME_to_ulonglong_datetime(const MYSQL_TIME *); ulonglong TIME_to_ulonglong_date(const MYSQL_TIME *); ulonglong TIME_to_ulonglong_time(const MYSQL_TIME *); ulonglong TIME_to_ulonglong(const MYSQL_TIME *); double TIME_to_double(const MYSQL_TIME *my_time); int check_time_range(struct st_mysql_time *my_time, uint dec, int *warning); my_bool check_datetime_range(const MYSQL_TIME *ltime); long calc_daynr(uint year,uint month,uint day); uint calc_days_in_year(uint year); uint year_2000_handling(uint year); void my_init_time(void); /* Function to check sanity of a TIMESTAMP value DESCRIPTION Check if a given MYSQL_TIME value fits in TIMESTAMP range. This function doesn't make precise check, but rather a rough estimate. RETURN VALUES TRUE The value seems sane FALSE The MYSQL_TIME value is definitely out of range */ static inline my_bool validate_timestamp_range(const MYSQL_TIME *t) { if ((t->year > TIMESTAMP_MAX_YEAR || t->year < TIMESTAMP_MIN_YEAR) || (t->year == TIMESTAMP_MAX_YEAR && (t->month > 1 || t->day > 19)) || (t->year == TIMESTAMP_MIN_YEAR && (t->month < 12 || t->day < 31))) return FALSE; return TRUE; } /* Can't include mysqld_error.h, it needs mysys to build, thus hardcode 2 error values here. */ #ifndef ER_WARN_DATA_OUT_OF_RANGE #define ER_WARN_DATA_OUT_OF_RANGE 1264 #define ER_WARN_INVALID_TIMESTAMP 1299 #endif my_time_t my_system_gmt_sec(const MYSQL_TIME *t, long *my_timezone, uint *error_code); void set_zero_time(MYSQL_TIME *tm, enum enum_mysql_timestamp_type time_type); /* Required buffer length for my_time_to_str, my_date_to_str, my_datetime_to_str and TIME_to_string functions. Note, that the caller is still responsible to check that given TIME structure has values in valid ranges, otherwise size of the buffer could be not enough. We also rely on the fact that even wrong values sent using binary protocol fit in this buffer. */ #define MAX_DATE_STRING_REP_LENGTH 30 #define AUTO_SEC_PART_DIGITS DECIMAL_NOT_SPECIFIED int my_interval_DDhhmmssff_to_str(const MYSQL_TIME *, char *to, uint digits); int my_time_to_str(const MYSQL_TIME *l_time, char *to, uint digits); int my_date_to_str(const MYSQL_TIME *l_time, char *to); int my_datetime_to_str(const MYSQL_TIME *l_time, char *to, uint digits); int my_TIME_to_str(const MYSQL_TIME *l_time, char *to, uint digits); int my_timeval_to_str(const struct timeval *tm, char *to, uint dec); static inline longlong sec_part_shift(longlong second_part, uint digits) { return second_part / (longlong)log_10_int[TIME_SECOND_PART_DIGITS - digits]; } static inline longlong sec_part_unshift(longlong second_part, uint digits) { return second_part * (longlong)log_10_int[TIME_SECOND_PART_DIGITS - digits]; } /* Date/time rounding and truncation functions */ static inline long my_time_fraction_remainder(long nr, uint decimals) { return nr % (long) log_10_int[TIME_SECOND_PART_DIGITS - decimals]; } static inline void my_datetime_trunc(MYSQL_TIME *ltime, uint decimals) { ltime->second_part-= my_time_fraction_remainder(ltime->second_part, decimals); } static inline void my_time_trunc(MYSQL_TIME *ltime, uint decimals) { ltime->second_part-= my_time_fraction_remainder(ltime->second_part, decimals); if (!ltime->second_part && ltime->neg && !ltime->hour && !ltime->minute && !ltime->second) ltime->neg= FALSE; } #ifdef _WIN32 #define suseconds_t long #endif static inline void my_timeval_trunc(struct timeval *tv, uint decimals) { tv->tv_usec-= (suseconds_t) my_time_fraction_remainder(tv->tv_usec, decimals); } #define hrtime_to_my_time(X) ((my_time_t)hrtime_to_time(X)) /* Available interval types used in any statement. 'interval_type' must be sorted so that simple intervals comes first, ie year, quarter, month, week, day, hour, etc. The order based on interval size is also important and the intervals should be kept in a large to smaller order. (get_interval_value() depends on this) Note: If you change the order of elements in this enum you should fix order of elements in 'interval_type_to_name' and 'interval_names' arrays See also interval_type_to_name, get_interval_value, interval_names, append_interval */ enum interval_type { INTERVAL_YEAR, INTERVAL_QUARTER, INTERVAL_MONTH, INTERVAL_WEEK, INTERVAL_DAY, INTERVAL_HOUR, INTERVAL_MINUTE, INTERVAL_SECOND, INTERVAL_MICROSECOND, INTERVAL_YEAR_MONTH, INTERVAL_DAY_HOUR, INTERVAL_DAY_MINUTE, INTERVAL_DAY_SECOND, INTERVAL_HOUR_MINUTE, INTERVAL_HOUR_SECOND, INTERVAL_MINUTE_SECOND, INTERVAL_DAY_MICROSECOND, INTERVAL_HOUR_MICROSECOND, INTERVAL_MINUTE_MICROSECOND, INTERVAL_SECOND_MICROSECOND, INTERVAL_LAST }; C_MODE_END #endif /* _my_time_h_ */ mysql/server/private/custom_conf.h000064400000002072151027430560013365 0ustar00/* Copyright (c) 2000, 2006 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef __MYSQL_CUSTOM_BUILD_CONFIG__ #define __MYSQL_CUSTOM_BUILD_CONFIG__ #define MYSQL_PORT 5002 #ifdef _WIN32 #define MYSQL_NAMEDPIPE "SwSqlServer" #define MYSQL_SERVICENAME "SwSqlServer" #define KEY_SERVICE_PARAMETERS "SYSTEM\\CurrentControlSet\\Services\\SwSqlServer\\Parameters" #endif #endif /* __MYSQL_CUSTOM_BUILD_CONFIG__ */ mysql/server/private/sql_analyze_stmt.h000064400000030611151027430560014437 0ustar00/* Copyright (c) 2015, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* == ANALYZE-stmt classes == This file contains classes for supporting "ANALYZE statement" feature. These are a set of data structures that can be used to store the data about how the statement executed. There are two kinds of data collection: 1. Various counters. We assume that incrementing counters has very low overhead. Because of that, execution code increments counters unconditionally (even when not running "ANALYZE $statement" commands. You run regular SELECT/ UPDATE/DELETE/etc and the counters are incremented). As a free bonus, this lets us print detailed information into the slow query log, should the query be slow. 2. Timing data. Measuring the time it took to run parts of query has noticeable overhead. Because of that, we measure the time only when running "ANALYZE $stmt"). */ /* fake microseconds as cycles if cycles isn't available */ static inline double timer_tracker_frequency() { #if (MY_TIMER_ROUTINE_CYCLES) return static_cast(sys_timer_info.cycles.frequency); #else return static_cast(sys_timer_info.microseconds.frequency); #endif } class Gap_time_tracker; void attach_gap_time_tracker(THD *thd, Gap_time_tracker *gap_tracker, ulonglong timeval); void process_gap_time_tracker(THD *thd, ulonglong timeval); /* A class for tracking time it takes to do a certain action */ class Exec_time_tracker { protected: ulonglong count; ulonglong cycles; ulonglong last_start; ulonglong measure() const { #if (MY_TIMER_ROUTINE_CYCLES) return my_timer_cycles(); #else return my_timer_microseconds(); #endif } void cycles_stop_tracking(THD *thd) { ulonglong end= measure(); cycles += end - last_start; process_gap_time_tracker(thd, end); if (my_gap_tracker) attach_gap_time_tracker(thd, my_gap_tracker, end); } /* The time spent after stop_tracking() call on this object and any subsequent time tracking call will be billed to this tracker. */ Gap_time_tracker *my_gap_tracker; public: Exec_time_tracker() : count(0), cycles(0), my_gap_tracker(NULL) {} void set_gap_tracker(Gap_time_tracker *gap_tracker) { my_gap_tracker= gap_tracker; } // interface for collecting time void start_tracking(THD *thd) { last_start= measure(); process_gap_time_tracker(thd, last_start); } void stop_tracking(THD *thd) { count++; cycles_stop_tracking(thd); } // interface for getting the time ulonglong get_loops() const { return count; } inline double cycles_to_ms(ulonglong cycles_arg) const { // convert 'cycles' to milliseconds. return 1000.0 * static_cast(cycles_arg) / timer_tracker_frequency(); } double get_time_ms() const { return cycles_to_ms(cycles); } ulonglong get_cycles() const { return cycles; } bool has_timed_statistics() const { return cycles > 0; } }; /* Tracker for time spent between the calls to Exec_time_tracker's {start| stop}_tracking(). @seealso Gap_time_tracker_data in sql_class.h */ class Gap_time_tracker { ulonglong cycles; public: Gap_time_tracker() : cycles(0) {} void log_time(ulonglong start, ulonglong end) { cycles += end - start; } double get_time_ms() const { // convert 'cycles' to milliseconds. return 1000.0 * static_cast(cycles) / timer_tracker_frequency(); } }; /* A class for counting certain actions (in all queries), and optionally collecting the timings (in ANALYZE queries). */ class Time_and_counter_tracker: public Exec_time_tracker { public: const bool timed; Time_and_counter_tracker(bool timed_arg) : timed(timed_arg) {} /* Loops are counted in both ANALYZE and regular queries, as this is cheap */ void incr_loops() { count++; } /* Unlike Exec_time_tracker::stop_tracking, we don't increase loops. */ void stop_tracking(THD *thd) { cycles_stop_tracking(thd); } }; #define ANALYZE_START_TRACKING(thd, tracker) \ { \ (tracker)->incr_loops(); \ if (unlikely((tracker)->timed)) \ { (tracker)->start_tracking(thd); } \ } #define ANALYZE_STOP_TRACKING(thd, tracker) \ if (unlikely((tracker)->timed)) \ { (tracker)->stop_tracking(thd); } /* Just a counter to increment one value. Wrapped in a class to be uniform with other counters used by ANALYZE. */ class Counter_tracker { public: Counter_tracker() : r_scans(0) {} ha_rows r_scans; inline void on_scan_init() { r_scans++; } bool has_scans() const { return (r_scans != 0); } ha_rows get_loops() const { return r_scans; } }; /* A class for collecting read statistics. The idea is that we run several scans. Each scans gets rows, and then filters some of them out. We count scans, rows, and rows left after filtering. (note: at the moment, the class is not actually tied to a physical table. It can be used to track reading from files, buffers, etc). */ class Table_access_tracker { public: Table_access_tracker() : r_scans(0), r_rows(0), r_rows_after_where(0) {} ha_rows r_scans; /* how many scans were ran on this join_tab */ ha_rows r_rows; /* How many rows we've got after that */ ha_rows r_rows_after_where; /* Rows after applying attached part of WHERE */ double get_avg_rows() const { return r_scans ? static_cast(r_rows) / static_cast(r_scans) : 0; } double get_filtered_after_where() const { return r_rows > 0 ? static_cast(r_rows_after_where) / static_cast(r_rows) : 1.0; } inline void on_scan_init() { r_scans++; } inline void on_record_read() { r_rows++; } inline void on_record_after_where() { r_rows_after_where++; } bool has_scans() const { return (r_scans != 0); } ha_rows get_loops() const { return r_scans; } }; class Json_writer; /* This stores the data about how filesort executed. A few things from here (e.g. r_used_pq, r_limit) belong to the query plan, however, these parameters are calculated right during the execution so we can't easily put them into the query plan. The class is designed to handle multiple invocations of filesort(). */ class Filesort_tracker : public Sql_alloc { public: Filesort_tracker(bool do_timing) : time_tracker(do_timing), r_limit(0), r_used_pq(0), r_examined_rows(0), r_sorted_rows(0), r_output_rows(0), sort_passes(0), sort_buffer_size(0), r_using_addons(false), r_packed_addon_fields(false), r_sort_keys_packed(false) {} /* Functions that filesort uses to report various things about its execution */ inline void report_use(THD *thd, ha_rows r_limit_arg) { if (!time_tracker.get_loops()) r_limit= r_limit_arg; else r_limit= (r_limit != r_limit_arg)? 0: r_limit_arg; ANALYZE_START_TRACKING(thd, &time_tracker); } inline void incr_pq_used() { r_used_pq++; } inline void report_row_numbers(ha_rows examined_rows, ha_rows sorted_rows, ha_rows returned_rows) { r_examined_rows += examined_rows; r_sorted_rows += sorted_rows; r_output_rows += returned_rows; } inline void report_merge_passes_at_start(ulong passes) { sort_passes -= passes; } inline void report_merge_passes_at_end(THD *thd, ulong passes) { ANALYZE_STOP_TRACKING(thd, &time_tracker); sort_passes += passes; } inline void report_sort_buffer_size(size_t bufsize) { if (sort_buffer_size) sort_buffer_size= ulonglong(-1); // multiple buffers of different sizes else sort_buffer_size= bufsize; } inline void report_addon_fields_format(bool addons_packed) { r_using_addons= true; r_packed_addon_fields= addons_packed; } inline void report_sort_keys_format(bool sort_keys_packed) { r_sort_keys_packed= sort_keys_packed; } void get_data_format(String *str); /* Functions to get the statistics */ void print_json_members(Json_writer *writer); ulonglong get_r_loops() const { return time_tracker.get_loops(); } double get_avg_examined_rows() const { return static_cast(r_examined_rows) / static_cast(get_r_loops()); } double get_avg_returned_rows() const { return static_cast(r_output_rows) / static_cast(get_r_loops()); } double get_r_filtered() const { return r_examined_rows > 0 ? static_cast(r_sorted_rows) / static_cast(r_examined_rows) : 1.0; } private: Time_and_counter_tracker time_tracker; //ulonglong r_loops; /* How many times filesort was invoked */ /* LIMIT is typically a constant. There is never "LIMIT 0". HA_POS_ERROR means we never had a limit 0 means different values of LIMIT were used in different filesort invocations other value means the same LIMIT value was used every time. */ ulonglong r_limit; ulonglong r_used_pq; /* How many times PQ was used */ /* How many rows were examined (before checking the select->cond) */ ulonglong r_examined_rows; /* How many rows were put into sorting (this is examined_rows minus rows that didn't pass the WHERE condition) */ ulonglong r_sorted_rows; /* How many rows were returned. This is equal to r_sorted_rows, unless there was a LIMIT N clause in which case filesort would not have returned more than N rows. */ ulonglong r_output_rows; /* How many sorts in total (divide by r_count to get the average) */ ulonglong sort_passes; /* 0 - means not used (or not known (ulonglong)-1 - multiple other - value */ ulonglong sort_buffer_size; bool r_using_addons; bool r_packed_addon_fields; bool r_sort_keys_packed; }; /** A class to collect data about how rowid filter is executed. It stores information about how rowid filter container is filled, containers size and observed selectivity. The observed selectivity is calculated in this way. Some elements elem_set are checked if they belong to container. Observed selectivity is calculated as the count of elem_set elements that belong to container devided by all elem_set elements. */ class Rowid_filter_tracker : public Sql_alloc { private: /* A member to track the time to fill the rowid filter */ Time_and_counter_tracker time_tracker; /* Size of the rowid filter container buffer */ size_t container_buff_size; /* Count of elements that were used to fill the rowid filter container */ uint container_elements; /* Elements counts used for observed selectivity calculation */ uint n_checks; uint n_positive_checks; public: Rowid_filter_tracker(bool do_timing) : time_tracker(do_timing), container_buff_size(0), container_elements(0), n_checks(0), n_positive_checks(0) {} inline void start_tracking(THD *thd) { ANALYZE_START_TRACKING(thd, &time_tracker); } inline void stop_tracking(THD *thd) { ANALYZE_STOP_TRACKING(thd, &time_tracker); } /* Save container buffer size in bytes */ inline void report_container_buff_size(uint elem_size) { container_buff_size= container_elements * elem_size / 8; } Time_and_counter_tracker *get_time_tracker() { return &time_tracker; } double get_time_fill_container_ms() const { return time_tracker.get_time_ms(); } void increment_checked_elements_count(bool was_checked) { n_checks++; if (was_checked) n_positive_checks++; } inline void increment_container_elements_count() { container_elements++; } uint get_container_elements() const { return container_elements; } uint get_container_lookups() { return n_checks; } double get_r_selectivity_pct() const { return n_checks ? static_cast(n_positive_checks) / static_cast(n_checks) : 0; } size_t get_container_buff_size() const { return container_buff_size; } }; mysql/server/private/pfs_transaction_provider.h000064400000005436151027430560016164 0ustar00/* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_TRANSACTION_PROVIDER_H #define PFS_TRANSACTION_PROVIDER_H /** @file include/pfs_transaction_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_TRANSACTION_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_TRANSACTION_CALL(M) pfs_ ## M ## _v1 C_MODE_START PSI_transaction_locker* pfs_get_thread_transaction_locker_v1(PSI_transaction_locker_state *state, const void *xid, ulonglong trxid, int isolation_level, my_bool read_only, my_bool autocommit); void pfs_start_transaction_v1(PSI_transaction_locker *locker, const char *src_file, uint src_line); void pfs_set_transaction_xid_v1(PSI_transaction_locker *locker, const void *xid, int xa_state); void pfs_set_transaction_xa_state_v1(PSI_transaction_locker *locker, int xa_state); void pfs_set_transaction_gtid_v1(PSI_transaction_locker *locker, const void *sid, const void *gtid_spec); void pfs_set_transaction_trxid_v1(PSI_transaction_locker *locker, const ulonglong *trxid); void pfs_inc_transaction_savepoints_v1(PSI_transaction_locker *locker, ulong count); void pfs_inc_transaction_rollback_to_savepoint_v1(PSI_transaction_locker *locker, ulong count); void pfs_inc_transaction_release_savepoint_v1(PSI_transaction_locker *locker, ulong count); void pfs_end_transaction_v1(PSI_transaction_locker *locker, my_bool commit); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_TRANSACTION_INTERFACE */ #endif mysql/server/private/probes_mysql_dtrace.h000064400000100355151027430560015112 0ustar00/* Generated by the Systemtap dtrace wrapper */ #define _SDT_HAS_SEMAPHORES 1 #define STAP_HAS_SEMAPHORES 1 /* deprecated */ #include /* MYSQL_CONNECTION_START ( unsigned long conn_id, char * user, char * host ) */ #if defined STAP_SDT_V1 #define MYSQL_CONNECTION_START_ENABLED() __builtin_expect (connection__start_semaphore, 0) #define mysql_connection__start_semaphore connection__start_semaphore #else #define MYSQL_CONNECTION_START_ENABLED() __builtin_expect (mysql_connection__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_connection__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_CONNECTION_START(arg1, arg2, arg3) \ DTRACE_PROBE3 (mysql, connection__start, arg1, arg2, arg3) /* MYSQL_CONNECTION_DONE ( int status, unsigned long conn_id ) */ #if defined STAP_SDT_V1 #define MYSQL_CONNECTION_DONE_ENABLED() __builtin_expect (connection__done_semaphore, 0) #define mysql_connection__done_semaphore connection__done_semaphore #else #define MYSQL_CONNECTION_DONE_ENABLED() __builtin_expect (mysql_connection__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_connection__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_CONNECTION_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, connection__done, arg1, arg2) /* MYSQL_COMMAND_START ( unsigned long conn_id, int command, char * user, char * host ) */ #if defined STAP_SDT_V1 #define MYSQL_COMMAND_START_ENABLED() __builtin_expect (command__start_semaphore, 0) #define mysql_command__start_semaphore command__start_semaphore #else #define MYSQL_COMMAND_START_ENABLED() __builtin_expect (mysql_command__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_command__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_COMMAND_START(arg1, arg2, arg3, arg4) \ DTRACE_PROBE4 (mysql, command__start, arg1, arg2, arg3, arg4) /* MYSQL_COMMAND_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_COMMAND_DONE_ENABLED() __builtin_expect (command__done_semaphore, 0) #define mysql_command__done_semaphore command__done_semaphore #else #define MYSQL_COMMAND_DONE_ENABLED() __builtin_expect (mysql_command__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_command__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_COMMAND_DONE(arg1) \ DTRACE_PROBE1 (mysql, command__done, arg1) /* MYSQL_QUERY_START ( char * query, unsigned long conn_id, char * db_name, char * user, char * host ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_START_ENABLED() __builtin_expect (query__start_semaphore, 0) #define mysql_query__start_semaphore query__start_semaphore #else #define MYSQL_QUERY_START_ENABLED() __builtin_expect (mysql_query__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_START(arg1, arg2, arg3, arg4, arg5) \ DTRACE_PROBE5 (mysql, query__start, arg1, arg2, arg3, arg4, arg5) /* MYSQL_QUERY_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_DONE_ENABLED() __builtin_expect (query__done_semaphore, 0) #define mysql_query__done_semaphore query__done_semaphore #else #define MYSQL_QUERY_DONE_ENABLED() __builtin_expect (mysql_query__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_DONE(arg1) \ DTRACE_PROBE1 (mysql, query__done, arg1) /* MYSQL_QUERY_PARSE_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_PARSE_START_ENABLED() __builtin_expect (query__parse__start_semaphore, 0) #define mysql_query__parse__start_semaphore query__parse__start_semaphore #else #define MYSQL_QUERY_PARSE_START_ENABLED() __builtin_expect (mysql_query__parse__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__parse__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_PARSE_START(arg1) \ DTRACE_PROBE1 (mysql, query__parse__start, arg1) /* MYSQL_QUERY_PARSE_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_PARSE_DONE_ENABLED() __builtin_expect (query__parse__done_semaphore, 0) #define mysql_query__parse__done_semaphore query__parse__done_semaphore #else #define MYSQL_QUERY_PARSE_DONE_ENABLED() __builtin_expect (mysql_query__parse__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__parse__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_PARSE_DONE(arg1) \ DTRACE_PROBE1 (mysql, query__parse__done, arg1) /* MYSQL_QUERY_CACHE_HIT ( char * query, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_CACHE_HIT_ENABLED() __builtin_expect (query__cache__hit_semaphore, 0) #define mysql_query__cache__hit_semaphore query__cache__hit_semaphore #else #define MYSQL_QUERY_CACHE_HIT_ENABLED() __builtin_expect (mysql_query__cache__hit_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__cache__hit_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_CACHE_HIT(arg1, arg2) \ DTRACE_PROBE2 (mysql, query__cache__hit, arg1, arg2) /* MYSQL_QUERY_CACHE_MISS ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_CACHE_MISS_ENABLED() __builtin_expect (query__cache__miss_semaphore, 0) #define mysql_query__cache__miss_semaphore query__cache__miss_semaphore #else #define MYSQL_QUERY_CACHE_MISS_ENABLED() __builtin_expect (mysql_query__cache__miss_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__cache__miss_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_CACHE_MISS(arg1) \ DTRACE_PROBE1 (mysql, query__cache__miss, arg1) /* MYSQL_QUERY_EXEC_START ( char * query, unsigned long connid, char * db_name, char * user, char * host, int exec_type ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_EXEC_START_ENABLED() __builtin_expect (query__exec__start_semaphore, 0) #define mysql_query__exec__start_semaphore query__exec__start_semaphore #else #define MYSQL_QUERY_EXEC_START_ENABLED() __builtin_expect (mysql_query__exec__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__exec__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_EXEC_START(arg1, arg2, arg3, arg4, arg5, arg6) \ DTRACE_PROBE6 (mysql, query__exec__start, arg1, arg2, arg3, arg4, arg5, arg6) /* MYSQL_QUERY_EXEC_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_QUERY_EXEC_DONE_ENABLED() __builtin_expect (query__exec__done_semaphore, 0) #define mysql_query__exec__done_semaphore query__exec__done_semaphore #else #define MYSQL_QUERY_EXEC_DONE_ENABLED() __builtin_expect (mysql_query__exec__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_query__exec__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_QUERY_EXEC_DONE(arg1) \ DTRACE_PROBE1 (mysql, query__exec__done, arg1) /* MYSQL_INSERT_ROW_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_INSERT_ROW_START_ENABLED() __builtin_expect (insert__row__start_semaphore, 0) #define mysql_insert__row__start_semaphore insert__row__start_semaphore #else #define MYSQL_INSERT_ROW_START_ENABLED() __builtin_expect (mysql_insert__row__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_insert__row__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INSERT_ROW_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, insert__row__start, arg1, arg2) /* MYSQL_INSERT_ROW_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_INSERT_ROW_DONE_ENABLED() __builtin_expect (insert__row__done_semaphore, 0) #define mysql_insert__row__done_semaphore insert__row__done_semaphore #else #define MYSQL_INSERT_ROW_DONE_ENABLED() __builtin_expect (mysql_insert__row__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_insert__row__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INSERT_ROW_DONE(arg1) \ DTRACE_PROBE1 (mysql, insert__row__done, arg1) /* MYSQL_UPDATE_ROW_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_UPDATE_ROW_START_ENABLED() __builtin_expect (update__row__start_semaphore, 0) #define mysql_update__row__start_semaphore update__row__start_semaphore #else #define MYSQL_UPDATE_ROW_START_ENABLED() __builtin_expect (mysql_update__row__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_update__row__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_UPDATE_ROW_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, update__row__start, arg1, arg2) /* MYSQL_UPDATE_ROW_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_UPDATE_ROW_DONE_ENABLED() __builtin_expect (update__row__done_semaphore, 0) #define mysql_update__row__done_semaphore update__row__done_semaphore #else #define MYSQL_UPDATE_ROW_DONE_ENABLED() __builtin_expect (mysql_update__row__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_update__row__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_UPDATE_ROW_DONE(arg1) \ DTRACE_PROBE1 (mysql, update__row__done, arg1) /* MYSQL_DELETE_ROW_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_DELETE_ROW_START_ENABLED() __builtin_expect (delete__row__start_semaphore, 0) #define mysql_delete__row__start_semaphore delete__row__start_semaphore #else #define MYSQL_DELETE_ROW_START_ENABLED() __builtin_expect (mysql_delete__row__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_delete__row__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_DELETE_ROW_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, delete__row__start, arg1, arg2) /* MYSQL_DELETE_ROW_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_DELETE_ROW_DONE_ENABLED() __builtin_expect (delete__row__done_semaphore, 0) #define mysql_delete__row__done_semaphore delete__row__done_semaphore #else #define MYSQL_DELETE_ROW_DONE_ENABLED() __builtin_expect (mysql_delete__row__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_delete__row__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_DELETE_ROW_DONE(arg1) \ DTRACE_PROBE1 (mysql, delete__row__done, arg1) /* MYSQL_READ_ROW_START ( char * db, char * table, int scan_flag ) */ #if defined STAP_SDT_V1 #define MYSQL_READ_ROW_START_ENABLED() __builtin_expect (read__row__start_semaphore, 0) #define mysql_read__row__start_semaphore read__row__start_semaphore #else #define MYSQL_READ_ROW_START_ENABLED() __builtin_expect (mysql_read__row__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_read__row__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_READ_ROW_START(arg1, arg2, arg3) \ DTRACE_PROBE3 (mysql, read__row__start, arg1, arg2, arg3) /* MYSQL_READ_ROW_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_READ_ROW_DONE_ENABLED() __builtin_expect (read__row__done_semaphore, 0) #define mysql_read__row__done_semaphore read__row__done_semaphore #else #define MYSQL_READ_ROW_DONE_ENABLED() __builtin_expect (mysql_read__row__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_read__row__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_READ_ROW_DONE(arg1) \ DTRACE_PROBE1 (mysql, read__row__done, arg1) /* MYSQL_INDEX_READ_ROW_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_INDEX_READ_ROW_START_ENABLED() __builtin_expect (index__read__row__start_semaphore, 0) #define mysql_index__read__row__start_semaphore index__read__row__start_semaphore #else #define MYSQL_INDEX_READ_ROW_START_ENABLED() __builtin_expect (mysql_index__read__row__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_index__read__row__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INDEX_READ_ROW_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, index__read__row__start, arg1, arg2) /* MYSQL_INDEX_READ_ROW_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_INDEX_READ_ROW_DONE_ENABLED() __builtin_expect (index__read__row__done_semaphore, 0) #define mysql_index__read__row__done_semaphore index__read__row__done_semaphore #else #define MYSQL_INDEX_READ_ROW_DONE_ENABLED() __builtin_expect (mysql_index__read__row__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_index__read__row__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INDEX_READ_ROW_DONE(arg1) \ DTRACE_PROBE1 (mysql, index__read__row__done, arg1) /* MYSQL_HANDLER_RDLOCK_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_HANDLER_RDLOCK_START_ENABLED() __builtin_expect (handler__rdlock__start_semaphore, 0) #define mysql_handler__rdlock__start_semaphore handler__rdlock__start_semaphore #else #define MYSQL_HANDLER_RDLOCK_START_ENABLED() __builtin_expect (mysql_handler__rdlock__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_handler__rdlock__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_HANDLER_RDLOCK_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, handler__rdlock__start, arg1, arg2) /* MYSQL_HANDLER_WRLOCK_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_HANDLER_WRLOCK_START_ENABLED() __builtin_expect (handler__wrlock__start_semaphore, 0) #define mysql_handler__wrlock__start_semaphore handler__wrlock__start_semaphore #else #define MYSQL_HANDLER_WRLOCK_START_ENABLED() __builtin_expect (mysql_handler__wrlock__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_handler__wrlock__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_HANDLER_WRLOCK_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, handler__wrlock__start, arg1, arg2) /* MYSQL_HANDLER_UNLOCK_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_HANDLER_UNLOCK_START_ENABLED() __builtin_expect (handler__unlock__start_semaphore, 0) #define mysql_handler__unlock__start_semaphore handler__unlock__start_semaphore #else #define MYSQL_HANDLER_UNLOCK_START_ENABLED() __builtin_expect (mysql_handler__unlock__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_handler__unlock__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_HANDLER_UNLOCK_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, handler__unlock__start, arg1, arg2) /* MYSQL_HANDLER_RDLOCK_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_HANDLER_RDLOCK_DONE_ENABLED() __builtin_expect (handler__rdlock__done_semaphore, 0) #define mysql_handler__rdlock__done_semaphore handler__rdlock__done_semaphore #else #define MYSQL_HANDLER_RDLOCK_DONE_ENABLED() __builtin_expect (mysql_handler__rdlock__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_handler__rdlock__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_HANDLER_RDLOCK_DONE(arg1) \ DTRACE_PROBE1 (mysql, handler__rdlock__done, arg1) /* MYSQL_HANDLER_WRLOCK_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_HANDLER_WRLOCK_DONE_ENABLED() __builtin_expect (handler__wrlock__done_semaphore, 0) #define mysql_handler__wrlock__done_semaphore handler__wrlock__done_semaphore #else #define MYSQL_HANDLER_WRLOCK_DONE_ENABLED() __builtin_expect (mysql_handler__wrlock__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_handler__wrlock__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_HANDLER_WRLOCK_DONE(arg1) \ DTRACE_PROBE1 (mysql, handler__wrlock__done, arg1) /* MYSQL_HANDLER_UNLOCK_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_HANDLER_UNLOCK_DONE_ENABLED() __builtin_expect (handler__unlock__done_semaphore, 0) #define mysql_handler__unlock__done_semaphore handler__unlock__done_semaphore #else #define MYSQL_HANDLER_UNLOCK_DONE_ENABLED() __builtin_expect (mysql_handler__unlock__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_handler__unlock__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_HANDLER_UNLOCK_DONE(arg1) \ DTRACE_PROBE1 (mysql, handler__unlock__done, arg1) /* MYSQL_FILESORT_START ( char * db, char * table ) */ #if defined STAP_SDT_V1 #define MYSQL_FILESORT_START_ENABLED() __builtin_expect (filesort__start_semaphore, 0) #define mysql_filesort__start_semaphore filesort__start_semaphore #else #define MYSQL_FILESORT_START_ENABLED() __builtin_expect (mysql_filesort__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_filesort__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_FILESORT_START(arg1, arg2) \ DTRACE_PROBE2 (mysql, filesort__start, arg1, arg2) /* MYSQL_FILESORT_DONE ( int status, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_FILESORT_DONE_ENABLED() __builtin_expect (filesort__done_semaphore, 0) #define mysql_filesort__done_semaphore filesort__done_semaphore #else #define MYSQL_FILESORT_DONE_ENABLED() __builtin_expect (mysql_filesort__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_filesort__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_FILESORT_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, filesort__done, arg1, arg2) /* MYSQL_SELECT_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_SELECT_START_ENABLED() __builtin_expect (select__start_semaphore, 0) #define mysql_select__start_semaphore select__start_semaphore #else #define MYSQL_SELECT_START_ENABLED() __builtin_expect (mysql_select__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_select__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_SELECT_START(arg1) \ DTRACE_PROBE1 (mysql, select__start, arg1) /* MYSQL_SELECT_DONE ( int status, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_SELECT_DONE_ENABLED() __builtin_expect (select__done_semaphore, 0) #define mysql_select__done_semaphore select__done_semaphore #else #define MYSQL_SELECT_DONE_ENABLED() __builtin_expect (mysql_select__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_select__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_SELECT_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, select__done, arg1, arg2) /* MYSQL_INSERT_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_INSERT_START_ENABLED() __builtin_expect (insert__start_semaphore, 0) #define mysql_insert__start_semaphore insert__start_semaphore #else #define MYSQL_INSERT_START_ENABLED() __builtin_expect (mysql_insert__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_insert__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INSERT_START(arg1) \ DTRACE_PROBE1 (mysql, insert__start, arg1) /* MYSQL_INSERT_DONE ( int status, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_INSERT_DONE_ENABLED() __builtin_expect (insert__done_semaphore, 0) #define mysql_insert__done_semaphore insert__done_semaphore #else #define MYSQL_INSERT_DONE_ENABLED() __builtin_expect (mysql_insert__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_insert__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INSERT_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, insert__done, arg1, arg2) /* MYSQL_INSERT_SELECT_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_INSERT_SELECT_START_ENABLED() __builtin_expect (insert__select__start_semaphore, 0) #define mysql_insert__select__start_semaphore insert__select__start_semaphore #else #define MYSQL_INSERT_SELECT_START_ENABLED() __builtin_expect (mysql_insert__select__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_insert__select__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INSERT_SELECT_START(arg1) \ DTRACE_PROBE1 (mysql, insert__select__start, arg1) /* MYSQL_INSERT_SELECT_DONE ( int status, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_INSERT_SELECT_DONE_ENABLED() __builtin_expect (insert__select__done_semaphore, 0) #define mysql_insert__select__done_semaphore insert__select__done_semaphore #else #define MYSQL_INSERT_SELECT_DONE_ENABLED() __builtin_expect (mysql_insert__select__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_insert__select__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_INSERT_SELECT_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, insert__select__done, arg1, arg2) /* MYSQL_UPDATE_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_UPDATE_START_ENABLED() __builtin_expect (update__start_semaphore, 0) #define mysql_update__start_semaphore update__start_semaphore #else #define MYSQL_UPDATE_START_ENABLED() __builtin_expect (mysql_update__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_update__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_UPDATE_START(arg1) \ DTRACE_PROBE1 (mysql, update__start, arg1) /* MYSQL_UPDATE_DONE ( int status, unsigned long rowsmatches, unsigned long rowschanged ) */ #if defined STAP_SDT_V1 #define MYSQL_UPDATE_DONE_ENABLED() __builtin_expect (update__done_semaphore, 0) #define mysql_update__done_semaphore update__done_semaphore #else #define MYSQL_UPDATE_DONE_ENABLED() __builtin_expect (mysql_update__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_update__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_UPDATE_DONE(arg1, arg2, arg3) \ DTRACE_PROBE3 (mysql, update__done, arg1, arg2, arg3) /* MYSQL_MULTI_UPDATE_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_MULTI_UPDATE_START_ENABLED() __builtin_expect (multi__update__start_semaphore, 0) #define mysql_multi__update__start_semaphore multi__update__start_semaphore #else #define MYSQL_MULTI_UPDATE_START_ENABLED() __builtin_expect (mysql_multi__update__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_multi__update__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_MULTI_UPDATE_START(arg1) \ DTRACE_PROBE1 (mysql, multi__update__start, arg1) /* MYSQL_MULTI_UPDATE_DONE ( int status, unsigned long rowsmatches, unsigned long rowschanged ) */ #if defined STAP_SDT_V1 #define MYSQL_MULTI_UPDATE_DONE_ENABLED() __builtin_expect (multi__update__done_semaphore, 0) #define mysql_multi__update__done_semaphore multi__update__done_semaphore #else #define MYSQL_MULTI_UPDATE_DONE_ENABLED() __builtin_expect (mysql_multi__update__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_multi__update__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_MULTI_UPDATE_DONE(arg1, arg2, arg3) \ DTRACE_PROBE3 (mysql, multi__update__done, arg1, arg2, arg3) /* MYSQL_DELETE_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_DELETE_START_ENABLED() __builtin_expect (delete__start_semaphore, 0) #define mysql_delete__start_semaphore delete__start_semaphore #else #define MYSQL_DELETE_START_ENABLED() __builtin_expect (mysql_delete__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_delete__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_DELETE_START(arg1) \ DTRACE_PROBE1 (mysql, delete__start, arg1) /* MYSQL_DELETE_DONE ( int status, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_DELETE_DONE_ENABLED() __builtin_expect (delete__done_semaphore, 0) #define mysql_delete__done_semaphore delete__done_semaphore #else #define MYSQL_DELETE_DONE_ENABLED() __builtin_expect (mysql_delete__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_delete__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_DELETE_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, delete__done, arg1, arg2) /* MYSQL_MULTI_DELETE_START ( char * query ) */ #if defined STAP_SDT_V1 #define MYSQL_MULTI_DELETE_START_ENABLED() __builtin_expect (multi__delete__start_semaphore, 0) #define mysql_multi__delete__start_semaphore multi__delete__start_semaphore #else #define MYSQL_MULTI_DELETE_START_ENABLED() __builtin_expect (mysql_multi__delete__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_multi__delete__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_MULTI_DELETE_START(arg1) \ DTRACE_PROBE1 (mysql, multi__delete__start, arg1) /* MYSQL_MULTI_DELETE_DONE ( int status, unsigned long rows ) */ #if defined STAP_SDT_V1 #define MYSQL_MULTI_DELETE_DONE_ENABLED() __builtin_expect (multi__delete__done_semaphore, 0) #define mysql_multi__delete__done_semaphore multi__delete__done_semaphore #else #define MYSQL_MULTI_DELETE_DONE_ENABLED() __builtin_expect (mysql_multi__delete__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_multi__delete__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_MULTI_DELETE_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, multi__delete__done, arg1, arg2) /* MYSQL_NET_READ_START ( ) */ #if defined STAP_SDT_V1 #define MYSQL_NET_READ_START_ENABLED() __builtin_expect (net__read__start_semaphore, 0) #define mysql_net__read__start_semaphore net__read__start_semaphore #else #define MYSQL_NET_READ_START_ENABLED() __builtin_expect (mysql_net__read__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_net__read__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_NET_READ_START() \ DTRACE_PROBE (mysql, net__read__start) /* MYSQL_NET_READ_DONE ( int status, unsigned long bytes ) */ #if defined STAP_SDT_V1 #define MYSQL_NET_READ_DONE_ENABLED() __builtin_expect (net__read__done_semaphore, 0) #define mysql_net__read__done_semaphore net__read__done_semaphore #else #define MYSQL_NET_READ_DONE_ENABLED() __builtin_expect (mysql_net__read__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_net__read__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_NET_READ_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, net__read__done, arg1, arg2) /* MYSQL_NET_WRITE_START ( unsigned long bytes ) */ #if defined STAP_SDT_V1 #define MYSQL_NET_WRITE_START_ENABLED() __builtin_expect (net__write__start_semaphore, 0) #define mysql_net__write__start_semaphore net__write__start_semaphore #else #define MYSQL_NET_WRITE_START_ENABLED() __builtin_expect (mysql_net__write__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_net__write__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_NET_WRITE_START(arg1) \ DTRACE_PROBE1 (mysql, net__write__start, arg1) /* MYSQL_NET_WRITE_DONE ( int status ) */ #if defined STAP_SDT_V1 #define MYSQL_NET_WRITE_DONE_ENABLED() __builtin_expect (net__write__done_semaphore, 0) #define mysql_net__write__done_semaphore net__write__done_semaphore #else #define MYSQL_NET_WRITE_DONE_ENABLED() __builtin_expect (mysql_net__write__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_net__write__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_NET_WRITE_DONE(arg1) \ DTRACE_PROBE1 (mysql, net__write__done, arg1) /* MYSQL_KEYCACHE_READ_START ( char * filepath, unsigned long bytes, unsigned long mem_used, unsigned long mem_free ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_READ_START_ENABLED() __builtin_expect (keycache__read__start_semaphore, 0) #define mysql_keycache__read__start_semaphore keycache__read__start_semaphore #else #define MYSQL_KEYCACHE_READ_START_ENABLED() __builtin_expect (mysql_keycache__read__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__read__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_READ_START(arg1, arg2, arg3, arg4) \ DTRACE_PROBE4 (mysql, keycache__read__start, arg1, arg2, arg3, arg4) /* MYSQL_KEYCACHE_READ_BLOCK ( unsigned long bytes ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_READ_BLOCK_ENABLED() __builtin_expect (keycache__read__block_semaphore, 0) #define mysql_keycache__read__block_semaphore keycache__read__block_semaphore #else #define MYSQL_KEYCACHE_READ_BLOCK_ENABLED() __builtin_expect (mysql_keycache__read__block_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__read__block_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_READ_BLOCK(arg1) \ DTRACE_PROBE1 (mysql, keycache__read__block, arg1) /* MYSQL_KEYCACHE_READ_HIT ( ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_READ_HIT_ENABLED() __builtin_expect (keycache__read__hit_semaphore, 0) #define mysql_keycache__read__hit_semaphore keycache__read__hit_semaphore #else #define MYSQL_KEYCACHE_READ_HIT_ENABLED() __builtin_expect (mysql_keycache__read__hit_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__read__hit_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_READ_HIT() \ DTRACE_PROBE (mysql, keycache__read__hit) /* MYSQL_KEYCACHE_READ_MISS ( ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_READ_MISS_ENABLED() __builtin_expect (keycache__read__miss_semaphore, 0) #define mysql_keycache__read__miss_semaphore keycache__read__miss_semaphore #else #define MYSQL_KEYCACHE_READ_MISS_ENABLED() __builtin_expect (mysql_keycache__read__miss_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__read__miss_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_READ_MISS() \ DTRACE_PROBE (mysql, keycache__read__miss) /* MYSQL_KEYCACHE_READ_DONE ( unsigned long mem_used, unsigned long mem_free ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_READ_DONE_ENABLED() __builtin_expect (keycache__read__done_semaphore, 0) #define mysql_keycache__read__done_semaphore keycache__read__done_semaphore #else #define MYSQL_KEYCACHE_READ_DONE_ENABLED() __builtin_expect (mysql_keycache__read__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__read__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_READ_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, keycache__read__done, arg1, arg2) /* MYSQL_KEYCACHE_WRITE_START ( char * filepath, unsigned long bytes, unsigned long mem_used, unsigned long mem_free ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_WRITE_START_ENABLED() __builtin_expect (keycache__write__start_semaphore, 0) #define mysql_keycache__write__start_semaphore keycache__write__start_semaphore #else #define MYSQL_KEYCACHE_WRITE_START_ENABLED() __builtin_expect (mysql_keycache__write__start_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__write__start_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_WRITE_START(arg1, arg2, arg3, arg4) \ DTRACE_PROBE4 (mysql, keycache__write__start, arg1, arg2, arg3, arg4) /* MYSQL_KEYCACHE_WRITE_BLOCK ( unsigned long bytes ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_WRITE_BLOCK_ENABLED() __builtin_expect (keycache__write__block_semaphore, 0) #define mysql_keycache__write__block_semaphore keycache__write__block_semaphore #else #define MYSQL_KEYCACHE_WRITE_BLOCK_ENABLED() __builtin_expect (mysql_keycache__write__block_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__write__block_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_WRITE_BLOCK(arg1) \ DTRACE_PROBE1 (mysql, keycache__write__block, arg1) /* MYSQL_KEYCACHE_WRITE_DONE ( unsigned long mem_used, unsigned long mem_free ) */ #if defined STAP_SDT_V1 #define MYSQL_KEYCACHE_WRITE_DONE_ENABLED() __builtin_expect (keycache__write__done_semaphore, 0) #define mysql_keycache__write__done_semaphore keycache__write__done_semaphore #else #define MYSQL_KEYCACHE_WRITE_DONE_ENABLED() __builtin_expect (mysql_keycache__write__done_semaphore, 0) #endif __extension__ extern unsigned short mysql_keycache__write__done_semaphore __attribute__ ((unused)) __attribute__ ((section (".probes"))); #define MYSQL_KEYCACHE_WRITE_DONE(arg1, arg2) \ DTRACE_PROBE2 (mysql, keycache__write__done, arg1, arg2) mysql/server/private/sql_plugin_compat.h000064400000004275151027430560014575 0ustar00/* Copyright (C) 2013 Sergei Golubchik and Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* old plugin api structures, used for backward compatibility */ #define upgrade_var(X) latest->X= X #define upgrade_str(X) strmake_buf(latest->X, X) #define downgrade_var(X) X= latest->X #define downgrade_str(X) strmake_buf(X, latest->X) /**************************************************************/ /* Authentication API, version 0x0100 *************************/ #define MIN_AUTHENTICATION_INTERFACE_VERSION 0x0100 struct MYSQL_SERVER_AUTH_INFO_0x0100 { const char *user_name; unsigned int user_name_length; const char *auth_string; unsigned long auth_string_length; char authenticated_as[49]; char external_user[512]; int password_used; const char *host_or_ip; unsigned int host_or_ip_length; void upgrade(MYSQL_SERVER_AUTH_INFO *latest) { upgrade_var(user_name); upgrade_var(user_name_length); upgrade_var(auth_string); upgrade_var(auth_string_length); upgrade_str(authenticated_as); upgrade_str(external_user); upgrade_var(password_used); upgrade_var(host_or_ip); upgrade_var(host_or_ip_length); } void downgrade(MYSQL_SERVER_AUTH_INFO *latest) { downgrade_var(user_name); downgrade_var(user_name_length); downgrade_var(auth_string); downgrade_var(auth_string_length); downgrade_str(authenticated_as); downgrade_str(external_user); downgrade_var(password_used); downgrade_var(host_or_ip); downgrade_var(host_or_ip_length); } }; /**************************************************************/ mysql/server/private/item_row.h000064400000012145151027430560012675 0ustar00#ifndef ITEM_ROW_INCLUDED #define ITEM_ROW_INCLUDED /* Copyright (c) 2002, 2013, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** Row items used for comparing rows and IN operations on rows: @verbatim (a, b, c) > (10, 10, 30) (a, b, c) = (select c, d, e, from t1 where x=12) (a, b, c) IN ((1,2,2), (3,4,5), (6,7,8) (a, b, c) IN (select c, d, e, from t1) @endverbatim */ /** Item which stores (x,y,...) and ROW(x,y,...). Note that this can be recursive: ((x,y),(z,t)) is a ROW of ROWs. */ class Item_row: public Item_fixed_hybrid, private Item_args, private Used_tables_and_const_cache { table_map not_null_tables_cache; /** If elements are made only of constants, of which one or more are NULL. For example, this item is (1,2,NULL), or ( (1,NULL), (2,3) ). */ bool with_null; public: Item_row(THD *thd, List &list) :Item_fixed_hybrid(thd), Item_args(thd, list), not_null_tables_cache(0), with_null(0) { } Item_row(THD *thd, Item_row *row) :Item_fixed_hybrid(thd), Item_args(thd, static_cast(row)), Used_tables_and_const_cache(), not_null_tables_cache(0), with_null(0) { } enum Type type() const override { return ROW_ITEM; }; const Type_handler *type_handler() const override { return &type_handler_row; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { return NULL; // Check with Vicentiu why it's called for Item_row } void illegal_method_call(const char *); bool is_null() override { return null_value; } void make_send_field(THD *thd, Send_field *) override { illegal_method_call((const char*)"make_send_field"); }; double val_real() override { illegal_method_call((const char*)"val"); return 0; }; longlong val_int() override { illegal_method_call((const char*)"val_int"); return 0; }; String *val_str(String *) override { illegal_method_call((const char*)"val_str"); return 0; }; my_decimal *val_decimal(my_decimal *) override { illegal_method_call((const char*)"val_decimal"); return 0; }; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { illegal_method_call((const char*)"get_date"); return true; } bool fix_fields(THD *thd, Item **ref) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; void cleanup() override; void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) override; table_map used_tables() const override { return used_tables_cache; }; bool const_item() const override { return const_item_cache; }; void update_used_tables() override { used_tables_and_const_cache_init(); used_tables_and_const_cache_update_and_join(arg_count, args); } table_map not_null_tables() const override { return not_null_tables_cache; } void print(String *str, enum_query_type query_type) override; bool walk(Item_processor processor, bool walk_subquery, void *arg) override { if (walk_args(processor, walk_subquery, arg)) return true; return (this->*processor)(arg); } Item *transform(THD *thd, Item_transformer transformer, uchar *arg) override; bool eval_not_null_tables(void *opt_arg) override; bool find_not_null_fields(table_map allowed) override; uint cols() const override { return arg_count; } Item* element_index(uint i) override { return args[i]; } Item** addr(uint i) override { return args + i; } bool check_cols(uint c) override; bool null_inside() override { return with_null; }; void bring_value() override; Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { Item_args::propagate_equal_fields(thd, Context_identity(), cond); return this; } bool excl_dep_on_table(table_map tab_map) override { return Item_args::excl_dep_on_table(tab_map); } bool excl_dep_on_grouping_fields(st_select_lex *sel) override { return Item_args::excl_dep_on_grouping_fields(sel); } bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override { return Item_args::excl_dep_on_in_subq_left_part(subq_pred); } bool check_vcol_func_processor(void *arg) override {return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override; }; #endif /* ITEM_ROW_INCLUDED */ mysql/server/private/wsrep_priv.h000064400000003142151027430560013245 0ustar00/* Copyright 2010-2023 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ //! @file declares symbols private to wsrep integration layer #ifndef WSREP_PRIV_H #define WSREP_PRIV_H #include "wsrep_api.h" #include "wsrep/server_state.hpp" ssize_t wsrep_sst_prepare (void** msg); wsrep_cb_status wsrep_sst_donate_cb (void* app_ctx, void* recv_ctx, const wsrep_buf_t* msg, const wsrep_gtid_t* state_id, const wsrep_buf_t* state, bool bypass); extern wsrep_uuid_t local_uuid; extern wsrep_seqno_t local_seqno; // a helper function bool wsrep_sst_received(THD*, const wsrep_uuid_t&, wsrep_seqno_t, const void*, size_t); void wsrep_notify_status(enum wsrep::server_state::state status, const wsrep::view* view= 0); #endif /* WSREP_PRIV_H */ mysql/server/private/mariadb.h000064400000002375151027430560012453 0ustar00/* Copyright (c) 2010, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Include file that should always be included first in all file in the sql directory. Used to ensure that some files, like my_global.h and my_config.h are always included first. It can also be used to speed up compilation by using precompiled headers. This file should include a minum set of header files used by all files and header files that are very seldom changed. It can also include some defines that all files should be aware of. */ #ifndef MARIADB_INCLUDED #define MARIADB_INCLUDED #include #endif /* MARIADB_INCLUDED */ mysql/server/private/pfs_metadata_provider.h000064400000003552151027430560015414 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_METADATA_PROVIDER_H #define PFS_METADATA_PROVIDER_H /** @file include/pfs_metadata_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_METADATA_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_METADATA_CALL(M) pfs_ ## M ## _v1 C_MODE_START PSI_metadata_lock* pfs_create_metadata_lock_v1 (void *identity, const MDL_key *key, opaque_mdl_type mdl_type, opaque_mdl_duration mdl_duration, opaque_mdl_status mdl_status, const char *src_file, uint src_line); void pfs_set_metadata_lock_status_v1 (PSI_metadata_lock *lock, opaque_mdl_status mdl_status); void pfs_destroy_metadata_lock_v1(PSI_metadata_lock *lock); struct PSI_metadata_locker* pfs_start_metadata_wait_v1 (struct PSI_metadata_locker_state_v1 *state, struct PSI_metadata_lock *mdl, const char *src_file, uint src_line); void pfs_end_metadata_wait_v1 (struct PSI_metadata_locker *locker, int rc); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_METADATA_INTERFACE */ #endif mysql/server/private/sql_callback.h000064400000003006151027430560013457 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_CALLBACK_INCLUDED #define SQL_CALLBACK_INCLUDED /** Macro used for an internal callback. The macro will check that the object exists and that the function is defined. If that is the case, it will call the function with the given parameters. If the object or the function is not defined, the callback will be considered successful (nothing needed to be done) and will therefore return no error. */ #define MYSQL_CALLBACK(OBJ, FUNC, PARAMS) \ do { \ if ((OBJ) && ((OBJ)->FUNC)) \ (OBJ)->FUNC PARAMS; \ } while (0) #define MYSQL_CALLBACK_ELSE(OBJ, FUNC, PARAMS, ELSE) \ (((OBJ) && ((OBJ)->FUNC)) ? (OBJ)->FUNC PARAMS : (ELSE)) #endif /* SQL_CALLBACK_INCLUDED */ mysql/server/private/wsrep_sst.h000064400000007557151027430560013114 0ustar00/* Copyright (C) 2013-2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #ifndef WSREP_SST_H #define WSREP_SST_H #include #include "wsrep/gtid.hpp" #include #include #define WSREP_SST_OPT_ROLE "--role" #define WSREP_SST_OPT_ADDR "--address" #define WSREP_SST_OPT_AUTH "--auth" #define WSREP_SST_OPT_DATA "--datadir" #define WSREP_SST_OPT_CONF "--defaults-file" #define WSREP_SST_OPT_CONF_SUFFIX "--defaults-group-suffix" #define WSREP_SST_OPT_CONF_EXTRA "--defaults-extra-file" #define WSREP_SST_OPT_PARENT "--parent" #define WSREP_SST_OPT_BINLOG "--binlog" #define WSREP_SST_OPT_BINLOG_INDEX "--binlog-index" #define WSREP_SST_OPT_PROGRESS "--progress" #define WSREP_SST_OPT_MYSQLD "--mysqld-args" // mysqldump-specific options #define WSREP_SST_OPT_USER "--user" #define WSREP_SST_OPT_PSWD "--password" #define WSREP_SST_OPT_HOST "--host" #define WSREP_SST_OPT_PORT "--port" #define WSREP_SST_OPT_LPORT "--local-port" // donor-specific #define WSREP_SST_OPT_SOCKET "--socket" #define WSREP_SST_OPT_GTID "--gtid" #define WSREP_SST_OPT_BYPASS "--bypass" #define WSREP_SST_OPT_GTID_DOMAIN_ID "--gtid-domain-id" #define WSREP_SST_MYSQLDUMP "mysqldump" #define WSREP_SST_RSYNC "rsync" #define WSREP_SST_SKIP "skip" #define WSREP_SST_MARIABACKUP "mariabackup" #define WSREP_SST_XTRABACKUP "xtrabackup" #define WSREP_SST_XTRABACKUPV2 "xtrabackupv2" #define WSREP_SST_DEFAULT WSREP_SST_RSYNC #define WSREP_SST_ADDRESS_AUTO "AUTO" #define WSREP_SST_AUTH_MASK "********" /* system variables */ extern const char* wsrep_sst_method; extern const char* wsrep_sst_receive_address; extern const char* wsrep_sst_donor; extern const char* wsrep_sst_auth; extern my_bool wsrep_sst_donor_rejects_queries; /*! Synchronizes applier thread start with init thread */ extern void wsrep_sst_grab(); /*! Init thread waits for SST completion */ extern bool wsrep_sst_wait(); /*! Signals wsrep that initialization is complete, writesets can be applied */ extern bool wsrep_sst_continue(); extern void wsrep_sst_auth_init(); extern void wsrep_sst_auth_free(); extern void wsrep_SE_init_grab(); /*! grab init critical section */ extern void wsrep_SE_init_wait(); /*! wait for SE init to complete */ extern void wsrep_SE_init_done(); /*! signal that SE init is complte */ extern void wsrep_SE_initialized(); /*! mark SE initialization complete */ /** Return a string containing the state transfer request string. Note that the string may contain a '\0' in the middle. */ std::string wsrep_sst_prepare(); /** Donate a SST. @param request SST request string received from the joiner. Note that the string may contain a '\0' in the middle. @param gtid Current position of the donor @param bypass If true, full SST is not needed. Joiner needs to be notified that it can continue starting from gtid. */ int wsrep_sst_donate(const std::string& request, const wsrep::gtid& gtid, bool bypass); #else #define wsrep_SE_initialized() do { } while(0) #define wsrep_SE_init_grab() do { } while(0) #define wsrep_SE_init_done() do { } while(0) #define wsrep_sst_continue() (0) #endif /* WSREP_SST_H */ mysql/server/private/log.h000064400000132003151027430560011625 0ustar00/* Copyright (c) 2005, 2016, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef LOG_H #define LOG_H #include "handler.h" /* my_xid */ #include "rpl_constants.h" class Relay_log_info; class Format_description_log_event; bool reopen_fstreams(const char *filename, FILE *outstream, FILE *errstream); void setup_log_handling(); bool trans_has_updated_trans_table(const THD* thd); bool stmt_has_updated_trans_table(const THD *thd); bool use_trans_cache(const THD* thd, bool is_transactional); bool ending_trans(THD* thd, const bool all); bool ending_single_stmt_trans(THD* thd, const bool all); bool trans_has_updated_non_trans_table(const THD* thd); bool stmt_has_updated_non_trans_table(const THD* thd); /* Transaction Coordinator log - a base abstract class for two different implementations */ class TC_LOG { public: int using_heuristic_recover(); TC_LOG() = default; virtual ~TC_LOG() = default; virtual int open(const char *opt_name)=0; virtual void close()=0; /* Transaction coordinator 2-phase commit. Must invoke the run_prepare_ordered and run_commit_ordered methods, as described below for these methods. In addition, must invoke THD::wait_for_prior_commit(), or equivalent wait, to ensure that one commit waits for another if registered to do so. */ virtual int log_and_order(THD *thd, my_xid xid, bool all, bool need_prepare_ordered, bool need_commit_ordered) = 0; virtual int unlog(ulong cookie, my_xid xid)=0; virtual int unlog_xa_prepare(THD *thd, bool all)= 0; virtual void commit_checkpoint_notify(void *cookie)= 0; protected: /* These methods are meant to be invoked from log_and_order() implementations to run any prepare_ordered() respectively commit_ordered() methods in participating handlers. They must be called using suitable thread syncronisation to ensure that they are each called in the correct commit order among all transactions. However, it is only necessary to call them if the corresponding flag passed to log_and_order is set (it is safe, but not required, to call them when the flag is false). The caller must be holding LOCK_prepare_ordered respectively LOCK_commit_ordered when calling these methods. */ void run_prepare_ordered(THD *thd, bool all); void run_commit_ordered(THD *thd, bool all); }; /* Locks used to ensure serialised execution of TC_LOG::run_prepare_ordered() and TC_LOG::run_commit_ordered(), or any other code that calls handler prepare_ordered() or commit_ordered() methods. */ extern mysql_mutex_t LOCK_prepare_ordered; extern mysql_cond_t COND_prepare_ordered; extern mysql_mutex_t LOCK_after_binlog_sync; extern mysql_mutex_t LOCK_commit_ordered; #ifdef HAVE_PSI_INTERFACE extern PSI_mutex_key key_LOCK_prepare_ordered, key_LOCK_commit_ordered; extern PSI_mutex_key key_LOCK_after_binlog_sync; extern PSI_cond_key key_COND_prepare_ordered; #endif class TC_LOG_DUMMY: public TC_LOG // use it to disable the logging { public: TC_LOG_DUMMY() = default; int open(const char *opt_name) override { return 0; } void close() override { } /* TC_LOG_DUMMY is only used when there are <= 1 XA-capable engines, and we only use internal XA during commit when >= 2 XA-capable engines participate. */ int log_and_order(THD *thd, my_xid xid, bool all, bool need_prepare_ordered, bool need_commit_ordered) override { DBUG_ASSERT(0); return 1; } int unlog(ulong cookie, my_xid xid) override { return 0; } int unlog_xa_prepare(THD *thd, bool all) override { return 0; } void commit_checkpoint_notify(void *cookie) override { DBUG_ASSERT(0); }; }; #define TC_LOG_PAGE_SIZE 8192 #ifdef HAVE_MMAP class TC_LOG_MMAP: public TC_LOG { public: // only to keep Sun Forte on sol9x86 happy typedef enum { PS_POOL, // page is in pool PS_ERROR, // last sync failed PS_DIRTY // new xids added since last sync } PAGE_STATE; struct pending_cookies { uint count; uint pending_count; ulong cookies[1]; }; private: typedef struct st_page { struct st_page *next; // page a linked in a fifo queue my_xid *start, *end; // usable area of a page my_xid *ptr; // next xid will be written here int size, free; // max and current number of free xid slots on the page int waiters; // number of waiters on condition PAGE_STATE state; // see above mysql_mutex_t lock; // to access page data or control structure mysql_cond_t cond; // to wait for a sync } PAGE; /* List of THDs for which to invoke commit_ordered(), in order. */ struct commit_entry { struct commit_entry *next; THD *thd; }; char logname[FN_REFLEN]; File fd; my_off_t file_length; uint npages, inited; uchar *data; struct st_page *pages, *syncing, *active, *pool, **pool_last_ptr; /* note that, e.g. LOCK_active is only used to protect 'active' pointer, to protect the content of the active page one has to use active->lock. Same for LOCK_pool and LOCK_sync */ mysql_mutex_t LOCK_active, LOCK_pool, LOCK_sync, LOCK_pending_checkpoint; mysql_cond_t COND_pool, COND_active; /* Queue of threads that need to call commit_ordered(). Access to this queue must be protected by LOCK_prepare_ordered. */ commit_entry *commit_ordered_queue; /* This flag and condition is used to reserve the queue while threads in it each run the commit_ordered() methods one after the other. Only once the last commit_ordered() in the queue is done can we start on a new queue run. Since we start this process in the first thread in the queue and finish in the last (and possibly different) thread, we need a condition variable for this (we cannot unlock a mutex in a different thread than the one who locked it). The condition is used together with the LOCK_prepare_ordered mutex. */ mysql_cond_t COND_queue_busy; my_bool commit_ordered_queue_busy; pending_cookies* pending_checkpoint; public: TC_LOG_MMAP(): inited(0), pending_checkpoint(0) {} int open(const char *opt_name) override; void close() override; int log_and_order(THD *thd, my_xid xid, bool all, bool need_prepare_ordered, bool need_commit_ordered) override; int unlog(ulong cookie, my_xid xid) override; int unlog_xa_prepare(THD *thd, bool all) override { return 0; } void commit_checkpoint_notify(void *cookie) override; int recover(); private: int log_one_transaction(my_xid xid); void get_active_from_pool(); int sync(); int overflow(); int delete_entry(ulong cookie); }; #else #define TC_LOG_MMAP TC_LOG_DUMMY #endif extern TC_LOG *tc_log; extern TC_LOG_MMAP tc_log_mmap; extern TC_LOG_DUMMY tc_log_dummy; /* log info errors */ #define LOG_INFO_EOF -1 #define LOG_INFO_IO -2 #define LOG_INFO_INVALID -3 #define LOG_INFO_SEEK -4 #define LOG_INFO_MEM -6 #define LOG_INFO_FATAL -7 #define LOG_INFO_IN_USE -8 #define LOG_INFO_EMFILE -9 /* bitmap to SQL_LOG::close() */ #define LOG_CLOSE_INDEX 1 #define LOG_CLOSE_TO_BE_OPENED 2 #define LOG_CLOSE_STOP_EVENT 4 #define LOG_CLOSE_DELAYED_CLOSE 8 /* Maximum unique log filename extension. Note: setting to 0x7FFFFFFF due to atol windows overflow/truncate. */ #define MAX_LOG_UNIQUE_FN_EXT 0x7FFFFFFF /* Number of warnings that will be printed to error log before extension number is exhausted. */ #define LOG_WARN_UNIQUE_FN_EXT_LEFT 1000 class Relay_log_info; /* Note that we destroy the lock mutex in the desctructor here. This means that object instances cannot be destroyed/go out of scope, until we have reset thd->current_linfo to NULL; */ typedef struct st_log_info { char log_file_name[FN_REFLEN]; my_off_t index_file_offset, index_file_start_offset; my_off_t pos; bool fatal; // if the purge happens to give us a negative offset st_log_info() : index_file_offset(0), index_file_start_offset(0), pos(0), fatal(0) { DBUG_ENTER("LOG_INFO"); log_file_name[0] = '\0'; DBUG_VOID_RETURN; } } LOG_INFO; /* Currently we have only 3 kinds of logging functions: old-fashioned logs, stdout and csv logging routines. */ #define MAX_LOG_HANDLERS_NUM 3 /* log event handler flags */ #define LOG_NONE 1U #define LOG_FILE 2U #define LOG_TABLE 4U class Log_event; class Rows_log_event; enum enum_log_type { LOG_UNKNOWN, LOG_NORMAL, LOG_BIN }; enum enum_log_state { LOG_OPENED, LOG_CLOSED, LOG_TO_BE_OPENED }; /* Use larger buffers when reading from and to binary log We make it one step smaller than 64K to account for malloc overhead. */ #define LOG_BIN_IO_SIZE MY_ALIGN_DOWN(65536-1, IO_SIZE) /* TODO use mmap instead of IO_CACHE for binlog (mmap+fsync is two times faster than write+fsync) */ class MYSQL_LOG { public: MYSQL_LOG(); virtual ~MYSQL_LOG() = default; void init_pthread_objects(); void cleanup(); bool open( #ifdef HAVE_PSI_INTERFACE PSI_file_key log_file_key, #endif const char *log_name, enum_log_type log_type, const char *new_name, ulong next_file_number, enum cache_type io_cache_type_arg); void close(uint exiting); inline bool is_open() { return log_state != LOG_CLOSED; } const char *generate_name(const char *log_name, const char *suffix, bool strip_ext, char *buff); virtual int generate_new_name(char *new_name, const char *log_name, ulong next_log_number); protected: /* LOCK_log is inited by init_pthread_objects() */ mysql_mutex_t LOCK_log; char *name; char log_file_name[FN_REFLEN]; char time_buff[20], db[NAME_LEN + 1]; bool write_error, inited; IO_CACHE log_file; enum_log_type log_type; volatile enum_log_state log_state; enum cache_type io_cache_type; friend class Log_event; #ifdef HAVE_PSI_INTERFACE /** Instrumentation key to use for file io in @c log_file */ PSI_file_key m_log_file_key; #endif bool init_and_set_log_file_name(const char *log_name, const char *new_name, ulong next_log_number, enum_log_type log_type_arg, enum cache_type io_cache_type_arg); }; /* Tell the io thread if we can delay the master info sync. */ #define SEMI_SYNC_SLAVE_DELAY_SYNC 1 /* Tell the io thread if the current event needs a ack. */ #define SEMI_SYNC_NEED_ACK 2 class MYSQL_QUERY_LOG: public MYSQL_LOG { public: MYSQL_QUERY_LOG() : last_time(0) {} void reopen_file(); bool write(time_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, const char *command_type, size_t command_type_len, const char *sql_text, size_t sql_text_len); bool write(THD *thd, time_t current_time, const char *user_host, size_t user_host_len, ulonglong query_utime, ulonglong lock_utime, bool is_command, const char *sql_text, size_t sql_text_len); bool open_slow_log(const char *log_name) { char buf[FN_REFLEN]; return open( #ifdef HAVE_PSI_INTERFACE key_file_slow_log, #endif generate_name(log_name, "-slow.log", 0, buf), LOG_NORMAL, 0, 0, WRITE_CACHE); } bool open_query_log(const char *log_name) { char buf[FN_REFLEN]; return open( #ifdef HAVE_PSI_INTERFACE key_file_query_log, #endif generate_name(log_name, ".log", 0, buf), LOG_NORMAL, 0, 0, WRITE_CACHE); } private: time_t last_time; }; /* We assign each binlog file an internal ID, used to identify them for unlog(). The IDs start from 0 and increment for each new binlog created. In unlog() we need to know the ID of the binlog file that the corresponding transaction was written into. We also need a special value for a corner case where there is no corresponding binlog id (since nothing was logged). And we need an error flag to mark that unlog() must return failure. We use the following macros to pack all of this information into the single ulong available with log_and_order() / unlog(). Note that we cannot use the value 0 for cookie, as that is reserved as error return value from log_and_order(). */ #define BINLOG_COOKIE_ERROR_RETURN 0 #define BINLOG_COOKIE_DUMMY_ID 1 #define BINLOG_COOKIE_BASE 2 #define BINLOG_COOKIE_DUMMY(error_flag) \ ( (BINLOG_COOKIE_DUMMY_ID<<1) | ((error_flag)&1) ) #define BINLOG_COOKIE_MAKE(id, error_flag) \ ( (((id)+BINLOG_COOKIE_BASE)<<1) | ((error_flag)&1) ) #define BINLOG_COOKIE_GET_ERROR_FLAG(c) ((c) & 1) #define BINLOG_COOKIE_GET_ID(c) ( ((ulong)(c)>>1) - BINLOG_COOKIE_BASE ) #define BINLOG_COOKIE_IS_DUMMY(c) \ ( ((ulong)(c)>>1) == BINLOG_COOKIE_DUMMY_ID ) class binlog_cache_mngr; class binlog_cache_data; struct rpl_gtid; struct wait_for_commit; class MYSQL_BIN_LOG: public TC_LOG, private MYSQL_LOG { #ifdef HAVE_PSI_INTERFACE /** The instrumentation key to use for @ LOCK_index. */ PSI_mutex_key m_key_LOCK_index; /** The instrumentation key to use for @ COND_relay_log_updated */ PSI_cond_key m_key_relay_log_update; /** The instrumentation key to use for @ COND_bin_log_updated */ PSI_cond_key m_key_bin_log_update; /** The instrumentation key to use for opening the log file. */ PSI_file_key m_key_file_log, m_key_file_log_cache; /** The instrumentation key to use for opening the log index file. */ PSI_file_key m_key_file_log_index, m_key_file_log_index_cache; PSI_cond_key m_key_COND_queue_busy; /** The instrumentation key to use for LOCK_binlog_end_pos. */ PSI_mutex_key m_key_LOCK_binlog_end_pos; #else static constexpr PSI_mutex_key m_key_LOCK_index= 0; static constexpr PSI_cond_key m_key_relay_log_update= 0; static constexpr PSI_cond_key m_key_bin_log_update= 0; static constexpr PSI_file_key m_key_file_log= 0, m_key_file_log_cache= 0; static constexpr PSI_file_key m_key_file_log_index= 0; static constexpr PSI_file_key m_key_file_log_index_cache= 0; static constexpr PSI_cond_key m_key_COND_queue_busy= 0; static constexpr PSI_mutex_key m_key_LOCK_binlog_end_pos= 0; #endif struct group_commit_entry { struct group_commit_entry *next; THD *thd; binlog_cache_mngr *cache_mngr; bool using_stmt_cache; bool using_trx_cache; /* Extra events (COMMIT/ROLLBACK/XID, and possibly INCIDENT) to be written during group commit. The incident_event is only valid if trx_data->has_incident() is true. */ Log_event *end_event; Log_event *incident_event; /* Set during group commit to record any per-thread error. */ int error; int commit_errno; IO_CACHE *error_cache; /* This is the `all' parameter for ha_commit_ordered(). */ bool all; /* True if we need to increment xid_count in trx_group_commit_leader() and decrement in unlog() (this is needed if there is a participating engine that does not implement the commit_checkpoint_request() handlerton method). */ bool need_unlog; /* Fields used to pass the necessary information to the last thread in a group commit, only used when opt_optimize_thread_scheduling is not set. */ bool check_purge; /* Flag used to optimise around wait_for_prior_commit. */ bool queued_by_other; ulong binlog_id; bool ro_1pc; // passes the binlog_cache_mngr::ro_1pc value to Gtid ctor }; /* When this is set, a RESET MASTER is in progress. Then we should not write any binlog checkpoints into the binlog (that could result in deadlock on LOCK_log, and we will delete all binlog files anyway). Instead we should signal COND_xid_list whenever a new binlog checkpoint arrives - when all have arrived, RESET MASTER will complete. */ uint reset_master_pending; ulong mark_xid_done_waiting; /* LOCK_log and LOCK_index are inited by init_pthread_objects() */ mysql_mutex_t LOCK_index; mysql_mutex_t LOCK_binlog_end_pos; mysql_mutex_t LOCK_xid_list; mysql_cond_t COND_xid_list; mysql_cond_t COND_relay_log_updated, COND_bin_log_updated; ulonglong bytes_written; IO_CACHE index_file; char index_file_name[FN_REFLEN]; /* purge_file is a temp file used in purge_logs so that the index file can be updated before deleting files from disk, yielding better crash recovery. It is created on demand the first time purge_logs is called and then reused for subsequent calls. It is cleaned up in cleanup(). */ IO_CACHE purge_index_file; char purge_index_file_name[FN_REFLEN]; /* The max size before rotation (usable only if log_type == LOG_BIN: binary logs and relay logs). For a binlog, max_size should be max_binlog_size. max_size is set in init(), and dynamically changed (when one does SET GLOBAL MAX_BINLOG_SIZE|MAX_RELAY_LOG_SIZE) from sys_vars.cc */ ulong max_size; /* Number generated by last call of find_uniq_filename(). Corresponds closely with current_binlog_id */ ulong last_used_log_number; // current file sequence number for load data infile binary logging uint file_id; uint open_count; // For replication int readers_count; /* Queue of transactions queued up to participate in group commit. */ group_commit_entry *group_commit_queue; /* Condition variable to mark that the group commit queue is busy. Used when each thread does it's own commit_ordered() (when binlog_optimize_thread_scheduling=1). Used with the LOCK_commit_ordered mutex. */ my_bool group_commit_queue_busy; mysql_cond_t COND_queue_busy; /* Total number of committed transactions. */ ulonglong num_commits; /* Number of group commits done. */ ulonglong num_group_commits; /* The reason why the group commit was grouped */ ulonglong group_commit_trigger_count, group_commit_trigger_timeout; ulonglong group_commit_trigger_lock_wait; /* binlog encryption data */ struct Binlog_crypt_data crypto; /* pointer to the sync period variable, for binlog this will be sync_binlog_period, for relay log this will be sync_relay_log_period */ uint *sync_period_ptr; uint sync_counter; bool state_file_deleted; bool binlog_state_recover_done; inline uint get_sync_period() { return *sync_period_ptr; } int write_to_file(IO_CACHE *cache); /* This is used to start writing to a new log file. The difference from new_file() is locking. new_file_without_locking() does not acquire LOCK_log. */ int new_file_without_locking(); int new_file_impl(); void do_checkpoint_request(ulong binlog_id); void purge(); int write_transaction_or_stmt(group_commit_entry *entry, uint64 commit_id); int queue_for_group_commit(group_commit_entry *entry); bool write_transaction_to_binlog_events(group_commit_entry *entry); void trx_group_commit_leader(group_commit_entry *leader); bool is_xidlist_idle_nolock(); public: /* A list of struct xid_count_per_binlog is used to keep track of how many XIDs are in prepared, but not committed, state in each binlog. And how many commit_checkpoint_request()'s are pending. When count drops to zero in a binlog after rotation, it means that there are no more XIDs in prepared state, so that binlog is no longer needed for XA crash recovery, and we can log a new binlog checkpoint event. The list is protected against simultaneous access from multiple threads by LOCK_xid_list. */ struct xid_count_per_binlog : public ilink { char *binlog_name; uint binlog_name_len; ulong binlog_id; /* Total prepared XIDs and pending checkpoint requests in this binlog. */ long xid_count; long notify_count; /* For linking in requests to the binlog background thread. */ xid_count_per_binlog *next_in_queue; xid_count_per_binlog(char *log_file_name, uint log_file_name_len) :binlog_id(0), xid_count(0), notify_count(0) { binlog_name_len= log_file_name_len; binlog_name= (char *) my_malloc(PSI_INSTRUMENT_ME, binlog_name_len, MYF(MY_ZEROFILL)); if (binlog_name) memcpy(binlog_name, log_file_name, binlog_name_len); } ~xid_count_per_binlog() { my_free(binlog_name); } }; I_List binlog_xid_count_list; mysql_mutex_t LOCK_binlog_background_thread; mysql_cond_t COND_binlog_background_thread; mysql_cond_t COND_binlog_background_thread_end; void stop_background_thread(); using MYSQL_LOG::generate_name; using MYSQL_LOG::is_open; /* This is relay log */ bool is_relay_log; ulong relay_signal_cnt; // update of the counter is checked by heartbeat enum enum_binlog_checksum_alg checksum_alg_reset; // to contain a new value when binlog is rotated /* Holds the last seen in Relay-Log FD's checksum alg value. The initial value comes from the slave's local FD that heads the very first Relay-Log file. In the following the value may change with each received master's FD_m. Besides to be used in verification events that IO thread receives (except the 1st fake Rotate, see @c Master_info:: checksum_alg_before_fd), the value specifies if/how to compute checksum for slave's local events and the first fake Rotate (R_f^1) coming from the master. R_f^1 needs logging checksum-compatibly with the RL's heading FD_s. Legends for the checksum related comments: FD - Format-Description event, R - Rotate event R_f - the fake Rotate event E - an arbirary event The underscore indexes for any event `_s' indicates the event is generated by Slave `_m' - by Master Two special underscore indexes of FD: FD_q - Format Description event for queuing (relay-logging) FD_e - Format Description event for executing (relay-logging) Upper indexes: E^n - n:th event is a sequence RL - Relay Log (A) - checksum algorithm descriptor value FD.(A) - the value of (A) in FD */ enum enum_binlog_checksum_alg relay_log_checksum_alg; /* These describe the log's format. This is used only for relay logs. _for_exec is used by the SQL thread, _for_queue by the I/O thread. It's necessary to have 2 distinct objects, because the I/O thread may be reading events in a different format from what the SQL thread is reading (consider the case of a master which has been upgraded from 5.0 to 5.1 without doing RESET MASTER, or from 4.x to 5.0). */ Format_description_log_event *description_event_for_exec, *description_event_for_queue; /* Binlog position of last commit (or non-transactional write) to the binlog. Access to this is protected by LOCK_commit_ordered. */ char last_commit_pos_file[FN_REFLEN]; my_off_t last_commit_pos_offset; ulong current_binlog_id; /* Tracks the number of times that the master has been reset */ Atomic_counter reset_master_count; MYSQL_BIN_LOG(uint *sync_period); /* note that there's no destructor ~MYSQL_BIN_LOG() ! The reason is that we don't want it to be automatically called on exit() - but only during the correct shutdown process */ #ifdef HAVE_PSI_INTERFACE void set_psi_keys(PSI_mutex_key key_LOCK_index, PSI_cond_key key_relay_log_update, PSI_cond_key key_bin_log_update, PSI_file_key key_file_log, PSI_file_key key_file_log_cache, PSI_file_key key_file_log_index, PSI_file_key key_file_log_index_cache, PSI_cond_key key_COND_queue_busy, PSI_mutex_key key_LOCK_binlog_end_pos) { m_key_LOCK_index= key_LOCK_index; m_key_relay_log_update= key_relay_log_update; m_key_bin_log_update= key_bin_log_update; m_key_file_log= key_file_log; m_key_file_log_cache= key_file_log_cache; m_key_file_log_index= key_file_log_index; m_key_file_log_index_cache= key_file_log_index_cache; m_key_COND_queue_busy= key_COND_queue_busy; m_key_LOCK_binlog_end_pos= key_LOCK_binlog_end_pos; } #endif int open(const char *opt_name) override; void close() override; int generate_new_name(char *new_name, const char *log_name, ulong next_log_number) override; int log_and_order(THD *thd, my_xid xid, bool all, bool need_prepare_ordered, bool need_commit_ordered) override; int unlog(ulong cookie, my_xid xid) override; int unlog_xa_prepare(THD *thd, bool all) override; void commit_checkpoint_notify(void *cookie) override; int recover(LOG_INFO *linfo, const char *last_log_name, IO_CACHE *first_log, Format_description_log_event *fdle, bool do_xa); int do_binlog_recovery(const char *opt_name, bool do_xa_recovery); #if !defined(MYSQL_CLIENT) int flush_and_set_pending_rows_event(THD *thd, Rows_log_event* event, bool is_transactional); int remove_pending_rows_event(THD *thd, bool is_transactional); #endif /* !defined(MYSQL_CLIENT) */ void reset_bytes_written() { bytes_written = 0; } void harvest_bytes_written(Atomic_counter *counter) { #ifdef DBUG_TRACE char buf1[22],buf2[22]; #endif DBUG_ENTER("harvest_bytes_written"); (*counter)+=bytes_written; DBUG_PRINT("info",("counter: %s bytes_written: %s", llstr(*counter,buf1), llstr(bytes_written,buf2))); bytes_written=0; DBUG_VOID_RETURN; } void set_max_size(ulong max_size_arg); /* Handle signaling that relay has been updated */ void signal_relay_log_update() { mysql_mutex_assert_owner(&LOCK_log); DBUG_ASSERT(is_relay_log); DBUG_ENTER("MYSQL_BIN_LOG::signal_relay_log_update"); relay_signal_cnt++; mysql_cond_broadcast(&COND_relay_log_updated); DBUG_VOID_RETURN; } void signal_bin_log_update() { mysql_mutex_assert_owner(&LOCK_binlog_end_pos); DBUG_ASSERT(!is_relay_log); DBUG_ENTER("MYSQL_BIN_LOG::signal_bin_log_update"); mysql_cond_broadcast(&COND_bin_log_updated); DBUG_VOID_RETURN; } void update_binlog_end_pos() { if (is_relay_log) signal_relay_log_update(); else { lock_binlog_end_pos(); binlog_end_pos= my_b_safe_tell(&log_file); signal_bin_log_update(); unlock_binlog_end_pos(); } } void update_binlog_end_pos(my_off_t pos) { mysql_mutex_assert_owner(&LOCK_log); mysql_mutex_assert_not_owner(&LOCK_binlog_end_pos); lock_binlog_end_pos(); /* Note: it would make more sense to assert(pos > binlog_end_pos) but there are two places triggered by mtr that has pos == binlog_end_pos i didn't investigate but accepted as it should do no harm */ DBUG_ASSERT(pos >= binlog_end_pos); binlog_end_pos= pos; signal_bin_log_update(); unlock_binlog_end_pos(); } void wait_for_sufficient_commits(); void binlog_trigger_immediate_group_commit(); void wait_for_update_relay_log(THD* thd); void init(ulong max_size); void init_pthread_objects(); void cleanup(); bool open(const char *log_name, const char *new_name, ulong next_log_number, enum cache_type io_cache_type_arg, ulong max_size, bool null_created, bool need_mutex); bool open_index_file(const char *index_file_name_arg, const char *log_name, bool need_mutex); /* Use this to start writing a new log file */ int new_file(); bool write(Log_event* event_info, my_bool *with_annotate= 0); // binary log write bool write_transaction_to_binlog(THD *thd, binlog_cache_mngr *cache_mngr, Log_event *end_ev, bool all, bool using_stmt_cache, bool using_trx_cache, bool is_ro_1pc); bool write_incident_already_locked(THD *thd); bool write_incident(THD *thd); void write_binlog_checkpoint_event_already_locked(const char *name, uint len); int write_cache(THD *thd, IO_CACHE *cache); void set_write_error(THD *thd, bool is_transactional); bool check_write_error(THD *thd); bool check_cache_error(THD *thd, binlog_cache_data *cache_data); void start_union_events(THD *thd, query_id_t query_id_param); void stop_union_events(THD *thd); bool is_query_in_union(THD *thd, query_id_t query_id_param); bool write_event(Log_event *ev, binlog_cache_data *data, IO_CACHE *file); bool write_event(Log_event *ev) { return write_event(ev, 0, &log_file); } bool write_event_buffer(uchar* buf,uint len); bool append(Log_event* ev); bool append_no_lock(Log_event* ev); void mark_xids_active(ulong cookie, uint xid_count); void mark_xid_done(ulong cookie, bool write_checkpoint); void make_log_name(char* buf, const char* log_ident); bool is_active(const char* log_file_name); bool can_purge_log(const char *log_file_name); int update_log_index(LOG_INFO* linfo, bool need_update_threads); int rotate(bool force_rotate, bool* check_purge); void checkpoint_and_purge(ulong binlog_id); int rotate_and_purge(bool force_rotate, DYNAMIC_ARRAY* drop_gtid_domain= NULL); /** Flush binlog cache and synchronize to disk. This function flushes events in binlog cache to binary log file, it will do synchronizing according to the setting of system variable 'sync_binlog'. If file is synchronized, @c synced will be set to 1, otherwise 0. @param[out] synced if not NULL, set to 1 if file is synchronized, otherwise 0 @retval 0 Success @retval other Failure */ bool flush_and_sync(bool *synced); int purge_logs(const char *to_log, bool included, bool need_mutex, bool need_update_threads, ulonglong *decrease_log_space); int purge_logs_before_date(time_t purge_time); int purge_first_log(Relay_log_info* rli, bool included); int set_purge_index_file_name(const char *base_file_name); int open_purge_index_file(bool destroy); bool truncate_and_remove_binlogs(const char *truncate_file, my_off_t truncate_pos, rpl_gtid *gtid); bool is_inited_purge_index_file(); int close_purge_index_file(); int clean_purge_index_file(); int sync_purge_index_file(); int register_purge_index_entry(const char* entry); int register_create_index_entry(const char* entry); int purge_index_entry(THD *thd, ulonglong *decrease_log_space, bool need_mutex); bool reset_logs(THD* thd, bool create_new_log, rpl_gtid *init_state, uint32 init_state_len, ulong next_log_number); void wait_for_last_checkpoint_event(); void close(uint exiting); void clear_inuse_flag_when_closing(File file); // iterating through the log index file int find_log_pos(LOG_INFO* linfo, const char* log_name, bool need_mutex); int find_next_log(LOG_INFO* linfo, bool need_mutex); int get_current_log(LOG_INFO* linfo); int raw_get_current_log(LOG_INFO* linfo); uint next_file_id(); inline char* get_index_fname() { return index_file_name;} inline char* get_log_fname() { return log_file_name; } inline char* get_name() { return name; } inline mysql_mutex_t* get_log_lock() { return &LOCK_log; } inline mysql_cond_t* get_bin_log_cond() { return &COND_bin_log_updated; } inline IO_CACHE* get_log_file() { return &log_file; } inline uint64 get_reset_master_count() { return reset_master_count; } inline void lock_index() { mysql_mutex_lock(&LOCK_index);} inline void unlock_index() { mysql_mutex_unlock(&LOCK_index);} inline IO_CACHE *get_index_file() { return &index_file;} inline uint32 get_open_count() { return open_count; } void set_status_variables(THD *thd); bool is_xidlist_idle(); bool write_gtid_event(THD *thd, bool standalone, bool is_transactional, uint64 commit_id, bool has_xid= false, bool ro_1pc= false); int read_state_from_file(); int write_state_to_file(); int get_most_recent_gtid_list(rpl_gtid **list, uint32 *size); bool append_state_pos(String *str); bool append_state(String *str); bool is_empty_state(); bool find_in_binlog_state(uint32 domain_id, uint32 server_id, rpl_gtid *out_gtid); bool lookup_domain_in_binlog_state(uint32 domain_id, rpl_gtid *out_gtid); int bump_seq_no_counter_if_needed(uint32 domain_id, uint64 seq_no); bool check_strict_gtid_sequence(uint32 domain_id, uint32 server_id, uint64 seq_no, bool no_error= false); /** * used when opening new file, and binlog_end_pos moves backwards */ void reset_binlog_end_pos(const char file_name[FN_REFLEN], my_off_t pos) { mysql_mutex_assert_owner(&LOCK_log); mysql_mutex_assert_not_owner(&LOCK_binlog_end_pos); lock_binlog_end_pos(); binlog_end_pos= pos; safe_strcpy(binlog_end_pos_file, sizeof(binlog_end_pos_file), file_name); signal_bin_log_update(); unlock_binlog_end_pos(); } /* It is called by the threads(e.g. dump thread) which want to read log without LOCK_log protection. */ my_off_t get_binlog_end_pos(char file_name_buf[FN_REFLEN]) const { mysql_mutex_assert_not_owner(&LOCK_log); mysql_mutex_assert_owner(&LOCK_binlog_end_pos); safe_strcpy(file_name_buf, FN_REFLEN, binlog_end_pos_file); return binlog_end_pos; } void lock_binlog_end_pos() { mysql_mutex_lock(&LOCK_binlog_end_pos); } void unlock_binlog_end_pos() { mysql_mutex_unlock(&LOCK_binlog_end_pos); } mysql_mutex_t* get_binlog_end_pos_lock() { return &LOCK_binlog_end_pos; } /* Ensures the log's state is either LOG_OPEN or LOG_CLOSED. If something failed along the desired path and left the log in invalid state, i.e. LOG_TO_BE_OPENED, forces the state to be LOG_CLOSED. */ void try_fix_log_state() { mysql_mutex_lock(get_log_lock()); /* Only change the log state if it is LOG_TO_BE_OPENED */ if (log_state == LOG_TO_BE_OPENED) log_state= LOG_CLOSED; mysql_mutex_unlock(get_log_lock()); } int wait_for_update_binlog_end_pos(THD* thd, struct timespec * timeout); /* Binlog position of end of the binlog. Access to this is protected by LOCK_binlog_end_pos The difference between this and last_commit_pos_{file,offset} is that the commit position is updated later. If semi-sync wait point is set to WAIT_AFTER_SYNC, the commit pos is update after semi-sync-ack has been received and the end point is updated after the write as it's needed for the dump threads to be able to semi-sync the event. */ my_off_t binlog_end_pos; char binlog_end_pos_file[FN_REFLEN]; }; class Log_event_handler { public: Log_event_handler() = default; virtual bool init()= 0; virtual void cleanup()= 0; virtual bool log_slow(THD *thd, my_hrtime_t current_time, const char *user_host, size_t user_host_len, ulonglong query_utime, ulonglong lock_utime, bool is_command, const char *sql_text, size_t sql_text_len)= 0; virtual bool log_error(enum loglevel level, const char *format, va_list args)= 0; virtual bool log_general(THD *thd, my_hrtime_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, const char *command_type, size_t command_type_len, const char *sql_text, size_t sql_text_len, CHARSET_INFO *client_cs)= 0; virtual ~Log_event_handler() = default; }; int check_if_log_table(const TABLE_LIST *table, bool check_if_opened, const char *errmsg); class Log_to_csv_event_handler: public Log_event_handler { friend class LOGGER; public: Log_to_csv_event_handler(); ~Log_to_csv_event_handler(); bool init() override; void cleanup() override; bool log_slow(THD *thd, my_hrtime_t current_time, const char *user_host, size_t user_host_len, ulonglong query_utime, ulonglong lock_utime, bool is_command, const char *sql_text, size_t sql_text_len) override; bool log_error(enum loglevel level, const char *format, va_list args) override; bool log_general(THD *thd, my_hrtime_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, const char *command_type, size_t command_type_len, const char *sql_text, size_t sql_text_len, CHARSET_INFO *client_cs) override; int activate_log(THD *thd, uint log_type); }; /* type of the log table */ #define QUERY_LOG_SLOW 1 #define QUERY_LOG_GENERAL 2 class Log_to_file_event_handler: public Log_event_handler { MYSQL_QUERY_LOG mysql_log; MYSQL_QUERY_LOG mysql_slow_log; bool is_initialized; public: Log_to_file_event_handler(): is_initialized(FALSE) {} bool init() override; void cleanup() override; bool log_slow(THD *thd, my_hrtime_t current_time, const char *user_host, size_t user_host_len, ulonglong query_utime, ulonglong lock_utime, bool is_command, const char *sql_text, size_t sql_text_len) override; bool log_error(enum loglevel level, const char *format, va_list args) override; bool log_general(THD *thd, my_hrtime_t event_time, const char *user_host, size_t user_host_len, my_thread_id thread_id, const char *command_type, size_t command_type_len, const char *sql_text, size_t sql_text_len, CHARSET_INFO *client_cs) override; void flush(); void init_pthread_objects(); MYSQL_QUERY_LOG *get_mysql_slow_log() { return &mysql_slow_log; } MYSQL_QUERY_LOG *get_mysql_log() { return &mysql_log; } }; /* Class which manages slow, general and error log event handlers */ class LOGGER { mysql_rwlock_t LOCK_logger; /* flag to check whether logger mutex is initialized */ uint inited; /* available log handlers */ Log_to_csv_event_handler *table_log_handler; Log_to_file_event_handler *file_log_handler; /* NULL-terminated arrays of log handlers */ Log_event_handler *error_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; Log_event_handler *slow_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; Log_event_handler *general_log_handler_list[MAX_LOG_HANDLERS_NUM + 1]; public: bool is_log_tables_initialized; LOGGER() : inited(0), table_log_handler(NULL), file_log_handler(NULL), is_log_tables_initialized(FALSE) {} void lock_shared() { mysql_rwlock_rdlock(&LOCK_logger); } void lock_exclusive() { mysql_rwlock_wrlock(&LOCK_logger); } void unlock() { mysql_rwlock_unlock(&LOCK_logger); } bool is_log_table_enabled(uint log_table_type); bool log_command(THD *thd, enum enum_server_command command); /* We want to initialize all log mutexes as soon as possible, but we cannot do it in constructor, as safe_mutex relies on initialization, performed by MY_INIT(). This why this is done in this function. */ void init_base(); void init_log_tables(); bool flush_slow_log(); bool flush_general_log(); /* Perform basic logger cleanup. this will leave e.g. error log open. */ void cleanup_base(); /* Free memory. Nothing could be logged after this function is called */ void cleanup_end(); bool error_log_print(enum loglevel level, const char *format, va_list args); bool slow_log_print(THD *thd, const char *query, size_t query_length, ulonglong current_utime); bool general_log_print(THD *thd,enum enum_server_command command, const char *format, va_list args); bool general_log_write(THD *thd, enum enum_server_command command, const char *query, size_t query_length); /* we use this function to setup all enabled log event handlers */ int set_handlers(ulonglong slow_log_printer, ulonglong general_log_printer); void init_error_log(ulonglong error_log_printer); void init_slow_log(ulonglong slow_log_printer); void init_general_log(ulonglong general_log_printer); void deactivate_log_handler(THD* thd, uint log_type); bool activate_log_handler(THD* thd, uint log_type); MYSQL_QUERY_LOG *get_slow_log_file_handler() const { if (file_log_handler) return file_log_handler->get_mysql_slow_log(); return NULL; } MYSQL_QUERY_LOG *get_log_file_handler() const { if (file_log_handler) return file_log_handler->get_mysql_log(); return NULL; } }; enum enum_binlog_format { BINLOG_FORMAT_MIXED= 0, ///< statement if safe, otherwise row - autodetected BINLOG_FORMAT_STMT= 1, ///< statement-based BINLOG_FORMAT_ROW= 2, ///< row-based BINLOG_FORMAT_UNSPEC=3 ///< thd_binlog_format() returns it when binlog is closed }; int query_error_code(THD *thd, bool not_killed); uint purge_log_get_error_code(int res); int vprint_msg_to_log(enum loglevel level, const char *format, va_list args); void sql_print_error(const char *format, ...); void sql_print_warning(const char *format, ...); void sql_print_information(const char *format, ...); void sql_print_information_v(const char *format, va_list ap); typedef void (*sql_print_message_func)(const char *format, ...); extern sql_print_message_func sql_print_message_handlers[]; int error_log_print(enum loglevel level, const char *format, va_list args); bool slow_log_print(THD *thd, const char *query, uint query_length, ulonglong current_utime); bool general_log_print(THD *thd, enum enum_server_command command, const char *format,...); bool general_log_write(THD *thd, enum enum_server_command command, const char *query, size_t query_length); void binlog_report_wait_for(THD *thd, THD *other_thd); void sql_perror(const char *message); bool flush_error_log(); File open_binlog(IO_CACHE *log, const char *log_file_name, const char **errmsg); void make_default_log_name(char **out, const char* log_ext, bool once); void binlog_reset_cache(THD *thd); bool write_annotated_row(THD *thd); extern MYSQL_PLUGIN_IMPORT MYSQL_BIN_LOG mysql_bin_log; extern handlerton *binlog_hton; extern LOGGER logger; extern const char *log_bin_index; extern const char *log_bin_basename; /** Turns a relative log binary log path into a full path, based on the opt_bin_logname or opt_relay_logname. @param from The log name we want to make into an absolute path. @param to The buffer where to put the results of the normalization. @param is_relay_log Switch that makes is used inside to choose which option (opt_bin_logname or opt_relay_logname) to use when calculating the base path. @returns true if a problem occurs, false otherwise. */ inline bool normalize_binlog_name(char *to, const char *from, bool is_relay_log) { DBUG_ENTER("normalize_binlog_name"); bool error= false; char buff[FN_REFLEN]; char *ptr= (char*) from; char *opt_name= is_relay_log ? opt_relay_logname : opt_bin_logname; DBUG_ASSERT(from); /* opt_name is not null and not empty and from is a relative path */ if (opt_name && opt_name[0] && from && !test_if_hard_path(from)) { // take the path from opt_name // take the filename from from char log_dirpart[FN_REFLEN], log_dirname[FN_REFLEN]; size_t log_dirpart_len, log_dirname_len; dirname_part(log_dirpart, opt_name, &log_dirpart_len); dirname_part(log_dirname, from, &log_dirname_len); /* log may be empty => relay-log or log-bin did not hold paths, just filename pattern */ if (log_dirpart_len > 0) { /* create the new path name */ if(fn_format(buff, from+log_dirname_len, log_dirpart, "", MYF(MY_UNPACK_FILENAME | MY_SAFE_PATH)) == NULL) { error= true; goto end; } ptr= buff; } } DBUG_ASSERT(ptr); if (ptr) strmake(to, ptr, strlen(ptr)); end: DBUG_RETURN(error); } static inline TC_LOG *get_tc_log_implementation() { if (total_ha_2pc <= 1) return &tc_log_dummy; if (opt_bin_log) return &mysql_bin_log; return &tc_log_mmap; } #ifdef WITH_WSREP IO_CACHE* wsrep_get_cache(THD *, bool); bool wsrep_is_binlog_cache_empty(THD *); void wsrep_thd_binlog_trx_reset(THD * thd); void wsrep_thd_binlog_stmt_rollback(THD * thd); #endif /* WITH_WSREP */ class Gtid_list_log_event; const char * get_gtid_list_event(IO_CACHE *cache, Gtid_list_log_event **out_gtid_list); int binlog_commit(THD *thd, bool all, bool is_ro_1pc= false); int binlog_commit_by_xid(handlerton *hton, XID *xid); int binlog_rollback_by_xid(handlerton *hton, XID *xid); #endif /* LOG_H */ mysql/server/private/sql_type_string.h000064400000003135151027430560014275 0ustar00/* Copyright (c) 2019 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SQL_TYPE_STRING_INCLUDED #define SQL_TYPE_STRING_INCLUDED class StringPack { CHARSET_INFO *m_cs; uint32 m_octet_length; CHARSET_INFO *charset() const { return m_cs; } uint mbmaxlen() const { return m_cs->mbmaxlen; }; uint32 char_length() const { return m_octet_length / mbmaxlen(); } public: StringPack(CHARSET_INFO *cs, uint32 octet_length) :m_cs(cs), m_octet_length(octet_length) { } uchar *pack(uchar *to, const uchar *from, uint max_length) const; const uchar *unpack(uchar *to, const uchar *from, const uchar *from_end, uint param_data) const; public: static uint max_packed_col_length(uint max_length) { return (max_length > 255 ? 2 : 1) + max_length; } static uint packed_col_length(const uchar *data_ptr, uint length) { if (length > 255) return uint2korr(data_ptr)+2; return (uint) *data_ptr + 1; } }; #endif // SQL_TYPE_STRING_INCLUDED mysql/server/private/hostname.h000064400000012453151027430560012670 0ustar00/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef HOSTNAME_INCLUDED #define HOSTNAME_INCLUDED #include "my_net.h" #include "hash_filo.h" struct Host_errors { public: Host_errors(); ~Host_errors(); void reset(); void aggregate(const Host_errors *errors); /** Number of connect errors. */ ulong m_connect; /** Number of host blocked errors. */ ulong m_host_blocked; /** Number of transient errors from getnameinfo(). */ ulong m_nameinfo_transient; /** Number of permanent errors from getnameinfo(). */ ulong m_nameinfo_permanent; /** Number of errors from is_hostname_valid(). */ ulong m_format; /** Number of transient errors from getaddrinfo(). */ ulong m_addrinfo_transient; /** Number of permanent errors from getaddrinfo(). */ ulong m_addrinfo_permanent; /** Number of errors from Forward-Confirmed reverse DNS checks. */ ulong m_FCrDNS; /** Number of errors from host grants. */ ulong m_host_acl; /** Number of errors from missing auth plugin. */ ulong m_no_auth_plugin; /** Number of errors from auth plugin. */ ulong m_auth_plugin; /** Number of errors from authentication plugins. */ ulong m_handshake; /** Number of errors from proxy user. */ ulong m_proxy_user; /** Number of errors from proxy user acl. */ ulong m_proxy_user_acl; /** Number of errors from authentication. */ ulong m_authentication; /** Number of errors from ssl. */ ulong m_ssl; /** Number of errors from max user connection. */ ulong m_max_user_connection; /** Number of errors from max user connection per hour. */ ulong m_max_user_connection_per_hour; /** Number of errors from the default database. */ ulong m_default_database; /** Number of errors from init_connect. */ ulong m_init_connect; /** Number of errors from the server itself. */ ulong m_local; bool has_error() const { return ((m_host_blocked != 0) || (m_nameinfo_transient != 0) || (m_nameinfo_permanent != 0) || (m_format != 0) || (m_addrinfo_transient != 0) || (m_addrinfo_permanent != 0) || (m_FCrDNS != 0) || (m_host_acl != 0) || (m_no_auth_plugin != 0) || (m_auth_plugin != 0) || (m_handshake != 0) || (m_proxy_user != 0) || (m_proxy_user_acl != 0) || (m_authentication != 0) || (m_ssl != 0) || (m_max_user_connection != 0) || (m_max_user_connection_per_hour != 0) || (m_default_database != 0) || (m_init_connect != 0) || (m_local != 0)); } void sum_connect_errors() { /* Current (historical) behavior: */ m_connect= m_handshake; } void clear_connect_errors() { m_connect= 0; } }; /** Size of IP address string in the hash cache. */ #define HOST_ENTRY_KEY_SIZE INET6_ADDRSTRLEN /** An entry in the hostname hash table cache. Host name cache does two things: - caches host names to save DNS look ups; - counts errors from IP. Host name can be empty (that means DNS look up failed), but errors still are counted. */ class Host_entry : public hash_filo_element { public: Host_entry *next() { return (Host_entry*) hash_filo_element::next(); } /** Client IP address. This is the key used with the hash table. The client IP address is always expressed in IPv6, even when the network IPv6 stack is not present. This IP address is never used to connect to a socket. */ char ip_key[HOST_ENTRY_KEY_SIZE]; /** One of the host names for the IP address. May be a zero length string. */ char m_hostname[HOSTNAME_LENGTH + 1]; /** Length in bytes of @c m_hostname. */ uint m_hostname_length; /** The hostname is validated and used for authorization. */ bool m_host_validated; ulonglong m_first_seen; ulonglong m_last_seen; ulonglong m_first_error_seen; ulonglong m_last_error_seen; /** Error statistics. */ Host_errors m_errors; void set_error_timestamps(ulonglong now) { if (m_first_error_seen == 0) m_first_error_seen= now; m_last_error_seen= now; } }; /** The size of the host_cache. */ extern ulong host_cache_size; #define RC_OK 0 #define RC_BLOCKED_HOST 1 int ip_to_hostname(struct sockaddr_storage *ip_storage, const char *ip_string, const char **hostname, uint *connect_errors); void inc_host_errors(const char *ip_string, Host_errors *errors); void reset_host_connect_errors(const char *ip_string); bool hostname_cache_init(); void hostname_cache_free(); void hostname_cache_refresh(void); uint hostname_cache_size(); void hostname_cache_resize(uint size); void hostname_cache_lock(); void hostname_cache_unlock(); Host_entry *hostname_cache_first(); #endif /* HOSTNAME_INCLUDED */ mysql/server/private/hash.h000064400000010541151027430560011771 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. Copyright (c) 2011, 2013, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Dynamic hashing of record with different key-length */ #ifndef _hash_h #define _hash_h #include "my_sys.h" /* DYNAMIC_ARRAY */ /* This forward declaration is used from C files where the real definition is included before. Since C does not allow repeated typedef declarations, even when identical, the definition may not be repeated. */ #ifdef __cplusplus extern "C" { #endif /* Overhead to store an element in hash Can be used to approximate memory consumption for a hash */ #define HASH_OVERHEAD (sizeof(char*)*2) /* flags for hash_init */ #define HASH_UNIQUE 1 /* hash_insert fails on duplicate key */ #define HASH_THREAD_SPECIFIC 2 /* Mark allocated memory THREAD_SPECIFIC */ typedef uint32 my_hash_value_type; typedef const uchar *(*my_hash_get_key)(const void *, size_t *, my_bool); typedef my_hash_value_type (*my_hash_function)(CHARSET_INFO *, const uchar *, size_t); typedef void (*my_hash_free_key)(void *); typedef my_bool (*my_hash_walk_action)(void *,void *); typedef struct st_hash { size_t key_offset,key_length; /* Length of key if const length */ size_t blength; ulong records; uint flags; DYNAMIC_ARRAY array; /* Place for hash_keys */ my_hash_get_key get_key; my_hash_function hash_function; void (*free)(void *); CHARSET_INFO *charset; } HASH; /* A search iterator state */ typedef uint HASH_SEARCH_STATE; #define my_hash_init(A,B,C,D,E,F,G,H,I) my_hash_init2(A,B,0,C,D,E,F,G,0,H,I) my_bool my_hash_init2(PSI_memory_key psi_key, HASH *hash, uint growth_size, CHARSET_INFO *charset, ulong default_array_elements, size_t key_offset, size_t key_length, my_hash_get_key get_key, my_hash_function hash_function, void (*free_element)(void*), uint flags); void my_hash_free(HASH *tree); void my_hash_reset(HASH *hash); uchar *my_hash_element(HASH *hash, size_t idx); uchar *my_hash_search(const HASH *info, const uchar *key, size_t length); uchar *my_hash_search_using_hash_value(const HASH *info, my_hash_value_type hash_value, const uchar *key, size_t length); my_hash_value_type my_hash_sort(CHARSET_INFO *cs, const uchar *key, size_t length); #define my_calc_hash(A, B, C) my_hash_sort((A)->charset, B, C) uchar *my_hash_first(const HASH *info, const uchar *key, size_t length, HASH_SEARCH_STATE *state); uchar *my_hash_first_from_hash_value(const HASH *info, my_hash_value_type hash_value, const uchar *key, size_t length, HASH_SEARCH_STATE *state); uchar *my_hash_next(const HASH *info, const uchar *key, size_t length, HASH_SEARCH_STATE *state); my_bool my_hash_insert(HASH *info, const uchar *data); my_bool my_hash_delete(HASH *hash, uchar *record); my_bool my_hash_update(HASH *hash, uchar *record, uchar *old_key, size_t old_key_length); void my_hash_replace(HASH *hash, HASH_SEARCH_STATE *state, uchar *new_row); my_bool my_hash_check(HASH *hash); /* Only in debug library */ my_bool my_hash_iterate(HASH *hash, my_hash_walk_action action, void *argument); #define my_hash_clear(H) bzero((char*) (H), sizeof(*(H))) #define my_hash_inited(H) ((H)->blength != 0) #define my_hash_init_opt(A,B,C,D,E,F,G,H,I) \ (!my_hash_inited(B) && my_hash_init(A,B,C,D,E,F,G,H,I)) #ifdef __cplusplus } #endif #endif mysql/server/private/sql_string.h000064400000115535151027430560013244 0ustar00#ifndef SQL_STRING_INCLUDED #define SQL_STRING_INCLUDED /* Copyright (c) 2000, 2013, Oracle and/or its affiliates. Copyright (c) 2008, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file is originally from the mysql distribution. Coded by monty */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "m_ctype.h" /* my_charset_bin */ #include /* alloc_root, my_free, my_realloc */ #include "m_string.h" /* TRASH */ #include "sql_list.h" class String; #ifdef MYSQL_SERVER extern PSI_memory_key key_memory_String_value; #define STRING_PSI_MEMORY_KEY key_memory_String_value #else #define STRING_PSI_MEMORY_KEY PSI_NOT_INSTRUMENTED #endif typedef struct st_io_cache IO_CACHE; typedef struct st_mem_root MEM_ROOT; #define ASSERT_LENGTH(A) DBUG_ASSERT(str_length + (uint32) (A) <= Alloced_length) #include "pack.h" class Binary_string; int sortcmp(const Binary_string *s, const Binary_string *t, CHARSET_INFO *cs); int stringcmp(const Binary_string *s, const Binary_string *t); String *copy_if_not_alloced(String *a,String *b,uint32 arg_length); inline uint32 copy_and_convert(char *to, size_t to_length, CHARSET_INFO *to_cs, const char *from, size_t from_length, CHARSET_INFO *from_cs, uint *errors) { return my_convert(to, (uint)to_length, to_cs, from, (uint)from_length, from_cs, errors); } class String_copy_status: protected MY_STRCOPY_STATUS { public: const char *source_end_pos() const { return m_source_end_pos; } const char *well_formed_error_pos() const { return m_well_formed_error_pos; } }; class Well_formed_prefix_status: public String_copy_status { public: Well_formed_prefix_status(CHARSET_INFO *cs, const char *str, const char *end, size_t nchars) { cs->well_formed_char_length(str, end, nchars, this); } }; class Well_formed_prefix: public Well_formed_prefix_status { const char *m_str; // The beginning of the string public: Well_formed_prefix(CHARSET_INFO *cs, const char *str, const char *end, size_t nchars) :Well_formed_prefix_status(cs, str, end, nchars), m_str(str) { } Well_formed_prefix(CHARSET_INFO *cs, const char *str, size_t length, size_t nchars) :Well_formed_prefix_status(cs, str, str + length, nchars), m_str(str) { } Well_formed_prefix(CHARSET_INFO *cs, const char *str, size_t length) :Well_formed_prefix_status(cs, str, str + length, length), m_str(str) { } Well_formed_prefix(CHARSET_INFO *cs, LEX_CSTRING str, size_t nchars) :Well_formed_prefix_status(cs, str.str, str.str + str.length, nchars), m_str(str.str) { } size_t length() const { return m_source_end_pos - m_str; } }; class String_copier: public String_copy_status, protected MY_STRCONV_STATUS { public: const char *cannot_convert_error_pos() const { return m_cannot_convert_error_pos; } const char *most_important_error_pos() const { return well_formed_error_pos() ? well_formed_error_pos() : cannot_convert_error_pos(); } /* Convert a string between character sets. "dstcs" and "srccs" cannot be &my_charset_bin. */ size_t convert_fix(CHARSET_INFO *dstcs, char *dst, size_t dst_length, CHARSET_INFO *srccs, const char *src, size_t src_length, size_t nchars) { return my_convert_fix(dstcs, dst, dst_length, srccs, src, src_length, nchars, this, this); } /* Copy a string. Fix bad bytes/characters to '?'. */ uint well_formed_copy(CHARSET_INFO *to_cs, char *to, size_t to_length, CHARSET_INFO *from_cs, const char *from, size_t from_length, size_t nchars); // Same as above, but without the "nchars" limit. uint well_formed_copy(CHARSET_INFO *to_cs, char *to, size_t to_length, CHARSET_INFO *from_cs, const char *from, size_t from_length) { return well_formed_copy(to_cs, to, to_length, from_cs, from, from_length, from_length /* No limit on "nchars"*/); } }; size_t my_copy_with_hex_escaping(CHARSET_INFO *cs, char *dst, size_t dstlen, const char *src, size_t srclen); uint convert_to_printable(char *to, size_t to_len, const char *from, size_t from_len, CHARSET_INFO *from_cs, size_t nbytes= 0); size_t convert_to_printable_required_length(uint len); class Charset { CHARSET_INFO *m_charset; public: Charset() :m_charset(&my_charset_bin) { } Charset(CHARSET_INFO *cs) :m_charset(cs) { } CHARSET_INFO *charset() const { return m_charset; } bool use_mb() const { return m_charset->use_mb(); } uint mbminlen() const { return m_charset->mbminlen; } uint mbmaxlen() const { return m_charset->mbmaxlen; } bool is_good_for_ft() const { // Binary and UCS2/UTF16/UTF32 are not supported return m_charset != &my_charset_bin && m_charset->mbminlen == 1; } size_t numchars(const char *str, const char *end) const { return m_charset->numchars(str, end); } size_t lengthsp(const char *str, size_t length) const { return m_charset->lengthsp(str, length); } size_t charpos(const char *str, const char *end, size_t pos) const { return m_charset->charpos(str, end, pos); } void set_charset(CHARSET_INFO *charset_arg) { m_charset= charset_arg; } void set_charset(const Charset &other) { m_charset= other.m_charset; } void swap(Charset &other) { swap_variables(CHARSET_INFO*, m_charset, other.m_charset); } bool same_encoding(const Charset &other) const { return my_charset_same(m_charset, other.m_charset); } /* Collation name without the character set name. For example, in case of "latin1_swedish_ci", this method returns "_swedish_ci". */ LEX_CSTRING collation_specific_name() const; bool encoding_allows_reinterpret_as(CHARSET_INFO *cs) const; bool eq_collation_specific_names(CHARSET_INFO *cs) const; bool can_have_collate_clause() const { return m_charset != &my_charset_bin; } /* The MariaDB version when the last collation change happened, e.g. due to a bug fix. See functions below. */ static ulong latest_mariadb_version_with_collation_change() { return 110002; } /* Check if the collation with the given ID changed its order since the given MariaDB version. */ static bool collation_changed_order(ulong mysql_version, uint cs_number) { if ((mysql_version < 50048 && (cs_number == 11 || /* ascii_general_ci - bug #29499, bug #27562 */ cs_number == 41 || /* latin7_general_ci - bug #29461 */ cs_number == 42 || /* latin7_general_cs - bug #29461 */ cs_number == 20 || /* latin7_estonian_cs - bug #29461 */ cs_number == 21 || /* latin2_hungarian_ci - bug #29461 */ cs_number == 22 || /* koi8u_general_ci - bug #29461 */ cs_number == 23 || /* cp1251_ukrainian_ci - bug #29461 */ cs_number == 26)) || /* cp1250_general_ci - bug #29461 */ (mysql_version < 50124 && (cs_number == 33 || /* utf8mb3_general_ci - bug #27877 */ cs_number == 35))) /* ucs2_general_ci - bug #27877 */ return true; if (cs_number == 159 && /* ucs2_general_mysql500_ci - MDEV-30746 */ ((mysql_version >= 100400 && mysql_version < 100429) || (mysql_version >= 100500 && mysql_version < 100520) || (mysql_version >= 100600 && mysql_version < 100613) || (mysql_version >= 100700 && mysql_version < 100708) || (mysql_version >= 100800 && mysql_version < 100808) || (mysql_version >= 100900 && mysql_version < 100906) || (mysql_version >= 101000 && mysql_version < 101004) || (mysql_version >= 101100 && mysql_version < 101103) || (mysql_version >= 110000 && mysql_version < 110002))) return true; return false; } /** Check if a collation has changed ID since the given version. Return the new ID. @param mysql_version @param cs_number - collation ID @retval the new collation ID (or cs_number, if no change) */ static uint upgrade_collation_id(ulong mysql_version, uint cs_number) { if (mysql_version >= 50300 && mysql_version <= 50399) { switch (cs_number) { case 149: return MY_PAGE2_COLLATION_ID_UCS2; // ucs2_crotian_ci case 213: return MY_PAGE2_COLLATION_ID_UTF8; // utf8_crotian_ci } } if ((mysql_version >= 50500 && mysql_version <= 50599) || (mysql_version >= 100000 && mysql_version <= 100005)) { switch (cs_number) { case 149: return MY_PAGE2_COLLATION_ID_UCS2; // ucs2_crotian_ci case 213: return MY_PAGE2_COLLATION_ID_UTF8; // utf8_crotian_ci case 214: return MY_PAGE2_COLLATION_ID_UTF32; // utf32_croatian_ci case 215: return MY_PAGE2_COLLATION_ID_UTF16; // utf16_croatian_ci case 245: return MY_PAGE2_COLLATION_ID_UTF8MB4;// utf8mb4_croatian_ci } } return cs_number; } }; /** Storage for strings with both length and allocated length. Automatically grows on demand. */ class Binary_string: public Sql_alloc { protected: char *Ptr; uint32 str_length, Alloced_length, extra_alloc; bool alloced, thread_specific; void init_private_data() { Ptr= 0; Alloced_length= extra_alloc= str_length= 0; alloced= thread_specific= false; } inline void free_buffer() { if (alloced) { alloced=0; my_free(Ptr); } } public: Binary_string() { init_private_data(); } explicit Binary_string(size_t length_arg) { init_private_data(); (void) real_alloc(length_arg); } /* NOTE: If one intend to use the c_ptr() method, the following two contructors need the size of memory for STR to be at least LEN+1 (to make room for zero termination). */ Binary_string(const char *str, size_t len) { Ptr= (char*) str; str_length= (uint32) len; Alloced_length= 0; /* Memory cannot be written to */ extra_alloc= 0; alloced= thread_specific= 0; } Binary_string(char *str, size_t len) { Ptr= str; str_length= Alloced_length= (uint32) len; extra_alloc= 0; alloced= thread_specific= 0; } explicit Binary_string(const Binary_string &str) { Ptr= str.Ptr; str_length= str.str_length; Alloced_length= str.Alloced_length; extra_alloc= 0; alloced= thread_specific= 0; } ~Binary_string() { free(); } inline uint32 length() const { return str_length;} inline char& operator [] (size_t i) const { return Ptr[i]; } inline void length(size_t len) { str_length=(uint32)len ; } inline bool is_empty() const { return (str_length == 0); } inline const char *ptr() const { return Ptr; } inline const char *end() const { return Ptr + str_length; } bool has_8bit_bytes() const { for (const char *c= ptr(), *c_end= end(); c < c_end; c++) { if (!my_isascii(*c)) return true; } return false; } bool bin_eq(const Binary_string *other) const { return length() == other->length() && !memcmp(ptr(), other->ptr(), length()); } /* PMG 2004.11.12 This is a method that works the same as perl's "chop". It simply drops the last character of a string. This is useful in the case of the federated storage handler where I'm building a unknown number, list of values and fields to be used in a sql insert statement to be run on the remote server, and have a comma after each. When the list is complete, I "chop" off the trailing comma ex. String stringobj; stringobj.append("VALUES ('foo', 'fi', 'fo',"); stringobj.chop(); stringobj.append(")"); In this case, the value of string was: VALUES ('foo', 'fi', 'fo', VALUES ('foo', 'fi', 'fo' VALUES ('foo', 'fi', 'fo') */ inline void chop() { if (str_length) { str_length--; Ptr[str_length]= '\0'; DBUG_ASSERT(strlen(Ptr) == str_length); } } // Returns offset to substring or -1 int strstr(const Binary_string &search, uint32 offset=0) const; int strstr(const char *search, uint32 search_length, uint32 offset=0) const; // Returns offset to substring or -1 int strrstr(const Binary_string &search, uint32 offset=0) const; /* The following append operations do not extend the strings and in production mode do NOT check that alloced memory! q_*** methods writes values of parameters itself qs_*** methods writes string representation of value */ void q_append(const char c) { ASSERT_LENGTH(1); Ptr[str_length++] = c; } void q_append2b(const uint32 n) { ASSERT_LENGTH(2); int2store(Ptr + str_length, n); str_length += 2; } void q_append(const uint32 n) { ASSERT_LENGTH(4); int4store(Ptr + str_length, n); str_length += 4; } void q_append(double d) { ASSERT_LENGTH(8); float8store(Ptr + str_length, d); str_length += 8; } void q_append(double *d) { ASSERT_LENGTH(8); float8store(Ptr + str_length, *d); str_length += 8; } /* Append a wide character. The caller must have allocated at least cs->mbmaxlen bytes. */ int q_append_wc(my_wc_t wc, CHARSET_INFO *cs) { int mblen; if ((mblen= cs->cset->wc_mb(cs, wc, (uchar *) end(), (uchar *) end() + cs->mbmaxlen)) > 0) str_length+= (uint32) mblen; return mblen; } void q_append(const char *data, size_t data_len) { ASSERT_LENGTH(data_len); if (data_len) memcpy(Ptr + str_length, data, data_len); DBUG_ASSERT(str_length <= UINT_MAX32 - data_len); str_length += (uint)data_len; } void q_append(const LEX_CSTRING *ls) { DBUG_ASSERT(ls->length < UINT_MAX32 && ((ls->length == 0 && !ls->str) || ls->length == strlen(ls->str))); q_append(ls->str, (uint32) ls->length); } void write_at_position(uint32 position, uint32 value) { DBUG_ASSERT(str_length >= position + 4); int4store(Ptr + position,value); } void qs_append(const LEX_CSTRING *ls) { DBUG_ASSERT(ls->length < UINT_MAX32 && ((ls->length == 0 && !ls->str) || ls->length == strlen(ls->str))); qs_append(ls->str, (uint32)ls->length); } void qs_append(const char *str, size_t len); void qs_append_hex(const char *str, uint32 len); void qs_append_hex_uint32(uint32 num); void qs_append(double d); void qs_append(const double *d); inline void qs_append(const char c) { ASSERT_LENGTH(1); Ptr[str_length]= c; str_length++; } void qs_append(int i); void qs_append(uint i) { qs_append((ulonglong)i); } void qs_append(ulong i) { qs_append((ulonglong)i); } void qs_append(ulonglong i); void qs_append(longlong i, int radix) { ASSERT_LENGTH(22); char *buff= Ptr + str_length; char *end= ll2str(i, buff, radix, 0); str_length+= (uint32) (end-buff); } /* Mark variable thread specific it it's not allocated already */ inline void set_thread_specific() { if (!alloced) thread_specific= 1; } bool is_alloced() const { return alloced; } inline uint32 alloced_length() const { return Alloced_length;} inline uint32 extra_allocation() const { return extra_alloc;} inline void extra_allocation(size_t len) { extra_alloc= (uint32)len; } inline void mark_as_const() { Alloced_length= 0;} inline bool uses_buffer_owned_by(const Binary_string *s) const { return (s->alloced && Ptr >= s->Ptr && Ptr < s->Ptr + s->Alloced_length); } /* Swap two string objects. Efficient way to exchange data without memcpy. */ void swap(Binary_string &s) { swap_variables(char *, Ptr, s.Ptr); swap_variables(uint32, str_length, s.str_length); swap_variables(uint32, Alloced_length, s.Alloced_length); swap_variables(bool, alloced, s.alloced); } /** Points the internal buffer to the supplied one. The old buffer is freed. @param str Pointer to the new buffer. @param arg_length Length of the new buffer in characters, excluding any null character. @note The new buffer will not be null terminated. */ void set_alloced(char *str, size_t length, size_t alloced_length) { free_buffer(); Ptr= str; str_length= (uint32) length; DBUG_ASSERT(alloced_length < UINT_MAX32); Alloced_length= (uint32) alloced_length; } inline void set(char *str, size_t arg_length) { set_alloced(str, arg_length, arg_length); } inline void set(const char *str, size_t length) { free_buffer(); Ptr= (char*) str; str_length= (uint32) length; Alloced_length= 0; } void set(Binary_string &str, size_t offset, size_t length) { DBUG_ASSERT(&str != this); free_buffer(); Ptr= str.Ptr + offset; str_length= (uint32) length; Alloced_length= 0; if (str.Alloced_length) Alloced_length= (uint32) (str.Alloced_length - offset); } LEX_CSTRING to_lex_cstring() const { LEX_CSTRING tmp= {Ptr, str_length}; return tmp; } inline LEX_CSTRING *get_value(LEX_CSTRING *res) const { res->str= Ptr; res->length= str_length; return res; } /* Take over handling of buffer from some other object */ void reset(char *ptr_arg, size_t length_arg, size_t alloced_length_arg) { set_alloced(ptr_arg, length_arg, alloced_length_arg); alloced= ptr_arg != 0; } /* Forget about the buffer, let some other object handle it */ char *release() { char *old= Ptr; init_private_data(); return old; } /* This is used to set a new buffer for String. However if the String already has an allocated buffer, it will keep that one. It's not to be used to set the value or length of the string. */ inline void set_buffer_if_not_allocated(char *str, size_t arg_length) { if (!alloced) { /* Following should really set str_length= 0, but some code may depend on that the String length is same as buffer length. */ Ptr= str; str_length= Alloced_length= (uint32) arg_length; } /* One should set str_length before using it */ MEM_UNDEFINED(&str_length, sizeof(str_length)); } inline Binary_string& operator=(const Binary_string &s) { if (&s != this) { /* It is forbidden to do assignments like some_string = substring_of_that_string */ DBUG_ASSERT(!s.uses_buffer_owned_by(this)); set_alloced((char *) s.Ptr, s.str_length, s.Alloced_length); } return *this; } bool set_hex(ulonglong num); bool set_hex(const char *str, uint32 len); bool set_fcvt(double num, uint decimals); bool copy(); // Alloc string if not alloced bool copy(const Binary_string &s); // Allocate new string bool copy(const char *s, size_t arg_length); // Allocate new string bool copy_or_move(const char *s,size_t arg_length); /** Convert a string to a printable format. All non-convertable and control characters are replaced to 5-character sequences '\hhhh'. */ bool copy_printable_hhhh(CHARSET_INFO *to_cs, CHARSET_INFO *from_cs, const char *from, size_t from_length); bool append_ulonglong(ulonglong val); bool append_longlong(longlong val); bool append(const char *s, size_t size) { if (!size) return false; if (realloc_with_extra_if_needed(str_length + size)) return true; q_append(s, size); return false; } bool append(const LEX_CSTRING &s) { return append(s.str, s.length); } bool append(const Binary_string &s) { return append(s.ptr(), s.length()); } bool append(IO_CACHE* file, uint32 arg_length); inline bool append_char(char chr) { if (str_length < Alloced_length) { Ptr[str_length++]= chr; } else { if (unlikely(realloc_with_extra(str_length + 1))) return true; Ptr[str_length++]= chr; } return false; } bool append_hex(const char *src, uint32 srclen) { for (const char *src_end= src + srclen ; src != src_end ; src++) { if (unlikely(append_char(_dig_vec_lower[((uchar) *src) >> 4])) || unlikely(append_char(_dig_vec_lower[((uchar) *src) & 0x0F]))) return true; } return false; } bool append_hex_uint32(uint32 num) { if (reserve(8)) return true; qs_append_hex_uint32(num); return false; } bool append_with_step(const char *s, uint32 arg_length, uint32 step_alloc) { uint32 new_length= arg_length + str_length; if (new_length > Alloced_length && unlikely(realloc(new_length + step_alloc))) return true; q_append(s, arg_length); return false; } inline char *c_ptr() { if (unlikely(!Ptr)) return (char*) ""; /* Here we assume that any buffer used to initalize String has an end \0 or have at least an accessable character at end. This is to handle the case of String("Hello",5) and String("hello",5) efficiently. We have two options here. To test for !Alloced_length or !alloced. Using "Alloced_length" is slightly safer so that we do not read from potentially unintialized memory (normally not dangerous but may give warnings in valgrind), but "alloced" is safer as there are less change to get memory loss from code that is using String((char*), length) or String.set((char*), length) and does not free things properly (and there is several places in the code where this happens and it is hard to find out if any of these will call c_ptr(). */ if (unlikely(!alloced && !Ptr[str_length])) return Ptr; if (str_length < Alloced_length) { Ptr[str_length]=0; return Ptr; } (void) realloc(str_length); /* This will add end \0 */ return Ptr; } /* One should use c_ptr() instead for most cases. This will be deleted soon, kept for compatiblity. */ inline char *c_ptr_quick() { return c_ptr_safe(); } /* This is to be used only in the case when one cannot use c_ptr(). The cases are: - When one initializes String with an external buffer and length and buffer[length] could be uninitalized when c_ptr() is called. - When valgrind gives warnings about uninitialized memory with c_ptr(). */ inline char *c_ptr_safe() { if (Ptr && str_length < Alloced_length) Ptr[str_length]=0; else (void) realloc(str_length); return Ptr; } inline void free() { free_buffer(); /* We have to clear the values as some Strings, like in Field, are reused after free(). Because of this we cannot use MEM_UNDEFINED() here. */ Ptr= 0; str_length= 0; Alloced_length= extra_alloc= 0; } inline bool alloc(size_t arg_length) { /* Allocate if we need more space or if we don't have done any allocation yet (we don't want to have Ptr to be NULL for empty strings). Note that if arg_length == Alloced_length then we don't allocate. This ensures we don't do any extra allocations in protocol and String:int, but the string will not be automatically null terminated if c_ptr() is not called. */ if (arg_length <= Alloced_length && Alloced_length) return 0; return real_alloc(arg_length); } bool real_alloc(size_t arg_length); // Empties old string bool realloc_raw(size_t arg_length); bool realloc(size_t arg_length) { if (realloc_raw(arg_length+1)) return TRUE; Ptr[arg_length]= 0; // This make other funcs shorter return FALSE; } bool realloc_with_extra(size_t arg_length) { if (extra_alloc < 4096) extra_alloc= extra_alloc*2+128; if (realloc_raw(arg_length + extra_alloc)) return TRUE; Ptr[arg_length]=0; // This make other funcs shorter return FALSE; } bool realloc_with_extra_if_needed(size_t arg_length) { if (arg_length < Alloced_length) { Ptr[arg_length]=0; // behave as if realloc was called. return 0; } return realloc_with_extra(arg_length); } // Shrink the buffer, but only if it is allocated on the heap. void shrink(size_t arg_length); void move(Binary_string &s) { set_alloced(s.Ptr, s.str_length, s.Alloced_length); extra_alloc= s.extra_alloc; alloced= s.alloced; thread_specific= s.thread_specific; s.alloced= 0; } bool fill(size_t max_length,char fill); /* Replace substring with string If wrong parameter or not enough memory, do nothing */ bool replace(uint32 offset,uint32 arg_length, const char *to, uint32 length); bool replace(uint32 offset,uint32 arg_length, const Binary_string &to) { return replace(offset,arg_length,to.ptr(),to.length()); } int reserve(size_t space_needed) { DBUG_ASSERT((ulonglong) str_length + space_needed < UINT_MAX32); return realloc(str_length + space_needed); } int reserve(size_t space_needed, size_t grow_by); inline char *prep_append(uint32 arg_length, uint32 step_alloc) { uint32 new_length= arg_length + str_length; if (new_length > Alloced_length) { if (unlikely(realloc(new_length + step_alloc))) return 0; } uint32 old_length= str_length; str_length+= arg_length; return Ptr + old_length; // Area to use } void q_net_store_length(ulonglong length) { DBUG_ASSERT(Alloced_length >= (str_length + net_length_size(length))); char *pos= (char *) net_store_length((uchar *)(Ptr + str_length), length); str_length= uint32(pos - Ptr); } void q_net_store_data(const uchar *from, size_t length) { DBUG_ASSERT(length < UINT_MAX32); DBUG_ASSERT(Alloced_length >= (str_length + length + net_length_size(length))); q_net_store_length(length); q_append((const char *)from, (uint32) length); } }; class String: public Charset, public Binary_string { public: String() = default; String(size_t length_arg) :Binary_string(length_arg) { } /* NOTE: If one intend to use the c_ptr() method, the following two contructors need the size of memory for STR to be at least LEN+1 (to make room for zero termination). */ String(const char *str, size_t len, CHARSET_INFO *cs) :Charset(cs), Binary_string(str, len) { } String(char *str, size_t len, CHARSET_INFO *cs) :Charset(cs), Binary_string(str, len) { } String(const String &str) = default; String(String &&str) noexcept :Charset(std::move(str)), Binary_string(std::move(str)){} void set(String &str,size_t offset,size_t arg_length) { Binary_string::set(str, offset, arg_length); set_charset(str); } inline void set(char *str,size_t arg_length, CHARSET_INFO *cs) { Binary_string::set(str, arg_length); set_charset(cs); } inline void set(const char *str,size_t arg_length, CHARSET_INFO *cs) { Binary_string::set(str, arg_length); set_charset(cs); } bool set_ascii(const char *str, size_t arg_length); inline void set_buffer_if_not_allocated(char *str,size_t arg_length, CHARSET_INFO *cs) { Binary_string::set_buffer_if_not_allocated(str, arg_length); set_charset(cs); } bool set_int(longlong num, bool unsigned_flag, CHARSET_INFO *cs); bool set(int num, CHARSET_INFO *cs) { return set_int(num, false, cs); } bool set(uint num, CHARSET_INFO *cs) { return set_int(num, true, cs); } bool set(long num, CHARSET_INFO *cs) { return set_int(num, false, cs); } bool set(ulong num, CHARSET_INFO *cs) { return set_int(num, true, cs); } bool set(longlong num, CHARSET_INFO *cs) { return set_int(num, false, cs); } bool set(ulonglong num, CHARSET_INFO *cs) { return set_int((longlong)num, true, cs); } bool set_real(double num,uint decimals, CHARSET_INFO *cs); bool set_fcvt(double num, uint decimals) { set_charset(&my_charset_latin1); return Binary_string::set_fcvt(num, decimals); } bool set_hex(ulonglong num) { set_charset(&my_charset_latin1); return Binary_string::set_hex(num); } bool set_hex(const char *str, uint32 len) { set_charset(&my_charset_latin1); return Binary_string::set_hex(str, len); } /* Take over handling of buffer from some other object */ void reset(char *ptr_arg, size_t length_arg, size_t alloced_length_arg, CHARSET_INFO *cs) { Binary_string::reset(ptr_arg, length_arg, alloced_length_arg); set_charset(cs); } inline String& operator = (const String &s) { if (&s != this) { set_charset(s); Binary_string::operator=(s); } return *this; } bool copy() { return Binary_string::copy(); } bool copy(const String &s) { set_charset(s); return Binary_string::copy(s); } bool copy(const char *s, size_t arg_length, CHARSET_INFO *cs) { set_charset(cs); return Binary_string::copy(s, arg_length); } bool copy_or_move(const char *s, size_t arg_length, CHARSET_INFO *cs) { set_charset(cs); return Binary_string::copy_or_move(s, arg_length); } static bool needs_conversion(size_t arg_length, CHARSET_INFO *cs_from, CHARSET_INFO *cs_to, uint32 *offset); static bool needs_conversion_on_storage(size_t arg_length, CHARSET_INFO *cs_from, CHARSET_INFO *cs_to); bool copy_aligned(const char *s, size_t arg_length, size_t offset, CHARSET_INFO *cs); bool set_or_copy_aligned(const char *s, size_t arg_length, CHARSET_INFO *cs); bool can_be_safely_converted_to(CHARSET_INFO *tocs) const { if (charset() == &my_charset_bin) return Well_formed_prefix(tocs, ptr(), length()).length() == length(); String try_val; uint try_conv_error= 0; try_val.copy(ptr(), length(), charset(), tocs, &try_conv_error); return try_conv_error == 0; } bool copy(const char*s, size_t arg_length, CHARSET_INFO *csfrom, CHARSET_INFO *csto, uint *errors); bool copy(const String *str, CHARSET_INFO *tocs, uint *errors) { return copy(str->ptr(), str->length(), str->charset(), tocs, errors); } bool copy(CHARSET_INFO *tocs, CHARSET_INFO *fromcs, const char *src, size_t src_length, size_t nchars, String_copier *copier) { if (unlikely(alloc(tocs->mbmaxlen * src_length))) return true; str_length= copier->well_formed_copy(tocs, Ptr, alloced_length(), fromcs, src, (uint) src_length, (uint) nchars); set_charset(tocs); return false; } // Append without character set conversion bool append(const String &s) { return Binary_string::append(s); } inline bool append(char chr) { return Binary_string::append_char(chr); } bool append_hex(const char *src, uint32 srclen) { return Binary_string::append_hex(src, srclen); } bool append_hex(const uchar *src, uint32 srclen) { return Binary_string::append_hex((const char*)src, srclen); } bool append_introducer_and_hex(const String *str) { return append('_') || append(str->charset()->cs_name) || append(STRING_WITH_LEN(" 0x")) || append_hex(str->ptr(), (uint32) str->length()); } bool append(IO_CACHE* file, uint32 arg_length) { return Binary_string::append(file, arg_length); } inline bool append(const char *s, uint32 arg_length, uint32 step_alloc) { return append_with_step(s, arg_length, step_alloc); } // Append with optional character set conversion from ASCII (e.g. to UCS2) bool append(const LEX_STRING *ls) { DBUG_ASSERT(ls->length < UINT_MAX32 && ((ls->length == 0 && !ls->str) || ls->length == strlen(ls->str))); return append(ls->str, (uint32) ls->length); } bool append(const LEX_CSTRING *ls) { DBUG_ASSERT(ls->length < UINT_MAX32 && ((ls->length == 0 && !ls->str) || ls->length == strlen(ls->str))); return append(ls->str, (uint32) ls->length); } bool append(const LEX_CSTRING &ls) { return append(&ls); } bool append_name_value(const LEX_CSTRING &name, const LEX_CSTRING &value, uchar quot= '\0') { return append(name) || append('=') || (quot && append(quot)) || append(value) || (quot && append(quot)); } bool append(const char *s, size_t size); bool append_parenthesized(long nr, int radix= 10); // Append with optional character set conversion from cs to charset() bool append(const char *s, size_t arg_length, CHARSET_INFO *cs); bool append(const LEX_CSTRING &s, CHARSET_INFO *cs) { return append(s.str, s.length, cs); } // Append a wide character bool append_wc(my_wc_t wc) { if (reserve(mbmaxlen())) return true; int mblen= q_append_wc(wc, charset()); if (mblen > 0) return false; else if (mblen == MY_CS_ILUNI && wc != '?') return q_append_wc('?', charset()) <= 0; return true; } // Append a number with zero prefilling bool append_zerofill(uint num, uint width) { static const char zeros[15]= "00000000000000"; char intbuff[15]; uint length= (uint) (int10_to_str(num, intbuff, 10) - intbuff); if (length < width && append(zeros, width - length, &my_charset_latin1)) return true; return append(intbuff, length, &my_charset_latin1); } /* Append a bitmask in an uint32 with a translation into a C-style human readable representation, e.g.: 0x05 -> "(flag04|flag01)" @param flags - the flags to translate @param names - an array of flag names @param count - the number of available elements in "names" */ bool append_flag32_names(uint32 flags, LEX_CSTRING names[], size_t count) { bool added= false; if (flags && append('(')) return true; for (ulong i= 0; i <= 31; i++) { ulong bit= 31 - i; if (flags & (1 << bit)) { if (added && append('|')) return true; if (bit < count ? append(names[bit]) : append('?')) return true; added= true; } } if (flags && append(')')) return true; return false; } void strip_sp(); friend String *copy_if_not_alloced(String *a,String *b,uint32 arg_length); friend class Field; uint32 numchars() const { return (uint32) Charset::numchars(ptr(), end()); } int charpos(longlong i, uint32 offset=0) { if (i <= 0) return (int) i; return (int) Charset::charpos(ptr() + offset, end(), (size_t) i); } size_t lengthsp() const { return Charset::lengthsp(Ptr, str_length); } void print(String *to) const; void print_with_conversion(String *to, CHARSET_INFO *cs) const; void print(String *to, CHARSET_INFO *cs) const { if (my_charset_same(charset(), cs)) print(to); else print_with_conversion(to, cs); } static my_wc_t escaped_wc_for_single_quote(my_wc_t ch) { switch (ch) { case '\\': return '\\'; case '\0': return '0'; case '\'': return '\''; case '\n': return 'n'; case '\r': return 'r'; case '\032': return 'Z'; } return 0; } // Append for single quote using mb_wc/wc_mb Unicode conversion bool append_for_single_quote_using_mb_wc(const char *str, size_t length, CHARSET_INFO *cs); // Append for single quote with optional mb_wc/wc_mb conversion bool append_for_single_quote_opt_convert(const char *str, size_t length, CHARSET_INFO *cs) { return charset() == &my_charset_bin || cs == &my_charset_bin || my_charset_same(charset(), cs) ? append_for_single_quote(str, length) : append_for_single_quote_using_mb_wc(str, length, cs); } bool append_for_single_quote_opt_convert(const String &str) { return append_for_single_quote_opt_convert(str.ptr(), str.length(), str.charset()); } bool append_for_single_quote(const char *st, size_t len); bool append_for_single_quote(const String *s) { return append_for_single_quote(s->ptr(), s->length()); } void swap(String &s) { Charset::swap(s); Binary_string::swap(s); } uint well_formed_length() const { return (uint) Well_formed_prefix(charset(), ptr(), length()).length(); } bool is_ascii() const { if (length() == 0) return TRUE; if (charset()->mbminlen > 1) return FALSE; return !has_8bit_bytes(); } bool eq(const String *other, CHARSET_INFO *cs) const { return !sortcmp(this, other, cs); } private: bool append_semi_hex(const char *s, uint len, CHARSET_INFO *cs); }; // The following class is a backport from MySQL 5.6: /** String class wrapper with a preallocated buffer of size buff_sz This class allows to replace sequences of: char buff[12345]; String str(buff, sizeof(buff)); str.length(0); with a simple equivalent declaration: StringBuffer<12345> str; */ template class StringBuffer : public String { char buff[buff_sz]; public: StringBuffer() : String(buff, buff_sz, &my_charset_bin) { length(0); } explicit StringBuffer(CHARSET_INFO *cs) : String(buff, buff_sz, cs) { length(0); } void set_buffer_if_not_allocated(CHARSET_INFO *cs) { if (!is_alloced()) { Ptr= buff; Alloced_length= (uint32) buff_sz; } str_length= 0; /* Safety, not required */ /* One should set str_length before using it */ MEM_UNDEFINED(&str_length, sizeof(str_length)); set_charset(cs); } }; template class BinaryStringBuffer : public Binary_string { char buff[buff_sz]; public: BinaryStringBuffer() : Binary_string(buff, buff_sz) { length(0); } }; static inline bool check_if_only_end_space(CHARSET_INFO *cs, const char *str, const char *end) { return str + cs->scan(str, end, MY_SEQ_SPACES) == end; } int append_query_string(CHARSET_INFO *csinfo, String *to, const char *str, size_t len, bool no_backslash); #endif /* SQL_STRING_INCLUDED */ mysql/server/private/sql_class.h000064400001012234151027430560013034 0ustar00/* Copyright (c) 2009, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_CLASS_INCLUDED #define SQL_CLASS_INCLUDED /* Classes in mysql */ #include #include #include "dur_prop.h" #include #include "sql_const.h" #include "lex_ident.h" #include #include "log.h" #include "rpl_tblmap.h" #include "mdl.h" #include "field.h" // Create_field #include "opt_trace_context.h" #include "probes_mysql.h" #include "sql_locale.h" /* my_locale_st */ #include "sql_profile.h" /* PROFILING */ #include "scheduler.h" /* thd_scheduler */ #include "protocol.h" /* Protocol_text, Protocol_binary */ #include "violite.h" /* vio_is_connected */ #include "thr_lock.h" /* thr_lock_type, THR_LOCK_DATA, THR_LOCK_INFO */ #include "thr_timer.h" #include "thr_malloc.h" #include "log_slow.h" /* LOG_SLOW_DISABLE_... */ #include #include "sql_digest_stream.h" // sql_digest_state #include #include #include #include #include #include "session_tracker.h" #include "backup.h" #include "xa.h" #include "scope.h" #include "ddl_log.h" /* DDL_LOG_STATE */ #include "ha_handler_stats.h" // ha_handler_stats */ extern "C" void set_thd_stage_info(void *thd, const PSI_stage_info *new_stage, PSI_stage_info *old_stage, const char *calling_func, const char *calling_file, const unsigned int calling_line); #define THD_STAGE_INFO(thd, stage) \ (thd)->enter_stage(&stage, __func__, __FILE__, __LINE__) #include "my_apc.h" #include "rpl_gtid.h" #include "wsrep.h" #include "wsrep_on.h" #include #ifdef WITH_WSREP /* wsrep-lib */ #include "wsrep_client_service.h" #include "wsrep_client_state.h" #include "wsrep_mutex.h" #include "wsrep_condition_variable.h" class Wsrep_applier_service; enum wsrep_consistency_check_mode { NO_CONSISTENCY_CHECK, CONSISTENCY_CHECK_DECLARED, CONSISTENCY_CHECK_RUNNING, }; #endif /* WITH_WSREP */ class Reprepare_observer; class Relay_log_info; struct rpl_group_info; class Rpl_filter; class Query_log_event; class Load_log_event; class Log_event_writer; class sp_rcontext; class sp_cache; class Lex_input_stream; class Parser_state; class Rows_log_event; class Sroutine_hash_entry; class user_var_entry; struct Trans_binlog_info; class rpl_io_thread_info; class rpl_sql_thread_info; #ifdef HAVE_REPLICATION struct Slave_info; #endif enum enum_ha_read_modes { RFIRST, RNEXT, RPREV, RLAST, RKEY, RNEXT_SAME }; enum enum_duplicates { DUP_ERROR, DUP_REPLACE, DUP_UPDATE }; enum enum_delay_key_write { DELAY_KEY_WRITE_NONE, DELAY_KEY_WRITE_ON, DELAY_KEY_WRITE_ALL }; enum enum_slave_exec_mode { SLAVE_EXEC_MODE_STRICT, SLAVE_EXEC_MODE_IDEMPOTENT, SLAVE_EXEC_MODE_LAST_BIT }; enum enum_slave_run_triggers_for_rbr { SLAVE_RUN_TRIGGERS_FOR_RBR_NO, SLAVE_RUN_TRIGGERS_FOR_RBR_YES, SLAVE_RUN_TRIGGERS_FOR_RBR_LOGGING, SLAVE_RUN_TRIGGERS_FOR_RBR_ENFORCE}; enum enum_slave_type_conversions { SLAVE_TYPE_CONVERSIONS_ALL_LOSSY, SLAVE_TYPE_CONVERSIONS_ALL_NON_LOSSY}; /* COLUMNS_READ: A column is goind to be read. COLUMNS_WRITE: A column is going to be written to. MARK_COLUMNS_READ: A column is goind to be read. A bit in read set is set to inform handler that the field is to be read. If field list contains duplicates, then thd->dup_field is set to point to the last found duplicate. MARK_COLUMNS_WRITE: A column is going to be written to. A bit is set in write set to inform handler that it needs to update this field in write_row and update_row. */ enum enum_column_usage { COLUMNS_READ, COLUMNS_WRITE, MARK_COLUMNS_READ, MARK_COLUMNS_WRITE}; static inline bool should_mark_column(enum_column_usage column_usage) { return column_usage >= MARK_COLUMNS_READ; } enum enum_filetype { FILETYPE_CSV, FILETYPE_XML }; enum enum_binlog_row_image { /** PKE in the before image and changed columns in the after image */ BINLOG_ROW_IMAGE_MINIMAL= 0, /** Whenever possible, before and after image contain all columns except blobs. */ BINLOG_ROW_IMAGE_NOBLOB= 1, /** All columns in both before and after image. */ BINLOG_ROW_IMAGE_FULL= 2 }; /* Bits for different SQL modes modes (including ANSI mode) */ #define MODE_REAL_AS_FLOAT (1ULL << 0) #define MODE_PIPES_AS_CONCAT (1ULL << 1) #define MODE_ANSI_QUOTES (1ULL << 2) #define MODE_IGNORE_SPACE (1ULL << 3) #define MODE_IGNORE_BAD_TABLE_OPTIONS (1ULL << 4) #define MODE_ONLY_FULL_GROUP_BY (1ULL << 5) #define MODE_NO_UNSIGNED_SUBTRACTION (1ULL << 6) #define MODE_NO_DIR_IN_CREATE (1ULL << 7) #define MODE_POSTGRESQL (1ULL << 8) #define MODE_ORACLE (1ULL << 9) #define MODE_MSSQL (1ULL << 10) #define MODE_DB2 (1ULL << 11) #define MODE_MAXDB (1ULL << 12) #define MODE_NO_KEY_OPTIONS (1ULL << 13) #define MODE_NO_TABLE_OPTIONS (1ULL << 14) #define MODE_NO_FIELD_OPTIONS (1ULL << 15) #define MODE_MYSQL323 (1ULL << 16) #define MODE_MYSQL40 (1ULL << 17) #define MODE_ANSI (1ULL << 18) #define MODE_NO_AUTO_VALUE_ON_ZERO (1ULL << 19) #define MODE_NO_BACKSLASH_ESCAPES (1ULL << 20) #define MODE_STRICT_TRANS_TABLES (1ULL << 21) #define MODE_STRICT_ALL_TABLES (1ULL << 22) #define MODE_NO_ZERO_IN_DATE (1ULL << 23) #define MODE_NO_ZERO_DATE (1ULL << 24) #define MODE_INVALID_DATES (1ULL << 25) #define MODE_ERROR_FOR_DIVISION_BY_ZERO (1ULL << 26) #define MODE_TRADITIONAL (1ULL << 27) #define MODE_NO_AUTO_CREATE_USER (1ULL << 28) #define MODE_HIGH_NOT_PRECEDENCE (1ULL << 29) #define MODE_NO_ENGINE_SUBSTITUTION (1ULL << 30) #define MODE_PAD_CHAR_TO_FULL_LENGTH (1ULL << 31) /* SQL mode bits defined above are common for MariaDB and MySQL */ #define MODE_MASK_MYSQL_COMPATIBLE 0xFFFFFFFFULL /* The following modes are specific to MariaDB */ #define MODE_EMPTY_STRING_IS_NULL (1ULL << 32) #define MODE_SIMULTANEOUS_ASSIGNMENT (1ULL << 33) #define MODE_TIME_ROUND_FRACTIONAL (1ULL << 34) /* The following modes are specific to MySQL */ #define MODE_MYSQL80_TIME_TRUNCATE_FRACTIONAL (1ULL << 32) /* Bits for different old style modes */ #define OLD_MODE_NO_DUP_KEY_WARNINGS_WITH_IGNORE (1 << 0) #define OLD_MODE_NO_PROGRESS_INFO (1 << 1) #define OLD_MODE_ZERO_DATE_TIME_CAST (1 << 2) #define OLD_MODE_UTF8_IS_UTF8MB3 (1 << 3) extern char internal_table_name[2]; extern char empty_c_string[1]; extern MYSQL_PLUGIN_IMPORT const char **errmesg; extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd); extern "C" unsigned long long thd_query_id(const MYSQL_THD thd); extern "C" size_t thd_query_safe(MYSQL_THD thd, char *buf, size_t buflen); extern "C" const char *thd_priv_user(MYSQL_THD thd, size_t *length); extern "C" const char *thd_priv_host(MYSQL_THD thd, size_t *length); extern "C" const char *thd_user_name(MYSQL_THD thd); extern "C" const char *thd_client_host(MYSQL_THD thd); extern "C" const char *thd_client_ip(MYSQL_THD thd); extern "C" LEX_CSTRING *thd_current_db(MYSQL_THD thd); extern "C" int thd_current_status(MYSQL_THD thd); extern "C" enum enum_server_command thd_current_command(MYSQL_THD thd); extern "C" int thd_double_innodb_cardinality(MYSQL_THD thd); /** @class CSET_STRING @brief Character set armed LEX_STRING */ class CSET_STRING { private: LEX_STRING string; CHARSET_INFO *cs; public: CSET_STRING() : cs(&my_charset_bin) { string.str= NULL; string.length= 0; } CSET_STRING(char *str_arg, size_t length_arg, CHARSET_INFO *cs_arg) : cs(cs_arg) { DBUG_ASSERT(cs_arg != NULL); string.str= str_arg; string.length= length_arg; } inline char *str() const { return string.str; } inline size_t length() const { return string.length; } CHARSET_INFO *charset() const { return cs; } friend LEX_STRING * thd_query_string (MYSQL_THD thd); }; class Recreate_info { ha_rows m_records_copied; ha_rows m_records_duplicate; public: Recreate_info() :m_records_copied(0), m_records_duplicate(0) { } Recreate_info(ha_rows records_copied, ha_rows records_duplicate) :m_records_copied(records_copied), m_records_duplicate(records_duplicate) { } ha_rows records_copied() const { return m_records_copied; } ha_rows records_duplicate() const { return m_records_duplicate; } ha_rows records_processed() const { return m_records_copied + m_records_duplicate; } }; #define TC_HEURISTIC_RECOVER_COMMIT 1 #define TC_HEURISTIC_RECOVER_ROLLBACK 2 extern ulong tc_heuristic_recover; typedef struct st_user_var_events { user_var_entry *user_var_event; char *value; size_t length; const Type_handler *th; uint charset_number; } BINLOG_USER_VAR_EVENT; /* The COPY_INFO structure is used by INSERT/REPLACE code. The schema of the row counting by the INSERT/INSERT ... ON DUPLICATE KEY UPDATE code: If a row is inserted then the copied variable is incremented. If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the new data differs from the old one then the copied and the updated variables are incremented. The touched variable is incremented if a row was touched by the update part of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row was actually changed or not. */ typedef struct st_copy_info { ha_rows records; /**< Number of processed records */ ha_rows deleted; /**< Number of deleted records */ ha_rows updated; /**< Number of updated records */ ha_rows copied; /**< Number of copied records */ ha_rows accepted_rows; /**< Number of accepted original rows (same as number of rows in RETURNING) */ ha_rows error_count; ha_rows touched; /* Number of touched records */ enum enum_duplicates handle_duplicates; int escape_char, last_errno; bool ignore; /* for INSERT ... UPDATE */ List *update_fields; List *update_values; /* for VIEW ... WITH CHECK OPTION */ TABLE_LIST *view; TABLE_LIST *table_list; /* Normal table */ } COPY_INFO; class Key_part_spec :public Sql_alloc { public: Lex_ident field_name; uint length; bool generated; Key_part_spec(const LEX_CSTRING *name, uint len, bool gen= false) : field_name(*name), length(len), generated(gen) {} bool operator==(const Key_part_spec& other) const; /** Construct a copy of this Key_part_spec. field_name is copied by-pointer as it is known to never change. At the same time 'length' may be reset in mysql_prepare_create_table, and this is why we supply it with a copy. @return If out of memory, 0 is returned and an error is set in THD. */ Key_part_spec *clone(MEM_ROOT *mem_root) const { return new (mem_root) Key_part_spec(*this); } bool check_key_for_blob(const class handler *file) const; bool check_key_length_for_blob() const; bool check_primary_key_for_blob(const class handler *file) const { return check_key_for_blob(file) || check_key_length_for_blob(); } bool check_foreign_key_for_blob(const class handler *file) const { return check_key_for_blob(file) || check_key_length_for_blob(); } bool init_multiple_key_for_blob(const class handler *file); }; class Alter_drop :public Sql_alloc { public: enum drop_type { KEY, COLUMN, FOREIGN_KEY, CHECK_CONSTRAINT, PERIOD }; const char *name; enum drop_type type; bool drop_if_exists; Alter_drop(enum drop_type par_type,const char *par_name, bool par_exists) :name(par_name), type(par_type), drop_if_exists(par_exists) { DBUG_ASSERT(par_name != NULL); } /** Used to make a clone of this object for ALTER/CREATE TABLE @sa comment for Key_part_spec::clone */ Alter_drop *clone(MEM_ROOT *mem_root) const { return new (mem_root) Alter_drop(*this); } const char *type_name() { return type == COLUMN ? "COLUMN" : type == CHECK_CONSTRAINT ? "CONSTRAINT" : type == PERIOD ? "PERIOD" : type == KEY ? "INDEX" : "FOREIGN KEY"; } }; class Alter_column :public Sql_alloc { public: LEX_CSTRING name; LEX_CSTRING new_name; Virtual_column_info *default_value; bool alter_if_exists; Alter_column(LEX_CSTRING par_name, Virtual_column_info *expr, bool par_exists) :name(par_name), new_name{NULL, 0}, default_value(expr), alter_if_exists(par_exists) {} Alter_column(LEX_CSTRING par_name, LEX_CSTRING _new_name, bool exists) :name(par_name), new_name(_new_name), default_value(NULL), alter_if_exists(exists) {} /** Used to make a clone of this object for ALTER/CREATE TABLE @sa comment for Key_part_spec::clone */ Alter_column *clone(MEM_ROOT *mem_root) const { return new (mem_root) Alter_column(*this); } bool is_rename() { DBUG_ASSERT(!new_name.str || !default_value); return new_name.str; } }; class Alter_rename_key : public Sql_alloc { public: LEX_CSTRING old_name; LEX_CSTRING new_name; bool alter_if_exists; Alter_rename_key(LEX_CSTRING old_name_arg, LEX_CSTRING new_name_arg, bool exists) : old_name(old_name_arg), new_name(new_name_arg), alter_if_exists(exists) {} Alter_rename_key *clone(MEM_ROOT *mem_root) const { return new (mem_root) Alter_rename_key(*this); } }; /* An ALTER INDEX operation that changes the ignorability of an index. */ class Alter_index_ignorability: public Sql_alloc { public: Alter_index_ignorability(const char *name, bool is_ignored, bool if_exists) : m_name(name), m_is_ignored(is_ignored), m_if_exists(if_exists) { assert(name != NULL); } const char *name() const { return m_name; } bool if_exists() const { return m_if_exists; } /* The ignorability after the operation is performed. */ bool is_ignored() const { return m_is_ignored; } Alter_index_ignorability *clone(MEM_ROOT *mem_root) const { return new (mem_root) Alter_index_ignorability(*this); } private: const char *m_name; bool m_is_ignored; bool m_if_exists; }; class Key :public Sql_alloc, public DDL_options { public: enum Keytype { PRIMARY, UNIQUE, MULTIPLE, FULLTEXT, SPATIAL, FOREIGN_KEY, IGNORE_KEY}; enum Keytype type; KEY_CREATE_INFO key_create_info; List columns; LEX_CSTRING name; engine_option_value *option_list; bool generated; bool invisible; bool without_overlaps; bool old; uint length; Lex_ident period; Key(enum Keytype type_par, const LEX_CSTRING *name_arg, ha_key_alg algorithm_arg, bool generated_arg, DDL_options_st ddl_options) :DDL_options(ddl_options), type(type_par), key_create_info(default_key_create_info), name(*name_arg), option_list(NULL), generated(generated_arg), invisible(false), without_overlaps(false), old(false), length(0) { key_create_info.algorithm= algorithm_arg; } Key(enum Keytype type_par, const LEX_CSTRING *name_arg, KEY_CREATE_INFO *key_info_arg, bool generated_arg, List *cols, engine_option_value *create_opt, DDL_options_st ddl_options) :DDL_options(ddl_options), type(type_par), key_create_info(*key_info_arg), columns(*cols), name(*name_arg), option_list(create_opt), generated(generated_arg), invisible(false), without_overlaps(false), old(false), length(0) {} Key(const Key &rhs, MEM_ROOT *mem_root); virtual ~Key() = default; /* Equality comparison of keys (ignoring name) */ friend bool is_foreign_key_prefix(Key *a, Key *b); /** Used to make a clone of this object for ALTER/CREATE TABLE @sa comment for Key_part_spec::clone */ virtual Key *clone(MEM_ROOT *mem_root) const { return new (mem_root) Key(*this, mem_root); } }; class Foreign_key: public Key { public: enum fk_match_opt { FK_MATCH_UNDEF, FK_MATCH_FULL, FK_MATCH_PARTIAL, FK_MATCH_SIMPLE}; LEX_CSTRING constraint_name; LEX_CSTRING ref_db; LEX_CSTRING ref_table; List ref_columns; enum enum_fk_option delete_opt, update_opt; enum fk_match_opt match_opt; Foreign_key(const LEX_CSTRING *name_arg, List *cols, const LEX_CSTRING *constraint_name_arg, const LEX_CSTRING *ref_db_arg, const LEX_CSTRING *ref_table_arg, List *ref_cols, enum_fk_option delete_opt_arg, enum_fk_option update_opt_arg, fk_match_opt match_opt_arg, DDL_options ddl_options) :Key(FOREIGN_KEY, name_arg, &default_key_create_info, 0, cols, NULL, ddl_options), constraint_name(*constraint_name_arg), ref_db(*ref_db_arg), ref_table(*ref_table_arg), ref_columns(*ref_cols), delete_opt(delete_opt_arg), update_opt(update_opt_arg), match_opt(match_opt_arg) { } Foreign_key(const Foreign_key &rhs, MEM_ROOT *mem_root); /** Used to make a clone of this object for ALTER/CREATE TABLE @sa comment for Key_part_spec::clone */ Key *clone(MEM_ROOT *mem_root) const override { return new (mem_root) Foreign_key(*this, mem_root); } /* Used to validate foreign key options */ bool validate(List &table_fields); }; typedef struct st_mysql_lock { TABLE **table; THR_LOCK_DATA **locks; uint table_count,lock_count; uint flags; } MYSQL_LOCK; class LEX_COLUMN : public Sql_alloc { public: String column; privilege_t rights; LEX_COLUMN (const String& x,const privilege_t & y ): column (x),rights (y) {} }; class MY_LOCALE; /** Query_cache_tls -- query cache thread local data. */ struct Query_cache_block; struct Query_cache_tls { /* 'first_query_block' should be accessed only via query cache functions and methods to maintain proper locking. */ Query_cache_block *first_query_block; void set_first_query_block(Query_cache_block *first_query_block_arg) { first_query_block= first_query_block_arg; } Query_cache_tls() :first_query_block(NULL) {} }; /* SIGNAL / RESIGNAL / GET DIAGNOSTICS */ /** This enumeration list all the condition item names of a condition in the SQL condition area. */ typedef enum enum_diag_condition_item_name { /* Conditions that can be set by the user (SIGNAL/RESIGNAL), and by the server implementation. */ DIAG_CLASS_ORIGIN= 0, FIRST_DIAG_SET_PROPERTY= DIAG_CLASS_ORIGIN, DIAG_SUBCLASS_ORIGIN= 1, DIAG_CONSTRAINT_CATALOG= 2, DIAG_CONSTRAINT_SCHEMA= 3, DIAG_CONSTRAINT_NAME= 4, DIAG_CATALOG_NAME= 5, DIAG_SCHEMA_NAME= 6, DIAG_TABLE_NAME= 7, DIAG_COLUMN_NAME= 8, DIAG_CURSOR_NAME= 9, DIAG_MESSAGE_TEXT= 10, DIAG_MYSQL_ERRNO= 11, LAST_DIAG_SET_PROPERTY= DIAG_MYSQL_ERRNO } Diag_condition_item_name; /** Name of each diagnostic condition item. This array is indexed by Diag_condition_item_name. */ extern const LEX_CSTRING Diag_condition_item_names[]; /** These states are bit coded with HARD. For each state there must be a pair , and _HARD. */ enum killed_state { NOT_KILLED= 0, KILL_HARD_BIT= 1, /* Bit for HARD KILL */ KILL_BAD_DATA= 2, KILL_BAD_DATA_HARD= 3, KILL_QUERY= 4, KILL_QUERY_HARD= 5, /* ABORT_QUERY signals to the query processor to stop execution ASAP without issuing an error. Instead a warning is issued, and when possible a partial query result is returned to the client. */ ABORT_QUERY= 6, ABORT_QUERY_HARD= 7, KILL_TIMEOUT= 8, KILL_TIMEOUT_HARD= 9, /* When binlog reading thread connects to the server it kills all the binlog threads with the same ID. */ KILL_SLAVE_SAME_ID= 10, /* All of the following killed states will kill the connection KILL_CONNECTION must be the first of these and it must start with an even number (becasue of HARD bit)! */ KILL_CONNECTION= 12, KILL_CONNECTION_HARD= 13, KILL_SYSTEM_THREAD= 14, KILL_SYSTEM_THREAD_HARD= 15, KILL_SERVER= 16, KILL_SERVER_HARD= 17, /* Used in threadpool to signal wait timeout. */ KILL_WAIT_TIMEOUT= 18, KILL_WAIT_TIMEOUT_HARD= 19 }; #define killed_mask_hard(killed) ((killed_state) ((killed) & ~KILL_HARD_BIT)) enum killed_type { KILL_TYPE_ID, KILL_TYPE_USER, KILL_TYPE_QUERY }; #define SECONDS_TO_WAIT_FOR_KILL 2 #define SECONDS_TO_WAIT_FOR_DUMP_THREAD_KILL 10 #if !defined(_WIN32) && defined(HAVE_SELECT) /* my_sleep() can wait for sub second times */ #define WAIT_FOR_KILL_TRY_TIMES 20 #else #define WAIT_FOR_KILL_TRY_TIMES 2 #endif #include "sql_lex.h" /* Must be here */ class Delayed_insert; class select_result; class Time_zone; #define THD_SENTRY_MAGIC 0xfeedd1ff #define THD_SENTRY_GONE 0xdeadbeef #define THD_CHECK_SENTRY(thd) DBUG_ASSERT(thd->dbug_sentry == THD_SENTRY_MAGIC) typedef struct system_variables { /* How dynamically allocated system variables are handled: The global_system_variables and max_system_variables are "authoritative" They both should have the same 'version' and 'size'. When attempting to access a dynamic variable, if the session version is out of date, then the session version is updated and realloced if neccessary and bytes copied from global to make up for missing data. Note that one should use my_bool instead of bool here, as the variables are used with my_getopt.c */ ulong dynamic_variables_version; char* dynamic_variables_ptr; uint dynamic_variables_head; /* largest valid variable offset */ uint dynamic_variables_size; /* how many bytes are in use */ ulonglong max_heap_table_size; ulonglong tmp_memory_table_size; ulonglong tmp_disk_table_size; ulonglong long_query_time; ulonglong max_statement_time; ulonglong optimizer_switch; ulonglong optimizer_trace; sql_mode_t sql_mode; ///< which non-standard SQL behaviour should be enabled sql_mode_t old_behavior; ///< which old SQL behaviour should be enabled ulonglong option_bits; ///< OPTION_xxx constants, e.g. OPTION_PROFILING ulonglong join_buff_space_limit; ulonglong log_slow_filter; ulonglong log_slow_verbosity; ulonglong log_slow_disabled_statements; ulonglong log_disabled_statements; ulonglong note_verbosity; ulonglong bulk_insert_buff_size; ulonglong join_buff_size; ulonglong sortbuff_size; ulonglong default_regex_flags; ulonglong max_mem_used; /* A bitmap of OPTIMIZER_ADJ_* flags (defined in sql_priv.h). See sys_vars.cc:adjust_secondary_key_cost for symbolic names. */ ulonglong optimizer_adjust_secondary_key_costs; /** Place holders to store Multi-source variables in sys_var.cc during update and show of variables. */ ulonglong slave_skip_counter; ulonglong max_relay_log_size; ha_rows select_limit; ha_rows max_join_size; ha_rows expensive_subquery_limit; uint analyze_max_length; ulong auto_increment_increment, auto_increment_offset; #ifdef WITH_WSREP /* Stored values of the auto_increment_increment and auto_increment_offset that are will be restored when wsrep_auto_increment_control will be set to 'OFF', because the setting it to 'ON' leads to overwriting of the original values (which are set by the user) by calculated ones (which are based on the cluster size): */ ulong saved_auto_increment_increment, saved_auto_increment_offset; ulong saved_lock_wait_timeout; ulonglong wsrep_gtid_seq_no; #endif /* WITH_WSREP */ uint eq_range_index_dive_limit; ulong column_compression_zlib_strategy; ulong lock_wait_timeout; ulong join_cache_level; ulong max_allowed_packet; ulong max_error_count; ulong max_length_for_sort_data; ulong max_recursive_iterations; ulong max_sort_length; ulong max_tmp_tables; ulong max_insert_delayed_threads; ulong min_examined_row_limit; ulong net_buffer_length; ulong net_interactive_timeout; ulong net_read_timeout; ulong net_retry_count; ulong net_wait_timeout; ulong net_write_timeout; ulonglong optimizer_join_limit_pref_ratio; ulong optimizer_prune_level; ulong optimizer_search_depth; ulong optimizer_selectivity_sampling_limit; ulong optimizer_use_condition_selectivity; ulong optimizer_max_sel_arg_weight; ulong optimizer_max_sel_args; ulong optimizer_trace_max_mem_size; ulong use_stat_tables; double sample_percentage; ulong histogram_size; ulong histogram_type; ulong preload_buff_size; ulong profiling_history_size; ulong read_buff_size; ulong read_rnd_buff_size; ulong mrr_buff_size; ulong div_precincrement; /* Total size of all buffers used by the subselect_rowid_merge_engine. */ ulong rowid_merge_buff_size; ulong max_sp_recursion_depth; ulong default_week_format; ulong max_seeks_for_key; ulong range_alloc_block_size; ulong query_alloc_block_size; ulong query_prealloc_size; ulong trans_alloc_block_size; ulong trans_prealloc_size; ulong log_warnings; ulong log_slow_max_warnings; /* Flags for slow log filtering */ ulong log_slow_rate_limit; ulong binlog_format; ///< binlog format for this thd (see enum_binlog_format) ulong binlog_row_image; ulong progress_report_time; ulong completion_type; ulong query_cache_type; ulong tx_isolation; ulong updatable_views_with_limit; ulong alter_algorithm; int max_user_connections; ulong server_id; /** In slave thread we need to know in behalf of which thread the query is being run to replicate temp tables properly */ my_thread_id pseudo_thread_id; /** When replicating an event group with GTID, keep these values around so slave binlog can receive the same GTID as the original. */ uint32 gtid_domain_id; uint64 gtid_seq_no; uint group_concat_max_len; /** Default transaction access mode. READ ONLY (true) or READ WRITE (false). */ my_bool tx_read_only; my_bool low_priority_updates; my_bool query_cache_wlock_invalidate; my_bool keep_files_on_create; my_bool old_mode; my_bool old_passwords; my_bool big_tables; my_bool only_standard_compliant_cte; my_bool query_cache_strip_comments; my_bool sql_log_slow; my_bool sql_log_bin; my_bool binlog_annotate_row_events; my_bool binlog_direct_non_trans_update; my_bool column_compression_zlib_wrap; plugin_ref table_plugin; plugin_ref tmp_table_plugin; plugin_ref enforced_table_plugin; /* Only charset part of these variables is sensible */ CHARSET_INFO *character_set_filesystem; CHARSET_INFO *character_set_client; CHARSET_INFO *character_set_results; /* Both charset and collation parts of these variables are important */ CHARSET_INFO *collation_server; CHARSET_INFO *collation_database; CHARSET_INFO *collation_connection; /* Names. These will be allocated in buffers in thd */ LEX_CSTRING default_master_connection; /* Error messages */ MY_LOCALE *lc_messages; const char ***errmsgs; /* lc_messages->errmsg->errmsgs */ /* Locale Support */ MY_LOCALE *lc_time_names; Time_zone *time_zone; my_bool sysdate_is_now; /* deadlock detection */ ulong wt_timeout_short, wt_deadlock_search_depth_short; ulong wt_timeout_long, wt_deadlock_search_depth_long; my_bool wsrep_on; my_bool wsrep_causal_reads; uint wsrep_sync_wait; ulong wsrep_retry_autocommit; ulonglong wsrep_trx_fragment_size; ulong wsrep_trx_fragment_unit; ulong wsrep_OSU_method; my_bool wsrep_dirty_reads; double long_query_time_double, max_statement_time_double; my_bool pseudo_slave_mode; char *session_track_system_variables; ulong session_track_transaction_info; my_bool session_track_schema; my_bool session_track_state_change; #ifdef USER_VAR_TRACKING my_bool session_track_user_variables; #endif // USER_VAR_TRACKING my_bool tcp_nodelay; ulong threadpool_priority; uint idle_transaction_timeout; uint idle_readonly_transaction_timeout; uint idle_write_transaction_timeout; uint column_compression_threshold; uint column_compression_zlib_level; uint in_subquery_conversion_threshold; ulonglong max_rowid_filter_size; vers_asof_timestamp_t vers_asof_timestamp; ulong vers_alter_history; } SV; /** Per thread status variables. Must be long/ulong up to last_system_status_var so that add_to_status/add_diff_to_status can work. */ typedef struct system_status_var { ulong column_compressions; ulong column_decompressions; ulong com_stat[(uint) SQLCOM_END]; ulong com_create_tmp_table; ulong com_drop_tmp_table; ulong com_other; ulong com_stmt_prepare; ulong com_stmt_reprepare; ulong com_stmt_execute; ulong com_stmt_send_long_data; ulong com_stmt_fetch; ulong com_stmt_reset; ulong com_stmt_close; ulong com_register_slave; ulong created_tmp_disk_tables_; ulong created_tmp_tables_; ulong ha_commit_count; ulong ha_delete_count; ulong ha_read_first_count; ulong ha_read_last_count; ulong ha_read_key_count; ulong ha_read_next_count; ulong ha_read_prev_count; ulong ha_read_retry_count; ulong ha_read_rnd_count; ulong ha_read_rnd_next_count; ulong ha_read_rnd_deleted_count; /* This number doesn't include calls to the default implementation and calls made by range access. The intent is to count only calls made by BatchedKeyAccess. */ ulong ha_mrr_init_count; ulong ha_mrr_key_refills_count; ulong ha_mrr_rowid_refills_count; ulong ha_rollback_count; ulong ha_update_count; ulong ha_write_count; /* The following are for internal temporary tables */ ulong ha_tmp_update_count; ulong ha_tmp_write_count; ulong ha_tmp_delete_count; ulong ha_prepare_count; ulong ha_icp_attempts; ulong ha_icp_match; ulong ha_discover_count; ulong ha_savepoint_count; ulong ha_savepoint_rollback_count; ulong ha_external_lock_count; ulong opened_tables; ulong opened_shares; ulong opened_views; /* +1 opening a view */ ulong select_full_join_count_; ulong select_full_range_join_count_; ulong select_range_count_; ulong select_range_check_count_; ulong select_scan_count_; ulong update_scan_count; ulong delete_scan_count; ulong executed_triggers; ulong long_query_count; ulong filesort_merge_passes_; ulong filesort_range_count_; ulong filesort_rows_; ulong filesort_scan_count_; ulong filesort_pq_sorts_; /* Features used */ ulong feature_custom_aggregate_functions; /* +1 when custom aggregate functions are used */ ulong feature_dynamic_columns; /* +1 when creating a dynamic column */ ulong feature_fulltext; /* +1 when MATCH is used */ ulong feature_gis; /* +1 opening a table with GIS features */ ulong feature_invisible_columns; /* +1 opening a table with invisible column */ ulong feature_json; /* +1 when JSON function appears in the statement */ ulong feature_locale; /* +1 when LOCALE is set */ ulong feature_subquery; /* +1 when subqueries are used */ ulong feature_system_versioning; /* +1 opening a table WITH SYSTEM VERSIONING */ ulong feature_application_time_periods; /* +1 opening a table with application-time period */ ulong feature_insert_returning; /* +1 when INSERT...RETURNING is used */ ulong feature_timezone; /* +1 when XPATH is used */ ulong feature_trigger; /* +1 opening a table with triggers */ ulong feature_xml; /* +1 when XPATH is used */ ulong feature_window_functions; /* +1 when window functions are used */ /* From MASTER_GTID_WAIT usage */ ulong master_gtid_wait_timeouts; /* Number of timeouts */ ulong master_gtid_wait_time; /* Time in microseconds */ ulong master_gtid_wait_count; ulong empty_queries; ulong access_denied_errors; ulong lost_connections; ulong max_statement_time_exceeded; /* Number of times where column info was not sent with prepared statement metadata. */ ulong skip_metadata_count; /* Number of statements sent from the client */ ulong questions; /* IMPORTANT! SEE last_system_status_var DEFINITION BELOW. Below 'last_system_status_var' are all variables that cannot be handled automatically by add_to_status()/add_diff_to_status(). */ ulonglong bytes_received; ulonglong bytes_sent; ulonglong rows_read; ulonglong rows_sent; ulonglong rows_tmp_read; ulonglong binlog_bytes_written; ulonglong table_open_cache_hits; ulonglong table_open_cache_misses; ulonglong table_open_cache_overflows; double last_query_cost; double cpu_time, busy_time; uint32 threads_running; /* Don't initialize */ /* Memory used for thread local storage */ int64 max_local_memory_used; volatile int64 local_memory_used; /* Memory allocated for global usage */ volatile int64 global_memory_used; } STATUS_VAR; /* This is used for 'SHOW STATUS'. It must be updated to the last ulong variable in system_status_var which is makes sense to add to the global counter */ #define last_system_status_var questions #define last_cleared_system_status_var local_memory_used /** Number of contiguous global status variables */ constexpr int COUNT_GLOBAL_STATUS_VARS= int(offsetof(STATUS_VAR, last_system_status_var) / sizeof(ulong)) + 1; /* Global status variables */ extern ulong feature_files_opened_with_delayed_keys, feature_check_constraint; void add_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var); void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var, STATUS_VAR *dec_var); uint calc_sum_of_all_status(STATUS_VAR *to); static inline void calc_sum_of_all_status_if_needed(STATUS_VAR *to) { if (to->local_memory_used == 0) { mysql_mutex_lock(&LOCK_status); *to= global_status_var; mysql_mutex_unlock(&LOCK_status); calc_sum_of_all_status(to); DBUG_ASSERT(to->local_memory_used); } } /* Update global_memory_used. We have to do this with atomic_add as the global value can change outside of LOCK_status. */ static inline void update_global_memory_status(int64 size) { DBUG_PRINT("info", ("global memory_used: %lld size: %lld", (longlong) global_status_var.global_memory_used, size)); // workaround for gcc 4.2.4-1ubuntu4 -fPIE (from DEB_BUILD_HARDENING=1) int64 volatile * volatile ptr= &global_status_var.global_memory_used; my_atomic_add64_explicit(ptr, size, MY_MEMORY_ORDER_RELAXED); } /** Get collation by name, send error to client on failure. @param name Collation name @param name_cs Character set of the name string @return @retval NULL on error @retval Pointter to CHARSET_INFO with the given name on success */ static inline CHARSET_INFO * mysqld_collation_get_by_name(const char *name, myf utf8_flag, CHARSET_INFO *name_cs= system_charset_info) { CHARSET_INFO *cs; MY_CHARSET_LOADER loader; my_charset_loader_init_mysys(&loader); if (!(cs= my_collation_get_by_name(&loader, name, MYF(utf8_flag)))) { ErrConvString err(name, name_cs); my_error(ER_UNKNOWN_COLLATION, MYF(0), err.ptr()); if (loader.error[0]) push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_COLLATION, "%s", loader.error); } return cs; } static inline bool is_supported_parser_charset(CHARSET_INFO *cs) { return MY_TEST(cs->mbminlen == 1 && cs->number != 17 /* filename */); } /** THD registry */ class THD_list_iterator { protected: I_List threads; mutable mysql_rwlock_t lock; public: /** Iterates registered threads. @param action called for every element @param argument opque argument passed to action @return @retval 0 iteration completed successfully @retval 1 iteration was interrupted (action returned 1) */ template int iterate(my_bool (*action)(THD *thd, T *arg), T *arg= 0) { int res= 0; mysql_rwlock_rdlock(&lock); I_List_iterator it(threads); while (auto tmp= it++) if ((res= action(tmp, arg))) break; mysql_rwlock_unlock(&lock); return res; } static THD_list_iterator *iterator(); }; /** A counter of THDs It must be specified as a first base class of THD, so that increment is done before any other THD constructors and decrement - after any other THD destructors. Destructor unblocks close_conneciton() if there are no more THD's left. */ struct THD_count { static Atomic_counter count; static uint value() { return static_cast(count); } static uint connection_thd_count(); THD_count() { count++; } ~THD_count() { count--; } }; #ifdef MYSQL_SERVER void free_tmp_table(THD *thd, TABLE *entry); /* The following macro is to make init of Query_arena simpler */ #ifdef DBUG_ASSERT_EXISTS #define INIT_ARENA_DBUG_INFO is_backup_arena= 0; is_reprepared= FALSE; #else #define INIT_ARENA_DBUG_INFO #endif class Query_arena { public: /* List of items created in the parser for this query. Every item puts itself to the list on creation (see Item::Item() for details)) */ Item *free_list; MEM_ROOT *mem_root; // Pointer to current memroot #ifdef DBUG_ASSERT_EXISTS bool is_backup_arena; /* True if this arena is used for backup. */ bool is_reprepared; #endif /* The states relfects three diffrent life cycles for three different types of statements: Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED. Stored procedure: STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED. Other statements: STMT_CONVENTIONAL_EXECUTION never changes. Special case for stored procedure arguments: STMT_SP_QUERY_ARGUMENTS This state never changes and used for objects whose lifetime is whole duration of function call (sp_rcontext, it's tables and items. etc). Such objects should be deallocated after every execution of a stored routine. Caller's arena/memroot can't be used for placing such objects since memory allocated on caller's arena not freed until termination of user's session. */ enum enum_state { STMT_INITIALIZED= 0, STMT_INITIALIZED_FOR_SP= 1, STMT_PREPARED= 2, STMT_CONVENTIONAL_EXECUTION= 3, STMT_EXECUTED= 4, STMT_SP_QUERY_ARGUMENTS= 5, STMT_ERROR= -1 }; enum_state state; public: /* We build without RTTI, so dynamic_cast can't be used. */ enum Type { STATEMENT, PREPARED_STATEMENT, STORED_PROCEDURE }; Query_arena(MEM_ROOT *mem_root_arg, enum enum_state state_arg) : free_list(0), mem_root(mem_root_arg), state(state_arg) { INIT_ARENA_DBUG_INFO; } /* This constructor is used only when Query_arena is created as backup storage for another instance of Query_arena. */ Query_arena() { INIT_ARENA_DBUG_INFO; } virtual Type type() const; virtual ~Query_arena() = default; inline bool is_stmt_prepare() const { return state == STMT_INITIALIZED; } inline bool is_stmt_prepare_or_first_sp_execute() const { return (int)state < (int)STMT_PREPARED; } inline bool is_stmt_prepare_or_first_stmt_execute() const { return (int)state <= (int)STMT_PREPARED; } inline bool is_stmt_execute() const { return state == STMT_PREPARED || state == STMT_EXECUTED; } inline bool is_conventional() const { return state == STMT_CONVENTIONAL_EXECUTION; } inline void* alloc(size_t size) { return alloc_root(mem_root,size); } inline void* calloc(size_t size) { void *ptr; if (likely((ptr=alloc_root(mem_root,size)))) bzero(ptr, size); return ptr; } inline char *strdup(const char *str) { return strdup_root(mem_root,str); } inline char *strmake(const char *str, size_t size) { return strmake_root(mem_root,str,size); } inline void *memdup(const void *str, size_t size) { return memdup_root(mem_root,str,size); } inline void *memdup_w_gap(const void *str, size_t size, size_t gap) { void *ptr; if (likely((ptr= alloc_root(mem_root,size+gap)))) memcpy(ptr,str,size); return ptr; } void set_query_arena(Query_arena *set); void free_items(); /* Close the active state associated with execution of this statement */ virtual bool cleanup_stmt(bool /*restore_set_statement_vars*/); }; class Query_arena_memroot: public Query_arena, public Sql_alloc { public: Query_arena_memroot(MEM_ROOT *mem_root_arg, enum enum_state state_arg) : Query_arena(mem_root_arg, state_arg) {} Query_arena_memroot() : Query_arena() {} virtual ~Query_arena_memroot() = default; }; class Query_arena_stmt { THD *thd; Query_arena backup; Query_arena *arena; public: Query_arena_stmt(THD *_thd); ~Query_arena_stmt(); bool arena_replaced() { return arena != NULL; } }; class Server_side_cursor; /* Struct to catch changes in column metadata that is sent to client. in the "result set metadata". Used to support MARIADB_CLIENT_CACHE_METADATA. */ struct send_column_info_state { /* Last client charset (affects metadata) */ CHARSET_INFO *last_charset= nullptr; /* Checksum, only used to check changes if 'immutable' is false*/ uint32 checksum= 0; /* Column info can only be changed by PreparedStatement::reprepare() There is a class of "weird" prepared statements like SELECT ? or SELECT @a that are not immutable, and depend on input parameters or user variables */ bool immutable= false; bool initialized= false; /* Used by PreparedStatement::reprepare()*/ void reset() { initialized= false; checksum= 0; } }; /** @class Statement @brief State of a single command executed against this connection. One connection can contain a lot of simultaneously running statements, some of which could be: - prepared, that is, contain placeholders, - opened as cursors. We maintain 1 to 1 relationship between statement and cursor - if user wants to create another cursor for his query, we create another statement for it. To perform some action with statement we reset THD part to the state of that statement, do the action, and then save back modified state from THD to the statement. It will be changed in near future, and Statement will be used explicitly. */ class Statement: public ilink, public Query_arena { Statement(const Statement &rhs); /* not implemented: */ Statement &operator=(const Statement &rhs); /* non-copyable */ public: /* Uniquely identifies each statement object in thread scope; change during statement lifetime. FIXME: must be const */ ulong id; enum enum_column_usage column_usage; LEX_CSTRING name; /* name for named prepared statements */ LEX *lex; // parse tree descriptor my_hrtime_t hr_prepare_time; // time of preparation in microseconds /* Points to the query associated with this statement. It's const, but we need to declare it char * because all table handlers are written in C and need to point to it. Note that if we set query = NULL, we must at the same time set query_length = 0, and protect the whole operation with LOCK_thd_data mutex. To avoid crashes in races, if we do not know that thd->query cannot change at the moment, we should print thd->query like this: (1) reserve the LOCK_thd_data mutex; (2) print or copy the value of query and query_length (3) release LOCK_thd_data mutex. This printing is needed at least in SHOW PROCESSLIST and SHOW ENGINE INNODB STATUS. */ CSET_STRING query_string; /* If opt_query_cache_strip_comments is set, this contains query without comments. If not set, it contains pointer to query_string. */ String base_query; inline char *query() const { return query_string.str(); } inline uint32 query_length() const { return static_cast(query_string.length()); } inline char *query_end() const { return query_string.str() + query_string.length(); } CHARSET_INFO *query_charset() const { return query_string.charset(); } void set_query_inner(const CSET_STRING &string_arg) { query_string= string_arg; } void set_query_inner(char *query_arg, uint32 query_length_arg, CHARSET_INFO *cs_arg) { set_query_inner(CSET_STRING(query_arg, query_length_arg, cs_arg)); } void reset_query_inner() { set_query_inner(CSET_STRING()); } /** Name of the current (default) database. If there is the current (default) database, "db.str" contains its name. If there is no current (default) database, "db.str" is NULL and "db.length" is 0. In other words, db must either be NULL, or contain a valid database name. */ LEX_CSTRING db; send_column_info_state column_info_state; /* This is set to 1 of last call to send_result_to_client() was ok */ my_bool query_cache_is_applicable; /* This constructor is called for backup statements */ Statement() = default; Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg, enum enum_state state_arg, ulong id_arg); virtual ~Statement(); /* Assign execution context (note: not all members) of given stmt to self */ virtual void set_statement(Statement *stmt); void set_n_backup_statement(Statement *stmt, Statement *backup); void restore_backup_statement(Statement *stmt, Statement *backup); /* return class type */ Type type() const override; }; /** Container for all statements created/used in a connection. Statements in Statement_map have unique Statement::id (guaranteed by id assignment in Statement::Statement) Non-empty statement names are unique too: attempt to insert a new statement with duplicate name causes older statement to be deleted Statements are auto-deleted when they are removed from the map and when the map is deleted. */ class Statement_map { public: Statement_map(); int insert(THD *thd, Statement *statement); Statement *find_by_name(const LEX_CSTRING *name) { Statement *stmt; stmt= (Statement*)my_hash_search(&names_hash, (uchar*)name->str, name->length); return stmt; } Statement *find(ulong id) { if (last_found_statement == 0 || id != last_found_statement->id) { Statement *stmt; stmt= (Statement *) my_hash_search(&st_hash, (uchar *) &id, sizeof(id)); if (stmt && stmt->name.str) return NULL; last_found_statement= stmt; } return last_found_statement; } /* Close all cursors of this connection that use tables of a storage engine that has transaction-specific state and therefore can not survive COMMIT or ROLLBACK. Currently all but MyISAM cursors are closed. */ void close_transient_cursors(); void erase(Statement *statement); /* Erase all statements (calls Statement destructor) */ void reset(); ~Statement_map(); private: HASH st_hash; HASH names_hash; I_List transient_cursor_list; Statement *last_found_statement; }; struct st_savepoint { struct st_savepoint *prev; char *name; uint length; Ha_trx_info *ha_list; /** State of metadata locks before this savepoint was set. */ MDL_savepoint mdl_savepoint; }; /** @class Security_context @brief A set of THD members describing the current authenticated user. */ class Security_context { public: Security_context() :master_access(NO_ACL), db_access(NO_ACL) {} /* Remove gcc warning */ /* host - host of the client user - user of the client, set to NULL until the user has been read from the connection priv_user - The user privilege we are using. May be "" for anonymous user. ip - client IP */ const char *host; const char *user, *ip; char priv_user[USERNAME_LENGTH]; char proxy_user[USERNAME_LENGTH + MAX_HOSTNAME + 5]; /* The host privilege we are using */ char priv_host[MAX_HOSTNAME]; /* The role privilege we are using */ char priv_role[USERNAME_LENGTH]; /* The external user (if available) */ char *external_user; /* points to host if host is available, otherwise points to ip */ const char *host_or_ip; privilege_t master_access; /* Global privileges from mysql.user */ privilege_t db_access; /* Privileges for current db */ bool password_expired; void init(); void destroy(); void skip_grants(); inline char *priv_host_name() { return (*priv_host ? priv_host : (char *)"%"); } bool set_user(char *user_arg); #ifndef NO_EMBEDDED_ACCESS_CHECKS bool change_security_context(THD *thd, LEX_CSTRING *definer_user, LEX_CSTRING *definer_host, LEX_CSTRING *db, Security_context **backup); void restore_security_context(THD *thd, Security_context *backup); #endif bool user_matches(Security_context *); /** Check global access @param want_access The required privileges @param match_any if the security context must match all or any of the req. * privileges. @return True if the security context fulfills the access requirements. */ bool check_access(const privilege_t want_access, bool match_any = false); bool is_priv_user(const char *user, const char *host); bool is_user_defined() const { return user && user != delayed_user && user != slave_user; }; }; /** A registry for item tree transformations performed during query optimization. We register only those changes which require a rollback to re-execute a prepared statement or stored procedure yet another time. */ struct Item_change_record; class Item_change_list { I_List change_list; public: void nocheck_register_item_tree_change(Item **place, Item *old_value, MEM_ROOT *runtime_memroot); void check_and_register_item_tree_change(Item **place, Item **new_value, MEM_ROOT *runtime_memroot); void rollback_item_tree_changes(); void move_elements_to(Item_change_list *to) { change_list.move_elements_to(&to->change_list); } bool is_empty() { return change_list.is_empty(); } }; class Item_change_list_savepoint: public Item_change_list { public: Item_change_list_savepoint(Item_change_list *list) { list->move_elements_to(this); } void rollback(Item_change_list *list) { list->rollback_item_tree_changes(); move_elements_to(list); } ~Item_change_list_savepoint() { DBUG_ASSERT(is_empty()); } }; /** Type of locked tables mode. See comment for THD::locked_tables_mode for complete description. */ enum enum_locked_tables_mode { LTM_NONE= 0, LTM_LOCK_TABLES, LTM_PRELOCKED, LTM_PRELOCKED_UNDER_LOCK_TABLES, LTM_always_last }; /** The following structure is an extension to TABLE_SHARE and is exclusively for temporary tables. @note: Although, TDC_element has data members (like next, prev & all_tables) to store the list of TABLE_SHARE & TABLE objects related to a particular TABLE_SHARE, they cannot be moved to TABLE_SHARE in order to be reused for temporary tables. This is because, as concurrent threads iterating through hash of TDC_element's may need access to all_tables, but if all_tables is made part of TABLE_SHARE, then TDC_element->share->all_tables is not always guaranteed to be valid, as TDC_element can live longer than TABLE_SHARE. */ struct TMP_TABLE_SHARE : public TABLE_SHARE { private: /* Link to all temporary table shares. Declared as private to avoid direct manipulation with those objects. One should use methods of I_P_List template instead. */ TMP_TABLE_SHARE *tmp_next; TMP_TABLE_SHARE **tmp_prev; friend struct All_tmp_table_shares; public: /* Doubly-linked (back-linked) lists of used and unused TABLE objects for this share. */ All_share_tables_list all_tmp_tables; }; /** Helper class which specifies which members of TMP_TABLE_SHARE are used for participation in the list of temporary tables. */ struct All_tmp_table_shares { static inline TMP_TABLE_SHARE **next_ptr(TMP_TABLE_SHARE *l) { return &l->tmp_next; } static inline TMP_TABLE_SHARE ***prev_ptr(TMP_TABLE_SHARE *l) { return &l->tmp_prev; } }; /* Also used in rpl_rli.h. */ typedef I_P_List All_tmp_tables_list; /** Class that holds information about tables which were opened and locked by the thread. It is also used to save/restore this information in push_open_tables_state()/pop_open_tables_state(). */ class Open_tables_state { public: /** As part of class THD, this member is set during execution of a prepared statement. When it is set, it is used by the locking subsystem to report a change in table metadata. When Open_tables_state part of THD is reset to open a system or INFORMATION_SCHEMA table, the member is cleared to avoid spurious ER_NEED_REPREPARE errors -- system and INFORMATION_SCHEMA tables are not subject to metadata version tracking. @sa check_and_update_table_version() */ Reprepare_observer *m_reprepare_observer; /** List of regular tables in use by this thread. Contains temporary and base tables that were opened with @see open_tables(). */ TABLE *open_tables; /** A list of temporary tables used by this thread. This includes user-level temporary tables, created with CREATE TEMPORARY TABLE, and internal temporary tables, created, e.g., to resolve a SELECT, or for an intermediate table used in ALTER. */ All_tmp_tables_list *temporary_tables; /* Derived tables. */ TABLE *derived_tables; /* Temporary tables created for recursive table references. */ TABLE *rec_tables; /* During a MySQL session, one can lock tables in two modes: automatic or manual. In automatic mode all necessary tables are locked just before statement execution, and all acquired locks are stored in 'lock' member. Unlocking takes place automatically as well, when the statement ends. Manual mode comes into play when a user issues a 'LOCK TABLES' statement. In this mode the user can only use the locked tables. Trying to use any other tables will give an error. The locked tables are also stored in this member, however, thd->locked_tables_mode is turned on. Manual locking is described in the 'LOCK_TABLES' chapter of the MySQL manual. See also lock_tables() for details. */ MYSQL_LOCK *lock; /* CREATE-SELECT keeps an extra lock for the table being created. This field is used to keep the extra lock available for lower level routines, which would otherwise miss that lock. */ MYSQL_LOCK *extra_lock; /* Enum enum_locked_tables_mode and locked_tables_mode member are used to indicate whether the so-called "locked tables mode" is on, and what kind of mode is active. Locked tables mode is used when it's necessary to open and lock many tables at once, for usage across multiple (sub-)statements. This may be necessary either for queries that use stored functions and triggers, in which case the statements inside functions and triggers may be executed many times, or for implementation of LOCK TABLES, in which case the opened tables are reused by all subsequent statements until a call to UNLOCK TABLES. The kind of locked tables mode employed for stored functions and triggers is also called "prelocked mode". In this mode, first open_tables() call to open the tables used in a statement analyses all functions used by the statement and adds all indirectly used tables to the list of tables to open and lock. It also marks the parse tree of the statement as requiring prelocking. After that, lock_tables() locks the entire list of tables and changes THD::locked_tables_modeto LTM_PRELOCKED. All statements executed inside functions or triggers use the prelocked tables, instead of opening their own ones. Prelocked mode is turned off automatically once close_thread_tables() of the main statement is called. */ enum enum_locked_tables_mode locked_tables_mode; uint current_tablenr; enum enum_flags { BACKUPS_AVAIL = (1U << 0) /* There are backups available */ }; /* Flags with information about the open tables state. */ uint state_flags; /** This constructor initializes Open_tables_state instance which can only be used as backup storage. To prepare Open_tables_state instance for operations which open/lock/close tables (e.g. open_table()) one has to call init_open_tables_state(). */ Open_tables_state() : state_flags(0U) { } void set_open_tables_state(Open_tables_state *state) { *this= *state; } void reset_open_tables_state(THD *thd) { open_tables= 0; temporary_tables= 0; derived_tables= 0; rec_tables= 0; extra_lock= 0; lock= 0; locked_tables_mode= LTM_NONE; state_flags= 0U; m_reprepare_observer= NULL; } }; /** Storage for backup of Open_tables_state. Must be used only to open system tables (TABLE_CATEGORY_SYSTEM and TABLE_CATEGORY_LOG). */ class Open_tables_backup: public Open_tables_state { public: /** When we backup the open tables state to open a system table or tables, we want to save state of metadata locks which were acquired before the backup. It is used to release metadata locks on system tables after they are no longer used. */ MDL_savepoint mdl_system_tables_svp; }; /** @class Sub_statement_state @brief Used to save context when executing a function or trigger operations on stat tables aren't technically a sub-statement, but they are similar in a sense that they cannot change the transaction status. */ /* Defines used for Sub_statement_state::in_sub_stmt */ #define SUB_STMT_TRIGGER 1 #define SUB_STMT_FUNCTION 2 #define SUB_STMT_STAT_TABLES 4 class Sub_statement_state { public: Discrete_interval auto_inc_interval_for_cur_row; Discrete_intervals_list auto_inc_intervals_forced; SAVEPOINT *savepoints; ulonglong option_bits; ulonglong first_successful_insert_id_in_prev_stmt; ulonglong first_successful_insert_id_in_cur_stmt, insert_id_for_cur_row; ulonglong limit_found_rows; ulonglong tmp_tables_size; ulonglong client_capabilities; ulonglong cuted_fields, sent_row_count, examined_row_count; ulonglong affected_rows; ulonglong bytes_sent_old; ha_handler_stats handler_stats; ulong tmp_tables_used; ulong tmp_tables_disk_used; ulong query_plan_fsort_passes; ulong query_plan_flags; uint in_sub_stmt; /* 0, SUB_STMT_TRIGGER or SUB_STMT_FUNCTION */ bool enable_slow_log; bool last_insert_id_used; enum enum_check_fields count_cuted_fields; }; /* Flags for the THD::system_thread variable */ enum enum_thread_type { NON_SYSTEM_THREAD= 0, SYSTEM_THREAD_DELAYED_INSERT= 1, SYSTEM_THREAD_SLAVE_IO= 2, SYSTEM_THREAD_SLAVE_SQL= 4, SYSTEM_THREAD_EVENT_SCHEDULER= 8, SYSTEM_THREAD_EVENT_WORKER= 16, SYSTEM_THREAD_BINLOG_BACKGROUND= 32, SYSTEM_THREAD_SLAVE_BACKGROUND= 64, SYSTEM_THREAD_GENERIC= 128, SYSTEM_THREAD_SEMISYNC_MASTER_BACKGROUND= 256 }; inline char const * show_system_thread(enum_thread_type thread) { #define RETURN_NAME_AS_STRING(NAME) case (NAME): return #NAME switch (thread) { static char buf[64]; RETURN_NAME_AS_STRING(NON_SYSTEM_THREAD); RETURN_NAME_AS_STRING(SYSTEM_THREAD_DELAYED_INSERT); RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_IO); RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_SQL); RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_SCHEDULER); RETURN_NAME_AS_STRING(SYSTEM_THREAD_EVENT_WORKER); RETURN_NAME_AS_STRING(SYSTEM_THREAD_SLAVE_BACKGROUND); RETURN_NAME_AS_STRING(SYSTEM_THREAD_SEMISYNC_MASTER_BACKGROUND); default: snprintf(buf, sizeof(buf), "", thread); return buf; } #undef RETURN_NAME_AS_STRING } /** This class represents the interface for internal error handlers. Internal error handlers are exception handlers used by the server implementation. */ class Internal_error_handler { protected: Internal_error_handler() : m_prev_internal_handler(NULL) {} virtual ~Internal_error_handler() = default; public: /** Handle a sql condition. This method can be implemented by a subclass to achieve any of the following: - mask a warning/error internally, prevent exposing it to the user, - mask a warning/error and throw another one instead. When this method returns true, the sql condition is considered 'handled', and will not be propagated to upper layers. It is the responsability of the code installing an internal handler to then check for trapped conditions, and implement logic to recover from the anticipated conditions trapped during runtime. This mechanism is similar to C++ try/throw/catch: - 'try' correspond to THD::push_internal_handler(), - 'throw' correspond to my_error(), which invokes my_message_sql(), - 'catch' correspond to checking how/if an internal handler was invoked, before removing it from the exception stack with THD::pop_internal_handler(). @param thd the calling thread @param cond the condition raised. @return true if the condition is handled */ virtual bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition ** cond_hdl) = 0; private: Internal_error_handler *m_prev_internal_handler; friend class THD; }; /** Implements the trivial error handler which cancels all error states and prevents an SQLSTATE to be set. Remembers the first error */ class Dummy_error_handler : public Internal_error_handler { uint m_unhandled_errors; uint first_error; public: Dummy_error_handler() : m_unhandled_errors(0), first_error(0) {} bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition ** cond_hdl) override { m_unhandled_errors++; if (!first_error) first_error= sql_errno; return TRUE; // Ignore error } bool any_error() { return m_unhandled_errors != 0; } uint got_error() { return first_error; } }; /** Implements the trivial error handler which counts errors as they happen. */ class Counting_error_handler : public Internal_error_handler { public: int errors; bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition ** cond_hdl) override { if (*level == Sql_condition::WARN_LEVEL_ERROR) errors++; return false; } Counting_error_handler() : errors(0) {} }; /** This class is an internal error handler implementation for DROP TABLE statements. The thing is that there may be warnings during execution of these statements, which should not be exposed to the user. This class is intended to silence such warnings. */ class Drop_table_error_handler : public Internal_error_handler { public: Drop_table_error_handler() = default; public: bool handle_condition(THD *thd, uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition ** cond_hdl) override; private: }; /** Internal error handler to process an error from MDL_context::upgrade_lock() and mysql_lock_tables(). Used by implementations of HANDLER READ and LOCK TABLES LOCAL. */ class MDL_deadlock_and_lock_abort_error_handler: public Internal_error_handler { public: virtual bool handle_condition(THD *thd, uint sql_errno, const char *sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition **cond_hdl) override; bool need_reopen() const { return m_need_reopen; }; void init() { m_need_reopen= FALSE; }; private: bool m_need_reopen; }; class Turn_errors_to_warnings_handler : public Internal_error_handler { public: Turn_errors_to_warnings_handler() = default; bool handle_condition(THD *, uint, const char*, Sql_condition::enum_warning_level *level, const char*, Sql_condition ** cond_hdl) override { *cond_hdl= NULL; if (*level == Sql_condition::WARN_LEVEL_ERROR) *level= Sql_condition::WARN_LEVEL_WARN; return(0); } }; struct Suppress_warnings_error_handler : public Internal_error_handler { bool handle_condition(THD *, uint, const char *, Sql_condition::enum_warning_level *level, const char *, Sql_condition **) override { return *level == Sql_condition::WARN_LEVEL_WARN; } }; /** Tables that were locked with LOCK TABLES statement. Encapsulates a list of TABLE_LIST instances for tables locked by LOCK TABLES statement, memory root for metadata locks, and, generally, the context of LOCK TABLES statement. In LOCK TABLES mode, the locked tables are kept open between statements. Therefore, we can't allocate metadata locks on execution memory root -- as well as tables, the locks need to stay around till UNLOCK TABLES is called. The locks are allocated in the memory root encapsulated in this class. Some SQL commands, like FLUSH TABLE or ALTER TABLE, demand that the tables they operate on are closed, at least temporarily. This class encapsulates a list of TABLE_LIST instances, one for each base table from LOCK TABLES list, which helps conveniently close the TABLEs when it's necessary and later reopen them. Implemented in sql_base.cc */ class Locked_tables_list { public: MEM_ROOT m_locked_tables_root; private: TABLE_LIST *m_locked_tables; TABLE_LIST **m_locked_tables_last; /** An auxiliary array used only in reopen_tables(). */ TABLE_LIST **m_reopen_array; /** Count the number of tables in m_locked_tables list. We can't rely on thd->lock->table_count because it excludes non-transactional temporary tables. We need to know an exact number of TABLE objects. */ uint m_locked_tables_count; public: bool some_table_marked_for_reopen; Locked_tables_list() :m_locked_tables(NULL), m_locked_tables_last(&m_locked_tables), m_reopen_array(NULL), m_locked_tables_count(0), some_table_marked_for_reopen(0) { init_sql_alloc(key_memory_locked_table_list, &m_locked_tables_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); } int unlock_locked_tables(THD *thd); int unlock_locked_table(THD *thd, MDL_ticket *mdl_ticket); ~Locked_tables_list() { reset(); } void reset(); bool init_locked_tables(THD *thd); TABLE_LIST *locked_tables() { return m_locked_tables; } void unlink_from_list(THD *thd, TABLE_LIST *table_list, bool remove_from_locked_tables); void unlink_all_closed_tables(THD *thd, MYSQL_LOCK *lock, size_t reopen_count); bool reopen_tables(THD *thd, bool need_reopen); bool restore_lock(THD *thd, TABLE_LIST *dst_table_list, TABLE *table, MYSQL_LOCK *lock); void add_back_last_deleted_lock(TABLE_LIST *dst_table_list); void mark_table_for_reopen(THD *thd, TABLE *table); }; /** Storage engine specific thread local data. */ struct Ha_data { /** Storage engine specific thread local data. Lifetime: one user connection. */ void *ha_ptr; /** 0: Life time: one statement within a transaction. If @@autocommit is on, also represents the entire transaction. @sa trans_register_ha() 1: Life time: one transaction within a connection. If the storage engine does not participate in a transaction, this should not be used. @sa trans_register_ha() */ Ha_trx_info ha_info[2]; /** NULL: engine is not bound to this thread non-NULL: engine is bound to this thread, engine shutdown forbidden */ plugin_ref lock; Ha_data() :ha_ptr(NULL) {} void reset() { ha_ptr= nullptr; for (auto &info : ha_info) info.reset(); lock= nullptr; } }; /** An instance of the global read lock in a connection. Implemented in lock.cc. */ class Global_read_lock { public: enum enum_grl_state { GRL_NONE, GRL_ACQUIRED, GRL_ACQUIRED_AND_BLOCKS_COMMIT }; Global_read_lock() : m_state(GRL_NONE), m_mdl_global_read_lock(NULL) {} bool lock_global_read_lock(THD *thd); void unlock_global_read_lock(THD *thd); bool make_global_read_lock_block_commit(THD *thd); bool is_acquired() const { return m_state != GRL_NONE; } void set_explicit_lock_duration(THD *thd); private: enum_grl_state m_state; /** Global read lock is acquired in two steps: 1. acquire MDL_BACKUP_FTWRL1 in BACKUP namespace to prohibit DDL and DML 2. upgrade to MDL_BACKUP_FTWRL2 to prohibit commits */ MDL_ticket *m_mdl_global_read_lock; }; /* Class to facilitate the commit of one transactions waiting for the commit of another transaction to complete first. This is used during (parallel) replication, to allow different transactions to be applied in parallel, but still commit in order. The transaction that wants to wait for a prior commit must first register to wait with register_wait_for_prior_commit(waitee). Such registration must be done holding the waitee->LOCK_wait_commit, to prevent the other THD from disappearing during the registration. Then during commit, if a THD is registered to wait, it will call wait_for_prior_commit() as part of ha_commit_trans(). If no wait is registered, or if the waitee for has already completed commit, then wait_for_prior_commit() returns immediately. And when a THD that may be waited for has completed commit (more precisely commit_ordered()), then it must call wakeup_subsequent_commits() to wake up any waiters. Note that this must be done at a point that is guaranteed to be later than any waiters registering themselves. It is safe to call wakeup_subsequent_commits() multiple times, as waiters are removed from registration as part of the wakeup. The reason for separate register and wait calls is that this allows to register the wait early, at a point where the waited-for THD is known to exist. And then the actual wait can be done much later, where the waited-for THD may have been long gone. By registering early, the waitee can signal before disappearing. */ struct wait_for_commit { /* The LOCK_wait_commit protects the fields subsequent_commits_list and wakeup_subsequent_commits_running (for a waitee), and the pointer waitee and associated COND_wait_commit (for a waiter). */ mysql_mutex_t LOCK_wait_commit; mysql_cond_t COND_wait_commit; /* List of threads that did register_wait_for_prior_commit() on us. */ wait_for_commit *subsequent_commits_list; /* Link field for entries in subsequent_commits_list. */ wait_for_commit *next_subsequent_commit; /* Our waitee, if we did register_wait_for_prior_commit(), and were not yet woken up. Else NULL. When this is cleared for wakeup, the COND_wait_commit condition is signalled. This pointer is protected by LOCK_wait_commit. But there is also a "fast path" where the waiter compares this to NULL without holding the lock. Such read must be done with acquire semantics (and all corresponding writes done with release semantics). This ensures that a wakeup with error is reliably detected as (waitee==NULL && wakeup_error != 0). */ std::atomic waitee; /* Generic pointer for use by the transaction coordinator to optimise the waiting for improved group commit. Currently used by binlog TC to signal that a waiter is ready to commit, so that the waitee can grab it and group commit it directly. It is free to be used by another transaction coordinator for similar purposes. */ void *opaque_pointer; /* The wakeup error code from the waitee. 0 means no error. */ int wakeup_error; /* Flag set when wakeup_subsequent_commits_running() is active, see comments on that function for details. */ bool wakeup_subsequent_commits_running; /* This flag can be set when a commit starts, but has not completed yet. It is used by binlog group commit to allow a waiting transaction T2 to join the group commit of an earlier transaction T1. When T1 has queued itself for group commit, it will set the commit_started flag. Then when T2 becomes ready to commit and needs to wait for T1 to commit first, T2 can queue itself before waiting, and thereby participate in the same group commit as T1. */ bool commit_started; /* Set to temporarily ignore calls to wakeup_subsequent_commits(). The caller must arrange that another wakeup_subsequent_commits() gets called later after wakeup_blocked has been set back to false. This is used for parallel replication with temporary tables. Temporary tables require strict single-threaded operation. The normal optimization, of doing wakeup_subsequent_commits early and overlapping part of the commit with the following transaction, is not safe. Thus when temporary tables are replicated, wakeup is blocked until the event group is fully done. */ bool wakeup_blocked; void register_wait_for_prior_commit(wait_for_commit *waitee); int wait_for_prior_commit(THD *thd, bool allow_kill=true) { /* Quick inline check, to avoid function call and locking in the common case where no wakeup is registered, or a registered wait was already signalled. */ if (waitee.load(std::memory_order_acquire)) return wait_for_prior_commit2(thd, allow_kill); else { if (unlikely(wakeup_error)) prior_commit_error(thd); return wakeup_error; } } void wakeup_subsequent_commits(int wakeup_error_arg) { /* Do the check inline, so only the wakeup case takes the cost of a function call for every commmit. Note that the check is done without locking. It is the responsibility of the user of the wakeup facility to ensure that no waiters can register themselves after the last call to wakeup_subsequent_commits(). This avoids having to take another lock for every commit, which would be pointless anyway - even if we check under lock, there is nothing to prevent a waiter from arriving just after releasing the lock. */ if (subsequent_commits_list) wakeup_subsequent_commits2(wakeup_error_arg); } void unregister_wait_for_prior_commit() { if (waitee.load(std::memory_order_relaxed)) unregister_wait_for_prior_commit2(); else wakeup_error= 0; } /* Remove a waiter from the list in the waitee. Used to unregister a wait. The caller must be holding the locks of both waiter and waitee. */ void remove_from_list(wait_for_commit **next_ptr_ptr) { wait_for_commit *cur; while ((cur= *next_ptr_ptr) != NULL) { if (cur == this) { *next_ptr_ptr= this->next_subsequent_commit; break; } next_ptr_ptr= &cur->next_subsequent_commit; } waitee.store(NULL, std::memory_order_relaxed); } void wakeup(int wakeup_error); int wait_for_prior_commit2(THD *thd, bool allow_kill); void prior_commit_error(THD *thd); void wakeup_subsequent_commits2(int wakeup_error); void unregister_wait_for_prior_commit2(); wait_for_commit(); ~wait_for_commit(); void reinit(); }; class Sp_caches { public: sp_cache *sp_proc_cache; sp_cache *sp_func_cache; sp_cache *sp_package_spec_cache; sp_cache *sp_package_body_cache; Sp_caches() :sp_proc_cache(NULL), sp_func_cache(NULL), sp_package_spec_cache(NULL), sp_package_body_cache(NULL) { } ~Sp_caches() { // All caches must be freed by the caller explicitly DBUG_ASSERT(sp_proc_cache == NULL); DBUG_ASSERT(sp_func_cache == NULL); DBUG_ASSERT(sp_package_spec_cache == NULL); DBUG_ASSERT(sp_package_body_cache == NULL); } void sp_caches_swap(Sp_caches &rhs) { swap_variables(sp_cache*, sp_proc_cache, rhs.sp_proc_cache); swap_variables(sp_cache*, sp_func_cache, rhs.sp_func_cache); swap_variables(sp_cache*, sp_package_spec_cache, rhs.sp_package_spec_cache); swap_variables(sp_cache*, sp_package_body_cache, rhs.sp_package_body_cache); } void sp_caches_clear(); /** Clear content of sp related caches. Don't delete cache objects itself. */ void sp_caches_empty(); }; extern "C" void my_message_sql(uint error, const char *str, myf MyFlags); class Gap_time_tracker; /* Thread context for Gap_time_tracker class. */ class Gap_time_tracker_data { public: Gap_time_tracker_data(): bill_to(NULL) {} Gap_time_tracker *bill_to; ulonglong start_time; void init() { bill_to = NULL; } }; /** Support structure for asynchronous group commit, or more generally any asynchronous operation that needs to finish before server writes response to client. An engine, or any other server component, can signal that there is a pending operation by incrementing a counter, i.e inc_pending_ops() and that pending operation is finished by decrementing that counter dec_pending_ops(). NOTE: Currently, pending operations can not fail, i.e there is no way to pass a return code in dec_pending_ops() The server does not write response to the client before the counter becomes 0. In case of group commit it ensures that data is persistent before success reported to client, i.e durability in ACID. */ struct thd_async_state { enum class enum_async_state { NONE, SUSPENDED, /* do_command() did not finish, and needs to be resumed */ RESUMED /* do_command() is resumed*/ }; enum_async_state m_state{enum_async_state::NONE}; /* Stuff we need to resume do_command where we finished last time*/ enum enum_server_command m_command{COM_SLEEP}; LEX_STRING m_packet{0,0}; mysql_mutex_t m_mtx; mysql_cond_t m_cond; /** Pending counter*/ Atomic_counter m_pending_ops=0; #ifndef DBUG_OFF /* Checks */ pthread_t m_dbg_thread; #endif thd_async_state() { mysql_mutex_init(PSI_NOT_INSTRUMENTED, &m_mtx, 0); mysql_cond_init(PSI_INSTRUMENT_ME, &m_cond, 0); } /* Currently only used with threadpool, one can "suspend" and "resume" a THD. Suspend only means leaving do_command earlier, after saving some state. Resume is continuing suspended THD's do_command(), from where it finished last time. */ bool try_suspend() { bool ret; mysql_mutex_lock(&m_mtx); DBUG_ASSERT(m_state == enum_async_state::NONE); DBUG_ASSERT(m_pending_ops >= 0); if(m_pending_ops) { ret=true; m_state= enum_async_state::SUSPENDED; } else { /* If there is no pending operations, can't suspend, since nobody can resume it. */ ret=false; } mysql_mutex_unlock(&m_mtx); return ret; } ~thd_async_state() { wait_for_pending_ops(); mysql_mutex_destroy(&m_mtx); mysql_cond_destroy(&m_cond); } /* Increment pending asynchronous operations. The client response may not be written if this count > 0. So, without threadpool query needs to wait for the operations to finish. With threadpool, THD can be suspended and resumed when this counter goes to 0. */ void inc_pending_ops() { mysql_mutex_lock(&m_mtx); #ifndef DBUG_OFF /* Check that increments are always done by the same thread. */ if (!m_pending_ops) m_dbg_thread= pthread_self(); else DBUG_ASSERT(pthread_equal(pthread_self(),m_dbg_thread)); #endif m_pending_ops++; mysql_mutex_unlock(&m_mtx); } int dec_pending_ops(enum_async_state* state) { int ret; mysql_mutex_lock(&m_mtx); ret= --m_pending_ops; if (!ret) mysql_cond_signal(&m_cond); *state = m_state; mysql_mutex_unlock(&m_mtx); return ret; } /* This is used for "dirty" reading pending ops, when dirty read is OK. */ int pending_ops() { return m_pending_ops; } /* Wait for pending operations to finish.*/ void wait_for_pending_ops() { /* It is fine to read m_pending_ops and compare it with 0, without mutex protection. The value is only incremented by the current thread, and will be decremented by another one, thus "dirty" may show positive number when it is really 0, but this is not a problem, and the only bad thing from that will be rechecking under mutex. */ if (!pending_ops()) return; mysql_mutex_lock(&m_mtx); DBUG_ASSERT(m_pending_ops >= 0); while (m_pending_ops) mysql_cond_wait(&m_cond, &m_mtx); mysql_mutex_unlock(&m_mtx); } }; enum class THD_WHERE { NOWHERE = 0, CHECKING_TRANSFORMED_SUBQUERY, IN_ALL_ANY_SUBQUERY, JSON_TABLE_ARGUMENT, FIELD_LIST, PARTITION_FUNCTION, FROM_CLAUSE, DEFAULT_WHERE, ON_CLAUSE, WHERE_CLAUSE, SET_LIST, INSERT_LIST, VALUES_CLAUSE, UPDATE_CLAUSE, RETURNING, FOR_SYSTEM_TIME, ORDER_CLAUSE, HAVING_CLAUSE, GROUP_STATEMENT, PROCEDURE_LIST, CHECK_OPTION, DO_STATEMENT, HANDLER_STATEMENT, USE_WHERE_STRING, // ugh, a compromise for vcol... }; class THD; const char *thd_where(THD *thd); /** @class THD For each client connection we create a separate thread with THD serving as a thread/connection descriptor */ class THD: public THD_count, /* this must be first */ public Statement, /* This is to track items changed during execution of a prepared statement/stored procedure. It's created by nocheck_register_item_tree_change() in memory root of THD, and freed in rollback_item_tree_changes(). For conventional execution it's always empty. */ public Item_change_list, public MDL_context_owner, public Open_tables_state, public Sp_caches { private: inline bool is_stmt_prepare() const { DBUG_ASSERT(0); return Statement::is_stmt_prepare(); } inline bool is_stmt_prepare_or_first_sp_execute() const { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_sp_execute(); } inline bool is_stmt_prepare_or_first_stmt_execute() const { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_stmt_execute(); } inline bool is_conventional() const { DBUG_ASSERT(0); return Statement::is_conventional(); } public: MDL_context mdl_context; /* Used to execute base64 coded binlog events in MySQL server */ Relay_log_info* rli_fake; rpl_group_info* rgi_fake; /* Slave applier execution context */ rpl_group_info* rgi_slave; union { rpl_io_thread_info *rpl_io_info; rpl_sql_thread_info *rpl_sql_info; } system_thread_info; /* Used for BACKUP LOCK */ MDL_ticket *mdl_backup_ticket, *mdl_backup_lock; /* Used to register that thread has a MDL_BACKUP_WAIT_COMMIT lock */ MDL_request *backup_commit_lock; void reset_for_next_command(bool do_clear_errors= 1); #ifdef EMBEDDED_LIBRARY struct st_mysql *mysql; unsigned long client_stmt_id; unsigned long client_param_count; struct st_mysql_bind *client_params; char *extra_data; ulong extra_length; struct st_mysql_data *cur_data; struct st_mysql_data *first_data; struct st_mysql_data **data_tail; void clear_data_list(); struct st_mysql_data *alloc_new_dataset(); /* In embedded server it points to the statement that is processed in the current query. We store some results directly in statement fields then. */ struct st_mysql_stmt *current_stmt; #endif #ifdef HAVE_QUERY_CACHE Query_cache_tls query_cache_tls; #endif NET net; // client connection descriptor /** Aditional network instrumentation for the server only. */ NET_SERVER m_net_server_extension; scheduler_functions *scheduler; // Scheduler for this connection Protocol *protocol; // Current protocol Protocol_text protocol_text; // Normal protocol Protocol_binary protocol_binary; // Binary protocol HASH user_vars; // hash for user variables String packet; // dynamic buffer for network I/O String convert_buffer; // buffer for charset conversions struct my_rnd_struct rand; // used for authentication struct system_variables variables; // Changeable local variables struct system_status_var status_var; // Per thread statistic vars struct system_status_var org_status_var; // For user statistics struct system_status_var *initial_status_var; /* used by show status */ ha_handler_stats handler_stats; // Handler statistics THR_LOCK_INFO lock_info; // Locking info of this thread /** Protects THD data accessed from other threads: - thd->query and thd->query_length (used by SHOW ENGINE INNODB STATUS and SHOW PROCESSLIST - thd->db (used in SHOW PROCESSLIST) Is locked when THD is deleted. */ mutable mysql_mutex_t LOCK_thd_data; /* Protects: - kill information - mysys_var (used by KILL statement and shutdown). - Also ensures that THD is not deleted while mutex is hold */ mutable mysql_mutex_t LOCK_thd_kill; /* all prepared statements and cursors of this connection */ Statement_map stmt_map; /* Last created prepared statement */ Statement *last_stmt; Statement *cur_stmt= 0; inline void set_last_stmt(Statement *stmt) { last_stmt= (is_error() ? NULL : stmt); } inline void clear_last_stmt() { last_stmt= NULL; } /* A pointer to the stack frame of handle_one_connection(), which is called first in the thread for handling a client */ void *thread_stack; /** Currently selected catalog. */ char *catalog; /** @note Some members of THD (currently 'Statement::db', 'catalog' and 'query') are set and alloced by the slave SQL thread (for the THD of that thread); that thread is (and must remain, for now) the only responsible for freeing these 3 members. If you add members here, and you add code to set them in replication, don't forget to free_them_and_set_them_to_0 in replication properly. For details see the 'err:' label of the handle_slave_sql() in sql/slave.cc. @see handle_slave_sql */ Security_context main_security_ctx; Security_context *security_ctx; Security_context *security_context() const { return security_ctx; } void set_security_context(Security_context *sctx) { security_ctx = sctx; } /* Points to info-string that we show in SHOW PROCESSLIST You are supposed to update thd->proc_info only if you have coded a time-consuming piece that MySQL can get stuck in for a long time. Set it using the thd_proc_info(THD *thread, const char *message) macro/function. This member is accessed and assigned without any synchronization. Therefore, it may point only to constant (statically allocated) strings, which memory won't go away over time. */ const char *proc_info; void set_psi(PSI_thread *psi) { my_atomic_storeptr((void*volatile*)&m_psi, psi); } PSI_thread* get_psi() { return static_cast(my_atomic_loadptr((void*volatile*)&m_psi)); } private: unsigned int m_current_stage_key; /** Performance schema thread instrumentation for this session. */ PSI_thread *m_psi; public: void enter_stage(const PSI_stage_info *stage, const char *calling_func, const char *calling_file, const unsigned int calling_line) { DBUG_PRINT("THD::enter_stage", ("%s at %s:%d", stage->m_name, calling_file, calling_line)); DBUG_ASSERT(stage); m_current_stage_key= stage->m_key; proc_info= stage->m_name; #if defined(ENABLED_PROFILING) profiling.status_change(proc_info, calling_func, calling_file, calling_line); #endif #ifdef HAVE_PSI_THREAD_INTERFACE m_stage_progress_psi= MYSQL_SET_STAGE(m_current_stage_key, calling_file, calling_line); #endif } void backup_stage(PSI_stage_info *stage) { stage->m_key= m_current_stage_key; stage->m_name= proc_info; } const char *get_proc_info() const { return proc_info; } // Used by thd_where() when where==USE_WHERE_STRING const char *where_str; /* Used in error messages to tell user in what part of MySQL we found an error. E. g. when where= "having clause", if fix_fields() fails, user will know that the error was in having clause. */ THD_WHERE where; /* Needed by MariaDB semi sync replication */ Trans_binlog_info *semisync_info; #ifndef DBUG_OFF /* If Active_tranx is missing an entry for a transaction which is planning to await an ACK, this ensures that the reason is because semi-sync was turned off then on in-between the binlogging of the transaction, and before it had started waiting for the ACK. */ ulong expected_semi_sync_offs; #endif /* If this is a semisync slave connection. */ bool semi_sync_slave; ulonglong client_capabilities; /* What the client supports */ ulong max_client_packet_length; HASH handler_tables_hash; /* A thread can hold named user-level locks. This variable contains granted tickets if a lock is present. See item_func.cc and chapter 'Miscellaneous functions', for functions GET_LOCK, RELEASE_LOCK. */ HASH ull_hash; /* Hash of used seqeunces (for PREVIOUS value) */ HASH sequences; #ifdef DBUG_ASSERT_EXISTS uint dbug_sentry; // watch out for memory corruption #endif struct st_my_thread_var *mysys_var; /* Original charset number from the first client packet, or COM_CHANGE_USER*/ CHARSET_INFO *org_charset; private: /* Type of current query: COM_STMT_PREPARE, COM_QUERY, etc. Set from first byte of the packet in do_command() */ enum enum_server_command m_command; public: uint32 file_id; // for LOAD DATA INFILE /* remote (peer) port */ uint16 peer_port; my_time_t start_time; // start_time and its sec_part ulong start_time_sec_part; // are almost always used separately my_hrtime_t user_time; // track down slow pthread_create ulonglong prior_thr_create_utime, thr_create_utime; ulonglong start_utime, utime_after_lock, utime_after_query; /* This can be used by handlers to send signals to the SQL level */ ulonglong replication_flags; // Process indicator struct { /* true, if the currently running command can send progress report packets to a client. Set by mysql_execute_command() for safe commands See CF_REPORT_PROGRESS */ bool report_to_client; /* true, if we will send progress report packets to a client (client has requested them, see MARIADB_CLIENT_PROGRESS; report_to_client is true; not in sub-statement) */ bool report; uint stage, max_stage; ulonglong counter, max_counter; ulonglong next_report_time; Query_arena *arena; } progress; thr_lock_type update_lock_default; Delayed_insert *di; /* <> 0 if we are inside of trigger or stored function. */ uint in_sub_stmt; /* True when opt_userstat_running is set at start of query */ bool userstat_running; /* True if we have to log all errors. Are set by some engines to temporary force errors to the error log. */ bool log_all_errors; /* Do not set socket timeouts for wait_timeout (used with threadpool) */ bool skip_wait_timeout; bool prepare_derived_at_open; /* Set to 1 if status of this THD is already in global status */ bool status_in_global; /* To signal that the tmp table to be created is created for materialized derived table or a view. */ bool create_tmp_table_for_derived; bool save_prep_leaf_list; /** The data member reset_sp_cache is to signal that content of sp_cache must be reset (all items be removed from it). */ bool reset_sp_cache; /* container for handler's private per-connection data */ Ha_data ha_data[MAX_HA]; /** Bit field for the state of binlog warnings. The first Lex::BINLOG_STMT_UNSAFE_COUNT bits list all types of unsafeness that the current statement has. This must be a member of THD and not of LEX, because warnings are detected and issued in different places (@c decide_logging_format() and @c binlog_query(), respectively). Between these calls, the THD->lex object may change; e.g., if a stored routine is invoked. Only THD persists between the calls. */ uint32 binlog_unsafe_warning_flags; #ifndef MYSQL_CLIENT binlog_cache_mngr * binlog_setup_trx_data(); /* If set, tell binlog to store the value as query 'xid' in the next Query_log_event */ ulonglong binlog_xid; /* Public interface to write RBR events to the binlog */ void binlog_start_trans_and_stmt(); void binlog_set_stmt_begin(); int binlog_write_row(TABLE* table, bool is_transactional, const uchar *buf); int binlog_delete_row(TABLE* table, bool is_transactional, const uchar *buf); int binlog_update_row(TABLE* table, bool is_transactional, const uchar *old_data, const uchar *new_data); bool prepare_handlers_for_update(uint flag); bool binlog_write_annotated_row(Log_event_writer *writer); void binlog_prepare_for_row_logging(); bool binlog_write_table_maps(); bool binlog_write_table_map(TABLE *table, bool with_annotate); static void binlog_prepare_row_images(TABLE* table); void set_server_id(uint32 sid) { variables.server_id = sid; } /* Member functions to handle pending event for row-level logging. */ template Rows_log_event* binlog_prepare_pending_rows_event(TABLE* table, uint32 serv_id, size_t needed, bool is_transactional, RowsEventT* hint); Rows_log_event* binlog_get_pending_rows_event(bool is_transactional) const; void binlog_set_pending_rows_event(Rows_log_event* ev, bool is_transactional); inline int binlog_flush_pending_rows_event(bool stmt_end) { return (binlog_flush_pending_rows_event(stmt_end, FALSE) || binlog_flush_pending_rows_event(stmt_end, TRUE)); } int binlog_flush_pending_rows_event(bool stmt_end, bool is_transactional); int binlog_remove_pending_rows_event(bool clear_maps, bool is_transactional); /** Determine the binlog format of the current statement. @retval 0 if the current statement will be logged in statement format. @retval nonzero if the current statement will be logged in row format. */ int is_current_stmt_binlog_format_row() const { DBUG_ASSERT(current_stmt_binlog_format == BINLOG_FORMAT_STMT || current_stmt_binlog_format == BINLOG_FORMAT_ROW); return current_stmt_binlog_format == BINLOG_FORMAT_ROW; } /** Determine if binlogging is disabled for this session @retval 0 if the current statement binlogging is disabled (could be because of binlog closed/binlog option is set to false). @retval 1 if the current statement will be binlogged */ inline bool is_current_stmt_binlog_disabled() const { return (!(variables.option_bits & OPTION_BIN_LOG) || !mysql_bin_log.is_open()); } enum binlog_filter_state { BINLOG_FILTER_UNKNOWN, BINLOG_FILTER_CLEAR, BINLOG_FILTER_SET }; inline void reset_binlog_local_stmt_filter() { m_binlog_filter_state= BINLOG_FILTER_UNKNOWN; } inline void clear_binlog_local_stmt_filter() { DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN); m_binlog_filter_state= BINLOG_FILTER_CLEAR; } inline void set_binlog_local_stmt_filter() { DBUG_ASSERT(m_binlog_filter_state == BINLOG_FILTER_UNKNOWN); m_binlog_filter_state= BINLOG_FILTER_SET; } inline binlog_filter_state get_binlog_local_stmt_filter() { return m_binlog_filter_state; } /** Checks if a user connection is read-only */ inline bool is_read_only_ctx() { return opt_readonly && !(security_ctx->master_access & PRIV_IGNORE_READ_ONLY) && !slave_thread; } private: /** Indicate if the current statement should be discarded instead of written to the binlog. This is used to discard special statements, such as DML or DDL that affects only 'local' (non replicated) tables, such as performance_schema.* */ binlog_filter_state m_binlog_filter_state; /** Indicates the format in which the current statement will be logged. This can only be set from @c decide_logging_format(). */ enum_binlog_format current_stmt_binlog_format; public: /* 1 if binlog table maps has been written */ bool binlog_table_maps; void issue_unsafe_warnings(); void reset_unsafe_warnings() { binlog_unsafe_warning_flags= 0; } void reset_binlog_for_next_statement() { binlog_table_maps= 0; } bool binlog_table_should_be_logged(const LEX_CSTRING *db); #endif /* MYSQL_CLIENT */ public: struct st_transactions { SAVEPOINT *savepoints; THD_TRANS all; // Trans since BEGIN WORK THD_TRANS stmt; // Trans for current statement bool on; // see ha_enable_transaction() XID_STATE xid_state; XID implicit_xid; WT_THD wt; ///< for deadlock detection Rows_log_event *m_pending_rows_event; struct st_trans_time : public timeval { void reset(THD *thd) { tv_sec= thd->query_start(); tv_usec= (long) thd->query_start_sec_part(); } } start_time; /* Tables changed in transaction (that must be invalidated in query cache). List contain only transactional tables, that not invalidated in query cache (instead of full list of changed in transaction tables). */ CHANGED_TABLE_LIST* changed_tables; MEM_ROOT mem_root; // Transaction-life memory allocation pool void cleanup() { DBUG_ENTER("THD::st_transactions::cleanup"); changed_tables= 0; savepoints= 0; implicit_xid.null(); free_root(&mem_root,MYF(MY_KEEP_PREALLOC)); DBUG_VOID_RETURN; } void free() { free_root(&mem_root,MYF(0)); } bool is_active() { return (all.ha_list != NULL); } bool is_empty() { return all.is_empty() && stmt.is_empty(); } st_transactions() { bzero((char*)this, sizeof(*this)); implicit_xid.null(); init_sql_alloc(key_memory_thd_transactions, &mem_root, DEFAULT_ROOT_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); } } default_transaction, *transaction; Global_read_lock global_read_lock; Field *dup_field; #ifndef _WIN32 sigset_t signals; #endif #ifdef SIGNAL_WITH_VIO_CLOSE Vio* active_vio; #endif /* A permanent memory area of the statement. For conventional execution, the parsed tree and execution runtime reside in the same memory root. In this case stmt_arena points to THD. In case of a prepared statement or a stored procedure statement, thd->mem_root conventionally points to runtime memory, and thd->stmt_arena points to the memory of the PS/SP, where the parsed tree of the statement resides. Whenever you need to perform a permanent transformation of a parsed tree, you should allocate new memory in stmt_arena, to allow correct re-execution of PS/SP. Note: in the parser, stmt_arena == thd, even for PS/SP. */ Query_arena *stmt_arena; /** Get either call or statement arena. In case some function is called from within a query the call arena has to be used for a memory allocation, else use the statement arena. */ Query_arena *active_stmt_arena_to_use() { return (state == Query_arena::STMT_SP_QUERY_ARGUMENTS) ? this : stmt_arena; } void *bulk_param; /* map for tables that will be updated for a multi-table update query statement, for other query statements, this will be zero. */ table_map table_map_for_update; /* Tells if LAST_INSERT_ID(#) was called for the current statement */ bool arg_of_last_insert_id_function; /* ALL OVER THIS FILE, "insert_id" means "*automatically generated* value for insertion into an auto_increment column". */ /* This is the first autogenerated insert id which was *successfully* inserted by the previous statement (exactly, if the previous statement didn't successfully insert an autogenerated insert id, then it's the one of the statement before, etc). It can also be set by SET LAST_INSERT_ID=# or SELECT LAST_INSERT_ID(#). It is returned by LAST_INSERT_ID(). */ ulonglong first_successful_insert_id_in_prev_stmt; /* Variant of the above, used for storing in statement-based binlog. The difference is that the one above can change as the execution of a stored function progresses, while the one below is set once and then does not change (which is the value which statement-based binlog needs). */ ulonglong first_successful_insert_id_in_prev_stmt_for_binlog; /* This is the first autogenerated insert id which was *successfully* inserted by the current statement. It is maintained only to set first_successful_insert_id_in_prev_stmt when statement ends. */ ulonglong first_successful_insert_id_in_cur_stmt; /* We follow this logic: - when stmt starts, first_successful_insert_id_in_prev_stmt contains the first insert id successfully inserted by the previous stmt. - as stmt makes progress, handler::insert_id_for_cur_row changes; every time get_auto_increment() is called, auto_inc_intervals_in_cur_stmt_for_binlog is augmented with the reserved interval (if statement-based binlogging). - at first successful insertion of an autogenerated value, first_successful_insert_id_in_cur_stmt is set to handler::insert_id_for_cur_row. - when stmt goes to binlog, auto_inc_intervals_in_cur_stmt_for_binlog is binlogged if non-empty. - when stmt ends, first_successful_insert_id_in_prev_stmt is set to first_successful_insert_id_in_cur_stmt. */ /* stmt_depends_on_first_successful_insert_id_in_prev_stmt is set when LAST_INSERT_ID() is used by a statement. If it is set, first_successful_insert_id_in_prev_stmt_for_binlog will be stored in the statement-based binlog. This variable is CUMULATIVE along the execution of a stored function or trigger: if one substatement sets it to 1 it will stay 1 until the function/trigger ends, thus making sure that first_successful_insert_id_in_prev_stmt_for_binlog does not change anymore and is propagated to the caller for binlogging. */ bool stmt_depends_on_first_successful_insert_id_in_prev_stmt; /* List of auto_increment intervals reserved by the thread so far, for storage in the statement-based binlog. Note that its minimum is not first_successful_insert_id_in_cur_stmt: assuming a table with an autoinc column, and this happens: INSERT INTO ... VALUES(3); SET INSERT_ID=3; INSERT IGNORE ... VALUES (NULL); then the latter INSERT will insert no rows (first_successful_insert_id_in_cur_stmt == 0), but storing "INSERT_ID=3" in the binlog is still needed; the list's minimum will contain 3. This variable is cumulative: if several statements are written to binlog as one (stored functions or triggers are used) this list is the concatenation of all intervals reserved by all statements. */ Discrete_intervals_list auto_inc_intervals_in_cur_stmt_for_binlog; /* Used by replication and SET INSERT_ID */ Discrete_intervals_list auto_inc_intervals_forced; /* There is BUG#19630 where statement-based replication of stored functions/triggers with two auto_increment columns breaks. We however ensure that it works when there is 0 or 1 auto_increment column; our rules are a) on master, while executing a top statement involving substatements, first top- or sub- statement to generate auto_increment values wins the exclusive right to see its values be written to binlog (the write will be done by the statement or its caller), and the losers won't see their values be written to binlog. b) on slave, while replicating a top statement involving substatements, first top- or sub- statement to need to read auto_increment values from the master's binlog wins the exclusive right to read them (so the losers won't read their values from binlog but instead generate on their own). a) implies that we mustn't backup/restore auto_inc_intervals_in_cur_stmt_for_binlog. b) implies that we mustn't backup/restore auto_inc_intervals_forced. If there are more than 1 auto_increment columns, then intervals for different columns may mix into the auto_inc_intervals_in_cur_stmt_for_binlog list, which is logically wrong, but there is no point in preventing this mixing by preventing intervals from the secondly inserted column to come into the list, as such prevention would be wrong too. What will happen in the case of INSERT INTO t1 (auto_inc) VALUES(NULL); where t1 has a trigger which inserts into an auto_inc column of t2, is that in binlog we'll store the interval of t1 and the interval of t2 (when we store intervals, soon), then in slave, t1 will use both intervals, t2 will use none; if t1 inserts the same number of rows as on master, normally the 2nd interval will not be used by t1, which is fine. t2's values will be wrong if t2's internal auto_increment counter is different from what it was on master (which is likely). In 5.1, in mixed binlogging mode, row-based binlogging is used for such cases where two auto_increment columns are inserted. */ inline void record_first_successful_insert_id_in_cur_stmt(ulonglong id_arg) { if (first_successful_insert_id_in_cur_stmt == 0) first_successful_insert_id_in_cur_stmt= id_arg; } inline ulonglong read_first_successful_insert_id_in_prev_stmt(void) { if (!stmt_depends_on_first_successful_insert_id_in_prev_stmt) { /* It's the first time we read it */ first_successful_insert_id_in_prev_stmt_for_binlog= first_successful_insert_id_in_prev_stmt; stmt_depends_on_first_successful_insert_id_in_prev_stmt= 1; } return first_successful_insert_id_in_prev_stmt; } /* Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#" (mysqlbinlog). We'll soon add a variant which can take many intervals in argument. */ inline void force_one_auto_inc_interval(ulonglong next_id) { auto_inc_intervals_forced.empty(); // in case of multiple SET INSERT_ID auto_inc_intervals_forced.append(next_id, ULONGLONG_MAX, 0); } inline void set_binlog_bit() { if (variables.sql_log_bin) variables.option_bits |= OPTION_BIN_LOG; else variables.option_bits &= ~OPTION_BIN_LOG; } ulonglong limit_found_rows; private: /** Stores the result of ROW_COUNT() function. ROW_COUNT() function is a MySQL extention, but we try to keep it similar to ROW_COUNT member of the GET DIAGNOSTICS stack of the SQL standard (see SQL99, part 2, search for ROW_COUNT). It's value is implementation defined for anything except INSERT, DELETE, UPDATE. ROW_COUNT is assigned according to the following rules: - In my_ok(): - for DML statements: to the number of affected rows; - for DDL statements: to 0. - In my_eof(): to -1 to indicate that there was a result set. We derive this semantics from the JDBC specification, where int java.sql.Statement.getUpdateCount() is defined to (sic) "return the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned". - In my_error(): to -1 to be compatible with the MySQL C API and MySQL ODBC driver. - For SIGNAL statements: to 0 per WL#2110 specification (see also sql_signal.cc comment). Zero is used since that's the "default" value of ROW_COUNT in the diagnostics area. */ longlong m_row_count_func; /* For the ROW_COUNT() function */ public: inline longlong get_row_count_func() const { return m_row_count_func; } inline void set_row_count_func(longlong row_count_func) { m_row_count_func= row_count_func; } inline void set_affected_rows(longlong row_count_func) { /* We have to add to affected_rows (used by slow log), as otherwise information for 'call' will be wrong */ affected_rows+= (row_count_func >= 0 ? row_count_func : 0); } ha_rows cuted_fields; private: /* number of rows we actually sent to the client, including "synthetic" rows in ROLLUP etc. */ ha_rows m_sent_row_count; /** Number of rows read and/or evaluated for a statement. Used for slow log reporting. An examined row is defined as a row that is read and/or evaluated according to a statement condition, including in create_sort_index(). Rows may be counted more than once, e.g., a statement including ORDER BY could possibly evaluate the row in filesort() before reading it for e.g. update. */ ha_rows m_examined_row_count; public: ha_rows get_sent_row_count() const { return m_sent_row_count; } ha_rows get_examined_row_count() const { DBUG_EXECUTE_IF("debug_huge_number_of_examined_rows", return (ULONGLONG_MAX - 1000000);); return m_examined_row_count; } ulonglong get_affected_rows() const { return affected_rows; } void set_sent_row_count(ha_rows count); void set_examined_row_count(ha_rows count); void inc_sent_row_count(ha_rows count); void inc_examined_row_count(ha_rows count); void inc_status_created_tmp_disk_tables(); void inc_status_created_tmp_files(); void inc_status_created_tmp_tables(); void inc_status_select_full_join(); void inc_status_select_full_range_join(); void inc_status_select_range(); void inc_status_select_range_check(); void inc_status_select_scan(); void inc_status_sort_merge_passes(); void inc_status_sort_range(); void inc_status_sort_rows(ha_rows count); void inc_status_sort_scan(); void set_status_no_index_used(); void set_status_no_good_index_used(); /** The number of rows and/or keys examined by the query, both read, changed or written. */ ulonglong accessed_rows_and_keys; /** Check if the number of rows accessed by a statement exceeded LIMIT ROWS EXAMINED. If so, signal the query engine to stop execution. */ void check_limit_rows_examined() { if (++accessed_rows_and_keys > lex->limit_rows_examined_cnt) set_killed(ABORT_QUERY); } USER_CONN *user_connect; CHARSET_INFO *db_charset; #if defined(ENABLED_PROFILING) PROFILING profiling; #endif /** Current stage progress instrumentation. */ PSI_stage_progress *m_stage_progress_psi; /** Current statement digest. */ sql_digest_state *m_digest; /** Current statement digest token array. */ unsigned char *m_token_array; /** Top level statement digest. */ sql_digest_state m_digest_state; /** Current statement instrumentation. */ PSI_statement_locker *m_statement_psi; #ifdef HAVE_PSI_STATEMENT_INTERFACE /** Current statement instrumentation state. */ PSI_statement_locker_state m_statement_state; #endif /* HAVE_PSI_STATEMENT_INTERFACE */ /** Current transaction instrumentation. */ PSI_transaction_locker *m_transaction_psi; #ifdef HAVE_PSI_TRANSACTION_INTERFACE /** Current transaction instrumentation state. */ PSI_transaction_locker_state m_transaction_state; #endif /* HAVE_PSI_TRANSACTION_INTERFACE */ /** Idle instrumentation. */ PSI_idle_locker *m_idle_psi; #ifdef HAVE_PSI_IDLE_INTERFACE /** Idle instrumentation state. */ PSI_idle_locker_state m_idle_state; #endif /* HAVE_PSI_IDLE_INTERFACE */ /* Id of current query. Statement can be reused to execute several queries query_id is global in context of the whole MySQL server. ID is automatically generated from mutex-protected counter. It's used in handler code for various purposes: to check which columns from table are necessary for this select, to check if it's necessary to update auto-updatable fields (like auto_increment and timestamp). */ query_id_t query_id; privilege_t col_access; /* Statement id is thread-wide. This counter is used to generate ids */ ulong statement_id_counter; ulong rand_saved_seed1, rand_saved_seed2; /* The following variables are used when printing to slow log */ ulong query_plan_flags; ulong query_plan_fsort_passes; ulong tmp_tables_used; ulong tmp_tables_disk_used; ulonglong tmp_tables_size; ulonglong bytes_sent_old; ulonglong affected_rows; /* Number of changed rows */ Opt_trace_context opt_trace; pthread_t real_id; /* For debugging */ my_thread_id thread_id, thread_dbug_id; uint32 os_thread_id; uint tmp_table, global_disable_checkpoint; uint server_status,open_options; enum enum_thread_type system_thread; enum backup_stages current_backup_stage; #ifdef WITH_WSREP bool wsrep_desynced_backup_stage; #endif /* WITH_WSREP */ /* Current or next transaction isolation level. When a connection is established, the value is taken from @@session.tx_isolation (default transaction isolation for the session), which is in turn taken from @@global.tx_isolation (the global value). If there is no transaction started, this variable holds the value of the next transaction's isolation level. When a transaction starts, the value stored in this variable becomes "actual". At transaction commit or rollback, we assign this variable again from @@session.tx_isolation. The only statement that can otherwise change the value of this variable is SET TRANSACTION ISOLATION LEVEL. Its purpose is to effect the isolation level of the next transaction in this session. When this statement is executed, the value in this variable is changed. However, since this statement is only allowed when there is no active transaction, this assignment (naturally) only affects the upcoming transaction. At the end of the current active transaction the value is be reset again from @@session.tx_isolation, as described above. */ enum_tx_isolation tx_isolation; /* Current or next transaction access mode. See comment above regarding tx_isolation. */ bool tx_read_only; enum_check_fields count_cuted_fields; DYNAMIC_ARRAY user_var_events; /* For user variables replication */ MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */ /* Define durability properties that engines may check to improve performance. Not yet used in MariaDB */ enum durability_properties durability_property; /* If checking this in conjunction with a wait condition, please include a check after enter_cond() if you want to avoid a race condition. For details see the implementation of awake(), especially the "broadcast" part. */ killed_state volatile killed; /* The following is used if one wants to have a specific error number and text for the kill */ struct err_info { int no; const char msg[256]; } *killed_err; /* See also thd_killed() */ inline bool check_killed(bool dont_send_error_message= 0) { if (unlikely(killed)) { if (!dont_send_error_message) send_kill_message(); return TRUE; } if (apc_target.have_apc_requests()) apc_target.process_apc_requests(false); return FALSE; } /* scramble - random string sent to client on handshake */ char scramble[SCRAMBLE_LENGTH+1]; /* If this is a slave, the name of the connection stored here. This is used for taging error messages in the log files. */ LEX_CSTRING connection_name; char default_master_connection_buff[MAX_CONNECTION_NAME+1]; uint8 password; /* 0, 1 or 2 */ uint8 failed_com_change_user; bool slave_thread; bool no_errors; /** Set to TRUE if execution of the current compound statement can not continue. In particular, disables activation of CONTINUE or EXIT handlers of stored routines. Reset in the end of processing of the current user request, in @see THD::reset_for_next_command(). */ bool is_fatal_error; /** Set by a storage engine to request the entire transaction (that possibly spans multiple engines) to rollback. Reset in ha_rollback. */ bool transaction_rollback_request; /** TRUE if we are in a sub-statement and the current error can not be safely recovered until we left the sub-statement mode. In particular, disables activation of CONTINUE and EXIT handlers inside sub-statements. E.g. if it is a deadlock error and requires a transaction-wide rollback, this flag is raised (traditionally, MySQL first has to close all the reads via @see handler::ha_index_or_rnd_end() and only then perform the rollback). Reset to FALSE when we leave the sub-statement mode. */ bool is_fatal_sub_stmt_error; bool rand_used, time_zone_used; bool query_start_sec_part_used; /* for IS NULL => = last_insert_id() fix in remove_eq_conds() */ bool substitute_null_with_insert_id; bool in_lock_tables; bool bootstrap, cleanup_done, free_connection_done; /** is set if some thread specific value(s) used in a statement. */ bool thread_specific_used; /** is set if a statement accesses a temporary table created through CREATE TEMPORARY TABLE. */ private: bool charset_is_system_charset, charset_is_collation_connection; bool charset_is_character_set_filesystem; public: bool enable_slow_log; /* Enable slow log for current statement */ bool abort_on_warning; bool got_warning; /* Set on call to push_warning() */ /* set during loop of derived table processing */ bool derived_tables_processing; bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */ /* True if we have to log the current statement */ bool log_current_statement; /** True if a slave error. Causes the slave to stop. Not the same as the statement execution error (is_error()), since a statement may be expected to return an error, e.g. because it returned an error on master, and this is OK on the slave. */ bool is_slave_error; /* True if we have printed something to the error log for this statement */ bool error_printed_to_log; /* True when a transaction is queued up for binlog group commit. Used so that if another transaction needs to wait for a row lock held by this transaction, it can signal to trigger the group commit immediately, skipping the normal --binlog-commit-wait-count wait. */ bool waiting_on_group_commit; /* Set true when another transaction goes to wait on a row lock held by this transaction. Used together with waiting_on_group_commit. */ bool has_waiter; /* In case of a slave, set to the error code the master got when executing the query. 0 if no error on the master. The stored into variable master error code may get reset inside execution stack when the event turns out to be ignored. */ int slave_expected_error; enum_sql_command last_sql_command; // Last sql_command exceuted in mysql_execute_command() sp_rcontext *spcont; // SP runtime context /** number of name_const() substitutions, see sp_head.cc:subst_spvars() */ uint query_name_consts; NET* slave_net; // network connection from slave -> m. /* Used to update global user stats. The global user stats are updated occasionally with the 'diff' variables. After the update, the 'diff' variables are reset to 0. */ /* Time when the current thread connected to MySQL. */ time_t current_connect_time; /* Last time when THD stats were updated in global_user_stats. */ time_t last_global_update_time; /* Number of commands not reflected in global_user_stats yet. */ uint select_commands, update_commands, other_commands; ulonglong start_cpu_time; ulonglong start_bytes_received; /* Used by the sys_var class to store temporary values */ union { my_bool my_bool_value; int int_value; uint uint_value; long long_value; ulong ulong_value; ulonglong ulonglong_value; double double_value; void *ptr_value; } sys_var_tmp; struct { /* If true, mysql_bin_log::write(Log_event) call will not write events to binlog, and maintain 2 below variables instead (use mysql_bin_log.start_union_events to turn this on) */ bool do_union; /* If TRUE, at least one mysql_bin_log::write(Log_event) call has been made after last mysql_bin_log.start_union_events() call. */ bool unioned_events; /* If TRUE, at least one mysql_bin_log::write(Log_event e), where e.cache_stmt == TRUE call has been made after last mysql_bin_log.start_union_events() call. */ bool unioned_events_trans; /* 'queries' (actually SP statements) that run under inside this binlog union have thd->query_id >= first_query_id. */ query_id_t first_query_id; } binlog_evt_union; /** Internal parser state. Note that since the parser is not re-entrant, we keep only one parser state here. This member is valid only when executing code during parsing. */ Parser_state *m_parser_state; Locked_tables_list locked_tables_list; #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *work_part_info; #endif #ifndef EMBEDDED_LIBRARY /** Array of active audit plugins which have been used by this THD. This list is later iterated to invoke release_thd() on those plugins. */ DYNAMIC_ARRAY audit_class_plugins; /** Array of bits indicating which audit classes have already been added to the list of audit plugins which are currently in use. */ unsigned long audit_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; int audit_plugin_version; #endif #if defined(ENABLED_DEBUG_SYNC) /* Debug Sync facility. See debug_sync.cc. */ struct st_debug_sync_control *debug_sync_control; #endif /* defined(ENABLED_DEBUG_SYNC) */ /** @param id thread identifier @param is_wsrep_applier thread type */ THD(my_thread_id id, bool is_wsrep_applier= false); ~THD(); void init(); /* Initialize memory roots necessary for query processing and (!) pre-allocate memory for it. We can't do that in THD constructor because there are use cases (acl_init, delayed inserts, watcher threads, killing mysqld) where it's vital to not allocate excessive and not used memory. Note, that we still don't return error from init_for_queries(): if preallocation fails, we should notice that at the first call to alloc_root. */ void init_for_queries(); void update_all_stats(); void update_stats(void); void change_user(void); void cleanup(void); void cleanup_after_query(); void free_connection(); void reset_for_reuse(); void store_globals(); void reset_stack() { thread_stack= 0; } void reset_globals(); bool trace_started() { return opt_trace.is_started(); } #ifdef SIGNAL_WITH_VIO_CLOSE inline void set_active_vio(Vio* vio) { mysql_mutex_lock(&LOCK_thd_data); active_vio = vio; mysql_mutex_unlock(&LOCK_thd_data); } inline void clear_active_vio() { mysql_mutex_lock(&LOCK_thd_data); active_vio = 0; mysql_mutex_unlock(&LOCK_thd_data); } void close_active_vio(); #endif void awake_no_mutex(killed_state state_to_set); void awake(killed_state state_to_set) { mysql_mutex_lock(&LOCK_thd_kill); mysql_mutex_lock(&LOCK_thd_data); awake_no_mutex(state_to_set); mysql_mutex_unlock(&LOCK_thd_data); mysql_mutex_unlock(&LOCK_thd_kill); } void abort_current_cond_wait(bool force); /** Disconnect the associated communication endpoint. */ void disconnect(); /* Allows this thread to serve as a target for others to schedule Async Procedure Calls on. It's possible to schedule any code to be executed this way, by inheriting from the Apc_call object. Currently, only Show_explain_request uses this. */ Apc_target apc_target; Gap_time_tracker_data gap_tracker_data; #ifndef MYSQL_CLIENT enum enum_binlog_query_type { /* The query can be logged in row format or in statement format. */ ROW_QUERY_TYPE, /* The query has to be logged in statement format. */ STMT_QUERY_TYPE, QUERY_TYPE_COUNT }; int binlog_query(enum_binlog_query_type qtype, char const *query, ulong query_len, bool is_trans, bool direct, bool suppress_use, int errcode); bool binlog_current_query_unfiltered(); #endif inline void enter_cond(mysql_cond_t *cond, mysql_mutex_t* mutex, const PSI_stage_info *stage, PSI_stage_info *old_stage, const char *src_function, const char *src_file, int src_line) override { mysql_mutex_assert_owner(mutex); mysys_var->current_mutex = mutex; mysys_var->current_cond = cond; if (old_stage) backup_stage(old_stage); if (stage) enter_stage(stage, src_function, src_file, src_line); } inline void exit_cond(const PSI_stage_info *stage, const char *src_function, const char *src_file, int src_line) override { /* Putting the mutex unlock in thd->exit_cond() ensures that mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is locked (if that would not be the case, you'll get a deadlock if someone does a THD::awake() on you). */ mysql_mutex_unlock(mysys_var->current_mutex); mysql_mutex_lock(&mysys_var->mutex); mysys_var->current_mutex = 0; mysys_var->current_cond = 0; if (stage) enter_stage(stage, src_function, src_file, src_line); mysql_mutex_unlock(&mysys_var->mutex); return; } int is_killed() override { return killed; } THD* get_thd() override { return this; } /** A callback to the server internals that is used to address special cases of the locking protocol. Invoked when acquiring an exclusive lock, for each thread that has a conflicting shared metadata lock. This function: - aborts waiting of the thread on a data lock, to make it notice the pending exclusive lock and back off. - if the thread is an INSERT DELAYED thread, sends it a KILL signal to terminate it. @note This function does not wait for the thread to give away its locks. Waiting is done outside for all threads at once. @param ctx_in_use The MDL context owner (thread) to wake up. @param needs_thr_lock_abort Indicates that to wake up thread this call needs to abort its waiting on table-level lock. @retval TRUE if the thread was woken up @retval FALSE otherwise. */ bool notify_shared_lock(MDL_context_owner *ctx_in_use, bool needs_thr_lock_abort) override; // End implementation of MDL_context_owner interface. inline bool is_strict_mode() const { return (bool) (variables.sql_mode & (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)); } inline bool backslash_escapes() const { return !MY_TEST(variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES); } const Type_handler *type_handler_for_datetime() const; bool timestamp_to_TIME(MYSQL_TIME *ltime, my_time_t ts, ulong sec_part, date_mode_t fuzzydate); inline my_time_t query_start() { return start_time; } inline ulong query_start_sec_part() { query_start_sec_part_used=1; return start_time_sec_part; } MYSQL_TIME query_start_TIME(); time_round_mode_t temporal_round_mode() const { return variables.sql_mode & MODE_TIME_ROUND_FRACTIONAL ? TIME_FRAC_ROUND : TIME_FRAC_TRUNCATE; } private: struct { my_hrtime_t start; my_time_t sec; ulong sec_part; } system_time; void set_system_time() { my_hrtime_t hrtime= my_hrtime(); my_time_t sec= hrtime_to_my_time(hrtime); ulong sec_part= hrtime_sec_part(hrtime); if (sec > system_time.sec || (sec == system_time.sec && sec_part > system_time.sec_part) || hrtime.val < system_time.start.val) { system_time.sec= sec; system_time.sec_part= sec_part; system_time.start= hrtime; } else { if (system_time.sec_part < TIME_MAX_SECOND_PART) system_time.sec_part++; else { system_time.sec++; system_time.sec_part= 0; } } } public: timeval transaction_time() { if (!in_multi_stmt_transaction_mode()) transaction->start_time.reset(this); return transaction->start_time; } inline void set_start_time() { if (user_time.val) { start_time= hrtime_to_my_time(user_time); start_time_sec_part= hrtime_sec_part(user_time); } else { set_system_time(); start_time= system_time.sec; start_time_sec_part= system_time.sec_part; } PSI_CALL_set_thread_start_time(start_time); } inline void set_time() { set_start_time(); start_utime= utime_after_lock= microsecond_interval_timer(); } /* only used in SET @@timestamp=... */ inline void set_time(my_hrtime_t t) { user_time= t; set_time(); } inline void force_set_time(my_time_t t, ulong sec_part) { start_time= system_time.sec= t; start_time_sec_part= system_time.sec_part= sec_part; } /* this is only used by replication and BINLOG command. usecs > TIME_MAX_SECOND_PART means "was not in binlog" */ inline void set_time(my_time_t t, ulong sec_part) { if (opt_secure_timestamp > (slave_thread ? SECTIME_REPL : SECTIME_SUPER)) set_time(); // note that BINLOG itself requires SUPER else { if (sec_part <= TIME_MAX_SECOND_PART) force_set_time(t, sec_part); else if (t != system_time.sec) force_set_time(t, 0); else { start_time= t; start_time_sec_part= ++system_time.sec_part; } user_time.val= hrtime_from_time(start_time) + start_time_sec_part; PSI_CALL_set_thread_start_time(start_time); start_utime= utime_after_lock= microsecond_interval_timer(); } } void set_time_after_lock() { utime_after_lock= microsecond_interval_timer(); MYSQL_SET_STATEMENT_LOCK_TIME(m_statement_psi, (utime_after_lock - start_utime)); } ulonglong current_utime() { return microsecond_interval_timer(); } /* Tell SHOW PROCESSLIST to show time from this point */ inline void set_time_for_next_stage() { utime_after_query= current_utime(); } /** Update server status after execution of a top level statement. Currently only checks if a query was slow, and assigns the status accordingly. Evaluate the current time, and if it exceeds the long-query-time setting, mark the query as slow. */ void update_server_status() { set_time_for_next_stage(); if (utime_after_query >= utime_after_lock + variables.long_query_time) server_status|= SERVER_QUERY_WAS_SLOW; } inline ulonglong found_rows(void) { return limit_found_rows; } /** Returns TRUE if session is in a multi-statement transaction mode. OPTION_NOT_AUTOCOMMIT: When autocommit is off, a multi-statement transaction is implicitly started on the first statement after a previous transaction has been ended. OPTION_BEGIN: Regardless of the autocommit status, a multi-statement transaction can be explicitly started with the statements "START TRANSACTION", "BEGIN [WORK]", "[COMMIT | ROLLBACK] AND CHAIN", etc. Note: this doesn't tell you whether a transaction is active. A session can be in multi-statement transaction mode, and yet have no active transaction, e.g., in case of: set @@autocommit=0; set @a= 3; <-- these statements don't set transaction isolation level serializable; <-- start an active flush tables; <-- transaction I.e. for the above scenario this function returns TRUE, even though no active transaction has begun. @sa in_active_multi_stmt_transaction() */ inline bool in_multi_stmt_transaction_mode() { return variables.option_bits & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN); } /** TRUE if the session is in a multi-statement transaction mode (@sa in_multi_stmt_transaction_mode()) *and* there is an active transaction, i.e. there is an explicit start of a transaction with BEGIN statement, or implicit with a statement that uses a transactional engine. For example, these scenarios don't start an active transaction (even though the server is in multi-statement transaction mode): set @@autocommit=0; select * from nontrans_table; set @var=TRUE; flush tables; Note, that even for a statement that starts a multi-statement transaction (i.e. select * from trans_table), this flag won't be set until we open the statement's tables and the engines register themselves for the transaction (see trans_register_ha()), hence this method is reliable to use only after open_tables() has completed. Why do we need a flag? ---------------------- We need to maintain a (at first glance redundant) session flag, rather than looking at thd->transaction.all.ha_list because of explicit start of a transaction with BEGIN. I.e. in case of BEGIN; select * from nontrans_t1; <-- in_active_multi_stmt_transaction() is true */ inline bool in_active_multi_stmt_transaction() { return server_status & SERVER_STATUS_IN_TRANS; } /* Commit both statement and full transaction */ int commit_whole_transaction_and_close_tables(); void give_protection_error(); /* Give an error if any of the following is true for this connection - BACKUP STAGE is active - FLUSH TABLE WITH READ LOCK is active - BACKUP LOCK table_name is active */ inline bool has_read_only_protection() { if (current_backup_stage == BACKUP_FINISHED && !global_read_lock.is_acquired() && !mdl_backup_lock) return FALSE; give_protection_error(); return TRUE; } inline bool fill_information_schema_tables() { return !stmt_arena->is_stmt_prepare(); } inline void* trans_alloc(size_t size) { return alloc_root(&transaction->mem_root,size); } LEX_CSTRING strmake_lex_cstring(const char *str, size_t length) { const char *tmp= strmake_root(mem_root, str, length); if (!tmp) return {0,0}; return {tmp, length}; } LEX_CSTRING strmake_lex_cstring(const LEX_CSTRING &from) { return strmake_lex_cstring(from.str, from.length); } LEX_CSTRING strmake_lex_cstring_trim_whitespace(const LEX_CSTRING &from) { return strmake_lex_cstring(Lex_cstring(from).trim_whitespace(charset())); } LEX_STRING *make_lex_string(LEX_STRING *lex_str, const char* str, size_t length) { if (!(lex_str->str= strmake_root(mem_root, str, length))) { lex_str->length= 0; return 0; } lex_str->length= length; return lex_str; } LEX_CSTRING *make_lex_string(LEX_CSTRING *lex_str, const char* str, size_t length) { if (!(lex_str->str= strmake_root(mem_root, str, length))) { lex_str->length= 0; return 0; } lex_str->length= length; return lex_str; } // Remove double quotes: aaa""bbb -> aaa"bbb bool quote_unescape(LEX_CSTRING *dst, const LEX_CSTRING *src, char quote) { const char *tmp= src->str; const char *tmpend= src->str + src->length; char *to; if (!(dst->str= to= (char *) alloc(src->length + 1))) { dst->length= 0; // Safety return true; } for ( ; tmp < tmpend; ) { if ((*to++= *tmp++) == quote) tmp++; // Skip double quotes } *to= 0; // End null for safety dst->length= to - dst->str; return false; } LEX_CSTRING *make_clex_string(const char* str, size_t length) { LEX_CSTRING *lex_str; char *tmp; if (unlikely(!(lex_str= (LEX_CSTRING *)alloc_root(mem_root, sizeof(LEX_CSTRING) + length+1)))) return 0; tmp= (char*) (lex_str+1); lex_str->str= tmp; memcpy(tmp, str, length); tmp[length]= 0; lex_str->length= length; return lex_str; } LEX_CSTRING *make_clex_string(const LEX_CSTRING from) { return make_clex_string(from.str, from.length); } // Allocate LEX_STRING for character set conversion bool alloc_lex_string(LEX_STRING *dst, size_t length) { if (likely((dst->str= (char*) alloc(length)))) return false; dst->length= 0; // Safety return true; // EOM } bool convert_string(LEX_STRING *to, CHARSET_INFO *to_cs, const char *from, size_t from_length, CHARSET_INFO *from_cs); bool reinterpret_string_from_binary(LEX_CSTRING *to, CHARSET_INFO *to_cs, const char *from, size_t from_length); bool convert_string(LEX_CSTRING *to, CHARSET_INFO *to_cs, const char *from, size_t from_length, CHARSET_INFO *from_cs) { LEX_STRING tmp; bool rc= convert_string(&tmp, to_cs, from, from_length, from_cs); to->str= tmp.str; to->length= tmp.length; return rc; } bool convert_string(LEX_CSTRING *to, CHARSET_INFO *tocs, const LEX_CSTRING *from, CHARSET_INFO *fromcs, bool simple_copy_is_possible) { if (!simple_copy_is_possible) return unlikely(convert_string(to, tocs, from->str, from->length, fromcs)); if (fromcs == &my_charset_bin) return reinterpret_string_from_binary(to, tocs, from->str, from->length); *to= *from; return false; } /* Convert a strings between character sets. Uses my_convert_fix(), which uses an mb_wc .. mc_mb loop internally. dstcs and srccs cannot be &my_charset_bin. */ bool convert_fix(CHARSET_INFO *dstcs, LEX_STRING *dst, CHARSET_INFO *srccs, const char *src, size_t src_length, String_copier *status); /* Same as above, but additionally sends ER_INVALID_CHARACTER_STRING in case of bad byte sequences or Unicode conversion problems. */ bool convert_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst, CHARSET_INFO *srccs, const char *src, size_t src_length); /* If either "dstcs" or "srccs" is &my_charset_bin, then performs native copying using copy_fix(). Otherwise, performs Unicode conversion using convert_fix(). */ bool copy_fix(CHARSET_INFO *dstcs, LEX_STRING *dst, CHARSET_INFO *srccs, const char *src, size_t src_length, String_copier *status); /* Same as above, but additionally sends ER_INVALID_CHARACTER_STRING in case of bad byte sequences or Unicode conversion problems. */ bool copy_with_error(CHARSET_INFO *dstcs, LEX_STRING *dst, CHARSET_INFO *srccs, const char *src, size_t src_length); bool convert_string(String *s, CHARSET_INFO *from_cs, CHARSET_INFO *to_cs); /* Check if the string is wellformed, raise an error if not wellformed. @param str - The string to check. @param length - the string length. */ bool check_string_for_wellformedness(const char *str, size_t length, CHARSET_INFO *cs) const; bool to_ident_sys_alloc(Lex_ident_sys_st *to, const Lex_ident_cli_st *from); /* Create a string literal with optional client->connection conversion. @param str - the string in the client character set @param length - length of the string @param repertoire - the repertoire of the string */ Item_basic_constant *make_string_literal(const char *str, size_t length, my_repertoire_t repertoire); Item_basic_constant *make_string_literal(const Lex_string_with_metadata_st &str) { my_repertoire_t repertoire= str.repertoire(variables.character_set_client); return make_string_literal(str.str, str.length, repertoire); } Item_basic_constant *make_string_literal_nchar(const Lex_string_with_metadata_st &str); Item_basic_constant *make_string_literal_charset(const Lex_string_with_metadata_st &str, CHARSET_INFO *cs); bool make_text_string_sys(LEX_CSTRING *to, const Lex_string_with_metadata_st *from) { return convert_string(to, system_charset_info, from, charset(), charset_is_system_charset); } bool make_text_string_connection(LEX_CSTRING *to, const Lex_string_with_metadata_st *from) { return convert_string(to, variables.collation_connection, from, charset(), charset_is_collation_connection); } bool make_text_string_filesystem(LEX_CSTRING *to, const Lex_string_with_metadata_st *from) { return convert_string(to, variables.character_set_filesystem, from, charset(), charset_is_character_set_filesystem); } void add_changed_table(TABLE *table); void add_changed_table(const char *key, size_t key_length); CHANGED_TABLE_LIST * changed_table_dup(const char *key, size_t key_length); int prepare_explain_fields(select_result *result, List *field_list, uint8 explain_flags, bool is_analyze); int send_explain_fields(select_result *result, uint8 explain_flags, bool is_analyze); void make_explain_field_list(List &field_list, uint8 explain_flags, bool is_analyze); void make_explain_json_field_list(List &field_list, bool is_analyze); /** Clear the current error, if any. We do not clear is_fatal_error or is_fatal_sub_stmt_error since we assume this is never called if the fatal error is set. @todo: To silence an error, one should use Internal_error_handler mechanism. Issuing an error that can be possibly later "cleared" is not compatible with other installed error handlers and audit plugins. */ inline void clear_error(bool clear_diagnostics= 0) { DBUG_ENTER("clear_error"); if (get_stmt_da()->is_error() || clear_diagnostics) get_stmt_da()->reset_diagnostics_area(); is_slave_error= 0; if (killed == KILL_BAD_DATA) reset_killed(); my_errno= 0; DBUG_VOID_RETURN; } #ifndef EMBEDDED_LIBRARY inline bool vio_ok() const { return net.vio != 0; } /** Return FALSE if connection to client is broken. */ bool is_connected() { /* All system threads (e.g., the slave IO thread) are connected but not using vio. So this function always returns true for all system threads. */ return system_thread || (vio_ok() ? vio_is_connected(net.vio) : FALSE); } #else inline bool vio_ok() const { return TRUE; } inline bool is_connected() { return TRUE; } #endif void my_ok_with_recreate_info(const Recreate_info &info, ulong warn_count); /** Mark the current error as fatal. Warning: this does not set any error, it sets a property of the error, so must be followed or prefixed with my_error(). */ inline void fatal_error() { DBUG_ASSERT(get_stmt_da()->is_error() || killed); is_fatal_error= 1; DBUG_PRINT("error",("Fatal error set")); } /** TRUE if there is an error in the error stack. Please use this method instead of direct access to net.report_error. If TRUE, the current (sub)-statement should be aborted. The main difference between this member and is_fatal_error is that a fatal error can not be handled by a stored procedure continue handler, whereas a normal error can. To raise this flag, use my_error(). */ inline bool is_error() const { return m_stmt_da->is_error(); } void set_bulk_execution(void *bulk) { bulk_param= bulk; m_stmt_da->set_bulk_execution(MY_TEST(bulk)); } bool is_bulk_op() const { return MY_TEST(bulk_param); } /// Returns Diagnostics-area for the current statement. Diagnostics_area *get_stmt_da() { return m_stmt_da; } /// Returns Diagnostics-area for the current statement. const Diagnostics_area *get_stmt_da() const { return m_stmt_da; } /// Sets Diagnostics-area for the current statement. void set_stmt_da(Diagnostics_area *da) { m_stmt_da= da; } inline CHARSET_INFO *charset() const { return variables.character_set_client; } void update_charset(); void update_charset(CHARSET_INFO *character_set_client, CHARSET_INFO *collation_connection) { variables.character_set_client= character_set_client; variables.collation_connection= collation_connection; update_charset(); } void update_charset(CHARSET_INFO *character_set_client, CHARSET_INFO *collation_connection, CHARSET_INFO *character_set_results) { variables.character_set_client= character_set_client; variables.collation_connection= collation_connection; variables.character_set_results= character_set_results; update_charset(); } inline Query_arena *activate_stmt_arena_if_needed(Query_arena *backup) { if (state == Query_arena::STMT_SP_QUERY_ARGUMENTS) /* Caller uses the arena with state STMT_SP_QUERY_ARGUMENTS for stored routine's parameters. Lifetime of these objects spans a lifetime of stored routine call and freed every time the stored routine execution has been completed. That is the reason why switching to statement's arena is not performed for arguments, else we would observe increasing of memory usage while a stored routine be called over and over again. */ return NULL; /* Use the persistent arena if we are in a prepared statement or a stored procedure statement and we have not already changed to use this arena. */ if (!stmt_arena->is_conventional() && mem_root != stmt_arena->mem_root) { set_n_backup_active_arena(stmt_arena, backup); return stmt_arena; } return 0; } bool is_item_tree_change_register_required() { return !stmt_arena->is_conventional(); } void register_item_tree_change(Item **place) { /* TODO: check for OOM condition here */ if (is_item_tree_change_register_required()) nocheck_register_item_tree_change(place, *place, mem_root); } void change_item_tree(Item **place, Item *new_value) { DBUG_ENTER("THD::change_item_tree"); DBUG_PRINT("enter", ("Register: %p (%p) <- %p", *place, place, new_value)); register_item_tree_change(place); *place= new_value; DBUG_VOID_RETURN; } /** Make change in item tree after checking whether it needs registering @param place place where we should assign new value @param new_value place of the new value @details see check_and_register_item_tree_change details */ void check_and_register_item_tree(Item **place, Item **new_value) { if (!stmt_arena->is_conventional()) check_and_register_item_tree_change(place, new_value, mem_root); /* We have to use memcpy instead of *place= *new_value merge to avoid problems with strict aliasing. */ memcpy((char*) place, new_value, sizeof(*new_value)); } /* Cleanup statement parse state (parse tree, lex) and execution state after execution of a non-prepared SQL statement. */ void end_statement(); /* Mark thread to be killed, with optional error number and string. string is not released, so it has to be allocted on thd mem_root or be a global string Ensure that we don't replace a kill with a lesser one. For example if user has done 'kill_connection' we shouldn't replace it with KILL_QUERY. */ inline void set_killed(killed_state killed_arg, int killed_errno_arg= 0, const char *killed_err_msg_arg= 0) { mysql_mutex_lock(&LOCK_thd_kill); set_killed_no_mutex(killed_arg, killed_errno_arg, killed_err_msg_arg); mysql_mutex_unlock(&LOCK_thd_kill); } /* This is only used by THD::awake where we need to keep the lock mutex locked over some time. It's ok to have this inline, as in most cases killed_errno_arg will be a constant 0 and most of the function will disappear. */ inline void set_killed_no_mutex(killed_state killed_arg, int killed_errno_arg= 0, const char *killed_err_msg_arg= 0) { if (killed <= killed_arg) { killed= killed_arg; if (killed_errno_arg) { /* If alloc fails, we only remember the killed flag. The worst things that can happen is that we get a suboptimal error message. */ if (!killed_err) killed_err= (err_info*) my_malloc(PSI_INSTRUMENT_ME, sizeof(*killed_err), MYF(MY_WME)); if (likely(killed_err)) { killed_err->no= killed_errno_arg; ::strmake((char*) killed_err->msg, killed_err_msg_arg, sizeof(killed_err->msg)-1); } } } } int killed_errno(); void reset_killed(); inline void reset_kill_query() { if (killed < KILL_CONNECTION) { reset_killed(); mysys_var->abort= 0; } } inline void send_kill_message() { mysql_mutex_lock(&LOCK_thd_kill); int err= killed_errno(); if (err) my_message(err, killed_err ? killed_err->msg : ER_THD(this, err), MYF(0)); mysql_mutex_unlock(&LOCK_thd_kill); } /* return TRUE if we will abort query if we make a warning now */ inline bool really_abort_on_warning() { return (abort_on_warning && (!transaction->stmt.modified_non_trans_table || (variables.sql_mode & MODE_STRICT_ALL_TABLES))); } void set_status_var_init(); void reset_n_backup_open_tables_state(Open_tables_backup *backup); void restore_backup_open_tables_state(Open_tables_backup *backup); void reset_sub_statement_state(Sub_statement_state *backup, uint new_state); void restore_sub_statement_state(Sub_statement_state *backup); void store_slow_query_state(Sub_statement_state *backup); void reset_slow_query_state(); void add_slow_query_state(Sub_statement_state *backup); void set_n_backup_active_arena(Query_arena *set, Query_arena *backup); void restore_active_arena(Query_arena *set, Query_arena *backup); inline void get_binlog_format(enum_binlog_format *format, enum_binlog_format *current_format) { *format= (enum_binlog_format) variables.binlog_format; *current_format= current_stmt_binlog_format; } inline enum_binlog_format get_current_stmt_binlog_format() { return current_stmt_binlog_format; } inline void set_binlog_format(enum_binlog_format format, enum_binlog_format current_format) { DBUG_ENTER("set_binlog_format"); variables.binlog_format= format; current_stmt_binlog_format= current_format; DBUG_VOID_RETURN; } inline void set_binlog_format_stmt() { DBUG_ENTER("set_binlog_format_stmt"); variables.binlog_format= BINLOG_FORMAT_STMT; current_stmt_binlog_format= BINLOG_FORMAT_STMT; DBUG_VOID_RETURN; } /* @todo Make these methods private or remove them completely. Only decide_logging_format should call them. /Sven */ inline void set_current_stmt_binlog_format_row_if_mixed() { DBUG_ENTER("set_current_stmt_binlog_format_row_if_mixed"); /* This should only be called from decide_logging_format. @todo Once we have ensured this, uncomment the following statement, remove the big comment below that, and remove the in_sub_stmt==0 condition from the following 'if'. */ /* DBUG_ASSERT(in_sub_stmt == 0); */ /* If in a stored/function trigger, the caller should already have done the change. We test in_sub_stmt to prevent introducing bugs where people wouldn't ensure that, and would switch to row-based mode in the middle of executing a stored function/trigger (which is too late, see also reset_current_stmt_binlog_format_row()); this condition will make their tests fail and so force them to propagate the lex->binlog_row_based_if_mixed upwards to the caller. */ if ((wsrep_binlog_format(variables.binlog_format) == BINLOG_FORMAT_MIXED) && (in_sub_stmt == 0)) set_current_stmt_binlog_format_row(); DBUG_VOID_RETURN; } inline void set_current_stmt_binlog_format(enum_binlog_format format) { current_stmt_binlog_format= format; } inline void set_current_stmt_binlog_format_row() { DBUG_ENTER("set_current_stmt_binlog_format_row"); current_stmt_binlog_format= BINLOG_FORMAT_ROW; DBUG_VOID_RETURN; } /* Set binlog format temporarily to statement. Returns old format */ inline enum_binlog_format set_current_stmt_binlog_format_stmt() { enum_binlog_format orig_format= current_stmt_binlog_format; DBUG_ENTER("set_current_stmt_binlog_format_stmt"); current_stmt_binlog_format= BINLOG_FORMAT_STMT; DBUG_RETURN(orig_format); } inline void restore_stmt_binlog_format(enum_binlog_format format) { DBUG_ENTER("restore_stmt_binlog_format"); DBUG_ASSERT(!is_current_stmt_binlog_format_row()); current_stmt_binlog_format= format; DBUG_VOID_RETURN; } inline void reset_current_stmt_binlog_format_row() { DBUG_ENTER("reset_current_stmt_binlog_format_row"); /* If there are temporary tables, don't reset back to statement-based. Indeed it could be that: CREATE TEMPORARY TABLE t SELECT UUID(); # row-based # and row-based does not store updates to temp tables # in the binlog. INSERT INTO u SELECT * FROM t; # stmt-based and then the INSERT will fail as data inserted into t was not logged. So we continue with row-based until the temp table is dropped. If we are in a stored function or trigger, we mustn't reset in the middle of its execution (as the binary logging way of a stored function or trigger is decided when it starts executing, depending for example on the caller (for a stored function: if caller is SELECT or INSERT/UPDATE/DELETE...). */ DBUG_PRINT("debug", ("temporary_tables: %s, in_sub_stmt: %s, system_thread: %s", YESNO(has_temporary_tables()), YESNO(in_sub_stmt), show_system_thread(system_thread))); if (in_sub_stmt == 0) { if (wsrep_binlog_format(variables.binlog_format) == BINLOG_FORMAT_ROW) set_current_stmt_binlog_format_row(); else if (!has_temporary_tables()) set_current_stmt_binlog_format_stmt(); } DBUG_VOID_RETURN; } /** Set the current database; use deep copy of C-string. @param new_db a pointer to the new database name. @param new_db_len length of the new database name. Initialize the current database from a NULL-terminated string with length. If we run out of memory, we free the current database and return TRUE. This way the user will notice the error as there will be no current database selected (in addition to the error message set by malloc). @note This operation just sets {db, db_length}. Switching the current database usually involves other actions, like switching other database attributes including security context. In the future, this operation will be made private and more convenient interface will be provided. @return Operation status @retval FALSE Success @retval TRUE Out-of-memory error */ bool set_db(const LEX_CSTRING *new_db); /** Set the current database, without copying */ void reset_db(const LEX_CSTRING *new_db); /* Copy the current database to the argument. Use the current arena to allocate memory for a deep copy: current database may be freed after a statement is parsed but before it's executed. Can only be called by owner of thd (no mutex protection) */ bool copy_db_to(LEX_CSTRING *to) { if (db.str) { to->str= strmake(db.str, db.length); to->length= db.length; return to->str == NULL; /* True on error */ } /* No default database is set. In this case if it's guaranteed that no CTE can be used in the statement then we can throw an error right now at the parser stage. Otherwise the decision about throwing such a message must be postponed until a post-parser stage when we are able to resolve all CTE names as we don't need this message to be thrown for any CTE references. */ if (!lex->with_cte_resolution) my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); return TRUE; } /* Get db name or "". */ const char *get_db() { return safe_str(db.str); } thd_scheduler event_scheduler; public: inline Internal_error_handler *get_internal_handler() { return m_internal_handler; } /** Add an internal error handler to the thread execution context. @param handler the exception handler to add */ void push_internal_handler(Internal_error_handler *handler); private: /** Handle a sql condition. @param sql_errno the condition error number @param sqlstate the condition sqlstate @param level the condition level @param msg the condition message text @param[out] cond_hdl the sql condition raised, if any @return true if the condition is handled */ bool handle_condition(uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level *level, const char* msg, Sql_condition ** cond_hdl); public: /** Remove the error handler last pushed. */ Internal_error_handler *pop_internal_handler(); /** Raise an exception condition. @param code the MYSQL_ERRNO error code of the error */ void raise_error(uint code); /** Raise an exception condition, with a formatted message. @param code the MYSQL_ERRNO error code of the error */ void raise_error_printf(uint code, ...); /** Raise a completion condition (warning). @param code the MYSQL_ERRNO error code of the warning */ void raise_warning(uint code); /** Raise a completion condition (warning), with a formatted message. @param code the MYSQL_ERRNO error code of the warning */ void raise_warning_printf(uint code, ...); /** Raise a completion condition (note), with a fixed message. @param code the MYSQL_ERRNO error code of the note */ void raise_note(uint code); /** Raise an completion condition (note), with a formatted message. @param code the MYSQL_ERRNO error code of the note */ void raise_note_printf(uint code, ...); /** @brief Push an error message into MySQL error stack with line and position information. This function provides semantic action implementers with a way to push the famous "You have a syntax error near..." error message into the error stack, which is normally produced only if a parse error is discovered internally by the Bison generated parser. */ void parse_error(const char *err_text, const char *yytext) { Lex_input_stream *lip= &m_parser_state->m_lip; if (!yytext && !(yytext= lip->get_tok_start())) yytext= ""; /* Push an error into the error stack */ ErrConvString err(yytext, strlen(yytext), variables.character_set_client); my_printf_error(ER_PARSE_ERROR, ER_THD(this, ER_PARSE_ERROR), MYF(0), err_text, err.ptr(), lip->yylineno); } void parse_error(uint err_number, const char *yytext= 0) { parse_error(ER_THD(this, err_number), yytext); } void parse_error() { parse_error(ER_SYNTAX_ERROR); } #ifdef mysqld_error_find_printf_error_used void parse_error(const char *t) { } #endif private: /* Only the implementation of the SIGNAL and RESIGNAL statements is permitted to raise SQL conditions in a generic way, or to raise them by bypassing handlers (RESIGNAL). To raise a SQL condition, the code should use the public raise_error() or raise_warning() methods provided by class THD. */ friend class Sql_cmd_common_signal; friend class Sql_cmd_signal; friend class Sql_cmd_resignal; friend void push_warning(THD*, Sql_condition::enum_warning_level, uint, const char*); friend void my_message_sql(uint, const char *, myf); /** Raise a generic SQL condition. @param sql_errno the condition error number @param sqlstate the condition SQLSTATE @param level the condition level @param msg the condition message text @return The condition raised, or NULL */ Sql_condition* raise_condition(uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level level, const char* msg) { return raise_condition(sql_errno, sqlstate, level, Sql_user_condition_identity(), msg); } /** Raise a generic or a user defined SQL condition. @param ucid - the user condition identity (or an empty identity if not a user condition) @param sql_errno - the condition error number @param sqlstate - the condition SQLSTATE @param level - the condition level @param msg - the condition message text @return The condition raised, or NULL */ Sql_condition* raise_condition(uint sql_errno, const char* sqlstate, Sql_condition::enum_warning_level level, const Sql_user_condition_identity &ucid, const char* msg); Sql_condition* raise_condition(const Sql_condition *cond) { Sql_condition *raised= raise_condition(cond->get_sql_errno(), cond->get_sqlstate(), cond->get_level(), *cond/*Sql_user_condition_identity*/, cond->get_message_text()); if (raised) raised->copy_opt_attributes(cond); return raised; } private: void push_warning_truncated_priv(Sql_condition::enum_warning_level level, uint sql_errno, const char *type_str, const char *val) { DBUG_ASSERT(sql_errno == ER_TRUNCATED_WRONG_VALUE || sql_errno == ER_WRONG_VALUE); char buff[MYSQL_ERRMSG_SIZE]; CHARSET_INFO *cs= &my_charset_latin1; cs->cset->snprintf(cs, buff, sizeof(buff), ER_THD(this, sql_errno), type_str, val); /* Note: the format string can vary between ER_TRUNCATED_WRONG_VALUE and ER_WRONG_VALUE, but the code passed to push_warning() is always ER_TRUNCATED_WRONG_VALUE. This is intentional. */ push_warning(this, level, ER_TRUNCATED_WRONG_VALUE, buff); } public: void push_warning_truncated_wrong_value(Sql_condition::enum_warning_level level, const char *type_str, const char *val) { return push_warning_truncated_priv(level, ER_TRUNCATED_WRONG_VALUE, type_str, val); } void push_warning_wrong_value(Sql_condition::enum_warning_level level, const char *type_str, const char *val) { return push_warning_truncated_priv(level, ER_WRONG_VALUE, type_str, val); } void push_warning_truncated_wrong_value(const char *type_str, const char *val) { return push_warning_truncated_wrong_value(Sql_condition::WARN_LEVEL_WARN, type_str, val); } void push_warning_truncated_value_for_field(Sql_condition::enum_warning_level level, const char *type_str, const char *val, const char *db_name, const char *table_name, const char *name) { DBUG_ASSERT(name); char buff[MYSQL_ERRMSG_SIZE]; CHARSET_INFO *cs= &my_charset_latin1; if (!db_name) db_name= ""; if (!table_name) table_name= ""; cs->cset->snprintf(cs, buff, sizeof(buff), ER_THD(this, ER_TRUNCATED_WRONG_VALUE_FOR_FIELD), type_str, val, db_name, table_name, name, (ulong) get_stmt_da()->current_row_for_warning()); push_warning(this, level, ER_TRUNCATED_WRONG_VALUE, buff); } void push_warning_wrong_or_truncated_value(Sql_condition::enum_warning_level level, bool totally_useless_value, const char *type_str, const char *val, const char *db_name, const char *table_name, const char *field_name) { if (field_name) push_warning_truncated_value_for_field(level, type_str, val, db_name, table_name, field_name); else if (totally_useless_value) push_warning_wrong_value(level, type_str, val); else push_warning_truncated_wrong_value(level, type_str, val); } public: /** Overloaded to guard query/query_length fields */ void set_statement(Statement *stmt) override; inline void set_command(enum enum_server_command command) { DBUG_ASSERT(command != COM_SLEEP); m_command= command; #ifdef HAVE_PSI_THREAD_INTERFACE PSI_STATEMENT_CALL(set_thread_command)(m_command); #endif } /* As sleep needs a bit of special handling, we have a special case for it */ inline void mark_connection_idle() { proc_info= 0; m_command= COM_SLEEP; #ifdef HAVE_PSI_THREAD_INTERFACE PSI_STATEMENT_CALL(set_thread_command)(m_command); #endif } inline enum enum_server_command get_command() const { return m_command; } /** Assign a new value to thd->query and thd->query_id and mysys_var. Protected with LOCK_thd_data mutex. */ void set_query(char *query_arg, size_t query_length_arg, CHARSET_INFO *cs_arg) { set_query(CSET_STRING(query_arg, query_length_arg, cs_arg)); } void set_query(char *query_arg, size_t query_length_arg) /*Mutex protected*/ { set_query(CSET_STRING(query_arg, query_length_arg, charset())); } void set_query(const CSET_STRING &string_arg) { mysql_mutex_lock(&LOCK_thd_data); set_query_inner(string_arg); mysql_mutex_unlock(&LOCK_thd_data); PSI_CALL_set_thread_info(query(), query_length()); } void reset_query() /* Mutex protected */ { set_query(CSET_STRING()); } void set_query_and_id(char *query_arg, uint32 query_length_arg, CHARSET_INFO *cs, query_id_t new_query_id); void set_query_id(query_id_t new_query_id) { query_id= new_query_id; #ifdef WITH_WSREP if (WSREP_NNULL(this)) { set_wsrep_next_trx_id(query_id); WSREP_DEBUG("assigned new next trx id: %" PRIu64, wsrep_next_trx_id()); } #endif /* WITH_WSREP */ } void set_open_tables(TABLE *open_tables_arg) { mysql_mutex_lock(&LOCK_thd_data); open_tables= open_tables_arg; mysql_mutex_unlock(&LOCK_thd_data); } void set_mysys_var(struct st_my_thread_var *new_mysys_var); void enter_locked_tables_mode(enum_locked_tables_mode mode_arg) { DBUG_ASSERT(locked_tables_mode == LTM_NONE); if (mode_arg == LTM_LOCK_TABLES) { /* When entering LOCK TABLES mode we should set explicit duration for all metadata locks acquired so far in order to avoid releasing them till UNLOCK TABLES statement. We don't do this when entering prelocked mode since sub-statements don't release metadata locks and restoring status-quo after leaving prelocking mode gets complicated. */ mdl_context.set_explicit_duration_for_all_locks(); } locked_tables_mode= mode_arg; } void leave_locked_tables_mode(); /* Relesae transactional locks if there are no active transactions */ void release_transactional_locks() { if (!in_active_multi_stmt_transaction()) mdl_context.release_transactional_locks(this); } int decide_logging_format(TABLE_LIST *tables); /* In Some cases when decide_logging_format is called it does not have all information to decide the logging format. So that cases we call decide_logging_format_2 at later stages in execution. One example would be binlog format for insert on duplicate key (IODKU) but column with unique key is not inserted. We do not have inserted columns info when we call decide_logging_format so on later stage we call reconsider_logging_format_for_iodup() */ void reconsider_logging_format_for_iodup(TABLE *table); enum need_invoker { INVOKER_NONE=0, INVOKER_USER, INVOKER_ROLE}; void binlog_invoker(bool role) { m_binlog_invoker= role ? INVOKER_ROLE : INVOKER_USER; } enum need_invoker need_binlog_invoker() { return m_binlog_invoker; } void get_definer(LEX_USER *definer, bool role); void set_invoker(const LEX_CSTRING *user, const LEX_CSTRING *host) { invoker.user= *user; invoker.host= *host; } LEX_CSTRING get_invoker_user() { return invoker.user; } LEX_CSTRING get_invoker_host() { return invoker.host; } bool has_invoker() { return invoker.user.length > 0; } void print_aborted_warning(uint threshold, const char *reason) { if (global_system_variables.log_warnings > threshold) { char real_ip_str[64]; real_ip_str[0]= 0; /* For proxied connections, add the real IP to the warning message */ if (net.using_proxy_protocol && net.vio) { if(net.vio->localhost) snprintf(real_ip_str, sizeof(real_ip_str), " real ip: 'localhost'"); else { char buf[INET6_ADDRSTRLEN]; if (!vio_getnameinfo((sockaddr *)&(net.vio->remote), buf, sizeof(buf),NULL, 0, NI_NUMERICHOST)) { snprintf(real_ip_str, sizeof(real_ip_str), " real ip: '%s'",buf); } } } Security_context *sctx= &main_security_ctx; sql_print_warning(ER_THD(this, ER_NEW_ABORTING_CONNECTION), thread_id, (db.str ? db.str : "unconnected"), sctx->user ? sctx->user : "unauthenticated", sctx->host_or_ip, real_ip_str, reason); } } public: void clear_wakeup_ready() { wakeup_ready= false; } /* Sleep waiting for others to wake us up with signal_wakeup_ready(). Must call clear_wakeup_ready() before waiting. */ void wait_for_wakeup_ready(); /* Wake this thread up from wait_for_wakeup_ready(). */ void signal_wakeup_ready(); void add_status_to_global() { DBUG_ASSERT(status_in_global == 0); mysql_mutex_lock(&LOCK_status); add_to_status(&global_status_var, &status_var); /* Mark that this THD status has already been added in global status */ status_var.global_memory_used= 0; status_in_global= 1; mysql_mutex_unlock(&LOCK_status); } wait_for_commit *wait_for_commit_ptr; int wait_for_prior_commit(bool allow_kill=true) { if (wait_for_commit_ptr) return wait_for_commit_ptr->wait_for_prior_commit(this, allow_kill); return 0; } void wakeup_subsequent_commits(int wakeup_error) { if (wait_for_commit_ptr) wait_for_commit_ptr->wakeup_subsequent_commits(wakeup_error); } wait_for_commit *suspend_subsequent_commits() { wait_for_commit *suspended= wait_for_commit_ptr; wait_for_commit_ptr= NULL; return suspended; } void resume_subsequent_commits(wait_for_commit *suspended) { DBUG_ASSERT(!wait_for_commit_ptr); wait_for_commit_ptr= suspended; } void mark_transaction_to_rollback(bool all); bool internal_transaction() { return transaction != &default_transaction; } private: /** The current internal error handler for this thread, or NULL. */ Internal_error_handler *m_internal_handler; /** The lex to hold the parsed tree of conventional (non-prepared) queries. Whereas for prepared and stored procedure statements we use an own lex instance for each new query, for conventional statements we reuse the same lex. (@see mysql_parse for details). */ LEX main_lex; /** This memory root is used for two purposes: - for conventional queries, to allocate structures stored in main_lex during parsing, and allocate runtime data (execution plan, etc.) during execution. - for prepared queries, only to allocate runtime data. The parsed tree itself is reused between executions and thus is stored elsewhere. */ MEM_ROOT main_mem_root; Diagnostics_area main_da; Diagnostics_area *m_stmt_da; /** It will be set if CURRENT_USER() or CURRENT_ROLE() is called in account management statements or default definer is set in CREATE/ALTER SP, SF, Event, TRIGGER or VIEW statements. Current user or role will be binlogged into Query_log_event if m_binlog_invoker is not NONE; It will be stored into invoker_host and invoker_user by SQL thread. */ enum need_invoker m_binlog_invoker; /** It points to the invoker in the Query_log_event. SQL thread use it as the default definer in CREATE/ALTER SP, SF, Event, TRIGGER or VIEW statements or current user in account management statements if it is not NULL. */ AUTHID invoker; public: Session_tracker session_tracker; /* Flag, mutex and condition for a thread to wait for a signal from another thread. Currently used to wait for group commit to complete, and COND_wakeup_ready is used for threads to wait on semi-sync ACKs (though is protected by Repl_semi_sync_master::LOCK_binlog). Note the following relationships between these two use-cases when using rpl_semi_sync_master_wait_point=AFTER_SYNC during group commit: 1) Non-leader threads use COND_wakeup_ready to wait for the leader thread to complete binlog commit. 2) The leader thread uses COND_wakeup_ready to await ACKs from the replica before signalling the non-leader threads to wake up. With wait_point=AFTER_COMMIT, there is no overlap as binlogging has finished, so COND_wakeup_ready is safe to re-use. */ bool wakeup_ready; mysql_mutex_t LOCK_wakeup_ready; mysql_cond_t COND_wakeup_ready; /* The GTID assigned to the last commit. If no GTID was assigned to any commit so far, this is indicated by last_commit_gtid.seq_no == 0. */ private: rpl_gtid m_last_commit_gtid; public: rpl_gtid get_last_commit_gtid() { return m_last_commit_gtid; } void set_last_commit_gtid(rpl_gtid >id); LF_PINS *tdc_hash_pins; LF_PINS *xid_hash_pins; bool fix_xid_hash_pins(); const XID *get_xid() const { #ifdef WITH_WSREP if (!wsrep_xid.is_null()) return &wsrep_xid; #endif /* WITH_WSREP */ return (transaction->xid_state.is_explicit_XA() ? transaction->xid_state.get_xid() : &transaction->implicit_xid); } /* Members related to temporary tables. */ public: /* Opened table states. */ enum Temporary_table_state { TMP_TABLE_IN_USE, TMP_TABLE_NOT_IN_USE, TMP_TABLE_ANY }; bool has_thd_temporary_tables(); bool has_temporary_tables(); TABLE *create_and_open_tmp_table(LEX_CUSTRING *frm, const char *path, const char *db, const char *table_name, bool open_internal_tables); TABLE *find_temporary_table(const char *db, const char *table_name, Temporary_table_state state= TMP_TABLE_IN_USE); TABLE *find_temporary_table(const TABLE_LIST *tl, Temporary_table_state state= TMP_TABLE_IN_USE); TMP_TABLE_SHARE *find_tmp_table_share_w_base_key(const char *key, uint key_length); TMP_TABLE_SHARE *find_tmp_table_share(const char *db, const char *table_name); TMP_TABLE_SHARE *find_tmp_table_share(const TABLE_LIST *tl); TMP_TABLE_SHARE *find_tmp_table_share(const char *key, size_t key_length); bool open_temporary_table(TABLE_LIST *tl); bool open_temporary_tables(TABLE_LIST *tl); bool close_temporary_tables(); bool rename_temporary_table(TABLE *table, const LEX_CSTRING *db, const LEX_CSTRING *table_name); bool drop_temporary_table(TABLE *table, bool *is_trans, bool delete_table); bool rm_temporary_table(handlerton *hton, const char *path); void mark_tmp_tables_as_free_for_reuse(); void mark_tmp_table_as_free_for_reuse(TABLE *table); TMP_TABLE_SHARE* save_tmp_table_share(TABLE *table); void restore_tmp_table_share(TMP_TABLE_SHARE *share); void close_unused_temporary_table_instances(const TABLE_LIST *tl); private: /* Whether a lock has been acquired? */ bool m_tmp_tables_locked; uint create_tmp_table_def_key(char *key, const char *db, const char *table_name); TMP_TABLE_SHARE *create_temporary_table(LEX_CUSTRING *frm, const char *path, const char *db, const char *table_name); TABLE *find_temporary_table(const char *key, uint key_length, Temporary_table_state state); TABLE *open_temporary_table(TMP_TABLE_SHARE *share, const char *alias); bool find_and_use_tmp_table(const TABLE_LIST *tl, TABLE **out_table); bool use_temporary_table(TABLE *table, TABLE **out_table); void close_temporary_table(TABLE *table); bool log_events_and_free_tmp_shares(); bool free_tmp_table_share(TMP_TABLE_SHARE *share, bool delete_table); void free_temporary_table(TABLE *table); bool lock_temporary_tables(); void unlock_temporary_tables(); inline uint tmpkeyval(TMP_TABLE_SHARE *share) { return uint4korr(share->table_cache_key.str + share->table_cache_key.length - 4); } inline TMP_TABLE_SHARE *tmp_table_share(TABLE *table) { DBUG_ASSERT(table->s->tmp_table); return static_cast(table->s); } public: thd_async_state async_state; #ifdef HAVE_REPLICATION /* If we do a purge of binary logs, log index info of the threads that are currently reading it needs to be adjusted. To do that each thread that is using LOG_INFO needs to adjust the pointer to it */ LOG_INFO *current_linfo; Slave_info *slave_info; void set_current_linfo(LOG_INFO *linfo); void reset_current_linfo() { set_current_linfo(0); } int register_slave(uchar *packet, size_t packet_length); void unregister_slave(); bool is_binlog_dump_thread(); #endif inline ulong wsrep_binlog_format(ulong binlog_format) const { #ifdef WITH_WSREP // During CTAS we force ROW format if (wsrep_ctas) return BINLOG_FORMAT_ROW; else return ((wsrep_forced_binlog_format != BINLOG_FORMAT_UNSPEC) ? wsrep_forced_binlog_format : binlog_format); #else return (binlog_format); #endif } #ifdef WITH_WSREP bool wsrep_applier; /* dedicated slave applier thread */ bool wsrep_applier_closing; /* applier marked to close */ bool wsrep_client_thread; /* to identify client threads*/ query_id_t wsrep_last_query_id; XID wsrep_xid; /** This flag denotes that record locking should be skipped during INSERT, gap locking during SELECT, and write-write conflicts due to innodb snapshot isolation during DELETE. Only used by the streaming replication thread that only modifies the mysql.wsrep_streaming_log table. */ my_bool wsrep_skip_locking; mysql_cond_t COND_wsrep_thd; // changed from wsrep_seqno_t to wsrep_trx_meta_t in wsrep API rev 75 uint32 wsrep_rand; rpl_group_info *wsrep_rgi; bool wsrep_converted_lock_session; char wsrep_info[128]; /* string for dynamic proc info */ ulong wsrep_retry_counter; // of autocommit bool wsrep_PA_safe; char* wsrep_retry_query; size_t wsrep_retry_query_len; enum enum_server_command wsrep_retry_command; enum wsrep_consistency_check_mode wsrep_consistency_check; std::vector wsrep_status_vars; int wsrep_mysql_replicated; const char* wsrep_TOI_pre_query; /* a query to apply before the actual TOI query */ size_t wsrep_TOI_pre_query_len; wsrep_po_handle_t wsrep_po_handle; size_t wsrep_po_cnt; void *wsrep_apply_format; uchar* wsrep_rbr_buf; wsrep_gtid_t wsrep_sync_wait_gtid; uint64 wsrep_last_written_gtid_seqno; uint64 wsrep_current_gtid_seqno; ulong wsrep_affected_rows; bool wsrep_has_ignored_error; /* true if wsrep_on was ON in last wsrep_on_update */ bool wsrep_was_on; /* When enabled, do not replicate/binlog updates from the current table that's being processed. At the moment, it is used to keep mysql.gtid_slave_pos table updates from being replicated to other nodes via galera replication. */ bool wsrep_ignore_table; /* thread who has started kill for this THD protected by LOCK_thd_data*/ my_thread_id wsrep_aborter; /* Kill signal used, if thread was killed by manual KILL. Protected by LOCK_thd_kill. */ std::atomic wsrep_abort_by_kill; /* */ struct err_info* wsrep_abort_by_kill_err; #ifndef DBUG_OFF int wsrep_killed_state; #endif /* DBUG_OFF */ /* true if BF abort is observed in do_command() right after reading client's packet, and if the client has sent PS execute command. */ bool wsrep_delayed_BF_abort; // true if this transaction is CREATE TABLE AS SELECT (CTAS) bool wsrep_ctas; /* Transaction id: * m_wsrep_next_trx_id is assigned on the first query after wsrep_next_trx_id() return WSREP_UNDEFINED_TRX_ID * Each storage engine must assign value of wsrep_next_trx_id() when the transaction starts. * Effective transaction id is returned via wsrep_trx_id() */ /* Return effective transaction id */ wsrep_trx_id_t wsrep_trx_id() const { return m_wsrep_client_state.transaction().id().get(); } /* Set next trx id */ void set_wsrep_next_trx_id(query_id_t query_id) { m_wsrep_next_trx_id = (wsrep_trx_id_t) query_id; } /* Return next trx id */ wsrep_trx_id_t wsrep_next_trx_id() const { return m_wsrep_next_trx_id; } /* If node is async slave and have parallel execution, wait for prior commits. */ bool wsrep_parallel_slave_wait_for_prior_commit(); private: wsrep_trx_id_t m_wsrep_next_trx_id; /* cast from query_id_t */ /* wsrep-lib */ Wsrep_mutex m_wsrep_mutex; Wsrep_condition_variable m_wsrep_cond; Wsrep_client_service m_wsrep_client_service; Wsrep_client_state m_wsrep_client_state; public: Wsrep_client_state& wsrep_cs() { return m_wsrep_client_state; } const Wsrep_client_state& wsrep_cs() const { return m_wsrep_client_state; } const wsrep::transaction& wsrep_trx() const { return m_wsrep_client_state.transaction(); } const wsrep::streaming_context& wsrep_sr() const { return m_wsrep_client_state.transaction().streaming_context(); } /* Pointer to applier service for streaming THDs. This is needed to be able to delete applier service object in case of background rollback. */ Wsrep_applier_service* wsrep_applier_service; /* wait_for_commit struct for binlog group commit */ wait_for_commit wsrep_wfc; #endif /* WITH_WSREP */ /* Handling of timeouts for commands */ thr_timer_t query_timer; public: void set_query_timer() { #ifndef EMBEDDED_LIBRARY /* Don't start a query timer if - If timeouts are not set - if we are in a stored procedure or sub statement - If this is a slave thread - If we already have set a timeout (happens when running prepared statements that calls mysql_execute_command()) */ if (!variables.max_statement_time || spcont || in_sub_stmt || slave_thread || query_timer.expired == 0) return; thr_timer_settime(&query_timer, variables.max_statement_time); #endif } void reset_query_timer() { #ifndef EMBEDDED_LIBRARY if (spcont || in_sub_stmt || slave_thread) return; if (!query_timer.expired) thr_timer_end(&query_timer); #endif } bool restore_set_statement_var() { return main_lex.restore_set_statement_var(); } /* Copy relevant `stmt` transaction flags to `all` transaction. */ void merge_unsafe_rollback_flags() { if (transaction->stmt.modified_non_trans_table) transaction->all.modified_non_trans_table= TRUE; transaction->all.m_unsafe_rollback_flags|= (transaction->stmt.m_unsafe_rollback_flags & (THD_TRANS::MODIFIED_NON_TRANS_TABLE | THD_TRANS::DID_WAIT | THD_TRANS::CREATED_TEMP_TABLE | THD_TRANS::DROPPED_TEMP_TABLE | THD_TRANS::DID_DDL | THD_TRANS::EXECUTED_TABLE_ADMIN_CMD)); } uint get_net_wait_timeout() { if (in_active_multi_stmt_transaction()) { if (transaction->all.is_trx_read_write()) { if (variables.idle_write_transaction_timeout > 0) return variables.idle_write_transaction_timeout; } else { if (variables.idle_readonly_transaction_timeout > 0) return variables.idle_readonly_transaction_timeout; } if (variables.idle_transaction_timeout > 0) return variables.idle_transaction_timeout; } return variables.net_wait_timeout; } /** Switch to a sublex, to parse a substatement or an expression. */ void set_local_lex(sp_lex_local *sublex) { DBUG_ASSERT(lex->sphead); lex= sublex; /* Reset part of parser state which needs this. */ m_parser_state->m_yacc.reset_before_substatement(); } /** Switch back from a sublex (currently pointed by this->lex) to the old lex. Sublex is merged to "oldlex" and this->lex is set to "oldlex". This method is called after parsing a substatement or an expression. set_local_lex() must be previously called. @param oldlex - The old lex which was active before set_local_lex(). @returns - false on success, true on error (failed to merge LEX's). See also sp_head::merge_lex(). */ bool restore_from_local_lex_to_old_lex(LEX *oldlex); Item *sp_fix_func_item(Item **it_addr); Item *sp_prepare_func_item(Item **it_addr, uint cols= 1); bool sp_eval_expr(Field *result_field, Item **expr_item_ptr); bool sql_parser(LEX *old_lex, LEX *lex, char *str, uint str_len, bool stmt_prepare_mode); myf get_utf8_flag() const { return (variables.old_behavior & OLD_MODE_UTF8_IS_UTF8MB3 ? MY_UTF8_IS_UTF8MB3 : 0); } /** Save current lex to the output parameter and reset it to point to main_lex. This method is called from mysql_client_binlog_statement() to temporary @param[out] backup_lex original value of current lex */ void backup_and_reset_current_lex(LEX **backup_lex) { *backup_lex= lex; lex= &main_lex; } /** Restore current lex to its original value it had before calling the method backup_and_reset_current_lex(). @param backup_lex original value of current lex */ void restore_current_lex(LEX *backup_lex) { lex= backup_lex; } bool should_collect_handler_stats() { /* We update handler_stats.active to ensure that we have the same value across the whole statement. This function is only called from TABLE::init() so the value will be the same for the whole statement. */ handler_stats.active= ((variables.log_slow_verbosity & LOG_SLOW_VERBOSITY_ENGINE) || lex->analyze_stmt); return handler_stats.active; } /* Return true if we should create a note when an unusable key is found */ bool give_notes_for_unusable_keys() { return ((variables.note_verbosity & (NOTE_VERBOSITY_UNUSABLE_KEYS)) || (lex->describe && // Is EXPLAIN (variables.note_verbosity & NOTE_VERBOSITY_EXPLAIN))); } }; /* Start a new independent transaction for the THD. The old one is stored in this object and restored when calling restore_old_transaction() or when the object is freed */ class start_new_trans { /* container for handler's private per-connection data */ Ha_data old_ha_data[MAX_HA]; struct THD::st_transactions *old_transaction, new_transaction; Open_tables_backup open_tables_state_backup; MDL_savepoint mdl_savepoint; PSI_transaction_locker *m_transaction_psi; THD *org_thd; uint in_sub_stmt; uint server_status; my_bool wsrep_on; public: start_new_trans(THD *thd); ~start_new_trans() { destroy(); } void destroy() { if (org_thd) // Safety restore_old_transaction(); new_transaction.free(); } void restore_old_transaction(); }; /** A short cut for thd->get_stmt_da()->set_ok_status(). */ inline void my_ok(THD *thd, ulonglong affected_rows_arg= 0, ulonglong id= 0, const char *message= NULL) { thd->set_row_count_func(affected_rows_arg); thd->set_affected_rows(affected_rows_arg); thd->get_stmt_da()->set_ok_status(affected_rows_arg, id, message); } /** A short cut for thd->get_stmt_da()->set_eof_status(). */ inline void my_eof(THD *thd) { thd->set_row_count_func(-1); thd->get_stmt_da()->set_eof_status(thd); TRANSACT_TRACKER(add_trx_state(thd, TX_RESULT_SET)); } #define tmp_disable_binlog(A) \ {ulonglong tmp_disable_binlog__save_options= (A)->variables.option_bits; \ (A)->variables.option_bits&= ~OPTION_BIN_LOG; \ (A)->variables.option_bits|= OPTION_BIN_TMP_LOG_OFF; #define reenable_binlog(A) \ (A)->variables.option_bits= tmp_disable_binlog__save_options; } inline date_conv_mode_t sql_mode_for_dates(THD *thd) { static_assert((ulonglong(date_conv_mode_t::KNOWN_MODES) & ulonglong(time_round_mode_t::KNOWN_MODES)) == 0, "date_conv_mode_t and time_round_mode_t must use different " "bit values"); static_assert(MODE_NO_ZERO_DATE == date_mode_t::NO_ZERO_DATE && MODE_NO_ZERO_IN_DATE == date_mode_t::NO_ZERO_IN_DATE && MODE_INVALID_DATES == date_mode_t::INVALID_DATES, "sql_mode_t and date_mode_t values must be equal"); return date_conv_mode_t(thd->variables.sql_mode & (MODE_NO_ZERO_DATE | MODE_NO_ZERO_IN_DATE | MODE_INVALID_DATES)); } /* Used to hold information about file and file structure in exchange via non-DB file (...INTO OUTFILE..., ...LOAD DATA...) XXX: We never call destructor for objects of this class. */ class sql_exchange :public Sql_alloc { public: enum enum_filetype filetype; /* load XML, Added by Arnold & Erik */ const char *file_name; String *field_term,*enclosed,*line_term,*line_start,*escaped; bool opt_enclosed; bool dumpfile; ulong skip_lines; CHARSET_INFO *cs; sql_exchange(const char *name, bool dumpfile_flag, enum_filetype filetype_arg= FILETYPE_CSV); bool escaped_given(void) const; }; /* This is used to get result from a select */ class JOIN; /* Pure interface for sending tabular data */ class select_result_sink: public Sql_alloc { public: THD *thd; select_result_sink(THD *thd_arg): thd(thd_arg) {} inline int send_data_with_check(List &items, SELECT_LEX_UNIT *u, ha_rows sent) { if (u->lim.check_offset(sent)) return 0; if (u->thd->killed == ABORT_QUERY) return 0; return send_data(items); } /* send_data returns 0 on ok, 1 on error and -1 if data was ignored, for example for a duplicate row entry written to a temp table. */ virtual int send_data(List &items)=0; virtual ~select_result_sink() = default; // Used in cursors to initialize and reset void reinit(THD *thd_arg) { thd= thd_arg; } }; class select_result_interceptor; /* Interface for sending tabular data, together with some other stuff: - Primary purpose seems to be seding typed tabular data: = the DDL is sent with send_fields() = the rows are sent with send_data() Besides that, - there seems to be an assumption that the sent data is a result of SELECT_LEX_UNIT *unit, - nest_level is used by SQL parser */ class select_result :public select_result_sink { protected: /* All descendant classes have their send_data() skip the first unit->offset_limit_cnt rows sent. Select_materialize also uses unit->get_column_types(). */ SELECT_LEX_UNIT *unit; /* Something used only by the parser: */ public: ha_rows est_records; /* estimated number of records in the result */ select_result(THD *thd_arg): select_result_sink(thd_arg), est_records(0) {} void set_unit(SELECT_LEX_UNIT *unit_arg) { unit= unit_arg; } virtual ~select_result() = default; /** Change wrapped select_result. Replace the wrapped result object with new_result and call prepare() and prepare2() on new_result. This base class implementation doesn't wrap other select_results. @param new_result The new result object to wrap around @retval false Success @retval true Error */ virtual bool change_result(select_result *new_result) { return false; } virtual int prepare(List &list, SELECT_LEX_UNIT *u) { unit= u; return 0; } virtual int prepare2(JOIN *join) { return 0; } /* Because of peculiarities of prepared statements protocol we need to know number of columns in the result set (if there is a result set) apart from sending columns metadata. */ virtual uint field_count(List &fields) const { return fields.elements; } virtual bool send_result_set_metadata(List &list, uint flags)=0; virtual bool initialize_tables (JOIN *join) { return 0; } virtual bool send_eof()=0; /** Check if this query returns a result set and therefore is allowed in cursors and set an error message if it is not the case. @retval FALSE success @retval TRUE error, an error message is set */ virtual bool check_simple_select() const; virtual void abort_result_set() {} virtual void reset_for_next_ps_execution(); void set_thd(THD *thd_arg) { thd= thd_arg; } void reinit(THD *thd_arg) { select_result_sink::reinit(thd_arg); unit= NULL; } #ifdef EMBEDDED_LIBRARY virtual void begin_dataset() {} #else void begin_dataset() {} #endif virtual void update_used_tables() {} /* this method is called just before the first row of the table can be read */ virtual void prepare_to_read_rows() {} void remove_offset_limit() { unit->lim.remove_offset(); } /* This returns - NULL if the class sends output row to the client - this if the output is set elsewhere (a file, @variable, or table). */ virtual select_result_interceptor *result_interceptor()=0; /* This method is used to distinguish an normal SELECT from the cursor structure discovery for cursor%ROWTYPE routine variables. If this method returns "true", then a SELECT execution performs only all preparation stages, but does not fetch any rows. */ virtual bool view_structure_only() const { return false; } }; /* This is a select_result_sink which simply writes all data into a (temporary) table. Creation/deletion of the table is outside of the scope of the class It is aimed at capturing SHOW EXPLAIN output, so: - Unlike select_result class, we don't assume that the sent data is an output of a SELECT_LEX_UNIT (and so we don't apply "LIMIT x,y" from the unit) - We don't try to convert the target table to MyISAM */ class select_result_explain_buffer : public select_result_sink { public: select_result_explain_buffer(THD *thd_arg, TABLE *table_arg) : select_result_sink(thd_arg), dst_table(table_arg) {}; TABLE *dst_table; /* table to write into */ /* The following is called in the child thread: */ int send_data(List &items) override; }; /* This is a select_result_sink which stores the data in text form. It is only used to save EXPLAIN output. */ class select_result_text_buffer : public select_result_sink { public: select_result_text_buffer(THD *thd_arg): select_result_sink(thd_arg) {} int send_data(List &items) override; bool send_result_set_metadata(List &fields, uint flag); void save_to(String *res); private: int append_row(List &items, bool send_names); List rows; int n_columns; }; /* Base class for select_result descendands which intercept and transform result set rows. As the rows are not sent to the client, sending of result set metadata should be suppressed as well. */ class select_result_interceptor: public select_result { public: select_result_interceptor(THD *thd_arg): select_result(thd_arg), suppress_my_ok(false) { DBUG_ENTER("select_result_interceptor::select_result_interceptor"); DBUG_PRINT("enter", ("this %p", this)); DBUG_VOID_RETURN; } /* Remove gcc warning */ uint field_count(List &fields) const override { return 0; } bool send_result_set_metadata(List &fields, uint flag) override { return FALSE; } select_result_interceptor *result_interceptor() override { return this; } /* Instruct the object to not call my_ok(). Client output will be handled elsewhere. (this is used by ANALYZE $stmt feature). */ void disable_my_ok_calls() { suppress_my_ok= true; } void reinit(THD *thd_arg) { select_result::reinit(thd_arg); suppress_my_ok= false; } protected: bool suppress_my_ok; }; class sp_cursor_statistics { protected: ulonglong m_fetch_count; // Number of FETCH commands since last OPEN ulonglong m_row_count; // Number of successful FETCH since last OPEN bool m_found; // If last FETCH fetched a row public: sp_cursor_statistics() :m_fetch_count(0), m_row_count(0), m_found(false) { } bool found() const { return m_found; } ulonglong row_count() const { return m_row_count; } ulonglong fetch_count() const { return m_fetch_count; } void reset() { *this= sp_cursor_statistics(); } }; /* A mediator between stored procedures and server side cursors */ class sp_lex_keeper; class sp_cursor: public sp_cursor_statistics { private: /// An interceptor of cursor result set used to implement /// FETCH INTO . class Select_fetch_into_spvars: public select_result_interceptor { List *spvar_list; uint field_count; bool m_view_structure_only; bool send_data_to_variable_list(List &vars, List &items); public: Select_fetch_into_spvars(THD *thd_arg, bool view_structure_only) :select_result_interceptor(thd_arg), m_view_structure_only(view_structure_only) {} void reset(THD *thd_arg) { select_result_interceptor::reinit(thd_arg); spvar_list= NULL; field_count= 0; } uint get_field_count() { return field_count; } void set_spvar_list(List *vars) { spvar_list= vars; } bool send_eof() override { return FALSE; } int send_data(List &items) override; int prepare(List &list, SELECT_LEX_UNIT *u) override; bool view_structure_only() const override { return m_view_structure_only; } }; public: sp_cursor() :result(NULL, false), m_lex_keeper(NULL), server_side_cursor(NULL) { } sp_cursor(THD *thd_arg, sp_lex_keeper *lex_keeper, bool view_structure_only) :result(thd_arg, view_structure_only), m_lex_keeper(lex_keeper), server_side_cursor(NULL) {} virtual ~sp_cursor() { destroy(); } sp_lex_keeper *get_lex_keeper() { return m_lex_keeper; } int open(THD *thd); int close(THD *thd); my_bool is_open() { return MY_TEST(server_side_cursor); } int fetch(THD *, List *vars, bool error_on_no_data); bool export_structure(THD *thd, Row_definition_list *list); void reset(THD *thd_arg, sp_lex_keeper *lex_keeper) { sp_cursor_statistics::reset(); result.reinit(thd_arg); m_lex_keeper= lex_keeper; server_side_cursor= NULL; } private: Select_fetch_into_spvars result; sp_lex_keeper *m_lex_keeper; Server_side_cursor *server_side_cursor; void destroy(); }; class select_send :public select_result { /** True if we have sent result set metadata to the client. In this case the client always expects us to end the result set with an eof or error packet */ bool is_result_set_started; public: select_send(THD *thd_arg): select_result(thd_arg), is_result_set_started(FALSE) {} bool send_result_set_metadata(List &list, uint flags) override; int send_data(List &items) override; bool send_eof() override; bool check_simple_select() const override { return FALSE; } void abort_result_set() override; void reset_for_next_ps_execution() override; select_result_interceptor *result_interceptor() override { return NULL; } }; /* We need this class, because select_send::send_eof() will call ::my_eof. See also class Protocol_discard. */ class select_send_analyze : public select_send { bool send_result_set_metadata(List &list, uint flags) override { return 0; } bool send_eof() override { return 0; } void abort_result_set() override {} public: select_send_analyze(THD *thd_arg): select_send(thd_arg) {} }; class select_to_file :public select_result_interceptor { protected: sql_exchange *exchange; File file; IO_CACHE cache; ha_rows row_count; char path[FN_REFLEN]; public: select_to_file(THD *thd_arg, sql_exchange *ex): select_result_interceptor(thd_arg), exchange(ex), file(-1),row_count(0L) { path[0]=0; } ~select_to_file(); bool send_eof() override; void abort_result_set() override; void reset_for_next_ps_execution() override; bool free_recources(); }; #define ESCAPE_CHARS "ntrb0ZN" // keep synchronous with READ_INFO::unescape /* List of all possible characters of a numeric value text representation. */ #define NUMERIC_CHARS ".0123456789e+-" class select_export :public select_to_file { uint field_term_length; int field_sep_char,escape_char,line_sep_char; int field_term_char; // first char of FIELDS TERMINATED BY or MAX_INT /* The is_ambiguous_field_sep field is true if a value of the field_sep_char field is one of the 'n', 't', 'r' etc characters (see the READ_INFO::unescape method and the ESCAPE_CHARS constant value). */ bool is_ambiguous_field_sep; /* The is_ambiguous_field_term is true if field_sep_char contains the first char of the FIELDS TERMINATED BY (ENCLOSED BY is empty), and items can contain this character. */ bool is_ambiguous_field_term; /* The is_unsafe_field_sep field is true if a value of the field_sep_char field is one of the '0'..'9', '+', '-', '.' and 'e' characters (see the NUMERIC_CHARS constant value). */ bool is_unsafe_field_sep; bool fixed_row_size; CHARSET_INFO *write_cs; // output charset public: select_export(THD *thd_arg, sql_exchange *ex): select_to_file(thd_arg, ex) {} ~select_export(); int prepare(List &list, SELECT_LEX_UNIT *u) override; int send_data(List &items) override; }; class select_dump :public select_to_file { public: select_dump(THD *thd_arg, sql_exchange *ex): select_to_file(thd_arg, ex) {} int prepare(List &list, SELECT_LEX_UNIT *u) override; int send_data(List &items) override; }; class select_insert :public select_result_interceptor { public: select_result *sel_result; TABLE_LIST *table_list; TABLE *table; List *fields; ulonglong autoinc_value_of_last_inserted_row; // autogenerated or not COPY_INFO info; bool insert_into_view; select_insert(THD *thd_arg, TABLE_LIST *table_list_par, TABLE *table_par, List *fields_par, List *update_fields, List *update_values, enum_duplicates duplic, bool ignore, select_result *sel_ret_list); ~select_insert(); int prepare(List &list, SELECT_LEX_UNIT *u) override; int prepare2(JOIN *join) override; int send_data(List &items) override; virtual bool store_values(List &values); virtual bool can_rollback_data() { return 0; } bool prepare_eof(); bool send_ok_packet(); bool send_eof() override; void abort_result_set() override; /* not implemented: select_insert is never re-used in prepared statements */ void reset_for_next_ps_execution() override; }; class select_create: public select_insert { TABLE_LIST *create_table; Table_specification_st *create_info; TABLE_LIST *select_tables; Alter_info *alter_info; Field **field; /* lock data for tmp table */ MYSQL_LOCK *m_lock; /* m_lock or thd->extra_lock */ MYSQL_LOCK **m_plock; bool exit_done; TMP_TABLE_SHARE *saved_tmp_table_share; DDL_LOG_STATE ddl_log_state_create, ddl_log_state_rm; public: select_create(THD *thd_arg, TABLE_LIST *table_arg, Table_specification_st *create_info_par, Alter_info *alter_info_arg, List &select_fields,enum_duplicates duplic, bool ignore, TABLE_LIST *select_tables_arg): select_insert(thd_arg, table_arg, NULL, &select_fields, 0, 0, duplic, ignore, NULL), create_table(table_arg), create_info(create_info_par), select_tables(select_tables_arg), alter_info(alter_info_arg), m_plock(NULL), exit_done(0), saved_tmp_table_share(0) { bzero(&ddl_log_state_create, sizeof(ddl_log_state_create)); bzero(&ddl_log_state_rm, sizeof(ddl_log_state_rm)); } int prepare(List &list, SELECT_LEX_UNIT *u) override; int binlog_show_create_table(TABLE **tables, uint count); bool store_values(List &values) override; bool send_eof() override; void abort_result_set() override; bool can_rollback_data() override { return 1; } // Needed for access from local class MY_HOOKS in prepare(), since thd is proteted. const THD *get_thd(void) { return thd; } const HA_CREATE_INFO *get_create_info() { return create_info; }; int prepare2(JOIN *join) override { return 0; } private: TABLE *create_table_from_items(THD *thd, List *items, MYSQL_LOCK **lock, TABLEOP_HOOKS *hooks); }; #include #ifdef WITH_ARIA_STORAGE_ENGINE #include #else #undef USE_ARIA_FOR_TMP_TABLES #endif #ifdef USE_ARIA_FOR_TMP_TABLES #define TMP_ENGINE_COLUMNDEF MARIA_COLUMNDEF #define TMP_ENGINE_HTON maria_hton #define TMP_ENGINE_NAME "Aria" inline uint tmp_table_max_key_length() { return maria_max_key_length(); } inline uint tmp_table_max_key_parts() { return maria_max_key_segments(); } #else #define TMP_ENGINE_COLUMNDEF MI_COLUMNDEF #define TMP_ENGINE_HTON myisam_hton #define TMP_ENGINE_NAME "MyISAM" inline uint tmp_table_max_key_length() { return MI_MAX_KEY_LENGTH; } inline uint tmp_table_max_key_parts() { return MI_MAX_KEY_SEG; } #endif /* Param to create temporary tables when doing SELECT:s NOTE This structure is copied using memcpy as a part of JOIN. */ class TMP_TABLE_PARAM :public Sql_alloc { public: List copy_funcs; Copy_field *copy_field, *copy_field_end; uchar *group_buff; const char *tmp_name; Item **items_to_copy; /* Fields in tmp table */ TMP_ENGINE_COLUMNDEF *recinfo, *start_recinfo; KEY *keyinfo; ha_rows end_write_records; /** Number of normal fields in the query, including those referred to from aggregate functions. Hence, "SELECT `field1`, SUM(`field2`) from t1" sets this counter to 2. @see count_field_types */ uint field_count; /** Number of fields in the query that have functions. Includes both aggregate functions (e.g., SUM) and non-aggregates (e.g., RAND). Also counts functions referred to from aggregate functions, i.e., "SELECT SUM(RAND())" sets this counter to 2. @see count_field_types */ uint func_count; /** Number of fields in the query that have aggregate functions. Note that the optimizer may choose to optimize away these fields by replacing them with constants, in which case sum_func_count will need to be updated. @see opt_sum_query, count_field_types */ uint sum_func_count; uint copy_func_count; // Allocated copy fields uint hidden_field_count; uint group_parts,group_length,group_null_parts; /* If we're doing a GROUP BY operation, shows which one is used: true TemporaryTableWithPartialSums algorithm (see end_update()). false OrderedGroupBy algorithm (see end_write_group()). */ uint quick_group; /** Enabled when we have atleast one outer_sum_func. Needed when used along with distinct. @see create_tmp_table */ bool using_outer_summary_function; CHARSET_INFO *table_charset; bool schema_table; /* TRUE if the temp table is created for subquery materialization. */ bool materialized_subquery; /* TRUE if all columns of the table are guaranteed to be non-nullable */ bool force_not_null_cols; /* True if GROUP BY and its aggregate functions are already computed by a table access method (e.g. by loose index scan). In this case query execution should not perform aggregation and should treat aggregate functions as normal functions. */ bool precomputed_group_by; bool group_concat; bool force_copy_fields; /* If TRUE, create_tmp_field called from create_tmp_table will convert all BIT fields to 64-bit longs. This is a workaround the limitation that MEMORY tables cannot index BIT columns. */ bool bit_fields_as_long; /* Whether to create or postpone actual creation of this temporary table. TRUE <=> create_tmp_table will create only the TABLE structure. */ bool skip_create_table; TMP_TABLE_PARAM() :copy_field(0), group_parts(0), group_length(0), group_null_parts(0), using_outer_summary_function(0), schema_table(0), materialized_subquery(0), force_not_null_cols(0), precomputed_group_by(0), group_concat(0), force_copy_fields(0), bit_fields_as_long(0), skip_create_table(0) { init(); } ~TMP_TABLE_PARAM() { cleanup(); } void init(void); inline void cleanup(void) { if (copy_field) /* Fix for Intel compiler */ { delete [] copy_field; copy_field= NULL; copy_field_end= NULL; } } }; class select_unit :public select_result_interceptor { protected: uint curr_step, prev_step, curr_sel; enum sub_select_type step; public: TMP_TABLE_PARAM tmp_table_param; /* Number of additional (hidden) field of the used temporary table */ int addon_cnt; int write_err; /* Error code from the last send_data->ha_write_row call. */ TABLE *table; select_unit(THD *thd_arg): select_result_interceptor(thd_arg), addon_cnt(0), table(0) { init(); tmp_table_param.init(); } int prepare(List &list, SELECT_LEX_UNIT *u) override; /** Do prepare() and prepare2() if they have been postponed until column type information is computed (used by select_union_direct). @param types Column types @return false on success, true on failure */ virtual bool postponed_prepare(List &types) { return false; } int send_data(List &items) override; int write_record(); int update_counter(Field *counter, longlong value); int delete_record(); bool send_eof() override; virtual bool flush(); void reset_for_next_ps_execution() override; virtual bool create_result_table(THD *thd, List *column_types, bool is_distinct, ulonglong options, const LEX_CSTRING *alias, bool bit_fields_as_long, bool create_table, bool keep_row_order, uint hidden); TMP_TABLE_PARAM *get_tmp_table_param() { return &tmp_table_param; } void init() { curr_step= prev_step= 0; curr_sel= UINT_MAX; step= UNION_TYPE; write_err= 0; } virtual void change_select(); virtual bool force_enable_index_if_needed() { return false; } }; /** @class select_unit_ext The class used when processing rows produced by operands of query expressions containing INTERSECT ALL and/or EXCEPT all operations. One or two extra fields of the temporary to store the rows of the partial and final result can be employed. Both of them contain counters. The second additional field is used only when the processed query expression contains INTERSECT ALL. Consider how these extra fields are used. Let table t1 (f char(8)) table t2 (f char(8)) table t3 (f char(8)) contain the following sets: ("b"),("a"),("d"),("c"),("b"),("a"),("c"),("a") ("c"),("b"),("c"),("c"),("a"),("b"),("g") ("c"),("a"),("b"),("d"),("b"),("e") - Let's demonstrate how the the set operation INTERSECT ALL is proceesed for the query SELECT f FROM t1 INTERSECT ALL SELECT f FROM t2 When send_data() is called for the rows of the first operand we put the processed record into the temporary table if there was no such record setting dup_cnt field to 1 and add_cnt field to 0 and increment the counter in the dup_cnt field by one otherwise. We get |add_cnt|dup_cnt| f | |0 |2 |b | |0 |3 |a | |0 |1 |d | |0 |2 |c | The call of send_eof() for the first operand swaps the values stored in dup_cnt and add_cnt. After this, we'll see the following rows in the temporary table |add_cnt|dup_cnt| f | |2 |0 |b | |3 |0 |a | |1 |0 |d | |2 |0 |c | When send_data() is called for the rows of the second operand we increment the counter in dup_cnt if the processed row is found in the table and do nothing otherwise. As a result we get |add_cnt|dup_cnt| f | |2 |2 |b | |3 |1 |a | |1 |0 |d | |2 |3 |c | At the call of send_eof() for the second operand first we disable index. Then for each record, the minimum of counters from dup_cnt and add_cnt m is taken. If m == 0 then the record is deleted. Otherwise record is replaced with m copies of it. Yet the counter in this copies are set to 1 for dup_cnt and to 0 for add_cnt |add_cnt|dup_cnt| f | |0 |1 |b | |0 |1 |b | |0 |1 |a | |0 |1 |c | |0 |1 |c | - Let's demonstrate how the the set operation EXCEPT ALL is proceesed for the query SELECT f FROM t1 EXCEPT ALL SELECT f FROM t3 Only one additional counter field dup_cnt is used for EXCEPT ALL. After the first operand has been processed we have in the temporary table |dup_cnt| f | |2 |b | |3 |a | |1 |d | |2 |c | When send_data() is called for the rows of the second operand we decrement the counter in dup_cnt if the processed row is found in the table and do nothing otherwise. If the counter becomes 0 we delete the record |dup_cnt| f | |2 |a | |1 |c | Finally at the call of send_eof() for the second operand we disable index unfold rows adding duplicates |dup_cnt| f | |1 |a | |1 |a | |1 |c | */ class select_unit_ext :public select_unit { public: select_unit_ext(THD *thd_arg): select_unit(thd_arg), increment(0), is_index_enabled(TRUE), curr_op_type(UNSPECIFIED) { }; int send_data(List &items) override; void change_select() override; int unfold_record(ha_rows cnt); bool send_eof() override; bool force_enable_index_if_needed() override { is_index_enabled= true; return true; } bool disable_index_if_needed(SELECT_LEX *curr_sl); /* How to change increment/decrement the counter in duplicate_cnt field when processing a record produced by the current operand in send_data(). The value can be 1 or -1 */ int increment; /* TRUE <=> the index of the result temporary table is enabled */ bool is_index_enabled; /* The type of the set operation currently executed */ enum set_op_type curr_op_type; /* Points to the extra field of the temporary table where duplicate counters are stored */ Field *duplicate_cnt; /* Points to the extra field of the temporary table where additional counters used only for INTERSECT ALL operations are stored */ Field *additional_cnt; }; class select_union_recursive :public select_unit { public: /* The temporary table with the new records generated by one iterative step */ TABLE *incr_table; /* The TMP_TABLE_PARAM structure used to create incr_table */ TMP_TABLE_PARAM incr_table_param; /* One of tables from the list rec_tables (determined dynamically) */ TABLE *first_rec_table_to_update; /* The list of all recursive table references to the CTE for whose specification this select_union_recursive was created */ List rec_table_refs; /* The count of how many times reset_for_next_ps_execution() was called with cleaned==false for the unit specifying the recursive CTE for which this object was created or for the unit specifying a CTE that mutually recursive with this CTE. */ uint cleanup_count; long row_counter; select_union_recursive(THD *thd_arg): select_unit(thd_arg), incr_table(0), first_rec_table_to_update(0), cleanup_count(0), row_counter(0) { incr_table_param.init(); }; int send_data(List &items) override; bool create_result_table(THD *thd, List *column_types, bool is_distinct, ulonglong options, const LEX_CSTRING *alias, bool bit_fields_as_long, bool create_table, bool keep_row_order, uint hidden) override; void reset_for_next_ps_execution() override; }; /** UNION result that is passed directly to the receiving select_result without filling a temporary table. Function calls are forwarded to the wrapped select_result, but some functions are expected to be called only once for each query, so they are only executed for the first SELECT in the union (execept for send_eof(), which is executed only for the last SELECT). This select_result is used when a UNION is not DISTINCT and doesn't have a global ORDER BY clause. @see st_select_lex_unit::prepare(). */ class select_union_direct :public select_unit { private: /* Result object that receives all rows */ select_result *result; /* The last SELECT_LEX of the union */ SELECT_LEX *last_select_lex; /* Wrapped result has received metadata */ bool done_send_result_set_metadata; /* Wrapped result has initialized tables */ bool done_initialize_tables; /* Accumulated limit_found_rows */ ulonglong limit_found_rows; /* Number of rows offset */ ha_rows offset; /* Number of rows limit + offset, @see select_union_direct::send_data() */ ha_rows limit; public: /* Number of rows in the union */ ha_rows send_records; select_union_direct(THD *thd_arg, select_result *result_arg, SELECT_LEX *last_select_lex_arg): select_unit(thd_arg), result(result_arg), last_select_lex(last_select_lex_arg), done_send_result_set_metadata(false), done_initialize_tables(false), limit_found_rows(0) { send_records= 0; } bool change_result(select_result *new_result) override; uint field_count(List &fields) const override { // Only called for top-level select_results, usually select_send DBUG_ASSERT(false); /* purecov: inspected */ return 0; /* purecov: inspected */ } bool postponed_prepare(List &types) override; bool send_result_set_metadata(List &list, uint flags) override; int send_data(List &items) override; bool initialize_tables (JOIN *join) override; bool send_eof() override; bool flush() override { return false; } bool check_simple_select() const override { /* Only called for top-level select_results, usually select_send */ DBUG_ASSERT(false); /* purecov: inspected */ return false; /* purecov: inspected */ } void abort_result_set() override { result->abort_result_set(); /* purecov: inspected */ } void reset_for_next_ps_execution() override { send_records= 0; } void set_thd(THD *thd_arg) { /* Only called for top-level select_results, usually select_send, and for the results of subquery engines (select__subselect). */ DBUG_ASSERT(false); /* purecov: inspected */ } void remove_offset_limit() { // EXPLAIN should never output to a select_union_direct DBUG_ASSERT(false); /* purecov: inspected */ } #ifdef EMBEDDED_LIBRARY void begin_dataset() override #else void begin_dataset() #endif { // Only called for sp_cursor::Select_fetch_into_spvars DBUG_ASSERT(false); /* purecov: inspected */ } }; /* Base subselect interface class */ class select_subselect :public select_result_interceptor { protected: Item_subselect *item; public: select_subselect(THD *thd_arg, Item_subselect *item_arg): select_result_interceptor(thd_arg), item(item_arg) {} int send_data(List &items) override=0; bool send_eof() override { return 0; }; }; /* Single value subselect interface class */ class select_singlerow_subselect :public select_subselect { public: select_singlerow_subselect(THD *thd_arg, Item_subselect *item_arg): select_subselect(thd_arg, item_arg) {} int send_data(List &items) override; }; /* This class specializes select_union to collect statistics about the data stored in the temp table. Currently the class collects statistcs about NULLs. */ class select_materialize_with_stats : public select_unit { protected: class Column_statistics { public: /* Count of NULLs per column. */ ha_rows null_count; /* The row number that contains the first NULL in a column. */ ha_rows min_null_row; /* The row number that contains the last NULL in a column. */ ha_rows max_null_row; }; /* Array of statistics data per column. */ Column_statistics* col_stat; /* The number of columns in the biggest sub-row that consists of only NULL values. */ uint max_nulls_in_row; /* Count of rows writtent to the temp table. This is redundant as it is already stored in handler::stats.records, however that one is relatively expensive to compute (given we need that for evry row). */ ha_rows count_rows; protected: void reset(); public: select_materialize_with_stats(THD *thd_arg): select_unit(thd_arg) { tmp_table_param.init(); } bool create_result_table(THD *thd, List *column_types, bool is_distinct, ulonglong options, const LEX_CSTRING *alias, bool bit_fields_as_long, bool create_table, bool keep_row_order, uint hidden) override; bool init_result_table(ulonglong select_options); int send_data(List &items) override; void reset_for_next_ps_execution() override; ha_rows get_null_count_of_col(uint idx) { DBUG_ASSERT(idx < table->s->fields); return col_stat[idx].null_count; } ha_rows get_max_null_of_col(uint idx) { DBUG_ASSERT(idx < table->s->fields); return col_stat[idx].max_null_row; } ha_rows get_min_null_of_col(uint idx) { DBUG_ASSERT(idx < table->s->fields); return col_stat[idx].min_null_row; } uint get_max_nulls_in_row() { return max_nulls_in_row; } }; /* used in independent ALL/ANY optimisation */ class select_max_min_finder_subselect :public select_subselect { Item_cache *cache; bool (select_max_min_finder_subselect::*op)(); bool fmax; bool is_all; void set_op(const Type_handler *ha); public: select_max_min_finder_subselect(THD *thd_arg, Item_subselect *item_arg, bool mx, bool all): select_subselect(thd_arg, item_arg), cache(0), fmax(mx), is_all(all) {} void reset_for_next_ps_execution() override; int send_data(List &items) override; bool cmp_real(); bool cmp_int(); bool cmp_decimal(); bool cmp_str(); bool cmp_time(); bool cmp_native(); }; /* EXISTS subselect interface class */ class select_exists_subselect :public select_subselect { public: select_exists_subselect(THD *thd_arg, Item_subselect *item_arg): select_subselect(thd_arg, item_arg) {} int send_data(List &items) override; }; /* Optimizer and executor structure for the materialized semi-join info. This structure contains - The sj-materialization temporary table - Members needed to make index lookup or a full scan of the temptable. */ class POSITION; class SJ_MATERIALIZATION_INFO : public Sql_alloc { public: /* Optimal join sub-order */ POSITION *positions; uint tables; /* Number of tables in the sj-nest */ /* Number of rows in the materialized table, before the de-duplication */ double rows_with_duplicates; /* Expected #rows in the materialized table, after de-duplication */ double rows; /* Cost to materialize - execute the sub-join and write rows into temp.table */ Cost_estimate materialization_cost; /* Cost to make one lookup in the temptable */ Cost_estimate lookup_cost; /* Cost of scanning the materialized table */ Cost_estimate scan_cost; /* --- Execution structures ---------- */ /* TRUE <=> This structure is used for execution. We don't necessarily pick sj-materialization, so some of SJ_MATERIALIZATION_INFO structures are not used by materialization */ bool is_used; bool materialized; /* TRUE <=> materialization already performed */ /* TRUE - the temptable is read with full scan FALSE - we use the temptable for index lookups */ bool is_sj_scan; /* The temptable and its related info */ TMP_TABLE_PARAM sjm_table_param; List sjm_table_cols; TABLE *table; /* Structure used to make index lookups */ struct st_table_ref *tab_ref; Item *in_equality; /* See create_subq_in_equalities() */ Item *join_cond; /* See comments in make_join_select() */ Copy_field *copy_field; /* Needed for SJ_Materialization scan */ }; /* Structs used when sorting */ struct SORT_FIELD_ATTR { /* If using mem-comparable fixed-size keys: length of the mem-comparable image of the field, in bytes. If using packed keys: still the same? Not clear what is the use of it. */ uint length; /* For most datatypes, this is 0. The exception are the VARBINARY columns. For those columns, the comparison actually compares (value_prefix(N), suffix=length(value)) Here value_prefix is either the whole value or its prefix if it was too long, and the suffix is the length of the original value. (this way, for values X and Y: if X=prefix(Y) then X compares as less than Y */ uint suffix_length; /* If using packed keys, number of bytes that are used to store the length of the packed key. */ uint length_bytes; /* Max. length of the original value, in bytes */ uint original_length; enum Type { FIXED_SIZE, VARIABLE_SIZE } type; /* TRUE : if the item or field is NULLABLE FALSE : otherwise */ bool maybe_null; CHARSET_INFO *cs; uint pack_sort_string(uchar *to, const Binary_string *str, CHARSET_INFO *cs) const; int compare_packed_fixed_size_vals(const uchar *a, size_t *a_len, const uchar *b, size_t *b_len); int compare_packed_varstrings(const uchar *a, size_t *a_len, const uchar *b, size_t *b_len); bool check_if_packing_possible(THD *thd) const; bool is_variable_sized() { return type == VARIABLE_SIZE; } void set_length_and_original_length(THD *thd, uint length_arg); }; struct SORT_FIELD: public SORT_FIELD_ATTR { Field *field; /* Field to sort */ Item *item; /* Item if not sorting fields */ bool reverse; /* if descending sort */ }; typedef struct st_sort_buffer { uint index; /* 0 or 1 */ uint sort_orders; uint change_pos; /* If sort-fields changed */ char **buff; SORT_FIELD *sortorder; } SORT_BUFFER; /* Structure for db & table in sql_yacc */ class Table_ident :public Sql_alloc { public: LEX_CSTRING db; LEX_CSTRING table; SELECT_LEX_UNIT *sel; inline Table_ident(THD *thd, const LEX_CSTRING *db_arg, const LEX_CSTRING *table_arg, bool force) :table(*table_arg), sel((SELECT_LEX_UNIT *)0) { if (!force && (thd->client_capabilities & CLIENT_NO_SCHEMA)) db= null_clex_str; else db= *db_arg; } inline Table_ident(const LEX_CSTRING *table_arg) :table(*table_arg), sel((SELECT_LEX_UNIT *)0) { db= null_clex_str; } /* This constructor is used only for the case when we create a derived table. A derived table has no name and doesn't belong to any database. Later, if there was an alias specified for the table, it will be set by add_table_to_list. */ inline Table_ident(SELECT_LEX_UNIT *s) : sel(s) { /* We must have a table name here as this is used with add_table_to_list */ db.str= empty_c_string; /* a subject to casedn_str */ db.length= 0; table.str= internal_table_name; table.length=1; } bool is_derived_table() const { return MY_TEST(sel); } inline void change_db(LEX_CSTRING *db_name) { db= *db_name; } bool resolve_table_rowtype_ref(THD *thd, Row_definition_list &defs); bool append_to(THD *thd, String *to) const; }; class Qualified_column_ident: public Table_ident { public: LEX_CSTRING m_column; public: Qualified_column_ident(const LEX_CSTRING *column) :Table_ident(&null_clex_str), m_column(*column) { } Qualified_column_ident(const LEX_CSTRING *table, const LEX_CSTRING *column) :Table_ident(table), m_column(*column) { } Qualified_column_ident(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *table, const LEX_CSTRING *column) :Table_ident(thd, db, table, false), m_column(*column) { } bool resolve_type_ref(THD *thd, Column_definition *def); bool append_to(THD *thd, String *to) const; }; // this is needed for user_vars hash class user_var_entry: public Type_handler_hybrid_field_type { CHARSET_INFO *m_charset; public: user_var_entry() = default; /* Remove gcc warning */ LEX_CSTRING name; char *value; size_t length; query_id_t update_query_id, used_query_id; double val_real(bool *null_value); longlong val_int(bool *null_value) const; String *val_str(bool *null_value, String *str, uint decimals) const; my_decimal *val_decimal(bool *null_value, my_decimal *result); CHARSET_INFO *charset() const { return m_charset; } void set_charset(CHARSET_INFO *cs) { m_charset= cs; } }; user_var_entry *get_variable(HASH *hash, LEX_CSTRING *name, bool create_if_not_exists); class SORT_INFO; class multi_delete :public select_result_interceptor { TABLE_LIST *delete_tables, *table_being_deleted; Unique **tempfiles; ha_rows deleted, found; uint num_of_tables; int error; bool do_delete; /* True if at least one table we delete from is transactional */ bool transactional_tables; /* True if at least one table we delete from is not transactional */ bool normal_tables; bool delete_while_scanning; /* error handling (rollback and binlogging) can happen in send_eof() so that afterward abort_result_set() needs to find out that. */ bool error_handled; public: // Methods used by ColumnStore uint get_num_of_tables() const { return num_of_tables; } TABLE_LIST* get_tables() const { return delete_tables; } public: multi_delete(THD *thd_arg, TABLE_LIST *dt, uint num_of_tables); ~multi_delete(); int prepare(List &list, SELECT_LEX_UNIT *u) override; int send_data(List &items) override; bool initialize_tables (JOIN *join) override; int do_deletes(); int do_table_deletes(TABLE *table, SORT_INFO *sort_info, bool ignore); bool send_eof() override; inline ha_rows num_deleted() const { return deleted; } void abort_result_set() override; void prepare_to_read_rows() override; }; class multi_update :public select_result_interceptor { TABLE_LIST *all_tables; /* query/update command tables */ List *leaves; /* list of leaves of join table tree */ List updated_leaves; /* list of of updated leaves */ TABLE_LIST *update_tables; TABLE **tmp_tables, *main_table, *table_to_update; TMP_TABLE_PARAM *tmp_table_param; ha_rows updated, found; List *fields, *values; List **fields_for_table, **values_for_table; uint table_count; /* List of tables referenced in the CHECK OPTION condition of the updated view excluding the updated table. */ List
unupdated_check_opt_tables; Copy_field *copy_field; enum enum_duplicates handle_duplicates; bool do_update, trans_safe; /* True if the update operation has made a change in a transactional table */ bool transactional_tables; bool ignore; /* error handling (rollback and binlogging) can happen in send_eof() so that afterward abort_result_set() needs to find out that. */ bool error_handled; /* Need this to protect against multiple prepare() calls */ bool prepared; // For System Versioning (may need to insert new fields to a table). ha_rows updated_sys_ver; bool has_vers_fields; public: multi_update(THD *thd_arg, TABLE_LIST *ut, List *leaves_list, List *fields, List *values, enum_duplicates handle_duplicates, bool ignore); ~multi_update(); bool init(THD *thd); int prepare(List &list, SELECT_LEX_UNIT *u) override; int send_data(List &items) override; bool initialize_tables (JOIN *join) override; int prepare2(JOIN *join) override; int do_updates(); bool send_eof() override; inline ha_rows num_found() const { return found; } inline ha_rows num_updated() const { return updated; } void abort_result_set() override; void update_used_tables() override; void prepare_to_read_rows() override; }; class my_var_sp; class my_var : public Sql_alloc { public: const LEX_CSTRING name; enum type { SESSION_VAR, LOCAL_VAR, PARAM_VAR }; type scope; my_var(const LEX_CSTRING *j, enum type s) : name(*j), scope(s) { } virtual ~my_var() = default; virtual bool set(THD *thd, Item *val) = 0; virtual my_var_sp *get_my_var_sp() { return NULL; } }; class my_var_sp: public my_var { const Sp_rcontext_handler *m_rcontext_handler; const Type_handler *m_type_handler; public: uint offset; /* Routine to which this Item_splocal belongs. Used for checking if correct runtime context is used for variable handling. */ sp_head *sp; my_var_sp(const Sp_rcontext_handler *rcontext_handler, const LEX_CSTRING *j, uint o, const Type_handler *type_handler, sp_head *s) : my_var(j, LOCAL_VAR), m_rcontext_handler(rcontext_handler), m_type_handler(type_handler), offset(o), sp(s) { } ~my_var_sp() = default; bool set(THD *thd, Item *val) override; my_var_sp *get_my_var_sp() override { return this; } const Type_handler *type_handler() const { return m_type_handler; } sp_rcontext *get_rcontext(sp_rcontext *local_ctx) const; }; /* This class handles fields of a ROW SP variable when it's used as a OUT parameter in a stored procedure. */ class my_var_sp_row_field: public my_var_sp { uint m_field_offset; public: my_var_sp_row_field(const Sp_rcontext_handler *rcontext_handler, const LEX_CSTRING *varname, const LEX_CSTRING *fieldname, uint var_idx, uint field_idx, sp_head *s) :my_var_sp(rcontext_handler, varname, var_idx, &type_handler_double/*Not really used*/, s), m_field_offset(field_idx) { } bool set(THD *thd, Item *val) override; }; class my_var_user: public my_var { public: my_var_user(const LEX_CSTRING *j) : my_var(j, SESSION_VAR) { } ~my_var_user() = default; bool set(THD *thd, Item *val) override; }; class select_dumpvar :public select_result_interceptor { ha_rows row_count; my_var_sp *m_var_sp_row; // Not NULL if SELECT INTO row_type_sp_variable bool send_data_to_var_list(List &items); public: List var_list; select_dumpvar(THD *thd_arg) :select_result_interceptor(thd_arg), row_count(0), m_var_sp_row(NULL) { var_list.empty(); } ~select_dumpvar() = default; int prepare(List &list, SELECT_LEX_UNIT *u) override; int send_data(List &items) override; bool send_eof() override; bool check_simple_select() const override; void reset_for_next_ps_execution() override; }; /* Bits in sql_command_flags */ #define CF_CHANGES_DATA (1U << 0) #define CF_REPORT_PROGRESS (1U << 1) #define CF_STATUS_COMMAND (1U << 2) #define CF_SHOW_TABLE_COMMAND (1U << 3) #define CF_WRITE_LOGS_COMMAND (1U << 4) /** Must be set for SQL statements that may contain Item expressions and/or use joins and tables. Indicates that the parse tree of such statement may contain rule-based optimizations that depend on metadata (i.e. number of columns in a table), and consequently that the statement must be re-prepared whenever referenced metadata changes. Must not be set for statements that themselves change metadata, e.g. RENAME, ALTER and other DDL, since otherwise will trigger constant reprepare. Consequently, complex item expressions and joins are currently prohibited in these statements. */ #define CF_REEXECUTION_FRAGILE (1U << 5) /** Implicitly commit before the SQL statement is executed. Statements marked with this flag will cause any active transaction to end (commit) before proceeding with the command execution. This flag should be set for statements that probably can't be rolled back or that do not expect any previously metadata locked tables. */ #define CF_IMPLICIT_COMMIT_BEGIN (1U << 6) /** Implicitly commit after the SQL statement. Statements marked with this flag are automatically committed at the end of the statement. This flag should be set for statements that will implicitly open and take metadata locks on system tables that should not be carried for the whole duration of a active transaction. */ #define CF_IMPLICIT_COMMIT_END (1U << 7) /** CF_IMPLICT_COMMIT_BEGIN and CF_IMPLICIT_COMMIT_END are used to ensure that the active transaction is implicitly committed before and after every DDL statement and any statement that modifies our currently non-transactional system tables. */ #define CF_AUTO_COMMIT_TRANS (CF_IMPLICIT_COMMIT_BEGIN | CF_IMPLICIT_COMMIT_END) /** Diagnostic statement. Diagnostic statements: - SHOW WARNING - SHOW ERROR - GET DIAGNOSTICS (WL#2111) do not modify the diagnostics area during execution. */ #define CF_DIAGNOSTIC_STMT (1U << 8) /** Identifies statements that may generate row events and that may end up in the binary log. */ #define CF_CAN_GENERATE_ROW_EVENTS (1U << 9) /** Identifies statements which may deal with temporary tables and for which temporary tables should be pre-opened to simplify privilege checks. */ #define CF_PREOPEN_TMP_TABLES (1U << 10) /** Identifies statements for which open handlers should be closed in the beginning of the statement. */ #define CF_HA_CLOSE (1U << 11) /** Identifies statements that can be explained with EXPLAIN. */ #define CF_CAN_BE_EXPLAINED (1U << 12) /** Identifies statements which may generate an optimizer trace */ #define CF_OPTIMIZER_TRACE (1U << 14) /** Identifies statements that should always be disallowed in read only transactions. */ #define CF_DISALLOW_IN_RO_TRANS (1U << 15) /** Statement that need the binlog format to be unchanged. */ #define CF_FORCE_ORIGINAL_BINLOG_FORMAT (1U << 16) /** Statement that inserts new rows (INSERT, REPLACE, LOAD, ALTER TABLE) */ #define CF_INSERTS_DATA (1U << 17) /** Statement that updates existing rows (UPDATE, multi-update) */ #define CF_UPDATES_DATA (1U << 18) /** Not logged into slow log as "admin commands" */ #define CF_ADMIN_COMMAND (1U << 19) /** SP Bulk execution safe */ #define CF_PS_ARRAY_BINDING_SAFE (1U << 20) /** SP Bulk execution optimized */ #define CF_PS_ARRAY_BINDING_OPTIMIZED (1U << 21) /** If command creates or drops a table */ #define CF_SCHEMA_CHANGE (1U << 22) /** If command creates or drops a database */ #define CF_DB_CHANGE (1U << 23) #ifdef WITH_WSREP /** DDL statement that may be subject to error filtering. */ #define CF_WSREP_MAY_IGNORE_ERRORS (1U << 24) /** Basic DML statements that create writeset. */ #define CF_WSREP_BASIC_DML (1u << 25) #endif /* WITH_WSREP */ /* Bits in server_command_flags */ /** Statement that deletes existing rows (DELETE, DELETE_MULTI) */ #define CF_DELETES_DATA (1U << 24) /** Skip the increase of the global query id counter. Commonly set for commands that are stateless (won't cause any change on the server internal states). */ #define CF_SKIP_QUERY_ID (1U << 0) /** Skip the increase of the number of statements that clients have sent to the server. Commonly used for commands that will cause a statement to be executed but the statement might have not been sent by the user (ie: stored procedure). */ #define CF_SKIP_QUESTIONS (1U << 1) #ifdef WITH_WSREP /** Do not check that wsrep snapshot is ready before allowing this command */ #define CF_SKIP_WSREP_CHECK (1U << 2) #else #define CF_SKIP_WSREP_CHECK 0 #endif /* WITH_WSREP */ /* Inline functions */ inline bool add_item_to_list(THD *thd, Item *item) { bool res; LEX *lex= thd->lex; if (lex->current_select->parsing_place == IN_RETURNING) res= lex->returning()->add_item_to_list(thd, item); else res= lex->current_select->add_item_to_list(thd, item); return res; } inline bool add_value_to_list(THD *thd, Item *value) { return thd->lex->value_list.push_back(value, thd->mem_root); } inline bool add_order_to_list(THD *thd, Item *item, bool asc) { return thd->lex->current_select->add_order_to_list(thd, item, asc); } inline bool add_gorder_to_list(THD *thd, Item *item, bool asc) { return thd->lex->current_select->add_gorder_to_list(thd, item, asc); } inline bool add_group_to_list(THD *thd, Item *item, bool asc) { return thd->lex->current_select->add_group_to_list(thd, item, asc); } inline Item *and_conds(THD *thd, Item *a, Item *b) { if (!b) return a; if (!a) return b; return new (thd->mem_root) Item_cond_and(thd, a, b); } /* inline handler methods that need to know TABLE and THD structures */ inline void handler::increment_statistics(ulong SSV::*offset) const { status_var_increment(table->in_use->status_var.*offset); table->in_use->check_limit_rows_examined(); } inline void handler::decrement_statistics(ulong SSV::*offset) const { status_var_decrement(table->in_use->status_var.*offset); } inline int handler::ha_ft_read(uchar *buf) { int error= ft_read(buf); if (!error) { update_rows_read(); if (table->vfield && buf == table->record[0]) table->update_virtual_fields(this, VCOL_UPDATE_FOR_READ); } table->status=error ? STATUS_NOT_FOUND: 0; return error; } inline int handler::ha_rnd_pos_by_record(uchar *buf) { int error= rnd_pos_by_record(buf); table->status=error ? STATUS_NOT_FOUND: 0; return error; } inline int handler::ha_read_first_row(uchar *buf, uint primary_key) { int error= read_first_row(buf, primary_key); if (!error) update_rows_read(); table->status=error ? STATUS_NOT_FOUND: 0; return error; } inline int handler::ha_write_tmp_row(uchar *buf) { int error; MYSQL_INSERT_ROW_START(table_share->db.str, table_share->table_name.str); increment_statistics(&SSV::ha_tmp_write_count); TABLE_IO_WAIT(tracker, PSI_TABLE_WRITE_ROW, MAX_KEY, error, { error= write_row(buf); }) MYSQL_INSERT_ROW_DONE(error); return error; } inline int handler::ha_delete_tmp_row(uchar *buf) { int error; MYSQL_DELETE_ROW_START(table_share->db.str, table_share->table_name.str); increment_statistics(&SSV::ha_tmp_delete_count); TABLE_IO_WAIT(tracker, PSI_TABLE_DELETE_ROW, MAX_KEY, error, { error= delete_row(buf); }) MYSQL_DELETE_ROW_DONE(error); return error; } inline int handler::ha_update_tmp_row(const uchar *old_data, uchar *new_data) { int error; MYSQL_UPDATE_ROW_START(table_share->db.str, table_share->table_name.str); increment_statistics(&SSV::ha_tmp_update_count); TABLE_IO_WAIT(tracker, PSI_TABLE_UPDATE_ROW, active_index, error, { error= update_row(old_data, new_data);}) MYSQL_UPDATE_ROW_DONE(error); return error; } inline bool handler::has_long_unique() { return table->s->long_unique_table; } extern pthread_attr_t *get_connection_attrib(void); /** Set thread entering a condition This function should be called before putting a thread to wait for a condition. @a mutex should be held before calling this function. After being waken up, @f thd_exit_cond should be called. @param thd The thread entering the condition, NULL means current thread @param cond The condition the thread is going to wait for @param mutex The mutex associated with the condition, this must be held before call this function @param stage The new process message for the thread @param old_stage The old process message for the thread @param src_function The caller source function name @param src_file The caller source file name @param src_line The caller source line number */ void thd_enter_cond(MYSQL_THD thd, mysql_cond_t *cond, mysql_mutex_t *mutex, const PSI_stage_info *stage, PSI_stage_info *old_stage, const char *src_function, const char *src_file, int src_line); #define THD_ENTER_COND(P1, P2, P3, P4, P5) \ thd_enter_cond(P1, P2, P3, P4, P5, __func__, __FILE__, __LINE__) /** Set thread leaving a condition This function should be called after a thread being waken up for a condition. @param thd The thread entering the condition, NULL means current thread @param stage The process message, ususally this should be the old process message before calling @f thd_enter_cond @param src_function The caller source function name @param src_file The caller source file name @param src_line The caller source line number */ void thd_exit_cond(MYSQL_THD thd, const PSI_stage_info *stage, const char *src_function, const char *src_file, int src_line); #define THD_EXIT_COND(P1, P2) \ thd_exit_cond(P1, P2, __func__, __FILE__, __LINE__) inline bool binlog_should_compress(size_t len) { return opt_bin_log_compress && len >= opt_bin_log_compress_min_len; } /** Save thd sql_mode on instantiation. On destruction it resets the mode to the previously stored value. */ class Sql_mode_save { public: Sql_mode_save(THD *thd) : thd(thd), old_mode(thd->variables.sql_mode) {} ~Sql_mode_save() { thd->variables.sql_mode = old_mode; } private: THD *thd; sql_mode_t old_mode; // SQL mode saved at construction time. }; /* Save the current sql_mode. Switch off sql_mode flags which can prevent normal parsing of VIEWs, expressions in generated columns. Restore the old sql_mode on destructor. */ class Sql_mode_save_for_frm_handling: public Sql_mode_save { public: Sql_mode_save_for_frm_handling(THD *thd) :Sql_mode_save(thd) { /* - MODE_REAL_AS_FLOAT affect only CREATE TABLE parsing + MODE_PIPES_AS_CONCAT affect expression parsing + MODE_ANSI_QUOTES affect expression parsing + MODE_IGNORE_SPACE affect expression parsing - MODE_IGNORE_BAD_TABLE_OPTIONS affect only CREATE/ALTER TABLE parsing * MODE_ONLY_FULL_GROUP_BY affect execution * MODE_NO_UNSIGNED_SUBTRACTION affect execution - MODE_NO_DIR_IN_CREATE affect table creation only - MODE_POSTGRESQL compounded from other modes + MODE_ORACLE affects Item creation (e.g for CONCAT) - MODE_MSSQL compounded from other modes - MODE_DB2 compounded from other modes - MODE_MAXDB affect only CREATE TABLE parsing - MODE_NO_KEY_OPTIONS affect only SHOW - MODE_NO_TABLE_OPTIONS affect only SHOW - MODE_NO_FIELD_OPTIONS affect only SHOW - MODE_MYSQL323 affect only SHOW - MODE_MYSQL40 affect only SHOW - MODE_ANSI compounded from other modes (+ transaction mode) ? MODE_NO_AUTO_VALUE_ON_ZERO affect UPDATEs + MODE_NO_BACKSLASH_ESCAPES affect expression parsing + MODE_EMPTY_STRING_IS_NULL affect expression parsing */ thd->variables.sql_mode&= ~(MODE_PIPES_AS_CONCAT | MODE_ANSI_QUOTES | MODE_IGNORE_SPACE | MODE_NO_BACKSLASH_ESCAPES | MODE_ORACLE | MODE_EMPTY_STRING_IS_NULL); }; }; class Switch_to_definer_security_ctx { public: Switch_to_definer_security_ctx(THD *thd, TABLE_LIST *table) : m_thd(thd), m_sctx(thd->security_ctx) { if (table->security_ctx) thd->security_ctx= table->security_ctx; } ~Switch_to_definer_security_ctx() { m_thd->security_ctx = m_sctx; } private: THD *m_thd; Security_context *m_sctx; }; class Sql_mode_instant_set: public Sql_mode_save { public: Sql_mode_instant_set(THD *thd, sql_mode_t temporary_value) :Sql_mode_save(thd) { thd->variables.sql_mode= temporary_value; } }; class Sql_mode_instant_remove: public Sql_mode_save { public: Sql_mode_instant_remove(THD *thd, sql_mode_t temporary_remove_flags) :Sql_mode_save(thd) { thd->variables.sql_mode&= ~temporary_remove_flags; } }; class Abort_on_warning_instant_set { THD *m_thd; bool m_save_abort_on_warning; public: Abort_on_warning_instant_set(THD *thd, bool temporary_value) :m_thd(thd), m_save_abort_on_warning(thd->abort_on_warning) { thd->abort_on_warning= temporary_value; } ~Abort_on_warning_instant_set() { m_thd->abort_on_warning= m_save_abort_on_warning; } }; class Check_level_instant_set { THD *m_thd; enum_check_fields m_check_level; public: Check_level_instant_set(THD *thd, enum_check_fields temporary_value) :m_thd(thd), m_check_level(thd->count_cuted_fields) { thd->count_cuted_fields= temporary_value; } ~Check_level_instant_set() { m_thd->count_cuted_fields= m_check_level; } }; class Use_relaxed_field_copy: public Sql_mode_save, public Check_level_instant_set, public Abort_on_warning_instant_set { public: Use_relaxed_field_copy(THD *thd) : Sql_mode_save(thd), Check_level_instant_set(thd, CHECK_FIELD_IGNORE), Abort_on_warning_instant_set(thd, 0) { thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE); thd->variables.sql_mode|= MODE_INVALID_DATES; } }; class Identifier_chain2 { LEX_CSTRING m_name[2]; public: Identifier_chain2() :m_name{Lex_cstring(), Lex_cstring()} { } Identifier_chain2(const LEX_CSTRING &a, const LEX_CSTRING &b) :m_name{a, b} { } const LEX_CSTRING& operator [] (size_t i) const { return m_name[i]; } static Identifier_chain2 split(const LEX_CSTRING &txt) { DBUG_ASSERT(txt.str[txt.length] == '\0'); // Expect 0-terminated input const char *dot= strchr(txt.str, '.'); if (!dot) return Identifier_chain2(Lex_cstring(), txt); size_t length0= dot - txt.str; Lex_cstring name0(txt.str, length0); Lex_cstring name1(txt.str + length0 + 1, txt.length - length0 - 1); return Identifier_chain2(name0, name1); } // Export as a qualified name string: 'db.name' size_t make_qname(char *dst, size_t dstlen, bool casedn_part1) const { size_t res= my_snprintf(dst, dstlen, "%.*s.%.*s", (int) m_name[0].length, m_name[0].str, (int) m_name[1].length, m_name[1].str); if (casedn_part1 && dstlen > m_name[0].length) my_casedn_str(system_charset_info, dst + m_name[0].length + 1); return res; } // Export as a qualified name string, allocate on mem_root. LEX_CSTRING make_qname(MEM_ROOT *mem_root, bool casedn_part1) const { LEX_STRING dst; /* format: [pkg + dot] + name + '\0' */ size_t dst_size= m_name[0].length + 1 /*dot*/ + m_name[1].length + 1/*\0*/; if (unlikely(!(dst.str= (char*) alloc_root(mem_root, dst_size)))) return {NULL, 0}; if (!m_name[0].length) { DBUG_ASSERT(!casedn_part1); // Should not be called this way dst.length= my_snprintf(dst.str, dst_size, "%.*s", (int) m_name[1].length, m_name[1].str); return {dst.str, dst.length}; } dst.length= make_qname(dst.str, dst_size, casedn_part1); return {dst.str, dst.length}; } }; /** This class resembles the SQL Standard schema qualified object name: ::= [ ] */ class Database_qualified_name { public: LEX_CSTRING m_db; LEX_CSTRING m_name; Database_qualified_name(const LEX_CSTRING *db, const LEX_CSTRING *name) :m_db(*db), m_name(*name) { } Database_qualified_name(const LEX_CSTRING &db, const LEX_CSTRING &name) :m_db(db), m_name(name) { } Database_qualified_name(const char *db, size_t db_length, const char *name, size_t name_length) { m_db.str= db; m_db.length= db_length; m_name.str= name; m_name.length= name_length; } bool eq(const Database_qualified_name *other) const { CHARSET_INFO *cs= lower_case_table_names ? &my_charset_utf8mb3_general_ci : &my_charset_utf8mb3_bin; return m_db.length == other->m_db.length && m_name.length == other->m_name.length && !cs->strnncoll(m_db.str, m_db.length, other->m_db.str, other->m_db.length) && !cs->strnncoll(m_name.str, m_name.length, other->m_name.str, other->m_name.length); } void copy(MEM_ROOT *mem_root, const LEX_CSTRING &db, const LEX_CSTRING &name); // Export db and name as a qualified name string: 'db.name' size_t make_qname(char *dst, size_t dstlen, bool casedn_name) const { return Identifier_chain2(m_db, m_name).make_qname(dst, dstlen, casedn_name); } // Export db and name as a qualified name string, allocate on mem_root. LEX_CSTRING make_qname(MEM_ROOT *mem_root, bool casedn_name) const { DBUG_SLOW_ASSERT(ok_for_lower_case_names(m_db.str)); return Identifier_chain2(m_db, m_name).make_qname(mem_root, casedn_name); } bool make_package_routine_name(MEM_ROOT *mem_root, const LEX_CSTRING &package, const LEX_CSTRING &routine) { char *tmp; size_t length= package.length + 1 + routine.length + 1; if (unlikely(!(tmp= (char *) alloc_root(mem_root, length)))) return true; m_name.length= Identifier_chain2(package, routine).make_qname(tmp, length, false); m_name.str= tmp; return false; } bool make_package_routine_name(MEM_ROOT *mem_root, const LEX_CSTRING &db, const LEX_CSTRING &package, const LEX_CSTRING &routine) { if (unlikely(make_package_routine_name(mem_root, package, routine))) return true; if (unlikely(!(m_db.str= strmake_root(mem_root, db.str, db.length)))) return true; m_db.length= db.length; return false; } }; class ErrConvDQName: public ErrConv { const Database_qualified_name *m_name; public: ErrConvDQName(const Database_qualified_name *name) :m_name(name) { } LEX_CSTRING lex_cstring() const override { size_t length= m_name->make_qname(err_buffer, sizeof(err_buffer), false); return {err_buffer, length}; } }; class Type_holder: public Sql_alloc, public Item_args, public Type_handler_hybrid_field_type, public Type_all_attributes { const TYPELIB *m_typelib; bool m_maybe_null; public: Type_holder() :m_typelib(NULL), m_maybe_null(false) { } void set_type_maybe_null(bool maybe_null_arg) override { m_maybe_null= maybe_null_arg; } bool get_maybe_null() const { return m_maybe_null; } decimal_digits_t decimal_precision() const override { /* Type_holder is not used directly to create fields, so its virtual decimal_precision() is never called. We should eventually extend create_result_table() to accept an array of Type_holders directly, without having to allocate Item_type_holder's and put them into List. */ DBUG_ASSERT(0); return 0; } void set_typelib(const TYPELIB *typelib) override { m_typelib= typelib; } const TYPELIB *get_typelib() const override { return m_typelib; } bool aggregate_attributes(THD *thd) { static LEX_CSTRING union_name= { STRING_WITH_LEN("UNION") }; for (uint i= 0; i < arg_count; i++) m_maybe_null|= args[i]->maybe_null(); return type_handler()->Item_hybrid_func_fix_attributes(thd, union_name, this, this, args, arg_count); } }; /* A helper class to set THD flags to emit warnings/errors in case of overflow/type errors during assigning values into the SP variable fields. Saves original flags values in constructor. Restores original flags in destructor. */ class Sp_eval_expr_state { THD *m_thd; enum_check_fields m_count_cuted_fields; bool m_abort_on_warning; bool m_stmt_modified_non_trans_table; void start() { m_thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL; m_thd->abort_on_warning= m_thd->is_strict_mode(); m_thd->transaction->stmt.modified_non_trans_table= false; } void stop() { m_thd->count_cuted_fields= m_count_cuted_fields; m_thd->abort_on_warning= m_abort_on_warning; m_thd->transaction->stmt.modified_non_trans_table= m_stmt_modified_non_trans_table; } public: Sp_eval_expr_state(THD *thd) :m_thd(thd), m_count_cuted_fields(thd->count_cuted_fields), m_abort_on_warning(thd->abort_on_warning), m_stmt_modified_non_trans_table(thd->transaction->stmt. modified_non_trans_table) { start(); } ~Sp_eval_expr_state() { stop(); } }; #ifndef DBUG_OFF void dbug_serve_apcs(THD *thd, int n_calls); #endif class ScopedStatementReplication { public: ScopedStatementReplication(THD *thd) : saved_binlog_format(thd ? thd->set_current_stmt_binlog_format_stmt() : BINLOG_FORMAT_MIXED), thd(thd) {} ~ScopedStatementReplication() { if (thd) thd->restore_stmt_binlog_format(saved_binlog_format); } private: const enum_binlog_format saved_binlog_format; THD *const thd; }; /** THD registry */ class THD_list: public THD_list_iterator { public: /** Constructor replacement. Unfortunately we can't use fair constructor to initialize mutex for two reasons: PFS and embedded. The former can probably be fixed, the latter can probably be dropped. */ void init() { mysql_rwlock_init(key_rwlock_THD_list, &lock); } /** Destructor replacement. */ void destroy() { mysql_rwlock_destroy(&lock); } /** Inserts thread to registry. @param thd thread Thread becomes accessible via server_threads. */ void insert(THD *thd) { mysql_rwlock_wrlock(&lock); threads.append(thd); mysql_rwlock_unlock(&lock); } /** Removes thread from registry. @param thd thread Thread becomes not accessible via server_threads. */ void erase(THD *thd) { thd->assert_linked(); mysql_rwlock_wrlock(&lock); thd->unlink(); mysql_rwlock_unlock(&lock); } }; extern THD_list server_threads; void setup_tmp_table_column_bitmaps(TABLE *table, uchar *bitmaps, uint field_count); C_MODE_START void mariadb_sleep_for_space(unsigned int seconds); C_MODE_END #endif /* MYSQL_SERVER */ #endif /* SQL_CLASS_INCLUDED */ mysql/server/private/slave.h000064400000027763151027430560012176 0ustar00/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. Copyright (c) 2009, 2016, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SLAVE_H #define SLAVE_H /** MASTER_DELAY can be at most (1 << 31) - 1. */ #define MASTER_DELAY_MAX (0x7FFFFFFF) #if INT_MAX < 0x7FFFFFFF #error "don't support platforms where INT_MAX < 0x7FFFFFFF" #endif /** @defgroup Replication Replication @{ @file */ /** Some of defines are need in parser even though replication is not compiled in (embedded). */ /** The maximum is defined as (ULONG_MAX/1000) with 4 bytes ulong */ #define SLAVE_MAX_HEARTBEAT_PERIOD 4294967 #ifdef HAVE_REPLICATION #include "log.h" #include "my_list.h" #include "rpl_filter.h" #include "rpl_tblmap.h" #include "rpl_gtid.h" #include "log_event.h" #define SLAVE_NET_TIMEOUT 60 #define MAX_SLAVE_ERROR ER_ERROR_LAST+1 #define MAX_REPLICATION_THREAD 64 // Forward declarations class Relay_log_info; class Master_info; class Master_info_index; struct rpl_group_info; struct rpl_parallel_thread; int init_intvar_from_file(int* var, IO_CACHE* f, int default_val); int init_strvar_from_file(char *var, int max_size, IO_CACHE *f, const char *default_val); int init_floatvar_from_file(float* var, IO_CACHE* f, float default_val); int init_dynarray_intvar_from_file(DYNAMIC_ARRAY* arr, IO_CACHE* f); /***************************************************************************** MySQL Replication Replication is implemented via two types of threads: I/O Thread - One of these threads is started for each master server. They maintain a connection to their master server, read log events from the master as they arrive, and queues them into a single, shared relay log file. A Master_info represents each of these threads. SQL Thread - One of these threads is started and reads from the relay log file, executing each event. A Relay_log_info represents this thread. Buffering in the relay log file makes it unnecessary to reread events from a master server across a slave restart. It also decouples the slave from the master where long-running updates and event logging are concerned--ie it can continue to log new events while a slow query executes on the slave. *****************************************************************************/ /* MUTEXES in replication: LOCK_active_mi: [note: this was originally meant for multimaster, to switch from a master to another, to protect active_mi] It is used to SERIALIZE ALL administrative commands of replication: START SLAVE, STOP SLAVE, CHANGE MASTER, RESET SLAVE, end_slave() (when mysqld stops) [init_slave() does not need it it's called early]. Any of these commands holds the mutex from the start till the end. This thus protects us against a handful of deadlocks (consider start_slave_thread() which, when starting the I/O thread, releases mi->run_lock, keeps rli->run_lock, and tries to re-acquire mi->run_lock). Currently active_mi never moves (it's created at startup and deleted at shutdown, and not changed: it always points to the same Master_info struct), because we don't have multimaster. So for the moment, mi does not move, and mi->rli does not either. In Master_info: run_lock, data_lock run_lock protects all information about the run state: slave_running, thd and the existence of the I/O thread (to stop/start it, you need this mutex). data_lock protects some moving members of the struct: counters (log name, position) and relay log (MYSQL_BIN_LOG object). In Relay_log_info: run_lock, data_lock see Master_info However, note that run_lock does not protect Relay_log_info.run_state; that is protected by data_lock. Order of acquisition: if you want to have LOCK_active_mi and a run_lock, you must acquire LOCK_active_mi first. In MYSQL_BIN_LOG: LOCK_log, LOCK_index of the binlog and the relay log LOCK_log: when you write to it. LOCK_index: when you create/delete a binlog (so that you have to update the .index file). */ extern ulong master_retry_count; extern MY_BITMAP slave_error_mask; extern char slave_skip_error_names[]; extern bool use_slave_mask; extern char slave_transaction_retry_error_names[]; extern uint *slave_transaction_retry_errors; extern uint slave_transaction_retry_error_length; extern char *slave_load_tmpdir; extern char *master_info_file; extern MYSQL_PLUGIN_IMPORT char *relay_log_info_file; extern char *opt_relay_logname, *opt_relaylog_index_name; extern my_bool opt_skip_slave_start, opt_reckless_slave; extern my_bool opt_log_slave_updates; extern char *opt_slave_skip_errors; extern char *opt_slave_transaction_retry_errors; extern my_bool opt_replicate_annotate_row_events; extern ulonglong relay_log_space_limit; extern ulonglong opt_read_binlog_speed_limit; extern ulonglong slave_skipped_errors; extern const char *relay_log_index; extern const char *relay_log_basename; /* 4 possible values for Master_info::slave_running and Relay_log_info::slave_running. The values 0,1,2,3 are very important: to keep the diff small, I didn't substitute places where we use 0/1 with the newly defined symbols. So don't change these values. The same way, code is assuming that in Relay_log_info we use only values 0/1. I started with using an enum, but enum_variable=1; is not legal so would have required many line changes. */ #define MYSQL_SLAVE_NOT_RUN 0 #define MYSQL_SLAVE_RUN_NOT_CONNECT 1 #define MYSQL_SLAVE_RUN_CONNECT 2 #define MYSQL_SLAVE_RUN_READING 3 #define RPL_LOG_NAME (rli->group_master_log_name[0] ? rli->group_master_log_name :\ "FIRST") #define IO_RPL_LOG_NAME (mi->master_log_name[0] ? mi->master_log_name :\ "FIRST") /* If the following is set, if first gives an error, second will be tried. Otherwise, if first fails, we fail. */ #define SLAVE_FORCE_ALL 4 /* Values for the option --replicate-events-marked-for-skip. Must match the names in replicate_events_marked_for_skip_names in sys_vars.cc */ #define RPL_SKIP_REPLICATE 0 #define RPL_SKIP_FILTER_ON_SLAVE 1 #define RPL_SKIP_FILTER_ON_MASTER 2 int init_slave(); int init_recovery(Master_info* mi, const char** errmsg); bool init_slave_skip_errors(const char* arg); bool init_slave_transaction_retry_errors(const char* arg); int register_slave_on_master(MYSQL* mysql); int terminate_slave_threads(Master_info* mi, int thread_mask, bool skip_lock = 0); int start_slave_threads(THD *thd, bool need_slave_mutex, bool wait_for_start, Master_info* mi, const char* master_info_fname, const char* slave_info_fname, int thread_mask); /* cond_lock is usually same as start_lock. It is needed for the case when start_lock is 0 which happens if start_slave_thread() is called already inside the start_lock section, but at the same time we want a mysql_cond_wait() on start_cond, start_lock */ int start_slave_thread( #ifdef HAVE_PSI_INTERFACE PSI_thread_key thread_key, #endif pthread_handler h_func, mysql_mutex_t *start_lock, mysql_mutex_t *cond_lock, mysql_cond_t *start_cond, volatile uint *slave_running, volatile ulong *slave_run_id, Master_info *mi); /* If fd is -1, dump to NET */ int mysql_table_dump(THD* thd, const char* db, const char* tbl_name, int fd = -1); /* retrieve table from master and copy to slave*/ int fetch_master_table(THD* thd, const char* db_name, const char* table_name, Master_info* mi, MYSQL* mysql, bool overwrite); void show_master_info_get_fields(THD *thd, List *field_list, bool full, size_t gtid_pos_length); bool show_master_info(THD* thd, Master_info* mi, bool full); bool show_all_master_info(THD* thd); void show_binlog_info_get_fields(THD *thd, List *field_list); bool show_binlog_info(THD* thd); bool rpl_master_has_bug(const Relay_log_info *rli, uint bug_id, bool report, bool (*pred)(const void *), const void *param, bool maria_master= false); bool rpl_master_erroneous_autoinc(THD* thd); const char *print_slave_db_safe(const char *db); void skip_load_data_infile(NET* net); void slave_prepare_for_shutdown(); void end_slave(); /* release slave threads */ void close_active_mi(); /* clean up slave threads data */ void clear_until_condition(Relay_log_info* rli); void clear_slave_error(Relay_log_info* rli); void end_relay_log_info(Relay_log_info* rli); void init_thread_mask(int* mask,Master_info* mi,bool inverse); Format_description_log_event * read_relay_log_description_event(IO_CACHE *cur_log, ulonglong start_pos, const char **errmsg); int init_relay_log_pos(Relay_log_info* rli,const char* log,ulonglong pos, bool need_data_lock, const char** errmsg, bool look_for_description_event); int purge_relay_logs(Relay_log_info* rli, THD *thd, bool just_reset, const char** errmsg); void set_slave_thread_options(THD* thd); void set_slave_thread_default_charset(THD *thd, rpl_group_info *rgi); int rotate_relay_log(Master_info* mi); int has_temporary_error(THD *thd); int sql_delay_event(Log_event *ev, THD *thd, rpl_group_info *rgi); int apply_event_and_update_pos(Log_event* ev, THD* thd, struct rpl_group_info *rgi); int apply_event_and_update_pos_for_parallel(Log_event* ev, THD* thd, struct rpl_group_info *rgi); int init_intvar_from_file(int* var, IO_CACHE* f, int default_val); int init_floatvar_from_file(float* var, IO_CACHE* f, float default_val); int init_strvar_from_file(char *var, int max_size, IO_CACHE *f, const char *default_val); int init_dynarray_intvar_from_file(DYNAMIC_ARRAY* arr, IO_CACHE* f); pthread_handler_t handle_slave_io(void *arg); void slave_output_error_info(rpl_group_info *rgi, THD *thd); pthread_handler_t handle_slave_sql(void *arg); bool net_request_file(NET* net, const char* fname); void slave_background_kill_request(THD *to_kill); void slave_background_gtid_pos_create_request (rpl_slave_state::gtid_pos_table *table_entry); void slave_background_gtid_pending_delete_request(void); extern Master_info *active_mi; /* active_mi for multi-master */ extern Master_info *default_master_info; /* To replace active_mi */ extern Master_info_index *master_info_index; extern LEX_CSTRING default_master_connection_name; extern my_bool replicate_same_server_id; extern int disconnect_slave_event_count, abort_slave_event_count ; /* the master variables are defaults read from my.cnf or command line */ extern uint report_port; extern char *master_info_file, *report_user; extern char *report_host, *report_password; extern I_List threads; /* Check that a binlog event (read from the relay log) is valid to update last_master_timestamp. That is, a valid event is one with a consistent timestamp which originated from a primary server. */ static inline bool event_can_update_last_master_timestamp(Log_event *ev) { return ev && !(ev->is_artificial_event() || ev->is_relay_log_event() || (ev->when == 0)); } #else #define close_active_mi() /* no-op */ #endif /* HAVE_REPLICATION */ /* masks for start/stop operations on io and sql slave threads */ #define SLAVE_IO 1 #define SLAVE_SQL 2 /** @} (end of group Replication) */ #endif mysql/server/private/my_cpu.h000064400000011367151027430560012351 0ustar00#ifndef MY_CPU_INCLUDED #define MY_CPU_INCLUDED /* Copyright (c) 2013, 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* instructions for specific cpu's */ /* Macros for adjusting thread priority (hardware multi-threading) The defines are the same ones used by the linux kernel */ #ifdef _ARCH_PWR8 #ifdef __GLIBC__ #include /* Very low priority */ #define HMT_very_low() __ppc_set_ppr_very_low() /* Low priority */ #define HMT_low() __ppc_set_ppr_low() /* Medium low priority */ #define HMT_medium_low() __ppc_set_ppr_med_low() /* Medium priority */ #define HMT_medium() __ppc_set_ppr_med() /* Medium high priority */ #define HMT_medium_high() __ppc_set_ppr_med_high() /* High priority */ #define HMT_high() asm volatile("or 3,3,3") #else /* GLIBC */ #if defined(__FreeBSD__) #include #include #endif #define HMT_very_low() __asm__ volatile ("or 31,31,31") #define HMT_low() __asm__ volatile ("or 1,1,1") #define HMT_medium_low() __asm__ volatile ("or 6,6,6") #define HMT_medium() __asm__ volatile ("or 2,2,2") #define HMT_medium_high() __asm__ volatile ("or 5,5,5") #define HMT_high() asm volatile("or 3,3,3") #endif /* GLIBC */ #else #define HMT_very_low() #define HMT_low() #define HMT_medium_low() #define HMT_medium() #define HMT_medium_high() #define HMT_high() #endif #if defined __i386__ || defined __x86_64__ || defined _WIN32 # define HAVE_PAUSE_INSTRUCTION /* added in Intel Pentium 4 */ #endif #ifdef _WIN32 #elif defined HAVE_PAUSE_INSTRUCTION #elif defined(_ARCH_PWR8) #elif defined __GNUC__ && (defined __arm__ || defined __aarch64__) #else # include "my_global.h" # include "my_atomic.h" #endif static inline void MY_RELAX_CPU(void) { #ifdef _WIN32 /* In the Win32 API, the x86 PAUSE instruction is executed by calling the YieldProcessor macro defined in WinNT.h. It is a CPU architecture- independent way by using YieldProcessor. */ YieldProcessor(); #elif defined HAVE_PAUSE_INSTRUCTION /* According to the gcc info page, asm volatile means that the instruction has important side-effects and must not be removed. Also asm volatile may trigger a memory barrier (spilling all registers to memory). */ #ifdef __SUNPRO_CC asm ("pause" ); #else __asm__ __volatile__ ("pause"); #endif #elif defined(_ARCH_PWR8) /* Changed from __ppc_get_timebase for musl and clang compatibility */ __builtin_ppc_get_timebase(); #elif defined __GNUC__ && defined __riscv /* The GCC-only __builtin_riscv_pause() or the pause instruction is encoded like a fence instruction with special parameters. On RISC-V implementations that do not support arch=+zihintpause this instruction could be interpreted as a more expensive memory fence; it should not be an illegal instruction. */ __asm__ volatile(".long 0x0100000f" ::: "memory"); #elif defined __GNUC__ /* Mainly, prevent the compiler from optimizing away delay loops */ __asm__ __volatile__ ("":::"memory"); #endif } #ifdef HAVE_PAUSE_INSTRUCTION # ifdef __cplusplus extern "C" { # endif extern unsigned my_cpu_relax_multiplier; void my_cpu_init(void); # ifdef __cplusplus } # endif #else # define my_cpu_relax_multiplier 200 # define my_cpu_init() /* nothing */ #endif /* LF_BACKOFF should be used to improve performance on hyperthreaded CPUs. Intel recommends to use it in spin loops also on non-HT machines to reduce power consumption (see e.g http://softwarecommunity.intel.com/articles/eng/2004.htm) Running benchmarks for spinlocks implemented with InterlockedCompareExchange and YieldProcessor shows that much better performance is achieved by calling YieldProcessor in a loop - that is, yielding longer. On Intel boxes setting loop count in the range 200-300 brought best results. */ static inline int LF_BACKOFF(void) { unsigned i= my_cpu_relax_multiplier; while (i--) MY_RELAX_CPU(); return 1; } /** Run a delay loop while waiting for a shared resource to be released. @param delay originally, roughly microseconds on 100 MHz Intel Pentium */ static inline void ut_delay(unsigned delay) { unsigned i= my_cpu_relax_multiplier / 4 * delay; HMT_low(); while (i--) MY_RELAX_CPU(); HMT_medium(); } #endif mysql/server/private/lex_string.h000064400000007744151027430560013237 0ustar00/* Copyright (c) 2018, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LEX_STRING_INCLUDED #define LEX_STRING_INCLUDED typedef struct st_mysql_const_lex_string LEX_CSTRING; class Lex_cstring : public LEX_CSTRING { public: Lex_cstring() { str= NULL; length= 0; } Lex_cstring(const LEX_CSTRING &str) { LEX_CSTRING::operator=(str); } Lex_cstring(const char *_str, size_t _len) { str= _str; length= _len; } Lex_cstring(const char *start, const char *end) { DBUG_ASSERT(start <= end); str= start; length= end - start; } void set(const char *_str, size_t _len) { str= _str; length= _len; } /* Trim left white spaces. Assumes that there are no multi-bytes characters that can be considered white-space. */ Lex_cstring ltrim_whitespace(CHARSET_INFO *cs) const { DBUG_ASSERT(cs->mbminlen == 1); Lex_cstring str= *this; while (str.length > 0 && my_isspace(cs, str.str[0])) { str.length--; str.str++; } return str; } /* Trim right white spaces. Assumes that there are no multi-bytes characters that can be considered white-space. Also, assumes that the character set supports backward space parsing. */ Lex_cstring rtrim_whitespace(CHARSET_INFO *cs) const { DBUG_ASSERT(cs->mbminlen == 1); Lex_cstring str= *this; while (str.length > 0 && my_isspace(cs, str.str[str.length - 1])) { str.length --; } return str; } /* Trim all spaces. */ Lex_cstring trim_whitespace(CHARSET_INFO *cs) const { return ltrim_whitespace(cs).rtrim_whitespace(cs); } /* Trim all spaces and return the length of the leading space sequence. */ Lex_cstring trim_whitespace(CHARSET_INFO *cs, size_t *prefix_length) const { Lex_cstring tmp= Lex_cstring(*this).ltrim_whitespace(cs); if (prefix_length) *prefix_length= tmp.str - str; return tmp.rtrim_whitespace(cs); } }; class Lex_cstring_strlen: public Lex_cstring { public: Lex_cstring_strlen(const char *from) :Lex_cstring(from, from ? strlen(from) : 0) { } }; /* Functions to compare if two lex strings are equal */ static inline bool lex_string_cmp(CHARSET_INFO *charset, const LEX_CSTRING *a, const LEX_CSTRING *b) { return my_strcasecmp(charset, a->str, b->str); } /* Compare to LEX_CSTRING's and return 0 if equal */ static inline bool cmp(const LEX_CSTRING *a, const LEX_CSTRING *b) { return a->length != b->length || (a->length && memcmp(a->str, b->str, a->length)); } static inline bool cmp(const LEX_CSTRING a, const LEX_CSTRING b) { return a.length != b.length || (a.length && memcmp(a.str, b.str, a.length)); } /* Compare if two LEX_CSTRING are equal. Assumption is that character set is ASCII (like for plugin names) */ static inline bool lex_string_eq(const LEX_CSTRING *a, const LEX_CSTRING *b) { if (a->length != b->length) return 0; /* Different */ return strcasecmp(a->str, b->str) == 0; } /* To be used when calling lex_string_eq with STRING_WITH_LEN() as second argument */ static inline bool lex_string_eq(const LEX_CSTRING *a, const char *b, size_t b_length) { if (a->length != b_length) return 0; /* Different */ return strcasecmp(a->str, b) == 0; } #endif /* LEX_STRING_INCLUDED */ mysql/server/private/event_queue.h000064400000006556151027430560013406 0ustar00#ifndef _EVENT_QUEUE_H_ #define _EVENT_QUEUE_H_ /* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @addtogroup Event_Scheduler @{ @file event_queue.h Queue of events awaiting execution. */ #ifdef HAVE_PSI_INTERFACE extern PSI_mutex_key key_LOCK_event_queue; extern PSI_cond_key key_COND_queue_state; #endif /* HAVE_PSI_INTERFACE */ #include "queues.h" // QUEUE #include "sql_string.h" /* LEX_CSTRING */ #include "my_time.h" /* my_time_t, interval_type */ class Event_basic; class Event_queue_element; class Event_queue_element_for_exec; class THD; /** Queue of active events awaiting execution. */ class Event_queue { public: Event_queue(); ~Event_queue(); bool init_queue(THD *thd); /* Methods for queue management follow */ bool create_event(THD *thd, Event_queue_element *new_element, bool *created); void update_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name, Event_queue_element *new_element); void drop_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name); void drop_schema_events(THD *thd, const LEX_CSTRING *schema); void recalculate_activation_times(THD *thd); bool get_top_for_execution_if_time(THD *thd, Event_queue_element_for_exec **event_name); void dump_internal_status(); private: void empty_queue(); void deinit_queue(); /* helper functions for working with mutexes & conditionals */ void lock_data(const char *func, uint line); void unlock_data(const char *func, uint line); void cond_wait(THD *thd, struct timespec *abstime, const PSI_stage_info *stage, const char *src_func, const char *src_file, uint src_line); void find_n_remove_event(const LEX_CSTRING *db, const LEX_CSTRING *name); void drop_matching_events(THD *thd, const LEX_CSTRING *pattern, bool (*)(const LEX_CSTRING*, Event_basic *)); void dbug_dump_queue(my_time_t now); /* LOCK_event_queue is the mutex which protects the access to the queue. */ mysql_mutex_t LOCK_event_queue; mysql_cond_t COND_queue_state; /* The sorted queue with the Event_queue_element objects */ QUEUE queue; my_time_t next_activation_at; uint mutex_last_locked_at_line; uint mutex_last_unlocked_at_line; uint mutex_last_attempted_lock_at_line; const char* mutex_last_locked_in_func; const char* mutex_last_unlocked_in_func; const char* mutex_last_attempted_lock_in_func; bool mutex_queue_data_locked; bool mutex_queue_data_attempting_lock; bool waiting_on_cond; }; /** @} (End of group Event_Scheduler) */ #endif /* _EVENT_QUEUE_H_ */ mysql/server/private/my_stack_alloc.h000064400000014535151027430560014041 0ustar00/* Copyright 2019 MariaDB corporation AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_stack_alloc_h #define _my_stack_alloc_h #ifdef _MSC_VER #include // For MSVC-specific intrinsics #else #include #endif /* Get the address of the current stack. This will fallback to using an estimate for the stack pointer in the cases where either the compiler or the architecture is not supported. */ static inline void *my_get_stack_pointer(void *default_stack) { void *stack_ptr= NULL; #if defined(__GNUC__) || defined(__clang__) /* GCC and Clang compilers */ #if defined(__i386__) /* Intel x86 (32-bit) */ __asm__ volatile ("movl %%esp, %0" : "=r" (stack_ptr)); #elif defined(__x86_64__) && defined (__ILP32__) /* Intel x86-64 (64-bit), X32 ABI */ __asm__ volatile ("movl %%esp, %0" : "=r" (stack_ptr)); #elif defined(__x86_64__) /* Intel x86-64 (64-bit) */ __asm__ volatile ("movq %%rsp, %0" : "=r" (stack_ptr)); #elif defined(__powerpc__) /* PowerPC (32-bit) */ __asm__ volatile ("mr %0, 1" : "=r" (stack_ptr)); /* GPR1 is the stack pointer */ #elif defined(__ppc64__) /* PowerPC (64-bit) */ __asm__ volatile ("mr %0, 1" : "=r" (stack_ptr)); #elif defined(__arm__) /* ARM 32-bit */ __asm__ volatile ("mov %0, sp" : "=r" (stack_ptr)); #elif defined(__aarch64__) /* ARM 64-bit */ __asm__ volatile ("mov %0, sp" : "=r" (stack_ptr)); #elif defined(__sparc__) /* SPARC 32-bit */ __asm__ volatile ("mov %%sp, %0" : "=r" (stack_ptr)); #elif defined(__sparc64__) /* SPARC 64-bit */ __asm__ volatile ("mov %%sp, %0" : "=r" (stack_ptr)); #elif defined(__s390x__) stack_ptr= __builtin_frame_address(0); #else /* Generic fallback for unsupported architectures in GCC/Clang */ stack_ptr= default_stack ? default_stack : (void*) &stack_ptr; #endif #elif defined(_MSC_VER) /* MSVC compiler (Intel only) */ #if defined(_M_IX86) /* Intel x86 (32-bit) */ __asm { mov stack_ptr, esp } #elif defined(_M_X64) /* Intel x86-64 (64-bit) */ /* rsp can’t be accessed directly in MSVC x64 */ stack_ptr= _AddressOfReturnAddress(); #else /* Generic fallback for unsupported architectures in MSVC */ stack_ptr= default_stack ? default_stack : (void*) &stack_ptr; #endif #else /* Generic fallback for unsupported compilers */ stack_ptr= default_stack ? default_stack : (void*) &stack_ptr; #endif return stack_ptr; } /* Do allocation through alloca if there is enough stack available. If not, use my_malloc() instead. The idea is that to be able to alloc as much as possible through the stack. To ensure this, we have two different limits, on for big blocks and one for small blocks. This will enable us to continue to do allocation for small blocks even when there is less stack space available. This is for example used by Aria when traversing the b-tree and the code needs to allocate one b-tree page and a few keys for each recursion. Even if there is not space to allocate the b-tree pages on stack we can still continue to allocate the keys. */ /* Default suggested allocations */ /* Allocate big blocks as long as there is this much left */ #define STACK_ALLOC_BIG_BLOCK 1024*64 /* Allocate small blocks as long as there is this much left */ #define STACK_ALLOC_SMALL_BLOCK 1024*32 /* Allocate small blocks as long as the block size is not bigger than */ #define STACK_ALLOC_SMALL_BLOCK_SIZE 4096 /* Allocate a block on stack or through malloc. The 'must_be_freed' variable will be set to 1 if malloc was called. 'must_be_freed' must be a variable on the stack! */ #ifdef HAVE_ALLOCA #define alloc_on_stack(stack_end, res, must_be_freed, size) \ do \ { \ size_t alloc_size= (size); \ void *stack= my_get_stack_pointer(0); \ size_t stack_left= available_stack_size(stack, (stack_end)); \ if (stack_left > alloc_size + STACK_ALLOC_SMALL_BLOCK && \ (stack_left > alloc_size + STACK_ALLOC_BIG_BLOCK || \ (STACK_ALLOC_SMALL_BLOCK_SIZE >= alloc_size))) \ { \ (must_be_freed)= 0; \ (res)= alloca(size); \ } \ else \ { \ (must_be_freed)= 1; \ (res)= my_malloc(PSI_INSTRUMENT_ME, size, MYF(MY_THREAD_SPECIFIC | MY_WME)); \ } \ } while(0) #else #define alloc_on_stack(stack_end, res, must_be_freed, size) \ do { \ (must_be_freed)= 1; \ (res)= my_malloc(PSI_INSTRUMENT_ME, size, MYF(MY_THREAD_SPECIFIC | MY_WME)); \ } while(0) #endif /* HAVE_ALLOCA */ /* Free memory allocated by stack_alloc */ static inline void stack_alloc_free(void *res, my_bool must_be_freed) { if (must_be_freed) my_free(res); } #endif /* _my_stack_alloc_h */ /* Get start and end of stack */ /* This is used in the case when we not know the exact stack start and have to estimate stack start with get_stack_pointer() */ #define MY_STACK_SAFE_MARGIN 8192 extern void my_get_stack_bounds(void **stack_start, void **stack_end, void *fallback_stack_start, size_t fallback_stack_size); mysql/server/private/events.h000064400000011140151027430560012346 0ustar00#ifndef _EVENT_H_ #define _EVENT_H_ /* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @defgroup Event_Scheduler Event Scheduler @ingroup Runtime_Environment @{ @file events.h A public interface of Events_Scheduler module. */ #ifdef HAVE_PSI_INTERFACE extern PSI_mutex_key key_event_scheduler_LOCK_scheduler_state; extern PSI_cond_key key_event_scheduler_COND_state; extern PSI_thread_key key_thread_event_scheduler, key_thread_event_worker; #endif /* HAVE_PSI_INTERFACE */ extern PSI_memory_key key_memory_event_basic_root; /* Always defined, for SHOW PROCESSLIST. */ extern PSI_stage_info stage_waiting_on_empty_queue; extern PSI_stage_info stage_waiting_for_next_activation; extern PSI_stage_info stage_waiting_for_scheduler_to_stop; #include "sql_string.h" /* LEX_CSTRING */ #include "my_time.h" /* interval_type */ class Event_db_repository; class Event_parse_data; class Event_queue; class Event_scheduler; struct TABLE_LIST; class THD; typedef class Item COND; int sortcmp_lex_string(const LEX_CSTRING *s, const LEX_CSTRING *t, const CHARSET_INFO *cs); /** @brief A facade to the functionality of the Event Scheduler. Every public operation against the scheduler has to be executed via the interface provided by a static method of this class. No instance of this class is ever created and it has no non-static data members. The life cycle of the Events module is the following: At server start up: init_mutexes() -> init() When the server is running: create_event(), drop_event(), start_or_stop_event_scheduler(), etc At shutdown: deinit(), destroy_mutexes(). The peculiar initialization and shutdown cycle is an adaptation to the outside server startup/shutdown framework and mimics the rest of MySQL subsystems (ACL, time zone tables, etc). */ class Events { public: /* the following block is to support --event-scheduler command line option and the @@global.event_scheduler SQL variable. See sys_var.cc */ enum enum_opt_event_scheduler { EVENTS_OFF, EVENTS_ON, EVENTS_DISABLED, EVENTS_ORIGINAL }; /* Protected using LOCK_global_system_variables only. */ static ulong opt_event_scheduler, startup_state; static ulong inited; static bool check_if_system_tables_error(); static bool start(int *err_no); static bool stop(); public: /* A hack needed for Event_queue_element */ static Event_db_repository * get_db_repository() { return db_repository; } static bool init(THD *thd, bool opt_noacl); static void deinit(); static void init_mutexes(); static void destroy_mutexes(); static bool create_event(THD *thd, Event_parse_data *parse_data); static bool update_event(THD *thd, Event_parse_data *parse_data, LEX_CSTRING *new_dbname, LEX_CSTRING *new_name); static bool drop_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name, bool if_exists); static void drop_schema_events(THD *thd, const char *db); static bool show_create_event(THD *thd, const LEX_CSTRING *dbname, const LEX_CSTRING *name); /* Needed for both SHOW CREATE EVENT and INFORMATION_SCHEMA */ static int reconstruct_interval_expression(String *buf, interval_type interval, longlong expression); static int fill_schema_events(THD *thd, TABLE_LIST *tables, COND * /* cond */); static void dump_internal_status(); static void set_original_state(ulong startup_state_org) { startup_state= startup_state_org; } private: static bool load_events_from_db(THD *thd); private: static Event_queue *event_queue; static Event_scheduler *scheduler; static Event_db_repository *db_repository; private: /* Prevent use of these */ Events(const Events &); void operator=(Events &); }; /** @} (end of group Event Scheduler) */ #endif /* _EVENT_H_ */ mysql/server/private/my_decimal.h000064400000034231151027430560013153 0ustar00/* Copyright (c) 2005, 2013, Oracle and/or its affiliates. Copyright (c) 2011, 2014, SkySQL Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file It is interface module to fixed precision decimals library. Most functions use 'uint mask' as parameter, if during operation error which fit in this mask is detected then it will be processed automatically here. (errors are E_DEC_* constants, see include/decimal.h) Most function are just inline wrappers around library calls */ #ifndef my_decimal_h #define my_decimal_h #include "sql_basic_types.h" #if defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) #include "sql_string.h" /* String */ #endif C_MODE_START #include #include C_MODE_END class String; class Field; typedef struct st_mysql_time MYSQL_TIME; /** maximum size of packet length. */ #define DECIMAL_MAX_FIELD_SIZE DECIMAL_MAX_PRECISION inline uint my_decimal_size(decimal_digits_t precision, decimal_digits_t scale) { /* Always allocate more space to allow library to put decimal point where it want */ return decimal_size(precision, scale) + 1; } inline decimal_digits_t my_decimal_int_part(decimal_digits_t precision, decimal_digits_t decimals) { return (decimal_digits_t) (precision - ((decimals == DECIMAL_NOT_SPECIFIED) ? 0 : decimals)); } #ifndef MYSQL_CLIENT int decimal_operation_results(int result, const char *value, const char *type); #else inline int decimal_operation_results(int result, const char *value, const char *type) { return result; } #endif /*MYSQL_CLIENT*/ inline int check_result(uint mask, int result) { if (result & mask) decimal_operation_results(result, "", "DECIMAL"); return result; } /** my_decimal class limits 'decimal_t' type to what we need in MySQL. It contains internally all necessary space needed by the instance so no extra memory is needed. One should call fix_buffer_pointer() function when he moves my_decimal objects in memory. */ class my_decimal :public decimal_t { /* Several of the routines in strings/decimal.c have had buffer overrun/underrun problems. These are *not* caught by valgrind. To catch them, we allocate dummy fields around the buffer, and test that their values do not change. */ #if !defined(DBUG_OFF) int foo1; #endif decimal_digit_t buffer[DECIMAL_BUFF_LENGTH]; #if !defined(DBUG_OFF) int foo2; static const int test_value= 123; #endif public: my_decimal(const my_decimal &rhs) : decimal_t(rhs) { init(); for (uint i= 0; i < DECIMAL_BUFF_LENGTH; i++) buffer[i]= rhs.buffer[i]; } my_decimal& operator=(const my_decimal &rhs) { if (this == &rhs) return *this; decimal_t::operator=(rhs); for (uint i= 0; i < DECIMAL_BUFF_LENGTH; i++) buffer[i]= rhs.buffer[i]; fix_buffer_pointer(); return *this; } void init() { #if !defined(DBUG_OFF) foo1= test_value; foo2= test_value; #endif len= DECIMAL_BUFF_LENGTH; buf= buffer; TRASH_ALLOC(buffer, sizeof(buffer)); } my_decimal() { init(); } my_decimal(const uchar *bin, decimal_digits_t prec, decimal_digits_t scale) { init(); check_result(E_DEC_FATAL_ERROR, bin2decimal(bin, this, prec, scale)); } my_decimal(Field *field); ~my_decimal() { sanity_check(); } void sanity_check() { DBUG_SLOW_ASSERT(foo1 == test_value); DBUG_SLOW_ASSERT(foo2 == test_value); } void fix_buffer_pointer() { buf= buffer; } bool sign() const { return decimal_t::sign; } void sign(bool s) { decimal_t::sign= s; } decimal_digits_t precision() const { return (decimal_digits_t) (intg + frac); } void set_zero() { /* We need the up-cast here, since my_decimal has sign() member functions, which conflicts with decimal_t::sign (and decimal_make_zero is a macro, rather than a funcion). */ decimal_make_zero(static_cast(this)); } int cmp(const my_decimal *other) const { return decimal_cmp(this, other); } #ifndef MYSQL_CLIENT bool to_bool() const { return !decimal_is_zero(this); } double to_double() const { double res; decimal2double(this, &res); return res; } longlong to_longlong(bool unsigned_flag) const; /* Return the value as a signed or unsigned longlong, depending on the sign. - Positive values are returned as unsigned. - Negative values are returned as signed. This is used by bit SQL operators: | & ^ ~ as well as by the SQL function BIT_COUNT(). */ longlong to_xlonglong() const { return to_longlong(!sign()); } // Convert to string returning decimal2string() error code int to_string_native(String *to, uint prec, uint dec, char filler, uint mask= E_DEC_FATAL_ERROR) const; // Convert to string returning the String pointer String *to_string(String *to, uint prec, uint dec, char filler) const { return to_string_native(to, prec, dec, filler) ? NULL : to; } String *to_string(String *to) const { return to_string(to, 0, 0, 0); } String *to_string_round(String *to, decimal_digits_t scale, my_decimal *round_buff) const { (void) round_to(round_buff, scale, HALF_UP); // QQ: check result? return round_buff->to_string(to); } /* Scale can be negative here when called from truncate() */ int round_to(my_decimal *to, int scale, decimal_round_mode mode, int mask= E_DEC_FATAL_ERROR) const { return check_result(mask, decimal_round(this, to, scale, mode)); } int to_binary(uchar *bin, int prec, decimal_digits_t scale, uint mask= E_DEC_FATAL_ERROR) const; #endif /** Swap two my_decimal values */ void swap(my_decimal &rhs) { swap_variables(my_decimal, *this, rhs); } }; #ifndef DBUG_OFF void print_decimal(const my_decimal *dec); void print_decimal_buff(const my_decimal *dec, const uchar* ptr, int length); const char *dbug_decimal_as_string(char *buff, const my_decimal *val); #else #define dbug_decimal_as_string(A) NULL #endif bool str_set_decimal(uint mask, const my_decimal *val, uint fixed_prec, uint fixed_dec, char filler, String *str, CHARSET_INFO *cs); extern my_decimal decimal_zero; inline void max_my_decimal(my_decimal *to, decimal_digits_t precision, decimal_digits_t frac) { DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION)&& (frac <= DECIMAL_MAX_SCALE)); max_decimal(precision, frac, to); } inline void max_internal_decimal(my_decimal *to) { max_my_decimal(to, DECIMAL_MAX_PRECISION, 0); } inline int check_result_and_overflow(uint mask, int result, my_decimal *val) { if (check_result(mask, result) & E_DEC_OVERFLOW) { bool sign= val->sign(); val->fix_buffer_pointer(); max_internal_decimal(val); val->sign(sign); } return result; } inline decimal_digits_t my_decimal_length_to_precision(decimal_digits_t length, decimal_digits_t scale, bool unsigned_flag) { /* Precision can't be negative thus ignore unsigned_flag when length is 0. */ DBUG_ASSERT(length || !scale); return (decimal_digits_t) (length - (scale>0 ? 1:0) - (unsigned_flag || !length ? 0:1)); } inline decimal_digits_t my_decimal_precision_to_length_no_truncation(decimal_digits_t precision, decimal_digits_t scale, bool unsigned_flag) { /* When precision is 0 it means that original length was also 0. Thus unsigned_flag is ignored in this case. */ DBUG_ASSERT(precision || !scale); return (decimal_digits_t)(precision + (scale > 0 ? 1 : 0) + (unsigned_flag || !precision ? 0 : 1)); } inline decimal_digits_t my_decimal_precision_to_length(decimal_digits_t precision, decimal_digits_t scale, bool unsigned_flag) { /* When precision is 0 it means that original length was also 0. Thus unsigned_flag is ignored in this case. */ DBUG_ASSERT(precision || !scale); set_if_smaller(precision, DECIMAL_MAX_PRECISION); return my_decimal_precision_to_length_no_truncation(precision, scale, unsigned_flag); } inline uint my_decimal_string_length(const my_decimal *d) { /* length of string representation including terminating '\0' */ return decimal_string_size(d); } inline uint my_decimal_max_length(const my_decimal *d) { /* -1 because we do not count \0 */ return decimal_string_size(d) - 1; } inline uint my_decimal_get_binary_size(decimal_digits_t precision, decimal_digits_t scale) { return decimal_bin_size(precision, scale); } inline void my_decimal2decimal(const my_decimal *from, my_decimal *to) { *to= *from; } inline int binary2my_decimal(uint mask, const uchar *bin, my_decimal *d, decimal_digits_t prec, decimal_digits_t scale) { return check_result(mask, bin2decimal(bin, d, prec, scale)); } inline int my_decimal_set_zero(my_decimal *d) { d->set_zero(); return 0; } inline bool my_decimal_is_zero(const my_decimal *decimal_value) { return decimal_is_zero(decimal_value); } inline bool str_set_decimal(const my_decimal *val, String *str, CHARSET_INFO *cs) { return str_set_decimal(E_DEC_FATAL_ERROR, val, 0, 0, 0, str, cs); } bool my_decimal2seconds(const my_decimal *d, ulonglong *sec, ulong *microsec, ulong *nanosec); my_decimal *seconds2my_decimal(bool sign, ulonglong sec, ulong microsec, my_decimal *d); #define TIME_to_my_decimal(TIME, DECIMAL) \ seconds2my_decimal((TIME)->neg, TIME_to_ulonglong(TIME), \ (TIME)->second_part, (DECIMAL)) int my_decimal2int(uint mask, const decimal_t *d, bool unsigned_flag, longlong *l, decimal_round_mode round_type= HALF_UP); inline int my_decimal2double(uint, const decimal_t *d, double *result) { /* No need to call check_result as this will always succeed */ return decimal2double(d, result); } inline int str2my_decimal(uint mask, const char *str, my_decimal *d, char **end) { return check_result_and_overflow(mask, string2decimal(str, d, end), d); } int str2my_decimal(uint mask, const char *from, size_t length, CHARSET_INFO *charset, my_decimal *decimal_value, const char **end); inline int str2my_decimal(uint mask, const char *from, size_t length, CHARSET_INFO *charset, my_decimal *decimal_value) { const char *end; return str2my_decimal(mask, from, length, charset, decimal_value, &end); } #if defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) inline int string2my_decimal(uint mask, const String *str, my_decimal *d) { const char *end; return str2my_decimal(mask, str->ptr(), str->length(), str->charset(), d, &end); } my_decimal *date2my_decimal(const MYSQL_TIME *ltime, my_decimal *dec); #endif /*defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) */ inline int double2my_decimal(uint mask, double val, my_decimal *d) { return check_result_and_overflow(mask, double2decimal(val, d), d); } inline int int2my_decimal(uint mask, longlong i, my_bool unsigned_flag, my_decimal *d) { return check_result(mask, (unsigned_flag ? ulonglong2decimal((ulonglong)i, d) : longlong2decimal(i, d))); } inline void decimal2my_decimal(decimal_t *from, my_decimal *to) { DBUG_ASSERT(to->len >= from->len); to->intg= from->intg; to->frac= from->frac; to->sign(from->sign); memcpy(to->buf, from->buf, to->len*sizeof(decimal_digit_t)); } inline void my_decimal_neg(decimal_t *arg) { if (decimal_is_zero(arg)) { arg->sign= 0; return; } decimal_neg(arg); } inline int my_decimal_add(uint mask, my_decimal *res, const my_decimal *a, const my_decimal *b) { return check_result_and_overflow(mask, decimal_add(a, b, res), res); } inline int my_decimal_sub(uint mask, my_decimal *res, const my_decimal *a, const my_decimal *b) { return check_result_and_overflow(mask, decimal_sub(a, b, res), res); } inline int my_decimal_mul(uint mask, my_decimal *res, const my_decimal *a, const my_decimal *b) { return check_result_and_overflow(mask, decimal_mul(a, b, res), res); } inline int my_decimal_div(uint mask, my_decimal *res, const my_decimal *a, const my_decimal *b, int div_scale_inc) { return check_result_and_overflow(mask, decimal_div(a, b, res, div_scale_inc), res); } inline int my_decimal_mod(uint mask, my_decimal *res, const my_decimal *a, const my_decimal *b) { return check_result_and_overflow(mask, decimal_mod(a, b, res), res); } /** @return -1 if ab and 0 if a==b */ inline int my_decimal_cmp(const my_decimal *a, const my_decimal *b) { return decimal_cmp(a, b); } inline int my_decimal_intg(const my_decimal *a) { return decimal_intg(a); } void my_decimal_trim(ulonglong *precision, decimal_digits_t *scale); #endif /*my_decimal_h*/ mysql/server/private/event_parse_data.h000064400000005523151027430560014356 0ustar00/* Copyright (c) 2008, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _EVENT_PARSE_DATA_H_ #define _EVENT_PARSE_DATA_H_ #include "sql_alloc.h" class Item; class THD; class sp_name; #define EVEX_GET_FIELD_FAILED -2 #define EVEX_BAD_PARAMS -5 #define EVEX_MICROSECOND_UNSUP -6 #define EVEX_MAX_INTERVAL_VALUE 1000000000L class Event_parse_data : public Sql_alloc { public: /* ENABLED = feature can function normally (is turned on) SLAVESIDE_DISABLED = feature is turned off on slave DISABLED = feature is turned off */ enum enum_status { ENABLED = 1, DISABLED, SLAVESIDE_DISABLED }; enum enum_on_completion { /* On CREATE EVENT, DROP is the DEFAULT as per the docs. On ALTER EVENT, "no change" is the DEFAULT. */ ON_COMPLETION_DEFAULT = 0, ON_COMPLETION_DROP, ON_COMPLETION_PRESERVE }; int on_completion; int status; bool status_changed; uint32 originator; /* do_not_create will be set if STARTS time is in the past and on_completion == ON_COMPLETION_DROP. */ bool do_not_create; bool body_changed; LEX_CSTRING dbname; LEX_CSTRING name; LEX_CSTRING definer;// combination of user and host LEX_CSTRING comment; Item* item_starts; Item* item_ends; Item* item_execute_at; my_time_t starts; my_time_t ends; my_time_t execute_at; bool starts_null; bool ends_null; bool execute_at_null; sp_name *identifier; Item* item_expression; longlong expression; interval_type interval; static Event_parse_data * new_instance(THD *thd); bool check_parse_data(THD *thd); bool check_dates(THD *thd, int previous_on_completion); private: void init_definer(THD *thd); void init_name(THD *thd, sp_name *spn); int init_execute_at(THD *thd); int init_interval(THD *thd); int init_starts(THD *thd); int init_ends(THD *thd); Event_parse_data(); ~Event_parse_data(); void report_bad_value(const char *item_name, Item *bad_item); void check_if_in_the_past(THD *thd, my_time_t ltime_utc); Event_parse_data(const Event_parse_data &); /* Prevent use of these */ void check_originator_id(THD *thd); void operator=(Event_parse_data &); }; #endif mysql/server/private/sql_rename.h000064400000001726151027430560013201 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_RENAME_INCLUDED #define SQL_RENAME_INCLUDED class THD; struct TABLE_LIST; bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent, bool if_exists); #endif /* SQL_RENAME_INCLUDED */ mysql/server/private/assume_aligned.h000064400000004456151027430560014036 0ustar00/* Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once #include #include #ifdef _MSC_VER template static inline T my_assume_aligned(T ptr) { assert(reinterpret_cast(ptr) % Alignment == 0); __assume(reinterpret_cast(ptr) % Alignment == 0); return ptr; } #else template static inline T my_assume_aligned(T ptr) { assert(reinterpret_cast(ptr) % Alignment == 0); return static_cast(__builtin_assume_aligned(ptr, Alignment)); } #endif template inline void *memcpy_aligned(void *dest, const void *src, size_t n) { static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); return std::memcpy(my_assume_aligned(dest), my_assume_aligned(src), n); } template inline void *memmove_aligned(void *dest, const void *src, size_t n) { static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); return std::memmove(my_assume_aligned(dest), my_assume_aligned(src), n); } template inline int memcmp_aligned(const void *s1, const void *s2, size_t n) { static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); return std::memcmp(my_assume_aligned(s1), my_assume_aligned(s2), n); } template inline void *memset_aligned(void *s, int c, size_t n) { static_assert(Alignment && !(Alignment & (Alignment - 1)), "power of 2"); return std::memset(my_assume_aligned(s), c, n); } mysql/server/private/sql_analyse.h000064400000025565151027430560013375 0ustar00#ifndef SQL_ANALYSE_INCLUDED #define SQL_ANALYSE_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Analyse database */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "procedure.h" /* Procedure */ #define my_thd_charset default_charset_info #define DEC_IN_AVG 4 typedef struct st_number_info { // if zerofill is true, the number must be zerofill, or string bool negative, is_float, zerofill, maybe_zerofill; int8 integers; int8 decimals; double dval; ulonglong ullval; } NUM_INFO; typedef struct st_extreme_value_number_info { ulonglong ullval; longlong llval; double max_dval, min_dval; } EV_NUM_INFO; typedef struct st_tree_info { bool found; String *str; Item *item; } TREE_INFO; uint check_ulonglong(const char *str, uint length); bool get_ev_num_info(EV_NUM_INFO *ev_info, NUM_INFO *info, const char *num); bool test_if_number(NUM_INFO *info, const char *str, uint str_len); int compare_double(const double *s, const double *t); int compare_double2(void *, const void *s, const void *t); int compare_longlong(const longlong *s, const longlong *t); int compare_longlong2(void *, const void *s, const void *t); int compare_ulonglong(const ulonglong *s, const ulonglong *t); int compare_ulonglong2(void *, const void *s, const void *t); int compare_decimal2(void *len, const void *s, const void *t); Procedure *proc_analyse_init(THD *thd, ORDER *param, select_result *result, List &field_list); int free_string(void* str, TREE_FREE, void*); class analyse; class field_info :public Sql_alloc { protected: ulong treemem, tree_elements, empty, nulls, min_length, max_length; uint room_in_tree; bool found; TREE tree; Item *item; analyse *pc; public: field_info(Item* a, analyse* b) : treemem(0), tree_elements(0), empty(0), nulls(0), min_length(0), max_length(0), room_in_tree(1), found(0),item(a), pc(b) {}; virtual ~field_info() { delete_tree(&tree, 0); } virtual void add() = 0; virtual void get_opt_type(String*, ha_rows) = 0; virtual String *get_min_arg(String *) = 0; virtual String *get_max_arg(String *) = 0; virtual String *avg(String*, ha_rows) = 0; virtual String *std(String*, ha_rows) = 0; virtual tree_walk_action collect_enum() = 0; virtual uint decimals() { return 0; } friend class analyse; }; int collect_string(void *element, element_count count, void *info); int sortcmp2(void *, const void *a, const void *b); class field_str :public field_info { String min_arg, max_arg; ulonglong sum; bool must_be_blob, was_zero_fill, was_maybe_zerofill, can_be_still_num; NUM_INFO num_info; EV_NUM_INFO ev_num_info; public: field_str(Item* a, analyse* b) :field_info(a,b), min_arg("",0,default_charset_info), max_arg("",0,default_charset_info), sum(0), must_be_blob(0), was_zero_fill(0), was_maybe_zerofill(0), can_be_still_num(1) { init_tree(&tree, 0, 0, sizeof(String), sortcmp2, free_string, NULL, MYF(MY_THREAD_SPECIFIC)); }; void add() override; void get_opt_type(String*, ha_rows) override; String *get_min_arg(String *not_used __attribute__((unused))) override { return &min_arg; } String *get_max_arg(String *not_used __attribute__((unused))) override { return &max_arg; } String *avg(String *s, ha_rows rows) override { if (!(rows - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else s->set_real((ulonglong2double(sum) / ulonglong2double(rows - nulls)), DEC_IN_AVG,my_thd_charset); return s; } friend int collect_string(String *element, element_count count, TREE_INFO *info); tree_walk_action collect_enum() override { return collect_string; } String *std(String *s __attribute__((unused)), ha_rows rows __attribute__((unused))) override { return (String*) 0; } }; int collect_decimal(void *element, element_count count, void *info); class field_decimal :public field_info { my_decimal min_arg, max_arg; my_decimal sum[2], sum_sqr[2]; int cur_sum; int bin_size; public: field_decimal(Item* a, analyse* b) :field_info(a,b) { bin_size= my_decimal_get_binary_size(a->max_length, a->decimals); init_tree(&tree, 0, 0, bin_size, compare_decimal2, 0, (void *) &bin_size, MYF(MY_THREAD_SPECIFIC)); }; void add() override; void get_opt_type(String*, ha_rows) override; String *get_min_arg(String *) override; String *get_max_arg(String *) override; String *avg(String *s, ha_rows rows) override; friend int collect_decimal(uchar *element, element_count count, TREE_INFO *info); tree_walk_action collect_enum() override { return collect_decimal; } String *std(String *s, ha_rows rows) override; }; int collect_real(void *element, element_count count, void *info); class field_real: public field_info { double min_arg, max_arg; double sum, sum_sqr; uint max_notzero_dec_len; public: field_real(Item* a, analyse* b) :field_info(a,b), min_arg(0), max_arg(0), sum(0), sum_sqr(0), max_notzero_dec_len(0) { init_tree(&tree, 0, 0, sizeof(double), compare_double2, NULL, NULL, MYF(MY_THREAD_SPECIFIC)); } void add() override; void get_opt_type(String*, ha_rows) override; String *get_min_arg(String *s) override { s->set_real(min_arg, item->decimals, my_thd_charset); return s; } String *get_max_arg(String *s) override { s->set_real(max_arg, item->decimals, my_thd_charset); return s; } String *avg(String *s, ha_rows rows) override { if (!(rows - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else s->set_real(((double)sum / (double) (rows - nulls)), item->decimals,my_thd_charset); return s; } String *std(String *s, ha_rows rows) override { double tmp = ulonglong2double(rows); if (!(tmp - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else { double tmp2 = ((sum_sqr - sum * sum / (tmp - nulls)) / (tmp - nulls)); s->set_real(((double) tmp2 <= 0.0 ? 0.0 : sqrt(tmp2)), item->decimals,my_thd_charset); } return s; } uint decimals() override { return item->decimals; } friend int collect_real(double *element, element_count count, TREE_INFO *info); tree_walk_action collect_enum() override { return collect_real;} }; int collect_longlong(void *element, element_count count, void *info); class field_longlong: public field_info { longlong min_arg, max_arg; longlong sum, sum_sqr; public: field_longlong(Item* a, analyse* b) :field_info(a,b), min_arg(0), max_arg(0), sum(0), sum_sqr(0) { init_tree(&tree, 0, 0, sizeof(longlong), compare_longlong2, NULL, NULL, MYF(MY_THREAD_SPECIFIC)); } void add() override; void get_opt_type(String*, ha_rows) override; String *get_min_arg(String *s) override { s->set(min_arg,my_thd_charset); return s; } String *get_max_arg(String *s) override { s->set(max_arg,my_thd_charset); return s; } String *avg(String *s, ha_rows rows) override { if (!(rows - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else s->set_real(((double) sum / (double) (rows - nulls)), DEC_IN_AVG,my_thd_charset); return s; } String *std(String *s, ha_rows rows) override { double tmp = ulonglong2double(rows); if (!(tmp - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else { double tmp2 = ((sum_sqr - sum * sum / (tmp - nulls)) / (tmp - nulls)); s->set_real(((double) tmp2 <= 0.0 ? 0.0 : sqrt(tmp2)), DEC_IN_AVG,my_thd_charset); } return s; } friend int collect_longlong(longlong *element, element_count count, TREE_INFO *info); tree_walk_action collect_enum() override { return collect_longlong;} }; int collect_ulonglong(void *element, element_count count, void *info); class field_ulonglong: public field_info { ulonglong min_arg, max_arg; ulonglong sum, sum_sqr; public: field_ulonglong(Item* a, analyse * b) :field_info(a,b), min_arg(0), max_arg(0), sum(0),sum_sqr(0) { init_tree(&tree, 0, 0, sizeof(ulonglong), compare_ulonglong2, NULL, NULL, MYF(MY_THREAD_SPECIFIC)); } void add() override; void get_opt_type(String*, ha_rows) override; String *get_min_arg(String *s) override { s->set(min_arg,my_thd_charset); return s; } String *get_max_arg(String *s) override { s->set(max_arg,my_thd_charset); return s; } String *avg(String *s, ha_rows rows) override { if (!(rows - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else s->set_real((ulonglong2double(sum) / ulonglong2double(rows - nulls)), DEC_IN_AVG,my_thd_charset); return s; } String *std(String *s, ha_rows rows) override { double tmp = ulonglong2double(rows); if (!(tmp - nulls)) s->set_real((double) 0.0, 1,my_thd_charset); else { double tmp2 = ((ulonglong2double(sum_sqr) - ulonglong2double(sum * sum) / (tmp - nulls)) / (tmp - nulls)); s->set_real(((double) tmp2 <= 0.0 ? 0.0 : sqrt(tmp2)), DEC_IN_AVG,my_thd_charset); } return s; } friend int collect_ulonglong(ulonglong *element, element_count count, TREE_INFO *info); tree_walk_action collect_enum() override { return collect_ulonglong; } }; Procedure *proc_analyse_init(THD *thd, ORDER *param, select_result *result, List &field_list); class analyse: public Procedure { protected: Item_proc *func_items[10]; List fields, result_fields; field_info **f_info, **f_end; ha_rows rows; uint output_str_length; public: uint max_tree_elements, max_treemem; analyse(select_result *res) :Procedure(res, PROC_NO_SORT), f_info(0), rows(0), output_str_length(0) {} ~analyse() { if (f_info) { for (field_info **f=f_info; f != f_end; f++) delete (*f); } } void add() override {} bool change_columns(THD *thd, List &fields) override; int send_row(List &field_list) override; void end_group(void) override {} int end_of_records(void) override; friend Procedure *proc_analyse_init(THD *thd, ORDER *param, select_result *result, List &field_list); }; #endif /* SQL_ANALYSE_INCLUDED */ mysql/server/private/probes_mysql.h000064400000001715151027430560013570 0ustar00/* Copyright (c) 2008 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef PROBES_MYSQL_H #define PROBES_MYSQL_H #if defined(HAVE_DTRACE) && !defined(DISABLE_DTRACE) #include "probes_mysql_dtrace.h" #else /* no dtrace */ #include "probes_mysql_nodtrace.h" #endif #endif /* PROBES_MYSQL_H */ mysql/server/private/pfs_stage_provider.h000064400000003024151027430560014731 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_STAGE_PROVIDER_H #define PFS_STAGE_PROVIDER_H /** @file include/pfs_stage_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_STAGE_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_STAGE_CALL(M) pfs_ ## M ## _v1 C_MODE_START void pfs_register_stage_v1(const char *category, PSI_stage_info_v1 **info_array, int count); PSI_stage_progress* pfs_start_stage_v1(PSI_stage_key key, const char *src_file, int src_line); PSI_stage_progress* pfs_get_current_stage_progress_v1(); void pfs_end_stage_v1(); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_STAGE_INTERFACE */ #endif mysql/server/private/debug_sync.h000064400000003776151027430560013204 0ustar00#ifndef DEBUG_SYNC_INCLUDED #define DEBUG_SYNC_INCLUDED /* Copyright (c) 2009, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Declarations for the Debug Sync Facility. See debug_sync.cc for details. */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif class THD; #if defined(ENABLED_DEBUG_SYNC) /* Command line option --debug-sync-timeout. See mysqld.cc. */ extern MYSQL_PLUGIN_IMPORT uint opt_debug_sync_timeout; /* Default WAIT_FOR timeout if command line option is given without argument. */ #define DEBUG_SYNC_DEFAULT_WAIT_TIMEOUT 300 /* Debug Sync prototypes. See debug_sync.cc. */ extern int debug_sync_init(void); extern void debug_sync_end(void); extern void debug_sync_init_thread(THD *thd); extern void debug_sync_end_thread(THD *thd); void debug_sync_reset_thread(THD *thd); extern bool debug_sync_set_action(THD *thd, const char *action_str, size_t len); extern bool debug_sync_update(THD *thd, char *val_str, size_t len); extern uchar *debug_sync_value_ptr(THD *thd); #else static inline void debug_sync_init_thread(THD *thd) {} static inline void debug_sync_end_thread(THD *thd) {} static inline void debug_sync_reset_thread(THD *thd) {} static inline bool debug_sync_set_action(THD *, const char *, size_t) { return false; } #endif /* defined(ENABLED_DEBUG_SYNC) */ #endif /* DEBUG_SYNC_INCLUDED */ mysql/server/private/pfs_idle_provider.h000064400000002551151027430560014547 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_IDLE_PROVIDER_H #define PFS_IDLE_PROVIDER_H /** @file include/pfs_idle_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_IDLE_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_IDLE_CALL(M) pfs_ ## M ## _v1 C_MODE_START PSI_idle_locker* pfs_start_idle_wait_v1(PSI_idle_locker_state* state, const char *src_file, uint src_line); void pfs_end_idle_wait_v1(PSI_idle_locker* locker); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_IDLE_INTERFACE */ #endif mysql/server/private/atomic/generic-msvc.h000064400000007224151027430560014710 0ustar00#ifndef ATOMIC_MSC_INCLUDED #define ATOMIC_MSC_INCLUDED /* Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include static inline int my_atomic_cas32(int32 volatile *a, int32 *cmp, int32 set) { int32 initial_cmp= *cmp; int32 initial_a= InterlockedCompareExchange((volatile LONG*)a, set, initial_cmp); int ret= (initial_a == initial_cmp); if (!ret) *cmp= initial_a; return ret; } static inline int my_atomic_cas64(int64 volatile *a, int64 *cmp, int64 set) { int64 initial_cmp= *cmp; int64 initial_a= InterlockedCompareExchange64((volatile LONGLONG*)a, (LONGLONG)set, (LONGLONG)initial_cmp); int ret= (initial_a == initial_cmp); if (!ret) *cmp= initial_a; return ret; } static inline int my_atomic_casptr(void * volatile *a, void **cmp, void *set) { void *initial_cmp= *cmp; void *initial_a= InterlockedCompareExchangePointer(a, set, initial_cmp); int ret= (initial_a == initial_cmp); if (!ret) *cmp= initial_a; return ret; } static inline int32 my_atomic_add32(int32 volatile *a, int32 v) { return (int32)InterlockedExchangeAdd((volatile LONG*)a, v); } static inline int64 my_atomic_add64(int64 volatile *a, int64 v) { return (int64)InterlockedExchangeAdd64((volatile LONGLONG*)a, (LONGLONG)v); } /* According to MSDN: Simple reads and writes to properly-aligned 32-bit variables are atomic operations. ... Simple reads and writes to properly aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. https://msdn.microsoft.com/en-us/library/windows/desktop/ms684122(v=vs.85).aspx */ static inline int32 my_atomic_load32(int32 volatile *a) { int32 value= *a; MemoryBarrier(); return value; } static inline int64 my_atomic_load64(int64 volatile *a) { #ifdef _M_X64 int64 value= *a; MemoryBarrier(); return value; #else return (int64) InterlockedCompareExchange64((volatile LONGLONG *) a, 0, 0); #endif } static inline void* my_atomic_loadptr(void * volatile *a) { void *value= *a; MemoryBarrier(); return value; } static inline int32 my_atomic_fas32(int32 volatile *a, int32 v) { return (int32)InterlockedExchange((volatile LONG*)a, v); } static inline int64 my_atomic_fas64(int64 volatile *a, int64 v) { return (int64)InterlockedExchange64((volatile LONGLONG*)a, v); } static inline void * my_atomic_fasptr(void * volatile *a, void * v) { return InterlockedExchangePointer(a, v); } static inline void my_atomic_store32(int32 volatile *a, int32 v) { MemoryBarrier(); *a= v; } static inline void my_atomic_store64(int64 volatile *a, int64 v) { #ifdef _M_X64 MemoryBarrier(); *a= v; #else (void) InterlockedExchange64((volatile LONGLONG *) a, v); #endif } static inline void my_atomic_storeptr(void * volatile *a, void *v) { MemoryBarrier(); *a= v; } #endif /* ATOMIC_MSC_INCLUDED */ mysql/server/private/atomic/gcc_builtins.h000064400000007341151027430560014773 0ustar00#ifndef ATOMIC_GCC_BUILTINS_INCLUDED #define ATOMIC_GCC_BUILTINS_INCLUDED /* Copyright (c) 2017 MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #define MY_MEMORY_ORDER_RELAXED __ATOMIC_RELAXED #define MY_MEMORY_ORDER_CONSUME __ATOMIC_CONSUME #define MY_MEMORY_ORDER_ACQUIRE __ATOMIC_ACQUIRE #define MY_MEMORY_ORDER_RELEASE __ATOMIC_RELEASE #define MY_MEMORY_ORDER_ACQ_REL __ATOMIC_ACQ_REL #define MY_MEMORY_ORDER_SEQ_CST __ATOMIC_SEQ_CST #define my_atomic_store32_explicit(P, D, O) __atomic_store_n((P), (D), (O)) #define my_atomic_store64_explicit(P, D, O) __atomic_store_n((P), (D), (O)) #define my_atomic_storeptr_explicit(P, D, O) __atomic_store_n((P), (D), (O)) #define my_atomic_load32_explicit(P, O) __atomic_load_n((P), (O)) #define my_atomic_load64_explicit(P, O) __atomic_load_n((P), (O)) #define my_atomic_loadptr_explicit(P, O) __atomic_load_n((P), (O)) #define my_atomic_fas32_explicit(P, D, O) __atomic_exchange_n((P), (D), (O)) #define my_atomic_fas64_explicit(P, D, O) __atomic_exchange_n((P), (D), (O)) #define my_atomic_fasptr_explicit(P, D, O) __atomic_exchange_n((P), (D), (O)) #define my_atomic_add32_explicit(P, A, O) __atomic_fetch_add((P), (A), (O)) #define my_atomic_add64_explicit(P, A, O) __atomic_fetch_add((P), (A), (O)) #define my_atomic_cas32_weak_explicit(P, E, D, S, F) \ __atomic_compare_exchange_n((P), (E), (D), 1, (S), (F)) #define my_atomic_cas64_weak_explicit(P, E, D, S, F) \ __atomic_compare_exchange_n((P), (E), (D), 1, (S), (F)) #define my_atomic_casptr_weak_explicit(P, E, D, S, F) \ __atomic_compare_exchange_n((P), (E), (D), 1, (S), (F)) #define my_atomic_cas32_strong_explicit(P, E, D, S, F) \ __atomic_compare_exchange_n((P), (E), (D), 0, (S), (F)) #define my_atomic_cas64_strong_explicit(P, E, D, S, F) \ __atomic_compare_exchange_n((P), (E), (D), 0, (S), (F)) #define my_atomic_casptr_strong_explicit(P, E, D, S, F) \ __atomic_compare_exchange_n((P), (E), (D), 0, (S), (F)) #define my_atomic_store32(P, D) __atomic_store_n((P), (D), __ATOMIC_SEQ_CST) #define my_atomic_store64(P, D) __atomic_store_n((P), (D), __ATOMIC_SEQ_CST) #define my_atomic_storeptr(P, D) __atomic_store_n((P), (D), __ATOMIC_SEQ_CST) #define my_atomic_load32(P) __atomic_load_n((P), __ATOMIC_SEQ_CST) #define my_atomic_load64(P) __atomic_load_n((P), __ATOMIC_SEQ_CST) #define my_atomic_loadptr(P) __atomic_load_n((P), __ATOMIC_SEQ_CST) #define my_atomic_fas32(P, D) __atomic_exchange_n((P), (D), __ATOMIC_SEQ_CST) #define my_atomic_fas64(P, D) __atomic_exchange_n((P), (D), __ATOMIC_SEQ_CST) #define my_atomic_fasptr(P, D) __atomic_exchange_n((P), (D), __ATOMIC_SEQ_CST) #define my_atomic_add32(P, A) __atomic_fetch_add((P), (A), __ATOMIC_SEQ_CST) #define my_atomic_add64(P, A) __atomic_fetch_add((P), (A), __ATOMIC_SEQ_CST) #define my_atomic_cas32(P, E, D) \ __atomic_compare_exchange_n((P), (E), (D), 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #define my_atomic_cas64(P, E, D) \ __atomic_compare_exchange_n((P), (E), (D), 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #define my_atomic_casptr(P, E, D) \ __atomic_compare_exchange_n((P), (E), (D), 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #endif /* ATOMIC_GCC_BUILTINS_INCLUDED */ mysql/server/private/atomic/solaris.h000064400000006125151027430560014001 0ustar00#ifndef ATOMIC_SOLARIS_INCLUDED #define ATOMIC_SOLARIS_INCLUDED /* Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include #if defined(__GNUC__) #define atomic_typeof(T,V) __typeof__(V) #else #define atomic_typeof(T,V) T #endif static inline int my_atomic_cas32(int32 volatile *a, int32 *cmp, int32 set) { int ret; atomic_typeof(uint32_t, *cmp) sav; sav= atomic_cas_32((volatile uint32_t *)a, (uint32_t)*cmp, (uint32_t)set); ret= (sav == *cmp); if (!ret) *cmp= sav; return ret; } static inline int my_atomic_cas64(int64 volatile *a, int64 *cmp, int64 set) { int ret; atomic_typeof(uint64_t, *cmp) sav; sav= atomic_cas_64((volatile uint64_t *)a, (uint64_t)*cmp, (uint64_t)set); ret= (sav == *cmp); if (!ret) *cmp= sav; return ret; } static inline int my_atomic_casptr(void * volatile *a, void **cmp, void *set) { int ret; atomic_typeof(void *, *cmp) sav; sav= atomic_cas_ptr((volatile void **)a, (void *)*cmp, (void *)set); ret= (sav == *cmp); if (!ret) *cmp= sav; return ret; } static inline int32 my_atomic_add32(int32 volatile *a, int32 v) { int32 nv= atomic_add_32_nv((volatile uint32_t *)a, v); return nv - v; } static inline int64 my_atomic_add64(int64 volatile *a, int64 v) { int64 nv= atomic_add_64_nv((volatile uint64_t *)a, v); return nv - v; } static inline int32 my_atomic_fas32(int32 volatile *a, int32 v) { return atomic_swap_32((volatile uint32_t *)a, (uint32_t)v); } static inline int64 my_atomic_fas64(int64 volatile *a, int64 v) { return atomic_swap_64((volatile uint64_t *)a, (uint64_t)v); } static inline void * my_atomic_fasptr(void * volatile *a, void * v) { return atomic_swap_ptr(a, v); } static inline int32 my_atomic_load32(int32 volatile *a) { return atomic_or_32_nv((volatile uint32_t *)a, 0); } static inline int64 my_atomic_load64(int64 volatile *a) { return atomic_or_64_nv((volatile uint64_t *)a, 0); } static inline void* my_atomic_loadptr(void * volatile *a) { return atomic_add_ptr_nv(a, 0); } static inline void my_atomic_store32(int32 volatile *a, int32 v) { (void) atomic_swap_32((volatile uint32_t *)a, (uint32_t)v); } static inline void my_atomic_store64(int64 volatile *a, int64 v) { (void) atomic_swap_64((volatile uint64_t *)a, (uint64_t)v); } static inline void my_atomic_storeptr(void * volatile *a, void *v) { (void) atomic_swap_ptr((volatile void **)a, (void *)v); } #endif /* ATOMIC_SOLARIS_INCLUDED */ mysql/server/private/rpl_reporting.h000064400000007201151027430560013733 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_REPORTING_H #define RPL_REPORTING_H #include /* loglevel */ /** Maximum size of an error message from a slave thread. */ #define MAX_SLAVE_ERRMSG 1024 /** Mix-in to handle the message logging and reporting for relay log info and master log info structures. By inheriting from this class, the class is imbued with capabilities to do slave reporting. */ class Slave_reporting_capability { public: /** lock used to synchronize m_last_error on 'SHOW SLAVE STATUS' **/ mutable mysql_mutex_t err_lock; /** Constructor. @param thread_name Printable name of the slave thread that is reporting. */ Slave_reporting_capability(char const *thread_name); mutable my_thread_id err_thread_id; /** Writes a message and, if it's an error message, to Last_Error (which will be displayed by SHOW SLAVE STATUS). @param level The severity level @param err_code The error code @param msg The message (usually related to the error code, but can contain more information), in printf() format. */ void report(loglevel level, int err_code, const char *extra_info, const char *msg, ...) const ATTRIBUTE_FORMAT(printf, 5, 6); /** Clear errors. They will not show up under SHOW SLAVE STATUS. */ void clear_error() { mysql_mutex_lock(&err_lock); m_last_error.clear(); mysql_mutex_unlock(&err_lock); } /** Error information structure. */ class Error { friend class Slave_reporting_capability; public: Error() { clear(); } void clear() { number= 0; message[0]= '\0'; timestamp[0]= '\0'; } void update_timestamp() { struct tm tm_tmp; struct tm *start; skr= my_time(0); localtime_r(&skr, &tm_tmp); start=&tm_tmp; snprintf(timestamp, sizeof(timestamp), "%02d%02d%02d %02d:%02d:%02d", start->tm_year % 100, start->tm_mon+1, start->tm_mday, start->tm_hour, start->tm_min, start->tm_sec); timestamp[15]= '\0'; } /** Error code */ uint32 number; /** Error message */ char message[MAX_SLAVE_ERRMSG]; /** Error timestamp as string */ char timestamp[64]; /** Error timestamp as time_t variable. Used in performance_schema */ time_t skr; }; Error const& last_error() const { return m_last_error; } virtual ~Slave_reporting_capability()= 0; private: /** Last error produced by the I/O or SQL thread respectively. */ mutable Error m_last_error; char const *const m_thread_name; // not implemented Slave_reporting_capability(const Slave_reporting_capability& rhs); Slave_reporting_capability& operator=(const Slave_reporting_capability& rhs); }; #endif // RPL_REPORTING_H mysql/server/private/my_atomic_wrapper.h000064400000005753151027430560014600 0ustar00/* Copyright (c) 2020, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once #ifdef __cplusplus #include /** A wrapper for std::atomic, defaulting to std::memory_order_relaxed. When it comes to atomic loads or stores at std::memory_order_relaxed on IA-32 or AMD64, this wrapper is only introducing some constraints to the C++ compiler, to prevent some optimizations of loads or stores. On POWER and ARM, atomic loads and stores involve different instructions from normal loads and stores and will thus incur some overhead. Because atomic read-modify-write operations will always incur overhead, we intentionally do not define operator++(), operator--(), operator+=(), operator-=(), or similar, to make the overhead stand out in the users of this code. */ template class Atomic_relaxed { std::atomic m; public: Atomic_relaxed(const Atomic_relaxed &rhs) { m.store(rhs, std::memory_order_relaxed); } Atomic_relaxed(Type val) : m(val) {} Atomic_relaxed() = default; Type load(std::memory_order o= std::memory_order_relaxed) const { return m.load(o); } void store(Type i, std::memory_order o= std::memory_order_relaxed) { m.store(i, o); } operator Type() const { return m.load(); } Type operator=(const Type i) { store(i); return i; } Type operator=(const Atomic_relaxed &rhs) { return *this= Type{rhs}; } Type operator+=(const Type i) { return fetch_add(i); } Type fetch_add(const Type i, std::memory_order o= std::memory_order_relaxed) { return m.fetch_add(i, o); } Type fetch_sub(const Type i, std::memory_order o= std::memory_order_relaxed) { return m.fetch_sub(i, o); } Type fetch_xor(const Type i, std::memory_order o= std::memory_order_relaxed) { return m.fetch_xor(i, o); } Type fetch_and(const Type i, std::memory_order o= std::memory_order_relaxed) { return m.fetch_and(i, o); } Type fetch_or(const Type i, std::memory_order o= std::memory_order_relaxed) { return m.fetch_or(i, o); } bool compare_exchange_strong(Type& i1, const Type i2, std::memory_order o1= std::memory_order_relaxed, std::memory_order o2= std::memory_order_relaxed) { return m.compare_exchange_strong(i1, i2, o1, o2); } Type exchange(const Type i, std::memory_order o= std::memory_order_relaxed) { return m.exchange(i, o); } }; #endif /* __cplusplus */ mysql/server/private/table_cache.h000064400000010210151027430560013251 0ustar00#ifndef TABLE_CACHE_H_INCLUDED #define TABLE_CACHE_H_INCLUDED /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2010, 2011 Monty Program Ab Copyright (C) 2013 Sergey Vojtovich and MariaDB Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ struct Share_free_tables { typedef I_P_List List; List list; /** Avoid false sharing between instances */ char pad[CPU_LEVEL1_DCACHE_LINESIZE]; }; struct TDC_element { uchar m_key[NAME_LEN + 1 + NAME_LEN + 1]; uint m_key_length; bool flushed; TABLE_SHARE *share; /** Protects ref_count, m_flush_tickets, all_tables, flushed, all_tables_refs. */ mysql_mutex_t LOCK_table_share; mysql_cond_t COND_release; TDC_element *next, **prev; /* Link to unused shares */ uint ref_count; /* How many TABLE objects uses this */ uint all_tables_refs; /* Number of refs to all_tables */ /** List of tickets representing threads waiting for the share to be flushed. */ Wait_for_flush_list m_flush_tickets; /* Doubly-linked (back-linked) lists of used and unused TABLE objects for this share. */ All_share_tables_list all_tables; /** Avoid false sharing between TDC_element and free_tables */ char pad[CPU_LEVEL1_DCACHE_LINESIZE]; Share_free_tables free_tables[1]; inline void wait_for_refs(uint my_refs); void flush(THD *thd, bool mark_flushed); void flush_unused(bool mark_flushed); }; extern ulong tdc_size; extern ulong tc_size; extern uint32 tc_instances; extern bool tdc_init(void); extern void tdc_start_shutdown(void); extern void tdc_deinit(void); extern ulong tdc_records(void); extern void tdc_purge(bool all); extern TDC_element *tdc_lock_share(THD *thd, const char *db, const char *table_name); extern void tdc_unlock_share(TDC_element *element); int tdc_share_is_cached(THD *thd, const char *db, const char *table_name); extern TABLE_SHARE *tdc_acquire_share(THD *thd, TABLE_LIST *tl, uint flags, TABLE **out_table= 0); extern void tdc_release_share(TABLE_SHARE *share); void tdc_remove_referenced_share(THD *thd, TABLE_SHARE *share); void tdc_remove_table(THD *thd, const char *db, const char *table_name); extern int tdc_wait_for_old_version(THD *thd, const char *db, const char *table_name, ulong wait_timeout, uint deadlock_weight); extern int tdc_iterate(THD *thd, my_hash_walk_action action, void *argument, bool no_dups= false); extern uint tc_records(void); int show_tc_active_instances(THD *thd, SHOW_VAR *var, void *buff, system_status_var *, enum enum_var_type scope); extern void tc_purge(); extern void tc_add_table(THD *thd, TABLE *table); extern void tc_release_table(TABLE *table); extern TABLE *tc_acquire_table(THD *thd, TDC_element *element); /** Create a table cache key for non-temporary table. @param key Buffer for key (must be at least NAME_LEN*2+2 bytes). @param db Database name. @param table_name Table name. @return Length of key. */ inline uint tdc_create_key(char *key, const char *db, const char *table_name) { /* In theory caller should ensure that both db and table_name are not longer than NAME_LEN bytes. In practice we play safe to avoid buffer overruns. */ return (uint) (strmake(strmake(key, db, NAME_LEN) + 1, table_name, NAME_LEN) - key + 1); } #endif /* TABLE_CACHE_H_INCLUDED */ mysql/server/private/sp_head.h000064400000175775151027430560012476 0ustar00/* -*- C++ -*- */ /* Copyright (c) 2002, 2011, Oracle and/or its affiliates. Copyright (c) 2020, 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _SP_HEAD_H_ #define _SP_HEAD_H_ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif /* It is necessary to include set_var.h instead of item.h because there are dependencies on include order for set_var.h and item.h. This will be resolved later. */ #include "sql_class.h" // THD, set_var.h: THD #include "set_var.h" // Item #include "sp_pcontext.h" // sp_pcontext #include #include "sp.h" /** @defgroup Stored_Routines Stored Routines @ingroup Runtime_Environment @{ */ uint sp_get_flags_for_command(LEX *lex); class sp_instr; class sp_instr_opt_meta; class sp_instr_jump_if_not; /** Number of PSI_statement_info instruments for internal stored programs statements. */ #ifdef HAVE_PSI_INTERFACE void init_sp_psi_keys(void); #endif /*************************************************************************/ /** Stored_program_creation_ctx -- base class for creation context of stored programs (stored routines, triggers, events). */ class Stored_program_creation_ctx :public Default_object_creation_ctx { public: CHARSET_INFO *get_db_cl() { return m_db_cl; } public: virtual Stored_program_creation_ctx *clone(MEM_ROOT *mem_root) = 0; protected: Stored_program_creation_ctx(THD *thd) : Default_object_creation_ctx(thd), m_db_cl(thd->variables.collation_database) { } Stored_program_creation_ctx(CHARSET_INFO *client_cs, CHARSET_INFO *connection_cl, CHARSET_INFO *db_cl) : Default_object_creation_ctx(client_cs, connection_cl), m_db_cl(db_cl) { } protected: void change_env(THD *thd) const override { thd->variables.collation_database= m_db_cl; Default_object_creation_ctx::change_env(thd); } protected: /** db_cl stores the value of the database collation. Both character set and collation attributes are used. Database collation is included into the context because it defines the default collation for stored-program variables. */ CHARSET_INFO *m_db_cl; }; /*************************************************************************/ class sp_name : public Sql_alloc, public Database_qualified_name { public: bool m_explicit_name; /**< Prepend the db name? */ sp_name(const LEX_CSTRING *db, const LEX_CSTRING *name, bool use_explicit_name) : Database_qualified_name(db, name), m_explicit_name(use_explicit_name) { if (lower_case_table_names && m_db.length) m_db.length= my_casedn_str(files_charset_info, (char*) m_db.str); } /** Create temporary sp_name object from MDL key. Store in qname_buff */ sp_name(const MDL_key *key, char *qname_buff); ~sp_name() = default; }; bool check_routine_name(const LEX_CSTRING *ident); class sp_head :private Query_arena, public Database_qualified_name, public Sql_alloc { sp_head(const sp_head &)= delete; void operator=(sp_head &)= delete; protected: MEM_ROOT main_mem_root; #ifdef PROTECT_STATEMENT_MEMROOT /* The following data member is wholly for debugging purpose. It can be used for possible crash analysis to determine how many times the stored routine was executed before the mem_root marked read_only was requested for a memory chunk. Additionally, a value of this data member is output to the log with DBUG_PRINT. */ ulong executed_counter; #endif public: /** Possible values of m_flags */ enum { HAS_RETURN= 1, // For FUNCTIONs only: is set if has RETURN MULTI_RESULTS= 8, // Is set if a procedure with SELECT(s) CONTAINS_DYNAMIC_SQL= 16, // Is set if a procedure with PREPARE/EXECUTE IS_INVOKED= 32, // Is set if this sp_head is being used HAS_SET_AUTOCOMMIT_STMT= 64,// Is set if a procedure with 'set autocommit' /* Is set if a procedure with COMMIT (implicit or explicit) | ROLLBACK */ HAS_COMMIT_OR_ROLLBACK= 128, LOG_SLOW_STATEMENTS= 256, // Used by events LOG_GENERAL_LOG= 512, // Used by events HAS_SQLCOM_RESET= 1024, HAS_SQLCOM_FLUSH= 2048, /** Marks routines that directly (i.e. not by calling other routines) change tables. Note that this flag is set automatically based on type of statements used in the stored routine and is different from routine characteristic provided by user in a form of CONTAINS SQL, READS SQL DATA, MODIFIES SQL DATA clauses. The latter are accepted by parser but pretty much ignored after that. We don't rely on them: a) for compatibility reasons. b) because in CONTAINS SQL case they don't provide enough information anyway. */ MODIFIES_DATA= 4096, /* Marks routines that have column type references: DECLARE a t1.a%TYPE; */ HAS_COLUMN_TYPE_REFS= 8192, /* Set if has FETCH GROUP NEXT ROW instr. Used to ensure that only functions with AGGREGATE keyword use the instr. */ HAS_AGGREGATE_INSTR= 16384 }; sp_package *m_parent; const Sp_handler *m_handler; uint m_flags; // Boolean attributes of a stored routine /** Instrumentation interface for SP. */ PSI_sp_share *m_sp_share; Column_definition m_return_field_def; /**< This is used for FUNCTIONs only. */ const char *m_tmp_query; ///< Temporary pointer to sub query string private: /* Private to guarantee that m_chistics.comment is properly set to: - a string which is alloced on this->mem_root - or (NULL,0) set_chistics() makes sure this. */ Sp_chistics m_chistics; void set_chistics(const st_sp_chistics &chistics); inline void set_chistics_agg_type(enum enum_sp_aggregate_type type) { m_chistics.agg_type= type; } public: sql_mode_t m_sql_mode; ///< For SHOW CREATE and execution bool m_explicit_name; /**< Prepend the db name? */ LEX_CSTRING m_qname; ///< db.name LEX_CSTRING m_params; LEX_CSTRING m_body; LEX_CSTRING m_body_utf8; LEX_CSTRING m_defstr; AUTHID m_definer; const st_sp_chistics &chistics() const { return m_chistics; } const LEX_CSTRING &comment() const { return m_chistics.comment; } void set_suid(enum_sp_suid_behaviour suid) { m_chistics.suid= suid; } enum_sp_suid_behaviour suid() const { return m_chistics.suid; } bool detistic() const { return m_chistics.detistic; } enum_sp_data_access daccess() const { return m_chistics.daccess; } enum_sp_aggregate_type agg_type() const { return m_chistics.agg_type; } /** Is this routine being executed? */ virtual bool is_invoked() const { return m_flags & IS_INVOKED; } /** Get the value of the SP cache version, as remembered when the routine was inserted into the cache. */ ulong sp_cache_version() const; /** Set the value of the SP cache version. */ void set_sp_cache_version(ulong version_arg) const { m_sp_cache_version= version_arg; } sp_rcontext *rcontext_create(THD *thd, Field *retval, List *args); sp_rcontext *rcontext_create(THD *thd, Field *retval, Item **args, uint arg_count); sp_rcontext *rcontext_create(THD *thd, Field *retval, Row_definition_list *list, bool switch_security_ctx); bool eq_routine_spec(const sp_head *) const; private: /** Version of the stored routine cache at the moment when the routine was added to it. Is used only for functions and procedures, not used for triggers or events. When sp_head is created, its version is 0. When it's added to the cache, the version is assigned the global value 'Cversion'. If later on Cversion is incremented, we know that the routine is obsolete and should not be used -- sp_cache_flush_obsolete() will purge it. */ mutable ulong m_sp_cache_version; Stored_program_creation_ctx *m_creation_ctx; /** Boolean combination of (1<clone(mem_root); } longlong m_created; longlong m_modified; /** Recursion level of the current SP instance. The levels are numbered from 0 */ ulong m_recursion_level; /** A list of diferent recursion level instances for the same procedure. For every recursion level we have a sp_head instance. This instances connected in the list. The list ordered by increasing recursion level (m_recursion_level). */ sp_head *m_next_cached_sp; /** Pointer to the first element of the above list */ sp_head *m_first_instance; /** Pointer to the first free (non-INVOKED) routine in the list of cached instances for this SP. This pointer is set only for the first SP in the list of instences (see above m_first_cached_sp pointer). The pointer equal to 0 if we have no free instances. For non-first instance value of this pointer meanless (point to itself); */ sp_head *m_first_free_instance; /** Pointer to the last element in the list of instances of the SP. For non-first instance value of this pointer meanless (point to itself); */ sp_head *m_last_cached_sp; /** Set containing names of stored routines used by this routine. Note that unlike elements of similar set for statement elements of this set are not linked in one list. Because of this we are able save memory by using for this set same objects that are used in 'sroutines' sets for statements of which this stored routine consists. */ HASH m_sroutines; // Pointers set during parsing const char *m_param_begin; const char *m_param_end; private: /* A pointer to the body start inside the cpp buffer. Used only during parsing. Should be removed eventually. The affected functions/methods should be fixed to get the cpp body start as a parameter, rather than through this member. */ const char *m_cpp_body_begin; public: /* Security context for stored routine which should be run under definer privileges. */ Security_context m_security_ctx; /** List of all items (Item_trigger_field objects) representing fields in old/new version of row in trigger. We use this list for checking whenever all such fields are valid at trigger creation time and for binding these fields to TABLE object at table open (although for latter pointer to table being opened is probably enough). */ SQL_I_List m_trg_table_fields; protected: sp_head(MEM_ROOT *mem_root, sp_package *parent, const Sp_handler *handler, enum_sp_aggregate_type agg_type); virtual ~sp_head(); public: static void destroy(sp_head *sp); static sp_head *create(sp_package *parent, const Sp_handler *handler, enum_sp_aggregate_type agg_type); /// Initialize after we have reset mem_root void init(LEX *lex); /** Copy sp name from parser. */ void init_sp_name(const sp_name *spname); /** Set the body-definition start position. */ void set_body_start(THD *thd, const char *cpp_body_start); /** Set the statement-definition (body-definition) end position. */ void set_stmt_end(THD *thd, const char *cpp_body_end); bool execute_trigger(THD *thd, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name, GRANT_INFO *grant_info); bool execute_function(THD *thd, Item **args, uint argcount, Field *return_fld, sp_rcontext **nctx, Query_arena *call_arena); bool execute_procedure(THD *thd, List *args); static void show_create_routine_get_fields(THD *thd, const Sp_handler *sph, List *fields); bool show_create_routine(THD *thd, const Sp_handler *sph); MEM_ROOT *get_main_mem_root() { return &main_mem_root; } int add_instr(sp_instr *instr); bool add_instr_jump(THD *thd, sp_pcontext *spcont); bool add_instr_jump(THD *thd, sp_pcontext *spcont, uint dest); bool add_instr_jump_forward_with_backpatch(THD *thd, sp_pcontext *spcont, sp_label *lab); bool add_instr_jump_forward_with_backpatch(THD *thd, sp_pcontext *spcont) { return add_instr_jump_forward_with_backpatch(thd, spcont, spcont->last_label()); } bool add_instr_freturn(THD *thd, sp_pcontext *spcont, Item *item, LEX *lex); bool add_instr_preturn(THD *thd, sp_pcontext *spcont); Item *adjust_assignment_source(THD *thd, Item *val, Item *val2); /** @param thd - the current thd @param spcont - the current parse context @param spv - the SP variable @param val - the value to be assigned to the variable @param lex - the LEX that was used to create "val" @param responsible_to_free_lex - if the generated sp_instr_set should free "lex". @retval true - on error @retval false - on success */ bool set_local_variable(THD *thd, sp_pcontext *spcont, const Sp_rcontext_handler *rh, sp_variable *spv, Item *val, LEX *lex, bool responsible_to_free_lex); bool set_local_variable_row_field(THD *thd, sp_pcontext *spcont, const Sp_rcontext_handler *rh, sp_variable *spv, uint field_idx, Item *val, LEX *lex); bool set_local_variable_row_field_by_name(THD *thd, sp_pcontext *spcont, const Sp_rcontext_handler *rh, sp_variable *spv, const LEX_CSTRING *field_name, Item *val, LEX *lex); bool check_package_routine_end_name(const LEX_CSTRING &end_name) const; bool check_standalone_routine_end_name(const sp_name *end_name) const; bool check_group_aggregate_instructions_function() const; bool check_group_aggregate_instructions_forbid() const; bool check_group_aggregate_instructions_require() const; private: /** Generate a code to set a single cursor parameter variable. @param thd - current thd, for mem_root allocations. @param param_spcont - the context of the parameter block @param idx - the index of the parameter @param prm - the actual parameter (contains information about the assignment source expression Item, its free list, and its LEX) */ bool add_set_cursor_param_variable(THD *thd, sp_pcontext *param_spcont, uint idx, sp_assignment_lex *prm) { DBUG_ASSERT(idx < param_spcont->context_var_count()); sp_variable *spvar= param_spcont->get_context_variable(idx); /* add_instr() gets free_list from m_thd->free_list. Initialize it before the set_local_variable() call. */ DBUG_ASSERT(m_thd->free_list == NULL); m_thd->free_list= prm->get_free_list(); if (set_local_variable(thd, param_spcont, &sp_rcontext_handler_local, spvar, prm->get_item(), prm, true)) return true; /* Safety: The item and its free_list are now fully owned by the sp_instr_set instance, created by set_local_variable(). The sp_instr_set instance is now responsible for freeing the item and the free_list. Reset the "item" and the "free_list" members of "prm", to avoid double pointers to the same objects from "prm" and from the sp_instr_set instance. */ prm->set_item_and_free_list(NULL, NULL); return false; } /** Generate a code to set all cursor parameter variables. This method is called only when parameters exists, and the number of formal parameters matches the number of actual parameters. See also comments to add_open_cursor(). */ bool add_set_cursor_param_variables(THD *thd, sp_pcontext *param_spcont, List *parameters) { DBUG_ASSERT(param_spcont->context_var_count() == parameters->elements); sp_assignment_lex *prm; List_iterator li(*parameters); for (uint idx= 0; (prm= li++); idx++) { if (add_set_cursor_param_variable(thd, param_spcont, idx, prm)) return true; } return false; } /** Generate a code to set all cursor parameter variables for a FOR LOOP, e.g.: FOR index IN cursor(1,2,3) @param */ bool add_set_for_loop_cursor_param_variables(THD *thd, sp_pcontext *param_spcont, sp_assignment_lex *param_lex, Item_args *parameters); public: /** Generate a code for an "OPEN cursor" statement. @param thd - current thd, for mem_root allocations @param spcont - the context of the cursor @param offset - the offset of the cursor @param param_spcont - the context of the cursor parameter block @param parameters - the list of the OPEN actual parameters The caller must make sure that the number of local variables in "param_spcont" (formal parameters) matches the number of list elements in "parameters" (actual parameters). NULL in either of them means 0 parameters. */ bool add_open_cursor(THD *thd, sp_pcontext *spcont, uint offset, sp_pcontext *param_spcont, List *parameters); /** Generate an initiation code for a CURSOR FOR LOOP, e.g.: FOR index IN cursor -- cursor without parameters FOR index IN cursor(1,2,3) -- cursor with parameters The code generated by this method does the following during SP run-time: - Sets all cursor parameter vartiables from "parameters" - Initializes the index ROW-type variable from the cursor (the structure is copied from the cursor to the index variable) - The cursor gets opened - The first records is fetched from the cursor to the variable "index". @param thd - the current thread (for mem_root and error reporting) @param spcont - the current parse context @param index - the loop "index" ROW-type variable @param pcursor - the cursor @param coffset - the cursor offset @param param_lex - the LEX that owns Items in "parameters" @param parameters - the cursor parameters Item array @retval true - on error (EOM) @retval false - on success */ bool add_for_loop_open_cursor(THD *thd, sp_pcontext *spcont, sp_variable *index, const sp_pcursor *pcursor, uint coffset, sp_assignment_lex *param_lex, Item_args *parameters); /** Returns true if any substatement in the routine directly (not through another routine) modifies data/changes table. @sa Comment for MODIFIES_DATA flag. */ bool modifies_data() const { return m_flags & MODIFIES_DATA; } inline uint instructions() { return m_instr.elements; } inline sp_instr * last_instruction() { sp_instr *i; get_dynamic(&m_instr, (uchar*)&i, m_instr.elements-1); return i; } bool replace_instr_to_nop(THD *thd, uint ip); /* Resets lex in 'thd' and keeps a copy of the old one. @todo Conflicting comment in sp_head.cc */ bool reset_lex(THD *thd); bool reset_lex(THD *thd, sp_lex_local *sublex); /** Merge two LEX instances. @param oldlex - the upper level LEX we're going to restore to. @param sublex - the local lex that have just parsed some substatement. @returns - false on success, true on error (e.g. failed to merge the routine list or the table list). This method is shared by: - restore_lex(), when the old LEX is popped by sp_head::m_lex.pop() - THD::restore_from_local_lex_to_old_lex(), when the old LEX is stored in the caller's local variable. */ bool merge_lex(THD *thd, LEX *oldlex, LEX *sublex); /** Restores lex in 'thd' from our copy, but keeps some status from the one in 'thd', like ptr, tables, fields, etc. @todo Conflicting comment in sp_head.cc */ bool restore_lex(THD *thd) { DBUG_ENTER("sp_head::restore_lex"); /* There is no a need to free the current thd->lex here. - In the majority of the cases restore_lex() is called on success and thd->lex does not need to be deleted. - In cases when restore_lex() is called on error, e.g. from sp_create_assignment_instr(), thd->lex is already linked to some sp_instr_xxx (using sp_lex_keeper). Note, we don't get to here in case of a syntax error when the current thd->lex is not yet completely initialized and linked. It gets automatically deleted by the Bison %destructor in sql_yacc.yy. */ LEX *oldlex= (LEX *) m_lex.pop(); if (!oldlex) DBUG_RETURN(false); // Nothing to restore // This restores thd->lex and thd->stmt_lex DBUG_RETURN(thd->restore_from_local_lex_to_old_lex(oldlex)); } /** Iterate through the LEX stack from the top (the newest) to the bottom (the oldest) and find the one that contains a non-zero spname. @returns - the address of spname, or NULL of no spname found. */ const sp_name *find_spname_recursive() { uint count= m_lex.elements; for (uint i= 0; i < count; i++) { const LEX *tmp= m_lex.elem(count - i - 1); if (tmp->spname) return tmp->spname; } return NULL; } /// Put the instruction on the backpatch list, associated with the label. int push_backpatch(THD *thd, sp_instr *, sp_label *); int push_backpatch_goto(THD *thd, sp_pcontext *ctx, sp_label *lab); /// Update all instruction with this label in the backpatch list to /// the current position. void backpatch(sp_label *); void backpatch_goto(THD *thd, sp_label *, sp_label *); /// Check for unresolved goto label bool check_unresolved_goto(); /// Start a new cont. backpatch level. If 'i' is NULL, the level is just incr. int new_cont_backpatch(sp_instr_opt_meta *i); /// Add an instruction to the current level int add_cont_backpatch(sp_instr_opt_meta *i); /// Backpatch (and pop) the current level to the current position. void do_cont_backpatch(); /// Add cpush instructions for all cursors declared in the current frame bool sp_add_instr_cpush_for_cursors(THD *thd, sp_pcontext *pcontext); const LEX_CSTRING *name() const { return &m_name; } char *create_string(THD *thd, ulong *lenp); Field *create_result_field(uint field_max_length, const LEX_CSTRING *field_name, TABLE *table) const; /** Check and prepare an instance of Column_definition for field creation (fill all necessary attributes), for variables, parameters and function return values. @param[in] thd Thread handle @param[in] lex Yacc parsing context @param[out] field_def An instance of create_field to be filled @retval false on success @retval true on error */ bool fill_field_definition(THD *thd, Column_definition *field_def) { const Type_handler *h= field_def->type_handler(); return h->Column_definition_fix_attributes(field_def) || field_def->sp_prepare_create_field(thd, mem_root); } bool row_fill_field_definitions(THD *thd, Row_definition_list *row) { /* Prepare all row fields. This will (among other things) - convert VARCHAR lengths from character length to octet length - calculate interval lengths for SET and ENUM */ List_iterator it(*row); for (Spvar_definition *def= it++; def; def= it++) { if (fill_spvar_definition(thd, def)) return true; } return false; } /** Check and prepare a Column_definition for a variable or a parameter. */ bool fill_spvar_definition(THD *thd, Column_definition *def) { if (fill_field_definition(thd, def)) return true; def->pack_flag|= FIELDFLAG_MAYBE_NULL; return false; } bool fill_spvar_definition(THD *thd, Column_definition *def, LEX_CSTRING *name) { def->field_name= *name; return fill_spvar_definition(thd, def); } private: /** Set a column type reference for a parameter definition */ void fill_spvar_using_type_reference(sp_variable *spvar, Qualified_column_ident *ref) { spvar->field_def.set_column_type_ref(ref); spvar->field_def.field_name= spvar->name; m_flags|= sp_head::HAS_COLUMN_TYPE_REFS; } void fill_spvar_using_table_rowtype_reference(THD *thd, sp_variable *spvar, Table_ident *ref) { spvar->field_def.set_table_rowtype_ref(ref); spvar->field_def.field_name= spvar->name; fill_spvar_definition(thd, &spvar->field_def); m_flags|= sp_head::HAS_COLUMN_TYPE_REFS; } public: bool spvar_fill_row(THD *thd, sp_variable *spvar, Row_definition_list *def); bool spvar_fill_type_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &table, const LEX_CSTRING &column); bool spvar_fill_type_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &db, const LEX_CSTRING &table, const LEX_CSTRING &column); bool spvar_fill_table_rowtype_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &table); bool spvar_fill_table_rowtype_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &db, const LEX_CSTRING &table); void set_c_chistics(const st_sp_chistics &chistics); void set_info(longlong created, longlong modified, const st_sp_chistics &chistics, sql_mode_t sql_mode); void set_definer(const char *definer, size_t definerlen) { AUTHID tmp; tmp.parse(definer, definerlen); m_definer.copy(mem_root, &tmp.user, &tmp.host); } void set_definer(const LEX_CSTRING *user_name, const LEX_CSTRING *host_name) { m_definer.copy(mem_root, user_name, host_name); } void reset_thd_mem_root(THD *thd); void restore_thd_mem_root(THD *thd); /** Optimize the code. */ void optimize(); /** Helper used during flow analysis during code optimization. See the implementation of opt_mark(). @param ip the instruction to add to the leads list @param leads the list of remaining paths to explore in the graph that represents the code, during flow analysis. */ void add_mark_lead(uint ip, List *leads); inline sp_instr * get_instr(uint i) { sp_instr *ip; if (i < m_instr.elements) get_dynamic(&m_instr, (uchar*)&ip, i); else ip= NULL; return ip; } #ifdef PROTECT_STATEMENT_MEMROOT int has_all_instrs_executed(); void reset_instrs_executed_counter(); #endif /* Add tables used by routine to the table list. */ bool add_used_tables_to_table_list(THD *thd, TABLE_LIST ***query_tables_last_ptr, TABLE_LIST *belong_to_view); /** Check if this stored routine contains statements disallowed in a stored function or trigger, and set an appropriate error message if this is the case. */ bool is_not_allowed_in_function(const char *where) { if (m_flags & CONTAINS_DYNAMIC_SQL) my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "Dynamic SQL"); else if (m_flags & MULTI_RESULTS) my_error(ER_SP_NO_RETSET, MYF(0), where); else if (m_flags & HAS_SET_AUTOCOMMIT_STMT) my_error(ER_SP_CANT_SET_AUTOCOMMIT, MYF(0)); else if (m_flags & HAS_COMMIT_OR_ROLLBACK) my_error(ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0)); else if (m_flags & HAS_SQLCOM_RESET) my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "RESET"); else if (m_flags & HAS_SQLCOM_FLUSH) my_error(ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG, MYF(0), "FLUSH"); return MY_TEST(m_flags & (CONTAINS_DYNAMIC_SQL | MULTI_RESULTS | HAS_SET_AUTOCOMMIT_STMT | HAS_COMMIT_OR_ROLLBACK | HAS_SQLCOM_RESET | HAS_SQLCOM_FLUSH)); } #ifndef DBUG_OFF int show_routine_code(THD *thd); #endif /* This method is intended for attributes of a routine which need to propagate upwards to the Query_tables_list of the caller (when a property of a sp_head needs to "taint" the calling statement). */ void propagate_attributes(Query_tables_list *prelocking_ctx) { DBUG_ENTER("sp_head::propagate_attributes"); /* If this routine needs row-based binary logging, the entire top statement too (we cannot switch from statement-based to row-based only for this routine, as in statement-based the top-statement may be binlogged and the substatements not). */ DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags(): 0x%x", prelocking_ctx->get_stmt_unsafe_flags())); DBUG_PRINT("info", ("sp_head(%p=%s)->unsafe_flags: 0x%x", this, name()->str, unsafe_flags)); prelocking_ctx->set_stmt_unsafe_flags(unsafe_flags); DBUG_VOID_RETURN; } sp_pcontext *get_parse_context() { return m_pcont; } /* Check EXECUTE access: - in case of a standalone rotuine, for the routine itself - in case of a package routine, for the owner package body */ bool check_execute_access(THD *thd) const; virtual sp_package *get_package() { return NULL; } virtual void init_psi_share(); protected: MEM_ROOT *m_thd_root; ///< Temp. store for thd's mem_root THD *m_thd; ///< Set if we have reset mem_root sp_pcontext *m_pcont; ///< Parse context List m_lex; ///< Temp. store for the other lex DYNAMIC_ARRAY m_instr; ///< The "instructions" enum backpatch_instr_type { GOTO, CPOP, HPOP }; typedef struct { sp_label *lab; sp_instr *instr; backpatch_instr_type instr_type; } bp_t; List m_backpatch; ///< Instructions needing backpatching List m_backpatch_goto; // Instructions needing backpatching (for goto) /** We need a special list for backpatching of instructions with a continue destination (in the case of a continue handler catching an error in the test), since it would otherwise interfere with the normal backpatch mechanism - e.g. jump_if_not instructions have two different destinations which are to be patched differently. Since these occur in a more restricted way (always the same "level" in the code), we don't need the label. */ List m_cont_backpatch; uint m_cont_level; // The current cont. backpatch level /** Multi-set representing optimized list of tables to be locked by this routine. Does not include tables which are used by invoked routines. @note For prelocking-free SPs this multiset is constructed too. We do so because the same instance of sp_head may be called both in prelocked mode and in non-prelocked mode. */ HASH m_sptabs; bool execute(THD *thd, bool merge_da_on_success); /** Perform a forward flow analysis in the generated code. Mark reachable instructions, for the optimizer. */ void opt_mark(); /** Merge the list of tables used by query into the multi-set of tables used by routine. */ bool merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check); /// Put the instruction on the a backpatch list, associated with the label. int push_backpatch(THD *thd, sp_instr *, sp_label *, List *list, backpatch_instr_type itype); }; // class sp_head : public Sql_alloc class sp_package: public sp_head { bool validate_public_routines(THD *thd, sp_package *spec); bool validate_private_routines(THD *thd); public: class LexList: public List { public: LexList() { elements= 0; } // Find a package routine by a non qualified name LEX *find(const LEX_CSTRING &name, enum_sp_type type); // Find a package routine by a package-qualified name, e.g. 'pkg.proc' LEX *find_qualified(const LEX_CSTRING &name, enum_sp_type type); // Check if a routine with the given qualified name already exists bool check_dup_qualified(const LEX_CSTRING &name, const Sp_handler *sph) { if (!find_qualified(name, sph->type())) return false; my_error(ER_SP_ALREADY_EXISTS, MYF(0), sph->type_str(), name.str); return true; } bool check_dup_qualified(const sp_head *sp) { return check_dup_qualified(sp->m_name, sp->m_handler); } void cleanup(); }; /* The LEX for a new package subroutine is initially assigned to m_current_routine. After scanning parameters, return type and chistics, the parser detects if we have a declaration or a definition, e.g.: PROCEDURE p1(a INT); vs PROCEDURE p1(a INT) AS BEGIN NULL; END; (i.e. either semicolon or the "AS" keyword) m_current_routine is then added either to m_routine_implementations, or m_routine_declarations, and then m_current_routine is set to NULL. */ LEX *m_current_routine; LexList m_routine_implementations; LexList m_routine_declarations; LEX *m_top_level_lex; sp_rcontext *m_rcontext; uint m_invoked_subroutine_count; bool m_is_instantiated; bool m_is_cloning_routine; private: sp_package(MEM_ROOT *mem_root, LEX *top_level_lex, const sp_name *name, const Sp_handler *sph); ~sp_package(); public: static sp_package *create(LEX *top_level_lex, const sp_name *name, const Sp_handler *sph); bool add_routine_declaration(LEX *lex) { return m_routine_declarations.check_dup_qualified(lex->sphead) || m_routine_declarations.push_back(lex, &main_mem_root); } bool add_routine_implementation(LEX *lex) { return m_routine_implementations.check_dup_qualified(lex->sphead) || m_routine_implementations.push_back(lex, &main_mem_root); } sp_package *get_package() override { return this; } void init_psi_share() override; bool is_invoked() const override { /* Cannot flush a package out of the SP cache when: - its initialization block is running - one of its subroutine is running */ return sp_head::is_invoked() || m_invoked_subroutine_count > 0; } sp_variable *find_package_variable(const LEX_CSTRING *name) const { /* sp_head::m_pcont is a special level for routine parameters. Variables declared inside CREATE PACKAGE BODY reside in m_children.at(0). */ sp_pcontext *ctx= m_pcont->child_context(0); return ctx ? ctx->find_variable(name, true) : NULL; } bool validate_after_parser(THD *thd); bool instantiate_if_needed(THD *thd); }; class sp_lex_cursor: public sp_lex_local, public Query_arena { public: sp_lex_cursor(THD *thd, const LEX *oldlex, MEM_ROOT *mem_root_arg) :sp_lex_local(thd, oldlex), Query_arena(mem_root_arg, STMT_INITIALIZED_FOR_SP) { } sp_lex_cursor(THD *thd, const LEX *oldlex) :sp_lex_local(thd, oldlex), Query_arena(thd->lex->sphead->get_main_mem_root(), STMT_INITIALIZED_FOR_SP) { } ~sp_lex_cursor() { free_items(); } bool cleanup_stmt(bool /*restore_set_statement_vars*/) override { return false; } Query_arena *query_arena() override { return this; } bool validate() { DBUG_ASSERT(sql_command == SQLCOM_SELECT); if (result) { my_error(ER_SP_BAD_CURSOR_SELECT, MYF(0)); return true; } return false; } bool stmt_finalize(THD *thd) { if (validate()) return true; sp_lex_in_use= true; free_list= thd->free_list; thd->free_list= NULL; return false; } }; // // "Instructions"... // class sp_instr :public Query_arena, public Sql_alloc { sp_instr(const sp_instr &); /**< Prevent use of these */ void operator=(sp_instr &); public: uint marked; uint m_ip; ///< My index sp_pcontext *m_ctx; ///< My parse context uint m_lineno; /// Should give each a name or type code for debugging purposes? sp_instr(uint ip, sp_pcontext *ctx) :Query_arena(0, STMT_INITIALIZED_FOR_SP), marked(0), m_ip(ip), m_ctx(ctx) #ifdef PROTECT_STATEMENT_MEMROOT , m_has_been_run(NON_RUN) #endif {} virtual ~sp_instr() { free_items(); } /** Execute this instruction @param thd Thread handle @param[out] nextp index of the next instruction to execute. (For most instructions this will be the instruction following this one). Note that this parameter is undefined in case of errors, use get_cont_dest() to find the continuation instruction for CONTINUE error handlers. @retval 0 on success, @retval other if some error occurred */ virtual int execute(THD *thd, uint *nextp) = 0; /** Execute open_and_lock_tables() for this statement. Open and lock the tables used by this statement, as a pre-requisite to execute the core logic of this instruction with exec_core(). @param thd the current thread @param tables the list of tables to open and lock @return zero on success, non zero on failure. */ int exec_open_and_lock_tables(THD *thd, TABLE_LIST *tables); /** Get the continuation destination of this instruction. @return the continuation destination */ virtual uint get_cont_dest() const; /* Execute core function of instruction after all preparations (e.g. setting of proper LEX, saving part of the thread context have been done). Should be implemented for instructions using expressions or whole statements (thus having to have own LEX). Used in concert with sp_lex_keeper class and its descendants (there are none currently). */ virtual int exec_core(THD *thd, uint *nextp); virtual void print(String *str) = 0; virtual void backpatch(uint dest, sp_pcontext *dst_ctx) {} /** Mark this instruction as reachable during optimization and return the index to the next instruction. Jump instruction will add their destination to the leads list. */ virtual uint opt_mark(sp_head *sp, List *leads) { marked= 1; return m_ip+1; } /** Short-cut jumps to jumps during optimization. This is used by the jump instructions' opt_mark() methods. 'start' is the starting point, used to prevent the mark sweep from looping for ever. Return the end destination. */ virtual uint opt_shortcut_jump(sp_head *sp, sp_instr *start) { return m_ip; } /** Inform the instruction that it has been moved during optimization. Most instructions will simply update its index, but jump instructions must also take care of their destination pointers. Forward jumps get pushed to the backpatch list 'ibp'. */ virtual void opt_move(uint dst, List *ibp) { m_ip= dst; } virtual PSI_statement_info* get_psi_info() = 0; #ifdef PROTECT_STATEMENT_MEMROOT bool has_been_run() const { return m_has_been_run == RUN; } void mark_as_qc_used() { m_has_been_run= QC; } void mark_as_run() { if (m_has_been_run == QC) m_has_been_run= NON_RUN; // answer was from WC => not really executed else m_has_been_run= RUN; } void mark_as_not_run() { m_has_been_run= NON_RUN; } private: enum {NON_RUN, QC, RUN} m_has_been_run; #endif }; // class sp_instr : public Sql_alloc /** Auxilary class to which instructions delegate responsibility for handling LEX and preparations before executing statement or calculating complex expression. Exist mainly to avoid having double hierarchy between instruction classes. @todo Add ability to not store LEX and do any preparations if expression used is simple. */ class sp_lex_keeper { /** Prevent use of these */ sp_lex_keeper(const sp_lex_keeper &); void operator=(sp_lex_keeper &); public: sp_lex_keeper(LEX *lex, bool lex_resp) : m_lex(lex), m_lex_resp(lex_resp), lex_query_tables_own_last(NULL) { lex->sp_lex_in_use= TRUE; } virtual ~sp_lex_keeper(); /** Prepare execution of instruction using LEX, if requested check whenever we have read access to tables used and open/lock them, call instruction's exec_core() method, perform cleanup afterwards. @todo Conflicting comment in sp_head.cc */ int reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, sp_instr* instr); int cursor_reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, sp_instr *instr); inline uint sql_command() const { return (uint)m_lex->sql_command; } void disable_query_cache() { m_lex->safe_to_cache_query= 0; } private: LEX *m_lex; /** Indicates whenever this sp_lex_keeper instance responsible for LEX deletion. */ bool m_lex_resp; /* Support for being able to execute this statement in two modes: a) inside prelocked mode set by the calling procedure or its ancestor. b) outside of prelocked mode, when this statement enters/leaves prelocked mode itself. */ /** List of additional tables this statement needs to lock when it enters/leaves prelocked mode on its own. */ TABLE_LIST *prelocking_tables; /** The value m_lex->query_tables_own_last should be set to this when the statement enters/leaves prelocked mode on its own. */ TABLE_LIST **lex_query_tables_own_last; }; /** Call out to some prepared SQL statement. */ class sp_instr_stmt : public sp_instr { sp_instr_stmt(const sp_instr_stmt &); /**< Prevent use of these */ void operator=(sp_instr_stmt &); public: LEX_STRING m_query; ///< For thd->query sp_instr_stmt(uint ip, sp_pcontext *ctx, LEX *lex) : sp_instr(ip, ctx), m_lex_keeper(lex, TRUE) { m_query.str= 0; m_query.length= 0; } virtual ~sp_instr_stmt() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; private: sp_lex_keeper m_lex_keeper; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_stmt : public sp_instr class sp_instr_set : public sp_instr { sp_instr_set(const sp_instr_set &); /**< Prevent use of these */ void operator=(sp_instr_set &); public: sp_instr_set(uint ip, sp_pcontext *ctx, const Sp_rcontext_handler *rh, uint offset, Item *val, LEX *lex, bool lex_resp) : sp_instr(ip, ctx), m_rcontext_handler(rh), m_offset(offset), m_value(val), m_lex_keeper(lex, lex_resp) {} virtual ~sp_instr_set() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; protected: sp_rcontext *get_rcontext(THD *thd) const; const Sp_rcontext_handler *m_rcontext_handler; uint m_offset; ///< Frame offset Item *m_value; sp_lex_keeper m_lex_keeper; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_set : public sp_instr /* This class handles assignments of a ROW fields: DECLARE rec ROW (a INT,b INT); SET rec.a= 10; */ class sp_instr_set_row_field : public sp_instr_set { sp_instr_set_row_field(const sp_instr_set_row_field &); // Prevent use of this void operator=(sp_instr_set_row_field &); uint m_field_offset; public: sp_instr_set_row_field(uint ip, sp_pcontext *ctx, const Sp_rcontext_handler *rh, uint offset, uint field_offset, Item *val, LEX *lex, bool lex_resp) : sp_instr_set(ip, ctx, rh, offset, val, lex, lex_resp), m_field_offset(field_offset) {} virtual ~sp_instr_set_row_field() = default; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; }; // class sp_instr_set_field : public sp_instr_set /** This class handles assignment instructions like this: DECLARE CURSOR cur IS SELECT * FROM t1; rec cur%ROWTYPE; BEGIN rec.column1:= 10; -- This instruction END; The idea is that during sp_rcontext::create() we do not know the extact structure of "rec". It gets resolved at run time, during the corresponding sp_instr_cursor_copy_struct::exec_core(). So sp_instr_set_row_field_by_name searches for ROW fields by name, while sp_instr_set_row_field (see above) searches for ROW fields by index. */ class sp_instr_set_row_field_by_name : public sp_instr_set { // Prevent use of this sp_instr_set_row_field_by_name(const sp_instr_set_row_field &); void operator=(sp_instr_set_row_field_by_name &); const LEX_CSTRING m_field_name; public: sp_instr_set_row_field_by_name(uint ip, sp_pcontext *ctx, const Sp_rcontext_handler *rh, uint offset, const LEX_CSTRING &field_name, Item *val, LEX *lex, bool lex_resp) : sp_instr_set(ip, ctx, rh, offset, val, lex, lex_resp), m_field_name(field_name) {} virtual ~sp_instr_set_row_field_by_name() = default; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; }; // class sp_instr_set_field_by_name : public sp_instr_set /** Set NEW/OLD row field value instruction. Used in triggers. */ class sp_instr_set_trigger_field : public sp_instr { sp_instr_set_trigger_field(const sp_instr_set_trigger_field &); void operator=(sp_instr_set_trigger_field &); public: sp_instr_set_trigger_field(uint ip, sp_pcontext *ctx, Item_trigger_field *trg_fld, Item *val, LEX *lex) : sp_instr(ip, ctx), trigger_field(trg_fld), value(val), m_lex_keeper(lex, TRUE) {} virtual ~sp_instr_set_trigger_field() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; private: Item_trigger_field *trigger_field; Item *value; sp_lex_keeper m_lex_keeper; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_trigger_field : public sp_instr /** An abstract class for all instructions with destinations that needs to be updated by the optimizer. Even if not all subclasses will use both the normal destination and the continuation destination, we put them both here for simplicity. */ class sp_instr_opt_meta : public sp_instr { public: uint m_dest; ///< Where we will go uint m_cont_dest; ///< Where continue handlers will go sp_instr_opt_meta(uint ip, sp_pcontext *ctx) : sp_instr(ip, ctx), m_dest(0), m_cont_dest(0), m_optdest(0), m_cont_optdest(0) {} sp_instr_opt_meta(uint ip, sp_pcontext *ctx, uint dest) : sp_instr(ip, ctx), m_dest(dest), m_cont_dest(0), m_optdest(0), m_cont_optdest(0) {} virtual ~sp_instr_opt_meta() = default; virtual void set_destination(uint old_dest, uint new_dest) = 0; uint get_cont_dest() const override; protected: sp_instr *m_optdest; ///< Used during optimization sp_instr *m_cont_optdest; ///< Used during optimization }; // class sp_instr_opt_meta : public sp_instr class sp_instr_jump : public sp_instr_opt_meta { sp_instr_jump(const sp_instr_jump &); /**< Prevent use of these */ void operator=(sp_instr_jump &); public: sp_instr_jump(uint ip, sp_pcontext *ctx) : sp_instr_opt_meta(ip, ctx) {} sp_instr_jump(uint ip, sp_pcontext *ctx, uint dest) : sp_instr_opt_meta(ip, ctx, dest) {} virtual ~sp_instr_jump() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override; uint opt_shortcut_jump(sp_head *sp, sp_instr *start) override; void opt_move(uint dst, List *ibp) override; void backpatch(uint dest, sp_pcontext *dst_ctx) override { /* Calling backpatch twice is a logic flaw in jump resolution. */ DBUG_ASSERT(m_dest == 0); m_dest= dest; } /** Update the destination; used by the optimizer. */ void set_destination(uint old_dest, uint new_dest) override { if (m_dest == old_dest) m_dest= new_dest; } public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_jump : public sp_instr_opt_meta class sp_instr_jump_if_not : public sp_instr_jump { sp_instr_jump_if_not(const sp_instr_jump_if_not &); /**< Prevent use of these */ void operator=(sp_instr_jump_if_not &); public: sp_instr_jump_if_not(uint ip, sp_pcontext *ctx, Item *i, LEX *lex) : sp_instr_jump(ip, ctx), m_expr(i), m_lex_keeper(lex, TRUE) {} sp_instr_jump_if_not(uint ip, sp_pcontext *ctx, Item *i, uint dest, LEX *lex) : sp_instr_jump(ip, ctx, dest), m_expr(i), m_lex_keeper(lex, TRUE) {} virtual ~sp_instr_jump_if_not() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override; /** Override sp_instr_jump's shortcut; we stop here */ uint opt_shortcut_jump(sp_head *sp, sp_instr *start) override { return m_ip; } void opt_move(uint dst, List *ibp) override; void set_destination(uint old_dest, uint new_dest) override { sp_instr_jump::set_destination(old_dest, new_dest); if (m_cont_dest == old_dest) m_cont_dest= new_dest; } private: Item *m_expr; ///< The condition sp_lex_keeper m_lex_keeper; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_jump_if_not : public sp_instr_jump class sp_instr_preturn : public sp_instr { sp_instr_preturn(const sp_instr_preturn &); /**< Prevent use of these */ void operator=(sp_instr_preturn &); public: sp_instr_preturn(uint ip, sp_pcontext *ctx) : sp_instr(ip, ctx) {} virtual ~sp_instr_preturn() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override { marked= 1; return UINT_MAX; } public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_preturn : public sp_instr class sp_instr_freturn : public sp_instr { sp_instr_freturn(const sp_instr_freturn &); /**< Prevent use of these */ void operator=(sp_instr_freturn &); public: sp_instr_freturn(uint ip, sp_pcontext *ctx, Item *val, const Type_handler *handler, LEX *lex) : sp_instr(ip, ctx), m_value(val), m_type_handler(handler), m_lex_keeper(lex, TRUE) {} virtual ~sp_instr_freturn() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override { marked= 1; return UINT_MAX; } protected: Item *m_value; const Type_handler *m_type_handler; sp_lex_keeper m_lex_keeper; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_freturn : public sp_instr class sp_instr_hpush_jump : public sp_instr_jump { sp_instr_hpush_jump(const sp_instr_hpush_jump &); /**< Prevent use of these */ void operator=(sp_instr_hpush_jump &); public: sp_instr_hpush_jump(uint ip, sp_pcontext *ctx, sp_handler *handler) :sp_instr_jump(ip, ctx), m_handler(handler), m_opt_hpop(0), m_frame(ctx->current_var_count()) { DBUG_ASSERT(m_handler->condition_values.elements == 0); } virtual ~sp_instr_hpush_jump() { m_handler->condition_values.empty(); m_handler= NULL; } int execute(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override; /** Override sp_instr_jump's shortcut; we stop here. */ uint opt_shortcut_jump(sp_head *sp, sp_instr *start) override { return m_ip; } void backpatch(uint dest, sp_pcontext *dst_ctx) override { DBUG_ASSERT(!m_dest || !m_opt_hpop); if (!m_dest) m_dest= dest; else m_opt_hpop= dest; } void add_condition(sp_condition_value *condition_value) { m_handler->condition_values.push_back(condition_value); } sp_handler *get_handler() { return m_handler; } private: /// Handler. sp_handler *m_handler; /// hpop marking end of handler scope. uint m_opt_hpop; // This attribute is needed for SHOW PROCEDURE CODE only (i.e. it's needed in // debug version only). It's used in print(). uint m_frame; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_hpush_jump : public sp_instr_jump class sp_instr_hpop : public sp_instr { sp_instr_hpop(const sp_instr_hpop &); /**< Prevent use of these */ void operator=(sp_instr_hpop &); public: sp_instr_hpop(uint ip, sp_pcontext *ctx, uint count) : sp_instr(ip, ctx), m_count(count) {} virtual ~sp_instr_hpop() = default; void update_count(uint count) { m_count= count; } int execute(THD *thd, uint *nextp) override; void print(String *str) override; private: uint m_count; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_hpop : public sp_instr class sp_instr_hreturn : public sp_instr_jump { sp_instr_hreturn(const sp_instr_hreturn &); /**< Prevent use of these */ void operator=(sp_instr_hreturn &); public: sp_instr_hreturn(uint ip, sp_pcontext *ctx) :sp_instr_jump(ip, ctx), m_frame(ctx->current_var_count()) {} virtual ~sp_instr_hreturn() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; /* This instruction will not be short cut optimized. */ uint opt_shortcut_jump(sp_head *sp, sp_instr *start) override { return m_ip; } uint opt_mark(sp_head *sp, List *leads) override; private: uint m_frame; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_hreturn : public sp_instr_jump /** This is DECLARE CURSOR */ class sp_instr_cpush : public sp_instr, public sp_cursor { sp_instr_cpush(const sp_instr_cpush &); /**< Prevent use of these */ void operator=(sp_instr_cpush &); public: sp_instr_cpush(uint ip, sp_pcontext *ctx, LEX *lex, uint offset) : sp_instr(ip, ctx), m_lex_keeper(lex, TRUE), m_cursor(offset) {} virtual ~sp_instr_cpush() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; /** This call is used to cleanup the instruction when a sensitive cursor is closed. For now stored procedures always use materialized cursors and the call is not used. */ bool cleanup_stmt(bool /*restore_set_statement_vars*/) override { return false; } private: sp_lex_keeper m_lex_keeper; uint m_cursor; /**< Frame offset (for debugging) */ public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_cpush : public sp_instr class sp_instr_cpop : public sp_instr { sp_instr_cpop(const sp_instr_cpop &); /**< Prevent use of these */ void operator=(sp_instr_cpop &); public: sp_instr_cpop(uint ip, sp_pcontext *ctx, uint count) : sp_instr(ip, ctx), m_count(count) {} virtual ~sp_instr_cpop() = default; void update_count(uint count) { m_count= count; } int execute(THD *thd, uint *nextp) override; void print(String *str) override; private: uint m_count; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_cpop : public sp_instr class sp_instr_copen : public sp_instr { sp_instr_copen(const sp_instr_copen &); /**< Prevent use of these */ void operator=(sp_instr_copen &); public: sp_instr_copen(uint ip, sp_pcontext *ctx, uint c) : sp_instr(ip, ctx), m_cursor(c) {} virtual ~sp_instr_copen() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; private: uint m_cursor; ///< Stack index public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_copen : public sp_instr_stmt /** Initialize the structure of a cursor%ROWTYPE variable from the LEX containing the cursor SELECT statement. */ class sp_instr_cursor_copy_struct: public sp_instr { /**< Prevent use of these */ sp_instr_cursor_copy_struct(const sp_instr_cursor_copy_struct &); void operator=(sp_instr_cursor_copy_struct &); sp_lex_keeper m_lex_keeper; uint m_cursor; uint m_var; public: sp_instr_cursor_copy_struct(uint ip, sp_pcontext *ctx, uint coffs, sp_lex_cursor *lex, uint voffs) : sp_instr(ip, ctx), m_lex_keeper(lex, FALSE), m_cursor(coffs), m_var(voffs) {} virtual ~sp_instr_cursor_copy_struct() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; class sp_instr_cclose : public sp_instr { sp_instr_cclose(const sp_instr_cclose &); /**< Prevent use of these */ void operator=(sp_instr_cclose &); public: sp_instr_cclose(uint ip, sp_pcontext *ctx, uint c) : sp_instr(ip, ctx), m_cursor(c) {} virtual ~sp_instr_cclose() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; private: uint m_cursor; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_cclose : public sp_instr class sp_instr_cfetch : public sp_instr { sp_instr_cfetch(const sp_instr_cfetch &); /**< Prevent use of these */ void operator=(sp_instr_cfetch &); public: sp_instr_cfetch(uint ip, sp_pcontext *ctx, uint c, bool error_on_no_data) : sp_instr(ip, ctx), m_cursor(c), m_error_on_no_data(error_on_no_data) { m_varlist.empty(); } virtual ~sp_instr_cfetch() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; void add_to_varlist(sp_variable *var) { m_varlist.push_back(var); } private: uint m_cursor; List m_varlist; bool m_error_on_no_data; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_cfetch : public sp_instr /* This class is created for the special fetch instruction FETCH GROUP NEXT ROW, used in the user-defined aggregate functions */ class sp_instr_agg_cfetch : public sp_instr { sp_instr_agg_cfetch(const sp_instr_cfetch &); /**< Prevent use of these */ void operator=(sp_instr_cfetch &); public: sp_instr_agg_cfetch(uint ip, sp_pcontext *ctx) : sp_instr(ip, ctx){} virtual ~sp_instr_agg_cfetch() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_agg_cfetch : public sp_instr class sp_instr_error : public sp_instr { sp_instr_error(const sp_instr_error &); /**< Prevent use of these */ void operator=(sp_instr_error &); public: sp_instr_error(uint ip, sp_pcontext *ctx, int errcode) : sp_instr(ip, ctx), m_errcode(errcode) {} virtual ~sp_instr_error() = default; int execute(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override { marked= 1; return UINT_MAX; } private: int m_errcode; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_error : public sp_instr class sp_instr_set_case_expr : public sp_instr_opt_meta { public: sp_instr_set_case_expr(uint ip, sp_pcontext *ctx, uint case_expr_id, Item *case_expr, LEX *lex) : sp_instr_opt_meta(ip, ctx), m_case_expr_id(case_expr_id), m_case_expr(case_expr), m_lex_keeper(lex, TRUE) {} virtual ~sp_instr_set_case_expr() = default; int execute(THD *thd, uint *nextp) override; int exec_core(THD *thd, uint *nextp) override; void print(String *str) override; uint opt_mark(sp_head *sp, List *leads) override; void opt_move(uint dst, List *ibp) override; void set_destination(uint old_dest, uint new_dest) override { if (m_cont_dest == old_dest) m_cont_dest= new_dest; } private: uint m_case_expr_id; Item *m_case_expr; sp_lex_keeper m_lex_keeper; public: PSI_statement_info* get_psi_info() override { return & psi_info; } static PSI_statement_info psi_info; }; // class sp_instr_set_case_expr : public sp_instr_opt_meta bool check_show_routine_access(THD *thd, sp_head *sp, bool *full_access); #ifndef NO_EMBEDDED_ACCESS_CHECKS bool sp_change_security_context(THD *thd, sp_head *sp, Security_context **backup); void sp_restore_security_context(THD *thd, Security_context *backup); bool set_routine_security_ctx(THD *thd, sp_head *sp, Security_context **save_ctx); #endif /* NO_EMBEDDED_ACCESS_CHECKS */ TABLE_LIST * sp_add_to_query_tables(THD *thd, LEX *lex, const LEX_CSTRING *db, const LEX_CSTRING *name, thr_lock_type locktype, enum_mdl_type mdl_type); /** @} (end of group Stored_Routines) */ #endif /* _SP_HEAD_H_ */ mysql/server/private/service_versions.h000064400000004001151027430560014430 0ustar00/* Copyright (c) 2009, 2010, Oracle and/or its affiliates. Copyright (c) 2012, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef _WIN32 #define SERVICE_VERSION __declspec(dllexport) void * #else #define SERVICE_VERSION void * #endif #define VERSION_debug_sync 0x1000 #define VERSION_kill_statement 0x1000 #define VERSION_base64 0x0100 #define VERSION_encryption 0x0300 #define VERSION_encryption_scheme 0x0100 #define VERSION_logger 0x0100 #define VERSION_my_crypt 0x0100 #define VERSION_my_md5 0x0100 #define VERSION_my_print_error 0x0100 #define VERSION_my_sha1 0x0101 #define VERSION_my_sha2 0x0100 #define VERSION_my_snprintf 0x0100 #define VERSION_progress_report 0x0100 #define VERSION_thd_alloc 0x0200 #define VERSION_thd_autoinc 0x0100 #define VERSION_thd_error_context 0x0200 #define VERSION_thd_rnd 0x0100 #define VERSION_thd_specifics 0x0100 #define VERSION_thd_timezone 0x0100 #define VERSION_thd_wait 0x0100 #define VERSION_wsrep 0x0500 #define VERSION_json 0x0100 #define VERSION_sql_service 0x0102 #define VERSION_thd_mdl 0x0100 #define VERSION_print_check_msg 0x0100 mysql/server/private/item_func.h000064400000413204151027430560013022 0ustar00#ifndef ITEM_FUNC_INCLUDED #define ITEM_FUNC_INCLUDED /* Copyright (c) 2000, 2016, Oracle and/or its affiliates. Copyright (c) 2009, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Function items used by mysql */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #ifdef HAVE_IEEEFP_H extern "C" /* Bug in BSDI include file */ { #include } #endif #include "sql_udf.h" // udf_handler #include "my_decimal.h" // string2my_decimal #include extern int st_append_json(String *s, CHARSET_INFO *json_cs, const uchar *js, uint js_len); class Item_func :public Item_func_or_sum { void sync_with_sum_func_and_with_field(List &list); protected: virtual bool check_arguments() const { return check_argument_types_scalar(0, arg_count); } bool check_argument_types_like_args0() const; bool check_argument_types_scalar(uint start, uint end) const; bool check_argument_types_traditional_scalar(uint start, uint end) const; bool check_argument_types_or_binary(const Type_handler *handler, uint start, uint end) const; bool check_argument_types_can_return_int(uint start, uint end) const; bool check_argument_types_can_return_real(uint start, uint end) const; bool check_argument_types_can_return_str(uint start, uint end) const; bool check_argument_types_can_return_text(uint start, uint end) const; bool check_argument_types_can_return_date(uint start, uint end) const; bool check_argument_types_can_return_time(uint start, uint end) const; void print_cast_temporal(String *str, enum_query_type query_type); void print_schema_qualified_name(String *to, const LEX_CSTRING &schema_name, const LEX_CSTRING &function_name) const { // e.g. oracle_schema.func() to->append(schema_name); to->append('.'); to->append(function_name); } void print_sql_mode_qualified_name(String *to, enum_query_type query_type, const LEX_CSTRING &function_name) const { const Schema *func_schema= schema(); if (!func_schema || func_schema == Schema::find_implied(current_thd)) to->append(function_name); else print_schema_qualified_name(to, func_schema->name(), function_name); } void print_sql_mode_qualified_name(String *to, enum_query_type query_type) const { return print_sql_mode_qualified_name(to, query_type, func_name_cstring()); } public: // Print an error message for a builtin-schema qualified function call static void wrong_param_count_error(const LEX_CSTRING &schema_name, const LEX_CSTRING &func_name); table_map not_null_tables_cache= 0; enum Functype { UNKNOWN_FUNC,EQ_FUNC,EQUAL_FUNC,NE_FUNC,LT_FUNC,LE_FUNC, GE_FUNC,GT_FUNC,FT_FUNC, LIKE_FUNC,ISNULL_FUNC,ISNOTNULL_FUNC, COND_AND_FUNC, COND_OR_FUNC, XOR_FUNC, BETWEEN, IN_FUNC, MULT_EQUAL_FUNC, INTERVAL_FUNC, ISNOTNULLTEST_FUNC, SP_EQUALS_FUNC, SP_DISJOINT_FUNC,SP_INTERSECTS_FUNC, SP_TOUCHES_FUNC,SP_CROSSES_FUNC,SP_WITHIN_FUNC, SP_CONTAINS_FUNC,SP_OVERLAPS_FUNC, SP_STARTPOINT,SP_ENDPOINT,SP_EXTERIORRING, SP_POINTN,SP_GEOMETRYN,SP_INTERIORRINGN, SP_RELATE_FUNC, NOT_FUNC, NOT_ALL_FUNC, TEMPTABLE_ROWID, NOW_FUNC, NOW_UTC_FUNC, SYSDATE_FUNC, TRIG_COND_FUNC, SUSERVAR_FUNC, GUSERVAR_FUNC, COLLATE_FUNC, EXTRACT_FUNC, CHAR_TYPECAST_FUNC, FUNC_SP, UDF_FUNC, NEG_FUNC, GSYSVAR_FUNC, IN_OPTIMIZER_FUNC, DYNCOL_FUNC, JSON_EXTRACT_FUNC, JSON_VALID_FUNC, ROWNUM_FUNC, CASE_SEARCHED_FUNC, // Used by ColumnStore/Spider CASE_SIMPLE_FUNC, // Used by ColumnStore/spider, }; /* A function bitmap. Useful when some operation needs to be applied only to certain functions. For now we only need to distinguish some comparison predicates. */ enum Bitmap : ulonglong { BITMAP_NONE= 0, BITMAP_EQ= 1ULL << EQ_FUNC, BITMAP_EQUAL= 1ULL << EQUAL_FUNC, BITMAP_NE= 1ULL << NE_FUNC, BITMAP_LT= 1ULL << LT_FUNC, BITMAP_LE= 1ULL << LE_FUNC, BITMAP_GE= 1ULL << GE_FUNC, BITMAP_GT= 1ULL << GT_FUNC, BITMAP_LIKE= 1ULL << LIKE_FUNC, BITMAP_BETWEEN= 1ULL << BETWEEN, BITMAP_IN= 1ULL << IN_FUNC, BITMAP_MULT_EQUAL= 1ULL << MULT_EQUAL_FUNC, BITMAP_OTHER= 1ULL << 63, BITMAP_ALL= 0xFFFFFFFFFFFFFFFFULL, BITMAP_ANY_EQUALITY= BITMAP_EQ | BITMAP_EQUAL | BITMAP_MULT_EQUAL, BITMAP_EXCEPT_ANY_EQUALITY= BITMAP_ALL & ~BITMAP_ANY_EQUALITY, }; ulonglong bitmap_bit() const { Functype type= functype(); return 1ULL << (type > 63 ? 63 : type); } static scalar_comparison_op functype_to_scalar_comparison_op(Functype type) { switch (type) { case EQ_FUNC: return SCALAR_CMP_EQ; case EQUAL_FUNC: return SCALAR_CMP_EQUAL; case LT_FUNC: return SCALAR_CMP_LT; case LE_FUNC: return SCALAR_CMP_LE; case GE_FUNC: return SCALAR_CMP_GE; case GT_FUNC: return SCALAR_CMP_GT; default: break; } DBUG_ASSERT(0); return SCALAR_CMP_EQ; } enum Type type() const override { return FUNC_ITEM; } virtual enum Functype functype() const { return UNKNOWN_FUNC; } Item_func(THD *thd): Item_func_or_sum(thd) { DBUG_ASSERT(with_flags == item_with_t::NONE); with_flags= item_with_t::NONE; } Item_func(THD *thd, Item *a): Item_func_or_sum(thd, a) { with_flags= a->with_flags; } Item_func(THD *thd, Item *a, Item *b): Item_func_or_sum(thd, a, b) { with_flags= a->with_flags | b->with_flags; } Item_func(THD *thd, Item *a, Item *b, Item *c): Item_func_or_sum(thd, a, b, c) { with_flags|= a->with_flags | b->with_flags | c->with_flags; } Item_func(THD *thd, Item *a, Item *b, Item *c, Item *d): Item_func_or_sum(thd, a, b, c, d) { with_flags= a->with_flags | b->with_flags | c->with_flags | d->with_flags; } Item_func(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e): Item_func_or_sum(thd, a, b, c, d, e) { with_flags= (a->with_flags | b->with_flags | c->with_flags | d->with_flags | e->with_flags); } Item_func(THD *thd, List &list): Item_func_or_sum(thd, list) { set_arguments(thd, list); } // Constructor used for Item_cond_and/or (see Item comment) Item_func(THD *thd, Item_func *item): Item_func_or_sum(thd, item), not_null_tables_cache(item->not_null_tables_cache) { } bool fix_fields(THD *, Item **ref) override; void cleanup() override { Item_func_or_sum::cleanup(); used_tables_and_const_cache_init(); } void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; void quick_fix_field() override; table_map not_null_tables() const override; void update_used_tables() override { used_tables_and_const_cache_init(); used_tables_and_const_cache_update_and_join(arg_count, args); } COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override { DBUG_ENTER("Item_func::get_mm_tree"); DBUG_RETURN(const_item() ? get_mm_tree_for_const(param) : NULL); } bool eq(const Item *item, bool binary_cmp) const override; virtual Item *key_item() const { return args[0]; } void set_arguments(THD *thd, List &list) { Item_args::set_arguments(thd, list); sync_with_sum_func_and_with_field(list); list.empty(); // Fields are used } void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) override; void print(String *str, enum_query_type query_type) override; void print_op(String *str, enum_query_type query_type); void print_args(String *str, uint from, enum_query_type query_type) const; void print_args_parenthesized(String *str, enum_query_type query_type) const { str->append('('); print_args(str, 0, query_type); str->append(')'); } bool is_null() override { update_null_value(); return null_value; } String *val_str_from_val_str_ascii(String *str, String *str2); void signal_divide_by_null(); friend class udf_handler; Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { return tmp_table_field_from_field_type(root, table); } Item *get_tmp_table_item(THD *thd) override; void fix_char_length_ulonglong(ulonglong max_char_length_arg) { ulonglong max_result_length= max_char_length_arg * collation.collation->mbmaxlen; if (max_result_length >= MAX_BLOB_WIDTH) { max_length= MAX_BLOB_WIDTH; set_maybe_null(); } else max_length= (uint32) max_result_length; } Item *transform(THD *thd, Item_transformer transformer, uchar *arg) override; Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) override; void traverse_cond(Cond_traverser traverser, void * arg, traverse_order order) override; bool eval_not_null_tables(void *opt_arg) override; bool find_not_null_fields(table_map allowed) override; // bool is_expensive_processor(void *arg); // virtual bool is_expensive() { return 0; } inline void raise_numeric_overflow(const char *type_name) { char buf[256]; String str(buf, sizeof(buf), system_charset_info); str.length(0); print(&str, QT_NO_DATA_EXPANSION); my_error(ER_DATA_OUT_OF_RANGE, MYF(0), type_name, str.c_ptr_safe()); } inline double raise_float_overflow() { raise_numeric_overflow("DOUBLE"); return 0.0; } inline longlong raise_integer_overflow() { raise_numeric_overflow(unsigned_flag ? "BIGINT UNSIGNED": "BIGINT"); return 0; } inline int raise_decimal_overflow() { raise_numeric_overflow("DECIMAL"); return E_DEC_OVERFLOW; } /** Throw an error if the input double number is not finite, i.e. is either +/-INF or NAN. */ inline double check_float_overflow(double value) { return std::isfinite(value) ? value : raise_float_overflow(); } /** Throw an error if the input BIGINT value represented by the (longlong value, bool unsigned flag) pair cannot be returned by the function, i.e. is not compatible with this Item's unsigned_flag. */ inline longlong check_integer_overflow(longlong value, bool val_unsigned) { return check_integer_overflow(Longlong_hybrid(value, val_unsigned)); } // Check if the value is compatible with Item::unsigned_flag. inline longlong check_integer_overflow(const Longlong_hybrid &sval) { Longlong_null res= sval.val_int(unsigned_flag); return res.is_null() ? raise_integer_overflow() : res.value(); } // Check if the value is compatible with Item::unsigned_flag. longlong check_integer_overflow(const ULonglong_hybrid &uval) { Longlong_null res= uval.val_int(unsigned_flag); return res.is_null() ? raise_integer_overflow() : res.value(); } /** Throw an error if the error code of a DECIMAL operation is E_DEC_OVERFLOW. */ inline int check_decimal_overflow(int error) { return (error == E_DEC_OVERFLOW) ? raise_decimal_overflow() : error; } bool has_timestamp_args() { DBUG_ASSERT(fixed()); for (uint i= 0; i < arg_count; i++) { if (args[i]->type() == Item::FIELD_ITEM && args[i]->field_type() == MYSQL_TYPE_TIMESTAMP) return TRUE; } return FALSE; } bool has_date_args() { DBUG_ASSERT(fixed()); for (uint i= 0; i < arg_count; i++) { if (args[i]->type() == Item::FIELD_ITEM && (args[i]->field_type() == MYSQL_TYPE_DATE || args[i]->field_type() == MYSQL_TYPE_DATETIME)) return TRUE; } return FALSE; } bool has_time_args() { DBUG_ASSERT(fixed()); for (uint i= 0; i < arg_count; i++) { if (args[i]->type() == Item::FIELD_ITEM && (args[i]->field_type() == MYSQL_TYPE_TIME || args[i]->field_type() == MYSQL_TYPE_DATETIME)) return TRUE; } return FALSE; } bool has_datetime_args() { DBUG_ASSERT(fixed()); for (uint i= 0; i < arg_count; i++) { if (args[i]->type() == Item::FIELD_ITEM && args[i]->field_type() == MYSQL_TYPE_DATETIME) return TRUE; } return FALSE; } Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { /* By default only substitution for a field whose two different values are never equal is allowed in the arguments of a function. This is overruled for the direct arguments of comparison functions. */ Item_args::propagate_equal_fields(thd, Context_identity(), cond); return this; } bool has_rand_bit() { return used_tables() & RAND_TABLE_BIT; } bool excl_dep_on_table(table_map tab_map) override { if (used_tables() & (OUTER_REF_TABLE_BIT | RAND_TABLE_BIT)) return false; return !(used_tables() & ~tab_map) || Item_args::excl_dep_on_table(tab_map); } bool excl_dep_on_grouping_fields(st_select_lex *sel) override { if (has_rand_bit() || with_subquery()) return false; return Item_args::excl_dep_on_grouping_fields(sel); } bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override { return Item_args::excl_dep_on_in_subq_left_part(subq_pred); } /* We assume the result of any function that has a TIMESTAMP argument to be timezone-dependent, since a TIMESTAMP value in both numeric and string contexts is interpreted according to the current timezone. The only exception is UNIX_TIMESTAMP() which returns the internal representation of a TIMESTAMP argument verbatim, and thus does not depend on the timezone. */ bool check_valid_arguments_processor(void *bool_arg) override { return has_timestamp_args(); } bool find_function_processor (void *arg) override { return functype() == *(Functype *) arg; } void no_rows_in_result() override { for (uint i= 0; i < arg_count; i++) { args[i]->no_rows_in_result(); } } void restore_to_before_no_rows_in_result() override { for (uint i= 0; i < arg_count; i++) { args[i]->restore_to_before_no_rows_in_result(); } } void convert_const_compared_to_int_field(THD *thd); Item_func *get_item_func() override { return this; } bool is_simplified_cond_processor(void *) override { return const_item() && !val_bool(); } }; class Item_real_func :public Item_func { public: Item_real_func(THD *thd): Item_func(thd) { collation= DTCollation_numeric(); } Item_real_func(THD *thd, Item *a): Item_func(thd, a) { collation= DTCollation_numeric(); } Item_real_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { collation= DTCollation_numeric(); } Item_real_func(THD *thd, List &list): Item_func(thd, list) { collation= DTCollation_numeric(); } String *val_str(String*str) override; my_decimal *val_decimal(my_decimal *decimal_value) override; longlong val_int() override { DBUG_ASSERT(fixed()); return Converter_double_to_longlong(val_real(), unsigned_flag).result(); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_real(thd, ltime, fuzzydate); } const Type_handler *type_handler() const override { return &type_handler_double; } bool fix_length_and_dec() override { decimals= NOT_FIXED_DEC; max_length= float_length(decimals); return FALSE; } }; /** Functions whose returned field type is determined at fix_fields() time. */ class Item_hybrid_func: public Item_func, public Type_handler_hybrid_field_type { protected: bool fix_attributes(Item **item, uint nitems); public: Item_hybrid_func(THD *thd): Item_func(thd) { } Item_hybrid_func(THD *thd, Item *a): Item_func(thd, a) { } Item_hybrid_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { } Item_hybrid_func(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b, c) { } Item_hybrid_func(THD *thd, List &list): Item_func(thd, list) { } Item_hybrid_func(THD *thd, Item_hybrid_func *item) :Item_func(thd, item), Type_handler_hybrid_field_type(item) { } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } void fix_length_and_dec_long_or_longlong(uint char_length, bool unsigned_arg) { collation= DTCollation_numeric(); unsigned_flag= unsigned_arg; max_length= char_length; set_handler(Type_handler::type_handler_long_or_longlong(char_length, unsigned_arg)); } void fix_length_and_dec_ulong_or_ulonglong_by_nbits(uint nbits) { uint digits= Type_handler_bit::Bit_decimal_notation_int_digits_by_nbits(nbits); collation= DTCollation_numeric(); unsigned_flag= true; max_length= digits; if (nbits > 32) set_handler(&type_handler_ulonglong); else set_handler(&type_handler_ulong); } }; class Item_handled_func: public Item_func { public: class Handler { public: virtual ~Handler() = default; virtual String *val_str(Item_handled_func *, String *) const= 0; virtual String *val_str_ascii(Item_handled_func *, String *) const= 0; virtual double val_real(Item_handled_func *) const= 0; virtual longlong val_int(Item_handled_func *) const= 0; virtual my_decimal *val_decimal(Item_handled_func *, my_decimal *) const= 0; virtual bool get_date(THD *thd, Item_handled_func *, MYSQL_TIME *, date_mode_t fuzzydate) const= 0; virtual bool val_native(THD *thd, Item_handled_func *, Native *to) const { DBUG_ASSERT(0); to->length(0); return true; } virtual const Type_handler * return_type_handler(const Item_handled_func *item) const= 0; virtual const Type_handler * type_handler_for_create_select(const Item_handled_func *item) const { return return_type_handler(item); } virtual bool fix_length_and_dec(Item_handled_func *) const= 0; }; class Handler_str: public Handler { public: String *val_str_ascii(Item_handled_func *item, String *str) const override { return item->Item::val_str_ascii(str); } double val_real(Item_handled_func *item) const override { DBUG_ASSERT(item->fixed()); StringBuffer<64> tmp; String *res= item->val_str(&tmp); return res ? item->double_from_string_with_check(res) : 0.0; } longlong val_int(Item_handled_func *item) const override { DBUG_ASSERT(item->fixed()); StringBuffer<22> tmp; String *res= item->val_str(&tmp); return res ? item->longlong_from_string_with_check(res) : 0; } my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const override { return item->val_decimal_from_string(to); } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzydate) const override { return item->get_date_from_string(thd, to, fuzzydate); } }; /** Abstract class for functions returning TIME, DATE, DATETIME or string values, whose data type depends on parameters and is set at fix_fields time. */ class Handler_temporal: public Handler { public: String *val_str(Item_handled_func *item, String *to) const override { StringBuffer ascii_buf; return item->val_str_from_val_str_ascii(to, &ascii_buf); } }; /** Abstract class for functions returning strings, which are generated from get_date() results, when get_date() can return different MYSQL_TIMESTAMP_XXX per row. */ class Handler_temporal_string: public Handler_temporal { public: const Type_handler *return_type_handler(const Item_handled_func *) const override { return &type_handler_string; } const Type_handler * type_handler_for_create_select(const Item_handled_func *item) const override { return return_type_handler(item)->type_handler_for_tmp_table(item); } double val_real(Item_handled_func *item) const override { return Temporal_hybrid(item).to_double(); } longlong val_int(Item_handled_func *item) const override { return Temporal_hybrid(item).to_longlong(); } my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const override { return Temporal_hybrid(item).to_decimal(to); } String *val_str_ascii(Item_handled_func *item, String *to) const override { return Temporal_hybrid(item).to_string(to, item->decimals); } }; class Handler_date: public Handler_temporal { public: const Type_handler *return_type_handler(const Item_handled_func *) const override { return &type_handler_newdate; } bool fix_length_and_dec(Item_handled_func *item) const override { item->fix_attributes_date(); return false; } double val_real(Item_handled_func *item) const override { return Date(item).to_double(); } longlong val_int(Item_handled_func *item) const override { return Date(item).to_longlong(); } my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const override { return Date(item).to_decimal(to); } String *val_str_ascii(Item_handled_func *item, String *to) const override { return Date(item).to_string(to); } }; class Handler_time: public Handler_temporal { public: const Type_handler *return_type_handler(const Item_handled_func *) const override { return &type_handler_time2; } double val_real(Item_handled_func *item) const override { return Time(item).to_double(); } longlong val_int(Item_handled_func *item) const override { return Time(item).to_longlong(); } my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const override { return Time(item).to_decimal(to); } String *val_str_ascii(Item_handled_func *item, String *to) const override { return Time(item).to_string(to, item->decimals); } bool val_native(THD *thd, Item_handled_func *item, Native *to) const override { return Time(thd, item).to_native(to, item->decimals); } }; class Handler_datetime: public Handler_temporal { public: const Type_handler *return_type_handler(const Item_handled_func *) const override { return &type_handler_datetime2; } double val_real(Item_handled_func *item) const override { return Datetime(item).to_double(); } longlong val_int(Item_handled_func *item) const override { return Datetime(item).to_longlong(); } my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const override { return Datetime(item).to_decimal(to); } String *val_str_ascii(Item_handled_func *item, String *to) const override { return Datetime(item).to_string(to, item->decimals); } }; class Handler_int: public Handler { public: String *val_str(Item_handled_func *item, String *to) const override { longlong nr= val_int(item); if (item->null_value) return 0; to->set_int(nr, item->unsigned_flag, item->collation.collation); return to; } String *val_str_ascii(Item_handled_func *item, String *to) const override { return item->Item::val_str_ascii(to); } double val_real(Item_handled_func *item) const override { return item->unsigned_flag ? (double) ((ulonglong) val_int(item)) : (double) val_int(item); } my_decimal *val_decimal(Item_handled_func *item, my_decimal *to) const override { return item->val_decimal_from_int(to); } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzydate) const override { return item->get_date_from_int(thd, to, fuzzydate); } longlong val_int(Item_handled_func *item) const override { Longlong_null tmp= to_longlong_null(item); item->null_value= tmp.is_null(); return tmp.value(); } virtual Longlong_null to_longlong_null(Item_handled_func *item) const= 0; }; class Handler_slong: public Handler_int { public: const Type_handler *return_type_handler(const Item_handled_func *item) const override { return &type_handler_slong; } bool fix_length_and_dec(Item_handled_func *item) const override { item->unsigned_flag= false; item->collation= DTCollation_numeric(); item->fix_char_length(11); return false; } }; class Handler_slong2: public Handler_slong { public: bool fix_length_and_dec(Item_handled_func *func) const override { bool rc= Handler_slong::fix_length_and_dec(func); func->max_length= 2; return rc; } }; class Handler_ulonglong: public Handler_int { public: const Type_handler *return_type_handler(const Item_handled_func *item) const override { return &type_handler_ulonglong; } bool fix_length_and_dec(Item_handled_func *item) const override { item->unsigned_flag= true; item->collation= DTCollation_numeric(); item->fix_char_length(21); return false; } }; protected: const Handler *m_func_handler; public: Item_handled_func(THD *thd, Item *a) :Item_func(thd, a), m_func_handler(NULL) { } Item_handled_func(THD *thd, Item *a, Item *b) :Item_func(thd, a, b), m_func_handler(NULL) { } void set_func_handler(const Handler *handler) { m_func_handler= handler; } const Type_handler *type_handler() const override { return m_func_handler->return_type_handler(this); } Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { DBUG_ASSERT(fixed()); const Type_handler *h= m_func_handler->type_handler_for_create_select(this); return h->make_and_init_table_field(root, &name, Record_addr(maybe_null()), *this, table); } String *val_str(String *to) override { return m_func_handler->val_str(this, to); } String *val_str_ascii(String *to) override { return m_func_handler->val_str_ascii(this, to); } double val_real() override { return m_func_handler->val_real(this); } longlong val_int() override { return m_func_handler->val_int(this); } my_decimal *val_decimal(my_decimal *to) override { return m_func_handler->val_decimal(this, to); } bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) override { return m_func_handler->get_date(thd, this, to, fuzzydate); } bool val_native(THD *thd, Native *to) override { return m_func_handler->val_native(thd, this, to); } }; /** Functions that at fix_fields() time determine the returned field type, trying to preserve the exact data type of the arguments. The descendants have to implement "native" value methods, i.e. str_op(), date_op(), int_op(), real_op(), decimal_op(). fix_fields() chooses which of the above value methods will be used during execution time, according to the returned field type. For example, if fix_fields() determines that the returned value type is MYSQL_TYPE_LONG, then: - int_op() is chosen as the execution time native method. - val_int() returns the result of int_op() as is. - all other methods, i.e. val_real(), val_decimal(), val_str(), get_date(), call int_op() first, then convert the result to the requested data type. */ class Item_func_hybrid_field_type: public Item_hybrid_func { /* Helper methods to make sure that the result of decimal_op(), str_op() and date_op() is properly synched with null_value. */ bool date_op_with_null_check(THD *thd, MYSQL_TIME *ltime) { bool rc= date_op(thd, ltime, date_mode_t(0)); DBUG_ASSERT(!rc ^ null_value); return rc; } bool time_op_with_null_check(THD *thd, MYSQL_TIME *ltime) { bool rc= time_op(thd, ltime); DBUG_ASSERT(!rc ^ null_value); DBUG_ASSERT(rc || ltime->time_type == MYSQL_TIMESTAMP_TIME); return rc; } String *str_op_with_null_check(String *str) { String *res= str_op(str); DBUG_ASSERT((res != NULL) ^ null_value); return res; } public: // Value methods that involve no conversion String *val_str_from_str_op(String *str) { return str_op_with_null_check(&str_value); } longlong val_int_from_int_op() { return int_op(); } double val_real_from_real_op() { return real_op(); } // Value methods that involve conversion String *val_str_from_real_op(String *str); String *val_str_from_int_op(String *str); String *val_str_from_date_op(String *str); String *val_str_from_time_op(String *str); my_decimal *val_decimal_from_str_op(my_decimal *dec); my_decimal *val_decimal_from_real_op(my_decimal *dec); my_decimal *val_decimal_from_int_op(my_decimal *dec); my_decimal *val_decimal_from_date_op(my_decimal *dec); my_decimal *val_decimal_from_time_op(my_decimal *dec); longlong val_int_from_str_op(); longlong val_int_from_real_op(); longlong val_int_from_date_op(); longlong val_int_from_time_op(); double val_real_from_str_op(); double val_real_from_date_op(); double val_real_from_time_op(); double val_real_from_int_op(); public: Item_func_hybrid_field_type(THD *thd): Item_hybrid_func(thd) { collation= DTCollation_numeric(); } Item_func_hybrid_field_type(THD *thd, Item *a): Item_hybrid_func(thd, a) { collation= DTCollation_numeric(); } Item_func_hybrid_field_type(THD *thd, Item *a, Item *b): Item_hybrid_func(thd, a, b) { collation= DTCollation_numeric(); } Item_func_hybrid_field_type(THD *thd, Item *a, Item *b, Item *c): Item_hybrid_func(thd, a, b, c) { collation= DTCollation_numeric(); } Item_func_hybrid_field_type(THD *thd, List &list): Item_hybrid_func(thd, list) { collation= DTCollation_numeric(); } double val_real() override { DBUG_ASSERT(fixed()); return Item_func_hybrid_field_type::type_handler()-> Item_func_hybrid_field_type_val_real(this); } longlong val_int() override { DBUG_ASSERT(!is_cond()); DBUG_ASSERT(fixed()); return Item_func_hybrid_field_type::type_handler()-> Item_func_hybrid_field_type_val_int(this); } my_decimal *val_decimal(my_decimal *dec) override { DBUG_ASSERT(fixed()); return Item_func_hybrid_field_type::type_handler()-> Item_func_hybrid_field_type_val_decimal(this, dec); } String *val_str(String*str) override { DBUG_ASSERT(fixed()); String *res= Item_func_hybrid_field_type::type_handler()-> Item_func_hybrid_field_type_val_str(this, str); DBUG_ASSERT(null_value == (res == NULL)); return res; } bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) override { DBUG_ASSERT(fixed()); return Item_func_hybrid_field_type::type_handler()-> Item_func_hybrid_field_type_get_date_with_warn(thd, this, to, mode); } bool val_native(THD *thd, Native *to) override { DBUG_ASSERT(fixed()); return native_op(thd, to); } /** @brief Performs the operation that this functions implements when the result type is INT. @return The result of the operation. */ virtual longlong int_op()= 0; Longlong_null to_longlong_null_op() { longlong nr= int_op(); /* C++ does not guarantee the order of parameter evaluation, so to make sure "null_value" is passed to the constructor after the int_op() call, int_op() is caled on a separate line. */ return Longlong_null(nr, null_value); } Longlong_hybrid_null to_longlong_hybrid_null_op() { return Longlong_hybrid_null(to_longlong_null_op(), unsigned_flag); } /** @brief Performs the operation that this functions implements when the result type is REAL. @return The result of the operation. */ virtual double real_op()= 0; Double_null to_double_null_op() { // val_real() must be caleed on a separate line. See to_longlong_null() double nr= real_op(); return Double_null(nr, null_value); } /** @brief Performs the operation that this functions implements when the result type is DECIMAL. @param A pointer where the DECIMAL value will be allocated. @return - 0 If the result is NULL - The same pointer it was given, with the area initialized to the result of the operation. */ virtual my_decimal *decimal_op(my_decimal *)= 0; /** @brief Performs the operation that this functions implements when the result type is a string type. @return The result of the operation. */ virtual String *str_op(String *)= 0; /** @brief Performs the operation that this functions implements when field type is DATETIME or DATE. @return The result of the operation. */ virtual bool date_op(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate)= 0; /** @brief Performs the operation that this functions implements when field type is TIME. @return The result of the operation. */ virtual bool time_op(THD *thd, MYSQL_TIME *res)= 0; virtual bool native_op(THD *thd, Native *native)= 0; }; /* This class resembles SQL standard CASE-alike expressions: CASE and its abbreviations COALESCE, NULLIF, IFNULL, IF. ::= | */ class Item_func_case_expression: public Item_func_hybrid_field_type { public: Item_func_case_expression(THD *thd) :Item_func_hybrid_field_type(thd) { } Item_func_case_expression(THD *thd, Item *a) :Item_func_hybrid_field_type(thd, a) { } Item_func_case_expression(THD *thd, Item *a, Item *b) :Item_func_hybrid_field_type(thd, a, b) { } Item_func_case_expression(THD *thd, Item *a, Item *b, Item *c) :Item_func_hybrid_field_type(thd, a, b, c) { } Item_func_case_expression(THD *thd, List &list): Item_func_hybrid_field_type(thd, list) { } bool find_not_null_fields(table_map allowed) override { return false; } }; class Item_func_numhybrid: public Item_func_hybrid_field_type { protected: inline void fix_decimals() { DBUG_ASSERT(result_type() == DECIMAL_RESULT); if (decimals == NOT_FIXED_DEC) set_if_smaller(decimals, max_length - 1); } public: Item_func_numhybrid(THD *thd): Item_func_hybrid_field_type(thd) { } Item_func_numhybrid(THD *thd, Item *a): Item_func_hybrid_field_type(thd, a) { } Item_func_numhybrid(THD *thd, Item *a, Item *b): Item_func_hybrid_field_type(thd, a, b) { } Item_func_numhybrid(THD *thd, Item *a, Item *b, Item *c): Item_func_hybrid_field_type(thd, a, b, c) { } Item_func_numhybrid(THD *thd, List &list): Item_func_hybrid_field_type(thd, list) { } String *str_op(String *str) override { DBUG_ASSERT(0); return 0; } bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { DBUG_ASSERT(0); return true; } bool time_op(THD *thd, MYSQL_TIME *ltime) override { DBUG_ASSERT(0); return true; } bool native_op(THD *thd, Native *to) override { DBUG_ASSERT(0); return true; } }; /* function where type of result detected by first argument */ class Item_func_num1: public Item_func_numhybrid { public: Item_func_num1(THD *thd, Item *a): Item_func_numhybrid(thd, a) {} Item_func_num1(THD *thd, Item *a, Item *b): Item_func_numhybrid(thd, a, b) {} bool check_partition_func_processor(void *int_arg) override { return FALSE; } bool check_vcol_func_processor(void *arg) override { return FALSE; } }; /* Base class for operations like '+', '-', '*' */ class Item_num_op :public Item_func_numhybrid { protected: bool check_arguments() const override { return false; // Checked by aggregate_for_num_op() } public: Item_num_op(THD *thd, Item *a, Item *b): Item_func_numhybrid(thd, a, b) {} virtual void result_precision()= 0; void print(String *str, enum_query_type query_type) override { print_op(str, query_type); } bool fix_type_handler(const Type_aggregator *aggregator); void fix_length_and_dec_double() { aggregate_numeric_attributes_real(args, arg_count); max_length= float_length(decimals); } void fix_length_and_dec_decimal() { unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag; result_precision(); fix_decimals(); } void fix_length_and_dec_int() { unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag; result_precision(); decimals= 0; set_handler(type_handler_long_or_longlong()); } void fix_length_and_dec_temporal(bool downcast_decimal_to_int) { set_handler(&type_handler_newdecimal); fix_length_and_dec_decimal(); if (decimals == 0 && downcast_decimal_to_int) set_handler(type_handler_long_or_longlong()); } bool need_parentheses_in_default() override { return true; } }; class Item_int_func :public Item_func { public: /* QQ: shouldn't 20 characters be enough: Max unsigned = 18,446,744,073,709,551,615 = 20 digits, 20 characters Max signed = 9,223,372,036,854,775,807 = 19 digits, 19 characters Min signed = -9,223,372,036,854,775,808 = 19 digits, 20 characters */ Item_int_func(THD *thd): Item_func(thd) { collation= DTCollation_numeric(); fix_char_length(21); } Item_int_func(THD *thd, Item *a): Item_func(thd, a) { collation= DTCollation_numeric(); fix_char_length(21); } Item_int_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { collation= DTCollation_numeric(); fix_char_length(21); } Item_int_func(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b, c) { collation= DTCollation_numeric(); fix_char_length(21); } Item_int_func(THD *thd, Item *a, Item *b, Item *c, Item *d): Item_func(thd, a, b, c, d) { collation= DTCollation_numeric(); fix_char_length(21); } Item_int_func(THD *thd, List &list): Item_func(thd, list) { collation= DTCollation_numeric(); fix_char_length(21); } Item_int_func(THD *thd, Item_int_func *item) :Item_func(thd, item) { collation= DTCollation_numeric(); } double val_real() override; String *val_str(String*str) override; my_decimal *val_decimal(my_decimal *decimal_value) override { return val_decimal_from_int(decimal_value); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_int(thd, ltime, fuzzydate); } const Type_handler *type_handler() const override= 0; bool fix_length_and_dec() override { return FALSE; } }; class Item_long_func: public Item_int_func { public: Item_long_func(THD *thd): Item_int_func(thd) { } Item_long_func(THD *thd, Item *a): Item_int_func(thd, a) {} Item_long_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} Item_long_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} Item_long_func(THD *thd, List &list): Item_int_func(thd, list) { } Item_long_func(THD *thd, Item_long_func *item) :Item_int_func(thd, item) {} const Type_handler *type_handler() const override { if (unsigned_flag) return &type_handler_ulong; return &type_handler_slong; } bool fix_length_and_dec() override { max_length= 11; return FALSE; } }; class Item_long_ge0_func: public Item_int_func { public: Item_long_ge0_func(THD *thd): Item_int_func(thd) { } Item_long_ge0_func(THD *thd, Item *a): Item_int_func(thd, a) {} Item_long_ge0_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} Item_long_ge0_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} Item_long_ge0_func(THD *thd, List &list): Item_int_func(thd, list) { } Item_long_ge0_func(THD *thd, Item_long_ge0_func *item) :Item_int_func(thd, item) {} const Type_handler *type_handler() const override { DBUG_ASSERT(!unsigned_flag); return &type_handler_slong_ge0; } bool fix_length_and_dec() override { max_length= 10; return FALSE; } }; class Item_func_hash: public Item_int_func { public: Item_func_hash(THD *thd, List &item): Item_int_func(thd, item) {} longlong val_int() override; bool fix_length_and_dec() override; const Type_handler *type_handler() const override { return &type_handler_slong; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } }; class Item_func_hash_mariadb_100403: public Item_func_hash { public: Item_func_hash_mariadb_100403(THD *thd, List &item) :Item_func_hash(thd, item) {} longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } }; class Item_longlong_func: public Item_int_func { public: Item_longlong_func(THD *thd): Item_int_func(thd) { } Item_longlong_func(THD *thd, Item *a): Item_int_func(thd, a) {} Item_longlong_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} Item_longlong_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} Item_longlong_func(THD *thd, Item *a, Item *b, Item *c, Item *d): Item_int_func(thd, a, b, c, d) {} Item_longlong_func(THD *thd, List &list): Item_int_func(thd, list) { } Item_longlong_func(THD *thd, Item_longlong_func *item) :Item_int_func(thd, item) {} const Type_handler *type_handler() const override { if (unsigned_flag) return &type_handler_ulonglong; return &type_handler_slonglong; } }; class Cursor_ref { protected: LEX_CSTRING m_cursor_name; uint m_cursor_offset; class sp_cursor *get_open_cursor_or_error(); Cursor_ref(const LEX_CSTRING *name, uint offset) :m_cursor_name(*name), m_cursor_offset(offset) { } void print_func(String *str, const LEX_CSTRING &func_name); }; class Item_func_cursor_rowcount: public Item_longlong_func, public Cursor_ref { public: Item_func_cursor_rowcount(THD *thd, const LEX_CSTRING *name, uint offset) :Item_longlong_func(thd), Cursor_ref(name, offset) { set_maybe_null(); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("%ROWCOUNT") }; return name; } longlong val_int() override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), arg, VCOL_SESSION_FUNC); } void print(String *str, enum_query_type query_type) override { return Cursor_ref::print_func(str, func_name_cstring()); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_connection_id :public Item_long_func { longlong value; public: Item_func_connection_id(THD *thd): Item_long_func(thd) { unsigned_flag=1; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("connection_id") }; return name; } bool fix_length_and_dec() override; bool fix_fields(THD *thd, Item **ref) override; longlong val_int() override { DBUG_ASSERT(fixed()); return value; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_signed :public Item_int_func { public: Item_func_signed(THD *thd, Item *a): Item_int_func(thd, a) { unsigned_flag= 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_signed") }; return name; } const Type_handler *type_handler() const override { return Type_handler::type_handler_long_or_longlong(max_char_length(), false); } longlong val_int() override { longlong value= args[0]->val_int_signed_typecast(); null_value= args[0]->null_value; return value; } void fix_length_and_dec_double() { fix_char_length(MAX_BIGINT_WIDTH); } void fix_length_and_dec_sint_ge0() { uint32 digits= args[0]->decimal_precision(); DBUG_ASSERT(digits > 0); DBUG_ASSERT(digits <= MY_INT64_NUM_DECIMAL_DIGITS); fix_char_length(digits + (unsigned_flag ? 0 : 1/*sign*/)); } void fix_length_and_dec_generic() { uint32 char_length= MY_MIN(args[0]->max_char_length(), MY_INT64_NUM_DECIMAL_DIGITS); /* args[0]->max_char_length() can return 0. Reserve max_length to fit at least one character for one digit, plus one character for the sign (if signed). */ set_if_bigger(char_length, 1U + (unsigned_flag ? 0 : 1)); fix_char_length(char_length); } void fix_length_and_dec_string() { /* For strings, use decimal_int_part() instead of max_char_length(). This is important for Item_hex_hybrid: SELECT CAST(0x1FFFFFFFF AS SIGNED); Length is 5, decimal_int_part() is 13. */ uint32 char_length= MY_MIN(args[0]->decimal_int_part(), MY_INT64_NUM_DECIMAL_DIGITS); set_if_bigger(char_length, 1U + (unsigned_flag ? 0 : 1)); fix_char_length(char_length); } bool fix_length_and_dec() override { return args[0]->type_handler()->Item_func_signed_fix_length_and_dec(this); } void print(String *str, enum_query_type query_type) override; decimal_digits_t decimal_precision() const override { return args[0]->decimal_precision(); } bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_unsigned :public Item_func_signed { public: Item_func_unsigned(THD *thd, Item *a): Item_func_signed(thd, a) { unsigned_flag= 1; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_unsigned") }; return name; } const Type_handler *type_handler() const override { if (max_char_length() <= MY_INT32_NUM_DECIMAL_DIGITS - 1) return &type_handler_ulong; return &type_handler_ulonglong; } longlong val_int() override { longlong value= args[0]->val_int_unsigned_typecast(); null_value= args[0]->null_value; return value; } bool fix_length_and_dec() override { return args[0]->type_handler()->Item_func_unsigned_fix_length_and_dec(this); } decimal_digits_t decimal_precision() const override { return max_length; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_decimal_typecast :public Item_func { my_decimal decimal_value; public: Item_decimal_typecast(THD *thd, Item *a, uint len, decimal_digits_t dec) :Item_func(thd, a) { decimals= dec; collation= DTCollation_numeric(); fix_char_length(my_decimal_precision_to_length_no_truncation(len, dec, unsigned_flag)); } String *val_str(String *str) override { return VDec(this).to_string(str); } double val_real() override { return VDec(this).to_double(); } longlong val_int() override { return VDec(this).to_longlong(unsigned_flag); } my_decimal *val_decimal(my_decimal*) override; bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) override { return decimal_to_datetime_with_warn(thd, VDec(this).ptr(), to, mode, NULL, NULL); } const Type_handler *type_handler() const override { return &type_handler_newdecimal; } void fix_length_and_dec_generic() {} bool fix_length_and_dec() override { return args[0]->type_handler()->Item_decimal_typecast_fix_length_and_dec(this); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("decimal_typecast") }; return name; } void print(String *str, enum_query_type query_type) override; bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_real_typecast: public Item_real_func { protected: double val_real_with_truncate(double max_value); public: Item_real_typecast(THD *thd, Item *a, uint len, uint dec) :Item_real_func(thd, a) { decimals= (uint8) dec; max_length= (uint32) len; } bool need_parentheses_in_default() override { return true; } void print(String *str, enum_query_type query_type) override; void fix_length_and_dec_generic() { set_maybe_null(); } }; class Item_float_typecast :public Item_real_typecast { public: Item_float_typecast(THD *thd, Item *a) :Item_real_typecast(thd, a, MAX_FLOAT_STR_LENGTH, NOT_FIXED_DEC) { } const Type_handler *type_handler() const override { return &type_handler_float; } bool fix_length_and_dec() override { return args[0]->type_handler()->Item_float_typecast_fix_length_and_dec(this); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("float_typecast") }; return name; } double val_real() override { return (double) (float) val_real_with_truncate(FLT_MAX); } String *val_str(String*str) override { Float nr(Item_float_typecast::val_real()); if (null_value) return 0; nr.to_string(str, decimals); return str; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_double_typecast :public Item_real_typecast { public: Item_double_typecast(THD *thd, Item *a, uint len, uint dec): Item_real_typecast(thd, a, len, dec) { } bool fix_length_and_dec() override { return args[0]->type_handler()->Item_double_typecast_fix_length_and_dec(this); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("double_typecast") }; return name; } double val_real() override { return val_real_with_truncate(DBL_MAX); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_additive_op :public Item_num_op { public: Item_func_additive_op(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} void result_precision() override; bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} }; class Item_func_plus :public Item_func_additive_op { public: Item_func_plus(THD *thd, Item *a, Item *b): Item_func_additive_op(thd, a, b) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("+") }; return name; } enum precedence precedence() const override { return ADD_PRECEDENCE; } bool fix_length_and_dec() override; longlong int_op() override; double real_op() override; my_decimal *decimal_op(my_decimal *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_minus :public Item_func_additive_op { bool m_depends_on_sql_mode_no_unsigned_subtraction; public: Item_func_minus(THD *thd, Item *a, Item *b): Item_func_additive_op(thd, a, b), m_depends_on_sql_mode_no_unsigned_subtraction(false) { } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("-") }; return name; } enum precedence precedence() const override { return ADD_PRECEDENCE; } Sql_mode_dependency value_depends_on_sql_mode() const override; longlong int_op() override; double real_op() override; my_decimal *decimal_op(my_decimal *) override; bool fix_length_and_dec() override; void fix_unsigned_flag(); void fix_length_and_dec_double() { Item_func_additive_op::fix_length_and_dec_double(); fix_unsigned_flag(); } void fix_length_and_dec_decimal() { Item_func_additive_op::fix_length_and_dec_decimal(); fix_unsigned_flag(); } void fix_length_and_dec_int() { Item_func_additive_op::fix_length_and_dec_int(); fix_unsigned_flag(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_mul :public Item_num_op { public: Item_func_mul(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("*") }; return name; } enum precedence precedence() const override { return MUL_PRECEDENCE; } longlong int_op() override; double real_op() override; my_decimal *decimal_op(my_decimal *) override; void result_precision() override; bool fix_length_and_dec() override; bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_div :public Item_num_op { public: uint prec_increment; Item_func_div(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} longlong int_op() override { DBUG_ASSERT(0); return 0; } double real_op() override; my_decimal *decimal_op(my_decimal *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("/") }; return name; } enum precedence precedence() const override { return MUL_PRECEDENCE; } bool fix_length_and_dec() override; void fix_length_and_dec_double(); void fix_length_and_dec_int(); void result_precision() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_int_div :public Item_int_func { public: Item_func_int_div(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("DIV") }; return name; } enum precedence precedence() const override { return MUL_PRECEDENCE; } const Type_handler *type_handler() const override { return type_handler_long_or_longlong(); } bool fix_length_and_dec() override; void print(String *str, enum_query_type query_type) override { print_op(str, query_type); } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_mod :public Item_num_op { public: Item_func_mod(THD *thd, Item *a, Item *b): Item_num_op(thd, a, b) {} longlong int_op() override; double real_op() override; my_decimal *decimal_op(my_decimal *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("MOD") }; return name; } enum precedence precedence() const override { return MUL_PRECEDENCE; } void result_precision() override; bool fix_length_and_dec() override; void fix_length_and_dec_double() { Item_num_op::fix_length_and_dec_double(); unsigned_flag= args[0]->unsigned_flag; } void fix_length_and_dec_decimal() { result_precision(); fix_decimals(); } void fix_length_and_dec_int() { result_precision(); DBUG_ASSERT(decimals == 0); set_handler(type_handler_long_or_longlong()); } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_neg :public Item_func_num1 { public: Item_func_neg(THD *thd, Item *a): Item_func_num1(thd, a) {} double real_op() override; longlong int_op() override; my_decimal *decimal_op(my_decimal *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("-") }; return name; } enum Functype functype() const override { return NEG_FUNC; } enum precedence precedence() const override { return NEG_PRECEDENCE; } void print(String *str, enum_query_type query_type) override { str->append(func_name_cstring()); args[0]->print_parenthesised(str, query_type, precedence()); } void fix_length_and_dec_int(); void fix_length_and_dec_double(); void fix_length_and_dec_decimal(); bool fix_length_and_dec() override; decimal_digits_t decimal_precision() const override { return args[0]->decimal_precision(); } bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_abs :public Item_func_num1 { public: Item_func_abs(THD *thd, Item *a): Item_func_num1(thd, a) {} double real_op() override; longlong int_op() override; my_decimal *decimal_op(my_decimal *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("abs") }; return name; } void fix_length_and_dec_int(); void fix_length_and_dec_sint_ge0(); void fix_length_and_dec_double(); void fix_length_and_dec_decimal(); bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; // A class to handle logarithmic and trigonometric functions class Item_dec_func :public Item_real_func { bool check_arguments() const override { return check_argument_types_can_return_real(0, arg_count); } public: Item_dec_func(THD *thd, Item *a): Item_real_func(thd, a) {} Item_dec_func(THD *thd, Item *a, Item *b): Item_real_func(thd, a, b) {} bool fix_length_and_dec() override { decimals= NOT_FIXED_DEC; max_length= float_length(decimals); set_maybe_null(); return FALSE; } }; class Item_func_exp :public Item_dec_func { public: Item_func_exp(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("exp") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ln :public Item_dec_func { public: Item_func_ln(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ln") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_log :public Item_dec_func { public: Item_func_log(THD *thd, Item *a): Item_dec_func(thd, a) {} Item_func_log(THD *thd, Item *a, Item *b): Item_dec_func(thd, a, b) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("log") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_log2 :public Item_dec_func { public: Item_func_log2(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("log2") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_log10 :public Item_dec_func { public: Item_func_log10(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("log10") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sqrt :public Item_dec_func { public: Item_func_sqrt(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sqrt") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_pow :public Item_dec_func { public: Item_func_pow(THD *thd, Item *a, Item *b): Item_dec_func(thd, a, b) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("pow") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_acos :public Item_dec_func { public: Item_func_acos(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("acos") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_asin :public Item_dec_func { public: Item_func_asin(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("asin") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_atan :public Item_dec_func { public: Item_func_atan(THD *thd, Item *a): Item_dec_func(thd, a) {} Item_func_atan(THD *thd, Item *a, Item *b): Item_dec_func(thd, a, b) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("atan") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_cos :public Item_dec_func { public: Item_func_cos(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cos") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sin :public Item_dec_func { public: Item_func_sin(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sin") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_tan :public Item_dec_func { public: Item_func_tan(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("tan") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_cot :public Item_dec_func { public: Item_func_cot(THD *thd, Item *a): Item_dec_func(thd, a) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cot") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_int_val :public Item_func_hybrid_field_type { public: Item_func_int_val(THD *thd, Item *a): Item_func_hybrid_field_type(thd, a) {} bool check_partition_func_processor(void *int_arg) override { return FALSE; } bool check_vcol_func_processor(void *arg) override { return FALSE; } virtual decimal_round_mode round_mode() const= 0; void fix_length_and_dec_double(); void fix_length_and_dec_int_or_decimal(); void fix_length_and_dec_time() { fix_attributes_time(0); set_handler(&type_handler_time2); } void fix_length_and_dec_datetime() { fix_attributes_datetime(0); set_handler(&type_handler_datetime2); // Thinks like CEILING(TIMESTAMP'0000-01-01 23:59:59.9') returns NULL set_maybe_null(); } bool fix_length_and_dec() override; String *str_op(String *str) override { DBUG_ASSERT(0); return 0; } bool native_op(THD *thd, Native *to) override; }; class Item_func_ceiling :public Item_func_int_val { public: Item_func_ceiling(THD *thd, Item *a): Item_func_int_val(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ceiling") }; return name; } decimal_round_mode round_mode() const override { return CEILING; } longlong int_op() override; double real_op() override; my_decimal *decimal_op(my_decimal *) override; bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_floor :public Item_func_int_val { public: Item_func_floor(THD *thd, Item *a): Item_func_int_val(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("floor") }; return name; } decimal_round_mode round_mode() const override { return FLOOR; } longlong int_op() override; double real_op() override; my_decimal *decimal_op(my_decimal *) override; bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* This handles round and truncate */ class Item_func_round :public Item_func_hybrid_field_type { bool truncate; void fix_length_and_dec_decimal(uint decimals_to_set); void fix_length_and_dec_double(uint decimals_to_set); bool test_if_length_can_increase(); public: Item_func_round(THD *thd, Item *a, Item *b, bool trunc_arg) :Item_func_hybrid_field_type(thd, a, b), truncate(trunc_arg) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING truncate_name= {STRING_WITH_LEN("truncate") }; static LEX_CSTRING round_name= {STRING_WITH_LEN("round") }; return truncate ? truncate_name : round_name; } double real_op() override; longlong int_op() override; my_decimal *decimal_op(my_decimal *) override; bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; bool native_op(THD *thd, Native *to) override; String *str_op(String *str) override { DBUG_ASSERT(0); return NULL; } void fix_arg_decimal(); void fix_arg_int(const Type_handler *preferred, const Type_std_attributes *preferred_attributes, bool use_decimal_on_length_increase); void fix_arg_slong_ge0(); void fix_arg_hex_hybrid(); void fix_arg_double(); void fix_arg_time(); void fix_arg_datetime(); void fix_arg_temporal(const Type_handler *h, uint int_part_length); bool fix_length_and_dec() override { /* We don't want to translate ENUM/SET to CHAR here. So let's real_type_handler(), not type_handler(). */ return args[0]->real_type_handler()->Item_func_round_fix_length_and_dec(this); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_rand :public Item_real_func { struct my_rnd_struct *rand; bool first_eval; // TRUE if val_real() is called 1st time bool check_arguments() const override { return check_argument_types_can_return_int(0, arg_count); } void seed_random (Item * val); public: Item_func_rand(THD *thd, Item *a): Item_real_func(thd, a), rand(0), first_eval(TRUE) {} Item_func_rand(THD *thd): Item_real_func(thd) {} double val_real() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("rand") }; return name; } bool const_item() const override { return 0; } void update_used_tables() override; bool fix_fields(THD *thd, Item **ref) override; void cleanup() override { first_eval= TRUE; Item_real_func::cleanup(); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_rownum final :public Item_longlong_func { /* This points to a variable that contains the number of rows accpted so far in the result set */ ha_rows *accepted_rows; SELECT_LEX *select; public: Item_func_rownum(THD *thd); longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("rownum") }; return name; } enum Functype functype() const override { return ROWNUM_FUNC; } void update_used_tables() override {} bool const_item() const override { return 0; } void fix_after_optimize(THD *thd) override; bool fix_length_and_dec() override { unsigned_flag= 1; used_tables_cache= RAND_TABLE_BIT; const_item_cache=0; set_maybe_null(); return FALSE; } void cleanup() override { Item_longlong_func::cleanup(); /* Ensure we don't point to freed memory */ accepted_rows= 0; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } bool check_handler_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return 0; } /* This function is used in insert, update and delete */ void store_pointer_to_row_counter(ha_rows *row_counter) { accepted_rows= row_counter; } }; void fix_rownum_pointers(THD *thd, SELECT_LEX *select_lex, ha_rows *ptr); class Item_func_sign :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_real(func_name_cstring()); } public: Item_func_sign(THD *thd, Item *a): Item_long_func(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sign") }; return name; } decimal_digits_t decimal_precision() const override { return 1; } bool fix_length_and_dec() override { fix_char_length(2); return FALSE; } longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_units :public Item_real_func { LEX_CSTRING name; double mul,add; bool check_arguments() const override { return check_argument_types_can_return_real(0, arg_count); } public: Item_func_units(THD *thd, char *name_arg, Item *a, double mul_arg, double add_arg): Item_real_func(thd, a), mul(mul_arg), add(add_arg) { name.str= name_arg; name.length= strlen(name_arg); } double val_real() override; LEX_CSTRING func_name_cstring() const override { return name; } bool fix_length_and_dec() override { decimals= NOT_FIXED_DEC; max_length= float_length(decimals); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** Item_func_min_max does not derive from Item_func_hybrid_field_type because the way how its methods val_xxx() and get_date() work depend not only by its arguments, but also on the context in which LEAST() and GREATEST() appear. For example, using Item_func_min_max in a CAST like this: CAST(LEAST('11','2') AS SIGNED) forces Item_func_min_max to compare the arguments as numbers rather than strings. Perhaps this should be changed eventually (see MDEV-5893). */ class Item_func_min_max :public Item_hybrid_func { String tmp_value; int cmp_sign; protected: bool check_arguments() const override { return false; // Checked by aggregate_for_min_max() } bool fix_attributes(Item **item, uint nitems); public: Item_func_min_max(THD *thd, List &list, int cmp_sign_arg): Item_hybrid_func(thd, list), cmp_sign(cmp_sign_arg) {} String *val_str_native(String *str); double val_real_native(); longlong val_int_native(); longlong val_uint_native(); my_decimal *val_decimal_native(my_decimal *); bool get_date_native(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate); bool get_time_native(THD *thd, MYSQL_TIME *res); double val_real() override { DBUG_ASSERT(fixed()); return Item_func_min_max::type_handler()-> Item_func_min_max_val_real(this); } longlong val_int() override { DBUG_ASSERT(fixed()); return Item_func_min_max::type_handler()-> Item_func_min_max_val_int(this); } String *val_str(String *str) override { DBUG_ASSERT(fixed()); return Item_func_min_max::type_handler()-> Item_func_min_max_val_str(this, str); } my_decimal *val_decimal(my_decimal *dec) override { DBUG_ASSERT(fixed()); return Item_func_min_max::type_handler()-> Item_func_min_max_val_decimal(this, dec); } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override { DBUG_ASSERT(fixed()); return Item_func_min_max::type_handler()-> Item_func_min_max_get_date(thd, this, res, fuzzydate); } bool val_native(THD *thd, Native *to) override; void aggregate_attributes_real(Item **items, uint nitems) { /* Aggregating attributes for the double data type for LEAST/GREATEST is almost the same with aggregating for CASE-alike hybrid functions, (CASE..THEN, COALESCE, IF, etc). There is one notable difference though, when a numeric argument is mixed with a string argument: - CASE-alike functions return a string data type in such cases COALESCE(10,'x') -> VARCHAR(2) = '10' - LEAST/GREATEST returns double: GREATEST(10,'10e4') -> DOUBLE = 100000 As the string argument can represent a number in the scientific notation, like in the example above, max_length of the result can be longer than max_length of the arguments. To handle this properly, max_length is additionally assigned to the result of float_length(decimals). */ Item_func::aggregate_attributes_real(items, nitems); max_length= float_length(decimals); } bool fix_length_and_dec() override { if (aggregate_for_min_max(func_name_cstring(), args, arg_count)) return true; fix_attributes(args, arg_count); return false; } }; class Item_func_min :public Item_func_min_max { public: Item_func_min(THD *thd, List &list): Item_func_min_max(thd, list, 1) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("least") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_max :public Item_func_min_max { public: Item_func_max(THD *thd, List &list): Item_func_min_max(thd, list, -1) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("greatest") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Objects of this class are used for ROLLUP queries to wrap up each constant item referred to in GROUP BY list. */ class Item_func_rollup_const :public Item_func { public: Item_func_rollup_const(THD *thd, Item *a): Item_func(thd, a) { name= a->name; } double val_real() override { return val_real_from_item(args[0]); } longlong val_int() override { return val_int_from_item(args[0]); } String *val_str(String *str) override { return val_str_from_item(args[0], str); } bool val_native(THD *thd, Native *to) override { return val_native_from_item(thd, args[0], to); } my_decimal *val_decimal(my_decimal *dec) override { return val_decimal_from_item(args[0], dec); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_item(thd, args[0], ltime, fuzzydate); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("rollup_const") }; return name; } bool const_item() const override { return 0; } const Type_handler *type_handler() const override { return args[0]->type_handler(); } bool fix_length_and_dec() override { Type_std_attributes::set(*args[0]); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_long_func_length: public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_str(func_name_cstring()); } public: Item_long_func_length(THD *thd, Item *a): Item_long_func(thd, a) {} bool fix_length_and_dec() override { max_length=10; return FALSE; } }; class Item_func_octet_length :public Item_long_func_length { String value; public: Item_func_octet_length(THD *thd, Item *a): Item_long_func_length(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("octet_length") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_bit_length :public Item_longlong_func { String value; public: Item_func_bit_length(THD *thd, Item *a): Item_longlong_func(thd, a) {} bool fix_length_and_dec() override { max_length= 11; // 0x100000000*8 = 34,359,738,368 return FALSE; } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("bit_length") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_char_length :public Item_long_func_length { String value; public: Item_func_char_length(THD *thd, Item *a): Item_long_func_length(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("char_length") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_coercibility :public Item_long_func { longlong m_cached_collation_derivation; bool check_arguments() const override { return args[0]->check_type_can_return_str(func_name_cstring()); } public: Item_func_coercibility(THD *thd, Item *a): Item_long_func(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("coercibility") }; return name; } bool fix_length_and_dec() override; bool eval_not_null_tables(void *) override { not_null_tables_cache= 0; return false; } bool find_not_null_fields(table_map allowed) override { return false; } Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { return this; } bool const_item() const override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } table_map used_tables() const override { return 0; } }; /* In the corner case LOCATE could return (4,294,967,296 + 1), which would not fit into Item_long_func range. But string lengths are limited with max_allowed_packet, which cannot be bigger than 1024*1024*1024. */ class Item_func_locate :public Item_long_func { bool check_arguments() const override { return check_argument_types_can_return_str(0, 2) || (arg_count > 2 && args[2]->check_type_can_return_int(func_name_cstring())); } String value1,value2; DTCollation cmp_collation; public: Item_func_locate(THD *thd, Item *a, Item *b) :Item_long_func(thd, a, b) {} Item_func_locate(THD *thd, Item *a, Item *b, Item *c) :Item_long_func(thd, a, b, c) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("locate") }; return name; } longlong val_int() override; bool fix_length_and_dec() override { max_length= MY_INT32_NUM_DECIMAL_DIGITS; return agg_arg_charsets_for_comparison(cmp_collation, args, 2); } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_field :public Item_long_func { String value,tmp; Item_result cmp_type; DTCollation cmp_collation; public: Item_func_field(THD *thd, List &list): Item_long_func(thd, list) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("field") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ascii :public Item_long_func { bool check_arguments() const override { return check_argument_types_can_return_str(0, arg_count); } String value; public: Item_func_ascii(THD *thd, Item *a): Item_long_func(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ascii") }; return name; } bool fix_length_and_dec() override { max_length=3; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ord :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_str(func_name_cstring()); } String value; public: Item_func_ord(THD *thd, Item *a): Item_long_func(thd, a) {} bool fix_length_and_dec() override { fix_char_length(7); return FALSE; } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ord") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_find_in_set :public Item_long_func { bool check_arguments() const override { return check_argument_types_can_return_str(0, 2); } String value,value2; uint enum_value; ulonglong enum_bit; DTCollation cmp_collation; public: Item_func_find_in_set(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b), enum_value(0) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("find_in_set") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Base class for all bit functions: '~', '|', '^', '&', '>>', '<<' */ class Item_func_bit_operator: public Item_handled_func { bool check_arguments() const override { return check_argument_types_can_return_int(0, arg_count); } protected: bool fix_length_and_dec_op1_std(const Handler *ha_int, const Handler *ha_dec) { set_func_handler(args[0]->cmp_type() == INT_RESULT ? ha_int : ha_dec); return m_func_handler->fix_length_and_dec(this); } bool fix_length_and_dec_op2_std(const Handler *ha_int, const Handler *ha_dec) { set_func_handler(args[0]->cmp_type() == INT_RESULT && args[1]->cmp_type() == INT_RESULT ? ha_int : ha_dec); return m_func_handler->fix_length_and_dec(this); } public: Item_func_bit_operator(THD *thd, Item *a) :Item_handled_func(thd, a) {} Item_func_bit_operator(THD *thd, Item *a, Item *b) :Item_handled_func(thd, a, b) {} void print(String *str, enum_query_type query_type) override { print_op(str, query_type); } bool need_parentheses_in_default() override { return true; } }; class Item_func_bit_or :public Item_func_bit_operator { public: Item_func_bit_or(THD *thd, Item *a, Item *b) :Item_func_bit_operator(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("|") }; return name; } enum precedence precedence() const override { return BITOR_PRECEDENCE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_bit_and :public Item_func_bit_operator { public: Item_func_bit_and(THD *thd, Item *a, Item *b) :Item_func_bit_operator(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("&") }; return name; } enum precedence precedence() const override { return BITAND_PRECEDENCE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_bit_count :public Item_handled_func { bool check_arguments() const override { return args[0]->check_type_can_return_int(func_name_cstring()); } public: Item_func_bit_count(THD *thd, Item *a): Item_handled_func(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("bit_count") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_shift_left :public Item_func_bit_operator { public: Item_func_shift_left(THD *thd, Item *a, Item *b) :Item_func_bit_operator(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("<<") }; return name; } enum precedence precedence() const override { return SHIFT_PRECEDENCE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_shift_right :public Item_func_bit_operator { public: Item_func_shift_right(THD *thd, Item *a, Item *b) :Item_func_bit_operator(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN(">>") }; return name; } enum precedence precedence() const override { return SHIFT_PRECEDENCE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_bit_neg :public Item_func_bit_operator { public: Item_func_bit_neg(THD *thd, Item *a): Item_func_bit_operator(thd, a) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("~") }; return name; } enum precedence precedence() const override { return NEG_PRECEDENCE; } void print(String *str, enum_query_type query_type) override { str->append(func_name_cstring()); args[0]->print_parenthesised(str, query_type, precedence()); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_last_insert_id :public Item_longlong_func { bool check_arguments() const override { return check_argument_types_can_return_int(0, arg_count); } public: Item_func_last_insert_id(THD *thd): Item_longlong_func(thd) {} Item_func_last_insert_id(THD *thd, Item *a): Item_longlong_func(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("last_insert_id") }; return name; } bool fix_length_and_dec() override { unsigned_flag= true; if (arg_count) max_length= args[0]->max_length; return FALSE; } bool fix_fields(THD *thd, Item **ref) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_benchmark :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_int(func_name_cstring()) || args[1]->check_type_scalar(func_name_cstring()); } public: Item_func_benchmark(THD *thd, Item *count_expr, Item *expr): Item_long_func(thd, count_expr, expr) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("benchmark") }; return name; } bool fix_length_and_dec() override { max_length=1; base_flags&= ~item_base_t::MAYBE_NULL; return FALSE; } void print(String *str, enum_query_type query_type) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; void item_func_sleep_init(void); void item_func_sleep_free(void); class Item_func_sleep :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_real(func_name_cstring()); } public: Item_func_sleep(THD *thd, Item *a): Item_long_func(thd, a) {} bool fix_length_and_dec() override { fix_char_length(1); return FALSE; } bool const_item() const override { return 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sleep") }; return name; } table_map used_tables() const override { return used_tables_cache | RAND_TABLE_BIT; } bool is_expensive() override { return 1; } longlong val_int() override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #ifdef HAVE_DLOPEN class Item_udf_func :public Item_func { /** Mark "this" as non-deterministic if it uses no tables and is not a constant at the same time. */ void set_non_deterministic_if_needed() { if (!const_item_cache && !used_tables_cache) used_tables_cache= RAND_TABLE_BIT; } protected: udf_handler udf; bool is_expensive_processor(void *arg) override { return TRUE; } class VDec_udf: public Dec_ptr_and_buffer { public: VDec_udf(Item_udf_func *func, udf_handler *udf) { my_bool tmp_null_value; m_ptr= udf->val_decimal(&tmp_null_value, &m_buffer); DBUG_ASSERT(is_null() == (tmp_null_value != 0)); func->null_value= is_null(); } }; public: Item_udf_func(THD *thd, udf_func *udf_arg): Item_func(thd), udf(udf_arg) {} Item_udf_func(THD *thd, udf_func *udf_arg, List &list): Item_func(thd, list), udf(udf_arg) {} LEX_CSTRING func_name_cstring() const override { const char *tmp= udf.name(); return { tmp, strlen(tmp) }; } enum Functype functype() const override { return UDF_FUNC; } bool fix_fields(THD *thd, Item **ref) override { DBUG_ASSERT(fixed() == 0); bool res= udf.fix_fields(thd, this, arg_count, args); set_non_deterministic_if_needed(); base_flags|= item_base_t::FIXED; return res; } void fix_num_length_and_dec(); void update_used_tables() override { /* TODO: Make a member in UDF_INIT and return if a UDF is deterministic or not. Currently UDF_INIT has a member (const_item) that is an in/out parameter to the init() call. The code in udf_handler::fix_fields also duplicates the arguments handling code in Item_func::fix_fields(). The lack of information if a UDF is deterministic makes writing a correct update_used_tables() for UDFs impossible. One solution to this would be : - Add a is_deterministic member of UDF_INIT - (optionally) deprecate the const_item member of UDF_INIT - Take away the duplicate code from udf_handler::fix_fields() and make Item_udf_func call Item_func::fix_fields() to process its arguments as for any other function. - Store the deterministic flag returned by _init into the udf_handler. - Don't implement Item_udf_func::fix_fields, implement Item_udf_func::fix_length_and_dec() instead (similar to non-UDF functions). - Override Item_func::update_used_tables to call Item_func::update_used_tables() and add a RAND_TABLE_BIT to the result of Item_func::update_used_tables() if the UDF is non-deterministic. - (optionally) rename RAND_TABLE_BIT to NONDETERMINISTIC_BIT to better describe its usage. The above would require a change of the UDF API. Until that change is done here's how the current code works: We call Item_func::update_used_tables() only when we know that the function depends on real non-const tables and is deterministic. This can be done only because we know that the optimizer will call update_used_tables() only when there's possibly a new const table. So update_used_tables() can only make a Item_func more constant than it is currently. That's why we don't need to do anything if a function is guaranteed to return non-constant (it's non-deterministic) or is already a const. */ if ((used_tables_cache & ~PSEUDO_TABLE_BITS) && !(used_tables_cache & RAND_TABLE_BIT)) { Item_func::update_used_tables(); set_non_deterministic_if_needed(); } } void cleanup() override; bool eval_not_null_tables(void *opt_arg) override { not_null_tables_cache= 0; return 0; } bool find_not_null_fields(table_map allowed) override { return false; } bool is_expensive() override { return 1; } void print(String *str, enum_query_type query_type) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } bool excl_dep_on_grouping_fields(st_select_lex *sel) override { return false; } }; class Item_func_udf_float :public Item_udf_func { public: Item_func_udf_float(THD *thd, udf_func *udf_arg): Item_udf_func(thd, udf_arg) {} Item_func_udf_float(THD *thd, udf_func *udf_arg, List &list): Item_udf_func(thd, udf_arg, list) {} longlong val_int() override { DBUG_ASSERT(fixed()); return Converter_double_to_longlong(Item_func_udf_float::val_real(), unsigned_flag).result(); } my_decimal *val_decimal(my_decimal *dec_buf) override { double res=val_real(); if (null_value) return NULL; double2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf); return dec_buf; } double val_real() override; String *val_str(String *str) override; const Type_handler *type_handler() const override { return &type_handler_double; } bool fix_length_and_dec() override { fix_num_length_and_dec(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_udf_int :public Item_udf_func { public: Item_func_udf_int(THD *thd, udf_func *udf_arg): Item_udf_func(thd, udf_arg) {} Item_func_udf_int(THD *thd, udf_func *udf_arg, List &list): Item_udf_func(thd, udf_arg, list) {} longlong val_int() override; double val_real() override { return (double) Item_func_udf_int::val_int(); } my_decimal *val_decimal(my_decimal *decimal_value) override { return val_decimal_from_int(decimal_value); } String *val_str(String *str) override; const Type_handler *type_handler() const override { if (unsigned_flag) return &type_handler_ulonglong; return &type_handler_slonglong; } bool fix_length_and_dec() override { decimals= 0; max_length= 21; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_udf_decimal :public Item_udf_func { public: Item_func_udf_decimal(THD *thd, udf_func *udf_arg): Item_udf_func(thd, udf_arg) {} Item_func_udf_decimal(THD *thd, udf_func *udf_arg, List &list): Item_udf_func(thd, udf_arg, list) {} longlong val_int() override { return VDec_udf(this, &udf).to_longlong(unsigned_flag); } double val_real() override { return VDec_udf(this, &udf).to_double(); } my_decimal *val_decimal(my_decimal *) override; String *val_str(String *str) override { return VDec_udf(this, &udf).to_string_round(str, decimals); } const Type_handler *type_handler() const override { return &type_handler_newdecimal; } bool fix_length_and_dec() override { fix_num_length_and_dec(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_udf_str :public Item_udf_func { public: Item_func_udf_str(THD *thd, udf_func *udf_arg): Item_udf_func(thd, udf_arg) {} Item_func_udf_str(THD *thd, udf_func *udf_arg, List &list): Item_udf_func(thd, udf_arg, list) {} String *val_str(String *) override; double val_real() override { int err_not_used; char *end_not_used; String *res; res= val_str(&str_value); return res ? res->charset()->strntod((char*) res->ptr(), res->length(), &end_not_used, &err_not_used) : 0.0; } longlong val_int() override { int err_not_used; String *res; res=val_str(&str_value); return res ? res->charset()->strntoll(res->ptr(),res->length(),10, (char**) 0, &err_not_used) : (longlong) 0; } my_decimal *val_decimal(my_decimal *dec_buf) override { String *res=val_str(&str_value); if (!res) return NULL; string2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf); return dec_buf; } const Type_handler *type_handler() const override { return string_type_handler(); } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #else /* Dummy functions to get yy_*.cc files compiled */ class Item_func_udf_float :public Item_real_func { public: Item_func_udf_float(THD *thd, udf_func *udf_arg): Item_real_func(thd) {} Item_func_udf_float(THD *thd, udf_func *udf_arg, List &list): Item_real_func(thd, list) {} double val_real() { DBUG_ASSERT(fixed()); return 0.0; } }; class Item_func_udf_int :public Item_int_func { public: Item_func_udf_int(THD *thd, udf_func *udf_arg): Item_int_func(thd) {} Item_func_udf_int(THD *thd, udf_func *udf_arg, List &list): Item_int_func(thd, list) {} const Type_handler *type_handler() const override { return &type_handler_slonglong; } longlong val_int() { DBUG_ASSERT(fixed()); return 0; } }; class Item_func_udf_decimal :public Item_int_func { public: Item_func_udf_decimal(THD *thd, udf_func *udf_arg): Item_int_func(thd) {} Item_func_udf_decimal(THD *thd, udf_func *udf_arg, List &list): Item_int_func(thd, list) {} const Type_handler *type_handler() const override { return &type_handler_slonglong; } my_decimal *val_decimal(my_decimal *) { DBUG_ASSERT(fixed()); return 0; } }; class Item_func_udf_str :public Item_func { public: Item_func_udf_str(THD *thd, udf_func *udf_arg): Item_func(thd) {} Item_func_udf_str(THD *thd, udf_func *udf_arg, List &list): Item_func(thd, list) {} String *val_str(String *) { DBUG_ASSERT(fixed()); null_value=1; return 0; } double val_real() { DBUG_ASSERT(fixed()); null_value= 1; return 0.0; } longlong val_int() { DBUG_ASSERT(fixed()); null_value=1; return 0; } bool fix_length_and_dec() override { base_flags|= item_base_t::MAYBE_NULL; max_length=0; return FALSE; } }; #endif /* HAVE_DLOPEN */ void mysql_ull_cleanup(THD *thd); void mysql_ull_set_explicit_lock_duration(THD *thd); class Item_func_lock :public Item_long_func { public: Item_func_lock(THD *thd): Item_long_func(thd) { } Item_func_lock(THD *thd, Item *a): Item_long_func(thd, a) {} Item_func_lock(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} table_map used_tables() const override { return used_tables_cache | RAND_TABLE_BIT; } bool const_item() const override { return 0; } bool is_expensive() override { return 1; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } }; class Item_func_get_lock final :public Item_func_lock { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()) || args[1]->check_type_can_return_real(func_name_cstring()); } String value; public: Item_func_get_lock(THD *thd, Item *a, Item *b) :Item_func_lock(thd, a, b) {} longlong val_int() override final; LEX_CSTRING func_name_cstring() const override final { static LEX_CSTRING name= {STRING_WITH_LEN("get_lock") }; return name; } bool fix_length_and_dec() override { max_length= 1; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override final { return get_item_copy(thd, this); } }; class Item_func_release_all_locks final :public Item_func_lock { public: Item_func_release_all_locks(THD *thd): Item_func_lock(thd) { unsigned_flag= 1; } longlong val_int() override final; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("release_all_locks") }; return name; } Item *do_get_copy(THD *thd) const override final { return get_item_copy(thd, this); } }; class Item_func_release_lock final :public Item_func_lock { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()); } String value; public: Item_func_release_lock(THD *thd, Item *a): Item_func_lock(thd, a) {} longlong val_int() override final; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("release_lock") }; return name; } bool fix_length_and_dec() override { max_length= 1; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override final { return get_item_copy(thd, this); } }; /* replication functions */ class Item_master_pos_wait :public Item_longlong_func { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()) || args[1]->check_type_can_return_int(func_name_cstring()) || (arg_count > 2 && args[2]->check_type_can_return_int(func_name_cstring())) || (arg_count > 3 && args[3]->check_type_general_purpose_string(func_name_cstring())); } String value; public: Item_master_pos_wait(THD *thd, Item *a, Item *b) :Item_longlong_func(thd, a, b) {} Item_master_pos_wait(THD *thd, Item *a, Item *b, Item *c): Item_longlong_func(thd, a, b, c) {} Item_master_pos_wait(THD *thd, Item *a, Item *b, Item *c, Item *d): Item_longlong_func(thd, a, b, c, d) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("master_pos_wait") }; return name; } bool fix_length_and_dec() override { max_length=21; set_maybe_null(); return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_master_gtid_wait :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()) || (arg_count > 1 && args[1]->check_type_can_return_real(func_name_cstring())); } String value; public: Item_master_gtid_wait(THD *thd, Item *a) :Item_long_func(thd, a) {} Item_master_gtid_wait(THD *thd, Item *a, Item *b) :Item_long_func(thd, a, b) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("master_gtid_wait") }; return name; } bool fix_length_and_dec() override { max_length=2; return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Handling of user definable variables */ class user_var_entry; /** A class to set and get user variables */ class Item_func_user_var :public Item_hybrid_func { protected: user_var_entry *m_var_entry; public: LEX_CSTRING name; // keep it public Item_func_user_var(THD *thd, const LEX_CSTRING *a) :Item_hybrid_func(thd), m_var_entry(NULL), name(*a) { } Item_func_user_var(THD *thd, const LEX_CSTRING *a, Item *b) :Item_hybrid_func(thd, b), m_var_entry(NULL), name(*a) { } Item_func_user_var(THD *thd, Item_func_user_var *item) :Item_hybrid_func(thd, item), m_var_entry(item->m_var_entry), name(item->name) { } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { DBUG_ASSERT(fixed()); return create_tmp_field_ex_from_handler(root, table, src, param, type_handler()); } Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { return create_table_field_from_handler(root, table); } bool check_vcol_func_processor(void *arg) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } }; class Item_func_set_user_var :public Item_func_user_var { /* The entry_thread_id variable is used: 1) to skip unnecessary updates of the entry field (see above); 2) to reset the entry field that was initialized in the other thread (for example, an item tree of a trigger that updates user variables may be shared between several connections, and the entry_thread_id field prevents updates of one connection user variables from a concurrent connection calling the same trigger that initially updated some user variable it the first connection context). */ my_thread_id entry_thread_id; String value; my_decimal decimal_buff; bool null_item; union { longlong vint; double vreal; String *vstr; my_decimal *vdec; } save_result; public: Item_func_set_user_var(THD *thd, const LEX_CSTRING *a, Item *b): Item_func_user_var(thd, a, b), entry_thread_id(0) {} Item_func_set_user_var(THD *thd, Item_func_set_user_var *item) :Item_func_user_var(thd, item), entry_thread_id(item->entry_thread_id), value(item->value), decimal_buff(item->decimal_buff), null_item(item->null_item), save_result(item->save_result) {} enum Functype functype() const override { return SUSERVAR_FUNC; } double val_real() override; longlong val_int() override; String *val_str(String *str) override; my_decimal *val_decimal(my_decimal *) override; double val_result() override; longlong val_int_result() override; bool val_bool_result() override; String *str_result(String *str) override; my_decimal *val_decimal_result(my_decimal *) override; bool is_null_result() override; bool update_hash(void *ptr, size_t length, const Type_handler *th, CHARSET_INFO *cs); bool send(Protocol *protocol, st_value *buffer) override; void make_send_field(THD *thd, Send_field *tmp_field) override; bool check(bool use_result_field); void save_item_result(Item *item); bool update(); bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return ASSIGN_PRECEDENCE; } void print_as_stmt(String *str, enum_query_type query_type); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("set_user_var") }; return name; } int save_in_field(Field *field, bool no_conversions, bool can_use_result_field); int save_in_field(Field *field, bool no_conversions) override { return save_in_field(field, no_conversions, 1); } void save_org_in_field(Field *field, fast_field_copier data __attribute__ ((__unused__))) override { (void) save_in_field(field, 1, 0); } bool register_field_in_read_map(void *arg) override; bool register_field_in_bitmap(void *arg) override; bool set_entry(THD *thd, bool create_if_not_exists); void cleanup() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool excl_dep_on_table(table_map tab_map) override { return false; } }; class Item_func_get_user_var :public Item_func_user_var, private Settable_routine_parameter { public: Item_func_get_user_var(THD *thd, const LEX_CSTRING *a): Item_func_user_var(thd, a) {} enum Functype functype() const override { return GUSERVAR_FUNC; } LEX_CSTRING get_name() { return name; } double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal*) override; String *val_str(String* str) override; bool fix_length_and_dec() override; void print(String *str, enum_query_type query_type) override; /* We must always return variables as strings to guard against selects of type select @t1:=1,@t1,@t:="hello",@t from foo where (@t1:= t2.b) */ LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("get_user_var") }; return name; } bool const_item() const override; table_map used_tables() const override { return const_item() ? 0 : RAND_TABLE_BIT; } bool eq(const Item *item, bool binary_cmp) const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override; public: Settable_routine_parameter *get_settable_routine_parameter() override { return this; } }; /* This item represents user variable used as out parameter (e.g in LOAD DATA), and it is supposed to be used only for this purprose. So it is simplified a lot. Actually you should never obtain its value. The only two reasons for this thing being an Item is possibility to store it in List and desire to place this code somewhere near other functions working with user variables. */ class Item_user_var_as_out_param :public Item_fixed_hybrid, public Load_data_outvar { LEX_CSTRING org_name; user_var_entry *entry; public: Item_user_var_as_out_param(THD *thd, const LEX_CSTRING *a) :Item_fixed_hybrid(thd) { DBUG_ASSERT(a->length < UINT_MAX32); org_name= *a; set_name(thd, a->str, a->length, system_charset_info); } Load_data_outvar *get_load_data_outvar() override { return this; } bool load_data_set_null(THD *thd, const Load_data_param *param) override { set_null_value(param->charset()); return false; } bool load_data_set_no_data(THD *thd, const Load_data_param *param) override { set_null_value(param->charset()); return false; } bool load_data_set_value(THD *thd, const char *pos, uint length, const Load_data_param *param) override { set_value(pos, length, param->charset()); return false; } void load_data_print_for_log_event(THD *thd, String *to) const override; bool load_data_add_outvar(THD *thd, Load_data_param *param) const override { return param->add_outvar_user_var(thd); } uint load_data_fixed_length() const override { return 0; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { DBUG_ASSERT(0); return NULL; } /* We should return something different from FIELD_ITEM here */ enum Type type() const override { return CONST_ITEM;} double val_real() override; longlong val_int() override; String *val_str(String *str) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; my_decimal *val_decimal(my_decimal *decimal_buffer) override; /* fix_fields() binds variable name with its entry structure */ bool fix_fields(THD *thd, Item **ref) override; void set_null_value(CHARSET_INFO* cs); void set_value(const char *str, uint length, CHARSET_INFO* cs); const Type_handler *type_handler() const override { return &type_handler_double; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /* A system variable */ #define GET_SYS_VAR_CACHE_LONG 1 #define GET_SYS_VAR_CACHE_DOUBLE 2 #define GET_SYS_VAR_CACHE_STRING 4 class Item_func_get_system_var :public Item_func { sys_var *var; enum_var_type var_type, orig_var_type; LEX_CSTRING component; longlong cached_llval; double cached_dval; String cached_strval; bool cached_null_value; query_id_t used_query_id; uchar cache_present; public: Item_func_get_system_var(THD *thd, sys_var *var_arg, enum_var_type var_type_arg, LEX_CSTRING *component_arg, const char *name_arg, size_t name_len_arg); enum Functype functype() const override { return GSYSVAR_FUNC; } void update_null_value() override; bool fix_length_and_dec() override; void print(String *str, enum_query_type query_type) override; bool const_item() const override { return true; } table_map used_tables() const override { return 0; } const Type_handler *type_handler() const override; double val_real() override; longlong val_int() override; String* val_str(String*) override; my_decimal *val_decimal(my_decimal *dec_buf) override { return val_decimal_from_real(dec_buf); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } /* TODO: fix to support views */ LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("get_system_var") }; return name; } /** Indicates whether this system variable is written to the binlog or not. Variables are written to the binlog as part of "status_vars" in Query_log_event, as an Intvar_log_event, or a Rand_log_event. @return true if the variable is written to the binlog, false otherwise. */ bool is_written_to_binlog(); bool eq(const Item *item, bool binary_cmp) const override; void cleanup() override; bool check_vcol_func_processor(void *arg) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* for fulltext search */ class Item_func_match :public Item_real_func { public: uint key, match_flags; bool join_key; DTCollation cmp_collation; FT_INFO *ft_handler; TABLE *table; Item_func_match *master; // for master-slave optimization Item *concat_ws; // Item_func_concat_ws String value; // value of concat_ws String search_value; // key_item()'s value converted to cmp_collation Item_func_match(THD *thd, List &a, uint b): Item_real_func(thd, a), key(0), match_flags(b), join_key(0), ft_handler(0), table(0), master(0), concat_ws(0) { } void cleanup() override { DBUG_ENTER("Item_func_match::cleanup"); Item_real_func::cleanup(); if (!master && ft_handler) ft_handler->please->close_search(ft_handler); ft_handler= 0; concat_ws= 0; table= 0; // required by Item_func_match::eq() DBUG_VOID_RETURN; } bool is_expensive_processor(void *arg) override { return TRUE; } enum Functype functype() const override { return FT_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("match") }; return name; } bool eval_not_null_tables(void *opt_arg) override { not_null_tables_cache= 0; return 0; } bool find_not_null_fields(table_map allowed) override { return false; } bool fix_fields(THD *thd, Item **ref) override; bool eq(const Item *, bool binary_cmp) const override; /* The following should be safe, even if we compare doubles */ longlong val_int() override { DBUG_ASSERT(fixed()); return val_real() != 0.0; } double val_real() override; void print(String *str, enum_query_type query_type) override; bool fix_index(); bool init_search(THD *thd, bool no_order); bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("match ... against()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return nullptr; } private: /** Check whether storage engine for given table, allows FTS Boolean search on non-indexed columns. @todo A flag should be added to the extended fulltext API so that it may be checked whether search on non-indexed columns are supported. Currently, it is not possible to check for such a flag since @c this->ft_handler is not yet set when this function is called. The current hack is to assume that search on non-indexed columns are supported for engines that does not support the extended fulltext API (e.g., MyISAM), while it is not supported for other engines (e.g., InnoDB) @param table_arg Table for which storage engine to check @retval true if BOOLEAN search on non-indexed columns is supported @retval false otherwise */ bool allows_search_on_non_indexed_columns(TABLE* table_arg) { // Only Boolean search may support non_indexed columns if (!(match_flags & FT_BOOL)) return false; DBUG_ASSERT(table_arg && table_arg->file); // Assume that if extended fulltext API is not supported, // non-indexed columns are allowed. This will be true for MyISAM. if ((table_arg->file->ha_table_flags() & HA_CAN_FULLTEXT_EXT) == 0) return true; return false; } }; class Item_func_bit_xor : public Item_func_bit_operator { public: Item_func_bit_xor(THD *thd, Item *a, Item *b) :Item_func_bit_operator(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("^") }; return name; } enum precedence precedence() const override { return BITXOR_PRECEDENCE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_is_free_lock :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()); } String value; public: Item_func_is_free_lock(THD *thd, Item *a): Item_long_func(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("is_free_lock") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=1; set_maybe_null(); return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_is_used_lock :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_general_purpose_string(func_name_cstring()); } String value; public: Item_func_is_used_lock(THD *thd, Item *a): Item_long_func(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("is_used_lock") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=10; set_maybe_null(); return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; struct Lex_cast_type_st: public Lex_length_and_dec_st { private: const Type_handler *m_type_handler; public: void set(const Type_handler *handler, const char *length, const char *dec) { m_type_handler= handler; Lex_length_and_dec_st::set(length, dec); } void set(const Type_handler *handler, Lex_length_and_dec_st length_and_dec) { m_type_handler= handler; Lex_length_and_dec_st::operator=(length_and_dec); } void set(const Type_handler *handler, const char *length) { set(handler, length, 0); } void set(const Type_handler *handler) { set(handler, 0, 0); } const Type_handler *type_handler() const { return m_type_handler; } Item *create_typecast_item(THD *thd, Item *item, CHARSET_INFO *cs= NULL) const { return m_type_handler-> create_typecast_item(thd, item, Type_cast_attributes(length(), dec(), cs)); } Item *create_typecast_item_or_error(THD *thd, Item *item, CHARSET_INFO *cs= NULL) const; }; class Item_func_row_count :public Item_longlong_func { public: Item_func_row_count(THD *thd): Item_longlong_func(thd) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("row_count") }; return name; } bool fix_length_and_dec() override { decimals= 0; base_flags&= ~item_base_t::MAYBE_NULL; return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* * * Stored FUNCTIONs * */ class Item_func_sp :public Item_func, public Item_sp { private: const Sp_handler *m_handler; bool execute(); protected: bool is_expensive_processor(void *arg) override { return is_expensive(); } bool check_arguments() const override { // sp_prepare_func_item() checks that the number of columns is correct return false; } public: Item_func_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name, const Sp_handler *sph); Item_func_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name, const Sp_handler *sph, List &list); virtual ~Item_func_sp() = default; void update_used_tables() override; void cleanup() override; LEX_CSTRING func_name_cstring() const override; const Type_handler *type_handler() const override; Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override; Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { return result_type() != STRING_RESULT ? sp_result_field : create_table_field_from_handler(root, table); } void make_send_field(THD *thd, Send_field *tmp_field) override; longlong val_int() override { if (execute()) return (longlong) 0; return sp_result_field->val_int(); } double val_real() override { if (execute()) return 0.0; return sp_result_field->val_real(); } my_decimal *val_decimal(my_decimal *dec_buf) override { if (execute()) return NULL; return sp_result_field->val_decimal(dec_buf); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { if (execute()) return true; return sp_result_field->get_date(ltime, fuzzydate); } String *val_str(String *str) override { String buf; char buff[20]; buf.set(buff, 20, str->charset()); buf.length(0); if (execute()) return NULL; /* result_field will set buf pointing to internal buffer of the resul_field. Due to this it will change any time when SP is executed. In order to prevent occasional corruption of returned value, we make here a copy. */ sp_result_field->val_str(&buf); str->copy(buf); return str; } bool val_native(THD *thd, Native *to) override { if (execute()) return true; return (null_value= sp_result_field->val_native(to)); } void update_null_value() override { execute(); } bool change_context_processor(void *cntx) override { context= (Name_resolution_context *)cntx; return FALSE; } enum Functype functype() const override { return FUNC_SP; } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec(void) override; bool is_expensive() override; inline Field *get_sp_result_field() { return sp_result_field; } const sp_name *get_sp_name() const { return m_name; } bool check_vcol_func_processor(void *arg) override; bool limit_index_condition_pushdown_processor(void *opt_arg) override { return TRUE; } Item *do_get_copy(THD *thd) const override { return 0; } bool eval_not_null_tables(void *opt_arg) override { not_null_tables_cache= 0; return 0; } bool excl_dep_on_grouping_fields(st_select_lex *sel) override { return false; } bool find_not_null_fields(table_map allowed) override { return false; } }; class Item_func_found_rows :public Item_longlong_func { public: Item_func_found_rows(THD *thd): Item_longlong_func(thd) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("found_rows") }; return name; } bool fix_length_and_dec() override { decimals= 0; base_flags&= ~item_base_t::MAYBE_NULL; return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_oracle_sql_rowcount :public Item_longlong_func { public: Item_func_oracle_sql_rowcount(THD *thd): Item_longlong_func(thd) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("SQL%ROWCOUNT") }; return name; } void print(String *str, enum_query_type query_type) override { str->append(func_name_cstring()); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sqlcode: public Item_long_func { public: Item_func_sqlcode(THD *thd): Item_long_func(thd) { } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("SQLCODE") }; return name; } void print(String *str, enum_query_type query_type) override { str->append(func_name_cstring()); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } bool fix_length_and_dec() override { base_flags&= ~item_base_t::MAYBE_NULL; null_value= false; max_length= 11; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; void uuid_short_init(); ulonglong server_uuid_value(); class Item_func_uuid_short :public Item_longlong_func { public: Item_func_uuid_short(THD *thd): Item_longlong_func(thd) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("uuid_short") }; return name; } longlong val_int() override; bool const_item() const override { return false; } bool fix_length_and_dec() override { max_length= 21; unsigned_flag=1; return FALSE; } table_map used_tables() const override { return RAND_TABLE_BIT; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_last_value :public Item_func { protected: Item *last_value; public: Item_func_last_value(THD *thd, List &list): Item_func(thd, list) {} double val_real() override; longlong val_int() override; String *val_str(String *) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("last_value") }; return name; } const Type_handler *type_handler() const override { return last_value->type_handler(); } bool eval_not_null_tables(void *) override { not_null_tables_cache= 0; return 0; } bool find_not_null_fields(table_map allowed) override { return false; } bool const_item() const override { return 0; } void evaluate_sideeffects(); void update_used_tables() override { Item_func::update_used_tables(); copy_flags(last_value, item_base_t::MAYBE_NULL); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Implementation for sequences: NEXT VALUE FOR sequence and NEXTVAL() */ class Item_func_nextval :public Item_longlong_func { protected: TABLE_LIST *table_list; TABLE *table; bool check_access(THD *, privilege_t); public: Item_func_nextval(THD *thd, TABLE_LIST *table_list_arg): Item_longlong_func(thd), table_list(table_list_arg) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("nextval") }; return name; } bool fix_fields(THD *thd, Item **ref) override { /* Don't check privileges, if it's parse_vcol_defs() */ return (table_list->table && check_sequence_privileges(thd)) || Item_longlong_func::fix_fields(thd, ref); } bool check_sequence_privileges(void *thd) override { return check_access((THD*)thd, INSERT_ACL | SELECT_ACL); } bool fix_length_and_dec() override { unsigned_flag= 0; max_length= MAX_BIGINT_WIDTH; set_maybe_null(); /* In case of errors */ return FALSE; } /* update_table() function must be called during the value function as in case of DEFAULT the sequence table may not yet be open while fix_fields() are called */ void update_table() { if (!(table= table_list->table)) { /* If nextval was used in DEFAULT then next_local points to the table_list used by to open the sequence table */ table= table_list->next_local->table; } } bool const_item() const override { return 0; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } void print(String *str, enum_query_type query_type) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_NEXTVAL); } }; /* Implementation for sequences: LASTVAL(sequence), PostgreSQL style */ class Item_func_lastval :public Item_func_nextval { public: Item_func_lastval(THD *thd, TABLE_LIST *table_list_arg): Item_func_nextval(thd, table_list_arg) {} bool check_sequence_privileges(void *thd) override { return check_access((THD*)thd, SELECT_ACL); } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("lastval") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Implementation for sequences: SETVAL(sequence), PostgreSQL style */ class Item_func_setval :public Item_func_nextval { longlong nextval; ulonglong round; bool is_used; public: Item_func_setval(THD *thd, TABLE_LIST *table_list_arg, longlong nextval_arg, ulonglong round_arg, bool is_used_arg) : Item_func_nextval(thd, table_list_arg), nextval(nextval_arg), round(round_arg), is_used(is_used_arg) {} bool check_sequence_privileges(void *thd) override { return check_access((THD*)thd, INSERT_ACL); } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("setval") }; return name; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; Item *get_system_var(THD *thd, enum_var_type var_type, const LEX_CSTRING *name, const LEX_CSTRING *component); extern bool check_reserved_words(const LEX_CSTRING *name); double my_double_round(double value, longlong dec, bool dec_unsigned, bool truncate); extern bool volatile mqh_used; bool update_hash(user_var_entry *entry, bool set_null, void *ptr, size_t length, const Type_handler *th, CHARSET_INFO *cs); #endif /* ITEM_FUNC_INCLUDED */ mysql/server/private/event_scheduler.h000064400000006332151027430560014230 0ustar00#ifndef _EVENT_SCHEDULER_H_ #define _EVENT_SCHEDULER_H_ /* Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @addtogroup Event_Scheduler @{ */ /** @file Declarations of the scheduler thread class and related functionality. This file is internal to Event_Scheduler module. Please do not include it directly. All public declarations of Event_Scheduler module are in events.h and event_data_objects.h. */ class Event_queue; class Event_job_data; class Event_db_repository; class Event_queue_element_for_exec; class Events; class THD; void pre_init_event_thread(THD* thd); bool post_init_event_thread(THD* thd); void deinit_event_thread(THD *thd); class Event_worker_thread { public: static void init(Event_db_repository *db_repository_arg) { db_repository= db_repository_arg; } void run(THD *thd, Event_queue_element_for_exec *event); private: void print_warnings(THD *thd, Event_job_data *et); static Event_db_repository *db_repository; }; class Event_scheduler { public: Event_scheduler(Event_queue *event_queue_arg); ~Event_scheduler(); /* State changing methods follow */ bool start(int *err_no); bool stop(); /* Need to be public because has to be called from the function passed to pthread_create. */ bool run(THD *thd); /* Information retrieving methods follow */ bool is_running(); void dump_internal_status(); private: uint workers_count(); /* helper functions */ bool execute_top(Event_queue_element_for_exec *event_name); /* helper functions for working with mutexes & conditionals */ void lock_data(const char *func, uint line); void unlock_data(const char *func, uint line); void cond_wait(THD *thd, struct timespec *abstime, const PSI_stage_info *stage, const char *src_func, const char *src_file, uint src_line); mysql_mutex_t LOCK_scheduler_state; enum enum_state { INITIALIZED = 0, RUNNING, STOPPING }; /* This is the current status of the life-cycle of the scheduler. */ enum enum_state state; THD *scheduler_thd; mysql_cond_t COND_state; Event_queue *queue; uint mutex_last_locked_at_line; uint mutex_last_unlocked_at_line; const char* mutex_last_locked_in_func; const char* mutex_last_unlocked_in_func; bool mutex_scheduler_data_locked; bool waiting_on_cond; ulonglong started_events; private: /* Prevent use of these */ Event_scheduler(const Event_scheduler &); void operator=(Event_scheduler &); }; /** @} (End of group Event_Scheduler) */ #endif /* _EVENT_SCHEDULER_H_ */ mysql/server/private/wsrep_schema.h000064400000011517151027430560013532 0ustar00/* Copyright (C) 2015-2024 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WSREP_SCHEMA_H #define WSREP_SCHEMA_H /* wsrep-lib */ #include "wsrep_types.h" #include "mysqld.h" #include "wsrep_mysqld.h" /* Forward decls */ class THD; class Relay_log_info; struct TABLE; struct TABLE_LIST; struct st_mysql_lex_string; typedef struct st_mysql_lex_string LEX_STRING; class Gtid_log_event; /** Name of the table in `wsrep_schema_str` used for storing streaming replication data. In an InnoDB full format, e.g. "database/tablename". */ extern const char* wsrep_sr_table_name_full; class Wsrep_schema { public: Wsrep_schema(); ~Wsrep_schema(); /* Initialize wsrep schema. Storage engines must be running before calling this function. */ int init(); /* Store wsrep view info into wsrep schema. */ int store_view(THD*, const Wsrep_view& view); /* Restore view info from stable storage. */ Wsrep_view restore_view(THD* thd, const Wsrep_id& own_id) const; /** Append transaction fragment to fragment storage. Transaction must have been started for THD before this call. In order to make changes durable, transaction must be committed separately after this call. @param thd THD object @param server_id Wsrep server identifier @param transaction_id Transaction identifier @param flags Flags for the fragment @param data Fragment data buffer @return Zero in case of success, non-zero on failure. */ int append_fragment(THD* thd, const wsrep::id& server_id, wsrep::transaction_id transaction_id, wsrep::seqno seqno, int flags, const wsrep::const_buffer& data); /** Update existing fragment meta data. The fragment must have been inserted before using append_fragment(). @param thd THD object @param ws_meta Wsrep meta data @return Zero in case of success, non-zero on failure. */ int update_fragment_meta(THD* thd, const wsrep::ws_meta& ws_meta); /** Remove fragments from storage. This method must be called inside active transaction. Fragment removal will be committed once the transaction commits. @param thd Pointer to THD object @param server_id Identifier of the running server @param transaction_id Identifier of the current transaction @param fragments Vector of fragment seqnos to be removed */ int remove_fragments(THD* thd, const wsrep::id& server_id, wsrep::transaction_id transaction_id, const std::vector& fragments); /** Replay a transaction from stored fragments. The caller must have started a transaction for a thd. @param thd Pointer to THD object @param ws_meta Write set meta data for commit fragment. @param fragments Vector of fragments to be replayed @return Zero on success, non-zero on failure. */ int replay_transaction(THD* thd, Relay_log_info* rli, const wsrep::ws_meta& ws_meta, const std::vector& fragments); /** Recover streaming transactions from SR table. This method should be called after storage enignes are initialized. It will scan SR table and replay found streaming transactions. @param orig_thd The THD object of the calling thread. @return Zero on success, non-zero on failure. */ int recover_sr_transactions(THD* orig_thd); /** Store GTID-event to mysql.gtid_slave_pos table. @param thd The THD object of the calling thread. @param gtid GTID event from binlog. @return Zero on success, non-zero on failure. */ int store_gtid_event(THD* thd, const Gtid_log_event *gtid); private: /* Non-copyable */ Wsrep_schema(const Wsrep_schema&); Wsrep_schema& operator=(const Wsrep_schema&); }; extern Wsrep_schema* wsrep_schema; extern LEX_CSTRING WSREP_LEX_SCHEMA; extern LEX_CSTRING WSREP_LEX_STREAMING; extern LEX_CSTRING WSREP_LEX_CLUSTER; extern LEX_CSTRING WSREP_LEX_MEMBERS; #endif /* !WSREP_SCHEMA_H */ mysql/server/private/wsrep_applier.h000064400000005217151027430560013726 0ustar00/* Copyright 2013-2019 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef WSREP_APPLIER_H #define WSREP_APPLIER_H #include "sql_class.h" // THD class #include "rpl_rli.h" // Relay_log_info #include "log_event.h" // Format_description_log_event int wsrep_apply_events(THD* thd, Relay_log_info* rli, const void* events_buf, size_t buf_len); /* Applier error codes, when nothing better is available. */ #define WSREP_RET_SUCCESS 0 // Success #define WSREP_ERR_GENERIC 1 // When in doubt (MySQL default error code) #define WSREP_ERR_BAD_EVENT 2 // Can't parse event #define WSREP_ERR_NOT_FOUND 3 // Key. table, schema not found #define WSREP_ERR_EXISTS 4 // Key, table, schema already exists #define WSREP_ERR_WRONG_TYPE 5 // Incompatible data type #define WSREP_ERR_FAILED 6 // Operation failed for some internal reason #define WSREP_ERR_ABORTED 7 // Operation was aborted externally /* Loops over THD diagnostic area and concatenates all error messages * and error codes to a single continuous buffer to create a unique * but consistent failure signature which provider can use for voting * between the nodes in the cluster. * * @param thd THD context * @param dst buffer to store the signature * @param include_msg whether to use MySQL error message in addition to * MySQL error code. Note that in the case of a TOI * operation the message may be not consistent between * the nodes e.g. due to a different client locale setting * and should be omitted */ void wsrep_store_error(const THD* thd, wsrep::mutable_buffer& buf, bool include_msg); class Format_description_log_event; void wsrep_set_apply_format(THD*, Format_description_log_event*); Format_description_log_event* wsrep_get_apply_format(THD* thd); #endif /* WSREP_APPLIER_H */ mysql/server/private/my_nosys.h000064400000002636151027430560012734 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Header to remove use of my_functions in functions where we need speed and where calls to posix functions should work */ #ifndef _my_nosys_h #define _my_nosys_h #ifdef __cplusplus extern "C" { #endif #ifndef __MY_NOSYS__ #define __MY_NOSYS__ #ifndef HAVE_STDLIB_H #include #endif #undef my_read #undef my_write #undef my_seek #define my_read(a,b,c,d) my_quick_read(a,b,c,d) #define my_write(a,b,c,d) my_quick_write(a,b,c) extern size_t my_quick_read(File Filedes,uchar *Buffer,size_t Count, myf myFlags); extern size_t my_quick_write(File Filedes,const uchar *Buffer,size_t Count); #endif /* __MY_NOSYS__ */ #ifdef __cplusplus } #endif #endif mysql/server/private/log_event.h000064400000554052151027430560013042 0ustar00/* Copyright (c) 2000, 2014, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @addtogroup Replication @{ @file @brief Binary log event definitions. This includes generic code common to all types of log events, as well as specific code for each type of log event. */ #ifndef _log_event_h #define _log_event_h #if defined(USE_PRAGMA_INTERFACE) && defined(MYSQL_SERVER) #pragma interface /* gcc class implementation */ #endif #include #include "rpl_constants.h" #include #include #include #include #include #ifdef MYSQL_CLIENT #include "sql_const.h" #include "rpl_utility.h" #include "hash.h" #include "rpl_tblmap.h" #include "sql_string.h" #endif #ifdef MYSQL_SERVER #include "rpl_record.h" #include "rpl_reporting.h" #include "sql_class.h" /* THD */ #endif #include "rpl_gtid.h" #include "log_event_data_type.h" /* Forward declarations */ #ifndef MYSQL_CLIENT class String; #endif #define PREFIX_SQL_LOAD "SQL_LOAD-" #define LONG_FIND_ROW_THRESHOLD 60 /* seconds */ /** Either assert or return an error. In debug build, the condition will be checked, but in non-debug builds, the error code given will be returned instead. @param COND Condition to check @param ERRNO Error number to return in non-debug builds */ #ifdef DBUG_OFF #define ASSERT_OR_RETURN_ERROR(COND, ERRNO) \ do { if (!(COND)) return ERRNO; } while (0) #else #define ASSERT_OR_RETURN_ERROR(COND, ERRNO) \ DBUG_ASSERT(COND) #endif #define LOG_READ_EOF -1 #define LOG_READ_BOGUS -2 #define LOG_READ_IO -3 #define LOG_READ_MEM -5 #define LOG_READ_TRUNC -6 #define LOG_READ_TOO_LARGE -7 #define LOG_READ_CHECKSUM_FAILURE -8 #define LOG_READ_DECRYPT -9 #define LOG_EVENT_OFFSET 4 /* 3 is MySQL 4.x; 4 is MySQL 5.0.0. Compared to version 3, version 4 has: - a different Start_log_event, which includes info about the binary log (sizes of headers); this info is included for better compatibility if the master's MySQL version is different from the slave's. - all events have a unique ID (the triplet (server_id, timestamp at server start, other) to be sure an event is not executed more than once in a multimaster setup, example: M1 / \ v v M2 M3 \ / v v S if a query is run on M1, it will arrive twice on S, so we need that S remembers the last unique ID it has processed, to compare and know if the event should be skipped or not. Example of ID: we already have the server id (4 bytes), plus: timestamp_when_the_master_started (4 bytes), a counter (a sequence number which increments every time we write an event to the binlog) (3 bytes). Q: how do we handle when the counter is overflowed and restarts from 0 ? - Query and Load (Create or Execute) events may have a more precise timestamp (with microseconds), number of matched/affected/warnings rows and fields of session variables: SQL_MODE, FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, SQL_AUTO_IS_NULL, the collations and charsets, the PASSWORD() version (old/new/...). */ #define BINLOG_VERSION 4 /* We could have used SERVER_VERSION_LENGTH, but this introduces an obscure dependency - if somebody decided to change SERVER_VERSION_LENGTH this would break the replication protocol */ #define ST_SERVER_VER_LEN 50 /* These are flags and structs to handle all the LOAD DATA INFILE options (LINES TERMINATED etc). */ /* These are flags and structs to handle all the LOAD DATA INFILE options (LINES TERMINATED etc). DUMPFILE_FLAG is probably useless (DUMPFILE is a clause of SELECT, not of LOAD DATA). */ #define DUMPFILE_FLAG 0x1 #define OPT_ENCLOSED_FLAG 0x2 #define REPLACE_FLAG 0x4 #define IGNORE_FLAG 0x8 #define FIELD_TERM_EMPTY 0x1 #define ENCLOSED_EMPTY 0x2 #define LINE_TERM_EMPTY 0x4 #define LINE_START_EMPTY 0x8 #define ESCAPED_EMPTY 0x10 #define NUM_LOAD_DELIM_STRS 5 /* The following is the max table_map_id. This is limited by that we are using 6 bytes for it in replication */ #define MAX_TABLE_MAP_ID ((1ULL << (6*8)) -1) /***************************************************************************** MySQL Binary Log This log consists of events. Each event has a fixed-length header, possibly followed by a variable length data body. The data body consists of an optional fixed length segment (post-header) and an optional variable length segment. See the #defines below for the format specifics. The events which really update data are Query_log_event, Execute_load_query_log_event and old Load_log_event and Execute_load_log_event events (Execute_load_query is used together with Begin_load_query and Append_block events to replicate LOAD DATA INFILE. Create_file/Append_block/Execute_load (which includes Load_log_event) were used to replicate LOAD DATA before the 5.0.3). ****************************************************************************/ #define LOG_EVENT_HEADER_LEN 19 /* the fixed header length */ #define OLD_HEADER_LEN 13 /* the fixed header length in 3.23 */ /* Fixed header length, where 4.x and 5.0 agree. That is, 5.0 may have a longer header (it will for sure when we have the unique event's ID), but at least the first 19 bytes are the same in 4.x and 5.0. So when we have the unique event's ID, LOG_EVENT_HEADER_LEN will be something like 26, but LOG_EVENT_MINIMAL_HEADER_LEN will remain 19. */ #define LOG_EVENT_MINIMAL_HEADER_LEN 19 /* event-specific post-header sizes */ // where 3.23, 4.x and 5.0 agree #define QUERY_HEADER_MINIMAL_LEN (4 + 4 + 1 + 2) // where 5.0 differs: 2 for len of N-bytes vars. #define QUERY_HEADER_LEN (QUERY_HEADER_MINIMAL_LEN + 2) #define STOP_HEADER_LEN 0 #define LOAD_HEADER_LEN (4 + 4 + 4 + 1 +1 + 4) #define SLAVE_HEADER_LEN 0 #define START_V3_HEADER_LEN (2 + ST_SERVER_VER_LEN + 4) #define ROTATE_HEADER_LEN 8 // this is FROZEN (the Rotate post-header is frozen) #define INTVAR_HEADER_LEN 0 #define CREATE_FILE_HEADER_LEN 4 #define APPEND_BLOCK_HEADER_LEN 4 #define EXEC_LOAD_HEADER_LEN 4 #define DELETE_FILE_HEADER_LEN 4 #define NEW_LOAD_HEADER_LEN LOAD_HEADER_LEN #define RAND_HEADER_LEN 0 #define USER_VAR_HEADER_LEN 0 #define FORMAT_DESCRIPTION_HEADER_LEN (START_V3_HEADER_LEN+1+LOG_EVENT_TYPES) #define XID_HEADER_LEN 0 #define BEGIN_LOAD_QUERY_HEADER_LEN APPEND_BLOCK_HEADER_LEN #define ROWS_HEADER_LEN_V1 8 #define TABLE_MAP_HEADER_LEN 8 #define EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN (4 + 4 + 4 + 1) #define EXECUTE_LOAD_QUERY_HEADER_LEN (QUERY_HEADER_LEN + EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN) #define INCIDENT_HEADER_LEN 2 #define HEARTBEAT_HEADER_LEN 0 #define IGNORABLE_HEADER_LEN 0 #define ROWS_HEADER_LEN_V2 10 #define ANNOTATE_ROWS_HEADER_LEN 0 #define BINLOG_CHECKPOINT_HEADER_LEN 4 #define GTID_HEADER_LEN 19 #define GTID_LIST_HEADER_LEN 4 #define START_ENCRYPTION_HEADER_LEN 0 #define XA_PREPARE_HEADER_LEN 0 /* Max number of possible extra bytes in a replication event compared to a packet (i.e. a query) sent from client to master; First, an auxiliary log_event status vars estimation: */ #define MAX_SIZE_LOG_EVENT_STATUS (1 + 4 /* type, flags2 */ + \ 1 + 8 /* type, sql_mode */ + \ 1 + 1 + 255 /* type, length, catalog */ + \ 1 + 4 /* type, auto_increment */ + \ 1 + 6 /* type, charset */ + \ 1 + 1 + 255 /* type, length, time_zone */ + \ 1 + 2 /* type, lc_time_names_number */ + \ 1 + 2 /* type, charset_database_number */ + \ 1 + 8 /* type, table_map_for_update */ + \ 1 + 4 /* type, master_data_written */ + \ 1 + 3 /* type, sec_part of NOW() */ + \ 1 + 16 + 1 + 60/* type, user_len, user, host_len, host */) #define MAX_LOG_EVENT_HEADER ( /* in order of Query_log_event::write */ \ LOG_EVENT_HEADER_LEN + /* write_header */ \ QUERY_HEADER_LEN + /* write_data */ \ EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN + /*write_post_header_for_derived */ \ MAX_SIZE_LOG_EVENT_STATUS + /* status */ \ NAME_LEN + 1) /* The new option is added to handle large packets that are sent from the master to the slave. It is used to increase the thd(max_allowed) for both the DUMP thread on the master and the SQL/IO thread on the slave. */ #define MAX_MAX_ALLOWED_PACKET (1024*1024*1024) /* Event header offsets; these point to places inside the fixed header. */ #define EVENT_TYPE_OFFSET 4 #define SERVER_ID_OFFSET 5 #define EVENT_LEN_OFFSET 9 #define LOG_POS_OFFSET 13 #define FLAGS_OFFSET 17 /* start event post-header (for v3 and v4) */ #define ST_BINLOG_VER_OFFSET 0 #define ST_SERVER_VER_OFFSET 2 #define ST_CREATED_OFFSET (ST_SERVER_VER_OFFSET + ST_SERVER_VER_LEN) #define ST_COMMON_HEADER_LEN_OFFSET (ST_CREATED_OFFSET + 4) /* slave event post-header (this event is never written) */ #define SL_MASTER_PORT_OFFSET 8 #define SL_MASTER_POS_OFFSET 0 #define SL_MASTER_HOST_OFFSET 10 /* query event post-header */ #define Q_THREAD_ID_OFFSET 0 #define Q_EXEC_TIME_OFFSET 4 #define Q_DB_LEN_OFFSET 8 #define Q_ERR_CODE_OFFSET 9 #define Q_STATUS_VARS_LEN_OFFSET 11 #define Q_DATA_OFFSET QUERY_HEADER_LEN /* these are codes, not offsets; not more than 256 values (1 byte). */ #define Q_FLAGS2_CODE 0 #define Q_SQL_MODE_CODE 1 /* Q_CATALOG_CODE is catalog with end zero stored; it is used only by MySQL 5.0.x where 0<=x<=3. We have to keep it to be able to replicate these old masters. */ #define Q_CATALOG_CODE 2 #define Q_AUTO_INCREMENT 3 #define Q_CHARSET_CODE 4 #define Q_TIME_ZONE_CODE 5 /* Q_CATALOG_NZ_CODE is catalog withOUT end zero stored; it is used by MySQL 5.0.x where x>=4. Saves one byte in every Query_log_event in binlog, compared to Q_CATALOG_CODE. The reason we didn't simply re-use Q_CATALOG_CODE is that then a 5.0.3 slave of this 5.0.x (x>=4) master would crash (segfault etc) because it would expect a 0 when there is none. */ #define Q_CATALOG_NZ_CODE 6 #define Q_LC_TIME_NAMES_CODE 7 #define Q_CHARSET_DATABASE_CODE 8 #define Q_TABLE_MAP_FOR_UPDATE_CODE 9 #define Q_MASTER_DATA_WRITTEN_CODE 10 #define Q_INVOKER 11 #define Q_HRNOW 128 #define Q_XID 129 /* Intvar event post-header */ /* Intvar event data */ #define I_TYPE_OFFSET 0 #define I_VAL_OFFSET 1 /* Rand event data */ #define RAND_SEED1_OFFSET 0 #define RAND_SEED2_OFFSET 8 /* User_var event data */ #define UV_VAL_LEN_SIZE 4 #define UV_VAL_IS_NULL 1 #define UV_VAL_TYPE_SIZE 1 #define UV_NAME_LEN_SIZE 4 #define UV_CHARSET_NUMBER_SIZE 4 /* Load event post-header */ #define L_THREAD_ID_OFFSET 0 #define L_EXEC_TIME_OFFSET 4 #define L_SKIP_LINES_OFFSET 8 #define L_TBL_LEN_OFFSET 12 #define L_DB_LEN_OFFSET 13 #define L_NUM_FIELDS_OFFSET 14 #define L_SQL_EX_OFFSET 18 #define L_DATA_OFFSET LOAD_HEADER_LEN /* Rotate event post-header */ #define R_POS_OFFSET 0 #define R_IDENT_OFFSET 8 /* CF to DF handle LOAD DATA INFILE */ /* CF = "Create File" */ #define CF_FILE_ID_OFFSET 0 #define CF_DATA_OFFSET CREATE_FILE_HEADER_LEN /* AB = "Append Block" */ #define AB_FILE_ID_OFFSET 0 #define AB_DATA_OFFSET APPEND_BLOCK_HEADER_LEN /* EL = "Execute Load" */ #define EL_FILE_ID_OFFSET 0 /* DF = "Delete File" */ #define DF_FILE_ID_OFFSET 0 /* TM = "Table Map" */ #define TM_MAPID_OFFSET 0 #define TM_FLAGS_OFFSET 6 /* RW = "RoWs" */ #define RW_MAPID_OFFSET 0 #define RW_FLAGS_OFFSET 6 #define RW_VHLEN_OFFSET 8 #define RW_V_TAG_LEN 1 #define RW_V_EXTRAINFO_TAG 0 /* ELQ = "Execute Load Query" */ #define ELQ_FILE_ID_OFFSET QUERY_HEADER_LEN #define ELQ_FN_POS_START_OFFSET ELQ_FILE_ID_OFFSET + 4 #define ELQ_FN_POS_END_OFFSET ELQ_FILE_ID_OFFSET + 8 #define ELQ_DUP_HANDLING_OFFSET ELQ_FILE_ID_OFFSET + 12 /* 4 bytes which all binlogs should begin with */ #define BINLOG_MAGIC (const uchar*) "\xfe\x62\x69\x6e" /* The 2 flags below were useless : - the first one was never set - the second one was set in all Rotate events on the master, but not used for anything useful. So they are now removed and their place may later be reused for other flags. Then one must remember that Rotate events in 4.x have LOG_EVENT_FORCED_ROTATE_F set, so one should not rely on the value of the replacing flag when reading a Rotate event. I keep the defines here just to remember what they were. */ #ifdef TO_BE_REMOVED #define LOG_EVENT_TIME_F 0x1 #define LOG_EVENT_FORCED_ROTATE_F 0x2 #endif /* This flag only makes sense for Format_description_log_event. It is set when the event is written, and *reset* when a binlog file is closed (yes, it's the only case when MySQL modifies already written part of binlog). Thus it is a reliable indicator that binlog was closed correctly. (Stop_log_event is not enough, there's always a small chance that mysqld crashes in the middle of insert and end of the binlog would look like a Stop_log_event). This flag is used to detect a restart after a crash, and to provide "unbreakable" binlog. The problem is that on a crash storage engines rollback automatically, while binlog does not. To solve this we use this flag and automatically append ROLLBACK to every non-closed binlog (append virtually, on reading, file itself is not changed). If this flag is found, mysqlbinlog simply prints "ROLLBACK" Replication master does not abort on binlog corruption, but takes it as EOF, and replication slave forces a rollback in this case. Note, that old binlogs does not have this flag set, so we get a a backward-compatible behaviour. */ #define LOG_EVENT_BINLOG_IN_USE_F 0x1 /** @def LOG_EVENT_THREAD_SPECIFIC_F If the query depends on the thread (for example: TEMPORARY TABLE). Currently this is used by mysqlbinlog to know it must print SET @@PSEUDO_THREAD_ID=xx; before the query (it would not hurt to print it for every query but this would be slow). */ #define LOG_EVENT_THREAD_SPECIFIC_F 0x4 /** @def LOG_EVENT_SUPPRESS_USE_F Suppress the generation of 'USE' statements before the actual statement. This flag should be set for any events that does not need the current database set to function correctly. Most notable cases are 'CREATE DATABASE' and 'DROP DATABASE'. This flags should only be used in exceptional circumstances, since it introduce a significant change in behaviour regarding the replication logic together with the flags --binlog-do-db and --replicated-do-db. */ #define LOG_EVENT_SUPPRESS_USE_F 0x8 /* Note: this is a place holder for the flag LOG_EVENT_UPDATE_TABLE_MAP_VERSION_F (0x10), which is not used any more, please do not reused this value for other flags. */ /** @def LOG_EVENT_ARTIFICIAL_F Artificial events are created arbitrarily and not written to binary log These events should not update the master log position when slave SQL thread executes them. */ #define LOG_EVENT_ARTIFICIAL_F 0x20 /** @def LOG_EVENT_RELAY_LOG_F Events with this flag set are created by slave IO thread and written to relay log */ #define LOG_EVENT_RELAY_LOG_F 0x40 /** @def LOG_EVENT_IGNORABLE_F For an event, 'e', carrying a type code, that a slave, 's', does not recognize, 's' will check 'e' for LOG_EVENT_IGNORABLE_F, and if the flag is set, then 'e' is ignored. Otherwise, 's' acknowledges that it has found an unknown event in the relay log. */ #define LOG_EVENT_IGNORABLE_F 0x80 /** @def LOG_EVENT_ACCEPT_OWN_F Flag sets by the semisync slave for accepting the same server_id ("own") events which the slave must not have in its state. Typically such events were never committed by their originator (this server) and discared at its semisync-slave recovery. */ #define LOG_EVENT_ACCEPT_OWN_F 0x4000 /** @def LOG_EVENT_SKIP_REPLICATION_F Flag set by application creating the event (with @@skip_replication); the slave will skip replication of such events if --replicate-events-marked-for-skip is not set to REPLICATE. This is a MariaDB flag; we allocate it from the end of the available values to reduce risk of conflict with new MySQL flags. */ #define LOG_EVENT_SKIP_REPLICATION_F 0x8000 /** @def OPTIONS_WRITTEN_TO_BIN_LOG OPTIONS_WRITTEN_TO_BIN_LOG are the bits of thd->options which must be written to the binlog. OPTIONS_WRITTEN_TO_BIN_LOG could be written into the Format_description_log_event, so that if later we don't want to replicate a variable we did replicate, or the contrary, it's doable. But it should not be too hard to deduct the value of OPTIONS_WRITTEN_TO_BIN_LOG from the master's version. This is done in deduct_options_written_to_bin_log(). You *must* update it, when changing the definition below. */ #define OPTIONS_WRITTEN_TO_BIN_LOG (OPTION_EXPLICIT_DEF_TIMESTAMP |\ OPTION_AUTO_IS_NULL | OPTION_NO_FOREIGN_KEY_CHECKS | \ OPTION_RELAXED_UNIQUE_CHECKS | OPTION_NOT_AUTOCOMMIT | OPTION_IF_EXISTS) #define CHECKSUM_CRC32_SIGNATURE_LEN 4 /** defined statically while there is just one alg implemented */ #define BINLOG_CHECKSUM_LEN CHECKSUM_CRC32_SIGNATURE_LEN #define BINLOG_CHECKSUM_ALG_DESC_LEN 1 /* 1 byte checksum alg descriptor */ /* These are capability numbers for MariaDB slave servers. Newer MariaDB slaves set this to inform the master about their capabilities. This allows the master to decide which events it can send to the slave without breaking replication on old slaves that maybe do not understand all events from newer masters. As new releases are backwards compatible, a given capability implies also all capabilities with smaller number. Older MariaDB slaves and other MySQL slave servers do not set this, so they are recorded with capability 0. */ /* MySQL or old MariaDB slave with no announced capability. */ #define MARIA_SLAVE_CAPABILITY_UNKNOWN 0 /* MariaDB >= 5.3, which understands ANNOTATE_ROWS_EVENT. */ #define MARIA_SLAVE_CAPABILITY_ANNOTATE 1 /* MariaDB >= 5.5. This version has the capability to tolerate events omitted from the binlog stream without breaking replication (MySQL slaves fail because they mis-compute the offsets into the master's binlog). */ #define MARIA_SLAVE_CAPABILITY_TOLERATE_HOLES 2 /* MariaDB >= 10.0, which knows about binlog_checkpoint_log_event. */ #define MARIA_SLAVE_CAPABILITY_BINLOG_CHECKPOINT 3 /* MariaDB >= 10.0.1, which knows about global transaction id events. */ #define MARIA_SLAVE_CAPABILITY_GTID 4 /* Our capability. */ #define MARIA_SLAVE_CAPABILITY_MINE MARIA_SLAVE_CAPABILITY_GTID /* When the size of 'log_pos' within Heartbeat_log_event exceeds UINT32_MAX it cannot be accommodated in common_header, as 'log_pos' is of 4 bytes size. In such cases, sub_header, of size 8 bytes will hold larger 'log_pos' value. */ #define HB_SUB_HEADER_LEN 8 /** @enum Log_event_type Enumeration type for the different types of log events. */ enum Log_event_type { /* Every time you update this enum (when you add a type), you have to fix Format_description_log_event::Format_description_log_event(). */ UNKNOWN_EVENT= 0, START_EVENT_V3= 1, QUERY_EVENT= 2, STOP_EVENT= 3, ROTATE_EVENT= 4, INTVAR_EVENT= 5, LOAD_EVENT= 6, SLAVE_EVENT= 7, CREATE_FILE_EVENT= 8, APPEND_BLOCK_EVENT= 9, EXEC_LOAD_EVENT= 10, DELETE_FILE_EVENT= 11, /* NEW_LOAD_EVENT is like LOAD_EVENT except that it has a longer sql_ex, allowing multibyte TERMINATED BY etc; both types share the same class (Load_log_event) */ NEW_LOAD_EVENT= 12, RAND_EVENT= 13, USER_VAR_EVENT= 14, FORMAT_DESCRIPTION_EVENT= 15, XID_EVENT= 16, BEGIN_LOAD_QUERY_EVENT= 17, EXECUTE_LOAD_QUERY_EVENT= 18, TABLE_MAP_EVENT = 19, /* These event numbers were used for 5.1.0 to 5.1.15 and are therefore obsolete. */ PRE_GA_WRITE_ROWS_EVENT = 20, PRE_GA_UPDATE_ROWS_EVENT = 21, PRE_GA_DELETE_ROWS_EVENT = 22, /* These event numbers are used from 5.1.16 until mysql-5.6.6, and in MariaDB */ WRITE_ROWS_EVENT_V1 = 23, UPDATE_ROWS_EVENT_V1 = 24, DELETE_ROWS_EVENT_V1 = 25, /* Something out of the ordinary happened on the master */ INCIDENT_EVENT= 26, /* Heartbeat event to be send by master at its idle time to ensure master's online status to slave */ HEARTBEAT_LOG_EVENT= 27, /* In some situations, it is necessary to send over ignorable data to the slave: data that a slave can handle in case there is code for handling it, but which can be ignored if it is not recognized. These mysql-5.6 events are not recognized (and ignored) by MariaDB */ IGNORABLE_LOG_EVENT= 28, ROWS_QUERY_LOG_EVENT= 29, /* Version 2 of the Row events, generated only by mysql-5.6.6+ */ WRITE_ROWS_EVENT = 30, UPDATE_ROWS_EVENT = 31, DELETE_ROWS_EVENT = 32, /* MySQL 5.6 GTID events, ignored by MariaDB */ GTID_LOG_EVENT= 33, ANONYMOUS_GTID_LOG_EVENT= 34, PREVIOUS_GTIDS_LOG_EVENT= 35, /* MySQL 5.7 events, ignored by MariaDB */ TRANSACTION_CONTEXT_EVENT= 36, VIEW_CHANGE_EVENT= 37, /* not ignored */ XA_PREPARE_LOG_EVENT= 38, /** Extension of UPDATE_ROWS_EVENT, allowing partial values according to binlog_row_value_options. */ PARTIAL_UPDATE_ROWS_EVENT = 39, TRANSACTION_PAYLOAD_EVENT = 40, HEARTBEAT_LOG_EVENT_V2 = 41, /* Add new events here - right above this comment! Existing events (except ENUM_END_EVENT) should never change their numbers */ /* New MySQL/Sun events are to be added right above this comment */ MYSQL_EVENTS_END, MARIA_EVENTS_BEGIN= 160, /* New Maria event numbers start from here */ ANNOTATE_ROWS_EVENT= 160, /* Binlog checkpoint event. Used for XA crash recovery on the master, not used in replication. A binlog checkpoint event specifies a binlog file such that XA crash recovery can start from that file - and it is guaranteed to find all XIDs that are prepared in storage engines but not yet committed. */ BINLOG_CHECKPOINT_EVENT= 161, /* Gtid event. For global transaction ID, used to start a new event group, instead of the old BEGIN query event, and also to mark stand-alone events. */ GTID_EVENT= 162, /* Gtid list event. Logged at the start of every binlog, to record the current replication state. This consists of the last GTID seen for each replication domain. */ GTID_LIST_EVENT= 163, START_ENCRYPTION_EVENT= 164, /* Compressed binlog event. Note that the order between WRITE/UPDATE/DELETE events is significant; this is so that we can convert from the compressed to the uncompressed event type with (type-WRITE_ROWS_COMPRESSED_EVENT + WRITE_ROWS_EVENT) and similar for _V1. */ QUERY_COMPRESSED_EVENT = 165, WRITE_ROWS_COMPRESSED_EVENT_V1 = 166, UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167, DELETE_ROWS_COMPRESSED_EVENT_V1 = 168, WRITE_ROWS_COMPRESSED_EVENT = 169, UPDATE_ROWS_COMPRESSED_EVENT = 170, DELETE_ROWS_COMPRESSED_EVENT = 171, /* Add new MariaDB events here - right above this comment! */ ENUM_END_EVENT /* end marker */ }; /* Bit flags for what has been writing to cache. Used to discard logs with table map events but not row events and nothing else important. This is stored by cache. */ enum enum_logged_status { LOGGED_TABLE_MAP= 1, LOGGED_ROW_EVENT= 2, LOGGED_NO_DATA= 4, LOGGED_CRITICAL= 8 }; static inline bool LOG_EVENT_IS_QUERY(enum Log_event_type type) { return type == QUERY_EVENT || type == QUERY_COMPRESSED_EVENT; } static inline bool LOG_EVENT_IS_WRITE_ROW(enum Log_event_type type) { return type == WRITE_ROWS_EVENT || type == WRITE_ROWS_EVENT_V1 || type == WRITE_ROWS_COMPRESSED_EVENT || type == WRITE_ROWS_COMPRESSED_EVENT_V1; } static inline bool LOG_EVENT_IS_UPDATE_ROW(enum Log_event_type type) { return type == UPDATE_ROWS_EVENT || type == UPDATE_ROWS_EVENT_V1 || type == UPDATE_ROWS_COMPRESSED_EVENT || type == UPDATE_ROWS_COMPRESSED_EVENT_V1; } static inline bool LOG_EVENT_IS_DELETE_ROW(enum Log_event_type type) { return type == DELETE_ROWS_EVENT || type == DELETE_ROWS_EVENT_V1 || type == DELETE_ROWS_COMPRESSED_EVENT || type == DELETE_ROWS_COMPRESSED_EVENT_V1; } static inline bool LOG_EVENT_IS_ROW_COMPRESSED(enum Log_event_type type) { return type == WRITE_ROWS_COMPRESSED_EVENT || type == WRITE_ROWS_COMPRESSED_EVENT_V1 || type == UPDATE_ROWS_COMPRESSED_EVENT || type == UPDATE_ROWS_COMPRESSED_EVENT_V1 || type == DELETE_ROWS_COMPRESSED_EVENT || type == DELETE_ROWS_COMPRESSED_EVENT_V1; } static inline bool LOG_EVENT_IS_ROW_V2(enum Log_event_type type) { return (type >= WRITE_ROWS_EVENT && type <= DELETE_ROWS_EVENT) || (type >= WRITE_ROWS_COMPRESSED_EVENT && type <= DELETE_ROWS_COMPRESSED_EVENT); } /* The number of types we handle in Format_description_log_event (UNKNOWN_EVENT is not to be handled, it does not exist in binlogs, it does not have a format). */ #define LOG_EVENT_TYPES (ENUM_END_EVENT-1) enum Int_event_type { INVALID_INT_EVENT = 0, LAST_INSERT_ID_EVENT = 1, INSERT_ID_EVENT = 2 }; #ifdef MYSQL_SERVER class String; class MYSQL_BIN_LOG; class THD; #endif class Format_description_log_event; class Relay_log_info; class binlog_cache_data; bool copy_event_cache_to_file_and_reinit(IO_CACHE *cache, FILE *file); #ifdef MYSQL_CLIENT enum enum_base64_output_mode { BASE64_OUTPUT_NEVER= 0, BASE64_OUTPUT_AUTO= 1, BASE64_OUTPUT_UNSPEC= 2, BASE64_OUTPUT_DECODE_ROWS= 3, /* insert new output modes here */ BASE64_OUTPUT_MODE_COUNT }; bool copy_event_cache_to_string_and_reinit(IO_CACHE *cache, LEX_STRING *to); /* A structure for mysqlbinlog to know how to print events This structure is passed to the event's print() methods, There are two types of settings stored here: 1. Last db, flags2, sql_mode etc comes from the last printed event. They are stored so that only the necessary USE and SET commands are printed. 2. Other information on how to print the events, e.g. short_form, hexdump_from. These are not dependent on the last event. */ typedef struct st_print_event_info { /* Settings for database, sql_mode etc that comes from the last event that was printed. We cache these so that we don't have to print them if they are unchanged. */ char db[FN_REFLEN+1]; // TODO: make this a LEX_STRING when thd->db is char charset[6]; // 3 variables, each of them storable in 2 bytes char time_zone_str[MAX_TIME_ZONE_NAME_LENGTH]; char delimiter[16]; sql_mode_t sql_mode; /* must be same as THD.variables.sql_mode */ my_thread_id thread_id; ulonglong row_events; ulong auto_increment_increment, auto_increment_offset; uint lc_time_names_number; uint charset_database_number; uint verbose; uchar gtid_ev_flags2; uint32 flags2; uint32 server_id; uint32 domain_id; uint8 common_header_len; enum_base64_output_mode base64_output_mode; my_off_t hexdump_from; table_mapping m_table_map; table_mapping m_table_map_ignored; bool flags2_inited; bool sql_mode_inited; bool charset_inited; bool thread_id_printed; bool server_id_printed; bool domain_id_printed; bool allow_parallel; bool allow_parallel_printed; bool found_row_event; bool print_row_count; static const uint max_delimiter_size= 16; /* Settings on how to print the events */ bool short_form; /* This is set whenever a Format_description_event is printed. Later, when an event is printed in base64, this flag is tested: if no Format_description_event has been seen, it is unsafe to print the base64 event, so an error message is generated. */ bool printed_fd_event; /* Track when @@skip_replication changes so we need to output a SET statement for it. */ bool skip_replication; bool print_table_metadata; /* These two caches are used by the row-based replication events to collect the header information and the main body of the events making up a statement. */ IO_CACHE head_cache; IO_CACHE body_cache; IO_CACHE tail_cache; #ifdef WHEN_FLASHBACK_REVIEW_READY /* Storing the SQL for reviewing */ IO_CACHE review_sql_cache; #endif FILE *file; st_print_event_info(); ~st_print_event_info() { close_cached_file(&head_cache); close_cached_file(&body_cache); close_cached_file(&tail_cache); #ifdef WHEN_FLASHBACK_REVIEW_READY close_cached_file(&review_sql_cache); #endif } bool init_ok() /* tells if construction was successful */ { return my_b_inited(&head_cache) && my_b_inited(&body_cache) #ifdef WHEN_FLASHBACK_REVIEW_READY && my_b_inited(&review_sql_cache) #endif ; } void flush_for_error() { if (!copy_event_cache_to_file_and_reinit(&head_cache, file)) copy_event_cache_to_file_and_reinit(&body_cache, file); fflush(file); } my_bool is_xa_trans(); } PRINT_EVENT_INFO; #endif // MYSQL_CLIENT /** This class encapsulates writing of Log_event objects to IO_CACHE. Automatically calculates the checksum and encrypts the data, if necessary. */ class Log_event_writer { /* Log_event_writer is updated when ctx is set */ int (Log_event_writer::*encrypt_or_write)(const uchar *pos, size_t len); public: ulonglong bytes_written; void *ctx; ///< Encryption context or 0 if no encryption is needed uint checksum_len; int write(Log_event *ev); int write_header(uchar *pos, size_t len); int write_data(const uchar *pos, size_t len); int write_footer(); my_off_t pos() { return my_b_safe_tell(file); } void add_status(enum_logged_status status); void set_incident(); void set_encrypted_writer() { encrypt_or_write= &Log_event_writer::encrypt_and_write; } Log_event_writer(IO_CACHE *file_arg, binlog_cache_data *cache_data_arg, Binlog_crypt_data *cr= 0) :encrypt_or_write(&Log_event_writer::write_internal), bytes_written(0), ctx(0), file(file_arg), cache_data(cache_data_arg), crypto(cr) { } private: IO_CACHE *file; binlog_cache_data *cache_data; /** Placeholder for event checksum while writing to binlog. */ ha_checksum crc; /** Encryption data (key, nonce). Only used if ctx != 0. */ Binlog_crypt_data *crypto; /** Event length to be written into the next encrypted block */ uint event_len; int write_internal(const uchar *pos, size_t len); int encrypt_and_write(const uchar *pos, size_t len); int maybe_write_event_len(uchar *pos, size_t len); }; /** the struct aggregates two parameters that identify an event uniquely in scope of communication of a particular master and slave couple. I.e there can not be 2 events from the same staying connected master which have the same coordinates. @note Such identifier is not yet unique generally as the event originating master is resettable. Also the crashed master can be replaced with some other. */ typedef struct event_coordinates { char * file_name; // binlog file name (directories stripped) my_off_t pos; // event's position in the binlog file } LOG_POS_COORD; /** @class Log_event This is the abstract base class for binary log events. @section Log_event_binary_format Binary Format Any @c Log_event saved on disk consists of the following three components. - Common-Header - Post-Header - Body The Common-Header, documented in the table @ref Table_common_header "below", always has the same form and length within one version of MySQL. Each event type specifies a format and length of the Post-Header. The length of the Common-Header is the same for all events of the same type. The Body may be of different format and length even for different events of the same type. The binary formats of Post-Header and Body are documented separately in each subclass. The binary format of Common-Header is as follows.
Common-Header
Name Format Description
timestamp 4 byte unsigned integer The time when the query started, in seconds since 1970.
type 1 byte enumeration See enum #Log_event_type.
server_id 4 byte unsigned integer Server ID of the server that created the event.
total_size 4 byte unsigned integer The total size of this event, in bytes. In other words, this is the sum of the sizes of Common-Header, Post-Header, and Body.
master_position 4 byte unsigned integer The position of the next event in the master binary log, in bytes from the beginning of the file. In a binlog that is not a relay log, this is just the position of the next event, in bytes from the beginning of the file. In a relay log, this is the position of the next event in the master's binlog.
flags 2 byte bitfield See Log_event::flags.
Summing up the numbers above, we see that the total size of the common header is 19 bytes. @subsection Log_event_format_of_atomic_primitives Format of Atomic Primitives - All numbers, whether they are 16-, 24-, 32-, or 64-bit numbers, are stored in little endian, i.e., the least significant byte first, unless otherwise specified. @anchor packed_integer - Some events use a special format for efficient representation of unsigned integers, called Packed Integer. A Packed Integer has the capacity of storing up to 8-byte integers, while small integers still can use 1, 3, or 4 bytes. The value of the first byte determines how to read the number, according to the following table:
Format of Packed Integer
First byte Format
0-250 The first byte is the number (in the range 0-250), and no more bytes are used.
252 Two more bytes are used. The number is in the range 251-0xffff.
253 Three more bytes are used. The number is in the range 0xffff-0xffffff.
254 Eight more bytes are used. The number is in the range 0xffffff-0xffffffffffffffff.
- Strings are stored in various formats. The format of each string is documented separately. */ class Log_event { public: /** Enumeration of what kinds of skipping (and non-skipping) that can occur when the slave executes an event. @see shall_skip @see do_shall_skip */ enum enum_skip_reason { /** Don't skip event. */ EVENT_SKIP_NOT, /** Skip event by ignoring it. This means that the slave skip counter will not be changed. */ EVENT_SKIP_IGNORE, /** Skip event and decrease skip counter. */ EVENT_SKIP_COUNT }; enum enum_event_cache_type { EVENT_INVALID_CACHE, /* If possible the event should use a non-transactional cache before being flushed to the binary log. This means that it must be flushed right after its correspondent statement is completed. */ EVENT_STMT_CACHE, /* The event should use a transactional cache before being flushed to the binary log. This means that it must be flushed upon commit or rollback. */ EVENT_TRANSACTIONAL_CACHE, /* The event must be written directly to the binary log without going through a cache. */ EVENT_NO_CACHE, /** If there is a need for different types, introduce them before this. */ EVENT_CACHE_COUNT }; /* The following type definition is to be used whenever data is placed and manipulated in a common buffer. Use this typedef for buffers that contain data containing binary and character data. */ typedef unsigned char Byte; /* The offset in the log where this event originally appeared (it is preserved in relay logs, making SHOW SLAVE STATUS able to print coordinates of the event in the master's binlog). Note: when a transaction is written by the master to its binlog (wrapped in BEGIN/COMMIT) the log_pos of all the queries it contains is the one of the BEGIN (this way, when one does SHOW SLAVE STATUS it sees the offset of the BEGIN, which is logical as rollback may occur), except the COMMIT query which has its real offset. */ my_off_t log_pos; /* A temp buffer for read_log_event; it is later analysed according to the event's type, and its content is distributed in the event-specific fields. */ uchar *temp_buf; /* TRUE <=> this event 'owns' temp_buf and should call my_free() when done with it */ bool event_owns_temp_buf; /* Timestamp on the master(for debugging and replication of NOW()/TIMESTAMP). It is important for queries and LOAD DATA INFILE. This is set at the event's creation time, except for Query and Load (et al.) events where this is set at the query's execution time, which guarantees good replication (otherwise, we could have a query and its event with different timestamps). */ my_time_t when; ulong when_sec_part; /* The number of seconds the query took to run on the master. */ ulong exec_time; /* Number of bytes written by write() function */ size_t data_written; /* The master's server id (is preserved in the relay log; used to prevent from infinite loops in circular replication). */ uint32 server_id; /** Some 16 flags. See the definitions above for LOG_EVENT_TIME_F, LOG_EVENT_FORCED_ROTATE_F, LOG_EVENT_THREAD_SPECIFIC_F, LOG_EVENT_SUPPRESS_USE_F, and LOG_EVENT_SKIP_REPLICATION_F for notes. */ uint16 flags; enum_event_cache_type cache_type; /** A storage to cache the global system variable's value. Handling of a separate event will be governed its member. */ ulong slave_exec_mode; Log_event_writer *writer; #ifdef MYSQL_SERVER THD* thd; Log_event(); Log_event(THD* thd_arg, uint16 flags_arg, bool is_transactional); /* init_show_field_list() prepares the column names and types for the output of SHOW BINLOG EVENTS; it is used only by SHOW BINLOG EVENTS. */ static void init_show_field_list(THD *thd, List* field_list); #ifdef HAVE_REPLICATION int net_send(Protocol *protocol, const char* log_name, my_off_t pos); /* pack_info() is used by SHOW BINLOG EVENTS; as print() it prepares and sends a string to display to the user, so it resembles print(). */ virtual void pack_info(Protocol *protocol); #endif /* HAVE_REPLICATION */ virtual const char* get_db() { return thd ? thd->db.str : 0; } #else Log_event() : temp_buf(0), when(0), flags(0) {} ha_checksum crc; /* print*() functions are used by mysqlbinlog */ virtual bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) = 0; bool print_timestamp(IO_CACHE* file, time_t *ts = 0); bool print_header(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info, bool is_more); bool print_base64(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info, bool do_print_encoded); #endif /* MYSQL_SERVER */ /* The following code used for Flashback */ #ifdef MYSQL_CLIENT my_bool is_flashback; my_bool need_flashback_review; String output_buf; // Storing the event output #ifdef WHEN_FLASHBACK_REVIEW_READY String m_review_dbname; String m_review_tablename; void set_review_dbname(const char *name) { if (name) { m_review_dbname.free(); m_review_dbname.append(name); } } void set_review_tablename(const char *name) { if (name) { m_review_tablename.free(); m_review_tablename.append(name); } } const char *get_review_dbname() const { return m_review_dbname.ptr(); } const char *get_review_tablename() const { return m_review_tablename.ptr(); } #endif #endif /* read_log_event() functions read an event from a binlog or relay log; used by SHOW BINLOG EVENTS, the binlog_dump thread on the master (reads master's binlog), the slave IO thread (reads the event sent by binlog_dump), the slave SQL thread (reads the event from the relay log). If mutex is 0, the read will proceed without mutex. We need the description_event to be able to parse the event (to know the post-header's size); in fact in read_log_event we detect the event's type, then call the specific event's constructor and pass description_event as an argument. */ static Log_event* read_log_event(IO_CACHE* file, int *out_error, const Format_description_log_event *description_event, my_bool crc_check, my_bool print_errors= 1); /** Reads an event from a binlog or relay log. Used by the dump thread this method reads the event into a raw buffer without parsing it. @Note If mutex is 0, the read will proceed without mutex. @Note If a log name is given than the method will check if the given binlog is still active. @param[in] file log file to be read @param[out] packet packet to hold the event @param[in] checksum_alg_arg verify the event checksum using this algorithm (or don't if it's use BINLOG_CHECKSUM_ALG_OFF) @retval 0 success @retval LOG_READ_EOF end of file, nothing was read @retval LOG_READ_BOGUS malformed event @retval LOG_READ_IO io error while reading @retval LOG_READ_MEM packet memory allocation failed @retval LOG_READ_TRUNC only a partial event could be read @retval LOG_READ_TOO_LARGE event too large */ static int read_log_event(IO_CACHE* file, String* packet, const Format_description_log_event *fdle, enum enum_binlog_checksum_alg checksum_alg_arg); /* The value is set by caller of FD constructor and Log_event::write_header() for the rest. In the FD case it's propagated into the last byte of post_header_len[] at FD::write(). On the slave side the value is assigned from post_header_len[last] of the last seen FD event. */ enum enum_binlog_checksum_alg checksum_alg; static void *operator new(size_t size) { extern PSI_memory_key key_memory_log_event; return my_malloc(key_memory_log_event, size, MYF(MY_WME|MY_FAE)); } static void operator delete(void *ptr, size_t) { my_free(ptr); } /* Placement version of the above operators */ static void *operator new(size_t, void* ptr) { return ptr; } static void operator delete(void*, void*) { } #ifdef MYSQL_SERVER bool write_header(size_t event_data_length); bool write_data(const uchar *buf, size_t data_length) { return writer->write_data(buf, data_length); } bool write_data(const char *buf, size_t data_length) { return write_data((uchar*)buf, data_length); } bool write_footer() { return writer->write_footer(); } my_bool need_checksum(); virtual bool write() { return write_header(get_data_size()) || write_data_header() || write_data_body() || write_footer(); } virtual bool write_data_header() { return 0; } virtual bool write_data_body() { return 0; } /* Return start of query time or current time */ inline my_time_t get_time() { THD *tmp_thd; if (when) return when; if (thd) { when= thd->start_time; when_sec_part= thd->start_time_sec_part; return when; } /* thd will only be 0 here at time of log creation */ if ((tmp_thd= current_thd)) { when= tmp_thd->start_time; when_sec_part= tmp_thd->start_time_sec_part; return when; } my_hrtime_t hrtime= my_hrtime(); when= hrtime_to_my_time(hrtime); when_sec_part= hrtime_sec_part(hrtime); return when; } #endif virtual Log_event_type get_type_code() = 0; virtual enum_logged_status logged_status() { return LOGGED_CRITICAL; } virtual bool is_valid() const = 0; virtual my_off_t get_header_len(my_off_t len) { return len; } void set_artificial_event() { flags |= LOG_EVENT_ARTIFICIAL_F; } void set_relay_log_event() { flags |= LOG_EVENT_RELAY_LOG_F; } bool is_artificial_event() const { return flags & LOG_EVENT_ARTIFICIAL_F; } bool is_relay_log_event() const { return flags & LOG_EVENT_RELAY_LOG_F; } inline bool use_trans_cache() const { return (cache_type == Log_event::EVENT_TRANSACTIONAL_CACHE); } inline void set_direct_logging() { cache_type = Log_event::EVENT_NO_CACHE; } inline bool use_direct_logging() { return (cache_type == Log_event::EVENT_NO_CACHE); } Log_event(const uchar *buf, const Format_description_log_event *description_event); virtual ~Log_event() { free_temp_buf();} void register_temp_buf(uchar* buf, bool must_free) { temp_buf= buf; event_owns_temp_buf= must_free; } void free_temp_buf() { if (temp_buf) { if (event_owns_temp_buf) my_free(temp_buf); temp_buf = 0; } } /* Get event length for simple events. For complicated events the length is calculated during write() */ virtual int get_data_size() { return 0;} static Log_event* read_log_event(const uchar *buf, uint event_len, const char **error, const Format_description_log_event *description_event, my_bool crc_check, my_bool print_errors= 1); /** Returns the human readable name of the given event type. */ static const char* get_type_str(Log_event_type type); /** Returns the human readable name of this event's type. */ const char* get_type_str(); #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) /** Apply the event to the database. This function represents the public interface for applying an event. @see do_apply_event */ int apply_event(rpl_group_info *rgi) { int res; THD_STAGE_INFO(thd, stage_apply_event); res= do_apply_event(rgi); THD_STAGE_INFO(thd, stage_after_apply_event); return res; } /** Update the relay log position. This function represents the public interface for "stepping over" the event and will update the relay log information. @see do_update_pos */ int update_pos(rpl_group_info *rgi) { return do_update_pos(rgi); } /** Decide if the event shall be skipped, and the reason for skipping it. @see do_shall_skip */ enum_skip_reason shall_skip(rpl_group_info *rgi) { return do_shall_skip(rgi); } /* Check if an event is non-final part of a stand-alone event group, such as Intvar_log_event (such events should be processed as part of the following event group, not individually). See also is_part_of_group() */ static bool is_part_of_group(enum Log_event_type ev_type) { switch (ev_type) { case GTID_EVENT: case INTVAR_EVENT: case RAND_EVENT: case USER_VAR_EVENT: case TABLE_MAP_EVENT: case ANNOTATE_ROWS_EVENT: return true; case DELETE_ROWS_EVENT: case UPDATE_ROWS_EVENT: case WRITE_ROWS_EVENT: /* ToDo: also check for non-final Rows_log_event (though such events are usually in a BEGIN-COMMIT group). */ default: return false; } } /* Same as above, but works on the object. In addition this is true for all rows event except the last one. */ virtual bool is_part_of_group() { return 0; } static bool is_group_event(enum Log_event_type ev_type) { switch (ev_type) { case START_EVENT_V3: case STOP_EVENT: case ROTATE_EVENT: case SLAVE_EVENT: case FORMAT_DESCRIPTION_EVENT: case INCIDENT_EVENT: case HEARTBEAT_LOG_EVENT: case BINLOG_CHECKPOINT_EVENT: case GTID_LIST_EVENT: case START_ENCRYPTION_EVENT: return false; default: return true; } } protected: /** Helper function to ignore an event w.r.t. the slave skip counter. This function can be used inside do_shall_skip() for functions that cannot end a group. If the slave skip counter is 1 when seeing such an event, the event shall be ignored, the counter left intact, and processing continue with the next event. A typical usage is: @code enum_skip_reason do_shall_skip(rpl_group_info *rgi) { return continue_group(rgi); } @endcode @return Skip reason */ enum_skip_reason continue_group(rpl_group_info *rgi); /** Primitive to apply an event to the database. This is where the change to the database is made. @note The primitive is protected instead of private, since there is a hierarchy of actions to be performed in some cases. @see Format_description_log_event::do_apply_event() @param rli Pointer to relay log info structure @retval 0 Event applied successfully @retval errno Error code if event application failed */ virtual int do_apply_event(rpl_group_info *rgi) { return 0; /* Default implementation does nothing */ } /** Advance relay log coordinates. This function is called to advance the relay log coordinates to just after the event. It is essential that both the relay log coordinate and the group log position is updated correctly, since this function is used also for skipping events. Normally, each implementation of do_update_pos() shall: - Update the event position to refer to the position just after the event. - Update the group log position to refer to the position just after the event if the event is last in a group @param rli Pointer to relay log info structure @retval 0 Coordinates changed successfully @retval errno Error code if advancing failed (usually just 1). Observe that handler errors are returned by the do_apply_event() function, and not by this one. */ virtual int do_update_pos(rpl_group_info *rgi); /** Decide if this event shall be skipped or not and the reason for skipping it. The default implementation decide that the event shall be skipped if either: - the server id of the event is the same as the server id of the server and rli->replicate_same_server_id is true, or - if rli->slave_skip_counter is greater than zero. @see do_apply_event @see do_update_pos @retval Log_event::EVENT_SKIP_NOT The event shall not be skipped and should be applied. @retval Log_event::EVENT_SKIP_IGNORE The event shall be skipped by just ignoring it, i.e., the slave skip counter shall not be changed. This happends if, for example, the originating server id of the event is the same as the server id of the slave. @retval Log_event::EVENT_SKIP_COUNT The event shall be skipped because the slave skip counter was non-zero. The caller shall decrease the counter by one. */ virtual enum_skip_reason do_shall_skip(rpl_group_info *rgi); #endif }; /* One class for each type of event. Two constructors for each class: - one to create the event for logging (when the server acts as a master), called after an update to the database is done, which accepts parameters like the query, the database, the options for LOAD DATA INFILE... - one to create the event from a packet (when the server acts as a slave), called before reproducing the update, which accepts parameters (like a buffer). Used to read from the master, from the relay log, and in mysqlbinlog. This constructor must be format-tolerant. */ /** @class Query_log_event A @c Query_log_event is created for each query that modifies the database, unless the query is logged row-based. @section Query_log_event_binary_format Binary format See @ref Log_event_binary_format "Binary format for log events" for a general discussion and introduction to the binary format of binlog events. The Post-Header has five components:
Post-Header for Query_log_event
Name Format Description
slave_proxy_id 4 byte unsigned integer An integer identifying the client thread that issued the query. The id is unique per server. (Note, however, that two threads on different servers may have the same slave_proxy_id.) This is used when a client thread creates a temporary table local to the client. The slave_proxy_id is used to distinguish temporary tables that belong to different clients.
exec_time 4 byte unsigned integer The time from when the query started to when it was logged in the binlog, in seconds.
db_len 1 byte integer The length of the name of the currently selected database.
error_code 2 byte unsigned integer Error code generated by the master. If the master fails, the slave will fail with the same error code, except for the error codes ER_DB_CREATE_EXISTS == 1007 and ER_DB_DROP_EXISTS == 1008.
status_vars_len 2 byte unsigned integer The length of the status_vars block of the Body, in bytes. See @ref query_log_event_status_vars "below".
The Body has the following components:
Body for Query_log_event
Name Format Description
@anchor query_log_event_status_vars status_vars status_vars_len bytes Zero or more status variables. Each status variable consists of one byte identifying the variable stored, followed by the value of the variable. The possible variables are listed separately in the table @ref Table_query_log_event_status_vars "below". MySQL always writes events in the order defined below; however, it is capable of reading them in any order.
db db_len+1 The currently selected database, as a null-terminated string. (The trailing zero is redundant since the length is already known; it is db_len from Post-Header.)
query variable length string without trailing zero, extending to the end of the event (determined by the length field of the Common-Header) The SQL query.
The following table lists the status variables that may appear in the status_vars field. @anchor Table_query_log_event_status_vars
Status variables for Query_log_event
Status variable 1 byte identifier Format Description
flags2 Q_FLAGS2_CODE == 0 4 byte bitfield The flags in @c thd->options, binary AND-ed with @c OPTIONS_WRITTEN_TO_BIN_LOG. The @c thd->options bitfield contains options for "SELECT". @c OPTIONS_WRITTEN identifies those options that need to be written to the binlog (not all do). These flags correspond to the SQL variables SQL_AUTO_IS_NULL, FOREIGN_KEY_CHECKS, UNIQUE_CHECKS, and AUTOCOMMIT, documented in the "SET Syntax" section of the MySQL Manual. This field is always written to the binlog in version >= 5.0, and never written in version < 5.0.
sql_mode Q_SQL_MODE_CODE == 1 8 byte bitfield The @c sql_mode variable. See the section "SQL Modes" in the MySQL manual, and see sql_priv.h for a list of the possible flags. Currently (2007-10-04), the following flags are available:
    MODE_REAL_AS_FLOAT==0x1
    MODE_PIPES_AS_CONCAT==0x2
    MODE_ANSI_QUOTES==0x4
    MODE_IGNORE_SPACE==0x8
    MODE_IGNORE_BAD_TABLE_OPTIONS==0x10
    MODE_ONLY_FULL_GROUP_BY==0x20
    MODE_NO_UNSIGNED_SUBTRACTION==0x40
    MODE_NO_DIR_IN_CREATE==0x80
    MODE_POSTGRESQL==0x100
    MODE_ORACLE==0x200
    MODE_MSSQL==0x400
    MODE_DB2==0x800
    MODE_MAXDB==0x1000
    MODE_NO_KEY_OPTIONS==0x2000
    MODE_NO_TABLE_OPTIONS==0x4000
    MODE_NO_FIELD_OPTIONS==0x8000
    MODE_MYSQL323==0x10000
    MODE_MYSQL323==0x20000
    MODE_MYSQL40==0x40000
    MODE_ANSI==0x80000
    MODE_NO_AUTO_VALUE_ON_ZERO==0x100000
    MODE_NO_BACKSLASH_ESCAPES==0x200000
    MODE_STRICT_TRANS_TABLES==0x400000
    MODE_STRICT_ALL_TABLES==0x800000
    MODE_NO_ZERO_IN_DATE==0x1000000
    MODE_NO_ZERO_DATE==0x2000000
    MODE_INVALID_DATES==0x4000000
    MODE_ERROR_FOR_DIVISION_BY_ZERO==0x8000000
    MODE_TRADITIONAL==0x10000000
    MODE_NO_AUTO_CREATE_USER==0x20000000
    MODE_HIGH_NOT_PRECEDENCE==0x40000000
    MODE_PAD_CHAR_TO_FULL_LENGTH==0x80000000
    
All these flags are replicated from the server. However, all flags except @c MODE_NO_DIR_IN_CREATE are honored by the slave; the slave always preserves its old value of @c MODE_NO_DIR_IN_CREATE. For a rationale, see comment in @c Query_log_event::do_apply_event in @c log_event.cc. This field is always written to the binlog.
catalog Q_CATALOG_NZ_CODE == 6 Variable-length string: the length in bytes (1 byte) followed by the characters (at most 255 bytes) Stores the client's current catalog. Every database belongs to a catalog, the same way that every table belongs to a database. Currently, there is only one catalog, "std". This field is written if the length of the catalog is > 0; otherwise it is not written.
auto_increment Q_AUTO_INCREMENT == 3 two 2 byte unsigned integers, totally 2+2=4 bytes The two variables auto_increment_increment and auto_increment_offset, in that order. For more information, see "System variables" in the MySQL manual. This field is written if auto_increment > 1. Otherwise, it is not written.
charset Q_CHARSET_CODE == 4 three 2 byte unsigned integers, totally 2+2+2=6 bytes The three variables character_set_client, collation_connection, and collation_server, in that order. character_set_client is a code identifying the character set and collation used by the client to encode the query. collation_connection identifies the character set and collation that the master converts the query to when it receives it; this is useful when comparing literal strings. collation_server is the default character set and collation used when a new database is created. See also "Connection Character Sets and Collations" in the MySQL 5.1 manual. All three variables are codes identifying a (character set, collation) pair. To see which codes map to which pairs, run the query "SELECT id, character_set_name, collation_name FROM COLLATIONS". Cf. Q_CHARSET_DATABASE_CODE below. This field is always written.
time_zone Q_TIME_ZONE_CODE == 5 Variable-length string: the length in bytes (1 byte) followed by the characters (at most 255 bytes). The time_zone of the master. See also "System Variables" and "MySQL Server Time Zone Support" in the MySQL manual. This field is written if the length of the time zone string is > 0; otherwise, it is not written.
lc_time_names_number Q_LC_TIME_NAMES_CODE == 7 2 byte integer A code identifying a table of month and day names. The mapping from codes to languages is defined in @c sql_locale.cc. This field is written if it is not 0, i.e., if the locale is not en_US.
charset_database_number Q_CHARSET_DATABASE_CODE == 8 2 byte integer The value of the collation_database system variable (in the source code stored in @c thd->variables.collation_database), which holds the code for a (character set, collation) pair as described above (see Q_CHARSET_CODE). collation_database was used in old versions (???WHEN). Its value was loaded when issuing a "use db" query and could be changed by issuing a "SET collation_database=xxx" query. It used to affect the "LOAD DATA INFILE" and "CREATE TABLE" commands. In newer versions, "CREATE TABLE" has been changed to take the character set from the database of the created table, rather than the character set of the current database. This makes a difference when creating a table in another database than the current one. "LOAD DATA INFILE" has not yet changed to do this, but there are plans to eventually do it, and to make collation_database read-only. This field is written if it is not 0.
table_map_for_update Q_TABLE_MAP_FOR_UPDATE_CODE == 9 8 byte integer The value of the table map that is to be updated by the multi-table update query statement. Every bit of this variable represents a table, and is set to 1 if the corresponding table is to be updated by this statement. The value of this variable is set when executing a multi-table update statement and used by slave to apply filter rules without opening all the tables on slave. This is required because some tables may not exist on slave because of the filter rules.
@subsection Query_log_event_notes_on_previous_versions Notes on Previous Versions * Status vars were introduced in version 5.0. To read earlier versions correctly, check the length of the Post-Header. * The status variable Q_CATALOG_CODE == 2 existed in MySQL 5.0.x, where 0<=x<=3. It was identical to Q_CATALOG_CODE, except that the string had a trailing '\0'. The '\0' was removed in 5.0.4 since it was redundant (the string length is stored before the string). The Q_CATALOG_CODE will never be written by a new master, but can still be understood by a new slave. * See Q_CHARSET_DATABASE_CODE in the table above. * When adding new status vars, please don't forget to update the MAX_SIZE_LOG_EVENT_STATUS, and update function code_name */ class Query_log_event: public Log_event { LEX_CSTRING user; LEX_CSTRING host; protected: Log_event::Byte* data_buf; public: const char* query; const char* catalog; const char* db; /* If we already know the length of the query string we pass it with q_len, so we would not have to call strlen() otherwise, set it to 0, in which case, we compute it with strlen() */ uint32 q_len; uint32 db_len; uint16 error_code; my_thread_id thread_id; /* For events created by Query_log_event::do_apply_event (and Load_log_event::do_apply_event()) we need the *original* thread id, to be able to log the event with the original (=master's) thread id (fix for BUG#1686). */ ulong slave_proxy_id; /* Binlog format 3 and 4 start to differ (as far as class members are concerned) from here. */ uint catalog_len; // <= 255 char; 0 means uninited /* We want to be able to store a variable number of N-bit status vars: (generally N=32; but N=64 for SQL_MODE) a user may want to log the number of affected rows (for debugging) while another does not want to lose 4 bytes in this. The storage on disk is the following: status_vars_len is part of the post-header, status_vars are in the variable-length part, after the post-header, before the db & query. status_vars on disk is a sequence of pairs (code, value) where 'code' means 'sql_mode', 'affected' etc. Sometimes 'value' must be a short string, so its first byte is its length. For now the order of status vars is: flags2 - sql_mode - catalog - autoinc - charset We should add the same thing to Load_log_event, but in fact LOAD DATA INFILE is going to be logged with a new type of event (logging of the plain text query), so Load_log_event would be frozen, so no need. The new way of logging LOAD DATA INFILE would use a derived class of Query_log_event, so automatically benefit from the work already done for status variables in Query_log_event. */ uint16 status_vars_len; /* 'flags2' is a second set of flags (on top of those in Log_event), for session variables. These are thd->options which is & against a mask (OPTIONS_WRITTEN_TO_BIN_LOG). flags2_inited helps make a difference between flags2==0 (3.23 or 4.x master, we don't know flags2, so use the slave server's global options) and flags2==0 (5.0 master, we know this has a meaning of flags all down which must influence the query). */ uint32 flags2_inited; bool sql_mode_inited; bool charset_inited; uint32 flags2; sql_mode_t sql_mode; ulong auto_increment_increment, auto_increment_offset; char charset[6]; uint time_zone_len; /* 0 means uninited */ const char *time_zone_str; uint lc_time_names_number; /* 0 means en_US */ uint charset_database_number; /* map for tables that will be updated for a multi-table update query statement, for other query statements, this will be zero. */ ulonglong table_map_for_update; /* Xid for the event, if such exists */ ulonglong xid; /* Holds the original length of a Query_log_event that comes from a master of version < 5.0 (i.e., binlog_version < 4). When the IO thread writes the relay log, it augments the Query_log_event with a Q_MASTER_DATA_WRITTEN_CODE status_var that holds the original event length. This field is initialized to non-zero in the SQL thread when it reads this augmented event. SQL thread does not write Q_MASTER_DATA_WRITTEN_CODE to the slave's server binlog. */ uint32 master_data_written; #ifdef MYSQL_SERVER Query_log_event(THD* thd_arg, const char* query_arg, size_t query_length, bool using_trans, bool direct, bool suppress_use, int error); const char* get_db() override { return db; } #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print_query_header(IO_CACHE* file, PRINT_EVENT_INFO* print_event_info); bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Query_log_event(); Query_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event, Log_event_type event_type); ~Query_log_event() { if (data_buf) my_free(data_buf); } Log_event_type get_type_code() override { return QUERY_EVENT; } static int dummy_event(String *packet, ulong ev_offset, enum enum_binlog_checksum_alg checksum_alg); static int begin_event(String *packet, ulong ev_offset, enum enum_binlog_checksum_alg checksum_alg); #ifdef MYSQL_SERVER bool write() override; virtual bool write_post_header_for_derived() { return FALSE; } #endif bool is_valid() const override { return query != 0; } /* Returns number of bytes additionally written to post header by derived events (so far it is only Execute_load_query event). */ virtual ulong get_post_header_size_for_derived() { return 0; } /* Writes derived event-specific part of post header. */ public: /* !!! Public in this patch to allow old usage */ #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; int do_apply_event(rpl_group_info *rgi) override; int do_apply_event(rpl_group_info *rgi, const char *query_arg, uint32 q_len_arg); static bool peek_is_commit_rollback(const uchar *event_start, size_t event_len, enum enum_binlog_checksum_alg checksum_alg); #endif /* HAVE_REPLICATION */ /* If true, the event always be applied by slave SQL thread or be printed by mysqlbinlog */ bool is_trans_keyword(bool is_xa) { /* Before the patch for bug#50407, The 'SAVEPOINT and ROLLBACK TO' queries input by user was written into log events directly. So the keywords can be written in both upper case and lower case together, strncasecmp is used to check both cases. they also could be binlogged with comments in the front of these keywords. for examples: / * bla bla * / SAVEPOINT a; / * bla bla * / ROLLBACK TO a; but we don't handle these cases and after the patch, both quiries are binlogged in upper case with no comments. */ return is_xa ? !strncasecmp(query, C_STRING_WITH_LEN("XA ")) : (!strncmp(query, "BEGIN", q_len) || !strncmp(query, "COMMIT", q_len) || !strncasecmp(query, "SAVEPOINT", 9) || !strncasecmp(query, "ROLLBACK", 8)); } virtual bool is_begin() { return !strcmp(query, "BEGIN"); } virtual bool is_commit() { return !strcmp(query, "COMMIT"); } virtual bool is_rollback() { return !strcmp(query, "ROLLBACK"); } }; class Query_compressed_log_event:public Query_log_event{ protected: Log_event::Byte* query_buf; // point to the uncompressed query public: Query_compressed_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event, Log_event_type event_type); ~Query_compressed_log_event() { if (query_buf) my_free(query_buf); } Log_event_type get_type_code() override { return QUERY_COMPRESSED_EVENT; } /* the min length of log_bin_compress_min_len is 10, means that Begin/Commit/Rollback would never be compressed! */ bool is_begin() override { return false; } bool is_commit() override { return false; } bool is_rollback() override { return false; } #ifdef MYSQL_SERVER Query_compressed_log_event(THD* thd_arg, const char* query_arg, ulong query_length, bool using_trans, bool direct, bool suppress_use, int error); bool write() override; #endif }; /***************************************************************************** sql_ex_info struct ****************************************************************************/ struct sql_ex_info { const char* field_term; const char* enclosed; const char* line_term; const char* line_start; const char* escaped; int cached_new_format= -1; uint8 field_term_len= 0, enclosed_len= 0, line_term_len= 0, line_start_len= 0, escaped_len= 0; char opt_flags; char empty_flags= 0; // store in new format even if old is possible void force_new_format() { cached_new_format = 1;} int data_size() { return (new_format() ? field_term_len + enclosed_len + line_term_len + line_start_len + escaped_len + 6 : 7); } bool write_data(Log_event_writer *writer); const uchar *init(const uchar *buf, const uchar* buf_end, bool use_new_format); bool new_format() { return ((cached_new_format != -1) ? cached_new_format : (cached_new_format=(field_term_len > 1 || enclosed_len > 1 || line_term_len > 1 || line_start_len > 1 || escaped_len > 1))); } }; /** @class Load_log_event This log event corresponds to a "LOAD DATA INFILE" SQL query on the following form: @verbatim (1) USE db; (2) LOAD DATA [CONCURRENT] [LOCAL] INFILE 'file_name' (3) [REPLACE | IGNORE] (4) INTO TABLE 'table_name' (5) [FIELDS (6) [TERMINATED BY 'field_term'] (7) [[OPTIONALLY] ENCLOSED BY 'enclosed'] (8) [ESCAPED BY 'escaped'] (9) ] (10) [LINES (11) [TERMINATED BY 'line_term'] (12) [LINES STARTING BY 'line_start'] (13) ] (14) [IGNORE skip_lines LINES] (15) (field_1, field_2, ..., field_n)@endverbatim @section Load_log_event_binary_format Binary Format The Post-Header consists of the following six components.
Post-Header for Load_log_event
Name Format Description
slave_proxy_id 4 byte unsigned integer An integer identifying the client thread that issued the query. The id is unique per server. (Note, however, that two threads on different servers may have the same slave_proxy_id.) This is used when a client thread creates a temporary table local to the client. The slave_proxy_id is used to distinguish temporary tables that belong to different clients.
exec_time 4 byte unsigned integer The time from when the query started to when it was logged in the binlog, in seconds.
skip_lines 4 byte unsigned integer The number on line (14) above, if present, or 0 if line (14) is left out.
table_name_len 1 byte unsigned integer The length of 'table_name' on line (4) above.
db_len 1 byte unsigned integer The length of 'db' on line (1) above.
num_fields 4 byte unsigned integer The number n of fields on line (15) above.
The Body contains the following components.
Body of Load_log_event
Name Format Description
sql_ex variable length Describes the part of the query on lines (3) and (5)–(13) above. More precisely, it stores the five strings (on lines) field_term (6), enclosed (7), escaped (8), line_term (11), and line_start (12); as well as a bitfield indicating the presence of the keywords REPLACE (3), IGNORE (3), and OPTIONALLY (7). The data is stored in one of two formats, called "old" and "new". The type field of Common-Header determines which of these two formats is used: type LOAD_EVENT means that the old format is used, and type NEW_LOAD_EVENT means that the new format is used. When MySQL writes a Load_log_event, it uses the new format if at least one of the five strings is two or more bytes long. Otherwise (i.e., if all strings are 0 or 1 bytes long), the old format is used. The new and old format differ in the way the five strings are stored.
  • In the new format, the strings are stored in the order field_term, enclosed, escaped, line_term, line_start. Each string consists of a length (1 byte), followed by a sequence of characters (0-255 bytes). Finally, a boolean combination of the following flags is stored in 1 byte: REPLACE_FLAG==0x4, IGNORE_FLAG==0x8, and OPT_ENCLOSED_FLAG==0x2. If a flag is set, it indicates the presence of the corresponding keyword in the SQL query.
  • In the old format, we know that each string has length 0 or 1. Therefore, only the first byte of each string is stored. The order of the strings is the same as in the new format. These five bytes are followed by the same 1 byte bitfield as in the new format. Finally, a 1 byte bitfield called empty_flags is stored. The low 5 bits of empty_flags indicate which of the five strings have length 0. For each of the following flags that is set, the corresponding string has length 0; for the flags that are not set, the string has length 1: FIELD_TERM_EMPTY==0x1, ENCLOSED_EMPTY==0x2, LINE_TERM_EMPTY==0x4, LINE_START_EMPTY==0x8, ESCAPED_EMPTY==0x10.
Thus, the size of the new format is 6 bytes + the sum of the sizes of the five strings. The size of the old format is always 7 bytes.
field_lens num_fields 1 byte unsigned integers An array of num_fields integers representing the length of each field in the query. (num_fields is from the Post-Header).
fields num_fields null-terminated strings An array of num_fields null-terminated strings, each representing a field in the query. (The trailing zero is redundant, since the length are stored in the num_fields array.) The total length of all strings equals to the sum of all field_lens, plus num_fields bytes for all the trailing zeros.
table_name null-terminated string of length table_len+1 bytes The 'table_name' from the query, as a null-terminated string. (The trailing zero is actually redundant since the table_len is known from Post-Header.)
db null-terminated string of length db_len+1 bytes The 'db' from the query, as a null-terminated string. (The trailing zero is actually redundant since the db_len is known from Post-Header.)
file_name variable length string without trailing zero, extending to the end of the event (determined by the length field of the Common-Header) The 'file_name' from the query.
@subsection Load_log_event_notes_on_previous_versions Notes on Previous Versions This event type is understood by current versions, but only generated by MySQL 3.23 and earlier. */ class Load_log_event: public Log_event { private: protected: int copy_log_event(const uchar *buf, ulong event_len, int body_offset, const Format_description_log_event* description_event); public: bool print_query(THD *thd, bool need_db, const char *cs, String *buf, my_off_t *fn_start, my_off_t *fn_end, const char *qualify_db); my_thread_id thread_id; ulong slave_proxy_id; uint32 table_name_len; /* No need to have a catalog, as these events can only come from 4.x. TODO: this may become false if Dmitri pushes his new LOAD DATA INFILE in 5.0 only (not in 4.x). */ uint32 db_len; uint32 fname_len; uint32 num_fields; const char* fields; const uchar* field_lens; uint32 field_block_len; const char* table_name; const char* db; const char* fname; uint32 skip_lines; sql_ex_info sql_ex; bool local_fname; /** Indicates that this event corresponds to LOAD DATA CONCURRENT, @note Since Load_log_event event coming from the binary log lacks information whether LOAD DATA on master was concurrent or not, this flag is only set to TRUE for an auxiliary Load_log_event object which is used in mysql_load() to re-construct LOAD DATA statement from function parameters, for logging. */ bool is_concurrent; /* fname doesn't point to memory inside Log_event::temp_buf */ void set_fname_outside_temp_buf(const char *afname, size_t alen) { fname= afname; fname_len= (uint)alen; local_fname= TRUE; } /* fname doesn't point to memory inside Log_event::temp_buf */ int check_fname_outside_temp_buf() { return local_fname; } #ifdef MYSQL_SERVER String field_lens_buf; String fields_buf; Load_log_event(THD* thd, const sql_exchange* ex, const char* db_arg, const char* table_name_arg, List& fields_arg, bool is_concurrent_arg, enum enum_duplicates handle_dup, bool ignore, bool using_trans); void set_fields(const char* db, List &fields_arg, Name_resolution_context *context); const char* get_db() override { return db; } #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, bool commented); #endif /* Note that for all the events related to LOAD DATA (Load_log_event, Create_file/Append/Exec/Delete, we pass description_event; however as logging of LOAD DATA is going to be changed in 4.1 or 5.0, this is only used for the common_header_len (post_header_len will not be changed). */ Load_log_event(const uchar *buf, uint event_len, const Format_description_log_event* description_event); ~Load_log_event() = default; Log_event_type get_type_code() override { return sql_ex.new_format() ? NEW_LOAD_EVENT: LOAD_EVENT; } #ifdef MYSQL_SERVER bool write_data_header() override; bool write_data_body() override; #endif bool is_valid() const override { return table_name != 0; } int get_data_size() override { return (table_name_len + db_len + 2 + fname_len + LOAD_HEADER_LEN + sql_ex.data_size() + field_block_len + num_fields); } public: /* !!! Public in this patch to allow old usage */ #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override { return do_apply_event(thd->slave_net,rgi,0); } int do_apply_event(NET *net, rpl_group_info *rgi, bool use_rli_only_for_errors); #endif }; /** @class Start_log_event_v3 Start_log_event_v3 is the Start_log_event of binlog format 3 (MySQL 3.23 and 4.x). Format_description_log_event derives from Start_log_event_v3; it is the Start_log_event of binlog format 4 (MySQL 5.0), that is, the event that describes the other events' Common-Header/Post-Header lengths. This event is sent by MySQL 5.0 whenever it starts sending a new binlog if the requested position is >4 (otherwise if ==4 the event will be sent naturally). @section Start_log_event_v3_binary_format Binary Format */ class Start_log_event_v3: public Log_event { public: /* If this event is at the start of the first binary log since server startup 'created' should be the timestamp when the event (and the binary log) was created. In the other case (i.e. this event is at the start of a binary log created by FLUSH LOGS or automatic rotation), 'created' should be 0. This "trick" is used by MySQL >=4.0.14 slaves to know whether they must drop stale temporary tables and whether they should abort unfinished transaction. Note that when 'created'!=0, it is always equal to the event's timestamp; indeed Start_log_event is written only in log.cc where the first constructor below is called, in which 'created' is set to 'when'. So in fact 'created' is a useless variable. When it is 0 we can read the actual value from timestamp ('when') and when it is non-zero we can read the same value from timestamp ('when'). Conclusion: - we use timestamp to print when the binlog was created. - we use 'created' only to know if this is a first binlog or not. In 3.23.57 we did not pay attention to this identity, so mysqlbinlog in 3.23.57 does not print 'created the_date' if created was zero. This is now fixed. */ time_t created; uint16 binlog_version; char server_version[ST_SERVER_VER_LEN]; /* We set this to 1 if we don't want to have the created time in the log, which is the case when we rollover to a new log. */ bool dont_set_created; #ifdef MYSQL_SERVER Start_log_event_v3(); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else Start_log_event_v3() = default; bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Start_log_event_v3(const uchar *buf, uint event_len, const Format_description_log_event* description_event); ~Start_log_event_v3() = default; Log_event_type get_type_code() override { return START_EVENT_V3;} my_off_t get_header_len(my_off_t l __attribute__((unused))) override { return LOG_EVENT_MINIMAL_HEADER_LEN; } #ifdef MYSQL_SERVER bool write() override; #endif bool is_valid() const override { return server_version[0] != 0; } int get_data_size() override { return START_V3_HEADER_LEN; //no variable-sized part } protected: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info*) override { /* Events from ourself should be skipped, but they should not decrease the slave skip counter. */ if (this->server_id == global_system_variables.server_id) return Log_event::EVENT_SKIP_IGNORE; else return Log_event::EVENT_SKIP_NOT; } #endif }; /** @class Start_encryption_log_event Start_encryption_log_event marks the beginning of encrypted data (all events after this event are encrypted). It contains the cryptographic scheme used for the encryption as well as any data required to decrypt (except the actual key). For binlog cryptoscheme 1: key version, and nonce for iv generation. */ class Start_encryption_log_event : public Log_event { public: #ifdef MYSQL_SERVER Start_encryption_log_event(uint crypto_scheme_arg, uint key_version_arg, const uchar* nonce_arg) : crypto_scheme(crypto_scheme_arg), key_version(key_version_arg) { cache_type = EVENT_NO_CACHE; DBUG_ASSERT(crypto_scheme == 1); memcpy(nonce, nonce_arg, BINLOG_NONCE_LENGTH); } bool write_data_body() override { uchar scheme_buf= crypto_scheme; uchar key_version_buf[BINLOG_KEY_VERSION_LENGTH]; int4store(key_version_buf, key_version); return write_data(&scheme_buf, sizeof(scheme_buf)) || write_data(key_version_buf, sizeof(key_version_buf)) || write_data(nonce, BINLOG_NONCE_LENGTH); } #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Start_encryption_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); bool is_valid() const override { return crypto_scheme == 1; } Log_event_type get_type_code() override { return START_ENCRYPTION_EVENT; } int get_data_size() override { return BINLOG_CRYPTO_SCHEME_LENGTH + BINLOG_KEY_VERSION_LENGTH + BINLOG_NONCE_LENGTH; } uint crypto_scheme; uint key_version; uchar nonce[BINLOG_NONCE_LENGTH]; protected: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info* rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info* rgi) override { return Log_event::EVENT_SKIP_NOT; } #endif }; class Version { protected: uchar m_ver[3]; int cmp(const Version &other) const { return memcmp(m_ver, other.m_ver, 3); } public: Version() { m_ver[0]= m_ver[1]= m_ver[2]= '\0'; } Version(uchar v0, uchar v1, uchar v2) { m_ver[0]= v0; m_ver[1]= v1; m_ver[2]= v2; } Version(const char *version, const char **endptr); const uchar& operator [] (size_t i) const { DBUG_ASSERT(i < 3); return m_ver[i]; } bool operator<(const Version &other) const { return cmp(other) < 0; } bool operator>(const Version &other) const { return cmp(other) > 0; } bool operator<=(const Version &other) const { return cmp(other) <= 0; } bool operator>=(const Version &other) const { return cmp(other) >= 0; } }; /** @class Format_description_log_event For binlog version 4. This event is saved by threads which read it, as they need it for future use (to decode the ordinary events). @section Format_description_log_event_binary_format Binary Format */ class Format_description_log_event: public Start_log_event_v3 { public: /* The size of the fixed header which _all_ events have (for binlogs written by this version, this is equal to LOG_EVENT_HEADER_LEN), except FORMAT_DESCRIPTION_EVENT and ROTATE_EVENT (those have a header of size LOG_EVENT_MINIMAL_HEADER_LEN). */ uint8 common_header_len; uint8 number_of_event_types; /* The list of post-headers' lengths followed by the checksum alg description byte */ uint8 *post_header_len; class master_version_split: public Version { public: enum {KIND_MYSQL, KIND_MARIADB}; int kind; master_version_split() :kind(KIND_MARIADB) { } master_version_split(const char *version); bool version_is_valid() const { /* It is invalid only when all version numbers are 0 */ return !(m_ver[0] == 0 && m_ver[1] == 0 && m_ver[2] == 0); } }; master_version_split server_version_split; const uint8 *event_type_permutation; uint32 options_written_to_bin_log; Format_description_log_event(uint8 binlog_ver, const char* server_ver=0); Format_description_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Format_description_log_event() { my_free(post_header_len); } Log_event_type get_type_code() override { return FORMAT_DESCRIPTION_EVENT;} #ifdef MYSQL_SERVER bool write() override; #endif bool header_is_valid() const { return ((common_header_len >= ((binlog_version==1) ? OLD_HEADER_LEN : LOG_EVENT_MINIMAL_HEADER_LEN)) && (post_header_len != NULL)); } bool is_valid() const override { return header_is_valid() && server_version_split.version_is_valid(); } int get_data_size() override { /* The vector of post-header lengths is considered as part of the post-header, because in a given version it never changes (contrary to the query in a Query_log_event). */ return FORMAT_DESCRIPTION_HEADER_LEN; } Binlog_crypt_data crypto_data; bool start_decryption(Start_encryption_log_event* sele); void copy_crypto_data(const Format_description_log_event* o) { crypto_data= o->crypto_data; } void reset_crypto() { crypto_data.scheme= 0; } void calc_server_version_split(); void deduct_options_written_to_bin_log(); static bool is_version_before_checksum(const master_version_split *version_split); protected: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif }; /** @class Intvar_log_event An Intvar_log_event will be created just before a Query_log_event, if the query uses one of the variables LAST_INSERT_ID or INSERT_ID. Each Intvar_log_event holds the value of one of these variables. @section Intvar_log_event_binary_format Binary Format The Post-Header for this event type is empty. The Body has two components:
Body for Intvar_log_event
Name Format Description
type 1 byte enumeration One byte identifying the type of variable stored. Currently, two identifiers are supported: LAST_INSERT_ID_EVENT==1 and INSERT_ID_EVENT==2.
value 8 byte unsigned integer The value of the variable.
*/ class Intvar_log_event: public Log_event { public: ulonglong val; uchar type; #ifdef MYSQL_SERVER Intvar_log_event(THD* thd_arg,uchar type_arg, ulonglong val_arg, bool using_trans, bool direct) :Log_event(thd_arg,0,using_trans),val(val_arg),type(type_arg) { if (direct) cache_type= Log_event::EVENT_NO_CACHE; } #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Intvar_log_event(const uchar *buf, const Format_description_log_event *description_event); ~Intvar_log_event() = default; Log_event_type get_type_code() override { return INTVAR_EVENT;} const char* get_var_type_name(); int get_data_size() override { return 9; /* sizeof(type) + sizeof(val) */;} #ifdef MYSQL_SERVER bool write() override; #ifdef HAVE_REPLICATION bool is_part_of_group() override { return 1; } #endif #endif bool is_valid() const override { return 1; } private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif }; /** @class Rand_log_event Logs random seed used by the next RAND(), and by PASSWORD() in 4.1.0. 4.1.1 does not need it (it's repeatable again) so this event needn't be written in 4.1.1 for PASSWORD() (but the fact that it is written is just a waste, it does not cause bugs). The state of the random number generation consists of 128 bits, which are stored internally as two 64-bit numbers. @section Rand_log_event_binary_format Binary Format The Post-Header for this event type is empty. The Body has two components:
Body for Rand_log_event
Name Format Description
seed1 8 byte unsigned integer 64 bit random seed1.
seed2 8 byte unsigned integer 64 bit random seed2.
*/ class Rand_log_event: public Log_event { public: ulonglong seed1; ulonglong seed2; #ifdef MYSQL_SERVER Rand_log_event(THD* thd_arg, ulonglong seed1_arg, ulonglong seed2_arg, bool using_trans, bool direct) :Log_event(thd_arg,0,using_trans),seed1(seed1_arg),seed2(seed2_arg) { if (direct) cache_type= Log_event::EVENT_NO_CACHE; } #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Rand_log_event(const uchar *buf, const Format_description_log_event *description_event); ~Rand_log_event() = default; Log_event_type get_type_code() override { return RAND_EVENT;} int get_data_size() override { return 16; /* sizeof(ulonglong) * 2*/ } #ifdef MYSQL_SERVER bool write() override; #ifdef HAVE_REPLICATION bool is_part_of_group() override { return 1; } #endif #endif bool is_valid() const override { return 1; } private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif }; class Xid_apply_log_event: public Log_event { public: #ifdef MYSQL_SERVER Xid_apply_log_event(THD* thd_arg): Log_event(thd_arg, 0, TRUE) {} #endif Xid_apply_log_event(const uchar *buf, const Format_description_log_event *description_event): Log_event(buf, description_event) {} ~Xid_apply_log_event() {} bool is_valid() const override { return 1; } private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) virtual int do_commit()= 0; int do_apply_event(rpl_group_info *rgi) override; int do_record_gtid(THD *thd, rpl_group_info *rgi, bool in_trans, void **out_hton, bool force_err= false); enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; virtual const char* get_query()= 0; #endif }; /** @class Xid_log_event Logs xid of the transaction-to-be-committed in the 2pc protocol. Has no meaning in replication, slaves ignore it. @section Xid_log_event_binary_format Binary Format */ #ifdef MYSQL_CLIENT typedef ulonglong my_xid; // this line is the same as in handler.h #endif class Xid_log_event: public Xid_apply_log_event { public: my_xid xid; #ifdef MYSQL_SERVER Xid_log_event(THD* thd_arg, my_xid x, bool direct): Xid_apply_log_event(thd_arg), xid(x) { if (direct) cache_type= Log_event::EVENT_NO_CACHE; } #ifdef HAVE_REPLICATION const char* get_query() override { return "COMMIT /* implicit, from Xid_log_event */"; } void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Xid_log_event(const uchar *buf, const Format_description_log_event *description_event); ~Xid_log_event() = default; Log_event_type get_type_code() override { return XID_EVENT;} int get_data_size() override { return sizeof(xid); } #ifdef MYSQL_SERVER bool write() override; #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_commit() override; #endif }; /** @class XA_prepare_log_event Similar to Xid_log_event except that - it is specific to XA transaction - it carries out the prepare logics rather than the final committing when @c one_phase member is off. The latter option is only for compatibility with the upstream. From the groupping perspective the event finalizes the current "prepare" group that is started with Gtid_log_event similarly to the regular replicated transaction. */ /** Function serializes XID which is characterized by by four last arguments of the function. Serialized XID is presented in valid hex format and is returned to the caller in a buffer pointed by the first argument. The buffer size provived by the caller must be not less than 8 + 2 * XIDDATASIZE + 4 * sizeof(XID::formatID) + 1, see {MYSQL_,}XID definitions. @param buf pointer to a buffer allocated for storing serialized data @param fmt formatID value @param gln gtrid_length value @param bln bqual_length value @param dat data value @return the value of the buffer pointer */ inline char *serialize_xid(char *buf, long fmt, long gln, long bln, const char *dat) { int i; char *c= buf; /* Build a string consisting of the hex format representation of XID as passed through fmt,gln,bln,dat argument: X'hex11hex12...hex1m',X'hex21hex22...hex2n',11 and store it into buf. */ c[0]= 'X'; c[1]= '\''; c+= 2; for (i= 0; i < gln; i++) { c[0]=_dig_vec_lower[((uchar*) dat)[i] >> 4]; c[1]=_dig_vec_lower[((uchar*) dat)[i] & 0x0f]; c+= 2; } c[0]= '\''; c[1]= ','; c[2]= 'X'; c[3]= '\''; c+= 4; for (; i < gln + bln; i++) { c[0]=_dig_vec_lower[((uchar*) dat)[i] >> 4]; c[1]=_dig_vec_lower[((uchar*) dat)[i] & 0x0f]; c+= 2; } c[0]= '\''; sprintf(c+1, ",%lu", fmt); return buf; } /* The size of the string containing serialized Xid representation is computed as a sum of eight as the number of formatting symbols (X'',X'',) plus 2 x XIDDATASIZE (2 due to hex format), plus space for decimal digits of XID::formatID, plus one for 0x0. */ static const uint ser_buf_size= 8 + 2 * MYSQL_XIDDATASIZE + 4 * sizeof(long) + 1; struct event_mysql_xid_t : MYSQL_XID { char buf[ser_buf_size]; char *serialize() { return serialize_xid(buf, formatID, gtrid_length, bqual_length, data); } }; #ifndef MYSQL_CLIENT struct event_xid_t : XID { char buf[ser_buf_size]; char *serialize(char *buf_arg) { return serialize_xid(buf_arg, formatID, gtrid_length, bqual_length, data); } char *serialize() { return serialize(buf); } }; #endif class XA_prepare_log_event: public Xid_apply_log_event { protected: /* Constant contributor to subheader in write() by members of XID struct. */ static const int xid_subheader_no_data= 12; event_mysql_xid_t m_xid; void *xid; bool one_phase; public: #ifdef MYSQL_SERVER XA_prepare_log_event(THD* thd_arg, XID *xid_arg, bool one_phase_arg): Xid_apply_log_event(thd_arg), xid(xid_arg), one_phase(one_phase_arg) { cache_type= Log_event::EVENT_NO_CACHE; } #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif XA_prepare_log_event(const uchar *buf, const Format_description_log_event *description_event); ~XA_prepare_log_event() {} Log_event_type get_type_code() override { return XA_PREPARE_LOG_EVENT; } bool is_valid() const override { return m_xid.formatID != -1; } int get_data_size() override { return xid_subheader_no_data + m_xid.gtrid_length + m_xid.bqual_length; } #ifdef MYSQL_SERVER bool write() override; #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) char query[sizeof("XA COMMIT ONE PHASE") + 1 + ser_buf_size]; int do_commit() override; const char* get_query() override { sprintf(query, (one_phase ? "XA COMMIT %s ONE PHASE" : "XA PREPARE %s"), m_xid.serialize()); return query; } #endif }; /** @class User_var_log_event Every time a query uses the value of a user variable, a User_var_log_event is written before the Query_log_event, to set the user variable. @section User_var_log_event_binary_format Binary Format */ class User_var_log_event: public Log_event, public Log_event_data_type { public: const char *name; size_t name_len; const char *val; size_t val_len; bool is_null; #ifdef MYSQL_SERVER bool deferred; query_id_t query_id; User_var_log_event(THD* thd_arg, const char *name_arg, size_t name_len_arg, const char *val_arg, size_t val_len_arg, const Log_event_data_type &data_type, bool using_trans, bool direct) :Log_event(thd_arg, 0, using_trans), Log_event_data_type(data_type), name(name_arg), name_len(name_len_arg), val(val_arg), val_len(val_len_arg), deferred(false) { is_null= !val; if (direct) cache_type= Log_event::EVENT_NO_CACHE; } #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif User_var_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~User_var_log_event() = default; Log_event_type get_type_code() override { return USER_VAR_EVENT;} #ifdef MYSQL_SERVER bool write() override; /* Getter and setter for deferred User-event. Returns true if the event is not applied directly and which case the applier adjusts execution path. */ bool is_deferred() { return deferred; } /* In case of the deferred applying the variable instance is flagged and the parsing time query id is stored to be used at applying time. */ void set_deferred(query_id_t qid) { deferred= true; query_id= qid; } #ifdef HAVE_REPLICATION bool is_part_of_group() override { return 1; } #endif #endif bool is_valid() const override { return name != 0; } private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif }; /** @class Stop_log_event @section Stop_log_event_binary_format Binary Format The Post-Header and Body for this event type are empty; it only has the Common-Header. */ class Stop_log_event: public Log_event { public: #ifdef MYSQL_SERVER Stop_log_event() :Log_event() {} #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Stop_log_event(const uchar *buf, const Format_description_log_event *description_event): Log_event(buf, description_event) {} ~Stop_log_event() = default; Log_event_type get_type_code() override { return STOP_EVENT;} bool is_valid() const override { return 1; } private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override { /* Events from ourself should be skipped, but they should not decrease the slave skip counter. */ if (this->server_id == global_system_variables.server_id) return Log_event::EVENT_SKIP_IGNORE; else return Log_event::EVENT_SKIP_NOT; } #endif }; /** @class Rotate_log_event This will be deprecated when we move to using sequence ids. @section Rotate_log_event_binary_format Binary Format The Post-Header has one component:
Post-Header for Rotate_log_event
Name Format Description
position 8 byte integer The position within the binlog to rotate to.
The Body has one component:
Body for Rotate_log_event
Name Format Description
new_log variable length string without trailing zero, extending to the end of the event (determined by the length field of the Common-Header) Name of the binlog to rotate to.
*/ class Rotate_log_event: public Log_event { public: enum { DUP_NAME= 2, // if constructor should dup the string argument RELAY_LOG=4 // rotate event for relay log }; const char *new_log_ident; ulonglong pos; uint ident_len; uint flags; #ifdef MYSQL_SERVER Rotate_log_event(const char* new_log_ident_arg, uint ident_len_arg, ulonglong pos_arg, uint flags); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Rotate_log_event(const uchar *buf, uint event_len, const Format_description_log_event* description_event); ~Rotate_log_event() { if (flags & DUP_NAME) my_free((void*) new_log_ident); } Log_event_type get_type_code() override { return ROTATE_EVENT;} my_off_t get_header_len(my_off_t l __attribute__((unused))) override { return LOG_EVENT_MINIMAL_HEADER_LEN; } int get_data_size() override { return ident_len + ROTATE_HEADER_LEN;} bool is_valid() const override { return new_log_ident != 0; } #ifdef MYSQL_SERVER bool write() override; #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif }; class Binlog_checkpoint_log_event: public Log_event { public: char *binlog_file_name; uint binlog_file_len; #ifdef MYSQL_SERVER Binlog_checkpoint_log_event(const char *binlog_file_name_arg, uint binlog_file_len_arg); #ifdef HAVE_REPLICATION void pack_info(Protocol *protocol) override; #endif #else bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif Binlog_checkpoint_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Binlog_checkpoint_log_event() { my_free(binlog_file_name); } Log_event_type get_type_code() override { return BINLOG_CHECKPOINT_EVENT;} int get_data_size() override { return binlog_file_len + BINLOG_CHECKPOINT_HEADER_LEN;} bool is_valid() const override { return binlog_file_name != 0; } #ifdef MYSQL_SERVER bool write() override; #ifdef HAVE_REPLICATION enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif #endif }; /** @class Gtid_log_event This event is logged as part of every event group to give the global transaction id (GTID) of that group. It replaces the BEGIN query event used in earlier versions to begin most event groups, but is also used for events that used to be stand-alone. @section Gtid_log_event_binary_format Binary Format The binary format for Gtid_log_event has 6 extra reserved bytes to make the length a total of 19 byte (+ 19 bytes of header in common with all events). This is just the minimal size for a BEGIN query event, which makes it easy to replace this event with such BEGIN event to remain compatible with old slave servers.
Post-Header
Name Format Description
seq_no 8 byte unsigned integer increasing id within one server_id. Starts at 1, holes in the sequence may occur
domain_id 4 byte unsigned integer Replication domain id, identifying independent replication streams>
flags 1 byte bitfield Bit 0 set indicates stand-alone event (no terminating COMMIT) Bit 1 set indicates group commit, and that commit id exists Bit 2 set indicates a transactional event group (can be safely rolled back). Bit 3 set indicates that user allowed optimistic parallel apply (the @@SESSION.replicate_allow_parallel value was true at commit). Bit 4 set indicates that this transaction encountered a row (or other) lock wait during execution.
Reserved (no group commit) / commit id (group commit) (see flags bit 1) 6 bytes / 8 bytes Reserved bytes, set to 0. Maybe be used for future expansion (no group commit). OR commit id, same for all GTIDs in the same group commit (see flags bit 1).
The Body of Gtid_log_event is empty. The total event size is 19 bytes + the normal 19 bytes common-header. */ class Gtid_log_event: public Log_event { public: uint64 seq_no; uint64 commit_id; uint32 domain_id; #ifdef MYSQL_SERVER event_xid_t xid; #else event_mysql_xid_t xid; #endif uchar flags2; uint flags_extra; // more flags area placed after the regular flags2's one /* Number of engine participants in transaction minus 1. When zero the event does not contain that information. */ uint8 extra_engines; /* Flags2. */ /* FL_STANDALONE is set when there is no terminating COMMIT event. */ static const uchar FL_STANDALONE= 1; /* FL_GROUP_COMMIT_ID is set when event group is part of a group commit on the master. Groups with same commit_id are part of the same group commit. */ static const uchar FL_GROUP_COMMIT_ID= 2; /* FL_TRANSACTIONAL is set for an event group that can be safely rolled back (no MyISAM, eg.). */ static const uchar FL_TRANSACTIONAL= 4; /* FL_ALLOW_PARALLEL reflects the (negation of the) value of @@SESSION.skip_parallel_replication at the time of commit. */ static const uchar FL_ALLOW_PARALLEL= 8; /* FL_WAITED is set if a row lock wait (or other wait) is detected during the execution of the transaction. */ static const uchar FL_WAITED= 16; /* FL_DDL is set for event group containing DDL. */ static const uchar FL_DDL= 32; /* FL_PREPARED_XA is set for XA transaction. */ static const uchar FL_PREPARED_XA= 64; /* FL_"COMMITTED or ROLLED-BACK"_XA is set for XA transaction. */ static const uchar FL_COMPLETED_XA= 128; /* Flags_extra. */ /* FL_EXTRA_MULTI_ENGINE is set for event group comprising a transaction involving multiple storage engines. No flag and extra data are added to the event when the transaction involves only one engine. */ static const uchar FL_EXTRA_MULTI_ENGINE= 1; #ifdef MYSQL_SERVER Gtid_log_event(THD *thd_arg, uint64 seq_no, uint32 domain_id, bool standalone, uint16 flags, bool is_transactional, uint64 commit_id, bool has_xid= false, bool is_ro_1pc= false); #ifdef HAVE_REPLICATION void pack_info(Protocol *protocol) override; int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif #else bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif Gtid_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Gtid_log_event() = default; Log_event_type get_type_code() override { return GTID_EVENT; } enum_logged_status logged_status() override { return LOGGED_NO_DATA; } int get_data_size() override { return GTID_HEADER_LEN + ((flags2 & FL_GROUP_COMMIT_ID) ? 2 : 0); } bool is_valid() const override { /* seq_no is set to 0 if the structure of a serialized GTID event does not align with that as indicated by flags and extra_flags. */ return seq_no != 0; } #ifdef MYSQL_SERVER bool write() override; static int make_compatible_event(String *packet, bool *need_dummy_event, ulong ev_offset, enum enum_binlog_checksum_alg checksum_alg); static bool peek(const uchar *event_start, size_t event_len, enum enum_binlog_checksum_alg checksum_alg, uint32 *domain_id, uint32 *server_id, uint64 *seq_no, uchar *flags2, const Format_description_log_event *fdev); #endif }; /** @class Gtid_list_log_event This event is logged at the start of every binlog file to record the current replication state: the last global transaction id (GTID) applied on the server within each replication domain. It consists of a list of GTIDs, one for each replication domain ever seen on the server. @section Gtid_list_log_event_binary_format Binary Format
Post-Header
Name Format Description
count 4 byte unsigned integer The lower 28 bits are the number of GTIDs. The upper 4 bits are flags bits.
Body
Name Format Description
domain_id 4 byte unsigned integer Replication domain id of one GTID
server_id 4 byte unsigned integer Server id of one GTID
seq_no 8 byte unsigned integer sequence number of one GTID
The three elements in the body repeat COUNT times to form the GTID list. At the time of writing, only two flag bit are in use. Bit 28 of `count' is used for flag FLAG_UNTIL_REACHED, which is sent in a Gtid_list event from the master to the slave to indicate that the START SLAVE UNTIL master_gtid_pos=xxx condition has been reached. (This flag is only sent in "fake" events generated on the fly, it is not written into the binlog). */ class Gtid_list_log_event: public Log_event { public: uint32 count; uint32 gl_flags; struct rpl_gtid *list; uint64 *sub_id_list; static const uint element_size= 4+4+8; /* Upper bits stored in 'count'. See comment above */ enum gtid_flags { FLAG_UNTIL_REACHED= (1<<28), FLAG_IGN_GTIDS= (1<<29), }; #ifdef MYSQL_SERVER Gtid_list_log_event(rpl_binlog_state *gtid_set, uint32 gl_flags); Gtid_list_log_event(slave_connection_state *gtid_set, uint32 gl_flags); #ifdef HAVE_REPLICATION void pack_info(Protocol *protocol) override; #endif #else bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif Gtid_list_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Gtid_list_log_event() { my_free(list); my_free(sub_id_list); } Log_event_type get_type_code() override { return GTID_LIST_EVENT; } int get_data_size() override { /* Replacing with dummy event, needed for older slaves, requires a minimum of 6 bytes in the body. */ return (count==0 ? GTID_LIST_HEADER_LEN+2 : GTID_LIST_HEADER_LEN+count*element_size); } bool is_valid() const override { return list != NULL; } #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) bool to_packet(String *packet); bool write() override; int do_apply_event(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif static bool peek(const char *event_start, size_t event_len, enum enum_binlog_checksum_alg checksum_alg, rpl_gtid **out_gtid_list, uint32 *out_list_len, const Format_description_log_event *fdev); }; /* the classes below are for the new LOAD DATA INFILE logging */ /** @class Create_file_log_event @section Create_file_log_event_binary_format Binary Format */ class Create_file_log_event: public Load_log_event { protected: /* Pretend we are Load event, so we can write out just our Load part - used on the slave when writing event out to SQL_LOAD-*.info file */ bool fake_base; public: uchar *block; const uchar *event_buf; uint block_len; uint file_id; bool inited_from_old; #ifdef MYSQL_SERVER Create_file_log_event(THD* thd, sql_exchange* ex, const char* db_arg, const char* table_name_arg, List& fields_arg, bool is_concurrent_arg, enum enum_duplicates handle_dup, bool ignore, uchar* block_arg, uint block_len_arg, bool using_trans); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, bool enable_local); #endif Create_file_log_event(const uchar *buf, uint event_len, const Format_description_log_event* description_event); ~Create_file_log_event() { my_free((void*) event_buf); } Log_event_type get_type_code() override { return fake_base ? Load_log_event::get_type_code() : CREATE_FILE_EVENT; } int get_data_size() override { return (fake_base ? Load_log_event::get_data_size() : Load_log_event::get_data_size() + 4 + 1 + block_len); } bool is_valid() const override { return inited_from_old || block != 0; } #ifdef MYSQL_SERVER bool write_data_header() override; bool write_data_body() override; /* Cut out Create_file extensions and write it as Load event - used on the slave */ bool write_base(); #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; #endif }; /** @class Append_block_log_event @section Append_block_log_event_binary_format Binary Format */ class Append_block_log_event: public Log_event { public: uchar* block; uint block_len; uint file_id; /* 'db' is filled when the event is created in mysql_load() (the event needs to have a 'db' member to be well filtered by binlog-*-db rules). 'db' is not written to the binlog (it's not used by Append_block_log_event::write()), so it can't be read in the Append_block_log_event(const uchar *buf, int event_len) constructor. In other words, 'db' is used only for filtering by binlog-*-db rules. Create_file_log_event is different: it's 'db' (which is inherited from Load_log_event) is written to the binlog and can be re-read. */ const char* db; #ifdef MYSQL_SERVER Append_block_log_event(THD* thd, const char* db_arg, uchar* block_arg, uint block_len_arg, bool using_trans); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; virtual int get_create_or_append() const; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Append_block_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Append_block_log_event() = default; Log_event_type get_type_code() override { return APPEND_BLOCK_EVENT;} int get_data_size() override { return block_len + APPEND_BLOCK_HEADER_LEN ;} bool is_valid() const override { return block != 0; } #ifdef MYSQL_SERVER bool write() override; const char* get_db() override { return db; } #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; #endif }; /** @class Delete_file_log_event @section Delete_file_log_event_binary_format Binary Format */ class Delete_file_log_event: public Log_event { public: uint file_id; const char* db; /* see comment in Append_block_log_event */ #ifdef MYSQL_SERVER Delete_file_log_event(THD* thd, const char* db_arg, bool using_trans); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, bool enable_local); #endif Delete_file_log_event(const uchar *buf, uint event_len, const Format_description_log_event* description_event); ~Delete_file_log_event() = default; Log_event_type get_type_code() override { return DELETE_FILE_EVENT;} int get_data_size() override { return DELETE_FILE_HEADER_LEN ;} bool is_valid() const override { return file_id != 0; } #ifdef MYSQL_SERVER bool write() override; const char* get_db() override { return db; } #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; #endif }; /** @class Execute_load_log_event @section Delete_file_log_event_binary_format Binary Format */ class Execute_load_log_event: public Log_event { public: uint file_id; const char* db; /* see comment in Append_block_log_event */ #ifdef MYSQL_SERVER Execute_load_log_event(THD* thd, const char* db_arg, bool using_trans); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; #endif Execute_load_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Execute_load_log_event() = default; Log_event_type get_type_code() override { return EXEC_LOAD_EVENT;} int get_data_size() override { return EXEC_LOAD_HEADER_LEN ;} bool is_valid() const override { return file_id != 0; } #ifdef MYSQL_SERVER bool write() override; const char* get_db() override { return db; } #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; #endif }; /** @class Begin_load_query_log_event Event for the first block of file to be loaded, its only difference from Append_block event is that this event creates or truncates existing file before writing data. @section Begin_load_query_log_event_binary_format Binary Format */ class Begin_load_query_log_event: public Append_block_log_event { public: #ifdef MYSQL_SERVER Begin_load_query_log_event(THD* thd_arg, const char *db_arg, uchar* block_arg, uint block_len_arg, bool using_trans); #ifdef HAVE_REPLICATION Begin_load_query_log_event(THD* thd); int get_create_or_append() const override; #endif /* HAVE_REPLICATION */ #endif Begin_load_query_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Begin_load_query_log_event() = default; Log_event_type get_type_code() override { return BEGIN_LOAD_QUERY_EVENT; } private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif }; /* Elements of this enum describe how LOAD DATA handles duplicates. */ enum enum_load_dup_handling { LOAD_DUP_ERROR= 0, LOAD_DUP_IGNORE, LOAD_DUP_REPLACE }; /** @class Execute_load_query_log_event Event responsible for LOAD DATA execution, it similar to Query_log_event but before executing the query it substitutes original filename in LOAD DATA query with name of temporary file. @section Execute_load_query_log_event_binary_format Binary Format */ class Execute_load_query_log_event: public Query_log_event { public: uint file_id; // file_id of temporary file uint fn_pos_start; // pointer to the part of the query that should // be substituted uint fn_pos_end; // pointer to the end of this part of query /* We have to store type of duplicate handling explicitly, because for LOAD DATA it also depends on LOCAL option. And this part of query will be rewritten during replication so this information may be lost... */ enum_load_dup_handling dup_handling; #ifdef MYSQL_SERVER Execute_load_query_log_event(THD* thd, const char* query_arg, ulong query_length, uint fn_pos_start_arg, uint fn_pos_end_arg, enum_load_dup_handling dup_handling_arg, bool using_trans, bool direct, bool suppress_use, int errcode); #ifdef HAVE_REPLICATION void pack_info(Protocol* protocol) override; #endif /* HAVE_REPLICATION */ #else bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; /* Prints the query as LOAD DATA LOCAL and with rewritten filename */ bool print(FILE* file, PRINT_EVENT_INFO* print_event_info, const char *local_fname); #endif Execute_load_query_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); ~Execute_load_query_log_event() = default; Log_event_type get_type_code() override { return EXECUTE_LOAD_QUERY_EVENT; } bool is_valid() const override { return Query_log_event::is_valid() && file_id != 0; } ulong get_post_header_size_for_derived() override; #ifdef MYSQL_SERVER bool write_post_header_for_derived() override; #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; #endif }; #ifdef MYSQL_CLIENT /** @class Unknown_log_event @section Unknown_log_event_binary_format Binary Format */ class Unknown_log_event: public Log_event { public: enum { UNKNOWN, ENCRYPTED } what; /* Even if this is an unknown event, we still pass description_event to Log_event's ctor, this way we can extract maximum information from the event's header (the unique ID for example). */ Unknown_log_event(const uchar *buf, const Format_description_log_event *description_event): Log_event(buf, description_event), what(UNKNOWN) {} /* constructor for hopelessly corrupted events */ Unknown_log_event(): Log_event(), what(ENCRYPTED) {} ~Unknown_log_event() = default; bool print(FILE* file, PRINT_EVENT_INFO* print_event_info) override; Log_event_type get_type_code() override { return UNKNOWN_EVENT;} bool is_valid() const override { return 1; } }; #endif char *str_to_hex(char *to, const char *from, size_t len); /** @class Annotate_rows_log_event In row-based mode, if binlog_annotate_row_events = ON, each group of Table_map_log_events is preceded by an Annotate_rows_log_event which contains the query which caused the subsequent rows operations. The Annotate_rows_log_event has no post-header and its body contains the corresponding query (without trailing zero). Note. The query length is to be calculated as a difference between the whole event length and the common header length. */ class Annotate_rows_log_event: public Log_event { public: #ifndef MYSQL_CLIENT Annotate_rows_log_event(THD*, bool using_trans, bool direct); #endif Annotate_rows_log_event(const uchar *buf, uint event_len, const Format_description_log_event*); ~Annotate_rows_log_event(); int get_data_size() override; Log_event_type get_type_code() override; enum_logged_status logged_status() override { return LOGGED_NO_DATA; } bool is_valid() const override; #ifndef MYSQL_CLIENT #ifdef HAVE_REPLICATION bool is_part_of_group() override { return 1; } #endif bool write_data_header() override; bool write_data_body() override; #endif #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) void pack_info(Protocol*) override; #endif #ifdef MYSQL_CLIENT bool print(FILE*, PRINT_EVENT_INFO*) override; #endif #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION) private: int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info*) override; #endif private: char *m_query_txt; uint m_query_len; char *m_save_thd_query_txt; uint m_save_thd_query_len; bool m_saved_thd_query; bool m_used_query_txt; }; /** @class Table_map_log_event In row-based mode, every row operation event is preceded by a Table_map_log_event which maps a table definition to a number. The table definition consists of database name, table name, and column definitions. @section Table_map_log_event_binary_format Binary Format The Post-Header has the following components:
Post-Header for Table_map_log_event
Name Format Description
table_id 6 bytes unsigned integer The number that identifies the table.
flags 2 byte bitfield Reserved for future use; currently always 0.
The Body has the following components:
Body for Table_map_log_event
Name Format Description
database_name one byte string length, followed by null-terminated string The name of the database in which the table resides. The name is represented as a one byte unsigned integer representing the number of bytes in the name, followed by length bytes containing the database name, followed by a terminating 0 byte. (Note the redundancy in the representation of the length.)
table_name one byte string length, followed by null-terminated string The name of the table, encoded the same way as the database name above.
column_count @ref packed_integer "Packed Integer" The number of columns in the table, represented as a packed variable-length integer.
column_type List of column_count 1 byte enumeration values The type of each column in the table, listed from left to right. Each byte is mapped to a column type according to the enumeration type enum_field_types defined in mysql_com.h. The mapping of types to numbers is listed in the table @ref Table_table_map_log_event_column_types "below" (along with description of the associated metadata field).
metadata_length @ref packed_integer "Packed Integer" The length of the following metadata block
metadata list of metadata for each column For each column from left to right, a chunk of data who's length and semantics depends on the type of the column. The length and semantics for the metadata for each column are listed in the table @ref Table_table_map_log_event_column_types "below".
null_bits column_count bits, rounded up to nearest byte For each column, a bit indicating whether data in the column can be NULL or not. The number of bytes needed for this is int((column_count+7)/8). The flag for the first column from the left is in the least-significant bit of the first byte, the second is in the second least significant bit of the first byte, the ninth is in the least significant bit of the second byte, and so on.
optional metadata fields optional metadata fields are stored in Type, Length, Value(TLV) format. Type takes 1 byte. Length is a packed integer value. Values takes Length bytes. There are some optional metadata defined. They are listed in the table @ref Table_table_map_event_optional_metadata. Optional metadata fields follow null_bits. Whether binlogging an optional metadata is decided by the server. The order is not defined, so they can be binlogged in any order.
The table below lists all column types, along with the numerical identifier for it and the size and interpretation of meta-data used to describe the type. @anchor Table_table_map_log_event_column_types
Table_map_log_event column types: numerical identifier and metadata
Name Identifier Size of metadata in bytes Description of metadata
MYSQL_TYPE_DECIMAL0 0 No column metadata.
MYSQL_TYPE_TINY1 0 No column metadata.
MYSQL_TYPE_SHORT2 0 No column metadata.
MYSQL_TYPE_LONG3 0 No column metadata.
MYSQL_TYPE_FLOAT4 1 byte 1 byte unsigned integer, representing the "pack_length", which is equal to sizeof(float) on the server from which the event originates.
MYSQL_TYPE_DOUBLE5 1 byte 1 byte unsigned integer, representing the "pack_length", which is equal to sizeof(double) on the server from which the event originates.
MYSQL_TYPE_NULL6 0 No column metadata.
MYSQL_TYPE_TIMESTAMP7 0 No column metadata.
MYSQL_TYPE_LONGLONG8 0 No column metadata.
MYSQL_TYPE_INT249 0 No column metadata.
MYSQL_TYPE_DATE10 0 No column metadata.
MYSQL_TYPE_TIME11 0 No column metadata.
MYSQL_TYPE_DATETIME12 0 No column metadata.
MYSQL_TYPE_YEAR13 0 No column metadata.
MYSQL_TYPE_NEWDATE14 This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_VARCHAR15 2 bytes 2 byte unsigned integer representing the maximum length of the string.
MYSQL_TYPE_BIT16 2 bytes A 1 byte unsigned int representing the length in bits of the bitfield (0 to 64), followed by a 1 byte unsigned int representing the number of bytes occupied by the bitfield. The number of bytes is either int((length+7)/8) or int(length/8).
MYSQL_TYPE_NEWDECIMAL246 2 bytes A 1 byte unsigned int representing the precision, followed by a 1 byte unsigned int representing the number of decimals.
MYSQL_TYPE_ENUM247 This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_SET248 This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_TINY_BLOB249 This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_MEDIUM_BLOB250 This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_LONG_BLOB251 This enumeration value is only used internally and cannot exist in a binlog.
MYSQL_TYPE_BLOB252 1 byte The pack length, i.e., the number of bytes needed to represent the length of the blob: 1, 2, 3, or 4.
MYSQL_TYPE_VAR_STRING253 2 bytes This is used to store both strings and enumeration values. The first byte is a enumeration value storing the real type, which may be either MYSQL_TYPE_VAR_STRING or MYSQL_TYPE_ENUM. The second byte is a 1 byte unsigned integer representing the field size, i.e., the number of bytes needed to store the length of the string.
MYSQL_TYPE_STRING254 2 bytes The first byte is always MYSQL_TYPE_VAR_STRING (i.e., 253). The second byte is the field size, i.e., the number of bytes in the representation of size of the string: 3 or 4.
MYSQL_TYPE_GEOMETRY255 1 byte The pack length, i.e., the number of bytes needed to represent the length of the geometry: 1, 2, 3, or 4.
The table below lists all optional metadata types, along with the numerical identifier for it and the size and interpretation of meta-data used to describe the type. @anchor Table_table_map_event_optional_metadata
Table_map_event optional metadata types: numerical identifier and metadata. Optional metadata fields are stored in TLV fields. Format of values are described in this table.
Type Description Format
SIGNEDNESS signedness of numeric colums. This is included for all values of binlog_row_metadata. For each numeric column, a bit indicates whether the numeric colunm has unsigned flag. 1 means it is unsigned. The number of bytes needed for this is int((column_count + 7) / 8). The order is the same as the order of column_type field.
DEFAULT_CHARSET Charsets of character columns. It has a default charset for the case that most of character columns have same charset and the most used charset is binlogged as default charset.Collation numbers are binlogged for identifying charsets. They are stored in packed length format. Either DEFAULT_CHARSET or COLUMN_CHARSET is included for all values of binlog_row_metadata. Default charset's collation is logged first. The charsets which are not same to default charset are logged following default charset. They are logged as column index and charset collation number pair sequence. The column index is counted only in all character columns. The order is same to the order of column_type field.
COLUMN_CHARSET Charsets of character columns. For the case that most of columns have different charsets, this field is logged. It is never logged with DEFAULT_CHARSET together. Either DEFAULT_CHARSET or COLUMN_CHARSET is included for all values of binlog_row_metadata. It is a collation number sequence for all character columns.
COLUMN_NAME Names of columns. This is only included if binlog_row_metadata=FULL. A sequence of column names. For each column name, 1 byte for the string length in bytes is followed by a string without null terminator.
SET_STR_VALUE The string values of SET columns. This is only included if binlog_row_metadata=FULL. For each SET column, a pack_length representing the value count is followed by a sequence of length and string pairs. length is the byte count in pack_length format. The string has no null terminator.
ENUM_STR_VALUE The string values is ENUM columns. This is only included if binlog_row_metadata=FULL. The format is the same as SET_STR_VALUE.
GEOMETRY_TYPE The real type of geometry columns. This is only included if binlog_row_metadata=FULL. A sequence of real type of geometry columns are stored in pack_length format.
SIMPLE_PRIMARY_KEY The primary key without any prefix. This is only included if binlog_row_metadata=FULL and there is a primary key where every key part covers an entire column. A sequence of column indexes. The indexes are stored in pack_length format.
PRIMARY_KEY_WITH_PREFIX The primary key with some prefix. It doesn't appear together with SIMPLE_PRIMARY_KEY. This is only included if binlog_row_metadata=FULL and there is a primary key where some key part covers a prefix of the column. A sequence of column index and prefix length pairs. Both column index and prefix length are in pack_length format. Prefix length 0 means that the whole column value is used.
ENUM_AND_SET_DEFAULT_CHARSET Charsets of ENUM and SET columns. It has the same layout as DEFAULT_CHARSET. If there are SET or ENUM columns and binlog_row_metadata=FULL, exactly one of ENUM_AND_SET_DEFAULT_CHARSET and ENUM_AND_SET_COLUMN_CHARSET appears (the encoder chooses the representation that uses the least amount of space). Otherwise, none of them appears. The same format as for DEFAULT_CHARSET, except it counts ENUM and SET columns rather than character columns.
ENUM_AND_SET_COLUMN_CHARSET Charsets of ENUM and SET columns. It has the same layout as COLUMN_CHARSET. If there are SET or ENUM columns and binlog_row_metadata=FULL, exactly one of ENUM_AND_SET_DEFAULT_CHARSET and ENUM_AND_SET_COLUMN_CHARSET appears (the encoder chooses the representation that uses the least amount of space). Otherwise, none of them appears. The same format as for COLUMN_CHARSET, except it counts ENUM and SET columns rather than character columns.
*/ class Table_map_log_event : public Log_event { public: /* Constants */ enum { TYPE_CODE = TABLE_MAP_EVENT }; /** Enumeration of the errors that can be returned. */ enum enum_error { ERR_OPEN_FAILURE = -1, /**< Failure to open table */ ERR_OK = 0, /**< No error */ ERR_TABLE_LIMIT_EXCEEDED = 1, /**< No more room for tables */ ERR_OUT_OF_MEM = 2, /**< Out of memory */ ERR_BAD_TABLE_DEF = 3, /**< Table definition does not match */ ERR_RBR_TO_SBR = 4 /**< daisy-chanining RBR to SBR not allowed */ }; enum enum_flag { /* Nothing here right now, but the flags support is there in preparation for changes that are coming. Need to add a constant to make it compile under HP-UX: aCC does not like empty enumerations. */ ENUM_FLAG_COUNT }; typedef uint16 flag_set; /** DEFAULT_CHARSET and COLUMN_CHARSET don't appear together, and ENUM_AND_SET_DEFAULT_CHARSET and ENUM_AND_SET_COLUMN_CHARSET don't appear together. They are just alternative ways to pack character set information. When binlogging, it logs character sets in the way that occupies least storage. SIMPLE_PRIMARY_KEY and PRIMARY_KEY_WITH_PREFIX don't appear together. SIMPLE_PRIMARY_KEY is for the primary keys which only use whole values of pk columns. PRIMARY_KEY_WITH_PREFIX is for the primary keys which just use part value of pk columns. */ enum Optional_metadata_field_type { SIGNEDNESS = 1, // UNSIGNED flag of numeric columns DEFAULT_CHARSET, /* Character set of string columns, optimized to minimize space when many columns have the same charset. */ COLUMN_CHARSET, /* Character set of string columns, optimized to minimize space when columns have many different charsets. */ COLUMN_NAME, SET_STR_VALUE, // String value of SET columns ENUM_STR_VALUE, // String value of ENUM columns GEOMETRY_TYPE, // Real type of geometry columns SIMPLE_PRIMARY_KEY, // Primary key without prefix PRIMARY_KEY_WITH_PREFIX, // Primary key with prefix ENUM_AND_SET_DEFAULT_CHARSET, /* Character set of enum and set columns, optimized to minimize space when many columns have the same charset. */ ENUM_AND_SET_COLUMN_CHARSET, /* Character set of enum and set columns, optimized to minimize space when many columns have the same charset. */ }; /** Metadata_fields organizes m_optional_metadata into a structured format which is easy to access. */ // Values for binlog_row_metadata sysvar enum enum_binlog_row_metadata { BINLOG_ROW_METADATA_NO_LOG= 0, BINLOG_ROW_METADATA_MINIMAL= 1, BINLOG_ROW_METADATA_FULL= 2 }; struct Optional_metadata_fields { typedef std::pair uint_pair; typedef std::vector str_vector; struct Default_charset { Default_charset() : default_charset(0) {} bool empty() const { return default_charset == 0; } // Default charset for the columns which are not in charset_pairs. unsigned int default_charset; /* The uint_pair means . */ std::vector charset_pairs; }; // Contents of DEFAULT_CHARSET field is converted into Default_charset. Default_charset m_default_charset; // Contents of ENUM_AND_SET_DEFAULT_CHARSET are converted into // Default_charset. Default_charset m_enum_and_set_default_charset; std::vector m_signedness; // Character set number of every string column std::vector m_column_charset; // Character set number of every ENUM or SET column. std::vector m_enum_and_set_column_charset; std::vector m_column_name; // each str_vector stores values of one enum/set column std::vector m_enum_str_value; std::vector m_set_str_value; std::vector m_geometry_type; /* The uint_pair means . Prefix length is 0 if whole column value is used. */ std::vector m_primary_key; /* It parses m_optional_metadata and populates into above variables. @param[in] optional_metadata points to the begin of optional metadata fields in table_map_event. @param[in] optional_metadata_len length of optional_metadata field. */ Optional_metadata_fields(unsigned char* optional_metadata, unsigned int optional_metadata_len); }; /** Print column metadata. Its format looks like: # Columns(colume_name type, colume_name type, ...) if colume_name field is not logged into table_map_log_event, then only type is printed. @@param[out] file the place where colume metadata is printed @@param[in] The metadata extracted from optional metadata fields */ void print_columns(IO_CACHE *file, const Optional_metadata_fields &fields); /** Print primary information. Its format looks like: # Primary Key(colume_name, column_name(prifix), ...) if colume_name field is not logged into table_map_log_event, then colume index is printed. @@param[out] file the place where primary key is printed @@param[in] The metadata extracted from optional metadata fields */ void print_primary_key(IO_CACHE *file, const Optional_metadata_fields &fields); /* Special constants representing sets of flags */ enum { TM_NO_FLAGS = 0U, TM_BIT_LEN_EXACT_F = (1U << 0), // MariaDB flags (we starts from the other end) TM_BIT_HAS_TRIGGERS_F= (1U << 14) }; flag_set get_flags(flag_set flag) const { return m_flags & flag; } #ifdef MYSQL_SERVER Table_map_log_event(THD *thd, TABLE *tbl, ulonglong tid, bool is_transactional); #endif #ifdef HAVE_REPLICATION Table_map_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif ~Table_map_log_event(); #ifdef MYSQL_CLIENT table_def *create_table_def() { return new table_def(m_coltype, m_colcnt, m_field_metadata, m_field_metadata_size, m_null_bits, m_flags); } int rewrite_db(const char* new_name, size_t new_name_len, const Format_description_log_event*); #endif ulonglong get_table_id() const { return m_table_id; } const char *get_table_name() const { return m_tblnam; } const char *get_db_name() const { return m_dbnam; } Log_event_type get_type_code() override { return TABLE_MAP_EVENT; } enum_logged_status logged_status() override { return LOGGED_TABLE_MAP; } bool is_valid() const override { return m_memory != NULL; /* we check malloc */ } int get_data_size() override { return (uint) m_data_size; } #ifdef MYSQL_SERVER #ifdef HAVE_REPLICATION bool is_part_of_group() override { return 1; } #endif virtual int save_field_metadata(); bool write_data_header() override; bool write_data_body() override; const char *get_db() override { return m_dbnam; } #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) void pack_info(Protocol *protocol) override; #endif #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; #endif #ifdef MYSQL_SERVER TABLE *m_table; Binlog_type_info *binlog_type_info_array; // Metadata fields buffer StringBuffer<1024> m_metadata_buf; /** Capture the optional metadata fields which should be logged into table_map_log_event and serialize them into m_metadata_buf. */ void init_metadata_fields(); bool init_signedness_field(); /** Capture and serialize character sets. Character sets for character columns (TEXT etc) and character sets for ENUM and SET columns are stored in different metadata fields. The reason is that TEXT character sets are included even when binlog_row_metadata=MINIMAL, whereas ENUM and SET character sets are included only when binlog_row_metadata=FULL. @param include_type Predicate to determine if a given Field object is to be included in the metadata field. @param default_charset_type Type code when storing in "default charset" format. (See comment above Table_maps_log_event in libbinlogevents/include/rows_event.h) @param column_charset_type Type code when storing in "column charset" format. (See comment above Table_maps_log_event in libbinlogevents/include/rows_event.h) */ bool init_charset_field(bool(* include_type)(Binlog_type_info *, Field *), Optional_metadata_field_type default_charset_type, Optional_metadata_field_type column_charset_type); bool init_column_name_field(); bool init_set_str_value_field(); bool init_enum_str_value_field(); bool init_geometry_type_field(); bool init_primary_key_field(); #endif #ifdef MYSQL_CLIENT class Charset_iterator; class Default_charset_iterator; class Column_charset_iterator; #endif char const *m_dbnam; size_t m_dblen; char const *m_tblnam; size_t m_tbllen; ulong m_colcnt; uchar *m_coltype; uchar *m_memory; ulonglong m_table_id; flag_set m_flags; size_t m_data_size; uchar *m_field_metadata; // buffer for field metadata /* The size of field metadata buffer set by calling save_field_metadata() */ ulong m_field_metadata_size; uchar *m_null_bits; uchar *m_meta_memory; unsigned int m_optional_metadata_len; unsigned char *m_optional_metadata; }; /** @class Rows_log_event Common base class for all row-containing log events. RESPONSIBILITIES Encode the common parts of all events containing rows, which are: - Write data header and data body to an IO_CACHE. - Provide an interface for adding an individual row to the event. @section Rows_log_event_binary_format Binary Format */ class Rows_log_event : public Log_event { public: /** Enumeration of the errors that can be returned. */ enum enum_error { ERR_OPEN_FAILURE = -1, /**< Failure to open table */ ERR_OK = 0, /**< No error */ ERR_TABLE_LIMIT_EXCEEDED = 1, /**< No more room for tables */ ERR_OUT_OF_MEM = 2, /**< Out of memory */ ERR_BAD_TABLE_DEF = 3, /**< Table definition does not match */ ERR_RBR_TO_SBR = 4 /**< daisy-chanining RBR to SBR not allowed */ }; /* These definitions allow you to combine the flags into an appropriate flag set using the normal bitwise operators. The implicit conversion from an enum-constant to an integer is accepted by the compiler, which is then used to set the real set of flags. */ enum enum_flag { /* Last event of a statement */ STMT_END_F = (1U << 0), /* Value of the OPTION_NO_FOREIGN_KEY_CHECKS flag in thd->options */ NO_FOREIGN_KEY_CHECKS_F = (1U << 1), /* Value of the OPTION_RELAXED_UNIQUE_CHECKS flag in thd->options */ RELAXED_UNIQUE_CHECKS_F = (1U << 2), /** Indicates that rows in this event are complete, that is contain values for all columns of the table. */ COMPLETE_ROWS_F = (1U << 3), /* Value of the OPTION_NO_CHECK_CONSTRAINT_CHECKS flag in thd->options */ NO_CHECK_CONSTRAINT_CHECKS_F = (1U << 7) }; typedef uint16 flag_set; /* Special constants representing sets of flags */ enum { RLE_NO_FLAGS = 0U }; virtual ~Rows_log_event(); void set_flags(flag_set flags_arg) { m_flags |= flags_arg; } void clear_flags(flag_set flags_arg) { m_flags &= ~flags_arg; } flag_set get_flags(flag_set flags_arg) const { return m_flags & flags_arg; } void update_flags() { int2store(temp_buf + m_flags_pos, m_flags); } Log_event_type get_type_code() override { return m_type; } /* Specific type (_V1 etc) */ enum_logged_status logged_status() override { return LOGGED_ROW_EVENT; } virtual Log_event_type get_general_type_code() = 0; /* General rows op type, no version */ #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) void pack_info(Protocol *protocol) override; #endif #ifdef MYSQL_CLIENT /* not for direct call, each derived has its own ::print() */ bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override= 0; void change_to_flashback_event(PRINT_EVENT_INFO *print_event_info, uchar *rows_buff, Log_event_type ev_type); bool print_verbose(IO_CACHE *file, PRINT_EVENT_INFO *print_event_info); size_t print_verbose_one_row(IO_CACHE *file, table_def *td, PRINT_EVENT_INFO *print_event_info, MY_BITMAP *cols_bitmap, const uchar *ptr, const uchar *prefix, const my_bool no_fill_output= 0); // if no_fill_output=1, then print result is unnecessary size_t calc_row_event_length(table_def *td, PRINT_EVENT_INFO *print_event_info, MY_BITMAP *cols_bitmap, const uchar *value); void count_row_events(PRINT_EVENT_INFO *print_event_info); #endif #ifdef MYSQL_SERVER int add_row_data(uchar *data, size_t length) { return do_add_row_data(data,length); } #endif /* Member functions to implement superclass interface */ int get_data_size() override; MY_BITMAP const *get_cols() const { return &m_cols; } MY_BITMAP const *get_cols_ai() const { return &m_cols_ai; } size_t get_width() const { return m_width; } ulonglong get_table_id() const { return m_table_id; } #if defined(MYSQL_SERVER) /* This member function compares the table's read/write_set with this event's m_cols and m_cols_ai. Comparison takes into account what type of rows event is this: Delete, Write or Update, therefore it uses the correct m_cols[_ai] according to the event type code. Note that this member function should only be called for the following events: - Delete_rows_log_event - Write_rows_log_event - Update_rows_log_event @param[IN] table The table to compare this events bitmaps against. @return TRUE if sets match, FALSE otherwise. (following bitmap_cmp return logic). */ bool read_write_bitmaps_cmp(TABLE *table) { bool res= FALSE; switch (get_general_type_code()) { case DELETE_ROWS_EVENT: res= bitmap_cmp(get_cols(), table->read_set); break; case UPDATE_ROWS_EVENT: res= (bitmap_cmp(get_cols(), table->read_set) && bitmap_cmp(get_cols_ai(), table->rpl_write_set)); break; case WRITE_ROWS_EVENT: res= bitmap_cmp(get_cols(), table->rpl_write_set); break; default: /* We should just compare bitmaps for Delete, Write or Update rows events. */ DBUG_ASSERT(0); } return res; } #endif #ifdef MYSQL_SERVER bool write_data_header() override; bool write_data_body() override; virtual bool write_compressed(); const char *get_db() override { return m_table->s->db.str; } #ifdef HAVE_REPLICATION bool is_part_of_group() override { return get_flags(STMT_END_F) != 0; } #endif #endif /* Check that malloc() succeeded in allocating memory for the rows buffer and the COLS vector. Checking that an Update_rows_log_event is valid is done in the Update_rows_log_event::is_valid() function. */ bool is_valid() const override { return m_cols.bitmap; } uint m_row_count; /* The number of rows added to the event */ const uchar* get_extra_row_data() const { return m_extra_row_data; } #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) virtual uint8 get_trg_event_map()= 0; inline bool do_invoke_trigger() { return (slave_run_triggers_for_rbr && !master_had_triggers) || slave_run_triggers_for_rbr == SLAVE_RUN_TRIGGERS_FOR_RBR_ENFORCE; } #endif protected: /* The constructors are protected since you're supposed to inherit this class, not create instances of this class. */ #ifdef MYSQL_SERVER Rows_log_event(THD*, TABLE*, ulonglong table_id, MY_BITMAP const *cols, bool is_transactional, Log_event_type event_type); #endif Rows_log_event(const uchar *row_data, uint event_len, const Format_description_log_event *description_event); void uncompress_buf(); #ifdef MYSQL_CLIENT bool print_helper(FILE *, PRINT_EVENT_INFO *, char const *const name); #endif #ifdef MYSQL_SERVER virtual int do_add_row_data(uchar *data, size_t length); #endif #ifdef MYSQL_SERVER TABLE *m_table; /* The table the rows belong to */ #endif ulonglong m_table_id; /* Table ID */ MY_BITMAP m_cols; /* Bitmap denoting columns available */ ulong m_width; /* The width of the columns bitmap */ /* Bitmap for columns available in the after image, if present. These fields are only available for Update_rows events. Observe that the width of both the before image COLS vector and the after image COLS vector is the same: the number of columns of the table on the master. */ MY_BITMAP m_cols_ai; ulong m_master_reclength; /* Length of record on master side */ /* Bit buffers in the same memory as the class */ my_bitmap_map m_bitbuf[128/(sizeof(my_bitmap_map)*8)]; my_bitmap_map m_bitbuf_ai[128/(sizeof(my_bitmap_map)*8)]; uchar *m_rows_buf; /* The rows in packed format */ uchar *m_rows_cur; /* One-after the end of the data */ uchar *m_rows_end; /* One-after the end of the allocated space */ size_t m_rows_before_size; /* The length before m_rows_buf */ size_t m_flags_pos; /* The position of the m_flags */ flag_set m_flags; /* Flags for row-level events */ Log_event_type m_type; /* Actual event type */ uchar *m_extra_row_data; /* Pointer to extra row data if any */ /* If non null, first byte is length */ bool m_vers_from_plain; /* helper functions */ #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) const uchar *m_curr_row; /* Start of the row being processed */ const uchar *m_curr_row_end; /* One-after the end of the current row */ uchar *m_key; /* Buffer to keep key value during searches */ KEY *m_key_info; /* Pointer to KEY info for m_key_nr */ uint m_key_nr; /* Key number */ bool master_had_triggers; /* set after tables opening */ /* RAII helper class to automatically handle the override/restore of thd->db when applying row events, so it will be visible in SHOW PROCESSLIST. If triggers will be invoked, their logic frees the current thread's db, so we use set_db() to use a copy of the table share's database. If not using triggers, the db is never freed, and we can reference the same memory owned by the table share. */ class Db_restore_ctx { private: THD *thd; LEX_CSTRING restore_db; bool db_copied; Db_restore_ctx(Rows_log_event *rev) : thd(rev->thd), restore_db(rev->thd->db) { TABLE *table= rev->m_table; if (table->triggers && rev->do_invoke_trigger()) { thd->reset_db(&null_clex_str); thd->set_db(&table->s->db); db_copied= true; } else { thd->reset_db(&table->s->db); db_copied= false; } } ~Db_restore_ctx() { if (db_copied) thd->set_db(&null_clex_str); thd->reset_db(&restore_db); } friend class Rows_log_event; }; int find_key(); // Find a best key to use in find_row() int find_row(rpl_group_info *); int write_row(rpl_group_info *, const bool); int update_sequence(); // Unpack the current row into m_table->record[0], but with // a different columns bitmap. int unpack_current_row(rpl_group_info *rgi, MY_BITMAP const *cols) { DBUG_ASSERT(m_table); ASSERT_OR_RETURN_ERROR(m_curr_row <= m_rows_end, HA_ERR_CORRUPT_EVENT); return ::unpack_row(rgi, m_table, m_width, m_curr_row, cols, &m_curr_row_end, &m_master_reclength, m_rows_end); } // Unpack the current row into m_table->record[0] int unpack_current_row(rpl_group_info *rgi) { DBUG_ASSERT(m_table); ASSERT_OR_RETURN_ERROR(m_curr_row <= m_rows_end, HA_ERR_CORRUPT_EVENT); return ::unpack_row(rgi, m_table, m_width, m_curr_row, &m_cols, &m_curr_row_end, &m_master_reclength, m_rows_end); } bool process_triggers(trg_event_type event, trg_action_time_type time_type, bool old_row_is_record1); /** Helper function to check whether there is an auto increment column on the table where the event is to be applied. @return true if there is an autoincrement field on the extra columns, false otherwise. */ inline bool is_auto_inc_in_extra_columns() { DBUG_ASSERT(m_table); return (m_table->next_number_field && m_table->next_number_field->field_index >= m_width); } #endif private: #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; int do_update_pos(rpl_group_info *rgi) override; enum_skip_reason do_shall_skip(rpl_group_info *rgi) override; /* Primitive to prepare for a sequence of row executions. DESCRIPTION Before doing a sequence of do_prepare_row() and do_exec_row() calls, this member function should be called to prepare for the entire sequence. Typically, this member function will allocate space for any buffers that are needed for the two member functions mentioned above. RETURN VALUE The member function will return 0 if all went OK, or a non-zero error code otherwise. */ virtual int do_before_row_operations(const Slave_reporting_capability *const log) = 0; /* Primitive to clean up after a sequence of row executions. DESCRIPTION After doing a sequence of do_prepare_row() and do_exec_row(), this member function should be called to clean up and release any allocated buffers. The error argument, if non-zero, indicates an error which happened during row processing before this function was called. In this case, even if function is successful, it should return the error code given in the argument. */ virtual int do_after_row_operations(const Slave_reporting_capability *const log, int error) = 0; /* Primitive to do the actual execution necessary for a row. DESCRIPTION The member function will do the actual execution needed to handle a row. The row is located at m_curr_row. When the function returns, m_curr_row_end should point at the next row (one byte after the end of the current row). RETURN VALUE 0 if execution succeeded, 1 if execution failed. */ virtual int do_exec_row(rpl_group_info *rli) = 0; #endif /* defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) */ friend class Old_rows_log_event; }; /** @class Write_rows_log_event Log row insertions and updates. The event contain several insert/update rows for a table. Note that each event contains only rows for one table. @section Write_rows_log_event_binary_format Binary Format */ class Write_rows_log_event : public Rows_log_event { public: enum { /* Support interface to THD::binlog_prepare_pending_rows_event */ TYPE_CODE = WRITE_ROWS_EVENT }; #if defined(MYSQL_SERVER) Write_rows_log_event(THD*, TABLE*, ulonglong table_id, bool is_transactional); #endif #ifdef HAVE_REPLICATION Write_rows_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif #if defined(MYSQL_SERVER) static bool binlog_row_logging_function(THD *thd, TABLE *table, bool is_transactional, const uchar *before_record __attribute__((unused)), const uchar *after_record) { DBUG_ASSERT(!table->versioned(VERS_TRX_ID)); return thd->binlog_write_row(table, is_transactional, after_record); } #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) uint8 get_trg_event_map() override; #endif private: Log_event_type get_general_type_code() override { return (Log_event_type)TYPE_CODE; } #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_before_row_operations(const Slave_reporting_capability *const) override; int do_after_row_operations(const Slave_reporting_capability *const,int) override; int do_exec_row(rpl_group_info *) override; #endif }; class Write_rows_compressed_log_event : public Write_rows_log_event { public: #if defined(MYSQL_SERVER) Write_rows_compressed_log_event(THD*, TABLE*, ulonglong table_id, bool is_transactional); bool write() override; #endif #ifdef HAVE_REPLICATION Write_rows_compressed_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif private: #if defined(MYSQL_CLIENT) bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif }; /** @class Update_rows_log_event Log row updates with a before image. The event contain several update rows for a table. Note that each event contains only rows for one table. Also note that the row data consists of pairs of row data: one row for the old data and one row for the new data. @section Update_rows_log_event_binary_format Binary Format */ class Update_rows_log_event : public Rows_log_event { public: enum { /* Support interface to THD::binlog_prepare_pending_rows_event */ TYPE_CODE = UPDATE_ROWS_EVENT }; #ifdef MYSQL_SERVER Update_rows_log_event(THD*, TABLE*, ulonglong table_id, bool is_transactional); void init(MY_BITMAP const *cols); #endif virtual ~Update_rows_log_event(); #ifdef HAVE_REPLICATION Update_rows_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif #ifdef MYSQL_SERVER static bool binlog_row_logging_function(THD *thd, TABLE *table, bool is_transactional, const uchar *before_record, const uchar *after_record) { DBUG_ASSERT(!table->versioned(VERS_TRX_ID)); return thd->binlog_update_row(table, is_transactional, before_record, after_record); } #endif bool is_valid() const override { return Rows_log_event::is_valid() && m_cols_ai.bitmap; } #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) uint8 get_trg_event_map() override; #endif protected: Log_event_type get_general_type_code() override { return (Log_event_type)TYPE_CODE; } #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_before_row_operations(const Slave_reporting_capability *const) override; int do_after_row_operations(const Slave_reporting_capability *const,int) override; int do_exec_row(rpl_group_info *) override; #endif /* defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) */ }; class Update_rows_compressed_log_event : public Update_rows_log_event { public: #if defined(MYSQL_SERVER) Update_rows_compressed_log_event(THD*, TABLE*, ulonglong table_id, bool is_transactional); bool write() override; #endif #ifdef HAVE_REPLICATION Update_rows_compressed_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif private: #if defined(MYSQL_CLIENT) bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif }; /** @class Delete_rows_log_event Log row deletions. The event contain several delete rows for a table. Note that each event contains only rows for one table. RESPONSIBILITIES - Act as a container for rows that has been deleted on the master and should be deleted on the slave. COLLABORATION Row_writer Create the event and add rows to the event. Row_reader Extract the rows from the event. @section Delete_rows_log_event_binary_format Binary Format */ class Delete_rows_log_event : public Rows_log_event { public: enum { /* Support interface to THD::binlog_prepare_pending_rows_event */ TYPE_CODE = DELETE_ROWS_EVENT }; #ifdef MYSQL_SERVER Delete_rows_log_event(THD*, TABLE*, ulonglong, bool is_transactional); #endif #ifdef HAVE_REPLICATION Delete_rows_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif #ifdef MYSQL_SERVER static bool binlog_row_logging_function(THD *thd, TABLE *table, bool is_transactional, const uchar *before_record, const uchar *after_record __attribute__((unused))) { DBUG_ASSERT(!table->versioned(VERS_TRX_ID)); return thd->binlog_delete_row(table, is_transactional, before_record); } #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) uint8 get_trg_event_map() override; #endif protected: Log_event_type get_general_type_code() override { return (Log_event_type)TYPE_CODE; } #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_before_row_operations(const Slave_reporting_capability *const) override; int do_after_row_operations(const Slave_reporting_capability *const,int) override; int do_exec_row(rpl_group_info *) override; #endif }; class Delete_rows_compressed_log_event : public Delete_rows_log_event { public: #if defined(MYSQL_SERVER) Delete_rows_compressed_log_event(THD*, TABLE*, ulonglong, bool is_transactional); bool write() override; #endif #ifdef HAVE_REPLICATION Delete_rows_compressed_log_event(const uchar *buf, uint event_len, const Format_description_log_event *description_event); #endif private: #if defined(MYSQL_CLIENT) bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif }; #include "log_event_old.h" /** @class Incident_log_event Class representing an incident, an occurence out of the ordinary, that happened on the master. The event is used to inform the slave that something out of the ordinary happened on the master that might cause the database to be in an inconsistent state.
Incident event format
Symbol Format Description
INCIDENT 2 Incident number as an unsigned integer
MSGLEN 1 Message length as an unsigned integer
MESSAGE MSGLEN The message, if present. Not null terminated.
@section Delete_rows_log_event_binary_format Binary Format */ class Incident_log_event : public Log_event { public: #ifdef MYSQL_SERVER Incident_log_event(THD *thd_arg, Incident incident) : Log_event(thd_arg, 0, FALSE), m_incident(incident) { DBUG_ENTER("Incident_log_event::Incident_log_event"); DBUG_PRINT("enter", ("m_incident: %d", m_incident)); m_message.str= NULL; /* Just as a precaution */ m_message.length= 0; set_direct_logging(); /* Replicate the incident regardless of @@skip_replication. */ flags&= ~LOG_EVENT_SKIP_REPLICATION_F; DBUG_VOID_RETURN; } Incident_log_event(THD *thd_arg, Incident incident, const LEX_CSTRING *msg) : Log_event(thd_arg, 0, FALSE), m_incident(incident) { extern PSI_memory_key key_memory_Incident_log_event_message; DBUG_ENTER("Incident_log_event::Incident_log_event"); DBUG_PRINT("enter", ("m_incident: %d", m_incident)); m_message.length= 0; if (!(m_message.str= (char*) my_malloc(key_memory_Incident_log_event_message, msg->length + 1, MYF(MY_WME)))) { /* Mark this event invalid */ m_incident= INCIDENT_NONE; DBUG_VOID_RETURN; } strmake(m_message.str, msg->str, msg->length); m_message.length= msg->length; set_direct_logging(); /* Replicate the incident regardless of @@skip_replication. */ flags&= ~LOG_EVENT_SKIP_REPLICATION_F; DBUG_VOID_RETURN; } #endif #ifdef MYSQL_SERVER #ifdef HAVE_REPLICATION void pack_info(Protocol*) override; #endif bool write_data_header() override; bool write_data_body() override; #endif Incident_log_event(const uchar *buf, uint event_len, const Format_description_log_event *descr_event); virtual ~Incident_log_event(); #ifdef MYSQL_CLIENT bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif #if defined(MYSQL_SERVER) && defined(HAVE_REPLICATION) int do_apply_event(rpl_group_info *rgi) override; #endif Log_event_type get_type_code() override { return INCIDENT_EVENT; } bool is_valid() const override { return m_incident > INCIDENT_NONE && m_incident < INCIDENT_COUNT; } int get_data_size() override { return INCIDENT_HEADER_LEN + 1 + (uint) m_message.length; } private: const char *description() const; Incident m_incident; LEX_STRING m_message; }; /** @class Ignorable_log_event Base class for ignorable log events. Events deriving from this class can be safely ignored by slaves that cannot recognize them. Newer slaves, will be able to read and handle them. This has been designed to be an open-ended architecture, so adding new derived events shall not harm the old slaves that support ignorable log event mechanism (they will just ignore unrecognized ignorable events). @note The only thing that makes an event ignorable is that it has the LOG_EVENT_IGNORABLE_F flag set. It is not strictly necessary that ignorable event types derive from Ignorable_log_event; they may just as well derive from Log_event and pass LOG_EVENT_IGNORABLE_F as argument to the Log_event constructor. **/ class Ignorable_log_event : public Log_event { public: int number; const char *description; #ifndef MYSQL_CLIENT Ignorable_log_event(THD *thd_arg) :Log_event(thd_arg, LOG_EVENT_IGNORABLE_F, FALSE), number(0), description("internal") { DBUG_ENTER("Ignorable_log_event::Ignorable_log_event"); DBUG_VOID_RETURN; } #endif Ignorable_log_event(const uchar *buf, const Format_description_log_event *descr_event, const char *event_name); virtual ~Ignorable_log_event(); #ifndef MYSQL_CLIENT #ifdef HAVE_REPLICATION void pack_info(Protocol*) override; #endif #else bool print(FILE *file, PRINT_EVENT_INFO *print_event_info) override; #endif Log_event_type get_type_code() override { return IGNORABLE_LOG_EVENT; } bool is_valid() const override { return 1; } int get_data_size() override { return IGNORABLE_HEADER_LEN; } }; #ifdef MYSQL_CLIENT bool copy_cache_to_string_wrapped(IO_CACHE *body, LEX_STRING *to, bool do_wrap, const char *delimiter, bool is_verbose); bool copy_cache_to_file_wrapped(IO_CACHE *body, FILE *file, bool do_wrap, const char *delimiter, bool is_verbose); #endif #ifdef MYSQL_SERVER /***************************************************************************** Heartbeat Log Event class Replication event to ensure to slave that master is alive. The event is originated by master's dump thread and sent straight to slave without being logged. Slave itself does not store it in relay log but rather uses a data for immediate checks and throws away the event. Two members of the class log_ident and Log_event::log_pos comprise @see the event_coordinates instance. The coordinates that a heartbeat instance carries correspond to the last event master has sent from its binlog. ****************************************************************************/ class Heartbeat_log_event: public Log_event { public: uint8 hb_flags; Heartbeat_log_event(const uchar *buf, uint event_len, const Format_description_log_event* description_event); Log_event_type get_type_code() override { return HEARTBEAT_LOG_EVENT; } bool is_valid() const override { return (log_ident != NULL && ident_len <= FN_REFLEN-1 && log_pos >= BIN_LOG_HEADER_SIZE); } const uchar * get_log_ident() { return log_ident; } uint get_ident_len() { return ident_len; } private: uint ident_len; const uchar *log_ident; }; inline int Log_event_writer::write(Log_event *ev) { ev->writer= this; int res= ev->write(); IF_DBUG(ev->writer= 0,); // writer must be set before every Log_event::write add_status(ev->logged_status()); return res; } /** The function is called by slave applier in case there are active table filtering rules to force gathering events associated with Query-log-event into an array to execute them once the fate of the Query is determined for execution. */ bool slave_execute_deferred_events(THD *thd); #endif bool event_that_should_be_ignored(const uchar *buf); bool event_checksum_test(uchar *buf, ulong event_len, enum_binlog_checksum_alg alg); enum enum_binlog_checksum_alg get_checksum_alg(const uchar *buf, ulong len); extern TYPELIB binlog_checksum_typelib; #ifdef WITH_WSREP enum Log_event_type wsrep_peak_event(rpl_group_info *rgi, ulonglong* event_size); #endif /* WITH_WSREP */ /** @} (end of group Replication) */ int binlog_buf_compress(const uchar *src, uchar *dst, uint32 len, uint32 *comlen); int binlog_buf_uncompress(const uchar *src, uchar *dst, uint32 len, uint32 *newlen); uint32 binlog_get_compress_len(uint32 len); uint32 binlog_get_uncompress_len(const uchar *buf); int query_event_uncompress(const Format_description_log_event *description_event, bool contain_checksum, const uchar *src, ulong src_len, uchar *buf, ulong buf_size, bool* is_malloc, uchar **dst, ulong *newlen); int row_log_event_uncompress(const Format_description_log_event *description_event, bool contain_checksum, const uchar *src, ulong src_len, uchar* buf, ulong buf_size, bool *is_malloc, uchar **dst, ulong *newlen); #endif /* _log_event_h */ mysql/server/private/sp_rcontext.h000064400000033776151027430560013435 0ustar00/* -*- C++ -*- */ /* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _SP_RCONTEXT_H_ #define _SP_RCONTEXT_H_ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_class.h" // select_result_interceptor #include "sp_pcontext.h" // sp_condition_value /////////////////////////////////////////////////////////////////////////// // sp_rcontext declaration. /////////////////////////////////////////////////////////////////////////// class sp_cursor; class sp_lex_keeper; class sp_instr_cpush; class sp_instr_hpush_jump; class Query_arena; class sp_head; class Item_cache; class Virtual_tmp_table; /* This class is a runtime context of a Stored Routine. It is used in an execution and is intended to contain all dynamic objects (i.e. objects, which can be changed during execution), such as: - stored routine variables; - cursors; - handlers; Runtime context is used with sp_head class. sp_head class is intended to contain all static things, related to the stored routines (code, for example). sp_head instance creates runtime context for the execution of a stored routine. There is a parsing context (an instance of sp_pcontext class), which is used on parsing stage. However, now it contains some necessary for an execution things, such as definition of used stored routine variables. That's why runtime context needs a reference to the parsing context. */ class sp_rcontext : public Sql_alloc { public: /// Construct and properly initialize a new sp_rcontext instance. The static /// create-function is needed because we need a way to return an error from /// the constructor. /// /// @param thd Thread handle. /// @param root_parsing_ctx Top-level parsing context for this stored program. /// @param return_value_fld Field object to store the return value /// (for stored functions only). /// /// @return valid sp_rcontext object or NULL in case of OOM-error. static sp_rcontext *create(THD *thd, const sp_head *owner, const sp_pcontext *root_parsing_ctx, Field *return_value_fld, Row_definition_list &defs); ~sp_rcontext(); private: sp_rcontext(const sp_head *owner, const sp_pcontext *root_parsing_ctx, Field *return_value_fld, bool in_sub_stmt); // Prevent use of copying constructor and operator. sp_rcontext(const sp_rcontext &); void operator=(sp_rcontext &); public: /// This class stores basic information about SQL-condition, such as: /// - SQL error code; /// - error level; /// - SQLSTATE; /// - text message. /// /// It's used to organize runtime SQL-handler call stack. /// /// Standard Sql_condition class can not be used, because we don't always have /// an Sql_condition object for an SQL-condition in Diagnostics_area. /// /// Eventually, this class should be moved to sql_error.h, and be a part of /// standard SQL-condition processing (Diagnostics_area should contain an /// object for active SQL-condition, not just information stored in DA's /// fields). class Sql_condition_info : public Sql_alloc, public Sql_condition_identity { public: /// Text message. char *message; /// The constructor. /// /// @param _sql_condition The SQL condition. /// @param arena Query arena for SP Sql_condition_info(const Sql_condition *_sql_condition, Query_arena *arena) :Sql_condition_identity(*_sql_condition) { message= strdup_root(arena->mem_root, _sql_condition->get_message_text()); } }; private: /// This class represents a call frame of SQL-handler (one invocation of a /// handler). Basically, it's needed to store continue instruction pointer for /// CONTINUE SQL-handlers. class Handler_call_frame : public Sql_alloc { public: /// SQL-condition, triggered handler activation. const Sql_condition_info *sql_condition; /// Continue-instruction-pointer for CONTINUE-handlers. /// The attribute contains 0 for EXIT-handlers. uint continue_ip; /// The constructor. /// /// @param _sql_condition SQL-condition, triggered handler activation. /// @param _continue_ip Continue instruction pointer. Handler_call_frame(const Sql_condition_info *_sql_condition, uint _continue_ip) :sql_condition(_sql_condition), continue_ip(_continue_ip) { } }; public: /// Arena used to (re) allocate items on. E.g. reallocate INOUT/OUT /// SP-variables when they don't fit into prealloced items. This is common /// situation with String items. It is used mainly in sp_eval_func_item(). Query_arena *callers_arena; /// Flag to end an open result set before start executing an SQL-handler /// (if one is found). Otherwise the client will hang due to a violation /// of the client/server protocol. bool end_partial_result_set; bool pause_state; bool quit_func; uint instr_ptr; /// The stored program for which this runtime context is created. Used for /// checking if correct runtime context is used for variable handling, /// and to access the package run-time context. /// Also used by slow log. const sp_head *m_sp; ///////////////////////////////////////////////////////////////////////// // SP-variables. ///////////////////////////////////////////////////////////////////////// uint argument_count() const { return m_root_parsing_ctx->context_var_count(); } int set_variable(THD *thd, uint var_idx, Item **value); int set_variable_row_field(THD *thd, uint var_idx, uint field_idx, Item **value); int set_variable_row_field_by_name(THD *thd, uint var_idx, const LEX_CSTRING &field_name, Item **value); int set_variable_row(THD *thd, uint var_idx, List &items); int set_parameter(THD *thd, uint var_idx, Item **value) { DBUG_ASSERT(var_idx < argument_count()); return set_variable(thd, var_idx, value); } Item_field *get_variable(uint var_idx) const { return m_var_items[var_idx]; } Item **get_variable_addr(uint var_idx) const { return ((Item **) m_var_items.array()) + var_idx; } Item_field *get_parameter(uint var_idx) const { DBUG_ASSERT(var_idx < argument_count()); return get_variable(var_idx); } bool find_row_field_by_name_or_error(uint *field_idx, uint var_idx, const LEX_CSTRING &field_name); bool set_return_value(THD *thd, Item **return_value_item); bool is_return_value_set() const { return m_return_value_set; } ///////////////////////////////////////////////////////////////////////// // SQL-handlers. ///////////////////////////////////////////////////////////////////////// /// Push an sp_instr_hpush_jump instance to the handler call stack. /// /// @param entry The condition handler entry /// /// @return error flag. /// @retval false on success. /// @retval true on error. bool push_handler(sp_instr_hpush_jump *entry); /// Pop and delete given number of instances from the handler /// call stack. /// /// @param count Number of handler entries to pop & delete. void pop_handlers(size_t count); const Sql_condition_info *raised_condition() const { return m_handler_call_stack.elements() ? (*m_handler_call_stack.back())->sql_condition : NULL; } /// Handle current SQL condition (if any). /// /// This is the public-interface function to handle SQL conditions in /// stored routines. /// /// @param thd Thread handle. /// @param ip[out] Instruction pointer to the first handler /// instruction. /// @param cur_spi Current SP instruction. /// /// @retval true if an SQL-handler has been activated. That means, all of /// the following conditions are satisfied: /// - the SP-instruction raised SQL-condition(s), /// - and there is an SQL-handler to process at least one of those /// SQL-conditions, /// - and that SQL-handler has been activated. /// Note, that the return value has nothing to do with "error flag" /// semantics. /// /// @retval false otherwise. bool handle_sql_condition(THD *thd, uint *ip, const sp_instr *cur_spi); /// Remove latest call frame from the handler call stack. /// /// @param da Diagnostics area containing handled conditions. /// /// @return continue instruction pointer of the removed handler. uint exit_handler(Diagnostics_area *da); ///////////////////////////////////////////////////////////////////////// // Cursors. ///////////////////////////////////////////////////////////////////////// /// Push a cursor to the cursor stack. /// /// @param cursor The cursor /// void push_cursor(sp_cursor *cur); void pop_cursor(THD *thd); /// Pop and delete given number of sp_cursor instance from the cursor stack. /// /// @param count Number of cursors to pop & delete. void pop_cursors(THD *thd, size_t count); void pop_all_cursors(THD *thd) { pop_cursors(thd, m_ccount); } sp_cursor *get_cursor(uint i) const { return m_cstack[i]; } ///////////////////////////////////////////////////////////////////////// // CASE expressions. ///////////////////////////////////////////////////////////////////////// /// Set CASE expression to the specified value. /// /// @param thd Thread handler. /// @param case_expr_id The CASE expression identifier. /// @param case_expr_item The CASE expression value /// /// @return error flag. /// @retval false on success. /// @retval true on error. /// /// @note The idea is to reuse Item_cache for the expression of the one /// CASE statement. This optimization takes place when there is CASE /// statement inside of a loop. So, in other words, we will use the same /// object on each iteration instead of creating a new one for each /// iteration. /// /// TODO /// Hypothetically, a type of CASE expression can be different for each /// iteration. For instance, this can happen if the expression contains /// a session variable (something like @@VAR) and its type is changed /// from one iteration to another. /// /// In order to cope with this problem, we check type each time, when we /// use already created object. If the type does not match, we re-create /// Item. This also can (should?) be optimized. bool set_case_expr(THD *thd, int case_expr_id, Item **case_expr_item_ptr); Item *get_case_expr(int case_expr_id) const { return m_case_expr_holders[case_expr_id]; } Item ** get_case_expr_addr(int case_expr_id) const { return (Item**) m_case_expr_holders.array() + case_expr_id; } private: /// Internal function to allocate memory for arrays. /// /// @param thd Thread handle. /// /// @return error flag: false on success, true in case of failure. bool alloc_arrays(THD *thd); /// Create and initialize a table to store SP-variables. /// /// param thd Thread handle. /// /// @return error flag. /// @retval false on success. /// @retval true on error. bool init_var_table(THD *thd, List &defs); /// Create and initialize an Item-adapter (Item_field) for each SP-var field. /// /// param thd Thread handle. /// /// @return error flag. /// @retval false on success. /// @retval true on error. bool init_var_items(THD *thd, List &defs); /// Create an instance of appropriate Item_cache class depending on the /// specified type in the callers arena. /// /// @note We should create cache items in the callers arena, as they are /// used between in several instructions. /// /// @param thd Thread handler. /// @param item Item to get the expression type. /// /// @return Pointer to valid object on success, or NULL in case of error. Item_cache *create_case_expr_holder(THD *thd, const Item *item) const; Virtual_tmp_table *virtual_tmp_table_for_row(uint idx); private: /// Top-level (root) parsing context for this runtime context. const sp_pcontext *m_root_parsing_ctx; /// Virtual table for storing SP-variables. Virtual_tmp_table *m_var_table; /// Collection of Item_field proxies, each of them points to the /// corresponding field in m_var_table. Bounds_checked_array m_var_items; /// This is a pointer to a field, which should contain return value for /// stored functions (only). For stored procedures, this pointer is NULL. Field *m_return_value_fld; /// Indicates whether the return value (in m_return_value_fld) has been /// set during execution. bool m_return_value_set; /// Flag to tell if the runtime context is created for a sub-statement. bool m_in_sub_stmt; /// Stack of visible handlers. Dynamic_array m_handlers; /// Stack of caught SQL conditions. Dynamic_array m_handler_call_stack; /// Stack of cursors. Bounds_checked_array m_cstack; /// Current number of cursors in m_cstack. uint m_ccount; /// Array of CASE expression holders. Bounds_checked_array m_case_expr_holders; }; // class sp_rcontext : public Sql_alloc #endif /* _SP_RCONTEXT_H_ */ mysql/server/private/sql_i_s.h000064400000020050151027430560012473 0ustar00#ifndef SQL_I_S_INCLUDED #define SQL_I_S_INCLUDED /* Copyright (c) 2000, 2017, Oracle and/or its affiliates. Copyright (c) 2009, 2019, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_const.h" // MAX_FIELD_VARCHARLENGTH #include "sql_basic_types.h" // enum_nullability #include "sql_string.h" // strlen, MY_CS_NAME_SIZE #include "lex_string.h" // LEX_CSTRING #include "mysql_com.h" // enum_field_types #include "my_time.h" // TIME_SECOND_PART_DIGITS #include "sql_type.h" // Type_handler_xxx struct TABLE_LIST; struct TABLE; typedef class Item COND; #ifdef MYSQL_CLIENT #error MYSQL_CLIENT must not be defined #endif // MYSQL_CLIENT bool schema_table_store_record(THD *thd, TABLE *table); COND *make_cond_for_info_schema(THD *thd, COND *cond, TABLE_LIST *table); enum enum_show_open_table { SKIP_OPEN_TABLE= 0U, // do not open table OPEN_FRM_ONLY= 1U, // open FRM file only OPEN_FULL_TABLE= 2U // open FRM,MYD, MYI files }; namespace Show { class Type { /** This denotes data type for the column. For the most part, there seems to be one entry in the enum for each SQL data type, although there seem to be a number of additional entries in the enum. */ const Type_handler *m_type_handler; /** For string-type columns, this is the maximum number of characters. Otherwise, it is the 'display-length' for the column. */ uint m_char_length; uint m_unsigned_flag; const Typelib *m_typelib; public: Type(const Type_handler *th, uint length, uint unsigned_flag, const Typelib *typelib= NULL) :m_type_handler(th), m_char_length(length), m_unsigned_flag(unsigned_flag), m_typelib(typelib) { } const Type_handler *type_handler() const { return m_type_handler; } uint char_length() const { return m_char_length; } decimal_digits_t decimal_precision() const { return (decimal_digits_t) ((m_char_length / 100) % 100); } decimal_digits_t decimal_scale() const { return (decimal_digits_t) (m_char_length % 10); } uint fsp() const { DBUG_ASSERT(m_char_length <= TIME_SECOND_PART_DIGITS); return m_char_length; } uint unsigned_flag() const { return m_unsigned_flag; } const Typelib *typelib() const { return m_typelib; } }; } // namespace Show class ST_FIELD_INFO: public Show::Type { protected: LEX_CSTRING m_name; // I_S column name enum_nullability m_nullability; // NULLABLE or NOT NULL LEX_CSTRING m_old_name; // SHOW column name enum_show_open_table m_open_method; public: ST_FIELD_INFO(const LEX_CSTRING &name, const Type &type, enum_nullability nullability, LEX_CSTRING &old_name, enum_show_open_table open_method) :Type(type), m_name(name), m_nullability(nullability), m_old_name(old_name), m_open_method(open_method) { } ST_FIELD_INFO(const char *name, const Type &type, enum_nullability nullability, const char *old_name, enum_show_open_table open_method) :Type(type), m_nullability(nullability), m_open_method(open_method) { m_name.str= name; m_name.length= safe_strlen(name); m_old_name.str= old_name; m_old_name.length= safe_strlen(old_name); } const LEX_CSTRING &name() const { return m_name; } bool nullable() const { return m_nullability == NULLABLE; } const LEX_CSTRING &old_name() const { return m_old_name; } enum_show_open_table open_method() const { return m_open_method; } bool end_marker() const { return m_name.str == NULL; } }; namespace Show { class Enum: public Type { public: Enum(const Typelib *typelib) :Type(&type_handler_enum, 0, false, typelib) { } }; class Blob: public Type { public: Blob(uint length) :Type(&type_handler_blob, length, false) { } }; class Varchar: public Type { public: Varchar(uint length) :Type(&type_handler_varchar, length, false) { DBUG_ASSERT(length * 3 <= MAX_FIELD_VARCHARLENGTH); } }; class Longtext: public Type { public: Longtext(uint length) :Type(&type_handler_varchar, length, false) { } }; class Yes_or_empty: public Varchar { public: Yes_or_empty(): Varchar(3) { } }; class Catalog: public Varchar { public: Catalog(): Varchar(FN_REFLEN) { } }; class Name: public Varchar { public: Name(): Varchar(NAME_CHAR_LEN) { } }; class Definer: public Varchar { public: Definer(): Varchar(DEFINER_CHAR_LENGTH) { } }; class Userhost: public Varchar { public: Userhost(): Varchar(USERNAME_CHAR_LENGTH + HOSTNAME_LENGTH + 2) { } }; class CSName: public Varchar { public: CSName(): Varchar(MY_CS_NAME_SIZE) { } }; class SQLMode: public Varchar { public: SQLMode(): Varchar(32*256) { } }; class Datetime: public Type { public: Datetime(uint dec) :Type(&type_handler_datetime2, dec, false) { } }; class Decimal: public Type { public: Decimal(uint length) :Type(&type_handler_newdecimal, length, false) { } }; class ULonglong: public Type { public: ULonglong(uint length) :Type(&type_handler_ulonglong, length, true) { } ULonglong() :ULonglong(MY_INT64_NUM_DECIMAL_DIGITS) { } }; class ULong: public Type { public: ULong(uint length) :Type(&type_handler_ulong, length, true) { } ULong() :ULong(MY_INT32_NUM_DECIMAL_DIGITS) { } }; class SLonglong: public Type { public: SLonglong(uint length) :Type(&type_handler_slonglong, length, false) { } SLonglong() :SLonglong(MY_INT64_NUM_DECIMAL_DIGITS) { } }; class SLong: public Type { public: SLong(uint length) :Type(&type_handler_slong, length, false) { } SLong() :SLong(MY_INT32_NUM_DECIMAL_DIGITS) { } }; class SShort: public Type { public: SShort(uint length) :Type(&type_handler_sshort, length, false) { } }; class STiny: public Type { public: STiny(uint length) :Type(&type_handler_stiny, length, false) { } }; class Double: public Type { public: Double(uint length) :Type(&type_handler_double, length, false) { } }; class Float: public Type { public: Float(uint length) :Type(&type_handler_float, length, false) { } }; class Column: public ST_FIELD_INFO { public: Column(const char *name, const Type &type, enum_nullability nullability, const char *old_name, enum_show_open_table open_method= SKIP_OPEN_TABLE) :ST_FIELD_INFO(name, type, nullability, old_name, open_method) { } Column(const char *name, const Type &type, enum_nullability nullability, enum_show_open_table open_method= SKIP_OPEN_TABLE) :ST_FIELD_INFO(name, type, nullability, NullS, open_method) { } }; // End marker class CEnd: public Column { public: CEnd() :Column(NullS, Varchar(0), NOT_NULL, NullS, SKIP_OPEN_TABLE) { } }; } // namespace Show struct TABLE_LIST; typedef class Item COND; typedef struct st_schema_table { const char *table_name; ST_FIELD_INFO *fields_info; /* for FLUSH table_name */ int (*reset_table) (); /* Fill table with data */ int (*fill_table) (THD *thd, TABLE_LIST *tables, COND *cond); /* Handle fileds for old SHOW */ int (*old_format) (THD *thd, struct st_schema_table *schema_table); int (*process_table) (THD *thd, TABLE_LIST *tables, TABLE *table, bool res, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name); int idx_field1, idx_field2; bool hidden; uint i_s_requested_object; /* the object we need to open(TABLE | VIEW) */ } ST_SCHEMA_TABLE; #endif // SQL_I_S_INCLUDED mysql/server/private/sql_type_geom.h000064400000045216151027430560013724 0ustar00#ifndef SQL_TYPE_GEOM_H_INCLUDED #define SQL_TYPE_GEOM_H_INCLUDED /* Copyright (c) 2015 MariaDB Foundation Copyright (c) 2019, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #ifdef USE_PRAGMA_IMPLEMENTATION #pragma implementation // gcc: Class implementation #endif #include "mariadb.h" #include "sql_type.h" #ifdef HAVE_SPATIAL class Type_handler_geometry: public Type_handler_string_result { public: enum geometry_types { GEOM_GEOMETRY = 0, GEOM_POINT = 1, GEOM_LINESTRING = 2, GEOM_POLYGON = 3, GEOM_MULTIPOINT = 4, GEOM_MULTILINESTRING = 5, GEOM_MULTIPOLYGON = 6, GEOM_GEOMETRYCOLLECTION = 7 }; static bool check_type_geom_or_binary(const LEX_CSTRING &opname, const Item *item); static bool check_types_geom_or_binary(const LEX_CSTRING &opname, Item * const *args, uint start, uint end); static const Type_handler_geometry *type_handler_geom_by_type(uint type); LEX_CSTRING extended_metadata_data_type_name() const; public: virtual ~Type_handler_geometry() {} enum_field_types field_type() const override { return MYSQL_TYPE_GEOMETRY; } bool Item_append_extended_type_info(Send_field_extended_metadata *to, const Item *item) const override { LEX_CSTRING tmp= extended_metadata_data_type_name(); return tmp.length ? to->set_data_type_name(tmp) : false; } bool is_param_long_data_type() const override { return true; } uint32 max_display_length_for_field(const Conv_source &src) const override; uint32 calc_pack_length(uint32 length) const override; const Type_collection *type_collection() const override; const Type_handler *type_handler_for_comparison() const override; virtual geometry_types geometry_type() const { return GEOM_GEOMETRY; } virtual Item *create_typecast_item(THD *thd, Item *item, const Type_cast_attributes &attr) const override; const Type_handler *type_handler_frm_unpack(const uchar *buffer) const override; bool is_binary_compatible_geom_super_type_for(const Type_handler_geometry *th) const { return geometry_type() == GEOM_GEOMETRY || geometry_type() == th->geometry_type(); } bool type_can_have_key_part() const override { return true; } bool subquery_type_allows_materialization(const Item *, const Item *, bool) const override { return false; // Materialization does not work with GEOMETRY columns } void Item_param_set_param_func(Item_param *param, uchar **pos, ulong len) const override; bool Item_param_set_from_value(THD *thd, Item_param *param, const Type_all_attributes *attr, const st_value *value) const override; Field *make_conversion_table_field(MEM_ROOT *root, TABLE *table, uint metadata, const Field *target) const override; Log_event_data_type user_var_log_event_data_type(uint charset_nr) const override { return Log_event_data_type(name().lex_cstring(), result_type(), charset_nr, false/*unsigned*/); } uint Column_definition_gis_options_image(uchar *buff, const Column_definition &def) const override; bool Column_definition_data_type_info_image(Binary_string *to, const Column_definition &def) const override { return false; } void Column_definition_attributes_frm_pack(const Column_definition_attributes *at, uchar *buff) const override; bool Column_definition_attributes_frm_unpack(Column_definition_attributes *attr, TABLE_SHARE *share, const uchar *buffer, LEX_CUSTRING *gis_options) const override; bool Column_definition_fix_attributes(Column_definition *c) const override; void Column_definition_reuse_fix_attributes(THD *thd, Column_definition *c, const Field *field) const override; bool Column_definition_prepare_stage1(THD *thd, MEM_ROOT *mem_root, Column_definition *c, handler *file, ulonglong table_flags, const Column_derived_attributes *derived_attr) const override; bool Column_definition_prepare_stage2(Column_definition *c, handler *file, ulonglong table_flags) const override; bool Key_part_spec_init_primary(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_unique(Key_part_spec *part, const Column_definition &def, const handler *file, bool *has_key_needed) const override; bool Key_part_spec_init_multiple(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_foreign(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_spatial(Key_part_spec *part, const Column_definition &def) const override; Field *make_table_field(MEM_ROOT *root, const LEX_CSTRING *name, const Record_addr &addr, const Type_all_attributes &attr, TABLE_SHARE *share) const override; Field *make_table_field_from_def(TABLE_SHARE *share, MEM_ROOT *mem_root, const LEX_CSTRING *name, const Record_addr &addr, const Bit_addr &bit, const Column_definition_attributes *attr, uint32 flags) const override; bool can_return_int() const override { return false; } bool can_return_decimal() const override { return false; } bool can_return_real() const override { return false; } bool can_return_text() const override { return false; } bool can_return_date() const override { return false; } bool can_return_time() const override { return false; } bool Item_func_round_fix_length_and_dec(Item_func_round *) const override; bool Item_func_int_val_fix_length_and_dec(Item_func_int_val *) const override; bool Item_func_abs_fix_length_and_dec(Item_func_abs *) const override; bool Item_func_neg_fix_length_and_dec(Item_func_neg *) const override; bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *h, Type_all_attributes *attr, Item **items, uint nitems) const override; bool Item_sum_sum_fix_length_and_dec(Item_sum_sum *) const override; bool Item_sum_avg_fix_length_and_dec(Item_sum_avg *) const override; bool Item_sum_variance_fix_length_and_dec(Item_sum_variance *) const override; bool Item_func_signed_fix_length_and_dec(Item_func_signed *) const override; bool Item_func_unsigned_fix_length_and_dec(Item_func_unsigned *) const override; bool Item_double_typecast_fix_length_and_dec(Item_double_typecast *) const override; bool Item_float_typecast_fix_length_and_dec(Item_float_typecast *) const override; bool Item_decimal_typecast_fix_length_and_dec(Item_decimal_typecast *) const override; bool Item_char_typecast_fix_length_and_dec(Item_char_typecast *) const override; bool Item_time_typecast_fix_length_and_dec(Item_time_typecast *) const override; bool Item_date_typecast_fix_length_and_dec(Item_date_typecast *) const override; bool Item_datetime_typecast_fix_length_and_dec(Item_datetime_typecast *) const override; }; class Type_handler_point: public Type_handler_geometry { // Binary length of a POINT value: 4 byte SRID + 21 byte WKB POINT static uint octet_length() { return 25; } public: geometry_types geometry_type() const override { return GEOM_POINT; } Item *make_constructor_item(THD *thd, List *args) const override; bool Key_part_spec_init_primary(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_unique(Key_part_spec *part, const Column_definition &def, const handler *file, bool *has_key_needed) const override; bool Key_part_spec_init_multiple(Key_part_spec *part, const Column_definition &def, const handler *file) const override; bool Key_part_spec_init_foreign(Key_part_spec *part, const Column_definition &def, const handler *file) const override; }; class Type_handler_linestring: public Type_handler_geometry { public: geometry_types geometry_type() const override { return GEOM_LINESTRING; } Item *make_constructor_item(THD *thd, List *args) const override; }; class Type_handler_polygon: public Type_handler_geometry { public: geometry_types geometry_type() const override { return GEOM_POLYGON; } Item *make_constructor_item(THD *thd, List *args) const override; }; class Type_handler_multipoint: public Type_handler_geometry { public: geometry_types geometry_type() const override { return GEOM_MULTIPOINT; } Item *make_constructor_item(THD *thd, List *args) const override; }; class Type_handler_multilinestring: public Type_handler_geometry { public: geometry_types geometry_type() const override { return GEOM_MULTILINESTRING; } Item *make_constructor_item(THD *thd, List *args) const override; }; class Type_handler_multipolygon: public Type_handler_geometry { public: geometry_types geometry_type() const override { return GEOM_MULTIPOLYGON; } Item *make_constructor_item(THD *thd, List *args) const override; }; class Type_handler_geometrycollection: public Type_handler_geometry { public: geometry_types geometry_type() const override { return GEOM_GEOMETRYCOLLECTION; } Item *make_constructor_item(THD *thd, List *args) const override; }; extern Named_type_handler type_handler_geometry; extern Named_type_handler type_handler_point; extern Named_type_handler type_handler_linestring; extern Named_type_handler type_handler_polygon; extern Named_type_handler type_handler_multipoint; extern Named_type_handler type_handler_multilinestring; extern Named_type_handler type_handler_multipolygon; extern Named_type_handler type_handler_geometrycollection; class Type_collection_geometry: public Type_collection { const Type_handler *aggregate_common(const Type_handler *a, const Type_handler *b) const { if (a == b) return a; if (dynamic_cast(a) && dynamic_cast(b)) return &type_handler_geometry; return NULL; } const Type_handler *aggregate_if_null(const Type_handler *a, const Type_handler *b) const { return a == &type_handler_null ? b : b == &type_handler_null ? a : NULL; } const Type_handler *aggregate_if_long_blob(const Type_handler *a, const Type_handler *b) const { return a == &type_handler_long_blob ? &type_handler_long_blob : b == &type_handler_long_blob ? &type_handler_long_blob : NULL; } const Type_handler *aggregate_if_string(const Type_handler *a, const Type_handler *b) const; #ifndef DBUG_OFF bool init_aggregators(Type_handler_data *data, const Type_handler *geom) const; #endif public: bool init(Type_handler_data *data) override; const Type_handler *aggregate_for_result(const Type_handler *a, const Type_handler *b) const override; const Type_handler *aggregate_for_comparison(const Type_handler *a, const Type_handler *b) const override; const Type_handler *aggregate_for_min_max(const Type_handler *a, const Type_handler *b) const override; const Type_handler *aggregate_for_num_op(const Type_handler *a, const Type_handler *b) const override { return NULL; } }; extern Type_collection_geometry type_collection_geometry; const Type_handler * Type_collection_geometry_handler_by_name(const LEX_CSTRING &name); #include "field.h" class Field_geom :public Field_blob { const Type_handler_geometry *m_type_handler; public: uint srid; uint precision; enum storage_type { GEOM_STORAGE_WKB= 0, GEOM_STORAGE_BINARY= 1}; enum storage_type storage; Field_geom(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const LEX_CSTRING *field_name_arg, TABLE_SHARE *share, uint blob_pack_length, const Type_handler_geometry *gth, uint field_srid) :Field_blob(ptr_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, share, blob_pack_length, &my_charset_bin), m_type_handler(gth) { srid= field_srid; } enum_conv_type rpl_conv_type_from(const Conv_source &source, const Relay_log_info *rli, const Conv_param ¶m) const override; enum ha_base_keytype key_type() const override { return HA_KEYTYPE_VARBINARY2; } const Type_handler *type_handler() const override { return m_type_handler; } const Type_handler_geometry *type_handler_geom() const { return m_type_handler; } void set_type_handler(const Type_handler_geometry *th) { m_type_handler= th; } enum_field_types type() const override { return MYSQL_TYPE_GEOMETRY; } enum_field_types real_type() const override { return MYSQL_TYPE_GEOMETRY; } Information_schema_character_attributes information_schema_character_attributes() const override { return Information_schema_character_attributes(); } void make_send_field(Send_field *to) override { Field_longstr::make_send_field(to); LEX_CSTRING tmp= m_type_handler->extended_metadata_data_type_name(); if (tmp.length) to->set_data_type_name(tmp); } Data_type_compatibility can_optimize_range(const Item_bool_func *cond, const Item *item, bool is_eq_func) const override; void sql_type(String &str) const override; Copy_func *get_copy_func(const Field *from) const override { const Type_handler_geometry *fth= dynamic_cast(from->type_handler()); if (fth && m_type_handler->is_binary_compatible_geom_super_type_for(fth)) return get_identical_copy_func(); return do_conv_blob; } bool memcpy_field_possible(const Field *from) const override { const Type_handler_geometry *fth= dynamic_cast(from->type_handler()); return fth && m_type_handler->is_binary_compatible_geom_super_type_for(fth) && !table->copy_blobs; } bool is_equal(const Column_definition &new_field) const override; int store(const char *to, size_t length, CHARSET_INFO *charset) override; int store(double nr) override; int store(longlong nr, bool unsigned_val) override; int store_decimal(const my_decimal *) override; uint size_of() const override{ return sizeof(*this); } /** Key length is provided only to support hash joins. (compared byte for byte) Ex: SELECT .. FROM t1,t2 WHERE t1.field_geom1=t2.field_geom2. The comparison is not very relevant, as identical geometry might be represented differently, but we need to support it either way. */ uint32 key_length() const override{ return packlength; } uint get_key_image(uchar *buff,uint length, const uchar *ptr_arg, imagetype type_arg) const override; /** Non-nullable GEOMETRY types cannot have defaults, but the underlying blob must still be reset. */ int reset(void) override{ return Field_blob::reset() || !maybe_null(); } bool load_data_set_null(THD *thd) override; bool load_data_set_no_data(THD *thd, bool fixed_format) override; uint get_srid() const { return srid; } void print_key_value(String *out, uint32 length) override { out->append(STRING_WITH_LEN("unprintable_geometry_value")); } Binlog_type_info binlog_type_info() const override; }; #endif // HAVE_SPATIAL #endif // SQL_TYPE_GEOM_H_INCLUDED mysql/server/private/sql_expression_cache.h000064400000010407151027430560015250 0ustar00/* Copyright (c) 2010, 2011, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_EXPRESSION_CACHE_INCLUDED #define SQL_EXPRESSION_CACHE_INCLUDED #include "sql_select.h" /** Interface for expression cache @note Parameters of an expression cache interface are set on the creation of the cache. They are passed when a cache object of the implementation class is constructed. That's why they are not visible in this interface. */ extern ulong subquery_cache_miss, subquery_cache_hit; class Expression_cache :public Sql_alloc { public: enum result {ERROR, HIT, MISS}; Expression_cache()= default; virtual ~Expression_cache() = default; /** Shall check the presence of expression value in the cache for a given set of values of the expression parameters. Return the result of the expression if it's found in the cache. */ virtual result check_value(Item **value)= 0; /** Shall put the value of an expression for given set of its parameters into the expression cache */ virtual my_bool put_value(Item *value)= 0; /** Print cache parameters */ virtual void print(String *str, enum_query_type query_type)= 0; /** Is this cache initialized */ virtual bool is_inited()= 0; /** Initialize this cache */ virtual void init()= 0; /** Save this object's statistics into Expression_cache_tracker object */ virtual void update_tracker()= 0; }; struct st_table_ref; struct st_join_table; class Item_field; class Expression_cache_tracker :public Sql_alloc { public: enum expr_cache_state {UNINITED, STOPPED, OK}; Expression_cache_tracker(Expression_cache *c) : cache(c), hit(0), miss(0), state(UNINITED) {} private: // This can be NULL if the cache is already deleted Expression_cache *cache; public: ulong hit, miss; enum expr_cache_state state; static const char* state_str[3]; void set(ulong h, ulong m, enum expr_cache_state s) {hit= h; miss= m; state= s;} void detach_from_cache() { cache= NULL; } void fetch_current_stats() { if (cache) cache->update_tracker(); } }; /** Implementation of expression cache over a temporary table */ class Expression_cache_tmptable :public Expression_cache { public: Expression_cache_tmptable(THD *thd, List &dependants, Item *value); virtual ~Expression_cache_tmptable(); result check_value(Item **value) override; my_bool put_value(Item *value) override; void print(String *str, enum_query_type query_type) override; bool is_inited() override { return inited; }; void init() override; void set_tracker(Expression_cache_tracker *st) { tracker= st; update_tracker(); } void update_tracker() override { if (tracker) { tracker->set(hit, miss, (inited ? (cache_table ? Expression_cache_tracker::OK : Expression_cache_tracker::STOPPED) : Expression_cache_tracker::UNINITED)); } } private: void disable_cache(); /* tmp table parameters */ TMP_TABLE_PARAM cache_table_param; /* temporary table to store this cache */ TABLE *cache_table; /* Thread handle for the temporary table */ THD *table_thd; /* EXPALIN/ANALYZE statistics */ Expression_cache_tracker *tracker; /* TABLE_REF for index lookup */ struct st_table_ref ref; /* Cached result */ Item_field *cached_result; /* List of parameter items */ List &items; /* Value Item example */ Item *val; /* hit/miss counters */ ulong hit, miss; /* Set on if the object has been successfully initialized with init() */ bool inited; }; #endif /* SQL_EXPRESSION_CACHE_INCLUDED */ mysql/server/private/sql_digest.h000064400000007353151027430560013213 0ustar00/* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_DIGEST_H #define SQL_DIGEST_H #include class String; #include "my_md5.h" #define MAX_DIGEST_STORAGE_SIZE (1024*1024) /** Structure to store token count/array for a statement on which digest is to be calculated. */ struct sql_digest_storage { bool m_full; uint m_byte_count; unsigned char m_md5[MD5_HASH_SIZE]; /** Character set number. */ uint m_charset_number; /** Token array. Token array is an array of bytes to store tokens received during parsing. Following is the way token array is formed. ... <non-id-token> <non-id-token> <id-token> <id_len> <id_text> ... For Example: SELECT * FROM T1; <SELECT_TOKEN> <*> <FROM_TOKEN> <ID_TOKEN> <2> <T1> @note Only the first @c m_byte_count bytes are initialized, out of @c m_token_array_length. */ unsigned char *m_token_array; /* Length of the token array to be considered for DIGEST_TEXT calculation. */ uint m_token_array_length; sql_digest_storage() { reset(NULL, 0); } inline void reset(unsigned char *token_array, size_t length) { m_token_array= token_array; m_token_array_length= (uint)length; reset(); } inline void reset() { m_full= false; m_byte_count= 0; m_charset_number= 0; memset(m_md5, 0, MD5_HASH_SIZE); } inline bool is_empty() { return (m_byte_count == 0); } inline void copy(const sql_digest_storage *from) { /* Keep in mind this is a dirty copy of something that may change, as the thread producing the digest is executing concurrently, without any lock enforced. */ uint byte_count_copy= m_token_array_length < from->m_byte_count ? m_token_array_length : from->m_byte_count; if (byte_count_copy > 0) { m_full= from->m_full; m_byte_count= byte_count_copy; m_charset_number= from->m_charset_number; memcpy(m_token_array, from->m_token_array, m_byte_count); memcpy(m_md5, from->m_md5, MD5_HASH_SIZE); } else { m_full= false; m_byte_count= 0; m_charset_number= 0; } } }; typedef struct sql_digest_storage sql_digest_storage; /** Compute a digest hash. @param digest_storage The digest @param [out] md5 The computed digest hash. This parameter is a buffer of size @c MD5_HASH_SIZE. */ void compute_digest_md5(const sql_digest_storage *digest_storage, unsigned char *md5); /** Compute a digest text. A 'digest text' is a textual representation of a query, where: - comments are removed, - non significant spaces are removed, - literal values are replaced with a special '?' marker, - lists of values are collapsed using a shorter notation @param digest_storage The digest @param [out] digest_text @param digest_text_length Size of @c digest_text. @param [out] truncated true if the text representation was truncated */ void compute_digest_text(const sql_digest_storage *digest_storage, String *digest_text); #endif mysql/server/private/wsrep_server_state.h000064400000004355151027430560015002 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_SERVER_STATE_H #define WSREP_SERVER_STATE_H /* wsrep-lib */ #include "wsrep/server_state.hpp" #include "wsrep/provider.hpp" /* implementation */ #include "wsrep_server_service.h" #include "wsrep_mutex.h" #include "wsrep_condition_variable.h" class Wsrep_server_state : public wsrep::server_state { public: static void init_once(const std::string& name, const std::string& incoming_address, const std::string& address, const std::string& working_dir, const wsrep::gtid& initial_position, int max_protocol_version); static void destroy(); static Wsrep_server_state& instance() { return *m_instance; } static bool is_inited() { return (m_instance != NULL); } static wsrep::provider& get_provider() { return instance().provider(); } static bool has_capability(int capability) { return (get_provider().capabilities() & capability); } static void handle_fatal_signal(); private: Wsrep_server_state(const std::string& name, const std::string& incoming_address, const std::string& address, const std::string& working_dir, const wsrep::gtid& initial_position, int max_protocol_version); ~Wsrep_server_state(); Wsrep_mutex m_mutex; Wsrep_condition_variable m_cond; Wsrep_server_service m_service; static Wsrep_server_state* m_instance; }; #endif // WSREP_SERVER_STATE_H mysql/server/private/rpl_injector.h000064400000022625151027430560013546 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef INJECTOR_H #define INJECTOR_H /* Pull in 'byte', 'my_off_t', and 'uint32' */ #include #include "rpl_constants.h" #include "table.h" /* TABLE */ /* Forward declarations */ class handler; class MYSQL_BIN_LOG; struct TABLE; /* Injector to inject rows into the MySQL server. The injector class is used to notify the MySQL server of new rows that have appeared outside of MySQL control. The original purpose of this is to allow clusters---which handle replication inside the cluster through other means---to insert new rows into binary log. Note, however, that the injector should be used whenever rows are altered in any manner that is outside of MySQL server visibility and which therefore are not seen by the MySQL server. */ class injector { public: /* Get an instance of the injector. DESCRIPTION The injector is a Singleton, so this static function return the available instance of the injector. RETURN VALUE A pointer to the available injector object. */ static injector *instance(); /* Delete the singleton instance (if allocated). Used during server shutdown. */ static void free_instance(); /* A transaction where rows can be added. DESCRIPTION The transaction class satisfy the **CopyConstructible** and **Assignable** requirements. Note that the transaction is *not* default constructible. */ class transaction { friend class injector; public: /* Convenience definitions */ typedef uchar* record_type; typedef uint32 server_id_type; /* Table reference. RESPONSIBILITY The class contains constructors to handle several forms of references to tables. The constructors can implicitly be used to construct references from, e.g., strings containing table names. EXAMPLE The class is intended to be used *by value*. Please, do not try to construct objects of this type using 'new'; instead construct an object, possibly a temporary object. For example: injector::transaction::table tbl(share->table, true); MY_BITMAP cols; my_bitmap_init(&cols, NULL, (i + 7) / 8, false); inj->write_row(::server_id, tbl, &cols, row_data); or MY_BITMAP cols; my_bitmap_init(&cols, NULL, (i + 7) / 8, false); inj->write_row(::server_id, injector::transaction::table(share->table, true), &cols, row_data); This will work, be more efficient, and have greater chance of inlining, not run the risk of losing pointers. COLLABORATION injector::transaction Provide a flexible interface to the representation of tables. */ class table { public: table(TABLE *table, bool is_transactional_arg) : m_table(table), m_is_transactional(is_transactional_arg) { } char const *db_name() const { return m_table->s->db.str; } char const *table_name() const { return m_table->s->table_name.str; } TABLE *get_table() const { return m_table; } bool is_transactional() const { return m_is_transactional; } private: TABLE *m_table; bool m_is_transactional; }; /* Binlog position as a structure. */ class binlog_pos { friend class transaction; public: char const *file_name() const { return m_file_name; } my_off_t file_pos() const { return m_file_pos; } private: char const *m_file_name; my_off_t m_file_pos; }; transaction() : m_thd(NULL) { } ~transaction(); /* Clear transaction, i.e., make calls to 'good()' return false. */ void clear() { m_thd= NULL; } /* Is the transaction in a good state? */ bool good() const { return m_thd != NULL; } /* Default assignment operator: standard implementation */ transaction& operator=(transaction t) { swap(t); return *this; } /* DESCRIPTION Register table for use within the transaction. All tables that are going to be used need to be registered before being used below. The member function will fail with an error if use_table() is called after any *_row() function has been called for the transaction. RETURN VALUE 0 All OK >0 Failure */ #ifdef TO_BE_DELETED int use_table(server_id_type sid, table tbl); #endif /* Commit a transaction. This member function will clean up after a sequence of *_row calls by, for example, releasing resource and unlocking files. */ int commit(); /* Get the position for the start of the transaction. Returns the position in the binary log of the first event in this transaction. If no event is yet written, the position where the event *will* be written is returned. This position is known, since a new_transaction() will lock the binary log and prevent any other writes to the binary log. */ binlog_pos start_pos() const; private: /* Only the injector may construct these object */ transaction(MYSQL_BIN_LOG *, THD *); void swap(transaction& o) { /* std::swap(m_start_pos, o.m_start_pos); */ { binlog_pos const tmp= m_start_pos; m_start_pos= o.m_start_pos; o.m_start_pos= tmp; } /* std::swap(m_thd, o.m_thd); */ { THD* const tmp= m_thd; m_thd= o.m_thd; o.m_thd= tmp; } { enum_state const tmp= m_state; m_state= o.m_state; o.m_state= tmp; } } enum enum_state { START_STATE, /* Start state */ TABLE_STATE, /* At least one table has been registered */ ROW_STATE, /* At least one row has been registered */ STATE_COUNT /* State count and sink state */ } m_state; /* Check and update the state. PARAMETER(S) target_state The state we are moving to: TABLE_STATE if we are writing a table and ROW_STATE if we are writing a row. DESCRIPTION The internal state will be updated to the target state if and only if it is a legal move. The only legal moves are: START_STATE -> START_STATE START_STATE -> TABLE_STATE TABLE_STATE -> TABLE_STATE TABLE_STATE -> ROW_STATE That is: - It is not possible to write any row before having written at least one table - It is not possible to write a table after at least one row has been written RETURN VALUE 0 All OK -1 Incorrect call sequence */ int check_state(enum_state const target_state) { #ifdef DBUG_TRACE static char const *state_name[] = { "START_STATE", "TABLE_STATE", "ROW_STATE", "STATE_COUNT" }; DBUG_PRINT("info", ("In state %s", state_name[m_state])); #endif DBUG_ASSERT(target_state <= STATE_COUNT); if (m_state <= target_state && target_state <= m_state + 1 && m_state < STATE_COUNT) m_state= target_state; else m_state= STATE_COUNT; return m_state == STATE_COUNT ? 1 : 0; } binlog_pos m_start_pos; THD *m_thd; }; /* Create a new transaction. This member function will prepare for a sequence of *_row calls by, for example, reserving resources and locking files. There are two overloaded alternatives: one returning a transaction by value and one using placement semantics. The following two calls are equivalent, with the exception that the latter will overwrite the transaction. injector::transaction trans1= inj->new_trans(thd); injector::transaction trans2; inj->new_trans(thd, &trans); */ transaction new_trans(THD *); void new_trans(THD *, transaction *); int record_incident(THD*, Incident incident); int record_incident(THD*, Incident incident, const LEX_CSTRING *message); private: explicit injector(); ~injector() = default; /* Nothing needs to be done */ injector(injector const&); /* You're not allowed to copy injector instances. */ }; #endif /* INJECTOR_H */ mysql/server/private/xa.h000064400000003465151027430560011465 0ustar00#ifndef XA_INCLUDED #define XA_INCLUDED /* Copyright (c) 2000, 2016, Oracle and/or its affiliates. Copyright (c) 2009, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ class XID_cache_element; enum xa_states { XA_ACTIVE= 0, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY, XA_NO_STATE }; struct XID_STATE { XID_cache_element *xid_cache_element; bool check_has_uncommitted_xa() const; bool is_explicit_XA() const { return xid_cache_element != 0; } void set_error(uint error); void set_rollback_only(); void er_xaer_rmfail() const; XID *get_xid() const; enum xa_states get_state_code() const; }; void xid_cache_init(void); void xid_cache_free(void); bool xid_cache_insert(XID *xid); bool xid_cache_insert(THD *thd, XID_STATE *xid_state, XID *xid); void xid_cache_delete(THD *thd, XID_STATE *xid_state); bool trans_xa_start(THD *thd); bool trans_xa_end(THD *thd); bool trans_xa_prepare(THD *thd); bool trans_xa_commit(THD *thd); bool trans_xa_rollback(THD *thd); bool trans_xa_detach(THD *thd); bool mysql_xa_recover(THD *thd); void xa_recover_get_fields(THD *thd, List *field_list, my_hash_walk_action *action); #endif /* XA_INCLUDED */ mysql/server/private/discover.h000064400000003042151027430560012662 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef DISCOVER_INCLUDED #define DISCOVER_INCLUDED int extension_based_table_discovery(MY_DIR *dirp, const char *ext, handlerton::discovered_list *tl); #ifdef MYSQL_SERVER int readfrm(const char *name, const uchar **data, size_t *length); int writefile(const char *path, const char *db, const char *table, bool tmp_table, const uchar *frmdata, size_t len); /* a helper to delete an frm file, given a path w/o .frm extension */ inline void deletefrm(const char *path) { char frm_name[FN_REFLEN]; strxnmov(frm_name, sizeof(frm_name)-1, path, reg_ext, NullS); mysql_file_delete(key_file_frm, frm_name, MYF(0)); } int ext_table_discovery_simple(MY_DIR *dirp, handlerton::discovered_list *result); #endif #endif /* DISCOVER_INCLUDED */ mysql/server/private/json_table.h000064400000022442151027430560013171 0ustar00#ifndef JSON_TABLE_INCLUDED #define JSON_TABLE_INCLUDED /* Copyright (c) 2020, MariaDB Corporation. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include class Json_table_column; /* The Json_table_nested_path represents the 'current nesting' level for a set of JSON_TABLE columns. Each column (Json_table_column instance) is linked with corresponding 'nested path' object and gets its piece of JSON to parse during the computation phase. The root 'nested_path' is always present as a part of Table_function_json_table, then other 'nested_paths' can be created and linked into a tree structure when new 'NESTED PATH' is met. The nested 'nested_paths' are linked with 'm_nested', the same-level 'nested_paths' are linked with 'm_next_nested'. So for instance JSON_TABLE( '...', '$[*]' COLUMNS( a INT PATH '$.a' , NESTED PATH '$.b[*]' COLUMNS (b INT PATH '$', NESTED PATH '$.c[*]' COLUMNS(x INT PATH '$')), NESTED PATH '$.n[*]' COLUMNS (z INT PATH '$')) results in 4 'nested_path' created: root nested_b nested_c nested_n m_path '$[*]' '$.b[*]' '$.c[*]' '$.n[*] m_nested &nested_b &nested_c NULL NULL n_next_nested NULL &nested_n NULL NULL and 4 columns created: a b x z m_nest &root &nested_b &nested_c &nested_n */ class Json_table_nested_path : public Sql_alloc { public: json_path_t m_path; /* The JSON Path to get the rows from */ bool m_null; // TRUE <=> producing a NULL-complemented row. /*** Construction interface ***/ Json_table_nested_path(): m_null(TRUE), m_nested(NULL), m_next_nested(NULL) {} int set_path(THD *thd, const LEX_CSTRING &path); /*** Methods for performing a scan ***/ void scan_start(CHARSET_INFO *i_cs, const uchar *str, const uchar *end); int scan_next(); bool check_error(const char *str); /*** Members for getting the values we've scanned to ***/ const uchar *get_value() { return m_engine.value_begin; } const uchar *get_value_end() { return m_engine.s.str_end; } /* Counts the rows produced. Used by FOR ORDINALITY columns */ longlong m_ordinality_counter; int print(THD *thd, Field ***f, String *str, List_iterator_fast &it, Json_table_column **last_column); private: /* The head of the list of nested NESTED PATH statements. */ Json_table_nested_path *m_nested; /* in the above list items are linked with the */ Json_table_nested_path *m_next_nested; /*** Members describing NESTED PATH structure ***/ /* Parent nested path. The "root" path has this NULL */ Json_table_nested_path *m_parent; /*** Members describing current JSON Path scan state ***/ /* The JSON Parser and JSON Path evaluator */ json_engine_t m_engine; /* The path the parser is currently pointing to */ json_path_t m_cur_path; /* The child NESTED PATH we're currently scanning */ Json_table_nested_path *m_cur_nested; static bool column_in_this_or_nested(const Json_table_nested_path *p, const Json_table_column *jc); friend class Table_function_json_table; }; /* @brief Describes the column definition in JSON_TABLE(...) syntax. @detail Has methods for printing/handling errors but otherwise it's a static object. */ class Json_table_column : public Sql_alloc { public: enum enum_type { FOR_ORDINALITY, PATH, EXISTS_PATH }; enum enum_on_type { ON_EMPTY, ON_ERROR }; enum enum_on_response { RESPONSE_NOT_SPECIFIED, RESPONSE_ERROR, RESPONSE_NULL, RESPONSE_DEFAULT }; struct On_response { public: Json_table_column::enum_on_response m_response; Item *m_default; int respond(Json_table_column *jc, Field *f, uint error_num); int print(const char *name, String *str) const; bool specified() const { return m_response != RESPONSE_NOT_SPECIFIED; } }; enum_type m_column_type; bool m_format_json; json_path_t m_path; On_response m_on_error; On_response m_on_empty; Create_field *m_field; Json_table_nested_path *m_nest; CHARSET_INFO *m_explicit_cs; void set(enum_type ctype) { m_column_type= ctype; } int set(THD *thd, enum_type ctype, const LEX_CSTRING &path, CHARSET_INFO *cs); Json_table_column(Create_field *f, Json_table_nested_path *nest) : m_field(f), m_nest(nest), m_explicit_cs(NULL) { m_on_error.m_response= RESPONSE_NOT_SPECIFIED; m_on_empty.m_response= RESPONSE_NOT_SPECIFIED; } int print(THD *tnd, Field **f, String *str); }; /* Class represents the table function, the function that returns the table as a result so supposed to appear in the FROM list of the SELECT statement. At the moment there is only one such function JSON_TABLE, so the class named after it, but should be refactored into the hierarchy root if we create more of that functions. As the parser finds the table function in the list it creates an instance of Table_function_json_table storing it into the TABLE_LIST::table_function. Then the ha_json_table instance is created based on it in the create_table_for_function(). == Replication: whether JSON_TABLE is deterministic == In sql_yacc.yy, we set BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION whenever JSON_TABLE is used. The reasoning behind this is as follows: In the current MariaDB code, evaluation of JSON_TABLE is deterministic, that is, for a given input string JSON_TABLE will always produce the same set of rows in the same order. However one can think of JSON documents that one can consider indentical which will produce different output. In order to be feature-proof and withstand changes like: - sorting JSON object members by name (like MySQL does) - changing the way duplicate object members are handled we mark the function as SBR-unsafe. (If there is ever an issue with this, marking the function as SBR-safe is a non-intrusive change we will always be able to make) */ class Table_function_json_table : public Sql_alloc { public: /*** Basic properties of the original JSON_TABLE(...) ***/ Item *m_json; /* The JSON value to be parsed. */ /* The COLUMNS(...) part representation. */ Json_table_nested_path m_nested_path; /* The list of table column definitions. */ List m_columns; /*** Name resolution functions ***/ bool setup(THD *thd, TABLE_LIST *sql_table, SELECT_LEX *s_lex); int walk_items(Item_processor processor, bool walk_subquery, void *argument); /*** Functions for interaction with the Query Optimizer ***/ void fix_after_pullout(TABLE_LIST *sql_table, st_select_lex *new_parent, bool merge); void update_used_tables() { m_json->update_used_tables(); } table_map used_tables() const { return m_json->used_tables(); } bool join_cache_allowed() const { /* Can use join cache when we have an outside reference. If there's dependency on any other table or randomness, cannot use it. */ return !(used_tables() & ~OUTER_REF_TABLE_BIT); } void get_estimates(ha_rows *out_rows, double *scan_time, double *startup_cost); int print(THD *thd, TABLE_LIST *sql_table, String *str, enum_query_type query_type); /*** Construction interface to be used from the parser ***/ Table_function_json_table(Item *json): m_json(json), m_context_setup_done(false) { cur_parent= &m_nested_path; last_sibling_hook= &m_nested_path.m_nested; } void start_nested_path(Json_table_nested_path *np); void end_nested_path(); Json_table_nested_path *get_cur_nested_path() { return cur_parent; } void set_name_resolution_context(Name_resolution_context *arg) { m_context= arg; } /* SQL Parser: current column in JSON_TABLE (...) syntax */ Json_table_column *m_cur_json_table_column; private: /* Context to be used for resolving the first argument. */ Name_resolution_context *m_context; bool m_context_setup_done; /* Current NESTED PATH level being parsed */ Json_table_nested_path *cur_parent; /* Pointer to the list tail where we add the next NESTED PATH. It points to the cur_parnt->m_nested for the first nested and prev_nested->m_next_nested for the coesequent ones. */ Json_table_nested_path **last_sibling_hook; }; bool push_table_function_arg_context(LEX *lex, MEM_ROOT *alloc); TABLE *create_table_for_function(THD *thd, TABLE_LIST *sql_table); table_map add_table_function_dependencies(List *join_list, table_map nest_tables); #endif /* JSON_TABLE_INCLUDED */ mysql/server/private/my_minidump.h000064400000001520151027430560013372 0ustar00/* Copyright (c) 2021, MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include #ifdef __cplusplus extern "C" { #endif BOOL my_create_minidump(DWORD pid, BOOL verbose); #ifdef __cplusplus } #endif mysql/server/private/item.h000064400001041326151027430560012012 0ustar00#ifndef SQL_ITEM_INCLUDED #define SQL_ITEM_INCLUDED /* Copyright (c) 2000, 2017, Oracle and/or its affiliates. Copyright (c) 2009, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_priv.h" /* STRING_BUFFER_USUAL_SIZE */ #include "unireg.h" #include "sql_const.h" /* RAND_TABLE_BIT, MAX_FIELD_NAME */ #include "field.h" /* Derivation */ #include "sql_type.h" #include "sql_time.h" #include "sql_schema.h" #include "mem_root_array.h" #include #include "cset_narrowing.h" C_MODE_START #include /* A prototype for a C-compatible structure to store a value of any data type. Currently it has to stay in /sql, as it depends on String and my_decimal. We'll do the following changes: 1. add pure C "struct st_string" and "struct st_my_decimal" 2. change type of m_string to struct st_string and move inside the union 3. change type of m_decmal to struct st_my_decimal and move inside the union 4. move the definition to some file in /include */ class st_value { public: st_value() {} st_value(char *buffer, size_t buffer_size) : m_string(buffer, buffer_size, &my_charset_bin) {} enum enum_dynamic_column_type m_type; union { longlong m_longlong; double m_double; MYSQL_TIME m_time; } value; String m_string; my_decimal m_decimal; }; C_MODE_END class Value: public st_value { public: Value(char *buffer, size_t buffer_size) : st_value(buffer, buffer_size) {} Value() {} bool is_null() const { return m_type == DYN_COL_NULL; } bool is_longlong() const { return m_type == DYN_COL_UINT || m_type == DYN_COL_INT; } bool is_double() const { return m_type == DYN_COL_DOUBLE; } bool is_temporal() const { return m_type == DYN_COL_DATETIME; } bool is_string() const { return m_type == DYN_COL_STRING; } bool is_decimal() const { return m_type == DYN_COL_DECIMAL; } }; template class ValueBuffer: public Value { char buffer[buffer_size]; public: ValueBuffer(): Value(buffer, buffer_size) {} void reset_buffer() { m_string.set_buffer_if_not_allocated(buffer, buffer_size, &my_charset_bin); } }; #ifdef DBUG_OFF static inline const char *dbug_print_item(Item *item) { return NULL; } #else const char *dbug_print_item(Item *item); #endif class Virtual_tmp_table; class sp_head; class Protocol; struct TABLE_LIST; void item_init(void); /* Init item functions */ class Item_basic_value; class Item_result_field; class Item_field; class Item_ref; class Item_param; class user_var_entry; class JOIN; struct KEY_FIELD; struct SARGABLE_PARAM; class RANGE_OPT_PARAM; class SEL_TREE; enum precedence { LOWEST_PRECEDENCE, ASSIGN_PRECEDENCE, // := OR_PRECEDENCE, // OR, || (unless PIPES_AS_CONCAT) XOR_PRECEDENCE, // XOR AND_PRECEDENCE, // AND, && NOT_PRECEDENCE, // NOT (unless HIGH_NOT_PRECEDENCE) CMP_PRECEDENCE, // =, <=>, >=, >, <=, <, <>, !=, IS BETWEEN_PRECEDENCE, // BETWEEN IN_PRECEDENCE, // IN, LIKE, REGEXP BITOR_PRECEDENCE, // | BITAND_PRECEDENCE, // & SHIFT_PRECEDENCE, // <<, >> INTERVAL_PRECEDENCE, // first argument in +INTERVAL ADD_PRECEDENCE, // +, - MUL_PRECEDENCE, // *, /, DIV, %, MOD BITXOR_PRECEDENCE, // ^ PIPES_PRECEDENCE, // || (if PIPES_AS_CONCAT) NEG_PRECEDENCE, // unary -, ~, !, NOT (if HIGH_NOT_PRECEDENCE) COLLATE_PRECEDENCE, // BINARY, COLLATE DEFAULT_PRECEDENCE, HIGHEST_PRECEDENCE }; bool mark_unsupported_function(const char *where, void *store, uint result); /* convenience helper for mark_unsupported_function() above */ bool mark_unsupported_function(const char *w1, const char *w2, void *store, uint result); /* Bits for the split_sum_func() function */ #define SPLIT_SUM_SKIP_REGISTERED 1 /* Skip registered funcs */ #define SPLIT_SUM_SELECT 2 /* SELECT item; Split all parts */ /* Values for item->marker for cond items in the WHERE clause as used by the optimizer. Note that for Item_fields, the marker contains 'select->cur_pos_in_select_list */ /* Used to check GROUP BY list in the MODE_ONLY_FULL_GROUP_BY mode */ #define MARKER_UNDEF_POS -1 #define MARKER_UNUSED 0 #define MARKER_CHANGE_COND 1 #define MARKER_PROCESSED 2 #define MARKER_CHECK_ON_READ 3 #define MARKER_NULL_KEY 4 #define MARKER_FOUND_IN_ORDER 6 /* Used as bits in marker by Item::check_pushable_cond() */ #define MARKER_NO_EXTRACTION (1 << 6) #define MARKER_FULL_EXTRACTION (1 << 7) #define MARKER_DELETION (1 << 8) #define MARKER_IMMUTABLE (1 << 9) #define MARKER_SUBSTITUTION (1 << 10) /* Used as bits in marker by window functions */ #define MARKER_SORTORDER_CHANGE (1 << 11) #define MARKER_PARTITION_CHANGE (1 << 12) #define MARKER_FRAME_CHANGE (1 << 13) #define MARKER_EXTRACTION_MASK \ (MARKER_NO_EXTRACTION | MARKER_FULL_EXTRACTION | MARKER_DELETION | \ MARKER_IMMUTABLE) extern const char *item_empty_name; void dummy_error_processor(THD *thd, void *data); void view_error_processor(THD *thd, void *data); typedef List* ignored_tables_list_t; bool ignored_list_includes_table(ignored_tables_list_t list, TABLE_LIST *tbl); /* Instances of Name_resolution_context store the information necessary for name resolution of Items and other context analysis of a query made in fix_fields(). This structure is a part of SELECT_LEX, a pointer to this structure is assigned when an item is created (which happens mostly during parsing (sql_yacc.yy)), but the structure itself will be initialized after parsing is complete TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to separate SELECT_LEX which allow to remove tricks of changing this structure before and after INSERT/CREATE and its SELECT to make correct field name resolution. */ struct Name_resolution_context: Sql_alloc { /* The name resolution context to search in when an Item cannot be resolved in this context (the context of an outer select) */ Name_resolution_context *outer_context= nullptr; /* List of tables used to resolve the items of this context. Usually these are tables from the FROM clause of SELECT statement. The exceptions are INSERT ... SELECT and CREATE ... SELECT statements, where SELECT subquery is not moved to a separate SELECT_LEX. For these types of statements we have to change this member dynamically to ensure correct name resolution of different parts of the statement. */ TABLE_LIST *table_list= nullptr; /* In most cases the two table references below replace 'table_list' above for the purpose of name resolution. The first and last name resolution table references allow us to search only in a sub-tree of the nested join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING and JOIN ... ON. */ TABLE_LIST *first_name_resolution_table= nullptr; /* Last table to search in the list of leaf table references that begins with first_name_resolution_table. */ TABLE_LIST *last_name_resolution_table= nullptr; /* Cache first_name_resolution_table in setup_natural_join_row_types */ TABLE_LIST *natural_join_first_table= nullptr; /* SELECT_LEX item belong to, in case of merged VIEW it can differ from SELECT_LEX where item was created, so we can't use table_list/field_list from there */ st_select_lex *select_lex= nullptr; /* Processor of errors caused during Item name resolving, now used only to hide underlying tables in errors about views (i.e. it substitute some errors for views) */ void (*error_processor)(THD *, void *)= &dummy_error_processor; void *error_processor_data= nullptr; /* When TRUE items are resolved in this context both against the SELECT list and this->table_list. If FALSE, items are resolved only against this->table_list. */ bool resolve_in_select_list= false; /* Bitmap of tables that should be ignored when doing name resolution. Normally it is {0}. Non-zero values are used by table functions. */ ignored_tables_list_t ignored_tables= nullptr; /* Security context of this name resolution context. It's used for views and is non-zero only if the view is defined with SQL SECURITY DEFINER. */ Security_context *security_ctx= nullptr; Name_resolution_context() = default; /** Name resolution context with resolution in only one table */ Name_resolution_context(TABLE_LIST *table) : first_name_resolution_table(table), last_name_resolution_table(table) {} void init() { resolve_in_select_list= FALSE; error_processor= &dummy_error_processor; ignored_tables= nullptr; first_name_resolution_table= nullptr; last_name_resolution_table= nullptr; } void resolve_in_table_list_only(TABLE_LIST *tables) { table_list= first_name_resolution_table= tables; resolve_in_select_list= FALSE; } void process_error(THD *thd) { (*error_processor)(thd, error_processor_data); } st_select_lex *outer_select() { return (outer_context ? outer_context->select_lex : NULL); } }; /* Store and restore the current state of a name resolution context. */ class Name_resolution_context_state { private: TABLE_LIST *save_table_list; TABLE_LIST *save_first_name_resolution_table; TABLE_LIST *save_next_name_resolution_table; bool save_resolve_in_select_list; TABLE_LIST *save_next_local; public: Name_resolution_context_state() = default; /* Remove gcc warning */ public: /* Save the state of a name resolution context. */ void save_state(Name_resolution_context *context, TABLE_LIST *table_list) { save_table_list= context->table_list; save_first_name_resolution_table= context->first_name_resolution_table; save_resolve_in_select_list= context->resolve_in_select_list; save_next_local= table_list->next_local; save_next_name_resolution_table= table_list->next_name_resolution_table; } /* Restore a name resolution context from saved state. */ void restore_state(Name_resolution_context *context, TABLE_LIST *table_list) { table_list->next_local= save_next_local; table_list->next_name_resolution_table= save_next_name_resolution_table; context->table_list= save_table_list; context->first_name_resolution_table= save_first_name_resolution_table; context->resolve_in_select_list= save_resolve_in_select_list; } TABLE_LIST *get_first_name_resolution_table() { return save_first_name_resolution_table; } }; class Name_resolution_context_backup { Name_resolution_context &ctx; TABLE_LIST &table_list; table_map save_map; Name_resolution_context_state ctx_state; public: Name_resolution_context_backup(Name_resolution_context &_ctx, TABLE_LIST &_table_list) : ctx(_ctx), table_list(_table_list), save_map(_table_list.map) { ctx_state.save_state(&ctx, &table_list); ctx.table_list= &table_list; ctx.first_name_resolution_table= &table_list; } ~Name_resolution_context_backup() { ctx_state.restore_state(&ctx, &table_list); table_list.map= save_map; } }; /* This enum is used to report information about monotonicity of function represented by Item* tree. Monotonicity is defined only for Item* trees that represent table partitioning expressions (i.e. have no subselects/user vars/PS parameters etc etc). An Item* tree is assumed to have the same monotonicity properties as its corresponding function F: [signed] longlong F(field1, field2, ...) { put values of field_i into table record buffer; return item->val_int(); } NOTE At the moment function monotonicity is not well defined (and so may be incorrect) for Item trees with parameters/return types that are different from INT_RESULT, may be NULL, or are unsigned. It will be possible to address this issue once the related partitioning bugs (BUG#16002, BUG#15447, BUG#13436) are fixed. The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns NULL which puts those rows into the NULL partition, but '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed for this (see Bug#20577). */ typedef enum monotonicity_info { NON_MONOTONIC, /* none of the below holds */ MONOTONIC_INCREASING, /* F() is unary and (x < y) => (F(x) <= F(y)) */ MONOTONIC_INCREASING_NOT_NULL, /* But only for valid/real x and y */ MONOTONIC_STRICT_INCREASING,/* F() is unary and (x < y) => (F(x) < F(y)) */ MONOTONIC_STRICT_INCREASING_NOT_NULL /* But only for valid/real x and y */ } enum_monotonicity_info; /*************************************************************************/ class sp_rcontext; /** A helper class to collect different behavior of various kinds of SP variables: - local SP variables and SP parameters - PACKAGE BODY routine variables - (there will be more kinds in the future) */ class Sp_rcontext_handler { public: virtual ~Sp_rcontext_handler() = default; /** A prefix used for SP variable names in queries: - EXPLAIN EXTENDED - SHOW PROCEDURE CODE Local variables and SP parameters have empty prefixes. Package body variables are marked with a special prefix. This improves readability of the output of these queries, especially when a local variable or a parameter has the same name with a package body variable. */ virtual const LEX_CSTRING *get_name_prefix() const= 0; /** At execution time THD->spcont points to the run-time context (sp_rcontext) of the currently executed routine. Local variables store their data in the sp_rcontext pointed by thd->spcont. Package body variables store data in separate sp_rcontext that belongs to the package. This method provides access to the proper sp_rcontext structure, depending on the SP variable kind. */ virtual sp_rcontext *get_rcontext(sp_rcontext *ctx) const= 0; }; class Sp_rcontext_handler_local: public Sp_rcontext_handler { public: const LEX_CSTRING *get_name_prefix() const override; sp_rcontext *get_rcontext(sp_rcontext *ctx) const override; }; class Sp_rcontext_handler_package_body: public Sp_rcontext_handler { public: const LEX_CSTRING *get_name_prefix() const override; sp_rcontext *get_rcontext(sp_rcontext *ctx) const override; }; extern MYSQL_PLUGIN_IMPORT Sp_rcontext_handler_local sp_rcontext_handler_local; extern MYSQL_PLUGIN_IMPORT Sp_rcontext_handler_package_body sp_rcontext_handler_package_body; class Item_equal; struct st_join_table* const NO_PARTICULAR_TAB= (struct st_join_table*)0x1; typedef struct replace_equal_field_arg { Item_equal *item_equal; struct st_join_table *context_tab; } REPLACE_EQUAL_FIELD_ARG; class Settable_routine_parameter { public: /* Set required privileges for accessing the parameter. SYNOPSIS set_required_privilege() rw if 'rw' is true then we are going to read and set the parameter, so SELECT and UPDATE privileges might be required, otherwise we only reading it and SELECT privilege might be required. */ Settable_routine_parameter() = default; virtual ~Settable_routine_parameter() = default; virtual void set_required_privilege(bool rw) {}; /* Set parameter value. SYNOPSIS set_value() thd thread handle ctx context to which parameter belongs (if it is local variable). it item which represents new value RETURN FALSE if parameter value has been set, TRUE if error has occurred. */ virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it)= 0; virtual void set_out_param_info(Send_field *info) {} virtual const Send_field *get_out_param_info() const { return NULL; } virtual Item_param *get_item_param() { return 0; } }; /* A helper class to calculate offset and length of a query fragment - outside of SP - inside an SP - inside a compound block */ class Query_fragment { uint m_pos; uint m_length; void set(size_t pos, size_t length) { DBUG_ASSERT(pos < UINT_MAX32); DBUG_ASSERT(length < UINT_MAX32); m_pos= (uint) pos; m_length= (uint) length; } public: Query_fragment(THD *thd, sp_head *sphead, const char *start, const char *end); uint pos() const { return m_pos; } uint length() const { return m_length; } }; /** This is used for items in the query that needs to be rewritten before binlogging At the moment this applies to Item_param and Item_splocal */ class Rewritable_query_parameter { public: /* Offset inside the query text. Value of 0 means that this object doesn't have to be replaced (for example SP variables in control statements) */ my_ptrdiff_t pos_in_query; /* Byte length of parameter name in the statement. This is not Item::name.length because name.length contains byte length of UTF8-encoded name, but the query string is in the client charset. */ uint len_in_query; bool limit_clause_param; Rewritable_query_parameter(uint pos_in_q= 0, uint len_in_q= 0) : pos_in_query(pos_in_q), len_in_query(len_in_q), limit_clause_param(false) { } virtual ~Rewritable_query_parameter() = default; virtual bool append_for_log(THD *thd, String *str) = 0; }; class Copy_query_with_rewrite { THD *thd; const char *src; size_t src_len, from; String *dst; bool copy_up_to(size_t bytes) { DBUG_ASSERT(bytes >= from); return dst->append(src + from, uint32(bytes - from)); } public: Copy_query_with_rewrite(THD *t, const char *s, size_t l, String *d) :thd(t), src(s), src_len(l), from(0), dst(d) { } bool append(Rewritable_query_parameter *p) { if (copy_up_to(p->pos_in_query) || p->append_for_log(thd, dst)) return true; from= p->pos_in_query + p->len_in_query; return false; } bool finalize() { return copy_up_to(src_len); } }; struct st_dyncall_create_def { Item *key, *value; CHARSET_INFO *cs; uint len, frac; DYNAMIC_COLUMN_TYPE type; }; typedef struct st_dyncall_create_def DYNCALL_CREATE_DEF; typedef bool (Item::*Item_processor) (void *arg); /* Analyzer function SYNOPSIS argp in/out IN: Analysis parameter OUT: Parameter to be passed to the transformer RETURN TRUE Invoke the transformer FALSE Don't do it */ typedef bool (Item::*Item_analyzer) (uchar **argp); typedef Item* (Item::*Item_transformer) (THD *thd, uchar *arg); typedef void (*Cond_traverser) (const Item *item, void *arg); typedef bool (Item::*Pushdown_checker) (uchar *arg); struct st_cond_statistic; struct find_selective_predicates_list_processor_data { TABLE *table; List list; }; class MY_LOCALE; class Item_equal; class COND_EQUAL; class st_select_lex_unit; class Item_func_not; class Item_splocal; /** String_copier that sends Item specific warnings. */ class String_copier_for_item: public String_copier { THD *m_thd; public: bool copy_with_warn(CHARSET_INFO *dstcs, String *dst, CHARSET_INFO *srccs, const char *src, uint32 src_length, uint32 nchars); String_copier_for_item(THD *thd): m_thd(thd) { } }; /** A helper class describing what kind of Item created a temporary field. - If m_field is set, then the temporary field was created from Field (e.g. when the Item was Item_field, or Item_ref pointing to Item_field) - If m_default_field is set, then there is a usable DEFAULT value. (e.g. when the Item is Item_field) - If m_item_result_field is set, then the temporary field was created from certain sub-types of Item_result_field (e.g. Item_func) See create_tmp_field() in sql_select.cc for details. */ class Tmp_field_src { Field *m_field; Field *m_default_field; Item_result_field *m_item_result_field; public: Tmp_field_src() :m_field(0), m_default_field(0), m_item_result_field(0) { } Field *field() const { return m_field; } Field *default_field() const { return m_default_field; } Item_result_field *item_result_field() const { return m_item_result_field; } void set_field(Field *field) { m_field= field; } void set_default_field(Field *field) { m_default_field= field; } void set_item_result_field(Item_result_field *item) { m_item_result_field= item; } }; /** Parameters for create_tmp_field_ex(). See create_tmp_field() in sql_select.cc for details. */ class Tmp_field_param { bool m_group; bool m_modify_item; bool m_table_cant_handle_bit_fields; bool m_make_copy_field; public: Tmp_field_param(bool group, bool modify_item, bool table_cant_handle_bit_fields, bool make_copy_field) :m_group(group), m_modify_item(modify_item), m_table_cant_handle_bit_fields(table_cant_handle_bit_fields), m_make_copy_field(make_copy_field) { } bool group() const { return m_group; } bool modify_item() const { return m_modify_item; } bool table_cant_handle_bit_fields() const { return m_table_cant_handle_bit_fields; } bool make_copy_field() const { return m_make_copy_field; } void set_modify_item(bool to) { m_modify_item= to; } }; class Item_const { public: virtual ~Item_const() = default; virtual const Type_all_attributes *get_type_all_attributes_from_const() const= 0; virtual bool const_is_null() const { return false; } virtual const longlong *const_ptr_longlong() const { return NULL; } virtual const double *const_ptr_double() const { return NULL; } virtual const my_decimal *const_ptr_my_decimal() const { return NULL; } virtual const MYSQL_TIME *const_ptr_mysql_time() const { return NULL; } virtual const String *const_ptr_string() const { return NULL; } }; struct subselect_table_finder_param { THD *thd; /* We're searching for different TABLE_LIST objects referring to the same table as this one */ const TABLE_LIST *find; /* NUL - not found, ERROR_TABLE - search error, or the found table reference */ TABLE_LIST *dup; }; /****************************************************************************/ #define STOP_PTR ((void *) 1) /* Base flags (including IN) for an item */ typedef uint8 item_flags_t; enum class item_base_t : item_flags_t { NONE= 0, #define ITEM_FLAGS_MAYBE_NULL_SHIFT 0 // Must match MAYBE_NULL MAYBE_NULL= (1<<0), // May be NULL. IN_ROLLUP= (1<<1), // Appears in GROUP BY list // of a query with ROLLUP. FIXED= (1<<2), // Was fixed with fix_fields(). IS_EXPLICIT_NAME= (1<<3), // The name of this Item was set by the user // (or was auto generated otherwise) IS_IN_WITH_CYCLE= (1<<4), // This item is in CYCLE clause // of WITH. IS_COND= (1<<5) // The item is used as . // Must be evaluated using val_bool(). // Note, not all items used as a search // condition set this flag yet. }; /* Flags that tells us what kind of items the item contains */ enum class item_with_t : item_flags_t { NONE= 0, SP_VAR= (1<<0), // If Item contains a stored procedure variable WINDOW_FUNC= (1<<1), // If item contains a window func FIELD= (1<<2), // If any item except Item_sum contains a field. SUM_FUNC= (1<<3), // If item contains a sum func SUBQUERY= (1<<4), // If item containts a sub query ROWNUM_FUNC= (1<<5), // If ROWNUM function was used PARAM= (1<<6) // If user parameter was used }; /* Make operations in item_base_t and item_with_t work like 'int' */ static inline item_base_t operator&(const item_base_t a, const item_base_t b) { return (item_base_t) (((item_flags_t) a) & ((item_flags_t) b)); } static inline item_base_t & operator&=(item_base_t &a, item_base_t b) { a= (item_base_t) (((item_flags_t) a) & (item_flags_t) b); return a; } static inline item_base_t operator|(const item_base_t a, const item_base_t b) { return (item_base_t) (((item_flags_t) a) | ((item_flags_t) b)); } static inline item_base_t & operator|=(item_base_t &a, item_base_t b) { a= (item_base_t) (((item_flags_t) a) | (item_flags_t) b); return a; } static inline item_base_t operator~(const item_base_t a) { return (item_base_t) ~(item_flags_t) a; } static inline item_with_t operator&(const item_with_t a, const item_with_t b) { return (item_with_t) (((item_flags_t) a) & ((item_flags_t) b)); } static inline item_with_t & operator&=(item_with_t &a, item_with_t b) { a= (item_with_t) (((item_flags_t) a) & (item_flags_t) b); return a; } static inline item_with_t operator|(const item_with_t a, const item_with_t b) { return (item_with_t) (((item_flags_t) a) | ((item_flags_t) b)); } static inline item_with_t & operator|=(item_with_t &a, item_with_t b) { a= (item_with_t) (((item_flags_t) a) | (item_flags_t) b); return a; } static inline item_with_t operator~(const item_with_t a) { return (item_with_t) ~(item_flags_t) a; } class Item :public Value_source, public Type_all_attributes { static void *operator new(size_t size); public: static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); } static void operator delete(void *ptr, MEM_ROOT *mem_root) {} enum Type {FIELD_ITEM= 0, FUNC_ITEM, SUM_FUNC_ITEM, WINDOW_FUNC_ITEM, /* NOT NULL literal-alike constants, which do not change their value during an SQL statement execution, but can optionally change their value between statements: - Item_literal - real NOT NULL constants - Item_param - can change between statements - Item_splocal - can change between statements - Item_user_var_as_out_param - hack Note, Item_user_var_as_out_param actually abuses the type code. It should be moved out of the Item tree eventually. */ CONST_ITEM, NULL_ITEM, // Item_null or Item_param bound to NULL COPY_STR_ITEM, FIELD_AVG_ITEM, DEFAULT_VALUE_ITEM, CONTEXTUALLY_TYPED_VALUE_ITEM, PROC_ITEM,COND_ITEM, REF_ITEM, FIELD_STD_ITEM, FIELD_VARIANCE_ITEM, INSERT_VALUE_ITEM, SUBSELECT_ITEM, ROW_ITEM, CACHE_ITEM, TYPE_HOLDER, PARAM_ITEM, TRIGGER_FIELD_ITEM, EXPR_CACHE_ITEM}; enum cond_result { COND_UNDEF,COND_OK,COND_TRUE,COND_FALSE }; enum traverse_order { POSTFIX, PREFIX }; protected: SEL_TREE *get_mm_tree_for_const(RANGE_OPT_PARAM *param); /** Create a field based on the exact data type handler. */ Field *create_table_field_from_handler(MEM_ROOT *root, TABLE *table) { const Type_handler *h= type_handler(); return h->make_and_init_table_field(root, &name, Record_addr(maybe_null()), *this, table); } /** Create a field based on field_type of argument. This is used to create a field for - IFNULL(x,something) - time functions - prepared statement placeholders - SP variables with data type references: DECLARE a TYPE OF t1.a; @retval NULL error @retval !NULL on success */ Field *tmp_table_field_from_field_type(MEM_ROOT *root, TABLE *table) { DBUG_ASSERT(fixed()); const Type_handler *h= type_handler()->type_handler_for_tmp_table(this); return h->make_and_init_table_field(root, &name, Record_addr(maybe_null()), *this, table); } /** Create a temporary field for a simple Item, which does not need any special action after the field creation: - is not an Item_field descendant (and not a reference to Item_field) - is not an Item_result_field descendant - does not need to copy any DEFAULT value to the result Field - does not need to set Field::is_created_from_null_item for the result See create_tmp_field_ex() for details on parameters and return values. */ Field *create_tmp_field_ex_simple(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) { DBUG_ASSERT(!param->make_copy_field()); DBUG_ASSERT(!is_result_field()); DBUG_ASSERT(type() != NULL_ITEM); return tmp_table_field_from_field_type(root, table); } Field *create_tmp_field_int(MEM_ROOT *root, TABLE *table, uint convert_int_length); Field *tmp_table_field_from_field_type_maybe_null(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param, bool is_explicit_null); virtual void raise_error_not_evaluable(); void push_note_converted_to_negative_complement(THD *thd); void push_note_converted_to_positive_complement(THD *thd); /* Helper methods, to get an Item value from another Item */ double val_real_from_item(Item *item) { DBUG_ASSERT(fixed()); double value= item->val_real(); null_value= item->null_value; return value; } longlong val_int_from_item(Item *item) { DBUG_ASSERT(fixed()); longlong value= item->val_int(); null_value= item->null_value; return value; } String *val_str_from_item(Item *item, String *str) { DBUG_ASSERT(fixed()); String *res= item->val_str(str); if (res) res->set_charset(collation.collation); if ((null_value= item->null_value)) res= NULL; return res; } bool val_native_from_item(THD *thd, Item *item, Native *to) { DBUG_ASSERT(fixed()); null_value= item->val_native(thd, to); DBUG_ASSERT(null_value == item->null_value); return null_value; } bool val_native_from_field(Field *field, Native *to) { if ((null_value= field->is_null())) return true; return (null_value= field->val_native(to)); } bool val_native_with_conversion_from_item(THD *thd, Item *item, Native *to, const Type_handler *handler) { DBUG_ASSERT(fixed()); return (null_value= item->val_native_with_conversion(thd, to, handler)); } my_decimal *val_decimal_from_item(Item *item, my_decimal *decimal_value) { DBUG_ASSERT(fixed()); my_decimal *value= item->val_decimal(decimal_value); if ((null_value= item->null_value)) value= NULL; return value; } bool get_date_from_item(THD *thd, Item *item, MYSQL_TIME *ltime, date_mode_t fuzzydate) { bool rc= item->get_date(thd, ltime, fuzzydate); null_value= MY_TEST(rc || item->null_value); return rc; } public: /* Cache val_str() into the own buffer, e.g. to evaluate constant expressions with subqueries in the ORDER/GROUP clauses. */ String *val_str() { return val_str(&str_value); } String *val_str_null_to_empty(String *to) { String *res= val_str(to); if (res) return res; to->set_charset(collation.collation); to->length(0); return to; } String *val_str_null_to_empty(String *to, bool null_to_empty) { return null_to_empty ? val_str_null_to_empty(to) : val_str(to); } virtual Item_func *get_item_func() { return NULL; } const MY_LOCALE *locale_from_val_str(); /* All variables for the Item class */ /** Intrusive list pointer for free list. If not null, points to the next Item on some Query_arena's free list. For instance, stored procedures have their own Query_arena's. @see Query_arena::free_list */ Item *next; /* str_values's main purpose is to be used to cache the value in save_in_field. Calling full_name() for Item_field will also use str_value. */ String str_value; LEX_CSTRING name; /* Name of item */ /* Original item name (if it was renamed)*/ const char *orig_name; /* All common bool variables for an Item is stored here */ item_base_t base_flags; item_with_t with_flags; /* Marker is used in some functions to temporary mark an item */ int16 marker; /* Tells is the val() value of the item is/was null. This should not be part of the bit flags as it's changed a lot and also we use pointers to it */ bool null_value; /* Cache of the result of is_expensive(). */ int8 is_expensive_cache; /** The index in the JOIN::join_tab array of the JOIN_TAB this Item is attached to. Items are attached (or 'pushed') to JOIN_TABs during optimization by the make_cond_for_table procedure. During query execution, this item is evaluated when the join loop reaches the corresponding JOIN_TAB. If the value of join_tab_idx >= MAX_TABLES, this means that there is no corresponding JOIN_TAB. */ uint8 join_tab_idx; inline bool maybe_null() const { return (bool) (base_flags & item_base_t::MAYBE_NULL); } inline bool in_rollup() const { return (bool) (base_flags & item_base_t::IN_ROLLUP); } inline bool fixed() const { return (bool) (base_flags & item_base_t::FIXED); } inline bool is_explicit_name() const { return (bool) (base_flags & item_base_t::IS_EXPLICIT_NAME); } inline bool is_in_with_cycle() const { return (bool) (base_flags & item_base_t::IS_IN_WITH_CYCLE); } inline bool is_cond() const { return (bool) (base_flags & item_base_t::IS_COND); } inline bool with_sp_var() const { return (bool) (with_flags & item_with_t::SP_VAR); } inline bool with_window_func() const { return (bool) (with_flags & item_with_t::WINDOW_FUNC); } inline bool with_field() const { return (bool) (with_flags & item_with_t::FIELD); } inline bool with_sum_func() const { return (bool) (with_flags & item_with_t::SUM_FUNC); } inline bool with_subquery() const { return (bool) (with_flags & item_with_t::SUBQUERY); } inline bool with_rownum_func() const { return (bool) (with_flags & item_with_t::ROWNUM_FUNC); } inline bool with_param() const { return (bool) (with_flags & item_with_t::PARAM); } inline void copy_flags(const Item *org, item_base_t mask) { base_flags= (item_base_t) (((item_flags_t) base_flags & ~(item_flags_t) mask) | ((item_flags_t) org->base_flags & (item_flags_t) mask)); } inline void copy_flags(const Item *org, item_with_t mask) { with_flags= (item_with_t) (((item_flags_t) with_flags & ~(item_flags_t) mask) | ((item_flags_t) org->with_flags & (item_flags_t) mask)); } // alloc & destruct is done as start of select on THD::mem_root Item(THD *thd); /* Constructor used by Item_field, Item_ref & aggregate (sum) functions. Used for duplicating lists in processing queries with temporary tables Also it used for Item_cond_and/Item_cond_or for creating top AND/OR structure of WHERE clause to protect it of optimisation changes in prepared statements */ Item(THD *thd, Item *item); Item(); /* For const item */ virtual ~Item() { #ifdef EXTRA_DEBUG name.str= 0; name.length= 0; #endif } /*lint -e1509 */ void set_name(THD *thd, const char *str, size_t length, CHARSET_INFO *cs); void set_name(THD *thd, String *str) { set_name(thd, str->ptr(), str->length(), str->charset()); } void set_name(THD *thd, const LEX_CSTRING &str, CHARSET_INFO *cs= system_charset_info) { set_name(thd, str.str, str.length, cs); } void set_name_no_truncate(THD *thd, const char *str, uint length, CHARSET_INFO *cs); void init_make_send_field(Send_field *tmp_field, const Type_handler *h); void share_name_with(const Item *item) { name= item->name; copy_flags(item, item_base_t::IS_EXPLICIT_NAME); } virtual void cleanup(); virtual void make_send_field(THD *thd, Send_field *field); bool fix_fields_if_needed(THD *thd, Item **ref) { return fixed() ? false : fix_fields(thd, ref); } /* fix_fields_if_needed_for_scalar() is used where we need to filter items that can't be scalars and want to return error for it. */ bool fix_fields_if_needed_for_scalar(THD *thd, Item **ref) { return fix_fields_if_needed(thd, ref) || check_cols(1); } bool fix_fields_if_needed_for_bool(THD *thd, Item **ref) { return fix_fields_if_needed_for_scalar(thd, ref); } bool fix_fields_if_needed_for_order_by(THD *thd, Item **ref) { return fix_fields_if_needed_for_scalar(thd, ref); } /* By default we assume that an Item is fixed by the constructor */ virtual bool fix_fields(THD *, Item **) { /* This should not normally be called, because usually before fix_fields() we check fixed() to be false. But historically we allow fix_fields() to be called for Items who return basic_const_item()==true. */ DBUG_ASSERT(fixed()); DBUG_ASSERT(basic_const_item()); return false; } virtual void unfix_fields() { DBUG_ASSERT(0); } /* Fix after some tables has been pulled out. Basically re-calculate all attributes that are dependent on the tables. */ virtual void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) {}; /* This is for items that require a fixup after the JOIN::prepare() is done. */ virtual void fix_after_optimize(THD *thd) {} /* This method should be used in case where we are sure that we do not need complete fix_fields() procedure. Usually this method is used by the optimizer when it has to create a new item out of other already fixed items. For example, if the optimizer has to create a new Item_func for an inferred equality whose left and right parts are already fixed items. In some cases the optimizer cannot use directly fixed items as the arguments of the created functional item, but rather uses intermediate type conversion items. Then the method is supposed to be applied recursively. */ virtual void quick_fix_field() { DBUG_ASSERT(0); } bool save_in_value(THD *thd, st_value *value) { return type_handler()->Item_save_in_value(thd, this, value); } /* Function returns 1 on overflow and -1 on fatal errors */ int save_in_field_no_warnings(Field *field, bool no_conversions); virtual int save_in_field(Field *field, bool no_conversions); virtual bool save_in_param(THD *thd, Item_param *param); virtual void save_org_in_field(Field *field, fast_field_copier data __attribute__ ((__unused__))) { (void) save_in_field(field, 1); } virtual fast_field_copier setup_fast_field_copier(Field *field) { return NULL; } virtual int save_safe_in_field(Field *field) { return save_in_field(field, 1); } virtual bool send(Protocol *protocol, st_value *buffer) { return type_handler()->Item_send(this, protocol, buffer); } virtual bool eq(const Item *, bool binary_cmp) const; enum_field_types field_type() const { return type_handler()->field_type(); } virtual const Type_handler *type_handler() const= 0; /** Detects if an Item has a fixed data type which is known even before fix_fields(). Currently it's important only to find Items with a fixed boolean data type. More item types can be marked in the future as having a fixed data type (e.g. all literals, all fixed type functions, etc). @retval NULL if the Item type is not known before fix_fields() @retval the pointer to the data type handler, if the data type is known before fix_fields(). */ virtual const Type_handler *fixed_type_handler() const { return NULL; } const Type_handler *type_handler_for_comparison() const { return type_handler()->type_handler_for_comparison(); } virtual const Type_handler *real_type_handler() const { return type_handler(); } const Type_handler *cast_to_int_type_handler() const { return real_type_handler()->cast_to_int_type_handler(); } /* result_type() of an item specifies how the value should be returned */ Item_result result_type() const { return type_handler()->result_type(); } /* ... while cmp_type() specifies how it should be compared */ Item_result cmp_type() const { return type_handler()->cmp_type(); } const Type_handler *string_type_handler() const { return Type_handler::string_type_handler(max_length); } /* Calculate the maximum length of an expression. This method is used in data type aggregation for UNION, e.g.: SELECT 'b' UNION SELECT COALESCE(double_10_3_field) FROM t1; The result is usually equal to max_length, except for some numeric types. In case of the INT, FLOAT, DOUBLE data types Item::max_length and Item::decimals are ignored, so the returned value depends only on the data type itself. E.g. for an expression of the DOUBLE(10,3) data type, the result is always 53 (length 10 and precision 3 do not matter). max_length is ignored for these numeric data types because the length limit means only "expected maximum length", it is not a hard limit, so it does not impose any data truncation. E.g. a column of the type INT(4) can normally store big values up to 2147483647 without truncation. When we're aggregating such column for UNION it's important to create a long enough result column, not to lose any data. For detailed behaviour of various data types see implementations of the corresponding Type_handler_xxx::max_display_length(). Note, Item_field::max_display_length() overrides this to get max_display_length() from the underlying field. */ virtual uint32 max_display_length() const { return type_handler()->max_display_length(this); } const TYPELIB *get_typelib() const override { return NULL; } /* optimized setting of maybe_null without jumps. Minimizes code size */ inline void set_maybe_null(bool maybe_null_arg) { base_flags= ((item_base_t) ((base_flags & ~item_base_t::MAYBE_NULL)) | (item_base_t) (maybe_null_arg << ITEM_FLAGS_MAYBE_NULL_SHIFT)); } /* This is used a lot, so make it simpler to use */ void set_maybe_null() { base_flags|= item_base_t::MAYBE_NULL; } /* This is used when calling Type_all_attributes::set_type_maybe_null() */ void set_type_maybe_null(bool maybe_null_arg) override { set_maybe_null(maybe_null_arg); } void set_typelib(const TYPELIB *typelib) override { // Non-field Items (e.g. hybrid functions) never have ENUM/SET types yet. DBUG_ASSERT(0); } Item_cache* get_cache(THD *thd) const { return type_handler()->Item_get_cache(thd, this); } virtual enum Type type() const =0; bool is_of_type(Type t, Item_result cmp) const { return type() == t && cmp_type() == cmp; } /* real_type() is the type of base item. This is same as type() for most items, except Item_ref() and Item_cache_wrapper() where it shows the type for the underlying item. */ virtual enum Type real_type() const { return type(); } /* Return information about function monotonicity. See comment for enum_monotonicity_info for details. This function can only be called after fix_fields() call. */ virtual enum_monotonicity_info get_monotonicity_info() const { return NON_MONOTONIC; } /* Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$ const2" SYNOPSIS val_int_endpoint() left_endp FALSE <=> The interval is "x < const" or "x <= const" TRUE <=> The interval is "x > const" or "x >= const" incl_endp IN FALSE <=> the comparison is '<' or '>' TRUE <=> the comparison is '<=' or '>=' OUT The same but for the "F(x) $CMP$ F(const)" comparison DESCRIPTION This function is defined only for unary monotonic functions. The caller supplies the source half-interval x $CMP$ const The value of const is supplied implicitly as the value this item's argument, the form of $CMP$ comparison is specified through the function's arguments. The calle returns the result interval F(x) $CMP2$ F(const) passing back F(const) as the return value, and the form of $CMP2$ through the out parameter. NULL values are assumed to be comparable and be less than any non-NULL values. RETURN The output range bound, which equal to the value of val_int() - If the value of the function is NULL then the bound is the smallest possible value of LONGLONG_MIN */ virtual longlong val_int_endpoint(bool left_endp, bool *incl_endp) { DBUG_ASSERT(0); return 0; } /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */ /* Return double precision floating point representation of item. SYNOPSIS val_real() RETURN In case of NULL value return 0.0 and set null_value flag to TRUE. If value is not null null_value flag will be reset to FALSE. */ virtual double val_real()=0; Double_null to_double_null() { // val_real() must be caleed on a separate line. See to_longlong_null() double nr= val_real(); return Double_null(nr, null_value); } /* Return integer representation of item. SYNOPSIS val_int() RETURN In case of NULL value return 0 and set null_value flag to TRUE. If value is not null null_value flag will be reset to FALSE. */ virtual longlong val_int()=0; Longlong_hybrid to_longlong_hybrid() { return Longlong_hybrid(val_int(), unsigned_flag); } Longlong_null to_longlong_null() { longlong nr= val_int(); /* C++ does not guarantee the order of parameter evaluation, so to make sure "null_value" is passed to the constructor after the val_int() call, val_int() is caled on a separate line. */ return Longlong_null(nr, null_value); } Longlong_hybrid_null to_longlong_hybrid_null() { return Longlong_hybrid_null(to_longlong_null(), unsigned_flag); } /** Get a value for CAST(x AS SIGNED). Too large positive unsigned integer values are converted to negative complements. Values of non-integer data types are adjusted to the SIGNED range. */ virtual longlong val_int_signed_typecast() { return cast_to_int_type_handler()->Item_val_int_signed_typecast(this); } longlong val_int_signed_typecast_from_str(); /** Get a value for CAST(x AS UNSIGNED). Negative signed integer values are converted to positive complements. Values of non-integer data types are adjusted to the UNSIGNED range. */ virtual longlong val_int_unsigned_typecast() { return cast_to_int_type_handler()->Item_val_int_unsigned_typecast(this); } longlong val_int_unsigned_typecast_from_int(); longlong val_int_unsigned_typecast_from_str(); longlong val_int_unsigned_typecast_from_real(); /** Get a value for CAST(x AS UNSIGNED). Huge positive unsigned values are converted to negative complements. */ longlong val_int_signed_typecast_from_int(); longlong val_int_signed_typecast_from_real(); /* This is just a shortcut to avoid the cast. You should still use unsigned_flag to check the sign of the item. */ inline ulonglong val_uint() { return (ulonglong) val_int(); } virtual bool hash_not_null(Hasher *hasher) { DBUG_ASSERT(0); return true; } /* Return string representation of this item object. SYNOPSIS val_str() str an allocated buffer this or any nested Item object can use to store return value of this method. NOTE The caller can modify the returned String, if it's not marked "const" (with the String::mark_as_const() method). That means that if the item returns its own internal buffer (e.g. tmp_value), it *must* be marked "const" [1]. So normally it's preferable to return the result value in the String, that was passed as an argument. But, for example, SUBSTR() returns a String that simply points into the buffer of SUBSTR()'s args[0]->val_str(). Such a String is always "const", so it's ok to use tmp_value for that and avoid reallocating/copying of the argument String. [1] consider SELECT CONCAT(f, ":", f) FROM (SELECT func() AS f); here the return value of f() is used twice in the top-level select, and if they share the same tmp_value buffer, modifying the first one will implicitly modify the second too. RETURN In case of NULL value return 0 (NULL pointer) and set null_value flag to TRUE. If value is not null null_value flag will be reset to FALSE. */ virtual String *val_str(String *str)=0; bool val_native_with_conversion(THD *thd, Native *to, const Type_handler *th) { return th->Item_val_native_with_conversion(thd, this, to); } bool val_native_with_conversion_result(THD *thd, Native *to, const Type_handler *th) { return th->Item_val_native_with_conversion_result(thd, this, to); } virtual bool val_native(THD *thd, Native *to) { /* The default implementation for the Items that do not need native format: - Item_basic_value (default implementation) - Item_copy - Item_exists_subselect - Item_sum_field - Item_sum_or_func (default implementation) - Item_proc - Item_type_holder (as val_xxx() are never called for it); These hybrid Item types override val_native(): - Item_field - Item_param - Item_sp_variable - Item_ref - Item_cache_wrapper - Item_direct_ref - Item_direct_view_ref - Item_ref_null_helper - Item_name_const - Item_time_literal - Item_sum_or_func Note, these hybrid type Item_sum_or_func descendants override the default implementation: * Item_sum_hybrid * Item_func_hybrid_field_type * Item_func_min_max * Item_func_sp * Item_func_last_value * Item_func_rollup_const */ DBUG_ASSERT(0); return (null_value= 1); } virtual bool val_native_result(THD *thd, Native *to) { return val_native(thd, to); } /* Returns string representation of this item in ASCII format. SYNOPSIS val_str_ascii() str - similar to val_str(); NOTE This method is introduced for performance optimization purposes. 1. val_str() result of some Items in string context depends on @@character_set_results. @@character_set_results can be set to a "real multibyte" character set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples below for convenience.) So the default string result of such functions in these circumstances is real multi-byte character set, like UTF32. For example, all numbers in string context return result in @@character_set_results: SELECT CONCAT(20010101); -> UTF32 We do sprintf() first (to get ASCII representation) and then convert to UTF32; So these kind "data sources" can use ASCII representation internally, but return multi-byte data only because @@character_set_results wants so. Therefore, conversion from ASCII to UTF32 is applied internally. 2. Some other functions need in fact ASCII input. For example, inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT(). Similar, fields of certain type, like DATE, TIME, when you insert string data into them, expect in fact ASCII input. If they get non-ASCII input, for example UTF32, they convert input from UTF32 to ASCII, and then use ASCII representation to do further processing. 3. Now imagine we pass result of a data source of the first type to a data destination of the second type. What happens: a. data source converts data from ASCII to UTF32, because @@character_set_results wants so and passes the result to data destination. b. data destination gets UTF32 string. c. data destination converts UTF32 string to ASCII, because it needs ASCII representation to be able to handle data correctly. As a result we get two steps of unnecessary conversion: From ASCII to UTF32, then from UTF32 to ASCII. A better way to handle these situations is to pass ASCII representation directly from the source to the destination. This is why val_str_ascii() introduced. RETURN Similar to val_str() */ virtual String *val_str_ascii(String *str); /* Returns the result of val_str_ascii(), translating NULLs back to empty strings (if MODE_EMPTY_STRING_IS_NULL is set). */ String *val_str_ascii_revert_empty_string_is_null(THD *thd, String *str); /* Returns the val_str() value converted to the given character set. */ String *val_str(String *str, String *converter, CHARSET_INFO *to); virtual String *val_json(String *str) { return val_str(str); } /* Return decimal representation of item with fixed point. SYNOPSIS val_decimal() decimal_buffer buffer which can be used by Item for returning value (but can be not) NOTE Returned value should not be changed if it is not the same which was passed via argument. RETURN Return pointer on my_decimal (it can be other then passed via argument) if value is not NULL (null_value flag will be reset to FALSE). In case of NULL value it return 0 pointer and set null_value flag to TRUE. */ virtual my_decimal *val_decimal(my_decimal *decimal_buffer)= 0; /* Return boolean value of item. RETURN FALSE value is false or NULL TRUE value is true (not equal to 0) */ virtual bool val_bool() { return type_handler()->Item_val_bool(this); } bool eval_const_cond() { DBUG_ASSERT(const_item()); DBUG_ASSERT(!is_expensive()); return val_bool(); } bool can_eval_in_optimize() { return const_item() && !is_expensive(); } /* save_val() is method of val_* family which stores value in the given field. */ virtual void save_val(Field *to) { save_org_in_field(to, NULL); } /* save_result() is method of val*result() family which stores value in the given field. */ virtual void save_result(Field *to) { save_val(to); } /* Helper functions, see item_sum.cc */ String *val_string_from_real(String *str); String *val_string_from_int(String *str); my_decimal *val_decimal_from_real(my_decimal *decimal_value); my_decimal *val_decimal_from_int(my_decimal *decimal_value); my_decimal *val_decimal_from_string(my_decimal *decimal_value); longlong val_int_from_real() { DBUG_ASSERT(fixed()); return Converter_double_to_longlong_with_warn(val_real(), false).result(); } longlong val_int_from_str(int *error); /* Returns true if this item can be calculated during value_depends_on_sql_mode() */ bool value_depends_on_sql_mode_const_item() { /* Currently we use value_depends_on_sql_mode() only for virtual column expressions. They should not contain any expensive items. If we ever get a crash on the assert below, it means check_vcol_func_processor() is badly implemented for this item. */ DBUG_ASSERT(!is_expensive()); /* It should return const_item() actually. But for some reasons Item_field::const_item() returns true at value_depends_on_sql_mode() call time. This should be checked and fixed. */ return basic_const_item(); } virtual Sql_mode_dependency value_depends_on_sql_mode() const { return Sql_mode_dependency(); } int save_time_in_field(Field *field, bool no_conversions); int save_date_in_field(Field *field, bool no_conversions); int save_str_in_field(Field *field, bool no_conversions); int save_real_in_field(Field *field, bool no_conversions); int save_int_in_field(Field *field, bool no_conversions); int save_bool_in_field(Field *field, bool no_conversions); int save_decimal_in_field(Field *field, bool no_conversions); int save_str_value_in_field(Field *field, String *result); virtual Field *get_tmp_table_field() { return 0; } virtual Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table); inline const char *full_name() const { return full_name_cstring().str; } virtual LEX_CSTRING full_name_cstring() const { if (name.str) return name; return { STRING_WITH_LEN("???") }; } const char *field_name_or_null() { return real_item()->type() == Item::FIELD_ITEM ? name.str : NULL; } const TABLE_SHARE *field_table_or_null(); /* *result* family of methods is analog of *val* family (see above) but return value of result_field of item if it is present. If Item have not result field, it return val(). This methods set null_value flag in same way as *val* methods do it. */ virtual double val_result() { return val_real(); } virtual longlong val_int_result() { return val_int(); } virtual String *str_result(String* tmp) { return val_str(tmp); } virtual my_decimal *val_decimal_result(my_decimal *val) { return val_decimal(val); } virtual bool val_bool_result() { return val_bool(); } virtual bool is_null_result() { return is_null(); } /* Returns 1 if result type and collation for val_str() can change between calls */ virtual bool dynamic_result() { return 0; } /* Bitmap of tables used by item (note: if you need to check dependencies on individual columns, check out class Field_enumerator) */ virtual table_map used_tables() const { return (table_map) 0L; } virtual table_map all_used_tables() const { return used_tables(); } /* Return table map of tables that can't be NULL tables (tables that are used in a context where if they would contain a NULL row generated by a LEFT or RIGHT join, the item would not be true). This expression is used on WHERE item to determinate if a LEFT JOIN can be converted to a normal join. Generally this function should return used_tables() if the function would return null if any of the arguments are null As this is only used in the beginning of optimization, the value don't have to be updated in update_used_tables() */ virtual table_map not_null_tables() const { return used_tables(); } /* Returns true if this is a simple constant item like an integer, not a constant expression. Used in the optimizer to propagate basic constants. */ virtual bool basic_const_item() const { return 0; } /** Determines if the expression is allowed as a virtual column assignment source: INSERT INTO t1 (vcol) VALUES (10) -> error INSERT INTO t1 (vcol) VALUES (NULL) -> ok */ virtual bool vcol_assignment_allowed_value() const { return false; } /** Test if "this" is an ORDER position (rather than an expression). Notes: - can be called before fix_fields(). - local SP variables (even of integer types) are always expressions, not positions. (And they can't be used before fix_fields is called for them). */ virtual bool is_order_clause_position() const { return false; } /* Determines if the Item is an evaluable expression, that is it can return a value, so we can call methods val_xxx(), get_date(), etc. Most items are evaluable expressions. Examples of non-evaluable expressions: - Item_contextually_typed_value_specification (handling DEFAULT and IGNORE) - Item_type_param bound to DEFAULT and IGNORE We cannot call the mentioned methods for these Items, their method implementations typically have DBUG_ASSERT(0). */ virtual bool is_evaluable_expression() const { return true; } /** * Check whether the item is a parameter ('?') of stored routine. * Default implementation returns false. Method is overridden in the class * Item_param where it returns true. */ virtual bool is_stored_routine_parameter() const { return false; } bool check_is_evaluable_expression_or_error() { if (is_evaluable_expression()) return false; // Ok raise_error_not_evaluable(); return true; // Error } /* Create a shallow copy of the item (usually invoking copy constructor). For deep copying see build_clone(). Return value: - pointer to a copy of the Item - nullptr if the item is not copyable */ Item *get_copy(THD *thd) const { Item *copy= do_get_copy(thd); if (copy) { // Make sure the copy is of same type as this item DBUG_ASSERT(typeid(*copy) == typeid(*this)); } return copy; } /* Creates a clone of the item by deep copying. Return value: - pointer to a clone of the Item - nullptr if the item is not clonable */ Item* build_clone(THD *thd) const { Item *clone= do_build_clone(thd); if (clone) { // Make sure the clone is of same type as this item DBUG_ASSERT(typeid(*clone) == typeid(*this)); } return clone; } /* Clones the constant item (not necessary returning the same item type) Return value: - pointer to a clone of the Item - nullptr if the item is not clonable Note: the clone may have item type different from this (i.e., instance of another basic constant class may be returned). For real clones look at build_clone()/get_copy() methods */ virtual Item *clone_item(THD *thd) const { return nullptr; } virtual cond_result eq_cmp_result() const { return COND_OK; } inline uint float_length(uint decimals_par) const { return decimals < FLOATING_POINT_DECIMALS ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;} /* Returns total number of decimal digits */ decimal_digits_t decimal_precision() const override { return type_handler()->Item_decimal_precision(this); } /* Returns the number of integer part digits only */ inline decimal_digits_t decimal_int_part() const { return (decimal_digits_t) my_decimal_int_part(decimal_precision(), decimals); } /* Returns the number of fractional digits only. NOT_FIXED_DEC is replaced to the maximum possible number of fractional digits, taking into account the data type. */ decimal_digits_t decimal_scale() const { return type_handler()->Item_decimal_scale(this); } /* Returns how many digits a divisor adds into a division result. This is important when the integer part of the divisor can be 0. In this example: SELECT 1 / 0.000001; -> 1000000.0000 the divisor adds 5 digits into the result precision. Currently this method only replaces NOT_FIXED_DEC to TIME_SECOND_PART_DIGITS for temporal data types. This method can be made virtual, to create more efficient (smaller) data types for division results. For example, in SELECT 1/1.000001; the divisor could provide no additional precision into the result, so could any other items that are know to return a result with non-zero integer part. */ uint divisor_precision_increment() const { return type_handler()->Item_divisor_precision_increment(this); } /** TIME or DATETIME precision of the item: 0..6 */ uint time_precision(THD *thd) { return const_item() ? type_handler()->Item_time_precision(thd, this) : MY_MIN(decimals, TIME_SECOND_PART_DIGITS); } uint datetime_precision(THD *thd) { return const_item() ? type_handler()->Item_datetime_precision(thd, this) : MY_MIN(decimals, TIME_SECOND_PART_DIGITS); } virtual longlong val_int_min() const { return LONGLONG_MIN; } /* Returns true if this is constant (during query execution, i.e. its value will not change until next fix_fields) and its value is known. */ virtual bool const_item() const { return used_tables() == 0; } /* Returns true if this is constant but its value may be not known yet. (Can be used for parameters of prep. stmts or of stored procedures.) */ virtual bool const_during_execution() const { return (used_tables() & ~PARAM_TABLE_BIT) == 0; } /** This method is used for to: - to generate a view definition query (SELECT-statement); - to generate a SQL-query for EXPLAIN EXTENDED; - to generate a SQL-query to be shown in INFORMATION_SCHEMA; - debug. For more information about view definition query, INFORMATION_SCHEMA query and why they should be generated from the Item-tree, @see mysql_register_view(). */ virtual enum precedence precedence() const { return DEFAULT_PRECEDENCE; } enum precedence higher_precedence() const { return (enum precedence)(precedence() + 1); } void print_parenthesised(String *str, enum_query_type query_type, enum precedence parent_prec); /** This helper is used to print expressions as a part of a table definition, in particular for - generated columns - check constraints - default value expressions - partitioning expressions */ void print_for_table_def(String *str) { print_parenthesised(str, (enum_query_type)(QT_ITEM_ORIGINAL_FUNC_NULLIF | QT_ITEM_IDENT_SKIP_DB_NAMES | QT_ITEM_IDENT_SKIP_TABLE_NAMES | QT_NO_DATA_EXPANSION | QT_TO_SYSTEM_CHARSET | QT_FOR_FRM), LOWEST_PRECEDENCE); } virtual void print(String *str, enum_query_type query_type); class Print: public String { public: Print(Item *item, enum_query_type type) { item->print(this, type); } }; void print_item_w_name(String *str, enum_query_type query_type); void print_value(String *str); virtual void update_used_tables() {} virtual COND *build_equal_items(THD *thd, COND_EQUAL *inheited, bool link_item_fields, COND_EQUAL **cond_equal_ref) { update_used_tables(); DBUG_ASSERT(!cond_equal_ref || !cond_equal_ref[0]); return this; } virtual COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, bool top_level); virtual void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) { return; } /* Make a select tree for all keys in a condition or a condition part @param param Context @param cond_ptr[OUT] Store a replacement item here if the condition can be simplified, e.g.: WHERE part1 OR part2 OR part3 with one of the partN evaluating to SEL_TREE::ALWAYS. */ virtual SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr); /* Checks whether the item is: - a simple equality (field=field_item or field=constant_item), or - a row equality and form multiple equality predicates. */ virtual bool check_equality(THD *thd, COND_EQUAL *cond, List *eq_list) { return false; } virtual void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) {} /* Called for items that really have to be split */ void split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, Item **ref, uint flags); virtual bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)= 0; bool get_date_from_int(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); bool get_date_from_real(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); bool get_date_from_string(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate); bool get_time(THD *thd, MYSQL_TIME *ltime) { return get_date(thd, ltime, Time::Options(thd)); } // Get a DATE or DATETIME value in numeric packed format for comparison virtual longlong val_datetime_packed(THD *thd) { return Datetime(thd, this, Datetime::Options_cmp(thd)).to_packed(); } // Get a TIME value in numeric packed format for comparison virtual longlong val_time_packed(THD *thd) { return Time(thd, this, Time::Options_cmp(thd)).to_packed(); } longlong val_datetime_packed_result(THD *thd); longlong val_time_packed_result(THD *thd); virtual bool get_date_result(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) { return get_date(thd, ltime,fuzzydate); } /* The method allows to determine nullness of a complex expression without fully evaluating it, instead of calling val/result*() then checking null_value. Used in Item_func_isnull/Item_func_isnotnull and Item_sum_count. Any new item which can be NULL must implement this method. */ virtual bool is_null() { return 0; } /* Make sure the null_value member has a correct value. */ virtual void update_null_value () { return type_handler()->Item_update_null_value(this); } /* Inform the item that there will be no distinction between its result being FALSE or NULL. NOTE This function will be called for eg. Items that are top-level AND-parts of the WHERE clause. Items implementing this function (currently Item_cond_and and subquery-related item) enable special optimizations when they are "top level". */ virtual void top_level_item() {} /* Return TRUE if it is item of top WHERE level (AND/OR) and it is important, return FALSE if it not important (we can not use to simplify calculations) or not top level */ virtual bool is_top_level_item() const { return FALSE; /* not important */} /* return IN/ALL/ANY subquery or NULL */ virtual Item_in_subselect* get_IN_subquery() { return NULL; /* in is not IN/ALL/ANY */ } /* set field of temporary table for Item which can be switched on temporary table during query processing (grouping and so on) */ virtual bool is_result_field() { return 0; } virtual bool is_bool_literal() const { return false; } /* This is to handle printing of default values */ virtual bool need_parentheses_in_default() { return false; } virtual void save_in_result_field(bool no_conversions) {} /* Data type format implied by the CHECK CONSTRAINT, to be sent to the client in the result set metadata. */ virtual bool set_format_by_check_constraint(Send_field_extended_metadata *) const { return false; } /* set value of aggregate function in case of no rows for grouping were found */ virtual void no_rows_in_result() {} virtual void restore_to_before_no_rows_in_result() {} virtual Item *copy_or_same(THD *thd) { return this; } virtual Item *copy_andor_structure(THD *thd) { return this; } virtual Item *real_item() { return this; } const Item *real_item() const { return const_cast(this)->real_item(); } virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); } virtual Item *make_odbc_literal(THD *thd, const LEX_CSTRING *typestr) { return this; } static CHARSET_INFO *default_charset(); CHARSET_INFO *charset_for_protocol(void) const { return type_handler()->charset_for_protocol(this); }; virtual bool walk(Item_processor processor, bool walk_subquery, void *arg) { return (this->*processor)(arg); } virtual Item* transform(THD *thd, Item_transformer transformer, uchar *arg); virtual Item* top_level_transform(THD *thd, Item_transformer transformer, uchar *arg) { return transform(thd, transformer, arg); } /* This function performs a generic "compilation" of the Item tree. The process of compilation is assumed to go as follows: compile() { if (this->*some_analyzer(...)) { compile children if any; this->*some_transformer(...); } } i.e. analysis is performed top-down while transformation is done bottom-up. */ virtual Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) { if ((this->*analyzer) (arg_p)) return ((this->*transformer) (thd, arg_t)); return 0; } virtual Item* top_level_compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) { return compile(thd, analyzer, arg_p, transformer, arg_t); } virtual void traverse_cond(Cond_traverser traverser, void *arg, traverse_order order) { (*traverser)(this, arg); } /*========= Item processors, to be used with Item::walk() ========*/ virtual bool remove_dependence_processor(void *arg) { return 0; } virtual bool cleanup_processor(void *arg); virtual bool cleanup_excluding_fields_processor (void *arg) { return cleanup_processor(arg); } bool cleanup_excluding_immutables_processor (void *arg); virtual bool cleanup_excluding_const_fields_processor (void *arg) { return cleanup_processor(arg); } virtual bool collect_item_field_processor(void *arg) { return 0; } virtual bool unknown_splocal_processor(void *arg) { return 0; } virtual bool collect_outer_ref_processor(void *arg) {return 0; } virtual bool check_inner_refs_processor(void *arg) { return 0; } virtual bool find_item_in_field_list_processor(void *arg) { return 0; } virtual bool find_item_processor(void *arg); virtual bool change_context_processor(void *arg) { return 0; } virtual bool reset_query_id_processor(void *arg) { return 0; } virtual bool is_expensive_processor(void *arg) { return 0; } bool remove_immutable_flag_processor (void *arg); // FIXME reduce the number of "add field to bitmap" processors virtual bool add_field_to_set_processor(void *arg) { return 0; } virtual bool register_field_in_read_map(void *arg) { return 0; } virtual bool register_field_in_write_map(void *arg) { return 0; } virtual bool register_field_in_bitmap(void *arg) { return 0; } virtual bool update_table_bitmaps_processor(void *arg) { return 0; } virtual bool enumerate_field_refs_processor(void *arg) { return 0; } virtual bool mark_as_eliminated_processor(void *arg) { return 0; } virtual bool eliminate_subselect_processor(void *arg) { return 0; } virtual bool view_used_tables_processor(void *arg) { return 0; } virtual bool eval_not_null_tables(void *arg) { return 0; } virtual bool is_subquery_processor(void *arg) { return 0; } virtual bool count_sargable_conds(void *arg) { return 0; } virtual bool limit_index_condition_pushdown_processor(void *arg) { return 0; } virtual bool exists2in_processor(void *arg) { return 0; } virtual bool find_selective_predicates_list_processor(void *arg) { return 0; } virtual bool cleanup_is_expensive_cache_processor(void *arg) { is_expensive_cache= (int8)(-1); return 0; } virtual bool set_extraction_flag_processor(void *arg) { set_extraction_flag(*(int16*)arg); return 0; } virtual bool subselect_table_finder_processor(void *arg) { return 0; }; /* TRUE if the expression depends only on the table indicated by tab_map or can be converted to such an exression using equalities. Not to be used for AND/OR formulas. */ virtual bool excl_dep_on_table(table_map tab_map) { return false; } /* TRUE if the expression depends only on grouping fields of sel or can be converted to such an expression using equalities. It also checks if the expression doesn't contain stored procedures, subqueries or randomly generated elements. Not to be used for AND/OR formulas. */ virtual bool excl_dep_on_grouping_fields(st_select_lex *sel) { return false; } /* TRUE if the expression depends only on fields from the left part of IN subquery or can be converted to such an expression using equalities. Not to be used for AND/OR formulas. */ virtual bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) { return false; } virtual bool switch_to_nullable_fields_processor(void *arg) { return 0; } virtual bool find_function_processor (void *arg) { return 0; } /* Check if a partition function is allowed SYNOPSIS check_partition_func_processor() int_arg Ignored RETURN VALUE TRUE Partition function not accepted FALSE Partition function accepted DESCRIPTION check_partition_func_processor is used to check if a partition function uses an allowed function. An allowed function will always ensure that X=Y guarantees that also part_function(X)=part_function(Y) where X is a set of partition fields and so is Y. The problems comes mainly from character sets where two equal strings can be quite unequal. E.g. the german character for double s is equal to 2 s. The default is that an item is not allowed in a partition function. Allowed functions can never depend on server version, they cannot depend on anything related to the environment. They can also only depend on a set of fields in the table itself. They cannot depend on other tables and cannot contain any queries and cannot contain udf's or similar. If a new Item class is defined and it inherits from a class that is allowed in a partition function then it is very important to consider whether this should be inherited to the new class. If not the function below should be defined in the new Item class. The general behaviour is that most integer functions are allowed. If the partition function contains any multi-byte collations then the function check_part_func_fields will report an error on the partition function independent of what functions are used. So the only character sets allowed are single character collation and even for those only a limited set of functions are allowed. The problem with multi-byte collations is that almost every string function has the ability to change things such that two strings that are equal will not be equal after manipulated by a string function. E.g. two strings one contains a double s, there is a special german character that is equal to two s. Now assume a string function removes one character at this place, then in one the double s will be removed and in the other there will still be one s remaining and the strings are no longer equal and thus the partition function will not sort equal strings into the same partitions. So the check if a partition function is valid is two steps. First check that the field types are valid, next check that the partition function is valid. The current set of partition functions valid assumes that there are no multi-byte collations amongst the partition fields. */ virtual bool check_partition_func_processor(void *arg) { return true; } virtual bool post_fix_fields_part_expr_processor(void *arg) { return 0; } virtual bool rename_fields_processor(void *arg) { return 0; } virtual bool rename_table_processor(void *arg) { return 0; } /* TRUE if the function is knowingly TRUE or FALSE. Not to be used for AND/OR formulas. */ virtual bool is_simplified_cond_processor(void *arg) { return false; } /** Processor used to check acceptability of an item in the defining expression for a virtual column @param arg always ignored @retval 0 the item is accepted in the definition of a virtual column @retval 1 otherwise */ struct vcol_func_processor_result { uint errors; /* Bits of possible errors */ const char *name; /* Not supported function */ Alter_info *alter_info; vcol_func_processor_result() : errors(0), name(NULL), alter_info(NULL) {} }; struct func_processor_rename { LEX_CSTRING db_name; LEX_CSTRING table_name; List fields; }; struct func_processor_rename_table { Lex_ident_db old_db; Lex_ident_table old_table; Lex_ident_db new_db; Lex_ident_table new_table; }; virtual bool check_vcol_func_processor(void *arg) { return mark_unsupported_function(full_name(), arg, VCOL_IMPOSSIBLE); } virtual bool check_handler_func_processor(void *arg) { return 0; } virtual bool check_field_expression_processor(void *arg) { return 0; } virtual bool check_func_default_processor(void *arg) { return 0; } virtual bool update_func_default_processor(void *arg) { return 0; } /* Check if an expression value has allowed arguments, like DATE/DATETIME for date functions. Also used by partitioning code to reject timezone-dependent expressions in a (sub)partitioning function. */ virtual bool check_valid_arguments_processor(void *arg) { return 0; } virtual bool update_vcol_processor(void *arg) { return 0; } virtual bool set_fields_as_dependent_processor(void *arg) { return 0; } /* Find if some of the key parts of table keys (the reference on table is passed as an argument) participate in the expression. If there is some, sets a bit for this key in the proper key map. */ virtual bool check_index_dependence(void *arg) { return 0; } virtual bool check_sequence_privileges(void *arg) { return 0; } /*============== End of Item processor list ======================*/ /* Given a condition P from the WHERE clause or from an ON expression of the processed SELECT S and a set of join tables from S marked in the parameter 'allowed'={T} a call of P->find_not_null_fields({T}) has to find the set fields {F} of the tables from 'allowed' such that: - each field from {F} is declared as nullable - each record of table t from {T} that contains NULL as the value for at at least one field from {F} can be ignored when building the result set for S It is assumed here that the condition P is conjunctive and all its column references belong to T. Examples: CREATE TABLE t1 (a int, b int); CREATE TABLE t2 (a int, b int); SELECT * FROM t1,t2 WHERE t1.a=t2.a and t1.b > 5; A call of find_not_null_fields() for the whole WHERE condition and {t1,t2} should find {t1.a,t1.b,t2.a} SELECT * FROM t1 LEFT JOIN ON (t1.a=t2.a and t2.a > t2.b); A call of find_not_null_fields() for the ON expression and {t2} should find {t2.a,t2.b} The function returns TRUE if it succeeds to prove that all records of a table from {T} can be ignored. Otherwise it always returns FALSE. Example: SELECT * FROM t1,t2 WHERE t1.a=t2.a AND t2.a IS NULL; A call of find_not_null_fields() for the WHERE condition and {t1,t2} will return TRUE. It is assumed that the implementation of this virtual function saves the info on the found set of fields in the structures associates with tables from {T}. */ virtual bool find_not_null_fields(table_map allowed) { return false; } bool cache_const_expr_analyzer(uchar **arg); Item* cache_const_expr_transformer(THD *thd, uchar *arg); virtual Item* propagate_equal_fields(THD*, const Context &, COND_EQUAL *) { return this; }; Item* propagate_equal_fields_and_change_item_tree(THD *thd, const Context &ctx, COND_EQUAL *cond, Item **place); /* arg points to REPLACE_EQUAL_FIELD_ARG object */ virtual Item *replace_equal_field(THD *thd, uchar *arg) { return this; } struct Collect_deps_prm { List *parameters; /* unit from which we count nest_level */ st_select_lex_unit *nest_level_base; uint count; int nest_level; bool collect; }; /* For SP local variable returns pointer to Item representing its current value and pointer to current Item otherwise. */ virtual Item *this_item() { return this; } virtual const Item *this_item() const { return this; } /* For SP local variable returns address of pointer to Item representing its current value and pointer passed via parameter otherwise. */ virtual Item **this_item_addr(THD *thd, Item **addr_arg) { return addr_arg; } // Row emulation virtual uint cols() const { return 1; } virtual Item* element_index(uint i) { return this; } virtual Item** addr(uint i) { return 0; } virtual bool check_cols(uint c); bool check_type_traditional_scalar(const LEX_CSTRING &opname) const; bool check_type_scalar(const LEX_CSTRING &opname) const; bool check_type_or_binary(const LEX_CSTRING &opname, const Type_handler *handler) const; bool check_type_general_purpose_string(const LEX_CSTRING &opname) const; bool check_type_can_return_int(const LEX_CSTRING &opname) const; bool check_type_can_return_decimal(const LEX_CSTRING &opname) const; bool check_type_can_return_real(const LEX_CSTRING &opname) const; bool check_type_can_return_str(const LEX_CSTRING &opname) const; bool check_type_can_return_text(const LEX_CSTRING &opname) const; bool check_type_can_return_date(const LEX_CSTRING &opname) const; bool check_type_can_return_time(const LEX_CSTRING &opname) const; // It is not row => null inside is impossible virtual bool null_inside() { return 0; } // used in row subselects to get value of elements virtual void bring_value() {} const Type_handler *type_handler_long_or_longlong() const { return Type_handler::type_handler_long_or_longlong(max_char_length(), unsigned_flag); } /** Create field for temporary table. @param table Temporary table @param [OUT] src Who created the fields @param param Create parameters @retval NULL (on error) @retval a pointer to a newly create Field (on success) */ virtual Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param)= 0; virtual Item_field *field_for_view_update() { return 0; } virtual Item *neg_transformer(THD *thd) { return NULL; } virtual Item *update_value_transformer(THD *thd, uchar *select_arg) { return this; } virtual Item *expr_cache_insert_transformer(THD *thd, uchar *unused) { return this; } virtual Item *derived_field_transformer_for_having(THD *thd, uchar *arg) { return this; } virtual Item *derived_field_transformer_for_where(THD *thd, uchar *arg) { return this; } virtual Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) { return this; } /* Now is not used. */ virtual Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) { return this; } virtual Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) { return this; } virtual Item *in_predicate_to_in_subs_transformer(THD *thd, uchar *arg) { return this; } virtual Item *in_predicate_to_equality_transformer(THD *thd, uchar *arg) { return this; } virtual Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg) { return this; } virtual Item *multiple_equality_transformer(THD *thd, uchar *arg); virtual bool expr_cache_is_needed(THD *) { return FALSE; } virtual Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs); bool needs_charset_converter(uint32 length, CHARSET_INFO *tocs) const { /* This will return "true" if conversion happens: - between two non-binary different character sets - from "binary" to "unsafe" character set (those that can have non-well-formed string) - from "binary" to UCS2-alike character set with mbminlen>1, when prefix left-padding is needed for an incomplete character: binary 0xFF -> ucs2 0x00FF) */ if (!String::needs_conversion_on_storage(length, collation.collation, tocs)) return false; /* No needs to add converter if an "arg" is NUMERIC or DATETIME value (which is pure ASCII) and at the same time target DTCollation is ASCII-compatible. For example, no needs to rewrite: SELECT * FROM t1 WHERE datetime_field = '2010-01-01'; to SELECT * FROM t1 WHERE CONVERT(datetime_field USING cs) = '2010-01-01'; TODO: avoid conversion of any values with repertoire ASCII and 7bit-ASCII-compatible, not only numeric/datetime origin. */ if (collation.derivation == DERIVATION_NUMERIC && collation.repertoire == MY_REPERTOIRE_ASCII && !(collation.collation->state & MY_CS_NONASCII) && !(tocs->state & MY_CS_NONASCII)) return false; return true; } bool needs_charset_converter(CHARSET_INFO *tocs) { // Pass 1 as length to force conversion if tocs->mbminlen>1. return needs_charset_converter(1, tocs); } Item *const_charset_converter(THD *thd, CHARSET_INFO *tocs, bool lossless, const char *func_name); Item *const_charset_converter(THD *thd, CHARSET_INFO *tocs, bool lossless) { return const_charset_converter(thd, tocs, lossless, NULL); } void delete_self() { cleanup(); delete this; } virtual const Item_const *get_item_const() const { return NULL; } virtual Item_splocal *get_item_splocal() { return 0; } virtual Rewritable_query_parameter *get_rewritable_query_parameter() { return 0; } /* Return Settable_routine_parameter interface of the Item. Return 0 if this Item is not Settable_routine_parameter. */ virtual Settable_routine_parameter *get_settable_routine_parameter() { return 0; } virtual Load_data_outvar *get_load_data_outvar() { return 0; } Load_data_outvar *get_load_data_outvar_or_error() { Load_data_outvar *dst= get_load_data_outvar(); if (dst) return dst; my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), name.str); return NULL; } /** Test whether an expression is expensive to compute. Used during optimization to avoid computing expensive expressions during this phase. Also used to force temp tables when sorting on expensive functions. @todo Normally we should have a method: cost Item::execution_cost(), where 'cost' is either 'double' or some structure of various cost parameters. @note This function is now used to prevent evaluation of expensive subquery predicates during the optimization phase. It also prevents evaluation of predicates that are not computable at this moment. */ virtual bool is_expensive() { if (is_expensive_cache < 0) is_expensive_cache= walk(&Item::is_expensive_processor, 0, NULL); return MY_TEST(is_expensive_cache); } String *check_well_formed_result(String *str, bool send_error= 0); bool eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs); bool too_big_for_varchar() const { return max_char_length() > CONVERT_IF_BIGGER_TO_BLOB; } void fix_length_and_charset(uint32 max_char_length_arg, CHARSET_INFO *cs) { max_length= char_to_byte_length_safe(max_char_length_arg, cs->mbmaxlen); collation.collation= cs; } void fix_char_length(size_t max_char_length_arg) { max_length= char_to_byte_length_safe(max_char_length_arg, collation.collation->mbmaxlen); } /* Return TRUE if the item points to a column of an outer-joined table. */ virtual bool is_outer_field() const { DBUG_ASSERT(fixed()); return FALSE; } Item* set_expr_cache(THD *thd); virtual Item_equal *get_item_equal() { return NULL; } virtual void set_item_equal(Item_equal *item_eq) {}; virtual Item_equal *find_item_equal(COND_EQUAL *cond_equal) { return NULL; } /** Set the join tab index to the minimal (left-most) JOIN_TAB to which this Item is attached. The number is an index is depth_first_tab() traversal order. */ virtual void set_join_tab_idx(uint8 join_tab_idx_arg) { if (join_tab_idx_arg < join_tab_idx) join_tab_idx= join_tab_idx_arg; } uint get_join_tab_idx() const { return join_tab_idx; } table_map view_used_tables(TABLE_LIST *view) { view->view_used_tables= 0; walk(&Item::view_used_tables_processor, 0, view); return view->view_used_tables; } /** Collect and add to the list cache parameters for this Item. @note Now implemented only for subqueries and in_optimizer, if we need it for general function then this method should be defined for Item_func. */ virtual void get_cache_parameters(List ¶meters) { }; virtual void mark_as_condition_AND_part(TABLE_LIST *embedding) {}; /* how much position should be reserved for Exists2In transformation */ virtual uint exists2in_reserved_items() { return 0; }; virtual Item *neg(THD *thd); /** Inform the item that it is located under a NOT, which is a top-level item. */ virtual void under_not(Item_func_not * upper __attribute__((unused))) {}; void register_in(THD *thd); bool depends_only_on(table_map view_map) { return marker & MARKER_FULL_EXTRACTION; } int get_extraction_flag() { return marker & MARKER_EXTRACTION_MASK; } void set_extraction_flag(int16 flags) { marker &= ~MARKER_EXTRACTION_MASK; marker|= flags; } void clear_extraction_flag() { marker &= ~MARKER_EXTRACTION_MASK; } void check_pushable_cond(Pushdown_checker excl_dep_func, uchar *arg); bool pushable_cond_checker_for_derived(uchar *arg) { return excl_dep_on_table(*((table_map *)arg)); } bool pushable_cond_checker_for_subquery(uchar *arg) { DBUG_ASSERT(((Item*) arg)->get_IN_subquery()); return excl_dep_on_in_subq_left_part(((Item*)arg)->get_IN_subquery()); } Item *build_pushable_cond(THD *thd, Pushdown_checker checker, uchar *arg); /* Checks if this item depends only on the arg table */ bool pushable_equality_checker_for_derived(uchar *arg) { return (used_tables() == *((table_map *)arg)); } /* Checks if this item consists in the left part of arg IN subquery predicate */ bool pushable_equality_checker_for_subquery(uchar *arg); /** This method is to set relationship between a positional parameter represented by the '?' and an actual argument value passed to the call of PS/SP by the USING clause. The method is overridden in classes Item_param and Item_default_value. */ virtual bool associate_with_target_field(THD *, Item_field *) { DBUG_ASSERT(fixed()); return false; } protected: /* Service function for public method get_copy(). See comments for get_copy() above. Override this method in derived classes to create shallow copies of the item */ virtual Item *do_get_copy(THD *thd) const = 0; /* Service function for public method build_clone(). See comments for build_clone() above. Override this method in derived classes to create deep copies (clones) of the item where possible */ virtual Item* do_build_clone(THD *thd) const = 0; }; MEM_ROOT *get_thd_memroot(THD *thd); template inline Item* get_item_copy (THD *thd, const T* item) { Item *copy= new (get_thd_memroot(thd)) T(*item); if (likely(copy)) copy->register_in(thd); return copy; } #ifndef DBUG_OFF /** A helper class to print the data type and the value for an Item in debug builds. */ class DbugStringItemTypeValue: public StringBuffer<128> { public: DbugStringItemTypeValue(THD *thd, const Item *item) { append('('); Name Item_name= item->type_handler()->name(); append(Item_name.ptr(), Item_name.length()); append(')'); const_cast(item)->print(this, QT_EXPLAIN); /* Append end \0 to allow usage of c_ptr() */ append('\0'); str_length--; } }; #endif /* DBUG_OFF */ /** Compare two Items for List::add_unique() */ bool cmp_items(Item *a, Item *b); /** Array of items, e.g. function or aggerate function arguments. */ class Item_args { protected: Item **args, *tmp_arg[2]; uint arg_count; void set_arguments(THD *thd, List &list); bool walk_args(Item_processor processor, bool walk_subquery, void *arg) { for (uint i= 0; i < arg_count; i++) { if (args[i]->walk(processor, walk_subquery, arg)) return true; } return false; } bool transform_args(THD *thd, Item_transformer transformer, uchar *arg); void propagate_equal_fields(THD *, const Item::Context &, COND_EQUAL *); bool excl_dep_on_table(table_map tab_map) { for (uint i= 0; i < arg_count; i++) { if (args[i]->const_item()) continue; if (!args[i]->excl_dep_on_table(tab_map)) return false; } return true; } bool excl_dep_on_grouping_fields(st_select_lex *sel); bool eq(const Item_args *other, bool binary_cmp) const { for (uint i= 0; i < arg_count ; i++) { if (!args[i]->eq(other->args[i], binary_cmp)) return false; } return true; } bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) { for (uint i= 0; i < arg_count; i++) { if (args[i]->const_item()) continue; if (!args[i]->excl_dep_on_in_subq_left_part(subq_pred)) return false; } return true; } public: Item_args(void) :args(NULL), arg_count(0) { } Item_args(Item *a) :args(tmp_arg), arg_count(1) { args[0]= a; } Item_args(Item *a, Item *b) :args(tmp_arg), arg_count(2) { args[0]= a; args[1]= b; } Item_args(THD *thd, Item *a, Item *b, Item *c) { arg_count= 0; if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 3)))) { arg_count= 3; args[0]= a; args[1]= b; args[2]= c; } } Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d) { arg_count= 0; if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 4)))) { arg_count= 4; args[0]= a; args[1]= b; args[2]= c; args[3]= d; } } Item_args(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e) { arg_count= 5; if (likely((args= (Item**) thd_alloc(thd, sizeof(Item*) * 5)))) { arg_count= 5; args[0]= a; args[1]= b; args[2]= c; args[3]= d; args[4]= e; } } Item_args(THD *thd, List &list) { set_arguments(thd, list); } Item_args(THD *thd, const Item_args *other); bool alloc_arguments(THD *thd, uint count); void add_argument(Item *item) { args[arg_count++]= item; } /** Extract row elements from the given position. For example, for this input: (1,2),(3,4),(5,6) pos=0 will extract (1,3,5) pos=1 will extract (2,4,6) @param thd - current thread, to allocate memory on its mem_root @param rows - an array of compatible ROW-type items @param pos - the element position to extract */ bool alloc_and_extract_row_elements(THD *thd, const Item_args *rows, uint pos) { DBUG_ASSERT(rows->argument_count() > 0); DBUG_ASSERT(rows->arguments()[0]->cols() > pos); if (alloc_arguments(thd, rows->argument_count())) return true; for (uint i= 0; i < rows->argument_count(); i++) { DBUG_ASSERT(rows->arguments()[0]->cols() == rows->arguments()[i]->cols()); Item *arg= rows->arguments()[i]->element_index(pos); add_argument(arg); } DBUG_ASSERT(argument_count() == rows->argument_count()); return false; } inline Item **arguments() const { return args; } inline uint argument_count() const { return arg_count; } inline void remove_arguments() { arg_count=0; } Sql_mode_dependency value_depends_on_sql_mode_bit_or() const; }; /* Class to be used to enumerate all field references in an item tree. This includes references to outside but not fields of the tables within a subquery. Suggested usage: class My_enumerator : public Field_enumerator { virtual void visit_field() { ... your actions ...} } My_enumerator enumerator; item->walk(Item::enumerate_field_refs_processor, ...,&enumerator); This is similar to Visitor pattern. */ class Field_enumerator { public: virtual void visit_field(Item_field *field)= 0; virtual ~Field_enumerator() = default;; /* purecov: inspected */ Field_enumerator() = default; /* Remove gcc warning */ }; class Item_string; class Item_fixed_hybrid: public Item { public: Item_fixed_hybrid(THD *thd): Item(thd) { base_flags&= ~item_base_t::FIXED; } Item_fixed_hybrid(THD *thd, Item_fixed_hybrid *item) :Item(thd, item) { base_flags|= (item->base_flags & item_base_t::FIXED); } bool fix_fields(THD *thd, Item **ref) override { DBUG_ASSERT(!fixed()); base_flags|= item_base_t::FIXED; return false; } void cleanup() override { Item::cleanup(); base_flags&= ~item_base_t::FIXED; } void quick_fix_field() override { base_flags|= item_base_t::FIXED; } void unfix_fields() override { base_flags&= ~item_base_t::FIXED; } }; /** A common class for Item_basic_constant and Item_param */ class Item_basic_value :public Item, public Item_const { protected: // Value metadata, e.g. to make string processing easier class Metadata: private MY_STRING_METADATA { public: Metadata(const String *str) { my_string_metadata_get(this, str->charset(), str->ptr(), str->length()); } Metadata(const String *str, my_repertoire_t repertoire_arg) { MY_STRING_METADATA::repertoire= repertoire_arg; MY_STRING_METADATA::char_length= str->numchars(); } my_repertoire_t repertoire() const { return MY_STRING_METADATA::repertoire; } size_t char_length() const { return MY_STRING_METADATA::char_length; } }; void fix_charset_and_length(CHARSET_INFO *cs, Derivation dv, Metadata metadata) { /* We have to have a different max_length than 'length' here to ensure that we get the right length if we do use the item to create a new table. In this case max_length must be the maximum number of chars for a string of this type because we in Create_field:: divide the max_length with mbmaxlen). */ collation.set(cs, dv, metadata.repertoire()); fix_char_length(metadata.char_length()); decimals= NOT_FIXED_DEC; } void fix_charset_and_length_from_str_value(const String &str, Derivation dv) { fix_charset_and_length(str.charset(), dv, Metadata(&str)); } Item_basic_value(THD *thd): Item(thd) {} Item_basic_value(): Item() {} public: Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { /* create_tmp_field_ex() for this type of Items is called for: - CREATE TABLE ... SELECT - In ORDER BY: SELECT max(a) FROM t1 GROUP BY a ORDER BY 'const'; - In CURSORS: DECLARE c CURSOR FOR SELECT 'test'; OPEN c; */ return tmp_table_field_from_field_type_maybe_null(root, table, src, param, type() == Item::NULL_ITEM); } bool eq(const Item *item, bool binary_cmp) const override; const Type_all_attributes *get_type_all_attributes_from_const() const override { return this; } }; class Item_basic_constant :public Item_basic_value { public: Item_basic_constant(THD *thd): Item_basic_value(thd) {}; Item_basic_constant(): Item_basic_value() {}; bool check_vcol_func_processor(void *) override { return false; } const Item_const *get_item_const() const override { return this; } virtual Item_basic_constant *make_string_literal_concat(THD *thd, const LEX_CSTRING *) { DBUG_ASSERT(0); return this; } bool val_bool() override = 0; }; /***************************************************************************** The class is a base class for representation of stored routine variables in the Item-hierarchy. There are the following kinds of SP-vars: - local variables (Item_splocal); - CASE expression (Item_case_expr); *****************************************************************************/ class Item_sp_variable :public Item_fixed_hybrid { protected: /* THD, which is stored in fix_fields() and is used in this_item() to avoid current_thd use. */ THD *m_thd; bool fix_fields_from_item(THD *thd, Item **, const Item *); public: LEX_CSTRING m_name; public: #ifdef DBUG_ASSERT_EXISTS /* Routine to which this Item_splocal belongs. Used for checking if correct runtime context is used for variable handling. */ const sp_head *m_sp; #endif public: Item_sp_variable(THD *thd, const LEX_CSTRING *sp_var_name); public: bool fix_fields(THD *thd, Item **) override= 0; double val_real() override; longlong val_int() override; String *val_str(String *sp) override; my_decimal *val_decimal(my_decimal *decimal_value) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *to) override; bool is_null() override; public: void make_send_field(THD *thd, Send_field *field) override; bool const_item() const override { return true; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { return create_tmp_field_ex_simple(root, table, src, param); } inline int save_in_field(Field *field, bool no_conversions) override; inline bool send(Protocol *protocol, st_value *buffer) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(m_name.str, arg, VCOL_IMPOSSIBLE); } }; /***************************************************************************** Item_sp_variable inline implementation. *****************************************************************************/ inline int Item_sp_variable::save_in_field(Field *field, bool no_conversions) { return this_item()->save_in_field(field, no_conversions); } inline bool Item_sp_variable::send(Protocol *protocol, st_value *buffer) { return this_item()->send(protocol, buffer); } /***************************************************************************** A reference to local SP variable (incl. reference to SP parameter), used in runtime. *****************************************************************************/ class Item_splocal :public Item_sp_variable, private Settable_routine_parameter, public Rewritable_query_parameter, public Type_handler_hybrid_field_type { protected: const Sp_rcontext_handler *m_rcontext_handler; uint m_var_idx; Type m_type; bool append_value_for_log(THD *thd, String *str); sp_rcontext *get_rcontext(sp_rcontext *local_ctx) const; Item_field *get_variable(sp_rcontext *ctx) const; public: Item_splocal(THD *thd, const Sp_rcontext_handler *rh, const LEX_CSTRING *sp_var_name, uint sp_var_idx, const Type_handler *handler, uint pos_in_q= 0, uint len_in_q= 0); bool fix_fields(THD *, Item **) override; Item *this_item() override; const Item *this_item() const override; Item **this_item_addr(THD *thd, Item **) override; void print(String *str, enum_query_type query_type) override; public: inline const LEX_CSTRING *my_name() const; inline uint get_var_idx() const; Type type() const override { return m_type; } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } uint cols() const override { return this_item()->cols(); } Item* element_index(uint i) override { return this_item()->element_index(i); } Item** addr(uint i) override { return this_item()->addr(i); } bool check_cols(uint c) override; private: bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override; public: Item_splocal *get_item_splocal() override { return this; } Rewritable_query_parameter *get_rewritable_query_parameter() override { return this; } Settable_routine_parameter *get_settable_routine_parameter() override { return this; } bool append_for_log(THD *thd, String *str) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } /* Override the inherited create_field_for_create_select(), because we want to preserve the exact data type for: DECLARE a1 INT; DECLARE a2 TYPE OF t1.a2; CREATE TABLE t1 AS SELECT a1, a2; The inherited implementation would create a column based on result_type(), which is less exact. */ Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { return create_table_field_from_handler(root, table); } bool is_valid_limit_clause_variable_with_error() const { /* In case if the variable has an anchored data type, e.g.: DECLARE a TYPE OF t1.a; type_handler() is set to &type_handler_null and this function detects such variable as not valid in LIMIT. */ if (type_handler()->is_limit_clause_valid_type()) return true; my_error(ER_WRONG_SPVAR_TYPE_IN_LIMIT, MYF(0)); return false; } }; /** An Item_splocal variant whose data type becomes known only at sp_rcontext creation time, e.g. "DECLARE var1 t1.col1%TYPE". */ class Item_splocal_with_delayed_data_type: public Item_splocal { public: Item_splocal_with_delayed_data_type(THD *thd, const Sp_rcontext_handler *rh, const LEX_CSTRING *sp_var_name, uint sp_var_idx, uint pos_in_q, uint len_in_q) :Item_splocal(thd, rh, sp_var_name, sp_var_idx, &type_handler_null, pos_in_q, len_in_q) { } Item *do_get_copy(THD *) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } }; /** SP variables that are fields of a ROW. DELCARE r ROW(a INT,b INT); SELECT r.a; -- This is handled by Item_splocal_row_field */ class Item_splocal_row_field :public Item_splocal { protected: LEX_CSTRING m_field_name; uint m_field_idx; bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override; public: Item_splocal_row_field(THD *thd, const Sp_rcontext_handler *rh, const LEX_CSTRING *sp_var_name, const LEX_CSTRING *sp_field_name, uint sp_var_idx, uint sp_field_idx, const Type_handler *handler, uint pos_in_q= 0, uint len_in_q= 0) :Item_splocal(thd, rh, sp_var_name, sp_var_idx, handler, pos_in_q, len_in_q), m_field_name(*sp_field_name), m_field_idx(sp_field_idx) { } bool fix_fields(THD *thd, Item **) override; Item *this_item() override; const Item *this_item() const override; Item **this_item_addr(THD *thd, Item **) override; bool append_for_log(THD *thd, String *str) override; void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } }; class Item_splocal_row_field_by_name :public Item_splocal_row_field { bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override; public: Item_splocal_row_field_by_name(THD *thd, const Sp_rcontext_handler *rh, const LEX_CSTRING *sp_var_name, const LEX_CSTRING *sp_field_name, uint sp_var_idx, const Type_handler *handler, uint pos_in_q= 0, uint len_in_q= 0) :Item_splocal_row_field(thd, rh, sp_var_name, sp_field_name, sp_var_idx, 0 /* field index will be set later */, handler, pos_in_q, len_in_q) { } bool fix_fields(THD *thd, Item **it) override; void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } }; /***************************************************************************** Item_splocal inline implementation. *****************************************************************************/ inline const LEX_CSTRING *Item_splocal::my_name() const { return &m_name; } inline uint Item_splocal::get_var_idx() const { return m_var_idx; } /***************************************************************************** A reference to case expression in SP, used in runtime. *****************************************************************************/ class Item_case_expr :public Item_sp_variable { public: Item_case_expr(THD *thd, uint case_expr_id); public: bool fix_fields(THD *thd, Item **) override; Item *this_item() override; const Item *this_item() const override; Item **this_item_addr(THD *thd, Item **) override; Type type() const override; const Type_handler *type_handler() const override { return this_item()->type_handler(); } public: /* NOTE: print() is intended to be used from views and for debug. Item_case_expr can not occur in views, so here it is only for debug purposes. */ void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } private: uint m_case_expr_id; }; /***************************************************************************** Item_case_expr inline implementation. *****************************************************************************/ inline enum Item::Type Item_case_expr::type() const { return this_item()->type(); } /* NAME_CONST(given_name, const_value). This 'function' has all properties of the supplied const_value (which is assumed to be a literal constant), and the name given_name. This is used to replace references to SP variables when we write PROCEDURE statements into the binary log. TODO Together with Item_splocal and Item::this_item() we can actually extract common a base of this class and Item_splocal. Maybe it is possible to extract a common base with class Item_ref, too. */ class Item_name_const : public Item_fixed_hybrid { Item *value_item; Item *name_item; public: Item_name_const(THD *thd, Item *name_arg, Item *val); bool fix_fields(THD *, Item **) override; Type type() const override; double val_real() override; longlong val_int() override; String *val_str(String *sp) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *to) override; bool is_null() override; void print(String *str, enum_query_type query_type) override; const Type_handler *type_handler() const override { return value_item->type_handler(); } bool const_item() const override { return true; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { /* We can get to here when using a CURSOR for a query with NAME_CONST(): DECLARE c CURSOR FOR SELECT NAME_CONST('x','y') FROM t1; OPEN c; */ return tmp_table_field_from_field_type_maybe_null(root, table, src, param, type() == Item::NULL_ITEM); } int save_in_field(Field *field, bool no_conversions) override { return value_item->save_in_field(field, no_conversions); } bool send(Protocol *protocol, st_value *buffer) override { return value_item->send(protocol, buffer); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("name_const()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_literal: public Item_basic_constant { public: Item_literal(THD *thd): Item_basic_constant(thd) { } Item_literal(): Item_basic_constant() {} Type type() const override { return CONST_ITEM; } bool check_partition_func_processor(void *int_arg) override { return false;} bool const_item() const override { return true; } bool basic_const_item() const override { return true; } bool is_expensive() override { return false; } bool cleanup_is_expensive_cache_processor(void *arg) override { return 0; } }; class Item_num: public Item_literal { public: Item_num(THD *thd): Item_literal(thd) { collation= DTCollation_numeric(); } Item_num(): Item_literal() { collation= DTCollation_numeric(); } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } }; #define NO_CACHED_FIELD_INDEX ((field_index_t) ~0U) class st_select_lex; class Item_result_field :public Item_fixed_hybrid /* Item with result field */ { protected: Field *create_tmp_field_ex_from_handler(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param, const Type_handler *h); public: Field *result_field; /* Save result here */ Item_result_field(THD *thd): Item_fixed_hybrid(thd), result_field(0) {} // Constructor used for Item_sum/Item_cond_and/or (see Item comment) Item_result_field(THD *thd, Item_result_field *item): Item_fixed_hybrid(thd, item), result_field(item->result_field) {} ~Item_result_field() = default; Field *get_tmp_table_field() override { return result_field; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { DBUG_ASSERT(fixed()); const Type_handler *h= type_handler()->type_handler_for_tmp_table(this); return create_tmp_field_ex_from_handler(root, table, src, param, h); } void get_tmp_field_src(Tmp_field_src *src, const Tmp_field_param *param); /* This implementation of used_tables() used by Item_avg_field and Item_variance_field which work when only temporary table left, so theu return table map of the temporary table. */ table_map used_tables() const override { return 1; } bool is_result_field() override { return true; } void save_in_result_field(bool no_conversions) override { save_in_field(result_field, no_conversions); } void cleanup() override; bool check_vcol_func_processor(void *) override { return false; } }; class Item_ident :public Item_result_field { protected: /* We have to store initial values of db_name, table_name and field_name to be able to restore them during cleanup() because they can be updated during fix_fields() to values from Field object and life-time of those is shorter than life-time of Item_field. */ Lex_table_name orig_db_name; Lex_table_name orig_table_name; Lex_ident orig_field_name; void undeclared_spvar_error() const; public: Name_resolution_context *context; Lex_table_name db_name; Lex_table_name table_name; Lex_ident field_name; /* Cached pointer to table which contains this field, used for the same reason by prep. stmt. too in case then we have not-fully qualified field. 0 - means no cached value. */ TABLE_LIST *cached_table; st_select_lex *depended_from; /* Cached value of index for this field in table->field array, used by prepared stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX if index value is not known. */ field_index_t cached_field_index; /* Some Items resolved in another select should not be marked as dependency of the subquery where they are. During normal name resolution, we check this. Stored procedures and prepared statements first try to resolve an ident item using a cached table reference and field position from the previous query execution (cached_table/cached_field_index). If the tables were not changed, the ident matches the table/field, and we have faster resolution of the ident without looking through all tables and fields in the query. But in this case, we can not check all conditions about this ident item dependency, so we should cache the condition in this variable. */ bool can_be_depended; /* NOTE: came from TABLE::alias_name_used and this is only a hint! See comment for TABLE::alias_name_used. */ bool alias_name_used; /* true if item was resolved against alias */ Item_ident(THD *thd, Name_resolution_context *context_arg, const LEX_CSTRING &db_name_arg, const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg); Item_ident(THD *thd, Item_ident *item); Item_ident(THD *thd, TABLE_LIST *view_arg, const LEX_CSTRING &field_name_arg); LEX_CSTRING full_name_cstring() const override; void cleanup() override; st_select_lex *get_depended_from() const; bool remove_dependence_processor(void * arg) override; void print(String *str, enum_query_type query_type) override; bool change_context_processor(void *cntx) override { context= (Name_resolution_context *)cntx; return FALSE; } /** Collect outer references */ bool collect_outer_ref_processor(void *arg) override; friend bool insert_fields(THD *thd, Name_resolution_context *context, const char *db_name, const char *table_name, List_iterator *it, bool any_privileges, bool returning_field); }; class Item_field :public Item_ident, public Load_data_outvar { protected: void set_field(Field *field); public: Field *field; Item_equal *item_equal; /* if any_privileges set to TRUE then here real effective privileges will be stored */ privilege_t have_privileges; /* field need any privileges (for VIEW creation) */ bool any_privileges; Item_field(THD *thd, Name_resolution_context *context_arg, const LEX_CSTRING &db_arg, const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg); Item_field(THD *thd, Name_resolution_context *context_arg, const LEX_CSTRING &field_name_arg) :Item_field(thd, context_arg, null_clex_str, null_clex_str, field_name_arg) { } Item_field(THD *thd, Name_resolution_context *context_arg) :Item_field(thd, context_arg, null_clex_str, null_clex_str, null_clex_str) { } /* Constructor needed to process subselect with temporary tables (see Item) */ Item_field(THD *thd, Item_field *item); /* Constructor used inside setup_wild(), ensures that field, table, and database names will live as long as Item_field (this is important in prepared statements). */ Item_field(THD *thd, Name_resolution_context *context_arg, Field *field); /* If this constructor is used, fix_fields() won't work, because db_name, table_name and column_name are unknown. It's necessary to call reset_field() before fix_fields() for all fields created this way. */ Item_field(THD *thd, Field *field); Type type() const override { return FIELD_ITEM; } bool eq(const Item *item, bool binary_cmp) const override; double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; String *val_str(String*) override; void save_result(Field *to) override; double val_result() override; longlong val_int_result() override; bool val_native(THD *thd, Native *to) override; bool val_native_result(THD *thd, Native *to) override; String *str_result(String* tmp) override; my_decimal *val_decimal_result(my_decimal *) override; bool val_bool_result() override; bool is_null_result() override; bool send(Protocol *protocol, st_value *buffer) override; Load_data_outvar *get_load_data_outvar() override { return this; } bool load_data_set_null(THD *thd, const Load_data_param *param) override { return field->load_data_set_null(thd); } bool load_data_set_value(THD *thd, const char *pos, uint length, const Load_data_param *param) override { field->load_data_set_value(pos, length, param->charset()); return false; } bool load_data_set_no_data(THD *thd, const Load_data_param *param) override; void load_data_print_for_log_event(THD *thd, String *to) const override; bool load_data_add_outvar(THD *thd, Load_data_param *param) const override { return param->add_outvar_field(thd, field); } uint load_data_fixed_length() const override { return field->field_length; } void reset_field(Field *f); bool fix_fields(THD *, Item **) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; void make_send_field(THD *thd, Send_field *tmp_field) override; int save_in_field(Field *field,bool no_conversions) override; void save_org_in_field(Field *field, fast_field_copier optimizer_data) override; fast_field_copier setup_fast_field_copier(Field *field) override; table_map used_tables() const override; table_map all_used_tables() const override; const Type_handler *type_handler() const override { const Type_handler *handler= field->type_handler(); return handler->type_handler_for_item_field(); } const Type_handler *real_type_handler() const override { if (field->is_created_from_null_item) return &type_handler_null; return field->type_handler(); } uint32 character_octet_length() const override { return field->character_octet_length(); } Field *create_tmp_field_from_item_field(MEM_ROOT *root, TABLE *new_table, Item_ref *orig_item, const Tmp_field_param *param); Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override; const TYPELIB *get_typelib() const override { return field->get_typelib(); } enum_monotonicity_info get_monotonicity_info() const override { return MONOTONIC_STRICT_INCREASING; } Sql_mode_dependency value_depends_on_sql_mode() const override { return Sql_mode_dependency(0, field->value_depends_on_sql_mode()); } bool hash_not_null(Hasher *hasher) override { if (field->is_null()) return true; field->hash_not_null(hasher); return false; } longlong val_int_endpoint(bool left_endp, bool *incl_endp) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool get_date_result(THD *thd, MYSQL_TIME *ltime,date_mode_t fuzzydate) override; longlong val_datetime_packed(THD *thd) override; longlong val_time_packed(THD *thd) override; bool is_null() override { return field->is_null(); } void update_null_value() override; void update_table_bitmaps() { if (field && field->table) { TABLE *tab= field->table; tab->covering_keys.intersect(field->part_of_key); if (tab->read_set) tab->mark_column_with_deps(field); } } void update_used_tables() override { update_table_bitmaps(); } COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override { /* normilize_cond() replaced all conditions of type WHERE/HAVING field to: WHERE/HAVING field<>0 By the time of a build_equal_items() call, all such conditions should already be replaced. No Item_field are possible. Note, some Item_field derivants are still possible. Item_insert_value: SELECT * FROM t1 WHERE VALUES(a); Item_default_value: SELECT * FROM t1 WHERE DEFAULT(a); */ DBUG_ASSERT(type() != FIELD_ITEM); return Item_ident::build_equal_items(thd, inherited, link_item_fields, cond_equal_ref); } bool is_result_field() override { return false; } void save_in_result_field(bool no_conversions) override; Item *get_tmp_table_item(THD *thd) override; bool find_not_null_fields(table_map allowed) override; bool collect_item_field_processor(void * arg) override; bool unknown_splocal_processor(void *arg) override; bool add_field_to_set_processor(void * arg) override; bool find_item_in_field_list_processor(void *arg) override; bool register_field_in_read_map(void *arg) override; bool register_field_in_write_map(void *arg) override; bool register_field_in_bitmap(void *arg) override; bool check_partition_func_processor(void *) override {return false;} bool post_fix_fields_part_expr_processor(void *bool_arg) override; bool check_valid_arguments_processor(void *bool_arg) override; bool check_field_expression_processor(void *arg) override; bool enumerate_field_refs_processor(void *arg) override; bool update_table_bitmaps_processor(void *arg) override; bool switch_to_nullable_fields_processor(void *arg) override; bool update_vcol_processor(void *arg) override; bool rename_fields_processor(void *arg) override; bool rename_table_processor(void *arg) override; bool check_vcol_func_processor(void *arg) override; bool set_fields_as_dependent_processor(void *arg) override { if (!(used_tables() & OUTER_REF_TABLE_BIT)) { depended_from= (st_select_lex *) arg; item_equal= NULL; } return 0; } void cleanup() override; Item_equal *get_item_equal() override { return item_equal; } void set_item_equal(Item_equal *item_eq) override { item_equal= item_eq; } Item_equal *find_item_equal(COND_EQUAL *cond_equal) override; Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override; Item *replace_equal_field(THD *thd, uchar *arg) override; uint32 max_display_length() const override { return field->max_display_length(); } Item_field *field_for_view_update() override { return this; } int fix_outer_field(THD *thd, Field **field, Item **reference); Item *update_value_transformer(THD *thd, uchar *select_arg) override; Item *derived_field_transformer_for_having(THD *thd, uchar *arg) override; Item *derived_field_transformer_for_where(THD *thd, uchar *arg) override; Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) override; Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) override; Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) override; void print(String *str, enum_query_type query_type) override; bool excl_dep_on_table(table_map tab_map) override; bool excl_dep_on_grouping_fields(st_select_lex *sel) override; bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override; bool cleanup_excluding_fields_processor(void *arg) override { return field ? 0 : cleanup_processor(arg); } bool cleanup_excluding_const_fields_processor(void *arg) override { return field && const_item() ? 0 : cleanup_processor(arg); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item* do_build_clone(THD *thd) const override { return get_copy(thd); } bool is_outer_field() const override { DBUG_ASSERT(fixed()); return field->table->pos_in_table_list->outer_join; } bool check_index_dependence(void *arg) override; friend class Item_default_value; friend class Item_insert_value; friend class st_select_lex_unit; }; /** Item_field for the ROW data type */ class Item_field_row: public Item_field, public Item_args { public: Item_field_row(THD *thd, Field *field) :Item_field(thd, field), Item_args() { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } const Type_handler *type_handler() const override { return &type_handler_row; } uint cols() const override { return arg_count; } Item* element_index(uint i) override { return arg_count ? args[i] : this; } Item** addr(uint i) override { return arg_count ? args + i : NULL; } bool check_cols(uint c) override { if (cols() != c) { my_error(ER_OPERAND_COLUMNS, MYF(0), c); return true; } return false; } bool row_create_items(THD *thd, List *list); }; /* @brief Item_temptable_field is the same as Item_field, except that print() continues to work even if the table has been dropped. @detail We need this item for "ANALYZE statement" feature. Query execution has these steps: 1. Run the query. 2. Cleanup starts. Temporary tables are destroyed 3. print "ANALYZE statement" output, if needed 4. Call close_thread_table() for regular tables. Step #4 is done after step #3, so "ANALYZE stmt" has no problem printing Item_field objects that refer to regular tables. However, Step #3 is done after Step #2. Attempt to print Item_field objects that refer to temporary tables will cause access to freed memory. To resolve this, we use Item_temptable_field to refer to items in temporary (work) tables. */ class Item_temptable_field :public Item_field { public: Item_temptable_field(THD *thd, Name_resolution_context *context_arg, Field *field) : Item_field(thd, context_arg, field) {} Item_temptable_field(THD *thd, Field *field) : Item_field(thd, field) {} Item_temptable_field(THD *thd, Item_field *item) : Item_field(thd, item) {}; void print(String *str, enum_query_type query_type) override; }; class Item_null :public Item_basic_constant { public: Item_null(THD *thd, const char *name_par=0, CHARSET_INFO *cs= &my_charset_bin): Item_basic_constant(thd) { set_maybe_null(); null_value= TRUE; max_length= 0; name.str= name_par ? name_par : "NULL"; name.length= strlen(name.str); collation.set(cs, DERIVATION_IGNORABLE, MY_REPERTOIRE_ASCII); } Type type() const override { return NULL_ITEM; } bool vcol_assignment_allowed_value() const override { return true; } bool val_bool() override; double val_real() override; longlong val_int() override; String *val_str(String *str) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; longlong val_datetime_packed(THD *) override; longlong val_time_packed(THD *) override; int save_in_field(Field *field, bool no_conversions) override; int save_safe_in_field(Field *field) override; bool send(Protocol *protocol, st_value *buffer) override; const Type_handler *type_handler() const override { return &type_handler_null; } bool basic_const_item() const override { return true; } Item *clone_item(THD *thd) const override; bool const_is_null() const override { return true; } bool is_null() override { return true; } void print(String *str, enum_query_type) override { str->append(NULL_clex_str); } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override; bool check_partition_func_processor(void *) override { return false; } Item_basic_constant *make_string_literal_concat(THD *thd, const LEX_CSTRING *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_null_result :public Item_null { public: Field *result_field; Item_null_result(THD *thd): Item_null(thd), result_field(0) {} bool is_result_field() override { return result_field != 0; } const Type_handler *type_handler() const override { if (result_field) return result_field->type_handler(); return &type_handler_null; } Field *create_tmp_field_ex(MEM_ROOT *, TABLE *, Tmp_field_src *, const Tmp_field_param *) override { DBUG_ASSERT(0); return NULL; } void save_in_result_field(bool no_conversions) override { save_in_field(result_field, no_conversions); } bool check_partition_func_processor(void *int_arg) override { return true; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(full_name(), arg, VCOL_IMPOSSIBLE); } }; /* Item represents one placeholder ('?') of prepared statement Notes: Item_param::field_type() is used when this item is in a temporary table. This is NOT placeholder metadata sent to client, as this value is assigned after sending metadata (in setup_one_conversion_function). For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both in result set and placeholders metadata, no matter what type you will supply for this placeholder in mysql_stmt_execute. Item_param has two Type_handler pointers, which can point to different handlers: 1. In the Type_handler_hybrid_field_type member It's initialized in: - Item_param::setup_conversion(), for client-server PS protocol, according to the bind type. - Item_param::set_from_item(), for EXECUTE and EXECUTE IMMEDIATE, according to the actual parameter data type. 2. In the "value" member. It's initialized in: - Item_param::set_param_func(), for client-server PS protocol. - Item_param::set_from_item(), for EXECUTE and EXECUTE IMMEDIATE. */ class Item_param :public Item_basic_value, private Settable_routine_parameter, public Rewritable_query_parameter, private Type_handler_hybrid_field_type { /* NO_VALUE is a special value meaning that the parameter has not been assigned yet. Item_param::state is assigned to NO_VALUE in constructor and is used at prepare time. 1. At prepare time Item_param::fix_fields() sets "fixed" to true, but as Item_param::state is still NO_VALUE, Item_param::basic_const_item() returns false. This prevents various optimizations to happen at prepare time fix_fields(). For example, in this query: PREPARE stmt FROM 'SELECT FORMAT(10000,2,?)'; Item_param::basic_const_item() is tested from Item_func_format::fix_length_and_dec(). 2. At execute time: When Item_param gets a value (or a pseudo-value like DEFAULT_VALUE or IGNORE_VALUE): - Item_param::state changes from NO_VALUE to something else - Item_param::fixed is changed to true All Item_param::set_xxx() make sure to do so. In the state with an assigned value: - Item_param::basic_const_item() returns true - Item::type() returns NULL_ITEM or CONST_ITEM, depending on the value assigned. So in this state Item_param behaves in many cases like a literal. When Item_param::cleanup() is called: - Item_param::state does not change - Item_param::fixed changes to false Note, this puts Item_param into an inconsistent state: - Item_param::basic_const_item() still returns "true" - Item_param::type() still pretends to be a basic constant Item Both are not expected in combination with fixed==false. However, these methods are not really called in this state, see asserts in Item_param::basic_const_item() and Item_param::type(). When Item_param::reset() is called: - Item_param::state changes to NO_VALUE - Item_param::fixed changes to false */ enum enum_item_param_state { NO_VALUE, NULL_VALUE, SHORT_DATA_VALUE, LONG_DATA_VALUE, DEFAULT_VALUE, IGNORE_VALUE } state; void fix_temporal(uint32 max_length_arg, uint decimals_arg); struct CONVERSION_INFO { /* Character sets conversion info for string values. Character sets of client and connection defined at bind time are used for all conversions, even if one of them is later changed (i.e. between subsequent calls to mysql_stmt_execute). */ CHARSET_INFO *character_set_client; CHARSET_INFO *character_set_of_placeholder; /* This points at character set of connection if conversion to it is required (i. e. if placeholder typecode is not BLOB). Otherwise it's equal to character_set_client (to simplify check in convert_str_value()). */ CHARSET_INFO *final_character_set_of_str_value; private: bool needs_conversion() const { return final_character_set_of_str_value != character_set_of_placeholder; } bool convert(THD *thd, String *str); public: void set(THD *thd, CHARSET_INFO *cs); bool convert_if_needed(THD *thd, String *str) { /* Check is so simple because all charsets were set up properly in setup_one_conversion_function, where typecode of placeholder was also taken into account: the variables are different here only if conversion is really necessary. */ if (needs_conversion()) return convert(thd, str); str->set_charset(final_character_set_of_str_value); return false; } }; bool m_empty_string_is_null; class PValue_simple { public: union { longlong integer; double real; CONVERSION_INFO cs_info; MYSQL_TIME time; }; void swap(PValue_simple &other) { swap_variables(PValue_simple, *this, other); } }; class PValue: public Type_handler_hybrid_field_type, public PValue_simple, public Value_source { public: PValue(): Type_handler_hybrid_field_type(&type_handler_null) {} my_decimal m_decimal; String m_string; /* A buffer for string and long data values. Historically all allocated values returned from val_str() were treated as eligible to modification. I. e. in some cases Item_func_concat can append it's second argument to return value of the first one. Because of that we can't return the original buffer holding string data from val_str(), and have to have one buffer for data and another just pointing to the data. This is the latter one and it's returned from val_str(). Can not be declared inside the union as it's not a POD type. */ String m_string_ptr; void swap(PValue &other) { Type_handler_hybrid_field_type::swap(other); PValue_simple::swap(other); m_decimal.swap(other.m_decimal); m_string.swap(other.m_string); m_string_ptr.swap(other.m_string_ptr); } double val_real(const Type_std_attributes *attr) const; longlong val_int(const Type_std_attributes *attr) const; my_decimal *val_decimal(my_decimal *dec, const Type_std_attributes *attr); String *val_str(String *str, const Type_std_attributes *attr); }; PValue value; const String *value_query_val_str(THD *thd, String* str) const; Item *value_clone_item(THD *thd) const; bool is_evaluable_expression() const override; bool can_return_value() const; public: /* Used for bulk protocol only. */ enum enum_indicator_type indicator; const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } bool vcol_assignment_allowed_value() const override { switch (state) { case NULL_VALUE: case DEFAULT_VALUE: case IGNORE_VALUE: return true; case NO_VALUE: case SHORT_DATA_VALUE: case LONG_DATA_VALUE: break; } return false; } Item_param(THD *thd, const LEX_CSTRING *name_arg, uint pos_in_query_arg, uint len_in_query_arg); void cleanup() override { m_default_field= NULL; Item::cleanup(); } Type type() const override { // Don't pretend to be a constant unless value for this item is set. switch (state) { case NO_VALUE: return PARAM_ITEM; case NULL_VALUE: return NULL_ITEM; case SHORT_DATA_VALUE: return CONST_ITEM; case LONG_DATA_VALUE: return CONST_ITEM; case DEFAULT_VALUE: return PARAM_ITEM; case IGNORE_VALUE: return PARAM_ITEM; } DBUG_ASSERT(0); return PARAM_ITEM; } bool is_order_clause_position() const override { return state == SHORT_DATA_VALUE && type_handler()->is_order_clause_position_type(); } const Item_const *get_item_const() const override { switch (state) { case SHORT_DATA_VALUE: case LONG_DATA_VALUE: case NULL_VALUE: return this; case IGNORE_VALUE: case DEFAULT_VALUE: case NO_VALUE: break; } return NULL; } bool const_is_null() const override { return state == NULL_VALUE; } bool can_return_const_value(Item_result type) const { return can_return_value() && value.type_handler()->cmp_type() == type && type_handler()->cmp_type() == type; } const longlong *const_ptr_longlong() const override { return can_return_const_value(INT_RESULT) ? &value.integer : NULL; } const double *const_ptr_double() const override { return can_return_const_value(REAL_RESULT) ? &value.real : NULL; } const my_decimal *const_ptr_my_decimal() const override { return can_return_const_value(DECIMAL_RESULT) ? &value.m_decimal : NULL; } const MYSQL_TIME *const_ptr_mysql_time() const override { return can_return_const_value(TIME_RESULT) ? &value.time : NULL; } const String *const_ptr_string() const override { return can_return_const_value(STRING_RESULT) ? &value.m_string : NULL; } double val_real() override { return can_return_value() ? value.val_real(this) : 0e0; } longlong val_int() override { return can_return_value() ? value.val_int(this) : 0; } my_decimal *val_decimal(my_decimal *dec) override { return can_return_value() ? value.val_decimal(dec, this) : NULL; } String *val_str(String *str) override { return can_return_value() ? value.val_str(str, this) : NULL; } bool get_date(THD *thd, MYSQL_TIME *tm, date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *to) override { return Item_param::type_handler()->Item_param_val_native(thd, this, to); } int save_in_field(Field *field, bool no_conversions) override; void set_default(bool set_type_handler_null); void set_ignore(bool set_type_handler_null); void set_null(); void set_int(longlong i, uint32 max_length_arg); void set_double(double i); void set_decimal(const char *str, ulong length); void set_decimal(const my_decimal *dv, bool unsigned_arg); bool set_str(const char *str, ulong length, CHARSET_INFO *fromcs, CHARSET_INFO *tocs); bool set_longdata(const char *str, ulong length); void set_time(MYSQL_TIME *tm, timestamp_type type, uint32 max_length_arg); void set_time(const MYSQL_TIME *tm, uint32 max_length_arg, uint decimals_arg); bool set_from_item(THD *thd, Item *item); void reset(); void set_param_tiny(uchar **pos, ulong len); void set_param_short(uchar **pos, ulong len); void set_param_int32(uchar **pos, ulong len); void set_param_int64(uchar **pos, ulong len); void set_param_float(uchar **pos, ulong len); void set_param_double(uchar **pos, ulong len); void set_param_decimal(uchar **pos, ulong len); void set_param_time(uchar **pos, ulong len); void set_param_datetime(uchar **pos, ulong len); void set_param_date(uchar **pos, ulong len); void set_param_str(uchar **pos, ulong len); void setup_conversion(THD *thd, uchar param_type); void setup_conversion_blob(THD *thd); void setup_conversion_string(THD *thd, CHARSET_INFO *fromcs); /* Assign placeholder value from bind data. Note, that 'len' has different semantics in embedded library (as we don't need to check that packet is not broken there). See sql_prepare.cc for details. */ void set_param_func(uchar **pos, ulong len) { /* To avoid Item_param::set_xxx() asserting on data type mismatch, we set the value type handler here: - It can not be initialized yet after Item_param::setup_conversion(). - Also, for LIMIT clause parameters, the value type handler might have changed from the real type handler to type_handler_longlong. So here we'll restore it. */ const Type_handler *h= Item_param::type_handler(); value.set_handler(h); h->Item_param_set_param_func(this, pos, len); } bool set_value(THD *thd, const Type_all_attributes *attr, const st_value *val, const Type_handler *h) { value.set_handler(h); // See comments in set_param_func() return h->Item_param_set_from_value(thd, this, attr, val); } bool set_limit_clause_param(longlong nr) { value.set_handler(&type_handler_slonglong); set_int(nr, MY_INT64_NUM_DECIMAL_DIGITS); return !unsigned_flag && value.integer < 0; } const String *query_val_str(THD *thd, String *str) const; bool convert_str_value(THD *thd); /* If value for parameter was not set we treat it as non-const so no one will use parameters value in fix_fields still parameter is constant during execution. */ bool const_item() const override { return state != NO_VALUE; } table_map used_tables() const override { return state != NO_VALUE ? (table_map)0 : PARAM_TABLE_BIT; } void print(String *str, enum_query_type query_type) override; bool is_null() override { DBUG_ASSERT(state != NO_VALUE); return state == NULL_VALUE; } bool basic_const_item() const override; bool has_no_value() const { return state == NO_VALUE; } bool has_long_data_value() const { return state == LONG_DATA_VALUE; } bool has_int_value() const { return state == SHORT_DATA_VALUE && value.type_handler()->cmp_type() == INT_RESULT; } bool is_stored_routine_parameter() const override { return true; } /* This method is used to make a copy of a basic constant item when propagating constants in the optimizer. The reason to create a new item and not use the existing one is not precisely known (2005/04/16). Probably we are trying to preserve tree structure of items, in other words, avoid pointing at one item from two different nodes of the tree. Return a new basic constant item if parameter value is a basic constant, assert otherwise. This method is called only if basic_const_item returned TRUE. */ Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override; Item *clone_item(THD *thd) const override; void set_param_type_and_swap_value(Item_param *from); Rewritable_query_parameter *get_rewritable_query_parameter() override { return this; } Settable_routine_parameter *get_settable_routine_parameter() override { return m_is_settable_routine_parameter ? this : nullptr; } bool append_for_log(THD *thd, String *str) override; bool check_vcol_func_processor(void *) override { return false; } Item *do_get_copy(THD *thd) const override { return nullptr; } Item *do_build_clone(THD *thd) const override { return nullptr; } bool add_as_clone(THD *thd); void sync_clones(); bool register_clone(Item_param *i) { return m_clones.push_back(i); } void raise_error_not_evaluable() override { invalid_default_param(); } private: void invalid_default_param() const; bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override; void set_out_param_info(Send_field *info) override; public: const Send_field *get_out_param_info() const override; Item_param *get_item_param() override { return this; } void make_send_field(THD *thd, Send_field *field) override; /** See comments on @see Item::associate_with_target_field for method description */ bool associate_with_target_field(THD *, Item_field *field) override { m_associated_field= field; return false; } bool assign_default(Field *field); private: Send_field *m_out_param_info; bool m_is_settable_routine_parameter; /* Array of all references of this parameter marker used in a CTE to its clones created for copies of this marker used the CTE's copies. It's used to synchronize the actual value of the parameter with the values of the clones. */ Mem_root_array m_clones; Item_field *m_associated_field; Field *m_default_field; }; class Item_int :public Item_num { public: longlong value; Item_int(THD *thd, int32 i,size_t length= MY_INT32_NUM_DECIMAL_DIGITS): Item_num(thd), value((longlong) i) { max_length=(uint32)length; } Item_int(THD *thd, longlong i,size_t length= MY_INT64_NUM_DECIMAL_DIGITS): Item_num(thd), value(i) { max_length=(uint32)length; } Item_int(THD *thd, ulonglong i, size_t length= MY_INT64_NUM_DECIMAL_DIGITS): Item_num(thd), value((longlong)i) { max_length=(uint32)length; unsigned_flag= 1; } Item_int(THD *thd, const char *str_arg,longlong i,size_t length): Item_num(thd), value(i) { max_length=(uint32)length; name.str= str_arg; name.length= safe_strlen(name.str); } Item_int(THD *thd, const char *str_arg,longlong i,size_t length, bool flag): Item_num(thd), value(i) { max_length=(uint32)length; name.str= str_arg; name.length= safe_strlen(name.str); unsigned_flag= flag; } Item_int(const char *str_arg,longlong i,size_t length): Item_num(), value(i) { max_length=(uint32)length; name.str= str_arg; name.length= safe_strlen(name.str); unsigned_flag= 1; } Item_int(THD *thd, const char *str_arg, size_t length=64); const Type_handler *type_handler() const override { return type_handler_long_or_longlong(); } Field *create_field_for_create_select(MEM_ROOT *root, TABLE *table) override { return tmp_table_field_from_field_type(root, table); } const longlong *const_ptr_longlong() const override { return &value; } bool val_bool() override { return value != 0; } longlong val_int() override { DBUG_ASSERT(!is_cond()); return value; } longlong val_int_min() const override { return value; } double val_real() override { return (double) value; } my_decimal *val_decimal(my_decimal *) override; String *val_str(String*) override; int save_in_field(Field *field, bool no_conversions) override; bool is_order_clause_position() const override { return true; } Item *clone_item(THD *thd) const override; void print(String *str, enum_query_type query_type) override; Item *neg(THD *thd) override; decimal_digits_t decimal_precision() const override { return (decimal_digits_t) (max_length - MY_TEST(value < 0)); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /* We sometimes need to distinguish a number from a boolean: a[1] and a[true] are different things in XPath. Also in JSON boolean values should be treated differently. */ class Item_bool :public Item_int { public: Item_bool(THD *thd, const char *str_arg, longlong i): Item_int(thd, str_arg, i, 1) {} Item_bool(THD *thd, bool i) :Item_int(thd, (longlong) i, 1) { } Item_bool(const char *str_arg, longlong i): Item_int(str_arg, i, 1) {} bool is_bool_literal() const override { return true; } Item *neg_transformer(THD *thd) override; const Type_handler *type_handler() const override { return &type_handler_bool; } const Type_handler *fixed_type_handler() const override { return &type_handler_bool; } void quick_fix_field() override { /* We can get here when Item_bool is created instead of a constant predicate at various condition optimization stages in sql_select. */ } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_bool_static :public Item_bool { public: Item_bool_static(const char *str_arg, longlong i): Item_bool(str_arg, i) {}; void set_join_tab_idx(uint8 join_tab_idx_arg) override { DBUG_ASSERT(0); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; extern const Item_bool_static Item_false, Item_true; class Item_uint :public Item_int { public: Item_uint(THD *thd, const char *str_arg, size_t length); Item_uint(THD *thd, ulonglong i): Item_int(thd, i, 10) {} Item_uint(THD *thd, const char *str_arg, longlong i, uint length); double val_real() override { return ulonglong2double((ulonglong)value); } Item *clone_item(THD *thd) const override; Item *neg(THD *thd) override; decimal_digits_t decimal_precision() const override { return decimal_digits_t(max_length); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_datetime :public Item_int { protected: MYSQL_TIME ltime; public: Item_datetime(THD *thd): Item_int(thd, 0) { unsigned_flag=0; } int save_in_field(Field *field, bool no_conversions) override; longlong val_int() override; double val_real() override { return (double)val_int(); } void set(longlong packed, enum_mysql_timestamp_type ts_type); bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate) override { *to= ltime; return false; } }; /* decimal (fixed point) constant */ class Item_decimal :public Item_num { protected: my_decimal decimal_value; public: Item_decimal(THD *thd, const char *str_arg, size_t length, CHARSET_INFO *charset); Item_decimal(THD *thd, const char *str, const my_decimal *val_arg, uint decimal_par, uint length); Item_decimal(THD *thd, const my_decimal *value_par); Item_decimal(THD *thd, longlong val, bool unsig); Item_decimal(THD *thd, double val, int precision, int scale); Item_decimal(THD *thd, const uchar *bin, int precision, int scale); const Type_handler *type_handler() const override { return &type_handler_newdecimal; } bool val_bool() override { return decimal_value.to_bool(); } longlong val_int() override { DBUG_ASSERT(!is_cond()); return decimal_value.to_longlong(unsigned_flag); } double val_real() override { return decimal_value.to_double(); } String *val_str(String *to) override { return decimal_value.to_string(to); } my_decimal *val_decimal(my_decimal *val) override { return &decimal_value; } const my_decimal *const_ptr_my_decimal() const override { return &decimal_value; } int save_in_field(Field *field, bool no_conversions) override; Item *clone_item(THD *thd) const override; void print(String *str, enum_query_type query_type) override { decimal_value.to_string(&str_value); str->append(str_value); } Item *neg(THD *thd) override; decimal_digits_t decimal_precision() const override { return decimal_value.precision(); } void set_decimal_value(my_decimal *value_par); Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_float :public Item_num { const char *presentation; public: double value; Item_float(THD *thd, const char *str_arg, size_t length); Item_float(THD *thd, const char *str, double val_arg, uint decimal_par, uint length): Item_num(thd), value(val_arg) { presentation= name.str= str; name.length= safe_strlen(str); decimals=(uint8) decimal_par; max_length= length; } Item_float(THD *thd, double value_par, uint decimal_par): Item_num(thd), presentation(0), value(value_par) { decimals= (uint8) decimal_par; } int save_in_field(Field *field, bool no_conversions) override; const Type_handler *type_handler() const override { return &type_handler_double; } const double *const_ptr_double() const override { return &value; } bool val_bool() override { return value != 0.0; } double val_real() override { return value; } longlong val_int() override { DBUG_ASSERT(!is_cond()); if (value <= (double) LONGLONG_MIN) { return LONGLONG_MIN; } else if (value >= (double) (ulonglong) LONGLONG_MAX) { return LONGLONG_MAX; } return (longlong) rint(value); } String *val_str(String*) override; my_decimal *val_decimal(my_decimal *) override; Item *clone_item(THD *thd) const override; Item *neg(THD *thd) override; void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_static_float_func :public Item_float { const char *func_name; public: Item_static_float_func(THD *thd, const char *str, double val_arg, uint decimal_par, uint length): Item_float(thd, NullS, val_arg, decimal_par, length), func_name(str) {} void print(String *str, enum_query_type) override { str->append(func_name, strlen(func_name)); } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override { return const_charset_converter(thd, tocs, true, func_name); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_string :public Item_literal { protected: void fix_from_value(Derivation dv, const Metadata metadata) { fix_charset_and_length(str_value.charset(), dv, metadata); } void fix_and_set_name_from_value(THD *thd, Derivation dv, const Metadata metadata) { fix_from_value(dv, metadata); set_name(thd, &str_value); } protected: /* Just create an item and do not fill string representation */ Item_string(THD *thd, CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE): Item_literal(thd) { collation.set(cs, dv); max_length= 0; set_name(thd, NULL, 0, system_charset_info); decimals= NOT_FIXED_DEC; } public: Item_string(THD *thd, CHARSET_INFO *csi, const char *str_arg, uint length_arg) :Item_literal(thd) { collation.set(csi, DERIVATION_COERCIBLE); set_name(thd, NULL, 0, system_charset_info); decimals= NOT_FIXED_DEC; str_value.copy(str_arg, length_arg, csi); max_length= str_value.numchars() * csi->mbmaxlen; } // Constructors with the item name set from its value Item_string(THD *thd, const char *str, uint length, CHARSET_INFO *cs, Derivation dv, my_repertoire_t repertoire) :Item_literal(thd) { str_value.set_or_copy_aligned(str, length, cs); fix_and_set_name_from_value(thd, dv, Metadata(&str_value, repertoire)); } Item_string(THD *thd, const char *str, size_t length, CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE) :Item_literal(thd) { str_value.set_or_copy_aligned(str, length, cs); fix_and_set_name_from_value(thd, dv, Metadata(&str_value)); } Item_string(THD *thd, const String *str, CHARSET_INFO *tocs, uint *conv_errors, Derivation dv, my_repertoire_t repertoire) :Item_literal(thd) { if (str_value.copy(str, tocs, conv_errors)) str_value.set("", 0, tocs); // EOM ? str_value.mark_as_const(); fix_and_set_name_from_value(thd, dv, Metadata(&str_value, repertoire)); } // Constructors with an externally provided item name Item_string(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str, CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE) :Item_literal(thd) { str_value.set_or_copy_aligned(str.str, str.length, cs); fix_from_value(dv, Metadata(&str_value)); set_name(thd, name_par); } Item_string(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str, CHARSET_INFO *cs, Derivation dv, my_repertoire_t repertoire) :Item_literal(thd) { str_value.set_or_copy_aligned(str.str, str.length, cs); fix_from_value(dv, Metadata(&str_value, repertoire)); set_name(thd, name_par); } void print_value(String *to) const { str_value.print(to); } bool val_bool() override { return val_real() != 0.0; } double val_real() override; longlong val_int() override; const String *const_ptr_string() const override { return &str_value; } String *val_str(String*) override { return (String*) &str_value; } my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_string(thd, ltime, fuzzydate); } int save_in_field(Field *field, bool no_conversions) override; const Type_handler *type_handler() const override { return &type_handler_varchar; } Item *clone_item(THD *thd) const override; Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override { return const_charset_converter(thd, tocs, true); } inline void append(const char *str, uint length) { str_value.append(str, length); max_length= str_value.numchars() * collation.collation->mbmaxlen; } void print(String *str, enum_query_type query_type) override; /** Return TRUE if character-set-introducer was explicitly specified in the original query for this item (text literal). This operation is to be called from Item_string::print(). The idea is that when a query is generated (re-constructed) from the Item-tree, character-set-introducers should appear only for those literals, where they were explicitly specified by the user. Otherwise, that may lead to loss collation information (character set introducers implies default collation for the literal). Basically, that makes sense only for views and hopefully will be gone one day when we start using original query as a view definition. @return This operation returns the value of m_cs_specified attribute. @retval TRUE if character set introducer was explicitly specified in the original query. @retval FALSE otherwise. */ virtual bool is_cs_specified() const { return false; } String *check_well_formed_result(bool send_error) { return Item::check_well_formed_result(&str_value, send_error); } Item_basic_constant *make_string_literal_concat(THD *thd, const LEX_CSTRING *) override; Item *make_odbc_literal(THD *thd, const LEX_CSTRING *typestr) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_string_with_introducer :public Item_string { public: Item_string_with_introducer(THD *thd, const LEX_CSTRING &str, CHARSET_INFO *cs): Item_string(thd, str.str, str.length, cs) { } Item_string_with_introducer(THD *thd, const LEX_CSTRING &name_arg, const LEX_CSTRING &str, CHARSET_INFO *tocs): Item_string(thd, name_arg, str, tocs) { } bool is_cs_specified() const override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_string_sys :public Item_string { public: Item_string_sys(THD *thd, const char *str, uint length): Item_string(thd, str, length, system_charset_info) { } Item_string_sys(THD *thd, const char *str): Item_string(thd, str, (uint) strlen(str), system_charset_info) { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_string_ascii :public Item_string { public: Item_string_ascii(THD *thd, const char *str, uint length): Item_string(thd, str, length, &my_charset_latin1, DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII) { } Item_string_ascii(THD *thd, const char *str): Item_string(thd, str, (uint) strlen(str), &my_charset_latin1, DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII) { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_static_string_func :public Item_string { const LEX_CSTRING func_name; public: Item_static_string_func(THD *thd, const LEX_CSTRING &name_par, const LEX_CSTRING &str, CHARSET_INFO *cs, Derivation dv= DERIVATION_COERCIBLE): Item_string(thd, LEX_CSTRING({NullS,0}), str, cs, dv), func_name(name_par) {} Item_static_string_func(THD *thd, const LEX_CSTRING &name_par, const String *str, CHARSET_INFO *tocs, uint *conv_errors, Derivation dv, my_repertoire_t repertoire): Item_string(thd, str, tocs, conv_errors, dv, repertoire), func_name(name_par) {} Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override { return const_charset_converter(thd, tocs, true, func_name.str); } void print(String *str, enum_query_type) override { str->append(func_name); } bool check_partition_func_processor(void *) override { return true; } bool check_vcol_func_processor(void *arg) override { // VCOL_TIME_FUNC because the value is not constant, but does not // require fix_fields() to be re-run for every statement. return mark_unsupported_function(func_name.str, arg, VCOL_TIME_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* for show tables */ class Item_partition_func_safe_string: public Item_string { public: Item_partition_func_safe_string(THD *thd, const LEX_CSTRING &name_arg, uint length, CHARSET_INFO *cs): Item_string(thd, name_arg, LEX_CSTRING({0,0}), cs) { max_length= length; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("safe_string", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** Item_empty_string -- is a utility class to put an item into List which is then used in protocol.send_result_set_metadata() when sending SHOW output to the client. */ class Item_empty_string :public Item_partition_func_safe_string { public: Item_empty_string(THD *thd, const LEX_CSTRING &header, uint length, CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci) :Item_partition_func_safe_string(thd, header, length * cs->mbmaxlen, cs) { } Item_empty_string(THD *thd, const char *header, uint length, CHARSET_INFO *cs= &my_charset_utf8mb3_general_ci) :Item_partition_func_safe_string(thd, LEX_CSTRING({header, strlen(header)}), length * cs->mbmaxlen, cs) { } void make_send_field(THD *thd, Send_field *field) override; }; class Item_return_int :public Item_int { enum_field_types int_field_type; public: Item_return_int(THD *thd, const char *name_arg, uint length, enum_field_types field_type_arg, longlong value_arg= 0): Item_int(thd, name_arg, value_arg, length), int_field_type(field_type_arg) { unsigned_flag=1; } const Type_handler *type_handler() const override { const Type_handler *h= Type_handler::get_handler_by_field_type(int_field_type); return unsigned_flag ? h->type_handler_unsigned() : h; } }; /** Item_hex_constant -- a common class for hex literals: X'HHHH' and 0xHHHH */ class Item_hex_constant: public Item_literal { private: void hex_string_init(THD *thd, const char *str, size_t str_length); public: Item_hex_constant(THD *thd): Item_literal(thd) { hex_string_init(thd, "", 0); } Item_hex_constant(THD *thd, const char *str, size_t str_length): Item_literal(thd) { hex_string_init(thd, str, str_length); } const Type_handler *type_handler() const override { return &type_handler_varchar; } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override { return const_charset_converter(thd, tocs, true); } const String *const_ptr_string() const override { return &str_value; } String *val_str(String*) override { return &str_value; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } }; /** Item_hex_hybrid -- is a class implementing 0xHHHH literals, e.g.: SELECT 0x3132; They can behave as numbers and as strings depending on context. */ class Item_hex_hybrid: public Item_hex_constant { public: Item_hex_hybrid(THD *thd): Item_hex_constant(thd) {} Item_hex_hybrid(THD *thd, const char *str, size_t str_length): Item_hex_constant(thd, str, str_length) {} const Type_handler *type_handler() const override { return &type_handler_hex_hybrid; } decimal_digits_t decimal_precision() const override; bool val_bool() override { return longlong_from_hex_hybrid(str_value.ptr(), str_value.length()) != 0; } double val_real() override { return (double) (ulonglong) Item_hex_hybrid::val_int(); } longlong val_int() override { DBUG_ASSERT(!is_cond()); return longlong_from_hex_hybrid(str_value.ptr(), str_value.length()); } my_decimal *val_decimal(my_decimal *decimal_value) override { longlong value= Item_hex_hybrid::val_int(); int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value); return decimal_value; } int save_in_field(Field *field, bool) override { field->set_notnull(); return field->store_hex_hybrid(str_value.ptr(), str_value.length()); } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** Item_hex_string -- is a class implementing X'HHHH' literals, e.g.: SELECT X'3132'; Unlike Item_hex_hybrid, X'HHHH' literals behave as strings in all contexts. X'HHHH' are also used in replication of string constants in case of "dangerous" charsets (sjis, cp932, big5, gbk) who can have backslash (0x5C) as the second byte of a multi-byte character, so using '\' escaping for these charsets is not desirable. */ class Item_hex_string: public Item_hex_constant { public: Item_hex_string(THD *thd): Item_hex_constant(thd) {} Item_hex_string(THD *thd, const char *str, size_t str_length): Item_hex_constant(thd, str, str_length) {} bool val_bool() override { return double_from_string_with_check(&str_value) != 0.0; } longlong val_int() override { DBUG_ASSERT(!is_cond()); return longlong_from_string_with_check(&str_value); } double val_real() override { return double_from_string_with_check(&str_value); } my_decimal *val_decimal(my_decimal *decimal_value) override { return val_decimal_from_string(decimal_value); } int save_in_field(Field *field, bool) override { field->set_notnull(); return field->store(str_value.ptr(), str_value.length(), collation.collation); } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_bin_string: public Item_hex_hybrid { public: Item_bin_string(THD *thd, const char *str, size_t str_length); void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_timestamp_literal: public Item_literal { Timestamp_or_zero_datetime m_value; public: Item_timestamp_literal(THD *thd) :Item_literal(thd) { } const Type_handler *type_handler() const override { return &type_handler_timestamp2; } int save_in_field(Field *field, bool) override { Timestamp_or_zero_datetime_native native(m_value, decimals); return native.save_in_field(field, decimals); } bool val_bool() override { return m_value.to_bool(); } longlong val_int() override { DBUG_ASSERT(!is_cond()); return m_value.to_datetime(current_thd).to_longlong(); } double val_real() override { return m_value.to_datetime(current_thd).to_double(); } String *val_str(String *to) override { return m_value.to_datetime(current_thd).to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { return m_value.to_datetime(current_thd).to_decimal(to); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { bool res= m_value.to_TIME(thd, ltime, fuzzydate); DBUG_ASSERT(!res); return res; } bool val_native(THD *thd, Native *to) override { return m_value.to_native(to, decimals); } void set_value(const Timestamp_or_zero_datetime &value) { m_value= value; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_temporal_literal :public Item_literal { public: Item_temporal_literal(THD *thd) :Item_literal(thd) { collation= DTCollation_numeric(); decimals= 0; } Item_temporal_literal(THD *thd, decimal_digits_t dec_arg): Item_literal(thd) { collation= DTCollation_numeric(); decimals= dec_arg; } int save_in_field(Field *field, bool no_conversions) override { return save_date_in_field(field, no_conversions); } }; /** DATE'2010-01-01' */ class Item_date_literal: public Item_temporal_literal { protected: Date cached_time; bool update_null() { return (maybe_null() && (null_value= cached_time.check_date_with_warn(current_thd))); } public: Item_date_literal(THD *thd, const Date *ltime) :Item_temporal_literal(thd), cached_time(*ltime) { DBUG_ASSERT(cached_time.is_valid_date()); max_length= MAX_DATE_WIDTH; /* If date has zero month or day, it can return NULL in case of NO_ZERO_DATE or NO_ZERO_IN_DATE. If date is `February 30`, it can return NULL in case if no ALLOW_INVALID_DATES is set. We can't set null_value using the current sql_mode here in constructor, because sql_mode can change in case of prepared statements between PREPARE and EXECUTE. Here we only set maybe_null to true if the value has such anomalies. Later (during execution time), if maybe_null is true, then the value will be checked per row, according to the execution time sql_mode. The check_date() below call should cover all cases mentioned. */ set_maybe_null(cached_time.check_date(TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE)); } const Type_handler *type_handler() const override { return &type_handler_newdate; } void print(String *str, enum_query_type query_type) override; const MYSQL_TIME *const_ptr_mysql_time() const override { return cached_time.get_mysql_time(); } Item *clone_item(THD *thd) const override; bool val_bool() override { return update_null() ? false : cached_time.to_bool(); } longlong val_int() override { DBUG_ASSERT(!is_cond()); return update_null() ? 0 : cached_time.to_longlong(); } double val_real() override { return update_null() ? 0 : cached_time.to_double(); } String *val_str(String *to) override { return update_null() ? 0 : cached_time.to_string(to); } my_decimal *val_decimal(my_decimal *to) override { return update_null() ? 0 : cached_time.to_decimal(to); } longlong val_datetime_packed(THD *thd) override { return update_null() ? 0 : cached_time.valid_date_to_packed(); } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** TIME'10:10:10' */ class Item_time_literal final: public Item_temporal_literal { protected: Time cached_time; public: Item_time_literal(THD *thd, const Time *ltime, decimal_digits_t dec_arg): Item_temporal_literal(thd, dec_arg), cached_time(*ltime) { DBUG_ASSERT(cached_time.is_valid_time()); max_length= MIN_TIME_WIDTH + (decimals ? decimals + 1 : 0); } const Type_handler *type_handler() const override { return &type_handler_time2; } void print(String *str, enum_query_type query_type) override; const MYSQL_TIME *const_ptr_mysql_time() const override { return cached_time.get_mysql_time(); } Item *clone_item(THD *thd) const override; bool val_bool() override { return cached_time.to_bool(); } longlong val_int() override { DBUG_ASSERT(!is_cond()); return cached_time.to_longlong(); } double val_real() override { return cached_time.to_double(); } String *val_str(String *to) override { return cached_time.to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { return cached_time.to_decimal(to); } longlong val_time_packed(THD *thd) override { return cached_time.valid_time_to_packed(); } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *to) override { return Time(thd, this).to_native(to, decimals); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** TIMESTAMP'2001-01-01 10:20:30' */ class Item_datetime_literal: public Item_temporal_literal { protected: Datetime cached_time; bool update_null() { return (maybe_null() && (null_value= cached_time.check_date_with_warn(current_thd))); } public: Item_datetime_literal(THD *thd, const Datetime *ltime, decimal_digits_t dec_arg): Item_temporal_literal(thd, dec_arg), cached_time(*ltime) { DBUG_ASSERT(cached_time.is_valid_datetime()); max_length= MAX_DATETIME_WIDTH + (decimals ? decimals + 1 : 0); // See the comment on maybe_null in Item_date_literal set_maybe_null(cached_time.check_date(TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE)); } const Type_handler *type_handler() const override { return &type_handler_datetime2; } void print(String *str, enum_query_type query_type) override; const MYSQL_TIME *const_ptr_mysql_time() const override { return cached_time.get_mysql_time(); } Item *clone_item(THD *thd) const override; bool val_bool() override { return update_null() ? false : cached_time.to_bool(); } longlong val_int() override { DBUG_ASSERT(!is_cond()); return update_null() ? 0 : cached_time.to_longlong(); } double val_real() override { return update_null() ? 0 : cached_time.to_double(); } String *val_str(String *to) override { return update_null() ? NULL : cached_time.to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { return update_null() ? NULL : cached_time.to_decimal(to); } longlong val_datetime_packed(THD *thd) override { return update_null() ? 0 : cached_time.valid_datetime_to_packed(); } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** An error-safe counterpart for Item_date_literal */ class Item_date_literal_for_invalid_dates: public Item_date_literal { /** During equal field propagation we can replace non-temporal constants found in equalities to their native temporal equivalents: WHERE date_column='2001-01-01' ... -> WHERE date_column=DATE'2001-01-01' ... This is done to make the equal field propagation code handle mixtures of different temporal types in the same expressions easier (MDEV-8706), e.g. WHERE LENGTH(date_column)=10 AND date_column=TIME'00:00:00' Item_date_literal_for_invalid_dates::get_date() (unlike the regular Item_date_literal::get_date()) does not check the result for NO_ZERO_IN_DATE and NO_ZERO_DATE, always returns success (false), and does not produce error/warning messages. We need these _for_invalid_dates classes to be able to rewrite: SELECT * FROM t1 WHERE date_column='0000-00-00' ... to: SELECT * FROM t1 WHERE date_column=DATE'0000-00-00' ... to avoid returning NULL value instead of '0000-00-00' even in sql_mode=TRADITIONAL. */ public: Item_date_literal_for_invalid_dates(THD *thd, const Date *ltime) :Item_date_literal(thd, ltime) { base_flags&= ~item_base_t::MAYBE_NULL; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { cached_time.copy_to_mysql_time(ltime); return (null_value= false); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** An error-safe counterpart for Item_datetime_literal (see Item_date_literal_for_invalid_dates for comments) */ class Item_datetime_literal_for_invalid_dates final: public Item_datetime_literal { public: Item_datetime_literal_for_invalid_dates(THD *thd, const Datetime *ltime, decimal_digits_t dec_arg) :Item_datetime_literal(thd, ltime, dec_arg) { base_flags&= ~item_base_t::MAYBE_NULL; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { cached_time.copy_to_mysql_time(ltime); return (null_value= false); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Used_tables_and_const_cache { public: /* In some cases used_tables_cache is not what used_tables() return so the method should be used where one need used tables bit map (even internally in Item_func_* code). */ table_map used_tables_cache; bool const_item_cache; Used_tables_and_const_cache() :used_tables_cache(0), const_item_cache(true) { } Used_tables_and_const_cache(const Used_tables_and_const_cache *other) :used_tables_cache(other->used_tables_cache), const_item_cache(other->const_item_cache) { } inline void used_tables_and_const_cache_init() { used_tables_cache= 0; const_item_cache= true; } inline void used_tables_and_const_cache_join(const Item *item) { used_tables_cache|= item->used_tables(); const_item_cache&= item->const_item(); } inline void used_tables_and_const_cache_update_and_join(Item *item) { item->update_used_tables(); used_tables_and_const_cache_join(item); } /* Call update_used_tables() for all "argc" items in the array "argv" and join with the current cache. "this" must be initialized with a constructor or re-initialized with used_tables_and_const_cache_init(). */ void used_tables_and_const_cache_update_and_join(uint argc, Item **argv) { for (uint i=0 ; i < argc ; i++) used_tables_and_const_cache_update_and_join(argv[i]); } /* Call update_used_tables() for all items in the list and join with the current cache. "this" must be initialized with a constructor or re-initialized with used_tables_and_const_cache_init(). */ void used_tables_and_const_cache_update_and_join(List &list) { List_iterator_fast li(list); Item *item; while ((item=li++)) used_tables_and_const_cache_update_and_join(item); } }; /** An abstract class representing common features of regular functions and aggregate functions. */ class Item_func_or_sum: public Item_result_field, public Item_args, public Used_tables_and_const_cache { protected: bool agg_arg_charsets(DTCollation &c, Item **items, uint nitems, uint flags, int item_sep) { return Type_std_attributes::agg_arg_charsets(c, func_name_cstring(), items, nitems, flags, item_sep); } bool agg_arg_charsets_for_string_result(DTCollation &c, Item **items, uint nitems, int item_sep= 1) { return Type_std_attributes:: agg_arg_charsets_for_string_result(c, func_name_cstring(), items, nitems, item_sep); } bool agg_arg_charsets_for_string_result_with_comparison(DTCollation &c, Item **items, uint nitems, int item_sep= 1) { return Type_std_attributes:: agg_arg_charsets_for_string_result_with_comparison(c, func_name_cstring(), items, nitems, item_sep); } /* Aggregate arguments for comparison, e.g: a=b, a LIKE b, a RLIKE b - don't convert to @@character_set_connection if all arguments are numbers - don't allow DERIVATION_NONE */ bool agg_arg_charsets_for_comparison(DTCollation &c, Item **items, uint nitems, int item_sep= 1) { return Type_std_attributes:: agg_arg_charsets_for_comparison(c, func_name_cstring(), items, nitems, item_sep); } public: // This method is used by Arg_comparator bool agg_arg_charsets_for_comparison(CHARSET_INFO **cs, Item **a, Item **b, bool allow_narrowing) { THD *thd= current_thd; DTCollation tmp; if (tmp.set((*a)->collation, (*b)->collation, MY_COLL_CMP_CONV) || tmp.derivation == DERIVATION_NONE) { my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0), (*a)->collation.collation->coll_name.str, (*a)->collation.derivation_name(), (*b)->collation.collation->coll_name.str, (*b)->collation.derivation_name(), func_name()); return true; } if (allow_narrowing && (*a)->collation.derivation == (*b)->collation.derivation) { // allow_narrowing==true only for = and <=> comparisons. if (Utf8_narrow::should_do_narrowing(thd, (*a)->collation.collation, (*b)->collation.collation)) { // a is a subset, b is a superset (e.g. utf8mb3 vs utf8mb4) *cs= (*b)->collation.collation; // Compare using the wider cset return false; } else if (Utf8_narrow::should_do_narrowing(thd, (*b)->collation.collation, (*a)->collation.collation)) { // a is a superset, b is a subset (e.g. utf8mb4 vs utf8mb3) *cs= (*a)->collation.collation; // Compare using the wider cset return false; } } /* If necessary, convert both *a and *b to the collation in tmp: */ Single_coll_err error_for_a= {(*b)->collation, true}; Single_coll_err error_for_b= {(*a)->collation, false}; if (agg_item_set_converter(tmp, func_name_cstring(), a, 1, MY_COLL_CMP_CONV, 1, /*just for error message*/ &error_for_a) || agg_item_set_converter(tmp, func_name_cstring(), b, 1, MY_COLL_CMP_CONV, 1, /*just for error message*/ &error_for_b)) return true; *cs= tmp.collation; return false; } public: Item_func_or_sum(THD *thd): Item_result_field(thd), Item_args() {} Item_func_or_sum(THD *thd, Item *a): Item_result_field(thd), Item_args(a) { } Item_func_or_sum(THD *thd, Item *a, Item *b): Item_result_field(thd), Item_args(a, b) { } Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c): Item_result_field(thd), Item_args(thd, a, b, c) { } Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c, Item *d): Item_result_field(thd), Item_args(thd, a, b, c, d) { } Item_func_or_sum(THD *thd, Item *a, Item *b, Item *c, Item *d, Item *e): Item_result_field(thd), Item_args(thd, a, b, c, d, e) { } Item_func_or_sum(THD *thd, Item_func_or_sum *item): Item_result_field(thd, item), Item_args(thd, item), Used_tables_and_const_cache(item) { } Item_func_or_sum(THD *thd, List &list): Item_result_field(thd), Item_args(thd, list) { } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { if (walk_args(processor, walk_subquery, arg)) return true; return (this->*processor)(arg); } /* Built-in schema, e.g. mariadb_schema, oracle_schema, maxdb_schema */ virtual const Schema *schema() const { // A function does not belong to a built-in schema by default return NULL; } /* This method is used for debug purposes to print the name of an item to the debug log. The second use of this method is as a helper function of print() and error messages, where it is applicable. To suit both goals it should return a meaningful, distinguishable and sintactically correct string. This method should not be used for runtime type identification, use enum {Sum}Functype and Item_func::functype()/Item_sum::sum_func() instead. Added here, to the parent class of both Item_func and Item_sum. NOTE: for Items inherited from Item_sum, func_name() and func_name_cstring() returns part of function name till first argument (including '(') to make difference in names for functions with 'distinct' clause and without 'distinct' and also to make printing of items inherited from Item_sum uniform. */ inline const char *func_name() const { return (char*) func_name_cstring().str; } virtual LEX_CSTRING func_name_cstring() const= 0; virtual bool fix_length_and_dec()= 0; bool const_item() const override { return const_item_cache; } table_map used_tables() const override { return used_tables_cache; } Item* do_build_clone(THD *thd) const override; Sql_mode_dependency value_depends_on_sql_mode() const override { return Item_args::value_depends_on_sql_mode_bit_or().soft_to_hard(); } }; class sp_head; class sp_name; struct st_sp_security_context; class Item_sp { protected: // Can be NULL in some non-SELECT queries Name_resolution_context *context; public: sp_name *m_name; sp_head *m_sp; TABLE *dummy_table; uchar result_buf[64]; sp_rcontext *func_ctx; MEM_ROOT sp_mem_root; Query_arena *sp_query_arena; /* The result field of the stored function. */ Field *sp_result_field; Item_sp(THD *thd, Name_resolution_context *context_arg, sp_name *name_arg); Item_sp(THD *thd, Item_sp *item); LEX_CSTRING func_name_cstring(THD *thd, bool is_package_function) const; void cleanup(); bool sp_check_access(THD *thd); bool execute(THD *thd, bool *null_value, Item **args, uint arg_count); bool execute_impl(THD *thd, Item **args, uint arg_count); bool init_result_field(THD *thd, uint max_length, uint maybe_null, bool *null_value, LEX_CSTRING *name); void process_error(THD *thd) { if (context) context->process_error(thd); } }; class Item_ref :public Item_ident { protected: void set_properties(); bool set_properties_only; // the item doesn't need full fix_fields public: enum Ref_Type { REF, DIRECT_REF, VIEW_REF, OUTER_REF, AGGREGATE_REF }; Item **ref; bool reference_trough_name; Item_ref(THD *thd, Name_resolution_context *context_arg, const LEX_CSTRING &db_arg, const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg): Item_ident(thd, context_arg, db_arg, table_name_arg, field_name_arg), set_properties_only(0), ref(0), reference_trough_name(1) {} Item_ref(THD *thd, Name_resolution_context *context_arg, const LEX_CSTRING &field_name_arg) :Item_ref(thd, context_arg, null_clex_str, null_clex_str, field_name_arg) { } /* This constructor is used in two scenarios: A) *item = NULL No initialization is performed, fix_fields() call will be necessary. B) *item points to an Item this Item_ref will refer to. This is used for GROUP BY. fix_fields() will not be called in this case, so we call set_properties to make this item "fixed". set_properties performs a subset of action Item_ref::fix_fields does, and this subset is enough for Item_ref's used in GROUP BY. TODO we probably fix a superset of problems like in BUG#6658. Check this with Bar, and if we have a more broader set of problems like this. */ Item_ref(THD *thd, Name_resolution_context *context_arg, Item **item, const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg, bool alias_name_used_arg= FALSE); Item_ref(THD *thd, TABLE_LIST *view_arg, Item **item, const LEX_CSTRING &field_name_arg, bool alias_name_used_arg= FALSE); /* Constructor need to process subselect with temporary tables (see Item) */ Item_ref(THD *thd, Item_ref *item) :Item_ident(thd, item), set_properties_only(0), ref(item->ref) {} enum Type type() const override { return REF_ITEM; } enum Type real_type() const override { return ref ? (*ref)->type() : REF_ITEM; } bool eq(const Item *item, bool binary_cmp) const override { const Item *it= item->real_item(); return ref && (*ref)->eq(it, binary_cmp); } void save_val(Field *to) override; void save_result(Field *to) override; double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; String *val_str(String* tmp) override; bool val_native(THD *thd, Native *to) override; bool is_null() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; longlong val_datetime_packed(THD *) override; longlong val_time_packed(THD *) override; double val_result() override; longlong val_int_result() override; String *str_result(String* tmp) override; bool val_native_result(THD *thd, Native *to) override; my_decimal *val_decimal_result(my_decimal *) override; bool val_bool_result() override; bool is_null_result() override; bool send(Protocol *prot, st_value *buffer) override; void make_send_field(THD *thd, Send_field *field) override; bool fix_fields(THD *, Item **) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; int save_in_field(Field *field, bool no_conversions) override; void save_org_in_field(Field *field, fast_field_copier optimizer_data) override; fast_field_copier setup_fast_field_copier(Field *field) override { return (*ref)->setup_fast_field_copier(field); } const Type_handler *type_handler() const override { return (*ref)->type_handler(); } const Type_handler *real_type_handler() const override { return (*ref)->real_type_handler(); } uint32 character_octet_length() const override { return Item_ref::real_item()->character_octet_length(); } Field *get_tmp_table_field() override { return result_field ? result_field : (*ref)->get_tmp_table_field(); } Item *get_tmp_table_item(THD *thd) override; Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override; Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override; table_map used_tables() const override; void update_used_tables() override; COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override { /* normilize_cond() replaced all conditions of type WHERE/HAVING field to: WHERE/HAVING field<>0 By the time of a build_equal_items() call, all such conditions should already be replaced. No Item_ref referencing to Item_field are possible. */ DBUG_ASSERT(real_type() != FIELD_ITEM); return Item_ident::build_equal_items(thd, inherited, link_item_fields, cond_equal_ref); } bool const_item() const override { return (*ref)->const_item(); } table_map not_null_tables() const override { return depended_from ? 0 : (*ref)->not_null_tables(); } bool find_not_null_fields(table_map allowed) override { return depended_from ? false : (*ref)->find_not_null_fields(allowed); } void save_in_result_field(bool no_conversions) override { (*ref)->save_in_field(result_field, no_conversions); } Item *real_item() override { return ref ? (*ref)->real_item() : this; } const Item *real_item() const { return const_cast(this)->Item_ref::real_item(); } const TYPELIB *get_typelib() const override { return ref ? (*ref)->get_typelib() : NULL; } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { if (ref && *ref) return (*ref)->walk(processor, walk_subquery, arg) || (this->*processor)(arg); else return FALSE; } Item* transform(THD *thd, Item_transformer, uchar *arg) override; Item* compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) override; bool enumerate_field_refs_processor(void *arg) override { return (*ref)->enumerate_field_refs_processor(arg); } void no_rows_in_result() override { (*ref)->no_rows_in_result(); } void restore_to_before_no_rows_in_result() override { (*ref)->restore_to_before_no_rows_in_result(); } void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return ref ? (*ref)->precedence() : DEFAULT_PRECEDENCE; } void cleanup() override; Item_field *field_for_view_update() override { return (*ref)->field_for_view_update(); } Load_data_outvar *get_load_data_outvar() override { return (*ref)->get_load_data_outvar(); } virtual Ref_Type ref_type() { return REF; } // Row emulation: forwarding of ROW-related calls to ref uint cols() const override { return ref && result_type() == ROW_RESULT ? (*ref)->cols() : 1; } Item* element_index(uint i) override { return ref && result_type() == ROW_RESULT ? (*ref)->element_index(i) : this; } Item** addr(uint i) override { return ref && result_type() == ROW_RESULT ? (*ref)->addr(i) : 0; } bool check_cols(uint c) override { return ref && result_type() == ROW_RESULT ? (*ref)->check_cols(c) : Item::check_cols(c); } bool null_inside() override { return ref && result_type() == ROW_RESULT ? (*ref)->null_inside() : 0; } void bring_value() override { if (ref && result_type() == ROW_RESULT) (*ref)->bring_value(); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("ref", arg, VCOL_IMPOSSIBLE); } bool basic_const_item() const override { return ref && (*ref)->basic_const_item(); } bool is_outer_field() const override { DBUG_ASSERT(fixed()); DBUG_ASSERT(ref); return (*ref)->is_outer_field(); } Item *do_build_clone(THD *thd) const override; /** Checks if the item tree that ref points to contains a subquery. */ Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool excl_dep_on_table(table_map tab_map) override { table_map used= used_tables(); if (used & OUTER_REF_TABLE_BIT) return false; return (used == tab_map) || (*ref)->excl_dep_on_table(tab_map); } bool excl_dep_on_grouping_fields(st_select_lex *sel) override { return (*ref)->excl_dep_on_grouping_fields(sel); } bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override { return (*ref)->excl_dep_on_in_subq_left_part(subq_pred); } bool cleanup_excluding_fields_processor(void *arg) override { Item *item= real_item(); if (item && item->type() == FIELD_ITEM && ((Item_field *)item)->field) return 0; return cleanup_processor(arg); } bool cleanup_excluding_const_fields_processor(void *arg) override { Item *item= real_item(); if (item && item->type() == FIELD_ITEM && ((Item_field *) item)->field && item->const_item()) return 0; return cleanup_processor(arg); } Item *field_transformer_for_having_pushdown(THD *thd, uchar *arg) override { return (*ref)->field_transformer_for_having_pushdown(thd, arg); } }; /* The same as Item_ref, but get value from val_* family of method to get value of item on which it referred instead of result* family. */ class Item_direct_ref :public Item_ref { public: Item_direct_ref(THD *thd, Name_resolution_context *context_arg, Item **item, const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg, bool alias_name_used_arg= FALSE): Item_ref(thd, context_arg, item, table_name_arg, field_name_arg, alias_name_used_arg) {} /* Constructor need to process subselect with temporary tables (see Item) */ Item_direct_ref(THD *thd, Item_direct_ref *item) : Item_ref(thd, item) {} Item_direct_ref(THD *thd, TABLE_LIST *view_arg, Item **item, const LEX_CSTRING &field_name_arg, bool alias_name_used_arg= FALSE): Item_ref(thd, view_arg, item, field_name_arg, alias_name_used_arg) {} bool fix_fields(THD *thd, Item **it) override { if ((*ref)->fix_fields_if_needed_for_scalar(thd, ref)) return TRUE; return Item_ref::fix_fields(thd, it); } void save_val(Field *to) override; /* Below we should have all val() methods as in Item_ref */ double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; String *val_str(String* tmp) override; bool val_native(THD *thd, Native *to) override; bool is_null() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; longlong val_datetime_packed(THD *) override; longlong val_time_packed(THD *) override; Ref_Type ref_type() override { return DIRECT_REF; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } /* Should be called if ref is changed */ inline void ref_changed() { set_properties(); } }; /** This class is the same as Item_direct_ref but created to wrap Item_ident before fix_fields() call */ class Item_direct_ref_to_ident :public Item_direct_ref { Item_ident *ident; public: Item_direct_ref_to_ident(THD *thd, Item_ident *item): Item_direct_ref(thd, item->context, (Item**)&item, item->table_name, item->field_name, FALSE) { ident= item; ref= (Item**)&ident; } bool fix_fields(THD *thd, Item **it) override { DBUG_ASSERT(ident->type() == FIELD_ITEM || ident->type() == REF_ITEM); if (ident->fix_fields_if_needed_for_scalar(thd, ref)) return TRUE; set_properties(); return FALSE; } void print(String *str, enum_query_type query_type) override { ident->print(str, query_type); } }; class Item_cache; class Expression_cache; class Expression_cache_tracker; /** The objects of this class can store its values in an expression cache. */ class Item_cache_wrapper :public Item_result_field { private: /* Pointer on the cached expression */ Item *orig_item; Expression_cache *expr_cache; /* In order to put the expression into the expression cache and return value of val_*() method, we will need to get the expression value twice (probably in different types). In order to avoid making two (potentially costly) orig_item->val_*() calls, we store expression value in this Item_cache object. */ Item_cache *expr_value; List parameters; Item *check_cache(); void cache(); void init_on_demand(); public: Item_cache_wrapper(THD *thd, Item *item_arg); ~Item_cache_wrapper(); Type type() const override { return EXPR_CACHE_ITEM; } Type real_type() const override { return orig_item->type(); } bool set_cache(THD *thd); Expression_cache_tracker* init_tracker(MEM_ROOT *mem_root); bool fix_fields(THD *thd, Item **it) override; void cleanup() override; Item *get_orig_item() const { return orig_item; } /* Methods of getting value which should be cached in the cache */ void save_val(Field *to) override; double val_real() override; longlong val_int() override; String *val_str(String* tmp) override; bool val_native(THD *thd, Native *to) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; bool is_null() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool send(Protocol *protocol, st_value *buffer) override; void save_org_in_field(Field *field, fast_field_copier) override { save_val(field); } void save_in_result_field(bool) override { save_val(result_field); } Item* get_tmp_table_item(THD *thd_arg) override; /* Following methods make this item transparent as much as possible */ void print(String *str, enum_query_type query_type) override; LEX_CSTRING full_name_cstring() const override { return orig_item->full_name_cstring(); } void make_send_field(THD *thd, Send_field *field) override { orig_item->make_send_field(thd, field); } bool eq(const Item *item, bool binary_cmp) const override { const Item *it= item->real_item(); return orig_item->eq(it, binary_cmp); } void fix_after_pullout(st_select_lex *new_parent, Item **refptr, bool merge) override { orig_item->fix_after_pullout(new_parent, &orig_item, merge); } int save_in_field(Field *to, bool no_conversions) override; const Type_handler *type_handler() const override { return orig_item->type_handler(); } table_map used_tables() const override { return orig_item->used_tables(); } void update_used_tables() override { orig_item->update_used_tables(); } bool const_item() const override { return orig_item->const_item(); } table_map not_null_tables() const override { return orig_item->not_null_tables(); } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { return orig_item->walk(processor, walk_subquery, arg) || (this->*processor)(arg); } bool enumerate_field_refs_processor(void *arg) override { return orig_item->enumerate_field_refs_processor(arg); } Item_field *field_for_view_update() override { return orig_item->field_for_view_update(); } /* Row emulation: forwarding of ROW-related calls to orig_item */ uint cols() const override { return result_type() == ROW_RESULT ? orig_item->cols() : 1; } Item* element_index(uint i) override { return result_type() == ROW_RESULT ? orig_item->element_index(i) : this; } Item** addr(uint i) override { return result_type() == ROW_RESULT ? orig_item->addr(i) : 0; } bool check_cols(uint c) override { return (result_type() == ROW_RESULT ? orig_item->check_cols(c) : Item::check_cols(c)); } bool null_inside() override { return result_type() == ROW_RESULT ? orig_item->null_inside() : 0; } void bring_value() override { if (result_type() == ROW_RESULT) orig_item->bring_value(); } bool is_expensive() override { return orig_item->is_expensive(); } bool is_expensive_processor(void *arg) override { return orig_item->is_expensive_processor(arg); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("cache", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *) const override { return nullptr; } }; /* Class for view fields, the same as Item_direct_ref, but call fix_fields of reference if it is not called yet */ class Item_direct_view_ref :public Item_direct_ref { Item_equal *item_equal; TABLE_LIST *view; TABLE *null_ref_table; #define NO_NULL_TABLE (reinterpret_cast(0x1)) void set_null_ref_table() { if (!view->is_inner_table_of_outer_join() || !(null_ref_table= view->get_real_join_table())) null_ref_table= NO_NULL_TABLE; if (null_ref_table && null_ref_table != NO_NULL_TABLE) set_maybe_null(); } bool check_null_ref() { DBUG_ASSERT(null_ref_table); if (null_ref_table != NO_NULL_TABLE && null_ref_table->null_row) { null_value= 1; return TRUE; } return FALSE; } public: Item_direct_view_ref(THD *thd, Name_resolution_context *context_arg, Item **item, LEX_CSTRING &table_name_arg, LEX_CSTRING &field_name_arg, TABLE_LIST *view_arg): Item_direct_ref(thd, context_arg, item, table_name_arg, field_name_arg), item_equal(0), view(view_arg), null_ref_table(NULL) { if (fixed()) set_null_ref_table(); } bool fix_fields(THD *, Item **) override; bool eq(const Item *item, bool binary_cmp) const override; Item *get_tmp_table_item(THD *thd) override { if (const_item()) return copy_or_same(thd); Item *item= Item_ref::get_tmp_table_item(thd); item->name= name; return item; } Ref_Type ref_type() override { return VIEW_REF; } Item_equal *get_item_equal() override { return item_equal; } void set_item_equal(Item_equal *item_eq) override { item_equal= item_eq; } Item_equal *find_item_equal(COND_EQUAL *cond_equal) override; Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override; Item *replace_equal_field(THD *thd, uchar *arg) override; table_map used_tables() const override; void update_used_tables() override; table_map not_null_tables() const override; bool const_item() const override { return (*ref)->const_item() && (null_ref_table == NO_NULL_TABLE); } TABLE *get_null_ref_table() const { return null_ref_table; } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { return (*ref)->walk(processor, walk_subquery, arg) || (this->*processor)(arg); } bool view_used_tables_processor(void *arg) override { TABLE_LIST *view_arg= (TABLE_LIST *) arg; if (view_arg == view) view_arg->view_used_tables|= (*ref)->used_tables(); return 0; } bool excl_dep_on_table(table_map tab_map) override; bool excl_dep_on_grouping_fields(st_select_lex *sel) override; bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override; Item *derived_field_transformer_for_having(THD *thd, uchar *arg) override; Item *derived_field_transformer_for_where(THD *thd, uchar *arg) override; Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) override; Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) override; Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) override; void save_val(Field *to) override { if (check_null_ref()) to->set_null(); else Item_direct_ref::save_val(to); } double val_real() override { if (check_null_ref()) return 0; else return Item_direct_ref::val_real(); } longlong val_int() override { if (check_null_ref()) return 0; else return Item_direct_ref::val_int(); } String *val_str(String* tmp) override { if (check_null_ref()) return NULL; else return Item_direct_ref::val_str(tmp); } bool val_native(THD *thd, Native *to) override { if (check_null_ref()) return true; return Item_direct_ref::val_native(thd, to); } my_decimal *val_decimal(my_decimal *tmp) override { if (check_null_ref()) return NULL; else return Item_direct_ref::val_decimal(tmp); } bool val_bool() override { if (check_null_ref()) return 0; else return Item_direct_ref::val_bool(); } bool is_null() override { if (check_null_ref()) return 1; else return Item_direct_ref::is_null(); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { if (check_null_ref()) { bzero((char*) ltime,sizeof(*ltime)); return 1; } return Item_direct_ref::get_date(thd, ltime, fuzzydate); } longlong val_time_packed(THD *thd) override { if (check_null_ref()) return 0; else return Item_direct_ref::val_time_packed(thd); } longlong val_datetime_packed(THD *thd) override { if (check_null_ref()) return 0; else return Item_direct_ref::val_datetime_packed(thd); } bool send(Protocol *protocol, st_value *buffer) override; void save_org_in_field(Field *field, fast_field_copier) override { if (check_null_ref()) field->set_null(); else Item_direct_ref::save_val(field); } void save_in_result_field(bool no_conversions) override { if (check_null_ref()) result_field->set_null(); else Item_direct_ref::save_in_result_field(no_conversions); } int save_in_field(Field *field, bool no_conversions) override { if (check_null_ref()) return set_field_to_null_with_conversions(field, no_conversions); return Item_direct_ref::save_in_field(field, no_conversions); } void cleanup() override { null_ref_table= NULL; item_equal= NULL; Item_direct_ref::cleanup(); } /* TODO move these val_*_result function to Item_direct_ref (maybe) */ double val_result() override; longlong val_int_result() override; String *str_result(String* tmp) override; my_decimal *val_decimal_result(my_decimal *val) override; bool val_bool_result() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *field_transformer_for_having_pushdown(THD *, uchar *) override { return this; } }; /* Class for outer fields. An object of this class is created when the select where the outer field was resolved is a grouping one. After it has been fixed the ref field will point to either an Item_ref or an Item_direct_ref object which will be used to access the field. See also comments for the fix_inner_refs() and the Item_field::fix_outer_field() functions. */ class Item_sum; class Item_outer_ref :public Item_direct_ref { public: Item *outer_ref; /* The aggregate function under which this outer ref is used, if any. */ Item_sum *in_sum_func; /* TRUE <=> that the outer_ref is already present in the select list of the outer select. */ bool found_in_select_list; bool found_in_group_by; Item_outer_ref(THD *thd, Name_resolution_context *context_arg, Item_field *outer_field_arg): Item_direct_ref(thd, context_arg, 0, outer_field_arg->table_name, outer_field_arg->field_name), outer_ref(outer_field_arg), in_sum_func(0), found_in_select_list(0), found_in_group_by(0) { ref= &outer_ref; set_properties(); /* reset flag set in set_properties() */ base_flags&= ~item_base_t::FIXED; } Item_outer_ref(THD *thd, Name_resolution_context *context_arg, Item **item, const LEX_CSTRING &table_name_arg, LEX_CSTRING &field_name_arg, bool alias_name_used_arg): Item_direct_ref(thd, context_arg, item, table_name_arg, field_name_arg, alias_name_used_arg), outer_ref(0), in_sum_func(0), found_in_select_list(1), found_in_group_by(0) {} void save_in_result_field(bool no_conversions) override { outer_ref->save_org_in_field(result_field, NULL); } bool fix_fields(THD *, Item **) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; table_map used_tables() const override { return (*ref)->const_item() ? 0 : OUTER_REF_TABLE_BIT; } table_map not_null_tables() const override { return 0; } Ref_Type ref_type() override { return OUTER_REF; } bool check_inner_refs_processor(void * arg) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_in_subselect; /* An object of this class: - Converts val_XXX() calls to ref->val_XXX_result() calls, like Item_ref. - Sets owner->was_null=TRUE if it has returned a NULL value from any val_XXX() function. This allows to inject an Item_ref_null_helper object into subquery and then check if the subquery has produced a row with NULL value. */ class Item_ref_null_helper: public Item_ref { protected: Item_in_subselect* owner; public: Item_ref_null_helper(THD *thd, Name_resolution_context *context_arg, Item_in_subselect* master, Item **item, const LEX_CSTRING &table_name_arg, const LEX_CSTRING &field_name_arg): Item_ref(thd, context_arg, item, table_name_arg, field_name_arg), owner(master) {} void save_val(Field *to) override; double val_real() override; longlong val_int() override; String* val_str(String* s) override; my_decimal *val_decimal(my_decimal *) override; bool val_bool() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *to) override; void print(String *str, enum_query_type query_type) override; table_map used_tables() const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* The following class is used to optimize comparing of date and bigint columns We need to save the original item ('ref') to be able to call ref->save_in_field(). This is used to create index search keys. An instance of Item_int_with_ref may have signed or unsigned integer value. */ class Item_int_with_ref :public Item_int { Item *ref; public: Item_int_with_ref(THD *thd, longlong i, Item *ref_arg, bool unsigned_arg): Item_int(thd, i), ref(ref_arg) { unsigned_flag= unsigned_arg; } int save_in_field(Field *field, bool no_conversions) override { return ref->save_in_field(field, no_conversions); } Item *clone_item(THD *thd) const override; Item *real_item() override { return ref; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; #ifdef MYSQL_SERVER #include "item_sum.h" #include "item_func.h" #include "item_row.h" #include "item_cmpfunc.h" #include "item_strfunc.h" #include "item_timefunc.h" #include "item_subselect.h" #include "item_xmlfunc.h" #include "item_jsonfunc.h" #include "item_create.h" #include "item_vers.h" #endif /** Base class to implement typed value caching Item classes Item_copy_ classes are very similar to the corresponding Item_ classes (e.g. Item_copy_string is similar to Item_string) but they add the following additional functionality to Item_ : 1. Nullability 2. Possibility to store the value not only on instantiation time, but also later. Item_copy_ classes are a functionality subset of Item_cache_ classes, as e.g. they don't support comparisons with the original Item as Item_cache_ classes do. Item_copy_ classes are used in GROUP BY calculation. TODO: Item_copy should be made an abstract interface and Item_copy_ classes should inherit both the respective Item_ class and the interface. Ideally we should drop Item_copy_ classes altogether and merge their functionality to Item_cache_ (and these should be made to inherit from Item_). */ class Item_copy :public Item, public Type_handler_hybrid_field_type { protected: /** Type_handler_hybrid_field_type is used to store the type of the resulting field that would be used to store the data in the cache. This is to avoid calls to the original item. */ /** The original item that is copied */ Item *item; /** Constructor of the Item_copy class stores metadata information about the original class as well as a pointer to it. */ Item_copy(THD *thd, Item *org): Item(thd) { DBUG_ASSERT(org->fixed()); item= org; null_value= item->maybe_null(); copy_flags(item, item_base_t::MAYBE_NULL); Type_std_attributes::set(item); name= item->name; set_handler(item->type_handler()); #ifndef DBUG_OFF copied_in= 0; #endif } #ifndef DBUG_OFF bool copied_in; #endif public: /** Update the cache with the value of the original item This is the method that updates the cached value. It must be explicitly called by the user of this class to store the value of the original item in the cache. */ virtual void copy() = 0; Item *get_item() { return item; } /** All of the subclasses should have the same type tag */ Type type() const override { return COPY_STR_ITEM; } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { DBUG_ASSERT(0); return NULL; } void make_send_field(THD *thd, Send_field *field) override { item->make_send_field(thd, field); } table_map used_tables() const override { return (table_map) 1L; } bool const_item() const override { return false; } bool is_null() override { return null_value; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("copy", arg, VCOL_IMPOSSIBLE); } /* Override the methods below as pure virtual to make sure all the sub-classes implement them. */ String *val_str(String*) override = 0; my_decimal *val_decimal(my_decimal *) override = 0; double val_real() override = 0; longlong val_int() override = 0; int save_in_field(Field *field, bool no_conversions) override = 0; bool walk(Item_processor processor, bool walk_subquery, void *args) override { return (item->walk(processor, walk_subquery, args)) || (this->*processor)(args); } }; /** Implementation of a string cache. Uses Item::str_value for storage */ class Item_copy_string : public Item_copy { public: Item_copy_string(THD *thd, Item *item_arg): Item_copy(thd, item_arg) {} String *val_str(String*) override; my_decimal *val_decimal(my_decimal *) override; double val_real() override; longlong val_int() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { DBUG_ASSERT(copied_in); return get_date_from_string(thd, ltime, fuzzydate); } void copy() override; int save_in_field(Field *field, bool no_conversions) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** We need a separate class Item_copy_timestamp because TIMESTAMP->string->TIMESTAMP conversion is not round trip safe near the DST change, e.g. '2010-10-31 02:25:26' can mean: - my_time_t(1288477526) - summer time in Moscow - my_time_t(1288481126) - winter time in Moscow, one hour later */ class Item_copy_timestamp: public Item_copy { Timestamp_or_zero_datetime m_value; bool sane() const { return !null_value || m_value.is_zero_datetime(); } public: Item_copy_timestamp(THD *thd, Item *arg): Item_copy(thd, arg) { } const Type_handler *type_handler() const override { return &type_handler_timestamp2; } void copy() override { Timestamp_or_zero_datetime_native_null tmp(current_thd, item, false); null_value= tmp.is_null(); m_value= tmp.is_null() ? Timestamp_or_zero_datetime() : Timestamp_or_zero_datetime(tmp); #ifndef DBUG_OFF copied_in=1; #endif } int save_in_field(Field *field, bool) override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); if (null_value) return set_field_to_null(field); Timestamp_or_zero_datetime_native native(m_value, decimals); return native.save_in_field(field, decimals); } longlong val_int() override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); return null_value ? 0 : m_value.to_datetime(current_thd).to_longlong(); } double val_real() override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); return null_value ? 0e0 : m_value.to_datetime(current_thd).to_double(); } String *val_str(String *to) override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); return null_value ? NULL : m_value.to_datetime(current_thd).to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); return null_value ? NULL : m_value.to_datetime(current_thd).to_decimal(to); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); bool res= m_value.to_TIME(thd, ltime, fuzzydate); DBUG_ASSERT(!res); return null_value || res; } bool val_native(THD *thd, Native *to) override { DBUG_ASSERT(copied_in); DBUG_ASSERT(sane()); return null_value || m_value.to_native(to, decimals); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /* Cached_item_XXX objects are not exactly caches. They do the following: Each Cached_item_XXX object has - its source item - saved value of the source item - cmp() method that compares the saved value with the current value of the source item, and if they were not equal saves item's value into the saved value. TODO: add here: - a way to save the new value w/o comparison - a way to do less/equal/greater comparison */ class Cached_item :public Sql_alloc { public: bool null_value; Cached_item() :null_value(0) {} /* Compare the cached value with the source value. If not equal, copy the source value to the cache. @return true - Not equal false - Equal */ virtual bool cmp(void)=0; /* Compare the cached value with the source value, without copying */ virtual int cmp_read_only()=0; virtual ~Cached_item(); /*line -e1509 */ }; class Cached_item_item : public Cached_item { protected: Item *item; Cached_item_item(Item *arg) : item(arg) {} public: void fetch_value_from(Item *new_item) { Item *save= item; item= new_item; cmp(); item= save; } }; class Cached_item_str :public Cached_item_item { uint32 value_max_length; String value,tmp_value; public: Cached_item_str(THD *thd, Item *arg); bool cmp() override; int cmp_read_only() override; ~Cached_item_str(); // Deallocate String:s }; class Cached_item_real :public Cached_item_item { double value; public: Cached_item_real(Item *item_par) :Cached_item_item(item_par),value(0.0) {} bool cmp() override; int cmp_read_only() override; }; class Cached_item_int :public Cached_item_item { longlong value; public: Cached_item_int(Item *item_par) :Cached_item_item(item_par),value(0) {} bool cmp() override; int cmp_read_only() override; }; class Cached_item_decimal :public Cached_item_item { my_decimal value; public: Cached_item_decimal(Item *item_par); bool cmp() override; int cmp_read_only() override; }; class Cached_item_field :public Cached_item { uchar *buff; Field *field; uint length; public: Cached_item_field(THD *thd, Field *arg_field): field(arg_field) { field= arg_field; /* TODO: take the memory allocation below out of the constructor. */ buff= (uchar*) thd_calloc(thd, length= field->pack_length()); } bool cmp() override; int cmp_read_only() override; }; class Item_default_value : public Item_field { bool vcol_assignment_ok:1; bool m_associated:1; bool m_share_field:1; void calculate(); public: Item *arg= nullptr; Item_default_value(THD *thd, Name_resolution_context *context_arg, Item *a, bool vcol_assignment_arg) : Item_field(thd, context_arg), vcol_assignment_ok(vcol_assignment_arg), arg(a) { m_associated= false; m_share_field= false; } Type type() const override { return DEFAULT_VALUE_ITEM; } bool eq(const Item *item, bool binary_cmp) const override; bool fix_fields(THD *, Item **) override; void cleanup() override; void print(String *str, enum_query_type query_type) override; String *val_str(String *str) override; double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *decimal_value) override; bool get_date(THD *thd, MYSQL_TIME *ltime,date_mode_t fuzzydate) override; bool val_native(THD *thd, Native *to) override; bool val_native_result(THD *thd, Native *to) override; longlong val_datetime_packed(THD *thd) override { return Item::val_datetime_packed(thd); } longlong val_time_packed(THD *thd) override { return Item::val_time_packed(thd); } /* Result variants */ double val_result() override; longlong val_int_result() override; String *str_result(String* tmp) override; my_decimal *val_decimal_result(my_decimal *val) override; bool val_bool_result() override; bool is_null_result() override; bool get_date_result(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool send(Protocol *protocol, st_value *buffer) override; int save_in_field(Field *field_arg, bool no_conversions) override; void save_in_result_field(bool no_conversions) override; bool save_in_param(THD *, Item_param *param) override { // It should not be possible to have "EXECUTE .. USING DEFAULT(a)" DBUG_ASSERT(0); param->set_default(true); return false; } table_map used_tables() const override; void update_used_tables() override { if (field && field->default_value) field->default_value->expr->update_used_tables(); } bool vcol_assignment_allowed_value() const override { return vcol_assignment_ok; } Item *get_tmp_table_item(THD *) override { return this; } Item_field *field_for_view_update() override { return nullptr; } bool update_vcol_processor(void *) override { return false; } bool check_field_expression_processor(void *arg) override; bool check_func_default_processor(void *) override { return true; } bool update_func_default_processor(void *arg) override; bool register_field_in_read_map(void *arg) override; bool walk(Item_processor processor, bool walk_subquery, void *args) override { return (arg && arg->walk(processor, walk_subquery, args)) || (this->*processor)(args); } Item *transform(THD *thd, Item_transformer transformer, uchar *args) override; Item *derived_field_transformer_for_having(THD *thd, uchar *arg) override { return NULL; } Item *derived_field_transformer_for_where(THD *thd, uchar *arg) override { return NULL; } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override; /** See comments on @see Item::associate_with_target_field for method description */ bool associate_with_target_field(THD *thd, Item_field *field) override; Item *do_get_copy(THD *thd) const override { Item_default_value *new_item= (Item_default_value *) get_item_copy(thd, this); // This is a copy so do not manage the field and should not delete it new_item->m_share_field= 1; return new_item; } Item* do_build_clone(THD *thd) const override { return get_copy(thd); } private: bool tie_field(THD *thd); }; class Item_contextually_typed_value_specification: public Item { public: Item_contextually_typed_value_specification(THD *thd) :Item(thd) { } Type type() const override { return CONTEXTUALLY_TYPED_VALUE_ITEM; } bool vcol_assignment_allowed_value() const override { return true; } bool eq(const Item *item, bool binary_cmp) const override { return false; } bool is_evaluable_expression() const override { return false; } Field *create_tmp_field_ex(MEM_ROOT *, TABLE *, Tmp_field_src *, const Tmp_field_param *) override { DBUG_ASSERT(0); return NULL; } String *val_str(String *str) override { DBUG_ASSERT(0); // never should be called null_value= true; return 0; } double val_real() override { DBUG_ASSERT(0); // never should be called null_value= true; return 0.0; } longlong val_int() override { DBUG_ASSERT(0); // never should be called null_value= true; return 0; } my_decimal *val_decimal(my_decimal *) override { DBUG_ASSERT(0); // never should be called null_value= true; return 0; } bool get_date(THD *, MYSQL_TIME *, date_mode_t) override { DBUG_ASSERT(0); // never should be called return (null_value= true); } bool send(Protocol *, st_value *) override { DBUG_ASSERT(0); return true; } const Type_handler *type_handler() const override { DBUG_ASSERT(0); return &type_handler_null; } }; /* ::= DEFAULT */ class Item_default_specification: public Item_contextually_typed_value_specification { public: Item_default_specification(THD *thd) :Item_contextually_typed_value_specification(thd) { } void print(String *str, enum_query_type) override { str->append(STRING_WITH_LEN("default")); } int save_in_field(Field *field_arg, bool) override { return field_arg->save_in_field_default_value(false); } bool save_in_param(THD *, Item_param *param) override { param->set_default(true); return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /** This class is used as bulk parameter INGNORE representation. It just do nothing when assigned to a field This is a non-standard MariaDB extension. */ class Item_ignore_specification: public Item_contextually_typed_value_specification { public: Item_ignore_specification(THD *thd) :Item_contextually_typed_value_specification(thd) { } void print(String *str, enum_query_type) override { str->append(STRING_WITH_LEN("ignore")); } int save_in_field(Field *field_arg, bool) override { return field_arg->save_in_field_ignore_value(false); } bool save_in_param(THD *, Item_param *param) override { param->set_ignore(true); return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /* Item_insert_value -- an implementation of VALUES() function. You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... UPDATE statement. In other words, VALUES(col_name) in the UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred. In all other places this function returns NULL. */ class Item_insert_value : public Item_field { public: Item *arg; Item_insert_value(THD *thd, Name_resolution_context *context_arg, Item *a) :Item_field(thd, context_arg), arg(a) {} bool eq(const Item *item, bool binary_cmp) const override; bool fix_fields(THD *, Item **) override; void print(String *str, enum_query_type query_type) override; int save_in_field(Field *field_arg, bool no_conversions) override { return Item_field::save_in_field(field_arg, no_conversions); } Type type() const override { return INSERT_VALUE_ITEM; } /* We use RAND_TABLE_BIT to prevent Item_insert_value from being treated as a constant and precalculated before execution */ table_map used_tables() const override { return RAND_TABLE_BIT; } Item_field *field_for_view_update() override { return nullptr; } bool walk(Item_processor processor, bool walk_subquery, void *args) override { return arg->walk(processor, walk_subquery, args) || (this->*processor)(args); } bool check_partition_func_processor(void *) override { return true; } bool update_vcol_processor(void *) override { return false; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function("value()", arg, VCOL_IMPOSSIBLE); } }; class Table_triggers_list; /* Represents NEW/OLD version of field of row which is changed/read in trigger. Note: For this item main part of actual binding to Field object happens not during fix_fields() call (like for Item_field) but right after parsing of trigger definition, when table is opened, with special setup_field() call. On fix_fields() stage we simply choose one of two Field instances representing either OLD or NEW version of this field. */ class Item_trigger_field : public Item_field, private Settable_routine_parameter { private: GRANT_INFO *table_grants; public: /* Next in list of all Item_trigger_field's in trigger */ Item_trigger_field *next_trg_field; /* Pointer to Table_trigger_list object for table of this trigger */ Table_triggers_list *triggers; /* Is this item represents row from NEW or OLD row ? */ enum __attribute__((packed)) row_version_type {OLD_ROW, NEW_ROW}; row_version_type row_version; /* Index of the field in the TABLE::field array */ field_index_t field_idx; private: /* Trigger field is read-only unless it belongs to the NEW row in a BEFORE INSERT of BEFORE UPDATE trigger. */ bool read_only; /* 'want_privilege' holds privileges required to perform operation on this trigger field (SELECT_ACL if we are going to read it and UPDATE_ACL if we are going to update it). It is initialized at parse time but can be updated later if this trigger field is used as OUT or INOUT parameter of stored routine (in this case set_required_privilege() is called to appropriately update want_privilege and cleanup() is responsible for restoring of original want_privilege once parameter's value is updated). */ privilege_t original_privilege; privilege_t want_privilege; public: Item_trigger_field(THD *thd, Name_resolution_context *context_arg, row_version_type row_ver_arg, const LEX_CSTRING &field_name_arg, privilege_t priv, const bool ro) :Item_field(thd, context_arg, field_name_arg), table_grants(NULL), next_trg_field(NULL), triggers(NULL), row_version(row_ver_arg), field_idx(NO_CACHED_FIELD_INDEX), read_only (ro), original_privilege(priv), want_privilege(priv) { } void setup_field(THD *thd, TABLE *table, GRANT_INFO *table_grant_info); Type type() const override { return TRIGGER_FIELD_ITEM; } bool eq(const Item *item, bool binary_cmp) const override; bool fix_fields(THD *, Item **) override; void print(String *str, enum_query_type query_type) override; table_map used_tables() const override { return (table_map)0L; } Field *get_tmp_table_field() override { return nullptr; } Item *copy_or_same(THD *) override { return this; } Item *get_tmp_table_item(THD *thd) override { return copy_or_same(thd); } void cleanup() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } private: void set_required_privilege(bool rw) override; bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override; public: Settable_routine_parameter *get_settable_routine_parameter() override { return read_only ? nullptr : this; } bool set_value(THD *thd, Item **it) { return set_value(thd, NULL, it); } public: bool unknown_splocal_processor(void *) override { return false; } bool check_vcol_func_processor(void *arg) override; }; /** @todo Implement the is_null() method for this class. Currently calling is_null() on any Item_cache object resolves to Item::is_null(), which returns FALSE for any value. */ class Item_cache: public Item_fixed_hybrid, public Type_handler_hybrid_field_type { protected: Item *example; /** Field that this object will get value from. This is used by index-based subquery engines to detect and remove the equality injected by IN->EXISTS transformation. */ Field *cached_field; /* TRUE <=> cache holds value of the last stored item (i.e actual value). store() stores item to be cached and sets this flag to FALSE. On the first call of val_xxx function if this flag is set to FALSE the cache_value() will be called to actually cache value of saved item. cache_value() will set this flag to TRUE. */ bool value_cached; table_map used_table_map; public: /* This is set if at least one of the values of a sub query is NULL Item_cache_row returns this with null_inside(). For not row items, it's set to the value of null_value It is set after cache_value() is called. */ bool null_value_inside; Item_cache(THD *thd): Item_fixed_hybrid(thd), Type_handler_hybrid_field_type(&type_handler_string), example(0), cached_field(0), value_cached(0), used_table_map(0) { set_maybe_null(); null_value= 1; null_value_inside= true; quick_fix_field(); } protected: Item_cache(THD *thd, const Type_handler *handler): Item_fixed_hybrid(thd), Type_handler_hybrid_field_type(handler), example(0), cached_field(0), value_cached(0), used_table_map(0) { set_maybe_null(); null_value= 1; null_value_inside= true; quick_fix_field(); } public: virtual bool allocate(THD *thd, uint i) { return 0; } virtual bool setup(THD *thd, Item *item) { example= item; Type_std_attributes::set(item); base_flags|= item->base_flags & item_base_t::IS_COND; if (item->type() == FIELD_ITEM) cached_field= ((Item_field *)item)->field; return 0; }; void set_used_tables(table_map map) { used_table_map= map; } table_map used_tables() const override { return used_table_map; } Type type() const override { return CACHE_ITEM; } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { return create_tmp_field_ex_simple(root, table, src, param); } virtual void keep_array() {} #ifndef DBUG_OFF bool is_array_kept() { return TRUE; } #endif void print(String *str, enum_query_type query_type) override; bool eq_def(const Field *field) { return cached_field ? cached_field->eq_def (field) : FALSE; } bool eq(const Item *item, bool binary_cmp) const override { return this == item; } bool check_vcol_func_processor(void *arg) override { if (example) { Item::vcol_func_processor_result *res= (Item::vcol_func_processor_result*) arg; example->check_vcol_func_processor(arg); /* Item_cache of a non-deterministic function requires re-fixing even if the function itself doesn't (e.g. CURRENT_TIMESTAMP) */ if (res->errors & VCOL_NOT_STRICTLY_DETERMINISTIC) res->errors|= VCOL_SESSION_FUNC; return false; } return mark_unsupported_function("cache", arg, VCOL_IMPOSSIBLE); } bool fix_fields(THD *thd, Item **ref) override { quick_fix_field(); if (example && !example->fixed()) return example->fix_fields(thd, ref); return 0; } void cleanup() override { clear(); Item_fixed_hybrid::cleanup(); } /** Check if saved item has a non-NULL value. Will cache value of saved item if not already done. @return TRUE if cached value is non-NULL. */ bool has_value() { return (value_cached || cache_value()) && !null_value; } virtual void store(Item *item); virtual Item *get_item() { return example; } virtual bool cache_value()= 0; bool basic_const_item() const override { return example && example->basic_const_item(); } virtual void clear() { null_value= TRUE; value_cached= FALSE; } bool is_null() override { return !has_value(); } bool is_expensive() override { if (value_cached) return false; return example->is_expensive(); } bool is_expensive_processor(void *arg) override { DBUG_ASSERT(example); if (value_cached) return false; return example->is_expensive_processor(arg); } virtual void set_null(); bool walk(Item_processor processor, bool walk_subquery, void *arg) override { if (arg == STOP_PTR) return FALSE; if (example && example->walk(processor, walk_subquery, arg)) return TRUE; return (this->*processor)(arg); } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override; void split_sum_func2_example(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) { example->split_sum_func2(thd, ref_pointer_array, fields, &example, flags); } Item *get_example() const { return example; } virtual Item *convert_to_basic_const_item(THD *thd) { return 0; }; Item *derived_field_transformer_for_having(THD *thd, uchar *) override { return convert_to_basic_const_item(thd); } Item *derived_field_transformer_for_where(THD *thd, uchar *) override { return convert_to_basic_const_item(thd); } Item *grouping_field_transformer_for_where(THD *thd, uchar *) override { return convert_to_basic_const_item(thd); } Item *in_subq_field_transformer_for_where(THD *thd, uchar *) override { return convert_to_basic_const_item(thd); } Item *in_subq_field_transformer_for_having(THD *thd, uchar *) override { return convert_to_basic_const_item(thd); } }; class Item_cache_int: public Item_cache { protected: longlong value; public: Item_cache_int(THD *thd, const Type_handler *handler): Item_cache(thd, handler), value(0) {} double val_real() override; longlong val_int() override; String* val_str(String *str) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_int(thd, ltime, fuzzydate); } bool cache_value() override; int save_in_field(Field *field, bool no_conversions) override; Item *convert_to_basic_const_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_bool: public Item_cache_int { public: Item_cache_bool(THD *thd) :Item_cache_int(thd, &type_handler_bool) { } bool cache_value() override; bool val_bool() override { return !has_value() ? false : (bool) value; } longlong val_int() override { DBUG_ASSERT(!is_cond()); return Item_cache_bool::val_bool(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_cache_year: public Item_cache_int { public: Item_cache_year(THD *thd, const Type_handler *handler) :Item_cache_int(thd, handler) { } bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) override { return type_handler_year.Item_get_date_with_warn(thd, this, to, mode); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_temporal: public Item_cache_int { protected: Item_cache_temporal(THD *thd, const Type_handler *handler); public: bool cache_value() override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; int save_in_field(Field *field, bool no_conversions) override; bool setup(THD *thd, Item *item) override { if (Item_cache_int::setup(thd, item)) return true; set_if_smaller(decimals, TIME_SECOND_PART_DIGITS); return false; } void store_packed(longlong val_arg, Item *example); /* Having a clone_item method tells optimizer that this object is a constant and need not be optimized further. Important when storing packed datetime values. */ Item *clone_item(THD *thd) const override; Item *convert_to_basic_const_item(THD *thd) override; virtual Item *make_literal(THD *) =0; }; class Item_cache_time: public Item_cache_temporal { public: Item_cache_time(THD *thd) :Item_cache_temporal(thd, &type_handler_time2) { } bool cache_value() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *make_literal(THD *) override; longlong val_datetime_packed(THD *thd) override { Datetime::Options_cmp opt(thd); return has_value() ? Datetime(thd, this, opt).to_packed() : 0; } longlong val_time_packed(THD *) override { return has_value() ? value : 0; } longlong val_int() override { return has_value() ? Time(this).to_longlong() : 0; } double val_real() override { return has_value() ? Time(this).to_double() : 0; } String *val_str(String *to) override { return has_value() ? Time(this).to_string(to, decimals) : NULL; } my_decimal *val_decimal(my_decimal *to) override { return has_value() ? Time(this).to_decimal(to) : NULL; } bool val_native(THD *thd, Native *to) override { return has_value() ? Time(thd, this).to_native(to, decimals) : true; } }; class Item_cache_datetime: public Item_cache_temporal { public: Item_cache_datetime(THD *thd) :Item_cache_temporal(thd, &type_handler_datetime2) { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *make_literal(THD *) override; longlong val_datetime_packed(THD *) override { return has_value() ? value : 0; } longlong val_time_packed(THD *thd) override { return Time(thd, this, Time::Options_cmp(thd)).to_packed(); } longlong val_int() override { return has_value() ? Datetime(this).to_longlong() : 0; } double val_real() override { return has_value() ? Datetime(this).to_double() : 0; } String *val_str(String *to) override { return has_value() ? Datetime(this).to_string(to, decimals) : NULL; } my_decimal *val_decimal(my_decimal *to) override { return has_value() ? Datetime(this).to_decimal(to) : NULL; } }; class Item_cache_date: public Item_cache_temporal { public: Item_cache_date(THD *thd) :Item_cache_temporal(thd, &type_handler_newdate) { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *make_literal(THD *) override; longlong val_datetime_packed(THD *) override { return has_value() ? value : 0; } longlong val_time_packed(THD *thd) override { return Time(thd, this, Time::Options_cmp(thd)).to_packed(); } longlong val_int() override { return has_value() ? Date(this).to_longlong() : 0; } double val_real() override { return has_value() ? Date(this).to_double() : 0; } String *val_str(String *to) override { return has_value() ? Date(this).to_string(to) : NULL; } my_decimal *val_decimal(my_decimal *to) override { return has_value() ? Date(this).to_decimal(to) : NULL; } }; class Item_cache_timestamp: public Item_cache { Timestamp_or_zero_datetime_native m_native; Datetime to_datetime(THD *thd); public: Item_cache_timestamp(THD *thd) :Item_cache(thd, &type_handler_timestamp2) { } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } bool cache_value() override; String* val_str(String *to) override { return to_datetime(current_thd).to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { return to_datetime(current_thd).to_decimal(to); } longlong val_int() override { return to_datetime(current_thd).to_longlong(); } double val_real() override { return to_datetime(current_thd).to_double(); } longlong val_datetime_packed(THD *thd) override { return to_datetime(thd).to_packed(); } longlong val_time_packed(THD *) override { DBUG_ASSERT(0); return 0; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; int save_in_field(Field *field, bool no_conversions) override; bool val_native(THD *thd, Native *to) override; }; class Item_cache_real: public Item_cache { protected: double value; public: Item_cache_real(THD *thd, const Type_handler *h) :Item_cache(thd, h), value(0) {} double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_real(thd, ltime, fuzzydate); } bool cache_value() override; Item *convert_to_basic_const_item(THD *thd) override; }; class Item_cache_double: public Item_cache_real { public: Item_cache_double(THD *thd) :Item_cache_real(thd, &type_handler_double) { } String *val_str(String *str) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_float: public Item_cache_real { public: Item_cache_float(THD *thd) :Item_cache_real(thd, &type_handler_float) { } String *val_str(String *str) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_decimal: public Item_cache { protected: my_decimal decimal_value; public: Item_cache_decimal(THD *thd): Item_cache(thd, &type_handler_newdecimal) {} double val_real() override; longlong val_int() override; String* val_str(String *str) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *to, date_mode_t mode) override { return decimal_to_datetime_with_warn(thd, VDec(this).ptr(), to, mode, NULL, NULL); } bool cache_value() override; Item *convert_to_basic_const_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_str: public Item_cache { char buffer[STRING_BUFFER_USUAL_SIZE]; String *value, value_buff; bool is_varbinary; public: Item_cache_str(THD *thd, const Item *item): Item_cache(thd, item->type_handler()), value(0), is_varbinary(item->type() == FIELD_ITEM && Item_cache_str::field_type() == MYSQL_TYPE_VARCHAR && !((const Item_field *) item)->field->has_charset()) { collation.set(const_cast(item->collation)); } double val_real() override; longlong val_int() override; String* val_str(String *) override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_string(thd, ltime, fuzzydate); } CHARSET_INFO *charset() const { return value->charset(); }; int save_in_field(Field *field, bool no_conversions) override; bool cache_value() override; Item *convert_to_basic_const_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_str_for_nullif: public Item_cache_str { public: Item_cache_str_for_nullif(THD *thd, const Item *item) :Item_cache_str(thd, item) { } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override { /** Item_cache_str::safe_charset_converter() returns a new Item_cache with Item_func_conv_charset installed on "example". The original Item_cache is not referenced (neither directly nor recursively) from the result of Item_cache_str::safe_charset_converter(). For NULLIF() purposes we need a different behavior: we need a new instance of Item_func_conv_charset, with the original Item_cache referenced in args[0]. See MDEV-9181. */ return Item::safe_charset_converter(thd, tocs); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; class Item_cache_row: public Item_cache { Item_cache **values; uint item_count; bool save_array; public: Item_cache_row(THD *thd): Item_cache(thd, &type_handler_row), values(0), item_count(2), save_array(0) {} /* 'allocate' used only in row transformer, to preallocate space for row cache. */ bool allocate(THD *thd, uint num) override; /* 'setup' is needed only by row => it not called by simple row subselect (only by IN subselect (in subselect optimizer)) */ bool setup(THD *thd, Item *item) override; void store(Item *item) override; void illegal_method_call(const char *); void make_send_field(THD *, Send_field *) override { illegal_method_call("make_send_field"); }; double val_real() override { illegal_method_call("val"); return 0; }; longlong val_int() override { illegal_method_call("val_int"); return 0; }; String *val_str(String *) override { illegal_method_call("val_str"); return nullptr; }; my_decimal *val_decimal(my_decimal *) override { illegal_method_call("val_decimal"); return nullptr; }; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { illegal_method_call("val_decimal"); return true; } uint cols() const override { return item_count; } Item *element_index(uint i) override { return values[i]; } Item **addr(uint i) override { return (Item **) (values + i); } bool check_cols(uint c) override; bool null_inside() override; void bring_value() override; void keep_array() override { save_array= 1; } #ifndef DBUG_OFF bool is_array_kept() { return save_array; } #endif void cleanup() override { DBUG_ENTER("Item_cache_row::cleanup"); Item_cache::cleanup(); if (!save_array) values= 0; DBUG_VOID_RETURN; } bool cache_value() override; void set_null() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { return get_copy(thd); } }; /* Item_type_holder used to store type. name, length of Item for UNIONS & derived tables. Item_type_holder do not need cleanup() because its time of live limited by single SP/PS execution. */ class Item_type_holder: public Item, public Type_handler_hybrid_field_type { protected: const TYPELIB *enum_set_typelib; public: Item_type_holder(THD *thd, Item *item, const Type_handler *handler, const Type_all_attributes *attr, bool maybe_null_arg) :Item(thd), Type_handler_hybrid_field_type(handler), enum_set_typelib(attr->get_typelib()) { name= item->name; Type_std_attributes::set(*attr); set_maybe_null(maybe_null_arg); copy_flags(item, item_base_t::IS_EXPLICIT_NAME | item_base_t::IS_IN_WITH_CYCLE); } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler()-> type_handler_for_item_field(); } const Type_handler *real_type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } Type type() const override { return TYPE_HOLDER; } const TYPELIB *get_typelib() const override { return enum_set_typelib; } /* When handling a query like this: VALUES ('') UNION VALUES( _utf16 0x0020 COLLATE utf16_bin); Item_type_holder can be passed to Type_handler_xxx::Item_hybrid_func_fix_attributes() We don't want the latter to perform character set conversion of a Item_type_holder by calling its val_str(), which calls DBUG_ASSERT(0). Let's override const_item() and is_expensive() to avoid this. Note, Item_hybrid_func_fix_attributes() could probably have a new argument to distinguish what we need: - (a) aggregate data type attributes only - (b) install converters after attribute aggregation So st_select_lex_unit::join_union_type_attributes() could ask it to do (a) only, without (b). */ bool const_item() const override { return false; } bool is_expensive() override { return true; } double val_real() override; longlong val_int() override; my_decimal *val_decimal(my_decimal *) override; String *val_str(String*) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; Field *create_tmp_field_ex(MEM_ROOT *root, TABLE *table, Tmp_field_src *src, const Tmp_field_param *param) override { return Item_type_holder::real_type_handler()-> make_and_init_table_field(root, &name, Record_addr(maybe_null()), *this, table); } Item *do_get_copy(THD *) const override { return nullptr; } Item *do_build_clone(THD *) const override { return nullptr; } }; class st_select_lex; void mark_select_range_as_dependent(THD *thd, st_select_lex *last_select, st_select_lex *current_sel, Field *found_field, Item *found_item, Item_ident *resolved_item, bool suppress_warning_output); extern Cached_item *new_Cached_item(THD *thd, Item *item, bool pass_through_ref); extern Item_result item_cmp_type(Item_result a,Item_result b); extern void resolve_const_item(THD *thd, Item **ref, Item *cmp_item); extern int stored_field_cmp_to_item(THD *thd, Field *field, Item *item); extern const String my_null_string; /** Interface for Item iterator */ class Item_iterator { public: /** Shall set this iterator to the position before the first item @note This method also may perform some other initialization actions like allocation of certain resources. */ virtual void open()= 0; /** Shall return the next Item (or NULL if there is no next item) and move pointer to position after it. */ virtual Item *next()= 0; /** Shall force iterator to free resources (if it holds them) @note One should not use the iterator without open() call after close() */ virtual void close()= 0; virtual ~Item_iterator() = default; }; /** Item iterator over List_iterator_fast for Item references */ class Item_iterator_ref_list: public Item_iterator { List_iterator list; public: Item_iterator_ref_list(List_iterator &arg_list): list(arg_list) {} void open() override { list.rewind(); } Item *next() override { return *(list++); } void close() override {} }; /** Item iterator over List_iterator_fast for Items */ class Item_iterator_list: public Item_iterator { List_iterator list; public: Item_iterator_list(List_iterator &arg_list): list(arg_list) {} void open() override { list.rewind(); } Item *next() override { return (list++); } void close() override {} }; /** Item iterator over Item interface for rows */ class Item_iterator_row: public Item_iterator { Item *base_item; uint current; public: Item_iterator_row(Item *base) : base_item(base), current(0) {} void open() override { current= 0; } Item *next() override { if (current >= base_item->cols()) return NULL; return base_item->element_index(current++); } void close() override {} }; /* fix_escape_item() sets the out "escape" parameter to: - native code in case of an 8bit character set - Unicode code point in case of a multi-byte character set The value meaning a not-initialized ESCAPE character must not be equal to any valid value, so must be outside of these ranges: - -128..+127, not to conflict with a valid 8bit charcter - 0..0x10FFFF, not to conflict with a valid Unicode code point The exact value does not matter. */ #define ESCAPE_NOT_INITIALIZED -1000 /* It's used in ::fix_fields() methods of LIKE and JSON_SEARCH functions to handle the ESCAPE parameter. This parameter is quite non-standard so the specific function. */ bool fix_escape_item(THD *thd, Item *escape_item, String *tmp_str, bool escape_used_in_parsing, CHARSET_INFO *cmp_cs, int *escape); inline bool Virtual_column_info::is_equal(const Virtual_column_info* vcol) const { return type_handler() == vcol->type_handler() && stored_in_db == vcol->is_stored() && expr->eq(vcol->expr, true); } inline void Virtual_column_info::print(String* str) { expr->print_for_table_def(str); } class Item_direct_ref_to_item : public Item_direct_ref { Item *m_item; public: Item_direct_ref_to_item(THD *thd, Item *item); void change_item(THD *thd, Item *); bool fix_fields(THD *thd, Item **it) override; void print(String *str, enum_query_type query_type) override; Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override; Item *get_tmp_table_item(THD *thd) override { return m_item->get_tmp_table_item(thd); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override { return m_item->build_equal_items(thd, inherited, link_item_fields, cond_equal_ref); } LEX_CSTRING full_name_cstring() const override { return m_item->full_name_cstring(); } void make_send_field(THD *thd, Send_field *field) override { m_item->make_send_field(thd, field); } bool eq(const Item *item, bool binary_cmp) const override { const Item *it= item->real_item(); return m_item->eq(it, binary_cmp); } void fix_after_pullout(st_select_lex *new_parent, Item **refptr, bool merge) override { m_item->fix_after_pullout(new_parent, &m_item, merge); } void save_val(Field *to) override { return m_item->save_val(to); } void save_result(Field *to) override { return m_item->save_result(to); } int save_in_field(Field *to, bool no_conversions) override { return m_item->save_in_field(to, no_conversions); } const Type_handler *type_handler() const override { return m_item->type_handler(); } table_map used_tables() const override { return m_item->used_tables(); } void update_used_tables() override { m_item->update_used_tables(); } bool const_item() const override { return m_item->const_item(); } table_map not_null_tables() const override { return m_item->not_null_tables(); } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { return m_item->walk(processor, walk_subquery, arg) || (this->*processor)(arg); } bool enumerate_field_refs_processor(void *arg) override { return m_item->enumerate_field_refs_processor(arg); } Item_field *field_for_view_update() override { return m_item->field_for_view_update(); } /* Row emulation: forwarding of ROW-related calls to orig_item */ uint cols() const override { return m_item->cols(); } Item* element_index(uint i) override { return this; } Item** addr(uint i) override { return &m_item; } bool check_cols(uint c) override { return Item::check_cols(c); } bool null_inside() override { return m_item->null_inside(); } void bring_value() override {} Item_equal *get_item_equal() override { return m_item->get_item_equal(); } void set_item_equal(Item_equal *item_eq) override { m_item->set_item_equal(item_eq); } Item_equal *find_item_equal(COND_EQUAL *cond_equal) override { return m_item->find_item_equal(cond_equal); } Item *propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { return m_item->propagate_equal_fields(thd, ctx, cond); } Item *replace_equal_field(THD *thd, uchar *arg) override { return m_item->replace_equal_field(thd, arg); } bool excl_dep_on_table(table_map tab_map) override { return m_item->excl_dep_on_table(tab_map); } bool excl_dep_on_grouping_fields(st_select_lex *sel) override { return m_item->excl_dep_on_grouping_fields(sel); } bool is_expensive() override { return m_item->is_expensive(); } void set_item(Item *item) { m_item= item; } Item *do_build_clone(THD *thd) const override { Item *clone_item= m_item->build_clone(thd); if (clone_item) { Item_direct_ref_to_item *copy= (Item_direct_ref_to_item *) get_copy(thd); if (!copy) return 0; copy->set_item(clone_item); return copy; } return 0; } void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) override { m_item->split_sum_func(thd, ref_pointer_array, fields, flags); } /* This processor states that this is safe for virtual columns (because this Item transparency) */ bool check_vcol_func_processor(void *arg) override { return FALSE;} }; inline bool TABLE::mark_column_with_deps(Field *field) { bool res; if (!(res= bitmap_fast_test_and_set(read_set, field->field_index))) { if (field->vcol_info) mark_virtual_column_deps(field); } return res; } inline bool TABLE::mark_virtual_column_with_deps(Field *field) { bool res; DBUG_ASSERT(field->vcol_info); if (!(res= bitmap_fast_test_and_set(read_set, field->field_index))) mark_virtual_column_deps(field); return res; } inline void TABLE::mark_virtual_column_deps(Field *field) { DBUG_ASSERT(field->vcol_info); DBUG_ASSERT(field->vcol_info->expr); field->vcol_info->expr->walk(&Item::register_field_in_read_map, 1, 0); } inline void TABLE::use_all_stored_columns() { bitmap_set_all(read_set); if (Field **vf= vfield) for (; *vf; vf++) bitmap_clear_bit(read_set, (*vf)->field_index); } #endif /* SQL_ITEM_INCLUDED */ mysql/server/private/lex_symbol.h000064400000002453151027430560013226 0ustar00/* Copyright (c) 2000, 2001, 2004, 2006, 2007 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This struct includes all reserved words and functions */ #ifndef _lex_symbol_h #define _lex_symbol_h struct st_sym_group; typedef struct st_symbol { const char *name; uint tok; uint length; struct st_sym_group *group; } SYMBOL; typedef struct st_lex_symbol { SYMBOL *symbol; char *str; uint length; } LEX_SYMBOL; typedef struct st_sym_group { const char *name; const char *needed_define; } SYM_GROUP; extern SYM_GROUP sym_group_common; extern SYM_GROUP sym_group_geom; extern SYM_GROUP sym_group_rtree; #endif /* _lex_symbol_h */ mysql/server/private/wsrep.h000064400000006354151027430560012215 0ustar00/* Copyright 2014 Codership Oy & SkySQL Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef WSREP_INCLUDED #define WSREP_INCLUDED #include #include "log.h" #ifdef WITH_WSREP #define IF_WSREP(A,B) A #define DBUG_ASSERT_IF_WSREP(A) DBUG_ASSERT(A) extern ulong wsrep_debug; // wsrep_mysqld.cc extern void WSREP_LOG(void (*fun)(const char* fmt, ...), const char* fmt, ...); #define WSREP_DEBUG(...) \ if (wsrep_debug) WSREP_LOG(sql_print_information, ##__VA_ARGS__) #define WSREP_INFO(...) WSREP_LOG(sql_print_information, ##__VA_ARGS__) #define WSREP_WARN(...) WSREP_LOG(sql_print_warning, ##__VA_ARGS__) #define WSREP_ERROR(...) WSREP_LOG(sql_print_error, ##__VA_ARGS__) #define WSREP_UNKNOWN(fmt, ...) WSREP_ERROR("UNKNOWN: " fmt, ##__VA_ARGS__) #define WSREP_LOG_CONFLICT_THD(thd, role) \ WSREP_INFO("%s: \n " \ " THD: %lu, mode: %s, state: %s, conflict: %s, seqno: %lld\n " \ " SQL: %s", \ role, \ thd_get_thread_id(thd), \ wsrep_thd_client_mode_str(thd), \ wsrep_thd_client_state_str(thd), \ wsrep_thd_transaction_state_str(thd), \ wsrep_thd_trx_seqno(thd), \ wsrep_thd_query(thd) \ ); #define WSREP_LOG_CONFLICT(bf_thd, victim_thd, bf_abort) \ if (wsrep_debug || wsrep_log_conflicts) \ { \ WSREP_INFO("cluster conflict due to %s for threads:", \ (bf_abort) ? "high priority abort" : "certification failure" \ ); \ if (bf_thd) WSREP_LOG_CONFLICT_THD(bf_thd, "Winning thread"); \ if (victim_thd) WSREP_LOG_CONFLICT_THD(victim_thd, "Victim thread"); \ WSREP_INFO("context: %s:%d", __FILE__, __LINE__); \ } #else /* !WITH_WSREP */ /* These macros are needed to compile MariaDB without WSREP support * (e.g. embedded) */ #define IF_WSREP(A,B) B //#define DBUG_ASSERT_IF_WSREP(A) #define WSREP_DEBUG(...) //#define WSREP_INFO(...) //#define WSREP_WARN(...) #define WSREP_ERROR(...) #endif /* WITH_WSREP */ #endif /* WSREP_INCLUDED */ mysql/server/private/sql_basic_types.h000064400000022470151027430560014236 0ustar00/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. Copyright (c) 2009, 2016, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* File that includes common types used globally in MariaDB */ #ifndef SQL_TYPES_INCLUDED #define SQL_TYPES_INCLUDED typedef ulonglong sql_mode_t; typedef int64 query_id_t; enum enum_nullability { NOT_NULL, NULLABLE }; /* "fuzzydate" with strict data type control. Represents a mixture of *only* data type conversion flags, without rounding. Please keep "explicit" in constructors and conversion methods. */ class date_conv_mode_t { public: enum value_t { CONV_NONE= 0U, /* FUZZY_DATES is used for the result will only be used for comparison purposes. Conversion is as relaxed as possible. */ FUZZY_DATES= 1U, TIME_ONLY= 4U, INTERVAL_hhmmssff= 8U, INTERVAL_DAY= 16U, RANGE0_LAST= INTERVAL_DAY, NO_ZERO_IN_DATE= (1UL << 23), // MODE_NO_ZERO_IN_DATE NO_ZERO_DATE= (1UL << 24), // MODE_NO_ZERO_DATE INVALID_DATES= (1UL << 25) // MODE_INVALID_DATES }; /* BIT-OR for all known values. Let's have a separate enum for it. - We don't put this value "value_t", to avoid handling it in switch(). - We don't put this value as a static const inside the class, because "gdb" would display it every time when we do "print" for a time_round_mode_t value. - We can't put into into a function returning this value, because it's not allowed to use functions in static_assert. */ enum known_values_t { KNOWN_MODES= FUZZY_DATES | TIME_ONLY | INTERVAL_hhmmssff | INTERVAL_DAY | NO_ZERO_IN_DATE | NO_ZERO_DATE | INVALID_DATES }; private: value_t m_mode; public: // Constructors explicit date_conv_mode_t(ulonglong fuzzydate) :m_mode((value_t) fuzzydate) { } // Conversion operators explicit operator ulonglong() const { return m_mode; } explicit operator bool() const { return m_mode != 0; } // Unary operators ulonglong operator~() const { return ~m_mode; } // Dyadic bitwise operators date_conv_mode_t operator&(const date_conv_mode_t &other) const { return date_conv_mode_t(m_mode & other.m_mode); } date_conv_mode_t operator&(const ulonglong other) const { return date_conv_mode_t(m_mode & other); } date_conv_mode_t operator|(const date_conv_mode_t &other) const { return date_conv_mode_t(m_mode | other.m_mode); } // Dyadic bitwise assignment operators date_conv_mode_t &operator&=(const date_conv_mode_t &other) { m_mode= value_t(m_mode & other.m_mode); return *this; } date_conv_mode_t &operator|=(const date_conv_mode_t &other) { m_mode= value_t(m_mode | other.m_mode); return *this; } }; /* Fractional rounding mode for temporal data types. */ class time_round_mode_t { public: enum value_t { /* Use FRAC_NONE when the value needs no rounding nor truncation, because it is already known not to haveany fractional digits outside of the requested precision. */ FRAC_NONE= 0, FRAC_TRUNCATE= date_conv_mode_t::RANGE0_LAST << 1, // 32 FRAC_ROUND= date_conv_mode_t::RANGE0_LAST << 2 // 64 }; // BIT-OR for all known values. See comments in time_conv_mode_t. enum known_values_t { KNOWN_MODES= FRAC_TRUNCATE | FRAC_ROUND }; private: value_t m_mode; public: // Constructors explicit time_round_mode_t(ulonglong mode) :m_mode((value_t) mode) { #ifdef MYSQL_SERVER DBUG_ASSERT(mode == FRAC_NONE || mode == FRAC_TRUNCATE || mode == FRAC_ROUND); #endif } // Conversion operators explicit operator ulonglong() const { return m_mode; } value_t mode() const { return m_mode; } // Comparison operators bool operator==(const time_round_mode_t &other) { return m_mode == other.m_mode; } }; /* "fuzzydate" with strict data type control. Used as a parameter to get_date() and represents a mixture of: - data type conversion flags - fractional second rounding flags Please keep "explicit" in constructors and conversion methods. */ class date_mode_t { public: enum value_t { CONV_NONE= date_conv_mode_t::CONV_NONE, // 0 FUZZY_DATES= date_conv_mode_t::FUZZY_DATES, // 1 TIME_ONLY= date_conv_mode_t::TIME_ONLY, // 4 INTERVAL_hhmmssff= date_conv_mode_t::INTERVAL_hhmmssff, // 8 INTERVAL_DAY= date_conv_mode_t::INTERVAL_DAY, // 16 FRAC_TRUNCATE= time_round_mode_t::FRAC_TRUNCATE, // 32 FRAC_ROUND= time_round_mode_t::FRAC_ROUND, // 64 NO_ZERO_IN_DATE= date_conv_mode_t::NO_ZERO_IN_DATE, // (1UL << 23) NO_ZERO_DATE= date_conv_mode_t::NO_ZERO_DATE, // (1UL << 24) INVALID_DATES= date_conv_mode_t::INVALID_DATES, // (1UL << 25) }; protected: value_t m_mode; public: // Constructors explicit date_mode_t(ulonglong fuzzydate) :m_mode((value_t) fuzzydate) { } // Conversion operators explicit operator ulonglong() const { return m_mode; } explicit operator bool() const { return m_mode != 0; } explicit operator date_conv_mode_t() const { return date_conv_mode_t(ulonglong(m_mode) & date_conv_mode_t::KNOWN_MODES); } explicit operator time_round_mode_t() const { return time_round_mode_t(ulonglong(m_mode) & time_round_mode_t::KNOWN_MODES); } // Unary operators ulonglong operator~() const { return ~m_mode; } bool operator!() const { return !m_mode; } // Dyadic bitwise operators date_mode_t operator&(const date_mode_t &other) const { return date_mode_t(m_mode & other.m_mode); } date_mode_t operator&(ulonglong other) const { return date_mode_t(m_mode & other); } date_mode_t operator|(const date_mode_t &other) const { return date_mode_t(m_mode | other.m_mode); } // Dyadic bitwise assignment operators date_mode_t &operator&=(const date_mode_t &other) { m_mode= value_t(m_mode & other.m_mode); return *this; } date_mode_t &operator|=(const date_mode_t &other) { m_mode= value_t(m_mode | other.m_mode); return *this; } date_mode_t &operator|=(const date_conv_mode_t &other) { m_mode= value_t(m_mode | ulonglong(other)); return *this; } }; // Bitwise OR out-of-class operators for data type mixtures static inline date_mode_t operator|(const date_mode_t &a, const date_conv_mode_t &b) { return date_mode_t(ulonglong(a) | ulonglong(b)); } static inline date_mode_t operator|(const date_conv_mode_t &a, const time_round_mode_t &b) { return date_mode_t(ulonglong(a) | ulonglong(b)); } static inline date_mode_t operator|(const date_conv_mode_t &a, const date_mode_t &b) { return date_mode_t(ulonglong(a) | ulonglong(b)); } // Bitwise AND out-of-class operators for data type mixtures static inline date_conv_mode_t operator&(const date_mode_t &a, const date_conv_mode_t &b) { return date_conv_mode_t(ulonglong(a) & ulonglong(b)); } static inline date_conv_mode_t operator&(const date_conv_mode_t &a, const date_mode_t &b) { return date_conv_mode_t(ulonglong(a) & ulonglong(b)); } static inline date_conv_mode_t operator&(sql_mode_t &a, const date_conv_mode_t &b) { return date_conv_mode_t(a & ulonglong(b)); } static const date_conv_mode_t TIME_CONV_NONE (date_conv_mode_t::CONV_NONE), TIME_FUZZY_DATES (date_conv_mode_t::FUZZY_DATES), TIME_TIME_ONLY (date_conv_mode_t::TIME_ONLY), TIME_INTERVAL_hhmmssff (date_conv_mode_t::INTERVAL_hhmmssff), TIME_INTERVAL_DAY (date_conv_mode_t::INTERVAL_DAY), TIME_NO_ZERO_IN_DATE (date_conv_mode_t::NO_ZERO_IN_DATE), TIME_NO_ZERO_DATE (date_conv_mode_t::NO_ZERO_DATE), TIME_INVALID_DATES (date_conv_mode_t::INVALID_DATES); // An often used combination static const date_conv_mode_t TIME_NO_ZEROS (date_conv_mode_t::NO_ZERO_DATE| date_conv_mode_t::NO_ZERO_IN_DATE); // Flags understood by str_to_xxx, number_to_xxx, check_date static const date_conv_mode_t TIME_MODE_FOR_XXX_TO_DATE (date_mode_t::NO_ZERO_IN_DATE | date_mode_t::NO_ZERO_DATE | date_mode_t::INVALID_DATES); static const time_round_mode_t TIME_FRAC_NONE (time_round_mode_t::FRAC_NONE), TIME_FRAC_TRUNCATE (time_round_mode_t::FRAC_TRUNCATE), TIME_FRAC_ROUND (time_round_mode_t::FRAC_ROUND); #endif mysql/server/private/wsrep_xid.h000064400000003015151027430560013050 0ustar00/* Copyright (C) 2015-2025 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #ifndef WSREP_XID_H #define WSREP_XID_H #include #ifdef WITH_WSREP #include "wsrep_mysqld.h" #include "wsrep/gtid.hpp" #include "handler.h" // XID typedef void wsrep_xid_init(xid_t*, const wsrep::gtid&, const wsrep_server_gtid_t&); const wsrep::id& wsrep_xid_uuid(const XID&); wsrep::seqno wsrep_xid_seqno(const XID&); template T wsrep_get_SE_checkpoint(); bool wsrep_set_SE_checkpoint(const wsrep::gtid& gtid, const wsrep_server_gtid_t&); //void wsrep_get_SE_checkpoint(XID&); /* uncomment if needed */ //void wsrep_set_SE_checkpoint(XID&); /* uncomment if needed */ void wsrep_sort_xid_array(XID *array, int len); std::string wsrep_xid_print(const XID *xid); bool wsrep_is_xid_gtid_undefined(const XID *xid); #endif /* WITH_WSREP */ #endif /* WSREP_UTILS_H */ mysql/server/private/embedded_priv.h000064400000003305151027430560013637 0ustar00/* Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Prototypes for the embedded version of MySQL */ #include C_MODE_START void lib_connection_phase(NET *net, int phase); void init_embedded_mysql(MYSQL *mysql, ulong client_flag); void *create_embedded_thd(ulong client_flag); int check_embedded_connection(MYSQL *mysql, const char *db); void free_old_query(MYSQL *mysql); THD *embedded_get_current_thd(); void embedded_set_current_thd(THD *thd); extern MYSQL_METHODS embedded_methods; /* This one is used by embedded library to gather returning data */ typedef struct embedded_query_result { MYSQL_ROWS **prev_ptr; unsigned int warning_count, server_status; struct st_mysql_data *next; my_ulonglong affected_rows, insert_id; char info[MYSQL_ERRMSG_SIZE]; MYSQL_FIELD *fields_list; unsigned int last_errno; char sqlstate[SQLSTATE_LENGTH+1]; } EQR; typedef struct st_mariadb_field_extension { MARIADB_CONST_STRING metadata[MARIADB_FIELD_ATTR_LAST+1]; /* 10.5 */ } MARIADB_FIELD_EXTENSION; C_MODE_END mysql/server/private/scope.h000064400000010451151027430560012157 0ustar00/* Copyright (c) 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once #include #include namespace detail { template class scope_exit { public: template explicit scope_exit(F &&f) : function_(std::forward(f)) { } template scope_exit(F &&f, bool engaged) : function_(std::forward(f)), engaged_(engaged) { } scope_exit(scope_exit &&rhs) : function_(std::move(rhs.function_)), engaged_(rhs.engaged_) { rhs.release(); } scope_exit(const scope_exit &)= delete; scope_exit &operator=(scope_exit &&)= delete; scope_exit &operator=(const scope_exit &)= delete; void release() { engaged_= false; } void engage() { DBUG_ASSERT(!engaged_); engaged_= true; } ~scope_exit() { if (engaged_) function_(); } private: Callable function_; bool engaged_= true; }; } // end namespace detail template inline ::detail::scope_exit::type> make_scope_exit(Callable &&f, bool engaged= true) { return ::detail::scope_exit::type>( std::forward(f), engaged); } #define CONCAT_IMPL(x, y) x##y #define CONCAT(x, y) CONCAT_IMPL(x, y) #define ANONYMOUS_VARIABLE CONCAT(_anonymous_variable, __LINE__) #define SCOPE_EXIT auto ANONYMOUS_VARIABLE= make_scope_exit #define IF_CLASS(C) typename std::enable_if::value>::type #define IF_NOT_CLASS(C) typename std::enable_if::value>::type namespace detail { template class Scope_value { public: // Use SFINAE for passing structs by reference and plain types by value. // This ctor is defined only if T is a class or struct: template Scope_value(T &variable, const T &scope_value) : variable_(&variable), saved_value_(variable) { variable= scope_value; } // This ctor is defined only if T is NOT a class or struct: template Scope_value(T &variable, const T scope_value) : variable_(&variable), saved_value_(variable) { variable= scope_value; } Scope_value(Scope_value &&rhs) : variable_(rhs.variable_), saved_value_(rhs.saved_value_) { rhs.variable_= NULL; } Scope_value(const Scope_value &)= delete; Scope_value &operator=(const Scope_value &)= delete; Scope_value &operator=(Scope_value &&)= delete; ~Scope_value() { if (variable_) *variable_= saved_value_; } private: T *variable_; T saved_value_; }; } // namespace detail // Use like this: // auto _= make_scope_value(var, tmp_value); template inline ::detail::Scope_value make_scope_value(T &variable, const T &scope_value) { return ::detail::Scope_value(variable, scope_value); } template inline ::detail::Scope_value make_scope_value(T &variable, T scope_value) { return ::detail::Scope_value(variable, scope_value); } /* Note: perfect forwarding version can not pass const: template inline detail::Scope_value make_scope_value(T &variable, U &&scope_value) { return detail::Scope_value(variable, std::forward(scope_value)); } as `const U &&` fails with error `expects an rvalue for 2nd argument`. That happens because const U && is treated as rvalue only (this is the exact syntax for declaring rvalues). */ #define SCOPE_VALUE auto ANONYMOUS_VARIABLE= make_scope_value #define SCOPE_SET(VAR, MASK) auto ANONYMOUS_VARIABLE= make_scope_value(VAR, VAR | MASK) #define SCOPE_CLEAR(VAR, MASK) auto ANONYMOUS_VARIABLE= make_scope_value(VAR, VAR & ~MASK) mysql/server/private/queues.h000064400000006625151027430560012365 0ustar00/* Copyright (C) 2010 Monty Program Ab All Rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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. */ /* Code for general handling of priority Queues. Implementation of queues from "Algorithms in C" by Robert Sedgewick. */ #ifndef _queues_h #define _queues_h #include #ifdef __cplusplus extern "C" { #endif typedef struct st_queue { uchar **root; void *first_cmp_arg; uint elements; uint max_elements; uint offset_to_key; /* compare is done on element+offset */ uint offset_to_queue_pos; /* If we want to store position in element */ uint auto_extent; int max_at_top; /* Normally 1, set to -1 if queue_top gives max */ qsort_cmp2 compare; } QUEUE; #define queue_first_element(queue) 1 #define queue_last_element(queue) (queue)->elements #define queue_empty(queue) ((queue)->elements == 0) #define queue_top(queue) ((queue)->root[1]) #define queue_element(queue,index) ((queue)->root[index]) #define queue_end(queue) ((queue)->root[(queue)->elements]) #define queue_replace_top(queue) _downheap(queue, 1) #define queue_set_cmp_arg(queue, set_arg) (queue)->first_cmp_arg= set_arg #define queue_set_max_at_top(queue, set_arg) \ (queue)->max_at_top= set_arg ? -1 : 1 #define queue_remove_top(queue_arg) queue_remove((queue_arg), queue_first_element(queue_arg)) int init_queue(QUEUE *queue,uint max_elements,uint offset_to_key, my_bool max_at_top, qsort_cmp2 compare, void *first_cmp_arg, uint offset_to_queue_pos, uint auto_extent); int reinit_queue(QUEUE *queue,uint max_elements,uint offset_to_key, my_bool max_at_top, qsort_cmp2 compare, void *first_cmp_arg, uint offset_to_queue_pos, uint auto_extent); int resize_queue(QUEUE *queue, uint max_elements); void delete_queue(QUEUE *queue); void queue_insert(QUEUE *queue, uchar *element); int queue_insert_safe(QUEUE *queue, uchar *element); uchar *queue_remove(QUEUE *queue,uint idx); void queue_replace(QUEUE *queue,uint idx); #define queue_remove_all(queue) { (queue)->elements= 0; } #define queue_is_full(queue) (queue->elements == queue->max_elements) void _downheap(QUEUE *queue, uint idx); void queue_fix(QUEUE *queue); #define is_queue_inited(queue) ((queue)->root != 0) #ifdef __cplusplus } #endif #endif mysql/server/private/sys_vars_shared.h000064400000005251151027430560014247 0ustar00#ifndef SYS_VARS_SHARED_INCLUDED #define SYS_VARS_SHARED_INCLUDED /* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file "protected" interface to sys_var - server configuration variables. This header is included by files implementing support and utility functions of sys_var's (set_var.cc) and files implementing classes in the sys_var hierarchy (sql_plugin.cc) */ #include #include "set_var.h" extern bool throw_bounds_warning(THD *thd, const char *name,const char *v); extern bool throw_bounds_warning(THD *thd, const char *name, bool fixed, bool is_unsigned, longlong v); extern bool throw_bounds_warning(THD *thd, const char *name, bool fixed, double v); extern sys_var *intern_find_sys_var(const char *str, size_t length); extern sys_var_chain all_sys_vars; /** wrapper to hide a mutex and an rwlock under a common interface */ class PolyLock { public: virtual void rdlock()= 0; virtual void wrlock()= 0; virtual void unlock()= 0; virtual ~PolyLock() = default; }; class PolyLock_mutex: public PolyLock { mysql_mutex_t *mutex; public: PolyLock_mutex(mysql_mutex_t *arg): mutex(arg) {} void rdlock() override { mysql_mutex_lock(mutex); } void wrlock() override { mysql_mutex_lock(mutex); } void unlock() override { mysql_mutex_unlock(mutex); } }; class PolyLock_rwlock: public PolyLock { mysql_rwlock_t *rwlock; public: PolyLock_rwlock(mysql_rwlock_t *arg): rwlock(arg) {} void rdlock() override { mysql_rwlock_rdlock(rwlock); } void wrlock() override { mysql_rwlock_wrlock(rwlock); } void unlock() override { mysql_rwlock_unlock(rwlock); } }; class AutoWLock { PolyLock *lock; public: AutoWLock(PolyLock *l) : lock(l) { if (lock) lock->wrlock(); } ~AutoWLock() { if (lock) lock->unlock(); } }; class AutoRLock { PolyLock *lock; public: AutoRLock(PolyLock *l) : lock(l) { if (lock) lock->rdlock(); } ~AutoRLock() { if (lock) lock->unlock(); } }; #endif /* SYS_VARS_SHARED_INCLUDED */ mysql/server/private/threadpool.h000064400000011312151027430560013204 0ustar00/* Copyright (C) 2012, 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once #ifdef HAVE_POOL_OF_THREADS #define MAX_THREAD_GROUPS 100000 /* Threadpool parameters */ extern uint threadpool_min_threads; /* Minimum threads in pool */ extern uint threadpool_idle_timeout; /* Shutdown idle worker threads after this timeout */ extern uint threadpool_size; /* Number of parallel executing threads */ extern uint threadpool_max_size; extern uint threadpool_stall_limit; /* time interval in milliseconds for stall checks*/ extern uint threadpool_max_threads; /* Maximum threads in pool */ extern uint threadpool_oversubscribe; /* Maximum active threads in group */ extern uint threadpool_prio_kickup_timer; /* Time before low prio item gets prio boost */ extern my_bool threadpool_exact_stats; /* Better queueing time stats for information_schema, at small performance cost */ extern my_bool threadpool_dedicated_listener; /* Listener thread does not pick up work items. */ #ifdef _WIN32 extern uint threadpool_mode; /* Thread pool implementation , windows or generic */ #define TP_MODE_WINDOWS 0 #define TP_MODE_GENERIC 1 #endif #define DEFAULT_THREADPOOL_STALL_LIMIT 500U struct TP_connection; struct st_vio; extern void tp_callback(TP_connection *c); extern void tp_timeout_handler(TP_connection *c); /* Threadpool statistics */ struct TP_STATISTICS { /* Current number of worker thread. */ Atomic_counter num_worker_threads; }; extern TP_STATISTICS tp_stats; /* Functions to set threadpool parameters */ extern void tp_set_min_threads(uint val); extern void tp_set_max_threads(uint val); extern void tp_set_threadpool_size(uint val); extern void tp_set_threadpool_stall_limit(uint val); extern int tp_get_idle_thread_count(); extern int tp_get_thread_count(); enum TP_PRIORITY { TP_PRIORITY_HIGH, TP_PRIORITY_LOW, TP_PRIORITY_AUTO }; enum TP_STATE { TP_STATE_IDLE, TP_STATE_RUNNING, TP_STATE_PENDING }; /* Connection structure, encapsulates THD + structures for asynchronous IO and pool. Platform specific parts are specified in subclasses called connection_t, inside threadpool_win.cc and threadpool_unix.cc */ class CONNECT; struct TP_connection { THD* thd; CONNECT* connect; TP_STATE state; TP_PRIORITY priority; TP_connection(CONNECT *c) : thd(0), connect(c), state(TP_STATE_IDLE), priority(TP_PRIORITY_HIGH) {} virtual ~TP_connection() = default; /* Initialize io structures windows threadpool, epoll etc */ virtual int init() = 0; virtual void set_io_timeout(int sec) = 0; /* Read for the next client command (async) with specified timeout */ virtual int start_io() = 0; virtual void wait_begin(int type)= 0; virtual void wait_end() = 0; IF_WIN(virtual,) void init_vio(st_vio *){}; }; struct TP_pool { virtual ~TP_pool() = default; virtual int init()= 0; virtual TP_connection *new_connection(CONNECT *)= 0; virtual void add(TP_connection *c)= 0; virtual int set_max_threads(uint){ return 0; } virtual int set_min_threads(uint){ return 0; } virtual int set_pool_size(uint){ return 0; } virtual int set_idle_timeout(uint){ return 0; } virtual int set_oversubscribe(uint){ return 0; } virtual int set_stall_limit(uint){ return 0; } virtual int get_thread_count() { return tp_stats.num_worker_threads; } virtual int get_idle_thread_count(){ return 0; } virtual void resume(TP_connection* c)=0; }; #ifdef _WIN32 struct TP_pool_win:TP_pool { TP_pool_win(); int init() override; ~TP_pool_win() override; TP_connection *new_connection(CONNECT *c) override; void add(TP_connection *) override; int set_max_threads(uint) override; int set_min_threads(uint) override; void resume(TP_connection *c) override; }; #endif struct TP_pool_generic :TP_pool { TP_pool_generic(); ~TP_pool_generic(); int init() override; TP_connection *new_connection(CONNECT *c) override; void add(TP_connection *) override; int set_pool_size(uint) override; int set_stall_limit(uint) override; int get_idle_thread_count() override; void resume(TP_connection* c) override; }; #endif /* HAVE_POOL_OF_THREADS */ mysql/server/private/session_tracker.h000064400000033703151027430560014251 0ustar00#ifndef SESSION_TRACKER_INCLUDED #define SESSION_TRACKER_INCLUDED /* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2016, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "m_string.h" #include "thr_lock.h" #include "sql_hset.h" #ifndef EMBEDDED_LIBRARY /* forward declarations */ class THD; class set_var; class String; class user_var_entry; enum enum_session_tracker { SESSION_SYSVARS_TRACKER, /* Session system variables */ CURRENT_SCHEMA_TRACKER, /* Current schema */ SESSION_STATE_CHANGE_TRACKER, TRANSACTION_INFO_TRACKER, /* Transaction state */ #ifdef USER_VAR_TRACKING USER_VARIABLES_TRACKER, #endif // USER_VAR_TRACKING SESSION_TRACKER_END /* must be the last */ }; /** State_tracker An abstract class that defines the interface for any of the server's 'session state change tracker'. A tracker, however, is a sub- class of this class which takes care of tracking the change in value of a part- icular session state type and thus defines various methods listed in this interface. The change information is later serialized and transmitted to the client through protocol's OK packet. Tracker system variables :- A tracker is normally mapped to a system variable. So in order to enable, disable or modify the sub-entities of a tracker, the user needs to modify the respective system variable either through SET command or via command line option. As required in system variable handling, this interface also includes two functions to help in the verification of the supplied value (ON_UPDATE) of the tracker system variable, namely - update(). */ class State_tracker { protected: /** Is tracking enabled for a particular session state type ? @note: it is a cache of the corresponding thd->variables.session_track_xxx variable */ bool m_enabled; void set_changed(THD *thd); private: /** Has the session state type changed ? */ bool m_changed; public: virtual ~State_tracker() = default; /** Getters */ bool is_enabled() const { return m_enabled; } bool is_changed() const { return m_changed; } void reset_changed() { m_changed= false; } /** Called by THD::init() when new connection is being created We may inherit m_changed from previous connection served by this THD if connection was broken or client didn't have session tracking capability. Thus we have to reset it here. */ virtual bool enable(THD *thd) { reset_changed(); return update(thd, 0); } /** To be invoked when the tracker's system variable is updated (ON_UPDATE).*/ virtual bool update(THD *thd, set_var *var)= 0; /** Store changed data into the given buffer. */ virtual bool store(THD *thd, String *buf)= 0; /** Mark the entity as changed. */ void mark_as_changed(THD *thd) { if (is_enabled()) set_changed(thd); } }; /** Session_sysvars_tracker This is a tracker class that enables & manages the tracking of session system variables. It internally maintains a hash of user supplied variable references and a boolean field to store if the variable was changed by the last statement. */ class Session_sysvars_tracker: public State_tracker { struct sysvar_node_st { sys_var *m_svar; bool *test_load; bool m_changed; }; class vars_list { /** Registered system variables. (@@session_track_system_variables) A hash to store the name of all the system variables specified by the user. */ HASH m_registered_sysvars; /** If TRUE then we want to check all session variable. */ bool track_all; void init() { my_hash_init(PSI_INSTRUMENT_ME, &m_registered_sysvars, &my_charset_bin, 0, 0, 0, sysvars_get_key, my_free, HASH_UNIQUE | (mysqld_server_initialized ? HASH_THREAD_SPECIFIC : 0)); } void free_hash() { DBUG_ASSERT(my_hash_inited(&m_registered_sysvars)); my_hash_free(&m_registered_sysvars); } sysvar_node_st *search(const sys_var *svar) { return reinterpret_cast( my_hash_search(&m_registered_sysvars, reinterpret_cast(&svar), sizeof(sys_var*))); } sysvar_node_st *at(ulong i) { DBUG_ASSERT(i < m_registered_sysvars.records); return reinterpret_cast( my_hash_element(&m_registered_sysvars, i)); } public: vars_list(): track_all(false) { init(); } ~vars_list() { if (my_hash_inited(&m_registered_sysvars)) free_hash(); } void deinit() { free_hash(); } sysvar_node_st *insert_or_search(const sys_var *svar) { sysvar_node_st *res= search(svar); if (!res) { if (track_all) { insert(svar); return search(svar); } } return res; } bool insert(const sys_var *svar); void reinit(); void reset(); inline bool is_enabled() { return track_all || m_registered_sysvars.records; } void copy(vars_list* from, THD *thd); bool parse_var_list(THD *thd, LEX_STRING var_list, bool throw_error, CHARSET_INFO *char_set); bool construct_var_list(char *buf, size_t buf_len); bool store(THD *thd, String *buf); }; /** Two objects of vars_list type are maintained to manage various operations. */ vars_list orig_list; bool m_parsed; public: void init(THD *thd); void deinit(THD *thd); bool enable(THD *thd) override; bool update(THD *thd, set_var *var) override; bool store(THD *thd, String *buf) override; void mark_as_changed(THD *thd, const sys_var *var); void deinit() { orig_list.deinit(); } /* callback */ static const uchar *sysvars_get_key(const void *entry, size_t *length, my_bool); friend bool sysvartrack_global_update(THD *thd, char *str, size_t len); }; bool sysvartrack_validate_value(THD *thd, const char *str, size_t len); bool sysvartrack_global_update(THD *thd, char *str, size_t len); /** Current_schema_tracker, This is a tracker class that enables & manages the tracking of current schema for a particular connection. */ class Current_schema_tracker: public State_tracker { public: bool update(THD *thd, set_var *var) override; bool store(THD *thd, String *buf) override; }; /* Session_state_change_tracker This is a boolean tracker class that will monitor any change that contributes to a session state change. Attributes that contribute to session state change include: - Successful change to System variables - User defined variables assignments - temporary tables created, altered or deleted - prepared statements added or removed - change in current database - change of current role */ class Session_state_change_tracker: public State_tracker { public: bool update(THD *thd, set_var *var) override; bool store(THD *thd, String *buf) override; }; /* Transaction_state_tracker */ /** Transaction state (no transaction, transaction active, work attached, etc.) */ enum enum_tx_state { TX_EMPTY = 0, ///< "none of the below" TX_EXPLICIT = 1, ///< an explicit transaction is active TX_IMPLICIT = 2, ///< an implicit transaction is active TX_READ_TRX = 4, ///< transactional reads were done TX_READ_UNSAFE = 8, ///< non-transaction reads were done TX_WRITE_TRX = 16, ///< transactional writes were done TX_WRITE_UNSAFE = 32, ///< non-transactional writes were done TX_STMT_UNSAFE = 64, ///< "unsafe" (non-deterministic like UUID()) stmts TX_RESULT_SET = 128, ///< result set was sent TX_WITH_SNAPSHOT= 256, ///< WITH CONSISTENT SNAPSHOT was used TX_LOCKED_TABLES= 512 ///< LOCK TABLES is active }; /** Transaction access mode */ enum enum_tx_read_flags { TX_READ_INHERIT = 0, ///< not explicitly set, inherit session.tx_read_only TX_READ_ONLY = 1, ///< START TRANSACTION READ ONLY, or tx_read_only=1 TX_READ_WRITE = 2, ///< START TRANSACTION READ WRITE, or tx_read_only=0 }; /** Transaction isolation level */ enum enum_tx_isol_level { TX_ISOL_INHERIT = 0, ///< not explicitly set, inherit session.tx_isolation TX_ISOL_UNCOMMITTED = 1, TX_ISOL_COMMITTED = 2, TX_ISOL_REPEATABLE = 3, TX_ISOL_SERIALIZABLE= 4 }; /** Transaction tracking level */ enum enum_session_track_transaction_info { TX_TRACK_NONE = 0, ///< do not send tracker items on transaction info TX_TRACK_STATE = 1, ///< track transaction status TX_TRACK_CHISTICS = 2 ///< track status and characteristics }; /** This is a tracker class that enables & manages the tracking of current transaction info for a particular connection. */ class Transaction_state_tracker : public State_tracker { /** Helper function: turn table info into table access flag */ enum_tx_state calc_trx_state(THD *thd, thr_lock_type l, bool has_trx); public: bool enable(THD *thd) override { m_enabled= false; tx_changed= TX_CHG_NONE; tx_curr_state= TX_EMPTY; tx_reported_state= TX_EMPTY; tx_read_flags= TX_READ_INHERIT; tx_isol_level= TX_ISOL_INHERIT; return State_tracker::enable(thd); } bool update(THD *thd, set_var *var) override; bool store(THD *thd, String *buf) override; /** Change transaction characteristics */ void set_read_flags(THD *thd, enum enum_tx_read_flags flags); void set_isol_level(THD *thd, enum enum_tx_isol_level level); /** Change transaction state */ void clear_trx_state(THD *thd, uint clear); void add_trx_state(THD *thd, uint add); void inline add_trx_state(THD *thd, thr_lock_type l, bool has_trx) { add_trx_state(thd, calc_trx_state(thd, l, has_trx)); } void add_trx_state_from_thd(THD *thd); void end_trx(THD *thd); private: enum enum_tx_changed { TX_CHG_NONE = 0, ///< no changes from previous stmt TX_CHG_STATE = 1, ///< state has changed from previous stmt TX_CHG_CHISTICS = 2 ///< characteristics have changed from previous stmt }; /** any trackable changes caused by this statement? */ uint tx_changed; /** transaction state */ uint tx_curr_state, tx_reported_state; /** r/w or r/o set? session default? */ enum enum_tx_read_flags tx_read_flags; /** isolation level */ enum enum_tx_isol_level tx_isol_level; inline void update_change_flags(THD *thd) { tx_changed &= uint(~TX_CHG_STATE); tx_changed |= (tx_curr_state != tx_reported_state) ? TX_CHG_STATE : 0; if (tx_changed != TX_CHG_NONE) set_changed(thd); } }; #define TRANSACT_TRACKER(X) \ do { if (thd->variables.session_track_transaction_info > TX_TRACK_NONE) \ thd->session_tracker.transaction_info.X; } while(0) /** User_variables_tracker This is a tracker class that enables & manages the tracking of user variables. */ #ifdef USER_VAR_TRACKING class User_variables_tracker: public State_tracker { Hash_set m_changed_user_variables; public: User_variables_tracker(): m_changed_user_variables(PSI_INSTRUMENT_ME, &my_charset_bin, 0, 0, sizeof(const user_var_entry*), 0, 0, HASH_UNIQUE | mysqld_server_initialized ? HASH_THREAD_SPECIFIC : 0) {} bool update(THD *thd, set_var *var); bool store(THD *thd, String *buf); void mark_as_changed(THD *thd, const user_var_entry *var) { if (is_enabled()) { m_changed_user_variables.insert(var); set_changed(thd); } } void deinit() { m_changed_user_variables.~Hash_set(); } }; #endif // USER_VAR_TRACKING /** Session_tracker This class holds an object each for all tracker classes and provides methods necessary for systematic detection and generation of session state change information. */ class Session_tracker { State_tracker *m_trackers[SESSION_TRACKER_END]; /* The following two functions are private to disable copying. */ Session_tracker(Session_tracker const &other) { DBUG_ASSERT(FALSE); } Session_tracker& operator= (Session_tracker const &rhs) { DBUG_ASSERT(FALSE); return *this; } public: Current_schema_tracker current_schema; Session_state_change_tracker state_change; Transaction_state_tracker transaction_info; Session_sysvars_tracker sysvars; #ifdef USER_VAR_TRACKING User_variables_tracker user_variables; #endif // USER_VAR_TRACKING Session_tracker() { m_trackers[SESSION_SYSVARS_TRACKER]= &sysvars; m_trackers[CURRENT_SCHEMA_TRACKER]= ¤t_schema; m_trackers[SESSION_STATE_CHANGE_TRACKER]= &state_change; m_trackers[TRANSACTION_INFO_TRACKER]= &transaction_info; #ifdef USER_VAR_TRACKING m_trackers[USER_VARIABLES_TRACKER]= &user_variables; #endif // USER_VAR_TRACKING } void enable(THD *thd) { for (int i= 0; i < SESSION_TRACKER_END; i++) m_trackers[i]->enable(thd); } void store(THD *thd, String *main_buf); }; int session_tracker_init(); #else #define TRANSACT_TRACKER(X) do{}while(0) class Session_tracker { class Dummy_tracker { public: void mark_as_changed(THD *thd) {} void mark_as_changed(THD *thd, const sys_var *var) {} }; public: Dummy_tracker current_schema; Dummy_tracker state_change; Dummy_tracker sysvars; }; #endif //EMBEDDED_LIBRARY #endif /* SESSION_TRACKER_INCLUDED */ mysql/server/private/sql_plugin.h000064400000016575151027430560013240 0ustar00/* Copyright (c) 2005, 2012, Oracle and/or its affiliates. Copyright (c) 2009, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _sql_plugin_h #define _sql_plugin_h /* the following #define adds server-only members to enum_mysql_show_type, that is defined in plugin.h */ #define SHOW_always_last SHOW_KEY_CACHE_LONG, \ SHOW_HAVE, SHOW_MY_BOOL, SHOW_HA_ROWS, SHOW_SYS, \ SHOW_LONG_NOFLUSH, SHOW_LEX_STRING, SHOW_ATOMIC_COUNTER_UINT32_T, \ /* SHOW_*_STATUS must be at the end, SHOW_LONG_STATUS being first */ \ SHOW_LONG_STATUS, SHOW_DOUBLE_STATUS, SHOW_LONGLONG_STATUS, \ SHOW_UINT32_STATUS #include "mariadb.h" #undef SHOW_always_last #include "m_string.h" /* LEX_STRING */ #include "my_alloc.h" /* MEM_ROOT */ class sys_var; enum SHOW_COMP_OPTION { SHOW_OPTION_YES, SHOW_OPTION_NO, SHOW_OPTION_DISABLED}; enum enum_plugin_load_option { PLUGIN_OFF, PLUGIN_ON, PLUGIN_FORCE, PLUGIN_FORCE_PLUS_PERMANENT }; extern const char *global_plugin_typelib_names[]; extern volatile int global_plugin_version; extern ulong dlopen_count; #include #include "sql_list.h" #ifdef DBUG_OFF #define plugin_ref_to_int(A) A #define plugin_int_to_ref(A) A #else #define plugin_ref_to_int(A) (A ? A[0] : NULL) #define plugin_int_to_ref(A) &(A) #endif /* the following flags are valid for plugin_init() */ #define PLUGIN_INIT_SKIP_PLUGIN_TABLE 1U #define PLUGIN_INIT_SKIP_INITIALIZATION 2U #define INITIAL_LEX_PLUGIN_LIST_SIZE 16 typedef enum enum_mysql_show_type SHOW_TYPE; typedef struct st_mysql_show_var SHOW_VAR; #define MYSQL_ANY_PLUGIN -1 /* different values of st_plugin_int::state though they look like a bitmap, plugin may only be in one of those eigenstates, not in a superposition of them :) It's a bitmap, because it makes it easier to test "whether the state is one of those..." */ #define PLUGIN_IS_FREED 1U #define PLUGIN_IS_DELETED 2U #define PLUGIN_IS_UNINITIALIZED 4U #define PLUGIN_IS_READY 8U #define PLUGIN_IS_DYING 16U #define PLUGIN_IS_DISABLED 32U struct st_ptr_backup { void **ptr; void *value; void save(void **p) { ptr= p; value= *p; } void save(const char **p) { save((void**)p); } void restore() { *ptr= value; } }; /* A handle for the dynamic library containing a plugin or plugins. */ struct st_plugin_dl { LEX_CSTRING dl; void *handle; struct st_maria_plugin *plugins; st_ptr_backup *ptr_backup; uint nbackups; uint ref_count; /* number of plugins loaded from the library */ int mysqlversion; int mariaversion; bool allocated; }; /* A handle of a plugin */ struct st_plugin_int { LEX_CSTRING name; struct st_maria_plugin *plugin; struct st_plugin_dl *plugin_dl; st_ptr_backup *ptr_backup; uint nbackups; uint state; uint ref_count; /* number of threads using the plugin */ uint locks_total; /* how many times the plugin was locked */ void *data; /* plugin type specific, e.g. handlerton */ MEM_ROOT mem_root; /* memory for dynamic plugin structures */ sys_var *system_vars; /* server variables for this plugin */ enum enum_plugin_load_option load_option; /* OFF, ON, FORCE, F+PERMANENT */ }; extern mysql_mutex_t LOCK_plugin; /* See intern_plugin_lock() for the explanation for the conditionally defined plugin_ref type */ #ifdef DBUG_OFF typedef struct st_plugin_int *plugin_ref; #define plugin_ref_to_int(A) A #define plugin_int_to_ref(A) A #define plugin_decl(pi) ((pi)->plugin) #define plugin_dlib(pi) ((pi)->plugin_dl) #define plugin_data(pi,cast) ((cast)((pi)->data)) #define plugin_name(pi) (&((pi)->name)) #define plugin_state(pi) ((pi)->state) #define plugin_load_option(pi) ((pi)->load_option) #define plugin_equals(p1,p2) ((p1) == (p2)) #else typedef struct st_plugin_int **plugin_ref; #define plugin_ref_to_int(A) (A ? A[0] : NULL) #define plugin_int_to_ref(A) &(A) #define plugin_decl(pi) ((pi)[0]->plugin) #define plugin_dlib(pi) ((pi)[0]->plugin_dl) #define plugin_data(pi,cast) ((cast)((pi)[0]->data)) #define plugin_name(pi) (&((pi)[0]->name)) #define plugin_state(pi) ((pi)[0]->state) #define plugin_load_option(pi) ((pi)[0]->load_option) #define plugin_equals(p1,p2) ((p1) && (p2) && (p1)[0] == (p2)[0]) #endif typedef int (*plugin_type_init)(void *); extern I_List *opt_plugin_load_list_ptr; extern char *opt_plugin_dir_ptr; extern MYSQL_PLUGIN_IMPORT char opt_plugin_dir[FN_REFLEN]; extern const LEX_CSTRING plugin_type_names[]; extern ulong plugin_maturity; extern TYPELIB plugin_maturity_values; extern const char *plugin_maturity_names[]; extern int plugin_init(int *argc, char **argv, int init_flags); extern void plugin_shutdown(void); void add_plugin_options(DYNAMIC_ARRAY *options, MEM_ROOT *mem_root); extern bool plugin_is_ready(const LEX_CSTRING *name, int type); #define my_plugin_lock_by_name(A,B,C) plugin_lock_by_name(A,B,C) #define my_plugin_lock(A,B) plugin_lock(A,B) extern plugin_ref plugin_lock(THD *thd, plugin_ref ptr); extern plugin_ref plugin_lock_by_name(THD *thd, const LEX_CSTRING *name, int type); extern void plugin_unlock(THD *thd, plugin_ref plugin); extern void plugin_unlock_list(THD *thd, plugin_ref *list, uint count); extern bool mysql_install_plugin(THD *thd, const LEX_CSTRING *name, const LEX_CSTRING *dl); extern bool mysql_uninstall_plugin(THD *thd, const LEX_CSTRING *name, const LEX_CSTRING *dl); extern bool plugin_register_builtin(struct st_mysql_plugin *plugin); extern void plugin_thdvar_init(THD *thd); extern void plugin_thdvar_cleanup(THD *thd); sys_var *find_plugin_sysvar(st_plugin_int *plugin, st_mysql_sys_var *var); void plugin_opt_set_limits(struct my_option *, const struct st_mysql_sys_var *); extern SHOW_COMP_OPTION plugin_status(const char *name, size_t len, int type); extern bool check_valid_path(const char *path, size_t length); extern void plugin_mutex_init(); typedef my_bool (plugin_foreach_func)(THD *thd, plugin_ref plugin, void *arg); #define plugin_foreach(A,B,C,D) plugin_foreach_with_mask(A,B,C,PLUGIN_IS_READY,D) extern bool plugin_foreach_with_mask(THD *thd, plugin_foreach_func *func, int type, uint state_mask, void *arg); extern void sync_dynamic_session_variables(THD* thd, bool global_lock); extern bool plugin_dl_foreach(THD *thd, const LEX_CSTRING *dl, plugin_foreach_func *func, void *arg); extern void sync_dynamic_session_variables(THD* thd, bool global_lock); #endif #ifdef WITH_WSREP extern void wsrep_plugins_pre_init(); extern void wsrep_plugins_post_init(); #endif /* WITH_WSREP */ mysql/server/private/wsrep_client_state.h000064400000003036151027430560014745 0ustar00/* Copyright 2018 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WSREP_CLIENT_STATE_H #define WSREP_CLIENT_STATE_H /* wsrep-lib */ #include "wsrep/client_state.hpp" #include "my_global.h" class THD; class Wsrep_client_state : public wsrep::client_state { public: Wsrep_client_state(THD* thd, wsrep::mutex& mutex, wsrep::condition_variable& cond, wsrep::server_state& server_state, wsrep::client_service& client_service, const wsrep::client_id& id) : wsrep::client_state(mutex, cond, server_state, client_service, id, wsrep::client_state::m_local) , m_thd(thd) { } THD* thd() { return m_thd; } private: THD* m_thd; }; #endif /* WSREP_CLIENT_STATE_H */ mysql/server/private/rpl_parallel.h000064400000042065151027430560013525 0ustar00#ifndef RPL_PARALLEL_H #define RPL_PARALLEL_H #include "log_event.h" struct rpl_parallel; struct rpl_parallel_entry; struct rpl_parallel_thread_pool; extern struct rpl_parallel_thread_pool pool_bkp_for_pfs; class Relay_log_info; struct inuse_relaylog; /* Structure used to keep track of the parallel replication of a batch of event-groups that group-committed together on the master. It is used to ensure that every event group in one batch has reached the commit stage before the next batch starts executing. Note the lifetime of this structure: - It is allocated when the first event in a new batch of group commits is queued, from the free list rpl_parallel_entry::gco_free_list. - The gco for the batch currently being queued is owned by rpl_parallel_entry::current_gco. The gco for a previous batch that has been fully queued is owned by the gco->prev_gco pointer of the gco for the following batch. - The worker thread waits on gco->COND_group_commit_orderer for rpl_parallel_entry::count_committing_event_groups to reach wait_count before starting; the first waiter links the gco into the next_gco pointer of the gco of the previous batch for signalling. - When an event group reaches the commit stage, it signals the COND_group_commit_orderer if its gco->next_gco pointer is non-NULL and rpl_parallel_entry::count_committing_event_groups has reached gco->next_gco->wait_count. - The gco lives until all its event groups have completed their commit. This is detected by rpl_parallel_entry::last_committed_sub_id being greater than or equal gco->last_sub_id. Once this happens, the gco is freed. Note that since update of last_committed_sub_id can happen out-of-order, the thread that frees a given gco can be for any later event group, not necessarily an event group from the gco being freed. */ struct group_commit_orderer { /* Wakeup condition, used with rpl_parallel_entry::LOCK_parallel_entry. */ mysql_cond_t COND_group_commit_orderer; uint64 wait_count; group_commit_orderer *prev_gco; group_commit_orderer *next_gco; /* The sub_id of last event group in the previous GCO. Only valid if prev_gco != NULL. */ uint64 prior_sub_id; /* The sub_id of the last event group in this GCO. Only valid when next_gco is non-NULL. */ uint64 last_sub_id; /* This flag is set when this GCO has been installed into the next_gco pointer of the previous GCO. */ bool installed; enum force_switch_bits { /* This flag is set for a GCO in which we have event groups with multiple different commit_id values from the master. This happens when we optimistically try to execute in parallel transactions not known to be conflict-free. When this flag is set, in case of DDL we need to start a new GCO regardless of current commit_id, as DDL is not safe to speculatively apply in parallel with prior event groups. */ MULTI_BATCH= 1, /* This flag is set for a GCO that contains DDL. If set, it forces a switch to a new GCO upon seeing a new commit_id, as DDL is not safe to speculatively replicate in parallel with subsequent transactions. */ FORCE_SWITCH= 2 }; uint8 flags; #ifndef DBUG_OFF /* Flag set when the GCO has been freed and entered the free list, to catch (in debug) errors in the complex lifetime of this object. */ bool gc_done; #endif }; struct rpl_parallel_thread { bool delay_start; bool running; bool stop; bool pause_for_ftwrl; mysql_mutex_t LOCK_rpl_thread; mysql_cond_t COND_rpl_thread; mysql_cond_t COND_rpl_thread_queue; mysql_cond_t COND_rpl_thread_stop; struct rpl_parallel_thread *next; /* For free list. */ struct rpl_parallel_thread_pool *pool; THD *thd; /* Who owns the thread, if any (it's a pointer into the rpl_parallel_entry::rpl_threads array. */ struct rpl_parallel_thread **current_owner; /* The rpl_parallel_entry of the owner. */ rpl_parallel_entry *current_entry; struct queued_event { queued_event *next; /* queued_event can hold either an event to be executed, or just a binlog position to be updated without any associated event. */ enum queued_event_t { QUEUED_EVENT, QUEUED_POS_UPDATE, QUEUED_MASTER_RESTART } typ; union { Log_event *ev; /* QUEUED_EVENT */ rpl_parallel_entry *entry_for_queued; /* QUEUED_POS_UPDATE and QUEUED_MASTER_RESTART */ }; rpl_group_info *rgi; inuse_relaylog *ir; ulonglong future_event_relay_log_pos; char event_relay_log_name[FN_REFLEN]; char future_event_master_log_name[FN_REFLEN]; ulonglong event_relay_log_pos; my_off_t future_event_master_log_pos; size_t event_size; } *event_queue, *last_in_queue; uint64 queued_size; /* These free lists are protected by LOCK_rpl_thread. */ queued_event *qev_free_list; rpl_group_info *rgi_free_list; group_commit_orderer *gco_free_list; /* These free lists are local to the thread, so need not be protected by any lock. They are moved to the global free lists in batches in the function batch_free(), to reduce LOCK_rpl_thread contention. The lists are not NULL-terminated (as we do not need to traverse them). Instead, if they are non-NULL, the loc_XXX_last_ptr_ptr points to the `next' pointer of the last element, which is used to link into the front of the global freelists. */ queued_event *loc_qev_list, **loc_qev_last_ptr_ptr; size_t loc_qev_size; uint64 qev_free_pending; rpl_group_info *loc_rgi_list, **loc_rgi_last_ptr_ptr; group_commit_orderer *loc_gco_list, **loc_gco_last_ptr_ptr; /* These keep track of batch update of inuse_relaylog refcounts. */ inuse_relaylog *accumulated_ir_last; uint64 accumulated_ir_count; char channel_name[MAX_CONNECTION_NAME]; uint channel_name_length; rpl_gtid last_seen_gtid; int last_error_number; char last_error_message[MAX_SLAVE_ERRMSG]; ulonglong last_error_timestamp; ulonglong worker_idle_time; ulong last_trans_retry_count; ulonglong start_time; void start_time_tracker() { start_time= microsecond_interval_timer(); } ulonglong compute_time_lapsed() { return (ulonglong)((microsecond_interval_timer() - start_time) / 1000000.0); } void add_to_worker_idle_time_and_reset() { worker_idle_time+= compute_time_lapsed(); start_time=0; } ulonglong get_worker_idle_time() { if (start_time) return (worker_idle_time + compute_time_lapsed()); else return worker_idle_time; } void enqueue(queued_event *qev) { if (last_in_queue) last_in_queue->next= qev; else event_queue= qev; last_in_queue= qev; queued_size+= qev->event_size; } void dequeue1(queued_event *list) { DBUG_ASSERT(list == event_queue); event_queue= last_in_queue= NULL; } void dequeue2(size_t dequeue_size) { queued_size-= dequeue_size; } queued_event *get_qev_common(Log_event *ev, ulonglong event_size); queued_event *get_qev(Log_event *ev, ulonglong event_size, Relay_log_info *rli); queued_event *retry_get_qev(Log_event *ev, queued_event *orig_qev, const char *relay_log_name, ulonglong event_pos, ulonglong event_size); /* Put a qev on the local free list, to be later released to the global free list by batch_free(). */ void loc_free_qev(queued_event *qev); /* Release an rgi immediately to the global free list. Requires holding the LOCK_rpl_thread mutex. */ void free_qev(queued_event *qev); rpl_group_info *get_rgi(Relay_log_info *rli, Gtid_log_event *gtid_ev, rpl_parallel_entry *e, ulonglong event_size); /* Put an gco on the local free list, to be later released to the global free list by batch_free(). */ void loc_free_rgi(rpl_group_info *rgi); /* Release an rgi immediately to the global free list. Requires holding the LOCK_rpl_thread mutex. */ void free_rgi(rpl_group_info *rgi); group_commit_orderer *get_gco(uint64 wait_count, group_commit_orderer *prev, uint64 first_sub_id); /* Put a gco on the local free list, to be later released to the global free list by batch_free(). */ void loc_free_gco(group_commit_orderer *gco); /* Move all local free lists to the global ones. Requires holding LOCK_rpl_thread. */ void batch_free(); /* Update inuse_relaylog refcounts with what we have accumulated so far. */ void inuse_relaylog_refcount_update(); rpl_parallel_thread(); }; struct pool_bkp_for_pfs{ uint32 count; bool inited, is_valid; struct rpl_parallel_thread **rpl_thread_arr; void init(uint32 thd_count) { DBUG_ASSERT(thd_count); rpl_thread_arr= (rpl_parallel_thread **) my_malloc(PSI_INSTRUMENT_ME, thd_count * sizeof(rpl_parallel_thread*), MYF(MY_WME | MY_ZEROFILL)); for (uint i=0; i *thread_sched_fifo; uint32 rpl_thread_max; /* Keep track of all XA XIDs that may still be active in a worker thread. The elements are of type xid_active_generation. */ DYNAMIC_ARRAY maybe_active_xid; /* Keeping track of the current scheduling generation. A new generation means that every worker thread in the rpl_threads array have been scheduled at least one event group. When we have scheduled to slot current_generation_idx= 0, 1, ..., N-1 in this order, we know that (at least) one generation has passed. */ uint64 current_generation; uint32 current_generation_idx; /* The sub_id of the last transaction to commit within this domain_id. Must be accessed under LOCK_parallel_entry protection. Event groups commit in order, so the rpl_group_info for an event group will be alive (at least) as long as rpl_group_info::gtid_sub_id > last_committed_sub_id. This can be used to safely refer back to previous event groups if they are still executing, and ignore them if they completed, without requiring explicit synchronisation between the threads. */ uint64 last_committed_sub_id; /* The sub_id of the last event group in this replication domain that was queued for execution by a worker thread. */ uint64 current_sub_id; /* The largest sub_id that has started its transaction. Protected by LOCK_parallel_entry. (Transactions can start out-of-order, so this value signifies that no transactions with larger sub_id have started, but not necessarily that all transactions with smaller sub_id have started). */ uint64 largest_started_sub_id; rpl_group_info *current_group_info; /* If we get an error in some event group, we set the sub_id of that event group here. Then later event groups (with higher sub_id) can know not to try to start (event groups that already started will be rolled back when wait_for_prior_commit() returns error). The value is ULONGLONG_MAX when no error occurred. */ uint64 stop_on_error_sub_id; /* During FLUSH TABLES WITH READ LOCK, transactions with sub_id larger than this value must not start, but wait until the global read lock is released. The value is set to ULONGLONG_MAX when no FTWRL is pending. */ uint64 pause_sub_id; /* Total count of event groups queued so far. */ uint64 count_queued_event_groups; /* Count of event groups that have started (but not necessarily completed) the commit phase. We use this to know when every event group in a previous batch of master group commits have started committing on the slave, so that it is safe to start executing the events in the following batch. */ uint64 count_committing_event_groups; /* The group_commit_orderer object for the events currently being queued. */ group_commit_orderer *current_gco; void check_scheduling_generation(sched_bucket *cur); sched_bucket *check_xa_xid_dependency(xid_t *xid); rpl_parallel_thread * choose_thread(rpl_group_info *rgi, bool *did_enter_cond, PSI_stage_info *old_stage, Gtid_log_event *gtid_ev); int queue_master_restart(rpl_group_info *rgi, Format_description_log_event *fdev); /* the initial size of maybe_ array corresponds to the case of each worker receives perhaps unlikely XA-PREPARE and XA-COMMIT within the same generation. */ inline uint active_xid_init_alloc() { return 3 * 2 * rpl_thread_max; } }; struct rpl_parallel { HASH domain_hash; rpl_parallel_entry *current; bool sql_thread_stopping; rpl_parallel(); ~rpl_parallel(); void reset(); rpl_parallel_entry *find(uint32 domain_id); void wait_for_done(THD *thd, Relay_log_info *rli); void stop_during_until(); int wait_for_workers_idle(THD *thd); int do_event(rpl_group_info *serial_rgi, Log_event *ev, ulonglong event_size); static bool workers_idle(Relay_log_info *rli); }; extern struct rpl_parallel_thread_pool global_rpl_thread_pool; extern void wait_for_pending_deadlock_kill(THD *thd, rpl_group_info *rgi); extern int rpl_parallel_resize_pool_if_no_slaves(void); extern int rpl_parallel_activate_pool(rpl_parallel_thread_pool *pool); extern int rpl_parallel_inactivate_pool(rpl_parallel_thread_pool *pool); extern bool process_gtid_for_restart_pos(Relay_log_info *rli, rpl_gtid *gtid); extern int rpl_pause_for_ftwrl(THD *thd); extern void rpl_unpause_after_ftwrl(THD *thd); #endif /* RPL_PARALLEL_H */ mysql/server/private/bounded_queue.h000064400000013715151027430560013700 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef BOUNDED_QUEUE_INCLUDED #define BOUNDED_QUEUE_INCLUDED #include "my_base.h" #include #include "queues.h" #include class Sort_param; /** A priority queue with a fixed, limited size. This is a wrapper on top of QUEUE and the queue_xxx() functions. It keeps the top-N elements which are inserted. Elements of type Element_type are pushed into the queue. For each element, we call a user-supplied keymaker_function, to generate a key of type Key_type for the element. Instances of Key_type are compared with the user-supplied compare_function. The underlying QUEUE implementation needs one extra element for replacing the lowest/highest element when pushing into a full queue. */ template class Bounded_queue { public: Bounded_queue() { memset(&m_queue, 0, sizeof(m_queue)); } ~Bounded_queue() { delete_queue(&m_queue); } /** Function for making sort-key from input data. @param param Sort parameters. @param to Where to put the key. @param from The input data. */ typedef uint (*keymaker_function)(Sort_param *param, Key_type *to, Element_type *from, bool packing_keys); /** Initialize the queue. @param max_elements The size of the queue. @param max_at_top Set to true if you want biggest element on top. false: We keep the n largest elements. pop() will return the smallest key in the result set. true: We keep the n smallest elements. pop() will return the largest key in the result set. @param compare_length Length of the data (i.e. the keys) used for sorting. @param keymaker Function which generates keys for elements. @param sort_param Sort parameters. @param sort_keys Array of pointers to keys to sort. @retval 0 OK, 1 Could not allocate memory. We do *not* take ownership of any of the input pointer arguments. */ int init(ha_rows max_elements, bool max_at_top, size_t compare_length, keymaker_function keymaker, Sort_param *sort_param, Key_type **sort_keys); /** Pushes an element on the queue. If the queue is already full, we discard one element. Calls keymaker_function to generate a key for the element. @param element The element to be pushed. */ void push(Element_type *element); /** Removes the top element from the queue. @retval Pointer to the (key of the) removed element. @note This function is for unit testing, where we push elements into to the queue, and test that the appropriate keys are retained. Interleaving of push() and pop() operations has not been tested. */ Key_type **pop() { // Don't return the extra element to the client code. if (queue_is_full((&m_queue))) queue_remove(&m_queue, 0); DBUG_ASSERT(m_queue.elements > 0); if (m_queue.elements == 0) return NULL; return reinterpret_cast(queue_remove(&m_queue, 0)); } /** The number of elements in the queue. */ uint num_elements() const { return m_queue.elements; } /** Is the queue initialized? */ bool is_initialized() const { return m_queue.max_elements > 0; } private: Key_type **m_sort_keys; size_t m_compare_length; keymaker_function m_keymaker; Sort_param *m_sort_param; st_queue m_queue; }; template int Bounded_queue::init(ha_rows max_elements, bool max_at_top, size_t compare_length, keymaker_function keymaker, Sort_param *sort_param, Key_type **sort_keys) { DBUG_ASSERT(sort_keys != NULL); m_sort_keys= sort_keys; m_compare_length= compare_length; m_keymaker= keymaker; m_sort_param= sort_param; // init_queue() takes an uint, and also does (max_elements + 1) if (max_elements >= (UINT_MAX - 1)) return 1; // We allocate space for one extra element, for replace when queue is full. return init_queue(&m_queue, (uint) max_elements + 1, 0, max_at_top, get_ptr_compare(compare_length), &m_compare_length, 0, 0); } template void Bounded_queue::push(Element_type *element) { DBUG_ASSERT(is_initialized()); if (queue_is_full((&m_queue))) { // Replace top element with new key, and re-order the queue. Key_type **pq_top= reinterpret_cast(queue_top(&m_queue)); (void)(*m_keymaker)(m_sort_param, *pq_top, element, false); queue_replace_top(&m_queue); } else { // Insert new key into the queue. (*m_keymaker)(m_sort_param, m_sort_keys[m_queue.elements], element, false); queue_insert(&m_queue, reinterpret_cast(&m_sort_keys[m_queue.elements])); } } #endif // BOUNDED_QUEUE_INCLUDED mysql/server/private/sql_hset.h000064400000006511151027430560012672 0ustar00#ifndef SQL_HSET_INCLUDED #define SQL_HSET_INCLUDED /* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #include "my_global.h" #include "hash.h" /** A type-safe wrapper around mysys HASH. */ template class Hash_set { public: enum { START_SIZE= 8 }; /** Constructs an empty unique hash. */ Hash_set(PSI_memory_key psi_key, const uchar *(*K)(const void *, size_t *, my_bool), CHARSET_INFO *cs= &my_charset_bin) { my_hash_init(psi_key, &m_hash, cs, START_SIZE, 0, 0, K, 0, HASH_UNIQUE); } Hash_set(PSI_memory_key psi_key, CHARSET_INFO *charset, ulong default_array_elements, size_t key_offset, size_t key_length, my_hash_get_key get_key, void (*free_element)(void*), uint flags) { my_hash_init(psi_key, &m_hash, charset, default_array_elements, key_offset, key_length, get_key, free_element, flags); } /** Destroy the hash by freeing the buckets table. Does not call destructors for the elements. */ ~Hash_set() { my_hash_free(&m_hash); } /** Insert a single value into a hash. Does not tell whether the value was inserted -- if an identical value existed, it is not replaced. @retval TRUE Out of memory. @retval FALSE OK. The value either was inserted or existed in the hash. */ bool insert(T *value) { return my_hash_insert(&m_hash, reinterpret_cast(value)); } bool remove(T *value) { return my_hash_delete(&m_hash, reinterpret_cast(value)); } T *find(const void *key, size_t klen) const { return (T*)my_hash_search(&m_hash, reinterpret_cast(key), klen); } /** Is this hash set empty? */ bool is_empty() const { return m_hash.records == 0; } /** Returns the number of unique elements. */ size_t size() const { return static_cast(m_hash.records); } /** Erases all elements from the container */ void clear() { my_hash_reset(&m_hash); } const T* at(size_t i) const { return reinterpret_cast(my_hash_element(const_cast(&m_hash), i)); } /** An iterator over hash elements. Is not insert-stable. */ class Iterator { public: Iterator(Hash_set &hash_set) : m_hash(&hash_set.m_hash), m_idx(0) {} /** Return the current element and reposition the iterator to the next element. */ inline T *operator++(int) { if (m_idx < m_hash->records) return reinterpret_cast(my_hash_element(m_hash, m_idx++)); return NULL; } void rewind() { m_idx= 0; } private: HASH *m_hash; uint m_idx; }; private: HASH m_hash; }; #endif // SQL_HSET_INCLUDED mysql/server/private/item_xmlfunc.h000064400000010777151027430560013553 0ustar00#ifndef ITEM_XMLFUNC_INCLUDED #define ITEM_XMLFUNC_INCLUDED /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2009, 2019, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file defines all XML functions */ typedef struct my_xml_node_st MY_XML_NODE; /* Structure to store nodeset elements */ class MY_XPATH_FLT { public: uint num; // Absolute position in MY_XML_NODE array uint pos; // Relative position in context uint size; // Context size public: MY_XPATH_FLT(uint32 num_arg, uint32 pos_arg) :num(num_arg), pos(pos_arg), size(0) { } MY_XPATH_FLT(uint32 num_arg, uint32 pos_arg, uint32 size_arg) :num(num_arg), pos(pos_arg), size(size_arg) { } bool append_to(Native *to) const { return to->append((const char*) this, (uint32) sizeof(*this)); } }; class NativeNodesetBuffer: public NativeBuffer<16*sizeof(MY_XPATH_FLT)> { public: const MY_XPATH_FLT &element(uint i) const { const MY_XPATH_FLT *p= (MY_XPATH_FLT*) (ptr() + i * sizeof(MY_XPATH_FLT)); return *p; } uint32 elements() const { return length() / sizeof(MY_XPATH_FLT); } }; class Item_xml_str_func: public Item_str_func { protected: /* A helper class to store raw and parsed XML. */ class XML { bool m_cached; String *m_raw_ptr; // Pointer to text representation String m_raw_buf; // Cached text representation String m_parsed_buf; // Array of MY_XML_NODEs, pointing to raw_buffer bool parse(); void reset() { m_cached= false; m_raw_ptr= (String *) 0; } public: XML() { reset(); } void set_charset(CHARSET_INFO *cs) { m_parsed_buf.set_charset(cs); } String *raw() { return m_raw_ptr; } String *parsed() { return &m_parsed_buf; } const MY_XML_NODE *node(uint idx); bool cached() { return m_cached; } bool parse(String *raw, bool cache); bool parse(Item *item, bool cache) { String *res; if (!(res= item->val_str(&m_raw_buf))) { m_raw_ptr= (String *) 0; m_cached= cache; return true; } return parse(res, cache); } }; String m_xpath_query; // XPath query text Item *nodeset_func; XML xml; bool get_xml(XML *xml_arg, bool cache= false) { if (!cache && xml_arg->cached()) return xml_arg->raw() == 0; return xml_arg->parse(args[0], cache); } public: Item_xml_str_func(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) { set_maybe_null(); } Item_xml_str_func(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c) { set_maybe_null(); } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; bool const_item() const override { return const_item_cache && (!nodeset_func || nodeset_func->const_item()); } }; class Item_func_xml_extractvalue: public Item_xml_str_func { public: Item_func_xml_extractvalue(THD *thd, Item *a, Item *b): Item_xml_str_func(thd, a, b) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("extractvalue") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_xml_update: public Item_xml_str_func { NativeNodesetBuffer tmp_native_value2; String tmp_value3; bool collect_result(String *str, const MY_XML_NODE *cut, const String *replace); public: Item_func_xml_update(THD *thd, Item *a, Item *b, Item *c): Item_xml_str_func(thd, a, b, c) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("updatexml") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #endif /* ITEM_XMLFUNC_INCLUDED */ mysql/server/private/partition_element.h000064400000012131151027430560014565 0ustar00#ifndef PARTITION_ELEMENT_INCLUDED #define PARTITION_ELEMENT_INCLUDED /* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "my_base.h" /* ha_rows */ #include "handler.h" /* UNDEF_NODEGROUP */ /** * An enum and a struct to handle partitioning and subpartitioning. */ enum partition_type { NOT_A_PARTITION= 0, RANGE_PARTITION, HASH_PARTITION, LIST_PARTITION, VERSIONING_PARTITION }; enum partition_state { PART_NORMAL= 0, PART_IS_DROPPED= 1, PART_TO_BE_DROPPED= 2, PART_TO_BE_ADDED= 3, PART_TO_BE_REORGED= 4, PART_REORGED_DROPPED= 5, PART_CHANGED= 6, PART_IS_CHANGED= 7, PART_IS_ADDED= 8, PART_ADMIN= 9 }; /* This struct is used to keep track of column expressions as part of the COLUMNS concept in conjunction with RANGE and LIST partitioning. The value can be either of MINVALUE, MAXVALUE and an expression that must be constant and evaluate to the same type as the column it represents. The data in this fixed in two steps. The parser will only fill in whether it is a max_value or provide an expression. Filling in column_value, part_info, partition_id, null_value is done by the function fix_column_value_function. However the item tree needs fixed also before writing it into the frm file (in add_column_list_values). To distinguish between those two variants, fixed= 1 after the fixing in add_column_list_values and fixed= 2 otherwise. This is since the fixing in add_column_list_values isn't a complete fixing. */ typedef struct p_column_list_val { void* column_value; Item* item_expression; partition_info *part_info; uint partition_id; bool max_value; // MAXVALUE for RANGE type or DEFAULT value for LIST type bool null_value; char fixed; } part_column_list_val; /* This struct is used to contain the value of an element in the VALUES IN struct. It needs to keep knowledge of whether it is a signed/unsigned value and whether it is NULL or not. */ typedef struct p_elem_val { longlong value; uint added_items; bool null_value; bool unsigned_flag; part_column_list_val *col_val_array; } part_elem_value; struct st_ddl_log_memory_entry; enum stat_trx_field { STAT_TRX_END= 0 }; class partition_element :public Sql_alloc { public: enum elem_type_enum { CONVENTIONAL= 0, CURRENT, HISTORY }; List subpartitions; List list_val_list; ha_rows part_max_rows; ha_rows part_min_rows; longlong range_value; const char *partition_name; const char *tablespace_name; struct st_ddl_log_memory_entry *log_entry; const char* part_comment; const char* data_file_name; const char* index_file_name; handlerton *engine_type; LEX_CSTRING connect_string; enum partition_state part_state; uint16 nodegroup_id; bool has_null_value; bool signed_flag; // Range value signed bool max_value; // MAXVALUE range uint32 id; bool empty; elem_type_enum type; partition_element() : part_max_rows(0), part_min_rows(0), range_value(0), partition_name(NULL), tablespace_name(NULL), log_entry(NULL), part_comment(NULL), data_file_name(NULL), index_file_name(NULL), engine_type(NULL), connect_string(null_clex_str), part_state(PART_NORMAL), nodegroup_id(UNDEF_NODEGROUP), has_null_value(FALSE), signed_flag(FALSE), max_value(FALSE), id(UINT_MAX32), empty(true), type(CONVENTIONAL) {} partition_element(partition_element *part_elem) : part_max_rows(part_elem->part_max_rows), part_min_rows(part_elem->part_min_rows), range_value(0), partition_name(NULL), tablespace_name(part_elem->tablespace_name), log_entry(NULL), part_comment(part_elem->part_comment), data_file_name(part_elem->data_file_name), index_file_name(part_elem->index_file_name), engine_type(part_elem->engine_type), connect_string(null_clex_str), part_state(part_elem->part_state), nodegroup_id(part_elem->nodegroup_id), has_null_value(FALSE), signed_flag(part_elem->signed_flag), max_value(part_elem->max_value), id(part_elem->id), empty(part_elem->empty), type(CONVENTIONAL) {} ~partition_element() = default; part_column_list_val& get_col_val(uint idx) { part_elem_value *ev= list_val_list.head(); DBUG_ASSERT(ev); DBUG_ASSERT(ev->col_val_array); return ev->col_val_array[idx]; } }; #endif /* PARTITION_ELEMENT_INCLUDED */ mysql/server/private/wsrep_trans_observer.h000064400000043307151027430560015332 0ustar00/* Copyright 2016-2025 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef WSREP_TRANS_OBSERVER_H #define WSREP_TRANS_OBSERVER_H #include "my_global.h" #include "mysql/service_wsrep.h" #include "wsrep_applier.h" /* wsrep_apply_error */ #include "wsrep_xid.h" #include "wsrep_thd.h" #include "wsrep_binlog.h" /* register/deregister group commit */ #include "my_dbug.h" class THD; void wsrep_commit_empty(THD* thd, bool all); /* Return true if THD has active wsrep transaction. */ static inline bool wsrep_is_active(THD* thd) { return (thd->wsrep_cs().state() != wsrep::client_state::s_none && thd->wsrep_cs().transaction().active() && !thd->internal_transaction()); } /* Return true if transaction is ordered. */ static inline bool wsrep_is_ordered(THD* thd) { return thd->wsrep_trx().ordered(); } /* Return true if transaction has been BF aborted but has not been rolled back yet. It is required that the caller holds thd->LOCK_thd_data. */ static inline bool wsrep_must_abort(THD* thd) { mysql_mutex_assert_owner(&thd->LOCK_thd_data); return (thd->wsrep_trx().state() == wsrep::transaction::s_must_abort); } /* Return true if the transaction must be replayed. */ static inline bool wsrep_must_replay(THD* thd) { return (thd->wsrep_trx().state() == wsrep::transaction::s_must_replay); } /* Return true if transaction has not been committed. Note that we don't require thd->LOCK_thd_data here. Calling this method makes sense only from codepaths which are past ordered_commit state and the wsrep transaction is immune to BF aborts at that point. */ static inline bool wsrep_not_committed(THD* thd) { return (thd->wsrep_trx().state() != wsrep::transaction::s_committed); } /* Return true if THD is either committing a transaction or statement is autocommit. */ static inline bool wsrep_is_real(THD* thd, bool all) { return (all || thd->transaction->all.ha_list == 0); } /* Check if a transaction has generated changes. */ static inline bool wsrep_has_changes(THD* thd) { // Transaction has changes to replicate if it // has appended one or more certification keys, // and has actual changes to replicate in binlog // cache. Except for streaming replication, // where commit message may have no payload. return !thd->wsrep_trx().is_empty() && (!wsrep_is_binlog_cache_empty(thd) || thd->wsrep_trx().is_streaming()); } /* Check if an active transaction has been BF aborted. */ static inline bool wsrep_is_bf_aborted(THD* thd) { return (thd->wsrep_trx().active() && thd->wsrep_trx().bf_aborted()); } static inline int wsrep_check_pk(THD* thd) { if (!wsrep_certify_nonPK) { for (TABLE* table= thd->open_tables; table != NULL; table= table->next) { if (table->key_info == NULL || table->s->primary_key == MAX_KEY) { WSREP_DEBUG("No primary key found for table %s.%s", table->s->db.str, table->s->table_name.str); wsrep_override_error(thd, ER_LOCK_DEADLOCK); return 1; } } } return 0; } static inline bool wsrep_streaming_enabled(THD* thd) { return (thd->wsrep_sr().fragment_size() > 0); } /* Return number of fragments successfully certified for the current statement. */ static inline size_t wsrep_fragments_certified_for_stmt(THD* thd) { return thd->wsrep_trx().fragments_certified_for_statement(); } static inline int wsrep_start_transaction(THD* thd, wsrep_trx_id_t trx_id) { if (thd->wsrep_cs().state() != wsrep::client_state::s_none) { if (wsrep_is_active(thd) == false) return thd->wsrep_cs().start_transaction(wsrep::transaction_id(trx_id)); } return 0; } /**/ static inline int wsrep_start_trx_if_not_started(THD* thd) { int ret= 0; DBUG_ASSERT(thd->wsrep_next_trx_id() != WSREP_UNDEFINED_TRX_ID); DBUG_ASSERT(thd->wsrep_cs().mode() == Wsrep_client_state::m_local); if (thd->wsrep_trx().active() == false) { ret= wsrep_start_transaction(thd, thd->wsrep_next_trx_id()); } return ret; } /* Called after each row operation. Return zero on succes, non-zero on failure. */ static inline int wsrep_after_row_internal(THD* thd) { if (thd->wsrep_cs().state() != wsrep::client_state::s_none && wsrep_thd_is_local(thd)) { if (wsrep_check_pk(thd)) { return 1; } else if (wsrep_streaming_enabled(thd)) { return thd->wsrep_cs().after_row(); } } return 0; } /* Helper method to determine whether commit time hooks should be run for the transaction. Commit hooks must be run in the following cases: - The transaction is local and has generated write set and is committing. - The transaction has been BF aborted - Is running in high priority mode and is ordered. This can be replayer, applier or storage access. */ static inline bool wsrep_run_commit_hook(THD* thd, bool all) { DBUG_ENTER("wsrep_run_commit_hook"); DBUG_PRINT("wsrep", ("Is_active: %d is_real %d has_changes %d is_applying %d " "is_ordered: %d", wsrep_is_active(thd), wsrep_is_real(thd, all), wsrep_has_changes(thd), wsrep_thd_is_applying(thd), wsrep_is_ordered(thd))); /* skipping non-wsrep threads */ if (!WSREP(thd)) DBUG_RETURN(false); /* Is MST commit or autocommit? */ bool ret= wsrep_is_active(thd) && wsrep_is_real(thd, all); /* Do not commit if we are aborting */ ret= ret && (thd->wsrep_trx().state() != wsrep::transaction::s_aborting); if (ret && !(wsrep_has_changes(thd) || /* Has generated write set */ /* Is high priority (replay, applier, storage) and the transaction is scheduled for commit ordering */ (wsrep_thd_is_applying(thd) && wsrep_is_ordered(thd)))) { mysql_mutex_lock(&thd->LOCK_thd_data); DBUG_PRINT("wsrep", ("state: %s", wsrep::to_c_string(thd->wsrep_trx().state()))); /* Transaction is local but has no changes, the commit hooks will be skipped and the wsrep transaction is terminated in wsrep_commit_empty() */ if (thd->wsrep_trx().state() == wsrep::transaction::s_executing) { ret= false; } mysql_mutex_unlock(&thd->LOCK_thd_data); } mysql_mutex_lock(&thd->LOCK_thd_data); /* Transaction creating sequence is TOI or RSU, CREATE SEQUENCE = CREATE + INSERT (initial value) and replicated using statement based replication, thus the commit hooks will be skipped. For TEMPORARY SEQUENCES commit hooks will be done as CREATE + INSERT is not replicated and needs to be committed locally. */ if (ret && (thd->wsrep_cs().mode() == wsrep::client_state::m_toi || thd->wsrep_cs().mode() == wsrep::client_state::m_rsu) && thd->lex->sql_command == SQLCOM_CREATE_SEQUENCE && !thd->lex->tmp_table()) ret= false; mysql_mutex_unlock(&thd->LOCK_thd_data); DBUG_PRINT("wsrep", ("return: %d", ret)); DBUG_RETURN(ret); } /* Called before the transaction is prepared. Return zero on succes, non-zero on failure. */ static inline int wsrep_before_prepare(THD* thd, bool all) { DBUG_ENTER("wsrep_before_prepare"); WSREP_DEBUG("wsrep_before_prepare: %d", wsrep_is_real(thd, all)); int ret= 0; DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); if ((ret= thd->wsrep_parallel_slave_wait_for_prior_commit())) { DBUG_RETURN(ret); } if ((ret= thd->wsrep_cs().before_prepare()) == 0) { DBUG_ASSERT(!thd->wsrep_trx().ws_meta().gtid().is_undefined()); /* Here we init xid with UUID and wsrep seqno. GTID is set to undefined because commit order is decided later in wsrep_before_commit(). wsrep_before_prepare() is executed out of order. */ wsrep_xid_init(&thd->wsrep_xid, thd->wsrep_trx().ws_meta().gtid(), wsrep_gtid_server.undefined()); } mysql_mutex_lock(&thd->LOCK_thd_kill); if (thd->killed) wsrep_backup_kill_for_commit(thd); mysql_mutex_unlock(&thd->LOCK_thd_kill); DBUG_RETURN(ret); } /* Called after the transaction has been prepared. Return zero on succes, non-zero on failure. */ static inline int wsrep_after_prepare(THD* thd, bool all) { DBUG_ENTER("wsrep_after_prepare"); WSREP_DEBUG("wsrep_after_prepare: %d", wsrep_is_real(thd, all)); DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); int ret= thd->wsrep_cs().after_prepare(); DBUG_ASSERT(ret == 0 || thd->wsrep_cs().current_error() || thd->wsrep_cs().transaction().state() == wsrep::transaction::s_must_replay); DBUG_RETURN(ret); } /* Called before the transaction is committed. This function must be called from both client and applier contexts before commit. Return zero on succes, non-zero on failure. */ static inline int wsrep_before_commit(THD* thd, bool all) { DBUG_ENTER("wsrep_before_commit"); WSREP_DEBUG("wsrep_before_commit: %d, %lld", wsrep_is_real(thd, all), (long long)wsrep_thd_trx_seqno(thd)); int ret= 0; DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); if ((ret= thd->wsrep_cs().before_commit()) == 0) { DBUG_ASSERT(!thd->wsrep_trx().ws_meta().gtid().is_undefined()); if (!thd->variables.gtid_seq_no && (thd->wsrep_trx().ws_meta().flags() & wsrep::provider::flag::commit)) { uint64 seqno= 0; if (thd->variables.wsrep_gtid_seq_no && thd->variables.wsrep_gtid_seq_no > wsrep_gtid_server.seqno()) { seqno= thd->variables.wsrep_gtid_seq_no; wsrep_gtid_server.seqno(thd->variables.wsrep_gtid_seq_no); } else { seqno= wsrep_gtid_server.seqno_inc(); } thd->variables.wsrep_gtid_seq_no= 0; thd->wsrep_current_gtid_seqno= seqno; if (mysql_bin_log.is_open() && wsrep_gtid_mode) { thd->variables.gtid_seq_no= seqno; thd->variables.gtid_domain_id= wsrep_gtid_server.domain_id; thd->variables.server_id= wsrep_gtid_server.server_id; } } wsrep_xid_init(&thd->wsrep_xid, thd->wsrep_trx().ws_meta().gtid(), wsrep_gtid_server.gtid()); wsrep_register_for_group_commit(thd); } mysql_mutex_lock(&thd->LOCK_thd_kill); if (thd->killed) wsrep_backup_kill_for_commit(thd); mysql_mutex_unlock(&thd->LOCK_thd_kill); DBUG_RETURN(ret); } /* Called after the transaction has been ordered for commit. This function must be called from both client and applier contexts after the commit has been ordered. @param thd Pointer to THD @param all @param err Error buffer in case of applying error Return zero on succes, non-zero on failure. */ static inline int wsrep_ordered_commit(THD* thd, bool all) { DBUG_ENTER("wsrep_ordered_commit"); WSREP_DEBUG("wsrep_ordered_commit: %d %lld", wsrep_is_real(thd, all), (long long) wsrep_thd_trx_seqno(thd)); DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); DBUG_RETURN(thd->wsrep_cs().ordered_commit()); } /* Called after the transaction has been committed. Return zero on succes, non-zero on failure. */ static inline int wsrep_after_commit(THD* thd, bool all) { DBUG_ENTER("wsrep_after_commit"); WSREP_DEBUG("wsrep_after_commit: %d, %d, %lld, %d", wsrep_is_real(thd, all), wsrep_is_active(thd), (long long)wsrep_thd_trx_seqno(thd), wsrep_has_changes(thd)); DBUG_ASSERT(wsrep_run_commit_hook(thd, all)); if (thd->internal_transaction()) DBUG_RETURN(0); int ret= 0; if (thd->wsrep_trx().state() == wsrep::transaction::s_committing) { ret= thd->wsrep_cs().ordered_commit(); } wsrep_unregister_from_group_commit(thd); thd->wsrep_xid.null(); DBUG_RETURN(ret || thd->wsrep_cs().after_commit()); } /* Called before the transaction is rolled back. Return zero on succes, non-zero on failure. */ static inline int wsrep_before_rollback(THD* thd, bool all) { DBUG_ENTER("wsrep_before_rollback"); int ret= 0; if (wsrep_is_active(thd)) { if (!all && thd->in_active_multi_stmt_transaction()) { if (wsrep_emulate_bin_log) { wsrep_thd_binlog_stmt_rollback(thd); } if (thd->wsrep_trx().is_streaming() && (wsrep_fragments_certified_for_stmt(thd) > 0)) { /* Non-safe statement rollback during SR multi statement transaction. A statement rollback is considered unsafe, if the same statement has already replicated one or more fragments. Self abort the transaction, the actual rollback and error handling will be done in after statement phase. */ WSREP_DEBUG("statement rollback is not safe for streaming replication"); wsrep_thd_self_abort(thd); ret= 0; } } else if (wsrep_is_real(thd, all) && thd->wsrep_trx().state() != wsrep::transaction::s_aborted) { /* Real transaction rolling back and wsrep abort not completed yet */ /* Reset XID so that it does not trigger writing serialization history in InnoDB. This needs to be avoided because rollback may happen out of order and replay may follow. */ thd->wsrep_xid.null(); ret= thd->wsrep_cs().before_rollback(); } } DBUG_RETURN(ret); } /* Called after the transaction has been rolled back. Return zero on succes, non-zero on failure. */ static inline int wsrep_after_rollback(THD* thd, bool all) { DBUG_ENTER("wsrep_after_rollback"); DBUG_RETURN((wsrep_is_real(thd, all) && wsrep_is_active(thd) && thd->wsrep_cs().transaction().state() != wsrep::transaction::s_aborted) ? thd->wsrep_cs().after_rollback() : 0); } static inline int wsrep_before_statement(THD* thd) { return (thd->wsrep_cs().state() != wsrep::client_state::s_none && !thd->internal_transaction() ? thd->wsrep_cs().before_statement() : 0); } static inline int wsrep_after_statement(THD* thd) { DBUG_ENTER("wsrep_after_statement"); int ret= ((thd->wsrep_cs().state() != wsrep::client_state::s_none && thd->wsrep_cs().mode() == Wsrep_client_state::m_local) && !thd->internal_transaction() ? thd->wsrep_cs().after_statement() : 0); if (wsrep_is_active(thd)) { mysql_mutex_lock(&thd->LOCK_thd_kill); wsrep_restore_kill_after_commit(thd); mysql_mutex_unlock(&thd->LOCK_thd_kill); } DBUG_RETURN(ret); } static inline void wsrep_after_apply(THD* thd) { DBUG_ASSERT(wsrep_thd_is_applying(thd)); WSREP_DEBUG("wsrep_after_apply %lld", thd->thread_id); if (!thd->internal_transaction()) thd->wsrep_cs().after_applying(); } static inline void wsrep_open(THD* thd) { DBUG_ENTER("wsrep_open"); if (WSREP_ON_) { /* WSREP_PROVIDER_EXISTS_ cannot be set if WSREP_ON_ is not set */ DBUG_ASSERT(WSREP_PROVIDER_EXISTS_); thd->wsrep_cs().open(wsrep::client_id(thd->thread_id)); thd->wsrep_cs().debug_log_level(wsrep_debug); if (!thd->wsrep_applier && thd->variables.wsrep_trx_fragment_size) { thd->wsrep_cs().enable_streaming( wsrep_fragment_unit(thd->variables.wsrep_trx_fragment_unit), size_t(thd->variables.wsrep_trx_fragment_size)); } } DBUG_VOID_RETURN; } static inline void wsrep_close(THD* thd) { DBUG_ENTER("wsrep_close"); if (thd->wsrep_cs().state() != wsrep::client_state::s_none && !thd->internal_transaction()) { thd->wsrep_cs().close(); } DBUG_VOID_RETURN; } static inline void wsrep_cleanup(THD* thd) { DBUG_ENTER("wsrep_cleanup"); if (thd->wsrep_cs().state() != wsrep::client_state::s_none) { thd->wsrep_cs().cleanup(); } DBUG_VOID_RETURN; } static inline void wsrep_wait_rollback_complete_and_acquire_ownership(THD *thd) { DBUG_ENTER("wsrep_wait_rollback_complete_and_acquire_ownership"); if (thd->wsrep_cs().state() != wsrep::client_state::s_none && !thd->internal_transaction()) { thd->wsrep_cs().wait_rollback_complete_and_acquire_ownership(); } DBUG_VOID_RETURN; } static inline int wsrep_before_command(THD* thd, bool keep_command_error) { return (thd->wsrep_cs().state() != wsrep::client_state::s_none && !thd->internal_transaction() ? thd->wsrep_cs().before_command(keep_command_error) : 0); } static inline int wsrep_before_command(THD* thd) { return wsrep_before_command(thd, false); } /* Called after each command. Return zero on success, non-zero on failure. */ static inline void wsrep_after_command_before_result(THD* thd) { if (thd->wsrep_cs().state() != wsrep::client_state::s_none && !thd->internal_transaction()) { thd->wsrep_cs().after_command_before_result(); } } static inline void wsrep_after_command_after_result(THD* thd) { if (thd->wsrep_cs().state() != wsrep::client_state::s_none && !thd->internal_transaction()) { thd->wsrep_cs().after_command_after_result(); } } static inline void wsrep_after_command_ignore_result(THD* thd) { wsrep_after_command_before_result(thd); DBUG_ASSERT(!thd->wsrep_cs().current_error()); wsrep_after_command_after_result(thd); } static inline enum wsrep::client_error wsrep_current_error(THD* thd) { return thd->wsrep_cs().current_error(); } static inline enum wsrep::provider::status wsrep_current_error_status(THD* thd) { return thd->wsrep_cs().current_error_status(); } #endif /* WSREP_TRANS_OBSERVER */ mysql/server/private/rpl_filter.h000064400000010667151027430560013221 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_FILTER_H #define RPL_FILTER_H #include "mysql.h" #include "mysqld.h" #include "sql_list.h" /* I_List */ #include "hash.h" /* HASH */ class String; struct TABLE_LIST; typedef struct st_dynamic_array DYNAMIC_ARRAY; typedef struct st_table_rule_ent { char* db; char* tbl_name; uint key_len; } TABLE_RULE_ENT; /* Rpl_filter Inclusion and exclusion rules of tables and databases. Also handles rewrites of db. Used for replication and binlogging. */ class Rpl_filter { public: Rpl_filter(); ~Rpl_filter(); Rpl_filter(Rpl_filter const&); Rpl_filter& operator=(Rpl_filter const&); /* Checks - returns true if ok to replicate/log */ #ifndef MYSQL_CLIENT bool tables_ok(const char* db, TABLE_LIST *tables); #endif bool db_ok(const char* db); bool db_ok_with_wild_table(const char *db); bool is_on(); bool is_db_empty(); /* Setters - add filtering rules */ int add_do_table(const char* table_spec); int add_ignore_table(const char* table_spec); int set_do_table(const char* table_spec); int set_ignore_table(const char* table_spec); int add_wild_do_table(const char* table_spec); int add_wild_ignore_table(const char* table_spec); int set_wild_do_table(const char* table_spec); int set_wild_ignore_table(const char* table_spec); int add_do_db(const char* db_spec); int add_ignore_db(const char* db_spec); int set_do_db(const char* db_spec); int set_ignore_db(const char* db_spec); void set_parallel_mode(enum_slave_parallel_mode mode) { parallel_mode= mode; } /* Return given parallel mode or if one is not given, the default mode */ enum_slave_parallel_mode get_parallel_mode() { return parallel_mode; } void add_db_rewrite(const char* from_db, const char* to_db); /* Getters - to get information about current rules */ void get_do_table(String* str); void get_ignore_table(String* str); void get_wild_do_table(String* str); void get_wild_ignore_table(String* str); bool rewrite_db_is_empty(); const char* get_rewrite_db(const char* db, size_t *new_len); void copy_rewrite_db(Rpl_filter *from); I_List* get_do_db(); I_List* get_ignore_db(); void get_do_db(String* str); void get_ignore_db(String* str); private: void init_table_rule_hash(HASH* h, bool* h_inited); void init_table_rule_array(DYNAMIC_ARRAY* a, bool* a_inited); int add_table_rule(HASH* h, const char* table_spec); int add_wild_table_rule(DYNAMIC_ARRAY* a, const char* table_spec); typedef int (Rpl_filter::*Add_filter)(char const*); int parse_filter_rule(const char* spec, Add_filter func); void free_string_array(DYNAMIC_ARRAY *a); void free_string_list(I_List *l); void table_rule_ent_hash_to_str(String* s, HASH* h, bool inited); void table_rule_ent_dynamic_array_to_str(String* s, DYNAMIC_ARRAY* a, bool inited); void db_rule_ent_list_to_str(String* s, I_List* l); TABLE_RULE_ENT* find_wild(DYNAMIC_ARRAY *a, const char* key, int len); int add_string_list(I_List *list, const char* spec); /* Those 4 structures below are uninitialized memory unless the corresponding *_inited variables are "true". */ HASH do_table; HASH ignore_table; DYNAMIC_ARRAY wild_do_table; DYNAMIC_ARRAY wild_ignore_table; enum_slave_parallel_mode parallel_mode; bool table_rules_on; bool do_table_inited; bool ignore_table_inited; bool wild_do_table_inited; bool wild_ignore_table_inited; I_List do_db; I_List ignore_db; I_List rewrite_db; }; extern Rpl_filter *global_rpl_filter; extern Rpl_filter *binlog_filter; #endif // RPL_FILTER_H mysql/server/private/mysys_err.h000064400000005716151027430560013112 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _mysys_err_h #define _mysys_err_h #ifdef __cplusplus extern "C" { #endif #define GLOBERRS (EE_ERROR_LAST - EE_ERROR_FIRST + 1) /* Nr of global errors */ #define EE(X) (globerrs[(X) - EE_ERROR_FIRST]) extern const char *globerrs[]; /* my_error_messages is here */ /* Error message numbers in global map */ /* Do not add error numbers before EE_ERROR_FIRST. If necessary to add lower numbers, change EE_ERROR_FIRST accordingly. We start with error 1 to not confuse peoples with 'error 0' */ #define EE_ERROR_FIRST 1 /*Copy first error nr.*/ #define EE_CANTCREATEFILE 1 #define EE_READ 2 #define EE_WRITE 3 #define EE_BADCLOSE 4 #define EE_OUTOFMEMORY 5 #define EE_DELETE 6 #define EE_LINK 7 #define EE_EOFERR 9 #define EE_CANTLOCK 10 #define EE_CANTUNLOCK 11 #define EE_DIR 12 #define EE_STAT 13 #define EE_CANT_CHSIZE 14 #define EE_CANT_OPEN_STREAM 15 #define EE_GETWD 16 #define EE_SETWD 17 #define EE_LINK_WARNING 18 #define EE_OPEN_WARNING 19 #define EE_DISK_FULL 20 #define EE_CANT_MKDIR 21 #define EE_UNKNOWN_CHARSET 22 #define EE_OUT_OF_FILERESOURCES 23 #define EE_CANT_READLINK 24 #define EE_CANT_SYMLINK 25 #define EE_REALPATH 26 #define EE_SYNC 27 #define EE_UNKNOWN_COLLATION 28 #define EE_FILENOTFOUND 29 #define EE_FILE_NOT_CLOSED 30 #define EE_CHANGE_OWNERSHIP 31 #define EE_CHANGE_PERMISSIONS 32 #define EE_CANT_SEEK 33 #define EE_CANT_CHMOD 34 #define EE_CANT_COPY_OWNERSHIP 35 #define EE_BADMEMORYRELEASE 36 #define EE_PERM_LOCK_MEMORY 37 #define EE_MEMCNTL 38 #define EE_DUPLICATE_CHARSET 39 #define EE_ERROR_LAST 39 /* Copy last error nr */ /* Add error numbers before EE_ERROR_LAST and change it accordingly. */ /* exit codes for all MySQL programs */ #define EXIT_UNSPECIFIED_ERROR 1 #define EXIT_UNKNOWN_OPTION 2 #define EXIT_AMBIGUOUS_OPTION 3 #define EXIT_NO_ARGUMENT_ALLOWED 4 #define EXIT_ARGUMENT_REQUIRED 5 #define EXIT_VAR_PREFIX_NOT_UNIQUE 6 #define EXIT_UNKNOWN_VARIABLE 7 #define EXIT_OUT_OF_MEMORY 8 #define EXIT_UNKNOWN_SUFFIX 9 #define EXIT_NO_PTR_TO_VARIABLE 10 #define EXIT_CANNOT_CONNECT_TO_SERVICE 11 #define EXIT_OPTION_DISABLED 12 #define EXIT_ARGUMENT_INVALID 13 #ifdef __cplusplus } #endif #endif mysql/server/private/thr_timer.h000064400000003033151027430560013041 0ustar00/* Copyright (c) 2014 Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 or later of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Prototypes when using thr_timer functions */ #ifndef THR_TIMER_INCLUDED #define THR_TIMER_INCLUDED #ifdef __cplusplus extern "C" { #endif typedef struct st_timer { struct timespec expire_time; ulonglong period; my_bool expired; uint index_in_queue; void (*func)(void*); void *func_arg; } thr_timer_t; /* Main functions for library */ my_bool init_thr_timer(uint init_size_for_timer_queue); void end_thr_timer(); /* Functions for handling one timer */ void thr_timer_init(thr_timer_t *timer_data, void(*function)(void*), void *arg); void thr_timer_set_period(thr_timer_t* timer_data, ulonglong microseconds); my_bool thr_timer_settime(thr_timer_t *timer_data, ulonglong microseconds); void thr_timer_end(thr_timer_t *timer_data); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* THR_TIMER_INCLUDED */ mysql/server/private/sql_type_json.h000064400000014013151027430560013735 0ustar00#ifndef SQL_TYPE_JSON_INCLUDED #define SQL_TYPE_JSON_INCLUDED /* Copyright (c) 2019, 2021 MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mariadb.h" #include "sql_type.h" class Type_handler_json_common { public: static Virtual_column_info *make_json_valid_expr(THD *thd, const LEX_CSTRING *field_name); static bool make_json_valid_expr_if_needed(THD *thd, Column_definition *c); static bool set_format_name(Send_field_extended_metadata *to) { static const Lex_cstring fmt(STRING_WITH_LEN("json")); return to->set_format_name(fmt); } static const Type_handler *json_type_handler(uint max_octet_length); static const Type_handler *json_blob_type_handler_by_length_bytes(uint len); static const Type_handler *json_type_handler_sum(const Item_sum *sum); static const Type_handler *json_type_handler_from_generic(const Type_handler *th); static bool has_json_valid_constraint(const Field *field); static const Type_collection *type_collection(); static bool is_json_type_handler(const Type_handler *handler) { return handler->type_collection() == type_collection(); } }; template &thbase> class Type_handler_general_purpose_string_to_json: public BASE, public Type_handler_json_common { public: const Type_handler *type_handler_base() const override { return &thbase; } const Type_collection *type_collection() const override { return Type_handler_json_common::type_collection(); } bool Column_definition_validate_check_constraint(THD *thd, Column_definition *c) const override { return make_json_valid_expr_if_needed(thd, c) || BASE::Column_definition_validate_check_constraint(thd, c); } bool Column_definition_data_type_info_image(Binary_string *to, const Column_definition &def) const override { /* Override the inherited method to avoid JSON type handlers writing any extended metadata to FRM. JSON type handlers are currently detected only by CHECK(JSON_VALID()) constraint. This may change in the future to do write extended metadata to FRM, for more reliable detection. */ return false; } bool Item_append_extended_type_info(Send_field_extended_metadata *to, const Item *item) const override { return set_format_name(to); // Send "format=json" in the protocol } bool Item_hybrid_func_fix_attributes(THD *thd, const LEX_CSTRING &name, Type_handler_hybrid_field_type *hybrid, Type_all_attributes *attr, Item **items, uint nitems) const override { if (BASE::Item_hybrid_func_fix_attributes(thd, name, hybrid, attr, items, nitems)) return true; /* The above call can change the type handler on "hybrid", e.g. choose a proper BLOB type handler according to the calculated max_length. Convert general purpose string type handler to its JSON counterpart. This makes hybrid functions preserve JSON data types, e.g.: COALESCE(json_expr1, json_expr2) -> JSON */ hybrid->set_handler(json_type_handler_from_generic(hybrid->type_handler())); return false; } }; class Type_handler_string_json: public Type_handler_general_purpose_string_to_json { }; class Type_handler_varchar_json: public Type_handler_general_purpose_string_to_json { }; class Type_handler_tiny_blob_json: public Type_handler_general_purpose_string_to_json { }; class Type_handler_blob_json: public Type_handler_general_purpose_string_to_json { }; class Type_handler_medium_blob_json: public Type_handler_general_purpose_string_to_json { }; class Type_handler_long_blob_json: public Type_handler_general_purpose_string_to_json { }; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_string_json; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_varchar_json; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_tiny_blob_json; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_blob_json; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_medium_blob_json; extern MYSQL_PLUGIN_IMPORT Named_type_handler type_handler_long_blob_json; #endif // SQL_TYPE_JSON_INCLUDED mysql/server/private/sql_repl.h000064400000005745151027430560012701 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_REPL_INCLUDED #define SQL_REPL_INCLUDED #include "rpl_filter.h" #ifdef HAVE_REPLICATION #include "slave.h" struct slave_connection_state; extern my_bool opt_show_slave_auth_info; extern char *master_host, *master_info_file; extern int max_binlog_dump_events; extern my_bool opt_sporadic_binlog_dump_fail; int start_slave(THD* thd, Master_info* mi, bool net_report); int stop_slave(THD* thd, Master_info* mi, bool net_report); bool change_master(THD* thd, Master_info* mi, bool *master_info_added); bool mysql_show_binlog_events(THD* thd); int reset_slave(THD *thd, Master_info* mi); int reset_master(THD* thd, rpl_gtid *init_state, uint32 init_state_len, ulong next_log_number); bool purge_master_logs(THD* thd, const char* to_log); bool purge_master_logs_before_date(THD* thd, time_t purge_time); bool log_in_use(const char* log_name); void adjust_linfo_offsets(my_off_t purge_offset); void show_binlogs_get_fields(THD *thd, List *field_list); bool show_binlogs(THD* thd); extern int init_master_info(Master_info* mi); bool kill_zombie_dump_threads(THD *thd, uint32 slave_server_id); int check_binlog_magic(IO_CACHE* log, const char** errmsg); int compare_log_name(const char *log_1, const char *log_2); struct LOAD_FILE_IO_CACHE : public IO_CACHE { THD* thd; my_off_t last_pos_in_file; bool wrote_create_file, log_delayed; int (*real_read_function)(struct st_io_cache *,uchar *,size_t); }; int log_loaded_block(IO_CACHE* file, uchar *Buffer, size_t Count); int init_replication_sys_vars(); void mysql_binlog_send(THD* thd, char* log_ident, my_off_t pos, ushort flags); #ifdef HAVE_PSI_INTERFACE extern PSI_mutex_key key_LOCK_slave_state, key_LOCK_binlog_state; #endif void rpl_init_gtid_slave_state(); void rpl_deinit_gtid_slave_state(); void rpl_init_gtid_waiting(); void rpl_deinit_gtid_waiting(); int gtid_state_from_binlog_pos(const char *name, uint32 pos, String *out_str); int rpl_append_gtid_state(String *dest, bool use_binlog); int rpl_load_gtid_state(slave_connection_state *state, bool use_binlog); bool rpl_gtid_pos_check(THD *thd, char *str, size_t len); bool rpl_gtid_pos_update(THD *thd, char *str, size_t len); #else struct LOAD_FILE_IO_CACHE : public IO_CACHE { }; #endif /* HAVE_REPLICATION */ #endif /* SQL_REPL_INCLUDED */ mysql/server/private/ssl_compat.h000064400000006113151027430560013212 0ustar00/* Copyright (c) 2016, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include /* OpenSSL version specific definitions */ #if defined(OPENSSL_VERSION_NUMBER) #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \ !(defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x30500000L) #define HAVE_OPENSSL11 1 #define SSL_LIBRARY OpenSSL_version(OPENSSL_VERSION) #define ERR_remove_state(X) ERR_clear_error() #define EVP_CIPHER_CTX_SIZE 200 #define EVP_MD_CTX_SIZE 80 #undef EVP_MD_CTX_init #define EVP_MD_CTX_init(X) do { memset((X), 0, EVP_MD_CTX_SIZE); EVP_MD_CTX_reset(X); } while(0) #undef EVP_CIPHER_CTX_init #define EVP_CIPHER_CTX_init(X) do { memset((X), 0, EVP_CIPHER_CTX_SIZE); EVP_CIPHER_CTX_reset(X); } while(0) /* Macros below are deprecated. OpenSSL 1.1 may define them or not, depending on how it was built. */ #undef ERR_free_strings #define ERR_free_strings() #undef EVP_cleanup #define EVP_cleanup() #undef CRYPTO_cleanup_all_ex_data #define CRYPTO_cleanup_all_ex_data() #undef SSL_load_error_strings #define SSL_load_error_strings() #else #define HAVE_OPENSSL10 1 #ifdef HAVE_WOLFSSL #define SSL_LIBRARY "WolfSSL " WOLFSSL_VERSION #else #define SSL_LIBRARY SSLeay_version(SSLEAY_VERSION) #endif #ifdef HAVE_WOLFSSL #undef ERR_remove_state #define ERR_remove_state(x) do {} while(0) #elif defined (HAVE_ERR_remove_thread_state) #define ERR_remove_state(X) ERR_remove_thread_state(NULL) #endif /* HAVE_ERR_remove_thread_state */ #endif /* HAVE_OPENSSL11 */ #endif #ifdef HAVE_WOLFSSL #define EVP_MD_CTX_SIZE sizeof(wc_Md5) #endif #ifndef HAVE_OPENSSL11 #ifndef ASN1_STRING_get0_data #define ASN1_STRING_get0_data(X) ASN1_STRING_data(X) #endif #ifndef EVP_MD_CTX_SIZE #define EVP_MD_CTX_SIZE sizeof(EVP_MD_CTX) #endif #ifndef DH_set0_pqg #define DH_set0_pqg(D,P,Q,G) ((D)->p= (P), (D)->g= (G)) #endif #define EVP_CIPHER_CTX_encrypting(ctx) ((ctx)->encrypt) #define EVP_CIPHER_CTX_SIZE sizeof(EVP_CIPHER_CTX) #ifndef HAVE_WOLFSSL #define OPENSSL_init_ssl(X,Y) SSL_library_init() #define EVP_MD_CTX_reset(X) EVP_MD_CTX_cleanup(X) #define EVP_CIPHER_CTX_reset(X) EVP_CIPHER_CTX_cleanup(X) #define X509_get0_notBefore(X) X509_get_notBefore(X) #define X509_get0_notAfter(X) X509_get_notAfter(X) #endif #endif #ifndef TLS1_3_VERSION #define SSL_CTX_set_ciphersuites(X,Y) 0 #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ int check_openssl_compatibility(); #ifdef __cplusplus } #endif mysql/server/private/hash_filo.h000064400000013070151027430560013002 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* ** A class for static sized hash tables where old entries are deleted in ** first-in-last-out to usage. */ #ifndef HASH_FILO_H #define HASH_FILO_H #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class interface */ #endif #include "hash.h" /* my_hash_get_key, my_hash_free_key, HASH */ #include "m_string.h" /* bzero */ #include "mysqld.h" /* key_hash_filo_lock */ class hash_filo_element { private: hash_filo_element *next_used,*prev_used; public: hash_filo_element() = default; hash_filo_element *next() { return next_used; } hash_filo_element *prev() { return prev_used; } friend class hash_filo; }; class hash_filo { private: PSI_memory_key m_psi_key; const uint key_offset, key_length; const my_hash_get_key get_key; /** Size of this hash table. */ uint m_size; my_hash_free_key free_element; bool init; CHARSET_INFO *hash_charset; hash_filo_element *first_link,*last_link; public: mysql_mutex_t lock; HASH cache; hash_filo(PSI_memory_key psi_key, uint size_arg, uint key_offset_arg, uint key_length_arg, my_hash_get_key get_key_arg, my_hash_free_key free_element_arg, CHARSET_INFO *hash_charset_arg) : m_psi_key(psi_key), key_offset(key_offset_arg), key_length(key_length_arg), get_key(get_key_arg), m_size(size_arg), free_element(free_element_arg),init(0), hash_charset(hash_charset_arg), first_link(NULL), last_link(NULL) { bzero((char*) &cache,sizeof(cache)); } ~hash_filo() { if (init) { if (cache.array.buffer) /* Avoid problems with thread library */ (void) my_hash_free(&cache); mysql_mutex_destroy(&lock); } } void clear(bool locked=0) { if (!init) { init=1; mysql_mutex_init(key_hash_filo_lock, &lock, MY_MUTEX_INIT_FAST); } if (!locked) mysql_mutex_lock(&lock); first_link= NULL; last_link= NULL; (void) my_hash_free(&cache); (void) my_hash_init(m_psi_key, &cache,hash_charset,m_size,key_offset, key_length, get_key, free_element, 0); if (!locked) mysql_mutex_unlock(&lock); } hash_filo_element *first() { mysql_mutex_assert_owner(&lock); return first_link; } hash_filo_element *last() { mysql_mutex_assert_owner(&lock); return last_link; } hash_filo_element *search(uchar* key, size_t length) { mysql_mutex_assert_owner(&lock); hash_filo_element *entry=(hash_filo_element*) my_hash_search(&cache,(uchar*) key,length); if (entry) { // Found; link it first DBUG_ASSERT(first_link != NULL); DBUG_ASSERT(last_link != NULL); if (entry != first_link) { // Relink used-chain if (entry == last_link) { last_link= last_link->prev_used; /* The list must have at least 2 elements, otherwise entry would be equal to first_link. */ DBUG_ASSERT(last_link != NULL); last_link->next_used= NULL; } else { DBUG_ASSERT(entry->next_used != NULL); DBUG_ASSERT(entry->prev_used != NULL); entry->next_used->prev_used = entry->prev_used; entry->prev_used->next_used = entry->next_used; } entry->prev_used= NULL; entry->next_used= first_link; first_link->prev_used= entry; first_link=entry; } } return entry; } bool add(hash_filo_element *entry) { if (!m_size) return 1; if (cache.records == m_size) { hash_filo_element *tmp=last_link; last_link= last_link->prev_used; if (last_link != NULL) { last_link->next_used= NULL; } else { /* Pathological case, m_size == 1 */ first_link= NULL; } my_hash_delete(&cache,(uchar*) tmp); } if (my_hash_insert(&cache,(uchar*) entry)) { if (free_element) (*free_element)(entry); // This should never happen return 1; } entry->prev_used= NULL; entry->next_used= first_link; if (first_link != NULL) first_link->prev_used= entry; else last_link= entry; first_link= entry; return 0; } uint size() { return m_size; } void resize(uint new_size) { mysql_mutex_lock(&lock); m_size= new_size; clear(true); mysql_mutex_unlock(&lock); } }; template class Hash_filo: public hash_filo { public: Hash_filo(PSI_memory_key psi_key, uint size_arg, uint key_offset_arg, uint key_length_arg, my_hash_get_key get_key_arg, my_hash_free_key free_element_arg, CHARSET_INFO *hash_charset_arg) : hash_filo(psi_key, size_arg, key_offset_arg, key_length_arg, get_key_arg, free_element_arg, hash_charset_arg) {} T* first() { return (T*)hash_filo::first(); } T* last() { return (T*)hash_filo::last(); } T* search(uchar* key, size_t len) { return (T*)hash_filo::search(key, len); } }; #endif mysql/server/private/init.h000064400000001524151027430560012012 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef INIT_INCLUDED #define INIT_INCLUDED void unireg_init(ulong options); #endif /* INIT_INCLUDED */ mysql/server/private/pfs_statement_provider.h000064400000010373151027430560015637 0ustar00/* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #ifndef PFS_STATEMENT_PROVIDER_H #define PFS_STATEMENT_PROVIDER_H /** @file include/pfs_statement_provider.h Performance schema instrumentation (declarations). */ #ifdef HAVE_PSI_STATEMENT_INTERFACE #ifdef MYSQL_SERVER #ifndef EMBEDDED_LIBRARY #ifndef MYSQL_DYNAMIC_PLUGIN #include "mysql/psi/psi.h" #define PSI_STATEMENT_CALL(M) pfs_ ## M ## _v1 #define PSI_DIGEST_CALL(M) pfs_ ## M ## _v1 C_MODE_START void pfs_register_statement_v1(const char *category, PSI_statement_info_v1 *info, int count); PSI_statement_locker* pfs_get_thread_statement_locker_v1(PSI_statement_locker_state *state, PSI_statement_key key, const void *charset, PSI_sp_share *sp_share); PSI_statement_locker* pfs_refine_statement_v1(PSI_statement_locker *locker, PSI_statement_key key); void pfs_start_statement_v1(PSI_statement_locker *locker, const char *db, uint db_len, const char *src_file, uint src_line); void pfs_set_statement_text_v1(PSI_statement_locker *locker, const char *text, uint text_len); void pfs_set_statement_lock_time_v1(PSI_statement_locker *locker, ulonglong count); void pfs_set_statement_rows_sent_v1(PSI_statement_locker *locker, ulonglong count); void pfs_set_statement_rows_examined_v1(PSI_statement_locker *locker, ulonglong count); void pfs_inc_statement_created_tmp_disk_tables_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_created_tmp_tables_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_full_join_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_full_range_join_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_range_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_range_check_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_select_scan_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_merge_passes_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_range_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_rows_v1(PSI_statement_locker *locker, ulong count); void pfs_inc_statement_sort_scan_v1(PSI_statement_locker *locker, ulong count); void pfs_set_statement_no_index_used_v1(PSI_statement_locker *locker); void pfs_set_statement_no_good_index_used_v1(PSI_statement_locker *locker); void pfs_end_statement_v1(PSI_statement_locker *locker, void *stmt_da); PSI_digest_locker *pfs_digest_start_v1(PSI_statement_locker *locker); void pfs_digest_end_v1(PSI_digest_locker *locker, const sql_digest_storage *digest); C_MODE_END #endif /* MYSQL_DYNAMIC_PLUGIN */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_SERVER */ #endif /* HAVE_PSI_STATEMENT_INTERFACE */ #endif mysql/server/private/scheduler.h000064400000006177151027430560013036 0ustar00#ifndef SCHEDULER_INCLUDED #define SCHEDULER_INCLUDED /* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2012, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Classes for the thread scheduler */ #ifdef USE_PRAGMA_INTERFACE #pragma interface #endif class THD; /* Functions used when manipulating threads */ struct scheduler_functions { uint max_threads; Atomic_counter *connection_count; ulong *max_connections; bool (*init)(void); void (*add_connection)(CONNECT *connect); void (*thd_wait_begin)(THD *thd, int wait_type); void (*thd_wait_end)(THD *thd); void (*post_kill_notification)(THD *thd); void (*end)(void); /** resume previous unfinished command (threadpool only)*/ void (*thd_resume)(THD* thd); }; /** Scheduler types enumeration. The default of --thread-handling is the first one in the thread_handling_names array, this array has to be consistent with the order in this array, so to change default one has to change the first entry in this enum and the first entry in the thread_handling_names array. @note The last entry of the enumeration is also used to mark the thread handling as dynamic. In this case the name of the thread handling is fetched from the name of the plugin that implements it. */ enum scheduler_types { /* The default of --thread-handling is the first one in the thread_handling_names array, this array has to be consistent with the order in this array, so to change default one has to change the first entry in this enum and the first entry in the thread_handling_names array. */ SCHEDULER_ONE_THREAD_PER_CONNECTION=0, SCHEDULER_NO_THREADS, SCHEDULER_TYPES_COUNT }; void one_thread_per_connection_scheduler(scheduler_functions *func, ulong *arg_max_connections, Atomic_counter *arg_connection_count); void one_thread_scheduler(scheduler_functions *func, Atomic_counter *arg_connection_count); extern void scheduler_init(); extern void post_kill_notification(THD *); /* To be used for pool-of-threads (implemeneted differently on various OSs) */ struct thd_scheduler { public: void *data; /* scheduler-specific data structure */ }; #ifdef HAVE_POOL_OF_THREADS void pool_of_threads_scheduler(scheduler_functions* func, ulong *arg_max_connections, Atomic_counter *arg_connection_count); #else #define pool_of_threads_scheduler(A,B,C) \ one_thread_per_connection_scheduler(A, B, C) #endif /*HAVE_POOL_OF_THREADS*/ #endif /* SCHEDULER_INCLUDED */ mysql/server/private/ha_sequence.h000064400000014145151027430560013332 0ustar00#ifndef HA_SEQUENCE_INCLUDED #define HA_SEQUENCE_INCLUDED /* Copyright (c) 2017 Aliyun and/or its affiliates. Copyright (c) 2017 MariaDB corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "sql_sequence.h" #include "table.h" #include "handler.h" extern handlerton *sql_sequence_hton; /* Sequence engine handler. The sequence engine is a logic engine. It doesn't store any data. All the sequence data stored into the base table which must support non rollback writes (HA_CAN_TABLES_WITHOUT_ROLLBACK) The sequence data (SEQUENCE class) is stored in TABLE_SHARE->sequence TABLE RULES: 1. When table is created, one row is automaticlly inserted into the table. The table will always have one and only one row. 2. Any inserts or updates to the table will be validated. 3. Inserts will overwrite the original row. 4. DELETE and TRUNCATE will not affect the table. Instead a warning will be given. 5. Cache will be reset for any updates. CACHE RULES: SEQUENCE class is used to cache values that sequence defined. 1. If hit cache, we can query back the sequence nextval directly instead of reading the underlying table. 2. When run out of values, the sequence engine will reserve new values in update the base table. 3. The cache is invalidated if any update on based table. */ class ha_sequence :public handler { private: handler *file; SEQUENCE *sequence; /* From table_share->sequence */ public: /* Set when handler is write locked */ bool write_locked; ha_sequence(handlerton *hton, TABLE_SHARE *share); ~ha_sequence(); virtual handlerton *storage_ht() const override { return file->ht; } /* virtual function that are re-implemented for sequence */ int open(const char *name, int mode, uint test_if_locked) override; int create(const char *name, TABLE *form, HA_CREATE_INFO *create_info) override; handler *clone(const char *name, MEM_ROOT *mem_root) override; int write_row(const uchar *buf) override; Table_flags table_flags() const override; /* One can't update or delete from sequence engine */ int update_row(const uchar *old_data, const uchar *new_data) override { return HA_ERR_WRONG_COMMAND; } int delete_row(const uchar *buf) override { return HA_ERR_WRONG_COMMAND; } /* One can't delete from sequence engine */ int truncate() override { return HA_ERR_WRONG_COMMAND; } /* Can't use query cache */ uint8 table_cache_type() override { return HA_CACHE_TBL_NOCACHE; } void print_error(int error, myf errflag) override; int info(uint) override; LEX_CSTRING *engine_name() override { return hton_name(file->ht); } int external_lock(THD *thd, int lock_type) override; int extra(enum ha_extra_function operation) override; /* For ALTER ONLINE TABLE */ bool check_if_incompatible_data(HA_CREATE_INFO *create_info, uint table_changes) override; enum_alter_inplace_result check_if_supported_inplace_alter(TABLE *altered_table, Alter_inplace_info *ai) override; void write_lock() { write_locked= 1;} void unlock() { write_locked= 0; } bool is_locked() { return write_locked; } /* Functions that are directly mapped to the underlying handler */ int rnd_init(bool scan) override { return file->rnd_init(scan); } /* We need to have a lock here to protect engines like MyISAM from simultaneous read and write. For sequence's this is not critical as this function is used extremely seldom. */ int rnd_next(uchar *buf) override { int error; table->s->sequence->read_lock(table); error= file->rnd_next(buf); table->s->sequence->read_unlock(table); return error; } int rnd_end() override { return file->rnd_end(); } int rnd_pos(uchar *buf, uchar *pos) override { int error; table->s->sequence->read_lock(table); error= file->rnd_pos(buf, pos); table->s->sequence->read_unlock(table); return error; } void position(const uchar *record) override { return file->position(record); } const char *table_type() const override { return file->table_type(); } ulong index_flags(uint inx, uint part, bool all_parts) const override { return file->index_flags(inx, part, all_parts); } THR_LOCK_DATA **store_lock(THD *thd, THR_LOCK_DATA **to, enum thr_lock_type lock_type) override { return file->store_lock(thd, to, lock_type); } int close(void) override { return file->close(); } const char **bas_ext() const { return file->bas_ext(); } int delete_table(const char*name) override { return file->delete_table(name); } int rename_table(const char *from, const char *to) override { return file->rename_table(from, to); } void unbind_psi() override { file->unbind_psi(); } void rebind_psi() override { file->rebind_psi(); } int discard_or_import_tablespace(my_bool discard) override; bool auto_repair(int error) const override { return file->auto_repair(error); } int repair(THD* thd, HA_CHECK_OPT* check_opt) override { return file->repair(thd, check_opt); } bool check_and_repair(THD *thd) override { return file->check_and_repair(thd); } bool is_crashed() const override { return file->is_crashed(); } void column_bitmaps_signal() override { return file->column_bitmaps_signal(); } /* New methods */ void register_original_handler(handler *file_arg) { file= file_arg; init(); /* Update cached_table_flags */ } }; #endif mysql/server/private/probes_mysql_nodtrace.h000064400000011615151027430560015447 0ustar00/* * Generated by dheadgen(1). */ #ifndef _PROBES_MYSQL_D #define _PROBES_MYSQL_D #ifdef __cplusplus extern "C" { #endif #define MYSQL_CONNECTION_START(arg0, arg1, arg2) #define MYSQL_CONNECTION_START_ENABLED() (0) #define MYSQL_CONNECTION_DONE(arg0, arg1) #define MYSQL_CONNECTION_DONE_ENABLED() (0) #define MYSQL_COMMAND_START(arg0, arg1, arg2, arg3) #define MYSQL_COMMAND_START_ENABLED() (0) #define MYSQL_COMMAND_DONE(arg0) #define MYSQL_COMMAND_DONE_ENABLED() (0) #define MYSQL_QUERY_START(arg0, arg1, arg2, arg3, arg4) #define MYSQL_QUERY_START_ENABLED() (0) #define MYSQL_QUERY_DONE(arg0) #define MYSQL_QUERY_DONE_ENABLED() (0) #define MYSQL_QUERY_PARSE_START(arg0) #define MYSQL_QUERY_PARSE_START_ENABLED() (0) #define MYSQL_QUERY_PARSE_DONE(arg0) #define MYSQL_QUERY_PARSE_DONE_ENABLED() (0) #define MYSQL_QUERY_CACHE_HIT(arg0, arg1) #define MYSQL_QUERY_CACHE_HIT_ENABLED() (0) #define MYSQL_QUERY_CACHE_MISS(arg0) #define MYSQL_QUERY_CACHE_MISS_ENABLED() (0) #define MYSQL_QUERY_EXEC_START(arg0, arg1, arg2, arg3, arg4, arg5) #define MYSQL_QUERY_EXEC_START_ENABLED() (0) #define MYSQL_QUERY_EXEC_DONE(arg0) #define MYSQL_QUERY_EXEC_DONE_ENABLED() (0) #define MYSQL_INSERT_ROW_START(arg0, arg1) #define MYSQL_INSERT_ROW_START_ENABLED() (0) #define MYSQL_INSERT_ROW_DONE(arg0) #define MYSQL_INSERT_ROW_DONE_ENABLED() (0) #define MYSQL_UPDATE_ROW_START(arg0, arg1) #define MYSQL_UPDATE_ROW_START_ENABLED() (0) #define MYSQL_UPDATE_ROW_DONE(arg0) #define MYSQL_UPDATE_ROW_DONE_ENABLED() (0) #define MYSQL_DELETE_ROW_START(arg0, arg1) #define MYSQL_DELETE_ROW_START_ENABLED() (0) #define MYSQL_DELETE_ROW_DONE(arg0) #define MYSQL_DELETE_ROW_DONE_ENABLED() (0) #define MYSQL_READ_ROW_START(arg0, arg1, arg2) #define MYSQL_READ_ROW_START_ENABLED() (0) #define MYSQL_READ_ROW_DONE(arg0) #define MYSQL_READ_ROW_DONE_ENABLED() (0) #define MYSQL_INDEX_READ_ROW_START(arg0, arg1) #define MYSQL_INDEX_READ_ROW_START_ENABLED() (0) #define MYSQL_INDEX_READ_ROW_DONE(arg0) #define MYSQL_INDEX_READ_ROW_DONE_ENABLED() (0) #define MYSQL_HANDLER_RDLOCK_START(arg0, arg1) #define MYSQL_HANDLER_RDLOCK_START_ENABLED() (0) #define MYSQL_HANDLER_WRLOCK_START(arg0, arg1) #define MYSQL_HANDLER_WRLOCK_START_ENABLED() (0) #define MYSQL_HANDLER_UNLOCK_START(arg0, arg1) #define MYSQL_HANDLER_UNLOCK_START_ENABLED() (0) #define MYSQL_HANDLER_RDLOCK_DONE(arg0) #define MYSQL_HANDLER_RDLOCK_DONE_ENABLED() (0) #define MYSQL_HANDLER_WRLOCK_DONE(arg0) #define MYSQL_HANDLER_WRLOCK_DONE_ENABLED() (0) #define MYSQL_HANDLER_UNLOCK_DONE(arg0) #define MYSQL_HANDLER_UNLOCK_DONE_ENABLED() (0) #define MYSQL_FILESORT_START(arg0, arg1) #define MYSQL_FILESORT_START_ENABLED() (0) #define MYSQL_FILESORT_DONE(arg0, arg1) #define MYSQL_FILESORT_DONE_ENABLED() (0) #define MYSQL_SELECT_START(arg0) #define MYSQL_SELECT_START_ENABLED() (0) #define MYSQL_SELECT_DONE(arg0, arg1) #define MYSQL_SELECT_DONE_ENABLED() (0) #define MYSQL_INSERT_START(arg0) #define MYSQL_INSERT_START_ENABLED() (0) #define MYSQL_INSERT_DONE(arg0, arg1) #define MYSQL_INSERT_DONE_ENABLED() (0) #define MYSQL_INSERT_SELECT_START(arg0) #define MYSQL_INSERT_SELECT_START_ENABLED() (0) #define MYSQL_INSERT_SELECT_DONE(arg0, arg1) #define MYSQL_INSERT_SELECT_DONE_ENABLED() (0) #define MYSQL_UPDATE_START(arg0) #define MYSQL_UPDATE_START_ENABLED() (0) #define MYSQL_UPDATE_DONE(arg0, arg1, arg2) #define MYSQL_UPDATE_DONE_ENABLED() (0) #define MYSQL_MULTI_UPDATE_START(arg0) #define MYSQL_MULTI_UPDATE_START_ENABLED() (0) #define MYSQL_MULTI_UPDATE_DONE(arg0, arg1, arg2) #define MYSQL_MULTI_UPDATE_DONE_ENABLED() (0) #define MYSQL_DELETE_START(arg0) #define MYSQL_DELETE_START_ENABLED() (0) #define MYSQL_DELETE_DONE(arg0, arg1) #define MYSQL_DELETE_DONE_ENABLED() (0) #define MYSQL_MULTI_DELETE_START(arg0) #define MYSQL_MULTI_DELETE_START_ENABLED() (0) #define MYSQL_MULTI_DELETE_DONE(arg0, arg1) #define MYSQL_MULTI_DELETE_DONE_ENABLED() (0) #define MYSQL_NET_READ_START() #define MYSQL_NET_READ_START_ENABLED() (0) #define MYSQL_NET_READ_DONE(arg0, arg1) #define MYSQL_NET_READ_DONE_ENABLED() (0) #define MYSQL_NET_WRITE_START(arg0) #define MYSQL_NET_WRITE_START_ENABLED() (0) #define MYSQL_NET_WRITE_DONE(arg0) #define MYSQL_NET_WRITE_DONE_ENABLED() (0) #define MYSQL_KEYCACHE_READ_START(arg0, arg1, arg2, arg3) #define MYSQL_KEYCACHE_READ_START_ENABLED() (0) #define MYSQL_KEYCACHE_READ_BLOCK(arg0) #define MYSQL_KEYCACHE_READ_BLOCK_ENABLED() (0) #define MYSQL_KEYCACHE_READ_HIT() #define MYSQL_KEYCACHE_READ_HIT_ENABLED() (0) #define MYSQL_KEYCACHE_READ_MISS() #define MYSQL_KEYCACHE_READ_MISS_ENABLED() (0) #define MYSQL_KEYCACHE_READ_DONE(arg0, arg1) #define MYSQL_KEYCACHE_READ_DONE_ENABLED() (0) #define MYSQL_KEYCACHE_WRITE_START(arg0, arg1, arg2, arg3) #define MYSQL_KEYCACHE_WRITE_START_ENABLED() (0) #define MYSQL_KEYCACHE_WRITE_BLOCK(arg0) #define MYSQL_KEYCACHE_WRITE_BLOCK_ENABLED() (0) #define MYSQL_KEYCACHE_WRITE_DONE(arg0, arg1) #define MYSQL_KEYCACHE_WRITE_DONE_ENABLED() (0) #ifdef __cplusplus } #endif #endif /* _PROBES_MYSQL_D */ mysql/server/private/rpl_mi.h000064400000035217151027430560012337 0ustar00/* Copyright (c) 2006, 2012, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_MI_H #define RPL_MI_H #ifdef HAVE_REPLICATION #include "rpl_rli.h" #include "rpl_reporting.h" #include #include "rpl_filter.h" #include "keycaches.h" typedef struct st_mysql MYSQL; /** Domain id based filter to handle DO_DOMAIN_IDS and IGNORE_DOMAIN_IDS used to set filtering on replication slave based on event's GTID domain_id. */ class Domain_id_filter { private: /* Flag to tell whether the events in the current GTID group get written to the relay log. It is set according to the domain_id based filtering rule on every GTID_EVENT and reset at the end of current GTID event group. */ bool m_filter; public: /* domain id list types */ enum enum_list_type { DO_DOMAIN_IDS= 0, IGNORE_DOMAIN_IDS }; /* DO_DOMAIN_IDS (0): Ignore all the events which do not belong to any of the domain ids in the list. IGNORE_DOMAIN_IDS (1): Ignore the events which belong to one of the domain ids in the list. */ DYNAMIC_ARRAY m_domain_ids[2]; Domain_id_filter(); ~Domain_id_filter(); /* Returns whether the current group needs to be filtered. */ bool is_group_filtered() { return m_filter; } /* Checks whether the group with the specified domain_id needs to be filtered and updates m_filter flag accordingly. */ void do_filter(ulong domain_id); /* Reset m_filter. It should be called when IO thread receives COMMIT_EVENT or XID_EVENT. */ void reset_filter(); /* Clear do_ids and ignore_ids to disable domain id filtering */ void clear_ids(); /* Update the do/ignore domain id filter lists. @param do_ids [IN] domain ids to be kept @param ignore_ids [IN] domain ids to be filtered out @param using_gtid [IN] use GTID? @retval false Success true Error */ bool update_ids(DYNAMIC_ARRAY *do_ids, DYNAMIC_ARRAY *ignore_ids, bool using_gtid); /* Serialize and store the ids from domain id lists into the thd's protocol buffer. @param thd [IN] thread handler @retval void */ void store_ids(THD *thd); /* Initialize the given domain id list (DYNAMIC_ARRAY) with the space-separated list of numbers from the specified IO_CACHE where the first number is the total number of entries to follows. @param f [IN] IO_CACHE file @param type [IN] domain id list type @retval false Success true Error */ bool init_ids(IO_CACHE *f, enum_list_type type); /* Return the elements of the give domain id list type as string. @param type [IN] domain id list type @retval a string buffer storing the total number of elements followed by the individual elements (space-separated) in the specified list. Note: Its caller's responsibility to free the returned string buffer. */ char *as_string(enum_list_type type); }; extern TYPELIB slave_parallel_mode_typelib; typedef struct st_rows_event_tracker { char binlog_file_name[FN_REFLEN]; my_off_t first_seen; my_off_t last_seen; bool stmt_end_seen; void update(const char *file_name, my_off_t pos, const uchar *buf, const Format_description_log_event *fdle); void reset(); bool check_and_report(const char* file_name, my_off_t pos); } Rows_event_tracker; /***************************************************************************** Replication IO Thread Master_info contains: - information about how to connect to a master - current master log name - current master log offset - misc control variables Master_info is initialized once from the master.info file if such exists. Otherwise, data members corresponding to master.info fields are initialized with defaults specified by master-* options. The initialization is done through init_master_info() call. The format of master.info file: log_name log_pos master_host master_user master_pass master_port master_connect_retry To write out the contents of master.info file to disk ( needed every time we read and queue data from the master ), a call to flush_master_info() is required. To clean up, call end_master_info() *****************************************************************************/ class Master_info : public Slave_reporting_capability { public: enum enum_using_gtid { USE_GTID_NO= 0, USE_GTID_CURRENT_POS= 1, USE_GTID_SLAVE_POS= 2 }; Master_info(LEX_CSTRING *connection_name, bool is_slave_recovery); ~Master_info(); bool shall_ignore_server_id(ulong s_id); void clear_in_memory_info(bool all); bool error() { /* If malloc() in initialization failed */ return connection_name.str == 0; } static const char *using_gtid_astext(enum enum_using_gtid arg); bool using_parallel() { return opt_slave_parallel_threads > 0 && parallel_mode > SLAVE_PARALLEL_NONE; } void release(); void wait_until_free(); void lock_slave_threads(); void unlock_slave_threads(); ulonglong get_slave_skip_counter() { return rli.slave_skip_counter; } ulonglong get_max_relay_log_size() { return rli.max_relay_log_size; } /* the variables below are needed because we can change masters on the fly */ char master_log_name[FN_REFLEN+6]; /* Room for multi-*/ char host[HOSTNAME_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; char user[USERNAME_LENGTH+1]; char password[MAX_PASSWORD_LENGTH*SYSTEM_CHARSET_MBMAXLEN+1]; LEX_CSTRING connection_name; /* User supplied connection name */ LEX_CSTRING cmp_connection_name; /* Connection name in lower case */ bool ssl; // enables use of SSL connection if true char ssl_ca[FN_REFLEN], ssl_capath[FN_REFLEN], ssl_cert[FN_REFLEN]; char ssl_cipher[FN_REFLEN], ssl_key[FN_REFLEN]; char ssl_crl[FN_REFLEN], ssl_crlpath[FN_REFLEN]; bool ssl_verify_server_cert; my_off_t master_log_pos; File fd; // we keep the file open, so we need to remember the file pointer IO_CACHE file; mysql_mutex_t data_lock, run_lock, sleep_lock, start_stop_lock; mysql_cond_t data_cond, start_cond, stop_cond, sleep_cond; THD *io_thd; MYSQL* mysql; uint32 file_id; /* for 3.23 load data infile */ Relay_log_info rli; uint port; Rpl_filter* rpl_filter; /* Each replication can set its filter rule*/ /* to hold checksum alg in use until IO thread has received FD. Initialized to novalue, then set to the queried from master @@global.binlog_checksum and deactivated once FD has been received. */ enum enum_binlog_checksum_alg checksum_alg_before_fd; uint connect_retry; #ifndef DBUG_OFF int events_till_disconnect; /* The following are auxiliary DBUG variables used to kill IO thread in the middle of a group/transaction (see "kill_slave_io_after_2_events"). */ bool dbug_do_disconnect; int dbug_event_counter; #endif bool inited; volatile bool abort_slave; volatile uint slave_running; volatile ulong slave_run_id; /* The difference in seconds between the clock of the master and the clock of the slave (second - first). It must be signed as it may be <0 or >0. clock_diff_with_master is computed when the I/O thread starts; for this the I/O thread does a SELECT UNIX_TIMESTAMP() on the master. "how late the slave is compared to the master" is computed like this: clock_of_slave - last_timestamp_executed_by_SQL_thread - clock_diff_with_master */ long clock_diff_with_master; /* Keeps track of the number of events before fsyncing. The option --sync-master-info determines how many events should happen before fsyncing. */ uint sync_counter; float heartbeat_period; // interface with CHANGE MASTER or master.info ulonglong received_heartbeats; // counter of received heartbeat events DYNAMIC_ARRAY ignore_server_ids; ulong master_id; /* At reconnect and until the first rotate event is seen, prev_master_id is the value of master_id during the previous connection, used to detect silent change of master server during reconnects. */ ulong prev_master_id; /* Which kind of GTID position (if any) is used when connecting to master. Note that you can not change the numeric values of these, they are used in master.info. */ enum enum_using_gtid using_gtid; /* This GTID position records how far we have fetched into the relay logs. This is used to continue fetching when the IO thread reconnects to the master. (Full slave stop/start does not use it, as it resets the relay logs). */ slave_connection_state gtid_current_pos; /* If events_queued_since_last_gtid is non-zero, it is the number of events queued so far in the relaylog of a GTID-prefixed event group. It is zero when no partial event group has been queued at the moment. */ uint64 events_queued_since_last_gtid; /* The GTID of the partially-queued event group, when events_queued_since_last_gtid is non-zero. */ rpl_gtid last_queued_gtid; /* Whether last_queued_gtid had the FL_STANDALONE flag set. */ bool last_queued_gtid_standalone; /* When slave IO thread needs to reconnect, gtid_reconnect_event_skip_count counts number of events to skip from the first GTID-prefixed event group, to avoid duplicating events in the relay log. */ uint64 gtid_reconnect_event_skip_count; /* gtid_event_seen is false until we receive first GTID event from master. */ bool gtid_event_seen; /** The struct holds some history of Rows- log-event reading/queuing by the receiver thread. Its fields are updated per each such event at time of queue_event(), and they are checked to detect the Rows- event group integrity violation at time of first non-Rows- event gets handled. */ Rows_event_tracker rows_event_tracker; bool in_start_all_slaves, in_stop_all_slaves; bool in_flush_all_relay_logs; uint users; /* Active user for object */ uint killed; /* No of DDL event group */ Atomic_counter total_ddl_groups; /* No of non-transactional event group*/ Atomic_counter total_non_trans_groups; /* No of transactional event group*/ Atomic_counter total_trans_groups; /* domain-id based filter */ Domain_id_filter domain_id_filter; /* The parallel replication mode. */ enum_slave_parallel_mode parallel_mode; /* semi_ack is used to identify if the current binlog event needs an ACK from slave, or if delay_master is enabled. */ int semi_ack; /* The flag has replicate_same_server_id semantics and is raised to accept a same-server-id event group by the gtid strict mode semisync slave. Own server-id events can normally appear as result of EITHER A. this server semisync (failover to) slave crash-recovery: the transaction was created on this server then being master, got replicated elsewhere right before the crash before commit, and finally at recovery the transaction gets evicted from the server's binlog and its gtid (slave) state; OR B. in a general circular configuration and then when a recieved (returned to slave) gtid exists in the server's binlog. Then, in gtid strict mode, it must be ignored similarly to the replicate-same-server-id rule. */ bool do_accept_own_server_id; /* Set to 1 when semi_sync is enabled. Set to 0 if there is any transmit problems to the slave, in which case any furter semi-sync reply is ignored */ bool semi_sync_reply_enabled; }; int init_master_info(Master_info* mi, const char* master_info_fname, const char* slave_info_fname, bool abort_if_no_master_info_file, int thread_mask); void end_master_info(Master_info* mi); int flush_master_info(Master_info* mi, bool flush_relay_log_cache, bool need_lock_relay_log); void copy_filter_setting(Rpl_filter* dst_filter, Rpl_filter* src_filter); void update_change_master_ids(DYNAMIC_ARRAY *new_ids, DYNAMIC_ARRAY *old_ids); void prot_store_ids(THD *thd, DYNAMIC_ARRAY *ids); /* Multi master are handled trough this struct. Changes to this needs to be protected by LOCK_active_mi; */ class Master_info_index { private: IO_CACHE index_file; char index_file_name[FN_REFLEN]; public: Master_info_index(); ~Master_info_index(); HASH master_info_hash; bool init_all_master_info(); bool write_master_name_to_index_file(LEX_CSTRING *connection_name, bool do_sync); bool check_duplicate_master_info(LEX_CSTRING *connection_name, const char *host, uint port); bool add_master_info(Master_info *mi, bool write_to_file); bool remove_master_info(Master_info *mi); Master_info *get_master_info(const LEX_CSTRING *connection_name, Sql_condition::enum_warning_level warning); bool start_all_slaves(THD *thd); bool stop_all_slaves(THD *thd); void free_connections(); bool flush_all_relay_logs(); }; /* The class rpl_io_thread_info is the THD::system_thread_info for the IO thread. */ class rpl_io_thread_info { public: }; Master_info *get_master_info(const LEX_CSTRING *connection_name, Sql_condition::enum_warning_level warning); bool check_master_connection_name(LEX_CSTRING *name); void create_logfile_name_with_suffix(char *res_file_name, size_t length, const char *info_file, bool append, LEX_CSTRING *suffix); uchar *get_key_master_info(Master_info *mi, size_t *length, my_bool not_used __attribute__((unused))); void free_key_master_info(Master_info *mi); uint any_slave_sql_running(bool already_locked); bool give_error_if_slave_running(bool already_lock); #endif /* HAVE_REPLICATION */ #endif /* RPL_MI_H */ mysql/server/private/waiting_threads.h000064400000010664151027430560014230 0ustar00/* Copyright (C) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _waiting_threads_h #define _waiting_threads_h #include #include C_MODE_START typedef struct st_wt_resource_id WT_RESOURCE_ID; typedef struct st_wt_resource WT_RESOURCE; typedef struct st_wt_resource_type { my_bool (*compare)(const void *a, const void *b); const void *(*make_key)(const WT_RESOURCE_ID *id, uint *len); /* not used */ } WT_RESOURCE_TYPE; struct st_wt_resource_id { ulonglong value; const WT_RESOURCE_TYPE *type; }; /* the below differs from sizeof(WT_RESOURCE_ID) by the amount of padding */ #define sizeof_WT_RESOURCE_ID (sizeof(ulonglong)+sizeof(void*)) #define WT_WAIT_STATS 24 #define WT_CYCLE_STATS 32 extern ulonglong wt_wait_table[WT_WAIT_STATS]; extern uint32 wt_wait_stats[WT_WAIT_STATS+1]; extern uint32 wt_cycle_stats[2][WT_CYCLE_STATS+1]; extern uint32 wt_success_stats; typedef struct st_wt_thd { /* XXX there's no protection (mutex) against concurrent access of the dynarray below. it is assumed that a caller will have it anyway (not to protect this array but to protect its own - caller's - data structures), and we'll get it for free. A caller needs to ensure that a blocker won't release a resource before a blocked thread starts waiting, which is usually done with a mutex. If the above assumption is wrong, we'll need to add a mutex here. */ DYNAMIC_ARRAY my_resources; /* 'waiting_for' is modified under waiting_for->lock, and only by thd itself 'waiting_for' is read lock-free (using pinning protocol), but a thd object can read its own 'waiting_for' without any locks or tricks. */ WT_RESOURCE *waiting_for; LF_PINS *pins; /* pointers to values */ const ulong *timeout_short; const ulong *deadlock_search_depth_short; const ulong *timeout_long; const ulong *deadlock_search_depth_long; /* weight relates to the desirability of a transaction being killed if it's part of a deadlock. In a deadlock situation transactions with lower weights are killed first. Examples of using the weight to implement different selection strategies: 1. Latest Keep all weights equal. 2. Random Assign weights at random. (variant: modify a weight randomly before every lock request) 3. Youngest Set weight to -NOW() 4. Minimum locks count locks granted in your lock manager, store the value as a weight 5. Minimum work depends on the definition of "work". For example, store the number of rows modifies in this transaction (or a length of REDO log for a transaction) as a weight. It is only statistically relevant and is not protected by any locks. */ ulong volatile weight; /* 'killed' is indirectly protected by waiting_for->lock because a killed thread needs to clear its 'waiting_for' and thus needs a lock. That is a thread needs an exclusive lock to read 'killed' reliably. But other threads may change 'killed' from 0 to 1, a shared lock is enough for that. */ my_bool killed; #ifndef DBUG_OFF const char *name; #endif } WT_THD; #define WT_TIMEOUT ETIMEDOUT #define WT_OK 0 #define WT_DEADLOCK -1 #define WT_DEPTH_EXCEEDED -2 #define WT_FREE_TO_GO -3 void wt_init(void); void wt_end(void); void wt_thd_lazy_init(WT_THD *, const ulong *, const ulong *, const ulong *, const ulong *); void wt_thd_destroy(WT_THD *); int wt_thd_will_wait_for(WT_THD *, WT_THD *, const WT_RESOURCE_ID *); int wt_thd_cond_timedwait(WT_THD *, mysql_mutex_t *); void wt_thd_release(WT_THD *, const WT_RESOURCE_ID *); #define wt_thd_release_all(THD) wt_thd_release((THD), 0) my_bool wt_resource_id_memcmp(const void *, const void *); C_MODE_END #endif mysql/server/private/mysqld_default_groups.h000064400000000314151027430560015457 0ustar00const char *load_default_groups[]= { "mysqld", "server", MYSQL_BASE_VERSION, "mariadb", MARIADB_BASE_VERSION, "mariadbd", MARIADBD_BASE_VERSION, "client-server", #ifdef WITH_WSREP "galera", #endif 0, 0}; mysql/server/private/item_cmpfunc.h000064400000407563151027430560013535 0ustar00#ifndef ITEM_CMPFUNC_INCLUDED #define ITEM_CMPFUNC_INCLUDED /* Copyright (c) 2000, 2015, Oracle and/or its affiliates. Copyright (c) 2009, 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* compare and test functions */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "item_func.h" /* Item_int_func, Item_bool_func */ #include "item.h" extern Item_result item_cmp_type(Item_result a,Item_result b); inline Item_result item_cmp_type(const Item *a, const Item *b) { return item_cmp_type(a->cmp_type(), b->cmp_type()); } inline Item_result item_cmp_type(Item_result a, const Item *b) { return item_cmp_type(a, b->cmp_type()); } class Item_bool_func2; class Arg_comparator; typedef int (Arg_comparator::*arg_cmp_func)(); typedef int (*Item_field_cmpfunc)(Item *f1, Item *f2, void *arg); class Arg_comparator: public Sql_alloc { Item **a, **b; const Type_handler *m_compare_handler; CHARSET_INFO *m_compare_collation; arg_cmp_func func; Item_func_or_sum *owner; bool set_null; // TRUE <=> set owner->null_value Arg_comparator *comparators; // used only for compare_row() double precision; /* Fields used in DATE/DATETIME comparison. */ Item *a_cache, *b_cache; // Cached values of a and b items // when one of arguments is NULL. int set_cmp_func(THD *thd, Item_func_or_sum *owner_arg, const Type_handler *compare_handler, Item **a1, Item **a2); int compare_not_null_values(longlong val1, longlong val2) { if (set_null) owner->null_value= false; if (val1 < val2) return -1; if (val1 == val2) return 0; return 1; } NativeBuffer m_native1, m_native2; public: /* Allow owner function to use string buffers. */ String value1, value2; Arg_comparator(): m_compare_handler(&type_handler_null), m_compare_collation(&my_charset_bin), set_null(TRUE), comparators(0), a_cache(0), b_cache(0) {}; Arg_comparator(Item **a1, Item **a2): a(a1), b(a2), m_compare_handler(&type_handler_null), m_compare_collation(&my_charset_bin), set_null(TRUE), comparators(0), a_cache(0), b_cache(0) {}; public: bool set_cmp_func_for_row_arguments(THD *thd); bool set_cmp_func_row(THD *thd); bool set_cmp_func_string(THD *thd); bool set_cmp_func_time(THD *thd); bool set_cmp_func_datetime(THD *thd); bool set_cmp_func_native(THD *thd); bool set_cmp_func_int(THD *thd); bool set_cmp_func_real(THD *thd); bool set_cmp_func_decimal(THD *thd); inline int set_cmp_func(THD *thd, Item_func_or_sum *owner_arg, const Type_handler *compare_handler, Item **a1, Item **a2, bool set_null_arg) { set_null= set_null_arg; return set_cmp_func(thd, owner_arg, compare_handler, a1, a2); } int set_cmp_func(THD *thd, Item_func_or_sum *owner_arg, Item **a1, Item **a2, bool set_null_arg) { Item *tmp_args[2]= { *a1, *a2 }; Type_handler_hybrid_field_type tmp; if (tmp.aggregate_for_comparison(owner_arg->func_name_cstring(), tmp_args, 2, false)) return 1; return set_cmp_func(thd, owner_arg, tmp.type_handler(), a1, a2, set_null_arg); } inline int compare() { return (this->*func)(); } int compare_string(); // compare args[0] & args[1] int compare_real(); // compare args[0] & args[1] int compare_decimal(); // compare args[0] & args[1] int compare_int_signed(); // compare args[0] & args[1] int compare_int_signed_unsigned(); int compare_int_unsigned_signed(); int compare_int_unsigned(); int compare_row(); // compare args[0] & args[1] int compare_e_string(); // compare args[0] & args[1] int compare_e_real(); // compare args[0] & args[1] int compare_e_decimal(); // compare args[0] & args[1] int compare_e_int(); // compare args[0] & args[1] int compare_e_int_diff_signedness(); int compare_e_row(); // compare args[0] & args[1] int compare_real_fixed(); int compare_e_real_fixed(); int compare_datetime(); int compare_e_datetime(); int compare_time(); int compare_e_time(); int compare_native(); int compare_e_native(); int compare_json_str_basic(Item *j, Item *s); int compare_json_str(); int compare_str_json(); int compare_e_json_str_basic(Item *j, Item *s); int compare_e_json_str(); int compare_e_str_json(); void min_max_update_field_native(THD *thd, Field *field, Item *item, int cmp_sign); Item** cache_converted_constant(THD *thd, Item **value, Item **cache, const Type_handler *type); inline bool is_owner_equal_func() { return (owner->type() == Item::FUNC_ITEM && ((Item_func*)owner)->functype() == Item_func::EQUAL_FUNC); } const Type_handler *compare_type_handler() const { return m_compare_handler; } Item_result compare_type() const { return m_compare_handler->cmp_type(); } CHARSET_INFO *compare_collation() const { return m_compare_collation; } Arg_comparator *subcomparators() const { return comparators; } void cleanup() { delete [] comparators; comparators= 0; } friend class Item_func; friend class Item_bool_rowready_func2; }; class SEL_ARG; struct KEY_PART; class Item_bool_func :public Item_int_func, public Type_cmp_attributes { protected: /* Build a SEL_TREE for a simple predicate @param param PARAM from SQL_SELECT::test_quick_select @param field field in the predicate @param value constant in the predicate @return Pointer to the tree built tree */ virtual SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) { DBUG_ENTER("Item_bool_func::get_func_mm_tree"); DBUG_ASSERT(0); DBUG_RETURN(0); } /* Return the full select tree for "field_item" and "value": - a single SEL_TREE if the field is not in a multiple equality, or - a conjunction of all SEL_TREEs for all fields from the same multiple equality with "field_item". */ SEL_TREE *get_full_func_mm_tree(RANGE_OPT_PARAM *param, Item_field *field_item, Item *value); /** Test if "item" and "value" are suitable for the range optimization and get their full select tree. "Suitable" means: - "item" is a field or a field reference - "value" is NULL (e.g. WHERE field IS NULL), or "value" is an unexpensive item (e.g. WHERE field OP value) @param item - the argument that is checked to be a field @param value - the other argument @returns - NULL if the arguments are not suitable for the range optimizer. @returns - the full select tree if the arguments are suitable. */ SEL_TREE *get_full_func_mm_tree_for_args(RANGE_OPT_PARAM *param, Item *item, Item *value) { DBUG_ENTER("Item_bool_func::get_full_func_mm_tree_for_args"); Item *field= item->real_item(); if (field->type() == Item::FIELD_ITEM && !field->const_item() && (!value || !value->is_expensive())) DBUG_RETURN(get_full_func_mm_tree(param, (Item_field *) field, value)); DBUG_RETURN(NULL); } SEL_TREE *get_mm_parts(RANGE_OPT_PARAM *param, Field *field, Item_func::Functype type, Item *value); SEL_TREE *get_ne_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *lt_value, Item *gt_value); virtual SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, KEY_PART *key_part, Item_func::Functype type, Item *value); void raise_note_if_key_become_unused(THD *thd, const Item_args &old_args); public: Item_bool_func(THD *thd): Item_int_func(thd) {} Item_bool_func(THD *thd, Item *a): Item_int_func(thd, a) {} Item_bool_func(THD *thd, Item *a, Item *b): Item_int_func(thd, a, b) {} Item_bool_func(THD *thd, Item *a, Item *b, Item *c): Item_int_func(thd, a, b, c) {} Item_bool_func(THD *thd, List &list): Item_int_func(thd, list) { } Item_bool_func(THD *thd, Item_bool_func *item) :Item_int_func(thd, item) {} const Type_handler *type_handler() const override { return &type_handler_bool; } const Type_handler *fixed_type_handler() const override { return &type_handler_bool; } CHARSET_INFO *compare_collation() const override { return NULL; } longlong val_int() override final { DBUG_ASSERT(!is_cond()); return val_bool(); } bool val_bool() override= 0; bool fix_length_and_dec() override { decimals=0; max_length=1; return FALSE; } decimal_digits_t decimal_precision() const override { return 1; } bool need_parentheses_in_default() override { return true; } }; /** Abstract Item class, to represent X IS [NOT] (TRUE | FALSE) boolean predicates. */ class Item_func_truth : public Item_bool_func { public: bool val_bool() override; bool fix_length_and_dec() override; void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return CMP_PRECEDENCE; } protected: Item_func_truth(THD *thd, Item *a, bool a_value, bool a_affirmative): Item_bool_func(thd, a), value(a_value), affirmative(a_affirmative) {} ~Item_func_truth() = default; private: /** True for X IS [NOT] TRUE, false for X IS [NOT] FALSE predicates. */ const bool value; /** True for X IS Y, false for X IS NOT Y predicates. */ const bool affirmative; }; /** This Item represents a X IS TRUE boolean predicate. */ class Item_func_istrue : public Item_func_truth { public: Item_func_istrue(THD *thd, Item *a): Item_func_truth(thd, a, true, true) {} ~Item_func_istrue() = default; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("istrue") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** This Item represents a X IS NOT TRUE boolean predicate. */ class Item_func_isnottrue : public Item_func_truth { public: Item_func_isnottrue(THD *thd, Item *a): Item_func_truth(thd, a, true, false) {} ~Item_func_isnottrue() = default; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("isnottrue") }; return name; } bool find_not_null_fields(table_map allowed) override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool eval_not_null_tables(void *) override { not_null_tables_cache= 0; return false; } }; /** This Item represents a X IS FALSE boolean predicate. */ class Item_func_isfalse : public Item_func_truth { public: Item_func_isfalse(THD *thd, Item *a): Item_func_truth(thd, a, false, true) {} ~Item_func_isfalse() = default; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("isfalse") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** This Item represents a X IS NOT FALSE boolean predicate. */ class Item_func_isnotfalse : public Item_func_truth { public: Item_func_isnotfalse(THD *thd, Item *a): Item_func_truth(thd, a, false, false) {} ~Item_func_isnotfalse() = default; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("isnotfalse") }; return name; } bool find_not_null_fields(table_map allowed) override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } bool eval_not_null_tables(void *) override { not_null_tables_cache= 0; return false; } }; class Item_cache; #define UNKNOWN (-1) /* Item_in_optimizer(left_expr, Item_in_subselect(...)) Item_in_optimizer is used to wrap an instance of Item_in_subselect. This class does the following: - Evaluate the left expression and store it in Item_cache_* object (to avoid re-evaluating it many times during subquery execution) - Shortcut the evaluation of "NULL IN (...)" to NULL in the cases where we don't care if the result is NULL or FALSE. NOTE It is not quite clear why the above listed functionality should be placed into a separate class called 'Item_in_optimizer'. */ class Item_in_optimizer: public Item_bool_func { protected: Item_cache *cache; Item *expr_cache; /* Stores the value of "NULL IN (SELECT ...)" for uncorrelated subqueries: UNKNOWN - "NULL in (SELECT ...)" has not yet been evaluated FALSE - result is FALSE TRUE - result is NULL */ int result_for_null_param; public: Item_in_optimizer(THD *thd, Item *a, Item *b): Item_bool_func(thd, a, b), cache(0), expr_cache(0), result_for_null_param(UNKNOWN) { with_flags|= item_with_t::SUBQUERY; } bool fix_fields(THD *, Item **) override; bool fix_left(THD *thd); table_map not_null_tables() const override { return 0; } bool is_null() override; bool val_bool() override; void cleanup() override; enum Functype functype() const override { return IN_OPTIMIZER_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } Item_cache **get_cache() { return &cache; } Item *transform(THD *thd, Item_transformer transformer, uchar *arg) override; Item *expr_cache_insert_transformer(THD *thd, uchar *unused) override; bool is_expensive_processor(void *arg) override; bool is_expensive() override; void set_join_tab_idx(uint8 join_tab_idx_arg) override { args[1]->set_join_tab_idx(join_tab_idx_arg); } void get_cache_parameters(List ¶meters) override; bool is_top_level_item() const override; bool eval_not_null_tables(void *opt_arg) override; bool find_not_null_fields(table_map allowed) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; bool invisible_mode(); bool walk(Item_processor processor, bool walk_subquery, void *arg) override; void reset_cache() { cache= NULL; } void print(String *str, enum_query_type query_type) override; void restore_first_argument(); Item* get_wrapped_in_subselect_item() { return args[1]; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } enum precedence precedence() const override { return args[1]->precedence(); } }; /* Functions and operators with two arguments that can use range optimizer. */ class Item_bool_func2 :public Item_bool_func { /* Bool with 2 string args */ protected: void add_key_fields_optimize_op(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables, bool equal_func); public: Item_bool_func2(THD *thd, Item *a, Item *b): Item_bool_func(thd, a, b) { } bool is_null() override { return MY_TEST(args[0]->is_null() || args[1]->is_null()); } COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, bool top_level) override; bool count_sargable_conds(void *arg) override; /* Specifies which result type the function uses to compare its arguments. This method is used in equal field propagation. */ virtual const Type_handler *compare_type_handler() const { /* Have STRING_RESULT by default, which means the function compares val_str() results of the arguments. This is suitable for Item_func_like and for Item_func_spatial_rel. Note, Item_bool_rowready_func2 overrides this default behaviour. */ return &type_handler_varchar; } SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override { DBUG_ENTER("Item_bool_func2::get_mm_tree"); DBUG_ASSERT(arg_count == 2); SEL_TREE *ftree= get_full_func_mm_tree_for_args(param, args[0], args[1]); if (!ftree) ftree= Item_func::get_mm_tree(param, cond_ptr); DBUG_RETURN(ftree); } }; /** A class for functions and operators that can use the range optimizer and have a reverse function/operator that can also use the range optimizer, so this condition: WHERE value OP field can be optimized as equivalent to: WHERE field REV_OP value This class covers: - scalar comparison predicates: <, <=, =, <=>, >=, > - MBR and precise spatial relation predicates (e.g. SP_TOUCHES(x,y)) For example: WHERE 10 > field can be optimized as: WHERE field < 10 */ class Item_bool_func2_with_rev :public Item_bool_func2 { protected: SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) override { DBUG_ENTER("Item_bool_func2_with_rev::get_func_mm_tree"); Item_func::Functype func_type= (value != arguments()[0]) ? functype() : rev_functype(); DBUG_RETURN(get_mm_parts(param, field, func_type, value)); } public: Item_bool_func2_with_rev(THD *thd, Item *a, Item *b): Item_bool_func2(thd, a, b) { } virtual enum Functype rev_functype() const= 0; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override { DBUG_ENTER("Item_bool_func2_with_rev::get_mm_tree"); DBUG_ASSERT(arg_count == 2); SEL_TREE *ftree; /* Even if get_full_func_mm_tree_for_args(param, args[0], args[1]) will not return a range predicate it may still be possible to create one by reversing the order of the operands. Note that this only applies to predicates where both operands are fields. Example: A query of the form WHERE t1.a OP t2.b In this case, args[0] == t1.a and args[1] == t2.b. When creating range predicates for t2, get_full_func_mm_tree_for_args(param, args[0], args[1]) will return NULL because 'field' belongs to t1 and only predicates that applies to t2 are of interest. In this case a call to get_full_func_mm_tree_for_args() with reversed operands may succeed. */ if (!(ftree= get_full_func_mm_tree_for_args(param, args[0], args[1])) && !(ftree= get_full_func_mm_tree_for_args(param, args[1], args[0]))) ftree= Item_func::get_mm_tree(param, cond_ptr); DBUG_RETURN(ftree); } }; class Item_bool_rowready_func2 :public Item_bool_func2_with_rev { protected: Arg_comparator cmp; bool check_arguments() const override { return check_argument_types_like_args0(); } public: Item_bool_rowready_func2(THD *thd, Item *a, Item *b): Item_bool_func2_with_rev(thd, a, b), cmp(tmp_arg, tmp_arg + 1) { } Sql_mode_dependency value_depends_on_sql_mode() const override; void print(String *str, enum_query_type query_type) override { Item_func::print_op(str, query_type); } enum precedence precedence() const override { return CMP_PRECEDENCE; } Item *neg_transformer(THD *thd) override; virtual Item *negated_item(THD *thd); Item *propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { Item_args::propagate_equal_fields(thd, Context(ANY_SUBST, cmp.compare_type_handler(), compare_collation()), cond); return this; } bool fix_length_and_dec() override; bool fix_length_and_dec_generic(THD *thd, const Type_handler *compare_handler) { DBUG_ASSERT(args == tmp_arg); return cmp.set_cmp_func(thd, this, compare_handler, tmp_arg, tmp_arg + 1, true/*set_null*/); } int set_cmp_func(THD *thd) { DBUG_ASSERT(args == tmp_arg); return cmp.set_cmp_func(thd, this, tmp_arg, tmp_arg + 1, true/*set_null*/); } CHARSET_INFO *compare_collation() const override { return cmp.compare_collation(); } const Type_handler *compare_type_handler() const override { return cmp.compare_type_handler(); } Arg_comparator *get_comparator() { return &cmp; } void cleanup() override { Item_bool_func2::cleanup(); cmp.cleanup(); } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override { return add_key_fields_optimize_op(join, key_fields, and_level, usable_tables, sargables, false); } Item *do_build_clone(THD *thd) const override { Item_bool_rowready_func2 *clone= (Item_bool_rowready_func2 *) Item_func::do_build_clone(thd); if (clone) { clone->cmp.comparators= 0; } return clone; } }; /** XOR inherits from Item_bool_func because it is not optimized yet. Later, when XOR is optimized, it needs to inherit from Item_cond instead. See WL#5800. */ class Item_func_xor :public Item_bool_func { public: Item_func_xor(THD *thd, Item *i1, Item *i2): Item_bool_func(thd, i1, i2) {} enum Functype functype() const override { return XOR_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("xor") }; return name; } enum precedence precedence() const override { return XOR_PRECEDENCE; } void print(String *str, enum_query_type query_type) override { Item_func::print_op(str, query_type); } bool val_bool() override; bool find_not_null_fields(table_map allowed) override { return false; } Item *neg_transformer(THD *thd) override; Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { Item_args::propagate_equal_fields(thd, Context_boolean(), cond); return this; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_not :public Item_bool_func { bool abort_on_null; public: Item_func_not(THD *thd, Item *a): Item_bool_func(thd, a), abort_on_null(FALSE) {} void top_level_item() override { abort_on_null= 1; } bool is_top_level_item() const override { return abort_on_null; } bool val_bool() override; enum Functype functype() const override { return NOT_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("not") }; return name; } bool find_not_null_fields(table_map allowed) override { return false; } enum precedence precedence() const override { return NEG_PRECEDENCE; } Item *neg_transformer(THD *thd) override; bool fix_fields(THD *, Item **) override; void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_maxmin_subselect; /* trigcond(arg) ::= param? arg : TRUE The class Item_func_trig_cond is used for guarded predicates which are employed only for internal purposes. A guarded predicate is an object consisting of an a regular or a guarded predicate P and a pointer to a boolean guard variable g. A guarded predicate P/g is evaluated to true if the value of the guard g is false, otherwise it is evaluated to the same value that the predicate P: val(P/g)= g ? val(P):true. Guarded predicates allow us to include predicates into a conjunction conditionally. Currently they are utilized for pushed down predicates in queries with outer join operations. In the future, probably, it makes sense to extend this class to the objects consisting of three elements: a predicate P, a pointer to a variable g and a firing value s with following evaluation rule: val(P/g,s)= g==s? val(P) : true. It will allow us to build only one item for the objects of the form P/g1/g2... Objects of this class are built only for query execution after the execution plan has been already selected. That's why this class needs only val_int out of generic methods. Current uses of Item_func_trig_cond objects: - To wrap selection conditions when executing outer joins - To wrap condition that is pushed down into subquery */ class Item_func_trig_cond: public Item_bool_func { bool *trig_var; public: Item_func_trig_cond(THD *thd, Item *a, bool *f): Item_bool_func(thd, a) { trig_var= f; } bool val_bool() override { return *trig_var ? args[0]->val_bool() : true; } enum Functype functype() const override { return TRIG_COND_FUNC; }; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("trigcond") }; return name; } bool const_item() const override { return FALSE; } bool *get_trig_var() { return trig_var; } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_not_all :public Item_func_not { /* allow to check presence of values in max/min optimization */ Item_sum_min_max *test_sum_item; Item_maxmin_subselect *test_sub_item; public: bool show; Item_func_not_all(THD *thd, Item *a): Item_func_not(thd, a), test_sum_item(0), test_sub_item(0), show(0) {} table_map not_null_tables() const override { return 0; } bool val_bool() override; enum Functype functype() const override { return NOT_ALL_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } enum precedence precedence() const override { return show ? Item_func::precedence() : args[0]->precedence(); } bool fix_fields(THD *thd, Item **ref) override { return Item_func::fix_fields(thd, ref);} void print(String *str, enum_query_type query_type) override; void set_sum_test(Item_sum_min_max *item) { test_sum_item= item; test_sub_item= 0; }; void set_sub_test(Item_maxmin_subselect *item) { test_sub_item= item; test_sum_item= 0;}; bool empty_underlying_subquery(); Item *neg_transformer(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_nop_all :public Item_func_not_all { public: Item_func_nop_all(THD *thd, Item *a): Item_func_not_all(thd, a) {} bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } Item *neg_transformer(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_eq :public Item_bool_rowready_func2 { bool abort_on_null; public: Item_func_eq(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b), abort_on_null(false), in_equality_no(UINT_MAX) {} bool val_bool() override; enum Functype functype() const override { return EQ_FUNC; } enum Functype rev_functype() const override { return EQ_FUNC; } cond_result eq_cmp_result() const override { return COND_TRUE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("=") }; return name; } void top_level_item() override { abort_on_null= true; } Item *negated_item(THD *thd) override; COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override; void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override { return add_key_fields_optimize_op(join, key_fields, and_level, usable_tables, sargables, true); } bool check_equality(THD *thd, COND_EQUAL *cond, List *eq_list) override; /* - If this equality is created from the subquery's IN-equality: number of the item it was created from, e.g. for (a,b) IN (SELECT c,d ...) a=c will have in_equality_no=0, and b=d will have in_equality_no=1. - Otherwise, UINT_MAX */ uint in_equality_no; uint exists2in_reserved_items() override { return 1; }; friend class Arg_comparator; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override; }; class Item_func_equal final :public Item_bool_rowready_func2 { public: Item_func_equal(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b) {} bool val_bool() override; bool fix_length_and_dec() override; table_map not_null_tables() const override { return 0; } bool find_not_null_fields(table_map allowed) override { return false; } enum Functype functype() const override { return EQUAL_FUNC; } enum Functype rev_functype() const override { return EQUAL_FUNC; } cond_result eq_cmp_result() const override { return COND_TRUE; } bool is_null() override { return false; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("<=>") }; return name; } Item *neg_transformer(THD *thd) override { return 0; } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override { return add_key_fields_optimize_op(join, key_fields, and_level, usable_tables, sargables, true); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ge :public Item_bool_rowready_func2 { public: Item_func_ge(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b) {}; bool val_bool() override; enum Functype functype() const override { return GE_FUNC; } enum Functype rev_functype() const override { return LE_FUNC; } cond_result eq_cmp_result() const override { return COND_TRUE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN(">=") }; return name; } Item *negated_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_gt :public Item_bool_rowready_func2 { public: Item_func_gt(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b) {}; bool val_bool() override; enum Functype functype() const override { return GT_FUNC; } enum Functype rev_functype() const override { return LT_FUNC; } cond_result eq_cmp_result() const override { return COND_FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN(">") }; return name; } Item *negated_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_le :public Item_bool_rowready_func2 { public: Item_func_le(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b) {}; bool val_bool() override; enum Functype functype() const override { return LE_FUNC; } enum Functype rev_functype() const override { return GE_FUNC; } cond_result eq_cmp_result() const override { return COND_TRUE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("<=") }; return name; } Item *negated_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_lt :public Item_bool_rowready_func2 { public: Item_func_lt(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b) {} bool val_bool() override; enum Functype functype() const override { return LT_FUNC; } enum Functype rev_functype() const override { return GT_FUNC; } cond_result eq_cmp_result() const override { return COND_FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("<") }; return name; } Item *negated_item(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ne :public Item_bool_rowready_func2 { protected: SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) override; public: Item_func_ne(THD *thd, Item *a, Item *b): Item_bool_rowready_func2(thd, a, b) {} bool val_bool() override; enum Functype functype() const override { return NE_FUNC; } enum Functype rev_functype() const override { return NE_FUNC; } cond_result eq_cmp_result() const override { return COND_FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("<>") }; return name; } Item *negated_item(THD *thd) override; void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* The class Item_func_opt_neg is defined to factor out the functionality common for the classes Item_func_between and Item_func_in. The objects of these classes can express predicates or there negations. The alternative approach would be to create pairs Item_func_between, Item_func_notbetween and Item_func_in, Item_func_notin. */ class Item_func_opt_neg :public Item_bool_func { protected: /* The data type handler that will be used for comparison. Data type handlers of all arguments are mixed to here. */ Type_handler_hybrid_field_type m_comparator; /* The collation that will be used for comparison in case when m_compare_type is STRING_RESULT. */ DTCollation cmp_collation; public: bool negated; /* <=> the item represents NOT */ bool pred_level; /* <=> [NOT] is used on a predicate level */ public: Item_func_opt_neg(THD *thd, Item *a, Item *b, Item *c): Item_bool_func(thd, a, b, c), negated(0), pred_level(0) {} Item_func_opt_neg(THD *thd, List &list): Item_bool_func(thd, list), negated(0), pred_level(0) {} public: void top_level_item() override { pred_level= 1; } bool is_top_level_item() const override { return pred_level; } Item *neg_transformer(THD *thd) override { negated= !negated; return this; } bool eq(const Item *item, bool binary_cmp) const override; CHARSET_INFO *compare_collation() const override { return cmp_collation.collation; } Item *propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override= 0; }; class Item_func_between :public Item_func_opt_neg { protected: SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) override; bool val_int_cmp_int_finalize(longlong value, longlong a, longlong b); public: String value0,value1,value2; Item_func_between(THD *thd, Item *a, Item *b, Item *c): Item_func_opt_neg(thd, a, b, c) { } bool val_bool() override { DBUG_ASSERT(fixed()); return m_comparator.type_handler()->Item_func_between_val_int(this); } enum Functype functype() const override { return BETWEEN; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("between") }; return name; } enum precedence precedence() const override { return BETWEEN_PRECEDENCE; } bool fix_length_and_dec() override; bool fix_length_and_dec_string(THD *) { return agg_arg_charsets_for_comparison(cmp_collation, args, 3); } bool fix_length_and_dec_temporal(THD *); bool fix_length_and_dec_numeric(THD *); void print(String *str, enum_query_type query_type) override; bool eval_not_null_tables(void *opt_arg) override; bool find_not_null_fields(table_map allowed) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; bool count_sargable_conds(void *arg) override; void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override; Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { Item_args::propagate_equal_fields(thd, Context(ANY_SUBST, m_comparator.type_handler(), compare_collation()), cond); return this; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } longlong val_int_cmp_string(); longlong val_int_cmp_datetime(); longlong val_int_cmp_time(); longlong val_int_cmp_native(); longlong val_int_cmp_int(); longlong val_int_cmp_real(); longlong val_int_cmp_decimal(); }; class Item_func_strcmp :public Item_long_func { bool check_arguments() const override { return check_argument_types_can_return_str(0, 2); } String value1, value2; DTCollation cmp_collation; public: Item_func_strcmp(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} longlong val_int() override; decimal_digits_t decimal_precision() const override { return 1; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("strcmp") }; return name; } bool fix_length_and_dec() override { if (agg_arg_charsets_for_comparison(cmp_collation, args, 2)) return TRUE; fix_char_length(2); // returns "1" or "0" or "-1" return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; struct interval_range { Item_result type; double dbl; my_decimal dec; }; class Item_func_interval :public Item_long_func { Item_row *row; bool use_decimal_comparison; interval_range *intervals; bool check_arguments() const override { return check_argument_types_like_args0(); } public: Item_func_interval(THD *thd, Item_row *a): Item_long_func(thd, a), row(a), intervals(0) { } longlong val_int() override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("interval") }; return name; } decimal_digits_t decimal_precision() const override { return 2; } void print(String *str, enum_query_type query_type) override { str->append(func_name_cstring()); print_args(str, 0, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_coalesce :public Item_func_case_expression { public: Item_func_coalesce(THD *thd, Item *a, Item *b): Item_func_case_expression(thd, a, b) {} Item_func_coalesce(THD *thd, List &list): Item_func_case_expression(thd, list) {} double real_op() override; longlong int_op() override; String *str_op(String *) override; my_decimal *decimal_op(my_decimal *) override; bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; bool native_op(THD *thd, Native *to) override; bool fix_length_and_dec() override { if (aggregate_for_result(func_name_cstring(), args, arg_count, true)) return TRUE; fix_attributes(args, arg_count); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("coalesce") }; return name; } table_map not_null_tables() const override { return 0; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Case abbreviations that aggregate its result field type by two arguments: IFNULL(arg1, arg2) IF(switch, arg1, arg2) NVL2(switch, arg1, arg2) */ class Item_func_case_abbreviation2 :public Item_func_case_expression { protected: bool fix_length_and_dec2(Item **items) { if (aggregate_for_result(func_name_cstring(), items, 2, true)) return TRUE; fix_attributes(items, 2); return FALSE; } void cache_type_info(const Item *source, bool maybe_null_arg) { Type_std_attributes::set(source); set_handler(source->type_handler()); set_maybe_null(maybe_null_arg); } bool fix_length_and_dec2_eliminate_null(Item **items) { // Let IF(cond, expr, NULL) and IF(cond, NULL, expr) inherit type from expr. if (items[0]->type() == NULL_ITEM) { cache_type_info(items[1], true); // If both arguments are NULL, make resulting type BINARY(0). if (items[1]->type() == NULL_ITEM) set_handler(&type_handler_string); } else if (items[1]->type() == NULL_ITEM) { cache_type_info(items[0], true); } else { if (fix_length_and_dec2(items)) return TRUE; } return FALSE; } public: Item_func_case_abbreviation2(THD *thd, Item *a, Item *b): Item_func_case_expression(thd, a, b) { } Item_func_case_abbreviation2(THD *thd, Item *a, Item *b, Item *c): Item_func_case_expression(thd, a, b, c) { } }; class Item_func_ifnull :public Item_func_case_abbreviation2 { public: Item_func_ifnull(THD *thd, Item *a, Item *b): Item_func_case_abbreviation2(thd, a, b) {} double real_op() override; longlong int_op() override; String *str_op(String *str) override; my_decimal *decimal_op(my_decimal *) override; bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; bool native_op(THD *thd, Native *to) override; bool fix_length_and_dec() override { /* Set nullability from args[1] by default. Note, some type handlers may reset maybe_null in Item_hybrid_func_fix_attributes() if args[1] is NOT NULL but cannot always be converted to the data type of "this" safely. E.g. Type_handler_inet6 does: IFNULL(inet6_not_null_expr, 'foo') -> INET6 NULL IFNULL(inet6_not_null_expr, '::1') -> INET6 NOT NULL */ copy_flags(args[1], item_base_t::MAYBE_NULL); if (Item_func_case_abbreviation2::fix_length_and_dec2(args)) return TRUE; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ifnull") }; return name; } table_map not_null_tables() const override { return 0; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** Case abbreviations that have a switch argument and two return arguments to choose from. Returns the value of either of the two return arguments depending on the switch argument value. IF(switch, arg1, arg2) NVL(switch, arg1, arg2) */ class Item_func_case_abbreviation2_switch: public Item_func_case_abbreviation2 { protected: virtual Item *find_item() const= 0; public: Item_func_case_abbreviation2_switch(THD *thd, Item *a, Item *b, Item *c) :Item_func_case_abbreviation2(thd, a, b, c) { } bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { Datetime_truncation_not_needed dt(thd, find_item(), fuzzydate); return (null_value= dt.copy_to_mysql_time(ltime, mysql_timestamp_type())); } bool time_op(THD *thd, MYSQL_TIME *ltime) override { return (null_value= Time(find_item()).copy_to_mysql_time(ltime)); } longlong int_op() override { return val_int_from_item(find_item()); } double real_op() override { return val_real_from_item(find_item()); } my_decimal *decimal_op(my_decimal *decimal_value) override { return val_decimal_from_item(find_item(), decimal_value); } String *str_op(String *str) override { return val_str_from_item(find_item(), str); } bool native_op(THD *thd, Native *to) override { return val_native_with_conversion_from_item(thd, find_item(), to, type_handler()); } }; class Item_func_if :public Item_func_case_abbreviation2_switch { protected: Item *find_item() const override { return args[0]->val_bool() ? args[1] : args[2]; } public: Item_func_if(THD *thd, Item *a, Item *b, Item *c): Item_func_case_abbreviation2_switch(thd, a, b, c) {} bool fix_fields(THD *, Item **) override; bool fix_length_and_dec() override { return fix_length_and_dec2_eliminate_null(args + 1); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("if") }; return name; } bool eval_not_null_tables(void *opt_arg) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } private: void cache_type_info(Item *source); }; class Item_func_nvl2 :public Item_func_case_abbreviation2_switch { protected: Item *find_item() const override { return args[0]->is_null() ? args[2] : args[1]; } public: Item_func_nvl2(THD *thd, Item *a, Item *b, Item *c): Item_func_case_abbreviation2_switch(thd, a, b, c) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("nvl2") }; return name; } bool fix_length_and_dec() override { return fix_length_and_dec2_eliminate_null(args + 1); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_nullif :public Item_func_case_expression { Arg_comparator cmp; /* NULLIF(a,b) is a short for: CASE WHEN a=b THEN NULL ELSE a END The left "a" is for comparison purposes. The right "a" is for return value purposes. These are two different "a" and they can be replaced to different items. The left "a" is in a comparison and can be replaced by: - Item_func::convert_const_compared_to_int_field() - agg_item_set_converter() in set_cmp_func() - cache_converted_constant() in set_cmp_func() Both "a"s are subject to equal fields propagation and can be replaced by: - Item_field::propagate_equal_fields(ANY_SUBST) for the left "a" - Item_field::propagate_equal_fields(IDENTITY_SUBST) for the right "a" */ Item_cache *m_cache; int compare(); void reset_first_arg_if_needed() { if (arg_count == 3 && args[0] != args[2]) args[0]= args[2]; } Item *m_arg0; public: /* Here we pass three arguments to the parent constructor, as NULLIF is a three-argument function, it needs two copies of the first argument (see above). But fix_fields() will be confused if we try to prepare the same Item twice (if args[0]==args[2]), so we hide the third argument (decrementing arg_count) and copy args[2]=args[0] again after fix_fields(). See also Item_func_nullif::fix_length_and_dec(). */ Item_func_nullif(THD *thd, Item *a, Item *b): Item_func_case_expression(thd, a, b, a), m_cache(NULL), m_arg0(NULL) { arg_count--; } void cleanup() override { Item_func_hybrid_field_type::cleanup(); arg_count= 2; // See the comment to the constructor } bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; double real_op() override; longlong int_op() override; String *str_op(String *str) override; my_decimal *decimal_op(my_decimal *) override; bool native_op(THD *thd, Native *to) override; bool fix_length_and_dec() override; bool walk(Item_processor processor, bool walk_subquery, void *arg) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("nullif") }; return name; } void print(String *str, enum_query_type query_type) override; void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) override; void update_used_tables() override; table_map not_null_tables() const override { return 0; } bool is_null() override; Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { Context cmpctx(ANY_SUBST, cmp.compare_type_handler(), cmp.compare_collation()); const Item *old0= args[0]; args[0]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, cond, &args[0]); args[1]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, cond, &args[1]); /* MDEV-9712 Performance degradation of nested NULLIF ANY_SUBST is more relaxed than IDENTITY_SUBST. If ANY_SUBST did not change args[0], then we can skip propagation for args[2]. */ if (old0 != args[0]) args[2]->propagate_equal_fields_and_change_item_tree(thd, Context_identity(), cond, &args[2]); return this; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *derived_field_transformer_for_having(THD *thd, uchar *arg) override { reset_first_arg_if_needed(); return this; } Item *derived_field_transformer_for_where(THD *thd, uchar *arg) override { reset_first_arg_if_needed(); return this; } Item *grouping_field_transformer_for_where(THD *thd, uchar *arg) override { reset_first_arg_if_needed(); return this; } Item *in_subq_field_transformer_for_where(THD *thd, uchar *arg) override { reset_first_arg_if_needed(); return this; } Item *in_subq_field_transformer_for_having(THD *thd, uchar *arg) override { reset_first_arg_if_needed(); return this; } }; /* Functions to handle the optimized IN */ /* A vector of values of some type */ class in_vector :public Sql_alloc { public: char *base; uint size; qsort_cmp2 compare; CHARSET_INFO *collation; uint count; uint used_count; in_vector() = default; in_vector(THD *thd, uint elements, uint element_length, qsort_cmp2 cmp_func, CHARSET_INFO *cmp_coll) :base((char*) thd_calloc(thd, elements * element_length)), size(element_length), compare(cmp_func), collation(cmp_coll), count(elements), used_count(elements) {} virtual ~in_vector() = default; /* Store an Item value at the given position. @returns false - the Item was not NULL, and the conversion from the Item data type to the cmp_item data type went without errors @returns true - the Item was NULL, or data type conversion returned NULL */ virtual bool set(uint pos, Item *item)=0; virtual uchar *get_value(Item *item)=0; void sort() { my_qsort2(base,used_count,size,compare,(void*)collation); } bool find(Item *item); /* Create an instance of Item_{type} (e.g. Item_decimal) constant object which type allows it to hold an element of this vector without any conversions. The purpose of this function is to be able to get elements of this vector in form of Item_xxx constants without creating Item_xxx object for every array element you get (i.e. this implements "FlyWeight" pattern) */ virtual Item* create_item(THD *thd) { return NULL; } /* Store the value at position #pos into provided item object SYNOPSIS value_to_item() pos Index of value to store item Constant item to store value into. The item must be of the same type that create_item() returns. */ virtual void value_to_item(uint pos, Item *item) { } /* Compare values number pos1 and pos2 for equality */ bool compare_elems(uint pos1, uint pos2) { return MY_TEST(compare(const_cast(collation), base + pos1 * size, base + pos2 * size)); } virtual const Type_handler *type_handler() const= 0; }; class in_string :public in_vector { char buff[STRING_BUFFER_USUAL_SIZE]; String tmp; class Item_string_for_in_vector: public Item_string { public: Item_string_for_in_vector(THD *thd, CHARSET_INFO *cs): Item_string(thd, cs) { } void set_value(const String *str) { str_value= *str; collation.set(str->charset()); } }; public: in_string(THD *thd, uint elements, qsort_cmp2 cmp_func, CHARSET_INFO *cs); ~in_string(); bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; Item* create_item(THD *thd) override; void value_to_item(uint pos, Item *item) override { String *str=((String*) base)+pos; Item_string_for_in_vector *to= (Item_string_for_in_vector*) item; to->set_value(str); } const Type_handler *type_handler() const override { return &type_handler_varchar; } }; class in_longlong :public in_vector { protected: /* Here we declare a temporary variable (tmp) of the same type as the elements of this vector. tmp is used in finding if a given value is in the list. */ struct packed_longlong { longlong val; longlong unsigned_flag; // Use longlong, not bool, to preserve alignment } tmp; public: in_longlong(THD *thd, uint elements); bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; Item* create_item(THD *thd) override; void value_to_item(uint pos, Item *item) override { ((Item_int*) item)->value= ((packed_longlong*) base)[pos].val; ((Item_int*) item)->unsigned_flag= (bool) ((packed_longlong*) base)[pos].unsigned_flag; } const Type_handler *type_handler() const override { return &type_handler_slonglong; } friend int cmp_longlong(void *cmp_arg, const void *a, const void *b); }; class in_timestamp :public in_vector { Timestamp_or_zero_datetime tmp; public: in_timestamp(THD *thd, uint elements); bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; Item* create_item(THD *thd) override; void value_to_item(uint pos, Item *item) override; const Type_handler *type_handler() const override { return &type_handler_timestamp2; } }; /* Class to represent a vector of constant DATE/DATETIME values. */ class in_temporal :public in_longlong { public: /* Cache for the left item. */ in_temporal(THD *thd, uint elements) :in_longlong(thd, elements) {}; Item *create_item(THD *thd) override; void value_to_item(uint pos, Item *item) override { packed_longlong *val= reinterpret_cast(base)+pos; Item_datetime *dt= static_cast(item); dt->set(val->val, type_handler()->mysql_timestamp_type()); } friend int cmp_longlong(void *cmp_arg, const void *a, const void *b); }; class in_datetime :public in_temporal { public: in_datetime(THD *thd, uint elements) :in_temporal(thd, elements) {} bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; const Type_handler *type_handler() const override { return &type_handler_datetime2; } }; class in_time :public in_temporal { public: in_time(THD *thd, uint elements) :in_temporal(thd, elements) {} bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; const Type_handler *type_handler() const override { return &type_handler_time2; } }; class in_double :public in_vector { double tmp; public: in_double(THD *thd, uint elements); bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; Item *create_item(THD *thd) override; void value_to_item(uint pos, Item *item) override { ((Item_float*)item)->value= ((double*) base)[pos]; } const Type_handler *type_handler() const override { return &type_handler_double; } }; class in_decimal :public in_vector { my_decimal val; public: in_decimal(THD *thd, uint elements); bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; Item *create_item(THD *thd) override; void value_to_item(uint pos, Item *item) override { my_decimal *dec= ((my_decimal *)base) + pos; Item_decimal *item_dec= (Item_decimal*)item; item_dec->set_decimal_value(dec); } const Type_handler *type_handler() const override { return &type_handler_newdecimal; } }; /* ** Classes for easy comparing of non const items */ class cmp_item :public Sql_alloc { public: CHARSET_INFO *cmp_charset; cmp_item() { cmp_charset= &my_charset_bin; } virtual ~cmp_item() = default; virtual void store_value(Item *item)= 0; /** @returns result (TRUE, FALSE or UNKNOWN) of "stored argument's value <> item's value" */ virtual int cmp(Item *item)= 0; virtual int cmp_not_null(const Value *value)= 0; // for optimized IN with row virtual int compare(const cmp_item *item) const= 0; virtual cmp_item *make_same(THD *thd)= 0; /* Store a scalar or a ROW value into "this". @returns false - the value (or every component in case of ROW) was not NULL and the data type conversion went without errors. @returns true - the value (or some of its components) was NULL, or the data type conversion of a not-NULL value returned NULL. */ virtual bool store_value_by_template(THD *thd, cmp_item *tmpl, Item *item)=0; }; /// cmp_item which stores a scalar (i.e. non-ROW). class cmp_item_scalar : public cmp_item { protected: bool m_null_value; ///< If stored value is NULL bool store_value_by_template(THD *thd, cmp_item *tmpl, Item *item) override { store_value(item); return m_null_value; } }; class cmp_item_string : public cmp_item_scalar { protected: String *value_res; public: cmp_item_string () = default; cmp_item_string (CHARSET_INFO *cs) { cmp_charset= cs; } void set_charset(CHARSET_INFO *cs) { cmp_charset= cs; } friend class cmp_item_sort_string; friend class cmp_item_sort_string_in_static; }; class cmp_item_sort_string :public cmp_item_string { protected: char value_buff[STRING_BUFFER_USUAL_SIZE]; String value; public: cmp_item_sort_string(): cmp_item_string() {} cmp_item_sort_string(CHARSET_INFO *cs): cmp_item_string(cs), value(value_buff, sizeof(value_buff), cs) {} void store_value(Item *item) override { value_res= item->val_str(&value); m_null_value= item->null_value; // Make sure to cache the result String inside "value" if (value_res && value_res != &value) { if (value.copy(*value_res)) value.set("", 0, item->collation.collation); value_res= &value; } } int cmp_not_null(const Value *val) override { DBUG_ASSERT(!val->is_null()); DBUG_ASSERT(val->is_string()); return sortcmp(value_res, &val->m_string, cmp_charset) != 0; } int cmp(Item *arg) override { char buff[STRING_BUFFER_USUAL_SIZE]; String tmp(buff, sizeof(buff), cmp_charset), *res= arg->val_str(&tmp); if (m_null_value || arg->null_value) return UNKNOWN; if (value_res && res) return sortcmp(value_res, res, cmp_charset) != 0; else if (!value_res && !res) return FALSE; else return TRUE; } int compare(const cmp_item *ci) const override { cmp_item_string *l_cmp= (cmp_item_string *) ci; return sortcmp(value_res, l_cmp->value_res, cmp_charset); } cmp_item *make_same(THD *thd) override; void set_charset(CHARSET_INFO *cs) { cmp_charset= cs; value.set_buffer_if_not_allocated(value_buff, sizeof(value_buff), cs); } }; class cmp_item_int : public cmp_item_scalar { longlong value; public: cmp_item_int() = default; /* Remove gcc warning */ void store_value(Item *item) override { value= item->val_int(); m_null_value= item->null_value; } int cmp_not_null(const Value *val) override { DBUG_ASSERT(!val->is_null()); DBUG_ASSERT(val->is_longlong()); return value != val->value.m_longlong; } int cmp(Item *arg) override { const bool rc= value != arg->val_int(); return (m_null_value || arg->null_value) ? UNKNOWN : rc; } int compare(const cmp_item *ci) const override { cmp_item_int *l_cmp= (cmp_item_int *)ci; return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1); } cmp_item *make_same(THD *thd) override; }; /* Compare items in the DATETIME context. */ class cmp_item_temporal: public cmp_item_scalar { protected: longlong value; public: cmp_item_temporal() = default; int compare(const cmp_item *ci) const override; }; class cmp_item_datetime: public cmp_item_temporal { public: cmp_item_datetime() :cmp_item_temporal() { } void store_value(Item *item) override { value= item->val_datetime_packed(current_thd); m_null_value= item->null_value; } int cmp_not_null(const Value *val) override; int cmp(Item *arg) override; cmp_item *make_same(THD *thd) override; }; class cmp_item_time: public cmp_item_temporal { public: cmp_item_time() :cmp_item_temporal() { } void store_value(Item *item) override { value= item->val_time_packed(current_thd); m_null_value= item->null_value; } int cmp_not_null(const Value *val) override; int cmp(Item *arg) override; cmp_item *make_same(THD *thd) override; }; class cmp_item_timestamp: public cmp_item_scalar { Timestamp_or_zero_datetime_native m_native; public: cmp_item_timestamp() :cmp_item_scalar() { } void store_value(Item *item) override; int cmp_not_null(const Value *val) override; int cmp(Item *arg) override; int compare(const cmp_item *ci) const override; cmp_item *make_same(THD *thd) override; }; class cmp_item_real : public cmp_item_scalar { double value; public: cmp_item_real() = default; /* Remove gcc warning */ void store_value(Item *item) override { value= item->val_real(); m_null_value= item->null_value; } int cmp_not_null(const Value *val) override { DBUG_ASSERT(!val->is_null()); DBUG_ASSERT(val->is_double()); return value != val->value.m_double; } int cmp(Item *arg) override { const bool rc= value != arg->val_real(); return (m_null_value || arg->null_value) ? UNKNOWN : rc; } int compare(const cmp_item *ci) const override { cmp_item_real *l_cmp= (cmp_item_real *) ci; return (value < l_cmp->value)? -1 : ((value == l_cmp->value) ? 0 : 1); } cmp_item *make_same(THD *thd) override; }; class cmp_item_decimal : public cmp_item_scalar { my_decimal value; public: cmp_item_decimal() = default; /* Remove gcc warning */ void store_value(Item *item) override; int cmp(Item *arg) override; int cmp_not_null(const Value *val) override; int compare(const cmp_item *c) const override; cmp_item *make_same(THD *thd) override; }; /* cmp_item for optimized IN with row (right part string, which never be changed) */ class cmp_item_sort_string_in_static :public cmp_item_string { protected: String value; public: cmp_item_sort_string_in_static(CHARSET_INFO *cs): cmp_item_string(cs) {} void store_value(Item *item) override { value_res= item->val_str(&value); m_null_value= item->null_value; } int cmp_not_null(const Value *val) override { DBUG_ASSERT(false); return TRUE; } int cmp(Item *item) override { // Should never be called DBUG_ASSERT(false); return TRUE; } int compare(const cmp_item *ci) const override { cmp_item_string *l_cmp= (cmp_item_string *) ci; return sortcmp(value_res, l_cmp->value_res, cmp_charset); } cmp_item *make_same(THD *) override { return new cmp_item_sort_string_in_static(cmp_charset); } }; /** A helper class to handle situations when some item "pred" (the predicant) is consequently compared to a list of other items value0..valueN (the values). Currently used to handle: - pred IN (value0, value1, value2) - CASE pred WHEN value0 .. WHEN value1 .. WHEN value2 .. END Every pair {pred,valueN} can be compared by its own Type_handler. Some pairs can use the same Type_handler. In cases when all pairs use exactly the same Type_handler, we say "all types are compatible". For example, for an expression 1 IN (1, 1e0, 1.0, 2) - pred is 1 - value0 is 1 - value1 is 1e0 - value2 is 1.1 - value3 is 2 Pairs (pred,valueN) are compared as follows: N expr1 Type - ----- ---- 0 1 INT 1 1e0 DOUBLE 2 1.0 DECIMAL 3 2 INT Types are not compatible in this example. During add_value() calls, each pair {pred,valueN} is analysed: - If valueN is an explicit NULL, it can be ignored in the caller asks to do so - If valueN is not an explicit NULL (or if the caller didn't ask to skip NULLs), then the value add an element in the array m_comparators[]. Every element m_comparators[] stores the following information: 1. m_arg_index - the position of the value expression in the original argument array, e.g. in Item_func_in::args[] or Item_func_case::args[]. 2. m_handler - the pointer to the data type handler that the owner will use to compare the pair {args[m_predicate_index],args[m_arg_index]}. 3. m_handler_index - the index of an m_comparators[] element corresponding to the leftmost pair that uses exactly the same Type_handler for comparison. m_handler_index helps to maintain unique data type handlers. - m_comparators[i].m_handler_index==i means that this is the leftmost pair that uses the Type_handler m_handler for comparision. - If m_comparators[i].m_handlex_index!=i, it means that some earlier element m_comparators[jm_cmp_item; DBUG_ASSERT(in_item); /* If this is the leftmost pair that uses the data type handler pointed by m_comparators[i].m_handler, then we need to cache the predicant value representation used by this handler. */ if (m_comparators[i].m_handler_index == i) in_item->store_value(args->arguments()[m_predicant_index]); /* If the predicant item has null_value==true then: - In case of scalar expression we can returns UNKNOWN immediately. No needs to check the result of the value item. - In case of ROW, null_value==true means that *some* row elements returned NULL, but *some* elements can still be non-NULL! We need to get the result of the value item and test if non-NULL elements in the predicant and the value produce TRUE (not equal), or UNKNOWN. */ if (args->arguments()[m_predicant_index]->null_value && m_comparators[i].m_handler != &type_handler_row) return UNKNOWN; return in_item->cmp(args->arguments()[m_comparators[i].m_arg_index]); } int cmp_args_nulls_equal(THD *thd, Item_args *args, uint i) { Predicant_to_value_comparator *cmp= &m_comparators[m_comparators[i].m_handler_index]; cmp_item *in_item= cmp->m_cmp_item; DBUG_ASSERT(in_item); Item *predicant= args->arguments()[m_predicant_index]; Item *arg= args->arguments()[m_comparators[i].m_arg_index]; ValueBuffer val; if (m_comparators[i].m_handler_index == i) in_item->store_value(predicant); m_comparators[i].m_handler->Item_save_in_value(thd, arg, &val); if (predicant->null_value && val.is_null()) return FALSE; // Two nulls are equal if (predicant->null_value || val.is_null()) return UNKNOWN; return in_item->cmp_not_null(&val); } /** Predicant_to_value_comparator - a comparator for one pair (pred,valueN). See comments above. */ struct Predicant_to_value_comparator { const Type_handler *m_handler; cmp_item *m_cmp_item; uint m_arg_index; uint m_handler_index; void cleanup() { if (m_cmp_item) delete m_cmp_item; memset(this, 0, sizeof(*this)); } }; Predicant_to_value_comparator *m_comparators; // The comparator array uint m_comparator_count;// The number of elements in m_comparators[] uint m_predicant_index; // The position of the predicant in its argument list, // e.g. for Item_func_in m_predicant_index is 0, // as predicant is stored in Item_func_in::args[0]. // For Item_func_case m_predicant_index is // set to Item_func_case::first_expr_num. public: Predicant_to_list_comparator(THD *thd, uint nvalues) :m_comparator_count(0), m_predicant_index(0) { alloc_comparators(thd, nvalues); } uint comparator_count() const { return m_comparator_count; } const Type_handler *get_comparator_type_handler(uint i) const { DBUG_ASSERT(i < m_comparator_count); return m_comparators[i].m_handler; } uint get_comparator_arg_index(uint i) const { DBUG_ASSERT(i < m_comparator_count); return m_comparators[i].m_arg_index; } cmp_item *get_comparator_cmp_item(uint i) const { DBUG_ASSERT(i < m_comparator_count); return m_comparators[i].m_cmp_item; } #ifndef DBUG_OFF void debug_print(THD *thd) { for (uint i= 0; i < m_comparator_count; i++) { DBUG_EXECUTE_IF("Predicant_to_list_comparator", push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_UNKNOWN_ERROR, "DBUG: [%d] arg=%d handler=%d (%s)", i, m_comparators[i].m_arg_index, m_comparators[i].m_handler_index, m_comparators[m_comparators[i].m_handler_index]. m_handler->name().ptr());); } } #endif void add_predicant(Item_args *args, uint predicant_index) { DBUG_ASSERT(m_comparator_count == 0); // Set in constructor DBUG_ASSERT(m_predicant_index == 0); // Set in constructor DBUG_ASSERT(predicant_index < args->argument_count()); m_predicant_index= predicant_index; } /** Add a new element into m_comparators[], using a {pred,valueN} pair. @param funcname - the name of the operation, for error reporting @param args - the owner function's argument list @param value_index - the value position in args @retval true - could not add an element because of non-comparable arguments (e.g. ROWs with size) @retval false - a new element was successfully added. */ bool add_value(const LEX_CSTRING &funcname, Item_args *args, uint value_index); /** Add a new element into m_comparators[], ignoring explicit NULL values. If the value appeared to be an explicit NULL, nulls_found[0] is set to true. */ bool add_value_skip_null(const LEX_CSTRING &funcname, Item_args *args, uint value_index, bool *nulls_found); /** Signal "this" that there will be no new add_value*() calls, so it can prepare its internal structures for comparison. @param [OUT] compatible - If all comparators are compatible, their data type handler is returned here. @param [OUT] unuque_cnt - The number of unique data type handlers found. If the value returned in *unique_cnt is 0, it means all values were explicit NULLs: expr0 IN (NULL,NULL,..,NULL) @param [OUT] found_type - The bit mask for all found cmp_type()'s. */ void all_values_added(Type_handler_hybrid_field_type *compatible, uint *unique_cnt, uint *found_types) { detect_unique_handlers(compatible, unique_cnt, found_types); } /** Creates cmp_item instances for all unique handlers and stores them into m_comparators[].m_cmp_item, using the information previously populated by add_predicant(), add_value() and detect_unque_handlers(). */ bool make_unique_cmp_items(THD *thd, CHARSET_INFO *cs); void cleanup() { DBUG_ASSERT(m_comparators); for (uint i= 0; i < m_comparator_count; i++) m_comparators[i].cleanup(); memset(m_comparators, 0, sizeof(m_comparators[0]) * m_comparator_count); m_comparator_count= 0; m_predicant_index= 0; } bool init_clone(THD *thd, uint nvalues) { m_comparator_count= 0; m_predicant_index= 0; return alloc_comparators(thd, nvalues); } /** @param [IN] args - The argument list that was previously used with add_predicant() and add_value(). @param [OUT] idx - In case if a value that is equal to the predicant was found, the index of the matching value is returned here. Otherwise, *idx is not changed. @param [IN/OUT] found_unknown_values - how to handle UNKNOWN results. If found_unknown_values is NULL (e.g. Item_func_case), cmp() returns immediately when the first UNKNOWN result is found. If found_unknown_values is non-NULL (Item_func_in), cmp() does not return when an UNKNOWN result is found, sets *found_unknown_values to true, and continues to compare the remaining pairs to find FALSE (i.e. the value that is equal to the predicant). @retval false - Found a value that is equal to the predicant @retval true - Didn't find an equal value */ bool cmp(Item_args *args, uint *idx, bool *found_unknown_values) { for (uint i= 0 ; i < m_comparator_count ; i++) { DBUG_ASSERT(m_comparators[i].m_handler != NULL); const int rc= cmp_arg(args, i); if (rc == FALSE) { *idx= m_comparators[i].m_arg_index; return false; // Found a matching value } if (rc == UNKNOWN) { if (!found_unknown_values) return true; *found_unknown_values= true; } } return true; // Not found } /* Same as above, but treats two NULLs as equal, e.g. as in DECODE_ORACLE(). */ bool cmp_nulls_equal(THD *thd, Item_args *args, uint *idx) { for (uint i= 0 ; i < m_comparator_count ; i++) { DBUG_ASSERT(m_comparators[i].m_handler != NULL); if (cmp_args_nulls_equal(thd, args, i) == FALSE) { *idx= m_comparators[i].m_arg_index; return false; // Found a matching value } } return true; // Not found } }; /* The class Item_func_case is the CASE ... WHEN ... THEN ... END function implementation. */ class Item_func_case :public Item_func_case_expression { protected: String tmp_value; DTCollation cmp_collation; bool aggregate_then_and_else_arguments(THD *thd, uint count); virtual Item **else_expr_addr() const= 0; virtual Item *find_item()= 0; inline void print_when_then_arguments(String *str, enum_query_type query_type, Item **items, uint count); inline void print_else_argument(String *str, enum_query_type query_type, Item *item); void reorder_args(uint start); public: Item_func_case(THD *thd, List &list) :Item_func_case_expression(thd, list) { } double real_op() override; longlong int_op() override; String *str_op(String *) override; my_decimal *decimal_op(my_decimal *) override; bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool time_op(THD *thd, MYSQL_TIME *ltime) override; bool native_op(THD *thd, Native *to) override; bool fix_fields(THD *thd, Item **ref) override; table_map not_null_tables() const override { return 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("case") }; return name; } CHARSET_INFO *compare_collation() const { return cmp_collation.collation; } bool need_parentheses_in_default() override { return true; } }; /* CASE WHEN cond THEN res [WHEN cond THEN res...] [ELSE res] END Searched CASE checks all WHEN expressions one after another. When some WHEN expression evaluated to TRUE then the value of the corresponding THEN expression is returned. */ class Item_func_case_searched: public Item_func_case { uint when_count() const { return arg_count / 2; } bool with_else() const { return arg_count % 2; } Item **else_expr_addr() const override { return with_else() ? &args[arg_count - 1] : 0; } public: Item_func_case_searched(THD *thd, List &list) :Item_func_case(thd, list) { DBUG_ASSERT(arg_count >= 2); reorder_args(0); } enum Functype functype() const override { return CASE_SEARCHED_FUNC; } void print(String *str, enum_query_type query_type) override; bool fix_length_and_dec() override; Item *propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { // None of the arguments are in a comparison context Item_args::propagate_equal_fields(thd, Context_identity(), cond); return this; } Item *find_item() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* CASE pred WHEN value THEN res [WHEN value THEN res...] [ELSE res] END When the predicant expression is specified then it is compared to each WHEN expression individually. When an equal WHEN expression is found the corresponding THEN expression is returned. In order to do correct comparisons several comparators are used. One for each result type. Different result types that are used in particular CASE ... END expression are collected in the fix_length_and_dec() member function and only comparators for there result types are used. */ class Item_func_case_simple: public Item_func_case, public Predicant_to_list_comparator { protected: uint m_found_types; uint when_count() const { return (arg_count - 1) / 2; } bool with_else() const { return arg_count % 2 == 0; } Item **else_expr_addr() const override { return with_else() ? &args[arg_count - 1] : 0; } bool aggregate_switch_and_when_arguments(THD *thd, bool nulls_equal); bool prepare_predicant_and_values(THD *thd, uint *found_types, bool nulls_equal); public: Item_func_case_simple(THD *thd, List &list) :Item_func_case(thd, list), Predicant_to_list_comparator(thd, arg_count), m_found_types(0) { DBUG_ASSERT(arg_count >= 3); reorder_args(1); } void cleanup() override { DBUG_ENTER("Item_func_case_simple::cleanup"); Item_func::cleanup(); Predicant_to_list_comparator::cleanup(); DBUG_VOID_RETURN; } enum Functype functype() const override { return CASE_SIMPLE_FUNC; } void print(String *str, enum_query_type query_type) override; bool fix_length_and_dec() override; Item *propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override; Item *find_item() override; Item *do_build_clone(THD *thd) const override { Item_func_case_simple *clone= (Item_func_case_simple *) Item_func_case::do_build_clone(thd); uint ncases= when_count(); if (clone && clone->Predicant_to_list_comparator::init_clone(thd, ncases)) return NULL; return clone; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_decode_oracle: public Item_func_case_simple { public: Item_func_decode_oracle(THD *thd, List &list) :Item_func_case_simple(thd, list) { } const Schema *schema() const override { return &oracle_schema_ref; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("decode") }; return name; } void print(String *str, enum_query_type query_type) override; bool fix_length_and_dec() override; Item *find_item() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* The Item_func_in class implements in_expr IN () and in_expr NOT IN () The current implementation distinguishes 2 cases: 1) all items in are constants and have the same result type. This case is handled by in_vector class, implementing fast bisection search. 2) otherwise Item_func_in employs several cmp_item objects to perform comparisons of in_expr and an item from . One cmp_item object for each result type. Different result types are collected in the fix_length_and_dec() member function by means of collect_cmp_types() function. Bisection is possible when: 1. All types are similar 2. All expressions in are const In the presence of NULLs, the correct result of evaluating this item must be UNKNOWN or FALSE. To achieve that: - If type is scalar, we can use bisection and the "have_null" boolean. - If type is ROW, we will need to scan all of when searching, so bisection is impossible. Unless: 3. UNKNOWN and FALSE are equivalent results 4. Neither left expression nor contain any NULL value */ class Item_func_in :public Item_func_opt_neg, public Predicant_to_list_comparator { /** Usable if is made only of constants. Returns true if one of these constants contains a NULL. Example: IN ( (-5, (12,NULL)), ... ). */ bool list_contains_null(); bool all_items_are_consts(Item **items, uint nitems) const { for (uint i= 0; i < nitems; i++) { if (!items[i]->can_eval_in_optimize()) return false; } return true; } bool prepare_predicant_and_values(THD *thd, uint *found_types); bool check_arguments() const override { return check_argument_types_like_args0(); } protected: SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) override; bool transform_into_subq; bool transform_into_subq_checked; public: /// An array of values, created when the bisection lookup method is used in_vector *array; /** If there is some NULL among , during a val_int() call; for example IN ( (1,(3,'col')), ... ), where 'col' is a column which evaluates to NULL. */ bool have_null; /** true when all arguments of the IN list are of compatible types and can be used safely as comparisons for key conditions */ bool arg_types_compatible; TABLE_LIST *emb_on_expr_nest; Item_func_in(THD *thd, List &list): Item_func_opt_neg(thd, list), Predicant_to_list_comparator(thd, arg_count - 1), transform_into_subq(false), transform_into_subq_checked(false), array(0), have_null(0), arg_types_compatible(FALSE), emb_on_expr_nest(0) { } bool val_bool() override; bool fix_fields(THD *, Item **) override; bool fix_length_and_dec() override; bool compatible_types_scalar_bisection_possible() { DBUG_ASSERT(m_comparator.cmp_type() != ROW_RESULT); return all_items_are_consts(args + 1, arg_count - 1); // Bisection #2 } bool compatible_types_row_bisection_possible() { DBUG_ASSERT(m_comparator.cmp_type() == ROW_RESULT); return all_items_are_consts(args + 1, arg_count - 1) && // Bisection #2 ((is_top_level_item() && !negated) || // Bisection #3 (!list_contains_null() && !args[0]->maybe_null())); // Bisection #4 } bool agg_all_arg_charsets_for_comparison() { return agg_arg_charsets_for_comparison(cmp_collation, args, arg_count); } void fix_in_vector(); bool value_list_convert_const_to_int(THD *thd); bool fix_for_scalar_comparison_using_bisection(THD *thd) { array= m_comparator.type_handler()->make_in_vector(thd, this, arg_count - 1); if (!array) // OOM return true; fix_in_vector(); return false; } bool fix_for_scalar_comparison_using_cmp_items(THD *thd, uint found_types); bool fix_for_row_comparison_using_cmp_items(THD *thd); bool fix_for_row_comparison_using_bisection(THD *thd); void cleanup() override { DBUG_ENTER("Item_func_in::cleanup"); Item_int_func::cleanup(); delete array; array= 0; Predicant_to_list_comparator::cleanup(); DBUG_VOID_RETURN; } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override; SEL_TREE *get_func_row_mm_tree(RANGE_OPT_PARAM *param, Item_row *key_row); Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { /* Note, we pass ANY_SUBST, this makes sure that non of the args will be replaced to a zero-filled Item_string. Such a change would require rebuilding of cmp_items. */ if (arg_types_compatible) { Context cmpctx(ANY_SUBST, m_comparator.type_handler(), Item_func_in::compare_collation()); args[0]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, cond, &args[0]); } for (uint i= 0; i < comparator_count(); i++) { Context cmpctx(ANY_SUBST, get_comparator_type_handler(i), Item_func_in::compare_collation()); uint idx= get_comparator_arg_index(i); args[idx]->propagate_equal_fields_and_change_item_tree(thd, cmpctx, cond, &args[idx]); } return this; } void print(String *str, enum_query_type query_type) override; enum Functype functype() const override { return IN_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("in") }; return name; } enum precedence precedence() const override { return IN_PRECEDENCE; } bool eval_not_null_tables(void *opt_arg) override; bool find_not_null_fields(table_map allowed) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; bool count_sargable_conds(void *arg) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } Item *do_build_clone(THD *thd) const override { Item_func_in *clone= (Item_func_in *) Item_func::do_build_clone(thd); if (clone) { clone->array= 0; if (clone->Predicant_to_list_comparator::init_clone(thd, arg_count - 1)) return NULL; } return clone; } void mark_as_condition_AND_part(TABLE_LIST *embedding) override; bool to_be_transformed_into_in_subq(THD *thd); bool create_value_list_for_tvc(THD *thd, List< List > *values); Item *in_predicate_to_in_subs_transformer(THD *thd, uchar *arg) override; Item *in_predicate_to_equality_transformer(THD *thd, uchar *arg) override; uint32 max_length_of_left_expr(); }; class cmp_item_row :public cmp_item { cmp_item **comparators; uint n; bool alloc_comparators(THD *thd, uint n); bool aggregate_row_elements_for_comparison(THD *thd, Type_handler_hybrid_field_type *cmp, Item_args *tmp, const LEX_CSTRING &funcname, uint col, uint level); public: cmp_item_row(): comparators(0), n(0) {} ~cmp_item_row(); void store_value(Item *item) override; bool prepare_comparators(THD *, const LEX_CSTRING &funcname, const Item_args *args, uint level); int cmp(Item *arg) override; int cmp_not_null(const Value *) override { DBUG_ASSERT(false); return TRUE; } int compare(const cmp_item *arg) const override; cmp_item *make_same(THD *thd) override; bool store_value_by_template(THD *thd, cmp_item *tmpl, Item *) override; friend class Item_func_in; cmp_item *get_comparator(uint i) { return comparators[i]; } }; class in_row :public in_vector { cmp_item_row tmp; public: in_row(THD *thd, uint elements, Item *); ~in_row(); bool set(uint pos, Item *item) override; uchar *get_value(Item *item) override; friend class Item_func_in; const Type_handler *type_handler() const override { return &type_handler_row; } cmp_item *get_cmp_item() { return &tmp; } }; /* Functions used by where clause */ class Item_func_null_predicate :public Item_bool_func { protected: SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) override { DBUG_ENTER("Item_func_null_predicate::get_func_mm_tree"); DBUG_RETURN(get_mm_parts(param, field, functype(), value)); } SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, KEY_PART *key_part, Item_func::Functype type, Item *value) override; public: Item_func_null_predicate(THD *thd, Item *a): Item_bool_func(thd, a) { } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override { DBUG_ENTER("Item_func_null_predicate::get_mm_tree"); SEL_TREE *ftree= get_full_func_mm_tree_for_args(param, args[0], NULL); if (!ftree) ftree= Item_func::get_mm_tree(param, cond_ptr); DBUG_RETURN(ftree); } CHARSET_INFO *compare_collation() const override { return args[0]->collation.collation; } bool fix_length_and_dec() override { decimals=0; max_length=1; base_flags&= ~item_base_t::MAYBE_NULL; return FALSE; } bool count_sargable_conds(void *arg) override; }; class Item_func_isnull :public Item_func_null_predicate { public: Item_func_isnull(THD *thd, Item *a): Item_func_null_predicate(thd, a) {} bool val_bool() override; enum Functype functype() const override { return ISNULL_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("isnull") }; return name; } void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return CMP_PRECEDENCE; } bool arg_is_datetime_notnull_field() { Item **args= arguments(); if (args[0]->real_item()->type() == Item::FIELD_ITEM) { Field *field=((Item_field*) args[0]->real_item())->field; if ((field->flags & NOT_NULL_FLAG) && field->type_handler()->cond_notnull_field_isnull_to_field_eq_zero()) return true; } return false; } /* Optimize case of not_null_column IS NULL */ void update_used_tables() override { if (!args[0]->maybe_null() && !arg_is_datetime_notnull_field()) { used_tables_cache= 0; /* is always false */ const_item_cache= 1; } else { args[0]->update_used_tables(); used_tables_cache= args[0]->used_tables(); const_item_cache= args[0]->const_item(); } } COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, bool top_level) override; table_map not_null_tables() const override { return 0; } bool find_not_null_fields(table_map allowed) override; Item *neg_transformer(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Functions used by HAVING for rewriting IN subquery */ class Item_in_subselect; /* This is like IS NOT NULL but it also remembers if it ever has encountered a NULL. */ class Item_is_not_null_test :public Item_func_isnull { Item_in_subselect* owner; public: Item_is_not_null_test(THD *thd, Item_in_subselect* ow, Item *a): Item_func_isnull(thd, a), owner(ow) {} enum Functype functype() const override { return ISNOTNULLTEST_FUNC; } bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } void update_used_tables() override; /* we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE */ table_map used_tables() const override { return used_tables_cache | RAND_TABLE_BIT; } bool const_item() const override { return FALSE; } }; class Item_func_isnotnull :public Item_func_null_predicate { bool abort_on_null; public: Item_func_isnotnull(THD *thd, Item *a): Item_func_null_predicate(thd, a), abort_on_null(0) { } bool val_bool() override; enum Functype functype() const override { return ISNOTNULL_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("isnotnull") }; return name; } enum precedence precedence() const override { return CMP_PRECEDENCE; } table_map not_null_tables() const override { return abort_on_null ? not_null_tables_cache : 0; } Item *neg_transformer(THD *thd) override; void print(String *str, enum_query_type query_type) override; void top_level_item() override { abort_on_null=1; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_like :public Item_bool_func2 { // Turbo Boyer-Moore data bool canDoTurboBM; // pattern is '%abcd%' case const char* pattern; int pattern_len; // TurboBM buffers, *this is owner int* bmGs; // good suffix shift table, size is pattern_len + 1 int* bmBc; // bad character shift table, size is alphabet_size void turboBM_compute_suffixes(int* suff); void turboBM_compute_good_suffix_shifts(int* suff); void turboBM_compute_bad_character_shifts(); bool turboBM_matches(const char* text, int text_len) const; enum { alphabet_size = 256 }; Item *escape_item; bool escape_used_in_parsing; bool use_sampling; DTCollation cmp_collation; String cmp_value1, cmp_value2; bool with_sargable_pattern() const; protected: SEL_TREE *get_func_mm_tree(RANGE_OPT_PARAM *param, Field *field, Item *value) override { DBUG_ENTER("Item_func_like::get_func_mm_tree"); DBUG_RETURN(get_mm_parts(param, field, LIKE_FUNC, value)); } SEL_ARG *get_mm_leaf(RANGE_OPT_PARAM *param, Field *field, KEY_PART *key_part, Item_func::Functype type, Item *value) override; public: int escape; bool negated; Item_func_like(THD *thd, Item *a, Item *b, Item *escape_arg, bool escape_used): Item_bool_func2(thd, a, b), canDoTurboBM(FALSE), pattern(0), pattern_len(0), bmGs(0), bmBc(0), escape_item(escape_arg), escape_used_in_parsing(escape_used), use_sampling(0), negated(0) {} bool get_negated() const { return negated; } // Used by ColumnStore Sql_mode_dependency value_depends_on_sql_mode() const override; bool val_bool() override; enum Functype functype() const override { return LIKE_FUNC; } void print(String *str, enum_query_type query_type) override; CHARSET_INFO *compare_collation() const override { return cmp_collation.collation; } cond_result eq_cmp_result() const override { /** We cannot always rewrite conditions as follows: from: WHERE expr1=const AND expr1 LIKE expr2 to: WHERE expr1=const AND const LIKE expr2 or from: WHERE expr1=const AND expr2 LIKE expr1 to: WHERE expr1=const AND expr2 LIKE const because LIKE works differently comparing to the regular "=" operator: 1. LIKE performs a stricter one-character-to-one-character comparison and does not recognize contractions and expansions. Replacing "expr1" to "const in LIKE would make the condition stricter in case of a complex collation. 2. LIKE does not ignore trailing spaces and thus works differently from the "=" operator in case of "PAD SPACE" collations (which are the majority in MariaDB). So, for "PAD SPACE" collations: - expr1=const - ignores trailing spaces - const LIKE expr2 - does not ignore trailing spaces - expr2 LIKE const - does not ignore trailing spaces Allow only "binary" for now. It neither ignores trailing spaces nor has contractions/expansions. TODO: We could still replace "expr1" to "const" in "expr1 LIKE expr2" in case of a "PAD SPACE" collation, but only if "expr2" has '%' at the end. */ return compare_collation() == &my_charset_bin ? COND_TRUE : COND_OK; } void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override; Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { /* LIKE differs from the regular comparison operator ('=') in the following: - LIKE never ignores trailing spaces (even for PAD SPACE collations) Propagation of equal fields with a PAD SPACE collation into LIKE is not safe. Example: WHERE a='a ' AND a LIKE 'a' - returns true for 'a' cannot be rewritten to: WHERE a='a ' AND 'a ' LIKE 'a' - returns false for 'a' Note, binary collations in MySQL/MariaDB, e.g. latin1_bin, still have the PAD SPACE attribute and ignore trailing spaces! - LIKE does not take into account contractions, expansions, and ignorable characters. Propagation of equal fields with contractions/expansions/ignorables is also not safe. It's safe to propagate my_charset_bin (BINARY/VARBINARY/BLOB) values, because they do not ignore trailing spaces and have one-to-one mapping between a string and its weights. The below condition should be true only for my_charset_bin (as of version 10.1.7). */ uint flags= Item_func_like::compare_collation()->state; if ((flags & MY_CS_NOPAD) && !(flags & MY_CS_NON1TO1)) Item_args::propagate_equal_fields(thd, Context(ANY_SUBST, &type_handler_long_blob, compare_collation()), cond); return this; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("like") }; return name; } enum precedence precedence() const override { return IN_PRECEDENCE; } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override { max_length= 1; Item_args old_predicant(args[0]); if (agg_arg_charsets_for_comparison(cmp_collation, args, 2)) return true; raise_note_if_key_become_unused(current_thd, old_predicant); return false; } void cleanup() override; Item *neg_transformer(THD *thd) override { negated= !negated; return this; } bool walk(Item_processor processor, bool walk_subquery, void *arg) override { return (walk_args(processor, walk_subquery, arg) || escape_item->walk(processor, walk_subquery, arg) || (this->*processor)(arg)); } bool find_selective_predicates_list_processor(void *arg) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; typedef struct pcre2_real_code_8 pcre2_code; typedef struct pcre2_real_match_data_8 pcre2_match_data; #define PCRE2_SIZE size_t class Regexp_processor_pcre { pcre2_code *m_pcre; pcre2_match_data *m_pcre_match_data; bool m_conversion_is_needed; bool m_is_const; int m_library_flags; CHARSET_INFO *m_library_charset; String m_prev_pattern; int m_pcre_exec_rc; PCRE2_SIZE *m_SubStrVec; void pcre_exec_warn(int rc) const; int pcre_exec_with_warn(const pcre2_code *code, pcre2_match_data *data, const char *subject, int length, int startoffset, int options); public: String *convert_if_needed(String *src, String *converter); String subject_converter; String pattern_converter; String replace_converter; Regexp_processor_pcre() : m_pcre(NULL), m_pcre_match_data(NULL), m_conversion_is_needed(true), m_is_const(0), m_library_flags(0), m_library_charset(&my_charset_utf8mb4_general_ci) {} int default_regex_flags(); void init(CHARSET_INFO *data_charset, int extra_flags); bool fix_owner(Item_func *owner, Item *subject_arg, Item *pattern_arg); bool compile(String *pattern, bool send_error); bool compile(Item *item, bool send_error); bool recompile(Item *item) { return !m_is_const && compile(item, false); } bool exec(const char *str, size_t length, size_t offset); bool exec(String *str, int offset, uint n_result_offsets_to_convert); bool exec(Item *item, int offset, uint n_result_offsets_to_convert); bool match() const { return m_pcre_exec_rc < 0 ? 0 : 1; } int nsubpatterns() const { return m_pcre_exec_rc <= 0 ? 0 : m_pcre_exec_rc; } size_t subpattern_start(int n) const { return m_pcre_exec_rc <= 0 ? 0 : m_SubStrVec[n * 2]; } size_t subpattern_end(int n) const { return m_pcre_exec_rc <= 0 ? 0 : m_SubStrVec[n * 2 + 1]; } size_t subpattern_length(int n) const { return subpattern_end(n) - subpattern_start(n); } void reset() { m_pcre= NULL; m_pcre_match_data= NULL; m_prev_pattern.length(0); } void cleanup(); bool is_compiled() const { return m_pcre != NULL; } bool is_const() const { return m_is_const; } void set_const(bool arg) { m_is_const= arg; } CHARSET_INFO * library_charset() const { return m_library_charset; } }; class Item_func_regex :public Item_bool_func { Regexp_processor_pcre re; DTCollation cmp_collation; public: Item_func_regex(THD *thd, Item *a, Item *b): Item_bool_func(thd, a, b) {} void cleanup() override { DBUG_ENTER("Item_func_regex::cleanup"); Item_bool_func::cleanup(); re.cleanup(); DBUG_VOID_RETURN; } bool val_bool() override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("regexp") }; return name; } enum precedence precedence() const override { return IN_PRECEDENCE; } Item *do_get_copy(THD *thd) const override { return 0; } void print(String *str, enum_query_type query_type) override { print_op(str, query_type); } CHARSET_INFO *compare_collation() const override { return cmp_collation.collation; } }; /* In the corner case REGEXP_INSTR could return (2^32 + 1), which would not fit into Item_long_func range. But string lengths are limited with max_allowed_packet, which cannot be bigger than 1024*1024*1024. */ class Item_func_regexp_instr :public Item_long_func { bool check_arguments() const override { return (args[0]->check_type_can_return_str(func_name_cstring()) || args[1]->check_type_can_return_text(func_name_cstring())); } Regexp_processor_pcre re; DTCollation cmp_collation; public: Item_func_regexp_instr(THD *thd, Item *a, Item *b) :Item_long_func(thd, a, b) {} void cleanup() override { DBUG_ENTER("Item_func_regexp_instr::cleanup"); Item_int_func::cleanup(); re.cleanup(); DBUG_VOID_RETURN; } longlong val_int() override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("regexp_instr") }; return name; } Item *do_get_copy(THD *thd) const override { return 0; } }; typedef class Item COND; class Item_cond :public Item_bool_func { protected: List list; bool abort_on_null; table_map and_tables_cache; public: /* Item_cond() is only used to create top level items */ Item_cond(THD *thd): Item_bool_func(thd), abort_on_null(1) { const_item_cache=0; } Item_cond(THD *thd, Item *i1, Item *i2); Item_cond(THD *thd, Item_cond *item); Item_cond(THD *thd, List &nlist): Item_bool_func(thd), list(nlist), abort_on_null(0) {} bool add(Item *item, MEM_ROOT *root) { DBUG_ASSERT(item); return list.push_back(item, root); } bool add_at_head(Item *item, MEM_ROOT *root) { DBUG_ASSERT(item); return list.push_front(item, root); } void add_at_head(List *nlist) { DBUG_ASSERT(nlist->elements); list.prepend(nlist); } void add_at_end(List *nlist) { DBUG_ASSERT(nlist->elements); list.append(nlist); } bool fix_fields(THD *, Item **ref) override; void fix_after_pullout(st_select_lex *new_parent, Item **ref, bool merge) override; enum Type type() const override { return COND_ITEM; } List* argument_list() { return &list; } table_map used_tables() const override; void update_used_tables() override { used_tables_and_const_cache_init(); used_tables_and_const_cache_update_and_join(list); } COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override; COND *remove_eq_conds(THD *thd, Item::cond_result *cond_value, bool top_level) override; void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override; void print(String *str, enum_query_type query_type) override; void split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array, List &fields, uint flags) override; friend int setup_conds(THD *thd, TABLE_LIST *tables, TABLE_LIST *leaves, COND **conds); void top_level_item() override { abort_on_null=1; } bool top_level() { return abort_on_null; } void copy_andor_arguments(THD *thd, Item_cond *item); bool walk(Item_processor processor, bool walk_subquery, void *arg) override; Item *do_transform(THD *thd, Item_transformer transformer, uchar *arg, bool toplevel); Item *transform(THD *thd, Item_transformer transformer, uchar *arg) override { return do_transform(thd, transformer, arg, 0); } Item *top_level_transform(THD *thd, Item_transformer transformer, uchar *arg) override { return do_transform(thd, transformer, arg, 1); } void traverse_cond(Cond_traverser, void *arg, traverse_order order) override; void neg_arguments(THD *thd); Item* propagate_equal_fields(THD *, const Context &, COND_EQUAL *) override; Item *do_compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t, bool toplevel); Item *compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) override { return do_compile(thd, analyzer, arg_p, transformer, arg_t, 0); } Item* top_level_compile(THD *thd, Item_analyzer analyzer, uchar **arg_p, Item_transformer transformer, uchar *arg_t) override { return do_compile(thd, analyzer, arg_p, transformer, arg_t, 1); } bool eval_not_null_tables(void *opt_arg) override; bool find_not_null_fields(table_map allowed) override; Item *do_build_clone(THD *thd) const override; bool excl_dep_on_table(table_map tab_map) override; bool excl_dep_on_grouping_fields(st_select_lex *sel) override; private: void merge_sub_condition(List_iterator& li); }; template class LI, class T> class Item_equal_iterator; /* The class Item_equal is used to represent conjunctions of equality predicates of the form field1 = field2, and field=const in where conditions and on expressions. All equality predicates of the form field1=field2 contained in a conjunction are substituted for a sequence of items of this class. An item of this class Item_equal(f1,f2,...fk) represents a multiple equality f1=f2=...=fk.l If a conjunction contains predicates f1=f2 and f2=f3, a new item of this class is created Item_equal(f1,f2,f3) representing the multiple equality f1=f2=f3 that substitutes the above equality predicates in the conjunction. A conjunction of the predicates f2=f1 and f3=f1 and f3=f2 will be substituted for the item representing the same multiple equality f1=f2=f3. An item Item_equal(f1,f2) can appear instead of a conjunction of f2=f1 and f1=f2, or instead of just the predicate f1=f2. An item of the class Item_equal inherits equalities from outer conjunctive levels. Suppose we have a where condition of the following form: WHERE f1=f2 AND f3=f4 AND f3=f5 AND ... AND (...OR (f1=f3 AND ...)). In this case: f1=f2 will be substituted for Item_equal(f1,f2); f3=f4 and f3=f5 will be substituted for Item_equal(f3,f4,f5); f1=f3 will be substituted for Item_equal(f1,f2,f3,f4,f5); An object of the class Item_equal can contain an optional constant item c. Then it represents a multiple equality of the form c=f1=...=fk. Objects of the class Item_equal are used for the following: 1. An object Item_equal(t1.f1,...,tk.fk) allows us to consider any pair of tables ti and tj as joined by an equi-condition. Thus it provide us with additional access paths from table to table. 2. An object Item_equal(t1.f1,...,tk.fk) is applied to deduce new SARGable predicates: f1=...=fk AND P(fi) => f1=...=fk AND P(fi) AND P(fj). It also can give us additional index scans and can allow us to improve selectivity estimates. 3. An object Item_equal(t1.f1,...,tk.fk) is used to optimize the selected execution plan for the query: if table ti is accessed before the table tj then in any predicate P in the where condition the occurrence of tj.fj is substituted for ti.fi. This can allow an evaluation of the predicate at an earlier step. When feature 1 is supported they say that join transitive closure is employed. When feature 2 is supported they say that search argument transitive closure is employed. Both features are usually supported by preprocessing original query and adding additional predicates. We do not just add predicates, we rather dynamically replace some predicates that can not be used to access tables in the investigated plan for those, obtained by substitution of some fields for equal fields, that can be used. Prepared Statements/Stored Procedures note: instances of class Item_equal are created only at the time a PS/SP is executed and are deleted in the end of execution. All changes made to these objects need not be registered in the list of changes of the parse tree and do not harm PS/SP re-execution. Item equal objects are employed only at the optimize phase. Usually they are not supposed to be evaluated. Yet in some cases we call the method val_int() for them. We have to take care of restricting the predicate such an object represents f1=f2= ...=fn to the projection of known fields fi1=...=fik. */ class Item_equal: public Item_bool_func { /* The list of equal items. Currently the list can contain: - Item_fields items for references to table columns - Item_direct_view_ref items for references to view columns - one const item If the list contains a constant item this item is always first in the list. The list contains at least two elements. Currently all Item_fields/Item_direct_view_ref items in the list should refer to table columns with equavalent type definitions. In particular if these are string columns they should have the same charset/collation. Use objects of the companion class Item_equal_fields_iterator to iterate over all items from the list of the Item_field/Item_direct_view_ref classes. */ List equal_items; /* TRUE <-> one of the items is a const item. Such item is always first in in the equal_items list */ bool with_const; /* The field eval_item is used when this item is evaluated with the method val_int() */ cmp_item *eval_item; /* This initially is set to FALSE. It becomes TRUE when this item is evaluated as being always false. If the flag is TRUE the contents of the list the equal_items should be ignored. */ bool cond_false; /* This initially is set to FALSE. It becomes TRUE when this item is evaluated as being always true. If the flag is TRUE the contents of the list the equal_items should be ignored. */ bool cond_true; /* For Item_equal objects inside an OR clause: one of the fields that were used in the original equality. */ Item_field *context_field; bool link_equal_fields; const Type_handler *m_compare_handler; CHARSET_INFO *m_compare_collation; public: COND_EQUAL *upper_levels; /* multiple equalities of upper and levels */ Item_equal(THD *thd, const Type_handler *handler, Item *f1, Item *f2, bool with_const_item); Item_equal(THD *thd, Item_equal *item_equal); /* Currently the const item is always the first in the list of equal items */ inline Item* get_const() { return with_const ? equal_items.head() : NULL; } void add_const(THD *thd, Item *c); /** Add a non-constant item to the multiple equality */ void add(Item *f, MEM_ROOT *root) { equal_items.push_back(f, root); } bool contains(Field *field); Item* get_first(struct st_join_table *context, Item *field); /** Get number of field items / references to field items in this object */ uint n_field_items() { return equal_items.elements - MY_TEST(with_const); } void merge(THD *thd, Item_equal *item); bool merge_with_check(THD *thd, Item_equal *equal_item, bool save_merged); void merge_into_list(THD *thd, List *list, bool save_merged, bool only_intersected); void update_const(THD *thd); enum Functype functype() const override { return MULT_EQUAL_FUNC; } bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("multiple equal") }; return name; } void sort(Item_field_cmpfunc compare, void *arg); bool fix_length_and_dec() override; bool fix_fields(THD *thd, Item **ref) override; void cleanup() override { delete eval_item; eval_item= NULL; } void update_used_tables() override; bool find_not_null_fields(table_map allowed) override; COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override; void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override; bool walk(Item_processor processor, bool walk_subquery, void *arg) override; Item *transform(THD *thd, Item_transformer transformer, uchar *arg) override; void print(String *str, enum_query_type query_type) override; const Type_handler *compare_type_handler() const { return m_compare_handler; } CHARSET_INFO *compare_collation() const override { return m_compare_collation; } void set_context_field(Item_field *ctx_field) { context_field= ctx_field; } void set_link_equal_fields(bool flag) { link_equal_fields= flag; } Item* do_get_copy(THD *thd) const override { return 0; } /* This does not comply with the specification of the virtual method, but Item_equal items are processed distinguishly anyway */ bool excl_dep_on_table(table_map tab_map) override { return used_tables() & tab_map; } bool excl_dep_on_in_subq_left_part(Item_in_subselect *subq_pred) override; bool excl_dep_on_grouping_fields(st_select_lex *sel) override; bool create_pushable_equalities(THD *thd, List *equalities, Pushdown_checker checker, uchar *arg, bool clone_const); /* Return the number of elements in this multiple equality */ uint elements_count() { return equal_items.elements; } friend class Item_equal_fields_iterator; bool count_sargable_conds(void *arg) override; Item *multiple_equality_transformer(THD *thd, uchar *arg) override; friend class Item_equal_iterator; friend class Item_equal_iterator; friend Item *eliminate_item_equal(THD *thd, COND *cond, COND_EQUAL *upper_levels, Item_equal *item_equal); friend bool setup_sj_materialization_part1(struct st_join_table *tab); friend bool setup_sj_materialization_part2(struct st_join_table *tab); }; class COND_EQUAL: public Sql_alloc { public: uint max_members; /* max number of members the current level list and all lower level lists */ COND_EQUAL *upper_levels; /* multiple equalities of upper and levels */ List current_level; /* list of multiple equalities of the current and level */ COND_EQUAL() { upper_levels= 0; } COND_EQUAL(Item_equal *item, MEM_ROOT *mem_root) :upper_levels(0) { current_level.push_back(item, mem_root); } void copy(COND_EQUAL &cond_equal) { max_members= cond_equal.max_members; upper_levels= cond_equal.upper_levels; if (cond_equal.current_level.is_empty()) current_level.empty(); else current_level= cond_equal.current_level; } bool is_empty() { return (current_level.elements == 0); } }; /* The template Item_equal_iterator is used to define classes Item_equal_fields_iterator and Item_equal_fields_iterator_slow. These are helper classes for the class Item equal Both classes are used to iterate over references to table/view columns from the list of equal items that included in an Item_equal object. The second class supports the operation of removal of the current member from the list when performing an iteration. */ template class LI, typename T> class Item_equal_iterator : public LI { protected: Item_equal *item_equal; Item *curr_item= nullptr; public: Item_equal_iterator(Item_equal &item_eq) :LI (item_eq.equal_items), item_equal(&item_eq) { if (item_eq.with_const) { LI *list_it= this; curr_item= (*list_it)++; } } Item* operator++(int) { LI *list_it= this; curr_item= (*list_it)++; return curr_item; } void rewind(void) { LI *list_it= this; list_it->rewind(); if (item_equal->with_const) curr_item= (*list_it)++; } Field *get_curr_field() { Item_field *item= (Item_field *) (curr_item->real_item()); return item->field; } }; typedef Item_equal_iterator Item_equal_iterator_fast; class Item_equal_fields_iterator :public Item_equal_iterator_fast { public: Item_equal_fields_iterator(Item_equal &item_eq) :Item_equal_iterator_fast(item_eq) { } Item ** ref() { return List_iterator_fast::ref(); } }; typedef Item_equal_iterator Item_equal_iterator_iterator_slow; class Item_equal_fields_iterator_slow :public Item_equal_iterator_iterator_slow { public: Item_equal_fields_iterator_slow(Item_equal &item_eq) :Item_equal_iterator_iterator_slow(item_eq) { } void remove() { List_iterator::remove(); } }; class Item_cond_and final :public Item_cond { public: COND_EQUAL m_cond_equal; /* contains list of Item_equal objects for the current and level and reference to multiple equalities of upper and levels */ Item_cond_and(THD *thd): Item_cond(thd) {} Item_cond_and(THD *thd, Item *i1,Item *i2): Item_cond(thd, i1, i2) {} Item_cond_and(THD *thd, Item_cond_and *item): Item_cond(thd, item) {} Item_cond_and(THD *thd, List &list_arg): Item_cond(thd, list_arg) {} enum Functype functype() const override { return COND_AND_FUNC; } bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("and") }; return name; } enum precedence precedence() const override { return AND_PRECEDENCE; } table_map not_null_tables() const override { return abort_on_null ? not_null_tables_cache: and_tables_cache; } Item *copy_andor_structure(THD *thd) override; Item *neg_transformer(THD *thd) override; void mark_as_condition_AND_part(TABLE_LIST *embedding) override; uint exists2in_reserved_items() override { return list.elements; }; COND *build_equal_items(THD *thd, COND_EQUAL *inherited, bool link_item_fields, COND_EQUAL **cond_equal_ref) override; bool set_format_by_check_constraint(Send_field_extended_metadata *to) const override; void add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level, table_map usable_tables, SARGABLE_PARAM **sargables) override; SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; inline bool is_cond_and(Item *item) { Item_func *func_item= item->get_item_func(); return func_item && func_item->functype() == Item_func::COND_AND_FUNC; } class Item_cond_or final :public Item_cond { public: Item_cond_or(THD *thd): Item_cond(thd) {} Item_cond_or(THD *thd, Item *i1,Item *i2): Item_cond(thd, i1, i2) {} Item_cond_or(THD *thd, Item_cond_or *item): Item_cond(thd, item) {} Item_cond_or(THD *thd, List &list_arg): Item_cond(thd, list_arg) {} enum Functype functype() const override { return COND_OR_FUNC; } bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("or") }; return name; } enum precedence precedence() const override { return OR_PRECEDENCE; } table_map not_null_tables() const override { return and_tables_cache; } Item *copy_andor_structure(THD *thd) override; Item *neg_transformer(THD *thd) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dyncol_check :public Item_bool_func { public: Item_func_dyncol_check(THD *thd, Item *str): Item_bool_func(thd, str) {} bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_check") }; return name; } bool need_parentheses_in_default() override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dyncol_exists :public Item_bool_func { public: Item_func_dyncol_exists(THD *thd, Item *str, Item *num): Item_bool_func(thd, str, num) {} bool val_bool() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_exists") }; return name; } bool need_parentheses_in_default() override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_cursor_bool_attr: public Item_bool_func, public Cursor_ref { public: Item_func_cursor_bool_attr(THD *thd, const LEX_CSTRING *name, uint offset) :Item_bool_func(thd), Cursor_ref(name, offset) { } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), arg, VCOL_SESSION_FUNC); } void print(String *str, enum_query_type query_type) override { Cursor_ref::print_func(str, func_name_cstring()); } }; class Item_func_cursor_isopen: public Item_func_cursor_bool_attr { public: Item_func_cursor_isopen(THD *thd, const LEX_CSTRING *name, uint offset) :Item_func_cursor_bool_attr(thd, name, offset) { } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("%ISOPEN") }; return name; } bool val_bool() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_cursor_found: public Item_func_cursor_bool_attr { public: Item_func_cursor_found(THD *thd, const LEX_CSTRING *name, uint offset) :Item_func_cursor_bool_attr(thd, name, offset) { set_maybe_null(); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("%FOUND") }; return name; } bool val_bool() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_cursor_notfound: public Item_func_cursor_bool_attr { public: Item_func_cursor_notfound(THD *thd, const LEX_CSTRING *name, uint offset) :Item_func_cursor_bool_attr(thd, name, offset) { set_maybe_null(); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("%NOTFOUND") }; return name; } bool val_bool() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; inline bool is_cond_or(Item *item) { Item_func *func_item= item->get_item_func(); return func_item && func_item->functype() == Item_func::COND_OR_FUNC; } Item *and_expressions(Item *a, Item *b, Item **org_item); class Comp_creator { public: Comp_creator() = default; /* Remove gcc warning */ virtual ~Comp_creator() = default; /* Remove gcc warning */ /** Create operation with given arguments. */ virtual Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const = 0; /** Create operation with given arguments in swap order. */ virtual Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const = 0; virtual const char* symbol(bool invert) const = 0; virtual bool eqne_op() const = 0; virtual bool l_op() const = 0; }; class Eq_creator :public Comp_creator { public: Eq_creator() = default; /* Remove gcc warning */ virtual ~Eq_creator() = default; /* Remove gcc warning */ Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const override; Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const override; const char* symbol(bool invert) const override { return invert? "<>" : "="; } bool eqne_op() const override { return 1; } bool l_op() const override { return 0; } }; class Ne_creator :public Comp_creator { public: Ne_creator() = default; /* Remove gcc warning */ virtual ~Ne_creator() = default; /* Remove gcc warning */ Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const override; Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const override; const char* symbol(bool invert) const override { return invert? "=" : "<>"; } bool eqne_op() const override { return 1; } bool l_op() const override { return 0; } }; class Gt_creator :public Comp_creator { public: Gt_creator() = default; /* Remove gcc warning */ virtual ~Gt_creator() = default; /* Remove gcc warning */ Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const override; Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const override; const char* symbol(bool invert) const override { return invert? "<=" : ">"; } bool eqne_op() const override { return 0; } bool l_op() const override { return 0; } }; class Lt_creator :public Comp_creator { public: Lt_creator() = default; /* Remove gcc warning */ virtual ~Lt_creator() = default; /* Remove gcc warning */ Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const override; Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const override; const char* symbol(bool invert) const override { return invert? ">=" : "<"; } bool eqne_op() const override { return 0; } bool l_op() const override { return 1; } }; class Ge_creator :public Comp_creator { public: Ge_creator() = default; /* Remove gcc warning */ virtual ~Ge_creator() = default; /* Remove gcc warning */ Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const override; Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const override; const char* symbol(bool invert) const override { return invert? "<" : ">="; } bool eqne_op() const override { return 0; } bool l_op() const override { return 0; } }; class Le_creator :public Comp_creator { public: Le_creator() = default; /* Remove gcc warning */ virtual ~Le_creator() = default; /* Remove gcc warning */ Item_bool_rowready_func2* create(THD *thd, Item *a, Item *b) const override; Item_bool_rowready_func2* create_swap(THD *thd, Item *a, Item *b) const override; const char* symbol(bool invert) const override { return invert? ">" : "<="; } bool eqne_op() const override { return 0; } bool l_op() const override { return 1; } }; /* These need definitions from this file but the variables are defined in mysqld.h. The variables really belong in this component, but for the time being we leave them in mysqld.cc to avoid merge problems. */ extern Eq_creator eq_creator; extern Ne_creator ne_creator; extern Gt_creator gt_creator; extern Lt_creator lt_creator; extern Ge_creator ge_creator; extern Le_creator le_creator; #endif /* ITEM_CMPFUNC_INCLUDED */ mysql/server/private/winservice.h000064400000002252151027430560013224 0ustar00/* Copyright (c) 2011, 2012, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Extract properties of a windows service binary path */ #ifdef __cplusplus extern "C" { #endif #include typedef struct mysqld_service_properties_st { char mysqld_exe[MAX_PATH]; char inifile[MAX_PATH]; char datadir[MAX_PATH]; int version_major; int version_minor; int version_patch; } mysqld_service_properties; extern int get_mysql_service_properties(const wchar_t *bin_path, mysqld_service_properties *props); #ifdef __cplusplus } #endif mysql/server/private/heap.h000064400000022410151027430560011761 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file should be included when using heap_database_functions */ /* Author: Michael Widenius */ #ifndef _heap_h #define _heap_h #ifdef __cplusplus extern "C" { #endif #ifndef _my_base_h #include #endif #include #include #include "my_compare.h" #include "my_tree.h" /* defines used by heap-functions */ #define HP_MAX_LEVELS 4 /* 128^5 records is enough */ #define HP_PTRS_IN_NOD 128 /* struct used with heap_functions */ typedef struct st_heapinfo /* Struct from heap_info */ { ulong records; /* Records in database */ ulong deleted; /* Deleted records in database */ ulong max_records; ulonglong data_length; ulonglong index_length; uint reclength; /* Length of one record */ int errkey; ulonglong auto_increment; time_t create_time; } HEAPINFO; /* Structs used by heap-database-handler */ typedef struct st_heap_ptrs { uchar *blocks[HP_PTRS_IN_NOD]; /* pointers to HP_PTRS or records */ } HP_PTRS; struct st_level_info { /* Number of unused slots in *last_blocks HP_PTRS block (0 for 0th level) */ uint free_ptrs_in_block; /* Maximum number of records that can be 'contained' inside of each element of last_blocks array. For level 0 - 1, for level 1 - HP_PTRS_IN_NOD, for level 2 - HP_PTRS_IN_NOD^2 and so forth. */ ulong records_under_level; /* Ptr to last allocated HP_PTRS (or records buffer for level 0) on this level. */ HP_PTRS *last_blocks; }; /* Heap table records and hash index entries are stored in HP_BLOCKs. HP_BLOCK is used as a 'growable array' of fixed-size records. Size of record is recbuffer bytes. The internal representation is as follows: HP_BLOCK is a hierarchical structure of 'blocks'. A block at level 0 is an array records_in_block records. A block at higher level is an HP_PTRS structure with pointers to blocks at lower levels. At the highest level there is one top block. It is stored in HP_BLOCK::root. See hp_find_block for a description of how record pointer is obtained from its index. See hp_get_new_block */ typedef struct st_heap_block { HP_PTRS *root; /* Top-level block */ struct st_level_info level_info[HP_MAX_LEVELS+1]; uint levels; /* number of used levels */ uint recbuffer; /* Length of one saved record */ ulong records_in_block; /* Records in one heap-block */ ulong last_allocated; /* number of records there is allocated space for */ size_t alloc_size; /* Allocate blocks of this size */ } HP_BLOCK; struct st_heap_info; /* For reference */ typedef struct st_hp_keydef /* Key definition with open */ { uint flag; /* HA_NOSAME | HA_NULL_PART_KEY */ uint keysegs; /* Number of key-segment */ uint length; /* Length of key (automatic) */ uint8 algorithm; /* HASH / BTREE */ HA_KEYSEG *seg; HP_BLOCK block; /* Where keys are saved */ /* Number of buckets used in hash table. Used only to provide #records estimates for heap key scans. */ ha_rows hash_buckets; TREE rb_tree; int (*write_key)(struct st_heap_info *info, struct st_hp_keydef *keyinfo, const uchar *record, uchar *recpos); int (*delete_key)(struct st_heap_info *info, struct st_hp_keydef *keyinfo, const uchar *record, uchar *recpos, int flag); uint (*get_key_length)(struct st_hp_keydef *keydef, const uchar *key); } HP_KEYDEF; typedef struct st_heap_share { HP_BLOCK block; HP_KEYDEF *keydef; ulonglong data_length,index_length,max_table_size; ulonglong auto_increment; ulong min_records,max_records; /* Params to open */ ulong records; /* records */ ulong blength; /* records rounded up to 2^n */ ulong deleted; /* Deleted records in database */ uint key_stat_version; /* version to indicate insert/delete */ uint key_version; /* Updated on key change */ uint file_version; /* Update on clear */ uint reclength; /* Length of one record */ uint visible; /* Offset to the visible/deleted mark */ uint changed; uint keys,max_key_length; uint currently_disabled_keys; /* saved value from "keys" when disabled */ uint open_count; uchar *del_link; /* Link to next block with del. rec */ char * name; /* Name of "memory-file" */ time_t create_time; THR_LOCK lock; my_bool delete_on_close; my_bool internal; /* Internal temporary table */ LIST open_list; uint auto_key; uint auto_key_type; /* real type of the auto key segment */ } HP_SHARE; struct st_hp_hash_info; typedef struct st_heap_info { HP_SHARE *s; uchar *current_ptr; struct st_hp_hash_info *current_hash_ptr; ulong current_record,next_block; int lastinx,errkey; int mode; /* Mode of file (READONLY..) */ uint opt_flag,update; uchar *lastkey; /* Last used key with rkey */ uchar *recbuf; /* Record buffer for rb-tree keys */ enum ha_rkey_function last_find_flag; TREE_ELEMENT *parents[MAX_TREE_HEIGHT+1]; TREE_ELEMENT **last_pos; uint key_version; /* Version at last read */ uint file_version; /* Version at scan */ uint lastkey_len; my_bool implicit_emptied; THR_LOCK_DATA lock; LIST open_list; } HP_INFO; typedef struct st_heap_create_info { HP_KEYDEF *keydef; uint auto_key; /* keynr [1 - maxkey] for auto key */ uint auto_key_type; uint keys; uint reclength; ulong max_records; ulong min_records; ulonglong max_table_size; ulonglong auto_increment; my_bool with_auto_increment; my_bool internal_table; /* TRUE if heap_create should 'pin' the created share by setting open_count to 1. Is only looked at if not internal_table. */ my_bool pin_share; } HP_CREATE_INFO; /* Prototypes for heap-functions */ extern HP_INFO *heap_open(const char *name, int mode); extern HP_INFO *heap_open_from_share(HP_SHARE *share, int mode); extern HP_INFO *heap_open_from_share_and_register(HP_SHARE *share, int mode); extern void heap_release_share(HP_SHARE *share, my_bool internal_table); extern int heap_close(HP_INFO *info); extern int heap_write(HP_INFO *info,const uchar *buff); extern int heap_update(HP_INFO *info,const uchar *old,const uchar *newdata); extern int heap_rrnd(HP_INFO *info,uchar *buf,uchar *pos); extern int heap_scan_init(HP_INFO *info); extern int heap_scan(HP_INFO *info, uchar *record); extern int heap_delete(HP_INFO *info,const uchar *buff); extern int heap_info(HP_INFO *info,HEAPINFO *x,int flag); extern int heap_create(const char *name, HP_CREATE_INFO *create_info, HP_SHARE **share, my_bool *created_new_share); extern int heap_delete_table(const char *name); extern void heap_drop_table(HP_INFO *info); extern int heap_extra(HP_INFO *info,enum ha_extra_function function); extern int heap_reset(HP_INFO *info); extern int heap_rename(const char *old_name,const char *new_name); extern int heap_panic(enum ha_panic_function flag); extern int heap_rsame(HP_INFO *info,uchar *record,int inx); extern int heap_rnext(HP_INFO *info,uchar *record); extern int heap_rprev(HP_INFO *info,uchar *record); extern int heap_rfirst(HP_INFO *info,uchar *record,int inx); extern int heap_rlast(HP_INFO *info,uchar *record,int inx); extern void heap_clear(HP_INFO *info); extern void heap_clear_keys(HP_INFO *info); extern int heap_disable_indexes(HP_INFO *info); extern int heap_enable_indexes(HP_INFO *info); extern int heap_indexes_are_disabled(HP_INFO *info); extern void heap_update_auto_increment(HP_INFO *info, const uchar *record); ha_rows hp_rb_records_in_range(HP_INFO *info, int inx, const key_range *min_key, const key_range *max_key); int hp_panic(enum ha_panic_function flag); int heap_rkey(HP_INFO *info, uchar *record, int inx, const uchar *key, key_part_map keypart_map, enum ha_rkey_function find_flag); extern uchar * heap_find(HP_INFO *info,int inx,const uchar *key); extern int heap_check_heap(const HP_INFO *info, my_bool print_status); extern uchar *heap_position(HP_INFO *info); /* The following is for programs that uses the old HEAP interface where pointer to rows where a long instead of a (uchar*). */ #if defined(WANT_OLD_HEAP_VERSION) || defined(OLD_HEAP_VERSION) extern int heap_rrnd_old(HP_INFO *info,uchar *buf,ulong pos); extern ulong heap_position_old(HP_INFO *info); #endif #ifdef OLD_HEAP_VERSION typedef ulong HEAP_PTR; #define heap_position(A) heap_position_old(A) #define heap_rrnd(A,B,C) heap_rrnd_old(A,B,C) #else typedef uchar *HEAP_PTR; #endif #ifdef __cplusplus } #endif #endif mysql/server/private/wsrep_on.h000064400000003266151027430560012710 0ustar00/* Copyright 2022 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #ifndef WSREP_ON_H #define WSREP_ON_H #ifdef WITH_WSREP extern bool WSREP_ON_; extern bool WSREP_PROVIDER_EXISTS_; extern my_bool wsrep_emulate_bin_log; extern ulong wsrep_forced_binlog_format; #define WSREP_ON unlikely(WSREP_ON_) /* use xxxxxx_NNULL macros when thd pointer is guaranteed to be non-null to * avoid compiler warnings (GCC 6 and later) */ #define WSREP_NNULL(thd) \ (WSREP_PROVIDER_EXISTS_ && thd->variables.wsrep_on) #define WSREP(thd) \ (thd && WSREP_NNULL(thd)) #define WSREP_CLIENT_NNULL(thd) \ (WSREP_NNULL(thd) && thd->wsrep_client_thread) #define WSREP_CLIENT(thd) \ (WSREP(thd) && thd->wsrep_client_thread) #define WSREP_EMULATE_BINLOG_NNULL(thd) \ (WSREP_NNULL(thd) && wsrep_emulate_bin_log) #define WSREP_EMULATE_BINLOG(thd) \ (WSREP(thd) && wsrep_emulate_bin_log) #else #define WSREP_ON false #define WSREP(T) (0) #define WSREP_NNULL(T) (0) #define WSREP_EMULATE_BINLOG(thd) (0) #define WSREP_EMULATE_BINLOG_NNULL(thd) (0) #endif #endif mysql/server/private/lex_hash.h000064400000425727151027430560012661 0ustar00/* Do not edit this file directly! */ /* Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. */ /* Do not edit this file! This is generated by gen_lex_hash.cc that seeks for a perfect hash function */ #include "lex.h" static uchar sql_functions_map[16228]= { 0, 0, 179, 2, '!', '|', 29, 0, '<', 'X', 157, 0, 'B', 'Y', 57, 1, 'A', 'W', 45, 3, 'A', 'W', 190, 4, 'A', 'W', 165, 6, 'C', 'Z', 0, 9, 'A', 'V', 19, 11, 'A', 'Y', 31, 12, 'C', 'U', 37, 13, 'C', 'V', 199, 13, 'C', 'W', 96, 14, 'A', 'U', 168, 14, 'A', 'S', 249, 14, 'D', 'U', 59, 15, 'C', 'S', 81, 15, 'C', 'S', 151, 15, 0, 0, 54, 2, 'M', 'M', 199, 15, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 78, 1, 0, 0, 80, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 75, 1, 0, 0, 3, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 0, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, '<', '>', 121, 0, 0, 0, 179, 2, '=', '>', 124, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'T', 126, 0, 0, 0, 49, 0, 0, 0, 179, 2, 0, 0, 149, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'S', 128, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 122, 1, 'F', 'R', 144, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 109, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 173, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 178, 2, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, 0, 23, 0, 0, 0, 27, 0, 0, 0, 236, 0, 0, 0, 179, 2, 0, 0, 238, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 246, 0, 0, 0, 12, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 15, 1, 0, 0, 138, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 141, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 150, 1, 0, 0, 7, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'V', 186, 0, 0, 0, 41, 0, 0, 0, 102, 0, 'A', 'I', 227, 0, 0, 0, 164, 0, 0, 0, 205, 0, 0, 0, 217, 0, 0, 0, 179, 2, 'N', 'P', 236, 0, 0, 0, 179, 2, 0, 0, 24, 1, 0, 0, 238, 255, 'A', 'O', 239, 0, 'O', 'O', 9, 1, 'N', 'U', 14, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 22, 1, 'E', 'U', 37, 1, 0, 0, 179, 2, 0, 0, 136, 2, 0, 0, 152, 2, 0, 0, 179, 2, 'M', 'O', 54, 1, 0, 0, 11, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 16, 0, 0, 0, 179, 2, 'D', 'Y', 205, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 24, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 32, 0, 0, 0, 21, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 22, 0, 0, 0, 122, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 128, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 148, 0, 0, 0, 2, 1, 0, 0, 179, 2, 0, 0, 14, 1, 0, 0, 236, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'N', 254, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 104, 1, 0, 0, 234, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 233, 255, 'T', 'W', 10, 1, 0, 0, 131, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 232, 255, 0, 0, 142, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 154, 1, 0, 0, 200, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 253, 1, 0, 0, 21, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 47, 2, 0, 0, 179, 2, 0, 0, 66, 2, 0, 0, 222, 255, 0, 0, 215, 255, 0, 0, 174, 2, 0, 0, 179, 2, 0, 0, 172, 2, 'L', 'Y', 81, 1, 'A', 'U', 112, 1, 'A', 'U', 157, 1, 'A', 'X', 184, 1, 'A', 'U', 226, 1, 0, 0, 219, 0, 'A', 'O', 247, 1, 'N', 'N', 11, 2, 'O', 'S', 44, 2, 'E', 'I', 49, 2, 'A', 'O', 54, 2, 0, 0, 105, 1, 'A', 'U', 112, 2, 'N', 'V', 133, 2, 'A', 'R', 142, 2, 0, 0, 179, 2, 'A', 'O', 174, 2, 'H', 'T', 211, 2, 'E', 'Y', 232, 2, 'N', 'S', 24, 3, 0, 0, 153, 2, 'A', 'O', 30, 3, 0, 0, 171, 2, 0, 0, 175, 2, 0, 0, 42, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'T', 95, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 50, 0, 0, 0, 44, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 45, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 47, 0, 'L', 'S', 133, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 60, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 69, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 72, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 105, 0, 0, 0, 52, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'T', 141, 1, 0, 0, 55, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 251, 255, 'T', 'T', 178, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 137, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 145, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 152, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 153, 0, 'A', 'E', 179, 1, 0, 0, 116, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 120, 0, 0, 0, 157, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 158, 0, 0, 0, 179, 2, 'D', 'U', 208, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 183, 0, 0, 0, 165, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 168, 0, 0, 0, 191, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 196, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 210, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 211, 0, 'R', 'S', 6, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 227, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'U', 8, 2, 0, 0, 224, 0, 0, 0, 225, 0, 0, 0, 230, 0, 0, 0, 179, 2, 0, 0, 232, 0, 'T', 'T', 12, 2, '1', 'O', 13, 2, 0, 0, 3, 1, 0, 0, 4, 1, 0, 0, 5, 1, 0, 0, 6, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 7, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 11, 1, 0, 0, 21, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 22, 1, 0, 0, 25, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 27, 1, 0, 0, 29, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'S', 69, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'K', 'S', 88, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 97, 2, 0, 0, 237, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 35, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 36, 1, 0, 0, 38, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 42, 1, 0, 0, 43, 1, 0, 0, 179, 2, 0, 0, 47, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 51, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 52, 1, 0, 0, 55, 1, 0, 0, 113, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 120, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 130, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 134, 1, 0, 0, 144, 1, 0, 0, 179, 2, 0, 0, 145, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 157, 1, 'G', 'T', 160, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 177, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 184, 1, 0, 0, 162, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 166, 1, 0, 0, 225, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 189, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'W', 199, 2, 'D', 'L', 190, 2, 0, 0, 201, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 205, 1, 0, 0, 249, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 0, 2, 0, 0, 24, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 29, 2, 0, 0, 33, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'F', 'M', 224, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 75, 2, 0, 0, 37, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 38, 2, 0, 0, 98, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'E', 253, 2, 'E', 'M', 2, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'U', 11, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 118, 2, 0, 0, 99, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 100, 2, 0, 0, 101, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 102, 2, 0, 0, 213, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 116, 2, 0, 0, 124, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 137, 2, 0, 0, 157, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 159, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 161, 2, 0, 0, 165, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 168, 2, 'D', 'S', 68, 3, 'E', 'T', 84, 3, 'A', 'Y', 100, 3, 0, 0, 179, 2, 'L', 'V', 130, 3, 'A', 'O', 147, 3, 'R', 'R', 180, 3, 0, 0, 231, 0, 'N', 'N', 196, 3, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 209, 3, 'A', 'Y', 0, 4, 'A', 'T', 25, 4, 'R', 'W', 45, 4, 'H', 'U', 51, 4, 'U', 'U', 65, 4, 'A', 'T', 71, 4, 'H', 'W', 118, 4, 0, 0, 90, 2, 'N', 'S', 147, 4, 0, 0, 144, 2, 'H', 'R', 174, 4, 0, 0, 12, 0, 0, 0, 179, 2, 0, 0, 13, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 18, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 25, 0, 0, 0, 36, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 43, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 48, 0, 0, 0, 51, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'E', 125, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 70, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 250, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 104, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 115, 0, 0, 0, 57, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 63, 0, 0, 0, 160, 0, 0, 0, 161, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 169, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'E', 141, 3, 'N', 'R', 142, 3, 0, 0, 173, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 175, 0, 0, 0, 190, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 194, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'X', 162, 3, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'U', 169, 3, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'U', 176, 3, 0, 0, 197, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 198, 0, 0, 0, 199, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 202, 0, 0, 0, 206, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 209, 0, 'A', 'O', 181, 3, 0, 0, 220, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 222, 0, 'D', 'O', 197, 3, 0, 0, 248, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 252, 0, 0, 0, 253, 0, 'A', 'V', 220, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'M', 'N', 242, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'C', 244, 3, 0, 0, 33, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 37, 1, 0, 0, 39, 1, 0, 0, 41, 1, 'A', 'K', 245, 3, 0, 0, 44, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 49, 1, 0, 0, 79, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 93, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 98, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 109, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 110, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 111, 1, 0, 0, 114, 1, 0, 0, 179, 2, 0, 0, 117, 1, 0, 0, 179, 2, 0, 0, 119, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 230, 255, 0, 0, 151, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 155, 1, 0, 0, 179, 2, 0, 0, 159, 1, 0, 0, 174, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 193, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 194, 1, 'E', 'I', 66, 4, 0, 0, 196, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 197, 1, 'I', 'N', 91, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'U', 97, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 247, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 248, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 4, 2, 0, 0, 198, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 199, 1, 0, 0, 204, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 214, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 234, 1, 0, 0, 179, 2, 0, 0, 244, 1, 0, 0, 23, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 30, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 134, 4, 0, 0, 83, 2, 0, 0, 179, 2, 0, 0, 85, 2, 'G', 'R', 135, 4, 0, 0, 42, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 67, 2, 'I', 'T', 153, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 165, 4, 0, 0, 126, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 132, 2, 0, 0, 135, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 140, 2, 'E', 'I', 185, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 170, 2, 0, 0, 162, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 163, 2, 'C', 'T', 213, 4, 'A', 'I', 231, 4, 'H', 'U', 10, 5, 'E', 'O', 26, 5, 'L', 'X', 37, 5, 'A', 'O', 78, 5, 'L', 'R', 101, 5, 0, 0, 226, 0, 'G', 'S', 108, 5, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 140, 5, 'A', 'O', 151, 5, 'E', 'U', 198, 5, 'F', 'T', 215, 5, 'A', 'L', 230, 5, 0, 0, 179, 2, 'E', 'O', 242, 5, 'C', 'Y', 37, 6, 0, 0, 92, 2, 'N', 'P', 150, 6, 0, 0, 145, 2, 'I', 'I', 157, 6, 0, 0, 10, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 19, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 28, 0, 0, 0, 34, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 35, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'G', 'T', 240, 4, 0, 0, 38, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'L', 254, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 253, 255, 0, 0, 39, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 40, 0, 0, 0, 58, 0, 0, 0, 66, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 68, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'M', 24, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 103, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 113, 0, 0, 0, 75, 0, 0, 0, 84, 0, 0, 0, 135, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 150, 0, 0, 0, 159, 0, 0, 0, 179, 2, 'A', 'G', 50, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 170, 0, 0, 0, 171, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 174, 0, 0, 0, 179, 2, 'C', 'P', 57, 5, 0, 0, 162, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 166, 0, 0, 0, 177, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 182, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'O', 71, 5, 0, 0, 185, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 186, 0, 0, 0, 192, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 195, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'O', 93, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 208, 0, 'A', 'A', 94, 5, 'T', 'T', 95, 5, '4', '8', 96, 5, 0, 0, 200, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 201, 0, 0, 0, 218, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 221, 0, 0, 0, 239, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 244, 0, 'F', 'S', 121, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'S', 135, 5, 0, 0, 250, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 255, 0, 0, 0, 17, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 18, 1, 0, 0, 34, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 40, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 48, 1, 0, 0, 57, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'M', 166, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 99, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 107, 1, 'I', 'I', 176, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 92, 1, 'A', 'U', 177, 5, 0, 0, 235, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 88, 1, 0, 0, 118, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 128, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 135, 1, 0, 0, 139, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 143, 1, 0, 0, 179, 2, 0, 0, 148, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 153, 1, 0, 0, 164, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 167, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 175, 1, 'G', 'V', 253, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'W', 25, 6, 0, 0, 213, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 220, 1, 0, 0, 221, 1, 0, 0, 222, 1, 0, 0, 179, 2, 'A', 'L', 13, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 239, 1, 0, 0, 241, 1, 0, 0, 179, 2, 0, 0, 246, 1, 0, 0, 224, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 232, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 227, 1, 0, 0, 251, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 255, 1, 0, 0, 7, 2, 0, 0, 179, 2, 'C', 'T', 60, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'G', 'M', 92, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 31, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'U', 105, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'R', 129, 6, 0, 0, 217, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 88, 2, 0, 0, 10, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 13, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'V', 78, 6, 0, 0, 179, 2, 0, 0, 22, 2, 0, 0, 17, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 20, 2, 'N', 'N', 99, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 28, 2, 'A', 'E', 100, 6, 0, 0, 26, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 27, 2, 0, 0, 36, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 39, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'R', 124, 6, 0, 0, 40, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 41, 2, 'R', 'T', 147, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 221, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 43, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 78, 2, 0, 0, 69, 2, 0, 0, 179, 2, 0, 0, 74, 2, 'I', 'L', 153, 6, 0, 0, 179, 2, 0, 0, 133, 2, 0, 0, 127, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 129, 2, 'N', 'T', 158, 6, 0, 0, 164, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 166, 2, 'C', 'U', 188, 6, 'E', 'O', 207, 6, 'A', 'U', 244, 6, 'E', 'Y', 53, 7, 'N', 'X', 101, 7, 'O', 'O', 130, 7, 0, 0, 214, 0, 'A', 'I', 138, 7, 'G', 'T', 147, 7, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 180, 7, 'I', 'O', 195, 7, 'A', 'U', 202, 7, 'P', 'U', 21, 8, 'A', 'R', 27, 8, 0, 0, 195, 1, 'E', 'O', 76, 8, 'C', 'Y', 137, 8, 'H', 'R', 185, 8, 'N', 'S', 196, 8, 'A', 'I', 205, 8, 'I', 'R', 246, 8, 0, 0, 9, 0, 0, 0, 255, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 14, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 20, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 29, 0, 0, 0, 37, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'T', 'T', 218, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 46, 0, '_', '_', 219, 6, 'A', 'X', 220, 6, 0, 0, 254, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 252, 255, 0, 0, 53, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 9, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 15, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'R', 35, 7, 'N', 'R', 10, 7, 0, 0, 59, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 62, 0, 'L', 'U', 18, 7, 'M', 'P', 28, 7, 'T', 'V', 32, 7, 0, 0, 73, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 77, 0, 0, 0, 83, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 86, 0, 0, 0, 98, 0, 0, 0, 179, 2, 0, 0, 101, 0, 'D', 'T', 36, 7, 0, 0, 248, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 106, 0, 0, 0, 179, 2, 0, 0, 247, 255, 'C', 'L', 74, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 97, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 156, 0, 'I', 'L', 84, 7, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 88, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 133, 0, 0, 0, 129, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 130, 0, 0, 0, 131, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 132, 0, 'A', 'C', 98, 7, 0, 0, 143, 0, 0, 0, 179, 2, 0, 0, 144, 0, 0, 0, 167, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 172, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'T', 112, 7, 0, 0, 179, 0, 0, 0, 179, 2, 0, 0, 180, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 187, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 243, 255, 'L', 'R', 131, 7, 0, 0, 204, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 207, 0, 0, 0, 223, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 229, 0, 0, 0, 240, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'V', 161, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 19, 1, 0, 0, 249, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 1, 1, 0, 0, 8, 1, 0, 0, 179, 2, 0, 0, 20, 1, 0, 0, 31, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 32, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 50, 1, 0, 0, 97, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 108, 1, 0, 0, 116, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 121, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', '_', 223, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 136, 1, 'A', 'Y', 252, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 127, 1, 0, 0, 125, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 126, 1, 0, 0, 147, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 156, 1, 'C', 'R', 45, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 176, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 178, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 61, 8, 0, 0, 160, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 168, 1, 0, 0, 182, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 186, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'F', 72, 8, 0, 0, 189, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 191, 1, 'B', 'V', 87, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'U', 'W', 134, 8, 0, 0, 206, 1, 0, 0, 207, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 219, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'L', 108, 8, 0, 0, 233, 1, 0, 0, 179, 2, 'T', 'T', 118, 8, 0, 0, 243, 1, 0, 0, 179, 2, 0, 0, 245, 1, 'A', 'I', 109, 8, 0, 0, 226, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 228, 1, 'A', 'O', 119, 8, 0, 0, 236, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 237, 1, 0, 0, 252, 1, 0, 0, 179, 2, 0, 0, 1, 2, 0, 0, 9, 2, 0, 0, 179, 2, 0, 0, 19, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 44, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 76, 2, 'B', 'S', 160, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 87, 2, 'D', 'J', 178, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 84, 2, 0, 0, 218, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 80, 2, 0, 0, 113, 2, 0, 0, 107, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 114, 2, 'I', 'K', 202, 8, 0, 0, 179, 2, 0, 0, 134, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 139, 2, 0, 0, 125, 2, 0, 0, 179, 2, 0, 0, 128, 2, 'R', 'R', 214, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'S', 244, 8, 'C', '_', 215, 8, 0, 0, 147, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 151, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 210, 255, 0, 0, 154, 2, 0, 0, 155, 2, 0, 0, 167, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 169, 2, 'A', 'O', 24, 9, 'A', 'U', 63, 9, 'N', 'X', 131, 9, 'U', 'U', 162, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 9, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 166, 9, 'A', 'O', 202, 9, 'A', 'V', 241, 9, 'P', 'V', 7, 10, 'A', 'R', 14, 10, 0, 0, 179, 2, 'E', 'O', 63, 10, 'C', 'W', 114, 10, 'I', 'R', 150, 10, 'N', 'T', 202, 10, 'A', 'A', 244, 10, 0, 0, 158, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 177, 2, 0, 0, 54, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 65, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'N', 39, 9, 0, 0, 71, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'T', 'T', 53, 9, 'A', 'I', 54, 9, 0, 0, 97, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 99, 0, 'T', 'Y', 84, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 138, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 146, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 154, 0, 'A', 'E', 90, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 123, 0, 'B', 'F', 95, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'T', '_', 100, 9, 0, 0, 117, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 119, 0, 0, 0, 121, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'S', 112, 9, 0, 0, 246, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 245, 255, 0, 0, 163, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'T', 142, 9, 0, 0, 176, 0, 0, 0, 179, 2, 0, 0, 178, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 188, 0, 'L', 'N', 163, 9, 0, 0, 212, 0, 0, 0, 179, 2, 0, 0, 213, 0, 0, 0, 28, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'N', 181, 9, 'G', 'G', 182, 9, 'B', 'T', 183, 9, 0, 0, 53, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 54, 1, 'X', 'X', 217, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'N', 230, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 106, 1, 'V', '_', 218, 9, 0, 0, 87, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'S', 228, 9, 0, 0, 82, 1, 0, 0, 83, 1, 'V', '_', 231, 9, 0, 0, 102, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 103, 1, 0, 0, 115, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 132, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 137, 1, 0, 0, 146, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 158, 1, 0, 0, 172, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 229, 255, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 32, 10, 'C', 'V', 43, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 192, 1, 0, 0, 179, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 183, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 185, 1, 'D', 'S', 74, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'W', 102, 10, 0, 0, 210, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 215, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 229, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'T', 90, 10, 0, 0, 235, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 238, 1, 0, 0, 250, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 254, 1, 0, 0, 6, 2, 0, 0, 179, 2, 'C', 'Q', 135, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 25, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 35, 2, 0, 0, 34, 2, 0, 0, 179, 2, 0, 0, 45, 2, 0, 0, 49, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 68, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 86, 2, 0, 0, 12, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 16, 2, 'N', 'N', 160, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'U', 181, 10, 'Y', 'Y', 161, 10, 'B', 'T', 162, 10, 0, 0, 106, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 108, 2, 0, 0, 110, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 115, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 117, 2, 'D', 'S', 209, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'C', 225, 10, 0, 0, 123, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 131, 2, '_', '_', 226, 10, 'D', 'T', 227, 10, 0, 0, 141, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 142, 2, 'R', 'R', 245, 10, 'C', '_', 246, 10, 0, 0, 149, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 211, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 209, 255, 'G', 'L', 41, 11, 0, 0, 179, 2, 'H', 'U', 47, 11, 'A', 'U', 64, 11, 'X', 'X', 85, 11, 'E', 'O', 100, 11, 0, 0, 215, 0, 0, 0, 179, 2, 'M', 'S', 111, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 45, 1, 'E', 'I', 138, 11, 'O', 'T', 143, 11, 0, 0, 179, 2, 'A', 'R', 149, 11, 0, 0, 179, 2, 'E', 'O', 200, 11, 'A', 'U', 231, 11, 'E', 'I', 255, 11, 'N', 'N', 12, 12, 'A', 'A', 21, 12, 0, 0, 15, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 17, 0, 0, 0, 61, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 61, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 249, 255, 0, 0, 74, 0, 0, 0, 85, 0, 0, 0, 90, 0, 0, 0, 118, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 142, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 155, 0, 'C', 'P', 86, 11, 0, 0, 181, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 184, 0, 0, 0, 193, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 203, 0, 0, 0, 243, 0, 'C', 'V', 118, 11, 0, 0, 13, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 16, 1, 0, 0, 247, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 245, 0, 0, 0, 179, 2, 0, 0, 10, 1, 0, 0, 90, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 96, 1, 0, 0, 129, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 231, 255, 'C', 'R', 167, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 183, 11, 0, 0, 161, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 169, 1, 'C', 'C', 194, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 188, 1, 'E', 'I', 195, 11, 0, 0, 180, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 181, 1, 'A', 'T', 211, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 2, 2, 0, 0, 202, 1, 0, 0, 179, 2, 0, 0, 208, 1, 0, 0, 211, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 242, 1, 0, 0, 5, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'P', 252, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 32, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 53, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 70, 2, 0, 0, 216, 255, 0, 0, 14, 2, 0, 0, 179, 2, 0, 0, 15, 2, 'M', 'M', 4, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 103, 2, 'P', 'P', 5, 12, 'O', 'T', 6, 12, 0, 0, 95, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 96, 2, 'B', 'I', 13, 12, 0, 0, 119, 2, 0, 0, 179, 2, 0, 0, 121, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 130, 2, 'R', 'R', 22, 12, 'B', 'I', 23, 12, 0, 0, 146, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 150, 2, 'C', 'S', 56, 12, 0, 0, 179, 2, 'H', 'O', 73, 12, 'A', 'E', 132, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 216, 0, 0, 0, 179, 2, 0, 0, 237, 0, 0, 0, 23, 1, 0, 0, 179, 2, 0, 0, 30, 1, 'A', 'E', 160, 12, 'O', 'O', 188, 12, 'P', 'R', 199, 12, 'A', 'R', 202, 12, 0, 0, 179, 2, 'E', 'O', 220, 12, 'Q', 'T', 2, 13, 'A', 'E', 16, 13, 0, 0, 179, 2, 0, 0, 156, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 176, 2, 0, 0, 8, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 26, 0, 0, 0, 64, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 81, 12, 'U', 'U', 84, 12, 'P', 'P', 95, 12, 'C', 'S', 103, 12, 'M', 'M', 85, 12, 'N', 'N', 86, 12, '_', '_', 87, 12, 'A', 'G', 88, 12, 0, 0, 78, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 82, 0, 'L', 'R', 96, 12, 0, 0, 87, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 88, 0, 0, 0, 89, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 91, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'T', 120, 12, 0, 0, 92, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 93, 0, 'Y', 'Y', 137, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'N', 146, 12, '_', '_', 138, 12, 'M', 'S', 139, 12, 0, 0, 125, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 126, 0, 0, 0, 127, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 244, 255, 0, 0, 67, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'D', 165, 12, 'I', 'I', 166, 12, 'U', 'U', 167, 12, 'M', 'M', 168, 12, 'B', 'T', 169, 12, 0, 0, 89, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 91, 1, 'M', 'M', 189, 12, 'A', 'I', 190, 12, 0, 0, 123, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 124, 1, 0, 0, 149, 1, 0, 0, 179, 2, 0, 0, 152, 1, 0, 0, 171, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 173, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 187, 1, 'A', 'P', 231, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'W', 'W', 247, 12, 0, 0, 203, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 212, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 223, 1, 0, 0, 225, 1, '_', '_', 248, 12, 'F', 'N', 249, 12, 0, 0, 3, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 224, 255, 'L', 'L', 6, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 220, 255, 'W', '_', 7, 13, 0, 0, 50, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 57, 2, 'B', 'B', 21, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 97, 2, 'L', 'L', 22, 13, 'E', 'E', 23, 13, 'S', '_', 24, 13, 0, 0, 93, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 91, 2, 'O', 'U', 56, 13, 'I', 'I', 66, 13, 0, 0, 189, 0, 0, 0, 242, 255, 0, 0, 179, 2, 'O', 'O', 86, 13, 0, 0, 254, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'Y', 97, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 190, 1, 0, 0, 179, 2, 'E', 'E', 141, 13, 'C', 'Y', 159, 13, 'R', 'R', 189, 13, 0, 0, 120, 2, 0, 0, 76, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'R', 63, 13, 'R', 'S', 64, 13, 0, 0, 108, 0, 0, 0, 114, 0, 'A', 'S', 67, 13, 0, 0, 141, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 147, 0, 'U', 'U', 87, 13, 'R', 'R', 88, 13, '_', '_', 89, 13, 'M', 'S', 90, 13, 0, 0, 234, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 235, 0, 'S', 'S', 122, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 95, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 112, 1, 'T', 'T', 123, 13, 'E', 'E', 124, 13, 'R', 'R', 125, 13, '_', '_', 126, 13, 'H', 'U', 127, 13, 0, 0, 61, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 65, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 76, 1, 'P', 'P', 142, 13, 'L', 'L', 143, 13, 'I', 'I', 144, 13, 'C', 'C', 145, 13, 'A', 'A', 146, 13, 'T', '_', 147, 13, 0, 0, 231, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 230, 1, 0, 0, 8, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 61, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 219, 255, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 182, 13, 'T', 'T', 183, 13, 'E', 'E', 184, 13, 'M', 'M', 185, 13, '_', '_', 186, 13, 'T', 'U', 187, 13, 0, 0, 89, 2, 0, 0, 214, 255, 'A', 'I', 190, 13, 0, 0, 111, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 212, 255, 'A', 'U', 219, 13, 0, 0, 139, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 241, 255, 0, 0, 179, 2, 0, 0, 251, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 56, 1, 'A', 'E', 11, 14, 0, 0, 179, 2, 0, 0, 140, 1, 'A', 'E', 16, 14, 0, 0, 179, 2, 0, 0, 218, 1, 'E', 'U', 21, 14, 0, 0, 104, 2, 0, 0, 179, 2, 0, 0, 148, 2, 0, 0, 56, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 67, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 240, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'R', 243, 13, 0, 0, 79, 0, 0, 0, 179, 2, 0, 0, 100, 0, 'R', 'R', 244, 13, 'E', 'E', 245, 13, 'N', 'N', 246, 13, 'T', 'T', 247, 13, '_', '_', 248, 13, 'D', 'U', 249, 13, 0, 0, 107, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 109, 0, 0, 0, 179, 2, 0, 0, 110, 0, 0, 0, 112, 0, 0, 0, 59, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 94, 1, 0, 0, 170, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 228, 255, 'R', 'S', 38, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'L', 40, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 81, 2, 0, 0, 18, 2, 0, 0, 223, 255, 'E', '_', 41, 14, 0, 0, 48, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'T', 68, 14, 0, 0, 55, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 75, 14, 'I', 'I', 76, 14, '_', '_', 77, 14, 'H', 'Y', 78, 14, 0, 0, 60, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 62, 2, 0, 0, 179, 2, 0, 0, 65, 2, 'O', 'O', 117, 14, 'E', 'O', 125, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 228, 0, 0, 0, 0, 1, 0, 0, 240, 255, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 136, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 163, 1, 0, 0, 179, 2, 'E', 'E', 145, 14, 'Q', 'U', 153, 14, 'I', 'R', 158, 14, 0, 0, 143, 2, 0, 0, 179, 2, 0, 0, 160, 2, 'L', 'L', 118, 14, 'U', 'U', 119, 14, 'M', 'M', 120, 14, 'N', 'N', 121, 14, '_', '_', 122, 14, 'C', 'D', 123, 14, 0, 0, 80, 0, 0, 0, 81, 0, 0, 0, 140, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 151, 0, 0, 0, 68, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 101, 1, 'F', 'L', 146, 14, 0, 0, 46, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 217, 1, 0, 0, 63, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 77, 2, 0, 0, 82, 2, 0, 0, 105, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 112, 2, 'U', 'V', 189, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 239, 255, 0, 0, 26, 1, 0, 0, 46, 1, 'A', 'A', 191, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 216, 1, 'Q', 'Q', 217, 14, 0, 0, 94, 2, 0, 0, 138, 2, 0, 0, 30, 0, 0, 0, 33, 0, 'S', 'S', 192, 14, 'T', 'T', 193, 14, 'E', 'E', 194, 14, 'R', 'R', 195, 14, '_', '_', 196, 14, 'L', 'S', 197, 14, 0, 0, 63, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 205, 14, 'L', 'L', 206, 14, '_', '_', 207, 14, 'C', 'K', 208, 14, 0, 0, 72, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 74, 1, 'L', 'L', 218, 14, '_', '_', 219, 14, 'B', 'T', 220, 14, 0, 0, 51, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 239, 14, 'I', 'I', 240, 14, '_', '_', 241, 14, 'M', 'S', 242, 14, 0, 0, 59, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 58, 2, 0, 0, 31, 0, 0, 0, 179, 2, 0, 0, 95, 0, 'A', 'E', 12, 15, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 17, 15, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'E', 38, 15, 0, 0, 179, 2, 0, 0, 179, 2, 'Q', 'U', 54, 15, 0, 0, 124, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 134, 0, 'S', 'S', 18, 15, 'T', 'T', 19, 15, 'E', 'E', 20, 15, 'R', 'R', 21, 15, '_', '_', 22, 15, 'G', 'U', 23, 15, 0, 0, 60, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 62, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 64, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 70, 1, 0, 0, 179, 2, 0, 0, 77, 1, 0, 0, 165, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'R', 43, 15, 'C', 'C', 44, 15, 'E', 'E', 45, 15, 'N', 'N', 46, 15, 'T', 'T', 47, 15, 'I', 'I', 48, 15, 'L', 'L', 49, 15, 'E', 'E', 50, 15, '_', '_', 51, 15, 'C', 'D', 52, 15, 0, 0, 227, 255, 0, 0, 226, 255, 0, 0, 64, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 79, 2, 0, 0, 136, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 233, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 66, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 209, 1, 'Q', 'T', 77, 15, 0, 0, 179, 2, 0, 0, 122, 2, 0, 0, 56, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 72, 2, 'O', 'U', 98, 15, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'G', 'G', 105, 15, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 127, 15, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 240, 1, 'Q', 'T', 147, 15, 0, 0, 96, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 111, 0, 'N', 'N', 106, 15, 'O', 'O', 107, 15, 'R', 'R', 108, 15, 'E', 'E', 109, 15, '_', '_', 110, 15, 'D', 'S', 111, 15, 0, 0, 241, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 242, 0, 'S', 'S', 128, 15, 'T', 'T', 129, 15, 'E', 'E', 130, 15, 'R', 'R', 131, 15, '_', '_', 132, 15, 'S', 'S', 133, 15, 'S', 'S', 134, 15, 'L', 'L', 135, 15, '_', '_', 136, 15, 'C', 'C', 137, 15, 'A', 'I', 138, 15, 0, 0, 69, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 71, 1, 0, 0, 52, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 71, 2, 0, 0, 94, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 168, 15, 0, 0, 133, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'T', 183, 15, 'S', 'X', 177, 15, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 100, 1, 0, 0, 73, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 84, 1, 0, 0, 11, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 73, 2, 'A', 'A', 200, 15, 'S', 'X', 201, 15, 0, 0, 58, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, '_', '_', 207, 15, 'Q', 'U', 208, 15, 0, 0, 81, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'P', 'S', 213, 15, 0, 0, 85, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 86, 1, }; static uchar symbols_map[14956]= { 0, 0, 179, 2, '!', '|', 29, 0, '<', 'X', 157, 0, 'B', 'Y', 24, 1, 'A', 'W', 230, 2, 'A', 'W', 104, 4, 'A', 'W', 51, 6, 'C', 'Z', 81, 8, 'A', 'V', 38, 10, 'A', 'Y', 37, 11, 'C', 'U', 15, 12, 'C', 'V', 160, 12, 'C', 'W', 50, 13, 'A', 'U', 122, 13, 'A', 'S', 203, 13, 'D', 'U', 253, 13, 'C', 'S', 19, 14, 'C', 'S', 89, 14, 0, 0, 54, 2, 'M', 'M', 137, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 78, 1, 0, 0, 80, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 75, 1, 0, 0, 3, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 0, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, '<', '>', 121, 0, 0, 0, 179, 2, '=', '>', 124, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'T', 126, 0, 0, 0, 49, 0, 0, 0, 179, 2, 0, 0, 149, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'S', 128, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 122, 1, 'F', 'R', 144, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 109, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 173, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 178, 2, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, 0, 23, 0, 0, 0, 27, 0, 0, 0, 236, 0, 0, 0, 179, 2, 0, 0, 238, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 246, 0, 0, 0, 12, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 15, 1, 0, 0, 138, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 141, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 150, 1, 0, 0, 7, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'V', 186, 0, 0, 0, 41, 0, 0, 0, 102, 0, 'A', 'I', 227, 0, 0, 0, 164, 0, 0, 0, 205, 0, 0, 0, 217, 0, 0, 0, 179, 2, 'N', 'P', 236, 0, 0, 0, 179, 2, 0, 0, 24, 1, 0, 0, 179, 2, 0, 0, 104, 1, 0, 0, 131, 1, 'N', 'U', 239, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 247, 0, 'E', 'S', 6, 1, 0, 0, 179, 2, 0, 0, 136, 2, 0, 0, 152, 2, 0, 0, 179, 2, 'M', 'O', 21, 1, 0, 0, 11, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 16, 0, 0, 0, 179, 2, 'D', 'Y', 205, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 24, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 32, 0, 0, 0, 21, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 22, 0, 0, 0, 122, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 128, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 148, 0, 0, 0, 2, 1, 0, 0, 179, 2, 0, 0, 14, 1, 0, 0, 142, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 154, 1, 0, 0, 200, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 253, 1, 0, 0, 21, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 47, 2, 0, 0, 179, 2, 0, 0, 66, 2, 0, 0, 174, 2, 0, 0, 179, 2, 0, 0, 172, 2, 'L', 'Y', 48, 1, 'A', 'U', 79, 1, 'A', 'U', 108, 1, 'A', 'X', 135, 1, 'A', 'U', 177, 1, 0, 0, 219, 0, 'A', 'O', 198, 1, 'N', 'N', 218, 1, 'O', 'S', 251, 1, 'E', 'I', 0, 2, 'A', 'O', 5, 2, 0, 0, 105, 1, 'A', 'U', 58, 2, 'N', 'V', 79, 2, 'A', 'R', 88, 2, 0, 0, 179, 2, 'E', 'O', 120, 2, 'H', 'T', 153, 2, 'E', 'Y', 174, 2, 'N', 'S', 209, 2, 0, 0, 153, 2, 'A', 'O', 215, 2, 0, 0, 171, 2, 0, 0, 175, 2, 0, 0, 42, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'T', 62, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 50, 0, 0, 0, 44, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 45, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 47, 0, 'L', 'S', 100, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 60, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 69, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 72, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 105, 0, 0, 0, 52, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 55, 0, 'T', 'T', 129, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 137, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 145, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 152, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 153, 0, 'A', 'E', 130, 1, 0, 0, 116, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 120, 0, 0, 0, 157, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 158, 0, 0, 0, 179, 2, 'D', 'U', 159, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 183, 0, 0, 0, 165, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 168, 0, 0, 0, 191, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 196, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 210, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 211, 0, 'R', 'S', 213, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 227, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'U', 215, 1, 0, 0, 224, 0, 0, 0, 225, 0, 0, 0, 230, 0, 0, 0, 179, 2, 0, 0, 232, 0, 'T', 'T', 219, 1, '1', 'O', 220, 1, 0, 0, 3, 1, 0, 0, 4, 1, 0, 0, 5, 1, 0, 0, 6, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 7, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 11, 1, 0, 0, 21, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 22, 1, 0, 0, 25, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 27, 1, 0, 0, 29, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'F', 'S', 20, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'K', 'S', 34, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 43, 2, 0, 0, 35, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 36, 1, 0, 0, 38, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 42, 1, 0, 0, 43, 1, 0, 0, 179, 2, 0, 0, 47, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 51, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 52, 1, 0, 0, 55, 1, 0, 0, 113, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 120, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 130, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 134, 1, 0, 0, 144, 1, 0, 0, 179, 2, 0, 0, 145, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 157, 1, 'G', 'T', 106, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 177, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 184, 1, 0, 0, 162, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 166, 1, 'A', 'A', 131, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'W', 141, 2, 'D', 'L', 132, 2, 0, 0, 201, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 205, 1, 0, 0, 249, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 0, 2, 0, 0, 24, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 29, 2, 0, 0, 33, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'F', 'M', 166, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 75, 2, 0, 0, 37, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 38, 2, 0, 0, 98, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'E', 195, 2, 'E', 'M', 200, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 116, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 118, 2, 0, 0, 99, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 100, 2, 0, 0, 101, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 102, 2, 0, 0, 124, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 137, 2, 0, 0, 157, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 159, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 161, 2, 0, 0, 165, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 168, 2, 'D', 'S', 253, 2, 'E', 'T', 13, 3, 'A', 'Y', 29, 3, 0, 0, 179, 2, 'L', 'V', 59, 3, 'A', 'O', 76, 3, 'R', 'R', 109, 3, 0, 0, 231, 0, 'N', 'N', 125, 3, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 138, 3, 'A', 'Y', 185, 3, 'A', 'E', 210, 3, 'R', 'W', 215, 3, 'H', 'U', 221, 3, 'U', 'U', 235, 3, 'A', 'T', 241, 3, 'H', 'W', 32, 4, 0, 0, 90, 2, 'N', 'S', 61, 4, 0, 0, 144, 2, 'H', 'R', 88, 4, 0, 0, 12, 0, 0, 0, 179, 2, 0, 0, 13, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 18, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 25, 0, 0, 0, 36, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 43, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 48, 0, 0, 0, 51, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'E', 54, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 70, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 104, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 115, 0, 0, 0, 57, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 63, 0, 0, 0, 160, 0, 0, 0, 161, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 169, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'E', 70, 3, 'N', 'R', 71, 3, 0, 0, 173, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 175, 0, 0, 0, 190, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 194, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'X', 91, 3, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'U', 98, 3, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'U', 105, 3, 0, 0, 197, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 198, 0, 0, 0, 199, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 202, 0, 0, 0, 206, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 209, 0, 'A', 'O', 110, 3, 0, 0, 220, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 222, 0, 'D', 'O', 126, 3, 0, 0, 248, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 252, 0, 0, 0, 253, 0, 'A', 'V', 149, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'M', 'N', 171, 3, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'C', 173, 3, 0, 0, 33, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 37, 1, 0, 0, 39, 1, 0, 0, 41, 1, 'A', 'K', 174, 3, 0, 0, 44, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 49, 1, 0, 0, 79, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 93, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 98, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 109, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 110, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 111, 1, 0, 0, 114, 1, 0, 0, 179, 2, 0, 0, 117, 1, 0, 0, 179, 2, 0, 0, 119, 1, 0, 0, 151, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 155, 1, 0, 0, 179, 2, 0, 0, 159, 1, 0, 0, 174, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 193, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 194, 1, 'E', 'I', 236, 3, 0, 0, 196, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 197, 1, 'I', 'N', 5, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'U', 11, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 247, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 248, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 4, 2, 0, 0, 198, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 199, 1, 0, 0, 204, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 214, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 234, 1, 0, 0, 179, 2, 0, 0, 244, 1, 0, 0, 23, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 30, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 48, 4, 0, 0, 83, 2, 0, 0, 179, 2, 0, 0, 85, 2, 'G', 'R', 49, 4, 0, 0, 42, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 67, 2, 'I', 'T', 67, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 79, 4, 0, 0, 126, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 132, 2, 0, 0, 135, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 140, 2, 'E', 'I', 99, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 170, 2, 0, 0, 162, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 163, 2, 'C', 'T', 127, 4, 'A', 'I', 145, 4, 'H', 'U', 174, 4, 'E', 'O', 190, 4, 'L', 'X', 201, 4, 'A', 'O', 242, 4, 'L', 'R', 9, 5, 0, 0, 226, 0, 'G', 'S', 16, 5, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 48, 5, 'A', 'O', 59, 5, 'E', 'U', 84, 5, 'F', 'T', 101, 5, 'A', 'L', 116, 5, 0, 0, 179, 2, 'E', 'O', 128, 5, 'C', 'Y', 179, 5, 0, 0, 92, 2, 'N', 'P', 36, 6, 0, 0, 145, 2, 'I', 'I', 43, 6, 0, 0, 10, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 19, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 28, 0, 0, 0, 34, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 35, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'G', 'N', 154, 4, 0, 0, 38, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'L', 162, 4, 0, 0, 39, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 40, 0, 0, 0, 58, 0, 0, 0, 66, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 68, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'M', 188, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 103, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 113, 0, 0, 0, 75, 0, 0, 0, 84, 0, 0, 0, 135, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 150, 0, 0, 0, 159, 0, 0, 0, 179, 2, 'A', 'G', 214, 4, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 170, 0, 0, 0, 171, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 174, 0, 0, 0, 179, 2, 'C', 'P', 221, 4, 0, 0, 162, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 166, 0, 0, 0, 177, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 182, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'O', 235, 4, 0, 0, 185, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 186, 0, 0, 0, 192, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 195, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'O', 1, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 208, 0, 'A', 'A', 2, 5, 'T', 'T', 3, 5, '4', '8', 4, 5, 0, 0, 200, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 201, 0, 0, 0, 218, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 221, 0, 0, 0, 239, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 244, 0, 'F', 'S', 29, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'S', 43, 5, 0, 0, 250, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 255, 0, 0, 0, 17, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 18, 1, 0, 0, 34, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 40, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 48, 1, 0, 0, 57, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'M', 74, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 99, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 107, 1, 0, 0, 88, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 92, 1, 0, 0, 118, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 128, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 135, 1, 0, 0, 139, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 143, 1, 0, 0, 179, 2, 0, 0, 148, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 153, 1, 0, 0, 164, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 167, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 175, 1, 'G', 'V', 139, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'W', 167, 5, 0, 0, 213, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 220, 1, 0, 0, 221, 1, 0, 0, 222, 1, 0, 0, 179, 2, 'A', 'L', 155, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 239, 1, 0, 0, 241, 1, 0, 0, 179, 2, 0, 0, 246, 1, 0, 0, 224, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 232, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 227, 1, 0, 0, 251, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 255, 1, 0, 0, 7, 2, 0, 0, 179, 2, 'C', 'T', 202, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'G', 'M', 234, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 31, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'U', 247, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'R', 15, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 88, 2, 0, 0, 10, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 13, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'V', 220, 5, 0, 0, 179, 2, 0, 0, 22, 2, 0, 0, 17, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 20, 2, 'N', 'N', 241, 5, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 28, 2, 'A', 'E', 242, 5, 0, 0, 26, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 27, 2, 0, 0, 36, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 39, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'R', 10, 6, 0, 0, 40, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 41, 2, 'R', 'T', 33, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 43, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 78, 2, 0, 0, 69, 2, 0, 0, 179, 2, 0, 0, 74, 2, 'I', 'L', 39, 6, 0, 0, 179, 2, 0, 0, 133, 2, 0, 0, 127, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 129, 2, 'N', 'T', 44, 6, 0, 0, 164, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 166, 2, 'C', 'U', 74, 6, 'E', 'O', 93, 6, 'A', 'U', 104, 6, 'E', 'Y', 151, 6, 'N', 'X', 199, 6, 'O', 'O', 224, 6, 0, 0, 214, 0, 'A', 'I', 232, 6, 'G', 'T', 241, 6, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 18, 7, 'I', 'O', 33, 7, 'A', 'U', 40, 7, 'P', 'U', 115, 7, 'A', 'R', 121, 7, 0, 0, 195, 1, 'E', 'O', 170, 7, 'C', 'Y', 231, 7, 'H', 'R', 16, 8, 'N', 'S', 27, 8, 'A', 'I', 36, 8, 'I', 'R', 71, 8, 0, 0, 9, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 14, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 20, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 29, 0, 0, 0, 37, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 46, 0, 0, 0, 53, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 125, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 131, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 106, 0, 'N', 'R', 126, 6, 0, 0, 59, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 62, 0, 'L', 'U', 134, 6, 'M', 'P', 144, 6, 'T', 'V', 148, 6, 0, 0, 73, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 77, 0, 0, 0, 83, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 86, 0, 0, 0, 98, 0, 0, 0, 179, 2, 0, 0, 101, 0, 'C', 'L', 172, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 195, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 156, 0, 'I', 'L', 182, 6, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 186, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 133, 0, 0, 0, 129, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 130, 0, 0, 0, 131, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 132, 0, 'A', 'C', 196, 6, 0, 0, 143, 0, 0, 0, 179, 2, 0, 0, 144, 0, 0, 0, 167, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 172, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'P', 210, 6, 0, 0, 179, 0, 0, 0, 179, 2, 0, 0, 180, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 187, 0, 'L', 'R', 225, 6, 0, 0, 204, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 207, 0, 0, 0, 223, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 229, 0, 0, 0, 240, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'V', 255, 6, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 19, 1, 0, 0, 249, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 1, 1, 0, 0, 8, 1, 0, 0, 179, 2, 0, 0, 20, 1, 0, 0, 31, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 32, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 50, 1, 0, 0, 97, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 108, 1, 0, 0, 116, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 121, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', '_', 61, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 136, 1, 'A', 'Y', 90, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 127, 1, 0, 0, 125, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 126, 1, 0, 0, 147, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 156, 1, 'C', 'R', 139, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 176, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 178, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 155, 7, 0, 0, 160, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 168, 1, 0, 0, 182, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 186, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'F', 166, 7, 0, 0, 189, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 191, 1, 'B', 'V', 181, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'U', 'W', 228, 7, 0, 0, 206, 1, 0, 0, 207, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 219, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'L', 202, 7, 0, 0, 233, 1, 0, 0, 179, 2, 'T', 'T', 212, 7, 0, 0, 243, 1, 0, 0, 179, 2, 0, 0, 245, 1, 'A', 'I', 203, 7, 0, 0, 226, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 228, 1, 'A', 'O', 213, 7, 0, 0, 236, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 237, 1, 0, 0, 252, 1, 0, 0, 179, 2, 0, 0, 1, 2, 0, 0, 9, 2, 0, 0, 179, 2, 0, 0, 19, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 44, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 76, 2, 'B', 'S', 254, 7, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 87, 2, 0, 0, 80, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 84, 2, 0, 0, 113, 2, 0, 0, 107, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 114, 2, 'I', 'K', 33, 8, 0, 0, 179, 2, 0, 0, 134, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 139, 2, 0, 0, 125, 2, 0, 0, 179, 2, 0, 0, 128, 2, 'R', 'R', 45, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'S', 69, 8, 'C', 'Y', 46, 8, 0, 0, 147, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 151, 2, 0, 0, 154, 2, 0, 0, 155, 2, 0, 0, 167, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 169, 2, 'A', 'O', 105, 8, 'A', 'U', 144, 8, 'N', 'X', 181, 8, 'U', 'U', 212, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 9, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'O', 216, 8, 'A', 'O', 252, 8, 'A', 'V', 35, 9, 'P', 'V', 57, 9, 'A', 'R', 64, 9, 0, 0, 179, 2, 'E', 'O', 113, 9, 'C', 'W', 164, 9, 'I', 'R', 200, 9, 'N', 'T', 252, 9, 0, 0, 149, 2, 0, 0, 158, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 177, 2, 0, 0, 54, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 65, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'N', 120, 8, 0, 0, 71, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'T', 'T', 134, 8, 'A', 'I', 135, 8, 0, 0, 97, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 99, 0, 'T', 'Y', 165, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 138, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 146, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 154, 0, 'A', 'E', 171, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 123, 0, 'B', 'F', 176, 8, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 121, 0, 0, 0, 117, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 119, 0, 0, 0, 163, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'T', 192, 8, 0, 0, 176, 0, 0, 0, 179, 2, 0, 0, 178, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 188, 0, 'L', 'N', 213, 8, 0, 0, 212, 0, 0, 0, 179, 2, 0, 0, 213, 0, 0, 0, 28, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'N', 231, 8, 'G', 'G', 232, 8, 'B', 'T', 233, 8, 0, 0, 53, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 54, 1, 'X', 'X', 11, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'N', 24, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 106, 1, 'V', '_', 12, 9, 0, 0, 87, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'S', 22, 9, 0, 0, 82, 1, 0, 0, 83, 1, 'V', '_', 25, 9, 0, 0, 102, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 103, 1, 0, 0, 115, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 132, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 137, 1, 0, 0, 146, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 158, 1, 0, 0, 172, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 82, 9, 'C', 'V', 93, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 192, 1, 0, 0, 179, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 183, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 185, 1, 'D', 'S', 124, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'W', 152, 9, 0, 0, 210, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 215, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 229, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'T', 140, 9, 0, 0, 235, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 238, 1, 0, 0, 250, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 254, 1, 0, 0, 6, 2, 0, 0, 179, 2, 'C', 'Q', 185, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 25, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 35, 2, 0, 0, 34, 2, 0, 0, 179, 2, 0, 0, 45, 2, 0, 0, 49, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 68, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 86, 2, 0, 0, 12, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 16, 2, 'N', 'N', 210, 9, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'U', 231, 9, 'Y', 'Y', 211, 9, 'B', 'T', 212, 9, 0, 0, 106, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 108, 2, 0, 0, 110, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 115, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 117, 2, 'D', 'S', 3, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'C', 'C', 19, 10, 0, 0, 123, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 131, 2, '_', '_', 20, 10, 'D', 'T', 21, 10, 0, 0, 141, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 142, 2, 'G', 'L', 60, 10, 0, 0, 179, 2, 'H', 'O', 66, 10, 'A', 'U', 77, 10, 'X', 'X', 98, 10, 'E', 'O', 113, 10, 0, 0, 215, 0, 0, 0, 179, 2, 'M', 'S', 124, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 45, 1, 'E', 'I', 151, 10, 0, 0, 129, 1, 0, 0, 179, 2, 'A', 'R', 156, 10, 0, 0, 179, 2, 'E', 'O', 207, 10, 'A', 'T', 238, 10, 'E', 'I', 5, 11, 'N', 'N', 18, 11, 'A', 'A', 27, 11, 0, 0, 15, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 17, 0, 0, 0, 61, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 74, 10, 0, 0, 74, 0, 0, 0, 85, 0, 0, 0, 90, 0, 0, 0, 118, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 142, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 155, 0, 'C', 'P', 99, 10, 0, 0, 181, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 184, 0, 0, 0, 193, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 203, 0, 0, 0, 243, 0, 'C', 'V', 131, 10, 0, 0, 13, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 16, 1, 0, 0, 247, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 245, 0, 0, 0, 179, 2, 0, 0, 10, 1, 0, 0, 90, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 96, 1, 'C', 'R', 174, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'O', 190, 10, 0, 0, 161, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 169, 1, 'C', 'C', 201, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 188, 1, 'E', 'I', 202, 10, 0, 0, 180, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 181, 1, 'A', 'T', 218, 10, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 2, 2, 0, 0, 202, 1, 0, 0, 179, 2, 0, 0, 208, 1, 0, 0, 211, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 242, 1, 0, 0, 5, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'P', 2, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 32, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 53, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 70, 2, 0, 0, 14, 2, 0, 0, 179, 2, 0, 0, 15, 2, 'M', 'M', 10, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 103, 2, 'P', 'P', 11, 11, 'O', 'T', 12, 11, 0, 0, 95, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 96, 2, 'B', 'I', 19, 11, 0, 0, 119, 2, 0, 0, 179, 2, 0, 0, 121, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 130, 2, 'R', 'R', 28, 11, 'B', 'I', 29, 11, 0, 0, 146, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 150, 2, 'C', 'S', 62, 11, 0, 0, 179, 2, 'H', 'O', 79, 11, 'A', 'E', 138, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 216, 0, 0, 0, 179, 2, 0, 0, 237, 0, 0, 0, 23, 1, 0, 0, 179, 2, 0, 0, 30, 1, 'A', 'E', 152, 11, 'O', 'O', 180, 11, 'P', 'R', 191, 11, 'A', 'R', 194, 11, 0, 0, 179, 2, 'E', 'O', 212, 11, 'Q', 'Q', 239, 11, 'A', 'E', 250, 11, 0, 0, 179, 2, 0, 0, 156, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 176, 2, 0, 0, 8, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 26, 0, 0, 0, 64, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 87, 11, 'U', 'U', 90, 11, 'P', 'P', 101, 11, 'C', 'S', 109, 11, 'M', 'M', 91, 11, 'N', 'N', 92, 11, '_', '_', 93, 11, 'A', 'G', 94, 11, 0, 0, 78, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 82, 0, 'L', 'R', 102, 11, 0, 0, 87, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 88, 0, 0, 0, 89, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 91, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'I', 'T', 126, 11, 0, 0, 92, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 93, 0, 'Y', 'Y', 143, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 127, 0, '_', '_', 144, 11, 'M', 'S', 145, 11, 0, 0, 125, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 126, 0, 0, 0, 67, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'D', 'D', 157, 11, 'I', 'I', 158, 11, 'U', 'U', 159, 11, 'M', 'M', 160, 11, 'B', 'T', 161, 11, 0, 0, 89, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 91, 1, 'M', 'M', 181, 11, 'A', 'I', 182, 11, 0, 0, 123, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 124, 1, 0, 0, 149, 1, 0, 0, 179, 2, 0, 0, 152, 1, 0, 0, 171, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 173, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 187, 1, 'A', 'P', 223, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 3, 2, 0, 0, 203, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 212, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 223, 1, 0, 0, 225, 1, 'L', 'L', 240, 11, 'W', '_', 241, 11, 0, 0, 50, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 57, 2, 'B', 'B', 255, 11, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 97, 2, 'L', 'L', 0, 12, 'E', 'E', 1, 12, 'S', '_', 2, 12, 0, 0, 93, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 91, 2, 'O', 'U', 34, 12, 'I', 'I', 44, 12, 0, 0, 189, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'O', 'O', 64, 12, 0, 0, 254, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'Y', 75, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 190, 1, 0, 0, 179, 2, 'E', 'E', 119, 12, 'C', 'Y', 137, 12, 0, 0, 111, 2, 0, 0, 120, 2, 0, 0, 76, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'R', 41, 12, 'R', 'S', 42, 12, 0, 0, 108, 0, 0, 0, 114, 0, 'A', 'S', 45, 12, 0, 0, 141, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 147, 0, 'U', 'U', 65, 12, 'R', 'R', 66, 12, '_', '_', 67, 12, 'M', 'S', 68, 12, 0, 0, 234, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 235, 0, 'S', 'S', 100, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 95, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 112, 1, 'T', 'T', 101, 12, 'E', 'E', 102, 12, 'R', 'R', 103, 12, '_', '_', 104, 12, 'H', 'U', 105, 12, 0, 0, 61, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 65, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 76, 1, 'P', 'P', 120, 12, 'L', 'L', 121, 12, 'I', 'I', 122, 12, 'C', 'C', 123, 12, 'A', 'A', 124, 12, 'T', '_', 125, 12, 0, 0, 231, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 230, 1, 0, 0, 8, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 61, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 89, 2, 'A', 'U', 180, 12, 0, 0, 139, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 251, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 56, 1, 'A', 'E', 228, 12, 0, 0, 179, 2, 0, 0, 140, 1, 0, 0, 170, 1, 0, 0, 179, 2, 0, 0, 218, 1, 'E', 'U', 233, 12, 0, 0, 104, 2, 0, 0, 179, 2, 0, 0, 148, 2, 0, 0, 56, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 67, 0, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'N', 201, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'R', 'R', 204, 12, 0, 0, 79, 0, 0, 0, 179, 2, 0, 0, 100, 0, 'R', 'R', 205, 12, 'E', 'E', 206, 12, 'N', 'N', 207, 12, 'T', 'T', 208, 12, '_', '_', 209, 12, 'D', 'U', 210, 12, 0, 0, 107, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 109, 0, 0, 0, 179, 2, 0, 0, 110, 0, 0, 0, 112, 0, 0, 0, 59, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 94, 1, 0, 0, 18, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'L', 'L', 250, 12, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 81, 2, 'E', '_', 251, 12, 0, 0, 48, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'N', 'T', 22, 13, 0, 0, 55, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 29, 13, 'I', 'I', 30, 13, '_', '_', 31, 13, 'H', 'Y', 32, 13, 0, 0, 60, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 62, 2, 0, 0, 179, 2, 0, 0, 65, 2, 'O', 'O', 71, 13, 'E', 'O', 79, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 228, 0, 0, 0, 0, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 90, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 163, 1, 0, 0, 179, 2, 'E', 'E', 99, 13, 'Q', 'U', 107, 13, 'I', 'R', 112, 13, 0, 0, 143, 2, 0, 0, 179, 2, 0, 0, 160, 2, 'L', 'L', 72, 13, 'U', 'U', 73, 13, 'M', 'M', 74, 13, 'N', 'N', 75, 13, '_', '_', 76, 13, 'C', 'D', 77, 13, 0, 0, 80, 0, 0, 0, 81, 0, 0, 0, 140, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 151, 0, 0, 0, 68, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 101, 1, 'F', 'L', 100, 13, 0, 0, 46, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 217, 1, 0, 0, 63, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 77, 2, 0, 0, 82, 2, 0, 0, 105, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 112, 2, 'U', 'V', 143, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 26, 1, 0, 0, 46, 1, 'A', 'A', 145, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 216, 1, 'Q', 'Q', 171, 13, 0, 0, 94, 2, 0, 0, 138, 2, 0, 0, 30, 0, 0, 0, 33, 0, 'S', 'S', 146, 13, 'T', 'T', 147, 13, 'E', 'E', 148, 13, 'R', 'R', 149, 13, '_', '_', 150, 13, 'L', 'S', 151, 13, 0, 0, 63, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 159, 13, 'L', 'L', 160, 13, '_', '_', 161, 13, 'C', 'K', 162, 13, 0, 0, 72, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 74, 1, 'L', 'L', 172, 13, '_', '_', 173, 13, 'B', 'T', 174, 13, 0, 0, 51, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'S', 'S', 193, 13, 'I', 'I', 194, 13, '_', '_', 195, 13, 'M', 'S', 196, 13, 0, 0, 59, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 58, 2, 0, 0, 31, 0, 0, 0, 179, 2, 0, 0, 95, 0, 'A', 'E', 222, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 227, 13, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 165, 1, 0, 0, 179, 2, 0, 0, 179, 2, 'Q', 'U', 248, 13, 0, 0, 124, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 134, 0, 'S', 'S', 228, 13, 'T', 'T', 229, 13, 'E', 'E', 230, 13, 'R', 'R', 231, 13, '_', '_', 232, 13, 'G', 'U', 233, 13, 0, 0, 60, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 62, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 64, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 70, 1, 0, 0, 179, 2, 0, 0, 77, 1, 0, 0, 64, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 79, 2, 0, 0, 136, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 233, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 66, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 209, 1, 'Q', 'T', 15, 14, 0, 0, 179, 2, 0, 0, 122, 2, 0, 0, 56, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 72, 2, 'O', 'U', 36, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'G', 'G', 43, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'A', 65, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 240, 1, 'Q', 'T', 85, 14, 0, 0, 96, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 111, 0, 'N', 'N', 44, 14, 'O', 'O', 45, 14, 'R', 'R', 46, 14, 'E', 'E', 47, 14, '_', '_', 48, 14, 'D', 'S', 49, 14, 0, 0, 241, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 242, 0, 'S', 'S', 66, 14, 'T', 'T', 67, 14, 'E', 'E', 68, 14, 'R', 'R', 69, 14, '_', '_', 70, 14, 'S', 'S', 71, 14, 'S', 'S', 72, 14, 'L', 'L', 73, 14, '_', '_', 74, 14, 'C', 'C', 75, 14, 'A', 'I', 76, 14, 0, 0, 69, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 71, 1, 0, 0, 52, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 71, 2, 0, 0, 94, 0, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'A', 'I', 106, 14, 0, 0, 133, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'E', 'T', 121, 14, 'S', 'X', 115, 14, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 100, 1, 0, 0, 73, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 84, 1, 0, 0, 11, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 73, 2, 'A', 'A', 138, 14, 'S', 'X', 139, 14, 0, 0, 58, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, '_', '_', 145, 14, 'Q', 'U', 146, 14, 0, 0, 81, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 179, 2, 'P', 'S', 151, 14, 0, 0, 85, 1, 0, 0, 179, 2, 0, 0, 179, 2, 0, 0, 86, 1, }; static unsigned int sql_functions_max_len=29; static unsigned int symbols_max_len=29; static SYMBOL *get_hash_symbol(const char *s, unsigned int len,bool function) { uchar *hash_map; const char *cur_str= s; if (len == 0) { DBUG_PRINT("warning", ("get_hash_symbol() received a request for a zero-length symbol, which is probably a mistake.")); return(NULL); } if (function){ if (len>sql_functions_max_len) return 0; hash_map= sql_functions_map; uint32 cur_struct= uint4korr(hash_map+((len-1)*4)); for (;;){ uchar first_char= (uchar)cur_struct; if (first_char == 0) { int16 ires= (int16)(cur_struct>>16); if (ires==array_elements(symbols)) return 0; SYMBOL *res; if (ires>=0) res= symbols+ires; else res= sql_functions-ires-1; uint count= (uint) (cur_str - s); return lex_casecmp(cur_str,res->name+count,len-count) ? 0 : res; } uchar cur_char= (uchar)to_upper_lex[(uchar)*cur_str]; if (cur_char>=8; if (cur_char>(uchar)cur_struct) return 0; cur_struct>>=8; cur_struct= uint4korr(hash_map+ (((uint16)cur_struct + cur_char - first_char)*4)); cur_str++; } }else{ if (len>symbols_max_len) return 0; hash_map= symbols_map; uint32 cur_struct= uint4korr(hash_map+((len-1)*4)); for (;;){ uchar first_char= (uchar)cur_struct; if (first_char==0) { int16 ires= (int16)(cur_struct>>16); if (ires==array_elements(symbols)) return 0; SYMBOL *res= symbols+ires; uint count= (uint) (cur_str - s); return lex_casecmp(cur_str,res->name+count,len-count)!=0 ? 0 : res; } uchar cur_char= (uchar)to_upper_lex[(uchar)*cur_str]; if (cur_char>=8; if (cur_char>(uchar)cur_struct) return 0; cur_struct>>=8; cur_struct= uint4korr(hash_map+ (((uint16)cur_struct + cur_char - first_char)*4)); cur_str++; } } } mysql/server/private/sql_delete.h000064400000002477151027430560013200 0ustar00/* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_DELETE_INCLUDED #define SQL_DELETE_INCLUDED #include "my_base.h" /* ha_rows */ class THD; struct TABLE_LIST; class Item; class select_result; typedef class Item COND; template class SQL_I_List; int mysql_prepare_delete(THD *thd, TABLE_LIST *table_list, Item **conds, bool *delete_while_scanning); bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds, SQL_I_List *order, ha_rows rows, ulonglong options, select_result *result); #endif /* SQL_DELETE_INCLUDED */ mysql/server/private/proxy_protocol.h000064400000001044151027430560014146 0ustar00#include "my_net.h" struct proxy_peer_info { struct sockaddr_storage peer_addr; int port; bool is_local_command; }; extern bool has_proxy_protocol_header(NET *net); extern int parse_proxy_protocol_header(NET *net, proxy_peer_info *peer_info); extern bool is_proxy_protocol_allowed(const sockaddr *remote_addr); extern int init_proxy_protocol_networks(const char *spec); extern void destroy_proxy_protocol_networks(); extern int set_proxy_protocol_networks(const char *spec); extern bool proxy_protocol_networks_valid(const char *spec); mysql/server/private/item_timefunc.h000064400000176147151027430560013715 0ustar00#ifndef ITEM_TIMEFUNC_INCLUDED #define ITEM_TIMEFUNC_INCLUDED /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. Copyright (c) 2009-2011, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Function items used by mysql */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif class MY_LOCALE; bool get_interval_value(THD *thd, Item *args, interval_type int_type, INTERVAL *interval); class Item_long_func_date_field: public Item_long_ge0_func { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()); } public: Item_long_func_date_field(THD *thd, Item *a) :Item_long_ge0_func(thd, a) { } }; class Item_long_func_time_field: public Item_long_ge0_func { bool check_arguments() const override { return args[0]->check_type_can_return_time(func_name_cstring()); } public: Item_long_func_time_field(THD *thd, Item *a) :Item_long_ge0_func(thd, a) { } }; class Item_func_period_add :public Item_long_func { bool check_arguments() const override { return check_argument_types_can_return_int(0, 2); } public: Item_func_period_add(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("period_add") }; return name; } bool fix_length_and_dec() override { max_length=6*MY_CHARSET_BIN_MB_MAXLEN; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_period_diff :public Item_long_func { bool check_arguments() const override { return check_argument_types_can_return_int(0, 2); } public: Item_func_period_diff(THD *thd, Item *a, Item *b): Item_long_func(thd, a, b) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("period_diff") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=6*MY_CHARSET_BIN_MB_MAXLEN; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_to_days :public Item_long_func_date_field { public: Item_func_to_days(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("to_days") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=6*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } enum_monotonicity_info get_monotonicity_info() const override; longlong val_int_endpoint(bool left_endp, bool *incl_endp) override; bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_to_seconds :public Item_longlong_func { bool check_arguments() const override { return check_argument_types_can_return_date(0, arg_count); } public: Item_func_to_seconds(THD *thd, Item *a): Item_longlong_func(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("to_seconds") }; return name; } bool fix_length_and_dec() override { decimals=0; fix_char_length(12); set_maybe_null(); return FALSE; } enum_monotonicity_info get_monotonicity_info() const override; longlong val_int_endpoint(bool left_endp, bool *incl_endp) override; bool check_partition_func_processor(void *bool_arg) override { return FALSE;} /* Only meaningful with date part and optional time part */ bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dayofmonth :public Item_long_func_date_field { public: Item_func_dayofmonth(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("dayofmonth") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_month :public Item_long_ge0_func { public: Item_func_month(THD *thd, Item *a): Item_long_ge0_func(thd, a) { } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("month") }; return name; } bool fix_length_and_dec() override { decimals= 0; fix_char_length(2); set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_monthname :public Item_str_func { MY_LOCALE *locale; public: Item_func_monthname(THD *thd, Item *a): Item_str_func(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("monthname") }; return name; } String *val_str(String *str) override; bool fix_length_and_dec() override; bool check_partition_func_processor(void *int_arg) override {return TRUE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dayofyear :public Item_long_func_date_field { public: Item_func_dayofyear(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("dayofyear") }; return name; } bool fix_length_and_dec() override { decimals= 0; fix_char_length(3); set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_hour :public Item_long_func_time_field { public: Item_func_hour(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("hour") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_time_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_minute :public Item_long_func_time_field { public: Item_func_minute(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("minute") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_time_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_quarter :public Item_long_func_date_field { public: Item_func_quarter(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("quarter") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=1*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_second :public Item_long_func_time_field { public: Item_func_second(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("second") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_time_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_week :public Item_long_ge0_func { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()) || (arg_count > 1 && args[1]->check_type_can_return_int(func_name_cstring())); } public: Item_func_week(THD *thd, Item *a): Item_long_ge0_func(thd, a) {} Item_func_week(THD *thd, Item *a, Item *b): Item_long_ge0_func(thd, a, b) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("week") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=2*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_vcol_func_processor(void *arg) override { if (arg_count == 2) return FALSE; return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } bool check_valid_arguments_processor(void *int_arg) override { return arg_count == 2; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_yearweek :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()) || args[1]->check_type_can_return_int(func_name_cstring()); } public: Item_func_yearweek(THD *thd, Item *a, Item *b) :Item_long_func(thd, a, b) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("yearweek") }; return name; } bool fix_length_and_dec() override { decimals=0; max_length=6*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_year :public Item_long_func_date_field { public: Item_func_year(THD *thd, Item *a): Item_long_func_date_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("year") }; return name; } enum_monotonicity_info get_monotonicity_info() const override; longlong val_int_endpoint(bool left_endp, bool *incl_endp) override; bool fix_length_and_dec() override { decimals=0; max_length=4*MY_CHARSET_BIN_MB_MAXLEN; set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_weekday :public Item_long_func { bool odbc_type; public: Item_func_weekday(THD *thd, Item *a, bool type_arg): Item_long_func(thd, a), odbc_type(type_arg) { } longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING dayofweek= {STRING_WITH_LEN("dayofweek") }; static LEX_CSTRING weekday= {STRING_WITH_LEN("weekday") }; return (odbc_type ? dayofweek : weekday); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return type_handler()->Item_get_date_with_warn(thd, this, ltime, fuzzydate); } bool fix_length_and_dec() override { decimals= 0; fix_char_length(1); set_maybe_null(); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dayname :public Item_str_func { MY_LOCALE *locale; public: Item_func_dayname(THD *thd, Item *a): Item_str_func(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("dayname") }; return name; } String *val_str(String *str) override; const Type_handler *type_handler() const override { return &type_handler_varchar; } bool fix_length_and_dec() override; bool check_partition_func_processor(void *int_arg) override {return TRUE;} bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } bool check_valid_arguments_processor(void *int_arg) override { return !has_date_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_seconds_hybrid: public Item_func_numhybrid { public: Item_func_seconds_hybrid(THD *thd): Item_func_numhybrid(thd) {} Item_func_seconds_hybrid(THD *thd, Item *a): Item_func_numhybrid(thd, a) {} void fix_length_and_dec_generic(uint dec) { DBUG_ASSERT(dec <= TIME_SECOND_PART_DIGITS); decimals= dec; max_length=17 + (decimals ? decimals + 1 : 0); set_maybe_null(); if (decimals) set_handler(&type_handler_newdecimal); else set_handler(type_handler_long_or_longlong()); } double real_op() override { DBUG_ASSERT(0); return 0; } String *str_op(String *str) override { DBUG_ASSERT(0); return 0; } bool date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { DBUG_ASSERT(0); return true; } }; class Item_func_unix_timestamp :public Item_func_seconds_hybrid { bool get_timestamp_value(my_time_t *seconds, ulong *second_part); public: Item_func_unix_timestamp(THD *thd): Item_func_seconds_hybrid(thd) {} Item_func_unix_timestamp(THD *thd, Item *a): Item_func_seconds_hybrid(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("unix_timestamp") }; return name; } enum_monotonicity_info get_monotonicity_info() const override; longlong val_int_endpoint(bool left_endp, bool *incl_endp) override; bool check_partition_func_processor(void *int_arg) override {return FALSE;} /* UNIX_TIMESTAMP() depends on the current timezone (and thus may not be used as a partitioning function) when its argument is NOT of the TIMESTAMP type. */ bool check_valid_arguments_processor(void *int_arg) override { return !has_timestamp_args(); } bool check_vcol_func_processor(void *arg) override { if (arg_count) return FALSE; return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); } bool fix_length_and_dec() override { fix_length_and_dec_generic(arg_count ? args[0]->datetime_precision(current_thd) : 0); return FALSE; } longlong int_op() override; my_decimal *decimal_op(my_decimal* buf) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_time_to_sec :public Item_func_seconds_hybrid { public: Item_func_time_to_sec(THD *thd, Item *item): Item_func_seconds_hybrid(thd, item) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("time_to_sec") }; return name; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_time_args(); } bool fix_length_and_dec() override { fix_length_and_dec_generic(args[0]->time_precision(current_thd)); return FALSE; } longlong int_op() override; my_decimal *decimal_op(my_decimal* buf) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_datefunc :public Item_func { public: Item_datefunc(THD *thd): Item_func(thd) { } Item_datefunc(THD *thd, Item *a): Item_func(thd, a) { } Item_datefunc(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { } const Type_handler *type_handler() const override { return &type_handler_newdate; } longlong val_int() override { DBUG_ASSERT(!is_cond()); return Date(this).to_longlong(); } double val_real() override { return Date(this).to_double(); } String *val_str(String *to) override { return Date(this).to_string(to); } my_decimal *val_decimal(my_decimal *to) override { return Date(this).to_decimal(to); } bool fix_length_and_dec() override { fix_attributes_date(); set_maybe_null(arg_count > 0); return FALSE; } }; class Item_timefunc :public Item_func { public: Item_timefunc(THD *thd): Item_func(thd) {} Item_timefunc(THD *thd, Item *a): Item_func(thd, a) {} Item_timefunc(THD *thd, Item *a, Item *b): Item_func(thd, a, b) {} Item_timefunc(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b ,c) {} const Type_handler *type_handler() const override { return &type_handler_time2; } longlong val_int() override { DBUG_ASSERT(!is_cond()); return Time(this).to_longlong(); } double val_real() override { return Time(this).to_double(); } String *val_str(String *to) override { return Time(this).to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { return Time(this).to_decimal(to); } bool val_native(THD *thd, Native *to) override { return Time(thd, this).to_native(to, decimals); } }; class Item_datetimefunc :public Item_func { public: Item_datetimefunc(THD *thd): Item_func(thd) {} Item_datetimefunc(THD *thd, Item *a): Item_func(thd, a) {} Item_datetimefunc(THD *thd, Item *a, Item *b): Item_func(thd, a, b) {} Item_datetimefunc(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b ,c) {} const Type_handler *type_handler() const override { return &type_handler_datetime2; } longlong val_int() override { DBUG_ASSERT(!is_cond()); return Datetime(this).to_longlong(); } double val_real() override { return Datetime(this).to_double(); } String *val_str(String *to) override { return Datetime(this).to_string(to, decimals); } my_decimal *val_decimal(my_decimal *to) override { return Datetime(this).to_decimal(to); } }; /* Abstract CURTIME function. Children should define what time zone is used */ class Item_func_curtime :public Item_timefunc { MYSQL_TIME ltime; query_id_t last_query_id; public: Item_func_curtime(THD *thd, uint dec): Item_timefunc(thd), last_query_id(0) { decimals= dec; } bool fix_fields(THD *, Item **) override; bool fix_length_and_dec() override { fix_attributes_time(decimals); return FALSE; } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; /* Abstract method that defines which time zone is used for conversion. Converts time current time in my_time_t representation to broken-down MYSQL_TIME representation using UTC-SYSTEM or per-thread time zone. */ virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time)=0; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); } void print(String *str, enum_query_type query_type) override; }; class Item_func_curtime_local :public Item_func_curtime { public: Item_func_curtime_local(THD *thd, uint dec): Item_func_curtime(thd, dec) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("curtime") }; return name; } void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_curtime_utc :public Item_func_curtime { public: Item_func_curtime_utc(THD *thd, uint dec): Item_func_curtime(thd, dec) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("utc_time") }; return name; } void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Abstract CURDATE function. See also Item_func_curtime. */ class Item_func_curdate :public Item_datefunc { query_id_t last_query_id; MYSQL_TIME ltime; public: Item_func_curdate(THD *thd): Item_datefunc(thd), last_query_id(0) {} bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time)=0; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); } }; class Item_func_curdate_local :public Item_func_curdate { public: Item_func_curdate_local(THD *thd): Item_func_curdate(thd) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("curdate") }; return name; } void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_curdate_utc :public Item_func_curdate { public: Item_func_curdate_utc(THD *thd): Item_func_curdate(thd) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("utc_date") }; return name; } void store_now_in_TIME(THD* thd, MYSQL_TIME *now_time) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Abstract CURRENT_TIMESTAMP function. See also Item_func_curtime */ class Item_func_now :public Item_datetimefunc { MYSQL_TIME ltime; query_id_t last_query_id; public: Item_func_now(THD *thd, uint dec): Item_datetimefunc(thd), last_query_id(0) { decimals= dec; } bool fix_fields(THD *, Item **) override; bool fix_length_and_dec() override { fix_attributes_datetime(decimals); return FALSE;} bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; virtual void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time)=0; bool check_vcol_func_processor(void *arg) override { /* NOW is safe for replication as slaves will run with same time as master */ return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC); } void print(String *str, enum_query_type query_type) override; }; class Item_func_now_local :public Item_func_now { public: Item_func_now_local(THD *thd, uint dec): Item_func_now(thd, dec) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("current_timestamp") }; return name; } int save_in_field(Field *field, bool no_conversions) override; void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time) override; enum Functype functype() const override { return NOW_FUNC; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_now_utc :public Item_func_now { public: Item_func_now_utc(THD *thd, uint dec): Item_func_now(thd, dec) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("utc_timestamp") }; return name; } void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time) override; enum Functype functype() const override { return NOW_UTC_FUNC; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC | VCOL_NON_DETERMINISTIC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* This is like NOW(), but always uses the real current time, not the query_start(). This matches the Oracle behavior. */ class Item_func_sysdate_local :public Item_func_now { public: Item_func_sysdate_local(THD *thd, uint dec): Item_func_now(thd, dec) {} bool const_item() const override { return 0; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sysdate") }; return name; } void store_now_in_TIME(THD *thd, MYSQL_TIME *now_time) override; bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; table_map used_tables() const override { return RAND_TABLE_BIT; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_TIME_FUNC | VCOL_NON_DETERMINISTIC); } enum Functype functype() const override { return SYSDATE_FUNC; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_from_days :public Item_datefunc { bool check_arguments() const override { return args[0]->check_type_can_return_int(func_name_cstring()); } public: Item_func_from_days(THD *thd, Item *a): Item_datefunc(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("from_days") }; return name; } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return has_date_args() || has_time_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_date_format :public Item_str_func { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()) || check_argument_types_can_return_text(1, arg_count); } const MY_LOCALE *locale; int fixed_length; String value; protected: bool is_time_format; public: Item_func_date_format(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b), locale(0), is_time_format(false) {} Item_func_date_format(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c), locale(0), is_time_format(false) {} String *val_str(String *str) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("date_format") }; return name; } bool fix_length_and_dec() override; uint format_length(const String *format); bool eq(const Item *item, bool binary_cmp) const override; bool check_vcol_func_processor(void *arg) override { if (arg_count > 2) return false; return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_time_format: public Item_func_date_format { public: Item_func_time_format(THD *thd, Item *a, Item *b): Item_func_date_format(thd, a, b) { is_time_format= true; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("time_format") }; return name; } bool check_vcol_func_processor(void *arg) override { return false; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* the max length of datetime format models string in Oracle is 144 */ #define MAX_DATETIME_FORMAT_MODEL_LEN 144 class Item_func_tochar :public Item_str_func { const MY_LOCALE *locale; THD *thd; String warning_message; bool fixed_length; /* When datetime format models is parsed, use uint16 integers to represent the format models and store in fmt_array. */ uint16 fmt_array[MAX_DATETIME_FORMAT_MODEL_LEN+1]; bool check_arguments() const override { return (args[0]->check_type_can_return_date(func_name_cstring()) && args[0]->check_type_can_return_time(func_name_cstring())) || check_argument_types_can_return_text(1, arg_count); } public: Item_func_tochar(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b), locale(0) { /* NOTE: max length of warning message is 64 */ warning_message.alloc(64); warning_message.length(0); } ~Item_func_tochar() { warning_message.free(); } String *val_str(String *str) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("to_char") }; return name; } bool fix_length_and_dec() override; bool parse_format_string(const String *format, uint *fmt_len); bool check_vcol_func_processor(void *arg) override { if (arg_count > 2) return false; return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_from_unixtime :public Item_datetimefunc { bool check_arguments() const override { return args[0]->check_type_can_return_decimal(func_name_cstring()); } Time_zone *tz; public: Item_func_from_unixtime(THD *thd, Item *a): Item_datetimefunc(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("from_unixtime") }; return name; } bool fix_length_and_dec() override; bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* We need Time_zone class declaration for storing pointers in Item_func_convert_tz. */ class Time_zone; /* This class represents CONVERT_TZ() function. The important fact about this function that it is handled in special way. When such function is met in expression time_zone system tables are added to global list of tables to open, so later those already opened and locked tables can be used during this function calculation for loading time zone descriptions. */ class Item_func_convert_tz :public Item_datetimefunc { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()) || check_argument_types_can_return_text(1, arg_count); } /* If time zone parameters are constants we are caching objects that represent them (we use separate from_tz_cached/to_tz_cached members to indicate this fact, since NULL is legal value for from_tz/to_tz members. */ bool from_tz_cached, to_tz_cached; Time_zone *from_tz, *to_tz; public: Item_func_convert_tz(THD *thd, Item *a, Item *b, Item *c): Item_datetimefunc(thd, a, b, c), from_tz_cached(0), to_tz_cached(0) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("convert_tz") }; return name; } bool fix_length_and_dec() override { fix_attributes_datetime(args[0]->datetime_precision(current_thd)); set_maybe_null(); return FALSE; } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; void cleanup() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sec_to_time :public Item_timefunc { bool check_arguments() const override { return args[0]->check_type_can_return_decimal(func_name_cstring()); } public: Item_func_sec_to_time(THD *thd, Item *item): Item_timefunc(thd, item) {} bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; bool fix_length_and_dec() override { fix_attributes_time(args[0]->decimals); set_maybe_null(); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sec_to_time") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_date_add_interval :public Item_handled_func { public: const interval_type int_type; // keep it public const bool date_sub_interval; // keep it public Item_date_add_interval(THD *thd, Item *a, Item *b, interval_type type_arg, bool neg_arg): Item_handled_func(thd, a, b), int_type(type_arg), date_sub_interval(neg_arg) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("date_add_interval") }; return name; } bool fix_length_and_dec() override; bool eq(const Item *item, bool binary_cmp) const override; void print(String *str, enum_query_type query_type) override; enum precedence precedence() const override { return INTERVAL_PRECEDENCE; } bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_extract :public Item_int_func, public Type_handler_hybrid_field_type { date_mode_t m_date_mode; const Type_handler_int_result *handler_by_length(uint32 length, uint32 threashold) { if (length >= threashold) return &type_handler_slonglong; return &type_handler_slong; } void set_date_length(uint32 length) { /* DATE components (e.g. YEAR, YEAR_MONTH, QUARTER, MONTH, WEEK) return non-negative values but historically EXTRACT for date components always returned the signed int data type. So do equivalent functions YEAR(), QUARTER(), MONTH(), WEEK(). Let's set the data type to "signed int, but not negative", so "this" produces better data types in VARCHAR and DECIMAL context by using the fact that all of the max_length characters are spent for digits (non of them are spent for the sign). */ set_handler(&type_handler_slong_ge0); fix_char_length(length); m_date_mode= date_mode_t(0); } void set_day_length(uint32 length) { /* Units starting with DAY can be negative: EXTRACT(DAY FROM '-24:00:00') -> -1 */ set_handler(handler_by_length(max_length= length + 1/*sign*/, 11)); m_date_mode= Temporal::Options(TIME_INTERVAL_DAY, current_thd); } void set_time_length(uint32 length) { set_handler(handler_by_length(max_length= length + 1/*sign*/, 11)); m_date_mode= Temporal::Options(TIME_INTERVAL_hhmmssff, current_thd); } public: const interval_type int_type; // keep it public Item_extract(THD *thd, interval_type type_arg, Item *a): Item_int_func(thd, a), Type_handler_hybrid_field_type(&type_handler_slonglong), m_date_mode(date_mode_t(0)), int_type(type_arg) { } const Type_handler *type_handler() const override { return Type_handler_hybrid_field_type::type_handler(); } longlong val_int() override; enum Functype functype() const override { return EXTRACT_FUNC; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("extract") }; return name; } bool check_arguments() const override; bool fix_length_and_dec() override; bool eq(const Item *item, bool binary_cmp) const override; void print(String *str, enum_query_type query_type) override; bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { if (int_type != INTERVAL_WEEK) return FALSE; return mark_unsupported_function(func_name(), "()", arg, VCOL_SESSION_FUNC); } bool check_valid_arguments_processor(void *int_arg) override { switch (int_type) { case INTERVAL_YEAR: case INTERVAL_YEAR_MONTH: case INTERVAL_QUARTER: case INTERVAL_MONTH: /* case INTERVAL_WEEK: Not allowed as partitioning function, bug#57071 */ case INTERVAL_DAY: return !has_date_args(); case INTERVAL_DAY_HOUR: case INTERVAL_DAY_MINUTE: case INTERVAL_DAY_SECOND: case INTERVAL_DAY_MICROSECOND: return !has_datetime_args(); case INTERVAL_HOUR: case INTERVAL_HOUR_MINUTE: case INTERVAL_HOUR_SECOND: case INTERVAL_MINUTE: case INTERVAL_MINUTE_SECOND: case INTERVAL_SECOND: case INTERVAL_MICROSECOND: case INTERVAL_HOUR_MICROSECOND: case INTERVAL_MINUTE_MICROSECOND: case INTERVAL_SECOND_MICROSECOND: return !has_time_args(); default: /* INTERVAL_LAST is only an end marker, INTERVAL_WEEK depends on default_week_format which is a session variable and cannot be used for partitioning. See bug#57071. */ break; } return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_char_typecast :public Item_handled_func { uint cast_length; CHARSET_INFO *cast_cs, *from_cs; bool charset_conversion; String tmp_value; bool m_suppress_warning_to_error_escalation; public: bool has_explicit_length() const { return cast_length != ~0U; } private: String *reuse(String *src, size_t length); String *copy(String *src, CHARSET_INFO *cs); uint adjusted_length_with_warn(uint length); void check_truncation_with_warn(String *src, size_t dstlen); void fix_length_and_dec_internal(CHARSET_INFO *fromcs); public: // Methods used by ColumnStore uint get_cast_length() const { return cast_length; } public: Item_char_typecast(THD *thd, Item *a, uint length_arg, CHARSET_INFO *cs_arg): Item_handled_func(thd, a), cast_length(length_arg), cast_cs(cs_arg), m_suppress_warning_to_error_escalation(false) {} enum Functype functype() const override { return CHAR_TYPECAST_FUNC; } bool eq(const Item *item, bool binary_cmp) const override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_char") }; return name; } CHARSET_INFO *cast_charset() const { return cast_cs; } String *val_str_generic(String *a); String *val_str_binary_from_native(String *a); void fix_length_and_dec_generic(); void fix_length_and_dec_numeric(); void fix_length_and_dec_str(); void fix_length_and_dec_native_to_binary(uint32 octet_length); bool fix_length_and_dec() override { return args[0]->type_handler()->Item_char_typecast_fix_length_and_dec(this); } void print(String *str, enum_query_type query_type) override; bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_interval_DDhhmmssff_typecast :public Item_char_typecast { uint m_fsp; public: Item_interval_DDhhmmssff_typecast(THD *thd, Item *a, uint fsp) :Item_char_typecast(thd, a,Interval_DDhhmmssff::max_char_length(fsp), &my_charset_latin1), m_fsp(fsp) { } String *val_str(String *to) override { Interval_DDhhmmssff it(current_thd, args[0], m_fsp); null_value= !it.is_valid_interval_DDhhmmssff(); return it.to_string(to, m_fsp); } }; class Item_date_typecast :public Item_datefunc { public: Item_date_typecast(THD *thd, Item *a): Item_datefunc(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_date") }; return name; } void print(String *str, enum_query_type query_type) override { print_cast_temporal(str, query_type); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool fix_length_and_dec() override { return args[0]->type_handler()->Item_date_typecast_fix_length_and_dec(this); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_time_typecast :public Item_timefunc { public: Item_time_typecast(THD *thd, Item *a, uint dec_arg): Item_timefunc(thd, a) { decimals= dec_arg; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_time") }; return name; } void print(String *str, enum_query_type query_type) override { print_cast_temporal(str, query_type); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool fix_length_and_dec() override { return args[0]->type_handler()-> Item_time_typecast_fix_length_and_dec(this); } Sql_mode_dependency value_depends_on_sql_mode() const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_datetime_typecast :public Item_datetimefunc { public: Item_datetime_typecast(THD *thd, Item *a, uint dec_arg): Item_datetimefunc(thd, a) { decimals= dec_arg; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_datetime") }; return name; } void print(String *str, enum_query_type query_type) override { print_cast_temporal(str, query_type); } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; bool fix_length_and_dec() override { return args[0]->type_handler()-> Item_datetime_typecast_fix_length_and_dec(this); } Sql_mode_dependency value_depends_on_sql_mode() const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_makedate :public Item_datefunc { bool check_arguments() const override { return check_argument_types_can_return_int(0, arg_count); } public: Item_func_makedate(THD *thd, Item *a, Item *b): Item_datefunc(thd, a, b) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("makedate") }; return name; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_timestamp :public Item_datetimefunc { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()) || args[1]->check_type_can_return_time(func_name_cstring()); } public: Item_func_timestamp(THD *thd, Item *a, Item *b) :Item_datetimefunc(thd, a, b) { } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("timestamp") }; return name; } bool fix_length_and_dec() override { THD *thd= current_thd; uint dec0= args[0]->datetime_precision(thd); uint dec1= Interval_DDhhmmssff::fsp(thd, args[1]); fix_attributes_datetime(MY_MAX(dec0, dec1)); set_maybe_null(); return false; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { Datetime dt(thd, args[0], Datetime::Options(TIME_CONV_NONE, thd)); if (!dt.is_valid_datetime()) return (null_value= 1); Interval_DDhhmmssff it(thd, args[1]); if (!it.is_valid_interval_DDhhmmssff()) return (null_value= true); return (null_value= Sec6_add(dt.get_mysql_time(), it.get_mysql_time(), 1). to_datetime(ltime)); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** ADDTIME(t,a) and SUBTIME(t,a) are time functions that calculate a time/datetime value t: time_or_datetime_expression a: time_expression Result: Time value or datetime value */ class Item_func_add_time :public Item_handled_func { int sign; public: // Methods used by ColumnStore int get_sign() const { return sign; } public: Item_func_add_time(THD *thd, Item *a, Item *b, bool neg_arg) :Item_handled_func(thd, a, b), sign(neg_arg ? -1 : 1) { } bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING addtime= { STRING_WITH_LEN("addtime") }; static LEX_CSTRING subtime= { STRING_WITH_LEN("subtime") }; return sign > 0 ? addtime : subtime; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_timediff :public Item_timefunc { bool check_arguments() const override { return check_argument_types_can_return_time(0, arg_count); } public: Item_func_timediff(THD *thd, Item *a, Item *b): Item_timefunc(thd, a, b) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("timediff") }; return name; } bool fix_length_and_dec() override { THD *thd= current_thd; uint dec= MY_MAX(args[0]->time_precision(thd), args[1]->time_precision(thd)); fix_attributes_time(dec); set_maybe_null(); return FALSE; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_maketime :public Item_timefunc { bool check_arguments() const override { return check_argument_types_can_return_int(0, 2) || args[2]->check_type_can_return_decimal(func_name_cstring()); } public: Item_func_maketime(THD *thd, Item *a, Item *b, Item *c): Item_timefunc(thd, a, b, c) {} bool fix_length_and_dec() override { fix_attributes_time(args[2]->decimals); set_maybe_null(); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("maketime") }; return name; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_microsecond :public Item_long_func_time_field { public: Item_func_microsecond(THD *thd, Item *a): Item_long_func_time_field(thd, a) {} longlong val_int() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("microsecond") }; return name; } bool fix_length_and_dec() override { decimals=0; set_maybe_null(); fix_char_length(6); return FALSE; } bool check_partition_func_processor(void *int_arg) override {return FALSE;} bool check_vcol_func_processor(void *arg) override { return FALSE;} bool check_valid_arguments_processor(void *int_arg) override { return !has_time_args(); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_timestamp_diff :public Item_longlong_func { bool check_arguments() const override { return check_argument_types_can_return_date(0, arg_count); } const interval_type int_type; public: // Methods used by ColumnStore interval_type get_int_type() const { return int_type; }; public: Item_func_timestamp_diff(THD *thd, Item *a, Item *b, interval_type type_arg): Item_longlong_func(thd, a, b), int_type(type_arg) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("timestampdiff") }; return name; } longlong val_int() override; bool fix_length_and_dec() override { decimals=0; set_maybe_null(); return FALSE; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; enum date_time_format { USA_FORMAT, JIS_FORMAT, ISO_FORMAT, EUR_FORMAT, INTERNAL_FORMAT }; class Item_func_get_format :public Item_str_ascii_func { public: const timestamp_type type; // keep it public Item_func_get_format(THD *thd, timestamp_type type_arg, Item *a): Item_str_ascii_func(thd, a), type(type_arg) {} String *val_str_ascii(String *str) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("get_format") }; return name; } bool fix_length_and_dec() override { set_maybe_null(); decimals=0; fix_length_and_charset(17, default_charset()); return FALSE; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_str_to_date :public Item_handled_func { bool const_item; String subject_converter; String format_converter; CHARSET_INFO *internal_charset; public: Item_func_str_to_date(THD *thd, Item *a, Item *b): Item_handled_func(thd, a, b), const_item(false), internal_charset(NULL) {} bool get_date_common(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate, timestamp_type); LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("str_to_date") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_last_day :public Item_datefunc { bool check_arguments() const override { return args[0]->check_type_can_return_date(func_name_cstring()); } public: Item_func_last_day(THD *thd, Item *a): Item_datefunc(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("last_day") }; return name; } bool get_date(THD *thd, MYSQL_TIME *res, date_mode_t fuzzydate) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /*****************************************************************************/ class Func_handler_date_add_interval { protected: static uint interval_dec(const Item *item, interval_type int_type) { if (int_type == INTERVAL_MICROSECOND || (int_type >= INTERVAL_DAY_MICROSECOND && int_type <= INTERVAL_SECOND_MICROSECOND)) return TIME_SECOND_PART_DIGITS; if (int_type == INTERVAL_SECOND && item->decimals > 0) return MY_MIN(item->decimals, TIME_SECOND_PART_DIGITS); return 0; } interval_type int_type(const Item_handled_func *item) const { return static_cast(item)->int_type; } bool sub(const Item_handled_func *item) const { return static_cast(item)->date_sub_interval; } bool add(THD *thd, Item *item, interval_type type, bool sub, MYSQL_TIME *to) const { INTERVAL interval; if (get_interval_value(thd, item, type, &interval)) return true; if (sub) interval.neg = !interval.neg; return date_add_interval(thd, to, type, interval); } }; class Func_handler_date_add_interval_datetime: public Item_handled_func::Handler_datetime, public Func_handler_date_add_interval { public: bool fix_length_and_dec(Item_handled_func *item) const override { uint dec= MY_MAX(item->arguments()[0]->datetime_precision(current_thd), interval_dec(item->arguments()[1], int_type(item))); item->fix_attributes_datetime(dec); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { Datetime::Options opt(TIME_CONV_NONE, thd); Datetime dt(thd, item->arguments()[0], opt); if (!dt.is_valid_datetime() || dt.check_date_with_warn(thd, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE)) return (item->null_value= true); dt.copy_to_mysql_time(to); return (item->null_value= add(thd, item->arguments()[1], int_type(item), sub(item), to)); } }; class Func_handler_date_add_interval_datetime_arg0_time: public Func_handler_date_add_interval_datetime { public: bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override; }; class Func_handler_date_add_interval_date: public Item_handled_func::Handler_date, public Func_handler_date_add_interval { public: bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { /* The first argument is known to be of the DATE data type (not DATETIME). We don't need rounding here. */ Date d(thd, item->arguments()[0], TIME_CONV_NONE); if (!d.is_valid_date() || d.check_date_with_warn(thd, TIME_NO_ZERO_DATE | TIME_NO_ZERO_IN_DATE)) return (item->null_value= true); d.copy_to_mysql_time(to); return (item->null_value= add(thd, item->arguments()[1], int_type(item), sub(item), to)); } }; class Func_handler_date_add_interval_time: public Item_handled_func::Handler_time, public Func_handler_date_add_interval { public: bool fix_length_and_dec(Item_handled_func *item) const override { uint dec= MY_MAX(item->arguments()[0]->time_precision(current_thd), interval_dec(item->arguments()[1], int_type(item))); item->fix_attributes_time(dec); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { Time t(thd, item->arguments()[0]); if (!t.is_valid_time()) return (item->null_value= true); t.copy_to_mysql_time(to); return (item->null_value= add(thd, item->arguments()[1], int_type(item), sub(item), to)); } }; class Func_handler_date_add_interval_string: public Item_handled_func::Handler_temporal_string, public Func_handler_date_add_interval { public: bool fix_length_and_dec(Item_handled_func *item) const override { uint dec= MY_MAX(item->arguments()[0]->datetime_precision(current_thd), interval_dec(item->arguments()[1], int_type(item))); item->Type_std_attributes::set( Type_temporal_attributes_not_fixed_dec(MAX_DATETIME_WIDTH, dec, false), DTCollation(item->default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII)); item->fix_char_length(item->max_length); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { if (item->arguments()[0]-> get_date(thd, to, Datetime::Options(TIME_CONV_NONE, thd)) || (to->time_type != MYSQL_TIMESTAMP_TIME && check_date_with_warn(thd, to, TIME_NO_ZEROS, MYSQL_TIMESTAMP_ERROR))) return (item->null_value= true); return (item->null_value= add(thd, item->arguments()[1], int_type(item), sub(item), to)); } }; class Func_handler_sign { protected: int m_sign; Func_handler_sign(int sign) :m_sign(sign) { } }; class Func_handler_add_time_datetime: public Item_handled_func::Handler_datetime, public Func_handler_sign { public: Func_handler_add_time_datetime(int sign) :Func_handler_sign(sign) { } bool fix_length_and_dec(Item_handled_func *item) const override { THD *thd= current_thd; uint dec0= item->arguments()[0]->datetime_precision(thd); uint dec1= Interval_DDhhmmssff::fsp(thd, item->arguments()[1]); item->fix_attributes_datetime(MY_MAX(dec0, dec1)); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { DBUG_ASSERT(item->fixed()); Datetime::Options opt(TIME_CONV_NONE, thd); Datetime dt(thd, item->arguments()[0], opt); if (!dt.is_valid_datetime()) return (item->null_value= true); Interval_DDhhmmssff it(thd, item->arguments()[1]); if (!it.is_valid_interval_DDhhmmssff()) return (item->null_value= true); return (item->null_value= (Sec6_add(dt.get_mysql_time(), it.get_mysql_time(), m_sign). to_datetime(to))); } }; class Func_handler_add_time_time: public Item_handled_func::Handler_time, public Func_handler_sign { public: Func_handler_add_time_time(int sign) :Func_handler_sign(sign) { } bool fix_length_and_dec(Item_handled_func *item) const override { THD *thd= current_thd; uint dec0= item->arguments()[0]->time_precision(thd); uint dec1= Interval_DDhhmmssff::fsp(thd, item->arguments()[1]); item->fix_attributes_time(MY_MAX(dec0, dec1)); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { DBUG_ASSERT(item->fixed()); Time t(thd, item->arguments()[0]); if (!t.is_valid_time()) return (item->null_value= true); Interval_DDhhmmssff i(thd, item->arguments()[1]); if (!i.is_valid_interval_DDhhmmssff()) return (item->null_value= true); return (item->null_value= (Sec6_add(t.get_mysql_time(), i.get_mysql_time(), m_sign). to_time(thd, to, item->decimals))); } }; class Func_handler_add_time_string: public Item_handled_func::Handler_temporal_string, public Func_handler_sign { public: Func_handler_add_time_string(int sign) :Func_handler_sign(sign) { } bool fix_length_and_dec(Item_handled_func *item) const override { uint dec0= item->arguments()[0]->decimals; uint dec1= Interval_DDhhmmssff::fsp(current_thd, item->arguments()[1]); uint dec= MY_MAX(dec0, dec1); item->Type_std_attributes::set( Type_temporal_attributes_not_fixed_dec(MAX_DATETIME_WIDTH, dec, false), DTCollation(item->default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII)); item->fix_char_length(item->max_length); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { DBUG_ASSERT(item->fixed()); // Detect a proper timestamp type based on the argument values Temporal_hybrid l_time1(thd, item->arguments()[0], Temporal::Options(TIME_TIME_ONLY, thd)); if (!l_time1.is_valid_temporal()) return (item->null_value= true); Interval_DDhhmmssff l_time2(thd, item->arguments()[1]); if (!l_time2.is_valid_interval_DDhhmmssff()) return (item->null_value= true); Sec6_add add(l_time1.get_mysql_time(), l_time2.get_mysql_time(), m_sign); return (item->null_value= (l_time1.get_mysql_time()->time_type == MYSQL_TIMESTAMP_TIME ? add.to_time(thd, to, item->decimals) : add.to_datetime(to))); } }; class Func_handler_str_to_date_datetime_sec: public Item_handled_func::Handler_datetime { public: bool fix_length_and_dec(Item_handled_func *item) const override { item->fix_attributes_datetime(0); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { return static_cast(item)-> get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_DATETIME); } }; class Func_handler_str_to_date_datetime_usec: public Item_handled_func::Handler_datetime { public: bool fix_length_and_dec(Item_handled_func *item) const override { item->fix_attributes_datetime(TIME_SECOND_PART_DIGITS); return false; } bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { return static_cast(item)-> get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_DATETIME); } }; class Func_handler_str_to_date_date: public Item_handled_func::Handler_date { public: bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { return static_cast(item)-> get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_DATE); } }; class Func_handler_str_to_date_time: public Item_handled_func::Handler_time { public: bool get_date(THD *thd, Item_handled_func *item, MYSQL_TIME *to, date_mode_t fuzzy) const override { if (static_cast(item)-> get_date_common(thd, to, fuzzy, MYSQL_TIMESTAMP_TIME)) return true; if (to->day) { /* Day part for time type can be nonzero value and so we should add hours from day part to hour part to keep valid time value. */ to->hour+= to->day * 24; to->day= 0; } return false; } }; class Func_handler_str_to_date_time_sec: public Func_handler_str_to_date_time { public: bool fix_length_and_dec(Item_handled_func *item) const override { item->fix_attributes_time(0); return false; } }; class Func_handler_str_to_date_time_usec: public Func_handler_str_to_date_time { public: bool fix_length_and_dec(Item_handled_func *item) const override { item->fix_attributes_time(TIME_SECOND_PART_DIGITS); return false; } }; #endif /* ITEM_TIMEFUNC_INCLUDED */ mysql/server/private/sql_limit.h000064400000006163151027430560013050 0ustar00/* Copyright (c) 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef INCLUDES_MARIADB_SQL_LIMIT_H #define INCLUDES_MARIADB_SQL_LIMIT_H /** LIMIT/OFFSET parameters for execution. */ class Select_limit_counters { ha_rows select_limit_cnt, offset_limit_cnt; bool with_ties; public: Select_limit_counters(): select_limit_cnt(0), offset_limit_cnt(0), with_ties(false) {}; Select_limit_counters(const Select_limit_counters &orig): select_limit_cnt(orig.select_limit_cnt), offset_limit_cnt(orig.offset_limit_cnt), with_ties(orig.with_ties) {}; void set_limit(ha_rows limit, ha_rows offset, bool with_ties_arg) { if (limit == 0) offset= 0; offset_limit_cnt= offset; select_limit_cnt= limit; with_ties= with_ties_arg; /* Guard against an overflow condition, where limit + offset exceede ha_rows value range. This case covers unreasonably large parameter values that do not have any practical use so assuming in this case that the query does not have a limit is fine. */ if (select_limit_cnt + offset_limit_cnt >= select_limit_cnt) select_limit_cnt+= offset_limit_cnt; else select_limit_cnt= HA_POS_ERROR; } void set_single_row() { offset_limit_cnt= 0; select_limit_cnt= 1; with_ties= false; } /* Send the first row, still honoring offset_limit_cnt */ void send_first_row() { /* Guard against overflow */ if ((select_limit_cnt= offset_limit_cnt +1 ) == 0) select_limit_cnt= offset_limit_cnt; // with_ties= false; Remove // on merge to 10.6 } bool is_unlimited() const { return select_limit_cnt == HA_POS_ERROR; } /* Set the limit to allow returning an unlimited number of rows. Useful for cases when we want to continue execution indefinitely after the limit is reached (for example for SQL_CALC_ROWS extension). */ void set_unlimited() { select_limit_cnt= HA_POS_ERROR; } /* Reset the limit entirely. */ void clear() { select_limit_cnt= HA_POS_ERROR; offset_limit_cnt= 0; with_ties= false;} bool check_offset(ha_rows sent) const { return sent < offset_limit_cnt; } void remove_offset() { offset_limit_cnt= 0; } ha_rows get_select_limit() const { return select_limit_cnt; } ha_rows get_offset_limit() const { return offset_limit_cnt; } bool is_with_ties() const { return with_ties; } }; #endif // INCLUDES_MARIADB_SQL_LIMIT_H mysql/server/private/spatial.h000064400000053441151027430560012511 0ustar00/* Copyright (c) 2002, 2013, Oracle and/or its affiliates. Copyright (c) 2009, 2013, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _spatial_h #define _spatial_h #include "sql_string.h" /* String, LEX_STRING */ #include #include #ifdef HAVE_SPATIAL class Gis_read_stream; #include "gcalc_tools.h" const uint SRID_SIZE= 4; const uint SIZEOF_STORED_DOUBLE= 8; const uint POINT_DATA_SIZE= (SIZEOF_STORED_DOUBLE * 2); const uint WKB_HEADER_SIZE= 1+4; const uint32 GET_SIZE_ERROR= ((uint32) -1); struct st_point_2d { double x; double y; }; struct st_linear_ring { uint32 n_points; st_point_2d points; }; /***************************** MBR *******************************/ /* It's ok that a lot of the functions are inline as these are only used once in MySQL */ struct MBR { double xmin, ymin, xmax, ymax; MBR() { xmin= ymin= DBL_MAX; xmax= ymax= -DBL_MAX; } MBR(const double xmin_arg, const double ymin_arg, const double xmax_arg, const double ymax_arg) :xmin(xmin_arg), ymin(ymin_arg), xmax(xmax_arg), ymax(ymax_arg) {} MBR(const st_point_2d &min, const st_point_2d &max) :xmin(min.x), ymin(min.y), xmax(max.x), ymax(max.y) {} MBR(const MBR &mbr1, const MBR &mbr2) :xmin(mbr1.xmin), ymin(mbr1.ymin), xmax(mbr1.xmax), ymax(mbr1.ymax) { add_mbr(&mbr2); } inline void add_xy(double x, double y) { /* Not using "else" for proper one point MBR calculation */ if (x < xmin) xmin= x; if (x > xmax) xmax= x; if (y < ymin) ymin= y; if (y > ymax) ymax= y; } void add_xy(const char *px, const char *py) { double x, y; float8get(x, px); float8get(y, py); add_xy(x,y); } void add_mbr(const MBR *mbr) { if (mbr->xmin < xmin) xmin= mbr->xmin; if (mbr->xmax > xmax) xmax= mbr->xmax; if (mbr->ymin < ymin) ymin= mbr->ymin; if (mbr->ymax > ymax) ymax= mbr->ymax; } void buffer(double d) { xmin-= d; ymin-= d; xmax+= d; ymax+= d; } int equals(const MBR *mbr) { /* The following should be safe, even if we compare doubles */ return ((mbr->xmin == xmin) && (mbr->ymin == ymin) && (mbr->xmax == xmax) && (mbr->ymax == ymax)); } int disjoint(const MBR *mbr) { /* The following should be safe, even if we compare doubles */ return ((mbr->xmin > xmax) || (mbr->ymin > ymax) || (mbr->xmax < xmin) || (mbr->ymax < ymin)); } int intersects(const MBR *mbr) { return !disjoint(mbr); } int touches(const MBR *mbr) { /* The following should be safe, even if we compare doubles */ return ((mbr->xmin == xmax || mbr->xmax == xmin) && ((mbr->ymin >= ymin && mbr->ymin <= ymax) || (mbr->ymax >= ymin && mbr->ymax <= ymax))) || ((mbr->ymin == ymax || mbr->ymax == ymin) && ((mbr->xmin >= xmin && mbr->xmin <= xmax) || (mbr->xmax >= xmin && mbr->xmax <= xmax))); } int within(const MBR *mbr); int contains(const MBR *mbr) { /* The following should be safe, even if we compare doubles */ return ((mbr->xmin >= xmin) && (mbr->ymin >= ymin) && (mbr->xmax <= xmax) && (mbr->ymax <= ymax)); } bool inner_point(double x, double y) const { /* The following should be safe, even if we compare doubles */ return (xminx) && (yminy); } /** The dimension maps to an integer as: - Polygon -> 2 - Horizontal or vertical line -> 1 - Point -> 0 - Invalid MBR -> -1 */ int dimension() const { int d= 0; if (xmin > xmax) return -1; else if (xmin < xmax) d++; if (ymin > ymax) return -1; else if (ymin < ymax) d++; return d; } int overlaps(const MBR *mbr) { /* overlaps() requires that some point inside *this is also inside *mbr, and that both geometries and their intersection are of the same dimension. */ int d = dimension(); if (d != mbr->dimension() || d <= 0 || contains(mbr) || within(mbr)) return 0; MBR intersection(MY_MAX(xmin, mbr->xmin), MY_MAX(ymin, mbr->ymin), MY_MIN(xmax, mbr->xmax), MY_MIN(ymax, mbr->ymax)); return (d == intersection.dimension()); } int valid() const { return xmin <= xmax && ymin <= ymax; } }; /***************************** Geometry *******************************/ struct Geometry_buffer; class Geometry { public: Geometry() = default; /* Remove gcc warning */ virtual ~Geometry() = default; /* Remove gcc warning */ static void *operator new(size_t size, void *buffer) { return buffer; } static void operator delete(void *ptr, void *buffer) {} static void operator delete(void *buffer) {} enum wkbType { wkb_point= 1, wkb_linestring= 2, wkb_polygon= 3, wkb_multipoint= 4, wkb_multilinestring= 5, wkb_multipolygon= 6, wkb_geometrycollection= 7, wkb_last=7 }; enum wkbByteOrder { wkb_xdr= 0, /* Big Endian */ wkb_ndr= 1 /* Little Endian */ }; enum geojson_errors { GEOJ_INCORRECT_GEOJSON= 1, GEOJ_TOO_FEW_POINTS= 2, GEOJ_POLYGON_NOT_CLOSED= 3, GEOJ_DIMENSION_NOT_SUPPORTED= 4, GEOJ_EMPTY_COORDINATES= 5, }; /** Callback which creates Geometry objects on top of a given placement. */ typedef Geometry *(*create_geom_t)(char *); class Class_info { public: LEX_STRING m_name; LEX_STRING m_geojson_name; int m_type_id; create_geom_t m_create_func; Class_info(const char *name, const char *gejson_name, int type_id, create_geom_t create_func); }; virtual const Class_info *get_class_info() const=0; virtual uint32 get_data_size() const=0; virtual bool init_from_wkt(Gis_read_stream *trs, String *wkb)=0; /* returns the length of the wkb that was read */ virtual uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res)=0; virtual uint init_from_opresult(String *bin, const char *opres, uint res_len) { return init_from_wkb(opres + 4, UINT_MAX32, wkb_ndr, bin) + 4; } virtual bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) { return true; } virtual bool get_data_as_wkt(String *txt, const char **end) const=0; virtual bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const=0; virtual bool get_mbr(MBR *mbr, const char **end) const=0; virtual bool dimension(uint32 *dim, const char **end) const=0; virtual int get_x(double *x) const { return -1; } virtual int get_y(double *y) const { return -1; } virtual int geom_length(double *len, const char **end) const { return -1; } virtual int area(double *ar, const char **end) const { return -1;} virtual int is_closed(int *closed) const { return -1; } virtual int num_interior_ring(uint32 *n_int_rings) const { return -1; } virtual int num_points(uint32 *n_points) const { return -1; } virtual int num_geometries(uint32 *num) const { return -1; } virtual int start_point(String *point) const { return -1; } virtual int end_point(String *point) const { return -1; } virtual int exterior_ring(String *ring) const { return -1; } virtual int centroid(String *point) const { return -1; } virtual int point_n(uint32 num, String *result) const { return -1; } virtual int interior_ring_n(uint32 num, String *result) const { return -1; } virtual int geometry_n(uint32 num, String *result) const { return -1; } virtual int store_shapes(Gcalc_shape_transporter *trn) const=0; public: static Geometry *create_by_typeid(Geometry_buffer *buffer, int type_id); static Geometry *construct(Geometry_buffer *buffer, const char *data, uint32 data_len); static Geometry *create_from_wkt(Geometry_buffer *buffer, Gis_read_stream *trs, String *wkt, bool init_stream=1); static Geometry *create_from_wkb(Geometry_buffer *buffer, const char *wkb, uint32 len, String *res); static Geometry *create_from_json(Geometry_buffer *buffer, json_engine_t *je, bool er_on_3D, String *res); static Geometry *create_from_opresult(Geometry_buffer *g_buf, String *res, Gcalc_result_receiver &rr); static uint get_key_image_itMBR(LEX_CSTRING &src, uchar *buff, uint length); int as_wkt(String *wkt, const char **end); int as_json(String *wkt, uint max_dec_digits, const char **end); int bbox_as_json(String *wkt); inline void set_data_ptr(const char *data, uint32 data_len) { m_data= data; m_data_end= data + data_len; } inline void shift_wkb_header() { m_data+= WKB_HEADER_SIZE; } const char *get_data_ptr() const { return m_data; } bool envelope(String *result) const; static Class_info *ci_collection[wkb_last+1]; static bool create_point(String *result, double x, double y); protected: static Class_info *find_class(int type_id) { return ((type_id < wkb_point) || (type_id > wkb_last)) ? NULL : ci_collection[type_id]; } static Class_info *find_class(const char *name, size_t len); const char *append_points(String *txt, uint32 n_points, const char *data, uint32 offset) const; bool create_point(String *result, const char *data) const; const char *get_mbr_for_points(MBR *mbr, const char *data, uint offset) const; public: /** Check if there're enough data remaining as requested @arg cur_data pointer to the position in the binary form @arg data_amount number of points expected @return true if not enough data */ inline bool no_data(const char *cur_data, size_t data_amount) const { return (cur_data + data_amount > m_data_end); } /** Check if there're enough points remaining as requested Need to perform the calculation in logical units, since multiplication can overflow the size data type. @arg data pointer to the beginning of the points array @arg expected_points number of points expected @arg extra_point_space extra space for each point element in the array @return true if there are not enough points */ inline bool not_enough_points(const char *data, uint32 expected_points, uint32 extra_point_space = 0) const { return (m_data_end < data || (expected_points > ((m_data_end - data) / (POINT_DATA_SIZE + extra_point_space)))); } protected: const char *m_data; const char *m_data_end; }; /***************************** Point *******************************/ class Gis_point: public Geometry { public: Gis_point() = default; /* Remove gcc warning */ virtual ~Gis_point() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int get_xy(double *x, double *y) const { const char *data= m_data; if (no_data(data, SIZEOF_STORED_DOUBLE * 2)) return 1; float8get(*x, data); float8get(*y, data + SIZEOF_STORED_DOUBLE); return 0; } int get_xy_radian(double *x, double *y) const { if (!get_xy(x, y)) { *x= (*x)*M_PI/180; *y= (*y)*M_PI/180; return 0; } return 1; } int get_x(double *x) const override { if (no_data(m_data, SIZEOF_STORED_DOUBLE)) return 1; float8get(*x, m_data); return 0; } int get_y(double *y) const override { const char *data= m_data; if (no_data(data, SIZEOF_STORED_DOUBLE * 2)) return 1; float8get(*y, data + SIZEOF_STORED_DOUBLE); return 0; } int geom_length(double *len, const char **end) const override; int area(double *ar, const char **end) const override; bool dimension(uint32 *dim, const char **end) const override { *dim= 0; *end= 0; /* No default end */ return 0; } int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; double calculate_haversine(const Geometry *g, const double sphere_radius, int *error); int spherical_distance_multipoints(Geometry *g, const double r, double *result, int *error); }; /***************************** LineString *******************************/ class Gis_line_string: public Geometry { public: Gis_line_string() = default; /* Remove gcc warning */ virtual ~Gis_line_string() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int geom_length(double *len, const char **end) const override; int area(double *ar, const char **end) const override; int is_closed(int *closed) const override; int num_points(uint32 *n_points) const override; int start_point(String *point) const override; int end_point(String *point) const override; int point_n(uint32 n, String *result) const override; bool dimension(uint32 *dim, const char **end) const override { *dim= 1; *end= 0; /* No default end */ return 0; } int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; }; /***************************** Polygon *******************************/ class Gis_polygon: public Geometry { public: Gis_polygon() = default; /* Remove gcc warning */ virtual ~Gis_polygon() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; uint init_from_opresult(String *bin, const char *opres, uint res_len) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int area(double *ar, const char **end) const override; int exterior_ring(String *result) const override; int num_interior_ring(uint32 *n_int_rings) const override; int interior_ring_n(uint32 num, String *result) const override; int centroid_xy(double *x, double *y) const; int centroid(String *result) const override; bool dimension(uint32 *dim, const char **end) const override { *dim= 2; *end= 0; /* No default end */ return 0; } int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; }; /***************************** MultiPoint *******************************/ class Gis_multi_point: public Geometry { // Maximum number of points in MultiPoint that can fit into String static const uint32 max_n_points= (uint32) (UINT_MAX32 - WKB_HEADER_SIZE - 4 /* n_points */) / (WKB_HEADER_SIZE + POINT_DATA_SIZE); public: Gis_multi_point() = default; /* Remove gcc warning */ virtual ~Gis_multi_point() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; uint init_from_opresult(String *bin, const char *opres, uint res_len) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int num_geometries(uint32 *num) const override; int geometry_n(uint32 num, String *result) const override; bool dimension(uint32 *dim, const char **end) const override { *dim= 0; *end= 0; /* No default end */ return 0; } int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; int spherical_distance_multipoints(Geometry *g, const double r, double *res, int *error); }; /***************************** MultiLineString *******************************/ class Gis_multi_line_string: public Geometry { public: Gis_multi_line_string() = default; /* Remove gcc warning */ virtual ~Gis_multi_line_string() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; uint init_from_opresult(String *bin, const char *opres, uint res_len) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int num_geometries(uint32 *num) const override; int geometry_n(uint32 num, String *result) const override; int geom_length(double *len, const char **end) const override; int is_closed(int *closed) const override; bool dimension(uint32 *dim, const char **end) const override { *dim= 1; *end= 0; /* No default end */ return 0; } int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; }; /***************************** MultiPolygon *******************************/ class Gis_multi_polygon: public Geometry { public: Gis_multi_polygon() = default; /* Remove gcc warning */ virtual ~Gis_multi_polygon() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int num_geometries(uint32 *num) const override; int geometry_n(uint32 num, String *result) const override; int area(double *ar, const char **end) const override; int centroid(String *result) const override; bool dimension(uint32 *dim, const char **end) const override { *dim= 2; *end= 0; /* No default end */ return 0; } int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; uint init_from_opresult(String *bin, const char *opres, uint res_len) override; }; /*********************** GeometryCollection *******************************/ class Gis_geometry_collection: public Geometry { public: Gis_geometry_collection() = default; /* Remove gcc warning */ virtual ~Gis_geometry_collection() = default; /* Remove gcc warning */ uint32 get_data_size() const override; bool init_from_wkt(Gis_read_stream *trs, String *wkb) override; uint init_from_wkb(const char *wkb, uint len, wkbByteOrder bo, String *res) override; uint init_from_opresult(String *bin, const char *opres, uint res_len) override; bool init_from_json(json_engine_t *je, bool er_on_3D, String *wkb) override; bool get_data_as_wkt(String *txt, const char **end) const override; bool get_data_as_json(String *txt, uint max_dec_digits, const char **end) const override; bool get_mbr(MBR *mbr, const char **end) const override; int area(double *ar, const char **end) const override; int geom_length(double *len, const char **end) const override; int num_geometries(uint32 *num) const override; int geometry_n(uint32 num, String *result) const override; bool dimension(uint32 *dim, const char **end) const override; int store_shapes(Gcalc_shape_transporter *trn) const override; const Class_info *get_class_info() const override; }; struct Geometry_buffer : public my_aligned_storage {}; #endif /*HAVE_SPATIAL*/ #endif mysql/server/private/sql_debug.h000064400000013016151027430560013013 0ustar00#ifndef SQL_DEBUG_INCLUDED #define SQL_DEBUG_INCLUDED /* Copyright (c) 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ class Debug_key: public String { public: Debug_key() = default; void print(THD *thd) const { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_UNKNOWN_ERROR, "DBUG: %.*s", length(), ptr()); } bool append_key_type(ha_base_keytype type) { static LEX_CSTRING names[20]= { {STRING_WITH_LEN("END")}, {STRING_WITH_LEN("TEXT")}, {STRING_WITH_LEN("BINARY")}, {STRING_WITH_LEN("SHORT_INT")}, {STRING_WITH_LEN("LONG_INT")}, {STRING_WITH_LEN("FLOAT")}, {STRING_WITH_LEN("DOUBLE")}, {STRING_WITH_LEN("NUM")}, {STRING_WITH_LEN("USHORT_INT")}, {STRING_WITH_LEN("ULONG_INT")}, {STRING_WITH_LEN("LONGLONG")}, {STRING_WITH_LEN("ULONGLONG")}, {STRING_WITH_LEN("INT24")}, {STRING_WITH_LEN("UINT24")}, {STRING_WITH_LEN("INT8")}, {STRING_WITH_LEN("VARTEXT1")}, {STRING_WITH_LEN("VARBINARY1")}, {STRING_WITH_LEN("VARTEXT2")}, {STRING_WITH_LEN("VARBINARY2")}, {STRING_WITH_LEN("BIT")} }; if ((uint) type >= array_elements(names)) return append(STRING_WITH_LEN("???")); return append(names[(uint) type]); } bool append_KEY_flag_names(ulong flags) { static LEX_CSTRING names[17]= { {STRING_WITH_LEN("HA_NOSAME")}, // 1 {STRING_WITH_LEN("HA_PACK_KEY")}, // 2; also in HA_KEYSEG {STRING_WITH_LEN("HA_SPACE_PACK_USED")}, // 4 {STRING_WITH_LEN("HA_VAR_LENGTH_KEY")}, // 8 {STRING_WITH_LEN("HA_AUTO_KEY")}, // 16 {STRING_WITH_LEN("HA_BINARY_PACK_KEY")}, // 32 {STRING_WITH_LEN("HA_NULL_PART_KEY")}, // 64 {STRING_WITH_LEN("HA_FULLTEXT")}, // 128 {STRING_WITH_LEN("HA_UNIQUE_CHECK")}, // 256 {STRING_WITH_LEN("HA_SORT_ALLOWS_SAME")}, // 512 {STRING_WITH_LEN("HA_SPATIAL")}, // 1024 {STRING_WITH_LEN("HA_NULL_ARE_EQUAL")}, // 2048 {STRING_WITH_LEN("HA_USES_COMMENT")}, // 4096 {STRING_WITH_LEN("HA_GENERATED_KEY")}, // 8192 {STRING_WITH_LEN("HA_USES_PARSER")}, // 16384 {STRING_WITH_LEN("HA_USES_BLOCK_SIZE")}, // 32768 {STRING_WITH_LEN("HA_KEY_HAS_PART_KEY_SEG")}// 65536 }; return append_flag32_names((uint) flags, names, array_elements(names)); } bool append_HA_KEYSEG_flag_names(uint32 flags) { static LEX_CSTRING names[]= { {STRING_WITH_LEN("HA_SPACE_PACK")}, // 1 {STRING_WITH_LEN("HA_PACK_KEY")}, // 2; also in KEY/MI/KEY_DEF {STRING_WITH_LEN("HA_PART_KEY_SEG")}, // 4 {STRING_WITH_LEN("HA_VAR_LENGTH_PART")}, // 8 {STRING_WITH_LEN("HA_NULL_PART")}, // 16 {STRING_WITH_LEN("HA_BLOB_PART")}, // 32 {STRING_WITH_LEN("HA_SWAP_KEY")}, // 64 {STRING_WITH_LEN("HA_REVERSE_SORT")}, // 128 {STRING_WITH_LEN("HA_NO_SORT")}, // 256 {STRING_WITH_LEN("??? 512 ???")}, // 512 {STRING_WITH_LEN("HA_BIT_PART")}, // 1024 {STRING_WITH_LEN("HA_CAN_MEMCMP")} // 2048 }; return append_flag32_names(flags, names, array_elements(names)); } bool append_HA_KEYSEG_type(ha_base_keytype type) { return append_ulonglong(type) || append(' ') || append_key_type(type); } bool append_HA_KEYSEG_flags(uint32 flags) { return append_hex_uint32(flags) || append(' ') || append_HA_KEYSEG_flag_names(flags); } bool append_key(const LEX_CSTRING &name, uint32 flags) { return append_name_value(Lex_cstring(STRING_WITH_LEN("name")), name, '`') || append(Lex_cstring(STRING_WITH_LEN(" flags="))) || append_hex_uint32(flags) || append(' ') || append_KEY_flag_names(flags); } bool append_KEY(const KEY &key) { return append_key(key.name, key.flags); } static void print_keysegs(THD *thd, const HA_KEYSEG *seg, uint count) { for (uint i= 0; i < count; i++) { Debug_key tmp; if (!tmp.append(Lex_cstring(STRING_WITH_LEN(" seg["))) && !tmp.append_ulonglong(i) && !tmp.append(Lex_cstring(STRING_WITH_LEN("].type="))) && !tmp.append_HA_KEYSEG_type((ha_base_keytype) seg[i].type)) tmp.print(thd); tmp.length(0); if (!tmp.append(Lex_cstring(STRING_WITH_LEN(" seg["))) && !tmp.append_ulonglong(i) && !tmp.append(Lex_cstring(STRING_WITH_LEN("].flag="))) && !tmp.append_HA_KEYSEG_flags(seg[i].flag)) tmp.print(thd); } } static void print_keys(THD *thd, const char *where, const KEY *keys, uint key_count) { for (uint i= 0; i < key_count; i++) { Debug_key tmp; if (!tmp.append(where, strlen(where)) && !tmp.append_KEY(keys[i])) tmp.print(thd); } } }; #endif // SQL_DEBUG_INCLUDED mysql/server/private/my_base.h000064400000065112151027430560012471 0ustar00/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 1995, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file includes constants used with all databases */ #ifndef _my_base_h #define _my_base_h #include /* This includes types */ #include #include #include #ifndef EOVERFLOW #define EOVERFLOW 84 #endif #include /* The following is bits in the flag parameter to ha_open() */ #define HA_OPEN_ABORT_IF_LOCKED 0U /* default */ #define HA_OPEN_WAIT_IF_LOCKED 1U #define HA_OPEN_IGNORE_IF_LOCKED 2U #define HA_OPEN_TMP_TABLE 4U /* Table is a temp table */ #define HA_OPEN_DELAY_KEY_WRITE 8U /* Don't update index */ #define HA_OPEN_ABORT_IF_CRASHED 16U #define HA_OPEN_FOR_REPAIR 32U /* open even if crashed */ #define HA_OPEN_FROM_SQL_LAYER 64U #define HA_OPEN_MMAP 128U /* open memory mapped */ #define HA_OPEN_COPY 256U /* Open copy (for repair) */ /* Internal temp table, used for temporary results */ #define HA_OPEN_INTERNAL_TABLE 512U #define HA_OPEN_NO_PSI_CALL 1024U /* Don't call/connect PSI */ #define HA_OPEN_MERGE_TABLE 2048U #define HA_OPEN_FOR_CREATE 4096U #define HA_OPEN_FOR_DROP (1U << 13) /* Open part of drop */ #define HA_OPEN_GLOBAL_TMP_TABLE (1U << 14) /* TMP table used by repliction */ /* Allow opening even if table is incompatible as this is for ALTER TABLE which will fix the table structure. */ #define HA_OPEN_FOR_ALTER 8192U /* Open table for FLUSH */ #define HA_OPEN_FOR_FLUSH 8192U /* The following is parameter to ha_rkey() how to use key */ /* We define a complete-field prefix of a key value as a prefix where the last included field in the prefix contains the full field, not just some bytes from the start of the field. A partial-field prefix is allowed to contain only a few first bytes from the last included field. Below HA_READ_KEY_EXACT, ..., HA_READ_BEFORE_KEY can take a complete-field prefix of a key value as the search key. HA_READ_PREFIX and HA_READ_PREFIX_LAST could also take a partial-field prefix, but currently (4.0.10) they are only used with complete-field prefixes. MySQL uses a padding trick to implement LIKE 'abc%' queries. NOTE that in InnoDB HA_READ_PREFIX_LAST will NOT work with a partial-field prefix because InnoDB currently strips spaces from the end of varchar fields! */ enum ha_rkey_function { HA_READ_KEY_EXACT, /* Find first record else error */ HA_READ_KEY_OR_NEXT, /* Record or next record */ HA_READ_KEY_OR_PREV, /* Record or previous */ HA_READ_AFTER_KEY, /* Find next rec. after key-record */ HA_READ_BEFORE_KEY, /* Find next rec. before key-record */ HA_READ_PREFIX, /* Key which as same prefix */ HA_READ_PREFIX_LAST, /* Last key with the same prefix */ HA_READ_PREFIX_LAST_OR_PREV, /* Last or prev key with the same prefix */ HA_READ_MBR_CONTAIN, HA_READ_MBR_INTERSECT, HA_READ_MBR_WITHIN, HA_READ_MBR_DISJOINT, HA_READ_MBR_EQUAL }; /* Key algorithm types */ enum ha_key_alg { HA_KEY_ALG_UNDEF= 0, /* Not specified (old file) */ HA_KEY_ALG_BTREE= 1, /* B-tree, default one */ HA_KEY_ALG_RTREE= 2, /* R-tree, for spatial searches */ HA_KEY_ALG_HASH= 3, /* HASH keys (HEAP tables) */ HA_KEY_ALG_FULLTEXT= 4, /* FULLTEXT (MyISAM tables) */ HA_KEY_ALG_LONG_HASH= 5 /* long BLOB keys */ }; /* Storage media types */ enum ha_storage_media { HA_SM_DEFAULT= 0, /* Not specified (engine default) */ HA_SM_DISK= 1, /* DISK storage */ HA_SM_MEMORY= 2 /* MAIN MEMORY storage */ }; /* The following is parameter to ha_extra() */ enum ha_extra_function { HA_EXTRA_NORMAL=0, /* Optimize for space (def) */ HA_EXTRA_QUICK=1, /* Optimize for speed */ HA_EXTRA_NOT_USED=2, /* Should be ignored by handler */ HA_EXTRA_CACHE=3, /* Cache record in HA_rrnd() */ HA_EXTRA_NO_CACHE=4, /* End caching of records (def) */ HA_EXTRA_NO_READCHECK=5, /* No readcheck on update */ HA_EXTRA_READCHECK=6, /* Use readcheck (def) */ HA_EXTRA_KEYREAD=7, /* Read only key to database */ HA_EXTRA_NO_KEYREAD=8, /* Normal read of records (def) */ HA_EXTRA_NO_USER_CHANGE=9, /* No user is allowed to write */ HA_EXTRA_KEY_CACHE=10, HA_EXTRA_NO_KEY_CACHE=11, HA_EXTRA_WAIT_LOCK=12, /* Wait until file is available (def) */ HA_EXTRA_NO_WAIT_LOCK=13, /* If file is locked, return quickly */ HA_EXTRA_WRITE_CACHE=14, /* Use write cache in ha_write() */ HA_EXTRA_FLUSH_CACHE=15, /* flush write_record_cache */ HA_EXTRA_NO_KEYS=16, /* Remove all update of keys */ HA_EXTRA_KEYREAD_CHANGE_POS=17, /* Keyread, but change pos */ /* xxxxchk -r must be used */ HA_EXTRA_REMEMBER_POS=18, /* Remember pos for next/prev */ HA_EXTRA_RESTORE_POS=19, HA_EXTRA_REINIT_CACHE=20, /* init cache from current record */ HA_EXTRA_FORCE_REOPEN=21, /* Datafile have changed on disk */ HA_EXTRA_FLUSH, /* Flush tables to disk */ HA_EXTRA_NO_ROWS, /* Don't write rows */ HA_EXTRA_RESET_STATE, /* Reset positions */ HA_EXTRA_IGNORE_DUP_KEY, /* Dup keys don't rollback everything*/ HA_EXTRA_NO_IGNORE_DUP_KEY, HA_EXTRA_PREPARE_FOR_DROP, HA_EXTRA_PREPARE_FOR_UPDATE, /* Remove read cache if problems */ HA_EXTRA_PRELOAD_BUFFER_SIZE, /* Set buffer size for preloading */ /* On-the-fly switching between unique and non-unique key inserting. */ HA_EXTRA_CHANGE_KEY_TO_UNIQUE, HA_EXTRA_CHANGE_KEY_TO_DUP, /* When using HA_EXTRA_KEYREAD, overwrite only key member fields and keep other fields intact. When this is off (by default) InnoDB will use memcpy to overwrite entire row. */ HA_EXTRA_KEYREAD_PRESERVE_FIELDS, HA_EXTRA_MMAP, /* Ignore if the a tuple is not found, continue processing the transaction and ignore that 'row'. Needed for idempotency handling on the slave */ HA_EXTRA_IGNORE_NO_KEY, HA_EXTRA_NO_IGNORE_NO_KEY, /* Mark the table as a log table. For some handlers (e.g. CSV) this results in a special locking for the table. */ HA_EXTRA_MARK_AS_LOG_TABLE, /* Informs handler that write_row() which tries to insert new row into the table and encounters some already existing row with same primary/unique key can replace old row with new row instead of reporting error (basically it informs handler that we do REPLACE instead of simple INSERT). Off by default. */ HA_EXTRA_WRITE_CAN_REPLACE, HA_EXTRA_WRITE_CANNOT_REPLACE, /* Inform handler that delete_row()/update_row() cannot batch deletes/updates and should perform them immediately. This may be needed when table has AFTER DELETE/UPDATE triggers which access to subject table. These flags are reset by the handler::extra(HA_EXTRA_RESET) call. */ HA_EXTRA_DELETE_CANNOT_BATCH, HA_EXTRA_UPDATE_CANNOT_BATCH, /* Inform handler that an "INSERT...ON DUPLICATE KEY UPDATE" will be executed. This condition is unset by HA_EXTRA_NO_IGNORE_DUP_KEY. */ HA_EXTRA_INSERT_WITH_UPDATE, /* Inform handler that we will do a rename */ HA_EXTRA_PREPARE_FOR_RENAME, /* Special actions for MERGE tables. */ HA_EXTRA_ADD_CHILDREN_LIST, HA_EXTRA_ATTACH_CHILDREN, HA_EXTRA_IS_ATTACHED_CHILDREN, HA_EXTRA_DETACH_CHILDREN, HA_EXTRA_DETACH_CHILD, /* Inform handler we will force a close as part of flush */ HA_EXTRA_PREPARE_FOR_FORCED_CLOSE, /* Inform handler that we will do an alter table */ HA_EXTRA_PREPARE_FOR_ALTER_TABLE, /* Used in ha_partition::handle_ordered_index_scan() to inform engine that we are starting an ordered index scan. Needed by Spider */ HA_EXTRA_STARTING_ORDERED_INDEX_SCAN, /** Start writing rows during ALTER TABLE...ALGORITHM=COPY. */ HA_EXTRA_BEGIN_ALTER_COPY, /** Finish writing rows during ALTER TABLE...ALGORITHM=COPY. */ HA_EXTRA_END_ALTER_COPY }; /* Compatible option, to be deleted in 6.0 */ #define HA_EXTRA_PREPARE_FOR_DELETE HA_EXTRA_PREPARE_FOR_DROP /* The following is parameter to ha_panic() */ enum ha_panic_function { HA_PANIC_CLOSE, /* Close all databases */ HA_PANIC_WRITE, /* Unlock and write status */ HA_PANIC_READ /* Lock and read keyinfo */ }; /* The following is parameter to ha_create(); keytypes */ enum ha_base_keytype { HA_KEYTYPE_END=0, HA_KEYTYPE_TEXT=1, /* Key is sorted as letters */ HA_KEYTYPE_BINARY=2, /* Key is sorted as unsigned chars */ HA_KEYTYPE_SHORT_INT=3, HA_KEYTYPE_LONG_INT=4, HA_KEYTYPE_FLOAT=5, HA_KEYTYPE_DOUBLE=6, HA_KEYTYPE_NUM=7, /* Not packed num with pre-space */ HA_KEYTYPE_USHORT_INT=8, HA_KEYTYPE_ULONG_INT=9, HA_KEYTYPE_LONGLONG=10, HA_KEYTYPE_ULONGLONG=11, HA_KEYTYPE_INT24=12, HA_KEYTYPE_UINT24=13, HA_KEYTYPE_INT8=14, /* Varchar (0-255 bytes) with length packed with 1 byte */ HA_KEYTYPE_VARTEXT1=15, /* Key is sorted as letters */ HA_KEYTYPE_VARBINARY1=16, /* Key is sorted as unsigned chars */ /* Varchar (0-65535 bytes) with length packed with 2 bytes */ HA_KEYTYPE_VARTEXT2=17, /* Key is sorted as letters */ HA_KEYTYPE_VARBINARY2=18, /* Key is sorted as unsigned chars */ HA_KEYTYPE_BIT=19 }; #define HA_MAX_KEYTYPE 31 /* Must be log2-1 */ /* These flags kan be OR:ed to key-flag Note that these can only be up to 16 bits! */ #define HA_NOSAME 1U /* Set if not dupplicated records */ #define HA_PACK_KEY 2U /* Pack string key to previous key */ #define HA_AUTO_KEY 16U /* MEMORY/MyISAM/Aria internal */ #define HA_BINARY_PACK_KEY 32U /* Packing of all keys to prev key */ #define HA_FULLTEXT 128U /* For full-text search */ #define HA_SPATIAL 1024U /* For spatial search */ #define HA_NULL_ARE_EQUAL 2048U /* NULL in key are cmp as equal */ #define HA_GENERATED_KEY 8192U /* Automatically generated key */ /* The combination of the above can be used for key type comparison. */ #define HA_KEYFLAG_MASK (HA_NOSAME | HA_AUTO_KEY | HA_FULLTEXT | \ HA_SPATIAL | HA_NULL_ARE_EQUAL | HA_GENERATED_KEY) /* Key contains partial segments. This flag is internal to the MySQL server by design. It is not supposed neither to be saved in FRM-files, nor to be passed to storage engines. It is intended to pass information into internal static sort_keys(KEY *, KEY *) function. This flag can be calculated -- it's based on key lengths comparison. */ #define HA_KEY_HAS_PART_KEY_SEG 65536 /* Internal Flag Can be calculated */ #define HA_INVISIBLE_KEY 2<<18 /* Automatic bits in key-flag */ #define HA_SPACE_PACK_USED 4 /* Test for if SPACE_PACK used */ #define HA_VAR_LENGTH_KEY 8 #define HA_NULL_PART_KEY 64 #define HA_USES_COMMENT 4096 #define HA_USES_PARSER 16384 /* Fulltext index uses [pre]parser */ #define HA_USES_BLOCK_SIZE ((uint) 32768) #define HA_SORT_ALLOWS_SAME 512 /* Intern bit when sorting records */ /* This flag can be used only in KEY::ext_key_flags */ #define HA_EXT_NOSAME 131072 /* These flags can be added to key-seg-flag */ #define HA_SPACE_PACK 1 /* Pack space in key-seg */ #define HA_PART_KEY_SEG 4 /* Used by MySQL for part-key-cols */ #define HA_VAR_LENGTH_PART 8 #define HA_NULL_PART 16 #define HA_BLOB_PART 32 #define HA_SWAP_KEY 64 #define HA_REVERSE_SORT 128 /* Sort key in reverse order */ #define HA_NO_SORT 256 /* do not bother sorting on this keyseg */ #define HA_BIT_PART 1024 #define HA_CAN_MEMCMP 2048 /* internal, never stored in frm */ /* optionbits for database */ #define HA_OPTION_PACK_RECORD 1U #define HA_OPTION_PACK_KEYS 2U #define HA_OPTION_COMPRESS_RECORD 4U #define HA_OPTION_LONG_BLOB_PTR 8U /* new ISAM format */ #define HA_OPTION_TMP_TABLE 16U #define HA_OPTION_CHECKSUM 32U #define HA_OPTION_DELAY_KEY_WRITE 64U #define HA_OPTION_NO_PACK_KEYS 128U /* Reserved for MySQL */ /* unused 256 */ #define HA_OPTION_RELIES_ON_SQL_LAYER 512U #define HA_OPTION_NULL_FIELDS 1024U #define HA_OPTION_PAGE_CHECKSUM 2048U /* STATS_PERSISTENT=1 has been specified in the SQL command (either CREATE or ALTER TABLE). Table and index statistics that are collected by the storage engine and used by the optimizer for query optimization will be stored on disk and will not change after a server restart. */ #define HA_OPTION_STATS_PERSISTENT 4096U /* STATS_PERSISTENT=0 has been specified in CREATE/ALTER TABLE. Statistics for the table will be wiped away on server shutdown and new ones recalculated after the server is started again. If none of HA_OPTION_STATS_PERSISTENT or HA_OPTION_NO_STATS_PERSISTENT is set, this means that the setting is not explicitly set at table level and the corresponding table will use whatever is the global server default. */ #define HA_OPTION_NO_STATS_PERSISTENT 8192U /* .frm has extra create options in linked-list format */ #define HA_OPTION_TEXT_CREATE_OPTIONS_legacy (1U << 14) /* 5.2 to 5.5, unused since 10.0 */ #define HA_OPTION_TEMP_COMPRESS_RECORD (1U << 15) /* set by isamchk */ #define HA_OPTION_READ_ONLY_DATA (1U << 16) /* Set by isamchk */ #define HA_OPTION_NO_CHECKSUM (1U << 17) #define HA_OPTION_NO_DELAY_KEY_WRITE (1U << 18) /* Bits in flag to create() */ #define HA_DONT_TOUCH_DATA 1U /* Don't empty datafile (isamchk) */ #define HA_PACK_RECORD 2U /* Request packed record format */ #define HA_CREATE_TMP_TABLE 4U #define HA_CREATE_CHECKSUM 8U #define HA_CREATE_KEEP_FILES 16U /* don't overwrite .MYD and MYI */ #define HA_CREATE_PAGE_CHECKSUM 32U #define HA_CREATE_DELAY_KEY_WRITE 64U #define HA_CREATE_RELIES_ON_SQL_LAYER 128U #define HA_CREATE_INTERNAL_TABLE 256U #define HA_PRESERVE_INSERT_ORDER 512U #define HA_CREATE_NO_ROLLBACK 1024U /* A temporary table that can be used by different threads, eg. replication threads. This flag ensure that memory is not allocated with THREAD_SPECIFIC, as we do for other temporary tables. */ #define HA_CREATE_GLOBAL_TMP_TABLE 2048U /* Flags used by start_bulk_insert */ #define HA_CREATE_UNIQUE_INDEX_BY_SORT 1U /* The following flags (OR-ed) are passed to handler::info() method. The method copies misc handler information out of the storage engine to data structures accessible from MySQL Same flags are also passed down to mi_status, myrg_status, etc. */ /* this one is not used */ #define HA_STATUS_POS 1U /* assuming the table keeps shared actual copy of the 'info' and local, possibly outdated copy, the following flag means that it should not try to get the actual data (locking the shared structure) slightly outdated version will suffice */ #define HA_STATUS_NO_LOCK 2U /* update the time of the last modification (in handler::update_time) */ #define HA_STATUS_TIME 4U /* update the 'constant' part of the info: handler::max_data_file_length, max_index_file_length, create_time sortkey, ref_length, block_size, data_file_name, index_file_name. handler::table->s->keys_in_use, keys_for_keyread, rec_per_key */ #define HA_STATUS_CONST 8U /* update the 'variable' part of the info: handler::records, deleted, data_file_length, index_file_length, check_time, mean_rec_length */ #define HA_STATUS_VARIABLE 16U /* get the information about the key that caused last duplicate value error update handler::errkey and handler::dupp_ref see handler::get_dup_key() */ #define HA_STATUS_ERRKEY 32U /* update handler::auto_increment_value */ #define HA_STATUS_AUTO 64U /* Get also delete_length when HA_STATUS_VARIABLE is called. It's ok to set it also when only HA_STATUS_VARIABLE but it won't be used. */ #define HA_STATUS_VARIABLE_EXTRA 128U /* Treat empty table as empty (ignore HA_STATUS_TIME hack). */ #define HA_STATUS_OPEN 256U /* Errorcodes given by handler functions opt_sum_query() assumes these codes are > 1 Do not add error numbers before HA_ERR_FIRST. If necessary to add lower numbers, change HA_ERR_FIRST accordingly. */ #define HA_ERR_FIRST 120 /* Copy of first error nr.*/ #define HA_ERR_KEY_NOT_FOUND 120 /* Didn't find key on read or update */ #define HA_ERR_FOUND_DUPP_KEY 121 /* Duplicate key on write */ #define HA_ERR_INTERNAL_ERROR 122 /* Internal error */ #define HA_ERR_RECORD_CHANGED 123 /* Update with is recoverable */ #define HA_ERR_WRONG_INDEX 124 /* Wrong index given to function */ #define HA_ERR_CRASHED 126 /* Indexfile is crashed */ #define HA_ERR_WRONG_IN_RECORD 127 /* Record-file is crashed */ #define HA_ERR_OUT_OF_MEM 128 /* Out of memory */ #define HA_ERR_RETRY_INIT 129 /* Initialization failed and should be retried */ #define HA_ERR_NOT_A_TABLE 130 /* not a MYI file - no signature */ #define HA_ERR_WRONG_COMMAND 131 /* Command not supported */ #define HA_ERR_OLD_FILE 132 /* old databasfile */ #define HA_ERR_NO_ACTIVE_RECORD 133 /* No record read in update() */ #define HA_ERR_RECORD_DELETED 134 /* A record is not there */ #define HA_ERR_RECORD_FILE_FULL 135 /* No more room in file */ #define HA_ERR_INDEX_FILE_FULL 136 /* No more room in file */ #define HA_ERR_END_OF_FILE 137 /* end in next/prev/first/last */ #define HA_ERR_UNSUPPORTED 138 /* unsupported extension used */ #define HA_ERR_TO_BIG_ROW 139 /* Too big row */ #define HA_WRONG_CREATE_OPTION 140 /* Wrong create option */ #define HA_ERR_FOUND_DUPP_UNIQUE 141 /* Duplicate unique on write */ #define HA_ERR_UNKNOWN_CHARSET 142 /* Can't open charset */ #define HA_ERR_WRONG_MRG_TABLE_DEF 143 /* conflicting tables in MERGE */ #define HA_ERR_CRASHED_ON_REPAIR 144 /* Last (automatic?) repair failed */ #define HA_ERR_CRASHED_ON_USAGE 145 /* Table must be repaired */ #define HA_ERR_LOCK_WAIT_TIMEOUT 146 #define HA_ERR_LOCK_TABLE_FULL 147 #define HA_ERR_READ_ONLY_TRANSACTION 148 /* Updates not allowed */ #define HA_ERR_LOCK_DEADLOCK 149 #define HA_ERR_CANNOT_ADD_FOREIGN 150 /* Cannot add a foreign key constr. */ #define HA_ERR_NO_REFERENCED_ROW 151 /* Cannot add a child row */ #define HA_ERR_ROW_IS_REFERENCED 152 /* Cannot delete a parent row */ #define HA_ERR_NO_SAVEPOINT 153 /* No savepoint with that name */ #define HA_ERR_NON_UNIQUE_BLOCK_SIZE 154 /* Non unique key block size */ #define HA_ERR_NO_SUCH_TABLE 155 /* The table does not exist in engine */ #define HA_ERR_TABLE_EXIST 156 /* The table existed in storage engine */ #define HA_ERR_NO_CONNECTION 157 /* Could not connect to storage engine */ /* NULLs are not supported in spatial index */ #define HA_ERR_NULL_IN_SPATIAL 158 #define HA_ERR_TABLE_DEF_CHANGED 159 /* The table changed in storage engine */ /* There's no partition in table for given value */ #define HA_ERR_NO_PARTITION_FOUND 160 #define HA_ERR_RBR_LOGGING_FAILED 161 /* Row-based binlogging of row failed */ #define HA_ERR_DROP_INDEX_FK 162 /* Index needed in foreign key constr */ /* Upholding foreign key constraints would lead to a duplicate key error in some other table. */ #define HA_ERR_FOREIGN_DUPLICATE_KEY 163 /* The table changed in storage engine */ #define HA_ERR_TABLE_NEEDS_UPGRADE 164 #define HA_ERR_TABLE_READONLY 165 /* The table is not writable */ #define HA_ERR_AUTOINC_READ_FAILED 166 /* Failed to get next autoinc value */ #define HA_ERR_AUTOINC_ERANGE 167 /* Failed to set row autoinc value */ #define HA_ERR_GENERIC 168 /* Generic error */ /* row not actually updated: new values same as the old values */ #define HA_ERR_RECORD_IS_THE_SAME 169 #define HA_ERR_LOGGING_IMPOSSIBLE 170 /* It is not possible to log this statement */ #define HA_ERR_CORRUPT_EVENT 171 /* The event was corrupt, leading to illegal data being read */ #define HA_ERR_NEW_FILE 172 /* New file format */ #define HA_ERR_ROWS_EVENT_APPLY 173 /* The event could not be processed no other handler error happened */ #define HA_ERR_INITIALIZATION 174 /* Error during initialization */ #define HA_ERR_FILE_TOO_SHORT 175 /* File too short */ #define HA_ERR_WRONG_CRC 176 /* Wrong CRC on page */ #define HA_ERR_TOO_MANY_CONCURRENT_TRXS 177 /*Too many active concurrent transactions */ /* There's no explicitly listed partition in table for the given value */ #define HA_ERR_NOT_IN_LOCK_PARTITIONS 178 #define HA_ERR_INDEX_COL_TOO_LONG 179 /* Index column length exceeds limit */ #define HA_ERR_INDEX_CORRUPT 180 /* Index corrupted */ #define HA_ERR_UNDO_REC_TOO_BIG 181 /* Undo log record too big */ #define HA_FTS_INVALID_DOCID 182 /* Invalid InnoDB Doc ID */ /* #define HA_ERR_TABLE_IN_FK_CHECK 183 */ /* Table being used in foreign key check */ #define HA_ERR_TABLESPACE_EXISTS 184 /* The tablespace existed in storage engine */ #define HA_ERR_TOO_MANY_FIELDS 185 /* Table has too many columns */ #define HA_ERR_ROW_IN_WRONG_PARTITION 186 /* Row in wrong partition */ #define HA_ERR_ROW_NOT_VISIBLE 187 #define HA_ERR_ABORTED_BY_USER 188 #define HA_ERR_DISK_FULL 189 #define HA_ERR_INCOMPATIBLE_DEFINITION 190 #define HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE 191 /* Too many words in a phrase */ #define HA_ERR_DECRYPTION_FAILED 192 /* Table encrypted but decrypt failed */ #define HA_ERR_FK_DEPTH_EXCEEDED 193 /* FK cascade depth exceeded */ #define HA_ERR_TABLESPACE_MISSING 194 /* Missing Tablespace */ #define HA_ERR_SEQUENCE_INVALID_DATA 195 #define HA_ERR_SEQUENCE_RUN_OUT 196 #define HA_ERR_COMMIT_ERROR 197 #define HA_ERR_PARTITION_LIST 198 #define HA_ERR_NO_ENCRYPTION 199 #define HA_ERR_ROLLBACK 200 /* Automatic rollback done */ #define HA_ERR_LAST 200 /* Copy of last error nr * */ /* Number of different errors */ #define HA_ERR_ERRORS (HA_ERR_LAST - HA_ERR_FIRST + 1) /* aliases */ #define HA_ERR_TABLE_CORRUPT HA_ERR_WRONG_IN_RECORD #define HA_ERR_QUERY_INTERRUPTED HA_ERR_ABORTED_BY_USER #define HA_ERR_NOT_ALLOWED_COMMAND HA_ERR_WRONG_COMMAND /* Other constants */ #define HA_NAMELEN 64 /* Max length of saved filename */ #define NO_SUCH_KEY (~(uint)0) /* used as a key no. */ typedef ulong key_part_map; #define HA_WHOLE_KEY (~(key_part_map)0) /* Intern constants in databases */ /* bits in _search */ #define SEARCH_FIND 1U #define SEARCH_NO_FIND 2U #define SEARCH_SAME 4U #define SEARCH_BIGGER 8U #define SEARCH_SMALLER 16U #define SEARCH_SAVE_BUFF 32U #define SEARCH_UPDATE 64U #define SEARCH_PREFIX 128U #define SEARCH_LAST 256U #define MBR_CONTAIN 512U #define MBR_INTERSECT 1024U #define MBR_WITHIN 2048U #define MBR_DISJOINT 4096U #define MBR_EQUAL 8192U #define MBR_DATA 16384U #define SEARCH_NULL_ARE_EQUAL 32768U /* NULL in keys are equal */ #define SEARCH_NULL_ARE_NOT_EQUAL 65536U/* NULL in keys are not equal */ /* Use this when inserting a key in position order */ #define SEARCH_INSERT (SEARCH_NULL_ARE_NOT_EQUAL*2) /* Only part of the key is specified while reading */ #define SEARCH_PART_KEY (SEARCH_INSERT*2) /* Used when user key (key 2) contains transaction id's */ #define SEARCH_USER_KEY_HAS_TRANSID (SEARCH_PART_KEY*2) /* Used when page key (key 1) contains transaction id's */ #define SEARCH_PAGE_KEY_HAS_TRANSID (SEARCH_USER_KEY_HAS_TRANSID*2) /* bits in opt_flag */ #define QUICK_USED 1U #define READ_CACHE_USED 2U #define READ_CHECK_USED 4U #define KEY_READ_USED 8U #define WRITE_CACHE_USED 16U #define OPT_NO_ROWS 32U /* bits in update */ #define HA_STATE_CHANGED 1U /* Database has changed */ #define HA_STATE_AKTIV 2U /* Has a current record */ #define HA_STATE_WRITTEN 4U /* Record is written */ #define HA_STATE_DELETED 8U #define HA_STATE_NEXT_FOUND 16U /* Next found record (record before) */ #define HA_STATE_PREV_FOUND 32U /* Prev found record (record after) */ #define HA_STATE_NO_KEY 64U /* Last read didn't find record */ #define HA_STATE_KEY_CHANGED 128U #define HA_STATE_WRITE_AT_END 256U /* set in _ps_find_writepos */ #define HA_STATE_BUFF_SAVED 512U /* If current keybuff is info->buff */ #define HA_STATE_ROW_CHANGED 1024U /* To invalidate ROW cache */ #define HA_STATE_EXTEND_BLOCK 2048U #define HA_STATE_RNEXT_SAME 4096U /* rnext_same occupied lastkey2 */ /* myisampack expects no more than 32 field types. */ enum en_fieldtype { FIELD_LAST=-1,FIELD_NORMAL,FIELD_SKIP_ENDSPACE,FIELD_SKIP_PRESPACE, FIELD_SKIP_ZERO,FIELD_BLOB,FIELD_CONSTANT,FIELD_INTERVALL,FIELD_ZERO, FIELD_VARCHAR,FIELD_CHECK, FIELD_enum_val_count }; enum data_file_type { STATIC_RECORD, DYNAMIC_RECORD, COMPRESSED_RECORD, BLOCK_RECORD, NO_RECORD }; /* For key ranges */ #define NO_MIN_RANGE 1U #define NO_MAX_RANGE 2U #define NEAR_MIN 4U #define NEAR_MAX 8U #define UNIQUE_RANGE 16U #define EQ_RANGE 32U #define NULL_RANGE 64U #define GEOM_FLAG 128U typedef struct st_key_range { const uchar *key; uint length; key_part_map keypart_map; enum ha_rkey_function flag; } key_range; typedef void *range_id_t; typedef struct st_key_multi_range { key_range start_key; key_range end_key; range_id_t ptr; /* Free to use by caller (ptr to row etc) */ /* A set of range flags that describe both endpoints: UNIQUE_RANGE, NULL_RANGE, EQ_RANGE, GEOM_FLAG. (Flags that describe one endpoint, NO_{MIN|MAX}_RANGE, NEAR_{MIN|MAX} will not be set here) */ uint range_flag; } KEY_MULTI_RANGE; /* Store first and last leaf page accessed by records_in_range */ typedef struct st_page_range { ulonglong first_page; ulonglong last_page; } page_range; #define UNUSED_PAGE_NO ULONGLONG_MAX #define unused_page_range { UNUSED_PAGE_NO, UNUSED_PAGE_NO } /* For number of records */ #ifdef BIG_TABLES #define rows2double(A) ulonglong2double(A) typedef my_off_t ha_rows; #else #define rows2double(A) (double) (A) typedef ulong ha_rows; #endif #define HA_POS_ERROR (~ (ha_rows) 0) #define HA_OFFSET_ERROR (~ (my_off_t) 0) #define HA_ROWS_MAX HA_POS_ERROR #if SIZEOF_OFF_T == 4 #define MAX_FILE_SIZE INT_MAX32 #else #define MAX_FILE_SIZE LONGLONG_MAX #endif #define HA_VARCHAR_PACKLENGTH(field_length) ((field_length) < 256 ? 1 :2) /* invalidator function reference for Query Cache */ C_MODE_START typedef void (* invalidator_by_filename)(const char * filename); C_MODE_END #endif /* _my_base_h */ mysql/server/private/myisamchk.h000064400000011154151027430560013034 0ustar00/* Copyright (C) 2006 MySQL AB Copyright (c) 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Definitions needed for myisamchk/mariachk.c */ #ifndef _myisamchk_h #define _myisamchk_h #include /* Flags used by xxxxchk.c or/and ha_xxxx.cc that are NOT passed to xxxcheck.c follows: */ #define TT_USEFRM 1U #define TT_FOR_UPGRADE 2U #define TT_FROM_MYSQL 4U /* Bits set in out_flag */ #define O_NEW_DATA 2U #define O_DATA_LOST 4U /* MARIA/MYISAM supports several statistics collection methods. Currently statistics collection method is not stored in MARIA file and has to be specified for each table analyze/repair operation in MI_CHECK::stats_method. */ typedef enum { /* Treat NULLs as inequal when collecting statistics (default for 4.1/5.0) */ MI_STATS_METHOD_NULLS_NOT_EQUAL, /* Treat NULLs as equal when collecting statistics (like 4.0 did) */ MI_STATS_METHOD_NULLS_EQUAL, /* Ignore NULLs - count only tuples without NULLs in the index components */ MI_STATS_METHOD_IGNORE_NULLS } enum_handler_stats_method; struct st_myisam_info; typedef struct st_handler_check_param { char *isam_file_name; MY_TMPDIR *tmpdir; void *thd; const char *db_name, *table_name, *op_name; ulonglong auto_increment_value; ulonglong max_data_file_length; ulonglong keys_in_use; ulonglong max_record_length; /* The next two are used to collect statistics, see update_key_parts for description. */ ulonglong unique_count[HA_MAX_KEY_SEG + 1]; ulonglong notnull_count[HA_MAX_KEY_SEG + 1]; ulonglong max_allowed_lsn; my_off_t search_after_block; my_off_t new_file_pos, key_file_blocks; my_off_t keydata, totaldata, key_blocks, start_check_pos; my_off_t used, empty, splits, del_length, link_used, lost; ha_rows total_records, total_deleted, records,del_blocks; ha_rows full_page_count, tail_count; ha_checksum record_checksum, glob_crc; ha_checksum key_crc[HA_MAX_POSSIBLE_KEY]; ha_checksum tmp_key_crc[HA_MAX_POSSIBLE_KEY]; ha_checksum tmp_record_checksum; ulonglong org_key_map; ulonglong testflag; /* Following is used to check if rows are visible */ ulonglong max_trid, max_found_trid; ulonglong not_visible_rows_found; ulonglong sort_buffer_length, orig_sort_buffer_length; ulonglong use_buffers; /* Used as param to getopt() */ size_t read_buffer_length, write_buffer_length, sort_key_blocks; time_t backup_time; /* To sign backup files */ ulong rec_per_key_part[HA_MAX_KEY_SEG * HA_MAX_POSSIBLE_KEY]; double new_rec_per_key_part[HA_MAX_KEY_SEG * HA_MAX_POSSIBLE_KEY]; uint out_flag, error_printed, verbose; uint opt_sort_key, total_files, max_level; uint key_cache_block_size, pagecache_block_size; uint skip_lsn_error_count; int tmpfile_createflag, err_count; myf myf_rw; uint16 language; my_bool warning_printed, note_printed, wrong_trd_printed; my_bool using_global_keycache, opt_lock_memory, opt_follow_links; my_bool retry_repair, force_sort, calc_checksum, static_row_size; char temp_filename[FN_REFLEN]; IO_CACHE read_cache; void **stack_end_ptr; enum_handler_stats_method stats_method; /* For reporting progress */ uint stage, max_stage; uint progress_counter; /* How often to call _report_progress() */ ulonglong progress, max_progress; void (*init_fix_record)(void *); int (*fix_record)(struct st_myisam_info *info, uchar *record, int keynum); mysql_mutex_t print_msg_mutex; my_bool need_print_msg_lock; myf malloc_flags; } HA_CHECK; typedef struct st_buffpek { my_off_t file_pos; /* Where we are in the sort file */ uchar *base, *key; /* Key pointers */ ha_rows count; /* Number of rows in table */ ha_rows mem_count; /* Numbers of keys in memory */ ha_rows max_keys; /* Max keys in buffert */ } BUFFPEK; #endif /* _myisamchk_h */ mysql/server/private/semisync_master.h000064400000062246151027430560014264 0ustar00/* Copyright (C) 2007 Google Inc. Copyright (c) 2008 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SEMISYNC_MASTER_H #define SEMISYNC_MASTER_H #include "semisync.h" #include "semisync_master_ack_receiver.h" #ifdef HAVE_PSI_INTERFACE extern PSI_mutex_key key_LOCK_rpl_semi_sync_master_enabled; extern PSI_mutex_key key_LOCK_binlog; extern PSI_cond_key key_COND_binlog_send; #endif struct Tranx_node { char log_name[FN_REFLEN]; bool thd_valid; /* thd is valid for signalling */ my_off_t log_pos; THD *thd; /* The thread awaiting an ACK */ struct Tranx_node *next; /* the next node in the sorted list */ struct Tranx_node *hash_next; /* the next node during hash collision */ }; /** @class Tranx_node_allocator This class provides memory allocating and freeing methods for Tranx_node. The main target is performance. @section ALLOCATE How to allocate a node The pointer of the first node after 'last_node' in current_block is returned. current_block will move to the next free Block when all nodes of it are in use. A new Block is allocated and is put into the rear of the Block link table if no Block is free. The list starts up empty (ie, there is no allocated Block). After some nodes are freed, there probably are some free nodes before the sequence of the allocated nodes, but we do not reuse it. It is better to keep the allocated nodes are in the sequence, for it is more efficient for allocating and freeing Tranx_node. @section FREENODE How to free nodes There are two methods for freeing nodes. They are free_all_nodes and free_nodes_before. 'A Block is free' means all of its nodes are free. @subsection free_nodes_before As all allocated nodes are in the sequence, 'Before one node' means all nodes before given node in the same Block and all Blocks before the Block which containing the given node. As such, all Blocks before the given one ('node') are free Block and moved into the rear of the Block link table. The Block containing the given 'node', however, is not. For at least the given 'node' is still in use. This will waste at most one Block, but it is more efficient. */ #define BLOCK_TRANX_NODES 16 class Tranx_node_allocator { public: /** @param reserved_nodes The number of reserved Tranx_nodes. It is used to set 'reserved_blocks' which can contain at least 'reserved_nodes' number of Tranx_nodes. When freeing memory, we will reserve at least reserved_blocks of Blocks not freed. */ Tranx_node_allocator(uint reserved_nodes) : reserved_blocks(reserved_nodes/BLOCK_TRANX_NODES + (reserved_nodes%BLOCK_TRANX_NODES > 1 ? 2 : 1)), first_block(NULL), last_block(NULL), current_block(NULL), last_node(-1), block_num(0) {} ~Tranx_node_allocator() { Block *block= first_block; while (block != NULL) { Block *next= block->next; free_block(block); block= next; } } /** The pointer of the first node after 'last_node' in current_block is returned. current_block will move to the next free Block when all nodes of it are in use. A new Block is allocated and is put into the rear of the Block link table if no Block is free. @return Return a Tranx_node *, or NULL if an error occurred. */ Tranx_node *allocate_node() { Tranx_node *trx_node; Block *block= current_block; if (last_node == BLOCK_TRANX_NODES-1) { current_block= current_block->next; last_node= -1; } if (current_block == NULL && allocate_block()) { current_block= block; if (current_block) last_node= BLOCK_TRANX_NODES-1; return NULL; } trx_node= &(current_block->nodes[++last_node]); trx_node->log_name[0] = '\0'; trx_node->thd_valid= false; trx_node->log_pos= 0; trx_node->thd= nullptr; trx_node->next= 0; trx_node->hash_next= 0; return trx_node; } /** All nodes are freed. @return Return 0, or 1 if an error occurred. */ int free_all_nodes() { current_block= first_block; last_node= -1; free_blocks(); return 0; } /** All Blocks before the given 'node' are free Block and moved into the rear of the Block link table. @param node All nodes before 'node' will be freed @return Return 0, or 1 if an error occurred. */ int free_nodes_before(Tranx_node* node) { Block *block; Block *prev_block= NULL; block= first_block; while (block != current_block->next) { /* Find the Block containing the given node */ if (&(block->nodes[0]) <= node && &(block->nodes[BLOCK_TRANX_NODES]) >= node) { /* All Blocks before the given node are put into the rear */ if (first_block != block) { last_block->next= first_block; first_block= block; last_block= prev_block; last_block->next= NULL; free_blocks(); } return 0; } prev_block= block; block= block->next; } /* Node does not find should never happen */ DBUG_ASSERT(0); return 1; } private: uint reserved_blocks; /** A sequence memory which contains BLOCK_TRANX_NODES Tranx_nodes. BLOCK_TRANX_NODES The number of Tranx_nodes which are in a Block. next Every Block has a 'next' pointer which points to the next Block. These linking Blocks constitute a Block link table. */ struct Block { Block *next; Tranx_node nodes[BLOCK_TRANX_NODES]; }; /** The 'first_block' is the head of the Block link table; */ Block *first_block; /** The 'last_block' is the rear of the Block link table; */ Block *last_block; /** current_block always points the Block in the Block link table in which the last allocated node is. The Blocks before it are all in use and the Blocks after it are all free. */ Block *current_block; /** It always points to the last node which has been allocated in the current_block. */ int last_node; /** How many Blocks are in the Block link table. */ uint block_num; /** Allocate a block and then assign it to current_block. */ int allocate_block() { Block *block= (Block *)my_malloc(PSI_INSTRUMENT_ME, sizeof(Block), MYF(0)); if (block) { block->next= NULL; if (first_block == NULL) first_block= block; else last_block->next= block; /* New Block is always put into the rear */ last_block= block; /* New Block is always the current_block */ current_block= block; ++block_num; return 0; } return 1; } /** Free a given Block. @param block The Block will be freed. */ void free_block(Block *block) { my_free(block); --block_num; } /** If there are some free Blocks and the total number of the Blocks in the Block link table is larger than the 'reserved_blocks', Some free Blocks will be freed until the total number of the Blocks is equal to the 'reserved_blocks' or there is only one free Block behind the 'current_block'. */ void free_blocks() { if (current_block == NULL || current_block->next == NULL) return; /* One free Block is always kept behind the current block */ Block *block= current_block->next->next; while (block_num > reserved_blocks && block != NULL) { Block *next= block->next; free_block(block); block= next; } current_block->next->next= block; if (block == NULL) last_block= current_block->next; } }; /** Function pointer type to run on the contents of an Active_tranx node. Return 0 for success, 1 for error. Note Repl_semi_sync_master::LOCK_binlog is not guaranteed to be held for its invocation. See the context in which it is called to know. */ typedef int (*active_tranx_action)(THD *trx_thd, bool thd_valid, const char *log_file_name, my_off_t trx_log_file_pos); /** This class manages memory for active transaction list. We record each active transaction with a Tranx_node, each session can have only one open transaction. Because of EVENT, the total active transaction nodes can exceed the maximum allowed connections. */ class Active_tranx :public Trace { private: Tranx_node_allocator m_allocator; /* These two record the active transaction list in sort order. */ Tranx_node *m_trx_front, *m_trx_rear; Tranx_node **m_trx_htb; /* A hash table on active transactions. */ int m_num_entries; /* maximum hash table entries */ mysql_mutex_t *m_lock; /* mutex lock */ mysql_cond_t *m_cond_empty; /* signalled when cleared all Tranx_node */ inline void assert_lock_owner(); inline unsigned int calc_hash(const unsigned char *key, size_t length); unsigned int get_hash_value(const char *log_file_name, my_off_t log_file_pos); int compare(const char *log_file_name1, my_off_t log_file_pos1, const Tranx_node *node2) { return compare(log_file_name1, log_file_pos1, node2->log_name, node2->log_pos); } int compare(const Tranx_node *node1, const char *log_file_name2, my_off_t log_file_pos2) { return compare(node1->log_name, node1->log_pos, log_file_name2, log_file_pos2); } int compare(const Tranx_node *node1, const Tranx_node *node2) { return compare(node1->log_name, node1->log_pos, node2->log_name, node2->log_pos); } public: Active_tranx(mysql_mutex_t *lock, mysql_cond_t *cond, unsigned long trace_level); ~Active_tranx(); /* Insert an active transaction node with the specified position. * * Return: * 0: success; non-zero: error */ int insert_tranx_node(THD *thd_to_wait, const char *log_file_name, my_off_t log_file_pos); /* Clear the active transaction nodes until(inclusive) the specified * position. * If log_file_name is NULL, everything will be cleared: the sorted * list and the hash table will be reset to empty. * * The pre_delete_hook parameter is a function pointer that will be invoked * for each Active_tranx node, in order, from m_trx_front to m_trx_rear, * e.g. to signal their wakeup condition. Repl_semi_sync_binlog::LOCK_binlog * is held while this is invoked. */ void clear_active_tranx_nodes(const char *log_file_name, my_off_t log_file_pos, active_tranx_action pre_delete_hook); /* Unlinks a thread from a Tranx_node, so it will not be referenced/signalled * if it is separately killed. Note that this keeps the Tranx_node itself in * the cache so it can still be awaited by await_all_slave_replies(), e.g. * as is done by SHUTDOWN WAIT FOR ALL SLAVES. */ void unlink_thd_as_waiter(const char *log_file_name, my_off_t log_file_pos); /* Uses DBUG_ASSERT statements to ensure that the argument thd_to_check * matches the thread of the respective Tranx_node::thd of the passed in * log_file_name and log_file_pos. */ Tranx_node * is_thd_waiter(THD *thd_to_check, const char *log_file_name, my_off_t log_file_pos); /* Given a position, check to see whether the position is an active * transaction's ending position by probing the hash table. */ bool is_tranx_end_pos(const char *log_file_name, my_off_t log_file_pos); /* Given two binlog positions, compare which one is bigger based on * (file_name, file_position). */ static int compare(const char *log_file_name1, my_off_t log_file_pos1, const char *log_file_name2, my_off_t log_file_pos2); /* Check if there are no transactions actively awaiting ACKs. Returns true * if the internal linked list has no entries, false otherwise. */ bool is_empty() { return m_trx_front == NULL; } }; /** The extension class for the master of semi-synchronous replication */ class Repl_semi_sync_master :public Repl_semi_sync_base { Active_tranx *m_active_tranxs; /* active transaction list: the list will be cleared when semi-sync switches off. */ /* True when init_object has been called */ bool m_init_done; /* This cond variable is signaled when enough binlog has been sent to slave, * so that a waiting trx can return the 'ok' to the client for a commit. */ mysql_cond_t COND_binlog_send; /* Mutex that protects the following state variables and the active * transaction list. * Under no cirumstances we can acquire mysql_bin_log.LOCK_log if we are * already holding m_LOCK_binlog because it can cause deadlocks. */ mysql_mutex_t LOCK_binlog; /* This is set to true when m_reply_file_name contains meaningful data. */ bool m_reply_file_name_inited; /* The binlog name up to which we have received replies from any slaves. */ char m_reply_file_name[FN_REFLEN]; /* The position in that file up to which we have the reply from any slaves. */ my_off_t m_reply_file_pos; /* This is set to true when we know the 'smallest' wait position. */ bool m_wait_file_name_inited; /* NULL, or the 'smallest' filename that a transaction is waiting for * slave replies. */ char m_wait_file_name[FN_REFLEN]; /* The smallest position in that file that a trx is waiting for: the trx * can proceed and send an 'ok' to the client when the master has got the * reply from the slave indicating that it already got the binlog events. */ my_off_t m_wait_file_pos; /* This is set to true when we know the 'largest' transaction commit * position in the binlog file. * We always maintain the position no matter whether semi-sync is switched * on switched off. When a transaction wait timeout occurs, semi-sync will * switch off. Binlog-dump thread can use the three fields to detect when * slaves catch up on replication so that semi-sync can switch on again. */ bool m_commit_file_name_inited; /* The 'largest' binlog filename that a commit transaction is seeing. */ char m_commit_file_name[FN_REFLEN]; /* The 'largest' position in that file that a commit transaction is seeing. */ my_off_t m_commit_file_pos; /* All global variables which can be set by parameters. */ volatile bool m_master_enabled; /* semi-sync is enabled on the master */ unsigned long m_wait_timeout; /* timeout period(ms) during tranx wait */ bool m_state; /* whether semi-sync is switched */ /*Waiting for ACK before/after innodb commit*/ ulong m_wait_point; void lock(); void unlock(); /* Is semi-sync replication on? */ bool is_on() { return (m_state); } void set_master_enabled(bool enabled) { m_master_enabled = enabled; } /* Switch semi-sync off because of timeout in transaction waiting. */ void switch_off(); /* Switch semi-sync on when slaves catch up. */ int try_switch_on(int server_id, const char *log_file_name, my_off_t log_file_pos); public: Repl_semi_sync_master(); ~Repl_semi_sync_master() = default; void cleanup(); bool get_master_enabled() { return m_master_enabled; } void set_trace_level(unsigned long trace_level) { m_trace_level = trace_level; if (m_active_tranxs) m_active_tranxs->m_trace_level = trace_level; } /* Set the transaction wait timeout period, in milliseconds. */ void set_wait_timeout(unsigned long wait_timeout) { m_wait_timeout = wait_timeout; } /* Calculates a timeout that is m_wait_timeout after start_arg and saves it in out. If start_arg is NULL, the timeout is m_wait_timeout after the current system time. */ void create_timeout(struct timespec *out, struct timespec *start_arg); /* Blocks the calling thread until the ack_receiver either receives ACKs for all transactions awaiting ACKs, or times out (from rpl_semi_sync_master_timeout). If info_msg is provided, it will be output via sql_print_information when there are transactions awaiting ACKs; info_msg is not output if there are no transasctions to await. */ void await_all_slave_replies(const char *msg); /*set the ACK point, after binlog sync or after transaction commit*/ void set_wait_point(unsigned long ack_point) { m_wait_point = ack_point; } ulong wait_point() //no cover line { return m_wait_point; //no cover line } /* Initialize this class after MySQL parameters are initialized. this * function should be called once at bootstrap time. */ int init_object(); /* Enable the object to enable semi-sync replication inside the master. */ int enable_master(); /* Disable the object to disable semi-sync replication inside the master. */ void disable_master(); /* Add a semi-sync replication slave */ void add_slave(); /* Remove a semi-sync replication slave */ void remove_slave(); /* It parses a reply packet and call report_reply_binlog to handle it. */ int report_reply_packet(uint32 server_id, const uchar *packet, ulong packet_len); /* In semi-sync replication, reports up to which binlog position we have * received replies from the slave indicating that it already get the events. * * Input: * server_id - (IN) master server id number * log_file_name - (IN) binlog file name * end_offset - (IN) the offset in the binlog file up to which we have * the replies from the slave * * Return: * 0: success; non-zero: error */ int report_reply_binlog(uint32 server_id, const char* log_file_name, my_off_t end_offset); /* Commit a transaction in the final step. This function is called from * InnoDB before returning from the low commit. If semi-sync is switch on, * the function will wait to see whether binlog-dump thread get the reply for * the events of the transaction. Remember that this is not a direct wait, * instead, it waits to see whether the binlog-dump thread has reached the * point. If the wait times out, semi-sync status will be switched off and * all other transaction would not wait either. * * Input: (the transaction events' ending binlog position) * trx_wait_binlog_name - (IN) ending position's file name * trx_wait_binlog_pos - (IN) ending position's file offset * * Return: * 0: success; non-zero: error */ int commit_trx(const char* trx_wait_binlog_name, my_off_t trx_wait_binlog_pos); /*Wait for ACK after writing/sync binlog to file*/ int wait_after_sync(const char* log_file, my_off_t log_pos); /*Wait for ACK after commting the transaction*/ int wait_after_commit(THD* thd, bool all); /*Wait after the transaction is rollback*/ int wait_after_rollback(THD *thd, bool all); /* Store the current binlog position in m_active_tranxs. This position should * be acked by slave. * * Inputs: * trans_thd Thread of the transaction which is executing the * transaction. * waiter_thd Thread that will wait for the ACK from the replica, * which depends on the semi-sync wait point. If AFTER_SYNC, * and also using binlog group commit, this will be the leader * thread of the binlog commit. Otherwise, it is the thread that * is executing the transaction, i.e. the same as trans_thd. * log_file Name of the binlog file that the transaction is written into * log_pos Offset within the binlog file that the transaction is written * at */ int report_binlog_update(THD *trans_thd, THD *waiter_thd, const char *log_file, my_off_t log_pos); int dump_start(THD* thd, const char *log_file, my_off_t log_pos); void dump_end(THD* thd); /* Reserve space in the replication event packet header: * . slave semi-sync off: 1 byte - (0) * . slave semi-sync on: 3 byte - (0, 0xef, 0/1} * * Input: * packet - (IN) the header buffer * * Return: * size of the bytes reserved for header */ int reserve_sync_header(String* packet); /* Update the sync bit in the packet header to indicate to the slave whether * the master will wait for the reply of the event. If semi-sync is switched * off and we detect that the slave is catching up, we switch semi-sync on. * * Input: * THD - (IN) current dump thread * packet - (IN) the packet containing the replication event * log_file_name - (IN) the event ending position's file name * log_file_pos - (IN) the event ending position's file offset * need_sync - (IN) identify if flush_net is needed to call. * server_id - (IN) master server id number * * Return: * 0: success; non-zero: error */ int update_sync_header(THD* thd, unsigned char *packet, const char *log_file_name, my_off_t log_file_pos, bool* need_sync); /* Called when a transaction finished writing binlog events. * . update the 'largest' transactions' binlog event position * . insert the ending position in the active transaction list if * semi-sync is on * * Input: (the transaction events' ending binlog position) * THD - (IN) thread that will wait for an ACK. This can be the * binlog leader thread when using wait_point * AFTER_SYNC with binlog group commit. In all other * cases, this is the user thread executing the * transaction. * log_file_name - (IN) transaction ending position's file name * log_file_pos - (IN) transaction ending position's file offset * * Return: * 0: success; non-zero: error */ int write_tranx_in_binlog(THD *thd, const char *log_file_name, my_off_t log_file_pos); /* Read the slave's reply so that we know how much progress the slave makes * on receive replication events. */ int flush_net(THD* thd, const char *event_buf); /* Export internal statistics for semi-sync replication. */ void set_export_stats(); /* 'reset master' command is issued from the user and semi-sync need to * go off for that. */ int after_reset_master(); /*called before reset master*/ int before_reset_master(); mysql_mutex_t LOCK_rpl_semi_sync_master_enabled; }; enum rpl_semi_sync_master_wait_point_t { SEMI_SYNC_MASTER_WAIT_POINT_AFTER_BINLOG_SYNC, SEMI_SYNC_MASTER_WAIT_POINT_AFTER_STORAGE_COMMIT, }; extern Repl_semi_sync_master repl_semisync_master; extern Ack_receiver ack_receiver; /* System and status variables for the master component */ extern my_bool rpl_semi_sync_master_enabled; extern my_bool rpl_semi_sync_master_status; extern ulong rpl_semi_sync_master_wait_point; extern ulong rpl_semi_sync_master_clients; extern ulong rpl_semi_sync_master_timeout; extern ulong rpl_semi_sync_master_trace_level; extern ulong rpl_semi_sync_master_yes_transactions; extern ulong rpl_semi_sync_master_no_transactions; extern ulong rpl_semi_sync_master_off_times; extern ulong rpl_semi_sync_master_wait_timeouts; extern ulong rpl_semi_sync_master_timefunc_fails; extern ulong rpl_semi_sync_master_num_timeouts; extern ulong rpl_semi_sync_master_wait_sessions; extern ulong rpl_semi_sync_master_wait_pos_backtraverse; extern ulong rpl_semi_sync_master_avg_trx_wait_time; extern ulong rpl_semi_sync_master_avg_net_wait_time; extern ulonglong rpl_semi_sync_master_net_wait_num; extern ulonglong rpl_semi_sync_master_trx_wait_num; extern ulonglong rpl_semi_sync_master_net_wait_time; extern ulonglong rpl_semi_sync_master_trx_wait_time; extern unsigned long long rpl_semi_sync_master_request_ack; extern unsigned long long rpl_semi_sync_master_get_ack; /* This indicates whether we should keep waiting if no semi-sync slave is available. 0 : stop waiting if detected no avaialable semi-sync slave. 1 (default) : keep waiting until timeout even no available semi-sync slave. */ extern char rpl_semi_sync_master_wait_no_slave; extern Repl_semi_sync_master repl_semisync_master; extern PSI_stage_info stage_waiting_for_semi_sync_ack_from_slave; extern PSI_stage_info stage_reading_semi_sync_ack; extern PSI_stage_info stage_waiting_for_semi_sync_slave; void semi_sync_master_deinit(); #endif /* SEMISYNC_MASTER_H */ mysql/server/private/ilist.h000064400000015610151027430560012174 0ustar00/* Copyright (c) 2019, 2020, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef ILIST_H #define ILIST_H #include "my_dbug.h" #include #include // Derive your class from this struct to insert to a linked list. template struct ilist_node { #ifndef DBUG_OFF ilist_node() noexcept : next(NULL), prev(NULL) {} #else ilist_node() = default; #endif ilist_node(ilist_node *next, ilist_node *prev) noexcept : next(next), prev(prev) { } ilist_node *next; ilist_node *prev; }; // Modelled after std::list template class ilist { public: typedef ilist_node ListNode; class Iterator; // All containers in C++ should define these types to implement generic // container interface. typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef value_type &reference; typedef const value_type &const_reference; typedef T *pointer; typedef const T *const_pointer; typedef Iterator iterator; typedef Iterator const_iterator; /* FIXME */ typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; class Iterator { public: // All iterators in C++ should define these types to implement generic // iterator interface. typedef std::bidirectional_iterator_tag iterator_category; typedef T value_type; typedef std::ptrdiff_t difference_type; typedef T *pointer; typedef T &reference; explicit Iterator(ListNode *node) noexcept : node_(node) { DBUG_ASSERT(node_ != nullptr); } Iterator &operator++() noexcept { node_= node_->next; DBUG_ASSERT(node_ != nullptr); return *this; } Iterator operator++(int) noexcept { Iterator tmp(*this); operator++(); return tmp; } Iterator &operator--() noexcept { node_= node_->prev; DBUG_ASSERT(node_ != nullptr); return *this; } Iterator operator--(int) noexcept { Iterator tmp(*this); operator--(); return tmp; } reference operator*() noexcept { return *static_cast(node_); } pointer operator->() noexcept { return static_cast(node_); } friend bool operator==(const Iterator &lhs, const Iterator &rhs) noexcept { return lhs.node_ == rhs.node_; } friend bool operator!=(const Iterator &lhs, const Iterator &rhs) noexcept { return !(lhs == rhs); } private: ListNode *node_; friend class ilist; }; ilist() noexcept : sentinel_(&sentinel_, &sentinel_) {} reference front() noexcept { return *begin(); } reference back() noexcept { return *--end(); } const_reference front() const noexcept { return *begin(); } const_reference back() const noexcept { return *--end(); } iterator begin() noexcept { return iterator(sentinel_.next); } const_iterator begin() const noexcept { return iterator(const_cast(sentinel_.next)); } iterator end() noexcept { return iterator(&sentinel_); } const_iterator end() const noexcept { return iterator(const_cast(&sentinel_)); } reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } const_reverse_iterator rbegin() const noexcept { return reverse_iterator(end()); } reverse_iterator rend() noexcept { return reverse_iterator(begin()); } const_reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } bool empty() const noexcept { return sentinel_.next == &sentinel_; } // Not implemented because it's O(N) // size_type size() const // { // return static_cast(std::distance(begin(), end())); // } void clear() noexcept { sentinel_.next= &sentinel_; sentinel_.prev= &sentinel_; } iterator insert(iterator pos, reference value) noexcept { ListNode *curr= pos.node_; ListNode *prev= pos.node_->prev; prev->next= &value; curr->prev= &value; static_cast(value).prev= prev; static_cast(value).next= curr; return iterator(&value); } iterator erase(iterator pos) noexcept { ListNode *prev= pos.node_->prev; ListNode *next= pos.node_->next; prev->next= next; next->prev= prev; #ifndef DBUG_OFF ListNode *curr= pos.node_; curr->prev= nullptr; curr->next= nullptr; #endif return Iterator(next); } void push_back(reference value) noexcept { insert(end(), value); } void pop_back() noexcept { erase(end()); } void push_front(reference value) noexcept { insert(begin(), value); } void pop_front() noexcept { erase(begin()); } // STL version is O(n) but this is O(1) because an element can't be inserted // several times in the same ilist. void remove(reference value) noexcept { erase(iterator(&value)); } private: ListNode sentinel_; }; // Similar to ilist but also has O(1) size() method. template class sized_ilist : public ilist { typedef ilist BASE; public: // All containers in C++ should define these types to implement generic // container interface. typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef value_type &reference; typedef const value_type &const_reference; typedef T *pointer; typedef const T *const_pointer; typedef typename BASE::Iterator iterator; typedef const typename BASE::Iterator const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; sized_ilist() noexcept : size_(0) {} size_type size() const noexcept { return size_; } void clear() noexcept { BASE::clear(); size_= 0; } iterator insert(iterator pos, reference value) noexcept { ++size_; return BASE::insert(pos, value); } iterator erase(iterator pos) noexcept { --size_; return BASE::erase(pos); } void push_back(reference value) noexcept { insert(BASE::end(), value); } void pop_back() noexcept { erase(BASE::end()); } void push_front(reference value) noexcept { insert(BASE::begin(), value); } void pop_front() noexcept { erase(BASE::begin()); } void remove(reference value) noexcept { erase(iterator(&value)); } private: size_type size_; }; #endif mysql/server/private/table.h000064400000342301151027430560012137 0ustar00#ifndef TABLE_INCLUDED #define TABLE_INCLUDED /* Copyright (c) 2000, 2017, Oracle and/or its affiliates. Copyright (c) 2009, 2022, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "sql_plist.h" #include "sql_list.h" /* Sql_alloc */ #include "mdl.h" #include "datadict.h" #include "sql_string.h" /* String */ #include "lex_string.h" #include "lex_ident.h" #ifndef MYSQL_CLIENT #include "my_cpu.h" /* LF_BACKOFF() */ #include "hash.h" /* HASH */ #include "handler.h" /* row_type, ha_choice, handler */ #include "mysql_com.h" /* enum_field_types */ #include "thr_lock.h" /* thr_lock_type */ #include "filesort_utils.h" #include "parse_file.h" #include "sql_i_s.h" #include "sql_type.h" /* vers_kind_t */ #include "privilege.h" /* privilege_t */ #include "my_bit.h" /* Buffer for unix timestamp in microseconds: 9,223,372,036,854,775,807 (signed int64 maximal value) 1 234 567 890 123 456 789 Note: we can use unsigned for calculation, but practically they are the same by probability to overflow them (signed int64 in microseconds is enough for almost 3e5 years) and signed allow to avoid increasing the buffer (the old buffer for human readable date was 19+1). */ #define MICROSECOND_TIMESTAMP_BUFFER_SIZE (19 + 1) /* Structs that defines the TABLE */ class Item; /* Needed by ORDER */ typedef Item (*Item_ptr); class Item_subselect; class Item_field; class Item_func_hash; class GRANT_TABLE; class st_select_lex_unit; class st_select_lex; class partition_info; class COND_EQUAL; class Security_context; struct TABLE_LIST; class ACL_internal_schema_access; class ACL_internal_table_access; class Field; class Table_statistics; class With_element; struct TDC_element; class Virtual_column_info; class Table_triggers_list; class TMP_TABLE_PARAM; class SEQUENCE; class Range_rowid_filter_cost_info; class derived_handler; class Pushdown_derived; struct Name_resolution_context; class Table_function_json_table; /* Used to identify NESTED_JOIN structures within a join (applicable only to structures that have not been simplified away and embed more the one element) */ typedef ulonglong nested_join_map; #define VIEW_MD5_LEN 32 #define tmp_file_prefix "#sql" /**< Prefix for tmp tables */ #define tmp_file_prefix_length 4 #define TMP_TABLE_KEY_EXTRA 8 /** Enumerate possible types of a table from re-execution standpoint. TABLE_LIST class has a member of this type. At prepared statement prepare, this member is assigned a value as of the current state of the database. Before (re-)execution of a prepared statement, we check that the value recorded at prepare matches the type of the object we obtained from the table definition cache. @sa check_and_update_table_version() @sa Execute_observer @sa Prepared_statement::reprepare() */ enum enum_table_ref_type { /** Initial value set by the parser */ TABLE_REF_NULL= 0, TABLE_REF_VIEW, TABLE_REF_BASE_TABLE, TABLE_REF_I_S_TABLE, TABLE_REF_TMP_TABLE }; /*************************************************************************/ /** Object_creation_ctx -- interface for creation context of database objects (views, stored routines, events, triggers). Creation context -- is a set of attributes, that should be fixed at the creation time and then be used each time the object is parsed or executed. */ class Object_creation_ctx { public: Object_creation_ctx *set_n_backup(THD *thd); void restore_env(THD *thd, Object_creation_ctx *backup_ctx); protected: Object_creation_ctx() = default; virtual Object_creation_ctx *create_backup_ctx(THD *thd) const = 0; virtual void change_env(THD *thd) const = 0; public: virtual ~Object_creation_ctx() = default; }; /*************************************************************************/ /** Default_object_creation_ctx -- default implementation of Object_creation_ctx. */ class Default_object_creation_ctx : public Object_creation_ctx { public: CHARSET_INFO *get_client_cs() { return m_client_cs; } CHARSET_INFO *get_connection_cl() { return m_connection_cl; } protected: Default_object_creation_ctx(THD *thd); Default_object_creation_ctx(CHARSET_INFO *client_cs, CHARSET_INFO *connection_cl); protected: Object_creation_ctx *create_backup_ctx(THD *thd) const override; void change_env(THD *thd) const override; protected: /** client_cs stores the value of character_set_client session variable. The only character set attribute is used. Client character set is included into query context, because we save query in the original character set, which is client character set. So, in order to parse the query properly we have to switch client character set on parsing. */ CHARSET_INFO *m_client_cs; /** connection_cl stores the value of collation_connection session variable. Both character set and collation attributes are used. Connection collation is included into query context, becase it defines the character set and collation of text literals in internal representation of query (item-objects). */ CHARSET_INFO *m_connection_cl; }; class Query_arena; /*************************************************************************/ /** View_creation_ctx -- creation context of view objects. */ class View_creation_ctx : public Default_object_creation_ctx, public Sql_alloc { public: static View_creation_ctx *create(THD *thd); static View_creation_ctx *create(THD *thd, TABLE_LIST *view); private: View_creation_ctx(THD *thd) : Default_object_creation_ctx(thd) { } }; /*************************************************************************/ /* Order clause list element */ typedef int (*fast_field_copier)(Field *to, Field *from); typedef struct st_order { struct st_order *next; Item **item; /* Point at item in select fields */ Item *item_ptr; /* Storage for initial item */ /* Reference to the function we are trying to optimize copy to a temporary table */ fast_field_copier fast_field_copier_func; /* Field for which above optimizer function setup */ Field *fast_field_copier_setup; int counter; /* position in SELECT list, correct only if counter_used is true*/ enum enum_order { ORDER_NOT_RELEVANT, ORDER_ASC, ORDER_DESC }; enum_order direction; /* Requested direction of ordering */ bool in_field_list; /* true if in select field list */ bool counter_used; /* parameter was counter of columns */ Field *field; /* If tmp-table group */ char *buff; /* If tmp-table group */ table_map used; /* NOTE: the below is only set to 0 but is still used by eq_ref_table */ table_map depend_map; } ORDER; /** State information for internal tables grants. This structure is part of the TABLE_LIST, and is updated during the ACL check process. @sa GRANT_INFO */ struct st_grant_internal_info { /** True if the internal lookup by schema name was done. */ bool m_schema_lookup_done; /** Cached internal schema access. */ const ACL_internal_schema_access *m_schema_access; /** True if the internal lookup by table name was done. */ bool m_table_lookup_done; /** Cached internal table access. */ const ACL_internal_table_access *m_table_access; }; typedef struct st_grant_internal_info GRANT_INTERNAL_INFO; /** @brief The current state of the privilege checking process for the current user, SQL statement and SQL object. @details The privilege checking process is divided into phases depending on the level of the privilege to be checked and the type of object to be accessed. Due to the mentioned scattering of privilege checking functionality, it is necessary to keep track of the state of the process. This information is stored in privilege, want_privilege, and orig_want_privilege. A GRANT_INFO also serves as a cache of the privilege hash tables. Relevant members are grant_table and version. */ typedef struct st_grant_info { /** @brief A copy of the privilege information regarding the current host, database, object and user. @details The version of this copy is found in GRANT_INFO::version. */ GRANT_TABLE *grant_table_user; GRANT_TABLE *grant_table_role; /** @brief Used for cache invalidation when caching privilege information. @details The privilege information is stored on disk, with dedicated caches residing in memory: table-level and column-level privileges, respectively, have their own dedicated caches. The GRANT_INFO works as a level 1 cache with this member updated to the current value of the global variable @c grant_version (@c static variable in sql_acl.cc). It is updated Whenever the GRANT_INFO is refreshed from the level 2 cache. The level 2 cache is the @c column_priv_hash structure (@c static variable in sql_acl.cc) @see grant_version */ uint version; /** @brief The set of privileges that the current user has fulfilled for a certain host, database, and object. @details This field is continually updated throughout the access checking process. In each step the "wanted privilege" is checked against the fulfilled privileges. When/if the intersection of these sets is empty, access is granted. The set is implemented as a bitmap, with the bits defined in sql_acl.h. */ privilege_t privilege; /** @brief the set of privileges that the current user needs to fulfil in order to carry out the requested operation. */ privilege_t want_privilege; /** Stores the requested access acl of top level tables list. Is used to check access rights to the underlying tables of a view. */ privilege_t orig_want_privilege; /** The grant state for internal tables. */ GRANT_INTERNAL_INFO m_internal; st_grant_info() :privilege(NO_ACL), want_privilege(NO_ACL), orig_want_privilege(NO_ACL) { } /* OR table and all column privileges */ privilege_t all_privilege(); } GRANT_INFO; enum tmp_table_type { NO_TMP_TABLE= 0, NON_TRANSACTIONAL_TMP_TABLE, TRANSACTIONAL_TMP_TABLE, INTERNAL_TMP_TABLE, SYSTEM_TMP_TABLE }; enum release_type { RELEASE_NORMAL, RELEASE_WAIT_FOR_DROP }; enum vcol_init_mode { VCOL_INIT_DEPENDENCY_FAILURE_IS_WARNING= 1, VCOL_INIT_DEPENDENCY_FAILURE_IS_ERROR= 2 /* There may be new flags here. e.g. to automatically remove sql_mode dependency: GENERATED ALWAYS AS (char_col) -> GENERATED ALWAYS AS (RTRIM(char_col)) */ }; enum enum_vcol_update_mode { VCOL_UPDATE_FOR_READ= 0, VCOL_UPDATE_FOR_WRITE, VCOL_UPDATE_FOR_DELETE, VCOL_UPDATE_INDEXED, VCOL_UPDATE_INDEXED_FOR_UPDATE, VCOL_UPDATE_FOR_REPLACE }; /* Field visibility enums */ enum __attribute__((packed)) field_visibility_t { VISIBLE= 0, INVISIBLE_USER, /* automatically added by the server. Can be queried explicitly in SELECT, otherwise invisible from anything" */ INVISIBLE_SYSTEM, INVISIBLE_FULL }; #define INVISIBLE_MAX_BITS 3 #define HA_HASH_FIELD_LENGTH 8 #define HA_HASH_KEY_LENGTH_WITHOUT_NULL 8 #define HA_HASH_KEY_LENGTH_WITH_NULL 9 int fields_in_hash_keyinfo(KEY *keyinfo); void setup_keyinfo_hash(KEY *key_info); void re_setup_keyinfo_hash(KEY *key_info); /** Category of table found in the table share. */ enum enum_table_category { /** Unknown value. */ TABLE_UNKNOWN_CATEGORY=0, /** Temporary table. The table is visible only in the session. Therefore, - FLUSH TABLES WITH READ LOCK - SET GLOBAL READ_ONLY = ON do not apply to this table. Note that LOCK TABLE t FOR READ/WRITE can be used on temporary tables. Temporary tables are not part of the table cache. */ TABLE_CATEGORY_TEMPORARY=1, /** User table. These tables do honor: - LOCK TABLE t FOR READ/WRITE - FLUSH TABLES WITH READ LOCK - SET GLOBAL READ_ONLY = ON User tables are cached in the table cache. */ TABLE_CATEGORY_USER=2, /** System table, maintained by the server. These tables do honor: - LOCK TABLE t FOR READ/WRITE - FLUSH TABLES WITH READ LOCK - SET GLOBAL READ_ONLY = ON Typically, writes to system tables are performed by the server implementation, not explicitly be a user. System tables are cached in the table cache. */ TABLE_CATEGORY_SYSTEM=3, /** Log tables. These tables are an interface provided by the system to inspect the system logs. These tables do *not* honor: - LOCK TABLE t FOR READ/WRITE - FLUSH TABLES WITH READ LOCK - SET GLOBAL READ_ONLY = ON as there is no point in locking explicitly a LOG table. An example of LOG tables are: - mysql.slow_log - mysql.general_log, which *are* updated even when there is either a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect. User queries do not write directly to these tables (there are exceptions for log tables). The server implementation perform writes. Log tables are cached in the table cache. */ TABLE_CATEGORY_LOG=4, /* Types below are read only tables, not affected by FLUSH TABLES or MDL locks. */ /** Information schema tables. These tables are an interface provided by the system to inspect the system metadata. These tables do *not* honor: - LOCK TABLE t FOR READ/WRITE - FLUSH TABLES WITH READ LOCK - SET GLOBAL READ_ONLY = ON as there is no point in locking explicitly an INFORMATION_SCHEMA table. Nothing is directly written to information schema tables. Note that this value is not used currently, since information schema tables are not shared, but implemented as session specific temporary tables. */ /* TODO: Fixing the performance issues of I_S will lead to I_S tables in the table cache, which should use this table type. */ TABLE_CATEGORY_INFORMATION=5, /** Performance schema tables. These tables are an interface provided by the system to inspect the system performance data. These tables do *not* honor: - LOCK TABLE t FOR READ/WRITE - FLUSH TABLES WITH READ LOCK - SET GLOBAL READ_ONLY = ON as there is no point in locking explicitly a PERFORMANCE_SCHEMA table. An example of PERFORMANCE_SCHEMA tables are: - performance_schema.* which *are* updated (but not using the handler interface) even when there is either a GLOBAL READ LOCK or a GLOBAL READ_ONLY in effect. User queries do not write directly to these tables (there are exceptions for SETUP_* tables). The server implementation perform writes. Performance tables are cached in the table cache. */ TABLE_CATEGORY_PERFORMANCE=6 }; typedef enum enum_table_category TABLE_CATEGORY; TABLE_CATEGORY get_table_category(const Lex_ident_db &db, const Lex_ident_table &name); typedef struct st_table_field_type { LEX_CSTRING name; LEX_CSTRING type; LEX_CSTRING cset; } TABLE_FIELD_TYPE; typedef struct st_table_field_def { uint count; const TABLE_FIELD_TYPE *field; uint primary_key_parts; const uint *primary_key_columns; } TABLE_FIELD_DEF; class Table_check_intact { protected: bool has_keys; virtual void report_error(uint code, const char *fmt, ...)= 0; public: Table_check_intact(bool keys= false) : has_keys(keys) {} virtual ~Table_check_intact() = default; /** Checks whether a table is intact. */ bool check(TABLE *table, const TABLE_FIELD_DEF *table_def); }; /* If the table isn't valid, report the error to the server log only. */ class Table_check_intact_log_error : public Table_check_intact { protected: void report_error(uint, const char *fmt, ...) override; public: Table_check_intact_log_error() : Table_check_intact(true) {} }; /** Class representing the fact that some thread waits for table share to be flushed. Is used to represent information about such waits in MDL deadlock detector. */ class Wait_for_flush : public MDL_wait_for_subgraph { MDL_context *m_ctx; TABLE_SHARE *m_share; uint m_deadlock_weight; public: Wait_for_flush(MDL_context *ctx_arg, TABLE_SHARE *share_arg, uint deadlock_weight_arg) : m_ctx(ctx_arg), m_share(share_arg), m_deadlock_weight(deadlock_weight_arg) {} MDL_context *get_ctx() const { return m_ctx; } bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor) override; uint get_deadlock_weight() const override; /** Pointers for participating in the list of waiters for table share. */ Wait_for_flush *next_in_share; Wait_for_flush **prev_in_share; }; typedef I_P_List > Wait_for_flush_list; enum open_frm_error { OPEN_FRM_OK = 0, OPEN_FRM_OPEN_ERROR, OPEN_FRM_READ_ERROR, OPEN_FRM_CORRUPTED, OPEN_FRM_DISCOVER, OPEN_FRM_ERROR_ALREADY_ISSUED, OPEN_FRM_NOT_A_VIEW, OPEN_FRM_NOT_A_TABLE, OPEN_FRM_NEEDS_REBUILD }; /** Control block to access table statistics loaded from persistent statistical tables */ #define TABLE_STAT_NO_STATS 0 #define TABLE_STAT_TABLE 1 #define TABLE_STAT_COLUMN 2 #define TABLE_STAT_INDEX 4 #define TABLE_STAT_HISTOGRAM 8 /* EITS statistics information for a table. This data is loaded from mysql.{table|index|column}_stats tables and then most of the time is owned by table's TABLE_SHARE object. Individual TABLE objects also have pointer to this object, and we do reference counting to know when to free it. See TABLE::update_engine_stats(), TABLE::free_engine_stats(), TABLE_SHARE::update_engine_stats(), TABLE_SHARE::destroy(). These implement a "shared pointer"-like functionality. When new statistics is loaded, we create new TABLE_STATISTICS_CB and make the TABLE_SHARE point to it. Some TABLE object may still be using older TABLE_STATISTICS_CB objects. Reference counting allows to free TABLE_STATISTICS_CB when it is no longer used. */ class TABLE_STATISTICS_CB { uint usage_count; // Instances of this stat public: TABLE_STATISTICS_CB(); ~TABLE_STATISTICS_CB(); MEM_ROOT mem_root; /* MEM_ROOT to allocate statistical data for the table */ Table_statistics *table_stats; /* Structure to access the statistical data */ ulong total_hist_size; /* Total size of all histograms */ uint stats_available; bool histograms_exists() const { return total_hist_size != 0; } bool unused() { return usage_count == 0; } /* Copy (latest) state from TABLE_SHARE to TABLE */ void update_stats_in_table(TABLE *table); friend struct TABLE; friend struct TABLE_SHARE; }; /** This structure is shared between different table objects. There is one instance of table share per one table in the database. */ struct TABLE_SHARE { TABLE_SHARE() = default; /* Remove gcc warning */ /** Category of this table. */ TABLE_CATEGORY table_category; /* hash of field names (contains pointers to elements of field array) */ HASH name_hash; /* hash of field names */ MEM_ROOT mem_root; TYPELIB keynames; /* Pointers to keynames */ TYPELIB fieldnames; /* Pointer to fieldnames */ TYPELIB *intervals; /* pointer to interval info */ mysql_mutex_t LOCK_ha_data; /* To protect access to ha_data */ mysql_mutex_t LOCK_share; /* To protect TABLE_SHARE */ mysql_mutex_t LOCK_statistics; /* To protect against concurrent load */ TDC_element *tdc; LEX_CUSTRING tabledef_version; engine_option_value *option_list; /* text options for table */ ha_table_option_struct *option_struct; /* structure with parsed options */ /* The following is copied to each TABLE on OPEN */ Field **field; Field **found_next_number_field; KEY *key_info; /* data of keys in database */ Virtual_column_info **check_constraints; uint *blob_field; /* Index to blobs in Field arrray*/ LEX_CUSTRING vcol_defs; /* definitions of generated columns */ /* EITS statistics data from the last time the table was opened or ANALYZE table was run. This is typically same as any related TABLE::stats_cb until ANALYZE table is run. This pointer is only to be de-referenced under LOCK_share as the pointer can change by another thread running ANALYZE TABLE. Without using a LOCK_share one can check if the statistics has been updated by checking if TABLE::stats_cb != TABLE_SHARE::stats_cb. */ TABLE_STATISTICS_CB *stats_cb; uchar *default_values; /* row with default values */ LEX_CSTRING comment; /* Comment about table */ CHARSET_INFO *table_charset; /* Default charset of string fields */ MY_BITMAP *check_set; /* Fields used by check constrant */ MY_BITMAP all_set; /* Key which is used for looking-up table in table cache and in the list of thread's temporary tables. Has the form of: "database_name\0table_name\0" + optional part for temporary tables. Note that all three 'table_cache_key', 'db' and 'table_name' members must be set (and be non-zero) for tables in table cache. They also should correspond to each other. To ensure this one can use set_table_cache() methods. */ LEX_CSTRING table_cache_key; LEX_CSTRING db; /* Pointer to db */ LEX_CSTRING table_name; /* Table name (for open) */ LEX_CSTRING path; /* Path to .frm file (from datadir) */ LEX_CSTRING normalized_path; /* unpack_filename(path) */ LEX_CSTRING connect_string; /* Set of keys in use, implemented as a Bitmap. Excludes keys disabled by ALTER TABLE ... DISABLE KEYS. */ key_map keys_in_use; /* The set of ignored indexes for a table. */ key_map ignored_indexes; key_map keys_for_keyread; ha_rows min_rows, max_rows; /* create information */ ulong avg_row_length; /* create information */ ulong mysql_version; /* 0 if .frm is created before 5.0 */ ulong reclength; /* Recordlength */ /* Stored record length. No generated-only virtual fields are included */ ulong stored_rec_length; plugin_ref db_plugin; /* storage engine plugin */ inline handlerton *db_type() const /* table_type for handler */ { return is_view ? view_pseudo_hton : db_plugin ? plugin_hton(db_plugin) : NULL; } enum row_type row_type; /* How rows are stored */ enum Table_type table_type; enum tmp_table_type tmp_table; /** Transactional or not. */ enum ha_choice transactional; /** Per-page checksums or not. */ enum ha_choice page_checksum; uint key_block_size; /* create key_block_size, if used */ uint stats_sample_pages; /* number of pages to sample during stats estimation, if used, otherwise 0. */ enum_stats_auto_recalc stats_auto_recalc; /* Automatic recalc of stats. */ uint null_bytes, last_null_bit_pos; /* Same as null_bytes, except that if there is only a 'delete-marker' in the record then this value is 0. */ uint null_bytes_for_compare; uint fields; /* number of fields */ /* number of stored fields, purely virtual not included */ uint stored_fields; uint virtual_fields; /* number of purely virtual fields */ /* number of purely virtual not stored blobs */ uint virtual_not_stored_blob_fields; uint null_fields; /* number of null fields */ uint blob_fields; /* number of blob fields */ uint varchar_fields; /* number of varchar fields */ uint default_fields; /* number of default fields */ uint visible_fields; /* number of visible fields */ uint default_expressions; uint table_check_constraints, field_check_constraints; uint rec_buff_length; /* Size of table->record[] buffer */ uint keys, key_parts; uint ext_key_parts; /* Total number of key parts in extended keys */ uint max_key_length, max_unique_length; uint uniques; /* Number of UNIQUE index */ uint db_create_options; /* Create options from database */ uint db_options_in_use; /* Options in use */ uint db_record_offset; /* if HA_REC_IN_SEQ */ uint rowid_field_offset; /* Field_nr +1 to rowid field */ /* Primary key index number, used in TABLE::key_info[] */ uint primary_key; uint next_number_index; /* autoincrement key number */ uint next_number_key_offset; /* autoinc keypart offset in a key */ uint next_number_keypart; /* autoinc keypart number in a key */ enum open_frm_error error; /* error from open_table_def() */ uint open_errno; /* error from open_table_def() */ uint column_bitmap_size; uchar frm_version; enum enum_v_keys { NOT_INITIALIZED=0, NO_V_KEYS, V_KEYS }; enum_v_keys check_set_initialized; bool use_ext_keys; /* Extended keys can be used */ bool null_field_first; bool system; /* Set if system table (one record) */ bool not_usable_by_query_cache; bool online_backup; /* Set if on-line backup supported */ /* This is used by log tables, for tables that have their own internal binary logging or for tables that doesn't support statement or row logging */ bool no_replicate; bool crashed; bool is_view; bool can_cmp_whole_record; /* This is set for temporary tables where CREATE was binary logged */ bool table_creation_was_logged; bool non_determinstic_insert; bool has_update_default_function; bool can_do_row_logging; /* 1 if table supports RBR */ bool long_unique_table; /* 1 if frm version cannot be updated as part of upgrade */ bool keep_original_mysql_version; ulonglong table_map_id; /* for row-based replication */ /* Things that are incompatible between the stored version and the current version. This is a set of HA_CREATE... bits that can be used to modify create_info->used_fields for ALTER TABLE. */ ulong incompatible_version; /** For shares representing views File_parser object with view definition read from .FRM file. */ const File_parser *view_def; /* For sequence tables, the current sequence state */ SEQUENCE *sequence; #ifdef WITH_PARTITION_STORAGE_ENGINE /* filled in when reading from frm */ bool auto_partitioned; char *partition_info_str; uint partition_info_str_len; uint partition_info_buffer_size; plugin_ref default_part_plugin; #endif /** System versioning and application-time periods support. */ struct period_info_t { field_index_t start_fieldno; field_index_t end_fieldno; Lex_ident name; Lex_ident constr_name; uint unique_keys; Field *start_field(TABLE_SHARE *s) const { return s->field[start_fieldno]; } Field *end_field(TABLE_SHARE *s) const { return s->field[end_fieldno]; } }; vers_kind_t versioned; period_info_t vers; period_info_t period; bool init_period_from_extra2(period_info_t *period, const uchar *data, const uchar *end); Field *vers_start_field() { DBUG_ASSERT(versioned); return field[vers.start_fieldno]; } Field *vers_end_field() { DBUG_ASSERT(versioned); return field[vers.end_fieldno]; } Field *period_start_field() const { DBUG_ASSERT(period.name); return field[period.start_fieldno]; } Field *period_end_field() const { DBUG_ASSERT(period.name); return field[period.end_fieldno]; } /** Cache the checked structure of this table. The pointer data is used to describe the structure that a instance of the table must have. Each element of the array specifies a field that must exist on the table. The pointer is cached in order to perform the check only once -- when the table is loaded from the disk. */ const TABLE_FIELD_DEF *table_field_def_cache; /** Main handler's share */ Handler_share *ha_share; /** Instrumentation for this table share. */ PSI_table_share *m_psi; inline void reset() { bzero((void*)this, sizeof(*this)); } /* Set share's table cache key and update its db and table name appropriately. SYNOPSIS set_table_cache_key() key_buff Buffer with already built table cache key to be referenced from share. key_length Key length. NOTES Since 'key_buff' buffer will be referenced from share it should has same life-time as share itself. This method automatically ensures that TABLE_SHARE::table_name/db have appropriate values by using table cache key as their source. */ void set_table_cache_key(char *key_buff, uint key_length) { table_cache_key.str= key_buff; table_cache_key.length= key_length; /* Let us use the fact that the key is "db/0/table_name/0" + optional part for temporary tables. */ db.str= table_cache_key.str; db.length= strlen(db.str); table_name.str= db.str + db.length + 1; table_name.length= strlen(table_name.str); } /* Set share's table cache key and update its db and table name appropriately. SYNOPSIS set_table_cache_key() key_buff Buffer to be used as storage for table cache key (should be at least key_length bytes). key Value for table cache key. key_length Key length. NOTE Since 'key_buff' buffer will be used as storage for table cache key it should has same life-time as share itself. */ void set_table_cache_key(char *key_buff, const char *key, uint key_length) { memcpy(key_buff, key, key_length); set_table_cache_key(key_buff, key_length); } inline bool require_write_privileges() { return (table_category == TABLE_CATEGORY_LOG); } inline ulonglong get_table_def_version() { return table_map_id; } /** Convert unrelated members of TABLE_SHARE to one enum representing its type. @todo perhaps we need to have a member instead of a function. */ enum enum_table_ref_type get_table_ref_type() const { if (is_view) return TABLE_REF_VIEW; switch (tmp_table) { case NO_TMP_TABLE: return TABLE_REF_BASE_TABLE; case SYSTEM_TMP_TABLE: return TABLE_REF_I_S_TABLE; default: return TABLE_REF_TMP_TABLE; } } /** Return a table metadata version. * for base tables and views, we return table_map_id. It is assigned from a global counter incremented for each new table loaded into the table definition cache (TDC). * for temporary tables it's table_map_id again. But for temporary tables table_map_id is assigned from thd->query_id. The latter is assigned from a thread local counter incremented for every new SQL statement. Since temporary tables are thread-local, each temporary table gets a unique id. * for everything else (e.g. information schema tables), the version id is zero. This choice of version id is a large compromise to have a working prepared statement validation in 5.1. In future version ids will be persistent, as described in WL#4180. Let's try to explain why and how this limited solution allows to validate prepared statements. Firstly, sets (in mathematical sense) of version numbers never intersect for different table types. Therefore, version id of a temporary table is never compared with a version id of a view, and vice versa. Secondly, for base tables and views, we know that each DDL flushes the respective share from the TDC. This ensures that whenever a table is altered or dropped and recreated, it gets a new version id. Unfortunately, since elements of the TDC are also flushed on LRU basis, this choice of version ids leads to false positives. E.g. when the TDC size is too small, we may have a SELECT * FROM INFORMATION_SCHEMA.TABLES flush all its elements, which in turn will lead to a validation error and a subsequent reprepare of all prepared statements. This is considered acceptable, since as long as prepared statements are automatically reprepared, spurious invalidation is only a performance hit. Besides, no better simple solution exists. For temporary tables, using thd->query_id ensures that if a temporary table was altered or recreated, a new version id is assigned. This suits validation needs very well and will perhaps never change. Metadata of information schema tables never changes. Thus we can safely assume 0 for a good enough version id. Finally, by taking into account table type, we always track that a change has taken place when a view is replaced with a base table, a base table is replaced with a temporary table and so on. @sa TABLE_LIST::is_the_same_definition() */ ulonglong get_table_ref_version() const { return (tmp_table == SYSTEM_TMP_TABLE) ? 0 : table_map_id; } bool is_optimizer_tmp_table() { return tmp_table == INTERNAL_TMP_TABLE && !db.length && table_name.length; } bool visit_subgraph(Wait_for_flush *waiting_ticket, MDL_wait_for_graph_visitor *gvisitor); bool wait_for_old_version(THD *thd, struct timespec *abstime, uint deadlock_weight); /** Release resources and free memory occupied by the table share. */ void destroy(); void set_use_ext_keys_flag(bool fl) { use_ext_keys= fl; } uint actual_n_key_parts(THD *thd); LEX_CUSTRING *frm_image; ///< only during CREATE TABLE (@sa ha_create_table) /* populates TABLE_SHARE from the table description in the binary frm image. if 'write' is true, this frm image is also written into a corresponding frm file, that serves as a persistent metadata cache to avoid discovering the table over and over again */ int init_from_binary_frm_image(THD *thd, bool write, const uchar *frm_image, size_t frm_length, const uchar *par_image=0, size_t par_length=0); /* populates TABLE_SHARE from the table description, specified as the complete CREATE TABLE sql statement. if 'write' is true, this frm image is also written into a corresponding frm file, that serves as a persistent metadata cache to avoid discovering the table over and over again */ int init_from_sql_statement_string(THD *thd, bool write, const char *sql, size_t sql_length); /* writes the frm image to an frm file, corresponding to this table */ bool write_frm_image(const uchar *frm_image, size_t frm_length); bool write_par_image(const uchar *par_image, size_t par_length); /* Only used by S3 */ bool write_frm_image(void) { return frm_image ? write_frm_image(frm_image->str, frm_image->length) : 0; } /* returns an frm image for this table. the memory is allocated and must be freed later */ bool read_frm_image(const uchar **frm_image, size_t *frm_length); /* frees the memory allocated in read_frm_image */ void free_frm_image(const uchar *frm); void set_overlapped_keys(); void set_ignored_indexes(); key_map usable_indexes(THD *thd); bool old_long_hash_function() const { return mysql_version < 100428 || (mysql_version >= 100500 && mysql_version < 100519) || (mysql_version >= 100600 && mysql_version < 100612) || (mysql_version >= 100700 && mysql_version < 100708) || (mysql_version >= 100800 && mysql_version < 100807) || (mysql_version >= 100900 && mysql_version < 100905) || (mysql_version >= 101000 && mysql_version < 101003) || (mysql_version >= 101100 && mysql_version < 101102); } Item_func_hash *make_long_hash_func(THD *thd, MEM_ROOT *mem_root, List *field_list) const; void update_engine_independent_stats(TABLE_STATISTICS_CB *stat); bool histograms_exists(); }; /* not NULL, but cannot be dereferenced */ #define UNUSABLE_TABLE_SHARE ((TABLE_SHARE*)1) /** Class is used as a BLOB field value storage for intermediate GROUP_CONCAT results. Used only for GROUP_CONCAT with DISTINCT or ORDER BY options. */ class Blob_mem_storage: public Sql_alloc { private: MEM_ROOT storage; /** Sign that some values were cut during saving into the storage. */ bool truncated_value; public: Blob_mem_storage() :truncated_value(false) { init_alloc_root(key_memory_blob_mem_storage, &storage, MAX_FIELD_VARCHARLENGTH, 0, MYF(0)); } ~ Blob_mem_storage() { free_root(&storage, MYF(0)); } void reset() { free_root(&storage, MYF(MY_MARK_BLOCKS_FREE)); truncated_value= false; } /** Fuction creates duplicate of 'from' string in 'storage' MEM_ROOT. @param from string to copy @param length string length @retval Pointer to the copied string. @retval 0 if an error occurred. */ char *store(const char *from, size_t length) { return (char*) memdup_root(&storage, from, length); } void set_truncated_value(bool is_truncated_value) { truncated_value= is_truncated_value; } bool is_truncated_value() { return truncated_value; } }; /* Information for one open table */ enum index_hint_type { INDEX_HINT_IGNORE, INDEX_HINT_USE, INDEX_HINT_FORCE }; struct st_cond_statistic; #define CHECK_ROW_FOR_NULLS_TO_REJECT (1 << 0) #define REJECT_ROW_DUE_TO_NULL_FIELDS (1 << 1) class SplM_opt_info; struct vers_select_conds_t; struct TABLE { TABLE() = default; /* Remove gcc warning */ TABLE_SHARE *s; handler *file; TABLE *next, *prev; private: /** Links for the list of all TABLE objects for this share. Declared as private to avoid direct manipulation with those objects. One should use methods of I_P_List template instead. */ TABLE *share_all_next, **share_all_prev; TABLE *global_free_next, **global_free_prev; friend struct All_share_tables; friend struct Table_cache_instance; public: uint32 instance; /** Table cache instance this TABLE is belonging to */ THD *in_use; /* Which thread uses this */ uchar *record[3]; /* Pointer to records */ uchar *write_row_record; /* Used as optimisation in THD::write_row */ uchar *insert_values; /* used by INSERT ... UPDATE */ /* Map of keys that can be used to retrieve all data from this table needed by the query without reading the row. */ key_map covering_keys, intersect_keys; /* A set of keys that can be used in the query that references this table. All indexes disabled on the table's TABLE_SHARE (see TABLE::s) will be subtracted from this set upon instantiation. Thus for any TABLE t it holds that t.keys_in_use_for_query is a subset of t.s.keys_in_use. Generally we must not introduce any new keys here (see setup_tables). The set is implemented as a bitmap. */ key_map keys_in_use_for_query; /* Map of keys that can be used to calculate GROUP BY without sorting */ key_map keys_in_use_for_group_by; /* Map of keys that can be used to calculate ORDER BY without sorting */ key_map keys_in_use_for_order_by; /* Map of keys dependent on some constraint */ key_map constraint_dependent_keys; KEY *key_info; /* data of keys in database */ Field **field; /* Pointer to fields */ Field **vfield; /* Pointer to virtual fields*/ Field **default_field; /* Fields with non-constant DEFAULT */ Field *next_number_field; /* Set if next_number is activated */ Field *found_next_number_field; /* Set on open */ Virtual_column_info **check_constraints; /* Table's triggers, 0 if there are no of them */ Table_triggers_list *triggers; TABLE_LIST *pos_in_table_list;/* Element referring to this table */ /* Position in thd->locked_table_list under LOCK TABLES */ TABLE_LIST *pos_in_locked_tables; /* Tables used in DEFAULT and CHECK CONSTRAINT (normally sequence tables) */ TABLE_LIST *internal_tables; /* Not-null for temporary tables only. Non-null values means this table is used to compute GROUP BY, it has a unique of GROUP BY columns. (set by create_tmp_table) */ ORDER *group; String alias; /* alias or table name */ uchar *null_flags; MY_BITMAP def_read_set, def_write_set, tmp_set; MY_BITMAP def_rpl_write_set; MY_BITMAP eq_join_set; /* used to mark equi-joined fields */ MY_BITMAP cond_set; /* used to mark fields from sargable conditions*/ /* Active column sets */ MY_BITMAP *read_set, *write_set, *rpl_write_set; /* On INSERT: fields that the user specified a value for */ MY_BITMAP has_value_set; /* The ID of the query that opened and is using this table. Has different meanings depending on the table type. Temporary tables: table->query_id is set to thd->query_id for the duration of a statement and is reset to 0 once it is closed by the same statement. A non-zero table->query_id means that a statement is using the table even if it's not the current statement (table is in use by some outer statement). Non-temporary tables: Under pre-locked or LOCK TABLES mode: query_id is set to thd->query_id for the duration of a statement and is reset to 0 once it is closed by the same statement. A non-zero query_id is used to control which tables in the list of pre-opened and locked tables are actually being used. */ query_id_t query_id; /* This structure is used for statistical data on the table that is collected by the function collect_statistics_for_table */ Table_statistics *collected_stats; /* The estimate of the number of records in the table used by optimizer */ ha_rows used_stat_records; key_map opt_range_keys; /* The following structure is filled for each key that has opt_range_keys.is_set(key) == TRUE */ struct OPT_RANGE { uint key_parts; uint ranges; ha_rows rows; double cost; /* If there is a range access by i-th index then the cost of index only access for it is stored in index_only_costs[i] */ double index_only_cost; } *opt_range; /* Bitmaps of key parts that =const for the duration of join execution. If we're in a subquery, then the constant may be different across subquery re-executions. */ key_part_map *const_key_parts; /* Estimate of number of records that satisfy SARGable part of the table condition, or table->file->records if no SARGable condition could be constructed. This value is used by join optimizer as an estimate of number of records that will pass the table condition (condition that depends on fields of this table and constants) */ ha_rows opt_range_condition_rows; double cond_selectivity; List *cond_selectivity_sampling_explain; table_map map; /* ID bit of table (1,2,4,8,16...) */ uint lock_position; /* Position in MYSQL_LOCK.table */ uint lock_data_start; /* Start pos. in MYSQL_LOCK.locks */ uint lock_count; /* Number of locks */ uint tablenr,used_fields; uint temp_pool_slot; /* Used by intern temp tables */ uint status; /* What's in record[0] */ uint db_stat; /* mode of file as in handler.h */ /* number of select if it is derived table */ uint derived_select_number; /* Possible values: - 0 by default - JOIN_TYPE_{LEFT|RIGHT} if the table is inner w.r.t an outer join operation - 1 if the SELECT has mixed_implicit_grouping=1. example: select max(col1), col2 from t1. In this case, the query produces one row with all columns having NULL values. Interpetation: If maybe_null!=0, all fields of the table are considered NULLable (and have NULL values when null_row=true) */ uint maybe_null; int current_lock; /* Type of lock on table */ bool copy_blobs; /* copy_blobs when storing */ /* Set if next_number_field is in the UPDATE fields of INSERT ... ON DUPLICATE KEY UPDATE. */ bool next_number_field_updated; /* If true, the current table row is considered to have all columns set to NULL, including columns declared as "not null" (see maybe_null). */ bool null_row; /* No rows that contain null values can be placed into this table. Currently this flag can be set to true only for a temporary table that used to store the result of materialization of a subquery. */ bool no_rows_with_nulls; /* This field can contain two bit flags: CHECK_ROW_FOR_NULLS_TO_REJECT REJECT_ROW_DUE_TO_NULL_FIELDS The first flag is set for the dynamic contexts where it is prohibited to write any null into the table. The second flag is set only if the first flag is set on. The informs the outer scope that there was an attept to write null into a field of the table in the context where it is prohibited. This flag should be set off as soon as the first flag is set on. Currently these flags are used only the tables tno_rows_with_nulls set to true. */ uint8 null_catch_flags; /* TODO: Each of the following flags take up 8 bits. They can just as easily be put into one single unsigned long and instead of taking up 18 bytes, it would take up 4. */ bool force_index; /** Flag set when the statement contains FORCE INDEX FOR ORDER BY See TABLE_LIST::process_index_hints(). */ bool force_index_order; /** Flag set when the statement contains FORCE INDEX FOR GROUP BY See TABLE_LIST::process_index_hints(). */ bool force_index_group; /* TRUE<=> this table was created with create_tmp_table(... distinct=TRUE..) call */ bool distinct; bool const_table,no_rows, used_for_duplicate_elimination; /** Forces DYNAMIC Aria row format for internal temporary tables. */ bool keep_row_order; bool no_keyread; /** If set, indicate that the table is not replicated by the server. */ bool locked_by_logger; bool locked_by_name; bool fulltext_searched; bool no_cache; /* To signal that the table is associated with a HANDLER statement */ bool open_by_handler; /* To indicate that a non-null value of the auto_increment field was provided by the user or retrieved from the current record. Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode. */ bool auto_increment_field_not_null; /* NOTE: alias_name_used is only a hint! It works only in need_correct_ident() condition. On other cases it is FALSE even if table_name is alias. E.g. in update t1 as x set a = 1 */ bool alias_name_used; /* true if table_name is alias */ bool get_fields_in_item_tree; /* Signal to fix_field */ List vcol_refix_list; private: bool m_needs_reopen; bool created; /* For tmp tables. TRUE <=> tmp table was actually created.*/ public: #ifdef HAVE_REPLICATION /* used in RBR Triggers */ bool master_had_triggers; #endif REGINFO reginfo; /* field connections */ MEM_ROOT mem_root; /* this is for temporary tables created inside Item_func_group_concat */ union { bool group_concat; /* used during create_tmp_table() */ Blob_mem_storage *blob_storage; /* used after create_tmp_table() */ }; GRANT_INFO grant; /* The arena which the items for expressions from the table definition are associated with. Currently only the items of the expressions for virtual columns are associated with this arena. TODO: To attach the partitioning expressions to this arena. */ Query_arena *expr_arena; #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *part_info; /* Partition related information */ /* If true, all partitions have been pruned away */ bool all_partitions_pruned_away; #endif uint max_keys; /* Size of allocated key_info array. */ bool stats_is_read; /* Persistent statistics is read for the table */ bool histograms_are_read; MDL_ticket *mdl_ticket; /* This is used only for potentially splittable materialized tables and it points to the info used by the optimizer to apply splitting optimization */ SplM_opt_info *spl_opt_info; key_map keys_usable_for_splitting; /* Conjunction of the predicates of the form IS NOT NULL(f) where f refers to a column of this TABLE such that they can be inferred from the condition of the WHERE clause or from some ON expression of the processed select and can be useful for range optimizer. */ Item *notnull_cond; TABLE_STATISTICS_CB *stats_cb; inline void reset() { bzero((void*)this, sizeof(*this)); } void init(THD *thd, TABLE_LIST *tl); bool fill_item_list(List *item_list) const; void reset_item_list(List *item_list, uint skip) const; void clear_column_bitmaps(void); void prepare_for_position(void); MY_BITMAP *prepare_for_keyread(uint index, MY_BITMAP *map); MY_BITMAP *prepare_for_keyread(uint index) { return prepare_for_keyread(index, &tmp_set); } void mark_index_columns(uint index, MY_BITMAP *bitmap); void mark_index_columns_no_reset(uint index, MY_BITMAP *bitmap); void mark_index_columns_for_read(uint index); void restore_column_maps_after_keyread(MY_BITMAP *backup); void mark_auto_increment_column(bool insert_fl); void mark_columns_needed_for_update(void); void mark_columns_needed_for_delete(void); void mark_columns_needed_for_insert(void); void mark_columns_per_binlog_row_image(void); inline bool mark_column_with_deps(Field *field); inline bool mark_virtual_column_with_deps(Field *field); inline void mark_virtual_column_deps(Field *field); bool mark_virtual_columns_for_write(bool insert_fl); bool check_virtual_columns_marked_for_read(); bool check_virtual_columns_marked_for_write(); void mark_default_fields_for_write(bool insert_fl); void mark_columns_used_by_virtual_fields(void); void mark_check_constraint_columns_for_read(void); int verify_constraints(bool ignore_failure); void free_engine_stats(); void update_engine_independent_stats(); inline void column_bitmaps_set(MY_BITMAP *read_set_arg) { read_set= read_set_arg; if (file) file->column_bitmaps_signal(); } inline void column_bitmaps_set(MY_BITMAP *read_set_arg, MY_BITMAP *write_set_arg) { read_set= read_set_arg; write_set= write_set_arg; if (file) file->column_bitmaps_signal(); } inline void column_bitmaps_set_no_signal(MY_BITMAP *read_set_arg, MY_BITMAP *write_set_arg) { read_set= read_set_arg; write_set= write_set_arg; } inline void use_all_columns() { column_bitmaps_set(&s->all_set, &s->all_set); } inline void use_all_stored_columns(); inline void default_column_bitmaps() { read_set= &def_read_set; write_set= &def_write_set; rpl_write_set= 0; } /** Should this instance of the table be reopened? */ inline bool needs_reopen() { return !db_stat || m_needs_reopen; } /* Mark that all current connection instances of the table should be reopen at end of statement */ void mark_table_for_reopen(); /* Should only be called from Locked_tables_list::mark_table_for_reopen() */ void internal_set_needs_reopen(bool value) { m_needs_reopen= value; } bool init_expr_arena(MEM_ROOT *mem_root); bool alloc_keys(uint key_count); bool check_tmp_key(uint key, uint key_parts, uint (*next_field_no) (uchar *), uchar *arg); bool add_tmp_key(uint key, uint key_parts, uint (*next_field_no) (uchar *), uchar *arg, bool unique); void create_key_part_by_field(KEY_PART_INFO *key_part_info, Field *field, uint fieldnr); void use_index(int key_to_save); void set_table_map(table_map map_arg, uint tablenr_arg) { map= map_arg; tablenr= tablenr_arg; } /// Return true if table is instantiated, and false otherwise. bool is_created() const { DBUG_ASSERT(!created || file != 0); return created; } /** Set the table as "created", and enable flags in storage engine that could not be enabled without an instantiated table. */ void set_created() { if (created) return; if (file->keyread_enabled()) file->extra(HA_EXTRA_KEYREAD); created= true; } void reset_created() { created= 0; } /* Returns TRUE if the table is filled at execution phase (and so, the optimizer must not do anything that depends on the contents of the table, like range analysis or constant table detection) */ bool is_filled_at_execution(); bool update_const_key_parts(COND *conds); void update_keypart_vcol_info(); inline void initialize_opt_range_structures(); my_ptrdiff_t default_values_offset() const { return (my_ptrdiff_t) (s->default_values - record[0]); } void move_fields(Field **ptr, const uchar *to, const uchar *from); void remember_blob_values(String *blob_storage); void restore_blob_values(String *blob_storage); uint actual_n_key_parts(KEY *keyinfo); ulong actual_key_flags(KEY *keyinfo); int update_virtual_field(Field *vf, bool ignore_warnings); int update_virtual_fields(handler *h, enum_vcol_update_mode update_mode); int update_default_fields(bool ignore_errors); void evaluate_update_default_function(); void reset_default_fields(); inline ha_rows stat_records() { return used_stat_records; } void prepare_triggers_for_insert_stmt_or_event(); bool prepare_triggers_for_delete_stmt_or_event(); bool prepare_triggers_for_update_stmt_or_event(); Field **field_to_fill(); bool validate_default_values_of_unset_fields(THD *thd) const; bool insert_all_rows_into_tmp_table(THD *thd, TABLE *tmp_table, TMP_TABLE_PARAM *tmp_table_param, bool with_cleanup); bool check_sequence_privileges(THD *thd); bool vcol_fix_expr(THD *thd); bool vcol_cleanup_expr(THD *thd); Field *find_field_by_name(LEX_CSTRING *str) const; bool export_structure(THD *thd, class Row_definition_list *defs); bool is_splittable() { return spl_opt_info != NULL; } void set_spl_opt_info(SplM_opt_info *spl_info); void deny_splitting(); double get_materialization_cost(); // Now used only if is_splittable()==true void add_splitting_info_for_key_field(struct KEY_FIELD *key_field); key_map with_impossible_ranges; /* Number of cost info elements for possible range filters */ uint range_rowid_filter_cost_info_elems; /* Pointer to the array of cost info elements for range filters */ Range_rowid_filter_cost_info *range_rowid_filter_cost_info; /* The array of pointers to cost info elements for range filters */ Range_rowid_filter_cost_info **range_rowid_filter_cost_info_ptr; void init_cost_info_for_usable_range_rowid_filters(THD *thd); void prune_range_rowid_filters(); void trace_range_rowid_filters(THD *thd) const; Range_rowid_filter_cost_info * best_range_rowid_filter_for_partial_join(uint access_key_no, double records, double access_cost_factor); /** System Versioning support */ bool vers_write; bool versioned() const { return s->versioned; } bool versioned(vers_kind_t type) const { DBUG_ASSERT(type); return s->versioned == type; } bool versioned_write() const { DBUG_ASSERT(versioned() || !vers_write); return versioned() ? vers_write : false; } bool versioned_write(vers_kind_t type) const { DBUG_ASSERT(type); DBUG_ASSERT(versioned() || !vers_write); return versioned(type) ? vers_write : false; } Field *vers_start_field() const { DBUG_ASSERT(s->versioned); return field[s->vers.start_fieldno]; } Field *vers_end_field() const { DBUG_ASSERT(s->versioned); return field[s->vers.end_fieldno]; } Field *period_start_field() const { DBUG_ASSERT(s->period.name); return field[s->period.start_fieldno]; } Field *period_end_field() const { DBUG_ASSERT(s->period.name); return field[s->period.end_fieldno]; } ulonglong vers_start_id() const; ulonglong vers_end_id() const; int update_generated_fields(); void period_prepare_autoinc(); int period_make_insert(Item *src, Field *dst); int insert_portion_of_time(THD *thd, const vers_select_conds_t &period_conds, ha_rows *rows_inserted); bool vers_check_update(List &items); static bool check_period_overlaps(const KEY &key, const uchar *lhs, const uchar *rhs); int delete_row(); /* Used in majority of DML (called from fill_record()) */ void vers_update_fields(); /* Used in DELETE, DUP REPLACE and insert history row */ void vers_update_end(); void find_constraint_correlated_indexes(); /** Number of additional fields used in versioned tables */ #define VERSIONING_FIELDS 2 }; /** Helper class which specifies which members of TABLE are used for participation in the list of used/unused TABLE objects for the share. */ struct TABLE_share { static inline TABLE **next_ptr(TABLE *l) { return &l->next; } static inline TABLE ***prev_ptr(TABLE *l) { return (TABLE ***) &l->prev; } }; struct All_share_tables { static inline TABLE **next_ptr(TABLE *l) { return &l->share_all_next; } static inline TABLE ***prev_ptr(TABLE *l) { return &l->share_all_prev; } }; typedef I_P_List All_share_tables_list; enum enum_schema_table_state { NOT_PROCESSED= 0, PROCESSED_BY_CREATE_SORT_INDEX, PROCESSED_BY_JOIN_EXEC }; enum enum_fk_option { FK_OPTION_UNDEF, FK_OPTION_RESTRICT, FK_OPTION_NO_ACTION, FK_OPTION_CASCADE, FK_OPTION_SET_NULL, FK_OPTION_SET_DEFAULT }; typedef struct st_foreign_key_info { LEX_CSTRING *foreign_id; LEX_CSTRING *foreign_db; LEX_CSTRING *foreign_table; LEX_CSTRING *referenced_db; LEX_CSTRING *referenced_table; enum_fk_option update_method; enum_fk_option delete_method; LEX_CSTRING *referenced_key_name; List foreign_fields; List referenced_fields; private: unsigned char *fields_nullable= nullptr; /** Get the number of fields exist in foreign key relationship */ unsigned get_n_fields() const noexcept { unsigned n_fields= foreign_fields.elements; if (n_fields == 0) n_fields= referenced_fields.elements; return n_fields; } /** Assign nullable field for referenced and foreign fields based on number of fields. This nullable fields should be allocated by engine for passing the foreign key information @param thd thread to allocate the memory @param num_fields number of fields */ void assign_nullable(THD *thd, unsigned num_fields) noexcept { fields_nullable= (unsigned char *)thd_calloc(thd, my_bits_in_bytes(2 * num_fields)); } public: /** Set nullable bit for the field in the given field @param referenced set null bit for referenced column @param field field number @param n_fields number of fields */ void set_nullable(THD *thd, bool referenced, unsigned field, unsigned n_fields) noexcept { if (!fields_nullable) assign_nullable(thd, n_fields); DBUG_ASSERT(fields_nullable); DBUG_ASSERT(field < n_fields); size_t bit= size_t{field} + referenced * n_fields; #if defined __GNUC__ && !defined __clang__ && __GNUC__ < 6 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wconversion" #endif fields_nullable[bit / 8]|= static_cast(1 << (bit % 8)); #if defined __GNUC__ && !defined __clang__ && __GNUC__ < 6 # pragma GCC diagnostic pop #endif } /** Check whether the given field_no in foreign key field or referenced key field @param referenced check referenced field nullable value @param field field number @return true if the field is nullable or false if it is not */ bool is_nullable(bool referenced, unsigned field) const noexcept { if (!fields_nullable) return false; unsigned n_field= get_n_fields(); DBUG_ASSERT(field < n_field); size_t bit= size_t{field} + referenced * n_field; return fields_nullable[bit / 8] & (1U << (bit % 8)); } } FOREIGN_KEY_INFO; LEX_CSTRING *fk_option_name(enum_fk_option opt); static inline bool fk_modifies_child(enum_fk_option opt) { return opt >= FK_OPTION_CASCADE; } class IS_table_read_plan; /* Types of derived tables. The ending part is a bitmap of phases that are applicable to a derived table of the type. */ #define DTYPE_ALGORITHM_UNDEFINED 0U #define DTYPE_VIEW 1U #define DTYPE_TABLE 2U #define DTYPE_MERGE 4U #define DTYPE_MATERIALIZE 8U #define DTYPE_MULTITABLE 16U #define DTYPE_MASK (DTYPE_VIEW|DTYPE_TABLE|DTYPE_MULTITABLE) /* Phases of derived tables/views handling, see sql_derived.cc Values are used as parts of a bitmap attached to derived table types. */ #define DT_INIT 1U #define DT_PREPARE 2U #define DT_OPTIMIZE 4U #define DT_MERGE 8U #define DT_MERGE_FOR_INSERT 16U #define DT_CREATE 32U #define DT_FILL 64U #define DT_REINIT 128U #define DT_PHASES 8U /* Phases that are applicable to all derived tables. */ #define DT_COMMON (DT_INIT + DT_PREPARE + DT_REINIT + DT_OPTIMIZE) /* Phases that are applicable only to materialized derived tables. */ #define DT_MATERIALIZE (DT_CREATE + DT_FILL) #define DT_PHASES_MERGE (DT_COMMON | DT_MERGE | DT_MERGE_FOR_INSERT) #define DT_PHASES_MATERIALIZE (DT_COMMON | DT_MATERIALIZE) #define VIEW_ALGORITHM_UNDEFINED 0 /* Special value for ALTER VIEW: inherit original algorithm. */ #define VIEW_ALGORITHM_INHERIT DTYPE_VIEW #define VIEW_ALGORITHM_MERGE (DTYPE_VIEW | DTYPE_MERGE) #define VIEW_ALGORITHM_TMPTABLE (DTYPE_VIEW | DTYPE_MATERIALIZE) /* View algorithm values as stored in the FRM. Values differ from in-memory representation for backward compatibility. */ #define VIEW_ALGORITHM_UNDEFINED_FRM 0U #define VIEW_ALGORITHM_MERGE_FRM 1U #define VIEW_ALGORITHM_TMPTABLE_FRM 2U #define JOIN_TYPE_LEFT 1U #define JOIN_TYPE_RIGHT 2U #define JOIN_TYPE_OUTER 4U /* Marker that this is an outer join */ /* view WITH CHECK OPTION parameter options */ #define VIEW_CHECK_NONE 0 #define VIEW_CHECK_LOCAL 1 #define VIEW_CHECK_CASCADED 2 /* result of view WITH CHECK OPTION parameter check */ #define VIEW_CHECK_OK 0 #define VIEW_CHECK_ERROR 1 #define VIEW_CHECK_SKIP 2 /** The threshold size a blob field buffer before it is freed */ #define MAX_TDC_BLOB_SIZE 65536 /** number of bytes used by field positional indexes in frm */ constexpr uint frm_fieldno_size= 2; /** number of bytes used by key position number in frm */ constexpr uint frm_keyno_size= 2; static inline field_index_t read_frm_fieldno(const uchar *data) { return uint2korr(data); } static inline void store_frm_fieldno(uchar *data, field_index_t fieldno) { int2store(data, fieldno); } static inline uint16 read_frm_keyno(const uchar *data) { return uint2korr(data); } static inline void store_frm_keyno(uchar *data, uint16 keyno) { int2store(data, keyno); } static inline size_t extra2_str_size(size_t len) { return (len > 255 ? 3 : 1) + len; } class select_unit; class TMP_TABLE_PARAM; Item *create_view_field(THD *thd, TABLE_LIST *view, Item **field_ref, LEX_CSTRING *name); struct Field_translator { Item *item; LEX_CSTRING name; }; /* Column reference of a NATURAL/USING join. Since column references in joins can be both from views and stored tables, may point to either a Field (for tables), or a Field_translator (for views). */ class Natural_join_column: public Sql_alloc { public: Field_translator *view_field; /* Column reference of merge view. */ Item_field *table_field; /* Column reference of table or temp view. */ TABLE_LIST *table_ref; /* Original base table/view reference. */ /* True if a common join column of two NATURAL/USING join operands. Notice that when we have a hierarchy of nested NATURAL/USING joins, a column can be common at some level of nesting but it may not be common at higher levels of nesting. Thus this flag may change depending on at which level we are looking at some column. */ bool is_common; public: Natural_join_column(Field_translator *field_param, TABLE_LIST *tab); Natural_join_column(Item_field *field_param, TABLE_LIST *tab); LEX_CSTRING *name(); Item *create_item(THD *thd); Field *field(); const char *safe_table_name(); const char *safe_db_name(); GRANT_INFO *grant(); }; /** Type of table which can be open for an element of table list. */ enum enum_open_type { OT_TEMPORARY_OR_BASE= 0, OT_TEMPORARY_ONLY, OT_BASE_ONLY }; class SJ_MATERIALIZATION_INFO; class Index_hint; class Item_in_subselect; /* trivial class, for %union in sql_yacc.yy */ struct vers_history_point_t { vers_kind_t unit; Item *item; }; class Vers_history_point : public vers_history_point_t { void fix_item(); public: Vers_history_point() { empty(); } Vers_history_point(vers_kind_t unit_arg, Item *item_arg) { unit= unit_arg; item= item_arg; fix_item(); } Vers_history_point(vers_history_point_t p) { unit= p.unit; item= p.item; fix_item(); } void empty() { unit= VERS_TIMESTAMP; item= NULL; } void print(String *str, enum_query_type, const char *prefix, size_t plen) const; bool check_unit(THD *thd); bool eq(const vers_history_point_t &point) const; }; struct vers_select_conds_t { vers_system_time_t type; vers_system_time_t orig_type; bool used:1; bool delete_history:1; Vers_history_point start; Vers_history_point end; Lex_ident name; Item_field *field_start; Item_field *field_end; const TABLE_SHARE::period_info_t *period; void empty() { type= SYSTEM_TIME_UNSPECIFIED; orig_type= SYSTEM_TIME_UNSPECIFIED; used= false; delete_history= false; start.empty(); end.empty(); } void init(vers_system_time_t _type, Vers_history_point _start= Vers_history_point(), Vers_history_point _end= Vers_history_point(), Lex_ident _name= "SYSTEM_TIME") { type= _type; orig_type= _type; used= false; delete_history= (type == SYSTEM_TIME_HISTORY || type == SYSTEM_TIME_BEFORE); start= _start; end= _end; name= _name; } void set_all() { type= SYSTEM_TIME_ALL; name= "SYSTEM_TIME"; } void print(String *str, enum_query_type query_type) const; bool init_from_sysvar(THD *thd); bool is_set() const { return type != SYSTEM_TIME_UNSPECIFIED; } bool check_units(THD *thd); bool was_set() const { return orig_type != SYSTEM_TIME_UNSPECIFIED; } bool need_setup() const { return type != SYSTEM_TIME_UNSPECIFIED && type != SYSTEM_TIME_ALL; } bool eq(const vers_select_conds_t &conds) const; }; /* Table reference in the FROM clause. These table references can be of several types that correspond to different SQL elements. Below we list all types of TABLE_LISTs with the necessary conditions to determine when a TABLE_LIST instance belongs to a certain type. 1) table (TABLE_LIST::view == NULL) - base table (TABLE_LIST::derived == NULL) - FROM-clause subquery - TABLE_LIST::table is a temp table (TABLE_LIST::derived != NULL) - information schema table (TABLE_LIST::schema_table != NULL) NOTICE: for schema tables TABLE_LIST::field_translation may be != NULL 2) view (TABLE_LIST::view != NULL) - merge (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_MERGE) also (TABLE_LIST::field_translation != NULL) - tmptable (TABLE_LIST::effective_algorithm == VIEW_ALGORITHM_TMPTABLE) also (TABLE_LIST::field_translation == NULL) 2.5) TODO: Add derived tables description here 3) nested table reference (TABLE_LIST::nested_join != NULL) - table sequence - e.g. (t1, t2, t3) TODO: how to distinguish from a JOIN? - general JOIN TODO: how to distinguish from a table sequence? - NATURAL JOIN (TABLE_LIST::natural_join != NULL) - JOIN ... USING (TABLE_LIST::join_using_fields != NULL) - semi-join nest (sj_on_expr!= NULL && sj_subq_pred!=NULL) 4) jtbm semi-join (jtbm_subselect != NULL) */ /** last_leaf_for_name_resolutioning support. */ struct LEX; class Index_hint; /* @struct TABLE_CHAIN @brief Subchain of global chain of table references The structure contains a pointer to the address of the next_global pointer to the first TABLE_LIST objectof the subchain and the address of the next_global pointer to the element right after the last TABLE_LIST object of the subchain. For an empty subchain both pointers have the same value. */ struct TABLE_CHAIN { TABLE_CHAIN() = default; TABLE_LIST **start_pos; TABLE_LIST ** end_pos; void set_start_pos(TABLE_LIST **pos) { start_pos= pos; } void set_end_pos(TABLE_LIST **pos) { end_pos= pos; } }; class Table_ident; struct TABLE_LIST { TABLE_LIST(THD *thd, LEX_CSTRING db_str, bool fqtn, LEX_CSTRING alias_str, bool has_alias_ptr, Table_ident *table_ident, thr_lock_type lock_t, enum_mdl_type mdl_t, ulong table_opts, bool info_schema, st_select_lex *sel, List *index_hints_ptr, LEX_STRING *option_ptr); TABLE_LIST() = default; /* Remove gcc warning */ enum prelocking_types { PRELOCK_NONE, PRELOCK_ROUTINE, PRELOCK_FK }; /** Prepare TABLE_LIST that consists of one table instance to use in open_and_lock_tables */ inline void reset() { bzero((void*)this, sizeof(*this)); } inline void init_one_table(const LEX_CSTRING *db_arg, const LEX_CSTRING *table_name_arg, const LEX_CSTRING *alias_arg, enum thr_lock_type lock_type_arg) { enum enum_mdl_type mdl_type; if (lock_type_arg >= TL_FIRST_WRITE) mdl_type= MDL_SHARED_WRITE; else if (lock_type_arg == TL_READ_NO_INSERT) mdl_type= MDL_SHARED_NO_WRITE; else mdl_type= MDL_SHARED_READ; reset(); DBUG_ASSERT(!db_arg->str || strlen(db_arg->str) == db_arg->length); DBUG_ASSERT(!table_name_arg->str || strlen(table_name_arg->str) == table_name_arg->length); DBUG_ASSERT(!alias_arg || strlen(alias_arg->str) == alias_arg->length); db= *db_arg; table_name= *table_name_arg; alias= (alias_arg ? *alias_arg : *table_name_arg); lock_type= lock_type_arg; updating= lock_type >= TL_FIRST_WRITE; MDL_REQUEST_INIT(&mdl_request, MDL_key::TABLE, db.str, table_name.str, mdl_type, MDL_TRANSACTION); } TABLE_LIST(TABLE *table_arg, thr_lock_type lock_type) { DBUG_ASSERT(table_arg->s); init_one_table(&table_arg->s->db, &table_arg->s->table_name, NULL, lock_type); table= table_arg; vers_conditions.name= table->s->vers.name; } inline void init_one_table_for_prelocking(const LEX_CSTRING *db_arg, const LEX_CSTRING *table_name_arg, const LEX_CSTRING *alias_arg, enum thr_lock_type lock_type_arg, prelocking_types prelocking_type, TABLE_LIST *belong_to_view_arg, uint8 trg_event_map_arg, TABLE_LIST ***last_ptr, my_bool insert_data) { init_one_table(db_arg, table_name_arg, alias_arg, lock_type_arg); cacheable_table= 1; prelocking_placeholder= prelocking_type; open_type= (prelocking_type == PRELOCK_ROUTINE ? OT_TEMPORARY_OR_BASE : OT_BASE_ONLY); belong_to_view= belong_to_view_arg; trg_event_map= trg_event_map_arg; /* MDL is enough for read-only FK checks, we don't need the table */ if (prelocking_type == PRELOCK_FK && lock_type < TL_FIRST_WRITE) open_strategy= OPEN_STUB; **last_ptr= this; prev_global= *last_ptr; *last_ptr= &next_global; for_insert_data= insert_data; } /* List of tables local to a subquery (used by SQL_I_List). Considers views as leaves (unlike 'next_leaf' below). Created at parse time in st_select_lex::add_table_to_list() -> table_list.link_in_list(). */ TABLE_LIST *next_local; /* link in a global list of all queries tables */ TABLE_LIST *next_global, **prev_global; LEX_CSTRING db; LEX_CSTRING table_name; LEX_CSTRING schema_table_name; LEX_CSTRING alias; const char *option; /* Used by cache index */ Item *on_expr; /* Used with outer join */ Name_resolution_context *on_context; /* For ON expressions */ Table_function_json_table *table_function; /* If it's the table function. */ Item *sj_on_expr; /* (Valid only for semi-join nests) Bitmap of tables that are within the semi-join (this is different from bitmap of all nest's children because tables that were pulled out of the semi-join nest remain listed as nest's children). */ table_map sj_inner_tables; /* Number of IN-compared expressions */ uint sj_in_exprs; /* If this is a non-jtbm semi-join nest: corresponding subselect predicate */ Item_in_subselect *sj_subq_pred; table_map original_subq_pred_used_tables; /* If this is a jtbm semi-join object: corresponding subselect predicate */ Item_in_subselect *jtbm_subselect; /* TODO: check if this can be joined with tablenr_exec */ uint jtbm_table_no; SJ_MATERIALIZATION_INFO *sj_mat_info; /* The structure of ON expression presented in the member above can be changed during certain optimizations. This member contains a snapshot of AND-OR structure of the ON expression made after permanent transformations of the parse tree, and is used to restore ON clause before every reexecution of a prepared statement or stored procedure. */ Item *prep_on_expr; COND_EQUAL *cond_equal; /* Used with outer join */ /* During parsing - left operand of NATURAL/USING join where 'this' is the right operand. After parsing (this->natural_join == this) iff 'this' represents a NATURAL or USING join operation. Thus after parsing 'this' is a NATURAL/USING join iff (natural_join != NULL). */ TABLE_LIST *natural_join; /* True if 'this' represents a nested join that is a NATURAL JOIN. For one of the operands of 'this', the member 'natural_join' points to the other operand of 'this'. */ bool is_natural_join; /* Field names in a USING clause for JOIN ... USING. */ List *join_using_fields; /* Explicitly store the result columns of either a NATURAL/USING join or an operand of such a join. */ List *join_columns; /* TRUE if join_columns contains all columns of this table reference. */ bool is_join_columns_complete; /* List of nodes in a nested join tree, that should be considered as leaves with respect to name resolution. The leaves are: views, top-most nodes representing NATURAL/USING joins, subqueries, and base tables. All of these TABLE_LIST instances contain a materialized list of columns. The list is local to a subquery. */ TABLE_LIST *next_name_resolution_table; /* Index names in a "... JOIN ... USE/IGNORE INDEX ..." clause. */ List *index_hints; TABLE *table; /* opened table */ ulonglong table_id; /* table id (from binlog) for opened table */ /* select_result for derived table to pass it from table creation to table filling procedure */ select_unit *derived_result; /* Stub used for materialized derived tables. */ table_map map; /* ID bit of table (1,2,4,8,16...) */ table_map get_map() { return jtbm_subselect? table_map(1) << jtbm_table_no : table->map; } uint get_tablenr() { return jtbm_subselect? jtbm_table_no : table->tablenr; } void set_tablenr(uint new_tablenr) { if (jtbm_subselect) { jtbm_table_no= new_tablenr; } if (table) { table->tablenr= new_tablenr; table->map= table_map(1) << new_tablenr; } } /* Reference from aux_tables to local list entry of main select of multi-delete statement: delete t1 from t2,t1 where t1.a<'B' and t2.b=t1.b; here it will be reference of first occurrence of t1 to second (as you can see this lists can't be merged) */ TABLE_LIST *correspondent_table; /** @brief Normally, this field is non-null for anonymous derived tables only. @details This field is set to non-null for - Anonymous derived tables, In this case it points to the SELECT_LEX_UNIT representing the derived table. E.g. for a query @verbatim SELECT * FROM (SELECT a FROM t1) b @endverbatim For the @c TABLE_LIST representing the derived table @c b, @c derived points to the SELECT_LEX_UNIT representing the result of the query within parenteses. - Views. This is set for views with @verbatim ALGORITHM = TEMPTABLE @endverbatim by mysql_make_view(). @note Inside views, a subquery in the @c FROM clause is not allowed. @note Do not use this field to separate views/base tables/anonymous derived tables. Use TABLE_LIST::is_anonymous_derived_table(). */ st_select_lex_unit *derived; /* SELECT_LEX_UNIT of derived table */ With_element *with; /* With element defining this table (if any) */ /* Bitmap of the defining with element */ table_map with_internal_reference_map; TABLE_LIST * next_with_rec_ref; bool is_derived_with_recursive_reference; bool block_handle_derived; /* The interface employed to materialize the table by a foreign engine */ derived_handler *dt_handler; /* The text of the query specifying the derived table */ LEX_CSTRING derived_spec; /* The object used to organize execution of the query that specifies the derived table by a foreign engine */ Pushdown_derived *pushdown_derived; ST_SCHEMA_TABLE *schema_table; /* Information_schema table */ st_select_lex *schema_select_lex; /* True when the view field translation table is used to convert schema table fields for backwards compatibility with SHOW command. */ bool schema_table_reformed; TMP_TABLE_PARAM *schema_table_param; /* link to select_lex where this table was used */ st_select_lex *select_lex; LEX *view; /* link on VIEW lex for merging */ Field_translator *field_translation; /* array of VIEW fields */ /* pointer to element after last one in translation table above */ Field_translator *field_translation_end; bool field_translation_updated; /* List (based on next_local) of underlying tables of this view. I.e. it does not include the tables of subqueries used in the view. Is set only for merged views. */ TABLE_LIST *merge_underlying_list; /* - 0 for base tables - in case of the view it is the list of all (not only underlying tables but also used in subquery ones) tables of the view. */ List *view_tables; /* most upper view this table belongs to */ TABLE_LIST *belong_to_view; /* A merged derived table this table belongs to */ TABLE_LIST *belong_to_derived; /* The view directly referencing this table (non-zero only for merged underlying tables of a view). */ TABLE_LIST *referencing_view; table_map view_used_tables; table_map map_exec; /* TODO: check if this can be joined with jtbm_table_no */ uint tablenr_exec; uint maybe_null_exec; /* Ptr to parent MERGE table list item. See top comment in ha_myisammrg.cc */ TABLE_LIST *parent_l; /* Security context (non-zero only for tables which belong to view with SQL SECURITY DEFINER) */ Security_context *security_ctx; uchar tabledef_version_buf[MY_UUID_SIZE > MICROSECOND_TIMESTAMP_BUFFER_SIZE-1 ? MY_UUID_SIZE + 1 : MICROSECOND_TIMESTAMP_BUFFER_SIZE]; LEX_CUSTRING tabledef_version; /* This view security context (non-zero only for views with SQL SECURITY DEFINER) */ Security_context *view_sctx; bool allowed_show; Item *where; /* VIEW WHERE clause condition */ Item *check_option; /* WITH CHECK OPTION condition */ LEX_STRING select_stmt; /* text of (CREATE/SELECT) statement */ LEX_CSTRING md5; /* md5 of query text */ LEX_CSTRING source; /* source of CREATE VIEW */ LEX_CSTRING view_db; /* saved view database */ LEX_CSTRING view_name; /* saved view name */ LEX_STRING hr_timestamp; /* time stamp of last operation */ LEX_USER definer; /* definer of view */ ulonglong file_version; /* version of file's field set */ ulonglong mariadb_version; /* version of server on creation */ ulonglong updatable_view; /* VIEW can be updated */ /** @brief The declared algorithm, if this is a view. @details One of - VIEW_ALGORITHM_UNDEFINED - VIEW_ALGORITHM_TMPTABLE - VIEW_ALGORITHM_MERGE @to do Replace with an enum */ ulonglong algorithm; ulonglong view_suid; /* view is suid (TRUE dy default) */ ulonglong with_check; /* WITH CHECK OPTION */ /* effective value of WITH CHECK OPTION (differ for temporary table algorithm) */ uint8 effective_with_check; /** @brief The view algorithm that is actually used, if this is a view. @details One of - VIEW_ALGORITHM_UNDEFINED - VIEW_ALGORITHM_TMPTABLE - VIEW_ALGORITHM_MERGE @to do Replace with an enum */ uint8 derived_type; GRANT_INFO grant; /* data need by some engines in query cache*/ ulonglong engine_data; /* call back function for asking handler about caching in query cache */ qc_engine_callback callback_func; thr_lock_type lock_type; /* Two fields below are set during parsing this table reference in the cases when the table reference can be potentially a reference to a CTE table. In this cases the fact that the reference is a reference to a CTE or not will be ascertained at the very end of parsing of the query when referencies to CTE are resolved. For references to CTE and to derived tables no mdl requests are needed while for other table references they are. If a request is possibly postponed the info that allows to issue this request must be saved in 'mdl_type' and 'table_options'. */ enum_mdl_type mdl_type; ulong table_options; uint outer_join; /* Which join type */ uint shared; /* Used in multi-upd */ bool updatable; /* VIEW/TABLE can be updated now */ bool straight; /* optimize with prev table */ bool updating; /* for replicate-do/ignore table */ bool force_index; /* prefer index over table scan */ bool ignore_leaves; /* preload only non-leaf nodes */ bool crashed; /* Table was found crashed */ bool skip_locked; /* Skip locked in view defination */ table_map dep_tables; /* tables the table depends on */ table_map on_expr_dep_tables; /* tables on expression depends on */ struct st_nested_join *nested_join; /* if the element is a nested join */ TABLE_LIST *embedding; /* nested join containing the table */ List *join_list;/* join list the table belongs to */ bool lifted; /* set to true when the table is moved to the upper level at the parsing stage */ bool cacheable_table; /* stop PS caching */ /* used in multi-upd/views privilege check */ bool table_in_first_from_clause; /** Specifies which kind of table should be open for this element of table list. */ enum enum_open_type open_type; /* TRUE if this merged view contain auto_increment field */ bool contain_auto_increment; bool compact_view_format; /* Use compact format for SHOW CREATE VIEW */ /* view where processed */ bool where_processed; /* TRUE <=> VIEW CHECK OPTION expression has been processed */ bool check_option_processed; /* TABLE_TYPE_UNKNOWN if any type is acceptable */ Table_type required_type; handlerton *db_type; /* table_type for handler */ char timestamp_buffer[MICROSECOND_TIMESTAMP_BUFFER_SIZE]; /* This TABLE_LIST object is just placeholder for prelocking, it will be used for implicit LOCK TABLES only and won't be used in real statement. */ prelocking_types prelocking_placeholder; /** Indicates that if TABLE_LIST object corresponds to the table/view which requires special handling. */ enum enum_open_strategy { /* Normal open. */ OPEN_NORMAL= 0, /* Associate a table share only if the the table exists. */ OPEN_IF_EXISTS, /* Don't associate a table share. */ OPEN_STUB } open_strategy; /** TRUE if an alias for this table was specified in the SQL. */ bool is_alias; /** TRUE if the table is referred to in the statement using a fully qualified name (.). */ bool is_fqtn; /* TRUE <=> derived table should be filled right after optimization. */ bool fill_me; /* TRUE <=> view/DT is merged. */ /* TODO: replace with derived_type */ bool merged; bool merged_for_insert; bool sequence; /* Part of NEXTVAL/CURVAL/LASTVAL */ /* Items created by create_view_field and collected to change them in case of materialization of the view/derived table */ List used_items; /* Sublist (tail) of persistent used_items */ List persistent_used_items; /* View creation context. */ View_creation_ctx *view_creation_ctx; /* Attributes to save/load view creation context in/from frm-file. Ther are required only to be able to use existing parser to load view-definition file. As soon as the parser parsed the file, view creation context is initialized and the attributes become redundant. These attributes MUST NOT be used for any purposes but the parsing. */ LEX_CSTRING view_client_cs_name; LEX_CSTRING view_connection_cl_name; /* View definition (SELECT-statement) in the UTF-form. */ LEX_CSTRING view_body_utf8; /* End of view definition context. */ /** Indicates what triggers we need to pre-load for this TABLE_LIST when opening an associated TABLE. This is filled after the parsed tree is created. slave_fk_event_map is filled on the slave side with bitmaps value representing row-based event operation to help find and prelock possible FK constrain-related child tables. */ uint8 trg_event_map, slave_fk_event_map; /* TRUE <=> this table is a const one and was optimized away. */ bool optimized_away; /** TRUE <=> already materialized. Valid only for materialized derived tables/views. */ bool materialized; /* I_S: Flags to open_table (e.g. OPEN_TABLE_ONLY or OPEN_VIEW_ONLY) */ uint i_s_requested_object; bool prohibit_cond_pushdown; /* I_S: how to read the tables (SKIP_OPEN_TABLE/OPEN_FRM_ONLY/OPEN_FULL_TABLE) */ uint table_open_method; /* I_S: where the schema table was filled (this is a hack. The code should be able to figure out whether reading from I_S should be done by create_sort_index() or by JOIN::exec.) */ enum enum_schema_table_state schema_table_state; /* Something like a "query plan" for reading INFORMATION_SCHEMA table */ IS_table_read_plan *is_table_read_plan; MDL_request mdl_request; #ifdef WITH_PARTITION_STORAGE_ENGINE /* List to carry partition names from PARTITION (...) clause in statement */ List *partition_names; #endif /* WITH_PARTITION_STORAGE_ENGINE */ void calc_md5(char *buffer); int view_check_option(THD *thd, bool ignore_failure); bool create_field_translation(THD *thd); bool setup_underlying(THD *thd); void cleanup_items(); bool placeholder() { return derived || view || schema_table || !table || table_function; } void print(THD *thd, table_map eliminated_tables, String *str, enum_query_type query_type); void print_leaf_tables(THD *thd, String *str, enum_query_type query_type); bool check_single_table(TABLE_LIST **table, table_map map, TABLE_LIST *view); bool set_insert_values(MEM_ROOT *mem_root); void replace_view_error_with_generic(THD *thd); TABLE_LIST *find_underlying_table(TABLE *table); TABLE_LIST *first_leaf_for_name_resolution(); TABLE_LIST *last_leaf_for_name_resolution(); /* System Versioning */ vers_select_conds_t vers_conditions; vers_select_conds_t period_conditions; bool has_period() const { return period_conditions.is_set(); } my_bool for_insert_data; /** @brief Find the bottom in the chain of embedded table VIEWs. @detail This is used for single-table UPDATE/DELETE when they are modifying a single-table VIEW. */ TABLE_LIST *find_table_for_update() { TABLE_LIST *tbl= this; while(!tbl->is_multitable() && tbl->single_table_updatable() && tbl->merge_underlying_list) { tbl= tbl->merge_underlying_list; } return tbl; } TABLE *get_real_join_table(); bool is_leaf_for_name_resolution(); inline TABLE_LIST *top_table() { return belong_to_view ? belong_to_view : this; } inline bool prepare_check_option(THD *thd) { bool res= FALSE; if (effective_with_check) res= prep_check_option(thd, effective_with_check); return res; } inline bool prepare_where(THD *thd, Item **conds, bool no_where_clause) { if (!view || is_merged_derived()) return prep_where(thd, conds, no_where_clause); return FALSE; } void register_want_access(privilege_t want_access); bool prepare_security(THD *thd); #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *find_view_security_context(THD *thd); bool prepare_view_security_context(THD *thd, bool upgrade_check); #endif /* Cleanup for re-execution in a prepared statement or a stored procedure. */ void reinit_before_use(THD *thd); Item_subselect *containing_subselect(); /* Compiles the tagged hints list and fills up TABLE::keys_in_use_for_query, TABLE::keys_in_use_for_group_by, TABLE::keys_in_use_for_order_by, TABLE::force_index and TABLE::covering_keys. */ bool process_index_hints(TABLE *table); bool is_the_same_definition(THD *thd, TABLE_SHARE *s); /** Record the value of metadata version of the corresponding table definition cache element in this parse tree node. @sa check_and_update_table_version() */ inline void set_table_ref_id(TABLE_SHARE *s) { set_table_ref_id(s->get_table_ref_type(), s->get_table_ref_version()); } inline void set_table_ref_id(enum_table_ref_type table_ref_type_arg, ulonglong table_ref_version_arg) { m_table_ref_type= table_ref_type_arg; m_table_ref_version= table_ref_version_arg; } void set_table_id(TABLE_SHARE *s) { set_table_ref_id(s); set_tabledef_version(s); } void set_tabledef_version(TABLE_SHARE *s) { if (!tabledef_version.length && s->tabledef_version.length) { DBUG_ASSERT(s->tabledef_version.length < sizeof(tabledef_version_buf)); tabledef_version.str= tabledef_version_buf; memcpy(tabledef_version_buf, s->tabledef_version.str, (tabledef_version.length= s->tabledef_version.length)); // safety tabledef_version_buf[tabledef_version.length]= 0; } } /* Set of functions returning/setting state of a derived table/view. */ bool is_non_derived() const { return (!derived_type); } bool is_view_or_derived() const { return derived_type; } bool is_view() const { return (derived_type & DTYPE_VIEW); } bool is_derived() const { return (derived_type & DTYPE_TABLE); } bool is_with_table(); bool is_recursive_with_table(); bool is_with_table_recursive_reference(); void register_as_derived_with_rec_ref(With_element *rec_elem); bool is_nonrecursive_derived_with_rec_ref(); bool fill_recursive(THD *thd); inline void set_view() { derived_type= DTYPE_VIEW; } inline void set_derived() { derived_type= DTYPE_TABLE; } bool is_merged_derived() const { return (derived_type & DTYPE_MERGE); } inline void set_merged_derived() { DBUG_ENTER("set_merged_derived"); DBUG_PRINT("enter", ("Alias: '%s' Unit: %p", (alias.str ? alias.str : ""), get_unit())); derived_type= static_cast((derived_type & DTYPE_MASK) | DTYPE_MERGE); set_check_merged(); DBUG_VOID_RETURN; } bool is_materialized_derived() const { return (derived_type & DTYPE_MATERIALIZE); } void set_materialized_derived() { DBUG_ENTER("set_materialized_derived"); DBUG_PRINT("enter", ("Alias: '%s' Unit: %p", (alias.str ? alias.str : ""), get_unit())); derived_type= static_cast((derived_type & (derived ? DTYPE_MASK : DTYPE_VIEW)) | DTYPE_MATERIALIZE); set_check_materialized(); DBUG_VOID_RETURN; } bool is_multitable() const { return (derived_type & DTYPE_MULTITABLE); } inline void set_multitable() { derived_type|= DTYPE_MULTITABLE; } bool set_as_with_table(THD *thd, With_element *with_elem); void reset_const_table(); bool handle_derived(LEX *lex, uint phases); /** @brief True if this TABLE_LIST represents an anonymous derived table, i.e. the result of a subquery. */ bool is_anonymous_derived_table() const { return derived && !view; } /** @brief Returns the name of the database that the referenced table belongs to. */ const LEX_CSTRING get_db_name() const { return view != NULL ? view_db : db; } /** @brief Returns the name of the table that this TABLE_LIST represents. @details The unqualified table name or view name for a table or view, respectively. */ const LEX_CSTRING get_table_name() const { return view != NULL ? view_name : table_name; } bool is_active_sjm(); bool is_sjm_scan_table(); bool is_jtbm() { return MY_TEST(jtbm_subselect != NULL); } st_select_lex_unit *get_unit(); st_select_lex *get_single_select(); void wrap_into_nested_join(List &join_list); bool init_derived(THD *thd, bool init_view); int fetch_number_of_rows(); bool change_refs_to_fields(); bool single_table_updatable(); bool is_inner_table_of_outer_join() { for (TABLE_LIST *tbl= this; tbl; tbl= tbl->embedding) { if (tbl->outer_join) return true; } return false; } void set_lock_type(THD* thd, enum thr_lock_type lock); derived_handler *find_derived_handler(THD *thd); TABLE_LIST *get_first_table(); void remove_join_columns() { if (join_columns) { join_columns->empty(); join_columns= NULL; is_join_columns_complete= FALSE; } } inline void set_view_def_version(LEX_STRING *version) { m_table_ref_type= TABLE_REF_VIEW; tabledef_version.str= (const uchar *) version->str; tabledef_version.length= version->length; } private: bool prep_check_option(THD *thd, uint8 check_opt_type); bool prep_where(THD *thd, Item **conds, bool no_where_clause); void set_check_materialized(); #ifndef DBUG_OFF void set_check_merged(); #else inline void set_check_merged() {} #endif /** See comments for set_table_ref_id() */ enum enum_table_ref_type m_table_ref_type; /** See comments for set_table_ref_id() */ ulonglong m_table_ref_version; }; #define ERROR_TABLE ((TABLE_LIST*) 0x1) class Item; /* Iterator over the fields of a generic table reference. */ class Field_iterator: public Sql_alloc { public: Field_iterator() = default; /* Remove gcc warning */ virtual ~Field_iterator() = default; virtual void set(TABLE_LIST *)= 0; virtual void next()= 0; virtual bool end_of_fields()= 0; /* Return 1 at end of list */ virtual LEX_CSTRING *name()= 0; virtual Item *create_item(THD *)= 0; virtual Field *field()= 0; }; /* Iterator over the fields of a base table, view with temporary table, or subquery. */ class Field_iterator_table: public Field_iterator { Field **ptr; public: Field_iterator_table() :ptr(0) {} void set(TABLE_LIST *table) override { ptr= table->table->field; } void set_table(TABLE *table) { ptr= table->field; } void next() override { ptr++; } bool end_of_fields() override { return *ptr == 0; } LEX_CSTRING *name() override; Item *create_item(THD *thd) override; Field *field() override { return *ptr; } }; /* Iterator over the fields of a merge view. */ class Field_iterator_view: public Field_iterator { Field_translator *ptr, *array_end; TABLE_LIST *view; public: Field_iterator_view() :ptr(0), array_end(0) {} void set(TABLE_LIST *table) override; void next() override { ptr++; } bool end_of_fields() override { return ptr == array_end; } LEX_CSTRING *name() override; Item *create_item(THD *thd) override; Item **item_ptr() {return &ptr->item; } Field *field() override { return 0; } inline Item *item() { return ptr->item; } Field_translator *field_translator() { return ptr; } }; /* Field_iterator interface to the list of materialized fields of a NATURAL/USING join. */ class Field_iterator_natural_join: public Field_iterator { List_iterator_fast column_ref_it; Natural_join_column *cur_column_ref; public: Field_iterator_natural_join() :cur_column_ref(NULL) {} ~Field_iterator_natural_join() = default; void set(TABLE_LIST *table) override; void next() override; bool end_of_fields() override { return !cur_column_ref; } LEX_CSTRING *name() override { return cur_column_ref->name(); } Item *create_item(THD *thd) override { return cur_column_ref->create_item(thd); } Field *field() override { return cur_column_ref->field(); } Natural_join_column *column_ref() { return cur_column_ref; } }; /* Generic iterator over the fields of an arbitrary table reference. DESCRIPTION This class unifies the various ways of iterating over the columns of a table reference depending on the type of SQL entity it represents. If such an entity represents a nested table reference, this iterator encapsulates the iteration over the columns of the members of the table reference. IMPLEMENTATION The implementation assumes that all underlying NATURAL/USING table references already contain their result columns and are linked into the list TABLE_LIST::next_name_resolution_table. */ class Field_iterator_table_ref: public Field_iterator { TABLE_LIST *table_ref, *first_leaf, *last_leaf; Field_iterator_table table_field_it; Field_iterator_view view_field_it; Field_iterator_natural_join natural_join_it; Field_iterator *field_it; void set_field_iterator(); public: Field_iterator_table_ref() :field_it(NULL) {} void set(TABLE_LIST *table) override; void next() override; bool end_of_fields() override { return (table_ref == last_leaf && field_it->end_of_fields()); } LEX_CSTRING *name() override { return field_it->name(); } const char *get_table_name(); const char *get_db_name(); GRANT_INFO *grant(); Item *create_item(THD *thd) override { return field_it->create_item(thd); } Field *field() override { return field_it->field(); } Natural_join_column *get_or_create_column_ref(THD *thd, TABLE_LIST *parent_table_ref); Natural_join_column *get_natural_column_ref(); }; #define JOIN_OP_NEST 1 #define REBALANCED_NEST 2 typedef struct st_nested_join { List join_list; /* list of elements in the nested join */ /* Currently the valid values for nest type are: JOIN_OP_NEST - for nest created for JOIN operation used as an operand in a join expression, contains 2 elements; JOIN_OP_NEST | REBALANCED_NEST - nest created after tree re-balancing in st_select_lex::add_cross_joined_table(), contains 1 element; 0 - for all other nests. Examples: 1. SELECT * FROM t1 JOIN t2 LEFT JOIN t3 ON t2.a=t3.a; Here the nest created for LEFT JOIN at first has nest_type==JOIN_OP_NEST. After re-balancing in st_select_lex::add_cross_joined_table() this nest has nest_type==JOIN_OP_NEST | REBALANCED_NEST. The nest for JOIN created in st_select_lex::add_cross_joined_table() has nest_type== JOIN_OP_NEST. 2. SELECT * FROM t1 JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a) Here the nest created for LEFT JOIN has nest_type==0, because it's not an operand in a join expression. The nest created for JOIN has nest_type set to JOIN_OP_NEST. */ uint nest_type; /* Bitmap of tables within this nested join (including those embedded within its children), including tables removed by table elimination. */ table_map used_tables; table_map not_null_tables; /* tables that rejects nulls */ /** Used for pointing out the first table in the plan being covered by this join nest. It is used exclusively within make_outerjoin_info(). */ struct st_join_table *first_nested; /* Used to count tables in the nested join in 2 isolated places: 1. In make_outerjoin_info(). 2. check_interleaving_with_nj/restore_prev_nj_state (these are called by the join optimizer. Before each use the counters are zeroed by reset_nj_counters. */ uint counter; /* Number of elements in join_list that participate in the join plan choice: - Base tables that were not removed by table elimination - Join nests that were not removed by mark_join_nest_as_const */ uint n_tables; nested_join_map nj_map; /* Bit used to identify this nested join*/ /* (Valid only for semi-join nests) Bitmap of tables outside the semi-join that are used within the semi-join's ON condition. */ table_map sj_depends_on; /* Outer non-trivially correlated tables */ table_map sj_corr_tables; List sj_outer_expr_list; /** True if this join nest node is completely covered by the query execution plan. This means two things. 1. All tables on its @c join_list are covered by the plan. 2. All child join nest nodes are fully covered. */ bool is_fully_covered() const { return n_tables == counter; } } NESTED_JOIN; typedef struct st_changed_table_list { struct st_changed_table_list *next; char *key; size_t key_length; } CHANGED_TABLE_LIST; typedef struct st_open_table_list{ struct st_open_table_list *next; char *db,*table; uint32 in_use,locked; } OPEN_TABLE_LIST; static inline MY_BITMAP *tmp_use_all_columns(TABLE *table, MY_BITMAP **bitmap) { MY_BITMAP *old= *bitmap; *bitmap= &table->s->all_set; return old; } static inline void tmp_restore_column_map(MY_BITMAP **bitmap, MY_BITMAP *old) { *bitmap= old; } /* The following is only needed for debugging */ static inline MY_BITMAP *dbug_tmp_use_all_columns(TABLE *table, MY_BITMAP **bitmap) { #ifdef DBUG_ASSERT_EXISTS return tmp_use_all_columns(table, bitmap); #else return 0; #endif } static inline void dbug_tmp_restore_column_map(MY_BITMAP **bitmap, MY_BITMAP *old) { #ifdef DBUG_ASSERT_EXISTS tmp_restore_column_map(bitmap, old); #endif } /* Variant of the above : handle both read and write sets. Provide for the possiblity of the read set being the same as the write set */ static inline void dbug_tmp_use_all_columns(TABLE *table, MY_BITMAP **save, MY_BITMAP **read_set, MY_BITMAP **write_set) { #ifdef DBUG_ASSERT_EXISTS save[0]= *read_set; save[1]= *write_set; (void) tmp_use_all_columns(table, read_set); (void) tmp_use_all_columns(table, write_set); #endif } static inline void dbug_tmp_restore_column_maps(MY_BITMAP **read_set, MY_BITMAP **write_set, MY_BITMAP **old) { #ifdef DBUG_ASSERT_EXISTS tmp_restore_column_map(read_set, old[0]); tmp_restore_column_map(write_set, old[1]); #endif } bool ok_for_lower_case_names(const char *names); enum get_table_share_flags { GTS_TABLE = 1, GTS_VIEW = 2, GTS_NOLOCK = 4, GTS_USE_DISCOVERY = 8, GTS_FORCE_DISCOVERY = 16 }; size_t max_row_length(TABLE *table, MY_BITMAP const *cols, const uchar *data); void init_mdl_requests(TABLE_LIST *table_list); enum open_frm_error open_table_from_share(THD *thd, TABLE_SHARE *share, const LEX_CSTRING *alias, uint db_stat, uint prgflag, uint ha_open_flags, TABLE *outparam, bool is_create_table, List *partitions_to_open= NULL); bool copy_keys_from_share(TABLE *outparam, MEM_ROOT *root); bool parse_vcol_defs(THD *thd, MEM_ROOT *mem_root, TABLE *table, bool *error_reported, vcol_init_mode expr); TABLE_SHARE *alloc_table_share(const char *db, const char *table_name, const char *key, uint key_length); void init_tmp_table_share(THD *thd, TABLE_SHARE *share, const char *key, uint key_length, const char *table_name, const char *path); void free_table_share(TABLE_SHARE *share); enum open_frm_error open_table_def(THD *thd, TABLE_SHARE *share, uint flags = GTS_TABLE); void open_table_error(TABLE_SHARE *share, enum open_frm_error error, int db_errno); void update_create_info_from_table(HA_CREATE_INFO *info, TABLE *form); bool check_db_name(LEX_STRING *db); bool check_column_name(const char *name); bool check_period_name(const char *name); bool check_table_name(const char *name, size_t length, bool check_for_path_chars); int rename_file_ext(const char * from,const char * to,const char * ext); char *get_field(MEM_ROOT *mem, Field *field); bool get_field(MEM_ROOT *mem, Field *field, class String *res); bool validate_comment_length(THD *thd, LEX_CSTRING *comment, size_t max_len, uint err_code, const char *name); int closefrm(TABLE *table); void free_blobs(TABLE *table); void free_field_buffers_larger_than(TABLE *table, uint32 size); ulong get_form_pos(File file, uchar *head, TYPELIB *save_names); void append_unescaped(String *res, const char *pos, size_t length); void prepare_frm_header(THD *thd, uint reclength, uchar *fileinfo, HA_CREATE_INFO *create_info, uint keys, KEY *key_info); const char *fn_frm_ext(const char *name); /* Check that the integer is in the internal */ static inline int set_zone(int nr,int min_zone,int max_zone) { if (nr <= min_zone) return min_zone; if (nr >= max_zone) return max_zone; return nr; } /* performance schema */ extern LEX_CSTRING PERFORMANCE_SCHEMA_DB_NAME; extern LEX_CSTRING GENERAL_LOG_NAME; extern LEX_CSTRING SLOW_LOG_NAME; extern LEX_CSTRING TRANSACTION_REG_NAME; /* information schema */ extern LEX_CSTRING INFORMATION_SCHEMA_NAME; extern Lex_ident_db MYSQL_SCHEMA_NAME; /* table names */ extern LEX_CSTRING MYSQL_PROC_NAME; inline bool is_infoschema_db(const LEX_CSTRING *name) { return lex_string_eq(&INFORMATION_SCHEMA_NAME, name); } inline bool is_perfschema_db(const LEX_CSTRING *name) { return lex_string_eq(&PERFORMANCE_SCHEMA_DB_NAME, name); } inline void mark_as_null_row(TABLE *table) { table->null_row=1; table->status|=STATUS_NULL_ROW; if (table->s->null_bytes) bfill(table->null_flags,table->s->null_bytes,255); } /* Restore table to state before mark_as_null_row() call. This assumes that the caller has restored table->null_flags, as is done in unclear_tables(). */ inline void unmark_as_null_row(TABLE *table) { table->null_row= 0; table->status&= ~STATUS_NULL_ROW; } bool is_simple_order(ORDER *order); class Open_tables_backup; /** Transaction Registry Table (TRT) This table holds transaction IDs, their corresponding times and other transaction-related data which is used for transaction order resolution. When versioned table marks its records lifetime with transaction IDs, TRT is used to get their actual timestamps. */ class TR_table: public TABLE_LIST { THD *thd; Open_tables_backup *open_tables_backup; public: enum field_id_t { FLD_TRX_ID= 0, FLD_COMMIT_ID, FLD_BEGIN_TS, FLD_COMMIT_TS, FLD_ISO_LEVEL, FIELD_COUNT }; enum enabled {NO, MAYBE, YES}; static enum enabled use_transaction_registry; /** @param[in,out] Thread handle @param[in] Current transaction is read-write. */ TR_table(THD *_thd, bool rw= false); /** Opens a transaction_registry table. @retval true on error, false otherwise. */ bool open(); ~TR_table(); /** @retval current thd */ THD *get_thd() const { return thd; } /** Stores value to internal transaction_registry TABLE object. @param[in] field number in a TABLE @param[in] value to store */ void store(uint field_id, ulonglong val); /** Stores value to internal transaction_registry TABLE object. @param[in] field number in a TABLE @param[in] value to store */ void store(uint field_id, timeval ts); /** Update the transaction_registry right before commit. @param start_id transaction identifier at start @param end_id transaction identifier at commit @retval false on success @retval true on error (the transaction must be rolled back) */ bool update(ulonglong start_id, ulonglong end_id); // return true if found; false if not found or error bool query(ulonglong trx_id); /** Gets a row from transaction_registry with the closest commit_timestamp to first argument. We can search for a value which a lesser or greater than first argument. Also loads a row into an internal TABLE object. @param[in] timestamp @param[in] true if we search for a lesser timestamp, false if greater @retval true if exists, false it not exists or an error occurred */ bool query(MYSQL_TIME &commit_time, bool backwards); /** Checks whether transaction1 sees transaction0. @param[out] true if transaction1 sees transaction0, undefined on error and when transaction1=transaction0 and false otherwise @param[in] transaction_id of transaction1 @param[in] transaction_id of transaction0 @param[in] commit time of transaction1 or 0 if we want it to be queried @param[in] isolation level (from handler.h) of transaction1 @param[in] commit time of transaction0 or 0 if we want it to be queried @retval true on error, false otherwise */ bool query_sees(bool &result, ulonglong trx_id1, ulonglong trx_id0, ulonglong commit_id1= 0, enum_tx_isolation iso_level1= ISO_READ_UNCOMMITTED, ulonglong commit_id0= 0); /** @retval transaction isolation level of a row from internal TABLE object. */ enum_tx_isolation iso_level() const; /** Stores transactioin isolation level to internal TABLE object. */ void store_iso_level(enum_tx_isolation iso_level) { DBUG_ASSERT(iso_level <= ISO_SERIALIZABLE); store(FLD_ISO_LEVEL, iso_level + 1); } /** Writes a message to MariaDB log about incorrect transaction_registry schema. @param[in] a message explained what's incorrect in schema */ void warn_schema_incorrect(const char *reason); /** Checks whether transaction_registry table has a correct schema. @retval true if schema is incorrect and false otherwise */ bool check(bool error); TABLE * operator-> () const { return table; } Field * operator[] (uint field_id) const { DBUG_ASSERT(field_id < FIELD_COUNT); return table->field[field_id]; } operator bool () const { return table; } bool operator== (const TABLE_LIST &subj) const { return (!cmp(&db, &subj.db) && !cmp(&table_name, &subj.table_name)); } bool operator!= (const TABLE_LIST &subj) const { return !(*this == subj); } }; #endif /* MYSQL_CLIENT */ #endif /* TABLE_INCLUDED */ mysql/server/private/rpl_gtid.h000064400000032563151027430560012662 0ustar00/* Copyright (c) 2013, Kristian Nielsen and MariaDB Services Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef RPL_GTID_H #define RPL_GTID_H #include "hash.h" #include "queues.h" #include /* Definitions for MariaDB global transaction ID (GTID). */ extern const LEX_CSTRING rpl_gtid_slave_state_table_name; class String; #define PARAM_GTID(G) G.domain_id, G.server_id, G.seq_no #define GTID_MAX_STR_LENGTH (10+1+10+1+20) struct rpl_gtid { uint32 domain_id; uint32 server_id; uint64 seq_no; }; inline bool operator==(const rpl_gtid& lhs, const rpl_gtid& rhs) { return lhs.domain_id == rhs.domain_id && lhs.server_id == rhs.server_id && lhs.seq_no == rhs.seq_no; }; enum enum_gtid_skip_type { GTID_SKIP_NOT, GTID_SKIP_STANDALONE, GTID_SKIP_TRANSACTION }; /* Structure to keep track of threads waiting in MASTER_GTID_WAIT(). Since replication is (mostly) single-threaded, we want to minimise the performance impact on that from MASTER_GTID_WAIT(). To achieve this, we are careful to keep the common lock between replication threads and MASTER_GTID_WAIT threads held for as short as possible. We keep only a single thread waiting to be notified by the replication threads; this thread then handles all the (potentially heavy) lifting of dealing with all current waiting threads. */ struct gtid_waiting { /* Elements in the hash, basically a priority queue for each domain. */ struct hash_element { QUEUE queue; uint32 domain_id; }; /* A priority queue to handle waiters in one domain in seq_no order. */ struct queue_element { uint64 wait_seq_no; THD *thd; int queue_idx; /* do_small_wait is true if we have responsibility for ensuring that there is a small waiter. */ bool do_small_wait; /* The flag `done' is set when the wait is completed (either due to reaching the position waited for, or due to timeout or kill). The queue_element is in the queue if and only if `done' is true. */ bool done; }; mysql_mutex_t LOCK_gtid_waiting; HASH hash; void init(); void destroy(); hash_element *get_entry(uint32 domain_id); int wait_for_pos(THD *thd, String *gtid_str, longlong timeout_us); void promote_new_waiter(gtid_waiting::hash_element *he); int wait_for_gtid(THD *thd, rpl_gtid *wait_gtid, struct timespec *wait_until); void process_wait_hash(uint64 wakeup_seq_no, gtid_waiting::hash_element *he); int register_in_wait_queue(THD *thd, rpl_gtid *wait_gtid, hash_element *he, queue_element *elem); void remove_from_wait_queue(hash_element *he, queue_element *elem); }; class Relay_log_info; struct rpl_group_info; class Gtid_list_log_event; /* Replication slave state. For every independent replication stream (identified by domain_id), this remembers the last gtid applied on the slave within this domain. Since events are always committed in-order within a single domain, this is sufficient to maintain the state of the replication slave. */ struct rpl_slave_state { /* Elements in the list of GTIDs kept for each domain_id. */ struct list_element { struct list_element *next; uint64 sub_id; uint32 domain_id; uint32 server_id; uint64 seq_no; /* hton of mysql.gtid_slave_pos* table used to record this GTID. Can be NULL if the gtid table failed to load (eg. missing mysql.gtid_slave_pos table following an upgrade). */ void *hton; }; /* Elements in the HASH that hold the state for one domain_id. */ struct element { struct list_element *list; uint32 domain_id; /* Highest seq_no seen so far in this domain. */ uint64 highest_seq_no; /* If this is non-NULL, then it is the waiter responsible for the small wait in MASTER_GTID_WAIT(). */ gtid_waiting::queue_element *gtid_waiter; /* If gtid_waiter is non-NULL, then this is the seq_no that its MASTER_GTID_WAIT() is waiting on. When we reach this seq_no, we need to signal the waiter on COND_wait_gtid. */ uint64 min_wait_seq_no; mysql_cond_t COND_wait_gtid; /* For --gtid-ignore-duplicates. The Relay_log_info that currently owns this domain, and the number of worker threads that are active in it. The idea is that only one of multiple master connections is allowed to actively apply events for a given domain. Other connections must either discard the events (if the seq_no in GTID shows they have already been applied), or wait to see if the current owner will apply it. */ const Relay_log_info *owner_rli; uint32 owner_count; mysql_cond_t COND_gtid_ignore_duplicates; list_element *grab_list() { list_element *l= list; list= NULL; return l; } void add(list_element *l) { l->next= list; list= l; } }; /* Descriptor for mysql.gtid_slave_posXXX table in specific engine. */ enum gtid_pos_table_state { GTID_POS_AUTO_CREATE, GTID_POS_CREATE_REQUESTED, GTID_POS_CREATE_IN_PROGRESS, GTID_POS_AVAILABLE }; struct gtid_pos_table { struct gtid_pos_table *next; /* Use a void * here, rather than handlerton *, to make explicit that we are not using the value to access any functionality in the engine. It is just used as an opaque value to identify which engine we are using for each GTID row. */ void *table_hton; LEX_CSTRING table_name; uint8 state; }; /* Mapping from domain_id to its element. */ HASH hash; /* GTIDs added since last purge of old mysql.gtid_slave_pos rows. */ uint32 pending_gtid_count; /* Mutex protecting access to the state. */ mysql_mutex_t LOCK_slave_state; /* Auxiliary buffer to sort gtid list. */ DYNAMIC_ARRAY gtid_sort_array; uint64 last_sub_id; /* List of tables available for durably storing the slave GTID position. Accesses to this table is protected by LOCK_slave_state. However for efficiency, there is also a provision for read access to it from a running slave without lock. An element can be added at the head of a list by storing the new gtid_pos_tables pointer atomically with release semantics, to ensure that the next pointer of the new element is visible to readers of the new list. Other changes (like deleting or replacing elements) must happen only while all SQL driver threads are stopped. LOCK_slave_state must be held in any case. The list can be read without lock by an SQL driver thread or worker thread by reading the gtid_pos_tables pointer atomically with acquire semantics, to ensure that it will see the correct next pointer of a new head element. */ std::atomic gtid_pos_tables; /* The default entry in gtid_pos_tables, mysql.gtid_slave_pos. */ std::atomic default_gtid_pos_table; bool loaded; rpl_slave_state(); ~rpl_slave_state(); void truncate_hash(); ulong count() const { return hash.records; } int update(uint32 domain_id, uint32 server_id, uint64 sub_id, uint64 seq_no, void *hton, rpl_group_info *rgi); int update_nolock(uint32 domain_id, uint32 server_id, uint64 sub_id, uint64 seq_no, void *hton, rpl_group_info *rgi); int truncate_state_table(THD *thd); void select_gtid_pos_table(THD *thd, LEX_CSTRING *out_tablename); int record_gtid(THD *thd, const rpl_gtid *gtid, uint64 sub_id, bool in_transaction, bool in_statement, void **out_hton); list_element *gtid_grab_pending_delete_list(); LEX_CSTRING *select_gtid_pos_table(void *hton); void gtid_delete_pending(THD *thd, rpl_slave_state::list_element **list_ptr); uint64 next_sub_id(uint32 domain_id); int iterate(int (*cb)(rpl_gtid *, void *), void *data, rpl_gtid *extra_gtids, uint32 num_extra, bool sort); int tostring(String *dest, rpl_gtid *extra_gtids, uint32 num_extra); bool domain_to_gtid(uint32 domain_id, rpl_gtid *out_gtid); int load(THD *thd, const char *state_from_master, size_t len, bool reset, bool in_statement); bool is_empty(); element *get_element(uint32 domain_id); int put_back_list(list_element *list); void update_state_hash(uint64 sub_id, rpl_gtid *gtid, void *hton, rpl_group_info *rgi); int record_and_update_gtid(THD *thd, struct rpl_group_info *rgi); int check_duplicate_gtid(rpl_gtid *gtid, rpl_group_info *rgi); void release_domain_owner(rpl_group_info *rgi); void set_gtid_pos_tables_list(gtid_pos_table *new_list, gtid_pos_table *default_entry); void add_gtid_pos_table(gtid_pos_table *entry); struct gtid_pos_table *alloc_gtid_pos_table(LEX_CSTRING *table_name, void *hton, rpl_slave_state::gtid_pos_table_state state); void free_gtid_pos_tables(struct gtid_pos_table *list); }; /* Binlog state. This keeps the last GTID written to the binlog for every distinct (domain_id, server_id) pair. This will be logged at the start of the next binlog file as a Gtid_list_log_event; this way, it is easy to find the binlog file containing a given GTID, by simply scanning backwards from the newest one until a lower seq_no is found in the Gtid_list_log_event at the start of a binlog for the given domain_id and server_id. We also remember the last logged GTID for every domain_id. This is used to know where to start when a master is changed to a slave. As a side effect, it also allows to skip a hash lookup in the very common case of logging a new GTID with same server id as last GTID. */ struct rpl_binlog_state { struct element { uint32 domain_id; HASH hash; /* Containing all server_id for one domain_id */ /* The most recent entry in the hash. */ rpl_gtid *last_gtid; /* Counter to allocate next seq_no for this domain. */ uint64 seq_no_counter; int update_element(const rpl_gtid *gtid); }; /* Mapping from domain_id to collection of elements. */ HASH hash; /* Mutex protecting access to the state. */ mysql_mutex_t LOCK_binlog_state; my_bool initialized; /* Auxiliary buffer to sort gtid list. */ DYNAMIC_ARRAY gtid_sort_array; rpl_binlog_state() :initialized(0) {} ~rpl_binlog_state(); void init(); void reset_nolock(); void reset(); void free(); bool load(struct rpl_gtid *list, uint32 count); bool load(rpl_slave_state *slave_pos); int update_nolock(const struct rpl_gtid *gtid, bool strict); int update(const struct rpl_gtid *gtid, bool strict); int update_with_next_gtid(uint32 domain_id, uint32 server_id, rpl_gtid *gtid); int alloc_element_nolock(const rpl_gtid *gtid); bool check_strict_sequence(uint32 domain_id, uint32 server_id, uint64 seq_no, bool no_error= false); int bump_seq_no_if_needed(uint32 domain_id, uint64 seq_no); int write_to_iocache(IO_CACHE *dest); int read_from_iocache(IO_CACHE *src); uint32 count(); int get_gtid_list(rpl_gtid *gtid_list, uint32 list_size); int get_most_recent_gtid_list(rpl_gtid **list, uint32 *size); bool append_pos(String *str); bool append_state(String *str); rpl_gtid *find_nolock(uint32 domain_id, uint32 server_id); rpl_gtid *find(uint32 domain_id, uint32 server_id); rpl_gtid *find_most_recent(uint32 domain_id); const char* drop_domain(DYNAMIC_ARRAY *ids, Gtid_list_log_event *glev, char*); }; /* Represent the GTID state that a slave connection to a master requests the master to start sending binlog events from. */ struct slave_connection_state { struct entry { rpl_gtid gtid; uint32 flags; }; /* Bits for 'flags' */ enum start_flags { START_OWN_SLAVE_POS= 0x1, START_ON_EMPTY_DOMAIN= 0x2 }; /* Mapping from domain_id to the entry with GTID requested for that domain. */ HASH hash; /* Auxiliary buffer to sort gtid list. */ DYNAMIC_ARRAY gtid_sort_array; slave_connection_state(); ~slave_connection_state(); void reset() { my_hash_reset(&hash); } int load(const char *slave_request, size_t len); int load(const rpl_gtid *gtid_list, uint32 count); int load(rpl_slave_state *state, rpl_gtid *extra_gtids, uint32 num_extra); rpl_gtid *find(uint32 domain_id); entry *find_entry(uint32 domain_id); int update(const rpl_gtid *in_gtid); void remove(const rpl_gtid *gtid); void remove_if_present(const rpl_gtid *in_gtid); ulong count() const { return hash.records; } int to_string(String *out_str); int append_to_string(String *out_str); int get_gtid_list(rpl_gtid *gtid_list, uint32 list_size); bool is_pos_reached(); }; extern bool rpl_slave_state_tostring_helper(String *dest, const rpl_gtid *gtid, bool *first); extern int gtid_check_rpl_slave_state_table(TABLE *table); extern rpl_gtid *gtid_parse_string_to_list(const char *p, size_t len, uint32 *out_len); #endif /* RPL_GTID_H */ mysql/server/private/my_stacktrace.h000064400000006217151027430560013704 0ustar00/* Copyright (c) 2001, 2011, Oracle and/or its affiliates. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_stacktrace_h_ #define _my_stacktrace_h_ #ifdef TARGET_OS_LINUX #if defined (__x86_64__) || defined (__i386__) || \ (defined(__alpha__) && defined(__GNUC__)) #define HAVE_STACKTRACE 1 #endif #elif defined(_WIN32) || defined(HAVE_PRINTSTACK) #define HAVE_STACKTRACE 1 #endif #if HAVE_BACKTRACE && (HAVE_BACKTRACE_SYMBOLS || HAVE_BACKTRACE_SYMBOLS_FD) #undef HAVE_STACKTRACE #define HAVE_STACKTRACE 1 #endif #define HAVE_WRITE_CORE #if HAVE_BACKTRACE && HAVE_BACKTRACE_SYMBOLS && HAVE_ABI_CXA_DEMANGLE && \ HAVE_WEAK_SYMBOL #define BACKTRACE_DEMANGLE 1 #endif C_MODE_START #if defined(HAVE_STACKTRACE) || defined(HAVE_BACKTRACE) void my_print_stacktrace(uchar* stack_bottom, ulong thread_stack, my_bool silent); int my_safe_print_str(const char* val, size_t max_len); void my_write_core(int sig); # if BACKTRACE_DEMANGLE char *my_demangle(const char *mangled_name, int *status); # endif /* BACKTRACE_DEMANGLE */ # ifdef _WIN32 # define my_setup_stacktrace() void my_set_exception_pointers(EXCEPTION_POINTERS *ep); # else void my_setup_stacktrace(void); # endif /* _WIN32 */ #else # define my_setup_stacktrace() #endif /* ! (defined(HAVE_STACKTRACE) || defined(HAVE_BACKTRACE)) */ #ifndef _WIN32 #define MY_ADDR_RESOLVE_FORK #endif #if defined(HAVE_BFD_H) || defined(MY_ADDR_RESOLVE_FORK) #define HAVE_MY_ADDR_RESOLVE 1 #endif typedef struct { const char *file; const char *func; uint line; } my_addr_loc; #ifdef HAVE_MY_ADDR_RESOLVE int my_addr_resolve(void *ptr, my_addr_loc *loc); const char *my_addr_resolve_init(); #else #define my_addr_resolve_init() (0) #define my_addr_resolve(A,B) (1) #endif #ifdef HAVE_WRITE_CORE void my_write_core(int sig); #endif /** A (very) limited version of snprintf, which writes the result to STDERR. @sa my_safe_snprintf Implemented with simplicity, and async-signal-safety in mind. @note Has an internal buffer capacity of 512 bytes, which should suffice for our signal handling routines. */ size_t my_safe_printf_stderr(const char* fmt, ...) ATTRIBUTE_FORMAT(printf, 1, 2); /** Writes up to count bytes from buffer to STDERR. Implemented with simplicity, and async-signal-safety in mind. @param buf Buffer containing data to be written. @param count Number of bytes to write. @returns Number of bytes written. */ size_t my_write_stderr(const void *buf, size_t count); C_MODE_END #endif /* _my_stacktrace_h_ */ mysql/server/private/sql_lex.h000064400000521004151027430560012516 0ustar00/* Copyright (c) 2000, 2019, Oracle and/or its affiliates. Copyright (c) 2010, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @defgroup Semantic_Analysis Semantic Analysis */ #ifndef SQL_LEX_INCLUDED #define SQL_LEX_INCLUDED #include "violite.h" /* SSL_type */ #include "sql_trigger.h" #include "thr_lock.h" /* thr_lock_type, TL_UNLOCK */ #include "mem_root_array.h" #include "grant.h" #include "sql_cmd.h" #include "sql_alter.h" // Alter_info #include "sql_window.h" #include "sql_trigger.h" #include "sp.h" // enum enum_sp_type #include "sql_tvc.h" #include "item.h" #include "sql_limit.h" // Select_limit_counters #include "json_table.h" // Json_table_column #include "sql_schema.h" #include "table.h" /* Used for flags of nesting constructs */ #define SELECT_NESTING_MAP_SIZE 64 typedef Bitmap nesting_map; /* YACC and LEX Definitions */ /** A string with metadata. Usually points to a string in the client character set, but unlike Lex_ident_cli_st (see below) it does not necessarily point to a query fragment. It can also point to memory of other kinds (e.g. an additional THD allocated memory buffer not overlapping with the current query text). We'll add more flags here eventually, to know if the string has, e.g.: - multi-byte characters - bad byte sequences - backslash escapes: 'a\nb' and reuse the original query fragments instead of making the string copy too early, in Lex_input_stream::get_text(). This will allow to avoid unnecessary copying, as well as create more optimal Item types in sql_yacc.yy */ struct Lex_string_with_metadata_st: public LEX_CSTRING { private: bool m_is_8bit; // True if the string has 8bit characters char m_quote; // Quote character, or 0 if not quoted public: void set_8bit(bool is_8bit) { m_is_8bit= is_8bit; } void set_metadata(bool is_8bit, char quote) { m_is_8bit= is_8bit; m_quote= quote; } void set(const char *s, size_t len, bool is_8bit, char quote) { str= s; length= len; set_metadata(is_8bit, quote); } void set(const LEX_CSTRING *s, bool is_8bit, char quote) { ((LEX_CSTRING &)*this)= *s; set_metadata(is_8bit, quote); } bool is_8bit() const { return m_is_8bit; } bool is_quoted() const { return m_quote != '\0'; } char quote() const { return m_quote; } // Get string repertoire by the 8-bit flag and the character set my_repertoire_t repertoire(CHARSET_INFO *cs) const { return !m_is_8bit && my_charset_is_ascii_based(cs) ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; } // Get string repertoire by the 8-bit flag, for ASCII-based character sets my_repertoire_t repertoire() const { return !m_is_8bit ? MY_REPERTOIRE_ASCII : MY_REPERTOIRE_UNICODE30; } }; /* Used to store identifiers in the client character set. Points to a query fragment. */ struct Lex_ident_cli_st: public Lex_string_with_metadata_st { public: void set_keyword(const char *s, size_t len) { set(s, len, false, '\0'); } void set_ident(const char *s, size_t len, bool is_8bit) { set(s, len, is_8bit, '\0'); } void set_ident_quoted(const char *s, size_t len, bool is_8bit, char quote) { set(s, len, is_8bit, quote); } void set_unquoted(const LEX_CSTRING *s, bool is_8bit) { set(s, is_8bit, '\0'); } const char *pos() const { return str - is_quoted(); } const char *end() const { return str + length + is_quoted(); } }; class Lex_ident_cli: public Lex_ident_cli_st { public: Lex_ident_cli(const LEX_CSTRING *s, bool is_8bit) { set_unquoted(s, is_8bit); } Lex_ident_cli(const char *s, size_t len) { set_ident(s, len, false); } }; struct Lex_ident_sys_st: public LEX_CSTRING { public: static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); } static void operator delete(void *ptr, MEM_ROOT *mem_root) {} bool copy_ident_cli(THD *thd, const Lex_ident_cli_st *str); bool copy_keyword(THD *thd, const Lex_ident_cli_st *str); bool copy_sys(THD *thd, const LEX_CSTRING *str); bool convert(THD *thd, const LEX_CSTRING *str, CHARSET_INFO *cs); bool copy_or_convert(THD *thd, const Lex_ident_cli_st *str, CHARSET_INFO *cs); bool is_null() const { return str == NULL; } bool to_size_number(ulonglong *to) const; void set_valid_utf8(const LEX_CSTRING *name) { DBUG_ASSERT(Well_formed_prefix(system_charset_info, name->str, name->length).length() == name->length); str= name->str ; length= name->length; } }; class Lex_ident_sys: public Lex_ident_sys_st { public: Lex_ident_sys(THD *thd, const Lex_ident_cli_st *str) { if (copy_ident_cli(thd, str)) ((LEX_CSTRING &) *this)= null_clex_str; } Lex_ident_sys() { ((LEX_CSTRING &) *this)= null_clex_str; } Lex_ident_sys(const char *name, size_t length) { LEX_CSTRING tmp= {name, length}; set_valid_utf8(&tmp); } Lex_ident_sys(THD *thd, const LEX_CSTRING *str) { set_valid_utf8(str); } Lex_ident_sys & operator=(const Lex_ident_sys_st &name) { Lex_ident_sys_st::operator=(name); return *this; } }; struct Lex_column_list_privilege_st { List *m_columns; privilege_t m_privilege; }; class Lex_column_list_privilege: public Lex_column_list_privilege_st { public: Lex_column_list_privilege(List *columns, privilege_t privilege) { m_columns= columns; m_privilege= privilege; } }; /** ORDER BY ... LIMIT parameters; */ class Lex_order_limit_lock: public Sql_alloc { public: SQL_I_List *order_list; /* ORDER clause */ Lex_select_lock lock; Lex_select_limit limit; Lex_order_limit_lock() :order_list(NULL) {} bool set_to(st_select_lex *sel); }; enum sub_select_type { UNSPECIFIED_TYPE, /* following 3 enums should be as they are*/ UNION_TYPE, INTERSECT_TYPE, EXCEPT_TYPE, GLOBAL_OPTIONS_TYPE, DERIVED_TABLE_TYPE, OLAP_TYPE }; enum set_op_type { UNSPECIFIED, UNION_DISTINCT, UNION_ALL, EXCEPT_DISTINCT, EXCEPT_ALL, INTERSECT_DISTINCT, INTERSECT_ALL }; inline int cmp_unit_op(enum sub_select_type op1, enum sub_select_type op2) { DBUG_ASSERT(op1 >= UNION_TYPE && op1 <= EXCEPT_TYPE); DBUG_ASSERT(op2 >= UNION_TYPE && op2 <= EXCEPT_TYPE); return (op1 == INTERSECT_TYPE ? 1 : 0) - (op2 == INTERSECT_TYPE ? 1 : 0); } enum unit_common_op {OP_MIX, OP_UNION, OP_INTERSECT, OP_EXCEPT}; enum enum_view_suid { VIEW_SUID_INVOKER= 0, VIEW_SUID_DEFINER= 1, VIEW_SUID_DEFAULT= 2 }; enum plsql_cursor_attr_t { PLSQL_CURSOR_ATTR_ISOPEN, PLSQL_CURSOR_ATTR_FOUND, PLSQL_CURSOR_ATTR_NOTFOUND, PLSQL_CURSOR_ATTR_ROWCOUNT }; enum enum_sp_suid_behaviour { SP_IS_DEFAULT_SUID= 0, SP_IS_NOT_SUID, SP_IS_SUID }; enum enum_sp_aggregate_type { DEFAULT_AGGREGATE= 0, NOT_AGGREGATE, GROUP_AGGREGATE }; /* These may not be declared yet */ class Table_ident; class sql_exchange; class LEX_COLUMN; class sp_head; class sp_name; class sp_instr; class sp_pcontext; class sp_variable; class sp_expr_lex; class sp_assignment_lex; class st_alter_tablespace; class partition_info; class Event_parse_data; class set_var_base; class sys_var; class Item_func_match; class File_parser; class Key_part_spec; class Item_window_func; struct sql_digest_state; class With_clause; class my_var; class select_handler; class Pushdown_select; #define ALLOC_ROOT_SET 1024 #ifdef MYSQL_SERVER /* There are 8 different type of table access so there is no more than combinations 2^8 = 256: . STMT_READS_TRANS_TABLE . STMT_READS_NON_TRANS_TABLE . STMT_READS_TEMP_TRANS_TABLE . STMT_READS_TEMP_NON_TRANS_TABLE . STMT_WRITES_TRANS_TABLE . STMT_WRITES_NON_TRANS_TABLE . STMT_WRITES_TEMP_TRANS_TABLE . STMT_WRITES_TEMP_NON_TRANS_TABLE The unsafe conditions for each combination is represented within a byte and stores the status of the option --binlog-direct-non-trans-updates, whether the trx-cache is empty or not, and whether the isolation level is lower than ISO_REPEATABLE_READ: . option (OFF/ON) . trx-cache (empty/not empty) . isolation (>= ISO_REPEATABLE_READ / < ISO_REPEATABLE_READ) bits 0 : . OFF, . empty, . >= ISO_REPEATABLE_READ bits 1 : . OFF, . empty, . < ISO_REPEATABLE_READ bits 2 : . OFF, . not empty, . >= ISO_REPEATABLE_READ bits 3 : . OFF, . not empty, . < ISO_REPEATABLE_READ bits 4 : . ON, . empty, . >= ISO_REPEATABLE_READ bits 5 : . ON, . empty, . < ISO_REPEATABLE_READ bits 6 : . ON, . not empty, . >= ISO_REPEATABLE_READ bits 7 : . ON, . not empty, . < ISO_REPEATABLE_READ */ extern uint binlog_unsafe_map[256]; /* Initializes the array with unsafe combinations and its respective conditions. */ void binlog_unsafe_map_init(); #endif #ifdef MYSQL_SERVER /* The following hack is needed because yy_*.cc do not define YYSTYPE before including this file */ #ifdef MYSQL_YACC #define LEX_YYSTYPE void * #else #include "lex_symbol.h" #ifdef MYSQL_LEX #include "item_func.h" /* Cast_target used in yy_mariadb.hh */ #include "sql_get_diagnostics.h" /* Types used in yy_mariadb.hh */ #include "sp_pcontext.h" #include "yy_mariadb.hh" #define LEX_YYSTYPE YYSTYPE * #else #define LEX_YYSTYPE void * #endif #endif #endif // describe/explain types #define DESCRIBE_NORMAL 1 #define DESCRIBE_EXTENDED 2 /* This is not within #ifdef because we want "EXPLAIN PARTITIONS ..." to produce additional "partitions" column even if partitioning is not compiled in. */ #define DESCRIBE_PARTITIONS 4 #define DESCRIBE_EXTENDED2 8 #ifdef MYSQL_SERVER extern const LEX_STRING empty_lex_str; extern const LEX_CSTRING empty_clex_str; extern const LEX_CSTRING star_clex_str; extern const LEX_CSTRING param_clex_str; enum enum_sp_data_access { SP_DEFAULT_ACCESS= 0, SP_CONTAINS_SQL, SP_NO_SQL, SP_READS_SQL_DATA, SP_MODIFIES_SQL_DATA }; const LEX_CSTRING sp_data_access_name[]= { { STRING_WITH_LEN("") }, { STRING_WITH_LEN("CONTAINS SQL") }, { STRING_WITH_LEN("NO SQL") }, { STRING_WITH_LEN("READS SQL DATA") }, { STRING_WITH_LEN("MODIFIES SQL DATA") } }; #define DERIVED_SUBQUERY 1 #define DERIVED_VIEW 2 #define DERIVED_WITH 4 enum enum_view_create_mode { VIEW_CREATE_NEW, // check that there are not such VIEW/table VIEW_ALTER, // check that VIEW .frm with such name exists VIEW_CREATE_OR_REPLACE // check only that there are not such table }; class Create_view_info: public Sql_alloc { public: LEX_CSTRING select; // The SELECT statement of CREATE VIEW enum enum_view_create_mode mode; uint16 algorithm; uint8 check; enum enum_view_suid suid; Create_view_info(enum_view_create_mode mode_arg, uint16 algorithm_arg, enum_view_suid suid_arg) :select(null_clex_str), mode(mode_arg), algorithm(algorithm_arg), check(VIEW_CHECK_NONE), suid(suid_arg) { } }; enum enum_drop_mode { DROP_DEFAULT, // mode is not specified DROP_CASCADE, // CASCADE option DROP_RESTRICT // RESTRICT option }; /* Options to add_table_to_list() */ #define TL_OPTION_UPDATING 1 #define TL_OPTION_FORCE_INDEX 2 #define TL_OPTION_IGNORE_LEAVES 4 #define TL_OPTION_ALIAS 8 #define TL_OPTION_SEQUENCE 16 #define TL_OPTION_TABLE_FUNCTION 32 typedef List List_item; typedef Mem_root_array Group_list_ptrs; /* SERVERS CACHE CHANGES */ typedef struct st_lex_server_options { long port; LEX_CSTRING server_name, host, db, username, password, scheme, socket, owner; void reset(LEX_CSTRING name) { server_name= name; host= db= username= password= scheme= socket= owner= null_clex_str; port= -1; } } LEX_SERVER_OPTIONS; /** Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE. Remark: this should not be confused with Master_info (and perhaps would better be renamed to st_lex_replication_info). Some fields, e.g., delay, are saved in Relay_log_info, not in Master_info. */ struct LEX_MASTER_INFO { DYNAMIC_ARRAY repl_ignore_server_ids; DYNAMIC_ARRAY repl_do_domain_ids; DYNAMIC_ARRAY repl_ignore_domain_ids; const char *host, *user, *password, *log_file_name; const char *ssl_key, *ssl_cert, *ssl_ca, *ssl_capath, *ssl_cipher; const char *ssl_crl, *ssl_crlpath; const char *relay_log_name; LEX_CSTRING connection_name; /* Value in START SLAVE UNTIL master_gtid_pos=xxx */ LEX_CSTRING gtid_pos_str; ulonglong pos; ulong relay_log_pos; ulong server_id; uint port, connect_retry; float heartbeat_period; int sql_delay; /* Enum is used for making it possible to detect if the user changed variable or if it should be left at old value */ enum {LEX_MI_UNCHANGED= 0, LEX_MI_DISABLE, LEX_MI_ENABLE} ssl, ssl_verify_server_cert, heartbeat_opt, repl_ignore_server_ids_opt, repl_do_domain_ids_opt, repl_ignore_domain_ids_opt; enum { LEX_GTID_UNCHANGED, LEX_GTID_NO, LEX_GTID_CURRENT_POS, LEX_GTID_SLAVE_POS } use_gtid_opt; void init() { bzero(this, sizeof(*this)); my_init_dynamic_array(PSI_INSTRUMENT_ME, &repl_ignore_server_ids, sizeof(::server_id), 0, 16, MYF(0)); my_init_dynamic_array(PSI_INSTRUMENT_ME, &repl_do_domain_ids, sizeof(ulong), 0, 16, MYF(0)); my_init_dynamic_array(PSI_INSTRUMENT_ME, &repl_ignore_domain_ids, sizeof(ulong), 0, 16, MYF(0)); sql_delay= -1; } void reset(bool is_change_master) { if (unlikely(is_change_master)) { delete_dynamic(&repl_ignore_server_ids); /* Free all the array elements. */ delete_dynamic(&repl_do_domain_ids); delete_dynamic(&repl_ignore_domain_ids); } host= user= password= log_file_name= ssl_key= ssl_cert= ssl_ca= ssl_capath= ssl_cipher= ssl_crl= ssl_crlpath= relay_log_name= NULL; pos= relay_log_pos= server_id= port= connect_retry= 0; heartbeat_period= 0; ssl= ssl_verify_server_cert= heartbeat_opt= repl_ignore_server_ids_opt= repl_do_domain_ids_opt= repl_ignore_domain_ids_opt= LEX_MI_UNCHANGED; gtid_pos_str= null_clex_str; use_gtid_opt= LEX_GTID_UNCHANGED; sql_delay= -1; } }; typedef struct st_lex_reset_slave { bool all; } LEX_RESET_SLAVE; enum olap_type { UNSPECIFIED_OLAP_TYPE, CUBE_TYPE, ROLLUP_TYPE }; /* String names used to print a statement with index hints. Keep in sync with index_hint_type. */ extern const char * index_hint_type_name[]; typedef uchar index_clause_map; /* Bits in index_clause_map : one for each possible FOR clause in USE/FORCE/IGNORE INDEX index hint specification */ #define INDEX_HINT_MASK_JOIN (1) #define INDEX_HINT_MASK_GROUP (1 << 1) #define INDEX_HINT_MASK_ORDER (1 << 2) #define INDEX_HINT_MASK_ALL (INDEX_HINT_MASK_JOIN | INDEX_HINT_MASK_GROUP | \ INDEX_HINT_MASK_ORDER) class select_result_sink; /* Single element of an USE/FORCE/IGNORE INDEX list specified as a SQL hint */ class Index_hint : public Sql_alloc { public: /* The type of the hint : USE/FORCE/IGNORE */ enum index_hint_type type; /* Where the hit applies to. A bitmask of INDEX_HINT_MASK_ values */ index_clause_map clause; /* The index name. Empty (str=NULL) name represents an empty list USE INDEX () clause */ LEX_CSTRING key_name; Index_hint (enum index_hint_type type_arg, index_clause_map clause_arg, const char *str, size_t length) : type(type_arg), clause(clause_arg) { key_name.str= str; key_name.length= length; } void print(THD *thd, String *str); }; /* The state of the lex parsing for selects master and slaves are pointers to select_lex. master is pointer to upper level node. slave is pointer to lower level node select_lex is a SELECT without union unit is container of either - One SELECT - UNION of selects select_lex and unit are both inherited form st_select_lex_node neighbors are two select_lex or units on the same level All select describing structures linked with following pointers: - list of neighbors (next/prev) (prev of first element point to slave pointer of upper structure) - For select this is a list of UNION's (or one element list) - For units this is a list of sub queries for the upper level select - pointer to master (master), which is If this is a unit - pointer to outer select_lex If this is a select_lex - pointer to outer unit structure for select - pointer to slave (slave), which is either: If this is a unit: - first SELECT that belong to this unit If this is a select_lex - first unit that belong to this SELECT (subquries or derived tables) - list of all select_lex (link_next/link_prev) This is to be used for things like derived tables creation, where we go through this list and create the derived tables. If unit contain several selects (UNION now, INTERSECT etc later) then it have special select_lex called fake_select_lex. It used for storing global parameters (like ORDER BY, LIMIT) and executing union. Subqueries used in global ORDER BY clause will be attached to this fake_select_lex, which will allow them correctly resolve fields of 'upper' UNION and outer selects. For example for following query: select * from table1 where table1.field IN (select * from table1_1_1 union select * from table1_1_2) union select * from table2 where table2.field=(select (select f1 from table2_1_1_1_1 where table2_1_1_1_1.f2=table2_1_1.f3) from table2_1_1 where table2_1_1.f1=table2.f2) union select * from table3; we will have following structure: select1: (select * from table1 ...) select2: (select * from table2 ...) select3: (select * from table3) select1.1.1: (select * from table1_1_1) ... main unit fake0 select1 select2 select3 |^^ |^ s||| ||master l||| |+---------------------------------+ a||| +---------------------------------+| v|||master slave || e||+-------------------------+ || V| neighbor | V| unit1.1<+==================>unit1.2 unit2.1 fake1.1 select1.1.1 select 1.1.2 select1.2.1 select2.1.1 |^ || V| unit2.1.1.1 select2.1.1.1.1 relation in main unit will be following: (bigger picture for: main unit fake0 select1 select2 select3 in the above picture) main unit |^^^^|fake_select_lex |||||+--------------------------------------------+ ||||+--------------------------------------------+| |||+------------------------------+ || ||+--------------+ | || slave||master | | || V| neighbor | neighbor | master|V select1<========>select2<========>select3 fake0 list of all select_lex will be following (as it will be constructed by parser): select1->select2->select3->select2.1.1->select 2.1.2->select2.1.1.1.1-+ | +---------------------------------------------------------------------+ | +->select1.1.1->select1.1.2 */ /* Base class for st_select_lex (SELECT_LEX) & st_select_lex_unit (SELECT_LEX_UNIT) */ struct LEX; class st_select_lex; class st_select_lex_unit; class st_select_lex_node { protected: st_select_lex_node *next, **prev, /* neighbor list */ *master, *slave, /* vertical links */ *link_next, **link_prev; /* list of whole SELECT_LEX */ enum sub_select_type linkage; void init_query_common(); public: ulonglong options; uint8 uncacheable; bool distinct:1; bool no_table_names_allowed:1; /* used for global order by */ /* result of this query can't be cached, bit field, can be : UNCACHEABLE_DEPENDENT_GENERATED UNCACHEABLE_DEPENDENT_INJECTED UNCACHEABLE_RAND UNCACHEABLE_SIDEEFFECT UNCACHEABLE_EXPLAIN UNCACHEABLE_PREPARE */ bool is_linkage_set() const { return linkage == UNION_TYPE || linkage == INTERSECT_TYPE || linkage == EXCEPT_TYPE; } enum sub_select_type get_linkage() { return linkage; } static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return (void*) alloc_root(mem_root, (uint) size); } static void operator delete(void *ptr,size_t size) { TRASH_FREE(ptr, size); } static void operator delete(void *ptr, MEM_ROOT *mem_root) {} // Ensures that at least all members used during cleanup() are initialized. st_select_lex_node() : next(NULL), prev(NULL), master(NULL), slave(NULL), link_next(NULL), link_prev(NULL), linkage(UNSPECIFIED_TYPE) { } inline st_select_lex_node* get_master() { return master; } void include_down(st_select_lex_node *upper); void attach_single(st_select_lex_node *slave_arg); void include_neighbour(st_select_lex_node *before); void link_chain_down(st_select_lex_node *first); void link_neighbour(st_select_lex_node *neighbour) { DBUG_ASSERT(next == NULL); DBUG_ASSERT(neighbour != NULL); next= neighbour; neighbour->prev= &next; } void cut_next() { next= NULL; } void include_standalone(st_select_lex_node *sel, st_select_lex_node **ref); void include_global(st_select_lex_node **plink); void exclude(); void exclude_from_tree(); void exclude_from_global() { if (!link_prev) return; if (((*link_prev)= link_next)) link_next->link_prev= link_prev; link_next= NULL; link_prev= NULL; } void substitute_in_tree(st_select_lex_node *subst); void set_slave(st_select_lex_node *slave_arg) { slave= slave_arg; } void move_node(st_select_lex_node *where_to_move) { if (where_to_move == this) return; if (next) next->prev= prev; *prev= next; *where_to_move->prev= this; next= where_to_move; } st_select_lex_node *insert_chain_before(st_select_lex_node **ptr_pos_to_insert, st_select_lex_node *end_chain_node); void move_as_slave(st_select_lex_node *new_master); void set_linkage(enum sub_select_type l) { DBUG_ENTER("st_select_lex_node::set_linkage"); DBUG_PRINT("info", ("node: %p linkage: %d->%d", this, linkage, l)); linkage= l; DBUG_VOID_RETURN; } /* This method created for reiniting LEX in mysql_admin_table() and can be used only if you are going remove all SELECT_LEX & units except belonger to LEX (LEX::unit & LEX::select, for other purposes there are SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree. It is also used in parsing to detach builtin select. */ void cut_subtree() { slave= 0; } friend class st_select_lex_unit; friend bool mysql_new_select(LEX *lex, bool move_down, SELECT_LEX *sel); friend bool mysql_make_view(THD *thd, TABLE_SHARE *share, TABLE_LIST *table, bool open_view_no_parse); friend class st_select_lex; private: void fast_exclude(); }; typedef class st_select_lex_node SELECT_LEX_NODE; /* SELECT_LEX_UNIT - unit of selects (UNION, INTERSECT, ...) group SELECT_LEXs */ class THD; class select_result; class JOIN; class select_unit; class Procedure; class Explain_query; void delete_explain_query(LEX *lex); void create_explain_query(LEX *lex, MEM_ROOT *mem_root); void create_explain_query_if_not_exists(LEX *lex, MEM_ROOT *mem_root); bool print_explain_for_slow_log(LEX *lex, THD *thd, String *str); class st_select_lex_unit: public st_select_lex_node { protected: TABLE_LIST result_table_list; select_unit *union_result; ulonglong found_rows_for_union; bool prepare_join(THD *thd, SELECT_LEX *sl, select_result *result, ulonglong additional_options, bool is_union_select); bool join_union_type_handlers(THD *thd, class Type_holder *holders, uint count); bool join_union_type_attributes(THD *thd, class Type_holder *holders, uint count); public: bool join_union_item_types(THD *thd, List &types, uint count); // Ensures that at least all members used during cleanup() are initialized. st_select_lex_unit() : union_result(NULL), table(NULL), result(NULL), fake_select_lex(NULL), last_procedure(NULL),cleaned(false), bag_set_op_optimized(false), have_except_all_or_intersect_all(false) { } TABLE *table; /* temporary table using for appending UNION results */ select_result *result; st_select_lex *pre_last_parse; /* Node on which we should return current_select pointer after parsing subquery */ st_select_lex *return_to; /* LIMIT clause runtime counters */ Select_limit_counters lim; /* not NULL if unit used in subselect, point to subselect item */ Item_subselect *item; /* TABLE_LIST representing this union in the embedding select. Used for derived tables/views handling. */ TABLE_LIST *derived; /* With clause attached to this unit (if any) */ With_clause *with_clause; /* With element where this unit is used as the specification (if any) */ With_element *with_element; /* The unit used as a CTE specification from which this unit is cloned */ st_select_lex_unit *cloned_from; /* thread handler */ THD *thd; /* SELECT_LEX for hidden SELECT in union which process global ORDER BY and LIMIT */ st_select_lex *fake_select_lex; /** SELECT_LEX that stores LIMIT and OFFSET for UNION ALL when noq fake_select_lex is used. */ st_select_lex *saved_fake_select_lex; /* pointer to the last node before last subsequence of UNION ALL */ st_select_lex *union_distinct; Procedure *last_procedure; /* Pointer to procedure, if such exists */ // list of fields which points to temporary table for union List item_list; /* list of types of items inside union (used for union & derived tables) Item_type_holders from which this list consist may have pointers to Field, pointers is valid only after preparing SELECTS of this unit and before any SELECT of this unit execution */ List types; bool prepared:1; // prepare phase already performed for UNION (unit) bool optimized:1; // optimize phase already performed for UNION (unit) bool optimized_2:1; bool executed:1; // already executed bool cleaned:1; bool bag_set_op_optimized:1; bool optimize_started:1; bool have_except_all_or_intersect_all:1; /** TRUE if the unit contained TVC at the top level that has been wrapped into SELECT: VALUES (v1) ... (vn) => SELECT * FROM (VALUES (v1) ... (vn)) as tvc */ bool with_wrapped_tvc:1; bool is_view:1; bool describe:1; /* union exec() called for EXPLAIN */ bool columns_are_renamed:1; protected: /* This is bool, not bit, as it's used and set in many places */ bool saved_error; public: /** Pointer to 'last' select, or pointer to select where we stored global parameters for union. If this is a union of multiple selects, the parser puts the global parameters in fake_select_lex. If the union doesn't use a temporary table, st_select_lex_unit::prepare() nulls out fake_select_lex, but saves a copy in saved_fake_select_lex in order to preserve the global parameters. If it is not a union, first_select() is the last select. @return select containing the global parameters */ inline st_select_lex *global_parameters() { if (fake_select_lex != NULL) return fake_select_lex; else if (saved_fake_select_lex != NULL) return saved_fake_select_lex; return first_select(); }; void init_query(); st_select_lex* outer_select(); const st_select_lex* first_select() const { return reinterpret_cast(slave); } st_select_lex* first_select() { return reinterpret_cast(slave); } void set_with_clause(With_clause *with_cl); st_select_lex_unit* next_unit() { return reinterpret_cast(next); } st_select_lex* return_after_parsing() { return return_to; } void exclude_level(); // void exclude_tree(); // it is not used for long time bool is_excluded() { return prev == NULL; } /* UNION methods */ bool prepare(TABLE_LIST *derived_arg, select_result *sel_result, ulonglong additional_options); bool optimize(); void optimize_bag_operation(bool is_outer_distinct); bool exec(); bool exec_recursive(); bool cleanup(); inline void unclean() { cleaned= 0; } void reinit_exec_mechanism(); void print(String *str, enum_query_type query_type); bool add_fake_select_lex(THD *thd); void init_prepare_fake_select_lex(THD *thd, bool first_execution); inline bool is_prepared() { return prepared; } bool change_result(select_result_interceptor *result, select_result_interceptor *old_result); void set_limit(st_select_lex *values); void set_thd(THD *thd_arg) { thd= thd_arg; } inline bool is_unit_op (); bool union_needs_tmp_table(); void set_unique_exclude(); bool check_distinct_in_union(); friend struct LEX; friend int subselect_union_engine::exec(); List *get_column_types(bool for_cursor); select_unit *get_union_result() { return union_result; } int save_union_explain(Explain_query *output); int save_union_explain_part2(Explain_query *output); unit_common_op common_op(); bool explainable() const; void reset_distinct(); void fix_distinct(); void register_select_chain(SELECT_LEX *first_sel); bool set_nest_level(int new_nest_level); bool check_parameters(SELECT_LEX *main_select); bool set_lock_to_the_last_select(Lex_select_lock l); void print_lock_from_the_last_select(String *str); bool can_be_merged(); friend class st_select_lex; }; typedef class st_select_lex_unit SELECT_LEX_UNIT; typedef Bounds_checked_array Ref_ptr_array; /** Structure which consists of the field and the item that corresponds to this field. */ class Field_pair :public Sql_alloc { public: Field *field; Item *corresponding_item; Field_pair(Field *fld, Item *item) :field(fld), corresponding_item(item) {} }; Field_pair *get_corresponding_field_pair(Item *item, List pair_list); Field_pair *find_matching_field_pair(Item *item, List pair_list); #define TOUCHED_SEL_COND 1/* WHERE/HAVING/ON should be reinited before use */ #define TOUCHED_SEL_DERIVED (1<<1)/* derived should be reinited before use */ #define UNIT_NEST_FL 1 /* SELECT_LEX - store information of parsed SELECT statment */ class st_select_lex: public st_select_lex_node { public: /* Currently the field first_nested is used only by parser. It containa either a reference to the first select of the nest of selects to which 'this' belongs to, or in the case of priority jump it contains a reference to the select to which the priority nest has to be attached to. If there is no priority jump then the first select of the nest contains the reference to itself in first_nested. Example: select1 union select2 intersect select Here we have a priority jump at select2. So select2->first_nested points to select1, while select3->first_nested points to select2 and select1->first_nested points to select1. */ Name_resolution_context context; LEX_CSTRING db; /* Point to the LEX in which it was created, used in view subquery detection. TODO: make also st_select_lex::parent_stmt_lex (see LEX::stmt_lex) and use st_select_lex::parent_lex & st_select_lex::parent_stmt_lex instead of global (from THD) references where it is possible. */ LEX *parent_lex; st_select_lex *first_nested; Item *where, *having; /* WHERE & HAVING clauses */ Item *prep_where; /* saved WHERE clause for prepared statement processing */ Item *prep_having;/* saved HAVING clause for prepared statement processing */ Item *cond_pushed_into_where; /* condition pushed into WHERE */ Item *cond_pushed_into_having; /* condition pushed into HAVING */ /* nest_levels are local to the query or VIEW, and that view merge procedure does not re-calculate them. So we also have to remember unit against which we count levels. */ SELECT_LEX_UNIT *nest_level_base; Item_sum *inner_sum_func_list; /* list of sum func in nested selects */ /* This is a copy of the original JOIN USING list that comes from the parser. The parser : 1. Sets the natural_join of the second TABLE_LIST in the join and the st_select_lex::prev_join_using. 2. Makes a parent TABLE_LIST and sets its is_natural_join/ join_using_fields members. 3. Uses the wrapper TABLE_LIST as a table in the upper level. We cannot assign directly to join_using_fields in the parser because at stage (1.) the parent TABLE_LIST is not constructed yet and the assignment will override the JOIN USING fields of the lower level joins on the right. */ List *prev_join_using; JOIN *join; /* after JOIN::prepare it is pointer to corresponding JOIN */ TABLE_LIST *embedding; /* table embedding to the above list */ table_value_constr *tvc; /* The interface employed to execute the select query by a foreign engine */ select_handler *select_h; /* The object used to organize execution of the query by a foreign engine */ select_handler *pushdown_select; List *join_list; /* list for the currently parsed join */ st_select_lex *merged_into; /* select which this select is merged into */ /* (not 0 only for views/derived tables) */ const char *type; /* type of select for EXPLAIN */ /* List of references to fields referenced from inner selects */ List inner_refs_list; List attach_to_conds; /* Saved values of the WHERE and HAVING clauses*/ Item::cond_result cond_value, having_value; /* Usually it is pointer to ftfunc_list_alloc, but in union used to create fake select_lex for calling mysql_select under results of union */ List *ftfunc_list; List ftfunc_list_alloc; /* The list of items to which MIN/MAX optimizations of opt_sum_query() have been applied. Used to rollback those optimizations if it's needed. */ List min_max_opt_list; List top_join_list; /* join list of the top level */ List sj_nests; /* Semi-join nests within this join */ /* Beginning of the list of leaves in a FROM clause, where the leaves inlcude all base tables including view tables. The tables are connected by TABLE_LIST::next_leaf, so leaf_tables points to the left-most leaf. List of all base tables local to a subquery including all view tables. Unlike 'next_local', this in this list views are *not* leaves. Created in setup_tables() -> make_leaves_list(). */ /* Subqueries that will need to be converted to semi-join nests, including those converted to jtbm nests. The list is emptied when conversion is done. */ List sj_subselects; /* List of IN-predicates in this st_select_lex that can be transformed into IN-subselect defined with TVC. */ List in_funcs; /** Flag to guard against double initialization of leaf tables list */ bool leaf_tables_saved; List leaf_tables; List leaf_tables_exec; List leaf_tables_prep; /* current index hint kind. used in filling up index_hints */ enum index_hint_type current_index_hint_type; /* FROM clause - points to the beginning of the TABLE_LIST::next_local list. */ SQL_I_List table_list; /* GROUP BY clause. This list may be mutated during optimization (by remove_const()), so for prepared statements, we keep a copy of the ORDER.next pointers in group_list_ptrs, and re-establish the original list before each execution. */ SQL_I_List group_list; SQL_I_List save_group_list; Group_list_ptrs *group_list_ptrs; List item_list; /* list of fields & expressions */ List pre_fix; /* above list before fix_fields */ List fix_after_optimize; SQL_I_List order_list; /* ORDER clause */ SQL_I_List save_order_list; SQL_I_List gorder_list; Lex_select_limit limit_params; /* LIMIT clause parameters */ /* Structure to store fields that are used in the GROUP BY of this select */ List grouping_tmp_fields; List udf_list; /* udf function calls stack */ List *index_hints; /* list of USE/FORCE/IGNORE INDEX */ /* This list is used to restore the names of items from item_list after each execution of the statement. */ List *orig_names_of_item_list_elems; List save_many_values; List *save_insert_list; bool is_item_list_lookup:1; /* Needed to correctly generate 'PRIMARY' or 'SIMPLE' for select_type column of EXPLAIN */ bool have_merged_subqueries:1; bool is_set_query_expr_tail:1; bool with_sum_func:1; /* sum function indicator */ bool with_rownum:1; /* rownum() function indicator */ bool braces:1; /* SELECT ... UNION (SELECT ... ) <- this braces */ bool automatic_brackets:1; /* dummy select for INTERSECT precedence */ /* TRUE when having fix field called in processing of this SELECT */ bool having_fix_field:1; /* TRUE when fix field is called for a new condition pushed into the HAVING clause of this SELECT */ bool having_fix_field_for_pushed_cond:1; /* there are subquery in HAVING clause => we can't close tables before query processing end even if we use temporary table */ bool subquery_in_having:1; /* TRUE <=> this SELECT is correlated w.r.t. some ancestor select */ bool with_all_modifier:1; /* used for selects in union */ bool is_correlated:1; bool first_natural_join_processing:1; bool first_cond_optimization:1; /** The purpose of this flag is to run initialization phase for rownum only once. This flag is set on at st_select_lex::init_query and reset to the value false after the method optimize_rownum() has been called from the method JOIN::optimize_inner. */ bool first_rownum_optimization:1; /* do not wrap view fields with Item_ref */ bool no_wrap_view_item:1; /* exclude this select from check of unique_table() */ bool exclude_from_table_unique_test:1; bool in_tvc:1; bool skip_locked:1; bool m_non_agg_field_used:1; bool m_agg_func_used:1; bool m_custom_agg_func_used:1; /* the select is "service-select" and can not have tables */ bool is_service_select:1; /// Array of pointers to top elements of all_fields list Ref_ptr_array ref_pointer_array; ulong table_join_options; /* number of items in select_list and HAVING clause used to get number bigger then can be number of entries that will be added to all item list during split_sum_func */ uint select_n_having_items; uint cond_count; /* number of sargable Items in where/having/on */ uint between_count; /* number of between predicates in where/having/on */ uint max_equal_elems; /* max number of elements in multiple equalities */ /* Number of fields used in select list or where clause of current select and all inner subselects. */ uint select_n_where_fields; /* Total number of elements in group by and order by lists */ uint order_group_num; /* reserved for exists 2 in */ uint select_n_reserved; /* it counts the number of bit fields in the SELECT list. These are used when DISTINCT is converted to a GROUP BY involving BIT fields. */ uint hidden_bit_fields; /* Number of fields used in the definition of all the windows functions. This includes: 1) Fields in the arguments 2) Fields in the PARTITION BY clause 3) Fields in the ORDER BY clause */ /* Number of current derived table made with TVC during the transformation of IN-predicate into IN-subquery for this st_select_lex. */ uint curr_tvc_name; /* true <=> select has been created a TVC wrapper */ bool is_tvc_wrapper; uint fields_in_window_functions; uint insert_tables; enum_parsing_place parsing_place; /* where we are parsing expression */ enum_parsing_place save_parsing_place; enum_parsing_place context_analysis_place; /* where we are in prepare */ enum leaf_list_state {UNINIT, READY, SAVED}; enum leaf_list_state prep_leaf_list_state; enum olap_type olap; /* SELECT [FOR UPDATE/LOCK IN SHARE MODE] [SKIP LOCKED] */ enum select_lock_type {NONE, IN_SHARE_MODE, FOR_UPDATE}; enum select_lock_type select_lock; uint in_sum_expr; uint select_number; /* number of select (used for EXPLAIN) */ uint with_wild; /* item list contain '*' ; Counter */ /* Number of Item_sum-derived objects in this SELECT */ uint n_sum_items; /* Number of Item_sum-derived objects in children and descendant SELECTs */ uint n_child_sum_items; uint versioned_tables; /* For versioning */ int nest_level; /* nesting level of select */ /* index in the select list of the expression currently being fixed */ int cur_pos_in_select_list; /* This array is used to note whether we have any candidates for expression caching in the corresponding clauses */ bool expr_cache_may_be_used[PARSING_PLACE_SIZE]; uint8 nest_flags; /* This variable is required to ensure proper work of subqueries and stored procedures. Generally, one should use the states of Query_arena to determine if it's a statement prepare or first execution of a stored procedure. However, in case when there was an error during the first execution of a stored procedure, the SP body is not expelled from the SP cache. Therefore, a deeply nested subquery might be left unoptimized. So we need this per-subquery variable to inidicate the optimization/execution state of every subquery. Prepared statements work OK in that regard, as in case of an error during prepare the PS is not created. */ uint8 changed_elements; // see TOUCHED_SEL_* /** The set of those tables whose fields are referenced in the select list of this select level. */ table_map select_list_tables; /* Set to 1 if any field in field list has ROWNUM() */ bool rownum_in_field_list; /* namp of nesting SELECT visibility (for aggregate functions check) */ nesting_map name_visibility_map; table_map with_dep; index_clause_map current_index_hint_clause; /* it is for correct printing SELECT options */ thr_lock_type lock_type; /** System Versioning */ int vers_setup_conds(THD *thd, TABLE_LIST *tables); /* push new Item_field into item_list */ bool vers_push_field(THD *thd, TABLE_LIST *table, const LEX_CSTRING field_name); int period_setup_conds(THD *thd, TABLE_LIST *table); void init_query(); void init_select(); st_select_lex_unit* master_unit() { return (st_select_lex_unit*) master; } inline void set_master_unit(st_select_lex_unit *master_unit) { master= (st_select_lex_node *)master_unit; } void set_master(st_select_lex *master_arg) { master= master_arg; } st_select_lex_unit* first_inner_unit() { return (st_select_lex_unit*) slave; } st_select_lex* outer_select(); bool is_query_topmost(THD *thd); st_select_lex* next_select() { return (st_select_lex*) next; } st_select_lex* next_select_in_list() { return (st_select_lex*) link_next; } st_select_lex_node** next_select_in_list_addr() { return &link_next; } st_select_lex* return_after_parsing() { return master_unit()->return_after_parsing(); } inline bool is_subquery_function() { return master_unit()->item != 0; } bool mark_as_dependent(THD *thd, st_select_lex *last, Item_ident *dependency); void set_braces(bool value) { braces= value; } bool inc_in_sum_expr(); uint get_in_sum_expr(); bool add_item_to_list(THD *thd, Item *item); bool add_group_to_list(THD *thd, Item *item, bool asc); bool add_ftfunc_to_list(THD *thd, Item_func_match *func); bool add_order_to_list(THD *thd, Item *item, bool asc); bool add_gorder_to_list(THD *thd, Item *item, bool asc); TABLE_LIST* add_table_to_list(THD *thd, Table_ident *table, LEX_CSTRING *alias, ulong table_options, thr_lock_type flags= TL_UNLOCK, enum_mdl_type mdl_type= MDL_SHARED_READ, List *hints= 0, List *partition_names= 0, LEX_STRING *option= 0); TABLE_LIST* get_table_list(); bool init_nested_join(THD *thd); TABLE_LIST *end_nested_join(THD *thd); TABLE_LIST *nest_last_join(THD *thd); void add_joined_table(TABLE_LIST *table); bool add_cross_joined_table(TABLE_LIST *left_op, TABLE_LIST *right_op, bool straight_fl); TABLE_LIST *convert_right_join(); List* get_item_list(); bool save_item_list_names(THD *thd); void restore_item_list_names(); ulong get_table_join_options(); void set_lock_for_tables(thr_lock_type lock_type, bool for_update, bool skip_locks); /* This method created for reiniting LEX in mysql_admin_table() and can be used only if you are going remove all SELECT_LEX & units except belonger to LEX (LEX::unit & LEX::select, for other purposes there are SELECT_LEX_UNIT::exclude_level & SELECT_LEX_UNIT::exclude_tree */ void cut_subtree() { slave= 0; } bool test_limit(); /** Get offset for LIMIT. Evaluate offset item if necessary. @return Number of rows to skip. */ ha_rows get_offset(); /** Get limit. Evaluate limit item if necessary. @return Limit of rows in result. */ ha_rows get_limit(); friend struct LEX; st_select_lex() : group_list_ptrs(NULL), braces(0), automatic_brackets(0), n_sum_items(0), n_child_sum_items(0) {} void make_empty_select() { init_query(); init_select(); } bool setup_ref_array(THD *thd, uint order_group_num); uint get_cardinality_of_ref_ptrs_slice(uint order_group_num_arg); void print(THD *thd, String *str, enum_query_type query_type); void print_lock_type(String *str); void print_item_list(THD *thd, String *str, enum_query_type query_type); void print_set_clause(THD *thd, String *str, enum_query_type query_type); void print_on_duplicate_key_clause(THD *thd, String *str, enum_query_type query_type); static void print_order(String *str, ORDER *order, enum_query_type query_type); void print_limit(THD *thd, String *str, enum_query_type query_type); void fix_prepare_information(THD *thd, Item **conds, Item **having_conds); /* Destroy the used execution plan (JOIN) of this subtree (this SELECT_LEX and all nested SELECT_LEXes and SELECT_LEX_UNITs). */ bool cleanup(); /* Recursively cleanup the join of this select lex and of all nested select lexes. */ void cleanup_all_joins(bool full); void set_index_hint_type(enum index_hint_type type, index_clause_map clause); /* Add a index hint to the tagged list of hints. The type and clause of the hint will be the current ones (set by set_index_hint()) */ bool add_index_hint (THD *thd, const char *str, size_t length); /* make a list to hold index hints */ void alloc_index_hints (THD *thd); /* read and clear the index hints */ List* pop_index_hints(void) { List *hints= index_hints; index_hints= NULL; return hints; } inline void clear_index_hints(void) { index_hints= NULL; } bool is_part_of_union() { return master_unit()->is_unit_op(); } bool is_top_level_node() { return (select_number == 1) && !is_part_of_union(); } bool optimize_unflattened_subqueries(bool const_only); /* Set the EXPLAIN type for this subquery. */ void set_explain_type(bool on_the_fly); bool handle_derived(LEX *lex, uint phases); void append_table_to_list(TABLE_LIST *TABLE_LIST::*link, TABLE_LIST *table); bool get_free_table_map(table_map *map, uint *tablenr); void replace_leaf_table(TABLE_LIST *table, List &tbl_list); void remap_tables(TABLE_LIST *derived, table_map map, uint tablenr, st_select_lex *parent_lex); bool merge_subquery(THD *thd, TABLE_LIST *derived, st_select_lex *subq_lex, uint tablenr, table_map map); inline bool is_mergeable() { return (next_select() == 0 && group_list.elements == 0 && having == 0 && with_sum_func == 0 && with_rownum == 0 && table_list.elements >= 1 && !(options & SELECT_DISTINCT) && limit_params.select_limit == 0); } void mark_as_belong_to_derived(TABLE_LIST *derived); void increase_derived_records(ha_rows records); void update_used_tables(); void update_correlated_cache(); void mark_const_derived(bool empty); bool save_leaf_tables(THD *thd); bool save_prep_leaf_tables(THD *thd); void set_unique_exclude(); bool is_merged_child_of(st_select_lex *ancestor); /* For MODE_ONLY_FULL_GROUP_BY we need to maintain two flags: - Non-aggregated fields are used in this select. - Aggregate functions are used in this select. In MODE_ONLY_FULL_GROUP_BY only one of these may be true. */ bool non_agg_field_used() const { return m_non_agg_field_used; } bool agg_func_used() const { return m_agg_func_used; } bool custom_agg_func_used() const { return m_custom_agg_func_used; } void set_non_agg_field_used(bool val) { m_non_agg_field_used= val; } void set_agg_func_used(bool val) { m_agg_func_used= val; } void set_custom_agg_func_used(bool val) { m_custom_agg_func_used= val; } inline void set_with_clause(With_clause *with_clause); With_clause *get_with_clause() { return master_unit()->with_clause; } With_element *get_with_element() { return master_unit()->cloned_from ? master_unit()->cloned_from->with_element : master_unit()->with_element; } With_element *find_table_def_in_with_clauses(TABLE_LIST *table, st_select_lex_unit * excl_spec); bool check_unrestricted_recursive(bool only_standard_compliant); bool check_subqueries_with_recursive_references(); void collect_grouping_fields_for_derived(THD *thd, ORDER *grouping_list); bool collect_grouping_fields(THD *thd); bool collect_fields_equal_to_grouping(THD *thd); void check_cond_extraction_for_grouping_fields(THD *thd, Item *cond); Item *build_cond_for_grouping_fields(THD *thd, Item *cond, bool no_to_clones); List window_specs; bool is_win_spec_list_built; void prepare_add_window_spec(THD *thd); bool add_window_def(THD *thd, LEX_CSTRING *win_name, LEX_CSTRING *win_ref, SQL_I_List win_partition_list, SQL_I_List win_order_list, Window_frame *win_frame); bool add_window_spec(THD *thd, LEX_CSTRING *win_ref, SQL_I_List win_partition_list, SQL_I_List win_order_list, Window_frame *win_frame); List window_funcs; bool add_window_func(Item_window_func *win_func); bool have_window_funcs() const { return (window_funcs.elements !=0); } ORDER *find_common_window_func_partition_fields(THD *thd); bool cond_pushdown_is_allowed() const { return !olap && !limit_params.explicit_limit && !tvc && !with_rownum; } bool build_pushable_cond_for_having_pushdown(THD *thd, Item *cond); void pushdown_cond_into_where_clause(THD *thd, Item *extracted_cond, Item **remaining_cond, Item_transformer transformer, uchar *arg); Item *pushdown_from_having_into_where(THD *thd, Item *having); select_handler *find_select_handler(THD *thd); bool is_set_op() { return linkage == UNION_TYPE || linkage == EXCEPT_TYPE || linkage == INTERSECT_TYPE; } inline void add_where_field(st_select_lex *sel) { DBUG_ASSERT(this != sel); select_n_where_fields+= sel->select_n_where_fields; } inline void set_linkage_and_distinct(enum sub_select_type l, bool d) { DBUG_ENTER("SELECT_LEX::set_linkage_and_distinct"); DBUG_PRINT("info", ("select: %p distinct %d", this, d)); set_linkage(l); DBUG_ASSERT(l == UNION_TYPE || l == INTERSECT_TYPE || l == EXCEPT_TYPE); if (d && master_unit() && master_unit()->union_distinct != this) master_unit()->union_distinct= this; distinct= d; with_all_modifier= !distinct; DBUG_VOID_RETURN; } bool set_nest_level(int new_nest_level); bool check_parameters(SELECT_LEX *main_select); void mark_select() { DBUG_ENTER("st_select_lex::mark_select()"); DBUG_PRINT("info", ("Select #%d", select_number)); DBUG_VOID_RETURN; } void register_unit(SELECT_LEX_UNIT *unit, Name_resolution_context *outer_context); SELECT_LEX_UNIT *attach_selects_chain(SELECT_LEX *sel, Name_resolution_context *context); void add_statistics(SELECT_LEX_UNIT *unit); bool make_unique_derived_name(THD *thd, LEX_CSTRING *alias); void lex_start(LEX *plex); bool is_unit_nest() { return (nest_flags & UNIT_NEST_FL); } void mark_as_unit_nest() { nest_flags= UNIT_NEST_FL; } TABLE_LIST *find_table(THD *thd, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name); }; typedef class st_select_lex SELECT_LEX; inline bool st_select_lex_unit::is_unit_op () { if (!first_select()->next_select()) { if (first_select()->tvc) return 1; else return 0; } enum sub_select_type linkage= first_select()->next_select()->linkage; return linkage == UNION_TYPE || linkage == INTERSECT_TYPE || linkage == EXCEPT_TYPE; } struct st_sp_chistics { LEX_CSTRING comment; enum enum_sp_suid_behaviour suid; bool detistic; enum enum_sp_data_access daccess; enum enum_sp_aggregate_type agg_type; void init() { bzero(this, sizeof(*this)); } void set(const st_sp_chistics &other) { *this= other; } bool read_from_mysql_proc_row(THD *thd, TABLE *table); }; class Sp_chistics: public st_sp_chistics { public: Sp_chistics() { init(); } }; struct st_trg_chistics: public st_trg_execution_order { enum trg_action_time_type action_time; enum trg_event_type event; const char *ordering_clause_begin; const char *ordering_clause_end; }; enum xa_option_words {XA_NONE, XA_JOIN, XA_RESUME, XA_ONE_PHASE, XA_SUSPEND, XA_FOR_MIGRATE}; class Sroutine_hash_entry; /* Class representing list of all tables used by statement and other information which is necessary for opening and locking its tables, like SQL command for this statement. Also contains information about stored functions used by statement since during its execution we may have to add all tables used by its stored functions/triggers to this list in order to pre-open and lock them. Also used by LEX::reset_n_backup/restore_backup_query_tables_list() methods to save and restore this information. */ class Query_tables_list { public: /** SQL command for this statement. Part of this class since the process of opening and locking tables for the statement needs this information to determine correct type of lock for some of the tables. */ enum_sql_command sql_command; /* Global list of all tables used by this statement */ TABLE_LIST *query_tables; /* Pointer to next_global member of last element in the previous list. */ TABLE_LIST **query_tables_last; /* If non-0 then indicates that query requires prelocking and points to next_global member of last own element in query table list (i.e. last table which was not added to it as part of preparation to prelocking). 0 - indicates that this query does not need prelocking. */ TABLE_LIST **query_tables_own_last; /* Set of stored routines called by statement. (Note that we use lazy-initialization for this hash). */ enum { START_SROUTINES_HASH_SIZE= 16 }; HASH sroutines; /* List linking elements of 'sroutines' set. Allows you to add new elements to this set as you iterate through the list of existing elements. 'sroutines_list_own_last' is pointer to ::next member of last element of this list which represents routine which is explicitly used by query. 'sroutines_list_own_elements' number of explicitly used routines. We use these two members for restoring of 'sroutines_list' to the state in which it was right after query parsing. */ SQL_I_List sroutines_list; Sroutine_hash_entry **sroutines_list_own_last; uint sroutines_list_own_elements; /* These constructor and destructor serve for creation/destruction of Query_tables_list instances which are used as backup storage. */ Query_tables_list() = default; ~Query_tables_list() = default; /* Initializes (or resets) Query_tables_list object for "real" use. */ void reset_query_tables_list(bool init); void destroy_query_tables_list(); void set_query_tables_list(Query_tables_list *state) { *this= *state; } /* Direct addition to the list of query tables. If you are using this function, you must ensure that the table object, in particular table->db member, is initialized. */ void add_to_query_tables(TABLE_LIST *table) { *(table->prev_global= query_tables_last)= table; query_tables_last= &table->next_global; } bool requires_prelocking() { return MY_TEST(query_tables_own_last); } void mark_as_requiring_prelocking(TABLE_LIST **tables_own_last) { query_tables_own_last= tables_own_last; } /* Return pointer to first not-own table in query-tables or 0 */ TABLE_LIST* first_not_own_table() { return ( query_tables_own_last ? *query_tables_own_last : 0); } void chop_off_not_own_tables() { if (query_tables_own_last) { *query_tables_own_last= 0; query_tables_last= query_tables_own_last; query_tables_own_last= 0; } } /** Return a pointer to the last element in query table list. */ TABLE_LIST *last_table() { /* Don't use offsetof() macro in order to avoid warnings. */ return query_tables ? (TABLE_LIST*) ((char*) query_tables_last - ((char*) &(query_tables->next_global) - (char*) query_tables)) : 0; } /** Enumeration listing of all types of unsafe statement. @note The order of elements of this enumeration type must correspond to the order of the elements of the @c explanations array defined in the body of @c THD::issue_unsafe_warnings. */ enum enum_binlog_stmt_unsafe { /** SELECT..LIMIT is unsafe because the set of rows returned cannot be predicted. */ BINLOG_STMT_UNSAFE_LIMIT= 0, /** INSERT DELAYED is unsafe because the time when rows are inserted cannot be predicted. */ BINLOG_STMT_UNSAFE_INSERT_DELAYED, /** Access to log tables is unsafe because slave and master probably log different things. */ BINLOG_STMT_UNSAFE_SYSTEM_TABLE, /** Inserting into an autoincrement column in a stored routine is unsafe. Even with just one autoincrement column, if the routine is invoked more than once slave is not guaranteed to execute the statement graph same way as the master. And since it's impossible to estimate how many times a routine can be invoked at the query pre-execution phase (see lock_tables), the statement is marked pessimistically unsafe. */ BINLOG_STMT_UNSAFE_AUTOINC_COLUMNS, /** Using a UDF (user-defined function) is unsafe. */ BINLOG_STMT_UNSAFE_UDF, /** Using most system variables is unsafe, because slave may run with different options than master. */ BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE, /** Using some functions is unsafe (e.g., UUID). */ BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION, /** Mixing transactional and non-transactional statements are unsafe if non-transactional reads or writes are occur after transactional reads or writes inside a transaction. */ BINLOG_STMT_UNSAFE_NONTRANS_AFTER_TRANS, /** Mixing self-logging and non-self-logging engines in a statement is unsafe. */ BINLOG_STMT_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE, /** Statements that read from both transactional and non-transactional tables and write to any of them are unsafe. */ BINLOG_STMT_UNSAFE_MIXED_STATEMENT, /** INSERT...IGNORE SELECT is unsafe because which rows are ignored depends on the order that rows are retrieved by SELECT. This order cannot be predicted and may differ on master and the slave. */ BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT, /** INSERT...SELECT...UPDATE is unsafe because which rows are updated depends on the order that rows are retrieved by SELECT. This order cannot be predicted and may differ on master and the slave. */ BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE, /** Query that writes to a table with auto_inc column after selecting from other tables are unsafe as the order in which the rows are retrieved by select may differ on master and slave. */ BINLOG_STMT_UNSAFE_WRITE_AUTOINC_SELECT, /** INSERT...REPLACE SELECT is unsafe because which rows are replaced depends on the order that rows are retrieved by SELECT. This order cannot be predicted and may differ on master and the slave. */ BINLOG_STMT_UNSAFE_REPLACE_SELECT, /** CREATE TABLE... IGNORE... SELECT is unsafe because which rows are ignored depends on the order that rows are retrieved by SELECT. This order cannot be predicted and may differ on master and the slave. */ BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT, /** CREATE TABLE...REPLACE... SELECT is unsafe because which rows are replaced depends on the order that rows are retrieved from SELECT. This order cannot be predicted and may differ on master and the slave */ BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT, /** CREATE TABLE...SELECT on a table with auto-increment column is unsafe because which rows are replaced depends on the order that rows are retrieved from SELECT. This order cannot be predicted and may differ on master and the slave */ BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC, /** UPDATE...IGNORE is unsafe because which rows are ignored depends on the order that rows are updated. This order cannot be predicted and may differ on master and the slave. */ BINLOG_STMT_UNSAFE_UPDATE_IGNORE, /** INSERT... ON DUPLICATE KEY UPDATE on a table with more than one UNIQUE KEYS is unsafe. */ BINLOG_STMT_UNSAFE_INSERT_TWO_KEYS, /** INSERT into auto-inc field which is not the first part of composed primary key. */ BINLOG_STMT_UNSAFE_AUTOINC_NOT_FIRST, /** Autoincrement lock mode is incompatible with STATEMENT binlog format. */ BINLOG_STMT_UNSAFE_AUTOINC_LOCK_MODE, /** INSERT .. SELECT ... SKIP LOCKED is unlikely to have the same rows locked on the replica. primary key. */ BINLOG_STMT_UNSAFE_SKIP_LOCKED, /* The last element of this enumeration type. */ BINLOG_STMT_UNSAFE_COUNT }; /** This has all flags from 0 (inclusive) to BINLOG_STMT_FLAG_COUNT (exclusive) set. */ static const uint32 BINLOG_STMT_UNSAFE_ALL_FLAGS= ((1U << BINLOG_STMT_UNSAFE_COUNT) - 1); /** Maps elements of enum_binlog_stmt_unsafe to error codes. */ static const int binlog_stmt_unsafe_errcode[BINLOG_STMT_UNSAFE_COUNT]; /** Determine if this statement is marked as unsafe. @retval 0 if the statement is not marked as unsafe. @retval nonzero if the statement is marked as unsafe. */ inline bool is_stmt_unsafe() const { return get_stmt_unsafe_flags() != 0; } inline bool is_stmt_unsafe(enum_binlog_stmt_unsafe unsafe) { return binlog_stmt_flags & (1 << unsafe); } /** Flag the current (top-level) statement as unsafe. The flag will be reset after the statement has finished. @param unsafe_type The type of unsafety: one of the @c BINLOG_STMT_FLAG_UNSAFE_* flags in @c enum_binlog_stmt_flag. */ inline void set_stmt_unsafe(enum_binlog_stmt_unsafe unsafe_type) { DBUG_ENTER("set_stmt_unsafe"); DBUG_ASSERT(unsafe_type >= 0 && unsafe_type < BINLOG_STMT_UNSAFE_COUNT); binlog_stmt_flags|= (1U << unsafe_type); DBUG_VOID_RETURN; } /** Set the bits of binlog_stmt_flags determining the type of unsafeness of the current statement. No existing bits will be cleared, but new bits may be set. @param flags A binary combination of zero or more bits, (1<= ISO_REPEATABLE_READ */ /** Sets the type of table that is about to be accessed while executing a statement. @param accessed_table Enumeration type that defines the type of table, e.g. temporary, transactional, non-transactional. */ inline void set_stmt_accessed_table(enum_stmt_accessed_table accessed_table) { DBUG_ENTER("LEX::set_stmt_accessed_table"); DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT); stmt_accessed_table_flag |= (1U << accessed_table); DBUG_VOID_RETURN; } /** Checks if a type of table is about to be accessed while executing a statement. @param accessed_table Enumeration type that defines the type of table, e.g. temporary, transactional, non-transactional. @return @retval TRUE if the type of the table is about to be accessed @retval FALSE otherwise */ inline bool stmt_accessed_table(enum_stmt_accessed_table accessed_table) { DBUG_ENTER("LEX::stmt_accessed_table"); DBUG_ASSERT(accessed_table >= 0 && accessed_table < STMT_ACCESS_TABLE_COUNT); DBUG_RETURN((stmt_accessed_table_flag & (1U << accessed_table)) != 0); } /** Checks either a trans/non trans temporary table is being accessed while executing a statement. @return @retval TRUE if a temporary table is being accessed @retval FALSE otherwise */ inline bool stmt_accessed_temp_table() { DBUG_ENTER("THD::stmt_accessed_temp_table"); DBUG_RETURN(stmt_accessed_non_trans_temp_table() || stmt_accessed_trans_temp_table()); } /** Checks if a temporary transactional table is being accessed while executing a statement. @return @retval TRUE if a temporary transactional table is being accessed @retval FALSE otherwise */ inline bool stmt_accessed_trans_temp_table() { DBUG_ENTER("THD::stmt_accessed_trans_temp_table"); DBUG_RETURN((stmt_accessed_table_flag & ((1U << STMT_READS_TEMP_TRANS_TABLE) | (1U << STMT_WRITES_TEMP_TRANS_TABLE))) != 0); } inline bool stmt_writes_to_non_temp_table() { DBUG_ENTER("THD::stmt_writes_to_non_temp_table"); DBUG_RETURN((stmt_accessed_table_flag & ((1U << STMT_WRITES_TRANS_TABLE) | (1U << STMT_WRITES_NON_TRANS_TABLE)))); } /** Checks if a temporary non-transactional table is about to be accessed while executing a statement. @return @retval TRUE if a temporary non-transactional table is about to be accessed @retval FALSE otherwise */ inline bool stmt_accessed_non_trans_temp_table() { DBUG_ENTER("THD::stmt_accessed_non_trans_temp_table"); DBUG_RETURN((stmt_accessed_table_flag & ((1U << STMT_READS_TEMP_NON_TRANS_TABLE) | (1U << STMT_WRITES_TEMP_NON_TRANS_TABLE))) != 0); } /* Checks if a mixed statement is unsafe. @param in_multi_stmt_transaction_mode defines if there is an on-going multi-transactional statement. @param binlog_direct defines if --binlog-direct-non-trans-updates is active. @param trx_cache_is_not_empty defines if the trx-cache is empty or not. @param trx_isolation defines the isolation level. @return @retval TRUE if the mixed statement is unsafe @retval FALSE otherwise */ inline bool is_mixed_stmt_unsafe(bool in_multi_stmt_transaction_mode, bool binlog_direct, bool trx_cache_is_not_empty, uint tx_isolation) { bool unsafe= FALSE; if (in_multi_stmt_transaction_mode) { uint condition= (binlog_direct ? BINLOG_DIRECT_ON : BINLOG_DIRECT_OFF) & (trx_cache_is_not_empty ? TRX_CACHE_NOT_EMPTY : TRX_CACHE_EMPTY) & (tx_isolation >= ISO_REPEATABLE_READ ? IL_GTE_REPEATABLE : IL_LT_REPEATABLE); unsafe= (binlog_unsafe_map[stmt_accessed_table_flag] & condition); #if !defined(DBUG_OFF) DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("RESULT %02X %02X %02X", condition, binlog_unsafe_map[stmt_accessed_table_flag], (binlog_unsafe_map[stmt_accessed_table_flag] & condition))); int type_in= 0; for (; type_in < STMT_ACCESS_TABLE_COUNT; type_in++) { if (stmt_accessed_table((enum_stmt_accessed_table) type_in)) DBUG_PRINT("LEX::is_mixed_stmt_unsafe", ("ACCESSED %s ", stmt_accessed_table_string((enum_stmt_accessed_table) type_in))); } #endif } if (stmt_accessed_table(STMT_WRITES_NON_TRANS_TABLE) && stmt_accessed_table(STMT_READS_TRANS_TABLE) && tx_isolation < ISO_REPEATABLE_READ) unsafe= TRUE; else if (stmt_accessed_table(STMT_WRITES_TEMP_NON_TRANS_TABLE) && stmt_accessed_table(STMT_READS_TRANS_TABLE) && tx_isolation < ISO_REPEATABLE_READ) unsafe= TRUE; return(unsafe); } /** true if the parsed tree contains references to stored procedures or functions, false otherwise */ bool uses_stored_routines() const { return sroutines_list.elements != 0; } private: /** Enumeration listing special types of statements. Currently, the only possible type is ROW_INJECTION. */ enum enum_binlog_stmt_type { /** The statement is a row injection (i.e., either a BINLOG statement or a row event executed by the slave SQL thread). */ BINLOG_STMT_TYPE_ROW_INJECTION = BINLOG_STMT_UNSAFE_COUNT, /** The last element of this enumeration type. */ BINLOG_STMT_TYPE_COUNT }; /** Bit field indicating the type of statement. There are two groups of bits: - The low BINLOG_STMT_UNSAFE_COUNT bits indicate the types of unsafeness that the current statement has. - The next BINLOG_STMT_TYPE_COUNT-BINLOG_STMT_TYPE_COUNT bits indicate if the statement is of some special type. This must be a member of LEX, not of THD: each stored procedure needs to remember its unsafeness state between calls and each stored procedure has its own LEX object (but no own THD object). */ uint32 binlog_stmt_flags; /** Bit field that determines the type of tables that are about to be be accessed while executing a statement. */ uint32 stmt_accessed_table_flag; }; /* st_parsing_options contains the flags for constructions that are allowed in the current statement. */ struct st_parsing_options { bool allows_variable; bool lookup_keywords_after_qualifier; st_parsing_options() { reset(); } void reset(); }; /** The state of the lexical parser, when parsing comments. */ enum enum_comment_state { /** Not parsing comments. */ NO_COMMENT, /** Parsing comments that need to be preserved. Typically, these are user comments '/' '*' ... '*' '/'. */ PRESERVE_COMMENT, /** Parsing comments that need to be discarded. Typically, these are special comments '/' '*' '!' ... '*' '/', or '/' '*' '!' 'M' 'M' 'm' 'm' 'm' ... '*' '/', where the comment markers should not be expanded. */ DISCARD_COMMENT }; /** @brief This class represents the character input stream consumed during lexical analysis. In addition to consuming the input stream, this class performs some comment pre processing, by filtering out out of bound special text from the query input stream. Two buffers, with pointers inside each buffers, are maintained in parallel. The 'raw' buffer is the original query text, which may contain out-of-bound comments. The 'cpp' (for comments pre processor) is the pre-processed buffer that contains only the query text that should be seen once out-of-bound data is removed. */ class Lex_input_stream { size_t unescape(CHARSET_INFO *cs, char *to, const char *str, const char *end, int sep); my_charset_conv_wc_mb get_escape_func(THD *thd, my_wc_t sep) const; public: Lex_input_stream() = default; ~Lex_input_stream() = default; /** Object initializer. Must be called before usage. @retval FALSE OK @retval TRUE Error */ bool init(THD *thd, char *buff, size_t length); void reset(char *buff, size_t length); /** The main method to scan the next token, with token contraction processing for LALR(2) resolution, e.g. translate "WITH" followed by "ROLLUP" to a single token WITH_ROLLUP_SYM. */ int lex_token(union YYSTYPE *yylval, THD *thd); void reduce_digest_token(uint token_left, uint token_right); private: enum Ident_mode { GENERAL_KEYWORD_OR_FUNC_LPAREN, QUALIFIED_SPECIAL_FUNC_LPAREN }; int scan_ident_common(THD *thd, Lex_ident_cli_st *str, Ident_mode mode); /** Set the echo mode. When echo is true, characters parsed from the raw input stream are preserved. When false, characters parsed are silently ignored. @param echo the echo mode. */ void set_echo(bool echo) { m_echo= echo; } void save_in_comment_state() { m_echo_saved= m_echo; in_comment_saved= in_comment; } void restore_in_comment_state() { m_echo= m_echo_saved; in_comment= in_comment_saved; } /** Skip binary from the input stream. @param n number of bytes to accept. */ void skip_binary(int n) { if (m_echo) { memcpy(m_cpp_ptr, m_ptr, n); m_cpp_ptr += n; } m_ptr += n; } /** Get a character, and advance in the stream. @return the next character to parse. */ unsigned char yyGet() { char c= *m_ptr++; if (m_echo) *m_cpp_ptr++ = c; return c; } /** Get the last character accepted. @return the last character accepted. */ unsigned char yyGetLast() const { return m_ptr[-1]; } /** Look at the next character to parse, but do not accept it. */ unsigned char yyPeek() const { return m_ptr[0]; } /** Look ahead at some character to parse. @param n offset of the character to look up */ unsigned char yyPeekn(int n) const { return m_ptr[n]; } /** Cancel the effect of the last yyGet() or yySkip(). Note that the echo mode should not change between calls to yyGet / yySkip and yyUnget. The caller is responsible for ensuring that. */ void yyUnget() { m_ptr--; if (m_echo) m_cpp_ptr--; } /** Accept a character, by advancing the input stream. */ void yySkip() { if (m_echo) *m_cpp_ptr++ = *m_ptr++; else m_ptr++; } /** Accept multiple characters at once. @param n the number of characters to accept. */ void yySkipn(int n) { if (m_echo) { memcpy(m_cpp_ptr, m_ptr, n); m_cpp_ptr += n; } m_ptr += n; } /** Puts a character back into the stream, canceling the effect of the last yyGet() or yySkip(). Note that the echo mode should not change between calls to unput, get, or skip from the stream. */ char *yyUnput(char ch) { *--m_ptr= ch; if (m_echo) m_cpp_ptr--; return m_ptr; } /** End of file indicator for the query text to parse. @param n number of characters expected @return true if there are less than n characters to parse */ bool eof(int n) const { return ((m_ptr + n) >= m_end_of_query); } /** Mark the stream position as the start of a new token. */ void start_token() { m_tok_start_prev= m_tok_start; m_tok_start= m_ptr; m_tok_end= m_ptr; m_cpp_tok_start_prev= m_cpp_tok_start; m_cpp_tok_start= m_cpp_ptr; m_cpp_tok_end= m_cpp_ptr; } /** Adjust the starting position of the current token. This is used to compensate for starting whitespace. */ void restart_token() { m_tok_start= m_ptr; m_cpp_tok_start= m_cpp_ptr; } /** Get the maximum length of the utf8-body buffer. The utf8 body can grow because of the character set conversion and escaping. */ size_t get_body_utf8_maximum_length(THD *thd) const; /** Get the length of the current token, in the raw buffer. */ uint yyLength() const { /* The assumption is that the lexical analyser is always 1 character ahead, which the -1 account for. */ DBUG_ASSERT(m_ptr > m_tok_start); return (uint) ((m_ptr - m_tok_start) - 1); } /** Test if a lookahead token was already scanned by lex_token(), for LALR(2) resolution. */ bool has_lookahead() const { return lookahead_token >= 0; } public: /** End of file indicator for the query text to parse. @return true if there are no more characters to parse */ bool eof() const { return (m_ptr >= m_end_of_query); } /** Get the raw query buffer. */ const char *get_buf() const { return m_buf; } /** Get the pre-processed query buffer. */ const char *get_cpp_buf() const { return m_cpp_buf; } /** Get the end of the raw query buffer. */ const char *get_end_of_query() const { return m_end_of_query; } /** Get the token start position, in the raw buffer. */ const char *get_tok_start() const { return has_lookahead() ? m_tok_start_prev : m_tok_start; } void set_cpp_tok_start(const char *pos) { m_cpp_tok_start= pos; } /** Get the token end position, in the raw buffer. */ const char *get_tok_end() const { return m_tok_end; } /** Get the current stream pointer, in the raw buffer. */ const char *get_ptr() const { return m_ptr; } /** Get the token start position, in the pre-processed buffer. */ const char *get_cpp_tok_start() const { return has_lookahead() ? m_cpp_tok_start_prev : m_cpp_tok_start; } /** Get the token end position, in the pre-processed buffer. */ const char *get_cpp_tok_end() const { return m_cpp_tok_end; } /** Get the token end position in the pre-processed buffer, with trailing spaces removed. */ const char *get_cpp_tok_end_rtrim() const { const char *p; for (p= m_cpp_tok_end; p > m_cpp_buf && my_isspace(system_charset_info, p[-1]); p--) { } return p; } /** Get the current stream pointer, in the pre-processed buffer. */ const char *get_cpp_ptr() const { return m_cpp_ptr; } /** Get the current stream pointer, in the pre-processed buffer, with traling spaces removed. */ const char *get_cpp_ptr_rtrim() const { const char *p; for (p= m_cpp_ptr; p > m_cpp_buf && my_isspace(system_charset_info, p[-1]); p--) { } return p; } /** Get the utf8-body string. */ LEX_CSTRING body_utf8() const { return LEX_CSTRING({m_body_utf8, (size_t) (m_body_utf8_ptr - m_body_utf8)}); } void body_utf8_start(THD *thd, const char *begin_ptr); void body_utf8_append(const char *ptr); void body_utf8_append(const char *ptr, const char *end_ptr); void body_utf8_append_ident(THD *thd, const Lex_string_with_metadata_st *txt, const char *end_ptr); void body_utf8_append_escape(THD *thd, const LEX_CSTRING *txt, CHARSET_INFO *txt_cs, const char *end_ptr, my_wc_t sep); private: /** LALR(2) resolution, look ahead token. Value of the next token to return, if any, or -1, if no token was parsed in advance. Note: 0 is a legal token, and represents YYEOF. */ int lookahead_token; /** LALR(2) resolution, value of the look ahead token.*/ LEX_YYSTYPE lookahead_yylval; bool get_text(Lex_string_with_metadata_st *to, uint sep, int pre_skip, int post_skip); void add_digest_token(uint token, LEX_YYSTYPE yylval); bool consume_comment(int remaining_recursions_permitted); int lex_one_token(union YYSTYPE *yylval, THD *thd); int find_keyword(Lex_ident_cli_st *str, uint len, bool function) const; int find_keyword_qualified_special_func(Lex_ident_cli_st *str, uint len) const; LEX_CSTRING get_token(uint skip, uint length); int scan_ident_start(THD *thd, Lex_ident_cli_st *str); int scan_ident_middle(THD *thd, Lex_ident_cli_st *str, CHARSET_INFO **cs, my_lex_states *); int scan_ident_delimited(THD *thd, Lex_ident_cli_st *str, uchar quote_char); bool get_7bit_or_8bit_ident(THD *thd, uchar *last_char); /** Current thread. */ THD *m_thd; /** Pointer to the current position in the raw input stream. */ char *m_ptr; /** Starting position of the last token parsed, in the raw buffer. */ const char *m_tok_start; /** Ending position of the previous token parsed, in the raw buffer. */ const char *m_tok_end; /** End of the query text in the input stream, in the raw buffer. */ const char *m_end_of_query; /** Starting position of the previous token parsed, in the raw buffer. */ const char *m_tok_start_prev; /** Begining of the query text in the input stream, in the raw buffer. */ const char *m_buf; /** Length of the raw buffer. */ size_t m_buf_length; /** Echo the parsed stream to the pre-processed buffer. */ bool m_echo:1; bool m_echo_saved:1; /** Pre-processed buffer. */ char *m_cpp_buf; /** Pointer to the current position in the pre-processed input stream. */ char *m_cpp_ptr; /** Starting position of the last token parsed, in the pre-processed buffer. */ const char *m_cpp_tok_start; /** Starting position of the previous token parsed, in the pre-procedded buffer. */ const char *m_cpp_tok_start_prev; /** Ending position of the previous token parsed, in the pre-processed buffer. */ const char *m_cpp_tok_end; /** UTF8-body buffer created during parsing. */ char *m_body_utf8; /** Pointer to the current position in the UTF8-body buffer. */ char *m_body_utf8_ptr; /** Position in the pre-processed buffer. The query from m_cpp_buf to m_cpp_utf_processed_ptr is converted to UTF8-body. */ const char *m_cpp_utf8_processed_ptr; public: /** Current state of the lexical analyser. */ enum my_lex_states next_state; /** Position of ';' in the stream, to delimit multiple queries. This delimiter is in the raw buffer. */ const char *found_semicolon; /** SQL_MODE = IGNORE_SPACE. */ bool ignore_space:1; /** TRUE if we're parsing a prepared statement: in this mode we should allow placeholders. */ bool stmt_prepare_mode:1; /** TRUE if we should allow multi-statements. */ bool multi_statements:1; /** Current line number. */ uint yylineno; /** Current statement digest instrumentation. */ sql_digest_state* m_digest; private: /** State of the lexical analyser for comments. */ enum_comment_state in_comment; enum_comment_state in_comment_saved; /** Starting position of the TEXT_STRING or IDENT in the pre-processed buffer. NOTE: this member must be used within MYSQLlex() function only. */ const char *m_cpp_text_start; /** Ending position of the TEXT_STRING or IDENT in the pre-processed buffer. NOTE: this member must be used within MYSQLlex() function only. */ const char *m_cpp_text_end; /** Character set specified by the character-set-introducer. NOTE: this member must be used within MYSQLlex() function only. */ CHARSET_INFO *m_underscore_cs; }; /** Abstract representation of a statement. This class is an interface between the parser and the runtime. The parser builds the appropriate sub classes of Sql_statement to represent a SQL statement in the parsed tree. The execute() method in the sub classes contain the runtime implementation. Note that this interface is used for SQL statement recently implemented, the code for older statements tend to load the LEX structure with more attributes instead. The recommended way to implement new statements is to sub-class Sql_statement, as this improves code modularity (see the 'big switch' in dispatch_command()), and decrease the total size of the LEX structure (therefore saving memory in stored programs). */ class Sql_statement : public Sql_alloc { public: /** Execute this SQL statement. @param thd the current thread. @return 0 on success. */ virtual bool execute(THD *thd) = 0; protected: /** Constructor. @param lex the LEX structure that represents parts of this statement. */ Sql_statement(LEX *lex) : m_lex(lex) {} /** Destructor. */ virtual ~Sql_statement() { /* Sql_statement objects are allocated in thd->mem_root. In MySQL, the C++ destructor is never called, the underlying MEM_ROOT is simply destroyed instead. Do not rely on the destructor for any cleanup. */ DBUG_ASSERT(FALSE); } protected: /** The legacy LEX structure for this statement. The LEX structure contains the existing properties of the parsed tree. TODO: with time, attributes from LEX should move to sub classes of Sql_statement, so that the parser only builds Sql_statement objects with the minimum set of attributes, instead of a LEX structure that contains the collection of every possible attribute. */ LEX *m_lex; }; class Delete_plan; class SQL_SELECT; class Explain_query; class Explain_update; class Explain_delete; /* Query plan of a single-table UPDATE. (This is actually a plan for single-table DELETE also) */ class Update_plan { protected: bool impossible_where; bool no_partitions; public: /* Allocate things there */ MEM_ROOT *mem_root; TABLE *table; SQL_SELECT *select; uint index; ha_rows scanned_rows; /* Top-level select_lex. Most of its fields are not used, we need it only to get to the subqueries. */ SELECT_LEX *select_lex; key_map possible_keys; bool using_filesort; bool using_io_buffer; /* Set this plan to be a plan to do nothing because of impossible WHERE */ void set_impossible_where() { impossible_where= true; } void set_no_partitions() { no_partitions= true; } Explain_update* save_explain_update_data(THD *thd, MEM_ROOT *mem_root); protected: bool save_explain_data_intern(THD *thd, MEM_ROOT *mem_root, Explain_update *eu, bool is_analyze); public: virtual ~Update_plan() = default; Update_plan(MEM_ROOT *mem_root_arg) : impossible_where(false), no_partitions(false), mem_root(mem_root_arg), using_filesort(false), using_io_buffer(false) {} }; /* Query plan of a single-table DELETE */ class Delete_plan : public Update_plan { bool deleting_all_rows; public: /* Construction functions */ Delete_plan(MEM_ROOT *mem_root_arg) : Update_plan(mem_root_arg), deleting_all_rows(false) {} /* Set this query plan to be a plan to make a call to h->delete_all_rows() */ void set_delete_all_rows(ha_rows rows_arg) { deleting_all_rows= true; scanned_rows= rows_arg; } void cancel_delete_all_rows() { deleting_all_rows= false; } Explain_delete* save_explain_delete_data(THD *thd, MEM_ROOT *mem_root); }; enum account_lock_type { ACCOUNTLOCK_UNSPECIFIED= 0, ACCOUNTLOCK_LOCKED, ACCOUNTLOCK_UNLOCKED }; enum password_exp_type { PASSWORD_EXPIRE_UNSPECIFIED= 0, PASSWORD_EXPIRE_NOW, PASSWORD_EXPIRE_NEVER, PASSWORD_EXPIRE_DEFAULT, PASSWORD_EXPIRE_INTERVAL }; struct Account_options: public USER_RESOURCES { Account_options() = default; void reset() { bzero(this, sizeof(*this)); ssl_type= SSL_TYPE_NOT_SPECIFIED; } enum SSL_type ssl_type; // defined in violite.h LEX_CSTRING x509_subject, x509_issuer, ssl_cipher; account_lock_type account_locked; password_exp_type password_expire; longlong num_expiration_days; }; class Query_arena_memroot; /* The state of the lex parsing. This is saved in the THD struct */ class Lex_prepared_stmt { Lex_ident_sys m_name; // Statement name (in all queries) Item *m_code; // PREPARE or EXECUTE IMMEDIATE source expression List m_params; // List of parameters for EXECUTE [IMMEDIATE] public: Lex_prepared_stmt() :m_code(NULL) { } const Lex_ident_sys &name() const { return m_name; } uint param_count() const { return m_params.elements; } List ¶ms() { return m_params; } void set(const Lex_ident_sys_st &ident, Item *code, List *params) { DBUG_ASSERT(m_params.elements == 0); m_name= ident; m_code= code; if (params) m_params= *params; } bool params_fix_fields(THD *thd) { // Fix Items in the EXECUTE..USING list List_iterator_fast param_it(m_params); while (Item *param= param_it++) { if (param->fix_fields_if_needed_for_scalar(thd, 0)) return true; } return false; } bool get_dynamic_sql_string(THD *thd, LEX_CSTRING *dst, String *buffer); void lex_start() { m_params.empty(); } }; class Lex_grant_object_name: public Grant_object_name, public Sql_alloc { public: Lex_grant_object_name(Table_ident *table_ident) :Grant_object_name(table_ident) { } Lex_grant_object_name(const LEX_CSTRING &db, Type type) :Grant_object_name(db, type) { } }; class Lex_grant_privilege: public Grant_privilege, public Sql_alloc { public: Lex_grant_privilege() {} Lex_grant_privilege(privilege_t grant, bool all_privileges= false) :Grant_privilege(grant, all_privileges) { } }; struct LEX: public Query_tables_list { SELECT_LEX_UNIT unit; /* most upper unit */ SELECT_LEX *first_select_lex() { return unit.first_select(); } const SELECT_LEX *first_select_lex() const { return unit.first_select(); } private: SELECT_LEX builtin_select; public: /* current SELECT_LEX in parsing */ SELECT_LEX *current_select; /* list of all SELECT_LEX */ SELECT_LEX *all_selects_list; /* current with clause in parsing if any, otherwise 0*/ With_clause *curr_with_clause; /* pointer to the first with clause in the current statement */ With_clause *with_clauses_list; /* (*with_clauses_list_last_next) contains a pointer to the last with clause in the current statement */ With_clause **with_clauses_list_last_next; /* When a copy of a with element is parsed this is set to the offset of the with element in the input string, otherwise it's set to 0 */ my_ptrdiff_t clone_spec_offset; Create_view_info *create_view; /* Query Plan Footprint of a currently running select */ Explain_query *explain; // type information CHARSET_INFO *charset; /* LEX which represents current statement (conventional, SP or PS) For example during view parsing THD::lex will point to the views LEX and lex::stmt_lex will point to LEX of the statement where the view will be included Currently it is used to have always correct select numbering inside statement (LEX::current_select_number) without storing and restoring a global counter which was THD::select_number. TODO: make some unified statement representation (now SP has different) to store such data like LEX::current_select_number. */ LEX *stmt_lex; LEX_CSTRING name; const char *help_arg; const char *backup_dir; /* For RESTORE/BACKUP */ const char* to_log; /* For PURGE MASTER LOGS TO */ String *wild; /* Wildcard in SHOW {something} LIKE 'wild'*/ sql_exchange *exchange; select_result *result; /** @c the two may also hold BINLOG arguments: either comment holds a base64-char string or both represent the BINLOG fragment user variables. */ LEX_CSTRING comment, ident; LEX_USER *grant_user; XID *xid; THD *thd; /* maintain a list of used plugins for this LEX */ DYNAMIC_ARRAY plugins; plugin_ref plugins_static_buffer[INITIAL_LEX_PLUGIN_LIST_SIZE]; /** SELECT of CREATE VIEW statement */ LEX_STRING create_view_select; /** Start of 'ON table', in trigger statements. */ const char* raw_trg_on_table_name_begin; /** End of 'ON table', in trigger statements. */ const char* raw_trg_on_table_name_end; /* Partition info structure filled in by PARTITION BY parse part */ partition_info *part_info; /* The definer of the object being created (view, trigger, stored routine). I.e. the value of DEFINER clause. */ LEX_USER *definer; /* Used in ALTER/CREATE user to store account locking options */ Account_options account_options; Table_type table_type; /* Used for SHOW CREATE */ List ref_list; List users_list; List *insert_list= nullptr,field_list,value_list,update_list; List many_values; List var_list; List stmt_var_list; //SET_STATEMENT values List old_var_list; // SET STATEMENT old values private: Query_arena_memroot *arena_for_set_stmt; MEM_ROOT *mem_root_for_set_stmt; bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock, class sp_label **splabel); bool sp_change_context(THD *thd, const sp_pcontext *ctx, bool exclusive); bool sp_exit_block(THD *thd, sp_label *lab); bool sp_exit_block(THD *thd, sp_label *lab, Item *when); bool sp_continue_loop(THD *thd, sp_label *lab); bool sp_for_loop_condition(THD *thd, const Lex_for_loop_st &loop); bool sp_for_loop_increment(THD *thd, const Lex_for_loop_st &loop); /* Check if Item_field and Item_ref are allowed in the current statement. @retval false OK (fields are allowed) @retval true ERROR (fields are not allowed). Error is raised. */ bool check_expr_allows_fields_or_error(THD *thd, const char *name) const; protected: bool sp_continue_loop(THD *thd, sp_label *lab, Item *when); public: void parse_error(uint err_number= ER_SYNTAX_ERROR); inline bool is_arena_for_set_stmt() {return arena_for_set_stmt != 0;} bool set_arena_for_set_stmt(Query_arena *backup); void reset_arena_for_set_stmt(Query_arena *backup); void free_arena_for_set_stmt(); void print(String *str, enum_query_type qtype); List set_var_list; // in-query assignment list List param_list; List view_list; // view list (list of field names in view) List *column_list; // list of column names (in ANALYZE) List *index_list; // list of index names (in ANALYZE) /* A stack of name resolution contexts for the query. This stack is used at parse time to set local name resolution contexts for various parts of a query. For example, in a JOIN ... ON (some_condition) clause the Items in 'some_condition' must be resolved only against the operands of the the join, and not against the whole clause. Similarly, Items in subqueries should be resolved against the subqueries (and outer queries). The stack is used in the following way: when the parser detects that all Items in some clause need a local context, it creates a new context and pushes it on the stack. All newly created Items always store the top-most context in the stack. Once the parser leaves the clause that required a local context, the parser pops the top-most context. */ List context_stack; SELECT_LEX *select_stack[MAX_SELECT_NESTING + 1]; uint select_stack_top; /* Usually this is set to 0, but for INSERT/REPLACE SELECT it is set to 1. When parsing such statements the pointer to the most outer select is placed into the second element of select_stack rather than into the first. */ uint select_stack_outer_barrier; SQL_I_List proc_list; SQL_I_List auxiliary_table_list, save_list; Column_definition *last_field; Table_function_json_table *json_table; Item_sum *in_sum_func; udf_func udf; HA_CHECK_OPT check_opt; // check/repair options Table_specification_st create_info; Key *last_key; LEX_MASTER_INFO mi; // used by CHANGE MASTER LEX_SERVER_OPTIONS server_options; LEX_CSTRING relay_log_connection_name; LEX_RESET_SLAVE reset_slave_info; ulonglong type; ulong next_binlog_file_number; /* The following is used by KILL */ killed_state kill_signal; killed_type kill_type; uint current_select_number; // valid for statment LEX (not view) /* The following bool variables should not be bit fields as they are not reset for every query */ bool autocommit; // Often used, better as bool bool sp_lex_in_use; // Keep track on lex usage in SPs for error handling /* Bit fields, reset for every query */ bool is_shutdown_wait_for_slaves:1; bool selects_allow_procedure:1; /* A special command "PARSE_VCOL_EXPR" is defined for the parser to translate a defining expression of a virtual column into an Item object. The following flag is used to prevent other applications to use this command. */ bool parse_vcol_expr:1; bool analyze_stmt:1; /* TRUE<=> this is "ANALYZE $stmt" */ bool explain_json:1; /* true <=> The parsed fragment requires resolution of references to CTE at the end of parsing. This name resolution process involves searching for possible dependencies between CTE defined in the parsed fragment and detecting possible recursive references. The flag is set to true if the fragment contains CTE definitions. */ bool with_cte_resolution:1; /* true <=> only resolution of references to CTE are required in the parsed fragment, no checking of dependencies between CTE is required. This flag is used only when parsing clones of CTE specifications. */ bool only_cte_resolution:1; bool local_file:1; bool check_exists:1; bool verbose:1, no_write_to_binlog:1; bool safe_to_cache_query:1; bool ignore:1; bool next_is_main:1; // use "main" SELECT_LEX for nrxt allocation; bool next_is_down:1; // use "main" SELECT_LEX for nrxt allocation; /* field_list was created for view and should be removed before PS/SP rexecuton */ bool empty_field_list_on_rset:1; /** During name resolution search only in the table list given by Name_resolution_context::first_name_resolution_table and Name_resolution_context::last_name_resolution_table (see Item_field::fix_fields()). */ bool use_only_table_context:1; bool escape_used:1; bool default_used:1; /* using default() function */ bool with_rownum:1; /* Using rownum() function */ bool is_lex_started:1; /* If lex_start() did run. For debugging. */ /* This variable is used in post-parse stage to declare that sum-functions, or functions which have sense only if GROUP BY is present, are allowed. For example in a query SELECT ... FROM ...WHERE MIN(i) == 1 GROUP BY ... HAVING MIN(i) > 2 MIN(i) in the WHERE clause is not allowed in the opposite to MIN(i) in the HAVING clause. Due to possible nesting of select construct the variable can contain 0 or 1 for each nest level. */ nesting_map allow_sum_func; Sql_cmd *m_sql_cmd; /* Usually `expr` rule of yacc is quite reused but some commands better not support subqueries which comes standard with this rule, like KILL, HA_READ, CREATE/ALTER EVENT etc. Set this to a non-NULL clause name to get an error. */ const char *clause_that_disallows_subselect; enum enum_duplicates duplicates; enum enum_tx_isolation tx_isolation; enum enum_ha_read_modes ha_read_mode; union { enum ha_rkey_function ha_rkey_mode; enum xa_option_words xa_opt; bool with_admin_option; // GRANT role bool with_persistent_for_clause; // uses PERSISTENT FOR clause (in ANALYZE) }; enum enum_var_type option_type; enum enum_drop_mode drop_mode; enum backup_stages backup_stage; enum Foreign_key::fk_match_opt fk_match_option; enum_fk_option fk_update_opt; enum_fk_option fk_delete_opt; enum enum_yes_no_unknown tx_chain, tx_release; st_parsing_options parsing_options; /* In sql_cache we store SQL_CACHE flag as specified by user to be able to restore SELECT statement from internal structures. */ enum e_sql_cache { SQL_CACHE_UNSPECIFIED, SQL_NO_CACHE, SQL_CACHE }; e_sql_cache sql_cache; uint slave_thd_opt, start_transaction_opt; uint profile_query_id; uint profile_options; int nest_level; /* In LEX representing update which were transformed to multi-update stores total number of tables. For LEX representing multi-delete holds number of tables from which we will delete records. */ uint table_count_update; uint8 describe; /* A flag that indicates what kinds of derived tables are present in the query (0 if no derived tables, otherwise a combination of flags DERIVED_SUBQUERY and DERIVED_VIEW). */ uint8 derived_tables; uint8 context_analysis_only; uint8 lex_options; // see OPTION_LEX_* Alter_info alter_info; Lex_prepared_stmt prepared_stmt; /* For CREATE TABLE statement last element of table list which is not part of SELECT or LIKE part (i.e. either element for table we are creating or last of tables referenced by foreign keys). */ TABLE_LIST *create_last_non_select_table; sp_head *sphead; sp_name *spname; sp_pcontext *spcont; st_sp_chistics sp_chistics; Event_parse_data *event_parse_data; /* Characterstics of trigger being created */ st_trg_chistics trg_chistics; /* List of all items (Item_trigger_field objects) representing fields in old/new version of row in trigger. We use this list for checking whenever all such fields are valid at trigger creation time and for binding these fields to TABLE object at table open (altough for latter pointer to table being opened is probably enough). */ SQL_I_List trg_table_fields; /* stmt_definition_begin is intended to point to the next word after DEFINER-clause in the following statements: - CREATE TRIGGER (points to "TRIGGER"); - CREATE PROCEDURE (points to "PROCEDURE"); - CREATE FUNCTION (points to "FUNCTION" or "AGGREGATE"); - CREATE EVENT (points to "EVENT") This pointer is required to add possibly omitted DEFINER-clause to the DDL-statement before dumping it to the binlog. keyword_delayed_begin_offset is the offset to the beginning of the DELAYED keyword in INSERT DELAYED statement. keyword_delayed_end_offset is the offset to the character right after the DELAYED keyword. */ union { const char *stmt_definition_begin; uint keyword_delayed_begin_offset; }; union { const char *stmt_definition_end; uint keyword_delayed_end_offset; }; /** Collects create options for KEY */ engine_option_value *option_list; /** Helper pointer to the end of the list when parsing options for LEX::create_info.option_list (for table) LEX::last_field->option_list (for fields) LEX::option_list (for indexes) */ engine_option_value *option_list_last; /* Reference to a struct that contains information in various commands to add/create/drop/change table spaces. */ st_alter_tablespace *alter_tablespace_info; /* The set of those tables whose fields are referenced in all subqueries of the query. TODO: possibly this it is incorrect to have used tables in LEX because with subquery, it is not clear what does the field mean. To fix this we should aggregate used tables information for selected expressions into the select_lex. */ table_map used_tables; /** Maximum number of rows and/or keys examined by the query, both read, changed or written. This is the argument of LIMIT ROWS EXAMINED. The limit is represented by two variables - the Item is needed because in case of parameters we have to delay its evaluation until execution. Once evaluated, its value is stored in examined_rows_limit_cnt. */ Item *limit_rows_examined; ulonglong limit_rows_examined_cnt; /** Holds a set of domain_ids for deletion at FLUSH..DELETE_DOMAIN_ID */ DYNAMIC_ARRAY delete_gtid_domain; static const ulong initial_gtid_domain_buffer_size= 16; uint32 gtid_domain_static_buffer[initial_gtid_domain_buffer_size]; inline void set_limit_rows_examined() { if (limit_rows_examined) limit_rows_examined_cnt= limit_rows_examined->val_uint(); else limit_rows_examined_cnt= ULONGLONG_MAX; } LEX_CSTRING *win_ref; Window_frame *win_frame; Window_frame_bound *frame_top_bound; Window_frame_bound *frame_bottom_bound; Window_spec *win_spec; Item *upd_del_where; /* System Versioning */ vers_select_conds_t vers_conditions; vers_select_conds_t period_conditions; inline void free_set_stmt_mem_root() { DBUG_ASSERT(!is_arena_for_set_stmt()); if (mem_root_for_set_stmt) { free_root(mem_root_for_set_stmt, MYF(0)); delete mem_root_for_set_stmt; mem_root_for_set_stmt= 0; } } LEX(); virtual ~LEX() { free_set_stmt_mem_root(); destroy_query_tables_list(); plugin_unlock_list(NULL, (plugin_ref *)plugins.buffer, plugins.elements); delete_dynamic(&plugins); } virtual class Query_arena *query_arena() { DBUG_ASSERT(0); return NULL; } void start(THD *thd); inline bool is_ps_or_view_context_analysis() { return (context_analysis_only & (CONTEXT_ANALYSIS_ONLY_PREPARE | CONTEXT_ANALYSIS_ONLY_VCOL_EXPR | CONTEXT_ANALYSIS_ONLY_VIEW)); } inline bool is_view_context_analysis() { return (context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW); } /** Mark all queries in this lex structure as uncacheable for the cause given @param cause the reason queries are to be marked as uncacheable Note, any cause is sufficient for st_select_lex_unit::can_be_merged() to disallow query merges. */ inline void uncacheable(uint8 cause) { safe_to_cache_query= 0; if (current_select) // initialisation SP variables has no SELECT { /* There are no sense to mark select_lex and union fields of LEX, but we should merk all subselects as uncacheable from current till most upper */ SELECT_LEX *sl; SELECT_LEX_UNIT *un; for (sl= current_select, un= sl->master_unit(); un && un != &unit; sl= sl->outer_select(), un= (sl ? sl->master_unit() : NULL)) { sl->uncacheable|= cause; un->uncacheable|= cause; } if (sl) sl->uncacheable|= cause; } if (first_select_lex()) first_select_lex()->uncacheable|= cause; } void set_trg_event_type_for_tables(); TABLE_LIST *unlink_first_table(bool *link_to_local); void link_first_table_back(TABLE_LIST *first, bool link_to_local); void first_lists_tables_same(); void fix_first_select_number(); bool can_be_merged(); bool can_use_merged(); bool can_not_use_merged(); bool only_view_structure(); bool need_correct_ident(); uint8 get_effective_with_check(TABLE_LIST *view); /* Is this update command where 'WHITH CHECK OPTION' clause is important SYNOPSIS LEX::which_check_option_applicable() RETURN TRUE have to take 'WHITH CHECK OPTION' clause into account FALSE 'WHITH CHECK OPTION' clause do not need */ inline bool which_check_option_applicable() { switch (sql_command) { case SQLCOM_UPDATE: case SQLCOM_UPDATE_MULTI: case SQLCOM_DELETE: case SQLCOM_DELETE_MULTI: case SQLCOM_INSERT: case SQLCOM_INSERT_SELECT: case SQLCOM_REPLACE: case SQLCOM_REPLACE_SELECT: case SQLCOM_LOAD: return TRUE; default: return FALSE; } } void cleanup_after_one_table_open(); bool push_context(Name_resolution_context *context); Name_resolution_context *pop_context(); SELECT_LEX *select_stack_head() { if (likely(select_stack_top)) return select_stack[select_stack_top - 1]; return NULL; } bool push_select(SELECT_LEX *select_lex) { DBUG_ENTER("LEX::push_select"); DBUG_PRINT("info", ("Top Select was %p (%d) depth: %u pushed: %p (%d)", select_stack_head(), select_stack_top, (select_stack_top ? select_stack_head()->select_number : 0), select_lex, select_lex->select_number)); if (unlikely(select_stack_top > MAX_SELECT_NESTING)) { my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0)); DBUG_RETURN(TRUE); } if (push_context(&select_lex->context)) DBUG_RETURN(TRUE); select_stack[select_stack_top++]= select_lex; current_select= select_lex; DBUG_RETURN(FALSE); } SELECT_LEX *pop_select() { DBUG_ENTER("LEX::pop_select"); SELECT_LEX *select_lex; if (likely(select_stack_top)) select_lex= select_stack[--select_stack_top]; else select_lex= 0; DBUG_PRINT("info", ("Top Select is %p (%d) depth: %u poped: %p (%d)", select_stack_head(), select_stack_top, (select_stack_top ? select_stack_head()->select_number : 0), select_lex, (select_lex ? select_lex->select_number : 0))); DBUG_ASSERT(select_lex); pop_context(); if (unlikely(!select_stack_top)) { current_select= &builtin_select; DBUG_PRINT("info", ("Top Select is empty -> sel builtin: %p service: %u", current_select, builtin_select.is_service_select)); builtin_select.is_service_select= false; } else current_select= select_stack[select_stack_top - 1]; DBUG_RETURN(select_lex); } SELECT_LEX *current_select_or_default() { return current_select ? current_select : &builtin_select; } bool copy_db_to(LEX_CSTRING *to); void inc_select_stack_outer_barrier() { select_stack_outer_barrier++; } SELECT_LEX *parser_current_outer_select() { return select_stack_top - 1 == select_stack_outer_barrier ? 0 : select_stack[select_stack_top - 2]; } Name_resolution_context *current_context() { return context_stack.head(); } /* Restore the LEX and THD in case of a parse error. */ static void cleanup_lex_after_parse_error(THD *thd); void reset_n_backup_query_tables_list(Query_tables_list *backup); void restore_backup_query_tables_list(Query_tables_list *backup); bool table_or_sp_used(); bool is_partition_management() const; bool part_values_current(THD *thd); bool part_values_history(THD *thd); /** @brief check if the statement is a single-level join @return result of the check @retval TRUE The statement doesn't contain subqueries, unions and stored procedure calls. @retval FALSE There are subqueries, UNIONs or stored procedure calls. */ bool is_single_level_stmt() { /* This check exploits the fact that the last added to all_select_list is on its top. So select_lex (as the first added) will be at the tail of the list. */ if (first_select_lex() == all_selects_list && !sroutines.records) { return TRUE; } return FALSE; } bool save_prep_leaf_tables(); int print_explain(select_result_sink *output, uint8 explain_flags, bool is_analyze, bool *printed_anything); bool restore_set_statement_var(); void init_last_field(Column_definition *field, const LEX_CSTRING *name, const CHARSET_INFO *cs); bool last_field_generated_always_as_row_start_or_end(Lex_ident *p, const char *type, uint flags); bool last_field_generated_always_as_row_start(); bool last_field_generated_always_as_row_end(); bool set_bincmp(CHARSET_INFO *cs, bool bin); bool new_sp_instr_stmt(THD *, const LEX_CSTRING &prefix, const LEX_CSTRING &suffix); bool sp_proc_stmt_statement_finalize_buf(THD *, const LEX_CSTRING &qbuf); bool sp_proc_stmt_statement_finalize(THD *, bool no_lookahead); sp_variable *sp_param_init(LEX_CSTRING *name); bool sp_param_fill_definition(sp_variable *spvar, const Lex_field_type_st &def); bool sf_return_fill_definition(const Lex_field_type_st &def); int case_stmt_action_then(); bool setup_select_in_parentheses(); bool set_trigger_new_row(const LEX_CSTRING *name, Item *val); bool set_trigger_field(const LEX_CSTRING *name1, const LEX_CSTRING *name2, Item *val); bool set_system_variable(enum_var_type var_type, sys_var *var, const Lex_ident_sys_st *base_name, Item *val); bool set_system_variable(enum_var_type var_type, const Lex_ident_sys_st *name, Item *val); bool set_system_variable(THD *thd, enum_var_type var_type, const Lex_ident_sys_st *name1, const Lex_ident_sys_st *name2, Item *val); bool set_default_system_variable(enum_var_type var_type, const Lex_ident_sys_st *name, Item *val); bool set_user_variable(THD *thd, const LEX_CSTRING *name, Item *val); void set_stmt_init(); sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name); sp_name *make_sp_name(THD *thd, const LEX_CSTRING *name1, const LEX_CSTRING *name2); sp_name *make_sp_name_package_routine(THD *thd, const LEX_CSTRING *name); sp_head *make_sp_head(THD *thd, const sp_name *name, const Sp_handler *sph, enum_sp_aggregate_type agg_type); sp_head *make_sp_head_no_recursive(THD *thd, const sp_name *name, const Sp_handler *sph, enum_sp_aggregate_type agg_type); bool sp_body_finalize_routine(THD *); bool sp_body_finalize_trigger(THD *); bool sp_body_finalize_event(THD *); bool sp_body_finalize_function(THD *); bool sp_body_finalize_procedure(THD *); bool sp_body_finalize_procedure_standalone(THD *, const sp_name *end_name); sp_package *create_package_start(THD *thd, enum_sql_command command, const Sp_handler *sph, const sp_name *name, DDL_options_st options); bool create_package_finalize(THD *thd, const sp_name *name, const sp_name *name2, const char *cpp_body_end); bool call_statement_start(THD *thd, sp_name *name); bool call_statement_start(THD *thd, const Lex_ident_sys_st *name); bool call_statement_start(THD *thd, const Lex_ident_sys_st *name1, const Lex_ident_sys_st *name2); bool call_statement_start(THD *thd, const Lex_ident_sys_st *db, const Lex_ident_sys_st *pkg, const Lex_ident_sys_st *proc); sp_variable *find_variable(const LEX_CSTRING *name, sp_pcontext **ctx, const Sp_rcontext_handler **rh) const; sp_variable *find_variable(const LEX_CSTRING *name, const Sp_rcontext_handler **rh) const { sp_pcontext *not_used_ctx; return find_variable(name, ¬_used_ctx, rh); } bool set_variable(const Lex_ident_sys_st *name, Item *item); bool set_variable(const Lex_ident_sys_st *name1, const Lex_ident_sys_st *name2, Item *item); void sp_variable_declarations_init(THD *thd, int nvars); bool sp_variable_declarations_finalize(THD *thd, int nvars, const Column_definition *cdef, Item *def); bool sp_variable_declarations_set_default(THD *thd, int nvars, Item *def); bool sp_variable_declarations_row_finalize(THD *thd, int nvars, Row_definition_list *row, Item *def); bool sp_variable_declarations_with_ref_finalize(THD *thd, int nvars, Qualified_column_ident *col, Item *def); bool sp_variable_declarations_rowtype_finalize(THD *thd, int nvars, Qualified_column_ident *, Item *def); bool sp_variable_declarations_cursor_rowtype_finalize(THD *thd, int nvars, uint offset, Item *def); bool sp_variable_declarations_table_rowtype_finalize(THD *thd, int nvars, const LEX_CSTRING &db, const LEX_CSTRING &table, Item *def); bool sp_variable_declarations_column_type_finalize(THD *thd, int nvars, Qualified_column_ident *ref, Item *def); bool sp_variable_declarations_vartype_finalize(THD *thd, int nvars, const LEX_CSTRING &name, Item *def); bool sp_variable_declarations_copy_type_finalize(THD *thd, int nvars, const Column_definition &ref, Row_definition_list *fields, Item *def); LEX_USER *current_user_for_set_password(THD *thd); bool sp_create_set_password_instr(THD *thd, LEX_USER *user, USER_AUTH *auth, bool no_lookahead); bool sp_create_set_password_instr(THD *thd, USER_AUTH *auth, bool no_lookahead) { LEX_USER *user; return !(user= current_user_for_set_password(thd)) || sp_create_set_password_instr(thd, user, auth, no_lookahead); } bool sp_handler_declaration_init(THD *thd, int type); bool sp_handler_declaration_finalize(THD *thd, int type); bool sp_declare_cursor(THD *thd, const LEX_CSTRING *name, class sp_lex_cursor *cursor_stmt, sp_pcontext *param_ctx, bool add_cpush_instr); bool sp_open_cursor(THD *thd, const LEX_CSTRING *name, List *parameters); Item_splocal *create_item_for_sp_var(const Lex_ident_cli_st *name, sp_variable *spvar); Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_sys_st *name); Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_sys_st *a, const Lex_ident_sys_st *b); Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_cli_st *cname) { Lex_ident_sys name(thd, cname); if (name.is_null()) return NULL; // EOM return create_item_qualified_asterisk(thd, &name); } Item *create_item_qualified_asterisk(THD *thd, const Lex_ident_cli_st *ca, const Lex_ident_cli_st *cb) { Lex_ident_sys a(thd, ca), b(thd, cb); if (a.is_null() || b.is_null()) return NULL; // EOM return create_item_qualified_asterisk(thd, &a, &b); } Item *create_item_ident_field(THD *thd, const Lex_ident_sys_st &db, const Lex_ident_sys_st &table, const Lex_ident_sys_st &name); Item *create_item_ident_nosp(THD *thd, Lex_ident_sys_st *name) { return create_item_ident_field(thd, Lex_ident_sys(), Lex_ident_sys(), *name); } Item *create_item_ident_sp(THD *thd, Lex_ident_sys_st *name, const char *start, const char *end); Item *create_item_ident(THD *thd, Lex_ident_cli_st *cname) { Lex_ident_sys name(thd, cname); if (name.is_null()) return NULL; // EOM return sphead ? create_item_ident_sp(thd, &name, cname->pos(), cname->end()) : create_item_ident_nosp(thd, &name); } /* Create an Item corresponding to a qualified name: a.b when the parser is out of an SP context. @param THD - THD, for mem_root @param a - the first name @param b - the second name @retval - a pointer to a created item, or NULL on error. Possible Item types that can be created: - Item_trigger_field - Item_field - Item_ref */ Item *create_item_ident_nospvar(THD *thd, const Lex_ident_sys_st *a, const Lex_ident_sys_st *b); /* Create an Item corresponding to a ROW field valiable: var.field @param THD - THD, for mem_root @param rh [OUT] - the rcontext handler (local vs package variables) @param var - the ROW variable name @param field - the ROW variable field name @param spvar - the variable that was previously found by name using "var_name". @param start - position in the query (for binary log) @param end - end in the query (for binary log) */ Item_splocal *create_item_spvar_row_field(THD *thd, const Sp_rcontext_handler *rh, const Lex_ident_sys *var, const Lex_ident_sys *field, sp_variable *spvar, const char *start, const char *end); /* Create an item from its qualified name. Depending on context, it can be either a ROW variable field, or trigger, table field, table field reference. See comments to create_item_spvar_row_field() and create_item_ident_nospvar(). @param thd - THD, for mem_root @param a - the first name @param b - the second name @retval - NULL on error, or a pointer to a new Item. */ Item *create_item_ident(THD *thd, const Lex_ident_cli_st *a, const Lex_ident_cli_st *b); /* Create an item from its qualified name. Depending on context, it can be a table field, a table field reference, or a sequence NEXTVAL and CURRVAL. @param thd - THD, for mem_root @param a - the first name @param b - the second name @param c - the third name @retval - NULL on error, or a pointer to a new Item. */ Item *create_item_ident(THD *thd, const Lex_ident_sys_st *a, const Lex_ident_sys_st *b, const Lex_ident_sys_st *c); Item *create_item_ident(THD *thd, const Lex_ident_cli_st *ca, const Lex_ident_cli_st *cb, const Lex_ident_cli_st *cc) { Lex_ident_sys b(thd, cb), c(thd, cc); if (b.is_null() || c.is_null()) return NULL; if (ca->pos() == cb->pos()) // SELECT .t1.col1 { DBUG_ASSERT(ca->length == 0); Lex_ident_sys none; return create_item_ident(thd, &none, &b, &c); } Lex_ident_sys a(thd, ca); return a.is_null() ? NULL : create_item_ident(thd, &a, &b, &c); } /* Create an item for "NEXT VALUE FOR sequence_name" */ Item *create_item_func_nextval(THD *thd, Table_ident *ident); Item *create_item_func_nextval(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *name); /* Create an item for "PREVIOUS VALUE FOR sequence_name" */ Item *create_item_func_lastval(THD *thd, Table_ident *ident); Item *create_item_func_lastval(THD *thd, const LEX_CSTRING *db, const LEX_CSTRING *name); /* Create an item for "SETVAL(sequence_name, value [, is_used [, round]]) */ Item *create_item_func_setval(THD *thd, Table_ident *ident, longlong value, ulonglong round, bool is_used); /* Create an item for a name in LIMIT clause: LIMIT var @param THD - THD, for mem_root @param var_name - the variable name @retval - a new Item corresponding to the SP variable, or NULL on error (non in SP, unknown variable, wrong data type). */ Item *create_item_limit(THD *thd, const Lex_ident_cli_st *var_name); /* Create an item for a qualified name in LIMIT clause: LIMIT var.field @param THD - THD, for mem_root @param var_name - the variable name @param field_name - the variable field name @param start - start in the query (for binary log) @param end - end in the query (for binary log) @retval - a new Item corresponding to the SP variable, or NULL on error (non in SP, unknown variable, unknown ROW field, wrong data type). */ Item *create_item_limit(THD *thd, const Lex_ident_cli_st *var_name, const Lex_ident_cli_st *field_name); Item *create_item_query_expression(THD *thd, st_select_lex_unit *unit); Item *make_item_func_sysdate(THD *thd, uint fsp); static const Schema * find_func_schema_by_name_or_error(const Lex_ident_sys &schema_name, const Lex_ident_sys &func_name); Item *make_item_func_replace(THD *thd, const Lex_ident_cli_st &schema_name, const Lex_ident_cli_st &func_name, Item *org, Item *find, Item *replace); Item *make_item_func_replace(THD *thd, const Lex_ident_cli_st &schema_name, const Lex_ident_cli_st &func_name, List *args); Item *make_item_func_substr(THD *thd, const Lex_ident_cli_st &schema_name, const Lex_ident_cli_st &func_name, const Lex_substring_spec_st &spec); Item *make_item_func_substr(THD *thd, const Lex_ident_cli_st &schema_name, const Lex_ident_cli_st &func_name, List *args); Item *make_item_func_trim(THD *thd, const Lex_ident_cli_st &schema_name, const Lex_ident_cli_st &func_name, const Lex_trim_st &spec); Item *make_item_func_trim(THD *thd, const Lex_ident_cli_st &schema_name, const Lex_ident_cli_st &func_name, List *args); Item *make_item_func_call_generic(THD *thd, const Lex_ident_cli_st *db, const Lex_ident_cli_st *name, List *args); Item *make_item_func_call_generic(THD *thd, const Lex_ident_sys &db, const Lex_ident_sys &name, List *args); Item *make_item_func_call_generic(THD *thd, Lex_ident_cli_st *db, Lex_ident_cli_st *pkg, Lex_ident_cli_st *name, List *args); Item *make_item_func_call_native_or_parse_error(THD *thd, Lex_ident_cli_st &name, List *args); my_var *create_outvar(THD *thd, const LEX_CSTRING *name); /* Create a my_var instance for a ROW field variable that was used as an OUT SP parameter: CALL p1(var.field); @param THD - THD, for mem_root @param var_name - the variable name @param field_name - the variable field name */ my_var *create_outvar(THD *thd, const LEX_CSTRING *var_name, const LEX_CSTRING *field_name); bool is_trigger_new_or_old_reference(const LEX_CSTRING *name) const; Item *create_and_link_Item_trigger_field(THD *thd, const LEX_CSTRING *name, bool new_row); // For syntax with colon, e.g. :NEW.a or :OLD.a Item *make_item_colon_ident_ident(THD *thd, const Lex_ident_cli_st *a, const Lex_ident_cli_st *b); // PLSQL: cursor%ISOPEN etc Item *make_item_plsql_cursor_attr(THD *thd, const LEX_CSTRING *name, plsql_cursor_attr_t attr); // For "SELECT @@var", "SELECT @@var.field" Item *make_item_sysvar(THD *thd, enum_var_type type, const LEX_CSTRING *name) { return make_item_sysvar(thd, type, name, &null_clex_str); } Item *make_item_sysvar(THD *thd, enum_var_type type, const LEX_CSTRING *name, const LEX_CSTRING *component); void sp_block_init(THD *thd, const LEX_CSTRING *label); void sp_block_init(THD *thd) { // Unlabeled blocks get an empty label sp_block_init(thd, &empty_clex_str); } bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock) { class sp_label *tmp; return sp_block_finalize(thd, spblock, &tmp); } bool sp_block_finalize(THD *thd) { return sp_block_finalize(thd, Lex_spblock()); } bool sp_block_finalize(THD *thd, const Lex_spblock_st spblock, const LEX_CSTRING *end_label); bool sp_block_finalize(THD *thd, const LEX_CSTRING *end_label) { return sp_block_finalize(thd, Lex_spblock(), end_label); } bool sp_declarations_join(Lex_spblock_st *res, const Lex_spblock_st b1, const Lex_spblock_st b2) const { if ((b2.vars || b2.conds) && (b1.curs || b1.hndlrs)) { my_error(ER_SP_VARCOND_AFTER_CURSHNDLR, MYF(0)); return true; } if (b2.curs && b1.hndlrs) { my_error(ER_SP_CURSOR_AFTER_HANDLER, MYF(0)); return true; } res->join(b1, b2); return false; } bool sp_block_with_exceptions_finalize_declarations(THD *thd); bool sp_block_with_exceptions_finalize_executable_section(THD *thd, uint executable_section_ip); bool sp_block_with_exceptions_finalize_exceptions(THD *thd, uint executable_section_ip, uint exception_count); bool sp_block_with_exceptions_add_empty(THD *thd); bool sp_exit_statement(THD *thd, Item *when); bool sp_exit_statement(THD *thd, const LEX_CSTRING *label_name, Item *item); bool sp_leave_statement(THD *thd, const LEX_CSTRING *label_name); bool sp_goto_statement(THD *thd, const LEX_CSTRING *label_name); bool sp_continue_statement(THD *thd); bool sp_continue_statement(THD *thd, const LEX_CSTRING *label_name); bool sp_iterate_statement(THD *thd, const LEX_CSTRING *label_name); bool maybe_start_compound_statement(THD *thd); bool sp_push_loop_label(THD *thd, const LEX_CSTRING *label_name); bool sp_push_loop_empty_label(THD *thd); bool sp_pop_loop_label(THD *thd, const LEX_CSTRING *label_name); void sp_pop_loop_empty_label(THD *thd); bool sp_while_loop_expression(THD *thd, Item *expr); bool sp_while_loop_finalize(THD *thd); bool sp_if_after_statements(THD *thd); bool sp_push_goto_label(THD *thd, const LEX_CSTRING *label_name); Item_param *add_placeholder(THD *thd, const LEX_CSTRING *name, const char *start, const char *end); /* Integer range FOR LOOP methods */ sp_variable *sp_add_for_loop_variable(THD *thd, const LEX_CSTRING *name, Item *value); sp_variable *sp_add_for_loop_target_bound(THD *thd, Item *value) { LEX_CSTRING name= { STRING_WITH_LEN("[target_bound]") }; return sp_add_for_loop_variable(thd, &name, value); } bool sp_for_loop_intrange_declarations(THD *thd, Lex_for_loop_st *loop, const LEX_CSTRING *index, const Lex_for_loop_bounds_st &bounds); bool sp_for_loop_intrange_condition_test(THD *thd, const Lex_for_loop_st &loop); bool sp_for_loop_intrange_iterate(THD *thd, const Lex_for_loop_st &loop); /* Cursor FOR LOOP methods */ bool sp_for_loop_cursor_declarations(THD *thd, Lex_for_loop_st *loop, const LEX_CSTRING *index, const Lex_for_loop_bounds_st &bounds); sp_variable *sp_add_for_loop_cursor_variable(THD *thd, const LEX_CSTRING *name, const class sp_pcursor *cur, uint coffset, sp_assignment_lex *param_lex, Item_args *parameters); bool sp_for_loop_implicit_cursor_statement(THD *thd, Lex_for_loop_bounds_st *bounds, sp_lex_cursor *cur); bool sp_for_loop_cursor_condition_test(THD *thd, const Lex_for_loop_st &loop); bool sp_for_loop_cursor_iterate(THD *thd, const Lex_for_loop_st &); /* Generic FOR LOOP methods*/ /* Generate FOR loop declarations and initialize "loop" from "index" and "bounds". @param [IN] thd - current THD, for mem_root and error reporting @param [OUT] loop - the loop generated SP variables are stored here, together with additional loop characteristics. @param [IN] index - the loop index variable name @param [IN] bounds - the loop bounds (in sp_assignment_lex format) and additional loop characteristics, as created by the sp_for_loop_bounds rule. @retval true - on error @retval false - on success This methods adds declarations: - An explicit integer or cursor%ROWTYPE "index" variable - An implicit integer upper bound variable, in case of integer range loops - A CURSOR, in case of an implicit CURSOR loops The generated variables are stored into "loop". Additional loop characteristics are copied from "bounds" to "loop". */ bool sp_for_loop_declarations(THD *thd, Lex_for_loop_st *loop, const LEX_CSTRING *index, const Lex_for_loop_bounds_st &bounds) { return bounds.is_for_loop_cursor() ? sp_for_loop_cursor_declarations(thd, loop, index, bounds) : sp_for_loop_intrange_declarations(thd, loop, index, bounds); } /* Generate a conditional jump instruction to leave the loop, using a proper condition depending on the loop type: - Item_func_le -- integer range loops - Item_func_ge -- integer range reverse loops - Item_func_cursor_found -- cursor loops */ bool sp_for_loop_condition_test(THD *thd, const Lex_for_loop_st &loop) { return loop.is_for_loop_cursor() ? sp_for_loop_cursor_condition_test(thd, loop) : sp_for_loop_intrange_condition_test(thd, loop); } /* Generate "increment" instructions followed by a jump to the condition test in the beginnig of the loop. "Increment" depends on the loop type and can be: - index:= index + 1; -- integer range loops - index:= index - 1; -- integer range reverse loops - FETCH cursor INTO index; -- cursor loops */ bool sp_for_loop_finalize(THD *thd, const Lex_for_loop_st &loop) { if (loop.is_for_loop_cursor() ? sp_for_loop_cursor_iterate(thd, loop) : sp_for_loop_intrange_iterate(thd, loop)) return true; // Generate a jump to the beginning of the loop return sp_while_loop_finalize(thd); } bool sp_for_loop_outer_block_finalize(THD *thd, const Lex_for_loop_st &loop); /* Make an Item when an identifier is found in the FOR loop bounds: FOR rec IN cursor FOR rec IN var1 .. var2 FOR rec IN row1.field1 .. xxx */ Item *create_item_for_loop_bound(THD *thd, const LEX_CSTRING *a, const LEX_CSTRING *b, const LEX_CSTRING *c); /* End of FOR LOOP methods */ bool add_signal_statement(THD *thd, const class sp_condition_value *value); bool add_resignal_statement(THD *thd, const class sp_condition_value *value); // Check if "KEY IF NOT EXISTS name" used outside of ALTER context bool check_add_key(DDL_options_st ddl) { if (ddl.if_not_exists() && sql_command != SQLCOM_ALTER_TABLE) { parse_error(); return true; } return false; } // Add a key as a part of CREATE TABLE or ALTER TABLE bool add_key(Key::Keytype key_type, const LEX_CSTRING *key_name, ha_key_alg algorithm, DDL_options_st ddl) { if (check_add_key(ddl) || !(last_key= new Key(key_type, key_name, algorithm, false, ddl))) return true; alter_info.key_list.push_back(last_key); return false; } // Add a key for a CREATE INDEX statement bool add_create_index(Key::Keytype key_type, const LEX_CSTRING *key_name, ha_key_alg algorithm, DDL_options_st ddl) { if (check_create_options(ddl) || !(last_key= new Key(key_type, key_name, algorithm, false, ddl))) return true; alter_info.key_list.push_back(last_key); return false; } bool add_create_index_prepare(Table_ident *table) { sql_command= SQLCOM_CREATE_INDEX; if (!current_select->add_table_to_list(thd, table, NULL, TL_OPTION_UPDATING, TL_READ_NO_INSERT, MDL_SHARED_UPGRADABLE)) return true; alter_info.reset(); alter_info.flags= ALTER_ADD_INDEX; option_list= NULL; return false; } /* Add an UNIQUE or PRIMARY key which is a part of a column definition: CREATE TABLE t1 (a INT PRIMARY KEY); */ void add_key_to_list(LEX_CSTRING *field_name, enum Key::Keytype type, bool check_exists); // Add a constraint as a part of CREATE TABLE or ALTER TABLE bool add_constraint(const LEX_CSTRING &name, Virtual_column_info *constr, bool if_not_exists) { constr->name= name; constr->if_not_exists= if_not_exists; alter_info.check_constraint_list.push_back(constr); return false; } bool add_alter_list(LEX_CSTRING par_name, Virtual_column_info *expr, bool par_exists); bool add_alter_list(LEX_CSTRING name, LEX_CSTRING new_name, bool exists); void set_command(enum_sql_command command, DDL_options_st options) { sql_command= command; create_info.set(options); } void set_command(enum_sql_command command, uint scope, DDL_options_st options) { set_command(command, options); create_info.options|= scope; // HA_LEX_CREATE_TMP_TABLE or 0 } bool check_create_options(DDL_options_st options) { if (options.or_replace() && options.if_not_exists()) { my_error(ER_WRONG_USAGE, MYF(0), "OR REPLACE", "IF NOT EXISTS"); return true; } return false; } bool set_create_options_with_check(DDL_options_st options) { create_info.set(options); return check_create_options(create_info); } bool add_create_options_with_check(DDL_options_st options) { create_info.add(options); return check_create_options(create_info); } bool sp_add_cfetch(THD *thd, const LEX_CSTRING *name); bool sp_add_agg_cfetch(); bool set_command_with_check(enum_sql_command command, uint scope, DDL_options_st options) { set_command(command, scope, options); return check_create_options(options); } bool set_command_with_check(enum_sql_command command, DDL_options_st options) { set_command(command, options); return check_create_options(options); } /* DROP shares lex->create_info to store TEMPORARY and IF EXISTS options to save on extra initialization in lex_start(). Add some wrappers, to avoid direct use of lex->create_info in the caller code processing DROP statements (which might look confusing). */ bool tmp_table() const { return create_info.tmp_table(); } bool if_exists() const { return create_info.if_exists(); } /* Run specified phases for derived tables/views in the given list @param table_list - list of derived tables/view to handle @param phase - phases to process tables/views through @details This method runs phases specified by the 'phases' on derived tables/views found in the 'table_list' with help of the TABLE_LIST::handle_derived function. 'this' is passed as an argument to the TABLE_LIST::handle_derived. @return false - ok @return true - error */ bool handle_list_of_derived(TABLE_LIST *table_list, uint phases) { for (TABLE_LIST *tl= table_list; tl; tl= tl->next_local) { if (tl->is_view_or_derived() && tl->handle_derived(this, phases)) return true; } return false; } bool create_like() const { DBUG_ASSERT(!create_info.like() || !first_select_lex()->item_list.elements); return create_info.like(); } bool create_select() const { DBUG_ASSERT(!create_info.like() || !first_select_lex()->item_list.elements); return first_select_lex()->item_list.elements; } bool create_simple() const { return !create_like() && !create_select(); } SELECT_LEX *exclude_last_select(); SELECT_LEX *exclude_not_first_select(SELECT_LEX *exclude); void check_automatic_up(enum sub_select_type type); bool create_or_alter_view_finalize(THD *thd, Table_ident *table_ident); bool add_alter_view(THD *thd, uint16 algorithm, enum_view_suid suid, Table_ident *table_ident); bool add_create_view(THD *thd, DDL_options_st ddl, uint16 algorithm, enum_view_suid suid, Table_ident *table_ident); bool add_grant_command(THD *thd, const List &columns); bool stmt_grant_table(THD *thd, Grant_privilege *grant, const Lex_grant_object_name &ident, privilege_t grant_option); bool stmt_revoke_table(THD *thd, Grant_privilege *grant, const Lex_grant_object_name &ident); bool stmt_grant_sp(THD *thd, Grant_privilege *grant, const Lex_grant_object_name &ident, const Sp_handler &sph, privilege_t grant_option); bool stmt_revoke_sp(THD *thd, Grant_privilege *grant, const Lex_grant_object_name &ident, const Sp_handler &sph); bool stmt_grant_proxy(THD *thd, LEX_USER *user, privilege_t grant_option); bool stmt_revoke_proxy(THD *thd, LEX_USER *user); Vers_parse_info &vers_get_info() { return create_info.vers_info; } /* The list of history-generating DML commands */ bool vers_history_generating() const { switch (sql_command) { case SQLCOM_DELETE: return !vers_conditions.delete_history; case SQLCOM_UPDATE: case SQLCOM_UPDATE_MULTI: case SQLCOM_DELETE_MULTI: case SQLCOM_REPLACE: case SQLCOM_REPLACE_SELECT: return true; case SQLCOM_INSERT: case SQLCOM_INSERT_SELECT: return duplicates == DUP_UPDATE; case SQLCOM_LOAD: return duplicates == DUP_REPLACE; default: /* Row injections (i.e. row binlog events and BINLOG statements) should generate history. */ return is_stmt_row_injection(); } } int add_period(Lex_ident name, Lex_ident_sys_st start, Lex_ident_sys_st end) { if (check_period_name(name.str)) { my_error(ER_WRONG_COLUMN_NAME, MYF(0), name.str); return 1; } if (lex_string_cmp(system_charset_info, &start, &end) == 0) { my_error(ER_FIELD_SPECIFIED_TWICE, MYF(0), start.str); return 1; } Table_period_info &info= create_info.period_info; if (check_exists && info.name.streq(name)) return 0; if (info.is_set()) { my_error(ER_MORE_THAN_ONE_PERIOD, MYF(0)); return 1; } info.set_period(start, end); info.name= name; info.constr= new Virtual_column_info(); info.constr->expr= lt_creator.create(thd, create_item_ident_nosp(thd, &start), create_item_ident_nosp(thd, &end)); add_constraint(null_clex_str, info.constr, false); return 0; } sp_package *get_sp_package() const; /** Check if the select is a simple select (not an union). @retval 0 ok @retval 1 error ; In this case the error messege is sent to the client */ bool check_simple_select(const LEX_CSTRING *option) { if (current_select != &builtin_select) { char command[80]; strmake(command, option->str, MY_MIN(option->length, sizeof(command)-1)); my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command); return true; } return false; } SELECT_LEX_UNIT *alloc_unit(); SELECT_LEX *alloc_select(bool is_select); SELECT_LEX_UNIT *create_unit(SELECT_LEX*); SELECT_LEX *wrap_unit_into_derived(SELECT_LEX_UNIT *unit); SELECT_LEX *wrap_select_chain_into_derived(SELECT_LEX *sel); void init_select() { current_select->init_select(); wild= 0; exchange= 0; } bool main_select_push(bool service= false); bool insert_select_hack(SELECT_LEX *sel); SELECT_LEX *create_priority_nest(SELECT_LEX *first_in_nest); bool set_main_unit(st_select_lex_unit *u) { unit.options= u->options; unit.uncacheable= u->uncacheable; unit.register_select_chain(u->first_select()); unit.first_select()->options|= builtin_select.options; unit.fake_select_lex= u->fake_select_lex; unit.union_distinct= u->union_distinct; unit.set_with_clause(u->with_clause); builtin_select.exclude_from_global(); return false; } bool check_main_unit_semantics(); SELECT_LEX_UNIT *parsed_select_expr_start(SELECT_LEX *s1, SELECT_LEX *s2, enum sub_select_type unit_type, bool distinct); SELECT_LEX_UNIT *parsed_select_expr_cont(SELECT_LEX_UNIT *unit, SELECT_LEX *s2, enum sub_select_type unit_type, bool distinct, bool oracle); bool parsed_multi_operand_query_expression_body(SELECT_LEX_UNIT *unit); SELECT_LEX_UNIT *add_tail_to_query_expression_body(SELECT_LEX_UNIT *unit, Lex_order_limit_lock *l); SELECT_LEX_UNIT * add_tail_to_query_expression_body_ext_parens(SELECT_LEX_UNIT *unit, Lex_order_limit_lock *l); SELECT_LEX_UNIT *parsed_body_ext_parens_primary(SELECT_LEX_UNIT *unit, SELECT_LEX *primary, enum sub_select_type unit_type, bool distinct); SELECT_LEX_UNIT * add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit, SELECT_LEX *sel, enum sub_select_type unit_type, bool distinct, bool oracle); SELECT_LEX_UNIT * add_primary_to_query_expression_body(SELECT_LEX_UNIT *unit, SELECT_LEX *sel, enum sub_select_type unit_type, bool distinct); SELECT_LEX_UNIT * add_primary_to_query_expression_body_ext_parens( SELECT_LEX_UNIT *unit, SELECT_LEX *sel, enum sub_select_type unit_type, bool distinct); SELECT_LEX *parsed_subselect(SELECT_LEX_UNIT *unit); bool parsed_insert_select(SELECT_LEX *firs_select); void save_values_list_state(); void restore_values_list_state(); bool parsed_TVC_start(); SELECT_LEX *parsed_TVC_end(); TABLE_LIST *parsed_derived_table(SELECT_LEX_UNIT *unit, int for_system_time, LEX_CSTRING *alias); bool parsed_create_view(SELECT_LEX_UNIT *unit, int check); bool select_finalize(st_select_lex_unit *expr); bool select_finalize(st_select_lex_unit *expr, Lex_select_lock l); void relink_hack(st_select_lex *select_lex); bool stmt_install_plugin(const DDL_options_st &opt, const Lex_ident_sys_st &name, const LEX_CSTRING &soname); void stmt_install_plugin(const LEX_CSTRING &soname); bool stmt_uninstall_plugin_by_name(const DDL_options_st &opt, const Lex_ident_sys_st &name); bool stmt_uninstall_plugin_by_soname(const DDL_options_st &opt, const LEX_CSTRING &soname); bool stmt_prepare_validate(const char *stmt_type); bool stmt_prepare(const Lex_ident_sys_st &ident, Item *code); bool stmt_execute(const Lex_ident_sys_st &ident, List *params); bool stmt_execute_immediate(Item *code, List *params); void stmt_deallocate_prepare(const Lex_ident_sys_st &ident); bool stmt_alter_table_exchange_partition(Table_ident *table); void stmt_purge_to(const LEX_CSTRING &to); bool stmt_purge_before(Item *item); SELECT_LEX *returning() { return &builtin_select; } bool has_returning() { return !builtin_select.item_list.is_empty(); } private: bool stmt_create_routine_start(const DDL_options_st &options) { create_info.set(options); return main_select_push() || check_create_options(options); } public: bool stmt_create_function_start(const DDL_options_st &options) { sql_command= SQLCOM_CREATE_SPFUNCTION; return stmt_create_routine_start(options); } bool stmt_create_procedure_start(const DDL_options_st &options) { sql_command= SQLCOM_CREATE_PROCEDURE; return stmt_create_routine_start(options); } void stmt_create_routine_finalize() { pop_select(); // main select } bool stmt_create_stored_function_start(const DDL_options_st &options, enum_sp_aggregate_type, const sp_name *name); bool stmt_create_stored_function_finalize_standalone(const sp_name *end_name); bool stmt_create_udf_function(const DDL_options_st &options, enum_sp_aggregate_type agg_type, const Lex_ident_sys_st &name, Item_result return_type, const LEX_CSTRING &soname); bool stmt_drop_function(const DDL_options_st &options, const Lex_ident_sys_st &db, const Lex_ident_sys_st &name); bool stmt_drop_function(const DDL_options_st &options, const Lex_ident_sys_st &name); bool stmt_drop_procedure(const DDL_options_st &options, sp_name *name); bool stmt_alter_function_start(sp_name *name); bool stmt_alter_procedure_start(sp_name *name); sp_condition_value *stmt_signal_value(const Lex_ident_sys_st &ident); Spvar_definition *row_field_name(THD *thd, const Lex_ident_sys_st &name); bool set_field_type_udt(Lex_field_type_st *type, const LEX_CSTRING &name, const Lex_length_and_dec_st &attr); bool set_cast_type_udt(Lex_cast_type_st *type, const LEX_CSTRING &name); bool map_data_type(const Lex_ident_sys_st &schema, Lex_field_type_st *type) const; void mark_first_table_as_inserting(); bool fields_are_impossible() { // no select or it is last select with no tables (service select) return !select_stack_head() || (select_stack_top == 1 && select_stack[0]->is_service_select); } bool add_table_foreign_key(const LEX_CSTRING *name, const LEX_CSTRING *constraint_name, Table_ident *table_name, DDL_options ddl_options); bool add_column_foreign_key(const LEX_CSTRING *name, const LEX_CSTRING *constraint_name, Table_ident *ref_table_name, DDL_options ddl_options); bool check_dependencies_in_with_clauses(); bool check_cte_dependencies_and_resolve_references(); bool resolve_references_to_cte(TABLE_LIST *tables, TABLE_LIST **tables_last, st_select_lex_unit *excl_spec); /** Turn on the SELECT_DESCRIBE flag for every SELECT_LEX involved into the statement being processed in case the statement is EXPLAIN UPDATE/DELETE. @param lex current LEX */ void promote_select_describe_flag_if_needed() { if (describe) builtin_select.options |= SELECT_DESCRIBE; } }; /** Set_signal_information is a container used in the parsed tree to represent the collection of assignments to condition items in the SIGNAL and RESIGNAL statements. */ class Set_signal_information { public: /** Empty default constructor, use clear() */ Set_signal_information() = default; /** Copy constructor. */ Set_signal_information(const Set_signal_information& set); /** Destructor. */ ~Set_signal_information() = default; /** Clear all items. */ void clear(); /** For each condition item assignment, m_item[] contains the parsed tree that represents the expression assigned, if any. m_item[] is an array indexed by Diag_condition_item_name. */ Item *m_item[LAST_DIAG_SET_PROPERTY+1]; }; /** The internal state of the syntax parser. This object is only available during parsing, and is private to the syntax parser implementation (sql_yacc.yy). */ class Yacc_state { public: Yacc_state() : yacc_yyss(NULL), yacc_yyvs(NULL) { reset(); } void reset() { if (yacc_yyss != NULL) { my_free(yacc_yyss); yacc_yyss = NULL; } if (yacc_yyvs != NULL) { my_free(yacc_yyvs); yacc_yyvs = NULL; } m_set_signal_info.clear(); m_lock_type= TL_READ_DEFAULT; m_mdl_type= MDL_SHARED_READ; } ~Yacc_state(); /** Reset part of the state which needs resetting before parsing substatement. */ void reset_before_substatement() { m_lock_type= TL_READ_DEFAULT; m_mdl_type= MDL_SHARED_READ; } /** Bison internal state stack, yyss, when dynamically allocated using my_yyoverflow(). */ uchar *yacc_yyss; /** Bison internal semantic value stack, yyvs, when dynamically allocated using my_yyoverflow(). */ uchar *yacc_yyvs; /** Fragments of parsed tree, used during the parsing of SIGNAL and RESIGNAL. */ Set_signal_information m_set_signal_info; /** Type of lock to be used for tables being added to the statement's table list in table_factor, table_alias_ref, single_multi and table_wild_one rules. Statements which use these rules but require lock type different from one specified by this member have to override it by using st_select_lex::set_lock_for_tables() method. The default value of this member is TL_READ_DEFAULT. The only two cases in which we change it are: - When parsing SELECT HIGH_PRIORITY. - Rule for DELETE. In which we use this member to pass information about type of lock from delete to single_multi part of rule. We should try to avoid introducing new use cases as we would like to get rid of this member eventually. */ thr_lock_type m_lock_type; /** The type of requested metadata lock for tables added to the statement table list. */ enum_mdl_type m_mdl_type; /* TODO: move more attributes from the LEX structure here. */ }; /** Internal state of the parser. The complete state consist of: - state data used during lexical parsing, - state data used during syntactic parsing. */ class Parser_state { public: Parser_state() : m_yacc() {} /** Object initializer. Must be called before usage. @retval FALSE OK @retval TRUE Error */ bool init(THD *thd, char *buff, size_t length) { return m_lip.init(thd, buff, length); } ~Parser_state() = default; Lex_input_stream m_lip; Yacc_state m_yacc; /** Current performance digest instrumentation. */ PSI_digest_locker* m_digest_psi; void reset(char *found_semicolon, unsigned int length) { m_lip.reset(found_semicolon, length); m_yacc.reset(); } }; extern sql_digest_state * digest_add_token(sql_digest_state *state, uint token, LEX_YYSTYPE yylval); extern sql_digest_state * digest_reduce_token(sql_digest_state *state, uint token_left, uint token_right); struct st_lex_local: public LEX, public Sql_alloc { }; /** An st_lex_local extension with automatic initialization for SP purposes. Used to parse sub-expressions and SP sub-statements. This class is reused for: 1. sp_head::reset_lex() based constructs - SP variable assignments (e.g. SET x=10;) - FOR loop conditions and index variable increments - Cursor statements - SP statements - SP function RETURN statements - CASE statements - REPEAT..UNTIL expressions - WHILE expressions - EXIT..WHEN and CONTINUE..WHEN statements 2. sp_assignment_lex based constructs: - CURSOR parameter assignments */ class sp_lex_local: public st_lex_local { public: sp_lex_local(THD *thd, const LEX *oldlex) { /* Reset most stuff. */ start(thd); /* Keep the parent SP stuff */ sphead= oldlex->sphead; spcont= oldlex->spcont; /* Keep the parent trigger stuff too */ trg_chistics= oldlex->trg_chistics; trg_table_fields.empty(); sp_lex_in_use= false; } }; class sp_lex_set_var: public sp_lex_local { public: sp_lex_set_var(THD *thd, const LEX *oldlex) :sp_lex_local(thd, oldlex) { // Set new LEX as if we at start of set rule init_select(); sql_command= SQLCOM_SET_OPTION; var_list.empty(); autocommit= 0; option_type= oldlex->option_type; // Inherit from the outer lex } }; class sp_expr_lex: public sp_lex_local { Item *m_item; // The expression public: sp_expr_lex(THD *thd, LEX *oldlex) :sp_lex_local(thd, oldlex), m_item(NULL) { } void set_item(Item *item) { m_item= item; } Item *get_item() const { return m_item; } bool sp_continue_when_statement(THD *thd); bool sp_continue_when_statement(THD *thd, const LEX_CSTRING *label_name); int case_stmt_action_expr(); int case_stmt_action_when(bool simple); bool sp_while_loop_expression(THD *thd) { return LEX::sp_while_loop_expression(thd, get_item()); } bool sp_repeat_loop_finalize(THD *thd); bool sp_if_expr(THD *thd); }; /** An assignment specific LEX, which additionally has an Item (an expression) and an associated with the Item free_list, which is usually freed after the expression is calculated. Note, consider changing some of sp_lex_local to sp_assignment_lex, as the latter allows to use a simpler grammar in sql_yacc.yy (IMO). If the expression is simple (e.g. does not have function calls), then m_item and m_free_list point to the same Item. If the expressions is complex (e.g. have function calls), then m_item points to the leftmost Item, while m_free_list points to the rightmost item. For example: f1(COALESCE(f2(10), f2(20))) - m_item points to Item_func_sp for f1 (the leftmost Item) - m_free_list points to Item_int for 20 (the rightmost Item) Note, we could avoid storing m_item at all, as we can always reach the leftmost item from the rightmost item by iterating through m_free_list. But with a separate m_item the code should be faster. */ class sp_assignment_lex: public sp_lex_local { Item *m_item; // The expression Item *m_free_list; // The associated free_list (sub-expressions) public: sp_assignment_lex(THD *thd, LEX *oldlex) :sp_lex_local(thd, oldlex), m_item(NULL), m_free_list(NULL) { } void set_item_and_free_list(Item *item, Item *free_list) { m_item= item; m_free_list= free_list; } Item *get_item() const { return m_item; } Item *get_free_list() const { return m_free_list; } }; extern void lex_init(void); extern void lex_free(void); extern void lex_start(THD *thd); extern void lex_end(LEX *lex); extern void lex_end_nops(LEX *lex); extern void lex_unlock_plugins(LEX *lex); void end_lex_with_single_table(THD *thd, TABLE *table, LEX *old_lex); int init_lex_with_single_table(THD *thd, TABLE *table, LEX *lex); extern int MYSQLlex(union YYSTYPE *yylval, THD *thd); extern int ORAlex(union YYSTYPE *yylval, THD *thd); inline void trim_whitespace(CHARSET_INFO *cs, LEX_CSTRING *str, size_t * prefix_length = 0) { *str= Lex_cstring(*str).trim_whitespace(cs, prefix_length); } extern bool is_lex_native_function(const LEX_CSTRING *name); extern bool is_native_function(THD *thd, const LEX_CSTRING *name); extern bool is_native_function_with_warn(THD *thd, const LEX_CSTRING *name); /** @} (End of group Semantic_Analysis) */ void my_missing_function_error(const LEX_CSTRING &token, const char *name); bool is_keyword(const char *name, uint len); int set_statement_var_if_exists(THD *thd, const char *var_name, size_t var_name_length, ulonglong value); Virtual_column_info *add_virtual_expression(THD *thd, Item *expr); Item* handle_sql2003_note184_exception(THD *thd, Item* left, bool equal, Item *expr); bool sp_create_assignment_lex(THD *thd, const char *pos); bool sp_create_assignment_instr(THD *thd, bool no_lookahead, bool need_set_keyword= true); void mark_or_conds_to_avoid_pushdown(Item *cond); #endif /* MYSQL_SERVER */ #endif /* SQL_LEX_INCLUDED */ mysql/server/private/wsrep_binlog.h000064400000006561151027430560013547 0ustar00/* Copyright (C) 2013 Codership Oy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA. */ #ifndef WSREP_BINLOG_H #define WSREP_BINLOG_H #include "my_global.h" #include "sql_class.h" // THD, IO_CACHE #define HEAP_PAGE_SIZE 65536 /* 64K */ #define WSREP_MAX_WS_SIZE 2147483647 /* 2GB */ /* Write the contents of a cache to a memory buffer. This function quite the same as MYSQL_BIN_LOG::write_cache(), with the exception that here we write in buffer instead of log file. */ int wsrep_write_cache_buf(IO_CACHE *cache, uchar **buf, size_t *buf_len); /* Write the contents of a cache to wsrep provider. This function quite the same as MYSQL_BIN_LOG::write_cache(), with the exception that here we write in buffer instead of log file. @param len total amount of data written @return wsrep error status */ int wsrep_write_cache(THD* thd, IO_CACHE* cache, size_t* len); /* Dump replication buffer to disk */ void wsrep_dump_rbr_buf(THD *thd, const void* rbr_buf, size_t buf_len); /* Dump replication buffer along with header to a file */ void wsrep_dump_rbr_buf_with_header(THD *thd, const void *rbr_buf, size_t buf_len); /** Write a skip event into binlog. @param thd Thread object pointer @return Zero in case of success, non-zero on failure. */ int wsrep_write_skip_event(THD* thd); /* Write dummy event into binlog in place of unused GTID. The binlog write is done in thd context. */ int wsrep_write_dummy_event_low(THD *thd, const char *msg); /* Write dummy event to binlog in place of unused GTID and commit. The binlog write and commit are done in temporary thd context, the original thd state is not altered. */ int wsrep_write_dummy_event(THD* thd, const char *msg); void wsrep_register_binlog_handler(THD *thd, bool trx); /** Return true if committing THD will write to binlog during commit. This is the case for: - Local THD, binlog is open - Replaying THD, binlog is open - Applier THD, log-slave-updates is enabled */ bool wsrep_commit_will_write_binlog(THD *thd); /** Register THD for group commit. The wsrep_trx must be in committing state, i.e. the call must be done after wsrep_before_commit() but before commit order is released. This call will release commit order critical section if it is determined that the commit will go through binlog group commit. */ void wsrep_register_for_group_commit(THD *thd); /** Deregister THD from group commit. The wsrep_trx must be in committing state, as for wsrep_register_for_group_commit() above. This call must be used only for THDs which will not go through binlog group commit. */ void wsrep_unregister_from_group_commit(THD *thd); #endif /* WSREP_BINLOG_H */ mysql/server/private/item_strfunc.h000064400000215061151027430560013554 0ustar00#ifndef ITEM_STRFUNC_INCLUDED #define ITEM_STRFUNC_INCLUDED /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. Copyright (c) 2009, 2021, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file defines all string functions */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif extern size_t username_char_length; class Item_str_func :public Item_func { protected: /** Sets the result value of the function an empty string, using the current character set. No memory is allocated. @retval A pointer to the str_value member. */ virtual String *make_empty_result(String *str) { /* Reset string length to an empty string. We don't use str_value.set() as we don't want to free and potentially have to reallocate the buffer for each call. */ if (!str->is_alloced()) str->set("", 0, collation.collation); /* Avoid null ptrs */ else { str->length(0); /* Reuse allocated area */ str->set_charset(collation.collation); } return str; } public: Item_str_func(THD *thd): Item_func(thd) { decimals=NOT_FIXED_DEC; } Item_str_func(THD *thd, Item *a): Item_func(thd, a) {decimals=NOT_FIXED_DEC; } Item_str_func(THD *thd, Item *a, Item *b): Item_func(thd, a, b) { decimals=NOT_FIXED_DEC; } Item_str_func(THD *thd, Item *a, Item *b, Item *c): Item_func(thd, a, b, c) { decimals=NOT_FIXED_DEC; } Item_str_func(THD *thd, Item *a, Item *b, Item *c, Item *d): Item_func(thd, a, b, c, d) { decimals=NOT_FIXED_DEC; } Item_str_func(THD *thd, Item *a, Item *b, Item *c, Item *d, Item* e): Item_func(thd, a, b, c, d, e) { decimals=NOT_FIXED_DEC; } Item_str_func(THD *thd, List &list): Item_func(thd, list) { decimals=NOT_FIXED_DEC; } longlong val_int() override; double val_real() override; my_decimal *val_decimal(my_decimal *) override; bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { return get_date_from_string(thd, ltime, fuzzydate); } const Type_handler *type_handler() const override { return string_type_handler(); } void left_right_max_length(); bool fix_fields(THD *thd, Item **ref) override; }; /* Functions that return values with ASCII repertoire */ class Item_str_ascii_func :public Item_str_func { String ascii_buf; public: Item_str_ascii_func(THD *thd): Item_str_func(thd) {} Item_str_ascii_func(THD *thd, Item *a): Item_str_func(thd, a) {} Item_str_ascii_func(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} Item_str_ascii_func(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c) {} String *val_str(String *str) override { return val_str_from_val_str_ascii(str, &ascii_buf); } String *val_str_ascii(String *) override= 0; }; /** Functions that return a checksum or a hash of the argument, or somehow else encode or decode the argument, returning an ASCII-repertoire string. */ class Item_str_ascii_checksum_func: public Item_str_ascii_func { public: Item_str_ascii_checksum_func(THD *thd, Item *a) :Item_str_ascii_func(thd, a) { } Item_str_ascii_checksum_func(THD *thd, Item *a, Item *b) :Item_str_ascii_func(thd, a, b) { } bool eq(const Item *item, bool binary_cmp) const override { // Always use binary argument comparison: MD5('x') != MD5('X') return Item_func::eq(item, true); } }; /** Functions that return a checksum or a hash of the argument, or somehow else encode or decode the argument, returning a binary string. */ class Item_str_binary_checksum_func: public Item_str_func { public: Item_str_binary_checksum_func(THD *thd, Item *a) :Item_str_func(thd, a) { } Item_str_binary_checksum_func(THD *thd, Item *a, Item *b) :Item_str_func(thd, a, b) { } bool eq(const Item *item, bool binary_cmp) const override { /* Always use binary argument comparison: FROM_BASE64('test') != FROM_BASE64('TEST') */ return Item_func::eq(item, true); } }; class Item_func_md5 :public Item_str_ascii_checksum_func { public: Item_func_md5(THD *thd, Item *a): Item_str_ascii_checksum_func(thd, a) {} String *val_str_ascii(String *) override; bool fix_length_and_dec() override { fix_length_and_charset(32, default_charset()); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("md5") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sha :public Item_str_ascii_checksum_func { public: Item_func_sha(THD *thd, Item *a): Item_str_ascii_checksum_func(thd, a) {} String *val_str_ascii(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sha") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sha2 :public Item_str_ascii_checksum_func { public: Item_func_sha2(THD *thd, Item *a, Item *b) :Item_str_ascii_checksum_func(thd, a, b) {} String *val_str_ascii(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("sha2") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_to_base64 :public Item_str_ascii_checksum_func { String tmp_value; public: Item_func_to_base64(THD *thd, Item *a) :Item_str_ascii_checksum_func(thd, a) {} String *val_str_ascii(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("to_base64") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_from_base64 :public Item_str_binary_checksum_func { String tmp_value; public: Item_func_from_base64(THD *thd, Item *a) :Item_str_binary_checksum_func(thd, a) { } String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("from_base64") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #include class Item_aes_crypt :public Item_str_binary_checksum_func { enum { AES_KEY_LENGTH = 128 }; void create_key(String *user_key, uchar* key); protected: int what; String tmp_value; public: Item_aes_crypt(THD *thd, Item *a, Item *b) :Item_str_binary_checksum_func(thd, a, b) {} String *val_str(String *) override; }; class Item_func_aes_encrypt :public Item_aes_crypt { public: Item_func_aes_encrypt(THD *thd, Item *a, Item *b) :Item_aes_crypt(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("aes_encrypt") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_aes_decrypt :public Item_aes_crypt { public: Item_func_aes_decrypt(THD *thd, Item *a, Item *b): Item_aes_crypt(thd, a, b) {} bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("aes_decrypt") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_concat :public Item_str_func { protected: String tmp_value; /* Append a non-NULL value to the result. @param [IN] thd - The current thread. @param [IN/OUT] res - The current val_str() return value. @param [IN] app - The value to be appended. @retval - false on success, true on error */ bool append_value(THD *thd, String *res, const String *app); bool realloc_result(String *str, uint length) const; public: Item_func_concat(THD *thd, List &list): Item_str_func(thd, list) {} Item_func_concat(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("concat") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* This class handles the || operator in sql_mode=ORACLE. Unlike the traditional MariaDB concat(), it treats NULL arguments as ''. */ class Item_func_concat_operator_oracle :public Item_func_concat { public: Item_func_concat_operator_oracle(THD *thd, List &list) :Item_func_concat(thd, list) { } Item_func_concat_operator_oracle(THD *thd, Item *a, Item *b) :Item_func_concat(thd, a, b) { } String *val_str(String *) override; const Schema *schema() const override { return &oracle_schema_ref; } void print(String *str, enum_query_type query_type) override { if (query_type & QT_FOR_FRM) { // 10.3 downgrade compatibility for FRM str->append(STRING_WITH_LEN("concat_operator_oracle")); } else print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_decode_histogram :public Item_str_func { public: Item_func_decode_histogram(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} String *val_str(String *) override; bool fix_length_and_dec() override { collation.set(system_charset_info); max_length= MAX_BLOB_WIDTH; set_maybe_null(); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("decode_histogram") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_concat_ws :public Item_str_func { String tmp_value; public: Item_func_concat_ws(THD *thd, List &list): Item_str_func(thd, list) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("concat_ws") }; return name; } table_map not_null_tables() const override { return 0; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_reverse :public Item_str_func { String tmp_value; public: Item_func_reverse(THD *thd, Item *a): Item_str_func(thd, a) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("reverse") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_replace :public Item_str_func { String tmp_value,tmp_value2; protected: String *val_str_internal(String *str, bool null_to_empty); public: Item_func_replace(THD *thd, Item *org, Item *find, Item *replace): Item_str_func(thd, org, find, replace) {} String *val_str(String *to) override { return val_str_internal(to, false); }; bool fix_length_and_dec() override; const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("replace") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_replace_oracle :public Item_func_replace { String tmp_emtpystr; public: Item_func_replace_oracle(THD *thd, Item *org, Item *find, Item *replace): Item_func_replace(thd, org, find, replace) {} String *val_str(String *to) override { return val_str_internal(to, true); }; const Schema *schema() const override { return &oracle_schema_ref; } void print(String *str, enum_query_type query_type) override { if (query_type & QT_FOR_FRM) { // 10.3 downgrade compatibility for FRM str->append(STRING_WITH_LEN("replace_oracle")); } else print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_regexp_replace :public Item_str_func { Regexp_processor_pcre re; bool append_replacement(String *str, const LEX_CSTRING *source, const LEX_CSTRING *replace); protected: String *val_str_internal(String *str, bool null_to_empty); public: Item_func_regexp_replace(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c) {} const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } void cleanup() override { DBUG_ENTER("Item_func_regexp_replace::cleanup"); Item_str_func::cleanup(); re.cleanup(); DBUG_VOID_RETURN; } String *val_str(String *str) override { return val_str_internal(str, false); } bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("regexp_replace") }; return name; } Item *do_get_copy(THD *thd) const override { return 0;} }; class Item_func_regexp_replace_oracle: public Item_func_regexp_replace { public: Item_func_regexp_replace_oracle(THD *thd, Item *a, Item *b, Item *c) :Item_func_regexp_replace(thd, a, b, c) {} const Schema *schema() const override { return &oracle_schema_ref; } bool fix_length_and_dec() override { bool rc= Item_func_regexp_replace::fix_length_and_dec(); set_maybe_null(); // Empty result is converted to NULL return rc; } String *val_str(String *str) override { return val_str_internal(str, true); } }; class Item_func_regexp_substr :public Item_str_func { Regexp_processor_pcre re; public: Item_func_regexp_substr(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} void cleanup() override { DBUG_ENTER("Item_func_regexp_substr::cleanup"); Item_str_func::cleanup(); re.cleanup(); DBUG_VOID_RETURN; } String *val_str(String *str) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("regexp_substr") }; return name; } Item *do_get_copy(THD *thd) const override { return 0; } }; class Item_func_insert :public Item_str_func { String tmp_value; public: Item_func_insert(THD *thd, Item *org, Item *start, Item *length, Item *new_str): Item_str_func(thd, org, start, length, new_str) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("insert") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_str_conv :public Item_str_func { protected: uint multiply; my_charset_conv_case converter; String tmp_value; public: Item_str_conv(THD *thd, Item *item): Item_str_func(thd, item) {} String *val_str(String *) override; }; class Item_func_lcase :public Item_str_conv { public: Item_func_lcase(THD *thd, Item *item): Item_str_conv(thd, item) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("lcase") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ucase :public Item_str_conv { public: Item_func_ucase(THD *thd, Item *item): Item_str_conv(thd, item) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ucase") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_left :public Item_str_func { String tmp_value; public: Item_func_left(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} bool hash_not_null(Hasher *hasher) override; String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("left") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_right :public Item_str_func { String tmp_value; public: Item_func_right(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("right") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_substr :public Item_str_func { String tmp_value; protected: virtual longlong get_position() { return args[1]->val_int(); } public: Item_func_substr(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} Item_func_substr(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c) {} Item_func_substr(THD *thd, List &list) :Item_str_func(thd, list) {} String *val_str(String *) override; bool fix_length_and_dec() override; const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("substr") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_substr_oracle :public Item_func_substr { protected: longlong get_position() override { longlong pos= args[1]->val_int(); return pos == 0 ? 1 : pos; } String *make_empty_result(String *str) override { null_value= 1; return NULL; } public: Item_func_substr_oracle(THD *thd, Item *a, Item *b): Item_func_substr(thd, a, b) {} Item_func_substr_oracle(THD *thd, Item *a, Item *b, Item *c): Item_func_substr(thd, a, b, c) {} Item_func_substr_oracle(THD *thd, List &list) :Item_func_substr(thd, list) {} bool fix_length_and_dec() override { bool res= Item_func_substr::fix_length_and_dec(); set_maybe_null(); return res; } const Schema *schema() const override { return &oracle_schema_ref; } void print(String *str, enum_query_type query_type) override { if (query_type & QT_FOR_FRM) { // 10.3 downgrade compatibility for FRM str->append(STRING_WITH_LEN("substr_oracle")); } else print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_substr_index :public Item_str_func { String tmp_value; public: Item_func_substr_index(THD *thd, Item *a,Item *b,Item *c): Item_str_func(thd, a, b, c) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("substring_index") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_trim :public Item_str_func { protected: String tmp_value; String remove; String *trimmed_value(String *res, uint32 offset, uint32 length) { if (length == 0) return make_empty_result(&tmp_value); tmp_value.set(*res, offset, length); /* Make sure to return correct charset and collation: TRIM(0x000000 FROM _ucs2 0x0061) should set charset to "binary" rather than to "ucs2". */ tmp_value.set_charset(collation.collation); return &tmp_value; } String *non_trimmed_value(String *res) { return trimmed_value(res, 0, res->length()); } public: Item_func_trim(THD *thd, Item *a, Item *b): Item_str_func(thd, a, b) {} Item_func_trim(THD *thd, Item *a): Item_str_func(thd, a) {} Sql_mode_dependency value_depends_on_sql_mode() const override; String *val_str(String *) override; bool fix_length_and_dec() override; const Schema *schema() const override { return &mariadb_schema; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("trim") }; return name; } void print(String *str, enum_query_type query_type) override; virtual LEX_CSTRING mode_name() const { return { "both", 4}; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_trim_oracle :public Item_func_trim { protected: String *make_empty_result(String *str) override { null_value= 1; return NULL; } public: Item_func_trim_oracle(THD *thd, Item *a, Item *b): Item_func_trim(thd, a, b) {} Item_func_trim_oracle(THD *thd, Item *a): Item_func_trim(thd, a) {} const Schema *schema() const override { return &oracle_schema_ref; } bool fix_length_and_dec() override { bool res= Item_func_trim::fix_length_and_dec(); set_maybe_null(); return res; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ltrim :public Item_func_trim { public: Item_func_ltrim(THD *thd, Item *a, Item *b): Item_func_trim(thd, a, b) {} Item_func_ltrim(THD *thd, Item *a): Item_func_trim(thd, a) {} Sql_mode_dependency value_depends_on_sql_mode() const override { return Item_func::value_depends_on_sql_mode(); } String *val_str(String *) override; const Schema *schema() const override { return &mariadb_schema; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("ltrim") }; return name; } LEX_CSTRING mode_name() const override { return { STRING_WITH_LEN("leading") }; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_ltrim_oracle :public Item_func_ltrim { protected: String *make_empty_result(String *str) override { null_value= 1; return NULL; } public: Item_func_ltrim_oracle(THD *thd, Item *a, Item *b): Item_func_ltrim(thd, a, b) {} Item_func_ltrim_oracle(THD *thd, Item *a): Item_func_ltrim(thd, a) {} const Schema *schema() const override { return &oracle_schema_ref; } bool fix_length_and_dec() override { bool res= Item_func_ltrim::fix_length_and_dec(); set_maybe_null(); return res; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_rtrim :public Item_func_trim { public: Item_func_rtrim(THD *thd, Item *a, Item *b): Item_func_trim(thd, a, b) {} Item_func_rtrim(THD *thd, Item *a): Item_func_trim(thd, a) {} String *val_str(String *) override; const Schema *schema() const override { return &mariadb_schema; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("rtrim") }; return name; } LEX_CSTRING mode_name() const override { return { STRING_WITH_LEN("trailing") }; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_rtrim_oracle :public Item_func_rtrim { protected: String *make_empty_result(String *str) override { null_value= 1; return NULL; } public: Item_func_rtrim_oracle(THD *thd, Item *a, Item *b): Item_func_rtrim(thd, a, b) {} Item_func_rtrim_oracle(THD *thd, Item *a): Item_func_rtrim(thd, a) {} const Schema *schema() const override { return &oracle_schema_ref; } bool fix_length_and_dec() override { bool res= Item_func_rtrim::fix_length_and_dec(); set_maybe_null(); return res; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* Item_func_password -- new (4.1.1) PASSWORD() function implementation. Returns strcat('*', octet2hex(sha1(sha1(password)))). '*' stands for new password format, sha1(sha1(password) is so-called hash_stage2 value. Length of returned string is always 41 byte. To find out how entire authentication procedure works, see comments in password.c. */ class Item_func_password :public Item_str_ascii_checksum_func { public: enum PW_Alg {OLD, NEW}; private: char tmp_value[SCRAMBLED_PASSWORD_CHAR_LENGTH+1]; enum PW_Alg alg; bool deflt; public: Item_func_password(THD *thd, Item *a): Item_str_ascii_checksum_func(thd, a), alg(NEW), deflt(1) {} Item_func_password(THD *thd, Item *a, PW_Alg al): Item_str_ascii_checksum_func(thd, a), alg(al), deflt(0) {} String *val_str_ascii(String *str) override; bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override { fix_length_and_charset((alg == 1 ? SCRAMBLED_PASSWORD_CHAR_LENGTH : SCRAMBLED_PASSWORD_CHAR_LENGTH_323), default_charset()); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING password_normal= {STRING_WITH_LEN("password") }; static LEX_CSTRING password_old= {STRING_WITH_LEN("old_password") }; return (deflt || alg == 1) ? password_normal : password_old; } static char *alloc(THD *thd, const char *password, size_t pass_len, enum PW_Alg al); Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_des_encrypt :public Item_str_binary_checksum_func { String tmp_value,tmp_arg; public: Item_func_des_encrypt(THD *thd, Item *a) :Item_str_binary_checksum_func(thd, a) {} Item_func_des_encrypt(THD *thd, Item *a, Item *b) :Item_str_binary_checksum_func(thd, a, b) {} String *val_str(String *) override; bool fix_length_and_dec() override { set_maybe_null(); /* 9 = MAX ((8- (arg_len % 8)) + 1) */ max_length = args[0]->max_length + 9; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("des_encrypt") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_des_decrypt :public Item_str_binary_checksum_func { String tmp_value; public: Item_func_des_decrypt(THD *thd, Item *a) :Item_str_binary_checksum_func(thd, a) {} Item_func_des_decrypt(THD *thd, Item *a, Item *b) :Item_str_binary_checksum_func(thd, a, b) {} String *val_str(String *) override; bool fix_length_and_dec() override { set_maybe_null(); /* 9 = MAX ((8- (arg_len % 8)) + 1) */ max_length= args[0]->max_length; if (max_length >= 9U) max_length-= 9U; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("des_decrypt") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /** QQ: Item_func_encrypt should derive from Item_str_ascii_checksum_func. However, it should be fixed to handle UCS2, UTF16, UTF32 properly first, as the underlying crypt() call expects a null-terminated input string. */ class Item_func_encrypt :public Item_str_binary_checksum_func { String tmp_value; /* Encapsulate common constructor actions */ void constructor_helper() { collation.set(&my_charset_bin); } public: Item_func_encrypt(THD *thd, Item *a): Item_str_binary_checksum_func(thd, a) { constructor_helper(); } Item_func_encrypt(THD *thd, Item *a, Item *b) :Item_str_binary_checksum_func(thd, a, b) { constructor_helper(); } String *val_str(String *) override; bool fix_length_and_dec() override { set_maybe_null(); max_length = 13; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("encrypt") }; return name; } bool check_vcol_func_processor(void *arg) override { return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #include "sql_crypt.h" class Item_func_encode :public Item_str_binary_checksum_func { private: /** Whether the PRNG has already been seeded. */ bool seeded; protected: SQL_CRYPT sql_crypt; public: Item_func_encode(THD *thd, Item *a, Item *seed_arg): Item_str_binary_checksum_func(thd, a, seed_arg) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("encode") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } protected: virtual void crypto_transform(String *); private: /** Provide a seed for the PRNG sequence. */ bool seed(); }; class Item_func_decode :public Item_func_encode { public: Item_func_decode(THD *thd, Item *a, Item *seed_arg): Item_func_encode(thd, a, seed_arg) {} const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("decode") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } protected: void crypto_transform(String *) override; }; class Item_func_sysconst :public Item_str_func { public: Item_func_sysconst(THD *thd): Item_str_func(thd) { collation.set(system_charset_info,DERIVATION_SYSCONST); } Item *safe_charset_converter(THD *thd, CHARSET_INFO *tocs) override; /* Used to create correct Item name in new converted item in safe_charset_converter, return string representation of this function call */ virtual const char *fully_qualified_func_name() const = 0; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(fully_qualified_func_name(), arg, VCOL_SESSION_FUNC); } bool const_item() const override; }; class Item_func_database :public Item_func_sysconst { public: Item_func_database(THD *thd): Item_func_sysconst(thd) {} String *val_str(String *) override; bool fix_length_and_dec() override { max_length= NAME_CHAR_LEN * system_charset_info->mbmaxlen; set_maybe_null(); return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("database") }; return name; } const char *fully_qualified_func_name() const override { return "database()"; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_sqlerrm :public Item_func_sysconst { public: Item_func_sqlerrm(THD *thd): Item_func_sysconst(thd) {} String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("SQLERRM") }; return name; } const char *fully_qualified_func_name() const override { return "SQLERRM"; } void print(String *str, enum_query_type query_type) override { str->append(func_name_cstring()); } bool fix_length_and_dec() override { max_length= 512 * system_charset_info->mbmaxlen; null_value= false; base_flags&= ~item_base_t::MAYBE_NULL; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_user :public Item_func_sysconst { protected: bool init (const char *user, const char *host); public: Item_func_user(THD *thd): Item_func_sysconst(thd) { str_value.set("", 0, system_charset_info); } String *val_str(String *) override { DBUG_ASSERT(fixed()); return (null_value ? 0 : &str_value); } bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override { max_length= (uint32) (username_char_length + HOSTNAME_LENGTH + 1) * SYSTEM_CHARSET_MBMAXLEN; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("user") }; return name; } const char *fully_qualified_func_name() const override { return "user()"; } int save_in_field(Field *field, bool no_conversions) override { return save_str_value_in_field(field, &str_value); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_current_user :public Item_func_user { Name_resolution_context *context; public: Item_func_current_user(THD *thd, Name_resolution_context *context_arg): Item_func_user(thd), context(context_arg) {} bool fix_fields(THD *thd, Item **ref) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("current_user") }; return name; } const char *fully_qualified_func_name() const override { return "current_user()"; } bool check_vcol_func_processor(void *arg) override { context= 0; return mark_unsupported_function(fully_qualified_func_name(), arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_current_role :public Item_func_sysconst { Name_resolution_context *context; public: Item_func_current_role(THD *thd, Name_resolution_context *context_arg): Item_func_sysconst(thd), context(context_arg) {} bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override { max_length= (uint32) username_char_length * SYSTEM_CHARSET_MBMAXLEN; return FALSE; } int save_in_field(Field *field, bool no_conversions) override { return save_str_value_in_field(field, &str_value); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("current_role") }; return name; } const char *fully_qualified_func_name() const override { return "current_role()"; } String *val_str(String *) override { DBUG_ASSERT(fixed()); return null_value ? NULL : &str_value; } bool check_vcol_func_processor(void *arg) override { context= 0; return mark_unsupported_function(fully_qualified_func_name(), arg, VCOL_SESSION_FUNC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_soundex :public Item_str_func { String tmp_value; public: Item_func_soundex(THD *thd, Item *a): Item_str_func(thd, a) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("soundex") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_elt :public Item_str_func { public: Item_func_elt(THD *thd, List &list): Item_str_func(thd, list) {} double val_real() override; longlong val_int() override; String *val_str(String *str) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("elt") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_make_set :public Item_str_func { String tmp_str; public: Item_func_make_set(THD *thd, List &list): Item_str_func(thd, list) {} String *val_str(String *str) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("make_set") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_format :public Item_str_ascii_func { const MY_LOCALE *locale; public: Item_func_format(THD *thd, Item *org, Item *dec): Item_str_ascii_func(thd, org, dec) {} Item_func_format(THD *thd, Item *org, Item *dec, Item *lang): Item_str_ascii_func(thd, org, dec, lang) {} String *val_str_ascii(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("format") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_char :public Item_str_func { public: Item_func_char(THD *thd, List &list): Item_str_func(thd, list) { collation.set(&my_charset_bin); } Item_func_char(THD *thd, List &list, CHARSET_INFO *cs): Item_str_func(thd, list) { collation.set(cs); } Item_func_char(THD *thd, Item *arg1, CHARSET_INFO *cs): Item_str_func(thd, arg1) { collation.set(cs); } String *val_str(String *) override; void append_char(String * str, int32 num); bool fix_length_and_dec() override { max_length= arg_count * 4; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("char") }; return name; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_chr :public Item_func_char { public: Item_func_chr(THD *thd, Item *arg1, CHARSET_INFO *cs): Item_func_char(thd, arg1, cs) {} String *val_str(String *) override; bool fix_length_and_dec() override { max_length= 4; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("chr") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_repeat :public Item_str_func { String tmp_value; public: Item_func_repeat(THD *thd, Item *arg1, Item *arg2): Item_str_func(thd, arg1, arg2) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("repeat") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_space :public Item_str_func { public: Item_func_space(THD *thd, Item *arg1): Item_str_func(thd, arg1) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("space") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_binlog_gtid_pos :public Item_str_func { public: Item_func_binlog_gtid_pos(THD *thd, Item *arg1, Item *arg2): Item_str_func(thd, arg1, arg2) {} String *val_str(String *) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("binlog_gtid_pos") }; return name; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_pad: public Item_str_func { protected: String tmp_value, pad_str; public: Item_func_pad(THD *thd, Item *arg1, Item *arg2, Item *arg3): Item_str_func(thd, arg1, arg2, arg3) {} Item_func_pad(THD *thd, Item *arg1, Item *arg2): Item_str_func(thd, arg1, arg2) {} Item_func_pad(THD *thd, List &list): Item_str_func(thd,list) {} bool fix_length_and_dec() override; }; class Item_func_rpad :public Item_func_pad { public: Item_func_rpad(THD *thd, Item *arg1, Item *arg2, Item *arg3): Item_func_pad(thd, arg1, arg2, arg3) {} Item_func_rpad(THD *thd, Item *arg1, Item *arg2): Item_func_pad(thd, arg1, arg2) {} Item_func_rpad(THD *thd, List &list): Item_func_pad(thd,list) {} String *val_str(String *) override; const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("rpad") }; return name; } Sql_mode_dependency value_depends_on_sql_mode() const override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_rpad_oracle :public Item_func_rpad { String *make_empty_result(String *str) override { null_value= 1; return NULL; } public: Item_func_rpad_oracle(THD *thd, Item *arg1, Item *arg2, Item *arg3): Item_func_rpad(thd, arg1, arg2, arg3) {} Item_func_rpad_oracle(THD *thd, Item *arg1, Item *arg2): Item_func_rpad(thd, arg1, arg2) {} Item_func_rpad_oracle(THD *thd, List &list): Item_func_rpad(thd,list) {} bool fix_length_and_dec() override { bool res= Item_func_rpad::fix_length_and_dec(); set_maybe_null(); return res; } const Schema *schema() const override { return &oracle_schema_ref; } void print(String *str, enum_query_type query_type) override { if (query_type & QT_FOR_FRM) { // 10.3 downgrade compatibility for FRM str->append(STRING_WITH_LEN("rpad_oracle")); } else print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_lpad :public Item_func_pad { public: Item_func_lpad(THD *thd, Item *arg1, Item *arg2, Item *arg3): Item_func_pad(thd, arg1, arg2, arg3) {} Item_func_lpad(THD *thd, Item *arg1, Item *arg2): Item_func_pad(thd, arg1, arg2) {} Item_func_lpad(THD *thd, List &list): Item_func_pad(thd,list) {} String *val_str(String *) override; const Schema *schema() const override { return &mariadb_schema; } void print(String *str, enum_query_type query_type) override { print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("lpad") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_lpad_oracle :public Item_func_lpad { String *make_empty_result(String *str) override { null_value= 1; return NULL; } public: Item_func_lpad_oracle(THD *thd, Item *arg1, Item *arg2, Item *arg3): Item_func_lpad(thd, arg1, arg2, arg3) {} Item_func_lpad_oracle(THD *thd, Item *arg1, Item *arg2): Item_func_lpad(thd, arg1, arg2) {} Item_func_lpad_oracle(THD *thd, List &list): Item_func_lpad(thd,list) {} bool fix_length_and_dec() override { bool res= Item_func_lpad::fix_length_and_dec(); set_maybe_null(); return res; } const Schema *schema() const override { return &oracle_schema_ref; } void print(String *str, enum_query_type query_type) override { if (query_type & QT_FOR_FRM) { // 10.3 downgrade compatibility for FRM str->append(STRING_WITH_LEN("lpad_oracle")); } else print_sql_mode_qualified_name(str, query_type); print_args_parenthesized(str, query_type); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_conv :public Item_str_func { public: Item_func_conv(THD *thd, Item *a, Item *b, Item *c): Item_str_func(thd, a, b, c) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("conv") }; return name; } String *val_str(String *) override; bool fix_length_and_dec() override { collation.set(default_charset()); fix_char_length(65); set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_hex :public Item_str_ascii_checksum_func { protected: String tmp_value; /* Calling arg[0]->type_handler() can be expensive on every row. It's a virtual method, and in case if args[0] is a complex Item, its type_handler() can call more virtual methods. So let's cache it during fix_length_and_dec(). */ const Type_handler *m_arg0_type_handler; public: Item_func_hex(THD *thd, Item *a): Item_str_ascii_checksum_func(thd, a), m_arg0_type_handler(NULL) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("hex") }; return name; } String *val_str_ascii_from_val_int(String *str); String *val_str_ascii_from_val_real(String *str); String *val_str_ascii_from_val_str(String *str); String *val_str_ascii(String *str) override { DBUG_ASSERT(fixed()); return m_arg0_type_handler->Item_func_hex_val_str_ascii(this, str); } bool fix_length_and_dec() override { m_arg0_type_handler= args[0]->type_handler(); collation.set(default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_ASCII); decimals=0; /* Reserve space for 16 characters for signed numeric data types: hex(-1) -> 'FFFFFFFFFFFFFFFF'. For unsigned numeric types, HEX() can create too large columns. This should be eventually fixed to create minimum possible columns. */ const Type_handler_numeric *tn= dynamic_cast(m_arg0_type_handler); size_t char_length= (tn && !(tn->flags() & UNSIGNED_FLAG)) ? (size_t) 16 : (size_t) args[0]->max_length * 2; fix_char_length(char_length); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_unhex :public Item_str_func { String tmp_value; public: Item_func_unhex(THD *thd, Item *a): Item_str_func(thd, a) { /* there can be bad hex strings */ set_maybe_null(); } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("unhex") }; return name; } String *val_str(String *) override; bool fix_length_and_dec() override { collation.set(&my_charset_bin); decimals=0; max_length=(1+args[0]->max_length)/2; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #ifndef DBUG_OFF class Item_func_like_range :public Item_str_func { protected: String min_str; String max_str; const bool is_min; public: Item_func_like_range(THD *thd, Item *a, Item *b, bool is_min_arg): Item_str_func(thd, a, b), is_min(is_min_arg) { set_maybe_null(); } String *val_str(String *) override; bool fix_length_and_dec() override { collation.set(args[0]->collation); decimals=0; max_length= MAX_BLOB_WIDTH; return FALSE; } }; class Item_func_like_range_min :public Item_func_like_range { public: Item_func_like_range_min(THD *thd, Item *a, Item *b): Item_func_like_range(thd, a, b, true) { } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("like_range_min") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_like_range_max :public Item_func_like_range { public: Item_func_like_range_max(THD *thd, Item *a, Item *b): Item_func_like_range(thd, a, b, false) { } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("like_range_max") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #endif class Item_func_binary :public Item_str_func { public: Item_func_binary(THD *thd, Item *a): Item_str_func(thd, a) {} String *val_str(String *a) override { DBUG_ASSERT(fixed()); String *tmp=args[0]->val_str(a); null_value=args[0]->null_value; if (tmp) tmp->set_charset(&my_charset_bin); return tmp; } bool fix_length_and_dec() override { collation.set(&my_charset_bin); max_length=args[0]->max_length; return FALSE; } void print(String *str, enum_query_type query_type) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("cast_as_binary") }; return name; } bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_load_file :public Item_str_func { String tmp_value; public: Item_load_file(THD *thd, Item *a): Item_str_func(thd, a) {} String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("load_file") }; return name; } bool fix_length_and_dec() override { collation.set(&my_charset_bin, DERIVATION_COERCIBLE); set_maybe_null(); max_length=MAX_BLOB_WIDTH; return FALSE; } bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_export_set: public Item_str_func { public: Item_func_export_set(THD *thd, Item *a, Item *b, Item* c): Item_str_func(thd, a, b, c) {} Item_func_export_set(THD *thd, Item *a, Item *b, Item* c, Item* d): Item_str_func(thd, a, b, c, d) {} Item_func_export_set(THD *thd, Item *a, Item *b, Item* c, Item* d, Item* e): Item_str_func(thd, a, b, c, d, e) {} String *val_str(String *str) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("export_set") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_quote :public Item_str_func { String tmp_value; public: Item_func_quote(THD *thd, Item *a): Item_str_func(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("quote") }; return name; } String *val_str(String *) override; bool fix_length_and_dec() override { collation.set(args[0]->collation); ulonglong max_result_length= (ulonglong) args[0]->max_length * 2 + 2 * collation.collation->mbmaxlen; // NULL argument is returned as a string "NULL" without quotes if (args[0]->maybe_null()) set_if_bigger(max_result_length, 4 * collation.collation->mbmaxlen); max_length= (uint32) MY_MIN(max_result_length, MAX_BLOB_WIDTH); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_conv_charset :public Item_str_func { bool use_cached_value; String tmp_value; public: bool safe; Item_func_conv_charset(THD *thd, Item *a, CHARSET_INFO *cs): Item_str_func(thd, a) { collation.set(cs, DERIVATION_IMPLICIT); use_cached_value= 0; safe= 0; } Item_func_conv_charset(THD *thd, Item *a, CHARSET_INFO *cs, bool cache_if_const): Item_str_func(thd, a) { collation.set(cs, DERIVATION_IMPLICIT); if (cache_if_const && args[0]->can_eval_in_optimize()) { uint errors= 0; String tmp, *str= args[0]->val_str(&tmp); if (!str || str_value.copy(str->ptr(), str->length(), str->charset(), cs, &errors)) null_value= 1; use_cached_value= 1; str_value.mark_as_const(); safe= (errors == 0); } else { use_cached_value= 0; /* Conversion from and to "binary" is safe. Conversion to Unicode is safe. Conversion from an expression with the ASCII repertoire to any character set that can store characters U+0000..U+007F is safe: - All supported multibyte character sets can store U+0000..U+007F - All supported 7bit character sets can store U+0000..U+007F except those marked with MY_CS_NONASCII (e.g. swe7). Other kind of conversions are potentially lossy. */ safe= (args[0]->collation.collation == &my_charset_bin || cs == &my_charset_bin || (cs->state & MY_CS_UNICODE) || (args[0]->collation.repertoire == MY_REPERTOIRE_ASCII && (cs->mbmaxlen > 1 || !(cs->state & MY_CS_NONASCII)))); } } String *val_str(String *) override; longlong val_int() override { if (args[0]->result_type() == STRING_RESULT) return Item_str_func::val_int(); longlong res= args[0]->val_int(); if ((null_value= args[0]->null_value)) return 0; return res; } double val_real() override { if (args[0]->result_type() == STRING_RESULT) return Item_str_func::val_real(); double res= args[0]->val_real(); if ((null_value= args[0]->null_value)) return 0; return res; } my_decimal *val_decimal(my_decimal *d) override { if (args[0]->result_type() == STRING_RESULT) return Item_str_func::val_decimal(d); my_decimal *res= args[0]->val_decimal(d); if ((null_value= args[0]->null_value)) return NULL; return res; } bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override { if (args[0]->result_type() == STRING_RESULT) return Item_str_func::get_date(thd, ltime, fuzzydate); bool res= args[0]->get_date(thd, ltime, fuzzydate); if ((null_value= args[0]->null_value)) return 1; return res; } bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("convert") }; return name; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } int save_in_field(Field*, bool) override; }; class Item_func_set_collation :public Item_str_func { CHARSET_INFO *m_set_collation; public: Item_func_set_collation(THD *thd, Item *a, CHARSET_INFO *set_collation): Item_str_func(thd, a), m_set_collation(set_collation) {} String *val_str(String *) override; bool fix_length_and_dec() override; bool eq(const Item *item, bool binary_cmp) const override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("collate") }; return name; } enum precedence precedence() const override { return COLLATE_PRECEDENCE; } enum Functype functype() const override { return COLLATE_FUNC; } void print(String *str, enum_query_type query_type) override; Item_field *field_for_view_update() override { /* this function is transparent for view updating */ return args[0]->field_for_view_update(); } bool need_parentheses_in_default() override { return true; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_expr_str_metadata :public Item_str_func { public: Item_func_expr_str_metadata(THD *thd, Item *a): Item_str_func(thd, a) { } bool fix_length_and_dec() override { collation.set(system_charset_info); max_length= 64 * collation.collation->mbmaxlen; // should be enough base_flags&= ~item_base_t::MAYBE_NULL; return FALSE; }; table_map not_null_tables() const override { return 0; } Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { return this; } bool const_item() const override { return true; } }; class Item_func_charset :public Item_func_expr_str_metadata { LEX_CSTRING m_cached_charset_info; public: Item_func_charset(THD *thd, Item *a) :Item_func_expr_str_metadata(thd, a) { } String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("charset") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } table_map used_tables() const override { return 0; } bool fix_length_and_dec() override { if (Item_func_expr_str_metadata::fix_length_and_dec()) return true; /* Since this is a const item which doesn't use tables (see used_tables()), we don't want to access the function arguments during execution. That's why we store the charset here during the preparation phase and only return it later at the execution phase */ DBUG_ASSERT(args[0]->fixed()); m_cached_charset_info.str= args[0]->charset_for_protocol()->cs_name.str; m_cached_charset_info.length= args[0]->charset_for_protocol()->cs_name.length; return false; } }; class Item_func_collation :public Item_func_expr_str_metadata { public: Item_func_collation(THD *thd, Item *a) :Item_func_expr_str_metadata(thd, a) {} String *val_str(String *) override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("collation") }; return name; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_weight_string :public Item_str_func { String tmp_value; uint weigth_flags; uint nweights; uint result_length; public: Item_func_weight_string(THD *thd, Item *a, uint result_length_arg, uint nweights_arg, uint flags_arg): Item_str_func(thd, a) { nweights= nweights_arg; weigth_flags= flags_arg; result_length= result_length_arg; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("weight_string") }; return name; } String *val_str(String *) override; bool fix_length_and_dec() override; bool eq(const Item *item, bool binary_cmp) const override { if (!Item_str_func::eq(item, binary_cmp)) return false; Item_func_weight_string *that= (Item_func_weight_string *)item; return this->weigth_flags == that->weigth_flags && this->nweights == that->nweights && this->result_length == that->result_length; } Item* propagate_equal_fields(THD *thd, const Context &ctx, COND_EQUAL *cond) override { return this; } void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_crc32 :public Item_long_func { bool check_arguments() const override { return args[0]->check_type_can_return_str(func_name_cstring()); } String value; public: Item_func_crc32(THD *thd, Item *a): Item_long_func(thd, a) { unsigned_flag= 1; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("crc32") }; return name; } bool fix_length_and_dec() override { max_length=10; return FALSE; } longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_uncompressed_length : public Item_long_func_length { String value; public: Item_func_uncompressed_length(THD *thd, Item *a) :Item_long_func_length(thd, a) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("uncompressed_length") }; return name; } bool fix_length_and_dec() override { max_length=10; set_maybe_null(); return FALSE; } longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #ifdef HAVE_COMPRESS #define ZLIB_DEPENDED_FUNCTION ; #else #define ZLIB_DEPENDED_FUNCTION { null_value=1; return 0; } #endif class Item_func_compress: public Item_str_binary_checksum_func { String tmp_value; public: Item_func_compress(THD *thd, Item *a) :Item_str_binary_checksum_func(thd, a) {} bool fix_length_and_dec() override { max_length= (args[0]->max_length * 120) / 100 + 12; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("compress") }; return name; } String *val_str(String *) override ZLIB_DEPENDED_FUNCTION Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_uncompress: public Item_str_binary_checksum_func { String tmp_value; public: Item_func_uncompress(THD *thd, Item *a) :Item_str_binary_checksum_func(thd, a) {} bool fix_length_and_dec() override { set_maybe_null(); max_length= MAX_BLOB_WIDTH; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("uncompress") }; return name; } String *val_str(String *) override ZLIB_DEPENDED_FUNCTION Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_uuid: public Item_str_func { /* Set if uuid should be returned without separators (Oracle sys_guid) */ bool without_separators; public: Item_func_uuid(THD *thd, bool without_separators_arg): Item_str_func(thd), without_separators(without_separators_arg) {} bool fix_length_and_dec() override { collation.set(DTCollation_numeric()); fix_char_length(without_separators ? MY_UUID_ORACLE_STRING_LENGTH : MY_UUID_STRING_LENGTH); return FALSE; } bool const_item() const override { return false; } table_map used_tables() const override { return RAND_TABLE_BIT; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING mariadb_name= {STRING_WITH_LEN("uuid") }; static LEX_CSTRING oracle_name= {STRING_WITH_LEN("sys_guid") }; return without_separators ? oracle_name : mariadb_name; } String *val_str(String *) override; bool check_vcol_func_processor(void *arg) override { return mark_unsupported_function(func_name(), "()", arg, VCOL_NON_DETERMINISTIC); } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dyncol_create: public Item_str_func { protected: DYNCALL_CREATE_DEF *defs; DYNAMIC_COLUMN_VALUE *vals; uint *keys_num; LEX_STRING *keys_str; bool names, force_names; bool prepare_arguments(THD *thd, bool force_names); void print_arguments(String *str, enum_query_type query_type); public: Item_func_dyncol_create(THD *thd, List &args, DYNCALL_CREATE_DEF *dfs); bool fix_fields(THD *thd, Item **ref) override; bool fix_length_and_dec() override; LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_create") }; return name; } String *val_str(String *) override; void print(String *str, enum_query_type query_type) override; enum Functype functype() const override { return DYNCOL_FUNC; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dyncol_add: public Item_func_dyncol_create { public: Item_func_dyncol_add(THD *thd, List &args_arg, DYNCALL_CREATE_DEF *dfs): Item_func_dyncol_create(thd, args_arg, dfs) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_add") }; return name; } String *val_str(String *) override; void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dyncol_json: public Item_str_func { public: Item_func_dyncol_json(THD *thd, Item *str): Item_str_func(thd, str) {collation.set(DYNCOL_UTF);} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_json") }; return name; } String *val_str(String *) override; bool fix_length_and_dec() override { max_length= MAX_BLOB_WIDTH; set_maybe_null(); decimals= 0; return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* The following functions is always called from an Item_cast function */ class Item_dyncol_get: public Item_str_func { public: Item_dyncol_get(THD *thd, Item *str, Item *num): Item_str_func(thd, str, num) {} bool fix_length_and_dec() override { set_maybe_null(); max_length= MAX_BLOB_WIDTH; return FALSE; } /* Mark that collation can change between calls */ bool dynamic_result() override { return 1; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_get") }; return name; } String *val_str(String *) override; longlong val_int() override; longlong val_int_signed_typecast() override { unsigned_flag= false; // Mark that we want to have a signed value longlong value= val_int(); // val_int() can change unsigned_flag if (!null_value && unsigned_flag && value < 0) push_note_converted_to_negative_complement(current_thd); return value; } longlong val_int_unsigned_typecast() override { unsigned_flag= true; // Mark that we want to have an unsigned value longlong value= val_int(); // val_int() can change unsigned_flag if (!null_value && unsigned_flag == 0 && value < 0) push_note_converted_to_positive_complement(current_thd); return value; } double val_real() override; my_decimal *val_decimal(my_decimal *) override; bool get_dyn_value(THD *thd, DYNAMIC_COLUMN_VALUE *val, String *tmp); bool get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate) override; void print(String *str, enum_query_type query_type) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_dyncol_list: public Item_str_func { public: Item_func_dyncol_list(THD *thd, Item *str): Item_str_func(thd, str) {collation.set(DYNCOL_UTF);} bool fix_length_and_dec() override { set_maybe_null(); max_length= MAX_BLOB_WIDTH; return FALSE; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("column_list") }; return name; } String *val_str(String *) override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; /* this is used by JOIN_TAB::keep_current_rowid and stores handler::position(). It has nothing to do with _rowid pseudo-column, that the parser supports. */ class Item_temptable_rowid :public Item_str_func { public: TABLE *table; Item_temptable_rowid(TABLE *table_arg); const Type_handler *type_handler() const override { return &type_handler_string; } Field *create_tmp_field(MEM_ROOT *root, bool group, TABLE *table) { return create_table_field_from_handler(root, table); } String *val_str(String *str) override; enum Functype functype() const override { return TEMPTABLE_ROWID; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("") }; return name; } bool fix_length_and_dec() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #ifdef WITH_WSREP #include "wsrep_api.h" class Item_func_wsrep_last_written_gtid: public Item_str_ascii_func { String gtid_str; public: Item_func_wsrep_last_written_gtid(THD *thd): Item_str_ascii_func(thd) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("wsrep_last_written_gtid") }; return name; } String *val_str_ascii(String *) override; bool fix_length_and_dec() override { max_length= WSREP_GTID_STR_LEN; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_wsrep_last_seen_gtid: public Item_str_ascii_func { String gtid_str; public: Item_func_wsrep_last_seen_gtid(THD *thd): Item_str_ascii_func(thd) {} LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("wsrep_last_seen_gtid") }; return name; } String *val_str_ascii(String *) override; bool fix_length_and_dec() override { max_length= WSREP_GTID_STR_LEN; set_maybe_null(); return FALSE; } Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; class Item_func_wsrep_sync_wait_upto: public Item_int_func { String value; public: Item_func_wsrep_sync_wait_upto(THD *thd, Item *a): Item_int_func(thd, a) {} Item_func_wsrep_sync_wait_upto(THD *thd, Item *a, Item* b): Item_int_func(thd, a, b) {} const Type_handler *type_handler() const override { return &type_handler_string; } LEX_CSTRING func_name_cstring() const override { static LEX_CSTRING name= {STRING_WITH_LEN("wsrep_sync_wait_upto_gtid") }; return name; } longlong val_int() override; Item *do_get_copy(THD *thd) const override { return get_item_copy(thd, this); } }; #endif /* WITH_WSREP */ #endif /* ITEM_STRFUNC_INCLUDED */ mysql/server/private/sql_admin.h000064400000005543151027430560013023 0ustar00/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef SQL_TABLE_MAINTENANCE_H #define SQL_TABLE_MAINTENANCE_H /* Must be able to hold ALTER TABLE t PARTITION BY ... KEY ALGORITHM = 1 ... */ #define SQL_ADMIN_MSG_TEXT_SIZE (128 * 1024) bool mysql_assign_to_keycache(THD* thd, TABLE_LIST* table_list, const LEX_CSTRING *key_cache_name); bool mysql_preload_keys(THD* thd, TABLE_LIST* table_list); int reassign_keycache_tables(THD* thd, KEY_CACHE *src_cache, KEY_CACHE *dst_cache); void fill_check_table_metadata_fields(THD *thd, List* fields); /** Sql_cmd_analyze_table represents the ANALYZE TABLE statement. */ class Sql_cmd_analyze_table : public Sql_cmd { public: /** Constructor, used to represent a ANALYZE TABLE statement. */ Sql_cmd_analyze_table() = default; ~Sql_cmd_analyze_table() = default; bool execute(THD *thd) override; enum_sql_command sql_command_code() const override { return SQLCOM_ANALYZE; } }; /** Sql_cmd_check_table represents the CHECK TABLE statement. */ class Sql_cmd_check_table : public Sql_cmd { public: /** Constructor, used to represent a CHECK TABLE statement. */ Sql_cmd_check_table() = default; ~Sql_cmd_check_table() = default; bool execute(THD *thd) override; enum_sql_command sql_command_code() const override { return SQLCOM_CHECK; } }; /** Sql_cmd_optimize_table represents the OPTIMIZE TABLE statement. */ class Sql_cmd_optimize_table : public Sql_cmd { public: /** Constructor, used to represent a OPTIMIZE TABLE statement. */ Sql_cmd_optimize_table() = default; ~Sql_cmd_optimize_table() = default; bool execute(THD *thd) override; enum_sql_command sql_command_code() const override { return SQLCOM_OPTIMIZE; } }; /** Sql_cmd_repair_table represents the REPAIR TABLE statement. */ class Sql_cmd_repair_table : public Sql_cmd { public: /** Constructor, used to represent a REPAIR TABLE statement. */ Sql_cmd_repair_table() = default; ~Sql_cmd_repair_table() = default; bool execute(THD *thd) override; enum_sql_command sql_command_code() const override { return SQLCOM_REPAIR; } }; #endif mysql/server/private/sql_mode.h000064400000015117151027430560012655 0ustar00#ifndef SQL_MODE_H_INCLUDED #define SQL_MODE_H_INCLUDED /* Copyright (c) 2019, MariaDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef USE_PRAGMA_INTERFACE #pragma interface /* gcc class implementation */ #endif #include "sql_basic_types.h" /* class Sql_mode_dependency A combination of hard and soft dependency on sql_mode. Used to watch if a GENERATED ALWAYS AS expression guarantees consitent data written to its virtual column. A virtual column can appear in an index if: - the generation expression does not depend on any sql_mode flags, or - the generation expression has a soft dependency on an sql_mode flag, and the column knows how to handle this dependeny. A virtual column cannot appear in an index if: - its generation expression has a hard dependency - its generation expression has a soft dependency, but the column cannot handle it on store. An error is reported in such cases. How dependencies appear: - When a column return value depends on some sql_mode flag, its Item_field adds a corresponding bit to m_soft. For example, Item_field for a CHAR(N) column adds the PAD_CHAR_TO_FULL_LENGTH flag. - When an SQL function/operator return value depends on some sql_mode flag, it adds a corresponding bit to m_soft. For example, Item_func_minus adds the MODE_NO_UNSIGNED_SUBTRACTION in case of unsigned arguments. How dependency are processed (see examples below): - All SQL functions/operators bit-OR all hard dependencies from all arguments. - Some soft dependencies can be handled by the underlying Field on store, e.g. CHAR(N) can handle PAD_CHAR_TO_FULL_LENGTH. - Some soft dependencies can be handled by SQL functions and operators, e.g. RTRIM(expr) removes expr's soft dependency on PAD_CHAR_TO_FULL_LENGTH. If a function or operator handles a soft dependency on a certain sql_mode flag, it removes the corresponding bit from m_soft (see below). Note, m_hard is not touched in such cases. - When an expression with a soft dependency on a certain sql_mode flag goes as an argument to an SQL function/operator which cannot handle this flag, the dependency escalates from soft to hard (by moving the corresponding bit from m_soft to m_hard) and cannot be handled any more on the upper level, neither by a Field on store, nor by another SQL function/operator. There are four kinds of Items: 1. Items that generate a soft or hard dependency, e.g. - Item_field for CHAR(N) - generates soft/PAD_CHAR_TO_FULL_LENGTH - Item_func_minus - generates soft/NO_UNSIGNED_SUBTRACTION 2. Items that convert a soft dependency to a hard dependency. This happens e.g. when an Item_func instance gets a soft dependency from its arguments, and it does not know how to handle this dependency. Most Item_func descendants do this. 3. Items that remove soft dependencies, e.g.: - Item_func_rtrim - removes soft/PAD_CHAR_TO_FULL_LENGTH that came from args[0] (under certain conditions) - Item_func_rpad - removes soft/PAD_CJAR_TO_FULL_LENGTH that came from args[0] (under certain conditions) 4. Items that repeat soft dependency from its arguments to the caller. They are not implemented yet. But functions like Item_func_coalesce, Item_func_case, Item_func_case_abbreviation2 could do this. Examples: 1. CREATE OR REPLACE TABLE t1 (a CHAR(5), v CHAR(20) AS(a), KEY(v)); Here `v` has a soft dependency on `a`. The value of `a` depends on PAD_CHAR_TO_FULL_LENGTH, it can return: - 'a' - if PAD_CHAR_TO_FULL_LENGTH is disabled - 'a' followed by four spaces - if PAD_CHAR_TO_FULL_LENGTH is enabled But `v` will pad trailing spaces to the full length on store anyway. So Field_string handles this soft dependency on store. This combination of the virtial column data type and its generation expression is safe and provides consistent data in `v`, which is 'a' followed by four spaces, no matter what PAD_CHAR_TO_FULL_LENGTH is. 2. CREATE OR REPLACE TABLE t1 (a CHAR(5), v VARCHAR(20) AS(a), KEY(v)); Here `v` has a soft dependency on `a`. But Field_varstring does not pad spaces on store, so it cannot handle this dependency. This combination of the virtual column data type and its generation expression is not safe. An error is returned. 3. CREATE OR REPLACE TABLE t1 (a CHAR(5), v INT AS(LENGTH(a)), KEY(v)); Here `v` has a hard dependency on `a`, because the value of `a` is wrapped to the function LENGTH(). The value of `LENGTH(a)` depends on PAD_CHAR_TO_FULL_LENGTH, it can return: - 1 - if PAD_CHAR_TO_FULL_LENGTH is disabled - 4 - if PAD_CHAR_TO_FULL_LENGTH is enabled This combination cannot provide consistent data stored to `v`, therefore it's disallowed. */ class Sql_mode_dependency { sql_mode_t m_hard; sql_mode_t m_soft; public: Sql_mode_dependency() :m_hard(0), m_soft(0) { } Sql_mode_dependency(sql_mode_t hard, sql_mode_t soft) :m_hard(hard), m_soft(soft) { } sql_mode_t hard() const { return m_hard; } sql_mode_t soft() const { return m_soft; } operator bool () const { return m_hard > 0 || m_soft > 0; } Sql_mode_dependency operator|(const Sql_mode_dependency &other) const { return Sql_mode_dependency(m_hard | other.m_hard, m_soft | other.m_soft); } Sql_mode_dependency operator&(const Sql_mode_dependency &other) const { return Sql_mode_dependency(m_hard & other.m_hard, m_soft & other.m_soft); } Sql_mode_dependency &operator|=(const Sql_mode_dependency &other) { m_hard|= other.m_hard; m_soft|= other.m_soft; return *this; } Sql_mode_dependency &operator&=(const Sql_mode_dependency &other) { m_hard&= other.m_hard; m_soft&= other.m_soft; return *this; } Sql_mode_dependency &soft_to_hard() { m_hard|= m_soft; m_soft= 0; return *this; } void push_dependency_warnings(THD *thd) const; }; #endif // SQL_MODE_H_INCLUDED mysql/server/private/myisampack.h000064400000035121151027430560013205 0ustar00#ifndef MYISAMPACK_INCLUDED #define MYISAMPACK_INCLUDED /* Copyright (c) 2000-2002, 2004 MySQL AB, 2009 Sun Microsystems, Inc. Copyright (c) 2020, MariaDB Corporation. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Storing of values in high byte first order. integer keys and file pointers are stored with high byte first to get better compression */ /* these two are for uniformity */ #define mi_sint1korr(A) ((int8)(*A)) #define mi_uint1korr(A) ((uint8)(*A)) #define mi_sint2korr(A) ((int16) (((int16) (((const uchar*) (A))[1])) |\ ((int16) ((uint16) ((const uchar*) (A))[0]) << 8))) #define mi_sint3korr(A) ((int32) (((((const uchar*) (A))[0]) & 128) ? \ (((uint32) 255L << 24) | \ (((uint32) ((const uchar*) (A))[0]) << 16) |\ (((uint32) ((const uchar*) (A))[1]) << 8) | \ ((uint32) ((const uchar*) (A))[2])) : \ (((uint32) ((const uchar*) (A))[0]) << 16) |\ (((uint32) ((const uchar*) (A))[1]) << 8) | \ ((uint32) ((const uchar*) (A))[2]))) #define mi_sint4korr(A) ((int32) (((uint32) (((const uchar*) (A))[3])) |\ ((uint32) (((const uchar*) (A))[2]) << 8) |\ ((uint32) (((const uchar*) (A))[1]) << 16) |\ ((uint32) (((const uchar*) (A))[0]) << 24))) #define mi_sint8korr(A) ((longlong) mi_uint8korr(A)) #define mi_uint2korr(A) ((uint16) (((uint16) (((const uchar*) (A))[1])) |\ ((uint16) (((const uchar*) (A))[0]) << 8))) #define mi_uint3korr(A) ((uint32) (((uint32) (((const uchar*) (A))[2])) |\ (((uint32) (((const uchar*) (A))[1])) << 8) |\ (((uint32) (((const uchar*) (A))[0])) << 16))) #define mi_uint4korr(A) ((uint32) (((uint32) (((const uchar*) (A))[3])) |\ (((uint32) (((const uchar*) (A))[2])) << 8) |\ (((uint32) (((const uchar*) (A))[1])) << 16) |\ (((uint32) (((const uchar*) (A))[0])) << 24))) #ifndef HAVE_mi_uint5korr #define mi_uint5korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[4])) |\ (((uint32) (((const uchar*) (A))[3])) << 8) |\ (((uint32) (((const uchar*) (A))[2])) << 16) |\ (((uint32) (((const uchar*) (A))[1])) << 24)) |\ (((ulonglong) (((const uchar*) (A))[0])) << 32)) #endif /* HAVE_mi_uint5korr */ #ifndef HAVE_mi_uint6korr #define mi_uint6korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[5])) |\ (((uint32) (((const uchar*) (A))[4])) << 8) |\ (((uint32) (((const uchar*) (A))[3])) << 16) |\ (((uint32) (((const uchar*) (A))[2])) << 24)) |\ (((ulonglong) (((uint32) (((const uchar*) (A))[1])) |\ (((uint32) (((const uchar*) (A))[0]) << 8)))) <<\ 32)) #endif /* HAVE_mi_uint6korr */ #ifndef HAVE_mi_uint7korr #define mi_uint7korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[6])) |\ (((uint32) (((const uchar*) (A))[5])) << 8) |\ (((uint32) (((const uchar*) (A))[4])) << 16) |\ (((uint32) (((const uchar*) (A))[3])) << 24)) |\ (((ulonglong) (((uint32) (((const uchar*) (A))[2])) |\ (((uint32) (((const uchar*) (A))[1])) << 8) |\ (((uint32) (((const uchar*) (A))[0])) << 16))) <<\ 32)) #endif /* HAVE_mi_uint7korr */ #ifndef HAVE_mi_uint8korr #define mi_uint8korr(A) ((ulonglong)(((uint32) (((const uchar*) (A))[7])) |\ (((uint32) (((const uchar*) (A))[6])) << 8) |\ (((uint32) (((const uchar*) (A))[5])) << 16) |\ (((uint32) (((const uchar*) (A))[4])) << 24)) |\ (((ulonglong) (((uint32) (((const uchar*) (A))[3])) |\ (((uint32) (((const uchar*) (A))[2])) << 8) |\ (((uint32) (((const uchar*) (A))[1])) << 16) |\ (((uint32) (((const uchar*) (A))[0])) << 24))) <<\ 32)) #endif /* HAVE_mi_uint8korr */ /* This one is for uniformity */ #define mi_int1store(T,A) *((uchar*)(T))= (uchar) (A) #define mi_int2store(T,A) { uint def_temp= (uint) (A) ;\ ((uchar*) (T))[1]= (uchar) (def_temp);\ ((uchar*) (T))[0]= (uchar) (def_temp >> 8); } #define mi_int3store(T,A) { /*lint -save -e734 */\ ulong def_temp= (ulong) (A);\ ((uchar*) (T))[2]= (uchar) (def_temp);\ ((uchar*) (T))[1]= (uchar) (def_temp >> 8);\ ((uchar*) (T))[0]= (uchar) (def_temp >> 16);\ /*lint -restore */} #define mi_int4store(T,A) { ulong def_temp= (ulong) (A);\ ((uchar*) (T))[3]= (uchar) (def_temp);\ ((uchar*) (T))[2]= (uchar) (def_temp >> 8);\ ((uchar*) (T))[1]= (uchar) (def_temp >> 16);\ ((uchar*) (T))[0]= (uchar) (def_temp >> 24); } #define mi_int5store(T,A) { ulong def_temp= (ulong) (A),\ def_temp2= (ulong) ((A) >> 32);\ ((uchar*) (T))[4]= (uchar) (def_temp);\ ((uchar*) (T))[3]= (uchar) (def_temp >> 8);\ ((uchar*) (T))[2]= (uchar) (def_temp >> 16);\ ((uchar*) (T))[1]= (uchar) (def_temp >> 24);\ ((uchar*) (T))[0]= (uchar) (def_temp2); } #define mi_int6store(T,A) { ulong def_temp= (ulong) (A),\ def_temp2= (ulong) ((A) >> 32);\ ((uchar*) (T))[5]= (uchar) (def_temp);\ ((uchar*) (T))[4]= (uchar) (def_temp >> 8);\ ((uchar*) (T))[3]= (uchar) (def_temp >> 16);\ ((uchar*) (T))[2]= (uchar) (def_temp >> 24);\ ((uchar*) (T))[1]= (uchar) (def_temp2);\ ((uchar*) (T))[0]= (uchar) (def_temp2 >> 8); } #define mi_int7store(T,A) { ulong def_temp= (ulong) (A),\ def_temp2= (ulong) ((A) >> 32);\ ((uchar*) (T))[6]= (uchar) (def_temp);\ ((uchar*) (T))[5]= (uchar) (def_temp >> 8);\ ((uchar*) (T))[4]= (uchar) (def_temp >> 16);\ ((uchar*) (T))[3]= (uchar) (def_temp >> 24);\ ((uchar*) (T))[2]= (uchar) (def_temp2);\ ((uchar*) (T))[1]= (uchar) (def_temp2 >> 8);\ ((uchar*) (T))[0]= (uchar) (def_temp2 >> 16); } #define mi_int8store(T,A) { ulong def_temp3= (ulong) (A),\ def_temp4= (ulong) ((A) >> 32);\ mi_int4store((uchar*) (T) + 0, def_temp4);\ mi_int4store((uchar*) (T) + 4, def_temp3); } #ifdef WORDS_BIGENDIAN #define mi_float4store(T,A) { ((uchar*) (T))[0]= ((uchar*) &A)[0];\ ((uchar*) (T))[1]= ((uchar*) &A)[1];\ ((uchar*) (T))[2]= ((uchar*) &A)[2];\ ((uchar*) (T))[3]= ((uchar*) &A)[3]; } #define mi_float4get(V,M) { float def_temp;\ ((uchar*) &def_temp)[0]= ((const uchar*) (M))[0];\ ((uchar*) &def_temp)[1]= ((const uchar*) (M))[1]; \ ((uchar*) &def_temp)[2]= ((const uchar*) (M))[2];\ ((uchar*) &def_temp)[3]= ((const uchar*) (M))[3];\ (V)= def_temp; } #define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[0];\ ((uchar*) (T))[1]= ((const uchar*) &V)[1];\ ((uchar*) (T))[2]= ((const uchar*) &V)[2];\ ((uchar*) (T))[3]= ((const uchar*) &V)[3];\ ((uchar*) (T))[4]= ((const uchar*) &V)[4];\ ((uchar*) (T))[5]= ((const uchar*) &V)[5];\ ((uchar*) (T))[6]= ((const uchar*) &V)[6];\ ((uchar*) (T))[7]= ((const uchar*) &V)[7]; } #define mi_float8get(V,M) { double def_temp;\ ((uchar*) &def_temp)[0]= ((const uchar*) (M))[0];\ ((uchar*) &def_temp)[1]= ((const uchar*) (M))[1];\ ((uchar*) &def_temp)[2]= ((const uchar*) (M))[2];\ ((uchar*) &def_temp)[3]= ((const uchar*) (M))[3];\ ((uchar*) &def_temp)[4]= ((const uchar*) (M))[4];\ ((uchar*) &def_temp)[5]= ((const uchar*) (M))[5];\ ((uchar*) &def_temp)[6]= ((const uchar*) (M))[6];\ ((uchar*) &def_temp)[7]= ((const uchar*) (M))[7]; \ (V)= def_temp; } #else #define mi_float4store(T,A) { ((uchar*) (T))[0]= ((const uchar*) &A)[3];\ ((uchar*) (T))[1]= ((const uchar*) &A)[2];\ ((uchar*) (T))[2]= ((const uchar*) &A)[1];\ ((uchar*) (T))[3]= ((const uchar*) &A)[0]; } #define mi_float4get(V,M) { float def_temp;\ ((uchar*) &def_temp)[0]= ((const uchar*) (M))[3];\ ((uchar*) &def_temp)[1]= ((const uchar*) (M))[2];\ ((uchar*) &def_temp)[2]= ((const uchar*) (M))[1];\ ((uchar*) &def_temp)[3]= ((const uchar*) (M))[0];\ (V)= def_temp; } #if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) #define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[3];\ ((uchar*) (T))[1]= ((const uchar*) &V)[2];\ ((uchar*) (T))[2]= ((const uchar*) &V)[1];\ ((uchar*) (T))[3]= ((const uchar*) &V)[0];\ ((uchar*) (T))[4]= ((const uchar*) &V)[7];\ ((uchar*) (T))[5]= ((const uchar*) &V)[6];\ ((uchar*) (T))[6]= ((const uchar*) &V)[5];\ ((uchar*) (T))[7]= ((const uchar*) &V)[4];} #define mi_float8get(V,M) { double def_temp;\ ((uchar*) &def_temp)[0]= ((const uchar*) (M))[3];\ ((uchar*) &def_temp)[1]= ((const uchar*) (M))[2];\ ((uchar*) &def_temp)[2]= ((const uchar*) (M))[1];\ ((uchar*) &def_temp)[3]= ((const uchar*) (M))[0];\ ((uchar*) &def_temp)[4]= ((const uchar*) (M))[7];\ ((uchar*) &def_temp)[5]= ((const uchar*) (M))[6];\ ((uchar*) &def_temp)[6]= ((const uchar*) (M))[5];\ ((uchar*) &def_temp)[7]= ((const uchar*) (M))[4];\ (V)= def_temp; } #else #define mi_float8store(T,V) { ((uchar*) (T))[0]= ((const uchar*) &V)[7];\ ((uchar*) (T))[1]= ((const uchar*) &V)[6];\ ((uchar*) (T))[2]= ((const uchar*) &V)[5];\ ((uchar*) (T))[3]= ((const uchar*) &V)[4];\ ((uchar*) (T))[4]= ((const uchar*) &V)[3];\ ((uchar*) (T))[5]= ((const uchar*) &V)[2];\ ((uchar*) (T))[6]= ((const uchar*) &V)[1];\ ((uchar*) (T))[7]= ((const uchar*) &V)[0];} #define mi_float8get(V,M) { double def_temp;\ ((uchar*) &def_temp)[0]= ((const uchar*) (M))[7];\ ((uchar*) &def_temp)[1]= ((const uchar*) (M))[6];\ ((uchar*) &def_temp)[2]= ((const uchar*) (M))[5];\ ((uchar*) &def_temp)[3]= ((const uchar*) (M))[4];\ ((uchar*) &def_temp)[4]= ((const uchar*) (M))[3];\ ((uchar*) &def_temp)[5]= ((const uchar*) (M))[2];\ ((uchar*) &def_temp)[6]= ((const uchar*) (M))[1];\ ((uchar*) &def_temp)[7]= ((const uchar*) (M))[0];\ (V)= def_temp; } #endif /* __FLOAT_WORD_ORDER */ #endif /* WORDS_BIGENDIAN */ /* Fix to avoid warnings when sizeof(ha_rows) == sizeof(long) */ #ifdef BIG_TABLES #define mi_rowstore(T,A) mi_int8store(T, A) #define mi_rowkorr(T) mi_uint8korr(T) #else #define mi_rowstore(T,A) { mi_int4store(T, 0);\ mi_int4store(((uchar*) (T) + 4), A); } #define mi_rowkorr(T) mi_uint4korr((const uchar*) (T) + 4) #endif #if SIZEOF_OFF_T > 4 #define mi_sizestore(T,A) mi_int8store(T, A) #define mi_sizekorr(T) mi_uint8korr(T) #else #define mi_sizestore(T,A) { if ((A) == HA_OFFSET_ERROR)\ bfill((char*) (T), 8, 255);\ else { mi_int4store((T), 0);\ mi_int4store(((T) + 4), A); }} #define mi_sizekorr(T) mi_uint4korr((const uchar*) (T) + 4) #endif #endif /* MYISAMPACK_INCLUDED */ mysql/server/private/debug.h000064400000002322151027430560012132 0ustar00#ifndef DEBUG_INCLUDED #define DEBUG_INCLUDED /* Copyright (c) 2021, MariaDB Corporation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Declarations for debug_crash_here and other future mariadb server debug functionality. */ /* debug_crash_here() functionallity. See mysql_test/suite/atomic/create_table.test for an example of how it can be used */ #ifndef DBUG_OFF void debug_crash_here(const char *keyword); bool debug_simulate_error(const char *keyword, uint error); #else #define debug_crash_here(A) do { } while(0) #define debug_simulate_error(A, B) 0 #endif #endif /* DEBUG_INCLUDED */ mysql/server/private/my_libwrap.h000064400000002237151027430560013216 0ustar00#ifndef MY_LIBWRAP_INCLUDED #define MY_LIBWRAP_INCLUDED /* Copyright (c) 2000, 2006 MySQL AB, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef HAVE_LIBWRAP #include #include #ifdef NEED_SYS_SYSLOG_H #include #endif /* NEED_SYS_SYSLOG_H */ extern void my_fromhost(struct request_info *req); extern int my_hosts_access(struct request_info *req); extern char *my_eval_client(struct request_info *req); #endif /* HAVE_LIBWRAP */ #endif /* MY_LIBWRAP_INCLUDED */ mysql/server/sslopt-longopts.h000064400000005137151027430560012570 0ustar00#ifndef SSLOPT_LONGOPTS_INCLUDED #define SSLOPT_LONGOPTS_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) {"ssl", 0, "Enable SSL for connection (automatically enabled with other flags).", &opt_use_ssl, &opt_use_ssl, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-ca", OPT_SSL_CA, "CA file in PEM format (check OpenSSL docs, implies --ssl).", &opt_ssl_ca, &opt_ssl_ca, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-capath", OPT_SSL_CAPATH, "CA directory (check OpenSSL docs, implies --ssl).", &opt_ssl_capath, &opt_ssl_capath, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-cert", OPT_SSL_CERT, "X509 cert in PEM format (implies --ssl).", &opt_ssl_cert, &opt_ssl_cert, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-cipher", OPT_SSL_CIPHER, "SSL cipher to use (implies --ssl).", &opt_ssl_cipher, &opt_ssl_cipher, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-key", OPT_SSL_KEY, "X509 key in PEM format (implies --ssl).", &opt_ssl_key, &opt_ssl_key, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-crl", OPT_SSL_CRL, "Certificate revocation list (implies --ssl).", &opt_ssl_crl, &opt_ssl_crl, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"ssl-crlpath", OPT_SSL_CRLPATH, "Certificate revocation list path (implies --ssl).", &opt_ssl_crlpath, &opt_ssl_crlpath, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, {"tls-version", 0, "TLS protocol version for secure connection.", &opt_tls_version, &opt_tls_version, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, #ifdef MYSQL_CLIENT {"ssl-verify-server-cert", 0, "Verify server's \"Common Name\" in its cert against hostname used " "when connecting. This option is disabled by default.", &opt_ssl_verify_server_cert, &opt_ssl_verify_server_cert, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0}, #endif #endif /* HAVE_OPENSSL */ #endif /* SSLOPT_LONGOPTS_INCLUDED */ mysql/server/mysql_version.h000064400000002405151027430560012306 0ustar00/* Copyright Abandoned 1996,1999 TCX DataKonsult AB & Monty Program KB & Detron HB, 1996, 1999-2004, 2007 MySQL AB. This file is public domain and comes with NO WARRANTY of any kind */ /* Version numbers for protocol & mysqld */ #ifndef _mysql_version_h #define _mysql_version_h #ifdef _CUSTOMCONFIG_ #include #else #define PROTOCOL_VERSION 10 #define MYSQL_SERVER_VERSION "10.6.23-MariaDB" #define MYSQL_BASE_VERSION "mysqld-10.6" #define MARIADB_BASE_VERSION "mariadb-10.6" #define MARIADBD_BASE_VERSION "mariadbd-10.6" #define MYSQL_SERVER_SUFFIX_DEF "" #define FRM_VER 6 #define MYSQL_VERSION_ID 100623 #define MARIADB_PORT 3306 #define MYSQL_PORT_DEFAULT 0 #define MARIADB_UNIX_ADDR "/var/lib/mysql/mysql.sock" #define MYSQL_CONFIG_NAME "my" #define MYSQL_COMPILATION_COMMENT "MariaDB Server" #define SERVER_MATURITY_LEVEL MariaDB_PLUGIN_MATURITY_STABLE #define MYSQL_PORT MARIADB_PORT #define MYSQL_UNIX_ADDR MARIADB_UNIX_ADDR #ifdef WITH_WSREP #define WSREP_PATCH_VERSION "wsrep_26.22" #endif /* mysqld compile time options */ #endif /* _CUSTOMCONFIG_ */ #ifndef LICENSE #define LICENSE GPL #endif /* LICENSE */ #endif /* _mysql_version_h */ mysql/server/byte_order_generic.h000064400000012172151027430560013230 0ustar00/* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Endianness-independent definitions for architectures other than the x86 architecture. */ #define sint2korr(A) (int16) (((int16) ((uchar) (A)[0])) |\ ((int16) ((int16) (A)[1]) << 8)) #define sint3korr(A) ((int32) ((((uchar) (A)[2]) & 128) ? \ (((uint32) 255L << 24) | \ (((uint32) (uchar) (A)[2]) << 16) |\ (((uint32) (uchar) (A)[1]) << 8) | \ ((uint32) (uchar) (A)[0])) : \ (((uint32) (uchar) (A)[2]) << 16) |\ (((uint32) (uchar) (A)[1]) << 8) | \ ((uint32) (uchar) (A)[0]))) #define sint4korr(A) (int32) (((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1]) << 8)) |\ (((uint32) ((uchar) (A)[2]) << 16)) |\ (((uint32) ((uchar) (A)[3]) << 24))) #define sint8korr(A) (longlong) uint8korr(A) #define uint2korr(A) (uint16) (((uint16) ((uchar) (A)[0])) |\ ((uint16) ((uchar) (A)[1]) << 8)) #define uint3korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16)) #define uint4korr(A) (uint32) (((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16) |\ (((uint32) ((uchar) (A)[3])) << 24)) #define uint5korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16) |\ (((uint32) ((uchar) (A)[3])) << 24)) |\ (((ulonglong) ((uchar) (A)[4])) << 32)) #define uint6korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) | \ (((uint32) ((uchar) (A)[1])) << 8) | \ (((uint32) ((uchar) (A)[2])) << 16) | \ (((uint32) ((uchar) (A)[3])) << 24)) | \ (((ulonglong) ((uchar) (A)[4])) << 32) | \ (((ulonglong) ((uchar) (A)[5])) << 40)) #define uint8korr(A) ((ulonglong)(((uint32) ((uchar) (A)[0])) |\ (((uint32) ((uchar) (A)[1])) << 8) |\ (((uint32) ((uchar) (A)[2])) << 16) |\ (((uint32) ((uchar) (A)[3])) << 24)) |\ (((ulonglong) (((uint32) ((uchar) (A)[4])) |\ (((uint32) ((uchar) (A)[5])) << 8) |\ (((uint32) ((uchar) (A)[6])) << 16) |\ (((uint32) ((uchar) (A)[7])) << 24))) <<\ 32)) #define int2store(T,A) do { uint def_temp= (uint) (A) ;\ *((uchar*) (T))= (uchar)(def_temp); \ *((uchar*) (T)+1)=(uchar)((def_temp >> 8)); \ } while(0) #define int3store(T,A) do { /*lint -save -e734 */\ *((uchar*)(T))=(uchar) ((A));\ *((uchar*) (T)+1)=(uchar) (((A) >> 8));\ *((uchar*)(T)+2)=(uchar) (((A) >> 16)); \ /*lint -restore */} while(0) #define int4store(T,A) do { *((char *)(T))=(char) ((A));\ *(((char *)(T))+1)=(char) (((A) >> 8));\ *(((char *)(T))+2)=(char) (((A) >> 16));\ *(((char *)(T))+3)=(char) (((A) >> 24));\ } while(0) #define int5store(T,A) do { *((char *)(T))= (char)((A)); \ *(((char *)(T))+1)= (char)(((A) >> 8)); \ *(((char *)(T))+2)= (char)(((A) >> 16)); \ *(((char *)(T))+3)= (char)(((A) >> 24)); \ *(((char *)(T))+4)= (char)(((A) >> 32)); \ } while(0) #define int6store(T,A) do { *((char *)(T))= (char)((A)); \ *(((char *)(T))+1)= (char)(((A) >> 8)); \ *(((char *)(T))+2)= (char)(((A) >> 16)); \ *(((char *)(T))+3)= (char)(((A) >> 24)); \ *(((char *)(T))+4)= (char)(((A) >> 32)); \ *(((char *)(T))+5)= (char)(((A) >> 40)); \ } while(0) #define int8store(T,A) do { uint def_temp= (uint) (A), \ def_temp2= (uint) ((A) >> 32); \ int4store((T),def_temp); \ int4store((T+4),def_temp2);\ } while(0) mysql/server/my_sys.h000064400000126311151027430560010722 0ustar00/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. Copyright (c) 2010, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_sys_h #define _my_sys_h #include #include C_MODE_START #include #include #include /* for CHARSET_INFO */ #include #include #include #include #include #include #define MY_INIT(name) { my_progname= name; my_init(); } /** Max length of an error message generated by mysys utilities. Some mysys functions produce error messages. These mostly go to stderr. This constant defines the size of the buffer used to format the message. It should be kept in sync with MYSQL_ERRMSG_SIZE, since sometimes mysys errors are stored in the server diagnostics area, and we would like to avoid unexpected truncation. */ #define MYSYS_ERRMSG_SIZE (512) #define MYSYS_STRERROR_SIZE (128) #define MY_FILE_ERROR ((size_t) -1) /* General bitmaps for my_func's */ #define MY_FFNF 1U /* Fatal if file not found */ #define MY_FNABP 2U /* Fatal if not all bytes read/written */ #define MY_NABP 4U /* Error if not all bytes read/written */ #define MY_FAE 8U /* Fatal if any error */ #define MY_WME 16U /* Write message on error */ #define MY_WAIT_IF_FULL 32U /* Wait and try again if disk full error */ #define MY_IGNORE_BADFD 32U /* my_sync(): ignore 'bad descriptor' errors */ #define MY_IGNORE_ENOENT 32U /* my_delete() ignores ENOENT (no such file) */ #define MY_ENCRYPT 64U /* Encrypt IO_CACHE temporary files */ #define MY_TEMPORARY 64U /* create_temp_file(): delete file at once */ #define MY_NOSYMLINKS 512U /* my_open(): don't follow symlinks */ #define MY_FULL_IO 512U /* my_read(): loop until I/O is complete */ #define MY_DONT_CHECK_FILESIZE 128U /* Option to init_io_cache() */ #define MY_LINK_WARNING 32U /* my_redel() gives warning if links */ #define MY_COPYTIME 64U /* my_redel() copies time */ #define MY_DELETE_OLD 256U /* my_create_with_symlink() */ #define MY_RESOLVE_LINK 128U /* my_realpath(); Only resolve links */ #define MY_HOLD_ORIGINAL_MODES 128U /* my_copy() holds to file modes */ #define MY_REDEL_MAKE_BACKUP 256U #define MY_SEEK_NOT_DONE 32U /* my_lock may have to do a seek */ #define MY_SHORT_WAIT 64U /* my_lock() don't wait if can't lock */ #define MY_FORCE_LOCK 128U /* use my_lock() even if disable_locking */ #define MY_NO_WAIT 256U /* my_lock() don't wait at all */ #define MY_NO_REGISTER 8196U /* my_open(), no malloc for file name */ /* If old_mode is UTF8_IS_UTF8MB3, then pass this flag. It mean utf8 is alias for utf8mb3. Otherwise utf8 is alias for utf8mb4. */ #define MY_UTF8_IS_UTF8MB3 1024U /* init_dynamic_array() has init buffer; Internal flag, not to be used by caller. */ #define MY_INIT_BUFFER_USED 256U #define MY_ZEROFILL 32U /* my_malloc(), fill array with zero */ #define MY_ALLOW_ZERO_PTR 64U /* my_realloc() ; zero ptr -> malloc */ #define MY_FREE_ON_ERROR 128U /* my_realloc() ; Free old ptr on error */ #define MY_DONT_OVERWRITE_FILE 2048U /* my_copy: Don't overwrite file */ #define MY_THREADSAFE 2048U /* my_seek(): lock fd mutex */ #define MY_SYNC 4096U /* my_copy(): sync dst file */ #define MY_SYNC_DIR 32768U /* my_create/delete/rename: sync directory */ #define MY_THREAD_SPECIFIC 0x10000U /* my_malloc(): thread specific */ /* Tree that should delete things automatically */ #define MY_TREE_WITH_DELETE 0x40000U #define MY_CHECK_ERROR 1U /* Params to my_end; Check open-close */ #define MY_GIVE_INFO 2U /* Give time info about process*/ #define MY_DONT_FREE_DBUG 4U /* Do not call DBUG_END() in my_end() */ #define ME_BELL 4U /* Ring bell then printing message */ #define ME_ERROR_LOG 64 /**< write the error message to error log */ #define ME_ERROR_LOG_ONLY 128 /**< write the error message to error log only */ #define ME_NOTE 1024 /**< not error but just info */ #define ME_WARNING 2048 /**< not error but just warning */ #define ME_FATAL 4096 /**< fatal statement error */ /* Bits in last argument to fn_format */ #define MY_REPLACE_DIR 1U /* replace dir in name with 'dir' */ #define MY_REPLACE_EXT 2U /* replace extension with 'ext' */ #define MY_UNPACK_FILENAME 4U /* Unpack name (~ -> home) */ #define MY_PACK_FILENAME 8U /* Pack name (home -> ~) */ #define MY_RESOLVE_SYMLINKS 16U /* Resolve all symbolic links */ #define MY_RETURN_REAL_PATH 32U /* return full path for file */ #define MY_SAFE_PATH 64U /* Return NULL if too long path */ #define MY_RELATIVE_PATH 128U /* name is relative to 'dir' */ #define MY_APPEND_EXT 256U /* add 'ext' as additional extension*/ /* My seek flags */ #define MY_SEEK_SET 0 #define MY_SEEK_CUR 1 #define MY_SEEK_END 2 /* Some constants */ #define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */ #define MY_WAIT_GIVE_USER_A_MESSAGE 10 /* Every 10 times of prev */ #define MIN_COMPRESS_LENGTH 50 /* Don't compress small bl. */ #define DFLT_INIT_HITS 3 /* root_alloc flags */ #define MY_KEEP_PREALLOC 1U #define MY_MARK_BLOCKS_FREE 2U /* move used to free list and reuse them */ /* Internal error numbers (for assembler functions) */ #define MY_ERRNO_EDOM 33 #define MY_ERRNO_ERANGE 34 /* Bits for get_date timeflag */ #define GETDATE_DATE_TIME 1U #define GETDATE_SHORT_DATE 2U #define GETDATE_HHMMSSTIME 4U #define GETDATE_GMT 8U #define GETDATE_FIXEDLENGTH 16U /* Extra length needed for filename if one calls my_create_backup_name */ #define MY_BACKUP_NAME_EXTRA_LENGTH 17 char *guess_malloc_library(); /* If we have our own safemalloc (for debugging) */ #if defined(SAFEMALLOC) void sf_report_leaked_memory(my_thread_id id); int sf_sanity(); extern my_thread_id (*sf_malloc_dbug_id)(void); #define SAFEMALLOC_REPORT_MEMORY(X) if (!sf_leaking_memory) sf_report_leaked_memory(X) #else #define SAFEMALLOC_REPORT_MEMORY(X) do {} while(0) #endif typedef void (*MALLOC_SIZE_CB) (long long size, my_bool is_thread_specific); extern void set_malloc_size_cb(MALLOC_SIZE_CB func); extern MALLOC_SIZE_CB update_malloc_size; /* defines when allocating data */ extern void *my_malloc(PSI_memory_key key, size_t size, myf MyFlags); extern void *my_multi_malloc(PSI_memory_key key, myf MyFlags, ...); extern void *my_multi_malloc_large(PSI_memory_key key, myf MyFlags, ...); extern void *my_realloc(PSI_memory_key key, void *ptr, size_t size, myf MyFlags); extern void my_free(void *ptr); extern void *my_memdup(PSI_memory_key key, const void *from,size_t length,myf MyFlags); extern char *my_strdup(PSI_memory_key key, const char *from,myf MyFlags); extern char *my_strndup(PSI_memory_key key, const char *from, size_t length, myf MyFlags); int my_init_large_pages(my_bool super_large_pages); uchar *my_large_malloc(size_t *size, myf my_flags); void my_large_free(void *ptr, size_t size); #ifdef _WIN32 extern BOOL my_obtain_privilege(LPCSTR lpPrivilege); #endif void my_init_atomic_write(void); #ifdef __linux__ my_bool my_test_if_atomic_write(File handle, int pagesize); my_bool my_test_if_thinly_provisioned(File handle); #else # define my_test_if_atomic_write(A, B) 0 # define my_test_if_thinly_provisioned(A) 0 #endif /* __linux__ */ extern my_bool my_may_have_atomic_write; #if defined(HAVE_ALLOCA) && !defined(HAVE_valgrind) #define my_alloca(SZ) alloca((size_t) (SZ)) #define my_afree(PTR) ((void)0) #define MAX_ALLOCA_SZ 4096 #define my_safe_alloca(size) (((size) <= MAX_ALLOCA_SZ) ? \ my_alloca(size) : \ my_malloc(PSI_NOT_INSTRUMENTED, (size), MYF(MY_THREAD_SPECIFIC|MY_WME))) #define my_safe_afree(ptr, size) \ do { if ((size) > MAX_ALLOCA_SZ) my_free(ptr); } while(0) #else #define my_alloca(SZ) my_malloc(PSI_NOT_INSTRUMENTED, SZ,MYF(MY_FAE)) #define my_afree(PTR) my_free(PTR) #define my_safe_alloca(size) my_alloca(size) #define my_safe_afree(ptr, size) my_afree(ptr) #endif /* HAVE_ALLOCA */ #ifndef errno /* did we already get it? */ #ifdef HAVE_ERRNO_AS_DEFINE #include /* errno is a define */ #else extern int errno; /* declare errno */ #endif #endif /* #ifndef errno */ extern char *home_dir; /* Home directory for user */ extern MYSQL_PLUGIN_IMPORT char *mysql_data_home; extern const char *my_progname; /* program-name (printed in errors) */ extern const char *my_progname_short; /* like above but without directory */ extern char curr_dir[]; /* Current directory for user */ extern void (*error_handler_hook)(uint my_err, const char *str,myf MyFlags); extern void (*fatal_error_handler_hook)(uint my_err, const char *str, myf MyFlags); extern uint my_file_limit; extern ulonglong my_thread_stack_size; extern int sf_leaking_memory; /* set to 1 to disable memleak detection */ extern void (*proc_info_hook)(void *, const PSI_stage_info *, PSI_stage_info *, const char *, const char *, const unsigned int); /* charsets */ #define MY_ALL_CHARSETS_SIZE 2048 extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *default_charset_info; extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *all_charsets[MY_ALL_CHARSETS_SIZE]; extern struct charset_info_st compiled_charsets[]; /* Collation properties and use statistics */ extern my_bool my_collation_is_known_id(uint id); extern ulonglong my_collation_statistics_get_use_count(uint id); extern const char *my_collation_get_tailoring(uint id); /* statistics */ extern ulong my_stream_opened, my_tmp_file_created; extern ulong my_file_total_opened; extern ulong my_sync_count; extern uint mysys_usage_id; extern int32 my_file_opened; extern my_bool my_init_done, my_thr_key_mysys_exists; extern my_bool my_assert; extern my_bool my_assert_on_error; extern myf my_global_flags; /* Set to MY_WME for more error messages */ /* Point to current my_message() */ extern void (*my_sigtstp_cleanup)(void), /* Executed before jump to shell */ (*my_sigtstp_restart)(void); /* Executed when coming from shell */ extern MYSQL_PLUGIN_IMPORT mode_t my_umask; /* Default creation mask */ extern mode_t my_umask_dir; extern int my_recived_signals, /* Signals we have got */ my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */ my_dont_interrupt; /* call remember_intr when set */ #ifdef _WIN32 extern SECURITY_ATTRIBUTES my_dir_security_attributes; LPSECURITY_ATTRIBUTES my_win_file_secattr(); #endif extern MYSQL_PLUGIN_IMPORT my_bool my_use_symdir; extern ulong my_default_record_cache_size; extern MYSQL_PLUGIN_IMPORT my_bool my_disable_locking; extern my_bool my_disable_async_io, my_disable_flush_key_blocks, my_disable_symlinks; extern my_bool my_disable_sync, my_disable_copystat_in_redel; extern char wild_many,wild_one,wild_prefix; extern const char *charsets_dir; enum cache_type { TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE, SEQ_READ_APPEND /* sequential read or append */, READ_FIFO, READ_NET}; enum flush_type { FLUSH_KEEP, /* flush block and keep it in the cache */ FLUSH_RELEASE, /* flush block and remove it from the cache */ FLUSH_IGNORE_CHANGED, /* remove block from the cache */ /* As my_disable_flush_pagecache_blocks is always 0, the following option is strictly equivalent to FLUSH_KEEP */ FLUSH_FORCE_WRITE, /** @brief like FLUSH_KEEP but return immediately if file is already being flushed (even partially) by another thread; only for page cache, forbidden for key cache. */ FLUSH_KEEP_LAZY }; typedef struct st_record_cache /* Used when caching records */ { File file; int rc_seek,error,inited; uint rc_length,read_length,reclength; my_off_t rc_record_pos,end_of_file; uchar *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos; enum cache_type type; } RECORD_CACHE; enum file_type { UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN, FILE_BY_O_TMPFILE, FILE_BY_MKSTEMP, FILE_BY_DUP }; struct st_my_file_info { char *name; #ifdef _WIN32 HANDLE fhandle; /* win32 file handle */ int oflag; /* open flags, e.g O_APPEND */ #endif enum file_type type; }; extern struct st_my_file_info *my_file_info; /* Free function pointer */ typedef void (*FREE_FUNC)(void *); typedef struct st_dynamic_array { uchar *buffer; uint elements,max_element; uint alloc_increment; uint size_of_element; PSI_memory_key m_psi_key; myf malloc_flags; } DYNAMIC_ARRAY; typedef struct st_my_tmpdir { DYNAMIC_ARRAY full_list; char **list; uint cur, max; mysql_mutex_t mutex; } MY_TMPDIR; typedef struct st_dynamic_string { char *str; size_t length,max_length,alloc_increment; } DYNAMIC_STRING; struct st_io_cache; typedef struct st_io_cache_share { mysql_mutex_t mutex; /* To sync on reads into buffer. */ mysql_cond_t cond; /* To wait for signals. */ mysql_cond_t cond_writer; /* For a synchronized writer. */ /* Offset in file corresponding to the first byte of buffer. */ my_off_t pos_in_file; /* If a synchronized write cache is the source of the data. */ struct st_io_cache *source_cache; uchar *buffer; /* The read buffer. */ uchar *read_end; /* Behind last valid byte of buffer. */ int running_threads; /* threads not in lock. */ int total_threads; /* threads sharing the cache. */ int error; /* Last error. */ #ifdef NOT_YET_IMPLEMENTED /* whether the structure should be free'd */ my_bool alloced; #endif } IO_CACHE_SHARE; typedef struct st_io_cache /* Used when caching files */ { /* Offset in file corresponding to the first byte of uchar* buffer. */ my_off_t pos_in_file; /* The offset of end of file for READ_CACHE and WRITE_CACHE. For SEQ_READ_APPEND it the maximum of the actual end of file and the position represented by read_end. */ my_off_t end_of_file; /* Points to current read position in the buffer */ uchar *read_pos; /* the non-inclusive boundary in the buffer for the currently valid read */ uchar *read_end; uchar *buffer; /* The read buffer */ /* Used in ASYNC_IO */ uchar *request_pos; /* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */ uchar *write_buffer; /* Only used in SEQ_READ_APPEND, and points to the current read position in the write buffer. Note that reads in SEQ_READ_APPEND caches can happen from both read buffer (uchar* buffer) and write buffer (uchar* write_buffer). */ uchar *append_read_pos; /* Points to current write position in the write buffer */ uchar *write_pos; /* The non-inclusive boundary of the valid write area */ uchar *write_end; /* The lock is for append buffer used in SEQ_READ_APPEND cache need mutex copying from append buffer to read buffer. */ mysql_mutex_t append_buffer_lock; /* The following is used when several threads are reading the same file in parallel. They are synchronized on disk accesses reading the cached part of the file asynchronously. It should be set to NULL to disable the feature. Only READ_CACHE mode is supported. */ IO_CACHE_SHARE *share; /* A caller will use my_b_read() macro to read from the cache if the data is already in cache, it will be simply copied with memcpy() and internal variables will be accordingly updated with no functions invoked. However, if the data is not fully in the cache, my_b_read() will call read_function to fetch the data. read_function must never be invoked directly. */ int (*read_function)(struct st_io_cache *,uchar *,size_t); /* Same idea as in the case of read_function, except my_b_write() needs to be replaced with my_b_append() for a SEQ_READ_APPEND cache */ int (*write_function)(struct st_io_cache *,const uchar *,size_t); /* Specifies the type of the cache. Depending on the type of the cache certain operations might not be available and yield unpredicatable results. Details to be documented later */ enum cache_type type; /* Counts the number of times, when we were forced to use disk. We use it to increase the binlog_cache_disk_use and binlog_stmt_cache_disk_use status variables. */ ulong disk_writes; char *file_name; /* if used with 'open_cached_file' */ const char *dir; char prefix[3]; File file; /* file descriptor */ struct st_io_cache *next_file_user; /* seek_not_done is set by my_b_seek() to inform the upcoming read/write operation that a seek needs to be preformed prior to the actual I/O error is 0 if the cache operation was successful, -1 if there was a "hard" error, and the actual number of I/O-ed bytes if the read/write was partial. */ int seek_not_done,error; /* length of the buffer used for storing un-encrypted data */ size_t buffer_length; /* read_length is the same as buffer_length except when we use async io */ size_t read_length; myf myflags; /* Flags used to my_read/my_write */ /* alloced_buffer is set to the size of the buffer allocated for the IO_CACHE. Includes the overhead(storing key to encrypt and decrypt) for encryption. Set to 0 if nothing is allocated. Currently READ_NET is the only one that will use a buffer allocated somewhere else */ size_t alloced_buffer; } IO_CACHE; typedef void (*my_error_reporter)(enum loglevel level, const char *format, ...) ATTRIBUTE_FORMAT_FPTR(printf, 2, 3); extern my_error_reporter my_charset_error_reporter; extern PSI_file_key key_file_io_cache; /* inline functions for mf_iocache */ extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock); extern int _my_b_get(IO_CACHE *info); extern int _my_b_read(IO_CACHE *info,uchar *Buffer,size_t Count); extern int _my_b_write(IO_CACHE *info,const uchar *Buffer,size_t Count); /* Test if buffer is inited */ static inline void my_b_clear(IO_CACHE *info) { info->buffer= 0; } static inline int my_b_inited(IO_CACHE *info) { return MY_TEST(info->buffer); } #define my_b_EOF INT_MIN static inline int my_b_read(IO_CACHE *info, uchar *Buffer, size_t Count) { if (info->read_pos + Count <= info->read_end) { memcpy(Buffer, info->read_pos, Count); info->read_pos+= Count; return 0; } return _my_b_read(info, Buffer, Count); } static inline int my_b_write(IO_CACHE *info, const uchar *Buffer, size_t Count) { MEM_CHECK_DEFINED(Buffer, Count); if (info->write_pos + Count <= info->write_end) { if (Count) { memcpy(info->write_pos, Buffer, Count); info->write_pos+= Count; } return 0; } return _my_b_write(info, Buffer, Count); } static inline int my_b_get(IO_CACHE *info) { if (info->read_pos != info->read_end) { info->read_pos++; return info->read_pos[-1]; } return _my_b_get(info); } static inline my_bool my_b_write_byte(IO_CACHE *info, uchar chr) { MEM_CHECK_DEFINED(&chr, 1); if (info->write_pos >= info->write_end) if (my_b_flush_io_cache(info, 1)) return 1; *info->write_pos++= chr; return 0; } /** Fill buffer of the cache. @note It assumes that you have already used all characters in the CACHE, independent of the read_pos value! @returns 0 On error or EOF (info->error = -1 on error) # Number of characters */ static inline size_t my_b_fill(IO_CACHE *info) { info->read_pos= info->read_end; return _my_b_read(info,0,0) ? 0 : (size_t) (info->read_end - info->read_pos); } static inline my_off_t my_b_tell(const IO_CACHE *info) { if (info->type == WRITE_CACHE) { return info->pos_in_file + (my_off_t)(info->write_pos - info->request_pos); } return info->pos_in_file + (my_off_t) (info->read_pos - info->request_pos); } static inline my_off_t my_b_write_tell(const IO_CACHE *info) { return info->pos_in_file + (my_off_t) (info->write_pos - info->write_buffer); } static inline uchar* my_b_get_buffer_start(const IO_CACHE *info) { return info->request_pos; } static inline size_t my_b_get_bytes_in_buffer(const IO_CACHE *info) { return (size_t) (info->read_end - info->request_pos); } static inline my_off_t my_b_get_pos_in_file(const IO_CACHE *info) { return info->pos_in_file; } static inline size_t my_b_bytes_in_cache(const IO_CACHE *info) { if (info->type == WRITE_CACHE) { return (size_t) (info->write_end - info->write_pos); } return (size_t) (info->read_end - info->read_pos); } int my_b_copy_to_file (IO_CACHE *cache, FILE *file, size_t count); int my_b_copy_all_to_file(IO_CACHE *cache, FILE *file); my_off_t my_b_append_tell(IO_CACHE* info); my_off_t my_b_safe_tell(IO_CACHE* info); /* picks the correct tell() */ int my_b_pread(IO_CACHE *info, uchar *Buffer, size_t Count, my_off_t pos); typedef uint32 ha_checksum; extern int (*mysys_test_invalid_symlink)(const char *filename); #include /* Prototypes for mysys and my_func functions */ extern int my_copy(const char *from,const char *to,myf MyFlags); extern int my_delete(const char *name,myf MyFlags); extern int my_rmtree(const char *name, myf Myflags); extern int my_getwd(char * buf,size_t size,myf MyFlags); extern int my_setwd(const char *dir,myf MyFlags); extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags); extern void *my_once_alloc(size_t Size,myf MyFlags); extern void my_once_free(void); extern char *my_once_strdup(const char *src,myf myflags); extern void *my_once_memdup(const void *src, size_t len, myf myflags); extern File my_open(const char *FileName,int Flags,myf MyFlags); extern File my_register_filename(File fd, const char *FileName, enum file_type type_of_file, uint error_message_number, myf MyFlags); extern File my_create(const char *FileName, mode_t CreateFlags, int AccessFlags, myf MyFlags); extern int my_close(File Filedes,myf MyFlags); extern int my_mkdir(const char *dir, int Flags, myf MyFlags); extern int my_readlink(char *to, const char *filename, myf MyFlags); extern int my_is_symlink(const char *filename); extern int my_realpath(char *to, const char *filename, myf MyFlags); extern File my_create_with_symlink(const char *linkname, const char *filename, mode_t createflags, int access_flags, myf MyFlags); extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags); extern int my_symlink(const char *content, const char *linkname, myf MyFlags); extern int my_handler_delete_with_symlink(const char *filename, myf sync_dir); extern size_t my_read(File Filedes,uchar *Buffer,size_t Count,myf MyFlags); extern size_t my_pread(File Filedes,uchar *Buffer,size_t Count,my_off_t offset, myf MyFlags); extern int my_rename(const char *from,const char *to,myf MyFlags); extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags); extern my_off_t my_tell(File fd,myf MyFlags); extern size_t my_write(File Filedes,const uchar *Buffer,size_t Count, myf MyFlags); extern size_t my_pwrite(File Filedes,const uchar *Buffer,size_t Count, my_off_t offset,myf MyFlags); extern size_t my_fread(FILE *stream,uchar *Buffer,size_t Count,myf MyFlags); extern size_t my_fwrite(FILE *stream,const uchar *Buffer,size_t Count, myf MyFlags); extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags); extern my_off_t my_ftell(FILE *stream,myf MyFlags); extern void (*my_sleep_for_space)(unsigned int seconds); extern int my_get_exepath(char *buf, size_t size, const char *argv0); /* implemented in my_memmem.c */ extern void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen); #ifdef _WIN32 extern int my_access(const char *path, int amode); #define my_check_user(A,B) (NULL) #define my_set_user(A,B,C) (0) #else #define my_access access struct passwd *my_check_user(const char *user, myf MyFlags); int my_set_user(const char *user, struct passwd *user_info, myf MyFlags); #endif extern int check_if_legal_filename(const char *path); extern int check_if_legal_tablename(const char *path); #ifdef _WIN32 extern my_bool is_filename_allowed(const char *name, size_t length, my_bool allow_current_dir); #else /* _WIN32 */ # define is_filename_allowed(name, length, allow_cwd) (TRUE) #endif /* _WIN32 */ #ifdef _WIN32 /* Windows-only functions (CRT equivalents)*/ extern HANDLE my_get_osfhandle(File fd); extern File my_win_handle2File(HANDLE hFile); extern void my_osmaperr(unsigned long last_error); #endif extern void init_glob_errs(void); extern const char** get_global_errmsgs(int nr); extern void wait_for_free_space(const char *filename, int errors); extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags); extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags); extern FILE *my_freopen(const char *path, const char *mode, FILE *stream); extern int my_fclose(FILE *fd,myf MyFlags); extern int my_vfprintf(FILE *stream, const char* format, va_list args); extern const char* my_strerror(char *buf, size_t len, int nr); extern int my_fprintf(FILE *stream, const char* format, ...); extern File my_fileno(FILE *fd); extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags); extern int my_chmod(const char *name, mode_t mode, myf my_flags); extern const char *my_basename(const char *filename); extern void thr_set_sync_wait_callback(void (*before_sync)(void), void (*after_sync)(void)); extern int my_sync(File fd, myf my_flags); extern int my_sync_dir(const char *dir_name, myf my_flags); extern int my_sync_dir_by_file(const char *file_name, myf my_flags); extern const char *my_get_err_msg(uint nr); extern int my_error_register(const char** (*get_errmsgs) (int nr), uint first, uint last); extern my_bool my_error_unregister(uint first, uint last); extern void my_message(uint my_err, const char *str,myf MyFlags); extern void my_message_stderr(uint my_err, const char *str, myf MyFlags); extern my_bool my_init(void); extern void my_end(int infoflag); extern int my_redel(const char *from, const char *to, time_t backup_time_stamp, myf MyFlags); void my_create_backup_name(char *to, const char *from, time_t backup_time_stamp); extern int my_copystat(const char *from, const char *to, int MyFlags); extern char * my_filename(File fd); extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist); extern char *my_tmpdir(MY_TMPDIR *tmpdir); extern void free_tmpdir(MY_TMPDIR *tmpdir); extern void my_remember_signal(int signal_number,sig_handler (*func)(int)); extern size_t dirname_part(char * to,const char *name, size_t *to_res_length); extern size_t dirname_length(const char *name); #define base_name(A) (A+dirname_length(A)) extern int test_if_hard_path(const char *dir_name); extern my_bool has_path(const char *name); extern char *convert_dirname(char *to, const char *from, const char *from_end); extern void to_unix_path(char * name); extern char * fn_ext(const char *name); extern char * fn_ext2(const char *name); extern char * fn_same(char * toname,const char *name,int flag); extern char * fn_format(char * to,const char *name,const char *dir, const char *form, uint flag); extern size_t strlength(const char *str); extern void pack_dirname(char * to,const char *from); extern size_t normalize_dirname(char * to, const char *from); extern size_t unpack_dirname(char * to,const char *from); extern size_t cleanup_dirname(char * to,const char *from); extern size_t system_filename(char * to,const char *from); extern size_t unpack_filename(char * to,const char *from); extern char * intern_filename(char * to,const char *from); extern int pack_filename(char * to, const char *name, size_t max_length); extern char * my_path(char * to,const char *progname, const char *own_pathname_part); extern char * my_load_path(char * to, const char *path, const char *own_path_prefix); extern int wild_compare(const char *str,const char *wildstr, pbool str_is_pattern); extern my_bool array_append_string_unique(const char *str, const char **array, size_t size); extern void get_date(char * to,int timeflag,time_t use_time); extern void soundex(CHARSET_INFO *, char * out_pntr, char * in_pntr, pbool remove_garbage); extern int init_record_cache(RECORD_CACHE *info,size_t cachesize,File file, size_t reclength,enum cache_type type, pbool use_async_io); extern int read_cache_record(RECORD_CACHE *info,uchar *to); extern int end_record_cache(RECORD_CACHE *info); extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos, const uchar *record,size_t length); extern int flush_write_cache(RECORD_CACHE *info); extern void handle_recived_signals(void); extern sig_handler my_set_alarm_variable(int signo); extern my_bool radixsort_is_appliccable(uint n_items, size_t size_of_element); extern void my_string_ptr_sort(uchar *base,uint items,size_t size); extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements, size_t size_of_element,uchar *buffer[]); extern qsort_t my_qsort(void *base_ptr, size_t total_elems, size_t size, qsort_cmp cmp); extern qsort_t my_qsort2(void *base_ptr, size_t total_elems, size_t size, qsort_cmp2 cmp, void *cmp_argument); extern qsort_cmp2 get_ptr_compare(size_t); void my_store_ptr(uchar *buff, size_t pack_length, my_off_t pos); my_off_t my_get_ptr(uchar *ptr, size_t pack_length); extern int init_io_cache(IO_CACHE *info,File file,size_t cachesize, enum cache_type type,my_off_t seek_offset, my_bool use_async_io, myf cache_myflags); extern int init_io_cache_ext(IO_CACHE *info, File file, size_t cachesize, enum cache_type type, my_off_t seek_offset, pbool use_async_io, myf cache_myflags, PSI_file_key file_key); extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type, my_off_t seek_offset, my_bool use_async_io, my_bool clear_cache); extern void init_io_cache_share(IO_CACHE *read_cache, IO_CACHE_SHARE *cshare, IO_CACHE *write_cache, uint num_threads); extern int init_slave_io_cache(IO_CACHE *master, IO_CACHE *slave); void end_slave_io_cache(IO_CACHE *cache); void seek_io_cache(IO_CACHE *cache, my_off_t needed_offset); extern void remove_io_thread(IO_CACHE *info); extern int my_b_append(IO_CACHE *info,const uchar *Buffer,size_t Count); extern int my_b_safe_write(IO_CACHE *info,const uchar *Buffer,size_t Count); extern int my_block_write(IO_CACHE *info, const uchar *Buffer, size_t Count, my_off_t pos); #define flush_io_cache(info) my_b_flush_io_cache((info),1) extern int end_io_cache(IO_CACHE *info); extern void my_b_seek(IO_CACHE *info,my_off_t pos); extern size_t my_b_gets(IO_CACHE *info, char *to, size_t max_length); extern my_off_t my_b_filelength(IO_CACHE *info); extern my_bool my_b_write_backtick_quote(IO_CACHE *info, const char *str, size_t len); extern my_bool my_b_printf(IO_CACHE *info, const char* fmt, ...); extern size_t my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap); extern my_bool open_cached_file(IO_CACHE *cache,const char *dir, const char *prefix, size_t cache_size, myf cache_myflags); extern my_bool real_open_cached_file(IO_CACHE *cache); extern void close_cached_file(IO_CACHE *cache); File create_temp_file(char *to, const char *dir, const char *pfx, int mode, myf MyFlags); #define my_init_dynamic_array(A,B,C,D,E,F) init_dynamic_array2(A,B,C,NULL,D,E,F) #define my_init_dynamic_array2(A,B,C,D,E,F,G) init_dynamic_array2(A,B,C,D,E,F,G) extern my_bool init_dynamic_array2(PSI_memory_key psi_key, DYNAMIC_ARRAY *array, uint element_size, void *init_buffer, uint init_alloc, uint alloc_increment, myf my_flags); extern my_bool insert_dynamic(DYNAMIC_ARRAY *array, const void* element); extern void *alloc_dynamic(DYNAMIC_ARRAY *array); extern void *pop_dynamic(DYNAMIC_ARRAY*); extern my_bool set_dynamic(DYNAMIC_ARRAY *array, const void *element, uint array_index); extern my_bool allocate_dynamic(DYNAMIC_ARRAY *array, uint max_elements); extern void get_dynamic(DYNAMIC_ARRAY *array, void *element, uint array_index); extern void delete_dynamic(DYNAMIC_ARRAY *array); extern void delete_dynamic_element(DYNAMIC_ARRAY *array, uint array_index); extern void delete_dynamic_with_callback(DYNAMIC_ARRAY *array, FREE_FUNC f); extern void freeze_size(DYNAMIC_ARRAY *array); extern int get_index_dynamic(DYNAMIC_ARRAY *array, void *element); #define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element) #define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index)) #define push_dynamic(A,B) insert_dynamic((A),(B)) #define reset_dynamic(array) ((array)->elements= 0) #define sort_dynamic(A,cmp) my_qsort((A)->buffer, (A)->elements, (A)->size_of_element, (cmp)) extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str, size_t init_alloc,size_t alloc_increment); extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append); my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append, size_t length); extern my_bool dynstr_append_os_quoted(DYNAMIC_STRING *str, const char *append, ...); extern my_bool dynstr_append_quoted(DYNAMIC_STRING *str, const char *append, size_t len, char quote); extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str); extern my_bool dynstr_realloc(DYNAMIC_STRING *str, size_t additional_size); extern my_bool dynstr_trunc(DYNAMIC_STRING *str, size_t n); extern void dynstr_free(DYNAMIC_STRING *str); extern uint32 copy_and_convert_extended(char *to, uint32 to_length, CHARSET_INFO *to_cs, const char *from, uint32 from_length, CHARSET_INFO *from_cs, uint *errors); extern void dynstr_reassociate(DYNAMIC_STRING *str, char **res, size_t *length, size_t *alloc_length); extern uint32 copy_and_convert_extended(char *to, uint32 to_length, CHARSET_INFO *to_cs, const char *from, uint32 from_length, CHARSET_INFO *from_cs, uint *errors); #ifdef HAVE_MLOCK extern void *my_malloc_lock(size_t length,myf flags); extern void my_free_lock(void *ptr); #else #define my_malloc_lock(A,B) my_malloc(PSI_INSTRUMENT_ME, (A),(B)) #define my_free_lock(A) my_free((A)) #endif #define alloc_root_inited(A) ((A)->min_malloc != 0) #define ALLOC_ROOT_MIN_BLOCK_SIZE (MALLOC_OVERHEAD + sizeof(USED_MEM) + 8) #define DEFAULT_ROOT_BLOCK_SIZE 1024 #define clear_alloc_root(A) do { (A)->free= (A)->used= (A)->pre_alloc= 0; (A)->min_malloc=0;} while(0) extern void init_alloc_root(PSI_memory_key key, MEM_ROOT *mem_root, size_t block_size, size_t pre_alloc_size, myf my_flags); extern void *alloc_root(MEM_ROOT *mem_root, size_t Size); extern void *multi_alloc_root(MEM_ROOT *mem_root, ...); extern void free_root(MEM_ROOT *root, myf MyFLAGS); extern void move_root(MEM_ROOT *to, MEM_ROOT *from); extern void set_prealloc_root(MEM_ROOT *root, char *ptr); extern void reset_root_defaults(MEM_ROOT *mem_root, size_t block_size, size_t prealloc_size); extern char *strdup_root(MEM_ROOT *root,const char *str); static inline char *safe_strdup_root(MEM_ROOT *root, const char *str) { return str ? strdup_root(root, str) : 0; } extern char *strmake_root(MEM_ROOT *root,const char *str,size_t len); extern void *memdup_root(MEM_ROOT *root,const void *str, size_t len); extern LEX_CSTRING safe_lexcstrdup_root(MEM_ROOT *root, const LEX_CSTRING str); extern my_bool my_compress(uchar *, size_t *, size_t *); extern my_bool my_uncompress(uchar *, size_t , size_t *); extern uchar *my_compress_alloc(const uchar *packet, size_t *len, size_t *complen); extern void *my_az_allocator(void *dummy, unsigned int items, unsigned int size); extern void my_az_free(void *dummy, void *address); extern int my_compress_buffer(uchar *dest, size_t *destLen, const uchar *source, size_t sourceLen); extern int packfrm(const uchar *, size_t, uchar **, size_t *); extern int unpackfrm(uchar **, size_t *, const uchar *); extern uint32 my_checksum(uint32, const void *, size_t); extern uint32 my_crc32c(uint32, const void *, size_t); extern const char *my_crc32c_implementation(); #ifdef DBUG_ASSERT_EXISTS extern void my_debug_put_break_here(void); #else #define my_debug_put_break_here() do {} while(0) #endif extern void my_sleep(ulong m_seconds); extern uint my_set_max_open_files(uint files); void my_free_open_file_info(void); extern my_bool my_gethwaddr(uchar *to); extern int my_getncpus(void); #define HRTIME_RESOLUTION 1000000ULL /* microseconds */ typedef struct {ulonglong val;} my_hrtime_t; void my_time_init(void); extern my_hrtime_t my_hrtime(void); #ifdef _WIN32 extern my_hrtime_t my_hrtime_coarse(); #else #define my_hrtime_coarse() my_hrtime() #endif extern ulonglong my_interval_timer(void); extern ulonglong my_getcputime(void); #define microsecond_interval_timer() (my_interval_timer()/1000) #define hrtime_to_time(X) ((time_t)((X).val/HRTIME_RESOLUTION)) #define hrtime_from_time(X) ((ulonglong)((X)*HRTIME_RESOLUTION)) #define hrtime_to_double(X) ((X).val/(double)HRTIME_RESOLUTION) #define hrtime_sec_part(X) ((ulong)((X).val % HRTIME_RESOLUTION)) #define my_time(X) hrtime_to_time(my_hrtime_coarse()) /** Make high resolution time from two parts. */ static inline my_hrtime_t make_hr_time(my_time_t time, ulong time_sec_part) { my_hrtime_t res= {((ulonglong) time)*1000000 + time_sec_part}; return res; } #if STACK_DIRECTION < 0 #define available_stack_size(CUR,END) (long) ((char*)(CUR) - (char*)(END)) #else #define available_stack_size(CUR,END) (long) ((char*)(END) - (char*)(CUR)) #endif #ifndef MAP_SYNC #define MAP_SYNC 0x80000 #endif #ifndef MAP_SHARED_VALIDATE #define MAP_SHARED_VALIDATE 0x03 #endif #ifdef HAVE_SYS_MMAN_H #ifndef MAP_NOSYNC #define MAP_NOSYNC 0 #endif #ifndef MAP_NORESERVE #define MAP_NORESERVE 0 /* For irix and AIX */ #endif #ifdef HAVE_MMAP64 #define my_mmap(a,b,c,d,e,f) mmap64(a,b,c,d,e,f) #else #define my_mmap(a,b,c,d,e,f) mmap(a,b,c,d,e,f) #endif #define my_munmap(a,b) munmap((a),(b)) #else /* not a complete set of mmap() flags, but only those that necessary */ #define PROT_READ 1 #define PROT_WRITE 2 #define MAP_NORESERVE 0 #define MAP_SHARED 0x0001 #define MAP_PRIVATE 0x0002 #define MAP_NOSYNC 0x0800 #define MAP_FAILED ((void *)-1) #define MS_SYNC 0x0000 #define HAVE_MMAP void *my_mmap(void *, size_t, int, int, int, my_off_t); int my_munmap(void *, size_t); #endif #ifdef _WIN32 extern FILE* my_win_popen(const char*, const char*); extern int my_win_pclose(FILE*); #define my_popen(A,B) my_win_popen(A,B) #define my_pclose(A) my_win_pclose(A) #else #define my_popen(A,B) popen(A,B) #define my_pclose(A) pclose(A) #endif /* my_getpagesize */ #ifdef HAVE_GETPAGESIZE #define my_getpagesize() getpagesize() #else int my_getpagesize(void); #endif int my_msync(int, void *, size_t, int); #define MY_UUID_SIZE 16 #define MY_UUID_STRING_LENGTH (8+1+4+1+4+1+4+1+12) #define MY_UUID_ORACLE_STRING_LENGTH (8+4+4+4+12) void my_uuid_init(ulong seed1, ulong seed2); void my_uuid(uchar *guid); void my_uuid2str(const uchar *guid, char *s); void my_uuid2str_oracle(const uchar *guid, char *s); void my_uuid_end(void); const char *my_dlerror(const char *dlpath); /* character sets */ extern void my_charset_loader_init_mysys(MY_CHARSET_LOADER *loader); extern uint get_charset_number(const char *cs_name, uint cs_flags, myf flags); extern uint get_collation_number(const char *name,myf flags); extern const char *get_charset_name(uint cs_number); extern CHARSET_INFO *get_charset(uint cs_number, myf flags); extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags); extern CHARSET_INFO *my_collation_get_by_name(MY_CHARSET_LOADER *loader, const char *name, myf flags); extern CHARSET_INFO *get_charset_by_csname(const char *cs_name, uint cs_flags, myf my_flags); extern CHARSET_INFO *my_charset_get_by_name(MY_CHARSET_LOADER *loader, const char *name, uint cs_flags, myf my_flags); extern my_bool resolve_charset(const char *cs_name, CHARSET_INFO *default_cs, CHARSET_INFO **cs, myf flags); extern my_bool resolve_collation(const char *cl_name, CHARSET_INFO *default_cl, CHARSET_INFO **cl, myf my_flags); extern void free_charsets(void); extern char *get_charsets_dir(char *buf); static inline my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2) { return (cs1->cs_name.str == cs2->cs_name.str); } extern my_bool init_compiled_charsets(myf flags); extern void add_compiled_collation(struct charset_info_st *cs); extern void add_compiled_extra_collation(struct charset_info_st *cs); extern size_t escape_string_for_mysql(CHARSET_INFO *charset_info, char *to, size_t to_length, const char *from, size_t length, my_bool *overflow); extern char *my_get_tty_password(const char *opt_message); #ifdef _WIN32 #define BACKSLASH_MBTAIL /* File system character set */ extern CHARSET_INFO *fs_character_set(void); #endif extern const char *my_default_csname(void); extern size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info, char *to, size_t to_length, const char *from, size_t length, my_bool *overflow); extern void thd_increment_bytes_sent(void *thd, size_t length); extern void thd_increment_bytes_received(void *thd, size_t length); extern void thd_increment_net_big_packet_count(void *thd, size_t length); #ifdef _WIN32 /* implemented in my_conio.c */ char* my_cgets(char *string, size_t clen, size_t* plen); #endif #include #ifdef HAVE_PSI_INTERFACE extern MYSQL_PLUGIN_IMPORT struct PSI_bootstrap *PSI_hook; extern void set_psi_server(PSI *psi); void my_init_mysys_psi_keys(void); #endif struct st_mysql_file; extern struct st_mysql_file *mysql_stdin; C_MODE_END #endif /* _my_sys_h */ mysql/server/my_list.h000064400000002742151027430560011060 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _list_h_ #define _list_h_ #ifdef __cplusplus extern "C" { #endif typedef struct st_list { struct st_list *prev,*next; void *data; } LIST; typedef int (*list_walk_action)(void *,void *); extern LIST *list_add(LIST *root,LIST *element); extern LIST *list_delete(LIST *root,LIST *element); extern LIST *list_cons(void *data,LIST *root); extern LIST *list_reverse(LIST *root); extern void list_free(LIST *root,unsigned int free_data); extern unsigned int list_length(LIST *); extern int list_walk(LIST *,list_walk_action action,unsigned char * argument); #define list_rest(a) ((a)->next) #define list_push(a,b) (a)=list_cons((b),(a)) #define list_pop(A) {LIST *old=(A); (A)=list_delete(old,old); my_free(old); } #ifdef __cplusplus } #endif #endif mysql/server/my_cmp.h000064400000001622151027430560010660 0ustar00/* Copyright (c) 2024, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #pragma once #ifdef __cplusplus extern "C" { #endif typedef int (*qsort_cmp)(const void *, const void *); typedef int (*qsort_cmp2)(void *param, const void *a, const void *b); #ifdef __cplusplus } #endif mysql/server/mysql.h000064400000115460151027430560010547 0ustar00/* Copyright (c) 2000, 2012, Oracle and/or its affiliates. Copyright (c) 2012, Monty Program Ab. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* This file defines the client API to MySQL and also the ABI of the dynamically linked libmysqlclient. The ABI should never be changed in a released product of MySQL, thus you need to take great care when changing the file. In case the file is changed so the ABI is broken, you must also update the SHARED_LIB_MAJOR_VERSION in cmake/mysql_version.cmake */ #ifndef _mysql_h #define _mysql_h #ifdef _AIX /* large-file support will break without this */ #include #endif #ifdef __cplusplus extern "C" { #endif #ifndef MY_GLOBAL_INCLUDED /* If not standard header */ #ifndef MYSQL_ABI_CHECK #include #endif #ifndef MYSQL_PLUGIN_INCLUDED typedef char my_bool; #endif #if !defined(_WIN32) #define STDCALL #else #define STDCALL __stdcall #endif #ifndef my_socket_defined #if defined (_WIN64) #define my_socket unsigned long long #elif defined (_WIN32) #define my_socket unsigned int #else typedef int my_socket; #endif /* _WIN64 */ #endif /* my_socket_defined */ #endif /* MY_GLOBAL_INCLUDED */ #include "mariadb_capi_rename.h" #include "mysql_version.h" #include "mysql_com.h" #include "mysql_time.h" #include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */ extern unsigned int mariadb_deinitialize_ssl; extern unsigned int mysql_port; extern char *mysql_unix_port; #define CLIENT_NET_READ_TIMEOUT (365*24*3600) /* Timeout on read */ #define CLIENT_NET_WRITE_TIMEOUT (365*24*3600) /* Timeout on write */ #define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG) #define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG) #define IS_BLOB(n) ((n) & BLOB_FLAG) /** Returns true if the value is a number which does not need quotes for the sql_lex.cc parser to parse correctly. */ #define IS_NUM(t) (((t) <= MYSQL_TYPE_INT24 && (t) != MYSQL_TYPE_TIMESTAMP) || (t) == MYSQL_TYPE_YEAR || (t) == MYSQL_TYPE_NEWDECIMAL) #define IS_LONGDATA(t) ((t) >= MYSQL_TYPE_TINY_BLOB && (t) <= MYSQL_TYPE_STRING) typedef struct st_mysql_const_lex_string MARIADB_CONST_STRING; typedef struct st_mysql_field { char *name; /* Name of column */ char *org_name; /* Original column name, if an alias */ char *table; /* Table of column if column was a field */ char *org_table; /* Org table name, if table was an alias */ char *db; /* Database for table */ char *catalog; /* Catalog for table */ char *def; /* Default value (set by mysql_list_fields) */ unsigned long length; /* Width of column (create length) */ unsigned long max_length; /* Max width for selected set */ unsigned int name_length; unsigned int org_name_length; unsigned int table_length; unsigned int org_table_length; unsigned int db_length; unsigned int catalog_length; unsigned int def_length; unsigned int flags; /* Div flags */ unsigned int decimals; /* Number of decimals in field */ unsigned int charsetnr; /* Character set */ enum enum_field_types type; /* Type of field. See mysql_com.h for types */ void *extension; } MYSQL_FIELD; typedef char **MYSQL_ROW; /* return data as array of strings */ typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */ #ifndef MY_GLOBAL_INCLUDED #if defined(NO_CLIENT_LONG_LONG) typedef unsigned long my_ulonglong; #elif defined (_WIN32) typedef unsigned __int64 my_ulonglong; #else typedef unsigned long long my_ulonglong; #endif #endif #include "typelib.h" #define MYSQL_COUNT_ERROR (~(my_ulonglong) 0) /* backward compatibility define - to be removed eventually */ #define ER_WARN_DATA_TRUNCATED WARN_DATA_TRUNCATED #define WARN_PLUGIN_DELETE_BUILTIN ER_PLUGIN_DELETE_BUILTIN #define ER_FK_DUP_NAME ER_DUP_CONSTRAINT_NAME #define ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED #define ER_PRIMARY_KEY_BASED_ON_VIRTUAL_COLUMN ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN #define ER_WRONG_FK_OPTION_FOR_VIRTUAL_COLUMN ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN #define ER_UNSUPPORTED_ACTION_ON_VIRTUAL_COLUMN ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN #define ER_UNSUPPORTED_ENGINE_FOR_VIRTUAL_COLUMNS ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS #define ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT ER_QUERY_RESULT_INCOMPLETE typedef struct st_mysql_rows { struct st_mysql_rows *next; /* list of rows */ MYSQL_ROW data; unsigned long length; } MYSQL_ROWS; typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */ #include "my_alloc.h" typedef struct embedded_query_result EMBEDDED_QUERY_RESULT; typedef struct st_mysql_data { MYSQL_ROWS *data; struct embedded_query_result *embedded_info; MEM_ROOT alloc; my_ulonglong rows; unsigned int fields; /* extra info for embedded library */ void *extension; } MYSQL_DATA; enum mysql_option { MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE, MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP, MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE, MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT, MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT, MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION, MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH, MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, MYSQL_PLUGIN_DIR, MYSQL_DEFAULT_AUTH, MYSQL_OPT_BIND, MYSQL_OPT_SSL_KEY, MYSQL_OPT_SSL_CERT, MYSQL_OPT_SSL_CA, MYSQL_OPT_SSL_CAPATH, MYSQL_OPT_SSL_CIPHER, MYSQL_OPT_SSL_CRL, MYSQL_OPT_SSL_CRLPATH, MYSQL_OPT_CONNECT_ATTR_RESET, MYSQL_OPT_CONNECT_ATTR_ADD, MYSQL_OPT_CONNECT_ATTR_DELETE, MYSQL_SERVER_PUBLIC_KEY, MYSQL_ENABLE_CLEARTEXT_PLUGIN, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, /* MariaDB options */ MYSQL_PROGRESS_CALLBACK=5999, MYSQL_OPT_NONBLOCK, MYSQL_OPT_USE_THREAD_SPECIFIC_MEMORY }; /** @todo remove the "extension", move st_mysql_options completely out of mysql.h */ struct st_mysql_options_extention; struct st_mysql_options { unsigned int connect_timeout, read_timeout, write_timeout; unsigned int port, protocol; unsigned long client_flag; char *host,*user,*password,*unix_socket,*db; struct st_dynamic_array *init_commands; char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name; char *ssl_key; /* PEM key file */ char *ssl_cert; /* PEM cert file */ char *ssl_ca; /* PEM CA file */ char *ssl_capath; /* PEM directory of CA-s? */ char *ssl_cipher; /* cipher to use */ char *shared_memory_base_name; unsigned long max_allowed_packet; my_bool use_ssl; /* if to use SSL or not */ my_bool compress,named_pipe; my_bool use_thread_specific_memory; my_bool unused2; my_bool unused3; my_bool unused4; enum mysql_option methods_to_use; char *client_ip; /* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */ my_bool secure_auth; /* 0 - never report, 1 - always report (default) */ my_bool report_data_truncation; /* function pointers for local infile support */ int (*local_infile_init)(void **, const char *, void *); int (*local_infile_read)(void *, char *, unsigned int); void (*local_infile_end)(void *); int (*local_infile_error)(void *, char *, unsigned int); void *local_infile_userdata; struct st_mysql_options_extention *extension; }; enum mysql_status { MYSQL_STATUS_READY, MYSQL_STATUS_GET_RESULT, MYSQL_STATUS_USE_RESULT, MYSQL_STATUS_STATEMENT_GET_RESULT }; enum mysql_protocol_type { MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET, MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY }; typedef struct character_set { unsigned int number; /* character set number */ unsigned int state; /* character set state */ const char *csname; /* collation name */ const char *name; /* character set name */ const char *comment; /* comment */ const char *dir; /* character set directory */ unsigned int mbminlen; /* min. length for multibyte strings */ unsigned int mbmaxlen; /* max. length for multibyte strings */ } MY_CHARSET_INFO; struct st_mysql_methods; struct st_mysql_stmt; typedef struct st_mysql { NET net; /* Communication parameters */ unsigned char *connector_fd; /* ConnectorFd for SSL */ char *host,*user,*passwd,*unix_socket,*server_version,*host_info; char *info, *db; const struct charset_info_st *charset; MEM_ROOT field_alloc; my_ulonglong affected_rows; my_ulonglong insert_id; /* id if insert on table with NEXTNR */ my_ulonglong extra_info; /* Not used */ unsigned long thread_id; /* Id for connection in server */ unsigned long packet_length; unsigned int port; unsigned long client_flag,server_capabilities; unsigned int protocol_version; unsigned int field_count; unsigned int server_status; unsigned int server_language; unsigned int warning_count; struct st_mysql_options options; enum mysql_status status; my_bool free_me; /* If free in mysql_close */ my_bool reconnect; /* set to 1 if automatic reconnect */ /* session-wide random string */ char scramble[SCRAMBLE_LENGTH+1]; my_bool auto_local_infile; void *unused2, *unused3, *unused4; MYSQL_FIELD *fields; LIST *stmts; /* list of all statements */ const struct st_mysql_methods *methods; void *thd; /* Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag from mysql_stmt_close if close had to cancel result set of this object. */ my_bool *unbuffered_fetch_owner; /* needed for embedded server - no net buffer to store the 'info' */ char *info_buffer; void *extension; } MYSQL; typedef struct st_mysql_res { my_ulonglong row_count; MYSQL_FIELD *fields; MYSQL_DATA *data; MYSQL_ROWS *data_cursor; unsigned long *lengths; /* column lengths of current row */ MYSQL *handle; /* for unbuffered reads */ const struct st_mysql_methods *methods; MYSQL_ROW row; /* If unbuffered read */ MYSQL_ROW current_row; /* buffer to current row */ MEM_ROOT field_alloc; unsigned int field_count, current_field; my_bool eof; /* Used by mysql_fetch_row */ /* mysql_stmt_close() had to cancel this result */ my_bool unbuffered_fetch_cancelled; void *extension; } MYSQL_RES; #if !defined(MYSQL_SERVICE_SQL) && !defined(MYSQL_CLIENT) #define MYSQL_CLIENT #endif typedef struct st_mysql_parameters { unsigned long *p_max_allowed_packet; unsigned long *p_net_buffer_length; void *extension; } MYSQL_PARAMETERS; /* Flag bits, the asynchronous methods return a combination of these ORed together to let the application know when to resume the suspended operation. */ /* Wait for data to be available on socket to read. mysql_get_socket_fd() will return socket descriptor. */ #define MYSQL_WAIT_READ 1 /* Wait for socket to be ready to write data. */ #define MYSQL_WAIT_WRITE 2 /* Wait for select() to mark exception on socket. */ #define MYSQL_WAIT_EXCEPT 4 /* Wait until timeout occurs. Value of timeout can be obtained from mysql_get_timeout_value(). */ #define MYSQL_WAIT_TIMEOUT 8 #if !defined(MYSQL_SERVICE_SQL) #define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet) #define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length) #endif /* Set up and bring down the server; to ensure that applications will work when linked against either the standard client library or the embedded server library, these functions should be called. */ int STDCALL mysql_server_init(int argc, char **argv, char **groups); void STDCALL mysql_server_end(void); /* mysql_server_init/end need to be called when using libmysqld or libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so you don't need to call it explicitly; but you need to call mysql_server_end() to free memory). The names are a bit misleading (mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general names which suit well whether you're using libmysqld or libmysqlclient. We intend to promote these aliases over the mysql_server* ones. */ #define mysql_library_init mysql_server_init #define mysql_library_end mysql_server_end MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void); /* Set up and bring down a thread; these function should be called for each thread in an application which opens at least one MySQL connection. All uses of the connection(s) should be between these function calls. */ my_bool STDCALL mysql_thread_init(void); void STDCALL mysql_thread_end(void); /* Functions to get information from the MYSQL and MYSQL_RES structures Should definitely be used if one uses shared libraries. */ my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res); unsigned int STDCALL mysql_num_fields(MYSQL_RES *res); my_bool STDCALL mysql_eof(MYSQL_RES *res); MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res, unsigned int fieldnr); MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res); MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res); MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res); int STDCALL mariadb_field_attr(MARIADB_CONST_STRING *attr, const MYSQL_FIELD *field, enum mariadb_field_attr_t type); unsigned int STDCALL mysql_field_count(MYSQL *mysql); my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql); my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql); unsigned int STDCALL mysql_errno(MYSQL *mysql); const char * STDCALL mysql_error(MYSQL *mysql); const char *STDCALL mysql_sqlstate(MYSQL *mysql); unsigned int STDCALL mysql_warning_count(MYSQL *mysql); const char * STDCALL mysql_info(MYSQL *mysql); unsigned long STDCALL mysql_thread_id(MYSQL *mysql); const char * STDCALL mysql_character_set_name(MYSQL *mysql); int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname); int STDCALL mysql_set_character_set_start(int *ret, MYSQL *mysql, const char *csname); int STDCALL mysql_set_character_set_cont(int *ret, MYSQL *mysql, int status); MYSQL * STDCALL mysql_init(MYSQL *mysql); my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key, const char *cert, const char *ca, const char *capath, const char *cipher); const char * STDCALL mysql_get_ssl_cipher(MYSQL *mysql); my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user, const char *passwd, const char *db); int STDCALL mysql_change_user_start(my_bool *ret, MYSQL *mysql, const char *user, const char *passwd, const char *db); int STDCALL mysql_change_user_cont(my_bool *ret, MYSQL *mysql, int status); MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); int STDCALL mysql_real_connect_start(MYSQL **ret, MYSQL *mysql, const char *host, const char *user, const char *passwd, const char *db, unsigned int port, const char *unix_socket, unsigned long clientflag); int STDCALL mysql_real_connect_cont(MYSQL **ret, MYSQL *mysql, int status); int STDCALL mysql_select_db(MYSQL *mysql, const char *db); int STDCALL mysql_select_db_start(int *ret, MYSQL *mysql, const char *db); int STDCALL mysql_select_db_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_query(MYSQL *mysql, const char *q); int STDCALL mysql_query_start(int *ret, MYSQL *mysql, const char *q); int STDCALL mysql_query_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_send_query(MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_send_query_start(int *ret, MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_send_query_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_real_query(MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_real_query_start(int *ret, MYSQL *mysql, const char *q, unsigned long length); int STDCALL mysql_real_query_cont(int *ret, MYSQL *mysql, int status); MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql); int STDCALL mysql_store_result_start(MYSQL_RES **ret, MYSQL *mysql); int STDCALL mysql_store_result_cont(MYSQL_RES **ret, MYSQL *mysql, int status); MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql); void STDCALL mysql_get_character_set_info(MYSQL *mysql, MY_CHARSET_INFO *charset); /* local infile support */ #define LOCAL_INFILE_ERROR_LEN 512 void mysql_set_local_infile_handler(MYSQL *mysql, int (*local_infile_init)(void **, const char *, void *), int (*local_infile_read)(void *, char *, unsigned int), void (*local_infile_end)(void *), int (*local_infile_error)(void *, char*, unsigned int), void *); void mysql_set_local_infile_default(MYSQL *mysql); int STDCALL mysql_shutdown(MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); int STDCALL mysql_shutdown_start(int *ret, MYSQL *mysql, enum mysql_enum_shutdown_level shutdown_level); int STDCALL mysql_shutdown_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_dump_debug_info(MYSQL *mysql); int STDCALL mysql_dump_debug_info_start(int *ret, MYSQL *mysql); int STDCALL mysql_dump_debug_info_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_refresh(MYSQL *mysql, unsigned int refresh_options); int STDCALL mysql_refresh_start(int *ret, MYSQL *mysql, unsigned int refresh_options); int STDCALL mysql_refresh_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid); int STDCALL mysql_kill_start(int *ret, MYSQL *mysql, unsigned long pid); int STDCALL mysql_kill_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_set_server_option(MYSQL *mysql, enum enum_mysql_set_option option); int STDCALL mysql_set_server_option_start(int *ret, MYSQL *mysql, enum enum_mysql_set_option option); int STDCALL mysql_set_server_option_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_ping(MYSQL *mysql); int STDCALL mysql_ping_start(int *ret, MYSQL *mysql); int STDCALL mysql_ping_cont(int *ret, MYSQL *mysql, int status); const char * STDCALL mysql_stat(MYSQL *mysql); int STDCALL mysql_stat_start(const char **ret, MYSQL *mysql); int STDCALL mysql_stat_cont(const char **ret, MYSQL *mysql, int status); const char * STDCALL mysql_get_server_info(MYSQL *mysql); const char * STDCALL mysql_get_server_name(MYSQL *mysql); const char * STDCALL mysql_get_client_info(void); unsigned long STDCALL mysql_get_client_version(void); const char * STDCALL mysql_get_host_info(MYSQL *mysql); unsigned long STDCALL mysql_get_server_version(MYSQL *mysql); unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql); MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild); int STDCALL mysql_list_dbs_start(MYSQL_RES **ret, MYSQL *mysql, const char *wild); int STDCALL mysql_list_dbs_cont(MYSQL_RES **ret, MYSQL *mysql, int status); MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild); int STDCALL mysql_list_tables_start(MYSQL_RES **ret, MYSQL *mysql, const char *wild); int STDCALL mysql_list_tables_cont(MYSQL_RES **ret, MYSQL *mysql, int status); MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql); int STDCALL mysql_list_processes_start(MYSQL_RES **ret, MYSQL *mysql); int STDCALL mysql_list_processes_cont(MYSQL_RES **ret, MYSQL *mysql, int status); int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg); int STDCALL mysql_options4(MYSQL *mysql,enum mysql_option option, const void *arg1, const void *arg2); void STDCALL mysql_free_result(MYSQL_RES *result); int STDCALL mysql_free_result_start(MYSQL_RES *result); int STDCALL mysql_free_result_cont(MYSQL_RES *result, int status); void STDCALL mysql_data_seek(MYSQL_RES *result, my_ulonglong offset); MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result, MYSQL_ROW_OFFSET offset); MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result, MYSQL_FIELD_OFFSET offset); MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); int STDCALL mysql_fetch_row_start(MYSQL_ROW *ret, MYSQL_RES *result); int STDCALL mysql_fetch_row_cont(MYSQL_ROW *ret, MYSQL_RES *result, int status); unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result); MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result); MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table, const char *wild); int STDCALL mysql_list_fields_start(MYSQL_RES **ret, MYSQL *mysql, const char *table, const char *wild); int STDCALL mysql_list_fields_cont(MYSQL_RES **ret, MYSQL *mysql, int status); unsigned long STDCALL mysql_escape_string(char *to,const char *from, unsigned long from_length); unsigned long STDCALL mysql_hex_string(char *to,const char *from, unsigned long from_length); unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql, char *to,const char *from, unsigned long length); void STDCALL mysql_debug(const char *debug); void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name); unsigned int STDCALL mysql_thread_safe(void); my_bool STDCALL mysql_embedded(void); my_bool STDCALL mariadb_connection(MYSQL *mysql); my_bool STDCALL mysql_read_query_result(MYSQL *mysql); int STDCALL mysql_read_query_result_start(my_bool *ret, MYSQL *mysql); int STDCALL mysql_read_query_result_cont(my_bool *ret, MYSQL *mysql, int status); /* The following definitions are added for the enhanced client-server protocol */ /* statement state */ enum enum_mysql_stmt_state { MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE, MYSQL_STMT_FETCH_DONE }; /* This structure is used to define bind information, and internally by the client library. Public members with their descriptions are listed below (conventionally `On input' refers to the binds given to mysql_stmt_bind_param, `On output' refers to the binds given to mysql_stmt_bind_result): buffer_type - One of the MYSQL_* types, used to describe the host language type of buffer. On output: if column type is different from buffer_type, column value is automatically converted to buffer_type before it is stored in the buffer. buffer - On input: points to the buffer with input data. On output: points to the buffer capable to store output data. The type of memory pointed by buffer must correspond to buffer_type. See the correspondence table in the comment to mysql_stmt_bind_param. The two above members are mandatory for any kind of bind. buffer_length - the length of the buffer. You don't have to set it for any fixed length buffer: float, double, int, etc. It must be set however for variable-length types, such as BLOBs or STRINGs. length - On input: in case when lengths of input values are different for each execute, you can set this to point at a variable containing value length. This way the value length can be different in each execute. If length is not NULL, buffer_length is not used. Note, length can even point at buffer_length if you keep bind structures around while fetching: this way you can change buffer_length before each execution, everything will work ok. On output: if length is set, mysql_stmt_fetch will write column length into it. is_null - On input: points to a boolean variable that should be set to TRUE for NULL values. This member is useful only if your data may be NULL in some but not all cases. If your data is never NULL, is_null should be set to 0. If your data is always NULL, set buffer_type to MYSQL_TYPE_NULL, and is_null will not be used. is_unsigned - On input: used to signify that values provided for one of numeric types are unsigned. On output describes signedness of the output buffer. If, taking into account is_unsigned flag, column data is out of range of the output buffer, data for this column is regarded truncated. Note that this has no correspondence to the sign of result set column, if you need to find it out use mysql_stmt_result_metadata. error - where to write a truncation error if it is present. possible error value is: 0 no truncation 1 value is out of range or buffer is too small Please note that MYSQL_BIND also has internals members. */ typedef struct st_mysql_bind { unsigned long *length; /* output length pointer */ my_bool *is_null; /* Pointer to null indicator */ void *buffer; /* buffer to get/put data */ /* set this if you want to track data truncations happened during fetch */ my_bool *error; unsigned char *row_ptr; /* for the current data position */ void (*store_param_func)(NET *net, struct st_mysql_bind *param); void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *, unsigned char **row); void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *, unsigned char **row); /* output buffer length, must be set when fetching str/binary */ unsigned long buffer_length; unsigned long offset; /* offset position for char/binary fetch */ unsigned long length_value; /* Used if length is 0 */ unsigned int param_number; /* For null count and error messages */ unsigned int pack_length; /* Internal length for packed data */ enum enum_field_types buffer_type; /* buffer type */ my_bool error_value; /* used if error is 0 */ my_bool is_unsigned; /* set if integer type is unsigned */ my_bool long_data_used; /* If used with mysql_send_long_data */ my_bool is_null_value; /* Used if is_null is 0 */ void *extension; } MYSQL_BIND; struct st_mysql_stmt_extension; /* statement handler */ typedef struct st_mysql_stmt { MEM_ROOT mem_root; /* root allocations */ LIST list; /* list to keep track of all stmts */ MYSQL *mysql; /* connection handle */ MYSQL_BIND *params; /* input parameters */ MYSQL_BIND *bind; /* output parameters */ MYSQL_FIELD *fields; /* result set metadata */ MYSQL_DATA result; /* cached result set */ MYSQL_ROWS *data_cursor; /* current row in cached result */ /* mysql_stmt_fetch() calls this function to fetch one row (it's different for buffered, unbuffered and cursor fetch). */ int (*read_row_func)(struct st_mysql_stmt *stmt, unsigned char **row); /* copy of mysql->affected_rows after statement execution */ my_ulonglong affected_rows; my_ulonglong insert_id; /* copy of mysql->insert_id */ unsigned long stmt_id; /* Id for prepared statement */ unsigned long flags; /* i.e. type of cursor to open */ unsigned long prefetch_rows; /* number of rows per one COM_FETCH */ /* Copied from mysql->server_status after execute/fetch to know server-side cursor status for this statement. */ unsigned int server_status; unsigned int last_errno; /* error code */ unsigned int param_count; /* input parameter count */ unsigned int field_count; /* number of columns in result set */ enum enum_mysql_stmt_state state; /* statement state */ char last_error[MYSQL_ERRMSG_SIZE]; /* error message */ char sqlstate[SQLSTATE_LENGTH+1]; /* Types of input parameters should be sent to server */ my_bool send_types_to_server; my_bool bind_param_done; /* input buffers were supplied */ unsigned char bind_result_done; /* output buffers were supplied */ /* mysql_stmt_close() had to cancel this result */ my_bool unbuffered_fetch_cancelled; /* Is set to true if we need to calculate field->max_length for metadata fields when doing mysql_stmt_store_result. */ my_bool update_max_length; struct st_mysql_stmt_extension *extension; } MYSQL_STMT; enum enum_stmt_attr_type { /* When doing mysql_stmt_store_result calculate max_length attribute of statement metadata. This is to be consistent with the old API, where this was done automatically. In the new API we do that only by request because it slows down mysql_stmt_store_result sufficiently. */ STMT_ATTR_UPDATE_MAX_LENGTH, /* unsigned long with combination of cursor flags (read only, for update, etc) */ STMT_ATTR_CURSOR_TYPE, /* Amount of rows to retrieve from server per one fetch if using cursors. Accepts unsigned long attribute in the range 1 - ulong_max */ STMT_ATTR_PREFETCH_ROWS }; MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql); int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query, unsigned long length); int STDCALL mysql_stmt_prepare_start(int *ret, MYSQL_STMT *stmt, const char *query, unsigned long length); int STDCALL mysql_stmt_prepare_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt); int STDCALL mysql_stmt_execute_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_execute_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt); int STDCALL mysql_stmt_fetch_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_fetch_cont(int *ret, MYSQL_STMT *stmt, int status); int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind_arg, unsigned int column, unsigned long offset); int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt); int STDCALL mysql_stmt_store_result_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_store_result_cont(int *ret, MYSQL_STMT *stmt, int status); unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt); my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, const void *attr); my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt, enum enum_stmt_attr_type attr_type, void *attr); my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd); my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd); my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt); int STDCALL mysql_stmt_close_start(my_bool *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_close_cont(my_bool *ret, MYSQL_STMT * stmt, int status); my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt); int STDCALL mysql_stmt_reset_start(my_bool *ret, MYSQL_STMT * stmt); int STDCALL mysql_stmt_reset_cont(my_bool *ret, MYSQL_STMT *stmt, int status); my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt); int STDCALL mysql_stmt_free_result_start(my_bool *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_free_result_cont(my_bool *ret, MYSQL_STMT *stmt, int status); my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long length); int STDCALL mysql_stmt_send_long_data_start(my_bool *ret, MYSQL_STMT *stmt, unsigned int param_number, const char *data, unsigned long len); int STDCALL mysql_stmt_send_long_data_cont(my_bool *ret, MYSQL_STMT *stmt, int status); MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt); MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt); unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt); const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt); const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt); MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt, MYSQL_ROW_OFFSET offset); MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt); void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset); my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt); my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt); my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt); unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt); my_bool STDCALL mysql_commit(MYSQL * mysql); int STDCALL mysql_commit_start(my_bool *ret, MYSQL * mysql); int STDCALL mysql_commit_cont(my_bool *ret, MYSQL * mysql, int status); my_bool STDCALL mysql_rollback(MYSQL * mysql); int STDCALL mysql_rollback_start(my_bool *ret, MYSQL * mysql); int STDCALL mysql_rollback_cont(my_bool *ret, MYSQL * mysql, int status); my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode); int STDCALL mysql_autocommit_start(my_bool *ret, MYSQL * mysql, my_bool auto_mode); int STDCALL mysql_autocommit_cont(my_bool *ret, MYSQL * mysql, int status); my_bool STDCALL mysql_more_results(MYSQL *mysql); int STDCALL mysql_next_result(MYSQL *mysql); int STDCALL mysql_next_result_start(int *ret, MYSQL *mysql); int STDCALL mysql_next_result_cont(int *ret, MYSQL *mysql, int status); int STDCALL mysql_stmt_next_result(MYSQL_STMT *stmt); int STDCALL mysql_stmt_next_result_start(int *ret, MYSQL_STMT *stmt); int STDCALL mysql_stmt_next_result_cont(int *ret, MYSQL_STMT *stmt, int status); void STDCALL mysql_close_slow_part(MYSQL *mysql); void STDCALL mysql_close(MYSQL *sock); int STDCALL mysql_close_start(MYSQL *sock); int STDCALL mysql_close_cont(MYSQL *sock, int status); my_socket STDCALL mysql_get_socket(const MYSQL *mysql); unsigned int STDCALL mysql_get_timeout_value(const MYSQL *mysql); unsigned int STDCALL mysql_get_timeout_value_ms(const MYSQL *mysql); /******************************************************************** mysql_net_ functions - low-level API to MySQL protocol *********************************************************************/ unsigned long STDCALL mysql_net_read_packet(MYSQL *mysql); unsigned long STDCALL mysql_net_field_length(unsigned char **packet); /* status return codes */ #define MYSQL_NO_DATA 100 #define MYSQL_DATA_TRUNCATED 101 #define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT) #ifdef USE_OLD_FUNCTIONS MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host, const char *user, const char *passwd); int STDCALL mysql_create_db(MYSQL *mysql, const char *DB); int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB); #endif #define HAVE_MYSQL_REAL_CONNECT #ifdef __cplusplus } #endif #endif /* _mysql_h */ mysql/server/mysql_com.h000064400000074223151027430560011406 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. Copyright (c) 2010, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* ** Common definition between mysql server & client */ #ifndef _mysql_com_h #define _mysql_com_h #include "my_decimal_limits.h" #define HOSTNAME_LENGTH 255 #define HOSTNAME_LENGTH_STR STRINGIFY_ARG(HOSTNAME_LENGTH) #define SYSTEM_CHARSET_MBMAXLEN 3 #define NAME_CHAR_LEN 64 /* Field/table name length */ #define USERNAME_CHAR_LENGTH 128 #define USERNAME_CHAR_LENGTH_STR STRINGIFY_ARG(USERNAME_CHAR_LENGTH) #define NAME_LEN (NAME_CHAR_LEN*SYSTEM_CHARSET_MBMAXLEN) #define USERNAME_LENGTH (USERNAME_CHAR_LENGTH*SYSTEM_CHARSET_MBMAXLEN) #define DEFINER_CHAR_LENGTH (USERNAME_CHAR_LENGTH + HOSTNAME_LENGTH + 1) #define DEFINER_LENGTH (USERNAME_LENGTH + HOSTNAME_LENGTH + 1) #define MYSQL_AUTODETECT_CHARSET_NAME "auto" #define MYSQL50_TABLE_NAME_PREFIX "#mysql50#" #define MYSQL50_TABLE_NAME_PREFIX_LENGTH (sizeof(MYSQL50_TABLE_NAME_PREFIX)-1) #define SAFE_NAME_LEN (NAME_LEN + MYSQL50_TABLE_NAME_PREFIX_LENGTH) /* MDEV-4088 MySQL (and MariaDB 5.x before the fix) was using the first character of the server version string (as sent in the first handshake protocol packet) to decide on the replication event formats. And for 10.x the first character is "1", which the slave thought comes from some ancient 1.x version (ignoring the fact that the first ever MySQL version was 3.x). To support replication to these old clients, we fake the version in the first handshake protocol packet to start from "5.5.5-" (for example, it might be "5.5.5-10.0.1-MariaDB-debug-log". On the client side we remove this fake version prefix to restore the correct server version. The version "5.5.5" did not support pluggable authentication, so any version starting from "5.5.5-" and claiming to support pluggable auth, must be using this fake prefix. */ /* this version must be the one that *does not* support pluggable auth */ #define RPL_VERSION_HACK "5.5.5-" #define SERVER_VERSION_LENGTH 60 #define SQLSTATE_LENGTH 5 #define LIST_PROCESS_HOST_LEN 64 /* Maximum length of comments */ #define TABLE_COMMENT_INLINE_MAXLEN 180 /* pre 5.5: 60 characters */ #define TABLE_COMMENT_MAXLEN 2048 #define COLUMN_COMMENT_MAXLEN 1024 #define INDEX_COMMENT_MAXLEN 1024 #define TABLE_PARTITION_COMMENT_MAXLEN 1024 #define DATABASE_COMMENT_MAXLEN 1024 /* Maximum length of protocol packet. OK packet length limit also restricted to this value as any length greater than this value will have first byte of OK packet to be 254 thus does not provide a means to identify if this is OK or EOF packet. */ #define MAX_PACKET_LENGTH (256L*256L*256L-1) /* USER_HOST_BUFF_SIZE -- length of string buffer, that is enough to contain username and hostname parts of the user identifier with trailing zero in MySQL standard format: user_name_part@host_name_part\0 */ #define USER_HOST_BUFF_SIZE HOSTNAME_LENGTH + USERNAME_LENGTH + 2 #define LOCAL_HOST "localhost" #define LOCAL_HOST_NAMEDPIPE "." #if defined(_WIN32) && !defined( _CUSTOMCONFIG_) #define MYSQL_NAMEDPIPE "MySQL" #define MYSQL_SERVICENAME "MySQL" #endif /* You should add new commands to the end of this list, otherwise old servers won't be able to handle them as 'unsupported'. */ enum enum_server_command { COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE, COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_DAEMON, COM_UNIMPLEMENTED, /* COM_BINLOG_DUMP_GTID in MySQL */ COM_RESET_CONNECTION, /* don't forget to update const char *command_name[] in sql_parse.cc */ COM_MDB_GAP_BEG, COM_MDB_GAP_END=249, COM_STMT_BULK_EXECUTE=250, COM_SLAVE_WORKER=251, COM_SLAVE_IO=252, COM_SLAVE_SQL=253, COM_RESERVED_1=254, /* Old COM_MULTI, now removed */ /* Must be last */ COM_END=255 }; /* Bulk PS protocol indicator value: */ enum enum_indicator_type { STMT_INDICATOR_NONE= 0, STMT_INDICATOR_NULL, STMT_INDICATOR_DEFAULT, STMT_INDICATOR_IGNORE }; /* bulk PS flags */ #define STMT_BULK_FLAG_CLIENT_SEND_TYPES 128 #define STMT_BULK_FLAG_INSERT_ID_REQUEST 64 /* sql type stored in .frm files for virtual fields */ #define MYSQL_TYPE_VIRTUAL 245 /* Length of random string sent by server on handshake; this is also length of obfuscated password, received from client */ #define SCRAMBLE_LENGTH 20 #define SCRAMBLE_LENGTH_323 8 /* length of password stored in the db: new passwords are preceded with '*' */ #define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1) #define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2) #define NOT_NULL_FLAG 1U /* Field can't be NULL */ #define PRI_KEY_FLAG 2U /* Field is part of a primary key */ #define UNIQUE_KEY_FLAG 4U /* Field is part of a unique key */ #define MULTIPLE_KEY_FLAG 8U /* Field is part of a key */ #define BLOB_FLAG 16U /* Field is a blob */ #define UNSIGNED_FLAG 32U /* Field is unsigned */ #define ZEROFILL_FLAG 64U /* Field is zerofill */ #define BINARY_FLAG 128U /* Field is binary */ /* The following are only sent to new clients */ #define ENUM_FLAG 256U /* field is an enum */ #define AUTO_INCREMENT_FLAG 512U /* field is a autoincrement field */ #define TIMESTAMP_FLAG 1024U /* Field is a timestamp */ #define SET_FLAG 2048U /* field is a set */ #define NO_DEFAULT_VALUE_FLAG 4096U /* Field doesn't have default value */ #define ON_UPDATE_NOW_FLAG 8192U /* Field is set to NOW on UPDATE */ #define NUM_FLAG 32768U /* Field is num (for clients) */ #define PART_KEY_FLAG 16384U /* Intern; Part of some key */ #define GROUP_FLAG 32768U /* Intern: Group field */ #define BINCMP_FLAG 131072U /* Intern: Used by sql_yacc */ #define GET_FIXED_FIELDS_FLAG (1U << 18) /* Used to get fields in item tree */ #define FIELD_IN_PART_FUNC_FLAG (1U << 19)/* Field part of partition func */ #define PART_INDIRECT_KEY_FLAG (1U << 20) /** Intern: Field in TABLE object for new version of altered table, which participates in a newly added index. */ #define FIELD_IN_ADD_INDEX (1U << 20) #define FIELD_IS_RENAMED (1U << 21) /* Intern: Field is being renamed */ #define FIELD_FLAGS_STORAGE_MEDIA 22 /* Field storage media, bit 22-23 */ #define FIELD_FLAGS_STORAGE_MEDIA_MASK (3U << FIELD_FLAGS_STORAGE_MEDIA) #define FIELD_FLAGS_COLUMN_FORMAT 24 /* Field column format, bit 24-25 */ #define FIELD_FLAGS_COLUMN_FORMAT_MASK (3U << FIELD_FLAGS_COLUMN_FORMAT) #define FIELD_IS_DROPPED (1U << 26) /* Intern: Field is being dropped */ #define VERS_ROW_START (1 << 27) /* autogenerated column declared with `generated always as row start` (see II.a SQL Standard) */ #define VERS_ROW_END (1 << 28) /* autogenerated column declared with `generated always as row end` (see II.a SQL Standard).*/ #define VERS_SYSTEM_FIELD (VERS_ROW_START | VERS_ROW_END) #define VERS_UPDATE_UNVERSIONED_FLAG (1 << 29) /* column that doesn't support system versioning when table itself supports it*/ #define LONG_UNIQUE_HASH_FIELD (1<< 30) /* This field will store hash for unique column */ #define FIELD_PART_OF_TMP_UNIQUE (1<< 31) /* part of an unique constrain for a tmporary table*/ #define REFRESH_GRANT (1ULL << 0) /* Refresh grant tables */ #define REFRESH_LOG (1ULL << 1) /* Start on new log file */ #define REFRESH_TABLES (1ULL << 2) /* close all tables */ #define REFRESH_HOSTS (1ULL << 3) /* Flush host cache */ #define REFRESH_STATUS (1ULL << 4) /* Flush status variables */ #define REFRESH_THREADS (1ULL << 5) /* Flush thread cache */ #define REFRESH_SLAVE (1ULL << 6) /* Reset master info and restart slave thread */ #define REFRESH_MASTER (1ULL << 7) /* Remove all bin logs in the index and truncate the index */ /* The following can't be set with mysql_refresh() */ #define REFRESH_ERROR_LOG (1ULL << 8) /* Rotate only the error log */ #define REFRESH_ENGINE_LOG (1ULL << 9) /* Flush all storage engine logs */ #define REFRESH_BINARY_LOG (1ULL << 10) /* Flush the binary log */ #define REFRESH_RELAY_LOG (1ULL << 11) /* Flush the relay log */ #define REFRESH_GENERAL_LOG (1ULL << 12) /* Flush the general log */ #define REFRESH_SLOW_LOG (1ULL << 13) /* Flush the slow query log */ #define REFRESH_READ_LOCK (1ULL << 14) /* Lock tables for read */ #define REFRESH_CHECKPOINT (1ULL << 15) /* With REFRESH_READ_LOCK: block checkpoints too */ #define REFRESH_QUERY_CACHE (1ULL << 16) /* clear the query cache */ #define REFRESH_QUERY_CACHE_FREE (1ULL << 17) /* pack query cache */ #define REFRESH_DES_KEY_FILE (1ULL << 18) #define REFRESH_USER_RESOURCES (1ULL << 19) #define REFRESH_FOR_EXPORT (1ULL << 20) /* FLUSH TABLES ... FOR EXPORT */ #define REFRESH_SSL (1ULL << 21) #define REFRESH_GENERIC (1ULL << 30) #define REFRESH_FAST (1ULL << 31) /* Intern flag */ #define CLIENT_LONG_PASSWORD 0 /* obsolete flag */ #define CLIENT_MYSQL 1ULL /* mysql/old mariadb server/client */ #define CLIENT_FOUND_ROWS 2ULL /* Found instead of affected rows */ #define CLIENT_LONG_FLAG 4ULL /* Get all column flags */ #define CLIENT_CONNECT_WITH_DB 8ULL /* One can specify db on connect */ #define CLIENT_NO_SCHEMA 16ULL /* Don't allow database.table.column */ #define CLIENT_COMPRESS 32ULL /* Can use compression protocol */ #define CLIENT_ODBC 64ULL /* Odbc client */ #define CLIENT_LOCAL_FILES 128ULL /* Can use LOAD DATA LOCAL */ #define CLIENT_IGNORE_SPACE 256ULL /* Ignore spaces before '(' */ #define CLIENT_PROTOCOL_41 512ULL /* New 4.1 protocol */ #define CLIENT_INTERACTIVE 1024ULL /* This is an interactive client */ #define CLIENT_SSL 2048ULL /* Switch to SSL after handshake */ #define CLIENT_IGNORE_SIGPIPE 4096ULL /* IGNORE sigpipes */ #define CLIENT_TRANSACTIONS 8192ULL /* Client knows about transactions */ #define CLIENT_RESERVED 16384ULL /* Old flag for 4.1 protocol */ #define CLIENT_SECURE_CONNECTION 32768ULL /* New 4.1 authentication */ #define CLIENT_MULTI_STATEMENTS (1ULL << 16) /* Enable/disable multi-stmt support */ #define CLIENT_MULTI_RESULTS (1ULL << 17) /* Enable/disable multi-results */ #define CLIENT_PS_MULTI_RESULTS (1ULL << 18) /* Multi-results in PS-protocol */ #define CLIENT_PLUGIN_AUTH (1ULL << 19) /* Client supports plugin authentication */ #define CLIENT_CONNECT_ATTRS (1ULL << 20) /* Client supports connection attributes */ /* Enable authentication response packet to be larger than 255 bytes. */ #define CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA (1ULL << 21) /* Don't close the connection for a connection with expired password. */ #define CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS (1ULL << 22) /** Capable of handling server state change information. Its a hint to the server to include the state change information in Ok packet. */ #define CLIENT_SESSION_TRACK (1ULL << 23) /* Client no longer needs EOF packet */ #define CLIENT_DEPRECATE_EOF (1ULL << 24) #define CLIENT_PROGRESS_OBSOLETE (1ULL << 29) #define CLIENT_SSL_VERIFY_SERVER_CERT_OBSOLETE (1ULL << 30) /* It used to be that if mysql_real_connect() failed, it would delete any options set by the client, unless the CLIENT_REMEMBER_OPTIONS flag was given. That behaviour does not appear very useful, and it seems unlikely that any applications would actually depend on this. So from MariaDB 5.5 we always preserve any options set in case of failed connect, and this option is effectively always set. */ #define CLIENT_REMEMBER_OPTIONS (1ULL << 31) /* MariaDB extended capability flags */ #define MARIADB_CLIENT_FLAGS_MASK 0xffffffff00000000ULL /* Client support progress indicator */ #define MARIADB_CLIENT_PROGRESS (1ULL << 32) /* Old COM_MULTI experiment (functionality removed).*/ #define MARIADB_CLIENT_RESERVED_1 (1ULL << 33) /* support of array binding */ #define MARIADB_CLIENT_STMT_BULK_OPERATIONS (1ULL << 34) /* support of extended metadata (e.g. type/format information) */ #define MARIADB_CLIENT_EXTENDED_METADATA (1ULL << 35) /* Do not resend metadata for prepared statements, since 10.6*/ #define MARIADB_CLIENT_CACHE_METADATA (1ULL << 36) #ifdef HAVE_COMPRESS #define CAN_CLIENT_COMPRESS CLIENT_COMPRESS #else #define CAN_CLIENT_COMPRESS 0 #endif /* Gather all possible capabilities (flags) supported by the server MARIADB_* flags supported only by MariaDB connector(s). */ #define CLIENT_ALL_FLAGS (\ CLIENT_FOUND_ROWS | \ CLIENT_LONG_FLAG | \ CLIENT_CONNECT_WITH_DB | \ CLIENT_NO_SCHEMA | \ CLIENT_COMPRESS | \ CLIENT_ODBC | \ CLIENT_LOCAL_FILES | \ CLIENT_IGNORE_SPACE | \ CLIENT_PROTOCOL_41 | \ CLIENT_INTERACTIVE | \ CLIENT_SSL | \ CLIENT_IGNORE_SIGPIPE | \ CLIENT_TRANSACTIONS | \ CLIENT_RESERVED | \ CLIENT_SECURE_CONNECTION | \ CLIENT_MULTI_STATEMENTS | \ CLIENT_MULTI_RESULTS | \ CLIENT_PS_MULTI_RESULTS | \ CLIENT_REMEMBER_OPTIONS | \ MARIADB_CLIENT_PROGRESS | \ CLIENT_PLUGIN_AUTH | \ CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | \ CLIENT_SESSION_TRACK |\ CLIENT_DEPRECATE_EOF |\ CLIENT_CONNECT_ATTRS |\ MARIADB_CLIENT_STMT_BULK_OPERATIONS |\ MARIADB_CLIENT_EXTENDED_METADATA|\ MARIADB_CLIENT_CACHE_METADATA |\ CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS) /* Switch off the flags that are optional and depending on build flags If any of the optional flags is supported by the build it will be switched on before sending to the client during the connection handshake. */ #define CLIENT_BASIC_FLAGS ((CLIENT_ALL_FLAGS & ~CLIENT_SSL) \ & ~CLIENT_COMPRESS) enum mariadb_field_attr_t { MARIADB_FIELD_ATTR_DATA_TYPE_NAME= 0, MARIADB_FIELD_ATTR_FORMAT_NAME= 1 }; #define MARIADB_FIELD_ATTR_LAST MARIADB_FIELD_ATTR_FORMAT_NAME /** Is raised when a multi-statement transaction has been started, either explicitly, by means of BEGIN or COMMIT AND CHAIN, or implicitly, by the first transactional statement, when autocommit=off. */ #define SERVER_STATUS_IN_TRANS 1U #define SERVER_STATUS_AUTOCOMMIT 2U /* Server in auto_commit mode */ #define SERVER_MORE_RESULTS_EXISTS 8U /* Multi query - next query exists */ #define SERVER_QUERY_NO_GOOD_INDEX_USED 16U #define SERVER_QUERY_NO_INDEX_USED 32U /** The server was able to fulfill the clients request and opened a read-only non-scrollable cursor for a query. This flag comes in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. */ #define SERVER_STATUS_CURSOR_EXISTS 64U /** This flag is sent when a read-only cursor is exhausted, in reply to COM_STMT_FETCH command. */ #define SERVER_STATUS_LAST_ROW_SENT 128U #define SERVER_STATUS_DB_DROPPED 256U /* A database was dropped */ #define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512U /** Sent to the client if after a prepared statement reprepare we discovered that the new statement returns a different number of result set columns. */ #define SERVER_STATUS_METADATA_CHANGED 1024U #define SERVER_QUERY_WAS_SLOW 2048U /** To mark ResultSet containing output parameter values. */ #define SERVER_PS_OUT_PARAMS 4096U /** Set at the same time as SERVER_STATUS_IN_TRANS if the started multi-statement transaction is a read-only transaction. Cleared when the transaction commits or aborts. Since this flag is sent to clients in OK and EOF packets, the flag indicates the transaction status at the end of command execution. */ #define SERVER_STATUS_IN_TRANS_READONLY 8192U /** This status flag, when on, implies that one of the state information has changed on the server because of the execution of the last statement. */ #define SERVER_SESSION_STATE_CHANGED 16384U #define SERVER_STATUS_ANSI_QUOTES 32768U /** Server status flags that must be cleared when starting execution of a new SQL statement. Flags from this set are only added to the current server status by the execution engine, but never removed -- the execution engine expects them to disappear automagically by the next command. */ #define SERVER_STATUS_CLEAR_SET (SERVER_QUERY_NO_GOOD_INDEX_USED| \ SERVER_QUERY_NO_INDEX_USED|\ SERVER_MORE_RESULTS_EXISTS|\ SERVER_STATUS_METADATA_CHANGED |\ SERVER_QUERY_WAS_SLOW |\ SERVER_STATUS_DB_DROPPED |\ SERVER_STATUS_CURSOR_EXISTS|\ SERVER_STATUS_LAST_ROW_SENT|\ SERVER_SESSION_STATE_CHANGED) #define MYSQL_ERRMSG_SIZE 512 #define NET_READ_TIMEOUT 30 /* Timeout on read */ #define NET_WRITE_TIMEOUT 60 /* Timeout on write */ #define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */ struct st_vio; /* Only C */ typedef struct st_vio Vio; #define MAX_TINYINT_WIDTH 3 /* Max width for a TINY w.o. sign */ #define MAX_SMALLINT_WIDTH 5 /* Max width for a SHORT w.o. sign */ #define MAX_MEDIUMINT_WIDTH 8 /* Max width for a INT24 w.o. sign */ #define MAX_INT_WIDTH 10 /* Max width for a LONG w.o. sign */ #define MAX_BIGINT_WIDTH 20 /* Max width for a LONGLONG */ #define MAX_CHAR_WIDTH 255 /* Max length for a CHAR column */ #define MAX_BLOB_WIDTH 16777216 /* Default width for blob */ typedef struct st_net { #if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY) Vio *vio; unsigned char *buff,*buff_end,*write_pos,*read_pos; my_socket fd; /* For Perl DBI/dbd */ /* The following variable is set if we are doing several queries in one command ( as in LOAD TABLE ... FROM MASTER ), and do not want to confuse the client with OK at the wrong time */ unsigned long remain_in_buf,length, buf_length, where_b; unsigned long max_packet,max_packet_size; unsigned int pkt_nr,compress_pkt_nr; unsigned int write_timeout, read_timeout, retry_count; int fcntl; unsigned int *return_status; unsigned char reading_or_writing; char save_char; char net_skip_rest_factor; my_bool thread_specific_malloc; unsigned char compress; my_bool pkt_nr_can_be_reset; my_bool using_proxy_protocol; /* Pointer to query object in query cache, do not equal NULL (0) for queries in cache that have not stored its results yet */ #endif void *thd; /* Used by MariaDB server to avoid calling current_thd */ unsigned int last_errno; unsigned char error; my_bool unused4; /* Please remove with the next incompatible ABI change. */ my_bool unused5; /* Please remove with the next incompatible ABI change. */ /** Client library error message buffer. Actually belongs to struct MYSQL. */ char last_error[MYSQL_ERRMSG_SIZE]; /** Client library sqlstate buffer. Set along with the error message. */ char sqlstate[SQLSTATE_LENGTH+1]; void *extension; } NET; #define packet_error ~0UL enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY, MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG, MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE, MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP, MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24, MYSQL_TYPE_DATE, MYSQL_TYPE_TIME, MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR, MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR, MYSQL_TYPE_BIT, /* mysql-5.6 compatibility temporal types. They're only used internally for reading RBR mysql-5.6 binary log events and mysql-5.6 frm files. They're never sent to the client. */ MYSQL_TYPE_TIMESTAMP2, MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIME2, /* Compressed types are only used internally for RBR. */ MYSQL_TYPE_BLOB_COMPRESSED= 140, MYSQL_TYPE_VARCHAR_COMPRESSED= 141, MYSQL_TYPE_NEWDECIMAL=246, MYSQL_TYPE_ENUM=247, MYSQL_TYPE_SET=248, MYSQL_TYPE_TINY_BLOB=249, MYSQL_TYPE_MEDIUM_BLOB=250, MYSQL_TYPE_LONG_BLOB=251, MYSQL_TYPE_BLOB=252, MYSQL_TYPE_VAR_STRING=253, MYSQL_TYPE_STRING=254, MYSQL_TYPE_GEOMETRY=255 }; /* For backward compatibility */ #define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS #define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL #define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL #define FIELD_TYPE_TINY MYSQL_TYPE_TINY #define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT #define FIELD_TYPE_LONG MYSQL_TYPE_LONG #define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT #define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE #define FIELD_TYPE_NULL MYSQL_TYPE_NULL #define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP #define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG #define FIELD_TYPE_INT24 MYSQL_TYPE_INT24 #define FIELD_TYPE_DATE MYSQL_TYPE_DATE #define FIELD_TYPE_TIME MYSQL_TYPE_TIME #define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME #define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR #define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE #define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM #define FIELD_TYPE_SET MYSQL_TYPE_SET #define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB #define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB #define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB #define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB #define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING #define FIELD_TYPE_STRING MYSQL_TYPE_STRING #define FIELD_TYPE_CHAR MYSQL_TYPE_TINY #define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM #define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY #define FIELD_TYPE_BIT MYSQL_TYPE_BIT /* Shutdown/kill enums and constants */ /* Bits for THD::killable. */ #define MYSQL_SHUTDOWN_KILLABLE_CONNECT (unsigned char)(1 << 0) #define MYSQL_SHUTDOWN_KILLABLE_TRANS (unsigned char)(1 << 1) #define MYSQL_SHUTDOWN_KILLABLE_LOCK_TABLE (unsigned char)(1 << 2) #define MYSQL_SHUTDOWN_KILLABLE_UPDATE (unsigned char)(1 << 3) enum mysql_enum_shutdown_level { /* We want levels to be in growing order of hardness (because we use number comparisons). Note that DEFAULT does not respect the growing property, but it's ok. */ SHUTDOWN_DEFAULT = 0, /* wait for existing connections to finish */ SHUTDOWN_WAIT_CONNECTIONS= MYSQL_SHUTDOWN_KILLABLE_CONNECT, /* wait for existing trans to finish */ SHUTDOWN_WAIT_TRANSACTIONS= MYSQL_SHUTDOWN_KILLABLE_TRANS, /* wait for existing updates to finish (=> no partial MyISAM update) */ SHUTDOWN_WAIT_UPDATES= MYSQL_SHUTDOWN_KILLABLE_UPDATE, /* flush InnoDB buffers and other storage engines' buffers*/ SHUTDOWN_WAIT_ALL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1), /* don't flush InnoDB buffers, flush other storage engines' buffers*/ SHUTDOWN_WAIT_CRITICAL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1) + 1 }; enum enum_cursor_type { CURSOR_TYPE_NO_CURSOR= 0, CURSOR_TYPE_READ_ONLY= 1, CURSOR_TYPE_FOR_UPDATE= 2, CURSOR_TYPE_SCROLLABLE= 4 }; /* options for mysql_set_option */ enum enum_mysql_set_option { MYSQL_OPTION_MULTI_STATEMENTS_ON, MYSQL_OPTION_MULTI_STATEMENTS_OFF }; /* Type of state change information that the server can include in the Ok packet. */ enum enum_session_state_type { SESSION_TRACK_SYSTEM_VARIABLES, /* Session system variables */ SESSION_TRACK_SCHEMA, /* Current schema */ SESSION_TRACK_STATE_CHANGE, /* track session state changes */ SESSION_TRACK_GTIDS, SESSION_TRACK_TRANSACTION_CHARACTERISTICS, /* Transaction chistics */ SESSION_TRACK_TRANSACTION_STATE, /* Transaction state */ #ifdef USER_VAR_TRACKING SESSION_TRACK_MYSQL_RESERVED1, SESSION_TRACK_MYSQL_RESERVED2, SESSION_TRACK_MYSQL_RESERVED3, SESSION_TRACK_MYSQL_RESERVED4, SESSION_TRACK_MYSQL_RESERVED5, SESSION_TRACK_MYSQL_RESERVED6, SESSION_TRACK_USER_VARIABLES, #endif // USER_VAR_TRACKING SESSION_TRACK_always_at_the_end /* must be last */ }; #define SESSION_TRACK_BEGIN SESSION_TRACK_SYSTEM_VARIABLES #define IS_SESSION_STATE_TYPE(T) \ (((int)(T) >= SESSION_TRACK_BEGIN) && ((T) < SESSION_TRACK_always_at_the_end)) #define net_new_transaction(net) ((net)->pkt_nr=0) #ifdef __cplusplus extern "C" { #endif my_bool my_net_init(NET *net, Vio* vio, void *thd, unsigned int my_flags); void my_net_local_init(NET *net); void net_end(NET *net); void net_clear(NET *net, my_bool clear_buffer); my_bool net_realloc(NET *net, size_t length); my_bool net_flush(NET *net); my_bool my_net_write(NET *net,const unsigned char *packet, size_t len); my_bool net_write_command(NET *net,unsigned char command, const unsigned char *header, size_t head_len, const unsigned char *packet, size_t len); int net_real_write(NET *net,const unsigned char *packet, size_t len); unsigned long my_net_read_packet(NET *net, my_bool read_from_server); unsigned long my_net_read_packet_reallen(NET *net, my_bool read_from_server, unsigned long* reallen); #define my_net_read(A) my_net_read_packet((A), 0) #ifdef MY_GLOBAL_INCLUDED void my_net_set_write_timeout(NET *net, uint timeout); void my_net_set_read_timeout(NET *net, uint timeout); #endif struct sockaddr; int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen, unsigned int timeout); struct my_rnd_struct; #ifdef __cplusplus } #endif /* The following is for user defined functions */ enum Item_result { STRING_RESULT=0, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT, TIME_RESULT }; typedef struct st_udf_args { unsigned int arg_count; /* Number of arguments */ enum Item_result *arg_type; /* Pointer to item_results */ char **args; /* Pointer to argument */ unsigned long *lengths; /* Length of string arguments */ char *maybe_null; /* Set to 1 for all maybe_null args */ const char **attributes; /* Pointer to attribute name */ unsigned long *attribute_lengths; /* Length of attribute arguments */ void *extension; } UDF_ARGS; /* This holds information about the result */ typedef struct st_udf_init { my_bool maybe_null; /* 1 if function can return NULL */ unsigned int decimals; /* for real functions */ unsigned long max_length; /* For string functions */ char *ptr; /* free pointer for function data */ my_bool const_item; /* 1 if function always returns the same value */ void *extension; } UDF_INIT; /* TODO: add a notion for determinism of the UDF. See Item_udf_func::update_used_tables () */ /* Constants when using compression */ #define NET_HEADER_SIZE 4 /* standard header size */ #define COMP_HEADER_SIZE 3 /* compression header extra size */ /* Prototypes to password functions */ #ifdef __cplusplus extern "C" { #endif /* These functions are used for authentication by client and server and implemented in sql/password.c */ void create_random_string(char *to, unsigned int length, struct my_rnd_struct *rand_st); void hash_password(unsigned long *to, const char *password, unsigned int password_len); void make_scrambled_password_323(char *to, const char *password); void scramble_323(char *to, const char *message, const char *password); my_bool check_scramble_323(const unsigned char *reply, const char *message, unsigned long *salt); void get_salt_from_password_323(unsigned long *res, const char *password); void make_scrambled_password(char *to, const char *password); void scramble(char *to, const char *message, const char *password); my_bool check_scramble(const unsigned char *reply, const char *message, const unsigned char *hash_stage2); void get_salt_from_password(unsigned char *res, const char *password); char *octet2hex(char *to, const char *str, size_t len); /* end of password.c */ char *get_tty_password(const char *opt_message); void get_tty_password_buff(const char *opt_message, char *to, size_t length); const char *mysql_errno_to_sqlstate(unsigned int mysql_errno); /* Some other useful functions */ my_bool my_thread_init(void); void my_thread_end(void); #ifdef MY_GLOBAL_INCLUDED #include "pack.h" #endif #ifdef __cplusplus } #endif #define NULL_LENGTH ~0UL /* For net_store_length */ #define MYSQL_STMT_HEADER 4U #define MYSQL_LONG_DATA_HEADER 6U /* If a float or double field have more than this number of decimals, it's regarded as floating point field without any specific number of decimals */ #endif mysql/server/ma_dyncol.h000064400000017555151027430560011355 0ustar00/* Copyright (c) 2011, Monty Program Ab Copyright (c) 2011, Oleksandr Byelkin 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 the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY ``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 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ma_dyncol_h #define ma_dyncol_h #ifdef __cplusplus extern "C" { #endif #include #include #include #ifndef _my_sys_h typedef struct st_dynamic_string { char *str; size_t length,max_length,alloc_increment; } DYNAMIC_STRING; #endif #ifndef MY_GLOBAL_INCLUDED struct st_mysql_lex_string { char *str; size_t length; }; typedef struct st_mysql_lex_string MYSQL_LEX_STRING; typedef struct st_mysql_lex_string LEX_STRING; #endif /* Limits of implementation */ #define MAX_TOTAL_NAME_LENGTH 65535 #define MAX_NAME_LENGTH (MAX_TOTAL_NAME_LENGTH/4) /* NO and OK is the same used just to show semantics */ #define ER_DYNCOL_NO ER_DYNCOL_OK #ifdef HAVE_CHARSET_utf8mb4 #define DYNCOL_UTF (&my_charset_utf8mb4_general_ci) #else #define DYNCOL_UTF (&my_charset_utf8mb3_general_ci) #endif /* escape json strings */ #define DYNCOL_JSON_ESC ((char)1) enum enum_dyncol_func_result { ER_DYNCOL_OK= 0, ER_DYNCOL_YES= 1, /* For functions returning 0/1 */ ER_DYNCOL_FORMAT= -1, /* Wrong format of the encoded string */ ER_DYNCOL_LIMIT= -2, /* Some limit reached */ ER_DYNCOL_RESOURCE= -3, /* Out of resources */ ER_DYNCOL_DATA= -4, /* Incorrect input data */ ER_DYNCOL_UNKNOWN_CHARSET= -5, /* Unknown character set */ ER_DYNCOL_TRUNCATED= 2 /* OK, but data was truncated */ }; typedef DYNAMIC_STRING DYNAMIC_COLUMN; enum enum_dynamic_column_type { DYN_COL_NULL= 0, DYN_COL_INT, DYN_COL_UINT, DYN_COL_DOUBLE, DYN_COL_STRING, DYN_COL_DECIMAL, DYN_COL_DATETIME, DYN_COL_DATE, DYN_COL_TIME, DYN_COL_DYNCOL }; typedef enum enum_dynamic_column_type DYNAMIC_COLUMN_TYPE; struct st_dynamic_column_value { DYNAMIC_COLUMN_TYPE type; union { long long long_value; unsigned long long ulong_value; double double_value; struct { MYSQL_LEX_STRING value; CHARSET_INFO *charset; } string; struct { decimal_digit_t buffer[DECIMAL_BUFF_LENGTH]; decimal_t value; } decimal; MYSQL_TIME time_value; } x; }; typedef struct st_dynamic_column_value DYNAMIC_COLUMN_VALUE; #ifdef MADYNCOL_DEPRECATED enum enum_dyncol_func_result dynamic_column_create(DYNAMIC_COLUMN *str, uint column_nr, DYNAMIC_COLUMN_VALUE *value); enum enum_dyncol_func_result dynamic_column_create_many(DYNAMIC_COLUMN *str, uint column_count, uint *column_numbers, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result dynamic_column_update(DYNAMIC_COLUMN *org, uint column_nr, DYNAMIC_COLUMN_VALUE *value); enum enum_dyncol_func_result dynamic_column_update_many(DYNAMIC_COLUMN *str, uint add_column_count, uint *column_numbers, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result dynamic_column_exists(DYNAMIC_COLUMN *org, uint column_nr); enum enum_dyncol_func_result dynamic_column_list(DYNAMIC_COLUMN *org, DYNAMIC_ARRAY *array_of_uint); enum enum_dyncol_func_result dynamic_column_get(DYNAMIC_COLUMN *org, uint column_nr, DYNAMIC_COLUMN_VALUE *store_it_here); #endif /* new functions */ enum enum_dyncol_func_result mariadb_dyncol_create_many_num(DYNAMIC_COLUMN *str, uint column_count, uint *column_numbers, DYNAMIC_COLUMN_VALUE *values, my_bool new_string); enum enum_dyncol_func_result mariadb_dyncol_create_many_named(DYNAMIC_COLUMN *str, uint column_count, MYSQL_LEX_STRING *column_keys, DYNAMIC_COLUMN_VALUE *values, my_bool new_string); enum enum_dyncol_func_result mariadb_dyncol_update_many_num(DYNAMIC_COLUMN *str, uint add_column_count, uint *column_keys, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result mariadb_dyncol_update_many_named(DYNAMIC_COLUMN *str, uint add_column_count, MYSQL_LEX_STRING *column_keys, DYNAMIC_COLUMN_VALUE *values); enum enum_dyncol_func_result mariadb_dyncol_exists_num(DYNAMIC_COLUMN *org, uint column_nr); enum enum_dyncol_func_result mariadb_dyncol_exists_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name); /* List of not NULL columns */ enum enum_dyncol_func_result mariadb_dyncol_list_num(DYNAMIC_COLUMN *str, uint *count, uint **nums); enum enum_dyncol_func_result mariadb_dyncol_list_named(DYNAMIC_COLUMN *str, uint *count, MYSQL_LEX_STRING **names); /* if the column do not exists it is NULL */ enum enum_dyncol_func_result mariadb_dyncol_get_num(DYNAMIC_COLUMN *org, uint column_nr, DYNAMIC_COLUMN_VALUE *store_it_here); enum enum_dyncol_func_result mariadb_dyncol_get_named(DYNAMIC_COLUMN *str, MYSQL_LEX_STRING *name, DYNAMIC_COLUMN_VALUE *store_it_here); my_bool mariadb_dyncol_has_names(DYNAMIC_COLUMN *str); enum enum_dyncol_func_result mariadb_dyncol_check(DYNAMIC_COLUMN *str); enum enum_dyncol_func_result mariadb_dyncol_json(DYNAMIC_COLUMN *str, DYNAMIC_STRING *json); #define mariadb_dyncol_init(A) memset((A), 0, sizeof(*(A))) void mariadb_dyncol_free(DYNAMIC_COLUMN *str); /* conversion of values to 3 base types */ enum enum_dyncol_func_result mariadb_dyncol_val_str(DYNAMIC_STRING *str, DYNAMIC_COLUMN_VALUE *val, CHARSET_INFO *cs, my_bool quote); enum enum_dyncol_func_result mariadb_dyncol_val_long(longlong *ll, DYNAMIC_COLUMN_VALUE *val); enum enum_dyncol_func_result mariadb_dyncol_val_double(double *dbl, DYNAMIC_COLUMN_VALUE *val); enum enum_dyncol_func_result mariadb_dyncol_unpack(DYNAMIC_COLUMN *str, uint *count, MYSQL_LEX_STRING **names, DYNAMIC_COLUMN_VALUE **vals); void mariadb_dyncol_unpack_free(MYSQL_LEX_STRING *names, DYNAMIC_COLUMN_VALUE *vals); int mariadb_dyncol_column_cmp_named(const MYSQL_LEX_STRING *s1, const MYSQL_LEX_STRING *s2); enum enum_dyncol_func_result mariadb_dyncol_column_count(DYNAMIC_COLUMN *str, uint *column_count); #define mariadb_dyncol_value_init(V) (V)->type= DYN_COL_NULL /* Prepare value for using as decimal */ void mariadb_dyncol_prepare_decimal(DYNAMIC_COLUMN_VALUE *value); #ifdef __cplusplus } #endif #endif mysql/server/handler_state.h000064400000001366151027430560012216 0ustar00/* Map handler error message to sql states. Note that this list MUST be in increasing order! See sql_state.c for usage */ { HA_ERR_KEY_NOT_FOUND, "02000", "" }, { HA_ERR_FOUND_DUPP_KEY, "23000", "" }, { HA_ERR_WRONG_COMMAND, "0A000", "" }, { HA_ERR_UNSUPPORTED, "0A000", "" }, { HA_WRONG_CREATE_OPTION, "0A000", "" }, { HA_ERR_FOUND_DUPP_UNIQUE, "23000", "" }, { HA_ERR_UNKNOWN_CHARSET, "0A000", "" }, { HA_ERR_READ_ONLY_TRANSACTION, "25000", "" }, { HA_ERR_LOCK_DEADLOCK, "40001", "" }, { HA_ERR_NO_REFERENCED_ROW, "23000", "" }, { HA_ERR_ROW_IS_REFERENCED, "23000", "" }, { HA_ERR_TABLE_EXIST, "42S01", "" }, { HA_ERR_FOREIGN_DUPLICATE_KEY, "23000", "" }, { HA_ERR_TABLE_READONLY, "25000", "" }, { HA_ERR_AUTOINC_ERANGE, "22003", "" }, mysql/server/my_global.h000064400000100031151027430560011333 0ustar00/* Copyright (c) 2001, 2013, Oracle and/or its affiliates. Copyright (c) 2009, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* This is the include file that should be included 'first' in every C file. */ #ifndef MY_GLOBAL_INCLUDED #define MY_GLOBAL_INCLUDED /* MDEV-25602 Deprecate __WIN__ symbol. */ #if defined (_MSC_VER) && !defined(__clang__) #pragma deprecated("__WIN__") #elif defined (__GNUC__) #pragma GCC poison __WIN__ #endif /* InnoDB depends on some MySQL internals which other plugins should not need. This is because of InnoDB's foreign key support, "safe" binlog truncation, and other similar legacy features. We define accessors for these internals unconditionally, but do not expose them in mysql/plugin.h. They are declared in ha_innodb.h for InnoDB's use. */ #define INNODB_COMPATIBILITY_HOOKS #ifdef __CYGWIN__ /* We use a Unix API, so pretend it's not Windows */ #undef WIN #undef WIN32 #undef _WIN #undef _WIN32 #undef _WIN64 #undef _WIN32 #undef __WIN32__ #define HAVE_ERRNO_AS_DEFINE #define _POSIX_MONOTONIC_CLOCK #define _POSIX_THREAD_CPUTIME #endif /* __CYGWIN__ */ #if defined(__OpenBSD__) && (OpenBSD >= 200411) #define HAVE_ERRNO_AS_DEFINE #endif #if defined(i386) && !defined(__i386__) #define __i386__ #endif /* Macros to make switching between C and C++ mode easier */ #ifdef __cplusplus #define C_MODE_START extern "C" { #define C_MODE_END } #else #define C_MODE_START #define C_MODE_END #endif #ifdef __cplusplus #define CPP_UNNAMED_NS_START namespace { #define CPP_UNNAMED_NS_END } #endif #include #ifdef WITH_PERFSCHEMA_STORAGE_ENGINE #define HAVE_PSI_INTERFACE #endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */ /* Make it easier to add conditional code in _expressions_ */ #ifdef _WIN32 #define IF_WIN(A,B) A #else #define IF_WIN(A,B) B #endif #ifdef EMBEDDED_LIBRARY #define IF_EMBEDDED(A,B) A #else #define IF_EMBEDDED(A,B) B #endif #ifdef WITH_PARTITION_STORAGE_ENGINE #define IF_PARTITIONING(A,B) A #else #define IF_PARTITIONING(A,B) B #endif #if defined (_WIN32) /* off_t is 32 bit long. We do not use C runtime functions with off_t but native Win32 file IO APIs, that work with 64 bit offsets. */ #undef SIZEOF_OFF_T #define SIZEOF_OFF_T 8 /* Prevent inclusion of Windows GDI headers - they define symbol ERROR that conflicts with mysql headers. */ #ifndef NOGDI #define NOGDI #endif /* Include common headers.*/ #include #include /* SOCKET */ #include /* access(), chmod() */ #include /* getpid() */ #define sleep(a) Sleep((a)*1000) /* Define missing access() modes. */ #define F_OK 0 #define W_OK 2 #define R_OK 4 /* Test for read permission. */ /* Define missing file locking constants. */ #define F_RDLCK 1 #define F_WRLCK 2 #define F_UNLCK 3 #define F_TO_EOF 0x3FFFFFFF #endif /* _WIN32*/ /* The macros below are used to allow build of Universal/fat binaries of MySQL and MySQL applications under darwin. */ #if defined(__APPLE__) && defined(__MACH__) # undef SIZEOF_CHARP # undef SIZEOF_INT # undef SIZEOF_LONG # undef SIZEOF_LONG_LONG # undef SIZEOF_OFF_T # undef WORDS_BIGENDIAN # define SIZEOF_INT 4 # define SIZEOF_LONG_LONG 8 # define SIZEOF_OFF_T 8 # if defined(__i386__) || defined(__ppc__) # define SIZEOF_CHARP 4 # define SIZEOF_LONG 4 # elif defined(__x86_64__) || defined(__ppc64__) || defined(__aarch64__) || defined(__arm64__) # define SIZEOF_CHARP 8 # define SIZEOF_LONG 8 # else # error Building FAT binary for an unknown architecture. # endif # if defined(__ppc__) || defined(__ppc64__) # define WORDS_BIGENDIAN # endif #endif /* defined(__APPLE__) && defined(__MACH__) */ /* The macros below are borrowed from include/linux/compiler.h in the Linux kernel. Use them to indicate the likelihood of the truthfulness of a condition. This serves two purposes - newer versions of gcc will be able to optimize for branch predication, which could yield siginficant performance gains in frequently executed sections of the code, and the other reason to use them is for documentation */ #if !defined(__GNUC__) || (__GNUC__ == 2 && __GNUC_MINOR__ < 96) #define __builtin_expect(x, expected_value) (x) #endif /* Fix problem with S_ISLNK() on Linux */ #if defined(TARGET_OS_LINUX) || defined(__GLIBC__) #undef _GNU_SOURCE #define _GNU_SOURCE 1 #endif /* Temporary solution to solve bug#7156. Include "sys/types.h" before the thread headers, else the function madvise() will not be defined */ #if defined(HAVE_SYS_TYPES_H) && ( defined(sun) || defined(__sun) ) #include #endif #define __EXTENSIONS__ 1 /* We want some extension */ #ifndef __STDC_EXT__ #define __STDC_EXT__ 1 /* To get large file support on hpux */ #endif /* Solaris 9 include file refers to X/Open document System Interfaces and Headers, Issue 5 saying we should define _XOPEN_SOURCE=500 to get POSIX.1c prototypes, but apparently other systems (namely FreeBSD) don't agree. On a newer Solaris 10, the above file recognizes also _XOPEN_SOURCE=600. Furthermore, it tests that if a program requires older standard (_XOPEN_SOURCE<600 or _POSIX_C_SOURCE<200112L) it cannot be run on a new compiler (that defines _STDC_C99) and issues an #error. It's also an #error if a program requires new standard (_XOPEN_SOURCE=600 or _POSIX_C_SOURCE=200112L) and a compiler does not define _STDC_C99. To add more to this mess, Sun Studio C compiler defines _STDC_C99 while C++ compiler does not! So, in a desperate attempt to get correct prototypes for both C and C++ code, we define either _XOPEN_SOURCE=600 or _XOPEN_SOURCE=500 depending on the compiler's announced C standard support. Cleaner solutions are welcome. */ #ifdef __sun #if __STDC_VERSION__ - 0 >= 199901L #define _XOPEN_SOURCE 600 #else #define _XOPEN_SOURCE 500 #endif #endif #ifdef _AIX /* AIX includes inttypes.h from sys/types.h Explicitly request format macros before the first inclusion of inttypes.h */ #if !defined(__STDC_FORMAT_MACROS) #define __STDC_FORMAT_MACROS #endif // !defined(__STDC_FORMAT_MACROS) #endif #if !defined(_WIN32) #ifndef _POSIX_PTHREAD_SEMANTICS #define _POSIX_PTHREAD_SEMANTICS /* We want posix threads */ #endif #if !defined(SCO) #define _REENTRANT 1 /* Some thread libraries require this */ #endif #if !defined(_THREAD_SAFE) && !defined(_AIX) #define _THREAD_SAFE /* Required for OSF1 */ #endif #if defined(HPUX10) || defined(HPUX11) C_MODE_START /* HPUX needs this, signal.h bug */ #include C_MODE_END #else #include /* AIX must have this included first */ #endif #if !defined(SCO) && !defined(_REENTRANT) #define _REENTRANT 1 /* Threads requires reentrant code */ #endif #endif /* !defined(_WIN32) */ /* gcc/egcs issues */ #if defined(__GNUC) && defined(__EXCEPTIONS) #error "Please add -fno-exceptions to CXXFLAGS and reconfigure/recompile" #endif #if defined(_lint) && !defined(lint) #define lint #endif #ifndef stdin #include #endif #include #ifdef HAVE_STDLIB_H #include #endif #ifdef HAVE_STDDEF_H #include #endif #include #ifdef HAVE_LIMITS_H #include #endif #ifdef HAVE_FLOAT_H #include #endif #ifdef HAVE_FENV_H #include /* For fesetround() */ #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #if TIME_WITH_SYS_TIME # include # include #else # if HAVE_SYS_TIME_H # include # else # include # endif #endif /* TIME_WITH_SYS_TIME */ #ifdef HAVE_UNISTD_H #include #endif #include /* Recommended by debian */ /* We need the following to go around a problem with openssl on solaris */ #if defined(HAVE_CRYPT_H) #include #endif /* Add checking if we are using likely/unlikely wrong */ #ifdef CHECK_UNLIKELY C_MODE_START extern void init_my_likely(), end_my_likely(FILE *); extern int my_likely_ok(const char *file_name, uint line); extern int my_likely_fail(const char *file_name, uint line); C_MODE_END #define likely(A) ((A) ? (my_likely_ok(__FILE__, __LINE__),1) : (my_likely_fail(__FILE__, __LINE__), 0)) #define unlikely(A) ((A) ? (my_likely_fail(__FILE__, __LINE__),1) : (my_likely_ok(__FILE__, __LINE__), 0)) /* These macros should be used when the check fails often when running benchmarks but we know for sure that the check is correct in a production environment */ #define checked_likely(A) (A) #define checked_unlikely(A) (A) #else /** The semantics of builtin_expect() are that 1) its two arguments are long 2) it's likely that they are == Those of our likely(x) are that x can be bool/int/longlong/pointer. */ #define likely(x) __builtin_expect(((x) != 0),1) #define unlikely(x) __builtin_expect(((x) != 0),0) #define checked_likely(x) likely(x) #define checked_unlikely(x) unlikely(x) #endif /* CHECK_UNLIKELY */ /* A lot of our programs uses asserts, so better to always include it This also fixes a problem when people uses DBUG_ASSERT without including assert.h */ #include /* an assert that works at compile-time. only for constant expression */ #ifdef _some_old_compiler_that_does_not_understand_the_construct_below_ #define compile_time_assert(X) do { } while(0) #else #define compile_time_assert(X) \ do \ { \ typedef char compile_time_assert[(X) ? 1 : -1] __attribute__((unused)); \ } while(0) #endif /* Go around some bugs in different OS and compilers */ #if defined (HPUX11) && defined(_LARGEFILE_SOURCE) #ifndef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE #endif #endif #if defined(_HPUX_SOURCE) && defined(HAVE_SYS_STREAM_H) #include /* HPUX 10.20 defines ulong here. UGLY !!! */ #define HAVE_ULONG #endif #if defined(HPUX10) && defined(_LARGEFILE64_SOURCE) /* Fix bug in setrlimit */ #undef setrlimit #define setrlimit cma_setrlimit64 #endif /* Declare madvise where it is not declared for C++, like Solaris */ #if HAVE_MADVISE && !HAVE_DECL_MADVISE && defined(__cplusplus) extern "C" int madvise(void *addr, size_t len, int behav); #endif #ifdef HAVE_SYS_MMAN_H #include #endif /** FreeBSD equivalent */ #if defined(MADV_CORE) && !defined(MADV_DODUMP) #define MADV_DODUMP MADV_CORE #define MADV_DONTDUMP MADV_NOCORE #define DODUMP_STR "MADV_CORE" #define DONTDUMP_STR "MADV_NOCORE" #else #define DODUMP_STR "MADV_DODUMP" #define DONTDUMP_STR "MADV_DONTDUMP" #endif #define QUOTE_ARG(x) #x /* Quote argument (before cpp) */ #define STRINGIFY_ARG(x) QUOTE_ARG(x) /* Quote argument, after cpp */ /* Paranoid settings. Define I_AM_PARANOID if you are paranoid */ #ifdef I_AM_PARANOID #define DONT_ALLOW_USER_CHANGE 1 #define DONT_USE_MYSQL_PWD 1 #endif /* Does the system remember a signal handler after a signal ? */ #if !defined(HAVE_BSD_SIGNALS) && !defined(HAVE_SIGACTION) #define SIGNAL_HANDLER_RESET_ON_DELIVERY #endif /* don't assume that STDERR_FILENO is 2, mysqld can freopen */ #undef STDERR_FILENO #ifndef SO_EXT #ifdef _WIN32 #define SO_EXT ".dll" #else #define SO_EXT ".so" #endif #endif /* Suppress uninitialized variable warning without generating code. */ #if defined(__GNUC__) /* GCC specific self-initialization which inhibits the warning. */ #define UNINIT_VAR(x) x= x #elif defined(_lint) || defined(FORCE_INIT_OF_VARS) #define UNINIT_VAR(x) x= 0 #else #define UNINIT_VAR(x) x #endif /* This is only to be used when resetting variables in a class constructor */ #if defined(_lint) || defined(FORCE_INIT_OF_VARS) #define LINT_INIT(x) x= 0 #else #define LINT_INIT(x) #endif #if !defined(HAVE_UINT) #undef HAVE_UINT #define HAVE_UINT typedef unsigned int uint; typedef unsigned short ushort; #endif #define swap_variables(t, a, b) do { t dummy; dummy= a; a= b; b= dummy; } while(0) #define MY_TEST(a) ((a) ? 1 : 0) #define set_if_bigger(a,b) do { if ((a) < (b)) (a)=(b); } while(0) #define set_if_smaller(a,b) do { if ((a) > (b)) (a)=(b); } while(0) #define set_bits(type, bit_count) (sizeof(type)*8 <= (bit_count) ? ~(type) 0 : ((((type) 1) << (bit_count)) - (type) 1)) #define test_all_bits(a,b) (((a) & (b)) == (b)) #define array_elements(A) ((uint) (sizeof(A)/sizeof(A[0]))) /* Define some general constants */ #ifndef TRUE #define TRUE (1) /* Logical true */ #define FALSE (0) /* Logical false */ #endif #include #include /* Wen using the embedded library, users might run into link problems, duplicate declaration of __cxa_pure_virtual, solved by declaring it a weak symbol. */ #if defined(USE_MYSYS_NEW) && ! defined(DONT_DECLARE_CXA_PURE_VIRTUAL) C_MODE_START int __cxa_pure_virtual () __attribute__ ((weak)); C_MODE_END #endif /* The DBUG_ON flag always takes precedence over default DBUG_OFF */ #if defined(DBUG_ON) && defined(DBUG_OFF) #undef DBUG_OFF #endif /* We might be forced to turn debug off, if not turned off already */ #if (defined(FORCE_DBUG_OFF) || defined(_lint)) && !defined(DBUG_OFF) # define DBUG_OFF # ifdef DBUG_ON # undef DBUG_ON # endif #endif #ifdef DBUG_OFF #undef EXTRA_DEBUG #endif /* Some types that is different between systems */ typedef int File; /* File descriptor */ #ifdef _WIN32 typedef SOCKET my_socket; #else typedef int my_socket; /* File descriptor for sockets */ #define INVALID_SOCKET -1 #endif /* Type for functions that handles signals */ #define sig_handler RETSIGTYPE #if defined(__GNUC__) && !defined(_lint) typedef char pchar; /* Mixed prototypes can take char */ typedef char puchar; /* Mixed prototypes can take char */ typedef char pbool; /* Mixed prototypes can take char */ typedef short pshort; /* Mixed prototypes can take short int */ typedef float pfloat; /* Mixed prototypes can take float */ #else typedef int pchar; /* Mixed prototypes can't take char */ typedef uint puchar; /* Mixed prototypes can't take char */ typedef int pbool; /* Mixed prototypes can't take char */ typedef int pshort; /* Mixed prototypes can't take short int */ typedef double pfloat; /* Mixed prototypes can't take float */ #endif #include #define qsort_t RETQSORTTYPE /* Broken GCC can't handle typedef !!!! */ #ifdef HAVE_SYS_SOCKET_H #include #endif typedef SOCKET_SIZE_TYPE size_socket; #ifndef SOCKOPT_OPTLEN_TYPE #define SOCKOPT_OPTLEN_TYPE size_socket #endif /* file create flags */ #ifndef O_SHARE /* Probably not windows */ #define O_SHARE 0 /* Flag to my_open for shared files */ #ifndef O_BINARY #define O_BINARY 0 /* Flag to my_open for binary files */ #endif #ifndef FILE_BINARY #define FILE_BINARY O_BINARY /* Flag to my_fopen for binary streams */ #endif #ifdef HAVE_FCNTL #define HAVE_FCNTL_LOCK #define F_TO_EOF 0L /* Param to lockf() to lock rest of file */ #endif #endif /* O_SHARE */ #ifndef O_SEQUENTIAL #define O_SEQUENTIAL 0 #endif #ifndef O_SHORT_LIVED #define O_SHORT_LIVED 0 #endif #ifndef O_NOFOLLOW #define O_NOFOLLOW 0 #endif #ifndef O_CLOEXEC #define O_CLOEXEC 0 #endif #ifdef __GLIBC__ #define STR_O_CLOEXEC "e" #else #define STR_O_CLOEXEC "" #endif #ifndef SOCK_CLOEXEC #define SOCK_CLOEXEC 0 #else #define HAVE_SOCK_CLOEXEC #endif /* additional file share flags for win32 */ #ifdef _WIN32 #define _SH_DENYRWD 0x110 /* deny read/write mode & delete */ #define _SH_DENYWRD 0x120 /* deny write mode & delete */ #define _SH_DENYRDD 0x130 /* deny read mode & delete */ #define _SH_DENYDEL 0x140 /* deny delete only */ #endif /* _WIN32 */ /* General constants */ #define FN_LEN 256 /* Max file name len */ #define FN_HEADLEN 253 /* Max length of filepart of file name */ #define FN_EXTLEN 20 /* Max length of extension (part of FN_LEN) */ #define FN_REFLEN 512 /* Max length of full path-name */ #define FN_EXTCHAR '.' #define FN_HOMELIB '~' /* ~/ is used as abbrev for home dir */ #define FN_CURLIB '.' /* ./ is used as abbrev for current dir */ #define FN_PARENTDIR ".." /* Parent directory; Must be a string */ #ifdef _WIN32 #define FN_LIBCHAR '\\' #define FN_LIBCHAR2 '/' #define FN_DIRSEP "/\\" /* Valid directory separators */ #define FN_EXEEXT ".exe" #define FN_SOEXT ".dll" #define FN_ROOTDIR "\\" #define FN_DEVCHAR ':' #define FN_NETWORK_DRIVES /* Uses \\ to indicate network drives */ #define FN_NO_CASE_SENCE /* Files are not case-sensitive */ #else #define FN_LIBCHAR '/' #define FN_LIBCHAR2 '/' #define FN_DIRSEP "/" /* Valid directory separators */ #define FN_EXEEXT "" #define FN_SOEXT ".so" #define FN_ROOTDIR "/" #endif /* MY_FILE_MIN is Windows speciality and is used to quickly detect the mismatch of CRT and mysys file IO usage on Windows at runtime. CRT file descriptors can be in the range 0-2047, whereas descriptors returned by my_open() will start with 2048. If a file descriptor with value less then MY_FILE_MIN is passed to mysys IO function, chances are it stems from open()/fileno() and not my_open()/my_fileno. For Posix, mysys functions are light wrappers around libc, and MY_FILE_MIN is logically 0. */ #ifdef _WIN32 #define MY_FILE_MIN 2048 #else #define MY_FILE_MIN 0 #endif /* MY_NFILE is the default size of my_file_info array. It is larger on Windows, because it all file handles are stored in my_file_info Default size is 16384 and this should be enough for most cases.If it is not enough, --max-open-files with larger value can be used. For Posix , my_file_info array is only used to store filenames for error reporting and its size is not a limitation for number of open files. */ #ifdef _WIN32 #define MY_NFILE (16384 + MY_FILE_MIN) #else #define MY_NFILE 64 #endif #ifndef OS_FILE_LIMIT #define OS_FILE_LIMIT UINT_MAX #endif /* Io buffer size; Must be a power of 2 and a multiple of 512. May be smaller what the disk page size. This influences the speed of the isam btree library. eg to big to slow. */ #define IO_SIZE 4096U /* How much overhead does malloc/my_malloc have. The code often allocates something like 1024-MALLOC_OVERHEAD bytes */ #define MALLOC_OVERHEAD (8+24) /* get memory in huncs */ #define ONCE_ALLOC_INIT (uint) 4096 /* Typical record cache */ #define RECORD_CACHE_SIZE (uint) (128*1024) /* Typical key cache */ #define KEY_CACHE_SIZE (uint) (128L*1024L*1024L) /* Default size of a key cache block */ #define KEY_CACHE_BLOCK_SIZE (uint) 1024 /* Some things that this system doesn't have */ #ifdef _WIN32 #define NO_DIR_LIBRARY /* Not standard dir-library */ #endif /* Some defines of functions for portability */ #undef remove /* Crashes MySQL on SCO 5.0.0 */ #ifndef _WIN32 #define closesocket(A) close(A) #endif #if defined(_MSC_VER) #if !defined(_WIN64) inline double my_ulonglong2double(unsigned long long value) { long long nr=(long long) value; if (nr >= 0) return (double) nr; return (18446744073709551616.0 + (double) nr); } #define ulonglong2double my_ulonglong2double #define my_off_t2double my_ulonglong2double #endif /* _WIN64 */ inline unsigned long long my_double2ulonglong(double d) { double t= d - (double) 0x8000000000000000ULL; if (t >= 0) return ((unsigned long long) t) + 0x8000000000000000ULL; return (unsigned long long) d; } #define double2ulonglong my_double2ulonglong #endif #ifndef ulonglong2double #define ulonglong2double(A) ((double) (ulonglong) (A)) #define my_off_t2double(A) ((double) (my_off_t) (A)) #endif #ifndef double2ulonglong #define double2ulonglong(A) ((ulonglong) (double) (A)) #endif #ifndef offsetof #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #endif #define ulong_to_double(X) ((double) (ulong) (X)) #ifndef STACK_DIRECTION #error "please add -DSTACK_DIRECTION=1 or -1 to your CPPFLAGS" #endif #if !defined(HAVE_STRTOK_R) #define strtok_r(A,B,C) strtok((A),(B)) #endif #if SIZEOF_LONG_LONG >= 8 #define HAVE_LONG_LONG 1 #else #error WHAT? sizeof(long long) < 8 ??? #endif /* Some pre-ANSI-C99 systems like AIX 5.1 and Linux/GCC 2.95 define ULONGLONG_MAX, LONGLONG_MIN, LONGLONG_MAX; we use them if they're defined. */ #if defined(HAVE_LONG_LONG) && !defined(LONGLONG_MIN) #define LONGLONG_MIN ((long long) 0x8000000000000000LL) #define LONGLONG_MAX ((long long) 0x7FFFFFFFFFFFFFFFLL) #endif /* Max length needed for a buffer to hold a longlong or ulonglong + end \0 */ #define LONGLONG_BUFFER_SIZE 21 #if defined(HAVE_LONG_LONG) && !defined(ULONGLONG_MAX) /* First check for ANSI C99 definition: */ #ifdef ULLONG_MAX #define ULONGLONG_MAX ULLONG_MAX #else #define ULONGLONG_MAX ((unsigned long long)(~0ULL)) #endif #endif /* defined (HAVE_LONG_LONG) && !defined(ULONGLONG_MAX)*/ #define INT_MIN64 (~0x7FFFFFFFFFFFFFFFLL) #define INT_MAX64 0x7FFFFFFFFFFFFFFFLL #define INT_MIN32 (~0x7FFFFFFFL) #define INT_MAX32 0x7FFFFFFFL #define UINT_MAX32 0xFFFFFFFFL #define INT_MIN24 (~0x007FFFFF) #define INT_MAX24 0x007FFFFF #define UINT_MAX24 0x00FFFFFF #define INT_MIN16 (~0x7FFF) #define INT_MAX16 0x7FFF #define UINT_MAX16 0xFFFF #define INT_MIN8 (~0x7F) #define INT_MAX8 0x7F #define UINT_MAX8 0xFF /* From limits.h instead */ #ifndef DBL_MIN #define DBL_MIN 4.94065645841246544e-324 #define FLT_MIN ((float)1.40129846432481707e-45) #endif #ifndef DBL_MAX #define DBL_MAX 1.79769313486231470e+308 #define FLT_MAX ((float)3.40282346638528860e+38) #endif #ifndef SIZE_T_MAX #define SIZE_T_MAX (~((size_t) 0)) #endif /* Define missing math constants. */ #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_E #define M_E 2.7182818284590452354 #endif #ifndef M_LN2 #define M_LN2 0.69314718055994530942 #endif /* Max size that must be added to a so that we know Size to make addressable obj. */ #if SIZEOF_CHARP == 4 typedef long my_ptrdiff_t; #else typedef long long my_ptrdiff_t; #endif #define MY_ALIGN(A,L) (((A) + (L) - 1) & ~((L) - 1)) #define MY_ALIGN_DOWN(A,L) ((A) & ~((L) - 1)) #define ALIGN_SIZE(A) MY_ALIGN((A),sizeof(double)) #define ALIGN_MAX_UNIT (sizeof(double)) /* Size to make addressable obj. */ #define ALIGN_PTR(A, t) ((t*) MY_ALIGN((A), sizeof(double))) #define ADD_TO_PTR(ptr,size,type) (type) ((uchar*) (ptr)+size) #define PTR_BYTE_DIFF(A,B) (my_ptrdiff_t) ((uchar*) (A) - (uchar*) (B)) /* Custom version of standard offsetof() macro which can be used to get offsets of members in class for non-POD types (according to the current version of C++ standard offsetof() macro can't be used in such cases and attempt to do so causes warnings to be emitted, OTOH in many cases it is still OK to assume that all instances of the class has the same offsets for the same members). This is temporary solution which should be removed once File_parser class and related routines are refactored. */ #define my_offsetof(TYPE, MEMBER) PTR_BYTE_DIFF(&((TYPE *)0x10)->MEMBER, 0x10) #define NullS (char *) 0 #ifdef STDCALL #undef STDCALL #endif #ifdef _WIN32 #define STDCALL __stdcall #else #define STDCALL #endif /* Typdefs for easier portability */ #ifndef HAVE_UCHAR typedef unsigned char uchar; /* Short for unsigned char */ #endif #ifndef HAVE_INT8 typedef signed char int8; /* Signed integer >= 8 bits */ #endif #ifndef HAVE_UINT8 typedef unsigned char uint8; /* Unsigned integer >= 8 bits */ #endif #ifndef HAVE_INT16 typedef short int16; #endif #ifndef HAVE_UINT16 typedef unsigned short uint16; #endif #if SIZEOF_INT == 4 #ifndef HAVE_INT32 typedef int int32; #endif #ifndef HAVE_UINT32 typedef unsigned int uint32; #endif #elif SIZEOF_LONG == 4 #ifndef HAVE_INT32 typedef long int32; #endif #ifndef HAVE_UINT32 typedef unsigned long uint32; #endif #else #error Neither int or long is of 4 bytes width #endif #if !defined(HAVE_ULONG) && !defined(__USE_MISC) typedef unsigned long ulong; /* Short for unsigned long */ #endif #ifndef longlong_defined /* Using [unsigned] long long is preferable as [u]longlong because we use [unsigned] long long unconditionally in many places, for example in constants with [U]LL suffix. */ #if defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 8 typedef unsigned long long int ulonglong; /* ulong or unsigned long long */ typedef long long int longlong; #else typedef unsigned long ulonglong; /* ulong or unsigned long long */ typedef long longlong; #endif #endif #ifndef HAVE_INT64 typedef longlong int64; #endif #ifndef HAVE_UINT64 typedef ulonglong uint64; #endif #if defined(NO_CLIENT_LONG_LONG) typedef unsigned long my_ulonglong; #elif defined (_WIN32) typedef unsigned __int64 my_ulonglong; #else typedef unsigned long long my_ulonglong; #endif #if SIZEOF_CHARP == SIZEOF_INT typedef unsigned int intptr; #elif SIZEOF_CHARP == SIZEOF_LONG typedef unsigned long intptr; #elif SIZEOF_CHARP == SIZEOF_LONG_LONG typedef unsigned long long intptr; #else #error sizeof(void *) is neither sizeof(int) nor sizeof(long) nor sizeof(long long) #endif #define MY_ERRPTR ((void*)(intptr)1) #if defined(_WIN32) typedef unsigned long long my_off_t; typedef unsigned long long os_off_t; #else typedef off_t os_off_t; #if SIZEOF_OFF_T > 4 typedef ulonglong my_off_t; #else typedef unsigned long my_off_t; #endif #endif /*_WIN32*/ #define MY_FILEPOS_ERROR (~(my_off_t) 0) /* TODO Convert these to use Bitmap class. */ typedef ulonglong table_map; /* Used for table bits in join */ /* often used type names - opaque declarations */ typedef const struct charset_info_st CHARSET_INFO; typedef struct st_mysql_lex_string LEX_STRING; #if defined(_WIN32) #define socket_errno WSAGetLastError() #define SOCKET_EINTR WSAEINTR #define SOCKET_ETIMEDOUT WSAETIMEDOUT #define SOCKET_EWOULDBLOCK WSAEWOULDBLOCK #define SOCKET_EADDRINUSE WSAEADDRINUSE #define SOCKET_ECONNRESET WSAECONNRESET #define SOCKET_ENFILE ENFILE #define SOCKET_EMFILE EMFILE #define SOCKET_CLOSED EIO #else /* Unix */ #define socket_errno errno #define closesocket(A) close(A) #define SOCKET_EINTR EINTR #define SOCKET_EAGAIN EAGAIN #define SOCKET_EWOULDBLOCK EWOULDBLOCK #define SOCKET_EADDRINUSE EADDRINUSE #define SOCKET_ETIMEDOUT ETIMEDOUT #define SOCKET_ECONNRESET ECONNRESET #define SOCKET_CLOSED EIO #define SOCKET_ENFILE ENFILE #define SOCKET_EMFILE EMFILE #endif #include /* my_bool */ typedef ulong myf; /* Type of MyFlags in my_funcs */ #define MYF(v) (myf) (v) /* Defines to make it possible to prioritize register assignments. No longer that important with modern compilers. */ #ifndef USING_X #define reg1 register #define reg2 register #define reg3 register #define reg4 register #define reg5 register #define reg6 register #define reg7 register #define reg8 register #define reg9 register #define reg10 register #define reg11 register #define reg12 register #define reg13 register #define reg14 register #define reg15 register #define reg16 register #endif /* MYSQL_PLUGIN_IMPORT macro is used to export mysqld data (i.e variables) for usage in storage engine loadable plugins. Outside of Windows, it is dummy. */ #ifndef MYSQL_PLUGIN_IMPORT #if (defined(_WIN32) && defined(MYSQL_DYNAMIC_PLUGIN)) #define MYSQL_PLUGIN_IMPORT __declspec(dllimport) #else #define MYSQL_PLUGIN_IMPORT #endif #endif #include /* Some helper macros */ #define YESNO(X) ((X) ? "yes" : "no") #define MY_HOW_OFTEN_TO_ALARM 2 /* How often we want info on screen */ #define MY_HOW_OFTEN_TO_WRITE 10000 /* How often we want info on screen */ #include #ifdef HAVE_CHARSET_utf8mb4 #define MYSQL_UNIVERSAL_CLIENT_CHARSET "utf8mb4" #elif defined(HAVE_CHARSET_utf8mb3) #define MYSQL_UNIVERSAL_CLIENT_CHARSET "utf8mb3" #else #define MYSQL_UNIVERSAL_CLIENT_CHARSET MYSQL_DEFAULT_CHARSET_NAME #endif #if defined(EMBEDDED_LIBRARY) && !defined(HAVE_EMBEDDED_PRIVILEGE_CONTROL) #define NO_EMBEDDED_ACCESS_CHECKS #endif #ifdef _WIN32 #define dlsym(lib, name) (void*)GetProcAddress((HMODULE)lib, name) #define dlopen(libname, unused) LoadLibraryEx(libname, NULL, 0) #define RTLD_DEFAULT GetModuleHandle(NULL) #define dlclose(lib) FreeLibrary((HMODULE)lib) static inline char *dlerror(void) { static char win_errormsg[2048]; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, 0, GetLastError(), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), win_errormsg, 2048, NULL); return win_errormsg; } #define HAVE_DLOPEN 1 #define HAVE_DLERROR 1 #endif #ifdef HAVE_DLFCN_H #include #endif #ifdef HAVE_DLOPEN #ifndef HAVE_DLERROR #define dlerror() "" #endif #ifndef HAVE_DLADDR #define dladdr(A, B) 0 /* Dummy definition in case we're missing dladdr() */ typedef struct { const char *dli_fname, dli_fbase; } Dl_info; #endif #else #define dlerror() "No support for dynamic loading (static build?)" #define dlopen(A,B) 0 #define dlsym(A,B) 0 #define dlclose(A) 0 #define dladdr(A, B) 0 /* Dummy definition in case we're missing dladdr() */ typedef struct { const char *dli_fname, dli_fbase; } Dl_info; #endif /* * Include standard definitions of operator new and delete. */ #ifdef __cplusplus #include #endif /* Length of decimal number represented by INT32. */ #define MY_INT32_NUM_DECIMAL_DIGITS 11 /* Length of decimal number represented by INT64. */ #define MY_INT64_NUM_DECIMAL_DIGITS 21 #ifdef __cplusplus #include /* should be included before min/max macros */ #endif /* Define some useful general macros (should be done after all headers). */ #define MY_MAX(a, b) ((a) > (b) ? (a) : (b)) #define MY_MIN(a, b) ((a) < (b) ? (a) : (b)) #define CMP_NUM(a,b) (((a) < (b)) ? -1 : ((a) == (b)) ? 0 : 1) /* Only Linux is known to need an explicit sync of the directory to make sure a file creation/deletion/renaming in(from,to) this directory durable. */ #ifdef TARGET_OS_LINUX #define NEED_EXPLICIT_SYNC_DIR 1 #else /* On linux default rwlock scheduling policy is good enough for waiting_threads.c, on other systems use our special implementation (which is slower). QQ perhaps this should be tested in configure ? how ? */ #define WT_RWLOCKS_USE_MUTEXES 1 #endif #if !defined(__cplusplus) && !defined(bool) #define bool In_C_you_should_use_my_bool_instead() #endif /* Provide __func__ macro definition for platforms that miss it. */ #if !defined (__func__) #if defined(__STDC_VERSION__) && __STDC_VERSION__ < 199901L # if __GNUC__ >= 2 # define __func__ __FUNCTION__ # else # define __func__ "" # endif #elif defined(_MSC_VER) # if _MSC_VER < 1300 # define __func__ "" # else # define __func__ __FUNCTION__ # endif #elif defined(__BORLANDC__) # define __func__ __FUNC__ #else # define __func__ "" #endif #endif /* !defined(__func__) */ /* Defines that are unique to the embedded version of MySQL */ #ifdef EMBEDDED_LIBRARY /* Things we don't need in the embedded version of MySQL */ /* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */ #else #define HAVE_REPLICATION #define HAVE_EXTERNAL_CLIENT #endif /* EMBEDDED_LIBRARY */ /* Provide defaults for the CPU cache line size, if it has not been detected by CMake using getconf */ #if !defined(CPU_LEVEL1_DCACHE_LINESIZE) || CPU_LEVEL1_DCACHE_LINESIZE == 0 #if defined(CPU_LEVEL1_DCACHE_LINESIZE) && CPU_LEVEL1_DCACHE_LINESIZE == 0 #undef CPU_LEVEL1_DCACHE_LINESIZE #endif #if defined(__s390__) #define CPU_LEVEL1_DCACHE_LINESIZE 256 #elif defined(__powerpc__) || defined(__aarch64__) #define CPU_LEVEL1_DCACHE_LINESIZE 128 #else #define CPU_LEVEL1_DCACHE_LINESIZE 64 #endif #endif #define FLOATING_POINT_DECIMALS 31 /* Keep client compatible with earlier versions */ #ifdef MYSQL_SERVER #define NOT_FIXED_DEC DECIMAL_NOT_SPECIFIED #else #define NOT_FIXED_DEC FLOATING_POINT_DECIMALS #endif #endif /* my_global_h */ mysql/server/handler_ername.h000064400000010773151027430560012347 0ustar00/* Copyright (c) 2013, 2021, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /* Names of all handler error numbers. Used by mysqltest */ { "HA_ERR_KEY_NOT_FOUND", HA_ERR_KEY_NOT_FOUND, "" }, { "HA_ERR_FOUND_DUPP_KEY", HA_ERR_FOUND_DUPP_KEY, "" }, { "HA_ERR_INTERNAL_ERROR", HA_ERR_INTERNAL_ERROR, "" }, { "HA_ERR_RECORD_CHANGED", HA_ERR_RECORD_CHANGED, "" }, { "HA_ERR_WRONG_INDEX", HA_ERR_WRONG_INDEX, "" }, { "HA_ERR_CRASHED", HA_ERR_CRASHED, "" }, { "HA_ERR_WRONG_IN_RECORD", HA_ERR_WRONG_IN_RECORD, "" }, { "HA_ERR_OUT_OF_MEM", HA_ERR_OUT_OF_MEM, "" }, { "HA_ERR_NOT_A_TABLE", HA_ERR_NOT_A_TABLE, "" }, { "HA_ERR_WRONG_COMMAND", HA_ERR_WRONG_COMMAND, "" }, { "HA_ERR_OLD_FILE", HA_ERR_OLD_FILE, "" }, { "HA_ERR_NO_ACTIVE_RECORD", HA_ERR_NO_ACTIVE_RECORD, "" }, { "HA_ERR_RECORD_DELETED", HA_ERR_RECORD_DELETED, "" }, { "HA_ERR_RECORD_FILE_FULL", HA_ERR_RECORD_FILE_FULL, "" }, { "HA_ERR_INDEX_FILE_FULL", HA_ERR_INDEX_FILE_FULL, "" }, { "HA_ERR_END_OF_FILE", HA_ERR_END_OF_FILE, "" }, { "HA_ERR_UNSUPPORTED", HA_ERR_UNSUPPORTED, "" }, { "HA_ERR_TO_BIG_ROW", HA_ERR_TO_BIG_ROW, "" }, { "HA_WRONG_CREATE_OPTION", HA_WRONG_CREATE_OPTION, "" }, { "HA_ERR_FOUND_DUPP_UNIQUE", HA_ERR_FOUND_DUPP_UNIQUE, "" }, { "HA_ERR_UNKNOWN_CHARSET", HA_ERR_UNKNOWN_CHARSET, "" }, { "HA_ERR_WRONG_MRG_TABLE_DEF", HA_ERR_WRONG_MRG_TABLE_DEF, "" }, { "HA_ERR_CRASHED_ON_REPAIR", HA_ERR_CRASHED_ON_REPAIR, "" }, { "HA_ERR_CRASHED_ON_USAGE", HA_ERR_CRASHED_ON_USAGE, "" }, { "HA_ERR_LOCK_WAIT_TIMEOUT", HA_ERR_LOCK_WAIT_TIMEOUT, "" }, { "HA_ERR_LOCK_TABLE_FULL", HA_ERR_LOCK_TABLE_FULL, "" }, { "HA_ERR_READ_ONLY_TRANSACTION", HA_ERR_READ_ONLY_TRANSACTION, "" }, { "HA_ERR_LOCK_DEADLOCK", HA_ERR_LOCK_DEADLOCK, "" }, { "HA_ERR_CANNOT_ADD_FOREIGN", HA_ERR_CANNOT_ADD_FOREIGN, "" }, { "HA_ERR_NO_REFERENCED_ROW", HA_ERR_NO_REFERENCED_ROW, "" }, { "HA_ERR_ROW_IS_REFERENCED", HA_ERR_ROW_IS_REFERENCED, "" }, { "HA_ERR_NO_SAVEPOINT", HA_ERR_NO_SAVEPOINT, "" }, { "HA_ERR_NON_UNIQUE_BLOCK_SIZE", HA_ERR_NON_UNIQUE_BLOCK_SIZE, "" }, { "HA_ERR_NO_SUCH_TABLE", HA_ERR_NO_SUCH_TABLE, "" }, { "HA_ERR_TABLE_EXIST", HA_ERR_TABLE_EXIST, "" }, { "HA_ERR_NO_CONNECTION", HA_ERR_NO_CONNECTION, "" }, { "HA_ERR_NULL_IN_SPATIAL", HA_ERR_NULL_IN_SPATIAL, "" }, { "HA_ERR_TABLE_DEF_CHANGED", HA_ERR_TABLE_DEF_CHANGED, "" }, { "HA_ERR_NO_PARTITION_FOUND", HA_ERR_NO_PARTITION_FOUND, "" }, { "HA_ERR_RBR_LOGGING_FAILED", HA_ERR_RBR_LOGGING_FAILED, "" }, { "HA_ERR_DROP_INDEX_FK", HA_ERR_DROP_INDEX_FK, "" }, { "HA_ERR_FOREIGN_DUPLICATE_KEY", HA_ERR_FOREIGN_DUPLICATE_KEY, "" }, { "HA_ERR_TABLE_NEEDS_UPGRADE", HA_ERR_TABLE_NEEDS_UPGRADE, "" }, { "HA_ERR_TABLE_READONLY", HA_ERR_TABLE_READONLY, "" }, { "HA_ERR_AUTOINC_READ_FAILED", HA_ERR_AUTOINC_READ_FAILED, "" }, { "HA_ERR_AUTOINC_ERANGE", HA_ERR_AUTOINC_ERANGE, "" }, { "HA_ERR_GENERIC", HA_ERR_GENERIC, "" }, { "HA_ERR_RECORD_IS_THE_SAME", HA_ERR_RECORD_IS_THE_SAME, "" }, { "HA_ERR_LOGGING_IMPOSSIBLE", HA_ERR_LOGGING_IMPOSSIBLE, "" }, { "HA_ERR_CORRUPT_EVENT", HA_ERR_CORRUPT_EVENT, "" }, { "HA_ERR_NEW_FILE", HA_ERR_NEW_FILE, "" }, { "HA_ERR_ROWS_EVENT_APPLY", HA_ERR_ROWS_EVENT_APPLY, "" }, { "HA_ERR_INITIALIZATION", HA_ERR_INITIALIZATION, "" }, { "HA_ERR_FILE_TOO_SHORT", HA_ERR_FILE_TOO_SHORT, "" }, { "HA_ERR_WRONG_CRC", HA_ERR_WRONG_CRC, "" }, { "HA_ERR_TOO_MANY_CONCURRENT_TRXS", HA_ERR_TOO_MANY_CONCURRENT_TRXS, "" }, { "HA_ERR_INDEX_COL_TOO_LONG", HA_ERR_INDEX_COL_TOO_LONG, "" }, { "HA_ERR_INDEX_CORRUPT", HA_ERR_INDEX_CORRUPT, "" }, { "HA_ERR_UNDO_REC_TOO_BIG", HA_ERR_UNDO_REC_TOO_BIG, "" }, { "HA_ERR_ROW_NOT_VISIBLE", HA_ERR_ROW_NOT_VISIBLE, "" }, { "HA_ERR_ABORTED_BY_USER", HA_ERR_ABORTED_BY_USER, "" }, { "HA_ERR_DISK_FULL", HA_ERR_DISK_FULL, "" }, { "HA_ERR_INCOMPATIBLE_DEFINITION", HA_ERR_INCOMPATIBLE_DEFINITION, "" }, { "HA_ERR_COMMIT_ERROR", HA_ERR_COMMIT_ERROR, "" }, { "HA_ERR_PARTITION_LIST", HA_ERR_PARTITION_LIST, ""}, { "HA_ERR_NO_ENCRYPTION", HA_ERR_NO_ENCRYPTION, ""}, { "HA_ERR_ROLLBACK", HA_ERR_ROLLBACK, "" }, mysql/server/my_dbug.h000064400000023577151027430560011037 0ustar00/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. Copyright (C) 2000, 2019, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_dbug_h #define _my_dbug_h #ifndef _WIN32 #include #endif #ifdef __cplusplus extern "C" { #endif #if !defined(DBUG_OFF) && !defined(_lint) struct _db_stack_frame_ { const char *func; /* function name of the previous stack frame */ const char *file; /* filename of the function of previous frame */ uint level; /* this nesting level, highest bit enables tracing */ int line; /* line of DBUG_RETURN */ struct _db_stack_frame_ *prev; /* pointer to the previous frame */ }; struct _db_code_state_; extern my_bool _dbug_on_; extern my_bool _db_keyword_(struct _db_code_state_ *, const char *, int); extern int _db_explain_(struct _db_code_state_ *cs, char *buf, size_t len); extern int _db_explain_init_(char *buf, size_t len); extern int _db_is_pushed_(void); extern void _db_setjmp_(void); extern void _db_longjmp_(void); extern void _db_process_(const char *name); extern void _db_push_(const char *control); extern void _db_pop_(void); extern void _db_set_(const char *control); extern void _db_set_init_(const char *control); extern void _db_enter_(const char *_func_, const char *_file_, uint _line_, struct _db_stack_frame_ *_stack_frame_); extern void _db_return_(struct _db_stack_frame_ *_stack_frame_); extern int _db_pargs_(uint _line_,const char *keyword); extern void _db_doprnt_(const char *format,...) #ifdef WAITING_FOR_BUGFIX_TO_VSPRINTF ATTRIBUTE_FORMAT(printf, 1, 2) #endif ; extern void _db_dump_(uint _line_,const char *keyword, const unsigned char *memory, size_t length); extern void _db_end_(void); extern void _db_lock_file_(void); extern void _db_unlock_file_(void); ATTRIBUTE_COLD extern my_bool _db_my_assert(const char *file, int line, const char *msg); extern FILE *_db_fp_(void); extern void _db_flush_(void); extern void dbug_swap_code_state(void **code_state_store); extern void dbug_free_code_state(void **code_state_store); extern const char* _db_get_func_(void); extern int (*dbug_sanity)(void); #ifdef DBUG_TRACE #define DBUG_LEAVE do { \ _db_stack_frame_.line= __LINE__; \ _db_return_ (&_db_stack_frame_); \ _db_stack_frame_.line= 0; \ } while(0) #define DBUG_PRINT(keyword,arglist) \ do if (_db_pargs_(__LINE__,keyword)) _db_doprnt_ arglist; while(0) #ifdef HAVE_ATTRIBUTE_CLEANUP #define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_ __attribute__((cleanup(_db_return_))); \ _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_) #define DBUG_RETURN(a1) do { _db_stack_frame_.line=__LINE__; return(a1);} while(0) #define DBUG_VOID_RETURN do { _db_stack_frame_.line=__LINE__; return;} while(0) #else #define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_; \ _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_) #define DBUG_RETURN(a1) do {DBUG_LEAVE; return(a1);} while(0) #define DBUG_VOID_RETURN do {DBUG_LEAVE; return;} while(0) #endif #else #define DBUG_LEAVE #define DBUG_ENTER(a) #define DBUG_RETURN(a1) return(a1) #define DBUG_VOID_RETURN return #define DBUG_PRINT(keyword,arglist) do{} while(0) #endif #define DBUG_EXECUTE(keyword,a1) \ do {if (_db_keyword_(0, (keyword), 0)) { a1 }} while(0) #define DBUG_EXECUTE_IF(keyword,a1) \ do {if (_db_keyword_(0, (keyword), 1)) { a1 }} while(0) #define DBUG_EVALUATE(keyword,a1,a2) \ (_db_keyword_(0,(keyword), 0) ? (a1) : (a2)) #define DBUG_EVALUATE_IF(keyword,a1,a2) \ (_db_keyword_(0,(keyword), 1) ? (a1) : (a2)) #define DBUG_PUSH_EMPTY if (_dbug_on_) { DBUG_PUSH(""); } #define DBUG_POP_EMPTY if (_dbug_on_) { DBUG_POP(); } #define DBUG_PUSH(a1) _db_push_ (a1) #define DBUG_POP() _db_pop_ () #define DBUG_SET(a1) _db_set_ (a1) #define DBUG_SET_INITIAL(a1) _db_set_init_ (a1) #define DBUG_PROCESS(a1) _db_process_(a1) #define DBUG_FILE _db_fp_() #define DBUG_DUMP(keyword,a1,a2) _db_dump_(__LINE__,keyword,a1,a2) #define DBUG_END() _db_end_ () #define DBUG_LOCK_FILE _db_lock_file_() #define DBUG_UNLOCK_FILE _db_unlock_file_() #define DBUG_ASSERT(A) do { \ if (unlikely(!(A)) && _db_my_assert(__FILE__, __LINE__, #A)) assert(A); \ } while (0) #define DBUG_SLOW_ASSERT(A) DBUG_ASSERT(A) #define DBUG_ASSERT_EXISTS #define DBUG_EXPLAIN(buf,len) _db_explain_(0, (buf),(len)) #define DBUG_EXPLAIN_INITIAL(buf,len) _db_explain_init_((buf),(len)) #define DEBUGGER_OFF do { _dbug_on_= 0; } while(0) #define DEBUGGER_ON do { _dbug_on_= 1; } while(0) #define IF_DBUG(A,B) A #define IF_DBUG_ASSERT(A,B) A #define DBUG_SWAP_CODE_STATE(arg) dbug_swap_code_state(arg) #define DBUG_FREE_CODE_STATE(arg) dbug_free_code_state(arg) #undef DBUG_ASSERT_AS_PRINTF #ifndef _WIN32 #define DBUG_ABORT() (_db_flush_(), abort()) #else /* Avoid popup with abort/retry/ignore buttons. When BUG#31745 is fixed we can call abort() instead of _exit(3) (now it would cause a "test signal" popup). */ #include #define DBUG_ABORT() (_db_flush_(),\ (void)_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE),\ (void)_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR),\ TerminateProcess(GetCurrentProcess(),3)) #endif /* Make the program fail, without creating a core file. abort() will send SIGABRT which (most likely) generates core. Use SIGKILL instead, which cannot be caught. We also pause the current thread, until the signal is actually delivered. An alternative would be to use _exit(EXIT_FAILURE), but then valgrind would report lots of memory leaks. */ #ifdef _WIN32 #define DBUG_SUICIDE() DBUG_ABORT() #else extern void _db_suicide_(void); #define DBUG_SUICIDE() (_db_flush_(), _db_suicide_()) #endif /* _WIN32 */ #else /* No debugger */ #define DBUG_ENTER(a1) #define DBUG_VIOLATION_HELPER_LEAVE do { } while(0) #define DBUG_LEAVE #define DBUG_RETURN(a1) do { return(a1); } while(0) #define DBUG_VOID_RETURN do { return; } while(0) #define DBUG_PRINT(keyword, arglist) do { } while(0) #define DBUG_EXECUTE(keyword,a1) do { } while(0) #define DBUG_EXECUTE_IF(keyword,a1) do { } while(0) #define DBUG_EVALUATE(keyword,a1,a2) (a2) #define DBUG_EVALUATE_IF(keyword,a1,a2) (a2) #define DBUG_PRINT(keyword,arglist) do { } while(0) #define DBUG_PUSH_EMPTY do { } while(0) #define DBUG_POP_EMPTY do { } while(0) #define DBUG_PUSH(a1) do { } while(0) #define DBUG_SET(a1) do { } while(0) #define DBUG_SET_INITIAL(a1) do { } while(0) #define DBUG_POP() do { } while(0) #define DBUG_PROCESS(a1) do { } while(0) #define DBUG_DUMP(keyword,a1,a2) do { } while(0) #define DBUG_END() do { } while(0) #define DBUG_SLOW_ASSERT(A) do { } while(0) #define DBUG_LOCK_FILE do { } while(0) #define DBUG_FILE (stderr) #define DBUG_UNLOCK_FILE do { } while(0) #define DBUG_EXPLAIN(buf,len) #define DBUG_EXPLAIN_INITIAL(buf,len) #define DEBUGGER_OFF do { } while(0) #define DEBUGGER_ON do { } while(0) #define IF_DBUG(A,B) B #define DBUG_SWAP_CODE_STATE(arg) do { } while(0) #define DBUG_FREE_CODE_STATE(arg) do { } while(0) #define DBUG_ABORT() do { } while(0) #define DBUG_CRASH_ENTER(func) #define DBUG_CRASH_RETURN(val) do { return(val); } while(0) #define DBUG_CRASH_VOID_RETURN do { return; } while(0) #define DBUG_SUICIDE() do { } while(0) #ifdef DBUG_ASSERT_AS_PRINTF extern void (*my_dbug_assert_failed)(const char *assert_expr, const char* file, unsigned long line); #define DBUG_ASSERT(assert_expr) do { if (!(assert_expr)) { my_dbug_assert_failed(#assert_expr, __FILE__, __LINE__); }} while (0) #define DBUG_ASSERT_EXISTS #define IF_DBUG_ASSERT(A,B) A #else #define DBUG_ASSERT(A) do { } while(0) #define IF_DBUG_ASSERT(A,B) B #endif /* DBUG_ASSERT_AS_PRINTF */ #endif /* !defined(DBUG_OFF) && !defined(_lint) */ #ifdef EXTRA_DEBUG /** Sync points allow us to force the server to reach a certain line of code and block there until the client tells the server it is ok to go on. The client tells the server to block with SELECT GET_LOCK() and unblocks it with SELECT RELEASE_LOCK(). Used for debugging difficult concurrency problems */ #define DBUG_SYNC_POINT(lock_name,lock_timeout) \ debug_sync_point(lock_name,lock_timeout) void debug_sync_point(const char* lock_name, uint lock_timeout); #else #define DBUG_SYNC_POINT(lock_name,lock_timeout) #endif /* EXTRA_DEBUG */ #ifdef __cplusplus } /* DBUG_LOG() was initially intended for InnoDB. To be able to use it elsewhere one should #include . We intentionally avoid including it here to save compilation time. */ # ifdef DBUG_OFF # define DBUG_LOG(keyword, v) do {} while (0) # else # define DBUG_LOG(keyword, v) do { \ if (_db_pargs_(__LINE__, keyword)) { \ std::ostringstream _db_s; _db_s << v; \ _db_doprnt_("%s", _db_s.str().c_str()); \ }} while (0) # endif #endif #endif /* _my_dbug_h */ mysql/server/my_compiler.h000064400000012222151027430560011711 0ustar00#ifndef MY_COMPILER_INCLUDED #define MY_COMPILER_INCLUDED /* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. Copyright (c) 2017, 2022, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** Header for compiler-dependent features. Intended to contain a set of reusable wrappers for preprocessor macros, attributes, pragmas, and any other features that are specific to a target compiler. */ /** Compiler-dependent internal convenience macros. */ /* C vs C++ */ #ifdef __cplusplus #define CONSTEXPR constexpr #else #define CONSTEXPR #endif /* __cplusplus */ /* GNU C/C++ */ #if defined __GNUC__ # define MY_ALIGN_EXT /* __builtin_unreachable() removes the "statement may fall through" warning-as- error when MY_ASSERT_UNREACHABLE() is used in "case xxx:" in switch (...) statements. abort() is there to prevent the execution from reaching the __builtin_unreachable() as this may cause misleading stack traces. */ # define MY_ASSERT_UNREACHABLE() { abort(); __builtin_unreachable(); } /* Microsoft Visual C++ */ #elif defined _MSC_VER # define MY_ALIGNOF(type) __alignof(type) # define MY_ALIGNED(n) __declspec(align(n)) /* Oracle Solaris Studio */ #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) # if __SUNPRO_C >= 0x590 # define MY_ALIGN_EXT # endif /* IBM XL C/C++ */ #elif defined __xlC__ # if __xlC__ >= 0x0600 # define MY_ALIGN_EXT # endif /* HP aCC */ #elif defined(__HP_aCC) || defined(__HP_cc) # if (__HP_aCC >= 60000) || (__HP_cc >= 60000) # define MY_ALIGN_EXT # endif #endif #ifdef MY_ALIGN_EXT /** Specifies the minimum alignment of a type. */ # define MY_ALIGNOF(type) __alignof__(type) /** Determine the alignment requirement of a type. */ # define MY_ALIGNED(n) __attribute__((__aligned__((n)))) #endif /** Generic (compiler-independent) features. */ #ifndef MY_ALIGNOF # ifdef __cplusplus template struct my_alignof_helper { char m1; type m2; }; /* Invalid for non-POD types, but most compilers give the right answer. */ # define MY_ALIGNOF(type) offsetof(my_alignof_helper, m2) # else # define MY_ALIGNOF(type) offsetof(struct { char m1; type m2; }, m2) # endif #endif #ifndef MY_ASSERT_UNREACHABLE # define MY_ASSERT_UNREACHABLE() do { abort(); } while (0) #endif /** C++ Type Traits */ #ifdef __cplusplus /** Opaque storage with a particular alignment. */ # if defined(MY_ALIGNED) /* Partial specialization used due to MSVC++. */ template struct my_alignment_imp; template<> struct MY_ALIGNED(1) my_alignment_imp<1> {}; template<> struct MY_ALIGNED(2) my_alignment_imp<2> {}; template<> struct MY_ALIGNED(4) my_alignment_imp<4> {}; template<> struct MY_ALIGNED(8) my_alignment_imp<8> {}; template<> struct MY_ALIGNED(16) my_alignment_imp<16> {}; /* ... expand as necessary. */ # else template struct my_alignment_imp { double m1; }; # endif /** A POD type with a given size and alignment. @remark If the compiler does not support a alignment attribute (MY_ALIGN macro), the default alignment of a double is used instead. @tparam size The minimum size. @tparam alignment The desired alignment: 1, 2, 4, 8 or 16. */ template struct my_aligned_storage { union { char data[size]; my_alignment_imp align; }; }; #endif /* __cplusplus */ # ifndef MY_ALIGNED /* Make sure MY_ALIGNED can be used also on platforms where we don't have a way of aligning data structures. */ #define MY_ALIGNED(size) #endif #ifdef __GNUC__ # define ATTRIBUTE_NORETURN __attribute__((noreturn)) # define ATTRIBUTE_NOINLINE __attribute__((noinline)) /** Starting with GCC 4.3, the "cold" attribute is used to inform the compiler that a function is unlikely executed. The function is optimized for size rather than speed and on many targets it is placed into special subsection of the text section so all cold functions appears close together improving code locality of non-cold parts of program. The paths leading to call of cold functions within code are marked as unlikely by the branch prediction mechanism. optimize a rarely invoked function for size instead for speed. */ # define ATTRIBUTE_COLD __attribute__((cold)) #elif defined _MSC_VER # define ATTRIBUTE_NORETURN __declspec(noreturn) # define ATTRIBUTE_NOINLINE __declspec(noinline) #else # define ATTRIBUTE_NORETURN /* empty */ # define ATTRIBUTE_NOINLINE /* empty */ #endif #ifndef ATTRIBUTE_COLD # define ATTRIBUTE_COLD /* empty */ #endif #include #endif /* MY_COMPILER_INCLUDED */ mysql/server/sql_common.h000064400000012224151027430560011543 0ustar00#ifndef SQL_COMMON_INCLUDED #define SQL_COMMON_INCLUDED /* Copyright (c) 2003, 2018, Oracle and/or its affiliates. Copyright (c) 2010, 2018, MariaDB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifdef __cplusplus extern "C" { #endif #include #include extern const char *unknown_sqlstate; extern const char *cant_connect_sqlstate; extern const char *not_error_sqlstate; struct st_mysql_options_extention { char *plugin_dir; char *default_auth; char *ssl_crl; /* PEM CRL file */ char *ssl_crlpath; /* PEM directory of CRL-s? */ void (*report_progress)(const MYSQL *mysql, unsigned int stage, unsigned int max_stage, double progress, const char *proc_info, uint proc_info_length); HASH connection_attributes; size_t connection_attributes_length; my_bool tls_verify_server_cert; }; typedef struct st_mysql_methods { my_bool (*read_query_result)(MYSQL *mysql); my_bool (*advanced_command)(MYSQL *mysql, enum enum_server_command command, const unsigned char *header, unsigned long header_length, const unsigned char *arg, unsigned long arg_length, my_bool skip_check, MYSQL_STMT *stmt); MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields, unsigned int fields); MYSQL_RES * (*use_result)(MYSQL *mysql); void (*fetch_lengths)(unsigned long *to, MYSQL_ROW column, unsigned int field_count); void (*flush_use_result)(MYSQL *mysql, my_bool flush_all_results); int (*read_change_user_result)(MYSQL *mysql); void (*on_close_free)(MYSQL *mysql); #if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) MYSQL_FIELD * (*list_fields)(MYSQL *mysql); my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt); int (*stmt_execute)(MYSQL_STMT *stmt); int (*read_binary_rows)(MYSQL_STMT *stmt); int (*unbuffered_fetch)(MYSQL *mysql, char **row); const char *(*read_statistics)(MYSQL *mysql); my_bool (*next_result)(MYSQL *mysql); int (*read_rows_from_cursor)(MYSQL_STMT *stmt); #endif } MYSQL_METHODS; #ifdef LIBMARIADB #define simple_command(mysql, command, arg, length, skip_check) ma_simple_command(mysql, command, (char *)arg, length, skip_check, NULL) #else #define simple_command(mysql, command, arg, length, skip_check) \ (*(mysql)->methods->advanced_command)(mysql, command, 0, \ 0, arg, length, skip_check, NULL) #endif #define stmt_command(mysql, command, arg, length, stmt) \ (*(mysql)->methods->advanced_command)(mysql, command, 0, \ 0, arg, length, 1, stmt) extern CHARSET_INFO *default_client_charset_info; MYSQL_FIELD *unpack_fields(MYSQL *mysql, MYSQL_DATA *data,MEM_ROOT *alloc, uint fields, my_bool default_value, uint server_capabilities); void free_rows(MYSQL_DATA *cur); void free_old_query(MYSQL *mysql); void end_server(MYSQL *mysql); my_bool mysql_reconnect(MYSQL *mysql); void mysql_read_default_options(struct st_mysql_options *options, const char *filename,const char *group); my_bool cli_advanced_command(MYSQL *mysql, enum enum_server_command command, const unsigned char *header, ulong header_length, const unsigned char *arg, ulong arg_length, my_bool skip_check, MYSQL_STMT *stmt); unsigned long cli_safe_read(MYSQL *mysql); unsigned long cli_safe_read_reallen(MYSQL *mysql, ulong* reallen); void net_clear_error(NET *net); void set_stmt_errmsg(MYSQL_STMT *stmt, NET *net); void set_stmt_error(MYSQL_STMT *stmt, int errcode, const char *sqlstate, const char *err); void set_mysql_error(MYSQL *mysql, int errcode, const char *sqlstate); void set_mysql_extended_error(MYSQL *mysql, int errcode, const char *sqlstate, const char *format, ...); /* client side of the pluggable authentication */ struct st_vio; struct st_plugin_vio_info; void mpvio_info(struct st_vio *vio, struct st_plugin_vio_info *info); int run_plugin_auth(MYSQL *mysql, char *data, uint data_len, const char *data_plugin, const char *db); int mysql_client_plugin_init(); void mysql_client_plugin_deinit(); struct st_mysql_client_plugin; extern struct st_mysql_client_plugin *mysql_client_builtins[]; uchar * send_client_connect_attrs(MYSQL *mysql, uchar *buf); #ifdef __cplusplus } #endif #define protocol_41(A) ((A)->server_capabilities & CLIENT_PROTOCOL_41) #endif /* SQL_COMMON_INCLUDED */ mysql/server/big_endian.h000064400000010631151027430560011453 0ustar00/* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Data in big-endian format. */ #define float4store(T,A) do { *(T)= ((uchar *) &A)[3];\ *((T)+1)=(char) ((uchar *) &A)[2];\ *((T)+2)=(char) ((uchar *) &A)[1];\ *((T)+3)=(char) ((uchar *) &A)[0]; } while(0) #define float4get(V,M) do { float def_temp;\ ((uchar*) &def_temp)[0]=(M)[3];\ ((uchar*) &def_temp)[1]=(M)[2];\ ((uchar*) &def_temp)[2]=(M)[1];\ ((uchar*) &def_temp)[3]=(M)[0];\ (V)=def_temp; } while(0) #define float8store(T,V) do { *(T)= ((uchar *) &V)[7];\ *((T)+1)=(char) ((uchar *) &V)[6];\ *((T)+2)=(char) ((uchar *) &V)[5];\ *((T)+3)=(char) ((uchar *) &V)[4];\ *((T)+4)=(char) ((uchar *) &V)[3];\ *((T)+5)=(char) ((uchar *) &V)[2];\ *((T)+6)=(char) ((uchar *) &V)[1];\ *((T)+7)=(char) ((uchar *) &V)[0]; } while(0) #define float8get(V,M) do { double def_temp;\ ((uchar*) &def_temp)[0]=(M)[7];\ ((uchar*) &def_temp)[1]=(M)[6];\ ((uchar*) &def_temp)[2]=(M)[5];\ ((uchar*) &def_temp)[3]=(M)[4];\ ((uchar*) &def_temp)[4]=(M)[3];\ ((uchar*) &def_temp)[5]=(M)[2];\ ((uchar*) &def_temp)[6]=(M)[1];\ ((uchar*) &def_temp)[7]=(M)[0];\ (V) = def_temp; } while(0) #define ushortget(V,M) do { V = (uint16) (((uint16) ((uchar) (M)[1]))+\ ((uint16) ((uint16) (M)[0]) << 8)); } while(0) #define shortget(V,M) do { V = (short) (((short) ((uchar) (M)[1]))+\ ((short) ((short) (M)[0]) << 8)); } while(0) #define longget(V,M) do { int32 def_temp;\ ((uchar*) &def_temp)[0]=(M)[0];\ ((uchar*) &def_temp)[1]=(M)[1];\ ((uchar*) &def_temp)[2]=(M)[2];\ ((uchar*) &def_temp)[3]=(M)[3];\ (V)=def_temp; } while(0) #define ulongget(V,M) do { uint32 def_temp;\ ((uchar*) &def_temp)[0]=(M)[0];\ ((uchar*) &def_temp)[1]=(M)[1];\ ((uchar*) &def_temp)[2]=(M)[2];\ ((uchar*) &def_temp)[3]=(M)[3];\ (V)=def_temp; } while(0) #define shortstore(T,A) do { uint def_temp=(uint) (A) ;\ *(((char*)T)+1)=(char)(def_temp); \ *(((char*)T)+0)=(char)(def_temp >> 8); } while(0) #define longstore(T,A) do { *(((char*)T)+3)=((A));\ *(((char*)T)+2)=(((A) >> 8));\ *(((char*)T)+1)=(((A) >> 16));\ *(((char*)T)+0)=(((A) >> 24)); } while(0) #define floatget(V,M) memcpy(&V, (M), sizeof(float)) /* Cast away type qualifiers (necessary as macro takes argument by value). */ #define floatstore(T,V) memcpy((T), (void*) (&V), sizeof(float)) #define doubleget(V,M) memcpy(&V, (M), sizeof(double)) /* Cast away type qualifiers (necessary as macro takes argument by value). */ #define doublestore(T,V) memcpy((T), (void*) &V, sizeof(double)) #define longlongget(V,M) memcpy(&V, (M), sizeof(ulonglong)) #define longlongstore(T,V) memcpy((T), &V, sizeof(ulonglong)) mysql/server/m_ctype.h000064400000177412151027430560011047 0ustar00/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. Copyright (c) 2009, 2020, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* A better implementation of the UNIX ctype(3) library. */ #ifndef _m_ctype_h #define _m_ctype_h #include #include enum loglevel { ERROR_LEVEL= 0, WARNING_LEVEL= 1, INFORMATION_LEVEL= 2 }; #ifdef __cplusplus extern "C" { #endif #define MY_CS_NAME_SIZE 32 #define MY_CS_CTYPE_TABLE_SIZE 257 #define MY_CS_TO_LOWER_TABLE_SIZE 256 #define MY_CS_TO_UPPER_TABLE_SIZE 256 #define MY_CS_SORT_ORDER_TABLE_SIZE 256 #define MY_CS_TO_UNI_TABLE_SIZE 256 #define CHARSET_DIR "charsets/" #define my_wc_t ulong #define MY_CS_REPLACEMENT_CHARACTER 0xFFFD /** Maximum character length of a string produced by wc_to_printable(). Note, wc_to_printable() is currently limited to BMP. One non-printable or non-convertable character can produce a string with at most 5 characters: \hhhh. If we ever modify wc_to_printable() to support supplementary characters, e.g. \+hhhhhh, this constant should be changed to 8. Note, maximum octet length of a wc_to_printable() result can be calculated as: (MY_CS_PRINTABLE_CHAR_LENGTH*cs->mbminlen). */ #define MY_CS_PRINTABLE_CHAR_LENGTH 5 /* On i386 we store Unicode->CS conversion tables for some character sets using Big-endian order, to copy two bytes at once. This gives some performance improvement. */ #ifdef __i386__ #define MB2(x) (((x) >> 8) + (((x) & 0xFF) << 8)) #define MY_PUT_MB2(s, code) { *((uint16*)(s))= (code); } #else #define MB2(x) (x) #define MY_PUT_MB2(s, code) { (s)[0]= code >> 8; (s)[1]= code & 0xFF; } #endif typedef const struct my_charset_handler_st MY_CHARSET_HANDLER; typedef const struct my_collation_handler_st MY_COLLATION_HANDLER; typedef const struct unicase_info_st MY_UNICASE_INFO; typedef const struct uni_ctype_st MY_UNI_CTYPE; typedef const struct my_uni_idx_st MY_UNI_IDX; typedef uint16 decimal_digits_t; typedef struct unicase_info_char_st { uint32 toupper; uint32 tolower; uint32 sort; } MY_UNICASE_CHARACTER; struct unicase_info_st { my_wc_t maxchar; MY_UNICASE_CHARACTER **page; }; extern MY_UNICASE_INFO my_unicase_default; extern MY_UNICASE_INFO my_unicase_turkish; extern MY_UNICASE_INFO my_unicase_mysql500; extern MY_UNICASE_INFO my_unicase_unicode520; #define MY_UCA_MAX_CONTRACTION 6 /* The DUCET tables in ctype-uca.c are dumped with a limit of 8 weights per character. cs->strxfrm_multiply is set to 8 for all UCA based collations. In language-specific UCA collations (with tailorings) we also do not allow a single character to have more than 8 weights to stay with the same strxfrm_multiply limit. Note, contractions are allowed to have twice longer weight strings (up to 16 weights). As a contraction consists of at least 2 characters, this makes sure that strxfrm_multiply ratio of 8 is respected. */ #define MY_UCA_MAX_WEIGHT_SIZE (8+1) /* Including 0 terminator */ #define MY_UCA_CONTRACTION_MAX_WEIGHT_SIZE (2*8+1) /* Including 0 terminator */ #define MY_UCA_WEIGHT_LEVELS 2 typedef struct my_contraction_t { my_wc_t ch[MY_UCA_MAX_CONTRACTION]; /* Character sequence */ uint16 weight[MY_UCA_CONTRACTION_MAX_WEIGHT_SIZE];/* Its weight string, 0-terminated */ my_bool with_context; } MY_CONTRACTION; typedef struct my_contraction_list_t { size_t nitems; /* Number of items in the list */ MY_CONTRACTION *item; /* List of contractions */ char *flags; /* Character flags, e.g. "is contraction head") */ } MY_CONTRACTIONS; my_bool my_uca_can_be_contraction_head(const MY_CONTRACTIONS *c, my_wc_t wc); my_bool my_uca_can_be_contraction_tail(const MY_CONTRACTIONS *c, my_wc_t wc); uint16 *my_uca_contraction2_weight(const MY_CONTRACTIONS *c, my_wc_t wc1, my_wc_t wc2); /* Collation weights on a single level (e.g. primary, secondary, tertiary) */ typedef struct my_uca_level_info_st { my_wc_t maxchar; uchar *lengths; uint16 **weights; MY_CONTRACTIONS contractions; uint levelno; } MY_UCA_WEIGHT_LEVEL; typedef struct uca_info_st { MY_UCA_WEIGHT_LEVEL level[MY_UCA_WEIGHT_LEVELS]; /* Logical positions */ my_wc_t first_non_ignorable; my_wc_t last_non_ignorable; my_wc_t first_primary_ignorable; my_wc_t last_primary_ignorable; my_wc_t first_secondary_ignorable; my_wc_t last_secondary_ignorable; my_wc_t first_tertiary_ignorable; my_wc_t last_tertiary_ignorable; my_wc_t first_trailing; my_wc_t last_trailing; my_wc_t first_variable; my_wc_t last_variable; } MY_UCA_INFO; extern MY_UCA_INFO my_uca_v400; struct uni_ctype_st { uchar pctype; const uchar *ctype; }; extern MY_UNI_CTYPE my_uni_ctype[256]; /* wm_wc and wc_mb return codes */ #define MY_CS_ILSEQ 0 /* Wrong by sequence: wb_wc */ #define MY_CS_ILUNI 0 /* Cannot encode Unicode to charset: wc_mb */ #define MY_CS_TOOSMALL -101 /* Need at least one byte: wc_mb and mb_wc */ #define MY_CS_TOOSMALL2 -102 /* Need at least two bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL3 -103 /* Need at least three bytes: wc_mb and mb_wc */ /* These following three are currently not really used */ #define MY_CS_TOOSMALL4 -104 /* Need at least 4 bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL5 -105 /* Need at least 5 bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL6 -106 /* Need at least 6 bytes: wc_mb and mb_wc */ /* A helper macros for "need at least n bytes" */ #define MY_CS_TOOSMALLN(n) (-100-(n)) #define MY_CS_MBMAXLEN 6 /* Maximum supported mbmaxlen */ #define MY_CS_IS_TOOSMALL(rc) ((rc) >= MY_CS_TOOSMALL6 && (rc) <= MY_CS_TOOSMALL) #define MY_SEQ_INTTAIL 1 #define MY_SEQ_SPACES 2 #define MY_SEQ_NONSPACES 3 /* Skip non-space characters, including bad bytes */ /* My charsets_list flags */ #define MY_CS_COMPILED 1 /* compiled-in sets */ #define MY_CS_CONFIG 2 /* sets that have a *.conf file */ #define MY_CS_INDEX 4 /* sets listed in the Index file */ #define MY_CS_LOADED 8 /* sets that are currently loaded */ #define MY_CS_BINSORT 16 /* if binary sort order */ #define MY_CS_PRIMARY 32 /* if primary collation */ #define MY_CS_STRNXFRM 64 /* if strnxfrm is used for sort */ #define MY_CS_UNICODE 128 /* is a charset is BMP Unicode */ #define MY_CS_READY 256 /* if a charset is initialized */ #define MY_CS_AVAILABLE 512 /* If either compiled-in or loaded*/ #define MY_CS_CSSORT 1024 /* if case sensitive sort order */ #define MY_CS_HIDDEN 2048 /* don't display in SHOW */ #define MY_CS_PUREASCII 4096 /* if a charset is pure ascii */ #define MY_CS_NONASCII 8192 /* if not ASCII-compatible */ #define MY_CS_UNICODE_SUPPLEMENT 16384 /* Non-BMP Unicode characters */ #define MY_CS_LOWER_SORT 32768 /* If use lower case as weight */ #define MY_CS_STRNXFRM_BAD_NWEIGHTS 0x10000 /* strnxfrm ignores "nweights" */ #define MY_CS_NOPAD 0x20000 /* if does not ignore trailing spaces */ #define MY_CS_NON1TO1 0x40000 /* Has a complex mapping from characters to weights, e.g. contractions, expansions, ignorable characters */ #define MY_CHARSET_UNDEFINED 0 /* Character repertoire flags */ typedef enum enum_repertoire_t { MY_REPERTOIRE_NONE= 0, MY_REPERTOIRE_ASCII= 1, /* Pure ASCII U+0000..U+007F */ MY_REPERTOIRE_EXTENDED= 2, /* Extended characters: U+0080..U+FFFF */ MY_REPERTOIRE_UNICODE30= 3 /* ASCII | EXTENDED: U+0000..U+FFFF */ } my_repertoire_t; /* Flags for strxfrm */ #define MY_STRXFRM_LEVEL1 0x00000001 /* for primary weights */ #define MY_STRXFRM_LEVEL2 0x00000002 /* for secondary weights */ #define MY_STRXFRM_LEVEL3 0x00000004 /* for tertiary weights */ #define MY_STRXFRM_LEVEL4 0x00000008 /* fourth level weights */ #define MY_STRXFRM_LEVEL5 0x00000010 /* fifth level weights */ #define MY_STRXFRM_LEVEL6 0x00000020 /* sixth level weights */ #define MY_STRXFRM_LEVEL_ALL 0x0000003F /* Bit OR for the above six */ #define MY_STRXFRM_NLEVELS 6 /* Number of possible levels*/ #define MY_STRXFRM_PAD_WITH_SPACE 0x00000040 /* if pad result with spaces */ #define MY_STRXFRM_PAD_TO_MAXLEN 0x00000080 /* if pad tail(for filesort) */ #define MY_STRXFRM_DESC_LEVEL1 0x00000100 /* if desc order for level1 */ #define MY_STRXFRM_DESC_LEVEL2 0x00000200 /* if desc order for level2 */ #define MY_STRXFRM_DESC_LEVEL3 0x00000300 /* if desc order for level3 */ #define MY_STRXFRM_DESC_LEVEL4 0x00000800 /* if desc order for level4 */ #define MY_STRXFRM_DESC_LEVEL5 0x00001000 /* if desc order for level5 */ #define MY_STRXFRM_DESC_LEVEL6 0x00002000 /* if desc order for level6 */ #define MY_STRXFRM_DESC_SHIFT 8 #define MY_STRXFRM_UNUSED_00004000 0x00004000 /* for future extensions */ #define MY_STRXFRM_UNUSED_00008000 0x00008000 /* for future extensions */ #define MY_STRXFRM_REVERSE_LEVEL1 0x00010000 /* if reverse order for level1 */ #define MY_STRXFRM_REVERSE_LEVEL2 0x00020000 /* if reverse order for level2 */ #define MY_STRXFRM_REVERSE_LEVEL3 0x00040000 /* if reverse order for level3 */ #define MY_STRXFRM_REVERSE_LEVEL4 0x00080000 /* if reverse order for level4 */ #define MY_STRXFRM_REVERSE_LEVEL5 0x00100000 /* if reverse order for level5 */ #define MY_STRXFRM_REVERSE_LEVEL6 0x00200000 /* if reverse order for level6 */ #define MY_STRXFRM_REVERSE_SHIFT 16 /* Flags to strnncollsp_nchars */ /* MY_STRNNCOLLSP_NCHARS_EMULATE_TRIMMED_TRAILING_SPACES - defines if inside strnncollsp_nchars() short strings should be virtually extended to "nchars" characters by emulating trimmed trailing spaces. This flag is needed when comparing packed strings of the CHAR data type, when trailing spaces are trimmed on storage (like in InnoDB), however the actual values (after unpacking) will have those trailing spaces. If this flag is passed, strnncollsp_nchars() performs both truncating longer strings and extending shorter strings to exactly "nchars". If this flag is not passed, strnncollsp_nchars() only truncates longer strings to "nchars", but does not extend shorter strings to "nchars". */ #define MY_STRNNCOLLSP_NCHARS_EMULATE_TRIMMED_TRAILING_SPACES 1 /* Collation IDs for MariaDB that should not conflict with MySQL. We reserve 256..511, because MySQL will most likely use this range when the range 0..255 is full. We use the next 256 IDs starting from 512 and divide them into 8 chunks, 32 collations each, as follows: 512 + (0..31) for single byte collations (e.g. latin9) 512 + (32..63) reserved (e.g. for utf32le, or more single byte collations) 512 + (64..95) for utf8 512 + (96..127) for utf8mb4 512 + (128..159) for ucs2 512 + (160..192) for utf16 512 + (192..223) for utf16le 512 + (224..255) for utf32 */ #define MY_PAGE2_COLLATION_ID_8BIT 0x200 #define MY_PAGE2_COLLATION_ID_RESERVED 0x220 #define MY_PAGE2_COLLATION_ID_UTF8 0x240 #define MY_PAGE2_COLLATION_ID_UTF8MB4 0x260 #define MY_PAGE2_COLLATION_ID_UCS2 0x280 #define MY_PAGE2_COLLATION_ID_UTF16 0x2A0 #define MY_PAGE2_COLLATION_ID_UTF16LE 0x2C0 #define MY_PAGE2_COLLATION_ID_UTF32 0x2E0 struct my_uni_idx_st { uint16 from; uint16 to; const uchar *tab; }; typedef struct { uint beg; uint end; uint mb_len; } my_match_t; enum my_lex_states { MY_LEX_START, MY_LEX_CHAR, MY_LEX_IDENT, MY_LEX_IDENT_SEP, MY_LEX_IDENT_START, MY_LEX_REAL, MY_LEX_HEX_NUMBER, MY_LEX_BIN_NUMBER, MY_LEX_CMP_OP, MY_LEX_LONG_CMP_OP, MY_LEX_STRING, MY_LEX_COMMENT, MY_LEX_END, MY_LEX_OPERATOR_OR_IDENT, MY_LEX_NUMBER_IDENT, MY_LEX_INT_OR_REAL, MY_LEX_REAL_OR_POINT, MY_LEX_BOOL, MY_LEX_EOL, MY_LEX_ESCAPE, MY_LEX_LONG_COMMENT, MY_LEX_END_LONG_COMMENT, MY_LEX_SEMICOLON, MY_LEX_SET_VAR, MY_LEX_USER_END, MY_LEX_HOSTNAME, MY_LEX_SKIP, MY_LEX_USER_VARIABLE_DELIMITER, MY_LEX_SYSTEM_VAR, MY_LEX_IDENT_OR_KEYWORD, MY_LEX_IDENT_OR_HEX, MY_LEX_IDENT_OR_BIN, MY_LEX_IDENT_OR_NCHAR, MY_LEX_STRING_OR_DELIMITER, MY_LEX_MINUS_OR_COMMENT, MY_LEX_PLACEHOLDER, MY_LEX_COMMA, MY_LEX_IDENT_OR_QUALIFIED_SPECIAL_FUNC }; struct charset_info_st; typedef struct my_charset_loader_st { char error[128]; void *(*once_alloc)(size_t); void *(*malloc)(size_t); void *(*realloc)(void *, size_t); void (*free)(void *); void (*reporter)(enum loglevel, const char *format, ...); int (*add_collation)(struct charset_info_st *cs); } MY_CHARSET_LOADER; extern int (*my_string_stack_guard)(int); /* See strings/CHARSET_INFO.txt for information about this structure */ struct my_collation_handler_st { my_bool (*init)(struct charset_info_st *, MY_CHARSET_LOADER *); /* Collation routines */ int (*strnncoll)(CHARSET_INFO *, const uchar *, size_t, const uchar *, size_t, my_bool); int (*strnncollsp)(CHARSET_INFO *, const uchar *, size_t, const uchar *, size_t); /* strnncollsp_nchars() - similar to strnncollsp() but assumes that both strings were originally CHAR(N) values with the same N, then were optionally space-padded, or optionally space-trimmed. In other words, this function compares in the way if we insert both values into a CHAR(N) column and then compare the two column values. It compares the same amount of characters from the two strings. This is especially important for NOPAD collations. If CHAR_LENGTH of the two strings are different, the shorter string is virtually padded with trailing spaces up to CHAR_LENGTH of the longer string, to guarantee that the same amount of characters are compared. This is important if the two CHAR(N) strings are space-trimmed (e.g. like in InnoDB compact format for CHAR). The function compares not more than "nchars" characters only. This can be useful to compare CHAR(N) space-padded strings (when the exact N is known) without having to truncate them before the comparison. For example, Field_string stores a "CHAR(3) CHARACTER SET utf8mb4" value of "aaa" as 12 bytes in a record buffer: - 3 bytes of the actual data, followed by - 9 bytes of spaces (just fillers, not real data) The caller can pass nchars=3 to compare CHAR(3) record values. In such case, the comparator won't go inside the 9 bytes of the fillers. If N is not known, the caller can pass max(len1,len2) as the "nchars" value (i.e. the maximum of the OCTET_LENGTH of the two strings). Notes on complex collations. This function counts contraction parts as individual characters. For example, the Czech letter 'ch' (in Czech collations) is ordinarily counted by the "nchars" limit as TWO characters (although it is only one letter). This corresponds to what CHAR(N) does in INSERT. If the "nchars" limit tears apart a contraction, only the part fitting into "nchars" characters is used. For example, in case of a Czech collation, the string "ach" with nchars=2 is compared as 'ac': the contraction 'ch' is torn apart and the letter 'c' acts as an individual character. This emulates the same comparison result with the scenario when we insert 'ach' into a CHAR(2) column and then compare it. */ int (*strnncollsp_nchars)(CHARSET_INFO *, const uchar *str1, size_t len1, const uchar *str2, size_t len2, size_t nchars, uint flags); size_t (*strnxfrm)(CHARSET_INFO *, uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags); size_t (*strnxfrmlen)(CHARSET_INFO *, size_t); my_bool (*like_range)(CHARSET_INFO *, const char *s, size_t s_length, pchar w_prefix, pchar w_one, pchar w_many, size_t res_length, char *min_str, char *max_str, size_t *min_len, size_t *max_len); int (*wildcmp)(CHARSET_INFO *, const char *str,const char *str_end, const char *wildstr,const char *wildend, int escape,int w_one, int w_many); int (*strcasecmp)(CHARSET_INFO *, const char *, const char *); uint (*instr)(CHARSET_INFO *, const char *b, size_t b_length, const char *s, size_t s_length, my_match_t *match, uint nmatch); /* Hash calculation */ void (*hash_sort)(CHARSET_INFO *cs, const uchar *key, size_t len, ulong *nr1, ulong *nr2); my_bool (*propagate)(CHARSET_INFO *cs, const uchar *str, size_t len); /* Make minimum and maximum strings for the collation. Put not more than "nchars" characters. */ size_t (*min_str)(CHARSET_INFO *cs, uchar *dst, size_t dstlen, size_t nchars); size_t (*max_str)(CHARSET_INFO *cs, uchar *dst, size_t dstlen, size_t nchars); }; extern MY_COLLATION_HANDLER my_collation_8bit_bin_handler; extern MY_COLLATION_HANDLER my_collation_8bit_simple_ci_handler; extern MY_COLLATION_HANDLER my_collation_8bit_nopad_bin_handler; extern MY_COLLATION_HANDLER my_collation_8bit_simple_nopad_ci_handler; /* Some typedef to make it easy for C++ to make function pointers */ typedef int (*my_charset_conv_mb_wc)(CHARSET_INFO *, my_wc_t *, const uchar *, const uchar *); typedef int (*my_charset_conv_wc_mb)(CHARSET_INFO *, my_wc_t, uchar *, uchar *); typedef size_t (*my_charset_conv_case)(CHARSET_INFO *, const char *, size_t, char *, size_t); /* A structure to return the statistics of a native string copying, when no Unicode conversion is involved. The structure is OK to be uninitialized before calling a copying routine. A copying routine must populate the structure as follows: - m_source_end_pos must be set by to a non-NULL value in the range of the input string. - m_well_formed_error_pos must be set to NULL if the string was well formed, or to the position of the leftmost bad byte sequence. */ typedef struct { const char *m_source_end_pos; /* Position where reading stopped */ const char *m_well_formed_error_pos; /* Position where a bad byte was found*/ } MY_STRCOPY_STATUS; /* A structure to return the statistics of a Unicode string conversion. */ typedef struct { const char *m_cannot_convert_error_pos; } MY_STRCONV_STATUS; /* See strings/CHARSET_INFO.txt about information on this structure */ struct my_charset_handler_st { my_bool (*init)(struct charset_info_st *, MY_CHARSET_LOADER *loader); /* Multibyte routines */ size_t (*numchars)(CHARSET_INFO *, const char *b, const char *e); size_t (*charpos)(CHARSET_INFO *, const char *b, const char *e, size_t pos); size_t (*lengthsp)(CHARSET_INFO *, const char *ptr, size_t length); size_t (*numcells)(CHARSET_INFO *, const char *b, const char *e); /* Unicode conversion */ my_charset_conv_mb_wc mb_wc; my_charset_conv_wc_mb wc_mb; /* CTYPE scanner */ int (*ctype)(CHARSET_INFO *cs, int *ctype, const uchar *s, const uchar *e); /* Functions for case and sort conversion */ size_t (*caseup_str)(CHARSET_INFO *, char *); size_t (*casedn_str)(CHARSET_INFO *, char *); my_charset_conv_case caseup; my_charset_conv_case casedn; /* Charset dependent snprintf() */ size_t (*snprintf)(CHARSET_INFO *, char *to, size_t n, const char *fmt, ...) ATTRIBUTE_FORMAT_FPTR(printf, 4, 5); size_t (*long10_to_str)(CHARSET_INFO *, char *to, size_t n, int radix, long int val); size_t (*longlong10_to_str)(CHARSET_INFO *, char *to, size_t n, int radix, longlong val); void (*fill)(CHARSET_INFO *, char *to, size_t len, int fill); /* String-to-number conversion routines */ long (*strntol)(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); ulong (*strntoul)(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); longlong (*strntoll)(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); ulonglong (*strntoull)(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); double (*strntod)(CHARSET_INFO *, char *s, size_t l, char **e, int *err); longlong (*strtoll10)(CHARSET_INFO *cs, const char *nptr, char **endptr, int *error); ulonglong (*strntoull10rnd)(CHARSET_INFO *cs, const char *str, size_t length, int unsigned_fl, char **endptr, int *error); size_t (*scan)(CHARSET_INFO *, const char *b, const char *e, int sq); /* String copying routines and helpers for them */ /* charlen() - calculate length of the left-most character in bytes. @param cs Character set @param str The beginning of the string @param end The end of the string @return MY_CS_ILSEQ if a bad byte sequence was found. @return MY_CS_TOOSMALLN(x) if the string ended unexpectedly. @return a positive number in the range 1..mbmaxlen, if a valid character was found. */ int (*charlen)(CHARSET_INFO *cs, const uchar *str, const uchar *end); /* well_formed_char_length() - returns character length of a string. @param cs Character set @param str The beginning of the string @param end The end of the string @param nchars Not more than "nchars" left-most characters are checked. @param status[OUT] Additional statistics is returned here. "status" can be uninitialized before the call, and it is fully initialized after the call. status->m_source_end_pos is set to the position where reading stopped. If a bad byte sequence is found, the function returns immediately and status->m_well_formed_error_pos is set to the position where a bad byte sequence was found. status->m_well_formed_error_pos is set to NULL if no bad bytes were found. If status->m_well_formed_error_pos is NULL after the call, that means: - either the function reached the end of the string, - or all "nchars" characters were read. The caller can check status->m_source_end_pos to detect which of these two happened. */ size_t (*well_formed_char_length)(CHARSET_INFO *cs, const char *str, const char *end, size_t nchars, MY_STRCOPY_STATUS *status); /* copy_fix() - copy a string, replace bad bytes to '?'. Not more than "nchars" characters are copied. status->m_source_end_pos is set to a position in the range between "src" and "src + src_length", where reading stopped. status->m_well_formed_error_pos is set to NULL if the string in the range "src" and "status->m_source_end_pos" was well formed, or is set to a position between "src" and "src + src_length" where the leftmost bad byte sequence was found. */ size_t (*copy_fix)(CHARSET_INFO *, char *dst, size_t dst_length, const char *src, size_t src_length, size_t nchars, MY_STRCOPY_STATUS *status); /** Write a character to the target string, using its native code. For Unicode character sets (utf8, ucs2, utf16, utf16le, utf32, filename) native codes are equivalent to Unicode code points. For 8bit character sets the native code is just the byte value. For Asian characters sets: - MB1 native code is just the byte value (e.g. on the ASCII range) - MB2 native code is ((b0 << 8) + b1). - MB3 native code is ((b0 <<16) + (b1 << 8) + b2) Note, CHARSET_INFO::min_sort_char and CHARSET_INFO::max_sort_char are defined in native notation and should be written using my_ci_native_to_mb() rather than my_ci_wc_mb(). */ my_charset_conv_wc_mb native_to_mb; my_charset_conv_wc_mb wc_to_printable; }; extern MY_CHARSET_HANDLER my_charset_8bit_handler; extern MY_CHARSET_HANDLER my_charset_ucs2_handler; extern MY_CHARSET_HANDLER my_charset_utf8mb3_handler; /* We define this CHARSET_INFO_DEFINED here to prevent a repeat of the typedef in hash.c, which will cause a compiler error. */ #define CHARSET_INFO_DEFINED /* See strings/CHARSET_INFO.txt about information on this structure */ struct charset_info_st { uint number; uint primary_number; uint binary_number; uint state; LEX_CSTRING cs_name; LEX_CSTRING coll_name; const char *comment; const char *tailoring; const uchar *m_ctype; const uchar *to_lower; const uchar *to_upper; const uchar *sort_order; MY_UCA_INFO *uca; const uint16 *tab_to_uni; MY_UNI_IDX *tab_from_uni; MY_UNICASE_INFO *caseinfo; const uchar *state_map; const uchar *ident_map; uint strxfrm_multiply; uchar caseup_multiply; uchar casedn_multiply; uint mbminlen; uint mbmaxlen; /* min_sort_char and max_sort_char represent the minimum and the maximum character in the collation respectively. For Unicode collations, these numbers are Unicode code points. For non-Unicode collations these numbers are native character codes. For example, in all 8bit collations these numbers are in the range 0x00..0xFF. min_sort_char and max_sort_char normally should not be used directly. They are used internally in the following virtual functions: - MY_COLLATION_HANDLER::like_range() - MY_COLLATION_HANDLER::min_str() - MY_COLLATION_HANDLER::max_str() */ my_wc_t min_sort_char; my_wc_t max_sort_char; uchar pad_char; my_bool escape_with_backslash_is_dangerous; uchar levels_for_order; MY_CHARSET_HANDLER *cset; MY_COLLATION_HANDLER *coll; #ifdef __cplusplus /* Character set routines */ bool use_mb() const { return mbmaxlen > 1; } size_t numchars(const char *b, const char *e) const { return (cset->numchars)(this, b, e); } size_t charpos(const char *b, const char *e, size_t pos) const { return (cset->charpos)(this, b, e, pos); } size_t charpos(const uchar *b, const uchar *e, size_t pos) const { return (cset->charpos)(this, (const char *) b, (const char*) e, pos); } size_t lengthsp(const char *str, size_t length) const { return (cset->lengthsp)(this, str, length); } size_t numcells(const char *b, const char *e) const { return (cset->numcells)(this, b, e); } size_t caseup(const char *src, size_t srclen, char *dst, size_t dstlen) const { return (cset->caseup)(this, src, srclen, dst, dstlen); } size_t casedn(const char *src, size_t srclen, char *dst, size_t dstlen) const { return (cset->casedn)(this, src, srclen, dst, dstlen); } size_t long10_to_str(char *dst, size_t dstlen, int radix, long int val) const { return (cset->long10_to_str)(this, dst, dstlen, radix, val); } size_t (longlong10_to_str)(char *dst, size_t dstlen, int radix, longlong val) const { return (cset->longlong10_to_str)(this, dst, dstlen, radix, val); } int mb_wc(my_wc_t *wc, const uchar *b, const uchar *e) const { return (cset->mb_wc)(this, wc, b, e); } int wc_mb(my_wc_t wc, uchar *s, uchar *e) const { return (cset->wc_mb)(this, wc, s, e); } int native_to_mb(my_wc_t wc, uchar *s, uchar *e) const { return (cset->native_to_mb)(this, wc, s, e); } int wc_to_printable(my_wc_t wc, uchar *s, uchar *e) const { return (cset->wc_to_printable)(this, wc, s, e); } int ctype(int *to, const uchar *s, const uchar *e) const { return (cset->ctype)(this, to, s, e); } void fill(char *to, size_t len, int ch) const { (cset->fill)(this, to, len, ch); } long strntol(const char *str, size_t length, int base, char **endptr, int *error) const { return (cset->strntol)(this, str, length, base, endptr, error); } ulong strntoul(const char *str, size_t length, int base, char **endptr, int *error) const { return (cset->strntoul)(this, str, length, base, endptr, error); } longlong strntoll(const char *str, size_t length, int base, char **endptr, int *error) const { return (cset->strntoll)(this, str, length, base, endptr, error); } ulonglong strntoull(const char *str, size_t length, int base, char **endptr, int *error) const { return (cset->strntoull)(this, str, length, base, endptr, error); } double strntod(char *str, size_t length, char **endptr, int *error) const { return (cset->strntod)(this, str, length, endptr, error); } longlong strtoll10(const char *str, char **endptr, int *error) const { return (cset->strtoll10)(this, str, endptr, error); } ulonglong strntoull10rnd(const char *str, size_t length, int unsigned_fl, char **endptr, int *error) const { return (cset->strntoull10rnd)(this, str, length, unsigned_fl, endptr, error); } size_t scan(const char *b, const char *e, int seq) const { return (cset->scan)(this, b, e, seq); } int charlen(const uchar *str, const uchar *end) const { return (cset->charlen)(this, str, end); } int charlen(const char *str, const char *end) const { return (cset->charlen)(this, (const uchar *) str, (const uchar *) end); } uint charlen_fix(const uchar *str, const uchar *end) const { int char_length= (cset->charlen)(this, str, end); DBUG_ASSERT(str < end); return char_length > 0 ? (uint) char_length : (uint) 1U; } uint charlen_fix(const char *str, const char *end) const { return charlen_fix((const uchar *) str, (const uchar *) end); } size_t well_formed_char_length(const char *str, const char *end, size_t nchars, MY_STRCOPY_STATUS *status) const { return (cset->well_formed_char_length)(this, str, end, nchars, status); } size_t copy_fix(char *dst, size_t dst_length, const char *src, size_t src_length, size_t nchars, MY_STRCOPY_STATUS *status) const { return (cset->copy_fix)(this, dst, dst_length, src, src_length, nchars, status); } /* Collation routines */ int strnncoll(const uchar *a, size_t alen, const uchar *b, size_t blen, my_bool b_is_prefix= FALSE) const { return (coll->strnncoll)(this, a, alen, b, blen, b_is_prefix); } int strnncoll(const char *a, size_t alen, const char *b, size_t blen, my_bool b_is_prefix= FALSE) const { return (coll->strnncoll)(this, (const uchar *) a, alen, (const uchar *) b, blen, b_is_prefix); } int strnncollsp(const uchar *a, size_t alen, const uchar *b, size_t blen) const { return (coll->strnncollsp)(this, a, alen, b, blen); } int strnncollsp(const char *a, size_t alen, const char *b, size_t blen) const { return (coll->strnncollsp)(this, (uchar *) a, alen, (uchar *) b, blen); } int strnncollsp(const LEX_CSTRING &a, const LEX_CSTRING &b) const { return (coll->strnncollsp)(this, (uchar *) a.str, a.length, (uchar *) b.str, b.length); } size_t strnxfrm(char *dst, size_t dstlen, uint nweights, const char *src, size_t srclen, uint flags) const { return (coll->strnxfrm)(this, (uchar *) dst, dstlen, nweights, (const uchar *) src, srclen, flags); } size_t strnxfrm(uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags) const { return (coll->strnxfrm)(this, dst, dstlen, nweights, src, srclen, flags); } size_t strnxfrm(uchar *dst, size_t dstlen, const uchar *src, size_t srclen) const { return (coll->strnxfrm)(this, dst, dstlen, (uint) dstlen, src, srclen, MY_STRXFRM_PAD_WITH_SPACE); } size_t strnxfrmlen(size_t length) const { return (coll->strnxfrmlen)(this, length); } my_bool like_range(const char *s, size_t s_length, pchar w_prefix, pchar w_one, pchar w_many, size_t res_length, char *min_str, char *max_str, size_t *min_len, size_t *max_len) const { return (coll->like_range)(this, s, s_length, w_prefix, w_one, w_many, res_length, min_str, max_str, min_len, max_len); } int wildcmp(const char *str,const char *str_end, const char *wildstr,const char *wildend, int escape,int w_one, int w_many) const { return (coll->wildcmp)(this, str, str_end, wildstr, wildend, escape, w_one, w_many); } uint instr(const char *b, size_t b_length, const char *s, size_t s_length, my_match_t *match, uint nmatch) const { return (coll->instr)(this, b, b_length, s, s_length, match, nmatch); } void hash_sort(const uchar *key, size_t len, ulong *nr1, ulong *nr2) const { (coll->hash_sort)(this, key, len, nr1, nr2); } my_bool propagate(const uchar *str, size_t len) const { return (coll->propagate)(this, str, len); } size_t min_str(uchar *dst, size_t dstlen, size_t nchars) const { return (coll->min_str)(this, dst, dstlen, nchars); } size_t max_str(uchar *dst, size_t dstlen, size_t nchars) const { return (coll->max_str)(this, dst, dstlen, nchars); } #endif /* __cplusplus */ }; /* Character set routines */ static inline my_bool my_ci_init_charset(struct charset_info_st *ci, MY_CHARSET_LOADER *loader) { if (!ci->cset->init) return FALSE; return (ci->cset->init)(ci, loader); } static inline my_bool my_ci_use_mb(CHARSET_INFO *ci) { return ci->mbmaxlen > 1 ? TRUE : FALSE; } static inline size_t my_ci_numchars(CHARSET_INFO *cs, const char *b, const char *e) { return (cs->cset->numchars)(cs, b, e); } static inline size_t my_ci_charpos(CHARSET_INFO *cs, const char *b, const char *e, size_t pos) { return (cs->cset->charpos)(cs, b, e, pos); } static inline size_t my_ci_lengthsp(CHARSET_INFO *cs, const char *str, size_t length) { return (cs->cset->lengthsp)(cs, str, length); } static inline size_t my_ci_numcells(CHARSET_INFO *cs, const char *b, const char *e) { return (cs->cset->numcells)(cs, b, e); } static inline size_t my_ci_caseup(CHARSET_INFO *ci, const char *src, size_t srclen, char *dst, size_t dstlen) { return (ci->cset->caseup)(ci, src, srclen, dst, dstlen); } static inline size_t my_ci_casedn(CHARSET_INFO *ci, const char *src, size_t srclen, char *dst, size_t dstlen) { return (ci->cset->casedn)(ci, src, srclen, dst, dstlen); } static inline size_t my_ci_long10_to_str(CHARSET_INFO *cs, char *dst, size_t dstlen, int radix, long int val) { return (cs->cset->long10_to_str)(cs, dst, dstlen, radix, val); } static inline size_t my_ci_longlong10_to_str(CHARSET_INFO *cs, char *dst, size_t dstlen, int radix, longlong val) { return (cs->cset->longlong10_to_str)(cs, dst, dstlen, radix, val); } #define my_ci_mb_wc(s, pwc, b, e) ((s)->cset->mb_wc)(s, pwc, b, e) #define my_ci_wc_mb(s, wc, b, e) ((s)->cset->wc_mb)(s, wc, b, e) #define my_ci_native_to_mb(s, wc, b, e) ((s)->cset->native_to_mb)(s, wc, b, e) #define my_ci_ctype(s, pctype, b, e) ((s)->cset->ctype)(s, pctype, b, e) static inline void my_ci_fill(CHARSET_INFO *cs, char *to, size_t len, int ch) { (cs->cset->fill)(cs, to, len, ch); } static inline long my_ci_strntol(CHARSET_INFO *cs, const char *str, size_t length, int base, char **endptr, int *error) { return (cs->cset->strntol)(cs, str, length, base, endptr, error); } static inline ulong my_ci_strntoul(CHARSET_INFO *cs, const char *str, size_t length, int base, char **endptr, int *error) { return (cs->cset->strntoul)(cs, str, length, base, endptr, error); } static inline longlong my_ci_strntoll(CHARSET_INFO *cs, const char *str, size_t length, int base, char **endptr, int *error) { return (cs->cset->strntoll)(cs, str, length, base, endptr, error); } static inline ulonglong my_ci_strntoull(CHARSET_INFO *cs, const char *str, size_t length, int base, char **endptr, int *error) { return (cs->cset->strntoull)(cs, str, length, base, endptr, error); } static inline double my_ci_strntod(CHARSET_INFO *cs, char *str, size_t length, char **endptr, int *error) { return (cs->cset->strntod)(cs, str, length, endptr, error); } static inline longlong my_ci_strtoll10(CHARSET_INFO *cs, const char *str, char **endptr, int *error) { return (cs->cset->strtoll10)(cs, str, endptr, error); } static inline ulonglong my_ci_strntoull10rnd(CHARSET_INFO *cs, const char *str, size_t length, int unsigned_fl, char **endptr, int *error) { return (cs->cset->strntoull10rnd)(cs, str, length, unsigned_fl, endptr, error); } static inline size_t my_ci_scan(CHARSET_INFO *cs, const char *b, const char *e, int seq) { return (cs->cset->scan)(cs, b, e, seq); } /** Return length of the leftmost character in a string. @param cs - character set @param str - the beginning of the string @param end - the string end (the next byte after the string) @return <=0 on errors (EOL, wrong byte sequence) @return 1 on a single byte character @return >1 on a multi-byte character Note, inlike my_ismbchar(), 1 is returned for a single byte character. */ static inline int my_ci_charlen(CHARSET_INFO *cs, const uchar *str, const uchar *end) { return (cs->cset->charlen)(cs, str, end); } static inline size_t my_ci_well_formed_char_length(CHARSET_INFO *cs, const char *str, const char *end, size_t nchars, MY_STRCOPY_STATUS *status) { return (cs->cset->well_formed_char_length)(cs, str, end, nchars, status); } static inline size_t my_ci_copy_fix(CHARSET_INFO *cs, char *dst, size_t dst_length, const char *src, size_t src_length, size_t nchars, MY_STRCOPY_STATUS *status) { return (cs->cset->copy_fix)(cs, dst, dst_length, src, src_length, nchars, status); } /* Collation routines */ static inline my_bool my_ci_init_collation(struct charset_info_st *ci, MY_CHARSET_LOADER *loader) { if (!ci->coll->init) return FALSE; return (ci->coll->init)(ci, loader); } static inline int my_ci_strnncoll(CHARSET_INFO *ci, const uchar *a, size_t alen, const uchar *b, size_t blen, my_bool b_is_prefix) { return (ci->coll->strnncoll)(ci, a, alen, b, blen, b_is_prefix); } static inline int my_ci_strnncollsp(CHARSET_INFO *ci, const uchar *a, size_t alen, const uchar *b, size_t blen) { return (ci->coll->strnncollsp)(ci, a, alen, b, blen); } static inline my_bool my_ci_like_range(CHARSET_INFO *ci, const char *s, size_t s_length, pchar w_prefix, pchar w_one, pchar w_many, size_t res_length, char *min_str, char *max_str, size_t *min_len, size_t *max_len) { return (ci->coll->like_range)(ci, s, s_length, w_prefix, w_one, w_many, res_length, min_str, max_str, min_len, max_len); } static inline uint my_ci_instr(CHARSET_INFO *ci, const char *b, size_t b_length, const char *s, size_t s_length, my_match_t *match, uint nmatch) { return (ci->coll->instr)(ci, b, b_length, s, s_length, match, nmatch); } static inline void my_ci_hash_sort(CHARSET_INFO *ci, const uchar *key, size_t len, ulong *nr1, ulong *nr2) { (ci->coll->hash_sort)(ci, key, len, nr1, nr2); } #define ILLEGAL_CHARSET_INFO_NUMBER (~0U) extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_bin; extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_latin1; extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_latin1_nopad; extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_filename; extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_utf8mb3_general_ci; extern struct charset_info_st my_charset_big5_bin; extern struct charset_info_st my_charset_big5_chinese_ci; extern struct charset_info_st my_charset_big5_nopad_bin; extern struct charset_info_st my_charset_big5_chinese_nopad_ci; extern struct charset_info_st my_charset_cp1250_czech_cs; extern struct charset_info_st my_charset_cp932_bin; extern struct charset_info_st my_charset_cp932_japanese_ci; extern struct charset_info_st my_charset_cp932_nopad_bin; extern struct charset_info_st my_charset_cp932_japanese_nopad_ci; extern struct charset_info_st my_charset_eucjpms_bin; extern struct charset_info_st my_charset_eucjpms_japanese_ci; extern struct charset_info_st my_charset_eucjpms_nopad_bin; extern struct charset_info_st my_charset_eucjpms_japanese_nopad_ci; extern struct charset_info_st my_charset_euckr_bin; extern struct charset_info_st my_charset_euckr_korean_ci; extern struct charset_info_st my_charset_euckr_nopad_bin; extern struct charset_info_st my_charset_euckr_korean_nopad_ci; extern struct charset_info_st my_charset_gb2312_bin; extern struct charset_info_st my_charset_gb2312_chinese_ci; extern struct charset_info_st my_charset_gb2312_nopad_bin; extern struct charset_info_st my_charset_gb2312_chinese_nopad_ci; extern struct charset_info_st my_charset_gbk_bin; extern struct charset_info_st my_charset_gbk_chinese_ci; extern struct charset_info_st my_charset_gbk_nopad_bin; extern struct charset_info_st my_charset_gbk_chinese_nopad_ci; extern struct charset_info_st my_charset_latin1_bin; extern struct charset_info_st my_charset_latin1_nopad_bin; extern struct charset_info_st my_charset_latin1_german2_ci; extern struct charset_info_st my_charset_latin2_czech_cs; extern struct charset_info_st my_charset_sjis_bin; extern struct charset_info_st my_charset_sjis_japanese_ci; extern struct charset_info_st my_charset_sjis_nopad_bin; extern struct charset_info_st my_charset_sjis_japanese_nopad_ci; extern struct charset_info_st my_charset_tis620_bin; extern struct charset_info_st my_charset_tis620_thai_ci; extern struct charset_info_st my_charset_tis620_nopad_bin; extern struct charset_info_st my_charset_tis620_thai_nopad_ci; extern struct charset_info_st my_charset_ucs2_bin; extern struct charset_info_st my_charset_ucs2_general_ci; extern struct charset_info_st my_charset_ucs2_nopad_bin; extern struct charset_info_st my_charset_ucs2_general_nopad_ci; extern struct charset_info_st my_charset_ucs2_general_mysql500_ci; extern struct charset_info_st my_charset_ucs2_unicode_ci; extern struct charset_info_st my_charset_ucs2_unicode_nopad_ci; extern struct charset_info_st my_charset_ucs2_general_mysql500_ci; extern struct charset_info_st my_charset_ujis_bin; extern struct charset_info_st my_charset_ujis_japanese_ci; extern struct charset_info_st my_charset_ujis_nopad_bin; extern struct charset_info_st my_charset_ujis_japanese_nopad_ci; extern struct charset_info_st my_charset_utf16_bin; extern struct charset_info_st my_charset_utf16_general_ci; extern struct charset_info_st my_charset_utf16_unicode_ci; extern struct charset_info_st my_charset_utf16_unicode_nopad_ci; extern struct charset_info_st my_charset_utf16le_bin; extern struct charset_info_st my_charset_utf16le_general_ci; extern struct charset_info_st my_charset_utf16_general_nopad_ci; extern struct charset_info_st my_charset_utf16_nopad_bin; extern struct charset_info_st my_charset_utf16le_nopad_bin; extern struct charset_info_st my_charset_utf16le_general_nopad_ci; extern struct charset_info_st my_charset_utf32_bin; extern struct charset_info_st my_charset_utf32_general_ci; extern struct charset_info_st my_charset_utf32_unicode_ci; extern struct charset_info_st my_charset_utf32_unicode_nopad_ci; extern struct charset_info_st my_charset_utf32_nopad_bin; extern struct charset_info_st my_charset_utf32_general_nopad_ci; extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_utf8mb3_bin; extern struct charset_info_st my_charset_utf8mb3_nopad_bin; extern struct charset_info_st my_charset_utf8mb3_general_nopad_ci; extern struct charset_info_st my_charset_utf8mb3_general_mysql500_ci; extern struct charset_info_st my_charset_utf8mb3_unicode_ci; extern struct charset_info_st my_charset_utf8mb3_unicode_nopad_ci; extern MYSQL_PLUGIN_IMPORT struct charset_info_st my_charset_utf8mb4_bin; extern struct charset_info_st my_charset_utf8mb4_general_ci; extern struct charset_info_st my_charset_utf8mb4_nopad_bin; extern struct charset_info_st my_charset_utf8mb4_general_nopad_ci; extern struct charset_info_st my_charset_utf8mb4_unicode_ci; extern struct charset_info_st my_charset_utf8mb4_unicode_nopad_ci; #define MY_UTF8MB3 "utf8mb3" #define MY_UTF8MB4 "utf8mb4" my_bool my_cs_have_contractions(CHARSET_INFO *cs); my_bool my_cs_can_be_contraction_head(CHARSET_INFO *cs, my_wc_t wc); my_bool my_cs_can_be_contraction_tail(CHARSET_INFO *cs, my_wc_t wc); const uint16 *my_cs_contraction2_weight(CHARSET_INFO *cs, my_wc_t wc1, my_wc_t wc2); /* declarations for simple charsets */ extern size_t my_strnxfrm_simple(CHARSET_INFO *, uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags); size_t my_strnxfrmlen_simple(CHARSET_INFO *, size_t); extern int my_strnncoll_simple(CHARSET_INFO *, const uchar *, size_t, const uchar *, size_t, my_bool); extern int my_strnncollsp_simple(CHARSET_INFO *, const uchar *, size_t, const uchar *, size_t); extern void my_hash_sort_simple(CHARSET_INFO *cs, const uchar *key, size_t len, ulong *nr1, ulong *nr2); extern void my_hash_sort_simple_nopad(CHARSET_INFO *cs, const uchar *key, size_t len, ulong *nr1, ulong *nr2); extern void my_hash_sort_bin(CHARSET_INFO *cs, const uchar *key, size_t len, ulong *nr1, ulong *nr2); /** Compare a string to an array of spaces, for PAD SPACE comparison. The function iterates through the string and compares every byte to 0x20. @param - the string @param - its length @return <0 - if a byte less than 0x20 was found in the string. @return 0 - if all bytes in the string were 0x20, or if length was 0. @return >0 - if a byte greater than 0x20 was found in the string. */ extern int my_strnncollsp_padspace_bin(const uchar *str, size_t length); extern size_t my_lengthsp_8bit(CHARSET_INFO *cs, const char *ptr, size_t length); extern uint my_instr_simple(CHARSET_INFO *, const char *b, size_t b_length, const char *s, size_t s_length, my_match_t *match, uint nmatch); size_t my_copy_8bit(CHARSET_INFO *, char *dst, size_t dst_length, const char *src, size_t src_length, size_t nchars, MY_STRCOPY_STATUS *); size_t my_copy_fix_mb(CHARSET_INFO *cs, char *dst, size_t dst_length, const char *src, size_t src_length, size_t nchars, MY_STRCOPY_STATUS *); /* Functions for 8bit */ extern size_t my_caseup_str_8bit(CHARSET_INFO *, char *); extern size_t my_casedn_str_8bit(CHARSET_INFO *, char *); extern size_t my_caseup_8bit(CHARSET_INFO *, const char *src, size_t srclen, char *dst, size_t dstlen); extern size_t my_casedn_8bit(CHARSET_INFO *, const char *src, size_t srclen, char *dst, size_t dstlen); extern int my_strcasecmp_8bit(CHARSET_INFO * cs, const char *, const char *); int my_mb_wc_8bit(CHARSET_INFO *cs,my_wc_t *wc, const uchar *s,const uchar *e); int my_wc_mb_8bit(CHARSET_INFO *cs,my_wc_t wc, uchar *s, uchar *e); int my_wc_mb_bin(CHARSET_INFO *cs,my_wc_t wc, uchar *s, uchar *e); int my_mb_ctype_8bit(CHARSET_INFO *,int *, const uchar *,const uchar *); int my_mb_ctype_mb(CHARSET_INFO *,int *, const uchar *,const uchar *); size_t my_scan_8bit(CHARSET_INFO *cs, const char *b, const char *e, int sq); size_t my_snprintf_8bit(CHARSET_INFO *, char *to, size_t n, const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 4, 5); long my_strntol_8bit(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); ulong my_strntoul_8bit(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); longlong my_strntoll_8bit(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); ulonglong my_strntoull_8bit(CHARSET_INFO *, const char *s, size_t l, int base, char **e, int *err); double my_strntod_8bit(CHARSET_INFO *, char *s, size_t l,char **e, int *err); size_t my_long10_to_str_8bit(CHARSET_INFO *, char *to, size_t l, int radix, long int val); size_t my_longlong10_to_str_8bit(CHARSET_INFO *, char *to, size_t l, int radix, longlong val); longlong my_strtoll10_8bit(CHARSET_INFO *cs, const char *nptr, char **endptr, int *error); longlong my_strtoll10_ucs2(CHARSET_INFO *cs, const char *nptr, char **endptr, int *error); ulonglong my_strntoull10rnd_8bit(CHARSET_INFO *cs, const char *str, size_t length, int unsigned_fl, char **endptr, int *error); ulonglong my_strntoull10rnd_ucs2(CHARSET_INFO *cs, const char *str, size_t length, int unsigned_fl, char **endptr, int *error); void my_fill_8bit(CHARSET_INFO *cs, char* to, size_t l, int fill); /* For 8-bit character set */ my_bool my_like_range_simple(CHARSET_INFO *cs, const char *ptr, size_t ptr_length, pbool escape, pbool w_one, pbool w_many, size_t res_length, char *min_str, char *max_str, size_t *min_length, size_t *max_length); /* For ASCII-based multi-byte character sets with mbminlen=1 */ my_bool my_like_range_mb(CHARSET_INFO *cs, const char *ptr, size_t ptr_length, pbool escape, pbool w_one, pbool w_many, size_t res_length, char *min_str, char *max_str, size_t *min_length, size_t *max_length); /* For other character sets, with arbitrary mbminlen and mbmaxlen numbers */ my_bool my_like_range_generic(CHARSET_INFO *cs, const char *ptr, size_t ptr_length, pbool escape, pbool w_one, pbool w_many, size_t res_length, char *min_str, char *max_str, size_t *min_length, size_t *max_length); int my_wildcmp_8bit(CHARSET_INFO *, const char *str,const char *str_end, const char *wildstr,const char *wildend, int escape, int w_one, int w_many); int my_wildcmp_bin(CHARSET_INFO *, const char *str,const char *str_end, const char *wildstr,const char *wildend, int escape, int w_one, int w_many); size_t my_numchars_8bit(CHARSET_INFO *, const char *b, const char *e); size_t my_numcells_8bit(CHARSET_INFO *, const char *b, const char *e); size_t my_charpos_8bit(CHARSET_INFO *, const char *b, const char *e, size_t pos); size_t my_well_formed_char_length_8bit(CHARSET_INFO *cs, const char *b, const char *e, size_t nchars, MY_STRCOPY_STATUS *status); int my_charlen_8bit(CHARSET_INFO *, const uchar *str, const uchar *end); /* Functions for multibyte charsets */ extern size_t my_caseup_str_mb(CHARSET_INFO *, char *); extern size_t my_casedn_str_mb(CHARSET_INFO *, char *); extern size_t my_caseup_mb(CHARSET_INFO *, const char *src, size_t srclen, char *dst, size_t dstlen); extern size_t my_casedn_mb(CHARSET_INFO *, const char *src, size_t srclen, char *dst, size_t dstlen); extern size_t my_caseup_ujis(CHARSET_INFO *, const char *src, size_t srclen, char *dst, size_t dstlen); extern size_t my_casedn_ujis(CHARSET_INFO *, const char *src, size_t srclen, char *dst, size_t dstlen); extern int my_strcasecmp_mb(CHARSET_INFO * cs,const char *, const char *); int my_wildcmp_mb(CHARSET_INFO *, const char *str,const char *str_end, const char *wildstr,const char *wildend, int escape, int w_one, int w_many); size_t my_numchars_mb(CHARSET_INFO *, const char *b, const char *e); size_t my_numcells_mb(CHARSET_INFO *, const char *b, const char *e); size_t my_charpos_mb(CHARSET_INFO *, const char *b, const char *e, size_t pos); uint my_instr_mb(CHARSET_INFO *, const char *b, size_t b_length, const char *s, size_t s_length, my_match_t *match, uint nmatch); int my_wildcmp_mb_bin(CHARSET_INFO *cs, const char *str,const char *str_end, const char *wildstr,const char *wildend, int escape, int w_one, int w_many); int my_strcasecmp_mb_bin(CHARSET_INFO * cs __attribute__((unused)), const char *s, const char *t); void my_hash_sort_mb_bin(CHARSET_INFO *cs __attribute__((unused)), const uchar *key, size_t len,ulong *nr1, ulong *nr2); void my_hash_sort_mb_nopad_bin(CHARSET_INFO *cs __attribute__((unused)), const uchar *key, size_t len, ulong *nr1, ulong *nr2); size_t my_strnxfrm_mb(CHARSET_INFO *, uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags); size_t my_strnxfrm_mb_nopad(CHARSET_INFO *, uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags); size_t my_strnxfrmlen_unicode(CHARSET_INFO *, size_t); size_t my_strnxfrm_unicode_full_bin(CHARSET_INFO *, uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags); size_t my_strnxfrm_unicode_full_nopad_bin(CHARSET_INFO *, uchar *dst, size_t dstlen, uint nweights, const uchar *src, size_t srclen, uint flags); size_t my_strnxfrmlen_unicode_full_bin(CHARSET_INFO *, size_t); int my_wildcmp_unicode(CHARSET_INFO *cs, const char *str, const char *str_end, const char *wildstr, const char *wildend, int escape, int w_one, int w_many, MY_UNICASE_INFO *weights); extern my_bool my_parse_charset_xml(MY_CHARSET_LOADER *loader, const char *buf, size_t buflen); extern char *my_strchr(CHARSET_INFO *cs, const char *str, const char *end, pchar c); extern size_t my_strcspn(CHARSET_INFO *cs, const char *str, const char *end, const char *accept); my_bool my_propagate_simple(CHARSET_INFO *cs, const uchar *str, size_t len); my_bool my_propagate_complex(CHARSET_INFO *cs, const uchar *str, size_t len); typedef struct { size_t char_length; my_repertoire_t repertoire; } MY_STRING_METADATA; void my_string_metadata_get(MY_STRING_METADATA *metadata, CHARSET_INFO *cs, const char *str, size_t len); my_repertoire_t my_string_repertoire(CHARSET_INFO *cs, const char *str, size_t len); my_bool my_charset_is_ascii_based(CHARSET_INFO *cs); my_repertoire_t my_charset_repertoire(CHARSET_INFO *cs); uint my_strxfrm_flag_normalize(uint flags, uint nlevels); void my_strxfrm_desc_and_reverse(uchar *str, uchar *strend, uint flags, uint level); size_t my_strxfrm_pad_desc_and_reverse(CHARSET_INFO *cs, uchar *str, uchar *frmend, uchar *strend, uint nweights, uint flags, uint level); size_t my_strxfrm_pad_desc_and_reverse_nopad(CHARSET_INFO *cs, uchar *str, uchar *frmend, uchar *strend, uint nweights, uint flags, uint level); const MY_CONTRACTIONS *my_charset_get_contractions(CHARSET_INFO *cs, int level); extern size_t my_vsnprintf_ex(CHARSET_INFO *cs, char *to, size_t n, const char* fmt, va_list ap); /* Convert a string between two character sets. Bad byte sequences as well as characters that cannot be encoded in the destination character set are replaced to '?'. */ uint32 my_convert(char *to, uint32 to_length, CHARSET_INFO *to_cs, const char *from, uint32 from_length, CHARSET_INFO *from_cs, uint *errors); /** An extended version of my_convert(), to pass non-default mb_wc() and wc_mb(). For example, String::copy_printable() which is used in Protocol::store_warning() uses this to escape control and non-convertible characters. */ uint32 my_convert_using_func(char *to, size_t to_length, CHARSET_INFO *to_cs, my_charset_conv_wc_mb mb_wc, const char *from, size_t from_length, CHARSET_INFO *from_cs, my_charset_conv_mb_wc wc_mb, uint *errors); /* Convert a string between two character sets. Bad byte sequences as well as characters that cannot be encoded in the destination character set are replaced to '?'. Not more than "nchars" characters are copied. Conversion statistics is returned in "status" and is set as follows: - status->m_native_copy_status.m_source_end_pos - to the position between (src) and (src+src_length), where the function stopped reading the source string. - status->m_native_copy_status.m_well_formed_error_pos - to the position between (src) and (src+src_length), where the first badly formed byte sequence was found, or to NULL if the string was well formed in the given range. - status->m_cannot_convert_error_pos - to the position between (src) and (src+src_length), where the first character that cannot be represented in the destination character set was found, or to NULL if all characters in the given range were successfully converted. "src" is allowed to be a NULL pointer. In this case "src_length" must be equal to 0. All "status" members are initialized to NULL, and 0 is returned. */ size_t my_convert_fix(CHARSET_INFO *dstcs, char *dst, size_t dst_length, CHARSET_INFO *srccs, const char *src, size_t src_length, size_t nchars, MY_STRCOPY_STATUS *copy_status, MY_STRCONV_STATUS *conv_status); #define _MY_U 01 /* Upper case */ #define _MY_L 02 /* Lower case */ #define _MY_NMR 04 /* Numeral (digit) */ #define _MY_SPC 010 /* Spacing character */ #define _MY_PNT 020 /* Punctuation */ #define _MY_CTR 040 /* Control character */ #define _MY_B 0100 /* Blank */ #define _MY_X 0200 /* heXadecimal digit */ #define my_isascii(c) (!((c) & ~0177)) #define my_toascii(c) ((c) & 0177) #define my_tocntrl(c) ((c) & 31) #define my_toprint(c) ((c) | 64) #define my_toupper(s,c) (char) ((s)->to_upper[(uchar) (c)]) #define my_tolower(s,c) (char) ((s)->to_lower[(uchar) (c)]) #define my_isalpha(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_U | _MY_L)) #define my_isupper(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_U) #define my_islower(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_L) #define my_isdigit(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_NMR) #define my_isxdigit(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_X) #define my_isalnum(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_U | _MY_L | _MY_NMR)) #define my_isspace(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_SPC) #define my_ispunct(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_PNT) #define my_isprint(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR | _MY_B)) #define my_isgraph(s, c) (((s)->m_ctype+1)[(uchar) (c)] & (_MY_PNT | _MY_U | _MY_L | _MY_NMR)) #define my_iscntrl(s, c) (((s)->m_ctype+1)[(uchar) (c)] & _MY_CTR) /* Some macros that should be cleaned up a little */ #define my_isvar(s,c) (my_isalnum(s,c) || (c) == '_') #define my_isvar_start(s,c) (my_isalpha(s,c) || (c) == '_') #define my_binary_compare(s) ((s)->state & MY_CS_BINSORT) #define use_strnxfrm(s) ((s)->state & MY_CS_STRNXFRM) #define my_strnncoll(s, a, b, c, d) ((s)->coll->strnncoll((s), (a), (b), (c), (d), 0)) #define my_strcasecmp(s, a, b) ((s)->coll->strcasecmp((s), (a), (b))) /** Detect if the leftmost character in a string is a valid multi-byte character and return its length, or return 0 otherwise. @param cs - character set @param str - the beginning of the string @param end - the string end (the next byte after the string) @return >0, for a multi-byte character @return 0, for a single byte character, broken sequence, empty string. */ static inline uint my_ismbchar(CHARSET_INFO *cs, const char *str, const char *end) { int char_length= (cs->cset->charlen)(cs, (const uchar *) str, (const uchar *) end); return char_length > 1 ? (uint) char_length : 0U; } /** Convert broken and incomplete byte sequences to 1 byte. */ static inline uint my_ci_charlen_fix(CHARSET_INFO *cs, const uchar *str, const uchar *end) { int char_length= my_ci_charlen(cs, str, end); DBUG_ASSERT(str < end); return char_length > 0 ? (uint) char_length : (uint) 1U; } /* A compatibility replacement pure C function for the former cs->cset->well_formed_len(). In C++ code please use Well_formed_prefix::length() instead. */ static inline size_t my_well_formed_length(CHARSET_INFO *cs, const char *b, const char *e, size_t nchars, int *error) { MY_STRCOPY_STATUS status; (void) my_ci_well_formed_char_length(cs, b, e, nchars, &status); *error= status.m_well_formed_error_pos == NULL ? 0 : 1; return (size_t) (status.m_source_end_pos - b); } #define my_caseup_str(s, a) ((s)->cset->caseup_str((s), (a))) #define my_casedn_str(s, a) ((s)->cset->casedn_str((s), (a))) /* XXX: still need to take care of this one */ #ifdef MY_CHARSET_TIS620 #error The TIS620 charset is broken at the moment. Tell tim to fix it. #define USE_TIS620 #include "t_ctype.h" #endif int my_wc_mb_utf8mb4_bmp_only(CHARSET_INFO *cs, my_wc_t wc, uchar *r, uchar *e); #ifdef __cplusplus } #endif #endif /* _m_ctype_h */ mysql/server/mysql_embed.h000064400000002144151027430560011675 0ustar00#ifndef MYSQL_EMBED_INCLUDED #define MYSQL_EMBED_INCLUDED /* Copyright (c) 2000, 2011, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Defines that are unique to the embedded version of MySQL */ #ifdef EMBEDDED_LIBRARY /* Things we don't need in the embedded version of MySQL */ /* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */ #undef HAVE_DLOPEN /* No udf functions */ #endif /* EMBEDDED_LIBRARY */ #endif /* MYSQL_EMBED_INCLUDED */ mysql/server/keycache.h000064400000021173151027430560011153 0ustar00/* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Key cache variable structures */ #ifndef _keycache_h #define _keycache_h #include "my_sys.h" /* flush_type */ C_MODE_START /* Currently the default key cache is created as non-partitioned at the start of the server unless the server is started with the parameter --key-cache-partitions that is greater than 0 */ #define DEFAULT_KEY_CACHE_PARTITIONS 0 /* MAX_KEY_CACHE_PARTITIONS cannot be greater than sizeof(MYISAM_SHARE::dirty_part_map) Currently sizeof(MYISAM_SHARE::dirty_part_map)=sizeof(ulonglong) */ #define MAX_KEY_CACHE_PARTITIONS 64 /* The structure to get statistical data about a key cache */ typedef struct st_key_cache_statistics { ulonglong mem_size; /* memory for cache buffers/auxiliary structures */ ulonglong block_size; /* size of the each buffers in the key cache */ ulonglong blocks_used; /* maximum number of used blocks/buffers */ ulonglong blocks_unused; /* number of currently unused blocks */ ulonglong blocks_changed; /* number of currently dirty blocks */ ulonglong blocks_warm; /* number of blocks in warm sub-chain */ ulonglong read_requests; /* number of read requests (read hits) */ ulonglong reads; /* number of actual reads from files into buffers */ ulonglong write_requests; /* number of write requests (write hits) */ ulonglong writes; /* number of actual writes from buffers into files */ } KEY_CACHE_STATISTICS; #define NUM_LONG_KEY_CACHE_STAT_VARIABLES 3 /* The type of a key cache object */ typedef enum key_cache_type { SIMPLE_KEY_CACHE, PARTITIONED_KEY_CACHE } KEY_CACHE_TYPE; typedef int (*INIT_KEY_CACHE) (void *, uint key_cache_block_size, size_t use_mem, uint division_limit, uint age_threshold, uint changed_blocks_hash_size); typedef int (*RESIZE_KEY_CACHE) (void *, uint key_cache_block_size, size_t use_mem, uint division_limit, uint age_threshold, uint changed_blocks_hash_size); typedef void (*CHANGE_KEY_CACHE_PARAM) (void *keycache_cb, uint division_limit, uint age_threshold); typedef uchar* (*KEY_CACHE_READ) (void *keycache_cb, File file, my_off_t filepos, int level, uchar *buff, uint length, uint block_length, int return_buffer); typedef int (*KEY_CACHE_INSERT) (void *keycache_cb, File file, my_off_t filepos, int level, uchar *buff, uint length); typedef int (*KEY_CACHE_WRITE) (void *keycache_cb, File file, void *file_extra, my_off_t filepos, int level, uchar *buff, uint length, uint block_length, int force_write); typedef int (*FLUSH_KEY_BLOCKS) (void *keycache_cb, int file, void *file_extra, enum flush_type type); typedef int (*RESET_KEY_CACHE_COUNTERS) (const char *name, void *keycache_cb); typedef void (*END_KEY_CACHE) (void *keycache_cb, my_bool cleanup); typedef void (*GET_KEY_CACHE_STATISTICS) (void *keycache_cb, uint partition_no, KEY_CACHE_STATISTICS *key_cache_stats); /* An object of the type KEY_CACHE_FUNCS contains pointers to all functions from the key cache interface. Currently a key cache can be of two types: simple and partitioned. For each of them its own static structure of the type KEY_CACHE_FUNCS is defined . The structures contain the pointers to the implementations of the interface functions used by simple key caches and partitioned key caches respectively. Pointers to these structures are assigned to key cache objects at the time of their creation. */ typedef struct st_key_cache_funcs { INIT_KEY_CACHE init; RESIZE_KEY_CACHE resize; CHANGE_KEY_CACHE_PARAM change_param; KEY_CACHE_READ read; KEY_CACHE_INSERT insert; KEY_CACHE_WRITE write; FLUSH_KEY_BLOCKS flush; RESET_KEY_CACHE_COUNTERS reset_counters; END_KEY_CACHE end; GET_KEY_CACHE_STATISTICS get_stats; } KEY_CACHE_FUNCS; typedef struct st_key_cache { KEY_CACHE_TYPE key_cache_type; /* type of the key cache used for debugging */ void *keycache_cb; /* control block of the used key cache */ KEY_CACHE_FUNCS *interface_funcs; /* interface functions of the key cache */ ulonglong param_buff_size; /* size the memory allocated for the cache */ ulonglong param_block_size; /* size of the blocks in the key cache */ ulonglong param_division_limit;/* min. percentage of warm blocks */ ulonglong param_age_threshold; /* determines when hot block is downgraded */ ulonglong param_partitions; /* number of the key cache partitions */ ulonglong changed_blocks_hash_size; /* number of hash buckets for changed files */ my_bool key_cache_inited; /* <=> key cache has been created */ my_bool can_be_used; /* usage of cache for read/write is allowed */ my_bool in_init; /* set to 1 in MySQL during init/resize */ uint partitions; /* actual number of partitions */ size_t key_cache_mem_size; /* specified size of the cache memory */ pthread_mutex_t op_lock; /* to serialize operations like 'resize' */ } KEY_CACHE; /* The default key cache */ extern KEY_CACHE dflt_key_cache_var, *dflt_key_cache; extern int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, size_t use_mem, uint division_limit, uint age_threshold, uint changed_blocks_hash_size, uint partitions); extern int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, size_t use_mem, uint division_limit, uint age_threshold, uint changed_blocks_hash_size); extern void change_key_cache_param(KEY_CACHE *keycache, uint division_limit, uint age_threshold); extern uchar *key_cache_read(KEY_CACHE *keycache, File file, my_off_t filepos, int level, uchar *buff, uint length, uint block_length,int return_buffer); extern int key_cache_insert(KEY_CACHE *keycache, File file, my_off_t filepos, int level, uchar *buff, uint length); extern int key_cache_write(KEY_CACHE *keycache, File file, void *file_extra, my_off_t filepos, int level, uchar *buff, uint length, uint block_length, int force_write); extern int flush_key_blocks(KEY_CACHE *keycache, int file, void *file_extra, enum flush_type type); extern void end_key_cache(KEY_CACHE *keycache, my_bool cleanup); extern void get_key_cache_statistics(KEY_CACHE *keycache, uint partition_no, KEY_CACHE_STATISTICS *key_cache_stats); /* Functions to handle multiple key caches */ extern my_bool multi_keycache_init(void); extern void multi_keycache_free(void); extern KEY_CACHE *multi_key_cache_search(uchar *key, uint length, KEY_CACHE *def); extern my_bool multi_key_cache_set(const uchar *key, uint length, KEY_CACHE *key_cache); extern void multi_key_cache_change(KEY_CACHE *old_data, KEY_CACHE *new_data); extern int reset_key_cache_counters(const char *name, KEY_CACHE *key_cache, void *); extern int repartition_key_cache(KEY_CACHE *keycache, uint key_cache_block_size, size_t use_mem, uint division_limit, uint age_threshold, uint changed_blocks_hash_size, uint partitions); C_MODE_END #endif /* _keycache_h */ mysql/server/mysqld_ername.h000064400000371032151027430560012241 0ustar00/* Autogenerated file, please don't edit */ { "ER_HASHCHK", 1000, "hashchk" }, { "ER_NISAMCHK", 1001, "isamchk" }, { "ER_NO", 1002, "NO" }, { "ER_YES", 1003, "YES" }, { "ER_CANT_CREATE_FILE", 1004, "Can\'t create file \'%-.200s\' (errno: %M)" }, { "ER_CANT_CREATE_TABLE", 1005, "Can\'t create table %`s.%`s (errno: %M)" }, { "ER_CANT_CREATE_DB", 1006, "Can\'t create database \'%-.192s\' (errno: %M)" }, { "ER_DB_CREATE_EXISTS", 1007, "Can\'t create database \'%-.192s\'; database exists" }, { "ER_DB_DROP_EXISTS", 1008, "Can\'t drop database \'%-.192s\'; database doesn\'t exist" }, { "ER_DB_DROP_DELETE", 1009, "Error dropping database (can\'t delete \'%-.192s\', errno: %M)" }, { "ER_DB_DROP_RMDIR", 1010, "Error dropping database (can\'t rmdir \'%-.192s\', errno: %M)" }, { "ER_CANT_DELETE_FILE", 1011, "Error on delete of \'%-.192s\' (errno: %M)" }, { "ER_CANT_FIND_SYSTEM_REC", 1012, "Can\'t read record in system table" }, { "ER_CANT_GET_STAT", 1013, "Can\'t get status of \'%-.200s\' (errno: %M)" }, { "ER_CANT_GET_WD", 1014, "Can\'t get working directory (errno: %M)" }, { "ER_CANT_LOCK", 1015, "Can\'t lock file (errno: %M)" }, { "ER_CANT_OPEN_FILE", 1016, "Can\'t open file: \'%-.200s\' (errno: %M)" }, { "ER_FILE_NOT_FOUND", 1017, "Can\'t find file: \'%-.200s\' (errno: %M)" }, { "ER_CANT_READ_DIR", 1018, "Can\'t read dir of \'%-.192s\' (errno: %M)" }, { "ER_CANT_SET_WD", 1019, "Can\'t change dir to \'%-.192s\' (errno: %M)" }, { "ER_CHECKREAD", 1020, "Record has changed since last read in table \'%-.192s\'" }, { "ER_DISK_FULL", 1021, "Disk full (%s); waiting for someone to free some space... (errno: %M)" }, { "ER_DUP_KEY", 1022, "Can\'t write; duplicate key in table \'%-.192s\'" }, { "ER_ERROR_ON_CLOSE", 1023, "Error on close of \'%-.192s\' (errno: %M)" }, { "ER_ERROR_ON_READ", 1024, "Error reading file \'%-.200s\' (errno: %M)" }, { "ER_ERROR_ON_RENAME", 1025, "Error on rename of \'%-.210s\' to \'%-.210s\' (errno: %M)" }, { "ER_ERROR_ON_WRITE", 1026, "Error writing file \'%-.200s\' (errno: %M)" }, { "ER_FILE_USED", 1027, "\'%-.192s\' is locked against change" }, { "ER_FILSORT_ABORT", 1028, "Sort aborted" }, { "ER_FORM_NOT_FOUND", 1029, "View \'%-.192s\' doesn\'t exist for \'%-.192s\'" }, { "ER_GET_ERRNO", 1030, "Got error %M from storage engine %s" }, { "ER_ILLEGAL_HA", 1031, "Storage engine %s of the table %`s.%`s doesn\'t have this option" }, { "ER_KEY_NOT_FOUND", 1032, "Can\'t find record in \'%-.192s\'" }, { "ER_NOT_FORM_FILE", 1033, "Incorrect information in file: \'%-.200s\'" }, { "ER_NOT_KEYFILE", 1034, "Index for table \'%-.200s\' is corrupt; try to repair it" }, { "ER_OLD_KEYFILE", 1035, "Old key file for table \'%-.192s\'; repair it!" }, { "ER_OPEN_AS_READONLY", 1036, "Table \'%-.192s\' is read only" }, { "ER_OUTOFMEMORY", 1037, "Out of memory; restart server and try again (needed %d bytes)" }, { "ER_OUT_OF_SORTMEMORY", 1038, "Out of sort memory, consider increasing server sort buffer size" }, { "ER_UNEXPECTED_EOF", 1039, "Unexpected EOF found when reading file \'%-.192s\' (errno: %M)" }, { "ER_CON_COUNT_ERROR", 1040, "Too many connections" }, { "ER_OUT_OF_RESOURCES", 1041, "Out of memory." }, { "ER_BAD_HOST_ERROR", 1042, "Can\'t get hostname for your address" }, { "ER_HANDSHAKE_ERROR", 1043, "Bad handshake" }, { "ER_DBACCESS_DENIED_ERROR", 1044, "Access denied for user \'%s\'@\'%s\' to database \'%-.192s\'" }, { "ER_ACCESS_DENIED_ERROR", 1045, "Access denied for user \'%s\'@\'%s\' (using password: %s)" }, { "ER_NO_DB_ERROR", 1046, "No database selected" }, { "ER_UNKNOWN_COM_ERROR", 1047, "Unknown command" }, { "ER_BAD_NULL_ERROR", 1048, "Column \'%-.192s\' cannot be null" }, { "ER_BAD_DB_ERROR", 1049, "Unknown database \'%-.192s\'" }, { "ER_TABLE_EXISTS_ERROR", 1050, "Table \'%-.192s\' already exists" }, { "ER_BAD_TABLE_ERROR", 1051, "Unknown table \'%-.100T\'" }, { "ER_NON_UNIQ_ERROR", 1052, "Column \'%-.192s\' in %-.192s is ambiguous" }, { "ER_SERVER_SHUTDOWN", 1053, "Server shutdown in progress" }, { "ER_BAD_FIELD_ERROR", 1054, "Unknown column \'%-.192s\' in \'%-.192s\'" }, { "ER_WRONG_FIELD_WITH_GROUP", 1055, "\'%-.192s\' isn\'t in GROUP BY" }, { "ER_WRONG_GROUP_FIELD", 1056, "Can\'t group on \'%-.192s\'" }, { "ER_WRONG_SUM_SELECT", 1057, "Statement has sum functions and columns in same statement" }, { "ER_WRONG_VALUE_COUNT", 1058, "Column count doesn\'t match value count" }, { "ER_TOO_LONG_IDENT", 1059, "Identifier name \'%-.100T\' is too long" }, { "ER_DUP_FIELDNAME", 1060, "Duplicate column name \'%-.192s\'" }, { "ER_DUP_KEYNAME", 1061, "Duplicate key name \'%-.192s\'" }, { "ER_DUP_ENTRY", 1062, "Duplicate entry \'%-.192T\' for key %d" }, { "ER_WRONG_FIELD_SPEC", 1063, "Incorrect column specifier for column \'%-.192s\'" }, { "ER_PARSE_ERROR", 1064, "%s near \'%-.80T\' at line %d" }, { "ER_EMPTY_QUERY", 1065, "Query was empty" }, { "ER_NONUNIQ_TABLE", 1066, "Not unique table/alias: \'%-.192s\'" }, { "ER_INVALID_DEFAULT", 1067, "Invalid default value for \'%-.192s\'" }, { "ER_MULTIPLE_PRI_KEY", 1068, "Multiple primary key defined" }, { "ER_TOO_MANY_KEYS", 1069, "Too many keys specified; max %d keys allowed" }, { "ER_TOO_MANY_KEY_PARTS", 1070, "Too many key parts specified; max %d parts allowed" }, { "ER_TOO_LONG_KEY", 1071, "Specified key was too long; max key length is %d bytes" }, { "ER_KEY_COLUMN_DOES_NOT_EXITS", 1072, "Key column \'%-.192s\' doesn\'t exist in table" }, { "ER_BLOB_USED_AS_KEY", 1073, "BLOB column %`s can\'t be used in key specification in the %s table" }, { "ER_TOO_BIG_FIELDLENGTH", 1074, "Column length too big for column \'%-.192s\' (max = %lu); use BLOB or TEXT instead" }, { "ER_WRONG_AUTO_KEY", 1075, "Incorrect table definition; there can be only one auto column and it must be defined as a key" }, { "ER_BINLOG_CANT_DELETE_GTID_DOMAIN", 1076, "Could not delete gtid domain. Reason: %s." }, { "ER_NORMAL_SHUTDOWN", 1077, "%s (initiated by: %s): Normal shutdown" }, { "ER_GOT_SIGNAL", 1078, "%s: Got signal %d. Aborting!" }, { "ER_SHUTDOWN_COMPLETE", 1079, "%s: Shutdown complete" }, { "ER_FORCING_CLOSE", 1080, "%s: Forcing close of thread %ld user: \'%-.48s\'" }, { "ER_IPSOCK_ERROR", 1081, "Can\'t create IP socket" }, { "ER_NO_SUCH_INDEX", 1082, "Table \'%-.192s\' has no index like the one used in CREATE INDEX; recreate the table" }, { "ER_WRONG_FIELD_TERMINATORS", 1083, "Field separator argument is not what is expected; check the manual" }, { "ER_BLOBS_AND_NO_TERMINATED", 1084, "You can\'t use fixed rowlength with BLOBs; please use \'fields terminated by\'" }, { "ER_TEXTFILE_NOT_READABLE", 1085, "The file \'%-.128s\' must be in the database directory or be readable by all" }, { "ER_FILE_EXISTS_ERROR", 1086, "File \'%-.200s\' already exists" }, { "ER_LOAD_INFO", 1087, "Records: %ld Deleted: %ld Skipped: %ld Warnings: %ld" }, { "ER_ALTER_INFO", 1088, "Records: %ld Duplicates: %ld" }, { "ER_WRONG_SUB_KEY", 1089, "Incorrect prefix key; the used key part isn\'t a string, the used length is longer than the key part, or the storage engine doesn\'t support unique prefix keys" }, { "ER_CANT_REMOVE_ALL_FIELDS", 1090, "You can\'t delete all columns with ALTER TABLE; use DROP TABLE instead" }, { "ER_CANT_DROP_FIELD_OR_KEY", 1091, "Can\'t DROP %s %`-.192s; check that it exists" }, { "ER_INSERT_INFO", 1092, "Records: %ld Duplicates: %ld Warnings: %ld" }, { "ER_UPDATE_TABLE_USED", 1093, "Table \'%-.192s\' is specified twice, both as a target for \'%s\' and as a separate source for data" }, { "ER_NO_SUCH_THREAD", 1094, "Unknown thread id: %lu" }, { "ER_KILL_DENIED_ERROR", 1095, "You are not owner of thread %lld" }, { "ER_NO_TABLES_USED", 1096, "No tables used" }, { "ER_TOO_BIG_SET", 1097, "Too many strings for column %-.192s and SET" }, { "ER_NO_UNIQUE_LOGFILE", 1098, "Can\'t generate a unique log-filename %-.200s.(1-999)" }, { "ER_TABLE_NOT_LOCKED_FOR_WRITE", 1099, "Table \'%-.192s\' was locked with a READ lock and can\'t be updated" }, { "ER_TABLE_NOT_LOCKED", 1100, "Table \'%-.192s\' was not locked with LOCK TABLES" }, { "ER_UNUSED_17", 1101, "You should never see it" }, { "ER_WRONG_DB_NAME", 1102, "Incorrect database name \'%-.100T\'" }, { "ER_WRONG_TABLE_NAME", 1103, "Incorrect table name \'%-.100s\'" }, { "ER_TOO_BIG_SELECT", 1104, "The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay" }, { "ER_UNKNOWN_ERROR", 1105, "Unknown error" }, { "ER_UNKNOWN_PROCEDURE", 1106, "Unknown procedure \'%-.192s\'" }, { "ER_WRONG_PARAMCOUNT_TO_PROCEDURE", 1107, "Incorrect parameter count to procedure \'%-.192s\'" }, { "ER_WRONG_PARAMETERS_TO_PROCEDURE", 1108, "Incorrect parameters to procedure \'%-.192s\'" }, { "ER_UNKNOWN_TABLE", 1109, "Unknown table \'%-.192s\' in %-.32s" }, { "ER_FIELD_SPECIFIED_TWICE", 1110, "Column \'%-.192s\' specified twice" }, { "ER_INVALID_GROUP_FUNC_USE", 1111, "Invalid use of group function" }, { "ER_UNSUPPORTED_EXTENSION", 1112, "Table \'%-.192s\' uses an extension that doesn\'t exist in this MariaDB version" }, { "ER_TABLE_MUST_HAVE_COLUMNS", 1113, "A table must have at least 1 column" }, { "ER_RECORD_FILE_FULL", 1114, "The table \'%-.192s\' is full" }, { "ER_UNKNOWN_CHARACTER_SET", 1115, "Unknown character set: \'%-.64s\'" }, { "ER_TOO_MANY_TABLES", 1116, "Too many tables; MariaDB can only use %d tables in a join" }, { "ER_TOO_MANY_FIELDS", 1117, "Too many columns" }, { "ER_TOO_BIG_ROWSIZE", 1118, "Row size too large. The maximum row size for the used table type, not counting BLOBs, is %ld. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs" }, { "ER_STACK_OVERRUN", 1119, "Thread stack overrun: Used: %ld of a %ld stack. Use \'mariadbd --thread_stack=#\' to specify a bigger stack if needed" }, { "ER_WRONG_OUTER_JOIN", 1120, "Cross dependency found in OUTER JOIN; examine your ON conditions" }, { "ER_NULL_COLUMN_IN_INDEX", 1121, "Table handler doesn\'t support NULL in given index. Please change column \'%-.192s\' to be NOT NULL or use another handler" }, { "ER_CANT_FIND_UDF", 1122, "Can\'t load function \'%-.192s\'" }, { "ER_CANT_INITIALIZE_UDF", 1123, "Can\'t initialize function \'%-.192s\'; %-.80s" }, { "ER_UDF_NO_PATHS", 1124, "No paths allowed for shared library" }, { "ER_UDF_EXISTS", 1125, "Function \'%-.192s\' already exists" }, { "ER_CANT_OPEN_LIBRARY", 1126, "Can\'t open shared library \'%-.192s\' (errno: %d, %-.128s)" }, { "ER_CANT_FIND_DL_ENTRY", 1127, "Can\'t find symbol \'%-.128s\' in library" }, { "ER_FUNCTION_NOT_DEFINED", 1128, "Function \'%-.192s\' is not defined" }, { "ER_HOST_IS_BLOCKED", 1129, "Host \'%-.64s\' is blocked because of many connection errors; unblock with \'mariadb-admin flush-hosts\'" }, { "ER_HOST_NOT_PRIVILEGED", 1130, "Host \'%-.64s\' is not allowed to connect to this MariaDB server" }, { "ER_PASSWORD_ANONYMOUS_USER", 1131, "You are using MariaDB as an anonymous user and anonymous users are not allowed to modify user settings" }, { "ER_PASSWORD_NOT_ALLOWED", 1132, "You must have privileges to update tables in the mysql database to be able to change passwords for others" }, { "ER_PASSWORD_NO_MATCH", 1133, "Can\'t find any matching row in the user table" }, { "ER_UPDATE_INFO", 1134, "Rows matched: %ld Changed: %ld Warnings: %ld" }, { "ER_CANT_CREATE_THREAD", 1135, "Can\'t create a new thread (errno %M); if you are not out of available memory, you can consult the manual for a possible OS-dependent bug" }, { "ER_WRONG_VALUE_COUNT_ON_ROW", 1136, "Column count doesn\'t match value count at row %lu" }, { "ER_CANT_REOPEN_TABLE", 1137, "Can\'t reopen table: \'%-.192s\'" }, { "ER_INVALID_USE_OF_NULL", 1138, "Invalid use of NULL value" }, { "ER_REGEXP_ERROR", 1139, "Regex error \'%s\'" }, { "ER_MIX_OF_GROUP_FUNC_AND_FIELDS", 1140, "Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause" }, { "ER_NONEXISTING_GRANT", 1141, "There is no such grant defined for user \'%-.48s\' on host \'%-.64s\'" }, { "ER_TABLEACCESS_DENIED_ERROR", 1142, "%-.100T command denied to user \'%s\'@\'%s\' for table %`s.%`s" }, { "ER_COLUMNACCESS_DENIED_ERROR", 1143, "%-.32s command denied to user \'%s\'@\'%s\' for column \'%-.192s\' in table \'%-.192s\'" }, { "ER_ILLEGAL_GRANT_FOR_TABLE", 1144, "Illegal GRANT/REVOKE command; please consult the manual to see which privileges can be used" }, { "ER_GRANT_WRONG_HOST_OR_USER", 1145, "The host or user argument to GRANT is too long" }, { "ER_NO_SUCH_TABLE", 1146, "Table \'%-.192s.%-.192s\' doesn\'t exist" }, { "ER_NONEXISTING_TABLE_GRANT", 1147, "There is no such grant defined for user \'%-.48s\' on host \'%-.64s\' on table \'%-.192s\'" }, { "ER_NOT_ALLOWED_COMMAND", 1148, "The used command is not allowed with this MariaDB version" }, { "ER_SYNTAX_ERROR", 1149, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use" }, { "ER_DELAYED_CANT_CHANGE_LOCK", 1150, "Delayed insert thread couldn\'t get requested lock for table %-.192s" }, { "ER_TOO_MANY_DELAYED_THREADS", 1151, "Too many delayed threads in use" }, { "ER_ABORTING_CONNECTION", 1152, "Aborted connection %ld to db: \'%-.192s\' user: \'%-.48s\' (%-.64s)" }, { "ER_NET_PACKET_TOO_LARGE", 1153, "Got a packet bigger than \'max_allowed_packet\' bytes" }, { "ER_NET_READ_ERROR_FROM_PIPE", 1154, "Got a read error from the connection pipe" }, { "ER_NET_FCNTL_ERROR", 1155, "Got an error from fcntl()" }, { "ER_NET_PACKETS_OUT_OF_ORDER", 1156, "Got packets out of order" }, { "ER_NET_UNCOMPRESS_ERROR", 1157, "Couldn\'t uncompress communication packet" }, { "ER_NET_READ_ERROR", 1158, "Got an error reading communication packets" }, { "ER_NET_READ_INTERRUPTED", 1159, "Got timeout reading communication packets" }, { "ER_NET_ERROR_ON_WRITE", 1160, "Got an error writing communication packets" }, { "ER_NET_WRITE_INTERRUPTED", 1161, "Got timeout writing communication packets" }, { "ER_TOO_LONG_STRING", 1162, "Result string is longer than \'max_allowed_packet\' bytes" }, { "ER_TABLE_CANT_HANDLE_BLOB", 1163, "Storage engine %s doesn\'t support BLOB/TEXT columns" }, { "ER_TABLE_CANT_HANDLE_AUTO_INCREMENT", 1164, "Storage engine %s doesn\'t support AUTO_INCREMENT columns" }, { "ER_DELAYED_INSERT_TABLE_LOCKED", 1165, "INSERT DELAYED can\'t be used with table \'%-.192s\' because it is locked with LOCK TABLES" }, { "ER_WRONG_COLUMN_NAME", 1166, "Incorrect column name \'%-.100s\'" }, { "ER_WRONG_KEY_COLUMN", 1167, "The storage engine %s can\'t index column %`s" }, { "ER_WRONG_MRG_TABLE", 1168, "Unable to open underlying table which is differently defined or of non-MyISAM type or doesn\'t exist" }, { "ER_DUP_UNIQUE", 1169, "Can\'t write, because of unique constraint, to table \'%-.192s\'" }, { "ER_BLOB_KEY_WITHOUT_LENGTH", 1170, "BLOB/TEXT column \'%-.192s\' used in key specification without a key length" }, { "ER_PRIMARY_CANT_HAVE_NULL", 1171, "All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead" }, { "ER_TOO_MANY_ROWS", 1172, "Result consisted of more than one row" }, { "ER_REQUIRES_PRIMARY_KEY", 1173, "This table type requires a primary key" }, { "ER_NO_RAID_COMPILED", 1174, "This version of MariaDB is not compiled with RAID support" }, { "ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE", 1175, "You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column" }, { "ER_KEY_DOES_NOT_EXISTS", 1176, "Key \'%-.192s\' doesn\'t exist in table \'%-.192s\'" }, { "ER_CHECK_NO_SUCH_TABLE", 1177, "Can\'t open table" }, { "ER_CHECK_NOT_IMPLEMENTED", 1178, "The storage engine for the table doesn\'t support %s" }, { "ER_CANT_DO_THIS_DURING_AN_TRANSACTION", 1179, "You are not allowed to execute this command in a transaction" }, { "ER_ERROR_DURING_COMMIT", 1180, "Got error %M during COMMIT" }, { "ER_ERROR_DURING_ROLLBACK", 1181, "Got error %M during ROLLBACK" }, { "ER_ERROR_DURING_FLUSH_LOGS", 1182, "Got error %M during FLUSH_LOGS" }, { "ER_ERROR_DURING_CHECKPOINT", 1183, "Got error %M during CHECKPOINT" }, { "ER_NEW_ABORTING_CONNECTION", 1184, "Aborted connection %lld to db: \'%-.192s\' user: \'%-.48s\' host: \'%-.64s\'%-.64s (%-.64s)" }, { "ER_UNUSED_10", 1185, "You should never see it" }, { "ER_FLUSH_MASTER_BINLOG_CLOSED", 1186, "Binlog closed, cannot RESET MASTER" }, { "ER_INDEX_REBUILD", 1187, "Failed rebuilding the index of dumped table \'%-.192s\'" }, { "ER_MASTER", 1188, "Error from master: \'%-.64s\'" }, { "ER_MASTER_NET_READ", 1189, "Net error reading from master" }, { "ER_MASTER_NET_WRITE", 1190, "Net error writing to master" }, { "ER_FT_MATCHING_KEY_NOT_FOUND", 1191, "Can\'t find FULLTEXT index matching the column list" }, { "ER_LOCK_OR_ACTIVE_TRANSACTION", 1192, "Can\'t execute the given command because you have active locked tables or an active transaction" }, { "ER_UNKNOWN_SYSTEM_VARIABLE", 1193, "Unknown system variable \'%-.*s\'" }, { "ER_CRASHED_ON_USAGE", 1194, "Table \'%-.192s\' is marked as crashed and should be repaired" }, { "ER_CRASHED_ON_REPAIR", 1195, "Table \'%-.192s\' is marked as crashed and last (automatic?) repair failed" }, { "ER_WARNING_NOT_COMPLETE_ROLLBACK", 1196, "Some non-transactional changed tables couldn\'t be rolled back" }, { "ER_TRANS_CACHE_FULL", 1197, "Multi-statement transaction required more than \'max_binlog_cache_size\' bytes of storage; increase this mariadbd variable and try again" }, { "ER_SLAVE_MUST_STOP", 1198, "This operation cannot be performed as you have a running slave \'%2$*1$s\'; run STOP SLAVE \'%2$*1$s\' first" }, { "ER_SLAVE_NOT_RUNNING", 1199, "This operation requires a running slave; configure slave and do START SLAVE" }, { "ER_BAD_SLAVE", 1200, "The server is not configured as slave; fix in config file or with CHANGE MASTER TO" }, { "ER_MASTER_INFO", 1201, "Could not initialize master info structure for \'%.*s\'; more error messages can be found in the MariaDB error log" }, { "ER_SLAVE_THREAD", 1202, "Could not create slave thread; check system resources" }, { "ER_TOO_MANY_USER_CONNECTIONS", 1203, "User %-.64s already has more than \'max_user_connections\' active connections" }, { "ER_SET_CONSTANTS_ONLY", 1204, "You may only use constant expressions in this statement" }, { "ER_LOCK_WAIT_TIMEOUT", 1205, "Lock wait timeout exceeded; try restarting transaction" }, { "ER_LOCK_TABLE_FULL", 1206, "The total number of locks exceeds the lock table size" }, { "ER_READ_ONLY_TRANSACTION", 1207, "Update locks cannot be acquired during a READ UNCOMMITTED transaction" }, { "ER_DROP_DB_WITH_READ_LOCK", 1208, "DROP DATABASE not allowed while thread is holding global read lock" }, { "ER_CREATE_DB_WITH_READ_LOCK", 1209, "CREATE DATABASE not allowed while thread is holding global read lock" }, { "ER_WRONG_ARGUMENTS", 1210, "Incorrect arguments to %s" }, { "ER_NO_PERMISSION_TO_CREATE_USER", 1211, "\'%s\'@\'%s\' is not allowed to create new users" }, { "ER_UNION_TABLES_IN_DIFFERENT_DIR", 1212, "Incorrect table definition; all MERGE tables must be in the same database" }, { "ER_LOCK_DEADLOCK", 1213, "Deadlock found when trying to get lock; try restarting transaction" }, { "ER_TABLE_CANT_HANDLE_FT", 1214, "The storage engine %s doesn\'t support FULLTEXT indexes" }, { "ER_CANNOT_ADD_FOREIGN", 1215, "Cannot add foreign key constraint for `%s`" }, { "ER_NO_REFERENCED_ROW", 1216, "Cannot add or update a child row: a foreign key constraint fails" }, { "ER_ROW_IS_REFERENCED", 1217, "Cannot delete or update a parent row: a foreign key constraint fails" }, { "ER_CONNECT_TO_MASTER", 1218, "Error connecting to master: %-.128s" }, { "ER_QUERY_ON_MASTER", 1219, "Error running query on master: %-.128s" }, { "ER_ERROR_WHEN_EXECUTING_COMMAND", 1220, "Error when executing command %s: %-.128s" }, { "ER_WRONG_USAGE", 1221, "Incorrect usage of %s and %s" }, { "ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT", 1222, "The used SELECT statements have a different number of columns" }, { "ER_CANT_UPDATE_WITH_READLOCK", 1223, "Can\'t execute the query because you have a conflicting read lock" }, { "ER_MIXING_NOT_ALLOWED", 1224, "Mixing of transactional and non-transactional tables is disabled" }, { "ER_DUP_ARGUMENT", 1225, "Option \'%s\' used twice in statement" }, { "ER_USER_LIMIT_REACHED", 1226, "User \'%-.64s\' has exceeded the \'%s\' resource (current value: %ld)" }, { "ER_SPECIFIC_ACCESS_DENIED_ERROR", 1227, "Access denied; you need (at least one of) the %-.128s privilege(s) for this operation" }, { "ER_LOCAL_VARIABLE", 1228, "Variable \'%-.64s\' is a SESSION variable and can\'t be used with SET GLOBAL" }, { "ER_GLOBAL_VARIABLE", 1229, "Variable \'%-.64s\' is a GLOBAL variable and should be set with SET GLOBAL" }, { "ER_NO_DEFAULT", 1230, "Variable \'%-.64s\' doesn\'t have a default value" }, { "ER_WRONG_VALUE_FOR_VAR", 1231, "Variable \'%-.64s\' can\'t be set to the value of \'%-.200T\'" }, { "ER_WRONG_TYPE_FOR_VAR", 1232, "Incorrect argument type to variable \'%-.64s\'" }, { "ER_VAR_CANT_BE_READ", 1233, "Variable \'%-.64s\' can only be set, not read" }, { "ER_CANT_USE_OPTION_HERE", 1234, "Incorrect usage/placement of \'%s\'" }, { "ER_NOT_SUPPORTED_YET", 1235, "This version of MariaDB doesn\'t yet support \'%s\'" }, { "ER_MASTER_FATAL_ERROR_READING_BINLOG", 1236, "Got fatal error %d from master when reading data from binary log: \'%-.320s\'" }, { "ER_SLAVE_IGNORED_TABLE", 1237, "Slave SQL thread ignored the query because of replicate-*-table rules" }, { "ER_INCORRECT_GLOBAL_LOCAL_VAR", 1238, "Variable \'%-.192s\' is a %s variable" }, { "ER_WRONG_FK_DEF", 1239, "Incorrect foreign key definition for \'%-.192s\': %s" }, { "ER_KEY_REF_DO_NOT_MATCH_TABLE_REF", 1240, "Key reference and table reference don\'t match" }, { "ER_OPERAND_COLUMNS", 1241, "Operand should contain %d column(s)" }, { "ER_SUBQUERY_NO_1_ROW", 1242, "Subquery returns more than 1 row" }, { "ER_UNKNOWN_STMT_HANDLER", 1243, "Unknown prepared statement handler (%.*s) given to %s" }, { "ER_CORRUPT_HELP_DB", 1244, "Help database is corrupt or does not exist" }, { "ER_CYCLIC_REFERENCE", 1245, "Cyclic reference on subqueries" }, { "ER_AUTO_CONVERT", 1246, "Converting column \'%s\' from %s to %s" }, { "ER_ILLEGAL_REFERENCE", 1247, "Reference \'%-.64s\' not supported (%s)" }, { "ER_DERIVED_MUST_HAVE_ALIAS", 1248, "Every derived table must have its own alias" }, { "ER_SELECT_REDUCED", 1249, "Select %u was reduced during optimization" }, { "ER_TABLENAME_NOT_ALLOWED_HERE", 1250, "Table \'%-.192s\' from one of the SELECTs cannot be used in %-.32s" }, { "ER_NOT_SUPPORTED_AUTH_MODE", 1251, "Client does not support authentication protocol requested by server; consider upgrading MariaDB client" }, { "ER_SPATIAL_CANT_HAVE_NULL", 1252, "All parts of a SPATIAL index must be NOT NULL" }, { "ER_COLLATION_CHARSET_MISMATCH", 1253, "COLLATION \'%s\' is not valid for CHARACTER SET \'%s\'" }, { "ER_SLAVE_WAS_RUNNING", 1254, "Slave is already running" }, { "ER_SLAVE_WAS_NOT_RUNNING", 1255, "Slave already has been stopped" }, { "ER_TOO_BIG_FOR_UNCOMPRESS", 1256, "Uncompressed data size too large; the maximum size is %d (probably, length of uncompressed data was corrupted)" }, { "ER_ZLIB_Z_MEM_ERROR", 1257, "ZLIB: Not enough memory" }, { "ER_ZLIB_Z_BUF_ERROR", 1258, "ZLIB: Not enough room in the output buffer (probably, length of uncompressed data was corrupted)" }, { "ER_ZLIB_Z_DATA_ERROR", 1259, "ZLIB: Input data corrupted" }, { "ER_CUT_VALUE_GROUP_CONCAT", 1260, "Row %u was cut by %s)" }, { "ER_WARN_TOO_FEW_RECORDS", 1261, "Row %lu doesn\'t contain data for all columns" }, { "ER_WARN_TOO_MANY_RECORDS", 1262, "Row %lu was truncated; it contained more data than there were input columns" }, { "ER_WARN_NULL_TO_NOTNULL", 1263, "Column set to default value; NULL supplied to NOT NULL column \'%s\' at row %lu" }, { "ER_WARN_DATA_OUT_OF_RANGE", 1264, "Out of range value for column \'%s\' at row %lu" }, { "WARN_DATA_TRUNCATED", 1265, "Data truncated for column \'%s\' at row %lu" }, { "ER_WARN_USING_OTHER_HANDLER", 1266, "Using storage engine %s for table \'%s\'" }, { "ER_CANT_AGGREGATE_2COLLATIONS", 1267, "Illegal mix of collations (%s,%s) and (%s,%s) for operation \'%s\'" }, { "ER_DROP_USER", 1268, "Cannot drop one or more of the requested users" }, { "ER_REVOKE_GRANTS", 1269, "Can\'t revoke all privileges for one or more of the requested users" }, { "ER_CANT_AGGREGATE_3COLLATIONS", 1270, "Illegal mix of collations (%s,%s), (%s,%s), (%s,%s) for operation \'%s\'" }, { "ER_CANT_AGGREGATE_NCOLLATIONS", 1271, "Illegal mix of collations for operation \'%s\'" }, { "ER_VARIABLE_IS_NOT_STRUCT", 1272, "Variable \'%-.64s\' is not a variable component (can\'t be used as XXXX.variable_name)" }, { "ER_UNKNOWN_COLLATION", 1273, "Unknown collation: \'%-.64s\'" }, { "ER_SLAVE_IGNORED_SSL_PARAMS", 1274, "SSL parameters in CHANGE MASTER are ignored because this MariaDB slave was compiled without SSL support; they can be used later if MariaDB slave with SSL is started" }, { "ER_SERVER_IS_IN_SECURE_AUTH_MODE", 1275, "Server is running in --secure-auth mode, but \'%s\'@\'%s\' has a password in the old format; please change the password to the new format" }, { "ER_WARN_FIELD_RESOLVED", 1276, "Field or reference \'%-.192s%s%-.192s%s%-.192s\' of SELECT #%d was resolved in SELECT #%d" }, { "ER_BAD_SLAVE_UNTIL_COND", 1277, "Incorrect parameter or combination of parameters for START SLAVE UNTIL" }, { "ER_MISSING_SKIP_SLAVE", 1278, "It is recommended to use --skip-slave-start when doing step-by-step replication with START SLAVE UNTIL; otherwise, you will get problems if you get an unexpected slave\'s mariadbd restart" }, { "ER_UNTIL_COND_IGNORED", 1279, "SQL thread is not to be started so UNTIL options are ignored" }, { "ER_WRONG_NAME_FOR_INDEX", 1280, "Incorrect index name \'%-.100s\'" }, { "ER_WRONG_NAME_FOR_CATALOG", 1281, "Incorrect catalog name \'%-.100s\'" }, { "ER_WARN_QC_RESIZE", 1282, "Query cache failed to set size %llu; new query cache size is %lu" }, { "ER_BAD_FT_COLUMN", 1283, "Column \'%-.192s\' cannot be part of FULLTEXT index" }, { "ER_UNKNOWN_KEY_CACHE", 1284, "Unknown key cache \'%-.100s\'" }, { "ER_WARN_HOSTNAME_WONT_WORK", 1285, "MariaDB is started in --skip-name-resolve mode; you must restart it without this switch for this grant to work" }, { "ER_UNKNOWN_STORAGE_ENGINE", 1286, "Unknown storage engine \'%s\'" }, { "ER_WARN_DEPRECATED_SYNTAX", 1287, "\'%s\' is deprecated and will be removed in a future release. Please use %s instead" }, { "ER_NON_UPDATABLE_TABLE", 1288, "The target table %-.100s of the %s is not updatable" }, { "ER_FEATURE_DISABLED", 1289, "The \'%s\' feature is disabled; you need MariaDB built with \'%s\' to have it working" }, { "ER_OPTION_PREVENTS_STATEMENT", 1290, "The MariaDB server is running with the %s option so it cannot execute this statement" }, { "ER_DUPLICATED_VALUE_IN_TYPE", 1291, "Column \'%-.100s\' has duplicated value \'%-.64s\' in %s" }, { "ER_TRUNCATED_WRONG_VALUE", 1292, "Truncated incorrect %-.32T value: \'%-.128T\'" }, { "ER_TOO_MUCH_AUTO_TIMESTAMP_COLS", 1293, "Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause" }, { "ER_INVALID_ON_UPDATE", 1294, "Invalid ON UPDATE clause for \'%-.192s\' column" }, { "ER_UNSUPPORTED_PS", 1295, "This command is not supported in the prepared statement protocol yet" }, { "ER_GET_ERRMSG", 1296, "Got error %d \'%-.200s\' from %s" }, { "ER_GET_TEMPORARY_ERRMSG", 1297, "Got temporary error %d \'%-.200s\' from %s" }, { "ER_UNKNOWN_TIME_ZONE", 1298, "Unknown or incorrect time zone: \'%-.64s\'" }, { "ER_WARN_INVALID_TIMESTAMP", 1299, "Invalid TIMESTAMP value in column \'%s\' at row %lu" }, { "ER_INVALID_CHARACTER_STRING", 1300, "Invalid %s character string: \'%.64T\'" }, { "ER_WARN_ALLOWED_PACKET_OVERFLOWED", 1301, "Result of %s() was larger than max_allowed_packet (%ld) - truncated" }, { "ER_CONFLICTING_DECLARATIONS", 1302, "Conflicting declarations: \'%s%s\' and \'%s%s\'" }, { "ER_SP_NO_RECURSIVE_CREATE", 1303, "Can\'t create a %s from within another stored routine" }, { "ER_SP_ALREADY_EXISTS", 1304, "%s %s already exists" }, { "ER_SP_DOES_NOT_EXIST", 1305, "%s %s does not exist" }, { "ER_SP_DROP_FAILED", 1306, "Failed to DROP %s %s" }, { "ER_SP_STORE_FAILED", 1307, "Failed to CREATE %s %s" }, { "ER_SP_LILABEL_MISMATCH", 1308, "%s with no matching label: %s" }, { "ER_SP_LABEL_REDEFINE", 1309, "Redefining label %s" }, { "ER_SP_LABEL_MISMATCH", 1310, "End-label %s without match" }, { "ER_SP_UNINIT_VAR", 1311, "Referring to uninitialized variable %s" }, { "ER_SP_BADSELECT", 1312, "PROCEDURE %s can\'t return a result set in the given context" }, { "ER_SP_BADRETURN", 1313, "RETURN is only allowed in a FUNCTION" }, { "ER_SP_BADSTATEMENT", 1314, "%s is not allowed in stored procedures" }, { "ER_UPDATE_LOG_DEPRECATED_IGNORED", 1315, "The update log is deprecated and replaced by the binary log; SET SQL_LOG_UPDATE has been ignored. This option will be removed in MariaDB 5.6" }, { "ER_UPDATE_LOG_DEPRECATED_TRANSLATED", 1316, "The update log is deprecated and replaced by the binary log; SET SQL_LOG_UPDATE has been translated to SET SQL_LOG_BIN. This option will be removed in MariaDB 5.6" }, { "ER_QUERY_INTERRUPTED", 1317, "Query execution was interrupted" }, { "ER_SP_WRONG_NO_OF_ARGS", 1318, "Incorrect number of arguments for %s %s; expected %u, got %u" }, { "ER_SP_COND_MISMATCH", 1319, "Undefined CONDITION: %s" }, { "ER_SP_NORETURN", 1320, "No RETURN found in FUNCTION %s" }, { "ER_SP_NORETURNEND", 1321, "FUNCTION %s ended without RETURN" }, { "ER_SP_BAD_CURSOR_QUERY", 1322, "Cursor statement must be a SELECT" }, { "ER_SP_BAD_CURSOR_SELECT", 1323, "Cursor SELECT must not have INTO" }, { "ER_SP_CURSOR_MISMATCH", 1324, "Undefined CURSOR: %s" }, { "ER_SP_CURSOR_ALREADY_OPEN", 1325, "Cursor is already open" }, { "ER_SP_CURSOR_NOT_OPEN", 1326, "Cursor is not open" }, { "ER_SP_UNDECLARED_VAR", 1327, "Undeclared variable: %s" }, { "ER_SP_WRONG_NO_OF_FETCH_ARGS", 1328, "Incorrect number of FETCH variables" }, { "ER_SP_FETCH_NO_DATA", 1329, "No data - zero rows fetched, selected, or processed" }, { "ER_SP_DUP_PARAM", 1330, "Duplicate parameter: %s" }, { "ER_SP_DUP_VAR", 1331, "Duplicate variable: %s" }, { "ER_SP_DUP_COND", 1332, "Duplicate condition: %s" }, { "ER_SP_DUP_CURS", 1333, "Duplicate cursor: %s" }, { "ER_SP_CANT_ALTER", 1334, "Failed to ALTER %s %s" }, { "ER_SP_SUBSELECT_NYI", 1335, "Subquery value not supported" }, { "ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG", 1336, "%s is not allowed in stored function or trigger" }, { "ER_SP_VARCOND_AFTER_CURSHNDLR", 1337, "Variable or condition declaration after cursor or handler declaration" }, { "ER_SP_CURSOR_AFTER_HANDLER", 1338, "Cursor declaration after handler declaration" }, { "ER_SP_CASE_NOT_FOUND", 1339, "Case not found for CASE statement" }, { "ER_FPARSER_TOO_BIG_FILE", 1340, "Configuration file \'%-.192s\' is too big" }, { "ER_FPARSER_BAD_HEADER", 1341, "Malformed file type header in file \'%-.192s\'" }, { "ER_FPARSER_EOF_IN_COMMENT", 1342, "Unexpected end of file while parsing comment \'%-.200s\'" }, { "ER_FPARSER_ERROR_IN_PARAMETER", 1343, "Error while parsing parameter \'%-.192s\' (line: \'%-.192s\')" }, { "ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER", 1344, "Unexpected end of file while skipping unknown parameter \'%-.192s\'" }, { "ER_VIEW_NO_EXPLAIN", 1345, "ANALYZE/EXPLAIN/SHOW can not be issued; lacking privileges for underlying table" }, { "ER_FRM_UNKNOWN_TYPE", 1346, "File \'%-.192s\' has unknown type \'%-.64s\' in its header" }, { "ER_WRONG_OBJECT", 1347, "\'%-.192s.%-.192s\' is not of type \'%s\'" }, { "ER_NONUPDATEABLE_COLUMN", 1348, "Column \'%-.192s\' is not updatable" }, { "ER_VIEW_SELECT_DERIVED", 1349, "View\'s SELECT contains a subquery in the FROM clause" }, { "ER_VIEW_SELECT_CLAUSE", 1350, "View\'s SELECT contains a \'%s\' clause" }, { "ER_VIEW_SELECT_VARIABLE", 1351, "View\'s SELECT contains a variable or parameter" }, { "ER_VIEW_SELECT_TMPTABLE", 1352, "View\'s SELECT refers to a temporary table \'%-.192s\'" }, { "ER_VIEW_WRONG_LIST", 1353, "View\'s SELECT and view\'s field list have different column counts" }, { "ER_WARN_VIEW_MERGE", 1354, "View merge algorithm can\'t be used here for now (assumed undefined algorithm)" }, { "ER_WARN_VIEW_WITHOUT_KEY", 1355, "View being updated does not have complete key of underlying table in it" }, { "ER_VIEW_INVALID", 1356, "View \'%-.192s.%-.192s\' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them" }, { "ER_SP_NO_DROP_SP", 1357, "Can\'t drop or alter a %s from within another stored routine" }, { "ER_SP_GOTO_IN_HNDLR", 1358, "GOTO is not allowed in a stored procedure handler" }, { "ER_TRG_ALREADY_EXISTS", 1359, "Trigger \'%s\' already exists" }, { "ER_TRG_DOES_NOT_EXIST", 1360, "Trigger does not exist" }, { "ER_TRG_ON_VIEW_OR_TEMP_TABLE", 1361, "Trigger\'s \'%-.192s\' is a view, temporary table or sequence" }, { "ER_TRG_CANT_CHANGE_ROW", 1362, "Updating of %s row is not allowed in %strigger" }, { "ER_TRG_NO_SUCH_ROW_IN_TRG", 1363, "There is no %s row in %s trigger" }, { "ER_NO_DEFAULT_FOR_FIELD", 1364, "Field \'%-.192s\' doesn\'t have a default value" }, { "ER_DIVISION_BY_ZERO", 1365, "Division by 0" }, { "ER_TRUNCATED_WRONG_VALUE_FOR_FIELD", 1366, "Incorrect %-.32s value: \'%-.128T\' for column `%.192s`.`%.192s`.`%.192s` at row %lu" }, { "ER_ILLEGAL_VALUE_FOR_TYPE", 1367, "Illegal %s \'%-.192T\' value found during parsing" }, { "ER_VIEW_NONUPD_CHECK", 1368, "CHECK OPTION on non-updatable view %`-.192s.%`-.192s" }, { "ER_VIEW_CHECK_FAILED", 1369, "CHECK OPTION failed %`-.192s.%`-.192s" }, { "ER_PROCACCESS_DENIED_ERROR", 1370, "%-.32s command denied to user \'%s\'@\'%s\' for routine \'%-.192s\'" }, { "ER_RELAY_LOG_FAIL", 1371, "Failed purging old relay logs: %s" }, { "ER_PASSWD_LENGTH", 1372, "Password hash should be a %d-digit hexadecimal number" }, { "ER_UNKNOWN_TARGET_BINLOG", 1373, "Target log not found in binlog index" }, { "ER_IO_ERR_LOG_INDEX_READ", 1374, "I/O error reading log index file" }, { "ER_BINLOG_PURGE_PROHIBITED", 1375, "Server configuration does not permit binlog purge" }, { "ER_FSEEK_FAIL", 1376, "Failed on fseek()" }, { "ER_BINLOG_PURGE_FATAL_ERR", 1377, "Fatal error during log purge" }, { "ER_LOG_IN_USE", 1378, "A purgeable log is in use, will not purge" }, { "ER_LOG_PURGE_UNKNOWN_ERR", 1379, "Unknown error during log purge" }, { "ER_RELAY_LOG_INIT", 1380, "Failed initializing relay log position: %s" }, { "ER_NO_BINARY_LOGGING", 1381, "You are not using binary logging" }, { "ER_RESERVED_SYNTAX", 1382, "The \'%-.64s\' syntax is reserved for purposes internal to the MariaDB server" }, { "ER_WSAS_FAILED", 1383, "WSAStartup Failed" }, { "ER_DIFF_GROUPS_PROC", 1384, "Can\'t handle procedures with different groups yet" }, { "ER_NO_GROUP_FOR_PROC", 1385, "Select must have a group with this procedure" }, { "ER_ORDER_WITH_PROC", 1386, "Can\'t use ORDER clause with this procedure" }, { "ER_LOGGING_PROHIBIT_CHANGING_OF", 1387, "Binary logging and replication forbid changing the global server %s" }, { "ER_NO_FILE_MAPPING", 1388, "Can\'t map file: %-.200s, errno: %M" }, { "ER_WRONG_MAGIC", 1389, "Wrong magic in %-.64s" }, { "ER_PS_MANY_PARAM", 1390, "Prepared statement contains too many placeholders" }, { "ER_KEY_PART_0", 1391, "Key part \'%-.192s\' length cannot be 0" }, { "ER_VIEW_CHECKSUM", 1392, "View text checksum failed" }, { "ER_VIEW_MULTIUPDATE", 1393, "Can not modify more than one base table through a join view \'%-.192s.%-.192s\'" }, { "ER_VIEW_NO_INSERT_FIELD_LIST", 1394, "Can not insert into join view \'%-.192s.%-.192s\' without fields list" }, { "ER_VIEW_DELETE_MERGE_VIEW", 1395, "Can not delete from join view \'%-.192s.%-.192s\'" }, { "ER_CANNOT_USER", 1396, "Operation %s failed for %.256s" }, { "ER_XAER_NOTA", 1397, "XAER_NOTA: Unknown XID" }, { "ER_XAER_INVAL", 1398, "XAER_INVAL: Invalid arguments (or unsupported command)" }, { "ER_XAER_RMFAIL", 1399, "XAER_RMFAIL: The command cannot be executed when global transaction is in the %.64s state" }, { "ER_XAER_OUTSIDE", 1400, "XAER_OUTSIDE: Some work is done outside global transaction" }, { "ER_XAER_RMERR", 1401, "XAER_RMERR: Fatal error occurred in the transaction branch - check your data for consistency" }, { "ER_XA_RBROLLBACK", 1402, "XA_RBROLLBACK: Transaction branch was rolled back" }, { "ER_NONEXISTING_PROC_GRANT", 1403, "There is no such grant defined for user \'%-.48s\' on host \'%-.64s\' on routine \'%-.192s\'" }, { "ER_PROC_AUTO_GRANT_FAIL", 1404, "Failed to grant EXECUTE and ALTER ROUTINE privileges" }, { "ER_PROC_AUTO_REVOKE_FAIL", 1405, "Failed to revoke all privileges to dropped routine" }, { "ER_DATA_TOO_LONG", 1406, "Data too long for column \'%s\' at row %lu" }, { "ER_SP_BAD_SQLSTATE", 1407, "Bad SQLSTATE: \'%s\'" }, { "ER_STARTUP", 1408, "%s: ready for connections.\nVersion: \'%s\' socket: \'%s\' port: %d %s" }, { "ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR", 1409, "Can\'t load value from file with fixed size rows to variable" }, { "ER_CANT_CREATE_USER_WITH_GRANT", 1410, "You are not allowed to create a user with GRANT" }, { "ER_WRONG_VALUE_FOR_TYPE", 1411, "Incorrect %-.32s value: \'%-.128T\' for function %-.32s" }, { "ER_TABLE_DEF_CHANGED", 1412, "Table definition has changed, please retry transaction" }, { "ER_SP_DUP_HANDLER", 1413, "Duplicate handler declared in the same block" }, { "ER_SP_NOT_VAR_ARG", 1414, "OUT or INOUT argument %d for routine %s is not a variable or NEW pseudo-variable in BEFORE trigger" }, { "ER_SP_NO_RETSET", 1415, "Not allowed to return a result set from a %s" }, { "ER_CANT_CREATE_GEOMETRY_OBJECT", 1416, "Cannot get geometry object from data you send to the GEOMETRY field" }, { "ER_FAILED_ROUTINE_BREAK_BINLOG", 1417, "A routine failed and has neither NO SQL nor READS SQL DATA in its declaration and binary logging is enabled; if non-transactional tables were updated, the binary log will miss their changes" }, { "ER_BINLOG_UNSAFE_ROUTINE", 1418, "This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)" }, { "ER_BINLOG_CREATE_ROUTINE_NEED_SUPER", 1419, "You do not have the SUPER privilege and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)" }, { "ER_EXEC_STMT_WITH_OPEN_CURSOR", 1420, "You can\'t execute a prepared statement which has an open cursor associated with it. Reset the statement to re-execute it" }, { "ER_STMT_HAS_NO_OPEN_CURSOR", 1421, "The statement (%lu) has no open cursor" }, { "ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG", 1422, "Explicit or implicit commit is not allowed in stored function or trigger" }, { "ER_NO_DEFAULT_FOR_VIEW_FIELD", 1423, "Field of view \'%-.192s.%-.192s\' underlying table doesn\'t have a default value" }, { "ER_SP_NO_RECURSION", 1424, "Recursive stored functions and triggers are not allowed" }, { "ER_TOO_BIG_SCALE", 1425, "Too big scale %llu specified for \'%-.192s\'. Maximum is %u" }, { "ER_TOO_BIG_PRECISION", 1426, "Too big precision %llu specified for \'%-.192s\'. Maximum is %u" }, { "ER_M_BIGGER_THAN_D", 1427, "For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column \'%-.192s\')" }, { "ER_WRONG_LOCK_OF_SYSTEM_TABLE", 1428, "You can\'t combine write-locking of system tables with other tables or lock types" }, { "ER_CONNECT_TO_FOREIGN_DATA_SOURCE", 1429, "Unable to connect to foreign data source: %.64s" }, { "ER_QUERY_ON_FOREIGN_DATA_SOURCE", 1430, "There was a problem processing the query on the foreign data source. Data source error: %-.64s" }, { "ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST", 1431, "The foreign data source you are trying to reference does not exist. Data source error: %-.64s" }, { "ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE", 1432, "Can\'t create federated table. The data source connection string \'%-.64s\' is not in the correct format" }, { "ER_FOREIGN_DATA_STRING_INVALID", 1433, "The data source connection string \'%-.64s\' is not in the correct format" }, { "ER_CANT_CREATE_FEDERATED_TABLE", 1434, "Can\'t create federated table. Foreign data src error: %-.64s" }, { "ER_TRG_IN_WRONG_SCHEMA", 1435, "Trigger in wrong schema" }, { "ER_STACK_OVERRUN_NEED_MORE", 1436, "Thread stack overrun: %ld bytes used of a %ld byte stack, and %ld bytes needed. Consider increasing the thread_stack system variable." }, { "ER_TOO_LONG_BODY", 1437, "Routine body for \'%-.100s\' is too long" }, { "ER_WARN_CANT_DROP_DEFAULT_KEYCACHE", 1438, "Cannot drop default keycache" }, { "ER_TOO_BIG_DISPLAYWIDTH", 1439, "Display width out of range for \'%-.192s\' (max = %lu)" }, { "ER_XAER_DUPID", 1440, "XAER_DUPID: The XID already exists" }, { "ER_DATETIME_FUNCTION_OVERFLOW", 1441, "Datetime function: %-.32s field overflow" }, { "ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG", 1442, "Can\'t update table \'%-.192s\' in stored function/trigger because it is already used by statement which invoked this stored function/trigger" }, { "ER_VIEW_PREVENT_UPDATE", 1443, "The definition of table \'%-.192s\' prevents operation %-.192s on table \'%-.192s\'" }, { "ER_PS_NO_RECURSION", 1444, "The prepared statement contains a stored routine call that refers to that same statement. It\'s not allowed to execute a prepared statement in such a recursive manner" }, { "ER_SP_CANT_SET_AUTOCOMMIT", 1445, "Not allowed to set autocommit from a stored function or trigger" }, { "ER_MALFORMED_DEFINER", 1446, "Invalid definer" }, { "ER_VIEW_FRM_NO_USER", 1447, "View \'%-.192s\'.\'%-.192s\' has no definer information (old table format). Current user is used as definer. Please recreate the view!" }, { "ER_VIEW_OTHER_USER", 1448, "You need the SUPER privilege for creation view with \'%-.192s\'@\'%-.192s\' definer" }, { "ER_NO_SUCH_USER", 1449, "The user specified as a definer (\'%-.64s\'@\'%-.64s\') does not exist" }, { "ER_FORBID_SCHEMA_CHANGE", 1450, "Changing schema from \'%-.192s\' to \'%-.192s\' is not allowed" }, { "ER_ROW_IS_REFERENCED_2", 1451, "Cannot delete or update a parent row: a foreign key constraint fails (%s)" }, { "ER_NO_REFERENCED_ROW_2", 1452, "Cannot add or update a child row: a foreign key constraint fails (%s)" }, { "ER_SP_BAD_VAR_SHADOW", 1453, "Variable \'%-.64s\' must be quoted with `...`, or renamed" }, { "ER_TRG_NO_DEFINER", 1454, "No definer attribute for trigger \'%-.192s\'.\'%-.192s\'. The trigger will be activated under the authorization of the invoker, which may have insufficient privileges. Please recreate the trigger" }, { "ER_OLD_FILE_FORMAT", 1455, "\'%-.192s\' has an old format, you should re-create the \'%s\' object(s)" }, { "ER_SP_RECURSION_LIMIT", 1456, "Recursive limit %d (as set by the max_sp_recursion_depth variable) was exceeded for routine %.192s" }, { "ER_SP_PROC_TABLE_CORRUPT", 1457, "Failed to load routine %-.192s (internal code %d). For more details, run SHOW WARNINGS" }, { "ER_SP_WRONG_NAME", 1458, "Incorrect routine name \'%-.192s\'" }, { "ER_TABLE_NEEDS_UPGRADE", 1459, "Upgrade required. Please do \"REPAIR %s %`s\" or dump/reload to fix it!" }, { "ER_SP_NO_AGGREGATE", 1460, "AGGREGATE is not supported for stored functions" }, { "ER_MAX_PREPARED_STMT_COUNT_REACHED", 1461, "Can\'t create more than max_prepared_stmt_count statements (current value: %u)" }, { "ER_VIEW_RECURSIVE", 1462, "%`s.%`s contains view recursion" }, { "ER_NON_GROUPING_FIELD_USED", 1463, "Non-grouping field \'%-.192s\' is used in %-.64s clause" }, { "ER_TABLE_CANT_HANDLE_SPKEYS", 1464, "The storage engine %s doesn\'t support SPATIAL indexes" }, { "ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA", 1465, "Triggers can not be created on system tables" }, { "ER_REMOVED_SPACES", 1466, "Leading spaces are removed from name \'%s\'" }, { "ER_AUTOINC_READ_FAILED", 1467, "Failed to read auto-increment value from storage engine" }, { "ER_USERNAME", 1468, "user name" }, { "ER_HOSTNAME", 1469, "host name" }, { "ER_WRONG_STRING_LENGTH", 1470, "String \'%-.70T\' is too long for %s (should be no longer than %d)" }, { "ER_NON_INSERTABLE_TABLE", 1471, "The target table %-.100s of the %s is not insertable-into" }, { "ER_ADMIN_WRONG_MRG_TABLE", 1472, "Table \'%-.64s\' is differently defined or of non-MyISAM type or doesn\'t exist" }, { "ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT", 1473, "Too high level of nesting for select" }, { "ER_NAME_BECOMES_EMPTY", 1474, "Name \'%-.64s\' has become \'\'" }, { "ER_AMBIGUOUS_FIELD_TERM", 1475, "First character of the FIELDS TERMINATED string is ambiguous; please use non-optional and non-empty FIELDS ENCLOSED BY" }, { "ER_FOREIGN_SERVER_EXISTS", 1476, "Cannot create foreign server \'%s\' as it already exists" }, { "ER_FOREIGN_SERVER_DOESNT_EXIST", 1477, "The foreign server name you are trying to reference does not exist. Data source error: %-.64s" }, { "ER_ILLEGAL_HA_CREATE_OPTION", 1478, "Table storage engine \'%-.64s\' does not support the create option \'%.64s\'" }, { "ER_PARTITION_REQUIRES_VALUES_ERROR", 1479, "Syntax error: %-.64s PARTITIONING requires definition of VALUES %-.64s for each partition" }, { "ER_PARTITION_WRONG_VALUES_ERROR", 1480, "Only %-.64s PARTITIONING can use VALUES %-.64s in partition definition" }, { "ER_PARTITION_MAXVALUE_ERROR", 1481, "MAXVALUE can only be used in last partition definition" }, { "ER_PARTITION_SUBPARTITION_ERROR", 1482, "Subpartitions can only be hash partitions and by key" }, { "ER_PARTITION_SUBPART_MIX_ERROR", 1483, "Must define subpartitions on all partitions if on one partition" }, { "ER_PARTITION_WRONG_NO_PART_ERROR", 1484, "Wrong number of partitions defined, mismatch with previous setting" }, { "ER_PARTITION_WRONG_NO_SUBPART_ERROR", 1485, "Wrong number of subpartitions defined, mismatch with previous setting" }, { "ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR", 1486, "Constant, random or timezone-dependent expressions in (sub)partitioning function are not allowed" }, { "ER_NOT_CONSTANT_EXPRESSION", 1487, "Expression in %s must be constant" }, { "ER_FIELD_NOT_FOUND_PART_ERROR", 1488, "Field in list of fields for partition function not found in table" }, { "ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR", 1489, "List of fields is only allowed in KEY partitions" }, { "ER_INCONSISTENT_PARTITION_INFO_ERROR", 1490, "The partition info in the frm file is not consistent with what can be written into the frm file" }, { "ER_PARTITION_FUNC_NOT_ALLOWED_ERROR", 1491, "The %-.192s function returns the wrong type" }, { "ER_PARTITIONS_MUST_BE_DEFINED_ERROR", 1492, "For %-.64s partitions each partition must be defined" }, { "ER_RANGE_NOT_INCREASING_ERROR", 1493, "VALUES LESS THAN value must be strictly increasing for each partition" }, { "ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR", 1494, "VALUES value must be of same type as partition function" }, { "ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR", 1495, "Multiple definition of same constant in list partitioning" }, { "ER_PARTITION_ENTRY_ERROR", 1496, "Partitioning can not be used stand-alone in query" }, { "ER_MIX_HANDLER_ERROR", 1497, "The mix of handlers in the partitions is not allowed in this version of MariaDB" }, { "ER_PARTITION_NOT_DEFINED_ERROR", 1498, "For the partitioned engine it is necessary to define all %-.64s" }, { "ER_TOO_MANY_PARTITIONS_ERROR", 1499, "Too many partitions (including subpartitions) were defined" }, { "ER_SUBPARTITION_ERROR", 1500, "It is only possible to mix RANGE/LIST partitioning with HASH/KEY partitioning for subpartitioning" }, { "ER_CANT_CREATE_HANDLER_FILE", 1501, "Failed to create specific handler file" }, { "ER_BLOB_FIELD_IN_PART_FUNC_ERROR", 1502, "A BLOB field is not allowed in partition function" }, { "ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF", 1503, "A %-.192s must include all columns in the table\'s partitioning function" }, { "ER_NO_PARTS_ERROR", 1504, "Number of %-.64s = 0 is not an allowed value" }, { "ER_PARTITION_MGMT_ON_NONPARTITIONED", 1505, "Partition management on a not partitioned table is not possible" }, { "ER_FEATURE_NOT_SUPPORTED_WITH_PARTITIONING", 1506, "Partitioned tables do not support %s" }, { "ER_DROP_PARTITION_NON_EXISTENT", 1507, "Error in list of partitions to %-.64s" }, { "ER_DROP_LAST_PARTITION", 1508, "Cannot remove all partitions, use DROP TABLE instead" }, { "ER_COALESCE_ONLY_ON_HASH_PARTITION", 1509, "COALESCE PARTITION can only be used on HASH/KEY partitions" }, { "ER_REORG_HASH_ONLY_ON_SAME_NO", 1510, "REORGANIZE PARTITION can only be used to reorganize partitions not to change their numbers" }, { "ER_REORG_NO_PARAM_ERROR", 1511, "REORGANIZE PARTITION without parameters can only be used on auto-partitioned tables using HASH PARTITIONs" }, { "ER_ONLY_ON_RANGE_LIST_PARTITION", 1512, "%-.64s PARTITION can only be used on RANGE/LIST partitions" }, { "ER_ADD_PARTITION_SUBPART_ERROR", 1513, "Trying to Add partition(s) with wrong number of subpartitions" }, { "ER_ADD_PARTITION_NO_NEW_PARTITION", 1514, "At least one partition must be added" }, { "ER_COALESCE_PARTITION_NO_PARTITION", 1515, "At least one partition must be coalesced" }, { "ER_REORG_PARTITION_NOT_EXIST", 1516, "More partitions to reorganize than there are partitions" }, { "ER_SAME_NAME_PARTITION", 1517, "Duplicate partition name %-.192s" }, { "ER_NO_BINLOG_ERROR", 1518, "It is not allowed to shut off binlog on this command" }, { "ER_CONSECUTIVE_REORG_PARTITIONS", 1519, "When reorganizing a set of partitions they must be in consecutive order" }, { "ER_REORG_OUTSIDE_RANGE", 1520, "Reorganize of range partitions cannot change total ranges except for last partition where it can extend the range" }, { "ER_PARTITION_FUNCTION_FAILURE", 1521, "Partition function not supported in this version for this handler" }, { "ER_PART_STATE_ERROR", 1522, "Partition state cannot be defined from CREATE/ALTER TABLE" }, { "ER_LIMITED_PART_RANGE", 1523, "The %-.64s handler only supports 32 bit integers in VALUES" }, { "ER_PLUGIN_IS_NOT_LOADED", 1524, "Plugin \'%-.192s\' is not loaded" }, { "ER_WRONG_VALUE", 1525, "Incorrect %-.32s value: \'%-.128T\'" }, { "ER_NO_PARTITION_FOR_GIVEN_VALUE", 1526, "Table has no partition for value %-.64s" }, { "ER_FILEGROUP_OPTION_ONLY_ONCE", 1527, "It is not allowed to specify %s more than once" }, { "ER_CREATE_FILEGROUP_FAILED", 1528, "Failed to create %s" }, { "ER_DROP_FILEGROUP_FAILED", 1529, "Failed to drop %s" }, { "ER_TABLESPACE_AUTO_EXTEND_ERROR", 1530, "The handler doesn\'t support autoextend of tablespaces" }, { "ER_WRONG_SIZE_NUMBER", 1531, "A size parameter was incorrectly specified, either number or on the form 10M" }, { "ER_SIZE_OVERFLOW_ERROR", 1532, "The size number was correct but we don\'t allow the digit part to be more than 2 billion" }, { "ER_ALTER_FILEGROUP_FAILED", 1533, "Failed to alter: %s" }, { "ER_BINLOG_ROW_LOGGING_FAILED", 1534, "Writing one row to the row-based binary log failed" }, { "ER_BINLOG_ROW_WRONG_TABLE_DEF", 1535, "Table definition on master and slave does not match: %s" }, { "ER_BINLOG_ROW_RBR_TO_SBR", 1536, "Slave running with --log-slave-updates must use row-based binary logging to be able to replicate row-based binary log events" }, { "ER_EVENT_ALREADY_EXISTS", 1537, "Event \'%-.192s\' already exists" }, { "ER_EVENT_STORE_FAILED", 1538, "Failed to store event %s. Error code %M from storage engine" }, { "ER_EVENT_DOES_NOT_EXIST", 1539, "Unknown event \'%-.192s\'" }, { "ER_EVENT_CANT_ALTER", 1540, "Failed to alter event \'%-.192s\'" }, { "ER_EVENT_DROP_FAILED", 1541, "Failed to drop %s" }, { "ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG", 1542, "INTERVAL is either not positive or too big" }, { "ER_EVENT_ENDS_BEFORE_STARTS", 1543, "ENDS is either invalid or before STARTS" }, { "ER_EVENT_EXEC_TIME_IN_THE_PAST", 1544, "Event execution time is in the past. Event has been disabled" }, { "ER_EVENT_OPEN_TABLE_FAILED", 1545, "Failed to open mysql.event" }, { "ER_EVENT_NEITHER_M_EXPR_NOR_M_AT", 1546, "No datetime expression provided" }, { "ER_UNUSED_2", 1547, "You should never see it" }, { "ER_UNUSED_3", 1548, "You should never see it" }, { "ER_EVENT_CANNOT_DELETE", 1549, "Failed to delete the event from mysql.event" }, { "ER_EVENT_COMPILE_ERROR", 1550, "Error during compilation of event\'s body" }, { "ER_EVENT_SAME_NAME", 1551, "Same old and new event name" }, { "ER_EVENT_DATA_TOO_LONG", 1552, "Data for column \'%s\' too long" }, { "ER_DROP_INDEX_FK", 1553, "Cannot drop index \'%-.192s\': needed in a foreign key constraint" }, { "ER_WARN_DEPRECATED_SYNTAX_WITH_VER", 1554, "The syntax \'%s\' is deprecated and will be removed in MariaDB %s. Please use %s instead" }, { "ER_CANT_WRITE_LOCK_LOG_TABLE", 1555, "You can\'t write-lock a log table. Only read access is possible" }, { "ER_CANT_LOCK_LOG_TABLE", 1556, "You can\'t use locks with log tables" }, { "ER_UNUSED_4", 1557, "You should never see it" }, { "ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE", 1558, "Column count of mysql.%s is wrong. Expected %d, found %d. Created with MariaDB %d, now running %d. Please use mariadb-upgrade to fix this error" }, { "ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR", 1559, "Cannot switch out of the row-based binary log format when the session has open temporary tables" }, { "ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT", 1560, "Cannot change the binary logging format inside a stored function or trigger" }, { "ER_UNUSED_13", 1561, "You should never see it" }, { "ER_PARTITION_NO_TEMPORARY", 1562, "Cannot create temporary table with partitions" }, { "ER_PARTITION_CONST_DOMAIN_ERROR", 1563, "Partition constant is out of partition function domain" }, { "ER_PARTITION_FUNCTION_IS_NOT_ALLOWED", 1564, "This partition function is not allowed" }, { "ER_DDL_LOG_ERROR", 1565, "Error in DDL log" }, { "ER_NULL_IN_VALUES_LESS_THAN", 1566, "Not allowed to use NULL value in VALUES LESS THAN" }, { "ER_WRONG_PARTITION_NAME", 1567, "Incorrect partition name" }, { "ER_CANT_CHANGE_TX_CHARACTERISTICS", 1568, "Transaction characteristics can\'t be changed while a transaction is in progress" }, { "ER_DUP_ENTRY_AUTOINCREMENT_CASE", 1569, "ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry \'%-.192T\' for key \'%-.192s\'" }, { "ER_EVENT_MODIFY_QUEUE_ERROR", 1570, "Internal scheduler error %d" }, { "ER_EVENT_SET_VAR_ERROR", 1571, "Error during starting/stopping of the scheduler. Error code %M" }, { "ER_PARTITION_MERGE_ERROR", 1572, "Engine cannot be used in partitioned tables" }, { "ER_CANT_ACTIVATE_LOG", 1573, "Cannot activate \'%-.64s\' log" }, { "ER_RBR_NOT_AVAILABLE", 1574, "The server was not built with row-based replication" }, { "ER_BASE64_DECODE_ERROR", 1575, "Decoding of base64 string failed" }, { "ER_EVENT_RECURSION_FORBIDDEN", 1576, "Recursion of EVENT DDL statements is forbidden when body is present" }, { "ER_EVENTS_DB_ERROR", 1577, "Cannot proceed, because event scheduler is disabled" }, { "ER_ONLY_INTEGERS_ALLOWED", 1578, "Only integers allowed as number here" }, { "ER_UNSUPORTED_LOG_ENGINE", 1579, "Storage engine %s cannot be used for log tables" }, { "ER_BAD_LOG_STATEMENT", 1580, "You cannot \'%s\' a log table if logging is enabled" }, { "ER_CANT_RENAME_LOG_TABLE", 1581, "Cannot rename \'%s\'. When logging enabled, rename to/from log table must rename two tables: the log table to an archive table and another table back to \'%s\'" }, { "ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT", 1582, "Incorrect parameter count in the call to native function \'%-.192s\'" }, { "ER_WRONG_PARAMETERS_TO_NATIVE_FCT", 1583, "Incorrect parameters in the call to native function \'%-.192s\'" }, { "ER_WRONG_PARAMETERS_TO_STORED_FCT", 1584, "Incorrect parameters in the call to stored function \'%-.192s\'" }, { "ER_NATIVE_FCT_NAME_COLLISION", 1585, "This function \'%-.192s\' has the same name as a native function" }, { "ER_DUP_ENTRY_WITH_KEY_NAME", 1586, "Duplicate entry \'%-.64T\' for key \'%-.192s\'" }, { "ER_BINLOG_PURGE_EMFILE", 1587, "Too many files opened, please execute the command again" }, { "ER_EVENT_CANNOT_CREATE_IN_THE_PAST", 1588, "Event execution time is in the past and ON COMPLETION NOT PRESERVE is set. The event was dropped immediately after creation" }, { "ER_EVENT_CANNOT_ALTER_IN_THE_PAST", 1589, "Event execution time is in the past and ON COMPLETION NOT PRESERVE is set. The event was not changed. Specify a time in the future" }, { "ER_SLAVE_INCIDENT", 1590, "The incident %s occurred on the master. Message: %-.64s" }, { "ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT", 1591, "Table has no partition for some existing values" }, { "ER_BINLOG_UNSAFE_STATEMENT", 1592, "Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. %s" }, { "ER_SLAVE_FATAL_ERROR", 1593, "Fatal error: %s" }, { "ER_SLAVE_RELAY_LOG_READ_FAILURE", 1594, "Relay log read failure: %s" }, { "ER_SLAVE_RELAY_LOG_WRITE_FAILURE", 1595, "Relay log write failure: %s" }, { "ER_SLAVE_CREATE_EVENT_FAILURE", 1596, "Failed to create %s" }, { "ER_SLAVE_MASTER_COM_FAILURE", 1597, "Master command %s failed: %s" }, { "ER_BINLOG_LOGGING_IMPOSSIBLE", 1598, "Binary logging not possible. Message: %s" }, { "ER_VIEW_NO_CREATION_CTX", 1599, "View %`s.%`s has no creation context" }, { "ER_VIEW_INVALID_CREATION_CTX", 1600, "Creation context of view %`s.%`s is invalid" }, { "ER_SR_INVALID_CREATION_CTX", 1601, "Creation context of stored routine %`s.%`s is invalid" }, { "ER_TRG_CORRUPTED_FILE", 1602, "Corrupted TRG file for table %`s.%`s" }, { "ER_TRG_NO_CREATION_CTX", 1603, "Triggers for table %`s.%`s have no creation context" }, { "ER_TRG_INVALID_CREATION_CTX", 1604, "Trigger creation context of table %`s.%`s is invalid" }, { "ER_EVENT_INVALID_CREATION_CTX", 1605, "Creation context of event %`s.%`s is invalid" }, { "ER_TRG_CANT_OPEN_TABLE", 1606, "Cannot open table for trigger %`s.%`s" }, { "ER_CANT_CREATE_SROUTINE", 1607, "Cannot create stored routine %`s. Check warnings" }, { "ER_UNUSED_11", 1608, "You should never see it" }, { "ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT", 1609, "The BINLOG statement of type %s was not preceded by a format description BINLOG statement" }, { "ER_SLAVE_CORRUPT_EVENT", 1610, "Corrupted replication event was detected" }, { "ER_LOAD_DATA_INVALID_COLUMN", 1611, "Invalid column reference (%-.64s) in LOAD DATA" }, { "ER_LOG_PURGE_NO_FILE", 1612, "Being purged log %s was not found" }, { "ER_XA_RBTIMEOUT", 1613, "XA_RBTIMEOUT: Transaction branch was rolled back: took too long" }, { "ER_XA_RBDEADLOCK", 1614, "XA_RBDEADLOCK: Transaction branch was rolled back: deadlock was detected" }, { "ER_NEED_REPREPARE", 1615, "Prepared statement needs to be re-prepared" }, { "ER_DELAYED_NOT_SUPPORTED", 1616, "DELAYED option not supported for table \'%-.192s\'" }, { "WARN_NO_MASTER_INFO", 1617, "There is no master connection \'%.*s\'" }, { "WARN_OPTION_IGNORED", 1618, "<%-.64s> option ignored" }, { "ER_PLUGIN_DELETE_BUILTIN", 1619, "Built-in plugins cannot be deleted" }, { "WARN_PLUGIN_BUSY", 1620, "Plugin is busy and will be uninstalled on shutdown" }, { "ER_VARIABLE_IS_READONLY", 1621, "%s variable \'%s\' is read-only. Use SET %s to assign the value" }, { "ER_WARN_ENGINE_TRANSACTION_ROLLBACK", 1622, "Storage engine %s does not support rollback for this statement. Transaction rolled back and must be restarted" }, { "ER_SLAVE_HEARTBEAT_FAILURE", 1623, "Unexpected master\'s heartbeat data: %s" }, { "ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE", 1624, "The requested value for the heartbeat period is either negative or exceeds the maximum allowed (%u seconds)" }, { "ER_UNUSED_14", 1625, "You should never see it" }, { "ER_CONFLICT_FN_PARSE_ERROR", 1626, "Error in parsing conflict function. Message: %-.64s" }, { "ER_EXCEPTIONS_WRITE_ERROR", 1627, "Write to exceptions table failed. Message: %-.128s\"" }, { "ER_TOO_LONG_TABLE_COMMENT", 1628, "Comment for table \'%-.64s\' is too long (max = %u)" }, { "ER_TOO_LONG_FIELD_COMMENT", 1629, "Comment for field \'%-.64s\' is too long (max = %u)" }, { "ER_FUNC_INEXISTENT_NAME_COLLISION", 1630, "FUNCTION %s does not exist. Check the \'Function Name Parsing and Resolution\' section in the Reference Manual" }, { "ER_DATABASE_NAME", 1631, "Database" }, { "ER_TABLE_NAME", 1632, "Table" }, { "ER_PARTITION_NAME", 1633, "Partition" }, { "ER_SUBPARTITION_NAME", 1634, "Subpartition" }, { "ER_TEMPORARY_NAME", 1635, "Temporary" }, { "ER_RENAMED_NAME", 1636, "Renamed" }, { "ER_TOO_MANY_CONCURRENT_TRXS", 1637, "Too many active concurrent transactions" }, { "WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED", 1638, "Non-ASCII separator arguments are not fully supported" }, { "ER_DEBUG_SYNC_TIMEOUT", 1639, "debug sync point wait timed out" }, { "ER_DEBUG_SYNC_HIT_LIMIT", 1640, "debug sync point hit limit reached" }, { "ER_DUP_SIGNAL_SET", 1641, "Duplicate condition information item \'%s\'" }, { "ER_SIGNAL_WARN", 1642, "Unhandled user-defined warning condition" }, { "ER_SIGNAL_NOT_FOUND", 1643, "Unhandled user-defined not found condition" }, { "ER_SIGNAL_EXCEPTION", 1644, "Unhandled user-defined exception condition" }, { "ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER", 1645, "RESIGNAL when handler not active" }, { "ER_SIGNAL_BAD_CONDITION_TYPE", 1646, "SIGNAL/RESIGNAL can only use a CONDITION defined with SQLSTATE" }, { "WARN_COND_ITEM_TRUNCATED", 1647, "Data truncated for condition item \'%s\'" }, { "ER_COND_ITEM_TOO_LONG", 1648, "Data too long for condition item \'%s\'" }, { "ER_UNKNOWN_LOCALE", 1649, "Unknown locale: \'%-.64s\'" }, { "ER_SLAVE_IGNORE_SERVER_IDS", 1650, "The requested server id %d clashes with the slave startup option --replicate-same-server-id" }, { "ER_QUERY_CACHE_DISABLED", 1651, "Query cache is disabled; set query_cache_type to ON or DEMAND to enable it" }, { "ER_SAME_NAME_PARTITION_FIELD", 1652, "Duplicate partition field name \'%-.192s\'" }, { "ER_PARTITION_COLUMN_LIST_ERROR", 1653, "Inconsistency in usage of column lists for partitioning" }, { "ER_WRONG_TYPE_COLUMN_VALUE_ERROR", 1654, "Partition column values of incorrect type" }, { "ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR", 1655, "Too many fields in \'%-.192s\'" }, { "ER_MAXVALUE_IN_VALUES_IN", 1656, "Cannot use MAXVALUE as value in VALUES IN" }, { "ER_TOO_MANY_VALUES_ERROR", 1657, "Cannot have more than one value for this type of %-.64s partitioning" }, { "ER_ROW_SINGLE_PARTITION_FIELD_ERROR", 1658, "Row expressions in VALUES IN only allowed for multi-field column partitioning" }, { "ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD", 1659, "Field \'%-.192s\' is of a not allowed type for this type of partitioning" }, { "ER_PARTITION_FIELDS_TOO_LONG", 1660, "The total length of the partitioning fields is too large" }, { "ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE", 1661, "Cannot execute statement: impossible to write to binary log since both row-incapable engines and statement-incapable engines are involved" }, { "ER_BINLOG_ROW_MODE_AND_STMT_ENGINE", 1662, "Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = ROW and at least one table uses a storage engine limited to statement-based logging" }, { "ER_BINLOG_UNSAFE_AND_STMT_ENGINE", 1663, "Cannot execute statement: impossible to write to binary log since statement is unsafe, storage engine is limited to statement-based logging, and BINLOG_FORMAT = MIXED. %s" }, { "ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE", 1664, "Cannot execute statement: impossible to write to binary log since statement is in row format and at least one table uses a storage engine limited to statement-based logging" }, { "ER_BINLOG_STMT_MODE_AND_ROW_ENGINE", 1665, "Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a storage engine limited to row-based logging.%s" }, { "ER_BINLOG_ROW_INJECTION_AND_STMT_MODE", 1666, "Cannot execute statement: impossible to write to binary log since statement is in row format and BINLOG_FORMAT = STATEMENT" }, { "ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE", 1667, "Cannot execute statement: impossible to write to binary log since more than one engine is involved and at least one engine is self-logging" }, { "ER_BINLOG_UNSAFE_LIMIT", 1668, "The statement is unsafe because it uses a LIMIT clause. This is unsafe because the set of rows included cannot be predicted" }, { "ER_BINLOG_UNSAFE_INSERT_DELAYED", 1669, "The statement is unsafe because it uses INSERT DELAYED. This is unsafe because the times when rows are inserted cannot be predicted" }, { "ER_BINLOG_UNSAFE_SYSTEM_TABLE", 1670, "The statement is unsafe because it uses the general log, slow query log, or performance_schema table(s). This is unsafe because system tables may differ on slaves" }, { "ER_BINLOG_UNSAFE_AUTOINC_COLUMNS", 1671, "Statement is unsafe because it invokes a trigger or a stored function that inserts into an AUTO_INCREMENT column. Inserted values cannot be logged correctly" }, { "ER_BINLOG_UNSAFE_UDF", 1672, "Statement is unsafe because it uses a UDF which may not return the same value on the slave" }, { "ER_BINLOG_UNSAFE_SYSTEM_VARIABLE", 1673, "Statement is unsafe because it uses a system variable that may have a different value on the slave" }, { "ER_BINLOG_UNSAFE_SYSTEM_FUNCTION", 1674, "Statement is unsafe because it uses a system function that may return a different value on the slave" }, { "ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS", 1675, "Statement is unsafe because it accesses a non-transactional table after accessing a transactional table within the same transaction" }, { "ER_MESSAGE_AND_STATEMENT", 1676, "%s. Statement: %s" }, { "ER_SLAVE_CONVERSION_FAILED", 1677, "Column %d of table \'%-.192s.%-.192s\' cannot be converted from type \'%-.50s\' to type \'%-.50s\'" }, { "ER_SLAVE_CANT_CREATE_CONVERSION", 1678, "Can\'t create conversion table for table \'%-.192s.%-.192s\'" }, { "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT", 1679, "Cannot modify @@session.binlog_format inside a transaction" }, { "ER_PATH_LENGTH", 1680, "The path specified for %.64T is too long" }, { "ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT", 1681, "\'%s\' is deprecated and will be removed in a future release" }, { "ER_WRONG_NATIVE_TABLE_STRUCTURE", 1682, "Native table \'%-.64s\'.\'%-.64s\' has the wrong structure" }, { "ER_WRONG_PERFSCHEMA_USAGE", 1683, "Invalid performance_schema usage" }, { "ER_WARN_I_S_SKIPPED_TABLE", 1684, "Table \'%s\'.\'%s\' was skipped since its definition is being modified by concurrent DDL statement" }, { "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT", 1685, "Cannot modify @@session.binlog_direct_non_transactional_updates inside a transaction" }, { "ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT", 1686, "Cannot change the binlog direct flag inside a stored function or trigger" }, { "ER_SPATIAL_MUST_HAVE_GEOM_COL", 1687, "A SPATIAL index may only contain a geometrical type column" }, { "ER_TOO_LONG_INDEX_COMMENT", 1688, "Comment for index \'%-.64s\' is too long (max = %lu)" }, { "ER_LOCK_ABORTED", 1689, "Wait on a lock was aborted due to a pending exclusive lock" }, { "ER_DATA_OUT_OF_RANGE", 1690, "%s value is out of range in \'%s\'" }, { "ER_WRONG_SPVAR_TYPE_IN_LIMIT", 1691, "A variable of a non-integer based type in LIMIT clause" }, { "ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE", 1692, "Mixing self-logging and non-self-logging engines in a statement is unsafe" }, { "ER_BINLOG_UNSAFE_MIXED_STATEMENT", 1693, "Statement accesses nontransactional table as well as transactional or temporary table, and writes to any of them" }, { "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN", 1694, "Cannot modify @@session.sql_log_bin inside a transaction" }, { "ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN", 1695, "Cannot change the sql_log_bin inside a stored function or trigger" }, { "ER_FAILED_READ_FROM_PAR_FILE", 1696, "Failed to read from the .par file" }, { "ER_VALUES_IS_NOT_INT_TYPE_ERROR", 1697, "VALUES value for partition \'%-.64s\' must have type INT" }, { "ER_ACCESS_DENIED_NO_PASSWORD_ERROR", 1698, "Access denied for user \'%s\'@\'%s\'" }, { "ER_SET_PASSWORD_AUTH_PLUGIN", 1699, "SET PASSWORD is not applicable for users authenticating via %s plugin" }, { "ER_GRANT_PLUGIN_USER_EXISTS", 1700, "GRANT with IDENTIFIED WITH is illegal because the user %-.*s already exists" }, { "ER_TRUNCATE_ILLEGAL_FK", 1701, "Cannot truncate a table referenced in a foreign key constraint (%.192s)" }, { "ER_PLUGIN_IS_PERMANENT", 1702, "Plugin \'%s\' is force_plus_permanent and can not be unloaded" }, { "ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN", 1703, "The requested value for the heartbeat period is less than 1 millisecond. The value is reset to 0, meaning that heartbeating will effectively be disabled" }, { "ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX", 1704, "The requested value for the heartbeat period exceeds the value of `slave_net_timeout\' seconds. A sensible value for the period should be less than the timeout" }, { "ER_STMT_CACHE_FULL", 1705, "Multi-row statements required more than \'max_binlog_stmt_cache_size\' bytes of storage." }, { "ER_MULTI_UPDATE_KEY_CONFLICT", 1706, "Primary key/partition key update is not allowed since the table is updated both as \'%-.192s\' and \'%-.192s\'" }, { "ER_TABLE_NEEDS_REBUILD", 1707, "Table rebuild required. Please do \"ALTER TABLE %`s FORCE\" or dump/reload to fix it!" }, { "WARN_OPTION_BELOW_LIMIT", 1708, "The value of \'%s\' should be no less than the value of \'%s\'" }, { "ER_INDEX_COLUMN_TOO_LONG", 1709, "Index column size too large. The maximum column size is %lu bytes" }, { "ER_ERROR_IN_TRIGGER_BODY", 1710, "Trigger \'%-.64s\' has an error in its body: \'%-.256s\'" }, { "ER_ERROR_IN_UNKNOWN_TRIGGER_BODY", 1711, "Unknown trigger has an error in its body: \'%-.256s\'" }, { "ER_INDEX_CORRUPT", 1712, "Index %s is corrupted" }, { "ER_UNDO_RECORD_TOO_BIG", 1713, "Undo log record is too big" }, { "ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT", 1714, "INSERT IGNORE... SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE", 1715, "INSERT... SELECT... ON DUPLICATE KEY UPDATE is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are updated. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_REPLACE_SELECT", 1716, "REPLACE... SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are replaced. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT", 1717, "CREATE... IGNORE SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT", 1718, "CREATE... REPLACE SELECT is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are replaced. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_UPDATE_IGNORE", 1719, "UPDATE IGNORE is unsafe because the order in which rows are updated determines which (if any) rows are ignored. This order cannot be predicted and may differ on master and the slave" }, { "ER_UNUSED_15", 1720, "You should never see it" }, { "ER_UNUSED_16", 1721, "You should never see it" }, { "ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT", 1722, "Statements writing to a table with an auto-increment column after selecting from another table are unsafe because the order in which rows are retrieved determines what (if any) rows will be written. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC", 1723, "CREATE TABLE... SELECT... on a table with an auto-increment column is unsafe because the order in which rows are retrieved by the SELECT determines which (if any) rows are inserted. This order cannot be predicted and may differ on master and the slave" }, { "ER_BINLOG_UNSAFE_INSERT_TWO_KEYS", 1724, "INSERT... ON DUPLICATE KEY UPDATE on a table with more than one UNIQUE KEY is unsafe" }, { "ER_UNUSED_28", 1725, "You should never see it" }, { "ER_VERS_NOT_ALLOWED", 1726, "Not allowed for system-versioned table %`s.%`s" }, { "ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST", 1727, "INSERT into autoincrement field which is not the first part in the composed primary key is unsafe" }, { "ER_CANNOT_LOAD_FROM_TABLE_V2", 1728, "Cannot load from %s.%s. The table is probably corrupted" }, { "ER_MASTER_DELAY_VALUE_OUT_OF_RANGE", 1729, "The requested value %lu for the master delay exceeds the maximum %lu" }, { "ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT", 1730, "Only Format_description_log_event and row events are allowed in BINLOG statements (but %s was provided)" }, { "ER_PARTITION_EXCHANGE_DIFFERENT_OPTION", 1731, "Non matching attribute \'%-.64s\' between partition and table" }, { "ER_PARTITION_EXCHANGE_PART_TABLE", 1732, "Table to exchange with partition is partitioned: \'%-.64s\'" }, { "ER_PARTITION_EXCHANGE_TEMP_TABLE", 1733, "Table to exchange with partition is temporary: \'%-.64s\'" }, { "ER_PARTITION_INSTEAD_OF_SUBPARTITION", 1734, "Subpartitioned table, use subpartition instead of partition" }, { "ER_UNKNOWN_PARTITION", 1735, "Unknown partition \'%-.64s\' in table \'%-.64s\'" }, { "ER_TABLES_DIFFERENT_METADATA", 1736, "Tables have different definitions" }, { "ER_ROW_DOES_NOT_MATCH_PARTITION", 1737, "Found a row that does not match the partition" }, { "ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX", 1738, "Option binlog_cache_size (%lu) is greater than max_binlog_cache_size (%lu); setting binlog_cache_size equal to max_binlog_cache_size" }, { "ER_WARN_INDEX_NOT_APPLICABLE", 1739, "Cannot use %-.64s access on index \'%-.64s\' due to type or collation conversion on field \'%-.64s\'" }, { "ER_PARTITION_EXCHANGE_FOREIGN_KEY", 1740, "Table to exchange with partition has foreign key references: \'%-.64s\'" }, { "ER_NO_SUCH_KEY_VALUE", 1741, "Key value \'%-.192s\' was not found in table \'%-.192s.%-.192s\'" }, { "ER_VALUE_TOO_LONG", 1742, "Too long value for \'%s\'" }, { "ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE", 1743, "Replication event checksum verification failed while reading from network" }, { "ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE", 1744, "Replication event checksum verification failed while reading from a log file" }, { "ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX", 1745, "Option binlog_stmt_cache_size (%lu) is greater than max_binlog_stmt_cache_size (%lu); setting binlog_stmt_cache_size equal to max_binlog_stmt_cache_size" }, { "ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT", 1746, "Can\'t update table \'%-.192s\' while \'%-.192s\' is being created" }, { "ER_PARTITION_CLAUSE_ON_NONPARTITIONED", 1747, "PARTITION () clause on non partitioned table" }, { "ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET", 1748, "Found a row not matching the given partition set" }, { "ER_UNUSED_5", 1749, "You should never see it" }, { "ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE", 1750, "Failure while changing the type of replication repository: %s" }, { "ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE", 1751, "The creation of some temporary tables could not be rolled back" }, { "ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE", 1752, "Some temporary tables were dropped, but these operations could not be rolled back" }, { "ER_MTS_FEATURE_IS_NOT_SUPPORTED", 1753, "%s is not supported in multi-threaded slave mode. %s" }, { "ER_MTS_UPDATED_DBS_GREATER_MAX", 1754, "The number of modified databases exceeds the maximum %d; the database names will not be included in the replication event metadata" }, { "ER_MTS_CANT_PARALLEL", 1755, "Cannot execute the current event group in the parallel mode. Encountered event %s, relay-log name %s, position %s which prevents execution of this event group in parallel mode. Reason: %s" }, { "ER_MTS_INCONSISTENT_DATA", 1756, "%s" }, { "ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING", 1757, "FULLTEXT index is not supported for partitioned tables" }, { "ER_DA_INVALID_CONDITION_NUMBER", 1758, "Invalid condition number" }, { "ER_INSECURE_PLAIN_TEXT", 1759, "Sending passwords in plain text without SSL/TLS is extremely insecure" }, { "ER_INSECURE_CHANGE_MASTER", 1760, "Storing MariaDB user name or password information in the master.info repository is not secure and is therefore not recommended. Please see the MariaDB Manual for more about this issue and possible alternatives" }, { "ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO", 1761, "Foreign key constraint for table \'%.192s\', record \'%-.192s\' would lead to a duplicate entry in table \'%.192s\', key \'%.192s\'" }, { "ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO", 1762, "Foreign key constraint for table \'%.192s\', record \'%-.192s\' would lead to a duplicate entry in a child table" }, { "ER_SQLTHREAD_WITH_SECURE_SLAVE", 1763, "Setting authentication options is not possible when only the Slave SQL Thread is being started" }, { "ER_TABLE_HAS_NO_FT", 1764, "The table does not have FULLTEXT index to support this query" }, { "ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER", 1765, "The system variable %.200s cannot be set in stored functions or triggers" }, { "ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION", 1766, "The system variable %.200s cannot be set when there is an ongoing transaction" }, { "ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST", 1767, "The system variable @@SESSION.GTID_NEXT has the value %.200s, which is not listed in @@SESSION.GTID_NEXT_LIST" }, { "ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL", 1768, "When @@SESSION.GTID_NEXT_LIST == NULL, the system variable @@SESSION.GTID_NEXT cannot change inside a transaction" }, { "ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION", 1769, "The statement \'SET %.200s\' cannot invoke a stored function" }, { "ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL", 1770, "The system variable @@SESSION.GTID_NEXT cannot be \'AUTOMATIC\' when @@SESSION.GTID_NEXT_LIST is non-NULL" }, { "ER_SKIPPING_LOGGED_TRANSACTION", 1771, "Skipping transaction %.200s because it has already been executed and logged" }, { "ER_MALFORMED_GTID_SET_SPECIFICATION", 1772, "Malformed GTID set specification \'%.200s\'" }, { "ER_MALFORMED_GTID_SET_ENCODING", 1773, "Malformed GTID set encoding" }, { "ER_MALFORMED_GTID_SPECIFICATION", 1774, "Malformed GTID specification \'%.200s\'" }, { "ER_GNO_EXHAUSTED", 1775, "Impossible to generate Global Transaction Identifier: the integer component reached the maximal value. Restart the server with a new server_uuid" }, { "ER_BAD_SLAVE_AUTO_POSITION", 1776, "Parameters MASTER_LOG_FILE, MASTER_LOG_POS, RELAY_LOG_FILE and RELAY_LOG_POS cannot be set when MASTER_AUTO_POSITION is active" }, { "ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON", 1777, "CHANGE MASTER TO MASTER_AUTO_POSITION = 1 can only be executed when GTID_MODE = ON" }, { "ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET", 1778, "Cannot execute statements with implicit commit inside a transaction when GTID_NEXT != AUTOMATIC or GTID_NEXT_LIST != NULL" }, { "ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON", 1779, "GTID_MODE = ON or GTID_MODE = UPGRADE_STEP_2 requires ENFORCE_GTID_CONSISTENCY = 1" }, { "ER_GTID_MODE_REQUIRES_BINLOG", 1780, "GTID_MODE = ON or UPGRADE_STEP_1 or UPGRADE_STEP_2 requires --log-bin and --log-slave-updates" }, { "ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF", 1781, "GTID_NEXT cannot be set to UUID:NUMBER when GTID_MODE = OFF" }, { "ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON", 1782, "GTID_NEXT cannot be set to ANONYMOUS when GTID_MODE = ON" }, { "ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF", 1783, "GTID_NEXT_LIST cannot be set to a non-NULL value when GTID_MODE = OFF" }, { "ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF", 1784, "Found a Gtid_log_event or Previous_gtids_log_event when GTID_MODE = OFF" }, { "ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE", 1785, "When ENFORCE_GTID_CONSISTENCY = 1, updates to non-transactional tables can only be done in either autocommitted statements or single-statement transactions, and never in the same statement as updates to transactional tables" }, { "ER_GTID_UNSAFE_CREATE_SELECT", 1786, "CREATE TABLE ... SELECT is forbidden when ENFORCE_GTID_CONSISTENCY = 1" }, { "ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION", 1787, "When ENFORCE_GTID_CONSISTENCY = 1, the statements CREATE TEMPORARY TABLE and DROP TEMPORARY TABLE can be executed in a non-transactional context only, and require that AUTOCOMMIT = 1" }, { "ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME", 1788, "The value of GTID_MODE can only change one step at a time: OFF <-> UPGRADE_STEP_1 <-> UPGRADE_STEP_2 <-> ON. Also note that this value must be stepped up or down simultaneously on all servers; see the Manual for instructions." }, { "ER_MASTER_HAS_PURGED_REQUIRED_GTIDS", 1789, "The slave is connecting using CHANGE MASTER TO MASTER_AUTO_POSITION = 1, but the master has purged binary logs containing GTIDs that the slave requires" }, { "ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID", 1790, "GTID_NEXT cannot be changed by a client that owns a GTID. The client owns %s. Ownership is released on COMMIT or ROLLBACK" }, { "ER_UNKNOWN_EXPLAIN_FORMAT", 1791, "Unknown %s format name: \'%s\'" }, { "ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION", 1792, "Cannot execute statement in a READ ONLY transaction" }, { "ER_TOO_LONG_TABLE_PARTITION_COMMENT", 1793, "Comment for table partition \'%-.64s\' is too long (max = %lu)" }, { "ER_SLAVE_CONFIGURATION", 1794, "Slave is not configured or failed to initialize properly. You must at least set --server-id to enable either a master or a slave. Additional error messages can be found in the MariaDB error log" }, { "ER_INNODB_FT_LIMIT", 1795, "InnoDB presently supports one FULLTEXT index creation at a time" }, { "ER_INNODB_NO_FT_TEMP_TABLE", 1796, "Cannot create FULLTEXT index on temporary InnoDB table" }, { "ER_INNODB_FT_WRONG_DOCID_COLUMN", 1797, "Column \'%-.192s\' is of wrong type for an InnoDB FULLTEXT index" }, { "ER_INNODB_FT_WRONG_DOCID_INDEX", 1798, "Index \'%-.192s\' is of wrong type for an InnoDB FULLTEXT index" }, { "ER_INNODB_ONLINE_LOG_TOO_BIG", 1799, "Creating index \'%-.192s\' required more than \'innodb_online_alter_log_max_size\' bytes of modification log. Please try again" }, { "ER_UNKNOWN_ALTER_ALGORITHM", 1800, "Unknown ALGORITHM \'%s\'" }, { "ER_UNKNOWN_ALTER_LOCK", 1801, "Unknown LOCK type \'%s\'" }, { "ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS", 1802, "CHANGE MASTER cannot be executed when the slave was stopped with an error or killed in MTS mode. Consider using RESET SLAVE or START SLAVE UNTIL" }, { "ER_MTS_RECOVERY_FAILURE", 1803, "Cannot recover after SLAVE errored out in parallel execution mode. Additional error messages can be found in the MariaDB error log" }, { "ER_MTS_RESET_WORKERS", 1804, "Cannot clean up worker info tables. Additional error messages can be found in the MariaDB error log" }, { "ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2", 1805, "Column count of %s.%s is wrong. Expected %d, found %d. The table is probably corrupted" }, { "ER_SLAVE_SILENT_RETRY_TRANSACTION", 1806, "Slave must silently retry current transaction" }, { "ER_UNUSED_22", 1807, "You should never see it" }, { "ER_TABLE_SCHEMA_MISMATCH", 1808, "Schema mismatch (%s)" }, { "ER_TABLE_IN_SYSTEM_TABLESPACE", 1809, "Table %-.192s in system tablespace" }, { "ER_IO_READ_ERROR", 1810, "IO Read error: (%lu, %s) %s" }, { "ER_IO_WRITE_ERROR", 1811, "IO Write error: (%lu, %s) %s" }, { "ER_TABLESPACE_MISSING", 1812, "Tablespace is missing for table \'%-.192s\'" }, { "ER_TABLESPACE_EXISTS", 1813, "Tablespace for table \'%-.192s\' exists. Please DISCARD the tablespace before IMPORT" }, { "ER_TABLESPACE_DISCARDED", 1814, "Tablespace has been discarded for table %`s" }, { "ER_INTERNAL_ERROR", 1815, "Internal error: %-.192s" }, { "ER_INNODB_IMPORT_ERROR", 1816, "ALTER TABLE \'%-.192s\' IMPORT TABLESPACE failed with error %lu : \'%s\'" }, { "ER_INNODB_INDEX_CORRUPT", 1817, "Index corrupt: %s" }, { "ER_INVALID_YEAR_COLUMN_LENGTH", 1818, "YEAR(%lu) column type is deprecated. Creating YEAR(4) column instead" }, { "ER_NOT_VALID_PASSWORD", 1819, "Your password does not satisfy the current policy requirements (%s)" }, { "ER_MUST_CHANGE_PASSWORD", 1820, "You must SET PASSWORD before executing this statement" }, { "ER_FK_NO_INDEX_CHILD", 1821, "Failed to add the foreign key constraint. Missing index for constraint \'%s\' in the foreign table \'%s\'" }, { "ER_FK_NO_INDEX_PARENT", 1822, "Failed to add the foreign key constraint. Missing index for constraint \'%s\' in the referenced table \'%s\'" }, { "ER_FK_FAIL_ADD_SYSTEM", 1823, "Failed to add the foreign key constraint \'%s\' to system tables" }, { "ER_FK_CANNOT_OPEN_PARENT", 1824, "Failed to open the referenced table \'%s\'" }, { "ER_FK_INCORRECT_OPTION", 1825, "Failed to add the foreign key constraint on table \'%s\'. Incorrect options in FOREIGN KEY constraint \'%s\'" }, { "ER_DUP_CONSTRAINT_NAME", 1826, "Duplicate %s constraint name \'%s\'" }, { "ER_PASSWORD_FORMAT", 1827, "The password hash doesn\'t have the expected format. Check if the correct password algorithm is being used with the PASSWORD() function" }, { "ER_FK_COLUMN_CANNOT_DROP", 1828, "Cannot drop column \'%-.192s\': needed in a foreign key constraint \'%-.192s\'" }, { "ER_FK_COLUMN_CANNOT_DROP_CHILD", 1829, "Cannot drop column \'%-.192s\': needed in a foreign key constraint \'%-.192s\' of table %-.192s" }, { "ER_FK_COLUMN_NOT_NULL", 1830, "Column \'%-.192s\' cannot be NOT NULL: needed in a foreign key constraint \'%-.192s\' SET NULL" }, { "ER_DUP_INDEX", 1831, "Duplicate index %`s. This is deprecated and will be disallowed in a future release" }, { "ER_FK_COLUMN_CANNOT_CHANGE", 1832, "Cannot change column \'%-.192s\': used in a foreign key constraint \'%-.192s\'" }, { "ER_FK_COLUMN_CANNOT_CHANGE_CHILD", 1833, "Cannot change column \'%-.192s\': used in a foreign key constraint \'%-.192s\' of table \'%-.192s\'" }, { "ER_FK_CANNOT_DELETE_PARENT", 1834, "Cannot delete rows from table which is parent in a foreign key constraint \'%-.192s\' of table \'%-.192s\'" }, { "ER_MALFORMED_PACKET", 1835, "Malformed communication packet" }, { "ER_READ_ONLY_MODE", 1836, "Running in read-only mode" }, { "ER_GTID_NEXT_TYPE_UNDEFINED_GROUP", 1837, "When GTID_NEXT is set to a GTID, you must explicitly set it again after a COMMIT or ROLLBACK. If you see this error message in the slave SQL thread, it means that a table in the current transaction is transactional on the master and non-transactional on the slave. In a client connection, it means that you executed SET GTID_NEXT before a transaction and forgot to set GTID_NEXT to a different identifier or to \'AUTOMATIC\' after COMMIT or ROLLBACK. Current GTID_NEXT is \'%s\'" }, { "ER_VARIABLE_NOT_SETTABLE_IN_SP", 1838, "The system variable %.200s cannot be set in stored procedures" }, { "ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF", 1839, "GTID_PURGED can only be set when GTID_MODE = ON" }, { "ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY", 1840, "GTID_PURGED can only be set when GTID_EXECUTED is empty" }, { "ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY", 1841, "GTID_PURGED can only be set when there are no ongoing transactions (not even in other clients)" }, { "ER_GTID_PURGED_WAS_CHANGED", 1842, "GTID_PURGED was changed from \'%s\' to \'%s\'" }, { "ER_GTID_EXECUTED_WAS_CHANGED", 1843, "GTID_EXECUTED was changed from \'%s\' to \'%s\'" }, { "ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES", 1844, "Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT, and both replicated and non replicated tables are written to" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED", 1845, "%s is not supported for this operation. Try %s" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON", 1846, "%s is not supported. Reason: %s. Try %s" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY", 1847, "COPY algorithm requires a lock" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION", 1848, "Partition specific operations do not yet support LOCK/ALGORITHM" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME", 1849, "Columns participating in a foreign key are renamed" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE", 1850, "Cannot change column type" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK", 1851, "Adding foreign keys needs foreign_key_checks=OFF" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE", 1852, "Creating unique indexes with IGNORE requires COPY algorithm to remove duplicate rows" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK", 1853, "Dropping a primary key is not allowed without also adding a new primary key" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC", 1854, "Adding an auto-increment column requires a lock" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS", 1855, "Cannot replace hidden FTS_DOC_ID with a user-visible one" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS", 1856, "Cannot drop or rename FTS_DOC_ID" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS", 1857, "Fulltext index creation requires a lock" }, { "ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE", 1858, "sql_slave_skip_counter can not be set when the server is running with GTID_MODE = ON. Instead, for each transaction that you want to skip, generate an empty transaction with the same GTID as the transaction" }, { "ER_DUP_UNKNOWN_IN_INDEX", 1859, "Duplicate entry for key \'%-.192s\'" }, { "ER_IDENT_CAUSES_TOO_LONG_PATH", 1860, "Long database name and identifier for object resulted in path length exceeding %d characters. Path: \'%s\'" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL", 1861, "cannot convert NULL to non-constant DEFAULT" }, { "ER_MUST_CHANGE_PASSWORD_LOGIN", 1862, "Your password has expired. To log in you must change it using a client that supports expired passwords" }, { "ER_ROW_IN_WRONG_PARTITION", 1863, "Found a row in wrong partition %s" }, { "ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX", 1864, "Cannot schedule event %s, relay-log name %s, position %s to Worker thread because its size %lu exceeds %lu of slave_pending_jobs_size_max" }, { "ER_INNODB_NO_FT_USES_PARSER", 1865, "Cannot CREATE FULLTEXT INDEX WITH PARSER on InnoDB table" }, { "ER_BINLOG_LOGICAL_CORRUPTION", 1866, "The binary log file \'%s\' is logically corrupted: %s" }, { "ER_WARN_PURGE_LOG_IN_USE", 1867, "file %s was not purged because it was being read by %d thread(s), purged only %d out of %d files" }, { "ER_WARN_PURGE_LOG_IS_ACTIVE", 1868, "file %s was not purged because it is the active log file" }, { "ER_AUTO_INCREMENT_CONFLICT", 1869, "Auto-increment value in UPDATE conflicts with internally generated values" }, { "WARN_ON_BLOCKHOLE_IN_RBR", 1870, "Row events are not logged for %s statements that modify BLACKHOLE tables in row format. Table(s): \'%-.192s\'" }, { "ER_SLAVE_MI_INIT_REPOSITORY", 1871, "Slave failed to initialize master info structure from the repository" }, { "ER_SLAVE_RLI_INIT_REPOSITORY", 1872, "Slave failed to initialize relay log info structure from the repository" }, { "ER_ACCESS_DENIED_CHANGE_USER_ERROR", 1873, "Access denied trying to change to user \'%-.48s\'@\'%-.64s\' (using password: %s). Disconnecting" }, { "ER_INNODB_READ_ONLY", 1874, "InnoDB is in read only mode" }, { "ER_STOP_SLAVE_SQL_THREAD_TIMEOUT", 1875, "STOP SLAVE command execution is incomplete: Slave SQL thread got the stop signal, thread is busy, SQL thread will stop once the current task is complete" }, { "ER_STOP_SLAVE_IO_THREAD_TIMEOUT", 1876, "STOP SLAVE command execution is incomplete: Slave IO thread got the stop signal, thread is busy, IO thread will stop once the current task is complete" }, { "ER_TABLE_CORRUPT", 1877, "Operation cannot be performed. The table \'%-.64s.%-.64s\' is missing, corrupt or contains bad data" }, { "ER_TEMP_FILE_WRITE_FAILURE", 1878, "Temporary file write failure" }, { "ER_INNODB_FT_AUX_NOT_HEX_ID", 1879, "Upgrade index name failed, please use create index(alter table) algorithm copy to rebuild index" }, { "ER_LAST_MYSQL_ERROR_MESSAGE", 1880, "\"" }, { "ER_UNUSED_18", 1900, "You should never see it" }, { "ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED", 1901, "Function or expression \'%s\' cannot be used in the %s clause of %`s" }, { "ER_UNUSED_19", 1902, "You should never see it" }, { "ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN", 1903, "Primary key cannot be defined upon a generated column" }, { "ER_KEY_BASED_ON_GENERATED_VIRTUAL_COLUMN", 1904, "Key/Index cannot be defined on a virtual generated column" }, { "ER_WRONG_FK_OPTION_FOR_GENERATED_COLUMN", 1905, "Cannot define foreign key with %s clause on a generated column" }, { "ER_WARNING_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN", 1906, "The value specified for generated column \'%s\' in table \'%s\' has been ignored" }, { "ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN", 1907, "This is not yet supported for generated columns" }, { "ER_UNUSED_20", 1908, "You should never see it" }, { "ER_UNUSED_21", 1909, "You should never see it" }, { "ER_UNSUPPORTED_ENGINE_FOR_GENERATED_COLUMNS", 1910, "%s storage engine does not support generated columns" }, { "ER_UNKNOWN_OPTION", 1911, "Unknown option \'%-.64s\'" }, { "ER_BAD_OPTION_VALUE", 1912, "Incorrect value \'%-.64T\' for option \'%-.64s\'" }, { "ER_UNUSED_6", 1913, "You should never see it" }, { "ER_UNUSED_7", 1914, "You should never see it" }, { "ER_UNUSED_8", 1915, "You should never see it" }, { "ER_DATA_OVERFLOW", 1916, "Got overflow when converting \'%-.128s\' to %-.32s. Value truncated" }, { "ER_DATA_TRUNCATED", 1917, "Truncated value \'%-.128s\' when converting to %-.32s" }, { "ER_BAD_DATA", 1918, "Encountered illegal value \'%-.128s\' when converting to %-.32s" }, { "ER_DYN_COL_WRONG_FORMAT", 1919, "Encountered illegal format of dynamic column string" }, { "ER_DYN_COL_IMPLEMENTATION_LIMIT", 1920, "Dynamic column implementation limit reached" }, { "ER_DYN_COL_DATA", 1921, "Illegal value used as argument of dynamic column function" }, { "ER_DYN_COL_WRONG_CHARSET", 1922, "Dynamic column contains unknown character set" }, { "ER_ILLEGAL_SUBQUERY_OPTIMIZER_SWITCHES", 1923, "At least one of the \'in_to_exists\' or \'materialization\' optimizer_switch flags must be \'on\'" }, { "ER_QUERY_CACHE_IS_DISABLED", 1924, "Query cache is disabled (resize or similar command in progress); repeat this command later" }, { "ER_QUERY_CACHE_IS_GLOBALY_DISABLED", 1925, "Query cache is globally disabled and you can\'t enable it only for this session" }, { "ER_VIEW_ORDERBY_IGNORED", 1926, "View \'%-.192s\'.\'%-.192s\' ORDER BY clause ignored because there is other ORDER BY clause already" }, { "ER_CONNECTION_KILLED", 1927, "Connection was killed" }, { "ER_UNUSED_12", 1928, "You should never see it" }, { "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SKIP_REPLICATION", 1929, "Cannot modify @@session.skip_replication inside a transaction" }, { "ER_STORED_FUNCTION_PREVENTS_SWITCH_SKIP_REPLICATION", 1930, "Cannot modify @@session.skip_replication inside a stored function or trigger" }, { "ER_QUERY_RESULT_INCOMPLETE", 1931, "Query execution was interrupted. The query exceeded %s %llu. The query result may be incomplete" }, { "ER_NO_SUCH_TABLE_IN_ENGINE", 1932, "Table \'%-.192s.%-.192s\' doesn\'t exist in engine" }, { "ER_TARGET_NOT_EXPLAINABLE", 1933, "Target is not running an EXPLAINable command" }, { "ER_CONNECTION_ALREADY_EXISTS", 1934, "Connection \'%.*s\' conflicts with existing connection \'%.*s\'" }, { "ER_MASTER_LOG_PREFIX", 1935, "Master \'%.*s\': " }, { "ER_CANT_START_STOP_SLAVE", 1936, "Can\'t %s SLAVE \'%.*s\'" }, { "ER_SLAVE_STARTED", 1937, "SLAVE \'%.*s\' started" }, { "ER_SLAVE_STOPPED", 1938, "SLAVE \'%.*s\' stopped" }, { "ER_SQL_DISCOVER_ERROR", 1939, "Engine %s failed to discover table %`-.192s.%`-.192s with \'%s\'" }, { "ER_FAILED_GTID_STATE_INIT", 1940, "Failed initializing replication GTID state" }, { "ER_INCORRECT_GTID_STATE", 1941, "Could not parse GTID list" }, { "ER_CANNOT_UPDATE_GTID_STATE", 1942, "Could not update replication slave gtid state" }, { "ER_DUPLICATE_GTID_DOMAIN", 1943, "GTID %u-%u-%llu and %u-%u-%llu conflict (duplicate domain id %u)" }, { "ER_GTID_OPEN_TABLE_FAILED", 1944, "Failed to open %s.%s" }, { "ER_GTID_POSITION_NOT_FOUND_IN_BINLOG", 1945, "Connecting slave requested to start from GTID %u-%u-%llu, which is not in the master\'s binlog" }, { "ER_CANNOT_LOAD_SLAVE_GTID_STATE", 1946, "Failed to load replication slave GTID position from table %s.%s" }, { "ER_MASTER_GTID_POS_CONFLICTS_WITH_BINLOG", 1947, "Specified GTID %u-%u-%llu conflicts with the binary log which contains a more recent GTID %u-%u-%llu. If MASTER_GTID_POS=CURRENT_POS is used, the binlog position will override the new value of @@gtid_slave_pos" }, { "ER_MASTER_GTID_POS_MISSING_DOMAIN", 1948, "Specified value for @@gtid_slave_pos contains no value for replication domain %u. This conflicts with the binary log which contains GTID %u-%u-%llu. If MASTER_GTID_POS=CURRENT_POS is used, the binlog position will override the new value of @@gtid_slave_pos" }, { "ER_UNTIL_REQUIRES_USING_GTID", 1949, "START SLAVE UNTIL master_gtid_pos requires that slave is using GTID" }, { "ER_GTID_STRICT_OUT_OF_ORDER", 1950, "An attempt was made to binlog GTID %u-%u-%llu which would create an out-of-order sequence number with existing GTID %u-%u-%llu, and gtid strict mode is enabled" }, { "ER_GTID_START_FROM_BINLOG_HOLE", 1951, "The binlog on the master is missing the GTID %u-%u-%llu requested by the slave (even though a subsequent sequence number does exist), and GTID strict mode is enabled" }, { "ER_SLAVE_UNEXPECTED_MASTER_SWITCH", 1952, "Unexpected GTID received from master after reconnect. This normally indicates that the master server was replaced without restarting the slave threads. %s" }, { "ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO", 1953, "Cannot modify @@session.gtid_domain_id or @@session.gtid_seq_no inside a transaction" }, { "ER_STORED_FUNCTION_PREVENTS_SWITCH_GTID_DOMAIN_ID_SEQ_NO", 1954, "Cannot modify @@session.gtid_domain_id or @@session.gtid_seq_no inside a stored function or trigger" }, { "ER_GTID_POSITION_NOT_FOUND_IN_BINLOG2", 1955, "Connecting slave requested to start from GTID %u-%u-%llu, which is not in the master\'s binlog. Since the master\'s binlog contains GTIDs with higher sequence numbers, it probably means that the slave has diverged due to executing extra erroneous transactions" }, { "ER_BINLOG_MUST_BE_EMPTY", 1956, "This operation is not allowed if any GTID has been logged to the binary log. Run RESET MASTER first to erase the log" }, { "ER_NO_SUCH_QUERY", 1957, "Unknown query id: %lld" }, { "ER_BAD_BASE64_DATA", 1958, "Bad base64 data as position %u" }, { "ER_INVALID_ROLE", 1959, "Invalid role specification %`s" }, { "ER_INVALID_CURRENT_USER", 1960, "The current user is invalid" }, { "ER_CANNOT_GRANT_ROLE", 1961, "Cannot grant role \'%s\' to: %s" }, { "ER_CANNOT_REVOKE_ROLE", 1962, "Cannot revoke role \'%s\' from: %s" }, { "ER_CHANGE_SLAVE_PARALLEL_THREADS_ACTIVE", 1963, "Cannot change @@slave_parallel_threads while another change is in progress" }, { "ER_PRIOR_COMMIT_FAILED", 1964, "Commit failed due to failure of an earlier commit on which this one depends" }, { "ER_IT_IS_A_VIEW", 1965, "\'%-.192s\' is a view" }, { "ER_SLAVE_SKIP_NOT_IN_GTID", 1966, "When using parallel replication and GTID with multiple replication domains, @@sql_slave_skip_counter can not be used. Instead, setting @@gtid_slave_pos explicitly can be used to skip to after a given GTID position" }, { "ER_TABLE_DEFINITION_TOO_BIG", 1967, "The definition for table %`s is too big" }, { "ER_PLUGIN_INSTALLED", 1968, "Plugin \'%-.192s\' already installed" }, { "ER_STATEMENT_TIMEOUT", 1969, "Query execution was interrupted (max_statement_time exceeded)" }, { "ER_SUBQUERIES_NOT_SUPPORTED", 1970, "%s does not support subqueries or stored functions" }, { "ER_SET_STATEMENT_NOT_SUPPORTED", 1971, "The system variable %.200s cannot be set in SET STATEMENT." }, { "ER_UNUSED_9", 1972, "You should never see it" }, { "ER_USER_CREATE_EXISTS", 1973, "Can\'t create user \'%-.64s\'@\'%-.64s\'; it already exists" }, { "ER_USER_DROP_EXISTS", 1974, "Can\'t drop user \'%-.64s\'@\'%-.64s\'; it doesn\'t exist" }, { "ER_ROLE_CREATE_EXISTS", 1975, "Can\'t create role \'%-.64s\'; it already exists" }, { "ER_ROLE_DROP_EXISTS", 1976, "Can\'t drop role \'%-.64s\'; it doesn\'t exist" }, { "ER_CANNOT_CONVERT_CHARACTER", 1977, "Cannot convert \'%s\' character 0x%-.64s to \'%s\'" }, { "ER_INVALID_DEFAULT_VALUE_FOR_FIELD", 1978, "Incorrect default value \'%-.128T\' for column \'%.192s\'" }, { "ER_KILL_QUERY_DENIED_ERROR", 1979, "You are not owner of query %lld" }, { "ER_NO_EIS_FOR_FIELD", 1980, "Engine-independent statistics are not collected for column \'%s\'" }, { "ER_WARN_AGGFUNC_DEPENDENCE", 1981, "Aggregate function \'%-.192s)\' of SELECT #%d belongs to SELECT #%d" }, { "WARN_INNODB_PARTITION_OPTION_IGNORED", 1982, "<%-.64s> option ignored for InnoDB partition" }, { "ER_FILE_CORRUPT", 3000, "File %s is corrupted" }, { "ER_ERROR_ON_MASTER", 3001, "Query partially completed on the master (error on master: %d) and was aborted. There is a chance that your master is inconsistent at this point. If you are sure that your master is ok, run this query manually on the slave and then restart the slave with SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; START SLAVE;. Query:\'%s\'" }, { "ER_INCONSISTENT_ERROR", 3002, "Query caused different errors on master and slave. Error on master: message (format)=\'%s\' error code=%d; Error on slave:actual message=\'%s\', error code=%d. Default database:\'%s\'. Query:\'%s\'" }, { "ER_STORAGE_ENGINE_NOT_LOADED", 3003, "Storage engine for table \'%s\'.\'%s\' is not loaded." }, { "ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER", 3004, "GET STACKED DIAGNOSTICS when handler not active" }, { "ER_WARN_LEGACY_SYNTAX_CONVERTED", 3005, "%s is no longer supported. The statement was converted to %s." }, { "ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN", 3006, "Statement is unsafe because it uses a fulltext parser plugin which may not return the same value on the slave." }, { "ER_CANNOT_DISCARD_TEMPORARY_TABLE", 3007, "Cannot DISCARD/IMPORT tablespace associated with temporary table" }, { "ER_FK_DEPTH_EXCEEDED", 3008, "Foreign key cascade delete/update exceeds max depth of %d." }, { "ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2", 3009, "Column count of %s.%s is wrong. Expected %d, found %d. Created with MariaDB %d, now running %d. Please use mariadb-upgrade to fix this error." }, { "ER_WARN_TRIGGER_DOESNT_HAVE_CREATED", 3010, "Trigger %s.%s.%s does not have CREATED attribute." }, { "ER_REFERENCED_TRG_DOES_NOT_EXIST_MYSQL", 3011, "Referenced trigger \'%s\' for the given action time and event type does not exist." }, { "ER_EXPLAIN_NOT_SUPPORTED", 3012, "EXPLAIN FOR CONNECTION command is supported only for SELECT/UPDATE/INSERT/DELETE/REPLACE" }, { "ER_INVALID_FIELD_SIZE", 3013, "Invalid size for column \'%-.192s\'." }, { "ER_MISSING_HA_CREATE_OPTION", 3014, "Table storage engine \'%-.64s\' found required create option missing" }, { "ER_ENGINE_OUT_OF_MEMORY", 3015, "Out of memory in storage engine \'%-.64s\'." }, { "ER_PASSWORD_EXPIRE_ANONYMOUS_USER", 3016, "The password for anonymous user cannot be expired." }, { "ER_SLAVE_SQL_THREAD_MUST_STOP", 3017, "This operation cannot be performed with a running slave sql thread; run STOP SLAVE SQL_THREAD first" }, { "ER_NO_FT_MATERIALIZED_SUBQUERY", 3018, "Cannot create FULLTEXT index on materialized subquery" }, { "ER_INNODB_UNDO_LOG_FULL", 3019, "Undo Log error: %s" }, { "ER_INVALID_ARGUMENT_FOR_LOGARITHM", 3020, "Invalid argument for logarithm" }, { "ER_SLAVE_CHANNEL_IO_THREAD_MUST_STOP", 3021, "This operation cannot be performed with a running slave io thread; run STOP SLAVE IO_THREAD FOR CHANNEL \'%s\' first." }, { "ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO", 3022, "This operation may not be safe when the slave has temporary tables. The tables will be kept open until the server restarts or until the tables are deleted by any replicated DROP statement. Suggest to wait until slave_open_temp_tables = 0." }, { "ER_WARN_ONLY_MASTER_LOG_FILE_NO_POS", 3023, "CHANGE MASTER TO with a MASTER_LOG_FILE clause but no MASTER_LOG_POS clause may not be safe. The old position value may not be valid for the new binary log file." }, { "ER_UNUSED_1", 3024, "You should never see it" }, { "ER_NON_RO_SELECT_DISABLE_TIMER", 3025, "Select is not a read only statement, disabling timer" }, { "ER_DUP_LIST_ENTRY", 3026, "Duplicate entry \'%-.192s\'." }, { "ER_SQL_MODE_NO_EFFECT", 3027, "\'%s\' mode no longer has any effect. Use STRICT_ALL_TABLES or STRICT_TRANS_TABLES instead." }, { "ER_AGGREGATE_ORDER_FOR_UNION", 3028, "Expression #%u of ORDER BY contains aggregate function and applies to a UNION" }, { "ER_AGGREGATE_ORDER_NON_AGG_QUERY", 3029, "Expression #%u of ORDER BY contains aggregate function and applies to the result of a non-aggregated query" }, { "ER_SLAVE_WORKER_STOPPED_PREVIOUS_THD_ERROR", 3030, "Slave worker has stopped after at least one previous worker encountered an error when slave-preserve-commit-order was enabled. To preserve commit order, the last transaction executed by this thread has not been committed. When restarting the slave after fixing any failed threads, you should fix this worker as well." }, { "ER_DONT_SUPPORT_SLAVE_PRESERVE_COMMIT_ORDER", 3031, "slave_preserve_commit_order is not supported %s." }, { "ER_SERVER_OFFLINE_MODE", 3032, "The server is currently in offline mode" }, { "ER_GIS_DIFFERENT_SRIDS", 3033, "Binary geometry function %s given two geometries of different srids: %u and %u, which should have been identical." }, { "ER_GIS_UNSUPPORTED_ARGUMENT", 3034, "Calling geometry function %s with unsupported types of arguments." }, { "ER_GIS_UNKNOWN_ERROR", 3035, "Unknown GIS error occurred in function %s." }, { "ER_GIS_UNKNOWN_EXCEPTION", 3036, "Unknown exception caught in GIS function %s." }, { "ER_GIS_INVALID_DATA", 3037, "Invalid GIS data provided to function %s." }, { "ER_BOOST_GEOMETRY_EMPTY_INPUT_EXCEPTION", 3038, "The geometry has no data in function %s." }, { "ER_BOOST_GEOMETRY_CENTROID_EXCEPTION", 3039, "Unable to calculate centroid because geometry is empty in function %s." }, { "ER_BOOST_GEOMETRY_OVERLAY_INVALID_INPUT_EXCEPTION", 3040, "Geometry overlay calculation error: geometry data is invalid in function %s." }, { "ER_BOOST_GEOMETRY_TURN_INFO_EXCEPTION", 3041, "Geometry turn info calculation error: geometry data is invalid in function %s." }, { "ER_BOOST_GEOMETRY_SELF_INTERSECTION_POINT_EXCEPTION", 3042, "Analysis procedures of intersection points interrupted unexpectedly in function %s." }, { "ER_BOOST_GEOMETRY_UNKNOWN_EXCEPTION", 3043, "Unknown exception thrown in function %s." }, { "ER_STD_BAD_ALLOC_ERROR", 3044, "Memory allocation error: %-.256s in function %s." }, { "ER_STD_DOMAIN_ERROR", 3045, "Domain error: %-.256s in function %s." }, { "ER_STD_LENGTH_ERROR", 3046, "Length error: %-.256s in function %s." }, { "ER_STD_INVALID_ARGUMENT", 3047, "Invalid argument error: %-.256s in function %s." }, { "ER_STD_OUT_OF_RANGE_ERROR", 3048, "Out of range error: %-.256s in function %s." }, { "ER_STD_OVERFLOW_ERROR", 3049, "Overflow error: %-.256s in function %s." }, { "ER_STD_RANGE_ERROR", 3050, "Range error: %-.256s in function %s." }, { "ER_STD_UNDERFLOW_ERROR", 3051, "Underflow error: %-.256s in function %s." }, { "ER_STD_LOGIC_ERROR", 3052, "Logic error: %-.256s in function %s." }, { "ER_STD_RUNTIME_ERROR", 3053, "Runtime error: %-.256s in function %s." }, { "ER_STD_UNKNOWN_EXCEPTION", 3054, "Unknown exception: %-.384s in function %s." }, { "ER_GIS_DATA_WRONG_ENDIANESS", 3055, "Geometry byte string must be little endian." }, { "ER_CHANGE_MASTER_PASSWORD_LENGTH", 3056, "The password provided for the replication user exceeds the maximum length of 32 characters" }, { "ER_USER_LOCK_WRONG_NAME", 3057, "Incorrect user-level lock name \'%-.192s\'." }, { "ER_USER_LOCK_DEADLOCK", 3058, "Deadlock found when trying to get user-level lock; try rolling back transaction/releasing locks and restarting lock acquisition." }, { "ER_REPLACE_INACCESSIBLE_ROWS", 3059, "REPLACE cannot be executed as it requires deleting rows that are not in the view" }, { "ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_GIS", 3060, "Do not support online operation on table with GIS index" }, { "ER_UNUSED_26", 4000, "This error never happens" }, { "ER_UNUSED_27", 4001, "This error never happens" }, { "ER_WITH_COL_WRONG_LIST", 4002, "WITH column list and SELECT field list have different column counts" }, { "ER_TOO_MANY_DEFINITIONS_IN_WITH_CLAUSE", 4003, "Too many WITH elements in WITH clause" }, { "ER_DUP_QUERY_NAME", 4004, "Duplicate query name %`-.64s in WITH clause" }, { "ER_RECURSIVE_WITHOUT_ANCHORS", 4005, "No anchors for recursive WITH element \'%s\'" }, { "ER_UNACCEPTABLE_MUTUAL_RECURSION", 4006, "Unacceptable mutual recursion with anchored table \'%s\'" }, { "ER_REF_TO_RECURSIVE_WITH_TABLE_IN_DERIVED", 4007, "Reference to recursive WITH table \'%s\' in materialized derived" }, { "ER_NOT_STANDARD_COMPLIANT_RECURSIVE", 4008, "Restrictions imposed on recursive definitions are violated for table \'%s\'" }, { "ER_WRONG_WINDOW_SPEC_NAME", 4009, "Window specification with name \'%s\' is not defined" }, { "ER_DUP_WINDOW_NAME", 4010, "Multiple window specifications with the same name \'%s\'" }, { "ER_PARTITION_LIST_IN_REFERENCING_WINDOW_SPEC", 4011, "Window specification referencing another one \'%s\' cannot contain partition list" }, { "ER_ORDER_LIST_IN_REFERENCING_WINDOW_SPEC", 4012, "Referenced window specification \'%s\' already contains order list" }, { "ER_WINDOW_FRAME_IN_REFERENCED_WINDOW_SPEC", 4013, "Referenced window specification \'%s\' cannot contain window frame" }, { "ER_BAD_COMBINATION_OF_WINDOW_FRAME_BOUND_SPECS", 4014, "Unacceptable combination of window frame bound specifications" }, { "ER_WRONG_PLACEMENT_OF_WINDOW_FUNCTION", 4015, "Window function is allowed only in SELECT list and ORDER BY clause" }, { "ER_WINDOW_FUNCTION_IN_WINDOW_SPEC", 4016, "Window function is not allowed in window specification" }, { "ER_NOT_ALLOWED_WINDOW_FRAME", 4017, "Window frame is not allowed with \'%s\'" }, { "ER_NO_ORDER_LIST_IN_WINDOW_SPEC", 4018, "No order list in window specification for \'%s\'" }, { "ER_RANGE_FRAME_NEEDS_SIMPLE_ORDERBY", 4019, "RANGE-type frame requires ORDER BY clause with single sort key" }, { "ER_WRONG_TYPE_FOR_ROWS_FRAME", 4020, "Integer is required for ROWS-type frame" }, { "ER_WRONG_TYPE_FOR_RANGE_FRAME", 4021, "Numeric datatype is required for RANGE-type frame" }, { "ER_FRAME_EXCLUSION_NOT_SUPPORTED", 4022, "Frame exclusion is not supported yet" }, { "ER_WINDOW_FUNCTION_DONT_HAVE_FRAME", 4023, "This window function may not have a window frame" }, { "ER_INVALID_NTILE_ARGUMENT", 4024, "Argument of NTILE must be greater than 0" }, { "ER_CONSTRAINT_FAILED", 4025, "CONSTRAINT %`s failed for %`-.192s.%`-.192s" }, { "ER_EXPRESSION_IS_TOO_BIG", 4026, "Expression in the %s clause is too big" }, { "ER_ERROR_EVALUATING_EXPRESSION", 4027, "Got an error evaluating stored expression %s" }, { "ER_CALCULATING_DEFAULT_VALUE", 4028, "Got an error when calculating default value for %`s" }, { "ER_EXPRESSION_REFERS_TO_UNINIT_FIELD", 4029, "Expression for field %`-.64s is referring to uninitialized field %`s" }, { "ER_PARTITION_DEFAULT_ERROR", 4030, "Only one DEFAULT partition allowed" }, { "ER_REFERENCED_TRG_DOES_NOT_EXIST", 4031, "Referenced trigger \'%s\' for the given action time and event type does not exist" }, { "ER_INVALID_DEFAULT_PARAM", 4032, "Default/ignore value is not supported for such parameter usage" }, { "ER_BINLOG_NON_SUPPORTED_BULK", 4033, "Only row based replication supported for bulk operations" }, { "ER_BINLOG_UNCOMPRESS_ERROR", 4034, "Uncompress the compressed binlog failed" }, { "ER_JSON_BAD_CHR", 4035, "Broken JSON string in argument %d to function \'%s\' at position %d" }, { "ER_JSON_NOT_JSON_CHR", 4036, "Character disallowed in JSON in argument %d to function \'%s\' at position %d" }, { "ER_JSON_EOS", 4037, "Unexpected end of JSON text in argument %d to function \'%s\'" }, { "ER_JSON_SYNTAX", 4038, "Syntax error in JSON text in argument %d to function \'%s\' at position %d" }, { "ER_JSON_ESCAPING", 4039, "Incorrect escaping in JSON text in argument %d to function \'%s\' at position %d" }, { "ER_JSON_DEPTH", 4040, "Limit of %d on JSON nested structures depth is reached in argument %d to function \'%s\' at position %d" }, { "ER_JSON_PATH_EOS", 4041, "Unexpected end of JSON path in argument %d to function \'%s\'" }, { "ER_JSON_PATH_SYNTAX", 4042, "Syntax error in JSON path in argument %d to function \'%s\' at position %d" }, { "ER_JSON_PATH_DEPTH", 4043, "Limit of %d on JSON path depth is reached in argument %d to function \'%s\' at position %d" }, { "ER_JSON_PATH_NO_WILDCARD", 4044, "Wildcards in JSON path not allowed in argument %d to function \'%s\'" }, { "ER_JSON_PATH_ARRAY", 4045, "JSON path should end with an array identifier in argument %d to function \'%s\'" }, { "ER_JSON_ONE_OR_ALL", 4046, "Argument 2 to function \'%s\' must be \"one\" or \"all\"." }, { "ER_UNSUPPORTED_COMPRESSED_TABLE", 4047, "InnoDB refuses to write tables with ROW_FORMAT=COMPRESSED or KEY_BLOCK_SIZE." }, { "ER_GEOJSON_INCORRECT", 4048, "Incorrect GeoJSON format specified for st_geomfromgeojson function." }, { "ER_GEOJSON_TOO_FEW_POINTS", 4049, "Incorrect GeoJSON format - too few points for linestring specified." }, { "ER_GEOJSON_NOT_CLOSED", 4050, "Incorrect GeoJSON format - polygon not closed." }, { "ER_JSON_PATH_EMPTY", 4051, "Path expression \'$\' is not allowed in argument %d to function \'%s\'." }, { "ER_SLAVE_SAME_ID", 4052, "A slave with the same server_uuid/server_id as this slave has connected to the master" }, { "ER_FLASHBACK_NOT_SUPPORTED", 4053, "Flashback does not support %s %s" }, { "ER_KEYS_OUT_OF_ORDER", 4054, "Keys are out order during bulk load" }, { "ER_OVERLAPPING_KEYS", 4055, "Bulk load rows overlap existing rows" }, { "ER_REQUIRE_ROW_BINLOG_FORMAT", 4056, "Can\'t execute updates on master with binlog_format != ROW." }, { "ER_ISOLATION_MODE_NOT_SUPPORTED", 4057, "MyRocks supports only READ COMMITTED and REPEATABLE READ isolation levels. Please change from current isolation level %s" }, { "ER_ON_DUPLICATE_DISABLED", 4058, "When unique checking is disabled in MyRocks, INSERT,UPDATE,LOAD statements with clauses that update or replace the key (i.e. INSERT ON DUPLICATE KEY UPDATE, REPLACE) are not allowed. Query: %s" }, { "ER_UPDATES_WITH_CONSISTENT_SNAPSHOT", 4059, "Can\'t execute updates when you started a transaction with START TRANSACTION WITH CONSISTENT [ROCKSDB] SNAPSHOT." }, { "ER_ROLLBACK_ONLY", 4060, "This transaction was rolled back and cannot be committed. Only supported operation is to roll it back, so all pending changes will be discarded. Please restart another transaction." }, { "ER_ROLLBACK_TO_SAVEPOINT", 4061, "MyRocks currently does not support ROLLBACK TO SAVEPOINT if modifying rows." }, { "ER_ISOLATION_LEVEL_WITH_CONSISTENT_SNAPSHOT", 4062, "Only REPEATABLE READ isolation level is supported for START TRANSACTION WITH CONSISTENT SNAPSHOT in RocksDB Storage Engine." }, { "ER_UNSUPPORTED_COLLATION", 4063, "Unsupported collation on string indexed column %s.%s Use binary collation (%s)." }, { "ER_METADATA_INCONSISTENCY", 4064, "Table \'%s\' does not exist, but metadata information exists inside MyRocks. This is a sign of data inconsistency. Please check if \'%s.frm\' exists, and try to restore it if it does not exist." }, { "ER_CF_DIFFERENT", 4065, "Column family (\'%s\') flag (%d) is different from an existing flag (%d). Assign a new CF flag, or do not change existing CF flag." }, { "ER_RDB_TTL_DURATION_FORMAT", 4066, "TTL duration (%s) in MyRocks must be an unsigned non-null 64-bit integer." }, { "ER_RDB_STATUS_GENERAL", 4067, "Status error %d received from RocksDB: %s" }, { "ER_RDB_STATUS_MSG", 4068, "%s, Status error %d received from RocksDB: %s" }, { "ER_RDB_TTL_UNSUPPORTED", 4069, "TTL support is currently disabled when table has a hidden PK." }, { "ER_RDB_TTL_COL_FORMAT", 4070, "TTL column (%s) in MyRocks must be an unsigned non-null 64-bit integer, exist inside the table, and have an accompanying ttl duration." }, { "ER_PER_INDEX_CF_DEPRECATED", 4071, "The per-index column family option has been deprecated" }, { "ER_KEY_CREATE_DURING_ALTER", 4072, "MyRocks failed creating new key definitions during alter." }, { "ER_SK_POPULATE_DURING_ALTER", 4073, "MyRocks failed populating secondary key during alter." }, { "ER_SUM_FUNC_WITH_WINDOW_FUNC_AS_ARG", 4074, "Window functions can not be used as arguments to group functions." }, { "ER_NET_OK_PACKET_TOO_LARGE", 4075, "OK packet too large" }, { "ER_GEOJSON_EMPTY_COORDINATES", 4076, "Incorrect GeoJSON format - empty \'coordinates\' array." }, { "ER_MYROCKS_CANT_NOPAD_COLLATION", 4077, "MyRocks doesn\'t currently support collations with \"No pad\" attribute." }, { "ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION", 4078, "Illegal parameter data types %s and %s for operation \'%s\'" }, { "ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION", 4079, "Illegal parameter data type %s for operation \'%s\'" }, { "ER_WRONG_PARAMCOUNT_TO_CURSOR", 4080, "Incorrect parameter count to cursor \'%-.192s\'" }, { "ER_UNKNOWN_STRUCTURED_VARIABLE", 4081, "Unknown structured system variable or ROW routine variable \'%-.*s\'" }, { "ER_ROW_VARIABLE_DOES_NOT_HAVE_FIELD", 4082, "Row variable \'%-.192s\' does not have a field \'%-.192s\'" }, { "ER_END_IDENTIFIER_DOES_NOT_MATCH", 4083, "END identifier \'%-.192s\' does not match \'%-.192s\'" }, { "ER_SEQUENCE_RUN_OUT", 4084, "Sequence \'%-.64s.%-.64s\' has run out" }, { "ER_SEQUENCE_INVALID_DATA", 4085, "Sequence \'%-.64s.%-.64s\' has out of range value for options" }, { "ER_SEQUENCE_INVALID_TABLE_STRUCTURE", 4086, "Sequence \'%-.64s.%-.64s\' table structure is invalid (%s)" }, { "ER_SEQUENCE_ACCESS_ERROR", 4087, "Sequence \'%-.64s.%-.64s\' access error" }, { "ER_SEQUENCE_BINLOG_FORMAT", 4088, "Sequences requires binlog_format mixed or row" }, { "ER_NOT_SEQUENCE", 4089, "\'%-.64s.%-.64s\' is not a SEQUENCE" }, { "ER_NOT_SEQUENCE2", 4090, "\'%-.192s\' is not a SEQUENCE" }, { "ER_UNKNOWN_SEQUENCES", 4091, "Unknown SEQUENCE: \'%-.300s\'" }, { "ER_UNKNOWN_VIEW", 4092, "Unknown VIEW: \'%-.300s\'" }, { "ER_WRONG_INSERT_INTO_SEQUENCE", 4093, "Wrong INSERT into a SEQUENCE. One can only do single table INSERT into a sequence object (like with mariadb-dump). If you want to change the SEQUENCE, use ALTER SEQUENCE instead." }, { "ER_SP_STACK_TRACE", 4094, "At line %u in %s" }, { "ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY", 4095, "Subroutine \'%-.192s\' is declared in the package specification but is not defined in the package body" }, { "ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED", 4096, "Subroutine \'%-.192s\' has a forward declaration but is not defined" }, { "ER_COMPRESSED_COLUMN_USED_AS_KEY", 4097, "Compressed column \'%-.192s\' can\'t be used in key specification" }, { "ER_UNKNOWN_COMPRESSION_METHOD", 4098, "Unknown compression method: %s" }, { "ER_WRONG_NUMBER_OF_VALUES_IN_TVC", 4099, "The used table value constructor has a different number of values" }, { "ER_FIELD_REFERENCE_IN_TVC", 4100, "Field reference \'%-.192s\' can\'t be used in table value constructor" }, { "ER_WRONG_TYPE_FOR_PERCENTILE_FUNC", 4101, "Numeric datatype is required for %s function" }, { "ER_ARGUMENT_NOT_CONSTANT", 4102, "Argument to the %s function is not a constant for a partition" }, { "ER_ARGUMENT_OUT_OF_RANGE", 4103, "Argument to the %s function does not belong to the range [0,1]" }, { "ER_WRONG_TYPE_OF_ARGUMENT", 4104, "%s function only accepts arguments that can be converted to numerical types" }, { "ER_NOT_AGGREGATE_FUNCTION", 4105, "Aggregate specific instruction (FETCH GROUP NEXT ROW) used in a wrong context" }, { "ER_INVALID_AGGREGATE_FUNCTION", 4106, "Aggregate specific instruction(FETCH GROUP NEXT ROW) missing from the aggregate function" }, { "ER_INVALID_VALUE_TO_LIMIT", 4107, "Limit only accepts integer values" }, { "ER_INVISIBLE_NOT_NULL_WITHOUT_DEFAULT", 4108, "Invisible column %`s must have a default value" }, { "ER_UPDATE_INFO_WITH_SYSTEM_VERSIONING", 4109, "Rows matched: %ld Changed: %ld Inserted: %ld Warnings: %ld" }, { "ER_VERS_FIELD_WRONG_TYPE", 4110, "%`s must be of type %s for system-versioned table %`s" }, { "ER_VERS_ENGINE_UNSUPPORTED", 4111, "Transaction-precise system versioning for %`s is not supported" }, { "ER_UNUSED_23", 4112, "You should never see it" }, { "ER_PARTITION_WRONG_TYPE", 4113, "Wrong partitioning type, expected type: %`s" }, { "WARN_VERS_PART_FULL", 4114, "Versioned table %`s.%`s: last HISTORY partition (%`s) is out of %s, need more HISTORY partitions" }, { "WARN_VERS_PARAMETERS", 4115, "Maybe missing parameters: %s" }, { "ER_VERS_DROP_PARTITION_INTERVAL", 4116, "Can only drop oldest partitions when rotating by INTERVAL" }, { "ER_UNUSED_25", 4117, "You should never see it" }, { "WARN_VERS_PART_NON_HISTORICAL", 4118, "Partition %`s contains non-historical data" }, { "ER_VERS_ALTER_NOT_ALLOWED", 4119, "Not allowed for system-versioned %`s.%`s. Change @@system_versioning_alter_history to proceed with ALTER." }, { "ER_VERS_ALTER_ENGINE_PROHIBITED", 4120, "Not allowed for system-versioned %`s.%`s. Change to/from native system versioning engine is not supported." }, { "ER_VERS_RANGE_PROHIBITED", 4121, "SYSTEM_TIME range selector is not allowed" }, { "ER_CONFLICTING_FOR_SYSTEM_TIME", 4122, "Conflicting FOR SYSTEM_TIME clauses in WITH RECURSIVE" }, { "ER_VERS_TABLE_MUST_HAVE_COLUMNS", 4123, "Table %`s must have at least one versioned column" }, { "ER_VERS_NOT_VERSIONED", 4124, "Table %`s is not system-versioned" }, { "ER_MISSING", 4125, "Wrong parameters for %`s: missing \'%s\'" }, { "ER_VERS_PERIOD_COLUMNS", 4126, "PERIOD FOR SYSTEM_TIME must use columns %`s and %`s" }, { "ER_PART_WRONG_VALUE", 4127, "Wrong parameters for partitioned %`s: wrong value for \'%s\'" }, { "ER_VERS_WRONG_PARTS", 4128, "Wrong partitions for %`s: must have at least one HISTORY and exactly one last CURRENT" }, { "ER_VERS_NO_TRX_ID", 4129, "TRX_ID %llu not found in `mysql.transaction_registry`" }, { "ER_VERS_ALTER_SYSTEM_FIELD", 4130, "Can not change system versioning field %`s" }, { "ER_DROP_VERSIONING_SYSTEM_TIME_PARTITION", 4131, "Can not DROP SYSTEM VERSIONING for table %`s partitioned BY SYSTEM_TIME" }, { "ER_VERS_DB_NOT_SUPPORTED", 4132, "System-versioned tables in the %`s database are not supported" }, { "ER_VERS_TRT_IS_DISABLED", 4133, "Transaction registry is disabled" }, { "ER_VERS_DUPLICATE_ROW_START_END", 4134, "Duplicate ROW %s column %`s" }, { "ER_VERS_ALREADY_VERSIONED", 4135, "Table %`s is already system-versioned" }, { "ER_UNUSED_24", 4136, "You should never see it" }, { "ER_VERS_NOT_SUPPORTED", 4137, "System-versioned tables do not support %s" }, { "ER_VERS_TRX_PART_HISTORIC_ROW_NOT_SUPPORTED", 4138, "Transaction-precise system-versioned tables do not support partitioning by ROW START or ROW END" }, { "ER_INDEX_FILE_FULL", 4139, "The index file for table \'%-.192s\' is full" }, { "ER_UPDATED_COLUMN_ONLY_ONCE", 4140, "The column %`s.%`s cannot be changed more than once in a single UPDATE statement" }, { "ER_EMPTY_ROW_IN_TVC", 4141, "Row with no elements is not allowed in table value constructor in this context" }, { "ER_VERS_QUERY_IN_PARTITION", 4142, "SYSTEM_TIME partitions in table %`s does not support historical query" }, { "ER_KEY_DOESNT_SUPPORT", 4143, "%s index %`s does not support this operation" }, { "ER_ALTER_OPERATION_TABLE_OPTIONS_NEED_REBUILD", 4144, "Changing table options requires the table to be rebuilt" }, { "ER_BACKUP_LOCK_IS_ACTIVE", 4145, "Can\'t execute the command as you have a BACKUP STAGE active" }, { "ER_BACKUP_NOT_RUNNING", 4146, "You must start backup with \"BACKUP STAGE START\"" }, { "ER_BACKUP_WRONG_STAGE", 4147, "Backup stage \'%s\' is same or before current backup stage \'%s\'" }, { "ER_BACKUP_STAGE_FAILED", 4148, "Backup stage \'%s\' failed" }, { "ER_BACKUP_UNKNOWN_STAGE", 4149, "Unknown backup stage: \'%s\'. Stage should be one of START, FLUSH, BLOCK_DDL, BLOCK_COMMIT or END" }, { "ER_USER_IS_BLOCKED", 4150, "User is blocked because of too many credential errors; unblock with \'ALTER USER / FLUSH PRIVILEGES\'" }, { "ER_ACCOUNT_HAS_BEEN_LOCKED", 4151, "Access denied, this account is locked" }, { "ER_PERIOD_TEMPORARY_NOT_ALLOWED", 4152, "Application-time period table cannot be temporary" }, { "ER_PERIOD_TYPES_MISMATCH", 4153, "Fields of PERIOD FOR %`s have different types" }, { "ER_MORE_THAN_ONE_PERIOD", 4154, "Cannot specify more than one application-time period" }, { "ER_PERIOD_FIELD_WRONG_ATTRIBUTES", 4155, "Period field %`s cannot be %s" }, { "ER_PERIOD_NOT_FOUND", 4156, "Period %`s is not found in table" }, { "ER_PERIOD_COLUMNS_UPDATED", 4157, "Column %`s used in period %`s specified in update SET list" }, { "ER_PERIOD_CONSTRAINT_DROP", 4158, "Can\'t DROP CONSTRAINT `%s`. Use DROP PERIOD `%s` for this" }, { "ER_TOO_LONG_KEYPART", 4159, "Specified key part was too long; max key part length is %u bytes" }, { "ER_TOO_LONG_DATABASE_COMMENT", 4160, "Comment for database \'%-.64s\' is too long (max = %u)" }, { "ER_UNKNOWN_DATA_TYPE", 4161, "Unknown data type: \'%-.64s\'" }, { "ER_UNKNOWN_OPERATOR", 4162, "Operator does not exist: \'%-.128s\'" }, { "ER_WARN_HISTORY_ROW_START_TIME", 4163, "Table `%s.%s` history row start \'%s\' is later than row end \'%s\'" }, { "ER_PART_STARTS_BEYOND_INTERVAL", 4164, "%`s: STARTS is later than query time, first history partition may exceed INTERVAL value" }, { "ER_GALERA_REPLICATION_NOT_SUPPORTED", 4165, "Galera replication not supported" }, { "ER_LOAD_INFILE_CAPABILITY_DISABLED", 4166, "The used command is not allowed because the MariaDB server or client has disabled the local infile capability" }, { "ER_NO_SECURE_TRANSPORTS_CONFIGURED", 4167, "No secure transports are configured, unable to set --require_secure_transport=ON" }, { "ER_SLAVE_IGNORED_SHARED_TABLE", 4168, "Slave SQL thread ignored the \'%s\' because table is shared" }, { "ER_NO_AUTOINCREMENT_WITH_UNIQUE", 4169, "AUTO_INCREMENT column %`s cannot be used in the UNIQUE index %`s" }, { "ER_KEY_CONTAINS_PERIOD_FIELDS", 4170, "Key %`s cannot explicitly include column %`s" }, { "ER_KEY_CANT_HAVE_WITHOUT_OVERLAPS", 4171, "Key %`s cannot have WITHOUT OVERLAPS" }, { "ER_NOT_ALLOWED_IN_THIS_CONTEXT", 4172, "\'%-.128s\' is not allowed in this context" }, { "ER_DATA_WAS_COMMITED_UNDER_ROLLBACK", 4173, "Engine %s does not support rollback. Changes were committed during rollback call" }, { "ER_PK_INDEX_CANT_BE_IGNORED", 4174, "A primary key cannot be marked as IGNORE" }, { "ER_BINLOG_UNSAFE_SKIP_LOCKED", 4175, "SKIP LOCKED makes this statement unsafe" }, { "ER_JSON_TABLE_ERROR_ON_FIELD", 4176, "Field \'%s\' can\'t be set for JSON_TABLE \'%s\'." }, { "ER_JSON_TABLE_ALIAS_REQUIRED", 4177, "Every table function must have an alias." }, { "ER_JSON_TABLE_SCALAR_EXPECTED", 4178, "Can\'t store an array or an object in the scalar column \'%s\' of JSON_TABLE \'%s\'." }, { "ER_JSON_TABLE_MULTIPLE_MATCHES", 4179, "Can\'t store multiple matches of the path in the column \'%s\' of JSON_TABLE \'%s\'." }, { "ER_WITH_TIES_NEEDS_ORDER", 4180, "FETCH ... WITH TIES requires ORDER BY clause to be present" }, { "ER_REMOVED_ORPHAN_TRIGGER", 4181, "Dropped orphan trigger \'%-.64s\', originally created for table: \'%-.192s\'" }, { "ER_STORAGE_ENGINE_DISABLED", 4182, "Storage engine %s is disabled" }, mysql/server/sslopt-case.h000064400000002776151027430560011644 0ustar00#ifndef SSLOPT_CASE_INCLUDED #define SSLOPT_CASE_INCLUDED /* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) case OPT_SSL_KEY: case OPT_SSL_CERT: case OPT_SSL_CA: case OPT_SSL_CAPATH: case OPT_SSL_CIPHER: case OPT_SSL_CRL: case OPT_SSL_CRLPATH: /* Enable use of SSL if we are using any ssl option One can disable SSL later by using --skip-ssl or --ssl=0 */ opt_use_ssl= 1; #if defined (HAVE_WOLFSSL) #if defined(MYSQL_SERVER) /* CRL does not work with WolfSSL (server) */ opt_ssl_crl= NULL; #endif #if !defined(_WIN32) || !defined(LIBMARIADB) /* CRL_PATH does not work with WolfSSL (server) and GnuTLS (client) */ opt_ssl_crlpath= NULL; #endif #endif break; #endif #endif /* SSLOPT_CASE_INCLUDED */ mysql/server/my_getopt.h000064400000012744151027430560011412 0ustar00/* Copyright (c) 2002, 2013, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_getopt_h #define _my_getopt_h #include "my_sys.h" /* loglevel */ /* my_getopt and my_default are almost always used together */ #include C_MODE_START #define GET_NO_ARG 1 #define GET_BOOL 2 #define GET_INT 3 #define GET_UINT 4 #define GET_LONG 5 #define GET_ULONG 6 #define GET_LL 7 #define GET_ULL 8 #define GET_STR 9 #define GET_STR_ALLOC 10 #define GET_DISABLED 11 #define GET_ENUM 12 #define GET_SET 13 #define GET_DOUBLE 14 #define GET_FLAGSET 15 #define GET_BIT 16 #define GET_ASK_ADDR 128 #define GET_AUTO 64 #define GET_TYPE_MASK 63 /** Enumeration of the my_option::arg_type attributes. It should be noted that for historical reasons variables with the combination arg_type=NO_ARG, my_option::var_type=GET_BOOL still accepts arguments. This is someone counter intuitive and care should be taken if the code is refactored. */ enum get_opt_arg_type { NO_ARG, OPT_ARG, REQUIRED_ARG }; struct st_typelib; struct my_option { const char *name; /**< Name of the option. name=NULL marks the end of the my_option[] array. */ int id; /**< For 0255 no short option is created, but a long option still can be identified uniquely in the my_get_one_option() callback. If an opton needs neither special treatment in the my_get_one_option() nor one-letter short equivalent use id=0 */ const char *comment; /**< option comment, for autom. --help. if it's NULL the option is not visible in --help. */ void *value; /**< A pointer to the variable value */ void *u_max_value; /**< The user def. max variable value */ struct st_typelib *typelib; /**< Pointer to possible values */ ulong var_type; /**< GET_BOOL, GET_ULL, etc */ enum get_opt_arg_type arg_type; /**< e.g. REQUIRED_ARG or OPT_ARG */ longlong def_value; /**< Default value */ longlong min_value; /**< Min allowed value (for numbers) */ ulonglong max_value; /**< Max allowed value (for numbers) */ longlong sub_size; /**< Unused */ long block_size; /**< Value should be a mult. of this (for numbers) */ void *app_type; /**< To be used by an application */ }; typedef my_bool (*my_get_one_option)(const struct my_option *, const char *, const char *); /** Used to retrieve a reference to the object (variable) that holds the value for the given option. For example, if var_type is GET_UINT, the function must return a pointer to a variable of type uint. A argument is stored in the location pointed to by the returned pointer. */ typedef void *(*my_getopt_value)(const char *, uint, const struct my_option *, int *); extern char *disabled_my_option; extern char *autoset_my_option; extern my_bool my_getopt_print_errors; extern my_bool my_getopt_skip_unknown; extern my_bool my_getopt_prefix_matching; extern my_bool my_handle_options_init_variables; extern my_error_reporter my_getopt_error_reporter; extern my_getopt_value my_getopt_get_addr; extern int handle_options (int *argc, char ***argv, const struct my_option *longopts, my_get_one_option) __attribute__((nonnull)); extern void my_cleanup_options(const struct my_option *options); extern void my_print_help(const struct my_option *options); extern void my_print_variables(const struct my_option *options); ulonglong getopt_ull_limit_value(ulonglong num, const struct my_option *optp, my_bool *fix); longlong getopt_ll_limit_value(longlong, const struct my_option *, my_bool *fix); double getopt_double_limit_value(double num, const struct my_option *optp, my_bool *fix); ulonglong getopt_double2ulonglong(double); double getopt_ulonglong2double(ulonglong); C_MODE_END #endif /* _my_getopt_h */ mysql/server/my_byteorder.h000064400000004005151027430560012076 0ustar00#ifndef MY_BYTEORDER_INCLUDED #define MY_BYTEORDER_INCLUDED /* Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Macro for reading 32-bit integer from network byte order (big-endian) from an unaligned memory location. */ #define int4net(A) (int32) (((uint32) ((uchar) (A)[3])) | \ (((uint32) ((uchar) (A)[2])) << 8) | \ (((uint32) ((uchar) (A)[1])) << 16) | \ (((uint32) ((uchar) (A)[0])) << 24)) /* Function-like macros for reading and storing in machine independent format (low byte first). There are 'korr' (assume 'corrector') variants for integer types, but 'get' (assume 'getter') for floating point types. */ #if (defined(__i386__) || defined(_M_IX86)) && !defined(WITH_UBSAN) #define MY_BYTE_ORDER_ARCH_OPTIMIZED #include "byte_order_generic_x86.h" #elif (defined(__x86_64__) || defined (_M_X64)) && !defined(WITH_UBSAN) #include "byte_order_generic_x86_64.h" #else #include "byte_order_generic.h" #endif /* Function-like macros for reading and storing in machine format from/to short/long to/from some place in memory V should be a variable (not on a register) and M a pointer to byte. */ #ifdef WORDS_BIGENDIAN #include "big_endian.h" #else #include "little_endian.h" #endif #endif /* MY_BYTEORDER_INCLUDED */ mysql/server/my_xml.h000064400000005420151027430560010701 0ustar00/* Copyright (c) 2000, 2002, 2003, 2005, 2007 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _my_xml_h #define _my_xml_h #ifdef __cplusplus extern "C" { #endif #define MY_XML_OK 0 #define MY_XML_ERROR 1 /* A flag whether to use absolute tag names in call-back functions, like "a", "a.b" and "a.b.c" (used in character set file parser), or relative names like "a", "b" and "c". */ #define MY_XML_FLAG_RELATIVE_NAMES 1 /* A flag whether to skip normilization of text values before calling call-back functions: i.e. skip leading/trailing spaces, \r, \n, \t characters. */ #define MY_XML_FLAG_SKIP_TEXT_NORMALIZATION 2 enum my_xml_node_type { MY_XML_NODE_TAG, /* can have TAG, ATTR and TEXT children */ MY_XML_NODE_ATTR, /* can have TEXT children */ MY_XML_NODE_TEXT /* cannot have children */ }; typedef struct xml_stack_st { int flags; enum my_xml_node_type current_node_type; char errstr[128]; struct { char static_buffer[128]; char *buffer; size_t buffer_size; char *start; char *end; } attr; const char *beg; const char *cur; const char *end; void *user_data; int (*enter)(struct xml_stack_st *st,const char *val, size_t len); int (*value)(struct xml_stack_st *st,const char *val, size_t len); int (*leave_xml)(struct xml_stack_st *st,const char *val, size_t len); } MY_XML_PARSER; void my_xml_parser_create(MY_XML_PARSER *st); void my_xml_parser_free(MY_XML_PARSER *st); int my_xml_parse(MY_XML_PARSER *st,const char *str, size_t len); void my_xml_set_value_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, const char *, size_t len)); void my_xml_set_enter_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, const char *, size_t len)); void my_xml_set_leave_handler(MY_XML_PARSER *st, int (*)(MY_XML_PARSER *, const char *, size_t len)); void my_xml_set_user_data(MY_XML_PARSER *st, void *); size_t my_xml_error_pos(MY_XML_PARSER *st); uint my_xml_error_lineno(MY_XML_PARSER *st); const char *my_xml_error_string(MY_XML_PARSER *st); #ifdef __cplusplus } #endif #endif /* _my_xml_h */ mysql/server/little_endian.h000064400000006764151027430560012223 0ustar00/* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /* Data in little-endian format. */ #ifndef MY_BYTE_ORDER_ARCH_OPTIMIZED #define float4get(V,M) memcpy(&V, (M), sizeof(float)) #define float4store(V,M) memcpy(V, (&M), sizeof(float)) #define float8get(V,M) doubleget((V),(M)) #define float8store(V,M) doublestore((V),(M)) /* Bi-endian hardware.... */ #if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) #define doublestore(T,V) do { *(((char*)T)+0)=(char) ((uchar *) &V)[4];\ *(((char*)T)+1)=(char) ((uchar *) &V)[5];\ *(((char*)T)+2)=(char) ((uchar *) &V)[6];\ *(((char*)T)+3)=(char) ((uchar *) &V)[7];\ *(((char*)T)+4)=(char) ((uchar *) &V)[0];\ *(((char*)T)+5)=(char) ((uchar *) &V)[1];\ *(((char*)T)+6)=(char) ((uchar *) &V)[2];\ *(((char*)T)+7)=(char) ((uchar *) &V)[3]; }\ while(0) #define doubleget(V,M) do { double def_temp;\ ((uchar*) &def_temp)[0]=(M)[4];\ ((uchar*) &def_temp)[1]=(M)[5];\ ((uchar*) &def_temp)[2]=(M)[6];\ ((uchar*) &def_temp)[3]=(M)[7];\ ((uchar*) &def_temp)[4]=(M)[0];\ ((uchar*) &def_temp)[5]=(M)[1];\ ((uchar*) &def_temp)[6]=(M)[2];\ ((uchar*) &def_temp)[7]=(M)[3];\ (V) = def_temp; } while(0) #else /* Bi-endian hardware.... */ /* Cast away type qualifiers (necessary as macro takes argument by value). */ #define doublestore(T,V) memcpy((T), (void*) &V, sizeof(double)) #define doubleget(V,M) memcpy(&V, (M), sizeof(double)) #endif /* Bi-endian hardware.... */ #endif /* !MY_BYTE_ORDER_ARCH_OPTIMIZED */ #define ushortget(V,M) do { uchar *pM= (uchar*)(M);V = uint2korr(pM);} while(0) #define shortget(V,M) do { uchar *pM= (uchar*)(M);V = sint2korr(pM);} while(0) #define longget(V,M) do { uchar *pM= (uchar*)(M);V = sint4korr(pM);} while(0) #define ulongget(V,M) do { uchar *pM= (uchar*)(M);V = uint4korr(pM);} while(0) #define shortstore(T,V) int2store(T,V) #define longstore(T,V) int4store(T,V) #ifndef floatstore /* Cast away type qualifiers (necessary as macro takes argument by value). */ #define floatstore(T,V) memcpy((T), (void*) (&V), sizeof(float)) #define floatget(V,M) memcpy(&V, (M), sizeof(float)) #endif #ifndef doubleget #define doubleget(V,M) memcpy(&V, (M), sizeof(double)) #define doublestore(T,V) memcpy((T), (void *) &V, sizeof(double)) #endif /* doubleget */ #define longlongget(V,M) memcpy(&V, (M), sizeof(ulonglong)) #define longlongstore(T,V) memcpy((T), &V, sizeof(ulonglong)) mysql/server/mysql_time.h000064400000004564151027430560011567 0ustar00/* Copyright (c) 2004, 2006 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _mysql_time_h_ #define _mysql_time_h_ /* Portable time_t replacement. Should be signed and hold seconds for 1902 -- 2038-01-19 range i.e at least a 32bit variable Using the system built in time_t is not an option as we rely on the above requirements in the time functions */ typedef long my_time_t; /* Time declarations shared between the server and client API: you should not add anything to this header unless it's used (and hence should be visible) in mysql.h. If you're looking for a place to add new time-related declaration, it's most likely my_time.h. See also "C API Handling of Date and Time Values" chapter in documentation. */ enum enum_mysql_timestamp_type { MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1, MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2 }; /* Structure which is used to represent datetime values inside MySQL. We assume that values in this structure are normalized, i.e. year <= 9999, month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions in server such as my_system_gmt_sec() or make_time() family of functions rely on this (actually now usage of make_*() family relies on a bit weaker restriction). Also functions that produce MYSQL_TIME as result ensure this. There is one exception to this rule though if this structure holds time value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold bigger values. */ typedef struct st_mysql_time { unsigned int year, month, day, hour, minute, second; unsigned long second_part; my_bool neg; enum enum_mysql_timestamp_type time_type; } MYSQL_TIME; #endif /* _mysql_time_h_ */ mysql/server/decimal.h000064400000011471151027430560010775 0ustar00/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ #ifndef _decimal_h #define _decimal_h #ifdef __cplusplus extern "C" { #endif typedef enum {TRUNCATE=0, HALF_EVEN, HALF_UP, CEILING, FLOOR} decimal_round_mode; typedef int32 decimal_digit_t; /** intg is the number of *decimal* digits (NOT number of decimal_digit_t's !) before the point frac is the number of decimal digits after the point len is the length of buf (length of allocated space) in decimal_digit_t's, not in bytes sign false means positive, true means negative buf is an array of decimal_digit_t's */ typedef struct st_decimal_t { int intg, frac, len; my_bool sign; decimal_digit_t *buf; } decimal_t; int internal_str2dec(const char *from, decimal_t *to, char **end, my_bool fixed); int decimal2string(const decimal_t *from, char *to, int *to_len, decimal_digits_t fixed_precision, decimal_digits_t fixed_decimals, char filler); int decimal2ulonglong(const decimal_t *from, ulonglong *to); int ulonglong2decimal(ulonglong from, decimal_t *to); int decimal2longlong(const decimal_t *from, longlong *to); int longlong2decimal(longlong from, decimal_t *to); int decimal2double(const decimal_t *from, double *to); int double2decimal(double from, decimal_t *to); decimal_digits_t decimal_actual_fraction(const decimal_t *from); int decimal2bin(const decimal_t *from, uchar *to, decimal_digits_t precision, decimal_digits_t scale); int bin2decimal(const uchar *from, decimal_t *to, decimal_digits_t precision, decimal_digits_t scale); uint decimal_size(decimal_digits_t precision, decimal_digits_t scale); uint decimal_bin_size(decimal_digits_t precision, decimal_digits_t scale); uint decimal_result_size(decimal_t *from1, decimal_t *from2, char op, int param); decimal_digits_t decimal_intg(const decimal_t *from); int decimal_add(const decimal_t *from1, const decimal_t *from2, decimal_t *to); int decimal_sub(const decimal_t *from1, const decimal_t *from2, decimal_t *to); int decimal_cmp(const decimal_t *from1, const decimal_t *from2); int decimal_mul(const decimal_t *from1, const decimal_t *from2, decimal_t *to); int decimal_div(const decimal_t *from1, const decimal_t *from2, decimal_t *to, int scale_incr); int decimal_mod(const decimal_t *from1, const decimal_t *from2, decimal_t *to); int decimal_round(const decimal_t *from, decimal_t *to, int new_scale, decimal_round_mode mode); int decimal_is_zero(const decimal_t *from); void max_decimal(decimal_digits_t precision, decimal_digits_t frac, decimal_t *to); #define string2decimal(A,B,C) internal_str2dec((A), (B), (C), 0) #define string2decimal_fixed(A,B,C) internal_str2dec((A), (B), (C), 1) /* set a decimal_t to zero */ #define decimal_make_zero(dec) do { \ (dec)->buf[0]=0; \ (dec)->intg=1; \ (dec)->frac=0; \ (dec)->sign=0; \ } while(0) /* returns the length of the buffer to hold string representation of the decimal (including decimal dot, possible sign and \0) */ #define decimal_string_size(dec) (((dec)->intg ? (dec)->intg : 1) + \ (dec)->frac + ((dec)->frac > 0) + 2) /* negate a decimal */ #define decimal_neg(dec) do { (dec)->sign^=1; } while(0) /* conventions: decimal_smth() == 0 -- everything's ok decimal_smth() <= 1 -- result is usable, but precision loss is possible decimal_smth() <= 2 -- result can be unusable, most significant digits could've been lost decimal_smth() > 2 -- no result was generated */ #define E_DEC_OK 0 #define E_DEC_TRUNCATED 1 #define E_DEC_OVERFLOW 2 #define E_DEC_DIV_ZERO 4 #define E_DEC_BAD_NUM 8 #define E_DEC_OOM 16 #define E_DEC_ERROR 31 #define E_DEC_FATAL_ERROR 30 #ifdef __cplusplus } #endif #endif mysql/mariadb_rpl.h000064400000045667151027430560010363 0ustar00/* Copyright (C) 2018-2022 MariaDB Corporation AB This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA */ #ifndef _mariadb_rpl_h_ #define _mariadb_rpl_h_ #ifdef __cplusplus extern "C" { #endif #include #include #define MARIADB_RPL_VERSION 0x0002 #define MARIADB_RPL_REQUIRED_VERSION 0x0002 #define RPL_BINLOG_MAGIC (const uchar*) "\xFE\x62\x69\x6E" #define RPL_BINLOG_MAGIC_SIZE 4 /* Protocol flags */ #define MARIADB_RPL_BINLOG_DUMP_NON_BLOCK 1 #define MARIADB_RPL_BINLOG_SEND_ANNOTATE_ROWS 2 #define MARIADB_RPL_IGNORE_HEARTBEAT (1 << 17) #define EVENT_HEADER_OFS 20 #define FL_STMT_END 1 /* GTID flags */ /* FL_STANDALONE is set in case there is no terminating COMMIT event. */ #define FL_STANDALONE 0x01 /* FL_GROUP_COMMIT_ID is set when event group is part of a group commit */ #define FL_GROUP_COMMIT_ID 0x02 /* FL_TRANSACTIONAL is set for an event group that can be safely rolled back (no MyISAM, eg.). */ #define FL_TRANSACTIONAL 0x04 /* FL_ALLOW_PARALLEL reflects the (negation of the) value of @@SESSION.skip_parallel_replication at the time of commit. */ #define FL_ALLOW_PARALLEL 0x08; /* FL_WAITED is set if a row lock wait (or other wait) is detected during the execution of the transaction. */ #define FL_WAITED 0x10 /* FL_DDL is set for event group containing DDL. */ #define FL_DDL 0x20 /* FL_PREPARED_XA is set for XA transaction. */ #define FL_PREPARED_XA 0x40 /* FL_"COMMITTED or ROLLED-BACK"_XA is set for XA transaction. */ #define FL_COMPLETED_XA 0x80 /* SEMI SYNCHRONOUS REPLICATION */ #define SEMI_SYNC_INDICATOR 0xEF #define SEMI_SYNC_ACK_REQ 0x01 /* Options */ enum mariadb_rpl_option { MARIADB_RPL_FILENAME, /* Filename and length */ MARIADB_RPL_START, /* Start position */ MARIADB_RPL_SERVER_ID, /* Server ID */ MARIADB_RPL_FLAGS, /* Protocol flags */ MARIADB_RPL_GTID_CALLBACK, /* GTID callback function */ MARIADB_RPL_GTID_DATA, /* GTID data */ MARIADB_RPL_BUFFER, MARIADB_RPL_VERIFY_CHECKSUM, MARIADB_RPL_UNCOMPRESS, MARIADB_RPL_HOST, MARIADB_RPL_PORT, MARIADB_RPL_EXTRACT_VALUES, MARIADB_RPL_SEMI_SYNC, }; /* Event types: From MariaDB Server sql/log_event.h */ enum mariadb_rpl_event { UNKNOWN_EVENT= 0, START_EVENT_V3= 1, QUERY_EVENT= 2, STOP_EVENT= 3, ROTATE_EVENT= 4, INTVAR_EVENT= 5, LOAD_EVENT= 6, SLAVE_EVENT= 7, CREATE_FILE_EVENT= 8, APPEND_BLOCK_EVENT= 9, EXEC_LOAD_EVENT= 10, DELETE_FILE_EVENT= 11, NEW_LOAD_EVENT= 12, RAND_EVENT= 13, USER_VAR_EVENT= 14, FORMAT_DESCRIPTION_EVENT= 15, XID_EVENT= 16, BEGIN_LOAD_QUERY_EVENT= 17, EXECUTE_LOAD_QUERY_EVENT= 18, TABLE_MAP_EVENT = 19, PRE_GA_WRITE_ROWS_EVENT = 20, /* deprecated */ PRE_GA_UPDATE_ROWS_EVENT = 21, /* deprecated */ PRE_GA_DELETE_ROWS_EVENT = 22, /* deprecated */ WRITE_ROWS_EVENT_V1 = 23, UPDATE_ROWS_EVENT_V1 = 24, DELETE_ROWS_EVENT_V1 = 25, INCIDENT_EVENT= 26, HEARTBEAT_LOG_EVENT= 27, IGNORABLE_LOG_EVENT= 28, ROWS_QUERY_LOG_EVENT= 29, WRITE_ROWS_EVENT = 30, UPDATE_ROWS_EVENT = 31, DELETE_ROWS_EVENT = 32, GTID_LOG_EVENT= 33, ANONYMOUS_GTID_LOG_EVENT= 34, PREVIOUS_GTIDS_LOG_EVENT= 35, TRANSACTION_CONTEXT_EVENT= 36, VIEW_CHANGE_EVENT= 37, XA_PREPARE_LOG_EVENT= 38, PARTIAL_UPDATE_ROWS_EVENT = 39, /* Add new events here - right above this comment! Existing events (except ENUM_END_EVENT) should never change their numbers */ /* New MySQL events are to be added right above this comment */ MYSQL_EVENTS_END, MARIA_EVENTS_BEGIN= 160, ANNOTATE_ROWS_EVENT= 160, BINLOG_CHECKPOINT_EVENT= 161, GTID_EVENT= 162, GTID_LIST_EVENT= 163, START_ENCRYPTION_EVENT= 164, QUERY_COMPRESSED_EVENT = 165, WRITE_ROWS_COMPRESSED_EVENT_V1 = 166, UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167, DELETE_ROWS_COMPRESSED_EVENT_V1 = 168, WRITE_ROWS_COMPRESSED_EVENT = 169, UPDATE_ROWS_COMPRESSED_EVENT = 170, DELETE_ROWS_COMPRESSED_EVENT = 171, /* Add new MariaDB events here - right above this comment! */ ENUM_END_EVENT /* end marker */ }; /* ROWS_EVENT flags */ #define STMT_END_F 0x01 #define NO_FOREIGN_KEY_CHECKS_F 0x02 #define RELAXED_UNIQUE_KEY_CHECKS_F 0x04 #define COMPLETE_ROWS_F 0x08 #define NO_CHECK_CONSTRAINT_CHECKS_F 0x80 enum mariadb_rpl_status_code { Q_FLAGS2_CODE= 0x00, Q_SQL_MODE_CODE= 0x01, Q_CATALOG_CODE= 0x02, Q_AUTO_INCREMENT_CODE= 0x03, Q_CHARSET_CODE= 0x04, Q_TIMEZONE_CODE= 0x05, Q_CATALOG_NZ_CODE= 0x06, Q_LC_TIME_NAMES_CODE= 0x07, Q_CHARSET_DATABASE_CODE= 0x08, Q_TABLE_MAP_FOR_UPDATE_CODE= 0x09, Q_MASTER_DATA_WRITTEN_CODE= 0x0A, Q_INVOKERS_CODE= 0x0B, Q_UPDATED_DB_NAMES_CODE= 0x0C, Q_MICROSECONDS_CODE= 0x0D, Q_COMMIT_TS_CODE= 0x0E, /* unused */ Q_COMMIT_TS2_CODE= 0x0F, /* unused */ Q_EXPLICIT_DEFAULTS_FOR_TIMESTAMP_CODE= 0x10, Q_DDL_LOGGED_WITH_XID_CODE= 0x11, Q_DEFAULT_COLLATION_FOR_UTF8_CODE= 0x12, Q_SQL_REQUIRE_PRIMARY_KEY_CODE= 0x13, Q_DEFAULT_TABLE_ENCRYPTION_CODE= 0x14, Q_HRNOW= 128, /* second part: 3 bytes */ Q_XID= 129 /* xid: 8 bytes */ }; #ifdef DEFAULT_CHARSET #undef DEFAULT_CHARSET #endif enum opt_metadata_field_type { SIGNEDNESS = 1, DEFAULT_CHARSET, COLUMN_CHARSET, COLUMN_NAME, SET_STR_VALUE, ENUM_STR_VALUE, GEOMETRY_TYPE, SIMPLE_PRIMARY_KEY, PRIMARY_KEY_WITH_PREFIX, ENUM_AND_SET_DEFAULT_CHARSET, ENUM_AND_SET_COLUMN_CHARSET }; /* QFLAGS2 codes */ #define OPTION_AUTO_IS_NULL 0x00040000 #define OPTION_NOT_AUTOCOMMIT 0x00080000 #define OPTION_NO_FOREIGN_KEY_CHECKS 0x04000000 #define OPTION_RELAXED_UNIQUE_CHECKS 0x08000000 /* SQL modes */ #define MODE_REAL_AS_FLOAT 0x00000001 #define MODE_PIPES_AS_CONCAT 0x00000002 #define MODE_ANSI_QUOTES 0x00000004 #define MODE_IGNORE_SPACE 0x00000008 #define MODE_NOT_USED 0x00000010 #define MODE_ONLY_FULL_GROUP_BY 0x00000020 #define MODE_NO_UNSIGNED_SUBTRACTION 0x00000040 #define MODE_NO_DIR_IN_CREATE 0x00000080 #define MODE_POSTGRESQL 0x00000100 #define MODE_ORACLE 0x00000200 #define MODE_MSSQL 0x00000400 #define MODE_DB2 0x00000800 #define MODE_MAXDB 0x00001000 #define MODE_NO_KEY_OPTIONS 0x00002000 #define MODE_NO_TABLE_OPTIONS 0x00004000 #define MODE_NO_FIELD_OPTIONS 0x00008000 #define MODE_MYSQL323 0x00010000 #define MODE_MYSQL40 0x00020000 #define MODE_ANSI 0x00040000 #define MODE_NO_AUTO_VALUE_ON_ZERO 0x00080000 #define MODE_NO_BACKSLASH_ESCAPES 0x00100000 #define MODE_STRICT_TRANS_TABLES 0x00200000 #define MODE_STRICT_ALL_TABLES 0x00400000 #define MODE_NO_ZERO_IN_DATE 0x00800000 #define MODE_NO_ZERO_DATE 0x01000000 #define MODE_INVALID_DATES 0x02000000 #define MODE_ERROR_FOR_DIVISION_BY_ZERO 0x04000000 #define MODE_TRADITIONAL 0x08000000 #define MODE_NO_AUTO_CREATE_USER 0x10000000 #define MODE_HIGH_NOT_PRECEDENCE 0x20000000 #define MODE_NO_ENGINE_SUBSTITUTION 0x40000000 #define MODE_PAD_CHAR_TO_FULL_LENGTH 0x80000000 /* Log Event flags */ /* used in FOMRAT_DESCRIPTION_EVENT. Indicates if it is the active binary log. Note: When reading data via COM_BINLOG_DUMP this flag is never set. */ #define LOG_EVENT_BINLOG_IN_USE_F 0x0001 /* Looks like this flag is no longer in use */ #define LOG_EVENT_FORCED_ROTATE_F 0x0002 /* Log entry depends on thread, e.g. when using user variables or temporary tables */ #define LOG_EVENT_THREAD_SPECIFIC_F 0x0004 /* Indicates that the USE command can be suppressed before executing a statement: e.g. DRIP SCHEMA */ #define LOG_EVENT_SUPPRESS_USE_F 0x0008 /* ??? */ #define LOG_EVENT_UPDATE_TABLE_MAP_F 0x0010 /* Artifical event */ #define LOG_EVENT_ARTIFICIAL_F 0x0020 /* ??? */ #define LOG_EVENT_RELAY_LOG_F 0x0040 /* If an event is not supported, and LOG_EVENT_IGNORABLE_F was not set, an error will be reported. */ #define LOG_EVENT_IGNORABLE_F 0x0080 /* ??? */ #define LOG_EVENT_NO_FILTER_F 0x0100 /* ?? */ #define LOG_EVENT_MTS_ISOLATE_F 0x0200 /* if session variable @@skip_repliation was set, this flag will be reported for events which should be skipped. */ #define LOG_EVENT_SKIP_REPLICATION_F 0x8000 typedef struct { char *str; size_t length; } MARIADB_STRING; enum mariadb_row_event_type { WRITE_ROWS= 0, UPDATE_ROWS= 1, DELETE_ROWS= 2 }; /* Global transaction id */ typedef struct st_mariadb_gtid { unsigned int domain_id; unsigned int server_id; unsigned long long sequence_nr; } MARIADB_GTID; /* Generic replication handle */ typedef struct st_mariadb_rpl { unsigned int version; MYSQL *mysql; char *filename; uint32_t filename_length; uint32_t server_id; unsigned long start_position; uint16_t flags; uint8_t fd_header_len; /* header len from last format description event */ uint8_t use_checksum; uint8_t artificial_checksum; uint8_t verify_checksum; uint8_t post_header_len[ENUM_END_EVENT]; MA_FILE *fp; uint32_t error_no; char error_msg[MYSQL_ERRMSG_SIZE]; uint8_t uncompress; char *host; uint32_t port; uint8_t extract_values; char nonce[12]; uint8_t encrypted; uint8_t is_semi_sync; }MARIADB_RPL; typedef struct st_mariadb_rpl_value { enum enum_field_types field_type; uint8_t is_null; uint8_t is_signed; union { int64_t ll; uint64_t ull; float f; double d; MYSQL_TIME tm; MARIADB_STRING str; } val; } MARIADB_RPL_VALUE; typedef struct st_rpl_mariadb_row { uint32_t column_count; MARIADB_RPL_VALUE *columns; struct st_rpl_mariadb_row *next; } MARIADB_RPL_ROW; /* Event header */ struct st_mariadb_rpl_rotate_event { unsigned long long position; MARIADB_STRING filename; }; struct st_mariadb_rpl_query_event { uint32_t thread_id; uint32_t seconds; MARIADB_STRING database; uint32_t errornr; MARIADB_STRING status; MARIADB_STRING statement; }; struct st_mariadb_rpl_previous_gtid_event { MARIADB_CONST_DATA content; }; struct st_mariadb_rpl_gtid_list_event { uint32_t gtid_cnt; MARIADB_GTID *gtid; }; struct st_mariadb_rpl_format_description_event { uint16_t format; char *server_version; uint32_t timestamp; uint8_t header_len; MARIADB_STRING post_header_lengths; }; struct st_mariadb_rpl_checkpoint_event { MARIADB_STRING filename; }; struct st_mariadb_rpl_xid_event { uint64_t transaction_nr; }; struct st_mariadb_rpl_gtid_event { uint64_t sequence_nr; uint32_t domain_id; uint8_t flags; uint64_t commit_id; uint32_t format_id; uint8_t gtrid_len; uint8_t bqual_len; MARIADB_STRING xid; }; struct st_mariadb_rpl_annotate_rows_event { MARIADB_STRING statement; }; struct st_mariadb_rpl_table_map_event { unsigned long long table_id; MARIADB_STRING database; MARIADB_STRING table; uint32_t column_count; MARIADB_STRING column_types; MARIADB_STRING metadata; unsigned char *null_indicator; unsigned char *signed_indicator; MARIADB_CONST_DATA column_names; MARIADB_CONST_DATA geometry_types; uint32_t default_charset; MARIADB_CONST_DATA column_charsets; MARIADB_CONST_DATA simple_primary_keys; MARIADB_CONST_DATA prefixed_primary_keys; MARIADB_CONST_DATA set_values; MARIADB_CONST_DATA enum_values; uint8_t enum_set_default_charset; MARIADB_CONST_DATA enum_set_column_charsets; }; struct st_mariadb_rpl_rand_event { unsigned long long first_seed; unsigned long long second_seed; }; struct st_mariadb_rpl_intvar_event { unsigned long long value; uint8_t type; }; struct st_mariadb_begin_load_query_event { uint32_t file_id; unsigned char *data; }; struct st_mariadb_start_encryption_event { uint8_t scheme; uint32_t key_version; char nonce[12]; }; struct st_mariadb_execute_load_query_event { uint32_t thread_id; uint32_t execution_time; MARIADB_STRING schema; uint16_t error_code; uint32_t file_id; uint32_t ofs1; uint32_t ofs2; uint8_t duplicate_flag; MARIADB_STRING status_vars; MARIADB_STRING statement; }; struct st_mariadb_rpl_uservar_event { MARIADB_STRING name; uint8_t is_null; uint8_t type; uint32_t charset_nr; MARIADB_STRING value; uint8_t flags; }; struct st_mariadb_rpl_rows_event { enum mariadb_row_event_type type; uint64_t table_id; uint16_t flags; uint32_t column_count; unsigned char *column_bitmap; unsigned char *column_update_bitmap; unsigned char *null_bitmap; size_t row_data_size; void *row_data; size_t extra_data_size; void *extra_data; uint8_t compressed; uint32_t row_count; }; struct st_mariadb_rpl_heartbeat_event { uint32_t timestamp; uint32_t next_position; uint8_t type; uint16_t flags; }; struct st_mariadb_rpl_xa_prepare_log_event { uint8_t one_phase; uint32_t format_id; uint32_t gtrid_len; uint32_t bqual_len; MARIADB_STRING xid; }; struct st_mariadb_gtid_log_event { uint8_t commit_flag; char source_id[16]; uint64_t sequence_nr; }; typedef struct st_mariadb_rpl_event { /* common header */ MA_MEM_ROOT memroot; unsigned char *raw_data; size_t raw_data_size; size_t raw_data_ofs; unsigned int checksum; char ok; enum mariadb_rpl_event event_type; unsigned int timestamp; unsigned int server_id; unsigned int event_length; unsigned int next_event_pos; unsigned short flags; /****************/ union { struct st_mariadb_rpl_rotate_event rotate; struct st_mariadb_rpl_query_event query; struct st_mariadb_rpl_format_description_event format_description; struct st_mariadb_rpl_gtid_list_event gtid_list; struct st_mariadb_rpl_checkpoint_event checkpoint; struct st_mariadb_rpl_xid_event xid; struct st_mariadb_rpl_gtid_event gtid; struct st_mariadb_rpl_annotate_rows_event annotate_rows; struct st_mariadb_rpl_table_map_event table_map; struct st_mariadb_rpl_rand_event rand; struct st_mariadb_rpl_intvar_event intvar; struct st_mariadb_rpl_uservar_event uservar; struct st_mariadb_rpl_rows_event rows; struct st_mariadb_rpl_heartbeat_event heartbeat; struct st_mariadb_rpl_xa_prepare_log_event xa_prepare_log; struct st_mariadb_begin_load_query_event begin_load_query; struct st_mariadb_execute_load_query_event execute_load_query; struct st_mariadb_gtid_log_event gtid_log; struct st_mariadb_start_encryption_event start_encryption; struct st_mariadb_rpl_previous_gtid_event previous_gtid; } event; /* Added in C/C 3.3.0 */ uint8_t is_semi_sync; uint8_t semi_sync_flags; /* Added in C/C 3.3.5 */ MARIADB_RPL *rpl; } MARIADB_RPL_EVENT; /* compression uses myisampack format */ #define myisam_uint1korr(B) ((uint8_t)(*B)) #define myisam_sint1korr(B) ((int8_t)(*B)) #define myisam_uint2korr(B)\ ((uint16_t)(((uint16_t)(((const uchar*)(B))[1])) | ((uint16_t) (((const uchar*) (B))[0]) << 8))) #define myisam_sint2korr(B)\ ((int16_t)(((int16_t)(((const uchar*)(B))[1])) | ((int16_t) (((const uchar*) (B))[0]) << 8))) #define myisam_uint3korr(B)\ ((uint32_t)(((uint32_t)(((const uchar*)(B))[2])) |\ (((uint32_t)(((const uchar*)(B))[1])) << 8) |\ (((uint32_t)(((const uchar*)(B))[0])) << 16))) #define myisam_sint3korr(B)\ ((int32_t)(((int32_t)(((const uchar*)(B))[2])) |\ (((int32_t)(((const uchar*)(B))[1])) << 8) |\ (((int32_t)(((const uchar*)(B))[0])) << 16))) #define myisam_uint4korr(B)\ ((uint32_t)(((uint32_t)(((const uchar*)(B))[3])) |\ (((uint32_t)(((const uchar*)(B))[2])) << 8) |\ (((uint32_t)(((const uchar*) (B))[1])) << 16) |\ (((uint32_t)(((const uchar*) (B))[0])) << 24))) #define myisam_sint4korr(B)\ ((int32_t)(((int32_t)(((const uchar*)(B))[3])) |\ (((int32_t)(((const uchar*)(B))[2])) << 8) |\ (((int32_t)(((const uchar*) (B))[1])) << 16) |\ (((int32_t)(((const uchar*) (B))[0])) << 24))) #define mi_uint5korr(B)\ ((uint64_t)(((uint32_t) (((const uchar*) (B))[4])) |\ (((uint32_t) (((const uchar*) (B))[3])) << 8) |\ (((uint32_t) (((const uchar*) (B))[2])) << 16) |\ (((uint32_t) (((const uchar*) (B))[1])) << 24)) |\ (((uint64_t) (((const uchar*) (B))[0])) << 32)) #define RPL_SAFEGUARD(rpl, event, condition) \ if (!(condition))\ {\ my_set_error((rpl)->mysql, CR_BINLOG_ERROR, SQLSTATE_UNKNOWN, 0,\ (rpl)->filename_length, (rpl)->filename,\ (rpl)->start_position,\ "Packet corrupted");\ mariadb_free_rpl_event((event));\ return 0;\ } #define mariadb_rpl_init(a) mariadb_rpl_init_ex((a), MARIADB_RPL_VERSION) #define rpl_clear_error(rpl)\ (rpl)->error_no= (rpl)->error_msg[0]= 0 #define IS_ROW_VERSION2(a)\ ((a) == WRITE_ROWS_EVENT || (a) == UPDATE_ROWS_EVENT || \ (a) == DELETE_ROWS_EVENT || (a) == WRITE_ROWS_COMPRESSED_EVENT ||\ (a) == UPDATE_ROWS_COMPRESSED_EVENT || (a) == DELETE_ROWS_COMPRESSED_EVENT) #define IS_ROW_EVENT(a)\ ((a)->event_type == WRITE_ROWS_COMPRESSED_EVENT_V1 ||\ (a)->event_type == UPDATE_ROWS_COMPRESSED_EVENT_V1 ||\ (a)->event_type == DELETE_ROWS_COMPRESSED_EVENT_V1 ||\ (a)->event_type == WRITE_ROWS_EVENT_V1 ||\ (a)->event_type == UPDATE_ROWS_EVENT_V1 ||\ (a)->event_type == DELETE_ROWS_EVENT_V1 ||\ (a)->event_type == WRITE_ROWS_EVENT ||\ (a)->event_type == UPDATE_ROWS_EVENT ||\ (a)->event_type == DELETE_ROWS_EVENT) /* Function prototypes */ MARIADB_RPL * STDCALL mariadb_rpl_init_ex(MYSQL *mysql, unsigned int version); const char * STDCALL mariadb_rpl_error(MARIADB_RPL *rpl); uint32_t STDCALL mariadb_rpl_errno(MARIADB_RPL *rpl); int STDCALL mariadb_rpl_optionsv(MARIADB_RPL *rpl, enum mariadb_rpl_option, ...); int STDCALL mariadb_rpl_get_optionsv(MARIADB_RPL *rpl, enum mariadb_rpl_option, ...); int STDCALL mariadb_rpl_open(MARIADB_RPL *rpl); void STDCALL mariadb_rpl_close(MARIADB_RPL *rpl); MARIADB_RPL_EVENT * STDCALL mariadb_rpl_fetch(MARIADB_RPL *rpl, MARIADB_RPL_EVENT *event); void STDCALL mariadb_free_rpl_event(MARIADB_RPL_EVENT *event); MARIADB_RPL_ROW * STDCALL mariadb_rpl_extract_rows(MARIADB_RPL *rpl, MARIADB_RPL_EVENT *tm_event, MARIADB_RPL_EVENT *row_event); #ifdef __cplusplus } #endif #endif mysql/ma_tls.h000064400000010371151027430560007346 0ustar00#ifndef _ma_tls_h_ #define _ma_tls_h_ enum enum_pvio_tls_type { SSL_TYPE_DEFAULT=0, #ifdef _WIN32 SSL_TYPE_SCHANNEL, #endif SSL_TYPE_OPENSSL, SSL_TYPE_GNUTLS }; #define PROTOCOL_SSLV3 0 #define PROTOCOL_TLS_1_0 1 #define PROTOCOL_TLS_1_1 2 #define PROTOCOL_TLS_1_2 3 #define PROTOCOL_TLS_1_3 4 #define PROTOCOL_UNKNOWN 5 #define PROTOCOL_MAX PROTOCOL_TLS_1_3 #define TLS_VERSION_LENGTH 64 extern char tls_library_version[TLS_VERSION_LENGTH]; typedef struct st_ma_pvio_tls { void *data; MARIADB_PVIO *pvio; void *ssl; } MARIADB_TLS; /* Function prototypes */ /* ma_tls_start initializes the ssl library Parameter: errmsg pointer to error message buffer errmsg_len length of error message buffer Returns: 0 success 1 if an error occurred Notes: On success the global variable ma_tls_initialized will be set to 1 */ int ma_tls_start(char *errmsg, size_t errmsg_len); /* ma_tls_end unloads/deinitializes ssl library and unsets global variable ma_tls_initialized */ void ma_tls_end(void); /* ma_tls_init creates a new SSL structure for a SSL connection and loads client certificates Parameters: MYSQL a mysql structure Returns: void * a pointer to internal SSL structure */ void * ma_tls_init(MYSQL *mysql); /* ma_tls_connect performs SSL handshake Parameters: MARIADB_TLS MariaDB SSL container Returns: 0 success 1 error */ my_bool ma_tls_connect(MARIADB_TLS *ctls); /* ma_tls_read reads up to length bytes from socket Parameters: ctls MariaDB SSL container buffer read buffer length buffer length Returns: 0-n bytes read -1 if an error occurred */ ssize_t ma_tls_read(MARIADB_TLS *ctls, const uchar* buffer, size_t length); /* ma_tls_write write buffer to socket Parameters: ctls MariaDB SSL container buffer write buffer length buffer length Returns: 0-n bytes written -1 if an error occurred */ ssize_t ma_tls_write(MARIADB_TLS *ctls, const uchar* buffer, size_t length); /* ma_tls_close closes SSL connection and frees SSL structure which was previously created by ma_tls_init call Parameters: MARIADB_TLS MariaDB SSL container Returns: 0 success 1 error */ my_bool ma_tls_close(MARIADB_TLS *ctls); /* ma_tls_verify_server_cert validation check of server certificate Parameter: MARIADB_TLS MariaDB SSL container Returns: ß success 1 error */ int ma_tls_verify_server_cert(MARIADB_TLS *ctls); /* ma_tls_get_cipher returns cipher for current ssl connection Parameter: MARIADB_TLS MariaDB SSL container Returns: cipher in use or NULL on error */ const char *ma_tls_get_cipher(MARIADB_TLS *ssl); /* ma_tls_get_finger_print returns SHA1 finger print of server certificate Parameter: MARIADB_TLS MariaDB SSL container fp buffer for fingerprint fp_len buffer length Returns: actual size of finger print */ unsigned int ma_tls_get_finger_print(MARIADB_TLS *ctls, char *fp, unsigned int fp_len); /* ma_tls_get_protocol_version returns protocol version number in use Parameter: MARIADB_TLS MariaDB SSL container Returns: protocol number */ int ma_tls_get_protocol_version(MARIADB_TLS *ctls); const char *ma_pvio_tls_get_protocol_version(MARIADB_TLS *ctls); int ma_pvio_tls_get_protocol_version_id(MARIADB_TLS *ctls); void ma_tls_set_connection(MYSQL *mysql); /* Function prototypes */ MARIADB_TLS *ma_pvio_tls_init(MYSQL *mysql); my_bool ma_pvio_tls_connect(MARIADB_TLS *ctls); ssize_t ma_pvio_tls_read(MARIADB_TLS *ctls, const uchar *buffer, size_t length); ssize_t ma_pvio_tls_write(MARIADB_TLS *ctls, const uchar *buffer, size_t length); my_bool ma_pvio_tls_close(MARIADB_TLS *ctls); int ma_pvio_tls_verify_server_cert(MARIADB_TLS *ctls); const char *ma_pvio_tls_cipher(MARIADB_TLS *ctls); my_bool ma_pvio_tls_check_fp(MARIADB_TLS *ctls, const char *fp, const char *fp_list); my_bool ma_pvio_start_ssl(MARIADB_PVIO *pvio); void ma_pvio_tls_set_connection(MYSQL *mysql); void ma_pvio_tls_end(); #endif /* _ma_tls_h_ */ krad.h000064400000021345151027430560005646 0ustar00/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2013 Red Hat, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This API is not considered as stable as the main krb5 API. * * - We may make arbitrary incompatible changes between feature releases * (e.g. from 1.12 to 1.13). * - We will make some effort to avoid making incompatible changes for * bugfix releases, but will make them if necessary. */ #ifndef KRAD_H_ #define KRAD_H_ #include #include #include #include #define KRAD_PACKET_SIZE_MAX 4096 #define KRAD_SERVICE_TYPE_LOGIN 1 #define KRAD_SERVICE_TYPE_FRAMED 2 #define KRAD_SERVICE_TYPE_CALLBACK_LOGIN 3 #define KRAD_SERVICE_TYPE_CALLBACK_FRAMED 4 #define KRAD_SERVICE_TYPE_OUTBOUND 5 #define KRAD_SERVICE_TYPE_ADMINISTRATIVE 6 #define KRAD_SERVICE_TYPE_NAS_PROMPT 7 #define KRAD_SERVICE_TYPE_AUTHENTICATE_ONLY 8 #define KRAD_SERVICE_TYPE_CALLBACK_NAS_PROMPT 9 #define KRAD_SERVICE_TYPE_CALL_CHECK 10 #define KRAD_SERVICE_TYPE_CALLBACK_ADMINISTRATIVE 11 typedef struct krad_attrset_st krad_attrset; typedef struct krad_packet_st krad_packet; typedef struct krad_client_st krad_client; typedef unsigned char krad_code; typedef unsigned char krad_attr; /* Called when a response is received or the request times out. */ typedef void (*krad_cb)(krb5_error_code retval, const krad_packet *request, const krad_packet *response, void *data); /* * Called to iterate over a set of requests. Either the callback will be * called until it returns NULL, or it will be called with cancel = TRUE to * terminate in the middle of an iteration. */ typedef const krad_packet * (*krad_packet_iter_cb)(void *data, krb5_boolean cancel); /* * Code */ /* Convert a code name to its number. Only works for codes defined * by RFC 2875 or 2882. Returns 0 if the name was not found. */ krad_code krad_code_name2num(const char *name); /* Convert a code number to its name. Only works for attributes defined * by RFC 2865 or 2882. Returns NULL if the name was not found. */ const char * krad_code_num2name(krad_code code); /* * Attribute */ /* Convert an attribute name to its number. Only works for attributes defined * by RFC 2865. Returns 0 if the name was not found. */ krad_attr krad_attr_name2num(const char *name); /* Convert an attribute number to its name. Only works for attributes defined * by RFC 2865. Returns NULL if the name was not found. */ const char * krad_attr_num2name(krad_attr type); /* * Attribute set */ /* Create a new attribute set. */ krb5_error_code krad_attrset_new(krb5_context ctx, krad_attrset **set); /* Create a deep copy of an attribute set. */ krb5_error_code krad_attrset_copy(const krad_attrset *set, krad_attrset **copy); /* Free an attribute set. */ void krad_attrset_free(krad_attrset *set); /* Add an attribute to a set. */ krb5_error_code krad_attrset_add(krad_attrset *set, krad_attr type, const krb5_data *data); /* Add a four-octet unsigned number attribute to the given set. */ krb5_error_code krad_attrset_add_number(krad_attrset *set, krad_attr type, krb5_ui_4 num); /* Delete the specified attribute. */ void krad_attrset_del(krad_attrset *set, krad_attr type, size_t indx); /* Get the specified attribute. */ const krb5_data * krad_attrset_get(const krad_attrset *set, krad_attr type, size_t indx); /* * Packet */ /* Determine the bytes needed from the socket to get the whole packet. Don't * cache the return value as it can change! Returns -1 on EBADMSG. */ ssize_t krad_packet_bytes_needed(const krb5_data *buffer); /* Free a packet. */ void krad_packet_free(krad_packet *pkt); /* * Create a new request packet. * * This function takes the attributes specified in set and converts them into a * radius packet. The packet will have a randomized id. If cb is not NULL, it * will be called passing data as the argument to iterate over a set of * outstanding requests. In this case, the id will be both random and unique * across the set of requests. */ krb5_error_code krad_packet_new_request(krb5_context ctx, const char *secret, krad_code code, const krad_attrset *set, krad_packet_iter_cb cb, void *data, krad_packet **request); /* * Create a new response packet. * * This function is similar to krad_packet_new_requst() except that it crafts a * packet in response to a request packet. This new packet will borrow values * from the request such as the id and the authenticator. */ krb5_error_code krad_packet_new_response(krb5_context ctx, const char *secret, krad_code code, const krad_attrset *set, const krad_packet *request, krad_packet **response); /* * Decode a request radius packet from krb5_data. * * The resulting decoded packet will be a request packet stored in *reqpkt. * * If cb is NULL, *duppkt will always be NULL. * * If cb is not NULL, it will be called (with the data argument) to iterate * over a set of requests currently being processed. In this case, if the * packet is a duplicate of an already received request, the original request * will be set in *duppkt. */ krb5_error_code krad_packet_decode_request(krb5_context ctx, const char *secret, const krb5_data *buffer, krad_packet_iter_cb cb, void *data, const krad_packet **duppkt, krad_packet **reqpkt); /* * Decode a response radius packet from krb5_data. * * The resulting decoded packet will be a response packet stored in *rsppkt. * * If cb is NULL, *reqpkt will always be NULL. * * If cb is not NULL, it will be called (with the data argument) to iterate * over a set of requests awaiting responses. In this case, if the response * packet matches one of these requests, the original request will be set in * *reqpkt. */ krb5_error_code krad_packet_decode_response(krb5_context ctx, const char *secret, const krb5_data *buffer, krad_packet_iter_cb cb, void *data, const krad_packet **reqpkt, krad_packet **rsppkt); /* Encode packet. */ const krb5_data * krad_packet_encode(const krad_packet *pkt); /* Get the code for the given packet. */ krad_code krad_packet_get_code(const krad_packet *pkt); /* Get the specified attribute. */ const krb5_data * krad_packet_get_attr(const krad_packet *pkt, krad_attr type, size_t indx); /* * Client */ /* Create a new client. */ krb5_error_code krad_client_new(krb5_context kctx, verto_ctx *vctx, krad_client **client); /* Free the client. */ void krad_client_free(krad_client *client); /* * Send a request to a radius server. * * The remote host may be specified by one of the following formats: * - /path/to/unix.socket * - IPv4 * - IPv4:port * - IPv4:service * - [IPv6] * - [IPv6]:port * - [IPv6]:service * - hostname * - hostname:port * - hostname:service * * The timeout parameter (milliseconds) is the total timeout across all remote * hosts (when DNS returns multiple entries) and all retries. For stream * sockets, the retries parameter is ignored and no retries are performed. * * The cb function will be called with the data argument when either a response * is received or the request times out on all possible remote hosts. */ krb5_error_code krad_client_send(krad_client *rc, krad_code code, const krad_attrset *attrs, const char *remote, const char *secret, int timeout, size_t retries, krad_cb cb, void *data); #endif /* KRAD_H_ */ wait.h000064400000000026151027430560005662 0ustar00#include asm/mce.h000064400000003230151027430560006242 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_MCE_H #define _ASM_X86_MCE_H #include #include /* * Fields are zero when not available. Also, this struct is shared with * userspace mcelog and thus must keep existing fields at current offsets. * Only add new fields to the end of the structure */ struct mce { __u64 status; /* Bank's MCi_STATUS MSR */ __u64 misc; /* Bank's MCi_MISC MSR */ __u64 addr; /* Bank's MCi_ADDR MSR */ __u64 mcgstatus; /* Machine Check Global Status MSR */ __u64 ip; /* Instruction Pointer when the error happened */ __u64 tsc; /* CPU time stamp counter */ __u64 time; /* Wall time_t when error was detected */ __u8 cpuvendor; /* Kernel's X86_VENDOR enum */ __u8 inject_flags; /* Software inject flags */ __u8 severity; /* Error severity */ __u8 pad; __u32 cpuid; /* CPUID 1 EAX */ __u8 cs; /* Code segment */ __u8 bank; /* Machine check bank reporting the error */ __u8 cpu; /* CPU number; obsoleted by extcpu */ __u8 finished; /* Entry is valid */ __u32 extcpu; /* Linux CPU number that detected the error */ __u32 socketid; /* CPU socket ID */ __u32 apicid; /* CPU initial APIC ID */ __u64 mcgcap; /* MCGCAP MSR: machine check capabilities of CPU */ __u64 synd; /* MCA_SYND MSR: only valid on SMCA systems */ __u64 ipid; /* MCA_IPID MSR: only valid on SMCA systems */ __u64 ppin; /* Protected Processor Inventory Number */ __u32 microcode; /* Microcode revision */ }; #define MCE_GET_RECORD_LEN _IOR('M', 1, int) #define MCE_GET_LOG_LEN _IOR('M', 2, int) #define MCE_GETCLEAR_FLAGS _IOR('M', 3, int) #endif /* _ASM_X86_MCE_H */ asm/sigcontext32.h000064400000000367151027430560010042 0ustar00/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _ASM_X86_SIGCONTEXT32_H #define _ASM_X86_SIGCONTEXT32_H /* This is a legacy file - all the type definitions are in sigcontext.h: */ #include #endif /* _ASM_X86_SIGCONTEXT32_H */ asm/ioctl.h000064400000000037151027430560006612 0ustar00#include asm/msr.h000064400000000532151027430560006301 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_MSR_H #define _ASM_X86_MSR_H #ifndef __ASSEMBLY__ #include #include #define X86_IOC_RDMSR_REGS _IOWR('c', 0xA0, __u32[8]) #define X86_IOC_WRMSR_REGS _IOWR('c', 0xA1, __u32[8]) #endif /* __ASSEMBLY__ */ #endif /* _ASM_X86_MSR_H */ asm/msgbuf.h000064400000002035151027430560006763 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_X64_MSGBUF_H #define __ASM_X64_MSGBUF_H #if !defined(__x86_64__) || !defined(__ILP32__) #include #else /* * The msqid64_ds structure for x86 architecture with x32 ABI. * * On x86-32 and x86-64 we can just use the generic definition, but * x32 uses the same binary layout as x86_64, which is differnet * from other 32-bit architectures. */ struct msqid64_ds { struct ipc64_perm msg_perm; __kernel_time_t msg_stime; /* last msgsnd time */ __kernel_time_t msg_rtime; /* last msgrcv time */ __kernel_time_t msg_ctime; /* last change time */ __kernel_ulong_t msg_cbytes; /* current number of bytes on queue */ __kernel_ulong_t msg_qnum; /* number of messages in queue */ __kernel_ulong_t msg_qbytes; /* max number of bytes on queue */ __kernel_pid_t msg_lspid; /* pid of last msgsnd */ __kernel_pid_t msg_lrpid; /* last receive pid */ __kernel_ulong_t __unused4; __kernel_ulong_t __unused5; }; #endif #endif /* __ASM_GENERIC_MSGBUF_H */ asm/vsyscall.h000064400000000407151027430560007341 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_VSYSCALL_H #define _ASM_X86_VSYSCALL_H enum vsyscall_num { __NR_vgettimeofday, __NR_vtime, __NR_vgetcpu, }; #define VSYSCALL_ADDR (-10UL << 20) #endif /* _ASM_X86_VSYSCALL_H */ asm/ldt.h000064400000002432151027430560006264 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * ldt.h * * Definitions of structures used with the modify_ldt system call. */ #ifndef _ASM_X86_LDT_H #define _ASM_X86_LDT_H /* Maximum number of LDT entries supported. */ #define LDT_ENTRIES 8192 /* The size of each LDT entry. */ #define LDT_ENTRY_SIZE 8 #ifndef __ASSEMBLY__ /* * Note on 64bit base and limit is ignored and you cannot set DS/ES/CS * not to the default values if you still want to do syscalls. This * call is more for 32bit mode therefore. */ struct user_desc { unsigned int entry_number; unsigned int base_addr; unsigned int limit; unsigned int seg_32bit:1; unsigned int contents:2; unsigned int read_exec_only:1; unsigned int limit_in_pages:1; unsigned int seg_not_present:1; unsigned int useable:1; #ifdef __x86_64__ /* * Because this bit is not present in 32-bit user code, user * programs can pass uninitialized values here. Therefore, in * any context in which a user_desc comes from a 32-bit program, * the kernel must act as though lm == 0, regardless of the * actual value. */ unsigned int lm:1; #endif }; #define MODIFY_LDT_CONTENTS_DATA 0 #define MODIFY_LDT_CONTENTS_STACK 1 #define MODIFY_LDT_CONTENTS_CODE 2 #endif /* !__ASSEMBLY__ */ #endif /* _ASM_X86_LDT_H */ asm/ptrace.h000064400000002727151027430560006766 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_PTRACE_H #define _ASM_X86_PTRACE_H /* For */ #include #include #ifndef __ASSEMBLY__ #ifdef __i386__ /* this struct defines the way the registers are stored on the stack during a system call. */ struct pt_regs { long ebx; long ecx; long edx; long esi; long edi; long ebp; long eax; int xds; int xes; int xfs; int xgs; long orig_eax; long eip; int xcs; long eflags; long esp; int xss; }; #else /* __i386__ */ struct pt_regs { /* * C ABI says these regs are callee-preserved. They aren't saved on kernel entry * unless syscall needs a complete, fully filled "struct pt_regs". */ unsigned long r15; unsigned long r14; unsigned long r13; unsigned long r12; unsigned long rbp; unsigned long rbx; /* These regs are callee-clobbered. Always saved on kernel entry. */ unsigned long r11; unsigned long r10; unsigned long r9; unsigned long r8; unsigned long rax; unsigned long rcx; unsigned long rdx; unsigned long rsi; unsigned long rdi; /* * On syscall entry, this is syscall#. On CPU exception, this is error code. * On hw interrupt, it's IRQ number: */ unsigned long orig_rax; /* Return frame for iretq */ unsigned long rip; unsigned long cs; unsigned long eflags; unsigned long rsp; unsigned long ss; /* top of stack page */ }; #endif /* !__i386__ */ #endif /* !__ASSEMBLY__ */ #endif /* _ASM_X86_PTRACE_H */ asm/stat.h000064400000006073151027430560006461 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_STAT_H #define _ASM_X86_STAT_H #include #define STAT_HAVE_NSEC 1 #ifdef __i386__ struct stat { unsigned long st_dev; unsigned long st_ino; unsigned short st_mode; unsigned short st_nlink; unsigned short st_uid; unsigned short st_gid; unsigned long st_rdev; unsigned long st_size; unsigned long st_blksize; unsigned long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned long st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long __unused4; unsigned long __unused5; }; /* We don't need to memset the whole thing just to initialize the padding */ #define INIT_STRUCT_STAT_PADDING(st) do { \ st.__unused4 = 0; \ st.__unused5 = 0; \ } while (0) #define STAT64_HAS_BROKEN_ST_INO 1 /* This matches struct stat64 in glibc2.1, hence the absolutely * insane amounts of padding around dev_t's. */ struct stat64 { unsigned long long st_dev; unsigned char __pad0[4]; unsigned long __st_ino; unsigned int st_mode; unsigned int st_nlink; unsigned long st_uid; unsigned long st_gid; unsigned long long st_rdev; unsigned char __pad3[4]; long long st_size; unsigned long st_blksize; /* Number 512-byte blocks allocated. */ unsigned long long st_blocks; unsigned long st_atime; unsigned long st_atime_nsec; unsigned long st_mtime; unsigned int st_mtime_nsec; unsigned long st_ctime; unsigned long st_ctime_nsec; unsigned long long st_ino; }; /* We don't need to memset the whole thing just to initialize the padding */ #define INIT_STRUCT_STAT64_PADDING(st) do { \ memset(&st.__pad0, 0, sizeof(st.__pad0)); \ memset(&st.__pad3, 0, sizeof(st.__pad3)); \ } while (0) #else /* __i386__ */ struct stat { __kernel_ulong_t st_dev; __kernel_ulong_t st_ino; __kernel_ulong_t st_nlink; unsigned int st_mode; unsigned int st_uid; unsigned int st_gid; unsigned int __pad0; __kernel_ulong_t st_rdev; __kernel_long_t st_size; __kernel_long_t st_blksize; __kernel_long_t st_blocks; /* Number 512-byte blocks allocated. */ __kernel_ulong_t st_atime; __kernel_ulong_t st_atime_nsec; __kernel_ulong_t st_mtime; __kernel_ulong_t st_mtime_nsec; __kernel_ulong_t st_ctime; __kernel_ulong_t st_ctime_nsec; __kernel_long_t __unused[3]; }; /* We don't need to memset the whole thing just to initialize the padding */ #define INIT_STRUCT_STAT_PADDING(st) do { \ st.__pad0 = 0; \ st.__unused[0] = 0; \ st.__unused[1] = 0; \ st.__unused[2] = 0; \ } while (0) #endif /* for 32bit emulation and 32 bit kernels */ struct __old_kernel_stat { unsigned short st_dev; unsigned short st_ino; unsigned short st_mode; unsigned short st_nlink; unsigned short st_uid; unsigned short st_gid; unsigned short st_rdev; #ifdef __i386__ unsigned long st_size; unsigned long st_atime; unsigned long st_mtime; unsigned long st_ctime; #else unsigned int st_size; unsigned int st_atime; unsigned int st_mtime; unsigned int st_ctime; #endif }; #endif /* _ASM_X86_STAT_H */ asm/vm86.h000064400000006056151027430560006307 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_VM86_H #define _ASM_X86_VM86_H /* * I'm guessing at the VIF/VIP flag usage, but hope that this is how * the Pentium uses them. Linux will return from vm86 mode when both * VIF and VIP is set. * * On a Pentium, we could probably optimize the virtual flags directly * in the eflags register instead of doing it "by hand" in vflags... * * Linus */ #include #define BIOSSEG 0x0f000 #define CPU_086 0 #define CPU_186 1 #define CPU_286 2 #define CPU_386 3 #define CPU_486 4 #define CPU_586 5 /* * Return values for the 'vm86()' system call */ #define VM86_TYPE(retval) ((retval) & 0xff) #define VM86_ARG(retval) ((retval) >> 8) #define VM86_SIGNAL 0 /* return due to signal */ #define VM86_UNKNOWN 1 /* unhandled GP fault - IO-instruction or similar */ #define VM86_INTx 2 /* int3/int x instruction (ARG = x) */ #define VM86_STI 3 /* sti/popf/iret instruction enabled virtual interrupts */ /* * Additional return values when invoking new vm86() */ #define VM86_PICRETURN 4 /* return due to pending PIC request */ #define VM86_TRAP 6 /* return due to DOS-debugger request */ /* * function codes when invoking new vm86() */ #define VM86_PLUS_INSTALL_CHECK 0 #define VM86_ENTER 1 #define VM86_ENTER_NO_BYPASS 2 #define VM86_REQUEST_IRQ 3 #define VM86_FREE_IRQ 4 #define VM86_GET_IRQ_BITS 5 #define VM86_GET_AND_RESET_IRQ 6 /* * This is the stack-layout seen by the user space program when we have * done a translation of "SAVE_ALL" from vm86 mode. The real kernel layout * is 'kernel_vm86_regs' (see below). */ struct vm86_regs { /* * normal regs, with special meaning for the segment descriptors.. */ long ebx; long ecx; long edx; long esi; long edi; long ebp; long eax; long __null_ds; long __null_es; long __null_fs; long __null_gs; long orig_eax; long eip; unsigned short cs, __csh; long eflags; long esp; unsigned short ss, __ssh; /* * these are specific to v86 mode: */ unsigned short es, __esh; unsigned short ds, __dsh; unsigned short fs, __fsh; unsigned short gs, __gsh; }; struct revectored_struct { unsigned long __map[8]; /* 256 bits */ }; struct vm86_struct { struct vm86_regs regs; unsigned long flags; unsigned long screen_bitmap; unsigned long cpu_type; struct revectored_struct int_revectored; struct revectored_struct int21_revectored; }; /* * flags masks */ #define VM86_SCREEN_BITMAP 0x0001 struct vm86plus_info_struct { unsigned long force_return_for_pic:1; unsigned long vm86dbg_active:1; /* for debugger */ unsigned long vm86dbg_TFpendig:1; /* for debugger */ unsigned long unused:28; unsigned long is_vm86pus:1; /* for vm86 internal use */ unsigned char vm86dbg_intxxtab[32]; /* for debugger */ }; struct vm86plus_struct { struct vm86_regs regs; unsigned long flags; unsigned long screen_bitmap; unsigned long cpu_type; struct revectored_struct int_revectored; struct revectored_struct int21_revectored; struct vm86plus_info_struct vm86plus; }; #endif /* _ASM_X86_VM86_H */ asm/perf_regs.h000064400000002573151027430560007463 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_PERF_REGS_H #define _ASM_X86_PERF_REGS_H enum perf_event_x86_regs { PERF_REG_X86_AX, PERF_REG_X86_BX, PERF_REG_X86_CX, PERF_REG_X86_DX, PERF_REG_X86_SI, PERF_REG_X86_DI, PERF_REG_X86_BP, PERF_REG_X86_SP, PERF_REG_X86_IP, PERF_REG_X86_FLAGS, PERF_REG_X86_CS, PERF_REG_X86_SS, PERF_REG_X86_DS, PERF_REG_X86_ES, PERF_REG_X86_FS, PERF_REG_X86_GS, PERF_REG_X86_R8, PERF_REG_X86_R9, PERF_REG_X86_R10, PERF_REG_X86_R11, PERF_REG_X86_R12, PERF_REG_X86_R13, PERF_REG_X86_R14, PERF_REG_X86_R15, /* These are the limits for the GPRs. */ PERF_REG_X86_32_MAX = PERF_REG_X86_GS + 1, PERF_REG_X86_64_MAX = PERF_REG_X86_R15 + 1, /* These all need two bits set because they are 128bit */ PERF_REG_X86_XMM0 = 32, PERF_REG_X86_XMM1 = 34, PERF_REG_X86_XMM2 = 36, PERF_REG_X86_XMM3 = 38, PERF_REG_X86_XMM4 = 40, PERF_REG_X86_XMM5 = 42, PERF_REG_X86_XMM6 = 44, PERF_REG_X86_XMM7 = 46, PERF_REG_X86_XMM8 = 48, PERF_REG_X86_XMM9 = 50, PERF_REG_X86_XMM10 = 52, PERF_REG_X86_XMM11 = 54, PERF_REG_X86_XMM12 = 56, PERF_REG_X86_XMM13 = 58, PERF_REG_X86_XMM14 = 60, PERF_REG_X86_XMM15 = 62, /* These include both GPRs and XMMX registers */ PERF_REG_X86_XMM_MAX = PERF_REG_X86_XMM15 + 2, }; #define PERF_REG_EXTENDED_MASK (~((1ULL << PERF_REG_X86_XMM0) - 1)) #endif /* _ASM_X86_PERF_REGS_H */ asm/e820.h000064400000005023151027430560006156 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_E820_H #define _ASM_X86_E820_H #define E820MAP 0x2d0 /* our map */ #define E820MAX 128 /* number of entries in E820MAP */ /* * Legacy E820 BIOS limits us to 128 (E820MAX) nodes due to the * constrained space in the zeropage. If we have more nodes than * that, and if we've booted off EFI firmware, then the EFI tables * passed us from the EFI firmware can list more nodes. Size our * internal memory map tables to have room for these additional * nodes, based on up to three entries per node for which the * kernel was built: MAX_NUMNODES == (1 << CONFIG_NODES_SHIFT), * plus E820MAX, allowing space for the possible duplicate E820 * entries that might need room in the same arrays, prior to the * call to sanitize_e820_map() to remove duplicates. The allowance * of three memory map entries per node is "enough" entries for * the initial hardware platform motivating this mechanism to make * use of additional EFI map entries. Future platforms may want * to allow more than three entries per node or otherwise refine * this size. */ #define E820_X_MAX E820MAX #define E820NR 0x1e8 /* # entries in E820MAP */ #define E820_RAM 1 #define E820_RESERVED 2 #define E820_ACPI 3 #define E820_NVS 4 #define E820_UNUSABLE 5 #define E820_PMEM 7 /* * This is a non-standardized way to represent ADR or NVDIMM regions that * persist over a reboot. The kernel will ignore their special capabilities * unless the CONFIG_X86_PMEM_LEGACY option is set. * * ( Note that older platforms also used 6 for the same type of memory, * but newer versions switched to 12 as 6 was assigned differently. Some * time they will learn... ) */ #define E820_PRAM 12 /* * reserved RAM used by kernel itself * if CONFIG_INTEL_TXT is enabled, memory of this type will be * included in the S3 integrity calculation and so should not include * any memory that BIOS might alter over the S3 transition */ #define E820_RESERVED_KERN 128 #ifndef __ASSEMBLY__ #include struct e820entry { __u64 addr; /* start of memory segment */ __u64 size; /* size of memory segment */ __u32 type; /* type of memory segment */ } __attribute__((packed)); struct e820map { __u32 nr_map; struct e820entry map[E820_X_MAX]; }; #define ISA_START_ADDRESS 0xa0000 #define ISA_END_ADDRESS 0x100000 #define BIOS_BEGIN 0x000a0000 #define BIOS_END 0x00100000 #define BIOS_ROM_BASE 0xffe00000 #define BIOS_ROM_END 0xffffffff #endif /* __ASSEMBLY__ */ #endif /* _ASM_X86_E820_H */ asm/socket.h000064400000000040151027430560006762 0ustar00#include asm/amd_hsmp.h000064400000021274151027430560007276 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_AMD_HSMP_H_ #define _ASM_X86_AMD_HSMP_H_ #include #pragma pack(4) #define HSMP_MAX_MSG_LEN 8 /* * HSMP Messages supported */ enum hsmp_message_ids { HSMP_TEST = 1, /* 01h Increments input value by 1 */ HSMP_GET_SMU_VER, /* 02h SMU FW version */ HSMP_GET_PROTO_VER, /* 03h HSMP interface version */ HSMP_GET_SOCKET_POWER, /* 04h average package power consumption */ HSMP_SET_SOCKET_POWER_LIMIT, /* 05h Set the socket power limit */ HSMP_GET_SOCKET_POWER_LIMIT, /* 06h Get current socket power limit */ HSMP_GET_SOCKET_POWER_LIMIT_MAX,/* 07h Get maximum socket power value */ HSMP_SET_BOOST_LIMIT, /* 08h Set a core maximum frequency limit */ HSMP_SET_BOOST_LIMIT_SOCKET, /* 09h Set socket maximum frequency level */ HSMP_GET_BOOST_LIMIT, /* 0Ah Get current frequency limit */ HSMP_GET_PROC_HOT, /* 0Bh Get PROCHOT status */ HSMP_SET_XGMI_LINK_WIDTH, /* 0Ch Set max and min width of xGMI Link */ HSMP_SET_DF_PSTATE, /* 0Dh Alter APEnable/Disable messages behavior */ HSMP_SET_AUTO_DF_PSTATE, /* 0Eh Enable DF P-State Performance Boost algorithm */ HSMP_GET_FCLK_MCLK, /* 0Fh Get FCLK and MEMCLK for current socket */ HSMP_GET_CCLK_THROTTLE_LIMIT, /* 10h Get CCLK frequency limit in socket */ HSMP_GET_C0_PERCENT, /* 11h Get average C0 residency in socket */ HSMP_SET_NBIO_DPM_LEVEL, /* 12h Set max/min LCLK DPM Level for a given NBIO */ HSMP_GET_NBIO_DPM_LEVEL, /* 13h Get LCLK DPM level min and max for a given NBIO */ HSMP_GET_DDR_BANDWIDTH, /* 14h Get theoretical maximum and current DDR Bandwidth */ HSMP_GET_TEMP_MONITOR, /* 15h Get socket temperature */ HSMP_GET_DIMM_TEMP_RANGE, /* 16h Get per-DIMM temperature range and refresh rate */ HSMP_GET_DIMM_POWER, /* 17h Get per-DIMM power consumption */ HSMP_GET_DIMM_THERMAL, /* 18h Get per-DIMM thermal sensors */ HSMP_GET_SOCKET_FREQ_LIMIT, /* 19h Get current active frequency per socket */ HSMP_GET_CCLK_CORE_LIMIT, /* 1Ah Get CCLK frequency limit per core */ HSMP_GET_RAILS_SVI, /* 1Bh Get SVI-based Telemetry for all rails */ HSMP_GET_SOCKET_FMAX_FMIN, /* 1Ch Get Fmax and Fmin per socket */ HSMP_GET_IOLINK_BANDWITH, /* 1Dh Get current bandwidth on IO Link */ HSMP_GET_XGMI_BANDWITH, /* 1Eh Get current bandwidth on xGMI Link */ HSMP_SET_GMI3_WIDTH, /* 1Fh Set max and min GMI3 Link width */ HSMP_SET_PCI_RATE, /* 20h Control link rate on PCIe devices */ HSMP_SET_POWER_MODE, /* 21h Select power efficiency profile policy */ HSMP_SET_PSTATE_MAX_MIN, /* 22h Set the max and min DF P-State */ HSMP_MSG_ID_MAX, }; struct hsmp_message { __u32 msg_id; /* Message ID */ __u16 num_args; /* Number of input argument words in message */ __u16 response_sz; /* Number of expected output/response words */ __u32 args[HSMP_MAX_MSG_LEN]; /* argument/response buffer */ __u16 sock_ind; /* socket number */ }; enum hsmp_msg_type { HSMP_RSVD = -1, HSMP_SET = 0, HSMP_GET = 1, }; struct hsmp_msg_desc { int num_args; int response_sz; enum hsmp_msg_type type; }; /* * User may use these comments as reference, please find the * supported list of messages and message definition in the * HSMP chapter of respective family/model PPR. * * Not supported messages would return -ENOMSG. */ static const struct hsmp_msg_desc hsmp_msg_desc_table[] = { /* RESERVED */ {0, 0, HSMP_RSVD}, /* * HSMP_TEST, num_args = 1, response_sz = 1 * input: args[0] = xx * output: args[0] = xx + 1 */ {1, 1, HSMP_GET}, /* * HSMP_GET_SMU_VER, num_args = 0, response_sz = 1 * output: args[0] = smu fw ver */ {0, 1, HSMP_GET}, /* * HSMP_GET_PROTO_VER, num_args = 0, response_sz = 1 * output: args[0] = proto version */ {0, 1, HSMP_GET}, /* * HSMP_GET_SOCKET_POWER, num_args = 0, response_sz = 1 * output: args[0] = socket power in mWatts */ {0, 1, HSMP_GET}, /* * HSMP_SET_SOCKET_POWER_LIMIT, num_args = 1, response_sz = 0 * input: args[0] = power limit value in mWatts */ {1, 0, HSMP_SET}, /* * HSMP_GET_SOCKET_POWER_LIMIT, num_args = 0, response_sz = 1 * output: args[0] = socket power limit value in mWatts */ {0, 1, HSMP_GET}, /* * HSMP_GET_SOCKET_POWER_LIMIT_MAX, num_args = 0, response_sz = 1 * output: args[0] = maximuam socket power limit in mWatts */ {0, 1, HSMP_GET}, /* * HSMP_SET_BOOST_LIMIT, num_args = 1, response_sz = 0 * input: args[0] = apic id[31:16] + boost limit value in MHz[15:0] */ {1, 0, HSMP_SET}, /* * HSMP_SET_BOOST_LIMIT_SOCKET, num_args = 1, response_sz = 0 * input: args[0] = boost limit value in MHz */ {1, 0, HSMP_SET}, /* * HSMP_GET_BOOST_LIMIT, num_args = 1, response_sz = 1 * input: args[0] = apic id * output: args[0] = boost limit value in MHz */ {1, 1, HSMP_GET}, /* * HSMP_GET_PROC_HOT, num_args = 0, response_sz = 1 * output: args[0] = proc hot status */ {0, 1, HSMP_GET}, /* * HSMP_SET_XGMI_LINK_WIDTH, num_args = 1, response_sz = 0 * input: args[0] = min link width[15:8] + max link width[7:0] */ {1, 0, HSMP_SET}, /* * HSMP_SET_DF_PSTATE, num_args = 1, response_sz = 0 * input: args[0] = df pstate[7:0] */ {1, 0, HSMP_SET}, /* HSMP_SET_AUTO_DF_PSTATE, num_args = 0, response_sz = 0 */ {0, 0, HSMP_SET}, /* * HSMP_GET_FCLK_MCLK, num_args = 0, response_sz = 2 * output: args[0] = fclk in MHz, args[1] = mclk in MHz */ {0, 2, HSMP_GET}, /* * HSMP_GET_CCLK_THROTTLE_LIMIT, num_args = 0, response_sz = 1 * output: args[0] = core clock in MHz */ {0, 1, HSMP_GET}, /* * HSMP_GET_C0_PERCENT, num_args = 0, response_sz = 1 * output: args[0] = average c0 residency */ {0, 1, HSMP_GET}, /* * HSMP_SET_NBIO_DPM_LEVEL, num_args = 1, response_sz = 0 * input: args[0] = nbioid[23:16] + max dpm level[15:8] + min dpm level[7:0] */ {1, 0, HSMP_SET}, /* * HSMP_GET_NBIO_DPM_LEVEL, num_args = 1, response_sz = 1 * input: args[0] = nbioid[23:16] * output: args[0] = max dpm level[15:8] + min dpm level[7:0] */ {1, 1, HSMP_GET}, /* * HSMP_GET_DDR_BANDWIDTH, num_args = 0, response_sz = 1 * output: args[0] = max bw in Gbps[31:20] + utilised bw in Gbps[19:8] + * bw in percentage[7:0] */ {0, 1, HSMP_GET}, /* * HSMP_GET_TEMP_MONITOR, num_args = 0, response_sz = 1 * output: args[0] = temperature in degree celsius. [15:8] integer part + * [7:5] fractional part */ {0, 1, HSMP_GET}, /* * HSMP_GET_DIMM_TEMP_RANGE, num_args = 1, response_sz = 1 * input: args[0] = DIMM address[7:0] * output: args[0] = refresh rate[3] + temperature range[2:0] */ {1, 1, HSMP_GET}, /* * HSMP_GET_DIMM_POWER, num_args = 1, response_sz = 1 * input: args[0] = DIMM address[7:0] * output: args[0] = DIMM power in mW[31:17] + update rate in ms[16:8] + * DIMM address[7:0] */ {1, 1, HSMP_GET}, /* * HSMP_GET_DIMM_THERMAL, num_args = 1, response_sz = 1 * input: args[0] = DIMM address[7:0] * output: args[0] = temperature in degree celcius[31:21] + update rate in ms[16:8] + * DIMM address[7:0] */ {1, 1, HSMP_GET}, /* * HSMP_GET_SOCKET_FREQ_LIMIT, num_args = 0, response_sz = 1 * output: args[0] = frequency in MHz[31:16] + frequency source[15:0] */ {0, 1, HSMP_GET}, /* * HSMP_GET_CCLK_CORE_LIMIT, num_args = 1, response_sz = 1 * input: args[0] = apic id [31:0] * output: args[0] = frequency in MHz[31:0] */ {1, 1, HSMP_GET}, /* * HSMP_GET_RAILS_SVI, num_args = 0, response_sz = 1 * output: args[0] = power in mW[31:0] */ {0, 1, HSMP_GET}, /* * HSMP_GET_SOCKET_FMAX_FMIN, num_args = 0, response_sz = 1 * output: args[0] = fmax in MHz[31:16] + fmin in MHz[15:0] */ {0, 1, HSMP_GET}, /* * HSMP_GET_IOLINK_BANDWITH, num_args = 1, response_sz = 1 * input: args[0] = link id[15:8] + bw type[2:0] * output: args[0] = io bandwidth in Mbps[31:0] */ {1, 1, HSMP_GET}, /* * HSMP_GET_XGMI_BANDWITH, num_args = 1, response_sz = 1 * input: args[0] = link id[15:8] + bw type[2:0] * output: args[0] = xgmi bandwidth in Mbps[31:0] */ {1, 1, HSMP_GET}, /* * HSMP_SET_GMI3_WIDTH, num_args = 1, response_sz = 0 * input: args[0] = min link width[15:8] + max link width[7:0] */ {1, 0, HSMP_SET}, /* * HSMP_SET_PCI_RATE, num_args = 1, response_sz = 1 * input: args[0] = link rate control value * output: args[0] = previous link rate control value */ {1, 1, HSMP_SET}, /* * HSMP_SET_POWER_MODE, num_args = 1, response_sz = 0 * input: args[0] = power efficiency mode[2:0] */ {1, 0, HSMP_SET}, /* * HSMP_SET_PSTATE_MAX_MIN, num_args = 1, response_sz = 0 * input: args[0] = min df pstate[15:8] + max df pstate[7:0] */ {1, 0, HSMP_SET}, }; /* Reset to default packing */ #pragma pack() /* Define unique ioctl command for hsmp msgs using generic _IOWR */ #define HSMP_BASE_IOCTL_NR 0xF8 #define HSMP_IOCTL_CMD _IOWR(HSMP_BASE_IOCTL_NR, 0, struct hsmp_message) #endif /*_ASM_X86_AMD_HSMP_H_*/ asm/ptrace-abi.h000064400000003765151027430560007522 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_PTRACE_ABI_H #define _ASM_X86_PTRACE_ABI_H #ifdef __i386__ #define EBX 0 #define ECX 1 #define EDX 2 #define ESI 3 #define EDI 4 #define EBP 5 #define EAX 6 #define DS 7 #define ES 8 #define FS 9 #define GS 10 #define ORIG_EAX 11 #define EIP 12 #define CS 13 #define EFL 14 #define UESP 15 #define SS 16 #define FRAME_SIZE 17 #else /* __i386__ */ #if defined(__ASSEMBLY__) || defined(__FRAME_OFFSETS) /* * C ABI says these regs are callee-preserved. They aren't saved on kernel entry * unless syscall needs a complete, fully filled "struct pt_regs". */ #define R15 0 #define R14 8 #define R13 16 #define R12 24 #define RBP 32 #define RBX 40 /* These regs are callee-clobbered. Always saved on kernel entry. */ #define R11 48 #define R10 56 #define R9 64 #define R8 72 #define RAX 80 #define RCX 88 #define RDX 96 #define RSI 104 #define RDI 112 /* * On syscall entry, this is syscall#. On CPU exception, this is error code. * On hw interrupt, it's IRQ number: */ #define ORIG_RAX 120 /* Return frame for iretq */ #define RIP 128 #define CS 136 #define EFLAGS 144 #define RSP 152 #define SS 160 #endif /* __ASSEMBLY__ */ /* top of stack page */ #define FRAME_SIZE 168 #endif /* !__i386__ */ /* Arbitrarily choose the same ptrace numbers as used by the Sparc code. */ #define PTRACE_GETREGS 12 #define PTRACE_SETREGS 13 #define PTRACE_GETFPREGS 14 #define PTRACE_SETFPREGS 15 #define PTRACE_GETFPXREGS 18 #define PTRACE_SETFPXREGS 19 #define PTRACE_OLDSETOPTIONS 21 /* only useful for access 32bit programs / kernels */ #define PTRACE_GET_THREAD_AREA 25 #define PTRACE_SET_THREAD_AREA 26 #ifdef __x86_64__ # define PTRACE_ARCH_PRCTL 30 #endif #define PTRACE_SYSEMU 31 #define PTRACE_SYSEMU_SINGLESTEP 32 #define PTRACE_SINGLEBLOCK 33 /* resume execution until next branch */ #ifndef __ASSEMBLY__ #include #endif #endif /* _ASM_X86_PTRACE_ABI_H */ asm/ioctls.h000064400000000040151027430560006767 0ustar00#include asm/posix_types_32.h000064400000001375151027430560010400 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_POSIX_TYPES_32_H #define _ASM_X86_POSIX_TYPES_32_H /* * This file is generally used by user-level software, so you need to * be a little careful about namespace pollution etc. Also, we cannot * assume GCC is being used. */ typedef unsigned short __kernel_mode_t; #define __kernel_mode_t __kernel_mode_t typedef unsigned short __kernel_ipc_pid_t; #define __kernel_ipc_pid_t __kernel_ipc_pid_t typedef unsigned short __kernel_uid_t; typedef unsigned short __kernel_gid_t; #define __kernel_uid_t __kernel_uid_t typedef unsigned short __kernel_old_dev_t; #define __kernel_old_dev_t __kernel_old_dev_t #include #endif /* _ASM_X86_POSIX_TYPES_32_H */ asm/param.h000064400000000037151027430560006600 0ustar00#include asm/unistd.h000064400000000547151027430560007014 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_UNISTD_H #define _ASM_X86_UNISTD_H /* x32 syscall flag bit */ #define __X32_SYSCALL_BIT 0x40000000 # ifdef __i386__ # include # elif defined(__ILP32__) # include # else # include # endif #endif /* _ASM_X86_UNISTD_H */ asm/setup.h000064400000000006151027430560006634 0ustar00/* */ asm/bpf_perf_event.h000064400000000050151027430560010457 0ustar00#include asm/bitsperlong.h000064400000000501151027430560010024 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __ASM_X86_BITSPERLONG_H #define __ASM_X86_BITSPERLONG_H #if defined(__x86_64__) && !defined(__ILP32__) # define __BITS_PER_LONG 64 #else # define __BITS_PER_LONG 32 #endif #include #endif /* __ASM_X86_BITSPERLONG_H */ asm/types.h000064400000000230151027430560006637 0ustar00/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _ASM_X86_TYPES_H #define _ASM_X86_TYPES_H #include #endif /* _ASM_X86_TYPES_H */ asm/auxvec.h000064400000001152151027430560006772 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_AUXVEC_H #define _ASM_X86_AUXVEC_H /* * Architecture-neutral AT_ values in 0-17, leave some room * for more of them, start the x86-specific ones at 32. */ #ifdef __i386__ #define AT_SYSINFO 32 #endif #define AT_SYSINFO_EHDR 33 /* entries in ARCH_DLINFO: */ #if defined(CONFIG_IA32_EMULATION) || !defined(CONFIG_X86_64) # define AT_VECTOR_SIZE_ARCH 3 # define ORIG_AT_VECTOR_SIZE_ARCH 2 #else /* else it's non-compat x86-64 */ # define AT_VECTOR_SIZE_ARCH 2 # define ORIG_AT_VECTOR_SIZE_ARCH 1 #endif #endif /* _ASM_X86_AUXVEC_H */ asm/mman.h000064400000001752151027430560006435 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_MMAN_H #define _ASM_X86_MMAN_H #define MAP_32BIT 0x40 /* only give out 32bit addresses */ #ifdef CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS /* * Take the 4 protection key bits out of the vma->vm_flags * value and turn them in to the bits that we can put in * to a pte. * * Only override these if Protection Keys are available * (which is only on 64-bit). */ #define arch_vm_get_page_prot(vm_flags) __pgprot( \ ((vm_flags) & VM_PKEY_BIT0 ? _PAGE_PKEY_BIT0 : 0) | \ ((vm_flags) & VM_PKEY_BIT1 ? _PAGE_PKEY_BIT1 : 0) | \ ((vm_flags) & VM_PKEY_BIT2 ? _PAGE_PKEY_BIT2 : 0) | \ ((vm_flags) & VM_PKEY_BIT3 ? _PAGE_PKEY_BIT3 : 0)) #define arch_calc_vm_prot_bits(prot, key) ( \ ((key) & 0x1 ? VM_PKEY_BIT0 : 0) | \ ((key) & 0x2 ? VM_PKEY_BIT1 : 0) | \ ((key) & 0x4 ? VM_PKEY_BIT2 : 0) | \ ((key) & 0x8 ? VM_PKEY_BIT3 : 0)) #endif #include #endif /* _ASM_X86_MMAN_H */ asm/kvm_perf.h000064400000000604151027430560007311 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_KVM_PERF_H #define _ASM_X86_KVM_PERF_H #include #include #include #define DECODE_STR_LEN 20 #define VCPU_ID "vcpu_id" #define KVM_ENTRY_TRACE "kvm:kvm_entry" #define KVM_EXIT_TRACE "kvm:kvm_exit" #define KVM_EXIT_REASON "exit_reason" #endif /* _ASM_X86_KVM_PERF_H */ asm/unistd_x32.h000064400000040043151027430560007503 0ustar00#ifndef _ASM_X86_UNISTD_X32_H #define _ASM_X86_UNISTD_X32_H 1 #define __NR_read (__X32_SYSCALL_BIT + 0) #define __NR_write (__X32_SYSCALL_BIT + 1) #define __NR_open (__X32_SYSCALL_BIT + 2) #define __NR_close (__X32_SYSCALL_BIT + 3) #define __NR_stat (__X32_SYSCALL_BIT + 4) #define __NR_fstat (__X32_SYSCALL_BIT + 5) #define __NR_lstat (__X32_SYSCALL_BIT + 6) #define __NR_poll (__X32_SYSCALL_BIT + 7) #define __NR_lseek (__X32_SYSCALL_BIT + 8) #define __NR_mmap (__X32_SYSCALL_BIT + 9) #define __NR_mprotect (__X32_SYSCALL_BIT + 10) #define __NR_munmap (__X32_SYSCALL_BIT + 11) #define __NR_brk (__X32_SYSCALL_BIT + 12) #define __NR_rt_sigprocmask (__X32_SYSCALL_BIT + 14) #define __NR_pread64 (__X32_SYSCALL_BIT + 17) #define __NR_pwrite64 (__X32_SYSCALL_BIT + 18) #define __NR_access (__X32_SYSCALL_BIT + 21) #define __NR_pipe (__X32_SYSCALL_BIT + 22) #define __NR_select (__X32_SYSCALL_BIT + 23) #define __NR_sched_yield (__X32_SYSCALL_BIT + 24) #define __NR_mremap (__X32_SYSCALL_BIT + 25) #define __NR_msync (__X32_SYSCALL_BIT + 26) #define __NR_mincore (__X32_SYSCALL_BIT + 27) #define __NR_madvise (__X32_SYSCALL_BIT + 28) #define __NR_shmget (__X32_SYSCALL_BIT + 29) #define __NR_shmat (__X32_SYSCALL_BIT + 30) #define __NR_shmctl (__X32_SYSCALL_BIT + 31) #define __NR_dup (__X32_SYSCALL_BIT + 32) #define __NR_dup2 (__X32_SYSCALL_BIT + 33) #define __NR_pause (__X32_SYSCALL_BIT + 34) #define __NR_nanosleep (__X32_SYSCALL_BIT + 35) #define __NR_getitimer (__X32_SYSCALL_BIT + 36) #define __NR_alarm (__X32_SYSCALL_BIT + 37) #define __NR_setitimer (__X32_SYSCALL_BIT + 38) #define __NR_getpid (__X32_SYSCALL_BIT + 39) #define __NR_sendfile (__X32_SYSCALL_BIT + 40) #define __NR_socket (__X32_SYSCALL_BIT + 41) #define __NR_connect (__X32_SYSCALL_BIT + 42) #define __NR_accept (__X32_SYSCALL_BIT + 43) #define __NR_sendto (__X32_SYSCALL_BIT + 44) #define __NR_shutdown (__X32_SYSCALL_BIT + 48) #define __NR_bind (__X32_SYSCALL_BIT + 49) #define __NR_listen (__X32_SYSCALL_BIT + 50) #define __NR_getsockname (__X32_SYSCALL_BIT + 51) #define __NR_getpeername (__X32_SYSCALL_BIT + 52) #define __NR_socketpair (__X32_SYSCALL_BIT + 53) #define __NR_clone (__X32_SYSCALL_BIT + 56) #define __NR_fork (__X32_SYSCALL_BIT + 57) #define __NR_vfork (__X32_SYSCALL_BIT + 58) #define __NR_exit (__X32_SYSCALL_BIT + 60) #define __NR_wait4 (__X32_SYSCALL_BIT + 61) #define __NR_kill (__X32_SYSCALL_BIT + 62) #define __NR_uname (__X32_SYSCALL_BIT + 63) #define __NR_semget (__X32_SYSCALL_BIT + 64) #define __NR_semop (__X32_SYSCALL_BIT + 65) #define __NR_semctl (__X32_SYSCALL_BIT + 66) #define __NR_shmdt (__X32_SYSCALL_BIT + 67) #define __NR_msgget (__X32_SYSCALL_BIT + 68) #define __NR_msgsnd (__X32_SYSCALL_BIT + 69) #define __NR_msgrcv (__X32_SYSCALL_BIT + 70) #define __NR_msgctl (__X32_SYSCALL_BIT + 71) #define __NR_fcntl (__X32_SYSCALL_BIT + 72) #define __NR_flock (__X32_SYSCALL_BIT + 73) #define __NR_fsync (__X32_SYSCALL_BIT + 74) #define __NR_fdatasync (__X32_SYSCALL_BIT + 75) #define __NR_truncate (__X32_SYSCALL_BIT + 76) #define __NR_ftruncate (__X32_SYSCALL_BIT + 77) #define __NR_getdents (__X32_SYSCALL_BIT + 78) #define __NR_getcwd (__X32_SYSCALL_BIT + 79) #define __NR_chdir (__X32_SYSCALL_BIT + 80) #define __NR_fchdir (__X32_SYSCALL_BIT + 81) #define __NR_rename (__X32_SYSCALL_BIT + 82) #define __NR_mkdir (__X32_SYSCALL_BIT + 83) #define __NR_rmdir (__X32_SYSCALL_BIT + 84) #define __NR_creat (__X32_SYSCALL_BIT + 85) #define __NR_link (__X32_SYSCALL_BIT + 86) #define __NR_unlink (__X32_SYSCALL_BIT + 87) #define __NR_symlink (__X32_SYSCALL_BIT + 88) #define __NR_readlink (__X32_SYSCALL_BIT + 89) #define __NR_chmod (__X32_SYSCALL_BIT + 90) #define __NR_fchmod (__X32_SYSCALL_BIT + 91) #define __NR_chown (__X32_SYSCALL_BIT + 92) #define __NR_fchown (__X32_SYSCALL_BIT + 93) #define __NR_lchown (__X32_SYSCALL_BIT + 94) #define __NR_umask (__X32_SYSCALL_BIT + 95) #define __NR_gettimeofday (__X32_SYSCALL_BIT + 96) #define __NR_getrlimit (__X32_SYSCALL_BIT + 97) #define __NR_getrusage (__X32_SYSCALL_BIT + 98) #define __NR_sysinfo (__X32_SYSCALL_BIT + 99) #define __NR_times (__X32_SYSCALL_BIT + 100) #define __NR_getuid (__X32_SYSCALL_BIT + 102) #define __NR_syslog (__X32_SYSCALL_BIT + 103) #define __NR_getgid (__X32_SYSCALL_BIT + 104) #define __NR_setuid (__X32_SYSCALL_BIT + 105) #define __NR_setgid (__X32_SYSCALL_BIT + 106) #define __NR_geteuid (__X32_SYSCALL_BIT + 107) #define __NR_getegid (__X32_SYSCALL_BIT + 108) #define __NR_setpgid (__X32_SYSCALL_BIT + 109) #define __NR_getppid (__X32_SYSCALL_BIT + 110) #define __NR_getpgrp (__X32_SYSCALL_BIT + 111) #define __NR_setsid (__X32_SYSCALL_BIT + 112) #define __NR_setreuid (__X32_SYSCALL_BIT + 113) #define __NR_setregid (__X32_SYSCALL_BIT + 114) #define __NR_getgroups (__X32_SYSCALL_BIT + 115) #define __NR_setgroups (__X32_SYSCALL_BIT + 116) #define __NR_setresuid (__X32_SYSCALL_BIT + 117) #define __NR_getresuid (__X32_SYSCALL_BIT + 118) #define __NR_setresgid (__X32_SYSCALL_BIT + 119) #define __NR_getresgid (__X32_SYSCALL_BIT + 120) #define __NR_getpgid (__X32_SYSCALL_BIT + 121) #define __NR_setfsuid (__X32_SYSCALL_BIT + 122) #define __NR_setfsgid (__X32_SYSCALL_BIT + 123) #define __NR_getsid (__X32_SYSCALL_BIT + 124) #define __NR_capget (__X32_SYSCALL_BIT + 125) #define __NR_capset (__X32_SYSCALL_BIT + 126) #define __NR_rt_sigsuspend (__X32_SYSCALL_BIT + 130) #define __NR_utime (__X32_SYSCALL_BIT + 132) #define __NR_mknod (__X32_SYSCALL_BIT + 133) #define __NR_personality (__X32_SYSCALL_BIT + 135) #define __NR_ustat (__X32_SYSCALL_BIT + 136) #define __NR_statfs (__X32_SYSCALL_BIT + 137) #define __NR_fstatfs (__X32_SYSCALL_BIT + 138) #define __NR_sysfs (__X32_SYSCALL_BIT + 139) #define __NR_getpriority (__X32_SYSCALL_BIT + 140) #define __NR_setpriority (__X32_SYSCALL_BIT + 141) #define __NR_sched_setparam (__X32_SYSCALL_BIT + 142) #define __NR_sched_getparam (__X32_SYSCALL_BIT + 143) #define __NR_sched_setscheduler (__X32_SYSCALL_BIT + 144) #define __NR_sched_getscheduler (__X32_SYSCALL_BIT + 145) #define __NR_sched_get_priority_max (__X32_SYSCALL_BIT + 146) #define __NR_sched_get_priority_min (__X32_SYSCALL_BIT + 147) #define __NR_sched_rr_get_interval (__X32_SYSCALL_BIT + 148) #define __NR_mlock (__X32_SYSCALL_BIT + 149) #define __NR_munlock (__X32_SYSCALL_BIT + 150) #define __NR_mlockall (__X32_SYSCALL_BIT + 151) #define __NR_munlockall (__X32_SYSCALL_BIT + 152) #define __NR_vhangup (__X32_SYSCALL_BIT + 153) #define __NR_modify_ldt (__X32_SYSCALL_BIT + 154) #define __NR_pivot_root (__X32_SYSCALL_BIT + 155) #define __NR_prctl (__X32_SYSCALL_BIT + 157) #define __NR_arch_prctl (__X32_SYSCALL_BIT + 158) #define __NR_adjtimex (__X32_SYSCALL_BIT + 159) #define __NR_setrlimit (__X32_SYSCALL_BIT + 160) #define __NR_chroot (__X32_SYSCALL_BIT + 161) #define __NR_sync (__X32_SYSCALL_BIT + 162) #define __NR_acct (__X32_SYSCALL_BIT + 163) #define __NR_settimeofday (__X32_SYSCALL_BIT + 164) #define __NR_mount (__X32_SYSCALL_BIT + 165) #define __NR_umount2 (__X32_SYSCALL_BIT + 166) #define __NR_swapon (__X32_SYSCALL_BIT + 167) #define __NR_swapoff (__X32_SYSCALL_BIT + 168) #define __NR_reboot (__X32_SYSCALL_BIT + 169) #define __NR_sethostname (__X32_SYSCALL_BIT + 170) #define __NR_setdomainname (__X32_SYSCALL_BIT + 171) #define __NR_iopl (__X32_SYSCALL_BIT + 172) #define __NR_ioperm (__X32_SYSCALL_BIT + 173) #define __NR_init_module (__X32_SYSCALL_BIT + 175) #define __NR_delete_module (__X32_SYSCALL_BIT + 176) #define __NR_quotactl (__X32_SYSCALL_BIT + 179) #define __NR_getpmsg (__X32_SYSCALL_BIT + 181) #define __NR_putpmsg (__X32_SYSCALL_BIT + 182) #define __NR_afs_syscall (__X32_SYSCALL_BIT + 183) #define __NR_tuxcall (__X32_SYSCALL_BIT + 184) #define __NR_security (__X32_SYSCALL_BIT + 185) #define __NR_gettid (__X32_SYSCALL_BIT + 186) #define __NR_readahead (__X32_SYSCALL_BIT + 187) #define __NR_setxattr (__X32_SYSCALL_BIT + 188) #define __NR_lsetxattr (__X32_SYSCALL_BIT + 189) #define __NR_fsetxattr (__X32_SYSCALL_BIT + 190) #define __NR_getxattr (__X32_SYSCALL_BIT + 191) #define __NR_lgetxattr (__X32_SYSCALL_BIT + 192) #define __NR_fgetxattr (__X32_SYSCALL_BIT + 193) #define __NR_listxattr (__X32_SYSCALL_BIT + 194) #define __NR_llistxattr (__X32_SYSCALL_BIT + 195) #define __NR_flistxattr (__X32_SYSCALL_BIT + 196) #define __NR_removexattr (__X32_SYSCALL_BIT + 197) #define __NR_lremovexattr (__X32_SYSCALL_BIT + 198) #define __NR_fremovexattr (__X32_SYSCALL_BIT + 199) #define __NR_tkill (__X32_SYSCALL_BIT + 200) #define __NR_time (__X32_SYSCALL_BIT + 201) #define __NR_futex (__X32_SYSCALL_BIT + 202) #define __NR_sched_setaffinity (__X32_SYSCALL_BIT + 203) #define __NR_sched_getaffinity (__X32_SYSCALL_BIT + 204) #define __NR_io_destroy (__X32_SYSCALL_BIT + 207) #define __NR_io_getevents (__X32_SYSCALL_BIT + 208) #define __NR_io_cancel (__X32_SYSCALL_BIT + 210) #define __NR_lookup_dcookie (__X32_SYSCALL_BIT + 212) #define __NR_epoll_create (__X32_SYSCALL_BIT + 213) #define __NR_remap_file_pages (__X32_SYSCALL_BIT + 216) #define __NR_getdents64 (__X32_SYSCALL_BIT + 217) #define __NR_set_tid_address (__X32_SYSCALL_BIT + 218) #define __NR_restart_syscall (__X32_SYSCALL_BIT + 219) #define __NR_semtimedop (__X32_SYSCALL_BIT + 220) #define __NR_fadvise64 (__X32_SYSCALL_BIT + 221) #define __NR_timer_settime (__X32_SYSCALL_BIT + 223) #define __NR_timer_gettime (__X32_SYSCALL_BIT + 224) #define __NR_timer_getoverrun (__X32_SYSCALL_BIT + 225) #define __NR_timer_delete (__X32_SYSCALL_BIT + 226) #define __NR_clock_settime (__X32_SYSCALL_BIT + 227) #define __NR_clock_gettime (__X32_SYSCALL_BIT + 228) #define __NR_clock_getres (__X32_SYSCALL_BIT + 229) #define __NR_clock_nanosleep (__X32_SYSCALL_BIT + 230) #define __NR_exit_group (__X32_SYSCALL_BIT + 231) #define __NR_epoll_wait (__X32_SYSCALL_BIT + 232) #define __NR_epoll_ctl (__X32_SYSCALL_BIT + 233) #define __NR_tgkill (__X32_SYSCALL_BIT + 234) #define __NR_utimes (__X32_SYSCALL_BIT + 235) #define __NR_mbind (__X32_SYSCALL_BIT + 237) #define __NR_set_mempolicy (__X32_SYSCALL_BIT + 238) #define __NR_get_mempolicy (__X32_SYSCALL_BIT + 239) #define __NR_mq_open (__X32_SYSCALL_BIT + 240) #define __NR_mq_unlink (__X32_SYSCALL_BIT + 241) #define __NR_mq_timedsend (__X32_SYSCALL_BIT + 242) #define __NR_mq_timedreceive (__X32_SYSCALL_BIT + 243) #define __NR_mq_getsetattr (__X32_SYSCALL_BIT + 245) #define __NR_add_key (__X32_SYSCALL_BIT + 248) #define __NR_request_key (__X32_SYSCALL_BIT + 249) #define __NR_keyctl (__X32_SYSCALL_BIT + 250) #define __NR_ioprio_set (__X32_SYSCALL_BIT + 251) #define __NR_ioprio_get (__X32_SYSCALL_BIT + 252) #define __NR_inotify_init (__X32_SYSCALL_BIT + 253) #define __NR_inotify_add_watch (__X32_SYSCALL_BIT + 254) #define __NR_inotify_rm_watch (__X32_SYSCALL_BIT + 255) #define __NR_migrate_pages (__X32_SYSCALL_BIT + 256) #define __NR_openat (__X32_SYSCALL_BIT + 257) #define __NR_mkdirat (__X32_SYSCALL_BIT + 258) #define __NR_mknodat (__X32_SYSCALL_BIT + 259) #define __NR_fchownat (__X32_SYSCALL_BIT + 260) #define __NR_futimesat (__X32_SYSCALL_BIT + 261) #define __NR_newfstatat (__X32_SYSCALL_BIT + 262) #define __NR_unlinkat (__X32_SYSCALL_BIT + 263) #define __NR_renameat (__X32_SYSCALL_BIT + 264) #define __NR_linkat (__X32_SYSCALL_BIT + 265) #define __NR_symlinkat (__X32_SYSCALL_BIT + 266) #define __NR_readlinkat (__X32_SYSCALL_BIT + 267) #define __NR_fchmodat (__X32_SYSCALL_BIT + 268) #define __NR_faccessat (__X32_SYSCALL_BIT + 269) #define __NR_pselect6 (__X32_SYSCALL_BIT + 270) #define __NR_ppoll (__X32_SYSCALL_BIT + 271) #define __NR_unshare (__X32_SYSCALL_BIT + 272) #define __NR_splice (__X32_SYSCALL_BIT + 275) #define __NR_tee (__X32_SYSCALL_BIT + 276) #define __NR_sync_file_range (__X32_SYSCALL_BIT + 277) #define __NR_utimensat (__X32_SYSCALL_BIT + 280) #define __NR_epoll_pwait (__X32_SYSCALL_BIT + 281) #define __NR_signalfd (__X32_SYSCALL_BIT + 282) #define __NR_timerfd_create (__X32_SYSCALL_BIT + 283) #define __NR_eventfd (__X32_SYSCALL_BIT + 284) #define __NR_fallocate (__X32_SYSCALL_BIT + 285) #define __NR_timerfd_settime (__X32_SYSCALL_BIT + 286) #define __NR_timerfd_gettime (__X32_SYSCALL_BIT + 287) #define __NR_accept4 (__X32_SYSCALL_BIT + 288) #define __NR_signalfd4 (__X32_SYSCALL_BIT + 289) #define __NR_eventfd2 (__X32_SYSCALL_BIT + 290) #define __NR_epoll_create1 (__X32_SYSCALL_BIT + 291) #define __NR_dup3 (__X32_SYSCALL_BIT + 292) #define __NR_pipe2 (__X32_SYSCALL_BIT + 293) #define __NR_inotify_init1 (__X32_SYSCALL_BIT + 294) #define __NR_perf_event_open (__X32_SYSCALL_BIT + 298) #define __NR_fanotify_init (__X32_SYSCALL_BIT + 300) #define __NR_fanotify_mark (__X32_SYSCALL_BIT + 301) #define __NR_prlimit64 (__X32_SYSCALL_BIT + 302) #define __NR_name_to_handle_at (__X32_SYSCALL_BIT + 303) #define __NR_open_by_handle_at (__X32_SYSCALL_BIT + 304) #define __NR_clock_adjtime (__X32_SYSCALL_BIT + 305) #define __NR_syncfs (__X32_SYSCALL_BIT + 306) #define __NR_setns (__X32_SYSCALL_BIT + 308) #define __NR_getcpu (__X32_SYSCALL_BIT + 309) #define __NR_kcmp (__X32_SYSCALL_BIT + 312) #define __NR_finit_module (__X32_SYSCALL_BIT + 313) #define __NR_sched_setattr (__X32_SYSCALL_BIT + 314) #define __NR_sched_getattr (__X32_SYSCALL_BIT + 315) #define __NR_renameat2 (__X32_SYSCALL_BIT + 316) #define __NR_seccomp (__X32_SYSCALL_BIT + 317) #define __NR_getrandom (__X32_SYSCALL_BIT + 318) #define __NR_memfd_create (__X32_SYSCALL_BIT + 319) #define __NR_kexec_file_load (__X32_SYSCALL_BIT + 320) #define __NR_bpf (__X32_SYSCALL_BIT + 321) #define __NR_userfaultfd (__X32_SYSCALL_BIT + 323) #define __NR_membarrier (__X32_SYSCALL_BIT + 324) #define __NR_mlock2 (__X32_SYSCALL_BIT + 325) #define __NR_copy_file_range (__X32_SYSCALL_BIT + 326) #define __NR_pkey_mprotect (__X32_SYSCALL_BIT + 329) #define __NR_pkey_alloc (__X32_SYSCALL_BIT + 330) #define __NR_pkey_free (__X32_SYSCALL_BIT + 331) #define __NR_statx (__X32_SYSCALL_BIT + 332) #define __NR_io_pgetevents (__X32_SYSCALL_BIT + 333) #define __NR_rseq (__X32_SYSCALL_BIT + 334) #define __NR_pidfd_send_signal (__X32_SYSCALL_BIT + 424) #define __NR_io_uring_setup (__X32_SYSCALL_BIT + 425) #define __NR_io_uring_enter (__X32_SYSCALL_BIT + 426) #define __NR_io_uring_register (__X32_SYSCALL_BIT + 427) #define __NR_open_tree (__X32_SYSCALL_BIT + 428) #define __NR_move_mount (__X32_SYSCALL_BIT + 429) #define __NR_fsopen (__X32_SYSCALL_BIT + 430) #define __NR_fsconfig (__X32_SYSCALL_BIT + 431) #define __NR_fsmount (__X32_SYSCALL_BIT + 432) #define __NR_fspick (__X32_SYSCALL_BIT + 433) #define __NR_close_range (__X32_SYSCALL_BIT + 436) #define __NR_openat2 (__X32_SYSCALL_BIT + 437) #define __NR_faccessat2 (__X32_SYSCALL_BIT + 439) #define __NR_rt_sigaction (__X32_SYSCALL_BIT + 512) #define __NR_rt_sigreturn (__X32_SYSCALL_BIT + 513) #define __NR_ioctl (__X32_SYSCALL_BIT + 514) #define __NR_readv (__X32_SYSCALL_BIT + 515) #define __NR_writev (__X32_SYSCALL_BIT + 516) #define __NR_recvfrom (__X32_SYSCALL_BIT + 517) #define __NR_sendmsg (__X32_SYSCALL_BIT + 518) #define __NR_recvmsg (__X32_SYSCALL_BIT + 519) #define __NR_execve (__X32_SYSCALL_BIT + 520) #define __NR_ptrace (__X32_SYSCALL_BIT + 521) #define __NR_rt_sigpending (__X32_SYSCALL_BIT + 522) #define __NR_rt_sigtimedwait (__X32_SYSCALL_BIT + 523) #define __NR_rt_sigqueueinfo (__X32_SYSCALL_BIT + 524) #define __NR_sigaltstack (__X32_SYSCALL_BIT + 525) #define __NR_timer_create (__X32_SYSCALL_BIT + 526) #define __NR_mq_notify (__X32_SYSCALL_BIT + 527) #define __NR_kexec_load (__X32_SYSCALL_BIT + 528) #define __NR_waitid (__X32_SYSCALL_BIT + 529) #define __NR_set_robust_list (__X32_SYSCALL_BIT + 530) #define __NR_get_robust_list (__X32_SYSCALL_BIT + 531) #define __NR_vmsplice (__X32_SYSCALL_BIT + 532) #define __NR_move_pages (__X32_SYSCALL_BIT + 533) #define __NR_preadv (__X32_SYSCALL_BIT + 534) #define __NR_pwritev (__X32_SYSCALL_BIT + 535) #define __NR_rt_tgsigqueueinfo (__X32_SYSCALL_BIT + 536) #define __NR_recvmmsg (__X32_SYSCALL_BIT + 537) #define __NR_sendmmsg (__X32_SYSCALL_BIT + 538) #define __NR_process_vm_readv (__X32_SYSCALL_BIT + 539) #define __NR_process_vm_writev (__X32_SYSCALL_BIT + 540) #define __NR_setsockopt (__X32_SYSCALL_BIT + 541) #define __NR_getsockopt (__X32_SYSCALL_BIT + 542) #define __NR_io_setup (__X32_SYSCALL_BIT + 543) #define __NR_io_submit (__X32_SYSCALL_BIT + 544) #define __NR_execveat (__X32_SYSCALL_BIT + 545) #define __NR_preadv2 (__X32_SYSCALL_BIT + 546) #define __NR_pwritev2 (__X32_SYSCALL_BIT + 547) #endif /* _ASM_X86_UNISTD_X32_H */ asm/unistd_64.h000064400000022144151027430560007322 0ustar00#ifndef _ASM_X86_UNISTD_64_H #define _ASM_X86_UNISTD_64_H 1 #define __NR_read 0 #define __NR_write 1 #define __NR_open 2 #define __NR_close 3 #define __NR_stat 4 #define __NR_fstat 5 #define __NR_lstat 6 #define __NR_poll 7 #define __NR_lseek 8 #define __NR_mmap 9 #define __NR_mprotect 10 #define __NR_munmap 11 #define __NR_brk 12 #define __NR_rt_sigaction 13 #define __NR_rt_sigprocmask 14 #define __NR_rt_sigreturn 15 #define __NR_ioctl 16 #define __NR_pread64 17 #define __NR_pwrite64 18 #define __NR_readv 19 #define __NR_writev 20 #define __NR_access 21 #define __NR_pipe 22 #define __NR_select 23 #define __NR_sched_yield 24 #define __NR_mremap 25 #define __NR_msync 26 #define __NR_mincore 27 #define __NR_madvise 28 #define __NR_shmget 29 #define __NR_shmat 30 #define __NR_shmctl 31 #define __NR_dup 32 #define __NR_dup2 33 #define __NR_pause 34 #define __NR_nanosleep 35 #define __NR_getitimer 36 #define __NR_alarm 37 #define __NR_setitimer 38 #define __NR_getpid 39 #define __NR_sendfile 40 #define __NR_socket 41 #define __NR_connect 42 #define __NR_accept 43 #define __NR_sendto 44 #define __NR_recvfrom 45 #define __NR_sendmsg 46 #define __NR_recvmsg 47 #define __NR_shutdown 48 #define __NR_bind 49 #define __NR_listen 50 #define __NR_getsockname 51 #define __NR_getpeername 52 #define __NR_socketpair 53 #define __NR_setsockopt 54 #define __NR_getsockopt 55 #define __NR_clone 56 #define __NR_fork 57 #define __NR_vfork 58 #define __NR_execve 59 #define __NR_exit 60 #define __NR_wait4 61 #define __NR_kill 62 #define __NR_uname 63 #define __NR_semget 64 #define __NR_semop 65 #define __NR_semctl 66 #define __NR_shmdt 67 #define __NR_msgget 68 #define __NR_msgsnd 69 #define __NR_msgrcv 70 #define __NR_msgctl 71 #define __NR_fcntl 72 #define __NR_flock 73 #define __NR_fsync 74 #define __NR_fdatasync 75 #define __NR_truncate 76 #define __NR_ftruncate 77 #define __NR_getdents 78 #define __NR_getcwd 79 #define __NR_chdir 80 #define __NR_fchdir 81 #define __NR_rename 82 #define __NR_mkdir 83 #define __NR_rmdir 84 #define __NR_creat 85 #define __NR_link 86 #define __NR_unlink 87 #define __NR_symlink 88 #define __NR_readlink 89 #define __NR_chmod 90 #define __NR_fchmod 91 #define __NR_chown 92 #define __NR_fchown 93 #define __NR_lchown 94 #define __NR_umask 95 #define __NR_gettimeofday 96 #define __NR_getrlimit 97 #define __NR_getrusage 98 #define __NR_sysinfo 99 #define __NR_times 100 #define __NR_ptrace 101 #define __NR_getuid 102 #define __NR_syslog 103 #define __NR_getgid 104 #define __NR_setuid 105 #define __NR_setgid 106 #define __NR_geteuid 107 #define __NR_getegid 108 #define __NR_setpgid 109 #define __NR_getppid 110 #define __NR_getpgrp 111 #define __NR_setsid 112 #define __NR_setreuid 113 #define __NR_setregid 114 #define __NR_getgroups 115 #define __NR_setgroups 116 #define __NR_setresuid 117 #define __NR_getresuid 118 #define __NR_setresgid 119 #define __NR_getresgid 120 #define __NR_getpgid 121 #define __NR_setfsuid 122 #define __NR_setfsgid 123 #define __NR_getsid 124 #define __NR_capget 125 #define __NR_capset 126 #define __NR_rt_sigpending 127 #define __NR_rt_sigtimedwait 128 #define __NR_rt_sigqueueinfo 129 #define __NR_rt_sigsuspend 130 #define __NR_sigaltstack 131 #define __NR_utime 132 #define __NR_mknod 133 #define __NR_uselib 134 #define __NR_personality 135 #define __NR_ustat 136 #define __NR_statfs 137 #define __NR_fstatfs 138 #define __NR_sysfs 139 #define __NR_getpriority 140 #define __NR_setpriority 141 #define __NR_sched_setparam 142 #define __NR_sched_getparam 143 #define __NR_sched_setscheduler 144 #define __NR_sched_getscheduler 145 #define __NR_sched_get_priority_max 146 #define __NR_sched_get_priority_min 147 #define __NR_sched_rr_get_interval 148 #define __NR_mlock 149 #define __NR_munlock 150 #define __NR_mlockall 151 #define __NR_munlockall 152 #define __NR_vhangup 153 #define __NR_modify_ldt 154 #define __NR_pivot_root 155 #define __NR__sysctl 156 #define __NR_prctl 157 #define __NR_arch_prctl 158 #define __NR_adjtimex 159 #define __NR_setrlimit 160 #define __NR_chroot 161 #define __NR_sync 162 #define __NR_acct 163 #define __NR_settimeofday 164 #define __NR_mount 165 #define __NR_umount2 166 #define __NR_swapon 167 #define __NR_swapoff 168 #define __NR_reboot 169 #define __NR_sethostname 170 #define __NR_setdomainname 171 #define __NR_iopl 172 #define __NR_ioperm 173 #define __NR_create_module 174 #define __NR_init_module 175 #define __NR_delete_module 176 #define __NR_get_kernel_syms 177 #define __NR_query_module 178 #define __NR_quotactl 179 #define __NR_nfsservctl 180 #define __NR_getpmsg 181 #define __NR_putpmsg 182 #define __NR_afs_syscall 183 #define __NR_tuxcall 184 #define __NR_security 185 #define __NR_gettid 186 #define __NR_readahead 187 #define __NR_setxattr 188 #define __NR_lsetxattr 189 #define __NR_fsetxattr 190 #define __NR_getxattr 191 #define __NR_lgetxattr 192 #define __NR_fgetxattr 193 #define __NR_listxattr 194 #define __NR_llistxattr 195 #define __NR_flistxattr 196 #define __NR_removexattr 197 #define __NR_lremovexattr 198 #define __NR_fremovexattr 199 #define __NR_tkill 200 #define __NR_time 201 #define __NR_futex 202 #define __NR_sched_setaffinity 203 #define __NR_sched_getaffinity 204 #define __NR_set_thread_area 205 #define __NR_io_setup 206 #define __NR_io_destroy 207 #define __NR_io_getevents 208 #define __NR_io_submit 209 #define __NR_io_cancel 210 #define __NR_get_thread_area 211 #define __NR_lookup_dcookie 212 #define __NR_epoll_create 213 #define __NR_epoll_ctl_old 214 #define __NR_epoll_wait_old 215 #define __NR_remap_file_pages 216 #define __NR_getdents64 217 #define __NR_set_tid_address 218 #define __NR_restart_syscall 219 #define __NR_semtimedop 220 #define __NR_fadvise64 221 #define __NR_timer_create 222 #define __NR_timer_settime 223 #define __NR_timer_gettime 224 #define __NR_timer_getoverrun 225 #define __NR_timer_delete 226 #define __NR_clock_settime 227 #define __NR_clock_gettime 228 #define __NR_clock_getres 229 #define __NR_clock_nanosleep 230 #define __NR_exit_group 231 #define __NR_epoll_wait 232 #define __NR_epoll_ctl 233 #define __NR_tgkill 234 #define __NR_utimes 235 #define __NR_vserver 236 #define __NR_mbind 237 #define __NR_set_mempolicy 238 #define __NR_get_mempolicy 239 #define __NR_mq_open 240 #define __NR_mq_unlink 241 #define __NR_mq_timedsend 242 #define __NR_mq_timedreceive 243 #define __NR_mq_notify 244 #define __NR_mq_getsetattr 245 #define __NR_kexec_load 246 #define __NR_waitid 247 #define __NR_add_key 248 #define __NR_request_key 249 #define __NR_keyctl 250 #define __NR_ioprio_set 251 #define __NR_ioprio_get 252 #define __NR_inotify_init 253 #define __NR_inotify_add_watch 254 #define __NR_inotify_rm_watch 255 #define __NR_migrate_pages 256 #define __NR_openat 257 #define __NR_mkdirat 258 #define __NR_mknodat 259 #define __NR_fchownat 260 #define __NR_futimesat 261 #define __NR_newfstatat 262 #define __NR_unlinkat 263 #define __NR_renameat 264 #define __NR_linkat 265 #define __NR_symlinkat 266 #define __NR_readlinkat 267 #define __NR_fchmodat 268 #define __NR_faccessat 269 #define __NR_pselect6 270 #define __NR_ppoll 271 #define __NR_unshare 272 #define __NR_set_robust_list 273 #define __NR_get_robust_list 274 #define __NR_splice 275 #define __NR_tee 276 #define __NR_sync_file_range 277 #define __NR_vmsplice 278 #define __NR_move_pages 279 #define __NR_utimensat 280 #define __NR_epoll_pwait 281 #define __NR_signalfd 282 #define __NR_timerfd_create 283 #define __NR_eventfd 284 #define __NR_fallocate 285 #define __NR_timerfd_settime 286 #define __NR_timerfd_gettime 287 #define __NR_accept4 288 #define __NR_signalfd4 289 #define __NR_eventfd2 290 #define __NR_epoll_create1 291 #define __NR_dup3 292 #define __NR_pipe2 293 #define __NR_inotify_init1 294 #define __NR_preadv 295 #define __NR_pwritev 296 #define __NR_rt_tgsigqueueinfo 297 #define __NR_perf_event_open 298 #define __NR_recvmmsg 299 #define __NR_fanotify_init 300 #define __NR_fanotify_mark 301 #define __NR_prlimit64 302 #define __NR_name_to_handle_at 303 #define __NR_open_by_handle_at 304 #define __NR_clock_adjtime 305 #define __NR_syncfs 306 #define __NR_sendmmsg 307 #define __NR_setns 308 #define __NR_getcpu 309 #define __NR_process_vm_readv 310 #define __NR_process_vm_writev 311 #define __NR_kcmp 312 #define __NR_finit_module 313 #define __NR_sched_setattr 314 #define __NR_sched_getattr 315 #define __NR_renameat2 316 #define __NR_seccomp 317 #define __NR_getrandom 318 #define __NR_memfd_create 319 #define __NR_kexec_file_load 320 #define __NR_bpf 321 #define __NR_execveat 322 #define __NR_userfaultfd 323 #define __NR_membarrier 324 #define __NR_mlock2 325 #define __NR_copy_file_range 326 #define __NR_preadv2 327 #define __NR_pwritev2 328 #define __NR_pkey_mprotect 329 #define __NR_pkey_alloc 330 #define __NR_pkey_free 331 #define __NR_statx 332 #define __NR_io_pgetevents 333 #define __NR_rseq 334 #define __NR_pidfd_send_signal 424 #define __NR_io_uring_setup 425 #define __NR_io_uring_enter 426 #define __NR_io_uring_register 427 #define __NR_open_tree 428 #define __NR_move_mount 429 #define __NR_fsopen 430 #define __NR_fsconfig 431 #define __NR_fsmount 432 #define __NR_fspick 433 #define __NR_close_range 436 #define __NR_openat2 437 #define __NR_faccessat2 439 #endif /* _ASM_X86_UNISTD_64_H */ asm/termios.h000064400000000041151027430560007155 0ustar00#include asm/mtrr.h000064400000010201151027430560006456 0ustar00/* SPDX-License-Identifier: LGPL-2.0+ WITH Linux-syscall-note */ /* Generic MTRR (Memory Type Range Register) ioctls. Copyright (C) 1997-1999 Richard Gooch This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Richard Gooch may be reached by email at rgooch@atnf.csiro.au The postal address is: Richard Gooch, c/o ATNF, P. O. Box 76, Epping, N.S.W., 2121, Australia. */ #ifndef _ASM_X86_MTRR_H #define _ASM_X86_MTRR_H #include #include #include #define MTRR_IOCTL_BASE 'M' /* Warning: this structure has a different order from i386 on x86-64. The 32bit emulation code takes care of that. But you need to use this for 64bit, otherwise your X server will break. */ #ifdef __i386__ struct mtrr_sentry { unsigned long base; /* Base address */ unsigned int size; /* Size of region */ unsigned int type; /* Type of region */ }; struct mtrr_gentry { unsigned int regnum; /* Register number */ unsigned long base; /* Base address */ unsigned int size; /* Size of region */ unsigned int type; /* Type of region */ }; #else /* __i386__ */ struct mtrr_sentry { __u64 base; /* Base address */ __u32 size; /* Size of region */ __u32 type; /* Type of region */ }; struct mtrr_gentry { __u64 base; /* Base address */ __u32 size; /* Size of region */ __u32 regnum; /* Register number */ __u32 type; /* Type of region */ __u32 _pad; /* Unused */ }; #endif /* !__i386__ */ struct mtrr_var_range { __u32 base_lo; __u32 base_hi; __u32 mask_lo; __u32 mask_hi; }; /* In the Intel processor's MTRR interface, the MTRR type is always held in an 8 bit field: */ typedef __u8 mtrr_type; #define MTRR_NUM_FIXED_RANGES 88 #define MTRR_MAX_VAR_RANGES 256 struct mtrr_state_type { struct mtrr_var_range var_ranges[MTRR_MAX_VAR_RANGES]; mtrr_type fixed_ranges[MTRR_NUM_FIXED_RANGES]; unsigned char enabled; unsigned char have_fixed; mtrr_type def_type; }; #define MTRRphysBase_MSR(reg) (0x200 + 2 * (reg)) #define MTRRphysMask_MSR(reg) (0x200 + 2 * (reg) + 1) /* These are the various ioctls */ #define MTRRIOC_ADD_ENTRY _IOW(MTRR_IOCTL_BASE, 0, struct mtrr_sentry) #define MTRRIOC_SET_ENTRY _IOW(MTRR_IOCTL_BASE, 1, struct mtrr_sentry) #define MTRRIOC_DEL_ENTRY _IOW(MTRR_IOCTL_BASE, 2, struct mtrr_sentry) #define MTRRIOC_GET_ENTRY _IOWR(MTRR_IOCTL_BASE, 3, struct mtrr_gentry) #define MTRRIOC_KILL_ENTRY _IOW(MTRR_IOCTL_BASE, 4, struct mtrr_sentry) #define MTRRIOC_ADD_PAGE_ENTRY _IOW(MTRR_IOCTL_BASE, 5, struct mtrr_sentry) #define MTRRIOC_SET_PAGE_ENTRY _IOW(MTRR_IOCTL_BASE, 6, struct mtrr_sentry) #define MTRRIOC_DEL_PAGE_ENTRY _IOW(MTRR_IOCTL_BASE, 7, struct mtrr_sentry) #define MTRRIOC_GET_PAGE_ENTRY _IOWR(MTRR_IOCTL_BASE, 8, struct mtrr_gentry) #define MTRRIOC_KILL_PAGE_ENTRY _IOW(MTRR_IOCTL_BASE, 9, struct mtrr_sentry) /* MTRR memory types, which are defined in SDM */ #define MTRR_TYPE_UNCACHABLE 0 #define MTRR_TYPE_WRCOMB 1 /*#define MTRR_TYPE_ 2*/ /*#define MTRR_TYPE_ 3*/ #define MTRR_TYPE_WRTHROUGH 4 #define MTRR_TYPE_WRPROT 5 #define MTRR_TYPE_WRBACK 6 #define MTRR_NUM_TYPES 7 /* * Invalid MTRR memory type. mtrr_type_lookup() returns this value when * MTRRs are disabled. Note, this value is allocated from the reserved * values (0x7-0xff) of the MTRR memory types. */ #define MTRR_TYPE_INVALID 0xff #endif /* _ASM_X86_MTRR_H */ asm/siginfo.h000064400000000646151027430560007144 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_SIGINFO_H #define _ASM_X86_SIGINFO_H #ifdef __x86_64__ # ifdef __ILP32__ /* x32 */ typedef long long __kernel_si_clock_t __attribute__((aligned(4))); # define __ARCH_SI_CLOCK_T __kernel_si_clock_t # define __ARCH_SI_ATTRIBUTES __attribute__((aligned(8))) # endif #endif #include #endif /* _ASM_X86_SIGINFO_H */ asm/unistd_32.h000064400000025573151027430560007326 0ustar00#ifndef _ASM_X86_UNISTD_32_H #define _ASM_X86_UNISTD_32_H 1 #define __NR_restart_syscall 0 #define __NR_exit 1 #define __NR_fork 2 #define __NR_read 3 #define __NR_write 4 #define __NR_open 5 #define __NR_close 6 #define __NR_waitpid 7 #define __NR_creat 8 #define __NR_link 9 #define __NR_unlink 10 #define __NR_execve 11 #define __NR_chdir 12 #define __NR_time 13 #define __NR_mknod 14 #define __NR_chmod 15 #define __NR_lchown 16 #define __NR_break 17 #define __NR_oldstat 18 #define __NR_lseek 19 #define __NR_getpid 20 #define __NR_mount 21 #define __NR_umount 22 #define __NR_setuid 23 #define __NR_getuid 24 #define __NR_stime 25 #define __NR_ptrace 26 #define __NR_alarm 27 #define __NR_oldfstat 28 #define __NR_pause 29 #define __NR_utime 30 #define __NR_stty 31 #define __NR_gtty 32 #define __NR_access 33 #define __NR_nice 34 #define __NR_ftime 35 #define __NR_sync 36 #define __NR_kill 37 #define __NR_rename 38 #define __NR_mkdir 39 #define __NR_rmdir 40 #define __NR_dup 41 #define __NR_pipe 42 #define __NR_times 43 #define __NR_prof 44 #define __NR_brk 45 #define __NR_setgid 46 #define __NR_getgid 47 #define __NR_signal 48 #define __NR_geteuid 49 #define __NR_getegid 50 #define __NR_acct 51 #define __NR_umount2 52 #define __NR_lock 53 #define __NR_ioctl 54 #define __NR_fcntl 55 #define __NR_mpx 56 #define __NR_setpgid 57 #define __NR_ulimit 58 #define __NR_oldolduname 59 #define __NR_umask 60 #define __NR_chroot 61 #define __NR_ustat 62 #define __NR_dup2 63 #define __NR_getppid 64 #define __NR_getpgrp 65 #define __NR_setsid 66 #define __NR_sigaction 67 #define __NR_sgetmask 68 #define __NR_ssetmask 69 #define __NR_setreuid 70 #define __NR_setregid 71 #define __NR_sigsuspend 72 #define __NR_sigpending 73 #define __NR_sethostname 74 #define __NR_setrlimit 75 #define __NR_getrlimit 76 #define __NR_getrusage 77 #define __NR_gettimeofday 78 #define __NR_settimeofday 79 #define __NR_getgroups 80 #define __NR_setgroups 81 #define __NR_select 82 #define __NR_symlink 83 #define __NR_oldlstat 84 #define __NR_readlink 85 #define __NR_uselib 86 #define __NR_swapon 87 #define __NR_reboot 88 #define __NR_readdir 89 #define __NR_mmap 90 #define __NR_munmap 91 #define __NR_truncate 92 #define __NR_ftruncate 93 #define __NR_fchmod 94 #define __NR_fchown 95 #define __NR_getpriority 96 #define __NR_setpriority 97 #define __NR_profil 98 #define __NR_statfs 99 #define __NR_fstatfs 100 #define __NR_ioperm 101 #define __NR_socketcall 102 #define __NR_syslog 103 #define __NR_setitimer 104 #define __NR_getitimer 105 #define __NR_stat 106 #define __NR_lstat 107 #define __NR_fstat 108 #define __NR_olduname 109 #define __NR_iopl 110 #define __NR_vhangup 111 #define __NR_idle 112 #define __NR_vm86old 113 #define __NR_wait4 114 #define __NR_swapoff 115 #define __NR_sysinfo 116 #define __NR_ipc 117 #define __NR_fsync 118 #define __NR_sigreturn 119 #define __NR_clone 120 #define __NR_setdomainname 121 #define __NR_uname 122 #define __NR_modify_ldt 123 #define __NR_adjtimex 124 #define __NR_mprotect 125 #define __NR_sigprocmask 126 #define __NR_create_module 127 #define __NR_init_module 128 #define __NR_delete_module 129 #define __NR_get_kernel_syms 130 #define __NR_quotactl 131 #define __NR_getpgid 132 #define __NR_fchdir 133 #define __NR_bdflush 134 #define __NR_sysfs 135 #define __NR_personality 136 #define __NR_afs_syscall 137 #define __NR_setfsuid 138 #define __NR_setfsgid 139 #define __NR__llseek 140 #define __NR_getdents 141 #define __NR__newselect 142 #define __NR_flock 143 #define __NR_msync 144 #define __NR_readv 145 #define __NR_writev 146 #define __NR_getsid 147 #define __NR_fdatasync 148 #define __NR__sysctl 149 #define __NR_mlock 150 #define __NR_munlock 151 #define __NR_mlockall 152 #define __NR_munlockall 153 #define __NR_sched_setparam 154 #define __NR_sched_getparam 155 #define __NR_sched_setscheduler 156 #define __NR_sched_getscheduler 157 #define __NR_sched_yield 158 #define __NR_sched_get_priority_max 159 #define __NR_sched_get_priority_min 160 #define __NR_sched_rr_get_interval 161 #define __NR_nanosleep 162 #define __NR_mremap 163 #define __NR_setresuid 164 #define __NR_getresuid 165 #define __NR_vm86 166 #define __NR_query_module 167 #define __NR_poll 168 #define __NR_nfsservctl 169 #define __NR_setresgid 170 #define __NR_getresgid 171 #define __NR_prctl 172 #define __NR_rt_sigreturn 173 #define __NR_rt_sigaction 174 #define __NR_rt_sigprocmask 175 #define __NR_rt_sigpending 176 #define __NR_rt_sigtimedwait 177 #define __NR_rt_sigqueueinfo 178 #define __NR_rt_sigsuspend 179 #define __NR_pread64 180 #define __NR_pwrite64 181 #define __NR_chown 182 #define __NR_getcwd 183 #define __NR_capget 184 #define __NR_capset 185 #define __NR_sigaltstack 186 #define __NR_sendfile 187 #define __NR_getpmsg 188 #define __NR_putpmsg 189 #define __NR_vfork 190 #define __NR_ugetrlimit 191 #define __NR_mmap2 192 #define __NR_truncate64 193 #define __NR_ftruncate64 194 #define __NR_stat64 195 #define __NR_lstat64 196 #define __NR_fstat64 197 #define __NR_lchown32 198 #define __NR_getuid32 199 #define __NR_getgid32 200 #define __NR_geteuid32 201 #define __NR_getegid32 202 #define __NR_setreuid32 203 #define __NR_setregid32 204 #define __NR_getgroups32 205 #define __NR_setgroups32 206 #define __NR_fchown32 207 #define __NR_setresuid32 208 #define __NR_getresuid32 209 #define __NR_setresgid32 210 #define __NR_getresgid32 211 #define __NR_chown32 212 #define __NR_setuid32 213 #define __NR_setgid32 214 #define __NR_setfsuid32 215 #define __NR_setfsgid32 216 #define __NR_pivot_root 217 #define __NR_mincore 218 #define __NR_madvise 219 #define __NR_getdents64 220 #define __NR_fcntl64 221 #define __NR_gettid 224 #define __NR_readahead 225 #define __NR_setxattr 226 #define __NR_lsetxattr 227 #define __NR_fsetxattr 228 #define __NR_getxattr 229 #define __NR_lgetxattr 230 #define __NR_fgetxattr 231 #define __NR_listxattr 232 #define __NR_llistxattr 233 #define __NR_flistxattr 234 #define __NR_removexattr 235 #define __NR_lremovexattr 236 #define __NR_fremovexattr 237 #define __NR_tkill 238 #define __NR_sendfile64 239 #define __NR_futex 240 #define __NR_sched_setaffinity 241 #define __NR_sched_getaffinity 242 #define __NR_set_thread_area 243 #define __NR_get_thread_area 244 #define __NR_io_setup 245 #define __NR_io_destroy 246 #define __NR_io_getevents 247 #define __NR_io_submit 248 #define __NR_io_cancel 249 #define __NR_fadvise64 250 #define __NR_exit_group 252 #define __NR_lookup_dcookie 253 #define __NR_epoll_create 254 #define __NR_epoll_ctl 255 #define __NR_epoll_wait 256 #define __NR_remap_file_pages 257 #define __NR_set_tid_address 258 #define __NR_timer_create 259 #define __NR_timer_settime 260 #define __NR_timer_gettime 261 #define __NR_timer_getoverrun 262 #define __NR_timer_delete 263 #define __NR_clock_settime 264 #define __NR_clock_gettime 265 #define __NR_clock_getres 266 #define __NR_clock_nanosleep 267 #define __NR_statfs64 268 #define __NR_fstatfs64 269 #define __NR_tgkill 270 #define __NR_utimes 271 #define __NR_fadvise64_64 272 #define __NR_vserver 273 #define __NR_mbind 274 #define __NR_get_mempolicy 275 #define __NR_set_mempolicy 276 #define __NR_mq_open 277 #define __NR_mq_unlink 278 #define __NR_mq_timedsend 279 #define __NR_mq_timedreceive 280 #define __NR_mq_notify 281 #define __NR_mq_getsetattr 282 #define __NR_kexec_load 283 #define __NR_waitid 284 #define __NR_add_key 286 #define __NR_request_key 287 #define __NR_keyctl 288 #define __NR_ioprio_set 289 #define __NR_ioprio_get 290 #define __NR_inotify_init 291 #define __NR_inotify_add_watch 292 #define __NR_inotify_rm_watch 293 #define __NR_migrate_pages 294 #define __NR_openat 295 #define __NR_mkdirat 296 #define __NR_mknodat 297 #define __NR_fchownat 298 #define __NR_futimesat 299 #define __NR_fstatat64 300 #define __NR_unlinkat 301 #define __NR_renameat 302 #define __NR_linkat 303 #define __NR_symlinkat 304 #define __NR_readlinkat 305 #define __NR_fchmodat 306 #define __NR_faccessat 307 #define __NR_pselect6 308 #define __NR_ppoll 309 #define __NR_unshare 310 #define __NR_set_robust_list 311 #define __NR_get_robust_list 312 #define __NR_splice 313 #define __NR_sync_file_range 314 #define __NR_tee 315 #define __NR_vmsplice 316 #define __NR_move_pages 317 #define __NR_getcpu 318 #define __NR_epoll_pwait 319 #define __NR_utimensat 320 #define __NR_signalfd 321 #define __NR_timerfd_create 322 #define __NR_eventfd 323 #define __NR_fallocate 324 #define __NR_timerfd_settime 325 #define __NR_timerfd_gettime 326 #define __NR_signalfd4 327 #define __NR_eventfd2 328 #define __NR_epoll_create1 329 #define __NR_dup3 330 #define __NR_pipe2 331 #define __NR_inotify_init1 332 #define __NR_preadv 333 #define __NR_pwritev 334 #define __NR_rt_tgsigqueueinfo 335 #define __NR_perf_event_open 336 #define __NR_recvmmsg 337 #define __NR_fanotify_init 338 #define __NR_fanotify_mark 339 #define __NR_prlimit64 340 #define __NR_name_to_handle_at 341 #define __NR_open_by_handle_at 342 #define __NR_clock_adjtime 343 #define __NR_syncfs 344 #define __NR_sendmmsg 345 #define __NR_setns 346 #define __NR_process_vm_readv 347 #define __NR_process_vm_writev 348 #define __NR_kcmp 349 #define __NR_finit_module 350 #define __NR_sched_setattr 351 #define __NR_sched_getattr 352 #define __NR_renameat2 353 #define __NR_seccomp 354 #define __NR_getrandom 355 #define __NR_memfd_create 356 #define __NR_bpf 357 #define __NR_execveat 358 #define __NR_socket 359 #define __NR_socketpair 360 #define __NR_bind 361 #define __NR_connect 362 #define __NR_listen 363 #define __NR_accept4 364 #define __NR_getsockopt 365 #define __NR_setsockopt 366 #define __NR_getsockname 367 #define __NR_getpeername 368 #define __NR_sendto 369 #define __NR_sendmsg 370 #define __NR_recvfrom 371 #define __NR_recvmsg 372 #define __NR_shutdown 373 #define __NR_userfaultfd 374 #define __NR_membarrier 375 #define __NR_mlock2 376 #define __NR_copy_file_range 377 #define __NR_preadv2 378 #define __NR_pwritev2 379 #define __NR_pkey_mprotect 380 #define __NR_pkey_alloc 381 #define __NR_pkey_free 382 #define __NR_statx 383 #define __NR_arch_prctl 384 #define __NR_io_pgetevents 385 #define __NR_rseq 386 #define __NR_clock_gettime64 403 #define __NR_clock_settime64 404 #define __NR_clock_adjtime64 405 #define __NR_clock_getres_time64 406 #define __NR_clock_nanosleep_time64 407 #define __NR_timer_gettime64 408 #define __NR_timer_settime64 409 #define __NR_timerfd_gettime64 410 #define __NR_timerfd_settime64 411 #define __NR_utimensat_time64 412 #define __NR_io_pgetevents_time64 416 #define __NR_mq_timedsend_time64 418 #define __NR_mq_timedreceive_time64 419 #define __NR_semtimedop_time64 420 #define __NR_futex_time64 422 #define __NR_sched_rr_get_interval_time64 423 #define __NR_pidfd_send_signal 424 #define __NR_io_uring_setup 425 #define __NR_io_uring_enter 426 #define __NR_io_uring_register 427 #define __NR_open_tree 428 #define __NR_move_mount 429 #define __NR_fsopen 430 #define __NR_fsconfig 431 #define __NR_fsmount 432 #define __NR_fspick 433 #define __NR_close_range 436 #define __NR_openat2 437 #define __NR_faccessat2 439 #endif /* _ASM_X86_UNISTD_32_H */ asm/bootparam.h000064400000017117151027430560007473 0ustar00/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_BOOTPARAM_H #define _ASM_X86_BOOTPARAM_H /* setup_data types */ #define SETUP_NONE 0 #define SETUP_E820_EXT 1 #define SETUP_DTB 2 #define SETUP_PCI 3 #define SETUP_EFI 4 #define SETUP_APPLE_PROPERTIES 5 #define SETUP_JAILHOUSE 6 #define SETUP_CC_BLOB 7 /* ram_size flags */ #define RAMDISK_IMAGE_START_MASK 0x07FF #define RAMDISK_PROMPT_FLAG 0x8000 #define RAMDISK_LOAD_FLAG 0x4000 /* loadflags */ #define LOADED_HIGH (1<<0) #define KASLR_FLAG (1<<1) #define QUIET_FLAG (1<<5) #define KEEP_SEGMENTS (1<<6) #define CAN_USE_HEAP (1<<7) /* xloadflags */ #define XLF_KERNEL_64 (1<<0) #define XLF_CAN_BE_LOADED_ABOVE_4G (1<<1) #define XLF_EFI_HANDOVER_32 (1<<2) #define XLF_EFI_HANDOVER_64 (1<<3) #define XLF_EFI_KEXEC (1<<4) #ifndef __ASSEMBLY__ #include #include #include #include #include #include
* *
Random Number Generator Requirements
To be documented.
* * @{ */ /** * @brief A model of a linear congruential random number generator. * * A random number generator that produces pseudorandom numbers via * linear function: * @f[ * x_{i+1}\leftarrow(ax_{i} + c) \bmod m * @f] * * The template parameter @p _UIntType must be an unsigned integral type * large enough to store values up to (__m-1). If the template parameter * @p __m is 0, the modulus @p __m used is * std::numeric_limits<_UIntType>::max() plus 1. Otherwise, the template * parameters @p __a and @p __c must be less than @p __m. * * The size of the state is @f$1@f$. */ template class linear_congruential_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(__m == 0u || (__a < __m && __c < __m), "template argument substituting __m out of bounds"); public: /** The type of the generated random value. */ typedef _UIntType result_type; /** The multiplier. */ static constexpr result_type multiplier = __a; /** An increment. */ static constexpr result_type increment = __c; /** The modulus. */ static constexpr result_type modulus = __m; static constexpr result_type default_seed = 1u; /** * @brief Constructs a %linear_congruential_engine random number * generator engine with seed @p __s. The default seed value * is 1. * * @param __s The initial seed value. */ explicit linear_congruential_engine(result_type __s = default_seed) { seed(__s); } /** * @brief Constructs a %linear_congruential_engine random number * generator engine seeded from the seed sequence @p __q. * * @param __q the seed sequence. */ template::value> ::type> explicit linear_congruential_engine(_Sseq& __q) { seed(__q); } /** * @brief Reseeds the %linear_congruential_engine random number generator * engine sequence to the seed @p __s. * * @param __s The new seed. */ void seed(result_type __s = default_seed); /** * @brief Reseeds the %linear_congruential_engine random number generator * engine * sequence using values from the seed sequence @p __q. * * @param __q the seed sequence. */ template typename std::enable_if::value>::type seed(_Sseq& __q); /** * @brief Gets the smallest possible value in the output range. * * The minimum depends on the @p __c parameter: if it is zero, the * minimum generated must be > 0, otherwise 0 is allowed. */ static constexpr result_type min() { return __c == 0u ? 1u : 0u; } /** * @brief Gets the largest possible value in the output range. */ static constexpr result_type max() { return __m - 1u; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next random number in the sequence. */ result_type operator()() { _M_x = __detail::__mod<_UIntType, __m, __a, __c>(_M_x); return _M_x; } /** * @brief Compares two linear congruential random number generator * objects of the same type for equality. * * @param __lhs A linear congruential random number generator object. * @param __rhs Another linear congruential random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const linear_congruential_engine& __lhs, const linear_congruential_engine& __rhs) { return __lhs._M_x == __rhs._M_x; } /** * @brief Writes the textual representation of the state x(i) of x to * @p __os. * * @param __os The output stream. * @param __lcr A % linear_congruential_engine random number generator. * @returns __os. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::linear_congruential_engine<_UIntType1, __a1, __c1, __m1>& __lcr); /** * @brief Sets the state of the engine by reading its textual * representation from @p __is. * * The textual representation must have been previously written using * an output stream whose imbued locale and whose type's template * specialization arguments _CharT and _Traits were the same as those * of @p __is. * * @param __is The input stream. * @param __lcr A % linear_congruential_engine random number generator. * @returns __is. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::linear_congruential_engine<_UIntType1, __a1, __c1, __m1>& __lcr); private: _UIntType _M_x; }; /** * @brief Compares two linear congruential random number generator * objects of the same type for inequality. * * @param __lhs A linear congruential random number generator object. * @param __rhs Another linear congruential random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::linear_congruential_engine<_UIntType, __a, __c, __m>& __lhs, const std::linear_congruential_engine<_UIntType, __a, __c, __m>& __rhs) { return !(__lhs == __rhs); } /** * A generalized feedback shift register discrete random number generator. * * This algorithm avoids multiplication and division and is designed to be * friendly to a pipelined architecture. If the parameters are chosen * correctly, this generator will produce numbers with a very long period and * fairly good apparent entropy, although still not cryptographically strong. * * The best way to use this generator is with the predefined mt19937 class. * * This algorithm was originally invented by Makoto Matsumoto and * Takuji Nishimura. * * @tparam __w Word size, the number of bits in each element of * the state vector. * @tparam __n The degree of recursion. * @tparam __m The period parameter. * @tparam __r The separation point bit index. * @tparam __a The last row of the twist matrix. * @tparam __u The first right-shift tempering matrix parameter. * @tparam __d The first right-shift tempering matrix mask. * @tparam __s The first left-shift tempering matrix parameter. * @tparam __b The first left-shift tempering matrix mask. * @tparam __t The second left-shift tempering matrix parameter. * @tparam __c The second left-shift tempering matrix mask. * @tparam __l The second right-shift tempering matrix parameter. * @tparam __f Initialization multiplier. */ template class mersenne_twister_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(1u <= __m && __m <= __n, "template argument substituting __m out of bounds"); static_assert(__r <= __w, "template argument substituting " "__r out of bound"); static_assert(__u <= __w, "template argument substituting " "__u out of bound"); static_assert(__s <= __w, "template argument substituting " "__s out of bound"); static_assert(__t <= __w, "template argument substituting " "__t out of bound"); static_assert(__l <= __w, "template argument substituting " "__l out of bound"); static_assert(__w <= std::numeric_limits<_UIntType>::digits, "template argument substituting __w out of bound"); static_assert(__a <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __a out of bound"); static_assert(__b <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __b out of bound"); static_assert(__c <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __c out of bound"); static_assert(__d <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __d out of bound"); static_assert(__f <= (__detail::_Shift<_UIntType, __w>::__value - 1), "template argument substituting __f out of bound"); public: /** The type of the generated random value. */ typedef _UIntType result_type; // parameter values static constexpr size_t word_size = __w; static constexpr size_t state_size = __n; static constexpr size_t shift_size = __m; static constexpr size_t mask_bits = __r; static constexpr result_type xor_mask = __a; static constexpr size_t tempering_u = __u; static constexpr result_type tempering_d = __d; static constexpr size_t tempering_s = __s; static constexpr result_type tempering_b = __b; static constexpr size_t tempering_t = __t; static constexpr result_type tempering_c = __c; static constexpr size_t tempering_l = __l; static constexpr result_type initialization_multiplier = __f; static constexpr result_type default_seed = 5489u; // constructors and member function explicit mersenne_twister_engine(result_type __sd = default_seed) { seed(__sd); } /** * @brief Constructs a %mersenne_twister_engine random number generator * engine seeded from the seed sequence @p __q. * * @param __q the seed sequence. */ template::value> ::type> explicit mersenne_twister_engine(_Sseq& __q) { seed(__q); } void seed(result_type __sd = default_seed); template typename std::enable_if::value>::type seed(_Sseq& __q); /** * @brief Gets the smallest possible value in the output range. */ static constexpr result_type min() { return 0; } /** * @brief Gets the largest possible value in the output range. */ static constexpr result_type max() { return __detail::_Shift<_UIntType, __w>::__value - 1; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z); result_type operator()(); /** * @brief Compares two % mersenne_twister_engine random number generator * objects of the same type for equality. * * @param __lhs A % mersenne_twister_engine random number generator * object. * @param __rhs Another % mersenne_twister_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const mersenne_twister_engine& __lhs, const mersenne_twister_engine& __rhs) { return (std::equal(__lhs._M_x, __lhs._M_x + state_size, __rhs._M_x) && __lhs._M_p == __rhs._M_p); } /** * @brief Inserts the current state of a % mersenne_twister_engine * random number generator engine @p __x into the output stream * @p __os. * * @param __os An output stream. * @param __x A % mersenne_twister_engine random number generator * engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::mersenne_twister_engine<_UIntType1, __w1, __n1, __m1, __r1, __a1, __u1, __d1, __s1, __b1, __t1, __c1, __l1, __f1>& __x); /** * @brief Extracts the current state of a % mersenne_twister_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A % mersenne_twister_engine random number generator * engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::mersenne_twister_engine<_UIntType1, __w1, __n1, __m1, __r1, __a1, __u1, __d1, __s1, __b1, __t1, __c1, __l1, __f1>& __x); private: void _M_gen_rand(); _UIntType _M_x[state_size]; size_t _M_p; }; /** * @brief Compares two % mersenne_twister_engine random number generator * objects of the same type for inequality. * * @param __lhs A % mersenne_twister_engine random number generator * object. * @param __rhs Another % mersenne_twister_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __lhs, const std::mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __rhs) { return !(__lhs == __rhs); } /** * @brief The Marsaglia-Zaman generator. * * This is a model of a Generalized Fibonacci discrete random number * generator, sometimes referred to as the SWC generator. * * A discrete random number generator that produces pseudorandom * numbers using: * @f[ * x_{i}\leftarrow(x_{i - s} - x_{i - r} - carry_{i-1}) \bmod m * @f] * * The size of the state is @f$r@f$ * and the maximum period of the generator is @f$(m^r - m^s - 1)@f$. */ template class subtract_with_carry_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(0u < __s && __s < __r, "0 < s < r"); static_assert(0u < __w && __w <= std::numeric_limits<_UIntType>::digits, "template argument substituting __w out of bounds"); public: /** The type of the generated random value. */ typedef _UIntType result_type; // parameter values static constexpr size_t word_size = __w; static constexpr size_t short_lag = __s; static constexpr size_t long_lag = __r; static constexpr result_type default_seed = 19780503u; /** * @brief Constructs an explicitly seeded % subtract_with_carry_engine * random number generator. */ explicit subtract_with_carry_engine(result_type __sd = default_seed) { seed(__sd); } /** * @brief Constructs a %subtract_with_carry_engine random number engine * seeded from the seed sequence @p __q. * * @param __q the seed sequence. */ template::value> ::type> explicit subtract_with_carry_engine(_Sseq& __q) { seed(__q); } /** * @brief Seeds the initial state @f$x_0@f$ of the random number * generator. * * N1688[4.19] modifies this as follows. If @p __value == 0, * sets value to 19780503. In any case, with a linear * congruential generator lcg(i) having parameters @f$ m_{lcg} = * 2147483563, a_{lcg} = 40014, c_{lcg} = 0, and lcg(0) = value * @f$, sets @f$ x_{-r} \dots x_{-1} @f$ to @f$ lcg(1) \bmod m * \dots lcg(r) \bmod m @f$ respectively. If @f$ x_{-1} = 0 @f$ * set carry to 1, otherwise sets carry to 0. */ void seed(result_type __sd = default_seed); /** * @brief Seeds the initial state @f$x_0@f$ of the * % subtract_with_carry_engine random number generator. */ template typename std::enable_if::value>::type seed(_Sseq& __q); /** * @brief Gets the inclusive minimum value of the range of random * integers returned by this generator. */ static constexpr result_type min() { return 0; } /** * @brief Gets the inclusive maximum value of the range of random * integers returned by this generator. */ static constexpr result_type max() { return __detail::_Shift<_UIntType, __w>::__value - 1; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next random number in the sequence. */ result_type operator()(); /** * @brief Compares two % subtract_with_carry_engine random number * generator objects of the same type for equality. * * @param __lhs A % subtract_with_carry_engine random number generator * object. * @param __rhs Another % subtract_with_carry_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const subtract_with_carry_engine& __lhs, const subtract_with_carry_engine& __rhs) { return (std::equal(__lhs._M_x, __lhs._M_x + long_lag, __rhs._M_x) && __lhs._M_carry == __rhs._M_carry && __lhs._M_p == __rhs._M_p); } /** * @brief Inserts the current state of a % subtract_with_carry_engine * random number generator engine @p __x into the output stream * @p __os. * * @param __os An output stream. * @param __x A % subtract_with_carry_engine random number generator * engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::subtract_with_carry_engine<_UIntType1, __w1, __s1, __r1>& __x); /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A % subtract_with_carry_engine random number generator * engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::subtract_with_carry_engine<_UIntType1, __w1, __s1, __r1>& __x); private: /// The state of the generator. This is a ring buffer. _UIntType _M_x[long_lag]; _UIntType _M_carry; ///< The carry size_t _M_p; ///< Current index of x(i - r). }; /** * @brief Compares two % subtract_with_carry_engine random number * generator objects of the same type for inequality. * * @param __lhs A % subtract_with_carry_engine random number generator * object. * @param __rhs Another % subtract_with_carry_engine random number * generator object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::subtract_with_carry_engine<_UIntType, __w, __s, __r>& __lhs, const std::subtract_with_carry_engine<_UIntType, __w, __s, __r>& __rhs) { return !(__lhs == __rhs); } /** * Produces random numbers from some base engine by discarding blocks of * data. * * 0 <= @p __r <= @p __p */ template class discard_block_engine { static_assert(1 <= __r && __r <= __p, "template argument substituting __r out of bounds"); public: /** The type of the generated random value. */ typedef typename _RandomNumberEngine::result_type result_type; // parameter values static constexpr size_t block_size = __p; static constexpr size_t used_block = __r; /** * @brief Constructs a default %discard_block_engine engine. * * The underlying engine is default constructed as well. */ discard_block_engine() : _M_b(), _M_n(0) { } /** * @brief Copy constructs a %discard_block_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit discard_block_engine(const _RandomNumberEngine& __rng) : _M_b(__rng), _M_n(0) { } /** * @brief Move constructs a %discard_block_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit discard_block_engine(_RandomNumberEngine&& __rng) : _M_b(std::move(__rng)), _M_n(0) { } /** * @brief Seed constructs a %discard_block_engine engine. * * Constructs the underlying generator engine seeded with @p __s. * @param __s A seed value for the base class engine. */ explicit discard_block_engine(result_type __s) : _M_b(__s), _M_n(0) { } /** * @brief Generator construct a %discard_block_engine engine. * * @param __q A seed sequence. */ template::value && !std::is_same<_Sseq, _RandomNumberEngine>::value> ::type> explicit discard_block_engine(_Sseq& __q) : _M_b(__q), _M_n(0) { } /** * @brief Reseeds the %discard_block_engine object with the default * seed for the underlying base class generator engine. */ void seed() { _M_b.seed(); _M_n = 0; } /** * @brief Reseeds the %discard_block_engine object with the default * seed for the underlying base class generator engine. */ void seed(result_type __s) { _M_b.seed(__s); _M_n = 0; } /** * @brief Reseeds the %discard_block_engine object with the given seed * sequence. * @param __q A seed generator function. */ template void seed(_Sseq& __q) { _M_b.seed(__q); _M_n = 0; } /** * @brief Gets a const reference to the underlying generator engine * object. */ const _RandomNumberEngine& base() const noexcept { return _M_b; } /** * @brief Gets the minimum value in the generated random number range. */ static constexpr result_type min() { return _RandomNumberEngine::min(); } /** * @brief Gets the maximum value in the generated random number range. */ static constexpr result_type max() { return _RandomNumberEngine::max(); } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next value in the generated random number sequence. */ result_type operator()(); /** * @brief Compares two %discard_block_engine random number generator * objects of the same type for equality. * * @param __lhs A %discard_block_engine random number generator object. * @param __rhs Another %discard_block_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const discard_block_engine& __lhs, const discard_block_engine& __rhs) { return __lhs._M_b == __rhs._M_b && __lhs._M_n == __rhs._M_n; } /** * @brief Inserts the current state of a %discard_block_engine random * number generator engine @p __x into the output stream * @p __os. * * @param __os An output stream. * @param __x A %discard_block_engine random number generator engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::discard_block_engine<_RandomNumberEngine1, __p1, __r1>& __x); /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A %discard_block_engine random number generator engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::discard_block_engine<_RandomNumberEngine1, __p1, __r1>& __x); private: _RandomNumberEngine _M_b; size_t _M_n; }; /** * @brief Compares two %discard_block_engine random number generator * objects of the same type for inequality. * * @param __lhs A %discard_block_engine random number generator object. * @param __rhs Another %discard_block_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::discard_block_engine<_RandomNumberEngine, __p, __r>& __lhs, const std::discard_block_engine<_RandomNumberEngine, __p, __r>& __rhs) { return !(__lhs == __rhs); } /** * Produces random numbers by combining random numbers from some base * engine to produce random numbers with a specifies number of bits @p __w. */ template class independent_bits_engine { static_assert(std::is_unsigned<_UIntType>::value, "result_type must be an unsigned integral type"); static_assert(0u < __w && __w <= std::numeric_limits<_UIntType>::digits, "template argument substituting __w out of bounds"); public: /** The type of the generated random value. */ typedef _UIntType result_type; /** * @brief Constructs a default %independent_bits_engine engine. * * The underlying engine is default constructed as well. */ independent_bits_engine() : _M_b() { } /** * @brief Copy constructs a %independent_bits_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit independent_bits_engine(const _RandomNumberEngine& __rng) : _M_b(__rng) { } /** * @brief Move constructs a %independent_bits_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit independent_bits_engine(_RandomNumberEngine&& __rng) : _M_b(std::move(__rng)) { } /** * @brief Seed constructs a %independent_bits_engine engine. * * Constructs the underlying generator engine seeded with @p __s. * @param __s A seed value for the base class engine. */ explicit independent_bits_engine(result_type __s) : _M_b(__s) { } /** * @brief Generator construct a %independent_bits_engine engine. * * @param __q A seed sequence. */ template::value && !std::is_same<_Sseq, _RandomNumberEngine>::value> ::type> explicit independent_bits_engine(_Sseq& __q) : _M_b(__q) { } /** * @brief Reseeds the %independent_bits_engine object with the default * seed for the underlying base class generator engine. */ void seed() { _M_b.seed(); } /** * @brief Reseeds the %independent_bits_engine object with the default * seed for the underlying base class generator engine. */ void seed(result_type __s) { _M_b.seed(__s); } /** * @brief Reseeds the %independent_bits_engine object with the given * seed sequence. * @param __q A seed generator function. */ template void seed(_Sseq& __q) { _M_b.seed(__q); } /** * @brief Gets a const reference to the underlying generator engine * object. */ const _RandomNumberEngine& base() const noexcept { return _M_b; } /** * @brief Gets the minimum value in the generated random number range. */ static constexpr result_type min() { return 0U; } /** * @brief Gets the maximum value in the generated random number range. */ static constexpr result_type max() { return __detail::_Shift<_UIntType, __w>::__value - 1; } /** * @brief Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * @brief Gets the next value in the generated random number sequence. */ result_type operator()(); /** * @brief Compares two %independent_bits_engine random number generator * objects of the same type for equality. * * @param __lhs A %independent_bits_engine random number generator * object. * @param __rhs Another %independent_bits_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const independent_bits_engine& __lhs, const independent_bits_engine& __rhs) { return __lhs._M_b == __rhs._M_b; } /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A %independent_bits_engine random number generator * engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __x) { __is >> __x._M_b; return __is; } private: _RandomNumberEngine _M_b; }; /** * @brief Compares two %independent_bits_engine random number generator * objects of the same type for inequality. * * @param __lhs A %independent_bits_engine random number generator * object. * @param __rhs Another %independent_bits_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __lhs, const std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __rhs) { return !(__lhs == __rhs); } /** * @brief Inserts the current state of a %independent_bits_engine random * number generator engine @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %independent_bits_engine random number generator engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::independent_bits_engine<_RandomNumberEngine, __w, _UIntType>& __x) { __os << __x.base(); return __os; } /** * @brief Produces random numbers by combining random numbers from some * base engine to produce random numbers with a specifies number of bits * @p __k. */ template class shuffle_order_engine { static_assert(1u <= __k, "template argument substituting " "__k out of bound"); public: /** The type of the generated random value. */ typedef typename _RandomNumberEngine::result_type result_type; static constexpr size_t table_size = __k; /** * @brief Constructs a default %shuffle_order_engine engine. * * The underlying engine is default constructed as well. */ shuffle_order_engine() : _M_b() { _M_initialize(); } /** * @brief Copy constructs a %shuffle_order_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit shuffle_order_engine(const _RandomNumberEngine& __rng) : _M_b(__rng) { _M_initialize(); } /** * @brief Move constructs a %shuffle_order_engine engine. * * Copies an existing base class random number generator. * @param __rng An existing (base class) engine object. */ explicit shuffle_order_engine(_RandomNumberEngine&& __rng) : _M_b(std::move(__rng)) { _M_initialize(); } /** * @brief Seed constructs a %shuffle_order_engine engine. * * Constructs the underlying generator engine seeded with @p __s. * @param __s A seed value for the base class engine. */ explicit shuffle_order_engine(result_type __s) : _M_b(__s) { _M_initialize(); } /** * @brief Generator construct a %shuffle_order_engine engine. * * @param __q A seed sequence. */ template::value && !std::is_same<_Sseq, _RandomNumberEngine>::value> ::type> explicit shuffle_order_engine(_Sseq& __q) : _M_b(__q) { _M_initialize(); } /** * @brief Reseeds the %shuffle_order_engine object with the default seed for the underlying base class generator engine. */ void seed() { _M_b.seed(); _M_initialize(); } /** * @brief Reseeds the %shuffle_order_engine object with the default seed * for the underlying base class generator engine. */ void seed(result_type __s) { _M_b.seed(__s); _M_initialize(); } /** * @brief Reseeds the %shuffle_order_engine object with the given seed * sequence. * @param __q A seed generator function. */ template void seed(_Sseq& __q) { _M_b.seed(__q); _M_initialize(); } /** * Gets a const reference to the underlying generator engine object. */ const _RandomNumberEngine& base() const noexcept { return _M_b; } /** * Gets the minimum value in the generated random number range. */ static constexpr result_type min() { return _RandomNumberEngine::min(); } /** * Gets the maximum value in the generated random number range. */ static constexpr result_type max() { return _RandomNumberEngine::max(); } /** * Discard a sequence of random numbers. */ void discard(unsigned long long __z) { for (; __z != 0ULL; --__z) (*this)(); } /** * Gets the next value in the generated random number sequence. */ result_type operator()(); /** * Compares two %shuffle_order_engine random number generator objects * of the same type for equality. * * @param __lhs A %shuffle_order_engine random number generator object. * @param __rhs Another %shuffle_order_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be equal, false otherwise. */ friend bool operator==(const shuffle_order_engine& __lhs, const shuffle_order_engine& __rhs) { return (__lhs._M_b == __rhs._M_b && std::equal(__lhs._M_v, __lhs._M_v + __k, __rhs._M_v) && __lhs._M_y == __rhs._M_y); } /** * @brief Inserts the current state of a %shuffle_order_engine random * number generator engine @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %shuffle_order_engine random number generator engine. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::shuffle_order_engine<_RandomNumberEngine1, __k1>& __x); /** * @brief Extracts the current state of a % subtract_with_carry_engine * random number generator engine @p __x from the input stream * @p __is. * * @param __is An input stream. * @param __x A %shuffle_order_engine random number generator engine. * * @returns The input stream with the state of @p __x extracted or in * an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::shuffle_order_engine<_RandomNumberEngine1, __k1>& __x); private: void _M_initialize() { for (size_t __i = 0; __i < __k; ++__i) _M_v[__i] = _M_b(); _M_y = _M_b(); } _RandomNumberEngine _M_b; result_type _M_v[__k]; result_type _M_y; }; /** * Compares two %shuffle_order_engine random number generator objects * of the same type for inequality. * * @param __lhs A %shuffle_order_engine random number generator object. * @param __rhs Another %shuffle_order_engine random number generator * object. * * @returns true if the infinite sequences of generated values * would be different, false otherwise. */ template inline bool operator!=(const std::shuffle_order_engine<_RandomNumberEngine, __k>& __lhs, const std::shuffle_order_engine<_RandomNumberEngine, __k>& __rhs) { return !(__lhs == __rhs); } /** * The classic Minimum Standard rand0 of Lewis, Goodman, and Miller. */ typedef linear_congruential_engine minstd_rand0; /** * An alternative LCR (Lehmer Generator function). */ typedef linear_congruential_engine minstd_rand; /** * The classic Mersenne Twister. * * Reference: * M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-Dimensionally * Equidistributed Uniform Pseudo-Random Number Generator, ACM Transactions * on Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. */ typedef mersenne_twister_engine< uint_fast32_t, 32, 624, 397, 31, 0x9908b0dfUL, 11, 0xffffffffUL, 7, 0x9d2c5680UL, 15, 0xefc60000UL, 18, 1812433253UL> mt19937; /** * An alternative Mersenne Twister. */ typedef mersenne_twister_engine< uint_fast64_t, 64, 312, 156, 31, 0xb5026f5aa96619e9ULL, 29, 0x5555555555555555ULL, 17, 0x71d67fffeda60000ULL, 37, 0xfff7eee000000000ULL, 43, 6364136223846793005ULL> mt19937_64; typedef subtract_with_carry_engine ranlux24_base; typedef subtract_with_carry_engine ranlux48_base; typedef discard_block_engine ranlux24; typedef discard_block_engine ranlux48; typedef shuffle_order_engine knuth_b; typedef minstd_rand0 default_random_engine; /** * A standard interface to a platform-specific non-deterministic * random number generator (if any are available). */ class random_device { public: /** The type of the generated random value. */ typedef unsigned int result_type; // constructors, destructors and member functions #ifdef _GLIBCXX_USE_RANDOM_TR1 explicit random_device(const std::string& __token = "default") { _M_init(__token); } ~random_device() { _M_fini(); } #else explicit random_device(const std::string& __token = "mt19937") { _M_init_pretr1(__token); } public: #endif static constexpr result_type min() { return std::numeric_limits::min(); } static constexpr result_type max() { return std::numeric_limits::max(); } double entropy() const noexcept { #ifdef _GLIBCXX_USE_RANDOM_TR1 return this->_M_getentropy(); #else return 0.0; #endif } result_type operator()() { #ifdef _GLIBCXX_USE_RANDOM_TR1 return this->_M_getval(); #else return this->_M_getval_pretr1(); #endif } // No copy functions. random_device(const random_device&) = delete; void operator=(const random_device&) = delete; private: void _M_init(const std::string& __token); void _M_init_pretr1(const std::string& __token); void _M_fini(); result_type _M_getval(); result_type _M_getval_pretr1(); double _M_getentropy() const noexcept; union { void* _M_file; mt19937 _M_mt; }; }; /* @} */ // group random_generators /** * @addtogroup random_distributions Random Number Distributions * @ingroup random * @{ */ /** * @addtogroup random_distributions_uniform Uniform Distributions * @ingroup random_distributions * @{ */ // std::uniform_int_distribution is defined in /** * @brief Return true if two uniform integer distributions have * different parameters. */ template inline bool operator!=(const std::uniform_int_distribution<_IntType>& __d1, const std::uniform_int_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %uniform_int_distribution random number * distribution @p __x into the output stream @p os. * * @param __os An output stream. * @param __x A %uniform_int_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>&, const std::uniform_int_distribution<_IntType>&); /** * @brief Extracts a %uniform_int_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %uniform_int_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>&, std::uniform_int_distribution<_IntType>&); /** * @brief Uniform continuous distribution for random numbers. * * A continuous random distribution on the range [min, max) with equal * probability throughout the range. The URNG should be real-valued and * deliver number in the range [0, 1). */ template class uniform_real_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef uniform_real_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { __glibcxx_assert(_M_a <= _M_b); } result_type a() const { return _M_a; } result_type b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; public: /** * @brief Constructs a uniform_real_distribution object. * * @param __a [IN] The lower bound of the distribution. * @param __b [IN] The upper bound of the distribution. */ explicit uniform_real_distribution(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit uniform_real_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for the uniform real distribution. */ void reset() { } result_type a() const { return _M_param.a(); } result_type b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the inclusive lower bound of the distribution range. */ result_type min() const { return this->a(); } /** * @brief Returns the inclusive upper bound of the distribution range. */ result_type max() const { return this->b(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return (__aurng() * (__p.b() - __p.a())) + __p.a(); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two uniform real distributions have * the same parameters. */ friend bool operator==(const uniform_real_distribution& __d1, const uniform_real_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two uniform real distributions have * different parameters. */ template inline bool operator!=(const std::uniform_real_distribution<_IntType>& __d1, const std::uniform_real_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %uniform_real_distribution random number * distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %uniform_real_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>&, const std::uniform_real_distribution<_RealType>&); /** * @brief Extracts a %uniform_real_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %uniform_real_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>&, std::uniform_real_distribution<_RealType>&); /* @} */ // group random_distributions_uniform /** * @addtogroup random_distributions_normal Normal Distributions * @ingroup random_distributions * @{ */ /** * @brief A normal continuous distribution for random numbers. * * The formula for the normal probability density function is * @f[ * p(x|\mu,\sigma) = \frac{1}{\sigma \sqrt{2 \pi}} * e^{- \frac{{x - \mu}^ {2}}{2 \sigma ^ {2}} } * @f] */ template class normal_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef normal_distribution<_RealType> distribution_type; explicit param_type(_RealType __mean = _RealType(0), _RealType __stddev = _RealType(1)) : _M_mean(__mean), _M_stddev(__stddev) { __glibcxx_assert(_M_stddev > _RealType(0)); } _RealType mean() const { return _M_mean; } _RealType stddev() const { return _M_stddev; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return (__p1._M_mean == __p2._M_mean && __p1._M_stddev == __p2._M_stddev); } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_mean; _RealType _M_stddev; }; public: /** * Constructs a normal distribution with parameters @f$mean@f$ and * standard deviation. */ explicit normal_distribution(result_type __mean = result_type(0), result_type __stddev = result_type(1)) : _M_param(__mean, __stddev) { } explicit normal_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { _M_saved_available = false; } /** * @brief Returns the mean of the distribution. */ _RealType mean() const { return _M_param.mean(); } /** * @brief Returns the standard deviation of the distribution. */ _RealType stddev() const { return _M_param.stddev(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two normal distributions have * the same parameters and the sequences that would * be generated are equal. */ template friend bool operator==(const std::normal_distribution<_RealType1>& __d1, const std::normal_distribution<_RealType1>& __d2); /** * @brief Inserts a %normal_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %normal_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::normal_distribution<_RealType1>& __x); /** * @brief Extracts a %normal_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %normal_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::normal_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; result_type _M_saved = 0; bool _M_saved_available = false; }; /** * @brief Return true if two normal distributions are different. */ template inline bool operator!=(const std::normal_distribution<_RealType>& __d1, const std::normal_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A lognormal_distribution random number distribution. * * The formula for the normal probability mass function is * @f[ * p(x|m,s) = \frac{1}{sx\sqrt{2\pi}} * \exp{-\frac{(\ln{x} - m)^2}{2s^2}} * @f] */ template class lognormal_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef lognormal_distribution<_RealType> distribution_type; explicit param_type(_RealType __m = _RealType(0), _RealType __s = _RealType(1)) : _M_m(__m), _M_s(__s) { } _RealType m() const { return _M_m; } _RealType s() const { return _M_s; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_m == __p2._M_m && __p1._M_s == __p2._M_s; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_m; _RealType _M_s; }; explicit lognormal_distribution(_RealType __m = _RealType(0), _RealType __s = _RealType(1)) : _M_param(__m, __s), _M_nd() { } explicit lognormal_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * */ _RealType m() const { return _M_param.m(); } _RealType s() const { return _M_param.s(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { return std::exp(__p.s() * _M_nd(__urng) + __p.m()); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two lognormal distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const lognormal_distribution& __d1, const lognormal_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd); } /** * @brief Inserts a %lognormal_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %lognormal_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::lognormal_distribution<_RealType1>& __x); /** * @brief Extracts a %lognormal_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %lognormal_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::lognormal_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::normal_distribution _M_nd; }; /** * @brief Return true if two lognormal distributions are different. */ template inline bool operator!=(const std::lognormal_distribution<_RealType>& __d1, const std::lognormal_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A gamma continuous distribution for random numbers. * * The formula for the gamma probability density function is: * @f[ * p(x|\alpha,\beta) = \frac{1}{\beta\Gamma(\alpha)} * (x/\beta)^{\alpha - 1} e^{-x/\beta} * @f] */ template class gamma_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef gamma_distribution<_RealType> distribution_type; friend class gamma_distribution<_RealType>; explicit param_type(_RealType __alpha_val = _RealType(1), _RealType __beta_val = _RealType(1)) : _M_alpha(__alpha_val), _M_beta(__beta_val) { __glibcxx_assert(_M_alpha > _RealType(0)); _M_initialize(); } _RealType alpha() const { return _M_alpha; } _RealType beta() const { return _M_beta; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return (__p1._M_alpha == __p2._M_alpha && __p1._M_beta == __p2._M_beta); } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); _RealType _M_alpha; _RealType _M_beta; _RealType _M_malpha, _M_a2; }; public: /** * @brief Constructs a gamma distribution with parameters * @f$\alpha@f$ and @f$\beta@f$. */ explicit gamma_distribution(_RealType __alpha_val = _RealType(1), _RealType __beta_val = _RealType(1)) : _M_param(__alpha_val, __beta_val), _M_nd() { } explicit gamma_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * @brief Returns the @f$\alpha@f$ of the distribution. */ _RealType alpha() const { return _M_param.alpha(); } /** * @brief Returns the @f$\beta@f$ of the distribution. */ _RealType beta() const { return _M_param.beta(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two gamma distributions have the same * parameters and the sequences that would be generated * are equal. */ friend bool operator==(const gamma_distribution& __d1, const gamma_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd); } /** * @brief Inserts a %gamma_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %gamma_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::gamma_distribution<_RealType1>& __x); /** * @brief Extracts a %gamma_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %gamma_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::gamma_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::normal_distribution _M_nd; }; /** * @brief Return true if two gamma distributions are different. */ template inline bool operator!=(const std::gamma_distribution<_RealType>& __d1, const std::gamma_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A chi_squared_distribution random number distribution. * * The formula for the normal probability mass function is * @f$p(x|n) = \frac{x^{(n/2) - 1}e^{-x/2}}{\Gamma(n/2) 2^{n/2}}@f$ */ template class chi_squared_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef chi_squared_distribution<_RealType> distribution_type; explicit param_type(_RealType __n = _RealType(1)) : _M_n(__n) { } _RealType n() const { return _M_n; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_n == __p2._M_n; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_n; }; explicit chi_squared_distribution(_RealType __n = _RealType(1)) : _M_param(__n), _M_gd(__n / 2) { } explicit chi_squared_distribution(const param_type& __p) : _M_param(__p), _M_gd(__p.n() / 2) { } /** * @brief Resets the distribution state. */ void reset() { _M_gd.reset(); } /** * */ _RealType n() const { return _M_param.n(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; typedef typename std::gamma_distribution::param_type param_type; _M_gd.param(param_type{__param.n() / 2}); } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return 2 * _M_gd(__urng); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; return 2 * _M_gd(__urng, param_type(__p.n() / 2)); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { typename std::gamma_distribution::param_type __p2(__p.n() / 2); this->__generate_impl(__f, __t, __urng, __p2); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { typename std::gamma_distribution::param_type __p2(__p.n() / 2); this->__generate_impl(__f, __t, __urng, __p2); } /** * @brief Return true if two Chi-squared distributions have * the same parameters and the sequences that would be * generated are equal. */ friend bool operator==(const chi_squared_distribution& __d1, const chi_squared_distribution& __d2) { return __d1._M_param == __d2._M_param && __d1._M_gd == __d2._M_gd; } /** * @brief Inserts a %chi_squared_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %chi_squared_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::chi_squared_distribution<_RealType1>& __x); /** * @brief Extracts a %chi_squared_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %chi_squared_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::chi_squared_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const typename std::gamma_distribution::param_type& __p); param_type _M_param; std::gamma_distribution _M_gd; }; /** * @brief Return true if two Chi-squared distributions are different. */ template inline bool operator!=(const std::chi_squared_distribution<_RealType>& __d1, const std::chi_squared_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A cauchy_distribution random number distribution. * * The formula for the normal probability mass function is * @f$p(x|a,b) = (\pi b (1 + (\frac{x-a}{b})^2))^{-1}@f$ */ template class cauchy_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef cauchy_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { } _RealType a() const { return _M_a; } _RealType b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; explicit cauchy_distribution(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit cauchy_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * */ _RealType a() const { return _M_param.a(); } _RealType b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Cauchy distributions have * the same parameters. */ friend bool operator==(const cauchy_distribution& __d1, const cauchy_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two Cauchy distributions have * different parameters. */ template inline bool operator!=(const std::cauchy_distribution<_RealType>& __d1, const std::cauchy_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %cauchy_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %cauchy_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::cauchy_distribution<_RealType>& __x); /** * @brief Extracts a %cauchy_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %cauchy_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::cauchy_distribution<_RealType>& __x); /** * @brief A fisher_f_distribution random number distribution. * * The formula for the normal probability mass function is * @f[ * p(x|m,n) = \frac{\Gamma((m+n)/2)}{\Gamma(m/2)\Gamma(n/2)} * (\frac{m}{n})^{m/2} x^{(m/2)-1} * (1 + \frac{mx}{n})^{-(m+n)/2} * @f] */ template class fisher_f_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef fisher_f_distribution<_RealType> distribution_type; explicit param_type(_RealType __m = _RealType(1), _RealType __n = _RealType(1)) : _M_m(__m), _M_n(__n) { } _RealType m() const { return _M_m; } _RealType n() const { return _M_n; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_m == __p2._M_m && __p1._M_n == __p2._M_n; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_m; _RealType _M_n; }; explicit fisher_f_distribution(_RealType __m = _RealType(1), _RealType __n = _RealType(1)) : _M_param(__m, __n), _M_gd_x(__m / 2), _M_gd_y(__n / 2) { } explicit fisher_f_distribution(const param_type& __p) : _M_param(__p), _M_gd_x(__p.m() / 2), _M_gd_y(__p.n() / 2) { } /** * @brief Resets the distribution state. */ void reset() { _M_gd_x.reset(); _M_gd_y.reset(); } /** * */ _RealType m() const { return _M_param.m(); } _RealType n() const { return _M_param.n(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return (_M_gd_x(__urng) * n()) / (_M_gd_y(__urng) * m()); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; return ((_M_gd_x(__urng, param_type(__p.m() / 2)) * n()) / (_M_gd_y(__urng, param_type(__p.n() / 2)) * m())); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Fisher f distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const fisher_f_distribution& __d1, const fisher_f_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_gd_x == __d2._M_gd_x && __d1._M_gd_y == __d2._M_gd_y); } /** * @brief Inserts a %fisher_f_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %fisher_f_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::fisher_f_distribution<_RealType1>& __x); /** * @brief Extracts a %fisher_f_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %fisher_f_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::fisher_f_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::gamma_distribution _M_gd_x, _M_gd_y; }; /** * @brief Return true if two Fisher f distributions are different. */ template inline bool operator!=(const std::fisher_f_distribution<_RealType>& __d1, const std::fisher_f_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A student_t_distribution random number distribution. * * The formula for the normal probability mass function is: * @f[ * p(x|n) = \frac{1}{\sqrt(n\pi)} \frac{\Gamma((n+1)/2)}{\Gamma(n/2)} * (1 + \frac{x^2}{n}) ^{-(n+1)/2} * @f] */ template class student_t_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef student_t_distribution<_RealType> distribution_type; explicit param_type(_RealType __n = _RealType(1)) : _M_n(__n) { } _RealType n() const { return _M_n; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_n == __p2._M_n; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_n; }; explicit student_t_distribution(_RealType __n = _RealType(1)) : _M_param(__n), _M_nd(), _M_gd(__n / 2, 2) { } explicit student_t_distribution(const param_type& __p) : _M_param(__p), _M_nd(), _M_gd(__p.n() / 2, 2) { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); _M_gd.reset(); } /** * */ _RealType n() const { return _M_param.n(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return _M_nd(__urng) * std::sqrt(n() / _M_gd(__urng)); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; const result_type __g = _M_gd(__urng, param_type(__p.n() / 2, 2)); return _M_nd(__urng) * std::sqrt(__p.n() / __g); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Student t distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const student_t_distribution& __d1, const student_t_distribution& __d2) { return (__d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd && __d1._M_gd == __d2._M_gd); } /** * @brief Inserts a %student_t_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %student_t_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::student_t_distribution<_RealType1>& __x); /** * @brief Extracts a %student_t_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %student_t_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::student_t_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::normal_distribution _M_nd; std::gamma_distribution _M_gd; }; /** * @brief Return true if two Student t distributions are different. */ template inline bool operator!=(const std::student_t_distribution<_RealType>& __d1, const std::student_t_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /* @} */ // group random_distributions_normal /** * @addtogroup random_distributions_bernoulli Bernoulli Distributions * @ingroup random_distributions * @{ */ /** * @brief A Bernoulli random number distribution. * * Generates a sequence of true and false values with likelihood @f$p@f$ * that true will come up and @f$(1 - p)@f$ that false will appear. */ class bernoulli_distribution { public: /** The type of the range of the distribution. */ typedef bool result_type; /** Parameter type. */ struct param_type { typedef bernoulli_distribution distribution_type; explicit param_type(double __p = 0.5) : _M_p(__p) { __glibcxx_assert((_M_p >= 0.0) && (_M_p <= 1.0)); } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: double _M_p; }; public: /** * @brief Constructs a Bernoulli distribution with likelihood @p p. * * @param __p [IN] The likelihood of a true result being returned. * Must be in the interval @f$[0, 1]@f$. */ explicit bernoulli_distribution(double __p = 0.5) : _M_param(__p) { } explicit bernoulli_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for a Bernoulli distribution. */ void reset() { } /** * @brief Returns the @p p parameter of the distribution. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::min(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); if ((__aurng() - __aurng.min()) < __p.p() * (__aurng.max() - __aurng.min())) return true; return false; } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Bernoulli distributions have * the same parameters. */ friend bool operator==(const bernoulli_distribution& __d1, const bernoulli_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two Bernoulli distributions have * different parameters. */ inline bool operator!=(const std::bernoulli_distribution& __d1, const std::bernoulli_distribution& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %bernoulli_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %bernoulli_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::bernoulli_distribution& __x); /** * @brief Extracts a %bernoulli_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %bernoulli_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::bernoulli_distribution& __x) { double __p; if (__is >> __p) __x.param(bernoulli_distribution::param_type(__p)); return __is; } /** * @brief A discrete binomial random number distribution. * * The formula for the binomial probability density function is * @f$p(i|t,p) = \binom{t}{i} p^i (1 - p)^{t - i}@f$ where @f$t@f$ * and @f$p@f$ are the parameters of the distribution. */ template class binomial_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef binomial_distribution<_IntType> distribution_type; friend class binomial_distribution<_IntType>; explicit param_type(_IntType __t = _IntType(1), double __p = 0.5) : _M_t(__t), _M_p(__p) { __glibcxx_assert((_M_t >= _IntType(0)) && (_M_p >= 0.0) && (_M_p <= 1.0)); _M_initialize(); } _IntType t() const { return _M_t; } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_t == __p2._M_t && __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); _IntType _M_t; double _M_p; double _M_q; #if _GLIBCXX_USE_C99_MATH_TR1 double _M_d1, _M_d2, _M_s1, _M_s2, _M_c, _M_a1, _M_a123, _M_s, _M_lf, _M_lp1p; #endif bool _M_easy; }; // constructors and member function explicit binomial_distribution(_IntType __t = _IntType(1), double __p = 0.5) : _M_param(__t, __p), _M_nd() { } explicit binomial_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * @brief Returns the distribution @p t parameter. */ _IntType t() const { return _M_param.t(); } /** * @brief Returns the distribution @p p parameter. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return 0; } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param.t(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two binomial distributions have * the same parameters and the sequences that would * be generated are equal. */ friend bool operator==(const binomial_distribution& __d1, const binomial_distribution& __d2) #ifdef _GLIBCXX_USE_C99_MATH_TR1 { return __d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd; } #else { return __d1._M_param == __d2._M_param; } #endif /** * @brief Inserts a %binomial_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %binomial_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::binomial_distribution<_IntType1>& __x); /** * @brief Extracts a %binomial_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %binomial_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::binomial_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); template result_type _M_waiting(_UniformRandomNumberGenerator& __urng, _IntType __t, double __q); param_type _M_param; // NB: Unused when _GLIBCXX_USE_C99_MATH_TR1 is undefined. std::normal_distribution _M_nd; }; /** * @brief Return true if two binomial distributions are different. */ template inline bool operator!=(const std::binomial_distribution<_IntType>& __d1, const std::binomial_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief A discrete geometric random number distribution. * * The formula for the geometric probability density function is * @f$p(i|p) = p(1 - p)^{i}@f$ where @f$p@f$ is the parameter of the * distribution. */ template class geometric_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef geometric_distribution<_IntType> distribution_type; friend class geometric_distribution<_IntType>; explicit param_type(double __p = 0.5) : _M_p(__p) { __glibcxx_assert((_M_p > 0.0) && (_M_p < 1.0)); _M_initialize(); } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize() { _M_log_1_p = std::log(1.0 - _M_p); } double _M_p; double _M_log_1_p; }; // constructors and member function explicit geometric_distribution(double __p = 0.5) : _M_param(__p) { } explicit geometric_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for the geometric distribution. */ void reset() { } /** * @brief Returns the distribution parameter @p p. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return 0; } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two geometric distributions have * the same parameters. */ friend bool operator==(const geometric_distribution& __d1, const geometric_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two geometric distributions have * different parameters. */ template inline bool operator!=(const std::geometric_distribution<_IntType>& __d1, const std::geometric_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %geometric_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %geometric_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::geometric_distribution<_IntType>& __x); /** * @brief Extracts a %geometric_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %geometric_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::geometric_distribution<_IntType>& __x); /** * @brief A negative_binomial_distribution random number distribution. * * The formula for the negative binomial probability mass function is * @f$p(i) = \binom{n}{i} p^i (1 - p)^{t - i}@f$ where @f$t@f$ * and @f$p@f$ are the parameters of the distribution. */ template class negative_binomial_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef negative_binomial_distribution<_IntType> distribution_type; explicit param_type(_IntType __k = 1, double __p = 0.5) : _M_k(__k), _M_p(__p) { __glibcxx_assert((_M_k > 0) && (_M_p > 0.0) && (_M_p <= 1.0)); } _IntType k() const { return _M_k; } double p() const { return _M_p; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_k == __p2._M_k && __p1._M_p == __p2._M_p; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _IntType _M_k; double _M_p; }; explicit negative_binomial_distribution(_IntType __k = 1, double __p = 0.5) : _M_param(__k, __p), _M_gd(__k, (1.0 - __p) / __p) { } explicit negative_binomial_distribution(const param_type& __p) : _M_param(__p), _M_gd(__p.k(), (1.0 - __p.p()) / __p.p()) { } /** * @brief Resets the distribution state. */ void reset() { _M_gd.reset(); } /** * @brief Return the @f$k@f$ parameter of the distribution. */ _IntType k() const { return _M_param.k(); } /** * @brief Return the @f$p@f$ parameter of the distribution. */ double p() const { return _M_param.p(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng); template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng) { this->__generate_impl(__f, __t, __urng); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two negative binomial distributions have * the same parameters and the sequences that would be * generated are equal. */ friend bool operator==(const negative_binomial_distribution& __d1, const negative_binomial_distribution& __d2) { return __d1._M_param == __d2._M_param && __d1._M_gd == __d2._M_gd; } /** * @brief Inserts a %negative_binomial_distribution random * number distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %negative_binomial_distribution random number * distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::negative_binomial_distribution<_IntType1>& __x); /** * @brief Extracts a %negative_binomial_distribution random number * distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %negative_binomial_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::negative_binomial_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng); template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; std::gamma_distribution _M_gd; }; /** * @brief Return true if two negative binomial distributions are different. */ template inline bool operator!=(const std::negative_binomial_distribution<_IntType>& __d1, const std::negative_binomial_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /* @} */ // group random_distributions_bernoulli /** * @addtogroup random_distributions_poisson Poisson Distributions * @ingroup random_distributions * @{ */ /** * @brief A discrete Poisson random number distribution. * * The formula for the Poisson probability density function is * @f$p(i|\mu) = \frac{\mu^i}{i!} e^{-\mu}@f$ where @f$\mu@f$ is the * parameter of the distribution. */ template class poisson_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef poisson_distribution<_IntType> distribution_type; friend class poisson_distribution<_IntType>; explicit param_type(double __mean = 1.0) : _M_mean(__mean) { __glibcxx_assert(_M_mean > 0.0); _M_initialize(); } double mean() const { return _M_mean; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_mean == __p2._M_mean; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: // Hosts either log(mean) or the threshold of the simple method. void _M_initialize(); double _M_mean; double _M_lm_thr; #if _GLIBCXX_USE_C99_MATH_TR1 double _M_lfm, _M_sm, _M_d, _M_scx, _M_1cx, _M_c2b, _M_cb; #endif }; // constructors and member function explicit poisson_distribution(double __mean = 1.0) : _M_param(__mean), _M_nd() { } explicit poisson_distribution(const param_type& __p) : _M_param(__p), _M_nd() { } /** * @brief Resets the distribution state. */ void reset() { _M_nd.reset(); } /** * @brief Returns the distribution parameter @p mean. */ double mean() const { return _M_param.mean(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return 0; } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Poisson distributions have the same * parameters and the sequences that would be generated * are equal. */ friend bool operator==(const poisson_distribution& __d1, const poisson_distribution& __d2) #ifdef _GLIBCXX_USE_C99_MATH_TR1 { return __d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd; } #else { return __d1._M_param == __d2._M_param; } #endif /** * @brief Inserts a %poisson_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %poisson_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::poisson_distribution<_IntType1>& __x); /** * @brief Extracts a %poisson_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %poisson_distribution random number generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::poisson_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; // NB: Unused when _GLIBCXX_USE_C99_MATH_TR1 is undefined. std::normal_distribution _M_nd; }; /** * @brief Return true if two Poisson distributions are different. */ template inline bool operator!=(const std::poisson_distribution<_IntType>& __d1, const std::poisson_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief An exponential continuous distribution for random numbers. * * The formula for the exponential probability density function is * @f$p(x|\lambda) = \lambda e^{-\lambda x}@f$. * * * * * * * * *
Distribution Statistics
Mean@f$\frac{1}{\lambda}@f$
Median@f$\frac{\ln 2}{\lambda}@f$
Mode@f$zero@f$
Range@f$[0, \infty]@f$
Standard Deviation@f$\frac{1}{\lambda}@f$
*/ template class exponential_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef exponential_distribution<_RealType> distribution_type; explicit param_type(_RealType __lambda = _RealType(1)) : _M_lambda(__lambda) { __glibcxx_assert(_M_lambda > _RealType(0)); } _RealType lambda() const { return _M_lambda; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_lambda == __p2._M_lambda; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_lambda; }; public: /** * @brief Constructs an exponential distribution with inverse scale * parameter @f$\lambda@f$. */ explicit exponential_distribution(const result_type& __lambda = result_type(1)) : _M_param(__lambda) { } explicit exponential_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Has no effect on exponential distributions. */ void reset() { } /** * @brief Returns the inverse scale parameter of the distribution. */ _RealType lambda() const { return _M_param.lambda(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return -std::log(result_type(1) - __aurng()) / __p.lambda(); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two exponential distributions have the same * parameters. */ friend bool operator==(const exponential_distribution& __d1, const exponential_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two exponential distributions have different * parameters. */ template inline bool operator!=(const std::exponential_distribution<_RealType>& __d1, const std::exponential_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %exponential_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %exponential_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::exponential_distribution<_RealType>& __x); /** * @brief Extracts a %exponential_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %exponential_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::exponential_distribution<_RealType>& __x); /** * @brief A weibull_distribution random number distribution. * * The formula for the normal probability density function is: * @f[ * p(x|\alpha,\beta) = \frac{\alpha}{\beta} (\frac{x}{\beta})^{\alpha-1} * \exp{(-(\frac{x}{\beta})^\alpha)} * @f] */ template class weibull_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef weibull_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(1), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { } _RealType a() const { return _M_a; } _RealType b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; explicit weibull_distribution(_RealType __a = _RealType(1), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit weibull_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Return the @f$a@f$ parameter of the distribution. */ _RealType a() const { return _M_param.a(); } /** * @brief Return the @f$b@f$ parameter of the distribution. */ _RealType b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two Weibull distributions have the same * parameters. */ friend bool operator==(const weibull_distribution& __d1, const weibull_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two Weibull distributions have different * parameters. */ template inline bool operator!=(const std::weibull_distribution<_RealType>& __d1, const std::weibull_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %weibull_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %weibull_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::weibull_distribution<_RealType>& __x); /** * @brief Extracts a %weibull_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %weibull_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::weibull_distribution<_RealType>& __x); /** * @brief A extreme_value_distribution random number distribution. * * The formula for the normal probability mass function is * @f[ * p(x|a,b) = \frac{1}{b} * \exp( \frac{a-x}{b} - \exp(\frac{a-x}{b})) * @f] */ template class extreme_value_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef extreme_value_distribution<_RealType> distribution_type; explicit param_type(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_a(__a), _M_b(__b) { } _RealType a() const { return _M_a; } _RealType b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _RealType _M_a; _RealType _M_b; }; explicit extreme_value_distribution(_RealType __a = _RealType(0), _RealType __b = _RealType(1)) : _M_param(__a, __b) { } explicit extreme_value_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Return the @f$a@f$ parameter of the distribution. */ _RealType a() const { return _M_param.a(); } /** * @brief Return the @f$b@f$ parameter of the distribution. */ _RealType b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return std::numeric_limits::lowest(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return std::numeric_limits::max(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two extreme value distributions have the same * parameters. */ friend bool operator==(const extreme_value_distribution& __d1, const extreme_value_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two extreme value distributions have different * parameters. */ template inline bool operator!=(const std::extreme_value_distribution<_RealType>& __d1, const std::extreme_value_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief Inserts a %extreme_value_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %extreme_value_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::extreme_value_distribution<_RealType>& __x); /** * @brief Extracts a %extreme_value_distribution random number * distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %extreme_value_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error state. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::extreme_value_distribution<_RealType>& __x); /** * @brief A discrete_distribution random number distribution. * * The formula for the discrete probability mass function is * */ template class discrete_distribution { static_assert(std::is_integral<_IntType>::value, "result_type must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef discrete_distribution<_IntType> distribution_type; friend class discrete_distribution<_IntType>; param_type() : _M_prob(), _M_cp() { } template param_type(_InputIterator __wbegin, _InputIterator __wend) : _M_prob(__wbegin, __wend), _M_cp() { _M_initialize(); } param_type(initializer_list __wil) : _M_prob(__wil.begin(), __wil.end()), _M_cp() { _M_initialize(); } template param_type(size_t __nw, double __xmin, double __xmax, _Func __fw); // See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/ param_type(const param_type&) = default; param_type& operator=(const param_type&) = default; std::vector probabilities() const { return _M_prob.empty() ? std::vector(1, 1.0) : _M_prob; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_prob == __p2._M_prob; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); std::vector _M_prob; std::vector _M_cp; }; discrete_distribution() : _M_param() { } template discrete_distribution(_InputIterator __wbegin, _InputIterator __wend) : _M_param(__wbegin, __wend) { } discrete_distribution(initializer_list __wl) : _M_param(__wl) { } template discrete_distribution(size_t __nw, double __xmin, double __xmax, _Func __fw) : _M_param(__nw, __xmin, __xmax, __fw) { } explicit discrete_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Returns the probabilities of the distribution. */ std::vector probabilities() const { return _M_param._M_prob.empty() ? std::vector(1, 1.0) : _M_param._M_prob; } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return result_type(0); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param._M_prob.empty() ? result_type(0) : result_type(_M_param._M_prob.size() - 1); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two discrete distributions have the same * parameters. */ friend bool operator==(const discrete_distribution& __d1, const discrete_distribution& __d2) { return __d1._M_param == __d2._M_param; } /** * @brief Inserts a %discrete_distribution random number distribution * @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %discrete_distribution random number distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::discrete_distribution<_IntType1>& __x); /** * @brief Extracts a %discrete_distribution random number distribution * @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %discrete_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::discrete_distribution<_IntType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two discrete distributions have different * parameters. */ template inline bool operator!=(const std::discrete_distribution<_IntType>& __d1, const std::discrete_distribution<_IntType>& __d2) { return !(__d1 == __d2); } /** * @brief A piecewise_constant_distribution random number distribution. * * The formula for the piecewise constant probability mass function is * */ template class piecewise_constant_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef piecewise_constant_distribution<_RealType> distribution_type; friend class piecewise_constant_distribution<_RealType>; param_type() : _M_int(), _M_den(), _M_cp() { } template param_type(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin); template param_type(initializer_list<_RealType> __bi, _Func __fw); template param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw); // See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/ param_type(const param_type&) = default; param_type& operator=(const param_type&) = default; std::vector<_RealType> intervals() const { if (_M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_int; } std::vector densities() const { return _M_den.empty() ? std::vector(1, 1.0) : _M_den; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_int == __p2._M_int && __p1._M_den == __p2._M_den; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); std::vector<_RealType> _M_int; std::vector _M_den; std::vector _M_cp; }; explicit piecewise_constant_distribution() : _M_param() { } template piecewise_constant_distribution(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_param(__bfirst, __bend, __wbegin) { } template piecewise_constant_distribution(initializer_list<_RealType> __bl, _Func __fw) : _M_param(__bl, __fw) { } template piecewise_constant_distribution(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_param(__nw, __xmin, __xmax, __fw) { } explicit piecewise_constant_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. */ void reset() { } /** * @brief Returns a vector of the intervals. */ std::vector<_RealType> intervals() const { if (_M_param._M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_param._M_int; } /** * @brief Returns a vector of the probability densities. */ std::vector densities() const { return _M_param._M_den.empty() ? std::vector(1, 1.0) : _M_param._M_den; } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return _M_param._M_int.empty() ? result_type(0) : _M_param._M_int.front(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param._M_int.empty() ? result_type(1) : _M_param._M_int.back(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two piecewise constant distributions have the * same parameters. */ friend bool operator==(const piecewise_constant_distribution& __d1, const piecewise_constant_distribution& __d2) { return __d1._M_param == __d2._M_param; } /** * @brief Inserts a %piecewise_constant_distribution random * number distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %piecewise_constant_distribution random number * distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::piecewise_constant_distribution<_RealType1>& __x); /** * @brief Extracts a %piecewise_constant_distribution random * number distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %piecewise_constant_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::piecewise_constant_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two piecewise constant distributions have * different parameters. */ template inline bool operator!=(const std::piecewise_constant_distribution<_RealType>& __d1, const std::piecewise_constant_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /** * @brief A piecewise_linear_distribution random number distribution. * * The formula for the piecewise linear probability mass function is * */ template class piecewise_linear_distribution { static_assert(std::is_floating_point<_RealType>::value, "result_type must be a floating point type"); public: /** The type of the range of the distribution. */ typedef _RealType result_type; /** Parameter type. */ struct param_type { typedef piecewise_linear_distribution<_RealType> distribution_type; friend class piecewise_linear_distribution<_RealType>; param_type() : _M_int(), _M_den(), _M_cp(), _M_m() { } template param_type(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin); template param_type(initializer_list<_RealType> __bl, _Func __fw); template param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw); // See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/ param_type(const param_type&) = default; param_type& operator=(const param_type&) = default; std::vector<_RealType> intervals() const { if (_M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_int; } std::vector densities() const { return _M_den.empty() ? std::vector(2, 1.0) : _M_den; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_int == __p2._M_int && __p1._M_den == __p2._M_den; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: void _M_initialize(); std::vector<_RealType> _M_int; std::vector _M_den; std::vector _M_cp; std::vector _M_m; }; explicit piecewise_linear_distribution() : _M_param() { } template piecewise_linear_distribution(_InputIteratorB __bfirst, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_param(__bfirst, __bend, __wbegin) { } template piecewise_linear_distribution(initializer_list<_RealType> __bl, _Func __fw) : _M_param(__bl, __fw) { } template piecewise_linear_distribution(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_param(__nw, __xmin, __xmax, __fw) { } explicit piecewise_linear_distribution(const param_type& __p) : _M_param(__p) { } /** * Resets the distribution state. */ void reset() { } /** * @brief Return the intervals of the distribution. */ std::vector<_RealType> intervals() const { if (_M_param._M_int.empty()) { std::vector<_RealType> __tmp(2); __tmp[1] = _RealType(1); return __tmp; } else return _M_param._M_int; } /** * @brief Return a vector of the probability densities of the * distribution. */ std::vector densities() const { return _M_param._M_den.empty() ? std::vector(2, 1.0) : _M_param._M_den; } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the greatest lower bound value of the distribution. */ result_type min() const { return _M_param._M_int.empty() ? result_type(0) : _M_param._M_int.front(); } /** * @brief Returns the least upper bound value of the distribution. */ result_type max() const { return _M_param._M_int.empty() ? result_type(1) : _M_param._M_int.back(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two piecewise linear distributions have the * same parameters. */ friend bool operator==(const piecewise_linear_distribution& __d1, const piecewise_linear_distribution& __d2) { return __d1._M_param == __d2._M_param; } /** * @brief Inserts a %piecewise_linear_distribution random number * distribution @p __x into the output stream @p __os. * * @param __os An output stream. * @param __x A %piecewise_linear_distribution random number * distribution. * * @returns The output stream with the state of @p __x inserted or in * an error state. */ template friend std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const std::piecewise_linear_distribution<_RealType1>& __x); /** * @brief Extracts a %piecewise_linear_distribution random number * distribution @p __x from the input stream @p __is. * * @param __is An input stream. * @param __x A %piecewise_linear_distribution random number * generator engine. * * @returns The input stream with @p __x extracted or in an error * state. */ template friend std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, std::piecewise_linear_distribution<_RealType1>& __x); private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; /** * @brief Return true if two piecewise linear distributions have * different parameters. */ template inline bool operator!=(const std::piecewise_linear_distribution<_RealType>& __d1, const std::piecewise_linear_distribution<_RealType>& __d2) { return !(__d1 == __d2); } /* @} */ // group random_distributions_poisson /* @} */ // group random_distributions /** * @addtogroup random_utilities Random Number Utilities * @ingroup random * @{ */ /** * @brief The seed_seq class generates sequences of seeds for random * number generators. */ class seed_seq { public: /** The type of the seed vales. */ typedef uint_least32_t result_type; /** Default constructor. */ seed_seq() noexcept : _M_v() { } template seed_seq(std::initializer_list<_IntType> __il); template seed_seq(_InputIterator __begin, _InputIterator __end); // generating functions template void generate(_RandomAccessIterator __begin, _RandomAccessIterator __end); // property functions size_t size() const noexcept { return _M_v.size(); } template void param(_OutputIterator __dest) const { std::copy(_M_v.begin(), _M_v.end(), __dest); } // no copy functions seed_seq(const seed_seq&) = delete; seed_seq& operator=(const seed_seq&) = delete; private: std::vector _M_v; }; /* @} */ // group random_utilities /* @} */ // group random _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/regex_automaton.tcc000064400000017236151027430570012135 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_automaton.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { #ifdef _GLIBCXX_DEBUG inline std::ostream& _State_base::_M_print(std::ostream& ostr) const { switch (_M_opcode) { case _S_opcode_alternative: case _S_opcode_repeat: ostr << "alt next=" << _M_next << " alt=" << _M_alt; break; case _S_opcode_subexpr_begin: ostr << "subexpr begin next=" << _M_next << " index=" << _M_subexpr; break; case _S_opcode_subexpr_end: ostr << "subexpr end next=" << _M_next << " index=" << _M_subexpr; break; case _S_opcode_backref: ostr << "backref next=" << _M_next << " index=" << _M_backref_index; break; case _S_opcode_match: ostr << "match next=" << _M_next; break; case _S_opcode_accept: ostr << "accept next=" << _M_next; break; default: ostr << "unknown next=" << _M_next; break; } return ostr; } // Prints graphviz dot commands for state. inline std::ostream& _State_base::_M_dot(std::ostream& __ostr, _StateIdT __id) const { switch (_M_opcode) { case _S_opcode_alternative: case _S_opcode_repeat: __ostr << __id << " [label=\"" << __id << "\\nALT\"];\n" << __id << " -> " << _M_next << " [label=\"next\", tailport=\"s\"];\n" << __id << " -> " << _M_alt << " [label=\"alt\", tailport=\"n\"];\n"; break; case _S_opcode_backref: __ostr << __id << " [label=\"" << __id << "\\nBACKREF " << _M_subexpr << "\"];\n" << __id << " -> " << _M_next << " [label=\"\"];\n"; break; case _S_opcode_line_begin_assertion: __ostr << __id << " [label=\"" << __id << "\\nLINE_BEGIN \"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_line_end_assertion: __ostr << __id << " [label=\"" << __id << "\\nLINE_END \"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_word_boundary: __ostr << __id << " [label=\"" << __id << "\\nWORD_BOUNDRY " << _M_neg << "\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_subexpr_lookahead: __ostr << __id << " [label=\"" << __id << "\\nLOOK_AHEAD\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\", tailport=\"s\"];\n" << __id << " -> " << _M_alt << " [label=\"\", tailport=\"n\"];\n"; break; case _S_opcode_subexpr_begin: __ostr << __id << " [label=\"" << __id << "\\nSBEGIN " << _M_subexpr << "\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_subexpr_end: __ostr << __id << " [label=\"" << __id << "\\nSEND " << _M_subexpr << "\"];\n" << __id << " -> " << _M_next << " [label=\"epsilon\"];\n"; break; case _S_opcode_dummy: break; case _S_opcode_match: __ostr << __id << " [label=\"" << __id << "\\nMATCH\"];\n" << __id << " -> " << _M_next << " [label=\"\"];\n"; break; case _S_opcode_accept: __ostr << __id << " [label=\"" << __id << "\\nACC\"];\n" ; break; default: _GLIBCXX_DEBUG_ASSERT(false); break; } return __ostr; } template std::ostream& _NFA<_TraitsT>::_M_dot(std::ostream& __ostr) const { __ostr << "digraph _Nfa {\n" " rankdir=LR;\n"; for (size_t __i = 0; __i < this->size(); ++__i) (*this)[__i]._M_dot(__ostr, __i); __ostr << "}\n"; return __ostr; } #endif template _StateIdT _NFA<_TraitsT>::_M_insert_backref(size_t __index) { if (this->_M_flags & regex_constants::__polynomial) __throw_regex_error(regex_constants::error_complexity, "Unexpected back-reference in polynomial mode."); // To figure out whether a backref is valid, a stack is used to store // unfinished sub-expressions. For example, when parsing // "(a(b)(c\\1(d)))" at '\\1', _M_subexpr_count is 3, indicating that 3 // sub expressions are parsed or partially parsed(in the stack), aka, // "(a..", "(b)" and "(c.."). // _M_paren_stack is {1, 3}, for incomplete "(a.." and "(c..". At this // time, "\\2" is valid, but "\\1" and "\\3" are not. if (__index >= _M_subexpr_count) __throw_regex_error( regex_constants::error_backref, "Back-reference index exceeds current sub-expression count."); for (auto __it : this->_M_paren_stack) if (__index == __it) __throw_regex_error( regex_constants::error_backref, "Back-reference referred to an opened sub-expression."); this->_M_has_backref = true; _StateT __tmp(_S_opcode_backref); __tmp._M_backref_index = __index; return _M_insert_state(std::move(__tmp)); } template void _NFA<_TraitsT>::_M_eliminate_dummy() { for (auto& __it : *this) { while (__it._M_next >= 0 && (*this)[__it._M_next]._M_opcode() == _S_opcode_dummy) __it._M_next = (*this)[__it._M_next]._M_next; if (__it._M_has_alt()) while (__it._M_alt >= 0 && (*this)[__it._M_alt]._M_opcode() == _S_opcode_dummy) __it._M_alt = (*this)[__it._M_alt]._M_next; } } // Just apply DFS on the sequence and re-link their links. template _StateSeq<_TraitsT> _StateSeq<_TraitsT>::_M_clone() { std::map<_StateIdT, _StateIdT> __m; std::stack<_StateIdT> __stack; __stack.push(_M_start); while (!__stack.empty()) { auto __u = __stack.top(); __stack.pop(); auto __dup = _M_nfa[__u]; // _M_insert_state() never return -1 auto __id = _M_nfa._M_insert_state(std::move(__dup)); __m[__u] = __id; if (__dup._M_has_alt()) if (__dup._M_alt != _S_invalid_state_id && __m.count(__dup._M_alt) == 0) __stack.push(__dup._M_alt); if (__u == _M_end) continue; if (__dup._M_next != _S_invalid_state_id && __m.count(__dup._M_next) == 0) __stack.push(__dup._M_next); } for (auto __it : __m) { auto __v = __it.second; auto& __ref = _M_nfa[__v]; if (__ref._M_next != _S_invalid_state_id) { __glibcxx_assert(__m.count(__ref._M_next) > 0); __ref._M_next = __m[__ref._M_next]; } if (__ref._M_has_alt()) if (__ref._M_alt != _S_invalid_state_id) { __glibcxx_assert(__m.count(__ref._M_alt) > 0); __ref._M_alt = __m[__ref._M_alt]; } } return _StateSeq(_M_nfa, __m[_M_start], __m[_M_end]); } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/bits/stl_uninitialized.h000064400000066075151027430570012151 0ustar00// Raw memory manipulators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_uninitialized.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_UNINITIALIZED_H #define _STL_UNINITIALIZED_H 1 #if __cplusplus > 201402L #include #endif #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template struct __uninitialized_copy { template static _ForwardIterator __uninit_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { _ForwardIterator __cur = __result; __try { for (; __first != __last; ++__first, (void)++__cur) std::_Construct(std::__addressof(*__cur), *__first); return __cur; } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_copy { template static _ForwardIterator __uninit_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { return std::copy(__first, __last, __result); } }; /** * @brief Copies the range [first,last) into result. * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return __result + (__first - __last) * * Like copy(), but does not require an initialized output range. */ template inline _ForwardIterator uninitialized_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType1; typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType2; #if __cplusplus < 201103L const bool __assignable = true; #else // trivial types can have deleted assignment typedef typename iterator_traits<_InputIterator>::reference _RefType1; typedef typename iterator_traits<_ForwardIterator>::reference _RefType2; const bool __assignable = is_assignable<_RefType2, _RefType1>::value; #endif return std::__uninitialized_copy<__is_trivial(_ValueType1) && __is_trivial(_ValueType2) && __assignable>:: __uninit_copy(__first, __last, __result); } template struct __uninitialized_fill { template static void __uninit_fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x) { _ForwardIterator __cur = __first; __try { for (; __cur != __last; ++__cur) std::_Construct(std::__addressof(*__cur), __x); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_fill { template static void __uninit_fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x) { std::fill(__first, __last, __x); } }; /** * @brief Copies the value x into the range [first,last). * @param __first An input iterator. * @param __last An input iterator. * @param __x The source value. * @return Nothing. * * Like fill(), but does not require an initialized output range. */ template inline void uninitialized_fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; #if __cplusplus < 201103L const bool __assignable = true; #else // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; #endif std::__uninitialized_fill<__is_trivial(_ValueType) && __assignable>:: __uninit_fill(__first, __last, __x); } template struct __uninitialized_fill_n { template static _ForwardIterator __uninit_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x) { _ForwardIterator __cur = __first; __try { for (; __n > 0; --__n, (void) ++__cur) std::_Construct(std::__addressof(*__cur), __x); return __cur; } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_fill_n { template static _ForwardIterator __uninit_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x) { return std::fill_n(__first, __n, __x); } }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 1339. uninitialized_fill_n should return the end of its range /** * @brief Copies the value x into the range [first,first+n). * @param __first An input iterator. * @param __n The number of copies to make. * @param __x The source value. * @return Nothing. * * Like fill_n(), but does not require an initialized output range. */ template inline _ForwardIterator uninitialized_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; #if __cplusplus < 201103L const bool __assignable = true; #else // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; #endif return __uninitialized_fill_n<__is_trivial(_ValueType) && __assignable>:: __uninit_fill_n(__first, __n, __x); } // Extensions: versions of uninitialized_copy, uninitialized_fill, // and uninitialized_fill_n that take an allocator parameter. // We dispatch back to the standard versions when we're given the // default allocator. For nondefault allocators we do not use // any of the POD optimizations. template _ForwardIterator __uninitialized_copy_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _Allocator& __alloc) { _ForwardIterator __cur = __result; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __first != __last; ++__first, (void)++__cur) __traits::construct(__alloc, std::__addressof(*__cur), *__first); return __cur; } __catch(...) { std::_Destroy(__result, __cur, __alloc); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_copy_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, allocator<_Tp>&) { return std::uninitialized_copy(__first, __last, __result); } template inline _ForwardIterator __uninitialized_move_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _Allocator& __alloc) { return std::__uninitialized_copy_a(_GLIBCXX_MAKE_MOVE_ITERATOR(__first), _GLIBCXX_MAKE_MOVE_ITERATOR(__last), __result, __alloc); } template inline _ForwardIterator __uninitialized_move_if_noexcept_a(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _Allocator& __alloc) { return std::__uninitialized_copy_a (_GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(__first), _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(__last), __result, __alloc); } template void __uninitialized_fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __cur != __last; ++__cur) __traits::construct(__alloc, std::__addressof(*__cur), __x); } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline void __uninitialized_fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __x, allocator<_Tp2>&) { std::uninitialized_fill(__first, __last, __x); } template _ForwardIterator __uninitialized_fill_n_a(_ForwardIterator __first, _Size __n, const _Tp& __x, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __n > 0; --__n, (void) ++__cur) __traits::construct(__alloc, std::__addressof(*__cur), __x); return __cur; } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_fill_n_a(_ForwardIterator __first, _Size __n, const _Tp& __x, allocator<_Tp2>&) { return std::uninitialized_fill_n(__first, __n, __x); } // Extensions: __uninitialized_copy_move, __uninitialized_move_copy, // __uninitialized_fill_move, __uninitialized_move_fill. // All of these algorithms take a user-supplied allocator, which is used // for construction and destruction. // __uninitialized_copy_move // Copies [first1, last1) into [result, result + (last1 - first1)), and // move [first2, last2) into // [result, result + (last1 - first1) + (last2 - first2)). template inline _ForwardIterator __uninitialized_copy_move(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _ForwardIterator __result, _Allocator& __alloc) { _ForwardIterator __mid = std::__uninitialized_copy_a(__first1, __last1, __result, __alloc); __try { return std::__uninitialized_move_a(__first2, __last2, __mid, __alloc); } __catch(...) { std::_Destroy(__result, __mid, __alloc); __throw_exception_again; } } // __uninitialized_move_copy // Moves [first1, last1) into [result, result + (last1 - first1)), and // copies [first2, last2) into // [result, result + (last1 - first1) + (last2 - first2)). template inline _ForwardIterator __uninitialized_move_copy(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _ForwardIterator __result, _Allocator& __alloc) { _ForwardIterator __mid = std::__uninitialized_move_a(__first1, __last1, __result, __alloc); __try { return std::__uninitialized_copy_a(__first2, __last2, __mid, __alloc); } __catch(...) { std::_Destroy(__result, __mid, __alloc); __throw_exception_again; } } // __uninitialized_fill_move // Fills [result, mid) with x, and moves [first, last) into // [mid, mid + (last - first)). template inline _ForwardIterator __uninitialized_fill_move(_ForwardIterator __result, _ForwardIterator __mid, const _Tp& __x, _InputIterator __first, _InputIterator __last, _Allocator& __alloc) { std::__uninitialized_fill_a(__result, __mid, __x, __alloc); __try { return std::__uninitialized_move_a(__first, __last, __mid, __alloc); } __catch(...) { std::_Destroy(__result, __mid, __alloc); __throw_exception_again; } } // __uninitialized_move_fill // Moves [first1, last1) into [first2, first2 + (last1 - first1)), and // fills [first2 + (last1 - first1), last2) with x. template inline void __uninitialized_move_fill(_InputIterator __first1, _InputIterator __last1, _ForwardIterator __first2, _ForwardIterator __last2, const _Tp& __x, _Allocator& __alloc) { _ForwardIterator __mid2 = std::__uninitialized_move_a(__first1, __last1, __first2, __alloc); __try { std::__uninitialized_fill_a(__mid2, __last2, __x, __alloc); } __catch(...) { std::_Destroy(__first2, __mid2, __alloc); __throw_exception_again; } } #if __cplusplus >= 201103L // Extensions: __uninitialized_default, __uninitialized_default_n, // __uninitialized_default_a, __uninitialized_default_n_a. template struct __uninitialized_default_1 { template static void __uninit_default(_ForwardIterator __first, _ForwardIterator __last) { _ForwardIterator __cur = __first; __try { for (; __cur != __last; ++__cur) std::_Construct(std::__addressof(*__cur)); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_1 { template static void __uninit_default(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; std::fill(__first, __last, _ValueType()); } }; template struct __uninitialized_default_n_1 { template static _ForwardIterator __uninit_default_n(_ForwardIterator __first, _Size __n) { _ForwardIterator __cur = __first; __try { for (; __n > 0; --__n, (void) ++__cur) std::_Construct(std::__addressof(*__cur)); return __cur; } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_n_1 { template static _ForwardIterator __uninit_default_n(_ForwardIterator __first, _Size __n) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; return std::fill_n(__first, __n, _ValueType()); } }; // __uninitialized_default // Fills [first, last) with std::distance(first, last) default // constructed value_types(s). template inline void __uninitialized_default(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; std::__uninitialized_default_1<__is_trivial(_ValueType) && __assignable>:: __uninit_default(__first, __last); } // __uninitialized_default_n // Fills [first, first + n) with n default constructed value_type(s). template inline _ForwardIterator __uninitialized_default_n(_ForwardIterator __first, _Size __n) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; // trivial types can have deleted assignment const bool __assignable = is_copy_assignable<_ValueType>::value; return __uninitialized_default_n_1<__is_trivial(_ValueType) && __assignable>:: __uninit_default_n(__first, __n); } // __uninitialized_default_a // Fills [first, last) with std::distance(first, last) default // constructed value_types(s), constructed with the allocator alloc. template void __uninitialized_default_a(_ForwardIterator __first, _ForwardIterator __last, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __cur != __last; ++__cur) __traits::construct(__alloc, std::__addressof(*__cur)); } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline void __uninitialized_default_a(_ForwardIterator __first, _ForwardIterator __last, allocator<_Tp>&) { std::__uninitialized_default(__first, __last); } // __uninitialized_default_n_a // Fills [first, first + n) with n default constructed value_types(s), // constructed with the allocator alloc. template _ForwardIterator __uninitialized_default_n_a(_ForwardIterator __first, _Size __n, _Allocator& __alloc) { _ForwardIterator __cur = __first; __try { typedef __gnu_cxx::__alloc_traits<_Allocator> __traits; for (; __n > 0; --__n, (void) ++__cur) __traits::construct(__alloc, std::__addressof(*__cur)); return __cur; } __catch(...) { std::_Destroy(__first, __cur, __alloc); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_default_n_a(_ForwardIterator __first, _Size __n, allocator<_Tp>&) { return std::__uninitialized_default_n(__first, __n); } template struct __uninitialized_default_novalue_1 { template static void __uninit_default_novalue(_ForwardIterator __first, _ForwardIterator __last) { _ForwardIterator __cur = __first; __try { for (; __cur != __last; ++__cur) std::_Construct_novalue(std::__addressof(*__cur)); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_novalue_1 { template static void __uninit_default_novalue(_ForwardIterator __first, _ForwardIterator __last) { } }; template struct __uninitialized_default_novalue_n_1 { template static _ForwardIterator __uninit_default_novalue_n(_ForwardIterator __first, _Size __n) { _ForwardIterator __cur = __first; __try { for (; __n > 0; --__n, (void) ++__cur) std::_Construct_novalue(std::__addressof(*__cur)); return __cur; } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_default_novalue_n_1 { template static _ForwardIterator __uninit_default_novalue_n(_ForwardIterator __first, _Size __n) { return std::next(__first, __n); } }; // __uninitialized_default_novalue // Fills [first, last) with std::distance(first, last) default-initialized // value_types(s). template inline void __uninitialized_default_novalue(_ForwardIterator __first, _ForwardIterator __last) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; std::__uninitialized_default_novalue_1< is_trivially_default_constructible<_ValueType>::value>:: __uninit_default_novalue(__first, __last); } // __uninitialized_default_n // Fills [first, first + n) with n default-initialized value_type(s). template inline _ForwardIterator __uninitialized_default_novalue_n(_ForwardIterator __first, _Size __n) { typedef typename iterator_traits<_ForwardIterator>::value_type _ValueType; return __uninitialized_default_novalue_n_1< is_trivially_default_constructible<_ValueType>::value>:: __uninit_default_novalue_n(__first, __n); } template _ForwardIterator __uninitialized_copy_n(_InputIterator __first, _Size __n, _ForwardIterator __result, input_iterator_tag) { _ForwardIterator __cur = __result; __try { for (; __n > 0; --__n, (void) ++__first, ++__cur) std::_Construct(std::__addressof(*__cur), *__first); return __cur; } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } template inline _ForwardIterator __uninitialized_copy_n(_RandomAccessIterator __first, _Size __n, _ForwardIterator __result, random_access_iterator_tag) { return std::uninitialized_copy(__first, __first + __n, __result); } template pair<_InputIterator, _ForwardIterator> __uninitialized_copy_n_pair(_InputIterator __first, _Size __n, _ForwardIterator __result, input_iterator_tag) { _ForwardIterator __cur = __result; __try { for (; __n > 0; --__n, (void) ++__first, ++__cur) std::_Construct(std::__addressof(*__cur), *__first); return {__first, __cur}; } __catch(...) { std::_Destroy(__result, __cur); __throw_exception_again; } } template inline pair<_RandomAccessIterator, _ForwardIterator> __uninitialized_copy_n_pair(_RandomAccessIterator __first, _Size __n, _ForwardIterator __result, random_access_iterator_tag) { auto __second_res = uninitialized_copy(__first, __first + __n, __result); auto __first_res = std::next(__first, __n); return {__first_res, __second_res}; } /** * @brief Copies the range [first,first+n) into result. * @param __first An input iterator. * @param __n The number of elements to copy. * @param __result An output iterator. * @return __result + __n * * Like copy_n(), but does not require an initialized output range. */ template inline _ForwardIterator uninitialized_copy_n(_InputIterator __first, _Size __n, _ForwardIterator __result) { return std::__uninitialized_copy_n(__first, __n, __result, std::__iterator_category(__first)); } template inline pair<_InputIterator, _ForwardIterator> __uninitialized_copy_n_pair(_InputIterator __first, _Size __n, _ForwardIterator __result) { return std::__uninitialized_copy_n_pair(__first, __n, __result, std::__iterator_category(__first)); } #endif #if __cplusplus >= 201703L # define __cpp_lib_raw_memory_algorithms 201606L template inline void uninitialized_default_construct(_ForwardIterator __first, _ForwardIterator __last) { __uninitialized_default_novalue(__first, __last); } template inline _ForwardIterator uninitialized_default_construct_n(_ForwardIterator __first, _Size __count) { return __uninitialized_default_novalue_n(__first, __count); } template inline void uninitialized_value_construct(_ForwardIterator __first, _ForwardIterator __last) { return __uninitialized_default(__first, __last); } template inline _ForwardIterator uninitialized_value_construct_n(_ForwardIterator __first, _Size __count) { return __uninitialized_default_n(__first, __count); } template inline _ForwardIterator uninitialized_move(_InputIterator __first, _InputIterator __last, _ForwardIterator __result) { return std::uninitialized_copy (_GLIBCXX_MAKE_MOVE_ITERATOR(__first), _GLIBCXX_MAKE_MOVE_ITERATOR(__last), __result); } template inline pair<_InputIterator, _ForwardIterator> uninitialized_move_n(_InputIterator __first, _Size __count, _ForwardIterator __result) { auto __res = std::__uninitialized_copy_n_pair (_GLIBCXX_MAKE_MOVE_ITERATOR(__first), __count, __result); return {__res.first.base(), __res.second}; } #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_UNINITIALIZED_H */ c++/8/bits/stl_multimap.h000064400000121125151027430570011115 0ustar00// Multimap implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_multimap.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{map} */ #ifndef _STL_MULTIMAP_H #define _STL_MULTIMAP_H 1 #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class map; /** * @brief A standard container made up of (key,value) pairs, which can be * retrieved based on a key, in logarithmic time. * * @ingroup associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to * allocator. * * Meets the requirements of a container, a * reversible container, and an * associative container (using equivalent * keys). For a @c multimap the key_type is Key, the mapped_type * is T, and the value_type is std::pair. * * Multimaps support bidirectional iterators. * * The private tree data is declared exactly the same way for map and * multimap; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template , typename _Alloc = std::allocator > > class multimap { public: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Alloc allocator_type; private: #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(value_type, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L && defined(__STRICT_ANSI__) static_assert(is_same::value, "std::multimap must have the same value_type as its allocator"); #endif public: class value_compare : public std::binary_function { friend class multimap<_Key, _Tp, _Compare, _Alloc>; protected: _Compare comp; value_compare(_Compare __c) : comp(__c) { } public: bool operator()(const value_type& __x, const value_type& __y) const { return comp(__x.first, __y.first); } }; private: /// This turns a red-black tree into a [multi]map. typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind::other _Pair_alloc_type; typedef _Rb_tree, key_compare, _Pair_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; typedef __gnu_cxx::__alloc_traits<_Pair_alloc_type> _Alloc_traits; public: // many of these are specified differently in ISO, but the following are // "functionally equivalent" typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Rep_type::iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; typedef typename _Rep_type::reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; #endif // [23.3.2] construct/copy/destroy // (get_allocator() is also listed in this section) /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L multimap() : _M_t() { } #else multimap() = default; #endif /** * @brief Creates a %multimap with no elements. * @param __comp A comparison object. * @param __a An allocator object. */ explicit multimap(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { } /** * @brief %Multimap copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multimap(const multimap& __x) : _M_t(__x._M_t) { } #else multimap(const multimap&) = default; /** * @brief %Multimap move constructor. * * The newly-created %multimap contains the exact contents of the * moved instance. The moved instance is a valid, but unspecified * %multimap. */ multimap(multimap&&) = default; /** * @brief Builds a %multimap from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multimap consisting of copies of the elements from * the initializer_list. This is linear in N if the list is already * sorted, and NlogN otherwise (where N is @a __l.size()). */ multimap(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit multimap(const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { } /// Allocator-extended copy constructor. multimap(const multimap& __m, const allocator_type& __a) : _M_t(__m._M_t, _Pair_alloc_type(__a)) { } /// Allocator-extended move constructor. multimap(multimap&& __m, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__m._M_t), _Pair_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. multimap(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template multimap(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } #endif /** * @brief Builds a %multimap from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %multimap consisting of copies of the elements from * [__first,__last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multimap(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_equal(__first, __last); } /** * @brief Builds a %multimap from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multimap consisting of copies of the elements from * [__first,__last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multimap(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } #if __cplusplus >= 201103L /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~multimap() = default; #endif /** * @brief %Multimap assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multimap& operator=(const multimap& __x) { _M_t = __x._M_t; return *this; } #else multimap& operator=(const multimap&) = default; /// Move assignment operator. multimap& operator=(multimap&&) = default; /** * @brief %Multimap list assignment operator. * @param __l An initializer_list. * * This function fills a %multimap with copies of the elements * in the initializer list @a __l. * * Note that the assignment completely changes the %multimap and * that the resulting %multimap's size is the same as the number * of elements assigned. */ multimap& operator=(initializer_list __l) { _M_t._M_assign_equal(__l.begin(), __l.end()); return *this; } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } // iterators /** * Returns a read/write iterator that points to the first pair in the * %multimap. Iteration is done in ascending order according to the * keys. */ iterator begin() _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points to the first pair * in the %multimap. Iteration is done in ascending order according to * the keys. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read/write iterator that points one past the last pair in * the %multimap. Iteration is done in ascending order according to the * keys. */ iterator end() _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %multimap. Iteration is done in ascending order according * to the keys. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read/write reverse iterator that points to the last pair in * the %multimap. Iteration is done in descending order according to the * keys. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %multimap. Iteration is done in descending order * according to the keys. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read/write reverse iterator that points to one before the * first pair in the %multimap. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return _M_t.rend(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %multimap. Iteration is done in * descending order according to the keys. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first pair * in the %multimap. Iteration is done in ascending order according to * the keys. */ const_iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %multimap. Iteration is done in ascending order according * to the keys. */ const_iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %multimap. Iteration is done in descending order * according to the keys. */ const_reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %multimap. Iteration is done in * descending order according to the keys. */ const_reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif // capacity /** Returns true if the %multimap is empty. */ bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /** Returns the size of the %multimap. */ size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /** Returns the maximum size of the %multimap. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } // modifiers #if __cplusplus >= 201103L /** * @brief Build and insert a std::pair into the %multimap. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return An iterator that points to the inserted (key,value) pair. * * This function builds and inserts a (key, value) %pair into the * %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * * Insertion requires logarithmic time. */ template iterator emplace(_Args&&... __args) { return _M_t._M_emplace_equal(std::forward<_Args>(__args)...); } /** * @brief Builds and inserts a std::pair into the %multimap. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the inserted (key,value) pair. * * This function inserts a (key, value) pair into the %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_equal(__pos, std::forward<_Args>(__args)...); } #endif /** * @brief Inserts a std::pair into the %multimap. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the inserted (key,value) pair. * * This function inserts a (key, value) pair into the %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * * Insertion requires logarithmic time. * @{ */ iterator insert(const value_type& __x) { return _M_t._M_insert_equal(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(value_type&& __x) { return _M_t._M_insert_equal(std::move(__x)); } template __enable_if_t::value, iterator> insert(_Pair&& __x) { return _M_t._M_emplace_equal(std::forward<_Pair>(__x)); } #endif // @} /** * @brief Inserts a std::pair into the %multimap. * @param __position An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the inserted (key,value) pair. * * This function inserts a (key, value) pair into the %multimap. * Contrary to a std::map the %multimap does not rely on unique keys and * thus multiple pairs with the same key can be inserted. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). * @{ */ iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { return _M_t._M_insert_equal_(__position, __x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_equal_(__position, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __position, _Pair&& __x) { return _M_t._M_emplace_hint_equal(__position, std::forward<_Pair>(__x)); } #endif // @} /** * @brief A template function that attempts to insert a range * of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_equal(__first, __last); } #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of std::pairs into the %multimap. * @param __l A std::initializer_list of pairs to be * inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_t._M_reinsert_node_equal(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_equal(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(multimap<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(multimap<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } template void merge(map<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(map<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %multimap. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from a %multimap. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. * * @{ */ iterator erase(const_iterator __position) { return _M_t.erase(__position); } // LWG 2059. _GLIBCXX_ABI_TAG_CXX11 iterator erase(iterator __position) { return _M_t.erase(__position); } // @} #else /** * @brief Erases an element from a %multimap. * @param __position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %multimap. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all elements located by the given key from a * %multimap. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %multimap. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to be * erased . * @return The iterator @a __last. * * This function erases a sequence of elements from a %multimap. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %multimap. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * * This function erases a sequence of elements from a %multimap. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * @brief Swaps data with another %multimap. * @param __x A %multimap of the same element and allocator types. * * This exchanges the elements between two multimaps in constant time. * (It is only swapping a pointer, an integer, and an instance of * the @c Compare type (which itself is often stateless and empty), so it * should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(m1,m2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(multimap& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } /** * Erases all elements in a %multimap. Note that this function only * erases the elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // observers /** * Returns the key comparison object out of which the %multimap * was constructed. */ key_compare key_comp() const { return _M_t.key_comp(); } /** * Returns a value comparison object, built from the key comparison * object out of which the %multimap was constructed. */ value_compare value_comp() const { return value_compare(_M_t.key_comp()); } // multimap operations //@{ /** * @brief Tries to locate an element in a %multimap. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to sought-after element, * or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after %pair. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Tries to locate an element in a %multimap. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to sought-after * element, or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns a constant * iterator pointing to the sought after %pair. If unsuccessful it * returns the past-the-end ( @c end() ) iterator. */ const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) const -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Finds the number of elements with given key. * @param __x Key of (key, value) pairs to be located. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_t.count(__x); } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first element * equal to or greater than key, or end(). * * This function returns the first element of a subsequence of * elements that matches the given key. If unsuccessful the * iterator will point to the next greatest element or, if no * such greater element exists, to end(). */ const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_lower_bound_tr(__x))) { return const_iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first iterator * greater than key, or end(). */ const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_upper_bound_tr(__x))) { return const_iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of read-only (constant) iterators that possibly points * to the subsequence matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). */ std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) const -> decltype(pair( _M_t._M_equal_range_tr(__x))) { return pair( _M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const multimap<_K1, _T1, _C1, _A1>&, const multimap<_K1, _T1, _C1, _A1>&); template friend bool operator<(const multimap<_K1, _T1, _C1, _A1>&, const multimap<_K1, _T1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> multimap(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<_Key, _Tp, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Allocator) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> multimap(initializer_list>, _Allocator) -> multimap<_Key, _Tp, less<_Key>, _Allocator>; #endif /** * @brief Multimap equality comparison. * @param __x A %multimap. * @param __y A %multimap of the same type as @a __x. * @return True iff the size and elements of the maps are equal. * * This is an equivalence relation. It is linear in the size of the * multimaps. Multimaps are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Multimap ordering relation. * @param __x A %multimap. * @param __y A %multimap of the same type as @a __x. * @return True iff @a x is lexicographically less than @a y. * * This is a total ordering relation. It is linear in the size of the * multimaps. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Based on operator== template inline bool operator!=(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const multimap<_Key, _Tp, _Compare, _Alloc>& __x, const multimap<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::multimap::swap(). template inline void swap(multimap<_Key, _Tp, _Compare, _Alloc>& __x, multimap<_Key, _Tp, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::multimap access to internals of compatible maps. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::map<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_MULTIMAP_H */ c++/8/bits/stl_numeric.h000064400000033010151027430570010722 0ustar00// Numeric functions implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_numeric.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{numeric} */ #ifndef _STL_NUMERIC_H #define _STL_NUMERIC_H 1 #include #include #include // For _GLIBCXX_MOVE #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Create a range of sequentially increasing values. * * For each element in the range @p [first,last) assigns @p value and * increments @p value as if by @p ++value. * * @param __first Start of range. * @param __last End of range. * @param __value Starting value. * @return Nothing. */ template void iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_function_requires(_ConvertibleConcept<_Tp, typename iterator_traits<_ForwardIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) { *__first = __value; ++__value; } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_ALGO /** * @brief Accumulate values in a range. * * Accumulates the values in the range [first,last) using operator+(). The * initial value is @a init. The values are processed in order. * * @param __first Start of range. * @param __last End of range. * @param __init Starting value to add other values to. * @return The final sum. */ template inline _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __init = __init + *__first; return __init; } /** * @brief Accumulate values in a range with operation. * * Accumulates the values in the range [first,last) using the function * object @p __binary_op. The initial value is @p __init. The values are * processed in order. * * @param __first Start of range. * @param __last End of range. * @param __init Starting value to add other values to. * @param __binary_op Function object to accumulate with. * @return The final sum. */ template inline _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOperation __binary_op) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first) __init = __binary_op(__init, *__first); return __init; } /** * @brief Compute inner product of two ranges. * * Starting with an initial value of @p __init, multiplies successive * elements from the two ranges and adds each product into the accumulated * value using operator+(). The values in the ranges are processed in * order. * * @param __first1 Start of range 1. * @param __last1 End of range 1. * @param __first2 Start of range 2. * @param __init Starting value to add other values to. * @return The final inner product. */ template inline _Tp inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) __init = __init + (*__first1 * *__first2); return __init; } /** * @brief Compute inner product of two ranges. * * Starting with an initial value of @p __init, applies @p __binary_op2 to * successive elements from the two ranges and accumulates each result into * the accumulated value using @p __binary_op1. The values in the ranges are * processed in order. * * @param __first1 Start of range 1. * @param __last1 End of range 1. * @param __first2 Start of range 2. * @param __init Starting value to add other values to. * @param __binary_op1 Function object to accumulate with. * @param __binary_op2 Function object to apply to pairs of input values. * @return The final inner product. */ template inline _Tp inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init, _BinaryOperation1 __binary_op1, _BinaryOperation2 __binary_op2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) __init = __binary_op1(__init, __binary_op2(*__first1, *__first2)); return __init; } /** * @brief Return list of partial sums * * Accumulates the values in the range [first,last) using the @c + operator. * As each successive input value is added into the total, that partial sum * is written to @p __result. Therefore, the first value in @p __result is * the first value of the input, the second value in @p __result is the sum * of the first and second input values, and so on. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sum. * @return Iterator pointing just beyond the values written to __result. */ template _OutputIterator partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { __value = __value + *__first; *++__result = __value; } return ++__result; } /** * @brief Return list of partial sums * * Accumulates the values in the range [first,last) using @p __binary_op. * As each successive input value is added into the total, that partial sum * is written to @p __result. Therefore, the first value in @p __result is * the first value of the input, the second value in @p __result is the sum * of the first and second input values, and so on. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sum. * @param __binary_op Function object. * @return Iterator pointing just beyond the values written to __result. */ template _OutputIterator partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryOperation __binary_op) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { __value = __binary_op(__value, *__first); *++__result = __value; } return ++__result; } /** * @brief Return differences between adjacent values. * * Computes the difference between adjacent values in the range * [first,last) using operator-() and writes the result to @p __result. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sums. * @return Iterator pointing just beyond the values written to result. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 539. partial_sum and adjacent_difference should mention requirements */ template _OutputIterator adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { _ValueType __tmp = *__first; *++__result = __tmp - __value; __value = _GLIBCXX_MOVE(__tmp); } return ++__result; } /** * @brief Return differences between adjacent values. * * Computes the difference between adjacent values in the range * [__first,__last) using the function object @p __binary_op and writes the * result to @p __result. * * @param __first Start of input range. * @param __last End of input range. * @param __result Output sum. * @param __binary_op Function object. * @return Iterator pointing just beyond the values written to result. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 539. partial_sum and adjacent_difference should mention requirements */ template _OutputIterator adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryOperation __binary_op) { typedef typename iterator_traits<_InputIterator>::value_type _ValueType; // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator, _ValueType>) __glibcxx_requires_valid_range(__first, __last); if (__first == __last) return __result; _ValueType __value = *__first; *__result = __value; while (++__first != __last) { _ValueType __tmp = *__first; *++__result = __binary_op(__tmp, __value); __value = _GLIBCXX_MOVE(__tmp); } return ++__result; } _GLIBCXX_END_NAMESPACE_ALGO } // namespace std #endif /* _STL_NUMERIC_H */ c++/8/bits/string_view.tcc000064400000015052151027430570011266 0ustar00// Components for manipulating non-owning sequences of characters -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/string_view.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string_view} */ // // N3762 basic_string_view library // #ifndef _GLIBCXX_STRING_VIEW_TCC #define _GLIBCXX_STRING_VIEW_TCC 1 #pragma GCC system_header #if __cplusplus >= 201703L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); if (__n == 0) return __pos <= this->_M_len ? __pos : npos; if (__n <= this->_M_len) { for (; __pos <= this->_M_len - __n; ++__pos) if (traits_type::eq(this->_M_str[__pos], __str[0]) && traits_type::compare(this->_M_str + __pos + 1, __str + 1, __n - 1) == 0) return __pos; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find(_CharT __c, size_type __pos) const noexcept { size_type __ret = npos; if (__pos < this->_M_len) { const size_type __n = this->_M_len - __pos; const _CharT* __p = traits_type::find(this->_M_str + __pos, __n, __c); if (__p) __ret = __p - this->_M_str; } return __ret; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: rfind(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); if (__n <= this->_M_len) { __pos = std::min(size_type(this->_M_len - __n), __pos); do { if (traits_type::compare(this->_M_str + __pos, __str, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: rfind(_CharT __c, size_type __pos) const noexcept { size_type __size = this->_M_len; if (__size > 0) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(this->_M_str[__size], __c)) return __size; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); for (; __n && __pos < this->_M_len; ++__pos) { const _CharT* __p = traits_type::find(__str, __n, this->_M_str[__pos]); if (__p) return __pos; } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__str, __n, this->_M_str[__size])) return __size; } while (__size-- != 0); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_not_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); for (; __pos < this->_M_len; ++__pos) if (!traits_type::find(__str, __n, this->_M_str[__pos])) return __pos; return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_first_not_of(_CharT __c, size_type __pos) const noexcept { for (; __pos < this->_M_len; ++__pos) if (!traits_type::eq(this->_M_str[__pos], __c)) return __pos; return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_not_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept { __glibcxx_requires_string_len(__str, __n); size_type __size = this->_M_len; if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__str, __n, this->_M_str[__size])) return __size; } while (__size--); } return npos; } template constexpr typename basic_string_view<_CharT, _Traits>::size_type basic_string_view<_CharT, _Traits>:: find_last_not_of(_CharT __c, size_type __pos) const noexcept { size_type __size = this->_M_len; if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(this->_M_str[__size], __c)) return __size; } while (__size--); } return npos; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus <= 201402L #endif // _GLIBCXX_STRING_VIEW_TCC c++/8/bits/refwrap.h000064400000027154151027430570010060 0ustar00// Implementation of std::reference_wrapper -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/refwrap.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _GLIBCXX_REFWRAP_H #define _GLIBCXX_REFWRAP_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include // for unary_function and binary_function namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * Derives from @c unary_function or @c binary_function, or perhaps * nothing, depending on the number of arguments provided. The * primary template is the basis case, which derives nothing. */ template struct _Maybe_unary_or_binary_function { }; /// Derives from @c unary_function, as appropriate. template struct _Maybe_unary_or_binary_function<_Res, _T1> : std::unary_function<_T1, _Res> { }; /// Derives from @c binary_function, as appropriate. template struct _Maybe_unary_or_binary_function<_Res, _T1, _T2> : std::binary_function<_T1, _T2, _Res> { }; template struct _Mem_fn_traits; template struct _Mem_fn_traits_base { using __result_type = _Res; using __maybe_type = _Maybe_unary_or_binary_function<_Res, _Class*, _ArgTypes...>; using __arity = integral_constant; }; #define _GLIBCXX_MEM_FN_TRAITS2(_CV, _REF, _LVAL, _RVAL) \ template \ struct _Mem_fn_traits<_Res (_Class::*)(_ArgTypes...) _CV _REF> \ : _Mem_fn_traits_base<_Res, _CV _Class, _ArgTypes...> \ { \ using __vararg = false_type; \ }; \ template \ struct _Mem_fn_traits<_Res (_Class::*)(_ArgTypes... ...) _CV _REF> \ : _Mem_fn_traits_base<_Res, _CV _Class, _ArgTypes...> \ { \ using __vararg = true_type; \ }; #define _GLIBCXX_MEM_FN_TRAITS(_REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2( , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(const , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(volatile , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(const volatile, _REF, _LVAL, _RVAL) _GLIBCXX_MEM_FN_TRAITS( , true_type, true_type) _GLIBCXX_MEM_FN_TRAITS(&, true_type, false_type) _GLIBCXX_MEM_FN_TRAITS(&&, false_type, true_type) #if __cplusplus > 201402L _GLIBCXX_MEM_FN_TRAITS(noexcept, true_type, true_type) _GLIBCXX_MEM_FN_TRAITS(& noexcept, true_type, false_type) _GLIBCXX_MEM_FN_TRAITS(&& noexcept, false_type, true_type) #endif #undef _GLIBCXX_MEM_FN_TRAITS #undef _GLIBCXX_MEM_FN_TRAITS2 /// If we have found a result_type, extract it. template> struct _Maybe_get_result_type { }; template struct _Maybe_get_result_type<_Functor, __void_t> { typedef typename _Functor::result_type result_type; }; /** * Base class for any function object that has a weak result type, as * defined in 20.8.2 [func.require] of C++11. */ template struct _Weak_result_type_impl : _Maybe_get_result_type<_Functor> { }; /// Retrieve the result type for a function type. template struct _Weak_result_type_impl<_Res(_ArgTypes...) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a varargs function type. template struct _Weak_result_type_impl<_Res(_ArgTypes......) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a function pointer. template struct _Weak_result_type_impl<_Res(*)(_ArgTypes...) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a varargs function pointer. template struct _Weak_result_type_impl<_Res(*)(_ArgTypes......) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; // Let _Weak_result_type_impl perform the real work. template::value> struct _Weak_result_type_memfun : _Weak_result_type_impl<_Functor> { }; // A pointer to member function has a weak result type. template struct _Weak_result_type_memfun<_MemFunPtr, true> { using result_type = typename _Mem_fn_traits<_MemFunPtr>::__result_type; }; // A pointer to data member doesn't have a weak result type. template struct _Weak_result_type_memfun<_Func _Class::*, false> { }; /** * Strip top-level cv-qualifiers from the function object and let * _Weak_result_type_memfun perform the real work. */ template struct _Weak_result_type : _Weak_result_type_memfun::type> { }; // Detect nested argument_type. template> struct _Refwrap_base_arg1 { }; // Nested argument_type. template struct _Refwrap_base_arg1<_Tp, __void_t> { typedef typename _Tp::argument_type argument_type; }; // Detect nested first_argument_type and second_argument_type. template> struct _Refwrap_base_arg2 { }; // Nested first_argument_type and second_argument_type. template struct _Refwrap_base_arg2<_Tp, __void_t> { typedef typename _Tp::first_argument_type first_argument_type; typedef typename _Tp::second_argument_type second_argument_type; }; /** * Derives from unary_function or binary_function when it * can. Specializations handle all of the easy cases. The primary * template determines what to do with a class type, which may * derive from both unary_function and binary_function. */ template struct _Reference_wrapper_base : _Weak_result_type<_Tp>, _Refwrap_base_arg1<_Tp>, _Refwrap_base_arg2<_Tp> { }; // - a function type (unary) template struct _Reference_wrapper_base<_Res(_T1) _GLIBCXX_NOEXCEPT_QUAL> : unary_function<_T1, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1) const> : unary_function<_T1, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1) volatile> : unary_function<_T1, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1) const volatile> : unary_function<_T1, _Res> { }; // - a function type (binary) template struct _Reference_wrapper_base<_Res(_T1, _T2) _GLIBCXX_NOEXCEPT_QUAL> : binary_function<_T1, _T2, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1, _T2) const> : binary_function<_T1, _T2, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1, _T2) volatile> : binary_function<_T1, _T2, _Res> { }; template struct _Reference_wrapper_base<_Res(_T1, _T2) const volatile> : binary_function<_T1, _T2, _Res> { }; // - a function pointer type (unary) template struct _Reference_wrapper_base<_Res(*)(_T1) _GLIBCXX_NOEXCEPT_QUAL> : unary_function<_T1, _Res> { }; // - a function pointer type (binary) template struct _Reference_wrapper_base<_Res(*)(_T1, _T2) _GLIBCXX_NOEXCEPT_QUAL> : binary_function<_T1, _T2, _Res> { }; template::value> struct _Reference_wrapper_base_memfun : _Reference_wrapper_base<_Tp> { }; template struct _Reference_wrapper_base_memfun<_MemFunPtr, true> : _Mem_fn_traits<_MemFunPtr>::__maybe_type { using result_type = typename _Mem_fn_traits<_MemFunPtr>::__result_type; }; /** * @brief Primary class template for reference_wrapper. * @ingroup functors * @{ */ template class reference_wrapper : public _Reference_wrapper_base_memfun::type> { _Tp* _M_data; public: typedef _Tp type; reference_wrapper(_Tp& __indata) noexcept : _M_data(std::__addressof(__indata)) { } reference_wrapper(_Tp&&) = delete; reference_wrapper(const reference_wrapper&) = default; reference_wrapper& operator=(const reference_wrapper&) = default; operator _Tp&() const noexcept { return this->get(); } _Tp& get() const noexcept { return *_M_data; } template typename result_of<_Tp&(_Args&&...)>::type operator()(_Args&&... __args) const { return std::__invoke(get(), std::forward<_Args>(__args)...); } }; /// Denotes a reference should be taken to a variable. template inline reference_wrapper<_Tp> ref(_Tp& __t) noexcept { return reference_wrapper<_Tp>(__t); } /// Denotes a const reference should be taken to a variable. template inline reference_wrapper cref(const _Tp& __t) noexcept { return reference_wrapper(__t); } template void ref(const _Tp&&) = delete; template void cref(const _Tp&&) = delete; /// std::ref overload to prevent wrapping a reference_wrapper template inline reference_wrapper<_Tp> ref(reference_wrapper<_Tp> __t) noexcept { return __t; } /// std::cref overload to prevent wrapping a reference_wrapper template inline reference_wrapper cref(reference_wrapper<_Tp> __t) noexcept { return { __t.get() }; } // @} group functors _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_REFWRAP_H c++/8/bits/regex_scanner.h000064400000015660151027430570011234 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_scanner.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @addtogroup regex-detail * @{ */ struct _ScannerBase { public: /// Token types returned from the scanner. enum _TokenT : unsigned { _S_token_anychar, _S_token_ord_char, _S_token_oct_num, _S_token_hex_num, _S_token_backref, _S_token_subexpr_begin, _S_token_subexpr_no_group_begin, _S_token_subexpr_lookahead_begin, // neg if _M_value[0] == 'n' _S_token_subexpr_end, _S_token_bracket_begin, _S_token_bracket_neg_begin, _S_token_bracket_end, _S_token_interval_begin, _S_token_interval_end, _S_token_quoted_class, _S_token_char_class_name, _S_token_collsymbol, _S_token_equiv_class_name, _S_token_opt, _S_token_or, _S_token_closure0, _S_token_closure1, _S_token_line_begin, _S_token_line_end, _S_token_word_bound, // neg if _M_value[0] == 'n' _S_token_comma, _S_token_dup_count, _S_token_eof, _S_token_bracket_dash, _S_token_unknown = -1u }; protected: typedef regex_constants::syntax_option_type _FlagT; enum _StateT { _S_state_normal, _S_state_in_brace, _S_state_in_bracket, }; protected: _ScannerBase(_FlagT __flags) : _M_state(_S_state_normal), _M_flags(__flags), _M_escape_tbl(_M_is_ecma() ? _M_ecma_escape_tbl : _M_awk_escape_tbl), _M_spec_char(_M_is_ecma() ? _M_ecma_spec_char : _M_flags & regex_constants::basic ? _M_basic_spec_char : _M_flags & regex_constants::extended ? _M_extended_spec_char : _M_flags & regex_constants::grep ? ".[\\*^$\n" : _M_flags & regex_constants::egrep ? ".[\\()*+?{|^$\n" : _M_flags & regex_constants::awk ? _M_extended_spec_char : nullptr), _M_at_bracket_start(false) { __glibcxx_assert(_M_spec_char); } protected: const char* _M_find_escape(char __c) { auto __it = _M_escape_tbl; for (; __it->first != '\0'; ++__it) if (__it->first == __c) return &__it->second; return nullptr; } bool _M_is_ecma() const { return _M_flags & regex_constants::ECMAScript; } bool _M_is_basic() const { return _M_flags & (regex_constants::basic | regex_constants::grep); } bool _M_is_extended() const { return _M_flags & (regex_constants::extended | regex_constants::egrep | regex_constants::awk); } bool _M_is_grep() const { return _M_flags & (regex_constants::grep | regex_constants::egrep); } bool _M_is_awk() const { return _M_flags & regex_constants::awk; } protected: // TODO: Make them static in the next abi change. const std::pair _M_token_tbl[9] = { {'^', _S_token_line_begin}, {'$', _S_token_line_end}, {'.', _S_token_anychar}, {'*', _S_token_closure0}, {'+', _S_token_closure1}, {'?', _S_token_opt}, {'|', _S_token_or}, {'\n', _S_token_or}, // grep and egrep {'\0', _S_token_or}, }; const std::pair _M_ecma_escape_tbl[8] = { {'0', '\0'}, {'b', '\b'}, {'f', '\f'}, {'n', '\n'}, {'r', '\r'}, {'t', '\t'}, {'v', '\v'}, {'\0', '\0'}, }; const std::pair _M_awk_escape_tbl[11] = { {'"', '"'}, {'/', '/'}, {'\\', '\\'}, {'a', '\a'}, {'b', '\b'}, {'f', '\f'}, {'n', '\n'}, {'r', '\r'}, {'t', '\t'}, {'v', '\v'}, {'\0', '\0'}, }; const char* _M_ecma_spec_char = "^$\\.*+?()[]{}|"; const char* _M_basic_spec_char = ".[\\*^$"; const char* _M_extended_spec_char = ".[\\()*+?{|^$"; _StateT _M_state; _FlagT _M_flags; _TokenT _M_token; const std::pair* _M_escape_tbl; const char* _M_spec_char; bool _M_at_bracket_start; }; /** * @brief Scans an input range for regex tokens. * * The %_Scanner class interprets the regular expression pattern in * the input range passed to its constructor as a sequence of parse * tokens passed to the regular expression compiler. The sequence * of tokens provided depends on the flag settings passed to the * constructor: different regular expression grammars will interpret * the same input pattern in syntactically different ways. */ template class _Scanner : public _ScannerBase { public: typedef const _CharT* _IterT; typedef std::basic_string<_CharT> _StringT; typedef regex_constants::syntax_option_type _FlagT; typedef const std::ctype<_CharT> _CtypeT; _Scanner(_IterT __begin, _IterT __end, _FlagT __flags, std::locale __loc); void _M_advance(); _TokenT _M_get_token() const { return _M_token; } const _StringT& _M_get_value() const { return _M_value; } #ifdef _GLIBCXX_DEBUG std::ostream& _M_print(std::ostream&); #endif private: void _M_scan_normal(); void _M_scan_in_bracket(); void _M_scan_in_brace(); void _M_eat_escape_ecma(); void _M_eat_escape_posix(); void _M_eat_escape_awk(); void _M_eat_class(char); _IterT _M_current; _IterT _M_end; _CtypeT& _M_ctype; _StringT _M_value; void (_Scanner::* _M_eat_escape)(); }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include c++/8/bits/std_abs.h000064400000006302151027430570010021 0ustar00// -*- C++ -*- C library enhancements header. // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/std_abs.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cmath, cstdlib} */ #ifndef _GLIBCXX_BITS_STD_ABS_H #define _GLIBCXX_BITS_STD_ABS_H #pragma GCC system_header #include #define _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include_next #ifdef __CORRECT_ISO_CPP_MATH_H_PROTO # include_next #endif #undef _GLIBCXX_INCLUDE_NEXT_C_HEADERS #undef abs extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::abs; #ifndef __CORRECT_ISO_CPP_STDLIB_H_PROTO inline long abs(long __i) { return __builtin_labs(__i); } #endif #ifdef _GLIBCXX_USE_LONG_LONG inline long long abs(long long __x) { return __builtin_llabs (__x); } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2192. Validity and return type of std::abs(0u) is unclear // 2294. should declare abs(double) #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR double abs(double __x) { return __builtin_fabs(__x); } inline _GLIBCXX_CONSTEXPR float abs(float __x) { return __builtin_fabsf(__x); } inline _GLIBCXX_CONSTEXPR long double abs(long double __x) { return __builtin_fabsl(__x); } #endif #if defined(__GLIBCXX_TYPE_INT_N_0) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_0 abs(__GLIBCXX_TYPE_INT_N_0 __x) { return __x >= 0 ? __x : -__x; } #endif #if defined(__GLIBCXX_TYPE_INT_N_1) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_1 abs(__GLIBCXX_TYPE_INT_N_1 __x) { return __x >= 0 ? __x : -__x; } #endif #if defined(__GLIBCXX_TYPE_INT_N_2) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_2 abs(__GLIBCXX_TYPE_INT_N_2 __x) { return __x >= 0 ? __x : -__x; } #endif #if defined(__GLIBCXX_TYPE_INT_N_3) inline _GLIBCXX_CONSTEXPR __GLIBCXX_TYPE_INT_N_3 abs(__GLIBCXX_TYPE_INT_N_3 __x) { return __x >= 0 ? __x : -__x; } #endif #if !defined(__STRICT_ANSI__) && defined(_GLIBCXX_USE_FLOAT128) inline _GLIBCXX_CONSTEXPR __float128 abs(__float128 __x) { return __x < 0 ? -__x : __x; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace } #endif // _GLIBCXX_BITS_STD_ABS_H c++/8/bits/memoryfwd.h000064400000004625151027430570010421 0ustar00// Forward declarations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1996-1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/memoryfwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _MEMORYFWD_H #define _MEMORYFWD_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup allocators Allocators * @ingroup memory * * Classes encapsulating memory operations. * * @{ */ template class allocator; template<> class allocator; #if __cplusplus >= 201103L /// Declare uses_allocator so it can be specialized in \ etc. template struct uses_allocator; #endif /// @} group memory _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/forward_list.h000064400000137427151027430570011116 0ustar00// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/forward_list.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{forward_list} */ #ifndef _FORWARD_LIST_H #define _FORWARD_LIST_H 1 #pragma GCC system_header #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * @brief A helper basic node class for %forward_list. * This is just a linked list with nothing inside it. * There are purely list shuffling utility methods here. */ struct _Fwd_list_node_base { _Fwd_list_node_base() = default; _Fwd_list_node_base(_Fwd_list_node_base&& __x) noexcept : _M_next(__x._M_next) { __x._M_next = nullptr; } _Fwd_list_node_base(const _Fwd_list_node_base&) = delete; _Fwd_list_node_base& operator=(const _Fwd_list_node_base&) = delete; _Fwd_list_node_base& operator=(_Fwd_list_node_base&& __x) noexcept { _M_next = __x._M_next; __x._M_next = nullptr; return *this; } _Fwd_list_node_base* _M_next = nullptr; _Fwd_list_node_base* _M_transfer_after(_Fwd_list_node_base* __begin, _Fwd_list_node_base* __end) noexcept { _Fwd_list_node_base* __keep = __begin->_M_next; if (__end) { __begin->_M_next = __end->_M_next; __end->_M_next = _M_next; } else __begin->_M_next = nullptr; _M_next = __keep; return __end; } void _M_reverse_after() noexcept { _Fwd_list_node_base* __tail = _M_next; if (!__tail) return; while (_Fwd_list_node_base* __temp = __tail->_M_next) { _Fwd_list_node_base* __keep = _M_next; _M_next = __temp; __tail->_M_next = __temp->_M_next; _M_next->_M_next = __keep; } } }; /** * @brief A helper node class for %forward_list. * This is just a linked list with uninitialized storage for a * data value in each node. * There is a sorting utility method. */ template struct _Fwd_list_node : public _Fwd_list_node_base { _Fwd_list_node() = default; __gnu_cxx::__aligned_buffer<_Tp> _M_storage; _Tp* _M_valptr() noexcept { return _M_storage._M_ptr(); } const _Tp* _M_valptr() const noexcept { return _M_storage._M_ptr(); } }; /** * @brief A forward_list::iterator. * * All the functions are op overloads. */ template struct _Fwd_list_iterator { typedef _Fwd_list_iterator<_Tp> _Self; typedef _Fwd_list_node<_Tp> _Node; typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; typedef ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Fwd_list_iterator() noexcept : _M_node() { } explicit _Fwd_list_iterator(_Fwd_list_node_base* __n) noexcept : _M_node(__n) { } reference operator*() const noexcept { return *static_cast<_Node*>(this->_M_node)->_M_valptr(); } pointer operator->() const noexcept { return static_cast<_Node*>(this->_M_node)->_M_valptr(); } _Self& operator++() noexcept { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) noexcept { _Self __tmp(*this); _M_node = _M_node->_M_next; return __tmp; } bool operator==(const _Self& __x) const noexcept { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const noexcept { return _M_node != __x._M_node; } _Self _M_next() const noexcept { if (_M_node) return _Fwd_list_iterator(_M_node->_M_next); else return _Fwd_list_iterator(nullptr); } _Fwd_list_node_base* _M_node; }; /** * @brief A forward_list::const_iterator. * * All the functions are op overloads. */ template struct _Fwd_list_const_iterator { typedef _Fwd_list_const_iterator<_Tp> _Self; typedef const _Fwd_list_node<_Tp> _Node; typedef _Fwd_list_iterator<_Tp> iterator; typedef _Tp value_type; typedef const _Tp* pointer; typedef const _Tp& reference; typedef ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Fwd_list_const_iterator() noexcept : _M_node() { } explicit _Fwd_list_const_iterator(const _Fwd_list_node_base* __n) noexcept : _M_node(__n) { } _Fwd_list_const_iterator(const iterator& __iter) noexcept : _M_node(__iter._M_node) { } reference operator*() const noexcept { return *static_cast<_Node*>(this->_M_node)->_M_valptr(); } pointer operator->() const noexcept { return static_cast<_Node*>(this->_M_node)->_M_valptr(); } _Self& operator++() noexcept { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) noexcept { _Self __tmp(*this); _M_node = _M_node->_M_next; return __tmp; } bool operator==(const _Self& __x) const noexcept { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const noexcept { return _M_node != __x._M_node; } _Self _M_next() const noexcept { if (this->_M_node) return _Fwd_list_const_iterator(_M_node->_M_next); else return _Fwd_list_const_iterator(nullptr); } const _Fwd_list_node_base* _M_node; }; /** * @brief Forward list iterator equality comparison. */ template inline bool operator==(const _Fwd_list_iterator<_Tp>& __x, const _Fwd_list_const_iterator<_Tp>& __y) noexcept { return __x._M_node == __y._M_node; } /** * @brief Forward list iterator inequality comparison. */ template inline bool operator!=(const _Fwd_list_iterator<_Tp>& __x, const _Fwd_list_const_iterator<_Tp>& __y) noexcept { return __x._M_node != __y._M_node; } /** * @brief Base class for %forward_list. */ template struct _Fwd_list_base { protected: typedef __alloc_rebind<_Alloc, _Fwd_list_node<_Tp>> _Node_alloc_type; typedef __gnu_cxx::__alloc_traits<_Node_alloc_type> _Node_alloc_traits; struct _Fwd_list_impl : public _Node_alloc_type { _Fwd_list_node_base _M_head; _Fwd_list_impl() noexcept(is_nothrow_default_constructible<_Node_alloc_type>::value) : _Node_alloc_type(), _M_head() { } _Fwd_list_impl(_Fwd_list_impl&&) = default; _Fwd_list_impl(_Fwd_list_impl&& __fl, _Node_alloc_type&& __a) : _Node_alloc_type(std::move(__a)), _M_head(std::move(__fl._M_head)) { } _Fwd_list_impl(_Node_alloc_type&& __a) : _Node_alloc_type(std::move(__a)), _M_head() { } }; _Fwd_list_impl _M_impl; public: typedef _Fwd_list_iterator<_Tp> iterator; typedef _Fwd_list_const_iterator<_Tp> const_iterator; typedef _Fwd_list_node<_Tp> _Node; _Node_alloc_type& _M_get_Node_allocator() noexcept { return this->_M_impl; } const _Node_alloc_type& _M_get_Node_allocator() const noexcept { return this->_M_impl; } _Fwd_list_base() = default; _Fwd_list_base(_Node_alloc_type&& __a) : _M_impl(std::move(__a)) { } // When allocators are always equal. _Fwd_list_base(_Fwd_list_base&& __lst, _Node_alloc_type&& __a, std::true_type) : _M_impl(std::move(__lst._M_impl), std::move(__a)) { } // When allocators are not always equal. _Fwd_list_base(_Fwd_list_base&& __lst, _Node_alloc_type&& __a); _Fwd_list_base(_Fwd_list_base&&) = default; ~_Fwd_list_base() { _M_erase_after(&_M_impl._M_head, nullptr); } protected: _Node* _M_get_node() { auto __ptr = _Node_alloc_traits::allocate(_M_get_Node_allocator(), 1); return std::__to_address(__ptr); } template _Node* _M_create_node(_Args&&... __args) { _Node* __node = this->_M_get_node(); __try { ::new ((void*)__node) _Node; _Node_alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), std::forward<_Args>(__args)...); } __catch(...) { this->_M_put_node(__node); __throw_exception_again; } return __node; } template _Fwd_list_node_base* _M_insert_after(const_iterator __pos, _Args&&... __args); void _M_put_node(_Node* __p) { typedef typename _Node_alloc_traits::pointer _Ptr; auto __ptr = std::pointer_traits<_Ptr>::pointer_to(*__p); _Node_alloc_traits::deallocate(_M_get_Node_allocator(), __ptr, 1); } _Fwd_list_node_base* _M_erase_after(_Fwd_list_node_base* __pos); _Fwd_list_node_base* _M_erase_after(_Fwd_list_node_base* __pos, _Fwd_list_node_base* __last); }; /** * @brief A standard container with linear time access to elements, * and fixed time insertion/deletion at any point in the sequence. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * sequence, including the * optional sequence requirements with the * %exception of @c at and @c operator[]. * * This is a @e singly @e linked %list. Traversal up the * %list requires linear time, but adding and removing elements (or * @e nodes) is done in constant time, regardless of where the * change takes place. Unlike std::vector and std::deque, * random-access iterators are not provided, so subscripting ( @c * [] ) access is not allowed. For algorithms which only need * sequential access, this lack makes no difference. * * Also unlike the other standard containers, std::forward_list provides * specialized algorithms %unique to linked lists, such as * splicing, sorting, and in-place reversal. */ template> class forward_list : private _Fwd_list_base<_Tp, _Alloc> { static_assert(is_same::type, _Tp>::value, "std::forward_list must have a non-const, non-volatile value_type"); #ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::forward_list must have the same value_type as its allocator"); #endif private: typedef _Fwd_list_base<_Tp, _Alloc> _Base; typedef _Fwd_list_node<_Tp> _Node; typedef _Fwd_list_node_base _Node_base; typedef typename _Base::_Node_alloc_type _Node_alloc_type; typedef typename _Base::_Node_alloc_traits _Node_alloc_traits; typedef allocator_traits<__alloc_rebind<_Alloc, _Tp>> _Alloc_traits; public: // types: typedef _Tp value_type; typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef _Fwd_list_iterator<_Tp> iterator; typedef _Fwd_list_const_iterator<_Tp> const_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef _Alloc allocator_type; // 23.3.4.2 construct/copy/destroy: /** * @brief Creates a %forward_list with no elements. */ forward_list() = default; /** * @brief Creates a %forward_list with no elements. * @param __al An allocator object. */ explicit forward_list(const _Alloc& __al) noexcept : _Base(_Node_alloc_type(__al)) { } /** * @brief Copy constructor with allocator argument. * @param __list Input list to copy. * @param __al An allocator object. */ forward_list(const forward_list& __list, const _Alloc& __al) : _Base(_Node_alloc_type(__al)) { _M_range_initialize(__list.begin(), __list.end()); } private: forward_list(forward_list&& __list, _Node_alloc_type&& __al, false_type) : _Base(std::move(__list), std::move(__al)) { // If __list is not empty it means its allocator is not equal to __a, // so we need to move from each element individually. insert_after(cbefore_begin(), std::__make_move_if_noexcept_iterator(__list.begin()), std::__make_move_if_noexcept_iterator(__list.end())); } forward_list(forward_list&& __list, _Node_alloc_type&& __al, true_type) noexcept : _Base(std::move(__list), _Node_alloc_type(__al), true_type{}) { } public: /** * @brief Move constructor with allocator argument. * @param __list Input list to move. * @param __al An allocator object. */ forward_list(forward_list&& __list, const _Alloc& __al) noexcept(_Node_alloc_traits::_S_always_equal()) : forward_list(std::move(__list), _Node_alloc_type(__al), typename _Node_alloc_traits::is_always_equal{}) { } /** * @brief Creates a %forward_list with default constructed elements. * @param __n The number of elements to initially create. * @param __al An allocator object. * * This constructor creates the %forward_list with @a __n default * constructed elements. */ explicit forward_list(size_type __n, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_default_initialize(__n); } /** * @brief Creates a %forward_list with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __al An allocator object. * * This constructor fills the %forward_list with @a __n copies of * @a __value. */ forward_list(size_type __n, const _Tp& __value, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_fill_initialize(__n, __value); } /** * @brief Builds a %forward_list from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __al An allocator object. * * Create a %forward_list consisting of copies of the elements from * [@a __first,@a __last). This is linear in N (where N is * distance(@a __first,@a __last)). */ template> forward_list(_InputIterator __first, _InputIterator __last, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_range_initialize(__first, __last); } /** * @brief The %forward_list copy constructor. * @param __list A %forward_list of identical element and allocator * types. */ forward_list(const forward_list& __list) : _Base(_Node_alloc_traits::_S_select_on_copy( __list._M_get_Node_allocator())) { _M_range_initialize(__list.begin(), __list.end()); } /** * @brief The %forward_list move constructor. * @param __list A %forward_list of identical element and allocator * types. * * The newly-created %forward_list contains the exact contents of the * moved instance. The contents of the moved instance are a valid, but * unspecified %forward_list. */ forward_list(forward_list&&) = default; /** * @brief Builds a %forward_list from an initializer_list * @param __il An initializer_list of value_type. * @param __al An allocator object. * * Create a %forward_list consisting of copies of the elements * in the initializer_list @a __il. This is linear in __il.size(). */ forward_list(std::initializer_list<_Tp> __il, const _Alloc& __al = _Alloc()) : _Base(_Node_alloc_type(__al)) { _M_range_initialize(__il.begin(), __il.end()); } /** * @brief The forward_list dtor. */ ~forward_list() noexcept { } /** * @brief The %forward_list assignment operator. * @param __list A %forward_list of identical element and allocator * types. * * All the elements of @a __list are copied. * * Whether the allocator is copied depends on the allocator traits. */ forward_list& operator=(const forward_list& __list); /** * @brief The %forward_list move assignment operator. * @param __list A %forward_list of identical element and allocator * types. * * The contents of @a __list are moved into this %forward_list * (without copying, if the allocators permit it). * * Afterwards @a __list is a valid, but unspecified %forward_list * * Whether the allocator is moved depends on the allocator traits. */ forward_list& operator=(forward_list&& __list) noexcept(_Node_alloc_traits::_S_nothrow_move()) { constexpr bool __move_storage = _Node_alloc_traits::_S_propagate_on_move_assign() || _Node_alloc_traits::_S_always_equal(); _M_move_assign(std::move(__list), __bool_constant<__move_storage>()); return *this; } /** * @brief The %forward_list initializer list assignment operator. * @param __il An initializer_list of value_type. * * Replace the contents of the %forward_list with copies of the * elements in the initializer_list @a __il. This is linear in * __il.size(). */ forward_list& operator=(std::initializer_list<_Tp> __il) { assign(__il); return *this; } /** * @brief Assigns a range to a %forward_list. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %forward_list with copies of the elements * in the range [@a __first,@a __last). * * Note that the assignment completely changes the %forward_list and * that the number of elements of the resulting %forward_list is the * same as the number of elements assigned. */ template> void assign(_InputIterator __first, _InputIterator __last) { typedef is_assignable<_Tp, decltype(*__first)> __assignable; _M_assign(__first, __last, __assignable()); } /** * @brief Assigns a given value to a %forward_list. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %forward_list with @a __n copies of the * given value. Note that the assignment completely changes the * %forward_list, and that the resulting %forward_list has __n * elements. */ void assign(size_type __n, const _Tp& __val) { _M_assign_n(__n, __val, is_copy_assignable<_Tp>()); } /** * @brief Assigns an initializer_list to a %forward_list. * @param __il An initializer_list of value_type. * * Replace the contents of the %forward_list with copies of the * elements in the initializer_list @a __il. This is linear in * il.size(). */ void assign(std::initializer_list<_Tp> __il) { assign(__il.begin(), __il.end()); } /// Get a copy of the memory allocation object. allocator_type get_allocator() const noexcept { return allocator_type(this->_M_get_Node_allocator()); } // 23.3.4.3 iterators: /** * Returns a read/write iterator that points before the first element * in the %forward_list. Iteration is done in ordinary element order. */ iterator before_begin() noexcept { return iterator(&this->_M_impl._M_head); } /** * Returns a read-only (constant) iterator that points before the * first element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator before_begin() const noexcept { return const_iterator(&this->_M_impl._M_head); } /** * Returns a read/write iterator that points to the first element * in the %forward_list. Iteration is done in ordinary element order. */ iterator begin() noexcept { return iterator(this->_M_impl._M_head._M_next); } /** * Returns a read-only (constant) iterator that points to the first * element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator begin() const noexcept { return const_iterator(this->_M_impl._M_head._M_next); } /** * Returns a read/write iterator that points one past the last * element in the %forward_list. Iteration is done in ordinary * element order. */ iterator end() noexcept { return iterator(nullptr); } /** * Returns a read-only iterator that points one past the last * element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator end() const noexcept { return const_iterator(nullptr); } /** * Returns a read-only (constant) iterator that points to the * first element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_impl._M_head._M_next); } /** * Returns a read-only (constant) iterator that points before the * first element in the %forward_list. Iteration is done in ordinary * element order. */ const_iterator cbefore_begin() const noexcept { return const_iterator(&this->_M_impl._M_head); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %forward_list. Iteration is done in * ordinary element order. */ const_iterator cend() const noexcept { return const_iterator(nullptr); } /** * Returns true if the %forward_list is empty. (Thus begin() would * equal end().) */ bool empty() const noexcept { return this->_M_impl._M_head._M_next == nullptr; } /** * Returns the largest possible number of elements of %forward_list. */ size_type max_size() const noexcept { return _Node_alloc_traits::max_size(this->_M_get_Node_allocator()); } // 23.3.4.4 element access: /** * Returns a read/write reference to the data at the first * element of the %forward_list. */ reference front() { _Node* __front = static_cast<_Node*>(this->_M_impl._M_head._M_next); return *__front->_M_valptr(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %forward_list. */ const_reference front() const { _Node* __front = static_cast<_Node*>(this->_M_impl._M_head._M_next); return *__front->_M_valptr(); } // 23.3.4.5 modifiers: /** * @brief Constructs object in %forward_list at the front of the * list. * @param __args Arguments. * * This function will insert an object of type Tp constructed * with Tp(std::forward(args)...) at the front of the list * Due to the nature of a %forward_list this operation can * be done in constant time, and does not invalidate iterators * and references. */ template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args) { this->_M_insert_after(cbefore_begin(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return front(); #endif } /** * @brief Add data to the front of the %forward_list. * @param __val Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %forward_list and assigns the given * data to it. Due to the nature of a %forward_list this operation * can be done in constant time, and does not invalidate iterators * and references. */ void push_front(const _Tp& __val) { this->_M_insert_after(cbefore_begin(), __val); } /** * */ void push_front(_Tp&& __val) { this->_M_insert_after(cbefore_begin(), std::move(__val)); } /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %forward_list * by one. Due to the nature of a %forward_list this operation can * be done in constant time, and only invalidates iterators/references * to the element being removed. * * Note that no data is returned, and if the first element's data * is needed, it should be retrieved before pop_front() is * called. */ void pop_front() { this->_M_erase_after(&this->_M_impl._M_head); } /** * @brief Constructs object in %forward_list after the specified * iterator. * @param __pos A const_iterator into the %forward_list. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) after the specified * location. Due to the nature of a %forward_list this operation can * be done in constant time, and does not invalidate iterators * and references. */ template iterator emplace_after(const_iterator __pos, _Args&&... __args) { return iterator(this->_M_insert_after(__pos, std::forward<_Args>(__args)...)); } /** * @brief Inserts given value into %forward_list after specified * iterator. * @param __pos An iterator into the %forward_list. * @param __val Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value after * the specified location. Due to the nature of a %forward_list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert_after(const_iterator __pos, const _Tp& __val) { return iterator(this->_M_insert_after(__pos, __val)); } /** * */ iterator insert_after(const_iterator __pos, _Tp&& __val) { return iterator(this->_M_insert_after(__pos, std::move(__val))); } /** * @brief Inserts a number of copies of given data into the * %forward_list. * @param __pos An iterator into the %forward_list. * @param __n Number of elements to be inserted. * @param __val Data to be inserted. * @return An iterator pointing to the last inserted copy of * @a val or @a pos if @a n == 0. * * This function will insert a specified number of copies of the * given data after the location specified by @a pos. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert_after(const_iterator __pos, size_type __n, const _Tp& __val); /** * @brief Inserts a range into the %forward_list. * @param __pos An iterator into the %forward_list. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator pointing to the last inserted element or * @a __pos if @a __first == @a __last. * * This function will insert copies of the data in the range * [@a __first,@a __last) into the %forward_list after the * location specified by @a __pos. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ template> iterator insert_after(const_iterator __pos, _InputIterator __first, _InputIterator __last); /** * @brief Inserts the contents of an initializer_list into * %forward_list after the specified iterator. * @param __pos An iterator into the %forward_list. * @param __il An initializer_list of value_type. * @return An iterator pointing to the last inserted element * or @a __pos if @a __il is empty. * * This function will insert copies of the data in the * initializer_list @a __il into the %forward_list before the location * specified by @a __pos. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert_after(const_iterator __pos, std::initializer_list<_Tp> __il) { return insert_after(__pos, __il.begin(), __il.end()); } /** * @brief Removes the element pointed to by the iterator following * @c pos. * @param __pos Iterator pointing before element to be erased. * @return An iterator pointing to the element following the one * that was erased, or end() if no such element exists. * * This function will erase the element at the given position and * thus shorten the %forward_list by one. * * Due to the nature of a %forward_list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. The user is also cautioned that * this function only erases the element, and that if the element * is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase_after(const_iterator __pos) { return iterator(this->_M_erase_after(const_cast<_Node_base*> (__pos._M_node))); } /** * @brief Remove a range of elements. * @param __pos Iterator pointing before the first element to be * erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return @ __last. * * This function will erase the elements in the range * @a (__pos,__last) and shorten the %forward_list accordingly. * * This operation is linear time in the size of the range and only * invalidates iterators/references to the element being removed. * The user is also cautioned that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ iterator erase_after(const_iterator __pos, const_iterator __last) { return iterator(this->_M_erase_after(const_cast<_Node_base*> (__pos._M_node), const_cast<_Node_base*> (__last._M_node))); } /** * @brief Swaps data with another %forward_list. * @param __list A %forward_list of the same element and allocator * types. * * This exchanges the elements between two lists in constant * time. Note that the global std::swap() function is * specialized such that std::swap(l1,l2) will feed to this * function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(forward_list& __list) noexcept { std::swap(this->_M_impl._M_head._M_next, __list._M_impl._M_head._M_next); _Node_alloc_traits::_S_on_swap(this->_M_get_Node_allocator(), __list._M_get_Node_allocator()); } /** * @brief Resizes the %forward_list to the specified number of * elements. * @param __sz Number of elements the %forward_list should contain. * * This function will %resize the %forward_list to the specified * number of elements. If the number is smaller than the * %forward_list's current number of elements the %forward_list * is truncated, otherwise the %forward_list is extended and the * new elements are default constructed. */ void resize(size_type __sz); /** * @brief Resizes the %forward_list to the specified number of * elements. * @param __sz Number of elements the %forward_list should contain. * @param __val Data with which new elements should be populated. * * This function will %resize the %forward_list to the specified * number of elements. If the number is smaller than the * %forward_list's current number of elements the %forward_list * is truncated, otherwise the %forward_list is extended and new * elements are populated with given data. */ void resize(size_type __sz, const value_type& __val); /** * @brief Erases all the elements. * * Note that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() noexcept { this->_M_erase_after(&this->_M_impl._M_head, nullptr); } // 23.3.4.6 forward_list operations: /** * @brief Insert contents of another %forward_list. * @param __pos Iterator referencing the element to insert after. * @param __list Source list. * * The elements of @a list are inserted in constant time after * the element referenced by @a pos. @a list becomes an empty * list. * * Requires this != @a x. */ void splice_after(const_iterator __pos, forward_list&& __list) noexcept { if (!__list.empty()) _M_splice_after(__pos, __list.before_begin(), __list.end()); } void splice_after(const_iterator __pos, forward_list& __list) noexcept { splice_after(__pos, std::move(__list)); } /** * @brief Insert element from another %forward_list. * @param __pos Iterator referencing the element to insert after. * @param __list Source list. * @param __i Iterator referencing the element before the element * to move. * * Removes the element in list @a list referenced by @a i and * inserts it into the current list after @a pos. */ void splice_after(const_iterator __pos, forward_list&& __list, const_iterator __i) noexcept; void splice_after(const_iterator __pos, forward_list& __list, const_iterator __i) noexcept { splice_after(__pos, std::move(__list), __i); } /** * @brief Insert range from another %forward_list. * @param __pos Iterator referencing the element to insert after. * @param __list Source list. * @param __before Iterator referencing before the start of range * in list. * @param __last Iterator referencing the end of range in list. * * Removes elements in the range (__before,__last) and inserts them * after @a __pos in constant time. * * Undefined if @a __pos is in (__before,__last). * @{ */ void splice_after(const_iterator __pos, forward_list&&, const_iterator __before, const_iterator __last) noexcept { _M_splice_after(__pos, __before, __last); } void splice_after(const_iterator __pos, forward_list&, const_iterator __before, const_iterator __last) noexcept { _M_splice_after(__pos, __before, __last); } // @} /** * @brief Remove all elements equal to value. * @param __val The value to remove. * * Removes every element in the list equal to @a __val. * Remaining elements stay in list order. Note that this * function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void remove(const _Tp& __val); /** * @brief Remove all elements satisfying a predicate. * @param __pred Unary predicate function or object. * * Removes every element in the list for which the predicate * returns true. Remaining elements stay in list order. Note * that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ template void remove_if(_Pred __pred); /** * @brief Remove consecutive duplicate elements. * * For each consecutive set of elements with the same value, * remove all but the first one. Remaining elements stay in * list order. Note that this function only erases the * elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ void unique() { unique(std::equal_to<_Tp>()); } /** * @brief Remove consecutive elements satisfying a predicate. * @param __binary_pred Binary predicate function or object. * * For each consecutive set of elements [first,last) that * satisfy predicate(first,i) where i is an iterator in * [first,last), remove all but the first one. Remaining * elements stay in list order. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ template void unique(_BinPred __binary_pred); /** * @brief Merge sorted lists. * @param __list Sorted list to merge. * * Assumes that both @a list and this list are sorted according to * operator<(). Merges elements of @a __list into this list in * sorted order, leaving @a __list empty when complete. Elements in * this list precede elements in @a __list that are equal. */ void merge(forward_list&& __list) { merge(std::move(__list), std::less<_Tp>()); } void merge(forward_list& __list) { merge(std::move(__list)); } /** * @brief Merge sorted lists according to comparison function. * @param __list Sorted list to merge. * @param __comp Comparison function defining sort order. * * Assumes that both @a __list and this list are sorted according to * comp. Merges elements of @a __list into this list * in sorted order, leaving @a __list empty when complete. Elements * in this list precede elements in @a __list that are equivalent * according to comp(). */ template void merge(forward_list&& __list, _Comp __comp); template void merge(forward_list& __list, _Comp __comp) { merge(std::move(__list), __comp); } /** * @brief Sort the elements of the list. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ void sort() { sort(std::less<_Tp>()); } /** * @brief Sort the forward_list using a comparison function. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ template void sort(_Comp __comp); /** * @brief Reverse the elements in list. * * Reverse the order of elements in the list in linear time. */ void reverse() noexcept { this->_M_impl._M_head._M_reverse_after(); } private: // Called by the range constructor to implement [23.3.4.2]/9 template void _M_range_initialize(_InputIterator __first, _InputIterator __last); // Called by forward_list(n,v,a), and the range constructor when it // turns out to be the same thing. void _M_fill_initialize(size_type __n, const value_type& __value); // Called by splice_after and insert_after. iterator _M_splice_after(const_iterator __pos, const_iterator __before, const_iterator __last); // Called by forward_list(n). void _M_default_initialize(size_type __n); // Called by resize(sz). void _M_default_insert_after(const_iterator __pos, size_type __n); // Called by operator=(forward_list&&) void _M_move_assign(forward_list&& __list, true_type) noexcept { clear(); this->_M_impl._M_head._M_next = __list._M_impl._M_head._M_next; __list._M_impl._M_head._M_next = nullptr; std::__alloc_on_move(this->_M_get_Node_allocator(), __list._M_get_Node_allocator()); } // Called by operator=(forward_list&&) void _M_move_assign(forward_list&& __list, false_type) { if (__list._M_get_Node_allocator() == this->_M_get_Node_allocator()) _M_move_assign(std::move(__list), true_type()); else // The rvalue's allocator cannot be moved, or is not equal, // so we need to individually move each element. this->assign(std::__make_move_if_noexcept_iterator(__list.begin()), std::__make_move_if_noexcept_iterator(__list.end())); } // Called by assign(_InputIterator, _InputIterator) if _Tp is // CopyAssignable. template void _M_assign(_InputIterator __first, _InputIterator __last, true_type) { auto __prev = before_begin(); auto __curr = begin(); auto __end = end(); while (__curr != __end && __first != __last) { *__curr = *__first; ++__prev; ++__curr; ++__first; } if (__first != __last) insert_after(__prev, __first, __last); else if (__curr != __end) erase_after(__prev, __end); } // Called by assign(_InputIterator, _InputIterator) if _Tp is not // CopyAssignable. template void _M_assign(_InputIterator __first, _InputIterator __last, false_type) { clear(); insert_after(cbefore_begin(), __first, __last); } // Called by assign(size_type, const _Tp&) if Tp is CopyAssignable void _M_assign_n(size_type __n, const _Tp& __val, true_type) { auto __prev = before_begin(); auto __curr = begin(); auto __end = end(); while (__curr != __end && __n > 0) { *__curr = __val; ++__prev; ++__curr; --__n; } if (__n > 0) insert_after(__prev, __n, __val); else if (__curr != __end) erase_after(__prev, __end); } // Called by assign(size_type, const _Tp&) if Tp is non-CopyAssignable void _M_assign_n(size_type __n, const _Tp& __val, false_type) { clear(); insert_after(cbefore_begin(), __n, __val); } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> forward_list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> forward_list<_ValT, _Allocator>; #endif /** * @brief Forward list equality comparison. * @param __lx A %forward_list * @param __ly A %forward_list of the same type as @a __lx. * @return True iff the elements of the forward lists are equal. * * This is an equivalence relation. It is linear in the number of * elements of the forward lists. Deques are considered equivalent * if corresponding elements compare equal. */ template bool operator==(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly); /** * @brief Forward list ordering relation. * @param __lx A %forward_list. * @param __ly A %forward_list of the same type as @a __lx. * @return True iff @a __lx is lexicographically less than @a __ly. * * This is a total ordering relation. It is linear in the number of * elements of the forward lists. The elements must be comparable * with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return std::lexicographical_compare(__lx.cbegin(), __lx.cend(), __ly.cbegin(), __ly.cend()); } /// Based on operator== template inline bool operator!=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx == __ly); } /// Based on operator< template inline bool operator>(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return (__ly < __lx); } /// Based on operator< template inline bool operator>=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx < __ly); } /// Based on operator< template inline bool operator<=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__ly < __lx); } /// See std::forward_list::swap(). template inline void swap(forward_list<_Tp, _Alloc>& __lx, forward_list<_Tp, _Alloc>& __ly) noexcept(noexcept(__lx.swap(__ly))) { __lx.swap(__ly); } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _FORWARD_LIST_H c++/8/bits/regex_compiler.tcc000064400000045530151027430570011736 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_compiler.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ // FIXME make comments doxygen format. /* // This compiler refers to "Regular Expression Matching Can Be Simple And Fast" // (http://swtch.com/~rsc/regexp/regexp1.html), // but doesn't strictly follow it. // // When compiling, states are *chained* instead of tree- or graph-constructed. // It's more like structured programs: there's if statement and loop statement. // // For alternative structure (say "a|b"), aka "if statement", two branches // should be constructed. However, these two shall merge to an "end_tag" at // the end of this operator: // // branch1 // / \ // => begin_tag end_tag => // \ / // branch2 // // This is the difference between this implementation and that in Russ's // article. // // That's why we introduced dummy node here ------ "end_tag" is a dummy node. // All dummy nodes will be eliminated at the end of compilation. */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { template _Compiler<_TraitsT>:: _Compiler(_IterT __b, _IterT __e, const typename _TraitsT::locale_type& __loc, _FlagT __flags) : _M_flags((__flags & (regex_constants::ECMAScript | regex_constants::basic | regex_constants::extended | regex_constants::grep | regex_constants::egrep | regex_constants::awk)) ? __flags : __flags | regex_constants::ECMAScript), _M_scanner(__b, __e, _M_flags, __loc), _M_nfa(make_shared<_RegexT>(__loc, _M_flags)), _M_traits(_M_nfa->_M_traits), _M_ctype(std::use_facet<_CtypeT>(__loc)) { _StateSeqT __r(*_M_nfa, _M_nfa->_M_start()); __r._M_append(_M_nfa->_M_insert_subexpr_begin()); this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_eof)) __throw_regex_error(regex_constants::error_paren); __r._M_append(_M_pop()); __glibcxx_assert(_M_stack.empty()); __r._M_append(_M_nfa->_M_insert_subexpr_end()); __r._M_append(_M_nfa->_M_insert_accept()); _M_nfa->_M_eliminate_dummy(); } template void _Compiler<_TraitsT>:: _M_disjunction() { this->_M_alternative(); while (_M_match_token(_ScannerT::_S_token_or)) { _StateSeqT __alt1 = _M_pop(); this->_M_alternative(); _StateSeqT __alt2 = _M_pop(); auto __end = _M_nfa->_M_insert_dummy(); __alt1._M_append(__end); __alt2._M_append(__end); // __alt2 is state._M_next, __alt1 is state._M_alt. The executor // executes _M_alt before _M_next, as well as executing left // alternative before right one. _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_alt( __alt2._M_start, __alt1._M_start, false), __end)); } } template void _Compiler<_TraitsT>:: _M_alternative() { if (this->_M_term()) { _StateSeqT __re = _M_pop(); this->_M_alternative(); __re._M_append(_M_pop()); _M_stack.push(__re); } else _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_dummy())); } template bool _Compiler<_TraitsT>:: _M_term() { if (this->_M_assertion()) return true; if (this->_M_atom()) { while (this->_M_quantifier()) ; return true; } return false; } template bool _Compiler<_TraitsT>:: _M_assertion() { if (_M_match_token(_ScannerT::_S_token_line_begin)) _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_line_begin())); else if (_M_match_token(_ScannerT::_S_token_line_end)) _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_line_end())); else if (_M_match_token(_ScannerT::_S_token_word_bound)) // _M_value[0] == 'n' means it's negative, say "not word boundary". _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa-> _M_insert_word_bound(_M_value[0] == 'n'))); else if (_M_match_token(_ScannerT::_S_token_subexpr_lookahead_begin)) { auto __neg = _M_value[0] == 'n'; this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_subexpr_end)) __throw_regex_error(regex_constants::error_paren, "Parenthesis is not closed."); auto __tmp = _M_pop(); __tmp._M_append(_M_nfa->_M_insert_accept()); _M_stack.push( _StateSeqT( *_M_nfa, _M_nfa->_M_insert_lookahead(__tmp._M_start, __neg))); } else return false; return true; } template bool _Compiler<_TraitsT>:: _M_quantifier() { bool __neg = (_M_flags & regex_constants::ECMAScript); auto __init = [this, &__neg]() { if (_M_stack.empty()) __throw_regex_error(regex_constants::error_badrepeat, "Nothing to repeat before a quantifier."); __neg = __neg && _M_match_token(_ScannerT::_S_token_opt); }; if (_M_match_token(_ScannerT::_S_token_closure0)) { __init(); auto __e = _M_pop(); _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_repeat(_S_invalid_state_id, __e._M_start, __neg)); __e._M_append(__r); _M_stack.push(__r); } else if (_M_match_token(_ScannerT::_S_token_closure1)) { __init(); auto __e = _M_pop(); __e._M_append(_M_nfa->_M_insert_repeat(_S_invalid_state_id, __e._M_start, __neg)); _M_stack.push(__e); } else if (_M_match_token(_ScannerT::_S_token_opt)) { __init(); auto __e = _M_pop(); auto __end = _M_nfa->_M_insert_dummy(); _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_repeat(_S_invalid_state_id, __e._M_start, __neg)); __e._M_append(__end); __r._M_append(__end); _M_stack.push(__r); } else if (_M_match_token(_ScannerT::_S_token_interval_begin)) { if (_M_stack.empty()) __throw_regex_error(regex_constants::error_badrepeat, "Nothing to repeat before a quantifier."); if (!_M_match_token(_ScannerT::_S_token_dup_count)) __throw_regex_error(regex_constants::error_badbrace, "Unexpected token in brace expression."); _StateSeqT __r(_M_pop()); _StateSeqT __e(*_M_nfa, _M_nfa->_M_insert_dummy()); long __min_rep = _M_cur_int_value(10); bool __infi = false; long __n; // {3 if (_M_match_token(_ScannerT::_S_token_comma)) if (_M_match_token(_ScannerT::_S_token_dup_count)) // {3,7} __n = _M_cur_int_value(10) - __min_rep; else __infi = true; else __n = 0; if (!_M_match_token(_ScannerT::_S_token_interval_end)) __throw_regex_error(regex_constants::error_brace, "Unexpected end of brace expression."); __neg = __neg && _M_match_token(_ScannerT::_S_token_opt); for (long __i = 0; __i < __min_rep; ++__i) __e._M_append(__r._M_clone()); if (__infi) { auto __tmp = __r._M_clone(); _StateSeqT __s(*_M_nfa, _M_nfa->_M_insert_repeat(_S_invalid_state_id, __tmp._M_start, __neg)); __tmp._M_append(__s); __e._M_append(__s); } else { if (__n < 0) __throw_regex_error(regex_constants::error_badbrace, "Invalid range in brace expression."); auto __end = _M_nfa->_M_insert_dummy(); // _M_alt is the "match more" branch, and _M_next is the // "match less" one. Switch _M_alt and _M_next of all created // nodes. This is a hack but IMO works well. std::stack<_StateIdT> __stack; for (long __i = 0; __i < __n; ++__i) { auto __tmp = __r._M_clone(); auto __alt = _M_nfa->_M_insert_repeat(__tmp._M_start, __end, __neg); __stack.push(__alt); __e._M_append(_StateSeqT(*_M_nfa, __alt, __tmp._M_end)); } __e._M_append(__end); while (!__stack.empty()) { auto& __tmp = (*_M_nfa)[__stack.top()]; __stack.pop(); std::swap(__tmp._M_next, __tmp._M_alt); } } _M_stack.push(__e); } else return false; return true; } #define __INSERT_REGEX_MATCHER(__func, ...)\ do {\ if (!(_M_flags & regex_constants::icase))\ if (!(_M_flags & regex_constants::collate))\ __func(__VA_ARGS__);\ else\ __func(__VA_ARGS__);\ else\ if (!(_M_flags & regex_constants::collate))\ __func(__VA_ARGS__);\ else\ __func(__VA_ARGS__);\ } while (false) template bool _Compiler<_TraitsT>:: _M_atom() { if (_M_match_token(_ScannerT::_S_token_anychar)) { if (!(_M_flags & regex_constants::ECMAScript)) __INSERT_REGEX_MATCHER(_M_insert_any_matcher_posix); else __INSERT_REGEX_MATCHER(_M_insert_any_matcher_ecma); } else if (_M_try_char()) __INSERT_REGEX_MATCHER(_M_insert_char_matcher); else if (_M_match_token(_ScannerT::_S_token_backref)) _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa-> _M_insert_backref(_M_cur_int_value(10)))); else if (_M_match_token(_ScannerT::_S_token_quoted_class)) __INSERT_REGEX_MATCHER(_M_insert_character_class_matcher); else if (_M_match_token(_ScannerT::_S_token_subexpr_no_group_begin)) { _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_dummy()); this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_subexpr_end)) __throw_regex_error(regex_constants::error_paren, "Parenthesis is not closed."); __r._M_append(_M_pop()); _M_stack.push(__r); } else if (_M_match_token(_ScannerT::_S_token_subexpr_begin)) { _StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_subexpr_begin()); this->_M_disjunction(); if (!_M_match_token(_ScannerT::_S_token_subexpr_end)) __throw_regex_error(regex_constants::error_paren, "Parenthesis is not closed."); __r._M_append(_M_pop()); __r._M_append(_M_nfa->_M_insert_subexpr_end()); _M_stack.push(__r); } else if (!_M_bracket_expression()) return false; return true; } template bool _Compiler<_TraitsT>:: _M_bracket_expression() { bool __neg = _M_match_token(_ScannerT::_S_token_bracket_neg_begin); if (!(__neg || _M_match_token(_ScannerT::_S_token_bracket_begin))) return false; __INSERT_REGEX_MATCHER(_M_insert_bracket_matcher, __neg); return true; } #undef __INSERT_REGEX_MATCHER template template void _Compiler<_TraitsT>:: _M_insert_any_matcher_ecma() { _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher (_AnyMatcher<_TraitsT, true, __icase, __collate> (_M_traits)))); } template template void _Compiler<_TraitsT>:: _M_insert_any_matcher_posix() { _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher (_AnyMatcher<_TraitsT, false, __icase, __collate> (_M_traits)))); } template template void _Compiler<_TraitsT>:: _M_insert_char_matcher() { _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher (_CharMatcher<_TraitsT, __icase, __collate> (_M_value[0], _M_traits)))); } template template void _Compiler<_TraitsT>:: _M_insert_character_class_matcher() { __glibcxx_assert(_M_value.size() == 1); _BracketMatcher<__icase, __collate> __matcher (_M_ctype.is(_CtypeT::upper, _M_value[0]), _M_traits); __matcher._M_add_character_class(_M_value, false); __matcher._M_ready(); _M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_matcher(std::move(__matcher)))); } template template void _Compiler<_TraitsT>:: _M_insert_bracket_matcher(bool __neg) { _BracketMatcher<__icase, __collate> __matcher(__neg, _M_traits); _BracketState __last_char; if (_M_try_char()) __last_char.set(_M_value[0]); else if (_M_match_token(_ScannerT::_S_token_bracket_dash)) // Dash as first character is a normal character. __last_char.set('-'); while (_M_expression_term(__last_char, __matcher)) ; if (__last_char._M_is_char()) __matcher._M_add_char(__last_char.get()); __matcher._M_ready(); _M_stack.push(_StateSeqT( *_M_nfa, _M_nfa->_M_insert_matcher(std::move(__matcher)))); } template template bool _Compiler<_TraitsT>:: _M_expression_term(_BracketState& __last_char, _BracketMatcher<__icase, __collate>& __matcher) { if (_M_match_token(_ScannerT::_S_token_bracket_end)) return false; // Add any previously cached char into the matcher and update cache. const auto __push_char = [&](_CharT __ch) { if (__last_char._M_is_char()) __matcher._M_add_char(__last_char.get()); __last_char.set(__ch); }; // Add any previously cached char into the matcher and update cache. const auto __push_class = [&] { if (__last_char._M_is_char()) __matcher._M_add_char(__last_char.get()); // We don't cache anything here, just record that the last thing // processed was a character class (or similar). __last_char.reset(_BracketState::_Type::_Class); }; if (_M_match_token(_ScannerT::_S_token_collsymbol)) { auto __symbol = __matcher._M_add_collate_element(_M_value); if (__symbol.size() == 1) __push_char(__symbol[0]); else __push_class(); } else if (_M_match_token(_ScannerT::_S_token_equiv_class_name)) { __push_class(); __matcher._M_add_equivalence_class(_M_value); } else if (_M_match_token(_ScannerT::_S_token_char_class_name)) { __push_class(); __matcher._M_add_character_class(_M_value, false); } else if (_M_try_char()) __push_char(_M_value[0]); // POSIX doesn't allow '-' as a start-range char (say [a-z--0]), // except when the '-' is the first or last character in the bracket // expression ([--0]). ECMAScript treats all '-' after a range as a // normal character. Also see above, where _M_expression_term gets called. // // As a result, POSIX rejects [-----], but ECMAScript doesn't. // Boost (1.57.0) always uses POSIX style even in its ECMAScript syntax. // Clang (3.5) always uses ECMAScript style even in its POSIX syntax. // // It turns out that no one reads BNFs ;) else if (_M_match_token(_ScannerT::_S_token_bracket_dash)) { if (_M_match_token(_ScannerT::_S_token_bracket_end)) { // For "-]" the dash is a literal character. __push_char('-'); return false; } else if (__last_char._M_is_class()) { // "\\w-" is invalid, start of range must be a single char. __throw_regex_error(regex_constants::error_range, "Invalid start of range in bracket expression."); } else if (__last_char._M_is_char()) { if (_M_try_char()) { // "x-y" __matcher._M_make_range(__last_char.get(), _M_value[0]); __last_char.reset(); } else if (_M_match_token(_ScannerT::_S_token_bracket_dash)) { // "x--" __matcher._M_make_range(__last_char.get(), '-'); __last_char.reset(); } else __throw_regex_error(regex_constants::error_range, "Invalid end of range in bracket expression."); } else if (_M_flags & regex_constants::ECMAScript) { // A dash that is not part of an existing range. Might be the // start of a new range, or might just be a literal '-' char. // Only ECMAScript allows that in the middle of a bracket expr. __push_char('-'); } else __throw_regex_error(regex_constants::error_range, "Invalid dash in bracket expression."); } else if (_M_match_token(_ScannerT::_S_token_quoted_class)) { __push_class(); __matcher._M_add_character_class(_M_value, _M_ctype.is(_CtypeT::upper, _M_value[0])); } else __throw_regex_error(regex_constants::error_brack, "Unexpected character in bracket expression."); return true; } template bool _Compiler<_TraitsT>:: _M_try_char() { bool __is_char = false; if (_M_match_token(_ScannerT::_S_token_oct_num)) { __is_char = true; _M_value.assign(1, _M_cur_int_value(8)); } else if (_M_match_token(_ScannerT::_S_token_hex_num)) { __is_char = true; _M_value.assign(1, _M_cur_int_value(16)); } else if (_M_match_token(_ScannerT::_S_token_ord_char)) __is_char = true; return __is_char; } template bool _Compiler<_TraitsT>:: _M_match_token(_TokenT __token) { if (__token == _M_scanner._M_get_token()) { _M_value = _M_scanner._M_get_value(); _M_scanner._M_advance(); return true; } return false; } template int _Compiler<_TraitsT>:: _M_cur_int_value(int __radix) { long __v = 0; for (typename _StringT::size_type __i = 0; __i < _M_value.length(); ++__i) __v =__v * __radix + _M_traits.value(_M_value[__i], __radix); return __v; } template bool _BracketMatcher<_TraitsT, __icase, __collate>:: _M_apply(_CharT __ch, false_type) const { return [this, __ch] { if (std::binary_search(_M_char_set.begin(), _M_char_set.end(), _M_translator._M_translate(__ch))) return true; auto __s = _M_translator._M_transform(__ch); for (auto& __it : _M_range_set) if (_M_translator._M_match_range(__it.first, __it.second, __s)) return true; if (_M_traits.isctype(__ch, _M_class_set)) return true; if (std::find(_M_equiv_set.begin(), _M_equiv_set.end(), _M_traits.transform_primary(&__ch, &__ch+1)) != _M_equiv_set.end()) return true; for (auto& __it : _M_neg_class_set) if (!_M_traits.isctype(__ch, __it)) return true; return false; }() ^ _M_is_non_matching; } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/bits/parse_numbers.h000064400000017410151027430570011251 0ustar00// Components for compile-time parsing of numbers -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/parse_numbers.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{chrono} */ #ifndef _GLIBCXX_PARSE_NUMBERS_H #define _GLIBCXX_PARSE_NUMBERS_H 1 #pragma GCC system_header // From n3642.pdf except I added binary literals and digit separator '\''. #if __cplusplus > 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __parse_int { template struct _Digit; template struct _Digit<_Base, '0'> : integral_constant { using __valid = true_type; }; template struct _Digit<_Base, '1'> : integral_constant { using __valid = true_type; }; template struct _Digit_impl : integral_constant { static_assert(_Base > _Val, "invalid digit"); using __valid = true_type; }; template struct _Digit<_Base, '2'> : _Digit_impl<_Base, 2> { }; template struct _Digit<_Base, '3'> : _Digit_impl<_Base, 3> { }; template struct _Digit<_Base, '4'> : _Digit_impl<_Base, 4> { }; template struct _Digit<_Base, '5'> : _Digit_impl<_Base, 5> { }; template struct _Digit<_Base, '6'> : _Digit_impl<_Base, 6> { }; template struct _Digit<_Base, '7'> : _Digit_impl<_Base, 7> { }; template struct _Digit<_Base, '8'> : _Digit_impl<_Base, 8> { }; template struct _Digit<_Base, '9'> : _Digit_impl<_Base, 9> { }; template struct _Digit<_Base, 'a'> : _Digit_impl<_Base, 0xa> { }; template struct _Digit<_Base, 'A'> : _Digit_impl<_Base, 0xa> { }; template struct _Digit<_Base, 'b'> : _Digit_impl<_Base, 0xb> { }; template struct _Digit<_Base, 'B'> : _Digit_impl<_Base, 0xb> { }; template struct _Digit<_Base, 'c'> : _Digit_impl<_Base, 0xc> { }; template struct _Digit<_Base, 'C'> : _Digit_impl<_Base, 0xc> { }; template struct _Digit<_Base, 'd'> : _Digit_impl<_Base, 0xd> { }; template struct _Digit<_Base, 'D'> : _Digit_impl<_Base, 0xd> { }; template struct _Digit<_Base, 'e'> : _Digit_impl<_Base, 0xe> { }; template struct _Digit<_Base, 'E'> : _Digit_impl<_Base, 0xe> { }; template struct _Digit<_Base, 'f'> : _Digit_impl<_Base, 0xf> { }; template struct _Digit<_Base, 'F'> : _Digit_impl<_Base, 0xf> { }; // Digit separator template struct _Digit<_Base, '\''> : integral_constant { using __valid = false_type; }; //------------------------------------------------------------------------------ template using __ull_constant = integral_constant; template struct _Power_help { using __next = typename _Power_help<_Base, _Digs...>::type; using __valid_digit = typename _Digit<_Base, _Dig>::__valid; using type = __ull_constant<__next::value * (__valid_digit{} ? _Base : 1ULL)>; }; template struct _Power_help<_Base, _Dig> { using __valid_digit = typename _Digit<_Base, _Dig>::__valid; using type = __ull_constant<__valid_digit::value>; }; template struct _Power : _Power_help<_Base, _Digs...>::type { }; template struct _Power<_Base> : __ull_constant<0> { }; //------------------------------------------------------------------------------ template struct _Number_help { using __digit = _Digit<_Base, _Dig>; using __valid_digit = typename __digit::__valid; using __next = _Number_help<_Base, __valid_digit::value ? _Pow / _Base : _Pow, _Digs...>; using type = __ull_constant<_Pow * __digit::value + __next::type::value>; static_assert((type::value / _Pow) == __digit::value, "integer literal does not fit in unsigned long long"); }; // Skip past digit separators: template struct _Number_help<_Base, _Pow, '\'', _Dig, _Digs...> : _Number_help<_Base, _Pow, _Dig, _Digs...> { }; // Terminating case for recursion: template struct _Number_help<_Base, 1ULL, _Dig> { using type = __ull_constant<_Digit<_Base, _Dig>::value>; }; template struct _Number : _Number_help<_Base, _Power<_Base, _Digs...>::value, _Digs...>::type { }; template struct _Number<_Base> : __ull_constant<0> { }; //------------------------------------------------------------------------------ template struct _Parse_int; template struct _Parse_int<'0', 'b', _Digs...> : _Number<2U, _Digs...>::type { }; template struct _Parse_int<'0', 'B', _Digs...> : _Number<2U, _Digs...>::type { }; template struct _Parse_int<'0', 'x', _Digs...> : _Number<16U, _Digs...>::type { }; template struct _Parse_int<'0', 'X', _Digs...> : _Number<16U, _Digs...>::type { }; template struct _Parse_int<'0', _Digs...> : _Number<8U, _Digs...>::type { }; template struct _Parse_int : _Number<10U, _Digs...>::type { }; } // namespace __parse_int namespace __select_int { template struct _Select_int_base; template struct _Select_int_base<_Val, _IntType, _Ints...> : conditional_t<(_Val <= std::numeric_limits<_IntType>::max()), integral_constant<_IntType, _Val>, _Select_int_base<_Val, _Ints...>> { }; template struct _Select_int_base<_Val> { }; template using _Select_int = typename _Select_int_base< __parse_int::_Parse_int<_Digs...>::value, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long >::type; } // namespace __select_int _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // __cplusplus > 201103L #endif // _GLIBCXX_PARSE_NUMBERS_H c++/8/bits/stream_iterator.h000064400000014776151027430570011624 0ustar00// Stream iterators // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/stream_iterator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _STREAM_ITERATOR_H #define _STREAM_ITERATOR_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup iterators * @{ */ /// Provides input iterator semantics for streams. template, typename _Dist = ptrdiff_t> class istream_iterator : public iterator { public: typedef _CharT char_type; typedef _Traits traits_type; typedef basic_istream<_CharT, _Traits> istream_type; private: istream_type* _M_stream; _Tp _M_value; bool _M_ok; public: /// Construct end of input stream iterator. _GLIBCXX_CONSTEXPR istream_iterator() : _M_stream(0), _M_value(), _M_ok(false) {} /// Construct start of input stream iterator. istream_iterator(istream_type& __s) : _M_stream(std::__addressof(__s)) { _M_read(); } istream_iterator(const istream_iterator& __obj) : _M_stream(__obj._M_stream), _M_value(__obj._M_value), _M_ok(__obj._M_ok) { } const _Tp& operator*() const { __glibcxx_requires_cond(_M_ok, _M_message(__gnu_debug::__msg_deref_istream) ._M_iterator(*this)); return _M_value; } const _Tp* operator->() const { return std::__addressof((operator*())); } istream_iterator& operator++() { __glibcxx_requires_cond(_M_ok, _M_message(__gnu_debug::__msg_inc_istream) ._M_iterator(*this)); _M_read(); return *this; } istream_iterator operator++(int) { __glibcxx_requires_cond(_M_ok, _M_message(__gnu_debug::__msg_inc_istream) ._M_iterator(*this)); istream_iterator __tmp = *this; _M_read(); return __tmp; } bool _M_equal(const istream_iterator& __x) const { return (_M_ok == __x._M_ok) && (!_M_ok || _M_stream == __x._M_stream); } private: void _M_read() { _M_ok = (_M_stream && *_M_stream) ? true : false; if (_M_ok) { *_M_stream >> _M_value; _M_ok = *_M_stream ? true : false; } } }; /// Return true if x and y are both end or not end, or x and y are the same. template inline bool operator==(const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __x, const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __y) { return __x._M_equal(__y); } /// Return false if x and y are both end or not end, or x and y are the same. template inline bool operator!=(const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __x, const istream_iterator<_Tp, _CharT, _Traits, _Dist>& __y) { return !__x._M_equal(__y); } /** * @brief Provides output iterator semantics for streams. * * This class provides an iterator to write to an ostream. The type Tp is * the only type written by this iterator and there must be an * operator<<(Tp) defined. * * @tparam _Tp The type to write to the ostream. * @tparam _CharT The ostream char_type. * @tparam _Traits The ostream char_traits. */ template > class ostream_iterator : public iterator { public: //@{ /// Public typedef typedef _CharT char_type; typedef _Traits traits_type; typedef basic_ostream<_CharT, _Traits> ostream_type; //@} private: ostream_type* _M_stream; const _CharT* _M_string; public: /// Construct from an ostream. ostream_iterator(ostream_type& __s) : _M_stream(std::__addressof(__s)), _M_string(0) {} /** * Construct from an ostream. * * The delimiter string @a c is written to the stream after every Tp * written to the stream. The delimiter is not copied, and thus must * not be destroyed while this iterator is in use. * * @param __s Underlying ostream to write to. * @param __c CharT delimiter string to insert. */ ostream_iterator(ostream_type& __s, const _CharT* __c) : _M_stream(&__s), _M_string(__c) { } /// Copy constructor. ostream_iterator(const ostream_iterator& __obj) : _M_stream(__obj._M_stream), _M_string(__obj._M_string) { } /// Writes @a value to underlying ostream using operator<<. If /// constructed with delimiter string, writes delimiter to ostream. ostream_iterator& operator=(const _Tp& __value) { __glibcxx_requires_cond(_M_stream != 0, _M_message(__gnu_debug::__msg_output_ostream) ._M_iterator(*this)); *_M_stream << __value; if (_M_string) *_M_stream << _M_string; return *this; } ostream_iterator& operator*() { return *this; } ostream_iterator& operator++() { return *this; } ostream_iterator& operator++(int) { return *this; } }; // @} group iterators _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/hashtable.h000064400000220071151027430570010336 0ustar00// hashtable.h header -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/hashtable.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{unordered_map, unordered_set} */ #ifndef _HASHTABLE_H #define _HASHTABLE_H 1 #pragma GCC system_header #include #if __cplusplus > 201402L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template using __cache_default = __not_<__and_, // Mandatory to have erase not throwing. __is_nothrow_invocable>>; /** * Primary class template _Hashtable. * * @ingroup hashtable-detail * * @tparam _Value CopyConstructible type. * * @tparam _Key CopyConstructible type. * * @tparam _Alloc An allocator type * ([lib.allocator.requirements]) whose _Alloc::value_type is * _Value. As a conforming extension, we allow for * _Alloc::value_type != _Value. * * @tparam _ExtractKey Function object that takes an object of type * _Value and returns a value of type _Key. * * @tparam _Equal Function object that takes two objects of type k * and returns a bool-like value that is true if the two objects * are considered equal. * * @tparam _H1 The hash function. A unary function object with * argument type _Key and result type size_t. Return values should * be distributed over the entire range [0, numeric_limits:::max()]. * * @tparam _H2 The range-hashing function (in the terminology of * Tavori and Dreizin). A binary function object whose argument * types and result type are all size_t. Given arguments r and N, * the return value is in the range [0, N). * * @tparam _Hash The ranged hash function (Tavori and Dreizin). A * binary function whose argument types are _Key and size_t and * whose result type is size_t. Given arguments k and N, the * return value is in the range [0, N). Default: hash(k, N) = * h2(h1(k), N). If _Hash is anything other than the default, _H1 * and _H2 are ignored. * * @tparam _RehashPolicy Policy class with three members, all of * which govern the bucket count. _M_next_bkt(n) returns a bucket * count no smaller than n. _M_bkt_for_elements(n) returns a * bucket count appropriate for an element count of n. * _M_need_rehash(n_bkt, n_elt, n_ins) determines whether, if the * current bucket count is n_bkt and the current element count is * n_elt, we need to increase the bucket count. If so, returns * make_pair(true, n), where n is the new bucket count. If not, * returns make_pair(false, ) * * @tparam _Traits Compile-time class with three boolean * std::integral_constant members: __cache_hash_code, __constant_iterators, * __unique_keys. * * Each _Hashtable data structure has: * * - _Bucket[] _M_buckets * - _Hash_node_base _M_before_begin * - size_type _M_bucket_count * - size_type _M_element_count * * with _Bucket being _Hash_node* and _Hash_node containing: * * - _Hash_node* _M_next * - Tp _M_value * - size_t _M_hash_code if cache_hash_code is true * * In terms of Standard containers the hashtable is like the aggregation of: * * - std::forward_list<_Node> containing the elements * - std::vector::iterator> representing the buckets * * The non-empty buckets contain the node before the first node in the * bucket. This design makes it possible to implement something like a * std::forward_list::insert_after on container insertion and * std::forward_list::erase_after on container erase * calls. _M_before_begin is equivalent to * std::forward_list::before_begin. Empty buckets contain * nullptr. Note that one of the non-empty buckets contains * &_M_before_begin which is not a dereferenceable node so the * node pointer in a bucket shall never be dereferenced, only its * next node can be. * * Walking through a bucket's nodes requires a check on the hash code to * see if each node is still in the bucket. Such a design assumes a * quite efficient hash functor and is one of the reasons it is * highly advisable to set __cache_hash_code to true. * * The container iterators are simply built from nodes. This way * incrementing the iterator is perfectly efficient independent of * how many empty buckets there are in the container. * * On insert we compute the element's hash code and use it to find the * bucket index. If the element must be inserted in an empty bucket * we add it at the beginning of the singly linked list and make the * bucket point to _M_before_begin. The bucket that used to point to * _M_before_begin, if any, is updated to point to its new before * begin node. * * On erase, the simple iterator design requires using the hash * functor to get the index of the bucket to update. For this * reason, when __cache_hash_code is set to false the hash functor must * not throw and this is enforced by a static assertion. * * Functionality is implemented by decomposition into base classes, * where the derived _Hashtable class is used in _Map_base, * _Insert, _Rehash_base, and _Equality base classes to access the * "this" pointer. _Hashtable_base is used in the base classes as a * non-recursive, fully-completed-type so that detailed nested type * information, such as iterator type and node type, can be * used. This is similar to the "Curiously Recurring Template * Pattern" (CRTP) technique, but uses a reconstructed, not * explicitly passed, template pattern. * * Base class templates are: * - __detail::_Hashtable_base * - __detail::_Map_base * - __detail::_Insert * - __detail::_Rehash_base * - __detail::_Equality */ template class _Hashtable : public __detail::_Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>, public __detail::_Map_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, public __detail::_Insert<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, public __detail::_Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, public __detail::_Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>, private __detail::_Hashtable_alloc< __alloc_rebind<_Alloc, __detail::_Hash_node<_Value, _Traits::__hash_cached::value>>> { static_assert(is_same::type, _Value>::value, "unordered container must have a non-const, non-volatile value_type"); #ifdef __STRICT_ANSI__ static_assert(is_same{}, "unordered container must have the same value_type as its allocator"); #endif using __traits_type = _Traits; using __hash_cached = typename __traits_type::__hash_cached; using __node_type = __detail::_Hash_node<_Value, __hash_cached::value>; using __node_alloc_type = __alloc_rebind<_Alloc, __node_type>; using __hashtable_alloc = __detail::_Hashtable_alloc<__node_alloc_type>; using __value_alloc_traits = typename __hashtable_alloc::__value_alloc_traits; using __node_alloc_traits = typename __hashtable_alloc::__node_alloc_traits; using __node_base = typename __hashtable_alloc::__node_base; using __bucket_type = typename __hashtable_alloc::__bucket_type; public: typedef _Key key_type; typedef _Value value_type; typedef _Alloc allocator_type; typedef _Equal key_equal; // mapped_type, if present, comes from _Map_base. // hasher, if present, comes from _Hash_code_base/_Hashtable_base. typedef typename __value_alloc_traits::pointer pointer; typedef typename __value_alloc_traits::const_pointer const_pointer; typedef value_type& reference; typedef const value_type& const_reference; private: using __rehash_type = _RehashPolicy; using __rehash_state = typename __rehash_type::_State; using __constant_iterators = typename __traits_type::__constant_iterators; using __unique_keys = typename __traits_type::__unique_keys; using __key_extract = typename std::conditional< __constant_iterators::value, __detail::_Identity, __detail::_Select1st>::type; using __hashtable_base = __detail:: _Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>; using __hash_code_base = typename __hashtable_base::__hash_code_base; using __hash_code = typename __hashtable_base::__hash_code; using __ireturn_type = typename __hashtable_base::__ireturn_type; using __map_base = __detail::_Map_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __rehash_base = __detail::_Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __eq_base = __detail::_Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __reuse_or_alloc_node_type = __detail::_ReuseOrAllocNode<__node_alloc_type>; // Metaprogramming for picking apart hash caching. template using __if_hash_cached = __or_<__not_<__hash_cached>, _Cond>; template using __if_hash_not_cached = __or_<__hash_cached, _Cond>; // Compile-time diagnostics. // _Hash_code_base has everything protected, so use this derived type to // access it. struct __hash_code_base_access : __hash_code_base { using __hash_code_base::_M_bucket_index; }; // Getting a bucket index from a node shall not throw because it is used // in methods (erase, swap...) that shall not throw. static_assert(noexcept(declval() ._M_bucket_index((const __node_type*)nullptr, (std::size_t)0)), "Cache the hash code or qualify your functors involved" " in hash code and bucket index computation with noexcept"); // Following two static assertions are necessary to guarantee // that local_iterator will be default constructible. // When hash codes are cached local iterator inherits from H2 functor // which must then be default constructible. static_assert(__if_hash_cached>::value, "Functor used to map hash code to bucket index" " must be default constructible"); template friend struct __detail::_Map_base; template friend struct __detail::_Insert_base; template friend struct __detail::_Insert; public: using size_type = typename __hashtable_base::size_type; using difference_type = typename __hashtable_base::difference_type; using iterator = typename __hashtable_base::iterator; using const_iterator = typename __hashtable_base::const_iterator; using local_iterator = typename __hashtable_base::local_iterator; using const_local_iterator = typename __hashtable_base:: const_local_iterator; #if __cplusplus > 201402L using node_type = _Node_handle<_Key, _Value, __node_alloc_type>; using insert_return_type = _Node_insert_return; #endif private: __bucket_type* _M_buckets = &_M_single_bucket; size_type _M_bucket_count = 1; __node_base _M_before_begin; size_type _M_element_count = 0; _RehashPolicy _M_rehash_policy; // A single bucket used when only need for 1 bucket. Especially // interesting in move semantic to leave hashtable with only 1 buckets // which is not allocated so that we can have those operations noexcept // qualified. // Note that we can't leave hashtable with 0 bucket without adding // numerous checks in the code to avoid 0 modulus. __bucket_type _M_single_bucket = nullptr; bool _M_uses_single_bucket(__bucket_type* __bkts) const { return __builtin_expect(__bkts == &_M_single_bucket, false); } bool _M_uses_single_bucket() const { return _M_uses_single_bucket(_M_buckets); } __hashtable_alloc& _M_base_alloc() { return *this; } __bucket_type* _M_allocate_buckets(size_type __n) { if (__builtin_expect(__n == 1, false)) { _M_single_bucket = nullptr; return &_M_single_bucket; } return __hashtable_alloc::_M_allocate_buckets(__n); } void _M_deallocate_buckets(__bucket_type* __bkts, size_type __n) { if (_M_uses_single_bucket(__bkts)) return; __hashtable_alloc::_M_deallocate_buckets(__bkts, __n); } void _M_deallocate_buckets() { _M_deallocate_buckets(_M_buckets, _M_bucket_count); } // Gets bucket begin, deals with the fact that non-empty buckets contain // their before begin node. __node_type* _M_bucket_begin(size_type __bkt) const; __node_type* _M_begin() const { return static_cast<__node_type*>(_M_before_begin._M_nxt); } template void _M_assign(const _Hashtable&, const _NodeGenerator&); void _M_move_assign(_Hashtable&&, std::true_type); void _M_move_assign(_Hashtable&&, std::false_type); void _M_reset() noexcept; _Hashtable(const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : __hashtable_base(__exk, __h1, __h2, __h, __eq), __hashtable_alloc(__node_alloc_type(__a)) { } public: // Constructor, destructor, assignment, swap _Hashtable() = default; _Hashtable(size_type __bucket_hint, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const allocator_type&); template _Hashtable(_InputIterator __first, _InputIterator __last, size_type __bucket_hint, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const allocator_type&); _Hashtable(const _Hashtable&); _Hashtable(_Hashtable&&) noexcept; _Hashtable(const _Hashtable&, const allocator_type&); _Hashtable(_Hashtable&&, const allocator_type&); // Use delegating constructors. explicit _Hashtable(const allocator_type& __a) : __hashtable_alloc(__node_alloc_type(__a)) { } explicit _Hashtable(size_type __n, const _H1& __hf = _H1(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Hashtable(__n, __hf, _H2(), _Hash(), __eql, __key_extract(), __a) { } template _Hashtable(_InputIterator __f, _InputIterator __l, size_type __n = 0, const _H1& __hf = _H1(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Hashtable(__f, __l, __n, __hf, _H2(), _Hash(), __eql, __key_extract(), __a) { } _Hashtable(initializer_list __l, size_type __n = 0, const _H1& __hf = _H1(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Hashtable(__l.begin(), __l.end(), __n, __hf, _H2(), _Hash(), __eql, __key_extract(), __a) { } _Hashtable& operator=(const _Hashtable& __ht); _Hashtable& operator=(_Hashtable&& __ht) noexcept(__node_alloc_traits::_S_nothrow_move() && is_nothrow_move_assignable<_H1>::value && is_nothrow_move_assignable<_Equal>::value) { constexpr bool __move_storage = __node_alloc_traits::_S_propagate_on_move_assign() || __node_alloc_traits::_S_always_equal(); _M_move_assign(std::move(__ht), __bool_constant<__move_storage>()); return *this; } _Hashtable& operator=(initializer_list __l) { __reuse_or_alloc_node_type __roan(_M_begin(), *this); _M_before_begin._M_nxt = nullptr; clear(); this->_M_insert_range(__l.begin(), __l.end(), __roan, __unique_keys()); return *this; } ~_Hashtable() noexcept; void swap(_Hashtable&) noexcept(__and_<__is_nothrow_swappable<_H1>, __is_nothrow_swappable<_Equal>>::value); // Basic container operations iterator begin() noexcept { return iterator(_M_begin()); } const_iterator begin() const noexcept { return const_iterator(_M_begin()); } iterator end() noexcept { return iterator(nullptr); } const_iterator end() const noexcept { return const_iterator(nullptr); } const_iterator cbegin() const noexcept { return const_iterator(_M_begin()); } const_iterator cend() const noexcept { return const_iterator(nullptr); } size_type size() const noexcept { return _M_element_count; } bool empty() const noexcept { return size() == 0; } allocator_type get_allocator() const noexcept { return allocator_type(this->_M_node_allocator()); } size_type max_size() const noexcept { return __node_alloc_traits::max_size(this->_M_node_allocator()); } // Observers key_equal key_eq() const { return this->_M_eq(); } // hash_function, if present, comes from _Hash_code_base. // Bucket operations size_type bucket_count() const noexcept { return _M_bucket_count; } size_type max_bucket_count() const noexcept { return max_size(); } size_type bucket_size(size_type __n) const { return std::distance(begin(__n), end(__n)); } size_type bucket(const key_type& __k) const { return _M_bucket_index(__k, this->_M_hash_code(__k)); } local_iterator begin(size_type __n) { return local_iterator(*this, _M_bucket_begin(__n), __n, _M_bucket_count); } local_iterator end(size_type __n) { return local_iterator(*this, nullptr, __n, _M_bucket_count); } const_local_iterator begin(size_type __n) const { return const_local_iterator(*this, _M_bucket_begin(__n), __n, _M_bucket_count); } const_local_iterator end(size_type __n) const { return const_local_iterator(*this, nullptr, __n, _M_bucket_count); } // DR 691. const_local_iterator cbegin(size_type __n) const { return const_local_iterator(*this, _M_bucket_begin(__n), __n, _M_bucket_count); } const_local_iterator cend(size_type __n) const { return const_local_iterator(*this, nullptr, __n, _M_bucket_count); } float load_factor() const noexcept { return static_cast(size()) / static_cast(bucket_count()); } // max_load_factor, if present, comes from _Rehash_base. // Generalization of max_load_factor. Extension, not found in // TR1. Only useful if _RehashPolicy is something other than // the default. const _RehashPolicy& __rehash_policy() const { return _M_rehash_policy; } void __rehash_policy(const _RehashPolicy& __pol) { _M_rehash_policy = __pol; } // Lookup. iterator find(const key_type& __k); const_iterator find(const key_type& __k) const; size_type count(const key_type& __k) const; std::pair equal_range(const key_type& __k); std::pair equal_range(const key_type& __k) const; protected: // Bucket index computation helpers. size_type _M_bucket_index(__node_type* __n) const noexcept { return __hash_code_base::_M_bucket_index(__n, _M_bucket_count); } size_type _M_bucket_index(const key_type& __k, __hash_code __c) const { return __hash_code_base::_M_bucket_index(__k, __c, _M_bucket_count); } // Find and insert helper functions and types // Find the node before the one matching the criteria. __node_base* _M_find_before_node(size_type, const key_type&, __hash_code) const; __node_type* _M_find_node(size_type __bkt, const key_type& __key, __hash_code __c) const { __node_base* __before_n = _M_find_before_node(__bkt, __key, __c); if (__before_n) return static_cast<__node_type*>(__before_n->_M_nxt); return nullptr; } // Insert a node at the beginning of a bucket. void _M_insert_bucket_begin(size_type, __node_type*); // Remove the bucket first node void _M_remove_bucket_begin(size_type __bkt, __node_type* __next_n, size_type __next_bkt); // Get the node before __n in the bucket __bkt __node_base* _M_get_previous_node(size_type __bkt, __node_base* __n); // Insert node with hash code __code, in bucket bkt if no rehash (assumes // no element with its key already present). Take ownership of the node, // deallocate it on exception. iterator _M_insert_unique_node(size_type __bkt, __hash_code __code, __node_type* __n, size_type __n_elt = 1); // Insert node with hash code __code. Take ownership of the node, // deallocate it on exception. iterator _M_insert_multi_node(__node_type* __hint, __hash_code __code, __node_type* __n); template std::pair _M_emplace(std::true_type, _Args&&... __args); template iterator _M_emplace(std::false_type __uk, _Args&&... __args) { return _M_emplace(cend(), __uk, std::forward<_Args>(__args)...); } // Emplace with hint, useless when keys are unique. template iterator _M_emplace(const_iterator, std::true_type __uk, _Args&&... __args) { return _M_emplace(__uk, std::forward<_Args>(__args)...).first; } template iterator _M_emplace(const_iterator, std::false_type, _Args&&... __args); template std::pair _M_insert(_Arg&&, const _NodeGenerator&, true_type, size_type = 1); template iterator _M_insert(_Arg&& __arg, const _NodeGenerator& __node_gen, false_type __uk) { return _M_insert(cend(), std::forward<_Arg>(__arg), __node_gen, __uk); } // Insert with hint, not used when keys are unique. template iterator _M_insert(const_iterator, _Arg&& __arg, const _NodeGenerator& __node_gen, true_type __uk) { return _M_insert(std::forward<_Arg>(__arg), __node_gen, __uk).first; } // Insert with hint when keys are not unique. template iterator _M_insert(const_iterator, _Arg&&, const _NodeGenerator&, false_type); size_type _M_erase(std::true_type, const key_type&); size_type _M_erase(std::false_type, const key_type&); iterator _M_erase(size_type __bkt, __node_base* __prev_n, __node_type* __n); public: // Emplace template __ireturn_type emplace(_Args&&... __args) { return _M_emplace(__unique_keys(), std::forward<_Args>(__args)...); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { return _M_emplace(__hint, __unique_keys(), std::forward<_Args>(__args)...); } // Insert member functions via inheritance. // Erase iterator erase(const_iterator); // LWG 2059. iterator erase(iterator __it) { return erase(const_iterator(__it)); } size_type erase(const key_type& __k) { return _M_erase(__unique_keys(), __k); } iterator erase(const_iterator, const_iterator); void clear() noexcept; // Set number of buckets to be appropriate for container of n element. void rehash(size_type __n); // DR 1189. // reserve, if present, comes from _Rehash_base. #if __cplusplus > 201402L /// Re-insert an extracted node into a container with unique keys. insert_return_type _M_reinsert_node(node_type&& __nh) { insert_return_type __ret; if (__nh.empty()) __ret.position = end(); else { __glibcxx_assert(get_allocator() == __nh.get_allocator()); const key_type& __k = __nh._M_key(); __hash_code __code = this->_M_hash_code(__k); size_type __bkt = _M_bucket_index(__k, __code); if (__node_type* __n = _M_find_node(__bkt, __k, __code)) { __ret.node = std::move(__nh); __ret.position = iterator(__n); __ret.inserted = false; } else { __ret.position = _M_insert_unique_node(__bkt, __code, __nh._M_ptr); __nh._M_ptr = nullptr; __ret.inserted = true; } } return __ret; } /// Re-insert an extracted node into a container with equivalent keys. iterator _M_reinsert_node_multi(const_iterator __hint, node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(get_allocator() == __nh.get_allocator()); auto __code = this->_M_hash_code(__nh._M_key()); auto __node = std::exchange(__nh._M_ptr, nullptr); // FIXME: this deallocates the node on exception. __ret = _M_insert_multi_node(__hint._M_cur, __code, __node); } return __ret; } /// Extract a node. node_type extract(const_iterator __pos) { __node_type* __n = __pos._M_cur; size_t __bkt = _M_bucket_index(__n); // Look for previous node to unlink it from the erased one, this // is why we need buckets to contain the before begin to make // this search fast. __node_base* __prev_n = _M_get_previous_node(__bkt, __n); if (__prev_n == _M_buckets[__bkt]) _M_remove_bucket_begin(__bkt, __n->_M_next(), __n->_M_nxt ? _M_bucket_index(__n->_M_next()) : 0); else if (__n->_M_nxt) { size_type __next_bkt = _M_bucket_index(__n->_M_next()); if (__next_bkt != __bkt) _M_buckets[__next_bkt] = __prev_n; } __prev_n->_M_nxt = __n->_M_nxt; __n->_M_nxt = nullptr; --_M_element_count; return { __n, this->_M_node_allocator() }; } /// Extract a node. node_type extract(const _Key& __k) { node_type __nh; auto __pos = find(__k); if (__pos != end()) __nh = extract(const_iterator(__pos)); return __nh; } /// Merge from a compatible container into one with unique keys. template void _M_merge_unique(_Compatible_Hashtable& __src) noexcept { static_assert(is_same_v, "Node types are compatible"); __glibcxx_assert(get_allocator() == __src.get_allocator()); auto __n_elt = __src.size(); for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) { auto __pos = __i++; const key_type& __k = this->_M_extract()(__pos._M_cur->_M_v()); __hash_code __code = this->_M_hash_code(__k); size_type __bkt = _M_bucket_index(__k, __code); if (_M_find_node(__bkt, __k, __code) == nullptr) { auto __nh = __src.extract(__pos); _M_insert_unique_node(__bkt, __code, __nh._M_ptr, __n_elt); __nh._M_ptr = nullptr; __n_elt = 1; } else if (__n_elt != 1) --__n_elt; } } /// Merge from a compatible container into one with equivalent keys. template void _M_merge_multi(_Compatible_Hashtable& __src) noexcept { static_assert(is_same_v, "Node types are compatible"); __glibcxx_assert(get_allocator() == __src.get_allocator()); this->reserve(size() + __src.size()); for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) _M_reinsert_node_multi(cend(), __src.extract(__i++)); } #endif // C++17 private: // Helper rehash method used when keys are unique. void _M_rehash_aux(size_type __n, std::true_type); // Helper rehash method used when keys can be non-unique. void _M_rehash_aux(size_type __n, std::false_type); // Unconditionally change size of bucket array to n, restore // hash policy state to __state on exception. void _M_rehash(size_type __n, const __rehash_state& __state); }; // Definitions of class template _Hashtable's out-of-line member functions. template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_bucket_begin(size_type __bkt) const -> __node_type* { __node_base* __n = _M_buckets[__bkt]; return __n ? static_cast<__node_type*>(__n->_M_nxt) : nullptr; } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(size_type __bucket_hint, const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : _Hashtable(__h1, __h2, __h, __eq, __exk, __a) { auto __bkt = _M_rehash_policy._M_next_bkt(__bucket_hint); if (__bkt > _M_bucket_count) { _M_buckets = _M_allocate_buckets(__bkt); _M_bucket_count = __bkt; } } template template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(_InputIterator __f, _InputIterator __l, size_type __bucket_hint, const _H1& __h1, const _H2& __h2, const _Hash& __h, const _Equal& __eq, const _ExtractKey& __exk, const allocator_type& __a) : _Hashtable(__h1, __h2, __h, __eq, __exk, __a) { auto __nb_elems = __detail::__distance_fw(__f, __l); auto __bkt_count = _M_rehash_policy._M_next_bkt( std::max(_M_rehash_policy._M_bkt_for_elements(__nb_elems), __bucket_hint)); if (__bkt_count > _M_bucket_count) { _M_buckets = _M_allocate_buckets(__bkt_count); _M_bucket_count = __bkt_count; } for (; __f != __l; ++__f) this->insert(*__f); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: operator=(const _Hashtable& __ht) -> _Hashtable& { if (&__ht == this) return *this; if (__node_alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_node_allocator(); auto& __that_alloc = __ht._M_node_allocator(); if (!__node_alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // Replacement allocator cannot free existing storage. this->_M_deallocate_nodes(_M_begin()); _M_before_begin._M_nxt = nullptr; _M_deallocate_buckets(); _M_buckets = nullptr; std::__alloc_on_copy(__this_alloc, __that_alloc); __hashtable_base::operator=(__ht); _M_bucket_count = __ht._M_bucket_count; _M_element_count = __ht._M_element_count; _M_rehash_policy = __ht._M_rehash_policy; __try { _M_assign(__ht, [this](const __node_type* __n) { return this->_M_allocate_node(__n->_M_v()); }); } __catch(...) { // _M_assign took care of deallocating all memory. Now we // must make sure this instance remains in a usable state. _M_reset(); __throw_exception_again; } return *this; } std::__alloc_on_copy(__this_alloc, __that_alloc); } // Reuse allocated buckets and nodes. __bucket_type* __former_buckets = nullptr; std::size_t __former_bucket_count = _M_bucket_count; const __rehash_state& __former_state = _M_rehash_policy._M_state(); if (_M_bucket_count != __ht._M_bucket_count) { __former_buckets = _M_buckets; _M_buckets = _M_allocate_buckets(__ht._M_bucket_count); _M_bucket_count = __ht._M_bucket_count; } else __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __try { __hashtable_base::operator=(__ht); _M_element_count = __ht._M_element_count; _M_rehash_policy = __ht._M_rehash_policy; __reuse_or_alloc_node_type __roan(_M_begin(), *this); _M_before_begin._M_nxt = nullptr; _M_assign(__ht, [&__roan](const __node_type* __n) { return __roan(__n->_M_v()); }); if (__former_buckets) _M_deallocate_buckets(__former_buckets, __former_bucket_count); } __catch(...) { if (__former_buckets) { // Restore previous buckets. _M_deallocate_buckets(); _M_rehash_policy._M_reset(__former_state); _M_buckets = __former_buckets; _M_bucket_count = __former_bucket_count; } __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __throw_exception_again; } return *this; } template template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_assign(const _Hashtable& __ht, const _NodeGenerator& __node_gen) { __bucket_type* __buckets = nullptr; if (!_M_buckets) _M_buckets = __buckets = _M_allocate_buckets(_M_bucket_count); __try { if (!__ht._M_before_begin._M_nxt) return; // First deal with the special first node pointed to by // _M_before_begin. __node_type* __ht_n = __ht._M_begin(); __node_type* __this_n = __node_gen(__ht_n); this->_M_copy_code(__this_n, __ht_n); _M_before_begin._M_nxt = __this_n; _M_buckets[_M_bucket_index(__this_n)] = &_M_before_begin; // Then deal with other nodes. __node_base* __prev_n = __this_n; for (__ht_n = __ht_n->_M_next(); __ht_n; __ht_n = __ht_n->_M_next()) { __this_n = __node_gen(__ht_n); __prev_n->_M_nxt = __this_n; this->_M_copy_code(__this_n, __ht_n); size_type __bkt = _M_bucket_index(__this_n); if (!_M_buckets[__bkt]) _M_buckets[__bkt] = __prev_n; __prev_n = __this_n; } } __catch(...) { clear(); if (__buckets) _M_deallocate_buckets(); __throw_exception_again; } } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_reset() noexcept { _M_rehash_policy._M_reset(); _M_bucket_count = 1; _M_single_bucket = nullptr; _M_buckets = &_M_single_bucket; _M_before_begin._M_nxt = nullptr; _M_element_count = 0; } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_move_assign(_Hashtable&& __ht, std::true_type) { this->_M_deallocate_nodes(_M_begin()); _M_deallocate_buckets(); __hashtable_base::operator=(std::move(__ht)); _M_rehash_policy = __ht._M_rehash_policy; if (!__ht._M_uses_single_bucket()) _M_buckets = __ht._M_buckets; else { _M_buckets = &_M_single_bucket; _M_single_bucket = __ht._M_single_bucket; } _M_bucket_count = __ht._M_bucket_count; _M_before_begin._M_nxt = __ht._M_before_begin._M_nxt; _M_element_count = __ht._M_element_count; std::__alloc_on_move(this->_M_node_allocator(), __ht._M_node_allocator()); // Fix buckets containing the _M_before_begin pointers that can't be // moved. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; __ht._M_reset(); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_move_assign(_Hashtable&& __ht, std::false_type) { if (__ht._M_node_allocator() == this->_M_node_allocator()) _M_move_assign(std::move(__ht), std::true_type()); else { // Can't move memory, move elements then. __bucket_type* __former_buckets = nullptr; size_type __former_bucket_count = _M_bucket_count; const __rehash_state& __former_state = _M_rehash_policy._M_state(); if (_M_bucket_count != __ht._M_bucket_count) { __former_buckets = _M_buckets; _M_buckets = _M_allocate_buckets(__ht._M_bucket_count); _M_bucket_count = __ht._M_bucket_count; } else __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __try { __hashtable_base::operator=(std::move(__ht)); _M_element_count = __ht._M_element_count; _M_rehash_policy = __ht._M_rehash_policy; __reuse_or_alloc_node_type __roan(_M_begin(), *this); _M_before_begin._M_nxt = nullptr; _M_assign(__ht, [&__roan](__node_type* __n) { return __roan(std::move_if_noexcept(__n->_M_v())); }); if (__former_buckets) _M_deallocate_buckets(__former_buckets, __former_bucket_count); __ht.clear(); } __catch(...) { if (__former_buckets) { _M_deallocate_buckets(); _M_rehash_policy._M_reset(__former_state); _M_buckets = __former_buckets; _M_bucket_count = __former_bucket_count; } __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); __throw_exception_again; } } } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(const _Hashtable& __ht) : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc( __node_alloc_traits::_S_select_on_copy(__ht._M_node_allocator())), _M_buckets(nullptr), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { _M_assign(__ht, [this](const __node_type* __n) { return this->_M_allocate_node(__n->_M_v()); }); } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(_Hashtable&& __ht) noexcept : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc(std::move(__ht._M_base_alloc())), _M_buckets(__ht._M_buckets), _M_bucket_count(__ht._M_bucket_count), _M_before_begin(__ht._M_before_begin._M_nxt), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { // Update, if necessary, buckets if __ht is using its single bucket. if (__ht._M_uses_single_bucket()) { _M_buckets = &_M_single_bucket; _M_single_bucket = __ht._M_single_bucket; } // Update, if necessary, bucket pointing to before begin that hasn't // moved. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; __ht._M_reset(); } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(const _Hashtable& __ht, const allocator_type& __a) : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc(__node_alloc_type(__a)), _M_buckets(), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { _M_assign(__ht, [this](const __node_type* __n) { return this->_M_allocate_node(__n->_M_v()); }); } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _Hashtable(_Hashtable&& __ht, const allocator_type& __a) : __hashtable_base(__ht), __map_base(__ht), __rehash_base(__ht), __hashtable_alloc(__node_alloc_type(__a)), _M_buckets(nullptr), _M_bucket_count(__ht._M_bucket_count), _M_element_count(__ht._M_element_count), _M_rehash_policy(__ht._M_rehash_policy) { if (__ht._M_node_allocator() == this->_M_node_allocator()) { if (__ht._M_uses_single_bucket()) { _M_buckets = &_M_single_bucket; _M_single_bucket = __ht._M_single_bucket; } else _M_buckets = __ht._M_buckets; _M_before_begin._M_nxt = __ht._M_before_begin._M_nxt; // Update, if necessary, bucket pointing to before begin that hasn't // moved. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; __ht._M_reset(); } else { _M_assign(__ht, [this](__node_type* __n) { return this->_M_allocate_node( std::move_if_noexcept(__n->_M_v())); }); __ht.clear(); } } template _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: ~_Hashtable() noexcept { clear(); _M_deallocate_buckets(); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: swap(_Hashtable& __x) noexcept(__and_<__is_nothrow_swappable<_H1>, __is_nothrow_swappable<_Equal>>::value) { // The only base class with member variables is hash_code_base. // We define _Hash_code_base::_M_swap because different // specializations have different members. this->_M_swap(__x); std::__alloc_on_swap(this->_M_node_allocator(), __x._M_node_allocator()); std::swap(_M_rehash_policy, __x._M_rehash_policy); // Deal properly with potentially moved instances. if (this->_M_uses_single_bucket()) { if (!__x._M_uses_single_bucket()) { _M_buckets = __x._M_buckets; __x._M_buckets = &__x._M_single_bucket; } } else if (__x._M_uses_single_bucket()) { __x._M_buckets = _M_buckets; _M_buckets = &_M_single_bucket; } else std::swap(_M_buckets, __x._M_buckets); std::swap(_M_bucket_count, __x._M_bucket_count); std::swap(_M_before_begin._M_nxt, __x._M_before_begin._M_nxt); std::swap(_M_element_count, __x._M_element_count); std::swap(_M_single_bucket, __x._M_single_bucket); // Fix buckets containing the _M_before_begin pointers that can't be // swapped. if (_M_begin()) _M_buckets[_M_bucket_index(_M_begin())] = &_M_before_begin; if (__x._M_begin()) __x._M_buckets[__x._M_bucket_index(__x._M_begin())] = &__x._M_before_begin; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: find(const key_type& __k) -> iterator { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); return __p ? iterator(__p) : end(); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: find(const key_type& __k) const -> const_iterator { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); return __p ? const_iterator(__p) : end(); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: count(const key_type& __k) const -> size_type { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_bucket_begin(__n); if (!__p) return 0; std::size_t __result = 0; for (;; __p = __p->_M_next()) { if (this->_M_equals(__k, __code, __p)) ++__result; else if (__result) // All equivalent values are next to each other, if we // found a non-equivalent value after an equivalent one it // means that we won't find any new equivalent value. break; if (!__p->_M_nxt || _M_bucket_index(__p->_M_next()) != __n) break; } return __result; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: equal_range(const key_type& __k) -> pair { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); if (__p) { __node_type* __p1 = __p->_M_next(); while (__p1 && _M_bucket_index(__p1) == __n && this->_M_equals(__k, __code, __p1)) __p1 = __p1->_M_next(); return std::make_pair(iterator(__p), iterator(__p1)); } else return std::make_pair(end(), end()); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: equal_range(const key_type& __k) const -> pair { __hash_code __code = this->_M_hash_code(__k); std::size_t __n = _M_bucket_index(__k, __code); __node_type* __p = _M_find_node(__n, __k, __code); if (__p) { __node_type* __p1 = __p->_M_next(); while (__p1 && _M_bucket_index(__p1) == __n && this->_M_equals(__k, __code, __p1)) __p1 = __p1->_M_next(); return std::make_pair(const_iterator(__p), const_iterator(__p1)); } else return std::make_pair(end(), end()); } // Find the node whose key compares equal to k in the bucket n. // Return nullptr if no node is found. template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_find_before_node(size_type __n, const key_type& __k, __hash_code __code) const -> __node_base* { __node_base* __prev_p = _M_buckets[__n]; if (!__prev_p) return nullptr; for (__node_type* __p = static_cast<__node_type*>(__prev_p->_M_nxt);; __p = __p->_M_next()) { if (this->_M_equals(__k, __code, __p)) return __prev_p; if (!__p->_M_nxt || _M_bucket_index(__p->_M_next()) != __n) break; __prev_p = __p; } return nullptr; } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_bucket_begin(size_type __bkt, __node_type* __node) { if (_M_buckets[__bkt]) { // Bucket is not empty, we just need to insert the new node // after the bucket before begin. __node->_M_nxt = _M_buckets[__bkt]->_M_nxt; _M_buckets[__bkt]->_M_nxt = __node; } else { // The bucket is empty, the new node is inserted at the // beginning of the singly-linked list and the bucket will // contain _M_before_begin pointer. __node->_M_nxt = _M_before_begin._M_nxt; _M_before_begin._M_nxt = __node; if (__node->_M_nxt) // We must update former begin bucket that is pointing to // _M_before_begin. _M_buckets[_M_bucket_index(__node->_M_next())] = __node; _M_buckets[__bkt] = &_M_before_begin; } } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_remove_bucket_begin(size_type __bkt, __node_type* __next, size_type __next_bkt) { if (!__next || __next_bkt != __bkt) { // Bucket is now empty // First update next bucket if any if (__next) _M_buckets[__next_bkt] = _M_buckets[__bkt]; // Second update before begin node if necessary if (&_M_before_begin == _M_buckets[__bkt]) _M_before_begin._M_nxt = __next; _M_buckets[__bkt] = nullptr; } } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_get_previous_node(size_type __bkt, __node_base* __n) -> __node_base* { __node_base* __prev_n = _M_buckets[__bkt]; while (__prev_n->_M_nxt != __n) __prev_n = __prev_n->_M_nxt; return __prev_n; } template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_emplace(std::true_type, _Args&&... __args) -> pair { // First build the node to get access to the hash code __node_type* __node = this->_M_allocate_node(std::forward<_Args>(__args)...); const key_type& __k = this->_M_extract()(__node->_M_v()); __hash_code __code; __try { __code = this->_M_hash_code(__k); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } size_type __bkt = _M_bucket_index(__k, __code); if (__node_type* __p = _M_find_node(__bkt, __k, __code)) { // There is already an equivalent node, no insertion this->_M_deallocate_node(__node); return std::make_pair(iterator(__p), false); } // Insert the node return std::make_pair(_M_insert_unique_node(__bkt, __code, __node), true); } template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_emplace(const_iterator __hint, std::false_type, _Args&&... __args) -> iterator { // First build the node to get its hash code. __node_type* __node = this->_M_allocate_node(std::forward<_Args>(__args)...); __hash_code __code; __try { __code = this->_M_hash_code(this->_M_extract()(__node->_M_v())); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } return _M_insert_multi_node(__hint._M_cur, __code, __node); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_unique_node(size_type __bkt, __hash_code __code, __node_type* __node, size_type __n_elt) -> iterator { const __rehash_state& __saved_state = _M_rehash_policy._M_state(); std::pair __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, __n_elt); __try { if (__do_rehash.first) { _M_rehash(__do_rehash.second, __saved_state); __bkt = _M_bucket_index(this->_M_extract()(__node->_M_v()), __code); } this->_M_store_code(__node, __code); // Always insert at the beginning of the bucket. _M_insert_bucket_begin(__bkt, __node); ++_M_element_count; return iterator(__node); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } } // Insert node, in bucket bkt if no rehash (assumes no element with its key // already present). Take ownership of the node, deallocate it on exception. template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_multi_node(__node_type* __hint, __hash_code __code, __node_type* __node) -> iterator { const __rehash_state& __saved_state = _M_rehash_policy._M_state(); std::pair __do_rehash = _M_rehash_policy._M_need_rehash(_M_bucket_count, _M_element_count, 1); __try { if (__do_rehash.first) _M_rehash(__do_rehash.second, __saved_state); this->_M_store_code(__node, __code); const key_type& __k = this->_M_extract()(__node->_M_v()); size_type __bkt = _M_bucket_index(__k, __code); // Find the node before an equivalent one or use hint if it exists and // if it is equivalent. __node_base* __prev = __builtin_expect(__hint != nullptr, false) && this->_M_equals(__k, __code, __hint) ? __hint : _M_find_before_node(__bkt, __k, __code); if (__prev) { // Insert after the node before the equivalent one. __node->_M_nxt = __prev->_M_nxt; __prev->_M_nxt = __node; if (__builtin_expect(__prev == __hint, false)) // hint might be the last bucket node, in this case we need to // update next bucket. if (__node->_M_nxt && !this->_M_equals(__k, __code, __node->_M_next())) { size_type __next_bkt = _M_bucket_index(__node->_M_next()); if (__next_bkt != __bkt) _M_buckets[__next_bkt] = __node; } } else // The inserted node has no equivalent in the // hashtable. We must insert the new node at the // beginning of the bucket to preserve equivalent // elements' relative positions. _M_insert_bucket_begin(__bkt, __node); ++_M_element_count; return iterator(__node); } __catch(...) { this->_M_deallocate_node(__node); __throw_exception_again; } } // Insert v if no element with its key is already present. template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert(_Arg&& __v, const _NodeGenerator& __node_gen, true_type, size_type __n_elt) -> pair { const key_type& __k = this->_M_extract()(__v); __hash_code __code = this->_M_hash_code(__k); size_type __bkt = _M_bucket_index(__k, __code); __node_type* __n = _M_find_node(__bkt, __k, __code); if (__n) return std::make_pair(iterator(__n), false); __n = __node_gen(std::forward<_Arg>(__v)); return { _M_insert_unique_node(__bkt, __code, __n, __n_elt), true }; } // Insert v unconditionally. template template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert(const_iterator __hint, _Arg&& __v, const _NodeGenerator& __node_gen, false_type) -> iterator { // First compute the hash code so that we don't do anything if it // throws. __hash_code __code = this->_M_hash_code(this->_M_extract()(__v)); // Second allocate new node so that we don't rehash if it throws. __node_type* __node = __node_gen(std::forward<_Arg>(__v)); return _M_insert_multi_node(__hint._M_cur, __code, __node); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: erase(const_iterator __it) -> iterator { __node_type* __n = __it._M_cur; std::size_t __bkt = _M_bucket_index(__n); // Look for previous node to unlink it from the erased one, this // is why we need buckets to contain the before begin to make // this search fast. __node_base* __prev_n = _M_get_previous_node(__bkt, __n); return _M_erase(__bkt, __prev_n, __n); } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_erase(size_type __bkt, __node_base* __prev_n, __node_type* __n) -> iterator { if (__prev_n == _M_buckets[__bkt]) _M_remove_bucket_begin(__bkt, __n->_M_next(), __n->_M_nxt ? _M_bucket_index(__n->_M_next()) : 0); else if (__n->_M_nxt) { size_type __next_bkt = _M_bucket_index(__n->_M_next()); if (__next_bkt != __bkt) _M_buckets[__next_bkt] = __prev_n; } __prev_n->_M_nxt = __n->_M_nxt; iterator __result(__n->_M_next()); this->_M_deallocate_node(__n); --_M_element_count; return __result; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_erase(std::true_type, const key_type& __k) -> size_type { __hash_code __code = this->_M_hash_code(__k); std::size_t __bkt = _M_bucket_index(__k, __code); // Look for the node before the first matching node. __node_base* __prev_n = _M_find_before_node(__bkt, __k, __code); if (!__prev_n) return 0; // We found a matching node, erase it. __node_type* __n = static_cast<__node_type*>(__prev_n->_M_nxt); _M_erase(__bkt, __prev_n, __n); return 1; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_erase(std::false_type, const key_type& __k) -> size_type { __hash_code __code = this->_M_hash_code(__k); std::size_t __bkt = _M_bucket_index(__k, __code); // Look for the node before the first matching node. __node_base* __prev_n = _M_find_before_node(__bkt, __k, __code); if (!__prev_n) return 0; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 526. Is it undefined if a function in the standard changes // in parameters? // We use one loop to find all matching nodes and another to deallocate // them so that the key stays valid during the first loop. It might be // invalidated indirectly when destroying nodes. __node_type* __n = static_cast<__node_type*>(__prev_n->_M_nxt); __node_type* __n_last = __n; std::size_t __n_last_bkt = __bkt; do { __n_last = __n_last->_M_next(); if (!__n_last) break; __n_last_bkt = _M_bucket_index(__n_last); } while (__n_last_bkt == __bkt && this->_M_equals(__k, __code, __n_last)); // Deallocate nodes. size_type __result = 0; do { __node_type* __p = __n->_M_next(); this->_M_deallocate_node(__n); __n = __p; ++__result; --_M_element_count; } while (__n != __n_last); if (__prev_n == _M_buckets[__bkt]) _M_remove_bucket_begin(__bkt, __n_last, __n_last_bkt); else if (__n_last && __n_last_bkt != __bkt) _M_buckets[__n_last_bkt] = __prev_n; __prev_n->_M_nxt = __n_last; return __result; } template auto _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: erase(const_iterator __first, const_iterator __last) -> iterator { __node_type* __n = __first._M_cur; __node_type* __last_n = __last._M_cur; if (__n == __last_n) return iterator(__n); std::size_t __bkt = _M_bucket_index(__n); __node_base* __prev_n = _M_get_previous_node(__bkt, __n); bool __is_bucket_begin = __n == _M_bucket_begin(__bkt); std::size_t __n_bkt = __bkt; for (;;) { do { __node_type* __tmp = __n; __n = __n->_M_next(); this->_M_deallocate_node(__tmp); --_M_element_count; if (!__n) break; __n_bkt = _M_bucket_index(__n); } while (__n != __last_n && __n_bkt == __bkt); if (__is_bucket_begin) _M_remove_bucket_begin(__bkt, __n, __n_bkt); if (__n == __last_n) break; __is_bucket_begin = true; __bkt = __n_bkt; } if (__n && (__n_bkt != __bkt || __is_bucket_begin)) _M_buckets[__n_bkt] = __prev_n; __prev_n->_M_nxt = __n; return iterator(__n); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: clear() noexcept { this->_M_deallocate_nodes(_M_begin()); __builtin_memset(_M_buckets, 0, _M_bucket_count * sizeof(__bucket_type)); _M_element_count = 0; _M_before_begin._M_nxt = nullptr; } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: rehash(size_type __n) { const __rehash_state& __saved_state = _M_rehash_policy._M_state(); std::size_t __buckets = std::max(_M_rehash_policy._M_bkt_for_elements(_M_element_count + 1), __n); __buckets = _M_rehash_policy._M_next_bkt(__buckets); if (__buckets != _M_bucket_count) _M_rehash(__buckets, __saved_state); else // No rehash, restore previous state to keep a consistent state. _M_rehash_policy._M_reset(__saved_state); } template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_rehash(size_type __n, const __rehash_state& __state) { __try { _M_rehash_aux(__n, __unique_keys()); } __catch(...) { // A failure here means that buckets allocation failed. We only // have to restore hash policy previous state. _M_rehash_policy._M_reset(__state); __throw_exception_again; } } // Rehash when there is no equivalent elements. template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_rehash_aux(size_type __n, std::true_type) { __bucket_type* __new_buckets = _M_allocate_buckets(__n); __node_type* __p = _M_begin(); _M_before_begin._M_nxt = nullptr; std::size_t __bbegin_bkt = 0; while (__p) { __node_type* __next = __p->_M_next(); std::size_t __bkt = __hash_code_base::_M_bucket_index(__p, __n); if (!__new_buckets[__bkt]) { __p->_M_nxt = _M_before_begin._M_nxt; _M_before_begin._M_nxt = __p; __new_buckets[__bkt] = &_M_before_begin; if (__p->_M_nxt) __new_buckets[__bbegin_bkt] = __p; __bbegin_bkt = __bkt; } else { __p->_M_nxt = __new_buckets[__bkt]->_M_nxt; __new_buckets[__bkt]->_M_nxt = __p; } __p = __next; } _M_deallocate_buckets(); _M_bucket_count = __n; _M_buckets = __new_buckets; } // Rehash when there can be equivalent elements, preserve their relative // order. template void _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_rehash_aux(size_type __n, std::false_type) { __bucket_type* __new_buckets = _M_allocate_buckets(__n); __node_type* __p = _M_begin(); _M_before_begin._M_nxt = nullptr; std::size_t __bbegin_bkt = 0; std::size_t __prev_bkt = 0; __node_type* __prev_p = nullptr; bool __check_bucket = false; while (__p) { __node_type* __next = __p->_M_next(); std::size_t __bkt = __hash_code_base::_M_bucket_index(__p, __n); if (__prev_p && __prev_bkt == __bkt) { // Previous insert was already in this bucket, we insert after // the previously inserted one to preserve equivalent elements // relative order. __p->_M_nxt = __prev_p->_M_nxt; __prev_p->_M_nxt = __p; // Inserting after a node in a bucket require to check that we // haven't change the bucket last node, in this case next // bucket containing its before begin node must be updated. We // schedule a check as soon as we move out of the sequence of // equivalent nodes to limit the number of checks. __check_bucket = true; } else { if (__check_bucket) { // Check if we shall update the next bucket because of // insertions into __prev_bkt bucket. if (__prev_p->_M_nxt) { std::size_t __next_bkt = __hash_code_base::_M_bucket_index(__prev_p->_M_next(), __n); if (__next_bkt != __prev_bkt) __new_buckets[__next_bkt] = __prev_p; } __check_bucket = false; } if (!__new_buckets[__bkt]) { __p->_M_nxt = _M_before_begin._M_nxt; _M_before_begin._M_nxt = __p; __new_buckets[__bkt] = &_M_before_begin; if (__p->_M_nxt) __new_buckets[__bbegin_bkt] = __p; __bbegin_bkt = __bkt; } else { __p->_M_nxt = __new_buckets[__bkt]->_M_nxt; __new_buckets[__bkt]->_M_nxt = __p; } } __prev_p = __p; __prev_bkt = __bkt; __p = __next; } if (__check_bucket && __prev_p->_M_nxt) { std::size_t __next_bkt = __hash_code_base::_M_bucket_index(__prev_p->_M_next(), __n); if (__next_bkt != __prev_bkt) __new_buckets[__next_bkt] = __prev_p; } _M_deallocate_buckets(); _M_bucket_count = __n; _M_buckets = __new_buckets; } #if __cplusplus > 201402L template class _Hash_merge_helper { }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _HASHTABLE_H c++/8/bits/basic_string.tcc000064400000150773151027430570011407 0ustar00// Components for manipulating sequences of characters -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_string.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // // Written by Jason Merrill based upon the specification by Takanori Adachi // in ANSI X3J16/94-0013R2. Rewritten by Nathan Myers to ISO-14882. // Non-reference-counted implementation written by Paolo Carlini and // updated by Jonathan Wakely for ISO-14882-2011. #ifndef _BASIC_STRING_TCC #define _BASIC_STRING_TCC 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if _GLIBCXX_USE_CXX11_ABI template const typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>::npos; template void basic_string<_CharT, _Traits, _Alloc>:: swap(basic_string& __s) _GLIBCXX_NOEXCEPT { if (this == &__s) return; _Alloc_traits::_S_on_swap(_M_get_allocator(), __s._M_get_allocator()); if (_M_is_local()) if (__s._M_is_local()) { if (length() && __s.length()) { _CharT __tmp_data[_S_local_capacity + 1]; traits_type::copy(__tmp_data, __s._M_local_buf, _S_local_capacity + 1); traits_type::copy(__s._M_local_buf, _M_local_buf, _S_local_capacity + 1); traits_type::copy(_M_local_buf, __tmp_data, _S_local_capacity + 1); } else if (__s.length()) { traits_type::copy(_M_local_buf, __s._M_local_buf, _S_local_capacity + 1); _M_length(__s.length()); __s._M_set_length(0); return; } else if (length()) { traits_type::copy(__s._M_local_buf, _M_local_buf, _S_local_capacity + 1); __s._M_length(length()); _M_set_length(0); return; } } else { const size_type __tmp_capacity = __s._M_allocated_capacity; traits_type::copy(__s._M_local_buf, _M_local_buf, _S_local_capacity + 1); _M_data(__s._M_data()); __s._M_data(__s._M_local_buf); _M_capacity(__tmp_capacity); } else { const size_type __tmp_capacity = _M_allocated_capacity; if (__s._M_is_local()) { traits_type::copy(_M_local_buf, __s._M_local_buf, _S_local_capacity + 1); __s._M_data(_M_data()); _M_data(_M_local_buf); } else { pointer __tmp_ptr = _M_data(); _M_data(__s._M_data()); __s._M_data(__tmp_ptr); _M_capacity(__s._M_allocated_capacity); } __s._M_capacity(__tmp_capacity); } const size_type __tmp_length = length(); _M_length(__s.length()); __s._M_length(__tmp_length); } template typename basic_string<_CharT, _Traits, _Alloc>::pointer basic_string<_CharT, _Traits, _Alloc>:: _M_create(size_type& __capacity, size_type __old_capacity) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 83. String::npos vs. string::max_size() if (__capacity > max_size()) std::__throw_length_error(__N("basic_string::_M_create")); // The below implements an exponential growth policy, necessary to // meet amortized linear time requirements of the library: see // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html. if (__capacity > __old_capacity && __capacity < 2 * __old_capacity) { __capacity = 2 * __old_capacity; // Never allocate a string bigger than max_size. if (__capacity > max_size()) __capacity = max_size(); } // NB: Need an array of char_type[__capacity], plus a terminating // null char_type() element. return _Alloc_traits::allocate(_M_get_allocator(), __capacity + 1); } // NB: This is the special case for Input Iterators, used in // istreambuf_iterators, etc. // Input Iterators have a cost structure very different from // pointers, calling for a different coding style. template template void basic_string<_CharT, _Traits, _Alloc>:: _M_construct(_InIterator __beg, _InIterator __end, std::input_iterator_tag) { size_type __len = 0; size_type __capacity = size_type(_S_local_capacity); while (__beg != __end && __len < __capacity) { _M_data()[__len++] = *__beg; ++__beg; } __try { while (__beg != __end) { if (__len == __capacity) { // Allocate more space. __capacity = __len + 1; pointer __another = _M_create(__capacity, __len); this->_S_copy(__another, _M_data(), __len); _M_dispose(); _M_data(__another); _M_capacity(__capacity); } _M_data()[__len++] = *__beg; ++__beg; } } __catch(...) { _M_dispose(); __throw_exception_again; } _M_set_length(__len); } template template void basic_string<_CharT, _Traits, _Alloc>:: _M_construct(_InIterator __beg, _InIterator __end, std::forward_iterator_tag) { // NB: Not required, but considered best practice. if (__gnu_cxx::__is_null_pointer(__beg) && __beg != __end) std::__throw_logic_error(__N("basic_string::" "_M_construct null not valid")); size_type __dnew = static_cast(std::distance(__beg, __end)); if (__dnew > size_type(_S_local_capacity)) { _M_data(_M_create(__dnew, size_type(0))); _M_capacity(__dnew); } // Check for out_of_range and length_error exceptions. __try { this->_S_copy_chars(_M_data(), __beg, __end); } __catch(...) { _M_dispose(); __throw_exception_again; } _M_set_length(__dnew); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_construct(size_type __n, _CharT __c) { if (__n > size_type(_S_local_capacity)) { _M_data(_M_create(__n, size_type(0))); _M_capacity(__n); } if (__n) this->_S_assign(_M_data(), __n, __c); _M_set_length(__n); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_assign(const basic_string& __str) { if (this != &__str) { const size_type __rsize = __str.length(); const size_type __capacity = capacity(); if (__rsize > __capacity) { size_type __new_capacity = __rsize; pointer __tmp = _M_create(__new_capacity, __capacity); _M_dispose(); _M_data(__tmp); _M_capacity(__new_capacity); } if (__rsize) this->_S_copy(_M_data(), __str._M_data(), __rsize); _M_set_length(__rsize); } } template void basic_string<_CharT, _Traits, _Alloc>:: reserve(size_type __res) { // Make sure we don't shrink below the current size. if (__res < length()) __res = length(); const size_type __capacity = capacity(); if (__res != __capacity) { if (__res > __capacity || __res > size_type(_S_local_capacity)) { pointer __tmp = _M_create(__res, __capacity); this->_S_copy(__tmp, _M_data(), length() + 1); _M_dispose(); _M_data(__tmp); _M_capacity(__res); } else if (!_M_is_local()) { this->_S_copy(_M_local_data(), _M_data(), length() + 1); _M_destroy(__capacity); _M_data(_M_local_data()); } } } template void basic_string<_CharT, _Traits, _Alloc>:: _M_mutate(size_type __pos, size_type __len1, const _CharT* __s, size_type __len2) { const size_type __how_much = length() - __pos - __len1; size_type __new_capacity = length() + __len2 - __len1; pointer __r = _M_create(__new_capacity, capacity()); if (__pos) this->_S_copy(__r, _M_data(), __pos); if (__s && __len2) this->_S_copy(__r + __pos, __s, __len2); if (__how_much) this->_S_copy(__r + __pos + __len2, _M_data() + __pos + __len1, __how_much); _M_dispose(); _M_data(__r); _M_capacity(__new_capacity); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_erase(size_type __pos, size_type __n) { const size_type __how_much = length() - __pos - __n; if (__how_much && __n) this->_S_move(_M_data() + __pos, _M_data() + __pos + __n, __how_much); _M_set_length(length() - __n); } template void basic_string<_CharT, _Traits, _Alloc>:: resize(size_type __n, _CharT __c) { const size_type __size = this->size(); if (__size < __n) this->append(__n - __size, __c); else if (__n < __size) this->_M_set_length(__n); } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_append(const _CharT* __s, size_type __n) { const size_type __len = __n + this->size(); if (__len <= this->capacity()) { if (__n) this->_S_copy(this->_M_data() + this->size(), __s, __n); } else this->_M_mutate(this->size(), size_type(0), __s, __n); this->_M_set_length(__len); return *this; } template template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2, std::__false_type) { const basic_string __s(__k1, __k2); const size_type __n1 = __i2 - __i1; return _M_replace(__i1 - begin(), __n1, __s._M_data(), __s.size()); } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c) { _M_check_length(__n1, __n2, "basic_string::_M_replace_aux"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __n2 - __n1; if (__new_size <= this->capacity()) { pointer __p = this->_M_data() + __pos1; const size_type __how_much = __old_size - __pos1 - __n1; if (__how_much && __n1 != __n2) this->_S_move(__p + __n2, __p + __n1, __how_much); } else this->_M_mutate(__pos1, __n1, 0, __n2); if (__n2) this->_S_assign(this->_M_data() + __pos1, __n2, __c); this->_M_set_length(__new_size); return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace(size_type __pos, size_type __len1, const _CharT* __s, const size_type __len2) { _M_check_length(__len1, __len2, "basic_string::_M_replace"); const size_type __old_size = this->size(); const size_type __new_size = __old_size + __len2 - __len1; if (__new_size <= this->capacity()) { pointer __p = this->_M_data() + __pos; const size_type __how_much = __old_size - __pos - __len1; if (_M_disjunct(__s)) { if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2) this->_S_copy(__p, __s, __len2); } else { // Work in-place. if (__len2 && __len2 <= __len1) this->_S_move(__p, __s, __len2); if (__how_much && __len1 != __len2) this->_S_move(__p + __len2, __p + __len1, __how_much); if (__len2 > __len1) { if (__s + __len2 <= __p + __len1) this->_S_move(__p, __s, __len2); else if (__s >= __p + __len1) this->_S_copy(__p, __s + __len2 - __len1, __len2); else { const size_type __nleft = (__p + __len1) - __s; this->_S_move(__p, __s, __nleft); this->_S_copy(__p + __nleft, __p + __len2, __len2 - __nleft); } } } } else this->_M_mutate(__pos, __len1, __s, __len2); this->_M_set_length(__new_size); return *this; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: copy(_CharT* __s, size_type __n, size_type __pos) const { _M_check(__pos, "basic_string::copy"); __n = _M_limit(__pos, __n); __glibcxx_requires_string_len(__s, __n); if (__n) _S_copy(__s, _M_data() + __pos, __n); // 21.3.5.7 par 3: do not append null. (good.) return __n; } #else // !_GLIBCXX_USE_CXX11_ABI template const typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: _Rep::_S_max_size = (((npos - sizeof(_Rep_base))/sizeof(_CharT)) - 1) / 4; template const _CharT basic_string<_CharT, _Traits, _Alloc>:: _Rep::_S_terminal = _CharT(); template const typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>::npos; // Linker sets _S_empty_rep_storage to all 0s (one reference, empty string) // at static init time (before static ctors are run). template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>::_Rep::_S_empty_rep_storage[ (sizeof(_Rep_base) + sizeof(_CharT) + sizeof(size_type) - 1) / sizeof(size_type)]; // NB: This is the special case for Input Iterators, used in // istreambuf_iterators, etc. // Input Iterators have a cost structure very different from // pointers, calling for a different coding style. template template _CharT* basic_string<_CharT, _Traits, _Alloc>:: _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, input_iterator_tag) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__beg == __end && __a == _Alloc()) return _S_empty_rep()._M_refdata(); #endif // Avoid reallocation for common case. _CharT __buf[128]; size_type __len = 0; while (__beg != __end && __len < sizeof(__buf) / sizeof(_CharT)) { __buf[__len++] = *__beg; ++__beg; } _Rep* __r = _Rep::_S_create(__len, size_type(0), __a); _M_copy(__r->_M_refdata(), __buf, __len); __try { while (__beg != __end) { if (__len == __r->_M_capacity) { // Allocate more space. _Rep* __another = _Rep::_S_create(__len + 1, __len, __a); _M_copy(__another->_M_refdata(), __r->_M_refdata(), __len); __r->_M_destroy(__a); __r = __another; } __r->_M_refdata()[__len++] = *__beg; ++__beg; } } __catch(...) { __r->_M_destroy(__a); __throw_exception_again; } __r->_M_set_length_and_sharable(__len); return __r->_M_refdata(); } template template _CharT* basic_string<_CharT, _Traits, _Alloc>:: _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, forward_iterator_tag) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__beg == __end && __a == _Alloc()) return _S_empty_rep()._M_refdata(); #endif // NB: Not required, but considered best practice. if (__gnu_cxx::__is_null_pointer(__beg) && __beg != __end) __throw_logic_error(__N("basic_string::_S_construct null not valid")); const size_type __dnew = static_cast(std::distance(__beg, __end)); // Check for out_of_range and length_error exceptions. _Rep* __r = _Rep::_S_create(__dnew, size_type(0), __a); __try { _S_copy_chars(__r->_M_refdata(), __beg, __end); } __catch(...) { __r->_M_destroy(__a); __throw_exception_again; } __r->_M_set_length_and_sharable(__dnew); return __r->_M_refdata(); } template _CharT* basic_string<_CharT, _Traits, _Alloc>:: _S_construct(size_type __n, _CharT __c, const _Alloc& __a) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__n == 0 && __a == _Alloc()) return _S_empty_rep()._M_refdata(); #endif // Check for out_of_range and length_error exceptions. _Rep* __r = _Rep::_S_create(__n, size_type(0), __a); if (__n) _M_assign(__r->_M_refdata(), __n, __c); __r->_M_set_length_and_sharable(__n); return __r->_M_refdata(); } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str) : _M_dataplus(__str._M_rep()->_M_grab(_Alloc(__str.get_allocator()), __str.get_allocator()), __str.get_allocator()) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const _Alloc& __a) : _M_dataplus(_S_construct(size_type(), _CharT(), __a), __a) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str, size_type __pos, const _Alloc& __a) : _M_dataplus(_S_construct(__str._M_data() + __str._M_check(__pos, "basic_string::basic_string"), __str._M_data() + __str._M_limit(__pos, npos) + __pos, __a), __a) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str, size_type __pos, size_type __n) : _M_dataplus(_S_construct(__str._M_data() + __str._M_check(__pos, "basic_string::basic_string"), __str._M_data() + __str._M_limit(__pos, __n) + __pos, _Alloc()), _Alloc()) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const basic_string& __str, size_type __pos, size_type __n, const _Alloc& __a) : _M_dataplus(_S_construct(__str._M_data() + __str._M_check(__pos, "basic_string::basic_string"), __str._M_data() + __str._M_limit(__pos, __n) + __pos, __a), __a) { } // TBD: DPG annotate template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const _CharT* __s, size_type __n, const _Alloc& __a) : _M_dataplus(_S_construct(__s, __s + __n, __a), __a) { } // TBD: DPG annotate template basic_string<_CharT, _Traits, _Alloc>:: basic_string(const _CharT* __s, const _Alloc& __a) : _M_dataplus(_S_construct(__s, __s ? __s + traits_type::length(__s) : __s + npos, __a), __a) { } template basic_string<_CharT, _Traits, _Alloc>:: basic_string(size_type __n, _CharT __c, const _Alloc& __a) : _M_dataplus(_S_construct(__n, __c, __a), __a) { } // TBD: DPG annotate template template basic_string<_CharT, _Traits, _Alloc>:: basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a) : _M_dataplus(_S_construct(__beg, __end, __a), __a) { } #if __cplusplus >= 201103L template basic_string<_CharT, _Traits, _Alloc>:: basic_string(initializer_list<_CharT> __l, const _Alloc& __a) : _M_dataplus(_S_construct(__l.begin(), __l.end(), __a), __a) { } #endif template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: assign(const basic_string& __str) { if (_M_rep() != __str._M_rep()) { // XXX MT const allocator_type __a = this->get_allocator(); _CharT* __tmp = __str._M_rep()->_M_grab(__a, __str.get_allocator()); _M_rep()->_M_dispose(__a); _M_data(__tmp); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: assign(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); _M_check_length(this->size(), __n, "basic_string::assign"); if (_M_disjunct(__s) || _M_rep()->_M_is_shared()) return _M_replace_safe(size_type(0), this->size(), __s, __n); else { // Work in-place. const size_type __pos = __s - _M_data(); if (__pos >= __n) _M_copy(_M_data(), __s, __n); else if (__pos) _M_move(_M_data(), __s, __n); _M_rep()->_M_set_length_and_sharable(__n); return *this; } } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(size_type __n, _CharT __c) { if (__n) { _M_check_length(size_type(0), __n, "basic_string::append"); const size_type __len = __n + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); _M_assign(_M_data() + this->size(), __n, __c); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); if (__n) { _M_check_length(size_type(0), __n, "basic_string::append"); const size_type __len = __n + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) { if (_M_disjunct(__s)) this->reserve(__len); else { const size_type __off = __s - _M_data(); this->reserve(__len); __s = _M_data() + __off; } } _M_copy(_M_data() + this->size(), __s, __n); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(const basic_string& __str) { const size_type __size = __str.size(); if (__size) { const size_type __len = __size + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); _M_copy(_M_data() + this->size(), __str._M_data(), __size); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: append(const basic_string& __str, size_type __pos, size_type __n) { __str._M_check(__pos, "basic_string::append"); __n = __str._M_limit(__pos, __n); if (__n) { const size_type __len = __n + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); _M_copy(_M_data() + this->size(), __str._M_data() + __pos, __n); _M_rep()->_M_set_length_and_sharable(__len); } return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: insert(size_type __pos, const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); _M_check(__pos, "basic_string::insert"); _M_check_length(size_type(0), __n, "basic_string::insert"); if (_M_disjunct(__s) || _M_rep()->_M_is_shared()) return _M_replace_safe(__pos, size_type(0), __s, __n); else { // Work in-place. const size_type __off = __s - _M_data(); _M_mutate(__pos, 0, __n); __s = _M_data() + __off; _CharT* __p = _M_data() + __pos; if (__s + __n <= __p) _M_copy(__p, __s, __n); else if (__s >= __p) _M_copy(__p, __s + __n, __n); else { const size_type __nleft = __p - __s; _M_copy(__p, __s, __nleft); _M_copy(__p + __nleft, __p + __n, __n - __nleft); } return *this; } } template typename basic_string<_CharT, _Traits, _Alloc>::iterator basic_string<_CharT, _Traits, _Alloc>:: erase(iterator __first, iterator __last) { _GLIBCXX_DEBUG_PEDASSERT(__first >= _M_ibegin() && __first <= __last && __last <= _M_iend()); // NB: This isn't just an optimization (bail out early when // there is nothing to do, really), it's also a correctness // issue vs MT, see libstdc++/40518. const size_type __size = __last - __first; if (__size) { const size_type __pos = __first - _M_ibegin(); _M_mutate(__pos, __size, size_type(0)); _M_rep()->_M_set_leaked(); return iterator(_M_data() + __pos); } else return __first; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) { __glibcxx_requires_string_len(__s, __n2); _M_check(__pos, "basic_string::replace"); __n1 = _M_limit(__pos, __n1); _M_check_length(__n1, __n2, "basic_string::replace"); bool __left; if (_M_disjunct(__s) || _M_rep()->_M_is_shared()) return _M_replace_safe(__pos, __n1, __s, __n2); else if ((__left = __s + __n2 <= _M_data() + __pos) || _M_data() + __pos + __n1 <= __s) { // Work in-place: non-overlapping case. size_type __off = __s - _M_data(); __left ? __off : (__off += __n2 - __n1); _M_mutate(__pos, __n1, __n2); _M_copy(_M_data() + __pos, _M_data() + __off, __n2); return *this; } else { // Todo: overlapping case. const basic_string __tmp(__s, __n2); return _M_replace_safe(__pos, __n1, __tmp._M_data(), __n2); } } template void basic_string<_CharT, _Traits, _Alloc>::_Rep:: _M_destroy(const _Alloc& __a) throw () { const size_type __size = sizeof(_Rep_base) + (this->_M_capacity + 1) * sizeof(_CharT); _Raw_bytes_alloc(__a).deallocate(reinterpret_cast(this), __size); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_leak_hard() { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (_M_rep() == &_S_empty_rep()) return; #endif if (_M_rep()->_M_is_shared()) _M_mutate(0, 0, 0); _M_rep()->_M_set_leaked(); } template void basic_string<_CharT, _Traits, _Alloc>:: _M_mutate(size_type __pos, size_type __len1, size_type __len2) { const size_type __old_size = this->size(); const size_type __new_size = __old_size + __len2 - __len1; const size_type __how_much = __old_size - __pos - __len1; if (__new_size > this->capacity() || _M_rep()->_M_is_shared()) { // Must reallocate. const allocator_type __a = get_allocator(); _Rep* __r = _Rep::_S_create(__new_size, this->capacity(), __a); if (__pos) _M_copy(__r->_M_refdata(), _M_data(), __pos); if (__how_much) _M_copy(__r->_M_refdata() + __pos + __len2, _M_data() + __pos + __len1, __how_much); _M_rep()->_M_dispose(__a); _M_data(__r->_M_refdata()); } else if (__how_much && __len1 != __len2) { // Work in-place. _M_move(_M_data() + __pos + __len2, _M_data() + __pos + __len1, __how_much); } _M_rep()->_M_set_length_and_sharable(__new_size); } template void basic_string<_CharT, _Traits, _Alloc>:: reserve(size_type __res) { if (__res != this->capacity() || _M_rep()->_M_is_shared()) { // Make sure we don't shrink below the current size if (__res < this->size()) __res = this->size(); const allocator_type __a = get_allocator(); _CharT* __tmp = _M_rep()->_M_clone(__a, __res - this->size()); _M_rep()->_M_dispose(__a); _M_data(__tmp); } } template void basic_string<_CharT, _Traits, _Alloc>:: swap(basic_string& __s) { if (_M_rep()->_M_is_leaked()) _M_rep()->_M_set_sharable(); if (__s._M_rep()->_M_is_leaked()) __s._M_rep()->_M_set_sharable(); if (this->get_allocator() == __s.get_allocator()) { _CharT* __tmp = _M_data(); _M_data(__s._M_data()); __s._M_data(__tmp); } // The code below can usually be optimized away. else { const basic_string __tmp1(_M_ibegin(), _M_iend(), __s.get_allocator()); const basic_string __tmp2(__s._M_ibegin(), __s._M_iend(), this->get_allocator()); *this = __tmp2; __s = __tmp1; } } template typename basic_string<_CharT, _Traits, _Alloc>::_Rep* basic_string<_CharT, _Traits, _Alloc>::_Rep:: _S_create(size_type __capacity, size_type __old_capacity, const _Alloc& __alloc) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 83. String::npos vs. string::max_size() if (__capacity > _S_max_size) __throw_length_error(__N("basic_string::_S_create")); // The standard places no restriction on allocating more memory // than is strictly needed within this layer at the moment or as // requested by an explicit application call to reserve(). // Many malloc implementations perform quite poorly when an // application attempts to allocate memory in a stepwise fashion // growing each allocation size by only 1 char. Additionally, // it makes little sense to allocate less linear memory than the // natural blocking size of the malloc implementation. // Unfortunately, we would need a somewhat low-level calculation // with tuned parameters to get this perfect for any particular // malloc implementation. Fortunately, generalizations about // common features seen among implementations seems to suffice. // __pagesize need not match the actual VM page size for good // results in practice, thus we pick a common value on the low // side. __malloc_header_size is an estimate of the amount of // overhead per memory allocation (in practice seen N * sizeof // (void*) where N is 0, 2 or 4). According to folklore, // picking this value on the high side is better than // low-balling it (especially when this algorithm is used with // malloc implementations that allocate memory blocks rounded up // to a size which is a power of 2). const size_type __pagesize = 4096; const size_type __malloc_header_size = 4 * sizeof(void*); // The below implements an exponential growth policy, necessary to // meet amortized linear time requirements of the library: see // http://gcc.gnu.org/ml/libstdc++/2001-07/msg00085.html. // It's active for allocations requiring an amount of memory above // system pagesize. This is consistent with the requirements of the // standard: http://gcc.gnu.org/ml/libstdc++/2001-07/msg00130.html if (__capacity > __old_capacity && __capacity < 2 * __old_capacity) __capacity = 2 * __old_capacity; // NB: Need an array of char_type[__capacity], plus a terminating // null char_type() element, plus enough for the _Rep data structure. // Whew. Seemingly so needy, yet so elemental. size_type __size = (__capacity + 1) * sizeof(_CharT) + sizeof(_Rep); const size_type __adj_size = __size + __malloc_header_size; if (__adj_size > __pagesize && __capacity > __old_capacity) { const size_type __extra = __pagesize - __adj_size % __pagesize; __capacity += __extra / sizeof(_CharT); // Never allocate a string bigger than _S_max_size. if (__capacity > _S_max_size) __capacity = _S_max_size; __size = (__capacity + 1) * sizeof(_CharT) + sizeof(_Rep); } // NB: Might throw, but no worries about a leak, mate: _Rep() // does not throw. void* __place = _Raw_bytes_alloc(__alloc).allocate(__size); _Rep *__p = new (__place) _Rep; __p->_M_capacity = __capacity; // ABI compatibility - 3.4.x set in _S_create both // _M_refcount and _M_length. All callers of _S_create // in basic_string.tcc then set just _M_length. // In 4.0.x and later both _M_refcount and _M_length // are initialized in the callers, unfortunately we can // have 3.4.x compiled code with _S_create callers inlined // calling 4.0.x+ _S_create. __p->_M_set_sharable(); return __p; } template _CharT* basic_string<_CharT, _Traits, _Alloc>::_Rep:: _M_clone(const _Alloc& __alloc, size_type __res) { // Requested capacity of the clone. const size_type __requested_cap = this->_M_length + __res; _Rep* __r = _Rep::_S_create(__requested_cap, this->_M_capacity, __alloc); if (this->_M_length) _M_copy(__r->_M_refdata(), _M_refdata(), this->_M_length); __r->_M_set_length_and_sharable(this->_M_length); return __r->_M_refdata(); } template void basic_string<_CharT, _Traits, _Alloc>:: resize(size_type __n, _CharT __c) { const size_type __size = this->size(); _M_check_length(__size, __n, "basic_string::resize"); if (__size < __n) this->append(__n - __size, __c); else if (__n < __size) this->erase(__n); // else nothing (in particular, avoid calling _M_mutate() unnecessarily.) } template template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_dispatch(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2, __false_type) { const basic_string __s(__k1, __k2); const size_type __n1 = __i2 - __i1; _M_check_length(__n1, __s.size(), "basic_string::_M_replace_dispatch"); return _M_replace_safe(__i1 - _M_ibegin(), __n1, __s._M_data(), __s.size()); } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c) { _M_check_length(__n1, __n2, "basic_string::_M_replace_aux"); _M_mutate(__pos1, __n1, __n2); if (__n2) _M_assign(_M_data() + __pos1, __n2, __c); return *this; } template basic_string<_CharT, _Traits, _Alloc>& basic_string<_CharT, _Traits, _Alloc>:: _M_replace_safe(size_type __pos1, size_type __n1, const _CharT* __s, size_type __n2) { _M_mutate(__pos1, __n1, __n2); if (__n2) _M_copy(_M_data() + __pos1, __s, __n2); return *this; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: copy(_CharT* __s, size_type __n, size_type __pos) const { _M_check(__pos, "basic_string::copy"); __n = _M_limit(__pos, __n); __glibcxx_requires_string_len(__s, __n); if (__n) _M_copy(__s, _M_data() + __pos, __n); // 21.3.5.7 par 3: do not append null. (good.) return __n; } #endif // !_GLIBCXX_USE_CXX11_ABI template basic_string<_CharT, _Traits, _Alloc> operator+(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { __glibcxx_requires_string(__lhs); typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __string_type::size_type __size_type; const __size_type __len = _Traits::length(__lhs); __string_type __str; __str.reserve(__len + __rhs.size()); __str.append(__lhs, __len); __str.append(__rhs); return __str; } template basic_string<_CharT, _Traits, _Alloc> operator+(_CharT __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __string_type::size_type __size_type; __string_type __str; const __size_type __len = __rhs.size(); __str.reserve(__len + 1); __str.append(__size_type(1), __lhs); __str.append(__rhs); return __str; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); if (__n == 0) return __pos <= __size ? __pos : npos; if (__pos >= __size) return npos; const _CharT __elem0 = __s[0]; const _CharT* const __data = data(); const _CharT* __first = __data + __pos; const _CharT* const __last = __data + __size; size_type __len = __size - __pos; while (__len >= __n) { // Find the first occurrence of __elem0: __first = traits_type::find(__first, __len - __n + 1, __elem0); if (!__first) return npos; // Compare the full strings from the first occurrence of __elem0. // We already know that __first[0] == __s[0] but compare them again // anyway because __s is probably aligned, which helps memcmp. if (traits_type::compare(__first, __s, __n) == 0) return __first - __data; __len = __last - ++__first; } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __ret = npos; const size_type __size = this->size(); if (__pos < __size) { const _CharT* __data = _M_data(); const size_type __n = __size - __pos; const _CharT* __p = traits_type::find(__data + __pos, __n, __c); if (__p) __ret = __p - __data; } return __ret; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: rfind(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); const size_type __size = this->size(); if (__n <= __size) { __pos = std::min(size_type(__size - __n), __pos); const _CharT* __data = _M_data(); do { if (traits_type::compare(__data + __pos, __s, __n) == 0) return __pos; } while (__pos-- > 0); } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: rfind(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; for (++__size; __size-- > 0; ) if (traits_type::eq(_M_data()[__size], __c)) return __size; } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); for (; __n && __pos < this->size(); ++__pos) { const _CharT* __p = traits_type::find(__s, __n, _M_data()[__pos]); if (__p) return __pos; } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size && __n) { if (--__size > __pos) __size = __pos; do { if (traits_type::find(__s, __n, _M_data()[__size])) return __size; } while (__size-- != 0); } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); for (; __pos < this->size(); ++__pos) if (!traits_type::find(__s, __n, _M_data()[__pos])) return __pos; return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_first_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { for (; __pos < this->size(); ++__pos) if (!traits_type::eq(_M_data()[__pos], __c)) return __pos; return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string_len(__s, __n); size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::find(__s, __n, _M_data()[__size])) return __size; } while (__size--); } return npos; } template typename basic_string<_CharT, _Traits, _Alloc>::size_type basic_string<_CharT, _Traits, _Alloc>:: find_last_not_of(_CharT __c, size_type __pos) const _GLIBCXX_NOEXCEPT { size_type __size = this->size(); if (__size) { if (--__size > __pos) __size = __pos; do { if (!traits_type::eq(_M_data()[__size], __c)) return __size; } while (__size--); } return npos; } template int basic_string<_CharT, _Traits, _Alloc>:: compare(size_type __pos, size_type __n, const basic_string& __str) const { _M_check(__pos, "basic_string::compare"); __n = _M_limit(__pos, __n); const size_type __osize = __str.size(); const size_type __len = std::min(__n, __osize); int __r = traits_type::compare(_M_data() + __pos, __str.data(), __len); if (!__r) __r = _S_compare(__n, __osize); return __r; } template int basic_string<_CharT, _Traits, _Alloc>:: compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2) const { _M_check(__pos1, "basic_string::compare"); __str._M_check(__pos2, "basic_string::compare"); __n1 = _M_limit(__pos1, __n1); __n2 = __str._M_limit(__pos2, __n2); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(_M_data() + __pos1, __str.data() + __pos2, __len); if (!__r) __r = _S_compare(__n1, __n2); return __r; } template int basic_string<_CharT, _Traits, _Alloc>:: compare(const _CharT* __s) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); const size_type __size = this->size(); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __s, __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } template int basic_string <_CharT, _Traits, _Alloc>:: compare(size_type __pos, size_type __n1, const _CharT* __s) const { __glibcxx_requires_string(__s); _M_check(__pos, "basic_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __osize = traits_type::length(__s); const size_type __len = std::min(__n1, __osize); int __r = traits_type::compare(_M_data() + __pos, __s, __len); if (!__r) __r = _S_compare(__n1, __osize); return __r; } template int basic_string <_CharT, _Traits, _Alloc>:: compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const { __glibcxx_requires_string_len(__s, __n2); _M_check(__pos, "basic_string::compare"); __n1 = _M_limit(__pos, __n1); const size_type __len = std::min(__n1, __n2); int __r = traits_type::compare(_M_data() + __pos, __s, __len); if (!__r) __r = _S_compare(__n1, __n2); return __r; } // 21.3.7.9 basic_string::getline and operators template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, basic_string<_CharT, _Traits, _Alloc>& __str) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __istream_type::ios_base __ios_base; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; typedef ctype<_CharT> __ctype_type; typedef typename __ctype_type::ctype_base __ctype_base; __size_type __extracted = 0; typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { __try { // Avoid reallocation for common case. __str.erase(); _CharT __buf[128]; __size_type __len = 0; const streamsize __w = __in.width(); const __size_type __n = __w > 0 ? static_cast<__size_type>(__w) : __str.max_size(); const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !__ct.is(__ctype_base::space, _Traits::to_char_type(__c))) { if (__len == sizeof(__buf) / sizeof(_CharT)) { __str.append(__buf, sizeof(__buf) / sizeof(_CharT)); __len = 0; } __buf[__len++] = _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } __str.append(__buf, __len); if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; __in.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } // 211. operator>>(istream&, string&) doesn't set failbit if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } template basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __in, basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __istream_type::ios_base __ios_base; typedef typename __istream_type::int_type __int_type; typedef typename __string_type::size_type __size_type; __size_type __extracted = 0; const __size_type __n = __str.max_size(); typename __ios_base::iostate __err = __ios_base::goodbit; typename __istream_type::sentry __cerb(__in, true); if (__cerb) { __try { __str.erase(); const __int_type __idelim = _Traits::to_int_type(__delim); const __int_type __eof = _Traits::eof(); __int_type __c = __in.rdbuf()->sgetc(); while (__extracted < __n && !_Traits::eq_int_type(__c, __eof) && !_Traits::eq_int_type(__c, __idelim)) { __str += _Traits::to_char_type(__c); ++__extracted; __c = __in.rdbuf()->snextc(); } if (_Traits::eq_int_type(__c, __eof)) __err |= __ios_base::eofbit; else if (_Traits::eq_int_type(__c, __idelim)) { ++__extracted; __in.rdbuf()->sbumpc(); } else __err |= __ios_base::failbit; } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 91. Description of operator>> and getline() for string<> // might cause endless loop __in._M_setstate(__ios_base::badbit); } } if (!__extracted) __err |= __ios_base::failbit; if (__err) __in.setstate(__err); return __in; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE // The explicit instantiations definitions in src/c++11/string-inst.cc // are compiled as C++14, so the new C++17 members aren't instantiated. // Until those definitions are compiled as C++17 suppress the declaration, // so C++17 code will implicitly instantiate std::string and std::wstring // as needed. # if __cplusplus <= 201402L && _GLIBCXX_EXTERN_TEMPLATE > 0 extern template class basic_string; # elif ! _GLIBCXX_USE_CXX11_ABI // Still need to prevent implicit instantiation of the COW empty rep, // to ensure the definition in libstdc++.so is unique (PR 86138). extern template basic_string::size_type basic_string::_Rep::_S_empty_rep_storage[]; # endif extern template basic_istream& operator>>(basic_istream&, string&); extern template basic_ostream& operator<<(basic_ostream&, const string&); extern template basic_istream& getline(basic_istream&, string&, char); extern template basic_istream& getline(basic_istream&, string&); #ifdef _GLIBCXX_USE_WCHAR_T # if __cplusplus <= 201402L && _GLIBCXX_EXTERN_TEMPLATE > 0 extern template class basic_string; # elif ! _GLIBCXX_USE_CXX11_ABI extern template basic_string::size_type basic_string::_Rep::_S_empty_rep_storage[]; # endif extern template basic_istream& operator>>(basic_istream&, wstring&); extern template basic_ostream& operator<<(basic_ostream&, const wstring&); extern template basic_istream& getline(basic_istream&, wstring&, wchar_t); extern template basic_istream& getline(basic_istream&, wstring&); #endif // _GLIBCXX_USE_WCHAR_T #endif // _GLIBCXX_EXTERN_TEMPLATE _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/cpp_type_traits.h000064400000023075151027430570011621 0ustar00// The -*- C++ -*- type traits classes for internal use in libstdc++ // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cpp_type_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/type_traits} */ // Written by Gabriel Dos Reis #ifndef _CPP_TYPE_TRAITS_H #define _CPP_TYPE_TRAITS_H 1 #pragma GCC system_header #include // // This file provides some compile-time information about various types. // These representations were designed, on purpose, to be constant-expressions // and not types as found in . In particular, they // can be used in control structures and the optimizer hopefully will do // the obvious thing. // // Why integral expressions, and not functions nor types? // Firstly, these compile-time entities are used as template-arguments // so function return values won't work: We need compile-time entities. // We're left with types and constant integral expressions. // Secondly, from the point of view of ease of use, type-based compile-time // information is -not- *that* convenient. On has to write lots of // overloaded functions and to hope that the compiler will select the right // one. As a net effect, the overall structure isn't very clear at first // glance. // Thirdly, partial ordering and overload resolution (of function templates) // is highly costly in terms of compiler-resource. It is a Good Thing to // keep these resource consumption as least as possible. // // See valarray_array.h for a case use. // // -- Gaby (dosreis@cmla.ens-cachan.fr) 2000-03-06. // // Update 2005: types are also provided and has been // removed. // extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct __true_type { }; struct __false_type { }; template struct __truth_type { typedef __false_type __type; }; template<> struct __truth_type { typedef __true_type __type; }; // N.B. The conversions to bool are needed due to the issue // explained in c++/19404. template struct __traitor { enum { __value = bool(_Sp::__value) || bool(_Tp::__value) }; typedef typename __truth_type<__value>::__type __type; }; // Compare for equality of types. template struct __are_same { enum { __value = 0 }; typedef __false_type __type; }; template struct __are_same<_Tp, _Tp> { enum { __value = 1 }; typedef __true_type __type; }; // Holds if the template-argument is a void type. template struct __is_void { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_void { enum { __value = 1 }; typedef __true_type __type; }; // // Integer types // template struct __is_integer { enum { __value = 0 }; typedef __false_type __type; }; // Thirteen specializations (yes there are eleven standard integer // types; long long and unsigned long long are // supported as extensions). Up to four target-specific __int // types are supported as well. template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; # ifdef _GLIBCXX_USE_WCHAR_T template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; # endif #if __cplusplus >= 201103L template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; #endif template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer { enum { __value = 1 }; typedef __true_type __type; }; #define __INT_N(TYPE) \ template<> \ struct __is_integer \ { \ enum { __value = 1 }; \ typedef __true_type __type; \ }; \ template<> \ struct __is_integer \ { \ enum { __value = 1 }; \ typedef __true_type __type; \ }; #ifdef __GLIBCXX_TYPE_INT_N_0 __INT_N(__GLIBCXX_TYPE_INT_N_0) #endif #ifdef __GLIBCXX_TYPE_INT_N_1 __INT_N(__GLIBCXX_TYPE_INT_N_1) #endif #ifdef __GLIBCXX_TYPE_INT_N_2 __INT_N(__GLIBCXX_TYPE_INT_N_2) #endif #ifdef __GLIBCXX_TYPE_INT_N_3 __INT_N(__GLIBCXX_TYPE_INT_N_3) #endif #undef __INT_N // // Floating point types // template struct __is_floating { enum { __value = 0 }; typedef __false_type __type; }; // three specializations (float, double and 'long double') template<> struct __is_floating { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_floating { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_floating { enum { __value = 1 }; typedef __true_type __type; }; // // Pointer types // template struct __is_pointer { enum { __value = 0 }; typedef __false_type __type; }; template struct __is_pointer<_Tp*> { enum { __value = 1 }; typedef __true_type __type; }; // // An arithmetic type is an integer type or a floating point type // template struct __is_arithmetic : public __traitor<__is_integer<_Tp>, __is_floating<_Tp> > { }; // // A scalar type is an arithmetic type or a pointer type // template struct __is_scalar : public __traitor<__is_arithmetic<_Tp>, __is_pointer<_Tp> > { }; // // For use in std::copy and std::find overloads for streambuf iterators. // template struct __is_char { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_char { enum { __value = 1 }; typedef __true_type __type; }; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct __is_char { enum { __value = 1 }; typedef __true_type __type; }; #endif template struct __is_byte { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; #if __cplusplus >= 201703L enum class byte : unsigned char; template<> struct __is_byte { enum { __value = 1 }; typedef __true_type __type; }; #endif // C++17 // // Move iterator type // template struct __is_move_iterator { enum { __value = 0 }; typedef __false_type __type; }; // Fallback implementation of the function in bits/stl_iterator.h used to // remove the move_iterator wrapper. template inline _Iterator __miter_base(_Iterator __it) { return __it; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace } // extern "C++" #endif //_CPP_TYPE_TRAITS_H c++/8/bits/stl_stack.h000064400000027242151027430570010377 0ustar00// Stack implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_stack.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{stack} */ #ifndef _STL_STACK_H #define _STL_STACK_H 1 #include #include #if __cplusplus >= 201103L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief A standard container giving FILO behavior. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Sequence Type of underlying sequence, defaults to deque<_Tp>. * * Meets many of the requirements of a * container, * but does not define anything to do with iterators. Very few of the * other standard container interfaces are defined. * * This is not a true container, but an @e adaptor. It holds * another container, and provides a wrapper interface to that * container. The wrapper is what enforces strict * first-in-last-out %stack behavior. * * The second template parameter defines the type of the underlying * sequence/container. It defaults to std::deque, but it can be * any type that supports @c back, @c push_back, and @c pop_back, * such as std::list, std::vector, or an appropriate user-defined * type. * * Members not found in @a normal containers are @c container_type, * which is a typedef for the second Sequence parameter, and @c * push, @c pop, and @c top, which are standard %stack/FILO * operations. */ template > class stack { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Sequence::value_type _Sequence_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) __glibcxx_class_requires(_Sequence, _BackInsertionSequenceConcept) # endif __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept) #endif template friend bool operator==(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&); template friend bool operator<(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&); #if __cplusplus >= 201103L template using _Uses = typename enable_if::value>::type; #endif public: typedef typename _Sequence::value_type value_type; typedef typename _Sequence::reference reference; typedef typename _Sequence::const_reference const_reference; typedef typename _Sequence::size_type size_type; typedef _Sequence container_type; protected: // See queue::c for notes on this name. _Sequence c; public: // XXX removed old def ctor, added def arg to this one to match 14882 /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L explicit stack(const _Sequence& __c = _Sequence()) : c(__c) { } #else template::value>::type> stack() : c() { } explicit stack(const _Sequence& __c) : c(__c) { } explicit stack(_Sequence&& __c) : c(std::move(__c)) { } template> explicit stack(const _Alloc& __a) : c(__a) { } template> stack(const _Sequence& __c, const _Alloc& __a) : c(__c, __a) { } template> stack(_Sequence&& __c, const _Alloc& __a) : c(std::move(__c), __a) { } template> stack(const stack& __q, const _Alloc& __a) : c(__q.c, __a) { } template> stack(stack&& __q, const _Alloc& __a) : c(std::move(__q.c), __a) { } #endif /** * Returns true if the %stack is empty. */ bool empty() const { return c.empty(); } /** Returns the number of elements in the %stack. */ size_type size() const { return c.size(); } /** * Returns a read/write reference to the data at the first * element of the %stack. */ reference top() { __glibcxx_requires_nonempty(); return c.back(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %stack. */ const_reference top() const { __glibcxx_requires_nonempty(); return c.back(); } /** * @brief Add data to the top of the %stack. * @param __x Data to be added. * * This is a typical %stack operation. The function creates an * element at the top of the %stack and assigns the given data * to it. The time complexity of the operation depends on the * underlying sequence. */ void push(const value_type& __x) { c.push_back(__x); } #if __cplusplus >= 201103L void push(value_type&& __x) { c.push_back(std::move(__x)); } #if __cplusplus > 201402L template decltype(auto) emplace(_Args&&... __args) { return c.emplace_back(std::forward<_Args>(__args)...); } #else template void emplace(_Args&&... __args) { c.emplace_back(std::forward<_Args>(__args)...); } #endif #endif /** * @brief Removes first element. * * This is a typical %stack operation. It shrinks the %stack * by one. The time complexity of the operation depends on the * underlying sequence. * * Note that no data is returned, and if the first element's * data is needed, it should be retrieved before pop() is * called. */ void pop() { __glibcxx_requires_nonempty(); c.pop_back(); } #if __cplusplus >= 201103L void swap(stack& __s) #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 noexcept(__is_nothrow_swappable<_Sequence>::value) #else noexcept(__is_nothrow_swappable<_Tp>::value) #endif { using std::swap; swap(c, __s.c); } #endif // __cplusplus >= 201103L }; #if __cpp_deduction_guides >= 201606 template::value>> stack(_Container) -> stack; template::value>, typename = enable_if_t<__is_allocator<_Allocator>::value>> stack(_Container, _Allocator) -> stack; #endif /** * @brief Stack equality comparison. * @param __x A %stack. * @param __y A %stack of the same type as @a __x. * @return True iff the size and elements of the stacks are equal. * * This is an equivalence relation. Complexity and semantics * depend on the underlying sequence type, but the expected rules * are: this relation is linear in the size of the sequences, and * stacks are considered equivalent if their sequences compare * equal. */ template inline bool operator==(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return __x.c == __y.c; } /** * @brief Stack ordering relation. * @param __x A %stack. * @param __y A %stack of the same type as @a x. * @return True iff @a x is lexicographically less than @a __y. * * This is an total ordering relation. Complexity and semantics * depend on the underlying sequence type, but the expected rules * are: this relation is linear in the size of the sequences, the * elements must be comparable with @c <, and * std::lexicographical_compare() is usually used to make the * determination. */ template inline bool operator<(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return __x.c < __y.c; } /// Based on operator== template inline bool operator!=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const stack<_Tp, _Seq>& __x, const stack<_Tp, _Seq>& __y) { return !(__x < __y); } #if __cplusplus >= 201103L template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__is_swappable<_Seq>::value>::type #else void #endif swap(stack<_Tp, _Seq>& __x, stack<_Tp, _Seq>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template struct uses_allocator, _Alloc> : public uses_allocator<_Seq, _Alloc>::type { }; #endif // __cplusplus >= 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_STACK_H */ c++/8/bits/stl_map.h000064400000147067151027430570010057 0ustar00// Map implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_map.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{map} */ #ifndef _STL_MAP_H #define _STL_MAP_H 1 #include #include #if __cplusplus >= 201103L #include #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class multimap; /** * @brief A standard container made up of (key,value) pairs, which can be * retrieved based on a key, in logarithmic time. * * @ingroup associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to * allocator. * * Meets the requirements of a container, a * reversible container, and an * associative container (using unique keys). * For a @c map the key_type is Key, the mapped_type is T, and the * value_type is std::pair. * * Maps support bidirectional iterators. * * The private tree data is declared exactly the same way for map and * multimap; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template , typename _Alloc = std::allocator > > class map { public: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Alloc allocator_type; private: #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(value_type, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L && defined(__STRICT_ANSI__) static_assert(is_same::value, "std::map must have the same value_type as its allocator"); #endif public: class value_compare : public std::binary_function { friend class map<_Key, _Tp, _Compare, _Alloc>; protected: _Compare comp; value_compare(_Compare __c) : comp(__c) { } public: bool operator()(const value_type& __x, const value_type& __y) const { return comp(__x.first, __y.first); } }; private: /// This turns a red-black tree into a [multi]map. typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind::other _Pair_alloc_type; typedef _Rb_tree, key_compare, _Pair_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; typedef __gnu_cxx::__alloc_traits<_Pair_alloc_type> _Alloc_traits; public: // many of these are specified differently in ISO, but the following are // "functionally equivalent" typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Rep_type::iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; typedef typename _Rep_type::reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; using insert_return_type = typename _Rep_type::insert_return_type; #endif // [23.3.1.1] construct/copy/destroy // (get_allocator() is also listed in this section) /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L map() : _M_t() { } #else map() = default; #endif /** * @brief Creates a %map with no elements. * @param __comp A comparison object. * @param __a An allocator object. */ explicit map(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { } /** * @brief %Map copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L map(const map& __x) : _M_t(__x._M_t) { } #else map(const map&) = default; /** * @brief %Map move constructor. * * The newly-created %map contains the exact contents of the moved * instance. The moved instance is a valid, but unspecified, %map. */ map(map&&) = default; /** * @brief Builds a %map from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison object. * @param __a An allocator object. * * Create a %map consisting of copies of the elements in the * initializer_list @a __l. * This is linear in N if the range is already sorted, and NlogN * otherwise (where N is @a __l.size()). */ map(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit map(const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { } /// Allocator-extended copy constructor. map(const map& __m, const allocator_type& __a) : _M_t(__m._M_t, _Pair_alloc_type(__a)) { } /// Allocator-extended move constructor. map(map&& __m, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__m._M_t), _Pair_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. map(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template map(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } #endif /** * @brief Builds a %map from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %map consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template map(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_unique(__first, __last); } /** * @brief Builds a %map from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %map consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template map(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Pair_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } #if __cplusplus >= 201103L /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~map() = default; #endif /** * @brief %Map assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L map& operator=(const map& __x) { _M_t = __x._M_t; return *this; } #else map& operator=(const map&) = default; /// Move assignment operator. map& operator=(map&&) = default; /** * @brief %Map list assignment operator. * @param __l An initializer_list. * * This function fills a %map with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %map and * that the resulting %map's size is the same as the number * of elements assigned. */ map& operator=(initializer_list __l) { _M_t._M_assign_unique(__l.begin(), __l.end()); return *this; } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } // iterators /** * Returns a read/write iterator that points to the first pair in the * %map. * Iteration is done in ascending order according to the keys. */ iterator begin() _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points to the first pair * in the %map. Iteration is done in ascending order according to the * keys. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read/write iterator that points one past the last * pair in the %map. Iteration is done in ascending order * according to the keys. */ iterator end() _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %map. Iteration is done in ascending order according to * the keys. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read/write reverse iterator that points to the last pair in * the %map. Iteration is done in descending order according to the * keys. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %map. Iteration is done in descending order * according to the keys. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read/write reverse iterator that points to one before the * first pair in the %map. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return _M_t.rend(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %map. Iteration is done in descending * order according to the keys. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first pair * in the %map. Iteration is done in ascending order according to the * keys. */ const_iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * pair in the %map. Iteration is done in ascending order according to * the keys. */ const_iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %map. Iteration is done in descending order * according to the keys. */ const_reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first pair in the %map. Iteration is done in descending * order according to the keys. */ const_reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif // capacity /** Returns true if the %map is empty. (Thus begin() would equal * end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /** Returns the size of the %map. */ size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /** Returns the maximum size of the %map. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } // [23.3.1.2] element access /** * @brief Subscript ( @c [] ) access to %map data. * @param __k The key for which data should be retrieved. * @return A reference to the data of the (key,data) %pair. * * Allows for easy lookup with the subscript ( @c [] ) * operator. Returns data associated with the key specified in * subscript. If the key does not exist, a pair with that key * is created using default values, which is then returned. * * Lookup requires logarithmic time. */ mapped_type& operator[](const key_type& __k) { // concept requirements __glibcxx_function_requires(_DefaultConstructibleConcept) iterator __i = lower_bound(__k); // __i->first is greater than or equivalent to __k. if (__i == end() || key_comp()(__k, (*__i).first)) #if __cplusplus >= 201103L __i = _M_t._M_emplace_hint_unique(__i, std::piecewise_construct, std::tuple(__k), std::tuple<>()); #else __i = insert(__i, value_type(__k, mapped_type())); #endif return (*__i).second; } #if __cplusplus >= 201103L mapped_type& operator[](key_type&& __k) { // concept requirements __glibcxx_function_requires(_DefaultConstructibleConcept) iterator __i = lower_bound(__k); // __i->first is greater than or equivalent to __k. if (__i == end() || key_comp()(__k, (*__i).first)) __i = _M_t._M_emplace_hint_unique(__i, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::tuple<>()); return (*__i).second; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. /** * @brief Access to %map data. * @param __k The key for which data should be retrieved. * @return A reference to the data whose key is equivalent to @a __k, if * such a data is present in the %map. * @throw std::out_of_range If no such data is present. */ mapped_type& at(const key_type& __k) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) __throw_out_of_range(__N("map::at")); return (*__i).second; } const mapped_type& at(const key_type& __k) const { const_iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) __throw_out_of_range(__N("map::at")); return (*__i).second; } // modifiers #if __cplusplus >= 201103L /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * * Insertion requires logarithmic time. */ template std::pair emplace(_Args&&... __args) { return _M_t._M_emplace_unique(std::forward<_Args>(__args)...); } /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_unique(__pos, std::forward<_Args>(__args)...); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_t._M_reinsert_node_unique(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_unique(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(map<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(map<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } template void merge(multimap<_Key, _Tp, _C2, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(multimap<_Key, _Tp, _C2, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus > 201402L #define __cpp_lib_map_try_emplace 201411 /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __k Key to use for finding a possibly existing pair in * the map. * @param __args Arguments used to generate the .second for a new pair * instance. * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * If a %pair is not inserted, this function has no effect. * * Insertion requires logarithmic time. */ template pair try_emplace(const key_type& __k, _Args&&... __args) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)); return {__i, true}; } return {__i, false}; } // move-capable overload template pair try_emplace(key_type&& __k, _Args&&... __args) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)); return {__i, true}; } return {__i, false}; } /** * @brief Attempts to build and insert a std::pair into the %map. * * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __args Arguments used to generate the .second for a new pair * instance. * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument * try_emplace() does. However, if insertion did not take place, * this function has no effect. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) __i = emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)); else __i = iterator(__true_hint.first); return __i; } // move-capable overload template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) __i = emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)); else __i = iterator(__true_hint.first); return __i; } #endif /** * @brief Attempts to insert a std::pair into the %map. * @param __x Pair to be inserted (see std::make_pair for easy * creation of pairs). * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * * Insertion requires logarithmic time. * @{ */ std::pair insert(const value_type& __x) { return _M_t._M_insert_unique(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { return _M_t._M_insert_unique(std::move(__x)); } template __enable_if_t::value, pair> insert(_Pair&& __x) { return _M_t._M_emplace_unique(std::forward<_Pair>(__x)); } #endif // @} #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of std::pairs into the %map. * @param __list A std::initializer_list of pairs to be * inserted. * * Complexity similar to that of the range constructor. */ void insert(std::initializer_list __list) { insert(__list.begin(), __list.end()); } #endif /** * @brief Attempts to insert a std::pair into the %map. * @param __position An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function is not concerned about whether the insertion * took place, and thus does not return a boolean like the * single-argument insert() does. Note that the first * parameter is only a hint and can potentially improve the * performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). * @{ */ iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { return _M_t._M_insert_unique_(__position, __x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_unique_(__position, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __position, _Pair&& __x) { return _M_t._M_emplace_hint_unique(__position, std::forward<_Pair>(__x)); } #endif // @} /** * @brief Template function that attempts to insert a range of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_unique(__first, __last); } #if __cplusplus > 201402L #define __cpp_lib_map_insertion 201411 /** * @brief Attempts to insert or assign a std::pair into the %map. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __obj Argument used to generate the .second for a pair * instance. * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * If the %pair was already in the %map, the .second of the %pair * is assigned from __obj. * * Insertion requires logarithmic time. */ template pair insert_or_assign(const key_type& __k, _Obj&& __obj) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Obj>(__obj))); return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } // move-capable overload template pair insert_or_assign(key_type&& __k, _Obj&& __obj) { iterator __i = lower_bound(__k); if (__i == end() || key_comp()(__k, (*__i).first)) { __i = emplace_hint(__i, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Obj>(__obj))); return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } /** * @brief Attempts to insert or assign a std::pair into the %map. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __obj Argument used to generate the .second for a pair * instance. * * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function attempts to insert a (key, value) %pair into the %map. * A %map relies on unique keys and thus a %pair is only inserted if its * first element (the key) is not already present in the %map. * If the %pair was already in the %map, the .second of the %pair * is assigned from __obj. * * Insertion requires logarithmic time. */ template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) { return emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Obj>(__obj))); } __i = iterator(__true_hint.first); (*__i).second = std::forward<_Obj>(__obj); return __i; } // move-capable overload template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { iterator __i; auto __true_hint = _M_t._M_get_insert_hint_unique_pos(__hint, __k); if (__true_hint.second) { return emplace_hint(iterator(__true_hint.second), std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Obj>(__obj))); } __i = iterator(__true_hint.first); (*__i).second = std::forward<_Obj>(__obj); return __i; } #endif #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %map. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given * iterator, from a %map. Note that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. * * @{ */ iterator erase(const_iterator __position) { return _M_t.erase(__position); } // LWG 2059 _GLIBCXX_ABI_TAG_CXX11 iterator erase(iterator __position) { return _M_t.erase(__position); } // @} #else /** * @brief Erases an element from a %map. * @param __position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given * iterator, from a %map. Note that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * a %map. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %map. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from a %map. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else /** * @brief Erases a [__first,__last) range of elements from a %map. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * * This function erases a sequence of elements from a %map. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * @brief Swaps data with another %map. * @param __x A %map of the same element and allocator types. * * This exchanges the elements between two maps in constant * time. (It is only swapping a pointer, an integer, and an * instance of the @c Compare type (which itself is often * stateless and empty), so it should be quite fast.) Note * that the global std::swap() function is specialized such * that std::swap(m1,m2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(map& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } /** * Erases all elements in a %map. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // observers /** * Returns the key comparison object out of which the %map was * constructed. */ key_compare key_comp() const { return _M_t.key_comp(); } /** * Returns a value comparison object, built from the key comparison * object out of which the %map was constructed. */ value_compare value_comp() const { return value_compare(_M_t.key_comp()); } // [23.3.1.3] map operations //@{ /** * @brief Tries to locate an element in a %map. * @param __x Key of (key, value) %pair to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after %pair. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Tries to locate an element in a %map. * @param __x Key of (key, value) %pair to be located. * @return Read-only (constant) iterator pointing to sought-after * element, or end() if not found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns a constant * iterator pointing to the sought after %pair. If unsuccessful it * returns the past-the-end ( @c end() ) iterator. */ const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) const -> decltype(_M_t._M_find_tr(__x)) { return _M_t._M_find_tr(__x); } #endif //@} //@{ /** * @brief Finds the number of elements with given key. * @param __x Key of (key, value) pairs to be located. * @return Number of elements with specified key. * * This function only makes sense for multimaps; for map the result will * either be 0 (not present) or 1 (present). */ size_type count(const key_type& __x) const { return _M_t.find(__x) == _M_t.end() ? 0 : 1; } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first element * equal to or greater than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_lower_bound_tr(__x))) { return const_iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key of (key, value) pair to be located. * @return Read-only (constant) iterator pointing to first iterator * greater than key, or end(). */ const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_upper_bound_tr(__x))) { return const_iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multimaps. */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key of (key, value) pairs to be located. * @return Pair of read-only (constant) iterators that possibly points * to the subsequence matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multimaps. */ std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) const -> decltype(pair( _M_t._M_equal_range_tr(__x))) { return pair( _M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const map<_K1, _T1, _C1, _A1>&, const map<_K1, _T1, _C1, _A1>&); template friend bool operator<(const map<_K1, _T1, _C1, _A1>&, const map<_K1, _T1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> map(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> map<_Key, _Tp, _Compare, _Allocator>; template , typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Allocator) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> map(initializer_list>, _Allocator) -> map<_Key, _Tp, less<_Key>, _Allocator>; #endif /** * @brief Map equality comparison. * @param __x A %map. * @param __y A %map of the same type as @a x. * @return True iff the size and elements of the maps are equal. * * This is an equivalence relation. It is linear in the size of the * maps. Maps are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Map ordering relation. * @param __x A %map. * @param __y A %map of the same type as @a x. * @return True iff @a x is lexicographically less than @a y. * * This is a total ordering relation. It is linear in the size of the * maps. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Based on operator== template inline bool operator!=(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const map<_Key, _Tp, _Compare, _Alloc>& __x, const map<_Key, _Tp, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::map::swap(). template inline void swap(map<_Key, _Tp, _Compare, _Alloc>& __x, map<_Key, _Tp, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::map access to internals of compatible maps. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::map<_Key, _Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::map<_Key, _Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::map<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multimap<_Key, _Val, _Cmp2, _Alloc>& __map) { return __map._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_MAP_H */ c++/8/bits/fs_ops.h000064400000023002151027430570007667 0ustar00// Filesystem operational functions -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your __option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_OPS_H #define _GLIBCXX_FS_OPS_H 1 #if __cplusplus >= 201703L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { /** * @ingroup filesystem * @{ */ path absolute(const path& __p); path absolute(const path& __p, error_code& __ec); path canonical(const path& __p); path canonical(const path& __p, error_code& __ec); inline void copy(const path& __from, const path& __to) { copy(__from, __to, copy_options::none); } inline void copy(const path& __from, const path& __to, error_code& __ec) { copy(__from, __to, copy_options::none, __ec); } void copy(const path& __from, const path& __to, copy_options __options); void copy(const path& __from, const path& __to, copy_options __options, error_code& __ec); inline bool copy_file(const path& __from, const path& __to) { return copy_file(__from, __to, copy_options::none); } inline bool copy_file(const path& __from, const path& __to, error_code& __ec) { return copy_file(__from, __to, copy_options::none, __ec); } bool copy_file(const path& __from, const path& __to, copy_options __option); bool copy_file(const path& __from, const path& __to, copy_options __option, error_code& __ec); void copy_symlink(const path& __existing_symlink, const path& __new_symlink); void copy_symlink(const path& __existing_symlink, const path& __new_symlink, error_code& __ec) noexcept; bool create_directories(const path& __p); bool create_directories(const path& __p, error_code& __ec); bool create_directory(const path& __p); bool create_directory(const path& __p, error_code& __ec) noexcept; bool create_directory(const path& __p, const path& attributes); bool create_directory(const path& __p, const path& attributes, error_code& __ec) noexcept; void create_directory_symlink(const path& __to, const path& __new_symlink); void create_directory_symlink(const path& __to, const path& __new_symlink, error_code& __ec) noexcept; void create_hard_link(const path& __to, const path& __new_hard_link); void create_hard_link(const path& __to, const path& __new_hard_link, error_code& __ec) noexcept; void create_symlink(const path& __to, const path& __new_symlink); void create_symlink(const path& __to, const path& __new_symlink, error_code& __ec) noexcept; path current_path(); path current_path(error_code& __ec); void current_path(const path& __p); void current_path(const path& __p, error_code& __ec) noexcept; bool equivalent(const path& __p1, const path& __p2); bool equivalent(const path& __p1, const path& __p2, error_code& __ec) noexcept; inline bool exists(file_status __s) noexcept { return status_known(__s) && __s.type() != file_type::not_found; } inline bool exists(const path& __p) { return exists(status(__p)); } inline bool exists(const path& __p, error_code& __ec) noexcept { auto __s = status(__p, __ec); if (status_known(__s)) { __ec.clear(); return __s.type() != file_type::not_found; } return false; } uintmax_t file_size(const path& __p); uintmax_t file_size(const path& __p, error_code& __ec) noexcept; uintmax_t hard_link_count(const path& __p); uintmax_t hard_link_count(const path& __p, error_code& __ec) noexcept; inline bool is_block_file(file_status __s) noexcept { return __s.type() == file_type::block; } inline bool is_block_file(const path& __p) { return is_block_file(status(__p)); } inline bool is_block_file(const path& __p, error_code& __ec) noexcept { return is_block_file(status(__p, __ec)); } inline bool is_character_file(file_status __s) noexcept { return __s.type() == file_type::character; } inline bool is_character_file(const path& __p) { return is_character_file(status(__p)); } inline bool is_character_file(const path& __p, error_code& __ec) noexcept { return is_character_file(status(__p, __ec)); } inline bool is_directory(file_status __s) noexcept { return __s.type() == file_type::directory; } inline bool is_directory(const path& __p) { return is_directory(status(__p)); } inline bool is_directory(const path& __p, error_code& __ec) noexcept { return is_directory(status(__p, __ec)); } bool is_empty(const path& __p); bool is_empty(const path& __p, error_code& __ec); inline bool is_fifo(file_status __s) noexcept { return __s.type() == file_type::fifo; } inline bool is_fifo(const path& __p) { return is_fifo(status(__p)); } inline bool is_fifo(const path& __p, error_code& __ec) noexcept { return is_fifo(status(__p, __ec)); } inline bool is_other(file_status __s) noexcept { return exists(__s) && !is_regular_file(__s) && !is_directory(__s) && !is_symlink(__s); } inline bool is_other(const path& __p) { return is_other(status(__p)); } inline bool is_other(const path& __p, error_code& __ec) noexcept { return is_other(status(__p, __ec)); } inline bool is_regular_file(file_status __s) noexcept { return __s.type() == file_type::regular; } inline bool is_regular_file(const path& __p) { return is_regular_file(status(__p)); } inline bool is_regular_file(const path& __p, error_code& __ec) noexcept { return is_regular_file(status(__p, __ec)); } inline bool is_socket(file_status __s) noexcept { return __s.type() == file_type::socket; } inline bool is_socket(const path& __p) { return is_socket(status(__p)); } inline bool is_socket(const path& __p, error_code& __ec) noexcept { return is_socket(status(__p, __ec)); } inline bool is_symlink(file_status __s) noexcept { return __s.type() == file_type::symlink; } inline bool is_symlink(const path& __p) { return is_symlink(symlink_status(__p)); } inline bool is_symlink(const path& __p, error_code& __ec) noexcept { return is_symlink(symlink_status(__p, __ec)); } file_time_type last_write_time(const path& __p); file_time_type last_write_time(const path& __p, error_code& __ec) noexcept; void last_write_time(const path& __p, file_time_type __new_time); void last_write_time(const path& __p, file_time_type __new_time, error_code& __ec) noexcept; void permissions(const path& __p, perms __prms, perm_options __opts = perm_options::replace); inline void permissions(const path& __p, perms __prms, error_code& __ec) noexcept { permissions(__p, __prms, perm_options::replace, __ec); } void permissions(const path& __p, perms __prms, perm_options __opts, error_code& __ec) noexcept; inline path proximate(const path& __p, error_code& __ec) { return proximate(__p, current_path(), __ec); } path proximate(const path& __p, const path& __base = current_path()); path proximate(const path& __p, const path& __base, error_code& __ec); path read_symlink(const path& __p); path read_symlink(const path& __p, error_code& __ec); inline path relative(const path& __p, error_code& __ec) { return relative(__p, current_path(), __ec); } path relative(const path& __p, const path& __base = current_path()); path relative(const path& __p, const path& __base, error_code& __ec); bool remove(const path& __p); bool remove(const path& __p, error_code& __ec) noexcept; uintmax_t remove_all(const path& __p); uintmax_t remove_all(const path& __p, error_code& __ec); void rename(const path& __from, const path& __to); void rename(const path& __from, const path& __to, error_code& __ec) noexcept; void resize_file(const path& __p, uintmax_t __size); void resize_file(const path& __p, uintmax_t __size, error_code& __ec) noexcept; space_info space(const path& __p); space_info space(const path& __p, error_code& __ec) noexcept; file_status status(const path& __p); file_status status(const path& __p, error_code& __ec) noexcept; inline bool status_known(file_status __s) noexcept { return __s.type() != file_type::none; } file_status symlink_status(const path& __p); file_status symlink_status(const path& __p, error_code& __ec) noexcept; path temp_directory_path(); path temp_directory_path(error_code& __ec); path weakly_canonical(const path& __p); path weakly_canonical(const path& __p, error_code& __ec); // @} group filesystem } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_OPS_H c++/8/bits/char_traits.h000064400000050663151027430570010716 0ustar00// Character Traits for use by standard string and iostream -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/char_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // #ifndef _CHAR_TRAITS_H #define _CHAR_TRAITS_H 1 #pragma GCC system_header #include // std::copy, std::fill_n #include // For streampos #include // For WEOF, wmemmove, wmemset, etc. #ifndef _GLIBCXX_ALWAYS_INLINE #define _GLIBCXX_ALWAYS_INLINE inline __attribute__((__always_inline__)) #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Mapping from character type to associated types. * * @note This is an implementation class for the generic version * of char_traits. It defines int_type, off_type, pos_type, and * state_type. By default these are unsigned long, streamoff, * streampos, and mbstate_t. Users who need a different set of * types, but who don't need to change the definitions of any function * defined in char_traits, can specialize __gnu_cxx::_Char_types * while leaving __gnu_cxx::char_traits alone. */ template struct _Char_types { typedef unsigned long int_type; typedef std::streampos pos_type; typedef std::streamoff off_type; typedef std::mbstate_t state_type; }; /** * @brief Base class used to implement std::char_traits. * * @note For any given actual character type, this definition is * probably wrong. (Most of the member functions are likely to be * right, but the int_type and state_type typedefs, and the eof() * member function, are likely to be wrong.) The reason this class * exists is so users can specialize it. Classes in namespace std * may not be specialized for fundamental types, but classes in * namespace __gnu_cxx may be. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html#strings.string.character_types * for advice on how to make use of this class for @a unusual character * types. Also, check out include/ext/pod_char_traits.h. */ template struct char_traits { typedef _CharT char_type; typedef typename _Char_types<_CharT>::int_type int_type; typedef typename _Char_types<_CharT>::pos_type pos_type; typedef typename _Char_types<_CharT>::off_type off_type; typedef typename _Char_types<_CharT>::state_type state_type; static _GLIBCXX14_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) { __c1 = __c2; } static _GLIBCXX_CONSTEXPR bool eq(const char_type& __c1, const char_type& __c2) { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR bool lt(const char_type& __c1, const char_type& __c2) { return __c1 < __c2; } static _GLIBCXX14_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, std::size_t __n); static _GLIBCXX14_CONSTEXPR std::size_t length(const char_type* __s); static _GLIBCXX14_CONSTEXPR const char_type* find(const char_type* __s, std::size_t __n, const char_type& __a); static char_type* move(char_type* __s1, const char_type* __s2, std::size_t __n); static char_type* copy(char_type* __s1, const char_type* __s2, std::size_t __n); static char_type* assign(char_type* __s, std::size_t __n, char_type __a); static _GLIBCXX_CONSTEXPR char_type to_char_type(const int_type& __c) { return static_cast(__c); } static _GLIBCXX_CONSTEXPR int_type to_int_type(const char_type& __c) { return static_cast(__c); } static _GLIBCXX_CONSTEXPR bool eq_int_type(const int_type& __c1, const int_type& __c2) { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR int_type eof() { return static_cast(_GLIBCXX_STDIO_EOF); } static _GLIBCXX_CONSTEXPR int_type not_eof(const int_type& __c) { return !eq_int_type(__c, eof()) ? __c : to_int_type(char_type()); } }; template _GLIBCXX14_CONSTEXPR int char_traits<_CharT>:: compare(const char_type* __s1, const char_type* __s2, std::size_t __n) { for (std::size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } template _GLIBCXX14_CONSTEXPR std::size_t char_traits<_CharT>:: length(const char_type* __p) { std::size_t __i = 0; while (!eq(__p[__i], char_type())) ++__i; return __i; } template _GLIBCXX14_CONSTEXPR const typename char_traits<_CharT>::char_type* char_traits<_CharT>:: find(const char_type* __s, std::size_t __n, const char_type& __a) { for (std::size_t __i = 0; __i < __n; ++__i) if (eq(__s[__i], __a)) return __s + __i; return 0; } template typename char_traits<_CharT>::char_type* char_traits<_CharT>:: move(char_type* __s1, const char_type* __s2, std::size_t __n) { if (__n == 0) return __s1; return static_cast<_CharT*>(__builtin_memmove(__s1, __s2, __n * sizeof(char_type))); } template typename char_traits<_CharT>::char_type* char_traits<_CharT>:: copy(char_type* __s1, const char_type* __s2, std::size_t __n) { // NB: Inline std::copy so no recursive dependencies. std::copy(__s2, __s2 + __n, __s1); return __s1; } template typename char_traits<_CharT>::char_type* char_traits<_CharT>:: assign(char_type* __s, std::size_t __n, char_type __a) { // NB: Inline std::fill_n so no recursive dependencies. std::fill_n(__s, __n, __a); return __s; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus > 201402 #define __cpp_lib_constexpr_char_traits 201611 /** * @brief Determine whether the characters of a NULL-terminated * string are known at compile time. * @param __s The string. * * Assumes that _CharT is a built-in character type. */ template static _GLIBCXX_ALWAYS_INLINE constexpr bool __constant_string_p(const _CharT* __s) { while (__builtin_constant_p(*__s) && *__s) __s++; return __builtin_constant_p(*__s); } /** * @brief Determine whether the characters of a character array are * known at compile time. * @param __a The character array. * @param __n Number of characters. * * Assumes that _CharT is a built-in character type. */ template static _GLIBCXX_ALWAYS_INLINE constexpr bool __constant_char_array_p(const _CharT* __a, size_t __n) { size_t __i = 0; while (__i < __n && __builtin_constant_p(__a[__i])) __i++; return __i == __n; } #endif // 21.1 /** * @brief Basis for explicit traits specializations. * * @note For any given actual character type, this definition is * probably wrong. Since this is just a thin wrapper around * __gnu_cxx::char_traits, it is possible to achieve a more * appropriate definition by specializing __gnu_cxx::char_traits. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/strings.html#strings.string.character_types * for advice on how to make use of this class for @a unusual character * types. Also, check out include/ext/pod_char_traits.h. */ template struct char_traits : public __gnu_cxx::char_traits<_CharT> { }; /// 21.1.3.1 char_traits specializations template<> struct char_traits { typedef char char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { __c1 = __c2; } static _GLIBCXX_CONSTEXPR bool eq(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR bool lt(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { // LWG 467. return (static_cast(__c1) < static_cast(__c2)); } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __constant_char_array_p(__s1, __n) && __constant_char_array_p(__s2, __n)) { for (size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } #endif if (__n == 0) return 0; return __builtin_memcmp(__s1, __s2, __n); } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { #if __cplusplus > 201402 if (__constant_string_p(__s)) return __gnu_cxx::char_traits::length(__s); #endif return __builtin_strlen(__s); } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __builtin_constant_p(__a) && __constant_char_array_p(__s, __n)) return __gnu_cxx::char_traits::find(__s, __n, __a); #endif if (__n == 0) return 0; return static_cast(__builtin_memchr(__s, __a, __n)); } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return static_cast(__builtin_memmove(__s1, __s2, __n)); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return static_cast(__builtin_memcpy(__s1, __s2, __n)); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { if (__n == 0) return __s; return static_cast(__builtin_memset(__s, __a, __n)); } static _GLIBCXX_CONSTEXPR char_type to_char_type(const int_type& __c) _GLIBCXX_NOEXCEPT { return static_cast(__c); } // To keep both the byte 0xff and the eof symbol 0xffffffff // from ending up as 0xffffffff. static _GLIBCXX_CONSTEXPR int_type to_int_type(const char_type& __c) _GLIBCXX_NOEXCEPT { return static_cast(static_cast(__c)); } static _GLIBCXX_CONSTEXPR bool eq_int_type(const int_type& __c1, const int_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR int_type eof() _GLIBCXX_NOEXCEPT { return static_cast(_GLIBCXX_STDIO_EOF); } static _GLIBCXX_CONSTEXPR int_type not_eof(const int_type& __c) _GLIBCXX_NOEXCEPT { return (__c == eof()) ? 0 : __c; } }; #ifdef _GLIBCXX_USE_WCHAR_T /// 21.1.3.2 char_traits specializations template<> struct char_traits { typedef wchar_t char_type; typedef wint_t int_type; typedef streamoff off_type; typedef wstreampos pos_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { __c1 = __c2; } static _GLIBCXX_CONSTEXPR bool eq(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR bool lt(const char_type& __c1, const char_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 < __c2; } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __constant_char_array_p(__s1, __n) && __constant_char_array_p(__s2, __n)) return __gnu_cxx::char_traits::compare(__s1, __s2, __n); #endif if (__n == 0) return 0; else return wmemcmp(__s1, __s2, __n); } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { #if __cplusplus > 201402 if (__constant_string_p(__s)) return __gnu_cxx::char_traits::length(__s); else #endif return wcslen(__s); } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { #if __cplusplus > 201402 if (__builtin_constant_p(__n) && __builtin_constant_p(__a) && __constant_char_array_p(__s, __n)) return __gnu_cxx::char_traits::find(__s, __n, __a); #endif if (__n == 0) return 0; else return wmemchr(__s, __a, __n); } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return wmemmove(__s1, __s2, __n); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return wmemcpy(__s1, __s2, __n); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { if (__n == 0) return __s; return wmemset(__s, __a, __n); } static _GLIBCXX_CONSTEXPR char_type to_char_type(const int_type& __c) _GLIBCXX_NOEXCEPT { return char_type(__c); } static _GLIBCXX_CONSTEXPR int_type to_int_type(const char_type& __c) _GLIBCXX_NOEXCEPT { return int_type(__c); } static _GLIBCXX_CONSTEXPR bool eq_int_type(const int_type& __c1, const int_type& __c2) _GLIBCXX_NOEXCEPT { return __c1 == __c2; } static _GLIBCXX_CONSTEXPR int_type eof() _GLIBCXX_NOEXCEPT { return static_cast(WEOF); } static _GLIBCXX_CONSTEXPR int_type not_eof(const int_type& __c) _GLIBCXX_NOEXCEPT { return eq_int_type(__c, eof()) ? 0 : __c; } }; #endif //_GLIBCXX_USE_WCHAR_T _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template<> struct char_traits { typedef char16_t char_type; typedef uint_least16_t int_type; typedef streamoff off_type; typedef u16streampos pos_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) noexcept { __c1 = __c2; } static constexpr bool eq(const char_type& __c1, const char_type& __c2) noexcept { return __c1 == __c2; } static constexpr bool lt(const char_type& __c1, const char_type& __c2) noexcept { return __c1 < __c2; } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { for (size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { size_t __i = 0; while (!eq(__s[__i], char_type())) ++__i; return __i; } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { for (size_t __i = 0; __i < __n; ++__i) if (eq(__s[__i], __a)) return __s + __i; return 0; } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memmove(__s1, __s2, __n * sizeof(char_type)))); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memcpy(__s1, __s2, __n * sizeof(char_type)))); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { for (size_t __i = 0; __i < __n; ++__i) assign(__s[__i], __a); return __s; } static constexpr char_type to_char_type(const int_type& __c) noexcept { return char_type(__c); } static constexpr int_type to_int_type(const char_type& __c) noexcept { return __c == eof() ? int_type(0xfffd) : int_type(__c); } static constexpr bool eq_int_type(const int_type& __c1, const int_type& __c2) noexcept { return __c1 == __c2; } static constexpr int_type eof() noexcept { return static_cast(-1); } static constexpr int_type not_eof(const int_type& __c) noexcept { return eq_int_type(__c, eof()) ? 0 : __c; } }; template<> struct char_traits { typedef char32_t char_type; typedef uint_least32_t int_type; typedef streamoff off_type; typedef u32streampos pos_type; typedef mbstate_t state_type; static _GLIBCXX17_CONSTEXPR void assign(char_type& __c1, const char_type& __c2) noexcept { __c1 = __c2; } static constexpr bool eq(const char_type& __c1, const char_type& __c2) noexcept { return __c1 == __c2; } static constexpr bool lt(const char_type& __c1, const char_type& __c2) noexcept { return __c1 < __c2; } static _GLIBCXX17_CONSTEXPR int compare(const char_type* __s1, const char_type* __s2, size_t __n) { for (size_t __i = 0; __i < __n; ++__i) if (lt(__s1[__i], __s2[__i])) return -1; else if (lt(__s2[__i], __s1[__i])) return 1; return 0; } static _GLIBCXX17_CONSTEXPR size_t length(const char_type* __s) { size_t __i = 0; while (!eq(__s[__i], char_type())) ++__i; return __i; } static _GLIBCXX17_CONSTEXPR const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { for (size_t __i = 0; __i < __n; ++__i) if (eq(__s[__i], __a)) return __s + __i; return 0; } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memmove(__s1, __s2, __n * sizeof(char_type)))); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return (static_cast (__builtin_memcpy(__s1, __s2, __n * sizeof(char_type)))); } static char_type* assign(char_type* __s, size_t __n, char_type __a) { for (size_t __i = 0; __i < __n; ++__i) assign(__s[__i], __a); return __s; } static constexpr char_type to_char_type(const int_type& __c) noexcept { return char_type(__c); } static constexpr int_type to_int_type(const char_type& __c) noexcept { return int_type(__c); } static constexpr bool eq_int_type(const int_type& __c1, const int_type& __c2) noexcept { return __c1 == __c2; } static constexpr int_type eof() noexcept { return static_cast(-1); } static constexpr int_type not_eof(const int_type& __c) noexcept { return eq_int_type(__c, eof()) ? 0 : __c; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif #endif // _CHAR_TRAITS_H c++/8/bits/stl_iterator_base_funcs.h000064400000017762151027430570013321 0ustar00// Functions used by iterators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_iterator_base_funcs.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} * * This file contains all of the general iterator-related utility * functions, such as distance() and advance(). */ #ifndef _STL_ITERATOR_BASE_FUNCS_H #define _STL_ITERATOR_BASE_FUNCS_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER // Forward declaration for the overloads of __distance. template struct _List_iterator; template struct _List_const_iterator; _GLIBCXX_END_NAMESPACE_CONTAINER template inline _GLIBCXX14_CONSTEXPR typename iterator_traits<_InputIterator>::difference_type __distance(_InputIterator __first, _InputIterator __last, input_iterator_tag) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) typename iterator_traits<_InputIterator>::difference_type __n = 0; while (__first != __last) { ++__first; ++__n; } return __n; } template inline _GLIBCXX14_CONSTEXPR typename iterator_traits<_RandomAccessIterator>::difference_type __distance(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) return __last - __first; } #if _GLIBCXX_USE_CXX11_ABI // Forward declaration because of the qualified call in distance. template ptrdiff_t __distance(_GLIBCXX_STD_C::_List_iterator<_Tp>, _GLIBCXX_STD_C::_List_iterator<_Tp>, input_iterator_tag); template ptrdiff_t __distance(_GLIBCXX_STD_C::_List_const_iterator<_Tp>, _GLIBCXX_STD_C::_List_const_iterator<_Tp>, input_iterator_tag); #endif /** * @brief A generalization of pointer arithmetic. * @param __first An input iterator. * @param __last An input iterator. * @return The distance between them. * * Returns @c n such that __first + n == __last. This requires * that @p __last must be reachable from @p __first. Note that @c * n may be negative. * * For random access iterators, this uses their @c + and @c - operations * and are constant time. For other %iterator classes they are linear time. */ template inline _GLIBCXX17_CONSTEXPR typename iterator_traits<_InputIterator>::difference_type distance(_InputIterator __first, _InputIterator __last) { // concept requirements -- taken care of in __distance return std::__distance(__first, __last, std::__iterator_category(__first)); } template inline _GLIBCXX14_CONSTEXPR void __advance(_InputIterator& __i, _Distance __n, input_iterator_tag) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) __glibcxx_assert(__n >= 0); while (__n--) ++__i; } template inline _GLIBCXX14_CONSTEXPR void __advance(_BidirectionalIterator& __i, _Distance __n, bidirectional_iterator_tag) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) if (__n > 0) while (__n--) ++__i; else while (__n++) --__i; } template inline _GLIBCXX14_CONSTEXPR void __advance(_RandomAccessIterator& __i, _Distance __n, random_access_iterator_tag) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) if (__builtin_constant_p(__n) && __n == 1) ++__i; else if (__builtin_constant_p(__n) && __n == -1) --__i; else __i += __n; } /** * @brief A generalization of pointer arithmetic. * @param __i An input iterator. * @param __n The @a delta by which to change @p __i. * @return Nothing. * * This increments @p i by @p n. For bidirectional and random access * iterators, @p __n may be negative, in which case @p __i is decremented. * * For random access iterators, this uses their @c + and @c - operations * and are constant time. For other %iterator classes they are linear time. */ template inline _GLIBCXX17_CONSTEXPR void advance(_InputIterator& __i, _Distance __n) { // concept requirements -- taken care of in __advance typename iterator_traits<_InputIterator>::difference_type __d = __n; std::__advance(__i, __d, std::__iterator_category(__i)); } #if __cplusplus >= 201103L template inline _GLIBCXX17_CONSTEXPR _InputIterator next(_InputIterator __x, typename iterator_traits<_InputIterator>::difference_type __n = 1) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator>) std::advance(__x, __n); return __x; } template inline _GLIBCXX17_CONSTEXPR _BidirectionalIterator prev(_BidirectionalIterator __x, typename iterator_traits<_BidirectionalIterator>::difference_type __n = 1) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept< _BidirectionalIterator>) std::advance(__x, -__n); return __x; } #endif // C++11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_ITERATOR_BASE_FUNCS_H */ c++/8/bits/stl_heap.h000064400000047356151027430570010217 0ustar00// Heap implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_heap.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{queue} */ #ifndef _STL_HEAP_H #define _STL_HEAP_H 1 #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup heap_algorithms Heap * @ingroup sorting_algorithms */ template _Distance __is_heap_until(_RandomAccessIterator __first, _Distance __n, _Compare& __comp) { _Distance __parent = 0; for (_Distance __child = 1; __child < __n; ++__child) { if (__comp(__first + __parent, __first + __child)) return __child; if ((__child & 1) == 0) ++__parent; } return __n; } // __is_heap, a predicate testing whether or not a range is a heap. // This function is an extension, not part of the C++ standard. template inline bool __is_heap(_RandomAccessIterator __first, _Distance __n) { __gnu_cxx::__ops::_Iter_less_iter __comp; return std::__is_heap_until(__first, __n, __comp) == __n; } template inline bool __is_heap(_RandomAccessIterator __first, _Compare __comp, _Distance __n) { typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); return std::__is_heap_until(__first, __n, __cmp) == __n; } template inline bool __is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { return std::__is_heap(__first, std::distance(__first, __last)); } template inline bool __is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { return std::__is_heap(__first, _GLIBCXX_MOVE(__comp), std::distance(__first, __last)); } // Heap-manipulation functions: push_heap, pop_heap, make_heap, sort_heap, // + is_heap and is_heap_until in C++0x. template void __push_heap(_RandomAccessIterator __first, _Distance __holeIndex, _Distance __topIndex, _Tp __value, _Compare& __comp) { _Distance __parent = (__holeIndex - 1) / 2; while (__holeIndex > __topIndex && __comp(__first + __parent, __value)) { *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __parent)); __holeIndex = __parent; __parent = (__holeIndex - 1) / 2; } *(__first + __holeIndex) = _GLIBCXX_MOVE(__value); } /** * @brief Push an element onto a heap. * @param __first Start of heap. * @param __last End of heap + element. * @ingroup heap_algorithms * * This operation pushes the element at last-1 onto the valid heap * over the range [__first,__last-1). After completion, * [__first,__last) is a valid heap. */ template inline void push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept<_ValueType>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_heap(__first, __last - 1); __gnu_cxx::__ops::_Iter_less_val __comp; _ValueType __value = _GLIBCXX_MOVE(*(__last - 1)); std::__push_heap(__first, _DistanceType((__last - __first) - 1), _DistanceType(0), _GLIBCXX_MOVE(__value), __comp); } /** * @brief Push an element onto a heap using comparison functor. * @param __first Start of heap. * @param __last End of heap + element. * @param __comp Comparison functor. * @ingroup heap_algorithms * * This operation pushes the element at __last-1 onto the valid * heap over the range [__first,__last-1). After completion, * [__first,__last) is a valid heap. Compare operations are * performed using comp. */ template inline void push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_heap_pred(__first, __last - 1, __comp); __decltype(__gnu_cxx::__ops::__iter_comp_val(_GLIBCXX_MOVE(__comp))) __cmp(_GLIBCXX_MOVE(__comp)); _ValueType __value = _GLIBCXX_MOVE(*(__last - 1)); std::__push_heap(__first, _DistanceType((__last - __first) - 1), _DistanceType(0), _GLIBCXX_MOVE(__value), __cmp); } template void __adjust_heap(_RandomAccessIterator __first, _Distance __holeIndex, _Distance __len, _Tp __value, _Compare __comp) { const _Distance __topIndex = __holeIndex; _Distance __secondChild = __holeIndex; while (__secondChild < (__len - 1) / 2) { __secondChild = 2 * (__secondChild + 1); if (__comp(__first + __secondChild, __first + (__secondChild - 1))) __secondChild--; *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + __secondChild)); __holeIndex = __secondChild; } if ((__len & 1) == 0 && __secondChild == (__len - 2) / 2) { __secondChild = 2 * (__secondChild + 1); *(__first + __holeIndex) = _GLIBCXX_MOVE(*(__first + (__secondChild - 1))); __holeIndex = __secondChild - 1; } __decltype(__gnu_cxx::__ops::__iter_comp_val(_GLIBCXX_MOVE(__comp))) __cmp(_GLIBCXX_MOVE(__comp)); std::__push_heap(__first, __holeIndex, __topIndex, _GLIBCXX_MOVE(__value), __cmp); } template inline void __pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _RandomAccessIterator __result, _Compare& __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; _ValueType __value = _GLIBCXX_MOVE(*__result); *__result = _GLIBCXX_MOVE(*__first); std::__adjust_heap(__first, _DistanceType(0), _DistanceType(__last - __first), _GLIBCXX_MOVE(__value), __comp); } /** * @brief Pop an element off a heap. * @param __first Start of heap. * @param __last End of heap. * @pre [__first, __last) is a valid, non-empty range. * @ingroup heap_algorithms * * This operation pops the top of the heap. The elements __first * and __last-1 are swapped and [__first,__last-1) is made into a * heap. */ template inline void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_non_empty_range(__first, __last); __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_heap(__first, __last); if (__last - __first > 1) { --__last; __gnu_cxx::__ops::_Iter_less_iter __comp; std::__pop_heap(__first, __last, __last, __comp); } } /** * @brief Pop an element off a heap using comparison functor. * @param __first Start of heap. * @param __last End of heap. * @param __comp Comparison functor to use. * @ingroup heap_algorithms * * This operation pops the top of the heap. The elements __first * and __last-1 are swapped and [__first,__last-1) is made into a * heap. Comparisons are made using comp. */ template inline void pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_non_empty_range(__first, __last); __glibcxx_requires_heap_pred(__first, __last, __comp); if (__last - __first > 1) { typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); --__last; std::__pop_heap(__first, __last, __last, __cmp); } } template void __make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _ValueType; typedef typename iterator_traits<_RandomAccessIterator>::difference_type _DistanceType; if (__last - __first < 2) return; const _DistanceType __len = __last - __first; _DistanceType __parent = (__len - 2) / 2; while (true) { _ValueType __value = _GLIBCXX_MOVE(*(__first + __parent)); std::__adjust_heap(__first, __parent, __len, _GLIBCXX_MOVE(__value), __comp); if (__parent == 0) return; __parent--; } } /** * @brief Construct a heap over a range. * @param __first Start of heap. * @param __last End of heap. * @ingroup heap_algorithms * * This operation makes the elements in [__first,__last) into a heap. */ template inline void make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __gnu_cxx::__ops::_Iter_less_iter __comp; std::__make_heap(__first, __last, __comp); } /** * @brief Construct a heap over a range using comparison functor. * @param __first Start of heap. * @param __last End of heap. * @param __comp Comparison functor to use. * @ingroup heap_algorithms * * This operation makes the elements in [__first,__last) into a heap. * Comparisons are made using __comp. */ template inline void make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); std::__make_heap(__first, __last, __cmp); } template void __sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare& __comp) { while (__last - __first > 1) { --__last; std::__pop_heap(__first, __last, __last, __comp); } } /** * @brief Sort a heap. * @param __first Start of heap. * @param __last End of heap. * @ingroup heap_algorithms * * This operation sorts the valid heap in the range [__first,__last). */ template inline void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __glibcxx_requires_heap(__first, __last); __gnu_cxx::__ops::_Iter_less_iter __comp; std::__sort_heap(__first, __last, __comp); } /** * @brief Sort a heap using comparison functor. * @param __first Start of heap. * @param __last End of heap. * @param __comp Comparison functor to use. * @ingroup heap_algorithms * * This operation sorts the valid heap in the range [__first,__last). * Comparisons are made using __comp. */ template inline void sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); __glibcxx_requires_heap_pred(__first, __last, __comp); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); std::__sort_heap(__first, __last, __cmp); } #if __cplusplus >= 201103L /** * @brief Search the end of a heap. * @param __first Start of range. * @param __last End of range. * @return An iterator pointing to the first element not in the heap. * @ingroup heap_algorithms * * This operation returns the last iterator i in [__first, __last) for which * the range [__first, i) is a heap. */ template inline _RandomAccessIterator is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); __gnu_cxx::__ops::_Iter_less_iter __comp; return __first + std::__is_heap_until(__first, std::distance(__first, __last), __comp); } /** * @brief Search the end of a heap using comparison functor. * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor to use. * @return An iterator pointing to the first element not in the heap. * @ingroup heap_algorithms * * This operation returns the last iterator i in [__first, __last) for which * the range [__first, i) is a heap. Comparisons are made using __comp. */ template inline _RandomAccessIterator is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); return __first + std::__is_heap_until(__first, std::distance(__first, __last), __cmp); } /** * @brief Determines whether a range is a heap. * @param __first Start of range. * @param __last End of range. * @return True if range is a heap, false otherwise. * @ingroup heap_algorithms */ template inline bool is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last) { return std::is_heap_until(__first, __last) == __last; } /** * @brief Determines whether a range is a heap using comparison functor. * @param __first Start of range. * @param __last End of range. * @param __comp Comparison functor to use. * @return True if range is a heap, false otherwise. * @ingroup heap_algorithms */ template inline bool is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { // concept requirements __glibcxx_function_requires(_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive_pred(__first, __last, __comp); const auto __dist = std::distance(__first, __last); typedef __decltype(__comp) _Cmp; __gnu_cxx::__ops::_Iter_comp_iter<_Cmp> __cmp(_GLIBCXX_MOVE(__comp)); return std::__is_heap_until(__first, __dist, __cmp) == __dist; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_HEAP_H */ c++/8/bits/stl_list.h000064400000203746151027430570010252 0ustar00// List implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_list.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{list} */ #ifndef _STL_LIST_H #define _STL_LIST_H 1 #include #include #if __cplusplus >= 201103L #include #include #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { // Supporting structures are split into common and templated // types; the latter publicly inherits from the former in an // effort to reduce code duplication. This results in some // "needless" static_cast'ing later on, but it's all safe // downcasting. /// Common part of a node in the %list. struct _List_node_base { _List_node_base* _M_next; _List_node_base* _M_prev; static void swap(_List_node_base& __x, _List_node_base& __y) _GLIBCXX_USE_NOEXCEPT; void _M_transfer(_List_node_base* const __first, _List_node_base* const __last) _GLIBCXX_USE_NOEXCEPT; void _M_reverse() _GLIBCXX_USE_NOEXCEPT; void _M_hook(_List_node_base* const __position) _GLIBCXX_USE_NOEXCEPT; void _M_unhook() _GLIBCXX_USE_NOEXCEPT; }; /// The %list node header. struct _List_node_header : public _List_node_base { #if _GLIBCXX_USE_CXX11_ABI std::size_t _M_size; #endif _List_node_header() _GLIBCXX_NOEXCEPT { _M_init(); } #if __cplusplus >= 201103L _List_node_header(_List_node_header&& __x) noexcept : _List_node_base{ __x._M_next, __x._M_prev } # if _GLIBCXX_USE_CXX11_ABI , _M_size(__x._M_size) # endif { if (__x._M_base()->_M_next == __x._M_base()) this->_M_next = this->_M_prev = this; else { this->_M_next->_M_prev = this->_M_prev->_M_next = this->_M_base(); __x._M_init(); } } void _M_move_nodes(_List_node_header&& __x) { _List_node_base* const __xnode = __x._M_base(); if (__xnode->_M_next == __xnode) _M_init(); else { _List_node_base* const __node = this->_M_base(); __node->_M_next = __xnode->_M_next; __node->_M_prev = __xnode->_M_prev; __node->_M_next->_M_prev = __node->_M_prev->_M_next = __node; # if _GLIBCXX_USE_CXX11_ABI _M_size = __x._M_size; # endif __x._M_init(); } } #endif void _M_init() _GLIBCXX_NOEXCEPT { this->_M_next = this->_M_prev = this; #if _GLIBCXX_USE_CXX11_ABI this->_M_size = 0; #endif } private: _List_node_base* _M_base() { return this; } }; } // namespace detail _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// An actual node in the %list. template struct _List_node : public __detail::_List_node_base { #if __cplusplus >= 201103L __gnu_cxx::__aligned_membuf<_Tp> _M_storage; _Tp* _M_valptr() { return _M_storage._M_ptr(); } _Tp const* _M_valptr() const { return _M_storage._M_ptr(); } #else _Tp _M_data; _Tp* _M_valptr() { return std::__addressof(_M_data); } _Tp const* _M_valptr() const { return std::__addressof(_M_data); } #endif }; /** * @brief A list::iterator. * * All the functions are op overloads. */ template struct _List_iterator { typedef _List_iterator<_Tp> _Self; typedef _List_node<_Tp> _Node; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef _Tp value_type; typedef _Tp* pointer; typedef _Tp& reference; _List_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _List_iterator(__detail::_List_node_base* __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } _Self _M_const_cast() const _GLIBCXX_NOEXCEPT { return *this; } // Must downcast from _List_node_base to _List_node to get to value. reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Node*>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Node*>(_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_next; return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_prev; return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_prev; return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } // The only member points to the %list element. __detail::_List_node_base* _M_node; }; /** * @brief A list::const_iterator. * * All the functions are op overloads. */ template struct _List_const_iterator { typedef _List_const_iterator<_Tp> _Self; typedef const _List_node<_Tp> _Node; typedef _List_iterator<_Tp> iterator; typedef ptrdiff_t difference_type; typedef std::bidirectional_iterator_tag iterator_category; typedef _Tp value_type; typedef const _Tp* pointer; typedef const _Tp& reference; _List_const_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _List_const_iterator(const __detail::_List_node_base* __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } _List_const_iterator(const iterator& __x) _GLIBCXX_NOEXCEPT : _M_node(__x._M_node) { } iterator _M_const_cast() const _GLIBCXX_NOEXCEPT { return iterator(const_cast<__detail::_List_node_base*>(_M_node)); } // Must downcast from List_node_base to _List_node to get to value. reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Node*>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Node*>(_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_next; return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_next; return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _M_node->_M_prev; return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _M_node->_M_prev; return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } // The only member points to the %list element. const __detail::_List_node_base* _M_node; }; template inline bool operator==(const _List_iterator<_Val>& __x, const _List_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node == __y._M_node; } template inline bool operator!=(const _List_iterator<_Val>& __x, const _List_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node != __y._M_node; } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /// See bits/stl_deque.h's _Deque_base for an explanation. template class _List_base { protected: typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type; typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tp_alloc_traits; typedef typename _Tp_alloc_traits::template rebind<_List_node<_Tp> >::other _Node_alloc_type; typedef __gnu_cxx::__alloc_traits<_Node_alloc_type> _Node_alloc_traits; #if !_GLIBCXX_INLINE_VERSION static size_t _S_distance(const __detail::_List_node_base* __first, const __detail::_List_node_base* __last) { size_t __n = 0; while (__first != __last) { __first = __first->_M_next; ++__n; } return __n; } #endif struct _List_impl : public _Node_alloc_type { __detail::_List_node_header _M_node; _List_impl() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Node_alloc_type>::value) : _Node_alloc_type() { } _List_impl(const _Node_alloc_type& __a) _GLIBCXX_NOEXCEPT : _Node_alloc_type(__a) { } #if __cplusplus >= 201103L _List_impl(_List_impl&&) = default; _List_impl(_Node_alloc_type&& __a, _List_impl&& __x) : _Node_alloc_type(std::move(__a)), _M_node(std::move(__x._M_node)) { } _List_impl(_Node_alloc_type&& __a) noexcept : _Node_alloc_type(std::move(__a)) { } #endif }; _List_impl _M_impl; #if _GLIBCXX_USE_CXX11_ABI size_t _M_get_size() const { return _M_impl._M_node._M_size; } void _M_set_size(size_t __n) { _M_impl._M_node._M_size = __n; } void _M_inc_size(size_t __n) { _M_impl._M_node._M_size += __n; } void _M_dec_size(size_t __n) { _M_impl._M_node._M_size -= __n; } # if !_GLIBCXX_INLINE_VERSION size_t _M_distance(const __detail::_List_node_base* __first, const __detail::_List_node_base* __last) const { return _S_distance(__first, __last); } // return the stored size size_t _M_node_count() const { return _M_get_size(); } # endif #else // dummy implementations used when the size is not stored size_t _M_get_size() const { return 0; } void _M_set_size(size_t) { } void _M_inc_size(size_t) { } void _M_dec_size(size_t) { } # if !_GLIBCXX_INLINE_VERSION size_t _M_distance(const void*, const void*) const { return 0; } // count the number of nodes size_t _M_node_count() const { return _S_distance(_M_impl._M_node._M_next, std::__addressof(_M_impl._M_node)); } # endif #endif typename _Node_alloc_traits::pointer _M_get_node() { return _Node_alloc_traits::allocate(_M_impl, 1); } void _M_put_node(typename _Node_alloc_traits::pointer __p) _GLIBCXX_NOEXCEPT { _Node_alloc_traits::deallocate(_M_impl, __p, 1); } public: typedef _Alloc allocator_type; _Node_alloc_type& _M_get_Node_allocator() _GLIBCXX_NOEXCEPT { return _M_impl; } const _Node_alloc_type& _M_get_Node_allocator() const _GLIBCXX_NOEXCEPT { return _M_impl; } #if __cplusplus >= 201103L _List_base() = default; #else _List_base() { } #endif _List_base(const _Node_alloc_type& __a) _GLIBCXX_NOEXCEPT : _M_impl(__a) { } #if __cplusplus >= 201103L _List_base(_List_base&&) = default; # if !_GLIBCXX_INLINE_VERSION _List_base(_List_base&& __x, _Node_alloc_type&& __a) : _M_impl(std::move(__a)) { if (__x._M_get_Node_allocator() == _M_get_Node_allocator()) _M_move_nodes(std::move(__x)); // else caller must move individual elements. } # endif // Used when allocator is_always_equal. _List_base(_Node_alloc_type&& __a, _List_base&& __x) : _M_impl(std::move(__a), std::move(__x._M_impl)) { } // Used when allocator !is_always_equal. _List_base(_Node_alloc_type&& __a) : _M_impl(std::move(__a)) { } void _M_move_nodes(_List_base&& __x) { _M_impl._M_node._M_move_nodes(std::move(__x._M_impl._M_node)); } #endif // This is what actually destroys the list. ~_List_base() _GLIBCXX_NOEXCEPT { _M_clear(); } void _M_clear() _GLIBCXX_NOEXCEPT; void _M_init() _GLIBCXX_NOEXCEPT { this->_M_impl._M_node._M_init(); } }; /** * @brief A standard container with linear time access to elements, * and fixed time insertion/deletion at any point in the sequence. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * reversible container, and a * sequence, including the * optional sequence requirements with the * %exception of @c at and @c operator[]. * * This is a @e doubly @e linked %list. Traversal up and down the * %list requires linear time, but adding and removing elements (or * @e nodes) is done in constant time, regardless of where the * change takes place. Unlike std::vector and std::deque, * random-access iterators are not provided, so subscripting ( @c * [] ) access is not allowed. For algorithms which only need * sequential access, this lack makes no difference. * * Also unlike the other standard containers, std::list provides * specialized algorithms %unique to linked lists, such as * splicing, sorting, and in-place reversal. * * A couple points on memory allocation for list: * * First, we never actually allocate a Tp, we allocate * List_node's and trust [20.1.5]/4 to DTRT. This is to ensure * that after elements from %list are spliced into * %list, destroying the memory of the second %list is a * valid operation, i.e., Alloc1 giveth and Alloc2 taketh away. * * Second, a %list conceptually represented as * @code * A <---> B <---> C <---> D * @endcode * is actually circular; a link exists between A and D. The %list * class holds (as its only data member) a private list::iterator * pointing to @e D, not to @e A! To get to the head of the %list, * we start at the tail and move forward by one. When this member * iterator's next/previous pointers refer to itself, the %list is * %empty. */ template > class list : protected _List_base<_Tp, _Alloc> { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires2(_Tp, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Tp>::value, "std::list must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::list must have the same value_type as its allocator"); # endif #endif typedef _List_base<_Tp, _Alloc> _Base; typedef typename _Base::_Tp_alloc_type _Tp_alloc_type; typedef typename _Base::_Tp_alloc_traits _Tp_alloc_traits; typedef typename _Base::_Node_alloc_type _Node_alloc_type; typedef typename _Base::_Node_alloc_traits _Node_alloc_traits; public: typedef _Tp value_type; typedef typename _Tp_alloc_traits::pointer pointer; typedef typename _Tp_alloc_traits::const_pointer const_pointer; typedef typename _Tp_alloc_traits::reference reference; typedef typename _Tp_alloc_traits::const_reference const_reference; typedef _List_iterator<_Tp> iterator; typedef _List_const_iterator<_Tp> const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; protected: // Note that pointers-to-_Node's can be ctor-converted to // iterator types. typedef _List_node<_Tp> _Node; using _Base::_M_impl; using _Base::_M_put_node; using _Base::_M_get_node; using _Base::_M_get_Node_allocator; /** * @param __args An instance of user data. * * Allocates space for a new node and constructs a copy of * @a __args in it. */ #if __cplusplus < 201103L _Node* _M_create_node(const value_type& __x) { _Node* __p = this->_M_get_node(); __try { _Tp_alloc_type __alloc(_M_get_Node_allocator()); __alloc.construct(__p->_M_valptr(), __x); } __catch(...) { _M_put_node(__p); __throw_exception_again; } return __p; } #else template _Node* _M_create_node(_Args&&... __args) { auto __p = this->_M_get_node(); auto& __alloc = _M_get_Node_allocator(); __allocated_ptr<_Node_alloc_type> __guard{__alloc, __p}; _Node_alloc_traits::construct(__alloc, __p->_M_valptr(), std::forward<_Args>(__args)...); __guard = nullptr; return __p; } #endif #if _GLIBCXX_USE_CXX11_ABI static size_t _S_distance(const_iterator __first, const_iterator __last) { return std::distance(__first, __last); } // return the stored size size_t _M_node_count() const { return this->_M_get_size(); } #else // dummy implementations used when the size is not stored static size_t _S_distance(const_iterator, const_iterator) { return 0; } // count the number of nodes size_t _M_node_count() const { return std::distance(begin(), end()); } #endif public: // [23.2.2.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Creates a %list with no elements. */ #if __cplusplus >= 201103L list() = default; #else list() { } #endif /** * @brief Creates a %list with no elements. * @param __a An allocator object. */ explicit list(const allocator_type& __a) _GLIBCXX_NOEXCEPT : _Base(_Node_alloc_type(__a)) { } #if __cplusplus >= 201103L /** * @brief Creates a %list with default constructed elements. * @param __n The number of elements to initially create. * @param __a An allocator object. * * This constructor fills the %list with @a __n default * constructed elements. */ explicit list(size_type __n, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_default_initialize(__n); } /** * @brief Creates a %list with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator object. * * This constructor fills the %list with @a __n copies of @a __value. */ list(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_fill_initialize(__n, __value); } #else /** * @brief Creates a %list with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator object. * * This constructor fills the %list with @a __n copies of @a __value. */ explicit list(size_type __n, const value_type& __value = value_type(), const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_fill_initialize(__n, __value); } #endif /** * @brief %List copy constructor. * @param __x A %list of identical element and allocator types. * * The newly-created %list uses a copy of the allocation object used * by @a __x (unless the allocator traits dictate a different object). */ list(const list& __x) : _Base(_Node_alloc_traits:: _S_select_on_copy(__x._M_get_Node_allocator())) { _M_initialize_dispatch(__x.begin(), __x.end(), __false_type()); } #if __cplusplus >= 201103L /** * @brief %List move constructor. * * The newly-created %list contains the exact contents of the moved * instance. The contents of the moved instance are a valid, but * unspecified %list. */ list(list&&) = default; /** * @brief Builds a %list from an initializer_list * @param __l An initializer_list of value_type. * @param __a An allocator object. * * Create a %list consisting of copies of the elements in the * initializer_list @a __l. This is linear in __l.size(). */ list(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_initialize_dispatch(__l.begin(), __l.end(), __false_type()); } list(const list& __x, const allocator_type& __a) : _Base(_Node_alloc_type(__a)) { _M_initialize_dispatch(__x.begin(), __x.end(), __false_type()); } private: list(list&& __x, const allocator_type& __a, true_type) noexcept : _Base(_Node_alloc_type(__a), std::move(__x)) { } list(list&& __x, const allocator_type& __a, false_type) : _Base(_Node_alloc_type(__a)) { if (__x._M_get_Node_allocator() == this->_M_get_Node_allocator()) this->_M_move_nodes(std::move(__x)); else insert(begin(), std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end())); } public: list(list&& __x, const allocator_type& __a) noexcept(_Node_alloc_traits::_S_always_equal()) : list(std::move(__x), __a, typename _Node_alloc_traits::is_always_equal{}) { } #endif /** * @brief Builds a %list from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __a An allocator object. * * Create a %list consisting of copies of the elements from * [@a __first,@a __last). This is linear in N (where N is * distance(@a __first,@a __last)). */ #if __cplusplus >= 201103L template> list(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template list(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(_Node_alloc_type(__a)) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * No explicit dtor needed as the _Base dtor takes care of * things. The _Base dtor only erases the elements, and note * that if the elements themselves are pointers, the pointed-to * memory is not touched in any way. Managing the pointer is * the user's responsibility. */ ~list() = default; #endif /** * @brief %List assignment operator. * @param __x A %list of identical element and allocator types. * * All the elements of @a __x are copied. * * Whether the allocator is copied depends on the allocator traits. */ list& operator=(const list& __x); #if __cplusplus >= 201103L /** * @brief %List move assignment operator. * @param __x A %list of identical element and allocator types. * * The contents of @a __x are moved into this %list (without copying). * * Afterwards @a __x is a valid, but unspecified %list * * Whether the allocator is moved depends on the allocator traits. */ list& operator=(list&& __x) noexcept(_Node_alloc_traits::_S_nothrow_move()) { constexpr bool __move_storage = _Node_alloc_traits::_S_propagate_on_move_assign() || _Node_alloc_traits::_S_always_equal(); _M_move_assign(std::move(__x), __bool_constant<__move_storage>()); return *this; } /** * @brief %List initializer list assignment operator. * @param __l An initializer_list of value_type. * * Replace the contents of the %list with copies of the elements * in the initializer_list @a __l. This is linear in l.size(). */ list& operator=(initializer_list __l) { this->assign(__l.begin(), __l.end()); return *this; } #endif /** * @brief Assigns a given value to a %list. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %list with @a __n copies of the given * value. Note that the assignment completely changes the %list * and that the resulting %list's size is the same as the number * of elements assigned. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %list. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %list with copies of the elements in the * range [@a __first,@a __last). * * Note that the assignment completely changes the %list and * that the resulting %list's size is the same as the number of * elements assigned. */ #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_dispatch(__first, __last, __false_type()); } #else template void assign(_InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * @brief Assigns an initializer_list to a %list. * @param __l An initializer_list of value_type. * * Replace the contents of the %list with copies of the elements * in the initializer_list @a __l. This is linear in __l.size(). */ void assign(initializer_list __l) { this->_M_assign_dispatch(__l.begin(), __l.end(), __false_type()); } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_Base::_M_get_Node_allocator()); } // iterators /** * Returns a read/write iterator that points to the first element in the * %list. Iteration is done in ordinary element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_node._M_next); } /** * Returns a read-only (constant) iterator that points to the * first element in the %list. Iteration is done in ordinary * element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_node._M_next); } /** * Returns a read/write iterator that points one past the last * element in the %list. Iteration is done in ordinary element * order. */ iterator end() _GLIBCXX_NOEXCEPT { return iterator(&this->_M_impl._M_node); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %list. Iteration is done in ordinary * element order. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(&this->_M_impl._M_node); } /** * Returns a read/write reverse iterator that points to the last * element in the %list. Iteration is done in reverse element * order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points to * the last element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %list. Iteration is done in * reverse element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the * first element in the %list. Iteration is done in ordinary * element order. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_impl._M_node._M_next); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %list. Iteration is done in ordinary * element order. */ const_iterator cend() const noexcept { return const_iterator(&this->_M_impl._M_node); } /** * Returns a read-only (constant) reverse iterator that points to * the last element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points to one * before the first element in the %list. Iteration is done in reverse * element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // [23.2.2.2] capacity /** * Returns true if the %list is empty. (Thus begin() would equal * end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_node._M_next == &this->_M_impl._M_node; } /** Returns the number of elements in the %list. */ size_type size() const _GLIBCXX_NOEXCEPT { return _M_node_count(); } /** Returns the size() of the largest possible %list. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Node_alloc_traits::max_size(_M_get_Node_allocator()); } #if __cplusplus >= 201103L /** * @brief Resizes the %list to the specified number of elements. * @param __new_size Number of elements the %list should contain. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise default * constructed elements are appended. */ void resize(size_type __new_size); /** * @brief Resizes the %list to the specified number of elements. * @param __new_size Number of elements the %list should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise the %list is * extended and new elements are populated with given data. */ void resize(size_type __new_size, const value_type& __x); #else /** * @brief Resizes the %list to the specified number of elements. * @param __new_size Number of elements the %list should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %list to the specified number * of elements. If the number is smaller than the %list's * current size the %list is truncated, otherwise the %list is * extended and new elements are populated with given data. */ void resize(size_type __new_size, value_type __x = value_type()); #endif // element access /** * Returns a read/write reference to the data at the first * element of the %list. */ reference front() _GLIBCXX_NOEXCEPT { return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %list. */ const_reference front() const _GLIBCXX_NOEXCEPT { return *begin(); } /** * Returns a read/write reference to the data at the last element * of the %list. */ reference back() _GLIBCXX_NOEXCEPT { iterator __tmp = end(); --__tmp; return *__tmp; } /** * Returns a read-only (constant) reference to the data at the last * element of the %list. */ const_reference back() const _GLIBCXX_NOEXCEPT { const_iterator __tmp = end(); --__tmp; return *__tmp; } // [23.2.2.3] modifiers /** * @brief Add data to the front of the %list. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %list and assigns the given data * to it. Due to the nature of a %list this operation can be * done in constant time, and does not invalidate iterators and * references. */ void push_front(const value_type& __x) { this->_M_insert(begin(), __x); } #if __cplusplus >= 201103L void push_front(value_type&& __x) { this->_M_insert(begin(), std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args) { this->_M_insert(begin(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return front(); #endif } #endif /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %list by * one. Due to the nature of a %list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. * * Note that no data is returned, and if the first element's data * is needed, it should be retrieved before pop_front() is * called. */ void pop_front() _GLIBCXX_NOEXCEPT { this->_M_erase(begin()); } /** * @brief Add data to the end of the %list. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %list and assigns the given data to * it. Due to the nature of a %list this operation can be done * in constant time, and does not invalidate iterators and * references. */ void push_back(const value_type& __x) { this->_M_insert(end(), __x); } #if __cplusplus >= 201103L void push_back(value_type&& __x) { this->_M_insert(end(), std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { this->_M_insert(end(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return back(); #endif } #endif /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %list by * one. Due to the nature of a %list this operation can be done * in constant time, and only invalidates iterators/references to * the element being removed. * * Note that no data is returned, and if the last element's data * is needed, it should be retrieved before pop_back() is called. */ void pop_back() _GLIBCXX_NOEXCEPT { this->_M_erase(iterator(this->_M_impl._M_node._M_prev)); } #if __cplusplus >= 201103L /** * @brief Constructs object in %list before specified iterator. * @param __position A const_iterator into the %list. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) before the specified * location. Due to the nature of a %list this operation can * be done in constant time, and does not invalidate iterators * and references. */ template iterator emplace(const_iterator __position, _Args&&... __args); /** * @brief Inserts given value into %list before specified iterator. * @param __position A const_iterator into the %list. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(const_iterator __position, const value_type& __x); #else /** * @brief Inserts given value into %list before specified iterator. * @param __position An iterator into the %list. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(iterator __position, const value_type& __x); #endif #if __cplusplus >= 201103L /** * @brief Inserts given rvalue into %list before specified iterator. * @param __position A const_iterator into the %list. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given rvalue before * the specified location. Due to the nature of a %list this * operation can be done in constant time, and does not * invalidate iterators and references. */ iterator insert(const_iterator __position, value_type&& __x) { return emplace(__position, std::move(__x)); } /** * @brief Inserts the contents of an initializer_list into %list * before specified const_iterator. * @param __p A const_iterator into the %list. * @param __l An initializer_list of value_type. * @return An iterator pointing to the first element inserted * (or __position). * * This function will insert copies of the data in the * initializer_list @a l into the %list before the location * specified by @a p. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert(const_iterator __p, initializer_list __l) { return this->insert(__p, __l.begin(), __l.end()); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a number of copies of given data into the %list. * @param __position A const_iterator into the %list. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * @return An iterator pointing to the first element inserted * (or __position). * * This function will insert a specified number of copies of the * given data before the location specified by @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ iterator insert(const_iterator __position, size_type __n, const value_type& __x); #else /** * @brief Inserts a number of copies of given data into the %list. * @param __position An iterator into the %list. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * * This function will insert a specified number of copies of the * given data before the location specified by @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ void insert(iterator __position, size_type __n, const value_type& __x) { list __tmp(__n, __x, get_allocator()); splice(__position, __tmp); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a range into the %list. * @param __position A const_iterator into the %list. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator pointing to the first element inserted * (or __position). * * This function will insert copies of the data in the range [@a * first,@a last) into the %list before the location specified by * @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last); #else /** * @brief Inserts a range into the %list. * @param __position An iterator into the %list. * @param __first An input iterator. * @param __last An input iterator. * * This function will insert copies of the data in the range [@a * first,@a last) into the %list before the location specified by * @a position. * * This operation is linear in the number of elements inserted and * does not invalidate iterators and references. */ template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { list __tmp(__first, __last, get_allocator()); splice(__position, __tmp); } #endif /** * @brief Remove element at given position. * @param __position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %list by one. * * Due to the nature of a %list this operation can be done in * constant time, and only invalidates iterators/references to * the element being removed. The user is also cautioned that * this function only erases the element, and that if the element * is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __position) noexcept; #else erase(iterator __position); #endif /** * @brief Remove a range of elements. * @param __first Iterator pointing to the first element to be erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range @a * [first,last) and shorten the %list accordingly. * * This operation is linear time in the size of the range and only * invalidates iterators/references to the element being removed. * The user is also cautioned that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) noexcept #else erase(iterator __first, iterator __last) #endif { while (__first != __last) __first = erase(__first); return __last._M_const_cast(); } /** * @brief Swaps data with another %list. * @param __x A %list of the same element and allocator types. * * This exchanges the elements between two lists in constant * time. Note that the global std::swap() function is * specialized such that std::swap(l1,l2) will feed to this * function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(list& __x) _GLIBCXX_NOEXCEPT { __detail::_List_node_base::swap(this->_M_impl._M_node, __x._M_impl._M_node); size_t __xsize = __x._M_get_size(); __x._M_set_size(this->_M_get_size()); this->_M_set_size(__xsize); _Node_alloc_traits::_S_on_swap(this->_M_get_Node_allocator(), __x._M_get_Node_allocator()); } /** * Erases all the elements. Note that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _Base::_M_clear(); _Base::_M_init(); } // [23.2.2.4] list operations /** * @brief Insert contents of another %list. * @param __position Iterator referencing the element to insert before. * @param __x Source list. * * The elements of @a __x are inserted in constant time in front of * the element referenced by @a __position. @a __x becomes an empty * list. * * Requires this != @a __x. */ void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x) noexcept #else splice(iterator __position, list& __x) #endif { if (!__x.empty()) { _M_check_equal_allocators(__x); this->_M_transfer(__position._M_const_cast(), __x.begin(), __x.end()); this->_M_inc_size(__x._M_get_size()); __x._M_set_size(0); } } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x) noexcept { splice(__position, std::move(__x)); } #endif #if __cplusplus >= 201103L /** * @brief Insert element from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __i Const_iterator referencing the element to move. * * Removes the element in list @a __x referenced by @a __i and * inserts it into the current list before @a __position. */ void splice(const_iterator __position, list&& __x, const_iterator __i) noexcept #else /** * @brief Insert element from another %list. * @param __position Iterator referencing the element to insert before. * @param __x Source list. * @param __i Iterator referencing the element to move. * * Removes the element in list @a __x referenced by @a __i and * inserts it into the current list before @a __position. */ void splice(iterator __position, list& __x, iterator __i) #endif { iterator __j = __i._M_const_cast(); ++__j; if (__position == __i || __position == __j) return; if (this != std::__addressof(__x)) _M_check_equal_allocators(__x); this->_M_transfer(__position._M_const_cast(), __i._M_const_cast(), __j); this->_M_inc_size(1); __x._M_dec_size(1); } #if __cplusplus >= 201103L /** * @brief Insert element from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __i Const_iterator referencing the element to move. * * Removes the element in list @a __x referenced by @a __i and * inserts it into the current list before @a __position. */ void splice(const_iterator __position, list& __x, const_iterator __i) noexcept { splice(__position, std::move(__x), __i); } #endif #if __cplusplus >= 201103L /** * @brief Insert range from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __first Const_iterator referencing the start of range in x. * @param __last Const_iterator referencing the end of range in x. * * Removes elements in the range [__first,__last) and inserts them * before @a __position in constant time. * * Undefined if @a __position is in [__first,__last). */ void splice(const_iterator __position, list&& __x, const_iterator __first, const_iterator __last) noexcept #else /** * @brief Insert range from another %list. * @param __position Iterator referencing the element to insert before. * @param __x Source list. * @param __first Iterator referencing the start of range in x. * @param __last Iterator referencing the end of range in x. * * Removes elements in the range [__first,__last) and inserts them * before @a __position in constant time. * * Undefined if @a __position is in [__first,__last). */ void splice(iterator __position, list& __x, iterator __first, iterator __last) #endif { if (__first != __last) { if (this != std::__addressof(__x)) _M_check_equal_allocators(__x); size_t __n = _S_distance(__first, __last); this->_M_inc_size(__n); __x._M_dec_size(__n); this->_M_transfer(__position._M_const_cast(), __first._M_const_cast(), __last._M_const_cast()); } } #if __cplusplus >= 201103L /** * @brief Insert range from another %list. * @param __position Const_iterator referencing the element to * insert before. * @param __x Source list. * @param __first Const_iterator referencing the start of range in x. * @param __last Const_iterator referencing the end of range in x. * * Removes elements in the range [__first,__last) and inserts them * before @a __position in constant time. * * Undefined if @a __position is in [__first,__last). */ void splice(const_iterator __position, list& __x, const_iterator __first, const_iterator __last) noexcept { splice(__position, std::move(__x), __first, __last); } #endif /** * @brief Remove all elements equal to value. * @param __value The value to remove. * * Removes every element in the list equal to @a value. * Remaining elements stay in list order. Note that this * function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void remove(const _Tp& __value); /** * @brief Remove all elements satisfying a predicate. * @tparam _Predicate Unary predicate function or object. * * Removes every element in the list for which the predicate * returns true. Remaining elements stay in list order. Note * that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ template void remove_if(_Predicate); /** * @brief Remove consecutive duplicate elements. * * For each consecutive set of elements with the same value, * remove all but the first one. Remaining elements stay in * list order. Note that this function only erases the * elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ void unique(); /** * @brief Remove consecutive elements satisfying a predicate. * @tparam _BinaryPredicate Binary predicate function or object. * * For each consecutive set of elements [first,last) that * satisfy predicate(first,i) where i is an iterator in * [first,last), remove all but the first one. Remaining * elements stay in list order. Note that this function only * erases the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ template void unique(_BinaryPredicate); /** * @brief Merge sorted lists. * @param __x Sorted list to merge. * * Assumes that both @a __x and this list are sorted according to * operator<(). Merges elements of @a __x into this list in * sorted order, leaving @a __x empty when complete. Elements in * this list precede elements in @a __x that are equal. */ #if __cplusplus >= 201103L void merge(list&& __x); void merge(list& __x) { merge(std::move(__x)); } #else void merge(list& __x); #endif /** * @brief Merge sorted lists according to comparison function. * @tparam _StrictWeakOrdering Comparison function defining * sort order. * @param __x Sorted list to merge. * @param __comp Comparison functor. * * Assumes that both @a __x and this list are sorted according to * StrictWeakOrdering. Merges elements of @a __x into this list * in sorted order, leaving @a __x empty when complete. Elements * in this list precede elements in @a __x that are equivalent * according to StrictWeakOrdering(). */ #if __cplusplus >= 201103L template void merge(list&& __x, _StrictWeakOrdering __comp); template void merge(list& __x, _StrictWeakOrdering __comp) { merge(std::move(__x), __comp); } #else template void merge(list& __x, _StrictWeakOrdering __comp); #endif /** * @brief Reverse the elements in list. * * Reverse the order of elements in the list in linear time. */ void reverse() _GLIBCXX_NOEXCEPT { this->_M_impl._M_node._M_reverse(); } /** * @brief Sort the elements. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ void sort(); /** * @brief Sort the elements according to comparison function. * * Sorts the elements of this list in NlogN time. Equivalent * elements remain in list order. */ template void sort(_StrictWeakOrdering); protected: // Internal constructor functions follow. // Called by the range constructor to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) { _M_fill_initialize(static_cast(__n), __x); } // Called by the range constructor to implement [23.1.1]/9 template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { for (; __first != __last; ++__first) #if __cplusplus >= 201103L emplace_back(*__first); #else push_back(*__first); #endif } // Called by list(n,v,a), and the range constructor when it turns out // to be the same thing. void _M_fill_initialize(size_type __n, const value_type& __x) { for (; __n; --__n) push_back(__x); } #if __cplusplus >= 201103L // Called by list(n). void _M_default_initialize(size_type __n) { for (; __n; --__n) emplace_back(); } // Called by resize(sz). void _M_default_append(size_type __n); #endif // Internal assign functions follow. // Called by the range assign to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } // Called by the range assign to implement [23.1.1]/9 template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type); // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val); // Moves the elements from [first,last) before position. void _M_transfer(iterator __position, iterator __first, iterator __last) { __position._M_node->_M_transfer(__first._M_node, __last._M_node); } // Inserts new element at position given and with value given. #if __cplusplus < 201103L void _M_insert(iterator __position, const value_type& __x) { _Node* __tmp = _M_create_node(__x); __tmp->_M_hook(__position._M_node); this->_M_inc_size(1); } #else template void _M_insert(iterator __position, _Args&&... __args) { _Node* __tmp = _M_create_node(std::forward<_Args>(__args)...); __tmp->_M_hook(__position._M_node); this->_M_inc_size(1); } #endif // Erases element at position given. void _M_erase(iterator __position) _GLIBCXX_NOEXCEPT { this->_M_dec_size(1); __position._M_node->_M_unhook(); _Node* __n = static_cast<_Node*>(__position._M_node); #if __cplusplus >= 201103L _Node_alloc_traits::destroy(_M_get_Node_allocator(), __n->_M_valptr()); #else _Tp_alloc_type(_M_get_Node_allocator()).destroy(__n->_M_valptr()); #endif _M_put_node(__n); } // To implement the splice (and merge) bits of N1599. void _M_check_equal_allocators(list& __x) _GLIBCXX_NOEXCEPT { if (std::__alloc_neq:: _S_do_it(_M_get_Node_allocator(), __x._M_get_Node_allocator())) __builtin_abort(); } // Used to implement resize. const_iterator _M_resize_pos(size_type& __new_size) const; #if __cplusplus >= 201103L void _M_move_assign(list&& __x, true_type) noexcept { this->_M_clear(); this->_M_move_nodes(std::move(__x)); std::__alloc_on_move(this->_M_get_Node_allocator(), __x._M_get_Node_allocator()); } void _M_move_assign(list&& __x, false_type) { if (__x._M_get_Node_allocator() == this->_M_get_Node_allocator()) _M_move_assign(std::move(__x), true_type{}); else // The rvalue's allocator cannot be moved, or is not equal, // so we need to individually move each element. _M_assign_dispatch(std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end()), __false_type{}); } #endif }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> list<_ValT, _Allocator>; #endif _GLIBCXX_END_NAMESPACE_CXX11 /** * @brief List equality comparison. * @param __x A %list. * @param __y A %list of the same type as @a __x. * @return True iff the size and elements of the lists are equal. * * This is an equivalence relation. It is linear in the size of * the lists. Lists are considered equivalent if their sizes are * equal, and if corresponding elements compare equal. */ template inline bool operator==(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { #if _GLIBCXX_USE_CXX11_ABI if (__x.size() != __y.size()) return false; #endif typedef typename list<_Tp, _Alloc>::const_iterator const_iterator; const_iterator __end1 = __x.end(); const_iterator __end2 = __y.end(); const_iterator __i1 = __x.begin(); const_iterator __i2 = __y.begin(); while (__i1 != __end1 && __i2 != __end2 && *__i1 == *__i2) { ++__i1; ++__i2; } return __i1 == __end1 && __i2 == __end2; } /** * @brief List ordering relation. * @param __x A %list. * @param __y A %list of the same type as @a __x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * lists. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template inline bool operator!=(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const list<_Tp, _Alloc>& __x, const list<_Tp, _Alloc>& __y) { return !(__x < __y); } /// See std::list::swap(). template inline void swap(list<_Tp, _Alloc>& __x, list<_Tp, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if _GLIBCXX_USE_CXX11_ABI // Detect when distance is used to compute the size of the whole list. template inline ptrdiff_t __distance(_GLIBCXX_STD_C::_List_iterator<_Tp> __first, _GLIBCXX_STD_C::_List_iterator<_Tp> __last, input_iterator_tag __tag) { typedef _GLIBCXX_STD_C::_List_const_iterator<_Tp> _CIter; return std::__distance(_CIter(__first), _CIter(__last), __tag); } template inline ptrdiff_t __distance(_GLIBCXX_STD_C::_List_const_iterator<_Tp> __first, _GLIBCXX_STD_C::_List_const_iterator<_Tp> __last, input_iterator_tag) { typedef __detail::_List_node_header _Sentinel; _GLIBCXX_STD_C::_List_const_iterator<_Tp> __beyond = __last; ++__beyond; const bool __whole = __first == __beyond; if (__builtin_constant_p (__whole) && __whole) return static_cast(__last._M_node)->_M_size; ptrdiff_t __n = 0; while (__first != __last) { ++__first; ++__n; } return __n; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_LIST_H */ c++/8/bits/nested_exception.h000064400000011302151027430570011736 0ustar00// Nested Exception support header (nested_exception class) for -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/nested_exception.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{exception} */ #ifndef _GLIBCXX_NESTED_EXCEPTION_H #define _GLIBCXX_NESTED_EXCEPTION_H 1 #pragma GCC visibility push(default) #if __cplusplus < 201103L # include #else #include #include extern "C++" { namespace std { /** * @addtogroup exceptions * @{ */ /// Exception class with exception_ptr data member. class nested_exception { exception_ptr _M_ptr; public: nested_exception() noexcept : _M_ptr(current_exception()) { } nested_exception(const nested_exception&) noexcept = default; nested_exception& operator=(const nested_exception&) noexcept = default; virtual ~nested_exception() noexcept; [[noreturn]] void rethrow_nested() const { if (_M_ptr) rethrow_exception(_M_ptr); std::terminate(); } exception_ptr nested_ptr() const noexcept { return _M_ptr; } }; template struct _Nested_exception : public _Except, public nested_exception { explicit _Nested_exception(const _Except& __ex) : _Except(__ex) { } explicit _Nested_exception(_Except&& __ex) : _Except(static_cast<_Except&&>(__ex)) { } }; // [except.nested]/8 // Throw an exception of unspecified type that is publicly derived from // both remove_reference_t<_Tp> and nested_exception. template [[noreturn]] inline void __throw_with_nested_impl(_Tp&& __t, true_type) { using _Up = typename remove_reference<_Tp>::type; throw _Nested_exception<_Up>{std::forward<_Tp>(__t)}; } template [[noreturn]] inline void __throw_with_nested_impl(_Tp&& __t, false_type) { throw std::forward<_Tp>(__t); } /// If @p __t is derived from nested_exception, throws @p __t. /// Else, throws an implementation-defined object derived from both. template [[noreturn]] inline void throw_with_nested(_Tp&& __t) { using _Up = typename decay<_Tp>::type; using _CopyConstructible = __and_, is_move_constructible<_Up>>; static_assert(_CopyConstructible::value, "throw_with_nested argument must be CopyConstructible"); using __nest = __and_, __bool_constant, __not_>>; std::__throw_with_nested_impl(std::forward<_Tp>(__t), __nest{}); } // Determine if dynamic_cast would be well-formed. template using __rethrow_if_nested_cond = typename enable_if< __and_, __or_<__not_>, is_convertible<_Tp*, nested_exception*>>>::value >::type; // Attempt dynamic_cast to nested_exception and call rethrow_nested(). template inline __rethrow_if_nested_cond<_Ex> __rethrow_if_nested_impl(const _Ex* __ptr) { if (auto __ne_ptr = dynamic_cast(__ptr)) __ne_ptr->rethrow_nested(); } // Otherwise, no effects. inline void __rethrow_if_nested_impl(const void*) { } /// If @p __ex is derived from nested_exception, @p __ex.rethrow_nested(). template inline void rethrow_if_nested(const _Ex& __ex) { std::__rethrow_if_nested_impl(std::__addressof(__ex)); } // @} group exceptions } // namespace std } // extern "C++" #endif // C++11 #pragma GCC visibility pop #endif // _GLIBCXX_NESTED_EXCEPTION_H c++/8/bits/vector.tcc000064400000071714151027430570010237 0ustar00// Vector implementation (out of line) -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/vector.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ #ifndef _VECTOR_TCC #define _VECTOR_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template void vector<_Tp, _Alloc>:: reserve(size_type __n) { if (__n > this->max_size()) __throw_length_error(__N("vector::reserve")); if (this->capacity() < __n) { const size_type __old_size = size(); pointer __tmp = _M_allocate_and_copy(__n, _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(this->_M_impl._M_start), _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(this->_M_impl._M_finish)); _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __tmp; this->_M_impl._M_finish = __tmp + __old_size; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; } } #if __cplusplus >= 201103L template template #if __cplusplus > 201402L typename vector<_Tp, _Alloc>::reference #else void #endif vector<_Tp, _Alloc>:: emplace_back(_Args&&... __args) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else _M_realloc_insert(end(), std::forward<_Args>(__args)...); #if __cplusplus > 201402L return back(); #endif } #endif template typename vector<_Tp, _Alloc>::iterator vector<_Tp, _Alloc>:: #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { const size_type __n = __position - begin(); if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) if (__position == end()) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else { #if __cplusplus >= 201103L const auto __pos = begin() + (__position - cbegin()); // __x could be an existing element of this vector, so make a // copy of it before _M_insert_aux moves elements around. _Temporary_value __x_copy(this, __x); _M_insert_aux(__pos, std::move(__x_copy._M_val())); #else _M_insert_aux(__position, __x); #endif } else #if __cplusplus >= 201103L _M_realloc_insert(begin() + (__position - cbegin()), __x); #else _M_realloc_insert(__position, __x); #endif return iterator(this->_M_impl._M_start + __n); } template typename vector<_Tp, _Alloc>::iterator vector<_Tp, _Alloc>:: _M_erase(iterator __position) { if (__position + 1 != end()) _GLIBCXX_MOVE3(__position + 1, end(), __position); --this->_M_impl._M_finish; _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_finish); _GLIBCXX_ASAN_ANNOTATE_SHRINK(1); return __position; } template typename vector<_Tp, _Alloc>::iterator vector<_Tp, _Alloc>:: _M_erase(iterator __first, iterator __last) { if (__first != __last) { if (__last != end()) _GLIBCXX_MOVE3(__last, end(), __first); _M_erase_at_end(__first.base() + (end() - __last)); } return __first; } template vector<_Tp, _Alloc>& vector<_Tp, _Alloc>:: operator=(const vector<_Tp, _Alloc>& __x) { if (&__x != this) { _GLIBCXX_ASAN_ANNOTATE_REINIT; #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { if (!_Alloc_traits::_S_always_equal() && _M_get_Tp_allocator() != __x._M_get_Tp_allocator()) { // replacement allocator cannot free existing storage this->clear(); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = nullptr; this->_M_impl._M_finish = nullptr; this->_M_impl._M_end_of_storage = nullptr; } std::__alloc_on_copy(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } #endif const size_type __xlen = __x.size(); if (__xlen > capacity()) { pointer __tmp = _M_allocate_and_copy(__xlen, __x.begin(), __x.end()); std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __tmp; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __xlen; } else if (size() >= __xlen) { std::_Destroy(std::copy(__x.begin(), __x.end(), begin()), end(), _M_get_Tp_allocator()); } else { std::copy(__x._M_impl._M_start, __x._M_impl._M_start + size(), this->_M_impl._M_start); std::__uninitialized_copy_a(__x._M_impl._M_start + size(), __x._M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); } this->_M_impl._M_finish = this->_M_impl._M_start + __xlen; } return *this; } template void vector<_Tp, _Alloc>:: _M_fill_assign(size_t __n, const value_type& __val) { if (__n > capacity()) { vector __tmp(__n, __val, _M_get_Tp_allocator()); __tmp._M_impl._M_swap_data(this->_M_impl); } else if (__n > size()) { std::fill(begin(), end(), __val); const size_type __add = __n - size(); _GLIBCXX_ASAN_ANNOTATE_GROW(__add); this->_M_impl._M_finish = std::__uninitialized_fill_n_a(this->_M_impl._M_finish, __add, __val, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__add); } else _M_erase_at_end(std::fill_n(this->_M_impl._M_start, __n, __val)); } template template void vector<_Tp, _Alloc>:: _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { pointer __cur(this->_M_impl._M_start); for (; __first != __last && __cur != this->_M_impl._M_finish; ++__cur, ++__first) *__cur = *__first; if (__first == __last) _M_erase_at_end(__cur); else _M_range_insert(end(), __first, __last, std::__iterator_category(__first)); } template template void vector<_Tp, _Alloc>:: _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __len = std::distance(__first, __last); if (__len > capacity()) { pointer __tmp(_M_allocate_and_copy(__len, __first, __last)); _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __tmp; this->_M_impl._M_finish = this->_M_impl._M_start + __len; this->_M_impl._M_end_of_storage = this->_M_impl._M_finish; } else if (size() >= __len) _M_erase_at_end(std::copy(__first, __last, this->_M_impl._M_start)); else { _ForwardIterator __mid = __first; std::advance(__mid, size()); std::copy(__first, __mid, this->_M_impl._M_start); const size_type __attribute__((__unused__)) __n = __len - size(); _GLIBCXX_ASAN_ANNOTATE_GROW(__n); this->_M_impl._M_finish = std::__uninitialized_copy_a(__mid, __last, this->_M_impl._M_finish, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__n); } } #if __cplusplus >= 201103L template auto vector<_Tp, _Alloc>:: _M_insert_rval(const_iterator __position, value_type&& __v) -> iterator { const auto __n = __position - cbegin(); if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) if (__position == cend()) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::move(__v)); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else _M_insert_aux(begin() + __n, std::move(__v)); else _M_realloc_insert(begin() + __n, std::move(__v)); return iterator(this->_M_impl._M_start + __n); } template template auto vector<_Tp, _Alloc>:: _M_emplace_aux(const_iterator __position, _Args&&... __args) -> iterator { const auto __n = __position - cbegin(); if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) if (__position == cend()) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else { // We need to construct a temporary because something in __args... // could alias one of the elements of the container and so we // need to use it before _M_insert_aux moves elements around. _Temporary_value __tmp(this, std::forward<_Args>(__args)...); _M_insert_aux(begin() + __n, std::move(__tmp._M_val())); } else _M_realloc_insert(begin() + __n, std::forward<_Args>(__args)...); return iterator(this->_M_impl._M_start + __n); } template template void vector<_Tp, _Alloc>:: _M_insert_aux(iterator __position, _Arg&& __arg) #else template void vector<_Tp, _Alloc>:: _M_insert_aux(iterator __position, const _Tp& __x) #endif { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, _GLIBCXX_MOVE(*(this->_M_impl._M_finish - 1))); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); #if __cplusplus < 201103L _Tp __x_copy = __x; #endif _GLIBCXX_MOVE_BACKWARD3(__position.base(), this->_M_impl._M_finish - 2, this->_M_impl._M_finish - 1); #if __cplusplus < 201103L *__position = __x_copy; #else *__position = std::forward<_Arg>(__arg); #endif } #if __cplusplus >= 201103L template template void vector<_Tp, _Alloc>:: _M_realloc_insert(iterator __position, _Args&&... __args) #else template void vector<_Tp, _Alloc>:: _M_realloc_insert(iterator __position, const _Tp& __x) #endif { const size_type __len = _M_check_len(size_type(1), "vector::_M_realloc_insert"); pointer __old_start = this->_M_impl._M_start; pointer __old_finish = this->_M_impl._M_finish; const size_type __elems_before = __position - begin(); pointer __new_start(this->_M_allocate(__len)); pointer __new_finish(__new_start); __try { // The order of the three operations is dictated by the C++11 // case, where the moves could alter a new element belonging // to the existing vector. This is an issue only for callers // taking the element by lvalue ref (see last bullet of C++11 // [res.on.arguments]). _Alloc_traits::construct(this->_M_impl, __new_start + __elems_before, #if __cplusplus >= 201103L std::forward<_Args>(__args)...); #else __x); #endif __new_finish = pointer(); __new_finish = std::__uninitialized_move_if_noexcept_a (__old_start, __position.base(), __new_start, _M_get_Tp_allocator()); ++__new_finish; __new_finish = std::__uninitialized_move_if_noexcept_a (__position.base(), __old_finish, __new_finish, _M_get_Tp_allocator()); } __catch(...) { if (!__new_finish) _Alloc_traits::destroy(this->_M_impl, __new_start + __elems_before); else std::_Destroy(__new_start, __new_finish, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(__old_start, __old_finish, _M_get_Tp_allocator()); _M_deallocate(__old_start, this->_M_impl._M_end_of_storage - __old_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_finish; this->_M_impl._M_end_of_storage = __new_start + __len; } template void vector<_Tp, _Alloc>:: _M_fill_insert(iterator __position, size_type __n, const value_type& __x) { if (__n != 0) { if (size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_finish) >= __n) { #if __cplusplus < 201103L value_type __x_copy = __x; #else _Temporary_value __tmp(this, __x); value_type& __x_copy = __tmp._M_val(); #endif const size_type __elems_after = end() - __position; pointer __old_finish(this->_M_impl._M_finish); if (__elems_after > __n) { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); std::__uninitialized_move_a(this->_M_impl._M_finish - __n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __n; _GLIBCXX_ASAN_ANNOTATE_GREW(__n); _GLIBCXX_MOVE_BACKWARD3(__position.base(), __old_finish - __n, __old_finish); std::fill(__position.base(), __position.base() + __n, __x_copy); } else { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); this->_M_impl._M_finish = std::__uninitialized_fill_n_a(this->_M_impl._M_finish, __n - __elems_after, __x_copy, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__n - __elems_after); std::__uninitialized_move_a(__position.base(), __old_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __elems_after; _GLIBCXX_ASAN_ANNOTATE_GREW(__elems_after); std::fill(__position.base(), __old_finish, __x_copy); } } else { const size_type __len = _M_check_len(__n, "vector::_M_fill_insert"); const size_type __elems_before = __position - begin(); pointer __new_start(this->_M_allocate(__len)); pointer __new_finish(__new_start); __try { // See _M_realloc_insert above. std::__uninitialized_fill_n_a(__new_start + __elems_before, __n, __x, _M_get_Tp_allocator()); __new_finish = pointer(); __new_finish = std::__uninitialized_move_if_noexcept_a (this->_M_impl._M_start, __position.base(), __new_start, _M_get_Tp_allocator()); __new_finish += __n; __new_finish = std::__uninitialized_move_if_noexcept_a (__position.base(), this->_M_impl._M_finish, __new_finish, _M_get_Tp_allocator()); } __catch(...) { if (!__new_finish) std::_Destroy(__new_start + __elems_before, __new_start + __elems_before + __n, _M_get_Tp_allocator()); else std::_Destroy(__new_start, __new_finish, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_finish; this->_M_impl._M_end_of_storage = __new_start + __len; } } } #if __cplusplus >= 201103L template void vector<_Tp, _Alloc>:: _M_default_append(size_type __n) { if (__n != 0) { const size_type __size = size(); size_type __navail = size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_finish); if (__size > max_size() || __navail > max_size() - __size) __builtin_unreachable(); if (__navail >= __n) { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); this->_M_impl._M_finish = std::__uninitialized_default_n_a(this->_M_impl._M_finish, __n, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_GREW(__n); } else { const size_type __len = _M_check_len(__n, "vector::_M_default_append"); pointer __new_start(this->_M_allocate(__len)); pointer __destroy_from = pointer(); __try { std::__uninitialized_default_n_a(__new_start + __size, __n, _M_get_Tp_allocator()); __destroy_from = __new_start + __size; std::__uninitialized_move_if_noexcept_a( this->_M_impl._M_start, this->_M_impl._M_finish, __new_start, _M_get_Tp_allocator()); } __catch(...) { if (__destroy_from) std::_Destroy(__destroy_from, __destroy_from + __n, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_start + __size + __n; this->_M_impl._M_end_of_storage = __new_start + __len; } } } template bool vector<_Tp, _Alloc>:: _M_shrink_to_fit() { if (capacity() == size()) return false; _GLIBCXX_ASAN_ANNOTATE_REINIT; return std::__shrink_to_fit_aux::_S_do_it(*this); } #endif template template void vector<_Tp, _Alloc>:: _M_range_insert(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag) { if (__pos == end()) { for (; __first != __last; ++__first) insert(end(), *__first); } else if (__first != __last) { vector __tmp(__first, __last, _M_get_Tp_allocator()); insert(__pos, _GLIBCXX_MAKE_MOVE_ITERATOR(__tmp.begin()), _GLIBCXX_MAKE_MOVE_ITERATOR(__tmp.end())); } } template template void vector<_Tp, _Alloc>:: _M_range_insert(iterator __position, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { if (__first != __last) { const size_type __n = std::distance(__first, __last); if (size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_finish) >= __n) { const size_type __elems_after = end() - __position; pointer __old_finish(this->_M_impl._M_finish); if (__elems_after > __n) { _GLIBCXX_ASAN_ANNOTATE_GROW(__n); std::__uninitialized_move_a(this->_M_impl._M_finish - __n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __n; _GLIBCXX_ASAN_ANNOTATE_GREW(__n); _GLIBCXX_MOVE_BACKWARD3(__position.base(), __old_finish - __n, __old_finish); std::copy(__first, __last, __position); } else { _ForwardIterator __mid = __first; std::advance(__mid, __elems_after); _GLIBCXX_ASAN_ANNOTATE_GROW(__n); std::__uninitialized_copy_a(__mid, __last, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __n - __elems_after; _GLIBCXX_ASAN_ANNOTATE_GREW(__n - __elems_after); std::__uninitialized_move_a(__position.base(), __old_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish += __elems_after; _GLIBCXX_ASAN_ANNOTATE_GREW(__elems_after); std::copy(__first, __mid, __position); } } else { const size_type __len = _M_check_len(__n, "vector::_M_range_insert"); pointer __new_start(this->_M_allocate(__len)); pointer __new_finish(__new_start); __try { __new_finish = std::__uninitialized_move_if_noexcept_a (this->_M_impl._M_start, __position.base(), __new_start, _M_get_Tp_allocator()); __new_finish = std::__uninitialized_copy_a(__first, __last, __new_finish, _M_get_Tp_allocator()); __new_finish = std::__uninitialized_move_if_noexcept_a (__position.base(), this->_M_impl._M_finish, __new_finish, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(__new_start, __new_finish, _M_get_Tp_allocator()); _M_deallocate(__new_start, __len); __throw_exception_again; } _GLIBCXX_ASAN_ANNOTATE_REINIT; std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _M_deallocate(this->_M_impl._M_start, this->_M_impl._M_end_of_storage - this->_M_impl._M_start); this->_M_impl._M_start = __new_start; this->_M_impl._M_finish = __new_finish; this->_M_impl._M_end_of_storage = __new_start + __len; } } } // vector template void vector:: _M_reallocate(size_type __n) { _Bit_pointer __q = this->_M_allocate(__n); iterator __start(std::__addressof(*__q), 0); iterator __finish(_M_copy_aligned(begin(), end(), __start)); this->_M_deallocate(); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; this->_M_impl._M_end_of_storage = __q + _S_nword(__n); } template void vector:: _M_fill_insert(iterator __position, size_type __n, bool __x) { if (__n == 0) return; if (capacity() - size() >= __n) { std::copy_backward(__position, end(), this->_M_impl._M_finish + difference_type(__n)); std::fill(__position, __position + difference_type(__n), __x); this->_M_impl._M_finish += difference_type(__n); } else { const size_type __len = _M_check_len(__n, "vector::_M_fill_insert"); _Bit_pointer __q = this->_M_allocate(__len); iterator __start(std::__addressof(*__q), 0); iterator __i = _M_copy_aligned(begin(), __position, __start); std::fill(__i, __i + difference_type(__n), __x); iterator __finish = std::copy(__position, end(), __i + difference_type(__n)); this->_M_deallocate(); this->_M_impl._M_end_of_storage = __q + _S_nword(__len); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; } } template template void vector:: _M_insert_range(iterator __position, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { if (__first != __last) { size_type __n = std::distance(__first, __last); if (capacity() - size() >= __n) { std::copy_backward(__position, end(), this->_M_impl._M_finish + difference_type(__n)); std::copy(__first, __last, __position); this->_M_impl._M_finish += difference_type(__n); } else { const size_type __len = _M_check_len(__n, "vector::_M_insert_range"); _Bit_pointer __q = this->_M_allocate(__len); iterator __start(std::__addressof(*__q), 0); iterator __i = _M_copy_aligned(begin(), __position, __start); __i = std::copy(__first, __last, __i); iterator __finish = std::copy(__position, end(), __i); this->_M_deallocate(); this->_M_impl._M_end_of_storage = __q + _S_nword(__len); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; } } } template void vector:: _M_insert_aux(iterator __position, bool __x) { if (this->_M_impl._M_finish._M_p != this->_M_impl._M_end_addr()) { std::copy_backward(__position, this->_M_impl._M_finish, this->_M_impl._M_finish + 1); *__position = __x; ++this->_M_impl._M_finish; } else { const size_type __len = _M_check_len(size_type(1), "vector::_M_insert_aux"); _Bit_pointer __q = this->_M_allocate(__len); iterator __start(std::__addressof(*__q), 0); iterator __i = _M_copy_aligned(begin(), __position, __start); *__i++ = __x; iterator __finish = std::copy(__position, end(), __i); this->_M_deallocate(); this->_M_impl._M_end_of_storage = __q + _S_nword(__len); this->_M_impl._M_start = __start; this->_M_impl._M_finish = __finish; } } template typename vector::iterator vector:: _M_erase(iterator __position) { if (__position + 1 != end()) std::copy(__position + 1, end(), __position); --this->_M_impl._M_finish; return __position; } template typename vector::iterator vector:: _M_erase(iterator __first, iterator __last) { if (__first != __last) _M_erase_at_end(std::copy(__last, end(), __first)); return __first; } #if __cplusplus >= 201103L template bool vector:: _M_shrink_to_fit() { if (capacity() - size() < int(_S_word_bit)) return false; __try { _M_reallocate(size()); return true; } __catch(...) { return false; } } #endif _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template size_t hash<_GLIBCXX_STD_C::vector>:: operator()(const _GLIBCXX_STD_C::vector& __b) const noexcept { size_t __hash = 0; using _GLIBCXX_STD_C::_S_word_bit; using _GLIBCXX_STD_C::_Bit_type; const size_t __words = __b.size() / _S_word_bit; if (__words) { const size_t __clength = __words * sizeof(_Bit_type); __hash = std::_Hash_impl::hash(__b._M_impl._M_start._M_p, __clength); } const size_t __extrabits = __b.size() % _S_word_bit; if (__extrabits) { _Bit_type __hiword = *__b._M_impl._M_finish._M_p; __hiword &= ~((~static_cast<_Bit_type>(0)) << __extrabits); const size_t __clength = (__extrabits + __CHAR_BIT__ - 1) / __CHAR_BIT__; if (__words) __hash = std::_Hash_impl::hash(&__hiword, __clength, __hash); else __hash = std::_Hash_impl::hash(&__hiword, __clength); } return __hash; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #undef _GLIBCXX_ASAN_ANNOTATE_REINIT #undef _GLIBCXX_ASAN_ANNOTATE_GROW #undef _GLIBCXX_ASAN_ANNOTATE_GREW #undef _GLIBCXX_ASAN_ANNOTATE_SHRINK #endif /* _VECTOR_TCC */ c++/8/bits/fs_fwd.h000064400000024047151027430570007660 0ustar00// Filesystem declarations -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_FWD_H #define _GLIBCXX_FS_FWD_H 1 #if __cplusplus >= 201703L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { #if _GLIBCXX_USE_CXX11_ABI inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } #endif /** * @defgroup filesystem Filesystem * * Utilities for performing operations on file systems and their components, * such as paths, regular files, and directories. * * @{ */ class file_status; _GLIBCXX_BEGIN_NAMESPACE_CXX11 class path; class filesystem_error; class directory_entry; class directory_iterator; class recursive_directory_iterator; _GLIBCXX_END_NAMESPACE_CXX11 struct space_info { uintmax_t capacity; uintmax_t free; uintmax_t available; }; enum class file_type : signed char { none = 0, not_found = -1, regular = 1, directory = 2, symlink = 3, block = 4, character = 5, fifo = 6, socket = 7, unknown = 8 }; /// Bitmask type enum class copy_options : unsigned short { none = 0, skip_existing = 1, overwrite_existing = 2, update_existing = 4, recursive = 8, copy_symlinks = 16, skip_symlinks = 32, directories_only = 64, create_symlinks = 128, create_hard_links = 256 }; constexpr copy_options operator&(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr copy_options operator|(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr copy_options operator^(copy_options __x, copy_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr copy_options operator~(copy_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline copy_options& operator&=(copy_options& __x, copy_options __y) noexcept { return __x = __x & __y; } inline copy_options& operator|=(copy_options& __x, copy_options __y) noexcept { return __x = __x | __y; } inline copy_options& operator^=(copy_options& __x, copy_options __y) noexcept { return __x = __x ^ __y; } /// Bitmask type enum class perms : unsigned { none = 0, owner_read = 0400, owner_write = 0200, owner_exec = 0100, owner_all = 0700, group_read = 040, group_write = 020, group_exec = 010, group_all = 070, others_read = 04, others_write = 02, others_exec = 01, others_all = 07, all = 0777, set_uid = 04000, set_gid = 02000, sticky_bit = 01000, mask = 07777, unknown = 0xFFFF, }; constexpr perms operator&(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr perms operator|(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr perms operator^(perms __x, perms __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr perms operator~(perms __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline perms& operator&=(perms& __x, perms __y) noexcept { return __x = __x & __y; } inline perms& operator|=(perms& __x, perms __y) noexcept { return __x = __x | __y; } inline perms& operator^=(perms& __x, perms __y) noexcept { return __x = __x ^ __y; } /// Bitmask type enum class perm_options : unsigned { replace = 0x1, add = 0x2, remove = 0x4, nofollow = 0x8 }; constexpr perm_options operator&(perm_options __x, perm_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr perm_options operator|(perm_options __x, perm_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr perm_options operator^(perm_options __x, perm_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr perm_options operator~(perm_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline perm_options& operator&=(perm_options& __x, perm_options __y) noexcept { return __x = __x & __y; } inline perm_options& operator|=(perm_options& __x, perm_options __y) noexcept { return __x = __x | __y; } inline perm_options& operator^=(perm_options& __x, perm_options __y) noexcept { return __x = __x ^ __y; } // Bitmask type enum class directory_options : unsigned char { none = 0, follow_directory_symlink = 1, skip_permission_denied = 2 }; constexpr directory_options operator&(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) & static_cast<__utype>(__y)); } constexpr directory_options operator|(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) | static_cast<__utype>(__y)); } constexpr directory_options operator^(directory_options __x, directory_options __y) noexcept { using __utype = typename std::underlying_type::type; return static_cast( static_cast<__utype>(__x) ^ static_cast<__utype>(__y)); } constexpr directory_options operator~(directory_options __x) noexcept { using __utype = typename std::underlying_type::type; return static_cast(~static_cast<__utype>(__x)); } inline directory_options& operator&=(directory_options& __x, directory_options __y) noexcept { return __x = __x & __y; } inline directory_options& operator|=(directory_options& __x, directory_options __y) noexcept { return __x = __x | __y; } inline directory_options& operator^=(directory_options& __x, directory_options __y) noexcept { return __x = __x ^ __y; } using file_time_type = std::chrono::system_clock::time_point; // operational functions void copy(const path& __from, const path& __to, copy_options __options); void copy(const path& __from, const path& __to, copy_options __options, error_code&); bool copy_file(const path& __from, const path& __to, copy_options __option); bool copy_file(const path& __from, const path& __to, copy_options __option, error_code&); path current_path(); bool exists(file_status) noexcept; bool is_other(file_status) noexcept; uintmax_t file_size(const path&); uintmax_t file_size(const path&, error_code&) noexcept; uintmax_t hard_link_count(const path&); uintmax_t hard_link_count(const path&, error_code&) noexcept; file_time_type last_write_time(const path&); file_time_type last_write_time(const path&, error_code&) noexcept; void permissions(const path&, perms, perm_options, error_code&) noexcept; path proximate(const path& __p, const path& __base, error_code& __ec); path proximate(const path& __p, const path& __base, error_code& __ec); path relative(const path& __p, const path& __base, error_code& __ec); file_status status(const path&); file_status status(const path&, error_code&) noexcept; bool status_known(file_status) noexcept; file_status symlink_status(const path&); file_status symlink_status(const path&, error_code&) noexcept; bool is_regular_file(file_status) noexcept; bool is_symlink(file_status) noexcept; // @} group filesystem } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_FWD_H c++/8/bits/valarray_after.h000064400000054177151027430570011421 0ustar00// The template and inlines for the -*- C++ -*- internal _Meta class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_after.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_AFTER_H #define _VALARRAY_AFTER_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // // gslice_array closure. // template class _GBase { public: typedef typename _Dom::value_type value_type; _GBase (const _Dom& __e, const valarray& __i) : _M_expr (__e), _M_index(__i) {} value_type operator[] (size_t __i) const { return _M_expr[_M_index[__i]]; } size_t size () const { return _M_index.size(); } private: const _Dom& _M_expr; const valarray& _M_index; }; template class _GBase<_Array<_Tp> > { public: typedef _Tp value_type; _GBase (_Array<_Tp> __a, const valarray& __i) : _M_array (__a), _M_index(__i) {} value_type operator[] (size_t __i) const { return _M_array._M_data[_M_index[__i]]; } size_t size () const { return _M_index.size(); } private: const _Array<_Tp> _M_array; const valarray& _M_index; }; template struct _GClos<_Expr, _Dom> : _GBase<_Dom> { typedef _GBase<_Dom> _Base; typedef typename _Base::value_type value_type; _GClos (const _Dom& __e, const valarray& __i) : _Base (__e, __i) {} }; template struct _GClos<_ValArray, _Tp> : _GBase<_Array<_Tp> > { typedef _GBase<_Array<_Tp> > _Base; typedef typename _Base::value_type value_type; _GClos (_Array<_Tp> __a, const valarray& __i) : _Base (__a, __i) {} }; // // indirect_array closure // template class _IBase { public: typedef typename _Dom::value_type value_type; _IBase (const _Dom& __e, const valarray& __i) : _M_expr (__e), _M_index (__i) {} value_type operator[] (size_t __i) const { return _M_expr[_M_index[__i]]; } size_t size() const { return _M_index.size(); } private: const _Dom& _M_expr; const valarray& _M_index; }; template struct _IClos<_Expr, _Dom> : _IBase<_Dom> { typedef _IBase<_Dom> _Base; typedef typename _Base::value_type value_type; _IClos (const _Dom& __e, const valarray& __i) : _Base (__e, __i) {} }; template struct _IClos<_ValArray, _Tp> : _IBase > { typedef _IBase > _Base; typedef _Tp value_type; _IClos (const valarray<_Tp>& __a, const valarray& __i) : _Base (__a, __i) {} }; // // class _Expr // template class _Expr { public: typedef _Tp value_type; _Expr(const _Clos&); const _Clos& operator()() const; value_type operator[](size_t) const; valarray operator[](slice) const; valarray operator[](const gslice&) const; valarray operator[](const valarray&) const; valarray operator[](const valarray&) const; _Expr<_UnClos<__unary_plus, std::_Expr, _Clos>, value_type> operator+() const; _Expr<_UnClos<__negate, std::_Expr, _Clos>, value_type> operator-() const; _Expr<_UnClos<__bitwise_not, std::_Expr, _Clos>, value_type> operator~() const; _Expr<_UnClos<__logical_not, std::_Expr, _Clos>, bool> operator!() const; size_t size() const; value_type sum() const; valarray shift(int) const; valarray cshift(int) const; value_type min() const; value_type max() const; valarray apply(value_type (*)(const value_type&)) const; valarray apply(value_type (*)(value_type)) const; private: const _Clos _M_closure; }; template inline _Expr<_Clos, _Tp>::_Expr(const _Clos& __c) : _M_closure(__c) {} template inline const _Clos& _Expr<_Clos, _Tp>::operator()() const { return _M_closure; } template inline _Tp _Expr<_Clos, _Tp>::operator[](size_t __i) const { return _M_closure[__i]; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](slice __s) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__s]; return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](const gslice& __gs) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__gs]; return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](const valarray& __m) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__m]; return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::operator[](const valarray& __i) const { valarray<_Tp> __v = valarray<_Tp>(*this)[__i]; return __v; } template inline size_t _Expr<_Clos, _Tp>::size() const { return _M_closure.size(); } template inline valarray<_Tp> _Expr<_Clos, _Tp>::shift(int __n) const { valarray<_Tp> __v = valarray<_Tp>(*this).shift(__n); return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::cshift(int __n) const { valarray<_Tp> __v = valarray<_Tp>(*this).cshift(__n); return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::apply(_Tp __f(const _Tp&)) const { valarray<_Tp> __v = valarray<_Tp>(*this).apply(__f); return __v; } template inline valarray<_Tp> _Expr<_Clos, _Tp>::apply(_Tp __f(_Tp)) const { valarray<_Tp> __v = valarray<_Tp>(*this).apply(__f); return __v; } // XXX: replace this with a more robust summation algorithm. template inline _Tp _Expr<_Clos, _Tp>::sum() const { size_t __n = _M_closure.size(); if (__n == 0) return _Tp(); else { _Tp __s = _M_closure[--__n]; while (__n != 0) __s += _M_closure[--__n]; return __s; } } template inline _Tp _Expr<_Clos, _Tp>::min() const { return __valarray_min(_M_closure); } template inline _Tp _Expr<_Clos, _Tp>::max() const { return __valarray_max(_M_closure); } template inline _Expr<_UnClos<__logical_not, _Expr, _Dom>, bool> _Expr<_Dom, _Tp>::operator!() const { typedef _UnClos<__logical_not, std::_Expr, _Dom> _Closure; return _Expr<_Closure, bool>(_Closure(this->_M_closure)); } #define _DEFINE_EXPR_UNARY_OPERATOR(_Op, _Name) \ template \ inline _Expr<_UnClos<_Name, std::_Expr, _Dom>, _Tp> \ _Expr<_Dom, _Tp>::operator _Op() const \ { \ typedef _UnClos<_Name, std::_Expr, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(this->_M_closure)); \ } _DEFINE_EXPR_UNARY_OPERATOR(+, __unary_plus) _DEFINE_EXPR_UNARY_OPERATOR(-, __negate) _DEFINE_EXPR_UNARY_OPERATOR(~, __bitwise_not) #undef _DEFINE_EXPR_UNARY_OPERATOR #define _DEFINE_EXPR_BINARY_OPERATOR(_Op, _Name) \ template \ inline _Expr<_BinClos<_Name, _Expr, _Expr, _Dom1, _Dom2>, \ typename __fun<_Name, typename _Dom1::value_type>::result_type> \ operator _Op(const _Expr<_Dom1, typename _Dom1::value_type>& __v, \ const _Expr<_Dom2, typename _Dom2::value_type>& __w) \ { \ typedef typename _Dom1::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Expr, _Expr, _Dom1, _Dom2> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__v(), __w())); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Expr, _Constant, _Dom, \ typename _Dom::value_type>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const _Expr<_Dom, typename _Dom::value_type>& __v, \ const typename _Dom::value_type& __t) \ { \ typedef typename _Dom::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Expr, _Constant, _Dom, _Arg> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__v(), __t)); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Constant, _Expr, \ typename _Dom::value_type, _Dom>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const typename _Dom::value_type& __t, \ const _Expr<_Dom, typename _Dom::value_type>& __v) \ { \ typedef typename _Dom::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Constant, _Expr, _Arg, _Dom> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__t, __v())); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Expr, _ValArray, \ _Dom, typename _Dom::value_type>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const _Expr<_Dom,typename _Dom::value_type>& __e, \ const valarray& __v) \ { \ typedef typename _Dom::value_type _Arg; \ typedef typename __fun<_Name, _Arg>::result_type _Value; \ typedef _BinClos<_Name, _Expr, _ValArray, _Dom, _Arg> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__e(), __v)); \ } \ \ template \ inline _Expr<_BinClos<_Name, _ValArray, _Expr, \ typename _Dom::value_type, _Dom>, \ typename __fun<_Name, typename _Dom::value_type>::result_type> \ operator _Op(const valarray& __v, \ const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef typename __fun<_Name, _Tp>::result_type _Value; \ typedef _BinClos<_Name, _ValArray, _Expr, _Tp, _Dom> _Closure; \ return _Expr<_Closure, _Value>(_Closure(__v, __e ())); \ } _DEFINE_EXPR_BINARY_OPERATOR(+, __plus) _DEFINE_EXPR_BINARY_OPERATOR(-, __minus) _DEFINE_EXPR_BINARY_OPERATOR(*, __multiplies) _DEFINE_EXPR_BINARY_OPERATOR(/, __divides) _DEFINE_EXPR_BINARY_OPERATOR(%, __modulus) _DEFINE_EXPR_BINARY_OPERATOR(^, __bitwise_xor) _DEFINE_EXPR_BINARY_OPERATOR(&, __bitwise_and) _DEFINE_EXPR_BINARY_OPERATOR(|, __bitwise_or) _DEFINE_EXPR_BINARY_OPERATOR(<<, __shift_left) _DEFINE_EXPR_BINARY_OPERATOR(>>, __shift_right) _DEFINE_EXPR_BINARY_OPERATOR(&&, __logical_and) _DEFINE_EXPR_BINARY_OPERATOR(||, __logical_or) _DEFINE_EXPR_BINARY_OPERATOR(==, __equal_to) _DEFINE_EXPR_BINARY_OPERATOR(!=, __not_equal_to) _DEFINE_EXPR_BINARY_OPERATOR(<, __less) _DEFINE_EXPR_BINARY_OPERATOR(>, __greater) _DEFINE_EXPR_BINARY_OPERATOR(<=, __less_equal) _DEFINE_EXPR_BINARY_OPERATOR(>=, __greater_equal) #undef _DEFINE_EXPR_BINARY_OPERATOR #define _DEFINE_EXPR_UNARY_FUNCTION(_Name, _UName) \ template \ inline _Expr<_UnClos<_UName, _Expr, _Dom>, \ typename _Dom::value_type> \ _Name(const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _UnClos<_UName, _Expr, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e())); \ } \ \ template \ inline _Expr<_UnClos<_UName, _ValArray, _Tp>, _Tp> \ _Name(const valarray<_Tp>& __v) \ { \ typedef _UnClos<_UName, _ValArray, _Tp> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__v)); \ } _DEFINE_EXPR_UNARY_FUNCTION(abs, _Abs) _DEFINE_EXPR_UNARY_FUNCTION(cos, _Cos) _DEFINE_EXPR_UNARY_FUNCTION(acos, _Acos) _DEFINE_EXPR_UNARY_FUNCTION(cosh, _Cosh) _DEFINE_EXPR_UNARY_FUNCTION(sin, _Sin) _DEFINE_EXPR_UNARY_FUNCTION(asin, _Asin) _DEFINE_EXPR_UNARY_FUNCTION(sinh, _Sinh) _DEFINE_EXPR_UNARY_FUNCTION(tan, _Tan) _DEFINE_EXPR_UNARY_FUNCTION(tanh, _Tanh) _DEFINE_EXPR_UNARY_FUNCTION(atan, _Atan) _DEFINE_EXPR_UNARY_FUNCTION(exp, _Exp) _DEFINE_EXPR_UNARY_FUNCTION(log, _Log) _DEFINE_EXPR_UNARY_FUNCTION(log10, _Log10) _DEFINE_EXPR_UNARY_FUNCTION(sqrt, _Sqrt) #undef _DEFINE_EXPR_UNARY_FUNCTION #define _DEFINE_EXPR_BINARY_FUNCTION(_Fun, _UFun) \ template \ inline _Expr<_BinClos<_UFun, _Expr, _Expr, _Dom1, _Dom2>, \ typename _Dom1::value_type> \ _Fun(const _Expr<_Dom1, typename _Dom1::value_type>& __e1, \ const _Expr<_Dom2, typename _Dom2::value_type>& __e2) \ { \ typedef typename _Dom1::value_type _Tp; \ typedef _BinClos<_UFun, _Expr, _Expr, _Dom1, _Dom2> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e1(), __e2())); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Expr, _ValArray, _Dom, \ typename _Dom::value_type>, \ typename _Dom::value_type> \ _Fun(const _Expr<_Dom, typename _Dom::value_type>& __e, \ const valarray& __v) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _Expr, _ValArray, _Dom, _Tp> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e(), __v)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _ValArray, _Expr, \ typename _Dom::value_type, _Dom>, \ typename _Dom::value_type> \ _Fun(const valarray& __v, \ const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _ValArray, _Expr, _Tp, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__v, __e())); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Expr, _Constant, _Dom, \ typename _Dom::value_type>, \ typename _Dom::value_type> \ _Fun(const _Expr<_Dom, typename _Dom::value_type>& __e, \ const typename _Dom::value_type& __t) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _Expr, _Constant, _Dom, _Tp> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__e(), __t)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Constant, _Expr, \ typename _Dom::value_type, _Dom>, \ typename _Dom::value_type> \ _Fun(const typename _Dom::value_type& __t, \ const _Expr<_Dom, typename _Dom::value_type>& __e) \ { \ typedef typename _Dom::value_type _Tp; \ typedef _BinClos<_UFun, _Constant, _Expr, _Tp, _Dom> _Closure; \ return _Expr<_Closure, _Tp>(_Closure(__t, __e())); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _ValArray, _ValArray, _Tp, _Tp>, _Tp> \ _Fun(const valarray<_Tp>& __v, const valarray<_Tp>& __w) \ { \ typedef _BinClos<_UFun, _ValArray, _ValArray, _Tp, _Tp> _Closure;\ return _Expr<_Closure, _Tp>(_Closure(__v, __w)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _ValArray, _Constant, _Tp, _Tp>, _Tp> \ _Fun(const valarray<_Tp>& __v, const _Tp& __t) \ { \ typedef _BinClos<_UFun, _ValArray, _Constant, _Tp, _Tp> _Closure;\ return _Expr<_Closure, _Tp>(_Closure(__v, __t)); \ } \ \ template \ inline _Expr<_BinClos<_UFun, _Constant, _ValArray, _Tp, _Tp>, _Tp> \ _Fun(const _Tp& __t, const valarray<_Tp>& __v) \ { \ typedef _BinClos<_UFun, _Constant, _ValArray, _Tp, _Tp> _Closure;\ return _Expr<_Closure, _Tp>(_Closure(__t, __v)); \ } _DEFINE_EXPR_BINARY_FUNCTION(atan2, _Atan2) _DEFINE_EXPR_BINARY_FUNCTION(pow, _Pow) #undef _DEFINE_EXPR_BINARY_FUNCTION _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _CPP_VALARRAY_AFTER_H */ c++/8/bits/valarray_array.tcc000064400000016126151027430570011750 0ustar00// The template and inlines for the -*- C++ -*- internal _Array helper class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_array.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_ARRAY_TCC #define _VALARRAY_ARRAY_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template void __valarray_fill(_Array<_Tp> __a, size_t __n, _Array __m, const _Tp& __t) { _Tp* __p = __a._M_data; bool* __ok (__m._M_data); for (size_t __i=0; __i < __n; ++__i, ++__ok, ++__p) { while (!*__ok) { ++__ok; ++__p; } *__p = __t; } } // Copy n elements of a into consecutive elements of b. When m is // false, the corresponding element of a is skipped. m must contain // at least n true elements. a must contain at least n elements and // enough elements to match up with m through the nth true element // of m. I.e. if n is 10, m has 15 elements with 5 false followed // by 10 true, a must have 15 elements. template void __valarray_copy(_Array<_Tp> __a, _Array __m, _Array<_Tp> __b, size_t __n) { _Tp* __p (__a._M_data); bool* __ok (__m._M_data); for (_Tp* __q = __b._M_data; __q < __b._M_data + __n; ++__q, ++__ok, ++__p) { while (! *__ok) { ++__ok; ++__p; } *__q = *__p; } } // Copy n consecutive elements from a into elements of b. Elements // of b are skipped if the corresponding element of m is false. m // must contain at least n true elements. b must have at least as // many elements as the index of the nth true element of m. I.e. if // m has 15 elements with 5 false followed by 10 true, b must have // at least 15 elements. template void __valarray_copy(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b, _Array __m) { _Tp* __q (__b._M_data); bool* __ok (__m._M_data); for (_Tp* __p = __a._M_data; __p < __a._M_data+__n; ++__p, ++__ok, ++__q) { while (! *__ok) { ++__ok; ++__q; } *__q = *__p; } } // Copy n elements from a into elements of b. Elements of a are // skipped if the corresponding element of m is false. Elements of // b are skipped if the corresponding element of k is false. m and // k must contain at least n true elements. a and b must have at // least as many elements as the index of the nth true element of m. template void __valarray_copy(_Array<_Tp> __a, _Array __m, size_t __n, _Array<_Tp> __b, _Array __k) { _Tp* __p (__a._M_data); _Tp* __q (__b._M_data); bool* __srcok (__m._M_data); bool* __dstok (__k._M_data); for (size_t __i = 0; __i < __n; ++__srcok, ++__p, ++__dstok, ++__q, ++__i) { while (! *__srcok) { ++__srcok; ++__p; } while (! *__dstok) { ++__dstok; ++__q; } *__q = *__p; } } // Copy n consecutive elements of e into consecutive elements of a. // I.e. a[i] = e[i]. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a) { _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, ++__p) *__p = __e[__i]; } // Copy n consecutive elements of e into elements of a using stride // s. I.e., a[0] = e[0], a[s] = e[1], a[2*s] = e[2]. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a, size_t __s) { _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, __p += __s) *__p = __e[__i]; } // Copy n consecutive elements of e into elements of a indexed by // contents of i. I.e., a[i[0]] = e[0]. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a, _Array __i) { size_t* __j (__i._M_data); for (size_t __k = 0; __k < __n; ++__k, ++__j) __a._M_data[*__j] = __e[__k]; } // Copy n elements of e indexed by contents of f into elements of a // indexed by contents of i. I.e., a[i[0]] = e[f[0]]. template void __valarray_copy(_Array<_Tp> __e, _Array __f, size_t __n, _Array<_Tp> __a, _Array __i) { size_t* __g (__f._M_data); size_t* __j (__i._M_data); for (size_t __k = 0; __k < __n; ++__k, ++__j, ++__g) __a._M_data[*__j] = __e._M_data[*__g]; } // Copy n consecutive elements of e into elements of a. Elements of // a are skipped if the corresponding element of m is false. m must // have at least n true elements and a must have at least as many // elements as the index of the nth true element of m. I.e. if m // has 5 false followed by 10 true elements and n == 10, a must have // at least 15 elements. template void __valarray_copy(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a, _Array __m) { bool* __ok (__m._M_data); _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, ++__ok, ++__p) { while (! *__ok) { ++__ok; ++__p; } *__p = __e[__i]; } } template void __valarray_copy_construct(const _Expr<_Dom, _Tp>& __e, size_t __n, _Array<_Tp> __a) { _Tp* __p (__a._M_data); for (size_t __i = 0; __i < __n; ++__i, ++__p) new (__p) _Tp(__e[__i]); } template void __valarray_copy_construct(_Array<_Tp> __a, _Array __m, _Array<_Tp> __b, size_t __n) { _Tp* __p (__a._M_data); bool* __ok (__m._M_data); for (_Tp* __q = __b._M_data; __q < __b._M_data+__n; ++__q, ++__ok, ++__p) { while (! *__ok) { ++__ok; ++__p; } new (__q) _Tp(*__p); } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _VALARRAY_ARRAY_TCC */ c++/8/bits/stl_tree.h000064400000222230151027430570010223 0ustar00// RB tree implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * */ /** @file bits/stl_tree.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{map,set} */ #ifndef _STL_TREE_H #define _STL_TREE_H 1 #pragma GCC system_header #include #include #include #include #include #if __cplusplus >= 201103L # include #endif #if __cplusplus > 201402L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus > 201103L # define __cpp_lib_generic_associative_lookup 201304 #endif // Red-black tree class, designed for use in implementing STL // associative containers (set, multiset, map, and multimap). The // insertion and deletion algorithms are based on those in Cormen, // Leiserson, and Rivest, Introduction to Algorithms (MIT Press, // 1990), except that // // (1) the header cell is maintained with links not only to the root // but also to the leftmost node of the tree, to enable constant // time begin(), and to the rightmost node of the tree, to enable // linear time performance when used with the generic set algorithms // (set_union, etc.) // // (2) when a node being deleted has two children its successor node // is relinked into its place, rather than copied, so that the only // iterators invalidated are those referring to the deleted node. enum _Rb_tree_color { _S_red = false, _S_black = true }; struct _Rb_tree_node_base { typedef _Rb_tree_node_base* _Base_ptr; typedef const _Rb_tree_node_base* _Const_Base_ptr; _Rb_tree_color _M_color; _Base_ptr _M_parent; _Base_ptr _M_left; _Base_ptr _M_right; static _Base_ptr _S_minimum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_left != 0) __x = __x->_M_left; return __x; } static _Const_Base_ptr _S_minimum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_left != 0) __x = __x->_M_left; return __x; } static _Base_ptr _S_maximum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_right != 0) __x = __x->_M_right; return __x; } static _Const_Base_ptr _S_maximum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { while (__x->_M_right != 0) __x = __x->_M_right; return __x; } }; // Helper type offering value initialization guarantee on the compare functor. template struct _Rb_tree_key_compare { _Key_compare _M_key_compare; _Rb_tree_key_compare() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Key_compare>::value) : _M_key_compare() { } _Rb_tree_key_compare(const _Key_compare& __comp) : _M_key_compare(__comp) { } #if __cplusplus >= 201103L // Copy constructor added for consistency with C++98 mode. _Rb_tree_key_compare(const _Rb_tree_key_compare&) = default; _Rb_tree_key_compare(_Rb_tree_key_compare&& __x) noexcept(is_nothrow_copy_constructible<_Key_compare>::value) : _M_key_compare(__x._M_key_compare) { } #endif }; // Helper type to manage default initialization of node count and header. struct _Rb_tree_header { _Rb_tree_node_base _M_header; size_t _M_node_count; // Keeps track of size of tree. _Rb_tree_header() _GLIBCXX_NOEXCEPT { _M_header._M_color = _S_red; _M_reset(); } #if __cplusplus >= 201103L _Rb_tree_header(_Rb_tree_header&& __x) noexcept { if (__x._M_header._M_parent != nullptr) _M_move_data(__x); else { _M_header._M_color = _S_red; _M_reset(); } } #endif void _M_move_data(_Rb_tree_header& __from) { _M_header._M_color = __from._M_header._M_color; _M_header._M_parent = __from._M_header._M_parent; _M_header._M_left = __from._M_header._M_left; _M_header._M_right = __from._M_header._M_right; _M_header._M_parent->_M_parent = &_M_header; _M_node_count = __from._M_node_count; __from._M_reset(); } void _M_reset() { _M_header._M_parent = 0; _M_header._M_left = &_M_header; _M_header._M_right = &_M_header; _M_node_count = 0; } }; template struct _Rb_tree_node : public _Rb_tree_node_base { typedef _Rb_tree_node<_Val>* _Link_type; #if __cplusplus < 201103L _Val _M_value_field; _Val* _M_valptr() { return std::__addressof(_M_value_field); } const _Val* _M_valptr() const { return std::__addressof(_M_value_field); } #else __gnu_cxx::__aligned_membuf<_Val> _M_storage; _Val* _M_valptr() { return _M_storage._M_ptr(); } const _Val* _M_valptr() const { return _M_storage._M_ptr(); } #endif }; _GLIBCXX_PURE _Rb_tree_node_base* _Rb_tree_increment(_Rb_tree_node_base* __x) throw (); _GLIBCXX_PURE const _Rb_tree_node_base* _Rb_tree_increment(const _Rb_tree_node_base* __x) throw (); _GLIBCXX_PURE _Rb_tree_node_base* _Rb_tree_decrement(_Rb_tree_node_base* __x) throw (); _GLIBCXX_PURE const _Rb_tree_node_base* _Rb_tree_decrement(const _Rb_tree_node_base* __x) throw (); template struct _Rb_tree_iterator { typedef _Tp value_type; typedef _Tp& reference; typedef _Tp* pointer; typedef bidirectional_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef _Rb_tree_iterator<_Tp> _Self; typedef _Rb_tree_node_base::_Base_ptr _Base_ptr; typedef _Rb_tree_node<_Tp>* _Link_type; _Rb_tree_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _Rb_tree_iterator(_Base_ptr __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Link_type>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Link_type> (_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_increment(_M_node); return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_increment(_M_node); return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_decrement(_M_node); return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_decrement(_M_node); return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } _Base_ptr _M_node; }; template struct _Rb_tree_const_iterator { typedef _Tp value_type; typedef const _Tp& reference; typedef const _Tp* pointer; typedef _Rb_tree_iterator<_Tp> iterator; typedef bidirectional_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef _Rb_tree_const_iterator<_Tp> _Self; typedef _Rb_tree_node_base::_Const_Base_ptr _Base_ptr; typedef const _Rb_tree_node<_Tp>* _Link_type; _Rb_tree_const_iterator() _GLIBCXX_NOEXCEPT : _M_node() { } explicit _Rb_tree_const_iterator(_Base_ptr __x) _GLIBCXX_NOEXCEPT : _M_node(__x) { } _Rb_tree_const_iterator(const iterator& __it) _GLIBCXX_NOEXCEPT : _M_node(__it._M_node) { } iterator _M_const_cast() const _GLIBCXX_NOEXCEPT { return iterator(const_cast(_M_node)); } reference operator*() const _GLIBCXX_NOEXCEPT { return *static_cast<_Link_type>(_M_node)->_M_valptr(); } pointer operator->() const _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(_M_node)->_M_valptr(); } _Self& operator++() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_increment(_M_node); return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_increment(_M_node); return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { _M_node = _Rb_tree_decrement(_M_node); return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; _M_node = _Rb_tree_decrement(_M_node); return __tmp; } bool operator==(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node == __x._M_node; } bool operator!=(const _Self& __x) const _GLIBCXX_NOEXCEPT { return _M_node != __x._M_node; } _Base_ptr _M_node; }; template inline bool operator==(const _Rb_tree_iterator<_Val>& __x, const _Rb_tree_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node == __y._M_node; } template inline bool operator!=(const _Rb_tree_iterator<_Val>& __x, const _Rb_tree_const_iterator<_Val>& __y) _GLIBCXX_NOEXCEPT { return __x._M_node != __y._M_node; } void _Rb_tree_insert_and_rebalance(const bool __insert_left, _Rb_tree_node_base* __x, _Rb_tree_node_base* __p, _Rb_tree_node_base& __header) throw (); _Rb_tree_node_base* _Rb_tree_rebalance_for_erase(_Rb_tree_node_base* const __z, _Rb_tree_node_base& __header) throw (); #if __cplusplus > 201103L template> struct __has_is_transparent { }; template struct __has_is_transparent<_Cmp, _SfinaeType, __void_t> { typedef void type; }; #endif #if __cplusplus > 201402L template struct _Rb_tree_merge_helper { }; #endif template > class _Rb_tree { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Rb_tree_node<_Val> >::other _Node_allocator; typedef __gnu_cxx::__alloc_traits<_Node_allocator> _Alloc_traits; protected: typedef _Rb_tree_node_base* _Base_ptr; typedef const _Rb_tree_node_base* _Const_Base_ptr; typedef _Rb_tree_node<_Val>* _Link_type; typedef const _Rb_tree_node<_Val>* _Const_Link_type; private: // Functor recycling a pool of nodes and using allocation once the pool // is empty. struct _Reuse_or_alloc_node { _Reuse_or_alloc_node(_Rb_tree& __t) : _M_root(__t._M_root()), _M_nodes(__t._M_rightmost()), _M_t(__t) { if (_M_root) { _M_root->_M_parent = 0; if (_M_nodes->_M_left) _M_nodes = _M_nodes->_M_left; } else _M_nodes = 0; } #if __cplusplus >= 201103L _Reuse_or_alloc_node(const _Reuse_or_alloc_node&) = delete; #endif ~_Reuse_or_alloc_node() { _M_t._M_erase(static_cast<_Link_type>(_M_root)); } template _Link_type #if __cplusplus < 201103L operator()(const _Arg& __arg) #else operator()(_Arg&& __arg) #endif { _Link_type __node = static_cast<_Link_type>(_M_extract()); if (__node) { _M_t._M_destroy_node(__node); _M_t._M_construct_node(__node, _GLIBCXX_FORWARD(_Arg, __arg)); return __node; } return _M_t._M_create_node(_GLIBCXX_FORWARD(_Arg, __arg)); } private: _Base_ptr _M_extract() { if (!_M_nodes) return _M_nodes; _Base_ptr __node = _M_nodes; _M_nodes = _M_nodes->_M_parent; if (_M_nodes) { if (_M_nodes->_M_right == __node) { _M_nodes->_M_right = 0; if (_M_nodes->_M_left) { _M_nodes = _M_nodes->_M_left; while (_M_nodes->_M_right) _M_nodes = _M_nodes->_M_right; if (_M_nodes->_M_left) _M_nodes = _M_nodes->_M_left; } } else // __node is on the left. _M_nodes->_M_left = 0; } else _M_root = 0; return __node; } _Base_ptr _M_root; _Base_ptr _M_nodes; _Rb_tree& _M_t; }; // Functor similar to the previous one but without any pool of nodes to // recycle. struct _Alloc_node { _Alloc_node(_Rb_tree& __t) : _M_t(__t) { } template _Link_type #if __cplusplus < 201103L operator()(const _Arg& __arg) const #else operator()(_Arg&& __arg) const #endif { return _M_t._M_create_node(_GLIBCXX_FORWARD(_Arg, __arg)); } private: _Rb_tree& _M_t; }; public: typedef _Key key_type; typedef _Val value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; _Node_allocator& _M_get_Node_allocator() _GLIBCXX_NOEXCEPT { return this->_M_impl; } const _Node_allocator& _M_get_Node_allocator() const _GLIBCXX_NOEXCEPT { return this->_M_impl; } allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Node_allocator()); } protected: _Link_type _M_get_node() { return _Alloc_traits::allocate(_M_get_Node_allocator(), 1); } void _M_put_node(_Link_type __p) _GLIBCXX_NOEXCEPT { _Alloc_traits::deallocate(_M_get_Node_allocator(), __p, 1); } #if __cplusplus < 201103L void _M_construct_node(_Link_type __node, const value_type& __x) { __try { get_allocator().construct(__node->_M_valptr(), __x); } __catch(...) { _M_put_node(__node); __throw_exception_again; } } _Link_type _M_create_node(const value_type& __x) { _Link_type __tmp = _M_get_node(); _M_construct_node(__tmp, __x); return __tmp; } void _M_destroy_node(_Link_type __p) { get_allocator().destroy(__p->_M_valptr()); } #else template void _M_construct_node(_Link_type __node, _Args&&... __args) { __try { ::new(__node) _Rb_tree_node<_Val>; _Alloc_traits::construct(_M_get_Node_allocator(), __node->_M_valptr(), std::forward<_Args>(__args)...); } __catch(...) { __node->~_Rb_tree_node<_Val>(); _M_put_node(__node); __throw_exception_again; } } template _Link_type _M_create_node(_Args&&... __args) { _Link_type __tmp = _M_get_node(); _M_construct_node(__tmp, std::forward<_Args>(__args)...); return __tmp; } void _M_destroy_node(_Link_type __p) noexcept { _Alloc_traits::destroy(_M_get_Node_allocator(), __p->_M_valptr()); __p->~_Rb_tree_node<_Val>(); } #endif void _M_drop_node(_Link_type __p) _GLIBCXX_NOEXCEPT { _M_destroy_node(__p); _M_put_node(__p); } template _Link_type _M_clone_node(_Const_Link_type __x, _NodeGen& __node_gen) { _Link_type __tmp = __node_gen(*__x->_M_valptr()); __tmp->_M_color = __x->_M_color; __tmp->_M_left = 0; __tmp->_M_right = 0; return __tmp; } protected: #if _GLIBCXX_INLINE_VERSION template #else // Unused _Is_pod_comparator is kept as it is part of mangled name. template #endif struct _Rb_tree_impl : public _Node_allocator , public _Rb_tree_key_compare<_Key_compare> , public _Rb_tree_header { typedef _Rb_tree_key_compare<_Key_compare> _Base_key_compare; _Rb_tree_impl() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Node_allocator>::value && is_nothrow_default_constructible<_Base_key_compare>::value ) : _Node_allocator() { } _Rb_tree_impl(const _Rb_tree_impl& __x) : _Node_allocator(_Alloc_traits::_S_select_on_copy(__x)) , _Base_key_compare(__x._M_key_compare) { } #if __cplusplus < 201103L _Rb_tree_impl(const _Key_compare& __comp, const _Node_allocator& __a) : _Node_allocator(__a), _Base_key_compare(__comp) { } #else _Rb_tree_impl(_Rb_tree_impl&&) = default; _Rb_tree_impl(const _Key_compare& __comp, _Node_allocator&& __a) : _Node_allocator(std::move(__a)), _Base_key_compare(__comp) { } #endif }; _Rb_tree_impl<_Compare> _M_impl; protected: _Base_ptr& _M_root() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_parent; } _Const_Base_ptr _M_root() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_parent; } _Base_ptr& _M_leftmost() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_left; } _Const_Base_ptr _M_leftmost() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_left; } _Base_ptr& _M_rightmost() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_right; } _Const_Base_ptr _M_rightmost() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_header._M_right; } _Link_type _M_begin() _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(this->_M_impl._M_header._M_parent); } _Const_Link_type _M_begin() const _GLIBCXX_NOEXCEPT { return static_cast<_Const_Link_type> (this->_M_impl._M_header._M_parent); } _Base_ptr _M_end() _GLIBCXX_NOEXCEPT { return &this->_M_impl._M_header; } _Const_Base_ptr _M_end() const _GLIBCXX_NOEXCEPT { return &this->_M_impl._M_header; } static const_reference _S_value(_Const_Link_type __x) { return *__x->_M_valptr(); } static const _Key& _S_key(_Const_Link_type __x) { #if __cplusplus >= 201103L // If we're asking for the key we're presumably using the comparison // object, and so this is a good place to sanity check it. static_assert(__is_invocable<_Compare&, const _Key&, const _Key&>{}, "comparison object must be invocable " "with two arguments of key type"); # if __cplusplus >= 201703L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2542. Missing const requirements for associative containers if constexpr (__is_invocable<_Compare&, const _Key&, const _Key&>{}) static_assert( is_invocable_v, "comparison object must be invocable as const"); # endif // C++17 #endif // C++11 return _KeyOfValue()(*__x->_M_valptr()); } static _Link_type _S_left(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(__x->_M_left); } static _Const_Link_type _S_left(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Const_Link_type>(__x->_M_left); } static _Link_type _S_right(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Link_type>(__x->_M_right); } static _Const_Link_type _S_right(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return static_cast<_Const_Link_type>(__x->_M_right); } static const_reference _S_value(_Const_Base_ptr __x) { return *static_cast<_Const_Link_type>(__x)->_M_valptr(); } static const _Key& _S_key(_Const_Base_ptr __x) { return _S_key(static_cast<_Const_Link_type>(__x)); } static _Base_ptr _S_minimum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_minimum(__x); } static _Const_Base_ptr _S_minimum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_minimum(__x); } static _Base_ptr _S_maximum(_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_maximum(__x); } static _Const_Base_ptr _S_maximum(_Const_Base_ptr __x) _GLIBCXX_NOEXCEPT { return _Rb_tree_node_base::_S_maximum(__x); } public: typedef _Rb_tree_iterator iterator; typedef _Rb_tree_const_iterator const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; #if __cplusplus > 201402L using node_type = _Node_handle<_Key, _Val, _Node_allocator>; using insert_return_type = _Node_insert_return< conditional_t, const_iterator, iterator>, node_type>; #endif pair<_Base_ptr, _Base_ptr> _M_get_insert_unique_pos(const key_type& __k); pair<_Base_ptr, _Base_ptr> _M_get_insert_equal_pos(const key_type& __k); pair<_Base_ptr, _Base_ptr> _M_get_insert_hint_unique_pos(const_iterator __pos, const key_type& __k); pair<_Base_ptr, _Base_ptr> _M_get_insert_hint_equal_pos(const_iterator __pos, const key_type& __k); private: #if __cplusplus >= 201103L template iterator _M_insert_(_Base_ptr __x, _Base_ptr __y, _Arg&& __v, _NodeGen&); iterator _M_insert_node(_Base_ptr __x, _Base_ptr __y, _Link_type __z); template iterator _M_insert_lower(_Base_ptr __y, _Arg&& __v); template iterator _M_insert_equal_lower(_Arg&& __x); iterator _M_insert_lower_node(_Base_ptr __p, _Link_type __z); iterator _M_insert_equal_lower_node(_Link_type __z); #else template iterator _M_insert_(_Base_ptr __x, _Base_ptr __y, const value_type& __v, _NodeGen&); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 233. Insertion hints in associative containers. iterator _M_insert_lower(_Base_ptr __y, const value_type& __v); iterator _M_insert_equal_lower(const value_type& __x); #endif template _Link_type _M_copy(_Const_Link_type __x, _Base_ptr __p, _NodeGen&); template _Link_type _M_copy(const _Rb_tree& __x, _NodeGen& __gen) { _Link_type __root = _M_copy(__x._M_begin(), _M_end(), __gen); _M_leftmost() = _S_minimum(__root); _M_rightmost() = _S_maximum(__root); _M_impl._M_node_count = __x._M_impl._M_node_count; return __root; } _Link_type _M_copy(const _Rb_tree& __x) { _Alloc_node __an(*this); return _M_copy(__x, __an); } void _M_erase(_Link_type __x); iterator _M_lower_bound(_Link_type __x, _Base_ptr __y, const _Key& __k); const_iterator _M_lower_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const; iterator _M_upper_bound(_Link_type __x, _Base_ptr __y, const _Key& __k); const_iterator _M_upper_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const; public: // allocation/deallocation #if __cplusplus < 201103L _Rb_tree() { } #else _Rb_tree() = default; #endif _Rb_tree(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_impl(__comp, _Node_allocator(__a)) { } _Rb_tree(const _Rb_tree& __x) : _M_impl(__x._M_impl) { if (__x._M_root() != 0) _M_root() = _M_copy(__x); } #if __cplusplus >= 201103L _Rb_tree(const allocator_type& __a) : _M_impl(_Compare(), _Node_allocator(__a)) { } _Rb_tree(const _Rb_tree& __x, const allocator_type& __a) : _M_impl(__x._M_impl._M_key_compare, _Node_allocator(__a)) { if (__x._M_root() != nullptr) _M_root() = _M_copy(__x); } _Rb_tree(_Rb_tree&&) = default; _Rb_tree(_Rb_tree&& __x, const allocator_type& __a) : _Rb_tree(std::move(__x), _Node_allocator(__a)) { } _Rb_tree(_Rb_tree&& __x, _Node_allocator&& __a); #endif ~_Rb_tree() _GLIBCXX_NOEXCEPT { _M_erase(_M_begin()); } _Rb_tree& operator=(const _Rb_tree& __x); // Accessors. _Compare key_comp() const { return _M_impl._M_key_compare; } iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_header._M_left); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_header._M_left); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(&this->_M_impl._M_header); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(&this->_M_impl._M_header); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } bool empty() const _GLIBCXX_NOEXCEPT { return _M_impl._M_node_count == 0; } size_type size() const _GLIBCXX_NOEXCEPT { return _M_impl._M_node_count; } size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Node_allocator()); } void swap(_Rb_tree& __t) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value); // Insert/erase. #if __cplusplus >= 201103L template pair _M_insert_unique(_Arg&& __x); template iterator _M_insert_equal(_Arg&& __x); template iterator _M_insert_unique_(const_iterator __pos, _Arg&& __x, _NodeGen&); template iterator _M_insert_unique_(const_iterator __pos, _Arg&& __x) { _Alloc_node __an(*this); return _M_insert_unique_(__pos, std::forward<_Arg>(__x), __an); } template iterator _M_insert_equal_(const_iterator __pos, _Arg&& __x, _NodeGen&); template iterator _M_insert_equal_(const_iterator __pos, _Arg&& __x) { _Alloc_node __an(*this); return _M_insert_equal_(__pos, std::forward<_Arg>(__x), __an); } template pair _M_emplace_unique(_Args&&... __args); template iterator _M_emplace_equal(_Args&&... __args); template iterator _M_emplace_hint_unique(const_iterator __pos, _Args&&... __args); template iterator _M_emplace_hint_equal(const_iterator __pos, _Args&&... __args); #else pair _M_insert_unique(const value_type& __x); iterator _M_insert_equal(const value_type& __x); template iterator _M_insert_unique_(const_iterator __pos, const value_type& __x, _NodeGen&); iterator _M_insert_unique_(const_iterator __pos, const value_type& __x) { _Alloc_node __an(*this); return _M_insert_unique_(__pos, __x, __an); } template iterator _M_insert_equal_(const_iterator __pos, const value_type& __x, _NodeGen&); iterator _M_insert_equal_(const_iterator __pos, const value_type& __x) { _Alloc_node __an(*this); return _M_insert_equal_(__pos, __x, __an); } #endif template void _M_insert_unique(_InputIterator __first, _InputIterator __last); template void _M_insert_equal(_InputIterator __first, _InputIterator __last); private: void _M_erase_aux(const_iterator __position); void _M_erase_aux(const_iterator __first, const_iterator __last); public: #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __position) { __glibcxx_assert(__position != end()); const_iterator __result = __position; ++__result; _M_erase_aux(__position); return __result._M_const_cast(); } // LWG 2059. _GLIBCXX_ABI_TAG_CXX11 iterator erase(iterator __position) { __glibcxx_assert(__position != end()); iterator __result = __position; ++__result; _M_erase_aux(__position); return __result; } #else void erase(iterator __position) { __glibcxx_assert(__position != end()); _M_erase_aux(__position); } void erase(const_iterator __position) { __glibcxx_assert(__position != end()); _M_erase_aux(__position); } #endif size_type erase(const key_type& __x); #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __first, const_iterator __last) { _M_erase_aux(__first, __last); return __last._M_const_cast(); } #else void erase(iterator __first, iterator __last) { _M_erase_aux(__first, __last); } void erase(const_iterator __first, const_iterator __last) { _M_erase_aux(__first, __last); } #endif void erase(const key_type* __first, const key_type* __last); void clear() _GLIBCXX_NOEXCEPT { _M_erase(_M_begin()); _M_impl._M_reset(); } // Set operations. iterator find(const key_type& __k); const_iterator find(const key_type& __k) const; size_type count(const key_type& __k) const; iterator lower_bound(const key_type& __k) { return _M_lower_bound(_M_begin(), _M_end(), __k); } const_iterator lower_bound(const key_type& __k) const { return _M_lower_bound(_M_begin(), _M_end(), __k); } iterator upper_bound(const key_type& __k) { return _M_upper_bound(_M_begin(), _M_end(), __k); } const_iterator upper_bound(const key_type& __k) const { return _M_upper_bound(_M_begin(), _M_end(), __k); } pair equal_range(const key_type& __k); pair equal_range(const key_type& __k) const; #if __cplusplus > 201103L template::type> iterator _M_find_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; return __const_this->_M_find_tr(__k)._M_const_cast(); } template::type> const_iterator _M_find_tr(const _Kt& __k) const { auto __j = _M_lower_bound_tr(__k); if (__j != end() && _M_impl._M_key_compare(__k, _S_key(__j._M_node))) __j = end(); return __j; } template::type> size_type _M_count_tr(const _Kt& __k) const { auto __p = _M_equal_range_tr(__k); return std::distance(__p.first, __p.second); } template::type> iterator _M_lower_bound_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; return __const_this->_M_lower_bound_tr(__k)._M_const_cast(); } template::type> const_iterator _M_lower_bound_tr(const _Kt& __k) const { auto __x = _M_begin(); auto __y = _M_end(); while (__x != 0) if (!_M_impl._M_key_compare(_S_key(__x), __k)) { __y = __x; __x = _S_left(__x); } else __x = _S_right(__x); return const_iterator(__y); } template::type> iterator _M_upper_bound_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; return __const_this->_M_upper_bound_tr(__k)._M_const_cast(); } template::type> const_iterator _M_upper_bound_tr(const _Kt& __k) const { auto __x = _M_begin(); auto __y = _M_end(); while (__x != 0) if (_M_impl._M_key_compare(__k, _S_key(__x))) { __y = __x; __x = _S_left(__x); } else __x = _S_right(__x); return const_iterator(__y); } template::type> pair _M_equal_range_tr(const _Kt& __k) { const _Rb_tree* __const_this = this; auto __ret = __const_this->_M_equal_range_tr(__k); return { __ret.first._M_const_cast(), __ret.second._M_const_cast() }; } template::type> pair _M_equal_range_tr(const _Kt& __k) const { auto __low = _M_lower_bound_tr(__k); auto __high = __low; auto& __cmp = _M_impl._M_key_compare; while (__high != end() && !__cmp(__k, _S_key(__high._M_node))) ++__high; return { __low, __high }; } #endif // Debugging. bool __rb_verify() const; #if __cplusplus >= 201103L _Rb_tree& operator=(_Rb_tree&&) noexcept(_Alloc_traits::_S_nothrow_move() && is_nothrow_move_assignable<_Compare>::value); template void _M_assign_unique(_Iterator, _Iterator); template void _M_assign_equal(_Iterator, _Iterator); private: // Move elements from container with equal allocator. void _M_move_data(_Rb_tree& __x, std::true_type) { _M_impl._M_move_data(__x._M_impl); } // Move elements from container with possibly non-equal allocator, // which might result in a copy not a move. void _M_move_data(_Rb_tree&, std::false_type); // Move assignment from container with equal allocator. void _M_move_assign(_Rb_tree&, std::true_type); // Move assignment from container with possibly non-equal allocator, // which might result in a copy not a move. void _M_move_assign(_Rb_tree&, std::false_type); #endif #if __cplusplus > 201402L public: /// Re-insert an extracted node. insert_return_type _M_reinsert_node_unique(node_type&& __nh) { insert_return_type __ret; if (__nh.empty()) __ret.position = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_unique_pos(__nh._M_key()); if (__res.second) { __ret.position = _M_insert_node(__res.first, __res.second, __nh._M_ptr); __nh._M_ptr = nullptr; __ret.inserted = true; } else { __ret.node = std::move(__nh); __ret.position = iterator(__res.first); __ret.inserted = false; } } return __ret; } /// Re-insert an extracted node. iterator _M_reinsert_node_equal(node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_equal_pos(__nh._M_key()); if (__res.second) __ret = _M_insert_node(__res.first, __res.second, __nh._M_ptr); else __ret = _M_insert_equal_lower_node(__nh._M_ptr); __nh._M_ptr = nullptr; } return __ret; } /// Re-insert an extracted node. iterator _M_reinsert_node_hint_unique(const_iterator __hint, node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_hint_unique_pos(__hint, __nh._M_key()); if (__res.second) { __ret = _M_insert_node(__res.first, __res.second, __nh._M_ptr); __nh._M_ptr = nullptr; } else __ret = iterator(__res.first); } return __ret; } /// Re-insert an extracted node. iterator _M_reinsert_node_hint_equal(const_iterator __hint, node_type&& __nh) { iterator __ret; if (__nh.empty()) __ret = end(); else { __glibcxx_assert(_M_get_Node_allocator() == *__nh._M_alloc); auto __res = _M_get_insert_hint_equal_pos(__hint, __nh._M_key()); if (__res.second) __ret = _M_insert_node(__res.first, __res.second, __nh._M_ptr); else __ret = _M_insert_equal_lower_node(__nh._M_ptr); __nh._M_ptr = nullptr; } return __ret; } /// Extract a node. node_type extract(const_iterator __pos) { auto __ptr = _Rb_tree_rebalance_for_erase( __pos._M_const_cast()._M_node, _M_impl._M_header); --_M_impl._M_node_count; return { static_cast<_Link_type>(__ptr), _M_get_Node_allocator() }; } /// Extract a node. node_type extract(const key_type& __k) { node_type __nh; auto __pos = find(__k); if (__pos != end()) __nh = extract(const_iterator(__pos)); return __nh; } template using _Compatible_tree = _Rb_tree<_Key, _Val, _KeyOfValue, _Compare2, _Alloc>; template friend class _Rb_tree_merge_helper; /// Merge from a compatible container into one with unique keys. template void _M_merge_unique(_Compatible_tree<_Compare2>& __src) noexcept { using _Merge_helper = _Rb_tree_merge_helper<_Rb_tree, _Compare2>; for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) { auto __pos = __i++; auto __res = _M_get_insert_unique_pos(_KeyOfValue()(*__pos)); if (__res.second) { auto& __src_impl = _Merge_helper::_S_get_impl(__src); auto __ptr = _Rb_tree_rebalance_for_erase( __pos._M_node, __src_impl._M_header); --__src_impl._M_node_count; _M_insert_node(__res.first, __res.second, static_cast<_Link_type>(__ptr)); } } } /// Merge from a compatible container into one with equivalent keys. template void _M_merge_equal(_Compatible_tree<_Compare2>& __src) noexcept { using _Merge_helper = _Rb_tree_merge_helper<_Rb_tree, _Compare2>; for (auto __i = __src.begin(), __end = __src.end(); __i != __end;) { auto __pos = __i++; auto __res = _M_get_insert_equal_pos(_KeyOfValue()(*__pos)); if (__res.second) { auto& __src_impl = _Merge_helper::_S_get_impl(__src); auto __ptr = _Rb_tree_rebalance_for_erase( __pos._M_node, __src_impl._M_header); --__src_impl._M_node_count; _M_insert_node(__res.first, __res.second, static_cast<_Link_type>(__ptr)); } } } #endif // C++17 }; template inline bool operator==(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return __x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin()); } template inline bool operator<(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } template inline bool operator!=(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return !(__x == __y); } template inline bool operator>(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return __y < __x; } template inline bool operator<=(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return !(__y < __x); } template inline bool operator>=(const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, const _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { return !(__x < __y); } template inline void swap(_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __x, _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& __y) { __x.swap(__y); } #if __cplusplus >= 201103L template _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _Rb_tree(_Rb_tree&& __x, _Node_allocator&& __a) : _M_impl(__x._M_impl._M_key_compare, std::move(__a)) { using __eq = typename _Alloc_traits::is_always_equal; if (__x._M_root() != nullptr) _M_move_data(__x, __eq()); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_move_data(_Rb_tree& __x, std::false_type) { if (_M_get_Node_allocator() == __x._M_get_Node_allocator()) _M_move_data(__x, std::true_type()); else { _Alloc_node __an(*this); auto __lbd = [&__an](const value_type& __cval) { auto& __val = const_cast(__cval); return __an(std::move_if_noexcept(__val)); }; _M_root() = _M_copy(__x, __lbd); } } template inline void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_move_assign(_Rb_tree& __x, true_type) { clear(); if (__x._M_root() != nullptr) _M_move_data(__x, std::true_type()); std::__alloc_on_move(_M_get_Node_allocator(), __x._M_get_Node_allocator()); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_move_assign(_Rb_tree& __x, false_type) { if (_M_get_Node_allocator() == __x._M_get_Node_allocator()) return _M_move_assign(__x, true_type{}); // Try to move each node reusing existing nodes and copying __x nodes // structure. _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); if (__x._M_root() != nullptr) { auto __lbd = [&__roan](const value_type& __cval) { auto& __val = const_cast(__cval); return __roan(std::move_if_noexcept(__val)); }; _M_root() = _M_copy(__x, __lbd); __x.clear(); } } template inline _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: operator=(_Rb_tree&& __x) noexcept(_Alloc_traits::_S_nothrow_move() && is_nothrow_move_assignable<_Compare>::value) { _M_impl._M_key_compare = std::move(__x._M_impl._M_key_compare); _M_move_assign(__x, __bool_constant<_Alloc_traits::_S_nothrow_move()>()); return *this; } template template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_assign_unique(_Iterator __first, _Iterator __last) { _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); for (; __first != __last; ++__first) _M_insert_unique_(end(), *__first, __roan); } template template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_assign_equal(_Iterator __first, _Iterator __last) { _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); for (; __first != __last; ++__first) _M_insert_equal_(end(), *__first, __roan); } #endif template _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>& _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: operator=(const _Rb_tree& __x) { if (this != &__x) { // Note that _Key may be a constant type. #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_get_Node_allocator(); auto& __that_alloc = __x._M_get_Node_allocator(); if (!_Alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // Replacement allocator cannot free existing storage, we need // to erase nodes first. clear(); std::__alloc_on_copy(__this_alloc, __that_alloc); } } #endif _Reuse_or_alloc_node __roan(*this); _M_impl._M_reset(); _M_impl._M_key_compare = __x._M_impl._M_key_compare; if (__x._M_root() != 0) _M_root() = _M_copy(__x, __roan); } return *this; } template #if __cplusplus >= 201103L template #else template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_(_Base_ptr __x, _Base_ptr __p, #if __cplusplus >= 201103L _Arg&& __v, #else const _Val& __v, #endif _NodeGen& __node_gen) { bool __insert_left = (__x != 0 || __p == _M_end() || _M_impl._M_key_compare(_KeyOfValue()(__v), _S_key(__p))); _Link_type __z = __node_gen(_GLIBCXX_FORWARD(_Arg, __v)); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template #if __cplusplus >= 201103L template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_lower(_Base_ptr __p, _Arg&& __v) #else _M_insert_lower(_Base_ptr __p, const _Val& __v) #endif { bool __insert_left = (__p == _M_end() || !_M_impl._M_key_compare(_S_key(__p), _KeyOfValue()(__v))); _Link_type __z = _M_create_node(_GLIBCXX_FORWARD(_Arg, __v)); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template #if __cplusplus >= 201103L template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_equal_lower(_Arg&& __v) #else _M_insert_equal_lower(const _Val& __v) #endif { _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { __y = __x; __x = !_M_impl._M_key_compare(_S_key(__x), _KeyOfValue()(__v)) ? _S_left(__x) : _S_right(__x); } return _M_insert_lower(__y, _GLIBCXX_FORWARD(_Arg, __v)); } template template typename _Rb_tree<_Key, _Val, _KoV, _Compare, _Alloc>::_Link_type _Rb_tree<_Key, _Val, _KoV, _Compare, _Alloc>:: _M_copy(_Const_Link_type __x, _Base_ptr __p, _NodeGen& __node_gen) { // Structural copy. __x and __p must be non-null. _Link_type __top = _M_clone_node(__x, __node_gen); __top->_M_parent = __p; __try { if (__x->_M_right) __top->_M_right = _M_copy(_S_right(__x), __top, __node_gen); __p = __top; __x = _S_left(__x); while (__x != 0) { _Link_type __y = _M_clone_node(__x, __node_gen); __p->_M_left = __y; __y->_M_parent = __p; if (__x->_M_right) __y->_M_right = _M_copy(_S_right(__x), __y, __node_gen); __p = __y; __x = _S_left(__x); } } __catch(...) { _M_erase(__top); __throw_exception_again; } return __top; } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_erase(_Link_type __x) { // Erase without rebalancing. while (__x != 0) { _M_erase(_S_right(__x)); _Link_type __y = _S_left(__x); _M_drop_node(__x); __x = __y; } } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_lower_bound(_Link_type __x, _Base_ptr __y, const _Key& __k) { while (__x != 0) if (!_M_impl._M_key_compare(_S_key(__x), __k)) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return iterator(__y); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_lower_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const { while (__x != 0) if (!_M_impl._M_key_compare(_S_key(__x), __k)) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return const_iterator(__y); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_upper_bound(_Link_type __x, _Base_ptr __y, const _Key& __k) { while (__x != 0) if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return iterator(__y); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_upper_bound(_Const_Link_type __x, _Const_Base_ptr __y, const _Key& __k) const { while (__x != 0) if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else __x = _S_right(__x); return const_iterator(__y); } template pair::iterator, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: equal_range(const _Key& __k) { _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { if (_M_impl._M_key_compare(_S_key(__x), __k)) __x = _S_right(__x); else if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else { _Link_type __xu(__x); _Base_ptr __yu(__y); __y = __x, __x = _S_left(__x); __xu = _S_right(__xu); return pair(_M_lower_bound(__x, __y, __k), _M_upper_bound(__xu, __yu, __k)); } } return pair(iterator(__y), iterator(__y)); } template pair::const_iterator, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: equal_range(const _Key& __k) const { _Const_Link_type __x = _M_begin(); _Const_Base_ptr __y = _M_end(); while (__x != 0) { if (_M_impl._M_key_compare(_S_key(__x), __k)) __x = _S_right(__x); else if (_M_impl._M_key_compare(__k, _S_key(__x))) __y = __x, __x = _S_left(__x); else { _Const_Link_type __xu(__x); _Const_Base_ptr __yu(__y); __y = __x, __x = _S_left(__x); __xu = _S_right(__xu); return pair(_M_lower_bound(__x, __y, __k), _M_upper_bound(__xu, __yu, __k)); } } return pair(const_iterator(__y), const_iterator(__y)); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: swap(_Rb_tree& __t) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { if (_M_root() == 0) { if (__t._M_root() != 0) _M_impl._M_move_data(__t._M_impl); } else if (__t._M_root() == 0) __t._M_impl._M_move_data(_M_impl); else { std::swap(_M_root(),__t._M_root()); std::swap(_M_leftmost(),__t._M_leftmost()); std::swap(_M_rightmost(),__t._M_rightmost()); _M_root()->_M_parent = _M_end(); __t._M_root()->_M_parent = __t._M_end(); std::swap(this->_M_impl._M_node_count, __t._M_impl._M_node_count); } // No need to swap header's color as it does not change. std::swap(this->_M_impl._M_key_compare, __t._M_impl._M_key_compare); _Alloc_traits::_S_on_swap(_M_get_Node_allocator(), __t._M_get_Node_allocator()); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_unique_pos(const key_type& __k) { typedef pair<_Base_ptr, _Base_ptr> _Res; _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); bool __comp = true; while (__x != 0) { __y = __x; __comp = _M_impl._M_key_compare(__k, _S_key(__x)); __x = __comp ? _S_left(__x) : _S_right(__x); } iterator __j = iterator(__y); if (__comp) { if (__j == begin()) return _Res(__x, __y); else --__j; } if (_M_impl._M_key_compare(_S_key(__j._M_node), __k)) return _Res(__x, __y); return _Res(__j._M_node, 0); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_equal_pos(const key_type& __k) { typedef pair<_Base_ptr, _Base_ptr> _Res; _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { __y = __x; __x = _M_impl._M_key_compare(__k, _S_key(__x)) ? _S_left(__x) : _S_right(__x); } return _Res(__x, __y); } template #if __cplusplus >= 201103L template #endif pair::iterator, bool> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_unique(_Arg&& __v) #else _M_insert_unique(const _Val& __v) #endif { typedef pair _Res; pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_unique_pos(_KeyOfValue()(__v)); if (__res.second) { _Alloc_node __an(*this); return _Res(_M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __an), true); } return _Res(iterator(__res.first), false); } template #if __cplusplus >= 201103L template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: #if __cplusplus >= 201103L _M_insert_equal(_Arg&& __v) #else _M_insert_equal(const _Val& __v) #endif { pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_equal_pos(_KeyOfValue()(__v)); _Alloc_node __an(*this); return _M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __an); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_hint_unique_pos(const_iterator __position, const key_type& __k) { iterator __pos = __position._M_const_cast(); typedef pair<_Base_ptr, _Base_ptr> _Res; // end() if (__pos._M_node == _M_end()) { if (size() > 0 && _M_impl._M_key_compare(_S_key(_M_rightmost()), __k)) return _Res(0, _M_rightmost()); else return _M_get_insert_unique_pos(__k); } else if (_M_impl._M_key_compare(__k, _S_key(__pos._M_node))) { // First, try before... iterator __before = __pos; if (__pos._M_node == _M_leftmost()) // begin() return _Res(_M_leftmost(), _M_leftmost()); else if (_M_impl._M_key_compare(_S_key((--__before)._M_node), __k)) { if (_S_right(__before._M_node) == 0) return _Res(0, __before._M_node); else return _Res(__pos._M_node, __pos._M_node); } else return _M_get_insert_unique_pos(__k); } else if (_M_impl._M_key_compare(_S_key(__pos._M_node), __k)) { // ... then try after. iterator __after = __pos; if (__pos._M_node == _M_rightmost()) return _Res(0, _M_rightmost()); else if (_M_impl._M_key_compare(__k, _S_key((++__after)._M_node))) { if (_S_right(__pos._M_node) == 0) return _Res(0, __pos._M_node); else return _Res(__after._M_node, __after._M_node); } else return _M_get_insert_unique_pos(__k); } else // Equivalent keys. return _Res(__pos._M_node, 0); } template #if __cplusplus >= 201103L template #else template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_unique_(const_iterator __position, #if __cplusplus >= 201103L _Arg&& __v, #else const _Val& __v, #endif _NodeGen& __node_gen) { pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_hint_unique_pos(__position, _KeyOfValue()(__v)); if (__res.second) return _M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __node_gen); return iterator(__res.first); } template pair::_Base_ptr, typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Base_ptr> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_get_insert_hint_equal_pos(const_iterator __position, const key_type& __k) { iterator __pos = __position._M_const_cast(); typedef pair<_Base_ptr, _Base_ptr> _Res; // end() if (__pos._M_node == _M_end()) { if (size() > 0 && !_M_impl._M_key_compare(__k, _S_key(_M_rightmost()))) return _Res(0, _M_rightmost()); else return _M_get_insert_equal_pos(__k); } else if (!_M_impl._M_key_compare(_S_key(__pos._M_node), __k)) { // First, try before... iterator __before = __pos; if (__pos._M_node == _M_leftmost()) // begin() return _Res(_M_leftmost(), _M_leftmost()); else if (!_M_impl._M_key_compare(__k, _S_key((--__before)._M_node))) { if (_S_right(__before._M_node) == 0) return _Res(0, __before._M_node); else return _Res(__pos._M_node, __pos._M_node); } else return _M_get_insert_equal_pos(__k); } else { // ... then try after. iterator __after = __pos; if (__pos._M_node == _M_rightmost()) return _Res(0, _M_rightmost()); else if (!_M_impl._M_key_compare(_S_key((++__after)._M_node), __k)) { if (_S_right(__pos._M_node) == 0) return _Res(0, __pos._M_node); else return _Res(__after._M_node, __after._M_node); } else return _Res(0, 0); } } template #if __cplusplus >= 201103L template #else template #endif typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_equal_(const_iterator __position, #if __cplusplus >= 201103L _Arg&& __v, #else const _Val& __v, #endif _NodeGen& __node_gen) { pair<_Base_ptr, _Base_ptr> __res = _M_get_insert_hint_equal_pos(__position, _KeyOfValue()(__v)); if (__res.second) return _M_insert_(__res.first, __res.second, _GLIBCXX_FORWARD(_Arg, __v), __node_gen); return _M_insert_equal_lower(_GLIBCXX_FORWARD(_Arg, __v)); } #if __cplusplus >= 201103L template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_node(_Base_ptr __x, _Base_ptr __p, _Link_type __z) { bool __insert_left = (__x != 0 || __p == _M_end() || _M_impl._M_key_compare(_S_key(__z), _S_key(__p))); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_lower_node(_Base_ptr __p, _Link_type __z) { bool __insert_left = (__p == _M_end() || !_M_impl._M_key_compare(_S_key(__p), _S_key(__z))); _Rb_tree_insert_and_rebalance(__insert_left, __z, __p, this->_M_impl._M_header); ++_M_impl._M_node_count; return iterator(__z); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_insert_equal_lower_node(_Link_type __z) { _Link_type __x = _M_begin(); _Base_ptr __y = _M_end(); while (__x != 0) { __y = __x; __x = !_M_impl._M_key_compare(_S_key(__x), _S_key(__z)) ? _S_left(__x) : _S_right(__x); } return _M_insert_lower_node(__y, __z); } template template pair::iterator, bool> _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_unique(_Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { typedef pair _Res; auto __res = _M_get_insert_unique_pos(_S_key(__z)); if (__res.second) return _Res(_M_insert_node(__res.first, __res.second, __z), true); _M_drop_node(__z); return _Res(iterator(__res.first), false); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } template template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_equal(_Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { auto __res = _M_get_insert_equal_pos(_S_key(__z)); return _M_insert_node(__res.first, __res.second, __z); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } template template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_hint_unique(const_iterator __pos, _Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { auto __res = _M_get_insert_hint_unique_pos(__pos, _S_key(__z)); if (__res.second) return _M_insert_node(__res.first, __res.second, __z); _M_drop_node(__z); return iterator(__res.first); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } template template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_emplace_hint_equal(const_iterator __pos, _Args&&... __args) { _Link_type __z = _M_create_node(std::forward<_Args>(__args)...); __try { auto __res = _M_get_insert_hint_equal_pos(__pos, _S_key(__z)); if (__res.second) return _M_insert_node(__res.first, __res.second, __z); return _M_insert_equal_lower_node(__z); } __catch(...) { _M_drop_node(__z); __throw_exception_again; } } #endif template template void _Rb_tree<_Key, _Val, _KoV, _Cmp, _Alloc>:: _M_insert_unique(_II __first, _II __last) { _Alloc_node __an(*this); for (; __first != __last; ++__first) _M_insert_unique_(end(), *__first, __an); } template template void _Rb_tree<_Key, _Val, _KoV, _Cmp, _Alloc>:: _M_insert_equal(_II __first, _II __last) { _Alloc_node __an(*this); for (; __first != __last; ++__first) _M_insert_equal_(end(), *__first, __an); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_erase_aux(const_iterator __position) { _Link_type __y = static_cast<_Link_type>(_Rb_tree_rebalance_for_erase (const_cast<_Base_ptr>(__position._M_node), this->_M_impl._M_header)); _M_drop_node(__y); --_M_impl._M_node_count; } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: _M_erase_aux(const_iterator __first, const_iterator __last) { if (__first == begin() && __last == end()) clear(); else while (__first != __last) _M_erase_aux(__first++); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::size_type _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: erase(const _Key& __x) { pair __p = equal_range(__x); const size_type __old_size = size(); _M_erase_aux(__p.first, __p.second); return __old_size - size(); } template void _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: erase(const _Key* __first, const _Key* __last) { while (__first != __last) erase(*__first++); } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: find(const _Key& __k) { iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k); return (__j == end() || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j; } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: find(const _Key& __k) const { const_iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k); return (__j == end() || _M_impl._M_key_compare(__k, _S_key(__j._M_node))) ? end() : __j; } template typename _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::size_type _Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>:: count(const _Key& __k) const { pair __p = equal_range(__k); const size_type __n = std::distance(__p.first, __p.second); return __n; } _GLIBCXX_PURE unsigned int _Rb_tree_black_count(const _Rb_tree_node_base* __node, const _Rb_tree_node_base* __root) throw (); template bool _Rb_tree<_Key,_Val,_KeyOfValue,_Compare,_Alloc>::__rb_verify() const { if (_M_impl._M_node_count == 0 || begin() == end()) return _M_impl._M_node_count == 0 && begin() == end() && this->_M_impl._M_header._M_left == _M_end() && this->_M_impl._M_header._M_right == _M_end(); unsigned int __len = _Rb_tree_black_count(_M_leftmost(), _M_root()); for (const_iterator __it = begin(); __it != end(); ++__it) { _Const_Link_type __x = static_cast<_Const_Link_type>(__it._M_node); _Const_Link_type __L = _S_left(__x); _Const_Link_type __R = _S_right(__x); if (__x->_M_color == _S_red) if ((__L && __L->_M_color == _S_red) || (__R && __R->_M_color == _S_red)) return false; if (__L && _M_impl._M_key_compare(_S_key(__x), _S_key(__L))) return false; if (__R && _M_impl._M_key_compare(_S_key(__R), _S_key(__x))) return false; if (!__L && !__R && _Rb_tree_black_count(__x, _M_root()) != __len) return false; } if (_M_leftmost() != _Rb_tree_node_base::_S_minimum(_M_root())) return false; if (_M_rightmost() != _Rb_tree_node_base::_S_maximum(_M_root())) return false; return true; } #if __cplusplus > 201402L // Allow access to internals of compatible _Rb_tree specializations. template struct _Rb_tree_merge_helper<_Rb_tree<_Key, _Val, _Sel, _Cmp1, _Alloc>, _Cmp2> { private: friend class _Rb_tree<_Key, _Val, _Sel, _Cmp1, _Alloc>; static auto& _S_get_impl(_Rb_tree<_Key, _Val, _Sel, _Cmp2, _Alloc>& __tree) { return __tree._M_impl; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/move.h000064400000014601151027430570007351 0ustar00// Move, forward and identity for C++11 + swap -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/move.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{utility} */ #ifndef _MOVE_H #define _MOVE_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Used, in C++03 mode too, by allocators, etc. /** * @brief Same as C++11 std::addressof * @ingroup utilities */ template inline _GLIBCXX_CONSTEXPR _Tp* __addressof(_Tp& __r) _GLIBCXX_NOEXCEPT { return __builtin_addressof(__r); } #if __cplusplus >= 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include // Brings in std::declval too. namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ /** * @brief Forward an lvalue. * @return The parameter cast to the specified type. * * This function is used to implement "perfect forwarding". */ template constexpr _Tp&& forward(typename std::remove_reference<_Tp>::type& __t) noexcept { return static_cast<_Tp&&>(__t); } /** * @brief Forward an rvalue. * @return The parameter cast to the specified type. * * This function is used to implement "perfect forwarding". */ template constexpr _Tp&& forward(typename std::remove_reference<_Tp>::type&& __t) noexcept { static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument" " substituting _Tp is an lvalue reference type"); return static_cast<_Tp&&>(__t); } /** * @brief Convert a value to an rvalue. * @param __t A thing of arbitrary type. * @return The parameter cast to an rvalue-reference to allow moving it. */ template constexpr typename std::remove_reference<_Tp>::type&& move(_Tp&& __t) noexcept { return static_cast::type&&>(__t); } template struct __move_if_noexcept_cond : public __and_<__not_>, is_copy_constructible<_Tp>>::type { }; /** * @brief Conditionally convert a value to an rvalue. * @param __x A thing of arbitrary type. * @return The parameter, possibly cast to an rvalue-reference. * * Same as std::move unless the type's move constructor could throw and the * type is copyable, in which case an lvalue-reference is returned instead. */ template constexpr typename conditional<__move_if_noexcept_cond<_Tp>::value, const _Tp&, _Tp&&>::type move_if_noexcept(_Tp& __x) noexcept { return std::move(__x); } // declval, from type_traits. #if __cplusplus > 201402L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2296. std::addressof should be constexpr # define __cpp_lib_addressof_constexpr 201603 #endif /** * @brief Returns the actual address of the object or function * referenced by r, even in the presence of an overloaded * operator&. * @param __r Reference to an object or function. * @return The actual address. */ template inline _GLIBCXX17_CONSTEXPR _Tp* addressof(_Tp& __r) noexcept { return std::__addressof(__r); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2598. addressof works on temporaries template const _Tp* addressof(const _Tp&&) = delete; // C++11 version of std::exchange for internal use. template inline _Tp __exchange(_Tp& __obj, _Up&& __new_val) { _Tp __old_val = std::move(__obj); __obj = std::forward<_Up>(__new_val); return __old_val; } /// @} group utilities #define _GLIBCXX_MOVE(__val) std::move(__val) #define _GLIBCXX_FORWARD(_Tp, __val) std::forward<_Tp>(__val) #else #define _GLIBCXX_MOVE(__val) (__val) #define _GLIBCXX_FORWARD(_Tp, __val) (__val) #endif /** * @addtogroup utilities * @{ */ /** * @brief Swaps two values. * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return Nothing. */ template inline #if __cplusplus >= 201103L typename enable_if<__and_<__not_<__is_tuple_like<_Tp>>, is_move_constructible<_Tp>, is_move_assignable<_Tp>>::value>::type swap(_Tp& __a, _Tp& __b) noexcept(__and_, is_nothrow_move_assignable<_Tp>>::value) #else void swap(_Tp& __a, _Tp& __b) #endif { // concept requirements __glibcxx_function_requires(_SGIAssignableConcept<_Tp>) _Tp __tmp = _GLIBCXX_MOVE(__a); __a = _GLIBCXX_MOVE(__b); __b = _GLIBCXX_MOVE(__tmp); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 809. std::swap should be overloaded for array types. /// Swap the contents of two arrays. template inline #if __cplusplus >= 201103L typename enable_if<__is_swappable<_Tp>::value>::type swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm]) noexcept(__is_nothrow_swappable<_Tp>::value) #else void swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm]) #endif { for (size_t __n = 0; __n < _Nm; ++__n) swap(__a[__n], __b[__n]); } /// @} group utilities _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _MOVE_H */ c++/8/bits/invoke.h000064400000007111151027430570007674 0ustar00// Implementation of INVOKE -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/invoke.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _GLIBCXX_INVOKE_H #define _GLIBCXX_INVOKE_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ // Used by __invoke_impl instead of std::forward<_Tp> so that a // reference_wrapper is converted to an lvalue-reference. template::type> constexpr _Up&& __invfwd(typename remove_reference<_Tp>::type& __t) noexcept { return static_cast<_Up&&>(__t); } template constexpr _Res __invoke_impl(__invoke_other, _Fn&& __f, _Args&&... __args) { return std::forward<_Fn>(__f)(std::forward<_Args>(__args)...); } template constexpr _Res __invoke_impl(__invoke_memfun_ref, _MemFun&& __f, _Tp&& __t, _Args&&... __args) { return (__invfwd<_Tp>(__t).*__f)(std::forward<_Args>(__args)...); } template constexpr _Res __invoke_impl(__invoke_memfun_deref, _MemFun&& __f, _Tp&& __t, _Args&&... __args) { return ((*std::forward<_Tp>(__t)).*__f)(std::forward<_Args>(__args)...); } template constexpr _Res __invoke_impl(__invoke_memobj_ref, _MemPtr&& __f, _Tp&& __t) { return __invfwd<_Tp>(__t).*__f; } template constexpr _Res __invoke_impl(__invoke_memobj_deref, _MemPtr&& __f, _Tp&& __t) { return (*std::forward<_Tp>(__t)).*__f; } /// Invoke a callable object. template constexpr typename __invoke_result<_Callable, _Args...>::type __invoke(_Callable&& __fn, _Args&&... __args) noexcept(__is_nothrow_invocable<_Callable, _Args...>::value) { using __result = __invoke_result<_Callable, _Args...>; using __type = typename __result::type; using __tag = typename __result::__invoke_type; return std::__invoke_impl<__type>(__tag{}, std::forward<_Callable>(__fn), std::forward<_Args>(__args)...); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_INVOKE_H c++/8/bits/list.tcc000064400000037150151027430570007704 0ustar00// List implementation (out of line) -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/list.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{list} */ #ifndef _LIST_TCC #define _LIST_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template void _List_base<_Tp, _Alloc>:: _M_clear() _GLIBCXX_NOEXCEPT { typedef _List_node<_Tp> _Node; __detail::_List_node_base* __cur = _M_impl._M_node._M_next; while (__cur != &_M_impl._M_node) { _Node* __tmp = static_cast<_Node*>(__cur); __cur = __tmp->_M_next; _Tp* __val = __tmp->_M_valptr(); #if __cplusplus >= 201103L _Node_alloc_traits::destroy(_M_get_Node_allocator(), __val); #else _Tp_alloc_type(_M_get_Node_allocator()).destroy(__val); #endif _M_put_node(__tmp); } } #if __cplusplus >= 201103L template template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: emplace(const_iterator __position, _Args&&... __args) { _Node* __tmp = _M_create_node(std::forward<_Args>(__args)...); __tmp->_M_hook(__position._M_const_cast()._M_node); this->_M_inc_size(1); return iterator(__tmp); } #endif template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { _Node* __tmp = _M_create_node(__x); __tmp->_M_hook(__position._M_const_cast()._M_node); this->_M_inc_size(1); return iterator(__tmp); } #if __cplusplus >= 201103L template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: insert(const_iterator __position, size_type __n, const value_type& __x) { if (__n) { list __tmp(__n, __x, get_allocator()); iterator __it = __tmp.begin(); splice(__position, __tmp); return __it; } return __position._M_const_cast(); } template template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { list __tmp(__first, __last, get_allocator()); if (!__tmp.empty()) { iterator __it = __tmp.begin(); splice(__position, __tmp); return __it; } return __position._M_const_cast(); } #endif template typename list<_Tp, _Alloc>::iterator list<_Tp, _Alloc>:: #if __cplusplus >= 201103L erase(const_iterator __position) noexcept #else erase(iterator __position) #endif { iterator __ret = iterator(__position._M_node->_M_next); _M_erase(__position._M_const_cast()); return __ret; } // Return a const_iterator indicating the position to start inserting or // erasing elements (depending whether the list is growing or shrinking), // and set __new_size to the number of new elements that must be appended. // Equivalent to the following, but performed optimally: // if (__new_size < size()) { // __new_size = 0; // return std::next(begin(), __new_size); // } else { // __newsize -= size(); // return end(); // } template typename list<_Tp, _Alloc>::const_iterator list<_Tp, _Alloc>:: _M_resize_pos(size_type& __new_size) const { const_iterator __i; #if _GLIBCXX_USE_CXX11_ABI const size_type __len = size(); if (__new_size < __len) { if (__new_size <= __len / 2) { __i = begin(); std::advance(__i, __new_size); } else { __i = end(); ptrdiff_t __num_erase = __len - __new_size; std::advance(__i, -__num_erase); } __new_size = 0; return __i; } else __i = end(); #else size_type __len = 0; for (__i = begin(); __i != end() && __len < __new_size; ++__i, ++__len) ; #endif __new_size -= __len; return __i; } #if __cplusplus >= 201103L template void list<_Tp, _Alloc>:: _M_default_append(size_type __n) { size_type __i = 0; __try { for (; __i < __n; ++__i) emplace_back(); } __catch(...) { for (; __i; --__i) pop_back(); __throw_exception_again; } } template void list<_Tp, _Alloc>:: resize(size_type __new_size) { const_iterator __i = _M_resize_pos(__new_size); if (__new_size) _M_default_append(__new_size); else erase(__i, end()); } template void list<_Tp, _Alloc>:: resize(size_type __new_size, const value_type& __x) { const_iterator __i = _M_resize_pos(__new_size); if (__new_size) insert(end(), __new_size, __x); else erase(__i, end()); } #else template void list<_Tp, _Alloc>:: resize(size_type __new_size, value_type __x) { const_iterator __i = _M_resize_pos(__new_size); if (__new_size) insert(end(), __new_size, __x); else erase(__i._M_const_cast(), end()); } #endif template list<_Tp, _Alloc>& list<_Tp, _Alloc>:: operator=(const list& __x) { if (this != std::__addressof(__x)) { #if __cplusplus >= 201103L if (_Node_alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_get_Node_allocator(); auto& __that_alloc = __x._M_get_Node_allocator(); if (!_Node_alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // replacement allocator cannot free existing storage clear(); } std::__alloc_on_copy(__this_alloc, __that_alloc); } #endif _M_assign_dispatch(__x.begin(), __x.end(), __false_type()); } return *this; } template void list<_Tp, _Alloc>:: _M_fill_assign(size_type __n, const value_type& __val) { iterator __i = begin(); for (; __i != end() && __n > 0; ++__i, --__n) *__i = __val; if (__n > 0) insert(end(), __n, __val); else erase(__i, end()); } template template void list<_Tp, _Alloc>:: _M_assign_dispatch(_InputIterator __first2, _InputIterator __last2, __false_type) { iterator __first1 = begin(); iterator __last1 = end(); for (; __first1 != __last1 && __first2 != __last2; ++__first1, ++__first2) *__first1 = *__first2; if (__first2 == __last2) erase(__first1, __last1); else insert(__last1, __first2, __last2); } template void list<_Tp, _Alloc>:: remove(const value_type& __value) { iterator __first = begin(); iterator __last = end(); iterator __extra = __last; while (__first != __last) { iterator __next = __first; ++__next; if (*__first == __value) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 526. Is it undefined if a function in the standard changes // in parameters? if (std::__addressof(*__first) != std::__addressof(__value)) _M_erase(__first); else __extra = __first; } __first = __next; } if (__extra != __last) _M_erase(__extra); } template void list<_Tp, _Alloc>:: unique() { iterator __first = begin(); iterator __last = end(); if (__first == __last) return; iterator __next = __first; while (++__next != __last) { if (*__first == *__next) _M_erase(__next); else __first = __next; __next = __first; } } template void list<_Tp, _Alloc>:: #if __cplusplus >= 201103L merge(list&& __x) #else merge(list& __x) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { _M_check_equal_allocators(__x); iterator __first1 = begin(); iterator __last1 = end(); iterator __first2 = __x.begin(); iterator __last2 = __x.end(); const size_t __orig_size = __x.size(); __try { while (__first1 != __last1 && __first2 != __last2) if (*__first2 < *__first1) { iterator __next = __first2; _M_transfer(__first1, __first2, ++__next); __first2 = __next; } else ++__first1; if (__first2 != __last2) _M_transfer(__last1, __first2, __last2); this->_M_inc_size(__x._M_get_size()); __x._M_set_size(0); } __catch(...) { const size_t __dist = std::distance(__first2, __last2); this->_M_inc_size(__orig_size - __dist); __x._M_set_size(__dist); __throw_exception_again; } } } template template void list<_Tp, _Alloc>:: #if __cplusplus >= 201103L merge(list&& __x, _StrictWeakOrdering __comp) #else merge(list& __x, _StrictWeakOrdering __comp) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { _M_check_equal_allocators(__x); iterator __first1 = begin(); iterator __last1 = end(); iterator __first2 = __x.begin(); iterator __last2 = __x.end(); const size_t __orig_size = __x.size(); __try { while (__first1 != __last1 && __first2 != __last2) if (__comp(*__first2, *__first1)) { iterator __next = __first2; _M_transfer(__first1, __first2, ++__next); __first2 = __next; } else ++__first1; if (__first2 != __last2) _M_transfer(__last1, __first2, __last2); this->_M_inc_size(__x._M_get_size()); __x._M_set_size(0); } __catch(...) { const size_t __dist = std::distance(__first2, __last2); this->_M_inc_size(__orig_size - __dist); __x._M_set_size(__dist); __throw_exception_again; } } } template void list<_Tp, _Alloc>:: sort() { // Do nothing if the list has length 0 or 1. if (this->_M_impl._M_node._M_next != &this->_M_impl._M_node && this->_M_impl._M_node._M_next->_M_next != &this->_M_impl._M_node) { list __carry; list __tmp[64]; list * __fill = __tmp; list * __counter; __try { do { __carry.splice(__carry.begin(), *this, begin()); for(__counter = __tmp; __counter != __fill && !__counter->empty(); ++__counter) { __counter->merge(__carry); __carry.swap(*__counter); } __carry.swap(*__counter); if (__counter == __fill) ++__fill; } while ( !empty() ); for (__counter = __tmp + 1; __counter != __fill; ++__counter) __counter->merge(*(__counter - 1)); swap( *(__fill - 1) ); } __catch(...) { this->splice(this->end(), __carry); for (int __i = 0; __i < sizeof(__tmp)/sizeof(__tmp[0]); ++__i) this->splice(this->end(), __tmp[__i]); __throw_exception_again; } } } template template void list<_Tp, _Alloc>:: remove_if(_Predicate __pred) { iterator __first = begin(); iterator __last = end(); while (__first != __last) { iterator __next = __first; ++__next; if (__pred(*__first)) _M_erase(__first); __first = __next; } } template template void list<_Tp, _Alloc>:: unique(_BinaryPredicate __binary_pred) { iterator __first = begin(); iterator __last = end(); if (__first == __last) return; iterator __next = __first; while (++__next != __last) { if (__binary_pred(*__first, *__next)) _M_erase(__next); else __first = __next; __next = __first; } } template template void list<_Tp, _Alloc>:: sort(_StrictWeakOrdering __comp) { // Do nothing if the list has length 0 or 1. if (this->_M_impl._M_node._M_next != &this->_M_impl._M_node && this->_M_impl._M_node._M_next->_M_next != &this->_M_impl._M_node) { list __carry; list __tmp[64]; list * __fill = __tmp; list * __counter; __try { do { __carry.splice(__carry.begin(), *this, begin()); for(__counter = __tmp; __counter != __fill && !__counter->empty(); ++__counter) { __counter->merge(__carry, __comp); __carry.swap(*__counter); } __carry.swap(*__counter); if (__counter == __fill) ++__fill; } while ( !empty() ); for (__counter = __tmp + 1; __counter != __fill; ++__counter) __counter->merge(*(__counter - 1), __comp); swap(*(__fill - 1)); } __catch(...) { this->splice(this->end(), __carry); for (int __i = 0; __i < sizeof(__tmp)/sizeof(__tmp[0]); ++__i) this->splice(this->end(), __tmp[__i]); __throw_exception_again; } } } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _LIST_TCC */ c++/8/bits/cxxabi_init_exception.h000064400000004254151027430570012765 0ustar00// ABI Support -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cxxabi_init_exception.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef _CXXABI_INIT_EXCEPTION_H #define _CXXABI_INIT_EXCEPTION_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #include #include #ifndef _GLIBCXX_CDTOR_CALLABI #define _GLIBCXX_CDTOR_CALLABI #define _GLIBCXX_HAVE_CDTOR_CALLABI 0 #else #define _GLIBCXX_HAVE_CDTOR_CALLABI 1 #endif #ifdef __cplusplus namespace std { class type_info; } namespace __cxxabiv1 { struct __cxa_refcounted_exception; extern "C" { // Allocate memory for the primary exception plus the thrown object. void* __cxa_allocate_exception(size_t) _GLIBCXX_NOTHROW; void __cxa_free_exception(void*) _GLIBCXX_NOTHROW; // Initialize exception (this is a GNU extension) __cxa_refcounted_exception* __cxa_init_primary_exception(void *object, std::type_info *tinfo, void (_GLIBCXX_CDTOR_CALLABI *dest) (void *)) _GLIBCXX_NOTHROW; } } // namespace __cxxabiv1 #endif #pragma GCC visibility pop #endif // _CXXABI_INIT_EXCEPTION_H c++/8/bits/regex_executor.tcc000064400000044631151027430570011763 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_executor.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_search() { if (_M_search_from_first()) return true; if (_M_flags & regex_constants::match_continuous) return false; _M_flags |= regex_constants::match_prev_avail; while (_M_begin != _M_end) { ++_M_begin; if (_M_search_from_first()) return true; } return false; } // The _M_main function operates in different modes, DFS mode or BFS mode, // indicated by template parameter __dfs_mode, and dispatches to one of the // _M_main_dispatch overloads. // // ------------------------------------------------------------ // // DFS mode: // // It applies a Depth-First-Search (aka backtracking) on given NFA and input // string. // At the very beginning the executor stands in the start state, then it // tries every possible state transition in current state recursively. Some // state transitions consume input string, say, a single-char-matcher or a // back-reference matcher; some don't, like assertion or other anchor nodes. // When the input is exhausted and/or the current state is an accepting // state, the whole executor returns true. // // TODO: This approach is exponentially slow for certain input. // Try to compile the NFA to a DFA. // // Time complexity: \Omega(match_length), O(2^(_M_nfa.size())) // Space complexity: \theta(match_results.size() + match_length) // template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_main_dispatch(_Match_mode __match_mode, __dfs) { _M_has_sol = false; *_M_states._M_get_sol_pos() = _BiIter(); _M_cur_results = _M_results; _M_dfs(__match_mode, _M_states._M_start); return _M_has_sol; } // ------------------------------------------------------------ // // BFS mode: // // Russ Cox's article (http://swtch.com/~rsc/regexp/regexp1.html) // explained this algorithm clearly. // // It first computes epsilon closure (states that can be achieved without // consuming characters) for every state that's still matching, // using the same DFS algorithm, but doesn't re-enter states (using // _M_states._M_visited to check), nor follow _S_opcode_match. // // Then apply DFS using every _S_opcode_match (in _M_states._M_match_queue) // as the start state. // // It significantly reduces potential duplicate states, so has a better // upper bound; but it requires more overhead. // // Time complexity: \Omega(match_length * match_results.size()) // O(match_length * _M_nfa.size() * match_results.size()) // Space complexity: \Omega(_M_nfa.size() + match_results.size()) // O(_M_nfa.size() * match_results.size()) template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_main_dispatch(_Match_mode __match_mode, __bfs) { _M_states._M_queue(_M_states._M_start, _M_results); bool __ret = false; while (1) { _M_has_sol = false; if (_M_states._M_match_queue.empty()) break; std::fill_n(_M_states._M_visited_states.get(), _M_nfa.size(), false); auto __old_queue = std::move(_M_states._M_match_queue); for (auto& __task : __old_queue) { _M_cur_results = std::move(__task.second); _M_dfs(__match_mode, __task.first); } if (__match_mode == _Match_mode::_Prefix) __ret |= _M_has_sol; if (_M_current == _M_end) break; ++_M_current; } if (__match_mode == _Match_mode::_Exact) __ret = _M_has_sol; _M_states._M_match_queue.clear(); return __ret; } // Return whether now match the given sub-NFA. template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_lookahead(_StateIdT __next) { // Backreferences may refer to captured content. // We may want to make this faster by not copying, // but let's not be clever prematurely. _ResultsVec __what(_M_cur_results); _Executor __sub(_M_current, _M_end, __what, _M_re, _M_flags); __sub._M_states._M_start = __next; if (__sub._M_search_from_first()) { for (size_t __i = 0; __i < __what.size(); __i++) if (__what[__i].matched) _M_cur_results[__i] = __what[__i]; return true; } return false; } // __rep_count records how many times (__rep_count.second) // this node is visited under certain input iterator // (__rep_count.first). This prevent the executor from entering // infinite loop by refusing to continue when it's already been // visited more than twice. It's `twice` instead of `once` because // we need to spare one more time for potential group capture. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_rep_once_more(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; auto& __rep_count = _M_rep_count[__i]; if (__rep_count.second == 0 || __rep_count.first != _M_current) { auto __back = __rep_count; __rep_count.first = _M_current; __rep_count.second = 1; _M_dfs(__match_mode, __state._M_alt); __rep_count = __back; } else { if (__rep_count.second < 2) { __rep_count.second++; _M_dfs(__match_mode, __state._M_alt); __rep_count.second--; } } } // _M_alt branch is "match once more", while _M_next is "get me out // of this quantifier". Executing _M_next first or _M_alt first don't // mean the same thing, and we need to choose the correct order under // given greedy mode. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_repeat(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; // Greedy. if (!__state._M_neg) { _M_rep_once_more(__match_mode, __i); // If it's DFS executor and already accepted, we're done. if (!__dfs_mode || !_M_has_sol) _M_dfs(__match_mode, __state._M_next); } else // Non-greedy mode { if (__dfs_mode) { // vice-versa. _M_dfs(__match_mode, __state._M_next); if (!_M_has_sol) _M_rep_once_more(__match_mode, __i); } else { // DON'T attempt anything, because there's already another // state with higher priority accepted. This state cannot // be better by attempting its next node. if (!_M_has_sol) { _M_dfs(__match_mode, __state._M_next); // DON'T attempt anything if it's already accepted. An // accepted state *must* be better than a solution that // matches a non-greedy quantifier one more time. if (!_M_has_sol) _M_rep_once_more(__match_mode, __i); } } } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_subexpr_begin(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; auto& __res = _M_cur_results[__state._M_subexpr]; auto __back = __res.first; __res.first = _M_current; _M_dfs(__match_mode, __state._M_next); __res.first = __back; } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_subexpr_end(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; auto& __res = _M_cur_results[__state._M_subexpr]; auto __back = __res; __res.second = _M_current; __res.matched = true; _M_dfs(__match_mode, __state._M_next); __res = __back; } template inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_line_begin_assertion(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_at_begin()) _M_dfs(__match_mode, __state._M_next); } template inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_line_end_assertion(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_at_end()) _M_dfs(__match_mode, __state._M_next); } template inline void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_word_boundary(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_word_boundary() == !__state._M_neg) _M_dfs(__match_mode, __state._M_next); } // Here __state._M_alt offers a single start node for a sub-NFA. // We recursively invoke our algorithm to match the sub-NFA. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_subexpr_lookahead(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_lookahead(__state._M_alt) == !__state._M_neg) _M_dfs(__match_mode, __state._M_next); } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_match(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_current == _M_end) return; if (__dfs_mode) { if (__state._M_matches(*_M_current)) { ++_M_current; _M_dfs(__match_mode, __state._M_next); --_M_current; } } else if (__state._M_matches(*_M_current)) _M_states._M_queue(__state._M_next, _M_cur_results); } template struct _Backref_matcher { _Backref_matcher(bool __icase, const _TraitsT& __traits) : _M_traits(__traits) { } bool _M_apply(_BiIter __expected_begin, _BiIter __expected_end, _BiIter __actual_begin, _BiIter __actual_end) { return _M_traits.transform(__expected_begin, __expected_end) == _M_traits.transform(__actual_begin, __actual_end); } const _TraitsT& _M_traits; }; template struct _Backref_matcher<_BiIter, std::regex_traits<_CharT>> { using _TraitsT = std::regex_traits<_CharT>; _Backref_matcher(bool __icase, const _TraitsT& __traits) : _M_icase(__icase), _M_traits(__traits) { } bool _M_apply(_BiIter __expected_begin, _BiIter __expected_end, _BiIter __actual_begin, _BiIter __actual_end) { if (!_M_icase) return _GLIBCXX_STD_A::__equal4(__expected_begin, __expected_end, __actual_begin, __actual_end); typedef std::ctype<_CharT> __ctype_type; const auto& __fctyp = use_facet<__ctype_type>(_M_traits.getloc()); return _GLIBCXX_STD_A::__equal4(__expected_begin, __expected_end, __actual_begin, __actual_end, [this, &__fctyp](_CharT __lhs, _CharT __rhs) { return __fctyp.tolower(__lhs) == __fctyp.tolower(__rhs); }); } bool _M_icase; const _TraitsT& _M_traits; }; // First fetch the matched result from _M_cur_results as __submatch; // then compare it with // (_M_current, _M_current + (__submatch.second - __submatch.first)). // If matched, keep going; else just return and try another state. template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_backref(_Match_mode __match_mode, _StateIdT __i) { __glibcxx_assert(__dfs_mode); const auto& __state = _M_nfa[__i]; auto& __submatch = _M_cur_results[__state._M_backref_index]; if (!__submatch.matched) return; auto __last = _M_current; for (auto __tmp = __submatch.first; __last != _M_end && __tmp != __submatch.second; ++__tmp) ++__last; if (_Backref_matcher<_BiIter, _TraitsT>( _M_re.flags() & regex_constants::icase, _M_re._M_automaton->_M_traits)._M_apply( __submatch.first, __submatch.second, _M_current, __last)) { if (__last != _M_current) { auto __backup = _M_current; _M_current = __last; _M_dfs(__match_mode, __state._M_next); _M_current = __backup; } else _M_dfs(__match_mode, __state._M_next); } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_accept(_Match_mode __match_mode, _StateIdT __i) { if (__dfs_mode) { __glibcxx_assert(!_M_has_sol); if (__match_mode == _Match_mode::_Exact) _M_has_sol = _M_current == _M_end; else _M_has_sol = true; if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_null)) _M_has_sol = false; if (_M_has_sol) { if (_M_nfa._M_flags & regex_constants::ECMAScript) _M_results = _M_cur_results; else // POSIX { __glibcxx_assert(_M_states._M_get_sol_pos()); // Here's POSIX's logic: match the longest one. However // we never know which one (lhs or rhs of "|") is longer // unless we try both of them and compare the results. // The member variable _M_sol_pos records the end // position of the last successful match. It's better // to be larger, because POSIX regex is always greedy. // TODO: This could be slow. if (*_M_states._M_get_sol_pos() == _BiIter() || std::distance(_M_begin, *_M_states._M_get_sol_pos()) < std::distance(_M_begin, _M_current)) { *_M_states._M_get_sol_pos() = _M_current; _M_results = _M_cur_results; } } } } else { if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_null)) return; if (__match_mode == _Match_mode::_Prefix || _M_current == _M_end) if (!_M_has_sol) { _M_has_sol = true; _M_results = _M_cur_results; } } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_handle_alternative(_Match_mode __match_mode, _StateIdT __i) { const auto& __state = _M_nfa[__i]; if (_M_nfa._M_flags & regex_constants::ECMAScript) { // TODO: Fix BFS support. It is wrong. _M_dfs(__match_mode, __state._M_alt); // Pick lhs if it matches. Only try rhs if it doesn't. if (!_M_has_sol) _M_dfs(__match_mode, __state._M_next); } else { // Try both and compare the result. // See "case _S_opcode_accept:" handling above. _M_dfs(__match_mode, __state._M_alt); auto __has_sol = _M_has_sol; _M_has_sol = false; _M_dfs(__match_mode, __state._M_next); _M_has_sol |= __has_sol; } } template void _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_dfs(_Match_mode __match_mode, _StateIdT __i) { if (_M_states._M_visited(__i)) return; switch (_M_nfa[__i]._M_opcode()) { case _S_opcode_repeat: _M_handle_repeat(__match_mode, __i); break; case _S_opcode_subexpr_begin: _M_handle_subexpr_begin(__match_mode, __i); break; case _S_opcode_subexpr_end: _M_handle_subexpr_end(__match_mode, __i); break; case _S_opcode_line_begin_assertion: _M_handle_line_begin_assertion(__match_mode, __i); break; case _S_opcode_line_end_assertion: _M_handle_line_end_assertion(__match_mode, __i); break; case _S_opcode_word_boundary: _M_handle_word_boundary(__match_mode, __i); break; case _S_opcode_subexpr_lookahead: _M_handle_subexpr_lookahead(__match_mode, __i); break; case _S_opcode_match: _M_handle_match(__match_mode, __i); break; case _S_opcode_backref: _M_handle_backref(__match_mode, __i); break; case _S_opcode_accept: _M_handle_accept(__match_mode, __i); break; case _S_opcode_alternative: _M_handle_alternative(__match_mode, __i); break; default: __glibcxx_assert(false); } } // Return whether now is at some word boundary. template bool _Executor<_BiIter, _Alloc, _TraitsT, __dfs_mode>:: _M_word_boundary() const { if (_M_current == _M_begin && (_M_flags & regex_constants::match_not_bow)) return false; if (_M_current == _M_end && (_M_flags & regex_constants::match_not_eow)) return false; bool __left_is_word = false; if (_M_current != _M_begin || (_M_flags & regex_constants::match_prev_avail)) { auto __prev = _M_current; if (_M_is_word(*std::prev(__prev))) __left_is_word = true; } bool __right_is_word = _M_current != _M_end && _M_is_word(*_M_current); return __left_is_word != __right_is_word; } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/bits/stringfwd.h000064400000005057151027430570010417 0ustar00// Forward declarations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/stringfwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // #ifndef _STRINGFWD_H #define _STRINGFWD_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup strings Strings * * @{ */ template struct char_traits; template<> struct char_traits; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct char_traits; #endif #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) template<> struct char_traits; template<> struct char_traits; #endif _GLIBCXX_BEGIN_NAMESPACE_CXX11 template, typename _Alloc = allocator<_CharT> > class basic_string; /// A string of @c char typedef basic_string string; #ifdef _GLIBCXX_USE_WCHAR_T /// A string of @c wchar_t typedef basic_string wstring; #endif #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) /// A string of @c char16_t typedef basic_string u16string; /// A string of @c char32_t typedef basic_string u32string; #endif _GLIBCXX_END_NAMESPACE_CXX11 /** @} */ _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _STRINGFWD_H c++/8/bits/unordered_set.h000064400000163414151027430570011254 0ustar00// unordered_set implementation -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/unordered_set.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{unordered_set} */ #ifndef _UNORDERED_SET_H #define _UNORDERED_SET_H namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// Base types for unordered_set. template using __uset_traits = __detail::_Hashtable_traits<_Cache, true, true>; template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value>, typename _Tr = __uset_traits<__cache_default<_Value, _Hash>::value>> using __uset_hashtable = _Hashtable<_Value, _Value, _Alloc, __detail::_Identity, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; /// Base types for unordered_multiset. template using __umset_traits = __detail::_Hashtable_traits<_Cache, true, false>; template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value>, typename _Tr = __umset_traits<__cache_default<_Value, _Hash>::value>> using __umset_hashtable = _Hashtable<_Value, _Value, _Alloc, __detail::_Identity, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; template class unordered_multiset; /** * @brief A standard container composed of unique keys (containing * at most one of each key value) in which the elements' keys are * the elements themselves. * * @ingroup unordered_associative_containers * * @tparam _Value Type of key objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults to * equal_to<_Value>. * * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, and * unordered associative container * * Base is _Hashtable, dispatched at compile time via template * alias __uset_hashtable. */ template, typename _Pred = equal_to<_Value>, typename _Alloc = allocator<_Value>> class unordered_set { typedef __uset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; using insert_return_type = typename _Hashtable::insert_return_type; #endif // construct/destroy/copy /// Default constructor. unordered_set() = default; /** * @brief Default constructor creates no elements. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_set(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_set from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_set consisting of copies of the elements from * [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_set(const unordered_set&) = default; /// Move constructor. unordered_set(unordered_set&&) = default; /** * @brief Creates an %unordered_set with no elements. * @param __a An allocator object. */ explicit unordered_set(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_set to copy. * @param __a An allocator object. */ unordered_set(const unordered_set& __uset, const allocator_type& __a) : _M_h(__uset._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __uset Input %unordered_set to move. * @param __a An allocator object. */ unordered_set(unordered_set&& __uset, const allocator_type& __a) : _M_h(std::move(__uset._M_h), __a) { } /** * @brief Builds an %unordered_set from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_set consisting of copies of the elements in the * list. This is linear in N (where N is @a __l.size()). */ unordered_set(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } unordered_set(size_type __n, const allocator_type& __a) : unordered_set(__n, hasher(), key_equal(), __a) { } unordered_set(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__n, __hf, key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_set(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__first, __last, __n, __hf, key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_set(__l, __n, hasher(), key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__l, __n, __hf, key_equal(), __a) { } /// Copy assignment operator. unordered_set& operator=(const unordered_set&) = default; /// Move assignment operator. unordered_set& operator=(unordered_set&&) = default; /** * @brief %Unordered_set list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_set with copies of the elements in * the initializer list @a __l. * * Note that the assignment completely changes the %unordered_set and * that the resulting %unordered_set's size is the same as the number * of elements assigned. */ unordered_set& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_set. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_set is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_set. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_set. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_set. */ iterator begin() noexcept { return _M_h.begin(); } const_iterator begin() const noexcept { return _M_h.begin(); } //@} //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_set. */ iterator end() noexcept { return _M_h.end(); } const_iterator end() const noexcept { return _M_h.end(); } //@} /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_set. */ const_iterator cbegin() const noexcept { return _M_h.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_set. */ const_iterator cend() const noexcept { return _M_h.end(); } // modifiers. /** * @brief Attempts to build and insert an element into the * %unordered_set. * @param __args Arguments used to generate an element. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to build and insert an element into the * %unordered_set. An %unordered_set relies on unique keys and thus an * element is only inserted if it is not already present in the * %unordered_set. * * Insertion requires amortized constant time. */ template std::pair emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Attempts to insert an element into the %unordered_set. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element to be * inserted. * @return An iterator that points to the element with key equivalent to * the one generated from @a __args (may or may not be the * element itself). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } //@{ /** * @brief Attempts to insert an element into the %unordered_set. * @param __x Element to be inserted. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to insert an element into the %unordered_set. * An %unordered_set relies on unique keys and thus an element is only * inserted if it is not already present in the %unordered_set. * * Insertion requires amortized constant time. */ std::pair insert(const value_type& __x) { return _M_h.insert(__x); } std::pair insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } //@} //@{ /** * @brief Attempts to insert an element into the %unordered_set. * @param __hint An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the element with key of * @a __x (may or may not be the element passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } //@} /** * @brief A template function that attempts to insert a range of * elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Attempts to insert a list of elements into the %unordered_set. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator, node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)).position; } #endif // C++17 //@{ /** * @brief Erases an element from an %unordered_set. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_set. Note that this function only erases the * element, and that if the element is itself a pointer, the pointed-to * memory is not touched in any way. Managing the pointer is the user's * responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_set. For an %unordered_set the result of this function * can only be 0 (not present) or 1 (present). * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_set. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an %unordered_set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_set. Note that this function only * erases the elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_set. * @param __x An %unordered_set of the same element and allocator * types. * * This exchanges the elements between two sets in constant time. * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. */ void swap(unordered_set& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_set<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_set<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_set was /// constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_set was /// constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_set. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Element to located. * @return Number of elements with specified key. * * This function only makes sense for unordered_multisets; for * unordered_set the result will either be 0 (not present) or 1 * (present). */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function probably only makes sense for multisets. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_set. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_set. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_set tries to keep the /// load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_set maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_set. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_set maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_set for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_set<_Value1, _Hash1, _Pred1, _Alloc1>&, const unordered_set<_Value1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_set(initializer_list<_Tp>, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Allocator) -> unordered_set::value_type, hash< typename iterator_traits<_InputIterator>::value_type>, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Hash, _Allocator) -> unordered_set::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Allocator) -> unordered_set<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Hash, _Allocator) -> unordered_set<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif /** * @brief A standard container composed of equivalent keys * (possibly containing multiple of each key value) in which the * elements' keys are the elements themselves. * * @ingroup unordered_associative_containers * * @tparam _Value Type of key objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults * to equal_to<_Value>. * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, and * unordered associative container * * Base is _Hashtable, dispatched at compile time via template * alias __umset_hashtable. */ template, typename _Pred = equal_to<_Value>, typename _Alloc = allocator<_Value>> class unordered_multiset { typedef __umset_hashtable<_Value, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; #endif // construct/destroy/copy /// Default constructor. unordered_multiset() = default; /** * @brief Default constructor creates no elements. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_multiset(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_multiset from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multiset consisting of copies of the elements * from [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_multiset(const unordered_multiset&) = default; /// Move constructor. unordered_multiset(unordered_multiset&&) = default; /** * @brief Builds an %unordered_multiset from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multiset consisting of copies of the elements in * the list. This is linear in N (where N is @a __l.size()). */ unordered_multiset(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } /// Copy assignment operator. unordered_multiset& operator=(const unordered_multiset&) = default; /// Move assignment operator. unordered_multiset& operator=(unordered_multiset&&) = default; /** * @brief Creates an %unordered_multiset with no elements. * @param __a An allocator object. */ explicit unordered_multiset(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_multiset to copy. * @param __a An allocator object. */ unordered_multiset(const unordered_multiset& __umset, const allocator_type& __a) : _M_h(__umset._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __umset Input %unordered_multiset to move. * @param __a An allocator object. */ unordered_multiset(unordered_multiset&& __umset, const allocator_type& __a) : _M_h(std::move(__umset._M_h), __a) { } unordered_multiset(size_type __n, const allocator_type& __a) : unordered_multiset(__n, hasher(), key_equal(), __a) { } unordered_multiset(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__n, __hf, key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multiset(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multiset(__l, __n, hasher(), key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__l, __n, __hf, key_equal(), __a) { } /** * @brief %Unordered_multiset list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_multiset with copies of the elements * in the initializer list @a __l. * * Note that the assignment completely changes the %unordered_multiset * and that the resulting %unordered_multiset's size is the same as the * number of elements assigned. */ unordered_multiset& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_multiset. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_multiset is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_multiset. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_multiset. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_multiset. */ iterator begin() noexcept { return _M_h.begin(); } const_iterator begin() const noexcept { return _M_h.begin(); } //@} //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_multiset. */ iterator end() noexcept { return _M_h.end(); } const_iterator end() const noexcept { return _M_h.end(); } //@} /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_multiset. */ const_iterator cbegin() const noexcept { return _M_h.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_multiset. */ const_iterator cend() const noexcept { return _M_h.end(); } // modifiers. /** * @brief Builds and insert an element into the %unordered_multiset. * @param __args Arguments used to generate an element. * @return An iterator that points to the inserted element. * * Insertion requires amortized constant time. */ template iterator emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Inserts an element into the %unordered_multiset. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element to be * inserted. * @return An iterator that points to the inserted element. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } //@{ /** * @brief Inserts an element into the %unordered_multiset. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * Insertion requires amortized constant time. */ iterator insert(const value_type& __x) { return _M_h.insert(__x); } iterator insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } //@} //@{ /** * @brief Inserts an element into the %unordered_multiset. * @param __hint An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires amortized constant. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } //@} /** * @brief A template function that inserts a range of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Inserts a list of elements into the %unordered_multiset. * @param __l A std::initializer_list of elements to be * inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_h._M_reinsert_node_multi(cend(), std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_h._M_reinsert_node_multi(__hint, std::move(__nh)); } #endif // C++17 //@{ /** * @brief Erases an element from an %unordered_multiset. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_multiset. * * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_multiset. * * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_multiset. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an * %unordered_multiset. * * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_multiset. * * Note that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_multiset. * @param __x An %unordered_multiset of the same element and allocator * types. * * This exchanges the elements between two sets in constant time. * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. */ void swap(unordered_multiset& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multiset<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_set<_Value, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_set<_Value, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_multiset /// was constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_multiset /// was constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_multiset. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Element to located. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_multiset. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_multiset. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_multiset tries to keep the /// load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_multiset maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_multiset. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_multiset maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_multiset for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_multiset<_Value1, _Hash1, _Pred1, _Alloc1>&, const unordered_multiset<_Value1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Allocator) -> unordered_multiset::value_type, hash::value_type>, equal_to::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Allocator) -> unordered_multiset<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif template inline void swap(unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline void swap(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } template inline bool operator==(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::unordered_set access to internals of compatible sets. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_set<_Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_set = _GLIBCXX_STD_C::unordered_set<_Tp...>; template using unordered_multiset = _GLIBCXX_STD_C::unordered_multiset<_Tp...>; friend unordered_set<_Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_set<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } static auto& _S_get_table(unordered_multiset<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } }; // Allow std::unordered_multiset access to internals of compatible sets. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_multiset<_Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_set = _GLIBCXX_STD_C::unordered_set<_Tp...>; template using unordered_multiset = _GLIBCXX_STD_C::unordered_multiset<_Tp...>; friend unordered_multiset<_Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_set<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } static auto& _S_get_table(unordered_multiset<_Val, _Hash2, _Eq2, _Alloc>& __set) { return __set._M_h; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _UNORDERED_SET_H */ c++/8/bits/locale_classes.tcc000064400000020267151027430570011706 0ustar00// Locale support -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_classes.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_CLASSES_TCC #define _LOCALE_CLASSES_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template locale:: locale(const locale& __other, _Facet* __f) { _M_impl = new _Impl(*__other._M_impl, 1); __try { _M_impl->_M_install_facet(&_Facet::id, __f); } __catch(...) { _M_impl->_M_remove_reference(); __throw_exception_again; } delete [] _M_impl->_M_names[0]; _M_impl->_M_names[0] = 0; // Unnamed. } template locale locale:: combine(const locale& __other) const { _Impl* __tmp = new _Impl(*_M_impl, 1); __try { __tmp->_M_replace_facet(__other._M_impl, &_Facet::id); } __catch(...) { __tmp->_M_remove_reference(); __throw_exception_again; } return locale(__tmp); } template bool locale:: operator()(const basic_string<_CharT, _Traits, _Alloc>& __s1, const basic_string<_CharT, _Traits, _Alloc>& __s2) const { typedef std::collate<_CharT> __collate_type; const __collate_type& __collate = use_facet<__collate_type>(*this); return (__collate.compare(__s1.data(), __s1.data() + __s1.length(), __s2.data(), __s2.data() + __s2.length()) < 0); } /** * @brief Test for the presence of a facet. * @ingroup locales * * has_facet tests the locale argument for the presence of the facet type * provided as the template parameter. Facets derived from the facet * parameter will also return true. * * @tparam _Facet The facet type to test the presence of. * @param __loc The locale to test. * @return true if @p __loc contains a facet of type _Facet, else false. */ template bool has_facet(const locale& __loc) throw() { const size_t __i = _Facet::id._M_id(); const locale::facet** __facets = __loc._M_impl->_M_facets; return (__i < __loc._M_impl->_M_facets_size #if __cpp_rtti && dynamic_cast(__facets[__i])); #else && static_cast(__facets[__i])); #endif } /** * @brief Return a facet. * @ingroup locales * * use_facet looks for and returns a reference to a facet of type Facet * where Facet is the template parameter. If has_facet(locale) is true, * there is a suitable facet to return. It throws std::bad_cast if the * locale doesn't contain a facet of type Facet. * * @tparam _Facet The facet type to access. * @param __loc The locale to use. * @return Reference to facet of type Facet. * @throw std::bad_cast if @p __loc doesn't contain a facet of type _Facet. */ template const _Facet& use_facet(const locale& __loc) { const size_t __i = _Facet::id._M_id(); const locale::facet** __facets = __loc._M_impl->_M_facets; if (__i >= __loc._M_impl->_M_facets_size || !__facets[__i]) __throw_bad_cast(); #if __cpp_rtti return dynamic_cast(*__facets[__i]); #else return static_cast(*__facets[__i]); #endif } // Generic version does nothing. template int collate<_CharT>::_M_compare(const _CharT*, const _CharT*) const throw () { return 0; } // Generic version does nothing. template size_t collate<_CharT>::_M_transform(_CharT*, const _CharT*, size_t) const throw () { return 0; } template int collate<_CharT>:: do_compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const { // strcoll assumes zero-terminated strings so we make a copy // and then put a zero at the end. const string_type __one(__lo1, __hi1); const string_type __two(__lo2, __hi2); const _CharT* __p = __one.c_str(); const _CharT* __pend = __one.data() + __one.length(); const _CharT* __q = __two.c_str(); const _CharT* __qend = __two.data() + __two.length(); // strcoll stops when it sees a nul character so we break // the strings into zero-terminated substrings and pass those // to strcoll. for (;;) { const int __res = _M_compare(__p, __q); if (__res) return __res; __p += char_traits<_CharT>::length(__p); __q += char_traits<_CharT>::length(__q); if (__p == __pend && __q == __qend) return 0; else if (__p == __pend) return -1; else if (__q == __qend) return 1; __p++; __q++; } } template typename collate<_CharT>::string_type collate<_CharT>:: do_transform(const _CharT* __lo, const _CharT* __hi) const { string_type __ret; // strxfrm assumes zero-terminated strings so we make a copy const string_type __str(__lo, __hi); const _CharT* __p = __str.c_str(); const _CharT* __pend = __str.data() + __str.length(); size_t __len = (__hi - __lo) * 2; _CharT* __c = new _CharT[__len]; __try { // strxfrm stops when it sees a nul character so we break // the string into zero-terminated substrings and pass those // to strxfrm. for (;;) { // First try a buffer perhaps big enough. size_t __res = _M_transform(__c, __p, __len); // If the buffer was not large enough, try again with the // correct size. if (__res >= __len) { __len = __res + 1; delete [] __c, __c = 0; __c = new _CharT[__len]; __res = _M_transform(__c, __p, __len); } __ret.append(__c, __res); __p += char_traits<_CharT>::length(__p); if (__p == __pend) break; __p++; __ret.push_back(_CharT()); } } __catch(...) { delete [] __c; __throw_exception_again; } delete [] __c; return __ret; } template long collate<_CharT>:: do_hash(const _CharT* __lo, const _CharT* __hi) const { unsigned long __val = 0; for (; __lo < __hi; ++__lo) __val = *__lo + ((__val << 7) | (__val >> (__gnu_cxx::__numeric_traits:: __digits - 7))); return static_cast(__val); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class collate; extern template class collate_byname; extern template const collate& use_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class collate; extern template class collate_byname; extern template const collate& use_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/c++0x_warning.h000064400000002702151027430570010747 0ustar00// Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++0x_warning.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _CXX0X_WARNING_H #define _CXX0X_WARNING_H 1 #if __cplusplus < 201103L #error This file requires compiler and library support \ for the ISO C++ 2011 standard. This support must be enabled \ with the -std=c++11 or -std=gnu++11 compiler options. #endif #endif c++/8/bits/stl_algobase.h000064400000142476151027430570011056 0ustar00// Core algorithmic facilities -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_algobase.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{algorithm} */ #ifndef _STL_ALGOBASE_H #define _STL_ALGOBASE_H 1 #include #include #include #include #include #include #include #include #include #include #include #include // For std::swap #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus < 201103L // See http://gcc.gnu.org/ml/libstdc++/2004-08/msg00167.html: in a // nutshell, we are partially implementing the resolution of DR 187, // when it's safe, i.e., the value_types are equal. template struct __iter_swap { template static void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) { typedef typename iterator_traits<_ForwardIterator1>::value_type _ValueType1; _ValueType1 __tmp = *__a; *__a = *__b; *__b = __tmp; } }; template<> struct __iter_swap { template static void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) { swap(*__a, *__b); } }; #endif /** * @brief Swaps the contents of two iterators. * @ingroup mutating_algorithms * @param __a An iterator. * @param __b Another iterator. * @return Nothing. * * This function swaps the values pointed to by two iterators, not the * iterators themselves. */ template inline void iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator1>) __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator2>) #if __cplusplus < 201103L typedef typename iterator_traits<_ForwardIterator1>::value_type _ValueType1; typedef typename iterator_traits<_ForwardIterator2>::value_type _ValueType2; __glibcxx_function_requires(_ConvertibleConcept<_ValueType1, _ValueType2>) __glibcxx_function_requires(_ConvertibleConcept<_ValueType2, _ValueType1>) typedef typename iterator_traits<_ForwardIterator1>::reference _ReferenceType1; typedef typename iterator_traits<_ForwardIterator2>::reference _ReferenceType2; std::__iter_swap<__are_same<_ValueType1, _ValueType2>::__value && __are_same<_ValueType1&, _ReferenceType1>::__value && __are_same<_ValueType2&, _ReferenceType2>::__value>:: iter_swap(__a, __b); #else swap(*__a, *__b); #endif } /** * @brief Swap the elements of two sequences. * @ingroup mutating_algorithms * @param __first1 A forward iterator. * @param __last1 A forward iterator. * @param __first2 A forward iterator. * @return An iterator equal to @p first2+(last1-first1). * * Swaps each element in the range @p [first1,last1) with the * corresponding element in the range @p [first2,(last1-first1)). * The ranges must not overlap. */ template _ForwardIterator2 swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator1>) __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) std::iter_swap(__first1, __first2); return __first2; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return The lesser of the parameters. * * This is the simple classic generic implementation. It will work on * temporary expressions, since they are only evaluated once, unlike a * preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& min(const _Tp& __a, const _Tp& __b) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) //return __b < __a ? __b : __a; if (__b < __a) return __b; return __a; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @return The greater of the parameters. * * This is the simple classic generic implementation. It will work on * temporary expressions, since they are only evaluated once, unlike a * preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& max(const _Tp& __a, const _Tp& __b) { // concept requirements __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) //return __a < __b ? __b : __a; if (__a < __b) return __b; return __a; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @param __comp A @link comparison_functors comparison functor@endlink. * @return The lesser of the parameters. * * This will work on temporary expressions, since they are only evaluated * once, unlike a preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& min(const _Tp& __a, const _Tp& __b, _Compare __comp) { //return __comp(__b, __a) ? __b : __a; if (__comp(__b, __a)) return __b; return __a; } /** * @brief This does what you think it does. * @ingroup sorting_algorithms * @param __a A thing of arbitrary type. * @param __b Another thing of arbitrary type. * @param __comp A @link comparison_functors comparison functor@endlink. * @return The greater of the parameters. * * This will work on temporary expressions, since they are only evaluated * once, unlike a preprocessor macro. */ template _GLIBCXX14_CONSTEXPR inline const _Tp& max(const _Tp& __a, const _Tp& __b, _Compare __comp) { //return __comp(__a, __b) ? __b : __a; if (__comp(__a, __b)) return __b; return __a; } // Fallback implementation of the function in bits/stl_iterator.h used to // remove the __normal_iterator wrapper. See copy, fill, ... template inline _Iterator __niter_base(_Iterator __it) { return __it; } // All of these auxiliary structs serve two purposes. (1) Replace // calls to copy with memmove whenever possible. (Memmove, not memcpy, // because the input and output ranges are permitted to overlap.) // (2) If we're using random access iterators, then write the loop as // a for loop with an explicit count. template struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { for (; __first != __last; ++__result, (void)++__first) *__result = *__first; return __result; } }; #if __cplusplus >= 201103L template struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { for (; __first != __last; ++__result, (void)++__first) *__result = std::move(*__first); return __result; } }; #endif template<> struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { typedef typename iterator_traits<_II>::difference_type _Distance; for(_Distance __n = __last - __first; __n > 0; --__n) { *__result = *__first; ++__first; ++__result; } return __result; } }; #if __cplusplus >= 201103L template<> struct __copy_move { template static _OI __copy_m(_II __first, _II __last, _OI __result) { typedef typename iterator_traits<_II>::difference_type _Distance; for(_Distance __n = __last - __first; __n > 0; --__n) { *__result = std::move(*__first); ++__first; ++__result; } return __result; } }; #endif template struct __copy_move<_IsMove, true, random_access_iterator_tag> { template static _Tp* __copy_m(const _Tp* __first, const _Tp* __last, _Tp* __result) { #if __cplusplus >= 201103L using __assignable = conditional<_IsMove, is_move_assignable<_Tp>, is_copy_assignable<_Tp>>; // trivial types can have deleted assignment static_assert( __assignable::type::value, "type is not assignable" ); #endif const ptrdiff_t _Num = __last - __first; if (_Num) __builtin_memmove(__result, __first, sizeof(_Tp) * _Num); return __result + _Num; } }; template inline _OI __copy_move_a(_II __first, _II __last, _OI __result) { typedef typename iterator_traits<_II>::value_type _ValueTypeI; typedef typename iterator_traits<_OI>::value_type _ValueTypeO; typedef typename iterator_traits<_II>::iterator_category _Category; const bool __simple = (__is_trivial(_ValueTypeI) && __is_pointer<_II>::__value && __is_pointer<_OI>::__value && __are_same<_ValueTypeI, _ValueTypeO>::__value); return std::__copy_move<_IsMove, __simple, _Category>::__copy_m(__first, __last, __result); } // Helpers for streambuf iterators (either istream or ostream). // NB: avoid including , relatively large. template struct char_traits; template class istreambuf_iterator; template class ostreambuf_iterator; template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type __copy_move_a2(_CharT*, _CharT*, ostreambuf_iterator<_CharT, char_traits<_CharT> >); template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type __copy_move_a2(const _CharT*, const _CharT*, ostreambuf_iterator<_CharT, char_traits<_CharT> >); template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, _CharT*>::__type __copy_move_a2(istreambuf_iterator<_CharT, char_traits<_CharT> >, istreambuf_iterator<_CharT, char_traits<_CharT> >, _CharT*); template inline _OI __copy_move_a2(_II __first, _II __last, _OI __result) { return _OI(std::__copy_move_a<_IsMove>(std::__niter_base(__first), std::__niter_base(__last), std::__niter_base(__result))); } /** * @brief Copies the range [first,last) into result. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return result + (first - last) * * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). Result may not be contained within * [first,last); the copy_backward function should be used instead. * * Note that the end of the output range is permitted to be contained * within [first,last). */ template inline _OI copy(_II __first, _II __last, _OI __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II>) __glibcxx_function_requires(_OutputIteratorConcept<_OI, typename iterator_traits<_II>::value_type>) __glibcxx_requires_valid_range(__first, __last); return (std::__copy_move_a2<__is_move_iterator<_II>::__value> (std::__miter_base(__first), std::__miter_base(__last), __result)); } #if __cplusplus >= 201103L /** * @brief Moves the range [first,last) into result. * @ingroup mutating_algorithms * @param __first An input iterator. * @param __last An input iterator. * @param __result An output iterator. * @return result + (first - last) * * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). Result may not be contained within * [first,last); the move_backward function should be used instead. * * Note that the end of the output range is permitted to be contained * within [first,last). */ template inline _OI move(_II __first, _II __last, _OI __result) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II>) __glibcxx_function_requires(_OutputIteratorConcept<_OI, typename iterator_traits<_II>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__copy_move_a2(std::__miter_base(__first), std::__miter_base(__last), __result); } #define _GLIBCXX_MOVE3(_Tp, _Up, _Vp) std::move(_Tp, _Up, _Vp) #else #define _GLIBCXX_MOVE3(_Tp, _Up, _Vp) std::copy(_Tp, _Up, _Vp) #endif template struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { while (__first != __last) *--__result = *--__last; return __result; } }; #if __cplusplus >= 201103L template struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { while (__first != __last) *--__result = std::move(*--__last); return __result; } }; #endif template<> struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { typename iterator_traits<_BI1>::difference_type __n; for (__n = __last - __first; __n > 0; --__n) *--__result = *--__last; return __result; } }; #if __cplusplus >= 201103L template<> struct __copy_move_backward { template static _BI2 __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) { typename iterator_traits<_BI1>::difference_type __n; for (__n = __last - __first; __n > 0; --__n) *--__result = std::move(*--__last); return __result; } }; #endif template struct __copy_move_backward<_IsMove, true, random_access_iterator_tag> { template static _Tp* __copy_move_b(const _Tp* __first, const _Tp* __last, _Tp* __result) { #if __cplusplus >= 201103L using __assignable = conditional<_IsMove, is_move_assignable<_Tp>, is_copy_assignable<_Tp>>; // trivial types can have deleted assignment static_assert( __assignable::type::value, "type is not assignable" ); #endif const ptrdiff_t _Num = __last - __first; if (_Num) __builtin_memmove(__result - _Num, __first, sizeof(_Tp) * _Num); return __result - _Num; } }; template inline _BI2 __copy_move_backward_a(_BI1 __first, _BI1 __last, _BI2 __result) { typedef typename iterator_traits<_BI1>::value_type _ValueType1; typedef typename iterator_traits<_BI2>::value_type _ValueType2; typedef typename iterator_traits<_BI1>::iterator_category _Category; const bool __simple = (__is_trivial(_ValueType1) && __is_pointer<_BI1>::__value && __is_pointer<_BI2>::__value && __are_same<_ValueType1, _ValueType2>::__value); return std::__copy_move_backward<_IsMove, __simple, _Category>::__copy_move_b(__first, __last, __result); } template inline _BI2 __copy_move_backward_a2(_BI1 __first, _BI1 __last, _BI2 __result) { return _BI2(std::__copy_move_backward_a<_IsMove> (std::__niter_base(__first), std::__niter_base(__last), std::__niter_base(__result))); } /** * @brief Copies the range [first,last) into result. * @ingroup mutating_algorithms * @param __first A bidirectional iterator. * @param __last A bidirectional iterator. * @param __result A bidirectional iterator. * @return result - (first - last) * * The function has the same effect as copy, but starts at the end of the * range and works its way to the start, returning the start of the result. * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). * * Result may not be in the range (first,last]. Use copy instead. Note * that the start of the output range may overlap [first,last). */ template inline _BI2 copy_backward(_BI1 __first, _BI1 __last, _BI2 __result) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>) __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>) __glibcxx_function_requires(_ConvertibleConcept< typename iterator_traits<_BI1>::value_type, typename iterator_traits<_BI2>::value_type>) __glibcxx_requires_valid_range(__first, __last); return (std::__copy_move_backward_a2<__is_move_iterator<_BI1>::__value> (std::__miter_base(__first), std::__miter_base(__last), __result)); } #if __cplusplus >= 201103L /** * @brief Moves the range [first,last) into result. * @ingroup mutating_algorithms * @param __first A bidirectional iterator. * @param __last A bidirectional iterator. * @param __result A bidirectional iterator. * @return result - (first - last) * * The function has the same effect as move, but starts at the end of the * range and works its way to the start, returning the start of the result. * This inline function will boil down to a call to @c memmove whenever * possible. Failing that, if random access iterators are passed, then the * loop count will be known (and therefore a candidate for compiler * optimizations such as unrolling). * * Result may not be in the range (first,last]. Use move instead. Note * that the start of the output range may overlap [first,last). */ template inline _BI2 move_backward(_BI1 __first, _BI1 __last, _BI2 __result) { // concept requirements __glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>) __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>) __glibcxx_function_requires(_ConvertibleConcept< typename iterator_traits<_BI1>::value_type, typename iterator_traits<_BI2>::value_type>) __glibcxx_requires_valid_range(__first, __last); return std::__copy_move_backward_a2(std::__miter_base(__first), std::__miter_base(__last), __result); } #define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp) std::move_backward(_Tp, _Up, _Vp) #else #define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp) std::copy_backward(_Tp, _Up, _Vp) #endif template inline typename __gnu_cxx::__enable_if::__value, void>::__type __fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { for (; __first != __last; ++__first) *__first = __value; } template inline typename __gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, void>::__type __fill_a(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { const _Tp __tmp = __value; for (; __first != __last; ++__first) *__first = __tmp; } // Specialization: for char types we can use memset. template inline typename __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, void>::__type __fill_a(_Tp* __first, _Tp* __last, const _Tp& __c) { const _Tp __tmp = __c; if (const size_t __len = __last - __first) __builtin_memset(__first, static_cast(__tmp), __len); } /** * @brief Fills the range [first,last) with copies of value. * @ingroup mutating_algorithms * @param __first A forward iterator. * @param __last A forward iterator. * @param __value A reference-to-const of arbitrary type. * @return Nothing. * * This function fills a range with copies of the same value. For char * types filling contiguous areas of memory, this becomes an inline call * to @c memset or @c wmemset. */ template inline void fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< _ForwardIterator>) __glibcxx_requires_valid_range(__first, __last); std::__fill_a(std::__niter_base(__first), std::__niter_base(__last), __value); } template inline typename __gnu_cxx::__enable_if::__value, _OutputIterator>::__type __fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value) { for (__decltype(__n + 0) __niter = __n; __niter > 0; --__niter, (void) ++__first) *__first = __value; return __first; } template inline typename __gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, _OutputIterator>::__type __fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value) { const _Tp __tmp = __value; for (__decltype(__n + 0) __niter = __n; __niter > 0; --__niter, (void) ++__first) *__first = __tmp; return __first; } template inline typename __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, _Tp*>::__type __fill_n_a(_Tp* __first, _Size __n, const _Tp& __c) { std::__fill_a(__first, __first + __n, __c); return __first + __n; } /** * @brief Fills the range [first,first+n) with copies of value. * @ingroup mutating_algorithms * @param __first An output iterator. * @param __n The count of copies to perform. * @param __value A reference-to-const of arbitrary type. * @return The iterator at first+n. * * This function fills a range with copies of the same value. For char * types filling contiguous areas of memory, this becomes an inline call * to @c memset or @ wmemset. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 865. More algorithms that throw away information */ template inline _OI fill_n(_OI __first, _Size __n, const _Tp& __value) { // concept requirements __glibcxx_function_requires(_OutputIteratorConcept<_OI, _Tp>) return _OI(std::__fill_n_a(std::__niter_base(__first), __n, __value)); } template struct __equal { template static bool equal(_II1 __first1, _II1 __last1, _II2 __first2) { for (; __first1 != __last1; ++__first1, (void) ++__first2) if (!(*__first1 == *__first2)) return false; return true; } }; template<> struct __equal { template static bool equal(const _Tp* __first1, const _Tp* __last1, const _Tp* __first2) { if (const size_t __len = (__last1 - __first1)) return !__builtin_memcmp(__first1, __first2, sizeof(_Tp) * __len); return true; } }; template inline bool __equal_aux(_II1 __first1, _II1 __last1, _II2 __first2) { typedef typename iterator_traits<_II1>::value_type _ValueType1; typedef typename iterator_traits<_II2>::value_type _ValueType2; const bool __simple = ((__is_integer<_ValueType1>::__value || __is_pointer<_ValueType1>::__value) && __is_pointer<_II1>::__value && __is_pointer<_II2>::__value && __are_same<_ValueType1, _ValueType2>::__value); return std::__equal<__simple>::equal(__first1, __last1, __first2); } template struct __lc_rai { template static _II1 __newlast1(_II1, _II1 __last1, _II2, _II2) { return __last1; } template static bool __cnd2(_II __first, _II __last) { return __first != __last; } }; template<> struct __lc_rai { template static _RAI1 __newlast1(_RAI1 __first1, _RAI1 __last1, _RAI2 __first2, _RAI2 __last2) { const typename iterator_traits<_RAI1>::difference_type __diff1 = __last1 - __first1; const typename iterator_traits<_RAI2>::difference_type __diff2 = __last2 - __first2; return __diff2 < __diff1 ? __first1 + __diff2 : __last1; } template static bool __cnd2(_RAI, _RAI) { return true; } }; template bool __lexicographical_compare_impl(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2, _Compare __comp) { typedef typename iterator_traits<_II1>::iterator_category _Category1; typedef typename iterator_traits<_II2>::iterator_category _Category2; typedef std::__lc_rai<_Category1, _Category2> __rai_type; __last1 = __rai_type::__newlast1(__first1, __last1, __first2, __last2); for (; __first1 != __last1 && __rai_type::__cnd2(__first2, __last2); ++__first1, (void)++__first2) { if (__comp(__first1, __first2)) return true; if (__comp(__first2, __first1)) return false; } return __first1 == __last1 && __first2 != __last2; } template struct __lexicographical_compare { template static bool __lc(_II1, _II1, _II2, _II2); }; template template bool __lexicographical_compare<_BoolType>:: __lc(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { return std::__lexicographical_compare_impl(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_less_iter()); } template<> struct __lexicographical_compare { template static bool __lc(const _Tp* __first1, const _Tp* __last1, const _Up* __first2, const _Up* __last2) { const size_t __len1 = __last1 - __first1; const size_t __len2 = __last2 - __first2; if (const size_t __len = std::min(__len1, __len2)) if (int __result = __builtin_memcmp(__first1, __first2, __len)) return __result < 0; return __len1 < __len2; } }; template inline bool __lexicographical_compare_aux(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { typedef typename iterator_traits<_II1>::value_type _ValueType1; typedef typename iterator_traits<_II2>::value_type _ValueType2; const bool __simple = (__is_byte<_ValueType1>::__value && __is_byte<_ValueType2>::__value && !__gnu_cxx::__numeric_traits<_ValueType1>::__is_signed && !__gnu_cxx::__numeric_traits<_ValueType2>::__is_signed && __is_pointer<_II1>::__value && __is_pointer<_II2>::__value); return std::__lexicographical_compare<__simple>::__lc(__first1, __last1, __first2, __last2); } template _ForwardIterator __lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val, _Compare __comp) { typedef typename iterator_traits<_ForwardIterator>::difference_type _DistanceType; _DistanceType __len = std::distance(__first, __last); while (__len > 0) { _DistanceType __half = __len >> 1; _ForwardIterator __middle = __first; std::advance(__middle, __half); if (__comp(__middle, __val)) { __first = __middle; ++__first; __len = __len - __half - 1; } else __len = __half; } return __first; } /** * @brief Finds the first position in which @a val could be inserted * without changing the ordering. * @param __first An iterator. * @param __last Another iterator. * @param __val The search term. * @return An iterator pointing to the first element not less * than @a val, or end() if every element is less than * @a val. * @ingroup binary_search_algorithms */ template inline _ForwardIterator lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __val) { // concept requirements __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __glibcxx_function_requires(_LessThanOpConcept< typename iterator_traits<_ForwardIterator>::value_type, _Tp>) __glibcxx_requires_partitioned_lower(__first, __last, __val); return std::__lower_bound(__first, __last, __val, __gnu_cxx::__ops::__iter_less_val()); } /// This is a helper function for the sort routines and for random.tcc. // Precondition: __n > 0. inline _GLIBCXX_CONSTEXPR int __lg(int __n) { return (int)sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); } inline _GLIBCXX_CONSTEXPR unsigned __lg(unsigned __n) { return (int)sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(__n); } inline _GLIBCXX_CONSTEXPR long __lg(long __n) { return (int)sizeof(long) * __CHAR_BIT__ - 1 - __builtin_clzl(__n); } inline _GLIBCXX_CONSTEXPR unsigned long __lg(unsigned long __n) { return (int)sizeof(long) * __CHAR_BIT__ - 1 - __builtin_clzl(__n); } inline _GLIBCXX_CONSTEXPR long long __lg(long long __n) { return (int)sizeof(long long) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); } inline _GLIBCXX_CONSTEXPR unsigned long long __lg(unsigned long long __n) { return (int)sizeof(long long) * __CHAR_BIT__ - 1 - __builtin_clzll(__n); } _GLIBCXX_BEGIN_NAMESPACE_ALGO /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @return A boolean true or false. * * This compares the elements of two ranges using @c == and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_II1 __first1, _II1 __last1, _II2 __first2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_II1>::value_type, typename iterator_traits<_II2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); return std::__equal_aux(std::__niter_base(__first1), std::__niter_base(__last1), std::__niter_base(__first2)); } /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A boolean true or false. * * This compares the elements of two ranges using the binary_pred * parameter, and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_IIter1>) __glibcxx_function_requires(_InputIteratorConcept<_IIter2>) __glibcxx_requires_valid_range(__first1, __last1); for (; __first1 != __last1; ++__first1, (void)++__first2) if (!bool(__binary_pred(*__first1, *__first2))) return false; return true; } #if __cplusplus >= 201103L // 4-iterator version of std::equal for use in C++11. template inline bool __equal4(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { using _RATag = random_access_iterator_tag; using _Cat1 = typename iterator_traits<_II1>::iterator_category; using _Cat2 = typename iterator_traits<_II2>::iterator_category; using _RAIters = __and_, is_same<_Cat2, _RATag>>; if (_RAIters()) { auto __d1 = std::distance(__first1, __last1); auto __d2 = std::distance(__first2, __last2); if (__d1 != __d2) return false; return _GLIBCXX_STD_A::equal(__first1, __last1, __first2); } for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2) if (!(*__first1 == *__first2)) return false; return __first1 == __last1 && __first2 == __last2; } // 4-iterator version of std::equal for use in C++11. template inline bool __equal4(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2, _BinaryPredicate __binary_pred) { using _RATag = random_access_iterator_tag; using _Cat1 = typename iterator_traits<_II1>::iterator_category; using _Cat2 = typename iterator_traits<_II2>::iterator_category; using _RAIters = __and_, is_same<_Cat2, _RATag>>; if (_RAIters()) { auto __d1 = std::distance(__first1, __last1); auto __d2 = std::distance(__first2, __last2); if (__d1 != __d2) return false; return _GLIBCXX_STD_A::equal(__first1, __last1, __first2, __binary_pred); } for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2) if (!bool(__binary_pred(*__first1, *__first2))) return false; return __first1 == __last1 && __first2 == __last2; } #endif // C++11 #if __cplusplus > 201103L #define __cpp_lib_robust_nonmodifying_seq_ops 201304 /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return A boolean true or false. * * This compares the elements of two ranges using @c == and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_II1>::value_type, typename iterator_traits<_II2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__equal4(__first1, __last1, __first2, __last2); } /** * @brief Tests a range for element-wise equality. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A boolean true or false. * * This compares the elements of two ranges using the binary_pred * parameter, and returns true or * false depending on whether all of the corresponding elements of the * ranges are equal. */ template inline bool equal(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _IIter2 __last2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_IIter1>) __glibcxx_function_requires(_InputIteratorConcept<_IIter2>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__equal4(__first1, __last1, __first2, __last2, __binary_pred); } #endif // C++14 /** * @brief Performs @b dictionary comparison on ranges. * @ingroup sorting_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return A boolean true or false. * * Returns true if the sequence of elements defined by the range * [first1,last1) is lexicographically less than the sequence of elements * defined by the range [first2,last2). Returns false otherwise. * (Quoted from [25.3.8]/1.) If the iterators are all character pointers, * then this is an inline call to @c memcmp. */ template inline bool lexicographical_compare(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename iterator_traits<_II1>::value_type _ValueType1; typedef typename iterator_traits<_II2>::value_type _ValueType2; #endif __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_function_requires(_LessThanOpConcept<_ValueType1, _ValueType2>) __glibcxx_function_requires(_LessThanOpConcept<_ValueType2, _ValueType1>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__lexicographical_compare_aux(std::__niter_base(__first1), std::__niter_base(__last1), std::__niter_base(__first2), std::__niter_base(__last2)); } /** * @brief Performs @b dictionary comparison on ranges. * @ingroup sorting_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @param __comp A @link comparison_functors comparison functor@endlink. * @return A boolean true or false. * * The same as the four-parameter @c lexicographical_compare, but uses the * comp parameter instead of @c <. */ template inline bool lexicographical_compare(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2, _Compare __comp) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_II1>) __glibcxx_function_requires(_InputIteratorConcept<_II2>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return std::__lexicographical_compare_impl (__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__comp)); } template pair<_InputIterator1, _InputIterator2> __mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __binary_pred) { while (__first1 != __last1 && __binary_pred(__first1, __first2)) { ++__first1; ++__first2; } return pair<_InputIterator1, _InputIterator2>(__first1, __first2); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using @c == and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using the binary_pred * parameter, and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); } #if __cplusplus > 201103L template pair<_InputIterator1, _InputIterator2> __mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __binary_pred) { while (__first1 != __last1 && __first2 != __last2 && __binary_pred(__first1, __first2)) { ++__first1; ++__first2; } return pair<_InputIterator1, _InputIterator2>(__first1, __first2); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using @c == and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_function_requires(_EqualOpConcept< typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_equal_to_iter()); } /** * @brief Finds the places in ranges which don't match. * @ingroup non_mutating_algorithms * @param __first1 An input iterator. * @param __last1 An input iterator. * @param __first2 An input iterator. * @param __last2 An input iterator. * @param __binary_pred A binary predicate @link functors * functor@endlink. * @return A pair of iterators pointing to the first mismatch. * * This compares the elements of two ranges using the binary_pred * parameter, and returns a pair * of iterators. The first iterator points into the first range, the * second iterator points into the second range, and the elements pointed * to by the iterators are not equal. */ template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __binary_pred) { // concept requirements __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) __glibcxx_requires_valid_range(__first1, __last1); __glibcxx_requires_valid_range(__first2, __last2); return _GLIBCXX_STD_A::__mismatch(__first1, __last1, __first2, __last2, __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); } #endif _GLIBCXX_END_NAMESPACE_ALGO _GLIBCXX_END_NAMESPACE_VERSION } // namespace std // NB: This file is included within many other C++ includes, as a way // of getting the base algorithms. So, make sure that parallel bits // come in too if requested. #ifdef _GLIBCXX_PARALLEL # include #endif #endif c++/8/bits/random.tcc000064400000316166151027430570010220 0ustar00// random number generation (out of line) -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/random.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _RANDOM_TCC #define _RANDOM_TCC 1 #include // std::accumulate and std::partial_sum namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /* * (Further) implementation-space details. */ namespace __detail { // General case for x = (ax + c) mod m -- use Schrage's algorithm // to avoid integer overflow. // // Preconditions: a > 0, m > 0. // // Note: only works correctly for __m % __a < __m / __a. template _Tp _Mod<_Tp, __m, __a, __c, false, true>:: __calc(_Tp __x) { if (__a == 1) __x %= __m; else { static const _Tp __q = __m / __a; static const _Tp __r = __m % __a; _Tp __t1 = __a * (__x % __q); _Tp __t2 = __r * (__x / __q); if (__t1 >= __t2) __x = __t1 - __t2; else __x = __m - __t2 + __t1; } if (__c != 0) { const _Tp __d = __m - __x; if (__d > __c) __x += __c; else __x = __c - __d; } return __x; } template _OutputIterator __normalize(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __factor) { for (; __first != __last; ++__first, ++__result) *__result = *__first / __factor; return __result; } } // namespace __detail template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::multiplier; template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::increment; template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::modulus; template constexpr _UIntType linear_congruential_engine<_UIntType, __a, __c, __m>::default_seed; /** * Seeds the LCR with integral value @p __s, adjusted so that the * ring identity is never a member of the convergence set. */ template void linear_congruential_engine<_UIntType, __a, __c, __m>:: seed(result_type __s) { if ((__detail::__mod<_UIntType, __m>(__c) == 0) && (__detail::__mod<_UIntType, __m>(__s) == 0)) _M_x = 1; else _M_x = __detail::__mod<_UIntType, __m>(__s); } /** * Seeds the LCR engine with a value generated by @p __q. */ template template typename std::enable_if::value>::type linear_congruential_engine<_UIntType, __a, __c, __m>:: seed(_Sseq& __q) { const _UIntType __k0 = __m == 0 ? std::numeric_limits<_UIntType>::digits : std::__lg(__m); const _UIntType __k = (__k0 + 31) / 32; uint_least32_t __arr[__k + 3]; __q.generate(__arr + 0, __arr + __k + 3); _UIntType __factor = 1u; _UIntType __sum = 0u; for (size_t __j = 0; __j < __k; ++__j) { __sum += __arr[__j + 3] * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } seed(__sum); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const linear_congruential_engine<_UIntType, __a, __c, __m>& __lcr) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__os.widen(' ')); __os << __lcr._M_x; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, linear_congruential_engine<_UIntType, __a, __c, __m>& __lcr) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec); __is >> __lcr._M_x; __is.flags(__flags); return __is; } template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::word_size; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::state_size; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::shift_size; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::mask_bits; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::xor_mask; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_u; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_d; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_s; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_b; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_t; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_c; template constexpr size_t mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::tempering_l; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: initialization_multiplier; template constexpr _UIntType mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::default_seed; template void mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: seed(result_type __sd) { _M_x[0] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sd); for (size_t __i = 1; __i < state_size; ++__i) { _UIntType __x = _M_x[__i - 1]; __x ^= __x >> (__w - 2); __x *= __f; __x += __detail::__mod<_UIntType, __n>(__i); _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__x); } _M_p = state_size; } template template typename std::enable_if::value>::type mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: seed(_Sseq& __q) { const _UIntType __upper_mask = (~_UIntType()) << __r; const size_t __k = (__w + 31) / 32; uint_least32_t __arr[__n * __k]; __q.generate(__arr + 0, __arr + __n * __k); bool __zero = true; for (size_t __i = 0; __i < state_size; ++__i) { _UIntType __factor = 1u; _UIntType __sum = 0u; for (size_t __j = 0; __j < __k; ++__j) { __sum += __arr[__k * __i + __j] * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sum); if (__zero) { if (__i == 0) { if ((_M_x[0] & __upper_mask) != 0u) __zero = false; } else if (_M_x[__i] != 0u) __zero = false; } } if (__zero) _M_x[0] = __detail::_Shift<_UIntType, __w - 1>::__value; _M_p = state_size; } template void mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: _M_gen_rand(void) { const _UIntType __upper_mask = (~_UIntType()) << __r; const _UIntType __lower_mask = ~__upper_mask; for (size_t __k = 0; __k < (__n - __m); ++__k) { _UIntType __y = ((_M_x[__k] & __upper_mask) | (_M_x[__k + 1] & __lower_mask)); _M_x[__k] = (_M_x[__k + __m] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); } for (size_t __k = (__n - __m); __k < (__n - 1); ++__k) { _UIntType __y = ((_M_x[__k] & __upper_mask) | (_M_x[__k + 1] & __lower_mask)); _M_x[__k] = (_M_x[__k + (__m - __n)] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); } _UIntType __y = ((_M_x[__n - 1] & __upper_mask) | (_M_x[0] & __lower_mask)); _M_x[__n - 1] = (_M_x[__m - 1] ^ (__y >> 1) ^ ((__y & 0x01) ? __a : 0)); _M_p = 0; } template void mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: discard(unsigned long long __z) { while (__z > state_size - _M_p) { __z -= state_size - _M_p; _M_gen_rand(); } _M_p += __z; } template typename mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>::result_type mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>:: operator()() { // Reload the vector - cost is O(n) amortized over n calls. if (_M_p >= state_size) _M_gen_rand(); // Calculate o(x(i)). result_type __z = _M_x[_M_p++]; __z ^= (__z >> __u) & __d; __z ^= (__z << __s) & __b; __z ^= (__z << __t) & __c; __z ^= (__z >> __l); return __z; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); for (size_t __i = 0; __i < __n; ++__i) __os << __x._M_x[__i] << __space; __os << __x._M_p; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, mersenne_twister_engine<_UIntType, __w, __n, __m, __r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); for (size_t __i = 0; __i < __n; ++__i) __is >> __x._M_x[__i]; __is >> __x._M_p; __is.flags(__flags); return __is; } template constexpr size_t subtract_with_carry_engine<_UIntType, __w, __s, __r>::word_size; template constexpr size_t subtract_with_carry_engine<_UIntType, __w, __s, __r>::short_lag; template constexpr size_t subtract_with_carry_engine<_UIntType, __w, __s, __r>::long_lag; template constexpr _UIntType subtract_with_carry_engine<_UIntType, __w, __s, __r>::default_seed; template void subtract_with_carry_engine<_UIntType, __w, __s, __r>:: seed(result_type __value) { std::linear_congruential_engine __lcg(__value == 0u ? default_seed : __value); const size_t __n = (__w + 31) / 32; for (size_t __i = 0; __i < long_lag; ++__i) { _UIntType __sum = 0u; _UIntType __factor = 1u; for (size_t __j = 0; __j < __n; ++__j) { __sum += __detail::__mod::__value> (__lcg()) * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sum); } _M_carry = (_M_x[long_lag - 1] == 0) ? 1 : 0; _M_p = 0; } template template typename std::enable_if::value>::type subtract_with_carry_engine<_UIntType, __w, __s, __r>:: seed(_Sseq& __q) { const size_t __k = (__w + 31) / 32; uint_least32_t __arr[__r * __k]; __q.generate(__arr + 0, __arr + __r * __k); for (size_t __i = 0; __i < long_lag; ++__i) { _UIntType __sum = 0u; _UIntType __factor = 1u; for (size_t __j = 0; __j < __k; ++__j) { __sum += __arr[__k * __i + __j] * __factor; __factor *= __detail::_Shift<_UIntType, 32>::__value; } _M_x[__i] = __detail::__mod<_UIntType, __detail::_Shift<_UIntType, __w>::__value>(__sum); } _M_carry = (_M_x[long_lag - 1] == 0) ? 1 : 0; _M_p = 0; } template typename subtract_with_carry_engine<_UIntType, __w, __s, __r>:: result_type subtract_with_carry_engine<_UIntType, __w, __s, __r>:: operator()() { // Derive short lag index from current index. long __ps = _M_p - short_lag; if (__ps < 0) __ps += long_lag; // Calculate new x(i) without overflow or division. // NB: Thanks to the requirements for _UIntType, _M_x[_M_p] + _M_carry // cannot overflow. _UIntType __xi; if (_M_x[__ps] >= _M_x[_M_p] + _M_carry) { __xi = _M_x[__ps] - _M_x[_M_p] - _M_carry; _M_carry = 0; } else { __xi = (__detail::_Shift<_UIntType, __w>::__value - _M_x[_M_p] - _M_carry + _M_x[__ps]); _M_carry = 1; } _M_x[_M_p] = __xi; // Adjust current index to loop around in ring buffer. if (++_M_p >= long_lag) _M_p = 0; return __xi; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const subtract_with_carry_engine<_UIntType, __w, __s, __r>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); for (size_t __i = 0; __i < __r; ++__i) __os << __x._M_x[__i] << __space; __os << __x._M_carry << __space << __x._M_p; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, subtract_with_carry_engine<_UIntType, __w, __s, __r>& __x) { typedef std::basic_ostream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); for (size_t __i = 0; __i < __r; ++__i) __is >> __x._M_x[__i]; __is >> __x._M_carry; __is >> __x._M_p; __is.flags(__flags); return __is; } template constexpr size_t discard_block_engine<_RandomNumberEngine, __p, __r>::block_size; template constexpr size_t discard_block_engine<_RandomNumberEngine, __p, __r>::used_block; template typename discard_block_engine<_RandomNumberEngine, __p, __r>::result_type discard_block_engine<_RandomNumberEngine, __p, __r>:: operator()() { if (_M_n >= used_block) { _M_b.discard(block_size - _M_n); _M_n = 0; } ++_M_n; return _M_b(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const discard_block_engine<_RandomNumberEngine, __p, __r>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); __os << __x.base() << __space << __x._M_n; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, discard_block_engine<_RandomNumberEngine, __p, __r>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); __is >> __x._M_b >> __x._M_n; __is.flags(__flags); return __is; } template typename independent_bits_engine<_RandomNumberEngine, __w, _UIntType>:: result_type independent_bits_engine<_RandomNumberEngine, __w, _UIntType>:: operator()() { typedef typename _RandomNumberEngine::result_type _Eresult_type; const _Eresult_type __r = (_M_b.max() - _M_b.min() < std::numeric_limits<_Eresult_type>::max() ? _M_b.max() - _M_b.min() + 1 : 0); const unsigned __edig = std::numeric_limits<_Eresult_type>::digits; const unsigned __m = __r ? std::__lg(__r) : __edig; typedef typename std::common_type<_Eresult_type, result_type>::type __ctype; const unsigned __cdig = std::numeric_limits<__ctype>::digits; unsigned __n, __n0; __ctype __s0, __s1, __y0, __y1; for (size_t __i = 0; __i < 2; ++__i) { __n = (__w + __m - 1) / __m + __i; __n0 = __n - __w % __n; const unsigned __w0 = __w / __n; // __w0 <= __m __s0 = 0; __s1 = 0; if (__w0 < __cdig) { __s0 = __ctype(1) << __w0; __s1 = __s0 << 1; } __y0 = 0; __y1 = 0; if (__r) { __y0 = __s0 * (__r / __s0); if (__s1) __y1 = __s1 * (__r / __s1); if (__r - __y0 <= __y0 / __n) break; } else break; } result_type __sum = 0; for (size_t __k = 0; __k < __n0; ++__k) { __ctype __u; do __u = _M_b() - _M_b.min(); while (__y0 && __u >= __y0); __sum = __s0 * __sum + (__s0 ? __u % __s0 : __u); } for (size_t __k = __n0; __k < __n; ++__k) { __ctype __u; do __u = _M_b() - _M_b.min(); while (__y1 && __u >= __y1); __sum = __s1 * __sum + (__s1 ? __u % __s1 : __u); } return __sum; } template constexpr size_t shuffle_order_engine<_RandomNumberEngine, __k>::table_size; template typename shuffle_order_engine<_RandomNumberEngine, __k>::result_type shuffle_order_engine<_RandomNumberEngine, __k>:: operator()() { size_t __j = __k * ((_M_y - _M_b.min()) / (_M_b.max() - _M_b.min() + 1.0L)); _M_y = _M_v[__j]; _M_v[__j] = _M_b(); return _M_y; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const shuffle_order_engine<_RandomNumberEngine, __k>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::dec | __ios_base::fixed | __ios_base::left); __os.fill(__space); __os << __x.base(); for (size_t __i = 0; __i < __k; ++__i) __os << __space << __x._M_v[__i]; __os << __space << __x._M_y; __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, shuffle_order_engine<_RandomNumberEngine, __k>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); __is >> __x._M_b; for (size_t __i = 0; __i < __k; ++__i) __is >> __x._M_v[__i]; __is >> __x._M_y; __is.flags(__flags); return __is; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const uniform_int_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, uniform_int_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _IntType __a, __b; if (__is >> __a >> __b) __x.param(typename uniform_int_distribution<_IntType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template template void uniform_real_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); auto __range = __p.b() - __p.a(); while (__f != __t) *__f++ = __aurng() * __range + __p.a(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const uniform_real_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, uniform_real_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename uniform_real_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template void std::bernoulli_distribution:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); auto __limit = __p.p() * (__aurng.max() - __aurng.min()); while (__f != __t) *__f++ = (__aurng() - __aurng.min()) < __limit; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const bernoulli_distribution& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits::max_digits10); __os << __x.p(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template template typename geometric_distribution<_IntType>::result_type geometric_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { // About the epsilon thing see this thread: // http://gcc.gnu.org/ml/gcc-patches/2006-10/msg00971.html const double __naf = (1 - std::numeric_limits::epsilon()) / 2; // The largest _RealType convertible to _IntType. const double __thr = std::numeric_limits<_IntType>::max() + __naf; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); double __cand; do __cand = std::floor(std::log(1.0 - __aurng()) / __param._M_log_1_p); while (__cand >= __thr); return result_type(__cand + __naf); } template template void geometric_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // About the epsilon thing see this thread: // http://gcc.gnu.org/ml/gcc-patches/2006-10/msg00971.html const double __naf = (1 - std::numeric_limits::epsilon()) / 2; // The largest _RealType convertible to _IntType. const double __thr = std::numeric_limits<_IntType>::max() + __naf; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); while (__f != __t) { double __cand; do __cand = std::floor(std::log(1.0 - __aurng()) / __param._M_log_1_p); while (__cand >= __thr); *__f++ = __cand + __naf; } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const geometric_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits::max_digits10); __os << __x.p(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, geometric_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); double __p; if (__is >> __p) __x.param(typename geometric_distribution<_IntType>::param_type(__p)); __is.flags(__flags); return __is; } // This is Leger's algorithm, also in Devroye, Ch. X, Example 1.5. template template typename negative_binomial_distribution<_IntType>::result_type negative_binomial_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng) { const double __y = _M_gd(__urng); // XXX Is the constructor too slow? std::poisson_distribution __poisson(__y); return __poisson(__urng); } template template typename negative_binomial_distribution<_IntType>::result_type negative_binomial_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { typedef typename std::gamma_distribution::param_type param_type; const double __y = _M_gd(__urng, param_type(__p.k(), (1.0 - __p.p()) / __p.p())); std::poisson_distribution __poisson(__y); return __poisson(__urng); } template template void negative_binomial_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) { const double __y = _M_gd(__urng); // XXX Is the constructor too slow? std::poisson_distribution __poisson(__y); *__f++ = __poisson(__urng); } } template template void negative_binomial_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typename std::gamma_distribution::param_type __p2(__p.k(), (1.0 - __p.p()) / __p.p()); while (__f != __t) { const double __y = _M_gd(__urng, __p2); std::poisson_distribution __poisson(__y); *__f++ = __poisson(__urng); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const negative_binomial_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits::max_digits10); __os << __x.k() << __space << __x.p() << __space << __x._M_gd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, negative_binomial_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); _IntType __k; double __p; if (__is >> __k >> __p >> __x._M_gd) __x.param(typename negative_binomial_distribution<_IntType>:: param_type(__k, __p)); __is.flags(__flags); return __is; } template void poisson_distribution<_IntType>::param_type:: _M_initialize() { #if _GLIBCXX_USE_C99_MATH_TR1 if (_M_mean >= 12) { const double __m = std::floor(_M_mean); _M_lm_thr = std::log(_M_mean); _M_lfm = std::lgamma(__m + 1); _M_sm = std::sqrt(__m); const double __pi_4 = 0.7853981633974483096156608458198757L; const double __dx = std::sqrt(2 * __m * std::log(32 * __m / __pi_4)); _M_d = std::round(std::max(6.0, std::min(__m, __dx))); const double __cx = 2 * __m + _M_d; _M_scx = std::sqrt(__cx / 2); _M_1cx = 1 / __cx; _M_c2b = std::sqrt(__pi_4 * __cx) * std::exp(_M_1cx); _M_cb = 2 * __cx * std::exp(-_M_d * _M_1cx * (1 + _M_d / 2)) / _M_d; } else #endif _M_lm_thr = std::exp(-_M_mean); } /** * A rejection algorithm when mean >= 12 and a simple method based * upon the multiplication of uniform random variates otherwise. * NB: The former is available only if _GLIBCXX_USE_C99_MATH_TR1 * is defined. * * Reference: * Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag, * New York, 1986, Ch. X, Sects. 3.3 & 3.4 (+ Errata!). */ template template typename poisson_distribution<_IntType>::result_type poisson_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); #if _GLIBCXX_USE_C99_MATH_TR1 if (__param.mean() >= 12) { double __x; // See comments above... const double __naf = (1 - std::numeric_limits::epsilon()) / 2; const double __thr = std::numeric_limits<_IntType>::max() + __naf; const double __m = std::floor(__param.mean()); // sqrt(pi / 2) const double __spi_2 = 1.2533141373155002512078826424055226L; const double __c1 = __param._M_sm * __spi_2; const double __c2 = __param._M_c2b + __c1; const double __c3 = __c2 + 1; const double __c4 = __c3 + 1; // 1 / 78 const double __178 = 0.0128205128205128205128205128205128L; // e^(1 / 78) const double __e178 = 1.0129030479320018583185514777512983L; const double __c5 = __c4 + __e178; const double __c = __param._M_cb + __c5; const double __2cx = 2 * (2 * __m + __param._M_d); bool __reject = true; do { const double __u = __c * __aurng(); const double __e = -std::log(1.0 - __aurng()); double __w = 0.0; if (__u <= __c1) { const double __n = _M_nd(__urng); const double __y = -std::abs(__n) * __param._M_sm - 1; __x = std::floor(__y); __w = -__n * __n / 2; if (__x < -__m) continue; } else if (__u <= __c2) { const double __n = _M_nd(__urng); const double __y = 1 + std::abs(__n) * __param._M_scx; __x = std::ceil(__y); __w = __y * (2 - __y) * __param._M_1cx; if (__x > __param._M_d) continue; } else if (__u <= __c3) // NB: This case not in the book, nor in the Errata, // but should be ok... __x = -1; else if (__u <= __c4) __x = 0; else if (__u <= __c5) { __x = 1; // Only in the Errata, see libstdc++/83237. __w = __178; } else { const double __v = -std::log(1.0 - __aurng()); const double __y = __param._M_d + __v * __2cx / __param._M_d; __x = std::ceil(__y); __w = -__param._M_d * __param._M_1cx * (1 + __y / 2); } __reject = (__w - __e - __x * __param._M_lm_thr > __param._M_lfm - std::lgamma(__x + __m + 1)); __reject |= __x + __m >= __thr; } while (__reject); return result_type(__x + __m + __naf); } else #endif { _IntType __x = 0; double __prod = 1.0; do { __prod *= __aurng(); __x += 1; } while (__prod > __param._M_lm_thr); return __x - 1; } } template template void poisson_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // We could duplicate everything from operator()... while (__f != __t) *__f++ = this->operator()(__urng, __param); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const poisson_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits::max_digits10); __os << __x.mean() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, poisson_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::skipws); double __mean; if (__is >> __mean >> __x._M_nd) __x.param(typename poisson_distribution<_IntType>::param_type(__mean)); __is.flags(__flags); return __is; } template void binomial_distribution<_IntType>::param_type:: _M_initialize() { const double __p12 = _M_p <= 0.5 ? _M_p : 1.0 - _M_p; _M_easy = true; #if _GLIBCXX_USE_C99_MATH_TR1 if (_M_t * __p12 >= 8) { _M_easy = false; const double __np = std::floor(_M_t * __p12); const double __pa = __np / _M_t; const double __1p = 1 - __pa; const double __pi_4 = 0.7853981633974483096156608458198757L; const double __d1x = std::sqrt(__np * __1p * std::log(32 * __np / (81 * __pi_4 * __1p))); _M_d1 = std::round(std::max(1.0, __d1x)); const double __d2x = std::sqrt(__np * __1p * std::log(32 * _M_t * __1p / (__pi_4 * __pa))); _M_d2 = std::round(std::max(1.0, __d2x)); // sqrt(pi / 2) const double __spi_2 = 1.2533141373155002512078826424055226L; _M_s1 = std::sqrt(__np * __1p) * (1 + _M_d1 / (4 * __np)); _M_s2 = std::sqrt(__np * __1p) * (1 + _M_d2 / (4 * _M_t * __1p)); _M_c = 2 * _M_d1 / __np; _M_a1 = std::exp(_M_c) * _M_s1 * __spi_2; const double __a12 = _M_a1 + _M_s2 * __spi_2; const double __s1s = _M_s1 * _M_s1; _M_a123 = __a12 + (std::exp(_M_d1 / (_M_t * __1p)) * 2 * __s1s / _M_d1 * std::exp(-_M_d1 * _M_d1 / (2 * __s1s))); const double __s2s = _M_s2 * _M_s2; _M_s = (_M_a123 + 2 * __s2s / _M_d2 * std::exp(-_M_d2 * _M_d2 / (2 * __s2s))); _M_lf = (std::lgamma(__np + 1) + std::lgamma(_M_t - __np + 1)); _M_lp1p = std::log(__pa / __1p); _M_q = -std::log(1 - (__p12 - __pa) / __1p); } else #endif _M_q = -std::log(1 - __p12); } template template typename binomial_distribution<_IntType>::result_type binomial_distribution<_IntType>:: _M_waiting(_UniformRandomNumberGenerator& __urng, _IntType __t, double __q) { _IntType __x = 0; double __sum = 0.0; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); do { if (__t == __x) return __x; const double __e = -std::log(1.0 - __aurng()); __sum += __e / (__t - __x); __x += 1; } while (__sum <= __q); return __x - 1; } /** * A rejection algorithm when t * p >= 8 and a simple waiting time * method - the second in the referenced book - otherwise. * NB: The former is available only if _GLIBCXX_USE_C99_MATH_TR1 * is defined. * * Reference: * Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag, * New York, 1986, Ch. X, Sect. 4 (+ Errata!). */ template template typename binomial_distribution<_IntType>::result_type binomial_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { result_type __ret; const _IntType __t = __param.t(); const double __p = __param.p(); const double __p12 = __p <= 0.5 ? __p : 1.0 - __p; __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); #if _GLIBCXX_USE_C99_MATH_TR1 if (!__param._M_easy) { double __x; // See comments above... const double __naf = (1 - std::numeric_limits::epsilon()) / 2; const double __thr = std::numeric_limits<_IntType>::max() + __naf; const double __np = std::floor(__t * __p12); // sqrt(pi / 2) const double __spi_2 = 1.2533141373155002512078826424055226L; const double __a1 = __param._M_a1; const double __a12 = __a1 + __param._M_s2 * __spi_2; const double __a123 = __param._M_a123; const double __s1s = __param._M_s1 * __param._M_s1; const double __s2s = __param._M_s2 * __param._M_s2; bool __reject; do { const double __u = __param._M_s * __aurng(); double __v; if (__u <= __a1) { const double __n = _M_nd(__urng); const double __y = __param._M_s1 * std::abs(__n); __reject = __y >= __param._M_d1; if (!__reject) { const double __e = -std::log(1.0 - __aurng()); __x = std::floor(__y); __v = -__e - __n * __n / 2 + __param._M_c; } } else if (__u <= __a12) { const double __n = _M_nd(__urng); const double __y = __param._M_s2 * std::abs(__n); __reject = __y >= __param._M_d2; if (!__reject) { const double __e = -std::log(1.0 - __aurng()); __x = std::floor(-__y); __v = -__e - __n * __n / 2; } } else if (__u <= __a123) { const double __e1 = -std::log(1.0 - __aurng()); const double __e2 = -std::log(1.0 - __aurng()); const double __y = __param._M_d1 + 2 * __s1s * __e1 / __param._M_d1; __x = std::floor(__y); __v = (-__e2 + __param._M_d1 * (1 / (__t - __np) -__y / (2 * __s1s))); __reject = false; } else { const double __e1 = -std::log(1.0 - __aurng()); const double __e2 = -std::log(1.0 - __aurng()); const double __y = __param._M_d2 + 2 * __s2s * __e1 / __param._M_d2; __x = std::floor(-__y); __v = -__e2 - __param._M_d2 * __y / (2 * __s2s); __reject = false; } __reject = __reject || __x < -__np || __x > __t - __np; if (!__reject) { const double __lfx = std::lgamma(__np + __x + 1) + std::lgamma(__t - (__np + __x) + 1); __reject = __v > __param._M_lf - __lfx + __x * __param._M_lp1p; } __reject |= __x + __np >= __thr; } while (__reject); __x += __np + __naf; const _IntType __z = _M_waiting(__urng, __t - _IntType(__x), __param._M_q); __ret = _IntType(__x) + __z; } else #endif __ret = _M_waiting(__urng, __t, __param._M_q); if (__p12 != __p) __ret = __t - __ret; return __ret; } template template void binomial_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // We could duplicate everything from operator()... while (__f != __t) *__f++ = this->operator()(__urng, __param); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const binomial_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits::max_digits10); __os << __x.t() << __space << __x.p() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, binomial_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _IntType __t; double __p; if (__is >> __t >> __p >> __x._M_nd) __x.param(typename binomial_distribution<_IntType>:: param_type(__t, __p)); __is.flags(__flags); return __is; } template template void std::exponential_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f != __t) *__f++ = -std::log(result_type(1) - __aurng()) / __p.lambda(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const exponential_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__os.widen(' ')); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.lambda(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, exponential_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __lambda; if (__is >> __lambda) __x.param(typename exponential_distribution<_RealType>:: param_type(__lambda)); __is.flags(__flags); return __is; } /** * Polar method due to Marsaglia. * * Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag, * New York, 1986, Ch. V, Sect. 4.4. */ template template typename normal_distribution<_RealType>::result_type normal_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { result_type __ret; __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); if (_M_saved_available) { _M_saved_available = false; __ret = _M_saved; } else { result_type __x, __y, __r2; do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); _M_saved = __x * __mult; _M_saved_available = true; __ret = __y * __mult; } __ret = __ret * __param.stddev() + __param.mean(); return __ret; } template template void normal_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) if (__f == __t) return; if (_M_saved_available) { _M_saved_available = false; *__f++ = _M_saved * __param.stddev() + __param.mean(); if (__f == __t) return; } __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f + 1 < __t) { result_type __x, __y, __r2; do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); *__f++ = __y * __mult * __param.stddev() + __param.mean(); *__f++ = __x * __mult * __param.stddev() + __param.mean(); } if (__f != __t) { result_type __x, __y, __r2; do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); _M_saved = __x * __mult; _M_saved_available = true; *__f = __y * __mult * __param.stddev() + __param.mean(); } } template bool operator==(const std::normal_distribution<_RealType>& __d1, const std::normal_distribution<_RealType>& __d2) { if (__d1._M_param == __d2._M_param && __d1._M_saved_available == __d2._M_saved_available) { if (__d1._M_saved_available && __d1._M_saved == __d2._M_saved) return true; else if(!__d1._M_saved_available) return true; else return false; } else return false; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const normal_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.mean() << __space << __x.stddev() << __space << __x._M_saved_available; if (__x._M_saved_available) __os << __space << __x._M_saved; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, normal_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); double __mean, __stddev; bool __saved_avail; if (__is >> __mean >> __stddev >> __saved_avail) { if (!__saved_avail || (__is >> __x._M_saved)) { __x._M_saved_available = __saved_avail; __x.param(typename normal_distribution<_RealType>:: param_type(__mean, __stddev)); } } __is.flags(__flags); return __is; } template template void lognormal_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = std::exp(__p.s() * _M_nd(__urng) + __p.m()); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const lognormal_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.m() << __space << __x.s() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, lognormal_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __m, __s; if (__is >> __m >> __s >> __x._M_nd) __x.param(typename lognormal_distribution<_RealType>:: param_type(__m, __s)); __is.flags(__flags); return __is; } template template void std::chi_squared_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = 2 * _M_gd(__urng); } template template void std::chi_squared_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const typename std::gamma_distribution::param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = 2 * _M_gd(__urng, __p); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const chi_squared_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.n() << __space << __x._M_gd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, chi_squared_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __n; if (__is >> __n >> __x._M_gd) __x.param(typename chi_squared_distribution<_RealType>:: param_type(__n)); __is.flags(__flags); return __is; } template template typename cauchy_distribution<_RealType>::result_type cauchy_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); _RealType __u; do __u = __aurng(); while (__u == 0.5); const _RealType __pi = 3.1415926535897932384626433832795029L; return __p.a() + __p.b() * std::tan(__pi * __u); } template template void cauchy_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) const _RealType __pi = 3.1415926535897932384626433832795029L; __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f != __t) { _RealType __u; do __u = __aurng(); while (__u == 0.5); *__f++ = __p.a() + __p.b() * std::tan(__pi * __u); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const cauchy_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, cauchy_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename cauchy_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template template void std::fisher_f_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = ((_M_gd_x(__urng) * n()) / (_M_gd_y(__urng) * m())); } template template void std::fisher_f_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typedef typename std::gamma_distribution::param_type param_type; param_type __p1(__p.m() / 2); param_type __p2(__p.n() / 2); while (__f != __t) *__f++ = ((_M_gd_x(__urng, __p1) * n()) / (_M_gd_y(__urng, __p2) * m())); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const fisher_f_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.m() << __space << __x.n() << __space << __x._M_gd_x << __space << __x._M_gd_y; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, fisher_f_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __m, __n; if (__is >> __m >> __n >> __x._M_gd_x >> __x._M_gd_y) __x.param(typename fisher_f_distribution<_RealType>:: param_type(__m, __n)); __is.flags(__flags); return __is; } template template void std::student_t_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) while (__f != __t) *__f++ = _M_nd(__urng) * std::sqrt(n() / _M_gd(__urng)); } template template void std::student_t_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typename std::gamma_distribution::param_type __p2(__p.n() / 2, 2); while (__f != __t) *__f++ = _M_nd(__urng) * std::sqrt(__p.n() / _M_gd(__urng, __p2)); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const student_t_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.n() << __space << __x._M_nd << __space << __x._M_gd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, student_t_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __n; if (__is >> __n >> __x._M_nd >> __x._M_gd) __x.param(typename student_t_distribution<_RealType>::param_type(__n)); __is.flags(__flags); return __is; } template void gamma_distribution<_RealType>::param_type:: _M_initialize() { _M_malpha = _M_alpha < 1.0 ? _M_alpha + _RealType(1.0) : _M_alpha; const _RealType __a1 = _M_malpha - _RealType(1.0) / _RealType(3.0); _M_a2 = _RealType(1.0) / std::sqrt(_RealType(9.0) * __a1); } /** * Marsaglia, G. and Tsang, W. W. * "A Simple Method for Generating Gamma Variables" * ACM Transactions on Mathematical Software, 26, 3, 363-372, 2000. */ template template typename gamma_distribution<_RealType>::result_type gamma_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); result_type __u, __v, __n; const result_type __a1 = (__param._M_malpha - _RealType(1.0) / _RealType(3.0)); do { do { __n = _M_nd(__urng); __v = result_type(1.0) + __param._M_a2 * __n; } while (__v <= 0.0); __v = __v * __v * __v; __u = __aurng(); } while (__u > result_type(1.0) - 0.0331 * __n * __n * __n * __n && (std::log(__u) > (0.5 * __n * __n + __a1 * (1.0 - __v + std::log(__v))))); if (__param.alpha() == __param._M_malpha) return __a1 * __v * __param.beta(); else { do __u = __aurng(); while (__u == 0.0); return (std::pow(__u, result_type(1.0) / __param.alpha()) * __a1 * __v * __param.beta()); } } template template void gamma_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); result_type __u, __v, __n; const result_type __a1 = (__param._M_malpha - _RealType(1.0) / _RealType(3.0)); if (__param.alpha() == __param._M_malpha) while (__f != __t) { do { do { __n = _M_nd(__urng); __v = result_type(1.0) + __param._M_a2 * __n; } while (__v <= 0.0); __v = __v * __v * __v; __u = __aurng(); } while (__u > result_type(1.0) - 0.0331 * __n * __n * __n * __n && (std::log(__u) > (0.5 * __n * __n + __a1 * (1.0 - __v + std::log(__v))))); *__f++ = __a1 * __v * __param.beta(); } else while (__f != __t) { do { do { __n = _M_nd(__urng); __v = result_type(1.0) + __param._M_a2 * __n; } while (__v <= 0.0); __v = __v * __v * __v; __u = __aurng(); } while (__u > result_type(1.0) - 0.0331 * __n * __n * __n * __n && (std::log(__u) > (0.5 * __n * __n + __a1 * (1.0 - __v + std::log(__v))))); do __u = __aurng(); while (__u == 0.0); *__f++ = (std::pow(__u, result_type(1.0) / __param.alpha()) * __a1 * __v * __param.beta()); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const gamma_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.alpha() << __space << __x.beta() << __space << __x._M_nd; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, gamma_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __alpha_val, __beta_val; if (__is >> __alpha_val >> __beta_val >> __x._M_nd) __x.param(typename gamma_distribution<_RealType>:: param_type(__alpha_val, __beta_val)); __is.flags(__flags); return __is; } template template typename weibull_distribution<_RealType>::result_type weibull_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return __p.b() * std::pow(-std::log(result_type(1) - __aurng()), result_type(1) / __p.a()); } template template void weibull_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); auto __inv_a = result_type(1) / __p.a(); while (__f != __t) *__f++ = __p.b() * std::pow(-std::log(result_type(1) - __aurng()), __inv_a); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const weibull_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, weibull_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename weibull_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template template typename extreme_value_distribution<_RealType>::result_type extreme_value_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p) { __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); return __p.a() - __p.b() * std::log(-std::log(result_type(1) - __aurng())); } template template void extreme_value_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); while (__f != __t) *__f++ = __p.a() - __p.b() * std::log(-std::log(result_type(1) - __aurng())); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const extreme_value_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); __os << __x.a() << __space << __x.b(); __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, extreme_value_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); _RealType __a, __b; if (__is >> __a >> __b) __x.param(typename extreme_value_distribution<_RealType>:: param_type(__a, __b)); __is.flags(__flags); return __is; } template void discrete_distribution<_IntType>::param_type:: _M_initialize() { if (_M_prob.size() < 2) { _M_prob.clear(); return; } const double __sum = std::accumulate(_M_prob.begin(), _M_prob.end(), 0.0); // Now normalize the probabilites. __detail::__normalize(_M_prob.begin(), _M_prob.end(), _M_prob.begin(), __sum); // Accumulate partial sums. _M_cp.reserve(_M_prob.size()); std::partial_sum(_M_prob.begin(), _M_prob.end(), std::back_inserter(_M_cp)); // Make sure the last cumulative probability is one. _M_cp[_M_cp.size() - 1] = 1.0; } template template discrete_distribution<_IntType>::param_type:: param_type(size_t __nw, double __xmin, double __xmax, _Func __fw) : _M_prob(), _M_cp() { const size_t __n = __nw == 0 ? 1 : __nw; const double __delta = (__xmax - __xmin) / __n; _M_prob.reserve(__n); for (size_t __k = 0; __k < __nw; ++__k) _M_prob.push_back(__fw(__xmin + __k * __delta + 0.5 * __delta)); _M_initialize(); } template template typename discrete_distribution<_IntType>::result_type discrete_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { if (__param._M_cp.empty()) return result_type(0); __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); const double __p = __aurng(); auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); return __pos - __param._M_cp.begin(); } template template void discrete_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) if (__param._M_cp.empty()) { while (__f != __t) *__f++ = result_type(0); return; } __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); while (__f != __t) { const double __p = __aurng(); auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); *__f++ = __pos - __param._M_cp.begin(); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const discrete_distribution<_IntType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits::max_digits10); std::vector __prob = __x.probabilities(); __os << __prob.size(); for (auto __dit = __prob.begin(); __dit != __prob.end(); ++__dit) __os << __space << *__dit; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } namespace __detail { template basic_istream<_CharT, _Traits>& __extract_params(basic_istream<_CharT, _Traits>& __is, vector<_ValT>& __vals, size_t __n) { __vals.reserve(__n); while (__n--) { _ValT __val; if (__is >> __val) __vals.push_back(__val); else break; } return __is; } } // namespace __detail template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, discrete_distribution<_IntType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); size_t __n; if (__is >> __n) { std::vector __prob_vec; if (__detail::__extract_params(__is, __prob_vec, __n)) __x.param({__prob_vec.begin(), __prob_vec.end()}); } __is.flags(__flags); return __is; } template void piecewise_constant_distribution<_RealType>::param_type:: _M_initialize() { if (_M_int.size() < 2 || (_M_int.size() == 2 && _M_int[0] == _RealType(0) && _M_int[1] == _RealType(1))) { _M_int.clear(); _M_den.clear(); return; } const double __sum = std::accumulate(_M_den.begin(), _M_den.end(), 0.0); __detail::__normalize(_M_den.begin(), _M_den.end(), _M_den.begin(), __sum); _M_cp.reserve(_M_den.size()); std::partial_sum(_M_den.begin(), _M_den.end(), std::back_inserter(_M_cp)); // Make sure the last cumulative probability is one. _M_cp[_M_cp.size() - 1] = 1.0; for (size_t __k = 0; __k < _M_den.size(); ++__k) _M_den[__k] /= _M_int[__k + 1] - _M_int[__k]; } template template piecewise_constant_distribution<_RealType>::param_type:: param_type(_InputIteratorB __bbegin, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_int(), _M_den(), _M_cp() { if (__bbegin != __bend) { for (;;) { _M_int.push_back(*__bbegin); ++__bbegin; if (__bbegin == __bend) break; _M_den.push_back(*__wbegin); ++__wbegin; } } _M_initialize(); } template template piecewise_constant_distribution<_RealType>::param_type:: param_type(initializer_list<_RealType> __bl, _Func __fw) : _M_int(), _M_den(), _M_cp() { _M_int.reserve(__bl.size()); for (auto __biter = __bl.begin(); __biter != __bl.end(); ++__biter) _M_int.push_back(*__biter); _M_den.reserve(_M_int.size() - 1); for (size_t __k = 0; __k < _M_int.size() - 1; ++__k) _M_den.push_back(__fw(0.5 * (_M_int[__k + 1] + _M_int[__k]))); _M_initialize(); } template template piecewise_constant_distribution<_RealType>::param_type:: param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_int(), _M_den(), _M_cp() { const size_t __n = __nw == 0 ? 1 : __nw; const _RealType __delta = (__xmax - __xmin) / __n; _M_int.reserve(__n + 1); for (size_t __k = 0; __k <= __nw; ++__k) _M_int.push_back(__xmin + __k * __delta); _M_den.reserve(__n); for (size_t __k = 0; __k < __nw; ++__k) _M_den.push_back(__fw(_M_int[__k] + 0.5 * __delta)); _M_initialize(); } template template typename piecewise_constant_distribution<_RealType>::result_type piecewise_constant_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); const double __p = __aurng(); if (__param._M_cp.empty()) return __p; auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); const size_t __i = __pos - __param._M_cp.begin(); const double __pref = __i > 0 ? __param._M_cp[__i - 1] : 0.0; return __param._M_int[__i] + (__p - __pref) / __param._M_den[__i]; } template template void piecewise_constant_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); if (__param._M_cp.empty()) { while (__f != __t) *__f++ = __aurng(); return; } while (__f != __t) { const double __p = __aurng(); auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); const size_t __i = __pos - __param._M_cp.begin(); const double __pref = __i > 0 ? __param._M_cp[__i - 1] : 0.0; *__f++ = (__param._M_int[__i] + (__p - __pref) / __param._M_den[__i]); } } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const piecewise_constant_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); std::vector<_RealType> __int = __x.intervals(); __os << __int.size() - 1; for (auto __xit = __int.begin(); __xit != __int.end(); ++__xit) __os << __space << *__xit; std::vector __den = __x.densities(); for (auto __dit = __den.begin(); __dit != __den.end(); ++__dit) __os << __space << *__dit; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, piecewise_constant_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); size_t __n; if (__is >> __n) { std::vector<_RealType> __int_vec; if (__detail::__extract_params(__is, __int_vec, __n + 1)) { std::vector __den_vec; if (__detail::__extract_params(__is, __den_vec, __n)) { __x.param({ __int_vec.begin(), __int_vec.end(), __den_vec.begin() }); } } } __is.flags(__flags); return __is; } template void piecewise_linear_distribution<_RealType>::param_type:: _M_initialize() { if (_M_int.size() < 2 || (_M_int.size() == 2 && _M_int[0] == _RealType(0) && _M_int[1] == _RealType(1) && _M_den[0] == _M_den[1])) { _M_int.clear(); _M_den.clear(); return; } double __sum = 0.0; _M_cp.reserve(_M_int.size() - 1); _M_m.reserve(_M_int.size() - 1); for (size_t __k = 0; __k < _M_int.size() - 1; ++__k) { const _RealType __delta = _M_int[__k + 1] - _M_int[__k]; __sum += 0.5 * (_M_den[__k + 1] + _M_den[__k]) * __delta; _M_cp.push_back(__sum); _M_m.push_back((_M_den[__k + 1] - _M_den[__k]) / __delta); } // Now normalize the densities... __detail::__normalize(_M_den.begin(), _M_den.end(), _M_den.begin(), __sum); // ... and partial sums... __detail::__normalize(_M_cp.begin(), _M_cp.end(), _M_cp.begin(), __sum); // ... and slopes. __detail::__normalize(_M_m.begin(), _M_m.end(), _M_m.begin(), __sum); // Make sure the last cumulative probablility is one. _M_cp[_M_cp.size() - 1] = 1.0; } template template piecewise_linear_distribution<_RealType>::param_type:: param_type(_InputIteratorB __bbegin, _InputIteratorB __bend, _InputIteratorW __wbegin) : _M_int(), _M_den(), _M_cp(), _M_m() { for (; __bbegin != __bend; ++__bbegin, ++__wbegin) { _M_int.push_back(*__bbegin); _M_den.push_back(*__wbegin); } _M_initialize(); } template template piecewise_linear_distribution<_RealType>::param_type:: param_type(initializer_list<_RealType> __bl, _Func __fw) : _M_int(), _M_den(), _M_cp(), _M_m() { _M_int.reserve(__bl.size()); _M_den.reserve(__bl.size()); for (auto __biter = __bl.begin(); __biter != __bl.end(); ++__biter) { _M_int.push_back(*__biter); _M_den.push_back(__fw(*__biter)); } _M_initialize(); } template template piecewise_linear_distribution<_RealType>::param_type:: param_type(size_t __nw, _RealType __xmin, _RealType __xmax, _Func __fw) : _M_int(), _M_den(), _M_cp(), _M_m() { const size_t __n = __nw == 0 ? 1 : __nw; const _RealType __delta = (__xmax - __xmin) / __n; _M_int.reserve(__n + 1); _M_den.reserve(__n + 1); for (size_t __k = 0; __k <= __nw; ++__k) { _M_int.push_back(__xmin + __k * __delta); _M_den.push_back(__fw(_M_int[__k] + __delta)); } _M_initialize(); } template template typename piecewise_linear_distribution<_RealType>::result_type piecewise_linear_distribution<_RealType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { __detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng); const double __p = __aurng(); if (__param._M_cp.empty()) return __p; auto __pos = std::lower_bound(__param._M_cp.begin(), __param._M_cp.end(), __p); const size_t __i = __pos - __param._M_cp.begin(); const double __pref = __i > 0 ? __param._M_cp[__i - 1] : 0.0; const double __a = 0.5 * __param._M_m[__i]; const double __b = __param._M_den[__i]; const double __cm = __p - __pref; _RealType __x = __param._M_int[__i]; if (__a == 0) __x += __cm / __b; else { const double __d = __b * __b + 4.0 * __a * __cm; __x += 0.5 * (std::sqrt(__d) - __b) / __a; } return __x; } template template void piecewise_linear_distribution<_RealType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) // We could duplicate everything from operator()... while (__f != __t) *__f++ = this->operator()(__urng, __param); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const piecewise_linear_distribution<_RealType>& __x) { typedef std::basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __os.flags(); const _CharT __fill = __os.fill(); const std::streamsize __precision = __os.precision(); const _CharT __space = __os.widen(' '); __os.flags(__ios_base::scientific | __ios_base::left); __os.fill(__space); __os.precision(std::numeric_limits<_RealType>::max_digits10); std::vector<_RealType> __int = __x.intervals(); __os << __int.size() - 1; for (auto __xit = __int.begin(); __xit != __int.end(); ++__xit) __os << __space << *__xit; std::vector __den = __x.densities(); for (auto __dit = __den.begin(); __dit != __den.end(); ++__dit) __os << __space << *__dit; __os.flags(__flags); __os.fill(__fill); __os.precision(__precision); return __os; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, piecewise_linear_distribution<_RealType>& __x) { typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; const typename __ios_base::fmtflags __flags = __is.flags(); __is.flags(__ios_base::dec | __ios_base::skipws); size_t __n; if (__is >> __n) { vector<_RealType> __int_vec; if (__detail::__extract_params(__is, __int_vec, __n + 1)) { vector __den_vec; if (__detail::__extract_params(__is, __den_vec, __n + 1)) { __x.param({ __int_vec.begin(), __int_vec.end(), __den_vec.begin() }); } } } __is.flags(__flags); return __is; } template seed_seq::seed_seq(std::initializer_list<_IntType> __il) { for (auto __iter = __il.begin(); __iter != __il.end(); ++__iter) _M_v.push_back(__detail::__mod::__value>(*__iter)); } template seed_seq::seed_seq(_InputIterator __begin, _InputIterator __end) { for (_InputIterator __iter = __begin; __iter != __end; ++__iter) _M_v.push_back(__detail::__mod::__value>(*__iter)); } template void seed_seq::generate(_RandomAccessIterator __begin, _RandomAccessIterator __end) { typedef typename iterator_traits<_RandomAccessIterator>::value_type _Type; if (__begin == __end) return; std::fill(__begin, __end, _Type(0x8b8b8b8bu)); const size_t __n = __end - __begin; const size_t __s = _M_v.size(); const size_t __t = (__n >= 623) ? 11 : (__n >= 68) ? 7 : (__n >= 39) ? 5 : (__n >= 7) ? 3 : (__n - 1) / 2; const size_t __p = (__n - __t) / 2; const size_t __q = __p + __t; const size_t __m = std::max(size_t(__s + 1), __n); for (size_t __k = 0; __k < __m; ++__k) { _Type __arg = (__begin[__k % __n] ^ __begin[(__k + __p) % __n] ^ __begin[(__k - 1) % __n]); _Type __r1 = __arg ^ (__arg >> 27); __r1 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(1664525u * __r1); _Type __r2 = __r1; if (__k == 0) __r2 += __s; else if (__k <= __s) __r2 += __k % __n + _M_v[__k - 1]; else __r2 += __k % __n; __r2 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(__r2); __begin[(__k + __p) % __n] += __r1; __begin[(__k + __q) % __n] += __r2; __begin[__k % __n] = __r2; } for (size_t __k = __m; __k < __m + __n; ++__k) { _Type __arg = (__begin[__k % __n] + __begin[(__k + __p) % __n] + __begin[(__k - 1) % __n]); _Type __r3 = __arg ^ (__arg >> 27); __r3 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(1566083941u * __r3); _Type __r4 = __r3 - __k % __n; __r4 = __detail::__mod<_Type, __detail::_Shift<_Type, 32>::__value>(__r4); __begin[(__k + __p) % __n] ^= __r3; __begin[(__k + __q) % __n] ^= __r4; __begin[__k % __n] = __r4; } } template _RealType generate_canonical(_UniformRandomNumberGenerator& __urng) { static_assert(std::is_floating_point<_RealType>::value, "template argument must be a floating point type"); const size_t __b = std::min(static_cast(std::numeric_limits<_RealType>::digits), __bits); const long double __r = static_cast(__urng.max()) - static_cast(__urng.min()) + 1.0L; const size_t __log2r = std::log(__r) / std::log(2.0L); const size_t __m = std::max(1UL, (__b + __log2r - 1UL) / __log2r); _RealType __ret; _RealType __sum = _RealType(0); _RealType __tmp = _RealType(1); for (size_t __k = __m; __k != 0; --__k) { __sum += _RealType(__urng() - __urng.min()) * __tmp; __tmp *= __r; } __ret = __sum / __tmp; if (__builtin_expect(__ret >= _RealType(1), 0)) { #if _GLIBCXX_USE_C99_MATH_TR1 __ret = std::nextafter(_RealType(1), _RealType(0)); #else __ret = _RealType(1) - std::numeric_limits<_RealType>::epsilon() / _RealType(2); #endif } return __ret; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/regex.tcc000064400000040265151027430570010044 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { // Result of merging regex_match and regex_search. // // __policy now can be _S_auto (auto dispatch) and _S_alternate (use // the other one if possible, for test purpose). // // That __match_mode is true means regex_match, else regex_search. template bool __regex_algo_impl(_BiIter __s, _BiIter __e, match_results<_BiIter, _Alloc>& __m, const basic_regex<_CharT, _TraitsT>& __re, regex_constants::match_flag_type __flags) { if (__re._M_automaton == nullptr) return false; typename match_results<_BiIter, _Alloc>::_Base_type& __res = __m; __m._M_begin = __s; __m._M_resize(__re._M_automaton->_M_sub_count()); for (auto& __it : __res) __it.matched = false; bool __ret; if ((__re.flags() & regex_constants::__polynomial) || (__policy == _RegexExecutorPolicy::_S_alternate && !__re._M_automaton->_M_has_backref)) { _Executor<_BiIter, _Alloc, _TraitsT, false> __executor(__s, __e, __m, __re, __flags); if (__match_mode) __ret = __executor._M_match(); else __ret = __executor._M_search(); } else { _Executor<_BiIter, _Alloc, _TraitsT, true> __executor(__s, __e, __m, __re, __flags); if (__match_mode) __ret = __executor._M_match(); else __ret = __executor._M_search(); } if (__ret) { for (auto& __it : __res) if (!__it.matched) __it.first = __it.second = __e; auto& __pre = __m._M_prefix(); auto& __suf = __m._M_suffix(); if (__match_mode) { __pre.matched = false; __pre.first = __s; __pre.second = __s; __suf.matched = false; __suf.first = __e; __suf.second = __e; } else { __pre.first = __s; __pre.second = __res[0].first; __pre.matched = (__pre.first != __pre.second); __suf.first = __res[0].second; __suf.second = __e; __suf.matched = (__suf.first != __suf.second); } } else { __m._M_resize(0); for (auto& __it : __res) { __it.matched = false; __it.first = __it.second = __e; } } return __ret; } } template template typename regex_traits<_Ch_type>::string_type regex_traits<_Ch_type>:: lookup_collatename(_Fwd_iter __first, _Fwd_iter __last) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); static const char* __collatenames[] = { "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "alert", "backspace", "tab", "newline", "vertical-tab", "form-feed", "carriage-return", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "IS4", "IS3", "IS2", "IS1", "space", "exclamation-mark", "quotation-mark", "number-sign", "dollar-sign", "percent-sign", "ampersand", "apostrophe", "left-parenthesis", "right-parenthesis", "asterisk", "plus-sign", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less-than-sign", "equals-sign", "greater-than-sign", "question-mark", "commercial-at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "left-square-bracket", "backslash", "right-square-bracket", "circumflex", "underscore", "grave-accent", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "left-curly-bracket", "vertical-line", "right-curly-bracket", "tilde", "DEL", }; string __s; for (; __first != __last; ++__first) __s += __fctyp.narrow(*__first, 0); for (const auto& __it : __collatenames) if (__s == __it) return string_type(1, __fctyp.widen( static_cast(&__it - __collatenames))); // TODO Add digraph support: // http://boost.sourceforge.net/libs/regex/doc/collating_names.html return string_type(); } template template typename regex_traits<_Ch_type>::char_class_type regex_traits<_Ch_type>:: lookup_classname(_Fwd_iter __first, _Fwd_iter __last, bool __icase) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); // Mappings from class name to class mask. static const pair __classnames[] = { {"d", ctype_base::digit}, {"w", {ctype_base::alnum, _RegexMask::_S_under}}, {"s", ctype_base::space}, {"alnum", ctype_base::alnum}, {"alpha", ctype_base::alpha}, {"blank", ctype_base::blank}, {"cntrl", ctype_base::cntrl}, {"digit", ctype_base::digit}, {"graph", ctype_base::graph}, {"lower", ctype_base::lower}, {"print", ctype_base::print}, {"punct", ctype_base::punct}, {"space", ctype_base::space}, {"upper", ctype_base::upper}, {"xdigit", ctype_base::xdigit}, }; string __s; for (; __first != __last; ++__first) __s += __fctyp.narrow(__fctyp.tolower(*__first), 0); for (const auto& __it : __classnames) if (__s == __it.first) { if (__icase && ((__it.second & (ctype_base::lower | ctype_base::upper)) != 0)) return ctype_base::alpha; return __it.second; } return 0; } template bool regex_traits<_Ch_type>:: isctype(_Ch_type __c, char_class_type __f) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); return __fctyp.is(__f._M_base, __c) // [[:w:]] || ((__f._M_extended & _RegexMask::_S_under) && __c == __fctyp.widen('_')); } template int regex_traits<_Ch_type>:: value(_Ch_type __ch, int __radix) const { std::basic_istringstream __is(string_type(1, __ch)); long __v; if (__radix == 8) __is >> std::oct; else if (__radix == 16) __is >> std::hex; __is >> __v; return __is.fail() ? -1 : __v; } template template _Out_iter match_results<_Bi_iter, _Alloc>:: format(_Out_iter __out, const match_results<_Bi_iter, _Alloc>::char_type* __fmt_first, const match_results<_Bi_iter, _Alloc>::char_type* __fmt_last, match_flag_type __flags) const { __glibcxx_assert( ready() ); regex_traits __traits; typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(__traits.getloc())); auto __output = [&](size_t __idx) { auto& __sub = (*this)[__idx]; if (__sub.matched) __out = std::copy(__sub.first, __sub.second, __out); }; if (__flags & regex_constants::format_sed) { bool __escaping = false; for (; __fmt_first != __fmt_last; __fmt_first++) { if (__escaping) { __escaping = false; if (__fctyp.is(__ctype_type::digit, *__fmt_first)) __output(__traits.value(*__fmt_first, 10)); else *__out++ = *__fmt_first; continue; } if (*__fmt_first == '\\') { __escaping = true; continue; } if (*__fmt_first == '&') { __output(0); continue; } *__out++ = *__fmt_first; } if (__escaping) *__out++ = '\\'; } else { while (1) { auto __next = std::find(__fmt_first, __fmt_last, '$'); if (__next == __fmt_last) break; __out = std::copy(__fmt_first, __next, __out); auto __eat = [&](char __ch) -> bool { if (*__next == __ch) { ++__next; return true; } return false; }; if (++__next == __fmt_last) *__out++ = '$'; else if (__eat('$')) *__out++ = '$'; else if (__eat('&')) __output(0); else if (__eat('`')) { auto& __sub = _M_prefix(); if (__sub.matched) __out = std::copy(__sub.first, __sub.second, __out); } else if (__eat('\'')) { auto& __sub = _M_suffix(); if (__sub.matched) __out = std::copy(__sub.first, __sub.second, __out); } else if (__fctyp.is(__ctype_type::digit, *__next)) { long __num = __traits.value(*__next, 10); if (++__next != __fmt_last && __fctyp.is(__ctype_type::digit, *__next)) { __num *= 10; __num += __traits.value(*__next++, 10); } if (0 <= __num && __num < this->size()) __output(__num); } else *__out++ = '$'; __fmt_first = __next; } __out = std::copy(__fmt_first, __fmt_last, __out); } return __out; } template _Out_iter regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags) { typedef regex_iterator<_Bi_iter, _Ch_type, _Rx_traits> _IterT; _IterT __i(__first, __last, __e, __flags); _IterT __end; if (__i == __end) { if (!(__flags & regex_constants::format_no_copy)) __out = std::copy(__first, __last, __out); } else { sub_match<_Bi_iter> __last; auto __len = char_traits<_Ch_type>::length(__fmt); for (; __i != __end; ++__i) { if (!(__flags & regex_constants::format_no_copy)) __out = std::copy(__i->prefix().first, __i->prefix().second, __out); __out = __i->format(__out, __fmt, __fmt + __len, __flags); __last = __i->suffix(); if (__flags & regex_constants::format_first_only) break; } if (!(__flags & regex_constants::format_no_copy)) __out = std::copy(__last.first, __last.second, __out); } return __out; } template bool regex_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator==(const regex_iterator& __rhs) const { if (_M_pregex == nullptr && __rhs._M_pregex == nullptr) return true; return _M_pregex == __rhs._M_pregex && _M_begin == __rhs._M_begin && _M_end == __rhs._M_end && _M_flags == __rhs._M_flags && _M_match[0] == __rhs._M_match[0]; } template regex_iterator<_Bi_iter, _Ch_type, _Rx_traits>& regex_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator++() { // In all cases in which the call to regex_search returns true, // match.prefix().first shall be equal to the previous value of // match[0].second, and for each index i in the half-open range // [0, match.size()) for which match[i].matched is true, // match[i].position() shall return distance(begin, match[i].first). // [28.12.1.4.5] if (_M_match[0].matched) { auto __start = _M_match[0].second; auto __prefix_first = _M_match[0].second; if (_M_match[0].first == _M_match[0].second) { if (__start == _M_end) { _M_pregex = nullptr; return *this; } else { if (regex_search(__start, _M_end, _M_match, *_M_pregex, _M_flags | regex_constants::match_not_null | regex_constants::match_continuous)) { __glibcxx_assert(_M_match[0].matched); auto& __prefix = _M_match._M_prefix(); __prefix.first = __prefix_first; __prefix.matched = __prefix.first != __prefix.second; // [28.12.1.4.5] _M_match._M_begin = _M_begin; return *this; } else ++__start; } } _M_flags |= regex_constants::match_prev_avail; if (regex_search(__start, _M_end, _M_match, *_M_pregex, _M_flags)) { __glibcxx_assert(_M_match[0].matched); auto& __prefix = _M_match._M_prefix(); __prefix.first = __prefix_first; __prefix.matched = __prefix.first != __prefix.second; // [28.12.1.4.5] _M_match._M_begin = _M_begin; } else _M_pregex = nullptr; } return *this; } template regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>& regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator=(const regex_token_iterator& __rhs) { _M_position = __rhs._M_position; _M_subs = __rhs._M_subs; _M_n = __rhs._M_n; _M_suffix = __rhs._M_suffix; _M_has_m1 = __rhs._M_has_m1; _M_normalize_result(); return *this; } template bool regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator==(const regex_token_iterator& __rhs) const { if (_M_end_of_seq() && __rhs._M_end_of_seq()) return true; if (_M_suffix.matched && __rhs._M_suffix.matched && _M_suffix == __rhs._M_suffix) return true; if (_M_end_of_seq() || _M_suffix.matched || __rhs._M_end_of_seq() || __rhs._M_suffix.matched) return false; return _M_position == __rhs._M_position && _M_n == __rhs._M_n && _M_subs == __rhs._M_subs; } template regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>& regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: operator++() { _Position __prev = _M_position; if (_M_suffix.matched) *this = regex_token_iterator(); else if (_M_n + 1 < _M_subs.size()) { _M_n++; _M_result = &_M_current_match(); } else { _M_n = 0; ++_M_position; if (_M_position != _Position()) _M_result = &_M_current_match(); else if (_M_has_m1 && __prev->suffix().length() != 0) { _M_suffix.matched = true; _M_suffix.first = __prev->suffix().first; _M_suffix.second = __prev->suffix().second; _M_result = &_M_suffix; } else *this = regex_token_iterator(); } return *this; } template void regex_token_iterator<_Bi_iter, _Ch_type, _Rx_traits>:: _M_init(_Bi_iter __a, _Bi_iter __b) { _M_has_m1 = false; for (auto __it : _M_subs) if (__it == -1) { _M_has_m1 = true; break; } if (_M_position != _Position()) _M_result = &_M_current_match(); else if (_M_has_m1) { _M_suffix.matched = true; _M_suffix.first = __a; _M_suffix.second = __b; _M_result = &_M_suffix; } else _M_result = nullptr; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/bits/shared_ptr_base.h000064400000152016151027430570011533 0ustar00// shared_ptr and weak_ptr implementation details -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // GCC Note: Based on files from version 1.32.0 of the Boost library. // shared_count.hpp // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // shared_ptr.hpp // Copyright (C) 1998, 1999 Greg Colvin and Beman Dawes. // Copyright (C) 2001, 2002, 2003 Peter Dimov // weak_ptr.hpp // Copyright (C) 2001, 2002, 2003 Peter Dimov // enable_shared_from_this.hpp // Copyright (C) 2002 Peter Dimov // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /** @file bits/shared_ptr_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _SHARED_PTR_BASE_H #define _SHARED_PTR_BASE_H 1 #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template class auto_ptr; #pragma GCC diagnostic pop #endif /** * @brief Exception possibly thrown by @c shared_ptr. * @ingroup exceptions */ class bad_weak_ptr : public std::exception { public: virtual char const* what() const noexcept; virtual ~bad_weak_ptr() noexcept; }; // Substitute for bad_weak_ptr object in the case of -fno-exceptions. inline void __throw_bad_weak_ptr() { _GLIBCXX_THROW_OR_ABORT(bad_weak_ptr()); } using __gnu_cxx::_Lock_policy; using __gnu_cxx::__default_lock_policy; using __gnu_cxx::_S_single; using __gnu_cxx::_S_mutex; using __gnu_cxx::_S_atomic; // Empty helper class except when the template argument is _S_mutex. template<_Lock_policy _Lp> class _Mutex_base { protected: // The atomic policy uses fully-fenced builtins, single doesn't care. enum { _S_need_barriers = 0 }; }; template<> class _Mutex_base<_S_mutex> : public __gnu_cxx::__mutex { protected: // This policy is used when atomic builtins are not available. // The replacement atomic operations might not have the necessary // memory barriers. enum { _S_need_barriers = 1 }; }; template<_Lock_policy _Lp = __default_lock_policy> class _Sp_counted_base : public _Mutex_base<_Lp> { public: _Sp_counted_base() noexcept : _M_use_count(1), _M_weak_count(1) { } virtual ~_Sp_counted_base() noexcept { } // Called when _M_use_count drops to zero, to release the resources // managed by *this. virtual void _M_dispose() noexcept = 0; // Called when _M_weak_count drops to zero. virtual void _M_destroy() noexcept { delete this; } virtual void* _M_get_deleter(const std::type_info&) noexcept = 0; void _M_add_ref_copy() { __gnu_cxx::__atomic_add_dispatch(&_M_use_count, 1); } void _M_add_ref_lock(); bool _M_add_ref_lock_nothrow(); void _M_release() noexcept { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_use_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_use_count); _M_dispose(); // There must be a memory barrier between dispose() and destroy() // to ensure that the effects of dispose() are observed in the // thread that runs destroy(). // See http://gcc.gnu.org/ml/libstdc++/2005-11/msg00136.html if (_Mutex_base<_Lp>::_S_need_barriers) { __atomic_thread_fence (__ATOMIC_ACQ_REL); } // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count); _M_destroy(); } } } void _M_weak_add_ref() noexcept { __gnu_cxx::__atomic_add_dispatch(&_M_weak_count, 1); } void _M_weak_release() noexcept { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_weak_count); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_weak_count, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_weak_count); if (_Mutex_base<_Lp>::_S_need_barriers) { // See _M_release(), // destroy() must observe results of dispose() __atomic_thread_fence (__ATOMIC_ACQ_REL); } _M_destroy(); } } long _M_get_use_count() const noexcept { // No memory barrier is used here so there is no synchronization // with other threads. return __atomic_load_n(&_M_use_count, __ATOMIC_RELAXED); } private: _Sp_counted_base(_Sp_counted_base const&) = delete; _Sp_counted_base& operator=(_Sp_counted_base const&) = delete; _Atomic_word _M_use_count; // #shared _Atomic_word _M_weak_count; // #weak + (#shared != 0) }; template<> inline void _Sp_counted_base<_S_single>:: _M_add_ref_lock() { if (_M_use_count == 0) __throw_bad_weak_ptr(); ++_M_use_count; } template<> inline void _Sp_counted_base<_S_mutex>:: _M_add_ref_lock() { __gnu_cxx::__scoped_lock sentry(*this); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, 1) == 0) { _M_use_count = 0; __throw_bad_weak_ptr(); } } template<> inline void _Sp_counted_base<_S_atomic>:: _M_add_ref_lock() { // Perform lock-free add-if-not-zero operation. _Atomic_word __count = _M_get_use_count(); do { if (__count == 0) __throw_bad_weak_ptr(); // Replace the current counter value with the old value + 1, as // long as it's not changed meanwhile. } while (!__atomic_compare_exchange_n(&_M_use_count, &__count, __count + 1, true, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)); } template<> inline bool _Sp_counted_base<_S_single>:: _M_add_ref_lock_nothrow() { if (_M_use_count == 0) return false; ++_M_use_count; return true; } template<> inline bool _Sp_counted_base<_S_mutex>:: _M_add_ref_lock_nothrow() { __gnu_cxx::__scoped_lock sentry(*this); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_use_count, 1) == 0) { _M_use_count = 0; return false; } return true; } template<> inline bool _Sp_counted_base<_S_atomic>:: _M_add_ref_lock_nothrow() { // Perform lock-free add-if-not-zero operation. _Atomic_word __count = _M_get_use_count(); do { if (__count == 0) return false; // Replace the current counter value with the old value + 1, as // long as it's not changed meanwhile. } while (!__atomic_compare_exchange_n(&_M_use_count, &__count, __count + 1, true, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)); return true; } template<> inline void _Sp_counted_base<_S_single>::_M_add_ref_copy() { ++_M_use_count; } template<> inline void _Sp_counted_base<_S_single>::_M_release() noexcept { if (--_M_use_count == 0) { _M_dispose(); if (--_M_weak_count == 0) _M_destroy(); } } template<> inline void _Sp_counted_base<_S_single>::_M_weak_add_ref() noexcept { ++_M_weak_count; } template<> inline void _Sp_counted_base<_S_single>::_M_weak_release() noexcept { if (--_M_weak_count == 0) _M_destroy(); } template<> inline long _Sp_counted_base<_S_single>::_M_get_use_count() const noexcept { return _M_use_count; } // Forward declarations. template class __shared_ptr; template class __weak_ptr; template class __enable_shared_from_this; template class shared_ptr; template class weak_ptr; template struct owner_less; template class enable_shared_from_this; template<_Lock_policy _Lp = __default_lock_policy> class __weak_count; template<_Lock_policy _Lp = __default_lock_policy> class __shared_count; // Counted ptr with no deleter or allocator support template class _Sp_counted_ptr final : public _Sp_counted_base<_Lp> { public: explicit _Sp_counted_ptr(_Ptr __p) noexcept : _M_ptr(__p) { } virtual void _M_dispose() noexcept { delete _M_ptr; } virtual void _M_destroy() noexcept { delete this; } virtual void* _M_get_deleter(const std::type_info&) noexcept { return nullptr; } _Sp_counted_ptr(const _Sp_counted_ptr&) = delete; _Sp_counted_ptr& operator=(const _Sp_counted_ptr&) = delete; private: _Ptr _M_ptr; }; template<> inline void _Sp_counted_ptr::_M_dispose() noexcept { } template<> inline void _Sp_counted_ptr::_M_dispose() noexcept { } template<> inline void _Sp_counted_ptr::_M_dispose() noexcept { } template struct _Sp_ebo_helper; /// Specialization using EBO. template struct _Sp_ebo_helper<_Nm, _Tp, true> : private _Tp { explicit _Sp_ebo_helper(const _Tp& __tp) : _Tp(__tp) { } explicit _Sp_ebo_helper(_Tp&& __tp) : _Tp(std::move(__tp)) { } static _Tp& _S_get(_Sp_ebo_helper& __eboh) { return static_cast<_Tp&>(__eboh); } }; /// Specialization not using EBO. template struct _Sp_ebo_helper<_Nm, _Tp, false> { explicit _Sp_ebo_helper(const _Tp& __tp) : _M_tp(__tp) { } explicit _Sp_ebo_helper(_Tp&& __tp) : _M_tp(std::move(__tp)) { } static _Tp& _S_get(_Sp_ebo_helper& __eboh) { return __eboh._M_tp; } private: _Tp _M_tp; }; // Support for custom deleter and/or allocator template class _Sp_counted_deleter final : public _Sp_counted_base<_Lp> { class _Impl : _Sp_ebo_helper<0, _Deleter>, _Sp_ebo_helper<1, _Alloc> { typedef _Sp_ebo_helper<0, _Deleter> _Del_base; typedef _Sp_ebo_helper<1, _Alloc> _Alloc_base; public: _Impl(_Ptr __p, _Deleter __d, const _Alloc& __a) noexcept : _M_ptr(__p), _Del_base(std::move(__d)), _Alloc_base(__a) { } _Deleter& _M_del() noexcept { return _Del_base::_S_get(*this); } _Alloc& _M_alloc() noexcept { return _Alloc_base::_S_get(*this); } _Ptr _M_ptr; }; public: using __allocator_type = __alloc_rebind<_Alloc, _Sp_counted_deleter>; // __d(__p) must not throw. _Sp_counted_deleter(_Ptr __p, _Deleter __d) noexcept : _M_impl(__p, std::move(__d), _Alloc()) { } // __d(__p) must not throw. _Sp_counted_deleter(_Ptr __p, _Deleter __d, const _Alloc& __a) noexcept : _M_impl(__p, std::move(__d), __a) { } ~_Sp_counted_deleter() noexcept { } virtual void _M_dispose() noexcept { _M_impl._M_del()(_M_impl._M_ptr); } virtual void _M_destroy() noexcept { __allocator_type __a(_M_impl._M_alloc()); __allocated_ptr<__allocator_type> __guard_ptr{ __a, this }; this->~_Sp_counted_deleter(); } virtual void* _M_get_deleter(const std::type_info& __ti) noexcept { #if __cpp_rtti // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2400. shared_ptr's get_deleter() should use addressof() return __ti == typeid(_Deleter) ? std::__addressof(_M_impl._M_del()) : nullptr; #else return nullptr; #endif } private: _Impl _M_impl; }; // helpers for make_shared / allocate_shared struct _Sp_make_shared_tag { private: template friend class _Sp_counted_ptr_inplace; static const type_info& _S_ti() noexcept _GLIBCXX_VISIBILITY(default) { alignas(type_info) static constexpr char __tag[sizeof(type_info)] = { }; return reinterpret_cast(__tag); } }; template struct _Sp_alloc_shared_tag { const _Alloc& _M_a; }; template class _Sp_counted_ptr_inplace final : public _Sp_counted_base<_Lp> { class _Impl : _Sp_ebo_helper<0, _Alloc> { typedef _Sp_ebo_helper<0, _Alloc> _A_base; public: explicit _Impl(_Alloc __a) noexcept : _A_base(__a) { } _Alloc& _M_alloc() noexcept { return _A_base::_S_get(*this); } __gnu_cxx::__aligned_buffer<_Tp> _M_storage; }; public: using __allocator_type = __alloc_rebind<_Alloc, _Sp_counted_ptr_inplace>; template _Sp_counted_ptr_inplace(_Alloc __a, _Args&&... __args) : _M_impl(__a) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2070. allocate_shared should use allocator_traits::construct allocator_traits<_Alloc>::construct(__a, _M_ptr(), std::forward<_Args>(__args)...); // might throw } ~_Sp_counted_ptr_inplace() noexcept { } virtual void _M_dispose() noexcept { allocator_traits<_Alloc>::destroy(_M_impl._M_alloc(), _M_ptr()); } // Override because the allocator needs to know the dynamic type virtual void _M_destroy() noexcept { __allocator_type __a(_M_impl._M_alloc()); __allocated_ptr<__allocator_type> __guard_ptr{ __a, this }; this->~_Sp_counted_ptr_inplace(); } private: friend class __shared_count<_Lp>; // To be able to call _M_ptr(). // No longer used, but code compiled against old libstdc++ headers // might still call it from __shared_ptr ctor to get the pointer out. virtual void* _M_get_deleter(const std::type_info& __ti) noexcept override { // Check for the fake type_info first, so we don't try to access it // as a real type_info object. if (&__ti == &_Sp_make_shared_tag::_S_ti()) return const_cast::type*>(_M_ptr()); #if __cpp_rtti // Callers compiled with old libstdc++ headers and RTTI enabled // might pass this instead: else if (__ti == typeid(_Sp_make_shared_tag)) return const_cast::type*>(_M_ptr()); #else // Cannot detect a real type_info object. If the linker keeps a // definition of this function compiled with -fno-rtti then callers // that have RTTI enabled and pass a real type_info object will get // a null pointer returned. #endif return nullptr; } _Tp* _M_ptr() noexcept { return _M_impl._M_storage._M_ptr(); } _Impl _M_impl; }; // The default deleter for shared_ptr and shared_ptr. struct __sp_array_delete { template void operator()(_Yp* __p) const { delete[] __p; } }; template<_Lock_policy _Lp> class __shared_count { template struct __not_alloc_shared_tag { using type = void; }; template struct __not_alloc_shared_tag<_Sp_alloc_shared_tag<_Tp>> { }; public: constexpr __shared_count() noexcept : _M_pi(0) { } template explicit __shared_count(_Ptr __p) : _M_pi(0) { __try { _M_pi = new _Sp_counted_ptr<_Ptr, _Lp>(__p); } __catch(...) { delete __p; __throw_exception_again; } } template __shared_count(_Ptr __p, /* is_array = */ false_type) : __shared_count(__p) { } template __shared_count(_Ptr __p, /* is_array = */ true_type) : __shared_count(__p, __sp_array_delete{}, allocator()) { } template::type> __shared_count(_Ptr __p, _Deleter __d) : __shared_count(__p, std::move(__d), allocator()) { } template::type> __shared_count(_Ptr __p, _Deleter __d, _Alloc __a) : _M_pi(0) { typedef _Sp_counted_deleter<_Ptr, _Deleter, _Alloc, _Lp> _Sp_cd_type; __try { typename _Sp_cd_type::__allocator_type __a2(__a); auto __guard = std::__allocate_guarded(__a2); _Sp_cd_type* __mem = __guard.get(); ::new (__mem) _Sp_cd_type(__p, std::move(__d), std::move(__a)); _M_pi = __mem; __guard = nullptr; } __catch(...) { __d(__p); // Call _Deleter on __p. __throw_exception_again; } } template __shared_count(_Tp*& __p, _Sp_alloc_shared_tag<_Alloc> __a, _Args&&... __args) { typedef _Sp_counted_ptr_inplace<_Tp, _Alloc, _Lp> _Sp_cp_type; typename _Sp_cp_type::__allocator_type __a2(__a._M_a); auto __guard = std::__allocate_guarded(__a2); _Sp_cp_type* __mem = __guard.get(); auto __pi = ::new (__mem) _Sp_cp_type(__a._M_a, std::forward<_Args>(__args)...); __guard = nullptr; _M_pi = __pi; __p = __pi->_M_ptr(); } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // Special case for auto_ptr<_Tp> to provide the strong guarantee. template explicit __shared_count(std::auto_ptr<_Tp>&& __r); #pragma GCC diagnostic pop #endif // Special case for unique_ptr<_Tp,_Del> to provide the strong guarantee. template explicit __shared_count(std::unique_ptr<_Tp, _Del>&& __r) : _M_pi(0) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2415. Inconsistency between unique_ptr and shared_ptr if (__r.get() == nullptr) return; using _Ptr = typename unique_ptr<_Tp, _Del>::pointer; using _Del2 = typename conditional::value, reference_wrapper::type>, _Del>::type; using _Sp_cd_type = _Sp_counted_deleter<_Ptr, _Del2, allocator, _Lp>; using _Alloc = allocator<_Sp_cd_type>; using _Alloc_traits = allocator_traits<_Alloc>; _Alloc __a; _Sp_cd_type* __mem = _Alloc_traits::allocate(__a, 1); _Alloc_traits::construct(__a, __mem, __r.release(), __r.get_deleter()); // non-throwing _M_pi = __mem; } // Throw bad_weak_ptr when __r._M_get_use_count() == 0. explicit __shared_count(const __weak_count<_Lp>& __r); // Does not throw if __r._M_get_use_count() == 0, caller must check. explicit __shared_count(const __weak_count<_Lp>& __r, std::nothrow_t); ~__shared_count() noexcept { if (_M_pi != nullptr) _M_pi->_M_release(); } __shared_count(const __shared_count& __r) noexcept : _M_pi(__r._M_pi) { if (_M_pi != 0) _M_pi->_M_add_ref_copy(); } __shared_count& operator=(const __shared_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; if (__tmp != _M_pi) { if (__tmp != 0) __tmp->_M_add_ref_copy(); if (_M_pi != 0) _M_pi->_M_release(); _M_pi = __tmp; } return *this; } void _M_swap(__shared_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; __r._M_pi = _M_pi; _M_pi = __tmp; } long _M_get_use_count() const noexcept { return _M_pi != 0 ? _M_pi->_M_get_use_count() : 0; } bool _M_unique() const noexcept { return this->_M_get_use_count() == 1; } void* _M_get_deleter(const std::type_info& __ti) const noexcept { return _M_pi ? _M_pi->_M_get_deleter(__ti) : nullptr; } bool _M_less(const __shared_count& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } bool _M_less(const __weak_count<_Lp>& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } // Friend function injected into enclosing namespace and found by ADL friend inline bool operator==(const __shared_count& __a, const __shared_count& __b) noexcept { return __a._M_pi == __b._M_pi; } private: friend class __weak_count<_Lp>; _Sp_counted_base<_Lp>* _M_pi; }; template<_Lock_policy _Lp> class __weak_count { public: constexpr __weak_count() noexcept : _M_pi(nullptr) { } __weak_count(const __shared_count<_Lp>& __r) noexcept : _M_pi(__r._M_pi) { if (_M_pi != nullptr) _M_pi->_M_weak_add_ref(); } __weak_count(const __weak_count& __r) noexcept : _M_pi(__r._M_pi) { if (_M_pi != nullptr) _M_pi->_M_weak_add_ref(); } __weak_count(__weak_count&& __r) noexcept : _M_pi(__r._M_pi) { __r._M_pi = nullptr; } ~__weak_count() noexcept { if (_M_pi != nullptr) _M_pi->_M_weak_release(); } __weak_count& operator=(const __shared_count<_Lp>& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; if (__tmp != nullptr) __tmp->_M_weak_add_ref(); if (_M_pi != nullptr) _M_pi->_M_weak_release(); _M_pi = __tmp; return *this; } __weak_count& operator=(const __weak_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; if (__tmp != nullptr) __tmp->_M_weak_add_ref(); if (_M_pi != nullptr) _M_pi->_M_weak_release(); _M_pi = __tmp; return *this; } __weak_count& operator=(__weak_count&& __r) noexcept { if (_M_pi != nullptr) _M_pi->_M_weak_release(); _M_pi = __r._M_pi; __r._M_pi = nullptr; return *this; } void _M_swap(__weak_count& __r) noexcept { _Sp_counted_base<_Lp>* __tmp = __r._M_pi; __r._M_pi = _M_pi; _M_pi = __tmp; } long _M_get_use_count() const noexcept { return _M_pi != nullptr ? _M_pi->_M_get_use_count() : 0; } bool _M_less(const __weak_count& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } bool _M_less(const __shared_count<_Lp>& __rhs) const noexcept { return std::less<_Sp_counted_base<_Lp>*>()(this->_M_pi, __rhs._M_pi); } // Friend function injected into enclosing namespace and found by ADL friend inline bool operator==(const __weak_count& __a, const __weak_count& __b) noexcept { return __a._M_pi == __b._M_pi; } private: friend class __shared_count<_Lp>; _Sp_counted_base<_Lp>* _M_pi; }; // Now that __weak_count is defined we can define this constructor: template<_Lock_policy _Lp> inline __shared_count<_Lp>::__shared_count(const __weak_count<_Lp>& __r) : _M_pi(__r._M_pi) { if (_M_pi != nullptr) _M_pi->_M_add_ref_lock(); else __throw_bad_weak_ptr(); } // Now that __weak_count is defined we can define this constructor: template<_Lock_policy _Lp> inline __shared_count<_Lp>:: __shared_count(const __weak_count<_Lp>& __r, std::nothrow_t) : _M_pi(__r._M_pi) { if (_M_pi != nullptr) if (!_M_pi->_M_add_ref_lock_nothrow()) _M_pi = nullptr; } #define __cpp_lib_shared_ptr_arrays 201603 // Helper traits for shared_ptr of array: // A pointer type Y* is said to be compatible with a pointer type T* when // either Y* is convertible to T* or Y is U[N] and T is U cv []. template struct __sp_compatible_with : false_type { }; template struct __sp_compatible_with<_Yp*, _Tp*> : is_convertible<_Yp*, _Tp*>::type { }; template struct __sp_compatible_with<_Up(*)[_Nm], _Up(*)[]> : true_type { }; template struct __sp_compatible_with<_Up(*)[_Nm], const _Up(*)[]> : true_type { }; template struct __sp_compatible_with<_Up(*)[_Nm], volatile _Up(*)[]> : true_type { }; template struct __sp_compatible_with<_Up(*)[_Nm], const volatile _Up(*)[]> : true_type { }; // Test conversion from Y(*)[N] to U(*)[N] without forming invalid type Y[N]. template struct __sp_is_constructible_arrN : false_type { }; template struct __sp_is_constructible_arrN<_Up, _Nm, _Yp, __void_t<_Yp[_Nm]>> : is_convertible<_Yp(*)[_Nm], _Up(*)[_Nm]>::type { }; // Test conversion from Y(*)[] to U(*)[] without forming invalid type Y[]. template struct __sp_is_constructible_arr : false_type { }; template struct __sp_is_constructible_arr<_Up, _Yp, __void_t<_Yp[]>> : is_convertible<_Yp(*)[], _Up(*)[]>::type { }; // Trait to check if shared_ptr can be constructed from Y*. template struct __sp_is_constructible; // When T is U[N], Y(*)[N] shall be convertible to T*; template struct __sp_is_constructible<_Up[_Nm], _Yp> : __sp_is_constructible_arrN<_Up, _Nm, _Yp>::type { }; // when T is U[], Y(*)[] shall be convertible to T*; template struct __sp_is_constructible<_Up[], _Yp> : __sp_is_constructible_arr<_Up, _Yp>::type { }; // otherwise, Y* shall be convertible to T*. template struct __sp_is_constructible : is_convertible<_Yp*, _Tp*>::type { }; // Define operator* and operator-> for shared_ptr. template::value, bool = is_void<_Tp>::value> class __shared_ptr_access { public: using element_type = _Tp; element_type& operator*() const noexcept { __glibcxx_assert(_M_get() != nullptr); return *_M_get(); } element_type* operator->() const noexcept { _GLIBCXX_DEBUG_PEDASSERT(_M_get() != nullptr); return _M_get(); } private: element_type* _M_get() const noexcept { return static_cast*>(this)->get(); } }; // Define operator-> for shared_ptr. template class __shared_ptr_access<_Tp, _Lp, false, true> { public: using element_type = _Tp; element_type* operator->() const noexcept { auto __ptr = static_cast*>(this)->get(); _GLIBCXX_DEBUG_PEDASSERT(__ptr != nullptr); return __ptr; } }; // Define operator[] for shared_ptr and shared_ptr. template class __shared_ptr_access<_Tp, _Lp, true, false> { public: using element_type = typename remove_extent<_Tp>::type; #if __cplusplus <= 201402L [[__deprecated__("shared_ptr::operator* is absent from C++17")]] element_type& operator*() const noexcept { __glibcxx_assert(_M_get() != nullptr); return *_M_get(); } [[__deprecated__("shared_ptr::operator-> is absent from C++17")]] element_type* operator->() const noexcept { _GLIBCXX_DEBUG_PEDASSERT(_M_get() != nullptr); return _M_get(); } #endif element_type& operator[](ptrdiff_t __i) const { __glibcxx_assert(_M_get() != nullptr); __glibcxx_assert(!extent<_Tp>::value || __i < extent<_Tp>::value); return _M_get()[__i]; } private: element_type* _M_get() const noexcept { return static_cast*>(this)->get(); } }; template class __shared_ptr : public __shared_ptr_access<_Tp, _Lp> { public: using element_type = typename remove_extent<_Tp>::type; private: // Constraint for taking ownership of a pointer of type _Yp*: template using _SafeConv = typename enable_if<__sp_is_constructible<_Tp, _Yp>::value>::type; // Constraint for construction from shared_ptr and weak_ptr: template using _Compatible = typename enable_if<__sp_compatible_with<_Yp*, _Tp*>::value, _Res>::type; // Constraint for assignment from shared_ptr and weak_ptr: template using _Assignable = _Compatible<_Yp, __shared_ptr&>; // Constraint for construction from unique_ptr: template::pointer> using _UniqCompatible = typename enable_if<__and_< __sp_compatible_with<_Yp*, _Tp*>, is_convertible<_Ptr, element_type*> >::value, _Res>::type; // Constraint for assignment from unique_ptr: template using _UniqAssignable = _UniqCompatible<_Yp, _Del, __shared_ptr&>; public: #if __cplusplus > 201402L using weak_type = __weak_ptr<_Tp, _Lp>; #endif constexpr __shared_ptr() noexcept : _M_ptr(0), _M_refcount() { } template> explicit __shared_ptr(_Yp* __p) : _M_ptr(__p), _M_refcount(__p, typename is_array<_Tp>::type()) { static_assert( !is_void<_Yp>::value, "incomplete type" ); static_assert( sizeof(_Yp) > 0, "incomplete type" ); _M_enable_shared_from_this_with(__p); } template> __shared_ptr(_Yp* __p, _Deleter __d) : _M_ptr(__p), _M_refcount(__p, std::move(__d)) { static_assert(__is_invocable<_Deleter&, _Yp*&>::value, "deleter expression d(p) is well-formed"); _M_enable_shared_from_this_with(__p); } template> __shared_ptr(_Yp* __p, _Deleter __d, _Alloc __a) : _M_ptr(__p), _M_refcount(__p, std::move(__d), std::move(__a)) { static_assert(__is_invocable<_Deleter&, _Yp*&>::value, "deleter expression d(p) is well-formed"); _M_enable_shared_from_this_with(__p); } template __shared_ptr(nullptr_t __p, _Deleter __d) : _M_ptr(0), _M_refcount(__p, std::move(__d)) { } template __shared_ptr(nullptr_t __p, _Deleter __d, _Alloc __a) : _M_ptr(0), _M_refcount(__p, std::move(__d), std::move(__a)) { } template __shared_ptr(const __shared_ptr<_Yp, _Lp>& __r, element_type* __p) noexcept : _M_ptr(__p), _M_refcount(__r._M_refcount) // never throws { } __shared_ptr(const __shared_ptr&) noexcept = default; __shared_ptr& operator=(const __shared_ptr&) noexcept = default; ~__shared_ptr() = default; template> __shared_ptr(const __shared_ptr<_Yp, _Lp>& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) { } __shared_ptr(__shared_ptr&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount() { _M_refcount._M_swap(__r._M_refcount); __r._M_ptr = 0; } template> __shared_ptr(__shared_ptr<_Yp, _Lp>&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount() { _M_refcount._M_swap(__r._M_refcount); __r._M_ptr = 0; } template> explicit __shared_ptr(const __weak_ptr<_Yp, _Lp>& __r) : _M_refcount(__r._M_refcount) // may throw { // It is now safe to copy __r._M_ptr, as // _M_refcount(__r._M_refcount) did not throw. _M_ptr = __r._M_ptr; } // If an exception is thrown this constructor has no effect. template> __shared_ptr(unique_ptr<_Yp, _Del>&& __r) : _M_ptr(__r.get()), _M_refcount() { auto __raw = __to_address(__r.get()); _M_refcount = __shared_count<_Lp>(std::move(__r)); _M_enable_shared_from_this_with(__raw); } #if __cplusplus <= 201402L && _GLIBCXX_USE_DEPRECATED protected: // If an exception is thrown this constructor has no effect. template>, is_array<_Tp1>, is_convertible::pointer, _Tp*> >::value, bool>::type = true> __shared_ptr(unique_ptr<_Tp1, _Del>&& __r, __sp_array_delete) : _M_ptr(__r.get()), _M_refcount() { auto __raw = __to_address(__r.get()); _M_refcount = __shared_count<_Lp>(std::move(__r)); _M_enable_shared_from_this_with(__raw); } public: #endif #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // Postcondition: use_count() == 1 and __r.get() == 0 template> __shared_ptr(auto_ptr<_Yp>&& __r); #pragma GCC diagnostic pop #endif constexpr __shared_ptr(nullptr_t) noexcept : __shared_ptr() { } template _Assignable<_Yp> operator=(const __shared_ptr<_Yp, _Lp>& __r) noexcept { _M_ptr = __r._M_ptr; _M_refcount = __r._M_refcount; // __shared_count::op= doesn't throw return *this; } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template _Assignable<_Yp> operator=(auto_ptr<_Yp>&& __r) { __shared_ptr(std::move(__r)).swap(*this); return *this; } #pragma GCC diagnostic pop #endif __shared_ptr& operator=(__shared_ptr&& __r) noexcept { __shared_ptr(std::move(__r)).swap(*this); return *this; } template _Assignable<_Yp> operator=(__shared_ptr<_Yp, _Lp>&& __r) noexcept { __shared_ptr(std::move(__r)).swap(*this); return *this; } template _UniqAssignable<_Yp, _Del> operator=(unique_ptr<_Yp, _Del>&& __r) { __shared_ptr(std::move(__r)).swap(*this); return *this; } void reset() noexcept { __shared_ptr().swap(*this); } template _SafeConv<_Yp> reset(_Yp* __p) // _Yp must be complete. { // Catch self-reset errors. __glibcxx_assert(__p == 0 || __p != _M_ptr); __shared_ptr(__p).swap(*this); } template _SafeConv<_Yp> reset(_Yp* __p, _Deleter __d) { __shared_ptr(__p, std::move(__d)).swap(*this); } template _SafeConv<_Yp> reset(_Yp* __p, _Deleter __d, _Alloc __a) { __shared_ptr(__p, std::move(__d), std::move(__a)).swap(*this); } element_type* get() const noexcept { return _M_ptr; } explicit operator bool() const // never throws { return _M_ptr == 0 ? false : true; } bool unique() const noexcept { return _M_refcount._M_unique(); } long use_count() const noexcept { return _M_refcount._M_get_use_count(); } void swap(__shared_ptr<_Tp, _Lp>& __other) noexcept { std::swap(_M_ptr, __other._M_ptr); _M_refcount._M_swap(__other._M_refcount); } template bool owner_before(__shared_ptr<_Tp1, _Lp> const& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } template bool owner_before(__weak_ptr<_Tp1, _Lp> const& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } protected: // This constructor is non-standard, it is used by allocate_shared. template __shared_ptr(_Sp_alloc_shared_tag<_Alloc> __tag, _Args&&... __args) : _M_ptr(), _M_refcount(_M_ptr, __tag, std::forward<_Args>(__args)...) { _M_enable_shared_from_this_with(_M_ptr); } template friend __shared_ptr<_Tp1, _Lp1> __allocate_shared(const _Alloc& __a, _Args&&... __args); // This constructor is used by __weak_ptr::lock() and // shared_ptr::shared_ptr(const weak_ptr&, std::nothrow_t). __shared_ptr(const __weak_ptr<_Tp, _Lp>& __r, std::nothrow_t) : _M_refcount(__r._M_refcount, std::nothrow) { _M_ptr = _M_refcount._M_get_use_count() ? __r._M_ptr : nullptr; } friend class __weak_ptr<_Tp, _Lp>; private: template using __esft_base_t = decltype(__enable_shared_from_this_base( std::declval&>(), std::declval<_Yp*>())); // Detect an accessible and unambiguous enable_shared_from_this base. template struct __has_esft_base : false_type { }; template struct __has_esft_base<_Yp, __void_t<__esft_base_t<_Yp>>> : __not_> { }; // No enable shared_from_this for arrays template::type> typename enable_if<__has_esft_base<_Yp2>::value>::type _M_enable_shared_from_this_with(_Yp* __p) noexcept { if (auto __base = __enable_shared_from_this_base(_M_refcount, __p)) __base->_M_weak_assign(const_cast<_Yp2*>(__p), _M_refcount); } template::type> typename enable_if::value>::type _M_enable_shared_from_this_with(_Yp*) noexcept { } void* _M_get_deleter(const std::type_info& __ti) const noexcept { return _M_refcount._M_get_deleter(__ti); } template friend class __shared_ptr; template friend class __weak_ptr; template friend _Del* get_deleter(const __shared_ptr<_Tp1, _Lp1>&) noexcept; template friend _Del* get_deleter(const shared_ptr<_Tp1>&) noexcept; element_type* _M_ptr; // Contained pointer. __shared_count<_Lp> _M_refcount; // Reference counter. }; // 20.7.2.2.7 shared_ptr comparisons template inline bool operator==(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return __a.get() == __b.get(); } template inline bool operator==(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return !__a; } template inline bool operator==(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return !__a; } template inline bool operator!=(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return __a.get() != __b.get(); } template inline bool operator!=(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return (bool)__a; } template inline bool operator!=(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return (bool)__a; } template inline bool operator<(const __shared_ptr<_Tp, _Lp>& __a, const __shared_ptr<_Up, _Lp>& __b) noexcept { using _Tp_elt = typename __shared_ptr<_Tp, _Lp>::element_type; using _Up_elt = typename __shared_ptr<_Up, _Lp>::element_type; using _Vp = typename common_type<_Tp_elt*, _Up_elt*>::type; return less<_Vp>()(__a.get(), __b.get()); } template inline bool operator<(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { using _Tp_elt = typename __shared_ptr<_Tp, _Lp>::element_type; return less<_Tp_elt*>()(__a.get(), nullptr); } template inline bool operator<(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { using _Tp_elt = typename __shared_ptr<_Tp, _Lp>::element_type; return less<_Tp_elt*>()(nullptr, __a.get()); } template inline bool operator<=(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return !(__b < __a); } template inline bool operator<=(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return !(nullptr < __a); } template inline bool operator<=(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return !(__a < nullptr); } template inline bool operator>(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return (__b < __a); } template inline bool operator>(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return nullptr < __a; } template inline bool operator>(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return __a < nullptr; } template inline bool operator>=(const __shared_ptr<_Tp1, _Lp>& __a, const __shared_ptr<_Tp2, _Lp>& __b) noexcept { return !(__a < __b); } template inline bool operator>=(const __shared_ptr<_Tp, _Lp>& __a, nullptr_t) noexcept { return !(__a < nullptr); } template inline bool operator>=(nullptr_t, const __shared_ptr<_Tp, _Lp>& __a) noexcept { return !(nullptr < __a); } template struct _Sp_less : public binary_function<_Sp, _Sp, bool> { bool operator()(const _Sp& __lhs, const _Sp& __rhs) const noexcept { typedef typename _Sp::element_type element_type; return std::less()(__lhs.get(), __rhs.get()); } }; template struct less<__shared_ptr<_Tp, _Lp>> : public _Sp_less<__shared_ptr<_Tp, _Lp>> { }; // 20.7.2.2.8 shared_ptr specialized algorithms. template inline void swap(__shared_ptr<_Tp, _Lp>& __a, __shared_ptr<_Tp, _Lp>& __b) noexcept { __a.swap(__b); } // 20.7.2.2.9 shared_ptr casts // The seemingly equivalent code: // shared_ptr<_Tp, _Lp>(static_cast<_Tp*>(__r.get())) // will eventually result in undefined behaviour, attempting to // delete the same object twice. /// static_pointer_cast template inline __shared_ptr<_Tp, _Lp> static_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; return _Sp(__r, static_cast(__r.get())); } // The seemingly equivalent code: // shared_ptr<_Tp, _Lp>(const_cast<_Tp*>(__r.get())) // will eventually result in undefined behaviour, attempting to // delete the same object twice. /// const_pointer_cast template inline __shared_ptr<_Tp, _Lp> const_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; return _Sp(__r, const_cast(__r.get())); } // The seemingly equivalent code: // shared_ptr<_Tp, _Lp>(dynamic_cast<_Tp*>(__r.get())) // will eventually result in undefined behaviour, attempting to // delete the same object twice. /// dynamic_pointer_cast template inline __shared_ptr<_Tp, _Lp> dynamic_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; if (auto* __p = dynamic_cast(__r.get())) return _Sp(__r, __p); return _Sp(); } #if __cplusplus > 201402L template inline __shared_ptr<_Tp, _Lp> reinterpret_pointer_cast(const __shared_ptr<_Tp1, _Lp>& __r) noexcept { using _Sp = __shared_ptr<_Tp, _Lp>; return _Sp(__r, reinterpret_cast(__r.get())); } #endif template class __weak_ptr { template using _Compatible = typename enable_if<__sp_compatible_with<_Yp*, _Tp*>::value, _Res>::type; // Constraint for assignment from shared_ptr and weak_ptr: template using _Assignable = _Compatible<_Yp, __weak_ptr&>; public: using element_type = typename remove_extent<_Tp>::type; constexpr __weak_ptr() noexcept : _M_ptr(nullptr), _M_refcount() { } __weak_ptr(const __weak_ptr&) noexcept = default; ~__weak_ptr() = default; // The "obvious" converting constructor implementation: // // template // __weak_ptr(const __weak_ptr<_Tp1, _Lp>& __r) // : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) // never throws // { } // // has a serious problem. // // __r._M_ptr may already have been invalidated. The _M_ptr(__r._M_ptr) // conversion may require access to *__r._M_ptr (virtual inheritance). // // It is not possible to avoid spurious access violations since // in multithreaded programs __r._M_ptr may be invalidated at any point. template> __weak_ptr(const __weak_ptr<_Yp, _Lp>& __r) noexcept : _M_refcount(__r._M_refcount) { _M_ptr = __r.lock().get(); } template> __weak_ptr(const __shared_ptr<_Yp, _Lp>& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(__r._M_refcount) { } __weak_ptr(__weak_ptr&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(std::move(__r._M_refcount)) { __r._M_ptr = nullptr; } template> __weak_ptr(__weak_ptr<_Yp, _Lp>&& __r) noexcept : _M_ptr(__r.lock().get()), _M_refcount(std::move(__r._M_refcount)) { __r._M_ptr = nullptr; } __weak_ptr& operator=(const __weak_ptr& __r) noexcept = default; template _Assignable<_Yp> operator=(const __weak_ptr<_Yp, _Lp>& __r) noexcept { _M_ptr = __r.lock().get(); _M_refcount = __r._M_refcount; return *this; } template _Assignable<_Yp> operator=(const __shared_ptr<_Yp, _Lp>& __r) noexcept { _M_ptr = __r._M_ptr; _M_refcount = __r._M_refcount; return *this; } __weak_ptr& operator=(__weak_ptr&& __r) noexcept { _M_ptr = __r._M_ptr; _M_refcount = std::move(__r._M_refcount); __r._M_ptr = nullptr; return *this; } template _Assignable<_Yp> operator=(__weak_ptr<_Yp, _Lp>&& __r) noexcept { _M_ptr = __r.lock().get(); _M_refcount = std::move(__r._M_refcount); __r._M_ptr = nullptr; return *this; } __shared_ptr<_Tp, _Lp> lock() const noexcept { return __shared_ptr(*this, std::nothrow); } long use_count() const noexcept { return _M_refcount._M_get_use_count(); } bool expired() const noexcept { return _M_refcount._M_get_use_count() == 0; } template bool owner_before(const __shared_ptr<_Tp1, _Lp>& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } template bool owner_before(const __weak_ptr<_Tp1, _Lp>& __rhs) const noexcept { return _M_refcount._M_less(__rhs._M_refcount); } void reset() noexcept { __weak_ptr().swap(*this); } void swap(__weak_ptr& __s) noexcept { std::swap(_M_ptr, __s._M_ptr); _M_refcount._M_swap(__s._M_refcount); } private: // Used by __enable_shared_from_this. void _M_assign(_Tp* __ptr, const __shared_count<_Lp>& __refcount) noexcept { if (use_count() == 0) { _M_ptr = __ptr; _M_refcount = __refcount; } } template friend class __shared_ptr; template friend class __weak_ptr; friend class __enable_shared_from_this<_Tp, _Lp>; friend class enable_shared_from_this<_Tp>; element_type* _M_ptr; // Contained pointer. __weak_count<_Lp> _M_refcount; // Reference counter. }; // 20.7.2.3.6 weak_ptr specialized algorithms. template inline void swap(__weak_ptr<_Tp, _Lp>& __a, __weak_ptr<_Tp, _Lp>& __b) noexcept { __a.swap(__b); } template struct _Sp_owner_less : public binary_function<_Tp, _Tp, bool> { bool operator()(const _Tp& __lhs, const _Tp& __rhs) const noexcept { return __lhs.owner_before(__rhs); } bool operator()(const _Tp& __lhs, const _Tp1& __rhs) const noexcept { return __lhs.owner_before(__rhs); } bool operator()(const _Tp1& __lhs, const _Tp& __rhs) const noexcept { return __lhs.owner_before(__rhs); } }; template<> struct _Sp_owner_less { template auto operator()(const _Tp& __lhs, const _Up& __rhs) const noexcept -> decltype(__lhs.owner_before(__rhs)) { return __lhs.owner_before(__rhs); } using is_transparent = void; }; template struct owner_less<__shared_ptr<_Tp, _Lp>> : public _Sp_owner_less<__shared_ptr<_Tp, _Lp>, __weak_ptr<_Tp, _Lp>> { }; template struct owner_less<__weak_ptr<_Tp, _Lp>> : public _Sp_owner_less<__weak_ptr<_Tp, _Lp>, __shared_ptr<_Tp, _Lp>> { }; template class __enable_shared_from_this { protected: constexpr __enable_shared_from_this() noexcept { } __enable_shared_from_this(const __enable_shared_from_this&) noexcept { } __enable_shared_from_this& operator=(const __enable_shared_from_this&) noexcept { return *this; } ~__enable_shared_from_this() { } public: __shared_ptr<_Tp, _Lp> shared_from_this() { return __shared_ptr<_Tp, _Lp>(this->_M_weak_this); } __shared_ptr shared_from_this() const { return __shared_ptr(this->_M_weak_this); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 __weak_ptr<_Tp, _Lp> weak_from_this() noexcept { return this->_M_weak_this; } __weak_ptr weak_from_this() const noexcept { return this->_M_weak_this; } #endif private: template void _M_weak_assign(_Tp1* __p, const __shared_count<_Lp>& __n) const noexcept { _M_weak_this._M_assign(__p, __n); } friend const __enable_shared_from_this* __enable_shared_from_this_base(const __shared_count<_Lp>&, const __enable_shared_from_this* __p) { return __p; } template friend class __shared_ptr; mutable __weak_ptr<_Tp, _Lp> _M_weak_this; }; template inline __shared_ptr<_Tp, _Lp> __allocate_shared(const _Alloc& __a, _Args&&... __args) { static_assert(!is_array<_Tp>::value, "make_shared not supported"); return __shared_ptr<_Tp, _Lp>(_Sp_alloc_shared_tag<_Alloc>{__a}, std::forward<_Args>(__args)...); } template inline __shared_ptr<_Tp, _Lp> __make_shared(_Args&&... __args) { typedef typename std::remove_const<_Tp>::type _Tp_nc; return std::__allocate_shared<_Tp, _Lp>(std::allocator<_Tp_nc>(), std::forward<_Args>(__args)...); } /// std::hash specialization for __shared_ptr. template struct hash<__shared_ptr<_Tp, _Lp>> : public __hash_base> { size_t operator()(const __shared_ptr<_Tp, _Lp>& __s) const noexcept { return hash::element_type*>()( __s.get()); } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _SHARED_PTR_BASE_H c++/8/bits/stl_vector.h000064400000166166151027430570010605 0ustar00// Vector implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_vector.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ #ifndef _STL_VECTOR_H #define _STL_VECTOR_H 1 #include #include #include #if __cplusplus >= 201103L #include #endif #include #if _GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR extern "C" void __sanitizer_annotate_contiguous_container(const void*, const void*, const void*, const void*); #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// See bits/stl_deque.h's _Deque_base for an explanation. template struct _Vector_base { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type; typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type>::pointer pointer; struct _Vector_impl : public _Tp_alloc_type { pointer _M_start; pointer _M_finish; pointer _M_end_of_storage; _Vector_impl() : _Tp_alloc_type(), _M_start(), _M_finish(), _M_end_of_storage() { } _Vector_impl(_Tp_alloc_type const& __a) _GLIBCXX_NOEXCEPT : _Tp_alloc_type(__a), _M_start(), _M_finish(), _M_end_of_storage() { } #if __cplusplus >= 201103L _Vector_impl(_Tp_alloc_type&& __a) noexcept : _Tp_alloc_type(std::move(__a)), _M_start(), _M_finish(), _M_end_of_storage() { } #endif void _M_swap_data(_Vector_impl& __x) _GLIBCXX_NOEXCEPT { std::swap(_M_start, __x._M_start); std::swap(_M_finish, __x._M_finish); std::swap(_M_end_of_storage, __x._M_end_of_storage); } #if _GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR template struct _Asan { typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type> ::size_type size_type; static void _S_shrink(_Vector_impl&, size_type) { } static void _S_on_dealloc(_Vector_impl&) { } typedef _Vector_impl& _Reinit; struct _Grow { _Grow(_Vector_impl&, size_type) { } void _M_grew(size_type) { } }; }; // Enable ASan annotations for memory obtained from std::allocator. template struct _Asan > { typedef typename __gnu_cxx::__alloc_traits<_Tp_alloc_type> ::size_type size_type; // Adjust ASan annotation for [_M_start, _M_end_of_storage) to // mark end of valid region as __curr instead of __prev. static void _S_adjust(_Vector_impl& __impl, pointer __prev, pointer __curr) { __sanitizer_annotate_contiguous_container(__impl._M_start, __impl._M_end_of_storage, __prev, __curr); } static void _S_grow(_Vector_impl& __impl, size_type __n) { _S_adjust(__impl, __impl._M_finish, __impl._M_finish + __n); } static void _S_shrink(_Vector_impl& __impl, size_type __n) { _S_adjust(__impl, __impl._M_finish + __n, __impl._M_finish); } static void _S_on_dealloc(_Vector_impl& __impl) { if (__impl._M_start) _S_adjust(__impl, __impl._M_finish, __impl._M_end_of_storage); } // Used on reallocation to tell ASan unused capacity is invalid. struct _Reinit { explicit _Reinit(_Vector_impl& __impl) : _M_impl(__impl) { // Mark unused capacity as valid again before deallocating it. _S_on_dealloc(_M_impl); } ~_Reinit() { // Mark unused capacity as invalid after reallocation. if (_M_impl._M_start) _S_adjust(_M_impl, _M_impl._M_end_of_storage, _M_impl._M_finish); } _Vector_impl& _M_impl; #if __cplusplus >= 201103L _Reinit(const _Reinit&) = delete; _Reinit& operator=(const _Reinit&) = delete; #endif }; // Tell ASan when unused capacity is initialized to be valid. struct _Grow { _Grow(_Vector_impl& __impl, size_type __n) : _M_impl(__impl), _M_n(__n) { _S_grow(_M_impl, __n); } ~_Grow() { if (_M_n) _S_shrink(_M_impl, _M_n); } void _M_grew(size_type __n) { _M_n -= __n; } #if __cplusplus >= 201103L _Grow(const _Grow&) = delete; _Grow& operator=(const _Grow&) = delete; #endif private: _Vector_impl& _M_impl; size_type _M_n; }; }; #define _GLIBCXX_ASAN_ANNOTATE_REINIT \ typename _Base::_Vector_impl::template _Asan<>::_Reinit const \ __attribute__((__unused__)) __reinit_guard(this->_M_impl) #define _GLIBCXX_ASAN_ANNOTATE_GROW(n) \ typename _Base::_Vector_impl::template _Asan<>::_Grow \ __attribute__((__unused__)) __grow_guard(this->_M_impl, (n)) #define _GLIBCXX_ASAN_ANNOTATE_GREW(n) __grow_guard._M_grew(n) #define _GLIBCXX_ASAN_ANNOTATE_SHRINK(n) \ _Base::_Vector_impl::template _Asan<>::_S_shrink(this->_M_impl, n) #define _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC \ _Base::_Vector_impl::template _Asan<>::_S_on_dealloc(this->_M_impl) #else // ! (_GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR) #define _GLIBCXX_ASAN_ANNOTATE_REINIT #define _GLIBCXX_ASAN_ANNOTATE_GROW(n) #define _GLIBCXX_ASAN_ANNOTATE_GREW(n) #define _GLIBCXX_ASAN_ANNOTATE_SHRINK(n) #define _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC #endif // _GLIBCXX_SANITIZE_STD_ALLOCATOR && _GLIBCXX_SANITIZE_VECTOR }; public: typedef _Alloc allocator_type; _Tp_alloc_type& _M_get_Tp_allocator() _GLIBCXX_NOEXCEPT { return *static_cast<_Tp_alloc_type*>(&this->_M_impl); } const _Tp_alloc_type& _M_get_Tp_allocator() const _GLIBCXX_NOEXCEPT { return *static_cast(&this->_M_impl); } allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Tp_allocator()); } _Vector_base() : _M_impl() { } _Vector_base(const allocator_type& __a) _GLIBCXX_NOEXCEPT : _M_impl(__a) { } _Vector_base(size_t __n) : _M_impl() { _M_create_storage(__n); } _Vector_base(size_t __n, const allocator_type& __a) : _M_impl(__a) { _M_create_storage(__n); } #if __cplusplus >= 201103L _Vector_base(_Tp_alloc_type&& __a) noexcept : _M_impl(std::move(__a)) { } _Vector_base(_Vector_base&& __x) noexcept : _M_impl(std::move(__x._M_get_Tp_allocator())) { this->_M_impl._M_swap_data(__x._M_impl); } _Vector_base(_Vector_base&& __x, const allocator_type& __a) : _M_impl(__a) { if (__x.get_allocator() == __a) this->_M_impl._M_swap_data(__x._M_impl); else { size_t __n = __x._M_impl._M_finish - __x._M_impl._M_start; _M_create_storage(__n); } } #endif ~_Vector_base() _GLIBCXX_NOEXCEPT { _M_deallocate(_M_impl._M_start, _M_impl._M_end_of_storage - _M_impl._M_start); } public: _Vector_impl _M_impl; pointer _M_allocate(size_t __n) { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tr; return __n != 0 ? _Tr::allocate(_M_impl, __n) : pointer(); } void _M_deallocate(pointer __p, size_t __n) { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Tr; if (__p) _Tr::deallocate(_M_impl, __p, __n); } private: void _M_create_storage(size_t __n) { this->_M_impl._M_start = this->_M_allocate(__n); this->_M_impl._M_finish = this->_M_impl._M_start; this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; } }; /** * @brief A standard container which offers fixed time access to * individual elements in any order. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * reversible container, and a * sequence, including the * optional sequence requirements with the * %exception of @c push_front and @c pop_front. * * In some terminology a %vector can be described as a dynamic * C-style array, it offers fast and efficient access to individual * elements in any order and saves the user from worrying about * memory and size allocation. Subscripting ( @c [] ) access is * also provided as with C-style arrays. */ template > class vector : protected _Vector_base<_Tp, _Alloc> { #ifdef _GLIBCXX_CONCEPT_CHECKS // Concept requirements. typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires2(_Tp, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Tp>::value, "std::vector must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::vector must have the same value_type as its allocator"); # endif #endif typedef _Vector_base<_Tp, _Alloc> _Base; typedef typename _Base::_Tp_alloc_type _Tp_alloc_type; typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Alloc_traits; public: typedef _Tp value_type; typedef typename _Base::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef __gnu_cxx::__normal_iterator iterator; typedef __gnu_cxx::__normal_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; protected: using _Base::_M_allocate; using _Base::_M_deallocate; using _Base::_M_impl; using _Base::_M_get_Tp_allocator; public: // [23.2.4.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Creates a %vector with no elements. */ vector() #if __cplusplus >= 201103L noexcept(is_nothrow_default_constructible<_Alloc>::value) #endif : _Base() { } /** * @brief Creates a %vector with no elements. * @param __a An allocator object. */ explicit vector(const allocator_type& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus >= 201103L /** * @brief Creates a %vector with default constructed elements. * @param __n The number of elements to initially create. * @param __a An allocator. * * This constructor fills the %vector with @a __n default * constructed elements. */ explicit vector(size_type __n, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { _M_default_initialize(__n); } /** * @brief Creates a %vector with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %vector with @a __n copies of @a __value. */ vector(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { _M_fill_initialize(__n, __value); } #else /** * @brief Creates a %vector with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %vector with @a __n copies of @a __value. */ explicit vector(size_type __n, const value_type& __value = value_type(), const allocator_type& __a = allocator_type()) : _Base(__n, __a) { _M_fill_initialize(__n, __value); } #endif /** * @brief %Vector copy constructor. * @param __x A %vector of identical element and allocator types. * * All the elements of @a __x are copied, but any unused capacity in * @a __x will not be copied * (i.e. capacity() == size() in the new %vector). * * The newly-created %vector uses a copy of the allocator object used * by @a __x (unless the allocator traits dictate a different object). */ vector(const vector& __x) : _Base(__x.size(), _Alloc_traits::_S_select_on_copy(__x._M_get_Tp_allocator())) { this->_M_impl._M_finish = std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief %Vector move constructor. * @param __x A %vector of identical element and allocator types. * * The newly-created %vector contains the exact contents of @a __x. * The contents of @a __x are a valid, but unspecified %vector. */ vector(vector&& __x) noexcept : _Base(std::move(__x)) { } /// Copy constructor with alternative allocator vector(const vector& __x, const allocator_type& __a) : _Base(__x.size(), __a) { this->_M_impl._M_finish = std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } /// Move constructor with alternative allocator vector(vector&& __rv, const allocator_type& __m) noexcept(_Alloc_traits::_S_always_equal()) : _Base(std::move(__rv), __m) { if (__rv.get_allocator() != __m) { this->_M_impl._M_finish = std::__uninitialized_move_a(__rv.begin(), __rv.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); __rv.clear(); } } /** * @brief Builds a %vector from an initializer list. * @param __l An initializer_list. * @param __a An allocator. * * Create a %vector consisting of copies of the elements in the * initializer_list @a __l. * * This will call the element type's copy constructor N times * (where N is @a __l.size()) and do no memory reallocation. */ vector(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_range_initialize(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /** * @brief Builds a %vector from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __a An allocator. * * Create a %vector consisting of copies of the elements from * [first,last). * * If the iterators are forward, bidirectional, or * random-access, then this will call the elements' copy * constructor N times (where N is distance(first,last)) and do * no memory reallocation. But if only input iterators are * used, then this will do at most 2N calls to the copy * constructor, and logN memory reallocations. */ #if __cplusplus >= 201103L template> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif /** * The dtor only erases the elements, and note that if the * elements themselves are pointers, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ ~vector() _GLIBCXX_NOEXCEPT { std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish, _M_get_Tp_allocator()); _GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC; } /** * @brief %Vector assignment operator. * @param __x A %vector of identical element and allocator types. * * All the elements of @a __x are copied, but any unused capacity in * @a __x will not be copied. * * Whether the allocator is copied depends on the allocator traits. */ vector& operator=(const vector& __x); #if __cplusplus >= 201103L /** * @brief %Vector move assignment operator. * @param __x A %vector of identical element and allocator types. * * The contents of @a __x are moved into this %vector (without copying, * if the allocators permit it). * Afterwards @a __x is a valid, but unspecified %vector. * * Whether the allocator is moved depends on the allocator traits. */ vector& operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move()) { constexpr bool __move_storage = _Alloc_traits::_S_propagate_on_move_assign() || _Alloc_traits::_S_always_equal(); _M_move_assign(std::move(__x), __bool_constant<__move_storage>()); return *this; } /** * @brief %Vector list assignment operator. * @param __l An initializer_list. * * This function fills a %vector with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. */ vector& operator=(initializer_list __l) { this->_M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); return *this; } #endif /** * @brief Assigns a given value to a %vector. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %vector with @a __n copies of the given * value. Note that the assignment completely changes the * %vector and that the resulting %vector's size is the same as * the number of elements assigned. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %vector. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %vector with copies of the elements in the * range [__first,__last). * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. */ #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_dispatch(__first, __last, __false_type()); } #else template void assign(_InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * @brief Assigns an initializer list to a %vector. * @param __l An initializer_list. * * This function fills a %vector with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %vector and * that the resulting %vector's size is the same as the number * of elements assigned. */ void assign(initializer_list __l) { this->_M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /// Get a copy of the memory allocation object. using _Base::get_allocator; // iterators /** * Returns a read/write iterator that points to the first * element in the %vector. Iteration is done in ordinary * element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_start); } /** * Returns a read-only (constant) iterator that points to the * first element in the %vector. Iteration is done in ordinary * element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_start); } /** * Returns a read/write iterator that points one past the last * element in the %vector. Iteration is done in ordinary * element order. */ iterator end() _GLIBCXX_NOEXCEPT { return iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %vector. Iteration is done in * ordinary element order. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(this->_M_impl._M_finish); } /** * Returns a read/write reverse iterator that points to the * last element in the %vector. Iteration is done in reverse * element order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %vector. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %vector. Iteration is done * in reverse element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %vector. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the * first element in the %vector. Iteration is done in ordinary * element order. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_impl._M_start); } /** * Returns a read-only (constant) iterator that points one past * the last element in the %vector. Iteration is done in * ordinary element order. */ const_iterator cend() const noexcept { return const_iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %vector. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %vector. Iteration * is done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // [23.2.4.2] capacity /** Returns the number of elements in the %vector. */ size_type size() const _GLIBCXX_NOEXCEPT { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); } /** Returns the size() of the largest possible %vector. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief Resizes the %vector to the specified number of elements. * @param __new_size Number of elements the %vector should contain. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * default constructed elements are appended. */ void resize(size_type __new_size) { if (__new_size > size()) _M_default_append(__new_size - size()); else if (__new_size < size()) _M_erase_at_end(this->_M_impl._M_start + __new_size); } /** * @brief Resizes the %vector to the specified number of elements. * @param __new_size Number of elements the %vector should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are populated with * given data. */ void resize(size_type __new_size, const value_type& __x) { if (__new_size > size()) _M_fill_insert(end(), __new_size - size(), __x); else if (__new_size < size()) _M_erase_at_end(this->_M_impl._M_start + __new_size); } #else /** * @brief Resizes the %vector to the specified number of elements. * @param __new_size Number of elements the %vector should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %vector to the specified * number of elements. If the number is smaller than the * %vector's current size the %vector is truncated, otherwise * the %vector is extended and new elements are populated with * given data. */ void resize(size_type __new_size, value_type __x = value_type()) { if (__new_size > size()) _M_fill_insert(end(), __new_size - size(), __x); else if (__new_size < size()) _M_erase_at_end(this->_M_impl._M_start + __new_size); } #endif #if __cplusplus >= 201103L /** A non-binding request to reduce capacity() to size(). */ void shrink_to_fit() { _M_shrink_to_fit(); } #endif /** * Returns the total number of elements that the %vector can * hold before needing to allocate more memory. */ size_type capacity() const _GLIBCXX_NOEXCEPT { return size_type(this->_M_impl._M_end_of_storage - this->_M_impl._M_start); } /** * Returns true if the %vector is empty. (Thus begin() would * equal end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return begin() == end(); } /** * @brief Attempt to preallocate enough memory for specified number of * elements. * @param __n Number of elements required. * @throw std::length_error If @a n exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %vector to hold the specified number of elements. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the number of elements * that will be required, the user can reserve the memory in * %advance, and thus prevent a possible reallocation of memory * and copying of %vector data. */ void reserve(size_type __n); // element access /** * @brief Subscript access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return *(this->_M_impl._M_start + __n); } /** * @brief Subscript access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return *(this->_M_impl._M_start + __n); } protected: /// Safety check used only from at(). void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("vector::_M_range_check: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); } public: /** * @brief Provides access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } /** * @brief Provides access to the data contained in the %vector. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the vector. The * function throws out_of_range if the check fails. */ const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } /** * Returns a read/write reference to the data at the first * element of the %vector. */ reference front() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %vector. */ const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read/write reference to the data at the last * element of the %vector. */ reference back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *(end() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %vector. */ const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *(end() - 1); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. // data access /** * Returns a pointer such that [data(), data() + size()) is a valid * range. For a non-empty %vector, data() == &front(). */ _Tp* data() _GLIBCXX_NOEXCEPT { return _M_data_ptr(this->_M_impl._M_start); } const _Tp* data() const _GLIBCXX_NOEXCEPT { return _M_data_ptr(this->_M_impl._M_start); } // [23.2.4.3] modifiers /** * @brief Add data to the end of the %vector. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %vector and assigns the given data * to it. Due to the nature of a %vector this operation can be * done in constant time if the %vector has preallocated space * available. */ void push_back(const value_type& __x) { if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage) { _GLIBCXX_ASAN_ANNOTATE_GROW(1); _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish, __x); ++this->_M_impl._M_finish; _GLIBCXX_ASAN_ANNOTATE_GREW(1); } else _M_realloc_insert(end(), __x); } #if __cplusplus >= 201103L void push_back(value_type&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args); #endif /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %vector by one. * * Note that no data is returned, and if the last element's * data is needed, it should be retrieved before pop_back() is * called. */ void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); --this->_M_impl._M_finish; _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_finish); _GLIBCXX_ASAN_ANNOTATE_SHRINK(1); } #if __cplusplus >= 201103L /** * @brief Inserts an object in %vector before specified iterator. * @param __position A const_iterator into the %vector. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) before the specified location. * Note that this kind of operation could be expensive for a %vector * and if it is frequently used the user should consider using * std::list. */ template iterator emplace(const_iterator __position, _Args&&... __args) { return _M_emplace_aux(__position, std::forward<_Args>(__args)...); } /** * @brief Inserts given value into %vector before specified iterator. * @param __position A const_iterator into the %vector. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(const_iterator __position, const value_type& __x); #else /** * @brief Inserts given value into %vector before specified iterator. * @param __position An iterator into the %vector. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(iterator __position, const value_type& __x); #endif #if __cplusplus >= 201103L /** * @brief Inserts given rvalue into %vector before specified iterator. * @param __position A const_iterator into the %vector. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given rvalue before * the specified location. Note that this kind of operation * could be expensive for a %vector and if it is frequently * used the user should consider using std::list. */ iterator insert(const_iterator __position, value_type&& __x) { return _M_insert_rval(__position, std::move(__x)); } /** * @brief Inserts an initializer_list into the %vector. * @param __position An iterator into the %vector. * @param __l An initializer_list. * * This function will insert copies of the data in the * initializer_list @a l into the %vector before the location * specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ iterator insert(const_iterator __position, initializer_list __l) { auto __offset = __position - cbegin(); _M_range_insert(begin() + __offset, __l.begin(), __l.end(), std::random_access_iterator_tag()); return begin() + __offset; } #endif #if __cplusplus >= 201103L /** * @brief Inserts a number of copies of given data into the %vector. * @param __position A const_iterator into the %vector. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a specified number of copies of * the given data before the location specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ iterator insert(const_iterator __position, size_type __n, const value_type& __x) { difference_type __offset = __position - cbegin(); _M_fill_insert(begin() + __offset, __n, __x); return begin() + __offset; } #else /** * @brief Inserts a number of copies of given data into the %vector. * @param __position An iterator into the %vector. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * * This function will insert a specified number of copies of * the given data before the location specified by @a position. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ void insert(iterator __position, size_type __n, const value_type& __x) { _M_fill_insert(__position, __n, __x); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a range into the %vector. * @param __position A const_iterator into the %vector. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator that points to the inserted data. * * This function will insert copies of the data in the range * [__first,__last) into the %vector before the location specified * by @a pos. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { difference_type __offset = __position - cbegin(); _M_insert_dispatch(begin() + __offset, __first, __last, __false_type()); return begin() + __offset; } #else /** * @brief Inserts a range into the %vector. * @param __position An iterator into the %vector. * @param __first An input iterator. * @param __last An input iterator. * * This function will insert copies of the data in the range * [__first,__last) into the %vector before the location specified * by @a pos. * * Note that this kind of operation could be expensive for a * %vector and if it is frequently used the user should * consider using std::list. */ template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } #endif /** * @brief Remove element at given position. * @param __position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %vector by one. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the element, and that if the element is itself a pointer, * the pointed-to memory is not touched in any way. Managing * the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __position) { return _M_erase(begin() + (__position - cbegin())); } #else erase(iterator __position) { return _M_erase(__position); } #endif /** * @brief Remove a range of elements. * @param __first Iterator pointing to the first element to be erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a __last * prior to erasing (or end()). * * This function will erase the elements in the range * [__first,__last) and shorten the %vector accordingly. * * Note This operation could be expensive and if it is * frequently used the user should consider using std::list. * The user is also cautioned that this function only erases * the elements, and that if the elements themselves are * pointers, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) { const auto __beg = begin(); const auto __cbeg = cbegin(); return _M_erase(__beg + (__first - __cbeg), __beg + (__last - __cbeg)); } #else erase(iterator __first, iterator __last) { return _M_erase(__first, __last); } #endif /** * @brief Swaps data with another %vector. * @param __x A %vector of the same element and allocator types. * * This exchanges the elements between two vectors in constant time. * (Three pointers, so it should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(v1,v2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(vector& __x) _GLIBCXX_NOEXCEPT { #if __cplusplus >= 201103L __glibcxx_assert(_Alloc_traits::propagate_on_container_swap::value || _M_get_Tp_allocator() == __x._M_get_Tp_allocator()); #endif this->_M_impl._M_swap_data(__x._M_impl); _Alloc_traits::_S_on_swap(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } /** * Erases all the elements. Note that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_erase_at_end(this->_M_impl._M_start); } protected: /** * Memory expansion handler. Uses the member allocation function to * obtain @a n bytes of memory, and then copies [first,last) into it. */ template pointer _M_allocate_and_copy(size_type __n, _ForwardIterator __first, _ForwardIterator __last) { pointer __result = this->_M_allocate(__n); __try { std::__uninitialized_copy_a(__first, __last, __result, _M_get_Tp_allocator()); return __result; } __catch(...) { _M_deallocate(__result, __n); __throw_exception_again; } } // Internal constructor functions follow. // Called by the range constructor to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __value, __true_type) { this->_M_impl._M_start = _M_allocate(static_cast(__n)); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + static_cast(__n); _M_fill_initialize(static_cast(__n), __value); } // Called by the range constructor to implement [23.1.1]/9 template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { typedef typename std::iterator_traits<_InputIterator>:: iterator_category _IterCategory; _M_range_initialize(__first, __last, _IterCategory()); } // Called by the second initialize_dispatch above template void _M_range_initialize(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { __try { for (; __first != __last; ++__first) #if __cplusplus >= 201103L emplace_back(*__first); #else push_back(*__first); #endif } __catch(...) { clear(); __throw_exception_again; } } // Called by the second initialize_dispatch above template void _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); this->_M_impl._M_start = this->_M_allocate(__n); this->_M_impl._M_end_of_storage = this->_M_impl._M_start + __n; this->_M_impl._M_finish = std::__uninitialized_copy_a(__first, __last, this->_M_impl._M_start, _M_get_Tp_allocator()); } // Called by the first initialize_dispatch above and by the // vector(n,value,a) constructor. void _M_fill_initialize(size_type __n, const value_type& __value) { this->_M_impl._M_finish = std::__uninitialized_fill_n_a(this->_M_impl._M_start, __n, __value, _M_get_Tp_allocator()); } #if __cplusplus >= 201103L // Called by the vector(n) constructor. void _M_default_initialize(size_type __n) { this->_M_impl._M_finish = std::__uninitialized_default_n_a(this->_M_impl._M_start, __n, _M_get_Tp_allocator()); } #endif // Internal assign functions follow. The *_aux functions do the actual // assignment work for the range versions. // Called by the range assign to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } // Called by the range assign to implement [23.1.1]/9 template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } // Called by the second assign_dispatch above template void _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag); // Called by the second assign_dispatch above template void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val); // Internal insert functions follow. // Called by the range insert to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __val, __true_type) { _M_fill_insert(__pos, __n, __val); } // Called by the range insert to implement [23.1.1]/9 template void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_range_insert(__pos, __first, __last, std::__iterator_category(__first)); } // Called by the second insert_dispatch above template void _M_range_insert(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag); // Called by the second insert_dispatch above template void _M_range_insert(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); // Called by insert(p,n,x), and the range insert when it turns out to be // the same thing. void _M_fill_insert(iterator __pos, size_type __n, const value_type& __x); #if __cplusplus >= 201103L // Called by resize(n). void _M_default_append(size_type __n); bool _M_shrink_to_fit(); #endif #if __cplusplus < 201103L // Called by insert(p,x) void _M_insert_aux(iterator __position, const value_type& __x); void _M_realloc_insert(iterator __position, const value_type& __x); #else // A value_type object constructed with _Alloc_traits::construct() // and destroyed with _Alloc_traits::destroy(). struct _Temporary_value { template explicit _Temporary_value(vector* __vec, _Args&&... __args) : _M_this(__vec) { _Alloc_traits::construct(_M_this->_M_impl, _M_ptr(), std::forward<_Args>(__args)...); } ~_Temporary_value() { _Alloc_traits::destroy(_M_this->_M_impl, _M_ptr()); } value_type& _M_val() { return *_M_ptr(); } private: _Tp* _M_ptr() { return reinterpret_cast<_Tp*>(&__buf); } vector* _M_this; typename aligned_storage::type __buf; }; // Called by insert(p,x) and other functions when insertion needs to // reallocate or move existing elements. _Arg is either _Tp& or _Tp. template void _M_insert_aux(iterator __position, _Arg&& __arg); template void _M_realloc_insert(iterator __position, _Args&&... __args); // Either move-construct at the end, or forward to _M_insert_aux. iterator _M_insert_rval(const_iterator __position, value_type&& __v); // Try to emplace at the end, otherwise forward to _M_insert_aux. template iterator _M_emplace_aux(const_iterator __position, _Args&&... __args); // Emplacing an rvalue of the correct type can use _M_insert_rval. iterator _M_emplace_aux(const_iterator __position, value_type&& __v) { return _M_insert_rval(__position, std::move(__v)); } #endif // Called by _M_fill_insert, _M_insert_aux etc. size_type _M_check_len(size_type __n, const char* __s) const { if (max_size() - size() < __n) __throw_length_error(__N(__s)); const size_type __len = size() + std::max(size(), __n); return (__len < size() || __len > max_size()) ? max_size() : __len; } // Internal erase functions follow. // Called by erase(q1,q2), clear(), resize(), _M_fill_assign, // _M_assign_aux. void _M_erase_at_end(pointer __pos) _GLIBCXX_NOEXCEPT { if (size_type __n = this->_M_impl._M_finish - __pos) { std::_Destroy(__pos, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __pos; _GLIBCXX_ASAN_ANNOTATE_SHRINK(__n); } } iterator _M_erase(iterator __position); iterator _M_erase(iterator __first, iterator __last); #if __cplusplus >= 201103L private: // Constant-time move assignment when source object's memory can be // moved, either because the source's allocator will move too // or because the allocators are equal. void _M_move_assign(vector&& __x, std::true_type) noexcept { vector __tmp(get_allocator()); this->_M_impl._M_swap_data(__tmp._M_impl); this->_M_impl._M_swap_data(__x._M_impl); std::__alloc_on_move(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } // Do move assignment when it might not be possible to move source // object's memory, resulting in a linear-time operation. void _M_move_assign(vector&& __x, std::false_type) { if (__x._M_get_Tp_allocator() == this->_M_get_Tp_allocator()) _M_move_assign(std::move(__x), std::true_type()); else { // The rvalue's allocator cannot be moved and is not equal, // so we need to individually move each element. this->assign(std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end())); __x.clear(); } } #endif template _Up* _M_data_ptr(_Up* __ptr) const _GLIBCXX_NOEXCEPT { return __ptr; } #if __cplusplus >= 201103L template typename std::pointer_traits<_Ptr>::element_type* _M_data_ptr(_Ptr __ptr) const { return empty() ? nullptr : std::__to_address(__ptr); } #else template _Up* _M_data_ptr(_Up* __ptr) _GLIBCXX_NOEXCEPT { return __ptr; } template value_type* _M_data_ptr(_Ptr __ptr) { return empty() ? (value_type*)0 : __ptr.operator->(); } template const value_type* _M_data_ptr(_Ptr __ptr) const { return empty() ? (const value_type*)0 : __ptr.operator->(); } #endif }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> vector(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> vector<_ValT, _Allocator>; #endif /** * @brief Vector equality comparison. * @param __x A %vector. * @param __y A %vector of the same type as @a __x. * @return True iff the size and elements of the vectors are equal. * * This is an equivalence relation. It is linear in the size of the * vectors. Vectors are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return (__x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin())); } /** * @brief Vector ordering relation. * @param __x A %vector. * @param __y A %vector of the same type as @a __x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * vectors. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template inline bool operator!=(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const vector<_Tp, _Alloc>& __x, const vector<_Tp, _Alloc>& __y) { return !(__x < __y); } /// See std::vector::swap(). template inline void swap(vector<_Tp, _Alloc>& __x, vector<_Tp, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_VECTOR_H */ c++/8/bits/stl_iterator.h000064400000122463151027430570011124 0ustar00// Iterators -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_iterator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} * * This file implements reverse_iterator, back_insert_iterator, * front_insert_iterator, insert_iterator, __normal_iterator, and their * supporting functions and overloaded operators. */ #ifndef _STL_ITERATOR_H #define _STL_ITERATOR_H 1 #include #include #include #include #if __cplusplus > 201402L # define __cpp_lib_array_constexpr 201603 #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup iterators * @{ */ // 24.4.1 Reverse iterators /** * Bidirectional and random access iterators have corresponding reverse * %iterator adaptors that iterate through the data structure in the * opposite direction. They have the same signatures as the corresponding * iterators. The fundamental relation between a reverse %iterator and its * corresponding %iterator @c i is established by the identity: * @code * &*(reverse_iterator(i)) == &*(i - 1) * @endcode * * This mapping is dictated by the fact that while there is always a * pointer past the end of an array, there might not be a valid pointer * before the beginning of an array. [24.4.1]/1,2 * * Reverse iterators can be tricky and surprising at first. Their * semantics make sense, however, and the trickiness is a side effect of * the requirement that the iterators must be safe. */ template class reverse_iterator : public iterator::iterator_category, typename iterator_traits<_Iterator>::value_type, typename iterator_traits<_Iterator>::difference_type, typename iterator_traits<_Iterator>::pointer, typename iterator_traits<_Iterator>::reference> { protected: _Iterator current; typedef iterator_traits<_Iterator> __traits_type; public: typedef _Iterator iterator_type; typedef typename __traits_type::difference_type difference_type; typedef typename __traits_type::pointer pointer; typedef typename __traits_type::reference reference; /** * The default constructor value-initializes member @p current. * If it is a pointer, that means it is zero-initialized. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 235 No specification of default ctor for reverse_iterator // 1012. reverse_iterator default ctor should value initialize _GLIBCXX17_CONSTEXPR reverse_iterator() : current() { } /** * This %iterator will move in the opposite direction that @p x does. */ explicit _GLIBCXX17_CONSTEXPR reverse_iterator(iterator_type __x) : current(__x) { } /** * The copy constructor is normal. */ _GLIBCXX17_CONSTEXPR reverse_iterator(const reverse_iterator& __x) : current(__x.current) { } /** * A %reverse_iterator across other types can be copied if the * underlying %iterator can be converted to the type of @c current. */ template _GLIBCXX17_CONSTEXPR reverse_iterator(const reverse_iterator<_Iter>& __x) : current(__x.base()) { } /** * @return @c current, the %iterator used for underlying work. */ _GLIBCXX17_CONSTEXPR iterator_type base() const { return current; } /** * @return A reference to the value at @c --current * * This requires that @c --current is dereferenceable. * * @warning This implementation requires that for an iterator of the * underlying iterator type, @c x, a reference obtained by * @c *x remains valid after @c x has been modified or * destroyed. This is a bug: http://gcc.gnu.org/PR51823 */ _GLIBCXX17_CONSTEXPR reference operator*() const { _Iterator __tmp = current; return *--__tmp; } /** * @return A pointer to the value at @c --current * * This requires that @c --current is dereferenceable. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2188. Reverse iterator does not fully support targets that overload & _GLIBCXX17_CONSTEXPR pointer operator->() const { return std::__addressof(operator*()); } /** * @return @c *this * * Decrements the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator++() { --current; return *this; } /** * @return The original value of @c *this * * Decrements the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator++(int) { reverse_iterator __tmp = *this; --current; return __tmp; } /** * @return @c *this * * Increments the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator--() { ++current; return *this; } /** * @return A reverse_iterator with the previous value of @c *this * * Increments the underlying iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator--(int) { reverse_iterator __tmp = *this; ++current; return __tmp; } /** * @return A reverse_iterator that refers to @c current - @a __n * * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator+(difference_type __n) const { return reverse_iterator(current - __n); } /** * @return *this * * Moves the underlying iterator backwards @a __n steps. * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator+=(difference_type __n) { current -= __n; return *this; } /** * @return A reverse_iterator that refers to @c current - @a __n * * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator operator-(difference_type __n) const { return reverse_iterator(current + __n); } /** * @return *this * * Moves the underlying iterator forwards @a __n steps. * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reverse_iterator& operator-=(difference_type __n) { current += __n; return *this; } /** * @return The value at @c current - @a __n - 1 * * The underlying iterator must be a Random Access Iterator. */ _GLIBCXX17_CONSTEXPR reference operator[](difference_type __n) const { return *(*this + __n); } }; //@{ /** * @param __x A %reverse_iterator. * @param __y A %reverse_iterator. * @return A simple bool. * * Reverse iterators forward many operations to their underlying base() * iterators. Others are implemented in terms of one another. * */ template inline _GLIBCXX17_CONSTEXPR bool operator==(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __y.base() < __x.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator>(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return !(__x < __y); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 280. Comparison of reverse_iterator to const reverse_iterator. template inline _GLIBCXX17_CONSTEXPR bool operator==(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __y.base() < __x.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator>(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return !(__x < __y); } //@} #if __cplusplus < 201103L template inline typename reverse_iterator<_Iterator>::difference_type operator-(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) { return __y.base() - __x.base(); } template inline typename reverse_iterator<_IteratorL>::difference_type operator-(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) { return __y.base() - __x.base(); } #else // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 685. reverse_iterator/move_iterator difference has invalid signatures template inline _GLIBCXX17_CONSTEXPR auto operator-(const reverse_iterator<_IteratorL>& __x, const reverse_iterator<_IteratorR>& __y) -> decltype(__y.base() - __x.base()) { return __y.base() - __x.base(); } #endif template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator> operator+(typename reverse_iterator<_Iterator>::difference_type __n, const reverse_iterator<_Iterator>& __x) { return reverse_iterator<_Iterator>(__x.base() - __n); } #if __cplusplus >= 201103L // Same as C++14 make_reverse_iterator but used in C++03 mode too. template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator> __make_reverse_iterator(_Iterator __i) { return reverse_iterator<_Iterator>(__i); } # if __cplusplus > 201103L # define __cpp_lib_make_reverse_iterator 201402 // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 2285. make_reverse_iterator /// Generator function for reverse_iterator. template inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator> make_reverse_iterator(_Iterator __i) { return reverse_iterator<_Iterator>(__i); } # endif #endif #if __cplusplus >= 201103L template auto __niter_base(reverse_iterator<_Iterator> __it) -> decltype(__make_reverse_iterator(__niter_base(__it.base()))) { return __make_reverse_iterator(__niter_base(__it.base())); } template struct __is_move_iterator > : __is_move_iterator<_Iterator> { }; template auto __miter_base(reverse_iterator<_Iterator> __it) -> decltype(__make_reverse_iterator(__miter_base(__it.base()))) { return __make_reverse_iterator(__miter_base(__it.base())); } #endif // 24.4.2.2.1 back_insert_iterator /** * @brief Turns assignment into insertion. * * These are output iterators, constructed from a container-of-T. * Assigning a T to the iterator appends it to the container using * push_back. * * Tip: Using the back_inserter function to create these iterators can * save typing. */ template class back_insert_iterator : public iterator { protected: _Container* container; public: /// A nested typedef for the type of whatever container you used. typedef _Container container_type; /// The only way to create this %iterator is with a container. explicit back_insert_iterator(_Container& __x) : container(std::__addressof(__x)) { } /** * @param __value An instance of whatever type * container_type::const_reference is; presumably a * reference-to-const T for container. * @return This %iterator, for chained operations. * * This kind of %iterator doesn't really have a @a position in the * container (you can think of the position as being permanently at * the end, if you like). Assigning a value to the %iterator will * always append the value to the end of the container. */ #if __cplusplus < 201103L back_insert_iterator& operator=(typename _Container::const_reference __value) { container->push_back(__value); return *this; } #else back_insert_iterator& operator=(const typename _Container::value_type& __value) { container->push_back(__value); return *this; } back_insert_iterator& operator=(typename _Container::value_type&& __value) { container->push_back(std::move(__value)); return *this; } #endif /// Simply returns *this. back_insert_iterator& operator*() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) back_insert_iterator& operator++() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) back_insert_iterator operator++(int) { return *this; } }; /** * @param __x A container of arbitrary type. * @return An instance of back_insert_iterator working on @p __x. * * This wrapper function helps in creating back_insert_iterator instances. * Typing the name of the %iterator requires knowing the precise full * type of the container, which can be tedious and impedes generic * programming. Using this function lets you take advantage of automatic * template parameter deduction, making the compiler match the correct * types for you. */ template inline back_insert_iterator<_Container> back_inserter(_Container& __x) { return back_insert_iterator<_Container>(__x); } /** * @brief Turns assignment into insertion. * * These are output iterators, constructed from a container-of-T. * Assigning a T to the iterator prepends it to the container using * push_front. * * Tip: Using the front_inserter function to create these iterators can * save typing. */ template class front_insert_iterator : public iterator { protected: _Container* container; public: /// A nested typedef for the type of whatever container you used. typedef _Container container_type; /// The only way to create this %iterator is with a container. explicit front_insert_iterator(_Container& __x) : container(std::__addressof(__x)) { } /** * @param __value An instance of whatever type * container_type::const_reference is; presumably a * reference-to-const T for container. * @return This %iterator, for chained operations. * * This kind of %iterator doesn't really have a @a position in the * container (you can think of the position as being permanently at * the front, if you like). Assigning a value to the %iterator will * always prepend the value to the front of the container. */ #if __cplusplus < 201103L front_insert_iterator& operator=(typename _Container::const_reference __value) { container->push_front(__value); return *this; } #else front_insert_iterator& operator=(const typename _Container::value_type& __value) { container->push_front(__value); return *this; } front_insert_iterator& operator=(typename _Container::value_type&& __value) { container->push_front(std::move(__value)); return *this; } #endif /// Simply returns *this. front_insert_iterator& operator*() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) front_insert_iterator& operator++() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) front_insert_iterator operator++(int) { return *this; } }; /** * @param __x A container of arbitrary type. * @return An instance of front_insert_iterator working on @p x. * * This wrapper function helps in creating front_insert_iterator instances. * Typing the name of the %iterator requires knowing the precise full * type of the container, which can be tedious and impedes generic * programming. Using this function lets you take advantage of automatic * template parameter deduction, making the compiler match the correct * types for you. */ template inline front_insert_iterator<_Container> front_inserter(_Container& __x) { return front_insert_iterator<_Container>(__x); } /** * @brief Turns assignment into insertion. * * These are output iterators, constructed from a container-of-T. * Assigning a T to the iterator inserts it in the container at the * %iterator's position, rather than overwriting the value at that * position. * * (Sequences will actually insert a @e copy of the value before the * %iterator's position.) * * Tip: Using the inserter function to create these iterators can * save typing. */ template class insert_iterator : public iterator { protected: _Container* container; typename _Container::iterator iter; public: /// A nested typedef for the type of whatever container you used. typedef _Container container_type; /** * The only way to create this %iterator is with a container and an * initial position (a normal %iterator into the container). */ insert_iterator(_Container& __x, typename _Container::iterator __i) : container(std::__addressof(__x)), iter(__i) {} /** * @param __value An instance of whatever type * container_type::const_reference is; presumably a * reference-to-const T for container. * @return This %iterator, for chained operations. * * This kind of %iterator maintains its own position in the * container. Assigning a value to the %iterator will insert the * value into the container at the place before the %iterator. * * The position is maintained such that subsequent assignments will * insert values immediately after one another. For example, * @code * // vector v contains A and Z * * insert_iterator i (v, ++v.begin()); * i = 1; * i = 2; * i = 3; * * // vector v contains A, 1, 2, 3, and Z * @endcode */ #if __cplusplus < 201103L insert_iterator& operator=(typename _Container::const_reference __value) { iter = container->insert(iter, __value); ++iter; return *this; } #else insert_iterator& operator=(const typename _Container::value_type& __value) { iter = container->insert(iter, __value); ++iter; return *this; } insert_iterator& operator=(typename _Container::value_type&& __value) { iter = container->insert(iter, std::move(__value)); ++iter; return *this; } #endif /// Simply returns *this. insert_iterator& operator*() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) insert_iterator& operator++() { return *this; } /// Simply returns *this. (This %iterator does not @a move.) insert_iterator& operator++(int) { return *this; } }; /** * @param __x A container of arbitrary type. * @param __i An iterator into the container. * @return An instance of insert_iterator working on @p __x. * * This wrapper function helps in creating insert_iterator instances. * Typing the name of the %iterator requires knowing the precise full * type of the container, which can be tedious and impedes generic * programming. Using this function lets you take advantage of automatic * template parameter deduction, making the compiler match the correct * types for you. */ template inline insert_iterator<_Container> inserter(_Container& __x, _Iterator __i) { return insert_iterator<_Container>(__x, typename _Container::iterator(__i)); } // @} group iterators _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // This iterator adapter is @a normal in the sense that it does not // change the semantics of any of the operators of its iterator // parameter. Its primary purpose is to convert an iterator that is // not a class, e.g. a pointer, into an iterator that is a class. // The _Container parameter exists solely so that different containers // using this template can instantiate different types, even if the // _Iterator parameter is the same. using std::iterator_traits; using std::iterator; template class __normal_iterator { protected: _Iterator _M_current; typedef iterator_traits<_Iterator> __traits_type; public: typedef _Iterator iterator_type; typedef typename __traits_type::iterator_category iterator_category; typedef typename __traits_type::value_type value_type; typedef typename __traits_type::difference_type difference_type; typedef typename __traits_type::reference reference; typedef typename __traits_type::pointer pointer; _GLIBCXX_CONSTEXPR __normal_iterator() _GLIBCXX_NOEXCEPT : _M_current(_Iterator()) { } explicit __normal_iterator(const _Iterator& __i) _GLIBCXX_NOEXCEPT : _M_current(__i) { } // Allow iterator to const_iterator conversion template __normal_iterator(const __normal_iterator<_Iter, typename __enable_if< (std::__are_same<_Iter, typename _Container::pointer>::__value), _Container>::__type>& __i) _GLIBCXX_NOEXCEPT : _M_current(__i.base()) { } // Forward iterator requirements reference operator*() const _GLIBCXX_NOEXCEPT { return *_M_current; } pointer operator->() const _GLIBCXX_NOEXCEPT { return _M_current; } __normal_iterator& operator++() _GLIBCXX_NOEXCEPT { ++_M_current; return *this; } __normal_iterator operator++(int) _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current++); } // Bidirectional iterator requirements __normal_iterator& operator--() _GLIBCXX_NOEXCEPT { --_M_current; return *this; } __normal_iterator operator--(int) _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current--); } // Random access iterator requirements reference operator[](difference_type __n) const _GLIBCXX_NOEXCEPT { return _M_current[__n]; } __normal_iterator& operator+=(difference_type __n) _GLIBCXX_NOEXCEPT { _M_current += __n; return *this; } __normal_iterator operator+(difference_type __n) const _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current + __n); } __normal_iterator& operator-=(difference_type __n) _GLIBCXX_NOEXCEPT { _M_current -= __n; return *this; } __normal_iterator operator-(difference_type __n) const _GLIBCXX_NOEXCEPT { return __normal_iterator(_M_current - __n); } const _Iterator& base() const _GLIBCXX_NOEXCEPT { return _M_current; } }; // Note: In what follows, the left- and right-hand-side iterators are // allowed to vary in types (conceptually in cv-qualification) so that // comparison between cv-qualified and non-cv-qualified iterators be // valid. However, the greedy and unfriendly operators in std::rel_ops // will make overload resolution ambiguous (when in scope) if we don't // provide overloads whose operands are of the same type. Can someone // remind me what generic programming is about? -- Gaby // Forward iterator requirements template inline bool operator==(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() == __rhs.base(); } template inline bool operator==(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() == __rhs.base(); } template inline bool operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() != __rhs.base(); } template inline bool operator!=(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() != __rhs.base(); } // Random access iterator requirements template inline bool operator<(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() < __rhs.base(); } template inline bool operator<(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() < __rhs.base(); } template inline bool operator>(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() > __rhs.base(); } template inline bool operator>(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() > __rhs.base(); } template inline bool operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() <= __rhs.base(); } template inline bool operator<=(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() <= __rhs.base(); } template inline bool operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() >= __rhs.base(); } template inline bool operator>=(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() >= __rhs.base(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR179 not only the various comparison // operators but also operator- must accept mixed iterator/const_iterator // parameters. template #if __cplusplus >= 201103L // DR 685. inline auto operator-(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) noexcept -> decltype(__lhs.base() - __rhs.base()) #else inline typename __normal_iterator<_IteratorL, _Container>::difference_type operator-(const __normal_iterator<_IteratorL, _Container>& __lhs, const __normal_iterator<_IteratorR, _Container>& __rhs) #endif { return __lhs.base() - __rhs.base(); } template inline typename __normal_iterator<_Iterator, _Container>::difference_type operator-(const __normal_iterator<_Iterator, _Container>& __lhs, const __normal_iterator<_Iterator, _Container>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.base() - __rhs.base(); } template inline __normal_iterator<_Iterator, _Container> operator+(typename __normal_iterator<_Iterator, _Container>::difference_type __n, const __normal_iterator<_Iterator, _Container>& __i) _GLIBCXX_NOEXCEPT { return __normal_iterator<_Iterator, _Container>(__i.base() + __n); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template _Iterator __niter_base(__gnu_cxx::__normal_iterator<_Iterator, _Container> __it) { return __it.base(); } #if __cplusplus >= 201103L /** * @addtogroup iterators * @{ */ // 24.4.3 Move iterators /** * Class template move_iterator is an iterator adapter with the same * behavior as the underlying iterator except that its dereference * operator implicitly converts the value returned by the underlying * iterator's dereference operator to an rvalue reference. Some * generic algorithms can be called with move iterators to replace * copying with moving. */ template class move_iterator { protected: _Iterator _M_current; typedef iterator_traits<_Iterator> __traits_type; typedef typename __traits_type::reference __base_ref; public: typedef _Iterator iterator_type; typedef typename __traits_type::iterator_category iterator_category; typedef typename __traits_type::value_type value_type; typedef typename __traits_type::difference_type difference_type; // NB: DR 680. typedef _Iterator pointer; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2106. move_iterator wrapping iterators returning prvalues typedef typename conditional::value, typename remove_reference<__base_ref>::type&&, __base_ref>::type reference; _GLIBCXX17_CONSTEXPR move_iterator() : _M_current() { } explicit _GLIBCXX17_CONSTEXPR move_iterator(iterator_type __i) : _M_current(__i) { } template _GLIBCXX17_CONSTEXPR move_iterator(const move_iterator<_Iter>& __i) : _M_current(__i.base()) { } _GLIBCXX17_CONSTEXPR iterator_type base() const { return _M_current; } _GLIBCXX17_CONSTEXPR reference operator*() const { return static_cast(*_M_current); } _GLIBCXX17_CONSTEXPR pointer operator->() const { return _M_current; } _GLIBCXX17_CONSTEXPR move_iterator& operator++() { ++_M_current; return *this; } _GLIBCXX17_CONSTEXPR move_iterator operator++(int) { move_iterator __tmp = *this; ++_M_current; return __tmp; } _GLIBCXX17_CONSTEXPR move_iterator& operator--() { --_M_current; return *this; } _GLIBCXX17_CONSTEXPR move_iterator operator--(int) { move_iterator __tmp = *this; --_M_current; return __tmp; } _GLIBCXX17_CONSTEXPR move_iterator operator+(difference_type __n) const { return move_iterator(_M_current + __n); } _GLIBCXX17_CONSTEXPR move_iterator& operator+=(difference_type __n) { _M_current += __n; return *this; } _GLIBCXX17_CONSTEXPR move_iterator operator-(difference_type __n) const { return move_iterator(_M_current - __n); } _GLIBCXX17_CONSTEXPR move_iterator& operator-=(difference_type __n) { _M_current -= __n; return *this; } _GLIBCXX17_CONSTEXPR reference operator[](difference_type __n) const { return std::move(_M_current[__n]); } }; // Note: See __normal_iterator operators note from Gaby to understand // why there are always 2 versions for most of the move_iterator // operators. template inline _GLIBCXX17_CONSTEXPR bool operator==(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator==(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return __x.base() == __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator!=(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return !(__x == __y); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return __x.base() < __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return __x.base() < __y.base(); } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator<=(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return !(__y < __x); } template inline _GLIBCXX17_CONSTEXPR bool operator>(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator>(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return __y < __x; } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) { return !(__x < __y); } template inline _GLIBCXX17_CONSTEXPR bool operator>=(const move_iterator<_Iterator>& __x, const move_iterator<_Iterator>& __y) { return !(__x < __y); } // DR 685. template inline _GLIBCXX17_CONSTEXPR auto operator-(const move_iterator<_IteratorL>& __x, const move_iterator<_IteratorR>& __y) -> decltype(__x.base() - __y.base()) { return __x.base() - __y.base(); } template inline _GLIBCXX17_CONSTEXPR move_iterator<_Iterator> operator+(typename move_iterator<_Iterator>::difference_type __n, const move_iterator<_Iterator>& __x) { return __x + __n; } template inline _GLIBCXX17_CONSTEXPR move_iterator<_Iterator> make_move_iterator(_Iterator __i) { return move_iterator<_Iterator>(__i); } template::value_type>::value, _Iterator, move_iterator<_Iterator>>::type> inline _GLIBCXX17_CONSTEXPR _ReturnType __make_move_if_noexcept_iterator(_Iterator __i) { return _ReturnType(__i); } // Overload for pointers that matches std::move_if_noexcept more closely, // returning a constant iterator when we don't want to move. template::value, const _Tp*, move_iterator<_Tp*>>::type> inline _GLIBCXX17_CONSTEXPR _ReturnType __make_move_if_noexcept_iterator(_Tp* __i) { return _ReturnType(__i); } // @} group iterators template auto __niter_base(move_iterator<_Iterator> __it) -> decltype(make_move_iterator(__niter_base(__it.base()))) { return make_move_iterator(__niter_base(__it.base())); } template struct __is_move_iterator > { enum { __value = 1 }; typedef __true_type __type; }; template auto __miter_base(move_iterator<_Iterator> __it) -> decltype(__miter_base(__it.base())) { return __miter_base(__it.base()); } #define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter) std::make_move_iterator(_Iter) #define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter) \ std::__make_move_if_noexcept_iterator(_Iter) #else #define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter) (_Iter) #define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter) (_Iter) #endif // C++11 #if __cpp_deduction_guides >= 201606 // These helper traits are used for deduction guides // of associative containers. template using __iter_key_t = remove_const_t< typename iterator_traits<_InputIterator>::value_type::first_type>; template using __iter_val_t = typename iterator_traits<_InputIterator>::value_type::second_type; template struct pair; template using __iter_to_alloc_t = pair>, __iter_val_t<_InputIterator>>; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #ifdef _GLIBCXX_DEBUG # include #endif #endif c++/8/bits/locale_facets.tcc000064400000115174151027430570011520 0ustar00// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ #ifndef _LOCALE_FACETS_TCC #define _LOCALE_FACETS_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Routine to access a cache for the facet. If the cache didn't // exist before, it gets constructed on the fly. template struct __use_cache { const _Facet* operator() (const locale& __loc) const; }; // Specializations. template struct __use_cache<__numpunct_cache<_CharT> > { const __numpunct_cache<_CharT>* operator() (const locale& __loc) const { const size_t __i = numpunct<_CharT>::id._M_id(); const locale::facet** __caches = __loc._M_impl->_M_caches; if (!__caches[__i]) { __numpunct_cache<_CharT>* __tmp = 0; __try { __tmp = new __numpunct_cache<_CharT>; __tmp->_M_cache(__loc); } __catch(...) { delete __tmp; __throw_exception_again; } __loc._M_impl->_M_install_cache(__tmp, __i); } return static_cast*>(__caches[__i]); } }; template void __numpunct_cache<_CharT>::_M_cache(const locale& __loc) { const numpunct<_CharT>& __np = use_facet >(__loc); char* __grouping = 0; _CharT* __truename = 0; _CharT* __falsename = 0; __try { const string& __g = __np.grouping(); _M_grouping_size = __g.size(); __grouping = new char[_M_grouping_size]; __g.copy(__grouping, _M_grouping_size); _M_use_grouping = (_M_grouping_size && static_cast(__grouping[0]) > 0 && (__grouping[0] != __gnu_cxx::__numeric_traits::__max)); const basic_string<_CharT>& __tn = __np.truename(); _M_truename_size = __tn.size(); __truename = new _CharT[_M_truename_size]; __tn.copy(__truename, _M_truename_size); const basic_string<_CharT>& __fn = __np.falsename(); _M_falsename_size = __fn.size(); __falsename = new _CharT[_M_falsename_size]; __fn.copy(__falsename, _M_falsename_size); _M_decimal_point = __np.decimal_point(); _M_thousands_sep = __np.thousands_sep(); const ctype<_CharT>& __ct = use_facet >(__loc); __ct.widen(__num_base::_S_atoms_out, __num_base::_S_atoms_out + __num_base::_S_oend, _M_atoms_out); __ct.widen(__num_base::_S_atoms_in, __num_base::_S_atoms_in + __num_base::_S_iend, _M_atoms_in); _M_grouping = __grouping; _M_truename = __truename; _M_falsename = __falsename; _M_allocated = true; } __catch(...) { delete [] __grouping; delete [] __truename; delete [] __falsename; __throw_exception_again; } } // Used by both numeric and monetary facets. // Check to make sure that the __grouping_tmp string constructed in // money_get or num_get matches the canonical grouping for a given // locale. // __grouping_tmp is parsed L to R // 1,222,444 == __grouping_tmp of "\1\3\3" // __grouping is parsed R to L // 1,222,444 == __grouping of "\3" == "\3\3\3" _GLIBCXX_PURE bool __verify_grouping(const char* __grouping, size_t __grouping_size, const string& __grouping_tmp) throw (); _GLIBCXX_BEGIN_NAMESPACE_LDBL template _GLIBCXX_DEFAULT_ABI_TAG _InIter num_get<_CharT, _InIter>:: _M_extract_float(_InIter __beg, _InIter __end, ios_base& __io, ios_base::iostate& __err, string& __xtrc) const { typedef char_traits<_CharT> __traits_type; typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __lit = __lc->_M_atoms_in; char_type __c = char_type(); // True if __beg becomes equal to __end. bool __testeof = __beg == __end; // First check for sign. if (!__testeof) { __c = *__beg; const bool __plus = __c == __lit[__num_base::_S_iplus]; if ((__plus || __c == __lit[__num_base::_S_iminus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) { __xtrc += __plus ? '+' : '-'; if (++__beg != __end) __c = *__beg; else __testeof = true; } } // Next, look for leading zeros. bool __found_mantissa = false; int __sep_pos = 0; while (!__testeof) { if ((__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) || __c == __lc->_M_decimal_point) break; else if (__c == __lit[__num_base::_S_izero]) { if (!__found_mantissa) { __xtrc += '0'; __found_mantissa = true; } ++__sep_pos; if (++__beg != __end) __c = *__beg; else __testeof = true; } else break; } // Only need acceptable digits for floating point numbers. bool __found_dec = false; bool __found_sci = false; string __found_grouping; if (__lc->_M_use_grouping) __found_grouping.reserve(32); const char_type* __lit_zero = __lit + __num_base::_S_izero; if (!__lc->_M_allocated) // "C" locale while (!__testeof) { const int __digit = _M_find(__lit_zero, 10, __c); if (__digit != -1) { __xtrc += '0' + __digit; __found_mantissa = true; } else if (__c == __lc->_M_decimal_point && !__found_dec && !__found_sci) { __xtrc += '.'; __found_dec = true; } else if ((__c == __lit[__num_base::_S_ie] || __c == __lit[__num_base::_S_iE]) && !__found_sci && __found_mantissa) { // Scientific notation. __xtrc += 'e'; __found_sci = true; // Remove optional plus or minus sign, if they exist. if (++__beg != __end) { __c = *__beg; const bool __plus = __c == __lit[__num_base::_S_iplus]; if (__plus || __c == __lit[__num_base::_S_iminus]) __xtrc += __plus ? '+' : '-'; else continue; } else { __testeof = true; break; } } else break; if (++__beg != __end) __c = *__beg; else __testeof = true; } else while (!__testeof) { // According to 22.2.2.1.2, p8-9, first look for thousands_sep // and decimal_point. if (__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) { if (!__found_dec && !__found_sci) { // NB: Thousands separator at the beginning of a string // is a no-no, as is two consecutive thousands separators. if (__sep_pos) { __found_grouping += static_cast(__sep_pos); __sep_pos = 0; } else { // NB: __convert_to_v will not assign __v and will // set the failbit. __xtrc.clear(); break; } } else break; } else if (__c == __lc->_M_decimal_point) { if (!__found_dec && !__found_sci) { // If no grouping chars are seen, no grouping check // is applied. Therefore __found_grouping is adjusted // only if decimal_point comes after some thousands_sep. if (__found_grouping.size()) __found_grouping += static_cast(__sep_pos); __xtrc += '.'; __found_dec = true; } else break; } else { const char_type* __q = __traits_type::find(__lit_zero, 10, __c); if (__q) { __xtrc += '0' + (__q - __lit_zero); __found_mantissa = true; ++__sep_pos; } else if ((__c == __lit[__num_base::_S_ie] || __c == __lit[__num_base::_S_iE]) && !__found_sci && __found_mantissa) { // Scientific notation. if (__found_grouping.size() && !__found_dec) __found_grouping += static_cast(__sep_pos); __xtrc += 'e'; __found_sci = true; // Remove optional plus or minus sign, if they exist. if (++__beg != __end) { __c = *__beg; const bool __plus = __c == __lit[__num_base::_S_iplus]; if ((__plus || __c == __lit[__num_base::_S_iminus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) __xtrc += __plus ? '+' : '-'; else continue; } else { __testeof = true; break; } } else break; } if (++__beg != __end) __c = *__beg; else __testeof = true; } // Digit grouping is checked. If grouping and found_grouping don't // match, then get very very upset, and set failbit. if (__found_grouping.size()) { // Add the ending grouping if a decimal or 'e'/'E' wasn't found. if (!__found_dec && !__found_sci) __found_grouping += static_cast(__sep_pos); if (!std::__verify_grouping(__lc->_M_grouping, __lc->_M_grouping_size, __found_grouping)) __err = ios_base::failbit; } return __beg; } template template _GLIBCXX_DEFAULT_ABI_TAG _InIter num_get<_CharT, _InIter>:: _M_extract_int(_InIter __beg, _InIter __end, ios_base& __io, ios_base::iostate& __err, _ValueT& __v) const { typedef char_traits<_CharT> __traits_type; using __gnu_cxx::__add_unsigned; typedef typename __add_unsigned<_ValueT>::__type __unsigned_type; typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __lit = __lc->_M_atoms_in; char_type __c = char_type(); // NB: Iff __basefield == 0, __base can change based on contents. const ios_base::fmtflags __basefield = __io.flags() & ios_base::basefield; const bool __oct = __basefield == ios_base::oct; int __base = __oct ? 8 : (__basefield == ios_base::hex ? 16 : 10); // True if __beg becomes equal to __end. bool __testeof = __beg == __end; // First check for sign. bool __negative = false; if (!__testeof) { __c = *__beg; __negative = __c == __lit[__num_base::_S_iminus]; if ((__negative || __c == __lit[__num_base::_S_iplus]) && !(__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) && !(__c == __lc->_M_decimal_point)) { if (++__beg != __end) __c = *__beg; else __testeof = true; } } // Next, look for leading zeros and check required digits // for base formats. bool __found_zero = false; int __sep_pos = 0; while (!__testeof) { if ((__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) || __c == __lc->_M_decimal_point) break; else if (__c == __lit[__num_base::_S_izero] && (!__found_zero || __base == 10)) { __found_zero = true; ++__sep_pos; if (__basefield == 0) __base = 8; if (__base == 8) __sep_pos = 0; } else if (__found_zero && (__c == __lit[__num_base::_S_ix] || __c == __lit[__num_base::_S_iX])) { if (__basefield == 0) __base = 16; if (__base == 16) { __found_zero = false; __sep_pos = 0; } else break; } else break; if (++__beg != __end) { __c = *__beg; if (!__found_zero) break; } else __testeof = true; } // At this point, base is determined. If not hex, only allow // base digits as valid input. const size_t __len = (__base == 16 ? __num_base::_S_iend - __num_base::_S_izero : __base); // Extract. typedef __gnu_cxx::__numeric_traits<_ValueT> __num_traits; string __found_grouping; if (__lc->_M_use_grouping) __found_grouping.reserve(32); bool __testfail = false; bool __testoverflow = false; const __unsigned_type __max = (__negative && __num_traits::__is_signed) ? -static_cast<__unsigned_type>(__num_traits::__min) : __num_traits::__max; const __unsigned_type __smax = __max / __base; __unsigned_type __result = 0; int __digit = 0; const char_type* __lit_zero = __lit + __num_base::_S_izero; if (!__lc->_M_allocated) // "C" locale while (!__testeof) { __digit = _M_find(__lit_zero, __len, __c); if (__digit == -1) break; if (__result > __smax) __testoverflow = true; else { __result *= __base; __testoverflow |= __result > __max - __digit; __result += __digit; ++__sep_pos; } if (++__beg != __end) __c = *__beg; else __testeof = true; } else while (!__testeof) { // According to 22.2.2.1.2, p8-9, first look for thousands_sep // and decimal_point. if (__lc->_M_use_grouping && __c == __lc->_M_thousands_sep) { // NB: Thousands separator at the beginning of a string // is a no-no, as is two consecutive thousands separators. if (__sep_pos) { __found_grouping += static_cast(__sep_pos); __sep_pos = 0; } else { __testfail = true; break; } } else if (__c == __lc->_M_decimal_point) break; else { const char_type* __q = __traits_type::find(__lit_zero, __len, __c); if (!__q) break; __digit = __q - __lit_zero; if (__digit > 15) __digit -= 6; if (__result > __smax) __testoverflow = true; else { __result *= __base; __testoverflow |= __result > __max - __digit; __result += __digit; ++__sep_pos; } } if (++__beg != __end) __c = *__beg; else __testeof = true; } // Digit grouping is checked. If grouping and found_grouping don't // match, then get very very upset, and set failbit. if (__found_grouping.size()) { // Add the ending grouping. __found_grouping += static_cast(__sep_pos); if (!std::__verify_grouping(__lc->_M_grouping, __lc->_M_grouping_size, __found_grouping)) __err = ios_base::failbit; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. if ((!__sep_pos && !__found_zero && !__found_grouping.size()) || __testfail) { __v = 0; __err = ios_base::failbit; } else if (__testoverflow) { if (__negative && __num_traits::__is_signed) __v = __num_traits::__min; else __v = __num_traits::__max; __err = ios_base::failbit; } else __v = __negative ? -__result : __result; if (__testeof) __err |= ios_base::eofbit; return __beg; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 17. Bad bool parsing template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool& __v) const { if (!(__io.flags() & ios_base::boolalpha)) { // Parse bool values as long. // NB: We can't just call do_get(long) here, as it might // refer to a derived class. long __l = -1; __beg = _M_extract_int(__beg, __end, __io, __err, __l); if (__l == 0 || __l == 1) __v = bool(__l); else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. __v = true; __err = ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; } } else { // Parse bool values as alphanumeric. typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); bool __testf = true; bool __testt = true; bool __donef = __lc->_M_falsename_size == 0; bool __donet = __lc->_M_truename_size == 0; bool __testeof = false; size_t __n = 0; while (!__donef || !__donet) { if (__beg == __end) { __testeof = true; break; } const char_type __c = *__beg; if (!__donef) __testf = __c == __lc->_M_falsename[__n]; if (!__testf && __donet) break; if (!__donet) __testt = __c == __lc->_M_truename[__n]; if (!__testt && __donef) break; if (!__testt && !__testf) break; ++__n; ++__beg; __donef = !__testf || __n >= __lc->_M_falsename_size; __donet = !__testt || __n >= __lc->_M_truename_size; } if (__testf && __n == __lc->_M_falsename_size && __n) { __v = false; if (__testt && __n == __lc->_M_truename_size) __err = ios_base::failbit; else __err = __testeof ? ios_base::eofbit : ios_base::goodbit; } else if (__testt && __n == __lc->_M_truename_size && __n) { __v = true; __err = __testeof ? ios_base::eofbit : ios_base::goodbit; } else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. __v = false; __err = ios_base::failbit; if (__testeof) __err |= ios_base::eofbit; } } return __beg; } template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, float& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ template _InIter num_get<_CharT, _InIter>:: __do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #endif template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, long double& __v) const { string __xtrc; __xtrc.reserve(32); __beg = _M_extract_float(__beg, __end, __io, __err, __xtrc); std::__convert_to_v(__xtrc.c_str(), __v, __err, _S_get_c_locale()); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, void*& __v) const { // Prepare for hex formatted input. typedef ios_base::fmtflags fmtflags; const fmtflags __fmt = __io.flags(); __io.flags((__fmt & ~ios_base::basefield) | ios_base::hex); typedef __gnu_cxx::__conditional_type<(sizeof(void*) <= sizeof(unsigned long)), unsigned long, unsigned long long>::__type _UIntPtrType; _UIntPtrType __ul; __beg = _M_extract_int(__beg, __end, __io, __err, __ul); // Reset from hex formatted input. __io.flags(__fmt); __v = reinterpret_cast(__ul); return __beg; } // For use by integer and floating-point types after they have been // converted into a char_type string. template void num_put<_CharT, _OutIter>:: _M_pad(_CharT __fill, streamsize __w, ios_base& __io, _CharT* __new, const _CharT* __cs, int& __len) const { // [22.2.2.2.2] Stage 3. // If necessary, pad. __pad<_CharT, char_traits<_CharT> >::_S_pad(__io, __fill, __new, __cs, __w, __len); __len = static_cast(__w); } _GLIBCXX_END_NAMESPACE_LDBL template int __int_to_char(_CharT* __bufend, _ValueT __v, const _CharT* __lit, ios_base::fmtflags __flags, bool __dec) { _CharT* __buf = __bufend; if (__builtin_expect(__dec, true)) { // Decimal. do { *--__buf = __lit[(__v % 10) + __num_base::_S_odigits]; __v /= 10; } while (__v != 0); } else if ((__flags & ios_base::basefield) == ios_base::oct) { // Octal. do { *--__buf = __lit[(__v & 0x7) + __num_base::_S_odigits]; __v >>= 3; } while (__v != 0); } else { // Hex. const bool __uppercase = __flags & ios_base::uppercase; const int __case_offset = __uppercase ? __num_base::_S_oudigits : __num_base::_S_odigits; do { *--__buf = __lit[(__v & 0xf) + __case_offset]; __v >>= 4; } while (__v != 0); } return __bufend - __buf; } _GLIBCXX_BEGIN_NAMESPACE_LDBL template void num_put<_CharT, _OutIter>:: _M_group_int(const char* __grouping, size_t __grouping_size, _CharT __sep, ios_base&, _CharT* __new, _CharT* __cs, int& __len) const { _CharT* __p = std::__add_grouping(__new, __sep, __grouping, __grouping_size, __cs, __cs + __len); __len = __p - __new; } template template _OutIter num_put<_CharT, _OutIter>:: _M_insert_int(_OutIter __s, ios_base& __io, _CharT __fill, _ValueT __v) const { using __gnu_cxx::__add_unsigned; typedef typename __add_unsigned<_ValueT>::__type __unsigned_type; typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __lit = __lc->_M_atoms_out; const ios_base::fmtflags __flags = __io.flags(); // Long enough to hold hex, dec, and octal representations. const int __ilen = 5 * sizeof(_ValueT); _CharT* __cs = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __ilen)); // [22.2.2.2.2] Stage 1, numeric conversion to character. // Result is returned right-justified in the buffer. const ios_base::fmtflags __basefield = __flags & ios_base::basefield; const bool __dec = (__basefield != ios_base::oct && __basefield != ios_base::hex); const __unsigned_type __u = ((__v > 0 || !__dec) ? __unsigned_type(__v) : -__unsigned_type(__v)); int __len = __int_to_char(__cs + __ilen, __u, __lit, __flags, __dec); __cs += __ilen - __len; // Add grouping, if necessary. if (__lc->_M_use_grouping) { // Grouping can add (almost) as many separators as the number // of digits + space is reserved for numeric base or sign. _CharT* __cs2 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * (__len + 1) * 2)); _M_group_int(__lc->_M_grouping, __lc->_M_grouping_size, __lc->_M_thousands_sep, __io, __cs2 + 2, __cs, __len); __cs = __cs2 + 2; } // Complete Stage 1, prepend numeric base or sign. if (__builtin_expect(__dec, true)) { // Decimal. if (__v >= 0) { if (bool(__flags & ios_base::showpos) && __gnu_cxx::__numeric_traits<_ValueT>::__is_signed) *--__cs = __lit[__num_base::_S_oplus], ++__len; } else *--__cs = __lit[__num_base::_S_ominus], ++__len; } else if (bool(__flags & ios_base::showbase) && __v) { if (__basefield == ios_base::oct) *--__cs = __lit[__num_base::_S_odigits], ++__len; else { // 'x' or 'X' const bool __uppercase = __flags & ios_base::uppercase; *--__cs = __lit[__num_base::_S_ox + __uppercase]; // '0' *--__cs = __lit[__num_base::_S_odigits]; __len += 2; } } // Pad. const streamsize __w = __io.width(); if (__w > static_cast(__len)) { _CharT* __cs3 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __w)); _M_pad(__fill, __w, __io, __cs3, __cs, __len); __cs = __cs3; } __io.width(0); // [22.2.2.2.2] Stage 4. // Write resulting, fully-formatted string to output iterator. return std::__write(__s, __cs, __len); } template void num_put<_CharT, _OutIter>:: _M_group_float(const char* __grouping, size_t __grouping_size, _CharT __sep, const _CharT* __p, _CharT* __new, _CharT* __cs, int& __len) const { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 282. What types does numpunct grouping refer to? // Add grouping, if necessary. const int __declen = __p ? __p - __cs : __len; _CharT* __p2 = std::__add_grouping(__new, __sep, __grouping, __grouping_size, __cs, __cs + __declen); // Tack on decimal part. int __newlen = __p2 - __new; if (__p) { char_traits<_CharT>::copy(__p2, __p, __len - __declen); __newlen += __len - __declen; } __len = __newlen; } // The following code uses vsnprintf (or vsprintf(), when // _GLIBCXX_USE_C99_STDIO is not defined) to convert floating point // values for insertion into a stream. An optimization would be to // replace them with code that works directly on a wide buffer and // then use __pad to do the padding. It would be good to replace // them anyway to gain back the efficiency that C++ provides by // knowing up front the type of the values to insert. Also, sprintf // is dangerous since may lead to accidental buffer overruns. This // implementation follows the C++ standard fairly directly as // outlined in 22.2.2.2 [lib.locale.num.put] template template _OutIter num_put<_CharT, _OutIter>:: _M_insert_float(_OutIter __s, ios_base& __io, _CharT __fill, char __mod, _ValueT __v) const { typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); // Use default precision if out of range. const streamsize __prec = __io.precision() < 0 ? 6 : __io.precision(); const int __max_digits = __gnu_cxx::__numeric_traits<_ValueT>::__digits10; // [22.2.2.2.2] Stage 1, numeric conversion to character. int __len; // Long enough for the max format spec. char __fbuf[16]; __num_base::_S_format_float(__io, __fbuf, __mod); #if _GLIBCXX_USE_C99_STDIO && !_GLIBCXX_HAVE_BROKEN_VSNPRINTF // Precision is always used except for hexfloat format. const bool __use_prec = (__io.flags() & ios_base::floatfield) != ios_base::floatfield; // First try a buffer perhaps big enough (most probably sufficient // for non-ios_base::fixed outputs) int __cs_size = __max_digits * 3; char* __cs = static_cast(__builtin_alloca(__cs_size)); if (__use_prec) __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __prec, __v); else __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __v); // If the buffer was not large enough, try again with the correct size. if (__len >= __cs_size) { __cs_size = __len + 1; __cs = static_cast(__builtin_alloca(__cs_size)); if (__use_prec) __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __prec, __v); else __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, __fbuf, __v); } #else // Consider the possibility of long ios_base::fixed outputs const bool __fixed = __io.flags() & ios_base::fixed; const int __max_exp = __gnu_cxx::__numeric_traits<_ValueT>::__max_exponent10; // The size of the output string is computed as follows. // ios_base::fixed outputs may need up to __max_exp + 1 chars // for the integer part + __prec chars for the fractional part // + 3 chars for sign, decimal point, '\0'. On the other hand, // for non-fixed outputs __max_digits * 2 + __prec chars are // largely sufficient. const int __cs_size = __fixed ? __max_exp + __prec + 4 : __max_digits * 2 + __prec; char* __cs = static_cast(__builtin_alloca(__cs_size)); __len = std::__convert_from_v(_S_get_c_locale(), __cs, 0, __fbuf, __prec, __v); #endif // [22.2.2.2.2] Stage 2, convert to char_type, using correct // numpunct.decimal_point() values for '.' and adding grouping. const ctype<_CharT>& __ctype = use_facet >(__loc); _CharT* __ws = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __len)); __ctype.widen(__cs, __cs + __len, __ws); // Replace decimal point. _CharT* __wp = 0; const char* __p = char_traits::find(__cs, __len, '.'); if (__p) { __wp = __ws + (__p - __cs); *__wp = __lc->_M_decimal_point; } // Add grouping, if necessary. // N.B. Make sure to not group things like 2e20, i.e., no decimal // point, scientific notation. if (__lc->_M_use_grouping && (__wp || __len < 3 || (__cs[1] <= '9' && __cs[2] <= '9' && __cs[1] >= '0' && __cs[2] >= '0'))) { // Grouping can add (almost) as many separators as the // number of digits, but no more. _CharT* __ws2 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __len * 2)); streamsize __off = 0; if (__cs[0] == '-' || __cs[0] == '+') { __off = 1; __ws2[0] = __ws[0]; __len -= 1; } _M_group_float(__lc->_M_grouping, __lc->_M_grouping_size, __lc->_M_thousands_sep, __wp, __ws2 + __off, __ws + __off, __len); __len += __off; __ws = __ws2; } // Pad. const streamsize __w = __io.width(); if (__w > static_cast(__len)) { _CharT* __ws3 = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __w)); _M_pad(__fill, __w, __io, __ws3, __ws, __len); __ws = __ws3; } __io.width(0); // [22.2.2.2.2] Stage 4. // Write resulting, fully-formatted string to output iterator. return std::__write(__s, __ws, __len); } template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, bool __v) const { const ios_base::fmtflags __flags = __io.flags(); if ((__flags & ios_base::boolalpha) == 0) { const long __l = __v; __s = _M_insert_int(__s, __io, __fill, __l); } else { typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __name = __v ? __lc->_M_truename : __lc->_M_falsename; int __len = __v ? __lc->_M_truename_size : __lc->_M_falsename_size; const streamsize __w = __io.width(); if (__w > static_cast(__len)) { const streamsize __plen = __w - __len; _CharT* __ps = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __plen)); char_traits<_CharT>::assign(__ps, __plen, __fill); __io.width(0); if ((__flags & ios_base::adjustfield) == ios_base::left) { __s = std::__write(__s, __name, __len); __s = std::__write(__s, __ps, __plen); } else { __s = std::__write(__s, __ps, __plen); __s = std::__write(__s, __name, __len); } return __s; } __io.width(0); __s = std::__write(__s, __name, __len); } return __s; } template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, double __v) const { return _M_insert_float(__s, __io, __fill, char(), __v); } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ template _OutIter num_put<_CharT, _OutIter>:: __do_put(iter_type __s, ios_base& __io, char_type __fill, double __v) const { return _M_insert_float(__s, __io, __fill, char(), __v); } #endif template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, long double __v) const { return _M_insert_float(__s, __io, __fill, 'L', __v); } template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, const void* __v) const { const ios_base::fmtflags __flags = __io.flags(); const ios_base::fmtflags __fmt = ~(ios_base::basefield | ios_base::uppercase); __io.flags((__flags & __fmt) | (ios_base::hex | ios_base::showbase)); typedef __gnu_cxx::__conditional_type<(sizeof(const void*) <= sizeof(unsigned long)), unsigned long, unsigned long long>::__type _UIntPtrType; __s = _M_insert_int(__s, __io, __fill, reinterpret_cast<_UIntPtrType>(__v)); __io.flags(__flags); return __s; } _GLIBCXX_END_NAMESPACE_LDBL // Construct correctly padded string, as per 22.2.2.2.2 // Assumes // __newlen > __oldlen // __news is allocated for __newlen size // NB: Of the two parameters, _CharT can be deduced from the // function arguments. The other (_Traits) has to be explicitly specified. template void __pad<_CharT, _Traits>::_S_pad(ios_base& __io, _CharT __fill, _CharT* __news, const _CharT* __olds, streamsize __newlen, streamsize __oldlen) { const size_t __plen = static_cast(__newlen - __oldlen); const ios_base::fmtflags __adjust = __io.flags() & ios_base::adjustfield; // Padding last. if (__adjust == ios_base::left) { _Traits::copy(__news, __olds, __oldlen); _Traits::assign(__news + __oldlen, __plen, __fill); return; } size_t __mod = 0; if (__adjust == ios_base::internal) { // Pad after the sign, if there is one. // Pad after 0[xX], if there is one. // Who came up with these rules, anyway? Jeeze. const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); if (__ctype.widen('-') == __olds[0] || __ctype.widen('+') == __olds[0]) { __news[0] = __olds[0]; __mod = 1; ++__news; } else if (__ctype.widen('0') == __olds[0] && __oldlen > 1 && (__ctype.widen('x') == __olds[1] || __ctype.widen('X') == __olds[1])) { __news[0] = __olds[0]; __news[1] = __olds[1]; __mod = 2; __news += 2; } // else Padding first. } _Traits::assign(__news, __plen, __fill); _Traits::copy(__news + __plen, __olds + __mod, __oldlen - __mod); } template _CharT* __add_grouping(_CharT* __s, _CharT __sep, const char* __gbeg, size_t __gsize, const _CharT* __first, const _CharT* __last) { size_t __idx = 0; size_t __ctr = 0; while (__last - __first > __gbeg[__idx] && static_cast(__gbeg[__idx]) > 0 && __gbeg[__idx] != __gnu_cxx::__numeric_traits::__max) { __last -= __gbeg[__idx]; __idx < __gsize - 1 ? ++__idx : ++__ctr; } while (__first != __last) *__s++ = *__first++; while (__ctr--) { *__s++ = __sep; for (char __i = __gbeg[__idx]; __i > 0; --__i) *__s++ = *__first++; } while (__idx--) { *__s++ = __sep; for (char __i = __gbeg[__idx]; __i > 0; --__i) *__s++ = *__first++; } return __s; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct; extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL num_get; extern template class _GLIBCXX_NAMESPACE_LDBL num_put; extern template class ctype_byname; extern template const ctype& use_facet >(const locale&); extern template const numpunct& use_facet >(const locale&); extern template const num_put& use_facet >(const locale&); extern template const num_get& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct; extern template class _GLIBCXX_NAMESPACE_CXX11 numpunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL num_get; extern template class _GLIBCXX_NAMESPACE_LDBL num_put; extern template class ctype_byname; extern template const ctype& use_facet >(const locale&); extern template const numpunct& use_facet >(const locale&); extern template const num_put& use_facet >(const locale&); extern template const num_get& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/streambuf.tcc000064400000011501151027430570010711 0ustar00// Stream buffer classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/streambuf.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{streambuf} */ // // ISO C++ 14882: 27.5 Stream buffers // #ifndef _STREAMBUF_TCC #define _STREAMBUF_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template streamsize basic_streambuf<_CharT, _Traits>:: xsgetn(char_type* __s, streamsize __n) { streamsize __ret = 0; while (__ret < __n) { const streamsize __buf_len = this->egptr() - this->gptr(); if (__buf_len) { const streamsize __remaining = __n - __ret; const streamsize __len = std::min(__buf_len, __remaining); traits_type::copy(__s, this->gptr(), __len); __ret += __len; __s += __len; this->__safe_gbump(__len); } if (__ret < __n) { const int_type __c = this->uflow(); if (!traits_type::eq_int_type(__c, traits_type::eof())) { traits_type::assign(*__s++, traits_type::to_char_type(__c)); ++__ret; } else break; } } return __ret; } template streamsize basic_streambuf<_CharT, _Traits>:: xsputn(const char_type* __s, streamsize __n) { streamsize __ret = 0; while (__ret < __n) { const streamsize __buf_len = this->epptr() - this->pptr(); if (__buf_len) { const streamsize __remaining = __n - __ret; const streamsize __len = std::min(__buf_len, __remaining); traits_type::copy(this->pptr(), __s, __len); __ret += __len; __s += __len; this->__safe_pbump(__len); } if (__ret < __n) { int_type __c = this->overflow(traits_type::to_int_type(*__s)); if (!traits_type::eq_int_type(__c, traits_type::eof())) { ++__ret; ++__s; } else break; } } return __ret; } // Conceivably, this could be used to implement buffer-to-buffer // copies, if this was ever desired in an un-ambiguous way by the // standard. template streamsize __copy_streambufs_eof(basic_streambuf<_CharT, _Traits>* __sbin, basic_streambuf<_CharT, _Traits>* __sbout, bool& __ineof) { streamsize __ret = 0; __ineof = true; typename _Traits::int_type __c = __sbin->sgetc(); while (!_Traits::eq_int_type(__c, _Traits::eof())) { __c = __sbout->sputc(_Traits::to_char_type(__c)); if (_Traits::eq_int_type(__c, _Traits::eof())) { __ineof = false; break; } ++__ret; __c = __sbin->snextc(); } return __ret; } template inline streamsize __copy_streambufs(basic_streambuf<_CharT, _Traits>* __sbin, basic_streambuf<_CharT, _Traits>* __sbout) { bool __ineof; return __copy_streambufs_eof(__sbin, __sbout, __ineof); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_streambuf; extern template streamsize __copy_streambufs(basic_streambuf*, basic_streambuf*); extern template streamsize __copy_streambufs_eof(basic_streambuf*, basic_streambuf*, bool&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_streambuf; extern template streamsize __copy_streambufs(basic_streambuf*, basic_streambuf*); extern template streamsize __copy_streambufs_eof(basic_streambuf*, basic_streambuf*, bool&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/concept_check.h000064400000006537151027430570011204 0ustar00// Concept-checking control -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/concept_check.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _CONCEPT_CHECK_H #define _CONCEPT_CHECK_H 1 #pragma GCC system_header #include // All places in libstdc++-v3 where these are used, or /might/ be used, or // don't need to be used, or perhaps /should/ be used, are commented with // "concept requirements" (and maybe some more text). So grep like crazy // if you're looking for additional places to use these. // Concept-checking code is off by default unless users turn it on via // configure options or editing c++config.h. // It is not supported for freestanding implementations. #if !defined(_GLIBCXX_CONCEPT_CHECKS) || !_GLIBCXX_HOSTED #define __glibcxx_function_requires(...) #define __glibcxx_class_requires(_a,_b) #define __glibcxx_class_requires2(_a,_b,_c) #define __glibcxx_class_requires3(_a,_b,_c,_d) #define __glibcxx_class_requires4(_a,_b,_c,_d,_e) #else // the checks are on #include // Note that the obvious and elegant approach of // //#define glibcxx_function_requires(C) debug::function_requires< debug::C >() // // won't work due to concept templates with more than one parameter, e.g., // BinaryPredicateConcept. The preprocessor tries to split things up on // the commas in the template argument list. We can't use an inner pair of // parenthesis to hide the commas, because "debug::(Temp)" isn't // a valid instantiation pattern. Thus, we steal a feature from C99. #define __glibcxx_function_requires(...) \ __gnu_cxx::__function_requires< __gnu_cxx::__VA_ARGS__ >(); #define __glibcxx_class_requires(_a,_C) \ _GLIBCXX_CLASS_REQUIRES(_a, __gnu_cxx, _C); #define __glibcxx_class_requires2(_a,_b,_C) \ _GLIBCXX_CLASS_REQUIRES2(_a, _b, __gnu_cxx, _C); #define __glibcxx_class_requires3(_a,_b,_c,_C) \ _GLIBCXX_CLASS_REQUIRES3(_a, _b, _c, __gnu_cxx, _C); #define __glibcxx_class_requires4(_a,_b,_c,_d,_C) \ _GLIBCXX_CLASS_REQUIRES4(_a, _b, _c, _d, __gnu_cxx, _C); #endif // enable/disable #endif // _GLIBCXX_CONCEPT_CHECK c++/8/bits/fs_path.h000064400000100176151027430570010032 0ustar00// Class filesystem::path -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_path.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_PATH_H #define _GLIBCXX_FS_PATH_H 1 #if __cplusplus >= 201703L #include #include #include #include #include #include #include #include #include #include #include #if defined(_WIN32) && !defined(__CYGWIN__) # define _GLIBCXX_FILESYSTEM_IS_WINDOWS 1 # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @ingroup filesystem * @{ */ /// A filesystem path. class path { template struct __is_encoded_char : std::false_type { }; template> using __is_path_iter_src = __and_<__is_encoded_char, std::is_base_of>; template static __is_path_iter_src<_Iter> __is_path_src(_Iter, int); template static __is_encoded_char<_CharT> __is_path_src(const basic_string<_CharT, _Traits, _Alloc>&, int); template static __is_encoded_char<_CharT> __is_path_src(const basic_string_view<_CharT, _Traits>&, int); template static std::false_type __is_path_src(const _Unknown&, ...); template struct __constructible_from; template struct __constructible_from<_Iter, _Iter> : __is_path_iter_src<_Iter> { }; template struct __constructible_from<_Source, void> : decltype(__is_path_src(std::declval<_Source>(), 0)) { }; template using _Path = typename std::enable_if<__and_<__not_, path>>, __not_>>, __constructible_from<_Tp1, _Tp2>>::value, path>::type; template static _Source _S_range_begin(_Source __begin) { return __begin; } struct __null_terminated { }; template static __null_terminated _S_range_end(_Source) { return {}; } template static const _CharT* _S_range_begin(const basic_string<_CharT, _Traits, _Alloc>& __str) { return __str.data(); } template static const _CharT* _S_range_end(const basic_string<_CharT, _Traits, _Alloc>& __str) { return __str.data() + __str.size(); } template static const _CharT* _S_range_begin(const basic_string_view<_CharT, _Traits>& __str) { return __str.data(); } template static const _CharT* _S_range_end(const basic_string_view<_CharT, _Traits>& __str) { return __str.data() + __str.size(); } template())), typename _Val = typename std::iterator_traits<_Iter>::value_type> using __value_type_is_char = typename std::enable_if::value>::type; public: #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS typedef wchar_t value_type; static constexpr value_type preferred_separator = L'\\'; #else typedef char value_type; static constexpr value_type preferred_separator = '/'; #endif typedef std::basic_string string_type; enum format { native_format, generic_format, auto_format }; // constructors and destructor path() noexcept { } path(const path& __p) = default; path(path&& __p) noexcept : _M_pathname(std::move(__p._M_pathname)), _M_type(__p._M_type) { if (_M_type == _Type::_Multi) _M_split_cmpts(); __p.clear(); } path(string_type&& __source, format = auto_format) : _M_pathname(std::move(__source)) { _M_split_cmpts(); } template> path(_Source const& __source, format = auto_format) : _M_pathname(_S_convert(_S_range_begin(__source), _S_range_end(__source))) { _M_split_cmpts(); } template> path(_InputIterator __first, _InputIterator __last, format = auto_format) : _M_pathname(_S_convert(__first, __last)) { _M_split_cmpts(); } template, typename _Require2 = __value_type_is_char<_Source>> path(_Source const& __source, const locale& __loc, format = auto_format) : _M_pathname(_S_convert_loc(_S_range_begin(__source), _S_range_end(__source), __loc)) { _M_split_cmpts(); } template, typename _Require2 = __value_type_is_char<_InputIterator>> path(_InputIterator __first, _InputIterator __last, const locale& __loc, format = auto_format) : _M_pathname(_S_convert_loc(__first, __last, __loc)) { _M_split_cmpts(); } ~path() = default; // assignments path& operator=(const path& __p) = default; path& operator=(path&& __p) noexcept; path& operator=(string_type&& __source); path& assign(string_type&& __source); template _Path<_Source>& operator=(_Source const& __source) { return *this = path(__source); } template _Path<_Source>& assign(_Source const& __source) { return *this = path(__source); } template _Path<_InputIterator, _InputIterator>& assign(_InputIterator __first, _InputIterator __last) { return *this = path(__first, __last); } // appends path& operator/=(const path& __p) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS if (__p.is_absolute() || (__p.has_root_name() && __p.root_name() != root_name())) operator=(__p); else { string_type __pathname; if (__p.has_root_directory()) __pathname = root_name().native(); else if (has_filename() || (!has_root_directory() && is_absolute())) __pathname = _M_pathname + preferred_separator; __pathname += __p.relative_path().native(); // XXX is this right? _M_pathname.swap(__pathname); _M_split_cmpts(); } #else // Much simpler, as any path with root-name or root-dir is absolute. if (__p.is_absolute()) operator=(__p); else { if (has_filename() || (_M_type == _Type::_Root_name)) _M_pathname += preferred_separator; _M_pathname += __p.native(); _M_split_cmpts(); } #endif return *this; } template _Path<_Source>& operator/=(_Source const& __source) { return _M_append(path(__source)); } template _Path<_Source>& append(_Source const& __source) { return _M_append(path(__source)); } template _Path<_InputIterator, _InputIterator>& append(_InputIterator __first, _InputIterator __last) { return _M_append(path(__first, __last)); } // concatenation path& operator+=(const path& __x); path& operator+=(const string_type& __x); path& operator+=(const value_type* __x); path& operator+=(value_type __x); path& operator+=(basic_string_view __x); template _Path<_Source>& operator+=(_Source const& __x) { return concat(__x); } template _Path<_CharT*, _CharT*>& operator+=(_CharT __x); template _Path<_Source>& concat(_Source const& __x) { return *this += _S_convert(_S_range_begin(__x), _S_range_end(__x)); } template _Path<_InputIterator, _InputIterator>& concat(_InputIterator __first, _InputIterator __last) { return *this += _S_convert(__first, __last); } // modifiers void clear() noexcept { _M_pathname.clear(); _M_split_cmpts(); } path& make_preferred(); path& remove_filename(); path& replace_filename(const path& __replacement); path& replace_extension(const path& __replacement = path()); void swap(path& __rhs) noexcept; // native format observers const string_type& native() const noexcept { return _M_pathname; } const value_type* c_str() const noexcept { return _M_pathname.c_str(); } operator string_type() const { return _M_pathname; } template, typename _Allocator = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Allocator> string(const _Allocator& __a = _Allocator()) const; std::string string() const; #if _GLIBCXX_USE_WCHAR_T std::wstring wstring() const; #endif std::string u8string() const; std::u16string u16string() const; std::u32string u32string() const; // generic format observers template, typename _Allocator = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Allocator> generic_string(const _Allocator& __a = _Allocator()) const; std::string generic_string() const; #if _GLIBCXX_USE_WCHAR_T std::wstring generic_wstring() const; #endif std::string generic_u8string() const; std::u16string generic_u16string() const; std::u32string generic_u32string() const; // compare int compare(const path& __p) const noexcept; int compare(const string_type& __s) const; int compare(const value_type* __s) const; int compare(const basic_string_view __s) const; // decomposition path root_name() const; path root_directory() const; path root_path() const; path relative_path() const; path parent_path() const; path filename() const; path stem() const; path extension() const; // query [[nodiscard]] bool empty() const noexcept { return _M_pathname.empty(); } bool has_root_name() const; bool has_root_directory() const; bool has_root_path() const; bool has_relative_path() const; bool has_parent_path() const; bool has_filename() const; bool has_stem() const; bool has_extension() const; bool is_absolute() const { return has_root_directory(); } bool is_relative() const { return !is_absolute(); } // generation path lexically_normal() const; path lexically_relative(const path& base) const; path lexically_proximate(const path& base) const; // iterators class iterator; typedef iterator const_iterator; iterator begin() const; iterator end() const; private: enum class _Type : unsigned char { _Multi, _Root_name, _Root_dir, _Filename }; path(string_type __str, _Type __type) : _M_pathname(__str), _M_type(__type) { __glibcxx_assert(_M_type != _Type::_Multi); } enum class _Split { _Stem, _Extension }; path& _M_append(path __p) { if (__p.is_absolute()) operator=(std::move(__p)); #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS else if (__p.has_root_name() && __p.root_name() != root_name()) operator=(std::move(__p)); #endif else operator/=(const_cast(__p)); return *this; } pair _M_find_extension() const; template struct _Cvt; static string_type _S_convert(value_type* __src, __null_terminated) { return string_type(__src); } static string_type _S_convert(const value_type* __src, __null_terminated) { return string_type(__src); } template static string_type _S_convert(_Iter __first, _Iter __last) { using __value_type = typename std::iterator_traits<_Iter>::value_type; return _Cvt::type>:: _S_convert(__first, __last); } template static string_type _S_convert(_InputIterator __src, __null_terminated) { using _Tp = typename std::iterator_traits<_InputIterator>::value_type; std::basic_string::type> __tmp; for (; *__src != _Tp{}; ++__src) __tmp.push_back(*__src); return _S_convert(__tmp.c_str(), __tmp.c_str() + __tmp.size()); } static string_type _S_convert_loc(const char* __first, const char* __last, const std::locale& __loc); template static string_type _S_convert_loc(_Iter __first, _Iter __last, const std::locale& __loc) { const std::string __str(__first, __last); return _S_convert_loc(__str.data(), __str.data()+__str.size(), __loc); } template static string_type _S_convert_loc(_InputIterator __src, __null_terminated, const std::locale& __loc) { std::string __tmp; while (*__src != '\0') __tmp.push_back(*__src++); return _S_convert_loc(__tmp.data(), __tmp.data()+__tmp.size(), __loc); } template static basic_string<_CharT, _Traits, _Allocator> _S_str_convert(basic_string_view, const _Allocator&); static bool _S_is_dir_sep(value_type __ch) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS return __ch == L'/' || __ch == preferred_separator; #else return __ch == '/'; #endif } void _M_split_cmpts(); void _M_trim(); void _M_add_root_name(size_t __n); void _M_add_root_dir(size_t __pos); void _M_add_filename(size_t __pos, size_t __n); string_type _M_pathname; struct _Cmpt; using _List = _GLIBCXX_STD_C::vector<_Cmpt>; _List _M_cmpts; // empty unless _M_type == _Type::_Multi _Type _M_type = _Type::_Filename; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = wchar_t; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char16_t; }; template<> struct path::__is_encoded_char : std::true_type { using value_type = char32_t; }; template struct path::__is_encoded_char : __is_encoded_char<_Tp> { }; inline void swap(path& __lhs, path& __rhs) noexcept { __lhs.swap(__rhs); } size_t hash_value(const path& __p) noexcept; /// Compare paths inline bool operator<(const path& __lhs, const path& __rhs) noexcept { return __lhs.compare(__rhs) < 0; } /// Compare paths inline bool operator<=(const path& __lhs, const path& __rhs) noexcept { return !(__rhs < __lhs); } /// Compare paths inline bool operator>(const path& __lhs, const path& __rhs) noexcept { return __rhs < __lhs; } /// Compare paths inline bool operator>=(const path& __lhs, const path& __rhs) noexcept { return !(__lhs < __rhs); } /// Compare paths inline bool operator==(const path& __lhs, const path& __rhs) noexcept { return __lhs.compare(__rhs) == 0; } /// Compare paths inline bool operator!=(const path& __lhs, const path& __rhs) noexcept { return !(__lhs == __rhs); } /// Append one path to another inline path operator/(const path& __lhs, const path& __rhs) { path __result(__lhs); __result /= __rhs; return __result; } /// Write a path to a stream template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const path& __p) { auto __tmp = __p.string<_CharT, _Traits>(); using __quoted_string = std::__detail::_Quoted_string; __os << __quoted_string{__tmp, '"', '\\'}; return __os; } /// Read a path from a stream template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, path& __p) { basic_string<_CharT, _Traits> __tmp; using __quoted_string = std::__detail::_Quoted_string; if (__is >> __quoted_string{ __tmp, '"', '\\' }) __p = std::move(__tmp); return __is; } template inline auto u8path(const _Source& __source) -> decltype(filesystem::path(__source, std::locale::classic())) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS const std::string __u8str{__source}; return std::filesystem::u8path(__u8str.begin(), __u8str.end()); #else return path{ __source }; #endif } template inline auto u8path(_InputIterator __first, _InputIterator __last) -> decltype(filesystem::path(__first, __last, std::locale::classic())) { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS codecvt_utf8 __cvt; string_type __tmp; if (__str_codecvt_in(__first, __last, __tmp, __cvt)) return path{ __tmp }; else return {}; #else return path{ __first, __last }; #endif } class filesystem_error : public std::system_error { public: filesystem_error(const string& __what_arg, error_code __ec) : system_error(__ec, __what_arg) { } filesystem_error(const string& __what_arg, const path& __p1, error_code __ec) : system_error(__ec, __what_arg), _M_path1(__p1) { } filesystem_error(const string& __what_arg, const path& __p1, const path& __p2, error_code __ec) : system_error(__ec, __what_arg), _M_path1(__p1), _M_path2(__p2) { } ~filesystem_error(); const path& path1() const noexcept { return _M_path1; } const path& path2() const noexcept { return _M_path2; } const char* what() const noexcept { return _M_what.c_str(); } private: std::string _M_gen_what(); path _M_path1; path _M_path2; std::string _M_what = _M_gen_what(); }; struct path::_Cmpt : path { _Cmpt(string_type __s, _Type __t, size_t __pos) : path(std::move(__s), __t), _M_pos(__pos) { } _Cmpt() : _M_pos(-1) { } size_t _M_pos; }; // specialize _Cvt for degenerate 'noconv' case template<> struct path::_Cvt { template static string_type _S_convert(_Iter __first, _Iter __last) { return string_type{__first, __last}; } }; template struct path::_Cvt { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS static string_type _S_wconvert(const char* __f, const char* __l, true_type) { using _Cvt = std::codecvt; const auto& __cvt = std::use_facet<_Cvt>(std::locale{}); std::wstring __wstr; if (__str_codecvt_in(__f, __l, __wstr, __cvt)) return __wstr; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } static string_type _S_wconvert(const _CharT* __f, const _CharT* __l, false_type) { std::codecvt_utf8<_CharT> __cvt; std::string __str; if (__str_codecvt_out(__f, __l, __str, __cvt)) { const char* __f2 = __str.data(); const char* __l2 = __f2 + __str.size(); std::codecvt_utf8 __wcvt; std::wstring __wstr; if (__str_codecvt_in(__f2, __l2, __wstr, __wcvt)) return __wstr; } _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } static string_type _S_convert(const _CharT* __f, const _CharT* __l) { return _S_wconvert(__f, __l, is_same<_CharT, char>{}); } #else static string_type _S_convert(const _CharT* __f, const _CharT* __l) { std::codecvt_utf8<_CharT> __cvt; std::string __str; if (__str_codecvt_out(__f, __l, __str, __cvt)) return __str; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } #endif static string_type _S_convert(_CharT* __f, _CharT* __l) { return _S_convert(const_cast(__f), const_cast(__l)); } template static string_type _S_convert(_Iter __first, _Iter __last) { const std::basic_string<_CharT> __str(__first, __last); return _S_convert(__str.data(), __str.data() + __str.size()); } template static string_type _S_convert(__gnu_cxx::__normal_iterator<_Iter, _Cont> __first, __gnu_cxx::__normal_iterator<_Iter, _Cont> __last) { return _S_convert(__first.base(), __last.base()); } }; /// An iterator for the components of a path class path::iterator { public: using difference_type = std::ptrdiff_t; using value_type = path; using reference = const path&; using pointer = const path*; using iterator_category = std::bidirectional_iterator_tag; iterator() : _M_path(nullptr), _M_cur(), _M_at_end() { } iterator(const iterator&) = default; iterator& operator=(const iterator&) = default; reference operator*() const; pointer operator->() const { return std::__addressof(**this); } iterator& operator++(); iterator operator++(int) { auto __tmp = *this; ++*this; return __tmp; } iterator& operator--(); iterator operator--(int) { auto __tmp = *this; --*this; return __tmp; } friend bool operator==(const iterator& __lhs, const iterator& __rhs) { return __lhs._M_equals(__rhs); } friend bool operator!=(const iterator& __lhs, const iterator& __rhs) { return !__lhs._M_equals(__rhs); } private: friend class path; iterator(const path* __path, path::_List::const_iterator __iter) : _M_path(__path), _M_cur(__iter), _M_at_end() { } iterator(const path* __path, bool __at_end) : _M_path(__path), _M_cur(), _M_at_end(__at_end) { } bool _M_equals(iterator) const; const path* _M_path; path::_List::const_iterator _M_cur; bool _M_at_end; // only used when type != _Multi }; inline path& path::operator=(path&& __p) noexcept { if (&__p == this) return *this; _M_pathname = std::move(__p._M_pathname); _M_cmpts = std::move(__p._M_cmpts); _M_type = __p._M_type; __p.clear(); return *this; } inline path& path::operator=(string_type&& __source) { return *this = path(std::move(__source)); } inline path& path::assign(string_type&& __source) { return *this = path(std::move(__source)); } inline path& path::operator+=(const path& __p) { return operator+=(__p.native()); } inline path& path::operator+=(const string_type& __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(const value_type* __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(value_type __x) { _M_pathname += __x; _M_split_cmpts(); return *this; } inline path& path::operator+=(basic_string_view __x) { _M_pathname.append(__x.data(), __x.size()); _M_split_cmpts(); return *this; } template inline path::_Path<_CharT*, _CharT*>& path::operator+=(_CharT __x) { auto* __addr = std::__addressof(__x); return concat(__addr, __addr + 1); } inline path& path::make_preferred() { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS std::replace(_M_pathname.begin(), _M_pathname.end(), L'/', preferred_separator); #endif return *this; } inline void path::swap(path& __rhs) noexcept { _M_pathname.swap(__rhs._M_pathname); _M_cmpts.swap(__rhs._M_cmpts); std::swap(_M_type, __rhs._M_type); } template std::basic_string<_CharT, _Traits, _Allocator> path::_S_str_convert(basic_string_view __str, const _Allocator& __a) { if (__str.size() == 0) return std::basic_string<_CharT, _Traits, _Allocator>(__a); const value_type* __first = __str.data(); const value_type* __last = __first + __str.size(); #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS using _CharAlloc = __alloc_rebind<_Allocator, char>; using _String = basic_string, _CharAlloc>; using _WString = basic_string<_CharT, _Traits, _Allocator>; // use codecvt_utf8 to convert native string to UTF-8 codecvt_utf8 __cvt; _String __u8str{_CharAlloc{__a}}; if (__str_codecvt_out(__first, __last, __u8str, __cvt)) { if constexpr (is_same_v<_CharT, char>) return __u8str; else { _WString __wstr; // use codecvt_utf8<_CharT> to convert UTF-8 to wide string codecvt_utf8<_CharT> __cvt; const char* __f = __u8str.data(); const char* __l = __f + __u8str.size(); if (__str_codecvt_in(__f, __l, __wstr, __cvt)) return __wstr; } } #else codecvt_utf8<_CharT> __cvt; basic_string<_CharT, _Traits, _Allocator> __wstr{__a}; if (__str_codecvt_in(__first, __last, __wstr, __cvt)) return __wstr; #endif _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); } template inline basic_string<_CharT, _Traits, _Allocator> path::string(const _Allocator& __a) const { if constexpr (is_same_v<_CharT, value_type>) #if _GLIBCXX_USE_CXX11_ABI return { _M_pathname, __a }; #else return { _M_pathname, string_type::size_type(0), __a }; #endif else return _S_str_convert<_CharT, _Traits>(_M_pathname, __a); } inline std::string path::string() const { return string(); } #if _GLIBCXX_USE_WCHAR_T inline std::wstring path::wstring() const { return string(); } #endif inline std::string path::u8string() const { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS std::string __str; // convert from native encoding to UTF-8 codecvt_utf8 __cvt; const value_type* __first = _M_pathname.data(); const value_type* __last = __first + _M_pathname.size(); if (__str_codecvt_out(__first, __last, __str, __cvt)) return __str; _GLIBCXX_THROW_OR_ABORT(filesystem_error( "Cannot convert character sequence", std::make_error_code(errc::illegal_byte_sequence))); #else return _M_pathname; #endif } inline std::u16string path::u16string() const { return string(); } inline std::u32string path::u32string() const { return string(); } template inline std::basic_string<_CharT, _Traits, _Allocator> path::generic_string(const _Allocator& __a) const { #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS const value_type __slash = L'/'; #else const value_type __slash = '/'; #endif using _Alloc2 = typename allocator_traits<_Allocator>::template rebind_alloc; basic_string, _Alloc2> __str(__a); if (_M_type == _Type::_Root_dir) __str.assign(1, __slash); else { __str.reserve(_M_pathname.size()); bool __add_slash = false; for (auto& __elem : *this) { if (__add_slash) __str += __slash; __str += basic_string_view(__elem._M_pathname); __add_slash = __elem._M_type == _Type::_Filename; } } if constexpr (is_same_v<_CharT, value_type>) return __str; else return _S_str_convert<_CharT, _Traits>(__str, __a); } inline std::string path::generic_string() const { return generic_string(); } #if _GLIBCXX_USE_WCHAR_T inline std::wstring path::generic_wstring() const { return generic_string(); } #endif inline std::string path::generic_u8string() const { return generic_string(); } inline std::u16string path::generic_u16string() const { return generic_string(); } inline std::u32string path::generic_u32string() const { return generic_string(); } inline int path::compare(const string_type& __s) const { return compare(path(__s)); } inline int path::compare(const value_type* __s) const { return compare(path(__s)); } inline int path::compare(basic_string_view __s) const { return compare(path(__s)); } inline path path::filename() const { if (empty()) return {}; else if (_M_type == _Type::_Filename) return *this; else if (_M_type == _Type::_Multi) { if (_M_pathname.back() == preferred_separator) return {}; auto& __last = *--end(); if (__last._M_type == _Type::_Filename) return __last; } return {}; } inline path path::stem() const { auto ext = _M_find_extension(); if (ext.first && ext.second != 0) return path{ext.first->substr(0, ext.second)}; return {}; } inline path path::extension() const { auto ext = _M_find_extension(); if (ext.first && ext.second != string_type::npos) return path{ext.first->substr(ext.second)}; return {}; } inline bool path::has_stem() const { auto ext = _M_find_extension(); return ext.first && ext.second != 0; } inline bool path::has_extension() const { auto ext = _M_find_extension(); return ext.first && ext.second != string_type::npos; } inline path::iterator path::begin() const { if (_M_type == _Type::_Multi) return iterator(this, _M_cmpts.begin()); return iterator(this, empty()); } inline path::iterator path::end() const { if (_M_type == _Type::_Multi) return iterator(this, _M_cmpts.end()); return iterator(this, true); } inline path::iterator& path::iterator::operator++() { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.end()); ++_M_cur; } else { __glibcxx_assert(!_M_at_end); _M_at_end = true; } return *this; } inline path::iterator& path::iterator::operator--() { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.begin()); --_M_cur; } else { __glibcxx_assert(_M_at_end); _M_at_end = false; } return *this; } inline path::iterator::reference path::iterator::operator*() const { __glibcxx_assert(_M_path != nullptr); if (_M_path->_M_type == _Type::_Multi) { __glibcxx_assert(_M_cur != _M_path->_M_cmpts.end()); return *_M_cur; } return *_M_path; } inline bool path::iterator::_M_equals(iterator __rhs) const { if (_M_path != __rhs._M_path) return false; if (_M_path == nullptr) return true; if (_M_path->_M_type == path::_Type::_Multi) return _M_cur == __rhs._M_cur; return _M_at_end == __rhs._M_at_end; } // @} group filesystem _GLIBCXX_END_NAMESPACE_CXX11 } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_PATH_H c++/8/bits/basic_string.h000064400000732011151027430570011054 0ustar00// Components for manipulating sequences of characters -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_string.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{string} */ // // ISO C++ 14882: 21 Strings library // #ifndef _BASIC_STRING_H #define _BASIC_STRING_H 1 #pragma GCC system_header #include #include #include #if __cplusplus >= 201103L #include #endif #if __cplusplus > 201402L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus >= 201703L // Support P0426R1 changes to char_traits in C++17. # define __cpp_lib_constexpr_string 201611L #endif #if _GLIBCXX_USE_CXX11_ABI _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @class basic_string basic_string.h * @brief Managing sequences of characters and character-like objects. * * @ingroup strings * @ingroup sequences * * @tparam _CharT Type of character * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * @tparam _Alloc Allocator type, defaults to allocator<_CharT>. * * Meets the requirements of a container, a * reversible container, and a * sequence. Of the * optional sequence requirements, only * @c push_back, @c at, and @c %array access are supported. */ template class basic_string { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_CharT>::other _Char_alloc_type; typedef __gnu_cxx::__alloc_traits<_Char_alloc_type> _Alloc_traits; // Types: public: typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef _Char_alloc_type allocator_type; typedef typename _Alloc_traits::size_type size_type; typedef typename _Alloc_traits::difference_type difference_type; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef __gnu_cxx::__normal_iterator iterator; typedef __gnu_cxx::__normal_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; /// Value returned by various member functions when they fail. static const size_type npos = static_cast(-1); private: // type used for positions in insert, erase etc. #if __cplusplus < 201103L typedef iterator __const_iterator; #else typedef const_iterator __const_iterator; #endif #if __cplusplus > 201402L // A helper type for avoiding boiler-plate. typedef basic_string_view<_CharT, _Traits> __sv_type; template using _If_sv = enable_if_t< __and_, __not_>, __not_>>::value, _Res>; // Allows an implicit conversion to __sv_type. static __sv_type _S_to_string_view(__sv_type __svt) noexcept { return __svt; } // Wraps a string_view by explicit conversion and thus // allows to add an internal constructor that does not // participate in overload resolution when a string_view // is provided. struct __sv_wrapper { explicit __sv_wrapper(__sv_type __sv) noexcept : _M_sv(__sv) { } __sv_type _M_sv; }; #endif // Use empty-base optimization: http://www.cantrip.org/emptyopt.html struct _Alloc_hider : allocator_type // TODO check __is_final { #if __cplusplus < 201103L _Alloc_hider(pointer __dat, const _Alloc& __a = _Alloc()) : allocator_type(__a), _M_p(__dat) { } #else _Alloc_hider(pointer __dat, const _Alloc& __a) : allocator_type(__a), _M_p(__dat) { } _Alloc_hider(pointer __dat, _Alloc&& __a = _Alloc()) : allocator_type(std::move(__a)), _M_p(__dat) { } #endif pointer _M_p; // The actual data. }; _Alloc_hider _M_dataplus; size_type _M_string_length; enum { _S_local_capacity = 15 / sizeof(_CharT) }; union { _CharT _M_local_buf[_S_local_capacity + 1]; size_type _M_allocated_capacity; }; void _M_data(pointer __p) { _M_dataplus._M_p = __p; } void _M_length(size_type __length) { _M_string_length = __length; } pointer _M_data() const { return _M_dataplus._M_p; } pointer _M_local_data() { #if __cplusplus >= 201103L return std::pointer_traits::pointer_to(*_M_local_buf); #else return pointer(_M_local_buf); #endif } const_pointer _M_local_data() const { #if __cplusplus >= 201103L return std::pointer_traits::pointer_to(*_M_local_buf); #else return const_pointer(_M_local_buf); #endif } void _M_capacity(size_type __capacity) { _M_allocated_capacity = __capacity; } void _M_set_length(size_type __n) { _M_length(__n); traits_type::assign(_M_data()[__n], _CharT()); } bool _M_is_local() const { return _M_data() == _M_local_data(); } // Create & Destroy pointer _M_create(size_type&, size_type); void _M_dispose() { if (!_M_is_local()) _M_destroy(_M_allocated_capacity); } void _M_destroy(size_type __size) throw() { _Alloc_traits::deallocate(_M_get_allocator(), _M_data(), __size + 1); } // _M_construct_aux is used to implement the 21.3.1 para 15 which // requires special behaviour if _InIterator is an integral type template void _M_construct_aux(_InIterator __beg, _InIterator __end, std::__false_type) { typedef typename iterator_traits<_InIterator>::iterator_category _Tag; _M_construct(__beg, __end, _Tag()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_construct_aux(_Integer __beg, _Integer __end, std::__true_type) { _M_construct_aux_2(static_cast(__beg), __end); } void _M_construct_aux_2(size_type __req, _CharT __c) { _M_construct(__req, __c); } template void _M_construct(_InIterator __beg, _InIterator __end) { typedef typename std::__is_integer<_InIterator>::__type _Integral; _M_construct_aux(__beg, __end, _Integral()); } // For Input Iterators, used in istreambuf_iterators, etc. template void _M_construct(_InIterator __beg, _InIterator __end, std::input_iterator_tag); // For forward_iterators up to random_access_iterators, used for // string::iterator, _CharT*, etc. template void _M_construct(_FwdIterator __beg, _FwdIterator __end, std::forward_iterator_tag); void _M_construct(size_type __req, _CharT __c); allocator_type& _M_get_allocator() { return _M_dataplus; } const allocator_type& _M_get_allocator() const { return _M_dataplus; } private: #ifdef _GLIBCXX_DISAMBIGUATE_REPLACE_INST // The explicit instantiations in misc-inst.cc require this due to // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64063 template::__value && !__are_same<_Tp, const _CharT*>::__value && !__are_same<_Tp, iterator>::__value && !__are_same<_Tp, const_iterator>::__value> struct __enable_if_not_native_iterator { typedef basic_string& __type; }; template struct __enable_if_not_native_iterator<_Tp, false> { }; #endif size_type _M_check(size_type __pos, const char* __s) const { if (__pos > this->size()) __throw_out_of_range_fmt(__N("%s: __pos (which is %zu) > " "this->size() (which is %zu)"), __s, __pos, this->size()); return __pos; } void _M_check_length(size_type __n1, size_type __n2, const char* __s) const { if (this->max_size() - (this->size() - __n1) < __n2) __throw_length_error(__N(__s)); } // NB: _M_limit doesn't check for a bad __pos value. size_type _M_limit(size_type __pos, size_type __off) const _GLIBCXX_NOEXCEPT { const bool __testoff = __off < this->size() - __pos; return __testoff ? __off : this->size() - __pos; } // True if _Rep and source do not overlap. bool _M_disjunct(const _CharT* __s) const _GLIBCXX_NOEXCEPT { return (less()(__s, _M_data()) || less()(_M_data() + this->size(), __s)); } // When __n = 1 way faster than the general multichar // traits_type::copy/move/assign. static void _S_copy(_CharT* __d, const _CharT* __s, size_type __n) { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::copy(__d, __s, __n); } static void _S_move(_CharT* __d, const _CharT* __s, size_type __n) { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::move(__d, __s, __n); } static void _S_assign(_CharT* __d, size_type __n, _CharT __c) { if (__n == 1) traits_type::assign(*__d, __c); else traits_type::assign(__d, __n, __c); } // _S_copy_chars is a separate template to permit specialization // to optimize for the common case of pointers as iterators. template static void _S_copy_chars(_CharT* __p, _Iterator __k1, _Iterator __k2) { for (; __k1 != __k2; ++__k1, (void)++__p) traits_type::assign(*__p, *__k1); // These types are off. } static void _S_copy_chars(_CharT* __p, iterator __k1, iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, const_iterator __k1, const_iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, _CharT* __k1, _CharT* __k2) _GLIBCXX_NOEXCEPT { _S_copy(__p, __k1, __k2 - __k1); } static void _S_copy_chars(_CharT* __p, const _CharT* __k1, const _CharT* __k2) _GLIBCXX_NOEXCEPT { _S_copy(__p, __k1, __k2 - __k1); } static int _S_compare(size_type __n1, size_type __n2) _GLIBCXX_NOEXCEPT { const difference_type __d = difference_type(__n1 - __n2); if (__d > __gnu_cxx::__numeric_traits::__max) return __gnu_cxx::__numeric_traits::__max; else if (__d < __gnu_cxx::__numeric_traits::__min) return __gnu_cxx::__numeric_traits::__min; else return int(__d); } void _M_assign(const basic_string&); void _M_mutate(size_type __pos, size_type __len1, const _CharT* __s, size_type __len2); void _M_erase(size_type __pos, size_type __n); public: // Construct/copy/destroy: // NB: We overload ctors in some cases instead of using default // arguments, per 17.4.4.4 para. 2 item 2. /** * @brief Default constructor creates an empty string. */ basic_string() _GLIBCXX_NOEXCEPT_IF(is_nothrow_default_constructible<_Alloc>::value) : _M_dataplus(_M_local_data()) { _M_set_length(0); } /** * @brief Construct an empty string using allocator @a a. */ explicit basic_string(const _Alloc& __a) _GLIBCXX_NOEXCEPT : _M_dataplus(_M_local_data(), __a) { _M_set_length(0); } /** * @brief Construct string with copy of value of @a __str. * @param __str Source string. */ basic_string(const basic_string& __str) : _M_dataplus(_M_local_data(), _Alloc_traits::_S_select_on_copy(__str._M_get_allocator())) { _M_construct(__str._M_data(), __str._M_data() + __str.length()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2583. no way to supply an allocator for basic_string(str, pos) /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { const _CharT* __start = __str._M_data() + __str._M_check(__pos, "basic_string::basic_string"); _M_construct(__start, __start + __str._M_limit(__pos, npos)); } /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. */ basic_string(const basic_string& __str, size_type __pos, size_type __n) : _M_dataplus(_M_local_data()) { const _CharT* __start = __str._M_data() + __str._M_check(__pos, "basic_string::basic_string"); _M_construct(__start, __start + __str._M_limit(__pos, __n)); } /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, size_type __n, const _Alloc& __a) : _M_dataplus(_M_local_data(), __a) { const _CharT* __start = __str._M_data() + __str._M_check(__pos, "string::string"); _M_construct(__start, __start + __str._M_limit(__pos, __n)); } /** * @brief Construct string initialized by a character %array. * @param __s Source character %array. * @param __n Number of characters to copy. * @param __a Allocator to use (default is default allocator). * * NB: @a __s must have at least @a __n characters, '\\0' * has no special meaning. */ basic_string(const _CharT* __s, size_type __n, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__s, __s + __n); } /** * @brief Construct string as copy of a C string. * @param __s Source C string. * @param __a Allocator to use (default is default allocator). */ #if __cpp_deduction_guides && ! defined _GLIBCXX_DEFINING_STRING_INSTANTIATIONS // _GLIBCXX_RESOLVE_LIB_DEFECTS // 3076. basic_string CTAD ambiguity template> #endif basic_string(const _CharT* __s, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__s, __s ? __s + traits_type::length(__s) : __s+npos); } /** * @brief Construct string as multiple characters. * @param __n Number of characters. * @param __c Character to use. * @param __a Allocator to use (default is default allocator). */ #if __cpp_deduction_guides && ! defined _GLIBCXX_DEFINING_STRING_INSTANTIATIONS // _GLIBCXX_RESOLVE_LIB_DEFECTS // 3076. basic_string CTAD ambiguity template> #endif basic_string(size_type __n, _CharT __c, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__n, __c); } #if __cplusplus >= 201103L /** * @brief Move construct string. * @param __str Source string. * * The newly-created string contains the exact contents of @a __str. * @a __str is a valid, but unspecified string. **/ basic_string(basic_string&& __str) noexcept : _M_dataplus(_M_local_data(), std::move(__str._M_get_allocator())) { if (__str._M_is_local()) { traits_type::copy(_M_local_buf, __str._M_local_buf, _S_local_capacity + 1); } else { _M_data(__str._M_data()); _M_capacity(__str._M_allocated_capacity); } // Must use _M_length() here not _M_set_length() because // basic_stringbuf relies on writing into unallocated capacity so // we mess up the contents if we put a '\0' in the string. _M_length(__str.length()); __str._M_data(__str._M_local_data()); __str._M_set_length(0); } /** * @brief Construct string from an initializer %list. * @param __l std::initializer_list of characters. * @param __a Allocator to use (default is default allocator). */ basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__l.begin(), __l.end()); } basic_string(const basic_string& __str, const _Alloc& __a) : _M_dataplus(_M_local_data(), __a) { _M_construct(__str.begin(), __str.end()); } basic_string(basic_string&& __str, const _Alloc& __a) noexcept(_Alloc_traits::_S_always_equal()) : _M_dataplus(_M_local_data(), __a) { if (__str._M_is_local()) { traits_type::copy(_M_local_buf, __str._M_local_buf, _S_local_capacity + 1); _M_length(__str.length()); __str._M_set_length(0); } else if (_Alloc_traits::_S_always_equal() || __str.get_allocator() == __a) { _M_data(__str._M_data()); _M_length(__str.length()); _M_capacity(__str._M_allocated_capacity); __str._M_data(__str._M_local_buf); __str._M_set_length(0); } else _M_construct(__str.begin(), __str.end()); } #endif // C++11 /** * @brief Construct string as copy of a range. * @param __beg Start of range. * @param __end End of range. * @param __a Allocator to use (default is default allocator). */ #if __cplusplus >= 201103L template> #else template #endif basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a = _Alloc()) : _M_dataplus(_M_local_data(), __a) { _M_construct(__beg, __end); } #if __cplusplus > 201402L /** * @brief Construct string from a substring of a string_view. * @param __t Source object convertible to string view. * @param __pos The index of the first character to copy from __t. * @param __n The number of characters to copy from __t. * @param __a Allocator to use. */ template> basic_string(const _Tp& __t, size_type __pos, size_type __n, const _Alloc& __a = _Alloc()) : basic_string(_S_to_string_view(__t).substr(__pos, __n), __a) { } /** * @brief Construct string from a string_view. * @param __t Source object convertible to string view. * @param __a Allocator to use (default is default allocator). */ template> explicit basic_string(const _Tp& __t, const _Alloc& __a = _Alloc()) : basic_string(__sv_wrapper(_S_to_string_view(__t)), __a) { } /** * @brief Only internally used: Construct string from a string view * wrapper. * @param __svw string view wrapper. * @param __a Allocator to use. */ explicit basic_string(__sv_wrapper __svw, const _Alloc& __a) : basic_string(__svw._M_sv.data(), __svw._M_sv.size(), __a) { } #endif // C++17 /** * @brief Destroy the string instance. */ ~basic_string() { _M_dispose(); } /** * @brief Assign the value of @a str to this string. * @param __str Source string. */ basic_string& operator=(const basic_string& __str) { #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { if (!_Alloc_traits::_S_always_equal() && !_M_is_local() && _M_get_allocator() != __str._M_get_allocator()) { // Propagating allocator cannot free existing storage so must // deallocate it before replacing current allocator. if (__str.size() <= _S_local_capacity) { _M_destroy(_M_allocated_capacity); _M_data(_M_local_data()); _M_set_length(0); } else { const auto __len = __str.size(); auto __alloc = __str._M_get_allocator(); // If this allocation throws there are no effects: auto __ptr = _Alloc_traits::allocate(__alloc, __len + 1); _M_destroy(_M_allocated_capacity); _M_data(__ptr); _M_capacity(__len); _M_set_length(__len); } } std::__alloc_on_copy(_M_get_allocator(), __str._M_get_allocator()); } #endif return this->assign(__str); } /** * @brief Copy contents of @a s into this string. * @param __s Source null-terminated string. */ basic_string& operator=(const _CharT* __s) { return this->assign(__s); } /** * @brief Set value to string of length 1. * @param __c Source character. * * Assigning to a character makes this string length 1 and * (*this)[0] == @a c. */ basic_string& operator=(_CharT __c) { this->assign(1, __c); return *this; } #if __cplusplus >= 201103L /** * @brief Move assign the value of @a str to this string. * @param __str Source string. * * The contents of @a str are moved into this string (without copying). * @a str is a valid, but unspecified string. **/ // PR 58265, this should be noexcept. // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2063. Contradictory requirements for string move assignment basic_string& operator=(basic_string&& __str) noexcept(_Alloc_traits::_S_nothrow_move()) { if (!_M_is_local() && _Alloc_traits::_S_propagate_on_move_assign() && !_Alloc_traits::_S_always_equal() && _M_get_allocator() != __str._M_get_allocator()) { // Destroy existing storage before replacing allocator. _M_destroy(_M_allocated_capacity); _M_data(_M_local_data()); _M_set_length(0); } // Replace allocator if POCMA is true. std::__alloc_on_move(_M_get_allocator(), __str._M_get_allocator()); if (__str._M_is_local()) { // We've always got room for a short string, just copy it. if (__str.size()) this->_S_copy(_M_data(), __str._M_data(), __str.size()); _M_set_length(__str.size()); } else if (_Alloc_traits::_S_propagate_on_move_assign() || _Alloc_traits::_S_always_equal() || _M_get_allocator() == __str._M_get_allocator()) { // Just move the allocated pointer, our allocator can free it. pointer __data = nullptr; size_type __capacity; if (!_M_is_local()) { if (_Alloc_traits::_S_always_equal()) { // __str can reuse our existing storage. __data = _M_data(); __capacity = _M_allocated_capacity; } else // __str can't use it, so free it. _M_destroy(_M_allocated_capacity); } _M_data(__str._M_data()); _M_length(__str.length()); _M_capacity(__str._M_allocated_capacity); if (__data) { __str._M_data(__data); __str._M_capacity(__capacity); } else __str._M_data(__str._M_local_buf); } else // Need to do a deep copy assign(__str); __str.clear(); return *this; } /** * @brief Set value to string constructed from initializer %list. * @param __l std::initializer_list. */ basic_string& operator=(initializer_list<_CharT> __l) { this->assign(__l.begin(), __l.size()); return *this; } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value to string constructed from a string_view. * @param __svt An object convertible to string_view. */ template _If_sv<_Tp, basic_string&> operator=(const _Tp& __svt) { return this->assign(__svt); } /** * @brief Convert to a string_view. * @return A string_view. */ operator __sv_type() const noexcept { return __sv_type(data(), size()); } #endif // C++17 // Iterators: /** * Returns a read/write iterator that points to the first character in * the %string. */ iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_M_data()); } /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data()); } /** * Returns a read/write iterator that points one past the last * character in the %string. */ iterator end() _GLIBCXX_NOEXCEPT { return iterator(_M_data() + this->size()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data() + this->size()); } /** * Returns a read/write reverse iterator that points to the last * character in the %string. Iteration is done in reverse element * order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->end()); } /** * Returns a read/write reverse iterator that points to one before the * first character in the %string. Iteration is done in reverse * element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_data()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator cend() const noexcept { return const_iterator(this->_M_data() + this->size()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } #endif public: // Capacity: /// Returns the number of characters in the string, not including any /// null-termination. size_type size() const _GLIBCXX_NOEXCEPT { return _M_string_length; } /// Returns the number of characters in the string, not including any /// null-termination. size_type length() const _GLIBCXX_NOEXCEPT { return _M_string_length; } /// Returns the size() of the largest possible %string. size_type max_size() const _GLIBCXX_NOEXCEPT { return (_Alloc_traits::max_size(_M_get_allocator()) - 1) / 2; } /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * @param __c Character to fill any new elements. * * This function will %resize the %string to the specified * number of characters. If the number is smaller than the * %string's current size the %string is truncated, otherwise * the %string is extended and new elements are %set to @a __c. */ void resize(size_type __n, _CharT __c); /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * * This function will resize the %string to the specified length. If * the new size is smaller than the %string's current size the %string * is truncated, otherwise the %string is extended and new characters * are default-constructed. For basic types such as char, this means * setting them to 0. */ void resize(size_type __n) { this->resize(__n, _CharT()); } #if __cplusplus >= 201103L /// A non-binding request to reduce capacity() to size(). void shrink_to_fit() noexcept { #if __cpp_exceptions if (capacity() > size()) { try { reserve(0); } catch(...) { } } #endif } #endif /** * Returns the total number of characters that the %string can hold * before needing to allocate more memory. */ size_type capacity() const _GLIBCXX_NOEXCEPT { return _M_is_local() ? size_type(_S_local_capacity) : _M_allocated_capacity; } /** * @brief Attempt to preallocate enough memory for specified number of * characters. * @param __res_arg Number of characters required. * @throw std::length_error If @a __res_arg exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %string to hold the specified number of characters. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the string length that will be * required, the user can reserve the memory in %advance, and thus * prevent a possible reallocation of memory and copying of %string * data. */ void reserve(size_type __res_arg = 0); /** * Erases the string, making it empty. */ void clear() _GLIBCXX_NOEXCEPT { _M_set_length(0); } /** * Returns true if the %string is empty. Equivalent to * *this == "". */ bool empty() const _GLIBCXX_NOEXCEPT { return this->size() == 0; } // Element access: /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read-only (constant) reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[] (size_type __pos) const _GLIBCXX_NOEXCEPT { __glibcxx_assert(__pos <= size()); return _M_data()[__pos]; } /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read/write reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __pos) { // Allow pos == size() both in C++98 mode, as v3 extension, // and in C++11 mode. __glibcxx_assert(__pos <= size()); // In pedantic mode be strict in C++98 mode. _GLIBCXX_DEBUG_PEDASSERT(__cplusplus >= 201103L || __pos < size()); return _M_data()[__pos]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read-only (const) reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ const_reference at(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); return _M_data()[__n]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read/write reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ reference at(size_type __n) { if (__n >= size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); return _M_data()[__n]; } #if __cplusplus >= 201103L /** * Returns a read/write reference to the data at the first * element of the %string. */ reference front() noexcept { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read-only (constant) reference to the data at the first * element of the %string. */ const_reference front() const noexcept { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read/write reference to the data at the last * element of the %string. */ reference back() noexcept { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %string. */ const_reference back() const noexcept { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } #endif // Modifiers: /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& operator+=(const basic_string& __str) { return this->append(__str); } /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& operator+=(const _CharT* __s) { return this->append(__s); } /** * @brief Append a character. * @param __c The character to append. * @return Reference to this string. */ basic_string& operator+=(_CharT __c) { this->push_back(__c); return *this; } #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to be appended. * @return Reference to this string. */ basic_string& operator+=(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt An object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> operator+=(const _Tp& __svt) { return this->append(__svt); } #endif // C++17 /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& append(const basic_string& __str) { return _M_append(__str._M_data(), __str.size()); } /** * @brief Append a substring. * @param __str The string to append. * @param __pos Index of the first character of str to append. * @param __n The number of characters to append. * @return Reference to this string. * @throw std::out_of_range if @a __pos is not a valid index. * * This function appends @a __n characters from @a __str * starting at @a __pos to this string. If @a __n is is larger * than the number of available characters in @a __str, the * remainder of @a __str is appended. */ basic_string& append(const basic_string& __str, size_type __pos, size_type __n = npos) { return _M_append(__str._M_data() + __str._M_check(__pos, "basic_string::append"), __str._M_limit(__pos, __n)); } /** * @brief Append a C substring. * @param __s The C string to append. * @param __n The number of characters to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); _M_check_length(size_type(0), __n, "basic_string::append"); return _M_append(__s, __n); } /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s) { __glibcxx_requires_string(__s); const size_type __n = traits_type::length(__s); _M_check_length(size_type(0), __n, "basic_string::append"); return _M_append(__s, __n); } /** * @brief Append multiple characters. * @param __n The number of characters to append. * @param __c The character to use. * @return Reference to this string. * * Appends __n copies of __c to this string. */ basic_string& append(size_type __n, _CharT __c) { return _M_replace_aux(this->size(), size_type(0), __n, __c); } #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to append. * @return Reference to this string. */ basic_string& append(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 /** * @brief Append a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Appends characters in the range [__first,__last) to this string. */ #if __cplusplus >= 201103L template> #else template #endif basic_string& append(_InputIterator __first, _InputIterator __last) { return this->replace(end(), end(), __first, __last); } #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt An object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt) { __sv_type __sv = __svt; return this->append(__sv.data(), __sv.size()); } /** * @brief Append a range of characters from a string_view. * @param __svt An object convertible to string_view to be appended from. * @param __pos The position in the string_view to append from. * @param __n The number of characters to append from the string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return _M_append(__sv.data() + __sv._M_check(__pos, "basic_string::append"), __sv._M_limit(__pos, __n)); } #endif // C++17 /** * @brief Append a single character. * @param __c Character to append. */ void push_back(_CharT __c) { const size_type __size = this->size(); if (__size + 1 > this->capacity()) this->_M_mutate(__size, size_type(0), 0, size_type(1)); traits_type::assign(this->_M_data()[__size], __c); this->_M_set_length(__size + 1); } /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. */ basic_string& assign(const basic_string& __str) { this->_M_assign(__str); return *this; } #if __cplusplus >= 201103L /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. * * This function sets this string to the exact contents of @a __str. * @a __str is a valid, but unspecified string. */ basic_string& assign(basic_string&& __str) noexcept(_Alloc_traits::_S_nothrow_move()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2063. Contradictory requirements for string move assignment return *this = std::move(__str); } #endif // C++11 /** * @brief Set value to a substring of a string. * @param __str The string to use. * @param __pos Index of the first character of str. * @param __n Number of characters to use. * @return Reference to this string. * @throw std::out_of_range if @a pos is not a valid index. * * This function sets this string to the substring of @a __str * consisting of @a __n characters at @a __pos. If @a __n is * is larger than the number of available characters in @a * __str, the remainder of @a __str is used. */ basic_string& assign(const basic_string& __str, size_type __pos, size_type __n = npos) { return _M_replace(size_type(0), this->size(), __str._M_data() + __str._M_check(__pos, "basic_string::assign"), __str._M_limit(__pos, __n)); } /** * @brief Set value to a C substring. * @param __s The C string to use. * @param __n Number of characters to use. * @return Reference to this string. * * This function sets the value of this string to the first @a __n * characters of @a __s. If @a __n is is larger than the number of * available characters in @a __s, the remainder of @a __s is used. */ basic_string& assign(const _CharT* __s, size_type __n) { __glibcxx_requires_string_len(__s, __n); return _M_replace(size_type(0), this->size(), __s, __n); } /** * @brief Set value to contents of a C string. * @param __s The C string to use. * @return Reference to this string. * * This function sets the value of this string to the value of @a __s. * The data is copied, so there is no dependence on @a __s once the * function returns. */ basic_string& assign(const _CharT* __s) { __glibcxx_requires_string(__s); return _M_replace(size_type(0), this->size(), __s, traits_type::length(__s)); } /** * @brief Set value to multiple characters. * @param __n Length of the resulting string. * @param __c The character to use. * @return Reference to this string. * * This function sets the value of this string to @a __n copies of * character @a __c. */ basic_string& assign(size_type __n, _CharT __c) { return _M_replace_aux(size_type(0), this->size(), __n, __c); } /** * @brief Set value to a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Sets value of string to characters in the range [__first,__last). */ #if __cplusplus >= 201103L template> #else template #endif basic_string& assign(_InputIterator __first, _InputIterator __last) { return this->replace(begin(), end(), __first, __last); } #if __cplusplus >= 201103L /** * @brief Set value to an initializer_list of characters. * @param __l The initializer_list of characters to assign. * @return Reference to this string. */ basic_string& assign(initializer_list<_CharT> __l) { return this->assign(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value from a string_view. * @param __svt The source object convertible to string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt) { __sv_type __sv = __svt; return this->assign(__sv.data(), __sv.size()); } /** * @brief Set value from a range of characters in a string_view. * @param __svt The source object convertible to string_view. * @param __pos The position in the string_view to assign from. * @param __n The number of characters to assign. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return _M_replace(size_type(0), this->size(), __sv.data() + __sv._M_check(__pos, "basic_string::assign"), __sv._M_limit(__pos, __n)); } #endif // C++17 #if __cplusplus >= 201103L /** * @brief Insert multiple characters. * @param __p Const_iterator referencing location in string to * insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @return Iterator referencing the first inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts @a __n copies of character @a __c starting at the * position referenced by iterator @a __p. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ iterator insert(const_iterator __p, size_type __n, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); const size_type __pos = __p - begin(); this->replace(__p, __p, __n, __c); return iterator(this->_M_data() + __pos); } #else /** * @brief Insert multiple characters. * @param __p Iterator referencing location in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts @a __n copies of character @a __c starting at the * position referenced by iterator @a __p. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ void insert(iterator __p, size_type __n, _CharT __c) { this->replace(__p, __p, __n, __c); } #endif #if __cplusplus >= 201103L /** * @brief Insert a range of characters. * @param __p Const_iterator referencing location in string to * insert at. * @param __beg Start of range. * @param __end End of range. * @return Iterator referencing the first inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts characters in range [beg,end). If adding characters * causes the length to exceed max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ template> iterator insert(const_iterator __p, _InputIterator __beg, _InputIterator __end) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); const size_type __pos = __p - begin(); this->replace(__p, __p, __beg, __end); return iterator(this->_M_data() + __pos); } #else /** * @brief Insert a range of characters. * @param __p Iterator referencing location in string to insert at. * @param __beg Start of range. * @param __end End of range. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts characters in range [__beg,__end). If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ template void insert(iterator __p, _InputIterator __beg, _InputIterator __end) { this->replace(__p, __p, __beg, __end); } #endif #if __cplusplus >= 201103L /** * @brief Insert an initializer_list of characters. * @param __p Iterator referencing location in string to insert at. * @param __l The initializer_list of characters to insert. * @throw std::length_error If new length exceeds @c max_size(). */ void insert(iterator __p, initializer_list<_CharT> __l) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); this->insert(__p - begin(), __l.begin(), __l.size()); } #endif // C++11 /** * @brief Insert value of a string. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts value of @a __str starting at @a __pos1. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str) { return this->replace(__pos1, size_type(0), __str._M_data(), __str.size()); } /** * @brief Insert a substring. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @param __pos2 Start of characters in str to insert. * @param __n Number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos1 > size() or * @a __pos2 > @a str.size(). * * Starting at @a pos1, insert @a __n character of @a __str * beginning with @a __pos2. If adding characters causes the * length to exceed max_size(), length_error is thrown. If @a * __pos1 is beyond the end of this string or @a __pos2 is * beyond the end of @a __str, out_of_range is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n = npos) { return this->replace(__pos1, size_type(0), __str._M_data() + __str._M_check(__pos2, "basic_string::insert"), __str._M_limit(__pos2, __n)); } /** * @brief Insert a C substring. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @param __n The number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts the first @a __n characters of @a __s starting at @a * __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos is beyond * end(), out_of_range is thrown. The value of the string * doesn't change if an error is thrown. */ basic_string& insert(size_type __pos, const _CharT* __s, size_type __n) { return this->replace(__pos, size_type(0), __s, __n); } /** * @brief Insert a C string. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Inserts the first @a n characters of @a __s starting at @a __pos. If * adding characters causes the length to exceed max_size(), * length_error is thrown. If @a __pos is beyond end(), out_of_range is * thrown. The value of the string doesn't change if an error is * thrown. */ basic_string& insert(size_type __pos, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__pos, size_type(0), __s, traits_type::length(__s)); } /** * @brief Insert multiple characters. * @param __pos Index in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts @a __n copies of character @a __c starting at index * @a __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos > length(), * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos, size_type __n, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::insert"), size_type(0), __n, __c); } /** * @brief Insert one character. * @param __p Iterator referencing position in string to insert at. * @param __c The character to insert. * @return Iterator referencing newly inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts character @a __c at position referenced by @a __p. * If adding character causes the length to exceed max_size(), * length_error is thrown. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ iterator insert(__const_iterator __p, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(__p >= begin() && __p <= end()); const size_type __pos = __p - begin(); _M_replace_aux(__pos, size_type(0), size_type(1), __c); return iterator(_M_data() + __pos); } #if __cplusplus > 201402L /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos, const _Tp& __svt) { __sv_type __sv = __svt; return this->insert(__pos, __sv.data(), __sv.size()); } /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert from. * @param __pos Iterator referencing position in string_view to insert * from. * @param __n The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos1, const _Tp& __svt, size_type __pos2, size_type __n = npos) { __sv_type __sv = __svt; return this->replace(__pos1, size_type(0), __sv.data() + __sv._M_check(__pos2, "basic_string::insert"), __sv._M_limit(__pos2, __n)); } #endif // C++17 /** * @brief Remove characters. * @param __pos Index of first character to remove (default 0). * @param __n Number of characters to remove (default remainder). * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Removes @a __n characters from this string starting at @a * __pos. The length of the string is reduced by @a __n. If * there are < @a __n characters to remove, the remainder of * the string is truncated. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& erase(size_type __pos = 0, size_type __n = npos) { _M_check(__pos, "basic_string::erase"); if (__n == npos) this->_M_set_length(__pos); else if (__n != 0) this->_M_erase(__pos, _M_limit(__pos, __n)); return *this; } /** * @brief Remove one character. * @param __position Iterator referencing the character to remove. * @return iterator referencing same location after removal. * * Removes the character at @a __position from this string. The value * of the string doesn't change if an error is thrown. */ iterator erase(__const_iterator __position) { _GLIBCXX_DEBUG_PEDASSERT(__position >= begin() && __position < end()); const size_type __pos = __position - begin(); this->_M_erase(__pos, size_type(1)); return iterator(_M_data() + __pos); } /** * @brief Remove a range of characters. * @param __first Iterator referencing the first character to remove. * @param __last Iterator referencing the end of the range. * @return Iterator referencing location of first after removal. * * Removes the characters in the range [first,last) from this string. * The value of the string doesn't change if an error is thrown. */ iterator erase(__const_iterator __first, __const_iterator __last) { _GLIBCXX_DEBUG_PEDASSERT(__first >= begin() && __first <= __last && __last <= end()); const size_type __pos = __first - begin(); if (__last == end()) this->_M_set_length(__pos); else this->_M_erase(__pos, __last - __first); return iterator(this->_M_data() + __pos); } #if __cplusplus >= 201103L /** * @brief Remove the last character. * * The string must be non-empty. */ void pop_back() noexcept { __glibcxx_assert(!empty()); _M_erase(size() - 1, 1); } #endif // C++11 /** * @brief Replace characters with value from another string. * @param __pos Index of first character to replace. * @param __n Number of characters to be replaced. * @param __str String to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos+__n) from * this string. In place, the value of @a __str is inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of the result exceeds max_size(), length_error * is thrown. The value of the string doesn't change if an * error is thrown. */ basic_string& replace(size_type __pos, size_type __n, const basic_string& __str) { return this->replace(__pos, __n, __str._M_data(), __str.size()); } /** * @brief Replace characters with value from another string. * @param __pos1 Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __str String to insert. * @param __pos2 Index of first character of str to use. * @param __n2 Number of characters from str to use. * @return Reference to this string. * @throw std::out_of_range If @a __pos1 > size() or @a __pos2 > * __str.size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos1,__pos1 + n) from this * string. In place, the value of @a __str is inserted. If @a __pos is * beyond end of string, out_of_range is thrown. If the length of the * result exceeds max_size(), length_error is thrown. The value of the * string doesn't change if an error is thrown. */ basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) { return this->replace(__pos1, __n1, __str._M_data() + __str._M_check(__pos2, "basic_string::replace"), __str._M_limit(__pos2, __n2)); } /** * @brief Replace characters with value of a C substring. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @param __n2 Number of characters from @a s to use. * @return Reference to this string. * @throw std::out_of_range If @a pos1 > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the first @a __n2 characters of * @a __s are inserted, or all of @a __s if @a __n2 is too large. If * @a __pos is beyond end of string, out_of_range is thrown. If * the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) { __glibcxx_requires_string_len(__s, __n2); return _M_replace(_M_check(__pos, "basic_string::replace"), _M_limit(__pos, __n1), __s, __n2); } /** * @brief Replace characters with value of a C string. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the characters of @a __s are * inserted. If @a __pos is beyond end of string, out_of_range * is thrown. If the length of result exceeds max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__pos, __n1, __s, traits_type::length(__s)); } /** * @brief Replace characters with multiple characters. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __n2 Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::out_of_range If @a __pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [pos,pos + n1) from this * string. In place, @a __n2 copies of @a __c are inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::replace"), _M_limit(__pos, __n1), __n2, __c); } /** * @brief Replace range of characters with string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __str String value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the value of @a __str is inserted. If the length of result * exceeds max_size(), length_error is thrown. The value of * the string doesn't change if an error is thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, const basic_string& __str) { return this->replace(__i1, __i2, __str._M_data(), __str.size()); } /** * @brief Replace range of characters with C substring. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @param __n Number of characters from s to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the first @a __n characters of @a __s are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __s, size_type __n) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); return this->replace(__i1 - begin(), __i2 - __i1, __s, __n); } /** * @brief Replace range of characters with C string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the characters of @a __s are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__i1, __i2, __s, traits_type::length(__s)); } /** * @brief Replace range of characters with multiple characters * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __n Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * @a __n copies of @a __c are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(__const_iterator __i1, __const_iterator __i2, size_type __n, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); return _M_replace_aux(__i1 - begin(), __i2 - __i1, __n, __c); } /** * @brief Replace range of characters with range. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __k1 Iterator referencing start of range to insert. * @param __k2 Iterator referencing end of range to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ #if __cplusplus >= 201103L template> basic_string& replace(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->_M_replace_dispatch(__i1, __i2, __k1, __k2, std::__false_type()); } #else template #ifdef _GLIBCXX_DISAMBIGUATE_REPLACE_INST typename __enable_if_not_native_iterator<_InputIterator>::__type #else basic_string& #endif replace(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); typedef typename std::__is_integer<_InputIterator>::__type _Integral; return _M_replace_dispatch(__i1, __i2, __k1, __k2, _Integral()); } #endif // Specializations for the common case of pointer and iterator: // useful to avoid the overhead of temporary buffering in _M_replace. basic_string& replace(__const_iterator __i1, __const_iterator __i2, _CharT* __k1, _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(__const_iterator __i1, __const_iterator __i2, const _CharT* __k1, const _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(__const_iterator __i1, __const_iterator __i2, iterator __k1, iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1.base(), __k2 - __k1); } basic_string& replace(__const_iterator __i1, __const_iterator __i2, const_iterator __k1, const_iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(begin() <= __i1 && __i1 <= __i2 && __i2 <= end()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - begin(), __i2 - __i1, __k1.base(), __k2 - __k1); } #if __cplusplus >= 201103L /** * @brief Replace range of characters with initializer_list. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __l The initializer_list of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(const_iterator __i1, const_iterator __i2, initializer_list<_CharT> __l) { return this->replace(__i1, __i2, __l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Replace range of characters with string_view. * @param __pos The position to replace at. * @param __n The number of characters to replace. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos, size_type __n, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__pos, __n, __sv.data(), __sv.size()); } /** * @brief Replace range of characters with string_view. * @param __pos1 The position to replace at. * @param __n1 The number of characters to replace. * @param __svt The object convertible to string_view to insert from. * @param __pos2 The position in the string_view to insert from. * @param __n2 The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) { __sv_type __sv = __svt; return this->replace(__pos1, __n1, __sv.data() + __sv._M_check(__pos2, "basic_string::replace"), __sv._M_limit(__pos2, __n2)); } /** * @brief Replace range of characters with string_view. * @param __i1 An iterator referencing the start position to replace at. * @param __i2 An iterator referencing the end position for the replace. * @param __svt The object convertible to string_view to insert from. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(const_iterator __i1, const_iterator __i2, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__i1 - begin(), __i2 - __i1, __sv); } #endif // C++17 private: template basic_string& _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _Integer __n, _Integer __val, __true_type) { return _M_replace_aux(__i1 - begin(), __i2 - __i1, __n, __val); } template basic_string& _M_replace_dispatch(const_iterator __i1, const_iterator __i2, _InputIterator __k1, _InputIterator __k2, __false_type); basic_string& _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c); basic_string& _M_replace(size_type __pos, size_type __len1, const _CharT* __s, const size_type __len2); basic_string& _M_append(const _CharT* __s, size_type __n); public: /** * @brief Copy substring into C string. * @param __s C string to copy value into. * @param __n Number of characters to copy. * @param __pos Index of first character to copy. * @return Number of characters actually copied * @throw std::out_of_range If __pos > size(). * * Copies up to @a __n characters starting at @a __pos into the * C string @a __s. If @a __pos is %greater than size(), * out_of_range is thrown. */ size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const; /** * @brief Swap contents with another string. * @param __s String to swap with. * * Exchanges the contents of this string with that of @a __s in constant * time. */ void swap(basic_string& __s) _GLIBCXX_NOEXCEPT; // String operations: /** * @brief Return const pointer to null-terminated contents. * * This is a handle to internal data. Do not modify or dire things may * happen. */ const _CharT* c_str() const _GLIBCXX_NOEXCEPT { return _M_data(); } /** * @brief Return const pointer to contents. * * This is a pointer to internal data. It is undefined to modify * the contents through the returned pointer. To get a pointer that * allows modifying the contents use @c &str[0] instead, * (or in C++17 the non-const @c str.data() overload). */ const _CharT* data() const _GLIBCXX_NOEXCEPT { return _M_data(); } #if __cplusplus > 201402L /** * @brief Return non-const pointer to contents. * * This is a pointer to the character sequence held by the string. * Modifying the characters in the sequence is allowed. */ _CharT* data() noexcept { return _M_data(); } #endif /** * @brief Return copy of allocator used to construct this string. */ allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return _M_get_allocator(); } /** * @brief Find position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search from. * @param __n Number of characters from @a s to search for. * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type find(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a string. * @param __str String to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for value of @a __str within * this string. If found, returns the index where it begins. If not * found, returns npos. */ size_type find(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. */ template _If_sv<_Tp, size_type> find(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a C string. * @param __s C string to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the value of @a * __s within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type find(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a string. * @param __str String to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for value of @a * __str within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type rfind(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find last position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. */ template _If_sv<_Tp, size_type> rfind(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->rfind(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a C string. * @param __s C string to locate. * @param __pos Index of character to start search at (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the value of * @a __s within this string. If found, returns the index * where it begins. If not found, returns npos. */ size_type rfind(const _CharT* __s, size_type __pos = npos) const { __glibcxx_requires_string(__s); return this->rfind(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type rfind(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find position of a character of a string_view. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character of C substring. * @param __s String containing characters to locate. * @param __pos Index of character to search from. * @param __n Number of characters from s to search for. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character of C string. * @param __s String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for the character * @a __c within this string. If found, returns the index * where it was found. If not found, returns npos. * * Note: equivalent to find(__c, __pos). */ size_type find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__c, __pos); } /** * @brief Find last position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find last position of a character of string. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character of C substring. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character of C string. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. * * Note: equivalent to rfind(__c, __pos). */ size_type find_last_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__c, __pos); } /** * @brief Find position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not contained * in @a __str within this string. If found, returns the index where it * was found. If not found, returns npos. */ size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_not_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find position of a character not in a string_view. * @param __svt A object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_not_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from. * @param __n Number of characters from __s to consider. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in the first @a __n characters of @a __s within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character * other than @a __c within this string. If found, returns the * index where it was found. If not found, returns npos. */ size_type find_first_not_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_not_of(__str.data(), __pos, __str.size()); } #if __cplusplus > 201402L /** * @brief Find last position of a character not in a string_view. * @param __svt An object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_not_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from. * @param __n Number of characters from s to consider. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character not * contained in the first @a __n characters of @a __s within this string. * If found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __s within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character other than * @a __c within this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_last_not_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; /** * @brief Get a substring. * @param __pos Index of first character (default 0). * @param __n Number of characters in substring (default remainder). * @return The new string. * @throw std::out_of_range If __pos > size(). * * Construct and return a new string using the @a __n * characters starting at @a __pos. If the string is too * short, use the remainder of the characters. If @a __pos is * beyond the end of the string, out_of_range is thrown. */ basic_string substr(size_type __pos = 0, size_type __n = npos) const { return basic_string(*this, _M_check(__pos, "basic_string::substr"), __n); } /** * @brief Compare to a string. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a * __str, 0 if their values are equivalent, or > 0 if this * string is ordered after @a __str. Determines the effective * length rlen of the strings to compare as the smallest of * size() and str.size(). The function then compares the two * strings by calling traits::compare(data(), str.data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(const basic_string& __str) const { const size_type __size = this->size(); const size_type __osize = __str.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __str.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } #if __cplusplus > 201402L /** * @brief Compare to a string_view. * @param __svt An object convertible to string_view to compare against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; const size_type __size = this->size(); const size_type __osize = __sv.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __sv.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } /** * @brief Compare to a string_view. * @param __pos A position in the string to start comparing from. * @param __n The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos, size_type __n, const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this).substr(__pos, __n).compare(__sv); } /** * @brief Compare to a string_view. * @param __pos1 A position in the string to start comparing from. * @param __n1 The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @param __pos2 A position in the string_view to start comparing from. * @param __n2 The number of characters to compare. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this) .substr(__pos1, __n1).compare(__sv.substr(__pos2, __n2)); } #endif // C++17 /** * @brief Compare substring to a string. * @param __pos Index of first character of substring. * @param __n Number of characters in substring. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n characters * starting at @a __pos. Returns an integer < 0 if the * substring is ordered before @a __str, 0 if their values are * equivalent, or > 0 if the substring is ordered after @a * __str. Determines the effective length rlen of the strings * to compare as the smallest of the length of the substring * and @a __str.size(). The function then compares the two * strings by calling * traits::compare(substring.data(),str.data(),rlen). If the * result of the comparison is nonzero returns it, otherwise * the shorter one is ordered first. */ int compare(size_type __pos, size_type __n, const basic_string& __str) const; /** * @brief Compare substring to a substring. * @param __pos1 Index of first character of substring. * @param __n1 Number of characters in substring. * @param __str String to compare against. * @param __pos2 Index of first character of substring of str. * @param __n2 Number of characters in substring of str. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos1. Form the substring of @a * __str from the @a __n2 characters starting at @a __pos2. * Returns an integer < 0 if this substring is ordered before * the substring of @a __str, 0 if their values are equivalent, * or > 0 if this substring is ordered after the substring of * @a __str. Determines the effective length rlen of the * strings to compare as the smallest of the lengths of the * substrings. The function then compares the two strings by * calling * traits::compare(substring.data(),str.substr(pos2,n2).data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) const; /** * @brief Compare to a C string. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a __s, 0 if * their values are equivalent, or > 0 if this string is ordered after * @a __s. Determines the effective length rlen of the strings to * compare as the smallest of size() and the length of a string * constructed from @a __s. The function then compares the two strings * by calling traits::compare(data(),s,rlen). If the result of the * comparison is nonzero returns it, otherwise the shorter one is * ordered first. */ int compare(const _CharT* __s) const _GLIBCXX_NOEXCEPT; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5 String::compare specification questionable /** * @brief Compare substring to a C string. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a pos. Returns an integer < 0 if * the substring is ordered before @a __s, 0 if their values * are equivalent, or > 0 if the substring is ordered after @a * __s. Determines the effective length rlen of the strings to * compare as the smallest of the length of the substring and * the length of a string constructed from @a __s. The * function then compares the two string by calling * traits::compare(substring.data(),__s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. */ int compare(size_type __pos, size_type __n1, const _CharT* __s) const; /** * @brief Compare substring against a character %array. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s character %array to compare against. * @param __n2 Number of characters of s. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos. Form a string from the * first @a __n2 characters of @a __s. Returns an integer < 0 * if this substring is ordered before the string from @a __s, * 0 if their values are equivalent, or > 0 if this substring * is ordered after the string from @a __s. Determines the * effective length rlen of the strings to compare as the * smallest of the length of the substring and @a __n2. The * function then compares the two strings by calling * traits::compare(substring.data(),s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. * * NB: s must have at least n2 characters, '\\0' has * no special meaning. */ int compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const; // Allow basic_stringbuf::__xfer_bufptrs to call _M_length: template friend class basic_stringbuf; }; _GLIBCXX_END_NAMESPACE_CXX11 #else // !_GLIBCXX_USE_CXX11_ABI // Reference-counted COW string implentation /** * @class basic_string basic_string.h * @brief Managing sequences of characters and character-like objects. * * @ingroup strings * @ingroup sequences * * @tparam _CharT Type of character * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * @tparam _Alloc Allocator type, defaults to allocator<_CharT>. * * Meets the requirements of a container, a * reversible container, and a * sequence. Of the * optional sequence requirements, only * @c push_back, @c at, and @c %array access are supported. * * @doctodo * * * Documentation? What's that? * Nathan Myers . * * A string looks like this: * * @code * [_Rep] * _M_length * [basic_string] _M_capacity * _M_dataplus _M_refcount * _M_p ----------------> unnamed array of char_type * @endcode * * Where the _M_p points to the first character in the string, and * you cast it to a pointer-to-_Rep and subtract 1 to get a * pointer to the header. * * This approach has the enormous advantage that a string object * requires only one allocation. All the ugliness is confined * within a single %pair of inline functions, which each compile to * a single @a add instruction: _Rep::_M_data(), and * string::_M_rep(); and the allocation function which gets a * block of raw bytes and with room enough and constructs a _Rep * object at the front. * * The reason you want _M_data pointing to the character %array and * not the _Rep is so that the debugger can see the string * contents. (Probably we should add a non-inline member to get * the _Rep for the debugger to use, so users can check the actual * string length.) * * Note that the _Rep object is a POD so that you can have a * static empty string _Rep object already @a constructed before * static constructors have run. The reference-count encoding is * chosen so that a 0 indicates one reference, so you never try to * destroy the empty-string _Rep object. * * All but the last paragraph is considered pretty conventional * for a C++ string implementation. */ // 21.3 Template class basic_string template class basic_string { typedef typename _Alloc::template rebind<_CharT>::other _CharT_alloc_type; // Types: public: typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef _Alloc allocator_type; typedef typename _CharT_alloc_type::size_type size_type; typedef typename _CharT_alloc_type::difference_type difference_type; typedef typename _CharT_alloc_type::reference reference; typedef typename _CharT_alloc_type::const_reference const_reference; typedef typename _CharT_alloc_type::pointer pointer; typedef typename _CharT_alloc_type::const_pointer const_pointer; typedef __gnu_cxx::__normal_iterator iterator; typedef __gnu_cxx::__normal_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; private: // _Rep: string representation // Invariants: // 1. String really contains _M_length + 1 characters: due to 21.3.4 // must be kept null-terminated. // 2. _M_capacity >= _M_length // Allocated memory is always (_M_capacity + 1) * sizeof(_CharT). // 3. _M_refcount has three states: // -1: leaked, one reference, no ref-copies allowed, non-const. // 0: one reference, non-const. // n>0: n + 1 references, operations require a lock, const. // 4. All fields==0 is an empty string, given the extra storage // beyond-the-end for a null terminator; thus, the shared // empty string representation needs no constructor. struct _Rep_base { size_type _M_length; size_type _M_capacity; _Atomic_word _M_refcount; }; struct _Rep : _Rep_base { // Types: typedef typename _Alloc::template rebind::other _Raw_bytes_alloc; // (Public) Data members: // The maximum number of individual char_type elements of an // individual string is determined by _S_max_size. This is the // value that will be returned by max_size(). (Whereas npos // is the maximum number of bytes the allocator can allocate.) // If one was to divvy up the theoretical largest size string, // with a terminating character and m _CharT elements, it'd // look like this: // npos = sizeof(_Rep) + (m * sizeof(_CharT)) + sizeof(_CharT) // Solving for m: // m = ((npos - sizeof(_Rep))/sizeof(CharT)) - 1 // In addition, this implementation quarters this amount. static const size_type _S_max_size; static const _CharT _S_terminal; // The following storage is init'd to 0 by the linker, resulting // (carefully) in an empty string with one reference. static size_type _S_empty_rep_storage[]; static _Rep& _S_empty_rep() _GLIBCXX_NOEXCEPT { // NB: Mild hack to avoid strict-aliasing warnings. Note that // _S_empty_rep_storage is never modified and the punning should // be reasonably safe in this case. void* __p = reinterpret_cast(&_S_empty_rep_storage); return *reinterpret_cast<_Rep*>(__p); } bool _M_is_leaked() const _GLIBCXX_NOEXCEPT { #if defined(__GTHREADS) // _M_refcount is mutated concurrently by _M_refcopy/_M_dispose, // so we need to use an atomic load. However, _M_is_leaked // predicate does not change concurrently (i.e. the string is either // leaked or not), so a relaxed load is enough. return __atomic_load_n(&this->_M_refcount, __ATOMIC_RELAXED) < 0; #else return this->_M_refcount < 0; #endif } bool _M_is_shared() const _GLIBCXX_NOEXCEPT { #if defined(__GTHREADS) // _M_refcount is mutated concurrently by _M_refcopy/_M_dispose, // so we need to use an atomic load. Another thread can drop last // but one reference concurrently with this check, so we need this // load to be acquire to synchronize with release fetch_and_add in // _M_dispose. return __atomic_load_n(&this->_M_refcount, __ATOMIC_ACQUIRE) > 0; #else return this->_M_refcount > 0; #endif } void _M_set_leaked() _GLIBCXX_NOEXCEPT { this->_M_refcount = -1; } void _M_set_sharable() _GLIBCXX_NOEXCEPT { this->_M_refcount = 0; } void _M_set_length_and_sharable(size_type __n) _GLIBCXX_NOEXCEPT { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__builtin_expect(this != &_S_empty_rep(), false)) #endif { this->_M_set_sharable(); // One reference. this->_M_length = __n; traits_type::assign(this->_M_refdata()[__n], _S_terminal); // grrr. (per 21.3.4) // You cannot leave those LWG people alone for a second. } } _CharT* _M_refdata() throw() { return reinterpret_cast<_CharT*>(this + 1); } _CharT* _M_grab(const _Alloc& __alloc1, const _Alloc& __alloc2) { return (!_M_is_leaked() && __alloc1 == __alloc2) ? _M_refcopy() : _M_clone(__alloc1); } // Create & Destroy static _Rep* _S_create(size_type, size_type, const _Alloc&); void _M_dispose(const _Alloc& __a) _GLIBCXX_NOEXCEPT { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__builtin_expect(this != &_S_empty_rep(), false)) #endif { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&this->_M_refcount); // Decrement of _M_refcount is acq_rel, because: // - all but last decrements need to release to synchronize with // the last decrement that will delete the object. // - the last decrement needs to acquire to synchronize with // all the previous decrements. // - last but one decrement needs to release to synchronize with // the acquire load in _M_is_shared that will conclude that // the object is not shared anymore. if (__gnu_cxx::__exchange_and_add_dispatch(&this->_M_refcount, -1) <= 0) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&this->_M_refcount); _M_destroy(__a); } } } // XXX MT void _M_destroy(const _Alloc&) throw(); _CharT* _M_refcopy() throw() { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 if (__builtin_expect(this != &_S_empty_rep(), false)) #endif __gnu_cxx::__atomic_add_dispatch(&this->_M_refcount, 1); return _M_refdata(); } // XXX MT _CharT* _M_clone(const _Alloc&, size_type __res = 0); }; // Use empty-base optimization: http://www.cantrip.org/emptyopt.html struct _Alloc_hider : _Alloc { _Alloc_hider(_CharT* __dat, const _Alloc& __a) _GLIBCXX_NOEXCEPT : _Alloc(__a), _M_p(__dat) { } _CharT* _M_p; // The actual data. }; public: // Data Members (public): // NB: This is an unsigned type, and thus represents the maximum // size that the allocator can hold. /// Value returned by various member functions when they fail. static const size_type npos = static_cast(-1); private: // Data Members (private): mutable _Alloc_hider _M_dataplus; _CharT* _M_data() const _GLIBCXX_NOEXCEPT { return _M_dataplus._M_p; } _CharT* _M_data(_CharT* __p) _GLIBCXX_NOEXCEPT { return (_M_dataplus._M_p = __p); } _Rep* _M_rep() const _GLIBCXX_NOEXCEPT { return &((reinterpret_cast<_Rep*> (_M_data()))[-1]); } // For the internal use we have functions similar to `begin'/`end' // but they do not call _M_leak. iterator _M_ibegin() const _GLIBCXX_NOEXCEPT { return iterator(_M_data()); } iterator _M_iend() const _GLIBCXX_NOEXCEPT { return iterator(_M_data() + this->size()); } void _M_leak() // for use in begin() & non-const op[] { if (!_M_rep()->_M_is_leaked()) _M_leak_hard(); } size_type _M_check(size_type __pos, const char* __s) const { if (__pos > this->size()) __throw_out_of_range_fmt(__N("%s: __pos (which is %zu) > " "this->size() (which is %zu)"), __s, __pos, this->size()); return __pos; } void _M_check_length(size_type __n1, size_type __n2, const char* __s) const { if (this->max_size() - (this->size() - __n1) < __n2) __throw_length_error(__N(__s)); } // NB: _M_limit doesn't check for a bad __pos value. size_type _M_limit(size_type __pos, size_type __off) const _GLIBCXX_NOEXCEPT { const bool __testoff = __off < this->size() - __pos; return __testoff ? __off : this->size() - __pos; } // True if _Rep and source do not overlap. bool _M_disjunct(const _CharT* __s) const _GLIBCXX_NOEXCEPT { return (less()(__s, _M_data()) || less()(_M_data() + this->size(), __s)); } // When __n = 1 way faster than the general multichar // traits_type::copy/move/assign. static void _M_copy(_CharT* __d, const _CharT* __s, size_type __n) _GLIBCXX_NOEXCEPT { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::copy(__d, __s, __n); } static void _M_move(_CharT* __d, const _CharT* __s, size_type __n) _GLIBCXX_NOEXCEPT { if (__n == 1) traits_type::assign(*__d, *__s); else traits_type::move(__d, __s, __n); } static void _M_assign(_CharT* __d, size_type __n, _CharT __c) _GLIBCXX_NOEXCEPT { if (__n == 1) traits_type::assign(*__d, __c); else traits_type::assign(__d, __n, __c); } // _S_copy_chars is a separate template to permit specialization // to optimize for the common case of pointers as iterators. template static void _S_copy_chars(_CharT* __p, _Iterator __k1, _Iterator __k2) { for (; __k1 != __k2; ++__k1, (void)++__p) traits_type::assign(*__p, *__k1); // These types are off. } static void _S_copy_chars(_CharT* __p, iterator __k1, iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, const_iterator __k1, const_iterator __k2) _GLIBCXX_NOEXCEPT { _S_copy_chars(__p, __k1.base(), __k2.base()); } static void _S_copy_chars(_CharT* __p, _CharT* __k1, _CharT* __k2) _GLIBCXX_NOEXCEPT { _M_copy(__p, __k1, __k2 - __k1); } static void _S_copy_chars(_CharT* __p, const _CharT* __k1, const _CharT* __k2) _GLIBCXX_NOEXCEPT { _M_copy(__p, __k1, __k2 - __k1); } static int _S_compare(size_type __n1, size_type __n2) _GLIBCXX_NOEXCEPT { const difference_type __d = difference_type(__n1 - __n2); if (__d > __gnu_cxx::__numeric_traits::__max) return __gnu_cxx::__numeric_traits::__max; else if (__d < __gnu_cxx::__numeric_traits::__min) return __gnu_cxx::__numeric_traits::__min; else return int(__d); } void _M_mutate(size_type __pos, size_type __len1, size_type __len2); void _M_leak_hard(); static _Rep& _S_empty_rep() _GLIBCXX_NOEXCEPT { return _Rep::_S_empty_rep(); } #if __cplusplus > 201402L // A helper type for avoiding boiler-plate. typedef basic_string_view<_CharT, _Traits> __sv_type; template using _If_sv = enable_if_t< __and_, __not_>, __not_>>::value, _Res>; // Allows an implicit conversion to __sv_type. static __sv_type _S_to_string_view(__sv_type __svt) noexcept { return __svt; } // Wraps a string_view by explicit conversion and thus // allows to add an internal constructor that does not // participate in overload resolution when a string_view // is provided. struct __sv_wrapper { explicit __sv_wrapper(__sv_type __sv) noexcept : _M_sv(__sv) { } __sv_type _M_sv; }; #endif public: // Construct/copy/destroy: // NB: We overload ctors in some cases instead of using default // arguments, per 17.4.4.4 para. 2 item 2. /** * @brief Default constructor creates an empty string. */ basic_string() #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 : _M_dataplus(_S_empty_rep()._M_refdata(), _Alloc()) { } #else : _M_dataplus(_S_construct(size_type(), _CharT(), _Alloc()), _Alloc()){ } #endif /** * @brief Construct an empty string using allocator @a a. */ explicit basic_string(const _Alloc& __a); // NB: per LWG issue 42, semantics different from IS: /** * @brief Construct string with copy of value of @a str. * @param __str Source string. */ basic_string(const basic_string& __str); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2583. no way to supply an allocator for basic_string(str, pos) /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, const _Alloc& __a = _Alloc()); /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. */ basic_string(const basic_string& __str, size_type __pos, size_type __n); /** * @brief Construct string as copy of a substring. * @param __str Source string. * @param __pos Index of first character to copy from. * @param __n Number of characters to copy. * @param __a Allocator to use. */ basic_string(const basic_string& __str, size_type __pos, size_type __n, const _Alloc& __a); /** * @brief Construct string initialized by a character %array. * @param __s Source character %array. * @param __n Number of characters to copy. * @param __a Allocator to use (default is default allocator). * * NB: @a __s must have at least @a __n characters, '\\0' * has no special meaning. */ basic_string(const _CharT* __s, size_type __n, const _Alloc& __a = _Alloc()); /** * @brief Construct string as copy of a C string. * @param __s Source C string. * @param __a Allocator to use (default is default allocator). */ basic_string(const _CharT* __s, const _Alloc& __a = _Alloc()); /** * @brief Construct string as multiple characters. * @param __n Number of characters. * @param __c Character to use. * @param __a Allocator to use (default is default allocator). */ basic_string(size_type __n, _CharT __c, const _Alloc& __a = _Alloc()); #if __cplusplus >= 201103L /** * @brief Move construct string. * @param __str Source string. * * The newly-created string contains the exact contents of @a __str. * @a __str is a valid, but unspecified string. **/ basic_string(basic_string&& __str) #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 noexcept // FIXME C++11: should always be noexcept. #endif : _M_dataplus(__str._M_dataplus) { #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 __str._M_data(_S_empty_rep()._M_refdata()); #else __str._M_data(_S_construct(size_type(), _CharT(), get_allocator())); #endif } /** * @brief Construct string from an initializer %list. * @param __l std::initializer_list of characters. * @param __a Allocator to use (default is default allocator). */ basic_string(initializer_list<_CharT> __l, const _Alloc& __a = _Alloc()); #endif // C++11 /** * @brief Construct string as copy of a range. * @param __beg Start of range. * @param __end End of range. * @param __a Allocator to use (default is default allocator). */ template basic_string(_InputIterator __beg, _InputIterator __end, const _Alloc& __a = _Alloc()); #if __cplusplus > 201402L /** * @brief Construct string from a substring of a string_view. * @param __t Source object convertible to string view. * @param __pos The index of the first character to copy from __t. * @param __n The number of characters to copy from __t. * @param __a Allocator to use. */ template> basic_string(const _Tp& __t, size_type __pos, size_type __n, const _Alloc& __a = _Alloc()) : basic_string(_S_to_string_view(__t).substr(__pos, __n), __a) { } /** * @brief Construct string from a string_view. * @param __t Source object convertible to string view. * @param __a Allocator to use (default is default allocator). */ template> explicit basic_string(const _Tp& __t, const _Alloc& __a = _Alloc()) : basic_string(__sv_wrapper(_S_to_string_view(__t)), __a) { } /** * @brief Only internally used: Construct string from a string view * wrapper. * @param __svw string view wrapper. * @param __a Allocator to use. */ explicit basic_string(__sv_wrapper __svw, const _Alloc& __a) : basic_string(__svw._M_sv.data(), __svw._M_sv.size(), __a) { } #endif // C++17 /** * @brief Destroy the string instance. */ ~basic_string() _GLIBCXX_NOEXCEPT { _M_rep()->_M_dispose(this->get_allocator()); } /** * @brief Assign the value of @a str to this string. * @param __str Source string. */ basic_string& operator=(const basic_string& __str) { return this->assign(__str); } /** * @brief Copy contents of @a s into this string. * @param __s Source null-terminated string. */ basic_string& operator=(const _CharT* __s) { return this->assign(__s); } /** * @brief Set value to string of length 1. * @param __c Source character. * * Assigning to a character makes this string length 1 and * (*this)[0] == @a c. */ basic_string& operator=(_CharT __c) { this->assign(1, __c); return *this; } #if __cplusplus >= 201103L /** * @brief Move assign the value of @a str to this string. * @param __str Source string. * * The contents of @a str are moved into this string (without copying). * @a str is a valid, but unspecified string. **/ // PR 58265, this should be noexcept. basic_string& operator=(basic_string&& __str) { // NB: DR 1204. this->swap(__str); return *this; } /** * @brief Set value to string constructed from initializer %list. * @param __l std::initializer_list. */ basic_string& operator=(initializer_list<_CharT> __l) { this->assign(__l.begin(), __l.size()); return *this; } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value to string constructed from a string_view. * @param __svt An object convertible to string_view. */ template _If_sv<_Tp, basic_string&> operator=(const _Tp& __svt) { return this->assign(__svt); } /** * @brief Convert to a string_view. * @return A string_view. */ operator __sv_type() const noexcept { return __sv_type(data(), size()); } #endif // C++17 // Iterators: /** * Returns a read/write iterator that points to the first character in * the %string. Unshares the string. */ iterator begin() // FIXME C++11: should be noexcept. { _M_leak(); return iterator(_M_data()); } /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data()); } /** * Returns a read/write iterator that points one past the last * character in the %string. Unshares the string. */ iterator end() // FIXME C++11: should be noexcept. { _M_leak(); return iterator(_M_data() + this->size()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_M_data() + this->size()); } /** * Returns a read/write reverse iterator that points to the last * character in the %string. Iteration is done in reverse element * order. Unshares the string. */ reverse_iterator rbegin() // FIXME C++11: should be noexcept. { return reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->end()); } /** * Returns a read/write reverse iterator that points to one before the * first character in the %string. Iteration is done in reverse * element order. Unshares the string. */ reverse_iterator rend() // FIXME C++11: should be noexcept. { return reverse_iterator(this->begin()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->begin()); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * character in the %string. */ const_iterator cbegin() const noexcept { return const_iterator(this->_M_data()); } /** * Returns a read-only (constant) iterator that points one past the * last character in the %string. */ const_iterator cend() const noexcept { return const_iterator(this->_M_data() + this->size()); } /** * Returns a read-only (constant) reverse iterator that points * to the last character in the %string. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first character in the %string. Iteration * is done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } #endif public: // Capacity: /// Returns the number of characters in the string, not including any /// null-termination. size_type size() const _GLIBCXX_NOEXCEPT { return _M_rep()->_M_length; } /// Returns the number of characters in the string, not including any /// null-termination. size_type length() const _GLIBCXX_NOEXCEPT { return _M_rep()->_M_length; } /// Returns the size() of the largest possible %string. size_type max_size() const _GLIBCXX_NOEXCEPT { return _Rep::_S_max_size; } /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * @param __c Character to fill any new elements. * * This function will %resize the %string to the specified * number of characters. If the number is smaller than the * %string's current size the %string is truncated, otherwise * the %string is extended and new elements are %set to @a __c. */ void resize(size_type __n, _CharT __c); /** * @brief Resizes the %string to the specified number of characters. * @param __n Number of characters the %string should contain. * * This function will resize the %string to the specified length. If * the new size is smaller than the %string's current size the %string * is truncated, otherwise the %string is extended and new characters * are default-constructed. For basic types such as char, this means * setting them to 0. */ void resize(size_type __n) { this->resize(__n, _CharT()); } #if __cplusplus >= 201103L /// A non-binding request to reduce capacity() to size(). void shrink_to_fit() _GLIBCXX_NOEXCEPT { #if __cpp_exceptions if (capacity() > size()) { try { reserve(0); } catch(...) { } } #endif } #endif /** * Returns the total number of characters that the %string can hold * before needing to allocate more memory. */ size_type capacity() const _GLIBCXX_NOEXCEPT { return _M_rep()->_M_capacity; } /** * @brief Attempt to preallocate enough memory for specified number of * characters. * @param __res_arg Number of characters required. * @throw std::length_error If @a __res_arg exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %string to hold the specified number of characters. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the string length that will be * required, the user can reserve the memory in %advance, and thus * prevent a possible reallocation of memory and copying of %string * data. */ void reserve(size_type __res_arg = 0); /** * Erases the string, making it empty. */ #if _GLIBCXX_FULLY_DYNAMIC_STRING == 0 void clear() _GLIBCXX_NOEXCEPT { if (_M_rep()->_M_is_shared()) { _M_rep()->_M_dispose(this->get_allocator()); _M_data(_S_empty_rep()._M_refdata()); } else _M_rep()->_M_set_length_and_sharable(0); } #else // PR 56166: this should not throw. void clear() { _M_mutate(0, this->size(), 0); } #endif /** * Returns true if the %string is empty. Equivalent to * *this == "". */ bool empty() const _GLIBCXX_NOEXCEPT { return this->size() == 0; } // Element access: /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read-only (constant) reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[] (size_type __pos) const _GLIBCXX_NOEXCEPT { __glibcxx_assert(__pos <= size()); return _M_data()[__pos]; } /** * @brief Subscript access to the data contained in the %string. * @param __pos The index of the character to access. * @return Read/write reference to the character. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) Unshares the string. */ reference operator[](size_type __pos) { // Allow pos == size() both in C++98 mode, as v3 extension, // and in C++11 mode. __glibcxx_assert(__pos <= size()); // In pedantic mode be strict in C++98 mode. _GLIBCXX_DEBUG_PEDASSERT(__cplusplus >= 201103L || __pos < size()); _M_leak(); return _M_data()[__pos]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read-only (const) reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. */ const_reference at(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); return _M_data()[__n]; } /** * @brief Provides access to the data contained in the %string. * @param __n The index of the character to access. * @return Read/write reference to the character. * @throw std::out_of_range If @a n is an invalid index. * * This function provides for safer data access. The parameter is * first checked that it is in the range of the string. The function * throws out_of_range if the check fails. Success results in * unsharing the string. */ reference at(size_type __n) { if (__n >= size()) __throw_out_of_range_fmt(__N("basic_string::at: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); _M_leak(); return _M_data()[__n]; } #if __cplusplus >= 201103L /** * Returns a read/write reference to the data at the first * element of the %string. */ reference front() { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read-only (constant) reference to the data at the first * element of the %string. */ const_reference front() const noexcept { __glibcxx_assert(!empty()); return operator[](0); } /** * Returns a read/write reference to the data at the last * element of the %string. */ reference back() { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %string. */ const_reference back() const noexcept { __glibcxx_assert(!empty()); return operator[](this->size() - 1); } #endif // Modifiers: /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& operator+=(const basic_string& __str) { return this->append(__str); } /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& operator+=(const _CharT* __s) { return this->append(__s); } /** * @brief Append a character. * @param __c The character to append. * @return Reference to this string. */ basic_string& operator+=(_CharT __c) { this->push_back(__c); return *this; } #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to be appended. * @return Reference to this string. */ basic_string& operator+=(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt The object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> operator+=(const _Tp& __svt) { return this->append(__svt); } #endif // C++17 /** * @brief Append a string to this string. * @param __str The string to append. * @return Reference to this string. */ basic_string& append(const basic_string& __str); /** * @brief Append a substring. * @param __str The string to append. * @param __pos Index of the first character of str to append. * @param __n The number of characters to append. * @return Reference to this string. * @throw std::out_of_range if @a __pos is not a valid index. * * This function appends @a __n characters from @a __str * starting at @a __pos to this string. If @a __n is is larger * than the number of available characters in @a __str, the * remainder of @a __str is appended. */ basic_string& append(const basic_string& __str, size_type __pos, size_type __n = npos); /** * @brief Append a C substring. * @param __s The C string to append. * @param __n The number of characters to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s, size_type __n); /** * @brief Append a C string. * @param __s The C string to append. * @return Reference to this string. */ basic_string& append(const _CharT* __s) { __glibcxx_requires_string(__s); return this->append(__s, traits_type::length(__s)); } /** * @brief Append multiple characters. * @param __n The number of characters to append. * @param __c The character to use. * @return Reference to this string. * * Appends __n copies of __c to this string. */ basic_string& append(size_type __n, _CharT __c); #if __cplusplus >= 201103L /** * @brief Append an initializer_list of characters. * @param __l The initializer_list of characters to append. * @return Reference to this string. */ basic_string& append(initializer_list<_CharT> __l) { return this->append(__l.begin(), __l.size()); } #endif // C++11 /** * @brief Append a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Appends characters in the range [__first,__last) to this string. */ template basic_string& append(_InputIterator __first, _InputIterator __last) { return this->replace(_M_iend(), _M_iend(), __first, __last); } #if __cplusplus > 201402L /** * @brief Append a string_view. * @param __svt The object convertible to string_view to be appended. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt) { __sv_type __sv = __svt; return this->append(__sv.data(), __sv.size()); } /** * @brief Append a range of characters from a string_view. * @param __svt The object convertible to string_view to be appended * from. * @param __pos The position in the string_view to append from. * @param __n The number of characters to append from the string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> append(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return append(__sv.data() + __sv._M_check(__pos, "basic_string::append"), __sv._M_limit(__pos, __n)); } #endif // C++17 /** * @brief Append a single character. * @param __c Character to append. */ void push_back(_CharT __c) { const size_type __len = 1 + this->size(); if (__len > this->capacity() || _M_rep()->_M_is_shared()) this->reserve(__len); traits_type::assign(_M_data()[this->size()], __c); _M_rep()->_M_set_length_and_sharable(__len); } /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. */ basic_string& assign(const basic_string& __str); #if __cplusplus >= 201103L /** * @brief Set value to contents of another string. * @param __str Source string to use. * @return Reference to this string. * * This function sets this string to the exact contents of @a __str. * @a __str is a valid, but unspecified string. */ // PR 58265, this should be noexcept. basic_string& assign(basic_string&& __str) { this->swap(__str); return *this; } #endif // C++11 /** * @brief Set value to a substring of a string. * @param __str The string to use. * @param __pos Index of the first character of str. * @param __n Number of characters to use. * @return Reference to this string. * @throw std::out_of_range if @a pos is not a valid index. * * This function sets this string to the substring of @a __str * consisting of @a __n characters at @a __pos. If @a __n is * is larger than the number of available characters in @a * __str, the remainder of @a __str is used. */ basic_string& assign(const basic_string& __str, size_type __pos, size_type __n = npos) { return this->assign(__str._M_data() + __str._M_check(__pos, "basic_string::assign"), __str._M_limit(__pos, __n)); } /** * @brief Set value to a C substring. * @param __s The C string to use. * @param __n Number of characters to use. * @return Reference to this string. * * This function sets the value of this string to the first @a __n * characters of @a __s. If @a __n is is larger than the number of * available characters in @a __s, the remainder of @a __s is used. */ basic_string& assign(const _CharT* __s, size_type __n); /** * @brief Set value to contents of a C string. * @param __s The C string to use. * @return Reference to this string. * * This function sets the value of this string to the value of @a __s. * The data is copied, so there is no dependence on @a __s once the * function returns. */ basic_string& assign(const _CharT* __s) { __glibcxx_requires_string(__s); return this->assign(__s, traits_type::length(__s)); } /** * @brief Set value to multiple characters. * @param __n Length of the resulting string. * @param __c The character to use. * @return Reference to this string. * * This function sets the value of this string to @a __n copies of * character @a __c. */ basic_string& assign(size_type __n, _CharT __c) { return _M_replace_aux(size_type(0), this->size(), __n, __c); } /** * @brief Set value to a range of characters. * @param __first Iterator referencing the first character to append. * @param __last Iterator marking the end of the range. * @return Reference to this string. * * Sets value of string to characters in the range [__first,__last). */ template basic_string& assign(_InputIterator __first, _InputIterator __last) { return this->replace(_M_ibegin(), _M_iend(), __first, __last); } #if __cplusplus >= 201103L /** * @brief Set value to an initializer_list of characters. * @param __l The initializer_list of characters to assign. * @return Reference to this string. */ basic_string& assign(initializer_list<_CharT> __l) { return this->assign(__l.begin(), __l.size()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Set value from a string_view. * @param __svt The source object convertible to string_view. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt) { __sv_type __sv = __svt; return this->assign(__sv.data(), __sv.size()); } /** * @brief Set value from a range of characters in a string_view. * @param __svt The source object convertible to string_view. * @param __pos The position in the string_view to assign from. * @param __n The number of characters to assign. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> assign(const _Tp& __svt, size_type __pos, size_type __n = npos) { __sv_type __sv = __svt; return assign(__sv.data() + __sv._M_check(__pos, "basic_string::assign"), __sv._M_limit(__pos, __n)); } #endif // C++17 /** * @brief Insert multiple characters. * @param __p Iterator referencing location in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts @a __n copies of character @a __c starting at the * position referenced by iterator @a __p. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ void insert(iterator __p, size_type __n, _CharT __c) { this->replace(__p, __p, __n, __c); } /** * @brief Insert a range of characters. * @param __p Iterator referencing location in string to insert at. * @param __beg Start of range. * @param __end End of range. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts characters in range [__beg,__end). If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ template void insert(iterator __p, _InputIterator __beg, _InputIterator __end) { this->replace(__p, __p, __beg, __end); } #if __cplusplus >= 201103L /** * @brief Insert an initializer_list of characters. * @param __p Iterator referencing location in string to insert at. * @param __l The initializer_list of characters to insert. * @throw std::length_error If new length exceeds @c max_size(). */ void insert(iterator __p, initializer_list<_CharT> __l) { _GLIBCXX_DEBUG_PEDASSERT(__p >= _M_ibegin() && __p <= _M_iend()); this->insert(__p - _M_ibegin(), __l.begin(), __l.size()); } #endif // C++11 /** * @brief Insert value of a string. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts value of @a __str starting at @a __pos1. If adding * characters causes the length to exceed max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str) { return this->insert(__pos1, __str, size_type(0), __str.size()); } /** * @brief Insert a substring. * @param __pos1 Iterator referencing location in string to insert at. * @param __str The string to insert. * @param __pos2 Start of characters in str to insert. * @param __n Number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos1 > size() or * @a __pos2 > @a str.size(). * * Starting at @a pos1, insert @a __n character of @a __str * beginning with @a __pos2. If adding characters causes the * length to exceed max_size(), length_error is thrown. If @a * __pos1 is beyond the end of this string or @a __pos2 is * beyond the end of @a __str, out_of_range is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n = npos) { return this->insert(__pos1, __str._M_data() + __str._M_check(__pos2, "basic_string::insert"), __str._M_limit(__pos2, __n)); } /** * @brief Insert a C substring. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @param __n The number of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts the first @a __n characters of @a __s starting at @a * __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos is beyond * end(), out_of_range is thrown. The value of the string * doesn't change if an error is thrown. */ basic_string& insert(size_type __pos, const _CharT* __s, size_type __n); /** * @brief Insert a C string. * @param __pos Iterator referencing location in string to insert at. * @param __s The C string to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Inserts the first @a n characters of @a __s starting at @a __pos. If * adding characters causes the length to exceed max_size(), * length_error is thrown. If @a __pos is beyond end(), out_of_range is * thrown. The value of the string doesn't change if an error is * thrown. */ basic_string& insert(size_type __pos, const _CharT* __s) { __glibcxx_requires_string(__s); return this->insert(__pos, __s, traits_type::length(__s)); } /** * @brief Insert multiple characters. * @param __pos Index in string to insert at. * @param __n Number of characters to insert * @param __c The character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * @throw std::out_of_range If @a __pos is beyond the end of this * string. * * Inserts @a __n copies of character @a __c starting at index * @a __pos. If adding characters causes the length to exceed * max_size(), length_error is thrown. If @a __pos > length(), * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& insert(size_type __pos, size_type __n, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::insert"), size_type(0), __n, __c); } /** * @brief Insert one character. * @param __p Iterator referencing position in string to insert at. * @param __c The character to insert. * @return Iterator referencing newly inserted char. * @throw std::length_error If new length exceeds @c max_size(). * * Inserts character @a __c at position referenced by @a __p. * If adding character causes the length to exceed max_size(), * length_error is thrown. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ iterator insert(iterator __p, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(__p >= _M_ibegin() && __p <= _M_iend()); const size_type __pos = __p - _M_ibegin(); _M_replace_aux(__pos, size_type(0), size_type(1), __c); _M_rep()->_M_set_leaked(); return iterator(_M_data() + __pos); } #if __cplusplus > 201402L /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos, const _Tp& __svt) { __sv_type __sv = __svt; return this->insert(__pos, __sv.data(), __sv.size()); } /** * @brief Insert a string_view. * @param __pos Iterator referencing position in string to insert at. * @param __svt The object convertible to string_view to insert from. * @param __pos Iterator referencing position in string_view to insert * from. * @param __n The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> insert(size_type __pos1, const _Tp& __svt, size_type __pos2, size_type __n = npos) { __sv_type __sv = __svt; return this->replace(__pos1, size_type(0), __sv.data() + __sv._M_check(__pos2, "basic_string::insert"), __sv._M_limit(__pos2, __n)); } #endif // C++17 /** * @brief Remove characters. * @param __pos Index of first character to remove (default 0). * @param __n Number of characters to remove (default remainder). * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * * Removes @a __n characters from this string starting at @a * __pos. The length of the string is reduced by @a __n. If * there are < @a __n characters to remove, the remainder of * the string is truncated. If @a __p is beyond end of string, * out_of_range is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& erase(size_type __pos = 0, size_type __n = npos) { _M_mutate(_M_check(__pos, "basic_string::erase"), _M_limit(__pos, __n), size_type(0)); return *this; } /** * @brief Remove one character. * @param __position Iterator referencing the character to remove. * @return iterator referencing same location after removal. * * Removes the character at @a __position from this string. The value * of the string doesn't change if an error is thrown. */ iterator erase(iterator __position) { _GLIBCXX_DEBUG_PEDASSERT(__position >= _M_ibegin() && __position < _M_iend()); const size_type __pos = __position - _M_ibegin(); _M_mutate(__pos, size_type(1), size_type(0)); _M_rep()->_M_set_leaked(); return iterator(_M_data() + __pos); } /** * @brief Remove a range of characters. * @param __first Iterator referencing the first character to remove. * @param __last Iterator referencing the end of the range. * @return Iterator referencing location of first after removal. * * Removes the characters in the range [first,last) from this string. * The value of the string doesn't change if an error is thrown. */ iterator erase(iterator __first, iterator __last); #if __cplusplus >= 201103L /** * @brief Remove the last character. * * The string must be non-empty. */ void pop_back() // FIXME C++11: should be noexcept. { __glibcxx_assert(!empty()); erase(size() - 1, 1); } #endif // C++11 /** * @brief Replace characters with value from another string. * @param __pos Index of first character to replace. * @param __n Number of characters to be replaced. * @param __str String to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos is beyond the end of this * string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos+__n) from * this string. In place, the value of @a __str is inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of the result exceeds max_size(), length_error * is thrown. The value of the string doesn't change if an * error is thrown. */ basic_string& replace(size_type __pos, size_type __n, const basic_string& __str) { return this->replace(__pos, __n, __str._M_data(), __str.size()); } /** * @brief Replace characters with value from another string. * @param __pos1 Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __str String to insert. * @param __pos2 Index of first character of str to use. * @param __n2 Number of characters from str to use. * @return Reference to this string. * @throw std::out_of_range If @a __pos1 > size() or @a __pos2 > * __str.size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos1,__pos1 + n) from this * string. In place, the value of @a __str is inserted. If @a __pos is * beyond end of string, out_of_range is thrown. If the length of the * result exceeds max_size(), length_error is thrown. The value of the * string doesn't change if an error is thrown. */ basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) { return this->replace(__pos1, __n1, __str._M_data() + __str._M_check(__pos2, "basic_string::replace"), __str._M_limit(__pos2, __n2)); } /** * @brief Replace characters with value of a C substring. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @param __n2 Number of characters from @a s to use. * @return Reference to this string. * @throw std::out_of_range If @a pos1 > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the first @a __n2 characters of * @a __s are inserted, or all of @a __s if @a __n2 is too large. If * @a __pos is beyond end of string, out_of_range is thrown. If * the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2); /** * @brief Replace characters with value of a C string. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __s C string to insert. * @return Reference to this string. * @throw std::out_of_range If @a pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__pos,__pos + __n1) * from this string. In place, the characters of @a __s are * inserted. If @a __pos is beyond end of string, out_of_range * is thrown. If the length of result exceeds max_size(), * length_error is thrown. The value of the string doesn't * change if an error is thrown. */ basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__pos, __n1, __s, traits_type::length(__s)); } /** * @brief Replace characters with multiple characters. * @param __pos Index of first character to replace. * @param __n1 Number of characters to be replaced. * @param __n2 Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::out_of_range If @a __pos > size(). * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [pos,pos + n1) from this * string. In place, @a __n2 copies of @a __c are inserted. * If @a __pos is beyond end of string, out_of_range is thrown. * If the length of result exceeds max_size(), length_error is * thrown. The value of the string doesn't change if an error * is thrown. */ basic_string& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) { return _M_replace_aux(_M_check(__pos, "basic_string::replace"), _M_limit(__pos, __n1), __n2, __c); } /** * @brief Replace range of characters with string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __str String value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the value of @a __str is inserted. If the length of result * exceeds max_size(), length_error is thrown. The value of * the string doesn't change if an error is thrown. */ basic_string& replace(iterator __i1, iterator __i2, const basic_string& __str) { return this->replace(__i1, __i2, __str._M_data(), __str.size()); } /** * @brief Replace range of characters with C substring. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @param __n Number of characters from s to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the first @a __n characters of @a __s are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s, size_type __n) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __s, __n); } /** * @brief Replace range of characters with C string. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __s C string value to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * the characters of @a __s are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s) { __glibcxx_requires_string(__s); return this->replace(__i1, __i2, __s, traits_type::length(__s)); } /** * @brief Replace range of characters with multiple characters * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __n Number of characters to insert. * @param __c Character to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * @a __n copies of @a __c are inserted. If the length of * result exceeds max_size(), length_error is thrown. The * value of the string doesn't change if an error is thrown. */ basic_string& replace(iterator __i1, iterator __i2, size_type __n, _CharT __c) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); return _M_replace_aux(__i1 - _M_ibegin(), __i2 - __i1, __n, __c); } /** * @brief Replace range of characters with range. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __k1 Iterator referencing start of range to insert. * @param __k2 Iterator referencing end of range to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ template basic_string& replace(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); typedef typename std::__is_integer<_InputIterator>::__type _Integral; return _M_replace_dispatch(__i1, __i2, __k1, __k2, _Integral()); } // Specializations for the common case of pointer and iterator: // useful to avoid the overhead of temporary buffering in _M_replace. basic_string& replace(iterator __i1, iterator __i2, _CharT* __k1, _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(iterator __i1, iterator __i2, const _CharT* __k1, const _CharT* __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1, __k2 - __k1); } basic_string& replace(iterator __i1, iterator __i2, iterator __k1, iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1.base(), __k2 - __k1); } basic_string& replace(iterator __i1, iterator __i2, const_iterator __k1, const_iterator __k2) { _GLIBCXX_DEBUG_PEDASSERT(_M_ibegin() <= __i1 && __i1 <= __i2 && __i2 <= _M_iend()); __glibcxx_requires_valid_range(__k1, __k2); return this->replace(__i1 - _M_ibegin(), __i2 - __i1, __k1.base(), __k2 - __k1); } #if __cplusplus >= 201103L /** * @brief Replace range of characters with initializer_list. * @param __i1 Iterator referencing start of range to replace. * @param __i2 Iterator referencing end of range to replace. * @param __l The initializer_list of characters to insert. * @return Reference to this string. * @throw std::length_error If new length exceeds @c max_size(). * * Removes the characters in the range [__i1,__i2). In place, * characters in the range [__k1,__k2) are inserted. If the * length of result exceeds max_size(), length_error is thrown. * The value of the string doesn't change if an error is * thrown. */ basic_string& replace(iterator __i1, iterator __i2, initializer_list<_CharT> __l) { return this->replace(__i1, __i2, __l.begin(), __l.end()); } #endif // C++11 #if __cplusplus > 201402L /** * @brief Replace range of characters with string_view. * @param __pos The position to replace at. * @param __n The number of characters to replace. * @param __svt The object convertible to string_view to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos, size_type __n, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__pos, __n, __sv.data(), __sv.size()); } /** * @brief Replace range of characters with string_view. * @param __pos1 The position to replace at. * @param __n1 The number of characters to replace. * @param __svt The object convertible to string_view to insert from. * @param __pos2 The position in the string_view to insert from. * @param __n2 The number of characters to insert. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) { __sv_type __sv = __svt; return this->replace(__pos1, __n1, __sv.data() + __sv._M_check(__pos2, "basic_string::replace"), __sv._M_limit(__pos2, __n2)); } /** * @brief Replace range of characters with string_view. * @param __i1 An iterator referencing the start position to replace at. * @param __i2 An iterator referencing the end position for the replace. * @param __svt The object convertible to string_view to insert from. * @return Reference to this string. */ template _If_sv<_Tp, basic_string&> replace(const_iterator __i1, const_iterator __i2, const _Tp& __svt) { __sv_type __sv = __svt; return this->replace(__i1 - begin(), __i2 - __i1, __sv); } #endif // C++17 private: template basic_string& _M_replace_dispatch(iterator __i1, iterator __i2, _Integer __n, _Integer __val, __true_type) { return _M_replace_aux(__i1 - _M_ibegin(), __i2 - __i1, __n, __val); } template basic_string& _M_replace_dispatch(iterator __i1, iterator __i2, _InputIterator __k1, _InputIterator __k2, __false_type); basic_string& _M_replace_aux(size_type __pos1, size_type __n1, size_type __n2, _CharT __c); basic_string& _M_replace_safe(size_type __pos1, size_type __n1, const _CharT* __s, size_type __n2); // _S_construct_aux is used to implement the 21.3.1 para 15 which // requires special behaviour if _InIter is an integral type template static _CharT* _S_construct_aux(_InIterator __beg, _InIterator __end, const _Alloc& __a, __false_type) { typedef typename iterator_traits<_InIterator>::iterator_category _Tag; return _S_construct(__beg, __end, __a, _Tag()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template static _CharT* _S_construct_aux(_Integer __beg, _Integer __end, const _Alloc& __a, __true_type) { return _S_construct_aux_2(static_cast(__beg), __end, __a); } static _CharT* _S_construct_aux_2(size_type __req, _CharT __c, const _Alloc& __a) { return _S_construct(__req, __c, __a); } template static _CharT* _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a) { typedef typename std::__is_integer<_InIterator>::__type _Integral; return _S_construct_aux(__beg, __end, __a, _Integral()); } // For Input Iterators, used in istreambuf_iterators, etc. template static _CharT* _S_construct(_InIterator __beg, _InIterator __end, const _Alloc& __a, input_iterator_tag); // For forward_iterators up to random_access_iterators, used for // string::iterator, _CharT*, etc. template static _CharT* _S_construct(_FwdIterator __beg, _FwdIterator __end, const _Alloc& __a, forward_iterator_tag); static _CharT* _S_construct(size_type __req, _CharT __c, const _Alloc& __a); public: /** * @brief Copy substring into C string. * @param __s C string to copy value into. * @param __n Number of characters to copy. * @param __pos Index of first character to copy. * @return Number of characters actually copied * @throw std::out_of_range If __pos > size(). * * Copies up to @a __n characters starting at @a __pos into the * C string @a __s. If @a __pos is %greater than size(), * out_of_range is thrown. */ size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const; /** * @brief Swap contents with another string. * @param __s String to swap with. * * Exchanges the contents of this string with that of @a __s in constant * time. */ // PR 58265, this should be noexcept. void swap(basic_string& __s); // String operations: /** * @brief Return const pointer to null-terminated contents. * * This is a handle to internal data. Do not modify or dire things may * happen. */ const _CharT* c_str() const _GLIBCXX_NOEXCEPT { return _M_data(); } /** * @brief Return const pointer to contents. * * This is a pointer to internal data. It is undefined to modify * the contents through the returned pointer. To get a pointer that * allows modifying the contents use @c &str[0] instead, * (or in C++17 the non-const @c str.data() overload). */ const _CharT* data() const _GLIBCXX_NOEXCEPT { return _M_data(); } #if __cplusplus > 201402L /** * @brief Return non-const pointer to contents. * * This is a pointer to the character sequence held by the string. * Modifying the characters in the sequence is allowed. */ _CharT* data() noexcept { _M_leak(); return _M_data(); } #endif /** * @brief Return copy of allocator used to construct this string. */ allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return _M_dataplus; } /** * @brief Find position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search from. * @param __n Number of characters from @a s to search for. * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type find(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a string. * @param __str String to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for value of @a __str within * this string. If found, returns the index where it begins. If not * found, returns npos. */ size_type find(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__str.data(), __pos, __str.size()); } /** * @brief Find position of a C string. * @param __s C string to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. * * Starting from @a __pos, searches forward for the value of @a * __s within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type find(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search from (default 0). * @return Index of start of first occurrence. */ template _If_sv<_Tp, size_type> find(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a string. * @param __str String to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for value of @a * __str within this string. If found, returns the index where * it begins. If not found, returns npos. */ size_type rfind(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__str.data(), __pos, __str.size()); } /** * @brief Find last position of a C substring. * @param __s C string to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the first @a * __n characters in @a __s within this string. If found, * returns the index where it begins. If not found, returns * npos. */ size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a C string. * @param __s C string to locate. * @param __pos Index of character to start search at (default end). * @return Index of start of last occurrence. * * Starting from @a __pos, searches backward for the value of * @a __s within this string. If found, returns the index * where it begins. If not found, returns npos. */ size_type rfind(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->rfind(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type rfind(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find last position of a string_view. * @param __svt The object convertible to string_view to locate. * @param __pos Index of character to search back from (default end). * @return Index of start of last occurrence. */ template _If_sv<_Tp, size_type> rfind(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->rfind(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_of(__str.data(), __pos, __str.size()); } /** * @brief Find position of a character of C substring. * @param __s String containing characters to locate. * @param __pos Index of character to search from. * @param __n Number of characters from s to search for. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character of C string. * @param __s String containing characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a character. * @param __c Character to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for the character * @a __c within this string. If found, returns the index * where it was found. If not found, returns npos. * * Note: equivalent to find(__c, __pos). */ size_type find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find(__c, __pos); } #if __cplusplus > 201402L /** * @brief Find position of a character of a string_view. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character of string. * @param __str String containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_of(__str.data(), __pos, __str.size()); } /** * @brief Find last position of a character of C substring. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from. * @param __n Number of characters from s to search for. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * first @a __n characters of @a __s within this string. If * found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character of C string. * @param __s C string containing characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for one of the * characters of @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_last_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a character. * @param __c Character to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for @a __c within * this string. If found, returns the index where it was * found. If not found, returns npos. * * Note: equivalent to rfind(__c, __pos). */ size_type find_last_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->rfind(__c, __pos); } #if __cplusplus > 201402L /** * @brief Find last position of a character of string. * @param __svt An object convertible to string_view containing * characters to locate. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not contained * in @a __str within this string. If found, returns the index where it * was found. If not found, returns npos. */ size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return this->find_first_not_of(__str.data(), __pos, __str.size()); } /** * @brief Find position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from. * @param __n Number of characters from __s to consider. * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in the first @a __n characters of @a __s within * this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character not * contained in @a __s within this string. If found, returns * the index where it was found. If not found, returns npos. */ size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_first_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. * * Starting from @a __pos, searches forward for a character * other than @a __c within this string. If found, returns the * index where it was found. If not found, returns npos. */ size_type find_first_not_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find position of a character not in a string_view. * @param __svt An object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search from (default 0). * @return Index of first occurrence. */ template _If_sv<_Tp, size_type> find_first_not_of(const _Tp& __svt, size_type __pos = 0) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_first_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Find last position of a character not in string. * @param __str String containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __str within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const basic_string& __str, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { return this->find_last_not_of(__str.data(), __pos, __str.size()); } /** * @brief Find last position of a character not in C substring. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from. * @param __n Number of characters from s to consider. * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character not * contained in the first @a __n characters of @a __s within this string. * If found, returns the index where it was found. If not found, * returns npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _GLIBCXX_NOEXCEPT; /** * @brief Find last position of a character not in C string. * @param __s C string containing characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character * not contained in @a __s within this string. If found, * returns the index where it was found. If not found, returns * npos. */ size_type find_last_not_of(const _CharT* __s, size_type __pos = npos) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_string(__s); return this->find_last_not_of(__s, __pos, traits_type::length(__s)); } /** * @brief Find last position of a different character. * @param __c Character to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. * * Starting from @a __pos, searches backward for a character other than * @a __c within this string. If found, returns the index where it was * found. If not found, returns npos. */ size_type find_last_not_of(_CharT __c, size_type __pos = npos) const _GLIBCXX_NOEXCEPT; #if __cplusplus > 201402L /** * @brief Find last position of a character not in a string_view. * @param __svt An object convertible to string_view containing * characters to avoid. * @param __pos Index of character to search back from (default end). * @return Index of last occurrence. */ template _If_sv<_Tp, size_type> find_last_not_of(const _Tp& __svt, size_type __pos = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return this->find_last_not_of(__sv.data(), __pos, __sv.size()); } #endif // C++17 /** * @brief Get a substring. * @param __pos Index of first character (default 0). * @param __n Number of characters in substring (default remainder). * @return The new string. * @throw std::out_of_range If __pos > size(). * * Construct and return a new string using the @a __n * characters starting at @a __pos. If the string is too * short, use the remainder of the characters. If @a __pos is * beyond the end of the string, out_of_range is thrown. */ basic_string substr(size_type __pos = 0, size_type __n = npos) const { return basic_string(*this, _M_check(__pos, "basic_string::substr"), __n); } /** * @brief Compare to a string. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a * __str, 0 if their values are equivalent, or > 0 if this * string is ordered after @a __str. Determines the effective * length rlen of the strings to compare as the smallest of * size() and str.size(). The function then compares the two * strings by calling traits::compare(data(), str.data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(const basic_string& __str) const { const size_type __size = this->size(); const size_type __osize = __str.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __str.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } #if __cplusplus > 201402L /** * @brief Compare to a string_view. * @param __svt An object convertible to string_view to compare against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; const size_type __size = this->size(); const size_type __osize = __sv.size(); const size_type __len = std::min(__size, __osize); int __r = traits_type::compare(_M_data(), __sv.data(), __len); if (!__r) __r = _S_compare(__size, __osize); return __r; } /** * @brief Compare to a string_view. * @param __pos A position in the string to start comparing from. * @param __n The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos, size_type __n, const _Tp& __svt) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this).substr(__pos, __n).compare(__sv); } /** * @brief Compare to a string_view. * @param __pos1 A position in the string to start comparing from. * @param __n1 The number of characters to compare. * @param __svt An object convertible to string_view to compare * against. * @param __pos2 A position in the string_view to start comparing from. * @param __n2 The number of characters to compare. * @return Integer < 0, 0, or > 0. */ template _If_sv<_Tp, int> compare(size_type __pos1, size_type __n1, const _Tp& __svt, size_type __pos2, size_type __n2 = npos) const noexcept(is_same<_Tp, __sv_type>::value) { __sv_type __sv = __svt; return __sv_type(*this) .substr(__pos1, __n1).compare(__sv.substr(__pos2, __n2)); } #endif // C++17 /** * @brief Compare substring to a string. * @param __pos Index of first character of substring. * @param __n Number of characters in substring. * @param __str String to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n characters * starting at @a __pos. Returns an integer < 0 if the * substring is ordered before @a __str, 0 if their values are * equivalent, or > 0 if the substring is ordered after @a * __str. Determines the effective length rlen of the strings * to compare as the smallest of the length of the substring * and @a __str.size(). The function then compares the two * strings by calling * traits::compare(substring.data(),str.data(),rlen). If the * result of the comparison is nonzero returns it, otherwise * the shorter one is ordered first. */ int compare(size_type __pos, size_type __n, const basic_string& __str) const; /** * @brief Compare substring to a substring. * @param __pos1 Index of first character of substring. * @param __n1 Number of characters in substring. * @param __str String to compare against. * @param __pos2 Index of first character of substring of str. * @param __n2 Number of characters in substring of str. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos1. Form the substring of @a * __str from the @a __n2 characters starting at @a __pos2. * Returns an integer < 0 if this substring is ordered before * the substring of @a __str, 0 if their values are equivalent, * or > 0 if this substring is ordered after the substring of * @a __str. Determines the effective length rlen of the * strings to compare as the smallest of the lengths of the * substrings. The function then compares the two strings by * calling * traits::compare(substring.data(),str.substr(pos2,n2).data(),rlen). * If the result of the comparison is nonzero returns it, * otherwise the shorter one is ordered first. */ int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2 = npos) const; /** * @brief Compare to a C string. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Returns an integer < 0 if this string is ordered before @a __s, 0 if * their values are equivalent, or > 0 if this string is ordered after * @a __s. Determines the effective length rlen of the strings to * compare as the smallest of size() and the length of a string * constructed from @a __s. The function then compares the two strings * by calling traits::compare(data(),s,rlen). If the result of the * comparison is nonzero returns it, otherwise the shorter one is * ordered first. */ int compare(const _CharT* __s) const _GLIBCXX_NOEXCEPT; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5 String::compare specification questionable /** * @brief Compare substring to a C string. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s C string to compare against. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a pos. Returns an integer < 0 if * the substring is ordered before @a __s, 0 if their values * are equivalent, or > 0 if the substring is ordered after @a * __s. Determines the effective length rlen of the strings to * compare as the smallest of the length of the substring and * the length of a string constructed from @a __s. The * function then compares the two string by calling * traits::compare(substring.data(),__s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. */ int compare(size_type __pos, size_type __n1, const _CharT* __s) const; /** * @brief Compare substring against a character %array. * @param __pos Index of first character of substring. * @param __n1 Number of characters in substring. * @param __s character %array to compare against. * @param __n2 Number of characters of s. * @return Integer < 0, 0, or > 0. * * Form the substring of this string from the @a __n1 * characters starting at @a __pos. Form a string from the * first @a __n2 characters of @a __s. Returns an integer < 0 * if this substring is ordered before the string from @a __s, * 0 if their values are equivalent, or > 0 if this substring * is ordered after the string from @a __s. Determines the * effective length rlen of the strings to compare as the * smallest of the length of the substring and @a __n2. The * function then compares the two strings by calling * traits::compare(substring.data(),s,rlen). If the result of * the comparison is nonzero returns it, otherwise the shorter * one is ordered first. * * NB: s must have at least n2 characters, '\\0' has * no special meaning. */ int compare(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) const; # ifdef _GLIBCXX_TM_TS_INTERNAL friend void ::_txnal_cow_string_C1_for_exceptions(void* that, const char* s, void* exc); friend const char* ::_txnal_cow_string_c_str(const void *that); friend void ::_txnal_cow_string_D1(void *that); friend void ::_txnal_cow_string_D1_commit(void *that); # endif }; #endif // !_GLIBCXX_USE_CXX11_ABI #if __cpp_deduction_guides >= 201606 _GLIBCXX_BEGIN_NAMESPACE_CXX11 template::value_type, typename _Allocator = allocator<_CharT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> basic_string(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> basic_string<_CharT, char_traits<_CharT>, _Allocator>; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 3075. basic_string needs deduction guides from basic_string_view template, typename = _RequireAllocator<_Allocator>> basic_string(basic_string_view<_CharT, _Traits>, const _Allocator& = _Allocator()) -> basic_string<_CharT, _Traits, _Allocator>; template, typename = _RequireAllocator<_Allocator>> basic_string(basic_string_view<_CharT, _Traits>, typename basic_string<_CharT, _Traits, _Allocator>::size_type, typename basic_string<_CharT, _Traits, _Allocator>::size_type, const _Allocator& = _Allocator()) -> basic_string<_CharT, _Traits, _Allocator>; _GLIBCXX_END_NAMESPACE_CXX11 #endif // operator+ /** * @brief Concatenate two strings. * @param __lhs First string. * @param __rhs Last string. * @return New string with value of @a __lhs followed by @a __rhs. */ template basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { basic_string<_CharT, _Traits, _Alloc> __str(__lhs); __str.append(__rhs); return __str; } /** * @brief Concatenate C string and string. * @param __lhs First string. * @param __rhs Last string. * @return New string with value of @a __lhs followed by @a __rhs. */ template basic_string<_CharT,_Traits,_Alloc> operator+(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Alloc>& __rhs); /** * @brief Concatenate character and string. * @param __lhs First string. * @param __rhs Last string. * @return New string with @a __lhs followed by @a __rhs. */ template basic_string<_CharT,_Traits,_Alloc> operator+(_CharT __lhs, const basic_string<_CharT,_Traits,_Alloc>& __rhs); /** * @brief Concatenate string and C string. * @param __lhs First string. * @param __rhs Last string. * @return New string with @a __lhs followed by @a __rhs. */ template inline basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { basic_string<_CharT, _Traits, _Alloc> __str(__lhs); __str.append(__rhs); return __str; } /** * @brief Concatenate string and character. * @param __lhs First string. * @param __rhs Last string. * @return New string with @a __lhs followed by @a __rhs. */ template inline basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, _CharT __rhs) { typedef basic_string<_CharT, _Traits, _Alloc> __string_type; typedef typename __string_type::size_type __size_type; __string_type __str(__lhs); __str.append(__size_type(1), __rhs); return __str; } #if __cplusplus >= 201103L template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return std::move(__lhs.append(__rhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { return std::move(__rhs.insert(0, __lhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { const auto __size = __lhs.size() + __rhs.size(); const bool __cond = (__size > __lhs.capacity() && __size <= __rhs.capacity()); return __cond ? std::move(__rhs.insert(0, __lhs)) : std::move(__lhs.append(__rhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(const _CharT* __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { return std::move(__rhs.insert(0, __lhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(_CharT __lhs, basic_string<_CharT, _Traits, _Alloc>&& __rhs) { return std::move(__rhs.insert(0, 1, __lhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, const _CharT* __rhs) { return std::move(__lhs.append(__rhs)); } template inline basic_string<_CharT, _Traits, _Alloc> operator+(basic_string<_CharT, _Traits, _Alloc>&& __lhs, _CharT __rhs) { return std::move(__lhs.append(1, __rhs)); } #endif // operator == /** * @brief Test equivalence of two strings. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs.compare(@a __rhs) == 0. False otherwise. */ template inline bool operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) == 0; } template inline typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, bool>::__type operator==(const basic_string<_CharT>& __lhs, const basic_string<_CharT>& __rhs) _GLIBCXX_NOEXCEPT { return (__lhs.size() == __rhs.size() && !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(), __lhs.size())); } /** * @brief Test equivalence of C string and string. * @param __lhs C string. * @param __rhs String. * @return True if @a __rhs.compare(@a __lhs) == 0. False otherwise. */ template inline bool operator==(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) == 0; } /** * @brief Test equivalence of string and C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs.compare(@a __rhs) == 0. False otherwise. */ template inline bool operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) == 0; } // operator != /** * @brief Test difference of two strings. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs.compare(@a __rhs) != 0. False otherwise. */ template inline bool operator!=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return !(__lhs == __rhs); } /** * @brief Test difference of C string and string. * @param __lhs C string. * @param __rhs String. * @return True if @a __rhs.compare(@a __lhs) != 0. False otherwise. */ template inline bool operator!=(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return !(__lhs == __rhs); } /** * @brief Test difference of string and C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs.compare(@a __rhs) != 0. False otherwise. */ template inline bool operator!=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return !(__lhs == __rhs); } // operator < /** * @brief Test if string precedes string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs precedes @a __rhs. False otherwise. */ template inline bool operator<(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) < 0; } /** * @brief Test if string precedes C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs precedes @a __rhs. False otherwise. */ template inline bool operator<(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) < 0; } /** * @brief Test if C string precedes string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs precedes @a __rhs. False otherwise. */ template inline bool operator<(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) > 0; } // operator > /** * @brief Test if string follows string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs follows @a __rhs. False otherwise. */ template inline bool operator>(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) > 0; } /** * @brief Test if string follows C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs follows @a __rhs. False otherwise. */ template inline bool operator>(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) > 0; } /** * @brief Test if C string follows string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs follows @a __rhs. False otherwise. */ template inline bool operator>(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) < 0; } // operator <= /** * @brief Test if string doesn't follow string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs doesn't follow @a __rhs. False otherwise. */ template inline bool operator<=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) <= 0; } /** * @brief Test if string doesn't follow C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs doesn't follow @a __rhs. False otherwise. */ template inline bool operator<=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) <= 0; } /** * @brief Test if C string doesn't follow string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs doesn't follow @a __rhs. False otherwise. */ template inline bool operator<=(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) >= 0; } // operator >= /** * @brief Test if string doesn't precede string. * @param __lhs First string. * @param __rhs Second string. * @return True if @a __lhs doesn't precede @a __rhs. False otherwise. */ template inline bool operator>=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT { return __lhs.compare(__rhs) >= 0; } /** * @brief Test if string doesn't precede C string. * @param __lhs String. * @param __rhs C string. * @return True if @a __lhs doesn't precede @a __rhs. False otherwise. */ template inline bool operator>=(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const _CharT* __rhs) { return __lhs.compare(__rhs) >= 0; } /** * @brief Test if C string doesn't precede string. * @param __lhs C string. * @param __rhs String. * @return True if @a __lhs doesn't precede @a __rhs. False otherwise. */ template inline bool operator>=(const _CharT* __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) { return __rhs.compare(__lhs) <= 0; } /** * @brief Swap contents of two strings. * @param __lhs First string. * @param __rhs Second string. * * Exchanges the contents of @a __lhs and @a __rhs in constant time. */ template inline void swap(basic_string<_CharT, _Traits, _Alloc>& __lhs, basic_string<_CharT, _Traits, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } /** * @brief Read stream into a string. * @param __is Input stream. * @param __str Buffer to store into. * @return Reference to the input stream. * * Stores characters from @a __is into @a __str until whitespace is * found, the end of the stream is encountered, or str.max_size() * is reached. If is.width() is non-zero, that is the limit on the * number of characters stored into @a __str. Any previous * contents of @a __str are erased. */ template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _Alloc>& __str); template<> basic_istream& operator>>(basic_istream& __is, basic_string& __str); /** * @brief Write string to a stream. * @param __os Output stream. * @param __str String to write out. * @return Reference to the output stream. * * Output characters of @a __str into os following the same rules as for * writing a C string. */ template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const basic_string<_CharT, _Traits, _Alloc>& __str) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 586. string inserter not a formatted function return __ostream_insert(__os, __str.data(), __str.size()); } /** * @brief Read a line from stream into a string. * @param __is Input stream. * @param __str Buffer to store into. * @param __delim Character marking end of line. * @return Reference to the input stream. * * Stores characters from @a __is into @a __str until @a __delim is * found, the end of the stream is encountered, or str.max_size() * is reached. Any previous contents of @a __str are erased. If * @a __delim is encountered, it is extracted but not stored into * @a __str. */ template basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim); /** * @brief Read a line from stream into a string. * @param __is Input stream. * @param __str Buffer to store into. * @return Reference to the input stream. * * Stores characters from is into @a __str until '\n' is * found, the end of the stream is encountered, or str.max_size() * is reached. Any previous contents of @a __str are erased. If * end of line is encountered, it is extracted but not stored into * @a __str. */ template inline basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _Alloc>& __str) { return std::getline(__is, __str, __is.widen('\n')); } #if __cplusplus >= 201103L /// Read a line from an rvalue stream into a string. template inline basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>&& __is, basic_string<_CharT, _Traits, _Alloc>& __str, _CharT __delim) { return std::getline(__is, __str, __delim); } /// Read a line from an rvalue stream into a string. template inline basic_istream<_CharT, _Traits>& getline(basic_istream<_CharT, _Traits>&& __is, basic_string<_CharT, _Traits, _Alloc>& __str) { return std::getline(__is, __str); } #endif template<> basic_istream& getline(basic_istream& __in, basic_string& __str, char __delim); #ifdef _GLIBCXX_USE_WCHAR_T template<> basic_istream& getline(basic_istream& __in, basic_string& __str, wchar_t __delim); #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if __cplusplus >= 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 #if _GLIBCXX_USE_C99_STDLIB // 21.4 Numeric Conversions [string.conversions]. inline int stoi(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtol, "stoi", __str.c_str(), __idx, __base); } inline long stol(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtol, "stol", __str.c_str(), __idx, __base); } inline unsigned long stoul(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtoul, "stoul", __str.c_str(), __idx, __base); } inline long long stoll(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtoll, "stoll", __str.c_str(), __idx, __base); } inline unsigned long long stoull(const string& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::strtoull, "stoull", __str.c_str(), __idx, __base); } // NB: strtof vs strtod. inline float stof(const string& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::strtof, "stof", __str.c_str(), __idx); } inline double stod(const string& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::strtod, "stod", __str.c_str(), __idx); } inline long double stold(const string& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::strtold, "stold", __str.c_str(), __idx); } #endif // _GLIBCXX_USE_C99_STDLIB #if _GLIBCXX_USE_C99_STDIO // NB: (v)snprintf vs sprintf. // DR 1261. inline string to_string(int __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(int), "%d", __val); } inline string to_string(unsigned __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(unsigned), "%u", __val); } inline string to_string(long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(long), "%ld", __val); } inline string to_string(unsigned long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(unsigned long), "%lu", __val); } inline string to_string(long long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(long long), "%lld", __val); } inline string to_string(unsigned long long __val) { return __gnu_cxx::__to_xstring(&std::vsnprintf, 4 * sizeof(unsigned long long), "%llu", __val); } inline string to_string(float __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vsnprintf, __n, "%f", __val); } inline string to_string(double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vsnprintf, __n, "%f", __val); } inline string to_string(long double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vsnprintf, __n, "%Lf", __val); } #endif // _GLIBCXX_USE_C99_STDIO #if defined(_GLIBCXX_USE_WCHAR_T) && _GLIBCXX_USE_C99_WCHAR inline int stoi(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstol, "stoi", __str.c_str(), __idx, __base); } inline long stol(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstol, "stol", __str.c_str(), __idx, __base); } inline unsigned long stoul(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstoul, "stoul", __str.c_str(), __idx, __base); } inline long long stoll(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstoll, "stoll", __str.c_str(), __idx, __base); } inline unsigned long long stoull(const wstring& __str, size_t* __idx = 0, int __base = 10) { return __gnu_cxx::__stoa(&std::wcstoull, "stoull", __str.c_str(), __idx, __base); } // NB: wcstof vs wcstod. inline float stof(const wstring& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::wcstof, "stof", __str.c_str(), __idx); } inline double stod(const wstring& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::wcstod, "stod", __str.c_str(), __idx); } inline long double stold(const wstring& __str, size_t* __idx = 0) { return __gnu_cxx::__stoa(&std::wcstold, "stold", __str.c_str(), __idx); } #ifndef _GLIBCXX_HAVE_BROKEN_VSWPRINTF // DR 1261. inline wstring to_wstring(int __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(int), L"%d", __val); } inline wstring to_wstring(unsigned __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(unsigned), L"%u", __val); } inline wstring to_wstring(long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(long), L"%ld", __val); } inline wstring to_wstring(unsigned long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(unsigned long), L"%lu", __val); } inline wstring to_wstring(long long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(long long), L"%lld", __val); } inline wstring to_wstring(unsigned long long __val) { return __gnu_cxx::__to_xstring(&std::vswprintf, 4 * sizeof(unsigned long long), L"%llu", __val); } inline wstring to_wstring(float __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vswprintf, __n, L"%f", __val); } inline wstring to_wstring(double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vswprintf, __n, L"%f", __val); } inline wstring to_wstring(long double __val) { const int __n = __gnu_cxx::__numeric_traits::__max_exponent10 + 20; return __gnu_cxx::__to_xstring(&std::vswprintf, __n, L"%Lf", __val); } #endif // _GLIBCXX_HAVE_BROKEN_VSWPRINTF #endif // _GLIBCXX_USE_WCHAR_T && _GLIBCXX_USE_C99_WCHAR _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* C++11 */ #if __cplusplus >= 201103L #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. #ifndef _GLIBCXX_COMPATIBILITY_CXX0X /// std::hash specialization for string. template<> struct hash : public __hash_base { size_t operator()(const string& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length()); } }; template<> struct __is_fast_hash> : std::false_type { }; #ifdef _GLIBCXX_USE_WCHAR_T /// std::hash specialization for wstring. template<> struct hash : public __hash_base { size_t operator()(const wstring& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(wchar_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif #endif /* _GLIBCXX_COMPATIBILITY_CXX0X */ #ifdef _GLIBCXX_USE_C99_STDINT_TR1 /// std::hash specialization for u16string. template<> struct hash : public __hash_base { size_t operator()(const u16string& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char16_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; /// std::hash specialization for u32string. template<> struct hash : public __hash_base { size_t operator()(const u32string& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char32_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif #if __cplusplus > 201103L #define __cpp_lib_string_udls 201304 inline namespace literals { inline namespace string_literals { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const char* __str, size_t __len) { return basic_string{__str, __len}; } #ifdef _GLIBCXX_USE_WCHAR_T _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const wchar_t* __str, size_t __len) { return basic_string{__str, __len}; } #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const char16_t* __str, size_t __len) { return basic_string{__str, __len}; } _GLIBCXX_DEFAULT_ABI_TAG inline basic_string operator""s(const char32_t* __str, size_t __len) { return basic_string{__str, __len}; } #endif #pragma GCC diagnostic pop } // inline namespace string_literals } // inline namespace literals #endif // __cplusplus > 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif /* _BASIC_STRING_H */ c++/8/bits/ptr_traits.h000064400000014742151027430570010604 0ustar00// Pointer Traits -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ptr_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _PTR_TRAITS_H #define _PTR_TRAITS_H 1 #if __cplusplus >= 201103L #include #if __cplusplus > 201703L namespace __gnu_debug { struct _Safe_iterator_base; } #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION class __undefined; // Given Template return T, otherwise invalid. template struct __get_first_arg { using type = __undefined; }; template class _Template, typename _Tp, typename... _Types> struct __get_first_arg<_Template<_Tp, _Types...>> { using type = _Tp; }; template using __get_first_arg_t = typename __get_first_arg<_Tp>::type; // Given Template and U return Template, otherwise invalid. template struct __replace_first_arg { }; template class _Template, typename _Up, typename _Tp, typename... _Types> struct __replace_first_arg<_Template<_Tp, _Types...>, _Up> { using type = _Template<_Up, _Types...>; }; template using __replace_first_arg_t = typename __replace_first_arg<_Tp, _Up>::type; template using __make_not_void = typename conditional::value, __undefined, _Tp>::type; /** * @brief Uniform interface to all pointer-like types * @ingroup pointer_abstractions */ template struct pointer_traits { private: template using __element_type = typename _Tp::element_type; template using __difference_type = typename _Tp::difference_type; template struct __rebind : __replace_first_arg<_Tp, _Up> { }; template struct __rebind<_Tp, _Up, __void_t>> { using type = typename _Tp::template rebind<_Up>; }; public: /// The pointer type. using pointer = _Ptr; /// The type pointed to. using element_type = __detected_or_t<__get_first_arg_t<_Ptr>, __element_type, _Ptr>; /// The type used to represent the difference between two pointers. using difference_type = __detected_or_t; /// A pointer to a different type. template using rebind = typename __rebind<_Ptr, _Up>::type; static _Ptr pointer_to(__make_not_void& __e) { return _Ptr::pointer_to(__e); } static_assert(!is_same::value, "pointer type defines element_type or is like SomePointer"); }; /** * @brief Partial specialization for built-in pointers. * @ingroup pointer_abstractions */ template struct pointer_traits<_Tp*> { /// The pointer type typedef _Tp* pointer; /// The type pointed to typedef _Tp element_type; /// Type used to represent the difference between two pointers typedef ptrdiff_t difference_type; template using rebind = _Up*; /** * @brief Obtain a pointer to an object * @param __r A reference to an object of type @c element_type * @return @c addressof(__r) */ static pointer pointer_to(__make_not_void& __r) noexcept { return std::addressof(__r); } }; /// Convenience alias for rebinding pointers. template using __ptr_rebind = typename pointer_traits<_Ptr>::template rebind<_Tp>; template constexpr _Tp* __to_address(_Tp* __ptr) noexcept { static_assert(!std::is_function<_Tp>::value, "not a function pointer"); return __ptr; } #if __cplusplus <= 201703L template constexpr typename std::pointer_traits<_Ptr>::element_type* __to_address(const _Ptr& __ptr) { return std::__to_address(__ptr.operator->()); } #else template constexpr auto __to_address(const _Ptr& __ptr) noexcept -> decltype(std::pointer_traits<_Ptr>::to_address(__ptr)) { return std::pointer_traits<_Ptr>::to_address(__ptr); } template constexpr auto __to_address(const _Ptr& __ptr, _None...) noexcept { if constexpr (is_base_of_v<__gnu_debug::_Safe_iterator_base, _Ptr>) return std::__to_address(__ptr.base().operator->()); else return std::__to_address(__ptr.operator->()); } /** * @brief Obtain address referenced by a pointer to an object * @param __ptr A pointer to an object * @return @c __ptr * @ingroup pointer_abstractions */ template constexpr _Tp* to_address(_Tp* __ptr) noexcept { return std::__to_address(__ptr); } /** * @brief Obtain address referenced by a pointer to an object * @param __ptr A pointer to an object * @return @c pointer_traits<_Ptr>::to_address(__ptr) if that expression is well-formed, otherwise @c to_address(__ptr.operator->()) * @ingroup pointer_abstractions */ template constexpr auto to_address(const _Ptr& __ptr) noexcept { return std::__to_address(__ptr); } #endif // C++2a _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif c++/8/bits/stl_relops.h000064400000010762151027430570010575 0ustar00// std::rel_ops implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the, 2009 Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * Copyright (c) 1996,1997 * Silicon Graphics * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file bits/stl_relops.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{utility} * * Inclusion of this file has been removed from * all of the other STL headers for safety reasons, except std_utility.h. * For more information, see the thread of about twenty messages starting * with http://gcc.gnu.org/ml/libstdc++/2001-01/msg00223.html, or * http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#faq.ambiguous_overloads * * Short summary: the rel_ops operators should be avoided for the present. */ #ifndef _STL_RELOPS_H #define _STL_RELOPS_H 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace rel_ops { /** @namespace std::rel_ops * @brief The generated relational operators are sequestered here. */ /** * @brief Defines @c != for arbitrary types, in terms of @c ==. * @param __x A thing. * @param __y Another thing. * @return __x != __y * * This function uses @c == to determine its result. */ template inline bool operator!=(const _Tp& __x, const _Tp& __y) { return !(__x == __y); } /** * @brief Defines @c > for arbitrary types, in terms of @c <. * @param __x A thing. * @param __y Another thing. * @return __x > __y * * This function uses @c < to determine its result. */ template inline bool operator>(const _Tp& __x, const _Tp& __y) { return __y < __x; } /** * @brief Defines @c <= for arbitrary types, in terms of @c <. * @param __x A thing. * @param __y Another thing. * @return __x <= __y * * This function uses @c < to determine its result. */ template inline bool operator<=(const _Tp& __x, const _Tp& __y) { return !(__y < __x); } /** * @brief Defines @c >= for arbitrary types, in terms of @c <. * @param __x A thing. * @param __y Another thing. * @return __x >= __y * * This function uses @c < to determine its result. */ template inline bool operator>=(const _Tp& __x, const _Tp& __y) { return !(__x < __y); } } // namespace rel_ops _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_RELOPS_H */ c++/8/bits/regex_constants.h000064400000034564151027430570011623 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_constants.h * @brief Constant definitions for the std regex library. * * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup regex Regular Expressions * * A facility for performing regular expression pattern matching. * @{ */ /** * @namespace std::regex_constants * @brief ISO C++-0x entities sub namespace for regex. */ namespace regex_constants { /** * @name 5.1 Regular Expression Syntax Options */ //@{ enum __syntax_option { _S_icase, _S_nosubs, _S_optimize, _S_collate, _S_ECMAScript, _S_basic, _S_extended, _S_awk, _S_grep, _S_egrep, _S_polynomial, _S_syntax_last }; /** * @brief This is a bitmask type indicating how to interpret the regex. * * The @c syntax_option_type is implementation defined but it is valid to * perform bitwise operations on these values and expect the right thing to * happen. * * A valid value of type syntax_option_type shall have exactly one of the * elements @c ECMAScript, @c basic, @c extended, @c awk, @c grep, @c egrep * %set. */ enum syntax_option_type : unsigned int { }; /** * Specifies that the matching of regular expressions against a character * sequence shall be performed without regard to case. */ _GLIBCXX17_INLINE constexpr syntax_option_type icase = static_cast(1 << _S_icase); /** * Specifies that when a regular expression is matched against a character * container sequence, no sub-expression matches are to be stored in the * supplied match_results structure. */ _GLIBCXX17_INLINE constexpr syntax_option_type nosubs = static_cast(1 << _S_nosubs); /** * Specifies that the regular expression engine should pay more attention to * the speed with which regular expressions are matched, and less to the * speed with which regular expression objects are constructed. Otherwise * it has no detectable effect on the program output. */ _GLIBCXX17_INLINE constexpr syntax_option_type optimize = static_cast(1 << _S_optimize); /** * Specifies that character ranges of the form [a-b] should be locale * sensitive. */ _GLIBCXX17_INLINE constexpr syntax_option_type collate = static_cast(1 << _S_collate); /** * Specifies that the grammar recognized by the regular expression engine is * that used by ECMAScript in ECMA-262 [Ecma International, ECMAScript * Language Specification, Standard Ecma-262, third edition, 1999], as * modified in section [28.13]. This grammar is similar to that defined * in the PERL scripting language but extended with elements found in the * POSIX regular expression grammar. */ _GLIBCXX17_INLINE constexpr syntax_option_type ECMAScript = static_cast(1 << _S_ECMAScript); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX basic regular expressions in IEEE Std 1003.1-2001, * Portable Operating System Interface (POSIX), Base Definitions and * Headers, Section 9, Regular Expressions [IEEE, Information Technology -- * Portable Operating System Interface (POSIX), IEEE Standard 1003.1-2001]. */ _GLIBCXX17_INLINE constexpr syntax_option_type basic = static_cast(1 << _S_basic); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX extended regular expressions in IEEE Std 1003.1-2001, * Portable Operating System Interface (POSIX), Base Definitions and * Headers, Section 9, Regular Expressions. */ _GLIBCXX17_INLINE constexpr syntax_option_type extended = static_cast(1 << _S_extended); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX utility awk in IEEE Std 1003.1-2001. This option is * identical to syntax_option_type extended, except that C-style escape * sequences are supported. These sequences are: * \\\\, \\a, \\b, \\f, \\n, \\r, \\t , \\v, \\&apos,, &apos,, * and \\ddd (where ddd is one, two, or three octal digits). */ _GLIBCXX17_INLINE constexpr syntax_option_type awk = static_cast(1 << _S_awk); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX utility grep in IEEE Std 1003.1-2001. This option is * identical to syntax_option_type basic, except that newlines are treated * as whitespace. */ _GLIBCXX17_INLINE constexpr syntax_option_type grep = static_cast(1 << _S_grep); /** * Specifies that the grammar recognized by the regular expression engine is * that used by POSIX utility grep when given the -E option in * IEEE Std 1003.1-2001. This option is identical to syntax_option_type * extended, except that newlines are treated as whitespace. */ _GLIBCXX17_INLINE constexpr syntax_option_type egrep = static_cast(1 << _S_egrep); /** * Extension: Ensure both space complexity of compiled regex and * time complexity execution are not exponential. * If specified in a regex with back-references, the exception * regex_constants::error_complexity will be thrown. */ _GLIBCXX17_INLINE constexpr syntax_option_type __polynomial = static_cast(1 << _S_polynomial); constexpr inline syntax_option_type operator&(syntax_option_type __a, syntax_option_type __b) { return (syntax_option_type)(static_cast(__a) & static_cast(__b)); } constexpr inline syntax_option_type operator|(syntax_option_type __a, syntax_option_type __b) { return (syntax_option_type)(static_cast(__a) | static_cast(__b)); } constexpr inline syntax_option_type operator^(syntax_option_type __a, syntax_option_type __b) { return (syntax_option_type)(static_cast(__a) ^ static_cast(__b)); } constexpr inline syntax_option_type operator~(syntax_option_type __a) { return (syntax_option_type)(~static_cast(__a)); } inline syntax_option_type& operator&=(syntax_option_type& __a, syntax_option_type __b) { return __a = __a & __b; } inline syntax_option_type& operator|=(syntax_option_type& __a, syntax_option_type __b) { return __a = __a | __b; } inline syntax_option_type& operator^=(syntax_option_type& __a, syntax_option_type __b) { return __a = __a ^ __b; } //@} /** * @name 5.2 Matching Rules * * Matching a regular expression against a sequence of characters [first, * last) proceeds according to the rules of the grammar specified for the * regular expression object, modified according to the effects listed * below for any bitmask elements set. * */ //@{ enum __match_flag { _S_not_bol, _S_not_eol, _S_not_bow, _S_not_eow, _S_any, _S_not_null, _S_continuous, _S_prev_avail, _S_sed, _S_no_copy, _S_first_only, _S_match_flag_last }; /** * @brief This is a bitmask type indicating regex matching rules. * * The @c match_flag_type is implementation defined but it is valid to * perform bitwise operations on these values and expect the right thing to * happen. */ enum match_flag_type : unsigned int { }; /** * The default matching rules. */ _GLIBCXX17_INLINE constexpr match_flag_type match_default = static_cast(0); /** * The first character in the sequence [first, last) is treated as though it * is not at the beginning of a line, so the character (^) in the regular * expression shall not match [first, first). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_bol = static_cast(1 << _S_not_bol); /** * The last character in the sequence [first, last) is treated as though it * is not at the end of a line, so the character ($) in the regular * expression shall not match [last, last). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_eol = static_cast(1 << _S_not_eol); /** * The expression \\b is not matched against the sub-sequence * [first,first). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_bow = static_cast(1 << _S_not_bow); /** * The expression \\b should not be matched against the sub-sequence * [last,last). */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_eow = static_cast(1 << _S_not_eow); /** * If more than one match is possible then any match is an acceptable * result. */ _GLIBCXX17_INLINE constexpr match_flag_type match_any = static_cast(1 << _S_any); /** * The expression does not match an empty sequence. */ _GLIBCXX17_INLINE constexpr match_flag_type match_not_null = static_cast(1 << _S_not_null); /** * The expression only matches a sub-sequence that begins at first . */ _GLIBCXX17_INLINE constexpr match_flag_type match_continuous = static_cast(1 << _S_continuous); /** * --first is a valid iterator position. When this flag is set then the * flags match_not_bol and match_not_bow are ignored by the regular * expression algorithms 28.11 and iterators 28.12. */ _GLIBCXX17_INLINE constexpr match_flag_type match_prev_avail = static_cast(1 << _S_prev_avail); /** * When a regular expression match is to be replaced by a new string, the * new string is constructed using the rules used by the ECMAScript replace * function in ECMA- 262 [Ecma International, ECMAScript Language * Specification, Standard Ecma-262, third edition, 1999], part 15.5.4.11 * String.prototype.replace. In addition, during search and replace * operations all non-overlapping occurrences of the regular expression * are located and replaced, and sections of the input that did not match * the expression are copied unchanged to the output string. * * Format strings (from ECMA-262 [15.5.4.11]): * @li $$ The dollar-sign itself ($) * @li $& The matched substring. * @li $` The portion of @a string that precedes the matched substring. * This would be match_results::prefix(). * @li $' The portion of @a string that follows the matched substring. * This would be match_results::suffix(). * @li $n The nth capture, where n is in [1,9] and $n is not followed by a * decimal digit. If n <= match_results::size() and the nth capture * is undefined, use the empty string instead. If n > * match_results::size(), the result is implementation-defined. * @li $nn The nnth capture, where nn is a two-digit decimal number on * [01, 99]. If nn <= match_results::size() and the nth capture is * undefined, use the empty string instead. If * nn > match_results::size(), the result is implementation-defined. */ _GLIBCXX17_INLINE constexpr match_flag_type format_default = static_cast(0); /** * When a regular expression match is to be replaced by a new string, the * new string is constructed using the rules used by the POSIX sed utility * in IEEE Std 1003.1- 2001 [IEEE, Information Technology -- Portable * Operating System Interface (POSIX), IEEE Standard 1003.1-2001]. */ _GLIBCXX17_INLINE constexpr match_flag_type format_sed = static_cast(1 << _S_sed); /** * During a search and replace operation, sections of the character * container sequence being searched that do not match the regular * expression shall not be copied to the output string. */ _GLIBCXX17_INLINE constexpr match_flag_type format_no_copy = static_cast(1 << _S_no_copy); /** * When specified during a search and replace operation, only the first * occurrence of the regular expression shall be replaced. */ _GLIBCXX17_INLINE constexpr match_flag_type format_first_only = static_cast(1 << _S_first_only); constexpr inline match_flag_type operator&(match_flag_type __a, match_flag_type __b) { return (match_flag_type)(static_cast(__a) & static_cast(__b)); } constexpr inline match_flag_type operator|(match_flag_type __a, match_flag_type __b) { return (match_flag_type)(static_cast(__a) | static_cast(__b)); } constexpr inline match_flag_type operator^(match_flag_type __a, match_flag_type __b) { return (match_flag_type)(static_cast(__a) ^ static_cast(__b)); } constexpr inline match_flag_type operator~(match_flag_type __a) { return (match_flag_type)(~static_cast(__a)); } inline match_flag_type& operator&=(match_flag_type& __a, match_flag_type __b) { return __a = __a & __b; } inline match_flag_type& operator|=(match_flag_type& __a, match_flag_type __b) { return __a = __a | __b; } inline match_flag_type& operator^=(match_flag_type& __a, match_flag_type __b) { return __a = __a ^ __b; } //@} } // namespace regex_constants /* @} */ // group regex _GLIBCXX_END_NAMESPACE_VERSION } // namespace std c++/8/bits/enable_special_members.h000064400000030143151027430570013042 0ustar00// -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/enable_special_members.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef _ENABLE_SPECIAL_MEMBERS_H #define _ENABLE_SPECIAL_MEMBERS_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct _Enable_default_constructor_tag { explicit constexpr _Enable_default_constructor_tag() = default; }; /** * @brief A mixin helper to conditionally enable or disable the default * constructor. * @sa _Enable_special_members */ template struct _Enable_default_constructor { constexpr _Enable_default_constructor() noexcept = default; constexpr _Enable_default_constructor(_Enable_default_constructor const&) noexcept = default; constexpr _Enable_default_constructor(_Enable_default_constructor&&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor const&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor&&) noexcept = default; // Can be used in other ctors. constexpr explicit _Enable_default_constructor(_Enable_default_constructor_tag) { } }; /** * @brief A mixin helper to conditionally enable or disable the default * destructor. * @sa _Enable_special_members */ template struct _Enable_destructor { }; /** * @brief A mixin helper to conditionally enable or disable the copy/move * special members. * @sa _Enable_special_members */ template struct _Enable_copy_move { }; /** * @brief A mixin helper to conditionally enable or disable the special * members. * * The @c _Tag type parameter is to make mixin bases unique and thus avoid * ambiguities. */ template struct _Enable_special_members : private _Enable_default_constructor<_Default, _Tag>, private _Enable_destructor<_Destructor, _Tag>, private _Enable_copy_move<_Copy, _CopyAssignment, _Move, _MoveAssignment, _Tag> { }; // Boilerplate follows. template struct _Enable_default_constructor { constexpr _Enable_default_constructor() noexcept = delete; constexpr _Enable_default_constructor(_Enable_default_constructor const&) noexcept = default; constexpr _Enable_default_constructor(_Enable_default_constructor&&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor const&) noexcept = default; _Enable_default_constructor& operator=(_Enable_default_constructor&&) noexcept = default; // Can be used in other ctors. constexpr explicit _Enable_default_constructor(_Enable_default_constructor_tag) { } }; template struct _Enable_destructor { ~_Enable_destructor() noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = default; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = default; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; template struct _Enable_copy_move { constexpr _Enable_copy_move() noexcept = default; constexpr _Enable_copy_move(_Enable_copy_move const&) noexcept = delete; constexpr _Enable_copy_move(_Enable_copy_move&&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move const&) noexcept = delete; _Enable_copy_move& operator=(_Enable_copy_move&&) noexcept = delete; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _ENABLE_SPECIAL_MEMBERS_H c++/8/bits/regex_automaton.h000064400000024742151027430570011613 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_automaton.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ // This macro defines the maximal state number a NFA can have. #ifndef _GLIBCXX_REGEX_STATE_LIMIT #define _GLIBCXX_REGEX_STATE_LIMIT 100000 #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @defgroup regex-detail Base and Implementation Classes * @ingroup regex * @{ */ typedef long _StateIdT; static const _StateIdT _S_invalid_state_id = -1; template using _Matcher = std::function; /// Operation codes that define the type of transitions within the base NFA /// that represents the regular expression. enum _Opcode : int { _S_opcode_unknown, _S_opcode_alternative, _S_opcode_repeat, _S_opcode_backref, _S_opcode_line_begin_assertion, _S_opcode_line_end_assertion, _S_opcode_word_boundary, _S_opcode_subexpr_lookahead, _S_opcode_subexpr_begin, _S_opcode_subexpr_end, _S_opcode_dummy, _S_opcode_match, _S_opcode_accept, }; struct _State_base { protected: _Opcode _M_opcode; // type of outgoing transition public: _StateIdT _M_next; // outgoing transition union // Since they are mutually exclusive. { size_t _M_subexpr; // for _S_opcode_subexpr_* size_t _M_backref_index; // for _S_opcode_backref struct { // for _S_opcode_alternative, _S_opcode_repeat and // _S_opcode_subexpr_lookahead _StateIdT _M_alt; // for _S_opcode_word_boundary or _S_opcode_subexpr_lookahead or // quantifiers (ungreedy if set true) bool _M_neg; }; // For _S_opcode_match __gnu_cxx::__aligned_membuf<_Matcher> _M_matcher_storage; }; protected: explicit _State_base(_Opcode __opcode) : _M_opcode(__opcode), _M_next(_S_invalid_state_id) { } public: bool _M_has_alt() { return _M_opcode == _S_opcode_alternative || _M_opcode == _S_opcode_repeat || _M_opcode == _S_opcode_subexpr_lookahead; } #ifdef _GLIBCXX_DEBUG std::ostream& _M_print(std::ostream& ostr) const; // Prints graphviz dot commands for state. std::ostream& _M_dot(std::ostream& __ostr, _StateIdT __id) const; #endif }; template struct _State : _State_base { typedef _Matcher<_Char_type> _MatcherT; static_assert(sizeof(_MatcherT) == sizeof(_Matcher), "std::function has the same size as " "std::function"); static_assert(alignof(_MatcherT) == alignof(_Matcher), "std::function has the same alignment as " "std::function"); explicit _State(_Opcode __opcode) : _State_base(__opcode) { if (_M_opcode() == _S_opcode_match) new (this->_M_matcher_storage._M_addr()) _MatcherT(); } _State(const _State& __rhs) : _State_base(__rhs) { if (__rhs._M_opcode() == _S_opcode_match) new (this->_M_matcher_storage._M_addr()) _MatcherT(__rhs._M_get_matcher()); } _State(_State&& __rhs) : _State_base(__rhs) { if (__rhs._M_opcode() == _S_opcode_match) new (this->_M_matcher_storage._M_addr()) _MatcherT(std::move(__rhs._M_get_matcher())); } _State& operator=(const _State&) = delete; ~_State() { if (_M_opcode() == _S_opcode_match) _M_get_matcher().~_MatcherT(); } // Since correct ctor and dtor rely on _M_opcode, it's better not to // change it over time. _Opcode _M_opcode() const { return _State_base::_M_opcode; } bool _M_matches(_Char_type __char) const { return _M_get_matcher()(__char); } _MatcherT& _M_get_matcher() { return *static_cast<_MatcherT*>(this->_M_matcher_storage._M_addr()); } const _MatcherT& _M_get_matcher() const { return *static_cast( this->_M_matcher_storage._M_addr()); } }; struct _NFA_base { typedef size_t _SizeT; typedef regex_constants::syntax_option_type _FlagT; explicit _NFA_base(_FlagT __f) : _M_flags(__f), _M_start_state(0), _M_subexpr_count(0), _M_has_backref(false) { } _NFA_base(_NFA_base&&) = default; protected: ~_NFA_base() = default; public: _FlagT _M_options() const { return _M_flags; } _StateIdT _M_start() const { return _M_start_state; } _SizeT _M_sub_count() const { return _M_subexpr_count; } std::vector _M_paren_stack; _FlagT _M_flags; _StateIdT _M_start_state; _SizeT _M_subexpr_count; bool _M_has_backref; }; template struct _NFA : _NFA_base, std::vector<_State> { typedef typename _TraitsT::char_type _Char_type; typedef _State<_Char_type> _StateT; typedef _Matcher<_Char_type> _MatcherT; _NFA(const typename _TraitsT::locale_type& __loc, _FlagT __flags) : _NFA_base(__flags) { _M_traits.imbue(__loc); } // for performance reasons _NFA objects should only be moved not copied _NFA(const _NFA&) = delete; _NFA(_NFA&&) = default; _StateIdT _M_insert_accept() { auto __ret = _M_insert_state(_StateT(_S_opcode_accept)); return __ret; } _StateIdT _M_insert_alt(_StateIdT __next, _StateIdT __alt, bool __neg __attribute__((__unused__))) { _StateT __tmp(_S_opcode_alternative); // It labels every quantifier to make greedy comparison easier in BFS // approach. __tmp._M_next = __next; __tmp._M_alt = __alt; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_repeat(_StateIdT __next, _StateIdT __alt, bool __neg) { _StateT __tmp(_S_opcode_repeat); // It labels every quantifier to make greedy comparison easier in BFS // approach. __tmp._M_next = __next; __tmp._M_alt = __alt; __tmp._M_neg = __neg; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_matcher(_MatcherT __m) { _StateT __tmp(_S_opcode_match); __tmp._M_get_matcher() = std::move(__m); return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_subexpr_begin() { auto __id = this->_M_subexpr_count++; this->_M_paren_stack.push_back(__id); _StateT __tmp(_S_opcode_subexpr_begin); __tmp._M_subexpr = __id; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_subexpr_end() { _StateT __tmp(_S_opcode_subexpr_end); __tmp._M_subexpr = this->_M_paren_stack.back(); this->_M_paren_stack.pop_back(); return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_backref(size_t __index); _StateIdT _M_insert_line_begin() { return _M_insert_state(_StateT(_S_opcode_line_begin_assertion)); } _StateIdT _M_insert_line_end() { return _M_insert_state(_StateT(_S_opcode_line_end_assertion)); } _StateIdT _M_insert_word_bound(bool __neg) { _StateT __tmp(_S_opcode_word_boundary); __tmp._M_neg = __neg; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_lookahead(_StateIdT __alt, bool __neg) { _StateT __tmp(_S_opcode_subexpr_lookahead); __tmp._M_alt = __alt; __tmp._M_neg = __neg; return _M_insert_state(std::move(__tmp)); } _StateIdT _M_insert_dummy() { return _M_insert_state(_StateT(_S_opcode_dummy)); } _StateIdT _M_insert_state(_StateT __s) { this->push_back(std::move(__s)); if (this->size() > _GLIBCXX_REGEX_STATE_LIMIT) __throw_regex_error( regex_constants::error_space, "Number of NFA states exceeds limit. Please use shorter regex " "string, or use smaller brace expression, or make " "_GLIBCXX_REGEX_STATE_LIMIT larger."); return this->size() - 1; } // Eliminate dummy node in this NFA to make it compact. void _M_eliminate_dummy(); #ifdef _GLIBCXX_DEBUG std::ostream& _M_dot(std::ostream& __ostr) const; #endif public: _TraitsT _M_traits; }; /// Describes a sequence of one or more %_State, its current start /// and end(s). This structure contains fragments of an NFA during /// construction. template class _StateSeq { public: typedef _NFA<_TraitsT> _RegexT; public: _StateSeq(_RegexT& __nfa, _StateIdT __s) : _M_nfa(__nfa), _M_start(__s), _M_end(__s) { } _StateSeq(_RegexT& __nfa, _StateIdT __s, _StateIdT __end) : _M_nfa(__nfa), _M_start(__s), _M_end(__end) { } // Append a state on *this and change *this to the new sequence. void _M_append(_StateIdT __id) { _M_nfa[_M_end]._M_next = __id; _M_end = __id; } // Append a sequence on *this and change *this to the new sequence. void _M_append(const _StateSeq& __s) { _M_nfa[_M_end]._M_next = __s._M_start; _M_end = __s._M_end; } // Clones an entire sequence. _StateSeq _M_clone(); public: _RegexT& _M_nfa; _StateIdT _M_start; _StateIdT _M_end; }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include c++/8/bits/regex_compiler.h000064400000043202151027430570011406 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_compiler.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class regex_traits; _GLIBCXX_END_NAMESPACE_CXX11 namespace __detail { /** * @addtogroup regex-detail * @{ */ template struct _BracketMatcher; /** * @brief Builds an NFA from an input iterator range. * * The %_TraitsT type should fulfill requirements [28.3]. */ template class _Compiler { public: typedef typename _TraitsT::char_type _CharT; typedef const _CharT* _IterT; typedef _NFA<_TraitsT> _RegexT; typedef regex_constants::syntax_option_type _FlagT; _Compiler(_IterT __b, _IterT __e, const typename _TraitsT::locale_type& __traits, _FlagT __flags); shared_ptr _M_get_nfa() { return std::move(_M_nfa); } private: typedef _Scanner<_CharT> _ScannerT; typedef typename _TraitsT::string_type _StringT; typedef typename _ScannerT::_TokenT _TokenT; typedef _StateSeq<_TraitsT> _StateSeqT; typedef std::stack<_StateSeqT> _StackT; typedef std::ctype<_CharT> _CtypeT; // accepts a specific token or returns false. bool _M_match_token(_TokenT __token); void _M_disjunction(); void _M_alternative(); bool _M_term(); bool _M_assertion(); bool _M_quantifier(); bool _M_atom(); bool _M_bracket_expression(); template void _M_insert_any_matcher_ecma(); template void _M_insert_any_matcher_posix(); template void _M_insert_char_matcher(); template void _M_insert_character_class_matcher(); template void _M_insert_bracket_matcher(bool __neg); // Cache of the last atom seen in a bracketed range expression. struct _BracketState { enum class _Type : char { _None, _Char, _Class } _M_type = _Type::_None; _CharT _M_char; void set(_CharT __c) noexcept { _M_type = _Type::_Char; _M_char = __c; } _GLIBCXX_NODISCARD _CharT get() const noexcept { return _M_char; } void reset(_Type __t = _Type::_None) noexcept { _M_type = __t; } explicit operator bool() const noexcept { return _M_type != _Type::_None; } // Previous token was a single character. _GLIBCXX_NODISCARD bool _M_is_char() const noexcept { return _M_type == _Type::_Char; } // Previous token was a character class, equivalent class, // collating symbol etc. _GLIBCXX_NODISCARD bool _M_is_class() const noexcept { return _M_type == _Type::_Class; } }; template using _BracketMatcher = std::__detail::_BracketMatcher<_TraitsT, __icase, __collate>; // Returns true if successfully parsed one term and should continue // compiling a bracket expression. // Returns false if the compiler should move on. template bool _M_expression_term(_BracketState& __last_char, _BracketMatcher<__icase, __collate>& __matcher); int _M_cur_int_value(int __radix); bool _M_try_char(); _StateSeqT _M_pop() { auto ret = _M_stack.top(); _M_stack.pop(); return ret; } _FlagT _M_flags; _ScannerT _M_scanner; shared_ptr<_RegexT> _M_nfa; _StringT _M_value; _StackT _M_stack; const _TraitsT& _M_traits; const _CtypeT& _M_ctype; }; template struct __has_contiguous_iter : std::false_type { }; template struct __has_contiguous_iter> : std::true_type { }; template struct __has_contiguous_iter> : std::true_type { }; template struct __is_contiguous_normal_iter : std::false_type { }; template struct __is_contiguous_normal_iter<_CharT*> : std::true_type { }; template struct __is_contiguous_normal_iter<__gnu_cxx::__normal_iterator<_Tp, _Cont>> : __has_contiguous_iter<_Cont>::type { }; template using __enable_if_contiguous_normal_iter = typename enable_if< __is_contiguous_normal_iter<_Iter>::value, std::shared_ptr> >::type; template using __disable_if_contiguous_normal_iter = typename enable_if< !__is_contiguous_normal_iter<_Iter>::value, std::shared_ptr> >::type; template inline __enable_if_contiguous_normal_iter<_FwdIter, _TraitsT> __compile_nfa(_FwdIter __first, _FwdIter __last, const typename _TraitsT::locale_type& __loc, regex_constants::syntax_option_type __flags) { size_t __len = __last - __first; const auto* __cfirst = __len ? std::__addressof(*__first) : nullptr; using _Cmplr = _Compiler<_TraitsT>; return _Cmplr(__cfirst, __cfirst + __len, __loc, __flags)._M_get_nfa(); } template inline __disable_if_contiguous_normal_iter<_FwdIter, _TraitsT> __compile_nfa(_FwdIter __first, _FwdIter __last, const typename _TraitsT::locale_type& __loc, regex_constants::syntax_option_type __flags) { const basic_string __str(__first, __last); return __compile_nfa<_TraitsT>(__str.data(), __str.data() + __str.size(), __loc, __flags); } // [28.13.14] template class _RegexTranslatorBase { public: typedef typename _TraitsT::char_type _CharT; typedef typename _TraitsT::string_type _StringT; typedef _StringT _StrTransT; explicit _RegexTranslatorBase(const _TraitsT& __traits) : _M_traits(__traits) { } _CharT _M_translate(_CharT __ch) const { if (__icase) return _M_traits.translate_nocase(__ch); else if (__collate) return _M_traits.translate(__ch); else return __ch; } _StrTransT _M_transform(_CharT __ch) const { _StrTransT __str(1, __ch); return _M_traits.transform(__str.begin(), __str.end()); } // See LWG 523. It's not efficiently implementable when _TraitsT is not // std::regex_traits<>, and __collate is true. See specializations for // implementations of other cases. bool _M_match_range(const _StrTransT& __first, const _StrTransT& __last, const _StrTransT& __s) const { return __first <= __s && __s <= __last; } protected: bool _M_in_range_icase(_CharT __first, _CharT __last, _CharT __ch) const { typedef std::ctype<_CharT> __ctype_type; const auto& __fctyp = use_facet<__ctype_type>(this->_M_traits.getloc()); auto __lower = __fctyp.tolower(__ch); auto __upper = __fctyp.toupper(__ch); return (__first <= __lower && __lower <= __last) || (__first <= __upper && __upper <= __last); } const _TraitsT& _M_traits; }; template class _RegexTranslator : public _RegexTranslatorBase<_TraitsT, __icase, __collate> { public: typedef _RegexTranslatorBase<_TraitsT, __icase, __collate> _Base; using _Base::_Base; }; template class _RegexTranslator<_TraitsT, __icase, false> : public _RegexTranslatorBase<_TraitsT, __icase, false> { public: typedef _RegexTranslatorBase<_TraitsT, __icase, false> _Base; typedef typename _Base::_CharT _CharT; typedef _CharT _StrTransT; using _Base::_Base; _StrTransT _M_transform(_CharT __ch) const { return __ch; } bool _M_match_range(_CharT __first, _CharT __last, _CharT __ch) const { if (!__icase) return __first <= __ch && __ch <= __last; return this->_M_in_range_icase(__first, __last, __ch); } }; template class _RegexTranslator, true, true> : public _RegexTranslatorBase, true, true> { public: typedef _RegexTranslatorBase, true, true> _Base; typedef typename _Base::_CharT _CharT; typedef typename _Base::_StrTransT _StrTransT; using _Base::_Base; bool _M_match_range(const _StrTransT& __first, const _StrTransT& __last, const _StrTransT& __str) const { __glibcxx_assert(__first.size() == 1); __glibcxx_assert(__last.size() == 1); __glibcxx_assert(__str.size() == 1); return this->_M_in_range_icase(__first[0], __last[0], __str[0]); } }; template class _RegexTranslator<_TraitsT, false, false> { public: typedef typename _TraitsT::char_type _CharT; typedef _CharT _StrTransT; explicit _RegexTranslator(const _TraitsT&) { } _CharT _M_translate(_CharT __ch) const { return __ch; } _StrTransT _M_transform(_CharT __ch) const { return __ch; } bool _M_match_range(_CharT __first, _CharT __last, _CharT __ch) const { return __first <= __ch && __ch <= __last; } }; template struct _AnyMatcher; template struct _AnyMatcher<_TraitsT, false, __icase, __collate> { typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; explicit _AnyMatcher(const _TraitsT& __traits) : _M_translator(__traits) { } bool operator()(_CharT __ch) const { static auto __nul = _M_translator._M_translate('\0'); return _M_translator._M_translate(__ch) != __nul; } _TransT _M_translator; }; template struct _AnyMatcher<_TraitsT, true, __icase, __collate> { typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; explicit _AnyMatcher(const _TraitsT& __traits) : _M_translator(__traits) { } bool operator()(_CharT __ch) const { return _M_apply(__ch, typename is_same<_CharT, char>::type()); } bool _M_apply(_CharT __ch, true_type) const { auto __c = _M_translator._M_translate(__ch); auto __n = _M_translator._M_translate('\n'); auto __r = _M_translator._M_translate('\r'); return __c != __n && __c != __r; } bool _M_apply(_CharT __ch, false_type) const { auto __c = _M_translator._M_translate(__ch); auto __n = _M_translator._M_translate('\n'); auto __r = _M_translator._M_translate('\r'); auto __u2028 = _M_translator._M_translate(u'\u2028'); auto __u2029 = _M_translator._M_translate(u'\u2029'); return __c != __n && __c != __r && __c != __u2028 && __c != __u2029; } _TransT _M_translator; }; template struct _CharMatcher { typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; _CharMatcher(_CharT __ch, const _TraitsT& __traits) : _M_translator(__traits), _M_ch(_M_translator._M_translate(__ch)) { } bool operator()(_CharT __ch) const { return _M_ch == _M_translator._M_translate(__ch); } _TransT _M_translator; _CharT _M_ch; }; /// Matches a character range (bracket expression) template struct _BracketMatcher { public: typedef _RegexTranslator<_TraitsT, __icase, __collate> _TransT; typedef typename _TransT::_CharT _CharT; typedef typename _TransT::_StrTransT _StrTransT; typedef typename _TraitsT::string_type _StringT; typedef typename _TraitsT::char_class_type _CharClassT; public: _BracketMatcher(bool __is_non_matching, const _TraitsT& __traits) : _M_class_set(0), _M_translator(__traits), _M_traits(__traits), _M_is_non_matching(__is_non_matching) { } bool operator()(_CharT __ch) const { _GLIBCXX_DEBUG_ASSERT(_M_is_ready); return _M_apply(__ch, _UseCache()); } void _M_add_char(_CharT __c) { _M_char_set.push_back(_M_translator._M_translate(__c)); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } _StringT _M_add_collate_element(const _StringT& __s) { auto __st = _M_traits.lookup_collatename(__s.data(), __s.data() + __s.size()); if (__st.empty()) __throw_regex_error(regex_constants::error_collate, "Invalid collate element."); _M_char_set.push_back(_M_translator._M_translate(__st[0])); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); return __st; } void _M_add_equivalence_class(const _StringT& __s) { auto __st = _M_traits.lookup_collatename(__s.data(), __s.data() + __s.size()); if (__st.empty()) __throw_regex_error(regex_constants::error_collate, "Invalid equivalence class."); __st = _M_traits.transform_primary(__st.data(), __st.data() + __st.size()); _M_equiv_set.push_back(__st); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } // __neg should be true for \D, \S and \W only. void _M_add_character_class(const _StringT& __s, bool __neg) { auto __mask = _M_traits.lookup_classname(__s.data(), __s.data() + __s.size(), __icase); if (__mask == 0) __throw_regex_error(regex_constants::error_collate, "Invalid character class."); if (!__neg) _M_class_set |= __mask; else _M_neg_class_set.push_back(__mask); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } void _M_make_range(_CharT __l, _CharT __r) { if (__l > __r) __throw_regex_error(regex_constants::error_range, "Invalid range in bracket expression."); _M_range_set.push_back(make_pair(_M_translator._M_transform(__l), _M_translator._M_transform(__r))); _GLIBCXX_DEBUG_ONLY(_M_is_ready = false); } void _M_ready() { std::sort(_M_char_set.begin(), _M_char_set.end()); auto __end = std::unique(_M_char_set.begin(), _M_char_set.end()); _M_char_set.erase(__end, _M_char_set.end()); _M_make_cache(_UseCache()); _GLIBCXX_DEBUG_ONLY(_M_is_ready = true); } private: // Currently we only use the cache for char typedef typename std::is_same<_CharT, char>::type _UseCache; static constexpr size_t _S_cache_size() { return 1ul << (sizeof(_CharT) * __CHAR_BIT__ * int(_UseCache::value)); } struct _Dummy { }; typedef typename std::conditional<_UseCache::value, std::bitset<_S_cache_size()>, _Dummy>::type _CacheT; typedef typename std::make_unsigned<_CharT>::type _UnsignedCharT; bool _M_apply(_CharT __ch, false_type) const; bool _M_apply(_CharT __ch, true_type) const { return _M_cache[static_cast<_UnsignedCharT>(__ch)]; } void _M_make_cache(true_type) { for (unsigned __i = 0; __i < _M_cache.size(); __i++) _M_cache[__i] = _M_apply(static_cast<_CharT>(__i), false_type()); } void _M_make_cache(false_type) { } private: std::vector<_CharT> _M_char_set; std::vector<_StringT> _M_equiv_set; std::vector> _M_range_set; std::vector<_CharClassT> _M_neg_class_set; _CharClassT _M_class_set; _TransT _M_translator; const _TraitsT& _M_traits; bool _M_is_non_matching; _CacheT _M_cache; #ifdef _GLIBCXX_DEBUG bool _M_is_ready = false; #endif }; //@} regex-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include c++/8/bits/allocated_ptr.h000064400000006335151027430570011225 0ustar00// Guarded Allocation -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/allocated_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _ALLOCATED_PTR_H #define _ALLOCATED_PTR_H 1 #if __cplusplus < 201103L # include #else # include # include # include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Non-standard RAII type for managing pointers obtained from allocators. template struct __allocated_ptr { using pointer = typename allocator_traits<_Alloc>::pointer; using value_type = typename allocator_traits<_Alloc>::value_type; /// Take ownership of __ptr __allocated_ptr(_Alloc& __a, pointer __ptr) noexcept : _M_alloc(std::__addressof(__a)), _M_ptr(__ptr) { } /// Convert __ptr to allocator's pointer type and take ownership of it template>> __allocated_ptr(_Alloc& __a, _Ptr __ptr) : _M_alloc(std::__addressof(__a)), _M_ptr(pointer_traits::pointer_to(*__ptr)) { } /// Transfer ownership of the owned pointer __allocated_ptr(__allocated_ptr&& __gd) noexcept : _M_alloc(__gd._M_alloc), _M_ptr(__gd._M_ptr) { __gd._M_ptr = nullptr; } /// Deallocate the owned pointer ~__allocated_ptr() { if (_M_ptr != nullptr) std::allocator_traits<_Alloc>::deallocate(*_M_alloc, _M_ptr, 1); } /// Release ownership of the owned pointer __allocated_ptr& operator=(std::nullptr_t) noexcept { _M_ptr = nullptr; return *this; } /// Get the address that the owned pointer refers to. value_type* get() { return std::__to_address(_M_ptr); } private: _Alloc* _M_alloc; pointer _M_ptr; }; /// Allocate space for a single object using __a template __allocated_ptr<_Alloc> __allocate_guarded(_Alloc& __a) { return { __a, std::allocator_traits<_Alloc>::allocate(__a, 1) }; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif c++/8/bits/atomic_lockfree_defines.h000064400000004315151027430570013227 0ustar00// -*- C++ -*- header. // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/atomic_lockfree_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{atomic} */ #ifndef _GLIBCXX_ATOMIC_LOCK_FREE_H #define _GLIBCXX_ATOMIC_LOCK_FREE_H 1 #pragma GCC system_header /** * @addtogroup atomics * @{ */ /** * Lock-free property. * * 0 indicates that the types are never lock-free. * 1 indicates that the types are sometimes lock-free. * 2 indicates that the types are always lock-free. */ #if __cplusplus >= 201103L #define ATOMIC_BOOL_LOCK_FREE __GCC_ATOMIC_BOOL_LOCK_FREE #define ATOMIC_CHAR_LOCK_FREE __GCC_ATOMIC_CHAR_LOCK_FREE #define ATOMIC_WCHAR_T_LOCK_FREE __GCC_ATOMIC_WCHAR_T_LOCK_FREE #define ATOMIC_CHAR16_T_LOCK_FREE __GCC_ATOMIC_CHAR16_T_LOCK_FREE #define ATOMIC_CHAR32_T_LOCK_FREE __GCC_ATOMIC_CHAR32_T_LOCK_FREE #define ATOMIC_SHORT_LOCK_FREE __GCC_ATOMIC_SHORT_LOCK_FREE #define ATOMIC_INT_LOCK_FREE __GCC_ATOMIC_INT_LOCK_FREE #define ATOMIC_LONG_LOCK_FREE __GCC_ATOMIC_LONG_LOCK_FREE #define ATOMIC_LLONG_LOCK_FREE __GCC_ATOMIC_LLONG_LOCK_FREE #define ATOMIC_POINTER_LOCK_FREE __GCC_ATOMIC_POINTER_LOCK_FREE #endif // @} group atomics #endif c++/8/bits/mask_array.h000064400000016653151027430570010545 0ustar00// The template and inlines for the -*- C++ -*- mask_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/mask_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _MASK_ARRAY_H #define _MASK_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Reference to selected subset of an array. * * A mask_array is a reference to the actual elements of an array specified * by a bitmask in the form of an array of bool. The way to get a * mask_array is to call operator[](valarray) on a valarray. The * returned mask_array then permits carrying operations out on the * referenced subset of elements in the original valarray. * * For example, if a mask_array is obtained using the array (false, true, * false, true) as an argument, the mask array has two elements referring * to array[1] and array[3] in the underlying array. * * @param Tp Element type. */ template class mask_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. mask_array (const mask_array&); /// Assignment operator. Assigns elements to corresponding elements /// of @a a. mask_array& operator=(const mask_array&); void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator=(const _Tp&) const; // ~mask_array (); template void operator=(const _Expr<_Dom,_Tp>&) const; template void operator*=(const _Expr<_Dom,_Tp>&) const; template void operator/=(const _Expr<_Dom,_Tp>&) const; template void operator%=(const _Expr<_Dom,_Tp>&) const; template void operator+=(const _Expr<_Dom,_Tp>&) const; template void operator-=(const _Expr<_Dom,_Tp>&) const; template void operator^=(const _Expr<_Dom,_Tp>&) const; template void operator&=(const _Expr<_Dom,_Tp>&) const; template void operator|=(const _Expr<_Dom,_Tp>&) const; template void operator<<=(const _Expr<_Dom,_Tp>&) const; template void operator>>=(const _Expr<_Dom,_Tp>&) const; private: mask_array(_Array<_Tp>, size_t, _Array); friend class valarray<_Tp>; const size_t _M_sz; const _Array _M_mask; const _Array<_Tp> _M_array; // not implemented mask_array(); }; template inline mask_array<_Tp>::mask_array(const mask_array<_Tp>& __a) : _M_sz(__a._M_sz), _M_mask(__a._M_mask), _M_array(__a._M_array) {} template inline mask_array<_Tp>::mask_array(_Array<_Tp> __a, size_t __s, _Array __m) : _M_sz(__s), _M_mask(__m), _M_array(__a) {} template inline mask_array<_Tp>& mask_array<_Tp>::operator=(const mask_array<_Tp>& __a) { std::__valarray_copy(__a._M_array, __a._M_mask, _M_sz, _M_array, _M_mask); return *this; } template inline void mask_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _M_sz, _M_mask, __t); } template inline void mask_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), __v.size(), _M_array, _M_mask); } template template inline void mask_array<_Tp>::operator=(const _Expr<_Ex, _Tp>& __e) const { std::__valarray_copy(__e, __e.size(), _M_array, _M_mask); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op, _Name) \ template \ inline void \ mask_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const \ { \ _Array_augmented_##_Name(_M_array, _M_mask, \ _Array<_Tp>(__v), __v.size()); \ } \ \ template \ template \ inline void \ mask_array<_Tp>::operator _Op##=(const _Expr<_Dom, _Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _M_mask, __e, __e.size()); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _MASK_ARRAY_H */ c++/8/bits/unique_ptr.h000064400000062600151027430570010600 0ustar00// unique_ptr implementation -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/unique_ptr.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _UNIQUE_PTR_H #define _UNIQUE_PTR_H 1 #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup pointer_abstractions * @{ */ #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template class auto_ptr; #pragma GCC diagnostic pop #endif /// Primary template of default_delete, used by unique_ptr template struct default_delete { /// Default constructor constexpr default_delete() noexcept = default; /** @brief Converting constructor. * * Allows conversion from a deleter for arrays of another type, @p _Up, * only if @p _Up* is convertible to @p _Tp*. */ template::value>::type> default_delete(const default_delete<_Up>&) noexcept { } /// Calls @c delete @p __ptr void operator()(_Tp* __ptr) const { static_assert(!is_void<_Tp>::value, "can't delete pointer to incomplete type"); static_assert(sizeof(_Tp)>0, "can't delete pointer to incomplete type"); delete __ptr; } }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 740 - omit specialization for array objects with a compile time length /// Specialization for arrays, default_delete. template struct default_delete<_Tp[]> { public: /// Default constructor constexpr default_delete() noexcept = default; /** @brief Converting constructor. * * Allows conversion from a deleter for arrays of another type, such as * a const-qualified version of @p _Tp. * * Conversions from types derived from @c _Tp are not allowed because * it is unsafe to @c delete[] an array of derived types through a * pointer to the base type. */ template::value>::type> default_delete(const default_delete<_Up[]>&) noexcept { } /// Calls @c delete[] @p __ptr template typename enable_if::value>::type operator()(_Up* __ptr) const { static_assert(sizeof(_Tp)>0, "can't delete pointer to incomplete type"); delete [] __ptr; } }; template class __uniq_ptr_impl { template struct _Ptr { using type = _Up*; }; template struct _Ptr<_Up, _Ep, __void_t::type::pointer>> { using type = typename remove_reference<_Ep>::type::pointer; }; public: using _DeleterConstraint = enable_if< __and_<__not_>, is_default_constructible<_Dp>>::value>; using pointer = typename _Ptr<_Tp, _Dp>::type; __uniq_ptr_impl() = default; __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; } template __uniq_ptr_impl(pointer __p, _Del&& __d) : _M_t(__p, std::forward<_Del>(__d)) { } pointer& _M_ptr() { return std::get<0>(_M_t); } pointer _M_ptr() const { return std::get<0>(_M_t); } _Dp& _M_deleter() { return std::get<1>(_M_t); } const _Dp& _M_deleter() const { return std::get<1>(_M_t); } void swap(__uniq_ptr_impl& __rhs) noexcept { using std::swap; swap(this->_M_ptr(), __rhs._M_ptr()); swap(this->_M_deleter(), __rhs._M_deleter()); } private: tuple _M_t; }; /// 20.7.1.2 unique_ptr for single objects. template > class unique_ptr { template using _DeleterConstraint = typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type; __uniq_ptr_impl<_Tp, _Dp> _M_t; public: using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer; using element_type = _Tp; using deleter_type = _Dp; // helper template for detecting a safe conversion from another // unique_ptr template using __safe_conversion_up = __and_< is_convertible::pointer, pointer>, __not_> >; // Constructors. /// Default constructor, creates a unique_ptr that owns nothing. template > constexpr unique_ptr() noexcept : _M_t() { } /** Takes ownership of a pointer. * * @param __p A pointer to an object of @c element_type * * The deleter will be value-initialized. */ template > explicit unique_ptr(pointer __p) noexcept : _M_t(__p) { } /** Takes ownership of a pointer. * * @param __p A pointer to an object of @c element_type * @param __d A reference to a deleter. * * The deleter will be initialized with @p __d */ unique_ptr(pointer __p, typename conditional::value, deleter_type, const deleter_type&>::type __d) noexcept : _M_t(__p, __d) { } /** Takes ownership of a pointer. * * @param __p A pointer to an object of @c element_type * @param __d An rvalue reference to a deleter. * * The deleter will be initialized with @p std::move(__d) */ unique_ptr(pointer __p, typename remove_reference::type&& __d) noexcept : _M_t(std::move(__p), std::move(__d)) { static_assert(!std::is_reference::value, "rvalue deleter bound to reference"); } /// Creates a unique_ptr that owns nothing. template > constexpr unique_ptr(nullptr_t) noexcept : _M_t() { } // Move constructors. /// Move constructor. unique_ptr(unique_ptr&& __u) noexcept : _M_t(__u.release(), std::forward(__u.get_deleter())) { } /** @brief Converting constructor from another type * * Requires that the pointer owned by @p __u is convertible to the * type of pointer owned by this object, @p __u does not own an array, * and @p __u has a compatible deleter type. */ template, typename conditional::value, is_same<_Ep, _Dp>, is_convertible<_Ep, _Dp>>::type>> unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter())) { } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" /// Converting constructor from @c auto_ptr template, is_same<_Dp, default_delete<_Tp>>>> unique_ptr(auto_ptr<_Up>&& __u) noexcept; #pragma GCC diagnostic pop #endif /// Destructor, invokes the deleter if the stored pointer is not null. ~unique_ptr() noexcept { auto& __ptr = _M_t._M_ptr(); if (__ptr != nullptr) get_deleter()(__ptr); __ptr = pointer(); } // Assignment. /** @brief Move assignment operator. * * @param __u The object to transfer ownership from. * * Invokes the deleter first if this object owns a pointer. */ unique_ptr& operator=(unique_ptr&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward(__u.get_deleter()); return *this; } /** @brief Assignment from another type. * * @param __u The object to transfer ownership from, which owns a * convertible pointer to a non-array object. * * Invokes the deleter first if this object owns a pointer. */ template typename enable_if< __and_< __safe_conversion_up<_Up, _Ep>, is_assignable >::value, unique_ptr&>::type operator=(unique_ptr<_Up, _Ep>&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward<_Ep>(__u.get_deleter()); return *this; } /// Reset the %unique_ptr to empty, invoking the deleter if necessary. unique_ptr& operator=(nullptr_t) noexcept { reset(); return *this; } // Observers. /// Dereference the stored pointer. typename add_lvalue_reference::type operator*() const { __glibcxx_assert(get() != pointer()); return *get(); } /// Return the stored pointer. pointer operator->() const noexcept { _GLIBCXX_DEBUG_PEDASSERT(get() != pointer()); return get(); } /// Return the stored pointer. pointer get() const noexcept { return _M_t._M_ptr(); } /// Return a reference to the stored deleter. deleter_type& get_deleter() noexcept { return _M_t._M_deleter(); } /// Return a reference to the stored deleter. const deleter_type& get_deleter() const noexcept { return _M_t._M_deleter(); } /// Return @c true if the stored pointer is not null. explicit operator bool() const noexcept { return get() == pointer() ? false : true; } // Modifiers. /// Release ownership of any stored pointer. pointer release() noexcept { pointer __p = get(); _M_t._M_ptr() = pointer(); return __p; } /** @brief Replace the stored pointer. * * @param __p The new pointer to store. * * The deleter will be invoked if a pointer is already owned. */ void reset(pointer __p = pointer()) noexcept { using std::swap; swap(_M_t._M_ptr(), __p); if (__p != pointer()) get_deleter()(__p); } /// Exchange the pointer and deleter with another object. void swap(unique_ptr& __u) noexcept { static_assert(__is_swappable<_Dp>::value, "deleter must be swappable"); _M_t.swap(__u._M_t); } // Disable copy from lvalue. unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; /// 20.7.1.3 unique_ptr for array objects with a runtime length // [unique.ptr.runtime] // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 740 - omit specialization for array objects with a compile time length template class unique_ptr<_Tp[], _Dp> { template using _DeleterConstraint = typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type; __uniq_ptr_impl<_Tp, _Dp> _M_t; template using __remove_cv = typename remove_cv<_Up>::type; // like is_base_of<_Tp, _Up> but false if unqualified types are the same template using __is_derived_Tp = __and_< is_base_of<_Tp, _Up>, __not_, __remove_cv<_Up>>> >; public: using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer; using element_type = _Tp; using deleter_type = _Dp; // helper template for detecting a safe conversion from another // unique_ptr template, typename _UP_pointer = typename _UPtr::pointer, typename _UP_element_type = typename _UPtr::element_type> using __safe_conversion_up = __and_< is_array<_Up>, is_same, is_same<_UP_pointer, _UP_element_type*>, is_convertible<_UP_element_type(*)[], element_type(*)[]> >; // helper template for detecting a safe conversion from a raw pointer template using __safe_conversion_raw = __and_< __or_<__or_, is_same<_Up, nullptr_t>>, __and_, is_same, is_convertible< typename remove_pointer<_Up>::type(*)[], element_type(*)[]> > > >; // Constructors. /// Default constructor, creates a unique_ptr that owns nothing. template > constexpr unique_ptr() noexcept : _M_t() { } /** Takes ownership of a pointer. * * @param __p A pointer to an array of a type safely convertible * to an array of @c element_type * * The deleter will be value-initialized. */ template, typename = typename enable_if< __safe_conversion_raw<_Up>::value, bool>::type> explicit unique_ptr(_Up __p) noexcept : _M_t(__p) { } /** Takes ownership of a pointer. * * @param __p A pointer to an array of a type safely convertible * to an array of @c element_type * @param __d A reference to a deleter. * * The deleter will be initialized with @p __d */ template::value, bool>::type> unique_ptr(_Up __p, typename conditional::value, deleter_type, const deleter_type&>::type __d) noexcept : _M_t(__p, __d) { } /** Takes ownership of a pointer. * * @param __p A pointer to an array of a type safely convertible * to an array of @c element_type * @param __d A reference to a deleter. * * The deleter will be initialized with @p std::move(__d) */ template::value, bool>::type> unique_ptr(_Up __p, typename remove_reference::type&& __d) noexcept : _M_t(std::move(__p), std::move(__d)) { static_assert(!is_reference::value, "rvalue deleter bound to reference"); } /// Move constructor. unique_ptr(unique_ptr&& __u) noexcept : _M_t(__u.release(), std::forward(__u.get_deleter())) { } /// Creates a unique_ptr that owns nothing. template > constexpr unique_ptr(nullptr_t) noexcept : _M_t() { } template, typename conditional::value, is_same<_Ep, _Dp>, is_convertible<_Ep, _Dp>>::type>> unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter())) { } /// Destructor, invokes the deleter if the stored pointer is not null. ~unique_ptr() { auto& __ptr = _M_t._M_ptr(); if (__ptr != nullptr) get_deleter()(__ptr); __ptr = pointer(); } // Assignment. /** @brief Move assignment operator. * * @param __u The object to transfer ownership from. * * Invokes the deleter first if this object owns a pointer. */ unique_ptr& operator=(unique_ptr&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward(__u.get_deleter()); return *this; } /** @brief Assignment from another type. * * @param __u The object to transfer ownership from, which owns a * convertible pointer to an array object. * * Invokes the deleter first if this object owns a pointer. */ template typename enable_if<__and_<__safe_conversion_up<_Up, _Ep>, is_assignable >::value, unique_ptr&>::type operator=(unique_ptr<_Up, _Ep>&& __u) noexcept { reset(__u.release()); get_deleter() = std::forward<_Ep>(__u.get_deleter()); return *this; } /// Reset the %unique_ptr to empty, invoking the deleter if necessary. unique_ptr& operator=(nullptr_t) noexcept { reset(); return *this; } // Observers. /// Access an element of owned array. typename std::add_lvalue_reference::type operator[](size_t __i) const { __glibcxx_assert(get() != pointer()); return get()[__i]; } /// Return the stored pointer. pointer get() const noexcept { return _M_t._M_ptr(); } /// Return a reference to the stored deleter. deleter_type& get_deleter() noexcept { return _M_t._M_deleter(); } /// Return a reference to the stored deleter. const deleter_type& get_deleter() const noexcept { return _M_t._M_deleter(); } /// Return @c true if the stored pointer is not null. explicit operator bool() const noexcept { return get() == pointer() ? false : true; } // Modifiers. /// Release ownership of any stored pointer. pointer release() noexcept { pointer __p = get(); _M_t._M_ptr() = pointer(); return __p; } /** @brief Replace the stored pointer. * * @param __p The new pointer to store. * * The deleter will be invoked if a pointer is already owned. */ template , __and_, is_pointer<_Up>, is_convertible< typename remove_pointer<_Up>::type(*)[], element_type(*)[] > > > >> void reset(_Up __p) noexcept { pointer __ptr = __p; using std::swap; swap(_M_t._M_ptr(), __ptr); if (__ptr != nullptr) get_deleter()(__ptr); } void reset(nullptr_t = nullptr) noexcept { reset(pointer()); } /// Exchange the pointer and deleter with another object. void swap(unique_ptr& __u) noexcept { static_assert(__is_swappable<_Dp>::value, "deleter must be swappable"); _M_t.swap(__u._M_t); } // Disable copy from lvalue. unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete; }; template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__is_swappable<_Dp>::value>::type #else void #endif swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) noexcept { __x.swap(__y); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if::value>::type swap(unique_ptr<_Tp, _Dp>&, unique_ptr<_Tp, _Dp>&) = delete; #endif template inline bool operator==(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return __x.get() == __y.get(); } template inline bool operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept { return !__x; } template inline bool operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept { return !__x; } template inline bool operator!=(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return __x.get() != __y.get(); } template inline bool operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept { return (bool)__x; } template inline bool operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept { return (bool)__x; } template inline bool operator<(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { typedef typename std::common_type::pointer, typename unique_ptr<_Up, _Ep>::pointer>::type _CT; return std::less<_CT>()(__x.get(), __y.get()); } template inline bool operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return std::less::pointer>()(__x.get(), nullptr); } template inline bool operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return std::less::pointer>()(nullptr, __x.get()); } template inline bool operator<=(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return !(__y < __x); } template inline bool operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return !(nullptr < __x); } template inline bool operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return !(__x < nullptr); } template inline bool operator>(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return (__y < __x); } template inline bool operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return std::less::pointer>()(nullptr, __x.get()); } template inline bool operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return std::less::pointer>()(__x.get(), nullptr); } template inline bool operator>=(const unique_ptr<_Tp, _Dp>& __x, const unique_ptr<_Up, _Ep>& __y) { return !(__x < __y); } template inline bool operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) { return !(__x < nullptr); } template inline bool operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) { return !(nullptr < __x); } /// std::hash specialization for unique_ptr. template struct hash> : public __hash_base>, private __poison_hash::pointer> { size_t operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept { typedef unique_ptr<_Tp, _Dp> _UP; return std::hash()(__u.get()); } }; #if __cplusplus > 201103L #define __cpp_lib_make_unique 201304 template struct _MakeUniq { typedef unique_ptr<_Tp> __single_object; }; template struct _MakeUniq<_Tp[]> { typedef unique_ptr<_Tp[]> __array; }; template struct _MakeUniq<_Tp[_Bound]> { struct __invalid_type { }; }; /// std::make_unique for single objects template inline typename _MakeUniq<_Tp>::__single_object make_unique(_Args&&... __args) { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); } /// std::make_unique for arrays of unknown bound template inline typename _MakeUniq<_Tp>::__array make_unique(size_t __num) { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); } /// Disable std::make_unique for arrays of known bound template inline typename _MakeUniq<_Tp>::__invalid_type make_unique(_Args&&...) = delete; #endif // @} group pointer_abstractions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _UNIQUE_PTR_H */ c++/8/bits/exception.h000064400000004350151027430570010401 0ustar00// Exception Handling support header for -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/exception.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. */ #ifndef __EXCEPTION_H #define __EXCEPTION_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #include extern "C++" { namespace std { /** * @defgroup exceptions Exceptions * @ingroup diagnostics * * Classes and functions for reporting errors via exception classes. * @{ */ /** * @brief Base class for all library exceptions. * * This is the base class for all exceptions thrown by the standard * library, and by certain language expressions. You are free to derive * your own %exception classes, or use a different hierarchy, or to * throw non-class data (e.g., fundamental types). */ class exception { public: exception() _GLIBCXX_USE_NOEXCEPT { } virtual ~exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; /** Returns a C-style character string describing the general cause * of the current error. */ virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; }; } // namespace std } #pragma GCC visibility pop #endif c++/8/bits/postypes.h000064400000020020151027430570010261 0ustar00// Position types -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/postypes.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ // // ISO C++ 14882: 27.4.1 - Types // ISO C++ 14882: 27.4.3 - Template class fpos // #ifndef _GLIBCXX_POSTYPES_H #define _GLIBCXX_POSTYPES_H 1 #pragma GCC system_header #include // For mbstate_t // XXX If is really needed, make sure to define the macros // before including it, in order not to break (and // in C++11). Reconsider all this as soon as possible... #if (defined(_GLIBCXX_HAVE_INT64_T) && !defined(_GLIBCXX_HAVE_INT64_T_LONG) \ && !defined(_GLIBCXX_HAVE_INT64_T_LONG_LONG)) #ifndef __STDC_LIMIT_MACROS # define _UNDEF__STDC_LIMIT_MACROS # define __STDC_LIMIT_MACROS #endif #ifndef __STDC_CONSTANT_MACROS # define _UNDEF__STDC_CONSTANT_MACROS # define __STDC_CONSTANT_MACROS #endif #include // For int64_t #ifdef _UNDEF__STDC_LIMIT_MACROS # undef __STDC_LIMIT_MACROS # undef _UNDEF__STDC_LIMIT_MACROS #endif #ifdef _UNDEF__STDC_CONSTANT_MACROS # undef __STDC_CONSTANT_MACROS # undef _UNDEF__STDC_CONSTANT_MACROS #endif #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // The types streamoff, streampos and wstreampos and the class // template fpos<> are described in clauses 21.1.2, 21.1.3, 27.1.2, // 27.2, 27.4.1, 27.4.3 and D.6. Despite all this verbiage, the // behaviour of these types is mostly implementation defined or // unspecified. The behaviour in this implementation is as noted // below. /** * @brief Type used by fpos, char_traits, and char_traits. * * In clauses 21.1.3.1 and 27.4.1 streamoff is described as an * implementation defined type. * Note: In versions of GCC up to and including GCC 3.3, streamoff * was typedef long. */ #ifdef _GLIBCXX_HAVE_INT64_T_LONG typedef long streamoff; #elif defined(_GLIBCXX_HAVE_INT64_T_LONG_LONG) typedef long long streamoff; #elif defined(_GLIBCXX_HAVE_INT64_T) typedef int64_t streamoff; #else typedef long long streamoff; #endif /// Integral type for I/O operation counts and buffer sizes. typedef ptrdiff_t streamsize; // Signed integral type /** * @brief Class representing stream positions. * * The standard places no requirements upon the template parameter StateT. * In this implementation StateT must be DefaultConstructible, * CopyConstructible and Assignable. The standard only requires that fpos * should contain a member of type StateT. In this implementation it also * contains an offset stored as a signed integer. * * @param StateT Type passed to and returned from state(). */ template class fpos { private: streamoff _M_off; _StateT _M_state; public: // The standard doesn't require that fpos objects can be default // constructed. This implementation provides a default // constructor that initializes the offset to 0 and default // constructs the state. fpos() : _M_off(0), _M_state() { } // The standard requires that fpos objects can be constructed // from streamoff objects using the constructor syntax, and // fails to give any meaningful semantics. In this // implementation implicit conversion is also allowed, and this // constructor stores the streamoff as the offset and default // constructs the state. /// Construct position from offset. fpos(streamoff __off) : _M_off(__off), _M_state() { } /// Convert to streamoff. operator streamoff() const { return _M_off; } /// Remember the value of @a st. void state(_StateT __st) { _M_state = __st; } /// Return the last set value of @a st. _StateT state() const { return _M_state; } // The standard requires that this operator must be defined, but // gives no semantics. In this implementation it just adds its // argument to the stored offset and returns *this. /// Add offset to this position. fpos& operator+=(streamoff __off) { _M_off += __off; return *this; } // The standard requires that this operator must be defined, but // gives no semantics. In this implementation it just subtracts // its argument from the stored offset and returns *this. /// Subtract offset from this position. fpos& operator-=(streamoff __off) { _M_off -= __off; return *this; } // The standard requires that this operator must be defined, but // defines its semantics only in terms of operator-. In this // implementation it constructs a copy of *this, adds the // argument to that copy using operator+= and then returns the // copy. /// Add position and offset. fpos operator+(streamoff __off) const { fpos __pos(*this); __pos += __off; return __pos; } // The standard requires that this operator must be defined, but // defines its semantics only in terms of operator+. In this // implementation it constructs a copy of *this, subtracts the // argument from that copy using operator-= and then returns the // copy. /// Subtract offset from position. fpos operator-(streamoff __off) const { fpos __pos(*this); __pos -= __off; return __pos; } // The standard requires that this operator must be defined, but // defines its semantics only in terms of operator+. In this // implementation it returns the difference between the offset // stored in *this and in the argument. /// Subtract position to return offset. streamoff operator-(const fpos& __other) const { return _M_off - __other._M_off; } }; // The standard only requires that operator== must be an // equivalence relation. In this implementation two fpos // objects belong to the same equivalence class if the contained // offsets compare equal. /// Test if equivalent to another position. template inline bool operator==(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs) { return streamoff(__lhs) == streamoff(__rhs); } template inline bool operator!=(const fpos<_StateT>& __lhs, const fpos<_StateT>& __rhs) { return streamoff(__lhs) != streamoff(__rhs); } // Clauses 21.1.3.1 and 21.1.3.2 describe streampos and wstreampos // as implementation defined types, but clause 27.2 requires that // they must both be typedefs for fpos /// File position for char streams. typedef fpos streampos; /// File position for wchar_t streams. typedef fpos wstreampos; #if __cplusplus >= 201103L /// File position for char16_t streams. typedef fpos u16streampos; /// File position for char32_t streams. typedef fpos u32streampos; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/valarray_array.h000064400000052457151027430570011435 0ustar00// The template and inlines for the -*- C++ -*- internal _Array helper class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_ARRAY_H #define _VALARRAY_ARRAY_H 1 #pragma GCC system_header #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // // Helper functions on raw pointers // // We get memory by the old fashion way inline void* __valarray_get_memory(size_t __n) { return operator new(__n); } template inline _Tp*__restrict__ __valarray_get_storage(size_t __n) { return static_cast<_Tp*__restrict__> (std::__valarray_get_memory(__n * sizeof(_Tp))); } // Return memory to the system inline void __valarray_release_memory(void* __p) { operator delete(__p); } // Turn a raw-memory into an array of _Tp filled with _Tp() // This is required in 'valarray v(n);' template struct _Array_default_ctor { // Please note that this isn't exception safe. But // valarrays aren't required to be exception safe. inline static void _S_do_it(_Tp* __b, _Tp* __e) { while (__b != __e) new(__b++) _Tp(); } }; template struct _Array_default_ctor<_Tp, true> { // For fundamental types, it suffices to say 'memset()' inline static void _S_do_it(_Tp* __b, _Tp* __e) { __builtin_memset(__b, 0, (__e - __b) * sizeof(_Tp)); } }; template inline void __valarray_default_construct(_Tp* __b, _Tp* __e) { _Array_default_ctor<_Tp, __is_scalar<_Tp>::__value>::_S_do_it(__b, __e); } // Turn a raw-memory into an array of _Tp filled with __t // This is the required in valarray v(n, t). Also // used in valarray<>::resize(). template struct _Array_init_ctor { // Please note that this isn't exception safe. But // valarrays aren't required to be exception safe. inline static void _S_do_it(_Tp* __b, _Tp* __e, const _Tp __t) { while (__b != __e) new(__b++) _Tp(__t); } }; template struct _Array_init_ctor<_Tp, true> { inline static void _S_do_it(_Tp* __b, _Tp* __e, const _Tp __t) { while (__b != __e) *__b++ = __t; } }; template inline void __valarray_fill_construct(_Tp* __b, _Tp* __e, const _Tp __t) { _Array_init_ctor<_Tp, __is_trivial(_Tp)>::_S_do_it(__b, __e, __t); } // // copy-construct raw array [__o, *) from plain array [__b, __e) // We can't just say 'memcpy()' // template struct _Array_copy_ctor { // Please note that this isn't exception safe. But // valarrays aren't required to be exception safe. inline static void _S_do_it(const _Tp* __b, const _Tp* __e, _Tp* __restrict__ __o) { while (__b != __e) new(__o++) _Tp(*__b++); } }; template struct _Array_copy_ctor<_Tp, true> { inline static void _S_do_it(const _Tp* __b, const _Tp* __e, _Tp* __restrict__ __o) { if (__b) __builtin_memcpy(__o, __b, (__e - __b) * sizeof(_Tp)); } }; template inline void __valarray_copy_construct(const _Tp* __b, const _Tp* __e, _Tp* __restrict__ __o) { _Array_copy_ctor<_Tp, __is_trivial(_Tp)>::_S_do_it(__b, __e, __o); } // copy-construct raw array [__o, *) from strided array __a[<__n : __s>] template inline void __valarray_copy_construct (const _Tp* __restrict__ __a, size_t __n, size_t __s, _Tp* __restrict__ __o) { if (__is_trivial(_Tp)) while (__n--) { *__o++ = *__a; __a += __s; } else while (__n--) { new(__o++) _Tp(*__a); __a += __s; } } // copy-construct raw array [__o, *) from indexed array __a[__i[<__n>]] template inline void __valarray_copy_construct (const _Tp* __restrict__ __a, const size_t* __restrict__ __i, _Tp* __restrict__ __o, size_t __n) { if (__is_trivial(_Tp)) while (__n--) *__o++ = __a[*__i++]; else while (__n--) new (__o++) _Tp(__a[*__i++]); } // Do the necessary cleanup when we're done with arrays. template inline void __valarray_destroy_elements(_Tp* __b, _Tp* __e) { if (!__is_trivial(_Tp)) while (__b != __e) { __b->~_Tp(); ++__b; } } // Fill a plain array __a[<__n>] with __t template inline void __valarray_fill(_Tp* __restrict__ __a, size_t __n, const _Tp& __t) { while (__n--) *__a++ = __t; } // fill strided array __a[<__n-1 : __s>] with __t template inline void __valarray_fill(_Tp* __restrict__ __a, size_t __n, size_t __s, const _Tp& __t) { for (size_t __i = 0; __i < __n; ++__i, __a += __s) *__a = __t; } // fill indirect array __a[__i[<__n>]] with __i template inline void __valarray_fill(_Tp* __restrict__ __a, const size_t* __restrict__ __i, size_t __n, const _Tp& __t) { for (size_t __j = 0; __j < __n; ++__j, ++__i) __a[*__i] = __t; } // copy plain array __a[<__n>] in __b[<__n>] // For non-fundamental types, it is wrong to say 'memcpy()' template struct _Array_copier { inline static void _S_do_it(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b) { while(__n--) *__b++ = *__a++; } }; template struct _Array_copier<_Tp, true> { inline static void _S_do_it(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b) { if (__n != 0) __builtin_memcpy(__b, __a, __n * sizeof (_Tp)); } }; // Copy a plain array __a[<__n>] into a play array __b[<>] template inline void __valarray_copy(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b) { _Array_copier<_Tp, __is_trivial(_Tp)>::_S_do_it(__a, __n, __b); } // Copy strided array __a[<__n : __s>] in plain __b[<__n>] template inline void __valarray_copy(const _Tp* __restrict__ __a, size_t __n, size_t __s, _Tp* __restrict__ __b) { for (size_t __i = 0; __i < __n; ++__i, ++__b, __a += __s) *__b = *__a; } // Copy a plain array __a[<__n>] into a strided array __b[<__n : __s>] template inline void __valarray_copy(const _Tp* __restrict__ __a, _Tp* __restrict__ __b, size_t __n, size_t __s) { for (size_t __i = 0; __i < __n; ++__i, ++__a, __b += __s) *__b = *__a; } // Copy strided array __src[<__n : __s1>] into another // strided array __dst[< : __s2>]. Their sizes must match. template inline void __valarray_copy(const _Tp* __restrict__ __src, size_t __n, size_t __s1, _Tp* __restrict__ __dst, size_t __s2) { for (size_t __i = 0; __i < __n; ++__i) __dst[__i * __s2] = __src[__i * __s1]; } // Copy an indexed array __a[__i[<__n>]] in plain array __b[<__n>] template inline void __valarray_copy(const _Tp* __restrict__ __a, const size_t* __restrict__ __i, _Tp* __restrict__ __b, size_t __n) { for (size_t __j = 0; __j < __n; ++__j, ++__b, ++__i) *__b = __a[*__i]; } // Copy a plain array __a[<__n>] in an indexed array __b[__i[<__n>]] template inline void __valarray_copy(const _Tp* __restrict__ __a, size_t __n, _Tp* __restrict__ __b, const size_t* __restrict__ __i) { for (size_t __j = 0; __j < __n; ++__j, ++__a, ++__i) __b[*__i] = *__a; } // Copy the __n first elements of an indexed array __src[<__i>] into // another indexed array __dst[<__j>]. template inline void __valarray_copy(const _Tp* __restrict__ __src, size_t __n, const size_t* __restrict__ __i, _Tp* __restrict__ __dst, const size_t* __restrict__ __j) { for (size_t __k = 0; __k < __n; ++__k) __dst[*__j++] = __src[*__i++]; } // // Compute the sum of elements in range [__f, __l) which must not be empty. // This is a naive algorithm. It suffers from cancelling. // In the future try to specialize for _Tp = float, double, long double // using a more accurate algorithm. // template inline _Tp __valarray_sum(const _Tp* __f, const _Tp* __l) { _Tp __r = *__f++; while (__f != __l) __r += *__f++; return __r; } // Compute the product of all elements in range [__f, __l) template inline _Tp __valarray_product(const _Tp* __f, const _Tp* __l) { _Tp __r = _Tp(1); while (__f != __l) __r = __r * *__f++; return __r; } // Compute the min/max of an array-expression template inline typename _Ta::value_type __valarray_min(const _Ta& __a) { size_t __s = __a.size(); typedef typename _Ta::value_type _Value_type; _Value_type __r = __s == 0 ? _Value_type() : __a[0]; for (size_t __i = 1; __i < __s; ++__i) { _Value_type __t = __a[__i]; if (__t < __r) __r = __t; } return __r; } template inline typename _Ta::value_type __valarray_max(const _Ta& __a) { size_t __s = __a.size(); typedef typename _Ta::value_type _Value_type; _Value_type __r = __s == 0 ? _Value_type() : __a[0]; for (size_t __i = 1; __i < __s; ++__i) { _Value_type __t = __a[__i]; if (__t > __r) __r = __t; } return __r; } // // Helper class _Array, first layer of valarray abstraction. // All operations on valarray should be forwarded to this class // whenever possible. -- gdr // template struct _Array { explicit _Array(size_t); explicit _Array(_Tp* const __restrict__); explicit _Array(const valarray<_Tp>&); _Array(const _Tp* __restrict__, size_t); _Tp* begin() const; _Tp* const __restrict__ _M_data; }; // Copy-construct plain array __b[<__n>] from indexed array __a[__i[<__n>]] template inline void __valarray_copy_construct(_Array<_Tp> __a, _Array __i, _Array<_Tp> __b, size_t __n) { std::__valarray_copy_construct(__a._M_data, __i._M_data, __b._M_data, __n); } // Copy-construct plain array __b[<__n>] from strided array __a[<__n : __s>] template inline void __valarray_copy_construct(_Array<_Tp> __a, size_t __n, size_t __s, _Array<_Tp> __b) { std::__valarray_copy_construct(__a._M_data, __n, __s, __b._M_data); } template inline void __valarray_fill (_Array<_Tp> __a, size_t __n, const _Tp& __t) { std::__valarray_fill(__a._M_data, __n, __t); } template inline void __valarray_fill(_Array<_Tp> __a, size_t __n, size_t __s, const _Tp& __t) { std::__valarray_fill(__a._M_data, __n, __s, __t); } template inline void __valarray_fill(_Array<_Tp> __a, _Array __i, size_t __n, const _Tp& __t) { std::__valarray_fill(__a._M_data, __i._M_data, __n, __t); } // Copy a plain array __a[<__n>] into a play array __b[<>] template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b) { std::__valarray_copy(__a._M_data, __n, __b._M_data); } // Copy strided array __a[<__n : __s>] in plain __b[<__n>] template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, size_t __s, _Array<_Tp> __b) { std::__valarray_copy(__a._M_data, __n, __s, __b._M_data); } // Copy a plain array __a[<__n>] into a strided array __b[<__n : __s>] template inline void __valarray_copy(_Array<_Tp> __a, _Array<_Tp> __b, size_t __n, size_t __s) { __valarray_copy(__a._M_data, __b._M_data, __n, __s); } // Copy strided array __src[<__n : __s1>] into another // strided array __dst[< : __s2>]. Their sizes must match. template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, size_t __s1, _Array<_Tp> __b, size_t __s2) { std::__valarray_copy(__a._M_data, __n, __s1, __b._M_data, __s2); } // Copy an indexed array __a[__i[<__n>]] in plain array __b[<__n>] template inline void __valarray_copy(_Array<_Tp> __a, _Array __i, _Array<_Tp> __b, size_t __n) { std::__valarray_copy(__a._M_data, __i._M_data, __b._M_data, __n); } // Copy a plain array __a[<__n>] in an indexed array __b[__i[<__n>]] template inline void __valarray_copy(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b, _Array __i) { std::__valarray_copy(__a._M_data, __n, __b._M_data, __i._M_data); } // Copy the __n first elements of an indexed array __src[<__i>] into // another indexed array __dst[<__j>]. template inline void __valarray_copy(_Array<_Tp> __src, size_t __n, _Array __i, _Array<_Tp> __dst, _Array __j) { std::__valarray_copy(__src._M_data, __n, __i._M_data, __dst._M_data, __j._M_data); } template inline _Array<_Tp>::_Array(size_t __n) : _M_data(__valarray_get_storage<_Tp>(__n)) { std::__valarray_default_construct(_M_data, _M_data + __n); } template inline _Array<_Tp>::_Array(_Tp* const __restrict__ __p) : _M_data (__p) {} template inline _Array<_Tp>::_Array(const valarray<_Tp>& __v) : _M_data (__v._M_data) {} template inline _Array<_Tp>::_Array(const _Tp* __restrict__ __b, size_t __s) : _M_data(__valarray_get_storage<_Tp>(__s)) { std::__valarray_copy_construct(__b, __s, _M_data); } template inline _Tp* _Array<_Tp>::begin () const { return _M_data; } #define _DEFINE_ARRAY_FUNCTION(_Op, _Name) \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, const _Tp& __t) \ { \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __n; ++__p) \ *__p _Op##= __t; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, _Array<_Tp> __b) \ { \ _Tp* __p = __a._M_data; \ for (_Tp* __q = __b._M_data; __q < __b._M_data + __n; ++__p, ++__q) \ *__p _Op##= *__q; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ _Tp* __p(__a._M_data); \ for (size_t __i = 0; __i < __n; ++__i, ++__p) \ *__p _Op##= __e[__i]; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, size_t __s, \ _Array<_Tp> __b) \ { \ _Tp* __q(__b._M_data); \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __s * __n; \ __p += __s, ++__q) \ *__p _Op##= *__q; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array<_Tp> __b, \ size_t __n, size_t __s) \ { \ _Tp* __q(__b._M_data); \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __n; \ ++__p, __q += __s) \ *__p _Op##= *__q; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __s, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ _Tp* __p(__a._M_data); \ for (size_t __i = 0; __i < __n; ++__i, __p += __s) \ *__p _Op##= __e[__i]; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __i, \ _Array<_Tp> __b, size_t __n) \ { \ _Tp* __q(__b._M_data); \ for (size_t* __j = __i._M_data; __j < __i._M_data + __n; \ ++__j, ++__q) \ __a._M_data[*__j] _Op##= *__q; \ } \ \ template \ inline void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, \ _Array<_Tp> __b, _Array __i) \ { \ _Tp* __p(__a._M_data); \ for (size_t* __j = __i._M_data; __j<__i._M_data + __n; \ ++__j, ++__p) \ *__p _Op##= __b._M_data[*__j]; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __i, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ size_t* __j(__i._M_data); \ for (size_t __k = 0; __k<__n; ++__k, ++__j) \ __a._M_data[*__j] _Op##= __e[__k]; \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __m, \ _Array<_Tp> __b, size_t __n) \ { \ bool* __ok(__m._M_data); \ _Tp* __p(__a._M_data); \ for (_Tp* __q = __b._M_data; __q < __b._M_data + __n; \ ++__q, ++__ok, ++__p) \ { \ while (! *__ok) \ { \ ++__ok; \ ++__p; \ } \ *__p _Op##= *__q; \ } \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, size_t __n, \ _Array<_Tp> __b, _Array __m) \ { \ bool* __ok(__m._M_data); \ _Tp* __q(__b._M_data); \ for (_Tp* __p = __a._M_data; __p < __a._M_data + __n; \ ++__p, ++__ok, ++__q) \ { \ while (! *__ok) \ { \ ++__ok; \ ++__q; \ } \ *__p _Op##= *__q; \ } \ } \ \ template \ void \ _Array_augmented_##_Name(_Array<_Tp> __a, _Array __m, \ const _Expr<_Dom, _Tp>& __e, size_t __n) \ { \ bool* __ok(__m._M_data); \ _Tp* __p(__a._M_data); \ for (size_t __i = 0; __i < __n; ++__i, ++__ok, ++__p) \ { \ while (! *__ok) \ { \ ++__ok; \ ++__p; \ } \ *__p _Op##= __e[__i]; \ } \ } _DEFINE_ARRAY_FUNCTION(+, __plus) _DEFINE_ARRAY_FUNCTION(-, __minus) _DEFINE_ARRAY_FUNCTION(*, __multiplies) _DEFINE_ARRAY_FUNCTION(/, __divides) _DEFINE_ARRAY_FUNCTION(%, __modulus) _DEFINE_ARRAY_FUNCTION(^, __bitwise_xor) _DEFINE_ARRAY_FUNCTION(|, __bitwise_or) _DEFINE_ARRAY_FUNCTION(&, __bitwise_and) _DEFINE_ARRAY_FUNCTION(<<, __shift_left) _DEFINE_ARRAY_FUNCTION(>>, __shift_right) #undef _DEFINE_ARRAY_FUNCTION _GLIBCXX_END_NAMESPACE_VERSION } // namespace # include #endif /* _ARRAY_H */ c++/8/bits/slice_array.h000064400000022204151027430570010676 0ustar00// The template and inlines for the -*- C++ -*- slice_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/slice_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _SLICE_ARRAY_H #define _SLICE_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Class defining one-dimensional subset of an array. * * The slice class represents a one-dimensional subset of an array, * specified by three parameters: start offset, size, and stride. The * start offset is the index of the first element of the array that is part * of the subset. The size is the total number of elements in the subset. * Stride is the distance between each successive array element to include * in the subset. * * For example, with an array of size 10, and a slice with offset 1, size 3 * and stride 2, the subset consists of array elements 1, 3, and 5. */ class slice { public: /// Construct an empty slice. slice(); /** * @brief Construct a slice. * * @param __o Offset in array of first element. * @param __d Number of elements in slice. * @param __s Stride between array elements. */ slice(size_t __o, size_t __d, size_t __s); /// Return array offset of first slice element. size_t start() const; /// Return size of slice. size_t size() const; /// Return array stride of slice. size_t stride() const; private: size_t _M_off; // offset size_t _M_sz; // size size_t _M_st; // stride unit }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 543. valarray slice default constructor inline slice::slice() : _M_off(0), _M_sz(0), _M_st(0) {} inline slice::slice(size_t __o, size_t __d, size_t __s) : _M_off(__o), _M_sz(__d), _M_st(__s) {} inline size_t slice::start() const { return _M_off; } inline size_t slice::size() const { return _M_sz; } inline size_t slice::stride() const { return _M_st; } /** * @brief Reference to one-dimensional subset of an array. * * A slice_array is a reference to the actual elements of an array * specified by a slice. The way to get a slice_array is to call * operator[](slice) on a valarray. The returned slice_array then permits * carrying operations out on the referenced subset of elements in the * original valarray. For example, operator+=(valarray) will add values * to the subset of elements in the underlying valarray this slice_array * refers to. * * @param Tp Element type. */ template class slice_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. slice_array(const slice_array&); /// Assignment operator. Assigns slice elements to corresponding /// elements of @a a. slice_array& operator=(const slice_array&); /// Assign slice elements to corresponding elements of @a v. void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator=(const _Tp &) const; // ~slice_array (); template void operator=(const _Expr<_Dom, _Tp>&) const; template void operator*=(const _Expr<_Dom, _Tp>&) const; template void operator/=(const _Expr<_Dom, _Tp>&) const; template void operator%=(const _Expr<_Dom, _Tp>&) const; template void operator+=(const _Expr<_Dom, _Tp>&) const; template void operator-=(const _Expr<_Dom, _Tp>&) const; template void operator^=(const _Expr<_Dom, _Tp>&) const; template void operator&=(const _Expr<_Dom, _Tp>&) const; template void operator|=(const _Expr<_Dom, _Tp>&) const; template void operator<<=(const _Expr<_Dom, _Tp>&) const; template void operator>>=(const _Expr<_Dom, _Tp>&) const; private: friend class valarray<_Tp>; slice_array(_Array<_Tp>, const slice&); const size_t _M_sz; const size_t _M_stride; const _Array<_Tp> _M_array; // not implemented slice_array(); }; template inline slice_array<_Tp>::slice_array(_Array<_Tp> __a, const slice& __s) : _M_sz(__s.size()), _M_stride(__s.stride()), _M_array(__a.begin() + __s.start()) {} template inline slice_array<_Tp>::slice_array(const slice_array<_Tp>& __a) : _M_sz(__a._M_sz), _M_stride(__a._M_stride), _M_array(__a._M_array) {} // template // inline slice_array<_Tp>::~slice_array () {} template inline slice_array<_Tp>& slice_array<_Tp>::operator=(const slice_array<_Tp>& __a) { std::__valarray_copy(__a._M_array, __a._M_sz, __a._M_stride, _M_array, _M_stride); return *this; } template inline void slice_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _M_sz, _M_stride, __t); } template inline void slice_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), _M_array, _M_sz, _M_stride); } template template inline void slice_array<_Tp>::operator=(const _Expr<_Dom,_Tp>& __e) const { std::__valarray_copy(__e, _M_sz, _M_array, _M_stride); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op,_Name) \ template \ inline void \ slice_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const \ { \ _Array_augmented_##_Name(_M_array, _M_sz, _M_stride, _Array<_Tp>(__v));\ } \ \ template \ template \ inline void \ slice_array<_Tp>::operator _Op##=(const _Expr<_Dom,_Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _M_stride, __e, _M_sz); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _SLICE_ARRAY_H */ c++/8/bits/quoted_string.h000064400000011675151027430570011302 0ustar00// Helpers for quoted stream manipulators -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/quoted_string.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iomanip} */ #ifndef _GLIBCXX_QUOTED_STRING_H #define _GLIBCXX_QUOTED_STRING_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /** * @brief Struct for delimited strings. */ template struct _Quoted_string { static_assert(is_reference<_String>::value || is_pointer<_String>::value, "String type must be pointer or reference"); _Quoted_string(_String __str, _CharT __del, _CharT __esc) : _M_string(__str), _M_delim{__del}, _M_escape{__esc} { } _Quoted_string& operator=(_Quoted_string&) = delete; _String _M_string; _CharT _M_delim; _CharT _M_escape; }; #if __cplusplus >= 201703L template struct _Quoted_string, _CharT> { _Quoted_string(basic_string_view<_CharT, _Traits> __str, _CharT __del, _CharT __esc) : _M_string(__str), _M_delim{__del}, _M_escape{__esc} { } _Quoted_string& operator=(_Quoted_string&) = delete; basic_string_view<_CharT, _Traits> _M_string; _CharT _M_delim; _CharT _M_escape; }; #endif // C++17 /** * @brief Inserter for quoted strings. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 2344 quoted()'s interaction with padding is unclear */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const _Quoted_string& __str) { std::basic_ostringstream<_CharT, _Traits> __ostr; __ostr << __str._M_delim; for (const _CharT* __c = __str._M_string; *__c; ++__c) { if (*__c == __str._M_delim || *__c == __str._M_escape) __ostr << __str._M_escape; __ostr << *__c; } __ostr << __str._M_delim; return __os << __ostr.str(); } /** * @brief Inserter for quoted strings. * * _GLIBCXX_RESOLVE_LIB_DEFECTS * DR 2344 quoted()'s interaction with padding is unclear */ template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const _Quoted_string<_String, _CharT>& __str) { std::basic_ostringstream<_CharT, _Traits> __ostr; __ostr << __str._M_delim; for (auto __c : __str._M_string) { if (__c == __str._M_delim || __c == __str._M_escape) __ostr << __str._M_escape; __ostr << __c; } __ostr << __str._M_delim; return __os << __ostr.str(); } /** * @brief Extractor for delimited strings. * The left and right delimiters can be different. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, const _Quoted_string&, _CharT>& __str) { _CharT __c; __is >> __c; if (!__is.good()) return __is; if (__c != __str._M_delim) { __is.unget(); __is >> __str._M_string; return __is; } __str._M_string.clear(); std::ios_base::fmtflags __flags = __is.flags(__is.flags() & ~std::ios_base::skipws); do { __is >> __c; if (!__is.good()) break; if (__c == __str._M_escape) { __is >> __c; if (!__is.good()) break; } else if (__c == __str._M_delim) break; __str._M_string += __c; } while (true); __is.setf(__flags); return __is; } } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif /* _GLIBCXX_QUOTED_STRING_H */ c++/8/bits/std_function.h000064400000055334151027430570011112 0ustar00// Implementation of std::function -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/std_function.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _GLIBCXX_STD_FUNCTION_H #define _GLIBCXX_STD_FUNCTION_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #if __cpp_rtti # include #endif #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Exception class thrown when class template function's * operator() is called with an empty target. * @ingroup exceptions */ class bad_function_call : public std::exception { public: virtual ~bad_function_call() noexcept; const char* what() const noexcept; }; /** * Trait identifying "location-invariant" types, meaning that the * address of the object (or any of its members) will not escape. * Trivially copyable types are location-invariant and users can * specialize this trait for other types. */ template struct __is_location_invariant : is_trivially_copyable<_Tp>::type { }; class _Undefined_class; union _Nocopy_types { void* _M_object; const void* _M_const_object; void (*_M_function_pointer)(); void (_Undefined_class::*_M_member_pointer)(); }; union [[gnu::may_alias]] _Any_data { void* _M_access() { return &_M_pod_data[0]; } const void* _M_access() const { return &_M_pod_data[0]; } template _Tp& _M_access() { return *static_cast<_Tp*>(_M_access()); } template const _Tp& _M_access() const { return *static_cast(_M_access()); } _Nocopy_types _M_unused; char _M_pod_data[sizeof(_Nocopy_types)]; }; enum _Manager_operation { __get_type_info, __get_functor_ptr, __clone_functor, __destroy_functor }; // Simple type wrapper that helps avoid annoying const problems // when casting between void pointers and pointers-to-pointers. template struct _Simple_type_wrapper { _Simple_type_wrapper(_Tp __value) : __value(__value) { } _Tp __value; }; template struct __is_location_invariant<_Simple_type_wrapper<_Tp> > : __is_location_invariant<_Tp> { }; template class function; /// Base class of all polymorphic function object wrappers. class _Function_base { public: static const std::size_t _M_max_size = sizeof(_Nocopy_types); static const std::size_t _M_max_align = __alignof__(_Nocopy_types); template class _Base_manager { protected: static const bool __stored_locally = (__is_location_invariant<_Functor>::value && sizeof(_Functor) <= _M_max_size && __alignof__(_Functor) <= _M_max_align && (_M_max_align % __alignof__(_Functor) == 0)); typedef integral_constant _Local_storage; // Retrieve a pointer to the function object static _Functor* _M_get_pointer(const _Any_data& __source) { const _Functor* __ptr = __stored_locally? std::__addressof(__source._M_access<_Functor>()) /* have stored a pointer */ : __source._M_access<_Functor*>(); return const_cast<_Functor*>(__ptr); } // Clone a location-invariant function object that fits within // an _Any_data structure. static void _M_clone(_Any_data& __dest, const _Any_data& __source, true_type) { ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>()); } // Clone a function object that is not location-invariant or // that cannot fit into an _Any_data structure. static void _M_clone(_Any_data& __dest, const _Any_data& __source, false_type) { __dest._M_access<_Functor*>() = new _Functor(*__source._M_access<_Functor*>()); } // Destroying a location-invariant object may still require // destruction. static void _M_destroy(_Any_data& __victim, true_type) { __victim._M_access<_Functor>().~_Functor(); } // Destroying an object located on the heap. static void _M_destroy(_Any_data& __victim, false_type) { delete __victim._M_access<_Functor*>(); } public: static bool _M_manager(_Any_data& __dest, const _Any_data& __source, _Manager_operation __op) { switch (__op) { #if __cpp_rtti case __get_type_info: __dest._M_access() = &typeid(_Functor); break; #endif case __get_functor_ptr: __dest._M_access<_Functor*>() = _M_get_pointer(__source); break; case __clone_functor: _M_clone(__dest, __source, _Local_storage()); break; case __destroy_functor: _M_destroy(__dest, _Local_storage()); break; } return false; } static void _M_init_functor(_Any_data& __functor, _Functor&& __f) { _M_init_functor(__functor, std::move(__f), _Local_storage()); } template static bool _M_not_empty_function(const function<_Signature>& __f) { return static_cast(__f); } template static bool _M_not_empty_function(_Tp* __fp) { return __fp != nullptr; } template static bool _M_not_empty_function(_Tp _Class::* __mp) { return __mp != nullptr; } template static bool _M_not_empty_function(const _Tp&) { return true; } private: static void _M_init_functor(_Any_data& __functor, _Functor&& __f, true_type) { ::new (__functor._M_access()) _Functor(std::move(__f)); } static void _M_init_functor(_Any_data& __functor, _Functor&& __f, false_type) { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); } }; _Function_base() : _M_manager(nullptr) { } ~_Function_base() { if (_M_manager) _M_manager(_M_functor, _M_functor, __destroy_functor); } bool _M_empty() const { return !_M_manager; } typedef bool (*_Manager_type)(_Any_data&, const _Any_data&, _Manager_operation); _Any_data _M_functor; _Manager_type _M_manager; }; template class _Function_handler; template class _Function_handler<_Res(_ArgTypes...), _Functor> : public _Function_base::_Base_manager<_Functor> { typedef _Function_base::_Base_manager<_Functor> _Base; public: static _Res _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { return (*_Base::_M_get_pointer(__functor))( std::forward<_ArgTypes>(__args)...); } }; template class _Function_handler : public _Function_base::_Base_manager<_Functor> { typedef _Function_base::_Base_manager<_Functor> _Base; public: static void _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { (*_Base::_M_get_pointer(__functor))( std::forward<_ArgTypes>(__args)...); } }; template class _Function_handler<_Res(_ArgTypes...), _Member _Class::*> : public _Function_handler { typedef _Function_handler _Base; public: static _Res _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { return std::__invoke(_Base::_M_get_pointer(__functor)->__value, std::forward<_ArgTypes>(__args)...); } }; template class _Function_handler : public _Function_base::_Base_manager< _Simple_type_wrapper< _Member _Class::* > > { typedef _Member _Class::* _Functor; typedef _Simple_type_wrapper<_Functor> _Wrapper; typedef _Function_base::_Base_manager<_Wrapper> _Base; public: static bool _M_manager(_Any_data& __dest, const _Any_data& __source, _Manager_operation __op) { switch (__op) { #if __cpp_rtti case __get_type_info: __dest._M_access() = &typeid(_Functor); break; #endif case __get_functor_ptr: __dest._M_access<_Functor*>() = &_Base::_M_get_pointer(__source)->__value; break; default: _Base::_M_manager(__dest, __source, __op); } return false; } static void _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args) { std::__invoke(_Base::_M_get_pointer(__functor)->__value, std::forward<_ArgTypes>(__args)...); } }; template using __check_func_return_type = __or_, is_same<_From, _To>, is_convertible<_From, _To>>; /** * @brief Primary class template for std::function. * @ingroup functors * * Polymorphic function wrapper. */ template class function<_Res(_ArgTypes...)> : public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>, private _Function_base { template::type> struct _Callable : __check_func_return_type<_Res2, _Res> { }; // Used so the return type convertibility checks aren't done when // performing overload resolution for copy construction/assignment. template struct _Callable : false_type { }; template using _Requires = typename enable_if<_Cond::value, _Tp>::type; public: typedef _Res result_type; // [3.7.2.1] construct/copy/destroy /** * @brief Default construct creates an empty function call wrapper. * @post @c !(bool)*this */ function() noexcept : _Function_base() { } /** * @brief Creates an empty function call wrapper. * @post @c !(bool)*this */ function(nullptr_t) noexcept : _Function_base() { } /** * @brief %Function copy constructor. * @param __x A %function object with identical call signature. * @post @c bool(*this) == bool(__x) * * The newly-created %function contains a copy of the target of @a * __x (if it has one). */ function(const function& __x); /** * @brief %Function move constructor. * @param __x A %function object rvalue with identical call signature. * * The newly-created %function contains the target of @a __x * (if it has one). */ function(function&& __x) noexcept : _Function_base() { __x.swap(*this); } /** * @brief Builds a %function that targets a copy of the incoming * function object. * @param __f A %function object that is callable with parameters of * type @c T1, @c T2, ..., @c TN and returns a value convertible * to @c Res. * * The newly-created %function object will target a copy of * @a __f. If @a __f is @c reference_wrapper, then this function * object will contain a reference to the function object @c * __f.get(). If @a __f is a NULL function pointer or NULL * pointer-to-member, the newly-created object will be empty. * * If @a __f is a non-NULL function pointer or an object of type @c * reference_wrapper, this function will not throw. */ template>, void>, typename = _Requires<_Callable<_Functor>, void>> function(_Functor); /** * @brief %Function assignment operator. * @param __x A %function with identical call signature. * @post @c (bool)*this == (bool)x * @returns @c *this * * The target of @a __x is copied to @c *this. If @a __x has no * target, then @c *this will be empty. * * If @a __x targets a function pointer or a reference to a function * object, then this operation will not throw an %exception. */ function& operator=(const function& __x) { function(__x).swap(*this); return *this; } /** * @brief %Function move-assignment operator. * @param __x A %function rvalue with identical call signature. * @returns @c *this * * The target of @a __x is moved to @c *this. If @a __x has no * target, then @c *this will be empty. * * If @a __x targets a function pointer or a reference to a function * object, then this operation will not throw an %exception. */ function& operator=(function&& __x) noexcept { function(std::move(__x)).swap(*this); return *this; } /** * @brief %Function assignment to zero. * @post @c !(bool)*this * @returns @c *this * * The target of @c *this is deallocated, leaving it empty. */ function& operator=(nullptr_t) noexcept { if (_M_manager) { _M_manager(_M_functor, _M_functor, __destroy_functor); _M_manager = nullptr; _M_invoker = nullptr; } return *this; } /** * @brief %Function assignment to a new target. * @param __f A %function object that is callable with parameters of * type @c T1, @c T2, ..., @c TN and returns a value convertible * to @c Res. * @return @c *this * * This %function object wrapper will target a copy of @a * __f. If @a __f is @c reference_wrapper, then this function * object will contain a reference to the function object @c * __f.get(). If @a __f is a NULL function pointer or NULL * pointer-to-member, @c this object will be empty. * * If @a __f is a non-NULL function pointer or an object of type @c * reference_wrapper, this function will not throw. */ template _Requires<_Callable::type>, function&> operator=(_Functor&& __f) { function(std::forward<_Functor>(__f)).swap(*this); return *this; } /// @overload template function& operator=(reference_wrapper<_Functor> __f) noexcept { function(__f).swap(*this); return *this; } // [3.7.2.2] function modifiers /** * @brief Swap the targets of two %function objects. * @param __x A %function with identical call signature. * * Swap the targets of @c this function object and @a __f. This * function will not throw an %exception. */ void swap(function& __x) noexcept { std::swap(_M_functor, __x._M_functor); std::swap(_M_manager, __x._M_manager); std::swap(_M_invoker, __x._M_invoker); } // [3.7.2.3] function capacity /** * @brief Determine if the %function wrapper has a target. * * @return @c true when this %function object contains a target, * or @c false when it is empty. * * This function will not throw an %exception. */ explicit operator bool() const noexcept { return !_M_empty(); } // [3.7.2.4] function invocation /** * @brief Invokes the function targeted by @c *this. * @returns the result of the target. * @throws bad_function_call when @c !(bool)*this * * The function call operator invokes the target function object * stored by @c this. */ _Res operator()(_ArgTypes... __args) const; #if __cpp_rtti // [3.7.2.5] function target access /** * @brief Determine the type of the target of this function object * wrapper. * * @returns the type identifier of the target function object, or * @c typeid(void) if @c !(bool)*this. * * This function will not throw an %exception. */ const type_info& target_type() const noexcept; /** * @brief Access the stored target function object. * * @return Returns a pointer to the stored target function object, * if @c typeid(_Functor).equals(target_type()); otherwise, a NULL * pointer. * * This function does not throw exceptions. * * @{ */ template _Functor* target() noexcept; template const _Functor* target() const noexcept; // @} #endif private: using _Invoker_type = _Res (*)(const _Any_data&, _ArgTypes&&...); _Invoker_type _M_invoker; }; #if __cpp_deduction_guides >= 201606 template struct __function_guide_helper { }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) noexcept(_Nx) > { using type = _Res(_Args...); }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) & noexcept(_Nx) > { using type = _Res(_Args...); }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) const noexcept(_Nx) > { using type = _Res(_Args...); }; template struct __function_guide_helper< _Res (_Tp::*) (_Args...) const & noexcept(_Nx) > { using type = _Res(_Args...); }; template function(_Res(*)(_ArgTypes...)) -> function<_Res(_ArgTypes...)>; template::type> function(_Functor) -> function<_Signature>; #endif // Out-of-line member definitions. template function<_Res(_ArgTypes...)>:: function(const function& __x) : _Function_base() { if (static_cast(__x)) { __x._M_manager(_M_functor, __x._M_functor, __clone_functor); _M_invoker = __x._M_invoker; _M_manager = __x._M_manager; } } template template function<_Res(_ArgTypes...)>:: function(_Functor __f) : _Function_base() { typedef _Function_handler<_Res(_ArgTypes...), _Functor> _My_handler; if (_My_handler::_M_not_empty_function(__f)) { _My_handler::_M_init_functor(_M_functor, std::move(__f)); _M_invoker = &_My_handler::_M_invoke; _M_manager = &_My_handler::_M_manager; } } template _Res function<_Res(_ArgTypes...)>:: operator()(_ArgTypes... __args) const { if (_M_empty()) __throw_bad_function_call(); return _M_invoker(_M_functor, std::forward<_ArgTypes>(__args)...); } #if __cpp_rtti template const type_info& function<_Res(_ArgTypes...)>:: target_type() const noexcept { if (_M_manager) { _Any_data __typeinfo_result; _M_manager(__typeinfo_result, _M_functor, __get_type_info); return *__typeinfo_result._M_access(); } else return typeid(void); } template template _Functor* function<_Res(_ArgTypes...)>:: target() noexcept { const function* __const_this = this; const _Functor* __func = __const_this->template target<_Functor>(); return const_cast<_Functor*>(__func); } template template const _Functor* function<_Res(_ArgTypes...)>:: target() const noexcept { if (typeid(_Functor) == target_type() && _M_manager) { _Any_data __ptr; _M_manager(__ptr, _M_functor, __get_functor_ptr); return __ptr._M_access(); } else return nullptr; } #endif // [20.7.15.2.6] null pointer comparisons /** * @brief Compares a polymorphic function object wrapper against 0 * (the NULL pointer). * @returns @c true if the wrapper has no target, @c false otherwise * * This function will not throw an %exception. */ template inline bool operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept { return !static_cast(__f); } /// @overload template inline bool operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept { return !static_cast(__f); } /** * @brief Compares a polymorphic function object wrapper against 0 * (the NULL pointer). * @returns @c false if the wrapper has no target, @c true otherwise * * This function will not throw an %exception. */ template inline bool operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept { return static_cast(__f); } /// @overload template inline bool operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept { return static_cast(__f); } // [20.7.15.2.7] specialized algorithms /** * @brief Swap the targets of two polymorphic function object wrappers. * * This function will not throw an %exception. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2062. Effect contradictions w/o no-throw guarantee of std::function swaps template inline void swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y) noexcept { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_STD_FUNCTION_H c++/8/bits/gslice_array.h000064400000017131151027430570011050 0ustar00// The template and inlines for the -*- C++ -*- gslice_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/gslice_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _GSLICE_ARRAY_H #define _GSLICE_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Reference to multi-dimensional subset of an array. * * A gslice_array is a reference to the actual elements of an array * specified by a gslice. The way to get a gslice_array is to call * operator[](gslice) on a valarray. The returned gslice_array then * permits carrying operations out on the referenced subset of elements in * the original valarray. For example, operator+=(valarray) will add * values to the subset of elements in the underlying valarray this * gslice_array refers to. * * @param Tp Element type. */ template class gslice_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. gslice_array(const gslice_array&); /// Assignment operator. Assigns slice elements to corresponding /// elements of @a a. gslice_array& operator=(const gslice_array&); /// Assign slice elements to corresponding elements of @a v. void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator=(const _Tp&) const; template void operator=(const _Expr<_Dom, _Tp>&) const; template void operator*=(const _Expr<_Dom, _Tp>&) const; template void operator/=(const _Expr<_Dom, _Tp>&) const; template void operator%=(const _Expr<_Dom, _Tp>&) const; template void operator+=(const _Expr<_Dom, _Tp>&) const; template void operator-=(const _Expr<_Dom, _Tp>&) const; template void operator^=(const _Expr<_Dom, _Tp>&) const; template void operator&=(const _Expr<_Dom, _Tp>&) const; template void operator|=(const _Expr<_Dom, _Tp>&) const; template void operator<<=(const _Expr<_Dom, _Tp>&) const; template void operator>>=(const _Expr<_Dom, _Tp>&) const; private: _Array<_Tp> _M_array; const valarray& _M_index; friend class valarray<_Tp>; gslice_array(_Array<_Tp>, const valarray&); // not implemented gslice_array(); }; template inline gslice_array<_Tp>::gslice_array(_Array<_Tp> __a, const valarray& __i) : _M_array(__a), _M_index(__i) {} template inline gslice_array<_Tp>::gslice_array(const gslice_array<_Tp>& __a) : _M_array(__a._M_array), _M_index(__a._M_index) {} template inline gslice_array<_Tp>& gslice_array<_Tp>::operator=(const gslice_array<_Tp>& __a) { std::__valarray_copy(_Array<_Tp>(__a._M_array), _Array(__a._M_index), _M_index.size(), _M_array, _Array(_M_index)); return *this; } template inline void gslice_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _Array(_M_index), _M_index.size(), __t); } template inline void gslice_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), __v.size(), _M_array, _Array(_M_index)); } template template inline void gslice_array<_Tp>::operator=(const _Expr<_Dom, _Tp>& __e) const { std::__valarray_copy (__e, _M_index.size(), _M_array, _Array(_M_index)); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op, _Name) \ template \ inline void \ gslice_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const \ { \ _Array_augmented_##_Name(_M_array, _Array(_M_index), \ _Array<_Tp>(__v), __v.size()); \ } \ \ template \ template \ inline void \ gslice_array<_Tp>::operator _Op##= (const _Expr<_Dom, _Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _Array(_M_index), __e,\ _M_index.size()); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GSLICE_ARRAY_H */ c++/8/bits/ostream_insert.h000064400000007642151027430570011450 0ustar00// Helpers for ostream inserters -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ostream_insert.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ostream} */ #ifndef _OSTREAM_INSERT_H #define _OSTREAM_INSERT_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template inline void __ostream_write(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s, streamsize __n) { typedef basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const streamsize __put = __out.rdbuf()->sputn(__s, __n); if (__put != __n) __out.setstate(__ios_base::badbit); } template inline void __ostream_fill(basic_ostream<_CharT, _Traits>& __out, streamsize __n) { typedef basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; const _CharT __c = __out.fill(); for (; __n > 0; --__n) { const typename _Traits::int_type __put = __out.rdbuf()->sputc(__c); if (_Traits::eq_int_type(__put, _Traits::eof())) { __out.setstate(__ios_base::badbit); break; } } } template basic_ostream<_CharT, _Traits>& __ostream_insert(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s, streamsize __n) { typedef basic_ostream<_CharT, _Traits> __ostream_type; typedef typename __ostream_type::ios_base __ios_base; typename __ostream_type::sentry __cerb(__out); if (__cerb) { __try { const streamsize __w = __out.width(); if (__w > __n) { const bool __left = ((__out.flags() & __ios_base::adjustfield) == __ios_base::left); if (!__left) __ostream_fill(__out, __w - __n); if (__out.good()) __ostream_write(__out, __s, __n); if (__left && __out.good()) __ostream_fill(__out, __w - __n); } else __ostream_write(__out, __s, __n); __out.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __out._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { __out._M_setstate(__ios_base::badbit); } } return __out; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template ostream& __ostream_insert(ostream&, const char*, streamsize); #ifdef _GLIBCXX_USE_WCHAR_T extern template wostream& __ostream_insert(wostream&, const wchar_t*, streamsize); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _OSTREAM_INSERT_H */ c++/8/bits/stl_set.h000064400000106435151027430570010067 0ustar00// Set implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_set.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{set} */ #ifndef _STL_SET_H #define _STL_SET_H 1 #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class multiset; /** * @brief A standard container made up of unique keys, which can be * retrieved in logarithmic time. * * @ingroup associative_containers * * @tparam _Key Type of key objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, a * reversible container, and an * associative container (using unique keys). * * Sets support bidirectional iterators. * * The private tree data is declared exactly the same way for set and * multiset; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template, typename _Alloc = std::allocator<_Key> > class set { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Key, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(_Key, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Key>::value, "std::set must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::set must have the same value_type as its allocator"); # endif #endif public: // typedefs: //@{ /// Public typedefs. typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Alloc allocator_type; //@} private: typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Key>::other _Key_alloc_type; typedef _Rb_tree, key_compare, _Key_alloc_type> _Rep_type; _Rep_type _M_t; // Red-black tree representing set. typedef __gnu_cxx::__alloc_traits<_Key_alloc_type> _Alloc_traits; public: //@{ /// Iterator-related typedefs. typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 103. set::iterator is required to be modifiable, // but this allows modification of keys. typedef typename _Rep_type::const_iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::const_reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; using insert_return_type = typename _Rep_type::insert_return_type; #endif // allocation/deallocation /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L set() : _M_t() { } #else set() = default; #endif /** * @brief Creates a %set with no elements. * @param __comp Comparator to use. * @param __a An allocator object. */ explicit set(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { } /** * @brief Builds a %set from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %set consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template set(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_unique(__first, __last); } /** * @brief Builds a %set from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %set consisting of copies of the elements from * [__first,__last). This is linear in N if the range is * already sorted, and NlogN otherwise (where N is * distance(__first,__last)). */ template set(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } /** * @brief %Set copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L set(const set& __x) : _M_t(__x._M_t) { } #else set(const set&) = default; /** * @brief %Set move constructor * * The newly-created %set contains the exact contents of the moved * instance. The moved instance is a valid, but unspecified, %set. */ set(set&&) = default; /** * @brief Builds a %set from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %set consisting of copies of the elements in the list. * This is linear in N if the list is already sorted, and NlogN * otherwise (where N is @a __l.size()). */ set(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit set(const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { } /// Allocator-extended copy constructor. set(const set& __x, const allocator_type& __a) : _M_t(__x._M_t, _Key_alloc_type(__a)) { } /// Allocator-extended move constructor. set(set&& __x, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__x._M_t), _Key_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. set(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_unique(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template set(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_unique(__first, __last); } /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~set() = default; #endif /** * @brief %Set assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L set& operator=(const set& __x) { _M_t = __x._M_t; return *this; } #else set& operator=(const set&) = default; /// Move assignment operator. set& operator=(set&&) = default; /** * @brief %Set list assignment operator. * @param __l An initializer_list. * * This function fills a %set with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %set and * that the resulting %set's size is the same as the number * of elements assigned. */ set& operator=(initializer_list __l) { _M_t._M_assign_unique(__l.begin(), __l.end()); return *this; } #endif // accessors: /// Returns the comparison object with which the %set was constructed. key_compare key_comp() const { return _M_t.key_comp(); } /// Returns the comparison object with which the %set was constructed. value_compare value_comp() const { return _M_t.key_comp(); } /// Returns the allocator object with which the %set was constructed. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } /** * Returns a read-only (constant) iterator that points to the first * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points to the last * element in the %set. Iteration is done in descending order according * to the keys. */ reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %set. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %set. Iteration is done in ascending order according * to the keys. */ iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) iterator that points to the last * element in the %set. Iteration is done in descending order according * to the keys. */ reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last pair in the %set. Iteration is done in descending order * according to the keys. */ reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif /// Returns true if the %set is empty. bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /// Returns the size of the %set. size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /// Returns the maximum size of the %set. size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } /** * @brief Swaps data with another %set. * @param __x A %set of the same element and allocator types. * * This exchanges the elements between two sets in constant * time. (It is only swapping a pointer, an integer, and an * instance of the @c Compare type (which itself is often * stateless and empty), so it should be quite fast.) Note * that the global std::swap() function is specialized such * that std::swap(s1,s2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(set& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } // insert/erase #if __cplusplus >= 201103L /** * @brief Attempts to build and insert an element into the %set. * @param __args Arguments used to generate an element. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to build and insert an element into the %set. * A %set relies on unique keys and thus an element is only inserted if * it is not already present in the %set. * * Insertion requires logarithmic time. */ template std::pair emplace(_Args&&... __args) { return _M_t._M_emplace_unique(std::forward<_Args>(__args)...); } /** * @brief Attempts to insert an element into the %set. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element to be * inserted. * @return An iterator that points to the element with key equivalent to * the one generated from @a __args (may or may not be the * element itself). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_unique(__pos, std::forward<_Args>(__args)...); } #endif /** * @brief Attempts to insert an element into the %set. * @param __x Element to be inserted. * @return A pair, of which the first element is an iterator that points * to the possibly inserted element, and the second is a bool * that is true if the element was actually inserted. * * This function attempts to insert an element into the %set. A %set * relies on unique keys and thus an element is only inserted if it is * not already present in the %set. * * Insertion requires logarithmic time. */ std::pair insert(const value_type& __x) { std::pair __p = _M_t._M_insert_unique(__x); return std::pair(__p.first, __p.second); } #if __cplusplus >= 201103L std::pair insert(value_type&& __x) { std::pair __p = _M_t._M_insert_unique(std::move(__x)); return std::pair(__p.first, __p.second); } #endif /** * @brief Attempts to insert an element into the %set. * @param __position An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the element with key of * @a __x (may or may not be the element passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * For more on @a hinting, see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * * Insertion requires logarithmic time (if the hint is not taken). */ iterator insert(const_iterator __position, const value_type& __x) { return _M_t._M_insert_unique_(__position, __x); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_unique_(__position, std::move(__x)); } #endif /** * @brief A template function that attempts to insert a range * of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_unique(__first, __last); } #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of elements into the %set. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_t._M_reinsert_node_unique(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_unique(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(set<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(set<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } template void merge(multiset<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_unique(_Merge_helper::_S_get_tree(__source)); } template void merge(multiset<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %set. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from a %set. Note that this function only erases the element, and * that if the element is itself a pointer, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __position) { return _M_t.erase(__position); } #else /** * @brief Erases an element from a %set. * @param position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %set. Note that this function only erases the element, and * that if the element is itself a pointer, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [__first,__last) range of elements from a %set. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else /** * @brief Erases a [first,last) range of elements from a %set. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * * This function erases a sequence of elements from a %set. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * Erases all elements in a %set. Note that this function only erases * the elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // set operations: //@{ /** * @brief Finds the number of elements. * @param __x Element to located. * @return Number of elements with specified key. * * This function only makes sense for multisets; for set the result will * either be 0 (not present) or 1 (present). */ size_type count(const key_type& __x) const { return _M_t.find(__x) == _M_t.end() ? 0 : 1; } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload //@{ /** * @brief Tries to locate an element in a %set. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(iterator{_M_t._M_find_tr(__x)}) { return iterator{_M_t._M_find_tr(__x)}; } template auto find(const _Kt& __x) const -> decltype(const_iterator{_M_t._M_find_tr(__x)}) { return const_iterator{_M_t._M_find_tr(__x)}; } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } template auto lower_bound(const _Kt& __x) const -> decltype(const_iterator(_M_t._M_lower_bound_tr(__x))) { return const_iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } template auto upper_bound(const _Kt& __x) const -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return const_iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multisets. */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } template auto equal_range(const _Kt& __x) const -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const set<_K1, _C1, _A1>&, const set<_K1, _C1, _A1>&); template friend bool operator<(const set<_K1, _C1, _A1>&, const set<_K1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> set::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> set(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> set<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Allocator) -> set::value_type, less::value_type>, _Allocator>; template> set(initializer_list<_Key>, _Allocator) -> set<_Key, less<_Key>, _Allocator>; #endif /** * @brief Set equality comparison. * @param __x A %set. * @param __y A %set of the same type as @a x. * @return True iff the size and elements of the sets are equal. * * This is an equivalence relation. It is linear in the size of the sets. * Sets are considered equivalent if their sizes are equal, and if * corresponding elements compare equal. */ template inline bool operator==(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Set ordering relation. * @param __x A %set. * @param __y A %set of the same type as @a x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * sets. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Returns !(x == y). template inline bool operator!=(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Returns y < x. template inline bool operator>(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return __y < __x; } /// Returns !(y < x) template inline bool operator<=(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Returns !(x < y) template inline bool operator>=(const set<_Key, _Compare, _Alloc>& __x, const set<_Key, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::set::swap(). template inline void swap(set<_Key, _Compare, _Alloc>& __x, set<_Key, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::set access to internals of compatible sets. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::set<_Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::set<_Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::set<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multiset<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } //namespace std #endif /* _STL_SET_H */ c++/8/bits/cxxabi_forced.h000064400000003423151027430570011203 0ustar00// cxxabi.h subset for cancellation -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cxxabi_forced.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cxxabi.h} */ #ifndef _CXXABI_FORCED_H #define _CXXABI_FORCED_H 1 #pragma GCC system_header #pragma GCC visibility push(default) #ifdef __cplusplus namespace __cxxabiv1 { /** * @brief Thrown as part of forced unwinding. * @ingroup exceptions * * A magic placeholder class that can be caught by reference to * recognize forced unwinding. */ class __forced_unwind { virtual ~__forced_unwind() throw(); // Prevent catch by value. virtual void __pure_dummy() = 0; }; } #endif // __cplusplus #pragma GCC visibility pop #endif // __CXXABI_FORCED_H c++/8/bits/fs_dir.h000064400000034604151027430570007656 0ustar00// Filesystem directory utilities -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/bits/fs_dir.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{filesystem} */ #ifndef _GLIBCXX_FS_DIR_H #define _GLIBCXX_FS_DIR_H 1 #if __cplusplus >= 201703L # include # include # include # include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace filesystem { /** * @ingroup filesystem * @{ */ class file_status { public: // constructors and destructor file_status() noexcept : file_status(file_type::none) {} explicit file_status(file_type __ft, perms __prms = perms::unknown) noexcept : _M_type(__ft), _M_perms(__prms) { } file_status(const file_status&) noexcept = default; file_status(file_status&&) noexcept = default; ~file_status() = default; file_status& operator=(const file_status&) noexcept = default; file_status& operator=(file_status&&) noexcept = default; // observers file_type type() const noexcept { return _M_type; } perms permissions() const noexcept { return _M_perms; } // modifiers void type(file_type __ft) noexcept { _M_type = __ft; } void permissions(perms __prms) noexcept { _M_perms = __prms; } private: file_type _M_type; perms _M_perms; }; _GLIBCXX_BEGIN_NAMESPACE_CXX11 struct _Dir; class directory_iterator; class recursive_directory_iterator; class directory_entry { public: // constructors and destructor directory_entry() noexcept = default; directory_entry(const directory_entry&) = default; directory_entry(directory_entry&&) noexcept = default; explicit directory_entry(const filesystem::path& __p) : _M_path(__p) { refresh(); } directory_entry(const filesystem::path& __p, error_code& __ec) : _M_path(__p) { refresh(__ec); if (__ec) _M_path.clear(); } ~directory_entry() = default; // modifiers directory_entry& operator=(const directory_entry&) = default; directory_entry& operator=(directory_entry&&) noexcept = default; void assign(const filesystem::path& __p) { _M_path = __p; refresh(); } void assign(const filesystem::path& __p, error_code& __ec) { _M_path = __p; refresh(__ec); } void replace_filename(const filesystem::path& __p) { _M_path.replace_filename(__p); refresh(); } void replace_filename(const filesystem::path& __p, error_code& __ec) { _M_path.replace_filename(__p); refresh(__ec); } void refresh() { _M_type = symlink_status().type(); } void refresh(error_code& __ec) noexcept { _M_type = symlink_status(__ec).type(); } // observers const filesystem::path& path() const noexcept { return _M_path; } operator const filesystem::path& () const noexcept { return _M_path; } bool exists() const { return filesystem::exists(file_status{_M_file_type()}); } bool exists(error_code& __ec) const noexcept { return filesystem::exists(file_status{_M_file_type(__ec)}); } bool is_block_file() const { return _M_file_type() == file_type::block; } bool is_block_file(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::block; } bool is_character_file() const { return _M_file_type() == file_type::character; } bool is_character_file(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::character; } bool is_directory() const { return _M_file_type() == file_type::directory; } bool is_directory(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::directory; } bool is_fifo() const { return _M_file_type() == file_type::fifo; } bool is_fifo(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::fifo; } bool is_other() const { return filesystem::is_other(file_status{_M_file_type()}); } bool is_other(error_code& __ec) const noexcept { return filesystem::is_other(file_status{_M_file_type(__ec)}); } bool is_regular_file() const { return _M_file_type() == file_type::regular; } bool is_regular_file(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::regular; } bool is_socket() const { return _M_file_type() == file_type::socket; } bool is_socket(error_code& __ec) const noexcept { return _M_file_type(__ec) == file_type::socket; } bool is_symlink() const { if (_M_type != file_type::none) return _M_type == file_type::symlink; return symlink_status().type() == file_type::symlink; } bool is_symlink(error_code& __ec) const noexcept { if (_M_type != file_type::none) return _M_type == file_type::symlink; return symlink_status(__ec).type() == file_type::symlink; } uintmax_t file_size() const { return filesystem::file_size(_M_path); } uintmax_t file_size(error_code& __ec) const noexcept { return filesystem::file_size(_M_path, __ec); } uintmax_t hard_link_count() const { return filesystem::hard_link_count(_M_path); } uintmax_t hard_link_count(error_code& __ec) const noexcept { return filesystem::hard_link_count(_M_path, __ec); } file_time_type last_write_time() const { return filesystem::last_write_time(_M_path); } file_time_type last_write_time(error_code& __ec) const noexcept { return filesystem::last_write_time(_M_path, __ec); } file_status status() const { return filesystem::status(_M_path); } file_status status(error_code& __ec) const noexcept { return filesystem::status(_M_path, __ec); } file_status symlink_status() const { return filesystem::symlink_status(_M_path); } file_status symlink_status(error_code& __ec) const noexcept { return filesystem::symlink_status(_M_path, __ec); } bool operator< (const directory_entry& __rhs) const noexcept { return _M_path < __rhs._M_path; } bool operator==(const directory_entry& __rhs) const noexcept { return _M_path == __rhs._M_path; } bool operator!=(const directory_entry& __rhs) const noexcept { return _M_path != __rhs._M_path; } bool operator<=(const directory_entry& __rhs) const noexcept { return _M_path <= __rhs._M_path; } bool operator> (const directory_entry& __rhs) const noexcept { return _M_path > __rhs._M_path; } bool operator>=(const directory_entry& __rhs) const noexcept { return _M_path >= __rhs._M_path; } private: friend class _Dir; friend class directory_iterator; friend class recursive_directory_iterator; directory_entry(const filesystem::path& __p, file_type __t) : _M_path(__p), _M_type(__t) { } // Equivalent to status().type() but uses cached value, if any. file_type _M_file_type() const { if (_M_type != file_type::none && _M_type != file_type::symlink) return _M_type; return status().type(); } // Equivalent to status(__ec).type() but uses cached value, if any. file_type _M_file_type(error_code& __ec) const noexcept { if (_M_type != file_type::none && _M_type != file_type::symlink) { __ec.clear(); return _M_type; } return status(__ec).type(); } filesystem::path _M_path; file_type _M_type = file_type::none; }; struct __directory_iterator_proxy { const directory_entry& operator*() const& noexcept { return _M_entry; } directory_entry operator*() && noexcept { return std::move(_M_entry); } private: friend class directory_iterator; friend class recursive_directory_iterator; explicit __directory_iterator_proxy(const directory_entry& __e) : _M_entry(__e) { } directory_entry _M_entry; }; class directory_iterator { public: typedef directory_entry value_type; typedef ptrdiff_t difference_type; typedef const directory_entry* pointer; typedef const directory_entry& reference; typedef input_iterator_tag iterator_category; directory_iterator() = default; explicit directory_iterator(const path& __p) : directory_iterator(__p, directory_options::none, nullptr) { } directory_iterator(const path& __p, directory_options __options) : directory_iterator(__p, __options, nullptr) { } directory_iterator(const path& __p, error_code& __ec) : directory_iterator(__p, directory_options::none, __ec) { } directory_iterator(const path& __p, directory_options __options, error_code& __ec) : directory_iterator(__p, __options, &__ec) { } directory_iterator(const directory_iterator& __rhs) = default; directory_iterator(directory_iterator&& __rhs) noexcept = default; ~directory_iterator() = default; directory_iterator& operator=(const directory_iterator& __rhs) = default; directory_iterator& operator=(directory_iterator&& __rhs) noexcept = default; const directory_entry& operator*() const; const directory_entry* operator->() const { return &**this; } directory_iterator& operator++(); directory_iterator& increment(error_code& __ec); __directory_iterator_proxy operator++(int) { __directory_iterator_proxy __pr{**this}; ++*this; return __pr; } private: directory_iterator(const path&, directory_options, error_code*); friend bool operator==(const directory_iterator& __lhs, const directory_iterator& __rhs); friend class recursive_directory_iterator; std::shared_ptr<_Dir> _M_dir; }; inline directory_iterator begin(directory_iterator __iter) noexcept { return __iter; } inline directory_iterator end(directory_iterator) noexcept { return directory_iterator(); } inline bool operator==(const directory_iterator& __lhs, const directory_iterator& __rhs) { return !__rhs._M_dir.owner_before(__lhs._M_dir) && !__lhs._M_dir.owner_before(__rhs._M_dir); } inline bool operator!=(const directory_iterator& __lhs, const directory_iterator& __rhs) { return !(__lhs == __rhs); } class recursive_directory_iterator { public: typedef directory_entry value_type; typedef ptrdiff_t difference_type; typedef const directory_entry* pointer; typedef const directory_entry& reference; typedef input_iterator_tag iterator_category; recursive_directory_iterator() = default; explicit recursive_directory_iterator(const path& __p) : recursive_directory_iterator(__p, directory_options::none, nullptr) { } recursive_directory_iterator(const path& __p, directory_options __options) : recursive_directory_iterator(__p, __options, nullptr) { } recursive_directory_iterator(const path& __p, directory_options __options, error_code& __ec) : recursive_directory_iterator(__p, __options, &__ec) { } recursive_directory_iterator(const path& __p, error_code& __ec) : recursive_directory_iterator(__p, directory_options::none, &__ec) { } recursive_directory_iterator( const recursive_directory_iterator&) = default; recursive_directory_iterator(recursive_directory_iterator&&) = default; ~recursive_directory_iterator(); // observers directory_options options() const { return _M_options; } int depth() const; bool recursion_pending() const { return _M_pending; } const directory_entry& operator*() const; const directory_entry* operator->() const { return &**this; } // modifiers recursive_directory_iterator& operator=(const recursive_directory_iterator& __rhs) noexcept; recursive_directory_iterator& operator=(recursive_directory_iterator&& __rhs) noexcept; recursive_directory_iterator& operator++(); recursive_directory_iterator& increment(error_code& __ec); __directory_iterator_proxy operator++(int) { __directory_iterator_proxy __pr{**this}; ++*this; return __pr; } void pop(); void pop(error_code&); void disable_recursion_pending() { _M_pending = false; } private: recursive_directory_iterator(const path&, directory_options, error_code*); friend bool operator==(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs); struct _Dir_stack; std::shared_ptr<_Dir_stack> _M_dirs; directory_options _M_options = {}; bool _M_pending = false; }; inline recursive_directory_iterator begin(recursive_directory_iterator __iter) noexcept { return __iter; } inline recursive_directory_iterator end(recursive_directory_iterator) noexcept { return recursive_directory_iterator(); } inline bool operator==(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs) { return !__rhs._M_dirs.owner_before(__lhs._M_dirs) && !__lhs._M_dirs.owner_before(__rhs._M_dirs); } inline bool operator!=(const recursive_directory_iterator& __lhs, const recursive_directory_iterator& __rhs) { return !(__lhs == __rhs); } _GLIBCXX_END_NAMESPACE_CXX11 // @} group filesystem } // namespace filesystem _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_FS_DIR_H c++/8/bits/regex.h000064400000276172151027430570007532 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 template class basic_regex; template class match_results; _GLIBCXX_END_NAMESPACE_CXX11 namespace __detail { enum class _RegexExecutorPolicy : int { _S_auto, _S_alternate }; template bool __regex_algo_impl(_BiIter __s, _BiIter __e, match_results<_BiIter, _Alloc>& __m, const basic_regex<_CharT, _TraitsT>& __re, regex_constants::match_flag_type __flags); template class _Executor; } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @addtogroup regex * @{ */ /** * @brief Describes aspects of a regular expression. * * A regular expression traits class that satisfies the requirements of * section [28.7]. * * The class %regex is parameterized around a set of related types and * functions used to complete the definition of its semantics. This class * satisfies the requirements of such a traits class. */ template struct regex_traits { public: typedef _Ch_type char_type; typedef std::basic_string string_type; typedef std::locale locale_type; private: struct _RegexMask { typedef std::ctype_base::mask _BaseType; _BaseType _M_base; unsigned char _M_extended; static constexpr unsigned char _S_under = 1 << 0; static constexpr unsigned char _S_valid_mask = 0x1; constexpr _RegexMask(_BaseType __base = 0, unsigned char __extended = 0) : _M_base(__base), _M_extended(__extended) { } constexpr _RegexMask operator&(_RegexMask __other) const { return _RegexMask(_M_base & __other._M_base, _M_extended & __other._M_extended); } constexpr _RegexMask operator|(_RegexMask __other) const { return _RegexMask(_M_base | __other._M_base, _M_extended | __other._M_extended); } constexpr _RegexMask operator^(_RegexMask __other) const { return _RegexMask(_M_base ^ __other._M_base, _M_extended ^ __other._M_extended); } constexpr _RegexMask operator~() const { return _RegexMask(~_M_base, ~_M_extended); } _RegexMask& operator&=(_RegexMask __other) { return *this = (*this) & __other; } _RegexMask& operator|=(_RegexMask __other) { return *this = (*this) | __other; } _RegexMask& operator^=(_RegexMask __other) { return *this = (*this) ^ __other; } constexpr bool operator==(_RegexMask __other) const { return (_M_extended & _S_valid_mask) == (__other._M_extended & _S_valid_mask) && _M_base == __other._M_base; } constexpr bool operator!=(_RegexMask __other) const { return !((*this) == __other); } }; public: typedef _RegexMask char_class_type; public: /** * @brief Constructs a default traits object. */ regex_traits() { } /** * @brief Gives the length of a C-style string starting at @p __p. * * @param __p a pointer to the start of a character sequence. * * @returns the number of characters between @p *__p and the first * default-initialized value of type @p char_type. In other words, uses * the C-string algorithm for determining the length of a sequence of * characters. */ static std::size_t length(const char_type* __p) { return string_type::traits_type::length(__p); } /** * @brief Performs the identity translation. * * @param __c A character to the locale-specific character set. * * @returns __c. */ char_type translate(char_type __c) const { return __c; } /** * @brief Translates a character into a case-insensitive equivalent. * * @param __c A character to the locale-specific character set. * * @returns the locale-specific lower-case equivalent of __c. * @throws std::bad_cast if the imbued locale does not support the ctype * facet. */ char_type translate_nocase(char_type __c) const { typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); return __fctyp.tolower(__c); } /** * @brief Gets a sort key for a character sequence. * * @param __first beginning of the character sequence. * @param __last one-past-the-end of the character sequence. * * Returns a sort key for the character sequence designated by the * iterator range [F1, F2) such that if the character sequence [G1, G2) * sorts before the character sequence [H1, H2) then * v.transform(G1, G2) < v.transform(H1, H2). * * What this really does is provide a more efficient way to compare a * string to multiple other strings in locales with fancy collation * rules and equivalence classes. * * @returns a locale-specific sort key equivalent to the input range. * * @throws std::bad_cast if the current locale does not have a collate * facet. */ template string_type transform(_Fwd_iter __first, _Fwd_iter __last) const { typedef std::collate __collate_type; const __collate_type& __fclt(use_facet<__collate_type>(_M_locale)); string_type __s(__first, __last); return __fclt.transform(__s.data(), __s.data() + __s.size()); } /** * @brief Gets a sort key for a character sequence, independent of case. * * @param __first beginning of the character sequence. * @param __last one-past-the-end of the character sequence. * * Effects: if typeid(use_facet >) == * typeid(collate_byname<_Ch_type>) and the form of the sort key * returned by collate_byname<_Ch_type>::transform(__first, __last) * is known and can be converted into a primary sort key * then returns that key, otherwise returns an empty string. * * @todo Implement this function correctly. */ template string_type transform_primary(_Fwd_iter __first, _Fwd_iter __last) const { // TODO : this is not entirely correct. // This function requires extra support from the platform. // // Read http://gcc.gnu.org/ml/libstdc++/2013-09/msg00117.html and // http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2003/n1429.htm // for details. typedef std::ctype __ctype_type; const __ctype_type& __fctyp(use_facet<__ctype_type>(_M_locale)); std::vector __s(__first, __last); __fctyp.tolower(__s.data(), __s.data() + __s.size()); return this->transform(__s.data(), __s.data() + __s.size()); } /** * @brief Gets a collation element by name. * * @param __first beginning of the collation element name. * @param __last one-past-the-end of the collation element name. * * @returns a sequence of one or more characters that represents the * collating element consisting of the character sequence designated by * the iterator range [__first, __last). Returns an empty string if the * character sequence is not a valid collating element. */ template string_type lookup_collatename(_Fwd_iter __first, _Fwd_iter __last) const; /** * @brief Maps one or more characters to a named character * classification. * * @param __first beginning of the character sequence. * @param __last one-past-the-end of the character sequence. * @param __icase ignores the case of the classification name. * * @returns an unspecified value that represents the character * classification named by the character sequence designated by * the iterator range [__first, __last). If @p icase is true, * the returned mask identifies the classification regardless of * the case of the characters to be matched (for example, * [[:lower:]] is the same as [[:alpha:]]), otherwise a * case-dependent classification is returned. The value * returned shall be independent of the case of the characters * in the character sequence. If the name is not recognized then * returns a value that compares equal to 0. * * At least the following names (or their wide-character equivalent) are * supported. * - d * - w * - s * - alnum * - alpha * - blank * - cntrl * - digit * - graph * - lower * - print * - punct * - space * - upper * - xdigit */ template char_class_type lookup_classname(_Fwd_iter __first, _Fwd_iter __last, bool __icase = false) const; /** * @brief Determines if @p c is a member of an identified class. * * @param __c a character. * @param __f a class type (as returned from lookup_classname). * * @returns true if the character @p __c is a member of the classification * represented by @p __f, false otherwise. * * @throws std::bad_cast if the current locale does not have a ctype * facet. */ bool isctype(_Ch_type __c, char_class_type __f) const; /** * @brief Converts a digit to an int. * * @param __ch a character representing a digit. * @param __radix the radix if the numeric conversion (limited to 8, 10, * or 16). * * @returns the value represented by the digit __ch in base radix if the * character __ch is a valid digit in base radix; otherwise returns -1. */ int value(_Ch_type __ch, int __radix) const; /** * @brief Imbues the regex_traits object with a copy of a new locale. * * @param __loc A locale. * * @returns a copy of the previous locale in use by the regex_traits * object. * * @note Calling imbue with a different locale than the one currently in * use invalidates all cached data held by *this. */ locale_type imbue(locale_type __loc) { std::swap(_M_locale, __loc); return __loc; } /** * @brief Gets a copy of the current locale in use by the regex_traits * object. */ locale_type getloc() const { return _M_locale; } protected: locale_type _M_locale; }; // [7.8] Class basic_regex /** * Objects of specializations of this class represent regular expressions * constructed from sequences of character type @p _Ch_type. * * Storage for the regular expression is allocated and deallocated as * necessary by the member functions of this class. */ template> class basic_regex { public: static_assert(is_same<_Ch_type, typename _Rx_traits::char_type>::value, "regex traits class must have the same char_type"); // types: typedef _Ch_type value_type; typedef _Rx_traits traits_type; typedef typename traits_type::string_type string_type; typedef regex_constants::syntax_option_type flag_type; typedef typename traits_type::locale_type locale_type; /** * @name Constants * std [28.8.1](1) */ //@{ static constexpr flag_type icase = regex_constants::icase; static constexpr flag_type nosubs = regex_constants::nosubs; static constexpr flag_type optimize = regex_constants::optimize; static constexpr flag_type collate = regex_constants::collate; static constexpr flag_type ECMAScript = regex_constants::ECMAScript; static constexpr flag_type basic = regex_constants::basic; static constexpr flag_type extended = regex_constants::extended; static constexpr flag_type awk = regex_constants::awk; static constexpr flag_type grep = regex_constants::grep; static constexpr flag_type egrep = regex_constants::egrep; //@} // [7.8.2] construct/copy/destroy /** * Constructs a basic regular expression that does not match any * character sequence. */ basic_regex() : _M_flags(ECMAScript), _M_loc(), _M_automaton(nullptr) { } /** * @brief Constructs a basic regular expression from the * sequence [__p, __p + char_traits<_Ch_type>::length(__p)) * interpreted according to the flags in @p __f. * * @param __p A pointer to the start of a C-style null-terminated string * containing a regular expression. * @param __f Flags indicating the syntax rules and options. * * @throws regex_error if @p __p is not a valid regular expression. */ explicit basic_regex(const _Ch_type* __p, flag_type __f = ECMAScript) : basic_regex(__p, __p + char_traits<_Ch_type>::length(__p), __f) { } /** * @brief Constructs a basic regular expression from the sequence * [p, p + len) interpreted according to the flags in @p f. * * @param __p A pointer to the start of a string containing a regular * expression. * @param __len The length of the string containing the regular * expression. * @param __f Flags indicating the syntax rules and options. * * @throws regex_error if @p __p is not a valid regular expression. */ basic_regex(const _Ch_type* __p, std::size_t __len, flag_type __f = ECMAScript) : basic_regex(__p, __p + __len, __f) { } /** * @brief Copy-constructs a basic regular expression. * * @param __rhs A @p regex object. */ basic_regex(const basic_regex& __rhs) = default; /** * @brief Move-constructs a basic regular expression. * * @param __rhs A @p regex object. */ basic_regex(basic_regex&& __rhs) noexcept = default; /** * @brief Constructs a basic regular expression from the string * @p s interpreted according to the flags in @p f. * * @param __s A string containing a regular expression. * @param __f Flags indicating the syntax rules and options. * * @throws regex_error if @p __s is not a valid regular expression. */ template explicit basic_regex(const std::basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s, flag_type __f = ECMAScript) : basic_regex(__s.data(), __s.data() + __s.size(), __f) { } /** * @brief Constructs a basic regular expression from the range * [first, last) interpreted according to the flags in @p f. * * @param __first The start of a range containing a valid regular * expression. * @param __last The end of a range containing a valid regular * expression. * @param __f The format flags of the regular expression. * * @throws regex_error if @p [__first, __last) is not a valid regular * expression. */ template basic_regex(_FwdIter __first, _FwdIter __last, flag_type __f = ECMAScript) : basic_regex(std::move(__first), std::move(__last), locale_type(), __f) { } /** * @brief Constructs a basic regular expression from an initializer list. * * @param __l The initializer list. * @param __f The format flags of the regular expression. * * @throws regex_error if @p __l is not a valid regular expression. */ basic_regex(initializer_list<_Ch_type> __l, flag_type __f = ECMAScript) : basic_regex(__l.begin(), __l.end(), __f) { } /** * @brief Destroys a basic regular expression. */ ~basic_regex() { } /** * @brief Assigns one regular expression to another. */ basic_regex& operator=(const basic_regex& __rhs) { return this->assign(__rhs); } /** * @brief Move-assigns one regular expression to another. */ basic_regex& operator=(basic_regex&& __rhs) noexcept { return this->assign(std::move(__rhs)); } /** * @brief Replaces a regular expression with a new one constructed from * a C-style null-terminated string. * * @param __p A pointer to the start of a null-terminated C-style string * containing a regular expression. */ basic_regex& operator=(const _Ch_type* __p) { return this->assign(__p); } /** * @brief Replaces a regular expression with a new one constructed from * an initializer list. * * @param __l The initializer list. * * @throws regex_error if @p __l is not a valid regular expression. */ basic_regex& operator=(initializer_list<_Ch_type> __l) { return this->assign(__l.begin(), __l.end()); } /** * @brief Replaces a regular expression with a new one constructed from * a string. * * @param __s A pointer to a string containing a regular expression. */ template basic_regex& operator=(const basic_string<_Ch_type, _Ch_traits, _Alloc>& __s) { return this->assign(__s); } // [7.8.3] assign /** * @brief the real assignment operator. * * @param __rhs Another regular expression object. */ basic_regex& assign(const basic_regex& __rhs) { basic_regex __tmp(__rhs); this->swap(__tmp); return *this; } /** * @brief The move-assignment operator. * * @param __rhs Another regular expression object. */ basic_regex& assign(basic_regex&& __rhs) noexcept { basic_regex __tmp(std::move(__rhs)); this->swap(__tmp); return *this; } /** * @brief Assigns a new regular expression to a regex object from a * C-style null-terminated string containing a regular expression * pattern. * * @param __p A pointer to a C-style null-terminated string containing * a regular expression pattern. * @param __flags Syntax option flags. * * @throws regex_error if __p does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, *this remains unchanged. */ basic_regex& assign(const _Ch_type* __p, flag_type __flags = ECMAScript) { return this->assign(string_type(__p), __flags); } /** * @brief Assigns a new regular expression to a regex object from a * C-style string containing a regular expression pattern. * * @param __p A pointer to a C-style string containing a * regular expression pattern. * @param __len The length of the regular expression pattern string. * @param __flags Syntax option flags. * * @throws regex_error if p does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, *this remains unchanged. */ basic_regex& assign(const _Ch_type* __p, std::size_t __len, flag_type __flags) { return this->assign(string_type(__p, __len), __flags); } /** * @brief Assigns a new regular expression to a regex object from a * string containing a regular expression pattern. * * @param __s A string containing a regular expression pattern. * @param __flags Syntax option flags. * * @throws regex_error if __s does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, *this remains unchanged. */ template basic_regex& assign(const basic_string<_Ch_type, _Ch_traits, _Alloc>& __s, flag_type __flags = ECMAScript) { return this->assign(basic_regex(__s.data(), __s.data() + __s.size(), _M_loc, __flags)); } /** * @brief Assigns a new regular expression to a regex object. * * @param __first The start of a range containing a valid regular * expression. * @param __last The end of a range containing a valid regular * expression. * @param __flags Syntax option flags. * * @throws regex_error if p does not contain a valid regular * expression pattern interpreted according to @p __flags. If * regex_error is thrown, the object remains unchanged. */ template basic_regex& assign(_InputIterator __first, _InputIterator __last, flag_type __flags = ECMAScript) { return this->assign(string_type(__first, __last), __flags); } /** * @brief Assigns a new regular expression to a regex object. * * @param __l An initializer list representing a regular expression. * @param __flags Syntax option flags. * * @throws regex_error if @p __l does not contain a valid * regular expression pattern interpreted according to @p * __flags. If regex_error is thrown, the object remains * unchanged. */ basic_regex& assign(initializer_list<_Ch_type> __l, flag_type __flags = ECMAScript) { return this->assign(__l.begin(), __l.end(), __flags); } // [7.8.4] const operations /** * @brief Gets the number of marked subexpressions within the regular * expression. */ unsigned int mark_count() const { if (_M_automaton) return _M_automaton->_M_sub_count() - 1; return 0; } /** * @brief Gets the flags used to construct the regular expression * or in the last call to assign(). */ flag_type flags() const { return _M_flags; } // [7.8.5] locale /** * @brief Imbues the regular expression object with the given locale. * * @param __loc A locale. */ locale_type imbue(locale_type __loc) { std::swap(__loc, _M_loc); _M_automaton.reset(); return __loc; } /** * @brief Gets the locale currently imbued in the regular expression * object. */ locale_type getloc() const { return _M_loc; } // [7.8.6] swap /** * @brief Swaps the contents of two regular expression objects. * * @param __rhs Another regular expression object. */ void swap(basic_regex& __rhs) { std::swap(_M_flags, __rhs._M_flags); std::swap(_M_loc, __rhs._M_loc); std::swap(_M_automaton, __rhs._M_automaton); } #ifdef _GLIBCXX_DEBUG void _M_dot(std::ostream& __ostr) { _M_automaton->_M_dot(__ostr); } #endif private: typedef std::shared_ptr> _AutomatonPtr; template basic_regex(_FwdIter __first, _FwdIter __last, locale_type __loc, flag_type __f) : _M_flags(__f), _M_loc(std::move(__loc)), _M_automaton(__detail::__compile_nfa<_Rx_traits>( std::move(__first), std::move(__last), _M_loc, _M_flags)) { } template friend bool __detail::__regex_algo_impl(_Bp, _Bp, match_results<_Bp, _Ap>&, const basic_regex<_Cp, _Rp>&, regex_constants::match_flag_type); template friend class __detail::_Executor; flag_type _M_flags; locale_type _M_loc; _AutomatonPtr _M_automaton; }; #if __cplusplus < 201703L template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::icase; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::nosubs; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::optimize; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::collate; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::ECMAScript; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::basic; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::extended; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::awk; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::grep; template constexpr regex_constants::syntax_option_type basic_regex<_Ch, _Tr>::egrep; #endif // ! C++17 #if __cpp_deduction_guides >= 201606 template basic_regex(_ForwardIterator, _ForwardIterator, regex_constants::syntax_option_type = {}) -> basic_regex::value_type>; #endif /** @brief Standard regular expressions. */ typedef basic_regex regex; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Standard wide-character regular expressions. */ typedef basic_regex wregex; #endif // [7.8.6] basic_regex swap /** * @brief Swaps the contents of two regular expression objects. * @param __lhs First regular expression. * @param __rhs Second regular expression. */ template inline void swap(basic_regex<_Ch_type, _Rx_traits>& __lhs, basic_regex<_Ch_type, _Rx_traits>& __rhs) { __lhs.swap(__rhs); } // [7.9] Class template sub_match /** * A sequence of characters matched by a particular marked sub-expression. * * An object of this class is essentially a pair of iterators marking a * matched subexpression within a regular expression pattern match. Such * objects can be converted to and compared with std::basic_string objects * of a similar base character type as the pattern matched by the regular * expression. * * The iterators that make up the pair are the usual half-open interval * referencing the actual original pattern matched. */ template class sub_match : public std::pair<_BiIter, _BiIter> { typedef iterator_traits<_BiIter> __iter_traits; public: typedef typename __iter_traits::value_type value_type; typedef typename __iter_traits::difference_type difference_type; typedef _BiIter iterator; typedef std::basic_string string_type; bool matched; constexpr sub_match() : matched() { } /** * Gets the length of the matching sequence. */ difference_type length() const { return this->matched ? std::distance(this->first, this->second) : 0; } /** * @brief Gets the matching sequence as a string. * * @returns the matching sequence as a string. * * This is the implicit conversion operator. It is identical to the * str() member function except that it will want to pop up in * unexpected places and cause a great deal of confusion and cursing * from the unwary. */ operator string_type() const { return this->matched ? string_type(this->first, this->second) : string_type(); } /** * @brief Gets the matching sequence as a string. * * @returns the matching sequence as a string. */ string_type str() const { return this->matched ? string_type(this->first, this->second) : string_type(); } /** * @brief Compares this and another matched sequence. * * @param __s Another matched sequence to compare to this one. * * @retval <0 this matched sequence will collate before @p __s. * @retval =0 this matched sequence is equivalent to @p __s. * @retval <0 this matched sequence will collate after @p __s. */ int compare(const sub_match& __s) const { return this->str().compare(__s.str()); } /** * @brief Compares this sub_match to a string. * * @param __s A string to compare to this sub_match. * * @retval <0 this matched sequence will collate before @p __s. * @retval =0 this matched sequence is equivalent to @p __s. * @retval <0 this matched sequence will collate after @p __s. */ int compare(const string_type& __s) const { return this->str().compare(__s); } /** * @brief Compares this sub_match to a C-style string. * * @param __s A C-style string to compare to this sub_match. * * @retval <0 this matched sequence will collate before @p __s. * @retval =0 this matched sequence is equivalent to @p __s. * @retval <0 this matched sequence will collate after @p __s. */ int compare(const value_type* __s) const { return this->str().compare(__s); } }; /** @brief Standard regex submatch over a C-style null-terminated string. */ typedef sub_match csub_match; /** @brief Standard regex submatch over a standard string. */ typedef sub_match ssub_match; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Regex submatch over a C-style null-terminated wide string. */ typedef sub_match wcsub_match; /** @brief Regex submatch over a standard wide string. */ typedef sub_match wssub_match; #endif // [7.9.2] sub_match non-member operators /** * @brief Tests the equivalence of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) == 0; } /** * @brief Tests the inequivalence of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) != 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) < 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) <= 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) >= 0; } /** * @brief Tests the ordering of two regular expression submatches. * @param __lhs First regular expression submatch. * @param __rhs Second regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_BiIter>& __lhs, const sub_match<_BiIter>& __rhs) { return __lhs.compare(__rhs) > 0; } // Alias for sub_match'd string. template using __sub_match_string = basic_string< typename iterator_traits<_Bi_iter>::value_type, _Ch_traits, _Ch_alloc>; /** * @brief Tests the equivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(__lhs.data(), __lhs.size())) == 0; } /** * @brief Tests the inequivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(__lhs.data(), __lhs.size())) > 0; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(__rhs.data(), __rhs.size())) == 0; } /** * @brief Tests the inequivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(__rhs.data(), __rhs.size())) < 0; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_Bi_iter>& __lhs, const __sub_match_string<_Bi_iter, _Ch_traits, _Ch_alloc>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a C string and a regular expression * submatch. * @param __lhs A C string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs.compare(__lhs) == 0; } /** * @brief Tests the inequivalence of an iterator value and a regular * expression submatch. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs.compare(__lhs) > 0; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(typename iterator_traits<_Bi_iter>::value_type const* __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A pointer to a string? * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return __lhs.compare(__rhs) == 0; } /** * @brief Tests the inequivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A pointer to a string. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return __lhs.compare(__rhs) < 0; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A string. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const* __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(1, __lhs)) == 0; } /** * @brief Tests the inequivalence of a string and a regular expression * submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __rhs.compare(string_type(1, __lhs)) > 0; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a string and a regular expression submatch. * @param __lhs A string. * @param __rhs A regular expression submatch. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(typename iterator_traits<_Bi_iter>::value_type const& __lhs, const sub_match<_Bi_iter>& __rhs) { return !(__rhs < __lhs); } /** * @brief Tests the equivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs is equivalent to @a __rhs, false otherwise. */ template inline bool operator==(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(1, __rhs)) == 0; } /** * @brief Tests the inequivalence of a regular expression submatch and a * string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs is not equivalent to @a __rhs, false otherwise. */ template inline bool operator!=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return !(__lhs == __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs precedes @a __rhs, false otherwise. */ template inline bool operator<(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { typedef typename sub_match<_Bi_iter>::string_type string_type; return __lhs.compare(string_type(1, __rhs)) < 0; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs succeeds @a __rhs, false otherwise. */ template inline bool operator>(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return __rhs < __lhs; } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs does not precede @a __rhs, false otherwise. */ template inline bool operator>=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return !(__lhs < __rhs); } /** * @brief Tests the ordering of a regular expression submatch and a string. * @param __lhs A regular expression submatch. * @param __rhs A const string reference. * @returns true if @a __lhs does not succeed @a __rhs, false otherwise. */ template inline bool operator<=(const sub_match<_Bi_iter>& __lhs, typename iterator_traits<_Bi_iter>::value_type const& __rhs) { return !(__rhs < __lhs); } /** * @brief Inserts a matched string into an output stream. * * @param __os The output stream. * @param __m A submatch string. * * @returns the output stream with the submatch string inserted. */ template inline basic_ostream<_Ch_type, _Ch_traits>& operator<<(basic_ostream<_Ch_type, _Ch_traits>& __os, const sub_match<_Bi_iter>& __m) { return __os << __m.str(); } // [7.10] Class template match_results /** * @brief The results of a match or search operation. * * A collection of character sequences representing the result of a regular * expression match. Storage for the collection is allocated and freed as * necessary by the member functions of class template match_results. * * This class satisfies the Sequence requirements, with the exception that * only the operations defined for a const-qualified Sequence are supported. * * The sub_match object stored at index 0 represents sub-expression 0, i.e. * the whole match. In this case the %sub_match member matched is always true. * The sub_match object stored at index n denotes what matched the marked * sub-expression n within the matched expression. If the sub-expression n * participated in a regular expression match then the %sub_match member * matched evaluates to true, and members first and second denote the range * of characters [first, second) which formed that match. Otherwise matched * is false, and members first and second point to the end of the sequence * that was searched. * * @nosubgrouping */ template > > class match_results : private std::vector, _Alloc> { private: /* * The vector base is empty if this does not represent a match (!ready()); * Otherwise if it's a match failure, it contains 3 elements: * [0] unmatched * [1] prefix * [2] suffix * Otherwise it contains n+4 elements where n is the number of marked * sub-expressions: * [0] entire match * [1] 1st marked subexpression * ... * [n] nth marked subexpression * [n+1] unmatched * [n+2] prefix * [n+3] suffix */ typedef std::vector, _Alloc> _Base_type; typedef std::iterator_traits<_Bi_iter> __iter_traits; typedef regex_constants::match_flag_type match_flag_type; public: /** * @name 10.? Public Types */ //@{ typedef sub_match<_Bi_iter> value_type; typedef const value_type& const_reference; typedef value_type& reference; typedef typename _Base_type::const_iterator const_iterator; typedef const_iterator iterator; typedef typename __iter_traits::difference_type difference_type; typedef typename allocator_traits<_Alloc>::size_type size_type; typedef _Alloc allocator_type; typedef typename __iter_traits::value_type char_type; typedef std::basic_string string_type; //@} public: /** * @name 28.10.1 Construction, Copying, and Destruction */ //@{ /** * @brief Constructs a default %match_results container. * @post size() returns 0 and str() returns an empty string. */ explicit match_results(const _Alloc& __a = _Alloc()) : _Base_type(__a) { } /** * @brief Copy constructs a %match_results. */ match_results(const match_results& __rhs) = default; /** * @brief Move constructs a %match_results. */ match_results(match_results&& __rhs) noexcept = default; /** * @brief Assigns rhs to *this. */ match_results& operator=(const match_results& __rhs) = default; /** * @brief Move-assigns rhs to *this. */ match_results& operator=(match_results&& __rhs) = default; /** * @brief Destroys a %match_results object. */ ~match_results() { } //@} // 28.10.2, state: /** * @brief Indicates if the %match_results is ready. * @retval true The object has a fully-established result state. * @retval false The object is not ready. */ bool ready() const { return !_Base_type::empty(); } /** * @name 28.10.2 Size */ //@{ /** * @brief Gets the number of matches and submatches. * * The number of matches for a given regular expression will be either 0 * if there was no match or mark_count() + 1 if a match was successful. * Some matches may be empty. * * @returns the number of matches found. */ size_type size() const { return _Base_type::empty() ? 0 : _Base_type::size() - 3; } size_type max_size() const { return _Base_type::max_size(); } /** * @brief Indicates if the %match_results contains no results. * @retval true The %match_results object is empty. * @retval false The %match_results object is not empty. */ bool empty() const { return size() == 0; } //@} /** * @name 10.3 Element Access */ //@{ /** * @brief Gets the length of the indicated submatch. * @param __sub indicates the submatch. * @pre ready() == true * * This function returns the length of the indicated submatch, or the * length of the entire match if @p __sub is zero (the default). */ difference_type length(size_type __sub = 0) const { return (*this)[__sub].length(); } /** * @brief Gets the offset of the beginning of the indicated submatch. * @param __sub indicates the submatch. * @pre ready() == true * * This function returns the offset from the beginning of the target * sequence to the beginning of the submatch, unless the value of @p __sub * is zero (the default), in which case this function returns the offset * from the beginning of the target sequence to the beginning of the * match. */ difference_type position(size_type __sub = 0) const { return std::distance(_M_begin, (*this)[__sub].first); } /** * @brief Gets the match or submatch converted to a string type. * @param __sub indicates the submatch. * @pre ready() == true * * This function gets the submatch (or match, if @p __sub is * zero) extracted from the target range and converted to the * associated string type. */ string_type str(size_type __sub = 0) const { return string_type((*this)[__sub]); } /** * @brief Gets a %sub_match reference for the match or submatch. * @param __sub indicates the submatch. * @pre ready() == true * * This function gets a reference to the indicated submatch, or * the entire match if @p __sub is zero. * * If @p __sub >= size() then this function returns a %sub_match with a * special value indicating no submatch. */ const_reference operator[](size_type __sub) const { __glibcxx_assert( ready() ); return __sub < size() ? _Base_type::operator[](__sub) : _M_unmatched_sub(); } /** * @brief Gets a %sub_match representing the match prefix. * @pre ready() == true * * This function gets a reference to a %sub_match object representing the * part of the target range between the start of the target range and the * start of the match. */ const_reference prefix() const { __glibcxx_assert( ready() ); return !empty() ? _M_prefix() : _M_unmatched_sub(); } /** * @brief Gets a %sub_match representing the match suffix. * @pre ready() == true * * This function gets a reference to a %sub_match object representing the * part of the target range between the end of the match and the end of * the target range. */ const_reference suffix() const { __glibcxx_assert( ready() ); return !empty() ? _M_suffix() : _M_unmatched_sub(); } /** * @brief Gets an iterator to the start of the %sub_match collection. */ const_iterator begin() const { return _Base_type::begin(); } /** * @brief Gets an iterator to the start of the %sub_match collection. */ const_iterator cbegin() const { return this->begin(); } /** * @brief Gets an iterator to one-past-the-end of the collection. */ const_iterator end() const { return _Base_type::end() - (empty() ? 0 : 3); } /** * @brief Gets an iterator to one-past-the-end of the collection. */ const_iterator cend() const { return this->end(); } //@} /** * @name 10.4 Formatting * * These functions perform formatted substitution of the matched * character sequences into their target. The format specifiers and * escape sequences accepted by these functions are determined by * their @p flags parameter as documented above. */ //@{ /** * @pre ready() == true */ template _Out_iter format(_Out_iter __out, const char_type* __fmt_first, const char_type* __fmt_last, match_flag_type __flags = regex_constants::format_default) const; /** * @pre ready() == true */ template _Out_iter format(_Out_iter __out, const basic_string& __fmt, match_flag_type __flags = regex_constants::format_default) const { return format(__out, __fmt.data(), __fmt.data() + __fmt.size(), __flags); } /** * @pre ready() == true */ template basic_string format(const basic_string& __fmt, match_flag_type __flags = regex_constants::format_default) const { basic_string __result; format(std::back_inserter(__result), __fmt, __flags); return __result; } /** * @pre ready() == true */ string_type format(const char_type* __fmt, match_flag_type __flags = regex_constants::format_default) const { string_type __result; format(std::back_inserter(__result), __fmt, __fmt + char_traits::length(__fmt), __flags); return __result; } //@} /** * @name 10.5 Allocator */ //@{ /** * @brief Gets a copy of the allocator. */ allocator_type get_allocator() const { return _Base_type::get_allocator(); } //@} /** * @name 10.6 Swap */ //@{ /** * @brief Swaps the contents of two match_results. */ void swap(match_results& __that) { using std::swap; _Base_type::swap(__that); swap(_M_begin, __that._M_begin); } //@} private: template friend class __detail::_Executor; template friend class regex_iterator; template friend bool __detail::__regex_algo_impl(_Bp, _Bp, match_results<_Bp, _Ap>&, const basic_regex<_Cp, _Rp>&, regex_constants::match_flag_type); void _M_resize(unsigned int __size) { _Base_type::resize(__size + 3); } const_reference _M_unmatched_sub() const { return _Base_type::operator[](_Base_type::size() - 3); } sub_match<_Bi_iter>& _M_unmatched_sub() { return _Base_type::operator[](_Base_type::size() - 3); } const_reference _M_prefix() const { return _Base_type::operator[](_Base_type::size() - 2); } sub_match<_Bi_iter>& _M_prefix() { return _Base_type::operator[](_Base_type::size() - 2); } const_reference _M_suffix() const { return _Base_type::operator[](_Base_type::size() - 1); } sub_match<_Bi_iter>& _M_suffix() { return _Base_type::operator[](_Base_type::size() - 1); } _Bi_iter _M_begin; }; typedef match_results cmatch; typedef match_results smatch; #ifdef _GLIBCXX_USE_WCHAR_T typedef match_results wcmatch; typedef match_results wsmatch; #endif // match_results comparisons /** * @brief Compares two match_results for equality. * @returns true if the two objects refer to the same match, * false otherwise. */ template inline bool operator==(const match_results<_Bi_iter, _Alloc>& __m1, const match_results<_Bi_iter, _Alloc>& __m2) { if (__m1.ready() != __m2.ready()) return false; if (!__m1.ready()) // both are not ready return true; if (__m1.empty() != __m2.empty()) return false; if (__m1.empty()) // both are empty return true; return __m1.prefix() == __m2.prefix() && __m1.size() == __m2.size() && std::equal(__m1.begin(), __m1.end(), __m2.begin()) && __m1.suffix() == __m2.suffix(); } /** * @brief Compares two match_results for inequality. * @returns true if the two objects do not refer to the same match, * false otherwise. */ template inline bool operator!=(const match_results<_Bi_iter, _Alloc>& __m1, const match_results<_Bi_iter, _Alloc>& __m2) { return !(__m1 == __m2); } // [7.10.6] match_results swap /** * @brief Swaps two match results. * @param __lhs A match result. * @param __rhs A match result. * * The contents of the two match_results objects are swapped. */ template inline void swap(match_results<_Bi_iter, _Alloc>& __lhs, match_results<_Bi_iter, _Alloc>& __rhs) { __lhs.swap(__rhs); } _GLIBCXX_END_NAMESPACE_CXX11 // [7.11.2] Function template regex_match /** * @name Matching, Searching, and Replacing */ //@{ /** * @brief Determines if there is a match between the regular expression @p e * and all of the character sequence [first, last). * * @param __s Start of the character sequence to match. * @param __e One-past-the-end of the character sequence to match. * @param __m The match results. * @param __re The regular expression. * @param __flags Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(_Bi_iter __s, _Bi_iter __e, match_results<_Bi_iter, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return __detail::__regex_algo_impl<_Bi_iter, _Alloc, _Ch_type, _Rx_traits, __detail::_RegexExecutorPolicy::_S_auto, true> (__s, __e, __m, __re, __flags); } /** * @brief Indicates if there is a match between the regular expression @p e * and all of the character sequence [first, last). * * @param __first Beginning of the character sequence to match. * @param __last One-past-the-end of the character sequence to match. * @param __re The regular expression. * @param __flags Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(_Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { match_results<_Bi_iter> __what; return regex_match(__first, __last, __what, __re, __flags); } /** * @brief Determines if there is a match between the regular expression @p e * and a C-style null-terminated string. * * @param __s The C-style null-terminated string to match. * @param __m The match results. * @param __re The regular expression. * @param __f Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const _Ch_type* __s, match_results& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_match(__s, __s + _Rx_traits::length(__s), __m, __re, __f); } /** * @brief Determines if there is a match between the regular expression @p e * and a string. * * @param __s The string to match. * @param __m The match results. * @param __re The regular expression. * @param __flags Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s, match_results::const_iterator, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_match(__s.begin(), __s.end(), __m, __re, __flags); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2329. regex_match() with match_results should forbid temporary strings /// Prevent unsafe attempts to get match_results from a temporary string. template bool regex_match(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>&&, match_results::const_iterator, _Alloc>&, const basic_regex<_Ch_type, _Rx_traits>&, regex_constants::match_flag_type = regex_constants::match_default) = delete; /** * @brief Indicates if there is a match between the regular expression @p e * and a C-style null-terminated string. * * @param __s The C-style null-terminated string to match. * @param __re The regular expression. * @param __f Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_match(__s, __s + _Rx_traits::length(__s), __re, __f); } /** * @brief Indicates if there is a match between the regular expression @p e * and a string. * * @param __s [IN] The string to match. * @param __re [IN] The regular expression. * @param __flags [IN] Controls how the regular expression is matched. * * @retval true A match exists. * @retval false Otherwise. * * @throws an exception of type regex_error. */ template inline bool regex_match(const basic_string<_Ch_type, _Ch_traits, _Str_allocator>& __s, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_match(__s.begin(), __s.end(), __re, __flags); } // [7.11.3] Function template regex_search /** * Searches for a regular expression within a range. * @param __s [IN] The start of the string to search. * @param __e [IN] One-past-the-end of the string to search. * @param __m [OUT] The match results. * @param __re [IN] The regular expression to search for. * @param __flags [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string, the content of %m is * undefined. * * @throws an exception of type regex_error. */ template inline bool regex_search(_Bi_iter __s, _Bi_iter __e, match_results<_Bi_iter, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { return __detail::__regex_algo_impl<_Bi_iter, _Alloc, _Ch_type, _Rx_traits, __detail::_RegexExecutorPolicy::_S_auto, false> (__s, __e, __m, __re, __flags); } /** * Searches for a regular expression within a range. * @param __first [IN] The start of the string to search. * @param __last [IN] One-past-the-end of the string to search. * @param __re [IN] The regular expression to search for. * @param __flags [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string. * * @throws an exception of type regex_error. */ template inline bool regex_search(_Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __re, regex_constants::match_flag_type __flags = regex_constants::match_default) { match_results<_Bi_iter> __what; return regex_search(__first, __last, __what, __re, __flags); } /** * @brief Searches for a regular expression within a C-string. * @param __s [IN] A C-string to search for the regex. * @param __m [OUT] The set of regex matches. * @param __e [IN] The regex to search for in @p s. * @param __f [IN] The search flags. * @retval true A match was found within the string. * @retval false No match was found within the string, the content of %m is * undefined. * * @throws an exception of type regex_error. */ template inline bool regex_search(const _Ch_type* __s, match_results& __m, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_search(__s, __s + _Rx_traits::length(__s), __m, __e, __f); } /** * @brief Searches for a regular expression within a C-string. * @param __s [IN] The C-string to search. * @param __e [IN] The regular expression to search for. * @param __f [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string. * * @throws an exception of type regex_error. */ template inline bool regex_search(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_search(__s, __s + _Rx_traits::length(__s), __e, __f); } /** * @brief Searches for a regular expression within a string. * @param __s [IN] The string to search. * @param __e [IN] The regular expression to search for. * @param __flags [IN] Search policy flags. * @retval true A match was found within the string. * @retval false No match was found within the string. * * @throws an exception of type regex_error. */ template inline bool regex_search(const basic_string<_Ch_type, _Ch_traits, _String_allocator>& __s, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_search(__s.begin(), __s.end(), __e, __flags); } /** * @brief Searches for a regular expression within a string. * @param __s [IN] A C++ string to search for the regex. * @param __m [OUT] The set of regex matches. * @param __e [IN] The regex to search for in @p s. * @param __f [IN] The search flags. * @retval true A match was found within the string. * @retval false No match was found within the string, the content of %m is * undefined. * * @throws an exception of type regex_error. */ template inline bool regex_search(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s, match_results::const_iterator, _Alloc>& __m, const basic_regex<_Ch_type, _Rx_traits>& __e, regex_constants::match_flag_type __f = regex_constants::match_default) { return regex_search(__s.begin(), __s.end(), __m, __e, __f); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2329. regex_search() with match_results should forbid temporary strings /// Prevent unsafe attempts to get match_results from a temporary string. template bool regex_search(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>&&, match_results::const_iterator, _Alloc>&, const basic_regex<_Ch_type, _Rx_traits>&, regex_constants::match_flag_type = regex_constants::match_default) = delete; // std [28.11.4] Function template regex_replace /** * @brief Search for a regular expression within a range for multiple times, and replace the matched parts through filling a format string. * @param __out [OUT] The output iterator. * @param __first [IN] The start of the string to search. * @param __last [IN] One-past-the-end of the string to search. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format string. * @param __flags [IN] Search and replace policy flags. * * @returns __out * @throws an exception of type regex_error. */ template inline _Out_iter regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __e, const basic_string<_Ch_type, _St, _Sa>& __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { return regex_replace(__out, __first, __last, __e, __fmt.c_str(), __flags); } /** * @brief Search for a regular expression within a range for multiple times, and replace the matched parts through filling a format C-string. * @param __out [OUT] The output iterator. * @param __first [IN] The start of the string to search. * @param __last [IN] One-past-the-end of the string to search. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format C-string. * @param __flags [IN] Search and replace policy flags. * * @returns __out * @throws an exception of type regex_error. */ template _Out_iter regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default); /** * @brief Search for a regular expression within a string for multiple times, and replace the matched parts through filling a format string. * @param __s [IN] The string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type, _St, _Sa> regex_replace(const basic_string<_Ch_type, _St, _Sa>& __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const basic_string<_Ch_type, _Fst, _Fsa>& __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type, _St, _Sa> __result; regex_replace(std::back_inserter(__result), __s.begin(), __s.end(), __e, __fmt, __flags); return __result; } /** * @brief Search for a regular expression within a string for multiple times, and replace the matched parts through filling a format C-string. * @param __s [IN] The string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format C-string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type, _St, _Sa> regex_replace(const basic_string<_Ch_type, _St, _Sa>& __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type, _St, _Sa> __result; regex_replace(std::back_inserter(__result), __s.begin(), __s.end(), __e, __fmt, __flags); return __result; } /** * @brief Search for a regular expression within a C-string for multiple times, and replace the matched parts through filling a format string. * @param __s [IN] The C-string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type> regex_replace(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const basic_string<_Ch_type, _St, _Sa>& __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type> __result; regex_replace(std::back_inserter(__result), __s, __s + char_traits<_Ch_type>::length(__s), __e, __fmt, __flags); return __result; } /** * @brief Search for a regular expression within a C-string for multiple times, and replace the matched parts through filling a format C-string. * @param __s [IN] The C-string to search and replace. * @param __e [IN] The regular expression to search for. * @param __fmt [IN] The format C-string. * @param __flags [IN] Search and replace policy flags. * * @returns The string after replacing. * @throws an exception of type regex_error. */ template inline basic_string<_Ch_type> regex_replace(const _Ch_type* __s, const basic_regex<_Ch_type, _Rx_traits>& __e, const _Ch_type* __fmt, regex_constants::match_flag_type __flags = regex_constants::match_default) { basic_string<_Ch_type> __result; regex_replace(std::back_inserter(__result), __s, __s + char_traits<_Ch_type>::length(__s), __e, __fmt, __flags); return __result; } //@} _GLIBCXX_BEGIN_NAMESPACE_CXX11 // std [28.12] Class template regex_iterator /** * An iterator adaptor that will provide repeated calls of regex_search over * a range until no more matches remain. */ template::value_type, typename _Rx_traits = regex_traits<_Ch_type> > class regex_iterator { public: typedef basic_regex<_Ch_type, _Rx_traits> regex_type; typedef match_results<_Bi_iter> value_type; typedef std::ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; typedef std::forward_iterator_tag iterator_category; /** * @brief Provides a singular iterator, useful for indicating * one-past-the-end of a range. */ regex_iterator() : _M_pregex() { } /** * Constructs a %regex_iterator... * @param __a [IN] The start of a text range to search. * @param __b [IN] One-past-the-end of the text range to search. * @param __re [IN] The regular expression to match. * @param __m [IN] Policy flags for match rules. */ regex_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_begin(__a), _M_end(__b), _M_pregex(&__re), _M_flags(__m), _M_match() { if (!regex_search(_M_begin, _M_end, _M_match, *_M_pregex, _M_flags)) *this = regex_iterator(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2332. regex_iterator should forbid temporary regexes regex_iterator(_Bi_iter, _Bi_iter, const regex_type&&, regex_constants::match_flag_type = regex_constants::match_default) = delete; /** * Copy constructs a %regex_iterator. */ regex_iterator(const regex_iterator& __rhs) = default; /** * @brief Assigns one %regex_iterator to another. */ regex_iterator& operator=(const regex_iterator& __rhs) = default; /** * @brief Tests the equivalence of two regex iterators. */ bool operator==(const regex_iterator& __rhs) const; /** * @brief Tests the inequivalence of two regex iterators. */ bool operator!=(const regex_iterator& __rhs) const { return !(*this == __rhs); } /** * @brief Dereferences a %regex_iterator. */ const value_type& operator*() const { return _M_match; } /** * @brief Selects a %regex_iterator member. */ const value_type* operator->() const { return &_M_match; } /** * @brief Increments a %regex_iterator. */ regex_iterator& operator++(); /** * @brief Postincrements a %regex_iterator. */ regex_iterator operator++(int) { auto __tmp = *this; ++(*this); return __tmp; } private: _Bi_iter _M_begin; _Bi_iter _M_end; const regex_type* _M_pregex; regex_constants::match_flag_type _M_flags; match_results<_Bi_iter> _M_match; }; typedef regex_iterator cregex_iterator; typedef regex_iterator sregex_iterator; #ifdef _GLIBCXX_USE_WCHAR_T typedef regex_iterator wcregex_iterator; typedef regex_iterator wsregex_iterator; #endif // [7.12.2] Class template regex_token_iterator /** * Iterates over submatches in a range (or @a splits a text string). * * The purpose of this iterator is to enumerate all, or all specified, * matches of a regular expression within a text range. The dereferenced * value of an iterator of this class is a std::sub_match object. */ template::value_type, typename _Rx_traits = regex_traits<_Ch_type> > class regex_token_iterator { public: typedef basic_regex<_Ch_type, _Rx_traits> regex_type; typedef sub_match<_Bi_iter> value_type; typedef std::ptrdiff_t difference_type; typedef const value_type* pointer; typedef const value_type& reference; typedef std::forward_iterator_tag iterator_category; public: /** * @brief Default constructs a %regex_token_iterator. * * A default-constructed %regex_token_iterator is a singular iterator * that will compare equal to the one-past-the-end value for any * iterator of the same type. */ regex_token_iterator() : _M_position(), _M_subs(), _M_suffix(), _M_n(0), _M_result(nullptr), _M_has_m1(false) { } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatch [IN] Which submatch to return. There are some * special values for this parameter: * - -1 each enumerated subexpression does NOT * match the regular expression (aka field * splitting) * - 0 the entire string matching the * subexpression is returned for each match * within the text. * - >0 enumerates only the indicated * subexpression from a match within the text. * @param __m [IN] Policy flags for match rules. */ regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, int __submatch = 0, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(1, __submatch), _M_n(0) { _M_init(__a, __b); } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatches [IN] A list of subexpressions to return for each * regular expression match within the text. * @param __m [IN] Policy flags for match rules. */ regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, const std::vector& __submatches, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(__submatches), _M_n(0) { _M_init(__a, __b); } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatches [IN] A list of subexpressions to return for each * regular expression match within the text. * @param __m [IN] Policy flags for match rules. */ regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, initializer_list __submatches, regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(__submatches), _M_n(0) { _M_init(__a, __b); } /** * Constructs a %regex_token_iterator... * @param __a [IN] The start of the text to search. * @param __b [IN] One-past-the-end of the text to search. * @param __re [IN] The regular expression to search for. * @param __submatches [IN] A list of subexpressions to return for each * regular expression match within the text. * @param __m [IN] Policy flags for match rules. */ template regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re, const int (&__submatches)[_Nm], regex_constants::match_flag_type __m = regex_constants::match_default) : _M_position(__a, __b, __re, __m), _M_subs(__submatches, __submatches + _Nm), _M_n(0) { _M_init(__a, __b); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2332. regex_token_iterator should forbid temporary regexes regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, int = 0, regex_constants::match_flag_type = regex_constants::match_default) = delete; regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, const std::vector&, regex_constants::match_flag_type = regex_constants::match_default) = delete; regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, initializer_list, regex_constants::match_flag_type = regex_constants::match_default) = delete; template regex_token_iterator(_Bi_iter, _Bi_iter, const regex_type&&, const int (&)[_Nm], regex_constants::match_flag_type = regex_constants::match_default) = delete; /** * @brief Copy constructs a %regex_token_iterator. * @param __rhs [IN] A %regex_token_iterator to copy. */ regex_token_iterator(const regex_token_iterator& __rhs) : _M_position(__rhs._M_position), _M_subs(__rhs._M_subs), _M_suffix(__rhs._M_suffix), _M_n(__rhs._M_n), _M_has_m1(__rhs._M_has_m1) { _M_normalize_result(); } /** * @brief Assigns a %regex_token_iterator to another. * @param __rhs [IN] A %regex_token_iterator to copy. */ regex_token_iterator& operator=(const regex_token_iterator& __rhs); /** * @brief Compares a %regex_token_iterator to another for equality. */ bool operator==(const regex_token_iterator& __rhs) const; /** * @brief Compares a %regex_token_iterator to another for inequality. */ bool operator!=(const regex_token_iterator& __rhs) const { return !(*this == __rhs); } /** * @brief Dereferences a %regex_token_iterator. */ const value_type& operator*() const { return *_M_result; } /** * @brief Selects a %regex_token_iterator member. */ const value_type* operator->() const { return _M_result; } /** * @brief Increments a %regex_token_iterator. */ regex_token_iterator& operator++(); /** * @brief Postincrements a %regex_token_iterator. */ regex_token_iterator operator++(int) { auto __tmp = *this; ++(*this); return __tmp; } private: typedef regex_iterator<_Bi_iter, _Ch_type, _Rx_traits> _Position; void _M_init(_Bi_iter __a, _Bi_iter __b); const value_type& _M_current_match() const { if (_M_subs[_M_n] == -1) return (*_M_position).prefix(); else return (*_M_position)[_M_subs[_M_n]]; } constexpr bool _M_end_of_seq() const { return _M_result == nullptr; } // [28.12.2.2.4] void _M_normalize_result() { if (_M_position != _Position()) _M_result = &_M_current_match(); else if (_M_has_m1) _M_result = &_M_suffix; else _M_result = nullptr; } _Position _M_position; std::vector _M_subs; value_type _M_suffix; std::size_t _M_n; const value_type* _M_result; // Show whether _M_subs contains -1 bool _M_has_m1; }; /** @brief Token iterator for C-style NULL-terminated strings. */ typedef regex_token_iterator cregex_token_iterator; /** @brief Token iterator for standard strings. */ typedef regex_token_iterator sregex_token_iterator; #ifdef _GLIBCXX_USE_WCHAR_T /** @brief Token iterator for C-style NULL-terminated wide strings. */ typedef regex_token_iterator wcregex_token_iterator; /** @brief Token iterator for standard wide-character strings. */ typedef regex_token_iterator wsregex_token_iterator; #endif //@} // group regex _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include c++/8/bits/stl_deque.h000064400000231357151027430570010401 0ustar00// Deque implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_deque.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{deque} */ #ifndef _STL_DEQUE_H #define _STL_DEQUE_H 1 #include #include #include #if __cplusplus >= 201103L #include #endif #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * @brief This function controls the size of memory nodes. * @param __size The size of an element. * @return The number (not byte size) of elements per node. * * This function started off as a compiler kludge from SGI, but * seems to be a useful wrapper around a repeated constant * expression. The @b 512 is tunable (and no other code needs to * change), but no investigation has been done since inheriting the * SGI code. Touch _GLIBCXX_DEQUE_BUF_SIZE only if you know what * you are doing, however: changing it breaks the binary * compatibility!! */ #ifndef _GLIBCXX_DEQUE_BUF_SIZE #define _GLIBCXX_DEQUE_BUF_SIZE 512 #endif _GLIBCXX_CONSTEXPR inline size_t __deque_buf_size(size_t __size) { return (__size < _GLIBCXX_DEQUE_BUF_SIZE ? size_t(_GLIBCXX_DEQUE_BUF_SIZE / __size) : size_t(1)); } /** * @brief A deque::iterator. * * Quite a bit of intelligence here. Much of the functionality of * deque is actually passed off to this class. A deque holds two * of these internally, marking its valid range. Access to * elements is done as offsets of either of those two, relying on * operator overloading in this class. * * All the functions are op overloads except for _M_set_node. */ template struct _Deque_iterator { #if __cplusplus < 201103L typedef _Deque_iterator<_Tp, _Tp&, _Tp*> iterator; typedef _Deque_iterator<_Tp, const _Tp&, const _Tp*> const_iterator; typedef _Tp* _Elt_pointer; typedef _Tp** _Map_pointer; #else private: template using __ptr_to = typename pointer_traits<_Ptr>::template rebind<_Up>; template using __iter = _Deque_iterator<_Tp, _CvTp&, __ptr_to<_CvTp>>; public: typedef __iter<_Tp> iterator; typedef __iter const_iterator; typedef __ptr_to<_Tp> _Elt_pointer; typedef __ptr_to<_Elt_pointer> _Map_pointer; #endif static size_t _S_buffer_size() _GLIBCXX_NOEXCEPT { return __deque_buf_size(sizeof(_Tp)); } typedef std::random_access_iterator_tag iterator_category; typedef _Tp value_type; typedef _Ptr pointer; typedef _Ref reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Deque_iterator _Self; _Elt_pointer _M_cur; _Elt_pointer _M_first; _Elt_pointer _M_last; _Map_pointer _M_node; _Deque_iterator(_Elt_pointer __x, _Map_pointer __y) _GLIBCXX_NOEXCEPT : _M_cur(__x), _M_first(*__y), _M_last(*__y + _S_buffer_size()), _M_node(__y) { } _Deque_iterator() _GLIBCXX_NOEXCEPT : _M_cur(), _M_first(), _M_last(), _M_node() { } _Deque_iterator(const iterator& __x) _GLIBCXX_NOEXCEPT : _M_cur(__x._M_cur), _M_first(__x._M_first), _M_last(__x._M_last), _M_node(__x._M_node) { } iterator _M_const_cast() const _GLIBCXX_NOEXCEPT { return iterator(_M_cur, _M_node); } reference operator*() const _GLIBCXX_NOEXCEPT { return *_M_cur; } pointer operator->() const _GLIBCXX_NOEXCEPT { return _M_cur; } _Self& operator++() _GLIBCXX_NOEXCEPT { ++_M_cur; if (_M_cur == _M_last) { _M_set_node(_M_node + 1); _M_cur = _M_first; } return *this; } _Self operator++(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; ++*this; return __tmp; } _Self& operator--() _GLIBCXX_NOEXCEPT { if (_M_cur == _M_first) { _M_set_node(_M_node - 1); _M_cur = _M_last; } --_M_cur; return *this; } _Self operator--(int) _GLIBCXX_NOEXCEPT { _Self __tmp = *this; --*this; return __tmp; } _Self& operator+=(difference_type __n) _GLIBCXX_NOEXCEPT { const difference_type __offset = __n + (_M_cur - _M_first); if (__offset >= 0 && __offset < difference_type(_S_buffer_size())) _M_cur += __n; else { const difference_type __node_offset = __offset > 0 ? __offset / difference_type(_S_buffer_size()) : -difference_type((-__offset - 1) / _S_buffer_size()) - 1; _M_set_node(_M_node + __node_offset); _M_cur = _M_first + (__offset - __node_offset * difference_type(_S_buffer_size())); } return *this; } _Self operator+(difference_type __n) const _GLIBCXX_NOEXCEPT { _Self __tmp = *this; return __tmp += __n; } _Self& operator-=(difference_type __n) _GLIBCXX_NOEXCEPT { return *this += -__n; } _Self operator-(difference_type __n) const _GLIBCXX_NOEXCEPT { _Self __tmp = *this; return __tmp -= __n; } reference operator[](difference_type __n) const _GLIBCXX_NOEXCEPT { return *(*this + __n); } /** * Prepares to traverse new_node. Sets everything except * _M_cur, which should therefore be set by the caller * immediately afterwards, based on _M_first and _M_last. */ void _M_set_node(_Map_pointer __new_node) _GLIBCXX_NOEXCEPT { _M_node = __new_node; _M_first = *__new_node; _M_last = _M_first + difference_type(_S_buffer_size()); } }; // Note: we also provide overloads whose operands are of the same type in // order to avoid ambiguous overload resolution when std::rel_ops operators // are in scope (for additional details, see libstdc++/3628) template inline bool operator==(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return __x._M_cur == __y._M_cur; } template inline bool operator==(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return __x._M_cur == __y._M_cur; } template inline bool operator!=(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return !(__x == __y); } template inline bool operator!=(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return !(__x == __y); } template inline bool operator<(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return (__x._M_node == __y._M_node) ? (__x._M_cur < __y._M_cur) : (__x._M_node < __y._M_node); } template inline bool operator<(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return (__x._M_node == __y._M_node) ? (__x._M_cur < __y._M_cur) : (__x._M_node < __y._M_node); } template inline bool operator>(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return __y < __x; } template inline bool operator>(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return __y < __x; } template inline bool operator<=(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return !(__y < __x); } template inline bool operator<=(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return !(__y < __x); } template inline bool operator>=(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return !(__x < __y); } template inline bool operator>=(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return !(__x < __y); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR179 not only the various comparison // operators but also operator- must accept mixed iterator/const_iterator // parameters. template inline typename _Deque_iterator<_Tp, _Ref, _Ptr>::difference_type operator-(const _Deque_iterator<_Tp, _Ref, _Ptr>& __x, const _Deque_iterator<_Tp, _Ref, _Ptr>& __y) _GLIBCXX_NOEXCEPT { return typename _Deque_iterator<_Tp, _Ref, _Ptr>::difference_type (_Deque_iterator<_Tp, _Ref, _Ptr>::_S_buffer_size()) * (__x._M_node - __y._M_node - 1) + (__x._M_cur - __x._M_first) + (__y._M_last - __y._M_cur); } template inline typename _Deque_iterator<_Tp, _RefL, _PtrL>::difference_type operator-(const _Deque_iterator<_Tp, _RefL, _PtrL>& __x, const _Deque_iterator<_Tp, _RefR, _PtrR>& __y) _GLIBCXX_NOEXCEPT { return typename _Deque_iterator<_Tp, _RefL, _PtrL>::difference_type (_Deque_iterator<_Tp, _RefL, _PtrL>::_S_buffer_size()) * (__x._M_node - __y._M_node - 1) + (__x._M_cur - __x._M_first) + (__y._M_last - __y._M_cur); } template inline _Deque_iterator<_Tp, _Ref, _Ptr> operator+(ptrdiff_t __n, const _Deque_iterator<_Tp, _Ref, _Ptr>& __x) _GLIBCXX_NOEXCEPT { return __x + __n; } template void fill(const _Deque_iterator<_Tp, _Tp&, _Tp*>&, const _Deque_iterator<_Tp, _Tp&, _Tp*>&, const _Tp&); template _Deque_iterator<_Tp, _Tp&, _Tp*> copy(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> copy(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::copy(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } template _Deque_iterator<_Tp, _Tp&, _Tp*> copy_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> copy_backward(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::copy_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } #if __cplusplus >= 201103L template _Deque_iterator<_Tp, _Tp&, _Tp*> move(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> move(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::move(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } template _Deque_iterator<_Tp, _Tp&, _Tp*> move_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, const _Tp&, const _Tp*>, _Deque_iterator<_Tp, _Tp&, _Tp*>); template inline _Deque_iterator<_Tp, _Tp&, _Tp*> move_backward(_Deque_iterator<_Tp, _Tp&, _Tp*> __first, _Deque_iterator<_Tp, _Tp&, _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { return std::move_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*>(__first), _Deque_iterator<_Tp, const _Tp&, const _Tp*>(__last), __result); } #endif /** * Deque base class. This class provides the unified face for %deque's * allocation. This class's constructor and destructor allocate and * deallocate (but do not initialize) storage. This makes %exception * safety easier. * * Nothing in this class ever constructs or destroys an actual Tp element. * (Deque handles that itself.) Only/All memory management is performed * here. */ template class _Deque_base { protected: typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Tp>::other _Tp_alloc_type; typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Alloc_traits; #if __cplusplus < 201103L typedef _Tp* _Ptr; typedef const _Tp* _Ptr_const; #else typedef typename _Alloc_traits::pointer _Ptr; typedef typename _Alloc_traits::const_pointer _Ptr_const; #endif typedef typename _Alloc_traits::template rebind<_Ptr>::other _Map_alloc_type; typedef __gnu_cxx::__alloc_traits<_Map_alloc_type> _Map_alloc_traits; public: typedef _Alloc allocator_type; typedef typename _Alloc_traits::size_type size_type; allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Tp_allocator()); } typedef _Deque_iterator<_Tp, _Tp&, _Ptr> iterator; typedef _Deque_iterator<_Tp, const _Tp&, _Ptr_const> const_iterator; _Deque_base() : _M_impl() { _M_initialize_map(0); } _Deque_base(size_t __num_elements) : _M_impl() { _M_initialize_map(__num_elements); } _Deque_base(const allocator_type& __a, size_t __num_elements) : _M_impl(__a) { _M_initialize_map(__num_elements); } _Deque_base(const allocator_type& __a) : _M_impl(__a) { /* Caller must initialize map. */ } #if __cplusplus >= 201103L _Deque_base(_Deque_base&& __x, false_type) : _M_impl(__x._M_move_impl()) { } _Deque_base(_Deque_base&& __x, true_type) : _M_impl(std::move(__x._M_get_Tp_allocator())) { _M_initialize_map(0); if (__x._M_impl._M_map) this->_M_impl._M_swap_data(__x._M_impl); } _Deque_base(_Deque_base&& __x) : _Deque_base(std::move(__x), typename _Alloc_traits::is_always_equal{}) { } _Deque_base(_Deque_base&& __x, const allocator_type& __a, size_type __n) : _M_impl(__a) { if (__x.get_allocator() == __a) { if (__x._M_impl._M_map) { _M_initialize_map(0); this->_M_impl._M_swap_data(__x._M_impl); } } else { _M_initialize_map(__n); } } #endif ~_Deque_base() _GLIBCXX_NOEXCEPT; protected: typedef typename iterator::_Map_pointer _Map_pointer; //This struct encapsulates the implementation of the std::deque //standard container and at the same time makes use of the EBO //for empty allocators. struct _Deque_impl : public _Tp_alloc_type { _Map_pointer _M_map; size_t _M_map_size; iterator _M_start; iterator _M_finish; _Deque_impl() : _Tp_alloc_type(), _M_map(), _M_map_size(0), _M_start(), _M_finish() { } _Deque_impl(const _Tp_alloc_type& __a) _GLIBCXX_NOEXCEPT : _Tp_alloc_type(__a), _M_map(), _M_map_size(0), _M_start(), _M_finish() { } #if __cplusplus >= 201103L _Deque_impl(_Deque_impl&&) = default; _Deque_impl(_Tp_alloc_type&& __a) noexcept : _Tp_alloc_type(std::move(__a)), _M_map(), _M_map_size(0), _M_start(), _M_finish() { } #endif void _M_swap_data(_Deque_impl& __x) _GLIBCXX_NOEXCEPT { using std::swap; swap(this->_M_start, __x._M_start); swap(this->_M_finish, __x._M_finish); swap(this->_M_map, __x._M_map); swap(this->_M_map_size, __x._M_map_size); } }; _Tp_alloc_type& _M_get_Tp_allocator() _GLIBCXX_NOEXCEPT { return *static_cast<_Tp_alloc_type*>(&this->_M_impl); } const _Tp_alloc_type& _M_get_Tp_allocator() const _GLIBCXX_NOEXCEPT { return *static_cast(&this->_M_impl); } _Map_alloc_type _M_get_map_allocator() const _GLIBCXX_NOEXCEPT { return _Map_alloc_type(_M_get_Tp_allocator()); } _Ptr _M_allocate_node() { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Traits; return _Traits::allocate(_M_impl, __deque_buf_size(sizeof(_Tp))); } void _M_deallocate_node(_Ptr __p) _GLIBCXX_NOEXCEPT { typedef __gnu_cxx::__alloc_traits<_Tp_alloc_type> _Traits; _Traits::deallocate(_M_impl, __p, __deque_buf_size(sizeof(_Tp))); } _Map_pointer _M_allocate_map(size_t __n) { _Map_alloc_type __map_alloc = _M_get_map_allocator(); return _Map_alloc_traits::allocate(__map_alloc, __n); } void _M_deallocate_map(_Map_pointer __p, size_t __n) _GLIBCXX_NOEXCEPT { _Map_alloc_type __map_alloc = _M_get_map_allocator(); _Map_alloc_traits::deallocate(__map_alloc, __p, __n); } protected: void _M_initialize_map(size_t); void _M_create_nodes(_Map_pointer __nstart, _Map_pointer __nfinish); void _M_destroy_nodes(_Map_pointer __nstart, _Map_pointer __nfinish) _GLIBCXX_NOEXCEPT; enum { _S_initial_map_size = 8 }; _Deque_impl _M_impl; #if __cplusplus >= 201103L private: _Deque_impl _M_move_impl() { if (!_M_impl._M_map) return std::move(_M_impl); // Create a copy of the current allocator. _Tp_alloc_type __alloc{_M_get_Tp_allocator()}; // Put that copy in a moved-from state. _Tp_alloc_type __sink __attribute((__unused__)) {std::move(__alloc)}; // Create an empty map that allocates using the moved-from allocator. _Deque_base __empty{__alloc}; __empty._M_initialize_map(0); // Now safe to modify current allocator and perform non-throwing swaps. _Deque_impl __ret{std::move(_M_get_Tp_allocator())}; _M_impl._M_swap_data(__ret); _M_impl._M_swap_data(__empty._M_impl); return __ret; } #endif }; template _Deque_base<_Tp, _Alloc>:: ~_Deque_base() _GLIBCXX_NOEXCEPT { if (this->_M_impl._M_map) { _M_destroy_nodes(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1); _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); } } /** * @brief Layout storage. * @param __num_elements The count of T's for which to allocate space * at first. * @return Nothing. * * The initial underlying memory layout is a bit complicated... */ template void _Deque_base<_Tp, _Alloc>:: _M_initialize_map(size_t __num_elements) { const size_t __num_nodes = (__num_elements/ __deque_buf_size(sizeof(_Tp)) + 1); this->_M_impl._M_map_size = std::max((size_t) _S_initial_map_size, size_t(__num_nodes + 2)); this->_M_impl._M_map = _M_allocate_map(this->_M_impl._M_map_size); // For "small" maps (needing less than _M_map_size nodes), allocation // starts in the middle elements and grows outwards. So nstart may be // the beginning of _M_map, but for small maps it may be as far in as // _M_map+3. _Map_pointer __nstart = (this->_M_impl._M_map + (this->_M_impl._M_map_size - __num_nodes) / 2); _Map_pointer __nfinish = __nstart + __num_nodes; __try { _M_create_nodes(__nstart, __nfinish); } __catch(...) { _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); this->_M_impl._M_map = _Map_pointer(); this->_M_impl._M_map_size = 0; __throw_exception_again; } this->_M_impl._M_start._M_set_node(__nstart); this->_M_impl._M_finish._M_set_node(__nfinish - 1); this->_M_impl._M_start._M_cur = _M_impl._M_start._M_first; this->_M_impl._M_finish._M_cur = (this->_M_impl._M_finish._M_first + __num_elements % __deque_buf_size(sizeof(_Tp))); } template void _Deque_base<_Tp, _Alloc>:: _M_create_nodes(_Map_pointer __nstart, _Map_pointer __nfinish) { _Map_pointer __cur; __try { for (__cur = __nstart; __cur < __nfinish; ++__cur) *__cur = this->_M_allocate_node(); } __catch(...) { _M_destroy_nodes(__nstart, __cur); __throw_exception_again; } } template void _Deque_base<_Tp, _Alloc>:: _M_destroy_nodes(_Map_pointer __nstart, _Map_pointer __nfinish) _GLIBCXX_NOEXCEPT { for (_Map_pointer __n = __nstart; __n < __nfinish; ++__n) _M_deallocate_node(*__n); } /** * @brief A standard container using fixed-size memory allocation and * constant-time manipulation of elements at either end. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Alloc Allocator type, defaults to allocator<_Tp>. * * Meets the requirements of a container, a * reversible container, and a * sequence, including the * optional sequence requirements. * * In previous HP/SGI versions of deque, there was an extra template * parameter so users could control the node size. This extension turned * out to violate the C++ standard (it can be detected using template * template parameters), and it was removed. * * Here's how a deque manages memory. Each deque has 4 members: * * - Tp** _M_map * - size_t _M_map_size * - iterator _M_start, _M_finish * * map_size is at least 8. %map is an array of map_size * pointers-to-@a nodes. (The name %map has nothing to do with the * std::map class, and @b nodes should not be confused with * std::list's usage of @a node.) * * A @a node has no specific type name as such, but it is referred * to as @a node in this file. It is a simple array-of-Tp. If Tp * is very large, there will be one Tp element per node (i.e., an * @a array of one). For non-huge Tp's, node size is inversely * related to Tp size: the larger the Tp, the fewer Tp's will fit * in a node. The goal here is to keep the total size of a node * relatively small and constant over different Tp's, to improve * allocator efficiency. * * Not every pointer in the %map array will point to a node. If * the initial number of elements in the deque is small, the * /middle/ %map pointers will be valid, and the ones at the edges * will be unused. This same situation will arise as the %map * grows: available %map pointers, if any, will be on the ends. As * new nodes are created, only a subset of the %map's pointers need * to be copied @a outward. * * Class invariants: * - For any nonsingular iterator i: * - i.node points to a member of the %map array. (Yes, you read that * correctly: i.node does not actually point to a node.) The member of * the %map array is what actually points to the node. * - i.first == *(i.node) (This points to the node (first Tp element).) * - i.last == i.first + node_size * - i.cur is a pointer in the range [i.first, i.last). NOTE: * the implication of this is that i.cur is always a dereferenceable * pointer, even if i is a past-the-end iterator. * - Start and Finish are always nonsingular iterators. NOTE: this * means that an empty deque must have one node, a deque with > class deque : protected _Deque_base<_Tp, _Alloc> { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires2(_Tp, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Tp>::value, "std::deque must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::deque must have the same value_type as its allocator"); # endif #endif typedef _Deque_base<_Tp, _Alloc> _Base; typedef typename _Base::_Tp_alloc_type _Tp_alloc_type; typedef typename _Base::_Alloc_traits _Alloc_traits; typedef typename _Base::_Map_pointer _Map_pointer; public: typedef _Tp value_type; typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; typedef typename _Base::iterator iterator; typedef typename _Base::const_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Alloc allocator_type; protected: static size_t _S_buffer_size() _GLIBCXX_NOEXCEPT { return __deque_buf_size(sizeof(_Tp)); } // Functions controlling memory layout, and nothing else. using _Base::_M_initialize_map; using _Base::_M_create_nodes; using _Base::_M_destroy_nodes; using _Base::_M_allocate_node; using _Base::_M_deallocate_node; using _Base::_M_allocate_map; using _Base::_M_deallocate_map; using _Base::_M_get_Tp_allocator; /** * A total of four data members accumulated down the hierarchy. * May be accessed via _M_impl.* */ using _Base::_M_impl; public: // [23.2.1.1] construct/copy/destroy // (assign() and get_allocator() are also listed in this section) /** * @brief Creates a %deque with no elements. */ deque() : _Base() { } /** * @brief Creates a %deque with no elements. * @param __a An allocator object. */ explicit deque(const allocator_type& __a) : _Base(__a, 0) { } #if __cplusplus >= 201103L /** * @brief Creates a %deque with default constructed elements. * @param __n The number of elements to initially create. * @param __a An allocator. * * This constructor fills the %deque with @a n default * constructed elements. */ explicit deque(size_type __n, const allocator_type& __a = allocator_type()) : _Base(__a, __n) { _M_default_initialize(); } /** * @brief Creates a %deque with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %deque with @a __n copies of @a __value. */ deque(size_type __n, const value_type& __value, const allocator_type& __a = allocator_type()) : _Base(__a, __n) { _M_fill_initialize(__value); } #else /** * @brief Creates a %deque with copies of an exemplar element. * @param __n The number of elements to initially create. * @param __value An element to copy. * @param __a An allocator. * * This constructor fills the %deque with @a __n copies of @a __value. */ explicit deque(size_type __n, const value_type& __value = value_type(), const allocator_type& __a = allocator_type()) : _Base(__a, __n) { _M_fill_initialize(__value); } #endif /** * @brief %Deque copy constructor. * @param __x A %deque of identical element and allocator types. * * The newly-created %deque uses a copy of the allocator object used * by @a __x (unless the allocator traits dictate a different object). */ deque(const deque& __x) : _Base(_Alloc_traits::_S_select_on_copy(__x._M_get_Tp_allocator()), __x.size()) { std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief %Deque move constructor. * @param __x A %deque of identical element and allocator types. * * The newly-created %deque contains the exact contents of @a __x. * The contents of @a __x are a valid, but unspecified %deque. */ deque(deque&& __x) : _Base(std::move(__x)) { } /// Copy constructor with alternative allocator deque(const deque& __x, const allocator_type& __a) : _Base(__a, __x.size()) { std::__uninitialized_copy_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); } /// Move constructor with alternative allocator deque(deque&& __x, const allocator_type& __a) : _Base(std::move(__x), __a, __x.size()) { if (__x.get_allocator() != __a) { std::__uninitialized_move_a(__x.begin(), __x.end(), this->_M_impl._M_start, _M_get_Tp_allocator()); __x.clear(); } } /** * @brief Builds a %deque from an initializer list. * @param __l An initializer_list. * @param __a An allocator object. * * Create a %deque consisting of copies of the elements in the * initializer_list @a __l. * * This will call the element type's copy constructor N times * (where N is __l.size()) and do no memory reallocation. */ deque(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_range_initialize(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /** * @brief Builds a %deque from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __a An allocator object. * * Create a %deque consisting of copies of the elements from [__first, * __last). * * If the iterators are forward, bidirectional, or random-access, then * this will call the elements' copy constructor N times (where N is * distance(__first,__last)) and do no memory reallocation. But if only * input iterators are used, then this will do at most 2N calls to the * copy constructor, and logN memory reallocations. */ #if __cplusplus >= 201103L template> deque(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template deque(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~deque() { _M_destroy_data(begin(), end(), _M_get_Tp_allocator()); } /** * @brief %Deque assignment operator. * @param __x A %deque of identical element and allocator types. * * All the elements of @a x are copied. * * The newly-created %deque uses a copy of the allocator object used * by @a __x (unless the allocator traits dictate a different object). */ deque& operator=(const deque& __x); #if __cplusplus >= 201103L /** * @brief %Deque move assignment operator. * @param __x A %deque of identical element and allocator types. * * The contents of @a __x are moved into this deque (without copying, * if the allocators permit it). * @a __x is a valid, but unspecified %deque. */ deque& operator=(deque&& __x) noexcept(_Alloc_traits::_S_always_equal()) { using __always_equal = typename _Alloc_traits::is_always_equal; _M_move_assign1(std::move(__x), __always_equal{}); return *this; } /** * @brief Assigns an initializer list to a %deque. * @param __l An initializer_list. * * This function fills a %deque with copies of the elements in the * initializer_list @a __l. * * Note that the assignment completely changes the %deque and that the * resulting %deque's size is the same as the number of elements * assigned. */ deque& operator=(initializer_list __l) { _M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); return *this; } #endif /** * @brief Assigns a given value to a %deque. * @param __n Number of elements to be assigned. * @param __val Value to be assigned. * * This function fills a %deque with @a n copies of the given * value. Note that the assignment completely changes the * %deque and that the resulting %deque's size is the same as * the number of elements assigned. */ void assign(size_type __n, const value_type& __val) { _M_fill_assign(__n, __val); } /** * @brief Assigns a range to a %deque. * @param __first An input iterator. * @param __last An input iterator. * * This function fills a %deque with copies of the elements in the * range [__first,__last). * * Note that the assignment completely changes the %deque and that the * resulting %deque's size is the same as the number of elements * assigned. */ #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_dispatch(__first, __last, __false_type()); } #else template void assign(_InputIterator __first, _InputIterator __last) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L /** * @brief Assigns an initializer list to a %deque. * @param __l An initializer_list. * * This function fills a %deque with copies of the elements in the * initializer_list @a __l. * * Note that the assignment completely changes the %deque and that the * resulting %deque's size is the same as the number of elements * assigned. */ void assign(initializer_list __l) { _M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif /// Get a copy of the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return _Base::get_allocator(); } // iterators /** * Returns a read/write iterator that points to the first element in the * %deque. Iteration is done in ordinary element order. */ iterator begin() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } /** * Returns a read-only (constant) iterator that points to the first * element in the %deque. Iteration is done in ordinary element order. */ const_iterator begin() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } /** * Returns a read/write iterator that points one past the last * element in the %deque. Iteration is done in ordinary * element order. */ iterator end() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } /** * Returns a read-only (constant) iterator that points one past * the last element in the %deque. Iteration is done in * ordinary element order. */ const_iterator end() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } /** * Returns a read/write reverse iterator that points to the * last element in the %deque. Iteration is done in reverse * element order. */ reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %deque. Iteration is done in * reverse element order. */ const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->_M_impl._M_finish); } /** * Returns a read/write reverse iterator that points to one * before the first element in the %deque. Iteration is done * in reverse element order. */ reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(this->_M_impl._M_start); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %deque. Iteration is * done in reverse element order. */ const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(this->_M_impl._M_start); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * element in the %deque. Iteration is done in ordinary element order. */ const_iterator cbegin() const noexcept { return this->_M_impl._M_start; } /** * Returns a read-only (constant) iterator that points one past * the last element in the %deque. Iteration is done in * ordinary element order. */ const_iterator cend() const noexcept { return this->_M_impl._M_finish; } /** * Returns a read-only (constant) reverse iterator that points * to the last element in the %deque. Iteration is done in * reverse element order. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->_M_impl._M_finish); } /** * Returns a read-only (constant) reverse iterator that points * to one before the first element in the %deque. Iteration is * done in reverse element order. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->_M_impl._M_start); } #endif // [23.2.1.2] capacity /** Returns the number of elements in the %deque. */ size_type size() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish - this->_M_impl._M_start; } /** Returns the size() of the largest possible %deque. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Tp_allocator()); } #if __cplusplus >= 201103L /** * @brief Resizes the %deque to the specified number of elements. * @param __new_size Number of elements the %deque should contain. * * This function will %resize the %deque to the specified * number of elements. If the number is smaller than the * %deque's current size the %deque is truncated, otherwise * default constructed elements are appended. */ void resize(size_type __new_size) { const size_type __len = size(); if (__new_size > __len) _M_default_append(__new_size - __len); else if (__new_size < __len) _M_erase_at_end(this->_M_impl._M_start + difference_type(__new_size)); } /** * @brief Resizes the %deque to the specified number of elements. * @param __new_size Number of elements the %deque should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %deque to the specified * number of elements. If the number is smaller than the * %deque's current size the %deque is truncated, otherwise the * %deque is extended and new elements are populated with given * data. */ void resize(size_type __new_size, const value_type& __x) { const size_type __len = size(); if (__new_size > __len) _M_fill_insert(this->_M_impl._M_finish, __new_size - __len, __x); else if (__new_size < __len) _M_erase_at_end(this->_M_impl._M_start + difference_type(__new_size)); } #else /** * @brief Resizes the %deque to the specified number of elements. * @param __new_size Number of elements the %deque should contain. * @param __x Data with which new elements should be populated. * * This function will %resize the %deque to the specified * number of elements. If the number is smaller than the * %deque's current size the %deque is truncated, otherwise the * %deque is extended and new elements are populated with given * data. */ void resize(size_type __new_size, value_type __x = value_type()) { const size_type __len = size(); if (__new_size > __len) _M_fill_insert(this->_M_impl._M_finish, __new_size - __len, __x); else if (__new_size < __len) _M_erase_at_end(this->_M_impl._M_start + difference_type(__new_size)); } #endif #if __cplusplus >= 201103L /** A non-binding request to reduce memory use. */ void shrink_to_fit() noexcept { _M_shrink_to_fit(); } #endif /** * Returns true if the %deque is empty. (Thus begin() would * equal end().) */ bool empty() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish == this->_M_impl._M_start; } // element access /** * @brief Subscript access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return this->_M_impl._M_start[difference_type(__n)]; } /** * @brief Subscript access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * * This operator allows for easy, array-style, data access. * Note that data access with this operator is unchecked and * out_of_range lookups are not defined. (For checked lookups * see at().) */ const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_requires_subscript(__n); return this->_M_impl._M_start[difference_type(__n)]; } protected: /// Safety check used only from at(). void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("deque::_M_range_check: __n " "(which is %zu)>= this->size() " "(which is %zu)"), __n, this->size()); } public: /** * @brief Provides access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read/write reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter * is first checked that it is in the range of the deque. The * function throws out_of_range if the check fails. */ reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } /** * @brief Provides access to the data contained in the %deque. * @param __n The index of the element for which data should be * accessed. * @return Read-only (constant) reference to data. * @throw std::out_of_range If @a __n is an invalid index. * * This function provides for safer data access. The parameter is first * checked that it is in the range of the deque. The function throws * out_of_range if the check fails. */ const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } /** * Returns a read/write reference to the data at the first * element of the %deque. */ reference front() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %deque. */ const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); return *begin(); } /** * Returns a read/write reference to the data at the last element of the * %deque. */ reference back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); iterator __tmp = end(); --__tmp; return *__tmp; } /** * Returns a read-only (constant) reference to the data at the last * element of the %deque. */ const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); const_iterator __tmp = end(); --__tmp; return *__tmp; } // [23.2.1.2] modifiers /** * @brief Add data to the front of the %deque. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the front of the %deque and assigns the given * data to it. Due to the nature of a %deque this operation * can be done in constant time. */ void push_front(const value_type& __x) { if (this->_M_impl._M_start._M_cur != this->_M_impl._M_start._M_first) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_start._M_cur - 1, __x); --this->_M_impl._M_start._M_cur; } else _M_push_front_aux(__x); } #if __cplusplus >= 201103L void push_front(value_type&& __x) { emplace_front(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args); #endif /** * @brief Add data to the end of the %deque. * @param __x Data to be added. * * This is a typical stack operation. The function creates an * element at the end of the %deque and assigns the given data * to it. Due to the nature of a %deque this operation can be * done in constant time. */ void push_back(const value_type& __x) { if (this->_M_impl._M_finish._M_cur != this->_M_impl._M_finish._M_last - 1) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish._M_cur, __x); ++this->_M_impl._M_finish._M_cur; } else _M_push_back_aux(__x); } #if __cplusplus >= 201103L void push_back(value_type&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args); #endif /** * @brief Removes first element. * * This is a typical stack operation. It shrinks the %deque by one. * * Note that no data is returned, and if the first element's data is * needed, it should be retrieved before pop_front() is called. */ void pop_front() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); if (this->_M_impl._M_start._M_cur != this->_M_impl._M_start._M_last - 1) { _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_start._M_cur); ++this->_M_impl._M_start._M_cur; } else _M_pop_front_aux(); } /** * @brief Removes last element. * * This is a typical stack operation. It shrinks the %deque by one. * * Note that no data is returned, and if the last element's data is * needed, it should be retrieved before pop_back() is called. */ void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_requires_nonempty(); if (this->_M_impl._M_finish._M_cur != this->_M_impl._M_finish._M_first) { --this->_M_impl._M_finish._M_cur; _Alloc_traits::destroy(this->_M_impl, this->_M_impl._M_finish._M_cur); } else _M_pop_back_aux(); } #if __cplusplus >= 201103L /** * @brief Inserts an object in %deque before specified iterator. * @param __position A const_iterator into the %deque. * @param __args Arguments. * @return An iterator that points to the inserted data. * * This function will insert an object of type T constructed * with T(std::forward(args)...) before the specified location. */ template iterator emplace(const_iterator __position, _Args&&... __args); /** * @brief Inserts given value into %deque before specified iterator. * @param __position A const_iterator into the %deque. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before the * specified location. */ iterator insert(const_iterator __position, const value_type& __x); #else /** * @brief Inserts given value into %deque before specified iterator. * @param __position An iterator into the %deque. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given value before the * specified location. */ iterator insert(iterator __position, const value_type& __x); #endif #if __cplusplus >= 201103L /** * @brief Inserts given rvalue into %deque before specified iterator. * @param __position A const_iterator into the %deque. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a copy of the given rvalue before the * specified location. */ iterator insert(const_iterator __position, value_type&& __x) { return emplace(__position, std::move(__x)); } /** * @brief Inserts an initializer list into the %deque. * @param __p An iterator into the %deque. * @param __l An initializer_list. * * This function will insert copies of the data in the * initializer_list @a __l into the %deque before the location * specified by @a __p. This is known as list insert. */ iterator insert(const_iterator __p, initializer_list __l) { auto __offset = __p - cbegin(); _M_range_insert_aux(__p._M_const_cast(), __l.begin(), __l.end(), std::random_access_iterator_tag()); return begin() + __offset; } #endif #if __cplusplus >= 201103L /** * @brief Inserts a number of copies of given data into the %deque. * @param __position A const_iterator into the %deque. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * @return An iterator that points to the inserted data. * * This function will insert a specified number of copies of the given * data before the location specified by @a __position. */ iterator insert(const_iterator __position, size_type __n, const value_type& __x) { difference_type __offset = __position - cbegin(); _M_fill_insert(__position._M_const_cast(), __n, __x); return begin() + __offset; } #else /** * @brief Inserts a number of copies of given data into the %deque. * @param __position An iterator into the %deque. * @param __n Number of elements to be inserted. * @param __x Data to be inserted. * * This function will insert a specified number of copies of the given * data before the location specified by @a __position. */ void insert(iterator __position, size_type __n, const value_type& __x) { _M_fill_insert(__position, __n, __x); } #endif #if __cplusplus >= 201103L /** * @brief Inserts a range into the %deque. * @param __position A const_iterator into the %deque. * @param __first An input iterator. * @param __last An input iterator. * @return An iterator that points to the inserted data. * * This function will insert copies of the data in the range * [__first,__last) into the %deque before the location specified * by @a __position. This is known as range insert. */ template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { difference_type __offset = __position - cbegin(); _M_insert_dispatch(__position._M_const_cast(), __first, __last, __false_type()); return begin() + __offset; } #else /** * @brief Inserts a range into the %deque. * @param __position An iterator into the %deque. * @param __first An input iterator. * @param __last An input iterator. * * This function will insert copies of the data in the range * [__first,__last) into the %deque before the location specified * by @a __position. This is known as range insert. */ template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { // Check whether it's an integral type. If so, it's not an iterator. typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } #endif /** * @brief Remove element at given position. * @param __position Iterator pointing to element to be erased. * @return An iterator pointing to the next element (or end()). * * This function will erase the element at the given position and thus * shorten the %deque by one. * * The user is cautioned that * this function only erases the element, and that if the element is * itself a pointer, the pointed-to memory is not touched in any way. * Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { return _M_erase(__position._M_const_cast()); } /** * @brief Remove a range of elements. * @param __first Iterator pointing to the first element to be erased. * @param __last Iterator pointing to one past the last element to be * erased. * @return An iterator pointing to the element pointed to by @a last * prior to erasing (or end()). * * This function will erase the elements in the range * [__first,__last) and shorten the %deque accordingly. * * The user is cautioned that * this function only erases the elements, and that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { return _M_erase(__first._M_const_cast(), __last._M_const_cast()); } /** * @brief Swaps data with another %deque. * @param __x A %deque of the same element and allocator types. * * This exchanges the elements between two deques in constant time. * (Four pointers, so it should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(d1,d2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(deque& __x) _GLIBCXX_NOEXCEPT { #if __cplusplus >= 201103L __glibcxx_assert(_Alloc_traits::propagate_on_container_swap::value || _M_get_Tp_allocator() == __x._M_get_Tp_allocator()); #endif _M_impl._M_swap_data(__x._M_impl); _Alloc_traits::_S_on_swap(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } /** * Erases all the elements. Note that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_erase_at_end(begin()); } protected: // Internal constructor functions follow. // called by the range constructor to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) { _M_initialize_map(static_cast(__n)); _M_fill_initialize(__x); } // called by the range constructor to implement [23.1.1]/9 template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_range_initialize(__first, __last, std::__iterator_category(__first)); } // called by the second initialize_dispatch above //@{ /** * @brief Fills the deque with whatever is in [first,last). * @param __first An input iterator. * @param __last An input iterator. * @return Nothing. * * If the iterators are actually forward iterators (or better), then the * memory layout can be done all at once. Else we move forward using * push_back on each value from the iterator. */ template void _M_range_initialize(_InputIterator __first, _InputIterator __last, std::input_iterator_tag); // called by the second initialize_dispatch above template void _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); //@} /** * @brief Fills the %deque with copies of value. * @param __value Initial value. * @return Nothing. * @pre _M_start and _M_finish have already been initialized, * but none of the %deque's elements have yet been constructed. * * This function is called only when the user provides an explicit size * (with or without an explicit exemplar value). */ void _M_fill_initialize(const value_type& __value); #if __cplusplus >= 201103L // called by deque(n). void _M_default_initialize(); #endif // Internal assign functions follow. The *_aux functions do the actual // assignment work for the range versions. // called by the range assign to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } // called by the range assign to implement [23.1.1]/9 template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } // called by the second assign_dispatch above template void _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag); // called by the second assign_dispatch above template void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __len = std::distance(__first, __last); if (__len > size()) { _ForwardIterator __mid = __first; std::advance(__mid, size()); std::copy(__first, __mid, begin()); _M_range_insert_aux(end(), __mid, __last, std::__iterator_category(__first)); } else _M_erase_at_end(std::copy(__first, __last, begin())); } // Called by assign(n,t), and the range assign when it turns out // to be the same thing. void _M_fill_assign(size_type __n, const value_type& __val) { if (__n > size()) { std::fill(begin(), end(), __val); _M_fill_insert(end(), __n - size(), __val); } else { _M_erase_at_end(begin() + difference_type(__n)); std::fill(begin(), end(), __val); } } //@{ /// Helper functions for push_* and pop_*. #if __cplusplus < 201103L void _M_push_back_aux(const value_type&); void _M_push_front_aux(const value_type&); #else template void _M_push_back_aux(_Args&&... __args); template void _M_push_front_aux(_Args&&... __args); #endif void _M_pop_back_aux(); void _M_pop_front_aux(); //@} // Internal insert functions follow. The *_aux functions do the actual // insertion work when all shortcuts fail. // called by the range insert to implement [23.1.1]/9 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __x, __true_type) { _M_fill_insert(__pos, __n, __x); } // called by the range insert to implement [23.1.1]/9 template void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_range_insert_aux(__pos, __first, __last, std::__iterator_category(__first)); } // called by the second insert_dispatch above template void _M_range_insert_aux(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag); // called by the second insert_dispatch above template void _M_range_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); // Called by insert(p,n,x), and the range insert when it turns out to be // the same thing. Can use fill functions in optimal situations, // otherwise passes off to insert_aux(p,n,x). void _M_fill_insert(iterator __pos, size_type __n, const value_type& __x); // called by insert(p,x) #if __cplusplus < 201103L iterator _M_insert_aux(iterator __pos, const value_type& __x); #else template iterator _M_insert_aux(iterator __pos, _Args&&... __args); #endif // called by insert(p,n,x) via fill_insert void _M_insert_aux(iterator __pos, size_type __n, const value_type& __x); // called by range_insert_aux for forward iterators template void _M_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, size_type __n); // Internal erase functions follow. void _M_destroy_data_aux(iterator __first, iterator __last); // Called by ~deque(). // NB: Doesn't deallocate the nodes. template void _M_destroy_data(iterator __first, iterator __last, const _Alloc1&) { _M_destroy_data_aux(__first, __last); } void _M_destroy_data(iterator __first, iterator __last, const std::allocator<_Tp>&) { if (!__has_trivial_destructor(value_type)) _M_destroy_data_aux(__first, __last); } // Called by erase(q1, q2). void _M_erase_at_begin(iterator __pos) { _M_destroy_data(begin(), __pos, _M_get_Tp_allocator()); _M_destroy_nodes(this->_M_impl._M_start._M_node, __pos._M_node); this->_M_impl._M_start = __pos; } // Called by erase(q1, q2), resize(), clear(), _M_assign_aux, // _M_fill_assign, operator=. void _M_erase_at_end(iterator __pos) { _M_destroy_data(__pos, end(), _M_get_Tp_allocator()); _M_destroy_nodes(__pos._M_node + 1, this->_M_impl._M_finish._M_node + 1); this->_M_impl._M_finish = __pos; } iterator _M_erase(iterator __pos); iterator _M_erase(iterator __first, iterator __last); #if __cplusplus >= 201103L // Called by resize(sz). void _M_default_append(size_type __n); bool _M_shrink_to_fit(); #endif //@{ /// Memory-handling helpers for the previous internal insert functions. iterator _M_reserve_elements_at_front(size_type __n) { const size_type __vacancies = this->_M_impl._M_start._M_cur - this->_M_impl._M_start._M_first; if (__n > __vacancies) _M_new_elements_at_front(__n - __vacancies); return this->_M_impl._M_start - difference_type(__n); } iterator _M_reserve_elements_at_back(size_type __n) { const size_type __vacancies = (this->_M_impl._M_finish._M_last - this->_M_impl._M_finish._M_cur) - 1; if (__n > __vacancies) _M_new_elements_at_back(__n - __vacancies); return this->_M_impl._M_finish + difference_type(__n); } void _M_new_elements_at_front(size_type __new_elements); void _M_new_elements_at_back(size_type __new_elements); //@} //@{ /** * @brief Memory-handling helpers for the major %map. * * Makes sure the _M_map has space for new nodes. Does not * actually add the nodes. Can invalidate _M_map pointers. * (And consequently, %deque iterators.) */ void _M_reserve_map_at_back(size_type __nodes_to_add = 1) { if (__nodes_to_add + 1 > this->_M_impl._M_map_size - (this->_M_impl._M_finish._M_node - this->_M_impl._M_map)) _M_reallocate_map(__nodes_to_add, false); } void _M_reserve_map_at_front(size_type __nodes_to_add = 1) { if (__nodes_to_add > size_type(this->_M_impl._M_start._M_node - this->_M_impl._M_map)) _M_reallocate_map(__nodes_to_add, true); } void _M_reallocate_map(size_type __nodes_to_add, bool __add_at_front); //@} #if __cplusplus >= 201103L // Constant-time, nothrow move assignment when source object's memory // can be moved because the allocators are equal. void _M_move_assign1(deque&& __x, /* always equal: */ true_type) noexcept { this->_M_impl._M_swap_data(__x._M_impl); __x.clear(); std::__alloc_on_move(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } // When the allocators are not equal the operation could throw, because // we might need to allocate a new map for __x after moving from it // or we might need to allocate new elements for *this. void _M_move_assign1(deque&& __x, /* always equal: */ false_type) { constexpr bool __move_storage = _Alloc_traits::_S_propagate_on_move_assign(); _M_move_assign2(std::move(__x), __bool_constant<__move_storage>()); } // Destroy all elements and deallocate all memory, then replace // with elements created from __args. template void _M_replace_map(_Args&&... __args) { // Create new data first, so if allocation fails there are no effects. deque __newobj(std::forward<_Args>(__args)...); // Free existing storage using existing allocator. clear(); _M_deallocate_node(*begin()._M_node); // one node left after clear() _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); this->_M_impl._M_map = nullptr; this->_M_impl._M_map_size = 0; // Take ownership of replacement memory. this->_M_impl._M_swap_data(__newobj._M_impl); } // Do move assignment when the allocator propagates. void _M_move_assign2(deque&& __x, /* propagate: */ true_type) { // Make a copy of the original allocator state. auto __alloc = __x._M_get_Tp_allocator(); // The allocator propagates so storage can be moved from __x, // leaving __x in a valid empty state with a moved-from allocator. _M_replace_map(std::move(__x)); // Move the corresponding allocator state too. _M_get_Tp_allocator() = std::move(__alloc); } // Do move assignment when it may not be possible to move source // object's memory, resulting in a linear-time operation. void _M_move_assign2(deque&& __x, /* propagate: */ false_type) { if (__x._M_get_Tp_allocator() == this->_M_get_Tp_allocator()) { // The allocators are equal so storage can be moved from __x, // leaving __x in a valid empty state with its current allocator. _M_replace_map(std::move(__x), __x.get_allocator()); } else { // The rvalue's allocator cannot be moved and is not equal, // so we need to individually move each element. _M_assign_aux(std::__make_move_if_noexcept_iterator(__x.begin()), std::__make_move_if_noexcept_iterator(__x.end()), std::random_access_iterator_tag()); __x.clear(); } } #endif }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> deque(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> deque<_ValT, _Allocator>; #endif /** * @brief Deque equality comparison. * @param __x A %deque. * @param __y A %deque of the same type as @a __x. * @return True iff the size and elements of the deques are equal. * * This is an equivalence relation. It is linear in the size of the * deques. Deques are considered equivalent if their sizes are equal, * and if corresponding elements compare equal. */ template inline bool operator==(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return __x.size() == __y.size() && std::equal(__x.begin(), __x.end(), __y.begin()); } /** * @brief Deque ordering relation. * @param __x A %deque. * @param __y A %deque of the same type as @a __x. * @return True iff @a x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * deques. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return std::lexicographical_compare(__x.begin(), __x.end(), __y.begin(), __y.end()); } /// Based on operator== template inline bool operator!=(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const deque<_Tp, _Alloc>& __x, const deque<_Tp, _Alloc>& __y) { return !(__x < __y); } /// See std::deque::swap(). template inline void swap(deque<_Tp,_Alloc>& __x, deque<_Tp,_Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } #undef _GLIBCXX_DEQUE_BUF_SIZE _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_DEQUE_H */ c++/8/bits/regex_error.h000064400000011450151027430570010725 0ustar00// class template regex -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/regex_error.h * @brief Error and exception objects for the std regex library. * * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{regex} */ namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup regex * @{ */ namespace regex_constants { /** * @name 5.3 Error Types */ //@{ enum error_type { _S_error_collate, _S_error_ctype, _S_error_escape, _S_error_backref, _S_error_brack, _S_error_paren, _S_error_brace, _S_error_badbrace, _S_error_range, _S_error_space, _S_error_badrepeat, _S_error_complexity, _S_error_stack, }; /** The expression contained an invalid collating element name. */ constexpr error_type error_collate(_S_error_collate); /** The expression contained an invalid character class name. */ constexpr error_type error_ctype(_S_error_ctype); /** * The expression contained an invalid escaped character, or a trailing * escape. */ constexpr error_type error_escape(_S_error_escape); /** The expression contained an invalid back reference. */ constexpr error_type error_backref(_S_error_backref); /** The expression contained mismatched [ and ]. */ constexpr error_type error_brack(_S_error_brack); /** The expression contained mismatched ( and ). */ constexpr error_type error_paren(_S_error_paren); /** The expression contained mismatched { and } */ constexpr error_type error_brace(_S_error_brace); /** The expression contained an invalid range in a {} expression. */ constexpr error_type error_badbrace(_S_error_badbrace); /** * The expression contained an invalid character range, * such as [b-a] in most encodings. */ constexpr error_type error_range(_S_error_range); /** * There was insufficient memory to convert the expression into a * finite state machine. */ constexpr error_type error_space(_S_error_space); /** * One of *?+{ was not preceded by a valid regular expression. */ constexpr error_type error_badrepeat(_S_error_badrepeat); /** * The complexity of an attempted match against a regular expression * exceeded a pre-set level. */ constexpr error_type error_complexity(_S_error_complexity); /** * There was insufficient memory to determine whether the * regular expression could match the specified character sequence. */ constexpr error_type error_stack(_S_error_stack); //@} } // namespace regex_constants // [7.8] Class regex_error /** * @brief A regular expression exception class. * @ingroup exceptions * * The regular expression library throws objects of this class on error. */ class regex_error : public std::runtime_error { regex_constants::error_type _M_code; public: /** * @brief Constructs a regex_error object. * * @param __ecode the regex error code. */ explicit regex_error(regex_constants::error_type __ecode); virtual ~regex_error() throw(); /** * @brief Gets the regex error code. * * @returns the regex error code. */ regex_constants::error_type code() const { return _M_code; } private: regex_error(regex_constants::error_type __ecode, const char* __what) : std::runtime_error(__what), _M_code(__ecode) { } friend void __throw_regex_error(regex_constants::error_type, const char*); }; //@} // group regex void __throw_regex_error(regex_constants::error_type __ecode); inline void __throw_regex_error(regex_constants::error_type __ecode, const char* __what) { _GLIBCXX_THROW_OR_ABORT(regex_error(__ecode, __what)); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std c++/8/bits/stl_pair.h000064400000044322151027430570010223 0ustar00// Pair implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_pair.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{utility} */ #ifndef _STL_PAIR_H #define _STL_PAIR_H 1 #include // for std::move / std::forward, and std::swap #if __cplusplus >= 201103L #include // for std::__decay_and_strip too #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ #if __cplusplus >= 201103L /// piecewise_construct_t struct piecewise_construct_t { explicit piecewise_construct_t() = default; }; /// piecewise_construct _GLIBCXX17_INLINE constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t(); // Forward declarations. template class tuple; template struct _Index_tuple; // Concept utility functions, reused in conditionally-explicit // constructors. // See PR 70437, don't look at is_constructible or // is_convertible if the types are the same to // avoid querying those properties for incomplete types. template struct _PCC { template static constexpr bool _ConstructiblePair() { return __and_, is_constructible<_T2, const _U2&>>::value; } template static constexpr bool _ImplicitlyConvertiblePair() { return __and_, is_convertible>::value; } template static constexpr bool _MoveConstructiblePair() { return __and_, is_constructible<_T2, _U2&&>>::value; } template static constexpr bool _ImplicitlyMoveConvertiblePair() { return __and_, is_convertible<_U2&&, _T2>>::value; } template static constexpr bool _CopyMovePair() { using __do_converts = __and_, is_convertible<_U2&&, _T2>>; using __converts = typename conditional<__implicit, __do_converts, __not_<__do_converts>>::type; return __and_, is_constructible<_T2, _U2&&>, __converts >::value; } template static constexpr bool _MoveCopyPair() { using __do_converts = __and_, is_convertible>; using __converts = typename conditional<__implicit, __do_converts, __not_<__do_converts>>::type; return __and_, is_constructible<_T2, const _U2&&>, __converts >::value; } }; template struct _PCC { template static constexpr bool _ConstructiblePair() { return false; } template static constexpr bool _ImplicitlyConvertiblePair() { return false; } template static constexpr bool _MoveConstructiblePair() { return false; } template static constexpr bool _ImplicitlyMoveConvertiblePair() { return false; } }; // PR libstdc++/79141, a utility type for preventing // initialization of an argument of a disabled assignment // operator from a pair of empty braces. struct __nonesuch_no_braces : std::__nonesuch { explicit __nonesuch_no_braces(const __nonesuch&) = delete; }; #endif // C++11 template class __pair_base { #if __cplusplus >= 201103L template friend struct pair; __pair_base() = default; ~__pair_base() = default; __pair_base(const __pair_base&) = default; __pair_base& operator=(const __pair_base&) = delete; #endif // C++11 }; /** * @brief Struct holding two objects of arbitrary type. * * @tparam _T1 Type of first object. * @tparam _T2 Type of second object. */ template struct pair : private __pair_base<_T1, _T2> { typedef _T1 first_type; /// @c first_type is the first bound type typedef _T2 second_type; /// @c second_type is the second bound type _T1 first; /// @c first is a copy of the first object _T2 second; /// @c second is a copy of the second object // _GLIBCXX_RESOLVE_LIB_DEFECTS // 265. std::pair::pair() effects overly restrictive /** The default constructor creates @c first and @c second using their * respective default constructors. */ #if __cplusplus >= 201103L template , __is_implicitly_default_constructible<_U2>> ::value, bool>::type = true> #endif _GLIBCXX_CONSTEXPR pair() : first(), second() { } #if __cplusplus >= 201103L template , is_default_constructible<_U2>, __not_< __and_<__is_implicitly_default_constructible<_U1>, __is_implicitly_default_constructible<_U2>>>> ::value, bool>::type = false> explicit constexpr pair() : first(), second() { } #endif /** Two objects may be passed to a @c pair constructor to be copied. */ #if __cplusplus < 201103L pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) { } #else // Shortcut for constraining the templates that don't take pairs. using _PCCP = _PCC; template() && _PCCP::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) { } template() && !_PCCP::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(const _T1& __a, const _T2& __b) : first(__a), second(__b) { } #endif /** There is also a templated copy ctor for the @c pair class itself. */ #if __cplusplus < 201103L template pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) { } #else // Shortcut for constraining the templates that take pairs. template using _PCCFP = _PCC::value || !is_same<_T2, _U2>::value, _T1, _T2>; template::template _ConstructiblePair<_U1, _U2>() && _PCCFP<_U1, _U2>::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) { } template::template _ConstructiblePair<_U1, _U2>() && !_PCCFP<_U1, _U2>::template _ImplicitlyConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) { } constexpr pair(const pair&) = default; constexpr pair(pair&&) = default; // DR 811. template(), bool>::type=true> constexpr pair(_U1&& __x, const _T2& __y) : first(std::forward<_U1>(__x)), second(__y) { } template(), bool>::type=false> explicit constexpr pair(_U1&& __x, const _T2& __y) : first(std::forward<_U1>(__x)), second(__y) { } template(), bool>::type=true> constexpr pair(const _T1& __x, _U2&& __y) : first(__x), second(std::forward<_U2>(__y)) { } template(), bool>::type=false> explicit pair(const _T1& __x, _U2&& __y) : first(__x), second(std::forward<_U2>(__y)) { } template() && _PCCP::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(_U1&& __x, _U2&& __y) : first(std::forward<_U1>(__x)), second(std::forward<_U2>(__y)) { } template() && !_PCCP::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(_U1&& __x, _U2&& __y) : first(std::forward<_U1>(__x)), second(std::forward<_U2>(__y)) { } template::template _MoveConstructiblePair<_U1, _U2>() && _PCCFP<_U1, _U2>::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=true> constexpr pair(pair<_U1, _U2>&& __p) : first(std::forward<_U1>(__p.first)), second(std::forward<_U2>(__p.second)) { } template::template _MoveConstructiblePair<_U1, _U2>() && !_PCCFP<_U1, _U2>::template _ImplicitlyMoveConvertiblePair<_U1, _U2>(), bool>::type=false> explicit constexpr pair(pair<_U1, _U2>&& __p) : first(std::forward<_U1>(__p.first)), second(std::forward<_U2>(__p.second)) { } template pair(piecewise_construct_t, tuple<_Args1...>, tuple<_Args2...>); pair& operator=(typename conditional< __and_, is_copy_assignable<_T2>>::value, const pair&, const __nonesuch_no_braces&>::type __p) { first = __p.first; second = __p.second; return *this; } pair& operator=(typename conditional< __and_, is_move_assignable<_T2>>::value, pair&&, __nonesuch_no_braces&&>::type __p) noexcept(__and_, is_nothrow_move_assignable<_T2>>::value) { first = std::forward(__p.first); second = std::forward(__p.second); return *this; } template typename enable_if<__and_, is_assignable<_T2&, const _U2&>>::value, pair&>::type operator=(const pair<_U1, _U2>& __p) { first = __p.first; second = __p.second; return *this; } template typename enable_if<__and_, is_assignable<_T2&, _U2&&>>::value, pair&>::type operator=(pair<_U1, _U2>&& __p) { first = std::forward<_U1>(__p.first); second = std::forward<_U2>(__p.second); return *this; } void swap(pair& __p) noexcept(__and_<__is_nothrow_swappable<_T1>, __is_nothrow_swappable<_T2>>::value) { using std::swap; swap(first, __p.first); swap(second, __p.second); } private: template pair(tuple<_Args1...>&, tuple<_Args2...>&, _Index_tuple<_Indexes1...>, _Index_tuple<_Indexes2...>); #endif }; #if __cpp_deduction_guides >= 201606 template pair(_T1, _T2) -> pair<_T1, _T2>; #endif /// Two pairs of the same type are equal iff their members are equal. template inline _GLIBCXX_CONSTEXPR bool operator==(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return __x.first == __y.first && __x.second == __y.second; } /// template inline _GLIBCXX_CONSTEXPR bool operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return __x.first < __y.first || (!(__y.first < __x.first) && __x.second < __y.second); } /// Uses @c operator== to find the result. template inline _GLIBCXX_CONSTEXPR bool operator!=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return !(__x == __y); } /// Uses @c operator< to find the result. template inline _GLIBCXX_CONSTEXPR bool operator>(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return __y < __x; } /// Uses @c operator< to find the result. template inline _GLIBCXX_CONSTEXPR bool operator<=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return !(__y < __x); } /// Uses @c operator< to find the result. template inline _GLIBCXX_CONSTEXPR bool operator>=(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) { return !(__x < __y); } #if __cplusplus >= 201103L /// See std::pair::swap(). // Note: no std::swap overloads in C++03 mode, this has performance // implications, see, eg, libstdc++/38466. template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__and_<__is_swappable<_T1>, __is_swappable<_T2>>::value>::type #else void #endif swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if, __is_swappable<_T2>>::value>::type swap(pair<_T1, _T2>&, pair<_T1, _T2>&) = delete; #endif #endif // __cplusplus >= 201103L /** * @brief A convenience wrapper for creating a pair from two objects. * @param __x The first object. * @param __y The second object. * @return A newly-constructed pair<> object of the appropriate type. * * The standard requires that the objects be passed by reference-to-const, * but LWG issue #181 says they should be passed by const value. We follow * the LWG by default. */ // _GLIBCXX_RESOLVE_LIB_DEFECTS // 181. make_pair() unintended behavior #if __cplusplus >= 201103L // NB: DR 706. template constexpr pair::__type, typename __decay_and_strip<_T2>::__type> make_pair(_T1&& __x, _T2&& __y) { typedef typename __decay_and_strip<_T1>::__type __ds_type1; typedef typename __decay_and_strip<_T2>::__type __ds_type2; typedef pair<__ds_type1, __ds_type2> __pair_type; return __pair_type(std::forward<_T1>(__x), std::forward<_T2>(__y)); } #else template inline pair<_T1, _T2> make_pair(_T1 __x, _T2 __y) { return pair<_T1, _T2>(__x, __y); } #endif /// @} _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_PAIR_H */ c++/8/bits/std_mutex.h000064400000022122151027430570010414 0ustar00// std::mutex implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/std_mutex.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{mutex} */ #ifndef _GLIBCXX_MUTEX_H #define _GLIBCXX_MUTEX_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include // for std::swap #ifdef _GLIBCXX_USE_C99_STDINT_TR1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup mutexes Mutexes * @ingroup concurrency * * Classes for mutex support. * @{ */ #ifdef _GLIBCXX_HAS_GTHREADS // Common base class for std::mutex and std::timed_mutex class __mutex_base { protected: typedef __gthread_mutex_t __native_type; #ifdef __GTHREAD_MUTEX_INIT __native_type _M_mutex = __GTHREAD_MUTEX_INIT; constexpr __mutex_base() noexcept = default; #else __native_type _M_mutex; __mutex_base() noexcept { // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may) __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex); } ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); } #endif __mutex_base(const __mutex_base&) = delete; __mutex_base& operator=(const __mutex_base&) = delete; }; /// The standard mutex type. class mutex : private __mutex_base { public: typedef __native_type* native_handle_type; #ifdef __GTHREAD_MUTEX_INIT constexpr #endif mutex() noexcept = default; ~mutex() = default; mutex(const mutex&) = delete; mutex& operator=(const mutex&) = delete; void lock() { int __e = __gthread_mutex_lock(&_M_mutex); // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may) if (__e) __throw_system_error(__e); } bool try_lock() noexcept { // XXX EINVAL, EAGAIN, EBUSY return !__gthread_mutex_trylock(&_M_mutex); } void unlock() { // XXX EINVAL, EAGAIN, EPERM __gthread_mutex_unlock(&_M_mutex); } native_handle_type native_handle() noexcept { return &_M_mutex; } }; #endif // _GLIBCXX_HAS_GTHREADS /// Do not acquire ownership of the mutex. struct defer_lock_t { explicit defer_lock_t() = default; }; /// Try to acquire ownership of the mutex without blocking. struct try_to_lock_t { explicit try_to_lock_t() = default; }; /// Assume the calling thread has already obtained mutex ownership /// and manage it. struct adopt_lock_t { explicit adopt_lock_t() = default; }; /// Tag used to prevent a scoped lock from acquiring ownership of a mutex. _GLIBCXX17_INLINE constexpr defer_lock_t defer_lock { }; /// Tag used to prevent a scoped lock from blocking if a mutex is locked. _GLIBCXX17_INLINE constexpr try_to_lock_t try_to_lock { }; /// Tag used to make a scoped lock take ownership of a locked mutex. _GLIBCXX17_INLINE constexpr adopt_lock_t adopt_lock { }; /** @brief A simple scoped lock type. * * A lock_guard controls mutex ownership within a scope, releasing * ownership in the destructor. */ template class lock_guard { public: typedef _Mutex mutex_type; explicit lock_guard(mutex_type& __m) : _M_device(__m) { _M_device.lock(); } lock_guard(mutex_type& __m, adopt_lock_t) noexcept : _M_device(__m) { } // calling thread owns mutex ~lock_guard() { _M_device.unlock(); } lock_guard(const lock_guard&) = delete; lock_guard& operator=(const lock_guard&) = delete; private: mutex_type& _M_device; }; /** @brief A movable scoped lock type. * * A unique_lock controls mutex ownership within a scope. Ownership of the * mutex can be delayed until after construction and can be transferred * to another unique_lock by move construction or move assignment. If a * mutex lock is owned when the destructor runs ownership will be released. */ template class unique_lock { public: typedef _Mutex mutex_type; unique_lock() noexcept : _M_device(0), _M_owns(false) { } explicit unique_lock(mutex_type& __m) : _M_device(std::__addressof(__m)), _M_owns(false) { lock(); _M_owns = true; } unique_lock(mutex_type& __m, defer_lock_t) noexcept : _M_device(std::__addressof(__m)), _M_owns(false) { } unique_lock(mutex_type& __m, try_to_lock_t) : _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock()) { } unique_lock(mutex_type& __m, adopt_lock_t) noexcept : _M_device(std::__addressof(__m)), _M_owns(true) { // XXX calling thread owns mutex } template unique_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __atime) : _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock_until(__atime)) { } template unique_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __rtime) : _M_device(std::__addressof(__m)), _M_owns(_M_device->try_lock_for(__rtime)) { } ~unique_lock() { if (_M_owns) unlock(); } unique_lock(const unique_lock&) = delete; unique_lock& operator=(const unique_lock&) = delete; unique_lock(unique_lock&& __u) noexcept : _M_device(__u._M_device), _M_owns(__u._M_owns) { __u._M_device = 0; __u._M_owns = false; } unique_lock& operator=(unique_lock&& __u) noexcept { if(_M_owns) unlock(); unique_lock(std::move(__u)).swap(*this); __u._M_device = 0; __u._M_owns = false; return *this; } void lock() { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_device->lock(); _M_owns = true; } } bool try_lock() { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_owns = _M_device->try_lock(); return _M_owns; } } template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime) { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_owns = _M_device->try_lock_until(__atime); return _M_owns; } } template bool try_lock_for(const chrono::duration<_Rep, _Period>& __rtime) { if (!_M_device) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); else { _M_owns = _M_device->try_lock_for(__rtime); return _M_owns; } } void unlock() { if (!_M_owns) __throw_system_error(int(errc::operation_not_permitted)); else if (_M_device) { _M_device->unlock(); _M_owns = false; } } void swap(unique_lock& __u) noexcept { std::swap(_M_device, __u._M_device); std::swap(_M_owns, __u._M_owns); } mutex_type* release() noexcept { mutex_type* __ret = _M_device; _M_device = 0; _M_owns = false; return __ret; } bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return owns_lock(); } mutex_type* mutex() const noexcept { return _M_device; } private: mutex_type* _M_device; bool _M_owns; // XXX use atomic_bool }; /// Swap overload for unique_lock objects. template inline void swap(unique_lock<_Mutex>& __x, unique_lock<_Mutex>& __y) noexcept { __x.swap(__y); } // @} group mutexes _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 #endif // _GLIBCXX_MUTEX_H c++/8/bits/stl_bvector.h000064400000101700151027430570010726 0ustar00// vector specialization -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1999 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_bvector.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ #ifndef _STL_BVECTOR_H #define _STL_BVECTOR_H 1 #if __cplusplus >= 201103L #include #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER typedef unsigned long _Bit_type; enum { _S_word_bit = int(__CHAR_BIT__ * sizeof(_Bit_type)) }; struct _Bit_reference { _Bit_type * _M_p; _Bit_type _M_mask; _Bit_reference(_Bit_type * __x, _Bit_type __y) : _M_p(__x), _M_mask(__y) { } _Bit_reference() _GLIBCXX_NOEXCEPT : _M_p(0), _M_mask(0) { } operator bool() const _GLIBCXX_NOEXCEPT { return !!(*_M_p & _M_mask); } _Bit_reference& operator=(bool __x) _GLIBCXX_NOEXCEPT { if (__x) *_M_p |= _M_mask; else *_M_p &= ~_M_mask; return *this; } _Bit_reference& operator=(const _Bit_reference& __x) _GLIBCXX_NOEXCEPT { return *this = bool(__x); } bool operator==(const _Bit_reference& __x) const { return bool(*this) == bool(__x); } bool operator<(const _Bit_reference& __x) const { return !bool(*this) && bool(__x); } void flip() _GLIBCXX_NOEXCEPT { *_M_p ^= _M_mask; } }; #if __cplusplus >= 201103L inline void swap(_Bit_reference __x, _Bit_reference __y) noexcept { bool __tmp = __x; __x = __y; __y = __tmp; } inline void swap(_Bit_reference __x, bool& __y) noexcept { bool __tmp = __x; __x = __y; __y = __tmp; } inline void swap(bool& __x, _Bit_reference __y) noexcept { bool __tmp = __x; __x = __y; __y = __tmp; } #endif struct _Bit_iterator_base : public std::iterator { _Bit_type * _M_p; unsigned int _M_offset; _Bit_iterator_base(_Bit_type * __x, unsigned int __y) : _M_p(__x), _M_offset(__y) { } void _M_bump_up() { if (_M_offset++ == int(_S_word_bit) - 1) { _M_offset = 0; ++_M_p; } } void _M_bump_down() { if (_M_offset-- == 0) { _M_offset = int(_S_word_bit) - 1; --_M_p; } } void _M_incr(ptrdiff_t __i) { difference_type __n = __i + _M_offset; _M_p += __n / int(_S_word_bit); __n = __n % int(_S_word_bit); if (__n < 0) { __n += int(_S_word_bit); --_M_p; } _M_offset = static_cast(__n); } bool operator==(const _Bit_iterator_base& __i) const { return _M_p == __i._M_p && _M_offset == __i._M_offset; } bool operator<(const _Bit_iterator_base& __i) const { return _M_p < __i._M_p || (_M_p == __i._M_p && _M_offset < __i._M_offset); } bool operator!=(const _Bit_iterator_base& __i) const { return !(*this == __i); } bool operator>(const _Bit_iterator_base& __i) const { return __i < *this; } bool operator<=(const _Bit_iterator_base& __i) const { return !(__i < *this); } bool operator>=(const _Bit_iterator_base& __i) const { return !(*this < __i); } }; inline ptrdiff_t operator-(const _Bit_iterator_base& __x, const _Bit_iterator_base& __y) { return (int(_S_word_bit) * (__x._M_p - __y._M_p) + __x._M_offset - __y._M_offset); } struct _Bit_iterator : public _Bit_iterator_base { typedef _Bit_reference reference; typedef _Bit_reference* pointer; typedef _Bit_iterator iterator; _Bit_iterator() : _Bit_iterator_base(0, 0) { } _Bit_iterator(_Bit_type * __x, unsigned int __y) : _Bit_iterator_base(__x, __y) { } iterator _M_const_cast() const { return *this; } reference operator*() const { return reference(_M_p, 1UL << _M_offset); } iterator& operator++() { _M_bump_up(); return *this; } iterator operator++(int) { iterator __tmp = *this; _M_bump_up(); return __tmp; } iterator& operator--() { _M_bump_down(); return *this; } iterator operator--(int) { iterator __tmp = *this; _M_bump_down(); return __tmp; } iterator& operator+=(difference_type __i) { _M_incr(__i); return *this; } iterator& operator-=(difference_type __i) { *this += -__i; return *this; } iterator operator+(difference_type __i) const { iterator __tmp = *this; return __tmp += __i; } iterator operator-(difference_type __i) const { iterator __tmp = *this; return __tmp -= __i; } reference operator[](difference_type __i) const { return *(*this + __i); } }; inline _Bit_iterator operator+(ptrdiff_t __n, const _Bit_iterator& __x) { return __x + __n; } struct _Bit_const_iterator : public _Bit_iterator_base { typedef bool reference; typedef bool const_reference; typedef const bool* pointer; typedef _Bit_const_iterator const_iterator; _Bit_const_iterator() : _Bit_iterator_base(0, 0) { } _Bit_const_iterator(_Bit_type * __x, unsigned int __y) : _Bit_iterator_base(__x, __y) { } _Bit_const_iterator(const _Bit_iterator& __x) : _Bit_iterator_base(__x._M_p, __x._M_offset) { } _Bit_iterator _M_const_cast() const { return _Bit_iterator(_M_p, _M_offset); } const_reference operator*() const { return _Bit_reference(_M_p, 1UL << _M_offset); } const_iterator& operator++() { _M_bump_up(); return *this; } const_iterator operator++(int) { const_iterator __tmp = *this; _M_bump_up(); return __tmp; } const_iterator& operator--() { _M_bump_down(); return *this; } const_iterator operator--(int) { const_iterator __tmp = *this; _M_bump_down(); return __tmp; } const_iterator& operator+=(difference_type __i) { _M_incr(__i); return *this; } const_iterator& operator-=(difference_type __i) { *this += -__i; return *this; } const_iterator operator+(difference_type __i) const { const_iterator __tmp = *this; return __tmp += __i; } const_iterator operator-(difference_type __i) const { const_iterator __tmp = *this; return __tmp -= __i; } const_reference operator[](difference_type __i) const { return *(*this + __i); } }; inline _Bit_const_iterator operator+(ptrdiff_t __n, const _Bit_const_iterator& __x) { return __x + __n; } inline void __fill_bvector(_Bit_type * __v, unsigned int __first, unsigned int __last, bool __x) { const _Bit_type __fmask = ~0ul << __first; const _Bit_type __lmask = ~0ul >> (_S_word_bit - __last); const _Bit_type __mask = __fmask & __lmask; if (__x) *__v |= __mask; else *__v &= ~__mask; } inline void fill(_Bit_iterator __first, _Bit_iterator __last, const bool& __x) { if (__first._M_p != __last._M_p) { _Bit_type* __first_p = __first._M_p; if (__first._M_offset != 0) __fill_bvector(__first_p++, __first._M_offset, _S_word_bit, __x); __builtin_memset(__first_p, __x ? ~0 : 0, (__last._M_p - __first_p) * sizeof(_Bit_type)); if (__last._M_offset != 0) __fill_bvector(__last._M_p, 0, __last._M_offset, __x); } else if (__first._M_offset != __last._M_offset) __fill_bvector(__first._M_p, __first._M_offset, __last._M_offset, __x); } template struct _Bvector_base { typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Bit_type>::other _Bit_alloc_type; typedef typename __gnu_cxx::__alloc_traits<_Bit_alloc_type> _Bit_alloc_traits; typedef typename _Bit_alloc_traits::pointer _Bit_pointer; struct _Bvector_impl_data { _Bit_iterator _M_start; _Bit_iterator _M_finish; _Bit_pointer _M_end_of_storage; _Bvector_impl_data() _GLIBCXX_NOEXCEPT : _M_start(), _M_finish(), _M_end_of_storage() { } #if __cplusplus >= 201103L _Bvector_impl_data(_Bvector_impl_data&& __x) noexcept : _M_start(__x._M_start), _M_finish(__x._M_finish) , _M_end_of_storage(__x._M_end_of_storage) { __x._M_reset(); } void _M_move_data(_Bvector_impl_data&& __x) noexcept { this->_M_start = __x._M_start; this->_M_finish = __x._M_finish; this->_M_end_of_storage = __x._M_end_of_storage; __x._M_reset(); } #endif void _M_reset() _GLIBCXX_NOEXCEPT { _M_start = _M_finish = _Bit_iterator(); _M_end_of_storage = _Bit_pointer(); } }; struct _Bvector_impl : public _Bit_alloc_type, public _Bvector_impl_data { public: _Bvector_impl() _GLIBCXX_NOEXCEPT_IF( is_nothrow_default_constructible<_Bit_alloc_type>::value) : _Bit_alloc_type() { } _Bvector_impl(const _Bit_alloc_type& __a) _GLIBCXX_NOEXCEPT : _Bit_alloc_type(__a) { } #if __cplusplus >= 201103L _Bvector_impl(_Bvector_impl&&) = default; #endif _Bit_type* _M_end_addr() const _GLIBCXX_NOEXCEPT { if (this->_M_end_of_storage) return std::__addressof(this->_M_end_of_storage[-1]) + 1; return 0; } }; public: typedef _Alloc allocator_type; _Bit_alloc_type& _M_get_Bit_allocator() _GLIBCXX_NOEXCEPT { return this->_M_impl; } const _Bit_alloc_type& _M_get_Bit_allocator() const _GLIBCXX_NOEXCEPT { return this->_M_impl; } allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_get_Bit_allocator()); } #if __cplusplus >= 201103L _Bvector_base() = default; #else _Bvector_base() { } #endif _Bvector_base(const allocator_type& __a) : _M_impl(__a) { } #if __cplusplus >= 201103L _Bvector_base(_Bvector_base&&) = default; #endif ~_Bvector_base() { this->_M_deallocate(); } protected: _Bvector_impl _M_impl; _Bit_pointer _M_allocate(size_t __n) { return _Bit_alloc_traits::allocate(_M_impl, _S_nword(__n)); } void _M_deallocate() { if (_M_impl._M_start._M_p) { const size_t __n = _M_impl._M_end_addr() - _M_impl._M_start._M_p; _Bit_alloc_traits::deallocate(_M_impl, _M_impl._M_end_of_storage - __n, __n); _M_impl._M_reset(); } } #if __cplusplus >= 201103L void _M_move_data(_Bvector_base&& __x) noexcept { _M_impl._M_move_data(std::move(__x._M_impl)); } #endif static size_t _S_nword(size_t __n) { return (__n + int(_S_word_bit) - 1) / int(_S_word_bit); } }; _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std // Declare a partial specialization of vector. #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * @brief A specialization of vector for booleans which offers fixed time * access to individual elements in any order. * * @ingroup sequences * * @tparam _Alloc Allocator type. * * Note that vector does not actually meet the requirements for being * a container. This is because the reference and pointer types are not * really references and pointers to bool. See DR96 for details. @see * vector for function documentation. * * In some terminology a %vector can be described as a dynamic * C-style array, it offers fast and efficient access to individual * elements in any order and saves the user from worrying about * memory and size allocation. Subscripting ( @c [] ) access is * also provided as with C-style arrays. */ template class vector : protected _Bvector_base<_Alloc> { typedef _Bvector_base<_Alloc> _Base; typedef typename _Base::_Bit_pointer _Bit_pointer; typedef typename _Base::_Bit_alloc_traits _Bit_alloc_traits; #if __cplusplus >= 201103L friend struct std::hash; #endif public: typedef bool value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Bit_reference reference; typedef bool const_reference; typedef _Bit_reference* pointer; typedef const bool* const_pointer; typedef _Bit_iterator iterator; typedef _Bit_const_iterator const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; typedef _Alloc allocator_type; allocator_type get_allocator() const { return _Base::get_allocator(); } protected: using _Base::_M_allocate; using _Base::_M_deallocate; using _Base::_S_nword; using _Base::_M_get_Bit_allocator; public: #if __cplusplus >= 201103L vector() = default; #else vector() { } #endif explicit vector(const allocator_type& __a) : _Base(__a) { } #if __cplusplus >= 201103L explicit vector(size_type __n, const allocator_type& __a = allocator_type()) : vector(__n, false, __a) { } vector(size_type __n, const bool& __value, const allocator_type& __a = allocator_type()) #else explicit vector(size_type __n, const bool& __value = bool(), const allocator_type& __a = allocator_type()) #endif : _Base(__a) { _M_initialize(__n); _M_initialize_value(__value); } vector(const vector& __x) : _Base(_Bit_alloc_traits::_S_select_on_copy(__x._M_get_Bit_allocator())) { _M_initialize(__x.size()); _M_copy_aligned(__x.begin(), __x.end(), this->_M_impl._M_start); } #if __cplusplus >= 201103L vector(vector&&) = default; vector(vector&& __x, const allocator_type& __a) noexcept(_Bit_alloc_traits::_S_always_equal()) : _Base(__a) { if (__x.get_allocator() == __a) this->_M_move_data(std::move(__x)); else { _M_initialize(__x.size()); _M_copy_aligned(__x.begin(), __x.end(), begin()); __x.clear(); } } vector(const vector& __x, const allocator_type& __a) : _Base(__a) { _M_initialize(__x.size()); _M_copy_aligned(__x.begin(), __x.end(), this->_M_impl._M_start); } vector(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_range(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif #if __cplusplus >= 201103L template> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { _M_initialize_dispatch(__first, __last, __false_type()); } #else template vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_initialize_dispatch(__first, __last, _Integral()); } #endif ~vector() _GLIBCXX_NOEXCEPT { } vector& operator=(const vector& __x) { if (&__x == this) return *this; #if __cplusplus >= 201103L if (_Bit_alloc_traits::_S_propagate_on_copy_assign()) { if (this->_M_get_Bit_allocator() != __x._M_get_Bit_allocator()) { this->_M_deallocate(); std::__alloc_on_copy(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); _M_initialize(__x.size()); } else std::__alloc_on_copy(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); } #endif if (__x.size() > capacity()) { this->_M_deallocate(); _M_initialize(__x.size()); } this->_M_impl._M_finish = _M_copy_aligned(__x.begin(), __x.end(), begin()); return *this; } #if __cplusplus >= 201103L vector& operator=(vector&& __x) noexcept(_Bit_alloc_traits::_S_nothrow_move()) { if (_Bit_alloc_traits::_S_propagate_on_move_assign() || this->_M_get_Bit_allocator() == __x._M_get_Bit_allocator()) { this->_M_deallocate(); this->_M_move_data(std::move(__x)); std::__alloc_on_move(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); } else { if (__x.size() > capacity()) { this->_M_deallocate(); _M_initialize(__x.size()); } this->_M_impl._M_finish = _M_copy_aligned(__x.begin(), __x.end(), begin()); __x.clear(); } return *this; } vector& operator=(initializer_list __l) { this->assign (__l.begin(), __l.end()); return *this; } #endif // assign(), a generalized assignment member function. Two // versions: one that takes a count, and one that takes a range. // The range version is a member template, so we dispatch on whether // or not the type is an integer. void assign(size_type __n, const bool& __x) { _M_fill_assign(__n, __x); } #if __cplusplus >= 201103L template> void assign(_InputIterator __first, _InputIterator __last) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } #else template void assign(_InputIterator __first, _InputIterator __last) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_assign_dispatch(__first, __last, _Integral()); } #endif #if __cplusplus >= 201103L void assign(initializer_list __l) { _M_assign_aux(__l.begin(), __l.end(), random_access_iterator_tag()); } #endif iterator begin() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } const_iterator begin() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_start; } iterator end() _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } const_iterator end() const _GLIBCXX_NOEXCEPT { return this->_M_impl._M_finish; } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return this->_M_impl._M_start; } const_iterator cend() const noexcept { return this->_M_impl._M_finish; } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif size_type size() const _GLIBCXX_NOEXCEPT { return size_type(end() - begin()); } size_type max_size() const _GLIBCXX_NOEXCEPT { const size_type __isize = __gnu_cxx::__numeric_traits::__max - int(_S_word_bit) + 1; const size_type __asize = _Bit_alloc_traits::max_size(_M_get_Bit_allocator()); return (__asize <= __isize / int(_S_word_bit) ? __asize * int(_S_word_bit) : __isize); } size_type capacity() const _GLIBCXX_NOEXCEPT { return size_type(const_iterator(this->_M_impl._M_end_addr(), 0) - begin()); } bool empty() const _GLIBCXX_NOEXCEPT { return begin() == end(); } reference operator[](size_type __n) { return *iterator(this->_M_impl._M_start._M_p + __n / int(_S_word_bit), __n % int(_S_word_bit)); } const_reference operator[](size_type __n) const { return *const_iterator(this->_M_impl._M_start._M_p + __n / int(_S_word_bit), __n % int(_S_word_bit)); } protected: void _M_range_check(size_type __n) const { if (__n >= this->size()) __throw_out_of_range_fmt(__N("vector::_M_range_check: __n " "(which is %zu) >= this->size() " "(which is %zu)"), __n, this->size()); } public: reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } const_reference at(size_type __n) const { _M_range_check(__n); return (*this)[__n]; } void reserve(size_type __n) { if (__n > max_size()) __throw_length_error(__N("vector::reserve")); if (capacity() < __n) _M_reallocate(__n); } reference front() { return *begin(); } const_reference front() const { return *begin(); } reference back() { return *(end() - 1); } const_reference back() const { return *(end() - 1); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. // N.B. DR 464 says nothing about vector but we need something // here due to the way we are implementing DR 464 in the debug-mode // vector class. void data() _GLIBCXX_NOEXCEPT { } void push_back(bool __x) { if (this->_M_impl._M_finish._M_p != this->_M_impl._M_end_addr()) *this->_M_impl._M_finish++ = __x; else _M_insert_aux(end(), __x); } void swap(vector& __x) _GLIBCXX_NOEXCEPT { std::swap(this->_M_impl._M_start, __x._M_impl._M_start); std::swap(this->_M_impl._M_finish, __x._M_impl._M_finish); std::swap(this->_M_impl._M_end_of_storage, __x._M_impl._M_end_of_storage); _Bit_alloc_traits::_S_on_swap(_M_get_Bit_allocator(), __x._M_get_Bit_allocator()); } // [23.2.5]/1, third-to-last entry in synopsis listing static void swap(reference __x, reference __y) _GLIBCXX_NOEXCEPT { bool __tmp = __x; __x = __y; __y = __tmp; } iterator #if __cplusplus >= 201103L insert(const_iterator __position, const bool& __x = bool()) #else insert(iterator __position, const bool& __x = bool()) #endif { const difference_type __n = __position - begin(); if (this->_M_impl._M_finish._M_p != this->_M_impl._M_end_addr() && __position == end()) *this->_M_impl._M_finish++ = __x; else _M_insert_aux(__position._M_const_cast(), __x); return begin() + __n; } #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { difference_type __offset = __position - cbegin(); _M_insert_dispatch(__position._M_const_cast(), __first, __last, __false_type()); return begin() + __offset; } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; _M_insert_dispatch(__position, __first, __last, _Integral()); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const bool& __x) { difference_type __offset = __position - cbegin(); _M_fill_insert(__position._M_const_cast(), __n, __x); return begin() + __offset; } #else void insert(iterator __position, size_type __n, const bool& __x) { _M_fill_insert(__position, __n, __x); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __p, initializer_list __l) { return this->insert(__p, __l.begin(), __l.end()); } #endif void pop_back() { --this->_M_impl._M_finish; } iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { return _M_erase(__position._M_const_cast()); } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { return _M_erase(__first._M_const_cast(), __last._M_const_cast()); } void resize(size_type __new_size, bool __x = bool()) { if (__new_size < size()) _M_erase_at_end(begin() + difference_type(__new_size)); else insert(end(), __new_size - size(), __x); } #if __cplusplus >= 201103L void shrink_to_fit() { _M_shrink_to_fit(); } #endif void flip() _GLIBCXX_NOEXCEPT { _Bit_type * const __end = this->_M_impl._M_end_addr(); for (_Bit_type * __p = this->_M_impl._M_start._M_p; __p != __end; ++__p) *__p = ~*__p; } void clear() _GLIBCXX_NOEXCEPT { _M_erase_at_end(begin()); } #if __cplusplus >= 201103L template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { push_back(bool(__args...)); #if __cplusplus > 201402L return back(); #endif } template iterator emplace(const_iterator __pos, _Args&&... __args) { return insert(__pos, bool(__args...)); } #endif protected: // Precondition: __first._M_offset == 0 && __result._M_offset == 0. iterator _M_copy_aligned(const_iterator __first, const_iterator __last, iterator __result) { _Bit_type* __q = std::copy(__first._M_p, __last._M_p, __result._M_p); return std::copy(const_iterator(__last._M_p, 0), __last, iterator(__q, 0)); } void _M_initialize(size_type __n) { if (__n) { _Bit_pointer __q = this->_M_allocate(__n); this->_M_impl._M_end_of_storage = __q + _S_nword(__n); this->_M_impl._M_start = iterator(std::__addressof(*__q), 0); } else { this->_M_impl._M_end_of_storage = _Bit_pointer(); this->_M_impl._M_start = iterator(0, 0); } this->_M_impl._M_finish = this->_M_impl._M_start + difference_type(__n); } void _M_initialize_value(bool __x) { if (_Bit_type* __p = this->_M_impl._M_start._M_p) __builtin_memset(__p, __x ? ~0 : 0, (this->_M_impl._M_end_addr() - __p) * sizeof(_Bit_type)); } void _M_reallocate(size_type __n); #if __cplusplus >= 201103L bool _M_shrink_to_fit(); #endif // Check whether it's an integral type. If so, it's not an iterator. // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_initialize_dispatch(_Integer __n, _Integer __x, __true_type) { _M_initialize(static_cast(__n)); _M_initialize_value(__x); } template void _M_initialize_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_initialize_range(__first, __last, std::__iterator_category(__first)); } template void _M_initialize_range(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { for (; __first != __last; ++__first) push_back(*__first); } template void _M_initialize_range(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); _M_initialize(__n); std::copy(__first, __last, this->_M_impl._M_start); } #if __cplusplus < 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign(__n, __val); } template void _M_assign_dispatch(_InputIterator __first, _InputIterator __last, __false_type) { _M_assign_aux(__first, __last, std::__iterator_category(__first)); } #endif void _M_fill_assign(size_t __n, bool __x) { if (__n > size()) { _M_initialize_value(__x); insert(end(), __n - size(), __x); } else { _M_erase_at_end(begin() + __n); _M_initialize_value(__x); } } template void _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { iterator __cur = begin(); for (; __first != __last && __cur != end(); ++__cur, ++__first) *__cur = *__first; if (__first == __last) _M_erase_at_end(__cur); else insert(end(), __first, __last); } template void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __len = std::distance(__first, __last); if (__len < size()) _M_erase_at_end(std::copy(__first, __last, begin())); else { _ForwardIterator __mid = __first; std::advance(__mid, size()); std::copy(__first, __mid, begin()); insert(end(), __mid, __last); } } // Check whether it's an integral type. If so, it's not an iterator. // _GLIBCXX_RESOLVE_LIB_DEFECTS // 438. Ambiguity in the "do the right thing" clause template void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __x, __true_type) { _M_fill_insert(__pos, __n, __x); } template void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_insert_range(__pos, __first, __last, std::__iterator_category(__first)); } void _M_fill_insert(iterator __position, size_type __n, bool __x); template void _M_insert_range(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag) { for (; __first != __last; ++__first) { __pos = insert(__pos, *__first); ++__pos; } } template void _M_insert_range(iterator __position, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag); void _M_insert_aux(iterator __position, bool __x); size_type _M_check_len(size_type __n, const char* __s) const { if (max_size() - size() < __n) __throw_length_error(__N(__s)); const size_type __len = size() + std::max(size(), __n); return (__len < size() || __len > max_size()) ? max_size() : __len; } void _M_erase_at_end(iterator __pos) { this->_M_impl._M_finish = __pos; } iterator _M_erase(iterator __pos); iterator _M_erase(iterator __first, iterator __last); }; _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. /// std::hash specialization for vector. template struct hash<_GLIBCXX_STD_C::vector> : public __hash_base> { size_t operator()(const _GLIBCXX_STD_C::vector&) const noexcept; }; _GLIBCXX_END_NAMESPACE_VERSION }// namespace std #endif // C++11 #endif c++/8/bits/stl_multiset.h000064400000105741151027430570011141 0ustar00// Multiset implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_multiset.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{set} */ #ifndef _STL_MULTISET_H #define _STL_MULTISET_H 1 #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template class set; /** * @brief A standard container made up of elements, which can be retrieved * in logarithmic time. * * @ingroup associative_containers * * * @tparam _Key Type of key objects. * @tparam _Compare Comparison function object type, defaults to less<_Key>. * @tparam _Alloc Allocator type, defaults to allocator<_Key>. * * Meets the requirements of a container, a * reversible container, and an * associative container (using equivalent * keys). For a @c multiset the key_type and value_type are Key. * * Multisets support bidirectional iterators. * * The private tree data is declared exactly the same way for set and * multiset; the distinction is made entirely in how the tree functions are * called (*_unique versus *_equal, same as the standard). */ template , typename _Alloc = std::allocator<_Key> > class multiset { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Alloc::value_type _Alloc_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Key, _SGIAssignableConcept) # endif __glibcxx_class_requires4(_Compare, bool, _Key, _Key, _BinaryFunctionConcept) __glibcxx_class_requires2(_Key, _Alloc_value_type, _SameTypeConcept) #endif #if __cplusplus >= 201103L static_assert(is_same::type, _Key>::value, "std::multiset must have a non-const, non-volatile value_type"); # ifdef __STRICT_ANSI__ static_assert(is_same::value, "std::multiset must have the same value_type as its allocator"); # endif #endif public: // typedefs: typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Alloc allocator_type; private: /// This turns a red-black tree into a [multi]set. typedef typename __gnu_cxx::__alloc_traits<_Alloc>::template rebind<_Key>::other _Key_alloc_type; typedef _Rb_tree, key_compare, _Key_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; typedef __gnu_cxx::__alloc_traits<_Key_alloc_type> _Alloc_traits; public: typedef typename _Alloc_traits::pointer pointer; typedef typename _Alloc_traits::const_pointer const_pointer; typedef typename _Alloc_traits::reference reference; typedef typename _Alloc_traits::const_reference const_reference; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 103. set::iterator is required to be modifiable, // but this allows modification of keys. typedef typename _Rep_type::const_iterator iterator; typedef typename _Rep_type::const_iterator const_iterator; typedef typename _Rep_type::const_reverse_iterator reverse_iterator; typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator; typedef typename _Rep_type::size_type size_type; typedef typename _Rep_type::difference_type difference_type; #if __cplusplus > 201402L using node_type = typename _Rep_type::node_type; #endif // allocation/deallocation /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L multiset() : _M_t() { } #else multiset() = default; #endif /** * @brief Creates a %multiset with no elements. * @param __comp Comparator to use. * @param __a An allocator object. */ explicit multiset(const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { } /** * @brief Builds a %multiset from a range. * @param __first An input iterator. * @param __last An input iterator. * * Create a %multiset consisting of copies of the elements from * [first,last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multiset(_InputIterator __first, _InputIterator __last) : _M_t() { _M_t._M_insert_equal(__first, __last); } /** * @brief Builds a %multiset from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multiset consisting of copies of the elements from * [__first,__last). This is linear in N if the range is already sorted, * and NlogN otherwise (where N is distance(__first,__last)). */ template multiset(_InputIterator __first, _InputIterator __last, const _Compare& __comp, const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } /** * @brief %Multiset copy constructor. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multiset(const multiset& __x) : _M_t(__x._M_t) { } #else multiset(const multiset&) = default; /** * @brief %Multiset move constructor. * * The newly-created %multiset contains the exact contents of the * moved instance. The moved instance is a valid, but unspecified * %multiset. */ multiset(multiset&&) = default; /** * @brief Builds a %multiset from an initializer_list. * @param __l An initializer_list. * @param __comp A comparison functor. * @param __a An allocator object. * * Create a %multiset consisting of copies of the elements from * the list. This is linear in N if the list is already sorted, * and NlogN otherwise (where N is @a __l.size()). */ multiset(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _M_t(__comp, _Key_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended default constructor. explicit multiset(const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { } /// Allocator-extended copy constructor. multiset(const multiset& __m, const allocator_type& __a) : _M_t(__m._M_t, _Key_alloc_type(__a)) { } /// Allocator-extended move constructor. multiset(multiset&& __m, const allocator_type& __a) noexcept(is_nothrow_copy_constructible<_Compare>::value && _Alloc_traits::_S_always_equal()) : _M_t(std::move(__m._M_t), _Key_alloc_type(__a)) { } /// Allocator-extended initialier-list constructor. multiset(initializer_list __l, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_equal(__l.begin(), __l.end()); } /// Allocator-extended range constructor. template multiset(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _M_t(_Compare(), _Key_alloc_type(__a)) { _M_t._M_insert_equal(__first, __last); } /** * The dtor only erases the elements, and note that if the elements * themselves are pointers, the pointed-to memory is not touched in any * way. Managing the pointer is the user's responsibility. */ ~multiset() = default; #endif /** * @brief %Multiset assignment operator. * * Whether the allocator is copied depends on the allocator traits. */ #if __cplusplus < 201103L multiset& operator=(const multiset& __x) { _M_t = __x._M_t; return *this; } #else multiset& operator=(const multiset&) = default; /// Move assignment operator. multiset& operator=(multiset&&) = default; /** * @brief %Multiset list assignment operator. * @param __l An initializer_list. * * This function fills a %multiset with copies of the elements in the * initializer list @a __l. * * Note that the assignment completely changes the %multiset and * that the resulting %multiset's size is the same as the number * of elements assigned. */ multiset& operator=(initializer_list __l) { _M_t._M_assign_equal(__l.begin(), __l.end()); return *this; } #endif // accessors: /// Returns the comparison object. key_compare key_comp() const { return _M_t.key_comp(); } /// Returns the comparison object. value_compare value_comp() const { return _M_t.key_comp(); } /// Returns the memory allocation object. allocator_type get_allocator() const _GLIBCXX_NOEXCEPT { return allocator_type(_M_t.get_allocator()); } /** * Returns a read-only (constant) iterator that points to the first * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator begin() const _GLIBCXX_NOEXCEPT { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator end() const _GLIBCXX_NOEXCEPT { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return _M_t.rend(); } #if __cplusplus >= 201103L /** * Returns a read-only (constant) iterator that points to the first * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator cbegin() const noexcept { return _M_t.begin(); } /** * Returns a read-only (constant) iterator that points one past the last * element in the %multiset. Iteration is done in ascending order * according to the keys. */ iterator cend() const noexcept { return _M_t.end(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator crbegin() const noexcept { return _M_t.rbegin(); } /** * Returns a read-only (constant) reverse iterator that points to the * last element in the %multiset. Iteration is done in descending order * according to the keys. */ reverse_iterator crend() const noexcept { return _M_t.rend(); } #endif /// Returns true if the %set is empty. bool empty() const _GLIBCXX_NOEXCEPT { return _M_t.empty(); } /// Returns the size of the %set. size_type size() const _GLIBCXX_NOEXCEPT { return _M_t.size(); } /// Returns the maximum size of the %set. size_type max_size() const _GLIBCXX_NOEXCEPT { return _M_t.max_size(); } /** * @brief Swaps data with another %multiset. * @param __x A %multiset of the same element and allocator types. * * This exchanges the elements between two multisets in constant time. * (It is only swapping a pointer, an integer, and an instance of the @c * Compare type (which itself is often stateless and empty), so it should * be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. * * Whether the allocators are swapped depends on the allocator traits. */ void swap(multiset& __x) _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Compare>::value) { _M_t.swap(__x._M_t); } // insert/erase #if __cplusplus >= 201103L /** * @brief Builds and inserts an element into the %multiset. * @param __args Arguments used to generate the element instance to be * inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Insertion requires logarithmic time. */ template iterator emplace(_Args&&... __args) { return _M_t._M_emplace_equal(std::forward<_Args>(__args)...); } /** * @brief Builds and inserts an element into the %multiset. * @param __pos An iterator that serves as a hint as to where the * element should be inserted. * @param __args Arguments used to generate the element instance to be * inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_t._M_emplace_hint_equal(__pos, std::forward<_Args>(__args)...); } #endif /** * @brief Inserts an element into the %multiset. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Insertion requires logarithmic time. */ iterator insert(const value_type& __x) { return _M_t._M_insert_equal(__x); } #if __cplusplus >= 201103L iterator insert(value_type&& __x) { return _M_t._M_insert_equal(std::move(__x)); } #endif /** * @brief Inserts an element into the %multiset. * @param __position An iterator that serves as a hint as to where the * element should be inserted. * @param __x Element to be inserted. * @return An iterator that points to the inserted element. * * This function inserts an element into the %multiset. Contrary * to a std::set the %multiset does not rely on unique keys and thus * multiple copies of the same element can be inserted. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires logarithmic time (if the hint is not taken). */ iterator insert(const_iterator __position, const value_type& __x) { return _M_t._M_insert_equal_(__position, __x); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { return _M_t._M_insert_equal_(__position, std::move(__x)); } #endif /** * @brief A template function that tries to insert a range of elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_t._M_insert_equal(__first, __last); } #if __cplusplus >= 201103L /** * @brief Attempts to insert a list of elements into the %multiset. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } #endif #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_t.extract(__pos); } /// Extract a node. node_type extract(const key_type& __x) { return _M_t.extract(__x); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_t._M_reinsert_node_equal(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_t._M_reinsert_node_hint_equal(__hint, std::move(__nh)); } template friend class std::_Rb_tree_merge_helper; template void merge(multiset<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(multiset<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } template void merge(set<_Key, _Compare1, _Alloc>& __source) { using _Merge_helper = _Rb_tree_merge_helper; _M_t._M_merge_equal(_Merge_helper::_S_get_tree(__source)); } template void merge(set<_Key, _Compare1, _Alloc>&& __source) { merge(__source); } #endif // C++17 #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases an element from a %multiset. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from a %multiset. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __position) { return _M_t.erase(__position); } #else /** * @brief Erases an element from a %multiset. * @param __position An iterator pointing to the element to be erased. * * This function erases an element, pointed to by the given iterator, * from a %multiset. Note that this function only erases the element, * and that if the element is itself a pointer, the pointed-to memory is * not touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __position) { _M_t.erase(__position); } #endif /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all elements located by the given key from a * %multiset. * Note that this function only erases the element, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_t.erase(__x); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 130. Associative erase should return an iterator. /** * @brief Erases a [first,last) range of elements from a %multiset. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a last. * * This function erases a sequence of elements from a %multiset. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ _GLIBCXX_ABI_TAG_CXX11 iterator erase(const_iterator __first, const_iterator __last) { return _M_t.erase(__first, __last); } #else /** * @brief Erases a [first,last) range of elements from a %multiset. * @param first Iterator pointing to the start of the range to be * erased. * @param last Iterator pointing to the end of the range to be erased. * * This function erases a sequence of elements from a %multiset. * Note that this function only erases the elements, and that if * the elements themselves are pointers, the pointed-to memory is not * touched in any way. Managing the pointer is the user's * responsibility. */ void erase(iterator __first, iterator __last) { _M_t.erase(__first, __last); } #endif /** * Erases all elements in a %multiset. Note that this function only * erases the elements, and that if the elements themselves are pointers, * the pointed-to memory is not touched in any way. Managing the pointer * is the user's responsibility. */ void clear() _GLIBCXX_NOEXCEPT { _M_t.clear(); } // multiset operations: //@{ /** * @brief Finds the number of elements with given key. * @param __x Key of elements to be located. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_t.count(__x); } #if __cplusplus > 201103L template auto count(const _Kt& __x) const -> decltype(_M_t._M_count_tr(__x)) { return _M_t._M_count_tr(__x); } #endif //@} // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload //@{ /** * @brief Tries to locate an element in a %set. * @param __x Element to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_t.find(__x); } const_iterator find(const key_type& __x) const { return _M_t.find(__x); } #if __cplusplus > 201103L template auto find(const _Kt& __x) -> decltype(iterator{_M_t._M_find_tr(__x)}) { return iterator{_M_t._M_find_tr(__x)}; } template auto find(const _Kt& __x) const -> decltype(const_iterator{_M_t._M_find_tr(__x)}) { return const_iterator{_M_t._M_find_tr(__x)}; } #endif //@} //@{ /** * @brief Finds the beginning of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to first element equal to or greater * than key, or end(). * * This function returns the first element of a subsequence of elements * that matches the given key. If unsuccessful it returns an iterator * pointing to the first element that has a greater value than given key * or end() if no such element exists. */ iterator lower_bound(const key_type& __x) { return _M_t.lower_bound(__x); } const_iterator lower_bound(const key_type& __x) const { return _M_t.lower_bound(__x); } #if __cplusplus > 201103L template auto lower_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } template auto lower_bound(const _Kt& __x) const -> decltype(iterator(_M_t._M_lower_bound_tr(__x))) { return iterator(_M_t._M_lower_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds the end of a subsequence matching given key. * @param __x Key to be located. * @return Iterator pointing to the first element * greater than key, or end(). */ iterator upper_bound(const key_type& __x) { return _M_t.upper_bound(__x); } const_iterator upper_bound(const key_type& __x) const { return _M_t.upper_bound(__x); } #if __cplusplus > 201103L template auto upper_bound(const _Kt& __x) -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } template auto upper_bound(const _Kt& __x) const -> decltype(iterator(_M_t._M_upper_bound_tr(__x))) { return iterator(_M_t._M_upper_bound_tr(__x)); } #endif //@} //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function is equivalent to * @code * std::make_pair(c.lower_bound(val), * c.upper_bound(val)) * @endcode * (but is faster than making the calls separately). * * This function probably only makes sense for multisets. */ std::pair equal_range(const key_type& __x) { return _M_t.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_t.equal_range(__x); } #if __cplusplus > 201103L template auto equal_range(const _Kt& __x) -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } template auto equal_range(const _Kt& __x) const -> decltype(pair(_M_t._M_equal_range_tr(__x))) { return pair(_M_t._M_equal_range_tr(__x)); } #endif //@} template friend bool operator==(const multiset<_K1, _C1, _A1>&, const multiset<_K1, _C1, _A1>&); template friend bool operator< (const multiset<_K1, _C1, _A1>&, const multiset<_K1, _C1, _A1>&); }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> multiset(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Allocator) -> multiset::value_type, less::value_type>, _Allocator>; template> multiset(initializer_list<_Key>, _Allocator) -> multiset<_Key, less<_Key>, _Allocator>; #endif /** * @brief Multiset equality comparison. * @param __x A %multiset. * @param __y A %multiset of the same type as @a __x. * @return True iff the size and elements of the multisets are equal. * * This is an equivalence relation. It is linear in the size of the * multisets. * Multisets are considered equivalent if their sizes are equal, and if * corresponding elements compare equal. */ template inline bool operator==(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return __x._M_t == __y._M_t; } /** * @brief Multiset ordering relation. * @param __x A %multiset. * @param __y A %multiset of the same type as @a __x. * @return True iff @a __x is lexicographically less than @a __y. * * This is a total ordering relation. It is linear in the size of the * sets. The elements must be comparable with @c <. * * See std::lexicographical_compare() for how the determination is made. */ template inline bool operator<(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return __x._M_t < __y._M_t; } /// Returns !(x == y). template inline bool operator!=(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return !(__x == __y); } /// Returns y < x. template inline bool operator>(const multiset<_Key,_Compare,_Alloc>& __x, const multiset<_Key,_Compare,_Alloc>& __y) { return __y < __x; } /// Returns !(y < x) template inline bool operator<=(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return !(__y < __x); } /// Returns !(x < y) template inline bool operator>=(const multiset<_Key, _Compare, _Alloc>& __x, const multiset<_Key, _Compare, _Alloc>& __y) { return !(__x < __y); } /// See std::multiset::swap(). template inline void swap(multiset<_Key, _Compare, _Alloc>& __x, multiset<_Key, _Compare, _Alloc>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::multiset access to internals of compatible sets. template struct _Rb_tree_merge_helper<_GLIBCXX_STD_C::multiset<_Val, _Cmp1, _Alloc>, _Cmp2> { private: friend class _GLIBCXX_STD_C::multiset<_Val, _Cmp1, _Alloc>; static auto& _S_get_tree(_GLIBCXX_STD_C::set<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } static auto& _S_get_tree(_GLIBCXX_STD_C::multiset<_Val, _Cmp2, _Alloc>& __set) { return __set._M_t; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _STL_MULTISET_H */ c++/8/bits/functional_hash.h000064400000020056151027430570011551 0ustar00// functional_hash.h header -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/functional_hash.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _FUNCTIONAL_HASH_H #define _FUNCTIONAL_HASH_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** @defgroup hashes Hashes * @ingroup functors * * Hashing functors taking a variable type and returning a @c std::size_t. * * @{ */ template struct __hash_base { typedef _Result result_type _GLIBCXX17_DEPRECATED; typedef _Arg argument_type _GLIBCXX17_DEPRECATED; }; /// Primary class template hash. template struct hash; template struct __poison_hash { static constexpr bool __enable_hash_call = false; private: // Private rather than deleted to be non-trivially-copyable. __poison_hash(__poison_hash&&); ~__poison_hash(); }; template struct __poison_hash<_Tp, __void_t()(declval<_Tp>()))>> { static constexpr bool __enable_hash_call = true; }; // Helper struct for SFINAE-poisoning non-enum types. template::value> struct __hash_enum { private: // Private rather than deleted to be non-trivially-copyable. __hash_enum(__hash_enum&&); ~__hash_enum(); }; // Helper struct for hash with enum types. template struct __hash_enum<_Tp, true> : public __hash_base { size_t operator()(_Tp __val) const noexcept { using __type = typename underlying_type<_Tp>::type; return hash<__type>{}(static_cast<__type>(__val)); } }; /// Primary class template hash, usable for enum types only. // Use with non-enum types still SFINAES. template struct hash : __hash_enum<_Tp> { }; /// Partial specializations for pointer types. template struct hash<_Tp*> : public __hash_base { size_t operator()(_Tp* __p) const noexcept { return reinterpret_cast(__p); } }; // Explicit specializations for integer types. #define _Cxx_hashtable_define_trivial_hash(_Tp) \ template<> \ struct hash<_Tp> : public __hash_base \ { \ size_t \ operator()(_Tp __val) const noexcept \ { return static_cast(__val); } \ }; /// Explicit specialization for bool. _Cxx_hashtable_define_trivial_hash(bool) /// Explicit specialization for char. _Cxx_hashtable_define_trivial_hash(char) /// Explicit specialization for signed char. _Cxx_hashtable_define_trivial_hash(signed char) /// Explicit specialization for unsigned char. _Cxx_hashtable_define_trivial_hash(unsigned char) /// Explicit specialization for wchar_t. _Cxx_hashtable_define_trivial_hash(wchar_t) /// Explicit specialization for char16_t. _Cxx_hashtable_define_trivial_hash(char16_t) /// Explicit specialization for char32_t. _Cxx_hashtable_define_trivial_hash(char32_t) /// Explicit specialization for short. _Cxx_hashtable_define_trivial_hash(short) /// Explicit specialization for int. _Cxx_hashtable_define_trivial_hash(int) /// Explicit specialization for long. _Cxx_hashtable_define_trivial_hash(long) /// Explicit specialization for long long. _Cxx_hashtable_define_trivial_hash(long long) /// Explicit specialization for unsigned short. _Cxx_hashtable_define_trivial_hash(unsigned short) /// Explicit specialization for unsigned int. _Cxx_hashtable_define_trivial_hash(unsigned int) /// Explicit specialization for unsigned long. _Cxx_hashtable_define_trivial_hash(unsigned long) /// Explicit specialization for unsigned long long. _Cxx_hashtable_define_trivial_hash(unsigned long long) #ifdef __GLIBCXX_TYPE_INT_N_0 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_0) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_0 unsigned) #endif #ifdef __GLIBCXX_TYPE_INT_N_1 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_1) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_1 unsigned) #endif #ifdef __GLIBCXX_TYPE_INT_N_2 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_2) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_2 unsigned) #endif #ifdef __GLIBCXX_TYPE_INT_N_3 _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_3) _Cxx_hashtable_define_trivial_hash(__GLIBCXX_TYPE_INT_N_3 unsigned) #endif #undef _Cxx_hashtable_define_trivial_hash struct _Hash_impl { static size_t hash(const void* __ptr, size_t __clength, size_t __seed = static_cast(0xc70f6907UL)) { return _Hash_bytes(__ptr, __clength, __seed); } template static size_t hash(const _Tp& __val) { return hash(&__val, sizeof(__val)); } template static size_t __hash_combine(const _Tp& __val, size_t __hash) { return hash(&__val, sizeof(__val), __hash); } }; // A hash function similar to FNV-1a (see PR59406 for how it differs). struct _Fnv_hash_impl { static size_t hash(const void* __ptr, size_t __clength, size_t __seed = static_cast(2166136261UL)) { return _Fnv_hash_bytes(__ptr, __clength, __seed); } template static size_t hash(const _Tp& __val) { return hash(&__val, sizeof(__val)); } template static size_t __hash_combine(const _Tp& __val, size_t __hash) { return hash(&__val, sizeof(__val), __hash); } }; /// Specialization for float. template<> struct hash : public __hash_base { size_t operator()(float __val) const noexcept { // 0 and -0 both hash to zero. return __val != 0.0f ? std::_Hash_impl::hash(__val) : 0; } }; /// Specialization for double. template<> struct hash : public __hash_base { size_t operator()(double __val) const noexcept { // 0 and -0 both hash to zero. return __val != 0.0 ? std::_Hash_impl::hash(__val) : 0; } }; /// Specialization for long double. template<> struct hash : public __hash_base { _GLIBCXX_PURE size_t operator()(long double __val) const noexcept; }; // @} group hashes // Hint about performance of hash functor. If not fast the hash-based // containers will cache the hash code. // Default behavior is to consider that hashers are fast unless specified // otherwise. template struct __is_fast_hash : public std::true_type { }; template<> struct __is_fast_hash> : public std::false_type { }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _FUNCTIONAL_HASH_H c++/8/bits/boost_concept_check.h000064400000065031151027430570012404 0ustar00// -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // (C) Copyright Jeremy Siek 2000. Permission to copy, use, modify, // sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. // /** @file bits/boost_concept_check.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ // GCC Note: based on version 1.12.0 of the Boost library. #ifndef _BOOST_CONCEPT_CHECK_H #define _BOOST_CONCEPT_CHECK_H 1 #pragma GCC system_header #include #include // for traits and tags namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #define _IsUnused __attribute__ ((__unused__)) // When the C-C code is in use, we would like this function to do as little // as possible at runtime, use as few resources as possible, and hopefully // be elided out of existence... hmmm. template inline void __function_requires() { void (_Concept::*__x)() _IsUnused = &_Concept::__constraints; } // No definition: if this is referenced, there's a problem with // the instantiating type not being one of the required integer types. // Unfortunately, this results in a link-time error, not a compile-time error. void __error_type_must_be_an_integer_type(); void __error_type_must_be_an_unsigned_integer_type(); void __error_type_must_be_a_signed_integer_type(); // ??? Should the "concept_checking*" structs begin with more than _ ? #define _GLIBCXX_CLASS_REQUIRES(_type_var, _ns, _concept) \ typedef void (_ns::_concept <_type_var>::* _func##_type_var##_concept)(); \ template <_func##_type_var##_concept _Tp1> \ struct _concept_checking##_type_var##_concept { }; \ typedef _concept_checking##_type_var##_concept< \ &_ns::_concept <_type_var>::__constraints> \ _concept_checking_typedef##_type_var##_concept #define _GLIBCXX_CLASS_REQUIRES2(_type_var1, _type_var2, _ns, _concept) \ typedef void (_ns::_concept <_type_var1,_type_var2>::* _func##_type_var1##_type_var2##_concept)(); \ template <_func##_type_var1##_type_var2##_concept _Tp1> \ struct _concept_checking##_type_var1##_type_var2##_concept { }; \ typedef _concept_checking##_type_var1##_type_var2##_concept< \ &_ns::_concept <_type_var1,_type_var2>::__constraints> \ _concept_checking_typedef##_type_var1##_type_var2##_concept #define _GLIBCXX_CLASS_REQUIRES3(_type_var1, _type_var2, _type_var3, _ns, _concept) \ typedef void (_ns::_concept <_type_var1,_type_var2,_type_var3>::* _func##_type_var1##_type_var2##_type_var3##_concept)(); \ template <_func##_type_var1##_type_var2##_type_var3##_concept _Tp1> \ struct _concept_checking##_type_var1##_type_var2##_type_var3##_concept { }; \ typedef _concept_checking##_type_var1##_type_var2##_type_var3##_concept< \ &_ns::_concept <_type_var1,_type_var2,_type_var3>::__constraints> \ _concept_checking_typedef##_type_var1##_type_var2##_type_var3##_concept #define _GLIBCXX_CLASS_REQUIRES4(_type_var1, _type_var2, _type_var3, _type_var4, _ns, _concept) \ typedef void (_ns::_concept <_type_var1,_type_var2,_type_var3,_type_var4>::* _func##_type_var1##_type_var2##_type_var3##_type_var4##_concept)(); \ template <_func##_type_var1##_type_var2##_type_var3##_type_var4##_concept _Tp1> \ struct _concept_checking##_type_var1##_type_var2##_type_var3##_type_var4##_concept { }; \ typedef _concept_checking##_type_var1##_type_var2##_type_var3##_type_var4##_concept< \ &_ns::_concept <_type_var1,_type_var2,_type_var3,_type_var4>::__constraints> \ _concept_checking_typedef##_type_var1##_type_var2##_type_var3##_type_var4##_concept template struct _Aux_require_same { }; template struct _Aux_require_same<_Tp,_Tp> { typedef _Tp _Type; }; template struct _SameTypeConcept { void __constraints() { typedef typename _Aux_require_same<_Tp1, _Tp2>::_Type _Required; } }; template struct _IntegerConcept { void __constraints() { __error_type_must_be_an_integer_type(); } }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints(){} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template <> struct _IntegerConcept { void __constraints() {} }; template struct _SignedIntegerConcept { void __constraints() { __error_type_must_be_a_signed_integer_type(); } }; template <> struct _SignedIntegerConcept { void __constraints() {} }; template <> struct _SignedIntegerConcept { void __constraints() {} }; template <> struct _SignedIntegerConcept { void __constraints() {} }; template <> struct _SignedIntegerConcept { void __constraints(){}}; template struct _UnsignedIntegerConcept { void __constraints() { __error_type_must_be_an_unsigned_integer_type(); } }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; template <> struct _UnsignedIntegerConcept { void __constraints() {} }; //=========================================================================== // Basic Concepts template struct _DefaultConstructibleConcept { void __constraints() { _Tp __a _IsUnused; // require default constructor } }; template struct _AssignableConcept { void __constraints() { __a = __a; // require assignment operator __const_constraints(__a); } void __const_constraints(const _Tp& __b) { __a = __b; // const required for argument to assignment } _Tp __a; // possibly should be "Tp* a;" and then dereference "a" in constraint // functions? present way would require a default ctor, i think... }; template struct _CopyConstructibleConcept { void __constraints() { _Tp __a(__b); // require copy constructor _Tp* __ptr _IsUnused = &__a; // require address of operator __const_constraints(__a); } void __const_constraints(const _Tp& __a) { _Tp __c _IsUnused(__a); // require const copy constructor const _Tp* __ptr _IsUnused = &__a; // require const address of operator } _Tp __b; }; // The SGI STL version of Assignable requires copy constructor and operator= template struct _SGIAssignableConcept { void __constraints() { _Tp __b _IsUnused(__a); __a = __a; // require assignment operator __const_constraints(__a); } void __const_constraints(const _Tp& __b) { _Tp __c _IsUnused(__b); __a = __b; // const required for argument to assignment } _Tp __a; }; template struct _ConvertibleConcept { void __constraints() { _To __y _IsUnused = __x; } _From __x; }; // The C++ standard requirements for many concepts talk about return // types that must be "convertible to bool". The problem with this // requirement is that it leaves the door open for evil proxies that // define things like operator|| with strange return types. Two // possible solutions are: // 1) require the return type to be exactly bool // 2) stay with convertible to bool, and also // specify stuff about all the logical operators. // For now we just test for convertible to bool. template void __aux_require_boolean_expr(const _Tp& __t) { bool __x _IsUnused = __t; } // FIXME template struct _EqualityComparableConcept { void __constraints() { __aux_require_boolean_expr(__a == __b); } _Tp __a, __b; }; template struct _LessThanComparableConcept { void __constraints() { __aux_require_boolean_expr(__a < __b); } _Tp __a, __b; }; // This is equivalent to SGI STL's LessThanComparable. template struct _ComparableConcept { void __constraints() { __aux_require_boolean_expr(__a < __b); __aux_require_boolean_expr(__a > __b); __aux_require_boolean_expr(__a <= __b); __aux_require_boolean_expr(__a >= __b); } _Tp __a, __b; }; #define _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(_OP,_NAME) \ template \ struct _NAME { \ void __constraints() { (void)__constraints_(); } \ bool __constraints_() { \ return __a _OP __b; \ } \ _First __a; \ _Second __b; \ } #define _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(_OP,_NAME) \ template \ struct _NAME { \ void __constraints() { (void)__constraints_(); } \ _Ret __constraints_() { \ return __a _OP __b; \ } \ _First __a; \ _Second __b; \ } _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(==, _EqualOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(!=, _NotEqualOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<, _LessThanOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<=, _LessEqualOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>, _GreaterThanOpConcept); _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>=, _GreaterEqualOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(+, _PlusOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(*, _TimesOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(/, _DivideOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(-, _SubtractOpConcept); _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT(%, _ModOpConcept); #undef _GLIBCXX_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT #undef _GLIBCXX_DEFINE_BINARY_OPERATOR_CONSTRAINT //=========================================================================== // Function Object Concepts template struct _GeneratorConcept { void __constraints() { const _Return& __r _IsUnused = __f();// require operator() member function } _Func __f; }; template struct _GeneratorConcept<_Func,void> { void __constraints() { __f(); // require operator() member function } _Func __f; }; template struct _UnaryFunctionConcept { void __constraints() { __r = __f(__arg); // require operator() } _Func __f; _Arg __arg; _Return __r; }; template struct _UnaryFunctionConcept<_Func, void, _Arg> { void __constraints() { __f(__arg); // require operator() } _Func __f; _Arg __arg; }; template struct _BinaryFunctionConcept { void __constraints() { __r = __f(__first, __second); // require operator() } _Func __f; _First __first; _Second __second; _Return __r; }; template struct _BinaryFunctionConcept<_Func, void, _First, _Second> { void __constraints() { __f(__first, __second); // require operator() } _Func __f; _First __first; _Second __second; }; template struct _UnaryPredicateConcept { void __constraints() { __aux_require_boolean_expr(__f(__arg)); // require op() returning bool } _Func __f; _Arg __arg; }; template struct _BinaryPredicateConcept { void __constraints() { __aux_require_boolean_expr(__f(__a, __b)); // require op() returning bool } _Func __f; _First __a; _Second __b; }; // use this when functor is used inside a container class like std::set template struct _Const_BinaryPredicateConcept { void __constraints() { __const_constraints(__f); } void __const_constraints(const _Func& __fun) { __function_requires<_BinaryPredicateConcept<_Func, _First, _Second> >(); // operator() must be a const member function __aux_require_boolean_expr(__fun(__a, __b)); } _Func __f; _First __a; _Second __b; }; //=========================================================================== // Iterator Concepts template struct _TrivialIteratorConcept { void __constraints() { // __function_requires< _DefaultConstructibleConcept<_Tp> >(); __function_requires< _AssignableConcept<_Tp> >(); __function_requires< _EqualityComparableConcept<_Tp> >(); // typedef typename std::iterator_traits<_Tp>::value_type _V; (void)*__i; // require dereference operator } _Tp __i; }; template struct _Mutable_TrivialIteratorConcept { void __constraints() { __function_requires< _TrivialIteratorConcept<_Tp> >(); *__i = *__j; // require dereference and assignment } _Tp __i, __j; }; template struct _InputIteratorConcept { void __constraints() { __function_requires< _TrivialIteratorConcept<_Tp> >(); // require iterator_traits typedef's typedef typename std::iterator_traits<_Tp>::difference_type _Diff; // __function_requires< _SignedIntegerConcept<_Diff> >(); typedef typename std::iterator_traits<_Tp>::reference _Ref; typedef typename std::iterator_traits<_Tp>::pointer _Pt; typedef typename std::iterator_traits<_Tp>::iterator_category _Cat; __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::input_iterator_tag> >(); ++__i; // require preincrement operator __i++; // require postincrement operator } _Tp __i; }; template struct _OutputIteratorConcept { void __constraints() { __function_requires< _AssignableConcept<_Tp> >(); ++__i; // require preincrement operator __i++; // require postincrement operator *__i++ = __t; // require postincrement and assignment } _Tp __i; _ValueT __t; }; template struct _ForwardIteratorConcept { void __constraints() { __function_requires< _InputIteratorConcept<_Tp> >(); __function_requires< _DefaultConstructibleConcept<_Tp> >(); __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::forward_iterator_tag> >(); typedef typename std::iterator_traits<_Tp>::reference _Ref; _Ref __r _IsUnused = *__i; } _Tp __i; }; template struct _Mutable_ForwardIteratorConcept { void __constraints() { __function_requires< _ForwardIteratorConcept<_Tp> >(); *__i++ = *__i; // require postincrement and assignment } _Tp __i; }; template struct _BidirectionalIteratorConcept { void __constraints() { __function_requires< _ForwardIteratorConcept<_Tp> >(); __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::bidirectional_iterator_tag> >(); --__i; // require predecrement operator __i--; // require postdecrement operator } _Tp __i; }; template struct _Mutable_BidirectionalIteratorConcept { void __constraints() { __function_requires< _BidirectionalIteratorConcept<_Tp> >(); __function_requires< _Mutable_ForwardIteratorConcept<_Tp> >(); *__i-- = *__i; // require postdecrement and assignment } _Tp __i; }; template struct _RandomAccessIteratorConcept { void __constraints() { __function_requires< _BidirectionalIteratorConcept<_Tp> >(); __function_requires< _ComparableConcept<_Tp> >(); __function_requires< _ConvertibleConcept< typename std::iterator_traits<_Tp>::iterator_category, std::random_access_iterator_tag> >(); // ??? We don't use _Ref, are we just checking for "referenceability"? typedef typename std::iterator_traits<_Tp>::reference _Ref; __i += __n; // require assignment addition operator __i = __i + __n; __i = __n + __i; // require addition with difference type __i -= __n; // require assignment subtraction op __i = __i - __n; // require subtraction with // difference type __n = __i - __j; // require difference operator (void)__i[__n]; // require element access operator } _Tp __a, __b; _Tp __i, __j; typename std::iterator_traits<_Tp>::difference_type __n; }; template struct _Mutable_RandomAccessIteratorConcept { void __constraints() { __function_requires< _RandomAccessIteratorConcept<_Tp> >(); __function_requires< _Mutable_BidirectionalIteratorConcept<_Tp> >(); __i[__n] = *__i; // require element access and assignment } _Tp __i; typename std::iterator_traits<_Tp>::difference_type __n; }; //=========================================================================== // Container Concepts template struct _ContainerConcept { typedef typename _Container::value_type _Value_type; typedef typename _Container::difference_type _Difference_type; typedef typename _Container::size_type _Size_type; typedef typename _Container::const_reference _Const_reference; typedef typename _Container::const_pointer _Const_pointer; typedef typename _Container::const_iterator _Const_iterator; void __constraints() { __function_requires< _InputIteratorConcept<_Const_iterator> >(); __function_requires< _AssignableConcept<_Container> >(); const _Container __c; __i = __c.begin(); __i = __c.end(); __n = __c.size(); __n = __c.max_size(); __b = __c.empty(); } bool __b; _Const_iterator __i; _Size_type __n; }; template struct _Mutable_ContainerConcept { typedef typename _Container::value_type _Value_type; typedef typename _Container::reference _Reference; typedef typename _Container::iterator _Iterator; typedef typename _Container::pointer _Pointer; void __constraints() { __function_requires< _ContainerConcept<_Container> >(); __function_requires< _AssignableConcept<_Value_type> >(); __function_requires< _InputIteratorConcept<_Iterator> >(); __i = __c.begin(); __i = __c.end(); __c.swap(__c2); } _Iterator __i; _Container __c, __c2; }; template struct _ForwardContainerConcept { void __constraints() { __function_requires< _ContainerConcept<_ForwardContainer> >(); typedef typename _ForwardContainer::const_iterator _Const_iterator; __function_requires< _ForwardIteratorConcept<_Const_iterator> >(); } }; template struct _Mutable_ForwardContainerConcept { void __constraints() { __function_requires< _ForwardContainerConcept<_ForwardContainer> >(); __function_requires< _Mutable_ContainerConcept<_ForwardContainer> >(); typedef typename _ForwardContainer::iterator _Iterator; __function_requires< _Mutable_ForwardIteratorConcept<_Iterator> >(); } }; template struct _ReversibleContainerConcept { typedef typename _ReversibleContainer::const_iterator _Const_iterator; typedef typename _ReversibleContainer::const_reverse_iterator _Const_reverse_iterator; void __constraints() { __function_requires< _ForwardContainerConcept<_ReversibleContainer> >(); __function_requires< _BidirectionalIteratorConcept<_Const_iterator> >(); __function_requires< _BidirectionalIteratorConcept<_Const_reverse_iterator> >(); const _ReversibleContainer __c; _Const_reverse_iterator __i = __c.rbegin(); __i = __c.rend(); } }; template struct _Mutable_ReversibleContainerConcept { typedef typename _ReversibleContainer::iterator _Iterator; typedef typename _ReversibleContainer::reverse_iterator _Reverse_iterator; void __constraints() { __function_requires<_ReversibleContainerConcept<_ReversibleContainer> >(); __function_requires< _Mutable_ForwardContainerConcept<_ReversibleContainer> >(); __function_requires<_Mutable_BidirectionalIteratorConcept<_Iterator> >(); __function_requires< _Mutable_BidirectionalIteratorConcept<_Reverse_iterator> >(); _Reverse_iterator __i = __c.rbegin(); __i = __c.rend(); } _ReversibleContainer __c; }; template struct _RandomAccessContainerConcept { typedef typename _RandomAccessContainer::size_type _Size_type; typedef typename _RandomAccessContainer::const_reference _Const_reference; typedef typename _RandomAccessContainer::const_iterator _Const_iterator; typedef typename _RandomAccessContainer::const_reverse_iterator _Const_reverse_iterator; void __constraints() { __function_requires< _ReversibleContainerConcept<_RandomAccessContainer> >(); __function_requires< _RandomAccessIteratorConcept<_Const_iterator> >(); __function_requires< _RandomAccessIteratorConcept<_Const_reverse_iterator> >(); const _RandomAccessContainer __c; _Const_reference __r _IsUnused = __c[__n]; } _Size_type __n; }; template struct _Mutable_RandomAccessContainerConcept { typedef typename _RandomAccessContainer::size_type _Size_type; typedef typename _RandomAccessContainer::reference _Reference; typedef typename _RandomAccessContainer::iterator _Iterator; typedef typename _RandomAccessContainer::reverse_iterator _Reverse_iterator; void __constraints() { __function_requires< _RandomAccessContainerConcept<_RandomAccessContainer> >(); __function_requires< _Mutable_ReversibleContainerConcept<_RandomAccessContainer> >(); __function_requires< _Mutable_RandomAccessIteratorConcept<_Iterator> >(); __function_requires< _Mutable_RandomAccessIteratorConcept<_Reverse_iterator> >(); _Reference __r _IsUnused = __c[__i]; } _Size_type __i; _RandomAccessContainer __c; }; // A Sequence is inherently mutable template struct _SequenceConcept { typedef typename _Sequence::reference _Reference; typedef typename _Sequence::const_reference _Const_reference; void __constraints() { // Matt Austern's book puts DefaultConstructible here, the C++ // standard places it in Container // function_requires< DefaultConstructible >(); __function_requires< _Mutable_ForwardContainerConcept<_Sequence> >(); __function_requires< _DefaultConstructibleConcept<_Sequence> >(); _Sequence __c _IsUnused(__n, __t), __c2 _IsUnused(__first, __last); __c.insert(__p, __t); __c.insert(__p, __n, __t); __c.insert(__p, __first, __last); __c.erase(__p); __c.erase(__p, __q); _Reference __r _IsUnused = __c.front(); __const_constraints(__c); } void __const_constraints(const _Sequence& __c) { _Const_reference __r _IsUnused = __c.front(); } typename _Sequence::value_type __t; typename _Sequence::size_type __n; typename _Sequence::value_type *__first, *__last; typename _Sequence::iterator __p, __q; }; template struct _FrontInsertionSequenceConcept { void __constraints() { __function_requires< _SequenceConcept<_FrontInsertionSequence> >(); __c.push_front(__t); __c.pop_front(); } _FrontInsertionSequence __c; typename _FrontInsertionSequence::value_type __t; }; template struct _BackInsertionSequenceConcept { typedef typename _BackInsertionSequence::reference _Reference; typedef typename _BackInsertionSequence::const_reference _Const_reference; void __constraints() { __function_requires< _SequenceConcept<_BackInsertionSequence> >(); __c.push_back(__t); __c.pop_back(); _Reference __r _IsUnused = __c.back(); } void __const_constraints(const _BackInsertionSequence& __c) { _Const_reference __r _IsUnused = __c.back(); }; _BackInsertionSequence __c; typename _BackInsertionSequence::value_type __t; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #pragma GCC diagnostic pop #undef _IsUnused #endif // _GLIBCXX_BOOST_CONCEPT_CHECK c++/8/bits/shared_ptr.h000064400000055611151027430570010544 0ustar00// shared_ptr and weak_ptr implementation -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // GCC Note: Based on files from version 1.32.0 of the Boost library. // shared_count.hpp // Copyright (c) 2001, 2002, 2003 Peter Dimov and Multi Media Ltd. // shared_ptr.hpp // Copyright (C) 1998, 1999 Greg Colvin and Beman Dawes. // Copyright (C) 2001, 2002, 2003 Peter Dimov // weak_ptr.hpp // Copyright (C) 2001, 2002, 2003 Peter Dimov // enable_shared_from_this.hpp // Copyright (C) 2002 Peter Dimov // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /** @file * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _SHARED_PTR_H #define _SHARED_PTR_H 1 #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup pointer_abstractions * @{ */ /// 20.7.2.2.11 shared_ptr I/O template inline std::basic_ostream<_Ch, _Tr>& operator<<(std::basic_ostream<_Ch, _Tr>& __os, const __shared_ptr<_Tp, _Lp>& __p) { __os << __p.get(); return __os; } template inline _Del* get_deleter(const __shared_ptr<_Tp, _Lp>& __p) noexcept { #if __cpp_rtti return static_cast<_Del*>(__p._M_get_deleter(typeid(_Del))); #else return 0; #endif } /// 20.7.2.2.10 shared_ptr get_deleter template inline _Del* get_deleter(const shared_ptr<_Tp>& __p) noexcept { #if __cpp_rtti return static_cast<_Del*>(__p._M_get_deleter(typeid(_Del))); #else return 0; #endif } /** * @brief A smart pointer with reference-counted copy semantics. * * The object pointed to is deleted when the last shared_ptr pointing to * it is destroyed or reset. */ template class shared_ptr : public __shared_ptr<_Tp> { template using _Constructible = typename enable_if< is_constructible<__shared_ptr<_Tp>, _Args...>::value >::type; template using _Assignable = typename enable_if< is_assignable<__shared_ptr<_Tp>&, _Arg>::value, shared_ptr& >::type; public: using element_type = typename __shared_ptr<_Tp>::element_type; #if __cplusplus > 201402L # define __cpp_lib_shared_ptr_weak_type 201606 using weak_type = weak_ptr<_Tp>; #endif /** * @brief Construct an empty %shared_ptr. * @post use_count()==0 && get()==0 */ constexpr shared_ptr() noexcept : __shared_ptr<_Tp>() { } shared_ptr(const shared_ptr&) noexcept = default; /** * @brief Construct a %shared_ptr that owns the pointer @a __p. * @param __p A pointer that is convertible to element_type*. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @c delete @a __p is called. */ template> explicit shared_ptr(_Yp* __p) : __shared_ptr<_Tp>(__p) { } /** * @brief Construct a %shared_ptr that owns the pointer @a __p * and the deleter @a __d. * @param __p A pointer. * @param __d A deleter. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw * * __shared_ptr will release __p by calling __d(__p) */ template> shared_ptr(_Yp* __p, _Deleter __d) : __shared_ptr<_Tp>(__p, std::move(__d)) { } /** * @brief Construct a %shared_ptr that owns a null pointer * and the deleter @a __d. * @param __p A null pointer constant. * @param __d A deleter. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw * * The last owner will call __d(__p) */ template shared_ptr(nullptr_t __p, _Deleter __d) : __shared_ptr<_Tp>(__p, std::move(__d)) { } /** * @brief Construct a %shared_ptr that owns the pointer @a __p * and the deleter @a __d. * @param __p A pointer. * @param __d A deleter. * @param __a An allocator. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw _Alloc's copy constructor and destructor must not * throw. * * __shared_ptr will release __p by calling __d(__p) */ template> shared_ptr(_Yp* __p, _Deleter __d, _Alloc __a) : __shared_ptr<_Tp>(__p, std::move(__d), std::move(__a)) { } /** * @brief Construct a %shared_ptr that owns a null pointer * and the deleter @a __d. * @param __p A null pointer constant. * @param __d A deleter. * @param __a An allocator. * @post use_count() == 1 && get() == __p * @throw std::bad_alloc, in which case @a __d(__p) is called. * * Requirements: _Deleter's copy constructor and destructor must * not throw _Alloc's copy constructor and destructor must not * throw. * * The last owner will call __d(__p) */ template shared_ptr(nullptr_t __p, _Deleter __d, _Alloc __a) : __shared_ptr<_Tp>(__p, std::move(__d), std::move(__a)) { } // Aliasing constructor /** * @brief Constructs a %shared_ptr instance that stores @a __p * and shares ownership with @a __r. * @param __r A %shared_ptr. * @param __p A pointer that will remain valid while @a *__r is valid. * @post get() == __p && use_count() == __r.use_count() * * This can be used to construct a @c shared_ptr to a sub-object * of an object managed by an existing @c shared_ptr. * * @code * shared_ptr< pair > pii(new pair()); * shared_ptr pi(pii, &pii->first); * assert(pii.use_count() == 2); * @endcode */ template shared_ptr(const shared_ptr<_Yp>& __r, element_type* __p) noexcept : __shared_ptr<_Tp>(__r, __p) { } /** * @brief If @a __r is empty, constructs an empty %shared_ptr; * otherwise construct a %shared_ptr that shares ownership * with @a __r. * @param __r A %shared_ptr. * @post get() == __r.get() && use_count() == __r.use_count() */ template&>> shared_ptr(const shared_ptr<_Yp>& __r) noexcept : __shared_ptr<_Tp>(__r) { } /** * @brief Move-constructs a %shared_ptr instance from @a __r. * @param __r A %shared_ptr rvalue. * @post *this contains the old value of @a __r, @a __r is empty. */ shared_ptr(shared_ptr&& __r) noexcept : __shared_ptr<_Tp>(std::move(__r)) { } /** * @brief Move-constructs a %shared_ptr instance from @a __r. * @param __r A %shared_ptr rvalue. * @post *this contains the old value of @a __r, @a __r is empty. */ template>> shared_ptr(shared_ptr<_Yp>&& __r) noexcept : __shared_ptr<_Tp>(std::move(__r)) { } /** * @brief Constructs a %shared_ptr that shares ownership with @a __r * and stores a copy of the pointer stored in @a __r. * @param __r A weak_ptr. * @post use_count() == __r.use_count() * @throw bad_weak_ptr when __r.expired(), * in which case the constructor has no effect. */ template&>> explicit shared_ptr(const weak_ptr<_Yp>& __r) : __shared_ptr<_Tp>(__r) { } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template>> shared_ptr(auto_ptr<_Yp>&& __r); #pragma GCC diagnostic pop #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2399. shared_ptr's constructor from unique_ptr should be constrained template>> shared_ptr(unique_ptr<_Yp, _Del>&& __r) : __shared_ptr<_Tp>(std::move(__r)) { } #if __cplusplus <= 201402L && _GLIBCXX_USE_DEPRECATED // This non-standard constructor exists to support conversions that // were possible in C++11 and C++14 but are ill-formed in C++17. // If an exception is thrown this constructor has no effect. template, __sp_array_delete>* = 0> shared_ptr(unique_ptr<_Yp, _Del>&& __r) : __shared_ptr<_Tp>(std::move(__r), __sp_array_delete()) { } #endif /** * @brief Construct an empty %shared_ptr. * @post use_count() == 0 && get() == nullptr */ constexpr shared_ptr(nullptr_t) noexcept : shared_ptr() { } shared_ptr& operator=(const shared_ptr&) noexcept = default; template _Assignable&> operator=(const shared_ptr<_Yp>& __r) noexcept { this->__shared_ptr<_Tp>::operator=(__r); return *this; } #if _GLIBCXX_USE_DEPRECATED #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" template _Assignable> operator=(auto_ptr<_Yp>&& __r) { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } #pragma GCC diagnostic pop #endif shared_ptr& operator=(shared_ptr&& __r) noexcept { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } template _Assignable> operator=(shared_ptr<_Yp>&& __r) noexcept { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } template _Assignable> operator=(unique_ptr<_Yp, _Del>&& __r) { this->__shared_ptr<_Tp>::operator=(std::move(__r)); return *this; } private: // This constructor is non-standard, it is used by allocate_shared. template shared_ptr(_Sp_alloc_shared_tag<_Alloc> __tag, _Args&&... __args) : __shared_ptr<_Tp>(__tag, std::forward<_Args>(__args)...) { } template friend shared_ptr<_Yp> allocate_shared(const _Alloc& __a, _Args&&... __args); // This constructor is non-standard, it is used by weak_ptr::lock(). shared_ptr(const weak_ptr<_Tp>& __r, std::nothrow_t) : __shared_ptr<_Tp>(__r, std::nothrow) { } friend class weak_ptr<_Tp>; }; #if __cpp_deduction_guides >= 201606 template shared_ptr(weak_ptr<_Tp>) -> shared_ptr<_Tp>; template shared_ptr(unique_ptr<_Tp, _Del>) -> shared_ptr<_Tp>; #endif // 20.7.2.2.7 shared_ptr comparisons template inline bool operator==(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return __a.get() == __b.get(); } template inline bool operator==(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !__a; } template inline bool operator==(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !__a; } template inline bool operator!=(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return __a.get() != __b.get(); } template inline bool operator!=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return (bool)__a; } template inline bool operator!=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return (bool)__a; } template inline bool operator<(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { using _Tp_elt = typename shared_ptr<_Tp>::element_type; using _Up_elt = typename shared_ptr<_Up>::element_type; using _Vp = typename common_type<_Tp_elt*, _Up_elt*>::type; return less<_Vp>()(__a.get(), __b.get()); } template inline bool operator<(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { using _Tp_elt = typename shared_ptr<_Tp>::element_type; return less<_Tp_elt*>()(__a.get(), nullptr); } template inline bool operator<(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { using _Tp_elt = typename shared_ptr<_Tp>::element_type; return less<_Tp_elt*>()(nullptr, __a.get()); } template inline bool operator<=(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return !(__b < __a); } template inline bool operator<=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !(nullptr < __a); } template inline bool operator<=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !(__a < nullptr); } template inline bool operator>(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return (__b < __a); } template inline bool operator>(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return nullptr < __a; } template inline bool operator>(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return __a < nullptr; } template inline bool operator>=(const shared_ptr<_Tp>& __a, const shared_ptr<_Up>& __b) noexcept { return !(__a < __b); } template inline bool operator>=(const shared_ptr<_Tp>& __a, nullptr_t) noexcept { return !(__a < nullptr); } template inline bool operator>=(nullptr_t, const shared_ptr<_Tp>& __a) noexcept { return !(nullptr < __a); } template struct less> : public _Sp_less> { }; // 20.7.2.2.8 shared_ptr specialized algorithms. template inline void swap(shared_ptr<_Tp>& __a, shared_ptr<_Tp>& __b) noexcept { __a.swap(__b); } // 20.7.2.2.9 shared_ptr casts. template inline shared_ptr<_Tp> static_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; return _Sp(__r, static_cast(__r.get())); } template inline shared_ptr<_Tp> const_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; return _Sp(__r, const_cast(__r.get())); } template inline shared_ptr<_Tp> dynamic_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; if (auto* __p = dynamic_cast(__r.get())) return _Sp(__r, __p); return _Sp(); } #if __cplusplus > 201402L template inline shared_ptr<_Tp> reinterpret_pointer_cast(const shared_ptr<_Up>& __r) noexcept { using _Sp = shared_ptr<_Tp>; return _Sp(__r, reinterpret_cast(__r.get())); } #endif /** * @brief A smart pointer with weak semantics. * * With forwarding constructors and assignment operators. */ template class weak_ptr : public __weak_ptr<_Tp> { template using _Constructible = typename enable_if< is_constructible<__weak_ptr<_Tp>, _Arg>::value >::type; template using _Assignable = typename enable_if< is_assignable<__weak_ptr<_Tp>&, _Arg>::value, weak_ptr& >::type; public: constexpr weak_ptr() noexcept = default; template&>> weak_ptr(const shared_ptr<_Yp>& __r) noexcept : __weak_ptr<_Tp>(__r) { } weak_ptr(const weak_ptr&) noexcept = default; template&>> weak_ptr(const weak_ptr<_Yp>& __r) noexcept : __weak_ptr<_Tp>(__r) { } weak_ptr(weak_ptr&&) noexcept = default; template>> weak_ptr(weak_ptr<_Yp>&& __r) noexcept : __weak_ptr<_Tp>(std::move(__r)) { } weak_ptr& operator=(const weak_ptr& __r) noexcept = default; template _Assignable&> operator=(const weak_ptr<_Yp>& __r) noexcept { this->__weak_ptr<_Tp>::operator=(__r); return *this; } template _Assignable&> operator=(const shared_ptr<_Yp>& __r) noexcept { this->__weak_ptr<_Tp>::operator=(__r); return *this; } weak_ptr& operator=(weak_ptr&& __r) noexcept = default; template _Assignable> operator=(weak_ptr<_Yp>&& __r) noexcept { this->__weak_ptr<_Tp>::operator=(std::move(__r)); return *this; } shared_ptr<_Tp> lock() const noexcept { return shared_ptr<_Tp>(*this, std::nothrow); } }; #if __cpp_deduction_guides >= 201606 template weak_ptr(shared_ptr<_Tp>) -> weak_ptr<_Tp>; #endif // 20.7.2.3.6 weak_ptr specialized algorithms. template inline void swap(weak_ptr<_Tp>& __a, weak_ptr<_Tp>& __b) noexcept { __a.swap(__b); } /// Primary template owner_less template struct owner_less; /// Void specialization of owner_less template<> struct owner_less : _Sp_owner_less { }; /// Partial specialization of owner_less for shared_ptr. template struct owner_less> : public _Sp_owner_less, weak_ptr<_Tp>> { }; /// Partial specialization of owner_less for weak_ptr. template struct owner_less> : public _Sp_owner_less, shared_ptr<_Tp>> { }; /** * @brief Base class allowing use of member function shared_from_this. */ template class enable_shared_from_this { protected: constexpr enable_shared_from_this() noexcept { } enable_shared_from_this(const enable_shared_from_this&) noexcept { } enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept { return *this; } ~enable_shared_from_this() { } public: shared_ptr<_Tp> shared_from_this() { return shared_ptr<_Tp>(this->_M_weak_this); } shared_ptr shared_from_this() const { return shared_ptr(this->_M_weak_this); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 #define __cpp_lib_enable_shared_from_this 201603 weak_ptr<_Tp> weak_from_this() noexcept { return this->_M_weak_this; } weak_ptr weak_from_this() const noexcept { return this->_M_weak_this; } #endif private: template void _M_weak_assign(_Tp1* __p, const __shared_count<>& __n) const noexcept { _M_weak_this._M_assign(__p, __n); } // Found by ADL when this is an associated class. friend const enable_shared_from_this* __enable_shared_from_this_base(const __shared_count<>&, const enable_shared_from_this* __p) { return __p; } template friend class __shared_ptr; mutable weak_ptr<_Tp> _M_weak_this; }; /** * @brief Create an object that is owned by a shared_ptr. * @param __a An allocator. * @param __args Arguments for the @a _Tp object's constructor. * @return A shared_ptr that owns the newly created object. * @throw An exception thrown from @a _Alloc::allocate or from the * constructor of @a _Tp. * * A copy of @a __a will be used to allocate memory for the shared_ptr * and the new object. */ template inline shared_ptr<_Tp> allocate_shared(const _Alloc& __a, _Args&&... __args) { static_assert(!is_array<_Tp>::value, "make_shared not supported"); return shared_ptr<_Tp>(_Sp_alloc_shared_tag<_Alloc>{__a}, std::forward<_Args>(__args)...); } /** * @brief Create an object that is owned by a shared_ptr. * @param __args Arguments for the @a _Tp object's constructor. * @return A shared_ptr that owns the newly created object. * @throw std::bad_alloc, or an exception thrown from the * constructor of @a _Tp. */ template inline shared_ptr<_Tp> make_shared(_Args&&... __args) { typedef typename std::remove_cv<_Tp>::type _Tp_nc; return std::allocate_shared<_Tp>(std::allocator<_Tp_nc>(), std::forward<_Args>(__args)...); } /// std::hash specialization for shared_ptr. template struct hash> : public __hash_base> { size_t operator()(const shared_ptr<_Tp>& __s) const noexcept { return std::hash::element_type*>()(__s.get()); } }; // @} group pointer_abstractions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _SHARED_PTR_H c++/8/bits/indirect_array.h000064400000017265151027430570011413 0ustar00// The template and inlines for the -*- C++ -*- indirect_array class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/indirect_array.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _INDIRECT_ARRAY_H #define _INDIRECT_ARRAY_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Reference to arbitrary subset of an array. * * An indirect_array is a reference to the actual elements of an array * specified by an ordered array of indices. The way to get an * indirect_array is to call operator[](valarray) on a valarray. * The returned indirect_array then permits carrying operations out on the * referenced subset of elements in the original valarray. * * For example, if an indirect_array is obtained using the array (4,2,0) as * an argument, and then assigned to an array containing (1,2,3), then the * underlying array will have array[0]==3, array[2]==2, and array[4]==1. * * @param Tp Element type. */ template class indirect_array { public: typedef _Tp value_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 253. valarray helper functions are almost entirely useless /// Copy constructor. Both slices refer to the same underlying array. indirect_array(const indirect_array&); /// Assignment operator. Assigns elements to corresponding elements /// of @a a. indirect_array& operator=(const indirect_array&); /// Assign slice elements to corresponding elements of @a v. void operator=(const valarray<_Tp>&) const; /// Multiply slice elements by corresponding elements of @a v. void operator*=(const valarray<_Tp>&) const; /// Divide slice elements by corresponding elements of @a v. void operator/=(const valarray<_Tp>&) const; /// Modulo slice elements by corresponding elements of @a v. void operator%=(const valarray<_Tp>&) const; /// Add corresponding elements of @a v to slice elements. void operator+=(const valarray<_Tp>&) const; /// Subtract corresponding elements of @a v from slice elements. void operator-=(const valarray<_Tp>&) const; /// Logical xor slice elements with corresponding elements of @a v. void operator^=(const valarray<_Tp>&) const; /// Logical and slice elements with corresponding elements of @a v. void operator&=(const valarray<_Tp>&) const; /// Logical or slice elements with corresponding elements of @a v. void operator|=(const valarray<_Tp>&) const; /// Left shift slice elements by corresponding elements of @a v. void operator<<=(const valarray<_Tp>&) const; /// Right shift slice elements by corresponding elements of @a v. void operator>>=(const valarray<_Tp>&) const; /// Assign all slice elements to @a t. void operator= (const _Tp&) const; // ~indirect_array(); template void operator=(const _Expr<_Dom, _Tp>&) const; template void operator*=(const _Expr<_Dom, _Tp>&) const; template void operator/=(const _Expr<_Dom, _Tp>&) const; template void operator%=(const _Expr<_Dom, _Tp>&) const; template void operator+=(const _Expr<_Dom, _Tp>&) const; template void operator-=(const _Expr<_Dom, _Tp>&) const; template void operator^=(const _Expr<_Dom, _Tp>&) const; template void operator&=(const _Expr<_Dom, _Tp>&) const; template void operator|=(const _Expr<_Dom, _Tp>&) const; template void operator<<=(const _Expr<_Dom, _Tp>&) const; template void operator>>=(const _Expr<_Dom, _Tp>&) const; private: /// Copy constructor. Both slices refer to the same underlying array. indirect_array(_Array<_Tp>, size_t, _Array); friend class valarray<_Tp>; friend class gslice_array<_Tp>; const size_t _M_sz; const _Array _M_index; const _Array<_Tp> _M_array; // not implemented indirect_array(); }; template inline indirect_array<_Tp>::indirect_array(const indirect_array<_Tp>& __a) : _M_sz(__a._M_sz), _M_index(__a._M_index), _M_array(__a._M_array) {} template inline indirect_array<_Tp>::indirect_array(_Array<_Tp> __a, size_t __s, _Array __i) : _M_sz(__s), _M_index(__i), _M_array(__a) {} template inline indirect_array<_Tp>& indirect_array<_Tp>::operator=(const indirect_array<_Tp>& __a) { std::__valarray_copy(__a._M_array, _M_sz, __a._M_index, _M_array, _M_index); return *this; } template inline void indirect_array<_Tp>::operator=(const _Tp& __t) const { std::__valarray_fill(_M_array, _M_index, _M_sz, __t); } template inline void indirect_array<_Tp>::operator=(const valarray<_Tp>& __v) const { std::__valarray_copy(_Array<_Tp>(__v), _M_sz, _M_array, _M_index); } template template inline void indirect_array<_Tp>::operator=(const _Expr<_Dom, _Tp>& __e) const { std::__valarray_copy(__e, _M_sz, _M_array, _M_index); } #undef _DEFINE_VALARRAY_OPERATOR #define _DEFINE_VALARRAY_OPERATOR(_Op, _Name) \ template \ inline void \ indirect_array<_Tp>::operator _Op##=(const valarray<_Tp>& __v) const\ { \ _Array_augmented_##_Name(_M_array, _M_index, _Array<_Tp>(__v), _M_sz); \ } \ \ template \ template \ inline void \ indirect_array<_Tp>::operator _Op##=(const _Expr<_Dom,_Tp>& __e) const\ { \ _Array_augmented_##_Name(_M_array, _M_index, __e, _M_sz); \ } _DEFINE_VALARRAY_OPERATOR(*, __multiplies) _DEFINE_VALARRAY_OPERATOR(/, __divides) _DEFINE_VALARRAY_OPERATOR(%, __modulus) _DEFINE_VALARRAY_OPERATOR(+, __plus) _DEFINE_VALARRAY_OPERATOR(-, __minus) _DEFINE_VALARRAY_OPERATOR(^, __bitwise_xor) _DEFINE_VALARRAY_OPERATOR(&, __bitwise_and) _DEFINE_VALARRAY_OPERATOR(|, __bitwise_or) _DEFINE_VALARRAY_OPERATOR(<<, __shift_left) _DEFINE_VALARRAY_OPERATOR(>>, __shift_right) #undef _DEFINE_VALARRAY_OPERATOR // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _INDIRECT_ARRAY_H */ c++/8/bits/forward_list.tcc000064400000031561151027430570011430 0ustar00// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/forward_list.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{forward_list} */ #ifndef _FORWARD_LIST_TCC #define _FORWARD_LIST_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template _Fwd_list_base<_Tp, _Alloc>:: _Fwd_list_base(_Fwd_list_base&& __lst, _Node_alloc_type&& __a) : _M_impl(std::move(__a)) { if (__lst._M_get_Node_allocator() == _M_get_Node_allocator()) this->_M_impl._M_head = std::move(__lst._M_impl._M_head); } template template _Fwd_list_node_base* _Fwd_list_base<_Tp, _Alloc>:: _M_insert_after(const_iterator __pos, _Args&&... __args) { _Fwd_list_node_base* __to = const_cast<_Fwd_list_node_base*>(__pos._M_node); _Node* __thing = _M_create_node(std::forward<_Args>(__args)...); __thing->_M_next = __to->_M_next; __to->_M_next = __thing; return __to->_M_next; } template _Fwd_list_node_base* _Fwd_list_base<_Tp, _Alloc>:: _M_erase_after(_Fwd_list_node_base* __pos) { _Node* __curr = static_cast<_Node*>(__pos->_M_next); __pos->_M_next = __curr->_M_next; _Node_alloc_traits::destroy(_M_get_Node_allocator(), __curr->_M_valptr()); __curr->~_Node(); _M_put_node(__curr); return __pos->_M_next; } template _Fwd_list_node_base* _Fwd_list_base<_Tp, _Alloc>:: _M_erase_after(_Fwd_list_node_base* __pos, _Fwd_list_node_base* __last) { _Node* __curr = static_cast<_Node*>(__pos->_M_next); while (__curr != __last) { _Node* __temp = __curr; __curr = static_cast<_Node*>(__curr->_M_next); _Node_alloc_traits::destroy(_M_get_Node_allocator(), __temp->_M_valptr()); __temp->~_Node(); _M_put_node(__temp); } __pos->_M_next = __last; return __last; } // Called by the range constructor to implement [23.3.4.2]/9 template template void forward_list<_Tp, _Alloc>:: _M_range_initialize(_InputIterator __first, _InputIterator __last) { _Node_base* __to = &this->_M_impl._M_head; for (; __first != __last; ++__first) { __to->_M_next = this->_M_create_node(*__first); __to = __to->_M_next; } } // Called by forward_list(n,v,a). template void forward_list<_Tp, _Alloc>:: _M_fill_initialize(size_type __n, const value_type& __value) { _Node_base* __to = &this->_M_impl._M_head; for (; __n; --__n) { __to->_M_next = this->_M_create_node(__value); __to = __to->_M_next; } } template void forward_list<_Tp, _Alloc>:: _M_default_initialize(size_type __n) { _Node_base* __to = &this->_M_impl._M_head; for (; __n; --__n) { __to->_M_next = this->_M_create_node(); __to = __to->_M_next; } } template forward_list<_Tp, _Alloc>& forward_list<_Tp, _Alloc>:: operator=(const forward_list& __list) { if (std::__addressof(__list) != this) { if (_Node_alloc_traits::_S_propagate_on_copy_assign()) { auto& __this_alloc = this->_M_get_Node_allocator(); auto& __that_alloc = __list._M_get_Node_allocator(); if (!_Node_alloc_traits::_S_always_equal() && __this_alloc != __that_alloc) { // replacement allocator cannot free existing storage clear(); } std::__alloc_on_copy(__this_alloc, __that_alloc); } assign(__list.cbegin(), __list.cend()); } return *this; } template void forward_list<_Tp, _Alloc>:: _M_default_insert_after(const_iterator __pos, size_type __n) { const_iterator __saved_pos = __pos; __try { for (; __n; --__n) __pos = emplace_after(__pos); } __catch(...) { erase_after(__saved_pos, ++__pos); __throw_exception_again; } } template void forward_list<_Tp, _Alloc>:: resize(size_type __sz) { iterator __k = before_begin(); size_type __len = 0; while (__k._M_next() != end() && __len < __sz) { ++__k; ++__len; } if (__len == __sz) erase_after(__k, end()); else _M_default_insert_after(__k, __sz - __len); } template void forward_list<_Tp, _Alloc>:: resize(size_type __sz, const value_type& __val) { iterator __k = before_begin(); size_type __len = 0; while (__k._M_next() != end() && __len < __sz) { ++__k; ++__len; } if (__len == __sz) erase_after(__k, end()); else insert_after(__k, __sz - __len, __val); } template typename forward_list<_Tp, _Alloc>::iterator forward_list<_Tp, _Alloc>:: _M_splice_after(const_iterator __pos, const_iterator __before, const_iterator __last) { _Node_base* __tmp = const_cast<_Node_base*>(__pos._M_node); _Node_base* __b = const_cast<_Node_base*>(__before._M_node); _Node_base* __end = __b; while (__end && __end->_M_next != __last._M_node) __end = __end->_M_next; if (__b != __end) return iterator(__tmp->_M_transfer_after(__b, __end)); else return iterator(__tmp); } template void forward_list<_Tp, _Alloc>:: splice_after(const_iterator __pos, forward_list&&, const_iterator __i) noexcept { const_iterator __j = __i; ++__j; if (__pos == __i || __pos == __j) return; _Node_base* __tmp = const_cast<_Node_base*>(__pos._M_node); __tmp->_M_transfer_after(const_cast<_Node_base*>(__i._M_node), const_cast<_Node_base*>(__j._M_node)); } template typename forward_list<_Tp, _Alloc>::iterator forward_list<_Tp, _Alloc>:: insert_after(const_iterator __pos, size_type __n, const _Tp& __val) { if (__n) { forward_list __tmp(__n, __val, get_allocator()); return _M_splice_after(__pos, __tmp.before_begin(), __tmp.end()); } else return iterator(const_cast<_Node_base*>(__pos._M_node)); } template template typename forward_list<_Tp, _Alloc>::iterator forward_list<_Tp, _Alloc>:: insert_after(const_iterator __pos, _InputIterator __first, _InputIterator __last) { forward_list __tmp(__first, __last, get_allocator()); if (!__tmp.empty()) return _M_splice_after(__pos, __tmp.before_begin(), __tmp.end()); else return iterator(const_cast<_Node_base*>(__pos._M_node)); } template void forward_list<_Tp, _Alloc>:: remove(const _Tp& __val) { _Node_base* __curr = &this->_M_impl._M_head; _Node_base* __extra = nullptr; while (_Node* __tmp = static_cast<_Node*>(__curr->_M_next)) { if (*__tmp->_M_valptr() == __val) { if (__tmp->_M_valptr() != std::__addressof(__val)) { this->_M_erase_after(__curr); continue; } else __extra = __curr; } __curr = __curr->_M_next; } if (__extra) this->_M_erase_after(__extra); } template template void forward_list<_Tp, _Alloc>:: remove_if(_Pred __pred) { _Node_base* __curr = &this->_M_impl._M_head; while (_Node* __tmp = static_cast<_Node*>(__curr->_M_next)) { if (__pred(*__tmp->_M_valptr())) this->_M_erase_after(__curr); else __curr = __curr->_M_next; } } template template void forward_list<_Tp, _Alloc>:: unique(_BinPred __binary_pred) { iterator __first = begin(); iterator __last = end(); if (__first == __last) return; iterator __next = __first; while (++__next != __last) { if (__binary_pred(*__first, *__next)) erase_after(__first); else __first = __next; __next = __first; } } template template void forward_list<_Tp, _Alloc>:: merge(forward_list&& __list, _Comp __comp) { _Node_base* __node = &this->_M_impl._M_head; while (__node->_M_next && __list._M_impl._M_head._M_next) { if (__comp(*static_cast<_Node*> (__list._M_impl._M_head._M_next)->_M_valptr(), *static_cast<_Node*> (__node->_M_next)->_M_valptr())) __node->_M_transfer_after(&__list._M_impl._M_head, __list._M_impl._M_head._M_next); __node = __node->_M_next; } if (__list._M_impl._M_head._M_next) *__node = std::move(__list._M_impl._M_head); } template bool operator==(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { // We don't have size() so we need to walk through both lists // making sure both iterators are valid. auto __ix = __lx.cbegin(); auto __iy = __ly.cbegin(); while (__ix != __lx.cend() && __iy != __ly.cend()) { if (!(*__ix == *__iy)) return false; ++__ix; ++__iy; } if (__ix == __lx.cend() && __iy == __ly.cend()) return true; else return false; } template template void forward_list<_Tp, _Alloc>:: sort(_Comp __comp) { // If `next' is nullptr, return immediately. _Node* __list = static_cast<_Node*>(this->_M_impl._M_head._M_next); if (!__list) return; unsigned long __insize = 1; while (1) { _Node* __p = __list; __list = nullptr; _Node* __tail = nullptr; // Count number of merges we do in this pass. unsigned long __nmerges = 0; while (__p) { ++__nmerges; // There exists a merge to be done. // Step `insize' places along from p. _Node* __q = __p; unsigned long __psize = 0; for (unsigned long __i = 0; __i < __insize; ++__i) { ++__psize; __q = static_cast<_Node*>(__q->_M_next); if (!__q) break; } // If q hasn't fallen off end, we have two lists to merge. unsigned long __qsize = __insize; // Now we have two lists; merge them. while (__psize > 0 || (__qsize > 0 && __q)) { // Decide whether next node of merge comes from p or q. _Node* __e; if (__psize == 0) { // p is empty; e must come from q. __e = __q; __q = static_cast<_Node*>(__q->_M_next); --__qsize; } else if (__qsize == 0 || !__q) { // q is empty; e must come from p. __e = __p; __p = static_cast<_Node*>(__p->_M_next); --__psize; } else if (!__comp(*__q->_M_valptr(), *__p->_M_valptr())) { // First node of q is not lower; e must come from p. __e = __p; __p = static_cast<_Node*>(__p->_M_next); --__psize; } else { // First node of q is lower; e must come from q. __e = __q; __q = static_cast<_Node*>(__q->_M_next); --__qsize; } // Add the next node to the merged list. if (__tail) __tail->_M_next = __e; else __list = __e; __tail = __e; } // Now p has stepped `insize' places along, and q has too. __p = __q; } __tail->_M_next = nullptr; // If we have done only one merge, we're finished. // Allow for nmerges == 0, the empty list case. if (__nmerges <= 1) { this->_M_impl._M_head._M_next = __list; return; } // Otherwise repeat, merging lists twice the size. __insize *= 2; } } _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _FORWARD_LIST_TCC */ c++/8/bits/deque.tcc000064400000102512151027430570010027 0ustar00// Deque implementation (out of line) -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/deque.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{deque} */ #ifndef _DEQUE_TCC #define _DEQUE_TCC 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_default_initialize() { _Map_pointer __cur; __try { for (__cur = this->_M_impl._M_start._M_node; __cur < this->_M_impl._M_finish._M_node; ++__cur) std::__uninitialized_default_a(*__cur, *__cur + _S_buffer_size(), _M_get_Tp_allocator()); std::__uninitialized_default_a(this->_M_impl._M_finish._M_first, this->_M_impl._M_finish._M_cur, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(this->_M_impl._M_start, iterator(*__cur, __cur), _M_get_Tp_allocator()); __throw_exception_again; } } #endif template deque<_Tp, _Alloc>& deque<_Tp, _Alloc>:: operator=(const deque& __x) { if (&__x != this) { #if __cplusplus >= 201103L if (_Alloc_traits::_S_propagate_on_copy_assign()) { if (!_Alloc_traits::_S_always_equal() && _M_get_Tp_allocator() != __x._M_get_Tp_allocator()) { // Replacement allocator cannot free existing storage, // so deallocate everything and take copy of __x's data. _M_replace_map(__x, __x.get_allocator()); std::__alloc_on_copy(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); return *this; } std::__alloc_on_copy(_M_get_Tp_allocator(), __x._M_get_Tp_allocator()); } #endif const size_type __len = size(); if (__len >= __x.size()) _M_erase_at_end(std::copy(__x.begin(), __x.end(), this->_M_impl._M_start)); else { const_iterator __mid = __x.begin() + difference_type(__len); std::copy(__x.begin(), __mid, this->_M_impl._M_start); _M_range_insert_aux(this->_M_impl._M_finish, __mid, __x.end(), std::random_access_iterator_tag()); } } return *this; } #if __cplusplus >= 201103L template template #if __cplusplus > 201402L typename deque<_Tp, _Alloc>::reference #else void #endif deque<_Tp, _Alloc>:: emplace_front(_Args&&... __args) { if (this->_M_impl._M_start._M_cur != this->_M_impl._M_start._M_first) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_start._M_cur - 1, std::forward<_Args>(__args)...); --this->_M_impl._M_start._M_cur; } else _M_push_front_aux(std::forward<_Args>(__args)...); #if __cplusplus > 201402L return front(); #endif } template template #if __cplusplus > 201402L typename deque<_Tp, _Alloc>::reference #else void #endif deque<_Tp, _Alloc>:: emplace_back(_Args&&... __args) { if (this->_M_impl._M_finish._M_cur != this->_M_impl._M_finish._M_last - 1) { _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish._M_cur, std::forward<_Args>(__args)...); ++this->_M_impl._M_finish._M_cur; } else _M_push_back_aux(std::forward<_Args>(__args)...); #if __cplusplus > 201402L return back(); #endif } #endif #if __cplusplus >= 201103L template template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: emplace(const_iterator __position, _Args&&... __args) { if (__position._M_cur == this->_M_impl._M_start._M_cur) { emplace_front(std::forward<_Args>(__args)...); return this->_M_impl._M_start; } else if (__position._M_cur == this->_M_impl._M_finish._M_cur) { emplace_back(std::forward<_Args>(__args)...); iterator __tmp = this->_M_impl._M_finish; --__tmp; return __tmp; } else return _M_insert_aux(__position._M_const_cast(), std::forward<_Args>(__args)...); } #endif template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { if (__position._M_cur == this->_M_impl._M_start._M_cur) { push_front(__x); return this->_M_impl._M_start; } else if (__position._M_cur == this->_M_impl._M_finish._M_cur) { push_back(__x); iterator __tmp = this->_M_impl._M_finish; --__tmp; return __tmp; } else return _M_insert_aux(__position._M_const_cast(), __x); } template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_erase(iterator __position) { iterator __next = __position; ++__next; const difference_type __index = __position - begin(); if (static_cast(__index) < (size() >> 1)) { if (__position != begin()) _GLIBCXX_MOVE_BACKWARD3(begin(), __position, __next); pop_front(); } else { if (__next != end()) _GLIBCXX_MOVE3(__next, end(), __position); pop_back(); } return begin() + __index; } template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_erase(iterator __first, iterator __last) { if (__first == __last) return __first; else if (__first == begin() && __last == end()) { clear(); return end(); } else { const difference_type __n = __last - __first; const difference_type __elems_before = __first - begin(); if (static_cast(__elems_before) <= (size() - __n) / 2) { if (__first != begin()) _GLIBCXX_MOVE_BACKWARD3(begin(), __first, __last); _M_erase_at_begin(begin() + __n); } else { if (__last != end()) _GLIBCXX_MOVE3(__last, end(), __first); _M_erase_at_end(end() - __n); } return begin() + __elems_before; } } template template void deque<_Tp, _Alloc>:: _M_assign_aux(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { iterator __cur = begin(); for (; __first != __last && __cur != end(); ++__cur, ++__first) *__cur = *__first; if (__first == __last) _M_erase_at_end(__cur); else _M_range_insert_aux(end(), __first, __last, std::__iterator_category(__first)); } template void deque<_Tp, _Alloc>:: _M_fill_insert(iterator __pos, size_type __n, const value_type& __x) { if (__pos._M_cur == this->_M_impl._M_start._M_cur) { iterator __new_start = _M_reserve_elements_at_front(__n); __try { std::__uninitialized_fill_a(__new_start, this->_M_impl._M_start, __x, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else if (__pos._M_cur == this->_M_impl._M_finish._M_cur) { iterator __new_finish = _M_reserve_elements_at_back(__n); __try { std::__uninitialized_fill_a(this->_M_impl._M_finish, __new_finish, __x, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } else _M_insert_aux(__pos, __n, __x); } #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_default_append(size_type __n) { if (__n) { iterator __new_finish = _M_reserve_elements_at_back(__n); __try { std::__uninitialized_default_a(this->_M_impl._M_finish, __new_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } } template bool deque<_Tp, _Alloc>:: _M_shrink_to_fit() { const difference_type __front_capacity = (this->_M_impl._M_start._M_cur - this->_M_impl._M_start._M_first); if (__front_capacity == 0) return false; const difference_type __back_capacity = (this->_M_impl._M_finish._M_last - this->_M_impl._M_finish._M_cur); if (__front_capacity + __back_capacity < _S_buffer_size()) return false; return std::__shrink_to_fit_aux::_S_do_it(*this); } #endif template void deque<_Tp, _Alloc>:: _M_fill_initialize(const value_type& __value) { _Map_pointer __cur; __try { for (__cur = this->_M_impl._M_start._M_node; __cur < this->_M_impl._M_finish._M_node; ++__cur) std::__uninitialized_fill_a(*__cur, *__cur + _S_buffer_size(), __value, _M_get_Tp_allocator()); std::__uninitialized_fill_a(this->_M_impl._M_finish._M_first, this->_M_impl._M_finish._M_cur, __value, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(this->_M_impl._M_start, iterator(*__cur, __cur), _M_get_Tp_allocator()); __throw_exception_again; } } template template void deque<_Tp, _Alloc>:: _M_range_initialize(_InputIterator __first, _InputIterator __last, std::input_iterator_tag) { this->_M_initialize_map(0); __try { for (; __first != __last; ++__first) #if __cplusplus >= 201103L emplace_back(*__first); #else push_back(*__first); #endif } __catch(...) { clear(); __throw_exception_again; } } template template void deque<_Tp, _Alloc>:: _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); this->_M_initialize_map(__n); _Map_pointer __cur_node; __try { for (__cur_node = this->_M_impl._M_start._M_node; __cur_node < this->_M_impl._M_finish._M_node; ++__cur_node) { _ForwardIterator __mid = __first; std::advance(__mid, _S_buffer_size()); std::__uninitialized_copy_a(__first, __mid, *__cur_node, _M_get_Tp_allocator()); __first = __mid; } std::__uninitialized_copy_a(__first, __last, this->_M_impl._M_finish._M_first, _M_get_Tp_allocator()); } __catch(...) { std::_Destroy(this->_M_impl._M_start, iterator(*__cur_node, __cur_node), _M_get_Tp_allocator()); __throw_exception_again; } } // Called only if _M_impl._M_finish._M_cur == _M_impl._M_finish._M_last - 1. template #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_push_back_aux(_Args&&... __args) #else void deque<_Tp, _Alloc>:: _M_push_back_aux(const value_type& __t) #endif { _M_reserve_map_at_back(); *(this->_M_impl._M_finish._M_node + 1) = this->_M_allocate_node(); __try { #if __cplusplus >= 201103L _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish._M_cur, std::forward<_Args>(__args)...); #else this->_M_impl.construct(this->_M_impl._M_finish._M_cur, __t); #endif this->_M_impl._M_finish._M_set_node(this->_M_impl._M_finish._M_node + 1); this->_M_impl._M_finish._M_cur = this->_M_impl._M_finish._M_first; } __catch(...) { _M_deallocate_node(*(this->_M_impl._M_finish._M_node + 1)); __throw_exception_again; } } // Called only if _M_impl._M_start._M_cur == _M_impl._M_start._M_first. template #if __cplusplus >= 201103L template void deque<_Tp, _Alloc>:: _M_push_front_aux(_Args&&... __args) #else void deque<_Tp, _Alloc>:: _M_push_front_aux(const value_type& __t) #endif { _M_reserve_map_at_front(); *(this->_M_impl._M_start._M_node - 1) = this->_M_allocate_node(); __try { this->_M_impl._M_start._M_set_node(this->_M_impl._M_start._M_node - 1); this->_M_impl._M_start._M_cur = this->_M_impl._M_start._M_last - 1; #if __cplusplus >= 201103L _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_start._M_cur, std::forward<_Args>(__args)...); #else this->_M_impl.construct(this->_M_impl._M_start._M_cur, __t); #endif } __catch(...) { ++this->_M_impl._M_start; _M_deallocate_node(*(this->_M_impl._M_start._M_node - 1)); __throw_exception_again; } } // Called only if _M_impl._M_finish._M_cur == _M_impl._M_finish._M_first. template void deque<_Tp, _Alloc>:: _M_pop_back_aux() { _M_deallocate_node(this->_M_impl._M_finish._M_first); this->_M_impl._M_finish._M_set_node(this->_M_impl._M_finish._M_node - 1); this->_M_impl._M_finish._M_cur = this->_M_impl._M_finish._M_last - 1; _Alloc_traits::destroy(_M_get_Tp_allocator(), this->_M_impl._M_finish._M_cur); } // Called only if _M_impl._M_start._M_cur == _M_impl._M_start._M_last - 1. // Note that if the deque has at least one element (a precondition for this // member function), and if // _M_impl._M_start._M_cur == _M_impl._M_start._M_last, // then the deque must have at least two nodes. template void deque<_Tp, _Alloc>:: _M_pop_front_aux() { _Alloc_traits::destroy(_M_get_Tp_allocator(), this->_M_impl._M_start._M_cur); _M_deallocate_node(this->_M_impl._M_start._M_first); this->_M_impl._M_start._M_set_node(this->_M_impl._M_start._M_node + 1); this->_M_impl._M_start._M_cur = this->_M_impl._M_start._M_first; } template template void deque<_Tp, _Alloc>:: _M_range_insert_aux(iterator __pos, _InputIterator __first, _InputIterator __last, std::input_iterator_tag) { std::copy(__first, __last, std::inserter(*this, __pos)); } template template void deque<_Tp, _Alloc>:: _M_range_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { const size_type __n = std::distance(__first, __last); if (__pos._M_cur == this->_M_impl._M_start._M_cur) { iterator __new_start = _M_reserve_elements_at_front(__n); __try { std::__uninitialized_copy_a(__first, __last, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else if (__pos._M_cur == this->_M_impl._M_finish._M_cur) { iterator __new_finish = _M_reserve_elements_at_back(__n); __try { std::__uninitialized_copy_a(__first, __last, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } else _M_insert_aux(__pos, __first, __last, __n); } template #if __cplusplus >= 201103L template typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, _Args&&... __args) { value_type __x_copy(std::forward<_Args>(__args)...); // XXX copy #else typename deque<_Tp, _Alloc>::iterator deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, const value_type& __x) { value_type __x_copy = __x; // XXX copy #endif difference_type __index = __pos - this->_M_impl._M_start; if (static_cast(__index) < size() / 2) { push_front(_GLIBCXX_MOVE(front())); iterator __front1 = this->_M_impl._M_start; ++__front1; iterator __front2 = __front1; ++__front2; __pos = this->_M_impl._M_start + __index; iterator __pos1 = __pos; ++__pos1; _GLIBCXX_MOVE3(__front2, __pos1, __front1); } else { push_back(_GLIBCXX_MOVE(back())); iterator __back1 = this->_M_impl._M_finish; --__back1; iterator __back2 = __back1; --__back2; __pos = this->_M_impl._M_start + __index; _GLIBCXX_MOVE_BACKWARD3(__pos, __back2, __back1); } *__pos = _GLIBCXX_MOVE(__x_copy); return __pos; } template void deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, size_type __n, const value_type& __x) { const difference_type __elems_before = __pos - this->_M_impl._M_start; const size_type __length = this->size(); value_type __x_copy = __x; if (__elems_before < difference_type(__length / 2)) { iterator __new_start = _M_reserve_elements_at_front(__n); iterator __old_start = this->_M_impl._M_start; __pos = this->_M_impl._M_start + __elems_before; __try { if (__elems_before >= difference_type(__n)) { iterator __start_n = (this->_M_impl._M_start + difference_type(__n)); std::__uninitialized_move_a(this->_M_impl._M_start, __start_n, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; _GLIBCXX_MOVE3(__start_n, __pos, __old_start); std::fill(__pos - difference_type(__n), __pos, __x_copy); } else { std::__uninitialized_move_fill(this->_M_impl._M_start, __pos, __new_start, this->_M_impl._M_start, __x_copy, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; std::fill(__old_start, __pos, __x_copy); } } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else { iterator __new_finish = _M_reserve_elements_at_back(__n); iterator __old_finish = this->_M_impl._M_finish; const difference_type __elems_after = difference_type(__length) - __elems_before; __pos = this->_M_impl._M_finish - __elems_after; __try { if (__elems_after > difference_type(__n)) { iterator __finish_n = (this->_M_impl._M_finish - difference_type(__n)); std::__uninitialized_move_a(__finish_n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; _GLIBCXX_MOVE_BACKWARD3(__pos, __finish_n, __old_finish); std::fill(__pos, __pos + difference_type(__n), __x_copy); } else { std::__uninitialized_fill_move(this->_M_impl._M_finish, __pos + difference_type(__n), __x_copy, __pos, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; std::fill(__pos, __old_finish, __x_copy); } } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } } template template void deque<_Tp, _Alloc>:: _M_insert_aux(iterator __pos, _ForwardIterator __first, _ForwardIterator __last, size_type __n) { const difference_type __elemsbefore = __pos - this->_M_impl._M_start; const size_type __length = size(); if (static_cast(__elemsbefore) < __length / 2) { iterator __new_start = _M_reserve_elements_at_front(__n); iterator __old_start = this->_M_impl._M_start; __pos = this->_M_impl._M_start + __elemsbefore; __try { if (__elemsbefore >= difference_type(__n)) { iterator __start_n = (this->_M_impl._M_start + difference_type(__n)); std::__uninitialized_move_a(this->_M_impl._M_start, __start_n, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; _GLIBCXX_MOVE3(__start_n, __pos, __old_start); std::copy(__first, __last, __pos - difference_type(__n)); } else { _ForwardIterator __mid = __first; std::advance(__mid, difference_type(__n) - __elemsbefore); std::__uninitialized_move_copy(this->_M_impl._M_start, __pos, __first, __mid, __new_start, _M_get_Tp_allocator()); this->_M_impl._M_start = __new_start; std::copy(__mid, __last, __old_start); } } __catch(...) { _M_destroy_nodes(__new_start._M_node, this->_M_impl._M_start._M_node); __throw_exception_again; } } else { iterator __new_finish = _M_reserve_elements_at_back(__n); iterator __old_finish = this->_M_impl._M_finish; const difference_type __elemsafter = difference_type(__length) - __elemsbefore; __pos = this->_M_impl._M_finish - __elemsafter; __try { if (__elemsafter > difference_type(__n)) { iterator __finish_n = (this->_M_impl._M_finish - difference_type(__n)); std::__uninitialized_move_a(__finish_n, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; _GLIBCXX_MOVE_BACKWARD3(__pos, __finish_n, __old_finish); std::copy(__first, __last, __pos); } else { _ForwardIterator __mid = __first; std::advance(__mid, __elemsafter); std::__uninitialized_copy_move(__mid, __last, __pos, this->_M_impl._M_finish, this->_M_impl._M_finish, _M_get_Tp_allocator()); this->_M_impl._M_finish = __new_finish; std::copy(__first, __mid, __pos); } } __catch(...) { _M_destroy_nodes(this->_M_impl._M_finish._M_node + 1, __new_finish._M_node + 1); __throw_exception_again; } } } template void deque<_Tp, _Alloc>:: _M_destroy_data_aux(iterator __first, iterator __last) { for (_Map_pointer __node = __first._M_node + 1; __node < __last._M_node; ++__node) std::_Destroy(*__node, *__node + _S_buffer_size(), _M_get_Tp_allocator()); if (__first._M_node != __last._M_node) { std::_Destroy(__first._M_cur, __first._M_last, _M_get_Tp_allocator()); std::_Destroy(__last._M_first, __last._M_cur, _M_get_Tp_allocator()); } else std::_Destroy(__first._M_cur, __last._M_cur, _M_get_Tp_allocator()); } template void deque<_Tp, _Alloc>:: _M_new_elements_at_front(size_type __new_elems) { if (this->max_size() - this->size() < __new_elems) __throw_length_error(__N("deque::_M_new_elements_at_front")); const size_type __new_nodes = ((__new_elems + _S_buffer_size() - 1) / _S_buffer_size()); _M_reserve_map_at_front(__new_nodes); size_type __i; __try { for (__i = 1; __i <= __new_nodes; ++__i) *(this->_M_impl._M_start._M_node - __i) = this->_M_allocate_node(); } __catch(...) { for (size_type __j = 1; __j < __i; ++__j) _M_deallocate_node(*(this->_M_impl._M_start._M_node - __j)); __throw_exception_again; } } template void deque<_Tp, _Alloc>:: _M_new_elements_at_back(size_type __new_elems) { if (this->max_size() - this->size() < __new_elems) __throw_length_error(__N("deque::_M_new_elements_at_back")); const size_type __new_nodes = ((__new_elems + _S_buffer_size() - 1) / _S_buffer_size()); _M_reserve_map_at_back(__new_nodes); size_type __i; __try { for (__i = 1; __i <= __new_nodes; ++__i) *(this->_M_impl._M_finish._M_node + __i) = this->_M_allocate_node(); } __catch(...) { for (size_type __j = 1; __j < __i; ++__j) _M_deallocate_node(*(this->_M_impl._M_finish._M_node + __j)); __throw_exception_again; } } template void deque<_Tp, _Alloc>:: _M_reallocate_map(size_type __nodes_to_add, bool __add_at_front) { const size_type __old_num_nodes = this->_M_impl._M_finish._M_node - this->_M_impl._M_start._M_node + 1; const size_type __new_num_nodes = __old_num_nodes + __nodes_to_add; _Map_pointer __new_nstart; if (this->_M_impl._M_map_size > 2 * __new_num_nodes) { __new_nstart = this->_M_impl._M_map + (this->_M_impl._M_map_size - __new_num_nodes) / 2 + (__add_at_front ? __nodes_to_add : 0); if (__new_nstart < this->_M_impl._M_start._M_node) std::copy(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1, __new_nstart); else std::copy_backward(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1, __new_nstart + __old_num_nodes); } else { size_type __new_map_size = this->_M_impl._M_map_size + std::max(this->_M_impl._M_map_size, __nodes_to_add) + 2; _Map_pointer __new_map = this->_M_allocate_map(__new_map_size); __new_nstart = __new_map + (__new_map_size - __new_num_nodes) / 2 + (__add_at_front ? __nodes_to_add : 0); std::copy(this->_M_impl._M_start._M_node, this->_M_impl._M_finish._M_node + 1, __new_nstart); _M_deallocate_map(this->_M_impl._M_map, this->_M_impl._M_map_size); this->_M_impl._M_map = __new_map; this->_M_impl._M_map_size = __new_map_size; } this->_M_impl._M_start._M_set_node(__new_nstart); this->_M_impl._M_finish._M_set_node(__new_nstart + __old_num_nodes - 1); } // Overload for deque::iterators, exploiting the "segmented-iterator // optimization". template void fill(const _Deque_iterator<_Tp, _Tp&, _Tp*>& __first, const _Deque_iterator<_Tp, _Tp&, _Tp*>& __last, const _Tp& __value) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; for (typename _Self::_Map_pointer __node = __first._M_node + 1; __node < __last._M_node; ++__node) std::fill(*__node, *__node + _Self::_S_buffer_size(), __value); if (__first._M_node != __last._M_node) { std::fill(__first._M_cur, __first._M_last, __value); std::fill(__last._M_first, __last._M_cur, __value); } else std::fill(__first._M_cur, __last._M_cur, __value); } template _Deque_iterator<_Tp, _Tp&, _Tp*> copy(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { const difference_type __clen = std::min(__len, std::min(__first._M_last - __first._M_cur, __result._M_last - __result._M_cur)); std::copy(__first._M_cur, __first._M_cur + __clen, __result._M_cur); __first += __clen; __result += __clen; __len -= __clen; } return __result; } template _Deque_iterator<_Tp, _Tp&, _Tp*> copy_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { difference_type __llen = __last._M_cur - __last._M_first; _Tp* __lend = __last._M_cur; difference_type __rlen = __result._M_cur - __result._M_first; _Tp* __rend = __result._M_cur; if (!__llen) { __llen = _Self::_S_buffer_size(); __lend = *(__last._M_node - 1) + __llen; } if (!__rlen) { __rlen = _Self::_S_buffer_size(); __rend = *(__result._M_node - 1) + __rlen; } const difference_type __clen = std::min(__len, std::min(__llen, __rlen)); std::copy_backward(__lend - __clen, __lend, __rend); __last -= __clen; __result -= __clen; __len -= __clen; } return __result; } #if __cplusplus >= 201103L template _Deque_iterator<_Tp, _Tp&, _Tp*> move(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { const difference_type __clen = std::min(__len, std::min(__first._M_last - __first._M_cur, __result._M_last - __result._M_cur)); std::move(__first._M_cur, __first._M_cur + __clen, __result._M_cur); __first += __clen; __result += __clen; __len -= __clen; } return __result; } template _Deque_iterator<_Tp, _Tp&, _Tp*> move_backward(_Deque_iterator<_Tp, const _Tp&, const _Tp*> __first, _Deque_iterator<_Tp, const _Tp&, const _Tp*> __last, _Deque_iterator<_Tp, _Tp&, _Tp*> __result) { typedef typename _Deque_iterator<_Tp, _Tp&, _Tp*>::_Self _Self; typedef typename _Self::difference_type difference_type; difference_type __len = __last - __first; while (__len > 0) { difference_type __llen = __last._M_cur - __last._M_first; _Tp* __lend = __last._M_cur; difference_type __rlen = __result._M_cur - __result._M_first; _Tp* __rend = __result._M_cur; if (!__llen) { __llen = _Self::_S_buffer_size(); __lend = *(__last._M_node - 1) + __llen; } if (!__rlen) { __rlen = _Self::_S_buffer_size(); __rend = *(__result._M_node - 1) + __rlen; } const difference_type __clen = std::min(__len, std::min(__llen, __rlen)); std::move_backward(__lend - __clen, __lend, __rend); __last -= __clen; __result -= __clen; __len -= __clen; } return __result; } #endif _GLIBCXX_END_NAMESPACE_CONTAINER _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/fstream.tcc000064400000100037151027430570010365 0ustar00// File based streams -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/fstream.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{fstream} */ // // ISO C++ 14882: 27.8 File-based streams // #ifndef _FSTREAM_TCC #define _FSTREAM_TCC 1 #pragma GCC system_header #include #include // for swap namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template void basic_filebuf<_CharT, _Traits>:: _M_allocate_internal_buffer() { // Allocate internal buffer only if one doesn't already exist // (either allocated or provided by the user via setbuf). if (!_M_buf_allocated && !_M_buf) { _M_buf = new char_type[_M_buf_size]; _M_buf_allocated = true; } } template void basic_filebuf<_CharT, _Traits>:: _M_destroy_internal_buffer() throw() { if (_M_buf_allocated) { delete [] _M_buf; _M_buf = 0; _M_buf_allocated = false; } delete [] _M_ext_buf; _M_ext_buf = 0; _M_ext_buf_size = 0; _M_ext_next = 0; _M_ext_end = 0; } template basic_filebuf<_CharT, _Traits>:: basic_filebuf() : __streambuf_type(), _M_lock(), _M_file(&_M_lock), _M_mode(ios_base::openmode(0)), _M_state_beg(), _M_state_cur(), _M_state_last(), _M_buf(0), _M_buf_size(BUFSIZ), _M_buf_allocated(false), _M_reading(false), _M_writing(false), _M_pback(), _M_pback_cur_save(0), _M_pback_end_save(0), _M_pback_init(false), _M_codecvt(0), _M_ext_buf(0), _M_ext_buf_size(0), _M_ext_next(0), _M_ext_end(0) { if (has_facet<__codecvt_type>(this->_M_buf_locale)) _M_codecvt = &use_facet<__codecvt_type>(this->_M_buf_locale); } #if __cplusplus >= 201103L template basic_filebuf<_CharT, _Traits>:: basic_filebuf(basic_filebuf&& __rhs) : __streambuf_type(__rhs), _M_lock(), _M_file(std::move(__rhs._M_file), &_M_lock), _M_mode(std::__exchange(__rhs._M_mode, ios_base::openmode(0))), _M_state_beg(std::move(__rhs._M_state_beg)), _M_state_cur(std::move(__rhs._M_state_cur)), _M_state_last(std::move(__rhs._M_state_last)), _M_buf(std::__exchange(__rhs._M_buf, nullptr)), _M_buf_size(std::__exchange(__rhs._M_buf_size, 1)), _M_buf_allocated(std::__exchange(__rhs._M_buf_allocated, false)), _M_reading(std::__exchange(__rhs._M_reading, false)), _M_writing(std::__exchange(__rhs._M_writing, false)), _M_pback(__rhs._M_pback), _M_pback_cur_save(std::__exchange(__rhs._M_pback_cur_save, nullptr)), _M_pback_end_save(std::__exchange(__rhs._M_pback_end_save, nullptr)), _M_pback_init(std::__exchange(__rhs._M_pback_init, false)), _M_codecvt(__rhs._M_codecvt), _M_ext_buf(std::__exchange(__rhs._M_ext_buf, nullptr)), _M_ext_buf_size(std::__exchange(__rhs._M_ext_buf_size, 0)), _M_ext_next(std::__exchange(__rhs._M_ext_next, nullptr)), _M_ext_end(std::__exchange(__rhs._M_ext_end, nullptr)) { __rhs._M_set_buffer(-1); __rhs._M_state_last = __rhs._M_state_cur = __rhs._M_state_beg; } template basic_filebuf<_CharT, _Traits>& basic_filebuf<_CharT, _Traits>:: operator=(basic_filebuf&& __rhs) { this->close(); __streambuf_type::operator=(__rhs); _M_file.swap(__rhs._M_file); _M_mode = std::__exchange(__rhs._M_mode, ios_base::openmode(0)); _M_state_beg = std::move(__rhs._M_state_beg); _M_state_cur = std::move(__rhs._M_state_cur); _M_state_last = std::move(__rhs._M_state_last); _M_buf = std::__exchange(__rhs._M_buf, nullptr); _M_buf_size = std::__exchange(__rhs._M_buf_size, 1); _M_buf_allocated = std::__exchange(__rhs._M_buf_allocated, false); _M_ext_buf = std::__exchange(__rhs._M_ext_buf, nullptr); _M_ext_buf_size = std::__exchange(__rhs._M_ext_buf_size, 0); _M_ext_next = std::__exchange(__rhs._M_ext_next, nullptr); _M_ext_end = std::__exchange(__rhs._M_ext_end, nullptr); _M_reading = std::__exchange(__rhs._M_reading, false); _M_writing = std::__exchange(__rhs._M_writing, false); _M_pback_cur_save = std::__exchange(__rhs._M_pback_cur_save, nullptr); _M_pback_end_save = std::__exchange(__rhs._M_pback_end_save, nullptr); _M_pback_init = std::__exchange(__rhs._M_pback_init, false); __rhs._M_set_buffer(-1); __rhs._M_state_last = __rhs._M_state_cur = __rhs._M_state_beg; return *this; } template void basic_filebuf<_CharT, _Traits>:: swap(basic_filebuf& __rhs) { __streambuf_type::swap(__rhs); _M_file.swap(__rhs._M_file); std::swap(_M_mode, __rhs._M_mode); std::swap(_M_state_beg, __rhs._M_state_beg); std::swap(_M_state_cur, __rhs._M_state_cur); std::swap(_M_state_last, __rhs._M_state_last); std::swap(_M_buf, __rhs._M_buf); std::swap(_M_buf_size, __rhs._M_buf_size); std::swap(_M_buf_allocated, __rhs._M_buf_allocated); std::swap(_M_ext_buf, __rhs._M_ext_buf); std::swap(_M_ext_buf_size, __rhs._M_ext_buf_size); std::swap(_M_ext_next, __rhs._M_ext_next); std::swap(_M_ext_end, __rhs._M_ext_end); std::swap(_M_reading, __rhs._M_reading); std::swap(_M_writing, __rhs._M_writing); std::swap(_M_pback_cur_save, __rhs._M_pback_cur_save); std::swap(_M_pback_end_save, __rhs._M_pback_end_save); std::swap(_M_pback_init, __rhs._M_pback_init); } #endif template typename basic_filebuf<_CharT, _Traits>::__filebuf_type* basic_filebuf<_CharT, _Traits>:: open(const char* __s, ios_base::openmode __mode) { __filebuf_type *__ret = 0; if (!this->is_open()) { _M_file.open(__s, __mode); if (this->is_open()) { _M_allocate_internal_buffer(); _M_mode = __mode; // Setup initial buffer to 'uncommitted' mode. _M_reading = false; _M_writing = false; _M_set_buffer(-1); // Reset to initial state. _M_state_last = _M_state_cur = _M_state_beg; // 27.8.1.3,4 if ((__mode & ios_base::ate) && this->seekoff(0, ios_base::end, __mode) == pos_type(off_type(-1))) this->close(); else __ret = this; } } return __ret; } template typename basic_filebuf<_CharT, _Traits>::__filebuf_type* basic_filebuf<_CharT, _Traits>:: close() { if (!this->is_open()) return 0; bool __testfail = false; { // NB: Do this here so that re-opened filebufs will be cool... struct __close_sentry { basic_filebuf *__fb; __close_sentry (basic_filebuf *__fbi): __fb(__fbi) { } ~__close_sentry () { __fb->_M_mode = ios_base::openmode(0); __fb->_M_pback_init = false; __fb->_M_destroy_internal_buffer(); __fb->_M_reading = false; __fb->_M_writing = false; __fb->_M_set_buffer(-1); __fb->_M_state_last = __fb->_M_state_cur = __fb->_M_state_beg; } } __cs (this); __try { if (!_M_terminate_output()) __testfail = true; } __catch(__cxxabiv1::__forced_unwind&) { _M_file.close(); __throw_exception_again; } __catch(...) { __testfail = true; } } if (!_M_file.close()) __testfail = true; if (__testfail) return 0; else return this; } template streamsize basic_filebuf<_CharT, _Traits>:: showmanyc() { streamsize __ret = -1; const bool __testin = _M_mode & ios_base::in; if (__testin && this->is_open()) { // For a stateful encoding (-1) the pending sequence might be just // shift and unshift prefixes with no actual character. __ret = this->egptr() - this->gptr(); #if _GLIBCXX_HAVE_DOS_BASED_FILESYSTEM // About this workaround, see libstdc++/20806. const bool __testbinary = _M_mode & ios_base::binary; if (__check_facet(_M_codecvt).encoding() >= 0 && __testbinary) #else if (__check_facet(_M_codecvt).encoding() >= 0) #endif __ret += _M_file.showmanyc() / _M_codecvt->max_length(); } return __ret; } template typename basic_filebuf<_CharT, _Traits>::int_type basic_filebuf<_CharT, _Traits>:: underflow() { int_type __ret = traits_type::eof(); const bool __testin = _M_mode & ios_base::in; if (__testin) { if (_M_writing) { if (overflow() == traits_type::eof()) return __ret; _M_set_buffer(-1); _M_writing = false; } // Check for pback madness, and if so switch back to the // normal buffers and jet outta here before expensive // fileops happen... _M_destroy_pback(); if (this->gptr() < this->egptr()) return traits_type::to_int_type(*this->gptr()); // Get and convert input sequence. const size_t __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1; // Will be set to true if ::read() returns 0 indicating EOF. bool __got_eof = false; // Number of internal characters produced. streamsize __ilen = 0; codecvt_base::result __r = codecvt_base::ok; if (__check_facet(_M_codecvt).always_noconv()) { __ilen = _M_file.xsgetn(reinterpret_cast(this->eback()), __buflen); if (__ilen == 0) __got_eof = true; } else { // Worst-case number of external bytes. // XXX Not done encoding() == -1. const int __enc = _M_codecvt->encoding(); streamsize __blen; // Minimum buffer size. streamsize __rlen; // Number of chars to read. if (__enc > 0) __blen = __rlen = __buflen * __enc; else { __blen = __buflen + _M_codecvt->max_length() - 1; __rlen = __buflen; } const streamsize __remainder = _M_ext_end - _M_ext_next; __rlen = __rlen > __remainder ? __rlen - __remainder : 0; // An imbue in 'read' mode implies first converting the external // chars already present. if (_M_reading && this->egptr() == this->eback() && __remainder) __rlen = 0; // Allocate buffer if necessary and move unconverted // bytes to front. if (_M_ext_buf_size < __blen) { char* __buf = new char[__blen]; if (__remainder) __builtin_memcpy(__buf, _M_ext_next, __remainder); delete [] _M_ext_buf; _M_ext_buf = __buf; _M_ext_buf_size = __blen; } else if (__remainder) __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder); _M_ext_next = _M_ext_buf; _M_ext_end = _M_ext_buf + __remainder; _M_state_last = _M_state_cur; do { if (__rlen > 0) { // Sanity check! // This may fail if the return value of // codecvt::max_length() is bogus. if (_M_ext_end - _M_ext_buf + __rlen > _M_ext_buf_size) { __throw_ios_failure(__N("basic_filebuf::underflow " "codecvt::max_length() " "is not valid")); } streamsize __elen = _M_file.xsgetn(_M_ext_end, __rlen); if (__elen == 0) __got_eof = true; else if (__elen == -1) break; _M_ext_end += __elen; } char_type* __iend = this->eback(); if (_M_ext_next < _M_ext_end) __r = _M_codecvt->in(_M_state_cur, _M_ext_next, _M_ext_end, _M_ext_next, this->eback(), this->eback() + __buflen, __iend); if (__r == codecvt_base::noconv) { size_t __avail = _M_ext_end - _M_ext_buf; __ilen = std::min(__avail, __buflen); traits_type::copy(this->eback(), reinterpret_cast (_M_ext_buf), __ilen); _M_ext_next = _M_ext_buf + __ilen; } else __ilen = __iend - this->eback(); // _M_codecvt->in may return error while __ilen > 0: this is // ok, and actually occurs in case of mixed encodings (e.g., // XML files). if (__r == codecvt_base::error) break; __rlen = 1; } while (__ilen == 0 && !__got_eof); } if (__ilen > 0) { _M_set_buffer(__ilen); _M_reading = true; __ret = traits_type::to_int_type(*this->gptr()); } else if (__got_eof) { // If the actual end of file is reached, set 'uncommitted' // mode, thus allowing an immediate write without an // intervening seek. _M_set_buffer(-1); _M_reading = false; // However, reaching it while looping on partial means that // the file has got an incomplete character. if (__r == codecvt_base::partial) __throw_ios_failure(__N("basic_filebuf::underflow " "incomplete character in file")); } else if (__r == codecvt_base::error) __throw_ios_failure(__N("basic_filebuf::underflow " "invalid byte sequence in file")); else __throw_ios_failure(__N("basic_filebuf::underflow " "error reading the file")); } return __ret; } template typename basic_filebuf<_CharT, _Traits>::int_type basic_filebuf<_CharT, _Traits>:: pbackfail(int_type __i) { int_type __ret = traits_type::eof(); const bool __testin = _M_mode & ios_base::in; if (__testin) { if (_M_writing) { if (overflow() == traits_type::eof()) return __ret; _M_set_buffer(-1); _M_writing = false; } // Remember whether the pback buffer is active, otherwise below // we may try to store in it a second char (libstdc++/9761). const bool __testpb = _M_pback_init; const bool __testeof = traits_type::eq_int_type(__i, __ret); int_type __tmp; if (this->eback() < this->gptr()) { this->gbump(-1); __tmp = traits_type::to_int_type(*this->gptr()); } else if (this->seekoff(-1, ios_base::cur) != pos_type(off_type(-1))) { __tmp = this->underflow(); if (traits_type::eq_int_type(__tmp, __ret)) return __ret; } else { // At the beginning of the buffer, need to make a // putback position available. But the seek may fail // (f.i., at the beginning of a file, see // libstdc++/9439) and in that case we return // traits_type::eof(). return __ret; } // Try to put back __i into input sequence in one of three ways. // Order these tests done in is unspecified by the standard. if (!__testeof && traits_type::eq_int_type(__i, __tmp)) __ret = __i; else if (__testeof) __ret = traits_type::not_eof(__i); else if (!__testpb) { _M_create_pback(); _M_reading = true; *this->gptr() = traits_type::to_char_type(__i); __ret = __i; } } return __ret; } template typename basic_filebuf<_CharT, _Traits>::int_type basic_filebuf<_CharT, _Traits>:: overflow(int_type __c) { int_type __ret = traits_type::eof(); const bool __testeof = traits_type::eq_int_type(__c, __ret); const bool __testout = (_M_mode & ios_base::out || _M_mode & ios_base::app); if (__testout) { if (_M_reading) { _M_destroy_pback(); const int __gptr_off = _M_get_ext_pos(_M_state_last); if (_M_seek(__gptr_off, ios_base::cur, _M_state_last) == pos_type(off_type(-1))) return __ret; } if (this->pbase() < this->pptr()) { // If appropriate, append the overflow char. if (!__testeof) { *this->pptr() = traits_type::to_char_type(__c); this->pbump(1); } // Convert pending sequence to external representation, // and output. if (_M_convert_to_external(this->pbase(), this->pptr() - this->pbase())) { _M_set_buffer(0); __ret = traits_type::not_eof(__c); } } else if (_M_buf_size > 1) { // Overflow in 'uncommitted' mode: set _M_writing, set // the buffer to the initial 'write' mode, and put __c // into the buffer. _M_set_buffer(0); _M_writing = true; if (!__testeof) { *this->pptr() = traits_type::to_char_type(__c); this->pbump(1); } __ret = traits_type::not_eof(__c); } else { // Unbuffered. char_type __conv = traits_type::to_char_type(__c); if (__testeof || _M_convert_to_external(&__conv, 1)) { _M_writing = true; __ret = traits_type::not_eof(__c); } } } return __ret; } template bool basic_filebuf<_CharT, _Traits>:: _M_convert_to_external(_CharT* __ibuf, streamsize __ilen) { // Sizes of external and pending output. streamsize __elen; streamsize __plen; if (__check_facet(_M_codecvt).always_noconv()) { __elen = _M_file.xsputn(reinterpret_cast(__ibuf), __ilen); __plen = __ilen; } else { // Worst-case number of external bytes needed. // XXX Not done encoding() == -1. streamsize __blen = __ilen * _M_codecvt->max_length(); char* __buf = static_cast(__builtin_alloca(__blen)); char* __bend; const char_type* __iend; codecvt_base::result __r; __r = _M_codecvt->out(_M_state_cur, __ibuf, __ibuf + __ilen, __iend, __buf, __buf + __blen, __bend); if (__r == codecvt_base::ok || __r == codecvt_base::partial) __blen = __bend - __buf; else if (__r == codecvt_base::noconv) { // Same as the always_noconv case above. __buf = reinterpret_cast(__ibuf); __blen = __ilen; } else __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external " "conversion error")); __elen = _M_file.xsputn(__buf, __blen); __plen = __blen; // Try once more for partial conversions. if (__r == codecvt_base::partial && __elen == __plen) { const char_type* __iresume = __iend; streamsize __rlen = this->pptr() - __iend; __r = _M_codecvt->out(_M_state_cur, __iresume, __iresume + __rlen, __iend, __buf, __buf + __blen, __bend); if (__r != codecvt_base::error) { __rlen = __bend - __buf; __elen = _M_file.xsputn(__buf, __rlen); __plen = __rlen; } else __throw_ios_failure(__N("basic_filebuf::_M_convert_to_external " "conversion error")); } } return __elen == __plen; } template streamsize basic_filebuf<_CharT, _Traits>:: xsgetn(_CharT* __s, streamsize __n) { // Clear out pback buffer before going on to the real deal... streamsize __ret = 0; if (_M_pback_init) { if (__n > 0 && this->gptr() == this->eback()) { *__s++ = *this->gptr(); // emulate non-underflowing sbumpc this->gbump(1); __ret = 1; --__n; } _M_destroy_pback(); } else if (_M_writing) { if (overflow() == traits_type::eof()) return __ret; _M_set_buffer(-1); _M_writing = false; } // Optimization in the always_noconv() case, to be generalized in the // future: when __n > __buflen we read directly instead of using the // buffer repeatedly. const bool __testin = _M_mode & ios_base::in; const streamsize __buflen = _M_buf_size > 1 ? _M_buf_size - 1 : 1; if (__n > __buflen && __check_facet(_M_codecvt).always_noconv() && __testin) { // First, copy the chars already present in the buffer. const streamsize __avail = this->egptr() - this->gptr(); if (__avail != 0) { traits_type::copy(__s, this->gptr(), __avail); __s += __avail; this->setg(this->eback(), this->gptr() + __avail, this->egptr()); __ret += __avail; __n -= __avail; } // Need to loop in case of short reads (relatively common // with pipes). streamsize __len; for (;;) { __len = _M_file.xsgetn(reinterpret_cast(__s), __n); if (__len == -1) __throw_ios_failure(__N("basic_filebuf::xsgetn " "error reading the file")); if (__len == 0) break; __n -= __len; __ret += __len; if (__n == 0) break; __s += __len; } if (__n == 0) { // Set _M_reading. Buffer is already in initial 'read' mode. _M_reading = true; } else if (__len == 0) { // If end of file is reached, set 'uncommitted' // mode, thus allowing an immediate write without // an intervening seek. _M_set_buffer(-1); _M_reading = false; } } else __ret += __streambuf_type::xsgetn(__s, __n); return __ret; } template streamsize basic_filebuf<_CharT, _Traits>:: xsputn(const _CharT* __s, streamsize __n) { streamsize __ret = 0; // Optimization in the always_noconv() case, to be generalized in the // future: when __n is sufficiently large we write directly instead of // using the buffer. const bool __testout = (_M_mode & ios_base::out || _M_mode & ios_base::app); if (__check_facet(_M_codecvt).always_noconv() && __testout && !_M_reading) { // Measurement would reveal the best choice. const streamsize __chunk = 1ul << 10; streamsize __bufavail = this->epptr() - this->pptr(); // Don't mistake 'uncommitted' mode buffered with unbuffered. if (!_M_writing && _M_buf_size > 1) __bufavail = _M_buf_size - 1; const streamsize __limit = std::min(__chunk, __bufavail); if (__n >= __limit) { const streamsize __buffill = this->pptr() - this->pbase(); const char* __buf = reinterpret_cast(this->pbase()); __ret = _M_file.xsputn_2(__buf, __buffill, reinterpret_cast(__s), __n); if (__ret == __buffill + __n) { _M_set_buffer(0); _M_writing = true; } if (__ret > __buffill) __ret -= __buffill; else __ret = 0; } else __ret = __streambuf_type::xsputn(__s, __n); } else __ret = __streambuf_type::xsputn(__s, __n); return __ret; } template typename basic_filebuf<_CharT, _Traits>::__streambuf_type* basic_filebuf<_CharT, _Traits>:: setbuf(char_type* __s, streamsize __n) { if (!this->is_open()) { if (__s == 0 && __n == 0) _M_buf_size = 1; else if (__s && __n > 0) { // This is implementation-defined behavior, and assumes that // an external char_type array of length __n exists and has // been pre-allocated. If this is not the case, things will // quickly blow up. When __n > 1, __n - 1 positions will be // used for the get area, __n - 1 for the put area and 1 // position to host the overflow char of a full put area. // When __n == 1, 1 position will be used for the get area // and 0 for the put area, as in the unbuffered case above. _M_buf = __s; _M_buf_size = __n; } } return this; } // According to 27.8.1.4 p11 - 13, seekoff should ignore the last // argument (of type openmode). template typename basic_filebuf<_CharT, _Traits>::pos_type basic_filebuf<_CharT, _Traits>:: seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode) { int __width = 0; if (_M_codecvt) __width = _M_codecvt->encoding(); if (__width < 0) __width = 0; pos_type __ret = pos_type(off_type(-1)); const bool __testfail = __off != 0 && __width <= 0; if (this->is_open() && !__testfail) { // tellg and tellp queries do not affect any state, unless // ! always_noconv and the put sequence is not empty. // In that case, determining the position requires converting the // put sequence. That doesn't use ext_buf, so requires a flush. bool __no_movement = __way == ios_base::cur && __off == 0 && (!_M_writing || _M_codecvt->always_noconv()); // Ditch any pback buffers to avoid confusion. if (!__no_movement) _M_destroy_pback(); // Correct state at destination. Note that this is the correct // state for the current position during output, because // codecvt::unshift() returns the state to the initial state. // This is also the correct state at the end of the file because // an unshift sequence should have been written at the end. __state_type __state = _M_state_beg; off_type __computed_off = __off * __width; if (_M_reading && __way == ios_base::cur) { __state = _M_state_last; __computed_off += _M_get_ext_pos(__state); } if (!__no_movement) __ret = _M_seek(__computed_off, __way, __state); else { if (_M_writing) __computed_off = this->pptr() - this->pbase(); off_type __file_off = _M_file.seekoff(0, ios_base::cur); if (__file_off != off_type(-1)) { __ret = __file_off + __computed_off; __ret.state(__state); } } } return __ret; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 171. Strange seekpos() semantics due to joint position // According to the resolution of DR 171, seekpos should ignore the last // argument (of type openmode). template typename basic_filebuf<_CharT, _Traits>::pos_type basic_filebuf<_CharT, _Traits>:: seekpos(pos_type __pos, ios_base::openmode) { pos_type __ret = pos_type(off_type(-1)); if (this->is_open()) { // Ditch any pback buffers to avoid confusion. _M_destroy_pback(); __ret = _M_seek(off_type(__pos), ios_base::beg, __pos.state()); } return __ret; } template typename basic_filebuf<_CharT, _Traits>::pos_type basic_filebuf<_CharT, _Traits>:: _M_seek(off_type __off, ios_base::seekdir __way, __state_type __state) { pos_type __ret = pos_type(off_type(-1)); if (_M_terminate_output()) { off_type __file_off = _M_file.seekoff(__off, __way); if (__file_off != off_type(-1)) { _M_reading = false; _M_writing = false; _M_ext_next = _M_ext_end = _M_ext_buf; _M_set_buffer(-1); _M_state_cur = __state; __ret = __file_off; __ret.state(_M_state_cur); } } return __ret; } // Returns the distance from the end of the ext buffer to the point // corresponding to gptr(). This is a negative value. Updates __state // from eback() correspondence to gptr(). template int basic_filebuf<_CharT, _Traits>:: _M_get_ext_pos(__state_type& __state) { if (_M_codecvt->always_noconv()) return this->gptr() - this->egptr(); else { // Calculate offset from _M_ext_buf that corresponds to // gptr(). Precondition: __state == _M_state_last, which // corresponds to eback(). const int __gptr_off = _M_codecvt->length(__state, _M_ext_buf, _M_ext_next, this->gptr() - this->eback()); return _M_ext_buf + __gptr_off - _M_ext_end; } } template bool basic_filebuf<_CharT, _Traits>:: _M_terminate_output() { // Part one: update the output sequence. bool __testvalid = true; if (this->pbase() < this->pptr()) { const int_type __tmp = this->overflow(); if (traits_type::eq_int_type(__tmp, traits_type::eof())) __testvalid = false; } // Part two: output unshift sequence. if (_M_writing && !__check_facet(_M_codecvt).always_noconv() && __testvalid) { // Note: this value is arbitrary, since there is no way to // get the length of the unshift sequence from codecvt, // without calling unshift. const size_t __blen = 128; char __buf[__blen]; codecvt_base::result __r; streamsize __ilen = 0; do { char* __next; __r = _M_codecvt->unshift(_M_state_cur, __buf, __buf + __blen, __next); if (__r == codecvt_base::error) __testvalid = false; else if (__r == codecvt_base::ok || __r == codecvt_base::partial) { __ilen = __next - __buf; if (__ilen > 0) { const streamsize __elen = _M_file.xsputn(__buf, __ilen); if (__elen != __ilen) __testvalid = false; } } } while (__r == codecvt_base::partial && __ilen > 0 && __testvalid); if (__testvalid) { // This second call to overflow() is required by the standard, // but it's not clear why it's needed, since the output buffer // should be empty by this point (it should have been emptied // in the first call to overflow()). const int_type __tmp = this->overflow(); if (traits_type::eq_int_type(__tmp, traits_type::eof())) __testvalid = false; } } return __testvalid; } template int basic_filebuf<_CharT, _Traits>:: sync() { // Make sure that the internal buffer resyncs its idea of // the file position with the external file. int __ret = 0; if (this->pbase() < this->pptr()) { const int_type __tmp = this->overflow(); if (traits_type::eq_int_type(__tmp, traits_type::eof())) __ret = -1; } return __ret; } template void basic_filebuf<_CharT, _Traits>:: imbue(const locale& __loc) { bool __testvalid = true; const __codecvt_type* _M_codecvt_tmp = 0; if (__builtin_expect(has_facet<__codecvt_type>(__loc), true)) _M_codecvt_tmp = &use_facet<__codecvt_type>(__loc); if (this->is_open()) { // encoding() == -1 is ok only at the beginning. if ((_M_reading || _M_writing) && __check_facet(_M_codecvt).encoding() == -1) __testvalid = false; else { if (_M_reading) { if (__check_facet(_M_codecvt).always_noconv()) { if (_M_codecvt_tmp && !__check_facet(_M_codecvt_tmp).always_noconv()) __testvalid = this->seekoff(0, ios_base::cur, _M_mode) != pos_type(off_type(-1)); } else { // External position corresponding to gptr(). _M_ext_next = _M_ext_buf + _M_codecvt->length(_M_state_last, _M_ext_buf, _M_ext_next, this->gptr() - this->eback()); const streamsize __remainder = _M_ext_end - _M_ext_next; if (__remainder) __builtin_memmove(_M_ext_buf, _M_ext_next, __remainder); _M_ext_next = _M_ext_buf; _M_ext_end = _M_ext_buf + __remainder; _M_set_buffer(-1); _M_state_last = _M_state_cur = _M_state_beg; } } else if (_M_writing && (__testvalid = _M_terminate_output())) _M_set_buffer(-1); } } if (__testvalid) _M_codecvt = _M_codecvt_tmp; else _M_codecvt = 0; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_filebuf; extern template class basic_ifstream; extern template class basic_ofstream; extern template class basic_fstream; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_filebuf; extern template class basic_ifstream; extern template class basic_ofstream; extern template class basic_fstream; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/hashtable_policy.h000064400000204603151027430570011720 0ustar00// Internal policy header for unordered_set and unordered_map -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/hashtable_policy.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. * @headername{unordered_map,unordered_set} */ #ifndef _HASHTABLE_POLICY_H #define _HASHTABLE_POLICY_H 1 #include // for std::tuple, std::forward_as_tuple #include // for std::uint_fast64_t #include // for std::min. namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template class _Hashtable; namespace __detail { /** * @defgroup hashtable-detail Base and Implementation Classes * @ingroup unordered_associative_containers * @{ */ template struct _Hashtable_base; // Helper function: return distance(first, last) for forward // iterators, or 0/1 for input iterators. template inline typename std::iterator_traits<_Iterator>::difference_type __distance_fw(_Iterator __first, _Iterator __last, std::input_iterator_tag) { return __first != __last ? 1 : 0; } template inline typename std::iterator_traits<_Iterator>::difference_type __distance_fw(_Iterator __first, _Iterator __last, std::forward_iterator_tag) { return std::distance(__first, __last); } template inline typename std::iterator_traits<_Iterator>::difference_type __distance_fw(_Iterator __first, _Iterator __last) { return __distance_fw(__first, __last, std::__iterator_category(__first)); } struct _Identity { template _Tp&& operator()(_Tp&& __x) const { return std::forward<_Tp>(__x); } }; struct _Select1st { template auto operator()(_Tp&& __x) const -> decltype(std::get<0>(std::forward<_Tp>(__x))) { return std::get<0>(std::forward<_Tp>(__x)); } }; template struct _Hashtable_alloc; // Functor recycling a pool of nodes and using allocation once the pool is // empty. template struct _ReuseOrAllocNode { private: using __node_alloc_type = _NodeAlloc; using __hashtable_alloc = _Hashtable_alloc<__node_alloc_type>; using __node_alloc_traits = typename __hashtable_alloc::__node_alloc_traits; using __node_type = typename __hashtable_alloc::__node_type; public: _ReuseOrAllocNode(__node_type* __nodes, __hashtable_alloc& __h) : _M_nodes(__nodes), _M_h(__h) { } _ReuseOrAllocNode(const _ReuseOrAllocNode&) = delete; ~_ReuseOrAllocNode() { _M_h._M_deallocate_nodes(_M_nodes); } template __node_type* operator()(_Arg&& __arg) const { if (_M_nodes) { __node_type* __node = _M_nodes; _M_nodes = _M_nodes->_M_next(); __node->_M_nxt = nullptr; auto& __a = _M_h._M_node_allocator(); __node_alloc_traits::destroy(__a, __node->_M_valptr()); __try { __node_alloc_traits::construct(__a, __node->_M_valptr(), std::forward<_Arg>(__arg)); } __catch(...) { __node->~__node_type(); __node_alloc_traits::deallocate(__a, __node, 1); __throw_exception_again; } return __node; } return _M_h._M_allocate_node(std::forward<_Arg>(__arg)); } private: mutable __node_type* _M_nodes; __hashtable_alloc& _M_h; }; // Functor similar to the previous one but without any pool of nodes to // recycle. template struct _AllocNode { private: using __hashtable_alloc = _Hashtable_alloc<_NodeAlloc>; using __node_type = typename __hashtable_alloc::__node_type; public: _AllocNode(__hashtable_alloc& __h) : _M_h(__h) { } template __node_type* operator()(_Arg&& __arg) const { return _M_h._M_allocate_node(std::forward<_Arg>(__arg)); } private: __hashtable_alloc& _M_h; }; // Auxiliary types used for all instantiations of _Hashtable nodes // and iterators. /** * struct _Hashtable_traits * * Important traits for hash tables. * * @tparam _Cache_hash_code Boolean value. True if the value of * the hash function is stored along with the value. This is a * time-space tradeoff. Storing it may improve lookup speed by * reducing the number of times we need to call the _Equal * function. * * @tparam _Constant_iterators Boolean value. True if iterator and * const_iterator are both constant iterator types. This is true * for unordered_set and unordered_multiset, false for * unordered_map and unordered_multimap. * * @tparam _Unique_keys Boolean value. True if the return value * of _Hashtable::count(k) is always at most one, false if it may * be an arbitrary number. This is true for unordered_set and * unordered_map, false for unordered_multiset and * unordered_multimap. */ template struct _Hashtable_traits { using __hash_cached = __bool_constant<_Cache_hash_code>; using __constant_iterators = __bool_constant<_Constant_iterators>; using __unique_keys = __bool_constant<_Unique_keys>; }; /** * struct _Hash_node_base * * Nodes, used to wrap elements stored in the hash table. A policy * template parameter of class template _Hashtable controls whether * nodes also store a hash code. In some cases (e.g. strings) this * may be a performance win. */ struct _Hash_node_base { _Hash_node_base* _M_nxt; _Hash_node_base() noexcept : _M_nxt() { } _Hash_node_base(_Hash_node_base* __next) noexcept : _M_nxt(__next) { } }; /** * struct _Hash_node_value_base * * Node type with the value to store. */ template struct _Hash_node_value_base : _Hash_node_base { typedef _Value value_type; __gnu_cxx::__aligned_buffer<_Value> _M_storage; _Value* _M_valptr() noexcept { return _M_storage._M_ptr(); } const _Value* _M_valptr() const noexcept { return _M_storage._M_ptr(); } _Value& _M_v() noexcept { return *_M_valptr(); } const _Value& _M_v() const noexcept { return *_M_valptr(); } }; /** * Primary template struct _Hash_node. */ template struct _Hash_node; /** * Specialization for nodes with caches, struct _Hash_node. * * Base class is __detail::_Hash_node_value_base. */ template struct _Hash_node<_Value, true> : _Hash_node_value_base<_Value> { std::size_t _M_hash_code; _Hash_node* _M_next() const noexcept { return static_cast<_Hash_node*>(this->_M_nxt); } }; /** * Specialization for nodes without caches, struct _Hash_node. * * Base class is __detail::_Hash_node_value_base. */ template struct _Hash_node<_Value, false> : _Hash_node_value_base<_Value> { _Hash_node* _M_next() const noexcept { return static_cast<_Hash_node*>(this->_M_nxt); } }; /// Base class for node iterators. template struct _Node_iterator_base { using __node_type = _Hash_node<_Value, _Cache_hash_code>; __node_type* _M_cur; _Node_iterator_base(__node_type* __p) noexcept : _M_cur(__p) { } void _M_incr() noexcept { _M_cur = _M_cur->_M_next(); } }; template inline bool operator==(const _Node_iterator_base<_Value, _Cache_hash_code>& __x, const _Node_iterator_base<_Value, _Cache_hash_code >& __y) noexcept { return __x._M_cur == __y._M_cur; } template inline bool operator!=(const _Node_iterator_base<_Value, _Cache_hash_code>& __x, const _Node_iterator_base<_Value, _Cache_hash_code>& __y) noexcept { return __x._M_cur != __y._M_cur; } /// Node iterators, used to iterate through all the hashtable. template struct _Node_iterator : public _Node_iterator_base<_Value, __cache> { private: using __base_type = _Node_iterator_base<_Value, __cache>; using __node_type = typename __base_type::__node_type; public: typedef _Value value_type; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; using pointer = typename std::conditional<__constant_iterators, const _Value*, _Value*>::type; using reference = typename std::conditional<__constant_iterators, const _Value&, _Value&>::type; _Node_iterator() noexcept : __base_type(0) { } explicit _Node_iterator(__node_type* __p) noexcept : __base_type(__p) { } reference operator*() const noexcept { return this->_M_cur->_M_v(); } pointer operator->() const noexcept { return this->_M_cur->_M_valptr(); } _Node_iterator& operator++() noexcept { this->_M_incr(); return *this; } _Node_iterator operator++(int) noexcept { _Node_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; /// Node const_iterators, used to iterate through all the hashtable. template struct _Node_const_iterator : public _Node_iterator_base<_Value, __cache> { private: using __base_type = _Node_iterator_base<_Value, __cache>; using __node_type = typename __base_type::__node_type; public: typedef _Value value_type; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; typedef const _Value* pointer; typedef const _Value& reference; _Node_const_iterator() noexcept : __base_type(0) { } explicit _Node_const_iterator(__node_type* __p) noexcept : __base_type(__p) { } _Node_const_iterator(const _Node_iterator<_Value, __constant_iterators, __cache>& __x) noexcept : __base_type(__x._M_cur) { } reference operator*() const noexcept { return this->_M_cur->_M_v(); } pointer operator->() const noexcept { return this->_M_cur->_M_valptr(); } _Node_const_iterator& operator++() noexcept { this->_M_incr(); return *this; } _Node_const_iterator operator++(int) noexcept { _Node_const_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; // Many of class template _Hashtable's template parameters are policy // classes. These are defaults for the policies. /// Default range hashing function: use division to fold a large number /// into the range [0, N). struct _Mod_range_hashing { typedef std::size_t first_argument_type; typedef std::size_t second_argument_type; typedef std::size_t result_type; result_type operator()(first_argument_type __num, second_argument_type __den) const noexcept { return __num % __den; } }; /// Default ranged hash function H. In principle it should be a /// function object composed from objects of type H1 and H2 such that /// h(k, N) = h2(h1(k), N), but that would mean making extra copies of /// h1 and h2. So instead we'll just use a tag to tell class template /// hashtable to do that composition. struct _Default_ranged_hash { }; /// Default value for rehash policy. Bucket size is (usually) the /// smallest prime that keeps the load factor small enough. struct _Prime_rehash_policy { using __has_load_factor = std::true_type; _Prime_rehash_policy(float __z = 1.0) noexcept : _M_max_load_factor(__z), _M_next_resize(0) { } float max_load_factor() const noexcept { return _M_max_load_factor; } // Return a bucket size no smaller than n. std::size_t _M_next_bkt(std::size_t __n) const; // Return a bucket count appropriate for n elements std::size_t _M_bkt_for_elements(std::size_t __n) const { return __builtin_ceil(__n / (long double)_M_max_load_factor); } // __n_bkt is current bucket count, __n_elt is current element count, // and __n_ins is number of elements to be inserted. Do we need to // increase bucket count? If so, return make_pair(true, n), where n // is the new bucket count. If not, return make_pair(false, 0). std::pair _M_need_rehash(std::size_t __n_bkt, std::size_t __n_elt, std::size_t __n_ins) const; typedef std::size_t _State; _State _M_state() const { return _M_next_resize; } void _M_reset() noexcept { _M_next_resize = 0; } void _M_reset(_State __state) { _M_next_resize = __state; } static const std::size_t _S_growth_factor = 2; float _M_max_load_factor; mutable std::size_t _M_next_resize; }; /// Range hashing function assuming that second arg is a power of 2. struct _Mask_range_hashing { typedef std::size_t first_argument_type; typedef std::size_t second_argument_type; typedef std::size_t result_type; result_type operator()(first_argument_type __num, second_argument_type __den) const noexcept { return __num & (__den - 1); } }; /// Compute closest power of 2. _GLIBCXX14_CONSTEXPR inline std::size_t __clp2(std::size_t __n) noexcept { #if __SIZEOF_SIZE_T__ >= 8 std::uint_fast64_t __x = __n; #else std::uint_fast32_t __x = __n; #endif // Algorithm from Hacker's Delight, Figure 3-3. __x = __x - 1; __x = __x | (__x >> 1); __x = __x | (__x >> 2); __x = __x | (__x >> 4); __x = __x | (__x >> 8); __x = __x | (__x >>16); #if __SIZEOF_SIZE_T__ >= 8 __x = __x | (__x >>32); #endif return __x + 1; } /// Rehash policy providing power of 2 bucket numbers. Avoids modulo /// operations. struct _Power2_rehash_policy { using __has_load_factor = std::true_type; _Power2_rehash_policy(float __z = 1.0) noexcept : _M_max_load_factor(__z), _M_next_resize(0) { } float max_load_factor() const noexcept { return _M_max_load_factor; } // Return a bucket size no smaller than n (as long as n is not above the // highest power of 2). std::size_t _M_next_bkt(std::size_t __n) noexcept { const auto __max_width = std::min(sizeof(size_t), 8); const auto __max_bkt = size_t(1) << (__max_width * __CHAR_BIT__ - 1); std::size_t __res = __clp2(__n); if (__res == __n) __res <<= 1; if (__res == 0) __res = __max_bkt; if (__res == __max_bkt) // Set next resize to the max value so that we never try to rehash again // as we already reach the biggest possible bucket number. // Note that it might result in max_load_factor not being respected. _M_next_resize = std::size_t(-1); else _M_next_resize = __builtin_ceil(__res * (long double)_M_max_load_factor); return __res; } // Return a bucket count appropriate for n elements std::size_t _M_bkt_for_elements(std::size_t __n) const noexcept { return __builtin_ceil(__n / (long double)_M_max_load_factor); } // __n_bkt is current bucket count, __n_elt is current element count, // and __n_ins is number of elements to be inserted. Do we need to // increase bucket count? If so, return make_pair(true, n), where n // is the new bucket count. If not, return make_pair(false, 0). std::pair _M_need_rehash(std::size_t __n_bkt, std::size_t __n_elt, std::size_t __n_ins) noexcept { if (__n_elt + __n_ins >= _M_next_resize) { long double __min_bkts = (__n_elt + __n_ins) / (long double)_M_max_load_factor; if (__min_bkts >= __n_bkt) return std::make_pair(true, _M_next_bkt(std::max(__builtin_floor(__min_bkts) + 1, __n_bkt * _S_growth_factor))); _M_next_resize = __builtin_floor(__n_bkt * (long double)_M_max_load_factor); return std::make_pair(false, 0); } else return std::make_pair(false, 0); } typedef std::size_t _State; _State _M_state() const noexcept { return _M_next_resize; } void _M_reset() noexcept { _M_next_resize = 0; } void _M_reset(_State __state) noexcept { _M_next_resize = __state; } static const std::size_t _S_growth_factor = 2; float _M_max_load_factor; std::size_t _M_next_resize; }; // Base classes for std::_Hashtable. We define these base classes // because in some cases we want to do different things depending on // the value of a policy class. In some cases the policy class // affects which member functions and nested typedefs are defined; // we handle that by specializing base class templates. Several of // the base class templates need to access other members of class // template _Hashtable, so we use a variant of the "Curiously // Recurring Template Pattern" (CRTP) technique. /** * Primary class template _Map_base. * * If the hashtable has a value type of the form pair and a * key extraction policy (_ExtractKey) that returns the first part * of the pair, the hashtable gets a mapped_type typedef. If it * satisfies those criteria and also has unique keys, then it also * gets an operator[]. */ template struct _Map_base { }; /// Partial specialization, __unique_keys set to false. template struct _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false> { using mapped_type = typename std::tuple_element<1, _Pair>::type; }; /// Partial specialization, __unique_keys set to true. template struct _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true> { private: using __hashtable_base = __detail::_Hashtable_base<_Key, _Pair, _Select1st, _Equal, _H1, _H2, _Hash, _Traits>; using __hashtable = _Hashtable<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __hash_code = typename __hashtable_base::__hash_code; using __node_type = typename __hashtable_base::__node_type; public: using key_type = typename __hashtable_base::key_type; using iterator = typename __hashtable_base::iterator; using mapped_type = typename std::tuple_element<1, _Pair>::type; mapped_type& operator[](const key_type& __k); mapped_type& operator[](key_type&& __k); // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 761. unordered_map needs an at() member function. mapped_type& at(const key_type& __k); const mapped_type& at(const key_type& __k) const; }; template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: operator[](const key_type& __k) -> mapped_type& { __hashtable* __h = static_cast<__hashtable*>(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) { __p = __h->_M_allocate_node(std::piecewise_construct, std::tuple(__k), std::tuple<>()); return __h->_M_insert_unique_node(__n, __code, __p)->second; } return __p->_M_v().second; } template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: operator[](key_type&& __k) -> mapped_type& { __hashtable* __h = static_cast<__hashtable*>(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) { __p = __h->_M_allocate_node(std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::tuple<>()); return __h->_M_insert_unique_node(__n, __code, __p)->second; } return __p->_M_v().second; } template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: at(const key_type& __k) -> mapped_type& { __hashtable* __h = static_cast<__hashtable*>(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) __throw_out_of_range(__N("_Map_base::at")); return __p->_M_v().second; } template auto _Map_base<_Key, _Pair, _Alloc, _Select1st, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: at(const key_type& __k) const -> const mapped_type& { const __hashtable* __h = static_cast(this); __hash_code __code = __h->_M_hash_code(__k); std::size_t __n = __h->_M_bucket_index(__k, __code); __node_type* __p = __h->_M_find_node(__n, __k, __code); if (!__p) __throw_out_of_range(__N("_Map_base::at")); return __p->_M_v().second; } /** * Primary class template _Insert_base. * * Defines @c insert member functions appropriate to all _Hashtables. */ template struct _Insert_base { protected: using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __hashtable_base = _Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>; using value_type = typename __hashtable_base::value_type; using iterator = typename __hashtable_base::iterator; using const_iterator = typename __hashtable_base::const_iterator; using size_type = typename __hashtable_base::size_type; using __unique_keys = typename __hashtable_base::__unique_keys; using __ireturn_type = typename __hashtable_base::__ireturn_type; using __node_type = _Hash_node<_Value, _Traits::__hash_cached::value>; using __node_alloc_type = __alloc_rebind<_Alloc, __node_type>; using __node_gen_type = _AllocNode<__node_alloc_type>; __hashtable& _M_conjure_hashtable() { return *(static_cast<__hashtable*>(this)); } template void _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter&, true_type); template void _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter&, false_type); public: __ireturn_type insert(const value_type& __v) { __hashtable& __h = _M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(__v, __node_gen, __unique_keys()); } iterator insert(const_iterator __hint, const value_type& __v) { __hashtable& __h = _M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(__hint, __v, __node_gen, __unique_keys()); } void insert(initializer_list __l) { this->insert(__l.begin(), __l.end()); } template void insert(_InputIterator __first, _InputIterator __last) { __hashtable& __h = _M_conjure_hashtable(); __node_gen_type __node_gen(__h); return _M_insert_range(__first, __last, __node_gen, __unique_keys()); } }; template template void _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter& __node_gen, true_type) { size_type __n_elt = __detail::__distance_fw(__first, __last); if (__n_elt == 0) return; __hashtable& __h = _M_conjure_hashtable(); for (; __first != __last; ++__first) { if (__h._M_insert(*__first, __node_gen, __unique_keys(), __n_elt).second) __n_elt = 1; else if (__n_elt != 1) --__n_elt; } } template template void _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>:: _M_insert_range(_InputIterator __first, _InputIterator __last, const _NodeGetter& __node_gen, false_type) { using __rehash_type = typename __hashtable::__rehash_type; using __rehash_state = typename __hashtable::__rehash_state; using pair_type = std::pair; size_type __n_elt = __detail::__distance_fw(__first, __last); if (__n_elt == 0) return; __hashtable& __h = _M_conjure_hashtable(); __rehash_type& __rehash = __h._M_rehash_policy; const __rehash_state& __saved_state = __rehash._M_state(); pair_type __do_rehash = __rehash._M_need_rehash(__h._M_bucket_count, __h._M_element_count, __n_elt); if (__do_rehash.first) __h._M_rehash(__do_rehash.second, __saved_state); for (; __first != __last; ++__first) __h._M_insert(*__first, __node_gen, __unique_keys()); } /** * Primary class template _Insert. * * Defines @c insert member functions that depend on _Hashtable policies, * via partial specializations. */ template struct _Insert; /// Specialization. template struct _Insert<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true> : public _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits> { using __base_type = _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using __hashtable_base = _Hashtable_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, _Hash, _Traits>; using value_type = typename __base_type::value_type; using iterator = typename __base_type::iterator; using const_iterator = typename __base_type::const_iterator; using __unique_keys = typename __base_type::__unique_keys; using __ireturn_type = typename __hashtable_base::__ireturn_type; using __hashtable = typename __base_type::__hashtable; using __node_gen_type = typename __base_type::__node_gen_type; using __base_type::insert; __ireturn_type insert(value_type&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(std::move(__v), __node_gen, __unique_keys()); } iterator insert(const_iterator __hint, value_type&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); __node_gen_type __node_gen(__h); return __h._M_insert(__hint, std::move(__v), __node_gen, __unique_keys()); } }; /// Specialization. template struct _Insert<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false> : public _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits> { using __base_type = _Insert_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; using value_type = typename __base_type::value_type; using iterator = typename __base_type::iterator; using const_iterator = typename __base_type::const_iterator; using __unique_keys = typename __base_type::__unique_keys; using __hashtable = typename __base_type::__hashtable; using __ireturn_type = typename __base_type::__ireturn_type; using __base_type::insert; template using __is_cons = std::is_constructible; template using _IFcons = std::enable_if<__is_cons<_Pair>::value>; template using _IFconsp = typename _IFcons<_Pair>::type; template> __ireturn_type insert(_Pair&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); return __h._M_emplace(__unique_keys(), std::forward<_Pair>(__v)); } template> iterator insert(const_iterator __hint, _Pair&& __v) { __hashtable& __h = this->_M_conjure_hashtable(); return __h._M_emplace(__hint, __unique_keys(), std::forward<_Pair>(__v)); } }; template using __has_load_factor = typename _Policy::__has_load_factor; /** * Primary class template _Rehash_base. * * Give hashtable the max_load_factor functions and reserve iff the * rehash policy supports it. */ template> struct _Rehash_base; /// Specialization when rehash policy doesn't provide load factor management. template struct _Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, std::false_type> { }; /// Specialization when rehash policy provide load factor management. template struct _Rehash_base<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, std::true_type> { using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; float max_load_factor() const noexcept { const __hashtable* __this = static_cast(this); return __this->__rehash_policy().max_load_factor(); } void max_load_factor(float __z) { __hashtable* __this = static_cast<__hashtable*>(this); __this->__rehash_policy(_RehashPolicy(__z)); } void reserve(std::size_t __n) { __hashtable* __this = static_cast<__hashtable*>(this); __this->rehash(__builtin_ceil(__n / max_load_factor())); } }; /** * Primary class template _Hashtable_ebo_helper. * * Helper class using EBO when it is not forbidden (the type is not * final) and when it is worth it (the type is empty.) */ template struct _Hashtable_ebo_helper; /// Specialization using EBO. template struct _Hashtable_ebo_helper<_Nm, _Tp, true> : private _Tp { _Hashtable_ebo_helper() = default; template _Hashtable_ebo_helper(_OtherTp&& __tp) : _Tp(std::forward<_OtherTp>(__tp)) { } static const _Tp& _S_cget(const _Hashtable_ebo_helper& __eboh) { return static_cast(__eboh); } static _Tp& _S_get(_Hashtable_ebo_helper& __eboh) { return static_cast<_Tp&>(__eboh); } }; /// Specialization not using EBO. template struct _Hashtable_ebo_helper<_Nm, _Tp, false> { _Hashtable_ebo_helper() = default; template _Hashtable_ebo_helper(_OtherTp&& __tp) : _M_tp(std::forward<_OtherTp>(__tp)) { } static const _Tp& _S_cget(const _Hashtable_ebo_helper& __eboh) { return __eboh._M_tp; } static _Tp& _S_get(_Hashtable_ebo_helper& __eboh) { return __eboh._M_tp; } private: _Tp _M_tp; }; /** * Primary class template _Local_iterator_base. * * Base class for local iterators, used to iterate within a bucket * but not between buckets. */ template struct _Local_iterator_base; /** * Primary class template _Hash_code_base. * * Encapsulates two policy issues that aren't quite orthogonal. * (1) the difference between using a ranged hash function and using * the combination of a hash function and a range-hashing function. * In the former case we don't have such things as hash codes, so * we have a dummy type as placeholder. * (2) Whether or not we cache hash codes. Caching hash codes is * meaningless if we have a ranged hash function. * * We also put the key extraction objects here, for convenience. * Each specialization derives from one or more of the template * parameters to benefit from Ebo. This is important as this type * is inherited in some cases by the _Local_iterator_base type used * to implement local_iterator and const_local_iterator. As with * any iterator type we prefer to make it as small as possible. * * Primary template is unused except as a hook for specializations. */ template struct _Hash_code_base; /// Specialization: ranged hash function, no caching hash codes. H1 /// and H2 are provided but ignored. We define a dummy hash code type. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false> : private _Hashtable_ebo_helper<0, _ExtractKey>, private _Hashtable_ebo_helper<1, _Hash> { private: using __ebo_extract_key = _Hashtable_ebo_helper<0, _ExtractKey>; using __ebo_hash = _Hashtable_ebo_helper<1, _Hash>; protected: typedef void* __hash_code; typedef _Hash_node<_Value, false> __node_type; // We need the default constructor for the local iterators and _Hashtable // default constructor. _Hash_code_base() = default; _Hash_code_base(const _ExtractKey& __ex, const _H1&, const _H2&, const _Hash& __h) : __ebo_extract_key(__ex), __ebo_hash(__h) { } __hash_code _M_hash_code(const _Key& __key) const { return 0; } std::size_t _M_bucket_index(const _Key& __k, __hash_code, std::size_t __n) const { return _M_ranged_hash()(__k, __n); } std::size_t _M_bucket_index(const __node_type* __p, std::size_t __n) const noexcept( noexcept(declval()(declval(), (std::size_t)0)) ) { return _M_ranged_hash()(_M_extract()(__p->_M_v()), __n); } void _M_store_code(__node_type*, __hash_code) const { } void _M_copy_code(__node_type*, const __node_type*) const { } void _M_swap(_Hash_code_base& __x) { std::swap(_M_extract(), __x._M_extract()); std::swap(_M_ranged_hash(), __x._M_ranged_hash()); } const _ExtractKey& _M_extract() const { return __ebo_extract_key::_S_cget(*this); } _ExtractKey& _M_extract() { return __ebo_extract_key::_S_get(*this); } const _Hash& _M_ranged_hash() const { return __ebo_hash::_S_cget(*this); } _Hash& _M_ranged_hash() { return __ebo_hash::_S_get(*this); } }; // No specialization for ranged hash function while caching hash codes. // That combination is meaningless, and trying to do it is an error. /// Specialization: ranged hash function, cache hash codes. This /// combination is meaningless, so we provide only a declaration /// and no definition. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, true>; /// Specialization: hash function and range-hashing function, no /// caching of hash codes. /// Provides typedef and accessor required by C++ 11. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, false> : private _Hashtable_ebo_helper<0, _ExtractKey>, private _Hashtable_ebo_helper<1, _H1>, private _Hashtable_ebo_helper<2, _H2> { private: using __ebo_extract_key = _Hashtable_ebo_helper<0, _ExtractKey>; using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>; using __ebo_h2 = _Hashtable_ebo_helper<2, _H2>; // Gives the local iterator implementation access to _M_bucket_index(). friend struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, false>; public: typedef _H1 hasher; hasher hash_function() const { return _M_h1(); } protected: typedef std::size_t __hash_code; typedef _Hash_node<_Value, false> __node_type; // We need the default constructor for the local iterators and _Hashtable // default constructor. _Hash_code_base() = default; _Hash_code_base(const _ExtractKey& __ex, const _H1& __h1, const _H2& __h2, const _Default_ranged_hash&) : __ebo_extract_key(__ex), __ebo_h1(__h1), __ebo_h2(__h2) { } __hash_code _M_hash_code(const _Key& __k) const { static_assert(__is_invocable{}, "hash function must be invocable with an argument of key type"); return _M_h1()(__k); } std::size_t _M_bucket_index(const _Key&, __hash_code __c, std::size_t __n) const { return _M_h2()(__c, __n); } std::size_t _M_bucket_index(const __node_type* __p, std::size_t __n) const noexcept( noexcept(declval()(declval())) && noexcept(declval()((__hash_code)0, (std::size_t)0)) ) { return _M_h2()(_M_h1()(_M_extract()(__p->_M_v())), __n); } void _M_store_code(__node_type*, __hash_code) const { } void _M_copy_code(__node_type*, const __node_type*) const { } void _M_swap(_Hash_code_base& __x) { std::swap(_M_extract(), __x._M_extract()); std::swap(_M_h1(), __x._M_h1()); std::swap(_M_h2(), __x._M_h2()); } const _ExtractKey& _M_extract() const { return __ebo_extract_key::_S_cget(*this); } _ExtractKey& _M_extract() { return __ebo_extract_key::_S_get(*this); } const _H1& _M_h1() const { return __ebo_h1::_S_cget(*this); } _H1& _M_h1() { return __ebo_h1::_S_get(*this); } const _H2& _M_h2() const { return __ebo_h2::_S_cget(*this); } _H2& _M_h2() { return __ebo_h2::_S_get(*this); } }; /// Specialization: hash function and range-hashing function, /// caching hash codes. H is provided but ignored. Provides /// typedef and accessor required by C++ 11. template struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, true> : private _Hashtable_ebo_helper<0, _ExtractKey>, private _Hashtable_ebo_helper<1, _H1>, private _Hashtable_ebo_helper<2, _H2> { private: // Gives the local iterator implementation access to _M_h2(). friend struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Default_ranged_hash, true>; using __ebo_extract_key = _Hashtable_ebo_helper<0, _ExtractKey>; using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>; using __ebo_h2 = _Hashtable_ebo_helper<2, _H2>; public: typedef _H1 hasher; hasher hash_function() const { return _M_h1(); } protected: typedef std::size_t __hash_code; typedef _Hash_node<_Value, true> __node_type; // We need the default constructor for _Hashtable default constructor. _Hash_code_base() = default; _Hash_code_base(const _ExtractKey& __ex, const _H1& __h1, const _H2& __h2, const _Default_ranged_hash&) : __ebo_extract_key(__ex), __ebo_h1(__h1), __ebo_h2(__h2) { } __hash_code _M_hash_code(const _Key& __k) const { static_assert(__is_invocable{}, "hash function must be invocable with an argument of key type"); return _M_h1()(__k); } std::size_t _M_bucket_index(const _Key&, __hash_code __c, std::size_t __n) const { return _M_h2()(__c, __n); } std::size_t _M_bucket_index(const __node_type* __p, std::size_t __n) const noexcept( noexcept(declval()((__hash_code)0, (std::size_t)0)) ) { return _M_h2()(__p->_M_hash_code, __n); } void _M_store_code(__node_type* __n, __hash_code __c) const { __n->_M_hash_code = __c; } void _M_copy_code(__node_type* __to, const __node_type* __from) const { __to->_M_hash_code = __from->_M_hash_code; } void _M_swap(_Hash_code_base& __x) { std::swap(_M_extract(), __x._M_extract()); std::swap(_M_h1(), __x._M_h1()); std::swap(_M_h2(), __x._M_h2()); } const _ExtractKey& _M_extract() const { return __ebo_extract_key::_S_cget(*this); } _ExtractKey& _M_extract() { return __ebo_extract_key::_S_get(*this); } const _H1& _M_h1() const { return __ebo_h1::_S_cget(*this); } _H1& _M_h1() { return __ebo_h1::_S_get(*this); } const _H2& _M_h2() const { return __ebo_h2::_S_cget(*this); } _H2& _M_h2() { return __ebo_h2::_S_get(*this); } }; /** * Primary class template _Equal_helper. * */ template struct _Equal_helper; /// Specialization. template struct _Equal_helper<_Key, _Value, _ExtractKey, _Equal, _HashCodeType, true> { static bool _S_equals(const _Equal& __eq, const _ExtractKey& __extract, const _Key& __k, _HashCodeType __c, _Hash_node<_Value, true>* __n) { return __c == __n->_M_hash_code && __eq(__k, __extract(__n->_M_v())); } }; /// Specialization. template struct _Equal_helper<_Key, _Value, _ExtractKey, _Equal, _HashCodeType, false> { static bool _S_equals(const _Equal& __eq, const _ExtractKey& __extract, const _Key& __k, _HashCodeType, _Hash_node<_Value, false>* __n) { return __eq(__k, __extract(__n->_M_v())); } }; /// Partial specialization used when nodes contain a cached hash code. template struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, true> : private _Hashtable_ebo_helper<0, _H2> { protected: using __base_type = _Hashtable_ebo_helper<0, _H2>; using __hash_code_base = _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, true>; _Local_iterator_base() = default; _Local_iterator_base(const __hash_code_base& __base, _Hash_node<_Value, true>* __p, std::size_t __bkt, std::size_t __bkt_count) : __base_type(__base._M_h2()), _M_cur(__p), _M_bucket(__bkt), _M_bucket_count(__bkt_count) { } void _M_incr() { _M_cur = _M_cur->_M_next(); if (_M_cur) { std::size_t __bkt = __base_type::_S_get(*this)(_M_cur->_M_hash_code, _M_bucket_count); if (__bkt != _M_bucket) _M_cur = nullptr; } } _Hash_node<_Value, true>* _M_cur; std::size_t _M_bucket; std::size_t _M_bucket_count; public: const void* _M_curr() const { return _M_cur; } // for equality ops std::size_t _M_get_bucket() const { return _M_bucket; } // for debug mode }; // Uninitialized storage for a _Hash_code_base. // This type is DefaultConstructible and Assignable even if the // _Hash_code_base type isn't, so that _Local_iterator_base<..., false> // can be DefaultConstructible and Assignable. template::value> struct _Hash_code_storage { __gnu_cxx::__aligned_buffer<_Tp> _M_storage; _Tp* _M_h() { return _M_storage._M_ptr(); } const _Tp* _M_h() const { return _M_storage._M_ptr(); } }; // Empty partial specialization for empty _Hash_code_base types. template struct _Hash_code_storage<_Tp, true> { static_assert( std::is_empty<_Tp>::value, "Type must be empty" ); // As _Tp is an empty type there will be no bytes written/read through // the cast pointer, so no strict-aliasing violation. _Tp* _M_h() { return reinterpret_cast<_Tp*>(this); } const _Tp* _M_h() const { return reinterpret_cast(this); } }; template using __hash_code_for_local_iter = _Hash_code_storage<_Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false>>; // Partial specialization used when hash codes are not cached template struct _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false> : __hash_code_for_local_iter<_Key, _Value, _ExtractKey, _H1, _H2, _Hash> { protected: using __hash_code_base = _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, false>; _Local_iterator_base() : _M_bucket_count(-1) { } _Local_iterator_base(const __hash_code_base& __base, _Hash_node<_Value, false>* __p, std::size_t __bkt, std::size_t __bkt_count) : _M_cur(__p), _M_bucket(__bkt), _M_bucket_count(__bkt_count) { _M_init(__base); } ~_Local_iterator_base() { if (_M_bucket_count != -1) _M_destroy(); } _Local_iterator_base(const _Local_iterator_base& __iter) : _M_cur(__iter._M_cur), _M_bucket(__iter._M_bucket), _M_bucket_count(__iter._M_bucket_count) { if (_M_bucket_count != -1) _M_init(*__iter._M_h()); } _Local_iterator_base& operator=(const _Local_iterator_base& __iter) { if (_M_bucket_count != -1) _M_destroy(); _M_cur = __iter._M_cur; _M_bucket = __iter._M_bucket; _M_bucket_count = __iter._M_bucket_count; if (_M_bucket_count != -1) _M_init(*__iter._M_h()); return *this; } void _M_incr() { _M_cur = _M_cur->_M_next(); if (_M_cur) { std::size_t __bkt = this->_M_h()->_M_bucket_index(_M_cur, _M_bucket_count); if (__bkt != _M_bucket) _M_cur = nullptr; } } _Hash_node<_Value, false>* _M_cur; std::size_t _M_bucket; std::size_t _M_bucket_count; void _M_init(const __hash_code_base& __base) { ::new(this->_M_h()) __hash_code_base(__base); } void _M_destroy() { this->_M_h()->~__hash_code_base(); } public: const void* _M_curr() const { return _M_cur; } // for equality ops and debug mode std::size_t _M_get_bucket() const { return _M_bucket; } // for debug mode }; template inline bool operator==(const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __x, const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __y) { return __x._M_curr() == __y._M_curr(); } template inline bool operator!=(const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __x, const _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>& __y) { return __x._M_curr() != __y._M_curr(); } /// local iterators template struct _Local_iterator : public _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache> { private: using __base_type = _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>; using __hash_code_base = typename __base_type::__hash_code_base; public: typedef _Value value_type; typedef typename std::conditional<__constant_iterators, const _Value*, _Value*>::type pointer; typedef typename std::conditional<__constant_iterators, const _Value&, _Value&>::type reference; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Local_iterator() = default; _Local_iterator(const __hash_code_base& __base, _Hash_node<_Value, __cache>* __p, std::size_t __bkt, std::size_t __bkt_count) : __base_type(__base, __p, __bkt, __bkt_count) { } reference operator*() const { return this->_M_cur->_M_v(); } pointer operator->() const { return this->_M_cur->_M_valptr(); } _Local_iterator& operator++() { this->_M_incr(); return *this; } _Local_iterator operator++(int) { _Local_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; /// local const_iterators template struct _Local_const_iterator : public _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache> { private: using __base_type = _Local_iterator_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __cache>; using __hash_code_base = typename __base_type::__hash_code_base; public: typedef _Value value_type; typedef const _Value* pointer; typedef const _Value& reference; typedef std::ptrdiff_t difference_type; typedef std::forward_iterator_tag iterator_category; _Local_const_iterator() = default; _Local_const_iterator(const __hash_code_base& __base, _Hash_node<_Value, __cache>* __p, std::size_t __bkt, std::size_t __bkt_count) : __base_type(__base, __p, __bkt, __bkt_count) { } _Local_const_iterator(const _Local_iterator<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __constant_iterators, __cache>& __x) : __base_type(__x) { } reference operator*() const { return this->_M_cur->_M_v(); } pointer operator->() const { return this->_M_cur->_M_valptr(); } _Local_const_iterator& operator++() { this->_M_incr(); return *this; } _Local_const_iterator operator++(int) { _Local_const_iterator __tmp(*this); this->_M_incr(); return __tmp; } }; /** * Primary class template _Hashtable_base. * * Helper class adding management of _Equal functor to * _Hash_code_base type. * * Base class templates are: * - __detail::_Hash_code_base * - __detail::_Hashtable_ebo_helper */ template struct _Hashtable_base : public _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, _Traits::__hash_cached::value>, private _Hashtable_ebo_helper<0, _Equal> { public: typedef _Key key_type; typedef _Value value_type; typedef _Equal key_equal; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; using __traits_type = _Traits; using __hash_cached = typename __traits_type::__hash_cached; using __constant_iterators = typename __traits_type::__constant_iterators; using __unique_keys = typename __traits_type::__unique_keys; using __hash_code_base = _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, _Hash, __hash_cached::value>; using __hash_code = typename __hash_code_base::__hash_code; using __node_type = typename __hash_code_base::__node_type; using iterator = __detail::_Node_iterator; using const_iterator = __detail::_Node_const_iterator; using local_iterator = __detail::_Local_iterator; using const_local_iterator = __detail::_Local_const_iterator; using __ireturn_type = typename std::conditional<__unique_keys::value, std::pair, iterator>::type; private: using _EqualEBO = _Hashtable_ebo_helper<0, _Equal>; using _EqualHelper = _Equal_helper<_Key, _Value, _ExtractKey, _Equal, __hash_code, __hash_cached::value>; protected: _Hashtable_base() = default; _Hashtable_base(const _ExtractKey& __ex, const _H1& __h1, const _H2& __h2, const _Hash& __hash, const _Equal& __eq) : __hash_code_base(__ex, __h1, __h2, __hash), _EqualEBO(__eq) { } bool _M_equals(const _Key& __k, __hash_code __c, __node_type* __n) const { static_assert(__is_invocable{}, "key equality predicate must be invocable with two arguments of " "key type"); return _EqualHelper::_S_equals(_M_eq(), this->_M_extract(), __k, __c, __n); } void _M_swap(_Hashtable_base& __x) { __hash_code_base::_M_swap(__x); std::swap(_M_eq(), __x._M_eq()); } const _Equal& _M_eq() const { return _EqualEBO::_S_cget(*this); } _Equal& _M_eq() { return _EqualEBO::_S_get(*this); } }; /** * struct _Equality_base. * * Common types and functions for class _Equality. */ struct _Equality_base { protected: template static bool _S_is_permutation(_Uiterator, _Uiterator, _Uiterator); }; // See std::is_permutation in N3068. template bool _Equality_base:: _S_is_permutation(_Uiterator __first1, _Uiterator __last1, _Uiterator __first2) { for (; __first1 != __last1; ++__first1, ++__first2) if (!(*__first1 == *__first2)) break; if (__first1 == __last1) return true; _Uiterator __last2 = __first2; std::advance(__last2, std::distance(__first1, __last1)); for (_Uiterator __it1 = __first1; __it1 != __last1; ++__it1) { _Uiterator __tmp = __first1; while (__tmp != __it1 && !bool(*__tmp == *__it1)) ++__tmp; // We've seen this one before. if (__tmp != __it1) continue; std::ptrdiff_t __n2 = 0; for (__tmp = __first2; __tmp != __last2; ++__tmp) if (*__tmp == *__it1) ++__n2; if (!__n2) return false; std::ptrdiff_t __n1 = 0; for (__tmp = __it1; __tmp != __last1; ++__tmp) if (*__tmp == *__it1) ++__n1; if (__n1 != __n2) return false; } return true; } /** * Primary class template _Equality. * * This is for implementing equality comparison for unordered * containers, per N3068, by John Lakos and Pablo Halpern. * Algorithmically, we follow closely the reference implementations * therein. */ template struct _Equality; /// Specialization. template struct _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true> { using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; bool _M_equal(const __hashtable&) const; }; template bool _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, true>:: _M_equal(const __hashtable& __other) const { const __hashtable* __this = static_cast(this); if (__this->size() != __other.size()) return false; for (auto __itx = __this->begin(); __itx != __this->end(); ++__itx) { const auto __ity = __other.find(_ExtractKey()(*__itx)); if (__ity == __other.end() || !bool(*__ity == *__itx)) return false; } return true; } /// Specialization. template struct _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false> : public _Equality_base { using __hashtable = _Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>; bool _M_equal(const __hashtable&) const; }; template bool _Equality<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits, false>:: _M_equal(const __hashtable& __other) const { const __hashtable* __this = static_cast(this); if (__this->size() != __other.size()) return false; for (auto __itx = __this->begin(); __itx != __this->end();) { const auto __xrange = __this->equal_range(_ExtractKey()(*__itx)); const auto __yrange = __other.equal_range(_ExtractKey()(*__itx)); if (std::distance(__xrange.first, __xrange.second) != std::distance(__yrange.first, __yrange.second)) return false; if (!_S_is_permutation(__xrange.first, __xrange.second, __yrange.first)) return false; __itx = __xrange.second; } return true; } /** * This type deals with all allocation and keeps an allocator instance through * inheritance to benefit from EBO when possible. */ template struct _Hashtable_alloc : private _Hashtable_ebo_helper<0, _NodeAlloc> { private: using __ebo_node_alloc = _Hashtable_ebo_helper<0, _NodeAlloc>; public: using __node_type = typename _NodeAlloc::value_type; using __node_alloc_type = _NodeAlloc; // Use __gnu_cxx to benefit from _S_always_equal and al. using __node_alloc_traits = __gnu_cxx::__alloc_traits<__node_alloc_type>; using __value_alloc_traits = typename __node_alloc_traits::template rebind_traits; using __node_base = __detail::_Hash_node_base; using __bucket_type = __node_base*; using __bucket_alloc_type = __alloc_rebind<__node_alloc_type, __bucket_type>; using __bucket_alloc_traits = std::allocator_traits<__bucket_alloc_type>; _Hashtable_alloc() = default; _Hashtable_alloc(const _Hashtable_alloc&) = default; _Hashtable_alloc(_Hashtable_alloc&&) = default; template _Hashtable_alloc(_Alloc&& __a) : __ebo_node_alloc(std::forward<_Alloc>(__a)) { } __node_alloc_type& _M_node_allocator() { return __ebo_node_alloc::_S_get(*this); } const __node_alloc_type& _M_node_allocator() const { return __ebo_node_alloc::_S_cget(*this); } template __node_type* _M_allocate_node(_Args&&... __args); void _M_deallocate_node(__node_type* __n); // Deallocate the linked list of nodes pointed to by __n void _M_deallocate_nodes(__node_type* __n); __bucket_type* _M_allocate_buckets(std::size_t __n); void _M_deallocate_buckets(__bucket_type*, std::size_t __n); }; // Definitions of class template _Hashtable_alloc's out-of-line member // functions. template template typename _Hashtable_alloc<_NodeAlloc>::__node_type* _Hashtable_alloc<_NodeAlloc>::_M_allocate_node(_Args&&... __args) { auto __nptr = __node_alloc_traits::allocate(_M_node_allocator(), 1); __node_type* __n = std::__to_address(__nptr); __try { ::new ((void*)__n) __node_type; __node_alloc_traits::construct(_M_node_allocator(), __n->_M_valptr(), std::forward<_Args>(__args)...); return __n; } __catch(...) { __node_alloc_traits::deallocate(_M_node_allocator(), __nptr, 1); __throw_exception_again; } } template void _Hashtable_alloc<_NodeAlloc>::_M_deallocate_node(__node_type* __n) { typedef typename __node_alloc_traits::pointer _Ptr; auto __ptr = std::pointer_traits<_Ptr>::pointer_to(*__n); __node_alloc_traits::destroy(_M_node_allocator(), __n->_M_valptr()); __n->~__node_type(); __node_alloc_traits::deallocate(_M_node_allocator(), __ptr, 1); } template void _Hashtable_alloc<_NodeAlloc>::_M_deallocate_nodes(__node_type* __n) { while (__n) { __node_type* __tmp = __n; __n = __n->_M_next(); _M_deallocate_node(__tmp); } } template typename _Hashtable_alloc<_NodeAlloc>::__bucket_type* _Hashtable_alloc<_NodeAlloc>::_M_allocate_buckets(std::size_t __n) { __bucket_alloc_type __alloc(_M_node_allocator()); auto __ptr = __bucket_alloc_traits::allocate(__alloc, __n); __bucket_type* __p = std::__to_address(__ptr); __builtin_memset(__p, 0, __n * sizeof(__bucket_type)); return __p; } template void _Hashtable_alloc<_NodeAlloc>::_M_deallocate_buckets(__bucket_type* __bkts, std::size_t __n) { typedef typename __bucket_alloc_traits::pointer _Ptr; auto __ptr = std::pointer_traits<_Ptr>::pointer_to(*__bkts); __bucket_alloc_type __alloc(_M_node_allocator()); __bucket_alloc_traits::deallocate(__alloc, __ptr, __n); } //@} hashtable-detail } // namespace __detail _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _HASHTABLE_POLICY_H c++/8/bits/stl_tempbuf.h000064400000020230151027430570010722 0ustar00// Temporary buffer implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_tempbuf.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_TEMPBUF_H #define _STL_TEMPBUF_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Allocates a temporary buffer. * @param __len The number of objects of type Tp. * @return See full description. * * Reinventing the wheel, but this time with prettier spokes! * * This function tries to obtain storage for @c __len adjacent Tp * objects. The objects themselves are not constructed, of course. * A pair<> is returned containing the buffer s address and * capacity (in the units of sizeof(_Tp)), or a pair of 0 values if * no storage can be obtained. Note that the capacity obtained * may be less than that requested if the memory is unavailable; * you should compare len with the .second return value. * * Provides the nothrow exception guarantee. */ template pair<_Tp*, ptrdiff_t> get_temporary_buffer(ptrdiff_t __len) _GLIBCXX_NOEXCEPT { const ptrdiff_t __max = __gnu_cxx::__numeric_traits::__max / sizeof(_Tp); if (__len > __max) __len = __max; while (__len > 0) { _Tp* __tmp = static_cast<_Tp*>(::operator new(__len * sizeof(_Tp), std::nothrow)); if (__tmp != 0) return std::pair<_Tp*, ptrdiff_t>(__tmp, __len); __len /= 2; } return std::pair<_Tp*, ptrdiff_t>(static_cast<_Tp*>(0), 0); } /** * @brief The companion to get_temporary_buffer(). * @param __p A buffer previously allocated by get_temporary_buffer. * @return None. * * Frees the memory pointed to by __p. */ template inline void return_temporary_buffer(_Tp* __p) { ::operator delete(__p, std::nothrow); } /** * This class is used in two places: stl_algo.h and ext/memory, * where it is wrapped as the temporary_buffer class. See * temporary_buffer docs for more notes. */ template class _Temporary_buffer { // concept requirements __glibcxx_class_requires(_ForwardIterator, _ForwardIteratorConcept) public: typedef _Tp value_type; typedef value_type* pointer; typedef pointer iterator; typedef ptrdiff_t size_type; protected: size_type _M_original_len; size_type _M_len; pointer _M_buffer; public: /// As per Table mumble. size_type size() const { return _M_len; } /// Returns the size requested by the constructor; may be >size(). size_type requested_size() const { return _M_original_len; } /// As per Table mumble. iterator begin() { return _M_buffer; } /// As per Table mumble. iterator end() { return _M_buffer + _M_len; } /** * Constructs a temporary buffer of a size somewhere between * zero and the size of the given range. */ _Temporary_buffer(_ForwardIterator __first, _ForwardIterator __last); ~_Temporary_buffer() { std::_Destroy(_M_buffer, _M_buffer + _M_len); std::return_temporary_buffer(_M_buffer); } private: // Disable copy constructor and assignment operator. _Temporary_buffer(const _Temporary_buffer&); void operator=(const _Temporary_buffer&); }; template struct __uninitialized_construct_buf_dispatch { template static void __ucr(_Pointer __first, _Pointer __last, _ForwardIterator __seed) { if(__first == __last) return; _Pointer __cur = __first; __try { std::_Construct(std::__addressof(*__first), _GLIBCXX_MOVE(*__seed)); _Pointer __prev = __cur; ++__cur; for(; __cur != __last; ++__cur, ++__prev) std::_Construct(std::__addressof(*__cur), _GLIBCXX_MOVE(*__prev)); *__seed = _GLIBCXX_MOVE(*__prev); } __catch(...) { std::_Destroy(__first, __cur); __throw_exception_again; } } }; template<> struct __uninitialized_construct_buf_dispatch { template static void __ucr(_Pointer, _Pointer, _ForwardIterator) { } }; // Constructs objects in the range [first, last). // Note that while these new objects will take valid values, // their exact value is not defined. In particular they may // be 'moved from'. // // While *__seed may be altered during this algorithm, it will have // the same value when the algorithm finishes, unless one of the // constructions throws. // // Requirements: _Pointer::value_type(_Tp&&) is valid. template inline void __uninitialized_construct_buf(_Pointer __first, _Pointer __last, _ForwardIterator __seed) { typedef typename std::iterator_traits<_Pointer>::value_type _ValueType; std::__uninitialized_construct_buf_dispatch< __has_trivial_constructor(_ValueType)>:: __ucr(__first, __last, __seed); } template _Temporary_buffer<_ForwardIterator, _Tp>:: _Temporary_buffer(_ForwardIterator __first, _ForwardIterator __last) : _M_original_len(std::distance(__first, __last)), _M_len(0), _M_buffer(0) { __try { std::pair __p(std::get_temporary_buffer< value_type>(_M_original_len)); _M_buffer = __p.first; _M_len = __p.second; if (_M_buffer) std::__uninitialized_construct_buf(_M_buffer, _M_buffer + _M_len, __first); } __catch(...) { std::return_temporary_buffer(_M_buffer); _M_buffer = 0; _M_len = 0; __throw_exception_again; } } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_TEMPBUF_H */ c++/8/bits/streambuf_iterator.h000064400000032676151027430570012320 0ustar00// Streambuf iterators // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/streambuf_iterator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iterator} */ #ifndef _STREAMBUF_ITERATOR_H #define _STREAMBUF_ITERATOR_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup iterators * @{ */ // 24.5.3 Template class istreambuf_iterator /// Provides input iterator semantics for streambufs. template class istreambuf_iterator : public iterator= 201103L // LWG 445. _CharT> #else _CharT&> #endif { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _Traits traits_type; typedef typename _Traits::int_type int_type; typedef basic_streambuf<_CharT, _Traits> streambuf_type; typedef basic_istream<_CharT, _Traits> istream_type; //@} template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, ostreambuf_iterator<_CharT2> >::__type copy(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, ostreambuf_iterator<_CharT2>); template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, _CharT2*>::__type __copy_move_a2(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, _CharT2*); template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, istreambuf_iterator<_CharT2> >::__type find(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, const _CharT2&); template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, void>::__type advance(istreambuf_iterator<_CharT2>&, _Distance); private: // 24.5.3 istreambuf_iterator // p 1 // If the end of stream is reached (streambuf_type::sgetc() // returns traits_type::eof()), the iterator becomes equal to // the "end of stream" iterator value. // NB: This implementation assumes the "end of stream" value // is EOF, or -1. mutable streambuf_type* _M_sbuf; int_type _M_c; public: /// Construct end of input stream iterator. _GLIBCXX_CONSTEXPR istreambuf_iterator() _GLIBCXX_USE_NOEXCEPT : _M_sbuf(0), _M_c(traits_type::eof()) { } #if __cplusplus >= 201103L istreambuf_iterator(const istreambuf_iterator&) noexcept = default; ~istreambuf_iterator() = default; #endif /// Construct start of input stream iterator. istreambuf_iterator(istream_type& __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s.rdbuf()), _M_c(traits_type::eof()) { } /// Construct start of streambuf iterator. istreambuf_iterator(streambuf_type* __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s), _M_c(traits_type::eof()) { } /// Return the current character pointed to by iterator. This returns /// streambuf.sgetc(). It cannot be assigned. NB: The result of /// operator*() on an end of stream is undefined. char_type operator*() const { int_type __c = _M_get(); #ifdef _GLIBCXX_DEBUG_PEDANTIC // Dereferencing a past-the-end istreambuf_iterator is a // libstdc++ extension __glibcxx_requires_cond(!_S_is_eof(__c), _M_message(__gnu_debug::__msg_deref_istreambuf) ._M_iterator(*this)); #endif return traits_type::to_char_type(__c); } /// Advance the iterator. Calls streambuf.sbumpc(). istreambuf_iterator& operator++() { __glibcxx_requires_cond(_M_sbuf && (!_S_is_eof(_M_c) || !_S_is_eof(_M_sbuf->sgetc())), _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(*this)); _M_sbuf->sbumpc(); _M_c = traits_type::eof(); return *this; } /// Advance the iterator. Calls streambuf.sbumpc(). istreambuf_iterator operator++(int) { __glibcxx_requires_cond(_M_sbuf && (!_S_is_eof(_M_c) || !_S_is_eof(_M_sbuf->sgetc())), _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(*this)); istreambuf_iterator __old = *this; __old._M_c = _M_sbuf->sbumpc(); _M_c = traits_type::eof(); return __old; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 110 istreambuf_iterator::equal not const // NB: there is also number 111 (NAD) relevant to this function. /// Return true both iterators are end or both are not end. bool equal(const istreambuf_iterator& __b) const { return _M_at_eof() == __b._M_at_eof(); } private: int_type _M_get() const { int_type __ret = _M_c; if (_M_sbuf && _S_is_eof(__ret) && _S_is_eof(__ret = _M_sbuf->sgetc())) _M_sbuf = 0; return __ret; } bool _M_at_eof() const { return _S_is_eof(_M_get()); } static bool _S_is_eof(int_type __c) { const int_type __eof = traits_type::eof(); return traits_type::eq_int_type(__c, __eof); } }; template inline bool operator==(const istreambuf_iterator<_CharT, _Traits>& __a, const istreambuf_iterator<_CharT, _Traits>& __b) { return __a.equal(__b); } template inline bool operator!=(const istreambuf_iterator<_CharT, _Traits>& __a, const istreambuf_iterator<_CharT, _Traits>& __b) { return !__a.equal(__b); } /// Provides output iterator semantics for streambufs. template class ostreambuf_iterator : public iterator { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _Traits traits_type; typedef basic_streambuf<_CharT, _Traits> streambuf_type; typedef basic_ostream<_CharT, _Traits> ostream_type; //@} template friend typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, ostreambuf_iterator<_CharT2> >::__type copy(istreambuf_iterator<_CharT2>, istreambuf_iterator<_CharT2>, ostreambuf_iterator<_CharT2>); private: streambuf_type* _M_sbuf; bool _M_failed; public: /// Construct output iterator from ostream. ostreambuf_iterator(ostream_type& __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s.rdbuf()), _M_failed(!_M_sbuf) { } /// Construct output iterator from streambuf. ostreambuf_iterator(streambuf_type* __s) _GLIBCXX_USE_NOEXCEPT : _M_sbuf(__s), _M_failed(!_M_sbuf) { } /// Write character to streambuf. Calls streambuf.sputc(). ostreambuf_iterator& operator=(_CharT __c) { if (!_M_failed && _Traits::eq_int_type(_M_sbuf->sputc(__c), _Traits::eof())) _M_failed = true; return *this; } /// Return *this. ostreambuf_iterator& operator*() { return *this; } /// Return *this. ostreambuf_iterator& operator++(int) { return *this; } /// Return *this. ostreambuf_iterator& operator++() { return *this; } /// Return true if previous operator=() failed. bool failed() const _GLIBCXX_USE_NOEXCEPT { return _M_failed; } ostreambuf_iterator& _M_put(const _CharT* __ws, streamsize __len) { if (__builtin_expect(!_M_failed, true) && __builtin_expect(this->_M_sbuf->sputn(__ws, __len) != __len, false)) _M_failed = true; return *this; } }; // Overloads for streambuf iterators. template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT> >::__type copy(istreambuf_iterator<_CharT> __first, istreambuf_iterator<_CharT> __last, ostreambuf_iterator<_CharT> __result) { if (__first._M_sbuf && !__last._M_sbuf && !__result._M_failed) { bool __ineof; __copy_streambufs_eof(__first._M_sbuf, __result._M_sbuf, __ineof); if (!__ineof) __result._M_failed = true; } return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT> >::__type __copy_move_a2(_CharT* __first, _CharT* __last, ostreambuf_iterator<_CharT> __result) { const streamsize __num = __last - __first; if (__num > 0) __result._M_put(__first, __num); return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, ostreambuf_iterator<_CharT> >::__type __copy_move_a2(const _CharT* __first, const _CharT* __last, ostreambuf_iterator<_CharT> __result) { const streamsize __num = __last - __first; if (__num > 0) __result._M_put(__first, __num); return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, _CharT*>::__type __copy_move_a2(istreambuf_iterator<_CharT> __first, istreambuf_iterator<_CharT> __last, _CharT* __result) { typedef istreambuf_iterator<_CharT> __is_iterator_type; typedef typename __is_iterator_type::traits_type traits_type; typedef typename __is_iterator_type::streambuf_type streambuf_type; typedef typename traits_type::int_type int_type; if (__first._M_sbuf && !__last._M_sbuf) { streambuf_type* __sb = __first._M_sbuf; int_type __c = __sb->sgetc(); while (!traits_type::eq_int_type(__c, traits_type::eof())) { const streamsize __n = __sb->egptr() - __sb->gptr(); if (__n > 1) { traits_type::copy(__result, __sb->gptr(), __n); __sb->__safe_gbump(__n); __result += __n; __c = __sb->underflow(); } else { *__result++ = traits_type::to_char_type(__c); __c = __sb->snextc(); } } } return __result; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, istreambuf_iterator<_CharT> >::__type find(istreambuf_iterator<_CharT> __first, istreambuf_iterator<_CharT> __last, const _CharT& __val) { typedef istreambuf_iterator<_CharT> __is_iterator_type; typedef typename __is_iterator_type::traits_type traits_type; typedef typename __is_iterator_type::streambuf_type streambuf_type; typedef typename traits_type::int_type int_type; const int_type __eof = traits_type::eof(); if (__first._M_sbuf && !__last._M_sbuf) { const int_type __ival = traits_type::to_int_type(__val); streambuf_type* __sb = __first._M_sbuf; int_type __c = __sb->sgetc(); while (!traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __ival)) { streamsize __n = __sb->egptr() - __sb->gptr(); if (__n > 1) { const _CharT* __p = traits_type::find(__sb->gptr(), __n, __val); if (__p) __n = __p - __sb->gptr(); __sb->__safe_gbump(__n); __c = __sb->sgetc(); } else __c = __sb->snextc(); } __first._M_c = __eof; } return __first; } template typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, void>::__type advance(istreambuf_iterator<_CharT>& __i, _Distance __n) { if (__n == 0) return; __glibcxx_assert(__n > 0); __glibcxx_requires_cond(!__i._M_at_eof(), _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(__i)); typedef istreambuf_iterator<_CharT> __is_iterator_type; typedef typename __is_iterator_type::traits_type traits_type; typedef typename __is_iterator_type::streambuf_type streambuf_type; typedef typename traits_type::int_type int_type; const int_type __eof = traits_type::eof(); streambuf_type* __sb = __i._M_sbuf; while (__n > 0) { streamsize __size = __sb->egptr() - __sb->gptr(); if (__size > __n) { __sb->__safe_gbump(__n); break; } __sb->__safe_gbump(__size); __n -= __size; if (traits_type::eq_int_type(__sb->underflow(), __eof)) { __glibcxx_requires_cond(__n == 0, _M_message(__gnu_debug::__msg_inc_istreambuf) ._M_iterator(__i)); break; } } __i._M_c = __eof; } // @} group iterators _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/locale_facets.h000064400000264250151027430570011176 0ustar00// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_FACETS_H #define _LOCALE_FACETS_H 1 #pragma GCC system_header #include // For wctype_t #include #include #include #include // For ios_base, ios_base::iostate #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // NB: Don't instantiate required wchar_t facets if no wchar_t support. #ifdef _GLIBCXX_USE_WCHAR_T # define _GLIBCXX_NUM_FACETS 28 # define _GLIBCXX_NUM_CXX11_FACETS 16 #else # define _GLIBCXX_NUM_FACETS 14 # define _GLIBCXX_NUM_CXX11_FACETS 8 #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 # define _GLIBCXX_NUM_UNICODE_FACETS 2 #else # define _GLIBCXX_NUM_UNICODE_FACETS 0 #endif // Convert string to numeric value of type _Tp and store results. // NB: This is specialized for all required types, there is no // generic definition. template void __convert_to_v(const char*, _Tp&, ios_base::iostate&, const __c_locale&) throw(); // Explicit specializations for required types. template<> void __convert_to_v(const char*, float&, ios_base::iostate&, const __c_locale&) throw(); template<> void __convert_to_v(const char*, double&, ios_base::iostate&, const __c_locale&) throw(); template<> void __convert_to_v(const char*, long double&, ios_base::iostate&, const __c_locale&) throw(); // NB: __pad is a struct, rather than a function, so it can be // partially-specialized. template struct __pad { static void _S_pad(ios_base& __io, _CharT __fill, _CharT* __news, const _CharT* __olds, streamsize __newlen, streamsize __oldlen); }; // Used by both numeric and monetary facets. // Inserts "group separator" characters into an array of characters. // It's recursive, one iteration per group. It moves the characters // in the buffer this way: "xxxx12345" -> "12,345xxx". Call this // only with __gsize != 0. template _CharT* __add_grouping(_CharT* __s, _CharT __sep, const char* __gbeg, size_t __gsize, const _CharT* __first, const _CharT* __last); // This template permits specializing facet output code for // ostreambuf_iterator. For ostreambuf_iterator, sputn is // significantly more efficient than incrementing iterators. template inline ostreambuf_iterator<_CharT> __write(ostreambuf_iterator<_CharT> __s, const _CharT* __ws, int __len) { __s._M_put(__ws, __len); return __s; } // This is the unspecialized form of the template. template inline _OutIter __write(_OutIter __s, const _CharT* __ws, int __len) { for (int __j = 0; __j < __len; __j++, ++__s) *__s = __ws[__j]; return __s; } // 22.2.1.1 Template class ctype // Include host and configuration specific ctype enums for ctype_base. /** * @brief Common base for ctype facet * * This template class provides implementations of the public functions * that forward to the protected virtual functions. * * This template also provides abstract stubs for the protected virtual * functions. */ template class __ctype_abstract_base : public locale::facet, public ctype_base { public: // Types: /// Typedef for the template parameter typedef _CharT char_type; /** * @brief Test char_type classification. * * This function finds a mask M for @a __c and compares it to * mask @a __m. It does so by returning the value of * ctype::do_is(). * * @param __c The char_type to compare the mask of. * @param __m The mask to compare against. * @return (M & __m) != 0. */ bool is(mask __m, char_type __c) const { return this->do_is(__m, __c); } /** * @brief Return a mask array. * * This function finds the mask for each char_type in the range [lo,hi) * and successively writes it to vec. vec must have as many elements * as the char array. It does so by returning the value of * ctype::do_is(). * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ const char_type* is(const char_type *__lo, const char_type *__hi, mask *__vec) const { return this->do_is(__lo, __hi, __vec); } /** * @brief Find char_type matching a mask * * This function searches for and returns the first char_type c in * [lo,hi) for which is(m,c) is true. It does so by returning * ctype::do_scan_is(). * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to matching char_type if found, else @a __hi. */ const char_type* scan_is(mask __m, const char_type* __lo, const char_type* __hi) const { return this->do_scan_is(__m, __lo, __hi); } /** * @brief Find char_type not matching a mask * * This function searches for and returns the first char_type c in * [lo,hi) for which is(m,c) is false. It does so by returning * ctype::do_scan_not(). * * @param __m The mask to compare against. * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return Pointer to non-matching char if found, else @a __hi. */ const char_type* scan_not(mask __m, const char_type* __lo, const char_type* __hi) const { return this->do_scan_not(__m, __lo, __hi); } /** * @brief Convert to uppercase. * * This function converts the argument to uppercase if possible. * If not possible (for example, '2'), returns the argument. It does * so by returning ctype::do_toupper(). * * @param __c The char_type to convert. * @return The uppercase char_type if convertible, else @a __c. */ char_type toupper(char_type __c) const { return this->do_toupper(__c); } /** * @brief Convert array to uppercase. * * This function converts each char_type in the range [lo,hi) to * uppercase if possible. Other elements remain untouched. It does so * by returning ctype:: do_toupper(lo, hi). * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* toupper(char_type *__lo, const char_type* __hi) const { return this->do_toupper(__lo, __hi); } /** * @brief Convert to lowercase. * * This function converts the argument to lowercase if possible. If * not possible (for example, '2'), returns the argument. It does so * by returning ctype::do_tolower(c). * * @param __c The char_type to convert. * @return The lowercase char_type if convertible, else @a __c. */ char_type tolower(char_type __c) const { return this->do_tolower(__c); } /** * @brief Convert array to lowercase. * * This function converts each char_type in the range [__lo,__hi) to * lowercase if possible. Other elements remain untouched. It does so * by returning ctype:: do_tolower(__lo, __hi). * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* tolower(char_type* __lo, const char_type* __hi) const { return this->do_tolower(__lo, __hi); } /** * @brief Widen char to char_type * * This function converts the char argument to char_type using the * simplest reasonable transformation. It does so by returning * ctype::do_widen(c). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted char_type. */ char_type widen(char __c) const { return this->do_widen(__c); } /** * @brief Widen array to char_type * * This function converts each char in the input to char_type using the * simplest reasonable transformation. It does so by returning * ctype::do_widen(c). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ const char* widen(const char* __lo, const char* __hi, char_type* __to) const { return this->do_widen(__lo, __hi, __to); } /** * @brief Narrow char_type to char * * This function converts the char_type to char using the simplest * reasonable transformation. If the conversion fails, dfault is * returned instead. It does so by returning * ctype::do_narrow(__c). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char_type to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ char narrow(char_type __c, char __dfault) const { return this->do_narrow(__c, __dfault); } /** * @brief Narrow array to char array * * This function converts each char_type in the input to char using the * simplest reasonable transformation and writes the results to the * destination array. For any char_type in the input that cannot be * converted, @a dfault is used instead. It does so by returning * ctype::do_narrow(__lo, __hi, __dfault, __to). * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ const char_type* narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const { return this->do_narrow(__lo, __hi, __dfault, __to); } protected: explicit __ctype_abstract_base(size_t __refs = 0): facet(__refs) { } virtual ~__ctype_abstract_base() { } /** * @brief Test char_type classification. * * This function finds a mask M for @a c and compares it to mask @a m. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __c The char_type to find the mask of. * @param __m The mask to compare against. * @return (M & __m) != 0. */ virtual bool do_is(mask __m, char_type __c) const = 0; /** * @brief Return a mask array. * * This function finds the mask for each char_type in the range [lo,hi) * and successively writes it to vec. vec must have as many elements * as the input. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const = 0; /** * @brief Find char_type matching mask * * This function searches for and returns the first char_type c in * [__lo,__hi) for which is(__m,c) is true. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a matching char_type if found, else @a __hi. */ virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const = 0; /** * @brief Find char_type not matching mask * * This function searches for and returns a pointer to the first * char_type c of [lo,hi) for which is(m,c) is false. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a non-matching char_type if found, else @a __hi. */ virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const = 0; /** * @brief Convert to uppercase. * * This virtual function converts the char_type argument to uppercase * if possible. If not possible (for example, '2'), returns the * argument. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __c The char_type to convert. * @return The uppercase char_type if convertible, else @a __c. */ virtual char_type do_toupper(char_type __c) const = 0; /** * @brief Convert array to uppercase. * * This virtual function converts each char_type in the range [__lo,__hi) * to uppercase if possible. Other elements remain untouched. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const = 0; /** * @brief Convert to lowercase. * * This virtual function converts the argument to lowercase if * possible. If not possible (for example, '2'), returns the argument. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __c The char_type to convert. * @return The lowercase char_type if convertible, else @a __c. */ virtual char_type do_tolower(char_type __c) const = 0; /** * @brief Convert array to lowercase. * * This virtual function converts each char_type in the range [__lo,__hi) * to lowercase if possible. Other elements remain untouched. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const = 0; /** * @brief Widen char * * This virtual function converts the char to char_type using the * simplest reasonable transformation. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted char_type */ virtual char_type do_widen(char __c) const = 0; /** * @brief Widen char array * * This function converts each char in the input to char_type using the * simplest reasonable transformation. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __to) const = 0; /** * @brief Narrow char_type to char * * This virtual function converts the argument to char using the * simplest reasonable transformation. If the conversion fails, dfault * is returned instead. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char_type to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ virtual char do_narrow(char_type __c, char __dfault) const = 0; /** * @brief Narrow char_type array to char * * This virtual function converts each char_type in the range * [__lo,__hi) to char using the simplest reasonable * transformation and writes the results to the destination * array. For any element in the input that cannot be * converted, @a __dfault is used instead. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const = 0; }; /** * @brief Primary class template ctype facet. * @ingroup locales * * This template class defines classification and conversion functions for * character sets. It wraps cctype functionality. Ctype gets used by * streams for many I/O operations. * * This template provides the protected virtual functions the developer * will have to replace in a derived class or specialization to make a * working facet. The public functions that access them are defined in * __ctype_abstract_base, to allow for implementation flexibility. See * ctype for an example. The functions are documented in * __ctype_abstract_base. * * Note: implementations are provided for all the protected virtual * functions, but will likely not be useful. */ template class ctype : public __ctype_abstract_base<_CharT> { public: // Types: typedef _CharT char_type; typedef typename __ctype_abstract_base<_CharT>::mask mask; /// The facet id for ctype static locale::id id; explicit ctype(size_t __refs = 0) : __ctype_abstract_base<_CharT>(__refs) { } protected: virtual ~ctype(); virtual bool do_is(mask __m, char_type __c) const; virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; virtual char_type do_toupper(char_type __c) const; virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; virtual char_type do_tolower(char_type __c) const; virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; virtual char_type do_widen(char __c) const; virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __dest) const; virtual char do_narrow(char_type, char __dfault) const; virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const; }; template locale::id ctype<_CharT>::id; /** * @brief The ctype specialization. * @ingroup locales * * This class defines classification and conversion functions for * the char type. It gets used by char streams for many I/O * operations. The char specialization provides a number of * optimizations as well. */ template<> class ctype : public locale::facet, public ctype_base { public: // Types: /// Typedef for the template parameter char. typedef char char_type; protected: // Data Members: __c_locale _M_c_locale_ctype; bool _M_del; __to_type _M_toupper; __to_type _M_tolower; const mask* _M_table; mutable char _M_widen_ok; mutable char _M_widen[1 + static_cast(-1)]; mutable char _M_narrow[1 + static_cast(-1)]; mutable char _M_narrow_ok; // 0 uninitialized, 1 init, // 2 memcpy can't be used public: /// The facet id for ctype static locale::id id; /// The size of the mask table. It is SCHAR_MAX + 1. static const size_t table_size = 1 + static_cast(-1); /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __table If non-zero, table is used as the per-char mask. * Else classic_table() is used. * @param __del If true, passes ownership of table to this facet. * @param __refs Passed to the base facet class. */ explicit ctype(const mask* __table = 0, bool __del = false, size_t __refs = 0); /** * @brief Constructor performs static initialization. * * This constructor is used to construct the initial C locale facet. * * @param __cloc Handle to C locale data. * @param __table If non-zero, table is used as the per-char mask. * @param __del If true, passes ownership of table to this facet. * @param __refs Passed to the base facet class. */ explicit ctype(__c_locale __cloc, const mask* __table = 0, bool __del = false, size_t __refs = 0); /** * @brief Test char classification. * * This function compares the mask table[c] to @a __m. * * @param __c The char to compare the mask of. * @param __m The mask to compare against. * @return True if __m & table[__c] is true, false otherwise. */ inline bool is(mask __m, char __c) const; /** * @brief Return a mask array. * * This function finds the mask for each char in the range [lo, hi) and * successively writes it to vec. vec must have as many elements as * the char array. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ inline const char* is(const char* __lo, const char* __hi, mask* __vec) const; /** * @brief Find char matching a mask * * This function searches for and returns the first char in [lo,hi) for * which is(m,char) is true. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a matching char if found, else @a __hi. */ inline const char* scan_is(mask __m, const char* __lo, const char* __hi) const; /** * @brief Find char not matching a mask * * This function searches for and returns a pointer to the first char * in [__lo,__hi) for which is(m,char) is false. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a non-matching char if found, else @a __hi. */ inline const char* scan_not(mask __m, const char* __lo, const char* __hi) const; /** * @brief Convert to uppercase. * * This function converts the char argument to uppercase if possible. * If not possible (for example, '2'), returns the argument. * * toupper() acts as if it returns ctype::do_toupper(c). * do_toupper() must always return the same result for the same input. * * @param __c The char to convert. * @return The uppercase char if convertible, else @a __c. */ char_type toupper(char_type __c) const { return this->do_toupper(__c); } /** * @brief Convert array to uppercase. * * This function converts each char in the range [__lo,__hi) to uppercase * if possible. Other chars remain untouched. * * toupper() acts as if it returns ctype:: do_toupper(__lo, __hi). * do_toupper() must always return the same result for the same input. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* toupper(char_type *__lo, const char_type* __hi) const { return this->do_toupper(__lo, __hi); } /** * @brief Convert to lowercase. * * This function converts the char argument to lowercase if possible. * If not possible (for example, '2'), returns the argument. * * tolower() acts as if it returns ctype::do_tolower(__c). * do_tolower() must always return the same result for the same input. * * @param __c The char to convert. * @return The lowercase char if convertible, else @a __c. */ char_type tolower(char_type __c) const { return this->do_tolower(__c); } /** * @brief Convert array to lowercase. * * This function converts each char in the range [lo,hi) to lowercase * if possible. Other chars remain untouched. * * tolower() acts as if it returns ctype:: do_tolower(__lo, __hi). * do_tolower() must always return the same result for the same input. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return @a __hi. */ const char_type* tolower(char_type* __lo, const char_type* __hi) const { return this->do_tolower(__lo, __hi); } /** * @brief Widen char * * This function converts the char to char_type using the simplest * reasonable transformation. For an underived ctype facet, the * argument will be returned unchanged. * * This function works as if it returns ctype::do_widen(c). * do_widen() must always return the same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted character. */ char_type widen(char __c) const { if (_M_widen_ok) return _M_widen[static_cast(__c)]; this->_M_widen_init(); return this->do_widen(__c); } /** * @brief Widen char array * * This function converts each char in the input to char using the * simplest reasonable transformation. For an underived ctype * facet, the argument will be copied unchanged. * * This function works as if it returns ctype::do_widen(c). * do_widen() must always return the same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ const char* widen(const char* __lo, const char* __hi, char_type* __to) const { if (_M_widen_ok == 1) { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } if (!_M_widen_ok) _M_widen_init(); return this->do_widen(__lo, __hi, __to); } /** * @brief Narrow char * * This function converts the char to char using the simplest * reasonable transformation. If the conversion fails, dfault is * returned instead. For an underived ctype facet, @a c * will be returned unchanged. * * This function works as if it returns ctype::do_narrow(c). * do_narrow() must always return the same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @param __dfault Char to return if conversion fails. * @return The converted character. */ char narrow(char_type __c, char __dfault) const { if (_M_narrow[static_cast(__c)]) return _M_narrow[static_cast(__c)]; const char __t = do_narrow(__c, __dfault); if (__t != __dfault) _M_narrow[static_cast(__c)] = __t; return __t; } /** * @brief Narrow char array * * This function converts each char in the input to char using the * simplest reasonable transformation and writes the results to the * destination array. For any char in the input that cannot be * converted, @a dfault is used instead. For an underived ctype * facet, the argument will be copied unchanged. * * This function works as if it returns ctype::do_narrow(lo, hi, * dfault, to). do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ const char_type* narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const { if (__builtin_expect(_M_narrow_ok == 1, true)) { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } if (!_M_narrow_ok) _M_narrow_init(); return this->do_narrow(__lo, __hi, __dfault, __to); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 695. ctype::classic_table() not accessible. /// Returns a pointer to the mask table provided to the constructor, or /// the default from classic_table() if none was provided. const mask* table() const throw() { return _M_table; } /// Returns a pointer to the C locale mask table. static const mask* classic_table() throw(); protected: /** * @brief Destructor. * * This function deletes table() if @a del was true in the * constructor. */ virtual ~ctype(); /** * @brief Convert to uppercase. * * This virtual function converts the char argument to uppercase if * possible. If not possible (for example, '2'), returns the argument. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __c The char to convert. * @return The uppercase char if convertible, else @a __c. */ virtual char_type do_toupper(char_type __c) const; /** * @brief Convert array to uppercase. * * This virtual function converts each char in the range [lo,hi) to * uppercase if possible. Other chars remain untouched. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; /** * @brief Convert to lowercase. * * This virtual function converts the char argument to lowercase if * possible. If not possible (for example, '2'), returns the argument. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __c The char to convert. * @return The lowercase char if convertible, else @a __c. */ virtual char_type do_tolower(char_type __c) const; /** * @brief Convert array to lowercase. * * This virtual function converts each char in the range [lo,hi) to * lowercase if possible. Other chars remain untouched. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __lo Pointer to first char in range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; /** * @brief Widen char * * This virtual function converts the char to char using the simplest * reasonable transformation. For an underived ctype facet, the * argument will be returned unchanged. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted character. */ virtual char_type do_widen(char __c) const { return __c; } /** * @brief Widen char array * * This function converts each char in the range [lo,hi) to char using * the simplest reasonable transformation. For an underived * ctype facet, the argument will be copied unchanged. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __to) const { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } /** * @brief Narrow char * * This virtual function converts the char to char using the simplest * reasonable transformation. If the conversion fails, dfault is * returned instead. For an underived ctype facet, @a c will be * returned unchanged. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ virtual char do_narrow(char_type __c, char __dfault __attribute__((__unused__))) const { return __c; } /** * @brief Narrow char array to char array * * This virtual function converts each char in the range [lo,hi) to * char using the simplest reasonable transformation and writes the * results to the destination array. For any char in the input that * cannot be converted, @a dfault is used instead. For an underived * ctype facet, the argument will be copied unchanged. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault __attribute__((__unused__)), char* __to) const { if (__builtin_expect(__hi != __lo, true)) __builtin_memcpy(__to, __lo, __hi - __lo); return __hi; } private: void _M_narrow_init() const; void _M_widen_init() const; }; #ifdef _GLIBCXX_USE_WCHAR_T /** * @brief The ctype specialization. * @ingroup locales * * This class defines classification and conversion functions for the * wchar_t type. It gets used by wchar_t streams for many I/O operations. * The wchar_t specialization provides a number of optimizations as well. * * ctype inherits its public methods from * __ctype_abstract_base. */ template<> class ctype : public __ctype_abstract_base { public: // Types: /// Typedef for the template parameter wchar_t. typedef wchar_t char_type; typedef wctype_t __wmask_type; protected: __c_locale _M_c_locale_ctype; // Pre-computed narrowed and widened chars. bool _M_narrow_ok; char _M_narrow[128]; wint_t _M_widen[1 + static_cast(-1)]; // Pre-computed elements for do_is. mask _M_bit[16]; __wmask_type _M_wmask[16]; public: // Data Members: /// The facet id for ctype static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit ctype(size_t __refs = 0); /** * @brief Constructor performs static initialization. * * This constructor is used to construct the initial C locale facet. * * @param __cloc Handle to C locale data. * @param __refs Passed to the base facet class. */ explicit ctype(__c_locale __cloc, size_t __refs = 0); protected: __wmask_type _M_convert_to_wmask(const mask __m) const throw(); /// Destructor virtual ~ctype(); /** * @brief Test wchar_t classification. * * This function finds a mask M for @a c and compares it to mask @a m. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __c The wchar_t to find the mask of. * @param __m The mask to compare against. * @return (M & __m) != 0. */ virtual bool do_is(mask __m, char_type __c) const; /** * @brief Return a mask array. * * This function finds the mask for each wchar_t in the range [lo,hi) * and successively writes it to vec. vec must have as many elements * as the input. * * do_is() is a hook for a derived facet to change the behavior of * classifying. do_is() must always return the same result for the * same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __vec Pointer to an array of mask storage. * @return @a __hi. */ virtual const char_type* do_is(const char_type* __lo, const char_type* __hi, mask* __vec) const; /** * @brief Find wchar_t matching mask * * This function searches for and returns the first wchar_t c in * [__lo,__hi) for which is(__m,c) is true. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a matching wchar_t if found, else @a __hi. */ virtual const char_type* do_scan_is(mask __m, const char_type* __lo, const char_type* __hi) const; /** * @brief Find wchar_t not matching mask * * This function searches for and returns a pointer to the first * wchar_t c of [__lo,__hi) for which is(__m,c) is false. * * do_scan_is() is a hook for a derived facet to change the behavior of * match searching. do_is() must always return the same result for the * same input. * * @param __m The mask to compare against. * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return Pointer to a non-matching wchar_t if found, else @a __hi. */ virtual const char_type* do_scan_not(mask __m, const char_type* __lo, const char_type* __hi) const; /** * @brief Convert to uppercase. * * This virtual function converts the wchar_t argument to uppercase if * possible. If not possible (for example, '2'), returns the argument. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __c The wchar_t to convert. * @return The uppercase wchar_t if convertible, else @a __c. */ virtual char_type do_toupper(char_type __c) const; /** * @brief Convert array to uppercase. * * This virtual function converts each wchar_t in the range [lo,hi) to * uppercase if possible. Other elements remain untouched. * * do_toupper() is a hook for a derived facet to change the behavior of * uppercasing. do_toupper() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_toupper(char_type* __lo, const char_type* __hi) const; /** * @brief Convert to lowercase. * * This virtual function converts the argument to lowercase if * possible. If not possible (for example, '2'), returns the argument. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __c The wchar_t to convert. * @return The lowercase wchar_t if convertible, else @a __c. */ virtual char_type do_tolower(char_type __c) const; /** * @brief Convert array to lowercase. * * This virtual function converts each wchar_t in the range [lo,hi) to * lowercase if possible. Other elements remain untouched. * * do_tolower() is a hook for a derived facet to change the behavior of * lowercasing. do_tolower() must always return the same result for * the same input. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @return @a __hi. */ virtual const char_type* do_tolower(char_type* __lo, const char_type* __hi) const; /** * @brief Widen char to wchar_t * * This virtual function converts the char to wchar_t using the * simplest reasonable transformation. For an underived ctype * facet, the argument will be cast to wchar_t. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The char to convert. * @return The converted wchar_t. */ virtual char_type do_widen(char __c) const; /** * @brief Widen char array to wchar_t array * * This function converts each char in the input to wchar_t using the * simplest reasonable transformation. For an underived ctype * facet, the argument will be copied, casting each element to wchar_t. * * do_widen() is a hook for a derived facet to change the behavior of * widening. do_widen() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start range. * @param __hi Pointer to end of range. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char* do_widen(const char* __lo, const char* __hi, char_type* __to) const; /** * @brief Narrow wchar_t to char * * This virtual function converts the argument to char using * the simplest reasonable transformation. If the conversion * fails, dfault is returned instead. For an underived * ctype facet, @a c will be cast to char and * returned. * * do_narrow() is a hook for a derived facet to change the * behavior of narrowing. do_narrow() must always return the * same result for the same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __c The wchar_t to convert. * @param __dfault Char to return if conversion fails. * @return The converted char. */ virtual char do_narrow(char_type __c, char __dfault) const; /** * @brief Narrow wchar_t array to char array * * This virtual function converts each wchar_t in the range [lo,hi) to * char using the simplest reasonable transformation and writes the * results to the destination array. For any wchar_t in the input that * cannot be converted, @a dfault is used instead. For an underived * ctype facet, the argument will be copied, casting each * element to char. * * do_narrow() is a hook for a derived facet to change the behavior of * narrowing. do_narrow() must always return the same result for the * same input. * * Note: this is not what you want for codepage conversions. See * codecvt for that. * * @param __lo Pointer to start of range. * @param __hi Pointer to end of range. * @param __dfault Char to use if conversion fails. * @param __to Pointer to the destination array. * @return @a __hi. */ virtual const char_type* do_narrow(const char_type* __lo, const char_type* __hi, char __dfault, char* __to) const; // For use at construction time only. void _M_initialize_ctype() throw(); }; #endif //_GLIBCXX_USE_WCHAR_T /// class ctype_byname [22.2.1.2]. template class ctype_byname : public ctype<_CharT> { public: typedef typename ctype<_CharT>::mask mask; explicit ctype_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit ctype_byname(const string& __s, size_t __refs = 0) : ctype_byname(__s.c_str(), __refs) { } #endif protected: virtual ~ctype_byname() { } }; /// 22.2.1.4 Class ctype_byname specializations. template<> class ctype_byname : public ctype { public: explicit ctype_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit ctype_byname(const string& __s, size_t __refs = 0); #endif protected: virtual ~ctype_byname(); }; #ifdef _GLIBCXX_USE_WCHAR_T template<> class ctype_byname : public ctype { public: explicit ctype_byname(const char* __s, size_t __refs = 0); #if __cplusplus >= 201103L explicit ctype_byname(const string& __s, size_t __refs = 0); #endif protected: virtual ~ctype_byname(); }; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace // Include host and configuration specific ctype inlines. #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 22.2.2 The numeric category. class __num_base { public: // NB: Code depends on the order of _S_atoms_out elements. // Below are the indices into _S_atoms_out. enum { _S_ominus, _S_oplus, _S_ox, _S_oX, _S_odigits, _S_odigits_end = _S_odigits + 16, _S_oudigits = _S_odigits_end, _S_oudigits_end = _S_oudigits + 16, _S_oe = _S_odigits + 14, // For scientific notation, 'e' _S_oE = _S_oudigits + 14, // For scientific notation, 'E' _S_oend = _S_oudigits_end }; // A list of valid numeric literals for output. This array // contains chars that will be passed through the current locale's // ctype<_CharT>.widen() and then used to render numbers. // For the standard "C" locale, this is // "-+xX0123456789abcdef0123456789ABCDEF". static const char* _S_atoms_out; // String literal of acceptable (narrow) input, for num_get. // "-+xX0123456789abcdefABCDEF" static const char* _S_atoms_in; enum { _S_iminus, _S_iplus, _S_ix, _S_iX, _S_izero, _S_ie = _S_izero + 14, _S_iE = _S_izero + 20, _S_iend = 26 }; // num_put // Construct and return valid scanf format for floating point types. static void _S_format_float(const ios_base& __io, char* __fptr, char __mod) throw(); }; template struct __numpunct_cache : public locale::facet { const char* _M_grouping; size_t _M_grouping_size; bool _M_use_grouping; const _CharT* _M_truename; size_t _M_truename_size; const _CharT* _M_falsename; size_t _M_falsename_size; _CharT _M_decimal_point; _CharT _M_thousands_sep; // A list of valid numeric literals for output: in the standard // "C" locale, this is "-+xX0123456789abcdef0123456789ABCDEF". // This array contains the chars after having been passed // through the current locale's ctype<_CharT>.widen(). _CharT _M_atoms_out[__num_base::_S_oend]; // A list of valid numeric literals for input: in the standard // "C" locale, this is "-+xX0123456789abcdefABCDEF" // This array contains the chars after having been passed // through the current locale's ctype<_CharT>.widen(). _CharT _M_atoms_in[__num_base::_S_iend]; bool _M_allocated; __numpunct_cache(size_t __refs = 0) : facet(__refs), _M_grouping(0), _M_grouping_size(0), _M_use_grouping(false), _M_truename(0), _M_truename_size(0), _M_falsename(0), _M_falsename_size(0), _M_decimal_point(_CharT()), _M_thousands_sep(_CharT()), _M_allocated(false) { } ~__numpunct_cache(); void _M_cache(const locale& __loc); private: __numpunct_cache& operator=(const __numpunct_cache&); explicit __numpunct_cache(const __numpunct_cache&); }; template __numpunct_cache<_CharT>::~__numpunct_cache() { if (_M_allocated) { delete [] _M_grouping; delete [] _M_truename; delete [] _M_falsename; } } _GLIBCXX_BEGIN_NAMESPACE_CXX11 /** * @brief Primary class template numpunct. * @ingroup locales * * This facet stores several pieces of information related to printing and * scanning numbers, such as the decimal point character. It takes a * template parameter specifying the char type. The numpunct facet is * used by streams for many I/O operations involving numbers. * * The numpunct template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from a numpunct facet. */ template class numpunct : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} typedef __numpunct_cache<_CharT> __cache_type; protected: __cache_type* _M_data; public: /// Numpunct facet id. static locale::id id; /** * @brief Numpunct constructor. * * @param __refs Refcount to pass to the base class. */ explicit numpunct(size_t __refs = 0) : facet(__refs), _M_data(0) { _M_initialize_numpunct(); } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up the * predefined locale facets. * * @param __cache __numpunct_cache object. * @param __refs Refcount to pass to the base class. */ explicit numpunct(__cache_type* __cache, size_t __refs = 0) : facet(__refs), _M_data(__cache) { _M_initialize_numpunct(); } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __refs Refcount to pass to the base class. */ explicit numpunct(__c_locale __cloc, size_t __refs = 0) : facet(__refs), _M_data(0) { _M_initialize_numpunct(__cloc); } /** * @brief Return decimal point character. * * This function returns a char_type to use as a decimal point. It * does so by returning returning * numpunct::do_decimal_point(). * * @return @a char_type representing a decimal point. */ char_type decimal_point() const { return this->do_decimal_point(); } /** * @brief Return thousands separator character. * * This function returns a char_type to use as a thousands * separator. It does so by returning returning * numpunct::do_thousands_sep(). * * @return char_type representing a thousands separator. */ char_type thousands_sep() const { return this->do_thousands_sep(); } /** * @brief Return grouping specification. * * This function returns a string representing groupings for the * integer part of a number. Groupings indicate where thousands * separators should be inserted in the integer part of a number. * * Each char in the return string is interpret as an integer * rather than a character. These numbers represent the number * of digits in a group. The first char in the string * represents the number of digits in the least significant * group. If a char is negative, it indicates an unlimited * number of digits for the group. If more chars from the * string are required to group a number, the last char is used * repeatedly. * * For example, if the grouping() returns "\003\002" and is * applied to the number 123456789, this corresponds to * 12,34,56,789. Note that if the string was "32", this would * put more than 50 digits into the least significant group if * the character set is ASCII. * * The string is returned by calling * numpunct::do_grouping(). * * @return string representing grouping specification. */ string grouping() const { return this->do_grouping(); } /** * @brief Return string representation of bool true. * * This function returns a string_type containing the text * representation for true bool variables. It does so by calling * numpunct::do_truename(). * * @return string_type representing printed form of true. */ string_type truename() const { return this->do_truename(); } /** * @brief Return string representation of bool false. * * This function returns a string_type containing the text * representation for false bool variables. It does so by calling * numpunct::do_falsename(). * * @return string_type representing printed form of false. */ string_type falsename() const { return this->do_falsename(); } protected: /// Destructor. virtual ~numpunct(); /** * @brief Return decimal point character. * * Returns a char_type to use as a decimal point. This function is a * hook for derived classes to change the value returned. * * @return @a char_type representing a decimal point. */ virtual char_type do_decimal_point() const { return _M_data->_M_decimal_point; } /** * @brief Return thousands separator character. * * Returns a char_type to use as a thousands separator. This function * is a hook for derived classes to change the value returned. * * @return @a char_type representing a thousands separator. */ virtual char_type do_thousands_sep() const { return _M_data->_M_thousands_sep; } /** * @brief Return grouping specification. * * Returns a string representing groupings for the integer part of a * number. This function is a hook for derived classes to change the * value returned. @see grouping() for details. * * @return String representing grouping specification. */ virtual string do_grouping() const { return _M_data->_M_grouping; } /** * @brief Return string representation of bool true. * * Returns a string_type containing the text representation for true * bool variables. This function is a hook for derived classes to * change the value returned. * * @return string_type representing printed form of true. */ virtual string_type do_truename() const { return _M_data->_M_truename; } /** * @brief Return string representation of bool false. * * Returns a string_type containing the text representation for false * bool variables. This function is a hook for derived classes to * change the value returned. * * @return string_type representing printed form of false. */ virtual string_type do_falsename() const { return _M_data->_M_falsename; } // For use at construction time only. void _M_initialize_numpunct(__c_locale __cloc = 0); }; template locale::id numpunct<_CharT>::id; template<> numpunct::~numpunct(); template<> void numpunct::_M_initialize_numpunct(__c_locale __cloc); #ifdef _GLIBCXX_USE_WCHAR_T template<> numpunct::~numpunct(); template<> void numpunct::_M_initialize_numpunct(__c_locale __cloc); #endif /// class numpunct_byname [22.2.3.2]. template class numpunct_byname : public numpunct<_CharT> { public: typedef _CharT char_type; typedef basic_string<_CharT> string_type; explicit numpunct_byname(const char* __s, size_t __refs = 0) : numpunct<_CharT>(__refs) { if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { __c_locale __tmp; this->_S_create_c_locale(__tmp, __s); this->_M_initialize_numpunct(__tmp); this->_S_destroy_c_locale(__tmp); } } #if __cplusplus >= 201103L explicit numpunct_byname(const string& __s, size_t __refs = 0) : numpunct_byname(__s.c_str(), __refs) { } #endif protected: virtual ~numpunct_byname() { } }; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_BEGIN_NAMESPACE_LDBL /** * @brief Primary class template num_get. * @ingroup locales * * This facet encapsulates the code to parse and return a number * from a string. It is used by the istream numeric extraction * operators. * * The num_get template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from the num_get facet. */ template class num_get : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _InIter iter_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit num_get(size_t __refs = 0) : facet(__refs) { } /** * @brief Numeric parsing. * * Parses the input stream into the bool @a v. It does so by calling * num_get::do_get(). * * If ios_base::boolalpha is set, attempts to read * ctype::truename() or ctype::falsename(). Sets * @a v to true or false if successful. Sets err to * ios_base::failbit if reading the string fails. Sets err to * ios_base::eofbit if the stream is emptied. * * If ios_base::boolalpha is not set, proceeds as with reading a long, * except if the value is 1, sets @a v to true, if the value is 0, sets * @a v to false, and otherwise set err to ios_base::failbit. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool& __v) const { return this->do_get(__in, __end, __io, __err, __v); } //@{ /** * @brief Numeric parsing. * * Parses the input stream into the integral variable @a v. It does so * by calling num_get::do_get(). * * Parsing is affected by the flag settings in @a io. * * The basic parse is affected by the value of io.flags() & * ios_base::basefield. If equal to ios_base::oct, parses like the * scanf %o specifier. Else if equal to ios_base::hex, parses like %X * specifier. Else if basefield equal to 0, parses like the %i * specifier. Otherwise, parses like %d for signed and %u for unsigned * types. The matching type length modifier is also used. * * Digit grouping is interpreted according to * numpunct::grouping() and numpunct::thousands_sep(). If the * pattern of digit groups isn't consistent, sets err to * ios_base::failbit. * * If parsing the string yields a valid value for @a v, @a v is set. * Otherwise, sets err to ios_base::failbit and leaves @a v unaltered. * Sets err to ios_base::eofbit if the stream is emptied. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned short& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned int& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } #ifdef _GLIBCXX_USE_LONG_LONG iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long long& __v) const { return this->do_get(__in, __end, __io, __err, __v); } #endif //@} //@{ /** * @brief Numeric parsing. * * Parses the input stream into the integral variable @a v. It does so * by calling num_get::do_get(). * * The input characters are parsed like the scanf %g specifier. The * matching type length modifier is also used. * * The decimal point character used is numpunct::decimal_point(). * Digit grouping is interpreted according to * numpunct::grouping() and numpunct::thousands_sep(). If the * pattern of digit groups isn't consistent, sets err to * ios_base::failbit. * * If parsing the string yields a valid value for @a v, @a v is set. * Otherwise, sets err to ios_base::failbit and leaves @a v unaltered. * Sets err to ios_base::eofbit if the stream is emptied. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, float& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, double& __v) const { return this->do_get(__in, __end, __io, __err, __v); } iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, long double& __v) const { return this->do_get(__in, __end, __io, __err, __v); } //@} /** * @brief Numeric parsing. * * Parses the input stream into the pointer variable @a v. It does so * by calling num_get::do_get(). * * The input characters are parsed like the scanf %p specifier. * * Digit grouping is interpreted according to * numpunct::grouping() and numpunct::thousands_sep(). If the * pattern of digit groups isn't consistent, sets err to * ios_base::failbit. * * Note that the digit grouping effect for pointers is a bit ambiguous * in the standard and shouldn't be relied on. See DR 344. * * If parsing the string yields a valid value for @a v, @a v is set. * Otherwise, sets err to ios_base::failbit and leaves @a v unaltered. * Sets err to ios_base::eofbit if the stream is emptied. * * @param __in Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, void*& __v) const { return this->do_get(__in, __end, __io, __err, __v); } protected: /// Destructor. virtual ~num_get() { } _GLIBCXX_DEFAULT_ABI_TAG iter_type _M_extract_float(iter_type, iter_type, ios_base&, ios_base::iostate&, string&) const; template _GLIBCXX_DEFAULT_ABI_TAG iter_type _M_extract_int(iter_type, iter_type, ios_base&, ios_base::iostate&, _ValueT&) const; template typename __gnu_cxx::__enable_if<__is_char<_CharT2>::__value, int>::__type _M_find(const _CharT2*, size_t __len, _CharT2 __c) const { int __ret = -1; if (__len <= 10) { if (__c >= _CharT2('0') && __c < _CharT2(_CharT2('0') + __len)) __ret = __c - _CharT2('0'); } else { if (__c >= _CharT2('0') && __c <= _CharT2('9')) __ret = __c - _CharT2('0'); else if (__c >= _CharT2('a') && __c <= _CharT2('f')) __ret = 10 + (__c - _CharT2('a')); else if (__c >= _CharT2('A') && __c <= _CharT2('F')) __ret = 10 + (__c - _CharT2('A')); } return __ret; } template typename __gnu_cxx::__enable_if::__value, int>::__type _M_find(const _CharT2* __zero, size_t __len, _CharT2 __c) const { int __ret = -1; const char_type* __q = char_traits<_CharT2>::find(__zero, __len, __c); if (__q) { __ret = __q - __zero; if (__ret > 15) __ret -= 6; } return __ret; } //@{ /** * @brief Numeric parsing. * * Parses the input stream into the variable @a v. This function is a * hook for derived classes to change the value returned. @see get() * for more details. * * @param __beg Start of input stream. * @param __end End of input stream. * @param __io Source of locale and flags. * @param __err Error flags to set. * @param __v Value to format and insert. * @return Iterator after reading. */ virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, bool&) const; virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned short& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned int& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } #ifdef _GLIBCXX_USE_LONG_LONG virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, long long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } virtual iter_type do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, unsigned long long& __v) const { return _M_extract_int(__beg, __end, __io, __err, __v); } #endif virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, float&) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, double&) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type __do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, double&) const; #else virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, long double&) const; #endif virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, void*&) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate&, long double&) const; #endif //@} }; template locale::id num_get<_CharT, _InIter>::id; /** * @brief Primary class template num_put. * @ingroup locales * * This facet encapsulates the code to convert a number to a string. It is * used by the ostream numeric insertion operators. * * The num_put template uses protected virtual functions to provide the * actual results. The public accessors forward the call to the virtual * functions. These virtual functions are hooks for developers to * implement the behavior they require from the num_put facet. */ template class num_put : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef _OutIter iter_type; //@} /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit num_put(size_t __refs = 0) : facet(__refs) { } /** * @brief Numeric formatting. * * Formats the boolean @a v and inserts it into a stream. It does so * by calling num_put::do_put(). * * If ios_base::boolalpha is set, writes ctype::truename() or * ctype::falsename(). Otherwise formats @a v as an int. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, bool __v) const { return this->do_put(__s, __io, __fill, __v); } //@{ /** * @brief Numeric formatting. * * Formats the integral value @a v and inserts it into a * stream. It does so by calling num_put::do_put(). * * Formatting is affected by the flag settings in @a io. * * The basic format is affected by the value of io.flags() & * ios_base::basefield. If equal to ios_base::oct, formats like the * printf %o specifier. Else if equal to ios_base::hex, formats like * %x or %X with ios_base::uppercase unset or set respectively. * Otherwise, formats like %d, %ld, %lld for signed and %u, %lu, %llu * for unsigned values. Note that if both oct and hex are set, neither * will take effect. * * If ios_base::showpos is set, '+' is output before positive values. * If ios_base::showbase is set, '0' precedes octal values (except 0) * and '0[xX]' precedes hex values. * * The decimal point character used is numpunct::decimal_point(). * Thousands separators are inserted according to * numpunct::grouping() and numpunct::thousands_sep(). * * If io.width() is non-zero, enough @a fill characters are inserted to * make the result at least that wide. If * (io.flags() & ios_base::adjustfield) == ios_base::left, result is * padded at the end. If ios_base::internal, then padding occurs * immediately after either a '+' or '-' or after '0x' or '0X'. * Otherwise, padding occurs at the beginning. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, long __v) const { return this->do_put(__s, __io, __fill, __v); } iter_type put(iter_type __s, ios_base& __io, char_type __fill, unsigned long __v) const { return this->do_put(__s, __io, __fill, __v); } #ifdef _GLIBCXX_USE_LONG_LONG iter_type put(iter_type __s, ios_base& __io, char_type __fill, long long __v) const { return this->do_put(__s, __io, __fill, __v); } iter_type put(iter_type __s, ios_base& __io, char_type __fill, unsigned long long __v) const { return this->do_put(__s, __io, __fill, __v); } #endif //@} //@{ /** * @brief Numeric formatting. * * Formats the floating point value @a v and inserts it into a stream. * It does so by calling num_put::do_put(). * * Formatting is affected by the flag settings in @a io. * * The basic format is affected by the value of io.flags() & * ios_base::floatfield. If equal to ios_base::fixed, formats like the * printf %f specifier. Else if equal to ios_base::scientific, formats * like %e or %E with ios_base::uppercase unset or set respectively. * Otherwise, formats like %g or %G depending on uppercase. Note that * if both fixed and scientific are set, the effect will also be like * %g or %G. * * The output precision is given by io.precision(). This precision is * capped at numeric_limits::digits10 + 2 (different for double and * long double). The default precision is 6. * * If ios_base::showpos is set, '+' is output before positive values. * If ios_base::showpoint is set, a decimal point will always be * output. * * The decimal point character used is numpunct::decimal_point(). * Thousands separators are inserted according to * numpunct::grouping() and numpunct::thousands_sep(). * * If io.width() is non-zero, enough @a fill characters are inserted to * make the result at least that wide. If * (io.flags() & ios_base::adjustfield) == ios_base::left, result is * padded at the end. If ios_base::internal, then padding occurs * immediately after either a '+' or '-' or after '0x' or '0X'. * Otherwise, padding occurs at the beginning. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, double __v) const { return this->do_put(__s, __io, __fill, __v); } iter_type put(iter_type __s, ios_base& __io, char_type __fill, long double __v) const { return this->do_put(__s, __io, __fill, __v); } //@} /** * @brief Numeric formatting. * * Formats the pointer value @a v and inserts it into a stream. It * does so by calling num_put::do_put(). * * This function formats @a v as an unsigned long with ios_base::hex * and ios_base::showbase set. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ iter_type put(iter_type __s, ios_base& __io, char_type __fill, const void* __v) const { return this->do_put(__s, __io, __fill, __v); } protected: template iter_type _M_insert_float(iter_type, ios_base& __io, char_type __fill, char __mod, _ValueT __v) const; void _M_group_float(const char* __grouping, size_t __grouping_size, char_type __sep, const char_type* __p, char_type* __new, char_type* __cs, int& __len) const; template iter_type _M_insert_int(iter_type, ios_base& __io, char_type __fill, _ValueT __v) const; void _M_group_int(const char* __grouping, size_t __grouping_size, char_type __sep, ios_base& __io, char_type* __new, char_type* __cs, int& __len) const; void _M_pad(char_type __fill, streamsize __w, ios_base& __io, char_type* __new, const char_type* __cs, int& __len) const; /// Destructor. virtual ~num_put() { } //@{ /** * @brief Numeric formatting. * * These functions do the work of formatting numeric values and * inserting them into a stream. This function is a hook for derived * classes to change the value returned. * * @param __s Stream to write to. * @param __io Source of locale and flags. * @param __fill Char_type to use for filling. * @param __v Value to format and insert. * @return Iterator after writing. */ virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, bool __v) const; virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, long __v) const { return _M_insert_int(__s, __io, __fill, __v); } virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, unsigned long __v) const { return _M_insert_int(__s, __io, __fill, __v); } #ifdef _GLIBCXX_USE_LONG_LONG virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, long long __v) const { return _M_insert_int(__s, __io, __fill, __v); } virtual iter_type do_put(iter_type __s, ios_base& __io, char_type __fill, unsigned long long __v) const { return _M_insert_int(__s, __io, __fill, __v); } #endif virtual iter_type do_put(iter_type, ios_base&, char_type, double) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type __do_put(iter_type, ios_base&, char_type, double) const; #else virtual iter_type do_put(iter_type, ios_base&, char_type, long double) const; #endif virtual iter_type do_put(iter_type, ios_base&, char_type, const void*) const; // XXX GLIBCXX_ABI Deprecated #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ virtual iter_type do_put(iter_type, ios_base&, char_type, long double) const; #endif //@} }; template locale::id num_put<_CharT, _OutIter>::id; _GLIBCXX_END_NAMESPACE_LDBL // Subclause convenience interfaces, inlines. // NB: These are inline because, when used in a loop, some compilers // can hoist the body out of the loop; then it's just as fast as the // C is*() function. /// Convenience interface to ctype.is(ctype_base::space, __c). template inline bool isspace(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::space, __c); } /// Convenience interface to ctype.is(ctype_base::print, __c). template inline bool isprint(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::print, __c); } /// Convenience interface to ctype.is(ctype_base::cntrl, __c). template inline bool iscntrl(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::cntrl, __c); } /// Convenience interface to ctype.is(ctype_base::upper, __c). template inline bool isupper(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::upper, __c); } /// Convenience interface to ctype.is(ctype_base::lower, __c). template inline bool islower(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::lower, __c); } /// Convenience interface to ctype.is(ctype_base::alpha, __c). template inline bool isalpha(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::alpha, __c); } /// Convenience interface to ctype.is(ctype_base::digit, __c). template inline bool isdigit(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::digit, __c); } /// Convenience interface to ctype.is(ctype_base::punct, __c). template inline bool ispunct(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::punct, __c); } /// Convenience interface to ctype.is(ctype_base::xdigit, __c). template inline bool isxdigit(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::xdigit, __c); } /// Convenience interface to ctype.is(ctype_base::alnum, __c). template inline bool isalnum(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::alnum, __c); } /// Convenience interface to ctype.is(ctype_base::graph, __c). template inline bool isgraph(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::graph, __c); } #if __cplusplus >= 201103L /// Convenience interface to ctype.is(ctype_base::blank, __c). template inline bool isblank(_CharT __c, const locale& __loc) { return use_facet >(__loc).is(ctype_base::blank, __c); } #endif /// Convenience interface to ctype.toupper(__c). template inline _CharT toupper(_CharT __c, const locale& __loc) { return use_facet >(__loc).toupper(__c); } /// Convenience interface to ctype.tolower(__c). template inline _CharT tolower(_CharT __c, const locale& __loc) { return use_facet >(__loc).tolower(__c); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std # include #endif c++/8/bits/valarray_before.h000064400000044121151027430570011546 0ustar00// The template and inlines for the -*- C++ -*- internal _Meta class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/valarray_before.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _VALARRAY_BEFORE_H #define _VALARRAY_BEFORE_H 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // // Implementing a loosened valarray return value is tricky. // First we need to meet 26.3.1/3: we should not add more than // two levels of template nesting. Therefore we resort to template // template to "flatten" loosened return value types. // At some point we use partial specialization to remove one level // template nesting due to _Expr<> // // This class is NOT defined. It doesn't need to. template class _Constant; // Implementations of unary functions applied to valarray<>s. // I use hard-coded object functions here instead of a generic // approach like pointers to function: // 1) correctness: some functions take references, others values. // we can't deduce the correct type afterwards. // 2) efficiency -- object functions can be easily inlined // 3) be Koenig-lookup-friendly struct _Abs { template _Tp operator()(const _Tp& __t) const { return abs(__t); } }; struct _Cos { template _Tp operator()(const _Tp& __t) const { return cos(__t); } }; struct _Acos { template _Tp operator()(const _Tp& __t) const { return acos(__t); } }; struct _Cosh { template _Tp operator()(const _Tp& __t) const { return cosh(__t); } }; struct _Sin { template _Tp operator()(const _Tp& __t) const { return sin(__t); } }; struct _Asin { template _Tp operator()(const _Tp& __t) const { return asin(__t); } }; struct _Sinh { template _Tp operator()(const _Tp& __t) const { return sinh(__t); } }; struct _Tan { template _Tp operator()(const _Tp& __t) const { return tan(__t); } }; struct _Atan { template _Tp operator()(const _Tp& __t) const { return atan(__t); } }; struct _Tanh { template _Tp operator()(const _Tp& __t) const { return tanh(__t); } }; struct _Exp { template _Tp operator()(const _Tp& __t) const { return exp(__t); } }; struct _Log { template _Tp operator()(const _Tp& __t) const { return log(__t); } }; struct _Log10 { template _Tp operator()(const _Tp& __t) const { return log10(__t); } }; struct _Sqrt { template _Tp operator()(const _Tp& __t) const { return sqrt(__t); } }; // In the past, we used to tailor operator applications semantics // to the specialization of standard function objects (i.e. plus<>, etc.) // That is incorrect. Therefore we provide our own surrogates. struct __unary_plus { template _Tp operator()(const _Tp& __t) const { return +__t; } }; struct __negate { template _Tp operator()(const _Tp& __t) const { return -__t; } }; struct __bitwise_not { template _Tp operator()(const _Tp& __t) const { return ~__t; } }; struct __plus { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x + __y; } }; struct __minus { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x - __y; } }; struct __multiplies { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x * __y; } }; struct __divides { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x / __y; } }; struct __modulus { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x % __y; } }; struct __bitwise_xor { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x ^ __y; } }; struct __bitwise_and { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x & __y; } }; struct __bitwise_or { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x | __y; } }; struct __shift_left { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x << __y; } }; struct __shift_right { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x >> __y; } }; struct __logical_and { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x && __y; } }; struct __logical_or { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x || __y; } }; struct __logical_not { template bool operator()(const _Tp& __x) const { return !__x; } }; struct __equal_to { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; } }; struct __not_equal_to { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x != __y; } }; struct __less { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } }; struct __greater { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; } }; struct __less_equal { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x <= __y; } }; struct __greater_equal { template bool operator()(const _Tp& __x, const _Tp& __y) const { return __x >= __y; } }; // The few binary functions we miss. struct _Atan2 { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return atan2(__x, __y); } }; struct _Pow { template _Tp operator()(const _Tp& __x, const _Tp& __y) const { return pow(__x, __y); } }; template struct __fun_with_valarray { typedef _Tp result_type; }; template struct __fun_with_valarray<_Tp, false> { // No result type defined for invalid value types. }; // We need these bits in order to recover the return type of // some functions/operators now that we're no longer using // function templates. template struct __fun : __fun_with_valarray<_Tp> { }; // several specializations for relational operators. template struct __fun<__logical_not, _Tp> { typedef bool result_type; }; template struct __fun<__logical_and, _Tp> { typedef bool result_type; }; template struct __fun<__logical_or, _Tp> { typedef bool result_type; }; template struct __fun<__less, _Tp> { typedef bool result_type; }; template struct __fun<__greater, _Tp> { typedef bool result_type; }; template struct __fun<__less_equal, _Tp> { typedef bool result_type; }; template struct __fun<__greater_equal, _Tp> { typedef bool result_type; }; template struct __fun<__equal_to, _Tp> { typedef bool result_type; }; template struct __fun<__not_equal_to, _Tp> { typedef bool result_type; }; // // Apply function taking a value/const reference closure // template class _FunBase { public: typedef typename _Dom::value_type value_type; _FunBase(const _Dom& __e, value_type __f(_Arg)) : _M_expr(__e), _M_func(__f) {} value_type operator[](size_t __i) const { return _M_func (_M_expr[__i]); } size_t size() const { return _M_expr.size ();} private: const _Dom& _M_expr; value_type (*_M_func)(_Arg); }; template struct _ValFunClos<_Expr,_Dom> : _FunBase<_Dom, typename _Dom::value_type> { typedef _FunBase<_Dom, typename _Dom::value_type> _Base; typedef typename _Base::value_type value_type; typedef value_type _Tp; _ValFunClos(const _Dom& __e, _Tp __f(_Tp)) : _Base(__e, __f) {} }; template struct _ValFunClos<_ValArray,_Tp> : _FunBase, _Tp> { typedef _FunBase, _Tp> _Base; typedef _Tp value_type; _ValFunClos(const valarray<_Tp>& __v, _Tp __f(_Tp)) : _Base(__v, __f) {} }; template struct _RefFunClos<_Expr, _Dom> : _FunBase<_Dom, const typename _Dom::value_type&> { typedef _FunBase<_Dom, const typename _Dom::value_type&> _Base; typedef typename _Base::value_type value_type; typedef value_type _Tp; _RefFunClos(const _Dom& __e, _Tp __f(const _Tp&)) : _Base(__e, __f) {} }; template struct _RefFunClos<_ValArray, _Tp> : _FunBase, const _Tp&> { typedef _FunBase, const _Tp&> _Base; typedef _Tp value_type; _RefFunClos(const valarray<_Tp>& __v, _Tp __f(const _Tp&)) : _Base(__v, __f) {} }; // // Unary expression closure. // template class _UnBase { public: typedef typename _Arg::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _UnBase(const _Arg& __e) : _M_expr(__e) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr[__i]); } size_t size() const { return _M_expr.size(); } private: const _Arg& _M_expr; }; template struct _UnClos<_Oper, _Expr, _Dom> : _UnBase<_Oper, _Dom> { typedef _Dom _Arg; typedef _UnBase<_Oper, _Dom> _Base; typedef typename _Base::value_type value_type; _UnClos(const _Arg& __e) : _Base(__e) {} }; template struct _UnClos<_Oper, _ValArray, _Tp> : _UnBase<_Oper, valarray<_Tp> > { typedef valarray<_Tp> _Arg; typedef _UnBase<_Oper, valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _UnClos(const _Arg& __e) : _Base(__e) {} }; // // Binary expression closure. // template class _BinBase { public: typedef typename _FirstArg::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _BinBase(const _FirstArg& __e1, const _SecondArg& __e2) : _M_expr1(__e1), _M_expr2(__e2) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr1[__i], _M_expr2[__i]); } size_t size() const { return _M_expr1.size(); } private: const _FirstArg& _M_expr1; const _SecondArg& _M_expr2; }; template class _BinBase2 { public: typedef typename _Clos::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _BinBase2(const _Clos& __e, const _Vt& __t) : _M_expr1(__e), _M_expr2(__t) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr1[__i], _M_expr2); } size_t size() const { return _M_expr1.size(); } private: const _Clos& _M_expr1; const _Vt& _M_expr2; }; template class _BinBase1 { public: typedef typename _Clos::value_type _Vt; typedef typename __fun<_Oper, _Vt>::result_type value_type; _BinBase1(const _Vt& __t, const _Clos& __e) : _M_expr1(__t), _M_expr2(__e) {} value_type operator[](size_t __i) const { return _Oper()(_M_expr1, _M_expr2[__i]); } size_t size() const { return _M_expr2.size(); } private: const _Vt& _M_expr1; const _Clos& _M_expr2; }; template struct _BinClos<_Oper, _Expr, _Expr, _Dom1, _Dom2> : _BinBase<_Oper, _Dom1, _Dom2> { typedef _BinBase<_Oper, _Dom1, _Dom2> _Base; typedef typename _Base::value_type value_type; _BinClos(const _Dom1& __e1, const _Dom2& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper,_ValArray, _ValArray, _Tp, _Tp> : _BinBase<_Oper, valarray<_Tp>, valarray<_Tp> > { typedef _BinBase<_Oper, valarray<_Tp>, valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const valarray<_Tp>& __v, const valarray<_Tp>& __w) : _Base(__v, __w) {} }; template struct _BinClos<_Oper, _Expr, _ValArray, _Dom, typename _Dom::value_type> : _BinBase<_Oper, _Dom, valarray > { typedef typename _Dom::value_type _Tp; typedef _BinBase<_Oper,_Dom,valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const _Dom& __e1, const valarray<_Tp>& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _ValArray, _Expr, typename _Dom::value_type, _Dom> : _BinBase<_Oper, valarray,_Dom> { typedef typename _Dom::value_type _Tp; typedef _BinBase<_Oper, valarray<_Tp>, _Dom> _Base; typedef typename _Base::value_type value_type; _BinClos(const valarray<_Tp>& __e1, const _Dom& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _Expr, _Constant, _Dom, typename _Dom::value_type> : _BinBase2<_Oper, _Dom> { typedef typename _Dom::value_type _Tp; typedef _BinBase2<_Oper,_Dom> _Base; typedef typename _Base::value_type value_type; _BinClos(const _Dom& __e1, const _Tp& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _Constant, _Expr, typename _Dom::value_type, _Dom> : _BinBase1<_Oper, _Dom> { typedef typename _Dom::value_type _Tp; typedef _BinBase1<_Oper, _Dom> _Base; typedef typename _Base::value_type value_type; _BinClos(const _Tp& __e1, const _Dom& __e2) : _Base(__e1, __e2) {} }; template struct _BinClos<_Oper, _ValArray, _Constant, _Tp, _Tp> : _BinBase2<_Oper, valarray<_Tp> > { typedef _BinBase2<_Oper,valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const valarray<_Tp>& __v, const _Tp& __t) : _Base(__v, __t) {} }; template struct _BinClos<_Oper, _Constant, _ValArray, _Tp, _Tp> : _BinBase1<_Oper, valarray<_Tp> > { typedef _BinBase1<_Oper, valarray<_Tp> > _Base; typedef typename _Base::value_type value_type; _BinClos(const _Tp& __t, const valarray<_Tp>& __v) : _Base(__t, __v) {} }; // // slice_array closure. // template class _SBase { public: typedef typename _Dom::value_type value_type; _SBase (const _Dom& __e, const slice& __s) : _M_expr (__e), _M_slice (__s) {} value_type operator[] (size_t __i) const { return _M_expr[_M_slice.start () + __i * _M_slice.stride ()]; } size_t size() const { return _M_slice.size (); } private: const _Dom& _M_expr; const slice& _M_slice; }; template class _SBase<_Array<_Tp> > { public: typedef _Tp value_type; _SBase (_Array<_Tp> __a, const slice& __s) : _M_array (__a._M_data+__s.start()), _M_size (__s.size()), _M_stride (__s.stride()) {} value_type operator[] (size_t __i) const { return _M_array._M_data[__i * _M_stride]; } size_t size() const { return _M_size; } private: const _Array<_Tp> _M_array; const size_t _M_size; const size_t _M_stride; }; template struct _SClos<_Expr, _Dom> : _SBase<_Dom> { typedef _SBase<_Dom> _Base; typedef typename _Base::value_type value_type; _SClos (const _Dom& __e, const slice& __s) : _Base (__e, __s) {} }; template struct _SClos<_ValArray, _Tp> : _SBase<_Array<_Tp> > { typedef _SBase<_Array<_Tp> > _Base; typedef _Tp value_type; _SClos (_Array<_Tp> __a, const slice& __s) : _Base (__a, __s) {} }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _CPP_VALARRAY_BEFORE_H */ c++/8/bits/node_handle.h000064400000020030151027430570010634 0ustar00// Node handles for containers -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/node_handle.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. * @headername{map,set,unordered_map,unordered_set} */ #ifndef _NODE_HANDLE #define _NODE_HANDLE 1 #pragma GCC system_header #if __cplusplus > 201402L # define __cpp_lib_node_extract 201606 #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// Base class for node handle types of maps and sets. template class _Node_handle_common { using _AllocTraits = allocator_traits<_NodeAlloc>; public: using allocator_type = __alloc_rebind<_NodeAlloc, _Val>; allocator_type get_allocator() const noexcept { __glibcxx_assert(!this->empty()); return allocator_type(*_M_alloc); } explicit operator bool() const noexcept { return _M_ptr != nullptr; } [[nodiscard]] bool empty() const noexcept { return _M_ptr == nullptr; } protected: constexpr _Node_handle_common() noexcept : _M_ptr(), _M_alloc() {} ~_Node_handle_common() { _M_destroy(); } _Node_handle_common(_Node_handle_common&& __nh) noexcept : _M_ptr(__nh._M_ptr), _M_alloc(std::move(__nh._M_alloc)) { __nh._M_ptr = nullptr; __nh._M_alloc = nullopt; } _Node_handle_common& operator=(_Node_handle_common&& __nh) noexcept { _M_destroy(); _M_ptr = __nh._M_ptr; if constexpr (is_move_assignable_v<_NodeAlloc>) { if (_AllocTraits::propagate_on_container_move_assignment::value || !this->_M_alloc) this->_M_alloc = std::move(__nh._M_alloc); else { __glibcxx_assert(this->_M_alloc == __nh._M_alloc); } } else { __glibcxx_assert(_M_alloc); } __nh._M_ptr = nullptr; __nh._M_alloc = nullopt; return *this; } _Node_handle_common(typename _AllocTraits::pointer __ptr, const _NodeAlloc& __alloc) : _M_ptr(__ptr), _M_alloc(__alloc) { } void _M_swap(_Node_handle_common& __nh) noexcept { using std::swap; swap(_M_ptr, __nh._M_ptr); if (_AllocTraits::propagate_on_container_swap::value || !_M_alloc || !__nh._M_alloc) _M_alloc.swap(__nh._M_alloc); else { __glibcxx_assert(_M_alloc == __nh._M_alloc); } } private: void _M_destroy() noexcept { if (_M_ptr != nullptr) { allocator_type __alloc(*_M_alloc); allocator_traits::destroy(__alloc, _M_ptr->_M_valptr()); _AllocTraits::deallocate(*_M_alloc, _M_ptr, 1); } } protected: typename _AllocTraits::pointer _M_ptr; private: optional<_NodeAlloc> _M_alloc; template friend class _Rb_tree; }; /// Node handle type for maps. template class _Node_handle : public _Node_handle_common<_Value, _NodeAlloc> { public: constexpr _Node_handle() noexcept = default; ~_Node_handle() = default; _Node_handle(_Node_handle&&) noexcept = default; _Node_handle& operator=(_Node_handle&&) noexcept = default; using key_type = _Key; using mapped_type = typename _Value::second_type; key_type& key() const noexcept { __glibcxx_assert(!this->empty()); return *_M_pkey; } mapped_type& mapped() const noexcept { __glibcxx_assert(!this->empty()); return *_M_pmapped; } void swap(_Node_handle& __nh) noexcept { this->_M_swap(__nh); using std::swap; swap(_M_pkey, __nh._M_pkey); swap(_M_pmapped, __nh._M_pmapped); } friend void swap(_Node_handle& __x, _Node_handle& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } private: using _AllocTraits = allocator_traits<_NodeAlloc>; _Node_handle(typename _AllocTraits::pointer __ptr, const _NodeAlloc& __alloc) : _Node_handle_common<_Value, _NodeAlloc>(__ptr, __alloc) { if (__ptr) { auto& __key = const_cast<_Key&>(__ptr->_M_valptr()->first); _M_pkey = _S_pointer_to(__key); _M_pmapped = _S_pointer_to(__ptr->_M_valptr()->second); } else { _M_pkey = nullptr; _M_pmapped = nullptr; } } template using __pointer = __ptr_rebind>; __pointer<_Key> _M_pkey = nullptr; __pointer _M_pmapped = nullptr; template __pointer<_Tp> _S_pointer_to(_Tp& __obj) { return pointer_traits<__pointer<_Tp>>::pointer_to(__obj); } const key_type& _M_key() const noexcept { return key(); } template friend class _Rb_tree; template friend class _Hashtable; }; /// Node handle type for sets. template class _Node_handle<_Value, _Value, _NodeAlloc> : public _Node_handle_common<_Value, _NodeAlloc> { public: constexpr _Node_handle() noexcept = default; ~_Node_handle() = default; _Node_handle(_Node_handle&&) noexcept = default; _Node_handle& operator=(_Node_handle&&) noexcept = default; using value_type = _Value; value_type& value() const noexcept { __glibcxx_assert(!this->empty()); return *this->_M_ptr->_M_valptr(); } void swap(_Node_handle& __nh) noexcept { this->_M_swap(__nh); } friend void swap(_Node_handle& __x, _Node_handle& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } private: using _AllocTraits = allocator_traits<_NodeAlloc>; _Node_handle(typename _AllocTraits::pointer __ptr, const _NodeAlloc& __alloc) : _Node_handle_common<_Value, _NodeAlloc>(__ptr, __alloc) { } const value_type& _M_key() const noexcept { return value(); } template friend class _Rb_tree; template friend class _Hashtable; }; /// Return type of insert(node_handle&&) on unique maps/sets. template struct _Node_insert_return { _Iterator position = _Iterator(); bool inserted = false; _NodeHandle node; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif c++/8/bits/exception_defines.h000064400000003155151027430570012100 0ustar00// -fno-exceptions Support -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/exception_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{exception} */ #ifndef _EXCEPTION_DEFINES_H #define _EXCEPTION_DEFINES_H 1 #if ! __cpp_exceptions // Iff -fno-exceptions, transform error handling code to work without it. # define __try if (true) # define __catch(X) if (false) # define __throw_exception_again #else // Else proceed normally. # define __try try # define __catch(X) catch(X) # define __throw_exception_again throw #endif #endif c++/8/bits/hash_bytes.h000064400000004142151027430570010533 0ustar00// Declarations for hash functions. -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/hash_bytes.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _HASH_BYTES_H #define _HASH_BYTES_H 1 #pragma GCC system_header #include namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Hash function implementation for the nontrivial specialization. // All of them are based on a primitive that hashes a pointer to a // byte array. The actual hash algorithm is not guaranteed to stay // the same from release to release -- it may be updated or tuned to // improve hash quality or speed. size_t _Hash_bytes(const void* __ptr, size_t __len, size_t __seed); // A similar hash primitive, using the FNV hash algorithm. This // algorithm is guaranteed to stay the same from release to release. // (although it might not produce the same values on different // machines.) size_t _Fnv_hash_bytes(const void* __ptr, size_t __len, size_t __seed); _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/locale_facets_nonio.tcc000064400000130340151027430570012712 0ustar00// Locale support -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_facets_nonio.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ #ifndef _LOCALE_FACETS_NONIO_TCC #define _LOCALE_FACETS_NONIO_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template struct __use_cache<__moneypunct_cache<_CharT, _Intl> > { const __moneypunct_cache<_CharT, _Intl>* operator() (const locale& __loc) const { const size_t __i = moneypunct<_CharT, _Intl>::id._M_id(); const locale::facet** __caches = __loc._M_impl->_M_caches; if (!__caches[__i]) { __moneypunct_cache<_CharT, _Intl>* __tmp = 0; __try { __tmp = new __moneypunct_cache<_CharT, _Intl>; __tmp->_M_cache(__loc); } __catch(...) { delete __tmp; __throw_exception_again; } __loc._M_impl->_M_install_cache(__tmp, __i); } return static_cast< const __moneypunct_cache<_CharT, _Intl>*>(__caches[__i]); } }; template void __moneypunct_cache<_CharT, _Intl>::_M_cache(const locale& __loc) { const moneypunct<_CharT, _Intl>& __mp = use_facet >(__loc); _M_decimal_point = __mp.decimal_point(); _M_thousands_sep = __mp.thousands_sep(); _M_frac_digits = __mp.frac_digits(); char* __grouping = 0; _CharT* __curr_symbol = 0; _CharT* __positive_sign = 0; _CharT* __negative_sign = 0; __try { const string& __g = __mp.grouping(); _M_grouping_size = __g.size(); __grouping = new char[_M_grouping_size]; __g.copy(__grouping, _M_grouping_size); _M_use_grouping = (_M_grouping_size && static_cast(__grouping[0]) > 0 && (__grouping[0] != __gnu_cxx::__numeric_traits::__max)); const basic_string<_CharT>& __cs = __mp.curr_symbol(); _M_curr_symbol_size = __cs.size(); __curr_symbol = new _CharT[_M_curr_symbol_size]; __cs.copy(__curr_symbol, _M_curr_symbol_size); const basic_string<_CharT>& __ps = __mp.positive_sign(); _M_positive_sign_size = __ps.size(); __positive_sign = new _CharT[_M_positive_sign_size]; __ps.copy(__positive_sign, _M_positive_sign_size); const basic_string<_CharT>& __ns = __mp.negative_sign(); _M_negative_sign_size = __ns.size(); __negative_sign = new _CharT[_M_negative_sign_size]; __ns.copy(__negative_sign, _M_negative_sign_size); _M_pos_format = __mp.pos_format(); _M_neg_format = __mp.neg_format(); const ctype<_CharT>& __ct = use_facet >(__loc); __ct.widen(money_base::_S_atoms, money_base::_S_atoms + money_base::_S_end, _M_atoms); _M_grouping = __grouping; _M_curr_symbol = __curr_symbol; _M_positive_sign = __positive_sign; _M_negative_sign = __negative_sign; _M_allocated = true; } __catch(...) { delete [] __grouping; delete [] __curr_symbol; delete [] __positive_sign; delete [] __negative_sign; __throw_exception_again; } } _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 template template _InIter money_get<_CharT, _InIter>:: _M_extract(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, string& __units) const { typedef char_traits<_CharT> __traits_type; typedef typename string_type::size_type size_type; typedef money_base::part part; typedef __moneypunct_cache<_CharT, _Intl> __cache_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); __use_cache<__cache_type> __uc; const __cache_type* __lc = __uc(__loc); const char_type* __lit = __lc->_M_atoms; // Deduced sign. bool __negative = false; // Sign size. size_type __sign_size = 0; // True if sign is mandatory. const bool __mandatory_sign = (__lc->_M_positive_sign_size && __lc->_M_negative_sign_size); // String of grouping info from thousands_sep plucked from __units. string __grouping_tmp; if (__lc->_M_use_grouping) __grouping_tmp.reserve(32); // Last position before the decimal point. int __last_pos = 0; // Separator positions, then, possibly, fractional digits. int __n = 0; // If input iterator is in a valid state. bool __testvalid = true; // Flag marking when a decimal point is found. bool __testdecfound = false; // The tentative returned string is stored here. string __res; __res.reserve(32); const char_type* __lit_zero = __lit + money_base::_S_zero; const money_base::pattern __p = __lc->_M_neg_format; for (int __i = 0; __i < 4 && __testvalid; ++__i) { const part __which = static_cast(__p.field[__i]); switch (__which) { case money_base::symbol: // According to 22.2.6.1.2, p2, symbol is required // if (__io.flags() & ios_base::showbase), otherwise // is optional and consumed only if other characters // are needed to complete the format. if (__io.flags() & ios_base::showbase || __sign_size > 1 || __i == 0 || (__i == 1 && (__mandatory_sign || (static_cast(__p.field[0]) == money_base::sign) || (static_cast(__p.field[2]) == money_base::space))) || (__i == 2 && ((static_cast(__p.field[3]) == money_base::value) || (__mandatory_sign && (static_cast(__p.field[3]) == money_base::sign))))) { const size_type __len = __lc->_M_curr_symbol_size; size_type __j = 0; for (; __beg != __end && __j < __len && *__beg == __lc->_M_curr_symbol[__j]; ++__beg, (void)++__j); if (__j != __len && (__j || __io.flags() & ios_base::showbase)) __testvalid = false; } break; case money_base::sign: // Sign might not exist, or be more than one character long. if (__lc->_M_positive_sign_size && __beg != __end && *__beg == __lc->_M_positive_sign[0]) { __sign_size = __lc->_M_positive_sign_size; ++__beg; } else if (__lc->_M_negative_sign_size && __beg != __end && *__beg == __lc->_M_negative_sign[0]) { __negative = true; __sign_size = __lc->_M_negative_sign_size; ++__beg; } else if (__lc->_M_positive_sign_size && !__lc->_M_negative_sign_size) // "... if no sign is detected, the result is given the sign // that corresponds to the source of the empty string" __negative = true; else if (__mandatory_sign) __testvalid = false; break; case money_base::value: // Extract digits, remove and stash away the // grouping of found thousands separators. for (; __beg != __end; ++__beg) { const char_type __c = *__beg; const char_type* __q = __traits_type::find(__lit_zero, 10, __c); if (__q != 0) { __res += money_base::_S_atoms[__q - __lit]; ++__n; } else if (__c == __lc->_M_decimal_point && !__testdecfound) { if (__lc->_M_frac_digits <= 0) break; __last_pos = __n; __n = 0; __testdecfound = true; } else if (__lc->_M_use_grouping && __c == __lc->_M_thousands_sep && !__testdecfound) { if (__n) { // Mark position for later analysis. __grouping_tmp += static_cast(__n); __n = 0; } else { __testvalid = false; break; } } else break; } if (__res.empty()) __testvalid = false; break; case money_base::space: // At least one space is required. if (__beg != __end && __ctype.is(ctype_base::space, *__beg)) ++__beg; else __testvalid = false; // fallthrough case money_base::none: // Only if not at the end of the pattern. if (__i != 3) for (; __beg != __end && __ctype.is(ctype_base::space, *__beg); ++__beg); break; } } // Need to get the rest of the sign characters, if they exist. if (__sign_size > 1 && __testvalid) { const char_type* __sign = __negative ? __lc->_M_negative_sign : __lc->_M_positive_sign; size_type __i = 1; for (; __beg != __end && __i < __sign_size && *__beg == __sign[__i]; ++__beg, (void)++__i); if (__i != __sign_size) __testvalid = false; } if (__testvalid) { // Strip leading zeros. if (__res.size() > 1) { const size_type __first = __res.find_first_not_of('0'); const bool __only_zeros = __first == string::npos; if (__first) __res.erase(0, __only_zeros ? __res.size() - 1 : __first); } // 22.2.6.1.2, p4 if (__negative && __res[0] != '0') __res.insert(__res.begin(), '-'); // Test for grouping fidelity. if (__grouping_tmp.size()) { // Add the ending grouping. __grouping_tmp += static_cast(__testdecfound ? __last_pos : __n); if (!std::__verify_grouping(__lc->_M_grouping, __lc->_M_grouping_size, __grouping_tmp)) __err |= ios_base::failbit; } // Iff not enough digits were supplied after the decimal-point. if (__testdecfound && __n != __lc->_M_frac_digits) __testvalid = false; } // Iff valid sequence is not recognized. if (!__testvalid) __err |= ios_base::failbit; else __units.swap(__res); // Iff no more characters are available. if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 template _InIter money_get<_CharT, _InIter>:: __do_get(iter_type __beg, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, double& __units) const { string __str; __beg = __intl ? _M_extract(__beg, __end, __io, __err, __str) : _M_extract(__beg, __end, __io, __err, __str); std::__convert_to_v(__str.c_str(), __units, __err, _S_get_c_locale()); return __beg; } #endif template _InIter money_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, long double& __units) const { string __str; __beg = __intl ? _M_extract(__beg, __end, __io, __err, __str) : _M_extract(__beg, __end, __io, __err, __str); std::__convert_to_v(__str.c_str(), __units, __err, _S_get_c_locale()); return __beg; } template _InIter money_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, bool __intl, ios_base& __io, ios_base::iostate& __err, string_type& __digits) const { typedef typename string::size_type size_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); string __str; __beg = __intl ? _M_extract(__beg, __end, __io, __err, __str) : _M_extract(__beg, __end, __io, __err, __str); const size_type __len = __str.size(); if (__len) { __digits.resize(__len); __ctype.widen(__str.data(), __str.data() + __len, &__digits[0]); } return __beg; } template template _OutIter money_put<_CharT, _OutIter>:: _M_insert(iter_type __s, ios_base& __io, char_type __fill, const string_type& __digits) const { typedef typename string_type::size_type size_type; typedef money_base::part part; typedef __moneypunct_cache<_CharT, _Intl> __cache_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); __use_cache<__cache_type> __uc; const __cache_type* __lc = __uc(__loc); const char_type* __lit = __lc->_M_atoms; // Determine if negative or positive formats are to be used, and // discard leading negative_sign if it is present. const char_type* __beg = __digits.data(); money_base::pattern __p; const char_type* __sign; size_type __sign_size; if (!(*__beg == __lit[money_base::_S_minus])) { __p = __lc->_M_pos_format; __sign = __lc->_M_positive_sign; __sign_size = __lc->_M_positive_sign_size; } else { __p = __lc->_M_neg_format; __sign = __lc->_M_negative_sign; __sign_size = __lc->_M_negative_sign_size; if (__digits.size()) ++__beg; } // Look for valid numbers in the ctype facet within input digits. size_type __len = __ctype.scan_not(ctype_base::digit, __beg, __beg + __digits.size()) - __beg; if (__len) { // Assume valid input, and attempt to format. // Break down input numbers into base components, as follows: // final_value = grouped units + (decimal point) + (digits) string_type __value; __value.reserve(2 * __len); // Add thousands separators to non-decimal digits, per // grouping rules. long __paddec = __len - __lc->_M_frac_digits; if (__paddec > 0) { if (__lc->_M_frac_digits < 0) __paddec = __len; if (__lc->_M_grouping_size) { __value.assign(2 * __paddec, char_type()); _CharT* __vend = std::__add_grouping(&__value[0], __lc->_M_thousands_sep, __lc->_M_grouping, __lc->_M_grouping_size, __beg, __beg + __paddec); __value.erase(__vend - &__value[0]); } else __value.assign(__beg, __paddec); } // Deal with decimal point, decimal digits. if (__lc->_M_frac_digits > 0) { __value += __lc->_M_decimal_point; if (__paddec >= 0) __value.append(__beg + __paddec, __lc->_M_frac_digits); else { // Have to pad zeros in the decimal position. __value.append(-__paddec, __lit[money_base::_S_zero]); __value.append(__beg, __len); } } // Calculate length of resulting string. const ios_base::fmtflags __f = __io.flags() & ios_base::adjustfield; __len = __value.size() + __sign_size; __len += ((__io.flags() & ios_base::showbase) ? __lc->_M_curr_symbol_size : 0); string_type __res; __res.reserve(2 * __len); const size_type __width = static_cast(__io.width()); const bool __testipad = (__f == ios_base::internal && __len < __width); // Fit formatted digits into the required pattern. for (int __i = 0; __i < 4; ++__i) { const part __which = static_cast(__p.field[__i]); switch (__which) { case money_base::symbol: if (__io.flags() & ios_base::showbase) __res.append(__lc->_M_curr_symbol, __lc->_M_curr_symbol_size); break; case money_base::sign: // Sign might not exist, or be more than one // character long. In that case, add in the rest // below. if (__sign_size) __res += __sign[0]; break; case money_base::value: __res += __value; break; case money_base::space: // At least one space is required, but if internal // formatting is required, an arbitrary number of // fill spaces will be necessary. if (__testipad) __res.append(__width - __len, __fill); else __res += __fill; break; case money_base::none: if (__testipad) __res.append(__width - __len, __fill); break; } } // Special case of multi-part sign parts. if (__sign_size > 1) __res.append(__sign + 1, __sign_size - 1); // Pad, if still necessary. __len = __res.size(); if (__width > __len) { if (__f == ios_base::left) // After. __res.append(__width - __len, __fill); else // Before. __res.insert(0, __width - __len, __fill); __len = __width; } // Write resulting, fully-formatted string to output iterator. __s = std::__write(__s, __res.data(), __len); } __io.width(0); return __s; } #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ \ && _GLIBCXX_USE_CXX11_ABI == 0 template _OutIter money_put<_CharT, _OutIter>:: __do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, double __units) const { return this->do_put(__s, __intl, __io, __fill, (long double) __units); } #endif template _OutIter money_put<_CharT, _OutIter>:: do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, long double __units) const { const locale __loc = __io.getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); #if _GLIBCXX_USE_C99_STDIO // First try a buffer perhaps big enough. int __cs_size = 64; char* __cs = static_cast(__builtin_alloca(__cs_size)); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 328. Bad sprintf format modifier in money_put<>::do_put() int __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, "%.*Lf", 0, __units); // If the buffer was not large enough, try again with the correct size. if (__len >= __cs_size) { __cs_size = __len + 1; __cs = static_cast(__builtin_alloca(__cs_size)); __len = std::__convert_from_v(_S_get_c_locale(), __cs, __cs_size, "%.*Lf", 0, __units); } #else // max_exponent10 + 1 for the integer part, + 2 for sign and '\0'. const int __cs_size = __gnu_cxx::__numeric_traits::__max_exponent10 + 3; char* __cs = static_cast(__builtin_alloca(__cs_size)); int __len = std::__convert_from_v(_S_get_c_locale(), __cs, 0, "%.*Lf", 0, __units); #endif string_type __digits(__len, char_type()); __ctype.widen(__cs, __cs + __len, &__digits[0]); return __intl ? _M_insert(__s, __io, __fill, __digits) : _M_insert(__s, __io, __fill, __digits); } template _OutIter money_put<_CharT, _OutIter>:: do_put(iter_type __s, bool __intl, ios_base& __io, char_type __fill, const string_type& __digits) const { return __intl ? _M_insert(__s, __io, __fill, __digits) : _M_insert(__s, __io, __fill, __digits); } _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 // NB: Not especially useful. Without an ios_base object or some // kind of locale reference, we are left clawing at the air where // the side of the mountain used to be... template time_base::dateorder time_get<_CharT, _InIter>::do_date_order() const { return time_base::no_order; } // Expand a strftime format string and parse it. E.g., do_get_date() may // pass %m/%d/%Y => extracted characters. template _InIter time_get<_CharT, _InIter>:: _M_extract_via_format(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const _CharT* __format) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const ctype<_CharT>& __ctype = use_facet >(__loc); const size_t __len = char_traits<_CharT>::length(__format); ios_base::iostate __tmperr = ios_base::goodbit; size_t __i = 0; for (; __beg != __end && __i < __len && !__tmperr; ++__i) { if (__ctype.narrow(__format[__i], 0) == '%') { // Verify valid formatting code, attempt to extract. char __c = __ctype.narrow(__format[++__i], 0); int __mem = 0; if (__c == 'E' || __c == 'O') __c = __ctype.narrow(__format[++__i], 0); switch (__c) { const char* __cs; _CharT __wcs[10]; case 'a': // Abbreviated weekday name [tm_wday] const char_type* __days1[7]; __tp._M_days_abbreviated(__days1); __beg = _M_extract_name(__beg, __end, __mem, __days1, 7, __io, __tmperr); if (!__tmperr) __tm->tm_wday = __mem; break; case 'A': // Weekday name [tm_wday]. const char_type* __days2[7]; __tp._M_days(__days2); __beg = _M_extract_name(__beg, __end, __mem, __days2, 7, __io, __tmperr); if (!__tmperr) __tm->tm_wday = __mem; break; case 'h': case 'b': // Abbreviated month name [tm_mon] const char_type* __months1[12]; __tp._M_months_abbreviated(__months1); __beg = _M_extract_name(__beg, __end, __mem, __months1, 12, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __mem; break; case 'B': // Month name [tm_mon]. const char_type* __months2[12]; __tp._M_months(__months2); __beg = _M_extract_name(__beg, __end, __mem, __months2, 12, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __mem; break; case 'c': // Default time and date representation. const char_type* __dt[2]; __tp._M_date_time_formats(__dt); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __dt[0]); break; case 'd': // Day [01, 31]. [tm_mday] __beg = _M_extract_num(__beg, __end, __mem, 1, 31, 2, __io, __tmperr); if (!__tmperr) __tm->tm_mday = __mem; break; case 'e': // Day [1, 31], with single digits preceded by // space. [tm_mday] if (__ctype.is(ctype_base::space, *__beg)) __beg = _M_extract_num(++__beg, __end, __mem, 1, 9, 1, __io, __tmperr); else __beg = _M_extract_num(__beg, __end, __mem, 10, 31, 2, __io, __tmperr); if (!__tmperr) __tm->tm_mday = __mem; break; case 'D': // Equivalent to %m/%d/%y.[tm_mon, tm_mday, tm_year] __cs = "%m/%d/%y"; __ctype.widen(__cs, __cs + 9, __wcs); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __wcs); break; case 'H': // Hour [00, 23]. [tm_hour] __beg = _M_extract_num(__beg, __end, __mem, 0, 23, 2, __io, __tmperr); if (!__tmperr) __tm->tm_hour = __mem; break; case 'I': // Hour [01, 12]. [tm_hour] __beg = _M_extract_num(__beg, __end, __mem, 1, 12, 2, __io, __tmperr); if (!__tmperr) __tm->tm_hour = __mem; break; case 'm': // Month [01, 12]. [tm_mon] __beg = _M_extract_num(__beg, __end, __mem, 1, 12, 2, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __mem - 1; break; case 'M': // Minute [00, 59]. [tm_min] __beg = _M_extract_num(__beg, __end, __mem, 0, 59, 2, __io, __tmperr); if (!__tmperr) __tm->tm_min = __mem; break; case 'n': if (__ctype.narrow(*__beg, 0) == '\n') ++__beg; else __tmperr |= ios_base::failbit; break; case 'R': // Equivalent to (%H:%M). __cs = "%H:%M"; __ctype.widen(__cs, __cs + 6, __wcs); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __wcs); break; case 'S': // Seconds. [tm_sec] // [00, 60] in C99 (one leap-second), [00, 61] in C89. #if _GLIBCXX_USE_C99 __beg = _M_extract_num(__beg, __end, __mem, 0, 60, 2, #else __beg = _M_extract_num(__beg, __end, __mem, 0, 61, 2, #endif __io, __tmperr); if (!__tmperr) __tm->tm_sec = __mem; break; case 't': if (__ctype.narrow(*__beg, 0) == '\t') ++__beg; else __tmperr |= ios_base::failbit; break; case 'T': // Equivalent to (%H:%M:%S). __cs = "%H:%M:%S"; __ctype.widen(__cs, __cs + 9, __wcs); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __wcs); break; case 'x': // Locale's date. const char_type* __dates[2]; __tp._M_date_formats(__dates); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __dates[0]); break; case 'X': // Locale's time. const char_type* __times[2]; __tp._M_time_formats(__times); __beg = _M_extract_via_format(__beg, __end, __io, __tmperr, __tm, __times[0]); break; case 'y': case 'C': // C99 // Two digit year. case 'Y': // Year [1900). // NB: We parse either two digits, implicitly years since // 1900, or 4 digits, full year. In both cases we can // reconstruct [tm_year]. See also libstdc++/26701. __beg = _M_extract_num(__beg, __end, __mem, 0, 9999, 4, __io, __tmperr); if (!__tmperr) __tm->tm_year = __mem < 0 ? __mem + 100 : __mem - 1900; break; case 'Z': // Timezone info. if (__ctype.is(ctype_base::upper, *__beg)) { int __tmp; __beg = _M_extract_name(__beg, __end, __tmp, __timepunct_cache<_CharT>::_S_timezones, 14, __io, __tmperr); // GMT requires special effort. if (__beg != __end && !__tmperr && __tmp == 0 && (*__beg == __ctype.widen('-') || *__beg == __ctype.widen('+'))) { __beg = _M_extract_num(__beg, __end, __tmp, 0, 23, 2, __io, __tmperr); __beg = _M_extract_num(__beg, __end, __tmp, 0, 59, 2, __io, __tmperr); } } else __tmperr |= ios_base::failbit; break; default: // Not recognized. __tmperr |= ios_base::failbit; } } else { // Verify format and input match, extract and discard. if (__format[__i] == *__beg) ++__beg; else __tmperr |= ios_base::failbit; } } if (__tmperr || __i != __len) __err |= ios_base::failbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: _M_extract_num(iter_type __beg, iter_type __end, int& __member, int __min, int __max, size_t __len, ios_base& __io, ios_base::iostate& __err) const { const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); // As-is works for __len = 1, 2, 4, the values actually used. int __mult = __len == 2 ? 10 : (__len == 4 ? 1000 : 1); ++__min; size_t __i = 0; int __value = 0; for (; __beg != __end && __i < __len; ++__beg, (void)++__i) { const char __c = __ctype.narrow(*__beg, '*'); if (__c >= '0' && __c <= '9') { __value = __value * 10 + (__c - '0'); const int __valuec = __value * __mult; if (__valuec > __max || __valuec + __mult < __min) break; __mult /= 10; } else break; } if (__i == __len) __member = __value; // Special encoding for do_get_year, 'y', and 'Y' above. else if (__len == 4 && __i == 2) __member = __value - 100; else __err |= ios_base::failbit; return __beg; } // Assumptions: // All elements in __names are unique. template _InIter time_get<_CharT, _InIter>:: _M_extract_name(iter_type __beg, iter_type __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base& __io, ios_base::iostate& __err) const { typedef char_traits<_CharT> __traits_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); int* __matches = static_cast(__builtin_alloca(sizeof(int) * __indexlen)); size_t __nmatches = 0; size_t __pos = 0; bool __testvalid = true; const char_type* __name; // Look for initial matches. // NB: Some of the locale data is in the form of all lowercase // names, and some is in the form of initially-capitalized // names. Look for both. if (__beg != __end) { const char_type __c = *__beg; for (size_t __i1 = 0; __i1 < __indexlen; ++__i1) if (__c == __names[__i1][0] || __c == __ctype.toupper(__names[__i1][0])) __matches[__nmatches++] = __i1; } while (__nmatches > 1) { // Find smallest matching string. size_t __minlen = __traits_type::length(__names[__matches[0]]); for (size_t __i2 = 1; __i2 < __nmatches; ++__i2) __minlen = std::min(__minlen, __traits_type::length(__names[__matches[__i2]])); ++__beg; ++__pos; if (__pos < __minlen && __beg != __end) for (size_t __i3 = 0; __i3 < __nmatches;) { __name = __names[__matches[__i3]]; if (!(__name[__pos] == *__beg)) __matches[__i3] = __matches[--__nmatches]; else ++__i3; } else break; } if (__nmatches == 1) { // Make sure found name is completely extracted. ++__beg; ++__pos; __name = __names[__matches[0]]; const size_t __len = __traits_type::length(__name); while (__pos < __len && __beg != __end && __name[__pos] == *__beg) ++__beg, (void)++__pos; if (__len == __pos) __member = __matches[0]; else __testvalid = false; } else __testvalid = false; if (!__testvalid) __err |= ios_base::failbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: _M_extract_wday_or_month(iter_type __beg, iter_type __end, int& __member, const _CharT** __names, size_t __indexlen, ios_base& __io, ios_base::iostate& __err) const { typedef char_traits<_CharT> __traits_type; const locale& __loc = __io._M_getloc(); const ctype<_CharT>& __ctype = use_facet >(__loc); int* __matches = static_cast(__builtin_alloca(2 * sizeof(int) * __indexlen)); size_t __nmatches = 0; size_t* __matches_lengths = 0; size_t __pos = 0; if (__beg != __end) { const char_type __c = *__beg; for (size_t __i = 0; __i < 2 * __indexlen; ++__i) if (__c == __names[__i][0] || __c == __ctype.toupper(__names[__i][0])) __matches[__nmatches++] = __i; } if (__nmatches) { ++__beg; ++__pos; __matches_lengths = static_cast(__builtin_alloca(sizeof(size_t) * __nmatches)); for (size_t __i = 0; __i < __nmatches; ++__i) __matches_lengths[__i] = __traits_type::length(__names[__matches[__i]]); } for (; __beg != __end; ++__beg, (void)++__pos) { size_t __nskipped = 0; const char_type __c = *__beg; for (size_t __i = 0; __i < __nmatches;) { const char_type* __name = __names[__matches[__i]]; if (__pos >= __matches_lengths[__i]) ++__nskipped, ++__i; else if (!(__name[__pos] == __c)) { --__nmatches; __matches[__i] = __matches[__nmatches]; __matches_lengths[__i] = __matches_lengths[__nmatches]; } else ++__i; } if (__nskipped == __nmatches) break; } if ((__nmatches == 1 && __matches_lengths[0] == __pos) || (__nmatches == 2 && (__matches_lengths[0] == __pos || __matches_lengths[1] == __pos))) __member = (__matches[0] >= __indexlen ? __matches[0] - __indexlen : __matches[0]); else __err |= ios_base::failbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_time(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __times[2]; __tp._M_time_formats(__times); __beg = _M_extract_via_format(__beg, __end, __io, __err, __tm, __times[0]); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_date(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __dates[2]; __tp._M_date_formats(__dates); __beg = _M_extract_via_format(__beg, __end, __io, __err, __tm, __dates[0]); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_weekday(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __days[14]; __tp._M_days_abbreviated(__days); __tp._M_days(__days + 7); int __tmpwday; ios_base::iostate __tmperr = ios_base::goodbit; __beg = _M_extract_wday_or_month(__beg, __end, __tmpwday, __days, 7, __io, __tmperr); if (!__tmperr) __tm->tm_wday = __tmpwday; else __err |= ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_monthname(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { const locale& __loc = __io._M_getloc(); const __timepunct<_CharT>& __tp = use_facet<__timepunct<_CharT> >(__loc); const char_type* __months[24]; __tp._M_months_abbreviated(__months); __tp._M_months(__months + 12); int __tmpmon; ios_base::iostate __tmperr = ios_base::goodbit; __beg = _M_extract_wday_or_month(__beg, __end, __tmpmon, __months, 12, __io, __tmperr); if (!__tmperr) __tm->tm_mon = __tmpmon; else __err |= ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; return __beg; } template _InIter time_get<_CharT, _InIter>:: do_get_year(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm) const { int __tmpyear; ios_base::iostate __tmperr = ios_base::goodbit; __beg = _M_extract_num(__beg, __end, __tmpyear, 0, 9999, 4, __io, __tmperr); if (!__tmperr) __tm->tm_year = __tmpyear < 0 ? __tmpyear + 100 : __tmpyear - 1900; else __err |= ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #if __cplusplus >= 201103L template inline _InIter time_get<_CharT, _InIter>:: get(iter_type __s, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, const char_type* __fmt, const char_type* __fmtend) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); __err = ios_base::goodbit; while (__fmt != __fmtend && __err == ios_base::goodbit) { if (__s == __end) { __err = ios_base::eofbit | ios_base::failbit; break; } else if (__ctype.narrow(*__fmt, 0) == '%') { char __format; char __mod = 0; if (++__fmt == __fmtend) { __err = ios_base::failbit; break; } const char __c = __ctype.narrow(*__fmt, 0); if (__c != 'E' && __c != 'O') __format = __c; else if (++__fmt != __fmtend) { __mod = __c; __format = __ctype.narrow(*__fmt, 0); } else { __err = ios_base::failbit; break; } __s = this->do_get(__s, __end, __io, __err, __tm, __format, __mod); ++__fmt; } else if (__ctype.is(ctype_base::space, *__fmt)) { ++__fmt; while (__fmt != __fmtend && __ctype.is(ctype_base::space, *__fmt)) ++__fmt; while (__s != __end && __ctype.is(ctype_base::space, *__s)) ++__s; } // TODO real case-insensitive comparison else if (__ctype.tolower(*__s) == __ctype.tolower(*__fmt) || __ctype.toupper(*__s) == __ctype.toupper(*__fmt)) { ++__s; ++__fmt; } else { __err = ios_base::failbit; break; } } return __s; } template inline _InIter time_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, tm* __tm, char __format, char __mod) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); __err = ios_base::goodbit; char_type __fmt[4]; __fmt[0] = __ctype.widen('%'); if (!__mod) { __fmt[1] = __format; __fmt[2] = char_type(); } else { __fmt[1] = __mod; __fmt[2] = __format; __fmt[3] = char_type(); } __beg = _M_extract_via_format(__beg, __end, __io, __err, __tm, __fmt); if (__beg == __end) __err |= ios_base::eofbit; return __beg; } #endif // __cplusplus >= 201103L template _OutIter time_put<_CharT, _OutIter>:: put(iter_type __s, ios_base& __io, char_type __fill, const tm* __tm, const _CharT* __beg, const _CharT* __end) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); for (; __beg != __end; ++__beg) if (__ctype.narrow(*__beg, 0) != '%') { *__s = *__beg; ++__s; } else if (++__beg != __end) { char __format; char __mod = 0; const char __c = __ctype.narrow(*__beg, 0); if (__c != 'E' && __c != 'O') __format = __c; else if (++__beg != __end) { __mod = __c; __format = __ctype.narrow(*__beg, 0); } else break; __s = this->do_put(__s, __io, __fill, __tm, __format, __mod); } else break; return __s; } template _OutIter time_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type, const tm* __tm, char __format, char __mod) const { const locale& __loc = __io._M_getloc(); ctype<_CharT> const& __ctype = use_facet >(__loc); __timepunct<_CharT> const& __tp = use_facet<__timepunct<_CharT> >(__loc); // NB: This size is arbitrary. Should this be a data member, // initialized at construction? const size_t __maxlen = 128; char_type __res[__maxlen]; // NB: In IEE 1003.1-200x, and perhaps other locale models, it // is possible that the format character will be longer than one // character. Possibilities include 'E' or 'O' followed by a // format character: if __mod is not the default argument, assume // it's a valid modifier. char_type __fmt[4]; __fmt[0] = __ctype.widen('%'); if (!__mod) { __fmt[1] = __format; __fmt[2] = char_type(); } else { __fmt[1] = __mod; __fmt[2] = __format; __fmt[3] = char_type(); } __tp._M_put(__res, __maxlen, __fmt, __tm); // Write resulting, fully-formatted string to output iterator. return std::__write(__s, __res, char_traits::length(__res)); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class moneypunct; extern template class moneypunct; extern template class moneypunct_byname; extern template class moneypunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_get; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_put; extern template class __timepunct; extern template class time_put; extern template class time_put_byname; extern template class time_get; extern template class time_get_byname; extern template class messages; extern template class messages_byname; extern template const moneypunct& use_facet >(const locale&); extern template const moneypunct& use_facet >(const locale&); extern template const money_put& use_facet >(const locale&); extern template const money_get& use_facet >(const locale&); extern template const __timepunct& use_facet<__timepunct >(const locale&); extern template const time_put& use_facet >(const locale&); extern template const time_get& use_facet >(const locale&); extern template const messages& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet<__timepunct >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #ifdef _GLIBCXX_USE_WCHAR_T extern template class moneypunct; extern template class moneypunct; extern template class moneypunct_byname; extern template class moneypunct_byname; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_get; extern template class _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 money_put; extern template class __timepunct; extern template class time_put; extern template class time_put_byname; extern template class time_get; extern template class time_get_byname; extern template class messages; extern template class messages_byname; extern template const moneypunct& use_facet >(const locale&); extern template const moneypunct& use_facet >(const locale&); extern template const money_put& use_facet >(const locale&); extern template const money_get& use_facet >(const locale&); extern template const __timepunct& use_facet<__timepunct >(const locale&); extern template const time_put& use_facet >(const locale&); extern template const time_get& use_facet >(const locale&); extern template const messages& use_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet<__timepunct >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); extern template bool has_facet >(const locale&); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/locale_conv.h000064400000037341151027430570010675 0ustar00// wstring_convert implementation -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_conv.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ #ifndef _LOCALE_CONV_H #define _LOCALE_CONV_H 1 #if __cplusplus < 201103L # include #else #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup locales * @{ */ template bool __do_str_codecvt(const _InChar* __first, const _InChar* __last, _OutStr& __outstr, const _Codecvt& __cvt, _State& __state, size_t& __count, _Fn __fn) { if (__first == __last) { __outstr.clear(); __count = 0; return true; } size_t __outchars = 0; auto __next = __first; const auto __maxlen = __cvt.max_length() + 1; codecvt_base::result __result; do { __outstr.resize(__outstr.size() + (__last - __next) * __maxlen); auto __outnext = &__outstr.front() + __outchars; auto const __outlast = &__outstr.back() + 1; __result = (__cvt.*__fn)(__state, __next, __last, __next, __outnext, __outlast, __outnext); __outchars = __outnext - &__outstr.front(); } while (__result == codecvt_base::partial && __next != __last && (__outstr.size() - __outchars) < __maxlen); if (__result == codecvt_base::error) { __count = __next - __first; return false; } if (__result == codecvt_base::noconv) { __outstr.assign(__first, __last); __count = __last - __first; } else { __outstr.resize(__outchars); __count = __next - __first; } return true; } // Convert narrow character string to wide. template inline bool __str_codecvt_in(const char* __first, const char* __last, basic_string<_CharT, _Traits, _Alloc>& __outstr, const codecvt<_CharT, char, _State>& __cvt, _State& __state, size_t& __count) { using _Codecvt = codecvt<_CharT, char, _State>; using _ConvFn = codecvt_base::result (_Codecvt::*)(_State&, const char*, const char*, const char*&, _CharT*, _CharT*, _CharT*&) const; _ConvFn __fn = &codecvt<_CharT, char, _State>::in; return __do_str_codecvt(__first, __last, __outstr, __cvt, __state, __count, __fn); } template inline bool __str_codecvt_in(const char* __first, const char* __last, basic_string<_CharT, _Traits, _Alloc>& __outstr, const codecvt<_CharT, char, _State>& __cvt) { _State __state = {}; size_t __n; return __str_codecvt_in(__first, __last, __outstr, __cvt, __state, __n); } // Convert wide character string to narrow. template inline bool __str_codecvt_out(const _CharT* __first, const _CharT* __last, basic_string& __outstr, const codecvt<_CharT, char, _State>& __cvt, _State& __state, size_t& __count) { using _Codecvt = codecvt<_CharT, char, _State>; using _ConvFn = codecvt_base::result (_Codecvt::*)(_State&, const _CharT*, const _CharT*, const _CharT*&, char*, char*, char*&) const; _ConvFn __fn = &codecvt<_CharT, char, _State>::out; return __do_str_codecvt(__first, __last, __outstr, __cvt, __state, __count, __fn); } template inline bool __str_codecvt_out(const _CharT* __first, const _CharT* __last, basic_string& __outstr, const codecvt<_CharT, char, _State>& __cvt) { _State __state = {}; size_t __n; return __str_codecvt_out(__first, __last, __outstr, __cvt, __state, __n); } #ifdef _GLIBCXX_USE_WCHAR_T _GLIBCXX_BEGIN_NAMESPACE_CXX11 /// String conversions template, typename _Byte_alloc = allocator> class wstring_convert { public: typedef basic_string, _Byte_alloc> byte_string; typedef basic_string<_Elem, char_traits<_Elem>, _Wide_alloc> wide_string; typedef typename _Codecvt::state_type state_type; typedef typename wide_string::traits_type::int_type int_type; /** Default constructor. * * @param __pcvt The facet to use for conversions. * * Takes ownership of @p __pcvt and will delete it in the destructor. */ explicit wstring_convert(_Codecvt* __pcvt = new _Codecvt()) : _M_cvt(__pcvt) { if (!_M_cvt) __throw_logic_error("wstring_convert"); } /** Construct with an initial converstion state. * * @param __pcvt The facet to use for conversions. * @param __state Initial conversion state. * * Takes ownership of @p __pcvt and will delete it in the destructor. * The object's conversion state will persist between conversions. */ wstring_convert(_Codecvt* __pcvt, state_type __state) : _M_cvt(__pcvt), _M_state(__state), _M_with_cvtstate(true) { if (!_M_cvt) __throw_logic_error("wstring_convert"); } /** Construct with error strings. * * @param __byte_err A string to return on failed conversions. * @param __wide_err A wide string to return on failed conversions. */ explicit wstring_convert(const byte_string& __byte_err, const wide_string& __wide_err = wide_string()) : _M_cvt(new _Codecvt), _M_byte_err_string(__byte_err), _M_wide_err_string(__wide_err), _M_with_strings(true) { if (!_M_cvt) __throw_logic_error("wstring_convert"); } ~wstring_convert() = default; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2176. Special members for wstring_convert and wbuffer_convert wstring_convert(const wstring_convert&) = delete; wstring_convert& operator=(const wstring_convert&) = delete; /// @{ Convert from bytes. wide_string from_bytes(char __byte) { char __bytes[2] = { __byte }; return from_bytes(__bytes, __bytes+1); } wide_string from_bytes(const char* __ptr) { return from_bytes(__ptr, __ptr+char_traits::length(__ptr)); } wide_string from_bytes(const byte_string& __str) { auto __ptr = __str.data(); return from_bytes(__ptr, __ptr + __str.size()); } wide_string from_bytes(const char* __first, const char* __last) { if (!_M_with_cvtstate) _M_state = state_type(); wide_string __out{ _M_wide_err_string.get_allocator() }; if (__str_codecvt_in(__first, __last, __out, *_M_cvt, _M_state, _M_count)) return __out; if (_M_with_strings) return _M_wide_err_string; __throw_range_error("wstring_convert::from_bytes"); } /// @} /// @{ Convert to bytes. byte_string to_bytes(_Elem __wchar) { _Elem __wchars[2] = { __wchar }; return to_bytes(__wchars, __wchars+1); } byte_string to_bytes(const _Elem* __ptr) { return to_bytes(__ptr, __ptr+wide_string::traits_type::length(__ptr)); } byte_string to_bytes(const wide_string& __wstr) { auto __ptr = __wstr.data(); return to_bytes(__ptr, __ptr + __wstr.size()); } byte_string to_bytes(const _Elem* __first, const _Elem* __last) { if (!_M_with_cvtstate) _M_state = state_type(); byte_string __out{ _M_byte_err_string.get_allocator() }; if (__str_codecvt_out(__first, __last, __out, *_M_cvt, _M_state, _M_count)) return __out; if (_M_with_strings) return _M_byte_err_string; __throw_range_error("wstring_convert::to_bytes"); } /// @} // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2174. wstring_convert::converted() should be noexcept /// The number of elements successfully converted in the last conversion. size_t converted() const noexcept { return _M_count; } /// The final conversion state of the last conversion. state_type state() const { return _M_state; } private: unique_ptr<_Codecvt> _M_cvt; byte_string _M_byte_err_string; wide_string _M_wide_err_string; state_type _M_state = state_type(); size_t _M_count = 0; bool _M_with_cvtstate = false; bool _M_with_strings = false; }; _GLIBCXX_END_NAMESPACE_CXX11 /// Buffer conversions template> class wbuffer_convert : public basic_streambuf<_Elem, _Tr> { typedef basic_streambuf<_Elem, _Tr> _Wide_streambuf; public: typedef typename _Codecvt::state_type state_type; /** Default constructor. * * @param __bytebuf The underlying byte stream buffer. * @param __pcvt The facet to use for conversions. * @param __state Initial conversion state. * * Takes ownership of @p __pcvt and will delete it in the destructor. */ explicit wbuffer_convert(streambuf* __bytebuf = 0, _Codecvt* __pcvt = new _Codecvt, state_type __state = state_type()) : _M_buf(__bytebuf), _M_cvt(__pcvt), _M_state(__state) { if (!_M_cvt) __throw_logic_error("wbuffer_convert"); _M_always_noconv = _M_cvt->always_noconv(); if (_M_buf) { this->setp(_M_put_area, _M_put_area + _S_buffer_length); this->setg(_M_get_area + _S_putback_length, _M_get_area + _S_putback_length, _M_get_area + _S_putback_length); } } ~wbuffer_convert() = default; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2176. Special members for wstring_convert and wbuffer_convert wbuffer_convert(const wbuffer_convert&) = delete; wbuffer_convert& operator=(const wbuffer_convert&) = delete; streambuf* rdbuf() const noexcept { return _M_buf; } streambuf* rdbuf(streambuf *__bytebuf) noexcept { auto __prev = _M_buf; _M_buf = __bytebuf; return __prev; } /// The conversion state following the last conversion. state_type state() const noexcept { return _M_state; } protected: int sync() { return _M_buf && _M_conv_put() && !_M_buf->pubsync() ? 0 : -1; } typename _Wide_streambuf::int_type overflow(typename _Wide_streambuf::int_type __out) { if (!_M_buf || !_M_conv_put()) return _Tr::eof(); else if (!_Tr::eq_int_type(__out, _Tr::eof())) return this->sputc(__out); return _Tr::not_eof(__out); } typename _Wide_streambuf::int_type underflow() { if (!_M_buf) return _Tr::eof(); if (this->gptr() < this->egptr() || (_M_buf && _M_conv_get())) return _Tr::to_int_type(*this->gptr()); else return _Tr::eof(); } streamsize xsputn(const typename _Wide_streambuf::char_type* __s, streamsize __n) { if (!_M_buf || __n == 0) return 0; streamsize __done = 0; do { auto __nn = std::min(this->epptr() - this->pptr(), __n - __done); _Tr::copy(this->pptr(), __s + __done, __nn); this->pbump(__nn); __done += __nn; } while (__done < __n && _M_conv_put()); return __done; } private: // fill the get area from converted contents of the byte stream buffer bool _M_conv_get() { const streamsize __pb1 = this->gptr() - this->eback(); const streamsize __pb2 = _S_putback_length; const streamsize __npb = std::min(__pb1, __pb2); _Tr::move(_M_get_area + _S_putback_length - __npb, this->gptr() - __npb, __npb); streamsize __nbytes = sizeof(_M_get_buf) - _M_unconv; __nbytes = std::min(__nbytes, _M_buf->in_avail()); if (__nbytes < 1) __nbytes = 1; __nbytes = _M_buf->sgetn(_M_get_buf + _M_unconv, __nbytes); if (__nbytes < 1) return false; __nbytes += _M_unconv; // convert _M_get_buf into _M_get_area _Elem* __outbuf = _M_get_area + _S_putback_length; _Elem* __outnext = __outbuf; const char* __bnext = _M_get_buf; codecvt_base::result __result; if (_M_always_noconv) __result = codecvt_base::noconv; else { _Elem* __outend = _M_get_area + _S_buffer_length; __result = _M_cvt->in(_M_state, __bnext, __bnext + __nbytes, __bnext, __outbuf, __outend, __outnext); } if (__result == codecvt_base::noconv) { // cast is safe because noconv means _Elem is same type as char auto __get_buf = reinterpret_cast(_M_get_buf); _Tr::copy(__outbuf, __get_buf, __nbytes); _M_unconv = 0; return true; } if ((_M_unconv = _M_get_buf + __nbytes - __bnext)) char_traits::move(_M_get_buf, __bnext, _M_unconv); this->setg(__outbuf, __outbuf, __outnext); return __result != codecvt_base::error; } // unused bool _M_put(...) { return false; } bool _M_put(const char* __p, streamsize __n) { if (_M_buf->sputn(__p, __n) < __n) return false; return true; } // convert the put area and write to the byte stream buffer bool _M_conv_put() { _Elem* const __first = this->pbase(); const _Elem* const __last = this->pptr(); const streamsize __pending = __last - __first; if (_M_always_noconv) return _M_put(__first, __pending); char __outbuf[2 * _S_buffer_length]; const _Elem* __next = __first; const _Elem* __start; do { __start = __next; char* __outnext = __outbuf; char* const __outlast = __outbuf + sizeof(__outbuf); auto __result = _M_cvt->out(_M_state, __next, __last, __next, __outnext, __outlast, __outnext); if (__result == codecvt_base::error) return false; else if (__result == codecvt_base::noconv) return _M_put(__next, __pending); if (!_M_put(__outbuf, __outnext - __outbuf)) return false; } while (__next != __last && __next != __start); if (__next != __last) _Tr::move(__first, __next, __last - __next); this->pbump(__first - __next); return __next != __first; } streambuf* _M_buf; unique_ptr<_Codecvt> _M_cvt; state_type _M_state; static const streamsize _S_buffer_length = 32; static const streamsize _S_putback_length = 3; _Elem _M_put_area[_S_buffer_length]; _Elem _M_get_area[_S_buffer_length]; streamsize _M_unconv = 0; char _M_get_buf[_S_buffer_length-_S_putback_length]; bool _M_always_noconv; }; #endif // _GLIBCXX_USE_WCHAR_T /// @} group locales _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // __cplusplus #endif /* _LOCALE_CONV_H */ c++/8/bits/ios_base.h000064400000074457151027430570010206 0ustar00// Iostreams base classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ios_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ // // ISO C++ 14882: 27.4 Iostreams base classes // #ifndef _IOS_BASE_H #define _IOS_BASE_H 1 #pragma GCC system_header #include #include #include #if __cplusplus < 201103L # include #else # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // The following definitions of bitmask types are enums, not ints, // as permitted (but not required) in the standard, in order to provide // better type safety in iostream calls. A side effect is that in C++98 // expressions involving them are not compile-time constants. enum _Ios_Fmtflags { _S_boolalpha = 1L << 0, _S_dec = 1L << 1, _S_fixed = 1L << 2, _S_hex = 1L << 3, _S_internal = 1L << 4, _S_left = 1L << 5, _S_oct = 1L << 6, _S_right = 1L << 7, _S_scientific = 1L << 8, _S_showbase = 1L << 9, _S_showpoint = 1L << 10, _S_showpos = 1L << 11, _S_skipws = 1L << 12, _S_unitbuf = 1L << 13, _S_uppercase = 1L << 14, _S_adjustfield = _S_left | _S_right | _S_internal, _S_basefield = _S_dec | _S_oct | _S_hex, _S_floatfield = _S_scientific | _S_fixed, _S_ios_fmtflags_end = 1L << 16, _S_ios_fmtflags_max = __INT_MAX__, _S_ios_fmtflags_min = ~__INT_MAX__ }; inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator&(_Ios_Fmtflags __a, _Ios_Fmtflags __b) { return _Ios_Fmtflags(static_cast(__a) & static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator|(_Ios_Fmtflags __a, _Ios_Fmtflags __b) { return _Ios_Fmtflags(static_cast(__a) | static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator^(_Ios_Fmtflags __a, _Ios_Fmtflags __b) { return _Ios_Fmtflags(static_cast(__a) ^ static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags operator~(_Ios_Fmtflags __a) { return _Ios_Fmtflags(~static_cast(__a)); } inline const _Ios_Fmtflags& operator|=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b) { return __a = __a | __b; } inline const _Ios_Fmtflags& operator&=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b) { return __a = __a & __b; } inline const _Ios_Fmtflags& operator^=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b) { return __a = __a ^ __b; } enum _Ios_Openmode { _S_app = 1L << 0, _S_ate = 1L << 1, _S_bin = 1L << 2, _S_in = 1L << 3, _S_out = 1L << 4, _S_trunc = 1L << 5, _S_ios_openmode_end = 1L << 16, _S_ios_openmode_max = __INT_MAX__, _S_ios_openmode_min = ~__INT_MAX__ }; inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator&(_Ios_Openmode __a, _Ios_Openmode __b) { return _Ios_Openmode(static_cast(__a) & static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator|(_Ios_Openmode __a, _Ios_Openmode __b) { return _Ios_Openmode(static_cast(__a) | static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator^(_Ios_Openmode __a, _Ios_Openmode __b) { return _Ios_Openmode(static_cast(__a) ^ static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Openmode operator~(_Ios_Openmode __a) { return _Ios_Openmode(~static_cast(__a)); } inline const _Ios_Openmode& operator|=(_Ios_Openmode& __a, _Ios_Openmode __b) { return __a = __a | __b; } inline const _Ios_Openmode& operator&=(_Ios_Openmode& __a, _Ios_Openmode __b) { return __a = __a & __b; } inline const _Ios_Openmode& operator^=(_Ios_Openmode& __a, _Ios_Openmode __b) { return __a = __a ^ __b; } enum _Ios_Iostate { _S_goodbit = 0, _S_badbit = 1L << 0, _S_eofbit = 1L << 1, _S_failbit = 1L << 2, _S_ios_iostate_end = 1L << 16, _S_ios_iostate_max = __INT_MAX__, _S_ios_iostate_min = ~__INT_MAX__ }; inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator&(_Ios_Iostate __a, _Ios_Iostate __b) { return _Ios_Iostate(static_cast(__a) & static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator|(_Ios_Iostate __a, _Ios_Iostate __b) { return _Ios_Iostate(static_cast(__a) | static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator^(_Ios_Iostate __a, _Ios_Iostate __b) { return _Ios_Iostate(static_cast(__a) ^ static_cast(__b)); } inline _GLIBCXX_CONSTEXPR _Ios_Iostate operator~(_Ios_Iostate __a) { return _Ios_Iostate(~static_cast(__a)); } inline const _Ios_Iostate& operator|=(_Ios_Iostate& __a, _Ios_Iostate __b) { return __a = __a | __b; } inline const _Ios_Iostate& operator&=(_Ios_Iostate& __a, _Ios_Iostate __b) { return __a = __a & __b; } inline const _Ios_Iostate& operator^=(_Ios_Iostate& __a, _Ios_Iostate __b) { return __a = __a ^ __b; } enum _Ios_Seekdir { _S_beg = 0, _S_cur = _GLIBCXX_STDIO_SEEK_CUR, _S_end = _GLIBCXX_STDIO_SEEK_END, _S_ios_seekdir_end = 1L << 16 }; #if __cplusplus >= 201103L /// I/O error code enum class io_errc { stream = 1 }; template <> struct is_error_code_enum : public true_type { }; const error_category& iostream_category() noexcept; inline error_code make_error_code(io_errc __e) noexcept { return error_code(static_cast(__e), iostream_category()); } inline error_condition make_error_condition(io_errc __e) noexcept { return error_condition(static_cast(__e), iostream_category()); } #endif // 27.4.2 Class ios_base /** * @brief The base of the I/O class hierarchy. * @ingroup io * * This class defines everything that can be defined about I/O that does * not depend on the type of characters being input or output. Most * people will only see @c ios_base when they need to specify the full * name of the various I/O flags (e.g., the openmodes). */ class ios_base { #if _GLIBCXX_USE_CXX11_ABI #if __cplusplus < 201103L // Type that is layout-compatible with std::system_error struct system_error : std::runtime_error { // Type that is layout-compatible with std::error_code struct error_code { error_code() { } private: int _M_value; const void* _M_cat; } _M_code; }; #endif #endif public: /** * @brief These are thrown to indicate problems with io. * @ingroup exceptions * * 27.4.2.1.1 Class ios_base::failure */ #if _GLIBCXX_USE_CXX11_ABI class _GLIBCXX_ABI_TAG_CXX11 failure : public system_error { public: explicit failure(const string& __str); #if __cplusplus >= 201103L explicit failure(const string&, const error_code&); explicit failure(const char*, const error_code& = io_errc::stream); #endif virtual ~failure() throw(); virtual const char* what() const throw(); }; #else class failure : public exception { public: // _GLIBCXX_RESOLVE_LIB_DEFECTS // 48. Use of non-existent exception constructor explicit failure(const string& __str) throw(); // This declaration is not useless: // http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Vague-Linkage.html virtual ~failure() throw(); virtual const char* what() const throw(); private: string _M_msg; }; #endif // 27.4.2.1.2 Type ios_base::fmtflags /** * @brief This is a bitmask type. * * @c @a _Ios_Fmtflags is implementation-defined, but it is valid to * perform bitwise operations on these values and expect the Right * Thing to happen. Defined objects of type fmtflags are: * - boolalpha * - dec * - fixed * - hex * - internal * - left * - oct * - right * - scientific * - showbase * - showpoint * - showpos * - skipws * - unitbuf * - uppercase * - adjustfield * - basefield * - floatfield */ typedef _Ios_Fmtflags fmtflags; /// Insert/extract @c bool in alphabetic rather than numeric format. static const fmtflags boolalpha = _S_boolalpha; /// Converts integer input or generates integer output in decimal base. static const fmtflags dec = _S_dec; /// Generate floating-point output in fixed-point notation. static const fmtflags fixed = _S_fixed; /// Converts integer input or generates integer output in hexadecimal base. static const fmtflags hex = _S_hex; /// Adds fill characters at a designated internal point in certain /// generated output, or identical to @c right if no such point is /// designated. static const fmtflags internal = _S_internal; /// Adds fill characters on the right (final positions) of certain /// generated output. (I.e., the thing you print is flush left.) static const fmtflags left = _S_left; /// Converts integer input or generates integer output in octal base. static const fmtflags oct = _S_oct; /// Adds fill characters on the left (initial positions) of certain /// generated output. (I.e., the thing you print is flush right.) static const fmtflags right = _S_right; /// Generates floating-point output in scientific notation. static const fmtflags scientific = _S_scientific; /// Generates a prefix indicating the numeric base of generated integer /// output. static const fmtflags showbase = _S_showbase; /// Generates a decimal-point character unconditionally in generated /// floating-point output. static const fmtflags showpoint = _S_showpoint; /// Generates a + sign in non-negative generated numeric output. static const fmtflags showpos = _S_showpos; /// Skips leading white space before certain input operations. static const fmtflags skipws = _S_skipws; /// Flushes output after each output operation. static const fmtflags unitbuf = _S_unitbuf; /// Replaces certain lowercase letters with their uppercase equivalents /// in generated output. static const fmtflags uppercase = _S_uppercase; /// A mask of left|right|internal. Useful for the 2-arg form of @c setf. static const fmtflags adjustfield = _S_adjustfield; /// A mask of dec|oct|hex. Useful for the 2-arg form of @c setf. static const fmtflags basefield = _S_basefield; /// A mask of scientific|fixed. Useful for the 2-arg form of @c setf. static const fmtflags floatfield = _S_floatfield; // 27.4.2.1.3 Type ios_base::iostate /** * @brief This is a bitmask type. * * @c @a _Ios_Iostate is implementation-defined, but it is valid to * perform bitwise operations on these values and expect the Right * Thing to happen. Defined objects of type iostate are: * - badbit * - eofbit * - failbit * - goodbit */ typedef _Ios_Iostate iostate; /// Indicates a loss of integrity in an input or output sequence (such /// as an irrecoverable read error from a file). static const iostate badbit = _S_badbit; /// Indicates that an input operation reached the end of an input sequence. static const iostate eofbit = _S_eofbit; /// Indicates that an input operation failed to read the expected /// characters, or that an output operation failed to generate the /// desired characters. static const iostate failbit = _S_failbit; /// Indicates all is well. static const iostate goodbit = _S_goodbit; // 27.4.2.1.4 Type ios_base::openmode /** * @brief This is a bitmask type. * * @c @a _Ios_Openmode is implementation-defined, but it is valid to * perform bitwise operations on these values and expect the Right * Thing to happen. Defined objects of type openmode are: * - app * - ate * - binary * - in * - out * - trunc */ typedef _Ios_Openmode openmode; /// Seek to end before each write. static const openmode app = _S_app; /// Open and seek to end immediately after opening. static const openmode ate = _S_ate; /// Perform input and output in binary mode (as opposed to text mode). /// This is probably not what you think it is; see /// https://gcc.gnu.org/onlinedocs/libstdc++/manual/fstreams.html#std.io.filestreams.binary static const openmode binary = _S_bin; /// Open for input. Default for @c ifstream and fstream. static const openmode in = _S_in; /// Open for output. Default for @c ofstream and fstream. static const openmode out = _S_out; /// Truncate an existing stream when opening. Default for @c ofstream. static const openmode trunc = _S_trunc; // 27.4.2.1.5 Type ios_base::seekdir /** * @brief This is an enumerated type. * * @c @a _Ios_Seekdir is implementation-defined. Defined values * of type seekdir are: * - beg * - cur, equivalent to @c SEEK_CUR in the C standard library. * - end, equivalent to @c SEEK_END in the C standard library. */ typedef _Ios_Seekdir seekdir; /// Request a seek relative to the beginning of the stream. static const seekdir beg = _S_beg; /// Request a seek relative to the current position within the sequence. static const seekdir cur = _S_cur; /// Request a seek relative to the current end of the sequence. static const seekdir end = _S_end; #if __cplusplus <= 201402L // Annex D.6 (removed in C++17) typedef int io_state; typedef int open_mode; typedef int seek_dir; typedef std::streampos streampos; typedef std::streamoff streamoff; #endif // Callbacks; /** * @brief The set of events that may be passed to an event callback. * * erase_event is used during ~ios() and copyfmt(). imbue_event is used * during imbue(). copyfmt_event is used during copyfmt(). */ enum event { erase_event, imbue_event, copyfmt_event }; /** * @brief The type of an event callback function. * @param __e One of the members of the event enum. * @param __b Reference to the ios_base object. * @param __i The integer provided when the callback was registered. * * Event callbacks are user defined functions that get called during * several ios_base and basic_ios functions, specifically imbue(), * copyfmt(), and ~ios(). */ typedef void (*event_callback) (event __e, ios_base& __b, int __i); /** * @brief Add the callback __fn with parameter __index. * @param __fn The function to add. * @param __index The integer to pass to the function when invoked. * * Registers a function as an event callback with an integer parameter to * be passed to the function when invoked. Multiple copies of the * function are allowed. If there are multiple callbacks, they are * invoked in the order they were registered. */ void register_callback(event_callback __fn, int __index); protected: streamsize _M_precision; streamsize _M_width; fmtflags _M_flags; iostate _M_exception; iostate _M_streambuf_state; // 27.4.2.6 Members for callbacks // 27.4.2.6 ios_base callbacks struct _Callback_list { // Data Members _Callback_list* _M_next; ios_base::event_callback _M_fn; int _M_index; _Atomic_word _M_refcount; // 0 means one reference. _Callback_list(ios_base::event_callback __fn, int __index, _Callback_list* __cb) : _M_next(__cb), _M_fn(__fn), _M_index(__index), _M_refcount(0) { } void _M_add_reference() { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); } // 0 => OK to delete. int _M_remove_reference() { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_refcount); int __res = __gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1); if (__res == 0) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_refcount); } return __res; } }; _Callback_list* _M_callbacks; void _M_call_callbacks(event __ev) throw(); void _M_dispose_callbacks(void) throw(); // 27.4.2.5 Members for iword/pword storage struct _Words { void* _M_pword; long _M_iword; _Words() : _M_pword(0), _M_iword(0) { } }; // Only for failed iword/pword calls. _Words _M_word_zero; // Guaranteed storage. // The first 5 iword and pword slots are reserved for internal use. enum { _S_local_word_size = 8 }; _Words _M_local_word[_S_local_word_size]; // Allocated storage. int _M_word_size; _Words* _M_word; _Words& _M_grow_words(int __index, bool __iword); // Members for locale and locale caching. locale _M_ios_locale; void _M_init() throw(); public: // 27.4.2.1.6 Class ios_base::Init // Used to initialize standard streams. In theory, g++ could use // -finit-priority to order this stuff correctly without going // through these machinations. class Init { friend class ios_base; public: Init(); ~Init(); private: static _Atomic_word _S_refcount; static bool _S_synced_with_stdio; }; // [27.4.2.2] fmtflags state functions /** * @brief Access to format flags. * @return The format control flags for both input and output. */ fmtflags flags() const { return _M_flags; } /** * @brief Setting new format flags all at once. * @param __fmtfl The new flags to set. * @return The previous format control flags. * * This function overwrites all the format flags with @a __fmtfl. */ fmtflags flags(fmtflags __fmtfl) { fmtflags __old = _M_flags; _M_flags = __fmtfl; return __old; } /** * @brief Setting new format flags. * @param __fmtfl Additional flags to set. * @return The previous format control flags. * * This function sets additional flags in format control. Flags that * were previously set remain set. */ fmtflags setf(fmtflags __fmtfl) { fmtflags __old = _M_flags; _M_flags |= __fmtfl; return __old; } /** * @brief Setting new format flags. * @param __fmtfl Additional flags to set. * @param __mask The flags mask for @a fmtfl. * @return The previous format control flags. * * This function clears @a mask in the format flags, then sets * @a fmtfl @c & @a mask. An example mask is @c ios_base::adjustfield. */ fmtflags setf(fmtflags __fmtfl, fmtflags __mask) { fmtflags __old = _M_flags; _M_flags &= ~__mask; _M_flags |= (__fmtfl & __mask); return __old; } /** * @brief Clearing format flags. * @param __mask The flags to unset. * * This function clears @a __mask in the format flags. */ void unsetf(fmtflags __mask) { _M_flags &= ~__mask; } /** * @brief Flags access. * @return The precision to generate on certain output operations. * * Be careful if you try to give a definition of @a precision here; see * DR 189. */ streamsize precision() const { return _M_precision; } /** * @brief Changing flags. * @param __prec The new precision value. * @return The previous value of precision(). */ streamsize precision(streamsize __prec) { streamsize __old = _M_precision; _M_precision = __prec; return __old; } /** * @brief Flags access. * @return The minimum field width to generate on output operations. * * Minimum field width refers to the number of characters. */ streamsize width() const { return _M_width; } /** * @brief Changing flags. * @param __wide The new width value. * @return The previous value of width(). */ streamsize width(streamsize __wide) { streamsize __old = _M_width; _M_width = __wide; return __old; } // [27.4.2.4] ios_base static members /** * @brief Interaction with the standard C I/O objects. * @param __sync Whether to synchronize or not. * @return True if the standard streams were previously synchronized. * * The synchronization referred to is @e only that between the standard * C facilities (e.g., stdout) and the standard C++ objects (e.g., * cout). User-declared streams are unaffected. See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/fstreams.html#std.io.filestreams.binary */ static bool sync_with_stdio(bool __sync = true); // [27.4.2.3] ios_base locale functions /** * @brief Setting a new locale. * @param __loc The new locale. * @return The previous locale. * * Sets the new locale for this stream, and then invokes each callback * with imbue_event. */ locale imbue(const locale& __loc) throw(); /** * @brief Locale access * @return A copy of the current locale. * * If @c imbue(loc) has previously been called, then this function * returns @c loc. Otherwise, it returns a copy of @c std::locale(), * the global C++ locale. */ locale getloc() const { return _M_ios_locale; } /** * @brief Locale access * @return A reference to the current locale. * * Like getloc above, but returns a reference instead of * generating a copy. */ const locale& _M_getloc() const { return _M_ios_locale; } // [27.4.2.5] ios_base storage functions /** * @brief Access to unique indices. * @return An integer different from all previous calls. * * This function returns a unique integer every time it is called. It * can be used for any purpose, but is primarily intended to be a unique * index for the iword and pword functions. The expectation is that an * application calls xalloc in order to obtain an index in the iword and * pword arrays that can be used without fear of conflict. * * The implementation maintains a static variable that is incremented and * returned on each invocation. xalloc is guaranteed to return an index * that is safe to use in the iword and pword arrays. */ static int xalloc() throw(); /** * @brief Access to integer array. * @param __ix Index into the array. * @return A reference to an integer associated with the index. * * The iword function provides access to an array of integers that can be * used for any purpose. The array grows as required to hold the * supplied index. All integers in the array are initialized to 0. * * The implementation reserves several indices. You should use xalloc to * obtain an index that is safe to use. Also note that since the array * can grow dynamically, it is not safe to hold onto the reference. */ long& iword(int __ix) { _Words& __word = (__ix < _M_word_size) ? _M_word[__ix] : _M_grow_words(__ix, true); return __word._M_iword; } /** * @brief Access to void pointer array. * @param __ix Index into the array. * @return A reference to a void* associated with the index. * * The pword function provides access to an array of pointers that can be * used for any purpose. The array grows as required to hold the * supplied index. All pointers in the array are initialized to 0. * * The implementation reserves several indices. You should use xalloc to * obtain an index that is safe to use. Also note that since the array * can grow dynamically, it is not safe to hold onto the reference. */ void*& pword(int __ix) { _Words& __word = (__ix < _M_word_size) ? _M_word[__ix] : _M_grow_words(__ix, false); return __word._M_pword; } // Destructor /** * Invokes each callback with erase_event. Destroys local storage. * * Note that the ios_base object for the standard streams never gets * destroyed. As a result, any callbacks registered with the standard * streams will not get invoked with erase_event (unless copyfmt is * used). */ virtual ~ios_base(); protected: ios_base() throw (); #if __cplusplus < 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 50. Copy constructor and assignment operator of ios_base private: ios_base(const ios_base&); ios_base& operator=(const ios_base&); #else public: ios_base(const ios_base&) = delete; ios_base& operator=(const ios_base&) = delete; protected: void _M_move(ios_base&) noexcept; void _M_swap(ios_base& __rhs) noexcept; #endif }; // [27.4.5.1] fmtflags manipulators /// Calls base.setf(ios_base::boolalpha). inline ios_base& boolalpha(ios_base& __base) { __base.setf(ios_base::boolalpha); return __base; } /// Calls base.unsetf(ios_base::boolalpha). inline ios_base& noboolalpha(ios_base& __base) { __base.unsetf(ios_base::boolalpha); return __base; } /// Calls base.setf(ios_base::showbase). inline ios_base& showbase(ios_base& __base) { __base.setf(ios_base::showbase); return __base; } /// Calls base.unsetf(ios_base::showbase). inline ios_base& noshowbase(ios_base& __base) { __base.unsetf(ios_base::showbase); return __base; } /// Calls base.setf(ios_base::showpoint). inline ios_base& showpoint(ios_base& __base) { __base.setf(ios_base::showpoint); return __base; } /// Calls base.unsetf(ios_base::showpoint). inline ios_base& noshowpoint(ios_base& __base) { __base.unsetf(ios_base::showpoint); return __base; } /// Calls base.setf(ios_base::showpos). inline ios_base& showpos(ios_base& __base) { __base.setf(ios_base::showpos); return __base; } /// Calls base.unsetf(ios_base::showpos). inline ios_base& noshowpos(ios_base& __base) { __base.unsetf(ios_base::showpos); return __base; } /// Calls base.setf(ios_base::skipws). inline ios_base& skipws(ios_base& __base) { __base.setf(ios_base::skipws); return __base; } /// Calls base.unsetf(ios_base::skipws). inline ios_base& noskipws(ios_base& __base) { __base.unsetf(ios_base::skipws); return __base; } /// Calls base.setf(ios_base::uppercase). inline ios_base& uppercase(ios_base& __base) { __base.setf(ios_base::uppercase); return __base; } /// Calls base.unsetf(ios_base::uppercase). inline ios_base& nouppercase(ios_base& __base) { __base.unsetf(ios_base::uppercase); return __base; } /// Calls base.setf(ios_base::unitbuf). inline ios_base& unitbuf(ios_base& __base) { __base.setf(ios_base::unitbuf); return __base; } /// Calls base.unsetf(ios_base::unitbuf). inline ios_base& nounitbuf(ios_base& __base) { __base.unsetf(ios_base::unitbuf); return __base; } // [27.4.5.2] adjustfield manipulators /// Calls base.setf(ios_base::internal, ios_base::adjustfield). inline ios_base& internal(ios_base& __base) { __base.setf(ios_base::internal, ios_base::adjustfield); return __base; } /// Calls base.setf(ios_base::left, ios_base::adjustfield). inline ios_base& left(ios_base& __base) { __base.setf(ios_base::left, ios_base::adjustfield); return __base; } /// Calls base.setf(ios_base::right, ios_base::adjustfield). inline ios_base& right(ios_base& __base) { __base.setf(ios_base::right, ios_base::adjustfield); return __base; } // [27.4.5.3] basefield manipulators /// Calls base.setf(ios_base::dec, ios_base::basefield). inline ios_base& dec(ios_base& __base) { __base.setf(ios_base::dec, ios_base::basefield); return __base; } /// Calls base.setf(ios_base::hex, ios_base::basefield). inline ios_base& hex(ios_base& __base) { __base.setf(ios_base::hex, ios_base::basefield); return __base; } /// Calls base.setf(ios_base::oct, ios_base::basefield). inline ios_base& oct(ios_base& __base) { __base.setf(ios_base::oct, ios_base::basefield); return __base; } // [27.4.5.4] floatfield manipulators /// Calls base.setf(ios_base::fixed, ios_base::floatfield). inline ios_base& fixed(ios_base& __base) { __base.setf(ios_base::fixed, ios_base::floatfield); return __base; } /// Calls base.setf(ios_base::scientific, ios_base::floatfield). inline ios_base& scientific(ios_base& __base) { __base.setf(ios_base::scientific, ios_base::floatfield); return __base; } #if __cplusplus >= 201103L // New C++11 floatfield manipulators /// Calls /// base.setf(ios_base::fixed|ios_base::scientific, ios_base::floatfield) inline ios_base& hexfloat(ios_base& __base) { __base.setf(ios_base::fixed | ios_base::scientific, ios_base::floatfield); return __base; } /// Calls @c base.unsetf(ios_base::floatfield) inline ios_base& defaultfloat(ios_base& __base) { __base.unsetf(ios_base::floatfield); return __base; } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _IOS_BASE_H */ c++/8/bits/specfun.h000064400000133713151027430570010054 0ustar00// Mathematical Special Functions for -*- C++ -*- // Copyright (C) 2006-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/specfun.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cmath} */ #ifndef _GLIBCXX_BITS_SPECFUN_H #define _GLIBCXX_BITS_SPECFUN_H 1 #pragma GCC visibility push(default) #include #define __STDCPP_MATH_SPEC_FUNCS__ 201003L #define __cpp_lib_math_special_functions 201603L #if __cplusplus <= 201403L && __STDCPP_WANT_MATH_SPEC_FUNCS__ == 0 # error include and define __STDCPP_WANT_MATH_SPEC_FUNCS__ #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup mathsf Mathematical Special Functions * @ingroup numerics * * A collection of advanced mathematical special functions, * defined by ISO/IEC IS 29124. * @{ */ /** * @mainpage Mathematical Special Functions * * @section intro Introduction and History * The first significant library upgrade on the road to C++2011, * * TR1, included a set of 23 mathematical functions that significantly * extended the standard transcendental functions inherited from C and declared * in @. * * Although most components from TR1 were eventually adopted for C++11 these * math functions were left behind out of concern for implementability. * The math functions were published as a separate international standard * * IS 29124 - Extensions to the C++ Library to Support Mathematical Special * Functions. * * For C++17 these functions were incorporated into the main standard. * * @section contents Contents * The following functions are implemented in namespace @c std: * - @ref assoc_laguerre "assoc_laguerre - Associated Laguerre functions" * - @ref assoc_legendre "assoc_legendre - Associated Legendre functions" * - @ref beta "beta - Beta functions" * - @ref comp_ellint_1 "comp_ellint_1 - Complete elliptic functions of the first kind" * - @ref comp_ellint_2 "comp_ellint_2 - Complete elliptic functions of the second kind" * - @ref comp_ellint_3 "comp_ellint_3 - Complete elliptic functions of the third kind" * - @ref cyl_bessel_i "cyl_bessel_i - Regular modified cylindrical Bessel functions" * - @ref cyl_bessel_j "cyl_bessel_j - Cylindrical Bessel functions of the first kind" * - @ref cyl_bessel_k "cyl_bessel_k - Irregular modified cylindrical Bessel functions" * - @ref cyl_neumann "cyl_neumann - Cylindrical Neumann functions or Cylindrical Bessel functions of the second kind" * - @ref ellint_1 "ellint_1 - Incomplete elliptic functions of the first kind" * - @ref ellint_2 "ellint_2 - Incomplete elliptic functions of the second kind" * - @ref ellint_3 "ellint_3 - Incomplete elliptic functions of the third kind" * - @ref expint "expint - The exponential integral" * - @ref hermite "hermite - Hermite polynomials" * - @ref laguerre "laguerre - Laguerre functions" * - @ref legendre "legendre - Legendre polynomials" * - @ref riemann_zeta "riemann_zeta - The Riemann zeta function" * - @ref sph_bessel "sph_bessel - Spherical Bessel functions" * - @ref sph_legendre "sph_legendre - Spherical Legendre functions" * - @ref sph_neumann "sph_neumann - Spherical Neumann functions" * * The hypergeometric functions were stricken from the TR29124 and C++17 * versions of this math library because of implementation concerns. * However, since they were in the TR1 version and since they are popular * we kept them as an extension in namespace @c __gnu_cxx: * - @ref __gnu_cxx::conf_hyperg "conf_hyperg - Confluent hypergeometric functions" * - @ref __gnu_cxx::hyperg "hyperg - Hypergeometric functions" * * @section general General Features * * @subsection promotion Argument Promotion * The arguments suppled to the non-suffixed functions will be promoted * according to the following rules: * 1. If any argument intended to be floating point is given an integral value * That integral value is promoted to double. * 2. All floating point arguments are promoted up to the largest floating * point precision among them. * * @subsection NaN NaN Arguments * If any of the floating point arguments supplied to these functions is * invalid or NaN (std::numeric_limits::quiet_NaN), * the value NaN is returned. * * @section impl Implementation * * We strive to implement the underlying math with type generic algorithms * to the greatest extent possible. In practice, the functions are thin * wrappers that dispatch to function templates. Type dependence is * controlled with std::numeric_limits and functions thereof. * * We don't promote @c float to @c double or @c double to long double * reflexively. The goal is for @c float functions to operate more quickly, * at the cost of @c float accuracy and possibly a smaller domain of validity. * Similaryly, long double should give you more dynamic range * and slightly more pecision than @c double on many systems. * * @section testing Testing * * These functions have been tested against equivalent implementations * from the * Gnu Scientific Library, GSL and * pbase()) __tmp.assign(this->pbase(), this->epptr() - this->pbase()); __tmp.push_back(__conv); _M_string.swap(__tmp); _M_sync(const_cast(_M_string.data()), this->gptr() - this->eback(), this->pptr() - this->pbase()); } else *this->pptr() = __conv; this->pbump(1); return __c; } template typename basic_stringbuf<_CharT, _Traits, _Alloc>::int_type basic_stringbuf<_CharT, _Traits, _Alloc>:: underflow() { int_type __ret = traits_type::eof(); const bool __testin = this->_M_mode & ios_base::in; if (__testin) { // Update egptr() to match the actual string end. _M_update_egptr(); if (this->gptr() < this->egptr()) __ret = traits_type::to_int_type(*this->gptr()); } return __ret; } template typename basic_stringbuf<_CharT, _Traits, _Alloc>::pos_type basic_stringbuf<_CharT, _Traits, _Alloc>:: seekoff(off_type __off, ios_base::seekdir __way, ios_base::openmode __mode) { pos_type __ret = pos_type(off_type(-1)); bool __testin = (ios_base::in & this->_M_mode & __mode) != 0; bool __testout = (ios_base::out & this->_M_mode & __mode) != 0; const bool __testboth = __testin && __testout && __way != ios_base::cur; __testin &= !(__mode & ios_base::out); __testout &= !(__mode & ios_base::in); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 453. basic_stringbuf::seekoff need not always fail for an empty stream. const char_type* __beg = __testin ? this->eback() : this->pbase(); if ((__beg || !__off) && (__testin || __testout || __testboth)) { _M_update_egptr(); off_type __newoffi = __off; off_type __newoffo = __newoffi; if (__way == ios_base::cur) { __newoffi += this->gptr() - __beg; __newoffo += this->pptr() - __beg; } else if (__way == ios_base::end) __newoffo = __newoffi += this->egptr() - __beg; if ((__testin || __testboth) && __newoffi >= 0 && this->egptr() - __beg >= __newoffi) { this->setg(this->eback(), this->eback() + __newoffi, this->egptr()); __ret = pos_type(__newoffi); } if ((__testout || __testboth) && __newoffo >= 0 && this->egptr() - __beg >= __newoffo) { _M_pbump(this->pbase(), this->epptr(), __newoffo); __ret = pos_type(__newoffo); } } return __ret; } template typename basic_stringbuf<_CharT, _Traits, _Alloc>::pos_type basic_stringbuf<_CharT, _Traits, _Alloc>:: seekpos(pos_type __sp, ios_base::openmode __mode) { pos_type __ret = pos_type(off_type(-1)); const bool __testin = (ios_base::in & this->_M_mode & __mode) != 0; const bool __testout = (ios_base::out & this->_M_mode & __mode) != 0; const char_type* __beg = __testin ? this->eback() : this->pbase(); if ((__beg || !off_type(__sp)) && (__testin || __testout)) { _M_update_egptr(); const off_type __pos(__sp); const bool __testpos = (0 <= __pos && __pos <= this->egptr() - __beg); if (__testpos) { if (__testin) this->setg(this->eback(), this->eback() + __pos, this->egptr()); if (__testout) _M_pbump(this->pbase(), this->epptr(), __pos); __ret = __sp; } } return __ret; } template void basic_stringbuf<_CharT, _Traits, _Alloc>:: _M_sync(char_type* __base, __size_type __i, __size_type __o) { const bool __testin = _M_mode & ios_base::in; const bool __testout = _M_mode & ios_base::out; char_type* __endg = __base + _M_string.size(); char_type* __endp = __base + _M_string.capacity(); if (__base != _M_string.data()) { // setbuf: __i == size of buffer area (_M_string.size() == 0). __endg += __i; __i = 0; __endp = __endg; } if (__testin) this->setg(__base, __base + __i, __endg); if (__testout) { _M_pbump(__base, __endp, __o); // egptr() always tracks the string end. When !__testin, // for the correct functioning of the streambuf inlines // the other get area pointers are identical. if (!__testin) this->setg(__endg, __endg, __endg); } } template void basic_stringbuf<_CharT, _Traits, _Alloc>:: _M_pbump(char_type* __pbeg, char_type* __pend, off_type __off) { this->setp(__pbeg, __pend); while (__off > __gnu_cxx::__numeric_traits::__max) { this->pbump(__gnu_cxx::__numeric_traits::__max); __off -= __gnu_cxx::__numeric_traits::__max; } this->pbump(__off); } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_stringbuf; extern template class basic_istringstream; extern template class basic_ostringstream; extern template class basic_stringstream; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_stringbuf; extern template class basic_istringstream; extern template class basic_ostringstream; extern template class basic_stringstream; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/stl_raw_storage_iter.h000064400000007366151027430570012637 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_raw_storage_iter.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _STL_RAW_STORAGE_ITERATOR_H #define _STL_RAW_STORAGE_ITERATOR_H 1 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * This iterator class lets algorithms store their results into * uninitialized memory. */ template class raw_storage_iterator : public iterator { protected: _OutputIterator _M_iter; public: explicit raw_storage_iterator(_OutputIterator __x) : _M_iter(__x) {} raw_storage_iterator& operator*() { return *this; } raw_storage_iterator& operator=(const _Tp& __element) { std::_Construct(std::__addressof(*_M_iter), __element); return *this; } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2127. Move-construction with raw_storage_iterator raw_storage_iterator& operator=(_Tp&& __element) { std::_Construct(std::__addressof(*_M_iter), std::move(__element)); return *this; } #endif raw_storage_iterator& operator++() { ++_M_iter; return *this; } raw_storage_iterator operator++(int) { raw_storage_iterator __tmp = *this; ++_M_iter; return __tmp; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2454. Add raw_storage_iterator::base() member _OutputIterator base() const { return _M_iter; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/bits/alloc_traits.h000064400000047142151027430570011071 0ustar00// Allocator traits -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/alloc_traits.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _ALLOC_TRAITS_H #define _ALLOC_TRAITS_H 1 #if __cplusplus >= 201103L #include #include #include #define __cpp_lib_allocator_traits_is_always_equal 201411 namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct __allocator_traits_base { template struct __rebind : __replace_first_arg<_Tp, _Up> { }; template struct __rebind<_Tp, _Up, __void_t::other>> { using type = typename _Tp::template rebind<_Up>::other; }; protected: template using __pointer = typename _Tp::pointer; template using __c_pointer = typename _Tp::const_pointer; template using __v_pointer = typename _Tp::void_pointer; template using __cv_pointer = typename _Tp::const_void_pointer; template using __pocca = typename _Tp::propagate_on_container_copy_assignment; template using __pocma = typename _Tp::propagate_on_container_move_assignment; template using __pocs = typename _Tp::propagate_on_container_swap; template using __equal = typename _Tp::is_always_equal; }; template using __alloc_rebind = typename __allocator_traits_base::template __rebind<_Alloc, _Up>::type; /** * @brief Uniform interface to all allocator types. * @ingroup allocators */ template struct allocator_traits : __allocator_traits_base { /// The allocator type typedef _Alloc allocator_type; /// The allocated type typedef typename _Alloc::value_type value_type; /** * @brief The allocator's pointer type. * * @c Alloc::pointer if that type exists, otherwise @c value_type* */ using pointer = __detected_or_t; private: // Select _Func<_Alloc> or pointer_traits::rebind<_Tp> template class _Func, typename _Tp, typename = void> struct _Ptr { using type = typename pointer_traits::template rebind<_Tp>; }; template class _Func, typename _Tp> struct _Ptr<_Func, _Tp, __void_t<_Func<_Alloc>>> { using type = _Func<_Alloc>; }; // Select _A2::difference_type or pointer_traits<_Ptr>::difference_type template struct _Diff { using type = typename pointer_traits<_PtrT>::difference_type; }; template struct _Diff<_A2, _PtrT, __void_t> { using type = typename _A2::difference_type; }; // Select _A2::size_type or make_unsigned<_DiffT>::type template struct _Size : make_unsigned<_DiffT> { }; template struct _Size<_A2, _DiffT, __void_t> { using type = typename _A2::size_type; }; public: /** * @brief The allocator's const pointer type. * * @c Alloc::const_pointer if that type exists, otherwise * pointer_traits::rebind */ using const_pointer = typename _Ptr<__c_pointer, const value_type>::type; /** * @brief The allocator's void pointer type. * * @c Alloc::void_pointer if that type exists, otherwise * pointer_traits::rebind */ using void_pointer = typename _Ptr<__v_pointer, void>::type; /** * @brief The allocator's const void pointer type. * * @c Alloc::const_void_pointer if that type exists, otherwise * pointer_traits::rebind */ using const_void_pointer = typename _Ptr<__cv_pointer, const void>::type; /** * @brief The allocator's difference type * * @c Alloc::difference_type if that type exists, otherwise * pointer_traits::difference_type */ using difference_type = typename _Diff<_Alloc, pointer>::type; /** * @brief The allocator's size type * * @c Alloc::size_type if that type exists, otherwise * make_unsigned::type */ using size_type = typename _Size<_Alloc, difference_type>::type; /** * @brief How the allocator is propagated on copy assignment * * @c Alloc::propagate_on_container_copy_assignment if that type exists, * otherwise @c false_type */ using propagate_on_container_copy_assignment = __detected_or_t; /** * @brief How the allocator is propagated on move assignment * * @c Alloc::propagate_on_container_move_assignment if that type exists, * otherwise @c false_type */ using propagate_on_container_move_assignment = __detected_or_t; /** * @brief How the allocator is propagated on swap * * @c Alloc::propagate_on_container_swap if that type exists, * otherwise @c false_type */ using propagate_on_container_swap = __detected_or_t; /** * @brief Whether all instances of the allocator type compare equal. * * @c Alloc::is_always_equal if that type exists, * otherwise @c is_empty::type */ using is_always_equal = __detected_or_t::type, __equal, _Alloc>; template using rebind_alloc = __alloc_rebind<_Alloc, _Tp>; template using rebind_traits = allocator_traits>; private: template static auto _S_allocate(_Alloc2& __a, size_type __n, const_void_pointer __hint, int) -> decltype(__a.allocate(__n, __hint)) { return __a.allocate(__n, __hint); } template static pointer _S_allocate(_Alloc2& __a, size_type __n, const_void_pointer, ...) { return __a.allocate(__n); } template struct __construct_helper { template()->construct( std::declval<_Tp*>(), std::declval<_Args>()...))> static true_type __test(int); template static false_type __test(...); using type = decltype(__test<_Alloc>(0)); }; template using __has_construct = typename __construct_helper<_Tp, _Args...>::type; template static _Require<__has_construct<_Tp, _Args...>> _S_construct(_Alloc& __a, _Tp* __p, _Args&&... __args) { __a.construct(__p, std::forward<_Args>(__args)...); } template static _Require<__and_<__not_<__has_construct<_Tp, _Args...>>, is_constructible<_Tp, _Args...>>> _S_construct(_Alloc&, _Tp* __p, _Args&&... __args) { ::new((void*)__p) _Tp(std::forward<_Args>(__args)...); } template static auto _S_destroy(_Alloc2& __a, _Tp* __p, int) -> decltype(__a.destroy(__p)) { __a.destroy(__p); } template static void _S_destroy(_Alloc2&, _Tp* __p, ...) { __p->~_Tp(); } template static auto _S_max_size(_Alloc2& __a, int) -> decltype(__a.max_size()) { return __a.max_size(); } template static size_type _S_max_size(_Alloc2&, ...) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2466. allocator_traits::max_size() default behavior is incorrect return __gnu_cxx::__numeric_traits::__max / sizeof(value_type); } template static auto _S_select(_Alloc2& __a, int) -> decltype(__a.select_on_container_copy_construction()) { return __a.select_on_container_copy_construction(); } template static _Alloc2 _S_select(_Alloc2& __a, ...) { return __a; } public: /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * * Calls @c a.allocate(n) */ static pointer allocate(_Alloc& __a, size_type __n) { return __a.allocate(__n); } /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * @param __hint Aid to locality. * @return Memory of suitable size and alignment for @a n objects * of type @c value_type * * Returns a.allocate(n, hint) if that expression is * well-formed, otherwise returns @c a.allocate(n) */ static pointer allocate(_Alloc& __a, size_type __n, const_void_pointer __hint) { return _S_allocate(__a, __n, __hint, 0); } /** * @brief Deallocate memory. * @param __a An allocator. * @param __p Pointer to the memory to deallocate. * @param __n The number of objects space was allocated for. * * Calls a.deallocate(p, n) */ static void deallocate(_Alloc& __a, pointer __p, size_type __n) { __a.deallocate(__p, __n); } /** * @brief Construct an object of type @a _Tp * @param __a An allocator. * @param __p Pointer to memory of suitable size and alignment for Tp * @param __args Constructor arguments. * * Calls __a.construct(__p, std::forward(__args)...) * if that expression is well-formed, otherwise uses placement-new * to construct an object of type @a _Tp at location @a __p from the * arguments @a __args... */ template static auto construct(_Alloc& __a, _Tp* __p, _Args&&... __args) -> decltype(_S_construct(__a, __p, std::forward<_Args>(__args)...)) { _S_construct(__a, __p, std::forward<_Args>(__args)...); } /** * @brief Destroy an object of type @a _Tp * @param __a An allocator. * @param __p Pointer to the object to destroy * * Calls @c __a.destroy(__p) if that expression is well-formed, * otherwise calls @c __p->~_Tp() */ template static void destroy(_Alloc& __a, _Tp* __p) { _S_destroy(__a, __p, 0); } /** * @brief The maximum supported allocation size * @param __a An allocator. * @return @c __a.max_size() or @c numeric_limits::max() * * Returns @c __a.max_size() if that expression is well-formed, * otherwise returns @c numeric_limits::max() */ static size_type max_size(const _Alloc& __a) noexcept { return _S_max_size(__a, 0); } /** * @brief Obtain an allocator to use when copying a container. * @param __rhs An allocator. * @return @c __rhs.select_on_container_copy_construction() or @a __rhs * * Returns @c __rhs.select_on_container_copy_construction() if that * expression is well-formed, otherwise returns @a __rhs */ static _Alloc select_on_container_copy_construction(const _Alloc& __rhs) { return _S_select(__rhs, 0); } }; /// Partial specialization for std::allocator. template struct allocator_traits> { /// The allocator type using allocator_type = allocator<_Tp>; /// The allocated type using value_type = _Tp; /// The allocator's pointer type. using pointer = _Tp*; /// The allocator's const pointer type. using const_pointer = const _Tp*; /// The allocator's void pointer type. using void_pointer = void*; /// The allocator's const void pointer type. using const_void_pointer = const void*; /// The allocator's difference type using difference_type = std::ptrdiff_t; /// The allocator's size type using size_type = std::size_t; /// How the allocator is propagated on copy assignment using propagate_on_container_copy_assignment = false_type; /// How the allocator is propagated on move assignment using propagate_on_container_move_assignment = true_type; /// How the allocator is propagated on swap using propagate_on_container_swap = false_type; /// Whether all instances of the allocator type compare equal. using is_always_equal = true_type; template using rebind_alloc = allocator<_Up>; template using rebind_traits = allocator_traits>; /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * * Calls @c a.allocate(n) */ static pointer allocate(allocator_type& __a, size_type __n) { return __a.allocate(__n); } /** * @brief Allocate memory. * @param __a An allocator. * @param __n The number of objects to allocate space for. * @param __hint Aid to locality. * @return Memory of suitable size and alignment for @a n objects * of type @c value_type * * Returns a.allocate(n, hint) */ static pointer allocate(allocator_type& __a, size_type __n, const_void_pointer __hint) { return __a.allocate(__n, __hint); } /** * @brief Deallocate memory. * @param __a An allocator. * @param __p Pointer to the memory to deallocate. * @param __n The number of objects space was allocated for. * * Calls a.deallocate(p, n) */ static void deallocate(allocator_type& __a, pointer __p, size_type __n) { __a.deallocate(__p, __n); } /** * @brief Construct an object of type @a _Up * @param __a An allocator. * @param __p Pointer to memory of suitable size and alignment for Tp * @param __args Constructor arguments. * * Calls __a.construct(__p, std::forward(__args)...) */ template static void construct(allocator_type& __a, _Up* __p, _Args&&... __args) { __a.construct(__p, std::forward<_Args>(__args)...); } /** * @brief Destroy an object of type @a _Up * @param __a An allocator. * @param __p Pointer to the object to destroy * * Calls @c __a.destroy(__p). */ template static void destroy(allocator_type& __a, _Up* __p) { __a.destroy(__p); } /** * @brief The maximum supported allocation size * @param __a An allocator. * @return @c __a.max_size() */ static size_type max_size(const allocator_type& __a) noexcept { return __a.max_size(); } /** * @brief Obtain an allocator to use when copying a container. * @param __rhs An allocator. * @return @c __rhs */ static allocator_type select_on_container_copy_construction(const allocator_type& __rhs) { return __rhs; } }; template inline void __do_alloc_on_copy(_Alloc& __one, const _Alloc& __two, true_type) { __one = __two; } template inline void __do_alloc_on_copy(_Alloc&, const _Alloc&, false_type) { } template inline void __alloc_on_copy(_Alloc& __one, const _Alloc& __two) { typedef allocator_traits<_Alloc> __traits; typedef typename __traits::propagate_on_container_copy_assignment __pocca; __do_alloc_on_copy(__one, __two, __pocca()); } template inline _Alloc __alloc_on_copy(const _Alloc& __a) { typedef allocator_traits<_Alloc> __traits; return __traits::select_on_container_copy_construction(__a); } template inline void __do_alloc_on_move(_Alloc& __one, _Alloc& __two, true_type) { __one = std::move(__two); } template inline void __do_alloc_on_move(_Alloc&, _Alloc&, false_type) { } template inline void __alloc_on_move(_Alloc& __one, _Alloc& __two) { typedef allocator_traits<_Alloc> __traits; typedef typename __traits::propagate_on_container_move_assignment __pocma; __do_alloc_on_move(__one, __two, __pocma()); } template inline void __do_alloc_on_swap(_Alloc& __one, _Alloc& __two, true_type) { using std::swap; swap(__one, __two); } template inline void __do_alloc_on_swap(_Alloc&, _Alloc&, false_type) { } template inline void __alloc_on_swap(_Alloc& __one, _Alloc& __two) { typedef allocator_traits<_Alloc> __traits; typedef typename __traits::propagate_on_container_swap __pocs; __do_alloc_on_swap(__one, __two, __pocs()); } template class __is_copy_insertable_impl { typedef allocator_traits<_Alloc> _Traits; template(), std::declval<_Up*>(), std::declval()))> static true_type _M_select(int); template static false_type _M_select(...); public: typedef decltype(_M_select(0)) type; }; // true if _Alloc::value_type is CopyInsertable into containers using _Alloc template struct __is_copy_insertable : __is_copy_insertable_impl<_Alloc>::type { }; // std::allocator<_Tp> just requires CopyConstructible template struct __is_copy_insertable> : is_copy_constructible<_Tp> { }; // Trait to detect Allocator-like types. template struct __is_allocator : false_type { }; template struct __is_allocator<_Alloc, __void_t().allocate(size_t{}))>> : true_type { }; template using _RequireAllocator = typename enable_if<__is_allocator<_Alloc>::value, _Alloc>::type; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _ALLOC_TRAITS_H c++/8/bits/unordered_map.h000064400000223115151027430570011231 0ustar00// unordered_map implementation -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/unordered_map.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{unordered_map} */ #ifndef _UNORDERED_MAP_H #define _UNORDERED_MAP_H namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /// Base types for unordered_map. template using __umap_traits = __detail::_Hashtable_traits<_Cache, false, true>; template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator >, typename _Tr = __umap_traits<__cache_default<_Key, _Hash>::value>> using __umap_hashtable = _Hashtable<_Key, std::pair, _Alloc, __detail::_Select1st, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; /// Base types for unordered_multimap. template using __ummap_traits = __detail::_Hashtable_traits<_Cache, false, false>; template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator >, typename _Tr = __ummap_traits<__cache_default<_Key, _Hash>::value>> using __ummap_hashtable = _Hashtable<_Key, std::pair, _Alloc, __detail::_Select1st, _Pred, _Hash, __detail::_Mod_range_hashing, __detail::_Default_ranged_hash, __detail::_Prime_rehash_policy, _Tr>; template class unordered_multimap; /** * @brief A standard container composed of unique keys (containing * at most one of each key value) that associates values of another type * with the keys. * * @ingroup unordered_associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults * to equal_to<_Value>. * @tparam _Alloc Allocator type, defaults to * std::allocator>. * * Meets the requirements of a container, and * unordered associative container * * The resulting value type of the container is std::pair. * * Base is _Hashtable, dispatched at compile time via template * alias __umap_hashtable. */ template, typename _Pred = equal_to<_Key>, typename _Alloc = allocator>> class unordered_map { typedef __umap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::mapped_type mapped_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; using insert_return_type = typename _Hashtable::insert_return_type; #endif //construct/destroy/copy /// Default constructor. unordered_map() = default; /** * @brief Default constructor creates no elements. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_map(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_map from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_map consisting of copies of the elements from * [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_map(const unordered_map&) = default; /// Move constructor. unordered_map(unordered_map&&) = default; /** * @brief Creates an %unordered_map with no elements. * @param __a An allocator object. */ explicit unordered_map(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_map to copy. * @param __a An allocator object. */ unordered_map(const unordered_map& __umap, const allocator_type& __a) : _M_h(__umap._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __uset Input %unordered_map to move. * @param __a An allocator object. */ unordered_map(unordered_map&& __umap, const allocator_type& __a) : _M_h(std::move(__umap._M_h), __a) { } /** * @brief Builds an %unordered_map from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_map consisting of copies of the elements in the * list. This is linear in N (where N is @a __l.size()). */ unordered_map(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } unordered_map(size_type __n, const allocator_type& __a) : unordered_map(__n, hasher(), key_equal(), __a) { } unordered_map(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__n, __hf, key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_map(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__first, __last, __n, __hf, key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_map(__l, __n, hasher(), key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__l, __n, __hf, key_equal(), __a) { } /// Copy assignment operator. unordered_map& operator=(const unordered_map&) = default; /// Move assignment operator. unordered_map& operator=(unordered_map&&) = default; /** * @brief %Unordered_map list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_map with copies of the elements in * the initializer list @a __l. * * Note that the assignment completely changes the %unordered_map and * that the resulting %unordered_map's size is the same as the number * of elements assigned. */ unordered_map& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_map. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_map is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_map. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_map. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. /** * Returns a read/write iterator that points to the first element in the * %unordered_map. */ iterator begin() noexcept { return _M_h.begin(); } //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_map. */ const_iterator begin() const noexcept { return _M_h.begin(); } const_iterator cbegin() const noexcept { return _M_h.begin(); } //@} /** * Returns a read/write iterator that points one past the last element in * the %unordered_map. */ iterator end() noexcept { return _M_h.end(); } //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_map. */ const_iterator end() const noexcept { return _M_h.end(); } const_iterator cend() const noexcept { return _M_h.end(); } //@} // modifiers. /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %unordered_map. * An %unordered_map relies on unique keys and thus a %pair is only * inserted if its first element (the key) is not already present in the * %unordered_map. * * Insertion requires amortized constant time. */ template std::pair emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. insert_return_type insert(node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator, node_type&& __nh) { return _M_h._M_reinsert_node(std::move(__nh)).position; } #define __cpp_lib_unordered_map_try_emplace 201411 /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __k Key to use for finding a possibly existing pair in * the unordered_map. * @param __args Arguments used to generate the .second for a * new pair instance. * * @return A pair, of which the first element is an iterator that points * to the possibly inserted pair, and the second is a bool that * is true if the pair was actually inserted. * * This function attempts to build and insert a (key, value) %pair into * the %unordered_map. * An %unordered_map relies on unique keys and thus a %pair is only * inserted if its first element (the key) is not already present in the * %unordered_map. * If a %pair is not inserted, this function has no effect. * * Insertion requires amortized constant time. */ template pair try_emplace(const key_type& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)) .first; return {__i, true}; } return {__i, false}; } // move-capable overload template pair try_emplace(key_type&& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)) .first; return {__i, true}; } return {__i, false}; } /** * @brief Attempts to build and insert a std::pair into the * %unordered_map. * * @param __hint An iterator that serves as a hint as to where the pair * should be inserted. * @param __k Key to use for finding a possibly existing pair in * the unordered_map. * @param __args Arguments used to generate the .second for a * new pair instance. * @return An iterator that points to the element with key of the * std::pair built from @a __args (may or may not be that * std::pair). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument emplace() * does. However, if insertion did not take place, * this function has no effect. * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) __i = emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Args>(__args)...)); return __i; } // move-capable overload template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { iterator __i = find(__k); if (__i == end()) __i = emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Args>(__args)...)); return __i; } #endif // C++17 //@{ /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __x Pair to be inserted (see std::make_pair for easy * creation of pairs). * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the * %unordered_map. An %unordered_map relies on unique keys and thus a * %pair is only inserted if its first element (the key) is not already * present in the %unordered_map. * * Insertion requires amortized constant time. */ std::pair insert(const value_type& __x) { return _M_h.insert(__x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } template __enable_if_t::value, pair> insert(_Pair&& __x) { return _M_h.emplace(std::forward<_Pair>(__x)); } //@} //@{ /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __hint, _Pair&& __x) { return _M_h.emplace_hint(__hint, std::forward<_Pair>(__x)); } //@} /** * @brief A template function that attempts to insert a range of * elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Attempts to insert a list of elements into the %unordered_map. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L #define __cpp_lib_unordered_map_insertion 201411 /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __k Key to use for finding a possibly existing pair in * the map. * @param __obj Argument used to generate the .second for a pair * instance. * * @return A pair, of which the first element is an iterator that * points to the possibly inserted pair, and the second is * a bool that is true if the pair was actually inserted. * * This function attempts to insert a (key, value) %pair into the * %unordered_map. An %unordered_map relies on unique keys and thus a * %pair is only inserted if its first element (the key) is not already * present in the %unordered_map. * If the %pair was already in the %unordered_map, the .second of * the %pair is assigned from __obj. * * Insertion requires amortized constant time. */ template pair insert_or_assign(const key_type& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple(std::forward<_Obj>(__obj))) .first; return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } // move-capable overload template pair insert_or_assign(key_type&& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { __i = emplace(std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple(std::forward<_Obj>(__obj))) .first; return {__i, true}; } (*__i).second = std::forward<_Obj>(__obj); return {__i, false}; } /** * @brief Attempts to insert a std::pair into the %unordered_map. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __k Key to use for finding a possibly existing pair in * the unordered_map. * @param __obj Argument used to generate the .second for a pair * instance. * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * This function is not concerned about whether the insertion took place, * and thus does not return a boolean like the single-argument insert() * does. * If the %pair was already in the %unordered map, the .second of * the %pair is assigned from __obj. * Note that the first parameter is only a hint and can * potentially improve the performance of the insertion process. A bad * hint would cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { return emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(__k), std::forward_as_tuple( std::forward<_Obj>(__obj))); } (*__i).second = std::forward<_Obj>(__obj); return __i; } // move-capable overload template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { iterator __i = find(__k); if (__i == end()) { return emplace_hint(__hint, std::piecewise_construct, std::forward_as_tuple(std::move(__k)), std::forward_as_tuple( std::forward<_Obj>(__obj))); } (*__i).second = std::forward<_Obj>(__obj); return __i; } #endif //@{ /** * @brief Erases an element from an %unordered_map. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_map. * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of element to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_map. For an %unordered_map the result of this function * can only be 0 (not present) or 1 (present). * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_map. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an %unordered_map. * Note that this function only erases the elements, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_map. * Note that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_map. * @param __x An %unordered_map of the same element and allocator * types. * * This exchanges the elements between two %unordered_map in constant * time. * Note that the global std::swap() function is specialized such that * std::swap(m1,m2) will feed to this function. */ void swap(unordered_map& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_unique(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_map was /// constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_map was /// constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_map. * @param __x Key to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Key to count. * @return Number of elements with specified key. * * This function only makes sense for %unordered_multimap; for * %unordered_map the result will either be 0 (not present) or 1 * (present). */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. * * This function probably only makes sense for %unordered_multimap. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} //@{ /** * @brief Subscript ( @c [] ) access to %unordered_map data. * @param __k The key for which data should be retrieved. * @return A reference to the data of the (key,data) %pair. * * Allows for easy lookup with the subscript ( @c [] )operator. Returns * data associated with the key specified in subscript. If the key does * not exist, a pair with that key is created using default values, which * is then returned. * * Lookup requires constant time. */ mapped_type& operator[](const key_type& __k) { return _M_h[__k]; } mapped_type& operator[](key_type&& __k) { return _M_h[std::move(__k)]; } //@} //@{ /** * @brief Access to %unordered_map data. * @param __k The key for which data should be retrieved. * @return A reference to the data whose key is equal to @a __k, if * such a data is present in the %unordered_map. * @throw std::out_of_range If no such data is present. */ mapped_type& at(const key_type& __k) { return _M_h.at(__k); } const mapped_type& at(const key_type& __k) const { return _M_h.at(__k); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_map. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_map. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } /** * @brief Returns a read/write iterator pointing to the first bucket * element. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} /** * @brief Returns a read/write iterator pointing to one past the last * bucket elements. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_map tries to keep the /// load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_map maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_map. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_map maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_map for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_map<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&, const unordered_map<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_map(initializer_list>, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif /** * @brief A standard container composed of equivalent keys * (possibly containing multiple of each key value) that associates * values of another type with the keys. * * @ingroup unordered_associative_containers * * @tparam _Key Type of key objects. * @tparam _Tp Type of mapped objects. * @tparam _Hash Hashing function object type, defaults to hash<_Value>. * @tparam _Pred Predicate function object type, defaults * to equal_to<_Value>. * @tparam _Alloc Allocator type, defaults to * std::allocator>. * * Meets the requirements of a container, and * unordered associative container * * The resulting value type of the container is std::pair. * * Base is _Hashtable, dispatched at compile time via template * alias __ummap_hashtable. */ template, typename _Pred = equal_to<_Key>, typename _Alloc = allocator>> class unordered_multimap { typedef __ummap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; public: // typedefs: //@{ /// Public typedefs. typedef typename _Hashtable::key_type key_type; typedef typename _Hashtable::value_type value_type; typedef typename _Hashtable::mapped_type mapped_type; typedef typename _Hashtable::hasher hasher; typedef typename _Hashtable::key_equal key_equal; typedef typename _Hashtable::allocator_type allocator_type; //@} //@{ /// Iterator-related typedefs. typedef typename _Hashtable::pointer pointer; typedef typename _Hashtable::const_pointer const_pointer; typedef typename _Hashtable::reference reference; typedef typename _Hashtable::const_reference const_reference; typedef typename _Hashtable::iterator iterator; typedef typename _Hashtable::const_iterator const_iterator; typedef typename _Hashtable::local_iterator local_iterator; typedef typename _Hashtable::const_local_iterator const_local_iterator; typedef typename _Hashtable::size_type size_type; typedef typename _Hashtable::difference_type difference_type; //@} #if __cplusplus > 201402L using node_type = typename _Hashtable::node_type; #endif //construct/destroy/copy /// Default constructor. unordered_multimap() = default; /** * @brief Default constructor creates no elements. * @param __n Mnimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. */ explicit unordered_multimap(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__n, __hf, __eql, __a) { } /** * @brief Builds an %unordered_multimap from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multimap consisting of copies of the elements * from [__first,__last). This is linear in N (where N is * distance(__first,__last)). */ template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__first, __last, __n, __hf, __eql, __a) { } /// Copy constructor. unordered_multimap(const unordered_multimap&) = default; /// Move constructor. unordered_multimap(unordered_multimap&&) = default; /** * @brief Creates an %unordered_multimap with no elements. * @param __a An allocator object. */ explicit unordered_multimap(const allocator_type& __a) : _M_h(__a) { } /* * @brief Copy constructor with allocator argument. * @param __uset Input %unordered_multimap to copy. * @param __a An allocator object. */ unordered_multimap(const unordered_multimap& __ummap, const allocator_type& __a) : _M_h(__ummap._M_h, __a) { } /* * @brief Move constructor with allocator argument. * @param __uset Input %unordered_multimap to move. * @param __a An allocator object. */ unordered_multimap(unordered_multimap&& __ummap, const allocator_type& __a) : _M_h(std::move(__ummap._M_h), __a) { } /** * @brief Builds an %unordered_multimap from an initializer_list. * @param __l An initializer_list. * @param __n Minimal initial number of buckets. * @param __hf A hash functor. * @param __eql A key equality functor. * @param __a An allocator object. * * Create an %unordered_multimap consisting of copies of the elements in * the list. This is linear in N (where N is @a __l.size()). */ unordered_multimap(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _M_h(__l, __n, __hf, __eql, __a) { } unordered_multimap(size_type __n, const allocator_type& __a) : unordered_multimap(__n, hasher(), key_equal(), __a) { } unordered_multimap(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__n, __hf, key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multimap(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multimap(__l, __n, hasher(), key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__l, __n, __hf, key_equal(), __a) { } /// Copy assignment operator. unordered_multimap& operator=(const unordered_multimap&) = default; /// Move assignment operator. unordered_multimap& operator=(unordered_multimap&&) = default; /** * @brief %Unordered_multimap list assignment operator. * @param __l An initializer_list. * * This function fills an %unordered_multimap with copies of the * elements in the initializer list @a __l. * * Note that the assignment completely changes the %unordered_multimap * and that the resulting %unordered_multimap's size is the same as the * number of elements assigned. */ unordered_multimap& operator=(initializer_list __l) { _M_h = __l; return *this; } /// Returns the allocator object used by the %unordered_multimap. allocator_type get_allocator() const noexcept { return _M_h.get_allocator(); } // size and capacity: /// Returns true if the %unordered_multimap is empty. bool empty() const noexcept { return _M_h.empty(); } /// Returns the size of the %unordered_multimap. size_type size() const noexcept { return _M_h.size(); } /// Returns the maximum size of the %unordered_multimap. size_type max_size() const noexcept { return _M_h.max_size(); } // iterators. /** * Returns a read/write iterator that points to the first element in the * %unordered_multimap. */ iterator begin() noexcept { return _M_h.begin(); } //@{ /** * Returns a read-only (constant) iterator that points to the first * element in the %unordered_multimap. */ const_iterator begin() const noexcept { return _M_h.begin(); } const_iterator cbegin() const noexcept { return _M_h.begin(); } //@} /** * Returns a read/write iterator that points one past the last element in * the %unordered_multimap. */ iterator end() noexcept { return _M_h.end(); } //@{ /** * Returns a read-only (constant) iterator that points one past the last * element in the %unordered_multimap. */ const_iterator end() const noexcept { return _M_h.end(); } const_iterator cend() const noexcept { return _M_h.end(); } //@} // modifiers. /** * @brief Attempts to build and insert a std::pair into the * %unordered_multimap. * * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * * @return An iterator that points to the inserted pair. * * This function attempts to build and insert a (key, value) %pair into * the %unordered_multimap. * * Insertion requires amortized constant time. */ template iterator emplace(_Args&&... __args) { return _M_h.emplace(std::forward<_Args>(__args)...); } /** * @brief Attempts to build and insert a std::pair into the * %unordered_multimap. * * @param __pos An iterator that serves as a hint as to where the pair * should be inserted. * @param __args Arguments used to generate a new pair instance (see * std::piecewise_contruct for passing arguments to each * part of the pair constructor). * @return An iterator that points to the element with key of the * std::pair built from @a __args. * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { return _M_h.emplace_hint(__pos, std::forward<_Args>(__args)...); } //@{ /** * @brief Inserts a std::pair into the %unordered_multimap. * @param __x Pair to be inserted (see std::make_pair for easy * creation of pairs). * * @return An iterator that points to the inserted pair. * * Insertion requires amortized constant time. */ iterator insert(const value_type& __x) { return _M_h.insert(__x); } iterator insert(value_type&& __x) { return _M_h.insert(std::move(__x)); } template __enable_if_t::value, iterator> insert(_Pair&& __x) { return _M_h.emplace(std::forward<_Pair>(__x)); } //@} //@{ /** * @brief Inserts a std::pair into the %unordered_multimap. * @param __hint An iterator that serves as a hint as to where the * pair should be inserted. * @param __x Pair to be inserted (see std::make_pair for easy creation * of pairs). * @return An iterator that points to the element with key of * @a __x (may or may not be the %pair passed in). * * Note that the first parameter is only a hint and can potentially * improve the performance of the insertion process. A bad hint would * cause no gains in efficiency. * * See * https://gcc.gnu.org/onlinedocs/libstdc++/manual/associative.html#containers.associative.insert_hints * for more on @a hinting. * * Insertion requires amortized constant time. */ iterator insert(const_iterator __hint, const value_type& __x) { return _M_h.insert(__hint, __x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { return _M_h.insert(__hint, std::move(__x)); } template __enable_if_t::value, iterator> insert(const_iterator __hint, _Pair&& __x) { return _M_h.emplace_hint(__hint, std::forward<_Pair>(__x)); } //@} /** * @brief A template function that attempts to insert a range of * elements. * @param __first Iterator pointing to the start of the range to be * inserted. * @param __last Iterator pointing to the end of the range. * * Complexity similar to that of the range constructor. */ template void insert(_InputIterator __first, _InputIterator __last) { _M_h.insert(__first, __last); } /** * @brief Attempts to insert a list of elements into the * %unordered_multimap. * @param __l A std::initializer_list of elements * to be inserted. * * Complexity similar to that of the range constructor. */ void insert(initializer_list __l) { _M_h.insert(__l); } #if __cplusplus > 201402L /// Extract a node. node_type extract(const_iterator __pos) { __glibcxx_assert(__pos != end()); return _M_h.extract(__pos); } /// Extract a node. node_type extract(const key_type& __key) { return _M_h.extract(__key); } /// Re-insert an extracted node. iterator insert(node_type&& __nh) { return _M_h._M_reinsert_node_multi(cend(), std::move(__nh)); } /// Re-insert an extracted node. iterator insert(const_iterator __hint, node_type&& __nh) { return _M_h._M_reinsert_node_multi(__hint, std::move(__nh)); } #endif // C++17 //@{ /** * @brief Erases an element from an %unordered_multimap. * @param __position An iterator pointing to the element to be erased. * @return An iterator pointing to the element immediately following * @a __position prior to the element being erased. If no such * element exists, end() is returned. * * This function erases an element, pointed to by the given iterator, * from an %unordered_multimap. * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __position) { return _M_h.erase(__position); } // LWG 2059. iterator erase(iterator __position) { return _M_h.erase(__position); } //@} /** * @brief Erases elements according to the provided key. * @param __x Key of elements to be erased. * @return The number of elements erased. * * This function erases all the elements located by the given key from * an %unordered_multimap. * Note that this function only erases the element, and that if the * element is itself a pointer, the pointed-to memory is not touched in * any way. Managing the pointer is the user's responsibility. */ size_type erase(const key_type& __x) { return _M_h.erase(__x); } /** * @brief Erases a [__first,__last) range of elements from an * %unordered_multimap. * @param __first Iterator pointing to the start of the range to be * erased. * @param __last Iterator pointing to the end of the range to * be erased. * @return The iterator @a __last. * * This function erases a sequence of elements from an * %unordered_multimap. * Note that this function only erases the elements, and that if * the element is itself a pointer, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ iterator erase(const_iterator __first, const_iterator __last) { return _M_h.erase(__first, __last); } /** * Erases all elements in an %unordered_multimap. * Note that this function only erases the elements, and that if the * elements themselves are pointers, the pointed-to memory is not touched * in any way. Managing the pointer is the user's responsibility. */ void clear() noexcept { _M_h.clear(); } /** * @brief Swaps data with another %unordered_multimap. * @param __x An %unordered_multimap of the same element and allocator * types. * * This exchanges the elements between two %unordered_multimap in * constant time. * Note that the global std::swap() function is specialized such that * std::swap(m1,m2) will feed to this function. */ void swap(unordered_multimap& __x) noexcept( noexcept(_M_h.swap(__x._M_h)) ) { _M_h.swap(__x._M_h); } #if __cplusplus > 201402L template friend class std::_Hash_merge_helper; template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_multimap<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>& __source) { using _Merge_helper = _Hash_merge_helper; _M_h._M_merge_multi(_Merge_helper::_S_get_table(__source)); } template void merge(unordered_map<_Key, _Tp, _H2, _P2, _Alloc>&& __source) { merge(__source); } #endif // C++17 // observers. /// Returns the hash functor object with which the %unordered_multimap /// was constructed. hasher hash_function() const { return _M_h.hash_function(); } /// Returns the key comparison object with which the %unordered_multimap /// was constructed. key_equal key_eq() const { return _M_h.key_eq(); } // lookup. //@{ /** * @brief Tries to locate an element in an %unordered_multimap. * @param __x Key to be located. * @return Iterator pointing to sought-after element, or end() if not * found. * * This function takes a key and tries to locate the element with which * the key matches. If successful the function returns an iterator * pointing to the sought after element. If unsuccessful it returns the * past-the-end ( @c end() ) iterator. */ iterator find(const key_type& __x) { return _M_h.find(__x); } const_iterator find(const key_type& __x) const { return _M_h.find(__x); } //@} /** * @brief Finds the number of elements. * @param __x Key to count. * @return Number of elements with specified key. */ size_type count(const key_type& __x) const { return _M_h.count(__x); } //@{ /** * @brief Finds a subsequence matching given key. * @param __x Key to be located. * @return Pair of iterators that possibly points to the subsequence * matching given key. */ std::pair equal_range(const key_type& __x) { return _M_h.equal_range(__x); } std::pair equal_range(const key_type& __x) const { return _M_h.equal_range(__x); } //@} // bucket interface. /// Returns the number of buckets of the %unordered_multimap. size_type bucket_count() const noexcept { return _M_h.bucket_count(); } /// Returns the maximum number of buckets of the %unordered_multimap. size_type max_bucket_count() const noexcept { return _M_h.max_bucket_count(); } /* * @brief Returns the number of elements in a given bucket. * @param __n A bucket index. * @return The number of elements in the bucket. */ size_type bucket_size(size_type __n) const { return _M_h.bucket_size(__n); } /* * @brief Returns the bucket index of a given element. * @param __key A key instance. * @return The key bucket index. */ size_type bucket(const key_type& __key) const { return _M_h.bucket(__key); } /** * @brief Returns a read/write iterator pointing to the first bucket * element. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator begin(size_type __n) { return _M_h.begin(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to the first * bucket element. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator begin(size_type __n) const { return _M_h.begin(__n); } const_local_iterator cbegin(size_type __n) const { return _M_h.cbegin(__n); } //@} /** * @brief Returns a read/write iterator pointing to one past the last * bucket elements. * @param __n The bucket index. * @return A read/write local iterator. */ local_iterator end(size_type __n) { return _M_h.end(__n); } //@{ /** * @brief Returns a read-only (constant) iterator pointing to one past * the last bucket elements. * @param __n The bucket index. * @return A read-only local iterator. */ const_local_iterator end(size_type __n) const { return _M_h.end(__n); } const_local_iterator cend(size_type __n) const { return _M_h.cend(__n); } //@} // hash policy. /// Returns the average number of elements per bucket. float load_factor() const noexcept { return _M_h.load_factor(); } /// Returns a positive number that the %unordered_multimap tries to keep /// the load factor less than or equal to. float max_load_factor() const noexcept { return _M_h.max_load_factor(); } /** * @brief Change the %unordered_multimap maximum load factor. * @param __z The new maximum load factor. */ void max_load_factor(float __z) { _M_h.max_load_factor(__z); } /** * @brief May rehash the %unordered_multimap. * @param __n The new number of buckets. * * Rehash will occur only if the new number of buckets respect the * %unordered_multimap maximum load factor. */ void rehash(size_type __n) { _M_h.rehash(__n); } /** * @brief Prepare the %unordered_multimap for a specified number of * elements. * @param __n Number of elements required. * * Same as rehash(ceil(n / max_load_factor())). */ void reserve(size_type __n) { _M_h.reserve(__n); } template friend bool operator==(const unordered_multimap<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&, const unordered_multimap<_Key1, _Tp1, _Hash1, _Pred1, _Alloc1>&); }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(initializer_list>, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif template inline void swap(unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline void swap(unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } template inline bool operator==(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_h._M_equal(__y._M_h); } template inline bool operator!=(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } _GLIBCXX_END_NAMESPACE_CONTAINER #if __cplusplus > 201402L // Allow std::unordered_map access to internals of compatible maps. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_map<_Key, _Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_map = _GLIBCXX_STD_C::unordered_map<_Tp...>; template using unordered_multimap = _GLIBCXX_STD_C::unordered_multimap<_Tp...>; friend unordered_map<_Key, _Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_map<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } static auto& _S_get_table(unordered_multimap<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } }; // Allow std::unordered_multimap access to internals of compatible maps. template struct _Hash_merge_helper< _GLIBCXX_STD_C::unordered_multimap<_Key, _Val, _Hash1, _Eq1, _Alloc>, _Hash2, _Eq2> { private: template using unordered_map = _GLIBCXX_STD_C::unordered_map<_Tp...>; template using unordered_multimap = _GLIBCXX_STD_C::unordered_multimap<_Tp...>; friend unordered_multimap<_Key, _Val, _Hash1, _Eq1, _Alloc>; static auto& _S_get_table(unordered_map<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } static auto& _S_get_table(unordered_multimap<_Key, _Val, _Hash2, _Eq2, _Alloc>& __map) { return __map._M_h; } }; #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif /* _UNORDERED_MAP_H */ c++/8/bits/basic_ios.h000064400000037312151027430570010342 0ustar00// Iostreams base classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/basic_ios.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ #ifndef _BASIC_IOS_H #define _BASIC_IOS_H 1 #pragma GCC system_header #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template inline const _Facet& __check_facet(const _Facet* __f) { if (!__f) __throw_bad_cast(); return *__f; } /** * @brief Template class basic_ios, virtual base class for all * stream classes. * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * Most of the member functions called dispatched on stream objects * (e.g., @c std::cout.foo(bar);) are consolidated in this class. */ template class basic_ios : public ios_base { public: //@{ /** * These are standard types. They permit a standardized way of * referring to names of (or names dependent on) the template * parameters, which are specific to the implementation. */ typedef _CharT char_type; typedef typename _Traits::int_type int_type; typedef typename _Traits::pos_type pos_type; typedef typename _Traits::off_type off_type; typedef _Traits traits_type; //@} //@{ /** * These are non-standard types. */ typedef ctype<_CharT> __ctype_type; typedef num_put<_CharT, ostreambuf_iterator<_CharT, _Traits> > __num_put_type; typedef num_get<_CharT, istreambuf_iterator<_CharT, _Traits> > __num_get_type; //@} // Data members: protected: basic_ostream<_CharT, _Traits>* _M_tie; mutable char_type _M_fill; mutable bool _M_fill_init; basic_streambuf<_CharT, _Traits>* _M_streambuf; // Cached use_facet, which is based on the current locale info. const __ctype_type* _M_ctype; // For ostream. const __num_put_type* _M_num_put; // For istream. const __num_get_type* _M_num_get; public: //@{ /** * @brief The quick-and-easy status check. * * This allows you to write constructs such as * if (!a_stream) ... and while (a_stream) ... */ #if __cplusplus >= 201103L explicit operator bool() const { return !this->fail(); } #else operator void*() const { return this->fail() ? 0 : const_cast(this); } #endif bool operator!() const { return this->fail(); } //@} /** * @brief Returns the error state of the stream buffer. * @return A bit pattern (well, isn't everything?) * * See std::ios_base::iostate for the possible bit values. Most * users will call one of the interpreting wrappers, e.g., good(). */ iostate rdstate() const { return _M_streambuf_state; } /** * @brief [Re]sets the error state. * @param __state The new state flag(s) to set. * * See std::ios_base::iostate for the possible bit values. Most * users will not need to pass an argument. */ void clear(iostate __state = goodbit); /** * @brief Sets additional flags in the error state. * @param __state The additional state flag(s) to set. * * See std::ios_base::iostate for the possible bit values. */ void setstate(iostate __state) { this->clear(this->rdstate() | __state); } // Flip the internal state on for the proper state bits, then // rethrows the propagated exception if bit also set in // exceptions(). void _M_setstate(iostate __state) { // 27.6.1.2.1 Common requirements. // Turn this on without causing an ios::failure to be thrown. _M_streambuf_state |= __state; if (this->exceptions() & __state) __throw_exception_again; } /** * @brief Fast error checking. * @return True if no error flags are set. * * A wrapper around rdstate. */ bool good() const { return this->rdstate() == 0; } /** * @brief Fast error checking. * @return True if the eofbit is set. * * Note that other iostate flags may also be set. */ bool eof() const { return (this->rdstate() & eofbit) != 0; } /** * @brief Fast error checking. * @return True if either the badbit or the failbit is set. * * Checking the badbit in fail() is historical practice. * Note that other iostate flags may also be set. */ bool fail() const { return (this->rdstate() & (badbit | failbit)) != 0; } /** * @brief Fast error checking. * @return True if the badbit is set. * * Note that other iostate flags may also be set. */ bool bad() const { return (this->rdstate() & badbit) != 0; } /** * @brief Throwing exceptions on errors. * @return The current exceptions mask. * * This changes nothing in the stream. See the one-argument version * of exceptions(iostate) for the meaning of the return value. */ iostate exceptions() const { return _M_exception; } /** * @brief Throwing exceptions on errors. * @param __except The new exceptions mask. * * By default, error flags are set silently. You can set an * exceptions mask for each stream; if a bit in the mask becomes set * in the error flags, then an exception of type * std::ios_base::failure is thrown. * * If the error flag is already set when the exceptions mask is * added, the exception is immediately thrown. Try running the * following under GCC 3.1 or later: * @code * #include * #include * #include * * int main() * { * std::set_terminate (__gnu_cxx::__verbose_terminate_handler); * * std::ifstream f ("/etc/motd"); * * std::cerr << "Setting badbit\n"; * f.setstate (std::ios_base::badbit); * * std::cerr << "Setting exception mask\n"; * f.exceptions (std::ios_base::badbit); * } * @endcode */ void exceptions(iostate __except) { _M_exception = __except; this->clear(_M_streambuf_state); } // Constructor/destructor: /** * @brief Constructor performs initialization. * * The parameter is passed by derived streams. */ explicit basic_ios(basic_streambuf<_CharT, _Traits>* __sb) : ios_base(), _M_tie(0), _M_fill(), _M_fill_init(false), _M_streambuf(0), _M_ctype(0), _M_num_put(0), _M_num_get(0) { this->init(__sb); } /** * @brief Empty. * * The destructor does nothing. More specifically, it does not * destroy the streambuf held by rdbuf(). */ virtual ~basic_ios() { } // Members: /** * @brief Fetches the current @e tied stream. * @return A pointer to the tied stream, or NULL if the stream is * not tied. * * A stream may be @e tied (or synchronized) to a second output * stream. When this stream performs any I/O, the tied stream is * first flushed. For example, @c std::cin is tied to @c std::cout. */ basic_ostream<_CharT, _Traits>* tie() const { return _M_tie; } /** * @brief Ties this stream to an output stream. * @param __tiestr The output stream. * @return The previously tied output stream, or NULL if the stream * was not tied. * * This sets up a new tie; see tie() for more. */ basic_ostream<_CharT, _Traits>* tie(basic_ostream<_CharT, _Traits>* __tiestr) { basic_ostream<_CharT, _Traits>* __old = _M_tie; _M_tie = __tiestr; return __old; } /** * @brief Accessing the underlying buffer. * @return The current stream buffer. * * This does not change the state of the stream. */ basic_streambuf<_CharT, _Traits>* rdbuf() const { return _M_streambuf; } /** * @brief Changing the underlying buffer. * @param __sb The new stream buffer. * @return The previous stream buffer. * * Associates a new buffer with the current stream, and clears the * error state. * * Due to historical accidents which the LWG refuses to correct, the * I/O library suffers from a design error: this function is hidden * in derived classes by overrides of the zero-argument @c rdbuf(), * which is non-virtual for hysterical raisins. As a result, you * must use explicit qualifications to access this function via any * derived class. For example: * * @code * std::fstream foo; // or some other derived type * std::streambuf* p = .....; * * foo.ios::rdbuf(p); // ios == basic_ios * @endcode */ basic_streambuf<_CharT, _Traits>* rdbuf(basic_streambuf<_CharT, _Traits>* __sb); /** * @brief Copies fields of __rhs into this. * @param __rhs The source values for the copies. * @return Reference to this object. * * All fields of __rhs are copied into this object except that rdbuf() * and rdstate() remain unchanged. All values in the pword and iword * arrays are copied. Before copying, each callback is invoked with * erase_event. After copying, each (new) callback is invoked with * copyfmt_event. The final step is to copy exceptions(). */ basic_ios& copyfmt(const basic_ios& __rhs); /** * @brief Retrieves the @a empty character. * @return The current fill character. * * It defaults to a space (' ') in the current locale. */ char_type fill() const { if (!_M_fill_init) { _M_fill = this->widen(' '); _M_fill_init = true; } return _M_fill; } /** * @brief Sets a new @a empty character. * @param __ch The new character. * @return The previous fill character. * * The fill character is used to fill out space when P+ characters * have been requested (e.g., via setw), Q characters are actually * used, and Qfill(); _M_fill = __ch; return __old; } // Locales: /** * @brief Moves to a new locale. * @param __loc The new locale. * @return The previous locale. * * Calls @c ios_base::imbue(loc), and if a stream buffer is associated * with this stream, calls that buffer's @c pubimbue(loc). * * Additional l10n notes are at * http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html */ locale imbue(const locale& __loc); /** * @brief Squeezes characters. * @param __c The character to narrow. * @param __dfault The character to narrow. * @return The narrowed character. * * Maps a character of @c char_type to a character of @c char, * if possible. * * Returns the result of * @code * std::use_facet >(getloc()).narrow(c,dfault) * @endcode * * Additional l10n notes are at * http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html */ char narrow(char_type __c, char __dfault) const { return __check_facet(_M_ctype).narrow(__c, __dfault); } /** * @brief Widens characters. * @param __c The character to widen. * @return The widened character. * * Maps a character of @c char to a character of @c char_type. * * Returns the result of * @code * std::use_facet >(getloc()).widen(c) * @endcode * * Additional l10n notes are at * http://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html */ char_type widen(char __c) const { return __check_facet(_M_ctype).widen(__c); } protected: // 27.4.5.1 basic_ios constructors /** * @brief Empty. * * The default constructor does nothing and is not normally * accessible to users. */ basic_ios() : ios_base(), _M_tie(0), _M_fill(char_type()), _M_fill_init(false), _M_streambuf(0), _M_ctype(0), _M_num_put(0), _M_num_get(0) { } /** * @brief All setup is performed here. * * This is called from the public constructor. It is not virtual and * cannot be redefined. */ void init(basic_streambuf<_CharT, _Traits>* __sb); #if __cplusplus >= 201103L basic_ios(const basic_ios&) = delete; basic_ios& operator=(const basic_ios&) = delete; void move(basic_ios& __rhs) { ios_base::_M_move(__rhs); _M_cache_locale(_M_ios_locale); this->tie(__rhs.tie(nullptr)); _M_fill = __rhs._M_fill; _M_fill_init = __rhs._M_fill_init; _M_streambuf = nullptr; } void move(basic_ios&& __rhs) { this->move(__rhs); } void swap(basic_ios& __rhs) noexcept { ios_base::_M_swap(__rhs); _M_cache_locale(_M_ios_locale); __rhs._M_cache_locale(__rhs._M_ios_locale); std::swap(_M_tie, __rhs._M_tie); std::swap(_M_fill, __rhs._M_fill); std::swap(_M_fill_init, __rhs._M_fill_init); } void set_rdbuf(basic_streambuf<_CharT, _Traits>* __sb) { _M_streambuf = __sb; } #endif void _M_cache_locale(const locale& __loc); }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include #endif /* _BASIC_IOS_H */ c++/8/bits/locale_classes.h000064400000060501151027430570011357 0ustar00// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/locale_classes.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // #ifndef _LOCALE_CLASSES_H #define _LOCALE_CLASSES_H 1 #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 22.1.1 Class locale /** * @brief Container class for localization functionality. * @ingroup locales * * The locale class is first a class wrapper for C library locales. It is * also an extensible container for user-defined localization. A locale is * a collection of facets that implement various localization features such * as money, time, and number printing. * * Constructing C++ locales does not change the C library locale. * * This library supports efficient construction and copying of locales * through a reference counting implementation of the locale class. */ class locale { public: // Types: /// Definition of locale::category. typedef int category; // Forward decls and friends: class facet; class id; class _Impl; friend class facet; friend class _Impl; template friend bool has_facet(const locale&) throw(); template friend const _Facet& use_facet(const locale&); template friend struct __use_cache; //@{ /** * @brief Category values. * * The standard category values are none, ctype, numeric, collate, time, * monetary, and messages. They form a bitmask that supports union and * intersection. The category all is the union of these values. * * NB: Order must match _S_facet_categories definition in locale.cc */ static const category none = 0; static const category ctype = 1L << 0; static const category numeric = 1L << 1; static const category collate = 1L << 2; static const category time = 1L << 3; static const category monetary = 1L << 4; static const category messages = 1L << 5; static const category all = (ctype | numeric | collate | time | monetary | messages); //@} // Construct/copy/destroy: /** * @brief Default constructor. * * Constructs a copy of the global locale. If no locale has been * explicitly set, this is the C locale. */ locale() throw(); /** * @brief Copy constructor. * * Constructs a copy of @a other. * * @param __other The locale to copy. */ locale(const locale& __other) throw(); /** * @brief Named locale constructor. * * Constructs a copy of the named C library locale. * * @param __s Name of the locale to construct. * @throw std::runtime_error if __s is null or an undefined locale. */ explicit locale(const char* __s); /** * @brief Construct locale with facets from another locale. * * Constructs a copy of the locale @a base. The facets specified by @a * cat are replaced with those from the locale named by @a s. If base is * named, this locale instance will also be named. * * @param __base The locale to copy. * @param __s Name of the locale to use facets from. * @param __cat Set of categories defining the facets to use from __s. * @throw std::runtime_error if __s is null or an undefined locale. */ locale(const locale& __base, const char* __s, category __cat); #if __cplusplus >= 201103L /** * @brief Named locale constructor. * * Constructs a copy of the named C library locale. * * @param __s Name of the locale to construct. * @throw std::runtime_error if __s is an undefined locale. */ explicit locale(const std::string& __s) : locale(__s.c_str()) { } /** * @brief Construct locale with facets from another locale. * * Constructs a copy of the locale @a base. The facets specified by @a * cat are replaced with those from the locale named by @a s. If base is * named, this locale instance will also be named. * * @param __base The locale to copy. * @param __s Name of the locale to use facets from. * @param __cat Set of categories defining the facets to use from __s. * @throw std::runtime_error if __s is an undefined locale. */ locale(const locale& __base, const std::string& __s, category __cat) : locale(__base, __s.c_str(), __cat) { } #endif /** * @brief Construct locale with facets from another locale. * * Constructs a copy of the locale @a base. The facets specified by @a * cat are replaced with those from the locale @a add. If @a base and @a * add are named, this locale instance will also be named. * * @param __base The locale to copy. * @param __add The locale to use facets from. * @param __cat Set of categories defining the facets to use from add. */ locale(const locale& __base, const locale& __add, category __cat); /** * @brief Construct locale with another facet. * * Constructs a copy of the locale @a __other. The facet @a __f * is added to @a __other, replacing an existing facet of type * Facet if there is one. If @a __f is null, this locale is a * copy of @a __other. * * @param __other The locale to copy. * @param __f The facet to add in. */ template locale(const locale& __other, _Facet* __f); /// Locale destructor. ~locale() throw(); /** * @brief Assignment operator. * * Set this locale to be a copy of @a other. * * @param __other The locale to copy. * @return A reference to this locale. */ const locale& operator=(const locale& __other) throw(); /** * @brief Construct locale with another facet. * * Constructs and returns a new copy of this locale. Adds or replaces an * existing facet of type Facet from the locale @a other into the new * locale. * * @tparam _Facet The facet type to copy from other * @param __other The locale to copy from. * @return Newly constructed locale. * @throw std::runtime_error if __other has no facet of type _Facet. */ template locale combine(const locale& __other) const; // Locale operations: /** * @brief Return locale name. * @return Locale name or "*" if unnamed. */ _GLIBCXX_DEFAULT_ABI_TAG string name() const; /** * @brief Locale equality. * * @param __other The locale to compare against. * @return True if other and this refer to the same locale instance, are * copies, or have the same name. False otherwise. */ bool operator==(const locale& __other) const throw(); /** * @brief Locale inequality. * * @param __other The locale to compare against. * @return ! (*this == __other) */ bool operator!=(const locale& __other) const throw() { return !(this->operator==(__other)); } /** * @brief Compare two strings according to collate. * * Template operator to compare two strings using the compare function of * the collate facet in this locale. One use is to provide the locale to * the sort function. For example, a vector v of strings could be sorted * according to locale loc by doing: * @code * std::sort(v.begin(), v.end(), loc); * @endcode * * @param __s1 First string to compare. * @param __s2 Second string to compare. * @return True if collate<_Char> facet compares __s1 < __s2, else false. */ template bool operator()(const basic_string<_Char, _Traits, _Alloc>& __s1, const basic_string<_Char, _Traits, _Alloc>& __s2) const; // Global locale objects: /** * @brief Set global locale * * This function sets the global locale to the argument and returns a * copy of the previous global locale. If the argument has a name, it * will also call std::setlocale(LC_ALL, loc.name()). * * @param __loc The new locale to make global. * @return Copy of the old global locale. */ static locale global(const locale& __loc); /** * @brief Return reference to the C locale. */ static const locale& classic(); private: // The (shared) implementation _Impl* _M_impl; // The "C" reference locale static _Impl* _S_classic; // Current global locale static _Impl* _S_global; // Names of underlying locale categories. // NB: locale::global() has to know how to modify all the // underlying categories, not just the ones required by the C++ // standard. static const char* const* const _S_categories; // Number of standard categories. For C++, these categories are // collate, ctype, monetary, numeric, time, and messages. These // directly correspond to ISO C99 macros LC_COLLATE, LC_CTYPE, // LC_MONETARY, LC_NUMERIC, and LC_TIME. In addition, POSIX (IEEE // 1003.1-2001) specifies LC_MESSAGES. // In addition to the standard categories, the underlying // operating system is allowed to define extra LC_* // macros. For GNU systems, the following are also valid: // LC_PAPER, LC_NAME, LC_ADDRESS, LC_TELEPHONE, LC_MEASUREMENT, // and LC_IDENTIFICATION. enum { _S_categories_size = 6 + _GLIBCXX_NUM_CATEGORIES }; #ifdef __GTHREADS static __gthread_once_t _S_once; #endif explicit locale(_Impl*) throw(); static void _S_initialize(); static void _S_initialize_once() throw(); static category _S_normalize_category(category); void _M_coalesce(const locale& __base, const locale& __add, category __cat); #if _GLIBCXX_USE_CXX11_ABI static const id* const _S_twinned_facets[]; #endif }; // 22.1.1.1.2 Class locale::facet /** * @brief Localization functionality base class. * @ingroup locales * * The facet class is the base class for a localization feature, such as * money, time, and number printing. It provides common support for facets * and reference management. * * Facets may not be copied or assigned. */ class locale::facet { private: friend class locale; friend class locale::_Impl; mutable _Atomic_word _M_refcount; // Contains data from the underlying "C" library for the classic locale. static __c_locale _S_c_locale; // String literal for the name of the classic locale. static const char _S_c_name[2]; #ifdef __GTHREADS static __gthread_once_t _S_once; #endif static void _S_initialize_once(); protected: /** * @brief Facet constructor. * * This is the constructor provided by the standard. If refs is 0, the * facet is destroyed when the last referencing locale is destroyed. * Otherwise the facet will never be destroyed. * * @param __refs The initial value for reference count. */ explicit facet(size_t __refs = 0) throw() : _M_refcount(__refs ? 1 : 0) { } /// Facet destructor. virtual ~facet(); static void _S_create_c_locale(__c_locale& __cloc, const char* __s, __c_locale __old = 0); static __c_locale _S_clone_c_locale(__c_locale& __cloc) throw(); static void _S_destroy_c_locale(__c_locale& __cloc); static __c_locale _S_lc_ctype_c_locale(__c_locale __cloc, const char* __s); // Returns data from the underlying "C" library data for the // classic locale. static __c_locale _S_get_c_locale(); _GLIBCXX_CONST static const char* _S_get_c_name() throw(); #if __cplusplus < 201103L private: facet(const facet&); // Not defined. facet& operator=(const facet&); // Not defined. #else facet(const facet&) = delete; facet& operator=(const facet&) = delete; #endif private: void _M_add_reference() const throw() { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); } void _M_remove_reference() const throw() { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_refcount); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_refcount); __try { delete this; } __catch(...) { } } } const facet* _M_sso_shim(const id*) const; const facet* _M_cow_shim(const id*) const; protected: class __shim; // For internal use only. }; // 22.1.1.1.3 Class locale::id /** * @brief Facet ID class. * @ingroup locales * * The ID class provides facets with an index used to identify them. * Every facet class must define a public static member locale::id, or be * derived from a facet that provides this member, otherwise the facet * cannot be used in a locale. The locale::id ensures that each class * type gets a unique identifier. */ class locale::id { private: friend class locale; friend class locale::_Impl; template friend const _Facet& use_facet(const locale&); template friend bool has_facet(const locale&) throw(); // NB: There is no accessor for _M_index because it may be used // before the constructor is run; the effect of calling a member // function (even an inline) would be undefined. mutable size_t _M_index; // Last id number assigned. static _Atomic_word _S_refcount; void operator=(const id&); // Not defined. id(const id&); // Not defined. public: // NB: This class is always a static data member, and thus can be // counted on to be zero-initialized. /// Constructor. id() { } size_t _M_id() const throw(); }; // Implementation object for locale. class locale::_Impl { public: // Friends. friend class locale; friend class locale::facet; template friend bool has_facet(const locale&) throw(); template friend const _Facet& use_facet(const locale&); template friend struct __use_cache; private: // Data Members. _Atomic_word _M_refcount; const facet** _M_facets; size_t _M_facets_size; const facet** _M_caches; char** _M_names; static const locale::id* const _S_id_ctype[]; static const locale::id* const _S_id_numeric[]; static const locale::id* const _S_id_collate[]; static const locale::id* const _S_id_time[]; static const locale::id* const _S_id_monetary[]; static const locale::id* const _S_id_messages[]; static const locale::id* const* const _S_facet_categories[]; void _M_add_reference() throw() { __gnu_cxx::__atomic_add_dispatch(&_M_refcount, 1); } void _M_remove_reference() throw() { // Be race-detector-friendly. For more info see bits/c++config. _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&_M_refcount); if (__gnu_cxx::__exchange_and_add_dispatch(&_M_refcount, -1) == 1) { _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&_M_refcount); __try { delete this; } __catch(...) { } } } _Impl(const _Impl&, size_t); _Impl(const char*, size_t); _Impl(size_t) throw(); ~_Impl() throw(); _Impl(const _Impl&); // Not defined. void operator=(const _Impl&); // Not defined. bool _M_check_same_name() { bool __ret = true; if (_M_names[1]) // We must actually compare all the _M_names: can be all equal! for (size_t __i = 0; __ret && __i < _S_categories_size - 1; ++__i) __ret = __builtin_strcmp(_M_names[__i], _M_names[__i + 1]) == 0; return __ret; } void _M_replace_categories(const _Impl*, category); void _M_replace_category(const _Impl*, const locale::id* const*); void _M_replace_facet(const _Impl*, const locale::id*); void _M_install_facet(const locale::id*, const facet*); template void _M_init_facet(_Facet* __facet) { _M_install_facet(&_Facet::id, __facet); } template void _M_init_facet_unchecked(_Facet* __facet) { __facet->_M_add_reference(); _M_facets[_Facet::id._M_id()] = __facet; } void _M_install_cache(const facet*, size_t); void _M_init_extra(facet**); void _M_init_extra(void*, void*, const char*, const char*); }; /** * @brief Facet for localized string comparison. * * This facet encapsulates the code to compare strings in a localized * manner. * * The collate template uses protected virtual functions to provide * the actual results. The public accessors forward the call to * the virtual functions. These virtual functions are hooks for * developers to implement the behavior they require from the * collate facet. */ template class _GLIBCXX_NAMESPACE_CXX11 collate : public locale::facet { public: // Types: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} protected: // Underlying "C" library locale information saved from // initialization, needed by collate_byname as well. __c_locale _M_c_locale_collate; public: /// Numpunct facet id. static locale::id id; /** * @brief Constructor performs initialization. * * This is the constructor provided by the standard. * * @param __refs Passed to the base facet class. */ explicit collate(size_t __refs = 0) : facet(__refs), _M_c_locale_collate(_S_get_c_locale()) { } /** * @brief Internal constructor. Not for general use. * * This is a constructor for use by the library itself to set up new * locales. * * @param __cloc The C locale. * @param __refs Passed to the base facet class. */ explicit collate(__c_locale __cloc, size_t __refs = 0) : facet(__refs), _M_c_locale_collate(_S_clone_c_locale(__cloc)) { } /** * @brief Compare two strings. * * This function compares two strings and returns the result by calling * collate::do_compare(). * * @param __lo1 Start of string 1. * @param __hi1 End of string 1. * @param __lo2 Start of string 2. * @param __hi2 End of string 2. * @return 1 if string1 > string2, -1 if string1 < string2, else 0. */ int compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const { return this->do_compare(__lo1, __hi1, __lo2, __hi2); } /** * @brief Transform string to comparable form. * * This function is a wrapper for strxfrm functionality. It takes the * input string and returns a modified string that can be directly * compared to other transformed strings. In the C locale, this * function just returns a copy of the input string. In some other * locales, it may replace two chars with one, change a char for * another, etc. It does so by returning collate::do_transform(). * * @param __lo Start of string. * @param __hi End of string. * @return Transformed string_type. */ string_type transform(const _CharT* __lo, const _CharT* __hi) const { return this->do_transform(__lo, __hi); } /** * @brief Return hash of a string. * * This function computes and returns a hash on the input string. It * does so by returning collate::do_hash(). * * @param __lo Start of string. * @param __hi End of string. * @return Hash value. */ long hash(const _CharT* __lo, const _CharT* __hi) const { return this->do_hash(__lo, __hi); } // Used to abstract out _CharT bits in virtual member functions, below. int _M_compare(const _CharT*, const _CharT*) const throw(); size_t _M_transform(_CharT*, const _CharT*, size_t) const throw(); protected: /// Destructor. virtual ~collate() { _S_destroy_c_locale(_M_c_locale_collate); } /** * @brief Compare two strings. * * This function is a hook for derived classes to change the value * returned. @see compare(). * * @param __lo1 Start of string 1. * @param __hi1 End of string 1. * @param __lo2 Start of string 2. * @param __hi2 End of string 2. * @return 1 if string1 > string2, -1 if string1 < string2, else 0. */ virtual int do_compare(const _CharT* __lo1, const _CharT* __hi1, const _CharT* __lo2, const _CharT* __hi2) const; /** * @brief Transform string to comparable form. * * This function is a hook for derived classes to change the value * returned. * * @param __lo Start. * @param __hi End. * @return transformed string. */ virtual string_type do_transform(const _CharT* __lo, const _CharT* __hi) const; /** * @brief Return hash of a string. * * This function computes and returns a hash on the input string. This * function is a hook for derived classes to change the value returned. * * @param __lo Start of string. * @param __hi End of string. * @return Hash value. */ virtual long do_hash(const _CharT* __lo, const _CharT* __hi) const; }; template locale::id collate<_CharT>::id; // Specializations. template<> int collate::_M_compare(const char*, const char*) const throw(); template<> size_t collate::_M_transform(char*, const char*, size_t) const throw(); #ifdef _GLIBCXX_USE_WCHAR_T template<> int collate::_M_compare(const wchar_t*, const wchar_t*) const throw(); template<> size_t collate::_M_transform(wchar_t*, const wchar_t*, size_t) const throw(); #endif /// class collate_byname [22.2.4.2]. template class _GLIBCXX_NAMESPACE_CXX11 collate_byname : public collate<_CharT> { public: //@{ /// Public typedefs typedef _CharT char_type; typedef basic_string<_CharT> string_type; //@} explicit collate_byname(const char* __s, size_t __refs = 0) : collate<_CharT>(__refs) { if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { this->_S_destroy_c_locale(this->_M_c_locale_collate); this->_S_create_c_locale(this->_M_c_locale_collate, __s); } } #if __cplusplus >= 201103L explicit collate_byname(const string& __s, size_t __refs = 0) : collate_byname(__s.c_str(), __refs) { } #endif protected: virtual ~collate_byname() { } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace # include #endif c++/8/bits/algorithmfwd.h000064400000052350151027430570011075 0ustar00// Forward declarations -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/algorithmfwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{algorithm} */ #ifndef _GLIBCXX_ALGORITHMFWD_H #define _GLIBCXX_ALGORITHMFWD_H 1 #pragma GCC system_header #include #include #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /* adjacent_find all_of (C++11) any_of (C++11) binary_search clamp (C++17) copy copy_backward copy_if (C++11) copy_n (C++11) count count_if equal equal_range fill fill_n find find_end find_first_of find_if find_if_not (C++11) for_each generate generate_n includes inplace_merge is_heap (C++11) is_heap_until (C++11) is_partitioned (C++11) is_sorted (C++11) is_sorted_until (C++11) iter_swap lexicographical_compare lower_bound make_heap max max_element merge min min_element minmax (C++11) minmax_element (C++11) mismatch next_permutation none_of (C++11) nth_element partial_sort partial_sort_copy partition partition_copy (C++11) partition_point (C++11) pop_heap prev_permutation push_heap random_shuffle remove remove_copy remove_copy_if remove_if replace replace_copy replace_copy_if replace_if reverse reverse_copy rotate rotate_copy search search_n set_difference set_intersection set_symmetric_difference set_union shuffle (C++11) sort sort_heap stable_partition stable_sort swap swap_ranges transform unique unique_copy upper_bound */ /** * @defgroup algorithms Algorithms * * Components for performing algorithmic operations. Includes * non-modifying sequence, modifying (mutating) sequence, sorting, * searching, merge, partition, heap, set, minima, maxima, and * permutation operations. */ /** * @defgroup mutating_algorithms Mutating * @ingroup algorithms */ /** * @defgroup non_mutating_algorithms Non-Mutating * @ingroup algorithms */ /** * @defgroup sorting_algorithms Sorting * @ingroup algorithms */ /** * @defgroup set_algorithms Set Operation * @ingroup sorting_algorithms * * These algorithms are common set operations performed on sequences * that are already sorted. The number of comparisons will be * linear. */ /** * @defgroup binary_search_algorithms Binary Search * @ingroup sorting_algorithms * * These algorithms are variations of a classic binary search, and * all assume that the sequence being searched is already sorted. * * The number of comparisons will be logarithmic (and as few as * possible). The number of steps through the sequence will be * logarithmic for random-access iterators (e.g., pointers), and * linear otherwise. * * The LWG has passed Defect Report 270, which notes: The * proposed resolution reinterprets binary search. Instead of * thinking about searching for a value in a sorted range, we view * that as an important special case of a more general algorithm: * searching for the partition point in a partitioned range. We * also add a guarantee that the old wording did not: we ensure that * the upper bound is no earlier than the lower bound, that the pair * returned by equal_range is a valid range, and that the first part * of that pair is the lower bound. * * The actual effect of the first sentence is that a comparison * functor passed by the user doesn't necessarily need to induce a * strict weak ordering relation. Rather, it partitions the range. */ // adjacent_find #if __cplusplus >= 201103L template bool all_of(_IIter, _IIter, _Predicate); template bool any_of(_IIter, _IIter, _Predicate); #endif template bool binary_search(_FIter, _FIter, const _Tp&); template bool binary_search(_FIter, _FIter, const _Tp&, _Compare); #if __cplusplus > 201402L template _GLIBCXX14_CONSTEXPR const _Tp& clamp(const _Tp&, const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR const _Tp& clamp(const _Tp&, const _Tp&, const _Tp&, _Compare); #endif template _OIter copy(_IIter, _IIter, _OIter); template _BIter2 copy_backward(_BIter1, _BIter1, _BIter2); #if __cplusplus >= 201103L template _OIter copy_if(_IIter, _IIter, _OIter, _Predicate); template _OIter copy_n(_IIter, _Size, _OIter); #endif // count // count_if template pair<_FIter, _FIter> equal_range(_FIter, _FIter, const _Tp&); template pair<_FIter, _FIter> equal_range(_FIter, _FIter, const _Tp&, _Compare); template void fill(_FIter, _FIter, const _Tp&); template _OIter fill_n(_OIter, _Size, const _Tp&); // find template _FIter1 find_end(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 find_end(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate); // find_first_of // find_if #if __cplusplus >= 201103L template _IIter find_if_not(_IIter, _IIter, _Predicate); #endif // for_each // generate // generate_n template bool includes(_IIter1, _IIter1, _IIter2, _IIter2); template bool includes(_IIter1, _IIter1, _IIter2, _IIter2, _Compare); template void inplace_merge(_BIter, _BIter, _BIter); template void inplace_merge(_BIter, _BIter, _BIter, _Compare); #if __cplusplus >= 201103L template bool is_heap(_RAIter, _RAIter); template bool is_heap(_RAIter, _RAIter, _Compare); template _RAIter is_heap_until(_RAIter, _RAIter); template _RAIter is_heap_until(_RAIter, _RAIter, _Compare); template bool is_partitioned(_IIter, _IIter, _Predicate); template bool is_permutation(_FIter1, _FIter1, _FIter2); template bool is_permutation(_FIter1, _FIter1, _FIter2, _BinaryPredicate); template bool is_sorted(_FIter, _FIter); template bool is_sorted(_FIter, _FIter, _Compare); template _FIter is_sorted_until(_FIter, _FIter); template _FIter is_sorted_until(_FIter, _FIter, _Compare); #endif template void iter_swap(_FIter1, _FIter2); template _FIter lower_bound(_FIter, _FIter, const _Tp&); template _FIter lower_bound(_FIter, _FIter, const _Tp&, _Compare); template void make_heap(_RAIter, _RAIter); template void make_heap(_RAIter, _RAIter, _Compare); template _GLIBCXX14_CONSTEXPR const _Tp& max(const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR const _Tp& max(const _Tp&, const _Tp&, _Compare); // max_element // merge template _GLIBCXX14_CONSTEXPR const _Tp& min(const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR const _Tp& min(const _Tp&, const _Tp&, _Compare); // min_element #if __cplusplus >= 201103L template _GLIBCXX14_CONSTEXPR pair minmax(const _Tp&, const _Tp&); template _GLIBCXX14_CONSTEXPR pair minmax(const _Tp&, const _Tp&, _Compare); template _GLIBCXX14_CONSTEXPR pair<_FIter, _FIter> minmax_element(_FIter, _FIter); template _GLIBCXX14_CONSTEXPR pair<_FIter, _FIter> minmax_element(_FIter, _FIter, _Compare); template _GLIBCXX14_CONSTEXPR _Tp min(initializer_list<_Tp>); template _GLIBCXX14_CONSTEXPR _Tp min(initializer_list<_Tp>, _Compare); template _GLIBCXX14_CONSTEXPR _Tp max(initializer_list<_Tp>); template _GLIBCXX14_CONSTEXPR _Tp max(initializer_list<_Tp>, _Compare); template _GLIBCXX14_CONSTEXPR pair<_Tp, _Tp> minmax(initializer_list<_Tp>); template _GLIBCXX14_CONSTEXPR pair<_Tp, _Tp> minmax(initializer_list<_Tp>, _Compare); #endif // mismatch template bool next_permutation(_BIter, _BIter); template bool next_permutation(_BIter, _BIter, _Compare); #if __cplusplus >= 201103L template bool none_of(_IIter, _IIter, _Predicate); #endif // nth_element // partial_sort template _RAIter partial_sort_copy(_IIter, _IIter, _RAIter, _RAIter); template _RAIter partial_sort_copy(_IIter, _IIter, _RAIter, _RAIter, _Compare); // partition #if __cplusplus >= 201103L template pair<_OIter1, _OIter2> partition_copy(_IIter, _IIter, _OIter1, _OIter2, _Predicate); template _FIter partition_point(_FIter, _FIter, _Predicate); #endif template void pop_heap(_RAIter, _RAIter); template void pop_heap(_RAIter, _RAIter, _Compare); template bool prev_permutation(_BIter, _BIter); template bool prev_permutation(_BIter, _BIter, _Compare); template void push_heap(_RAIter, _RAIter); template void push_heap(_RAIter, _RAIter, _Compare); // random_shuffle template _FIter remove(_FIter, _FIter, const _Tp&); template _FIter remove_if(_FIter, _FIter, _Predicate); template _OIter remove_copy(_IIter, _IIter, _OIter, const _Tp&); template _OIter remove_copy_if(_IIter, _IIter, _OIter, _Predicate); // replace template _OIter replace_copy(_IIter, _IIter, _OIter, const _Tp&, const _Tp&); template _OIter replace_copy_if(_Iter, _Iter, _OIter, _Predicate, const _Tp&); // replace_if template void reverse(_BIter, _BIter); template _OIter reverse_copy(_BIter, _BIter, _OIter); inline namespace _V2 { template _FIter rotate(_FIter, _FIter, _FIter); } template _OIter rotate_copy(_FIter, _FIter, _FIter, _OIter); // search // search_n // set_difference // set_intersection // set_symmetric_difference // set_union #if (__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99_STDINT_TR1) template void shuffle(_RAIter, _RAIter, _UGenerator&&); #endif template void sort_heap(_RAIter, _RAIter); template void sort_heap(_RAIter, _RAIter, _Compare); template _BIter stable_partition(_BIter, _BIter, _Predicate); #if __cplusplus < 201103L // For C++11 swap() is declared in . template inline void swap(_Tp& __a, _Tp& __b); template inline void swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm]); #endif template _FIter2 swap_ranges(_FIter1, _FIter1, _FIter2); // transform template _FIter unique(_FIter, _FIter); template _FIter unique(_FIter, _FIter, _BinaryPredicate); // unique_copy template _FIter upper_bound(_FIter, _FIter, const _Tp&); template _FIter upper_bound(_FIter, _FIter, const _Tp&, _Compare); _GLIBCXX_BEGIN_NAMESPACE_ALGO template _FIter adjacent_find(_FIter, _FIter); template _FIter adjacent_find(_FIter, _FIter, _BinaryPredicate); template typename iterator_traits<_IIter>::difference_type count(_IIter, _IIter, const _Tp&); template typename iterator_traits<_IIter>::difference_type count_if(_IIter, _IIter, _Predicate); template bool equal(_IIter1, _IIter1, _IIter2); template bool equal(_IIter1, _IIter1, _IIter2, _BinaryPredicate); template _IIter find(_IIter, _IIter, const _Tp&); template _FIter1 find_first_of(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 find_first_of(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate); template _IIter find_if(_IIter, _IIter, _Predicate); template _Funct for_each(_IIter, _IIter, _Funct); template void generate(_FIter, _FIter, _Generator); template _OIter generate_n(_OIter, _Size, _Generator); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2, _Compare); template _GLIBCXX14_CONSTEXPR _FIter max_element(_FIter, _FIter); template _GLIBCXX14_CONSTEXPR _FIter max_element(_FIter, _FIter, _Compare); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _GLIBCXX14_CONSTEXPR _FIter min_element(_FIter, _FIter); template _GLIBCXX14_CONSTEXPR _FIter min_element(_FIter, _FIter, _Compare); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2, _BinaryPredicate); template void nth_element(_RAIter, _RAIter, _RAIter); template void nth_element(_RAIter, _RAIter, _RAIter, _Compare); template void partial_sort(_RAIter, _RAIter, _RAIter); template void partial_sort(_RAIter, _RAIter, _RAIter, _Compare); template _BIter partition(_BIter, _BIter, _Predicate); template void random_shuffle(_RAIter, _RAIter); template void random_shuffle(_RAIter, _RAIter, #if __cplusplus >= 201103L _Generator&&); #else _Generator&); #endif template void replace(_FIter, _FIter, const _Tp&, const _Tp&); template void replace_if(_FIter, _FIter, _Predicate, const _Tp&); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate); template _FIter search_n(_FIter, _FIter, _Size, const _Tp&); template _FIter search_n(_FIter, _FIter, _Size, const _Tp&, _BinaryPredicate); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template void sort(_RAIter, _RAIter); template void sort(_RAIter, _RAIter, _Compare); template void stable_sort(_RAIter, _RAIter); template void stable_sort(_RAIter, _RAIter, _Compare); template _OIter transform(_IIter, _IIter, _OIter, _UnaryOperation); template _OIter transform(_IIter1, _IIter1, _IIter2, _OIter, _BinaryOperation); template _OIter unique_copy(_IIter, _IIter, _OIter); template _OIter unique_copy(_IIter, _IIter, _OIter, _BinaryPredicate); _GLIBCXX_END_NAMESPACE_ALGO _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #ifdef _GLIBCXX_PARALLEL # include #endif #endif c++/8/bits/ostream.tcc000064400000030033151027430570010374 0ustar00// ostream classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ostream.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ostream} */ // // ISO C++ 14882: 27.6.2 Output streams // #ifndef _OSTREAM_TCC #define _OSTREAM_TCC 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template basic_ostream<_CharT, _Traits>::sentry:: sentry(basic_ostream<_CharT, _Traits>& __os) : _M_ok(false), _M_os(__os) { // XXX MT if (__os.tie() && __os.good()) __os.tie()->flush(); if (__os.good()) _M_ok = true; else __os.setstate(ios_base::failbit); } template template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: _M_insert(_ValueT __v) { sentry __cerb(*this); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const __num_put_type& __np = __check_facet(this->_M_num_put); if (__np.put(*this, *this, this->fill(), __v).failed()) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: operator<<(short __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 117. basic_ostream uses nonexistent num_put member functions. const ios_base::fmtflags __fmt = this->flags() & ios_base::basefield; if (__fmt == ios_base::oct || __fmt == ios_base::hex) return _M_insert(static_cast(static_cast(__n))); else return _M_insert(static_cast(__n)); } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: operator<<(int __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 117. basic_ostream uses nonexistent num_put member functions. const ios_base::fmtflags __fmt = this->flags() & ios_base::basefield; if (__fmt == ios_base::oct || __fmt == ios_base::hex) return _M_insert(static_cast(static_cast(__n))); else return _M_insert(static_cast(__n)); } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: operator<<(__streambuf_type* __sbin) { ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this); if (__cerb && __sbin) { __try { if (!__copy_streambufs(__sbin, this->rdbuf())) __err |= ios_base::failbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::failbit); } } else if (!__sbin) __err |= ios_base::badbit; if (__err) this->setstate(__err); return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: put(char_type __c) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 60. What is a formatted input function? // basic_ostream::put(char_type) is an unformatted output function. // DR 63. Exception-handling policy for unformatted output. // Unformatted output functions should catch exceptions thrown // from streambuf members. sentry __cerb(*this); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __put = this->rdbuf()->sputc(__c); if (traits_type::eq_int_type(__put, traits_type::eof())) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: write(const _CharT* __s, streamsize __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 60. What is a formatted input function? // basic_ostream::write(const char_type*, streamsize) is an // unformatted output function. // DR 63. Exception-handling policy for unformatted output. // Unformatted output functions should catch exceptions thrown // from streambuf members. sentry __cerb(*this); if (__cerb) { __try { _M_write(__s, __n); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: flush() { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 60. What is a formatted input function? // basic_ostream::flush() is *not* an unformatted output function. ios_base::iostate __err = ios_base::goodbit; __try { if (this->rdbuf() && this->rdbuf()->pubsync() == -1) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); return *this; } template typename basic_ostream<_CharT, _Traits>::pos_type basic_ostream<_CharT, _Traits>:: tellp() { pos_type __ret = pos_type(-1); __try { if (!this->fail()) __ret = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::out); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } return __ret; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: seekp(pos_type __pos) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekpos(__pos, ios_base::out); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); return *this; } template basic_ostream<_CharT, _Traits>& basic_ostream<_CharT, _Traits>:: seekp(off_type __off, ios_base::seekdir __dir) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekoff(__off, __dir, ios_base::out); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); return *this; } template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s) { if (!__s) __out.setstate(ios_base::badbit); else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 167. Improper use of traits_type::length() const size_t __clen = char_traits::length(__s); __try { struct __ptr_guard { _CharT *__p; __ptr_guard (_CharT *__ip): __p(__ip) { } ~__ptr_guard() { delete[] __p; } _CharT* __get() { return __p; } } __pg (new _CharT[__clen]); _CharT *__ws = __pg.__get(); for (size_t __i = 0; __i < __clen; ++__i) __ws[__i] = __out.widen(__s[__i]); __ostream_insert(__out, __ws, __clen); } __catch(__cxxabiv1::__forced_unwind&) { __out._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __out._M_setstate(ios_base::badbit); } } return __out; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_ostream; extern template ostream& endl(ostream&); extern template ostream& ends(ostream&); extern template ostream& flush(ostream&); extern template ostream& operator<<(ostream&, char); extern template ostream& operator<<(ostream&, unsigned char); extern template ostream& operator<<(ostream&, signed char); extern template ostream& operator<<(ostream&, const char*); extern template ostream& operator<<(ostream&, const unsigned char*); extern template ostream& operator<<(ostream&, const signed char*); extern template ostream& ostream::_M_insert(long); extern template ostream& ostream::_M_insert(unsigned long); extern template ostream& ostream::_M_insert(bool); #ifdef _GLIBCXX_USE_LONG_LONG extern template ostream& ostream::_M_insert(long long); extern template ostream& ostream::_M_insert(unsigned long long); #endif extern template ostream& ostream::_M_insert(double); extern template ostream& ostream::_M_insert(long double); extern template ostream& ostream::_M_insert(const void*); #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_ostream; extern template wostream& endl(wostream&); extern template wostream& ends(wostream&); extern template wostream& flush(wostream&); extern template wostream& operator<<(wostream&, wchar_t); extern template wostream& operator<<(wostream&, char); extern template wostream& operator<<(wostream&, const wchar_t*); extern template wostream& operator<<(wostream&, const char*); extern template wostream& wostream::_M_insert(long); extern template wostream& wostream::_M_insert(unsigned long); extern template wostream& wostream::_M_insert(bool); #ifdef _GLIBCXX_USE_LONG_LONG extern template wostream& wostream::_M_insert(long long); extern template wostream& wostream::_M_insert(unsigned long long); #endif extern template wostream& wostream::_M_insert(double); extern template wostream& wostream::_M_insert(long double); extern template wostream& wostream::_M_insert(const void*); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/stl_queue.h000064400000057011151027430570010413 0ustar00// Queue implementation -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_queue.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{queue} */ #ifndef _STL_QUEUE_H #define _STL_QUEUE_H 1 #include #include #if __cplusplus >= 201103L # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief A standard container giving FIFO behavior. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Sequence Type of underlying sequence, defaults to deque<_Tp>. * * Meets many of the requirements of a * container, * but does not define anything to do with iterators. Very few of the * other standard container interfaces are defined. * * This is not a true container, but an @e adaptor. It holds another * container, and provides a wrapper interface to that container. The * wrapper is what enforces strict first-in-first-out %queue behavior. * * The second template parameter defines the type of the underlying * sequence/container. It defaults to std::deque, but it can be any type * that supports @c front, @c back, @c push_back, and @c pop_front, * such as std::list or an appropriate user-defined type. * * Members not found in @a normal containers are @c container_type, * which is a typedef for the second Sequence parameter, and @c push and * @c pop, which are standard %queue/FIFO operations. */ template > class queue { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Sequence::value_type _Sequence_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires(_Sequence, _FrontInsertionSequenceConcept) __glibcxx_class_requires(_Sequence, _BackInsertionSequenceConcept) __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept) #endif template friend bool operator==(const queue<_Tp1, _Seq1>&, const queue<_Tp1, _Seq1>&); template friend bool operator<(const queue<_Tp1, _Seq1>&, const queue<_Tp1, _Seq1>&); #if __cplusplus >= 201103L template using _Uses = typename enable_if::value>::type; #endif public: typedef typename _Sequence::value_type value_type; typedef typename _Sequence::reference reference; typedef typename _Sequence::const_reference const_reference; typedef typename _Sequence::size_type size_type; typedef _Sequence container_type; protected: /* Maintainers wondering why this isn't uglified as per style * guidelines should note that this name is specified in the standard, * C++98 [23.2.3.1]. * (Why? Presumably for the same reason that it's protected instead * of private: to allow derivation. But none of the other * containers allow for derivation. Odd.) */ /// @c c is the underlying container. _Sequence c; public: /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L explicit queue(const _Sequence& __c = _Sequence()) : c(__c) { } #else template::value>::type> queue() : c() { } explicit queue(const _Sequence& __c) : c(__c) { } explicit queue(_Sequence&& __c) : c(std::move(__c)) { } template> explicit queue(const _Alloc& __a) : c(__a) { } template> queue(const _Sequence& __c, const _Alloc& __a) : c(__c, __a) { } template> queue(_Sequence&& __c, const _Alloc& __a) : c(std::move(__c), __a) { } template> queue(const queue& __q, const _Alloc& __a) : c(__q.c, __a) { } template> queue(queue&& __q, const _Alloc& __a) : c(std::move(__q.c), __a) { } #endif /** * Returns true if the %queue is empty. */ bool empty() const { return c.empty(); } /** Returns the number of elements in the %queue. */ size_type size() const { return c.size(); } /** * Returns a read/write reference to the data at the first * element of the %queue. */ reference front() { __glibcxx_requires_nonempty(); return c.front(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %queue. */ const_reference front() const { __glibcxx_requires_nonempty(); return c.front(); } /** * Returns a read/write reference to the data at the last * element of the %queue. */ reference back() { __glibcxx_requires_nonempty(); return c.back(); } /** * Returns a read-only (constant) reference to the data at the last * element of the %queue. */ const_reference back() const { __glibcxx_requires_nonempty(); return c.back(); } /** * @brief Add data to the end of the %queue. * @param __x Data to be added. * * This is a typical %queue operation. The function creates an * element at the end of the %queue and assigns the given data * to it. The time complexity of the operation depends on the * underlying sequence. */ void push(const value_type& __x) { c.push_back(__x); } #if __cplusplus >= 201103L void push(value_type&& __x) { c.push_back(std::move(__x)); } #if __cplusplus > 201402L template decltype(auto) emplace(_Args&&... __args) { return c.emplace_back(std::forward<_Args>(__args)...); } #else template void emplace(_Args&&... __args) { c.emplace_back(std::forward<_Args>(__args)...); } #endif #endif /** * @brief Removes first element. * * This is a typical %queue operation. It shrinks the %queue by one. * The time complexity of the operation depends on the underlying * sequence. * * Note that no data is returned, and if the first element's * data is needed, it should be retrieved before pop() is * called. */ void pop() { __glibcxx_requires_nonempty(); c.pop_front(); } #if __cplusplus >= 201103L void swap(queue& __q) #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 noexcept(__is_nothrow_swappable<_Sequence>::value) #else noexcept(__is_nothrow_swappable<_Tp>::value) #endif { using std::swap; swap(c, __q.c); } #endif // __cplusplus >= 201103L }; #if __cpp_deduction_guides >= 201606 template::value>> queue(_Container) -> queue; template::value>, typename = enable_if_t<__is_allocator<_Allocator>::value>> queue(_Container, _Allocator) -> queue; #endif /** * @brief Queue equality comparison. * @param __x A %queue. * @param __y A %queue of the same type as @a __x. * @return True iff the size and elements of the queues are equal. * * This is an equivalence relation. Complexity and semantics depend on the * underlying sequence type, but the expected rules are: this relation is * linear in the size of the sequences, and queues are considered equivalent * if their sequences compare equal. */ template inline bool operator==(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return __x.c == __y.c; } /** * @brief Queue ordering relation. * @param __x A %queue. * @param __y A %queue of the same type as @a x. * @return True iff @a __x is lexicographically less than @a __y. * * This is an total ordering relation. Complexity and semantics * depend on the underlying sequence type, but the expected rules * are: this relation is linear in the size of the sequences, the * elements must be comparable with @c <, and * std::lexicographical_compare() is usually used to make the * determination. */ template inline bool operator<(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return __x.c < __y.c; } /// Based on operator== template inline bool operator!=(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return !(__x == __y); } /// Based on operator< template inline bool operator>(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return __y < __x; } /// Based on operator< template inline bool operator<=(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return !(__y < __x); } /// Based on operator< template inline bool operator>=(const queue<_Tp, _Seq>& __x, const queue<_Tp, _Seq>& __y) { return !(__x < __y); } #if __cplusplus >= 201103L template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__is_swappable<_Seq>::value>::type #else void #endif swap(queue<_Tp, _Seq>& __x, queue<_Tp, _Seq>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template struct uses_allocator, _Alloc> : public uses_allocator<_Seq, _Alloc>::type { }; #endif // __cplusplus >= 201103L /** * @brief A standard container automatically sorting its contents. * * @ingroup sequences * * @tparam _Tp Type of element. * @tparam _Sequence Type of underlying sequence, defaults to vector<_Tp>. * @tparam _Compare Comparison function object type, defaults to * less<_Sequence::value_type>. * * This is not a true container, but an @e adaptor. It holds * another container, and provides a wrapper interface to that * container. The wrapper is what enforces priority-based sorting * and %queue behavior. Very few of the standard container/sequence * interface requirements are met (e.g., iterators). * * The second template parameter defines the type of the underlying * sequence/container. It defaults to std::vector, but it can be * any type that supports @c front(), @c push_back, @c pop_back, * and random-access iterators, such as std::deque or an * appropriate user-defined type. * * The third template parameter supplies the means of making * priority comparisons. It defaults to @c less but * can be anything defining a strict weak ordering. * * Members not found in @a normal containers are @c container_type, * which is a typedef for the second Sequence parameter, and @c * push, @c pop, and @c top, which are standard %queue operations. * * @note No equality/comparison operators are provided for * %priority_queue. * * @note Sorting of the elements takes place as they are added to, * and removed from, the %priority_queue using the * %priority_queue's member functions. If you access the elements * by other means, and change their data such that the sorting * order would be different, the %priority_queue will not re-sort * the elements for you. (How could it know to do so?) */ template, typename _Compare = less > class priority_queue { #ifdef _GLIBCXX_CONCEPT_CHECKS // concept requirements typedef typename _Sequence::value_type _Sequence_value_type; # if __cplusplus < 201103L __glibcxx_class_requires(_Tp, _SGIAssignableConcept) # endif __glibcxx_class_requires(_Sequence, _SequenceConcept) __glibcxx_class_requires(_Sequence, _RandomAccessContainerConcept) __glibcxx_class_requires2(_Tp, _Sequence_value_type, _SameTypeConcept) __glibcxx_class_requires4(_Compare, bool, _Tp, _Tp, _BinaryFunctionConcept) #endif #if __cplusplus >= 201103L template using _Uses = typename enable_if::value>::type; #endif public: typedef typename _Sequence::value_type value_type; typedef typename _Sequence::reference reference; typedef typename _Sequence::const_reference const_reference; typedef typename _Sequence::size_type size_type; typedef _Sequence container_type; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 2684. priority_queue lacking comparator typedef typedef _Compare value_compare; protected: // See queue::c for notes on these names. _Sequence c; _Compare comp; public: /** * @brief Default constructor creates no elements. */ #if __cplusplus < 201103L explicit priority_queue(const _Compare& __x = _Compare(), const _Sequence& __s = _Sequence()) : c(__s), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } #else template, is_default_constructible<_Seq>>::value>::type> priority_queue() : c(), comp() { } explicit priority_queue(const _Compare& __x, const _Sequence& __s) : c(__s), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } explicit priority_queue(const _Compare& __x, _Sequence&& __s = _Sequence()) : c(std::move(__s)), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } template> explicit priority_queue(const _Alloc& __a) : c(__a), comp() { } template> priority_queue(const _Compare& __x, const _Alloc& __a) : c(__a), comp(__x) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2537. Constructors [...] taking allocators should call make_heap template> priority_queue(const _Compare& __x, const _Sequence& __c, const _Alloc& __a) : c(__c, __a), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } template> priority_queue(const _Compare& __x, _Sequence&& __c, const _Alloc& __a) : c(std::move(__c), __a), comp(__x) { std::make_heap(c.begin(), c.end(), comp); } template> priority_queue(const priority_queue& __q, const _Alloc& __a) : c(__q.c, __a), comp(__q.comp) { } template> priority_queue(priority_queue&& __q, const _Alloc& __a) : c(std::move(__q.c), __a), comp(std::move(__q.comp)) { } #endif /** * @brief Builds a %queue from a range. * @param __first An input iterator. * @param __last An input iterator. * @param __x A comparison functor describing a strict weak ordering. * @param __s An initial sequence with which to start. * * Begins by copying @a __s, inserting a copy of the elements * from @a [first,last) into the copy of @a __s, then ordering * the copy according to @a __x. * * For more information on function objects, see the * documentation on @link functors functor base * classes@endlink. */ #if __cplusplus < 201103L template priority_queue(_InputIterator __first, _InputIterator __last, const _Compare& __x = _Compare(), const _Sequence& __s = _Sequence()) : c(__s), comp(__x) { __glibcxx_requires_valid_range(__first, __last); c.insert(c.end(), __first, __last); std::make_heap(c.begin(), c.end(), comp); } #else template priority_queue(_InputIterator __first, _InputIterator __last, const _Compare& __x, const _Sequence& __s) : c(__s), comp(__x) { __glibcxx_requires_valid_range(__first, __last); c.insert(c.end(), __first, __last); std::make_heap(c.begin(), c.end(), comp); } template priority_queue(_InputIterator __first, _InputIterator __last, const _Compare& __x = _Compare(), _Sequence&& __s = _Sequence()) : c(std::move(__s)), comp(__x) { __glibcxx_requires_valid_range(__first, __last); c.insert(c.end(), __first, __last); std::make_heap(c.begin(), c.end(), comp); } #endif /** * Returns true if the %queue is empty. */ bool empty() const { return c.empty(); } /** Returns the number of elements in the %queue. */ size_type size() const { return c.size(); } /** * Returns a read-only (constant) reference to the data at the first * element of the %queue. */ const_reference top() const { __glibcxx_requires_nonempty(); return c.front(); } /** * @brief Add data to the %queue. * @param __x Data to be added. * * This is a typical %queue operation. * The time complexity of the operation depends on the underlying * sequence. */ void push(const value_type& __x) { c.push_back(__x); std::push_heap(c.begin(), c.end(), comp); } #if __cplusplus >= 201103L void push(value_type&& __x) { c.push_back(std::move(__x)); std::push_heap(c.begin(), c.end(), comp); } template void emplace(_Args&&... __args) { c.emplace_back(std::forward<_Args>(__args)...); std::push_heap(c.begin(), c.end(), comp); } #endif /** * @brief Removes first element. * * This is a typical %queue operation. It shrinks the %queue * by one. The time complexity of the operation depends on the * underlying sequence. * * Note that no data is returned, and if the first element's * data is needed, it should be retrieved before pop() is * called. */ void pop() { __glibcxx_requires_nonempty(); std::pop_heap(c.begin(), c.end(), comp); c.pop_back(); } #if __cplusplus >= 201103L void swap(priority_queue& __pq) noexcept(__and_< #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 __is_nothrow_swappable<_Sequence>, #else __is_nothrow_swappable<_Tp>, #endif __is_nothrow_swappable<_Compare> >::value) { using std::swap; swap(c, __pq.c); swap(comp, __pq.comp); } #endif // __cplusplus >= 201103L }; #if __cpp_deduction_guides >= 201606 template::value>, typename = enable_if_t::value>> priority_queue(_Compare, _Container) -> priority_queue; template::value_type, typename _Compare = less<_ValT>, typename _Container = vector<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = enable_if_t::value>, typename = enable_if_t::value>> priority_queue(_InputIterator, _InputIterator, _Compare = _Compare(), _Container = _Container()) -> priority_queue<_ValT, _Container, _Compare>; template::value>, typename = enable_if_t::value>, typename = enable_if_t<__is_allocator<_Allocator>::value>> priority_queue(_Compare, _Container, _Allocator) -> priority_queue; #endif // No equality/comparison operators are provided for priority_queue. #if __cplusplus >= 201103L template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__and_<__is_swappable<_Sequence>, __is_swappable<_Compare>>::value>::type #else void #endif swap(priority_queue<_Tp, _Sequence, _Compare>& __x, priority_queue<_Tp, _Sequence, _Compare>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template struct uses_allocator, _Alloc> : public uses_allocator<_Sequence, _Alloc>::type { }; #endif // __cplusplus >= 201103L _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _STL_QUEUE_H */ c++/8/bits/gslice.h000064400000012616151027430570007655 0ustar00// The template and inlines for the -*- C++ -*- gslice class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/gslice.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{valarray} */ // Written by Gabriel Dos Reis #ifndef _GSLICE_H #define _GSLICE_H 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ /** * @brief Class defining multi-dimensional subset of an array. * * The slice class represents a multi-dimensional subset of an array, * specified by three parameter sets: start offset, size array, and stride * array. The start offset is the index of the first element of the array * that is part of the subset. The size and stride array describe each * dimension of the slice. Size is the number of elements in that * dimension, and stride is the distance in the array between successive * elements in that dimension. Each dimension's size and stride is taken * to begin at an array element described by the previous dimension. The * size array and stride array must be the same size. * * For example, if you have offset==3, stride[0]==11, size[1]==3, * stride[1]==3, then slice[0,0]==array[3], slice[0,1]==array[6], * slice[0,2]==array[9], slice[1,0]==array[14], slice[1,1]==array[17], * slice[1,2]==array[20]. */ class gslice { public: /// Construct an empty slice. gslice(); /** * @brief Construct a slice. * * Constructs a slice with as many dimensions as the length of the @a l * and @a s arrays. * * @param __o Offset in array of first element. * @param __l Array of dimension lengths. * @param __s Array of dimension strides between array elements. */ gslice(size_t __o, const valarray& __l, const valarray& __s); // XXX: the IS says the copy-ctor and copy-assignment operators are // synthesized by the compiler but they are just unsuitable // for a ref-counted semantic /// Copy constructor. gslice(const gslice&); /// Destructor. ~gslice(); // XXX: See the note above. /// Assignment operator. gslice& operator=(const gslice&); /// Return array offset of first slice element. size_t start() const; /// Return array of sizes of slice dimensions. valarray size() const; /// Return array of array strides for each dimension. valarray stride() const; private: struct _Indexer { size_t _M_count; size_t _M_start; valarray _M_size; valarray _M_stride; valarray _M_index; // Linear array of referenced indices _Indexer() : _M_count(1), _M_start(0), _M_size(), _M_stride(), _M_index() {} _Indexer(size_t, const valarray&, const valarray&); void _M_increment_use() { ++_M_count; } size_t _M_decrement_use() { return --_M_count; } }; _Indexer* _M_index; template friend class valarray; }; inline size_t gslice::start() const { return _M_index ? _M_index->_M_start : 0; } inline valarray gslice::size() const { return _M_index ? _M_index->_M_size : valarray(); } inline valarray gslice::stride() const { return _M_index ? _M_index->_M_stride : valarray(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 543. valarray slice default constructor inline gslice::gslice() : _M_index(new gslice::_Indexer()) {} inline gslice::gslice(size_t __o, const valarray& __l, const valarray& __s) : _M_index(new gslice::_Indexer(__o, __l, __s)) {} inline gslice::gslice(const gslice& __g) : _M_index(__g._M_index) { if (_M_index) _M_index->_M_increment_use(); } inline gslice::~gslice() { if (_M_index && _M_index->_M_decrement_use() == 0) delete _M_index; } inline gslice& gslice::operator=(const gslice& __g) { if (__g._M_index) __g._M_index->_M_increment_use(); if (_M_index && _M_index->_M_decrement_use() == 0) delete _M_index; _M_index = __g._M_index; return *this; } // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GSLICE_H */ c++/8/bits/istream.tcc000064400000074565151027430570010410 0ustar00// istream classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/istream.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{istream} */ // // ISO C++ 14882: 27.6.1 Input streams // #ifndef _ISTREAM_TCC #define _ISTREAM_TCC 1 #pragma GCC system_header #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template basic_istream<_CharT, _Traits>::sentry:: sentry(basic_istream<_CharT, _Traits>& __in, bool __noskip) : _M_ok(false) { ios_base::iostate __err = ios_base::goodbit; if (__in.good()) __try { if (__in.tie()) __in.tie()->flush(); if (!__noskip && bool(__in.flags() & ios_base::skipws)) { const __int_type __eof = traits_type::eof(); __streambuf_type* __sb = __in.rdbuf(); __int_type __c = __sb->sgetc(); const __ctype_type& __ct = __check_facet(__in._M_ctype); while (!traits_type::eq_int_type(__c, __eof) && __ct.is(ctype_base::space, traits_type::to_char_type(__c))) __c = __sb->snextc(); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 195. Should basic_istream::sentry's constructor ever // set eofbit? if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __in._M_setstate(ios_base::badbit); } if (__in.good() && __err == ios_base::goodbit) _M_ok = true; else { __err |= ios_base::failbit; __in.setstate(__err); } } template template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: _M_extract(_ValueT& __v) { sentry __cerb(*this, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const __num_get_type& __ng = __check_facet(this->_M_num_get); __ng.get(*this, 0, *this, __err, __v); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: operator>>(short& __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 118. basic_istream uses nonexistent num_get member functions. sentry __cerb(*this, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { long __l; const __num_get_type& __ng = __check_facet(this->_M_num_get); __ng.get(*this, 0, *this, __err, __l); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 696. istream::operator>>(int&) broken. if (__l < __gnu_cxx::__numeric_traits::__min) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__min; } else if (__l > __gnu_cxx::__numeric_traits::__max) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__max; } else __n = short(__l); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: operator>>(int& __n) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 118. basic_istream uses nonexistent num_get member functions. sentry __cerb(*this, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { long __l; const __num_get_type& __ng = __check_facet(this->_M_num_get); __ng.get(*this, 0, *this, __err, __l); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 696. istream::operator>>(int&) broken. if (__l < __gnu_cxx::__numeric_traits::__min) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__min; } else if (__l > __gnu_cxx::__numeric_traits::__max) { __err |= ios_base::failbit; __n = __gnu_cxx::__numeric_traits::__max; } else __n = int(__l); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: operator>>(__streambuf_type* __sbout) { ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, false); if (__cerb && __sbout) { __try { bool __ineof; if (!__copy_streambufs_eof(this->rdbuf(), __sbout, __ineof)) __err |= ios_base::failbit; if (__ineof) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::failbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::failbit); } } else if (!__sbout) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template typename basic_istream<_CharT, _Traits>::int_type basic_istream<_CharT, _Traits>:: get(void) { const int_type __eof = traits_type::eof(); int_type __c = __eof; _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { __c = this->rdbuf()->sbumpc(); // 27.6.1.1 paragraph 3 if (!traits_type::eq_int_type(__c, __eof)) _M_gcount = 1; else __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return __c; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: get(char_type& __c) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __cb = this->rdbuf()->sbumpc(); // 27.6.1.1 paragraph 3 if (!traits_type::eq_int_type(__cb, traits_type::eof())) { _M_gcount = 1; __c = traits_type::to_char_type(__cb); } else __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: get(char_type* __s, streamsize __n, char_type __delim) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __idelim = traits_type::to_int_type(__delim); const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); while (_M_gcount + 1 < __n && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __idelim)) { *__s++ = traits_type::to_char_type(__c); ++_M_gcount; __c = __sb->snextc(); } if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 243. get and getline when sentry reports failure. if (__n > 0) *__s = char_type(); if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: get(__streambuf_type& __sb, char_type __delim) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __idelim = traits_type::to_int_type(__delim); const int_type __eof = traits_type::eof(); __streambuf_type* __this_sb = this->rdbuf(); int_type __c = __this_sb->sgetc(); char_type __c2 = traits_type::to_char_type(__c); while (!traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __idelim) && !traits_type::eq_int_type(__sb.sputc(__c2), __eof)) { ++_M_gcount; __c = __this_sb->snextc(); __c2 = traits_type::to_char_type(__c); } if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: getline(char_type* __s, streamsize __n, char_type __delim) { _M_gcount = 0; ios_base::iostate __err = ios_base::goodbit; sentry __cerb(*this, true); if (__cerb) { __try { const int_type __idelim = traits_type::to_int_type(__delim); const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); while (_M_gcount + 1 < __n && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __idelim)) { *__s++ = traits_type::to_char_type(__c); __c = __sb->snextc(); ++_M_gcount; } if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; else { if (traits_type::eq_int_type(__c, __idelim)) { __sb->sbumpc(); ++_M_gcount; } else __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 243. get and getline when sentry reports failure. if (__n > 0) *__s = char_type(); if (!_M_gcount) __err |= ios_base::failbit; if (__err) this->setstate(__err); return *this; } // We provide three overloads, since the first two are much simpler // than the general case. Also, the latter two can thus adopt the // same "batchy" strategy used by getline above. template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: ignore(void) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); if (traits_type::eq_int_type(__sb->sbumpc(), __eof)) __err |= ios_base::eofbit; else _M_gcount = 1; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: ignore(streamsize __n) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb && __n > 0) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); // N.B. On LFS-enabled platforms streamsize is still 32 bits // wide: if we want to implement the standard mandated behavior // for n == max() (see 27.6.1.3/24) we are at risk of signed // integer overflow: thus these contortions. Also note that, // by definition, when more than 2G chars are actually ignored, // _M_gcount (the return value of gcount, that is) cannot be // really correct, being unavoidably too small. bool __large_ignore = false; while (true) { while (_M_gcount < __n && !traits_type::eq_int_type(__c, __eof)) { ++_M_gcount; __c = __sb->snextc(); } if (__n == __gnu_cxx::__numeric_traits::__max && !traits_type::eq_int_type(__c, __eof)) { _M_gcount = __gnu_cxx::__numeric_traits::__min; __large_ignore = true; } else break; } if (__large_ignore) _M_gcount = __gnu_cxx::__numeric_traits::__max; if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: ignore(streamsize __n, int_type __delim) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb && __n > 0) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); int_type __c = __sb->sgetc(); // See comment above. bool __large_ignore = false; while (true) { while (_M_gcount < __n && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __delim)) { ++_M_gcount; __c = __sb->snextc(); } if (__n == __gnu_cxx::__numeric_traits::__max && !traits_type::eq_int_type(__c, __eof) && !traits_type::eq_int_type(__c, __delim)) { _M_gcount = __gnu_cxx::__numeric_traits::__min; __large_ignore = true; } else break; } if (__large_ignore) _M_gcount = __gnu_cxx::__numeric_traits::__max; if (traits_type::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; else if (traits_type::eq_int_type(__c, __delim)) { if (_M_gcount < __gnu_cxx::__numeric_traits::__max) ++_M_gcount; __sb->sbumpc(); } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template typename basic_istream<_CharT, _Traits>::int_type basic_istream<_CharT, _Traits>:: peek(void) { int_type __c = traits_type::eof(); _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { __c = this->rdbuf()->sgetc(); if (traits_type::eq_int_type(__c, traits_type::eof())) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return __c; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: read(char_type* __s, streamsize __n) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { _M_gcount = this->rdbuf()->sgetn(__s, __n); if (_M_gcount != __n) __err |= (ios_base::eofbit | ios_base::failbit); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template streamsize basic_istream<_CharT, _Traits>:: readsome(char_type* __s, streamsize __n) { _M_gcount = 0; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { // Cannot compare int_type with streamsize generically. const streamsize __num = this->rdbuf()->in_avail(); if (__num > 0) _M_gcount = this->rdbuf()->sgetn(__s, std::min(__num, __n)); else if (__num == -1) __err |= ios_base::eofbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return _M_gcount; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: putback(char_type __c) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 60. What is a formatted input function? _M_gcount = 0; // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); if (!__sb || traits_type::eq_int_type(__sb->sputbackc(__c), __eof)) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: unget(void) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 60. What is a formatted input function? _M_gcount = 0; // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const int_type __eof = traits_type::eof(); __streambuf_type* __sb = this->rdbuf(); if (!__sb || traits_type::eq_int_type(__sb->sungetc(), __eof)) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template int basic_istream<_CharT, _Traits>:: sync(void) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. int __ret = -1; sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { __streambuf_type* __sb = this->rdbuf(); if (__sb) { if (__sb->pubsync() == -1) __err |= ios_base::badbit; else __ret = 0; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return __ret; } template typename basic_istream<_CharT, _Traits>::pos_type basic_istream<_CharT, _Traits>:: tellg(void) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. pos_type __ret = pos_type(-1); sentry __cerb(*this, true); if (__cerb) { __try { if (!this->fail()) __ret = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::in); } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } } return __ret; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: seekg(pos_type __pos) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekpos(__pos, ios_base::in); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } template basic_istream<_CharT, _Traits>& basic_istream<_CharT, _Traits>:: seekg(off_type __off, ios_base::seekdir __dir) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR60. Do not change _M_gcount. // Clear eofbit per N3168. this->clear(this->rdstate() & ~ios_base::eofbit); sentry __cerb(*this, true); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { if (!this->fail()) { // 136. seekp, seekg setting wrong streams? const pos_type __p = this->rdbuf()->pubseekoff(__off, __dir, ios_base::in); // 129. Need error indication from seekp() and seekg() if (__p == pos_type(off_type(-1))) __err |= ios_base::failbit; } } __catch(__cxxabiv1::__forced_unwind&) { this->_M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { this->_M_setstate(ios_base::badbit); } if (__err) this->setstate(__err); } return *this; } // 27.6.1.2.3 Character extraction templates template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, _CharT& __c) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::int_type __int_type; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { const __int_type __cb = __in.rdbuf()->sbumpc(); if (!_Traits::eq_int_type(__cb, _Traits::eof())) __c = _Traits::to_char_type(__cb); else __err |= (ios_base::eofbit | ios_base::failbit); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __in._M_setstate(ios_base::badbit); } if (__err) __in.setstate(__err); } return __in; } template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, _CharT* __s) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_streambuf<_CharT, _Traits> __streambuf_type; typedef typename _Traits::int_type int_type; typedef _CharT char_type; typedef ctype<_CharT> __ctype_type; streamsize __extracted = 0; ios_base::iostate __err = ios_base::goodbit; typename __istream_type::sentry __cerb(__in, false); if (__cerb) { __try { // Figure out how many characters to extract. streamsize __num = __in.width(); if (__num <= 0) __num = __gnu_cxx::__numeric_traits::__max; const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const int_type __eof = _Traits::eof(); __streambuf_type* __sb = __in.rdbuf(); int_type __c = __sb->sgetc(); while (__extracted < __num - 1 && !_Traits::eq_int_type(__c, __eof) && !__ct.is(ctype_base::space, _Traits::to_char_type(__c))) { *__s++ = _Traits::to_char_type(__c); ++__extracted; __c = __sb->snextc(); } if (_Traits::eq_int_type(__c, __eof)) __err |= ios_base::eofbit; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 68. Extractors for char* should store null at end *__s = char_type(); __in.width(0); } __catch(__cxxabiv1::__forced_unwind&) { __in._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __in._M_setstate(ios_base::badbit); } } if (!__extracted) __err |= ios_base::failbit; if (__err) __in.setstate(__err); return __in; } // 27.6.1.4 Standard basic_istream manipulators template basic_istream<_CharT, _Traits>& ws(basic_istream<_CharT, _Traits>& __in) { typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_streambuf<_CharT, _Traits> __streambuf_type; typedef typename __istream_type::int_type __int_type; typedef ctype<_CharT> __ctype_type; const __ctype_type& __ct = use_facet<__ctype_type>(__in.getloc()); const __int_type __eof = _Traits::eof(); __streambuf_type* __sb = __in.rdbuf(); __int_type __c = __sb->sgetc(); while (!_Traits::eq_int_type(__c, __eof) && __ct.is(ctype_base::space, _Traits::to_char_type(__c))) __c = __sb->snextc(); if (_Traits::eq_int_type(__c, __eof)) __in.setstate(ios_base::eofbit); return __in; } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. #if _GLIBCXX_EXTERN_TEMPLATE extern template class basic_istream; extern template istream& ws(istream&); extern template istream& operator>>(istream&, char&); extern template istream& operator>>(istream&, char*); extern template istream& operator>>(istream&, unsigned char&); extern template istream& operator>>(istream&, signed char&); extern template istream& operator>>(istream&, unsigned char*); extern template istream& operator>>(istream&, signed char*); extern template istream& istream::_M_extract(unsigned short&); extern template istream& istream::_M_extract(unsigned int&); extern template istream& istream::_M_extract(long&); extern template istream& istream::_M_extract(unsigned long&); extern template istream& istream::_M_extract(bool&); #ifdef _GLIBCXX_USE_LONG_LONG extern template istream& istream::_M_extract(long long&); extern template istream& istream::_M_extract(unsigned long long&); #endif extern template istream& istream::_M_extract(float&); extern template istream& istream::_M_extract(double&); extern template istream& istream::_M_extract(long double&); extern template istream& istream::_M_extract(void*&); extern template class basic_iostream; #ifdef _GLIBCXX_USE_WCHAR_T extern template class basic_istream; extern template wistream& ws(wistream&); extern template wistream& operator>>(wistream&, wchar_t&); extern template wistream& operator>>(wistream&, wchar_t*); extern template wistream& wistream::_M_extract(unsigned short&); extern template wistream& wistream::_M_extract(unsigned int&); extern template wistream& wistream::_M_extract(long&); extern template wistream& wistream::_M_extract(unsigned long&); extern template wistream& wistream::_M_extract(bool&); #ifdef _GLIBCXX_USE_LONG_LONG extern template wistream& wistream::_M_extract(long long&); extern template wistream& wistream::_M_extract(unsigned long long&); #endif extern template wistream& wistream::_M_extract(float&); extern template wistream& wistream::_M_extract(double&); extern template wistream& wistream::_M_extract(long double&); extern template wistream& wistream::_M_extract(void*&); extern template class basic_iostream; #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/uniform_int_dist.h000064400000023541151027430570011762 0ustar00// Class template uniform_int_distribution -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file bits/uniform_int_dist.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _GLIBCXX_BITS_UNIFORM_INT_DIST_H #define _GLIBCXX_BITS_UNIFORM_INT_DIST_H #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { /* Determine whether number is a power of 2. */ template inline bool _Power_of_2(_Tp __x) { return ((__x - 1) & __x) == 0; } } /** * @brief Uniform discrete distribution for random numbers. * A discrete random distribution on the range @f$[min, max]@f$ with equal * probability throughout the range. */ template class uniform_int_distribution { static_assert(std::is_integral<_IntType>::value, "template argument must be an integral type"); public: /** The type of the range of the distribution. */ typedef _IntType result_type; /** Parameter type. */ struct param_type { typedef uniform_int_distribution<_IntType> distribution_type; explicit param_type(_IntType __a = 0, _IntType __b = std::numeric_limits<_IntType>::max()) : _M_a(__a), _M_b(__b) { __glibcxx_assert(_M_a <= _M_b); } result_type a() const { return _M_a; } result_type b() const { return _M_b; } friend bool operator==(const param_type& __p1, const param_type& __p2) { return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; } friend bool operator!=(const param_type& __p1, const param_type& __p2) { return !(__p1 == __p2); } private: _IntType _M_a; _IntType _M_b; }; public: /** * @brief Constructs a uniform distribution object. */ explicit uniform_int_distribution(_IntType __a = 0, _IntType __b = std::numeric_limits<_IntType>::max()) : _M_param(__a, __b) { } explicit uniform_int_distribution(const param_type& __p) : _M_param(__p) { } /** * @brief Resets the distribution state. * * Does nothing for the uniform integer distribution. */ void reset() { } result_type a() const { return _M_param.a(); } result_type b() const { return _M_param.b(); } /** * @brief Returns the parameter set of the distribution. */ param_type param() const { return _M_param; } /** * @brief Sets the parameter set of the distribution. * @param __param The new parameter set of the distribution. */ void param(const param_type& __param) { _M_param = __param; } /** * @brief Returns the inclusive lower bound of the distribution range. */ result_type min() const { return this->a(); } /** * @brief Returns the inclusive upper bound of the distribution range. */ result_type max() const { return this->b(); } /** * @brief Generating functions. */ template result_type operator()(_UniformRandomNumberGenerator& __urng) { return this->operator()(__urng, _M_param); } template result_type operator()(_UniformRandomNumberGenerator& __urng, const param_type& __p); template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng) { this->__generate(__f, __t, __urng, _M_param); } template void __generate(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } template void __generate(result_type* __f, result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __p) { this->__generate_impl(__f, __t, __urng, __p); } /** * @brief Return true if two uniform integer distributions have * the same parameters. */ friend bool operator==(const uniform_int_distribution& __d1, const uniform_int_distribution& __d2) { return __d1._M_param == __d2._M_param; } private: template void __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __p); param_type _M_param; }; template template typename uniform_int_distribution<_IntType>::result_type uniform_int_distribution<_IntType>:: operator()(_UniformRandomNumberGenerator& __urng, const param_type& __param) { typedef typename _UniformRandomNumberGenerator::result_type _Gresult_type; typedef typename std::make_unsigned::type __utype; typedef typename std::common_type<_Gresult_type, __utype>::type __uctype; const __uctype __urngmin = __urng.min(); const __uctype __urngmax = __urng.max(); const __uctype __urngrange = __urngmax - __urngmin; const __uctype __urange = __uctype(__param.b()) - __uctype(__param.a()); __uctype __ret; if (__urngrange > __urange) { // downscaling const __uctype __uerange = __urange + 1; // __urange can be zero const __uctype __scaling = __urngrange / __uerange; const __uctype __past = __uerange * __scaling; do __ret = __uctype(__urng()) - __urngmin; while (__ret >= __past); __ret /= __scaling; } else if (__urngrange < __urange) { // upscaling /* Note that every value in [0, urange] can be written uniquely as (urngrange + 1) * high + low where high in [0, urange / (urngrange + 1)] and low in [0, urngrange]. */ __uctype __tmp; // wraparound control do { const __uctype __uerngrange = __urngrange + 1; __tmp = (__uerngrange * operator() (__urng, param_type(0, __urange / __uerngrange))); __ret = __tmp + (__uctype(__urng()) - __urngmin); } while (__ret > __urange || __ret < __tmp); } else __ret = __uctype(__urng()) - __urngmin; return __ret + __param.a(); } template template void uniform_int_distribution<_IntType>:: __generate_impl(_ForwardIterator __f, _ForwardIterator __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) typedef typename _UniformRandomNumberGenerator::result_type _Gresult_type; typedef typename std::make_unsigned::type __utype; typedef typename std::common_type<_Gresult_type, __utype>::type __uctype; const __uctype __urngmin = __urng.min(); const __uctype __urngmax = __urng.max(); const __uctype __urngrange = __urngmax - __urngmin; const __uctype __urange = __uctype(__param.b()) - __uctype(__param.a()); __uctype __ret; if (__urngrange > __urange) { if (__detail::_Power_of_2(__urngrange + 1) && __detail::_Power_of_2(__urange + 1)) { while (__f != __t) { __ret = __uctype(__urng()) - __urngmin; *__f++ = (__ret & __urange) + __param.a(); } } else { // downscaling const __uctype __uerange = __urange + 1; // __urange can be zero const __uctype __scaling = __urngrange / __uerange; const __uctype __past = __uerange * __scaling; while (__f != __t) { do __ret = __uctype(__urng()) - __urngmin; while (__ret >= __past); *__f++ = __ret / __scaling + __param.a(); } } } else if (__urngrange < __urange) { // upscaling /* Note that every value in [0, urange] can be written uniquely as (urngrange + 1) * high + low where high in [0, urange / (urngrange + 1)] and low in [0, urngrange]. */ __uctype __tmp; // wraparound control while (__f != __t) { do { const __uctype __uerngrange = __urngrange + 1; __tmp = (__uerngrange * operator() (__urng, param_type(0, __urange / __uerngrange))); __ret = __tmp + (__uctype(__urng()) - __urngmin); } while (__ret > __urange || __ret < __tmp); *__f++ = __ret; } } else while (__f != __t) *__f++ = __uctype(__urng()) - __urngmin + __param.a(); } // operator!= and operator<< and operator>> are defined in _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif c++/8/bits/stl_function.h000064400000121421151027430570011111 0ustar00// Functor implementations -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996-1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file bits/stl_function.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{functional} */ #ifndef _STL_FUNCTION_H #define _STL_FUNCTION_H 1 #if __cplusplus > 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // 20.3.1 base classes /** @defgroup functors Function Objects * @ingroup utilities * * Function objects, or @e functors, are objects with an @c operator() * defined and accessible. They can be passed as arguments to algorithm * templates and used in place of a function pointer. Not only is the * resulting expressiveness of the library increased, but the generated * code can be more efficient than what you might write by hand. When we * refer to @a functors, then, generally we include function pointers in * the description as well. * * Often, functors are only created as temporaries passed to algorithm * calls, rather than being created as named variables. * * Two examples taken from the standard itself follow. To perform a * by-element addition of two vectors @c a and @c b containing @c double, * and put the result in @c a, use * \code * transform (a.begin(), a.end(), b.begin(), a.begin(), plus()); * \endcode * To negate every element in @c a, use * \code * transform(a.begin(), a.end(), a.begin(), negate()); * \endcode * The addition and negation functions will be inlined directly. * * The standard functors are derived from structs named @c unary_function * and @c binary_function. These two classes contain nothing but typedefs, * to aid in generic (template) programming. If you write your own * functors, you might consider doing the same. * * @{ */ /** * This is one of the @link functors functor base classes@endlink. */ template struct unary_function { /// @c argument_type is the type of the argument typedef _Arg argument_type; /// @c result_type is the return type typedef _Result result_type; }; /** * This is one of the @link functors functor base classes@endlink. */ template struct binary_function { /// @c first_argument_type is the type of the first argument typedef _Arg1 first_argument_type; /// @c second_argument_type is the type of the second argument typedef _Arg2 second_argument_type; /// @c result_type is the return type typedef _Result result_type; }; /** @} */ // 20.3.2 arithmetic /** @defgroup arithmetic_functors Arithmetic Classes * @ingroup functors * * Because basic math often needs to be done during an algorithm, * the library provides functors for those operations. See the * documentation for @link functors the base classes@endlink * for examples of their use. * * @{ */ #if __cplusplus > 201103L struct __is_transparent; // undefined template struct plus; template struct minus; template struct multiplies; template struct divides; template struct modulus; template struct negate; #endif /// One of the @link arithmetic_functors math functors@endlink. template struct plus : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x + __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct minus : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x - __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct multiplies : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x * __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct divides : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x / __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct modulus : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x % __y; } }; /// One of the @link arithmetic_functors math functors@endlink. template struct negate : public unary_function<_Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x) const { return -__x; } }; #if __cplusplus > 201103L #define __cpp_lib_transparent_operators 201510 template<> struct plus { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) + std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) + std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) + std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct minus { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) - std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) - std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) - std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct multiplies { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) * std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) * std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) * std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct divides { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) / std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) / std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) / std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct modulus { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) % std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) % std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) % std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link arithmetic_functors math functors@endlink. template<> struct negate { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t) const noexcept(noexcept(-std::forward<_Tp>(__t))) -> decltype(-std::forward<_Tp>(__t)) { return -std::forward<_Tp>(__t); } typedef __is_transparent is_transparent; }; #endif /** @} */ // 20.3.3 comparisons /** @defgroup comparison_functors Comparison Classes * @ingroup functors * * The library provides six wrapper functors for all the basic comparisons * in C++, like @c <. * * @{ */ #if __cplusplus > 201103L template struct equal_to; template struct not_equal_to; template struct greater; template struct less; template struct greater_equal; template struct less_equal; #endif /// One of the @link comparison_functors comparison functors@endlink. template struct equal_to : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct not_equal_to : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x != __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct greater : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct less : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct greater_equal : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x >= __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template struct less_equal : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x <= __y; } }; // Partial specialization of std::greater for pointers. template struct greater<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x > __y)) return __x > __y; return (__UINTPTR_TYPE__)__x > (__UINTPTR_TYPE__)__y; } }; // Partial specialization of std::less for pointers. template struct less<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x < __y)) return __x < __y; return (__UINTPTR_TYPE__)__x < (__UINTPTR_TYPE__)__y; } }; // Partial specialization of std::greater_equal for pointers. template struct greater_equal<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x >= __y)) return __x >= __y; return (__UINTPTR_TYPE__)__x >= (__UINTPTR_TYPE__)__y; } }; // Partial specialization of std::less_equal for pointers. template struct less_equal<_Tp*> : public binary_function<_Tp*, _Tp*, bool> { _GLIBCXX14_CONSTEXPR bool operator()(_Tp* __x, _Tp* __y) const _GLIBCXX_NOTHROW { if (__builtin_constant_p (__x <= __y)) return __x <= __y; return (__UINTPTR_TYPE__)__x <= (__UINTPTR_TYPE__)__y; } }; #if __cplusplus >= 201402L /// One of the @link comparison_functors comparison functors@endlink. template<> struct equal_to { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) == std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) == std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) == std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct not_equal_to { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) != std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) != std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) != std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct greater { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) > std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) > std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return greater>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) > std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return greater{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator> member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator>(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator>(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator> for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator>(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator>(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct less { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) < std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) < std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return less>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) < std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return less{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator< member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator<(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator<(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator< for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator<(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator<(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct greater_equal { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) >= std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) >= std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return greater_equal>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) >= std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return greater_equal{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator>= member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator>=(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator>=(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator>= for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator>=(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator>=(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; /// One of the @link comparison_functors comparison functors@endlink. template<> struct less_equal { template constexpr auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) <= std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) <= std::forward<_Up>(__u)) { return _S_cmp(std::forward<_Tp>(__t), std::forward<_Up>(__u), __ptr_cmp<_Tp, _Up>{}); } template constexpr bool operator()(_Tp* __t, _Up* __u) const noexcept { return less_equal>{}(__t, __u); } typedef __is_transparent is_transparent; private: template static constexpr decltype(auto) _S_cmp(_Tp&& __t, _Up&& __u, false_type) { return std::forward<_Tp>(__t) <= std::forward<_Up>(__u); } template static constexpr bool _S_cmp(_Tp&& __t, _Up&& __u, true_type) noexcept { return less_equal{}( static_cast(std::forward<_Tp>(__t)), static_cast(std::forward<_Up>(__u))); } // True if there is no viable operator<= member function. template struct __not_overloaded2 : true_type { }; // False if we can call T.operator<=(U) template struct __not_overloaded2<_Tp, _Up, __void_t< decltype(std::declval<_Tp>().operator<=(std::declval<_Up>()))>> : false_type { }; // True if there is no overloaded operator<= for these operands. template struct __not_overloaded : __not_overloaded2<_Tp, _Up> { }; // False if we can call operator<=(T,U) template struct __not_overloaded<_Tp, _Up, __void_t< decltype(operator<=(std::declval<_Tp>(), std::declval<_Up>()))>> : false_type { }; template using __ptr_cmp = __and_<__not_overloaded<_Tp, _Up>, is_convertible<_Tp, const volatile void*>, is_convertible<_Up, const volatile void*>>; }; #endif // C++14 /** @} */ // 20.3.4 logical operations /** @defgroup logical_functors Boolean Operations Classes * @ingroup functors * * Here are wrapper functors for Boolean operations: @c &&, @c ||, * and @c !. * * @{ */ #if __cplusplus > 201103L template struct logical_and; template struct logical_or; template struct logical_not; #endif /// One of the @link logical_functors Boolean operations functors@endlink. template struct logical_and : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x && __y; } }; /// One of the @link logical_functors Boolean operations functors@endlink. template struct logical_or : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x || __y; } }; /// One of the @link logical_functors Boolean operations functors@endlink. template struct logical_not : public unary_function<_Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x) const { return !__x; } }; #if __cplusplus > 201103L /// One of the @link logical_functors Boolean operations functors@endlink. template<> struct logical_and { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) && std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) && std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) && std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link logical_functors Boolean operations functors@endlink. template<> struct logical_or { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) || std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) || std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) || std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; /// One of the @link logical_functors Boolean operations functors@endlink. template<> struct logical_not { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t) const noexcept(noexcept(!std::forward<_Tp>(__t))) -> decltype(!std::forward<_Tp>(__t)) { return !std::forward<_Tp>(__t); } typedef __is_transparent is_transparent; }; #endif /** @} */ #if __cplusplus > 201103L template struct bit_and; template struct bit_or; template struct bit_xor; template struct bit_not; #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 660. Missing Bitwise Operations. template struct bit_and : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x & __y; } }; template struct bit_or : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x | __y; } }; template struct bit_xor : public binary_function<_Tp, _Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x, const _Tp& __y) const { return __x ^ __y; } }; template struct bit_not : public unary_function<_Tp, _Tp> { _GLIBCXX14_CONSTEXPR _Tp operator()(const _Tp& __x) const { return ~__x; } }; #if __cplusplus > 201103L template <> struct bit_and { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) & std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) & std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) & std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; template <> struct bit_or { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) | std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) | std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) | std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; template <> struct bit_xor { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t, _Up&& __u) const noexcept(noexcept(std::forward<_Tp>(__t) ^ std::forward<_Up>(__u))) -> decltype(std::forward<_Tp>(__t) ^ std::forward<_Up>(__u)) { return std::forward<_Tp>(__t) ^ std::forward<_Up>(__u); } typedef __is_transparent is_transparent; }; template <> struct bit_not { template _GLIBCXX14_CONSTEXPR auto operator()(_Tp&& __t) const noexcept(noexcept(~std::forward<_Tp>(__t))) -> decltype(~std::forward<_Tp>(__t)) { return ~std::forward<_Tp>(__t); } typedef __is_transparent is_transparent; }; #endif // 20.3.5 negators /** @defgroup negators Negators * @ingroup functors * * The functions @c not1 and @c not2 each take a predicate functor * and return an instance of @c unary_negate or * @c binary_negate, respectively. These classes are functors whose * @c operator() performs the stored predicate function and then returns * the negation of the result. * * For example, given a vector of integers and a trivial predicate, * \code * struct IntGreaterThanThree * : public std::unary_function * { * bool operator() (int x) { return x > 3; } * }; * * std::find_if (v.begin(), v.end(), not1(IntGreaterThanThree())); * \endcode * The call to @c find_if will locate the first index (i) of @c v for which * !(v[i] > 3) is true. * * The not1/unary_negate combination works on predicates taking a single * argument. The not2/binary_negate combination works on predicates which * take two arguments. * * @{ */ /// One of the @link negators negation functors@endlink. template class unary_negate : public unary_function { protected: _Predicate _M_pred; public: _GLIBCXX14_CONSTEXPR explicit unary_negate(const _Predicate& __x) : _M_pred(__x) { } _GLIBCXX14_CONSTEXPR bool operator()(const typename _Predicate::argument_type& __x) const { return !_M_pred(__x); } }; /// One of the @link negators negation functors@endlink. template _GLIBCXX14_CONSTEXPR inline unary_negate<_Predicate> not1(const _Predicate& __pred) { return unary_negate<_Predicate>(__pred); } /// One of the @link negators negation functors@endlink. template class binary_negate : public binary_function { protected: _Predicate _M_pred; public: _GLIBCXX14_CONSTEXPR explicit binary_negate(const _Predicate& __x) : _M_pred(__x) { } _GLIBCXX14_CONSTEXPR bool operator()(const typename _Predicate::first_argument_type& __x, const typename _Predicate::second_argument_type& __y) const { return !_M_pred(__x, __y); } }; /// One of the @link negators negation functors@endlink. template _GLIBCXX14_CONSTEXPR inline binary_negate<_Predicate> not2(const _Predicate& __pred) { return binary_negate<_Predicate>(__pred); } /** @} */ // 20.3.7 adaptors pointers functions /** @defgroup pointer_adaptors Adaptors for pointers to functions * @ingroup functors * * The advantage of function objects over pointers to functions is that * the objects in the standard library declare nested typedefs describing * their argument and result types with uniform names (e.g., @c result_type * from the base classes @c unary_function and @c binary_function). * Sometimes those typedefs are required, not just optional. * * Adaptors are provided to turn pointers to unary (single-argument) and * binary (double-argument) functions into function objects. The * long-winded functor @c pointer_to_unary_function is constructed with a * function pointer @c f, and its @c operator() called with argument @c x * returns @c f(x). The functor @c pointer_to_binary_function does the same * thing, but with a double-argument @c f and @c operator(). * * The function @c ptr_fun takes a pointer-to-function @c f and constructs * an instance of the appropriate functor. * * @{ */ /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template class pointer_to_unary_function : public unary_function<_Arg, _Result> { protected: _Result (*_M_ptr)(_Arg); public: pointer_to_unary_function() { } explicit pointer_to_unary_function(_Result (*__x)(_Arg)) : _M_ptr(__x) { } _Result operator()(_Arg __x) const { return _M_ptr(__x); } }; /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template inline pointer_to_unary_function<_Arg, _Result> ptr_fun(_Result (*__x)(_Arg)) { return pointer_to_unary_function<_Arg, _Result>(__x); } /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template class pointer_to_binary_function : public binary_function<_Arg1, _Arg2, _Result> { protected: _Result (*_M_ptr)(_Arg1, _Arg2); public: pointer_to_binary_function() { } explicit pointer_to_binary_function(_Result (*__x)(_Arg1, _Arg2)) : _M_ptr(__x) { } _Result operator()(_Arg1 __x, _Arg2 __y) const { return _M_ptr(__x, __y); } }; /// One of the @link pointer_adaptors adaptors for function pointers@endlink. template inline pointer_to_binary_function<_Arg1, _Arg2, _Result> ptr_fun(_Result (*__x)(_Arg1, _Arg2)) { return pointer_to_binary_function<_Arg1, _Arg2, _Result>(__x); } /** @} */ template struct _Identity : public unary_function<_Tp, _Tp> { _Tp& operator()(_Tp& __x) const { return __x; } const _Tp& operator()(const _Tp& __x) const { return __x; } }; // Partial specialization, avoids confusing errors in e.g. std::set. template struct _Identity : _Identity<_Tp> { }; template struct _Select1st : public unary_function<_Pair, typename _Pair::first_type> { typename _Pair::first_type& operator()(_Pair& __x) const { return __x.first; } const typename _Pair::first_type& operator()(const _Pair& __x) const { return __x.first; } #if __cplusplus >= 201103L template typename _Pair2::first_type& operator()(_Pair2& __x) const { return __x.first; } template const typename _Pair2::first_type& operator()(const _Pair2& __x) const { return __x.first; } #endif }; template struct _Select2nd : public unary_function<_Pair, typename _Pair::second_type> { typename _Pair::second_type& operator()(_Pair& __x) const { return __x.second; } const typename _Pair::second_type& operator()(const _Pair& __x) const { return __x.second; } }; // 20.3.8 adaptors pointers members /** @defgroup memory_adaptors Adaptors for pointers to members * @ingroup functors * * There are a total of 8 = 2^3 function objects in this family. * (1) Member functions taking no arguments vs member functions taking * one argument. * (2) Call through pointer vs call through reference. * (3) Const vs non-const member function. * * All of this complexity is in the function objects themselves. You can * ignore it by using the helper function mem_fun and mem_fun_ref, * which create whichever type of adaptor is appropriate. * * @{ */ /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun_t : public unary_function<_Tp*, _Ret> { public: explicit mem_fun_t(_Ret (_Tp::*__pf)()) : _M_f(__pf) { } _Ret operator()(_Tp* __p) const { return (__p->*_M_f)(); } private: _Ret (_Tp::*_M_f)(); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun_t : public unary_function { public: explicit const_mem_fun_t(_Ret (_Tp::*__pf)() const) : _M_f(__pf) { } _Ret operator()(const _Tp* __p) const { return (__p->*_M_f)(); } private: _Ret (_Tp::*_M_f)() const; }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun_ref_t : public unary_function<_Tp, _Ret> { public: explicit mem_fun_ref_t(_Ret (_Tp::*__pf)()) : _M_f(__pf) { } _Ret operator()(_Tp& __r) const { return (__r.*_M_f)(); } private: _Ret (_Tp::*_M_f)(); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun_ref_t : public unary_function<_Tp, _Ret> { public: explicit const_mem_fun_ref_t(_Ret (_Tp::*__pf)() const) : _M_f(__pf) { } _Ret operator()(const _Tp& __r) const { return (__r.*_M_f)(); } private: _Ret (_Tp::*_M_f)() const; }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun1_t : public binary_function<_Tp*, _Arg, _Ret> { public: explicit mem_fun1_t(_Ret (_Tp::*__pf)(_Arg)) : _M_f(__pf) { } _Ret operator()(_Tp* __p, _Arg __x) const { return (__p->*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun1_t : public binary_function { public: explicit const_mem_fun1_t(_Ret (_Tp::*__pf)(_Arg) const) : _M_f(__pf) { } _Ret operator()(const _Tp* __p, _Arg __x) const { return (__p->*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg) const; }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class mem_fun1_ref_t : public binary_function<_Tp, _Arg, _Ret> { public: explicit mem_fun1_ref_t(_Ret (_Tp::*__pf)(_Arg)) : _M_f(__pf) { } _Ret operator()(_Tp& __r, _Arg __x) const { return (__r.*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg); }; /// One of the @link memory_adaptors adaptors for member /// pointers@endlink. template class const_mem_fun1_ref_t : public binary_function<_Tp, _Arg, _Ret> { public: explicit const_mem_fun1_ref_t(_Ret (_Tp::*__pf)(_Arg) const) : _M_f(__pf) { } _Ret operator()(const _Tp& __r, _Arg __x) const { return (__r.*_M_f)(__x); } private: _Ret (_Tp::*_M_f)(_Arg) const; }; // Mem_fun adaptor helper functions. There are only two: // mem_fun and mem_fun_ref. template inline mem_fun_t<_Ret, _Tp> mem_fun(_Ret (_Tp::*__f)()) { return mem_fun_t<_Ret, _Tp>(__f); } template inline const_mem_fun_t<_Ret, _Tp> mem_fun(_Ret (_Tp::*__f)() const) { return const_mem_fun_t<_Ret, _Tp>(__f); } template inline mem_fun_ref_t<_Ret, _Tp> mem_fun_ref(_Ret (_Tp::*__f)()) { return mem_fun_ref_t<_Ret, _Tp>(__f); } template inline const_mem_fun_ref_t<_Ret, _Tp> mem_fun_ref(_Ret (_Tp::*__f)() const) { return const_mem_fun_ref_t<_Ret, _Tp>(__f); } template inline mem_fun1_t<_Ret, _Tp, _Arg> mem_fun(_Ret (_Tp::*__f)(_Arg)) { return mem_fun1_t<_Ret, _Tp, _Arg>(__f); } template inline const_mem_fun1_t<_Ret, _Tp, _Arg> mem_fun(_Ret (_Tp::*__f)(_Arg) const) { return const_mem_fun1_t<_Ret, _Tp, _Arg>(__f); } template inline mem_fun1_ref_t<_Ret, _Tp, _Arg> mem_fun_ref(_Ret (_Tp::*__f)(_Arg)) { return mem_fun1_ref_t<_Ret, _Tp, _Arg>(__f); } template inline const_mem_fun1_ref_t<_Ret, _Tp, _Arg> mem_fun_ref(_Ret (_Tp::*__f)(_Arg) const) { return const_mem_fun1_ref_t<_Ret, _Tp, _Arg>(__f); } /** @} */ _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if (__cplusplus < 201103L) || _GLIBCXX_USE_DEPRECATED # include #endif #endif /* _STL_FUNCTION_H */ c++/8/bits/uses_allocator.h000064400000014575151027430570011434 0ustar00// Uses-allocator Construction -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . #ifndef _USES_ALLOCATOR_H #define _USES_ALLOCATOR_H 1 #if __cplusplus < 201103L # include #else #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION struct __erased_type { }; template using __is_erased_or_convertible = __or_, is_convertible<_Alloc, _Tp>>; /// [allocator.tag] struct allocator_arg_t { explicit allocator_arg_t() = default; }; _GLIBCXX17_INLINE constexpr allocator_arg_t allocator_arg = allocator_arg_t(); template> struct __uses_allocator_helper : false_type { }; template struct __uses_allocator_helper<_Tp, _Alloc, __void_t> : __is_erased_or_convertible<_Alloc, typename _Tp::allocator_type>::type { }; /// [allocator.uses.trait] template struct uses_allocator : __uses_allocator_helper<_Tp, _Alloc>::type { }; struct __uses_alloc_base { }; struct __uses_alloc0 : __uses_alloc_base { struct _Sink { void operator=(const void*) { } } _M_a; }; template struct __uses_alloc1 : __uses_alloc_base { const _Alloc* _M_a; }; template struct __uses_alloc2 : __uses_alloc_base { const _Alloc* _M_a; }; template struct __uses_alloc; template struct __uses_alloc : conditional< is_constructible<_Tp, allocator_arg_t, const _Alloc&, _Args...>::value, __uses_alloc1<_Alloc>, __uses_alloc2<_Alloc>>::type { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2586. Wrong value category used in scoped_allocator_adaptor::construct static_assert(__or_< is_constructible<_Tp, allocator_arg_t, const _Alloc&, _Args...>, is_constructible<_Tp, _Args..., const _Alloc&>>::value, "construction with an allocator must be possible" " if uses_allocator is true"); }; template struct __uses_alloc : __uses_alloc0 { }; template using __uses_alloc_t = __uses_alloc::value, _Tp, _Alloc, _Args...>; template inline __uses_alloc_t<_Tp, _Alloc, _Args...> __use_alloc(const _Alloc& __a) { __uses_alloc_t<_Tp, _Alloc, _Args...> __ret; __ret._M_a = std::__addressof(__a); return __ret; } template void __use_alloc(const _Alloc&&) = delete; #if __cplusplus > 201402L template inline constexpr bool uses_allocator_v = uses_allocator<_Tp, _Alloc>::value; #endif // C++17 template class _Predicate, typename _Tp, typename _Alloc, typename... _Args> struct __is_uses_allocator_predicate : conditional::value, __or_<_Predicate<_Tp, allocator_arg_t, _Alloc, _Args...>, _Predicate<_Tp, _Args..., _Alloc>>, _Predicate<_Tp, _Args...>>::type { }; template struct __is_uses_allocator_constructible : __is_uses_allocator_predicate { }; #if __cplusplus >= 201402L template _GLIBCXX17_INLINE constexpr bool __is_uses_allocator_constructible_v = __is_uses_allocator_constructible<_Tp, _Alloc, _Args...>::value; #endif // C++14 template struct __is_nothrow_uses_allocator_constructible : __is_uses_allocator_predicate { }; #if __cplusplus >= 201402L template _GLIBCXX17_INLINE constexpr bool __is_nothrow_uses_allocator_constructible_v = __is_nothrow_uses_allocator_constructible<_Tp, _Alloc, _Args...>::value; #endif // C++14 template void __uses_allocator_construct_impl(__uses_alloc0 __a, _Tp* __ptr, _Args&&... __args) { ::new ((void*)__ptr) _Tp(std::forward<_Args>(__args)...); } template void __uses_allocator_construct_impl(__uses_alloc1<_Alloc> __a, _Tp* __ptr, _Args&&... __args) { ::new ((void*)__ptr) _Tp(allocator_arg, *__a._M_a, std::forward<_Args>(__args)...); } template void __uses_allocator_construct_impl(__uses_alloc2<_Alloc> __a, _Tp* __ptr, _Args&&... __args) { ::new ((void*)__ptr) _Tp(std::forward<_Args>(__args)..., *__a._M_a); } template void __uses_allocator_construct(const _Alloc& __a, _Tp* __ptr, _Args&&... __args) { __uses_allocator_construct_impl(__use_alloc<_Tp, _Alloc, _Args...>(__a), __ptr, std::forward<_Args>(__args)...); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif #endif c++/8/condition_variable000064400000021372151027430570011052 0ustar00// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/condition_variable * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_CONDITION_VARIABLE #define _GLIBCXX_CONDITION_VARIABLE 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include #include #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup condition_variables Condition Variables * @ingroup concurrency * * Classes for condition_variable support. * @{ */ /// cv_status enum class cv_status { no_timeout, timeout }; /// condition_variable class condition_variable { typedef chrono::system_clock __clock_t; typedef __gthread_cond_t __native_type; #ifdef __GTHREAD_COND_INIT __native_type _M_cond = __GTHREAD_COND_INIT; #else __native_type _M_cond; #endif public: typedef __native_type* native_handle_type; condition_variable() noexcept; ~condition_variable() noexcept; condition_variable(const condition_variable&) = delete; condition_variable& operator=(const condition_variable&) = delete; void notify_one() noexcept; void notify_all() noexcept; void wait(unique_lock& __lock) noexcept; template void wait(unique_lock& __lock, _Predicate __p) { while (!__p()) wait(__lock); } template cv_status wait_until(unique_lock& __lock, const chrono::time_point<__clock_t, _Duration>& __atime) { return __wait_until_impl(__lock, __atime); } template cv_status wait_until(unique_lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __atime - __c_entry; const auto __s_atime = __s_entry + __delta; return __wait_until_impl(__lock, __s_atime); } template bool wait_until(unique_lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime, _Predicate __p) { while (!__p()) if (wait_until(__lock, __atime) == cv_status::timeout) return __p(); return true; } template cv_status wait_for(unique_lock& __lock, const chrono::duration<_Rep, _Period>& __rtime) { using __dur = typename __clock_t::duration; auto __reltime = chrono::duration_cast<__dur>(__rtime); if (__reltime < __rtime) ++__reltime; return wait_until(__lock, __clock_t::now() + __reltime); } template bool wait_for(unique_lock& __lock, const chrono::duration<_Rep, _Period>& __rtime, _Predicate __p) { using __dur = typename __clock_t::duration; auto __reltime = chrono::duration_cast<__dur>(__rtime); if (__reltime < __rtime) ++__reltime; return wait_until(__lock, __clock_t::now() + __reltime, std::move(__p)); } native_handle_type native_handle() { return &_M_cond; } private: template cv_status __wait_until_impl(unique_lock& __lock, const chrono::time_point<__clock_t, _Dur>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); __gthread_time_t __ts = { static_cast(__s.time_since_epoch().count()), static_cast(__ns.count()) }; __gthread_cond_timedwait(&_M_cond, __lock.mutex()->native_handle(), &__ts); return (__clock_t::now() < __atime ? cv_status::no_timeout : cv_status::timeout); } }; void notify_all_at_thread_exit(condition_variable&, unique_lock); struct __at_thread_exit_elt { __at_thread_exit_elt* _M_next; void (*_M_cb)(void*); }; inline namespace _V2 { /// condition_variable_any // Like above, but mutex is not required to have try_lock. class condition_variable_any { typedef chrono::system_clock __clock_t; condition_variable _M_cond; shared_ptr _M_mutex; // scoped unlock - unlocks in ctor, re-locks in dtor template struct _Unlock { explicit _Unlock(_Lock& __lk) : _M_lock(__lk) { __lk.unlock(); } ~_Unlock() noexcept(false) { if (uncaught_exception()) { __try { _M_lock.lock(); } __catch(const __cxxabiv1::__forced_unwind&) { __throw_exception_again; } __catch(...) { } } else _M_lock.lock(); } _Unlock(const _Unlock&) = delete; _Unlock& operator=(const _Unlock&) = delete; _Lock& _M_lock; }; public: condition_variable_any() : _M_mutex(std::make_shared()) { } ~condition_variable_any() = default; condition_variable_any(const condition_variable_any&) = delete; condition_variable_any& operator=(const condition_variable_any&) = delete; void notify_one() noexcept { lock_guard __lock(*_M_mutex); _M_cond.notify_one(); } void notify_all() noexcept { lock_guard __lock(*_M_mutex); _M_cond.notify_all(); } template void wait(_Lock& __lock) { shared_ptr __mutex = _M_mutex; unique_lock __my_lock(*__mutex); _Unlock<_Lock> __unlock(__lock); // *__mutex must be unlocked before re-locking __lock so move // ownership of *__mutex lock to an object with shorter lifetime. unique_lock __my_lock2(std::move(__my_lock)); _M_cond.wait(__my_lock2); } template void wait(_Lock& __lock, _Predicate __p) { while (!__p()) wait(__lock); } template cv_status wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime) { shared_ptr __mutex = _M_mutex; unique_lock __my_lock(*__mutex); _Unlock<_Lock> __unlock(__lock); // *__mutex must be unlocked before re-locking __lock so move // ownership of *__mutex lock to an object with shorter lifetime. unique_lock __my_lock2(std::move(__my_lock)); return _M_cond.wait_until(__my_lock2, __atime); } template bool wait_until(_Lock& __lock, const chrono::time_point<_Clock, _Duration>& __atime, _Predicate __p) { while (!__p()) if (wait_until(__lock, __atime) == cv_status::timeout) return __p(); return true; } template cv_status wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __rtime) { return wait_until(__lock, __clock_t::now() + __rtime); } template bool wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __rtime, _Predicate __p) { return wait_until(__lock, __clock_t::now() + __rtime, std::move(__p)); } }; } // end inline namespace // @} group condition_variables _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 #endif // _GLIBCXX_CONDITION_VARIABLE c++/8/tr2/dynamic_bitset.tcc000064400000021335151027430570011473 0ustar00// TR2 -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file tr2/dynamic_bitset.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{tr2/dynamic_bitset} */ #ifndef _GLIBCXX_TR2_DYNAMIC_BITSET_TCC #define _GLIBCXX_TR2_DYNAMIC_BITSET_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr2 { // Definitions of non-inline functions from __dynamic_bitset_base. template void __dynamic_bitset_base<_WordT, _Alloc>::_M_do_left_shift(size_t __shift) { if (__builtin_expect(__shift != 0, 1)) { const size_t __wshift = __shift / _S_bits_per_block; const size_t __offset = __shift % _S_bits_per_block; if (__offset == 0) for (size_t __n = this->_M_w.size() - 1; __n >= __wshift; --__n) this->_M_w[__n] = this->_M_w[__n - __wshift]; else { const size_t __sub_offset = _S_bits_per_block - __offset; for (size_t __n = _M_w.size() - 1; __n > __wshift; --__n) this->_M_w[__n] = ((this->_M_w[__n - __wshift] << __offset) | (this->_M_w[__n - __wshift - 1] >> __sub_offset)); this->_M_w[__wshift] = this->_M_w[0] << __offset; } //// std::fill(this->_M_w.begin(), this->_M_w.begin() + __wshift, //// static_cast<_WordT>(0)); } } template void __dynamic_bitset_base<_WordT, _Alloc>::_M_do_right_shift(size_t __shift) { if (__builtin_expect(__shift != 0, 1)) { const size_t __wshift = __shift / _S_bits_per_block; const size_t __offset = __shift % _S_bits_per_block; const size_t __limit = this->_M_w.size() - __wshift - 1; if (__offset == 0) for (size_t __n = 0; __n <= __limit; ++__n) this->_M_w[__n] = this->_M_w[__n + __wshift]; else { const size_t __sub_offset = (_S_bits_per_block - __offset); for (size_t __n = 0; __n < __limit; ++__n) this->_M_w[__n] = ((this->_M_w[__n + __wshift] >> __offset) | (this->_M_w[__n + __wshift + 1] << __sub_offset)); this->_M_w[__limit] = this->_M_w[_M_w.size()-1] >> __offset; } ////std::fill(this->_M_w.begin() + __limit + 1, this->_M_w.end(), //// static_cast<_WordT>(0)); } } template unsigned long __dynamic_bitset_base<_WordT, _Alloc>::_M_do_to_ulong() const { size_t __n = sizeof(unsigned long) / sizeof(block_type); for (size_t __i = __n; __i < this->_M_w.size(); ++__i) if (this->_M_w[__i]) __throw_overflow_error(__N("__dynamic_bitset_base::_M_do_to_ulong")); unsigned long __res = 0UL; for (size_t __i = 0; __i < __n && __i < this->_M_w.size(); ++__i) __res += this->_M_w[__i] << (__i * _S_bits_per_block); return __res; } template unsigned long long __dynamic_bitset_base<_WordT, _Alloc>::_M_do_to_ullong() const { size_t __n = sizeof(unsigned long long) / sizeof(block_type); for (size_t __i = __n; __i < this->_M_w.size(); ++__i) if (this->_M_w[__i]) __throw_overflow_error(__N("__dynamic_bitset_base::_M_do_to_ullong")); unsigned long long __res = 0ULL; for (size_t __i = 0; __i < __n && __i < this->_M_w.size(); ++__i) __res += this->_M_w[__i] << (__i * _S_bits_per_block); return __res; } template size_t __dynamic_bitset_base<_WordT, _Alloc> ::_M_do_find_first(size_t __not_found) const { for (size_t __i = 0; __i < this->_M_w.size(); ++__i) { _WordT __thisword = this->_M_w[__i]; if (__thisword != static_cast<_WordT>(0)) return (__i * _S_bits_per_block + __builtin_ctzll(__thisword)); } // not found, so return an indication of failure. return __not_found; } template size_t __dynamic_bitset_base<_WordT, _Alloc> ::_M_do_find_next(size_t __prev, size_t __not_found) const { // make bound inclusive ++__prev; // check out of bounds if (__prev >= this->_M_w.size() * _S_bits_per_block) return __not_found; // search first word size_t __i = _S_whichword(__prev); _WordT __thisword = this->_M_w[__i]; // mask off bits below bound __thisword &= (~static_cast<_WordT>(0)) << _S_whichbit(__prev); if (__thisword != static_cast<_WordT>(0)) return (__i * _S_bits_per_block + __builtin_ctzll(__thisword)); // check subsequent words for (++__i; __i < this->_M_w.size(); ++__i) { __thisword = this->_M_w[__i]; if (__thisword != static_cast<_WordT>(0)) return (__i * _S_bits_per_block + __builtin_ctzll(__thisword)); } // not found, so return an indication of failure. return __not_found; } // end _M_do_find_next // Definitions of non-inline member functions. template template void dynamic_bitset<_WordT, _Alloc>:: _M_copy_from_ptr(const _CharT* __str, size_t __len, size_t __pos, size_t __n, _CharT __zero, _CharT __one) { reset(); const size_t __nbits = std::min(_M_Nb, std::min(__n, __len - __pos)); for (size_t __i = __nbits; __i > 0; --__i) { const _CharT __c = __str[__pos + __nbits - __i]; if (_Traits::eq(__c, __zero)) ; else if (_Traits::eq(__c, __one)) _M_unchecked_set(__i - 1); else __throw_invalid_argument(__N("dynamic_bitset::_M_copy_from_ptr")); } } /** * @brief Stream input operator for dynamic_bitset. * @ingroup dynamic_bitset * * Input will skip whitespace and only accept '0' and '1' characters. * The %dynamic_bitset will grow as necessary to hold the string of bits. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, dynamic_bitset<_WordT, _Alloc>& __x) { typedef typename _Traits::char_type char_type; typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; std::basic_string<_CharT, _Traits> __tmp; __tmp.reserve(__x.size()); const char_type __zero = __is.widen('0'); const char_type __one = __is.widen('1'); typename __ios_base::iostate __state = __ios_base::goodbit; typename __istream_type::sentry __sentry(__is); if (__sentry) { __try { while (1) { static typename _Traits::int_type __eof = _Traits::eof(); typename _Traits::int_type __c1 = __is.rdbuf()->sbumpc(); if (_Traits::eq_int_type(__c1, __eof)) { __state |= __ios_base::eofbit; break; } else { const char_type __c2 = _Traits::to_char_type(__c1); if (_Traits::eq(__c2, __zero)) __tmp.push_back(__zero); else if (_Traits::eq(__c2, __one)) __tmp.push_back(__one); else if (_Traits:: eq_int_type(__is.rdbuf()->sputbackc(__c2), __eof)) { __state |= __ios_base::failbit; break; } else break; } } } __catch(__cxxabiv1::__forced_unwind&) { __is._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { __is._M_setstate(__ios_base::badbit); } } __x.resize(__tmp.size()); if (__tmp.empty() && __x.size()) __state |= __ios_base::failbit; else __x._M_copy_from_string(__tmp, static_cast(0), __x.size(), __zero, __one); if (__state) __is.setstate(__state); return __is; } } // tr2 _GLIBCXX_END_NAMESPACE_VERSION } // std #endif /* _GLIBCXX_TR2_DYNAMIC_BITSET_TCC */ c++/8/tr2/type_traits000064400000005213151027430570010271 0ustar00// TR2 -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file tr2/type_traits * This is a TR2 C++ Library header. */ #ifndef _GLIBCXX_TR2_TYPE_TRAITS #define _GLIBCXX_TR2_TYPE_TRAITS 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr2 { /** * @addtogroup metaprogramming * @{ */ /** * See N2965: Type traits and base classes * by Michael Spertus */ /** * Simple typelist. Compile-time list of types. */ template struct __reflection_typelist; /// Specialization for an empty typelist. template<> struct __reflection_typelist<> { typedef std::true_type empty; }; /// Partial specialization. template struct __reflection_typelist<_First, _Rest...> { typedef std::false_type empty; struct first { typedef _First type; }; struct rest { typedef __reflection_typelist<_Rest...> type; }; }; /// Sequence abstraction metafunctions for manipulating a typelist. /// Enumerate all the base classes of a class. Form of a typelist. template struct bases { typedef __reflection_typelist<__bases(_Tp)...> type; }; /// Enumerate all the direct base classes of a class. Form of a typelist. template struct direct_bases { typedef __reflection_typelist<__direct_bases(_Tp)...> type; }; /// @} group metaprogramming } _GLIBCXX_END_NAMESPACE_VERSION } #endif // _GLIBCXX_TR2_TYPE_TRAITS c++/8/tr2/ratio000064400000004122151027430570007036 0ustar00// TR2 -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file tr2/ratio * This is a TR2 C++ Library header. */ #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr2 { template (std::numeric_limits::digits)> struct __safe_lshift { static const intmax_t __value = 0; }; template struct __safe_lshift<_Pn, _Bit, true> { static const intmax_t __value = _Pn << _Bit; }; /// Add binary prefixes (IEC 60027-2 A.2 and ISO/IEC 80000). typedef ratio<__safe_lshift<1, 10>::__value, 1> kibi; typedef ratio<__safe_lshift<1, 20>::__value, 1> mebi; typedef ratio<__safe_lshift<1, 30>::__value, 1> gibi; typedef ratio<__safe_lshift<1, 40>::__value, 1> tebi; typedef ratio<__safe_lshift<1, 50>::__value, 1> pebi; typedef ratio<__safe_lshift<1, 60>::__value, 1> exbi; //typedef ratio<__safe_lshift<1, 70>::__value, 1> zebi; //typedef ratio<__safe_lshift<1, 80>::__value, 1> yobi; } _GLIBCXX_END_NAMESPACE_VERSION } c++/8/tr2/bool_set000064400000016312151027430570007532 0ustar00// TR2 -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file tr2/bool_set * This is a TR2 C++ Library header. */ #ifndef _GLIBCXX_TR2_BOOL_SET #define _GLIBCXX_TR2_BOOL_SET 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr2 { /** * bool_set * * See N2136, Bool_set: multi-valued logic * by Hervé Brönnimann, Guillaume Melquiond, Sylvain Pion. * * The implicit conversion to bool is slippery! I may use the new * explicit conversion. This has been specialized in the language * so that in contexts requiring a bool the conversion happens * implicitly. Thus most objections should be eliminated. */ class bool_set { public: /// Default constructor. constexpr bool_set() : _M_b(_S_false) { } /// Constructor from bool. constexpr bool_set(bool __t) : _M_b(_Bool_set_val(__t)) { } // I'm not sure about this. bool contains(bool_set __b) const { return this->is_singleton() && this->equals(__b); } /// Return true if states are equal. bool equals(bool_set __b) const { return __b._M_b == _M_b; } /// Return true if this is empty. bool is_emptyset() const { return _M_b == _S_empty; } /// Return true if this is indeterminate. bool is_indeterminate() const { return _M_b == _S_indet; } /// Return true if this is false or true (normal boolean). bool is_singleton() const { return _M_b == _S_false || _M_b == _S_true_; } /// Conversion to bool. //explicit operator bool() const { if (! is_singleton()) throw std::bad_cast(); return _M_b; } /// static bool_set indeterminate() { bool_set __b; __b._M_b = _S_indet; return __b; } /// static bool_set emptyset() { bool_set __b; __b._M_b = _S_empty; return __b; } friend bool_set operator!(bool_set __b) { return __b._M_not(); } friend bool_set operator^(bool_set __s, bool_set __t) { return __s._M_xor(__t); } friend bool_set operator|(bool_set __s, bool_set __t) { return __s._M_or(__t); } friend bool_set operator&(bool_set __s, bool_set __t) { return __s._M_and(__t); } friend bool_set operator==(bool_set __s, bool_set __t) { return __s._M_eq(__t); } // These overloads replace the facet additions in the paper! template friend std::basic_ostream& operator<<(std::basic_ostream& __out, bool_set __b) { int __a = __b._M_b; __out << __a; } template friend std::basic_istream& operator>>(std::basic_istream& __in, bool_set& __b) { long __c; __in >> __c; if (__c >= _S_false && __c < _S_empty) __b._M_b = static_cast<_Bool_set_val>(__c); } private: /// enum _Bool_set_val: unsigned char { _S_false = 0, _S_true_ = 1, _S_indet = 2, _S_empty = 3 }; /// Bool set state. _Bool_set_val _M_b; /// bool_set(_Bool_set_val __c) : _M_b(__c) { } /// bool_set _M_not() const { return _S_not[this->_M_b]; } /// bool_set _M_xor(bool_set __b) const { return _S_xor[this->_M_b][__b._M_b]; } /// bool_set _M_or(bool_set __b) const { return _S_or[this->_M_b][__b._M_b]; } /// bool_set _M_and(bool_set __b) const { return _S_and[this->_M_b][__b._M_b]; } /// bool_set _M_eq(bool_set __b) const { return _S_eq[this->_M_b][__b._M_b]; } /// static _Bool_set_val _S_not[4]; /// static _Bool_set_val _S_xor[4][4]; /// static _Bool_set_val _S_or[4][4]; /// static _Bool_set_val _S_and[4][4]; /// static _Bool_set_val _S_eq[4][4]; }; // 20.2.3.2 bool_set values inline bool contains(bool_set __s, bool_set __t) { return __s.contains(__t); } inline bool equals(bool_set __s, bool_set __t) { return __s.equals(__t); } inline bool is_emptyset(bool_set __b) { return __b.is_emptyset(); } inline bool is_indeterminate(bool_set __b) { return __b.is_indeterminate(); } inline bool is_singleton(bool_set __b) { return __b.is_singleton(); } inline bool certainly(bool_set __b) { return ! __b.contains(false); } inline bool possibly(bool_set __b) { return __b.contains(true); } // 20.2.3.3 bool_set set operations inline bool_set set_union(bool __s, bool_set __t) { return bool_set(__s) | __t; } inline bool_set set_union(bool_set __s, bool __t) { return __s | bool_set(__t); } inline bool_set set_union(bool_set __s, bool_set __t) { return __s | __t; } inline bool_set set_intersection(bool __s, bool_set __t) { return bool_set(__s) & __t; } inline bool_set set_intersection(bool_set __s, bool __t) { return __s & bool_set(__t); } inline bool_set set_intersection(bool_set __s, bool_set __t) { return __s & __t; } inline bool_set set_complement(bool_set __b) { return ! __b; } // 20.2.3.4 bool_set logical operators inline bool_set operator^(bool __s, bool_set __t) { return bool_set(__s) ^ __t; } inline bool_set operator^(bool_set __s, bool __t) { return __s ^ bool_set(__t); } inline bool_set operator|(bool __s, bool_set __t) { return bool_set(__s) | __t; } inline bool_set operator|(bool_set __s, bool __t) { return __s | bool_set(__t); } inline bool_set operator&(bool __s, bool_set __t) { return bool_set(__s) & __t; } inline bool_set operator&(bool_set __s, bool __t) { return __s & bool_set(__t); } // 20.2.3.5 bool_set relational operators inline bool_set operator==(bool __s, bool_set __t) { return bool_set(__s) == __t; } inline bool_set operator==(bool_set __s, bool __t) { return __s == bool_set(__t); } inline bool_set operator!=(bool __s, bool_set __t) { return ! (__s == __t); } inline bool_set operator!=(bool_set __s, bool __t) { return ! (__s == __t); } inline bool_set operator!=(bool_set __s, bool_set __t) { return ! (__s == __t); } } _GLIBCXX_END_NAMESPACE_VERSION } #include #endif // _GLIBCXX_TR2_BOOL_SET c++/8/tr2/dynamic_bitset000064400000103023151027430570010716 0ustar00// TR2 -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file tr2/dynamic_bitset * This is a TR2 C++ Library header. */ #ifndef _GLIBCXX_TR2_DYNAMIC_BITSET #define _GLIBCXX_TR2_DYNAMIC_BITSET 1 #pragma GCC system_header #include #include #include #include #include #include // For fill #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr2 { /** * @defgroup dynamic_bitset Dynamic Bitset. * @ingroup extensions * * @{ */ /** * Base class, general case. * * See documentation for dynamic_bitset. */ template> struct __dynamic_bitset_base { static_assert(std::is_unsigned<_WordT>::value, "template argument " "_WordT not an unsigned integral type"); typedef _WordT block_type; typedef _Alloc allocator_type; typedef size_t size_type; static const size_type _S_bits_per_block = __CHAR_BIT__ * sizeof(block_type); static const size_type npos = static_cast(-1); /// 0 is the least significant word. std::vector _M_w; explicit __dynamic_bitset_base(const allocator_type& __alloc) : _M_w(__alloc) { } __dynamic_bitset_base() = default; __dynamic_bitset_base(const __dynamic_bitset_base&) = default; __dynamic_bitset_base(__dynamic_bitset_base&& __b) = default; __dynamic_bitset_base& operator=(const __dynamic_bitset_base&) = default; __dynamic_bitset_base& operator=(__dynamic_bitset_base&&) = default; ~__dynamic_bitset_base() = default; explicit __dynamic_bitset_base(size_type __nbits, unsigned long long __val = 0ULL, const allocator_type& __alloc = allocator_type()) : _M_w(__nbits / _S_bits_per_block + (__nbits % _S_bits_per_block > 0), block_type(0), __alloc) { if (__nbits < std::numeric_limits::digits) __val &= ~(-1ULL << __nbits); if (__val == 0) return; if _GLIBCXX17_CONSTEXPR (sizeof(__val) == sizeof(block_type)) _M_w[0] = __val; else { const size_t __n = std::min(_M_w.size(), sizeof(__val) / sizeof(block_type)); for (size_t __i = 0; __val && __i < __n; ++__i) { _M_w[__i] = static_cast(__val); __val >>= _S_bits_per_block; } } } void _M_swap(__dynamic_bitset_base& __b) noexcept { this->_M_w.swap(__b._M_w); } void _M_clear() noexcept { this->_M_w.clear(); } void _M_resize(size_t __nbits, bool __value) { size_t __sz = __nbits / _S_bits_per_block; if (__nbits % _S_bits_per_block > 0) ++__sz; if (__sz != this->_M_w.size()) { block_type __val = 0; if (__value) __val = std::numeric_limits::max(); this->_M_w.resize(__sz, __val); } } allocator_type _M_get_allocator() const noexcept { return this->_M_w.get_allocator(); } static size_type _S_whichword(size_type __pos) noexcept { return __pos / _S_bits_per_block; } static size_type _S_whichbyte(size_type __pos) noexcept { return (__pos % _S_bits_per_block) / __CHAR_BIT__; } static size_type _S_whichbit(size_type __pos) noexcept { return __pos % _S_bits_per_block; } static block_type _S_maskbit(size_type __pos) noexcept { return (static_cast(1)) << _S_whichbit(__pos); } block_type& _M_getword(size_type __pos) noexcept { return this->_M_w[_S_whichword(__pos)]; } block_type _M_getword(size_type __pos) const noexcept { return this->_M_w[_S_whichword(__pos)]; } block_type& _M_hiword() noexcept { return this->_M_w[_M_w.size() - 1]; } block_type _M_hiword() const noexcept { return this->_M_w[_M_w.size() - 1]; } void _M_do_and(const __dynamic_bitset_base& __x) noexcept { if (__x._M_w.size() == this->_M_w.size()) for (size_t __i = 0; __i < this->_M_w.size(); ++__i) this->_M_w[__i] &= __x._M_w[__i]; else return; } void _M_do_or(const __dynamic_bitset_base& __x) noexcept { if (__x._M_w.size() == this->_M_w.size()) for (size_t __i = 0; __i < this->_M_w.size(); ++__i) this->_M_w[__i] |= __x._M_w[__i]; else return; } void _M_do_xor(const __dynamic_bitset_base& __x) noexcept { if (__x._M_w.size() == this->_M_w.size()) for (size_t __i = 0; __i < this->_M_w.size(); ++__i) this->_M_w[__i] ^= __x._M_w[__i]; else return; } void _M_do_dif(const __dynamic_bitset_base& __x) noexcept { if (__x._M_w.size() == this->_M_w.size()) for (size_t __i = 0; __i < this->_M_w.size(); ++__i) this->_M_w[__i] &= ~__x._M_w[__i]; else return; } void _M_do_left_shift(size_t __shift); void _M_do_right_shift(size_t __shift); void _M_do_flip() noexcept { for (size_t __i = 0; __i < this->_M_w.size(); ++__i) this->_M_w[__i] = ~this->_M_w[__i]; } void _M_do_set() noexcept { for (size_t __i = 0; __i < this->_M_w.size(); ++__i) this->_M_w[__i] = static_cast(-1); } void _M_do_reset() noexcept { std::fill(_M_w.begin(), _M_w.end(), static_cast(0)); } bool _M_is_equal(const __dynamic_bitset_base& __x) const noexcept { if (__x._M_w.size() == this->_M_w.size()) { for (size_t __i = 0; __i < this->_M_w.size(); ++__i) if (this->_M_w[__i] != __x._M_w[__i]) return false; return true; } else return false; } bool _M_is_less(const __dynamic_bitset_base& __x) const noexcept { if (__x._M_w.size() == this->_M_w.size()) { for (size_t __i = this->_M_w.size(); __i > 0; --__i) { if (this->_M_w[__i-1] < __x._M_w[__i-1]) return true; else if (this->_M_w[__i-1] > __x._M_w[__i-1]) return false; } return false; } else return false; } size_t _M_are_all_aux() const noexcept { for (size_t __i = 0; __i < this->_M_w.size() - 1; ++__i) if (_M_w[__i] != static_cast(-1)) return 0; return ((this->_M_w.size() - 1) * _S_bits_per_block + __builtin_popcountll(this->_M_hiword())); } bool _M_is_any() const noexcept { for (size_t __i = 0; __i < this->_M_w.size(); ++__i) if (this->_M_w[__i] != static_cast(0)) return true; return false; } bool _M_is_subset_of(const __dynamic_bitset_base& __b) noexcept { if (__b._M_w.size() == this->_M_w.size()) { for (size_t __i = 0; __i < this->_M_w.size(); ++__i) if (this->_M_w[__i] != (this->_M_w[__i] | __b._M_w[__i])) return false; return true; } else return false; } bool _M_is_proper_subset_of(const __dynamic_bitset_base& __b) const noexcept { if (this->is_subset_of(__b)) { if (*this == __b) return false; else return true; } else return false; } size_t _M_do_count() const noexcept { size_t __result = 0; for (size_t __i = 0; __i < this->_M_w.size(); ++__i) __result += __builtin_popcountll(this->_M_w[__i]); return __result; } size_type _M_size() const noexcept { return this->_M_w.size(); } unsigned long _M_do_to_ulong() const; unsigned long long _M_do_to_ullong() const; // find first "on" bit size_type _M_do_find_first(size_t __not_found) const; // find the next "on" bit that follows "prev" size_type _M_do_find_next(size_t __prev, size_t __not_found) const; // do append of block void _M_do_append_block(block_type __block, size_type __pos) { size_t __offset = __pos % _S_bits_per_block; if (__offset == 0) this->_M_w.push_back(__block); else { this->_M_hiword() |= (__block << __offset); this->_M_w.push_back(__block >> (_S_bits_per_block - __offset)); } } }; /** * @brief The %dynamic_bitset class represents a sequence of bits. * * See N2050, * Proposal to Add a Dynamically Sizeable Bitset to the Standard Library. * http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2050.pdf * * In the general unoptimized case, storage is allocated in * word-sized blocks. Let B be the number of bits in a word, then * (Nb+(B-1))/B words will be used for storage. B - Nb%B bits are * unused. (They are the high-order bits in the highest word.) It * is a class invariant that those unused bits are always zero. * * If you think of %dynamic_bitset as "a simple array of bits," be * aware that your mental picture is reversed: a %dynamic_bitset * behaves the same way as bits in integers do, with the bit at * index 0 in the "least significant / right-hand" position, and * the bit at index Nb-1 in the "most significant / left-hand" * position. Thus, unlike other containers, a %dynamic_bitset's * index "counts from right to left," to put it very loosely. * * This behavior is preserved when translating to and from strings. * For example, the first line of the following program probably * prints "b('a') is 0001100001" on a modern ASCII system. * * @code * #include * #include * #include * * using namespace std; * * int main() * { * long a = 'a'; * dynamic_bitset<> b(a); * * cout << "b('a') is " << b << endl; * * ostringstream s; * s << b; * string str = s.str(); * cout << "index 3 in the string is " << str[3] << " but\n" * << "index 3 in the bitset is " << b[3] << endl; * } * @endcode * * Most of the actual code isn't contained in %dynamic_bitset<> * itself, but in the base class __dynamic_bitset_base. The base * class works with whole words, not with individual bits. This * allows us to specialize __dynamic_bitset_base for the important * special case where the %dynamic_bitset is only a single word. * * Extra confusion can result due to the fact that the storage for * __dynamic_bitset_base @e is a vector, and is indexed as such. This is * carefully encapsulated. */ template> class dynamic_bitset : private __dynamic_bitset_base<_WordT, _Alloc> { static_assert(std::is_unsigned<_WordT>::value, "template argument " "_WordT not an unsigned integral type"); public: typedef __dynamic_bitset_base<_WordT, _Alloc> _Base; typedef _WordT block_type; typedef _Alloc allocator_type; typedef size_t size_type; static const size_type bits_per_block = __CHAR_BIT__ * sizeof(block_type); // Use this: constexpr size_type std::numeric_limits::max(). static const size_type npos = static_cast(-1); private: // Clear the unused bits in the uppermost word. void _M_do_sanitize() { size_type __shift = this->_M_Nb % bits_per_block; if (__shift > 0) this->_M_hiword() &= block_type(~(block_type(-1) << __shift)); } // Set the unused bits in the uppermost word. void _M_do_fill() { size_type __shift = this->_M_Nb % bits_per_block; if (__shift > 0) this->_M_hiword() |= block_type(block_type(-1) << __shift); } /** * These versions of single-bit set, reset, flip, and test * do no range checking. */ dynamic_bitset& _M_unchecked_set(size_type __pos) noexcept { this->_M_getword(__pos) |= _Base::_S_maskbit(__pos); return *this; } dynamic_bitset& _M_unchecked_set(size_type __pos, int __val) noexcept { if (__val) this->_M_getword(__pos) |= _Base::_S_maskbit(__pos); else this->_M_getword(__pos) &= ~_Base::_S_maskbit(__pos); return *this; } dynamic_bitset& _M_unchecked_reset(size_type __pos) noexcept { this->_M_getword(__pos) &= ~_Base::_S_maskbit(__pos); return *this; } dynamic_bitset& _M_unchecked_flip(size_type __pos) noexcept { this->_M_getword(__pos) ^= _Base::_S_maskbit(__pos); return *this; } bool _M_unchecked_test(size_type __pos) const noexcept { return ((this->_M_getword(__pos) & _Base::_S_maskbit(__pos)) != static_cast<_WordT>(0)); } size_type _M_Nb = 0; public: /** * This encapsulates the concept of a single bit. An instance * of this class is a proxy for an actual bit; this way the * individual bit operations are done as faster word-size * bitwise instructions. * * Most users will never need to use this class directly; * conversions to and from bool are automatic and should be * transparent. Overloaded operators help to preserve the * illusion. * * (On a typical system, this "bit %reference" is 64 times the * size of an actual bit. Ha.) */ class reference { friend class dynamic_bitset; block_type *_M_wp; size_type _M_bpos; public: reference(dynamic_bitset& __b, size_type __pos) noexcept { this->_M_wp = &__b._M_getword(__pos); this->_M_bpos = _Base::_S_whichbit(__pos); } // For b[i] = __x; reference& operator=(bool __x) noexcept { if (__x) *this->_M_wp |= _Base::_S_maskbit(this->_M_bpos); else *this->_M_wp &= ~_Base::_S_maskbit(this->_M_bpos); return *this; } // For b[i] = b[__j]; reference& operator=(const reference& __j) noexcept { if ((*(__j._M_wp) & _Base::_S_maskbit(__j._M_bpos))) *this->_M_wp |= _Base::_S_maskbit(this->_M_bpos); else *this->_M_wp &= ~_Base::_S_maskbit(this->_M_bpos); return *this; } // Flips the bit bool operator~() const noexcept { return (*(_M_wp) & _Base::_S_maskbit(this->_M_bpos)) == 0; } // For __x = b[i]; operator bool() const noexcept { return (*(this->_M_wp) & _Base::_S_maskbit(this->_M_bpos)) != 0; } // For b[i].flip(); reference& flip() noexcept { *this->_M_wp ^= _Base::_S_maskbit(this->_M_bpos); return *this; } }; friend class reference; typedef bool const_reference; // 23.3.5.1 constructors: /// All bits set to zero. dynamic_bitset() = default; /// All bits set to zero. explicit dynamic_bitset(const allocator_type& __alloc) : _Base(__alloc) { } /// Initial bits bitwise-copied from a single word (others set to zero). explicit dynamic_bitset(size_type __nbits, unsigned long long __val = 0ULL, const allocator_type& __alloc = allocator_type()) : _Base(__nbits, __val, __alloc), _M_Nb(__nbits) { } dynamic_bitset(initializer_list __il, const allocator_type& __alloc = allocator_type()) : _Base(__alloc) { this->append(__il); } /** * @brief Use a subset of a string. * @param __str A string of '0' and '1' characters. * @param __pos Index of the first character in @p __str to use. * @param __n The number of characters to copy. * @param __zero The character to use for unset bits. * @param __one The character to use for set bits. * @param __alloc An allocator. * @throw std::out_of_range If @p __pos is bigger the size of @p __str. * @throw std::invalid_argument If a character appears in the string * which is neither '0' nor '1'. */ template explicit dynamic_bitset(const std::basic_string<_CharT, _Traits, _Alloc1>& __str, typename basic_string<_CharT,_Traits,_Alloc1>::size_type __pos = 0, typename basic_string<_CharT,_Traits,_Alloc1>::size_type __n = std::basic_string<_CharT, _Traits, _Alloc1>::npos, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1'), const allocator_type& __alloc = allocator_type()) : _Base(__alloc) { if (__pos > __str.size()) __throw_out_of_range(__N("dynamic_bitset::bitset initial position " "not valid")); // Watch for npos. this->_M_Nb = (__n > __str.size() ? __str.size() - __pos : __n); this->resize(this->_M_Nb); this->_M_copy_from_string(__str, __pos, __n); } /** * @brief Construct from a string. * @param __str A string of '0' and '1' characters. * @param __alloc An allocator. * @throw std::invalid_argument If a character appears in the string * which is neither '0' nor '1'. */ explicit dynamic_bitset(const char* __str, const allocator_type& __alloc = allocator_type()) : _Base(__builtin_strlen(__str), 0ULL, __alloc), _M_Nb(__builtin_strlen(__str)) { this->_M_copy_from_ptr(__str, _M_Nb, 0, _M_Nb); } /// Copy constructor. dynamic_bitset(const dynamic_bitset&) = default; /// Move constructor. dynamic_bitset(dynamic_bitset&& __b) noexcept : _Base(std::move(__b)), _M_Nb(__b._M_Nb) { __b.clear(); } /// Swap with another bitset. void swap(dynamic_bitset& __b) noexcept { this->_M_swap(__b); std::swap(this->_M_Nb, __b._M_Nb); } /// Copy assignment operator. dynamic_bitset& operator=(const dynamic_bitset&) = default; /// Move assignment operator. dynamic_bitset& operator=(dynamic_bitset&& __b) noexcept(std::is_nothrow_move_assignable<_Base>::value) { static_cast<_Base&>(*this) = static_cast<_Base&&>(__b); _M_Nb = __b._M_Nb; if _GLIBCXX17_CONSTEXPR (std::is_nothrow_move_assignable<_Base>::value) __b._M_Nb = 0; else if (get_allocator() == __b.get_allocator()) __b._M_Nb = 0; return *this; } /** * @brief Return the allocator for the bitset. */ allocator_type get_allocator() const noexcept { return this->_M_get_allocator(); } /** * @brief Resize the bitset. */ void resize(size_type __nbits, bool __value = false) { if (__value) this->_M_do_fill(); this->_M_resize(__nbits, __value); this->_M_Nb = __nbits; this->_M_do_sanitize(); } /** * @brief Clear the bitset. */ void clear() { this->_M_clear(); this->_M_Nb = 0; } /** * @brief Push a bit onto the high end of the bitset. */ void push_back(bool __bit) { if (size_t __offset = this->size() % bits_per_block == 0) this->_M_do_append_block(block_type(0), this->_M_Nb); ++this->_M_Nb; this->_M_unchecked_set(this->_M_Nb, __bit); } // XXX why is there no pop_back() member in the proposal? /** * @brief Append a block. */ void append(block_type __block) { this->_M_do_append_block(__block, this->_M_Nb); this->_M_Nb += bits_per_block; } /** * @brief */ void append(initializer_list __il) { this->append(__il.begin(), __il.end()); } /** * @brief Append an iterator range of blocks. */ template void append(_BlockInputIterator __first, _BlockInputIterator __last) { for (; __first != __last; ++__first) this->append(*__first); } // 23.3.5.2 dynamic_bitset operations: //@{ /** * @brief Operations on dynamic_bitsets. * @param __rhs A same-sized dynamic_bitset. * * These should be self-explanatory. */ dynamic_bitset& operator&=(const dynamic_bitset& __rhs) { this->_M_do_and(__rhs); return *this; } dynamic_bitset& operator&=(dynamic_bitset&& __rhs) { this->_M_do_and(std::move(__rhs)); return *this; } dynamic_bitset& operator|=(const dynamic_bitset& __rhs) { this->_M_do_or(__rhs); return *this; } dynamic_bitset& operator^=(const dynamic_bitset& __rhs) { this->_M_do_xor(__rhs); return *this; } dynamic_bitset& operator-=(const dynamic_bitset& __rhs) { this->_M_do_dif(__rhs); return *this; } //@} //@{ /** * @brief Operations on dynamic_bitsets. * @param __pos The number of places to shift. * * These should be self-explanatory. */ dynamic_bitset& operator<<=(size_type __pos) { if (__builtin_expect(__pos < this->_M_Nb, 1)) { this->_M_do_left_shift(__pos); this->_M_do_sanitize(); } else this->_M_do_reset(); return *this; } dynamic_bitset& operator>>=(size_type __pos) { if (__builtin_expect(__pos < this->_M_Nb, 1)) { this->_M_do_right_shift(__pos); this->_M_do_sanitize(); } else this->_M_do_reset(); return *this; } //@} // Set, reset, and flip. /** * @brief Sets every bit to true. */ dynamic_bitset& set() { this->_M_do_set(); this->_M_do_sanitize(); return *this; } /** * @brief Sets a given bit to a particular value. * @param __pos The index of the bit. * @param __val Either true or false, defaults to true. * @throw std::out_of_range If @a __pos is bigger the size of the %set. */ dynamic_bitset& set(size_type __pos, bool __val = true) { if (__pos >= _M_Nb) __throw_out_of_range(__N("dynamic_bitset::set")); return this->_M_unchecked_set(__pos, __val); } /** * @brief Sets every bit to false. */ dynamic_bitset& reset() { this->_M_do_reset(); return *this; } /** * @brief Sets a given bit to false. * @param __pos The index of the bit. * @throw std::out_of_range If @a __pos is bigger the size of the %set. * * Same as writing @c set(__pos, false). */ dynamic_bitset& reset(size_type __pos) { if (__pos >= _M_Nb) __throw_out_of_range(__N("dynamic_bitset::reset")); return this->_M_unchecked_reset(__pos); } /** * @brief Toggles every bit to its opposite value. */ dynamic_bitset& flip() { this->_M_do_flip(); this->_M_do_sanitize(); return *this; } /** * @brief Toggles a given bit to its opposite value. * @param __pos The index of the bit. * @throw std::out_of_range If @a __pos is bigger the size of the %set. */ dynamic_bitset& flip(size_type __pos) { if (__pos >= _M_Nb) __throw_out_of_range(__N("dynamic_bitset::flip")); return this->_M_unchecked_flip(__pos); } /// See the no-argument flip(). dynamic_bitset operator~() const { return dynamic_bitset<_WordT, _Alloc>(*this).flip(); } //@{ /** * @brief Array-indexing support. * @param __pos Index into the %dynamic_bitset. * @return A bool for a 'const %dynamic_bitset'. For non-const * bitsets, an instance of the reference proxy class. * @note These operators do no range checking and throw no * exceptions, as required by DR 11 to the standard. */ reference operator[](size_type __pos) { return reference(*this,__pos); } const_reference operator[](size_type __pos) const { return _M_unchecked_test(__pos); } //@} /** * @brief Returns a numerical interpretation of the %dynamic_bitset. * @return The integral equivalent of the bits. * @throw std::overflow_error If there are too many bits to be * represented in an @c unsigned @c long. */ unsigned long to_ulong() const { return this->_M_do_to_ulong(); } /** * @brief Returns a numerical interpretation of the %dynamic_bitset. * @return The integral equivalent of the bits. * @throw std::overflow_error If there are too many bits to be * represented in an @c unsigned @c long. */ unsigned long long to_ullong() const { return this->_M_do_to_ullong(); } /** * @brief Returns a character interpretation of the %dynamic_bitset. * @return The string equivalent of the bits. * * Note the ordering of the bits: decreasing character positions * correspond to increasing bit positions (see the main class notes for * an example). */ template, typename _Alloc1 = std::allocator<_CharT>> std::basic_string<_CharT, _Traits, _Alloc1> to_string(_CharT __zero = _CharT('0'), _CharT __one = _CharT('1')) const { std::basic_string<_CharT, _Traits, _Alloc1> __result; _M_copy_to_string(__result, __zero, __one); return __result; } // Helper functions for string operations. template, typename _CharT = typename _Traits::char_type> void _M_copy_from_ptr(const _CharT*, size_t, size_t, size_t, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1')); template void _M_copy_from_string(const basic_string<_CharT, _Traits, _Alloc1>& __str, size_t __pos, size_t __n, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1')) { _M_copy_from_ptr<_Traits>(__str.data(), __str.size(), __pos, __n, __zero, __one); } template void _M_copy_to_string(std::basic_string<_CharT, _Traits, _Alloc1>& __str, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1')) const; /// Returns the number of bits which are set. size_type count() const noexcept { return this->_M_do_count(); } /// Returns the total number of bits. size_type size() const noexcept { return this->_M_Nb; } /// Returns the total number of blocks. size_type num_blocks() const noexcept { return this->_M_size(); } /// Returns true if the dynamic_bitset is empty. bool empty() const noexcept { return (this->_M_Nb == 0); } /// Returns the maximum size of a dynamic_bitset object having the same /// type as *this. /// The real answer is max() * bits_per_block but is likely to overflow. constexpr size_type max_size() noexcept { return std::numeric_limits::max(); } /** * @brief Tests the value of a bit. * @param __pos The index of a bit. * @return The value at @a __pos. * @throw std::out_of_range If @a __pos is bigger the size of the %set. */ bool test(size_type __pos) const { if (__pos >= _M_Nb) __throw_out_of_range(__N("dynamic_bitset::test")); return _M_unchecked_test(__pos); } /** * @brief Tests whether all the bits are on. * @return True if all the bits are set. */ bool all() const { return this->_M_are_all_aux() == _M_Nb; } /** * @brief Tests whether any of the bits are on. * @return True if at least one bit is set. */ bool any() const { return this->_M_is_any(); } /** * @brief Tests whether any of the bits are on. * @return True if none of the bits are set. */ bool none() const { return !this->_M_is_any(); } //@{ /// Self-explanatory. dynamic_bitset operator<<(size_type __pos) const { return dynamic_bitset(*this) <<= __pos; } dynamic_bitset operator>>(size_type __pos) const { return dynamic_bitset(*this) >>= __pos; } //@} /** * @brief Finds the index of the first "on" bit. * @return The index of the first bit set, or size() if not found. * @sa find_next */ size_type find_first() const { return this->_M_do_find_first(this->_M_Nb); } /** * @brief Finds the index of the next "on" bit after prev. * @return The index of the next bit set, or size() if not found. * @param __prev Where to start searching. * @sa find_first */ size_type find_next(size_t __prev) const { return this->_M_do_find_next(__prev, this->_M_Nb); } bool is_subset_of(const dynamic_bitset& __b) const { return this->_M_is_subset_of(__b); } bool is_proper_subset_of(const dynamic_bitset& __b) const { return this->_M_is_proper_subset_of(__b); } friend bool operator==(const dynamic_bitset& __lhs, const dynamic_bitset& __rhs) noexcept { return __lhs._M_Nb == __rhs._M_Nb && __lhs._M_is_equal(__rhs); } friend bool operator<(const dynamic_bitset& __lhs, const dynamic_bitset& __rhs) noexcept { return __lhs._M_is_less(__rhs) || __lhs._M_Nb < __rhs._M_Nb; } }; template template inline void dynamic_bitset<_WordT, _Alloc>:: _M_copy_to_string(std::basic_string<_CharT, _Traits, _Alloc1>& __str, _CharT __zero, _CharT __one) const { __str.assign(_M_Nb, __zero); for (size_t __i = _M_Nb; __i > 0; --__i) if (_M_unchecked_test(__i - 1)) _Traits::assign(__str[_M_Nb - __i], __one); } //@{ /// These comparisons for equality/inequality are, well, @e bitwise. template inline bool operator!=(const dynamic_bitset<_WordT, _Alloc>& __lhs, const dynamic_bitset<_WordT, _Alloc>& __rhs) { return !(__lhs == __rhs); } template inline bool operator<=(const dynamic_bitset<_WordT, _Alloc>& __lhs, const dynamic_bitset<_WordT, _Alloc>& __rhs) { return !(__lhs > __rhs); } template inline bool operator>(const dynamic_bitset<_WordT, _Alloc>& __lhs, const dynamic_bitset<_WordT, _Alloc>& __rhs) { return __rhs < __lhs; } template inline bool operator>=(const dynamic_bitset<_WordT, _Alloc>& __lhs, const dynamic_bitset<_WordT, _Alloc>& __rhs) { return !(__lhs < __rhs); } //@} // 23.3.5.3 bitset operations: //@{ /** * @brief Global bitwise operations on bitsets. * @param __x A bitset. * @param __y A bitset of the same size as @a __x. * @return A new bitset. * * These should be self-explanatory. */ template inline dynamic_bitset<_WordT, _Alloc> operator&(const dynamic_bitset<_WordT, _Alloc>& __x, const dynamic_bitset<_WordT, _Alloc>& __y) { dynamic_bitset<_WordT, _Alloc> __result(__x); __result &= __y; return __result; } template inline dynamic_bitset<_WordT, _Alloc> operator|(const dynamic_bitset<_WordT, _Alloc>& __x, const dynamic_bitset<_WordT, _Alloc>& __y) { dynamic_bitset<_WordT, _Alloc> __result(__x); __result |= __y; return __result; } template inline dynamic_bitset<_WordT, _Alloc> operator^(const dynamic_bitset<_WordT, _Alloc>& __x, const dynamic_bitset<_WordT, _Alloc>& __y) { dynamic_bitset<_WordT, _Alloc> __result(__x); __result ^= __y; return __result; } template inline dynamic_bitset<_WordT, _Alloc> operator-(const dynamic_bitset<_WordT, _Alloc>& __x, const dynamic_bitset<_WordT, _Alloc>& __y) { dynamic_bitset<_WordT, _Alloc> __result(__x); __result -= __y; return __result; } //@} /// Stream output operator for dynamic_bitset. template inline std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const dynamic_bitset<_WordT, _Alloc>& __x) { std::basic_string<_CharT, _Traits> __tmp; const ctype<_CharT>& __ct = use_facet>(__os.getloc()); __x._M_copy_to_string(__tmp, __ct.widen('0'), __ct.widen('1')); return __os << __tmp; } /** * @} */ } // tr2 _GLIBCXX_END_NAMESPACE_VERSION } // std #include #endif /* _GLIBCXX_TR2_DYNAMIC_BITSET */ c++/8/tr2/bool_set.tcc000064400000020177151027430570010306 0ustar00// TR2 support files -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file tr2/bool_set.tcc * This is a TR2 C++ Library header. */ #ifndef _GLIBCXX_TR2_BOOL_SET_TCC #define _GLIBCXX_TR2_BOOL_SET_TCC 1 #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr2 { bool_set::_Bool_set_val bool_set::_S_not[4] = { _S_true_, _S_false, _S_indet, _S_empty }; bool_set::_Bool_set_val bool_set::_S_xor[4][4] = { { _S_false, _S_true_, _S_indet, _S_empty }, { _S_true_, _S_false, _S_indet, _S_empty }, { _S_indet, _S_indet, _S_indet, _S_empty }, { _S_empty, _S_empty, _S_empty, _S_empty } }; bool_set::_Bool_set_val bool_set::_S_or[4][4] = { { _S_false, _S_true_, _S_indet, _S_empty }, { _S_true_, _S_true_, _S_true_, _S_empty }, { _S_indet, _S_true_, _S_indet, _S_empty }, { _S_empty, _S_empty, _S_empty, _S_empty } }; bool_set::_Bool_set_val bool_set::_S_and[4][4] = { { _S_false, _S_false, _S_false, _S_empty }, { _S_false, _S_true_, _S_indet, _S_empty }, { _S_false, _S_indet, _S_indet, _S_empty }, { _S_empty, _S_empty, _S_empty, _S_empty } }; bool_set::_Bool_set_val bool_set::_S_eq[4][4] = { { _S_true_, _S_false, _S_indet, _S_empty }, { _S_false, _S_true_, _S_indet, _S_empty }, { _S_indet, _S_indet, _S_indet, _S_empty }, { _S_empty, _S_empty, _S_empty, _S_empty } }; } _GLIBCXX_END_NAMESPACE_VERSION } // I object to these things. // The stuff in locale facets are for basic types. // I think we could hack operator<< and operator>>. /** * @brief Numeric parsing. * * Parses the input stream into the bool @a v. It does so by calling * num_get::do_get(). * * If ios_base::boolalpha is set, attempts to read * ctype::truename() or ctype::falsename(). Sets * @a v to true or false if successful. Sets err to * ios_base::failbit if reading the string fails. Sets err to * ios_base::eofbit if the stream is emptied. * * If ios_base::boolalpha is not set, proceeds as with reading a long, * except if the value is 1, sets @a v to true, if the value is 0, sets * @a v to false, and otherwise set err to ios_base::failbit. * * @param in Start of input stream. * @param end End of input stream. * @param io Source of locale and flags. * @param err Error flags to set. * @param v Value to format and insert. * @return Iterator after reading. iter_type get(iter_type __in, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool& __v) const { return this->do_get(__in, __end, __io, __err, __v); } */ /* template _InIter num_get<_CharT, _InIter>:: do_get(iter_type __beg, iter_type __end, ios_base& __io, ios_base::iostate& __err, bool_set& __v) const { if (!(__io.flags() & ios_base::boolalpha)) { // Parse bool values as long. // NB: We can't just call do_get(long) here, as it might // refer to a derived class. long __l = -1; __beg = _M_extract_int(__beg, __end, __io, __err, __l); if (__c >= _S_false && __c < _S_empty) __b._M_b = static_cast<_Bool_set_val>(__c); else { // What should we do here? __v = true; __err = ios_base::failbit; if (__beg == __end) __err |= ios_base::eofbit; } } else { // Parse bool values as alphanumeric. typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); bool __testf = true; bool __testt = true; bool __donef = __lc->_M_falsename_size == 0; bool __donet = __lc->_M_truename_size == 0; bool __testeof = false; size_t __n = 0; while (!__donef || !__donet) { if (__beg == __end) { __testeof = true; break; } const char_type __c = *__beg; if (!__donef) __testf = __c == __lc->_M_falsename[__n]; if (!__testf && __donet) break; if (!__donet) __testt = __c == __lc->_M_truename[__n]; if (!__testt && __donef) break; if (!__testt && !__testf) break; ++__n; ++__beg; __donef = !__testf || __n >= __lc->_M_falsename_size; __donet = !__testt || __n >= __lc->_M_truename_size; } if (__testf && __n == __lc->_M_falsename_size && __n) { __v = false; if (__testt && __n == __lc->_M_truename_size) __err = ios_base::failbit; else __err = __testeof ? ios_base::eofbit : ios_base::goodbit; } else if (__testt && __n == __lc->_M_truename_size && __n) { __v = true; __err = __testeof ? ios_base::eofbit : ios_base::goodbit; } else { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 23. Num_get overflow result. __v = false; __err = ios_base::failbit; if (__testeof) __err |= ios_base::eofbit; } } return __beg; } */ /** * @brief Numeric formatting. * * Formats the boolean @a v and inserts it into a stream. It does so * by calling num_put::do_put(). * * If ios_base::boolalpha is set, writes ctype::truename() or * ctype::falsename(). Otherwise formats @a v as an int. * * @param s Stream to write to. * @param io Source of locale and flags. * @param fill Char_type to use for filling. * @param v Value to format and insert. * @return Iterator after writing. iter_type put(iter_type __s, ios_base& __f, char_type __fill, bool __v) const { return this->do_put(__s, __f, __fill, __v); } */ /* template _OutIter num_put<_CharT, _OutIter>:: do_put(iter_type __s, ios_base& __io, char_type __fill, bool_set __v) const { const ios_base::fmtflags __flags = __io.flags(); if ((__flags & ios_base::boolalpha) == 0) { const long __l = __v; __s = _M_insert_int(__s, __io, __fill, __l); } else { typedef __numpunct_cache<_CharT> __cache_type; __use_cache<__cache_type> __uc; const locale& __loc = __io._M_getloc(); const __cache_type* __lc = __uc(__loc); const _CharT* __name = __v ? __lc->_M_truename : __lc->_M_falsename; int __len = __v ? __lc->_M_truename_size : __lc->_M_falsename_size; const streamsize __w = __io.width(); if (__w > static_cast(__len)) { const streamsize __plen = __w - __len; _CharT* __ps = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __plen)); char_traits<_CharT>::assign(__ps, __plen, __fill); __io.width(0); if ((__flags & ios_base::adjustfield) == ios_base::left) { __s = std::__write(__s, __name, __len); __s = std::__write(__s, __ps, __plen); } else { __s = std::__write(__s, __ps, __plen); __s = std::__write(__s, __name, __len); } return __s; } __io.width(0); __s = std::__write(__s, __name, __len); } return __s; } */ #endif // _GLIBCXX_TR2_BOOL_SET_TCC c++/8/valarray000064400000116522151027430570007042 0ustar00// The template and inlines for the -*- C++ -*- valarray class. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/valarray * This is a Standard C++ Library header. */ // Written by Gabriel Dos Reis #ifndef _GLIBCXX_VALARRAY #define _GLIBCXX_VALARRAY 1 #pragma GCC system_header #include #include #include #include #if __cplusplus >= 201103L #include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template class _Expr; template class _ValArray; template class _Meta, class _Dom> struct _UnClos; template class _Meta1, template class _Meta2, class _Dom1, class _Dom2> class _BinClos; template class _Meta, class _Dom> class _SClos; template class _Meta, class _Dom> class _GClos; template class _Meta, class _Dom> class _IClos; template class _Meta, class _Dom> class _ValFunClos; template class _Meta, class _Dom> class _RefFunClos; template class valarray; // An array of type _Tp class slice; // BLAS-like slice out of an array template class slice_array; class gslice; // generalized slice out of an array template class gslice_array; template class mask_array; // masked array template class indirect_array; // indirected array _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup numeric_arrays Numeric Arrays * @ingroup numerics * * Classes and functions for representing and manipulating arrays of elements. * @{ */ /** * @brief Smart array designed to support numeric processing. * * A valarray is an array that provides constraints intended to allow for * effective optimization of numeric array processing by reducing the * aliasing that can result from pointer representations. It represents a * one-dimensional array from which different multidimensional subsets can * be accessed and modified. * * @tparam _Tp Type of object in the array. */ template class valarray { template struct _UnaryOp { typedef typename __fun<_Op, _Tp>::result_type __rt; typedef _Expr<_UnClos<_Op, _ValArray, _Tp>, __rt> _Rt; }; public: typedef _Tp value_type; // _lib.valarray.cons_ construct/destroy: /// Construct an empty array. valarray(); /// Construct an array with @a n elements. explicit valarray(size_t); /// Construct an array with @a n elements initialized to @a t. valarray(const _Tp&, size_t); /// Construct an array initialized to the first @a n elements of @a t. valarray(const _Tp* __restrict__, size_t); /// Copy constructor. valarray(const valarray&); #if __cplusplus >= 201103L /// Move constructor. valarray(valarray&&) noexcept; #endif /// Construct an array with the same size and values in @a sa. valarray(const slice_array<_Tp>&); /// Construct an array with the same size and values in @a ga. valarray(const gslice_array<_Tp>&); /// Construct an array with the same size and values in @a ma. valarray(const mask_array<_Tp>&); /// Construct an array with the same size and values in @a ia. valarray(const indirect_array<_Tp>&); #if __cplusplus >= 201103L /// Construct an array with an initializer_list of values. valarray(initializer_list<_Tp>); #endif template valarray(const _Expr<_Dom, _Tp>& __e); ~valarray() _GLIBCXX_NOEXCEPT; // _lib.valarray.assign_ assignment: /** * @brief Assign elements to an array. * * Assign elements of array to values in @a v. * * @param __v Valarray to get values from. */ valarray<_Tp>& operator=(const valarray<_Tp>& __v); #if __cplusplus >= 201103L /** * @brief Move assign elements to an array. * * Move assign elements of array to values in @a v. * * @param __v Valarray to get values from. */ valarray<_Tp>& operator=(valarray<_Tp>&& __v) noexcept; #endif /** * @brief Assign elements to a value. * * Assign all elements of array to @a t. * * @param __t Value for elements. */ valarray<_Tp>& operator=(const _Tp& __t); /** * @brief Assign elements to an array subset. * * Assign elements of array to values in @a sa. Results are undefined * if @a sa does not have the same size as this array. * * @param __sa Array slice to get values from. */ valarray<_Tp>& operator=(const slice_array<_Tp>& __sa); /** * @brief Assign elements to an array subset. * * Assign elements of array to values in @a ga. Results are undefined * if @a ga does not have the same size as this array. * * @param __ga Array slice to get values from. */ valarray<_Tp>& operator=(const gslice_array<_Tp>& __ga); /** * @brief Assign elements to an array subset. * * Assign elements of array to values in @a ma. Results are undefined * if @a ma does not have the same size as this array. * * @param __ma Array slice to get values from. */ valarray<_Tp>& operator=(const mask_array<_Tp>& __ma); /** * @brief Assign elements to an array subset. * * Assign elements of array to values in @a ia. Results are undefined * if @a ia does not have the same size as this array. * * @param __ia Array slice to get values from. */ valarray<_Tp>& operator=(const indirect_array<_Tp>& __ia); #if __cplusplus >= 201103L /** * @brief Assign elements to an initializer_list. * * Assign elements of array to values in @a __l. Results are undefined * if @a __l does not have the same size as this array. * * @param __l initializer_list to get values from. */ valarray& operator=(initializer_list<_Tp> __l); #endif template valarray<_Tp>& operator= (const _Expr<_Dom, _Tp>&); // _lib.valarray.access_ element access: /** * Return a reference to the i'th array element. * * @param __i Index of element to return. * @return Reference to the i'th element. */ _Tp& operator[](size_t __i); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 389. Const overload of valarray::operator[] returns by value. const _Tp& operator[](size_t) const; // _lib.valarray.sub_ subset operations: /** * @brief Return an array subset. * * Returns a new valarray containing the elements of the array * indicated by the slice argument. The new valarray has the same size * as the input slice. @see slice. * * @param __s The source slice. * @return New valarray containing elements in @a __s. */ _Expr<_SClos<_ValArray, _Tp>, _Tp> operator[](slice __s) const; /** * @brief Return a reference to an array subset. * * Returns a new valarray containing the elements of the array * indicated by the slice argument. The new valarray has the same size * as the input slice. @see slice. * * @param __s The source slice. * @return New valarray containing elements in @a __s. */ slice_array<_Tp> operator[](slice __s); /** * @brief Return an array subset. * * Returns a slice_array referencing the elements of the array * indicated by the slice argument. @see gslice. * * @param __s The source slice. * @return Slice_array referencing elements indicated by @a __s. */ _Expr<_GClos<_ValArray, _Tp>, _Tp> operator[](const gslice& __s) const; /** * @brief Return a reference to an array subset. * * Returns a new valarray containing the elements of the array * indicated by the gslice argument. The new valarray has * the same size as the input gslice. @see gslice. * * @param __s The source gslice. * @return New valarray containing elements in @a __s. */ gslice_array<_Tp> operator[](const gslice& __s); /** * @brief Return an array subset. * * Returns a new valarray containing the elements of the array * indicated by the argument. The input is a valarray of bool which * represents a bitmask indicating which elements should be copied into * the new valarray. Each element of the array is added to the return * valarray if the corresponding element of the argument is true. * * @param __m The valarray bitmask. * @return New valarray containing elements indicated by @a __m. */ valarray<_Tp> operator[](const valarray& __m) const; /** * @brief Return a reference to an array subset. * * Returns a new mask_array referencing the elements of the array * indicated by the argument. The input is a valarray of bool which * represents a bitmask indicating which elements are part of the * subset. Elements of the array are part of the subset if the * corresponding element of the argument is true. * * @param __m The valarray bitmask. * @return New valarray containing elements indicated by @a __m. */ mask_array<_Tp> operator[](const valarray& __m); /** * @brief Return an array subset. * * Returns a new valarray containing the elements of the array * indicated by the argument. The elements in the argument are * interpreted as the indices of elements of this valarray to copy to * the return valarray. * * @param __i The valarray element index list. * @return New valarray containing elements in @a __s. */ _Expr<_IClos<_ValArray, _Tp>, _Tp> operator[](const valarray& __i) const; /** * @brief Return a reference to an array subset. * * Returns an indirect_array referencing the elements of the array * indicated by the argument. The elements in the argument are * interpreted as the indices of elements of this valarray to include * in the subset. The returned indirect_array refers to these * elements. * * @param __i The valarray element index list. * @return Indirect_array referencing elements in @a __i. */ indirect_array<_Tp> operator[](const valarray& __i); // _lib.valarray.unary_ unary operators: /// Return a new valarray by applying unary + to each element. typename _UnaryOp<__unary_plus>::_Rt operator+() const; /// Return a new valarray by applying unary - to each element. typename _UnaryOp<__negate>::_Rt operator-() const; /// Return a new valarray by applying unary ~ to each element. typename _UnaryOp<__bitwise_not>::_Rt operator~() const; /// Return a new valarray by applying unary ! to each element. typename _UnaryOp<__logical_not>::_Rt operator!() const; // _lib.valarray.cassign_ computed assignment: /// Multiply each element of array by @a t. valarray<_Tp>& operator*=(const _Tp&); /// Divide each element of array by @a t. valarray<_Tp>& operator/=(const _Tp&); /// Set each element e of array to e % @a t. valarray<_Tp>& operator%=(const _Tp&); /// Add @a t to each element of array. valarray<_Tp>& operator+=(const _Tp&); /// Subtract @a t to each element of array. valarray<_Tp>& operator-=(const _Tp&); /// Set each element e of array to e ^ @a t. valarray<_Tp>& operator^=(const _Tp&); /// Set each element e of array to e & @a t. valarray<_Tp>& operator&=(const _Tp&); /// Set each element e of array to e | @a t. valarray<_Tp>& operator|=(const _Tp&); /// Left shift each element e of array by @a t bits. valarray<_Tp>& operator<<=(const _Tp&); /// Right shift each element e of array by @a t bits. valarray<_Tp>& operator>>=(const _Tp&); /// Multiply elements of array by corresponding elements of @a v. valarray<_Tp>& operator*=(const valarray<_Tp>&); /// Divide elements of array by corresponding elements of @a v. valarray<_Tp>& operator/=(const valarray<_Tp>&); /// Modulo elements of array by corresponding elements of @a v. valarray<_Tp>& operator%=(const valarray<_Tp>&); /// Add corresponding elements of @a v to elements of array. valarray<_Tp>& operator+=(const valarray<_Tp>&); /// Subtract corresponding elements of @a v from elements of array. valarray<_Tp>& operator-=(const valarray<_Tp>&); /// Logical xor corresponding elements of @a v with elements of array. valarray<_Tp>& operator^=(const valarray<_Tp>&); /// Logical or corresponding elements of @a v with elements of array. valarray<_Tp>& operator|=(const valarray<_Tp>&); /// Logical and corresponding elements of @a v with elements of array. valarray<_Tp>& operator&=(const valarray<_Tp>&); /// Left shift elements of array by corresponding elements of @a v. valarray<_Tp>& operator<<=(const valarray<_Tp>&); /// Right shift elements of array by corresponding elements of @a v. valarray<_Tp>& operator>>=(const valarray<_Tp>&); template valarray<_Tp>& operator*=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator/=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator%=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator+=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator-=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator^=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator|=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator&=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator<<=(const _Expr<_Dom, _Tp>&); template valarray<_Tp>& operator>>=(const _Expr<_Dom, _Tp>&); // _lib.valarray.members_ member functions: #if __cplusplus >= 201103L /// Swap. void swap(valarray<_Tp>& __v) noexcept; #endif /// Return the number of elements in array. size_t size() const; /** * @brief Return the sum of all elements in the array. * * Accumulates the sum of all elements into a Tp using +=. The order * of adding the elements is unspecified. */ _Tp sum() const; /// Return the minimum element using operator<(). _Tp min() const; /// Return the maximum element using operator<(). _Tp max() const; /** * @brief Return a shifted array. * * A new valarray is constructed as a copy of this array with elements * in shifted positions. For an element with index i, the new position * is i - n. The new valarray has the same size as the current one. * New elements without a value are set to 0. Elements whose new * position is outside the bounds of the array are discarded. * * Positive arguments shift toward index 0, discarding elements [0, n). * Negative arguments discard elements from the top of the array. * * @param __n Number of element positions to shift. * @return New valarray with elements in shifted positions. */ valarray<_Tp> shift (int __n) const; /** * @brief Return a rotated array. * * A new valarray is constructed as a copy of this array with elements * in shifted positions. For an element with index i, the new position * is (i - n) % size(). The new valarray has the same size as the * current one. Elements that are shifted beyond the array bounds are * shifted into the other end of the array. No elements are lost. * * Positive arguments shift toward index 0, wrapping around the top. * Negative arguments shift towards the top, wrapping around to 0. * * @param __n Number of element positions to rotate. * @return New valarray with elements in shifted positions. */ valarray<_Tp> cshift(int __n) const; /** * @brief Apply a function to the array. * * Returns a new valarray with elements assigned to the result of * applying func to the corresponding element of this array. The new * array has the same size as this one. * * @param func Function of Tp returning Tp to apply. * @return New valarray with transformed elements. */ _Expr<_ValFunClos<_ValArray, _Tp>, _Tp> apply(_Tp func(_Tp)) const; /** * @brief Apply a function to the array. * * Returns a new valarray with elements assigned to the result of * applying func to the corresponding element of this array. The new * array has the same size as this one. * * @param func Function of const Tp& returning Tp to apply. * @return New valarray with transformed elements. */ _Expr<_RefFunClos<_ValArray, _Tp>, _Tp> apply(_Tp func(const _Tp&)) const; /** * @brief Resize array. * * Resize this array to @a size and set all elements to @a c. All * references and iterators are invalidated. * * @param __size New array size. * @param __c New value for all elements. */ void resize(size_t __size, _Tp __c = _Tp()); private: size_t _M_size; _Tp* __restrict__ _M_data; friend class _Array<_Tp>; }; #if __cpp_deduction_guides >= 201606 template valarray(const _Tp(&)[_Nm], size_t) -> valarray<_Tp>; #endif template inline const _Tp& valarray<_Tp>::operator[](size_t __i) const { __glibcxx_requires_subscript(__i); return _M_data[__i]; } template inline _Tp& valarray<_Tp>::operator[](size_t __i) { __glibcxx_requires_subscript(__i); return _M_data[__i]; } // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup numeric_arrays * @{ */ template inline valarray<_Tp>::valarray() : _M_size(0), _M_data(0) {} template inline valarray<_Tp>::valarray(size_t __n) : _M_size(__n), _M_data(__valarray_get_storage<_Tp>(__n)) { std::__valarray_default_construct(_M_data, _M_data + __n); } template inline valarray<_Tp>::valarray(const _Tp& __t, size_t __n) : _M_size(__n), _M_data(__valarray_get_storage<_Tp>(__n)) { std::__valarray_fill_construct(_M_data, _M_data + __n, __t); } template inline valarray<_Tp>::valarray(const _Tp* __restrict__ __p, size_t __n) : _M_size(__n), _M_data(__valarray_get_storage<_Tp>(__n)) { __glibcxx_assert(__p != 0 || __n == 0); std::__valarray_copy_construct(__p, __p + __n, _M_data); } template inline valarray<_Tp>::valarray(const valarray<_Tp>& __v) : _M_size(__v._M_size), _M_data(__valarray_get_storage<_Tp>(__v._M_size)) { std::__valarray_copy_construct(__v._M_data, __v._M_data + _M_size, _M_data); } #if __cplusplus >= 201103L template inline valarray<_Tp>::valarray(valarray<_Tp>&& __v) noexcept : _M_size(__v._M_size), _M_data(__v._M_data) { __v._M_size = 0; __v._M_data = 0; } #endif template inline valarray<_Tp>::valarray(const slice_array<_Tp>& __sa) : _M_size(__sa._M_sz), _M_data(__valarray_get_storage<_Tp>(__sa._M_sz)) { std::__valarray_copy_construct (__sa._M_array, __sa._M_sz, __sa._M_stride, _Array<_Tp>(_M_data)); } template inline valarray<_Tp>::valarray(const gslice_array<_Tp>& __ga) : _M_size(__ga._M_index.size()), _M_data(__valarray_get_storage<_Tp>(_M_size)) { std::__valarray_copy_construct (__ga._M_array, _Array(__ga._M_index), _Array<_Tp>(_M_data), _M_size); } template inline valarray<_Tp>::valarray(const mask_array<_Tp>& __ma) : _M_size(__ma._M_sz), _M_data(__valarray_get_storage<_Tp>(__ma._M_sz)) { std::__valarray_copy_construct (__ma._M_array, __ma._M_mask, _Array<_Tp>(_M_data), _M_size); } template inline valarray<_Tp>::valarray(const indirect_array<_Tp>& __ia) : _M_size(__ia._M_sz), _M_data(__valarray_get_storage<_Tp>(__ia._M_sz)) { std::__valarray_copy_construct (__ia._M_array, __ia._M_index, _Array<_Tp>(_M_data), _M_size); } #if __cplusplus >= 201103L template inline valarray<_Tp>::valarray(initializer_list<_Tp> __l) : _M_size(__l.size()), _M_data(__valarray_get_storage<_Tp>(__l.size())) { std::__valarray_copy_construct(__l.begin(), __l.end(), _M_data); } #endif template template inline valarray<_Tp>::valarray(const _Expr<_Dom, _Tp>& __e) : _M_size(__e.size()), _M_data(__valarray_get_storage<_Tp>(_M_size)) { std::__valarray_copy_construct(__e, _M_size, _Array<_Tp>(_M_data)); } template inline valarray<_Tp>::~valarray() _GLIBCXX_NOEXCEPT { std::__valarray_destroy_elements(_M_data, _M_data + _M_size); std::__valarray_release_memory(_M_data); } template inline valarray<_Tp>& valarray<_Tp>::operator=(const valarray<_Tp>& __v) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 630. arrays of valarray. if (_M_size == __v._M_size) std::__valarray_copy(__v._M_data, _M_size, _M_data); else { if (_M_data) { std::__valarray_destroy_elements(_M_data, _M_data + _M_size); std::__valarray_release_memory(_M_data); } _M_size = __v._M_size; _M_data = __valarray_get_storage<_Tp>(_M_size); std::__valarray_copy_construct(__v._M_data, __v._M_data + _M_size, _M_data); } return *this; } #if __cplusplus >= 201103L template inline valarray<_Tp>& valarray<_Tp>::operator=(valarray<_Tp>&& __v) noexcept { if (_M_data) { std::__valarray_destroy_elements(_M_data, _M_data + _M_size); std::__valarray_release_memory(_M_data); } _M_size = __v._M_size; _M_data = __v._M_data; __v._M_size = 0; __v._M_data = 0; return *this; } template inline valarray<_Tp>& valarray<_Tp>::operator=(initializer_list<_Tp> __l) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 630. arrays of valarray. if (_M_size == __l.size()) std::__valarray_copy(__l.begin(), __l.size(), _M_data); else { if (_M_data) { std::__valarray_destroy_elements(_M_data, _M_data + _M_size); std::__valarray_release_memory(_M_data); } _M_size = __l.size(); _M_data = __valarray_get_storage<_Tp>(_M_size); std::__valarray_copy_construct(__l.begin(), __l.begin() + _M_size, _M_data); } return *this; } #endif template inline valarray<_Tp>& valarray<_Tp>::operator=(const _Tp& __t) { std::__valarray_fill(_M_data, _M_size, __t); return *this; } template inline valarray<_Tp>& valarray<_Tp>::operator=(const slice_array<_Tp>& __sa) { __glibcxx_assert(_M_size == __sa._M_sz); std::__valarray_copy(__sa._M_array, __sa._M_sz, __sa._M_stride, _Array<_Tp>(_M_data)); return *this; } template inline valarray<_Tp>& valarray<_Tp>::operator=(const gslice_array<_Tp>& __ga) { __glibcxx_assert(_M_size == __ga._M_index.size()); std::__valarray_copy(__ga._M_array, _Array(__ga._M_index), _Array<_Tp>(_M_data), _M_size); return *this; } template inline valarray<_Tp>& valarray<_Tp>::operator=(const mask_array<_Tp>& __ma) { __glibcxx_assert(_M_size == __ma._M_sz); std::__valarray_copy(__ma._M_array, __ma._M_mask, _Array<_Tp>(_M_data), _M_size); return *this; } template inline valarray<_Tp>& valarray<_Tp>::operator=(const indirect_array<_Tp>& __ia) { __glibcxx_assert(_M_size == __ia._M_sz); std::__valarray_copy(__ia._M_array, __ia._M_index, _Array<_Tp>(_M_data), _M_size); return *this; } template template inline valarray<_Tp>& valarray<_Tp>::operator=(const _Expr<_Dom, _Tp>& __e) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 630. arrays of valarray. if (_M_size == __e.size()) std::__valarray_copy(__e, _M_size, _Array<_Tp>(_M_data)); else { if (_M_data) { std::__valarray_destroy_elements(_M_data, _M_data + _M_size); std::__valarray_release_memory(_M_data); } _M_size = __e.size(); _M_data = __valarray_get_storage<_Tp>(_M_size); std::__valarray_copy_construct(__e, _M_size, _Array<_Tp>(_M_data)); } return *this; } template inline _Expr<_SClos<_ValArray,_Tp>, _Tp> valarray<_Tp>::operator[](slice __s) const { typedef _SClos<_ValArray,_Tp> _Closure; return _Expr<_Closure, _Tp>(_Closure (_Array<_Tp>(_M_data), __s)); } template inline slice_array<_Tp> valarray<_Tp>::operator[](slice __s) { return slice_array<_Tp>(_Array<_Tp>(_M_data), __s); } template inline _Expr<_GClos<_ValArray,_Tp>, _Tp> valarray<_Tp>::operator[](const gslice& __gs) const { typedef _GClos<_ValArray,_Tp> _Closure; return _Expr<_Closure, _Tp> (_Closure(_Array<_Tp>(_M_data), __gs._M_index->_M_index)); } template inline gslice_array<_Tp> valarray<_Tp>::operator[](const gslice& __gs) { return gslice_array<_Tp> (_Array<_Tp>(_M_data), __gs._M_index->_M_index); } template inline valarray<_Tp> valarray<_Tp>::operator[](const valarray& __m) const { size_t __s = 0; size_t __e = __m.size(); for (size_t __i=0; __i<__e; ++__i) if (__m[__i]) ++__s; return valarray<_Tp>(mask_array<_Tp>(_Array<_Tp>(_M_data), __s, _Array (__m))); } template inline mask_array<_Tp> valarray<_Tp>::operator[](const valarray& __m) { size_t __s = 0; size_t __e = __m.size(); for (size_t __i=0; __i<__e; ++__i) if (__m[__i]) ++__s; return mask_array<_Tp>(_Array<_Tp>(_M_data), __s, _Array(__m)); } template inline _Expr<_IClos<_ValArray,_Tp>, _Tp> valarray<_Tp>::operator[](const valarray& __i) const { typedef _IClos<_ValArray,_Tp> _Closure; return _Expr<_Closure, _Tp>(_Closure(*this, __i)); } template inline indirect_array<_Tp> valarray<_Tp>::operator[](const valarray& __i) { return indirect_array<_Tp>(_Array<_Tp>(_M_data), __i.size(), _Array(__i)); } #if __cplusplus >= 201103L template inline void valarray<_Tp>::swap(valarray<_Tp>& __v) noexcept { std::swap(_M_size, __v._M_size); std::swap(_M_data, __v._M_data); } #endif template inline size_t valarray<_Tp>::size() const { return _M_size; } template inline _Tp valarray<_Tp>::sum() const { __glibcxx_assert(_M_size > 0); return std::__valarray_sum(_M_data, _M_data + _M_size); } template inline valarray<_Tp> valarray<_Tp>::shift(int __n) const { valarray<_Tp> __ret; if (_M_size == 0) return __ret; _Tp* __restrict__ __tmp_M_data = std::__valarray_get_storage<_Tp>(_M_size); if (__n == 0) std::__valarray_copy_construct(_M_data, _M_data + _M_size, __tmp_M_data); else if (__n > 0) // shift left { if (size_t(__n) > _M_size) __n = int(_M_size); std::__valarray_copy_construct(_M_data + __n, _M_data + _M_size, __tmp_M_data); std::__valarray_default_construct(__tmp_M_data + _M_size - __n, __tmp_M_data + _M_size); } else // shift right { if (-size_t(__n) > _M_size) __n = -int(_M_size); std::__valarray_copy_construct(_M_data, _M_data + _M_size + __n, __tmp_M_data - __n); std::__valarray_default_construct(__tmp_M_data, __tmp_M_data - __n); } __ret._M_size = _M_size; __ret._M_data = __tmp_M_data; return __ret; } template inline valarray<_Tp> valarray<_Tp>::cshift(int __n) const { valarray<_Tp> __ret; if (_M_size == 0) return __ret; _Tp* __restrict__ __tmp_M_data = std::__valarray_get_storage<_Tp>(_M_size); if (__n == 0) std::__valarray_copy_construct(_M_data, _M_data + _M_size, __tmp_M_data); else if (__n > 0) // cshift left { if (size_t(__n) > _M_size) __n = int(__n % _M_size); std::__valarray_copy_construct(_M_data, _M_data + __n, __tmp_M_data + _M_size - __n); std::__valarray_copy_construct(_M_data + __n, _M_data + _M_size, __tmp_M_data); } else // cshift right { if (-size_t(__n) > _M_size) __n = -int(-size_t(__n) % _M_size); std::__valarray_copy_construct(_M_data + _M_size + __n, _M_data + _M_size, __tmp_M_data); std::__valarray_copy_construct(_M_data, _M_data + _M_size + __n, __tmp_M_data - __n); } __ret._M_size = _M_size; __ret._M_data = __tmp_M_data; return __ret; } template inline void valarray<_Tp>::resize(size_t __n, _Tp __c) { // This complication is so to make valarray > work // even though it is not required by the standard. Nobody should // be saying valarray > anyway. See the specs. std::__valarray_destroy_elements(_M_data, _M_data + _M_size); if (_M_size != __n) { std::__valarray_release_memory(_M_data); _M_size = __n; _M_data = __valarray_get_storage<_Tp>(__n); } std::__valarray_fill_construct(_M_data, _M_data + __n, __c); } template inline _Tp valarray<_Tp>::min() const { __glibcxx_assert(_M_size > 0); return *std::min_element(_M_data, _M_data + _M_size); } template inline _Tp valarray<_Tp>::max() const { __glibcxx_assert(_M_size > 0); return *std::max_element(_M_data, _M_data + _M_size); } template inline _Expr<_ValFunClos<_ValArray, _Tp>, _Tp> valarray<_Tp>::apply(_Tp func(_Tp)) const { typedef _ValFunClos<_ValArray, _Tp> _Closure; return _Expr<_Closure, _Tp>(_Closure(*this, func)); } template inline _Expr<_RefFunClos<_ValArray, _Tp>, _Tp> valarray<_Tp>::apply(_Tp func(const _Tp &)) const { typedef _RefFunClos<_ValArray, _Tp> _Closure; return _Expr<_Closure, _Tp>(_Closure(*this, func)); } #define _DEFINE_VALARRAY_UNARY_OPERATOR(_Op, _Name) \ template \ inline typename valarray<_Tp>::template _UnaryOp<_Name>::_Rt \ valarray<_Tp>::operator _Op() const \ { \ typedef _UnClos<_Name, _ValArray, _Tp> _Closure; \ typedef typename __fun<_Name, _Tp>::result_type _Rt; \ return _Expr<_Closure, _Rt>(_Closure(*this)); \ } _DEFINE_VALARRAY_UNARY_OPERATOR(+, __unary_plus) _DEFINE_VALARRAY_UNARY_OPERATOR(-, __negate) _DEFINE_VALARRAY_UNARY_OPERATOR(~, __bitwise_not) _DEFINE_VALARRAY_UNARY_OPERATOR (!, __logical_not) #undef _DEFINE_VALARRAY_UNARY_OPERATOR #define _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(_Op, _Name) \ template \ inline valarray<_Tp>& \ valarray<_Tp>::operator _Op##=(const _Tp &__t) \ { \ _Array_augmented_##_Name(_Array<_Tp>(_M_data), _M_size, __t); \ return *this; \ } \ \ template \ inline valarray<_Tp>& \ valarray<_Tp>::operator _Op##=(const valarray<_Tp> &__v) \ { \ __glibcxx_assert(_M_size == __v._M_size); \ _Array_augmented_##_Name(_Array<_Tp>(_M_data), _M_size, \ _Array<_Tp>(__v._M_data)); \ return *this; \ } _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(+, __plus) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(-, __minus) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(*, __multiplies) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(/, __divides) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(%, __modulus) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(^, __bitwise_xor) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(&, __bitwise_and) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(|, __bitwise_or) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(<<, __shift_left) _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT(>>, __shift_right) #undef _DEFINE_VALARRAY_AUGMENTED_ASSIGNMENT #define _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(_Op, _Name) \ template template \ inline valarray<_Tp>& \ valarray<_Tp>::operator _Op##=(const _Expr<_Dom, _Tp>& __e) \ { \ _Array_augmented_##_Name(_Array<_Tp>(_M_data), __e, _M_size); \ return *this; \ } _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(+, __plus) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(-, __minus) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(*, __multiplies) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(/, __divides) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(%, __modulus) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(^, __bitwise_xor) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(&, __bitwise_and) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(|, __bitwise_or) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(<<, __shift_left) _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT(>>, __shift_right) #undef _DEFINE_VALARRAY_EXPR_AUGMENTED_ASSIGNMENT #define _DEFINE_BINARY_OPERATOR(_Op, _Name) \ template \ inline _Expr<_BinClos<_Name, _ValArray, _ValArray, _Tp, _Tp>, \ typename __fun<_Name, _Tp>::result_type> \ operator _Op(const valarray<_Tp>& __v, const valarray<_Tp>& __w) \ { \ __glibcxx_assert(__v.size() == __w.size()); \ typedef _BinClos<_Name, _ValArray, _ValArray, _Tp, _Tp> _Closure; \ typedef typename __fun<_Name, _Tp>::result_type _Rt; \ return _Expr<_Closure, _Rt>(_Closure(__v, __w)); \ } \ \ template \ inline _Expr<_BinClos<_Name, _ValArray,_Constant, _Tp, _Tp>, \ typename __fun<_Name, _Tp>::result_type> \ operator _Op(const valarray<_Tp>& __v, const _Tp& __t) \ { \ typedef _BinClos<_Name, _ValArray, _Constant, _Tp, _Tp> _Closure; \ typedef typename __fun<_Name, _Tp>::result_type _Rt; \ return _Expr<_Closure, _Rt>(_Closure(__v, __t)); \ } \ \ template \ inline _Expr<_BinClos<_Name, _Constant, _ValArray, _Tp, _Tp>, \ typename __fun<_Name, _Tp>::result_type> \ operator _Op(const _Tp& __t, const valarray<_Tp>& __v) \ { \ typedef _BinClos<_Name, _Constant, _ValArray, _Tp, _Tp> _Closure; \ typedef typename __fun<_Name, _Tp>::result_type _Rt; \ return _Expr<_Closure, _Rt>(_Closure(__t, __v)); \ } _DEFINE_BINARY_OPERATOR(+, __plus) _DEFINE_BINARY_OPERATOR(-, __minus) _DEFINE_BINARY_OPERATOR(*, __multiplies) _DEFINE_BINARY_OPERATOR(/, __divides) _DEFINE_BINARY_OPERATOR(%, __modulus) _DEFINE_BINARY_OPERATOR(^, __bitwise_xor) _DEFINE_BINARY_OPERATOR(&, __bitwise_and) _DEFINE_BINARY_OPERATOR(|, __bitwise_or) _DEFINE_BINARY_OPERATOR(<<, __shift_left) _DEFINE_BINARY_OPERATOR(>>, __shift_right) _DEFINE_BINARY_OPERATOR(&&, __logical_and) _DEFINE_BINARY_OPERATOR(||, __logical_or) _DEFINE_BINARY_OPERATOR(==, __equal_to) _DEFINE_BINARY_OPERATOR(!=, __not_equal_to) _DEFINE_BINARY_OPERATOR(<, __less) _DEFINE_BINARY_OPERATOR(>, __greater) _DEFINE_BINARY_OPERATOR(<=, __less_equal) _DEFINE_BINARY_OPERATOR(>=, __greater_equal) #undef _DEFINE_BINARY_OPERATOR #if __cplusplus >= 201103L /** * @brief Return an iterator pointing to the first element of * the valarray. * @param __va valarray. */ template inline _Tp* begin(valarray<_Tp>& __va) { return std::__addressof(__va[0]); } /** * @brief Return an iterator pointing to the first element of * the const valarray. * @param __va valarray. */ template inline const _Tp* begin(const valarray<_Tp>& __va) { return std::__addressof(__va[0]); } /** * @brief Return an iterator pointing to one past the last element of * the valarray. * @param __va valarray. */ template inline _Tp* end(valarray<_Tp>& __va) { return std::__addressof(__va[0]) + __va.size(); } /** * @brief Return an iterator pointing to one past the last element of * the const valarray. * @param __va valarray. */ template inline const _Tp* end(const valarray<_Tp>& __va) { return std::__addressof(__va[0]) + __va.size(); } #endif // C++11 // @} group numeric_arrays _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GLIBCXX_VALARRAY */ c++/8/unordered_set000064400000003467151027430570010066 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/unordered_set * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_UNORDERED_SET #define _GLIBCXX_UNORDERED_SET 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include // equal_to, _Identity, _Select1st #include #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif // C++11 #endif // _GLIBCXX_UNORDERED_SET c++/8/cuchar000064400000004242151027430570006461 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cuchar * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c uchar.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882:2011 21.8 // #ifndef _GLIBCXX_CUCHAR #define _GLIBCXX_CUCHAR 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #if _GLIBCXX_USE_C11_UCHAR_CXX11 #include // Get rid of those macros defined in in lieu of real functions. #undef mbrtoc16 #undef c16rtomb #undef mbrtoc32 #undef c32rtomb namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::mbrtoc16; using ::c16rtomb; using ::mbrtoc32; using ::c32rtomb; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _GLIBCXX_USE_C11_UCHAR_CXX11 #endif // C++11 #endif // _GLIBCXX_CUCHAR c++/8/fenv.h000064400000003744151027430570006406 0ustar00// -*- C++ -*- compatibility header. // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file fenv.h * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FENV_H #define _GLIBCXX_FENV_H 1 #pragma GCC system_header #include #if _GLIBCXX_HAVE_FENV_H # include_next #endif #if __cplusplus >= 201103L #if _GLIBCXX_USE_C99_FENV_TR1 #undef feclearexcept #undef fegetexceptflag #undef feraiseexcept #undef fesetexceptflag #undef fetestexcept #undef fegetround #undef fesetround #undef fegetenv #undef feholdexcept #undef fesetenv #undef feupdateenv namespace std { // types using ::fenv_t; using ::fexcept_t; // functions using ::feclearexcept; using ::fegetexceptflag; using ::feraiseexcept; using ::fesetexceptflag; using ::fetestexcept; using ::fegetround; using ::fesetround; using ::fegetenv; using ::feholdexcept; using ::fesetenv; using ::feupdateenv; } // namespace #endif // _GLIBCXX_USE_C99_FENV_TR1 #endif // C++11 #endif // _GLIBCXX_FENV_H c++/8/array000064400000026611151027430570006336 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/array * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_ARRAY #define _GLIBCXX_ARRAY 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_CONTAINER template struct __array_traits { typedef _Tp _Type[_Nm]; typedef __is_swappable<_Tp> _Is_swappable; typedef __is_nothrow_swappable<_Tp> _Is_nothrow_swappable; static constexpr _Tp& _S_ref(const _Type& __t, std::size_t __n) noexcept { return const_cast<_Tp&>(__t[__n]); } static constexpr _Tp* _S_ptr(const _Type& __t) noexcept { return const_cast<_Tp*>(__t); } }; template struct __array_traits<_Tp, 0> { struct _Type { }; typedef true_type _Is_swappable; typedef true_type _Is_nothrow_swappable; static constexpr _Tp& _S_ref(const _Type&, std::size_t) noexcept { return *static_cast<_Tp*>(nullptr); } static constexpr _Tp* _S_ptr(const _Type&) noexcept { return nullptr; } }; /** * @brief A standard container for storing a fixed size sequence of elements. * * @ingroup sequences * * Meets the requirements of a container, a * reversible container, and a * sequence. * * Sets support random access iterators. * * @tparam Tp Type of element. Required to be a complete type. * @tparam N Number of elements. */ template struct array { typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef value_type* iterator; typedef const value_type* const_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // Support for zero-sized arrays mandatory. typedef _GLIBCXX_STD_C::__array_traits<_Tp, _Nm> _AT_Type; typename _AT_Type::_Type _M_elems; // No explicit construct/copy/destroy for aggregate type. // DR 776. void fill(const value_type& __u) { std::fill_n(begin(), size(), __u); } void swap(array& __other) noexcept(_AT_Type::_Is_nothrow_swappable::value) { std::swap_ranges(begin(), end(), __other.begin()); } // Iterators. _GLIBCXX17_CONSTEXPR iterator begin() noexcept { return iterator(data()); } _GLIBCXX17_CONSTEXPR const_iterator begin() const noexcept { return const_iterator(data()); } _GLIBCXX17_CONSTEXPR iterator end() noexcept { return iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR const_iterator end() const noexcept { return const_iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR reverse_iterator rend() noexcept { return reverse_iterator(begin()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } _GLIBCXX17_CONSTEXPR const_iterator cbegin() const noexcept { return const_iterator(data()); } _GLIBCXX17_CONSTEXPR const_iterator cend() const noexcept { return const_iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } // Capacity. constexpr size_type size() const noexcept { return _Nm; } constexpr size_type max_size() const noexcept { return _Nm; } constexpr bool empty() const noexcept { return size() == 0; } // Element access. _GLIBCXX17_CONSTEXPR reference operator[](size_type __n) noexcept { return _AT_Type::_S_ref(_M_elems, __n); } constexpr const_reference operator[](size_type __n) const noexcept { return _AT_Type::_S_ref(_M_elems, __n); } _GLIBCXX17_CONSTEXPR reference at(size_type __n) { if (__n >= _Nm) std::__throw_out_of_range_fmt(__N("array::at: __n (which is %zu) " ">= _Nm (which is %zu)"), __n, _Nm); return _AT_Type::_S_ref(_M_elems, __n); } constexpr const_reference at(size_type __n) const { // Result of conditional expression must be an lvalue so use // boolean ? lvalue : (throw-expr, lvalue) return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n) : (std::__throw_out_of_range_fmt(__N("array::at: __n (which is %zu) " ">= _Nm (which is %zu)"), __n, _Nm), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference front() noexcept { return *begin(); } constexpr const_reference front() const noexcept { return _AT_Type::_S_ref(_M_elems, 0); } _GLIBCXX17_CONSTEXPR reference back() noexcept { return _Nm ? *(end() - 1) : *end(); } constexpr const_reference back() const noexcept { return _Nm ? _AT_Type::_S_ref(_M_elems, _Nm - 1) : _AT_Type::_S_ref(_M_elems, 0); } _GLIBCXX17_CONSTEXPR pointer data() noexcept { return _AT_Type::_S_ptr(_M_elems); } _GLIBCXX17_CONSTEXPR const_pointer data() const noexcept { return _AT_Type::_S_ptr(_M_elems); } }; #if __cpp_deduction_guides >= 201606 template array(_Tp, _Up...) -> array && ...), _Tp>, 1 + sizeof...(_Up)>; #endif // Array comparisons. template inline bool operator==(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return std::equal(__one.begin(), __one.end(), __two.begin()); } template inline bool operator!=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one == __two); } template inline bool operator<(const array<_Tp, _Nm>& __a, const array<_Tp, _Nm>& __b) { return std::lexicographical_compare(__a.begin(), __a.end(), __b.begin(), __b.end()); } template inline bool operator>(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return __two < __one; } template inline bool operator<=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one > __two); } template inline bool operator>=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one < __two); } // Specialized algorithms. template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if< _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>::_Is_swappable::value >::type #else void #endif swap(array<_Tp, _Nm>& __one, array<_Tp, _Nm>& __two) noexcept(noexcept(__one.swap(__two))) { __one.swap(__two); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if< !_GLIBCXX_STD_C::__array_traits<_Tp, _Nm>::_Is_swappable::value>::type swap(array<_Tp, _Nm>&, array<_Tp, _Nm>&) = delete; #endif template constexpr _Tp& get(array<_Tp, _Nm>& __arr) noexcept { static_assert(_Int < _Nm, "array index is within bounds"); return _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>:: _S_ref(__arr._M_elems, _Int); } template constexpr _Tp&& get(array<_Tp, _Nm>&& __arr) noexcept { static_assert(_Int < _Nm, "array index is within bounds"); return std::move(_GLIBCXX_STD_C::get<_Int>(__arr)); } template constexpr const _Tp& get(const array<_Tp, _Nm>& __arr) noexcept { static_assert(_Int < _Nm, "array index is within bounds"); return _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>:: _S_ref(__arr._M_elems, _Int); } template constexpr const _Tp&& get(const array<_Tp, _Nm>&& __arr) noexcept { static_assert(_Int < _Nm, "array index is within bounds"); return std::move(_GLIBCXX_STD_C::get<_Int>(__arr)); } _GLIBCXX_END_NAMESPACE_CONTAINER } // namespace std namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Tuple interface to class template array. /// tuple_size template struct tuple_size; /// Partial specialization for std::array template struct tuple_size<_GLIBCXX_STD_C::array<_Tp, _Nm>> : public integral_constant { }; /// tuple_element template struct tuple_element; /// Partial specialization for std::array template struct tuple_element<_Int, _GLIBCXX_STD_C::array<_Tp, _Nm>> { static_assert(_Int < _Nm, "index is out of bounds"); typedef _Tp type; }; template struct __is_tuple_like_impl<_GLIBCXX_STD_C::array<_Tp, _Nm>> : true_type { }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif // C++11 #endif // _GLIBCXX_ARRAY c++/8/exception000064400000011303151027430570007206 0ustar00// Exception Handling support header for -*- C++ -*- // Copyright (C) 1995-2018 Free Software Foundation, Inc. // // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file exception * This is a Standard C++ Library header. */ #ifndef __EXCEPTION__ #define __EXCEPTION__ #pragma GCC system_header #pragma GCC visibility push(default) #include #include extern "C++" { namespace std { /** If an %exception is thrown which is not listed in a function's * %exception specification, one of these may be thrown. */ class bad_exception : public exception { public: bad_exception() _GLIBCXX_USE_NOEXCEPT { } // This declaration is not useless: // http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_6.html#SEC118 virtual ~bad_exception() _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; // See comment in eh_exception.cc. virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_USE_NOEXCEPT; }; /// If you write a replacement %terminate handler, it must be of this type. typedef void (*terminate_handler) (); /// If you write a replacement %unexpected handler, it must be of this type. typedef void (*unexpected_handler) (); /// Takes a new handler function as an argument, returns the old function. terminate_handler set_terminate(terminate_handler) _GLIBCXX_USE_NOEXCEPT; #if __cplusplus >= 201103L /// Return the current terminate handler. terminate_handler get_terminate() noexcept; #endif /** The runtime will call this function if %exception handling must be * abandoned for any reason. It can also be called by the user. */ void terminate() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__noreturn__)); /// Takes a new handler function as an argument, returns the old function. unexpected_handler set_unexpected(unexpected_handler) _GLIBCXX_USE_NOEXCEPT; #if __cplusplus >= 201103L /// Return the current unexpected handler. unexpected_handler get_unexpected() noexcept; #endif /** The runtime will call this function if an %exception is thrown which * violates the function's %exception specification. */ void unexpected() __attribute__ ((__noreturn__)); /** [18.6.4]/1: 'Returns true after completing evaluation of a * throw-expression until either completing initialization of the * exception-declaration in the matching handler or entering @c unexpected() * due to the throw; or after entering @c terminate() for any reason * other than an explicit call to @c terminate(). [Note: This includes * stack unwinding [15.2]. end note]' * * 2: 'When @c uncaught_exception() is true, throwing an * %exception can result in a call of @c terminate() * (15.5.1).' */ _GLIBCXX17_DEPRECATED bool uncaught_exception() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); #if __cplusplus >= 201703L || !defined(__STRICT_ANSI__) // c++17 or gnu++98 #define __cpp_lib_uncaught_exceptions 201411L /// The number of uncaught exceptions. int uncaught_exceptions() _GLIBCXX_USE_NOEXCEPT __attribute__ ((__pure__)); #endif // @} group exceptions } // namespace std namespace __gnu_cxx { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief A replacement for the standard terminate_handler which * prints more information about the terminating exception (if any) * on stderr. * * @ingroup exceptions * * Call * @code * std::set_terminate(__gnu_cxx::__verbose_terminate_handler) * @endcode * to use. For more info, see * http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt02ch06s02.html * * In 3.4 and later, this is on by default. */ void __verbose_terminate_handler(); _GLIBCXX_END_NAMESPACE_VERSION } // namespace } // extern "C++" #pragma GCC visibility pop #if (__cplusplus >= 201103L) #include #include #endif #endif c++/8/deque000064400000005151151027430570006317 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/deque * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_DEQUE #define _GLIBCXX_DEQUE 1 #pragma GCC system_header #include #include #include #include #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_DEQUE */ c++/8/string_view000064400000050467151027430570007566 0ustar00// Components for manipulating non-owning sequences of characters -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file string_view * This is a Standard C++ Library header. */ // // N3762 basic_string_view library // #ifndef _GLIBCXX_STRING_VIEW #define _GLIBCXX_STRING_VIEW 1 #pragma GCC system_header #if __cplusplus >= 201703L #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #define __cpp_lib_string_view 201603 /** * @class basic_string_view * @brief A non-owning reference to a string. * * @ingroup strings * @ingroup sequences * * @tparam _CharT Type of character * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * A basic_string_view looks like this: * * @code * _CharT* _M_str * size_t _M_len * @endcode */ template> class basic_string_view { public: // types using traits_type = _Traits; using value_type = _CharT; using pointer = const _CharT*; using const_pointer = const _CharT*; using reference = const _CharT&; using const_reference = const _CharT&; using const_iterator = const _CharT*; using iterator = const_iterator; using const_reverse_iterator = std::reverse_iterator; using reverse_iterator = const_reverse_iterator; using size_type = size_t; using difference_type = ptrdiff_t; static constexpr size_type npos = size_type(-1); // [string.view.cons], construct/copy constexpr basic_string_view() noexcept : _M_len{0}, _M_str{nullptr} { } constexpr basic_string_view(const basic_string_view&) noexcept = default; constexpr basic_string_view(const _CharT* __str) noexcept : _M_len{__str == nullptr ? 0 : traits_type::length(__str)}, _M_str{__str} { } constexpr basic_string_view(const _CharT* __str, size_type __len) noexcept : _M_len{__len}, _M_str{__str} { } constexpr basic_string_view& operator=(const basic_string_view&) noexcept = default; // [string.view.iterators], iterators constexpr const_iterator begin() const noexcept { return this->_M_str; } constexpr const_iterator end() const noexcept { return this->_M_str + this->_M_len; } constexpr const_iterator cbegin() const noexcept { return this->_M_str; } constexpr const_iterator cend() const noexcept { return this->_M_str + this->_M_len; } constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(this->end()); } constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator(this->begin()); } constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(this->end()); } constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(this->begin()); } // [string.view.capacity], capacity constexpr size_type size() const noexcept { return this->_M_len; } constexpr size_type length() const noexcept { return _M_len; } constexpr size_type max_size() const noexcept { return (npos - sizeof(size_type) - sizeof(void*)) / sizeof(value_type) / 4; } [[nodiscard]] constexpr bool empty() const noexcept { return this->_M_len == 0; } // [string.view.access], element access constexpr const _CharT& operator[](size_type __pos) const noexcept { __glibcxx_assert(__pos < this->_M_len); return *(this->_M_str + __pos); } constexpr const _CharT& at(size_type __pos) const { if (__pos >= _M_len) __throw_out_of_range_fmt(__N("basic_string_view::at: __pos " "(which is %zu) >= this->size() " "(which is %zu)"), __pos, this->size()); return *(this->_M_str + __pos); } constexpr const _CharT& front() const noexcept { __glibcxx_assert(this->_M_len > 0); return *this->_M_str; } constexpr const _CharT& back() const noexcept { __glibcxx_assert(this->_M_len > 0); return *(this->_M_str + this->_M_len - 1); } constexpr const _CharT* data() const noexcept { return this->_M_str; } // [string.view.modifiers], modifiers: constexpr void remove_prefix(size_type __n) noexcept { __glibcxx_assert(this->_M_len >= __n); this->_M_str += __n; this->_M_len -= __n; } constexpr void remove_suffix(size_type __n) noexcept { this->_M_len -= __n; } constexpr void swap(basic_string_view& __sv) noexcept { auto __tmp = *this; *this = __sv; __sv = __tmp; } // [string.view.ops], string operations: size_type copy(_CharT* __str, size_type __n, size_type __pos = 0) const { __glibcxx_requires_string_len(__str, __n); __pos = _M_check(__pos, "basic_string_view::copy"); const size_type __rlen = std::min(__n, _M_len - __pos); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2777. basic_string_view::copy should use char_traits::copy traits_type::copy(__str, data() + __pos, __rlen); return __rlen; } constexpr basic_string_view substr(size_type __pos = 0, size_type __n = npos) const noexcept(false) { __pos = _M_check(__pos, "basic_string_view::substr"); const size_type __rlen = std::min(__n, _M_len - __pos); return basic_string_view{_M_str + __pos, __rlen}; } constexpr int compare(basic_string_view __str) const noexcept { const size_type __rlen = std::min(this->_M_len, __str._M_len); int __ret = traits_type::compare(this->_M_str, __str._M_str, __rlen); if (__ret == 0) __ret = _S_compare(this->_M_len, __str._M_len); return __ret; } constexpr int compare(size_type __pos1, size_type __n1, basic_string_view __str) const { return this->substr(__pos1, __n1).compare(__str); } constexpr int compare(size_type __pos1, size_type __n1, basic_string_view __str, size_type __pos2, size_type __n2) const { return this->substr(__pos1, __n1).compare(__str.substr(__pos2, __n2)); } constexpr int compare(const _CharT* __str) const noexcept { return this->compare(basic_string_view{__str}); } constexpr int compare(size_type __pos1, size_type __n1, const _CharT* __str) const { return this->substr(__pos1, __n1).compare(basic_string_view{__str}); } constexpr int compare(size_type __pos1, size_type __n1, const _CharT* __str, size_type __n2) const noexcept(false) { return this->substr(__pos1, __n1) .compare(basic_string_view(__str, __n2)); } constexpr size_type find(basic_string_view __str, size_type __pos = 0) const noexcept { return this->find(__str._M_str, __pos, __str._M_len); } constexpr size_type find(_CharT __c, size_type __pos = 0) const noexcept; constexpr size_type find(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type find(const _CharT* __str, size_type __pos = 0) const noexcept { return this->find(__str, __pos, traits_type::length(__str)); } constexpr size_type rfind(basic_string_view __str, size_type __pos = npos) const noexcept { return this->rfind(__str._M_str, __pos, __str._M_len); } constexpr size_type rfind(_CharT __c, size_type __pos = npos) const noexcept; constexpr size_type rfind(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type rfind(const _CharT* __str, size_type __pos = npos) const noexcept { return this->rfind(__str, __pos, traits_type::length(__str)); } constexpr size_type find_first_of(basic_string_view __str, size_type __pos = 0) const noexcept { return this->find_first_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_first_of(_CharT __c, size_type __pos = 0) const noexcept { return this->find(__c, __pos); } constexpr size_type find_first_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type find_first_of(const _CharT* __str, size_type __pos = 0) const noexcept { return this->find_first_of(__str, __pos, traits_type::length(__str)); } constexpr size_type find_last_of(basic_string_view __str, size_type __pos = npos) const noexcept { return this->find_last_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_last_of(_CharT __c, size_type __pos=npos) const noexcept { return this->rfind(__c, __pos); } constexpr size_type find_last_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type find_last_of(const _CharT* __str, size_type __pos = npos) const noexcept { return this->find_last_of(__str, __pos, traits_type::length(__str)); } constexpr size_type find_first_not_of(basic_string_view __str, size_type __pos = 0) const noexcept { return this->find_first_not_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_first_not_of(_CharT __c, size_type __pos = 0) const noexcept; constexpr size_type find_first_not_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type find_first_not_of(const _CharT* __str, size_type __pos = 0) const noexcept { return this->find_first_not_of(__str, __pos, traits_type::length(__str)); } constexpr size_type find_last_not_of(basic_string_view __str, size_type __pos = npos) const noexcept { return this->find_last_not_of(__str._M_str, __pos, __str._M_len); } constexpr size_type find_last_not_of(_CharT __c, size_type __pos = npos) const noexcept; constexpr size_type find_last_not_of(const _CharT* __str, size_type __pos, size_type __n) const noexcept; constexpr size_type find_last_not_of(const _CharT* __str, size_type __pos = npos) const noexcept { return this->find_last_not_of(__str, __pos, traits_type::length(__str)); } constexpr size_type _M_check(size_type __pos, const char* __s) const noexcept(false) { if (__pos > this->size()) __throw_out_of_range_fmt(__N("%s: __pos (which is %zu) > " "this->size() (which is %zu)"), __s, __pos, this->size()); return __pos; } // NB: _M_limit doesn't check for a bad __pos value. constexpr size_type _M_limit(size_type __pos, size_type __off) const noexcept { const bool __testoff = __off < this->size() - __pos; return __testoff ? __off : this->size() - __pos; } private: static constexpr int _S_compare(size_type __n1, size_type __n2) noexcept { const difference_type __diff = __n1 - __n2; if (__diff > std::numeric_limits::max()) return std::numeric_limits::max(); if (__diff < std::numeric_limits::min()) return std::numeric_limits::min(); return static_cast(__diff); } size_t _M_len; const _CharT* _M_str; }; // [string.view.comparison], non-member basic_string_view comparison function namespace __detail { // Identity transform to create a non-deduced context, so that only one // argument participates in template argument deduction and the other // argument gets implicitly converted to the deduced type. See n3766.html. template using __idt = common_type_t<_Tp>; } template constexpr bool operator==(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.size() == __y.size() && __x.compare(__y) == 0; } template constexpr bool operator==(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.size() == __y.size() && __x.compare(__y) == 0; } template constexpr bool operator==(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.size() == __y.size() && __x.compare(__y) == 0; } template constexpr bool operator!=(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return !(__x == __y); } template constexpr bool operator!=(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return !(__x == __y); } template constexpr bool operator!=(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return !(__x == __y); } template constexpr bool operator< (basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) < 0; } template constexpr bool operator< (basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) < 0; } template constexpr bool operator< (__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) < 0; } template constexpr bool operator> (basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) > 0; } template constexpr bool operator> (basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) > 0; } template constexpr bool operator> (__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) > 0; } template constexpr bool operator<=(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) <= 0; } template constexpr bool operator<=(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) <= 0; } template constexpr bool operator<=(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) <= 0; } template constexpr bool operator>=(basic_string_view<_CharT, _Traits> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) >= 0; } template constexpr bool operator>=(basic_string_view<_CharT, _Traits> __x, __detail::__idt> __y) noexcept { return __x.compare(__y) >= 0; } template constexpr bool operator>=(__detail::__idt> __x, basic_string_view<_CharT, _Traits> __y) noexcept { return __x.compare(__y) >= 0; } // [string.view.io], Inserters and extractors template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, basic_string_view<_CharT,_Traits> __str) { return __ostream_insert(__os, __str.data(), __str.size()); } // basic_string_view typedef names using string_view = basic_string_view; #ifdef _GLIBCXX_USE_WCHAR_T using wstring_view = basic_string_view; #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 using u16string_view = basic_string_view; using u32string_view = basic_string_view; #endif // [string.view.hash], hash support: template struct hash; template<> struct hash : public __hash_base { size_t operator()(const string_view& __str) const noexcept { return std::_Hash_impl::hash(__str.data(), __str.length()); } }; template<> struct __is_fast_hash> : std::false_type { }; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct hash : public __hash_base { size_t operator()(const wstring_view& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(wchar_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 template<> struct hash : public __hash_base { size_t operator()(const u16string_view& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char16_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; template<> struct hash : public __hash_base { size_t operator()(const u32string_view& __s) const noexcept { return std::_Hash_impl::hash(__s.data(), __s.length() * sizeof(char32_t)); } }; template<> struct __is_fast_hash> : std::false_type { }; #endif inline namespace literals { inline namespace string_view_literals { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" inline constexpr basic_string_view operator""sv(const char* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } #ifdef _GLIBCXX_USE_WCHAR_T inline constexpr basic_string_view operator""sv(const wchar_t* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } #endif #ifdef _GLIBCXX_USE_C99_STDINT_TR1 inline constexpr basic_string_view operator""sv(const char16_t* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } inline constexpr basic_string_view operator""sv(const char32_t* __str, size_t __len) noexcept { return basic_string_view{__str, __len}; } #endif #pragma GCC diagnostic pop } // namespace string_literals } // namespace literals _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #include #endif // __cplusplus <= 201402L #endif // _GLIBCXX_EXPERIMENTAL_STRING_VIEW c++/8/parallel/tags.h000064400000013536151027430570010202 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file parallel/tags.h * @brief Tags for compile-time selection. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_TAGS_H #define _GLIBCXX_PARALLEL_TAGS_H 1 #include #include namespace __gnu_parallel { /** @brief Forces sequential execution at compile time. */ struct sequential_tag { }; /** @brief Recommends parallel execution at compile time, * optionally using a user-specified number of threads. */ struct parallel_tag { private: _ThreadIndex _M_num_threads; public: /** @brief Default constructor. Use default number of threads. */ parallel_tag() { _M_num_threads = 0; } /** @brief Default constructor. Recommend number of threads to use. * @param __num_threads Desired number of threads. */ parallel_tag(_ThreadIndex __num_threads) { _M_num_threads = __num_threads; } /** @brief Find out desired number of threads. * @return Desired number of threads. */ _ThreadIndex __get_num_threads() { if(_M_num_threads == 0) return omp_get_max_threads(); else return _M_num_threads; } /** @brief Set the desired number of threads. * @param __num_threads Desired number of threads. */ void set_num_threads(_ThreadIndex __num_threads) { _M_num_threads = __num_threads; } }; /** @brief Recommends parallel execution using the default parallel algorithm. */ struct default_parallel_tag : public parallel_tag { default_parallel_tag() { } default_parallel_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Recommends parallel execution using dynamic load-balancing at compile time. */ struct balanced_tag : public parallel_tag { }; /** @brief Recommends parallel execution using static load-balancing at compile time. */ struct unbalanced_tag : public parallel_tag { }; /** @brief Recommends parallel execution using OpenMP dynamic load-balancing at compile time. */ struct omp_loop_tag : public parallel_tag { }; /** @brief Recommends parallel execution using OpenMP static load-balancing at compile time. */ struct omp_loop_static_tag : public parallel_tag { }; /** @brief Base class for for std::find() variants. */ struct find_tag { }; /** @brief Forces parallel merging * with exact splitting, at compile time. */ struct exact_tag : public parallel_tag { exact_tag() { } exact_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Forces parallel merging * with exact splitting, at compile time. */ struct sampling_tag : public parallel_tag { sampling_tag() { } sampling_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Forces parallel sorting using multiway mergesort * at compile time. */ struct multiway_mergesort_tag : public parallel_tag { multiway_mergesort_tag() { } multiway_mergesort_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Forces parallel sorting using multiway mergesort * with exact splitting at compile time. */ struct multiway_mergesort_exact_tag : public parallel_tag { multiway_mergesort_exact_tag() { } multiway_mergesort_exact_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Forces parallel sorting using multiway mergesort * with splitting by sampling at compile time. */ struct multiway_mergesort_sampling_tag : public parallel_tag { multiway_mergesort_sampling_tag() { } multiway_mergesort_sampling_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Forces parallel sorting using unbalanced quicksort * at compile time. */ struct quicksort_tag : public parallel_tag { quicksort_tag() { } quicksort_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Forces parallel sorting using balanced quicksort * at compile time. */ struct balanced_quicksort_tag : public parallel_tag { balanced_quicksort_tag() { } balanced_quicksort_tag(_ThreadIndex __num_threads) : parallel_tag(__num_threads) { } }; /** @brief Selects the growing block size variant for std::find(). @see _GLIBCXX_FIND_GROWING_BLOCKS */ struct growing_blocks_tag : public find_tag { }; /** @brief Selects the constant block size variant for std::find(). @see _GLIBCXX_FIND_CONSTANT_SIZE_BLOCKS */ struct constant_size_blocks_tag : public find_tag { }; /** @brief Selects the equal splitting variant for std::find(). @see _GLIBCXX_FIND_EQUAL_SPLIT */ struct equal_split_tag : public find_tag { }; } #endif /* _GLIBCXX_PARALLEL_TAGS_H */ c++/8/parallel/sort.h000064400000017035151027430570010231 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/sort.h * @brief Parallel sorting algorithm switch. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_SORT_H #define _GLIBCXX_PARALLEL_SORT_H 1 #include #include #include #if _GLIBCXX_PARALLEL_ASSERTIONS #include #endif #if _GLIBCXX_MERGESORT #include #endif #if _GLIBCXX_QUICKSORT #include #endif #if _GLIBCXX_BAL_QUICKSORT #include #endif namespace __gnu_parallel { //prototype template void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, _Parallelism __parallelism); /** * @brief Choose multiway mergesort, splitting variant at run-time, * for parallel sorting. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, multiway_mergesort_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) if(_Settings::get().sort_splitting == EXACT) parallel_sort_mwms<__stable, true> (__begin, __end, __comp, __parallelism.__get_num_threads()); else parallel_sort_mwms<__stable, false> (__begin, __end, __comp, __parallelism.__get_num_threads()); } /** * @brief Choose multiway mergesort with exact splitting, * for parallel sorting. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, multiway_mergesort_exact_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) parallel_sort_mwms<__stable, true> (__begin, __end, __comp, __parallelism.__get_num_threads()); } /** * @brief Choose multiway mergesort with splitting by sampling, * for parallel sorting. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, multiway_mergesort_sampling_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) parallel_sort_mwms<__stable, false> (__begin, __end, __comp, __parallelism.__get_num_threads()); } /** * @brief Choose quicksort for parallel sorting. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, quicksort_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) _GLIBCXX_PARALLEL_ASSERT(__stable == false); __parallel_sort_qs(__begin, __end, __comp, __parallelism.__get_num_threads()); } /** * @brief Choose balanced quicksort for parallel sorting. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, balanced_quicksort_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) _GLIBCXX_PARALLEL_ASSERT(__stable == false); __parallel_sort_qsb(__begin, __end, __comp, __parallelism.__get_num_threads()); } /** * @brief Choose multiway mergesort with exact splitting, * for parallel sorting. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, default_parallel_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) __parallel_sort<__stable> (__begin, __end, __comp, multiway_mergesort_exact_tag(__parallelism.__get_num_threads())); } /** * @brief Choose a parallel sorting algorithm. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __comp Comparator. * @tparam __stable Sort stable. * @callgraph */ template inline void __parallel_sort(_RAIter __begin, _RAIter __end, _Compare __comp, parallel_tag __parallelism) { _GLIBCXX_CALL(__end - __begin) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; if (false) ; #if _GLIBCXX_MERGESORT else if (__stable || _Settings::get().sort_algorithm == MWMS) { if(_Settings::get().sort_splitting == EXACT) parallel_sort_mwms<__stable, true> (__begin, __end, __comp, __parallelism.__get_num_threads()); else parallel_sort_mwms (__begin, __end, __comp, __parallelism.__get_num_threads()); } #endif #if _GLIBCXX_QUICKSORT else if (_Settings::get().sort_algorithm == QS) __parallel_sort_qs(__begin, __end, __comp, __parallelism.__get_num_threads()); #endif #if _GLIBCXX_BAL_QUICKSORT else if (_Settings::get().sort_algorithm == QS_BALANCED) __parallel_sort_qsb(__begin, __end, __comp, __parallelism.__get_num_threads()); #endif else __gnu_sequential::sort(__begin, __end, __comp); } } // end namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_SORT_H */ c++/8/parallel/merge.h000064400000022552151027430570010341 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/merge.h * @brief Parallel implementation of std::merge(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_MERGE_H #define _GLIBCXX_PARALLEL_MERGE_H 1 #include #include namespace __gnu_parallel { /** @brief Merge routine being able to merge only the @c __max_length * smallest elements. * * The @c __begin iterators are advanced accordingly, they might not * reach @c __end, in contrast to the usual variant. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __target Target begin iterator. * @param __max_length Maximum number of elements to merge. * @param __comp Comparator. * @return Output end iterator. */ template _OutputIterator __merge_advance_usual(_RAIter1& __begin1, _RAIter1 __end1, _RAIter2& __begin2, _RAIter2 __end2, _OutputIterator __target, _DifferenceTp __max_length, _Compare __comp) { typedef _DifferenceTp _DifferenceType; while (__begin1 != __end1 && __begin2 != __end2 && __max_length > 0) { // array1[__i1] < array0[i0] if (__comp(*__begin2, *__begin1)) *__target++ = *__begin2++; else *__target++ = *__begin1++; --__max_length; } if (__begin1 != __end1) { __target = std::copy(__begin1, __begin1 + __max_length, __target); __begin1 += __max_length; } else { __target = std::copy(__begin2, __begin2 + __max_length, __target); __begin2 += __max_length; } return __target; } /** @brief Merge routine being able to merge only the @c __max_length * smallest elements. * * The @c __begin iterators are advanced accordingly, they might not * reach @c __end, in contrast to the usual variant. * Specially designed code should allow the compiler to generate * conditional moves instead of branches. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __target Target begin iterator. * @param __max_length Maximum number of elements to merge. * @param __comp Comparator. * @return Output end iterator. */ template _OutputIterator __merge_advance_movc(_RAIter1& __begin1, _RAIter1 __end1, _RAIter2& __begin2, _RAIter2 __end2, _OutputIterator __target, _DifferenceTp __max_length, _Compare __comp) { typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_RAIter2>::value_type _ValueType2; #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__max_length >= 0); #endif while (__begin1 != __end1 && __begin2 != __end2 && __max_length > 0) { _RAIter1 __next1 = __begin1 + 1; _RAIter2 __next2 = __begin2 + 1; _ValueType1 __element1 = *__begin1; _ValueType2 __element2 = *__begin2; if (__comp(__element2, __element1)) { __element1 = __element2; __begin2 = __next2; } else __begin1 = __next1; *__target = __element1; ++__target; --__max_length; } if (__begin1 != __end1) { __target = std::copy(__begin1, __begin1 + __max_length, __target); __begin1 += __max_length; } else { __target = std::copy(__begin2, __begin2 + __max_length, __target); __begin2 += __max_length; } return __target; } /** @brief Merge routine being able to merge only the @c __max_length * smallest elements. * * The @c __begin iterators are advanced accordingly, they might not * reach @c __end, in contrast to the usual variant. * Static switch on whether to use the conditional-move variant. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __target Target begin iterator. * @param __max_length Maximum number of elements to merge. * @param __comp Comparator. * @return Output end iterator. */ template inline _OutputIterator __merge_advance(_RAIter1& __begin1, _RAIter1 __end1, _RAIter2& __begin2, _RAIter2 __end2, _OutputIterator __target, _DifferenceTp __max_length, _Compare __comp) { _GLIBCXX_CALL(__max_length) return __merge_advance_movc(__begin1, __end1, __begin2, __end2, __target, __max_length, __comp); } /** @brief Merge routine fallback to sequential in case the iterators of the two input sequences are of different type. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __target Target begin iterator. * @param __max_length Maximum number of elements to merge. * @param __comp Comparator. * @return Output end iterator. */ template inline _RAIter3 __parallel_merge_advance(_RAIter1& __begin1, _RAIter1 __end1, _RAIter2& __begin2, // different iterators, parallel implementation // not available _RAIter2 __end2, _RAIter3 __target, typename std::iterator_traits<_RAIter1>:: difference_type __max_length, _Compare __comp) { return __merge_advance(__begin1, __end1, __begin2, __end2, __target, __max_length, __comp); } /** @brief Parallel merge routine being able to merge only the @c * __max_length smallest elements. * * The @c __begin iterators are advanced accordingly, they might not * reach @c __end, in contrast to the usual variant. * The functionality is projected onto parallel_multiway_merge. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __target Target begin iterator. * @param __max_length Maximum number of elements to merge. * @param __comp Comparator. * @return Output end iterator. */ template inline _RAIter3 __parallel_merge_advance(_RAIter1& __begin1, _RAIter1 __end1, _RAIter1& __begin2, _RAIter1 __end2, _RAIter3 __target, typename std::iterator_traits<_RAIter1>:: difference_type __max_length, _Compare __comp) { typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; typedef typename std::iterator_traits<_RAIter1>:: difference_type _DifferenceType1 /* == difference_type2 */; typedef typename std::iterator_traits<_RAIter3>:: difference_type _DifferenceType3; typedef typename std::pair<_RAIter1, _RAIter1> _IteratorPair; _IteratorPair __seqs[2] = { std::make_pair(__begin1, __end1), std::make_pair(__begin2, __end2) }; _RAIter3 __target_end = parallel_multiway_merge < /* __stable = */ true, /* __sentinels = */ false> (__seqs, __seqs + 2, __target, multiway_merge_exact_splitting < /* __stable = */ true, _IteratorPair*, _Compare, _DifferenceType1>, __max_length, __comp, omp_get_max_threads()); return __target_end; } } //namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_MERGE_H */ c++/8/parallel/quicksort.h000064400000013756151027430570011274 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/quicksort.h * @brief Implementation of a unbalanced parallel quicksort (in-place). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_QUICKSORT_H #define _GLIBCXX_PARALLEL_QUICKSORT_H 1 #include #include namespace __gnu_parallel { /** @brief Unbalanced quicksort divide step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __pivot_rank Desired __rank of the pivot. * @param __num_samples Choose pivot from that many samples. * @param __num_threads Number of threads that are allowed to work on * this part. */ template typename std::iterator_traits<_RAIter>::difference_type __parallel_sort_qs_divide(_RAIter __begin, _RAIter __end, _Compare __comp, typename std::iterator_traits <_RAIter>::difference_type __pivot_rank, typename std::iterator_traits <_RAIter>::difference_type __num_samples, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; __num_samples = std::min(__num_samples, __n); // Allocate uninitialized, to avoid default constructor. _ValueType* __samples = static_cast<_ValueType*> (::operator new(__num_samples * sizeof(_ValueType))); for (_DifferenceType __s = 0; __s < __num_samples; ++__s) { const unsigned long long __index = static_cast (__s) * __n / __num_samples; ::new(&(__samples[__s])) _ValueType(__begin[__index]); } __gnu_sequential::sort(__samples, __samples + __num_samples, __comp); _ValueType& __pivot = __samples[__pivot_rank * __num_samples / __n]; __gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool> __pred(__comp, __pivot); _DifferenceType __split = __parallel_partition(__begin, __end, __pred, __num_threads); for (_DifferenceType __s = 0; __s < __num_samples; ++__s) __samples[__s].~_ValueType(); ::operator delete(__samples); return __split; } /** @brief Unbalanced quicksort conquer step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template void __parallel_sort_qs_conquer(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; if (__num_threads <= 1) { __gnu_sequential::sort(__begin, __end, __comp); return; } _DifferenceType __n = __end - __begin, __pivot_rank; if (__n <= 1) return; _ThreadIndex __num_threads_left; if ((__num_threads % 2) == 1) __num_threads_left = __num_threads / 2 + 1; else __num_threads_left = __num_threads / 2; __pivot_rank = __n * __num_threads_left / __num_threads; _DifferenceType __split = __parallel_sort_qs_divide (__begin, __end, __comp, __pivot_rank, _Settings::get().sort_qs_num_samples_preset, __num_threads); #pragma omp parallel sections num_threads(2) { #pragma omp section __parallel_sort_qs_conquer(__begin, __begin + __split, __comp, __num_threads_left); #pragma omp section __parallel_sort_qs_conquer(__begin + __split, __end, __comp, __num_threads - __num_threads_left); } } /** @brief Unbalanced quicksort main call. * @param __begin Begin iterator of input sequence. * @param __end End iterator input sequence, ignored. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template void __parallel_sort_qs(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { _GLIBCXX_CALL(__n) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; // At least one element per processor. if (__num_threads > __n) __num_threads = static_cast<_ThreadIndex>(__n); __parallel_sort_qs_conquer( __begin, __begin + __n, __comp, __num_threads); } } //namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_QUICKSORT_H */ c++/8/parallel/compatibility.h000064400000007316151027430570012114 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/compatibility.h * @brief Compatibility layer, mostly concerned with atomic operations. * * This file is a GNU parallel extension to the Standard C++ Library * and contains implementation details for the library's internal use. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_COMPATIBILITY_H #define _GLIBCXX_PARALLEL_COMPATIBILITY_H 1 #include #include #if !defined(_WIN32) || defined (__CYGWIN__) #include #endif #ifdef __MINGW32__ // Including will drag in all the windows32 names. Since // that can cause user code portability problems, we just declare the // one needed function here. extern "C" __attribute((dllimport)) void __attribute__((stdcall)) Sleep (unsigned long); #endif namespace __gnu_parallel { template inline _Tp __add_omp(volatile _Tp* __ptr, _Tp __addend) { int64_t __res; #pragma omp critical { __res = *__ptr; *(__ptr) += __addend; } return __res; } /** @brief Add a value to a variable, atomically. * * @param __ptr Pointer to a signed integer. * @param __addend Value to add. */ template inline _Tp __fetch_and_add(volatile _Tp* __ptr, _Tp __addend) { if (__atomic_always_lock_free(sizeof(_Tp), __ptr)) return __atomic_fetch_add(__ptr, __addend, __ATOMIC_ACQ_REL); return __add_omp(__ptr, __addend); } template inline bool __cas_omp(volatile _Tp* __ptr, _Tp __comparand, _Tp __replacement) { bool __res = false; #pragma omp critical { if (*__ptr == __comparand) { *__ptr = __replacement; __res = true; } } return __res; } /** @brief Compare-and-swap * * Compare @c *__ptr and @c __comparand. If equal, let @c * *__ptr=__replacement and return @c true, return @c false otherwise. * * @param __ptr Pointer to signed integer. * @param __comparand Compare value. * @param __replacement Replacement value. */ template inline bool __compare_and_swap(volatile _Tp* __ptr, _Tp __comparand, _Tp __replacement) { if (__atomic_always_lock_free(sizeof(_Tp), __ptr)) return __atomic_compare_exchange_n(__ptr, &__comparand, __replacement, false, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED); return __cas_omp(__ptr, __comparand, __replacement); } /** @brief Yield control to another thread, without waiting for * the end of the time slice. */ inline void __yield() { #if defined (_WIN32) && !defined (__CYGWIN__) Sleep(0); #else sched_yield(); #endif } } // end namespace #endif /* _GLIBCXX_PARALLEL_COMPATIBILITY_H */ c++/8/parallel/partition.h000064400000035161151027430570011253 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/partition.h * @brief Parallel implementation of std::partition(), * std::nth_element(), and std::partial_sort(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_PARTITION_H #define _GLIBCXX_PARALLEL_PARTITION_H 1 #include #include #include #include #include /** @brief Decide whether to declare certain variables volatile. */ #define _GLIBCXX_VOLATILE volatile namespace __gnu_parallel { /** @brief Parallel implementation of std::partition. * @param __begin Begin iterator of input sequence to split. * @param __end End iterator of input sequence to split. * @param __pred Partition predicate, possibly including some kind * of pivot. * @param __num_threads Maximum number of threads to use for this task. * @return Number of elements not fulfilling the predicate. */ template typename std::iterator_traits<_RAIter>::difference_type __parallel_partition(_RAIter __begin, _RAIter __end, _Predicate __pred, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; _GLIBCXX_CALL(__n) const _Settings& __s = _Settings::get(); // shared _GLIBCXX_VOLATILE _DifferenceType __left = 0, __right = __n - 1, __dist = __n, __leftover_left, __leftover_right, __leftnew, __rightnew; // just 0 or 1, but int to allow atomic operations int* __reserved_left = 0, * __reserved_right = 0; _DifferenceType __chunk_size = __s.partition_chunk_size; //at least two chunks per thread if (__dist >= 2 * __num_threads * __chunk_size) # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __reserved_left = new int[__num_threads]; __reserved_right = new int[__num_threads]; if (__s.partition_chunk_share > 0.0) __chunk_size = std::max<_DifferenceType> (__s.partition_chunk_size, (double)__n * __s.partition_chunk_share / (double)__num_threads); else __chunk_size = __s.partition_chunk_size; } while (__dist >= 2 * __num_threads * __chunk_size) { # pragma omp single { _DifferenceType __num_chunks = __dist / __chunk_size; for (_ThreadIndex __r = 0; __r < __num_threads; ++__r) { __reserved_left [__r] = 0; // false __reserved_right[__r] = 0; // false } __leftover_left = 0; __leftover_right = 0; } //implicit barrier // Private. _DifferenceType __thread_left, __thread_left_border, __thread_right, __thread_right_border; __thread_left = __left + 1; // Just to satisfy the condition below. __thread_left_border = __thread_left - 1; __thread_right = __n - 1; // Just to satisfy the condition below. __thread_right_border = __thread_right + 1; bool __iam_finished = false; while (!__iam_finished) { if (__thread_left > __thread_left_border) { _DifferenceType __former_dist = __fetch_and_add(&__dist, -__chunk_size); if (__former_dist < __chunk_size) { __fetch_and_add(&__dist, __chunk_size); __iam_finished = true; break; } else { __thread_left = __fetch_and_add(&__left, __chunk_size); __thread_left_border = __thread_left + (__chunk_size - 1); } } if (__thread_right < __thread_right_border) { _DifferenceType __former_dist = __fetch_and_add(&__dist, -__chunk_size); if (__former_dist < __chunk_size) { __fetch_and_add(&__dist, __chunk_size); __iam_finished = true; break; } else { __thread_right = __fetch_and_add(&__right, -__chunk_size); __thread_right_border = __thread_right - (__chunk_size - 1); } } // Swap as usual. while (__thread_left < __thread_right) { while (__pred(__begin[__thread_left]) && __thread_left <= __thread_left_border) ++__thread_left; while (!__pred(__begin[__thread_right]) && __thread_right >= __thread_right_border) --__thread_right; if (__thread_left > __thread_left_border || __thread_right < __thread_right_border) // Fetch new chunk(__s). break; std::iter_swap(__begin + __thread_left, __begin + __thread_right); ++__thread_left; --__thread_right; } } // Now swap the leftover chunks to the right places. if (__thread_left <= __thread_left_border) # pragma omp atomic ++__leftover_left; if (__thread_right >= __thread_right_border) # pragma omp atomic ++__leftover_right; # pragma omp barrier _DifferenceType __leftold = __left, __leftnew = __left - __leftover_left * __chunk_size, __rightold = __right, __rightnew = __right + __leftover_right * __chunk_size; // <=> __thread_left_border + (__chunk_size - 1) >= __leftnew if (__thread_left <= __thread_left_border && __thread_left_border >= __leftnew) { // Chunk already in place, reserve spot. __reserved_left[(__left - (__thread_left_border + 1)) / __chunk_size] = 1; } // <=> __thread_right_border - (__chunk_size - 1) <= __rightnew if (__thread_right >= __thread_right_border && __thread_right_border <= __rightnew) { // Chunk already in place, reserve spot. __reserved_right[((__thread_right_border - 1) - __right) / __chunk_size] = 1; } # pragma omp barrier if (__thread_left <= __thread_left_border && __thread_left_border < __leftnew) { // Find spot and swap. _DifferenceType __swapstart = -1; for (int __r = 0; __r < __leftover_left; ++__r) if (__reserved_left[__r] == 0 && __compare_and_swap(&(__reserved_left[__r]), 0, 1)) { __swapstart = __leftold - (__r + 1) * __chunk_size; break; } #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__swapstart != -1); #endif std::swap_ranges(__begin + __thread_left_border - (__chunk_size - 1), __begin + __thread_left_border + 1, __begin + __swapstart); } if (__thread_right >= __thread_right_border && __thread_right_border > __rightnew) { // Find spot and swap _DifferenceType __swapstart = -1; for (int __r = 0; __r < __leftover_right; ++__r) if (__reserved_right[__r] == 0 && __compare_and_swap(&(__reserved_right[__r]), 0, 1)) { __swapstart = __rightold + __r * __chunk_size + 1; break; } #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__swapstart != -1); #endif std::swap_ranges(__begin + __thread_right_border, __begin + __thread_right_border + __chunk_size, __begin + __swapstart); } #if _GLIBCXX_PARALLEL_ASSERTIONS # pragma omp barrier # pragma omp single { for (_DifferenceType __r = 0; __r < __leftover_left; ++__r) _GLIBCXX_PARALLEL_ASSERT(__reserved_left[__r] == 1); for (_DifferenceType __r = 0; __r < __leftover_right; ++__r) _GLIBCXX_PARALLEL_ASSERT(__reserved_right[__r] == 1); } #endif __left = __leftnew; __right = __rightnew; __dist = __right - __left + 1; } # pragma omp flush(__left, __right) } // end "recursion" //parallel _DifferenceType __final_left = __left, __final_right = __right; while (__final_left < __final_right) { // Go right until key is geq than pivot. while (__pred(__begin[__final_left]) && __final_left < __final_right) ++__final_left; // Go left until key is less than pivot. while (!__pred(__begin[__final_right]) && __final_left < __final_right) --__final_right; if (__final_left == __final_right) break; std::iter_swap(__begin + __final_left, __begin + __final_right); ++__final_left; --__final_right; } // All elements on the left side are < piv, all elements on the // right are >= piv delete[] __reserved_left; delete[] __reserved_right; // Element "between" __final_left and __final_right might not have // been regarded yet if (__final_left < __n && !__pred(__begin[__final_left])) // Really swapped. return __final_left; else return __final_left + 1; } /** * @brief Parallel implementation of std::nth_element(). * @param __begin Begin iterator of input sequence. * @param __nth _Iterator of element that must be in position afterwards. * @param __end End iterator of input sequence. * @param __comp Comparator. */ template void __parallel_nth_element(_RAIter __begin, _RAIter __nth, _RAIter __end, _Compare __comp) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _GLIBCXX_CALL(__end - __begin) _RAIter __split; _RandomNumber __rng; const _Settings& __s = _Settings::get(); _DifferenceType __minimum_length = std::max<_DifferenceType>(2, std::max(__s.nth_element_minimal_n, __s.partition_minimal_n)); // Break if input range to small. while (static_cast<_SequenceIndex>(__end - __begin) >= __minimum_length) { _DifferenceType __n = __end - __begin; _RAIter __pivot_pos = __begin + __rng(__n); // Swap __pivot_pos value to end. if (__pivot_pos != (__end - 1)) std::iter_swap(__pivot_pos, __end - 1); __pivot_pos = __end - 1; // _Compare must have first_value_type, second_value_type, // result_type // _Compare == // __gnu_parallel::_Lexicographic > // __pivot_pos == std::pair* __gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool> __pred(__comp, *__pivot_pos); // Divide, leave pivot unchanged in last place. _RAIter __split_pos1, __split_pos2; __split_pos1 = __begin + __parallel_partition(__begin, __end - 1, __pred, __get_max_threads()); // Left side: < __pivot_pos; __right side: >= __pivot_pos // Swap pivot back to middle. if (__split_pos1 != __pivot_pos) std::iter_swap(__split_pos1, __pivot_pos); __pivot_pos = __split_pos1; // In case all elements are equal, __split_pos1 == 0 if ((__split_pos1 + 1 - __begin) < (__n >> 7) || (__end - __split_pos1) < (__n >> 7)) { // Very unequal split, one part smaller than one 128th // elements not strictly larger than the pivot. __gnu_parallel::__unary_negate<__gnu_parallel:: __binder1st<_Compare, _ValueType, _ValueType, bool>, _ValueType> __pred(__gnu_parallel::__binder1st<_Compare, _ValueType, _ValueType, bool>(__comp, *__pivot_pos)); // Find other end of pivot-equal range. __split_pos2 = __gnu_sequential::partition(__split_pos1 + 1, __end, __pred); } else // Only skip the pivot. __split_pos2 = __split_pos1 + 1; // Compare iterators. if (__split_pos2 <= __nth) __begin = __split_pos2; else if (__nth < __split_pos1) __end = __split_pos1; else break; } // Only at most _Settings::partition_minimal_n __elements __left. __gnu_sequential::nth_element(__begin, __nth, __end, __comp); } /** @brief Parallel implementation of std::partial_sort(). * @param __begin Begin iterator of input sequence. * @param __middle Sort until this position. * @param __end End iterator of input sequence. * @param __comp Comparator. */ template void __parallel_partial_sort(_RAIter __begin, _RAIter __middle, _RAIter __end, _Compare __comp) { __parallel_nth_element(__begin, __middle, __end, __comp); std::sort(__begin, __middle, __comp); } } //namespace __gnu_parallel #undef _GLIBCXX_VOLATILE #endif /* _GLIBCXX_PARALLEL_PARTITION_H */ c++/8/parallel/list_partition.h000064400000014616151027430570012310 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute __it and/or modify __it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that __it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/list_partition.h * @brief _Functionality to split __sequence referenced by only input * iterators. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Leonor Frias Moya and Johannes Singler. #ifndef _GLIBCXX_PARALLEL_LIST_PARTITION_H #define _GLIBCXX_PARALLEL_LIST_PARTITION_H 1 #include #include namespace __gnu_parallel { /** @brief Shrinks and doubles the ranges. * @param __os_starts Start positions worked on (oversampled). * @param __count_to_two Counts up to 2. * @param __range_length Current length of a chunk. * @param __make_twice Whether the @c __os_starts is allowed to be * grown or not */ template void __shrink_and_double(std::vector<_IIter>& __os_starts, size_t& __count_to_two, size_t& __range_length, const bool __make_twice) { ++__count_to_two; if (!__make_twice || __count_to_two < 2) __shrink(__os_starts, __count_to_two, __range_length); else { __os_starts.resize((__os_starts.size() - 1) * 2 + 1); __count_to_two = 0; } } /** @brief Combines two ranges into one and thus halves the number of ranges. * @param __os_starts Start positions worked on (oversampled). * @param __count_to_two Counts up to 2. * @param __range_length Current length of a chunk. */ template void __shrink(std::vector<_IIter>& __os_starts, size_t& __count_to_two, size_t& __range_length) { for (typename std::vector<_IIter>::size_type __i = 0; __i <= (__os_starts.size() / 2); ++__i) __os_starts[__i] = __os_starts[__i * 2]; __range_length *= 2; } /** @brief Splits a sequence given by input iterators into parts of * almost equal size * * The function needs only one pass over the sequence. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __starts Start iterators for the resulting parts, dimension * @c __num_parts+1. For convenience, @c __starts @c [__num_parts] * contains the end iterator of the sequence. * @param __lengths Length of the resulting parts. * @param __num_parts Number of parts to split the sequence into. * @param __f Functor to be applied to each element by traversing __it * @param __oversampling Oversampling factor. If 0, then the * partitions will differ in at most * \f$\sqrt{\mathrm{end} - \mathrm{begin}}\f$ * elements. Otherwise, the ratio between the * longest and the shortest part is bounded by * \f$1/(\mathrm{oversampling} \cdot \mathrm{num\_parts})\f$ * @return Length of the whole sequence. */ template size_t list_partition(const _IIter __begin, const _IIter __end, _IIter* __starts, size_t* __lengths, const int __num_parts, _FunctorType& __f, int __oversampling = 0) { bool __make_twice = false; // The resizing algorithm is chosen according to the oversampling factor. if (__oversampling == 0) { __make_twice = true; __oversampling = 1; } std::vector<_IIter> __os_starts(2 * __oversampling * __num_parts + 1); __os_starts[0] = __begin; _IIter __prev = __begin, __it = __begin; size_t __dist_limit = 0, __dist = 0; size_t __cur = 1, __next = 1; size_t __range_length = 1; size_t __count_to_two = 0; while (__it != __end) { __cur = __next; for (; __cur < __os_starts.size() and __it != __end; ++__cur) { for (__dist_limit += __range_length; __dist < __dist_limit and __it != __end; ++__dist) { __f(__it); ++__it; } __os_starts[__cur] = __it; } // Must compare for end and not __cur < __os_starts.size() , because // __cur could be == __os_starts.size() as well if (__it == __end) break; __shrink_and_double(__os_starts, __count_to_two, __range_length, __make_twice); __next = __os_starts.size() / 2 + 1; } // Calculation of the parts (one must be extracted from __current // because the partition beginning at end, consists only of // itself). size_t __size_part = (__cur - 1) / __num_parts; int __size_greater = static_cast((__cur - 1) % __num_parts); __starts[0] = __os_starts[0]; size_t __index = 0; // Smallest partitions. for (int __i = 1; __i < (__num_parts + 1 - __size_greater); ++__i) { __lengths[__i - 1] = __size_part * __range_length; __index += __size_part; __starts[__i] = __os_starts[__index]; } // Biggest partitions. for (int __i = __num_parts + 1 - __size_greater; __i <= __num_parts; ++__i) { __lengths[__i - 1] = (__size_part+1) * __range_length; __index += (__size_part+1); __starts[__i] = __os_starts[__index]; } // Correction of the end size (the end iteration has not finished). __lengths[__num_parts - 1] -= (__dist_limit - __dist); return __dist; } } #endif /* _GLIBCXX_PARALLEL_LIST_PARTITION_H */ c++/8/parallel/for_each_selectors.h000064400000024505151027430570013073 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/for_each_selectors.h * @brief Functors representing different tasks to be plugged into the * generic parallelization methods for embarrassingly parallel functions. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_FOR_EACH_SELECTORS_H #define _GLIBCXX_PARALLEL_FOR_EACH_SELECTORS_H 1 #include namespace __gnu_parallel { /** @brief Generic __selector for embarrassingly parallel functions. */ template struct __generic_for_each_selector { /** @brief _Iterator on last element processed; needed for some * algorithms (e. g. std::transform()). */ _It _M_finish_iterator; }; /** @brief std::for_each() selector. */ template struct __for_each_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator. * @param __i iterator referencing object. */ template bool operator()(_Op& __o, _It __i) { __o(*__i); return true; } }; /** @brief std::generate() selector. */ template struct __generate_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator. * @param __i iterator referencing object. */ template bool operator()(_Op& __o, _It __i) { *__i = __o(); return true; } }; /** @brief std::fill() selector. */ template struct __fill_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __v Current value. * @param __i iterator referencing object. */ template bool operator()(_ValueType& __v, _It __i) { *__i = __v; return true; } }; /** @brief std::transform() __selector, one input sequence variant. */ template struct __transform1_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator. * @param __i iterator referencing object. */ template bool operator()(_Op& __o, _It __i) { *__i.second = __o(*__i.first); return true; } }; /** @brief std::transform() __selector, two input sequences variant. */ template struct __transform2_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator. * @param __i iterator referencing object. */ template bool operator()(_Op& __o, _It __i) { *__i._M_third = __o(*__i._M_first, *__i._M_second); return true; } }; /** @brief std::replace() selector. */ template struct __replace_selector : public __generic_for_each_selector<_It> { /** @brief Value to replace with. */ const _Tp& __new_val; /** @brief Constructor * @param __new_val Value to replace with. */ explicit __replace_selector(const _Tp &__new_val) : __new_val(__new_val) {} /** @brief Functor execution. * @param __v Current value. * @param __i iterator referencing object. */ bool operator()(_Tp& __v, _It __i) { if (*__i == __v) *__i = __new_val; return true; } }; /** @brief std::replace() selector. */ template struct __replace_if_selector : public __generic_for_each_selector<_It> { /** @brief Value to replace with. */ const _Tp& __new_val; /** @brief Constructor. * @param __new_val Value to replace with. */ explicit __replace_if_selector(const _Tp &__new_val) : __new_val(__new_val) { } /** @brief Functor execution. * @param __o Operator. * @param __i iterator referencing object. */ bool operator()(_Op& __o, _It __i) { if (__o(*__i)) *__i = __new_val; return true; } }; /** @brief std::count() selector. */ template struct __count_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __v Current value. * @param __i iterator referencing object. * @return 1 if count, 0 if does not count. */ template _Diff operator()(_ValueType& __v, _It __i) { return (__v == *__i) ? 1 : 0; } }; /** @brief std::count_if () selector. */ template struct __count_if_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator. * @param __i iterator referencing object. * @return 1 if count, 0 if does not count. */ template _Diff operator()(_Op& __o, _It __i) { return (__o(*__i)) ? 1 : 0; } }; /** @brief std::accumulate() selector. */ template struct __accumulate_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator (unused). * @param __i iterator referencing object. * @return The current value. */ template typename std::iterator_traits<_It>::value_type operator()(_Op __o, _It __i) { return *__i; } }; /** @brief std::inner_product() selector. */ template struct __inner_product_selector : public __generic_for_each_selector<_It> { /** @brief Begin iterator of first sequence. */ _It __begin1_iterator; /** @brief Begin iterator of second sequence. */ _It2 __begin2_iterator; /** @brief Constructor. * @param __b1 Begin iterator of first sequence. * @param __b2 Begin iterator of second sequence. */ explicit __inner_product_selector(_It __b1, _It2 __b2) : __begin1_iterator(__b1), __begin2_iterator(__b2) { } /** @brief Functor execution. * @param __mult Multiplication functor. * @param __current iterator referencing object. * @return Inner product elemental __result. */ template _Tp operator()(_Op __mult, _It __current) { typename std::iterator_traits<_It>::difference_type __position = __current - __begin1_iterator; return __mult(*__current, *(__begin2_iterator + __position)); } }; /** @brief Selector that just returns the passed iterator. */ template struct __identity_selector : public __generic_for_each_selector<_It> { /** @brief Functor execution. * @param __o Operator (unused). * @param __i iterator referencing object. * @return Passed iterator. */ template _It operator()(_Op __o, _It __i) { return __i; } }; /** @brief Selector that returns the difference between two adjacent * __elements. */ template struct __adjacent_difference_selector : public __generic_for_each_selector<_It> { template bool operator()(_Op& __o, _It __i) { typename _It::first_type __go_back_one = __i.first; --__go_back_one; *__i.second = __o(*__i.first, *__go_back_one); return true; } }; /** @brief Functor doing nothing * * For some __reduction tasks (this is not a function object, but is * passed as __selector __dummy parameter. */ struct _Nothing { /** @brief Functor execution. * @param __i iterator referencing object. */ template void operator()(_It __i) { } }; /** @brief Reduction function doing nothing. */ struct _DummyReduct { bool operator()(bool, bool) const { return true; } }; /** @brief Reduction for finding the maximum element, using a comparator. */ template struct __min_element_reduct { _Compare& __comp; explicit __min_element_reduct(_Compare &__c) : __comp(__c) { } _It operator()(_It __x, _It __y) { return (__comp(*__x, *__y)) ? __x : __y; } }; /** @brief Reduction for finding the maximum element, using a comparator. */ template struct __max_element_reduct { _Compare& __comp; explicit __max_element_reduct(_Compare& __c) : __comp(__c) { } _It operator()(_It __x, _It __y) { return (__comp(*__x, *__y)) ? __y : __x; } }; /** @brief General reduction, using a binary operator. */ template struct __accumulate_binop_reduct { _BinOp& __binop; explicit __accumulate_binop_reduct(_BinOp& __b) : __binop(__b) { } template _Result operator()(const _Result& __x, const _Addend& __y) { return __binop(__x, __y); } }; } #endif /* _GLIBCXX_PARALLEL_FOR_EACH_SELECTORS_H */ c++/8/parallel/omp_loop.h000064400000007677151027430570011101 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/omp_loop.h * @brief Parallelization of embarrassingly parallel execution by * means of an OpenMP for loop. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_OMP_LOOP_H #define _GLIBCXX_PARALLEL_OMP_LOOP_H 1 #include #include #include #include namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using an OpenMP for loop. * * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __o User-supplied functor (comparator, predicate, adding * functor, etc.). * @param __f Functor to @a process an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to @a add a single __result to the already * processed elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template _Op __for_each_template_random_access_omp_loop(_RAIter __begin, _RAIter __end, _Op __o, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { typedef typename std::iterator_traits<_RAIter>::difference_type _DifferenceType; _DifferenceType __length = __end - __begin; _ThreadIndex __num_threads = __gnu_parallel::min<_DifferenceType> (__get_max_threads(), __length); _Result *__thread_results; # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __thread_results = new _Result[__num_threads]; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __thread_results[__i] = _Result(); } _ThreadIndex __iam = omp_get_thread_num(); #pragma omp for schedule(dynamic, _Settings::get().workstealing_chunk_size) for (_DifferenceType __pos = 0; __pos < __length; ++__pos) __thread_results[__iam] = __r(__thread_results[__iam], __f(__o, __begin+__pos)); } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __output = __r(__output, __thread_results[__i]); delete [] __thread_results; // Points to last element processed (needed as return value for // some algorithms like transform). __f._M_finish_iterator = __begin + __length; return __o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_OMP_LOOP_H */ c++/8/parallel/workstealing.h000064400000022614151027430570011752 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/workstealing.h * @brief Parallelization of embarrassingly parallel execution by * means of work-stealing. * * Work stealing is described in * * R. D. Blumofe and C. E. Leiserson. * Scheduling multithreaded computations by work stealing. * Journal of the ACM, 46(5):720–748, 1999. * * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_WORKSTEALING_H #define _GLIBCXX_PARALLEL_WORKSTEALING_H 1 #include #include #include namespace __gnu_parallel { #define _GLIBCXX_JOB_VOLATILE volatile /** @brief One __job for a certain thread. */ template struct _Job { typedef _DifferenceTp _DifferenceType; /** @brief First element. * * Changed by owning and stealing thread. By stealing thread, * always incremented. */ _GLIBCXX_JOB_VOLATILE _DifferenceType _M_first; /** @brief Last element. * * Changed by owning thread only. */ _GLIBCXX_JOB_VOLATILE _DifferenceType _M_last; /** @brief Number of elements, i.e. @c _M_last-_M_first+1. * * Changed by owning thread only. */ _GLIBCXX_JOB_VOLATILE _DifferenceType _M_load; }; /** @brief Work stealing algorithm for random access iterators. * * Uses O(1) additional memory. Synchronization at job lists is * done with atomic operations. * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __op User-supplied functor (comparator, predicate, adding * functor, ...). * @param __f Functor to @a process an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to @a add a single __result to the already * processed elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template _Op __for_each_template_random_access_workstealing(_RAIter __begin, _RAIter __end, _Op __op, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { _GLIBCXX_CALL(__end - __begin) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; const _Settings& __s = _Settings::get(); _DifferenceType __chunk_size = static_cast<_DifferenceType>(__s.workstealing_chunk_size); // How many jobs? _DifferenceType __length = (__bound < 0) ? (__end - __begin) : __bound; // To avoid false sharing in a cache line. const int __stride = (__s.cache_line_size * 10 / sizeof(_Job<_DifferenceType>) + 1); // Total number of threads currently working. _ThreadIndex __busy = 0; _Job<_DifferenceType> *__job; omp_lock_t __output_lock; omp_init_lock(&__output_lock); // Write base value to output. __output = __base; // No more threads than jobs, at least one thread. _ThreadIndex __num_threads = __gnu_parallel::max<_ThreadIndex> (1, __gnu_parallel::min<_DifferenceType>(__length, __get_max_threads())); # pragma omp parallel shared(__busy) num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); // Create job description array. __job = new _Job<_DifferenceType>[__num_threads * __stride]; } // Initialization phase. // Flags for every thread if it is doing productive work. bool __iam_working = false; // Thread id. _ThreadIndex __iam = omp_get_thread_num(); // This job. _Job<_DifferenceType>& __my_job = __job[__iam * __stride]; // Random number (for work stealing). _ThreadIndex __victim; // Local value for reduction. _Result __result = _Result(); // Number of elements to steal in one attempt. _DifferenceType __steal; // Every thread has its own random number generator // (modulo __num_threads). _RandomNumber __rand_gen(__iam, __num_threads); // This thread is currently working. # pragma omp atomic ++__busy; __iam_working = true; // How many jobs per thread? last thread gets the rest. __my_job._M_first = static_cast<_DifferenceType> (__iam * (__length / __num_threads)); __my_job._M_last = (__iam == (__num_threads - 1) ? (__length - 1) : ((__iam + 1) * (__length / __num_threads) - 1)); __my_job._M_load = __my_job._M_last - __my_job._M_first + 1; // Init result with _M_first value (to have a base value for reduction) if (__my_job._M_first <= __my_job._M_last) { // Cannot use volatile variable directly. _DifferenceType __my_first = __my_job._M_first; __result = __f(__op, __begin + __my_first); ++__my_job._M_first; --__my_job._M_load; } _RAIter __current; # pragma omp barrier // Actual work phase // Work on own or stolen current start while (__busy > 0) { // Work until no productive thread left. # pragma omp flush(__busy) // Thread has own work to do while (__my_job._M_first <= __my_job._M_last) { // fetch-and-add call // Reserve current job block (size __chunk_size) in my queue. _DifferenceType __current_job = __fetch_and_add<_DifferenceType>(&(__my_job._M_first), __chunk_size); // Update _M_load, to make the three values consistent, // _M_first might have been changed in the meantime __my_job._M_load = __my_job._M_last - __my_job._M_first + 1; for (_DifferenceType __job_counter = 0; __job_counter < __chunk_size && __current_job <= __my_job._M_last; ++__job_counter) { // Yes: process it! __current = __begin + __current_job; ++__current_job; // Do actual work. __result = __r(__result, __f(__op, __current)); } # pragma omp flush(__busy) } // After reaching this point, a thread's __job list is empty. if (__iam_working) { // This thread no longer has work. # pragma omp atomic --__busy; __iam_working = false; } _DifferenceType __supposed_first, __supposed_last, __supposed_load; do { // Find random nonempty deque (not own), do consistency check. __yield(); # pragma omp flush(__busy) __victim = __rand_gen(); __supposed_first = __job[__victim * __stride]._M_first; __supposed_last = __job[__victim * __stride]._M_last; __supposed_load = __job[__victim * __stride]._M_load; } while (__busy > 0 && ((__supposed_load <= 0) || ((__supposed_first + __supposed_load - 1) != __supposed_last))); if (__busy == 0) break; if (__supposed_load > 0) { // Has work and work to do. // Number of elements to steal (at least one). __steal = (__supposed_load < 2) ? 1 : __supposed_load / 2; // Push __victim's current start forward. _DifferenceType __stolen_first = __fetch_and_add<_DifferenceType> (&(__job[__victim * __stride]._M_first), __steal); _DifferenceType __stolen_try = (__stolen_first + __steal - _DifferenceType(1)); __my_job._M_first = __stolen_first; __my_job._M_last = __gnu_parallel::min(__stolen_try, __supposed_last); __my_job._M_load = __my_job._M_last - __my_job._M_first + 1; // Has potential work again. # pragma omp atomic ++__busy; __iam_working = true; # pragma omp flush(__busy) } # pragma omp flush(__busy) } // end while __busy > 0 // Add accumulated result to output. omp_set_lock(&__output_lock); __output = __r(__output, __result); omp_unset_lock(&__output_lock); } delete[] __job; // Points to last element processed (needed as return value for // some algorithms like transform) __f._M_finish_iterator = __begin + __length; omp_destroy_lock(&__output_lock); return __op; } } // end namespace #endif /* _GLIBCXX_PARALLEL_WORKSTEALING_H */ c++/8/parallel/algorithm000064400000002545151027430570011002 0ustar00// Algorithm extensions -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/algorithm * This file is a GNU extension to the Standard C++ Library. */ #ifndef _PARALLEL_ALGORITHM #define _PARALLEL_ALGORITHM 1 #pragma GCC system_header #include #include #include #include #endif c++/8/parallel/multiway_mergesort.h000064400000035647151027430570013215 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/multiway_mergesort.h * @brief Parallel multiway merge sort. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_MULTIWAY_MERGESORT_H #define _GLIBCXX_PARALLEL_MULTIWAY_MERGESORT_H 1 #include #include #include #include #include namespace __gnu_parallel { /** @brief Subsequence description. */ template struct _Piece { typedef _DifferenceTp _DifferenceType; /** @brief Begin of subsequence. */ _DifferenceType _M_begin; /** @brief End of subsequence. */ _DifferenceType _M_end; }; /** @brief Data accessed by all threads. * * PMWMS = parallel multiway mergesort */ template struct _PMWMSSortingData { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; /** @brief Number of threads involved. */ _ThreadIndex _M_num_threads; /** @brief Input __begin. */ _RAIter _M_source; /** @brief Start indices, per thread. */ _DifferenceType* _M_starts; /** @brief Storage in which to sort. */ _ValueType** _M_temporary; /** @brief Samples. */ _ValueType* _M_samples; /** @brief Offsets to add to the found positions. */ _DifferenceType* _M_offsets; /** @brief Pieces of data to merge @c [thread][__sequence] */ std::vector<_Piece<_DifferenceType> >* _M_pieces; }; /** * @brief Select _M_samples from a sequence. * @param __sd Pointer to algorithm data. _Result will be placed in * @c __sd->_M_samples. * @param __num_samples Number of _M_samples to select. */ template void __determine_samples(_PMWMSSortingData<_RAIter>* __sd, _DifferenceTp __num_samples) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef _DifferenceTp _DifferenceType; _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType* __es = new _DifferenceType[__num_samples + 2]; __equally_split(__sd->_M_starts[__iam + 1] - __sd->_M_starts[__iam], __num_samples + 1, __es); for (_DifferenceType __i = 0; __i < __num_samples; ++__i) ::new(&(__sd->_M_samples[__iam * __num_samples + __i])) _ValueType(__sd->_M_source[__sd->_M_starts[__iam] + __es[__i + 1]]); delete[] __es; } /** @brief Split consistently. */ template struct _SplitConsistently { }; /** @brief Split by exact splitting. */ template struct _SplitConsistently { void operator()(const _ThreadIndex __iam, _PMWMSSortingData<_RAIter>* __sd, _Compare& __comp, const typename std::iterator_traits<_RAIter>::difference_type __num_samples) const { # pragma omp barrier std::vector > __seqs(__sd->_M_num_threads); for (_ThreadIndex __s = 0; __s < __sd->_M_num_threads; __s++) __seqs[__s] = std::make_pair(__sd->_M_temporary[__s], __sd->_M_temporary[__s] + (__sd->_M_starts[__s + 1] - __sd->_M_starts[__s])); std::vector<_SortingPlacesIterator> __offsets(__sd->_M_num_threads); // if not last thread if (__iam < __sd->_M_num_threads - 1) multiseq_partition(__seqs.begin(), __seqs.end(), __sd->_M_starts[__iam + 1], __offsets.begin(), __comp); for (_ThreadIndex __seq = 0; __seq < __sd->_M_num_threads; __seq++) { // for each sequence if (__iam < (__sd->_M_num_threads - 1)) __sd->_M_pieces[__iam][__seq]._M_end = __offsets[__seq] - __seqs[__seq].first; else // very end of this sequence __sd->_M_pieces[__iam][__seq]._M_end = __sd->_M_starts[__seq + 1] - __sd->_M_starts[__seq]; } # pragma omp barrier for (_ThreadIndex __seq = 0; __seq < __sd->_M_num_threads; __seq++) { // For each sequence. if (__iam > 0) __sd->_M_pieces[__iam][__seq]._M_begin = __sd->_M_pieces[__iam - 1][__seq]._M_end; else // Absolute beginning. __sd->_M_pieces[__iam][__seq]._M_begin = 0; } } }; /** @brief Split by sampling. */ template struct _SplitConsistently { void operator()(const _ThreadIndex __iam, _PMWMSSortingData<_RAIter>* __sd, _Compare& __comp, const typename std::iterator_traits<_RAIter>::difference_type __num_samples) const { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; __determine_samples(__sd, __num_samples); # pragma omp barrier # pragma omp single __gnu_sequential::sort(__sd->_M_samples, __sd->_M_samples + (__num_samples * __sd->_M_num_threads), __comp); # pragma omp barrier for (_ThreadIndex __s = 0; __s < __sd->_M_num_threads; ++__s) { // For each sequence. if (__num_samples * __iam > 0) __sd->_M_pieces[__iam][__s]._M_begin = std::lower_bound(__sd->_M_temporary[__s], __sd->_M_temporary[__s] + (__sd->_M_starts[__s + 1] - __sd->_M_starts[__s]), __sd->_M_samples[__num_samples * __iam], __comp) - __sd->_M_temporary[__s]; else // Absolute beginning. __sd->_M_pieces[__iam][__s]._M_begin = 0; if ((__num_samples * (__iam + 1)) < (__num_samples * __sd->_M_num_threads)) __sd->_M_pieces[__iam][__s]._M_end = std::lower_bound(__sd->_M_temporary[__s], __sd->_M_temporary[__s] + (__sd->_M_starts[__s + 1] - __sd->_M_starts[__s]), __sd->_M_samples[__num_samples * (__iam + 1)], __comp) - __sd->_M_temporary[__s]; else // Absolute end. __sd->_M_pieces[__iam][__s]._M_end = (__sd->_M_starts[__s + 1] - __sd->_M_starts[__s]); } } }; template struct __possibly_stable_sort { }; template struct __possibly_stable_sort { void operator()(const _RAIter& __begin, const _RAIter& __end, _Compare& __comp) const { __gnu_sequential::stable_sort(__begin, __end, __comp); } }; template struct __possibly_stable_sort { void operator()(const _RAIter __begin, const _RAIter __end, _Compare& __comp) const { __gnu_sequential::sort(__begin, __end, __comp); } }; template struct __possibly_stable_multiway_merge { }; template struct __possibly_stable_multiway_merge { void operator()(const Seq_RAIter& __seqs_begin, const Seq_RAIter& __seqs_end, const _RAIter& __target, _Compare& __comp, _DiffType __length_am) const { stable_multiway_merge(__seqs_begin, __seqs_end, __target, __length_am, __comp, sequential_tag()); } }; template struct __possibly_stable_multiway_merge { void operator()(const Seq_RAIter& __seqs_begin, const Seq_RAIter& __seqs_end, const _RAIter& __target, _Compare& __comp, _DiffType __length_am) const { multiway_merge(__seqs_begin, __seqs_end, __target, __length_am, __comp, sequential_tag()); } }; /** @brief PMWMS code executed by each thread. * @param __sd Pointer to algorithm data. * @param __comp Comparator. */ template void parallel_sort_mwms_pu(_PMWMSSortingData<_RAIter>* __sd, _Compare& __comp) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _ThreadIndex __iam = omp_get_thread_num(); // Length of this thread's chunk, before merging. _DifferenceType __length_local = __sd->_M_starts[__iam + 1] - __sd->_M_starts[__iam]; // Sort in temporary storage, leave space for sentinel. typedef _ValueType* _SortingPlacesIterator; __sd->_M_temporary[__iam] = static_cast<_ValueType*>(::operator new(sizeof(_ValueType) * (__length_local + 1))); // Copy there. std::uninitialized_copy(__sd->_M_source + __sd->_M_starts[__iam], __sd->_M_source + __sd->_M_starts[__iam] + __length_local, __sd->_M_temporary[__iam]); __possibly_stable_sort<__stable, _SortingPlacesIterator, _Compare>() (__sd->_M_temporary[__iam], __sd->_M_temporary[__iam] + __length_local, __comp); // Invariant: locally sorted subsequence in sd->_M_temporary[__iam], // __sd->_M_temporary[__iam] + __length_local. // No barrier here: Synchronization is done by the splitting routine. _DifferenceType __num_samples = _Settings::get().sort_mwms_oversampling * __sd->_M_num_threads - 1; _SplitConsistently<__exact, _RAIter, _Compare, _SortingPlacesIterator>() (__iam, __sd, __comp, __num_samples); // Offset from __target __begin, __length after merging. _DifferenceType __offset = 0, __length_am = 0; for (_ThreadIndex __s = 0; __s < __sd->_M_num_threads; __s++) { __length_am += (__sd->_M_pieces[__iam][__s]._M_end - __sd->_M_pieces[__iam][__s]._M_begin); __offset += __sd->_M_pieces[__iam][__s]._M_begin; } typedef std::vector< std::pair<_SortingPlacesIterator, _SortingPlacesIterator> > _SeqVector; _SeqVector __seqs(__sd->_M_num_threads); for (_ThreadIndex __s = 0; __s < __sd->_M_num_threads; ++__s) { __seqs[__s] = std::make_pair(__sd->_M_temporary[__s] + __sd->_M_pieces[__iam][__s]._M_begin, __sd->_M_temporary[__s] + __sd->_M_pieces[__iam][__s]._M_end); } __possibly_stable_multiway_merge< __stable, typename _SeqVector::iterator, _RAIter, _Compare, _DifferenceType>()(__seqs.begin(), __seqs.end(), __sd->_M_source + __offset, __comp, __length_am); # pragma omp barrier for (_DifferenceType __i = 0; __i < __length_local; ++__i) __sd->_M_temporary[__iam][__i].~_ValueType(); ::operator delete(__sd->_M_temporary[__iam]); } /** @brief PMWMS main call. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __comp Comparator. * @param __num_threads Number of threads to use. */ template void parallel_sort_mwms(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { _GLIBCXX_CALL(__end - __begin) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; if (__n <= 1) return; // at least one element per thread if (__num_threads > __n) __num_threads = static_cast<_ThreadIndex>(__n); // shared variables _PMWMSSortingData<_RAIter> __sd; _DifferenceType* __starts; _DifferenceType __size; # pragma omp parallel num_threads(__num_threads) { __num_threads = omp_get_num_threads(); //no more threads than requested # pragma omp single { __sd._M_num_threads = __num_threads; __sd._M_source = __begin; __sd._M_temporary = new _ValueType*[__num_threads]; if (!__exact) { __size = (_Settings::get().sort_mwms_oversampling * __num_threads - 1) * __num_threads; __sd._M_samples = static_cast<_ValueType*> (::operator new(__size * sizeof(_ValueType))); } else __sd._M_samples = 0; __sd._M_offsets = new _DifferenceType[__num_threads - 1]; __sd._M_pieces = new std::vector<_Piece<_DifferenceType> >[__num_threads]; for (_ThreadIndex __s = 0; __s < __num_threads; ++__s) __sd._M_pieces[__s].resize(__num_threads); __starts = __sd._M_starts = new _DifferenceType[__num_threads + 1]; _DifferenceType __chunk_length = __n / __num_threads; _DifferenceType __split = __n % __num_threads; _DifferenceType __pos = 0; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) { __starts[__i] = __pos; __pos += ((__i < __split) ? (__chunk_length + 1) : __chunk_length); } __starts[__num_threads] = __pos; } //single // Now sort in parallel. parallel_sort_mwms_pu<__stable, __exact>(&__sd, __comp); } //parallel delete[] __starts; delete[] __sd._M_temporary; if (!__exact) { for (_DifferenceType __i = 0; __i < __size; ++__i) __sd._M_samples[__i].~_ValueType(); ::operator delete(__sd._M_samples); } delete[] __sd._M_offsets; delete[] __sd._M_pieces; } } //namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_MULTIWAY_MERGESORT_H */ c++/8/parallel/set_operations.h000064400000034376151027430570012307 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file parallel/set_operations.h * @brief Parallel implementations of set operations for random-access * iterators. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Marius Elvert and Felix Bondarenko. #ifndef _GLIBCXX_PARALLEL_SET_OPERATIONS_H #define _GLIBCXX_PARALLEL_SET_OPERATIONS_H 1 #include #include #include namespace __gnu_parallel { template _OutputIterator __copy_tail(std::pair<_IIter, _IIter> __b, std::pair<_IIter, _IIter> __e, _OutputIterator __r) { if (__b.first != __e.first) { do { *__r++ = *__b.first++; } while (__b.first != __e.first); } else { while (__b.second != __e.second) *__r++ = *__b.second++; } return __r; } template struct __symmetric_difference_func { typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename std::pair<_IIter, _IIter> _IteratorPair; __symmetric_difference_func(_Compare __comp) : _M_comp(__comp) {} _Compare _M_comp; _OutputIterator _M_invoke(_IIter __a, _IIter __b, _IIter __c, _IIter __d, _OutputIterator __r) const { while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { *__r = *__a; ++__a; ++__r; } else if (_M_comp(*__c, *__a)) { *__r = *__c; ++__c; ++__r; } else { ++__a; ++__c; } } return std::copy(__c, __d, std::copy(__a, __b, __r)); } _DifferenceType __count(_IIter __a, _IIter __b, _IIter __c, _IIter __d) const { _DifferenceType __counter = 0; while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { ++__a; ++__counter; } else if (_M_comp(*__c, *__a)) { ++__c; ++__counter; } else { ++__a; ++__c; } } return __counter + (__b - __a) + (__d - __c); } _OutputIterator __first_empty(_IIter __c, _IIter __d, _OutputIterator __out) const { return std::copy(__c, __d, __out); } _OutputIterator __second_empty(_IIter __a, _IIter __b, _OutputIterator __out) const { return std::copy(__a, __b, __out); } }; template struct __difference_func { typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename std::pair<_IIter, _IIter> _IteratorPair; __difference_func(_Compare __comp) : _M_comp(__comp) {} _Compare _M_comp; _OutputIterator _M_invoke(_IIter __a, _IIter __b, _IIter __c, _IIter __d, _OutputIterator __r) const { while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { *__r = *__a; ++__a; ++__r; } else if (_M_comp(*__c, *__a)) { ++__c; } else { ++__a; ++__c; } } return std::copy(__a, __b, __r); } _DifferenceType __count(_IIter __a, _IIter __b, _IIter __c, _IIter __d) const { _DifferenceType __counter = 0; while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { ++__a; ++__counter; } else if (_M_comp(*__c, *__a)) { ++__c; } else { ++__a; ++__c; } } return __counter + (__b - __a); } _OutputIterator __first_empty(_IIter, _IIter, _OutputIterator __out) const { return __out; } _OutputIterator __second_empty(_IIter __a, _IIter __b, _OutputIterator __out) const { return std::copy(__a, __b, __out); } }; template struct __intersection_func { typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename std::pair<_IIter, _IIter> _IteratorPair; __intersection_func(_Compare __comp) : _M_comp(__comp) {} _Compare _M_comp; _OutputIterator _M_invoke(_IIter __a, _IIter __b, _IIter __c, _IIter __d, _OutputIterator __r) const { while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { ++__a; } else if (_M_comp(*__c, *__a)) { ++__c; } else { *__r = *__a; ++__a; ++__c; ++__r; } } return __r; } _DifferenceType __count(_IIter __a, _IIter __b, _IIter __c, _IIter __d) const { _DifferenceType __counter = 0; while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { ++__a; } else if (_M_comp(*__c, *__a)) { ++__c; } else { ++__a; ++__c; ++__counter; } } return __counter; } _OutputIterator __first_empty(_IIter, _IIter, _OutputIterator __out) const { return __out; } _OutputIterator __second_empty(_IIter, _IIter, _OutputIterator __out) const { return __out; } }; template struct __union_func { typedef typename std::iterator_traits<_IIter>::difference_type _DifferenceType; __union_func(_Compare __comp) : _M_comp(__comp) {} _Compare _M_comp; _OutputIterator _M_invoke(_IIter __a, const _IIter __b, _IIter __c, const _IIter __d, _OutputIterator __r) const { while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { *__r = *__a; ++__a; } else if (_M_comp(*__c, *__a)) { *__r = *__c; ++__c; } else { *__r = *__a; ++__a; ++__c; } ++__r; } return std::copy(__c, __d, std::copy(__a, __b, __r)); } _DifferenceType __count(_IIter __a, _IIter __b, _IIter __c, _IIter __d) const { _DifferenceType __counter = 0; while (__a != __b && __c != __d) { if (_M_comp(*__a, *__c)) { ++__a; } else if (_M_comp(*__c, *__a)) { ++__c; } else { ++__a; ++__c; } ++__counter; } __counter += (__b - __a); __counter += (__d - __c); return __counter; } _OutputIterator __first_empty(_IIter __c, _IIter __d, _OutputIterator __out) const { return std::copy(__c, __d, __out); } _OutputIterator __second_empty(_IIter __a, _IIter __b, _OutputIterator __out) const { return std::copy(__a, __b, __out); } }; template _OutputIterator __parallel_set_operation(_IIter __begin1, _IIter __end1, _IIter __begin2, _IIter __end2, _OutputIterator __result, _Operation __op) { _GLIBCXX_CALL((__end1 - __begin1) + (__end2 - __begin2)) typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename std::pair<_IIter, _IIter> _IteratorPair; if (__begin1 == __end1) return __op.__first_empty(__begin2, __end2, __result); if (__begin2 == __end2) return __op.__second_empty(__begin1, __end1, __result); const _DifferenceType __size = (__end1 - __begin1) + (__end2 - __begin2); const _IteratorPair __sequence[2] = { std::make_pair(__begin1, __end1), std::make_pair(__begin2, __end2) }; _OutputIterator __return_value = __result; _DifferenceType *__borders; _IteratorPair *__block_begins; _DifferenceType* __lengths; _ThreadIndex __num_threads = std::min<_DifferenceType>(__get_max_threads(), std::min(__end1 - __begin1, __end2 - __begin2)); # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __borders = new _DifferenceType[__num_threads + 2]; __equally_split(__size, __num_threads + 1, __borders); __block_begins = new _IteratorPair[__num_threads + 1]; // Very __start. __block_begins[0] = std::make_pair(__begin1, __begin2); __lengths = new _DifferenceType[__num_threads]; } //single _ThreadIndex __iam = omp_get_thread_num(); // _Result from multiseq_partition. _IIter __offset[2]; const _DifferenceType __rank = __borders[__iam + 1]; multiseq_partition(__sequence, __sequence + 2, __rank, __offset, __op._M_comp); // allowed to read? // together // *(__offset[ 0 ] - 1) == *__offset[ 1 ] if (__offset[ 0 ] != __begin1 && __offset[1] != __end2 && !__op._M_comp(*(__offset[0] - 1), *__offset[1]) && !__op._M_comp(*__offset[1], *(__offset[0] - 1))) { // Avoid split between globally equal elements: move one to // front in first sequence. --__offset[0]; } _IteratorPair __block_end = __block_begins[__iam + 1] = _IteratorPair(__offset[0], __offset[1]); // Make sure all threads have their block_begin result written out. # pragma omp barrier _IteratorPair __block_begin = __block_begins[__iam]; // Begin working for the first block, while the others except // the last start to count. if (__iam == 0) { // The first thread can copy already. __lengths[ __iam ] = __op._M_invoke(__block_begin.first, __block_end.first, __block_begin.second, __block_end.second, __result) - __result; } else { __lengths[ __iam ] = __op.__count(__block_begin.first, __block_end.first, __block_begin.second, __block_end.second); } // Make sure everyone wrote their lengths. # pragma omp barrier _OutputIterator __r = __result; if (__iam == 0) { // Do the last block. for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __r += __lengths[__i]; __block_begin = __block_begins[__num_threads]; // Return the result iterator of the last block. __return_value = __op._M_invoke(__block_begin.first, __end1, __block_begin.second, __end2, __r); } else { for (_ThreadIndex __i = 0; __i < __iam; ++__i) __r += __lengths[ __i ]; // Reset begins for copy pass. __op._M_invoke(__block_begin.first, __block_end.first, __block_begin.second, __block_end.second, __r); } } return __return_value; } template inline _OutputIterator __parallel_set_union(_IIter __begin1, _IIter __end1, _IIter __begin2, _IIter __end2, _OutputIterator __result, _Compare __comp) { return __parallel_set_operation(__begin1, __end1, __begin2, __end2, __result, __union_func< _IIter, _OutputIterator, _Compare>(__comp)); } template inline _OutputIterator __parallel_set_intersection(_IIter __begin1, _IIter __end1, _IIter __begin2, _IIter __end2, _OutputIterator __result, _Compare __comp) { return __parallel_set_operation(__begin1, __end1, __begin2, __end2, __result, __intersection_func<_IIter, _OutputIterator, _Compare>(__comp)); } template inline _OutputIterator __parallel_set_difference(_IIter __begin1, _IIter __end1, _IIter __begin2, _IIter __end2, _OutputIterator __result, _Compare __comp) { return __parallel_set_operation(__begin1, __end1, __begin2, __end2, __result, __difference_func<_IIter, _OutputIterator, _Compare>(__comp)); } template inline _OutputIterator __parallel_set_symmetric_difference(_IIter __begin1, _IIter __end1, _IIter __begin2, _IIter __end2, _OutputIterator __result, _Compare __comp) { return __parallel_set_operation(__begin1, __end1, __begin2, __end2, __result, __symmetric_difference_func<_IIter, _OutputIterator, _Compare>(__comp)); } } #endif /* _GLIBCXX_PARALLEL_SET_OPERATIONS_H */ c++/8/parallel/losertree.h000064400000067660151027430570011257 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/losertree.h * @brief Many generic loser tree variants. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_LOSERTREE_H #define _GLIBCXX_PARALLEL_LOSERTREE_H 1 #include #include #include #include namespace __gnu_parallel { /** * @brief Guarded loser/tournament tree. * * The smallest element is at the top. * * Guarding is done explicitly through one flag _M_sup per element, * inf is not needed due to a better initialization routine. This * is a well-performing variant. * * @param _Tp the element type * @param _Compare the comparator to use, defaults to std::less<_Tp> */ template class _LoserTreeBase { protected: /** @brief Internal representation of a _LoserTree element. */ struct _Loser { /** @brief flag, true iff this is a "maximum" __sentinel. */ bool _M_sup; /** @brief __index of the __source __sequence. */ int _M_source; /** @brief _M_key of the element in the _LoserTree. */ _Tp _M_key; }; unsigned int _M_ik, _M_k, _M_offset; /** log_2{_M_k} */ unsigned int _M_log_k; /** @brief _LoserTree __elements. */ _Loser* _M_losers; /** @brief _Compare to use. */ _Compare _M_comp; /** * @brief State flag that determines whether the _LoserTree is empty. * * Only used for building the _LoserTree. */ bool _M_first_insert; public: /** * @brief The constructor. * * @param __k The number of sequences to merge. * @param __comp The comparator to use. */ _LoserTreeBase(unsigned int __k, _Compare __comp) : _M_comp(__comp) { _M_ik = __k; // Compute log_2{_M_k} for the _Loser Tree _M_log_k = __rd_log2(_M_ik - 1) + 1; // Next greater power of 2. _M_k = 1 << _M_log_k; _M_offset = _M_k; // Avoid default-constructing _M_losers[]._M_key _M_losers = static_cast<_Loser*>(::operator new(2 * _M_k * sizeof(_Loser))); for (unsigned int __i = _M_ik - 1; __i < _M_k; ++__i) _M_losers[__i + _M_k]._M_sup = true; _M_first_insert = true; } /** * @brief The destructor. */ ~_LoserTreeBase() { for (unsigned int __i = 0; __i < (2 * _M_k); ++__i) _M_losers[__i].~_Loser(); ::operator delete(_M_losers); } /** * @brief Initializes the sequence "_M_source" with the element "__key". * * @param __key the element to insert * @param __source __index of the __source __sequence * @param __sup flag that determines whether the value to insert is an * explicit __supremum. */ void __insert_start(const _Tp& __key, int __source, bool __sup) { unsigned int __pos = _M_k + __source; if (_M_first_insert) { // Construct all keys, so we can easily destruct them. for (unsigned int __i = 0; __i < (2 * _M_k); ++__i) ::new(&(_M_losers[__i]._M_key)) _Tp(__key); _M_first_insert = false; } else _M_losers[__pos]._M_key = __key; _M_losers[__pos]._M_sup = __sup; _M_losers[__pos]._M_source = __source; } /** * @return the index of the sequence with the smallest element. */ int __get_min_source() { return _M_losers[0]._M_source; } }; /** * @brief Stable _LoserTree variant. * * Provides the stable implementations of insert_start, __init_winner, * __init and __delete_min_insert. * * Unstable variant is done using partial specialisation below. */ template class _LoserTree : public _LoserTreeBase<_Tp, _Compare> { typedef _LoserTreeBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; using _Base::_M_first_insert; public: _LoserTree(unsigned int __k, _Compare __comp) : _Base::_LoserTreeBase(__k, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); if (_M_losers[__right]._M_sup || (!_M_losers[__left]._M_sup && !_M_comp(_M_losers[__right]._M_key, _M_losers[__left]._M_key))) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; } /** * @brief Delete the smallest element and insert a new element from * the previously smallest element's sequence. * * This implementation is stable. */ // Do not pass a const reference since __key will be used as // local variable. void __delete_min_insert(_Tp __key, bool __sup) { using std::swap; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted, ties are broken by _M_source. if ((__sup && (!_M_losers[__pos]._M_sup || _M_losers[__pos]._M_source < __source)) || (!__sup && !_M_losers[__pos]._M_sup && ((_M_comp(_M_losers[__pos]._M_key, __key)) || (!_M_comp(__key, _M_losers[__pos]._M_key) && _M_losers[__pos]._M_source < __source)))) { // The other one is smaller. std::swap(_M_losers[__pos]._M_sup, __sup); std::swap(_M_losers[__pos]._M_source, __source); swap(_M_losers[__pos]._M_key, __key); } } _M_losers[0]._M_sup = __sup; _M_losers[0]._M_source = __source; _M_losers[0]._M_key = __key; } }; /** * @brief Unstable _LoserTree variant. * * Stability (non-stable here) is selected with partial specialization. */ template class _LoserTree : public _LoserTreeBase<_Tp, _Compare> { typedef _LoserTreeBase<_Tp, _Compare> _Base; using _Base::_M_log_k; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; using _Base::_M_first_insert; public: _LoserTree(unsigned int __k, _Compare __comp) : _Base::_LoserTreeBase(__k, __comp) { } /** * Computes the winner of the competition at position "__root". * * Called recursively (starting at 0) to build the initial tree. * * @param __root __index of the "game" to start. */ unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); if (_M_losers[__right]._M_sup || (!_M_losers[__left]._M_sup && !_M_comp(_M_losers[__right]._M_key, _M_losers[__left]._M_key))) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; } /** * Delete the _M_key smallest element and insert the element __key * instead. * * @param __key the _M_key to insert * @param __sup true iff __key is an explicitly marked supremum */ // Do not pass a const reference since __key will be used as local // variable. void __delete_min_insert(_Tp __key, bool __sup) { using std::swap; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted. if (__sup || (!_M_losers[__pos]._M_sup && _M_comp(_M_losers[__pos]._M_key, __key))) { // The other one is smaller. std::swap(_M_losers[__pos]._M_sup, __sup); std::swap(_M_losers[__pos]._M_source, __source); swap(_M_losers[__pos]._M_key, __key); } } _M_losers[0]._M_sup = __sup; _M_losers[0]._M_source = __source; _M_losers[0]._M_key = __key; } }; /** * @brief Base class of _Loser Tree implementation using pointers. */ template class _LoserTreePointerBase { protected: /** @brief Internal representation of _LoserTree __elements. */ struct _Loser { bool _M_sup; int _M_source; const _Tp* _M_keyp; }; unsigned int _M_ik, _M_k, _M_offset; _Loser* _M_losers; _Compare _M_comp; public: _LoserTreePointerBase(unsigned int __k, _Compare __comp = std::less<_Tp>()) : _M_comp(__comp) { _M_ik = __k; // Next greater power of 2. _M_k = 1 << (__rd_log2(_M_ik - 1) + 1); _M_offset = _M_k; _M_losers = new _Loser[_M_k * 2]; for (unsigned int __i = _M_ik - 1; __i < _M_k; __i++) _M_losers[__i + _M_k]._M_sup = true; } ~_LoserTreePointerBase() { delete[] _M_losers; } int __get_min_source() { return _M_losers[0]._M_source; } void __insert_start(const _Tp& __key, int __source, bool __sup) { unsigned int __pos = _M_k + __source; _M_losers[__pos]._M_sup = __sup; _M_losers[__pos]._M_source = __source; _M_losers[__pos]._M_keyp = &__key; } }; /** * @brief Stable _LoserTree implementation. * * The unstable variant is implemented using partial instantiation below. */ template class _LoserTreePointer : public _LoserTreePointerBase<_Tp, _Compare> { typedef _LoserTreePointerBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; public: _LoserTreePointer(unsigned int __k, _Compare __comp = std::less<_Tp>()) : _Base::_LoserTreePointerBase(__k, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); if (_M_losers[__right]._M_sup || (!_M_losers[__left]._M_sup && !_M_comp(*_M_losers[__right]._M_keyp, *_M_losers[__left]._M_keyp))) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; } void __delete_min_insert(const _Tp& __key, bool __sup) { #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif const _Tp* __keyp = &__key; int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted, ties are broken by __source. if ((__sup && (!_M_losers[__pos]._M_sup || _M_losers[__pos]._M_source < __source)) || (!__sup && !_M_losers[__pos]._M_sup && ((_M_comp(*_M_losers[__pos]._M_keyp, *__keyp)) || (!_M_comp(*__keyp, *_M_losers[__pos]._M_keyp) && _M_losers[__pos]._M_source < __source)))) { // The other one is smaller. std::swap(_M_losers[__pos]._M_sup, __sup); std::swap(_M_losers[__pos]._M_source, __source); std::swap(_M_losers[__pos]._M_keyp, __keyp); } } _M_losers[0]._M_sup = __sup; _M_losers[0]._M_source = __source; _M_losers[0]._M_keyp = __keyp; } }; /** * @brief Unstable _LoserTree implementation. * * The stable variant is above. */ template class _LoserTreePointer : public _LoserTreePointerBase<_Tp, _Compare> { typedef _LoserTreePointerBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; public: _LoserTreePointer(unsigned int __k, _Compare __comp = std::less<_Tp>()) : _Base::_LoserTreePointerBase(__k, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); if (_M_losers[__right]._M_sup || (!_M_losers[__left]._M_sup && !_M_comp(*_M_losers[__right]._M_keyp, *_M_losers[__left]._M_keyp))) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; } void __delete_min_insert(const _Tp& __key, bool __sup) { #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif const _Tp* __keyp = &__key; int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted. if (__sup || (!_M_losers[__pos]._M_sup && _M_comp(*_M_losers[__pos]._M_keyp, *__keyp))) { // The other one is smaller. std::swap(_M_losers[__pos]._M_sup, __sup); std::swap(_M_losers[__pos]._M_source, __source); std::swap(_M_losers[__pos]._M_keyp, __keyp); } } _M_losers[0]._M_sup = __sup; _M_losers[0]._M_source = __source; _M_losers[0]._M_keyp = __keyp; } }; /** @brief Base class for unguarded _LoserTree implementation. * * The whole element is copied into the tree structure. * * No guarding is done, therefore not a single input sequence must * run empty. Unused __sequence heads are marked with a sentinel which * is > all elements that are to be merged. * * This is a very fast variant. */ template class _LoserTreeUnguardedBase { protected: struct _Loser { int _M_source; _Tp _M_key; }; unsigned int _M_ik, _M_k, _M_offset; _Loser* _M_losers; _Compare _M_comp; public: _LoserTreeUnguardedBase(unsigned int __k, const _Tp& __sentinel, _Compare __comp = std::less<_Tp>()) : _M_comp(__comp) { _M_ik = __k; // Next greater power of 2. _M_k = 1 << (__rd_log2(_M_ik - 1) + 1); _M_offset = _M_k; // Avoid default-constructing _M_losers[]._M_key _M_losers = static_cast<_Loser*>(::operator new(2 * _M_k * sizeof(_Loser))); for (unsigned int __i = 0; __i < _M_k; ++__i) { ::new(&(_M_losers[__i]._M_key)) _Tp(__sentinel); _M_losers[__i]._M_source = -1; } for (unsigned int __i = _M_k + _M_ik - 1; __i < (2 * _M_k); ++__i) { ::new(&(_M_losers[__i]._M_key)) _Tp(__sentinel); _M_losers[__i]._M_source = -1; } } ~_LoserTreeUnguardedBase() { for (unsigned int __i = 0; __i < (2 * _M_k); ++__i) _M_losers[__i].~_Loser(); ::operator delete(_M_losers); } int __get_min_source() { #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif return _M_losers[0]._M_source; } void __insert_start(const _Tp& __key, int __source, bool) { unsigned int __pos = _M_k + __source; ::new(&(_M_losers[__pos]._M_key)) _Tp(__key); _M_losers[__pos]._M_source = __source; } }; /** * @brief Stable implementation of unguarded _LoserTree. * * Unstable variant is selected below with partial specialization. */ template class _LoserTreeUnguarded : public _LoserTreeUnguardedBase<_Tp, _Compare> { typedef _LoserTreeUnguardedBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; public: _LoserTreeUnguarded(unsigned int __k, const _Tp& __sentinel, _Compare __comp = std::less<_Tp>()) : _Base::_LoserTreeUnguardedBase(__k, __sentinel, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); if (!_M_comp(_M_losers[__right]._M_key, _M_losers[__left]._M_key)) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top at the beginning // (0 sequences!) _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif } // Do not pass a const reference since __key will be used as // local variable. void __delete_min_insert(_Tp __key, bool) { using std::swap; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted, ties are broken by _M_source. if (_M_comp(_M_losers[__pos]._M_key, __key) || (!_M_comp(__key, _M_losers[__pos]._M_key) && _M_losers[__pos]._M_source < __source)) { // The other one is smaller. std::swap(_M_losers[__pos]._M_source, __source); swap(_M_losers[__pos]._M_key, __key); } } _M_losers[0]._M_source = __source; _M_losers[0]._M_key = __key; } }; /** * @brief Non-Stable implementation of unguarded _LoserTree. * * Stable implementation is above. */ template class _LoserTreeUnguarded : public _LoserTreeUnguardedBase<_Tp, _Compare> { typedef _LoserTreeUnguardedBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; public: _LoserTreeUnguarded(unsigned int __k, const _Tp& __sentinel, _Compare __comp = std::less<_Tp>()) : _Base::_LoserTreeUnguardedBase(__k, __sentinel, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); #if _GLIBCXX_PARALLEL_ASSERTIONS // If __left one is sentinel then __right one must be, too. if (_M_losers[__left]._M_source == -1) _GLIBCXX_PARALLEL_ASSERT(_M_losers[__right]._M_source == -1); #endif if (!_M_comp(_M_losers[__right]._M_key, _M_losers[__left]._M_key)) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top at the beginning // (0 sequences!) _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif } // Do not pass a const reference since __key will be used as // local variable. void __delete_min_insert(_Tp __key, bool) { using std::swap; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted. if (_M_comp(_M_losers[__pos]._M_key, __key)) { // The other one is smaller. std::swap(_M_losers[__pos]._M_source, __source); swap(_M_losers[__pos]._M_key, __key); } } _M_losers[0]._M_source = __source; _M_losers[0]._M_key = __key; } }; /** @brief Unguarded loser tree, keeping only pointers to the * elements in the tree structure. * * No guarding is done, therefore not a single input sequence must * run empty. This is a very fast variant. */ template class _LoserTreePointerUnguardedBase { protected: struct _Loser { int _M_source; const _Tp* _M_keyp; }; unsigned int _M_ik, _M_k, _M_offset; _Loser* _M_losers; _Compare _M_comp; public: _LoserTreePointerUnguardedBase(unsigned int __k, const _Tp& __sentinel, _Compare __comp = std::less<_Tp>()) : _M_comp(__comp) { _M_ik = __k; // Next greater power of 2. _M_k = 1 << (__rd_log2(_M_ik - 1) + 1); _M_offset = _M_k; // Avoid default-constructing _M_losers[]._M_key _M_losers = new _Loser[2 * _M_k]; for (unsigned int __i = _M_k + _M_ik - 1; __i < (2 * _M_k); ++__i) { _M_losers[__i]._M_keyp = &__sentinel; _M_losers[__i]._M_source = -1; } } ~_LoserTreePointerUnguardedBase() { delete[] _M_losers; } int __get_min_source() { #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif return _M_losers[0]._M_source; } void __insert_start(const _Tp& __key, int __source, bool) { unsigned int __pos = _M_k + __source; _M_losers[__pos]._M_keyp = &__key; _M_losers[__pos]._M_source = __source; } }; /** * @brief Stable unguarded _LoserTree variant storing pointers. * * Unstable variant is implemented below using partial specialization. */ template class _LoserTreePointerUnguarded : public _LoserTreePointerUnguardedBase<_Tp, _Compare> { typedef _LoserTreePointerUnguardedBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; public: _LoserTreePointerUnguarded(unsigned int __k, const _Tp& __sentinel, _Compare __comp = std::less<_Tp>()) : _Base::_LoserTreePointerUnguardedBase(__k, __sentinel, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); if (!_M_comp(*_M_losers[__right]._M_keyp, *_M_losers[__left]._M_keyp)) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top at the beginning // (0 sequences!) _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif } void __delete_min_insert(const _Tp& __key, bool __sup) { #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif const _Tp* __keyp = &__key; int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted, ties are broken by _M_source. if (_M_comp(*_M_losers[__pos]._M_keyp, *__keyp) || (!_M_comp(*__keyp, *_M_losers[__pos]._M_keyp) && _M_losers[__pos]._M_source < __source)) { // The other one is smaller. std::swap(_M_losers[__pos]._M_source, __source); std::swap(_M_losers[__pos]._M_keyp, __keyp); } } _M_losers[0]._M_source = __source; _M_losers[0]._M_keyp = __keyp; } }; /** * @brief Unstable unguarded _LoserTree variant storing pointers. * * Stable variant is above. */ template class _LoserTreePointerUnguarded : public _LoserTreePointerUnguardedBase<_Tp, _Compare> { typedef _LoserTreePointerUnguardedBase<_Tp, _Compare> _Base; using _Base::_M_k; using _Base::_M_comp; using _Base::_M_losers; public: _LoserTreePointerUnguarded(unsigned int __k, const _Tp& __sentinel, _Compare __comp = std::less<_Tp>()) : _Base::_LoserTreePointerUnguardedBase(__k, __sentinel, __comp) { } unsigned int __init_winner(unsigned int __root) { if (__root >= _M_k) return __root; else { unsigned int __left = __init_winner(2 * __root); unsigned int __right = __init_winner(2 * __root + 1); #if _GLIBCXX_PARALLEL_ASSERTIONS // If __left one is sentinel then __right one must be, too. if (_M_losers[__left]._M_source == -1) _GLIBCXX_PARALLEL_ASSERT(_M_losers[__right]._M_source == -1); #endif if (!_M_comp(*_M_losers[__right]._M_keyp, *_M_losers[__left]._M_keyp)) { // Left one is less or equal. _M_losers[__root] = _M_losers[__right]; return __left; } else { // Right one is less. _M_losers[__root] = _M_losers[__left]; return __right; } } } void __init() { _M_losers[0] = _M_losers[__init_winner(1)]; #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top at the beginning // (0 sequences!) _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif } void __delete_min_insert(const _Tp& __key, bool __sup) { #if _GLIBCXX_PARALLEL_ASSERTIONS // no dummy sequence can ever be at the top! _GLIBCXX_PARALLEL_ASSERT(_M_losers[0]._M_source != -1); #endif const _Tp* __keyp = &__key; int __source = _M_losers[0]._M_source; for (unsigned int __pos = (_M_k + __source) / 2; __pos > 0; __pos /= 2) { // The smaller one gets promoted. if (_M_comp(*(_M_losers[__pos]._M_keyp), *__keyp)) { // The other one is smaller. std::swap(_M_losers[__pos]._M_source, __source); std::swap(_M_losers[__pos]._M_keyp, __keyp); } } _M_losers[0]._M_source = __source; _M_losers[0]._M_keyp = __keyp; } }; } // namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_LOSERTREE_H */ c++/8/parallel/basic_iterator.h000064400000003062151027430570012227 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/basic_iterator.h * @brief Includes the original header files concerned with iterators * except for stream iterators. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_BASIC_ITERATOR_H #define _GLIBCXX_PARALLEL_BASIC_ITERATOR_H 1 #include #include #include #include #endif /* _GLIBCXX_PARALLEL_BASIC_ITERATOR_H */ c++/8/parallel/types.h000064400000007204151027430570010403 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/types.h * @brief Basic types and typedefs. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_TYPES_H #define _GLIBCXX_PARALLEL_TYPES_H 1 #include #include #include namespace __gnu_parallel { // Enumerated types. /// Run-time equivalents for the compile-time tags. enum _Parallelism { /// Not parallel. sequential, /// Parallel unbalanced (equal-sized chunks). parallel_unbalanced, /// Parallel balanced (work-stealing). parallel_balanced, /// Parallel with OpenMP dynamic load-balancing. parallel_omp_loop, /// Parallel with OpenMP static load-balancing. parallel_omp_loop_static, /// Parallel with OpenMP taskqueue construct. parallel_taskqueue }; /// Strategies for run-time algorithm selection: // force_sequential, force_parallel, heuristic. enum _AlgorithmStrategy { heuristic, force_sequential, force_parallel }; /// Sorting algorithms: // multi-way mergesort, quicksort, load-balanced quicksort. enum _SortAlgorithm { MWMS, QS, QS_BALANCED }; /// Merging algorithms: // bubblesort-alike, loser-tree variants, enum __sentinel. enum _MultiwayMergeAlgorithm { LOSER_TREE }; /// Partial sum algorithms: recursive, linear. enum _PartialSumAlgorithm { RECURSIVE, LINEAR }; /// Sorting/merging algorithms: sampling, __exact. enum _SplittingAlgorithm { SAMPLING, EXACT }; /// Find algorithms: // growing blocks, equal-sized blocks, equal splitting. enum _FindAlgorithm { GROWING_BLOCKS, CONSTANT_SIZE_BLOCKS, EQUAL_SPLIT }; /** * @brief Unsigned integer to index __elements. * The total number of elements for each algorithm must fit into this type. */ typedef uint64_t _SequenceIndex; /** * @brief Unsigned integer to index a thread number. * The maximum thread number (for each processor) must fit into this type. */ typedef uint16_t _ThreadIndex; // XXX atomics interface? /// Longest compare-and-swappable integer type on this platform. typedef int64_t _CASable; /// Number of bits of _CASable. static const int _CASable_bits = std::numeric_limits<_CASable>::digits; /// ::_CASable with the right half of bits set to 1. static const _CASable _CASable_mask = ((_CASable(1) << (_CASable_bits / 2)) - 1); } #endif /* _GLIBCXX_PARALLEL_TYPES_H */ c++/8/parallel/for_each.h000064400000007553151027430570011014 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/for_each.h * @brief Main interface for embarrassingly parallel functions. * * The explicit implementation are in other header files, like * workstealing.h, par_loop.h, omp_loop.h, and omp_loop_static.h. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_FOR_EACH_H #define _GLIBCXX_PARALLEL_FOR_EACH_H 1 #include #include #include #include namespace __gnu_parallel { /** @brief Chose the desired algorithm by evaluating @c __parallelism_tag. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __user_op A user-specified functor (comparator, predicate, * associative operator,...) * @param __functionality functor to @a process an element with * __user_op (depends on desired functionality, e. g. accumulate, * for_each,... * @param __reduction Reduction functor. * @param __reduction_start Initial value for reduction. * @param __output Output iterator. * @param __bound Maximum number of elements processed. * @param __parallelism_tag Parallelization method */ template _UserOp __for_each_template_random_access(_IIter __begin, _IIter __end, _UserOp __user_op, _Functionality& __functionality, _Red __reduction, _Result __reduction_start, _Result& __output, typename std::iterator_traits<_IIter>:: difference_type __bound, _Parallelism __parallelism_tag) { if (__parallelism_tag == parallel_unbalanced) return __for_each_template_random_access_ed (__begin, __end, __user_op, __functionality, __reduction, __reduction_start, __output, __bound); else if (__parallelism_tag == parallel_omp_loop) return __for_each_template_random_access_omp_loop (__begin, __end, __user_op, __functionality, __reduction, __reduction_start, __output, __bound); else if (__parallelism_tag == parallel_omp_loop_static) return __for_each_template_random_access_omp_loop (__begin, __end, __user_op, __functionality, __reduction, __reduction_start, __output, __bound); else //e. g. parallel_balanced return __for_each_template_random_access_workstealing (__begin, __end, __user_op, __functionality, __reduction, __reduction_start, __output, __bound); } } #endif /* _GLIBCXX_PARALLEL_FOR_EACH_H */ c++/8/parallel/features.h000064400000006727151027430570011066 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/features.h * @brief Defines on whether to include algorithm variants. * * Less variants reduce executable size and compile time. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_FEATURES_H #define _GLIBCXX_PARALLEL_FEATURES_H 1 #ifndef _GLIBCXX_MERGESORT /** @def _GLIBCXX_MERGESORT * @brief Include parallel multi-way mergesort. * @see __gnu_parallel::_Settings::sort_algorithm */ #define _GLIBCXX_MERGESORT 1 #endif #ifndef _GLIBCXX_QUICKSORT /** @def _GLIBCXX_QUICKSORT * @brief Include parallel unbalanced quicksort. * @see __gnu_parallel::_Settings::sort_algorithm */ #define _GLIBCXX_QUICKSORT 1 #endif #ifndef _GLIBCXX_BAL_QUICKSORT /** @def _GLIBCXX_BAL_QUICKSORT * @brief Include parallel dynamically load-balanced quicksort. * @see __gnu_parallel::_Settings::sort_algorithm */ #define _GLIBCXX_BAL_QUICKSORT 1 #endif #ifndef _GLIBCXX_FIND_GROWING_BLOCKS /** @brief Include the growing blocks variant for std::find. * @see __gnu_parallel::_Settings::find_algorithm */ #define _GLIBCXX_FIND_GROWING_BLOCKS 1 #endif #ifndef _GLIBCXX_FIND_CONSTANT_SIZE_BLOCKS /** @brief Include the equal-sized blocks variant for std::find. * @see __gnu_parallel::_Settings::find_algorithm */ #define _GLIBCXX_FIND_CONSTANT_SIZE_BLOCKS 1 #endif #ifndef _GLIBCXX_FIND_EQUAL_SPLIT /** @def _GLIBCXX_FIND_EQUAL_SPLIT * @brief Include the equal splitting variant for std::find. * @see __gnu_parallel::_Settings::find_algorithm */ #define _GLIBCXX_FIND_EQUAL_SPLIT 1 #endif #ifndef _GLIBCXX_TREE_INITIAL_SPLITTING /** @def _GLIBCXX_TREE_INITIAL_SPLITTING * @brief Include the initial splitting variant for * _Rb_tree::insert_unique(_IIter beg, _IIter __end). * @see __gnu_parallel::_Rb_tree */ #define _GLIBCXX_TREE_INITIAL_SPLITTING 1 #endif #ifndef _GLIBCXX_TREE_DYNAMIC_BALANCING /** @def _GLIBCXX_TREE_DYNAMIC_BALANCING * @brief Include the dynamic balancing variant for * _Rb_tree::insert_unique(_IIter beg, _IIter __end). * @see __gnu_parallel::_Rb_tree */ #define _GLIBCXX_TREE_DYNAMIC_BALANCING 1 #endif #ifndef _GLIBCXX_TREE_FULL_COPY /** @def _GLIBCXX_TREE_FULL_COPY * @brief In order to sort the input sequence of * _Rb_tree::insert_unique(_IIter beg, _IIter __end) a * full copy of the input elements is done. * @see __gnu_parallel::_Rb_tree */ #define _GLIBCXX_TREE_FULL_COPY 1 #endif #endif /* _GLIBCXX_PARALLEL_FEATURES_H */ c++/8/parallel/balanced_quicksort.h000064400000041070151027430570013073 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/balanced_quicksort.h * @brief Implementation of a dynamically load-balanced parallel quicksort. * * It works in-place and needs only logarithmic extra memory. * The algorithm is similar to the one proposed in * * P. Tsigas and Y. Zhang. * A simple, fast parallel implementation of quicksort and * its performance evaluation on SUN enterprise 10000. * In 11th Euromicro Conference on Parallel, Distributed and * Network-Based Processing, page 372, 2003. * * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H #define _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H 1 #include #include #include #include #include #include #include #if _GLIBCXX_PARALLEL_ASSERTIONS #include #ifdef _GLIBCXX_HAVE_UNISTD_H #include #endif #endif namespace __gnu_parallel { /** @brief Information local to one thread in the parallel quicksort run. */ template struct _QSBThreadLocal { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; /** @brief Continuous part of the sequence, described by an iterator pair. */ typedef std::pair<_RAIter, _RAIter> _Piece; /** @brief Initial piece to work on. */ _Piece _M_initial; /** @brief Work-stealing queue. */ _RestrictedBoundedConcurrentQueue<_Piece> _M_leftover_parts; /** @brief Number of threads involved in this algorithm. */ _ThreadIndex _M_num_threads; /** @brief Pointer to a counter of elements left over to sort. */ volatile _DifferenceType* _M_elements_leftover; /** @brief The complete sequence to sort. */ _Piece _M_global; /** @brief Constructor. * @param __queue_size size of the work-stealing queue. */ _QSBThreadLocal(int __queue_size) : _M_leftover_parts(__queue_size) { } }; /** @brief Balanced quicksort divide step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. * @pre @c (__end-__begin)>=1 */ template typename std::iterator_traits<_RAIter>::difference_type __qsb_divide(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { _GLIBCXX_PARALLEL_ASSERT(__num_threads > 0); typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _RAIter __pivot_pos = __median_of_three_iterators(__begin, __begin + (__end - __begin) / 2, __end - 1, __comp); #if defined(_GLIBCXX_PARALLEL_ASSERTIONS) // Must be in between somewhere. _DifferenceType __n = __end - __begin; _GLIBCXX_PARALLEL_ASSERT((!__comp(*__pivot_pos, *__begin) && !__comp(*(__begin + __n / 2), *__pivot_pos)) || (!__comp(*__pivot_pos, *__begin) && !__comp(*(__end - 1), *__pivot_pos)) || (!__comp(*__pivot_pos, *(__begin + __n / 2)) && !__comp(*__begin, *__pivot_pos)) || (!__comp(*__pivot_pos, *(__begin + __n / 2)) && !__comp(*(__end - 1), *__pivot_pos)) || (!__comp(*__pivot_pos, *(__end - 1)) && !__comp(*__begin, *__pivot_pos)) || (!__comp(*__pivot_pos, *(__end - 1)) && !__comp(*(__begin + __n / 2), *__pivot_pos))); #endif // Swap pivot value to end. if (__pivot_pos != (__end - 1)) std::iter_swap(__pivot_pos, __end - 1); __pivot_pos = __end - 1; __gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool> __pred(__comp, *__pivot_pos); // Divide, returning __end - __begin - 1 in the worst case. _DifferenceType __split_pos = __parallel_partition(__begin, __end - 1, __pred, __num_threads); // Swap back pivot to middle. std::iter_swap(__begin + __split_pos, __pivot_pos); __pivot_pos = __begin + __split_pos; #if _GLIBCXX_PARALLEL_ASSERTIONS _RAIter __r; for (__r = __begin; __r != __pivot_pos; ++__r) _GLIBCXX_PARALLEL_ASSERT(__comp(*__r, *__pivot_pos)); for (; __r != __end; ++__r) _GLIBCXX_PARALLEL_ASSERT(!__comp(*__r, *__pivot_pos)); #endif return __split_pos; } /** @brief Quicksort conquer step. * @param __tls Array of thread-local storages. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __iam Number of the thread processing this function. * @param __num_threads * Number of threads that are allowed to work on this part. */ template void __qsb_conquer(_QSBThreadLocal<_RAIter>** __tls, _RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __iam, _ThreadIndex __num_threads, bool __parent_wait) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; if (__num_threads <= 1 || __n <= 1) { __tls[__iam]->_M_initial.first = __begin; __tls[__iam]->_M_initial.second = __end; __qsb_local_sort_with_helping(__tls, __comp, __iam, __parent_wait); return; } // Divide step. _DifferenceType __split_pos = __qsb_divide(__begin, __end, __comp, __num_threads); #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(0 <= __split_pos && __split_pos < (__end - __begin)); #endif _ThreadIndex __num_threads_leftside = std::max<_ThreadIndex> (1, std::min<_ThreadIndex>(__num_threads - 1, __split_pos * __num_threads / __n)); # pragma omp atomic *__tls[__iam]->_M_elements_leftover -= (_DifferenceType)1; // Conquer step. # pragma omp parallel num_threads(2) { bool __wait; if(omp_get_num_threads() < 2) __wait = false; else __wait = __parent_wait; # pragma omp sections { # pragma omp section { __qsb_conquer(__tls, __begin, __begin + __split_pos, __comp, __iam, __num_threads_leftside, __wait); __wait = __parent_wait; } // The pivot_pos is left in place, to ensure termination. # pragma omp section { __qsb_conquer(__tls, __begin + __split_pos + 1, __end, __comp, __iam + __num_threads_leftside, __num_threads - __num_threads_leftside, __wait); __wait = __parent_wait; } } } } /** * @brief Quicksort step doing load-balanced local sort. * @param __tls Array of thread-local storages. * @param __comp Comparator. * @param __iam Number of the thread processing this function. */ template void __qsb_local_sort_with_helping(_QSBThreadLocal<_RAIter>** __tls, _Compare& __comp, _ThreadIndex __iam, bool __wait) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; typedef std::pair<_RAIter, _RAIter> _Piece; _QSBThreadLocal<_RAIter>& __tl = *__tls[__iam]; _DifferenceType __base_case_n = _Settings::get().sort_qsb_base_case_maximal_n; if (__base_case_n < 2) __base_case_n = 2; _ThreadIndex __num_threads = __tl._M_num_threads; // Every thread has its own random number generator. _RandomNumber __rng(__iam + 1); _Piece __current = __tl._M_initial; _DifferenceType __elements_done = 0; #if _GLIBCXX_PARALLEL_ASSERTIONS _DifferenceType __total_elements_done = 0; #endif for (;;) { // Invariant: __current must be a valid (maybe empty) range. _RAIter __begin = __current.first, __end = __current.second; _DifferenceType __n = __end - __begin; if (__n > __base_case_n) { // Divide. _RAIter __pivot_pos = __begin + __rng(__n); // Swap __pivot_pos value to end. if (__pivot_pos != (__end - 1)) std::iter_swap(__pivot_pos, __end - 1); __pivot_pos = __end - 1; __gnu_parallel::__binder2nd <_Compare, _ValueType, _ValueType, bool> __pred(__comp, *__pivot_pos); // Divide, leave pivot unchanged in last place. _RAIter __split_pos1, __split_pos2; __split_pos1 = __gnu_sequential::partition(__begin, __end - 1, __pred); // Left side: < __pivot_pos; __right side: >= __pivot_pos. #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__begin <= __split_pos1 && __split_pos1 < __end); #endif // Swap pivot back to middle. if (__split_pos1 != __pivot_pos) std::iter_swap(__split_pos1, __pivot_pos); __pivot_pos = __split_pos1; // In case all elements are equal, __split_pos1 == 0. if ((__split_pos1 + 1 - __begin) < (__n >> 7) || (__end - __split_pos1) < (__n >> 7)) { // Very unequal split, one part smaller than one 128th // elements not strictly larger than the pivot. __gnu_parallel::__unary_negate<__gnu_parallel::__binder1st <_Compare, _ValueType, _ValueType, bool>, _ValueType> __pred(__gnu_parallel::__binder1st <_Compare, _ValueType, _ValueType, bool> (__comp, *__pivot_pos)); // Find other end of pivot-equal range. __split_pos2 = __gnu_sequential::partition(__split_pos1 + 1, __end, __pred); } else // Only skip the pivot. __split_pos2 = __split_pos1 + 1; // Elements equal to pivot are done. __elements_done += (__split_pos2 - __split_pos1); #if _GLIBCXX_PARALLEL_ASSERTIONS __total_elements_done += (__split_pos2 - __split_pos1); #endif // Always push larger part onto stack. if (((__split_pos1 + 1) - __begin) < (__end - (__split_pos2))) { // Right side larger. if ((__split_pos2) != __end) __tl._M_leftover_parts.push_front (std::make_pair(__split_pos2, __end)); //__current.first = __begin; //already set anyway __current.second = __split_pos1; continue; } else { // Left side larger. if (__begin != __split_pos1) __tl._M_leftover_parts.push_front(std::make_pair (__begin, __split_pos1)); __current.first = __split_pos2; //__current.second = __end; //already set anyway continue; } } else { __gnu_sequential::sort(__begin, __end, __comp); __elements_done += __n; #if _GLIBCXX_PARALLEL_ASSERTIONS __total_elements_done += __n; #endif // Prefer own stack, small pieces. if (__tl._M_leftover_parts.pop_front(__current)) continue; # pragma omp atomic *__tl._M_elements_leftover -= __elements_done; __elements_done = 0; #if _GLIBCXX_PARALLEL_ASSERTIONS double __search_start = omp_get_wtime(); #endif // Look for new work. bool __successfully_stolen = false; while (__wait && *__tl._M_elements_leftover > 0 && !__successfully_stolen #if _GLIBCXX_PARALLEL_ASSERTIONS // Possible dead-lock. && (omp_get_wtime() < (__search_start + 1.0)) #endif ) { _ThreadIndex __victim; __victim = __rng(__num_threads); // Large pieces. __successfully_stolen = (__victim != __iam) && __tls[__victim]->_M_leftover_parts.pop_back(__current); if (!__successfully_stolen) __yield(); #if !defined(__ICC) && !defined(__ECC) # pragma omp flush #endif } #if _GLIBCXX_PARALLEL_ASSERTIONS if (omp_get_wtime() >= (__search_start + 1.0)) { sleep(1); _GLIBCXX_PARALLEL_ASSERT(omp_get_wtime() < (__search_start + 1.0)); } #endif if (!__successfully_stolen) { #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(*__tl._M_elements_leftover == 0); #endif return; } } } } /** @brief Top-level quicksort routine. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template void __parallel_sort_qsb(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { _GLIBCXX_CALL(__end - __begin) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; typedef std::pair<_RAIter, _RAIter> _Piece; typedef _QSBThreadLocal<_RAIter> _TLSType; _DifferenceType __n = __end - __begin; if (__n <= 1) return; // At least one element per processor. if (__num_threads > __n) __num_threads = static_cast<_ThreadIndex>(__n); // Initialize thread local storage _TLSType** __tls = new _TLSType*[__num_threads]; _DifferenceType __queue_size = (__num_threads * (_ThreadIndex)(__rd_log2(__n) + 1)); for (_ThreadIndex __t = 0; __t < __num_threads; ++__t) __tls[__t] = new _QSBThreadLocal<_RAIter>(__queue_size); // There can never be more than ceil(__rd_log2(__n)) ranges on the // stack, because // 1. Only one processor pushes onto the stack // 2. The largest range has at most length __n // 3. Each range is larger than half of the range remaining volatile _DifferenceType __elements_leftover = __n; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) { __tls[__i]->_M_elements_leftover = &__elements_leftover; __tls[__i]->_M_num_threads = __num_threads; __tls[__i]->_M_global = std::make_pair(__begin, __end); // Just in case nothing is left to assign. __tls[__i]->_M_initial = std::make_pair(__end, __end); } // Main recursion call. __qsb_conquer(__tls, __begin, __begin + __n, __comp, 0, __num_threads, true); #if _GLIBCXX_PARALLEL_ASSERTIONS // All stack must be empty. _Piece __dummy; for (_ThreadIndex __i = 1; __i < __num_threads; ++__i) _GLIBCXX_PARALLEL_ASSERT( !__tls[__i]->_M_leftover_parts.pop_back(__dummy)); #endif for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) delete __tls[__i]; delete[] __tls; } } // namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H */ c++/8/parallel/par_loop.h000064400000010710151027430570011046 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/par_loop.h * @brief Parallelization of embarrassingly parallel execution by * means of equal splitting. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_PAR_LOOP_H #define _GLIBCXX_PARALLEL_PAR_LOOP_H 1 #include #include #include #include namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using hand-crafted parallelization by equal splitting * the work. * * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __o User-supplied functor (comparator, predicate, adding * functor, ...) * @param __f Functor to "process" an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to "add" a single __result to the already * processed elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template _Op __for_each_template_random_access_ed(_RAIter __begin, _RAIter __end, _Op __o, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; const _DifferenceType __length = __end - __begin; _Result *__thread_results; bool* __constructed; _ThreadIndex __num_threads = __gnu_parallel::min<_DifferenceType> (__get_max_threads(), __length); # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __thread_results = static_cast<_Result*> (::operator new(__num_threads * sizeof(_Result))); __constructed = new bool[__num_threads]; } _ThreadIndex __iam = omp_get_thread_num(); // Neutral element. _Result* __reduct; _DifferenceType __start = __equally_split_point(__length, __num_threads, __iam), __stop = __equally_split_point(__length, __num_threads, __iam + 1); if (__start < __stop) { __reduct = new _Result(__f(__o, __begin + __start)); ++__start; __constructed[__iam] = true; } else __constructed[__iam] = false; for (; __start < __stop; ++__start) *__reduct = __r(*__reduct, __f(__o, __begin + __start)); if (__constructed[__iam]) { ::new(&__thread_results[__iam]) _Result(*__reduct); delete __reduct; } } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) if (__constructed[__i]) { __output = __r(__output, __thread_results[__i]); __thread_results[__i].~_Result(); } // Points to last element processed (needed as return value for // some algorithms like transform). __f._M_finish_iterator = __begin + __length; ::operator delete(__thread_results); delete[] __constructed; return __o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_PAR_LOOP_H */ c++/8/parallel/checkers.h000064400000004374151027430570011033 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/checkers.h * @brief Routines for checking the correctness of algorithm results. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_CHECKERS_H #define _GLIBCXX_PARALLEL_CHECKERS_H 1 #include #include #include namespace __gnu_parallel { /** * @brief Check whether @c [__begin, @c __end) is sorted according * to @c __comp. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __comp Comparator. * @return @c true if sorted, @c false otherwise. */ template bool __is_sorted(_IIter __begin, _IIter __end, _Compare __comp) { if (__begin == __end) return true; _IIter __current(__begin), __recent(__begin); unsigned long long __position = 1; for (__current++; __current != __end; __current++) { if (__comp(*__current, *__recent)) { return false; } __recent = __current; __position++; } return true; } } #endif /* _GLIBCXX_PARALLEL_CHECKERS_H */ c++/8/parallel/numeric000064400000050355151027430570010460 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** * @file parallel/numeric * * @brief Parallel STL function calls corresponding to stl_numeric.h. * The functions defined here mainly do case switches and * call the actual parallelized versions in other files. * Inlining policy: Functions that basically only contain one function call, * are declared inline. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_NUMERIC_H #define _GLIBCXX_PARALLEL_NUMERIC_H 1 #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __parallel { // Sequential fallback. template inline _Tp accumulate(_IIter __begin, _IIter __end, _Tp __init, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::accumulate(__begin, __end, __init); } template inline _Tp accumulate(_IIter __begin, _IIter __end, _Tp __init, _BinaryOperation __binary_op, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::accumulate(__begin, __end, __init, __binary_op); } // Sequential fallback for input iterator case. template inline _Tp __accumulate_switch(_IIter __begin, _IIter __end, _Tp __init, _IteratorTag) { return accumulate(__begin, __end, __init, __gnu_parallel::sequential_tag()); } template inline _Tp __accumulate_switch(_IIter __begin, _IIter __end, _Tp __init, _BinaryOperation __binary_op, _IteratorTag) { return accumulate(__begin, __end, __init, __binary_op, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators. template _Tp __accumulate_switch(__RAIter __begin, __RAIter __end, _Tp __init, _BinaryOperation __binary_op, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().accumulate_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { _Tp __res = __init; __gnu_parallel::__accumulate_selector<__RAIter> __my_selector; __gnu_parallel:: __for_each_template_random_access_ed(__begin, __end, __gnu_parallel::_Nothing(), __my_selector, __gnu_parallel:: __accumulate_binop_reduct <_BinaryOperation>(__binary_op), __res, __res, -1); return __res; } else return accumulate(__begin, __end, __init, __binary_op, __gnu_parallel::sequential_tag()); } // Public interface. template inline _Tp accumulate(_IIter __begin, _IIter __end, _Tp __init, __gnu_parallel::_Parallelism __parallelism_tag) { typedef std::iterator_traits<_IIter> _IteratorTraits; typedef typename _IteratorTraits::value_type _ValueType; typedef typename _IteratorTraits::iterator_category _IteratorCategory; return __accumulate_switch(__begin, __end, __init, __gnu_parallel::_Plus<_Tp, _ValueType>(), _IteratorCategory(), __parallelism_tag); } template inline _Tp accumulate(_IIter __begin, _IIter __end, _Tp __init) { typedef std::iterator_traits<_IIter> _IteratorTraits; typedef typename _IteratorTraits::value_type _ValueType; typedef typename _IteratorTraits::iterator_category _IteratorCategory; return __accumulate_switch(__begin, __end, __init, __gnu_parallel::_Plus<_Tp, _ValueType>(), _IteratorCategory()); } template inline _Tp accumulate(_IIter __begin, _IIter __end, _Tp __init, _BinaryOperation __binary_op, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_IIter> _IteratorTraits; typedef typename _IteratorTraits::iterator_category _IteratorCategory; return __accumulate_switch(__begin, __end, __init, __binary_op, _IteratorCategory(), __parallelism_tag); } template inline _Tp accumulate(_IIter __begin, _IIter __end, _Tp __init, _BinaryOperation __binary_op) { typedef iterator_traits<_IIter> _IteratorTraits; typedef typename _IteratorTraits::iterator_category _IteratorCategory; return __accumulate_switch(__begin, __end, __init, __binary_op, _IteratorCategory()); } // Sequential fallback. template inline _Tp inner_product(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::inner_product( __first1, __last1, __first2, __init); } template inline _Tp inner_product(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init, _BinaryFunction1 __binary_op1, _BinaryFunction2 __binary_op2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::inner_product(__first1, __last1, __first2, __init, __binary_op1, __binary_op2); } // Parallel algorithm for random access iterators. template _Tp __inner_product_switch(_RAIter1 __first1, _RAIter1 __last1, _RAIter2 __first2, _Tp __init, _BinaryFunction1 __binary_op1, _BinaryFunction2 __binary_op2, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION((__last1 - __first1) >= __gnu_parallel::_Settings::get(). accumulate_minimal_n && __gnu_parallel:: __is_parallel(__parallelism_tag))) { _Tp __res = __init; __gnu_parallel:: __inner_product_selector<_RAIter1, _RAIter2, _Tp> __my_selector(__first1, __first2); __gnu_parallel:: __for_each_template_random_access_ed( __first1, __last1, __binary_op2, __my_selector, __binary_op1, __res, __res, -1); return __res; } else return inner_product(__first1, __last1, __first2, __init, __gnu_parallel::sequential_tag()); } // No parallelism for input iterators. template inline _Tp __inner_product_switch(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init, _BinaryFunction1 __binary_op1, _BinaryFunction2 __binary_op2, _IteratorTag1, _IteratorTag2) { return inner_product(__first1, __last1, __first2, __init, __binary_op1, __binary_op2, __gnu_parallel::sequential_tag()); } template inline _Tp inner_product(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init, _BinaryFunction1 __binary_op1, _BinaryFunction2 __binary_op2, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_IIter1> _TraitsType1; typedef typename _TraitsType1::iterator_category _IteratorCategory1; typedef iterator_traits<_IIter2> _TraitsType2; typedef typename _TraitsType2::iterator_category _IteratorCategory2; return __inner_product_switch(__first1, __last1, __first2, __init, __binary_op1, __binary_op2, _IteratorCategory1(), _IteratorCategory2(), __parallelism_tag); } template inline _Tp inner_product(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init, _BinaryFunction1 __binary_op1, _BinaryFunction2 __binary_op2) { typedef iterator_traits<_IIter1> _TraitsType1; typedef typename _TraitsType1::iterator_category _IteratorCategory1; typedef iterator_traits<_IIter2> _TraitsType2; typedef typename _TraitsType2::iterator_category _IteratorCategory2; return __inner_product_switch(__first1, __last1, __first2, __init, __binary_op1, __binary_op2, _IteratorCategory1(), _IteratorCategory2()); } template inline _Tp inner_product(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_IIter1> _TraitsType1; typedef typename _TraitsType1::value_type _ValueType1; typedef iterator_traits<_IIter2> _TraitsType2; typedef typename _TraitsType2::value_type _ValueType2; typedef typename __gnu_parallel::_Multiplies<_ValueType1, _ValueType2>::result_type _MultipliesResultType; return __gnu_parallel::inner_product(__first1, __last1, __first2, __init, __gnu_parallel::_Plus<_Tp, _MultipliesResultType>(), __gnu_parallel:: _Multiplies<_ValueType1, _ValueType2>(), __parallelism_tag); } template inline _Tp inner_product(_IIter1 __first1, _IIter1 __last1, _IIter2 __first2, _Tp __init) { typedef iterator_traits<_IIter1> _TraitsType1; typedef typename _TraitsType1::value_type _ValueType1; typedef iterator_traits<_IIter2> _TraitsType2; typedef typename _TraitsType2::value_type _ValueType2; typedef typename __gnu_parallel::_Multiplies<_ValueType1, _ValueType2>::result_type _MultipliesResultType; return __gnu_parallel::inner_product(__first1, __last1, __first2, __init, __gnu_parallel::_Plus<_Tp, _MultipliesResultType>(), __gnu_parallel:: _Multiplies<_ValueType1, _ValueType2>()); } // Sequential fallback. template inline _OutputIterator partial_sum(_IIter __begin, _IIter __end, _OutputIterator __result, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::partial_sum(__begin, __end, __result); } // Sequential fallback. template inline _OutputIterator partial_sum(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::partial_sum(__begin, __end, __result, __bin_op); } // Sequential fallback for input iterator case. template inline _OutputIterator __partial_sum_switch(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, _IteratorTag1, _IteratorTag2) { return _GLIBCXX_STD_A::partial_sum(__begin, __end, __result, __bin_op); } // Parallel algorithm for random access iterators. template _OutputIterator __partial_sum_switch(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().partial_sum_minimal_n)) return __gnu_parallel::__parallel_partial_sum(__begin, __end, __result, __bin_op); else return partial_sum(__begin, __end, __result, __bin_op, __gnu_parallel::sequential_tag()); } // Public interface. template inline _OutputIterator partial_sum(_IIter __begin, _IIter __end, _OutputIterator __result) { typedef typename iterator_traits<_IIter>::value_type _ValueType; return __gnu_parallel::partial_sum(__begin, __end, __result, std::plus<_ValueType>()); } // Public interface template inline _OutputIterator partial_sum(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __binary_op) { typedef iterator_traits<_IIter> _ITraitsType; typedef typename _ITraitsType::iterator_category _IIteratorCategory; typedef iterator_traits<_OutputIterator> _OTraitsType; typedef typename _OTraitsType::iterator_category _OIterCategory; return __partial_sum_switch(__begin, __end, __result, __binary_op, _IIteratorCategory(), _OIterCategory()); } // Sequential fallback. template inline _OutputIterator adjacent_difference(_IIter __begin, _IIter __end, _OutputIterator __result, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::adjacent_difference(__begin, __end, __result); } // Sequential fallback. template inline _OutputIterator adjacent_difference(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::adjacent_difference(__begin, __end, __result, __bin_op); } // Sequential fallback for input iterator case. template inline _OutputIterator __adjacent_difference_switch(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, _IteratorTag1, _IteratorTag2) { return adjacent_difference(__begin, __end, __result, __bin_op, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators. template _OutputIterator __adjacent_difference_switch(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().adjacent_difference_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { bool __dummy = true; typedef __gnu_parallel::_IteratorPair<_IIter, _OutputIterator, random_access_iterator_tag> _ItTrip; *__result = *__begin; _ItTrip __begin_pair(__begin + 1, __result + 1), __end_pair(__end, __result + (__end - __begin)); __gnu_parallel::__adjacent_difference_selector<_ItTrip> __functionality; __gnu_parallel:: __for_each_template_random_access_ed( __begin_pair, __end_pair, __bin_op, __functionality, __gnu_parallel::_DummyReduct(), __dummy, __dummy, -1); return __functionality._M_finish_iterator; } else return adjacent_difference(__begin, __end, __result, __bin_op, __gnu_parallel::sequential_tag()); } // Public interface. template inline _OutputIterator adjacent_difference(_IIter __begin, _IIter __end, _OutputIterator __result, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; return adjacent_difference(__begin, __end, __result, std::minus<_ValueType>(), __parallelism_tag); } template inline _OutputIterator adjacent_difference(_IIter __begin, _IIter __end, _OutputIterator __result) { typedef iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; return adjacent_difference(__begin, __end, __result, std::minus<_ValueType>()); } template inline _OutputIterator adjacent_difference(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __binary_op, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_IIter> _ITraitsType; typedef typename _ITraitsType::iterator_category _IIteratorCategory; typedef iterator_traits<_OutputIterator> _OTraitsType; typedef typename _OTraitsType::iterator_category _OIterCategory; return __adjacent_difference_switch(__begin, __end, __result, __binary_op, _IIteratorCategory(), _OIterCategory(), __parallelism_tag); } template inline _OutputIterator adjacent_difference(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __binary_op) { typedef iterator_traits<_IIter> _ITraitsType; typedef typename _ITraitsType::iterator_category _IIteratorCategory; typedef iterator_traits<_OutputIterator> _OTraitsType; typedef typename _OTraitsType::iterator_category _OIterCategory; return __adjacent_difference_switch(__begin, __end, __result, __binary_op, _IIteratorCategory(), _OIterCategory()); } } // end namespace } // end namespace #endif /* _GLIBCXX_NUMERIC_H */ c++/8/parallel/omp_loop_static.h000064400000010010151027430570012417 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/omp_loop_static.h * @brief Parallelization of embarrassingly parallel execution by * means of an OpenMP for loop with static scheduling. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_OMP_LOOP_STATIC_H #define _GLIBCXX_PARALLEL_OMP_LOOP_STATIC_H 1 #include #include #include namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using an OpenMP for loop with static scheduling. * * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __o User-supplied functor (comparator, predicate, adding * functor, ...). * @param __f Functor to @a process an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to @a add a single __result to the already processed * __elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template _Op __for_each_template_random_access_omp_loop_static(_RAIter __begin, _RAIter __end, _Op __o, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { typedef typename std::iterator_traits<_RAIter>::difference_type _DifferenceType; _DifferenceType __length = __end - __begin; _ThreadIndex __num_threads = std::min<_DifferenceType> (__get_max_threads(), __length); _Result *__thread_results; # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __thread_results = new _Result[__num_threads]; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __thread_results[__i] = _Result(); } _ThreadIndex __iam = omp_get_thread_num(); #pragma omp for schedule(static, _Settings::get().workstealing_chunk_size) for (_DifferenceType __pos = 0; __pos < __length; ++__pos) __thread_results[__iam] = __r(__thread_results[__iam], __f(__o, __begin+__pos)); } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __output = __r(__output, __thread_results[__i]); delete [] __thread_results; // Points to last element processed (needed as return value for // some algorithms like transform). __f.finish_iterator = __begin + __length; return __o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_OMP_LOOP_STATIC_H */ c++/8/parallel/multiway_merge.h000064400000211607151027430570012275 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/multiway_merge.h * @brief Implementation of sequential and parallel multiway merge. * * Explanations on the high-speed merging routines in the appendix of * * P. Sanders. * Fast priority queues for cached memory. * ACM Journal of Experimental Algorithmics, 5, 2000. * * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Manuel Holtgrewe. #ifndef _GLIBCXX_PARALLEL_MULTIWAY_MERGE_H #define _GLIBCXX_PARALLEL_MULTIWAY_MERGE_H #include #include #include #include #include #include #if _GLIBCXX_PARALLEL_ASSERTIONS #include #endif /** @brief Length of a sequence described by a pair of iterators. */ #define _GLIBCXX_PARALLEL_LENGTH(__s) ((__s).second - (__s).first) namespace __gnu_parallel { template _OutputIterator __merge_advance(_RAIter1&, _RAIter1, _RAIter2&, _RAIter2, _OutputIterator, _DifferenceTp, _Compare); /** @brief _Iterator wrapper supporting an implicit supremum at the end * of the sequence, dominating all comparisons. * * The implicit supremum comes with a performance cost. * * Deriving from _RAIter is not possible since * _RAIter need not be a class. */ template class _GuardedIterator { private: /** @brief Current iterator __position. */ _RAIter _M_current; /** @brief End iterator of the sequence. */ _RAIter _M_end; /** @brief _Compare. */ _Compare& __comp; public: /** @brief Constructor. Sets iterator to beginning of sequence. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __comp Comparator provided for associated overloaded * compare operators. */ _GuardedIterator(_RAIter __begin, _RAIter __end, _Compare& __comp) : _M_current(__begin), _M_end(__end), __comp(__comp) { } /** @brief Pre-increment operator. * @return This. */ _GuardedIterator<_RAIter, _Compare>& operator++() { ++_M_current; return *this; } /** @brief Dereference operator. * @return Referenced element. */ typename std::iterator_traits<_RAIter>::value_type& operator*() { return *_M_current; } /** @brief Convert to wrapped iterator. * @return Wrapped iterator. */ operator _RAIter() { return _M_current; } /** @brief Compare two elements referenced by guarded iterators. * @param __bi1 First iterator. * @param __bi2 Second iterator. * @return @c true if less. */ friend bool operator<(_GuardedIterator<_RAIter, _Compare>& __bi1, _GuardedIterator<_RAIter, _Compare>& __bi2) { if (__bi1._M_current == __bi1._M_end) // __bi1 is sup return __bi2._M_current == __bi2._M_end; // __bi2 is not sup if (__bi2._M_current == __bi2._M_end) // __bi2 is sup return true; return (__bi1.__comp)(*__bi1, *__bi2); // normal compare } /** @brief Compare two elements referenced by guarded iterators. * @param __bi1 First iterator. * @param __bi2 Second iterator. * @return @c True if less equal. */ friend bool operator<=(_GuardedIterator<_RAIter, _Compare>& __bi1, _GuardedIterator<_RAIter, _Compare>& __bi2) { if (__bi2._M_current == __bi2._M_end) // __bi1 is sup return __bi1._M_current != __bi1._M_end; // __bi2 is not sup if (__bi1._M_current == __bi1._M_end) // __bi2 is sup return false; return !(__bi1.__comp)(*__bi2, *__bi1); // normal compare } }; template class _UnguardedIterator { private: /** @brief Current iterator __position. */ _RAIter _M_current; /** @brief _Compare. */ _Compare& __comp; public: /** @brief Constructor. Sets iterator to beginning of sequence. * @param __begin Begin iterator of sequence. * @param __end Unused, only for compatibility. * @param __comp Unused, only for compatibility. */ _UnguardedIterator(_RAIter __begin, _RAIter /* __end */, _Compare& __comp) : _M_current(__begin), __comp(__comp) { } /** @brief Pre-increment operator. * @return This. */ _UnguardedIterator<_RAIter, _Compare>& operator++() { ++_M_current; return *this; } /** @brief Dereference operator. * @return Referenced element. */ typename std::iterator_traits<_RAIter>::value_type& operator*() { return *_M_current; } /** @brief Convert to wrapped iterator. * @return Wrapped iterator. */ operator _RAIter() { return _M_current; } /** @brief Compare two elements referenced by unguarded iterators. * @param __bi1 First iterator. * @param __bi2 Second iterator. * @return @c true if less. */ friend bool operator<(_UnguardedIterator<_RAIter, _Compare>& __bi1, _UnguardedIterator<_RAIter, _Compare>& __bi2) { // Normal compare. return (__bi1.__comp)(*__bi1, *__bi2); } /** @brief Compare two elements referenced by unguarded iterators. * @param __bi1 First iterator. * @param __bi2 Second iterator. * @return @c True if less equal. */ friend bool operator<=(_UnguardedIterator<_RAIter, _Compare>& __bi1, _UnguardedIterator<_RAIter, _Compare>& __bi2) { // Normal compare. return !(__bi1.__comp)(*__bi2, *__bi1); } }; /** @brief Highly efficient 3-way merging procedure. * * Merging is done with the algorithm implementation described by Peter * Sanders. Basically, the idea is to minimize the number of necessary * comparison after merging an element. The implementation trick * that makes this fast is that the order of the sequences is stored * in the instruction pointer (translated into labels in C++). * * This works well for merging up to 4 sequences. * * Note that making the merging stable does @a not come at a * performance hit. * * Whether the merging is done guarded or unguarded is selected by the * used iterator class. * * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, less equal than the * total number of elements available. * * @return End iterator of output sequence. */ template class iterator, typename _RAIterIterator, typename _RAIter3, typename _DifferenceTp, typename _Compare> _RAIter3 multiway_merge_3_variant(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { _GLIBCXX_CALL(__length); typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; if (__length == 0) return __target; #if _GLIBCXX_PARALLEL_ASSERTIONS _DifferenceTp __orig_length = __length; #endif iterator<_RAIter1, _Compare> __seq0(__seqs_begin[0].first, __seqs_begin[0].second, __comp), __seq1(__seqs_begin[1].first, __seqs_begin[1].second, __comp), __seq2(__seqs_begin[2].first, __seqs_begin[2].second, __comp); if (__seq0 <= __seq1) { if (__seq1 <= __seq2) goto __s012; else if (__seq2 < __seq0) goto __s201; else goto __s021; } else { if (__seq1 <= __seq2) { if (__seq0 <= __seq2) goto __s102; else goto __s120; } else goto __s210; } #define _GLIBCXX_PARALLEL_MERGE_3_CASE(__a, __b, __c, __c0, __c1) \ __s ## __a ## __b ## __c : \ *__target = *__seq ## __a; \ ++__target; \ --__length; \ ++__seq ## __a; \ if (__length == 0) goto __finish; \ if (__seq ## __a __c0 __seq ## __b) goto __s ## __a ## __b ## __c; \ if (__seq ## __a __c1 __seq ## __c) goto __s ## __b ## __a ## __c; \ goto __s ## __b ## __c ## __a; _GLIBCXX_PARALLEL_MERGE_3_CASE(0, 1, 2, <=, <=); _GLIBCXX_PARALLEL_MERGE_3_CASE(1, 2, 0, <=, < ); _GLIBCXX_PARALLEL_MERGE_3_CASE(2, 0, 1, < , < ); _GLIBCXX_PARALLEL_MERGE_3_CASE(1, 0, 2, < , <=); _GLIBCXX_PARALLEL_MERGE_3_CASE(0, 2, 1, <=, <=); _GLIBCXX_PARALLEL_MERGE_3_CASE(2, 1, 0, < , < ); #undef _GLIBCXX_PARALLEL_MERGE_3_CASE __finish: ; #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT( ((_RAIter1)__seq0 - __seqs_begin[0].first) + ((_RAIter1)__seq1 - __seqs_begin[1].first) + ((_RAIter1)__seq2 - __seqs_begin[2].first) == __orig_length); #endif __seqs_begin[0].first = __seq0; __seqs_begin[1].first = __seq1; __seqs_begin[2].first = __seq2; return __target; } /** * @brief Highly efficient 4-way merging procedure. * * Merging is done with the algorithm implementation described by Peter * Sanders. Basically, the idea is to minimize the number of necessary * comparison after merging an element. The implementation trick * that makes this fast is that the order of the sequences is stored * in the instruction pointer (translated into goto labels in C++). * * This works well for merging up to 4 sequences. * * Note that making the merging stable does @a not come at a * performance hit. * * Whether the merging is done guarded or unguarded is selected by the * used iterator class. * * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, less equal than the * total number of elements available. * * @return End iterator of output sequence. */ template class iterator, typename _RAIterIterator, typename _RAIter3, typename _DifferenceTp, typename _Compare> _RAIter3 multiway_merge_4_variant(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { _GLIBCXX_CALL(__length); typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; iterator<_RAIter1, _Compare> __seq0(__seqs_begin[0].first, __seqs_begin[0].second, __comp), __seq1(__seqs_begin[1].first, __seqs_begin[1].second, __comp), __seq2(__seqs_begin[2].first, __seqs_begin[2].second, __comp), __seq3(__seqs_begin[3].first, __seqs_begin[3].second, __comp); #define _GLIBCXX_PARALLEL_DECISION(__a, __b, __c, __d) { \ if (__seq ## __d < __seq ## __a) \ goto __s ## __d ## __a ## __b ## __c; \ if (__seq ## __d < __seq ## __b) \ goto __s ## __a ## __d ## __b ## __c; \ if (__seq ## __d < __seq ## __c) \ goto __s ## __a ## __b ## __d ## __c; \ goto __s ## __a ## __b ## __c ## __d; } if (__seq0 <= __seq1) { if (__seq1 <= __seq2) _GLIBCXX_PARALLEL_DECISION(0,1,2,3) else if (__seq2 < __seq0) _GLIBCXX_PARALLEL_DECISION(2,0,1,3) else _GLIBCXX_PARALLEL_DECISION(0,2,1,3) } else { if (__seq1 <= __seq2) { if (__seq0 <= __seq2) _GLIBCXX_PARALLEL_DECISION(1,0,2,3) else _GLIBCXX_PARALLEL_DECISION(1,2,0,3) } else _GLIBCXX_PARALLEL_DECISION(2,1,0,3) } #define _GLIBCXX_PARALLEL_MERGE_4_CASE(__a, __b, __c, __d, \ __c0, __c1, __c2) \ __s ## __a ## __b ## __c ## __d: \ if (__length == 0) goto __finish; \ *__target = *__seq ## __a; \ ++__target; \ --__length; \ ++__seq ## __a; \ if (__seq ## __a __c0 __seq ## __b) \ goto __s ## __a ## __b ## __c ## __d; \ if (__seq ## __a __c1 __seq ## __c) \ goto __s ## __b ## __a ## __c ## __d; \ if (__seq ## __a __c2 __seq ## __d) \ goto __s ## __b ## __c ## __a ## __d; \ goto __s ## __b ## __c ## __d ## __a; _GLIBCXX_PARALLEL_MERGE_4_CASE(0, 1, 2, 3, <=, <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(0, 1, 3, 2, <=, <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(0, 2, 1, 3, <=, <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(0, 2, 3, 1, <=, <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(0, 3, 1, 2, <=, <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(0, 3, 2, 1, <=, <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(1, 0, 2, 3, < , <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(1, 0, 3, 2, < , <=, <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(1, 2, 0, 3, <=, < , <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(1, 2, 3, 0, <=, <=, < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(1, 3, 0, 2, <=, < , <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(1, 3, 2, 0, <=, <=, < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(2, 0, 1, 3, < , < , <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(2, 0, 3, 1, < , <=, < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(2, 1, 0, 3, < , < , <=); _GLIBCXX_PARALLEL_MERGE_4_CASE(2, 1, 3, 0, < , <=, < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(2, 3, 0, 1, <=, < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(2, 3, 1, 0, <=, < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(3, 0, 1, 2, < , < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(3, 0, 2, 1, < , < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(3, 1, 0, 2, < , < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(3, 1, 2, 0, < , < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(3, 2, 0, 1, < , < , < ); _GLIBCXX_PARALLEL_MERGE_4_CASE(3, 2, 1, 0, < , < , < ); #undef _GLIBCXX_PARALLEL_MERGE_4_CASE #undef _GLIBCXX_PARALLEL_DECISION __finish: ; __seqs_begin[0].first = __seq0; __seqs_begin[1].first = __seq1; __seqs_begin[2].first = __seq2; __seqs_begin[3].first = __seq3; return __target; } /** @brief Multi-way merging procedure for a high branching factor, * guarded case. * * This merging variant uses a LoserTree class as selected by _LT. * * Stability is selected through the used LoserTree class _LT. * * At least one non-empty sequence is required. * * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, less equal than the * total number of elements available. * * @return End iterator of output sequence. */ template _RAIter3 multiway_merge_loser_tree(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { _GLIBCXX_CALL(__length) typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIterIterator> ::difference_type _SeqNumber; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; _SeqNumber __k = static_cast<_SeqNumber>(__seqs_end - __seqs_begin); _LT __lt(__k, __comp); // Default value for potentially non-default-constructible types. _ValueType* __arbitrary_element = 0; for (_SeqNumber __t = 0; __t < __k; ++__t) { if(!__arbitrary_element && _GLIBCXX_PARALLEL_LENGTH(__seqs_begin[__t]) > 0) __arbitrary_element = &(*__seqs_begin[__t].first); } for (_SeqNumber __t = 0; __t < __k; ++__t) { if (__seqs_begin[__t].first == __seqs_begin[__t].second) __lt.__insert_start(*__arbitrary_element, __t, true); else __lt.__insert_start(*__seqs_begin[__t].first, __t, false); } __lt.__init(); _SeqNumber __source; for (_DifferenceType __i = 0; __i < __length; ++__i) { //take out __source = __lt.__get_min_source(); *(__target++) = *(__seqs_begin[__source].first++); // Feed. if (__seqs_begin[__source].first == __seqs_begin[__source].second) __lt.__delete_min_insert(*__arbitrary_element, true); else // Replace from same __source. __lt.__delete_min_insert(*__seqs_begin[__source].first, false); } return __target; } /** @brief Multi-way merging procedure for a high branching factor, * unguarded case. * * Merging is done using the LoserTree class _LT. * * Stability is selected by the used LoserTrees. * * @pre No input will run out of elements during the merge. * * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, less equal than the * total number of elements available. * * @return End iterator of output sequence. */ template _RAIter3 multiway_merge_loser_tree_unguarded(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, const typename std::iterator_traits::value_type::first_type>::value_type& __sentinel, _DifferenceTp __length, _Compare __comp) { _GLIBCXX_CALL(__length) typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIterIterator> ::difference_type _SeqNumber; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; _SeqNumber __k = __seqs_end - __seqs_begin; _LT __lt(__k, __sentinel, __comp); for (_SeqNumber __t = 0; __t < __k; ++__t) { #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__seqs_begin[__t].first != __seqs_begin[__t].second); #endif __lt.__insert_start(*__seqs_begin[__t].first, __t, false); } __lt.__init(); _SeqNumber __source; #if _GLIBCXX_PARALLEL_ASSERTIONS _DifferenceType __i = 0; #endif _RAIter3 __target_end = __target + __length; while (__target < __target_end) { // Take out. __source = __lt.__get_min_source(); #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(0 <= __source && __source < __k); _GLIBCXX_PARALLEL_ASSERT(__i == 0 || !__comp(*(__seqs_begin[__source].first), *(__target - 1))); #endif // Feed. *(__target++) = *(__seqs_begin[__source].first++); #if _GLIBCXX_PARALLEL_ASSERTIONS ++__i; #endif // Replace from same __source. __lt.__delete_min_insert(*__seqs_begin[__source].first, false); } return __target; } /** @brief Multi-way merging procedure for a high branching factor, * requiring sentinels to exist. * * @tparam UnguardedLoserTree _Loser Tree variant to use for the unguarded * merging. * * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, less equal than the * total number of elements available. * * @return End iterator of output sequence. */ template _RAIter3 multiway_merge_loser_tree_sentinel(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, const typename std::iterator_traits::value_type::first_type>::value_type& __sentinel, _DifferenceTp __length, _Compare __comp) { _GLIBCXX_CALL(__length) typedef _DifferenceTp _DifferenceType; typedef std::iterator_traits<_RAIterIterator> _TraitsType; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; _RAIter3 __target_end; for (_RAIterIterator __s = __seqs_begin; __s != __seqs_end; ++__s) // Move the sequence ends to the sentinel. This has the // effect that the sentinel appears to be within the sequence. Then, // we can use the unguarded variant if we merge out as many // non-sentinel elements as we have. ++((*__s).second); __target_end = multiway_merge_loser_tree_unguarded (__seqs_begin, __seqs_end, __target, __sentinel, __length, __comp); #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__target_end == __target + __length); _GLIBCXX_PARALLEL_ASSERT(__is_sorted(__target, __target_end, __comp)); #endif // Restore the sequence ends so the sentinels are not contained in the // sequence any more (see comment in loop above). for (_RAIterIterator __s = __seqs_begin; __s != __seqs_end; ++__s) --((*__s).second); return __target_end; } /** * @brief Traits for determining whether the loser tree should * use pointers or copies. * * The field "_M_use_pointer" is used to determine whether to use pointers * in he loser trees or whether to copy the values into the loser tree. * * The default behavior is to use pointers if the data type is 4 times as * big as the pointer to it. * * Specialize for your data type to customize the behavior. * * Example: * * template<> * struct _LoserTreeTraits * { static const bool _M_use_pointer = false; }; * * template<> * struct _LoserTreeTraits * { static const bool _M_use_pointer = true; }; * * @param _Tp type to give the loser tree traits for. */ template struct _LoserTreeTraits { /** * @brief True iff to use pointers instead of values in loser trees. * * The default behavior is to use pointers if the data type is four * times as big as the pointer to it. */ static const bool _M_use_pointer = (sizeof(_Tp) > 4 * sizeof(_Tp*)); }; /** * @brief Switch for 3-way merging with __sentinels turned off. * * Note that 3-way merging is always stable! */ template struct __multiway_merge_3_variant_sentinel_switch { _RAIter3 operator()(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { return multiway_merge_3_variant<_GuardedIterator> (__seqs_begin, __seqs_end, __target, __length, __comp); } }; /** * @brief Switch for 3-way merging with __sentinels turned on. * * Note that 3-way merging is always stable! */ template struct __multiway_merge_3_variant_sentinel_switch { _RAIter3 operator()(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { return multiway_merge_3_variant<_UnguardedIterator> (__seqs_begin, __seqs_end, __target, __length, __comp); } }; /** * @brief Switch for 4-way merging with __sentinels turned off. * * Note that 4-way merging is always stable! */ template struct __multiway_merge_4_variant_sentinel_switch { _RAIter3 operator()(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { return multiway_merge_4_variant<_GuardedIterator> (__seqs_begin, __seqs_end, __target, __length, __comp); } }; /** * @brief Switch for 4-way merging with __sentinels turned on. * * Note that 4-way merging is always stable! */ template struct __multiway_merge_4_variant_sentinel_switch { _RAIter3 operator()(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _DifferenceTp __length, _Compare __comp) { return multiway_merge_4_variant<_UnguardedIterator> (__seqs_begin, __seqs_end, __target, __length, __comp); } }; /** * @brief Switch for k-way merging with __sentinels turned on. */ template struct __multiway_merge_k_variant_sentinel_switch { _RAIter3 operator()(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, const typename std::iterator_traits::value_type::first_type>::value_type& __sentinel, _DifferenceTp __length, _Compare __comp) { typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; return multiway_merge_loser_tree_sentinel< typename __gnu_cxx::__conditional_type< _LoserTreeTraits<_ValueType>::_M_use_pointer, _LoserTreePointerUnguarded<__stable, _ValueType, _Compare>, _LoserTreeUnguarded<__stable, _ValueType, _Compare> >::__type> (__seqs_begin, __seqs_end, __target, __sentinel, __length, __comp); } }; /** * @brief Switch for k-way merging with __sentinels turned off. */ template struct __multiway_merge_k_variant_sentinel_switch { _RAIter3 operator()(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, const typename std::iterator_traits::value_type::first_type>::value_type& __sentinel, _DifferenceTp __length, _Compare __comp) { typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; return multiway_merge_loser_tree< typename __gnu_cxx::__conditional_type< _LoserTreeTraits<_ValueType>::_M_use_pointer, _LoserTreePointer<__stable, _ValueType, _Compare>, _LoserTree<__stable, _ValueType, _Compare> >::__type >(__seqs_begin, __seqs_end, __target, __length, __comp); } }; /** @brief Sequential multi-way merging switch. * * The _GLIBCXX_PARALLEL_DECISION is based on the branching factor and * runtime settings. * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, possibly larger than the * number of elements available. * @param __sentinel The sequences have __a __sentinel element. * @return End iterator of output sequence. */ template _RAIter3 __sequential_multiway_merge(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, const typename std::iterator_traits::value_type::first_type>::value_type& __sentinel, _DifferenceTp __length, _Compare __comp) { _GLIBCXX_CALL(__length) typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIterIterator> ::difference_type _SeqNumber; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; #if _GLIBCXX_PARALLEL_ASSERTIONS for (_RAIterIterator __s = __seqs_begin; __s != __seqs_end; ++__s) { _GLIBCXX_PARALLEL_ASSERT(__is_sorted((*__s).first, (*__s).second, __comp)); } #endif _DifferenceTp __total_length = 0; for (_RAIterIterator __s = __seqs_begin; __s != __seqs_end; ++__s) __total_length += _GLIBCXX_PARALLEL_LENGTH(*__s); __length = std::min<_DifferenceTp>(__length, __total_length); if(__length == 0) return __target; _RAIter3 __return_target = __target; _SeqNumber __k = static_cast<_SeqNumber>(__seqs_end - __seqs_begin); switch (__k) { case 0: break; case 1: __return_target = std::copy(__seqs_begin[0].first, __seqs_begin[0].first + __length, __target); __seqs_begin[0].first += __length; break; case 2: __return_target = __merge_advance(__seqs_begin[0].first, __seqs_begin[0].second, __seqs_begin[1].first, __seqs_begin[1].second, __target, __length, __comp); break; case 3: __return_target = __multiway_merge_3_variant_sentinel_switch <__sentinels, _RAIterIterator, _RAIter3, _DifferenceTp, _Compare>() (__seqs_begin, __seqs_end, __target, __length, __comp); break; case 4: __return_target = __multiway_merge_4_variant_sentinel_switch <__sentinels, _RAIterIterator, _RAIter3, _DifferenceTp, _Compare>() (__seqs_begin, __seqs_end, __target, __length, __comp); break; default: __return_target = __multiway_merge_k_variant_sentinel_switch <__sentinels, __stable, _RAIterIterator, _RAIter3, _DifferenceTp, _Compare>() (__seqs_begin, __seqs_end, __target, __sentinel, __length, __comp); break; } #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT( __is_sorted(__target, __target + __length, __comp)); #endif return __return_target; } /** * @brief Stable sorting functor. * * Used to reduce code instanciation in multiway_merge_sampling_splitting. */ template struct _SamplingSorter { void operator()(_RAIter __first, _RAIter __last, _StrictWeakOrdering __comp) { __gnu_sequential::stable_sort(__first, __last, __comp); } }; /** * @brief Non-__stable sorting functor. * * Used to reduce code instantiation in multiway_merge_sampling_splitting. */ template struct _SamplingSorter { void operator()(_RAIter __first, _RAIter __last, _StrictWeakOrdering __comp) { __gnu_sequential::sort(__first, __last, __comp); } }; /** * @brief Sampling based splitting for parallel multiway-merge routine. */ template void multiway_merge_sampling_splitting(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _DifferenceType __length, _DifferenceType __total_length, _Compare __comp, std::vector > *__pieces) { typedef typename std::iterator_traits<_RAIterIterator> ::difference_type _SeqNumber; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; // __k sequences. const _SeqNumber __k = static_cast<_SeqNumber>(__seqs_end - __seqs_begin); const _ThreadIndex __num_threads = omp_get_num_threads(); const _DifferenceType __num_samples = __gnu_parallel::_Settings::get().merge_oversampling * __num_threads; _ValueType* __samples = static_cast<_ValueType*> (::operator new(sizeof(_ValueType) * __k * __num_samples)); // Sample. for (_SeqNumber __s = 0; __s < __k; ++__s) for (_DifferenceType __i = 0; __i < __num_samples; ++__i) { _DifferenceType sample_index = static_cast<_DifferenceType> (_GLIBCXX_PARALLEL_LENGTH(__seqs_begin[__s]) * (double(__i + 1) / (__num_samples + 1)) * (double(__length) / __total_length)); new(&(__samples[__s * __num_samples + __i])) _ValueType(__seqs_begin[__s].first[sample_index]); } // Sort stable or non-stable, depending on value of template parameter // "__stable". _SamplingSorter<__stable, _ValueType*, _Compare>() (__samples, __samples + (__num_samples * __k), __comp); for (_ThreadIndex __slab = 0; __slab < __num_threads; ++__slab) // For each slab / processor. for (_SeqNumber __seq = 0; __seq < __k; ++__seq) { // For each sequence. if (__slab > 0) __pieces[__slab][__seq].first = std::upper_bound (__seqs_begin[__seq].first, __seqs_begin[__seq].second, __samples[__num_samples * __k * __slab / __num_threads], __comp) - __seqs_begin[__seq].first; else // Absolute beginning. __pieces[__slab][__seq].first = 0; if ((__slab + 1) < __num_threads) __pieces[__slab][__seq].second = std::upper_bound (__seqs_begin[__seq].first, __seqs_begin[__seq].second, __samples[__num_samples * __k * (__slab + 1) / __num_threads], __comp) - __seqs_begin[__seq].first; else // Absolute end. __pieces[__slab][__seq].second = _GLIBCXX_PARALLEL_LENGTH(__seqs_begin[__seq]); } for (_SeqNumber __s = 0; __s < __k; ++__s) for (_DifferenceType __i = 0; __i < __num_samples; ++__i) __samples[__s * __num_samples + __i].~_ValueType(); ::operator delete(__samples); } /** * @brief Exact splitting for parallel multiway-merge routine. * * None of the passed sequences may be empty. */ template void multiway_merge_exact_splitting(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _DifferenceType __length, _DifferenceType __total_length, _Compare __comp, std::vector > *__pieces) { typedef typename std::iterator_traits<_RAIterIterator> ::difference_type _SeqNumber; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; const bool __tight = (__total_length == __length); // __k sequences. const _SeqNumber __k = __seqs_end - __seqs_begin; const _ThreadIndex __num_threads = omp_get_num_threads(); // (Settings::multiway_merge_splitting // == __gnu_parallel::_Settings::EXACT). std::vector<_RAIter1>* __offsets = new std::vector<_RAIter1>[__num_threads]; std::vector > __se(__k); copy(__seqs_begin, __seqs_end, __se.begin()); _DifferenceType* __borders = new _DifferenceType[__num_threads + 1]; __equally_split(__length, __num_threads, __borders); for (_ThreadIndex __s = 0; __s < (__num_threads - 1); ++__s) { __offsets[__s].resize(__k); multiseq_partition(__se.begin(), __se.end(), __borders[__s + 1], __offsets[__s].begin(), __comp); // Last one also needed and available. if (!__tight) { __offsets[__num_threads - 1].resize(__k); multiseq_partition(__se.begin(), __se.end(), _DifferenceType(__length), __offsets[__num_threads - 1].begin(), __comp); } } delete[] __borders; for (_ThreadIndex __slab = 0; __slab < __num_threads; ++__slab) { // For each slab / processor. for (_SeqNumber __seq = 0; __seq < __k; ++__seq) { // For each sequence. if (__slab == 0) { // Absolute beginning. __pieces[__slab][__seq].first = 0; } else __pieces[__slab][__seq].first = __pieces[__slab - 1][__seq].second; if (!__tight || __slab < (__num_threads - 1)) __pieces[__slab][__seq].second = __offsets[__slab][__seq] - __seqs_begin[__seq].first; else { // __slab == __num_threads - 1 __pieces[__slab][__seq].second = _GLIBCXX_PARALLEL_LENGTH(__seqs_begin[__seq]); } } } delete[] __offsets; } /** @brief Parallel multi-way merge routine. * * The _GLIBCXX_PARALLEL_DECISION is based on the branching factor * and runtime settings. * * Must not be called if the number of sequences is 1. * * @tparam _Splitter functor to split input (either __exact or sampling based) * @tparam __stable Stable merging incurs a performance penalty. * @tparam __sentinel Ignored. * * @param __seqs_begin Begin iterator of iterator pair input sequence. * @param __seqs_end End iterator of iterator pair input sequence. * @param __target Begin iterator of output sequence. * @param __comp Comparator. * @param __length Maximum length to merge, possibly larger than the * number of elements available. * @return End iterator of output sequence. */ template _RAIter3 parallel_multiway_merge(_RAIterIterator __seqs_begin, _RAIterIterator __seqs_end, _RAIter3 __target, _Splitter __splitter, _DifferenceTp __length, _Compare __comp, _ThreadIndex __num_threads) { #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT(__seqs_end - __seqs_begin > 1); #endif _GLIBCXX_CALL(__length) typedef _DifferenceTp _DifferenceType; typedef typename std::iterator_traits<_RAIterIterator> ::difference_type _SeqNumber; typedef typename std::iterator_traits<_RAIterIterator> ::value_type::first_type _RAIter1; typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType; // Leave only non-empty sequences. typedef std::pair<_RAIter1, _RAIter1> seq_type; seq_type* __ne_seqs = new seq_type[__seqs_end - __seqs_begin]; _SeqNumber __k = 0; _DifferenceType __total_length = 0; for (_RAIterIterator __raii = __seqs_begin; __raii != __seqs_end; ++__raii) { _DifferenceTp __seq_length = _GLIBCXX_PARALLEL_LENGTH(*__raii); if(__seq_length > 0) { __total_length += __seq_length; __ne_seqs[__k++] = *__raii; } } _GLIBCXX_CALL(__total_length) __length = std::min<_DifferenceTp>(__length, __total_length); if (__total_length == 0 || __k == 0) { delete[] __ne_seqs; return __target; } std::vector >* __pieces; __num_threads = static_cast<_ThreadIndex> (std::min<_DifferenceType>(__num_threads, __total_length)); # pragma omp parallel num_threads (__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); // Thread __t will have to merge pieces[__iam][0..__k - 1] __pieces = new std::vector< std::pair<_DifferenceType, _DifferenceType> >[__num_threads]; for (_ThreadIndex __s = 0; __s < __num_threads; ++__s) __pieces[__s].resize(__k); _DifferenceType __num_samples = __gnu_parallel::_Settings::get().merge_oversampling * __num_threads; __splitter(__ne_seqs, __ne_seqs + __k, __length, __total_length, __comp, __pieces); } //single _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __target_position = 0; for (_SeqNumber __c = 0; __c < __k; ++__c) __target_position += __pieces[__iam][__c].first; seq_type* __chunks = new seq_type[__k]; for (_SeqNumber __s = 0; __s < __k; ++__s) __chunks[__s] = std::make_pair(__ne_seqs[__s].first + __pieces[__iam][__s].first, __ne_seqs[__s].first + __pieces[__iam][__s].second); if(__length > __target_position) __sequential_multiway_merge<__stable, __sentinels> (__chunks, __chunks + __k, __target + __target_position, *(__seqs_begin->second), __length - __target_position, __comp); delete[] __chunks; } // parallel #if _GLIBCXX_PARALLEL_ASSERTIONS _GLIBCXX_PARALLEL_ASSERT( __is_sorted(__target, __target + __length, __comp)); #endif __k = 0; // Update ends of sequences. for (_RAIterIterator __raii = __seqs_begin; __raii != __seqs_end; ++__raii) { _DifferenceTp __length = _GLIBCXX_PARALLEL_LENGTH(*__raii); if(__length > 0) (*__raii).first += __pieces[__num_threads - 1][__k++].second; } delete[] __pieces; delete[] __ne_seqs; return __target + __length; } /** * @brief Multiway Merge Frontend. * * Merge the sequences specified by seqs_begin and __seqs_end into * __target. __seqs_begin and __seqs_end must point to a sequence of * pairs. These pairs must contain an iterator to the beginning * of a sequence in their first entry and an iterator the _M_end of * the same sequence in their second entry. * * Ties are broken arbitrarily. See stable_multiway_merge for a variant * that breaks ties by sequence number but is slower. * * The first entries of the pairs (i.e. the begin iterators) will be moved * forward. * * The output sequence has to provide enough space for all elements * that are written to it. * * This function will merge the input sequences: * * - not stable * - parallel, depending on the input size and Settings * - using sampling for splitting * - not using sentinels * * Example: * *
   *   int sequences[10][10];
   *   for (int __i = 0; __i < 10; ++__i)
   *     for (int __j = 0; __i < 10; ++__j)
   *       sequences[__i][__j] = __j;
   *
   *   int __out[33];
   *   std::vector > seqs;
   *   for (int __i = 0; __i < 10; ++__i)
   *     { seqs.push(std::make_pair(sequences[__i],
   *                                      sequences[__i] + 10)) }
   *
   *   multiway_merge(seqs.begin(), seqs.end(), __target, std::less(), 33);
   * 
* * @see stable_multiway_merge * * @pre All input sequences must be sorted. * @pre Target must provide enough space to merge out length elements or * the number of elements in all sequences, whichever is smaller. * * @post [__target, return __value) contains merged __elements from the * input sequences. * @post return __value - __target = min(__length, number of elements in all * sequences). * * @tparam _RAIterPairIterator iterator over sequence * of pairs of iterators * @tparam _RAIterOut iterator over target sequence * @tparam _DifferenceTp difference type for the sequence * @tparam _Compare strict weak ordering type to compare elements * in sequences * * @param __seqs_begin __begin of sequence __sequence * @param __seqs_end _M_end of sequence __sequence * @param __target target sequence to merge to. * @param __comp strict weak ordering to use for element comparison. * @param __length Maximum length to merge, possibly larger than the * number of elements available. * * @return _M_end iterator of output sequence */ // multiway_merge // public interface template _RAIterOut multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::sequential_tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute multiway merge *sequentially*. return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::exact_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_exact_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::sampling_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_exact_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, parallel_tag __tag = parallel_tag(0)) { return multiway_merge(__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } // public interface template _RAIterOut multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, default_parallel_tag __tag) { return multiway_merge(__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } // stable_multiway_merge // public interface template _RAIterOut stable_multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::sequential_tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute multiway merge *sequentially*. return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut stable_multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::exact_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_exact_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut stable_multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, sampling_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_sampling_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut stable_multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, parallel_tag __tag = parallel_tag(0)) { return stable_multiway_merge (__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } // public interface template _RAIterOut stable_multiway_merge(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, default_parallel_tag __tag) { return stable_multiway_merge (__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } /** * @brief Multiway Merge Frontend. * * Merge the sequences specified by seqs_begin and __seqs_end into * __target. __seqs_begin and __seqs_end must point to a sequence of * pairs. These pairs must contain an iterator to the beginning * of a sequence in their first entry and an iterator the _M_end of * the same sequence in their second entry. * * Ties are broken arbitrarily. See stable_multiway_merge for a variant * that breaks ties by sequence number but is slower. * * The first entries of the pairs (i.e. the begin iterators) will be moved * forward accordingly. * * The output sequence has to provide enough space for all elements * that are written to it. * * This function will merge the input sequences: * * - not stable * - parallel, depending on the input size and Settings * - using sampling for splitting * - using sentinels * * You have to take care that the element the _M_end iterator points to is * readable and contains a value that is greater than any other non-sentinel * value in all sequences. * * Example: * *
   *   int sequences[10][11];
   *   for (int __i = 0; __i < 10; ++__i)
   *     for (int __j = 0; __i < 11; ++__j)
   *       sequences[__i][__j] = __j; // __last one is sentinel!
   *
   *   int __out[33];
   *   std::vector > seqs;
   *   for (int __i = 0; __i < 10; ++__i)
   *     { seqs.push(std::make_pair(sequences[__i],
   *                                      sequences[__i] + 10)) }
   *
   *   multiway_merge(seqs.begin(), seqs.end(), __target, std::less(), 33);
   * 
* * @pre All input sequences must be sorted. * @pre Target must provide enough space to merge out length elements or * the number of elements in all sequences, whichever is smaller. * @pre For each @c __i, @c __seqs_begin[__i].second must be the end * marker of the sequence, but also reference the one more __sentinel * element. * * @post [__target, return __value) contains merged __elements from the * input sequences. * @post return __value - __target = min(__length, number of elements in all * sequences). * * @see stable_multiway_merge_sentinels * * @tparam _RAIterPairIterator iterator over sequence * of pairs of iterators * @tparam _RAIterOut iterator over target sequence * @tparam _DifferenceTp difference type for the sequence * @tparam _Compare strict weak ordering type to compare elements * in sequences * * @param __seqs_begin __begin of sequence __sequence * @param __seqs_end _M_end of sequence __sequence * @param __target target sequence to merge to. * @param __comp strict weak ordering to use for element comparison. * @param __length Maximum length to merge, possibly larger than the * number of elements available. * * @return _M_end iterator of output sequence */ // multiway_merge_sentinels // public interface template _RAIterOut multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::sequential_tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute multiway merge *sequentially*. return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::exact_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_exact_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, sampling_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_sampling_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge ( __seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, parallel_tag __tag = parallel_tag(0)) { return multiway_merge_sentinels (__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } // public interface template _RAIterOut multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, default_parallel_tag __tag) { return multiway_merge_sentinels (__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } // stable_multiway_merge_sentinels // public interface template _RAIterOut stable_multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::sequential_tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute multiway merge *sequentially*. return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut stable_multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, __gnu_parallel::exact_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_exact_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut stable_multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, sampling_tag __tag) { typedef _DifferenceTp _DifferenceType; _GLIBCXX_CALL(__seqs_end - __seqs_begin) // catch special case: no sequences if (__seqs_begin == __seqs_end) return __target; // Execute merge; maybe parallel, depending on the number of merged // elements and the number of sequences and global thresholds in // Settings. if ((__seqs_end - __seqs_begin > 1) && _GLIBCXX_PARALLEL_CONDITION( ((__seqs_end - __seqs_begin) >= __gnu_parallel::_Settings::get().multiway_merge_minimal_k) && ((_SequenceIndex)__length >= __gnu_parallel::_Settings::get().multiway_merge_minimal_n))) return parallel_multiway_merge (__seqs_begin, __seqs_end, __target, multiway_merge_sampling_splitting ::value_type*, _Compare, _DifferenceTp>, static_cast<_DifferenceType>(__length), __comp, __tag.__get_num_threads()); else return __sequential_multiway_merge (__seqs_begin, __seqs_end, __target, *(__seqs_begin->second), __length, __comp); } // public interface template _RAIterOut stable_multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, parallel_tag __tag = parallel_tag(0)) { return stable_multiway_merge_sentinels (__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } // public interface template _RAIterOut stable_multiway_merge_sentinels(_RAIterPairIterator __seqs_begin, _RAIterPairIterator __seqs_end, _RAIterOut __target, _DifferenceTp __length, _Compare __comp, default_parallel_tag __tag) { return stable_multiway_merge_sentinels (__seqs_begin, __seqs_end, __target, __length, __comp, exact_tag(__tag.__get_num_threads())); } }; // namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_MULTIWAY_MERGE_H */ c++/8/parallel/random_shuffle.h000064400000044363151027430570012242 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/random_shuffle.h * @brief Parallel implementation of std::random_shuffle(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H #define _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H 1 #include #include #include #include namespace __gnu_parallel { /** @brief Type to hold the index of a bin. * * Since many variables of this type are allocated, it should be * chosen as small as possible. */ typedef unsigned short _BinIndex; /** @brief Data known to every thread participating in __gnu_parallel::__parallel_random_shuffle(). */ template struct _DRandomShufflingGlobalData { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; /** @brief Begin iterator of the __source. */ _RAIter& _M_source; /** @brief Temporary arrays for each thread. */ _ValueType** _M_temporaries; /** @brief Two-dimensional array to hold the thread-bin distribution. * * Dimensions (_M_num_threads + 1) __x (_M_num_bins + 1). */ _DifferenceType** _M_dist; /** @brief Start indexes of the threads' __chunks. */ _DifferenceType* _M_starts; /** @brief Number of the thread that will further process the corresponding bin. */ _ThreadIndex* _M_bin_proc; /** @brief Number of bins to distribute to. */ int _M_num_bins; /** @brief Number of bits needed to address the bins. */ int _M_num_bits; /** @brief Constructor. */ _DRandomShufflingGlobalData(_RAIter& __source) : _M_source(__source) { } }; /** @brief Local data for a thread participating in __gnu_parallel::__parallel_random_shuffle(). */ template struct _DRSSorterPU { /** @brief Number of threads participating in total. */ int _M_num_threads; /** @brief Begin index for bins taken care of by this thread. */ _BinIndex _M_bins_begin; /** @brief End index for bins taken care of by this thread. */ _BinIndex __bins_end; /** @brief Random _M_seed for this thread. */ uint32_t _M_seed; /** @brief Pointer to global data. */ _DRandomShufflingGlobalData<_RAIter>* _M_sd; }; /** @brief Generate a random number in @c [0,2^__logp). * @param __logp Logarithm (basis 2) of the upper range __bound. * @param __rng Random number generator to use. */ template inline int __random_number_pow2(int __logp, _RandomNumberGenerator& __rng) { return __rng.__genrand_bits(__logp); } /** @brief Random shuffle code executed by each thread. * @param __pus Array of thread-local data records. */ template void __parallel_random_shuffle_drs_pu(_DRSSorterPU<_RAIter, _RandomNumberGenerator>* __pus) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _ThreadIndex __iam = omp_get_thread_num(); _DRSSorterPU<_RAIter, _RandomNumberGenerator>* __d = &__pus[__iam]; _DRandomShufflingGlobalData<_RAIter>* __sd = __d->_M_sd; // Indexing: _M_dist[bin][processor] _DifferenceType __length = (__sd->_M_starts[__iam + 1] - __sd->_M_starts[__iam]); _BinIndex* __oracles = new _BinIndex[__length]; _DifferenceType* __dist = new _DifferenceType[__sd->_M_num_bins + 1]; _BinIndex* __bin_proc = new _BinIndex[__sd->_M_num_bins]; _ValueType** __temporaries = new _ValueType*[__d->_M_num_threads]; // Compute oracles and count appearances. for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b) __dist[__b] = 0; int __num_bits = __sd->_M_num_bits; _RandomNumber __rng(__d->_M_seed); // First main loop. for (_DifferenceType __i = 0; __i < __length; ++__i) { _BinIndex __oracle = __random_number_pow2(__num_bits, __rng); __oracles[__i] = __oracle; // To allow prefix (partial) sum. ++(__dist[__oracle + 1]); } for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b) __sd->_M_dist[__b][__iam + 1] = __dist[__b]; # pragma omp barrier # pragma omp single { // Sum up bins, __sd->_M_dist[__s + 1][__d->_M_num_threads] now // contains the total number of items in bin __s for (_BinIndex __s = 0; __s < __sd->_M_num_bins; ++__s) __gnu_sequential::partial_sum(__sd->_M_dist[__s + 1], __sd->_M_dist[__s + 1] + __d->_M_num_threads + 1, __sd->_M_dist[__s + 1]); } # pragma omp barrier _SequenceIndex __offset = 0, __global_offset = 0; for (_BinIndex __s = 0; __s < __d->_M_bins_begin; ++__s) __global_offset += __sd->_M_dist[__s + 1][__d->_M_num_threads]; # pragma omp barrier for (_BinIndex __s = __d->_M_bins_begin; __s < __d->__bins_end; ++__s) { for (int __t = 0; __t < __d->_M_num_threads + 1; ++__t) __sd->_M_dist[__s + 1][__t] += __offset; __offset = __sd->_M_dist[__s + 1][__d->_M_num_threads]; } __sd->_M_temporaries[__iam] = static_cast<_ValueType*> (::operator new(sizeof(_ValueType) * __offset)); # pragma omp barrier // Draw local copies to avoid false sharing. for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b) __dist[__b] = __sd->_M_dist[__b][__iam]; for (_BinIndex __b = 0; __b < __sd->_M_num_bins; ++__b) __bin_proc[__b] = __sd->_M_bin_proc[__b]; for (_ThreadIndex __t = 0; __t < __d->_M_num_threads; ++__t) __temporaries[__t] = __sd->_M_temporaries[__t]; _RAIter __source = __sd->_M_source; _DifferenceType __start = __sd->_M_starts[__iam]; // Distribute according to oracles, second main loop. for (_DifferenceType __i = 0; __i < __length; ++__i) { _BinIndex __target_bin = __oracles[__i]; _ThreadIndex __target_p = __bin_proc[__target_bin]; // Last column [__d->_M_num_threads] stays unchanged. ::new(&(__temporaries[__target_p][__dist[__target_bin + 1]++])) _ValueType(*(__source + __i + __start)); } delete[] __oracles; delete[] __dist; delete[] __bin_proc; delete[] __temporaries; # pragma omp barrier // Shuffle bins internally. for (_BinIndex __b = __d->_M_bins_begin; __b < __d->__bins_end; ++__b) { _ValueType* __begin = (__sd->_M_temporaries[__iam] + (__b == __d->_M_bins_begin ? 0 : __sd->_M_dist[__b][__d->_M_num_threads])), *__end = (__sd->_M_temporaries[__iam] + __sd->_M_dist[__b + 1][__d->_M_num_threads]); __sequential_random_shuffle(__begin, __end, __rng); std::copy(__begin, __end, __sd->_M_source + __global_offset + (__b == __d->_M_bins_begin ? 0 : __sd->_M_dist[__b][__d->_M_num_threads])); } for (_SequenceIndex __i = 0; __i < __offset; ++__i) __sd->_M_temporaries[__iam][__i].~_ValueType(); ::operator delete(__sd->_M_temporaries[__iam]); } /** @brief Round up to the next greater power of 2. * @param __x _Integer to round up */ template _Tp __round_up_to_pow2(_Tp __x) { if (__x <= 1) return 1; else return (_Tp)1 << (__rd_log2(__x - 1) + 1); } /** @brief Main parallel random shuffle step. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __n Length of sequence. * @param __num_threads Number of threads to use. * @param __rng Random number generator to use. */ template void __parallel_random_shuffle_drs(_RAIter __begin, _RAIter __end, typename std::iterator_traits <_RAIter>::difference_type __n, _ThreadIndex __num_threads, _RandomNumberGenerator& __rng) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _GLIBCXX_CALL(__n) const _Settings& __s = _Settings::get(); if (__num_threads > __n) __num_threads = static_cast<_ThreadIndex>(__n); _BinIndex __num_bins, __num_bins_cache; #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1 // Try the L1 cache first. // Must fit into L1. __num_bins_cache = std::max<_DifferenceType>(1, __n / (__s.L1_cache_size_lb / sizeof(_ValueType))); __num_bins_cache = __round_up_to_pow2(__num_bins_cache); // No more buckets than TLB entries, power of 2 // Power of 2 and at least one element per bin, at most the TLB size. __num_bins = std::min<_DifferenceType>(__n, __num_bins_cache); #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB // 2 TLB entries needed per bin. __num_bins = std::min<_DifferenceType>(__s.TLB_size / 2, __num_bins); #endif __num_bins = __round_up_to_pow2(__num_bins); if (__num_bins < __num_bins_cache) { #endif // Now try the L2 cache // Must fit into L2 __num_bins_cache = static_cast<_BinIndex> (std::max<_DifferenceType>(1, __n / (__s.L2_cache_size / sizeof(_ValueType)))); __num_bins_cache = __round_up_to_pow2(__num_bins_cache); // No more buckets than TLB entries, power of 2. __num_bins = static_cast<_BinIndex> (std::min(__n, static_cast<_DifferenceType>(__num_bins_cache))); // Power of 2 and at least one element per bin, at most the TLB size. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB // 2 TLB entries needed per bin. __num_bins = std::min(static_cast<_DifferenceType>(__s.TLB_size / 2), __num_bins); #endif __num_bins = __round_up_to_pow2(__num_bins); #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1 } #endif __num_bins = __round_up_to_pow2( std::max<_BinIndex>(__num_threads, __num_bins)); if (__num_threads <= 1) { _RandomNumber __derived_rng( __rng(std::numeric_limits::max())); __sequential_random_shuffle(__begin, __end, __derived_rng); return; } _DRandomShufflingGlobalData<_RAIter> __sd(__begin); _DRSSorterPU<_RAIter, _RandomNumber >* __pus; _DifferenceType* __starts; # pragma omp parallel num_threads(__num_threads) { _ThreadIndex __num_threads = omp_get_num_threads(); # pragma omp single { __pus = new _DRSSorterPU<_RAIter, _RandomNumber>[__num_threads]; __sd._M_temporaries = new _ValueType*[__num_threads]; __sd._M_dist = new _DifferenceType*[__num_bins + 1]; __sd._M_bin_proc = new _ThreadIndex[__num_bins]; for (_BinIndex __b = 0; __b < __num_bins + 1; ++__b) __sd._M_dist[__b] = new _DifferenceType[__num_threads + 1]; for (_BinIndex __b = 0; __b < (__num_bins + 1); ++__b) { __sd._M_dist[0][0] = 0; __sd._M_dist[__b][0] = 0; } __starts = __sd._M_starts = new _DifferenceType[__num_threads + 1]; int __bin_cursor = 0; __sd._M_num_bins = __num_bins; __sd._M_num_bits = __rd_log2(__num_bins); _DifferenceType __chunk_length = __n / __num_threads, __split = __n % __num_threads, __start = 0; _DifferenceType __bin_chunk_length = __num_bins / __num_threads, __bin_split = __num_bins % __num_threads; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) { __starts[__i] = __start; __start += (__i < __split ? (__chunk_length + 1) : __chunk_length); int __j = __pus[__i]._M_bins_begin = __bin_cursor; // Range of bins for this processor. __bin_cursor += (__i < __bin_split ? (__bin_chunk_length + 1) : __bin_chunk_length); __pus[__i].__bins_end = __bin_cursor; for (; __j < __bin_cursor; ++__j) __sd._M_bin_proc[__j] = __i; __pus[__i]._M_num_threads = __num_threads; __pus[__i]._M_seed = __rng(std::numeric_limits::max()); __pus[__i]._M_sd = &__sd; } __starts[__num_threads] = __start; } //single // Now shuffle in parallel. __parallel_random_shuffle_drs_pu(__pus); } // parallel delete[] __starts; delete[] __sd._M_bin_proc; for (int __s = 0; __s < (__num_bins + 1); ++__s) delete[] __sd._M_dist[__s]; delete[] __sd._M_dist; delete[] __sd._M_temporaries; delete[] __pus; } /** @brief Sequential cache-efficient random shuffle. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __rng Random number generator to use. */ template void __sequential_random_shuffle(_RAIter __begin, _RAIter __end, _RandomNumberGenerator& __rng) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; const _Settings& __s = _Settings::get(); _BinIndex __num_bins, __num_bins_cache; #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1 // Try the L1 cache first, must fit into L1. __num_bins_cache = std::max<_DifferenceType> (1, __n / (__s.L1_cache_size_lb / sizeof(_ValueType))); __num_bins_cache = __round_up_to_pow2(__num_bins_cache); // No more buckets than TLB entries, power of 2 // Power of 2 and at least one element per bin, at most the TLB size __num_bins = std::min(__n, (_DifferenceType)__num_bins_cache); #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB // 2 TLB entries needed per bin __num_bins = std::min((_DifferenceType)__s.TLB_size / 2, __num_bins); #endif __num_bins = __round_up_to_pow2(__num_bins); if (__num_bins < __num_bins_cache) { #endif // Now try the L2 cache, must fit into L2. __num_bins_cache = static_cast<_BinIndex> (std::max<_DifferenceType>(1, __n / (__s.L2_cache_size / sizeof(_ValueType)))); __num_bins_cache = __round_up_to_pow2(__num_bins_cache); // No more buckets than TLB entries, power of 2 // Power of 2 and at least one element per bin, at most the TLB size. __num_bins = static_cast<_BinIndex> (std::min(__n, static_cast<_DifferenceType>(__num_bins_cache))); #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB // 2 TLB entries needed per bin __num_bins = std::min<_DifferenceType>(__s.TLB_size / 2, __num_bins); #endif __num_bins = __round_up_to_pow2(__num_bins); #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1 } #endif int __num_bits = __rd_log2(__num_bins); if (__num_bins > 1) { _ValueType* __target = static_cast<_ValueType*>(::operator new(sizeof(_ValueType) * __n)); _BinIndex* __oracles = new _BinIndex[__n]; _DifferenceType* __dist0 = new _DifferenceType[__num_bins + 1], * __dist1 = new _DifferenceType[__num_bins + 1]; for (int __b = 0; __b < __num_bins + 1; ++__b) __dist0[__b] = 0; _RandomNumber __bitrng(__rng(0xFFFFFFFF)); for (_DifferenceType __i = 0; __i < __n; ++__i) { _BinIndex __oracle = __random_number_pow2(__num_bits, __bitrng); __oracles[__i] = __oracle; // To allow prefix (partial) sum. ++(__dist0[__oracle + 1]); } // Sum up bins. __gnu_sequential::partial_sum(__dist0, __dist0 + __num_bins + 1, __dist0); for (int __b = 0; __b < __num_bins + 1; ++__b) __dist1[__b] = __dist0[__b]; // Distribute according to oracles. for (_DifferenceType __i = 0; __i < __n; ++__i) ::new(&(__target[(__dist0[__oracles[__i]])++])) _ValueType(*(__begin + __i)); for (int __b = 0; __b < __num_bins; ++__b) __sequential_random_shuffle(__target + __dist1[__b], __target + __dist1[__b + 1], __rng); // Copy elements back. std::copy(__target, __target + __n, __begin); delete[] __dist0; delete[] __dist1; delete[] __oracles; for (_DifferenceType __i = 0; __i < __n; ++__i) __target[__i].~_ValueType(); ::operator delete(__target); } else __gnu_sequential::random_shuffle(__begin, __end, __rng); } /** @brief Parallel random public call. * @param __begin Begin iterator of sequence. * @param __end End iterator of sequence. * @param __rng Random number generator to use. */ template inline void __parallel_random_shuffle(_RAIter __begin, _RAIter __end, _RandomNumberGenerator __rng = _RandomNumber()) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; __parallel_random_shuffle_drs(__begin, __end, __n, __get_max_threads(), __rng); } } #endif /* _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H */ c++/8/parallel/multiseq_selection.h000064400000053073151027430570013154 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/multiseq_selection.h * @brief Functions to find elements of a certain global __rank in * multiple sorted sequences. Also serves for splitting such * sequence sets. * * The algorithm description can be found in * * P. J. Varman, S. D. Scheufler, B. R. Iyer, and G. R. Ricard. * Merging Multiple Lists on Hierarchical-Memory Multiprocessors. * Journal of Parallel and Distributed Computing, 12(2):171–177, 1991. * * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_MULTISEQ_SELECTION_H #define _GLIBCXX_PARALLEL_MULTISEQ_SELECTION_H 1 #include #include #include namespace __gnu_parallel { /** @brief Compare __a pair of types lexicographically, ascending. */ template class _Lexicographic : public std::binary_function, std::pair<_T1, _T2>, bool> { private: _Compare& _M_comp; public: _Lexicographic(_Compare& __comp) : _M_comp(__comp) { } bool operator()(const std::pair<_T1, _T2>& __p1, const std::pair<_T1, _T2>& __p2) const { if (_M_comp(__p1.first, __p2.first)) return true; if (_M_comp(__p2.first, __p1.first)) return false; // Firsts are equal. return __p1.second < __p2.second; } }; /** @brief Compare __a pair of types lexicographically, descending. */ template class _LexicographicReverse : public std::binary_function<_T1, _T2, bool> { private: _Compare& _M_comp; public: _LexicographicReverse(_Compare& __comp) : _M_comp(__comp) { } bool operator()(const std::pair<_T1, _T2>& __p1, const std::pair<_T1, _T2>& __p2) const { if (_M_comp(__p2.first, __p1.first)) return true; if (_M_comp(__p1.first, __p2.first)) return false; // Firsts are equal. return __p2.second < __p1.second; } }; /** * @brief Splits several sorted sequences at a certain global __rank, * resulting in a splitting point for each sequence. * The sequences are passed via a sequence of random-access * iterator pairs, none of the sequences may be empty. If there * are several equal elements across the split, the ones on the * __left side will be chosen from sequences with smaller number. * @param __begin_seqs Begin of the sequence of iterator pairs. * @param __end_seqs End of the sequence of iterator pairs. * @param __rank The global rank to partition at. * @param __begin_offsets A random-access __sequence __begin where the * __result will be stored in. Each element of the sequence is an * iterator that points to the first element on the greater part of * the respective __sequence. * @param __comp The ordering functor, defaults to std::less<_Tp>. */ template void multiseq_partition(_RanSeqs __begin_seqs, _RanSeqs __end_seqs, _RankType __rank, _RankIterator __begin_offsets, _Compare __comp = std::less< typename std::iterator_traits::value_type:: first_type>::value_type>()) // std::less<_Tp> { _GLIBCXX_CALL(__end_seqs - __begin_seqs) typedef typename std::iterator_traits<_RanSeqs>::value_type::first_type _It; typedef typename std::iterator_traits<_RanSeqs>::difference_type _SeqNumber; typedef typename std::iterator_traits<_It>::difference_type _DifferenceType; typedef typename std::iterator_traits<_It>::value_type _ValueType; _Lexicographic<_ValueType, _SeqNumber, _Compare> __lcomp(__comp); _LexicographicReverse<_ValueType, _SeqNumber, _Compare> __lrcomp(__comp); // Number of sequences, number of elements in total (possibly // including padding). _DifferenceType __m = std::distance(__begin_seqs, __end_seqs), __nn = 0, __nmax, __n, __r; for (_SeqNumber __i = 0; __i < __m; __i++) { __nn += std::distance(__begin_seqs[__i].first, __begin_seqs[__i].second); _GLIBCXX_PARALLEL_ASSERT( std::distance(__begin_seqs[__i].first, __begin_seqs[__i].second) > 0); } if (__rank == __nn) { for (_SeqNumber __i = 0; __i < __m; __i++) __begin_offsets[__i] = __begin_seqs[__i].second; // Very end. // Return __m - 1; return; } _GLIBCXX_PARALLEL_ASSERT(__m != 0); _GLIBCXX_PARALLEL_ASSERT(__nn != 0); _GLIBCXX_PARALLEL_ASSERT(__rank >= 0); _GLIBCXX_PARALLEL_ASSERT(__rank < __nn); _DifferenceType* __ns = new _DifferenceType[__m]; _DifferenceType* __a = new _DifferenceType[__m]; _DifferenceType* __b = new _DifferenceType[__m]; _DifferenceType __l; __ns[0] = std::distance(__begin_seqs[0].first, __begin_seqs[0].second); __nmax = __ns[0]; for (_SeqNumber __i = 0; __i < __m; __i++) { __ns[__i] = std::distance(__begin_seqs[__i].first, __begin_seqs[__i].second); __nmax = std::max(__nmax, __ns[__i]); } __r = __rd_log2(__nmax) + 1; // Pad all lists to this length, at least as long as any ns[__i], // equality iff __nmax = 2^__k - 1. __l = (1ULL << __r) - 1; for (_SeqNumber __i = 0; __i < __m; __i++) { __a[__i] = 0; __b[__i] = __l; } __n = __l / 2; // Invariants: // 0 <= __a[__i] <= __ns[__i], 0 <= __b[__i] <= __l #define __S(__i) (__begin_seqs[__i].first) // Initial partition. std::vector > __sample; for (_SeqNumber __i = 0; __i < __m; __i++) if (__n < __ns[__i]) //__sequence long enough __sample.push_back(std::make_pair(__S(__i)[__n], __i)); __gnu_sequential::sort(__sample.begin(), __sample.end(), __lcomp); for (_SeqNumber __i = 0; __i < __m; __i++) //conceptual infinity if (__n >= __ns[__i]) //__sequence too short, conceptual infinity __sample.push_back( std::make_pair(__S(__i)[0] /*__dummy element*/, __i)); _DifferenceType __localrank = __rank / __l; _SeqNumber __j; for (__j = 0; __j < __localrank && ((__n + 1) <= __ns[__sample[__j].second]); ++__j) __a[__sample[__j].second] += __n + 1; for (; __j < __m; __j++) __b[__sample[__j].second] -= __n + 1; // Further refinement. while (__n > 0) { __n /= 2; _SeqNumber __lmax_seq = -1; // to avoid warning const _ValueType* __lmax = 0; // impossible to avoid the warning? for (_SeqNumber __i = 0; __i < __m; __i++) { if (__a[__i] > 0) { if (!__lmax) { __lmax = &(__S(__i)[__a[__i] - 1]); __lmax_seq = __i; } else { // Max, favor rear sequences. if (!__comp(__S(__i)[__a[__i] - 1], *__lmax)) { __lmax = &(__S(__i)[__a[__i] - 1]); __lmax_seq = __i; } } } } _SeqNumber __i; for (__i = 0; __i < __m; __i++) { _DifferenceType __middle = (__b[__i] + __a[__i]) / 2; if (__lmax && __middle < __ns[__i] && __lcomp(std::make_pair(__S(__i)[__middle], __i), std::make_pair(*__lmax, __lmax_seq))) __a[__i] = std::min(__a[__i] + __n + 1, __ns[__i]); else __b[__i] -= __n + 1; } _DifferenceType __leftsize = 0; for (_SeqNumber __i = 0; __i < __m; __i++) __leftsize += __a[__i] / (__n + 1); _DifferenceType __skew = __rank / (__n + 1) - __leftsize; if (__skew > 0) { // Move to the left, find smallest. std::priority_queue, std::vector >, _LexicographicReverse<_ValueType, _SeqNumber, _Compare> > __pq(__lrcomp); for (_SeqNumber __i = 0; __i < __m; __i++) if (__b[__i] < __ns[__i]) __pq.push(std::make_pair(__S(__i)[__b[__i]], __i)); for (; __skew != 0 && !__pq.empty(); --__skew) { _SeqNumber __source = __pq.top().second; __pq.pop(); __a[__source] = std::min(__a[__source] + __n + 1, __ns[__source]); __b[__source] += __n + 1; if (__b[__source] < __ns[__source]) __pq.push( std::make_pair(__S(__source)[__b[__source]], __source)); } } else if (__skew < 0) { // Move to the right, find greatest. std::priority_queue, std::vector >, _Lexicographic<_ValueType, _SeqNumber, _Compare> > __pq(__lcomp); for (_SeqNumber __i = 0; __i < __m; __i++) if (__a[__i] > 0) __pq.push(std::make_pair(__S(__i)[__a[__i] - 1], __i)); for (; __skew != 0; ++__skew) { _SeqNumber __source = __pq.top().second; __pq.pop(); __a[__source] -= __n + 1; __b[__source] -= __n + 1; if (__a[__source] > 0) __pq.push(std::make_pair( __S(__source)[__a[__source] - 1], __source)); } } } // Postconditions: // __a[__i] == __b[__i] in most cases, except when __a[__i] has been // clamped because of having reached the boundary // Now return the result, calculate the offset. // Compare the keys on both edges of the border. // Maximum of left edge, minimum of right edge. _ValueType* __maxleft = 0; _ValueType* __minright = 0; for (_SeqNumber __i = 0; __i < __m; __i++) { if (__a[__i] > 0) { if (!__maxleft) __maxleft = &(__S(__i)[__a[__i] - 1]); else { // Max, favor rear sequences. if (!__comp(__S(__i)[__a[__i] - 1], *__maxleft)) __maxleft = &(__S(__i)[__a[__i] - 1]); } } if (__b[__i] < __ns[__i]) { if (!__minright) __minright = &(__S(__i)[__b[__i]]); else { // Min, favor fore sequences. if (__comp(__S(__i)[__b[__i]], *__minright)) __minright = &(__S(__i)[__b[__i]]); } } } _SeqNumber __seq = 0; for (_SeqNumber __i = 0; __i < __m; __i++) __begin_offsets[__i] = __S(__i) + __a[__i]; delete[] __ns; delete[] __a; delete[] __b; } /** * @brief Selects the element at a certain global __rank from several * sorted sequences. * * The sequences are passed via a sequence of random-access * iterator pairs, none of the sequences may be empty. * @param __begin_seqs Begin of the sequence of iterator pairs. * @param __end_seqs End of the sequence of iterator pairs. * @param __rank The global rank to partition at. * @param __offset The rank of the selected element in the global * subsequence of elements equal to the selected element. If the * selected element is unique, this number is 0. * @param __comp The ordering functor, defaults to std::less. */ template _Tp multiseq_selection(_RanSeqs __begin_seqs, _RanSeqs __end_seqs, _RankType __rank, _RankType& __offset, _Compare __comp = std::less<_Tp>()) { _GLIBCXX_CALL(__end_seqs - __begin_seqs) typedef typename std::iterator_traits<_RanSeqs>::value_type::first_type _It; typedef typename std::iterator_traits<_RanSeqs>::difference_type _SeqNumber; typedef typename std::iterator_traits<_It>::difference_type _DifferenceType; _Lexicographic<_Tp, _SeqNumber, _Compare> __lcomp(__comp); _LexicographicReverse<_Tp, _SeqNumber, _Compare> __lrcomp(__comp); // Number of sequences, number of elements in total (possibly // including padding). _DifferenceType __m = std::distance(__begin_seqs, __end_seqs); _DifferenceType __nn = 0; _DifferenceType __nmax, __n, __r; for (_SeqNumber __i = 0; __i < __m; __i++) __nn += std::distance(__begin_seqs[__i].first, __begin_seqs[__i].second); if (__m == 0 || __nn == 0 || __rank < 0 || __rank >= __nn) { // result undefined if there is no data or __rank is outside bounds throw std::exception(); } _DifferenceType* __ns = new _DifferenceType[__m]; _DifferenceType* __a = new _DifferenceType[__m]; _DifferenceType* __b = new _DifferenceType[__m]; _DifferenceType __l; __ns[0] = std::distance(__begin_seqs[0].first, __begin_seqs[0].second); __nmax = __ns[0]; for (_SeqNumber __i = 0; __i < __m; ++__i) { __ns[__i] = std::distance(__begin_seqs[__i].first, __begin_seqs[__i].second); __nmax = std::max(__nmax, __ns[__i]); } __r = __rd_log2(__nmax) + 1; // Pad all lists to this length, at least as long as any ns[__i], // equality iff __nmax = 2^__k - 1 __l = __round_up_to_pow2(__r) - 1; for (_SeqNumber __i = 0; __i < __m; ++__i) { __a[__i] = 0; __b[__i] = __l; } __n = __l / 2; // Invariants: // 0 <= __a[__i] <= __ns[__i], 0 <= __b[__i] <= __l #define __S(__i) (__begin_seqs[__i].first) // Initial partition. std::vector > __sample; for (_SeqNumber __i = 0; __i < __m; __i++) if (__n < __ns[__i]) __sample.push_back(std::make_pair(__S(__i)[__n], __i)); __gnu_sequential::sort(__sample.begin(), __sample.end(), __lcomp, sequential_tag()); // Conceptual infinity. for (_SeqNumber __i = 0; __i < __m; __i++) if (__n >= __ns[__i]) __sample.push_back( std::make_pair(__S(__i)[0] /*__dummy element*/, __i)); _DifferenceType __localrank = __rank / __l; _SeqNumber __j; for (__j = 0; __j < __localrank && ((__n + 1) <= __ns[__sample[__j].second]); ++__j) __a[__sample[__j].second] += __n + 1; for (; __j < __m; ++__j) __b[__sample[__j].second] -= __n + 1; // Further refinement. while (__n > 0) { __n /= 2; const _Tp* __lmax = 0; for (_SeqNumber __i = 0; __i < __m; ++__i) { if (__a[__i] > 0) { if (!__lmax) __lmax = &(__S(__i)[__a[__i] - 1]); else { if (__comp(*__lmax, __S(__i)[__a[__i] - 1])) //max __lmax = &(__S(__i)[__a[__i] - 1]); } } } _SeqNumber __i; for (__i = 0; __i < __m; __i++) { _DifferenceType __middle = (__b[__i] + __a[__i]) / 2; if (__lmax && __middle < __ns[__i] && __comp(__S(__i)[__middle], *__lmax)) __a[__i] = std::min(__a[__i] + __n + 1, __ns[__i]); else __b[__i] -= __n + 1; } _DifferenceType __leftsize = 0; for (_SeqNumber __i = 0; __i < __m; ++__i) __leftsize += __a[__i] / (__n + 1); _DifferenceType __skew = __rank / (__n + 1) - __leftsize; if (__skew > 0) { // Move to the left, find smallest. std::priority_queue, std::vector >, _LexicographicReverse<_Tp, _SeqNumber, _Compare> > __pq(__lrcomp); for (_SeqNumber __i = 0; __i < __m; ++__i) if (__b[__i] < __ns[__i]) __pq.push(std::make_pair(__S(__i)[__b[__i]], __i)); for (; __skew != 0 && !__pq.empty(); --__skew) { _SeqNumber __source = __pq.top().second; __pq.pop(); __a[__source] = std::min(__a[__source] + __n + 1, __ns[__source]); __b[__source] += __n + 1; if (__b[__source] < __ns[__source]) __pq.push( std::make_pair(__S(__source)[__b[__source]], __source)); } } else if (__skew < 0) { // Move to the right, find greatest. std::priority_queue, std::vector >, _Lexicographic<_Tp, _SeqNumber, _Compare> > __pq(__lcomp); for (_SeqNumber __i = 0; __i < __m; ++__i) if (__a[__i] > 0) __pq.push(std::make_pair(__S(__i)[__a[__i] - 1], __i)); for (; __skew != 0; ++__skew) { _SeqNumber __source = __pq.top().second; __pq.pop(); __a[__source] -= __n + 1; __b[__source] -= __n + 1; if (__a[__source] > 0) __pq.push(std::make_pair( __S(__source)[__a[__source] - 1], __source)); } } } // Postconditions: // __a[__i] == __b[__i] in most cases, except when __a[__i] has been // clamped because of having reached the boundary // Now return the result, calculate the offset. // Compare the keys on both edges of the border. // Maximum of left edge, minimum of right edge. bool __maxleftset = false, __minrightset = false; // Impossible to avoid the warning? _Tp __maxleft, __minright; for (_SeqNumber __i = 0; __i < __m; ++__i) { if (__a[__i] > 0) { if (!__maxleftset) { __maxleft = __S(__i)[__a[__i] - 1]; __maxleftset = true; } else { // Max. if (__comp(__maxleft, __S(__i)[__a[__i] - 1])) __maxleft = __S(__i)[__a[__i] - 1]; } } if (__b[__i] < __ns[__i]) { if (!__minrightset) { __minright = __S(__i)[__b[__i]]; __minrightset = true; } else { // Min. if (__comp(__S(__i)[__b[__i]], __minright)) __minright = __S(__i)[__b[__i]]; } } } // Minright is the __splitter, in any case. if (!__maxleftset || __comp(__minright, __maxleft)) { // Good luck, everything is split unambiguously. __offset = 0; } else { // We have to calculate an offset. __offset = 0; for (_SeqNumber __i = 0; __i < __m; ++__i) { _DifferenceType lb = std::lower_bound(__S(__i), __S(__i) + __ns[__i], __minright, __comp) - __S(__i); __offset += __a[__i] - lb; } } delete[] __ns; delete[] __a; delete[] __b; return __minright; } } #undef __S #endif /* _GLIBCXX_PARALLEL_MULTISEQ_SELECTION_H */ c++/8/parallel/algobase.h000064400000041403151027430570011013 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/algobase.h * @brief Parallel STL function calls corresponding to the * stl_algobase.h header. The functions defined here mainly do case * switches and call the actual parallelized versions in other files. * Inlining policy: Functions that basically only contain one * function call, are declared inline. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_ALGOBASE_H #define _GLIBCXX_PARALLEL_ALGOBASE_H 1 #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __parallel { // NB: equal and lexicographical_compare require mismatch. // Sequential fallback template inline pair<_IIter1, _IIter2> mismatch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::mismatch(__begin1, __end1, __begin2); } // Sequential fallback template inline pair<_IIter1, _IIter2> mismatch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::mismatch(__begin1, __end1, __begin2, __pred); } // Sequential fallback for input iterator case template inline pair<_IIter1, _IIter2> __mismatch_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _Predicate __pred, _IteratorTag1, _IteratorTag2) { return _GLIBCXX_STD_A::mismatch(__begin1, __end1, __begin2, __pred); } // Parallel mismatch for random access iterators template pair<_RAIter1, _RAIter2> __mismatch_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION(true)) { _RAIter1 __res = __gnu_parallel::__find_template(__begin1, __end1, __begin2, __pred, __gnu_parallel:: __mismatch_selector()).first; return make_pair(__res , __begin2 + (__res - __begin1)); } else return _GLIBCXX_STD_A::mismatch(__begin1, __end1, __begin2, __pred); } // Public interface template inline pair<_IIter1, _IIter2> mismatch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2) { typedef __gnu_parallel::_EqualTo< typename std::iterator_traits<_IIter1>::value_type, typename std::iterator_traits<_IIter2>::value_type> _EqualTo; return __mismatch_switch(__begin1, __end1, __begin2, _EqualTo(), std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } // Public interface template inline pair<_IIter1, _IIter2> mismatch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _Predicate __pred) { return __mismatch_switch(__begin1, __end1, __begin2, __pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } #if __cplusplus > 201103L // Sequential fallback. template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::mismatch(__first1, __last1, __first2, __last2); } // Sequential fallback. template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __binary_pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::mismatch(__first1, __last1, __first2, __last2, __binary_pred); } // Sequential fallback for input iterator case template inline pair<_IIter1, _IIter2> __mismatch_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _Predicate __pred, _IteratorTag1, _IteratorTag2) { return _GLIBCXX_STD_A::mismatch(__begin1, __end1, __begin2, __end2, __pred); } // Parallel mismatch for random access iterators template pair<_RAIter1, _RAIter2> __mismatch_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION(true)) { if ((__end2 - __begin2) < (__end1 - __begin1)) __end1 = __begin1 + (__end2 - __begin2); _RAIter1 __res = __gnu_parallel::__find_template(__begin1, __end1, __begin2, __pred, __gnu_parallel:: __mismatch_selector()).first; return make_pair(__res , __begin2 + (__res - __begin1)); } else return _GLIBCXX_STD_A::mismatch(__begin1, __end1, __begin2, __end2, __pred); } template inline pair<_IIter1, _IIter2> mismatch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2) { typedef __gnu_parallel::_EqualTo< typename std::iterator_traits<_IIter1>::value_type, typename std::iterator_traits<_IIter2>::value_type> _EqualTo; return __mismatch_switch(__begin1, __end1, __begin2, __end2, _EqualTo(), std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } template inline pair<_InputIterator1, _InputIterator2> mismatch(_InputIterator1 __begin1, _InputIterator1 __end1, _InputIterator2 __begin2, _InputIterator2 __end2, _BinaryPredicate __binary_pred) { return __mismatch_switch(__begin1, __end1, __begin2, __end2, __binary_pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } #endif // Sequential fallback template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::equal(__begin1, __end1, __begin2); } // Sequential fallback template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::equal(__begin1, __end1, __begin2, __pred); } // Public interface template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2) { return __gnu_parallel::mismatch(__begin1, __end1, __begin2).first == __end1; } // Public interface template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _Predicate __pred) { return __gnu_parallel::mismatch(__begin1, __end1, __begin2, __pred).first == __end1; } #if __cplusplus > 201103L // Sequential fallback template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::equal(__begin1, __end1, __begin2, __end2); } // Sequential fallback template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _BinaryPredicate __binary_pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::equal(__begin1, __end1, __begin2, __end2, __binary_pred); } // Sequential fallback for input iterator case template inline bool __equal_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _Predicate __pred, _IteratorTag1, _IteratorTag2) { return _GLIBCXX_STD_A::equal(__begin1, __end1, __begin2, __end2, __pred); } // Parallel equal for random access iterators template inline bool __equal_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION(true)) { if (std::distance(__begin1, __end1) != std::distance(__begin2, __end2)) return false; return __gnu_parallel::mismatch(__begin1, __end1, __begin2, __end2, __pred).first == __end1; } else return _GLIBCXX_STD_A::equal(__begin1, __end1, __begin2, __end2, __pred); } template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2) { typedef __gnu_parallel::_EqualTo< typename std::iterator_traits<_IIter1>::value_type, typename std::iterator_traits<_IIter2>::value_type> _EqualTo; return __equal_switch(__begin1, __end1, __begin2, __end2, _EqualTo(), std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } template inline bool equal(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _BinaryPredicate __binary_pred) { return __equal_switch(__begin1, __end1, __begin2, __end2, __binary_pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } #endif // Sequential fallback template inline bool lexicographical_compare(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::lexicographical_compare(__begin1, __end1, __begin2, __end2); } // Sequential fallback template inline bool lexicographical_compare(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::lexicographical_compare( __begin1, __end1, __begin2, __end2, __pred); } // Sequential fallback for input iterator case template inline bool __lexicographical_compare_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _Predicate __pred, _IteratorTag1, _IteratorTag2) { return _GLIBCXX_STD_A::lexicographical_compare( __begin1, __end1, __begin2, __end2, __pred); } // Parallel lexicographical_compare for random access iterators // Limitation: Both valuetypes must be the same template bool __lexicographical_compare_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION(true)) { typedef iterator_traits<_RAIter1> _TraitsType1; typedef typename _TraitsType1::value_type _ValueType1; typedef iterator_traits<_RAIter2> _TraitsType2; typedef typename _TraitsType2::value_type _ValueType2; typedef __gnu_parallel:: _EqualFromLess<_ValueType1, _ValueType2, _Predicate> _EqualFromLessCompare; // Longer sequence in first place. if ((__end1 - __begin1) < (__end2 - __begin2)) { typedef pair<_RAIter1, _RAIter2> _SpotType; _SpotType __mm = __mismatch_switch(__begin1, __end1, __begin2, _EqualFromLessCompare(__pred), random_access_iterator_tag(), random_access_iterator_tag()); return (__mm.first == __end1) || bool(__pred(*__mm.first, *__mm.second)); } else { typedef pair<_RAIter2, _RAIter1> _SpotType; _SpotType __mm = __mismatch_switch(__begin2, __end2, __begin1, _EqualFromLessCompare(__pred), random_access_iterator_tag(), random_access_iterator_tag()); return (__mm.first != __end2) && bool(__pred(*__mm.second, *__mm.first)); } } else return _GLIBCXX_STD_A::lexicographical_compare( __begin1, __end1, __begin2, __end2, __pred); } // Public interface template inline bool lexicographical_compare(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2) { typedef iterator_traits<_IIter1> _TraitsType1; typedef typename _TraitsType1::value_type _ValueType1; typedef typename _TraitsType1::iterator_category _IteratorCategory1; typedef iterator_traits<_IIter2> _TraitsType2; typedef typename _TraitsType2::value_type _ValueType2; typedef typename _TraitsType2::iterator_category _IteratorCategory2; typedef __gnu_parallel::_Less<_ValueType1, _ValueType2> _LessType; return __lexicographical_compare_switch( __begin1, __end1, __begin2, __end2, _LessType(), _IteratorCategory1(), _IteratorCategory2()); } // Public interface template inline bool lexicographical_compare(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _Predicate __pred) { typedef iterator_traits<_IIter1> _TraitsType1; typedef typename _TraitsType1::iterator_category _IteratorCategory1; typedef iterator_traits<_IIter2> _TraitsType2; typedef typename _TraitsType2::iterator_category _IteratorCategory2; return __lexicographical_compare_switch( __begin1, __end1, __begin2, __end2, __pred, _IteratorCategory1(), _IteratorCategory2()); } } // end namespace } // end namespace #endif /* _GLIBCXX_PARALLEL_ALGOBASE_H */ c++/8/parallel/random_number.h000064400000010203151027430570012060 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/random_number.h * @brief Random number generator based on the Mersenne twister. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_RANDOM_NUMBER_H #define _GLIBCXX_PARALLEL_RANDOM_NUMBER_H 1 #include #include #include namespace __gnu_parallel { /** @brief Random number generator, based on the Mersenne twister. */ class _RandomNumber { private: std::tr1::mt19937 _M_mt; uint64_t _M_supremum; uint64_t _M_rand_sup; double _M_supremum_reciprocal; double _M_rand_sup_reciprocal; // Assumed to be twice as long as the usual random number. uint64_t __cache; // Bit results. int __bits_left; static uint32_t __scale_down(uint64_t __x, #if _GLIBCXX_SCALE_DOWN_FPU uint64_t /*_M_supremum*/, double _M_supremum_reciprocal) #else uint64_t _M_supremum, double /*_M_supremum_reciprocal*/) #endif { #if _GLIBCXX_SCALE_DOWN_FPU return uint32_t(__x * _M_supremum_reciprocal); #else return static_cast(__x % _M_supremum); #endif } public: /** @brief Default constructor. Seed with 0. */ _RandomNumber() : _M_mt(0), _M_supremum(0x100000000ULL), _M_rand_sup(1ULL << std::numeric_limits::digits), _M_supremum_reciprocal(double(_M_supremum) / double(_M_rand_sup)), _M_rand_sup_reciprocal(1.0 / double(_M_rand_sup)), __cache(0), __bits_left(0) { } /** @brief Constructor. * @param __seed Random __seed. * @param _M_supremum Generate integer random numbers in the * interval @c [0,_M_supremum). */ _RandomNumber(uint32_t __seed, uint64_t _M_supremum = 0x100000000ULL) : _M_mt(__seed), _M_supremum(_M_supremum), _M_rand_sup(1ULL << std::numeric_limits::digits), _M_supremum_reciprocal(double(_M_supremum) / double(_M_rand_sup)), _M_rand_sup_reciprocal(1.0 / double(_M_rand_sup)), __cache(0), __bits_left(0) { } /** @brief Generate unsigned random 32-bit integer. */ uint32_t operator()() { return __scale_down(_M_mt(), _M_supremum, _M_supremum_reciprocal); } /** @brief Generate unsigned random 32-bit integer in the interval @c [0,local_supremum). */ uint32_t operator()(uint64_t local_supremum) { return __scale_down(_M_mt(), local_supremum, double(local_supremum * _M_rand_sup_reciprocal)); } /** @brief Generate a number of random bits, run-time parameter. * @param __bits Number of bits to generate. */ unsigned long __genrand_bits(int __bits) { unsigned long __res = __cache & ((1 << __bits) - 1); __cache = __cache >> __bits; __bits_left -= __bits; if (__bits_left < 32) { __cache |= ((uint64_t(_M_mt())) << __bits_left); __bits_left += 32; } return __res; } }; } // namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_RANDOM_NUMBER_H */ c++/8/parallel/queue.h000064400000012646151027430570010371 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/queue.h * @brief Lock-free double-ended queue. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_QUEUE_H #define _GLIBCXX_PARALLEL_QUEUE_H 1 #include #include #include /** @brief Decide whether to declare certain variable volatile in this file. */ #define _GLIBCXX_VOLATILE volatile namespace __gnu_parallel { /**@brief Double-ended queue of bounded size, allowing lock-free * atomic access. push_front() and pop_front() must not be called * concurrently to each other, while pop_back() can be called * concurrently at all times. * @c empty(), @c size(), and @c top() are intentionally not provided. * Calling them would not make sense in a concurrent setting. * @param _Tp Contained element type. */ template class _RestrictedBoundedConcurrentQueue { private: /** @brief Array of elements, seen as cyclic buffer. */ _Tp* _M_base; /** @brief Maximal number of elements contained at the same time. */ _SequenceIndex _M_max_size; /** @brief Cyclic __begin and __end pointers contained in one atomically changeable value. */ _GLIBCXX_VOLATILE _CASable _M_borders; public: /** @brief Constructor. Not to be called concurrent, of course. * @param __max_size Maximal number of elements to be contained. */ _RestrictedBoundedConcurrentQueue(_SequenceIndex __max_size) { _M_max_size = __max_size; _M_base = new _Tp[__max_size]; _M_borders = __encode2(0, 0); #pragma omp flush } /** @brief Destructor. Not to be called concurrent, of course. */ ~_RestrictedBoundedConcurrentQueue() { delete[] _M_base; } /** @brief Pushes one element into the queue at the front end. * Must not be called concurrently with pop_front(). */ void push_front(const _Tp& __t) { _CASable __former_borders = _M_borders; int __former_front, __former_back; __decode2(__former_borders, __former_front, __former_back); *(_M_base + __former_front % _M_max_size) = __t; #if _GLIBCXX_PARALLEL_ASSERTIONS // Otherwise: front - back > _M_max_size eventually. _GLIBCXX_PARALLEL_ASSERT(((__former_front + 1) - __former_back) <= _M_max_size); #endif __fetch_and_add(&_M_borders, __encode2(1, 0)); } /** @brief Pops one element from the queue at the front end. * Must not be called concurrently with pop_front(). */ bool pop_front(_Tp& __t) { int __former_front, __former_back; #pragma omp flush __decode2(_M_borders, __former_front, __former_back); while (__former_front > __former_back) { // Chance. _CASable __former_borders = __encode2(__former_front, __former_back); _CASable __new_borders = __encode2(__former_front - 1, __former_back); if (__compare_and_swap(&_M_borders, __former_borders, __new_borders)) { __t = *(_M_base + (__former_front - 1) % _M_max_size); return true; } #pragma omp flush __decode2(_M_borders, __former_front, __former_back); } return false; } /** @brief Pops one element from the queue at the front end. * Must not be called concurrently with pop_front(). */ bool pop_back(_Tp& __t) //queue behavior { int __former_front, __former_back; #pragma omp flush __decode2(_M_borders, __former_front, __former_back); while (__former_front > __former_back) { // Chance. _CASable __former_borders = __encode2(__former_front, __former_back); _CASable __new_borders = __encode2(__former_front, __former_back + 1); if (__compare_and_swap(&_M_borders, __former_borders, __new_borders)) { __t = *(_M_base + __former_back % _M_max_size); return true; } #pragma omp flush __decode2(_M_borders, __former_front, __former_back); } return false; } }; } //namespace __gnu_parallel #undef _GLIBCXX_VOLATILE #endif /* _GLIBCXX_PARALLEL_QUEUE_H */ c++/8/parallel/find.h000064400000032427151027430570010164 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/find.h * @brief Parallel implementation base for std::find(), std::equal() * and related functions. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze and Johannes Singler. #ifndef _GLIBCXX_PARALLEL_FIND_H #define _GLIBCXX_PARALLEL_FIND_H 1 #include #include #include #include #include namespace __gnu_parallel { /** * @brief Parallel std::find, switch for different algorithms. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. Must have same * length as first sequence. * @param __pred Find predicate. * @param __selector _Functionality (e. g. std::find_if(), std::equal(),...) * @return Place of finding in both sequences. */ template inline std::pair<_RAIter1, _RAIter2> __find_template(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred, _Selector __selector) { switch (_Settings::get().find_algorithm) { case GROWING_BLOCKS: return __find_template(__begin1, __end1, __begin2, __pred, __selector, growing_blocks_tag()); case CONSTANT_SIZE_BLOCKS: return __find_template(__begin1, __end1, __begin2, __pred, __selector, constant_size_blocks_tag()); case EQUAL_SPLIT: return __find_template(__begin1, __end1, __begin2, __pred, __selector, equal_split_tag()); default: _GLIBCXX_PARALLEL_ASSERT(false); return std::make_pair(__begin1, __begin2); } } #if _GLIBCXX_FIND_EQUAL_SPLIT /** * @brief Parallel std::find, equal splitting variant. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. Second __sequence * must have same length as first sequence. * @param __pred Find predicate. * @param __selector _Functionality (e. g. std::find_if(), std::equal(),...) * @return Place of finding in both sequences. */ template std::pair<_RAIter1, _RAIter2> __find_template(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred, _Selector __selector, equal_split_tag) { _GLIBCXX_CALL(__end1 - __begin1) typedef std::iterator_traits<_RAIter1> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename _TraitsType::value_type _ValueType; _DifferenceType __length = __end1 - __begin1; _DifferenceType __result = __length; _DifferenceType* __borders; omp_lock_t __result_lock; omp_init_lock(&__result_lock); _ThreadIndex __num_threads = __get_max_threads(); # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __borders = new _DifferenceType[__num_threads + 1]; __equally_split(__length, __num_threads, __borders); } //single _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __start = __borders[__iam], __stop = __borders[__iam + 1]; _RAIter1 __i1 = __begin1 + __start; _RAIter2 __i2 = __begin2 + __start; for (_DifferenceType __pos = __start; __pos < __stop; ++__pos) { # pragma omp flush(__result) // Result has been set to something lower. if (__result < __pos) break; if (__selector(__i1, __i2, __pred)) { omp_set_lock(&__result_lock); if (__pos < __result) __result = __pos; omp_unset_lock(&__result_lock); break; } ++__i1; ++__i2; } } //parallel omp_destroy_lock(&__result_lock); delete[] __borders; return std::pair<_RAIter1, _RAIter2>(__begin1 + __result, __begin2 + __result); } #endif #if _GLIBCXX_FIND_GROWING_BLOCKS /** * @brief Parallel std::find, growing block size variant. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. Second __sequence * must have same length as first sequence. * @param __pred Find predicate. * @param __selector _Functionality (e. g. std::find_if(), std::equal(),...) * @return Place of finding in both sequences. * @see __gnu_parallel::_Settings::find_sequential_search_size * @see __gnu_parallel::_Settings::find_scale_factor * * There are two main differences between the growing blocks and * the constant-size blocks variants. * 1. For GB, the block size grows; for CSB, the block size is fixed. * 2. For GB, the blocks are allocated dynamically; * for CSB, the blocks are allocated in a predetermined manner, * namely spacial round-robin. */ template std::pair<_RAIter1, _RAIter2> __find_template(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred, _Selector __selector, growing_blocks_tag) { _GLIBCXX_CALL(__end1 - __begin1) typedef std::iterator_traits<_RAIter1> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename _TraitsType::value_type _ValueType; const _Settings& __s = _Settings::get(); _DifferenceType __length = __end1 - __begin1; _DifferenceType __sequential_search_size = std::min<_DifferenceType> (__length, __s.find_sequential_search_size); // Try it sequentially first. std::pair<_RAIter1, _RAIter2> __find_seq_result = __selector._M_sequential_algorithm (__begin1, __begin1 + __sequential_search_size, __begin2, __pred); if (__find_seq_result.first != (__begin1 + __sequential_search_size)) return __find_seq_result; // Index of beginning of next free block (after sequential find). _DifferenceType __next_block_start = __sequential_search_size; _DifferenceType __result = __length; omp_lock_t __result_lock; omp_init_lock(&__result_lock); const float __scale_factor = __s.find_scale_factor; _ThreadIndex __num_threads = __get_max_threads(); # pragma omp parallel shared(__result) num_threads(__num_threads) { # pragma omp single __num_threads = omp_get_num_threads(); // Not within first __k elements -> start parallel. _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __block_size = std::max<_DifferenceType>(1, __scale_factor * __next_block_start); _DifferenceType __start = __fetch_and_add<_DifferenceType> (&__next_block_start, __block_size); // Get new block, update pointer to next block. _DifferenceType __stop = std::min<_DifferenceType>(__length, __start + __block_size); std::pair<_RAIter1, _RAIter2> __local_result; while (__start < __length) { # pragma omp flush(__result) // Get new value of result. if (__result < __start) { // No chance to find first element. break; } __local_result = __selector._M_sequential_algorithm (__begin1 + __start, __begin1 + __stop, __begin2 + __start, __pred); if (__local_result.first != (__begin1 + __stop)) { omp_set_lock(&__result_lock); if ((__local_result.first - __begin1) < __result) { __result = __local_result.first - __begin1; // Result cannot be in future blocks, stop algorithm. __fetch_and_add<_DifferenceType>(&__next_block_start, __length); } omp_unset_lock(&__result_lock); } _DifferenceType __block_size = std::max<_DifferenceType>(1, __scale_factor * __next_block_start); // Get new block, update pointer to next block. __start = __fetch_and_add<_DifferenceType>(&__next_block_start, __block_size); __stop = std::min<_DifferenceType>(__length, __start + __block_size); } } //parallel omp_destroy_lock(&__result_lock); // Return iterator on found element. return std::pair<_RAIter1, _RAIter2>(__begin1 + __result, __begin2 + __result); } #endif #if _GLIBCXX_FIND_CONSTANT_SIZE_BLOCKS /** * @brief Parallel std::find, constant block size variant. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. Second __sequence * must have same length as first sequence. * @param __pred Find predicate. * @param __selector _Functionality (e. g. std::find_if(), std::equal(),...) * @return Place of finding in both sequences. * @see __gnu_parallel::_Settings::find_sequential_search_size * @see __gnu_parallel::_Settings::find_block_size * There are two main differences between the growing blocks and the * constant-size blocks variants. * 1. For GB, the block size grows; for CSB, the block size is fixed. * 2. For GB, the blocks are allocated dynamically; for CSB, the * blocks are allocated in a predetermined manner, namely spacial * round-robin. */ template std::pair<_RAIter1, _RAIter2> __find_template(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred, _Selector __selector, constant_size_blocks_tag) { _GLIBCXX_CALL(__end1 - __begin1) typedef std::iterator_traits<_RAIter1> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; typedef typename _TraitsType::value_type _ValueType; const _Settings& __s = _Settings::get(); _DifferenceType __length = __end1 - __begin1; _DifferenceType __sequential_search_size = std::min<_DifferenceType> (__length, __s.find_sequential_search_size); // Try it sequentially first. std::pair<_RAIter1, _RAIter2> __find_seq_result = __selector._M_sequential_algorithm (__begin1, __begin1 + __sequential_search_size, __begin2, __pred); if (__find_seq_result.first != (__begin1 + __sequential_search_size)) return __find_seq_result; _DifferenceType __result = __length; omp_lock_t __result_lock; omp_init_lock(&__result_lock); // Not within first __sequential_search_size elements -> start parallel. _ThreadIndex __num_threads = __get_max_threads(); # pragma omp parallel shared(__result) num_threads(__num_threads) { # pragma omp single __num_threads = omp_get_num_threads(); _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __block_size = __s.find_initial_block_size; // First element of thread's current iteration. _DifferenceType __iteration_start = __sequential_search_size; // Where to work (initialization). _DifferenceType __start = __iteration_start + __iam * __block_size; _DifferenceType __stop = std::min<_DifferenceType>(__length, __start + __block_size); std::pair<_RAIter1, _RAIter2> __local_result; while (__start < __length) { // Get new value of result. # pragma omp flush(__result) // No chance to find first element. if (__result < __start) break; __local_result = __selector._M_sequential_algorithm (__begin1 + __start, __begin1 + __stop, __begin2 + __start, __pred); if (__local_result.first != (__begin1 + __stop)) { omp_set_lock(&__result_lock); if ((__local_result.first - __begin1) < __result) __result = __local_result.first - __begin1; omp_unset_lock(&__result_lock); // Will not find better value in its interval. break; } __iteration_start += __num_threads * __block_size; // Where to work. __start = __iteration_start + __iam * __block_size; __stop = std::min<_DifferenceType>(__length, __start + __block_size); } } //parallel omp_destroy_lock(&__result_lock); // Return iterator on found element. return std::pair<_RAIter1, _RAIter2>(__begin1 + __result, __begin2 + __result); } #endif } // end namespace #endif /* _GLIBCXX_PARALLEL_FIND_H */ c++/8/parallel/find_selectors.h000064400000015520151027430570012242 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/find_selectors.h * @brief _Function objects representing different tasks to be plugged * into the parallel find algorithm. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_FIND_SELECTORS_H #define _GLIBCXX_PARALLEL_FIND_SELECTORS_H 1 #include #include #include namespace __gnu_parallel { /** @brief Base class of all __gnu_parallel::__find_template selectors. */ struct __generic_find_selector { }; /** * @brief Test predicate on a single element, used for std::find() * and std::find_if (). */ struct __find_if_selector : public __generic_find_selector { /** @brief Test on one position. * @param __i1 _Iterator on first sequence. * @param __i2 _Iterator on second sequence (unused). * @param __pred Find predicate. */ template bool operator()(_RAIter1 __i1, _RAIter2 __i2, _Pred __pred) { return __pred(*__i1); } /** @brief Corresponding sequential algorithm on a sequence. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __pred Find predicate. */ template std::pair<_RAIter1, _RAIter2> _M_sequential_algorithm(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred) { return std::make_pair(find_if(__begin1, __end1, __pred, sequential_tag()), __begin2); } }; /** @brief Test predicate on two adjacent elements. */ struct __adjacent_find_selector : public __generic_find_selector { /** @brief Test on one position. * @param __i1 _Iterator on first sequence. * @param __i2 _Iterator on second sequence (unused). * @param __pred Find predicate. */ template bool operator()(_RAIter1 __i1, _RAIter2 __i2, _Pred __pred) { // Passed end iterator is one short. return __pred(*__i1, *(__i1 + 1)); } /** @brief Corresponding sequential algorithm on a sequence. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __pred Find predicate. */ template std::pair<_RAIter1, _RAIter2> _M_sequential_algorithm(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred) { // Passed end iterator is one short. _RAIter1 __spot = adjacent_find(__begin1, __end1 + 1, __pred, sequential_tag()); if (__spot == (__end1 + 1)) __spot = __end1; return std::make_pair(__spot, __begin2); } }; /** @brief Test inverted predicate on a single element. */ struct __mismatch_selector : public __generic_find_selector { /** * @brief Test on one position. * @param __i1 _Iterator on first sequence. * @param __i2 _Iterator on second sequence (unused). * @param __pred Find predicate. */ template bool operator()(_RAIter1 __i1, _RAIter2 __i2, _Pred __pred) { return !__pred(*__i1, *__i2); } /** * @brief Corresponding sequential algorithm on a sequence. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __pred Find predicate. */ template std::pair<_RAIter1, _RAIter2> _M_sequential_algorithm(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred) { return mismatch(__begin1, __end1, __begin2, __pred, sequential_tag()); } }; /** @brief Test predicate on several elements. */ template struct __find_first_of_selector : public __generic_find_selector { _FIterator _M_begin; _FIterator _M_end; explicit __find_first_of_selector(_FIterator __begin, _FIterator __end) : _M_begin(__begin), _M_end(__end) { } /** @brief Test on one position. * @param __i1 _Iterator on first sequence. * @param __i2 _Iterator on second sequence (unused). * @param __pred Find predicate. */ template bool operator()(_RAIter1 __i1, _RAIter2 __i2, _Pred __pred) { for (_FIterator __pos_in_candidates = _M_begin; __pos_in_candidates != _M_end; ++__pos_in_candidates) if (__pred(*__i1, *__pos_in_candidates)) return true; return false; } /** @brief Corresponding sequential algorithm on a sequence. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __pred Find predicate. */ template std::pair<_RAIter1, _RAIter2> _M_sequential_algorithm(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _Pred __pred) { return std::make_pair(find_first_of(__begin1, __end1, _M_begin, _M_end, __pred, sequential_tag()), __begin2); } }; } #endif /* _GLIBCXX_PARALLEL_FIND_SELECTORS_H */ c++/8/parallel/partial_sum.h000064400000016462151027430570011565 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/partial_sum.h * @brief Parallel implementation of std::partial_sum(), i.e. prefix * sums. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_PARTIAL_SUM_H #define _GLIBCXX_PARALLEL_PARTIAL_SUM_H 1 #include #include #include #include #include namespace __gnu_parallel { // Problem: there is no 0-element given. /** @brief Base case prefix sum routine. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __result Begin iterator of output sequence. * @param __bin_op Associative binary function. * @param __value Start value. Must be passed since the neutral * element is unknown in general. * @return End iterator of output sequence. */ template _OutputIterator __parallel_partial_sum_basecase(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, typename std::iterator_traits <_IIter>::value_type __value) { if (__begin == __end) return __result; while (__begin != __end) { __value = __bin_op(__value, *__begin); *__result = __value; ++__result; ++__begin; } return __result; } /** @brief Parallel partial sum implementation, two-phase approach, no recursion. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __result Begin iterator of output sequence. * @param __bin_op Associative binary function. * @param __n Length of sequence. * @return End iterator of output sequence. */ template _OutputIterator __parallel_partial_sum_linear(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op, typename std::iterator_traits<_IIter>::difference_type __n) { typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; if (__begin == __end) return __result; _ThreadIndex __num_threads = std::min<_DifferenceType>(__get_max_threads(), __n - 1); if (__num_threads < 2) { *__result = *__begin; return __parallel_partial_sum_basecase(__begin + 1, __end, __result + 1, __bin_op, *__begin); } _DifferenceType* __borders; _ValueType* __sums; const _Settings& __s = _Settings::get(); # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __borders = new _DifferenceType[__num_threads + 2]; if (__s.partial_sum_dilation == 1.0f) __equally_split(__n, __num_threads + 1, __borders); else { _DifferenceType __first_part_length = std::max<_DifferenceType>(1, __n / (1.0f + __s.partial_sum_dilation * __num_threads)); _DifferenceType __chunk_length = (__n - __first_part_length) / __num_threads; _DifferenceType __borderstart = __n - __num_threads * __chunk_length; __borders[0] = 0; for (_ThreadIndex __i = 1; __i < (__num_threads + 1); ++__i) { __borders[__i] = __borderstart; __borderstart += __chunk_length; } __borders[__num_threads + 1] = __n; } __sums = static_cast<_ValueType*>(::operator new(sizeof(_ValueType) * __num_threads)); _OutputIterator __target_end; } //single _ThreadIndex __iam = omp_get_thread_num(); if (__iam == 0) { *__result = *__begin; __parallel_partial_sum_basecase(__begin + 1, __begin + __borders[1], __result + 1, __bin_op, *__begin); ::new(&(__sums[__iam])) _ValueType(*(__result + __borders[1] - 1)); } else { ::new(&(__sums[__iam])) _ValueType(__gnu_parallel::accumulate( __begin + __borders[__iam] + 1, __begin + __borders[__iam + 1], *(__begin + __borders[__iam]), __bin_op, __gnu_parallel::sequential_tag())); } # pragma omp barrier # pragma omp single __parallel_partial_sum_basecase(__sums + 1, __sums + __num_threads, __sums + 1, __bin_op, __sums[0]); # pragma omp barrier // Still same team. __parallel_partial_sum_basecase(__begin + __borders[__iam + 1], __begin + __borders[__iam + 2], __result + __borders[__iam + 1], __bin_op, __sums[__iam]); } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __sums[__i].~_ValueType(); ::operator delete(__sums); delete[] __borders; return __result + __n; } /** @brief Parallel partial sum front-__end. * @param __begin Begin iterator of input sequence. * @param __end End iterator of input sequence. * @param __result Begin iterator of output sequence. * @param __bin_op Associative binary function. * @return End iterator of output sequence. */ template _OutputIterator __parallel_partial_sum(_IIter __begin, _IIter __end, _OutputIterator __result, _BinaryOperation __bin_op) { _GLIBCXX_CALL(__begin - __end) typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; switch (_Settings::get().partial_sum_algorithm) { case LINEAR: // Need an initial offset. return __parallel_partial_sum_linear(__begin, __end, __result, __bin_op, __n); default: // Partial_sum algorithm not implemented. _GLIBCXX_PARALLEL_ASSERT(0); return __result + __n; } } } #endif /* _GLIBCXX_PARALLEL_PARTIAL_SUM_H */ c++/8/parallel/unique_copy.h000064400000014025151027430570011576 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/unique_copy.h * @brief Parallel implementations of std::unique_copy(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Robert Geisberger and Robin Dapp. #ifndef _GLIBCXX_PARALLEL_UNIQUE_COPY_H #define _GLIBCXX_PARALLEL_UNIQUE_COPY_H 1 #include #include namespace __gnu_parallel { /** @brief Parallel std::unique_copy(), w/__o explicit equality predicate. * @param __first Begin iterator of input sequence. * @param __last End iterator of input sequence. * @param __result Begin iterator of result __sequence. * @param __binary_pred Equality predicate. * @return End iterator of result __sequence. */ template _OutputIterator __parallel_unique_copy(_IIter __first, _IIter __last, _OutputIterator __result, _BinaryPredicate __binary_pred) { _GLIBCXX_CALL(__last - __first) typedef std::iterator_traits<_IIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __size = __last - __first; if (__size == 0) return __result; // Let the first thread process two parts. _DifferenceType *__counter; _DifferenceType *__borders; _ThreadIndex __num_threads = __get_max_threads(); // First part contains at least one element. # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __borders = new _DifferenceType[__num_threads + 2]; __equally_split(__size, __num_threads + 1, __borders); __counter = new _DifferenceType[__num_threads + 1]; } _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __begin, __end; // Check for length without duplicates // Needed for position in output _DifferenceType __i = 0; _OutputIterator __out = __result; if (__iam == 0) { __begin = __borders[0] + 1; // == 1 __end = __borders[__iam + 1]; ++__i; *__out++ = *__first; for (_IIter __iter = __first + __begin; __iter < __first + __end; ++__iter) { if (!__binary_pred(*__iter, *(__iter - 1))) { ++__i; *__out++ = *__iter; } } } else { __begin = __borders[__iam]; //one part __end = __borders[__iam + 1]; for (_IIter __iter = __first + __begin; __iter < __first + __end; ++__iter) { if (!__binary_pred(*__iter, *(__iter - 1))) ++__i; } } __counter[__iam] = __i; // Last part still untouched. _DifferenceType __begin_output; # pragma omp barrier // Store result in output on calculated positions. __begin_output = 0; if (__iam == 0) { for (_ThreadIndex __t = 0; __t < __num_threads; ++__t) __begin_output += __counter[__t]; __i = 0; _OutputIterator __iter_out = __result + __begin_output; __begin = __borders[__num_threads]; __end = __size; for (_IIter __iter = __first + __begin; __iter < __first + __end; ++__iter) { if (__iter == __first || !__binary_pred(*__iter, *(__iter - 1))) { ++__i; *__iter_out++ = *__iter; } } __counter[__num_threads] = __i; } else { for (_ThreadIndex __t = 0; __t < __iam; __t++) __begin_output += __counter[__t]; _OutputIterator __iter_out = __result + __begin_output; for (_IIter __iter = __first + __begin; __iter < __first + __end; ++__iter) { if (!__binary_pred(*__iter, *(__iter - 1))) *__iter_out++ = *__iter; } } } _DifferenceType __end_output = 0; for (_ThreadIndex __t = 0; __t < __num_threads + 1; __t++) __end_output += __counter[__t]; delete[] __borders; return __result + __end_output; } /** @brief Parallel std::unique_copy(), without explicit equality predicate * @param __first Begin iterator of input sequence. * @param __last End iterator of input sequence. * @param __result Begin iterator of result __sequence. * @return End iterator of result __sequence. */ template inline _OutputIterator __parallel_unique_copy(_IIter __first, _IIter __last, _OutputIterator __result) { typedef typename std::iterator_traits<_IIter>::value_type _ValueType; return __parallel_unique_copy(__first, __last, __result, std::equal_to<_ValueType>()); } }//namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_UNIQUE_COPY_H */ c++/8/parallel/numericfwd.h000064400000016514151027430570011406 0ustar00// Forward declarations -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/numericfwd.h * This file is a GNU parallel extension to the Standard C++ Library. */ #ifndef _GLIBCXX_PARALLEL_NUMERICFWD_H #define _GLIBCXX_PARALLEL_NUMERICFWD_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __parallel { template _Tp accumulate(_IIter, _IIter, _Tp); template _Tp accumulate(_IIter, _IIter, _Tp, __gnu_parallel::sequential_tag); template _Tp accumulate(_IIter, _IIter, _Tp, __gnu_parallel::_Parallelism); template _Tp __accumulate_switch(_IIter, _IIter, _Tp, _Tag); template _Tp accumulate(_IIter, _IIter, _Tp, _BinaryOper); template _Tp accumulate(_IIter, _IIter, _Tp, _BinaryOper, __gnu_parallel::sequential_tag); template _Tp accumulate(_IIter, _IIter, _Tp, _BinaryOper, __gnu_parallel::_Parallelism); template _Tp __accumulate_switch(_IIter, _IIter, _Tp, _BinaryOper, _Tag); template _Tp __accumulate_switch(_RAIter, _RAIter, _Tp, _BinaryOper, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_unbalanced); template _OIter adjacent_difference(_IIter, _IIter, _OIter); template _OIter adjacent_difference(_IIter, _IIter, _OIter, _BinaryOper); template _OIter adjacent_difference(_IIter, _IIter, _OIter, __gnu_parallel::sequential_tag); template _OIter adjacent_difference(_IIter, _IIter, _OIter, _BinaryOper, __gnu_parallel::sequential_tag); template _OIter adjacent_difference(_IIter, _IIter, _OIter, __gnu_parallel::_Parallelism); template _OIter adjacent_difference(_IIter, _IIter, _OIter, _BinaryOper, __gnu_parallel::_Parallelism); template _OIter __adjacent_difference_switch(_IIter, _IIter, _OIter, _BinaryOper, _Tag1, _Tag2); template _OIter __adjacent_difference_switch(_IIter, _IIter, _OIter, _BinaryOper, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_unbalanced); template _Tp inner_product(_IIter1, _IIter1, _IIter2, _Tp); template _Tp inner_product(_IIter1, _IIter1, _IIter2, _Tp, __gnu_parallel::sequential_tag); template _Tp inner_product(_IIter1, _IIter1, _IIter2, _Tp, __gnu_parallel::_Parallelism); template _Tp inner_product(_IIter1, _IIter1, _IIter2, _Tp, _BinaryFunction1, _BinaryFunction2); template _Tp inner_product(_IIter1, _IIter1, _IIter2, _Tp, _BinaryFunction1, _BinaryFunction2, __gnu_parallel::sequential_tag); template _Tp inner_product(_IIter1, _IIter1, _IIter2, _Tp, BinaryFunction1, BinaryFunction2, __gnu_parallel::_Parallelism); template _Tp __inner_product_switch(_RAIter1, _RAIter1, _RAIter2, _Tp, BinaryFunction1, BinaryFunction2, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism = __gnu_parallel::parallel_unbalanced); template _Tp __inner_product_switch(_IIter1, _IIter1, _IIter2, _Tp, _BinaryFunction1, _BinaryFunction2, _Tag1, _Tag2); template _OIter partial_sum(_IIter, _IIter, _OIter, __gnu_parallel::sequential_tag); template _OIter partial_sum(_IIter, _IIter, _OIter, _BinaryOper, __gnu_parallel::sequential_tag); template _OIter partial_sum(_IIter, _IIter, _OIter __result); template _OIter partial_sum(_IIter, _IIter, _OIter, _BinaryOper); template _OIter __partial_sum_switch(_IIter, _IIter, _OIter, _BinaryOper, _Tag1, _Tag2); template _OIter __partial_sum_switch(_IIter, _IIter, _OIter, _BinaryOper, random_access_iterator_tag, random_access_iterator_tag); } // end namespace } // end namespace #endif /* _GLIBCXX_PARALLEL_NUMERICFWD_H */ c++/8/parallel/iterator.h000064400000013056151027430570011072 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/iterator.h * @brief Helper iterator classes for the std::transform() functions. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_ITERATOR_H #define _GLIBCXX_PARALLEL_ITERATOR_H 1 #include #include namespace __gnu_parallel { /** @brief A pair of iterators. The usual iterator operations are * applied to both child iterators. */ template class _IteratorPair : public std::pair<_Iterator1, _Iterator2> { private: typedef std::pair<_Iterator1, _Iterator2> _Base; public: typedef _IteratorCategory iterator_category; typedef void value_type; typedef std::iterator_traits<_Iterator1> _TraitsType; typedef typename _TraitsType::difference_type difference_type; typedef _IteratorPair* pointer; typedef _IteratorPair& reference; _IteratorPair() { } _IteratorPair(const _Iterator1& __first, const _Iterator2& __second) : _Base(__first, __second) { } // Pre-increment operator. _IteratorPair& operator++() { ++_Base::first; ++_Base::second; return *this; } // Post-increment operator. const _IteratorPair operator++(int) { return _IteratorPair(_Base::first++, _Base::second++); } // Pre-decrement operator. _IteratorPair& operator--() { --_Base::first; --_Base::second; return *this; } // Post-decrement operator. const _IteratorPair operator--(int) { return _IteratorPair(_Base::first--, _Base::second--); } // Type conversion. operator _Iterator2() const { return _Base::second; } _IteratorPair& operator=(const _IteratorPair& __other) { _Base::first = __other.first; _Base::second = __other.second; return *this; } _IteratorPair operator+(difference_type __delta) const { return _IteratorPair(_Base::first + __delta, _Base::second + __delta); } difference_type operator-(const _IteratorPair& __other) const { return _Base::first - __other.first; } }; /** @brief A triple of iterators. The usual iterator operations are applied to all three child iterators. */ template class _IteratorTriple { public: typedef _IteratorCategory iterator_category; typedef void value_type; typedef typename std::iterator_traits<_Iterator1>::difference_type difference_type; typedef _IteratorTriple* pointer; typedef _IteratorTriple& reference; _Iterator1 _M_first; _Iterator2 _M_second; _Iterator3 _M_third; _IteratorTriple() { } _IteratorTriple(const _Iterator1& __first, const _Iterator2& __second, const _Iterator3& __third) { _M_first = __first; _M_second = __second; _M_third = __third; } // Pre-increment operator. _IteratorTriple& operator++() { ++_M_first; ++_M_second; ++_M_third; return *this; } // Post-increment operator. const _IteratorTriple operator++(int) { return _IteratorTriple(_M_first++, _M_second++, _M_third++); } // Pre-decrement operator. _IteratorTriple& operator--() { --_M_first; --_M_second; --_M_third; return *this; } // Post-decrement operator. const _IteratorTriple operator--(int) { return _IteratorTriple(_M_first--, _M_second--, _M_third--); } // Type conversion. operator _Iterator3() const { return _M_third; } _IteratorTriple& operator=(const _IteratorTriple& __other) { _M_first = __other._M_first; _M_second = __other._M_second; _M_third = __other._M_third; return *this; } _IteratorTriple operator+(difference_type __delta) const { return _IteratorTriple(_M_first + __delta, _M_second + __delta, _M_third + __delta); } difference_type operator-(const _IteratorTriple& __other) const { return _M_first - __other._M_first; } }; } #endif /* _GLIBCXX_PARALLEL_ITERATOR_H */ c++/8/parallel/settings.h000064400000030252151027430570011076 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/settings.h * @brief Runtime settings and tuning parameters, heuristics to decide * whether to use parallelized algorithms. * This file is a GNU parallel extension to the Standard C++ Library. * * @section parallelization_decision * The decision whether to run an algorithm in parallel. * * There are several ways the user can switch on and __off the parallel * execution of an algorithm, both at compile- and run-time. * * Only sequential execution can be forced at compile-time. This * reduces code size and protects code parts that have * non-thread-safe side effects. * * Ultimately, forcing parallel execution at compile-time makes * sense. Often, the sequential algorithm implementation is used as * a subroutine, so no reduction in code size can be achieved. Also, * the machine the program is run on might have only one processor * core, so to avoid overhead, the algorithm is executed * sequentially. * * To force sequential execution of an algorithm ultimately at * compile-time, the user must add the tag * gnu_parallel::sequential_tag() to the end of the parameter list, * e. g. * * \code * std::sort(__v.begin(), __v.end(), __gnu_parallel::sequential_tag()); * \endcode * * This is compatible with all overloaded algorithm variants. No * additional code will be instantiated, at all. The same holds for * most algorithm calls with iterators not providing random access. * * If the algorithm call is not forced to be executed sequentially * at compile-time, the decision is made at run-time. * The global variable __gnu_parallel::_Settings::algorithm_strategy * is checked. _It is a tristate variable corresponding to: * * a. force_sequential, meaning the sequential algorithm is executed. * b. force_parallel, meaning the parallel algorithm is executed. * c. heuristic * * For heuristic, the parallel algorithm implementation is called * only if the input size is sufficiently large. For most * algorithms, the input size is the (combined) length of the input * sequence(__s). The threshold can be set by the user, individually * for each algorithm. The according variables are called * gnu_parallel::_Settings::[algorithm]_minimal_n . * * For some of the algorithms, there are even more tuning options, * e. g. the ability to choose from multiple algorithm variants. See * below for details. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_SETTINGS_H #define _GLIBCXX_PARALLEL_SETTINGS_H 1 #include /** * @brief Determine at compile(?)-time if the parallel variant of an * algorithm should be called. * @param __c A condition that is convertible to bool that is overruled by * __gnu_parallel::_Settings::algorithm_strategy. Usually a decision * based on the input size. */ #define _GLIBCXX_PARALLEL_CONDITION(__c) \ (__gnu_parallel::_Settings::get().algorithm_strategy \ != __gnu_parallel::force_sequential \ && ((__gnu_parallel::__get_max_threads() > 1 && (__c)) \ || __gnu_parallel::_Settings::get().algorithm_strategy \ == __gnu_parallel::force_parallel)) /* inline bool parallel_condition(bool __c) { bool ret = false; const _Settings& __s = _Settings::get(); if (__s.algorithm_strategy != force_seqential) { if (__s.algorithm_strategy == force_parallel) ret = true; else ret = __get_max_threads() > 1 && __c; } return ret; } */ namespace __gnu_parallel { /// class _Settings /// Run-time settings for the parallel mode including all tunable parameters. struct _Settings { _AlgorithmStrategy algorithm_strategy; _SortAlgorithm sort_algorithm; _PartialSumAlgorithm partial_sum_algorithm; _MultiwayMergeAlgorithm multiway_merge_algorithm; _FindAlgorithm find_algorithm; _SplittingAlgorithm sort_splitting; _SplittingAlgorithm merge_splitting; _SplittingAlgorithm multiway_merge_splitting; // Per-algorithm settings. /// Minimal input size for accumulate. _SequenceIndex accumulate_minimal_n; /// Minimal input size for adjacent_difference. unsigned int adjacent_difference_minimal_n; /// Minimal input size for count and count_if. _SequenceIndex count_minimal_n; /// Minimal input size for fill. _SequenceIndex fill_minimal_n; /// Block size increase factor for find. double find_increasing_factor; /// Initial block size for find. _SequenceIndex find_initial_block_size; /// Maximal block size for find. _SequenceIndex find_maximum_block_size; /// Start with looking for this many elements sequentially, for find. _SequenceIndex find_sequential_search_size; /// Minimal input size for for_each. _SequenceIndex for_each_minimal_n; /// Minimal input size for generate. _SequenceIndex generate_minimal_n; /// Minimal input size for max_element. _SequenceIndex max_element_minimal_n; /// Minimal input size for merge. _SequenceIndex merge_minimal_n; /// Oversampling factor for merge. unsigned int merge_oversampling; /// Minimal input size for min_element. _SequenceIndex min_element_minimal_n; /// Minimal input size for multiway_merge. _SequenceIndex multiway_merge_minimal_n; /// Oversampling factor for multiway_merge. int multiway_merge_minimal_k; /// Oversampling factor for multiway_merge. unsigned int multiway_merge_oversampling; /// Minimal input size for nth_element. _SequenceIndex nth_element_minimal_n; /// Chunk size for partition. _SequenceIndex partition_chunk_size; /// Chunk size for partition, relative to input size. If > 0.0, /// this value overrides partition_chunk_size. double partition_chunk_share; /// Minimal input size for partition. _SequenceIndex partition_minimal_n; /// Minimal input size for partial_sort. _SequenceIndex partial_sort_minimal_n; /// Ratio for partial_sum. Assume "sum and write result" to be /// this factor slower than just "sum". float partial_sum_dilation; /// Minimal input size for partial_sum. unsigned int partial_sum_minimal_n; /// Minimal input size for random_shuffle. unsigned int random_shuffle_minimal_n; /// Minimal input size for replace and replace_if. _SequenceIndex replace_minimal_n; /// Minimal input size for set_difference. _SequenceIndex set_difference_minimal_n; /// Minimal input size for set_intersection. _SequenceIndex set_intersection_minimal_n; /// Minimal input size for set_symmetric_difference. _SequenceIndex set_symmetric_difference_minimal_n; /// Minimal input size for set_union. _SequenceIndex set_union_minimal_n; /// Minimal input size for parallel sorting. _SequenceIndex sort_minimal_n; /// Oversampling factor for parallel std::sort (MWMS). unsigned int sort_mwms_oversampling; /// Such many samples to take to find a good pivot (quicksort). unsigned int sort_qs_num_samples_preset; /// Maximal subsequence __length to switch to unbalanced __base case. /// Applies to std::sort with dynamically load-balanced quicksort. _SequenceIndex sort_qsb_base_case_maximal_n; /// Minimal input size for parallel std::transform. _SequenceIndex transform_minimal_n; /// Minimal input size for unique_copy. _SequenceIndex unique_copy_minimal_n; _SequenceIndex workstealing_chunk_size; // Hardware dependent tuning parameters. /// size of the L1 cache in bytes (underestimation). unsigned long long L1_cache_size; /// size of the L2 cache in bytes (underestimation). unsigned long long L2_cache_size; /// size of the Translation Lookaside Buffer (underestimation). unsigned int TLB_size; /// Overestimation of cache line size. Used to avoid false /// sharing, i.e. elements of different threads are at least this /// amount apart. unsigned int cache_line_size; // Statistics. /// The number of stolen ranges in load-balanced quicksort. _SequenceIndex qsb_steals; /// Minimal input size for search and search_n. _SequenceIndex search_minimal_n; /// Block size scale-down factor with respect to current position. float find_scale_factor; /// Get the global settings. _GLIBCXX_CONST static const _Settings& get() throw(); /// Set the global settings. static void set(_Settings&) throw(); explicit _Settings() : algorithm_strategy(heuristic), sort_algorithm(MWMS), partial_sum_algorithm(LINEAR), multiway_merge_algorithm(LOSER_TREE), find_algorithm(CONSTANT_SIZE_BLOCKS), sort_splitting(EXACT), merge_splitting(EXACT), multiway_merge_splitting(EXACT), accumulate_minimal_n(1000), adjacent_difference_minimal_n(1000), count_minimal_n(1000), fill_minimal_n(1000), find_increasing_factor(2.0), find_initial_block_size(256), find_maximum_block_size(8192), find_sequential_search_size(256), for_each_minimal_n(1000), generate_minimal_n(1000), max_element_minimal_n(1000), merge_minimal_n(1000), merge_oversampling(10), min_element_minimal_n(1000), multiway_merge_minimal_n(1000), multiway_merge_minimal_k(2), multiway_merge_oversampling(10), nth_element_minimal_n(1000), partition_chunk_size(1000), partition_chunk_share(0.0), partition_minimal_n(1000), partial_sort_minimal_n(1000), partial_sum_dilation(1.0f), partial_sum_minimal_n(1000), random_shuffle_minimal_n(1000), replace_minimal_n(1000), set_difference_minimal_n(1000), set_intersection_minimal_n(1000), set_symmetric_difference_minimal_n(1000), set_union_minimal_n(1000), sort_minimal_n(1000), sort_mwms_oversampling(10), sort_qs_num_samples_preset(100), sort_qsb_base_case_maximal_n(100), transform_minimal_n(1000), unique_copy_minimal_n(10000), workstealing_chunk_size(100), L1_cache_size(16 << 10), L2_cache_size(256 << 10), TLB_size(128), cache_line_size(64), qsb_steals(0), search_minimal_n(1000), find_scale_factor(0.01f) { } }; } #endif /* _GLIBCXX_PARALLEL_SETTINGS_H */ c++/8/parallel/base.h000064400000030125151027430570010147 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/base.h * @brief Sequential helper functions. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_BASE_H #define _GLIBCXX_PARALLEL_BASE_H 1 #include #include #include #include #include #include // Parallel mode namespaces. /** * @namespace std::__parallel * @brief GNU parallel code, replaces standard behavior with parallel behavior. */ namespace std _GLIBCXX_VISIBILITY(default) { namespace __parallel { } } /** * @namespace __gnu_parallel * @brief GNU parallel code for public use. */ namespace __gnu_parallel { // Import all the parallel versions of components in namespace std. using namespace std::__parallel; } /** * @namespace __gnu_sequential * @brief GNU sequential classes for public use. */ namespace __gnu_sequential { // Import whatever is the serial version. #ifdef _GLIBCXX_PARALLEL using namespace std::_GLIBCXX_STD_A; #else using namespace std; #endif } namespace __gnu_parallel { // NB: Including this file cannot produce (unresolved) symbols from // the OpenMP runtime unless the parallel mode is actually invoked // and active, which imples that the OpenMP runtime is actually // going to be linked in. inline _ThreadIndex __get_max_threads() { _ThreadIndex __i = omp_get_max_threads(); return __i > 1 ? __i : 1; } inline bool __is_parallel(const _Parallelism __p) { return __p != sequential; } /** @brief Calculates the rounded-down logarithm of @c __n for base 2. * @param __n Argument. * @return Returns 0 for any argument <1. */ template inline _Size __rd_log2(_Size __n) { _Size __k; for (__k = 0; __n > 1; __n >>= 1) ++__k; return __k; } /** @brief Encode two integers into one gnu_parallel::_CASable. * @param __a First integer, to be encoded in the most-significant @c * _CASable_bits/2 bits. * @param __b Second integer, to be encoded in the least-significant * @c _CASable_bits/2 bits. * @return value encoding @c __a and @c __b. * @see __decode2 */ inline _CASable __encode2(int __a, int __b) //must all be non-negative, actually { return (((_CASable)__a) << (_CASable_bits / 2)) | (((_CASable)__b) << 0); } /** @brief Decode two integers from one gnu_parallel::_CASable. * @param __x __gnu_parallel::_CASable to decode integers from. * @param __a First integer, to be decoded from the most-significant * @c _CASable_bits/2 bits of @c __x. * @param __b Second integer, to be encoded in the least-significant * @c _CASable_bits/2 bits of @c __x. * @see __encode2 */ inline void __decode2(_CASable __x, int& __a, int& __b) { __a = (int)((__x >> (_CASable_bits / 2)) & _CASable_mask); __b = (int)((__x >> 0 ) & _CASable_mask); } //needed for parallel "numeric", even if "algorithm" not included /** @brief Equivalent to std::min. */ template inline const _Tp& min(const _Tp& __a, const _Tp& __b) { return (__a < __b) ? __a : __b; } /** @brief Equivalent to std::max. */ template inline const _Tp& max(const _Tp& __a, const _Tp& __b) { return (__a > __b) ? __a : __b; } /** @brief Constructs predicate for equality from strict weak * ordering predicate */ template class _EqualFromLess : public std::binary_function<_T1, _T2, bool> { private: _Compare& _M_comp; public: _EqualFromLess(_Compare& __comp) : _M_comp(__comp) { } bool operator()(const _T1& __a, const _T2& __b) { return !_M_comp(__a, __b) && !_M_comp(__b, __a); } }; /** @brief Similar to std::unary_negate, * but giving the argument types explicitly. */ template class __unary_negate : public std::unary_function { protected: _Predicate _M_pred; public: explicit __unary_negate(const _Predicate& __x) : _M_pred(__x) { } bool operator()(const argument_type& __x) { return !_M_pred(__x); } }; /** @brief Similar to std::binder1st, * but giving the argument types explicitly. */ template class __binder1st : public std::unary_function<_SecondArgumentType, _ResultType> { protected: _Operation _M_op; _FirstArgumentType _M_value; public: __binder1st(const _Operation& __x, const _FirstArgumentType& __y) : _M_op(__x), _M_value(__y) { } _ResultType operator()(const _SecondArgumentType& __x) { return _M_op(_M_value, __x); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 109. Missing binders for non-const sequence elements _ResultType operator()(_SecondArgumentType& __x) const { return _M_op(_M_value, __x); } }; /** * @brief Similar to std::binder2nd, but giving the argument types * explicitly. */ template class __binder2nd : public std::unary_function<_FirstArgumentType, _ResultType> { protected: _Operation _M_op; _SecondArgumentType _M_value; public: __binder2nd(const _Operation& __x, const _SecondArgumentType& __y) : _M_op(__x), _M_value(__y) { } _ResultType operator()(const _FirstArgumentType& __x) const { return _M_op(__x, _M_value); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 109. Missing binders for non-const sequence elements _ResultType operator()(_FirstArgumentType& __x) { return _M_op(__x, _M_value); } }; /** @brief Similar to std::equal_to, but allows two different types. */ template struct _EqualTo : std::binary_function<_T1, _T2, bool> { bool operator()(const _T1& __t1, const _T2& __t2) const { return __t1 == __t2; } }; /** @brief Similar to std::less, but allows two different types. */ template struct _Less : std::binary_function<_T1, _T2, bool> { bool operator()(const _T1& __t1, const _T2& __t2) const { return __t1 < __t2; } bool operator()(const _T2& __t2, const _T1& __t1) const { return __t2 < __t1; } }; // Partial specialization for one type. Same as std::less. template struct _Less<_Tp, _Tp> : public std::less<_Tp> { }; /** @brief Similar to std::plus, but allows two different types. */ template(0) + *static_cast<_Tp2*>(0))> struct _Plus : public std::binary_function<_Tp1, _Tp2, _Result> { _Result operator()(const _Tp1& __x, const _Tp2& __y) const { return __x + __y; } }; // Partial specialization for one type. Same as std::plus. template struct _Plus<_Tp, _Tp, _Tp> : public std::plus<_Tp> { }; /** @brief Similar to std::multiplies, but allows two different types. */ template(0) * *static_cast<_Tp2*>(0))> struct _Multiplies : public std::binary_function<_Tp1, _Tp2, _Result> { _Result operator()(const _Tp1& __x, const _Tp2& __y) const { return __x * __y; } }; // Partial specialization for one type. Same as std::multiplies. template struct _Multiplies<_Tp, _Tp, _Tp> : public std::multiplies<_Tp> { }; /** @brief _Iterator associated with __gnu_parallel::_PseudoSequence. * If features the usual random-access iterator functionality. * @param _Tp Sequence _M_value type. * @param _DifferenceTp Sequence difference type. */ template class _PseudoSequenceIterator { public: typedef _DifferenceTp _DifferenceType; _PseudoSequenceIterator(const _Tp& __val, _DifferenceType __pos) : _M_val(__val), _M_pos(__pos) { } // Pre-increment operator. _PseudoSequenceIterator& operator++() { ++_M_pos; return *this; } // Post-increment operator. _PseudoSequenceIterator operator++(int) { return _PseudoSequenceIterator(_M_pos++); } const _Tp& operator*() const { return _M_val; } const _Tp& operator[](_DifferenceType) const { return _M_val; } bool operator==(const _PseudoSequenceIterator& __i2) { return _M_pos == __i2._M_pos; } bool operator!=(const _PseudoSequenceIterator& __i2) { return _M_pos != __i2._M_pos; } _DifferenceType operator-(const _PseudoSequenceIterator& __i2) { return _M_pos - __i2._M_pos; } private: const _Tp& _M_val; _DifferenceType _M_pos; }; /** @brief Sequence that conceptually consists of multiple copies of the same element. * The copies are not stored explicitly, of course. * @param _Tp Sequence _M_value type. * @param _DifferenceTp Sequence difference type. */ template class _PseudoSequence { public: typedef _DifferenceTp _DifferenceType; // Better cast down to uint64_t, than up to _DifferenceTp. typedef _PseudoSequenceIterator<_Tp, uint64_t> iterator; /** @brief Constructor. * @param __val Element of the sequence. * @param __count Number of (virtual) copies. */ _PseudoSequence(const _Tp& __val, _DifferenceType __count) : _M_val(__val), _M_count(__count) { } /** @brief Begin iterator. */ iterator begin() const { return iterator(_M_val, 0); } /** @brief End iterator. */ iterator end() const { return iterator(_M_val, _M_count); } private: const _Tp& _M_val; _DifferenceType _M_count; }; /** @brief Compute the median of three referenced elements, according to @c __comp. * @param __a First iterator. * @param __b Second iterator. * @param __c Third iterator. * @param __comp Comparator. */ template _RAIter __median_of_three_iterators(_RAIter __a, _RAIter __b, _RAIter __c, _Compare __comp) { if (__comp(*__a, *__b)) if (__comp(*__b, *__c)) return __b; else if (__comp(*__a, *__c)) return __c; else return __a; else { // Just swap __a and __b. if (__comp(*__a, *__c)) return __a; else if (__comp(*__b, *__c)) return __c; else return __b; } } #if _GLIBCXX_PARALLEL_ASSERTIONS && defined(__glibcxx_assert_impl) #define _GLIBCXX_PARALLEL_ASSERT(_Condition) __glibcxx_assert_impl(_Condition) #else #define _GLIBCXX_PARALLEL_ASSERT(_Condition) #endif } //namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_BASE_H */ c++/8/parallel/equally_split.h000064400000006434151027430570012132 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/equally_split.h * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_EQUALLY_SPLIT_H #define _GLIBCXX_PARALLEL_EQUALLY_SPLIT_H 1 namespace __gnu_parallel { /** @brief function to split a sequence into parts of almost equal size. * * The resulting sequence __s of length __num_threads+1 contains the * splitting positions when splitting the range [0,__n) into parts of * almost equal size (plus minus 1). The first entry is 0, the last * one n. There may result empty parts. * @param __n Number of elements * @param __num_threads Number of parts * @param __s Splitters * @returns End of __splitter sequence, i.e. @c __s+__num_threads+1 */ template _OutputIterator __equally_split(_DifferenceType __n, _ThreadIndex __num_threads, _OutputIterator __s) { _DifferenceType __chunk_length = __n / __num_threads; _DifferenceType __num_longer_chunks = __n % __num_threads; _DifferenceType __pos = 0; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) { *__s++ = __pos; __pos += ((__i < __num_longer_chunks) ? (__chunk_length + 1) : __chunk_length); } *__s++ = __n; return __s; } /** @brief function to split a sequence into parts of almost equal size. * * Returns the position of the splitting point between * thread number __thread_no (included) and * thread number __thread_no+1 (excluded). * @param __n Number of elements * @param __num_threads Number of parts * @param __thread_no Number of threads * @returns splitting point */ template _DifferenceType __equally_split_point(_DifferenceType __n, _ThreadIndex __num_threads, _ThreadIndex __thread_no) { _DifferenceType __chunk_length = __n / __num_threads; _DifferenceType __num_longer_chunks = __n % __num_threads; if (__thread_no < __num_longer_chunks) return __thread_no * (__chunk_length + 1); else return __num_longer_chunks * (__chunk_length + 1) + (__thread_no - __num_longer_chunks) * __chunk_length; } } #endif /* _GLIBCXX_PARALLEL_EQUALLY_SPLIT_H */ c++/8/parallel/parallel.h000064400000003050151027430570011026 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/parallel.h * @brief End-user include file. Provides advanced settings and * tuning options. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze and Johannes Singler. #ifndef _GLIBCXX_PARALLEL_PARALLEL_H #define _GLIBCXX_PARALLEL_PARALLEL_H 1 #include #include #include #include #include #endif /* _GLIBCXX_PARALLEL_PARALLEL_H */ c++/8/parallel/algorithmfwd.h000064400000076716151027430570011744 0ustar00// Forward declarations -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/algorithmfwd.h * This file is a GNU parallel extension to the Standard C++ Library. */ #ifndef _GLIBCXX_PARALLEL_ALGORITHMFWD_H #define _GLIBCXX_PARALLEL_ALGORITHMFWD_H 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __parallel { template _FIter adjacent_find(_FIter, _FIter); template _FIter adjacent_find(_FIter, _FIter, __gnu_parallel::sequential_tag); template _FIter __adjacent_find_switch(_FIter, _FIter, _IterTag); template _RAIter __adjacent_find_switch(_RAIter, _RAIter, random_access_iterator_tag); template _FIter adjacent_find(_FIter, _FIter, _BiPredicate); template _FIter adjacent_find(_FIter, _FIter, _BiPredicate, __gnu_parallel::sequential_tag); template _FIter __adjacent_find_switch(_FIter, _FIter, _BiPredicate, _IterTag); template _RAIter __adjacent_find_switch(_RAIter, _RAIter, _BiPredicate, random_access_iterator_tag); template typename iterator_traits<_IIter>::difference_type count(_IIter, _IIter, const _Tp&); template typename iterator_traits<_IIter>::difference_type count(_IIter, _IIter, const _Tp&, __gnu_parallel::sequential_tag); template typename iterator_traits<_IIter>::difference_type count(_IIter, _IIter, const _Tp&, __gnu_parallel::_Parallelism); template typename iterator_traits<_IIter>::difference_type __count_switch(_IIter, _IIter, const _Tp&, _IterTag); template typename iterator_traits<_RAIter>::difference_type __count_switch(_RAIter, _RAIter, const _Tp&, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_unbalanced); template typename iterator_traits<_IIter>::difference_type count_if(_IIter, _IIter, _Predicate); template typename iterator_traits<_IIter>::difference_type count_if(_IIter, _IIter, _Predicate, __gnu_parallel::sequential_tag); template typename iterator_traits<_IIter>::difference_type count_if(_IIter, _IIter, _Predicate, __gnu_parallel::_Parallelism); template typename iterator_traits<_IIter>::difference_type __count_if_switch(_IIter, _IIter, _Predicate, _IterTag); template typename iterator_traits<_RAIter>::difference_type __count_if_switch(_RAIter, _RAIter, _Predicate, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_unbalanced); // algobase.h template bool equal(_IIter1, _IIter1, _IIter2, __gnu_parallel::sequential_tag); template bool equal(_IIter1, _IIter1, _IIter2, _Predicate, __gnu_parallel::sequential_tag); template bool equal(_IIter1, _IIter1, _IIter2); template bool equal(_IIter1, _IIter1, _IIter2, _Predicate); template _IIter find(_IIter, _IIter, const _Tp&, __gnu_parallel::sequential_tag); template _IIter find(_IIter, _IIter, const _Tp& __val); template _IIter __find_switch(_IIter, _IIter, const _Tp&, _IterTag); template _RAIter __find_switch(_RAIter, _RAIter, const _Tp&, random_access_iterator_tag); template _IIter find_if(_IIter, _IIter, _Predicate, __gnu_parallel::sequential_tag); template _IIter find_if(_IIter, _IIter, _Predicate); template _IIter __find_if_switch(_IIter, _IIter, _Predicate, _IterTag); template _RAIter __find_if_switch(_RAIter, _RAIter, _Predicate, random_access_iterator_tag); template _IIter find_first_of(_IIter, _IIter, _FIter, _FIter, __gnu_parallel::sequential_tag); template _IIter find_first_of(_IIter, _IIter, _FIter, _FIter, _BiPredicate, __gnu_parallel::sequential_tag); template _IIter find_first_of(_IIter, _IIter, _FIter, _FIter, _BiPredicate); template _IIter find_first_of(_IIter, _IIter, _FIter, _FIter); template _IIter __find_first_of_switch( _IIter, _IIter, _FIter, _FIter, _IterTag1, _IterTag2); template _RAIter __find_first_of_switch(_RAIter, _RAIter, _FIter, _FIter, _BiPredicate, random_access_iterator_tag, _IterTag); template _IIter __find_first_of_switch(_IIter, _IIter, _FIter, _FIter, _BiPredicate, _IterTag1, _IterTag2); template _Function for_each(_IIter, _IIter, _Function); template _Function for_each(_IIter, _IIter, _Function, __gnu_parallel::sequential_tag); template _Function for_each(_Iterator, _Iterator, _Function, __gnu_parallel::_Parallelism); template _Function __for_each_switch(_IIter, _IIter, _Function, _IterTag); template _Function __for_each_switch(_RAIter, _RAIter, _Function, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template void generate(_FIter, _FIter, _Generator); template void generate(_FIter, _FIter, _Generator, __gnu_parallel::sequential_tag); template void generate(_FIter, _FIter, _Generator, __gnu_parallel::_Parallelism); template void __generate_switch(_FIter, _FIter, _Generator, _IterTag); template void __generate_switch(_RAIter, _RAIter, _Generator, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template _OIter generate_n(_OIter, _Size, _Generator); template _OIter generate_n(_OIter, _Size, _Generator, __gnu_parallel::sequential_tag); template _OIter generate_n(_OIter, _Size, _Generator, __gnu_parallel::_Parallelism); template _OIter __generate_n_switch(_OIter, _Size, _Generator, _IterTag); template _RAIter __generate_n_switch(_RAIter, _Size, _Generator, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2, __gnu_parallel::sequential_tag); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2, _Predicate, __gnu_parallel::sequential_tag); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2); template bool lexicographical_compare(_IIter1, _IIter1, _IIter2, _IIter2, _Predicate); template bool __lexicographical_compare_switch(_IIter1, _IIter1, _IIter2, _IIter2, _Predicate, _IterTag1, _IterTag2); template bool __lexicographical_compare_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, _Predicate, random_access_iterator_tag, random_access_iterator_tag); // algo.h template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2, __gnu_parallel::sequential_tag); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2, _Predicate, __gnu_parallel::sequential_tag); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2); template pair<_IIter1, _IIter2> mismatch(_IIter1, _IIter1, _IIter2, _Predicate); template pair<_IIter1, _IIter2> __mismatch_switch(_IIter1, _IIter1, _IIter2, _Predicate, _IterTag1, _IterTag2); template pair<_RAIter1, _RAIter2> __mismatch_switch(_RAIter1, _RAIter1, _RAIter2, _Predicate, random_access_iterator_tag, random_access_iterator_tag); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2, __gnu_parallel::sequential_tag); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2, _BiPredicate, __gnu_parallel::sequential_tag); template _FIter1 search(_FIter1, _FIter1, _FIter2, _FIter2, _BiPredicate); template _RAIter1 __search_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, random_access_iterator_tag, random_access_iterator_tag); template _FIter1 __search_switch(_FIter1, _FIter1, _FIter2, _FIter2, _IterTag1, _IterTag2); template _RAIter1 __search_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, _BiPredicate, random_access_iterator_tag, random_access_iterator_tag); template _FIter1 __search_switch(_FIter1, _FIter1, _FIter2, _FIter2, _BiPredicate, _IterTag1, _IterTag2); template _FIter search_n(_FIter, _FIter, _Integer, const _Tp&, __gnu_parallel::sequential_tag); template _FIter search_n(_FIter, _FIter, _Integer, const _Tp&, _BiPredicate, __gnu_parallel::sequential_tag); template _FIter search_n(_FIter, _FIter, _Integer, const _Tp&); template _FIter search_n(_FIter, _FIter, _Integer, const _Tp&, _BiPredicate); template _RAIter __search_n_switch(_RAIter, _RAIter, _Integer, const _Tp&, _BiPredicate, random_access_iterator_tag); template _FIter __search_n_switch(_FIter, _FIter, _Integer, const _Tp&, _BiPredicate, _IterTag); template _OIter transform(_IIter, _IIter, _OIter, _UnaryOperation); template _OIter transform(_IIter, _IIter, _OIter, _UnaryOperation, __gnu_parallel::sequential_tag); template _OIter transform(_IIter, _IIter, _OIter, _UnaryOperation, __gnu_parallel::_Parallelism); template _OIter __transform1_switch(_IIter, _IIter, _OIter, _UnaryOperation, _IterTag1, _IterTag2); template _RAOIter __transform1_switch(_RAIIter, _RAIIter, _RAOIter, _UnaryOperation, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template _OIter transform(_IIter1, _IIter1, _IIter2, _OIter, _BiOperation); template _OIter transform(_IIter1, _IIter1, _IIter2, _OIter, _BiOperation, __gnu_parallel::sequential_tag); template _OIter transform(_IIter1, _IIter1, _IIter2, _OIter, _BiOperation, __gnu_parallel::_Parallelism); template _RAIter3 __transform2_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter3, _BiOperation, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template _OIter __transform2_switch(_IIter1, _IIter1, _IIter2, _OIter, _BiOperation, _Tag1, _Tag2, _Tag3); template void replace(_FIter, _FIter, const _Tp&, const _Tp&); template void replace(_FIter, _FIter, const _Tp&, const _Tp&, __gnu_parallel::sequential_tag); template void replace(_FIter, _FIter, const _Tp&, const _Tp&, __gnu_parallel::_Parallelism); template void __replace_switch(_FIter, _FIter, const _Tp&, const _Tp&, _IterTag); template void __replace_switch(_RAIter, _RAIter, const _Tp&, const _Tp&, random_access_iterator_tag, __gnu_parallel::_Parallelism); template void replace_if(_FIter, _FIter, _Predicate, const _Tp&); template void replace_if(_FIter, _FIter, _Predicate, const _Tp&, __gnu_parallel::sequential_tag); template void replace_if(_FIter, _FIter, _Predicate, const _Tp&, __gnu_parallel::_Parallelism); template void __replace_if_switch(_FIter, _FIter, _Predicate, const _Tp&, _IterTag); template void __replace_if_switch(_RAIter, _RAIter, _Predicate, const _Tp&, random_access_iterator_tag, __gnu_parallel::_Parallelism); template _FIter max_element(_FIter, _FIter); template _FIter max_element(_FIter, _FIter, __gnu_parallel::sequential_tag); template _FIter max_element(_FIter, _FIter, __gnu_parallel::_Parallelism); template _FIter max_element(_FIter, _FIter, _Compare); template _FIter max_element(_FIter, _FIter, _Compare, __gnu_parallel::sequential_tag); template _FIter max_element(_FIter, _FIter, _Compare, __gnu_parallel::_Parallelism); template _FIter __max_element_switch(_FIter, _FIter, _Compare, _IterTag); template _RAIter __max_element_switch( _RAIter, _RAIter, _Compare, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, __gnu_parallel::sequential_tag); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare, __gnu_parallel::sequential_tag); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare); template _OIter merge(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter __merge_switch(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare, _IterTag1, _IterTag2, _IterTag3); template _OIter __merge_switch(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Compare, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag); template _FIter min_element(_FIter, _FIter); template _FIter min_element(_FIter, _FIter, __gnu_parallel::sequential_tag); template _FIter min_element(_FIter, _FIter, __gnu_parallel::_Parallelism __parallelism_tag); template _FIter min_element(_FIter, _FIter, _Compare); template _FIter min_element(_FIter, _FIter, _Compare, __gnu_parallel::sequential_tag); template _FIter min_element(_FIter, _FIter, _Compare, __gnu_parallel::_Parallelism); template _FIter __min_element_switch(_FIter, _FIter, _Compare, _IterTag); template _RAIter __min_element_switch( _RAIter, _RAIter, _Compare, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism = __gnu_parallel::parallel_balanced); template void nth_element(_RAIter, _RAIter, _RAIter, __gnu_parallel::sequential_tag); template void nth_element(_RAIter, _RAIter, _RAIter, _Compare, __gnu_parallel::sequential_tag); template void nth_element(_RAIter, _RAIter, _RAIter, _Compare); template void nth_element(_RAIter, _RAIter, _RAIter); template void partial_sort(_RAIter, _RAIter, _RAIter, _Compare, __gnu_parallel::sequential_tag); template void partial_sort(_RAIter, _RAIter, _RAIter, __gnu_parallel::sequential_tag); template void partial_sort(_RAIter, _RAIter, _RAIter, _Compare); template void partial_sort(_RAIter, _RAIter, _RAIter); template _FIter partition(_FIter, _FIter, _Predicate, __gnu_parallel::sequential_tag); template _FIter partition(_FIter, _FIter, _Predicate); template _FIter __partition_switch(_FIter, _FIter, _Predicate, _IterTag); template _RAIter __partition_switch( _RAIter, _RAIter, _Predicate, random_access_iterator_tag); template void random_shuffle(_RAIter, _RAIter, __gnu_parallel::sequential_tag); template void random_shuffle(_RAIter, _RAIter, _RandomNumberGenerator&, __gnu_parallel::sequential_tag); template void random_shuffle(_RAIter, _RAIter); template void random_shuffle(_RAIter, _RAIter, #if __cplusplus >= 201103L _RandomNumberGenerator&&); #else _RandomNumberGenerator&); #endif template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, __gnu_parallel::sequential_tag); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, __gnu_parallel::sequential_tag); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_union(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate); template _OIter __set_union_switch(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, _IterTag1, _IterTag2, _IterTag3); template _Output_RAIter __set_union_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, _Output_RAIter, _Predicate, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, __gnu_parallel::sequential_tag); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, __gnu_parallel::sequential_tag); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate); template _OIter __set_intersection_switch(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, _IterTag1, _IterTag2, _IterTag3); template _Output_RAIter __set_intersection_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, _Output_RAIter, _Predicate, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, __gnu_parallel::sequential_tag); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, __gnu_parallel::sequential_tag); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_symmetric_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate); template _OIter __set_symmetric_difference_switch(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, _IterTag1, _IterTag2, _IterTag3); template _Output_RAIter __set_symmetric_difference_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, _Output_RAIter, _Predicate, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, __gnu_parallel::sequential_tag); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, __gnu_parallel::sequential_tag); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter); template _OIter set_difference(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate); template _OIter __set_difference_switch(_IIter1, _IIter1, _IIter2, _IIter2, _OIter, _Predicate, _IterTag1, _IterTag2, _IterTag3); template _Output_RAIter __set_difference_switch(_RAIter1, _RAIter1, _RAIter2, _RAIter2, _Output_RAIter, _Predicate, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag); template void sort(_RAIter, _RAIter, __gnu_parallel::sequential_tag); template void sort(_RAIter, _RAIter, _Compare, __gnu_parallel::sequential_tag); template void sort(_RAIter, _RAIter); template void sort(_RAIter, _RAIter, _Compare); template void stable_sort(_RAIter, _RAIter, __gnu_parallel::sequential_tag); template void stable_sort(_RAIter, _RAIter, _Compare, __gnu_parallel::sequential_tag); template void stable_sort(_RAIter, _RAIter); template void stable_sort(_RAIter, _RAIter, _Compare); template _OIter unique_copy(_IIter, _IIter, _OIter, __gnu_parallel::sequential_tag); template _OIter unique_copy(_IIter, _IIter, _OIter, _Predicate, __gnu_parallel::sequential_tag); template _OIter unique_copy(_IIter, _IIter, _OIter); template _OIter unique_copy(_IIter, _IIter, _OIter, _Predicate); template _OIter __unique_copy_switch(_IIter, _IIter, _OIter, _Predicate, _IterTag1, _IterTag2); template _RandomAccess_OIter __unique_copy_switch(_RAIter, _RAIter, _RandomAccess_OIter, _Predicate, random_access_iterator_tag, random_access_iterator_tag); } // end namespace __parallel } // end namespace std #endif /* _GLIBCXX_PARALLEL_ALGORITHMFWD_H */ c++/8/parallel/search.h000064400000012417151027430570010506 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/search.h * @brief Parallel implementation base for std::search() and * std::search_n(). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_SEARCH_H #define _GLIBCXX_PARALLEL_SEARCH_H 1 #include #include #include namespace __gnu_parallel { /** * @brief Precalculate __advances for Knuth-Morris-Pratt algorithm. * @param __elements Begin iterator of sequence to search for. * @param __length Length of sequence to search for. * @param __off Returned __offsets. */ template void __calc_borders(_RAIter __elements, _DifferenceTp __length, _DifferenceTp* __off) { typedef _DifferenceTp _DifferenceType; __off[0] = -1; if (__length > 1) __off[1] = 0; _DifferenceType __k = 0; for (_DifferenceType __j = 2; __j <= __length; __j++) { while ((__k >= 0) && !(__elements[__k] == __elements[__j-1])) __k = __off[__k]; __off[__j] = ++__k; } } // Generic parallel find algorithm (requires random access iterator). /** @brief Parallel std::search. * @param __begin1 Begin iterator of first sequence. * @param __end1 End iterator of first sequence. * @param __begin2 Begin iterator of second sequence. * @param __end2 End iterator of second sequence. * @param __pred Find predicate. * @return Place of finding in first sequences. */ template __RAIter1 __search_template(__RAIter1 __begin1, __RAIter1 __end1, __RAIter2 __begin2, __RAIter2 __end2, _Pred __pred) { typedef std::iterator_traits<__RAIter1> _TraitsType; typedef typename _TraitsType::difference_type _DifferenceType; _GLIBCXX_CALL((__end1 - __begin1) + (__end2 - __begin2)); _DifferenceType __pattern_length = __end2 - __begin2; // Pattern too short. if(__pattern_length <= 0) return __end1; // Last point to start search. _DifferenceType __input_length = (__end1 - __begin1) - __pattern_length; // Where is first occurrence of pattern? defaults to end. _DifferenceType __result = (__end1 - __begin1); _DifferenceType *__splitters; // Pattern too long. if (__input_length < 0) return __end1; omp_lock_t __result_lock; omp_init_lock(&__result_lock); _ThreadIndex __num_threads = std::max<_DifferenceType> (1, std::min<_DifferenceType>(__input_length, __get_max_threads())); _DifferenceType __advances[__pattern_length]; __calc_borders(__begin2, __pattern_length, __advances); # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __splitters = new _DifferenceType[__num_threads + 1]; __equally_split(__input_length, __num_threads, __splitters); } _ThreadIndex __iam = omp_get_thread_num(); _DifferenceType __start = __splitters[__iam], __stop = __splitters[__iam + 1]; _DifferenceType __pos_in_pattern = 0; bool __found_pattern = false; while (__start <= __stop && !__found_pattern) { // Get new value of result. #pragma omp flush(__result) // No chance for this thread to find first occurrence. if (__result < __start) break; while (__pred(__begin1[__start + __pos_in_pattern], __begin2[__pos_in_pattern])) { ++__pos_in_pattern; if (__pos_in_pattern == __pattern_length) { // Found new candidate for result. omp_set_lock(&__result_lock); __result = std::min(__result, __start); omp_unset_lock(&__result_lock); __found_pattern = true; break; } } // Make safe jump. __start += (__pos_in_pattern - __advances[__pos_in_pattern]); __pos_in_pattern = (__advances[__pos_in_pattern] < 0 ? 0 : __advances[__pos_in_pattern]); } } //parallel omp_destroy_lock(&__result_lock); delete[] __splitters; // Return iterator on found element. return (__begin1 + __result); } } // end namespace #endif /* _GLIBCXX_PARALLEL_SEARCH_H */ c++/8/parallel/compiletime_settings.h000064400000005467151027430570013477 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/compiletime_settings.h * @brief Defines on options concerning debugging and performance, at * compile-time. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #include /** @brief Determine verbosity level of the parallel mode. * Level 1 prints a message each time a parallel-mode function is entered. */ #define _GLIBCXX_VERBOSE_LEVEL 0 /** @def _GLIBCXX_CALL * @brief Macro to produce log message when entering a function. * @param __n Input size. * @see _GLIBCXX_VERBOSE_LEVEL */ #if (_GLIBCXX_VERBOSE_LEVEL == 0) #define _GLIBCXX_CALL(__n) #endif #if (_GLIBCXX_VERBOSE_LEVEL == 1) #define _GLIBCXX_CALL(__n) \ printf(" %__s:\niam = %d, __n = %ld, __num_threads = %d\n", \ __PRETTY_FUNCTION__, omp_get_thread_num(), (__n), __get_max_threads()); #endif #ifndef _GLIBCXX_SCALE_DOWN_FPU /** @brief Use floating-point scaling instead of modulo for mapping * random numbers to a range. This can be faster on certain CPUs. */ #define _GLIBCXX_SCALE_DOWN_FPU 0 #endif #ifndef _GLIBCXX_PARALLEL_ASSERTIONS /** @brief Switch on many _GLIBCXX_PARALLEL_ASSERTions in parallel code. * Should be switched on only locally. */ #define _GLIBCXX_PARALLEL_ASSERTIONS (_GLIBCXX_ASSERTIONS+0) #endif #ifndef _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1 /** @brief Switch on many _GLIBCXX_PARALLEL_ASSERTions in parallel code. * Consider the size of the L1 cache for * gnu_parallel::__parallel_random_shuffle(). */ #define _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1 0 #endif #ifndef _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB /** @brief Switch on many _GLIBCXX_PARALLEL_ASSERTions in parallel code. * Consider the size of the TLB for * gnu_parallel::__parallel_random_shuffle(). */ #define _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB 0 #endif c++/8/parallel/algo.h000064400000234236151027430570010170 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file parallel/algo.h * @brief Parallel STL function calls corresponding to the stl_algo.h header. * * The functions defined here mainly do case switches and * call the actual parallelized versions in other files. * Inlining policy: Functions that basically only contain one function call, * are declared inline. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler and Felix Putze. #ifndef _GLIBCXX_PARALLEL_ALGO_H #define _GLIBCXX_PARALLEL_ALGO_H 1 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __parallel { // Sequential fallback template inline _Function for_each(_IIter __begin, _IIter __end, _Function __f, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::for_each(__begin, __end, __f); } // Sequential fallback for input iterator case template inline _Function __for_each_switch(_IIter __begin, _IIter __end, _Function __f, _IteratorTag) { return for_each(__begin, __end, __f, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators template _Function __for_each_switch(_RAIter __begin, _RAIter __end, _Function __f, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().for_each_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { bool __dummy; __gnu_parallel::__for_each_selector<_RAIter> __functionality; return __gnu_parallel:: __for_each_template_random_access( __begin, __end, __f, __functionality, __gnu_parallel::_DummyReduct(), true, __dummy, -1, __parallelism_tag); } else return for_each(__begin, __end, __f, __gnu_parallel::sequential_tag()); } // Public interface template inline _Function for_each(_Iterator __begin, _Iterator __end, _Function __f, __gnu_parallel::_Parallelism __parallelism_tag) { return __for_each_switch(__begin, __end, __f, std::__iterator_category(__begin), __parallelism_tag); } template inline _Function for_each(_Iterator __begin, _Iterator __end, _Function __f) { return __for_each_switch(__begin, __end, __f, std::__iterator_category(__begin)); } // Sequential fallback template inline _IIter find(_IIter __begin, _IIter __end, const _Tp& __val, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::find(__begin, __end, __val); } // Sequential fallback for input iterator case template inline _IIter __find_switch(_IIter __begin, _IIter __end, const _Tp& __val, _IteratorTag) { return _GLIBCXX_STD_A::find(__begin, __end, __val); } // Parallel find for random access iterators template _RAIter __find_switch(_RAIter __begin, _RAIter __end, const _Tp& __val, random_access_iterator_tag) { typedef iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; if (_GLIBCXX_PARALLEL_CONDITION(true)) { __gnu_parallel::__binder2nd<__gnu_parallel::_EqualTo<_ValueType, const _Tp&>, _ValueType, const _Tp&, bool> __comp(__gnu_parallel::_EqualTo<_ValueType, const _Tp&>(), __val); return __gnu_parallel::__find_template( __begin, __end, __begin, __comp, __gnu_parallel::__find_if_selector()).first; } else return _GLIBCXX_STD_A::find(__begin, __end, __val); } // Public interface template inline _IIter find(_IIter __begin, _IIter __end, const _Tp& __val) { return __find_switch(__begin, __end, __val, std::__iterator_category(__begin)); } // Sequential fallback template inline _IIter find_if(_IIter __begin, _IIter __end, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::find_if(__begin, __end, __pred); } // Sequential fallback for input iterator case template inline _IIter __find_if_switch(_IIter __begin, _IIter __end, _Predicate __pred, _IteratorTag) { return _GLIBCXX_STD_A::find_if(__begin, __end, __pred); } // Parallel find_if for random access iterators template _RAIter __find_if_switch(_RAIter __begin, _RAIter __end, _Predicate __pred, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION(true)) return __gnu_parallel::__find_template(__begin, __end, __begin, __pred, __gnu_parallel:: __find_if_selector()).first; else return _GLIBCXX_STD_A::find_if(__begin, __end, __pred); } // Public interface template inline _IIter find_if(_IIter __begin, _IIter __end, _Predicate __pred) { return __find_if_switch(__begin, __end, __pred, std::__iterator_category(__begin)); } // Sequential fallback template inline _IIter find_first_of(_IIter __begin1, _IIter __end1, _FIterator __begin2, _FIterator __end2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::find_first_of(__begin1, __end1, __begin2, __end2); } // Sequential fallback template inline _IIter find_first_of(_IIter __begin1, _IIter __end1, _FIterator __begin2, _FIterator __end2, _BinaryPredicate __comp, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::find_first_of( __begin1, __end1, __begin2, __end2, __comp); } // Sequential fallback for input iterator type template inline _IIter __find_first_of_switch(_IIter __begin1, _IIter __end1, _FIterator __begin2, _FIterator __end2, _IteratorTag1, _IteratorTag2) { return find_first_of(__begin1, __end1, __begin2, __end2, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators template inline _RAIter __find_first_of_switch(_RAIter __begin1, _RAIter __end1, _FIterator __begin2, _FIterator __end2, _BinaryPredicate __comp, random_access_iterator_tag, _IteratorTag) { return __gnu_parallel:: __find_template(__begin1, __end1, __begin1, __comp, __gnu_parallel::__find_first_of_selector <_FIterator>(__begin2, __end2)).first; } // Sequential fallback for input iterator type template inline _IIter __find_first_of_switch(_IIter __begin1, _IIter __end1, _FIterator __begin2, _FIterator __end2, _BinaryPredicate __comp, _IteratorTag1, _IteratorTag2) { return find_first_of(__begin1, __end1, __begin2, __end2, __comp, __gnu_parallel::sequential_tag()); } // Public interface template inline _IIter find_first_of(_IIter __begin1, _IIter __end1, _FIterator __begin2, _FIterator __end2, _BinaryPredicate __comp) { return __find_first_of_switch(__begin1, __end1, __begin2, __end2, __comp, std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } // Public interface, insert default comparator template inline _IIter find_first_of(_IIter __begin1, _IIter __end1, _FIterator __begin2, _FIterator __end2) { typedef typename std::iterator_traits<_IIter>::value_type _IValueType; typedef typename std::iterator_traits<_FIterator>::value_type _FValueType; return __gnu_parallel::find_first_of(__begin1, __end1, __begin2, __end2, __gnu_parallel::_EqualTo<_IValueType, _FValueType>()); } // Sequential fallback template inline _OutputIterator unique_copy(_IIter __begin1, _IIter __end1, _OutputIterator __out, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::unique_copy(__begin1, __end1, __out); } // Sequential fallback template inline _OutputIterator unique_copy(_IIter __begin1, _IIter __end1, _OutputIterator __out, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::unique_copy(__begin1, __end1, __out, __pred); } // Sequential fallback for input iterator case template inline _OutputIterator __unique_copy_switch(_IIter __begin, _IIter __last, _OutputIterator __out, _Predicate __pred, _IteratorTag1, _IteratorTag2) { return _GLIBCXX_STD_A::unique_copy(__begin, __last, __out, __pred); } // Parallel unique_copy for random access iterators template RandomAccessOutputIterator __unique_copy_switch(_RAIter __begin, _RAIter __last, RandomAccessOutputIterator __out, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__last - __begin) > __gnu_parallel::_Settings::get().unique_copy_minimal_n)) return __gnu_parallel::__parallel_unique_copy( __begin, __last, __out, __pred); else return _GLIBCXX_STD_A::unique_copy(__begin, __last, __out, __pred); } // Public interface template inline _OutputIterator unique_copy(_IIter __begin1, _IIter __end1, _OutputIterator __out) { typedef typename std::iterator_traits<_IIter>::value_type _ValueType; return __unique_copy_switch( __begin1, __end1, __out, equal_to<_ValueType>(), std::__iterator_category(__begin1), std::__iterator_category(__out)); } // Public interface template inline _OutputIterator unique_copy(_IIter __begin1, _IIter __end1, _OutputIterator __out, _Predicate __pred) { return __unique_copy_switch( __begin1, __end1, __out, __pred, std::__iterator_category(__begin1), std::__iterator_category(__out)); } // Sequential fallback template inline _OutputIterator set_union(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_union( __begin1, __end1, __begin2, __end2, __out); } // Sequential fallback template inline _OutputIterator set_union(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_union(__begin1, __end1, __begin2, __end2, __out, __pred); } // Sequential fallback for input iterator case template inline _OutputIterator __set_union_switch( _IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Predicate __pred, _IteratorTag1, _IteratorTag2, _IteratorTag3) { return _GLIBCXX_STD_A::set_union(__begin1, __end1, __begin2, __end2, __result, __pred); } // Parallel set_union for random access iterators template _Output_RAIter __set_union_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Output_RAIter __result, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().set_union_minimal_n || static_cast<__gnu_parallel::_SequenceIndex>(__end2 - __begin2) >= __gnu_parallel::_Settings::get().set_union_minimal_n)) return __gnu_parallel::__parallel_set_union( __begin1, __end1, __begin2, __end2, __result, __pred); else return _GLIBCXX_STD_A::set_union(__begin1, __end1, __begin2, __end2, __result, __pred); } // Public interface template inline _OutputIterator set_union(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out) { typedef typename std::iterator_traits<_IIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_IIter2>::value_type _ValueType2; return __set_union_switch( __begin1, __end1, __begin2, __end2, __out, __gnu_parallel::_Less<_ValueType1, _ValueType2>(), std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Public interface template inline _OutputIterator set_union(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred) { return __set_union_switch( __begin1, __end1, __begin2, __end2, __out, __pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Sequential fallback. template inline _OutputIterator set_intersection(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_intersection(__begin1, __end1, __begin2, __end2, __out); } // Sequential fallback. template inline _OutputIterator set_intersection(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_intersection( __begin1, __end1, __begin2, __end2, __out, __pred); } // Sequential fallback for input iterator case template inline _OutputIterator __set_intersection_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Predicate __pred, _IteratorTag1, _IteratorTag2, _IteratorTag3) { return _GLIBCXX_STD_A::set_intersection(__begin1, __end1, __begin2, __end2, __result, __pred); } // Parallel set_intersection for random access iterators template _Output_RAIter __set_intersection_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Output_RAIter __result, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().set_union_minimal_n || static_cast<__gnu_parallel::_SequenceIndex>(__end2 - __begin2) >= __gnu_parallel::_Settings::get().set_union_minimal_n)) return __gnu_parallel::__parallel_set_intersection( __begin1, __end1, __begin2, __end2, __result, __pred); else return _GLIBCXX_STD_A::set_intersection( __begin1, __end1, __begin2, __end2, __result, __pred); } // Public interface template inline _OutputIterator set_intersection(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out) { typedef typename std::iterator_traits<_IIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_IIter2>::value_type _ValueType2; return __set_intersection_switch( __begin1, __end1, __begin2, __end2, __out, __gnu_parallel::_Less<_ValueType1, _ValueType2>(), std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } template inline _OutputIterator set_intersection(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred) { return __set_intersection_switch( __begin1, __end1, __begin2, __end2, __out, __pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Sequential fallback template inline _OutputIterator set_symmetric_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_symmetric_difference( __begin1, __end1, __begin2, __end2, __out); } // Sequential fallback template inline _OutputIterator set_symmetric_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_symmetric_difference( __begin1, __end1, __begin2, __end2, __out, __pred); } // Sequential fallback for input iterator case template inline _OutputIterator __set_symmetric_difference_switch( _IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Predicate __pred, _IteratorTag1, _IteratorTag2, _IteratorTag3) { return _GLIBCXX_STD_A::set_symmetric_difference( __begin1, __end1, __begin2, __end2, __result, __pred); } // Parallel set_symmetric_difference for random access iterators template _Output_RAIter __set_symmetric_difference_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Output_RAIter __result, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().set_symmetric_difference_minimal_n || static_cast<__gnu_parallel::_SequenceIndex>(__end2 - __begin2) >= __gnu_parallel::_Settings::get().set_symmetric_difference_minimal_n)) return __gnu_parallel::__parallel_set_symmetric_difference( __begin1, __end1, __begin2, __end2, __result, __pred); else return _GLIBCXX_STD_A::set_symmetric_difference( __begin1, __end1, __begin2, __end2, __result, __pred); } // Public interface. template inline _OutputIterator set_symmetric_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out) { typedef typename std::iterator_traits<_IIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_IIter2>::value_type _ValueType2; return __set_symmetric_difference_switch( __begin1, __end1, __begin2, __end2, __out, __gnu_parallel::_Less<_ValueType1, _ValueType2>(), std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Public interface. template inline _OutputIterator set_symmetric_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred) { return __set_symmetric_difference_switch( __begin1, __end1, __begin2, __end2, __out, __pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Sequential fallback. template inline _OutputIterator set_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_difference( __begin1,__end1, __begin2, __end2, __out); } // Sequential fallback. template inline _OutputIterator set_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::set_difference(__begin1, __end1, __begin2, __end2, __out, __pred); } // Sequential fallback for input iterator case. template inline _OutputIterator __set_difference_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Predicate __pred, _IteratorTag1, _IteratorTag2, _IteratorTag3) { return _GLIBCXX_STD_A::set_difference( __begin1, __end1, __begin2, __end2, __result, __pred); } // Parallel set_difference for random access iterators template _Output_RAIter __set_difference_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _Output_RAIter __result, _Predicate __pred, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().set_difference_minimal_n || static_cast<__gnu_parallel::_SequenceIndex>(__end2 - __begin2) >= __gnu_parallel::_Settings::get().set_difference_minimal_n)) return __gnu_parallel::__parallel_set_difference( __begin1, __end1, __begin2, __end2, __result, __pred); else return _GLIBCXX_STD_A::set_difference( __begin1, __end1, __begin2, __end2, __result, __pred); } // Public interface template inline _OutputIterator set_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out) { typedef typename std::iterator_traits<_IIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_IIter2>::value_type _ValueType2; return __set_difference_switch( __begin1, __end1, __begin2, __end2, __out, __gnu_parallel::_Less<_ValueType1, _ValueType2>(), std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Public interface template inline _OutputIterator set_difference(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __out, _Predicate __pred) { return __set_difference_switch( __begin1, __end1, __begin2, __end2, __out, __pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__out)); } // Sequential fallback template inline _FIterator adjacent_find(_FIterator __begin, _FIterator __end, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::adjacent_find(__begin, __end); } // Sequential fallback template inline _FIterator adjacent_find(_FIterator __begin, _FIterator __end, _BinaryPredicate __binary_pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::adjacent_find(__begin, __end, __binary_pred); } // Parallel algorithm for random access iterators template _RAIter __adjacent_find_switch(_RAIter __begin, _RAIter __end, random_access_iterator_tag) { typedef iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; if (_GLIBCXX_PARALLEL_CONDITION(true)) { _RAIter __spot = __gnu_parallel:: __find_template( __begin, __end - 1, __begin, equal_to<_ValueType>(), __gnu_parallel::__adjacent_find_selector()) .first; if (__spot == (__end - 1)) return __end; else return __spot; } else return adjacent_find(__begin, __end, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case template inline _FIterator __adjacent_find_switch(_FIterator __begin, _FIterator __end, _IteratorTag) { return adjacent_find(__begin, __end, __gnu_parallel::sequential_tag()); } // Public interface template inline _FIterator adjacent_find(_FIterator __begin, _FIterator __end) { return __adjacent_find_switch(__begin, __end, std::__iterator_category(__begin)); } // Sequential fallback for input iterator case template inline _FIterator __adjacent_find_switch(_FIterator __begin, _FIterator __end, _BinaryPredicate __pred, _IteratorTag) { return adjacent_find(__begin, __end, __pred, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators template _RAIter __adjacent_find_switch(_RAIter __begin, _RAIter __end, _BinaryPredicate __pred, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION(true)) return __gnu_parallel::__find_template(__begin, __end, __begin, __pred, __gnu_parallel:: __adjacent_find_selector()).first; else return adjacent_find(__begin, __end, __pred, __gnu_parallel::sequential_tag()); } // Public interface template inline _FIterator adjacent_find(_FIterator __begin, _FIterator __end, _BinaryPredicate __pred) { return __adjacent_find_switch(__begin, __end, __pred, std::__iterator_category(__begin)); } // Sequential fallback template inline typename iterator_traits<_IIter>::difference_type count(_IIter __begin, _IIter __end, const _Tp& __value, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::count(__begin, __end, __value); } // Parallel code for random access iterators template typename iterator_traits<_RAIter>::difference_type __count_switch(_RAIter __begin, _RAIter __end, const _Tp& __value, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; typedef __gnu_parallel::_SequenceIndex _SequenceIndex; if (_GLIBCXX_PARALLEL_CONDITION( static_cast<_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().count_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { __gnu_parallel::__count_selector<_RAIter, _DifferenceType> __functionality; _DifferenceType __res = 0; __gnu_parallel:: __for_each_template_random_access( __begin, __end, __value, __functionality, std::plus<_SequenceIndex>(), __res, __res, -1, __parallelism_tag); return __res; } else return count(__begin, __end, __value, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case. template inline typename iterator_traits<_IIter>::difference_type __count_switch(_IIter __begin, _IIter __end, const _Tp& __value, _IteratorTag) { return count(__begin, __end, __value, __gnu_parallel::sequential_tag()); } // Public interface. template inline typename iterator_traits<_IIter>::difference_type count(_IIter __begin, _IIter __end, const _Tp& __value, __gnu_parallel::_Parallelism __parallelism_tag) { return __count_switch(__begin, __end, __value, std::__iterator_category(__begin), __parallelism_tag); } template inline typename iterator_traits<_IIter>::difference_type count(_IIter __begin, _IIter __end, const _Tp& __value) { return __count_switch(__begin, __end, __value, std::__iterator_category(__begin)); } // Sequential fallback. template inline typename iterator_traits<_IIter>::difference_type count_if(_IIter __begin, _IIter __end, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::count_if(__begin, __end, __pred); } // Parallel count_if for random access iterators template typename iterator_traits<_RAIter>::difference_type __count_if_switch(_RAIter __begin, _RAIter __end, _Predicate __pred, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { typedef iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; typedef __gnu_parallel::_SequenceIndex _SequenceIndex; if (_GLIBCXX_PARALLEL_CONDITION( static_cast<_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().count_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { _DifferenceType __res = 0; __gnu_parallel:: __count_if_selector<_RAIter, _DifferenceType> __functionality; __gnu_parallel:: __for_each_template_random_access( __begin, __end, __pred, __functionality, std::plus<_SequenceIndex>(), __res, __res, -1, __parallelism_tag); return __res; } else return count_if(__begin, __end, __pred, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case. template inline typename iterator_traits<_IIter>::difference_type __count_if_switch(_IIter __begin, _IIter __end, _Predicate __pred, _IteratorTag) { return count_if(__begin, __end, __pred, __gnu_parallel::sequential_tag()); } // Public interface. template inline typename iterator_traits<_IIter>::difference_type count_if(_IIter __begin, _IIter __end, _Predicate __pred, __gnu_parallel::_Parallelism __parallelism_tag) { return __count_if_switch(__begin, __end, __pred, std::__iterator_category(__begin), __parallelism_tag); } template inline typename iterator_traits<_IIter>::difference_type count_if(_IIter __begin, _IIter __end, _Predicate __pred) { return __count_if_switch(__begin, __end, __pred, std::__iterator_category(__begin)); } // Sequential fallback. template inline _FIterator1 search(_FIterator1 __begin1, _FIterator1 __end1, _FIterator2 __begin2, _FIterator2 __end2, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::search(__begin1, __end1, __begin2, __end2); } // Parallel algorithm for random access iterator template _RAIter1 __search_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, random_access_iterator_tag, random_access_iterator_tag) { typedef typename std::iterator_traits<_RAIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_RAIter2>::value_type _ValueType2; if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().search_minimal_n)) return __gnu_parallel:: __search_template( __begin1, __end1, __begin2, __end2, __gnu_parallel::_EqualTo<_ValueType1, _ValueType2>()); else return search(__begin1, __end1, __begin2, __end2, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case template inline _FIterator1 __search_switch(_FIterator1 __begin1, _FIterator1 __end1, _FIterator2 __begin2, _FIterator2 __end2, _IteratorTag1, _IteratorTag2) { return search(__begin1, __end1, __begin2, __end2, __gnu_parallel::sequential_tag()); } // Public interface. template inline _FIterator1 search(_FIterator1 __begin1, _FIterator1 __end1, _FIterator2 __begin2, _FIterator2 __end2) { return __search_switch(__begin1, __end1, __begin2, __end2, std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } // Public interface. template inline _FIterator1 search(_FIterator1 __begin1, _FIterator1 __end1, _FIterator2 __begin2, _FIterator2 __end2, _BinaryPredicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::search( __begin1, __end1, __begin2, __end2, __pred); } // Parallel algorithm for random access iterator. template _RAIter1 __search_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter2 __end2, _BinaryPredicate __pred, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().search_minimal_n)) return __gnu_parallel::__search_template(__begin1, __end1, __begin2, __end2, __pred); else return search(__begin1, __end1, __begin2, __end2, __pred, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case template inline _FIterator1 __search_switch(_FIterator1 __begin1, _FIterator1 __end1, _FIterator2 __begin2, _FIterator2 __end2, _BinaryPredicate __pred, _IteratorTag1, _IteratorTag2) { return search(__begin1, __end1, __begin2, __end2, __pred, __gnu_parallel::sequential_tag()); } // Public interface template inline _FIterator1 search(_FIterator1 __begin1, _FIterator1 __end1, _FIterator2 __begin2, _FIterator2 __end2, _BinaryPredicate __pred) { return __search_switch(__begin1, __end1, __begin2, __end2, __pred, std::__iterator_category(__begin1), std::__iterator_category(__begin2)); } // Sequential fallback template inline _FIterator search_n(_FIterator __begin, _FIterator __end, _Integer __count, const _Tp& __val, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::search_n(__begin, __end, __count, __val); } // Sequential fallback template inline _FIterator search_n(_FIterator __begin, _FIterator __end, _Integer __count, const _Tp& __val, _BinaryPredicate __binary_pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::search_n( __begin, __end, __count, __val, __binary_pred); } // Public interface. template inline _FIterator search_n(_FIterator __begin, _FIterator __end, _Integer __count, const _Tp& __val) { typedef typename iterator_traits<_FIterator>::value_type _ValueType; return __gnu_parallel::search_n(__begin, __end, __count, __val, __gnu_parallel::_EqualTo<_ValueType, _Tp>()); } // Parallel algorithm for random access iterators. template _RAIter __search_n_switch(_RAIter __begin, _RAIter __end, _Integer __count, const _Tp& __val, _BinaryPredicate __binary_pred, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().search_minimal_n)) { __gnu_parallel::_PseudoSequence<_Tp, _Integer> __ps(__val, __count); return __gnu_parallel::__search_template( __begin, __end, __ps.begin(), __ps.end(), __binary_pred); } else return _GLIBCXX_STD_A::search_n(__begin, __end, __count, __val, __binary_pred); } // Sequential fallback for input iterator case. template inline _FIterator __search_n_switch(_FIterator __begin, _FIterator __end, _Integer __count, const _Tp& __val, _BinaryPredicate __binary_pred, _IteratorTag) { return _GLIBCXX_STD_A::search_n(__begin, __end, __count, __val, __binary_pred); } // Public interface. template inline _FIterator search_n(_FIterator __begin, _FIterator __end, _Integer __count, const _Tp& __val, _BinaryPredicate __binary_pred) { return __search_n_switch(__begin, __end, __count, __val, __binary_pred, std::__iterator_category(__begin)); } // Sequential fallback. template inline _OutputIterator transform(_IIter __begin, _IIter __end, _OutputIterator __result, _UnaryOperation __unary_op, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::transform(__begin, __end, __result, __unary_op); } // Parallel unary transform for random access iterators. template _RAIter2 __transform1_switch(_RAIter1 __begin, _RAIter1 __end, _RAIter2 __result, _UnaryOperation __unary_op, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().transform_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { bool __dummy = true; typedef __gnu_parallel::_IteratorPair<_RAIter1, _RAIter2, random_access_iterator_tag> _ItTrip; _ItTrip __begin_pair(__begin, __result), __end_pair(__end, __result + (__end - __begin)); __gnu_parallel::__transform1_selector<_ItTrip> __functionality; __gnu_parallel:: __for_each_template_random_access( __begin_pair, __end_pair, __unary_op, __functionality, __gnu_parallel::_DummyReduct(), __dummy, __dummy, -1, __parallelism_tag); return __functionality._M_finish_iterator; } else return transform(__begin, __end, __result, __unary_op, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case. template inline _RAIter2 __transform1_switch(_RAIter1 __begin, _RAIter1 __end, _RAIter2 __result, _UnaryOperation __unary_op, _IteratorTag1, _IteratorTag2) { return transform(__begin, __end, __result, __unary_op, __gnu_parallel::sequential_tag()); } // Public interface. template inline _OutputIterator transform(_IIter __begin, _IIter __end, _OutputIterator __result, _UnaryOperation __unary_op, __gnu_parallel::_Parallelism __parallelism_tag) { return __transform1_switch(__begin, __end, __result, __unary_op, std::__iterator_category(__begin), std::__iterator_category(__result), __parallelism_tag); } template inline _OutputIterator transform(_IIter __begin, _IIter __end, _OutputIterator __result, _UnaryOperation __unary_op) { return __transform1_switch(__begin, __end, __result, __unary_op, std::__iterator_category(__begin), std::__iterator_category(__result)); } // Sequential fallback template inline _OutputIterator transform(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _OutputIterator __result, _BinaryOperation __binary_op, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::transform(__begin1, __end1, __begin2, __result, __binary_op); } // Parallel binary transform for random access iterators. template _RAIter3 __transform2_switch(_RAIter1 __begin1, _RAIter1 __end1, _RAIter2 __begin2, _RAIter3 __result, _BinaryOperation __binary_op, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( (__end1 - __begin1) >= __gnu_parallel::_Settings::get().transform_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { bool __dummy = true; typedef __gnu_parallel::_IteratorTriple<_RAIter1, _RAIter2, _RAIter3, random_access_iterator_tag> _ItTrip; _ItTrip __begin_triple(__begin1, __begin2, __result), __end_triple(__end1, __begin2 + (__end1 - __begin1), __result + (__end1 - __begin1)); __gnu_parallel::__transform2_selector<_ItTrip> __functionality; __gnu_parallel:: __for_each_template_random_access(__begin_triple, __end_triple, __binary_op, __functionality, __gnu_parallel::_DummyReduct(), __dummy, __dummy, -1, __parallelism_tag); return __functionality._M_finish_iterator; } else return transform(__begin1, __end1, __begin2, __result, __binary_op, __gnu_parallel::sequential_tag()); } // Sequential fallback for input iterator case. template inline _OutputIterator __transform2_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _OutputIterator __result, _BinaryOperation __binary_op, _Tag1, _Tag2, _Tag3) { return transform(__begin1, __end1, __begin2, __result, __binary_op, __gnu_parallel::sequential_tag()); } // Public interface. template inline _OutputIterator transform(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _OutputIterator __result, _BinaryOperation __binary_op, __gnu_parallel::_Parallelism __parallelism_tag) { return __transform2_switch( __begin1, __end1, __begin2, __result, __binary_op, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__result), __parallelism_tag); } template inline _OutputIterator transform(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _OutputIterator __result, _BinaryOperation __binary_op) { return __transform2_switch( __begin1, __end1, __begin2, __result, __binary_op, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__result)); } // Sequential fallback template inline void replace(_FIterator __begin, _FIterator __end, const _Tp& __old_value, const _Tp& __new_value, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::replace(__begin, __end, __old_value, __new_value); } // Sequential fallback for input iterator case template inline void __replace_switch(_FIterator __begin, _FIterator __end, const _Tp& __old_value, const _Tp& __new_value, _IteratorTag) { replace(__begin, __end, __old_value, __new_value, __gnu_parallel::sequential_tag()); } // Parallel replace for random access iterators template inline void __replace_switch(_RAIter __begin, _RAIter __end, const _Tp& __old_value, const _Tp& __new_value, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { // XXX parallel version is where? replace(__begin, __end, __old_value, __new_value, __gnu_parallel::sequential_tag()); } // Public interface template inline void replace(_FIterator __begin, _FIterator __end, const _Tp& __old_value, const _Tp& __new_value, __gnu_parallel::_Parallelism __parallelism_tag) { __replace_switch(__begin, __end, __old_value, __new_value, std::__iterator_category(__begin), __parallelism_tag); } template inline void replace(_FIterator __begin, _FIterator __end, const _Tp& __old_value, const _Tp& __new_value) { __replace_switch(__begin, __end, __old_value, __new_value, std::__iterator_category(__begin)); } // Sequential fallback template inline void replace_if(_FIterator __begin, _FIterator __end, _Predicate __pred, const _Tp& __new_value, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::replace_if(__begin, __end, __pred, __new_value); } // Sequential fallback for input iterator case template inline void __replace_if_switch(_FIterator __begin, _FIterator __end, _Predicate __pred, const _Tp& __new_value, _IteratorTag) { replace_if(__begin, __end, __pred, __new_value, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators. template void __replace_if_switch(_RAIter __begin, _RAIter __end, _Predicate __pred, const _Tp& __new_value, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().replace_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { bool __dummy; __gnu_parallel:: __replace_if_selector<_RAIter, _Predicate, _Tp> __functionality(__new_value); __gnu_parallel:: __for_each_template_random_access( __begin, __end, __pred, __functionality, __gnu_parallel::_DummyReduct(), true, __dummy, -1, __parallelism_tag); } else replace_if(__begin, __end, __pred, __new_value, __gnu_parallel::sequential_tag()); } // Public interface. template inline void replace_if(_FIterator __begin, _FIterator __end, _Predicate __pred, const _Tp& __new_value, __gnu_parallel::_Parallelism __parallelism_tag) { __replace_if_switch(__begin, __end, __pred, __new_value, std::__iterator_category(__begin), __parallelism_tag); } template inline void replace_if(_FIterator __begin, _FIterator __end, _Predicate __pred, const _Tp& __new_value) { __replace_if_switch(__begin, __end, __pred, __new_value, std::__iterator_category(__begin)); } // Sequential fallback template inline void generate(_FIterator __begin, _FIterator __end, _Generator __gen, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::generate(__begin, __end, __gen); } // Sequential fallback for input iterator case. template inline void __generate_switch(_FIterator __begin, _FIterator __end, _Generator __gen, _IteratorTag) { generate(__begin, __end, __gen, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators. template void __generate_switch(_RAIter __begin, _RAIter __end, _Generator __gen, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().generate_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { bool __dummy; __gnu_parallel::__generate_selector<_RAIter> __functionality; __gnu_parallel:: __for_each_template_random_access( __begin, __end, __gen, __functionality, __gnu_parallel::_DummyReduct(), true, __dummy, -1, __parallelism_tag); } else generate(__begin, __end, __gen, __gnu_parallel::sequential_tag()); } // Public interface. template inline void generate(_FIterator __begin, _FIterator __end, _Generator __gen, __gnu_parallel::_Parallelism __parallelism_tag) { __generate_switch(__begin, __end, __gen, std::__iterator_category(__begin), __parallelism_tag); } template inline void generate(_FIterator __begin, _FIterator __end, _Generator __gen) { __generate_switch(__begin, __end, __gen, std::__iterator_category(__begin)); } // Sequential fallback. template inline _OutputIterator generate_n(_OutputIterator __begin, _Size __n, _Generator __gen, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::generate_n(__begin, __n, __gen); } // Sequential fallback for input iterator case. template inline _OutputIterator __generate_n_switch(_OutputIterator __begin, _Size __n, _Generator __gen, _IteratorTag) { return generate_n(__begin, __n, __gen, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators. template inline _RAIter __generate_n_switch(_RAIter __begin, _Size __n, _Generator __gen, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { // XXX parallel version is where? return generate_n(__begin, __n, __gen, __gnu_parallel::sequential_tag()); } // Public interface. template inline _OutputIterator generate_n(_OutputIterator __begin, _Size __n, _Generator __gen, __gnu_parallel::_Parallelism __parallelism_tag) { return __generate_n_switch(__begin, __n, __gen, std::__iterator_category(__begin), __parallelism_tag); } template inline _OutputIterator generate_n(_OutputIterator __begin, _Size __n, _Generator __gen) { return __generate_n_switch(__begin, __n, __gen, std::__iterator_category(__begin)); } // Sequential fallback. template inline void random_shuffle(_RAIter __begin, _RAIter __end, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::random_shuffle(__begin, __end); } // Sequential fallback. template inline void random_shuffle(_RAIter __begin, _RAIter __end, _RandomNumberGenerator& __rand, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::random_shuffle(__begin, __end, __rand); } /** @brief Functor wrapper for std::rand(). */ template struct _CRandNumber { int operator()(int __limit) { return rand() % __limit; } }; // Fill in random number generator. template inline void random_shuffle(_RAIter __begin, _RAIter __end) { _CRandNumber<> __r; // Parallelization still possible. __gnu_parallel::random_shuffle(__begin, __end, __r); } // Parallel algorithm for random access iterators. template void random_shuffle(_RAIter __begin, _RAIter __end, #if __cplusplus >= 201103L _RandomNumberGenerator&& __rand) #else _RandomNumberGenerator& __rand) #endif { if (__begin == __end) return; if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().random_shuffle_minimal_n)) __gnu_parallel::__parallel_random_shuffle(__begin, __end, __rand); else __gnu_parallel::__sequential_random_shuffle(__begin, __end, __rand); } // Sequential fallback. template inline _FIterator partition(_FIterator __begin, _FIterator __end, _Predicate __pred, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::partition(__begin, __end, __pred); } // Sequential fallback for input iterator case. template inline _FIterator __partition_switch(_FIterator __begin, _FIterator __end, _Predicate __pred, _IteratorTag) { return partition(__begin, __end, __pred, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators. template _RAIter __partition_switch(_RAIter __begin, _RAIter __end, _Predicate __pred, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().partition_minimal_n)) { typedef typename std::iterator_traits<_RAIter>:: difference_type _DifferenceType; _DifferenceType __middle = __gnu_parallel:: __parallel_partition(__begin, __end, __pred, __gnu_parallel::__get_max_threads()); return __begin + __middle; } else return partition(__begin, __end, __pred, __gnu_parallel::sequential_tag()); } // Public interface. template inline _FIterator partition(_FIterator __begin, _FIterator __end, _Predicate __pred) { return __partition_switch(__begin, __end, __pred, std::__iterator_category(__begin)); } // sort interface // Sequential fallback template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::sort(__begin, __end); } // Sequential fallback template inline void sort(_RAIter __begin, _RAIter __end, _Compare __comp, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::sort<_RAIter, _Compare>(__begin, __end, __comp); } // Public interface template void sort(_RAIter __begin, _RAIter __end, _Compare __comp, _Parallelism __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; if (__begin != __end) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().sort_minimal_n)) __gnu_parallel::__parallel_sort( __begin, __end, __comp, __parallelism); else sort(__begin, __end, __comp, __gnu_parallel::sequential_tag()); } } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __gnu_parallel::default_parallel_tag()); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::default_parallel_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::parallel_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::multiway_mergesort_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::multiway_mergesort_sampling_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::multiway_mergesort_exact_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::quicksort_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void sort(_RAIter __begin, _RAIter __end, __gnu_parallel::balanced_quicksort_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface template void sort(_RAIter __begin, _RAIter __end, _Compare __comp) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; sort(__begin, __end, __comp, __gnu_parallel::default_parallel_tag()); } // stable_sort interface // Sequential fallback template inline void stable_sort(_RAIter __begin, _RAIter __end, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::stable_sort(__begin, __end); } // Sequential fallback template inline void stable_sort(_RAIter __begin, _RAIter __end, _Compare __comp, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::stable_sort<_RAIter, _Compare>(__begin, __end, __comp); } // Public interface template void stable_sort(_RAIter __begin, _RAIter __end, _Compare __comp, _Parallelism __parallelism) { typedef iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; if (__begin != __end) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().sort_minimal_n)) __gnu_parallel::__parallel_sort(__begin, __end, __comp, __parallelism); else stable_sort(__begin, __end, __comp, __gnu_parallel::sequential_tag()); } } // Public interface, insert default comparator template inline void stable_sort(_RAIter __begin, _RAIter __end) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; stable_sort(__begin, __end, std::less<_ValueType>(), __gnu_parallel::default_parallel_tag()); } // Public interface, insert default comparator template inline void stable_sort(_RAIter __begin, _RAIter __end, __gnu_parallel::default_parallel_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; stable_sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void stable_sort(_RAIter __begin, _RAIter __end, __gnu_parallel::parallel_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; stable_sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void stable_sort(_RAIter __begin, _RAIter __end, __gnu_parallel::multiway_mergesort_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; stable_sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void stable_sort(_RAIter __begin, _RAIter __end, __gnu_parallel::quicksort_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; stable_sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface, insert default comparator template inline void stable_sort(_RAIter __begin, _RAIter __end, __gnu_parallel::balanced_quicksort_tag __parallelism) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; stable_sort(__begin, __end, std::less<_ValueType>(), __parallelism); } // Public interface template void stable_sort(_RAIter __begin, _RAIter __end, _Compare __comp) { stable_sort( __begin, __end, __comp, __gnu_parallel::default_parallel_tag()); } // Sequential fallback template inline _OutputIterator merge(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::merge( __begin1, __end1, __begin2, __end2, __result); } // Sequential fallback template inline _OutputIterator merge(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Compare __comp, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::merge( __begin1, __end1, __begin2, __end2, __result, __comp); } // Sequential fallback for input iterator case template inline _OutputIterator __merge_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Compare __comp, _IteratorTag1, _IteratorTag2, _IteratorTag3) { return _GLIBCXX_STD_A::merge(__begin1, __end1, __begin2, __end2, __result, __comp); } // Parallel algorithm for random access iterators template _OutputIterator __merge_switch(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Compare __comp, random_access_iterator_tag, random_access_iterator_tag, random_access_iterator_tag) { if (_GLIBCXX_PARALLEL_CONDITION( (static_cast<__gnu_parallel::_SequenceIndex>(__end1 - __begin1) >= __gnu_parallel::_Settings::get().merge_minimal_n || static_cast<__gnu_parallel::_SequenceIndex>(__end2 - __begin2) >= __gnu_parallel::_Settings::get().merge_minimal_n))) return __gnu_parallel::__parallel_merge_advance( __begin1, __end1, __begin2, __end2, __result, (__end1 - __begin1) + (__end2 - __begin2), __comp); else return __gnu_parallel::__merge_advance( __begin1, __end1, __begin2, __end2, __result, (__end1 - __begin1) + (__end2 - __begin2), __comp); } // Public interface template inline _OutputIterator merge(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result, _Compare __comp) { return __merge_switch( __begin1, __end1, __begin2, __end2, __result, __comp, std::__iterator_category(__begin1), std::__iterator_category(__begin2), std::__iterator_category(__result)); } // Public interface, insert default comparator template inline _OutputIterator merge(_IIter1 __begin1, _IIter1 __end1, _IIter2 __begin2, _IIter2 __end2, _OutputIterator __result) { typedef typename std::iterator_traits<_IIter1>::value_type _ValueType1; typedef typename std::iterator_traits<_IIter2>::value_type _ValueType2; return __gnu_parallel::merge(__begin1, __end1, __begin2, __end2, __result, __gnu_parallel::_Less<_ValueType1, _ValueType2>()); } // Sequential fallback template inline void nth_element(_RAIter __begin, _RAIter __nth, _RAIter __end, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::nth_element(__begin, __nth, __end); } // Sequential fallback template inline void nth_element(_RAIter __begin, _RAIter __nth, _RAIter __end, _Compare __comp, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::nth_element(__begin, __nth, __end, __comp); } // Public interface template inline void nth_element(_RAIter __begin, _RAIter __nth, _RAIter __end, _Compare __comp) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().nth_element_minimal_n)) __gnu_parallel::__parallel_nth_element(__begin, __nth, __end, __comp); else nth_element(__begin, __nth, __end, __comp, __gnu_parallel::sequential_tag()); } // Public interface, insert default comparator template inline void nth_element(_RAIter __begin, _RAIter __nth, _RAIter __end) { typedef typename iterator_traits<_RAIter>::value_type _ValueType; __gnu_parallel::nth_element(__begin, __nth, __end, std::less<_ValueType>()); } // Sequential fallback template inline void partial_sort(_RAIter __begin, _RAIter __middle, _RAIter __end, _Compare __comp, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::partial_sort(__begin, __middle, __end, __comp); } // Sequential fallback template inline void partial_sort(_RAIter __begin, _RAIter __middle, _RAIter __end, __gnu_parallel::sequential_tag) { _GLIBCXX_STD_A::partial_sort(__begin, __middle, __end); } // Public interface, parallel algorithm for random access iterators template void partial_sort(_RAIter __begin, _RAIter __middle, _RAIter __end, _Compare __comp) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().partial_sort_minimal_n)) __gnu_parallel:: __parallel_partial_sort(__begin, __middle, __end, __comp); else partial_sort(__begin, __middle, __end, __comp, __gnu_parallel::sequential_tag()); } // Public interface, insert default comparator template inline void partial_sort(_RAIter __begin, _RAIter __middle, _RAIter __end) { typedef iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; __gnu_parallel::partial_sort(__begin, __middle, __end, std::less<_ValueType>()); } // Sequential fallback template inline _FIterator max_element(_FIterator __begin, _FIterator __end, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::max_element(__begin, __end); } // Sequential fallback template inline _FIterator max_element(_FIterator __begin, _FIterator __end, _Compare __comp, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::max_element(__begin, __end, __comp); } // Sequential fallback for input iterator case template inline _FIterator __max_element_switch(_FIterator __begin, _FIterator __end, _Compare __comp, _IteratorTag) { return max_element(__begin, __end, __comp, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators template _RAIter __max_element_switch(_RAIter __begin, _RAIter __end, _Compare __comp, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().max_element_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { _RAIter __res(__begin); __gnu_parallel::__identity_selector<_RAIter> __functionality; __gnu_parallel:: __for_each_template_random_access( __begin, __end, __gnu_parallel::_Nothing(), __functionality, __gnu_parallel::__max_element_reduct<_Compare, _RAIter>(__comp), __res, __res, -1, __parallelism_tag); return __res; } else return max_element(__begin, __end, __comp, __gnu_parallel::sequential_tag()); } // Public interface, insert default comparator template inline _FIterator max_element(_FIterator __begin, _FIterator __end, __gnu_parallel::_Parallelism __parallelism_tag) { typedef typename iterator_traits<_FIterator>::value_type _ValueType; return max_element(__begin, __end, std::less<_ValueType>(), __parallelism_tag); } template inline _FIterator max_element(_FIterator __begin, _FIterator __end) { typedef typename iterator_traits<_FIterator>::value_type _ValueType; return __gnu_parallel::max_element(__begin, __end, std::less<_ValueType>()); } // Public interface template inline _FIterator max_element(_FIterator __begin, _FIterator __end, _Compare __comp, __gnu_parallel::_Parallelism __parallelism_tag) { return __max_element_switch(__begin, __end, __comp, std::__iterator_category(__begin), __parallelism_tag); } template inline _FIterator max_element(_FIterator __begin, _FIterator __end, _Compare __comp) { return __max_element_switch(__begin, __end, __comp, std::__iterator_category(__begin)); } // Sequential fallback template inline _FIterator min_element(_FIterator __begin, _FIterator __end, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::min_element(__begin, __end); } // Sequential fallback template inline _FIterator min_element(_FIterator __begin, _FIterator __end, _Compare __comp, __gnu_parallel::sequential_tag) { return _GLIBCXX_STD_A::min_element(__begin, __end, __comp); } // Sequential fallback for input iterator case template inline _FIterator __min_element_switch(_FIterator __begin, _FIterator __end, _Compare __comp, _IteratorTag) { return min_element(__begin, __end, __comp, __gnu_parallel::sequential_tag()); } // Parallel algorithm for random access iterators template _RAIter __min_element_switch(_RAIter __begin, _RAIter __end, _Compare __comp, random_access_iterator_tag, __gnu_parallel::_Parallelism __parallelism_tag) { if (_GLIBCXX_PARALLEL_CONDITION( static_cast<__gnu_parallel::_SequenceIndex>(__end - __begin) >= __gnu_parallel::_Settings::get().min_element_minimal_n && __gnu_parallel::__is_parallel(__parallelism_tag))) { _RAIter __res(__begin); __gnu_parallel::__identity_selector<_RAIter> __functionality; __gnu_parallel:: __for_each_template_random_access( __begin, __end, __gnu_parallel::_Nothing(), __functionality, __gnu_parallel::__min_element_reduct<_Compare, _RAIter>(__comp), __res, __res, -1, __parallelism_tag); return __res; } else return min_element(__begin, __end, __comp, __gnu_parallel::sequential_tag()); } // Public interface, insert default comparator template inline _FIterator min_element(_FIterator __begin, _FIterator __end, __gnu_parallel::_Parallelism __parallelism_tag) { typedef typename iterator_traits<_FIterator>::value_type _ValueType; return min_element(__begin, __end, std::less<_ValueType>(), __parallelism_tag); } template inline _FIterator min_element(_FIterator __begin, _FIterator __end) { typedef typename iterator_traits<_FIterator>::value_type _ValueType; return __gnu_parallel::min_element(__begin, __end, std::less<_ValueType>()); } // Public interface template inline _FIterator min_element(_FIterator __begin, _FIterator __end, _Compare __comp, __gnu_parallel::_Parallelism __parallelism_tag) { return __min_element_switch(__begin, __end, __comp, std::__iterator_category(__begin), __parallelism_tag); } template inline _FIterator min_element(_FIterator __begin, _FIterator __end, _Compare __comp) { return __min_element_switch(__begin, __end, __comp, std::__iterator_category(__begin)); } } // end namespace } // end namespace #endif /* _GLIBCXX_PARALLEL_ALGO_H */ c++/8/cassert000064400000003160151027430570006656 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file cassert * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c assert.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 19.2 Assertions // // No include guards on this header... #pragma GCC system_header #include #include c++/8/cstring000064400000006063151027430570006670 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file cstring * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c string.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CSTRING #define _GLIBCXX_CSTRING 1 // Get rid of those macros defined in in lieu of real functions. #undef memchr #undef memcmp #undef memcpy #undef memmove #undef memset #undef strcat #undef strchr #undef strcmp #undef strcoll #undef strcpy #undef strcspn #undef strerror #undef strlen #undef strncat #undef strncmp #undef strncpy #undef strpbrk #undef strrchr #undef strspn #undef strstr #undef strtok #undef strxfrm namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::memchr; using ::memcmp; using ::memcpy; using ::memmove; using ::memset; using ::strcat; using ::strcmp; using ::strcoll; using ::strcpy; using ::strcspn; using ::strerror; using ::strlen; using ::strncat; using ::strncmp; using ::strncpy; using ::strspn; using ::strtok; using ::strxfrm; using ::strchr; using ::strpbrk; using ::strrchr; using ::strstr; #ifndef __CORRECT_ISO_CPP_STRING_H_PROTO inline void* memchr(void* __s, int __c, size_t __n) { return __builtin_memchr(__s, __c, __n); } inline char* strchr(char* __s, int __n) { return __builtin_strchr(__s, __n); } inline char* strpbrk(char* __s1, const char* __s2) { return __builtin_strpbrk(__s1, __s2); } inline char* strrchr(char* __s, int __n) { return __builtin_strrchr(__s, __n); } inline char* strstr(char* __s1, const char* __s2) { return __builtin_strstr(__s1, __s2); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/ios000064400000003101151027430570005777 0ustar00// Iostreams base classes -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/ios * This is a Standard C++ Library header. */ // // ISO C++ 14882: 27.4 Iostreams base classes // #ifndef _GLIBCXX_IOS #define _GLIBCXX_IOS 1 #pragma GCC system_header #include #include // For ios_base::failure #include // For char_traits, streamoff, streamsize, fpos #include // For class locale #include // For ios_base declarations. #include #include #endif /* _GLIBCXX_IOS */ c++/8/cfloat000064400000003541151027430570006465 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cfloat * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c float.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 18.2.2 Implementation properties: C library // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CFLOAT #define _GLIBCXX_CFLOAT 1 #if __cplusplus >= 201103L # ifndef DECIMAL_DIG # define DECIMAL_DIG __DECIMAL_DIG__ # endif # ifndef FLT_EVAL_METHOD # define FLT_EVAL_METHOD __FLT_EVAL_METHOD__ # endif #endif #endif c++/8/functional000064400000111566151027430570007366 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ /** @file include/functional * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FUNCTIONAL #define _GLIBCXX_FUNCTIONAL 1 #pragma GCC system_header #include #include #if __cplusplus >= 201103L #include #include #include #include #include #include // std::reference_wrapper and _Mem_fn_traits #include // std::function #if __cplusplus > 201402L # include # include # include # include # include #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus > 201402L # define __cpp_lib_invoke 201411 /// Invoke a callable object. template inline invoke_result_t<_Callable, _Args...> invoke(_Callable&& __fn, _Args&&... __args) noexcept(is_nothrow_invocable_v<_Callable, _Args...>) { return std::__invoke(std::forward<_Callable>(__fn), std::forward<_Args>(__args)...); } #endif template::value> class _Mem_fn_base : public _Mem_fn_traits<_MemFunPtr>::__maybe_type { using _Traits = _Mem_fn_traits<_MemFunPtr>; using _Arity = typename _Traits::__arity; using _Varargs = typename _Traits::__vararg; template friend struct _Bind_check_arity; _MemFunPtr _M_pmf; public: using result_type = typename _Traits::__result_type; explicit constexpr _Mem_fn_base(_MemFunPtr __pmf) noexcept : _M_pmf(__pmf) { } template auto operator()(_Args&&... __args) const noexcept(noexcept( std::__invoke(_M_pmf, std::forward<_Args>(__args)...))) -> decltype(std::__invoke(_M_pmf, std::forward<_Args>(__args)...)) { return std::__invoke(_M_pmf, std::forward<_Args>(__args)...); } }; // Partial specialization for member object pointers. template class _Mem_fn_base<_MemObjPtr, false> { using _Arity = integral_constant; using _Varargs = false_type; template friend struct _Bind_check_arity; _MemObjPtr _M_pm; public: explicit constexpr _Mem_fn_base(_MemObjPtr __pm) noexcept : _M_pm(__pm) { } template auto operator()(_Tp&& __obj) const noexcept(noexcept(std::__invoke(_M_pm, std::forward<_Tp>(__obj)))) -> decltype(std::__invoke(_M_pm, std::forward<_Tp>(__obj))) { return std::__invoke(_M_pm, std::forward<_Tp>(__obj)); } }; template struct _Mem_fn; // undefined template struct _Mem_fn<_Res _Class::*> : _Mem_fn_base<_Res _Class::*> { using _Mem_fn_base<_Res _Class::*>::_Mem_fn_base; }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2048. Unnecessary mem_fn overloads /** * @brief Returns a function object that forwards to the member * pointer @a pm. * @ingroup functors */ template inline _Mem_fn<_Tp _Class::*> mem_fn(_Tp _Class::* __pm) noexcept { return _Mem_fn<_Tp _Class::*>(__pm); } /** * @brief Determines if the given type _Tp is a function object that * should be treated as a subexpression when evaluating calls to * function objects returned by bind(). * * C++11 [func.bind.isbind]. * @ingroup binders */ template struct is_bind_expression : public false_type { }; /** * @brief Determines if the given type _Tp is a placeholder in a * bind() expression and, if so, which placeholder it is. * * C++11 [func.bind.isplace]. * @ingroup binders */ template struct is_placeholder : public integral_constant { }; #if __cplusplus > 201402L template inline constexpr bool is_bind_expression_v = is_bind_expression<_Tp>::value; template inline constexpr int is_placeholder_v = is_placeholder<_Tp>::value; #endif // C++17 /** @brief The type of placeholder objects defined by libstdc++. * @ingroup binders */ template struct _Placeholder { }; /** @namespace std::placeholders * @brief ISO C++11 entities sub-namespace for functional. * @ingroup binders */ namespace placeholders { /* Define a large number of placeholders. There is no way to * simplify this with variadic templates, because we're introducing * unique names for each. */ extern const _Placeholder<1> _1; extern const _Placeholder<2> _2; extern const _Placeholder<3> _3; extern const _Placeholder<4> _4; extern const _Placeholder<5> _5; extern const _Placeholder<6> _6; extern const _Placeholder<7> _7; extern const _Placeholder<8> _8; extern const _Placeholder<9> _9; extern const _Placeholder<10> _10; extern const _Placeholder<11> _11; extern const _Placeholder<12> _12; extern const _Placeholder<13> _13; extern const _Placeholder<14> _14; extern const _Placeholder<15> _15; extern const _Placeholder<16> _16; extern const _Placeholder<17> _17; extern const _Placeholder<18> _18; extern const _Placeholder<19> _19; extern const _Placeholder<20> _20; extern const _Placeholder<21> _21; extern const _Placeholder<22> _22; extern const _Placeholder<23> _23; extern const _Placeholder<24> _24; extern const _Placeholder<25> _25; extern const _Placeholder<26> _26; extern const _Placeholder<27> _27; extern const _Placeholder<28> _28; extern const _Placeholder<29> _29; } /** * Partial specialization of is_placeholder that provides the placeholder * number for the placeholder objects defined by libstdc++. * @ingroup binders */ template struct is_placeholder<_Placeholder<_Num> > : public integral_constant { }; template struct is_placeholder > : public integral_constant { }; // Like tuple_element_t but SFINAE-friendly. template using _Safe_tuple_element_t = typename enable_if<(__i < tuple_size<_Tuple>::value), tuple_element<__i, _Tuple>>::type::type; /** * Maps an argument to bind() into an actual argument to the bound * function object [func.bind.bind]/10. Only the first parameter should * be specified: the rest are used to determine among the various * implementations. Note that, although this class is a function * object, it isn't entirely normal because it takes only two * parameters regardless of the number of parameters passed to the * bind expression. The first parameter is the bound argument and * the second parameter is a tuple containing references to the * rest of the arguments. */ template::value, bool _IsPlaceholder = (is_placeholder<_Arg>::value > 0)> class _Mu; /** * If the argument is reference_wrapper<_Tp>, returns the * underlying reference. * C++11 [func.bind.bind] p10 bullet 1. */ template class _Mu, false, false> { public: /* Note: This won't actually work for const volatile * reference_wrappers, because reference_wrapper::get() is const * but not volatile-qualified. This might be a defect in the TR. */ template _Tp& operator()(_CVRef& __arg, _Tuple&) const volatile { return __arg.get(); } }; /** * If the argument is a bind expression, we invoke the underlying * function object with the same cv-qualifiers as we are given and * pass along all of our arguments (unwrapped). * C++11 [func.bind.bind] p10 bullet 2. */ template class _Mu<_Arg, true, false> { public: template auto operator()(_CVArg& __arg, tuple<_Args...>& __tuple) const volatile -> decltype(__arg(declval<_Args>()...)) { // Construct an index tuple and forward to __call typedef typename _Build_index_tuple::__type _Indexes; return this->__call(__arg, __tuple, _Indexes()); } private: // Invokes the underlying function object __arg by unpacking all // of the arguments in the tuple. template auto __call(_CVArg& __arg, tuple<_Args...>& __tuple, const _Index_tuple<_Indexes...>&) const volatile -> decltype(__arg(declval<_Args>()...)) { return __arg(std::get<_Indexes>(std::move(__tuple))...); } }; /** * If the argument is a placeholder for the Nth argument, returns * a reference to the Nth argument to the bind function object. * C++11 [func.bind.bind] p10 bullet 3. */ template class _Mu<_Arg, false, true> { public: template _Safe_tuple_element_t<(is_placeholder<_Arg>::value - 1), _Tuple>&& operator()(const volatile _Arg&, _Tuple& __tuple) const volatile { return ::std::get<(is_placeholder<_Arg>::value - 1)>(std::move(__tuple)); } }; /** * If the argument is just a value, returns a reference to that * value. The cv-qualifiers on the reference are determined by the caller. * C++11 [func.bind.bind] p10 bullet 4. */ template class _Mu<_Arg, false, false> { public: template _CVArg&& operator()(_CVArg&& __arg, _Tuple&) const volatile { return std::forward<_CVArg>(__arg); } }; // std::get for volatile-qualified tuples template inline auto __volget(volatile tuple<_Tp...>& __tuple) -> __tuple_element_t<_Ind, tuple<_Tp...>> volatile& { return std::get<_Ind>(const_cast&>(__tuple)); } // std::get for const-volatile-qualified tuples template inline auto __volget(const volatile tuple<_Tp...>& __tuple) -> __tuple_element_t<_Ind, tuple<_Tp...>> const volatile& { return std::get<_Ind>(const_cast&>(__tuple)); } /// Type of the function object returned from bind(). template struct _Bind; template class _Bind<_Functor(_Bound_args...)> : public _Weak_result_type<_Functor> { typedef typename _Build_index_tuple::__type _Bound_indexes; _Functor _M_f; tuple<_Bound_args...> _M_bound_args; // Call unqualified template _Result __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) { return std::__invoke(_M_f, _Mu<_Bound_args>()(std::get<_Indexes>(_M_bound_args), __args)... ); } // Call as const template _Result __call_c(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const { return std::__invoke(_M_f, _Mu<_Bound_args>()(std::get<_Indexes>(_M_bound_args), __args)... ); } // Call as volatile template _Result __call_v(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) volatile { return std::__invoke(_M_f, _Mu<_Bound_args>()(__volget<_Indexes>(_M_bound_args), __args)... ); } // Call as const volatile template _Result __call_c_v(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const volatile { return std::__invoke(_M_f, _Mu<_Bound_args>()(__volget<_Indexes>(_M_bound_args), __args)... ); } template using _Mu_type = decltype( _Mu::type>()( std::declval<_BoundArg&>(), std::declval<_CallArgs&>()) ); template using _Res_type_impl = typename result_of< _Fn&(_Mu_type<_BArgs, _CallArgs>&&...) >::type; template using _Res_type = _Res_type_impl<_Functor, _CallArgs, _Bound_args...>; template using __dependent = typename enable_if::value+1), _Functor>::type; template class __cv_quals> using _Res_type_cv = _Res_type_impl< typename __cv_quals<__dependent<_CallArgs>>::type, _CallArgs, typename __cv_quals<_Bound_args>::type...>; public: template explicit _Bind(const _Functor& __f, _Args&&... __args) : _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...) { } template explicit _Bind(_Functor&& __f, _Args&&... __args) : _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...) { } _Bind(const _Bind&) = default; _Bind(_Bind&& __b) : _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args)) { } // Call unqualified template>> _Result operator()(_Args&&... __args) { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const template, add_const>> _Result operator()(_Args&&... __args) const { return this->__call_c<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } #if __cplusplus > 201402L # define _GLIBCXX_DEPR_BIND \ [[deprecated("std::bind does not support volatile in C++17")]] #else # define _GLIBCXX_DEPR_BIND #endif // Call as volatile template, add_volatile>> _GLIBCXX_DEPR_BIND _Result operator()(_Args&&... __args) volatile { return this->__call_v<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const volatile template, add_cv>> _GLIBCXX_DEPR_BIND _Result operator()(_Args&&... __args) const volatile { return this->__call_c_v<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } }; /// Type of the function object returned from bind(). template struct _Bind_result; template class _Bind_result<_Result, _Functor(_Bound_args...)> { typedef typename _Build_index_tuple::__type _Bound_indexes; _Functor _M_f; tuple<_Bound_args...> _M_bound_args; // sfinae types template using __enable_if_void = typename enable_if{}>::type; template using __disable_if_void = typename enable_if{}, _Result>::type; // Call unqualified template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) { return std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call unqualified, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) { std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call as const template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const { return std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call as const, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const { std::__invoke(_M_f, _Mu<_Bound_args>() (std::get<_Indexes>(_M_bound_args), __args)...); } // Call as volatile template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) volatile { return std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } // Call as volatile, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) volatile { std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } // Call as const volatile template __disable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const volatile { return std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } // Call as const volatile, return void template __enable_if_void<_Res> __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const volatile { std::__invoke(_M_f, _Mu<_Bound_args>() (__volget<_Indexes>(_M_bound_args), __args)...); } public: typedef _Result result_type; template explicit _Bind_result(const _Functor& __f, _Args&&... __args) : _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...) { } template explicit _Bind_result(_Functor&& __f, _Args&&... __args) : _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...) { } _Bind_result(const _Bind_result&) = default; _Bind_result(_Bind_result&& __b) : _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args)) { } // Call unqualified template result_type operator()(_Args&&... __args) { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const template result_type operator()(_Args&&... __args) const { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as volatile template _GLIBCXX_DEPR_BIND result_type operator()(_Args&&... __args) volatile { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } // Call as const volatile template _GLIBCXX_DEPR_BIND result_type operator()(_Args&&... __args) const volatile { return this->__call<_Result>( std::forward_as_tuple(std::forward<_Args>(__args)...), _Bound_indexes()); } }; #undef _GLIBCXX_DEPR_BIND /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression<_Bind<_Signature> > : public true_type { }; /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression > : public true_type { }; /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression > : public true_type { }; /** * @brief Class template _Bind is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression<_Bind_result<_Result, _Signature>> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; /** * @brief Class template _Bind_result is always a bind expression. * @ingroup binders */ template struct is_bind_expression> : public true_type { }; template struct _Bind_check_arity { }; template struct _Bind_check_arity<_Ret (*)(_Args...), _BoundArgs...> { static_assert(sizeof...(_BoundArgs) == sizeof...(_Args), "Wrong number of arguments for function"); }; template struct _Bind_check_arity<_Ret (*)(_Args......), _BoundArgs...> { static_assert(sizeof...(_BoundArgs) >= sizeof...(_Args), "Wrong number of arguments for function"); }; template struct _Bind_check_arity<_Tp _Class::*, _BoundArgs...> { using _Arity = typename _Mem_fn<_Tp _Class::*>::_Arity; using _Varargs = typename _Mem_fn<_Tp _Class::*>::_Varargs; static_assert(_Varargs::value ? sizeof...(_BoundArgs) >= _Arity::value + 1 : sizeof...(_BoundArgs) == _Arity::value + 1, "Wrong number of arguments for pointer-to-member"); }; // Trait type used to remove std::bind() from overload set via SFINAE // when first argument has integer type, so that std::bind() will // not be a better match than ::bind() from the BSD Sockets API. template::type> using __is_socketlike = __or_, is_enum<_Tp2>>; template struct _Bind_helper : _Bind_check_arity::type, _BoundArgs...> { typedef typename decay<_Func>::type __func_type; typedef _Bind<__func_type(typename decay<_BoundArgs>::type...)> type; }; // Partial specialization for is_socketlike == true, does not define // nested type so std::bind() will not participate in overload resolution // when the first argument might be a socket file descriptor. template struct _Bind_helper { }; /** * @brief Function template for std::bind. * @ingroup binders */ template inline typename _Bind_helper<__is_socketlike<_Func>::value, _Func, _BoundArgs...>::type bind(_Func&& __f, _BoundArgs&&... __args) { typedef _Bind_helper __helper_type; return typename __helper_type::type(std::forward<_Func>(__f), std::forward<_BoundArgs>(__args)...); } template struct _Bindres_helper : _Bind_check_arity::type, _BoundArgs...> { typedef typename decay<_Func>::type __functor_type; typedef _Bind_result<_Result, __functor_type(typename decay<_BoundArgs>::type...)> type; }; /** * @brief Function template for std::bind. * @ingroup binders */ template inline typename _Bindres_helper<_Result, _Func, _BoundArgs...>::type bind(_Func&& __f, _BoundArgs&&... __args) { typedef _Bindres_helper<_Result, _Func, _BoundArgs...> __helper_type; return typename __helper_type::type(std::forward<_Func>(__f), std::forward<_BoundArgs>(__args)...); } #if __cplusplus >= 201402L /// Generalized negator. template class _Not_fn { template using __inv_res_t = typename __invoke_result<_Fn2, _Args...>::type; template static decltype(!std::declval<_Tp>()) _S_not() noexcept(noexcept(!std::declval<_Tp>())); public: template _Not_fn(_Fn2&& __fn, int) : _M_fn(std::forward<_Fn2>(__fn)) { } _Not_fn(const _Not_fn& __fn) = default; _Not_fn(_Not_fn&& __fn) = default; ~_Not_fn() = default; // Macro to define operator() with given cv-qualifiers ref-qualifiers, // forwarding _M_fn and the function arguments with the same qualifiers, // and deducing the return type and exception-specification. #define _GLIBCXX_NOT_FN_CALL_OP( _QUALS ) \ template \ decltype(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>()) \ operator()(_Args&&... __args) _QUALS \ noexcept(__is_nothrow_invocable<_Fn _QUALS, _Args...>::value \ && noexcept(_S_not<__inv_res_t<_Fn _QUALS, _Args...>>())) \ { \ return !std::__invoke(std::forward< _Fn _QUALS >(_M_fn), \ std::forward<_Args>(__args)...); \ } _GLIBCXX_NOT_FN_CALL_OP( & ) _GLIBCXX_NOT_FN_CALL_OP( const & ) _GLIBCXX_NOT_FN_CALL_OP( && ) _GLIBCXX_NOT_FN_CALL_OP( const && ) #undef _GLIBCXX_NOT_FN_CALL private: _Fn _M_fn; }; template struct __is_byte_like : false_type { }; template struct __is_byte_like<_Tp, equal_to<_Tp>> : __bool_constant::value> { }; template struct __is_byte_like<_Tp, equal_to> : __bool_constant::value> { }; #if __cplusplus >= 201703L // Declare std::byte (full definition is in ). enum class byte : unsigned char; template<> struct __is_byte_like> : true_type { }; template<> struct __is_byte_like> : true_type { }; #define __cpp_lib_not_fn 201603 /// [func.not_fn] Function template not_fn template inline auto not_fn(_Fn&& __fn) noexcept(std::is_nothrow_constructible, _Fn&&>::value) { return _Not_fn>{std::forward<_Fn>(__fn), 0}; } // Searchers #define __cpp_lib_boyer_moore_searcher 201603 template> class default_searcher { public: default_searcher(_ForwardIterator1 __pat_first, _ForwardIterator1 __pat_last, _BinaryPredicate __pred = _BinaryPredicate()) : _M_m(__pat_first, __pat_last, std::move(__pred)) { } template pair<_ForwardIterator2, _ForwardIterator2> operator()(_ForwardIterator2 __first, _ForwardIterator2 __last) const { _ForwardIterator2 __first_ret = std::search(__first, __last, std::get<0>(_M_m), std::get<1>(_M_m), std::get<2>(_M_m)); auto __ret = std::make_pair(__first_ret, __first_ret); if (__ret.first != __last) std::advance(__ret.second, std::distance(std::get<0>(_M_m), std::get<1>(_M_m))); return __ret; } private: tuple<_ForwardIterator1, _ForwardIterator1, _BinaryPredicate> _M_m; }; template struct __boyer_moore_map_base { template __boyer_moore_map_base(_RAIter __pat, size_t __patlen, _Hash&& __hf, _Pred&& __pred) : _M_bad_char{ __patlen, std::move(__hf), std::move(__pred) } { if (__patlen > 0) for (__diff_type __i = 0; __i < __patlen - 1; ++__i) _M_bad_char[__pat[__i]] = __patlen - 1 - __i; } using __diff_type = _Tp; __diff_type _M_lookup(_Key __key, __diff_type __not_found) const { auto __iter = _M_bad_char.find(__key); if (__iter == _M_bad_char.end()) return __not_found; return __iter->second; } _Pred _M_pred() const { return _M_bad_char.key_eq(); } _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred> _M_bad_char; }; template struct __boyer_moore_array_base { template __boyer_moore_array_base(_RAIter __pat, size_t __patlen, _Unused&&, _Pred&& __pred) : _M_bad_char{ _GLIBCXX_STD_C::array<_Tp, _Len>{}, std::move(__pred) } { std::get<0>(_M_bad_char).fill(__patlen); if (__patlen > 0) for (__diff_type __i = 0; __i < __patlen - 1; ++__i) { auto __ch = __pat[__i]; using _UCh = make_unsigned_t; auto __uch = static_cast<_UCh>(__ch); std::get<0>(_M_bad_char)[__uch] = __patlen - 1 - __i; } } using __diff_type = _Tp; template __diff_type _M_lookup(_Key __key, __diff_type __not_found) const { auto __ukey = static_cast>(__key); if (__ukey >= _Len) return __not_found; return std::get<0>(_M_bad_char)[__ukey]; } const _Pred& _M_pred() const { return std::get<1>(_M_bad_char); } tuple<_GLIBCXX_STD_C::array<_Tp, _Len>, _Pred> _M_bad_char; }; // Use __boyer_moore_array_base when pattern consists of narrow characters // (or std::byte) and uses std::equal_to as the predicate. template::value_type, typename _Diff = typename iterator_traits<_RAIter>::difference_type> using __boyer_moore_base_t = conditional_t<__is_byte_like<_Val, _Pred>::value, __boyer_moore_array_base<_Diff, 256, _Pred>, __boyer_moore_map_base<_Val, _Diff, _Hash, _Pred>>; template::value_type>, typename _BinaryPredicate = equal_to<>> class boyer_moore_searcher : __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate> { using _Base = __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate>; using typename _Base::__diff_type; public: boyer_moore_searcher(_RAIter __pat_first, _RAIter __pat_last, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()); template pair<_RandomAccessIterator2, _RandomAccessIterator2> operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const; private: bool _M_is_prefix(_RAIter __word, __diff_type __len, __diff_type __pos) { const auto& __pred = this->_M_pred(); __diff_type __suffixlen = __len - __pos; for (__diff_type __i = 0; __i < __suffixlen; ++__i) if (!__pred(__word[__i], __word[__pos + __i])) return false; return true; } __diff_type _M_suffix_length(_RAIter __word, __diff_type __len, __diff_type __pos) { const auto& __pred = this->_M_pred(); __diff_type __i = 0; while (__pred(__word[__pos - __i], __word[__len - 1 - __i]) && __i < __pos) { ++__i; } return __i; } template __diff_type _M_bad_char_shift(_Tp __c) const { return this->_M_lookup(__c, _M_pat_end - _M_pat); } _RAIter _M_pat; _RAIter _M_pat_end; _GLIBCXX_STD_C::vector<__diff_type> _M_good_suffix; }; template::value_type>, typename _BinaryPredicate = equal_to<>> class boyer_moore_horspool_searcher : __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate> { using _Base = __boyer_moore_base_t<_RAIter, _Hash, _BinaryPredicate>; using typename _Base::__diff_type; public: boyer_moore_horspool_searcher(_RAIter __pat, _RAIter __pat_end, _Hash __hf = _Hash(), _BinaryPredicate __pred = _BinaryPredicate()) : _Base(__pat, __pat_end - __pat, std::move(__hf), std::move(__pred)), _M_pat(__pat), _M_pat_end(__pat_end) { } template pair<_RandomAccessIterator2, _RandomAccessIterator2> operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const { const auto& __pred = this->_M_pred(); auto __patlen = _M_pat_end - _M_pat; if (__patlen == 0) return std::make_pair(__first, __first); auto __len = __last - __first; while (__len >= __patlen) { for (auto __scan = __patlen - 1; __pred(__first[__scan], _M_pat[__scan]); --__scan) if (__scan == 0) return std::make_pair(__first, __first + __patlen); auto __shift = _M_bad_char_shift(__first[__patlen - 1]); __len -= __shift; __first += __shift; } return std::make_pair(__last, __last); } private: template __diff_type _M_bad_char_shift(_Tp __c) const { return this->_M_lookup(__c, _M_pat_end - _M_pat); } _RAIter _M_pat; _RAIter _M_pat_end; }; template boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate>:: boyer_moore_searcher(_RAIter __pat, _RAIter __pat_end, _Hash __hf, _BinaryPredicate __pred) : _Base(__pat, __pat_end - __pat, std::move(__hf), std::move(__pred)), _M_pat(__pat), _M_pat_end(__pat_end), _M_good_suffix(__pat_end - __pat) { auto __patlen = __pat_end - __pat; if (__patlen == 0) return; __diff_type __last_prefix = __patlen - 1; for (__diff_type __p = __patlen - 1; __p >= 0; --__p) { if (_M_is_prefix(__pat, __patlen, __p + 1)) __last_prefix = __p + 1; _M_good_suffix[__p] = __last_prefix + (__patlen - 1 - __p); } for (__diff_type __p = 0; __p < __patlen - 1; ++__p) { auto __slen = _M_suffix_length(__pat, __patlen, __p); auto __pos = __patlen - 1 - __slen; if (!__pred(__pat[__p - __slen], __pat[__pos])) _M_good_suffix[__pos] = __patlen - 1 - __p + __slen; } } template template pair<_RandomAccessIterator2, _RandomAccessIterator2> boyer_moore_searcher<_RAIter, _Hash, _BinaryPredicate>:: operator()(_RandomAccessIterator2 __first, _RandomAccessIterator2 __last) const { auto __patlen = _M_pat_end - _M_pat; if (__patlen == 0) return std::make_pair(__first, __first); const auto& __pred = this->_M_pred(); __diff_type __i = __patlen - 1; auto __stringlen = __last - __first; while (__i < __stringlen) { __diff_type __j = __patlen - 1; while (__j >= 0 && __pred(__first[__i], _M_pat[__j])) { --__i; --__j; } if (__j < 0) { const auto __match = __first + __i + 1; return std::make_pair(__match, __match + __patlen); } __i += std::max(_M_bad_char_shift(__first[__i]), _M_good_suffix[__j]); } return std::make_pair(__last, __last); } #endif // C++17 #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_FUNCTIONAL c++/8/atomic000064400000120141151027430570006465 0ustar00// -*- C++ -*- header. // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/atomic * This is a Standard C++ Library header. */ // Based on "C++ Atomic Types and Operations" by Hans Boehm and Lawrence Crowl. // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html #ifndef _GLIBCXX_ATOMIC #define _GLIBCXX_ATOMIC 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup atomics * @{ */ #if __cplusplus > 201402L # define __cpp_lib_atomic_is_always_lock_free 201603 #endif template struct atomic; /// atomic // NB: No operators or fetch-operations for this type. template<> struct atomic { private: __atomic_base _M_base; public: atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(bool __i) noexcept : _M_base(__i) { } bool operator=(bool __i) noexcept { return _M_base.operator=(__i); } bool operator=(bool __i) volatile noexcept { return _M_base.operator=(__i); } operator bool() const noexcept { return _M_base.load(); } operator bool() const volatile noexcept { return _M_base.load(); } bool is_lock_free() const noexcept { return _M_base.is_lock_free(); } bool is_lock_free() const volatile noexcept { return _M_base.is_lock_free(); } #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_BOOL_LOCK_FREE == 2; #endif void store(bool __i, memory_order __m = memory_order_seq_cst) noexcept { _M_base.store(__i, __m); } void store(bool __i, memory_order __m = memory_order_seq_cst) volatile noexcept { _M_base.store(__i, __m); } bool load(memory_order __m = memory_order_seq_cst) const noexcept { return _M_base.load(__m); } bool load(memory_order __m = memory_order_seq_cst) const volatile noexcept { return _M_base.load(__m); } bool exchange(bool __i, memory_order __m = memory_order_seq_cst) noexcept { return _M_base.exchange(__i, __m); } bool exchange(bool __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_base.exchange(__i, __m); } bool compare_exchange_weak(bool& __i1, bool __i2, memory_order __m1, memory_order __m2) noexcept { return _M_base.compare_exchange_weak(__i1, __i2, __m1, __m2); } bool compare_exchange_weak(bool& __i1, bool __i2, memory_order __m1, memory_order __m2) volatile noexcept { return _M_base.compare_exchange_weak(__i1, __i2, __m1, __m2); } bool compare_exchange_weak(bool& __i1, bool __i2, memory_order __m = memory_order_seq_cst) noexcept { return _M_base.compare_exchange_weak(__i1, __i2, __m); } bool compare_exchange_weak(bool& __i1, bool __i2, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_base.compare_exchange_weak(__i1, __i2, __m); } bool compare_exchange_strong(bool& __i1, bool __i2, memory_order __m1, memory_order __m2) noexcept { return _M_base.compare_exchange_strong(__i1, __i2, __m1, __m2); } bool compare_exchange_strong(bool& __i1, bool __i2, memory_order __m1, memory_order __m2) volatile noexcept { return _M_base.compare_exchange_strong(__i1, __i2, __m1, __m2); } bool compare_exchange_strong(bool& __i1, bool __i2, memory_order __m = memory_order_seq_cst) noexcept { return _M_base.compare_exchange_strong(__i1, __i2, __m); } bool compare_exchange_strong(bool& __i1, bool __i2, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_base.compare_exchange_strong(__i1, __i2, __m); } }; /** * @brief Generic atomic type, primary class template. * * @tparam _Tp Type to be made atomic, must be trivally copyable. */ template struct atomic { private: // Align 1/2/4/8/16-byte types to at least their size. static constexpr int _S_min_alignment = (sizeof(_Tp) & (sizeof(_Tp) - 1)) || sizeof(_Tp) > 16 ? 0 : sizeof(_Tp); static constexpr int _S_alignment = _S_min_alignment > alignof(_Tp) ? _S_min_alignment : alignof(_Tp); alignas(_S_alignment) _Tp _M_i; static_assert(__is_trivially_copyable(_Tp), "std::atomic requires a trivially copyable type"); static_assert(sizeof(_Tp) > 0, "Incomplete or zero-sized types are not supported"); public: atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(_Tp __i) noexcept : _M_i(__i) { } operator _Tp() const noexcept { return load(); } operator _Tp() const volatile noexcept { return load(); } _Tp operator=(_Tp __i) noexcept { store(__i); return __i; } _Tp operator=(_Tp __i) volatile noexcept { store(__i); return __i; } bool is_lock_free() const noexcept { // Produce a fake, minimally aligned pointer. return __atomic_is_lock_free(sizeof(_M_i), reinterpret_cast(-__alignof(_M_i))); } bool is_lock_free() const volatile noexcept { // Produce a fake, minimally aligned pointer. return __atomic_is_lock_free(sizeof(_M_i), reinterpret_cast(-__alignof(_M_i))); } #if __cplusplus > 201402L static constexpr bool is_always_lock_free = __atomic_always_lock_free(sizeof(_M_i), 0); #endif void store(_Tp __i, memory_order __m = memory_order_seq_cst) noexcept { __atomic_store(std::__addressof(_M_i), std::__addressof(__i), __m); } void store(_Tp __i, memory_order __m = memory_order_seq_cst) volatile noexcept { __atomic_store(std::__addressof(_M_i), std::__addressof(__i), __m); } _Tp load(memory_order __m = memory_order_seq_cst) const noexcept { alignas(_Tp) unsigned char __buf[sizeof(_Tp)]; _Tp* __ptr = reinterpret_cast<_Tp*>(__buf); __atomic_load(std::__addressof(_M_i), __ptr, __m); return *__ptr; } _Tp load(memory_order __m = memory_order_seq_cst) const volatile noexcept { alignas(_Tp) unsigned char __buf[sizeof(_Tp)]; _Tp* __ptr = reinterpret_cast<_Tp*>(__buf); __atomic_load(std::__addressof(_M_i), __ptr, __m); return *__ptr; } _Tp exchange(_Tp __i, memory_order __m = memory_order_seq_cst) noexcept { alignas(_Tp) unsigned char __buf[sizeof(_Tp)]; _Tp* __ptr = reinterpret_cast<_Tp*>(__buf); __atomic_exchange(std::__addressof(_M_i), std::__addressof(__i), __ptr, __m); return *__ptr; } _Tp exchange(_Tp __i, memory_order __m = memory_order_seq_cst) volatile noexcept { alignas(_Tp) unsigned char __buf[sizeof(_Tp)]; _Tp* __ptr = reinterpret_cast<_Tp*>(__buf); __atomic_exchange(std::__addressof(_M_i), std::__addressof(__i), __ptr, __m); return *__ptr; } bool compare_exchange_weak(_Tp& __e, _Tp __i, memory_order __s, memory_order __f) noexcept { return __atomic_compare_exchange(std::__addressof(_M_i), std::__addressof(__e), std::__addressof(__i), true, __s, __f); } bool compare_exchange_weak(_Tp& __e, _Tp __i, memory_order __s, memory_order __f) volatile noexcept { return __atomic_compare_exchange(std::__addressof(_M_i), std::__addressof(__e), std::__addressof(__i), true, __s, __f); } bool compare_exchange_weak(_Tp& __e, _Tp __i, memory_order __m = memory_order_seq_cst) noexcept { return compare_exchange_weak(__e, __i, __m, __cmpexch_failure_order(__m)); } bool compare_exchange_weak(_Tp& __e, _Tp __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return compare_exchange_weak(__e, __i, __m, __cmpexch_failure_order(__m)); } bool compare_exchange_strong(_Tp& __e, _Tp __i, memory_order __s, memory_order __f) noexcept { return __atomic_compare_exchange(std::__addressof(_M_i), std::__addressof(__e), std::__addressof(__i), false, __s, __f); } bool compare_exchange_strong(_Tp& __e, _Tp __i, memory_order __s, memory_order __f) volatile noexcept { return __atomic_compare_exchange(std::__addressof(_M_i), std::__addressof(__e), std::__addressof(__i), false, __s, __f); } bool compare_exchange_strong(_Tp& __e, _Tp __i, memory_order __m = memory_order_seq_cst) noexcept { return compare_exchange_strong(__e, __i, __m, __cmpexch_failure_order(__m)); } bool compare_exchange_strong(_Tp& __e, _Tp __i, memory_order __m = memory_order_seq_cst) volatile noexcept { return compare_exchange_strong(__e, __i, __m, __cmpexch_failure_order(__m)); } }; /// Partial specialization for pointer types. template struct atomic<_Tp*> { typedef _Tp* __pointer_type; typedef __atomic_base<_Tp*> __base_type; __base_type _M_b; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__pointer_type __p) noexcept : _M_b(__p) { } operator __pointer_type() const noexcept { return __pointer_type(_M_b); } operator __pointer_type() const volatile noexcept { return __pointer_type(_M_b); } __pointer_type operator=(__pointer_type __p) noexcept { return _M_b.operator=(__p); } __pointer_type operator=(__pointer_type __p) volatile noexcept { return _M_b.operator=(__p); } __pointer_type operator++(int) noexcept { return _M_b++; } __pointer_type operator++(int) volatile noexcept { return _M_b++; } __pointer_type operator--(int) noexcept { return _M_b--; } __pointer_type operator--(int) volatile noexcept { return _M_b--; } __pointer_type operator++() noexcept { return ++_M_b; } __pointer_type operator++() volatile noexcept { return ++_M_b; } __pointer_type operator--() noexcept { return --_M_b; } __pointer_type operator--() volatile noexcept { return --_M_b; } __pointer_type operator+=(ptrdiff_t __d) noexcept { return _M_b.operator+=(__d); } __pointer_type operator+=(ptrdiff_t __d) volatile noexcept { return _M_b.operator+=(__d); } __pointer_type operator-=(ptrdiff_t __d) noexcept { return _M_b.operator-=(__d); } __pointer_type operator-=(ptrdiff_t __d) volatile noexcept { return _M_b.operator-=(__d); } bool is_lock_free() const noexcept { return _M_b.is_lock_free(); } bool is_lock_free() const volatile noexcept { return _M_b.is_lock_free(); } #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_POINTER_LOCK_FREE == 2; #endif void store(__pointer_type __p, memory_order __m = memory_order_seq_cst) noexcept { return _M_b.store(__p, __m); } void store(__pointer_type __p, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_b.store(__p, __m); } __pointer_type load(memory_order __m = memory_order_seq_cst) const noexcept { return _M_b.load(__m); } __pointer_type load(memory_order __m = memory_order_seq_cst) const volatile noexcept { return _M_b.load(__m); } __pointer_type exchange(__pointer_type __p, memory_order __m = memory_order_seq_cst) noexcept { return _M_b.exchange(__p, __m); } __pointer_type exchange(__pointer_type __p, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_b.exchange(__p, __m); } bool compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2, memory_order __m1, memory_order __m2) noexcept { return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); } bool compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2, memory_order __m1, memory_order __m2) volatile noexcept { return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); } bool compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2, memory_order __m = memory_order_seq_cst) noexcept { return compare_exchange_weak(__p1, __p2, __m, __cmpexch_failure_order(__m)); } bool compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2, memory_order __m = memory_order_seq_cst) volatile noexcept { return compare_exchange_weak(__p1, __p2, __m, __cmpexch_failure_order(__m)); } bool compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2, memory_order __m1, memory_order __m2) noexcept { return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); } bool compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2, memory_order __m1, memory_order __m2) volatile noexcept { return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); } bool compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2, memory_order __m = memory_order_seq_cst) noexcept { return _M_b.compare_exchange_strong(__p1, __p2, __m, __cmpexch_failure_order(__m)); } bool compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_b.compare_exchange_strong(__p1, __p2, __m, __cmpexch_failure_order(__m)); } __pointer_type fetch_add(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) noexcept { return _M_b.fetch_add(__d, __m); } __pointer_type fetch_add(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_b.fetch_add(__d, __m); } __pointer_type fetch_sub(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) noexcept { return _M_b.fetch_sub(__d, __m); } __pointer_type fetch_sub(ptrdiff_t __d, memory_order __m = memory_order_seq_cst) volatile noexcept { return _M_b.fetch_sub(__d, __m); } }; /// Explicit specialization for char. template<> struct atomic : __atomic_base { typedef char __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_CHAR_LOCK_FREE == 2; #endif }; /// Explicit specialization for signed char. template<> struct atomic : __atomic_base { typedef signed char __integral_type; typedef __atomic_base __base_type; atomic() noexcept= default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_CHAR_LOCK_FREE == 2; #endif }; /// Explicit specialization for unsigned char. template<> struct atomic : __atomic_base { typedef unsigned char __integral_type; typedef __atomic_base __base_type; atomic() noexcept= default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_CHAR_LOCK_FREE == 2; #endif }; /// Explicit specialization for short. template<> struct atomic : __atomic_base { typedef short __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_SHORT_LOCK_FREE == 2; #endif }; /// Explicit specialization for unsigned short. template<> struct atomic : __atomic_base { typedef unsigned short __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_SHORT_LOCK_FREE == 2; #endif }; /// Explicit specialization for int. template<> struct atomic : __atomic_base { typedef int __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_INT_LOCK_FREE == 2; #endif }; /// Explicit specialization for unsigned int. template<> struct atomic : __atomic_base { typedef unsigned int __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_INT_LOCK_FREE == 2; #endif }; /// Explicit specialization for long. template<> struct atomic : __atomic_base { typedef long __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_LONG_LOCK_FREE == 2; #endif }; /// Explicit specialization for unsigned long. template<> struct atomic : __atomic_base { typedef unsigned long __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_LONG_LOCK_FREE == 2; #endif }; /// Explicit specialization for long long. template<> struct atomic : __atomic_base { typedef long long __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_LLONG_LOCK_FREE == 2; #endif }; /// Explicit specialization for unsigned long long. template<> struct atomic : __atomic_base { typedef unsigned long long __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_LLONG_LOCK_FREE == 2; #endif }; /// Explicit specialization for wchar_t. template<> struct atomic : __atomic_base { typedef wchar_t __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_WCHAR_T_LOCK_FREE == 2; #endif }; /// Explicit specialization for char16_t. template<> struct atomic : __atomic_base { typedef char16_t __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_CHAR16_T_LOCK_FREE == 2; #endif }; /// Explicit specialization for char32_t. template<> struct atomic : __atomic_base { typedef char32_t __integral_type; typedef __atomic_base __base_type; atomic() noexcept = default; ~atomic() noexcept = default; atomic(const atomic&) = delete; atomic& operator=(const atomic&) = delete; atomic& operator=(const atomic&) volatile = delete; constexpr atomic(__integral_type __i) noexcept : __base_type(__i) { } using __base_type::operator __integral_type; using __base_type::operator=; #if __cplusplus > 201402L static constexpr bool is_always_lock_free = ATOMIC_CHAR32_T_LOCK_FREE == 2; #endif }; /// atomic_bool typedef atomic atomic_bool; /// atomic_char typedef atomic atomic_char; /// atomic_schar typedef atomic atomic_schar; /// atomic_uchar typedef atomic atomic_uchar; /// atomic_short typedef atomic atomic_short; /// atomic_ushort typedef atomic atomic_ushort; /// atomic_int typedef atomic atomic_int; /// atomic_uint typedef atomic atomic_uint; /// atomic_long typedef atomic atomic_long; /// atomic_ulong typedef atomic atomic_ulong; /// atomic_llong typedef atomic atomic_llong; /// atomic_ullong typedef atomic atomic_ullong; /// atomic_wchar_t typedef atomic atomic_wchar_t; /// atomic_char16_t typedef atomic atomic_char16_t; /// atomic_char32_t typedef atomic atomic_char32_t; #ifdef _GLIBCXX_USE_C99_STDINT_TR1 // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2441. Exact-width atomic typedefs should be provided /// atomic_int8_t typedef atomic atomic_int8_t; /// atomic_uint8_t typedef atomic atomic_uint8_t; /// atomic_int16_t typedef atomic atomic_int16_t; /// atomic_uint16_t typedef atomic atomic_uint16_t; /// atomic_int32_t typedef atomic atomic_int32_t; /// atomic_uint32_t typedef atomic atomic_uint32_t; /// atomic_int64_t typedef atomic atomic_int64_t; /// atomic_uint64_t typedef atomic atomic_uint64_t; /// atomic_int_least8_t typedef atomic atomic_int_least8_t; /// atomic_uint_least8_t typedef atomic atomic_uint_least8_t; /// atomic_int_least16_t typedef atomic atomic_int_least16_t; /// atomic_uint_least16_t typedef atomic atomic_uint_least16_t; /// atomic_int_least32_t typedef atomic atomic_int_least32_t; /// atomic_uint_least32_t typedef atomic atomic_uint_least32_t; /// atomic_int_least64_t typedef atomic atomic_int_least64_t; /// atomic_uint_least64_t typedef atomic atomic_uint_least64_t; /// atomic_int_fast8_t typedef atomic atomic_int_fast8_t; /// atomic_uint_fast8_t typedef atomic atomic_uint_fast8_t; /// atomic_int_fast16_t typedef atomic atomic_int_fast16_t; /// atomic_uint_fast16_t typedef atomic atomic_uint_fast16_t; /// atomic_int_fast32_t typedef atomic atomic_int_fast32_t; /// atomic_uint_fast32_t typedef atomic atomic_uint_fast32_t; /// atomic_int_fast64_t typedef atomic atomic_int_fast64_t; /// atomic_uint_fast64_t typedef atomic atomic_uint_fast64_t; #endif /// atomic_intptr_t typedef atomic atomic_intptr_t; /// atomic_uintptr_t typedef atomic atomic_uintptr_t; /// atomic_size_t typedef atomic atomic_size_t; /// atomic_ptrdiff_t typedef atomic atomic_ptrdiff_t; #ifdef _GLIBCXX_USE_C99_STDINT_TR1 /// atomic_intmax_t typedef atomic atomic_intmax_t; /// atomic_uintmax_t typedef atomic atomic_uintmax_t; #endif // Function definitions, atomic_flag operations. inline bool atomic_flag_test_and_set_explicit(atomic_flag* __a, memory_order __m) noexcept { return __a->test_and_set(__m); } inline bool atomic_flag_test_and_set_explicit(volatile atomic_flag* __a, memory_order __m) noexcept { return __a->test_and_set(__m); } inline void atomic_flag_clear_explicit(atomic_flag* __a, memory_order __m) noexcept { __a->clear(__m); } inline void atomic_flag_clear_explicit(volatile atomic_flag* __a, memory_order __m) noexcept { __a->clear(__m); } inline bool atomic_flag_test_and_set(atomic_flag* __a) noexcept { return atomic_flag_test_and_set_explicit(__a, memory_order_seq_cst); } inline bool atomic_flag_test_and_set(volatile atomic_flag* __a) noexcept { return atomic_flag_test_and_set_explicit(__a, memory_order_seq_cst); } inline void atomic_flag_clear(atomic_flag* __a) noexcept { atomic_flag_clear_explicit(__a, memory_order_seq_cst); } inline void atomic_flag_clear(volatile atomic_flag* __a) noexcept { atomic_flag_clear_explicit(__a, memory_order_seq_cst); } // Function templates generally applicable to atomic types. template inline bool atomic_is_lock_free(const atomic<_ITp>* __a) noexcept { return __a->is_lock_free(); } template inline bool atomic_is_lock_free(const volatile atomic<_ITp>* __a) noexcept { return __a->is_lock_free(); } template inline void atomic_init(atomic<_ITp>* __a, _ITp __i) noexcept { __a->store(__i, memory_order_relaxed); } template inline void atomic_init(volatile atomic<_ITp>* __a, _ITp __i) noexcept { __a->store(__i, memory_order_relaxed); } template inline void atomic_store_explicit(atomic<_ITp>* __a, _ITp __i, memory_order __m) noexcept { __a->store(__i, __m); } template inline void atomic_store_explicit(volatile atomic<_ITp>* __a, _ITp __i, memory_order __m) noexcept { __a->store(__i, __m); } template inline _ITp atomic_load_explicit(const atomic<_ITp>* __a, memory_order __m) noexcept { return __a->load(__m); } template inline _ITp atomic_load_explicit(const volatile atomic<_ITp>* __a, memory_order __m) noexcept { return __a->load(__m); } template inline _ITp atomic_exchange_explicit(atomic<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->exchange(__i, __m); } template inline _ITp atomic_exchange_explicit(volatile atomic<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->exchange(__i, __m); } template inline bool atomic_compare_exchange_weak_explicit(atomic<_ITp>* __a, _ITp* __i1, _ITp __i2, memory_order __m1, memory_order __m2) noexcept { return __a->compare_exchange_weak(*__i1, __i2, __m1, __m2); } template inline bool atomic_compare_exchange_weak_explicit(volatile atomic<_ITp>* __a, _ITp* __i1, _ITp __i2, memory_order __m1, memory_order __m2) noexcept { return __a->compare_exchange_weak(*__i1, __i2, __m1, __m2); } template inline bool atomic_compare_exchange_strong_explicit(atomic<_ITp>* __a, _ITp* __i1, _ITp __i2, memory_order __m1, memory_order __m2) noexcept { return __a->compare_exchange_strong(*__i1, __i2, __m1, __m2); } template inline bool atomic_compare_exchange_strong_explicit(volatile atomic<_ITp>* __a, _ITp* __i1, _ITp __i2, memory_order __m1, memory_order __m2) noexcept { return __a->compare_exchange_strong(*__i1, __i2, __m1, __m2); } template inline void atomic_store(atomic<_ITp>* __a, _ITp __i) noexcept { atomic_store_explicit(__a, __i, memory_order_seq_cst); } template inline void atomic_store(volatile atomic<_ITp>* __a, _ITp __i) noexcept { atomic_store_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_load(const atomic<_ITp>* __a) noexcept { return atomic_load_explicit(__a, memory_order_seq_cst); } template inline _ITp atomic_load(const volatile atomic<_ITp>* __a) noexcept { return atomic_load_explicit(__a, memory_order_seq_cst); } template inline _ITp atomic_exchange(atomic<_ITp>* __a, _ITp __i) noexcept { return atomic_exchange_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_exchange(volatile atomic<_ITp>* __a, _ITp __i) noexcept { return atomic_exchange_explicit(__a, __i, memory_order_seq_cst); } template inline bool atomic_compare_exchange_weak(atomic<_ITp>* __a, _ITp* __i1, _ITp __i2) noexcept { return atomic_compare_exchange_weak_explicit(__a, __i1, __i2, memory_order_seq_cst, memory_order_seq_cst); } template inline bool atomic_compare_exchange_weak(volatile atomic<_ITp>* __a, _ITp* __i1, _ITp __i2) noexcept { return atomic_compare_exchange_weak_explicit(__a, __i1, __i2, memory_order_seq_cst, memory_order_seq_cst); } template inline bool atomic_compare_exchange_strong(atomic<_ITp>* __a, _ITp* __i1, _ITp __i2) noexcept { return atomic_compare_exchange_strong_explicit(__a, __i1, __i2, memory_order_seq_cst, memory_order_seq_cst); } template inline bool atomic_compare_exchange_strong(volatile atomic<_ITp>* __a, _ITp* __i1, _ITp __i2) noexcept { return atomic_compare_exchange_strong_explicit(__a, __i1, __i2, memory_order_seq_cst, memory_order_seq_cst); } // Function templates for atomic_integral operations only, using // __atomic_base. Template argument should be constricted to // intergral types as specified in the standard, excluding address // types. template inline _ITp atomic_fetch_add_explicit(__atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_add(__i, __m); } template inline _ITp atomic_fetch_add_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_add(__i, __m); } template inline _ITp atomic_fetch_sub_explicit(__atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_sub(__i, __m); } template inline _ITp atomic_fetch_sub_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_sub(__i, __m); } template inline _ITp atomic_fetch_and_explicit(__atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_and(__i, __m); } template inline _ITp atomic_fetch_and_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_and(__i, __m); } template inline _ITp atomic_fetch_or_explicit(__atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_or(__i, __m); } template inline _ITp atomic_fetch_or_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_or(__i, __m); } template inline _ITp atomic_fetch_xor_explicit(__atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_xor(__i, __m); } template inline _ITp atomic_fetch_xor_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i, memory_order __m) noexcept { return __a->fetch_xor(__i, __m); } template inline _ITp atomic_fetch_add(__atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_add_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_add(volatile __atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_add_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_sub(__atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_sub_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_sub(volatile __atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_sub_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_and(__atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_and_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_and(volatile __atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_and_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_or(__atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_or_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_or(volatile __atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_or_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_xor(__atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_xor_explicit(__a, __i, memory_order_seq_cst); } template inline _ITp atomic_fetch_xor(volatile __atomic_base<_ITp>* __a, _ITp __i) noexcept { return atomic_fetch_xor_explicit(__a, __i, memory_order_seq_cst); } // Partial specializations for pointers. template inline _ITp* atomic_fetch_add_explicit(atomic<_ITp*>* __a, ptrdiff_t __d, memory_order __m) noexcept { return __a->fetch_add(__d, __m); } template inline _ITp* atomic_fetch_add_explicit(volatile atomic<_ITp*>* __a, ptrdiff_t __d, memory_order __m) noexcept { return __a->fetch_add(__d, __m); } template inline _ITp* atomic_fetch_add(volatile atomic<_ITp*>* __a, ptrdiff_t __d) noexcept { return __a->fetch_add(__d); } template inline _ITp* atomic_fetch_add(atomic<_ITp*>* __a, ptrdiff_t __d) noexcept { return __a->fetch_add(__d); } template inline _ITp* atomic_fetch_sub_explicit(volatile atomic<_ITp*>* __a, ptrdiff_t __d, memory_order __m) noexcept { return __a->fetch_sub(__d, __m); } template inline _ITp* atomic_fetch_sub_explicit(atomic<_ITp*>* __a, ptrdiff_t __d, memory_order __m) noexcept { return __a->fetch_sub(__d, __m); } template inline _ITp* atomic_fetch_sub(volatile atomic<_ITp*>* __a, ptrdiff_t __d) noexcept { return __a->fetch_sub(__d); } template inline _ITp* atomic_fetch_sub(atomic<_ITp*>* __a, ptrdiff_t __d) noexcept { return __a->fetch_sub(__d); } // @} group atomics _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif // _GLIBCXX_ATOMIC c++/8/bitset000064400000131526151027430570006514 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1998 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/bitset * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_BITSET #define _GLIBCXX_BITSET 1 #pragma GCC system_header #include #include // For invalid_argument, out_of_range, // overflow_error #include #include #if __cplusplus >= 201103L # include #endif #define _GLIBCXX_BITSET_BITS_PER_WORD (__CHAR_BIT__ * __SIZEOF_LONG__) #define _GLIBCXX_BITSET_WORDS(__n) \ ((__n) / _GLIBCXX_BITSET_BITS_PER_WORD + \ ((__n) % _GLIBCXX_BITSET_BITS_PER_WORD == 0 ? 0 : 1)) #define _GLIBCXX_BITSET_BITS_PER_ULL (__CHAR_BIT__ * __SIZEOF_LONG_LONG__) namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_CONTAINER /** * Base class, general case. It is a class invariant that _Nw will be * nonnegative. * * See documentation for bitset. */ template struct _Base_bitset { typedef unsigned long _WordT; /// 0 is the least significant word. _WordT _M_w[_Nw]; _GLIBCXX_CONSTEXPR _Base_bitset() _GLIBCXX_NOEXCEPT : _M_w() { } #if __cplusplus >= 201103L constexpr _Base_bitset(unsigned long long __val) noexcept : _M_w{ _WordT(__val) #if __SIZEOF_LONG_LONG__ > __SIZEOF_LONG__ , _WordT(__val >> _GLIBCXX_BITSET_BITS_PER_WORD) #endif } { } #else _Base_bitset(unsigned long __val) : _M_w() { _M_w[0] = __val; } #endif static _GLIBCXX_CONSTEXPR size_t _S_whichword(size_t __pos) _GLIBCXX_NOEXCEPT { return __pos / _GLIBCXX_BITSET_BITS_PER_WORD; } static _GLIBCXX_CONSTEXPR size_t _S_whichbyte(size_t __pos) _GLIBCXX_NOEXCEPT { return (__pos % _GLIBCXX_BITSET_BITS_PER_WORD) / __CHAR_BIT__; } static _GLIBCXX_CONSTEXPR size_t _S_whichbit(size_t __pos) _GLIBCXX_NOEXCEPT { return __pos % _GLIBCXX_BITSET_BITS_PER_WORD; } static _GLIBCXX_CONSTEXPR _WordT _S_maskbit(size_t __pos) _GLIBCXX_NOEXCEPT { return (static_cast<_WordT>(1)) << _S_whichbit(__pos); } _WordT& _M_getword(size_t __pos) _GLIBCXX_NOEXCEPT { return _M_w[_S_whichword(__pos)]; } _GLIBCXX_CONSTEXPR _WordT _M_getword(size_t __pos) const _GLIBCXX_NOEXCEPT { return _M_w[_S_whichword(__pos)]; } #if __cplusplus >= 201103L const _WordT* _M_getdata() const noexcept { return _M_w; } #endif _WordT& _M_hiword() _GLIBCXX_NOEXCEPT { return _M_w[_Nw - 1]; } _GLIBCXX_CONSTEXPR _WordT _M_hiword() const _GLIBCXX_NOEXCEPT { return _M_w[_Nw - 1]; } void _M_do_and(const _Base_bitset<_Nw>& __x) _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) _M_w[__i] &= __x._M_w[__i]; } void _M_do_or(const _Base_bitset<_Nw>& __x) _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) _M_w[__i] |= __x._M_w[__i]; } void _M_do_xor(const _Base_bitset<_Nw>& __x) _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) _M_w[__i] ^= __x._M_w[__i]; } void _M_do_left_shift(size_t __shift) _GLIBCXX_NOEXCEPT; void _M_do_right_shift(size_t __shift) _GLIBCXX_NOEXCEPT; void _M_do_flip() _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) _M_w[__i] = ~_M_w[__i]; } void _M_do_set() _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) _M_w[__i] = ~static_cast<_WordT>(0); } void _M_do_reset() _GLIBCXX_NOEXCEPT { __builtin_memset(_M_w, 0, _Nw * sizeof(_WordT)); } bool _M_is_equal(const _Base_bitset<_Nw>& __x) const _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; ++__i) if (_M_w[__i] != __x._M_w[__i]) return false; return true; } template bool _M_are_all() const _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw - 1; __i++) if (_M_w[__i] != ~static_cast<_WordT>(0)) return false; return _M_hiword() == (~static_cast<_WordT>(0) >> (_Nw * _GLIBCXX_BITSET_BITS_PER_WORD - _Nb)); } bool _M_is_any() const _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) if (_M_w[__i] != static_cast<_WordT>(0)) return true; return false; } size_t _M_do_count() const _GLIBCXX_NOEXCEPT { size_t __result = 0; for (size_t __i = 0; __i < _Nw; __i++) __result += __builtin_popcountl(_M_w[__i]); return __result; } unsigned long _M_do_to_ulong() const; #if __cplusplus >= 201103L unsigned long long _M_do_to_ullong() const; #endif // find first "on" bit size_t _M_do_find_first(size_t) const _GLIBCXX_NOEXCEPT; // find the next "on" bit that follows "prev" size_t _M_do_find_next(size_t, size_t) const _GLIBCXX_NOEXCEPT; }; // Definitions of non-inline functions from _Base_bitset. template void _Base_bitset<_Nw>::_M_do_left_shift(size_t __shift) _GLIBCXX_NOEXCEPT { if (__builtin_expect(__shift != 0, 1)) { const size_t __wshift = __shift / _GLIBCXX_BITSET_BITS_PER_WORD; const size_t __offset = __shift % _GLIBCXX_BITSET_BITS_PER_WORD; if (__offset == 0) for (size_t __n = _Nw - 1; __n >= __wshift; --__n) _M_w[__n] = _M_w[__n - __wshift]; else { const size_t __sub_offset = (_GLIBCXX_BITSET_BITS_PER_WORD - __offset); for (size_t __n = _Nw - 1; __n > __wshift; --__n) _M_w[__n] = ((_M_w[__n - __wshift] << __offset) | (_M_w[__n - __wshift - 1] >> __sub_offset)); _M_w[__wshift] = _M_w[0] << __offset; } std::fill(_M_w + 0, _M_w + __wshift, static_cast<_WordT>(0)); } } template void _Base_bitset<_Nw>::_M_do_right_shift(size_t __shift) _GLIBCXX_NOEXCEPT { if (__builtin_expect(__shift != 0, 1)) { const size_t __wshift = __shift / _GLIBCXX_BITSET_BITS_PER_WORD; const size_t __offset = __shift % _GLIBCXX_BITSET_BITS_PER_WORD; const size_t __limit = _Nw - __wshift - 1; if (__offset == 0) for (size_t __n = 0; __n <= __limit; ++__n) _M_w[__n] = _M_w[__n + __wshift]; else { const size_t __sub_offset = (_GLIBCXX_BITSET_BITS_PER_WORD - __offset); for (size_t __n = 0; __n < __limit; ++__n) _M_w[__n] = ((_M_w[__n + __wshift] >> __offset) | (_M_w[__n + __wshift + 1] << __sub_offset)); _M_w[__limit] = _M_w[_Nw-1] >> __offset; } std::fill(_M_w + __limit + 1, _M_w + _Nw, static_cast<_WordT>(0)); } } template unsigned long _Base_bitset<_Nw>::_M_do_to_ulong() const { for (size_t __i = 1; __i < _Nw; ++__i) if (_M_w[__i]) __throw_overflow_error(__N("_Base_bitset::_M_do_to_ulong")); return _M_w[0]; } #if __cplusplus >= 201103L template unsigned long long _Base_bitset<_Nw>::_M_do_to_ullong() const { const bool __dw = sizeof(unsigned long long) > sizeof(unsigned long); for (size_t __i = 1 + __dw; __i < _Nw; ++__i) if (_M_w[__i]) __throw_overflow_error(__N("_Base_bitset::_M_do_to_ullong")); if (__dw) return _M_w[0] + (static_cast(_M_w[1]) << _GLIBCXX_BITSET_BITS_PER_WORD); return _M_w[0]; } #endif template size_t _Base_bitset<_Nw>:: _M_do_find_first(size_t __not_found) const _GLIBCXX_NOEXCEPT { for (size_t __i = 0; __i < _Nw; __i++) { _WordT __thisword = _M_w[__i]; if (__thisword != static_cast<_WordT>(0)) return (__i * _GLIBCXX_BITSET_BITS_PER_WORD + __builtin_ctzl(__thisword)); } // not found, so return an indication of failure. return __not_found; } template size_t _Base_bitset<_Nw>:: _M_do_find_next(size_t __prev, size_t __not_found) const _GLIBCXX_NOEXCEPT { // make bound inclusive ++__prev; // check out of bounds if (__prev >= _Nw * _GLIBCXX_BITSET_BITS_PER_WORD) return __not_found; // search first word size_t __i = _S_whichword(__prev); _WordT __thisword = _M_w[__i]; // mask off bits below bound __thisword &= (~static_cast<_WordT>(0)) << _S_whichbit(__prev); if (__thisword != static_cast<_WordT>(0)) return (__i * _GLIBCXX_BITSET_BITS_PER_WORD + __builtin_ctzl(__thisword)); // check subsequent words __i++; for (; __i < _Nw; __i++) { __thisword = _M_w[__i]; if (__thisword != static_cast<_WordT>(0)) return (__i * _GLIBCXX_BITSET_BITS_PER_WORD + __builtin_ctzl(__thisword)); } // not found, so return an indication of failure. return __not_found; } // end _M_do_find_next /** * Base class, specialization for a single word. * * See documentation for bitset. */ template<> struct _Base_bitset<1> { typedef unsigned long _WordT; _WordT _M_w; _GLIBCXX_CONSTEXPR _Base_bitset() _GLIBCXX_NOEXCEPT : _M_w(0) { } #if __cplusplus >= 201103L constexpr _Base_bitset(unsigned long long __val) noexcept #else _Base_bitset(unsigned long __val) #endif : _M_w(__val) { } static _GLIBCXX_CONSTEXPR size_t _S_whichword(size_t __pos) _GLIBCXX_NOEXCEPT { return __pos / _GLIBCXX_BITSET_BITS_PER_WORD; } static _GLIBCXX_CONSTEXPR size_t _S_whichbyte(size_t __pos) _GLIBCXX_NOEXCEPT { return (__pos % _GLIBCXX_BITSET_BITS_PER_WORD) / __CHAR_BIT__; } static _GLIBCXX_CONSTEXPR size_t _S_whichbit(size_t __pos) _GLIBCXX_NOEXCEPT { return __pos % _GLIBCXX_BITSET_BITS_PER_WORD; } static _GLIBCXX_CONSTEXPR _WordT _S_maskbit(size_t __pos) _GLIBCXX_NOEXCEPT { return (static_cast<_WordT>(1)) << _S_whichbit(__pos); } _WordT& _M_getword(size_t) _GLIBCXX_NOEXCEPT { return _M_w; } _GLIBCXX_CONSTEXPR _WordT _M_getword(size_t) const _GLIBCXX_NOEXCEPT { return _M_w; } #if __cplusplus >= 201103L const _WordT* _M_getdata() const noexcept { return &_M_w; } #endif _WordT& _M_hiword() _GLIBCXX_NOEXCEPT { return _M_w; } _GLIBCXX_CONSTEXPR _WordT _M_hiword() const _GLIBCXX_NOEXCEPT { return _M_w; } void _M_do_and(const _Base_bitset<1>& __x) _GLIBCXX_NOEXCEPT { _M_w &= __x._M_w; } void _M_do_or(const _Base_bitset<1>& __x) _GLIBCXX_NOEXCEPT { _M_w |= __x._M_w; } void _M_do_xor(const _Base_bitset<1>& __x) _GLIBCXX_NOEXCEPT { _M_w ^= __x._M_w; } void _M_do_left_shift(size_t __shift) _GLIBCXX_NOEXCEPT { _M_w <<= __shift; } void _M_do_right_shift(size_t __shift) _GLIBCXX_NOEXCEPT { _M_w >>= __shift; } void _M_do_flip() _GLIBCXX_NOEXCEPT { _M_w = ~_M_w; } void _M_do_set() _GLIBCXX_NOEXCEPT { _M_w = ~static_cast<_WordT>(0); } void _M_do_reset() _GLIBCXX_NOEXCEPT { _M_w = 0; } bool _M_is_equal(const _Base_bitset<1>& __x) const _GLIBCXX_NOEXCEPT { return _M_w == __x._M_w; } template bool _M_are_all() const _GLIBCXX_NOEXCEPT { return _M_w == (~static_cast<_WordT>(0) >> (_GLIBCXX_BITSET_BITS_PER_WORD - _Nb)); } bool _M_is_any() const _GLIBCXX_NOEXCEPT { return _M_w != 0; } size_t _M_do_count() const _GLIBCXX_NOEXCEPT { return __builtin_popcountl(_M_w); } unsigned long _M_do_to_ulong() const _GLIBCXX_NOEXCEPT { return _M_w; } #if __cplusplus >= 201103L unsigned long long _M_do_to_ullong() const noexcept { return _M_w; } #endif size_t _M_do_find_first(size_t __not_found) const _GLIBCXX_NOEXCEPT { if (_M_w != 0) return __builtin_ctzl(_M_w); else return __not_found; } // find the next "on" bit that follows "prev" size_t _M_do_find_next(size_t __prev, size_t __not_found) const _GLIBCXX_NOEXCEPT { ++__prev; if (__prev >= ((size_t) _GLIBCXX_BITSET_BITS_PER_WORD)) return __not_found; _WordT __x = _M_w >> __prev; if (__x != 0) return __builtin_ctzl(__x) + __prev; else return __not_found; } }; /** * Base class, specialization for no storage (zero-length %bitset). * * See documentation for bitset. */ template<> struct _Base_bitset<0> { typedef unsigned long _WordT; _GLIBCXX_CONSTEXPR _Base_bitset() _GLIBCXX_NOEXCEPT { } #if __cplusplus >= 201103L constexpr _Base_bitset(unsigned long long) noexcept #else _Base_bitset(unsigned long) #endif { } static _GLIBCXX_CONSTEXPR size_t _S_whichword(size_t __pos) _GLIBCXX_NOEXCEPT { return __pos / _GLIBCXX_BITSET_BITS_PER_WORD; } static _GLIBCXX_CONSTEXPR size_t _S_whichbyte(size_t __pos) _GLIBCXX_NOEXCEPT { return (__pos % _GLIBCXX_BITSET_BITS_PER_WORD) / __CHAR_BIT__; } static _GLIBCXX_CONSTEXPR size_t _S_whichbit(size_t __pos) _GLIBCXX_NOEXCEPT { return __pos % _GLIBCXX_BITSET_BITS_PER_WORD; } static _GLIBCXX_CONSTEXPR _WordT _S_maskbit(size_t __pos) _GLIBCXX_NOEXCEPT { return (static_cast<_WordT>(1)) << _S_whichbit(__pos); } // This would normally give access to the data. The bounds-checking // in the bitset class will prevent the user from getting this far, // but (1) it must still return an lvalue to compile, and (2) the // user might call _Unchecked_set directly, in which case this /needs/ // to fail. Let's not penalize zero-length users unless they actually // make an unchecked call; all the memory ugliness is therefore // localized to this single should-never-get-this-far function. _WordT& _M_getword(size_t) _GLIBCXX_NOEXCEPT { __throw_out_of_range(__N("_Base_bitset::_M_getword")); return *new _WordT; } _GLIBCXX_CONSTEXPR _WordT _M_getword(size_t) const _GLIBCXX_NOEXCEPT { return 0; } _GLIBCXX_CONSTEXPR _WordT _M_hiword() const _GLIBCXX_NOEXCEPT { return 0; } void _M_do_and(const _Base_bitset<0>&) _GLIBCXX_NOEXCEPT { } void _M_do_or(const _Base_bitset<0>&) _GLIBCXX_NOEXCEPT { } void _M_do_xor(const _Base_bitset<0>&) _GLIBCXX_NOEXCEPT { } void _M_do_left_shift(size_t) _GLIBCXX_NOEXCEPT { } void _M_do_right_shift(size_t) _GLIBCXX_NOEXCEPT { } void _M_do_flip() _GLIBCXX_NOEXCEPT { } void _M_do_set() _GLIBCXX_NOEXCEPT { } void _M_do_reset() _GLIBCXX_NOEXCEPT { } // Are all empty bitsets equal to each other? Are they equal to // themselves? How to compare a thing which has no state? What is // the sound of one zero-length bitset clapping? bool _M_is_equal(const _Base_bitset<0>&) const _GLIBCXX_NOEXCEPT { return true; } template bool _M_are_all() const _GLIBCXX_NOEXCEPT { return true; } bool _M_is_any() const _GLIBCXX_NOEXCEPT { return false; } size_t _M_do_count() const _GLIBCXX_NOEXCEPT { return 0; } unsigned long _M_do_to_ulong() const _GLIBCXX_NOEXCEPT { return 0; } #if __cplusplus >= 201103L unsigned long long _M_do_to_ullong() const noexcept { return 0; } #endif // Normally "not found" is the size, but that could also be // misinterpreted as an index in this corner case. Oh well. size_t _M_do_find_first(size_t) const _GLIBCXX_NOEXCEPT { return 0; } size_t _M_do_find_next(size_t, size_t) const _GLIBCXX_NOEXCEPT { return 0; } }; // Helper class to zero out the unused high-order bits in the highest word. template struct _Sanitize { typedef unsigned long _WordT; static void _S_do_sanitize(_WordT& __val) _GLIBCXX_NOEXCEPT { __val &= ~((~static_cast<_WordT>(0)) << _Extrabits); } }; template<> struct _Sanitize<0> { typedef unsigned long _WordT; static void _S_do_sanitize(_WordT) _GLIBCXX_NOEXCEPT { } }; #if __cplusplus >= 201103L template struct _Sanitize_val { static constexpr unsigned long long _S_do_sanitize_val(unsigned long long __val) { return __val; } }; template struct _Sanitize_val<_Nb, true> { static constexpr unsigned long long _S_do_sanitize_val(unsigned long long __val) { return __val & ~((~static_cast(0)) << _Nb); } }; #endif /** * @brief The %bitset class represents a @e fixed-size sequence of bits. * @ingroup utilities * * (Note that %bitset does @e not meet the formal requirements of a * container. Mainly, it lacks iterators.) * * The template argument, @a Nb, may be any non-negative number, * specifying the number of bits (e.g., "0", "12", "1024*1024"). * * In the general unoptimized case, storage is allocated in word-sized * blocks. Let B be the number of bits in a word, then (Nb+(B-1))/B * words will be used for storage. B - Nb%B bits are unused. (They are * the high-order bits in the highest word.) It is a class invariant * that those unused bits are always zero. * * If you think of %bitset as a simple array of bits, be * aware that your mental picture is reversed: a %bitset behaves * the same way as bits in integers do, with the bit at index 0 in * the least significant / right-hand position, and the bit at * index Nb-1 in the most significant / left-hand position. * Thus, unlike other containers, a %bitset's index counts from * right to left, to put it very loosely. * * This behavior is preserved when translating to and from strings. For * example, the first line of the following program probably prints * b('a') is 0001100001 on a modern ASCII system. * * @code * #include * #include * #include * * using namespace std; * * int main() * { * long a = 'a'; * bitset<10> b(a); * * cout << "b('a') is " << b << endl; * * ostringstream s; * s << b; * string str = s.str(); * cout << "index 3 in the string is " << str[3] << " but\n" * << "index 3 in the bitset is " << b[3] << endl; * } * @endcode * * Also see: * https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_containers.html * for a description of extensions. * * Most of the actual code isn't contained in %bitset<> itself, but in the * base class _Base_bitset. The base class works with whole words, not with * individual bits. This allows us to specialize _Base_bitset for the * important special case where the %bitset is only a single word. * * Extra confusion can result due to the fact that the storage for * _Base_bitset @e is a regular array, and is indexed as such. This is * carefully encapsulated. */ template class bitset : private _Base_bitset<_GLIBCXX_BITSET_WORDS(_Nb)> { private: typedef _Base_bitset<_GLIBCXX_BITSET_WORDS(_Nb)> _Base; typedef unsigned long _WordT; template void _M_check_initial_position(const std::basic_string<_CharT, _Traits, _Alloc>& __s, size_t __position) const { if (__position > __s.size()) __throw_out_of_range_fmt(__N("bitset::bitset: __position " "(which is %zu) > __s.size() " "(which is %zu)"), __position, __s.size()); } void _M_check(size_t __position, const char *__s) const { if (__position >= _Nb) __throw_out_of_range_fmt(__N("%s: __position (which is %zu) " ">= _Nb (which is %zu)"), __s, __position, _Nb); } void _M_do_sanitize() _GLIBCXX_NOEXCEPT { typedef _Sanitize<_Nb % _GLIBCXX_BITSET_BITS_PER_WORD> __sanitize_type; __sanitize_type::_S_do_sanitize(this->_M_hiword()); } #if __cplusplus >= 201103L friend struct std::hash; #endif public: /** * This encapsulates the concept of a single bit. An instance of this * class is a proxy for an actual bit; this way the individual bit * operations are done as faster word-size bitwise instructions. * * Most users will never need to use this class directly; conversions * to and from bool are automatic and should be transparent. Overloaded * operators help to preserve the illusion. * * (On a typical system, this bit %reference is 64 * times the size of an actual bit. Ha.) */ class reference { friend class bitset; _WordT* _M_wp; size_t _M_bpos; // left undefined reference(); public: reference(bitset& __b, size_t __pos) _GLIBCXX_NOEXCEPT { _M_wp = &__b._M_getword(__pos); _M_bpos = _Base::_S_whichbit(__pos); } ~reference() _GLIBCXX_NOEXCEPT { } // For b[i] = __x; reference& operator=(bool __x) _GLIBCXX_NOEXCEPT { if (__x) *_M_wp |= _Base::_S_maskbit(_M_bpos); else *_M_wp &= ~_Base::_S_maskbit(_M_bpos); return *this; } // For b[i] = b[__j]; reference& operator=(const reference& __j) _GLIBCXX_NOEXCEPT { if ((*(__j._M_wp) & _Base::_S_maskbit(__j._M_bpos))) *_M_wp |= _Base::_S_maskbit(_M_bpos); else *_M_wp &= ~_Base::_S_maskbit(_M_bpos); return *this; } // Flips the bit bool operator~() const _GLIBCXX_NOEXCEPT { return (*(_M_wp) & _Base::_S_maskbit(_M_bpos)) == 0; } // For __x = b[i]; operator bool() const _GLIBCXX_NOEXCEPT { return (*(_M_wp) & _Base::_S_maskbit(_M_bpos)) != 0; } // For b[i].flip(); reference& flip() _GLIBCXX_NOEXCEPT { *_M_wp ^= _Base::_S_maskbit(_M_bpos); return *this; } }; friend class reference; // 23.3.5.1 constructors: /// All bits set to zero. _GLIBCXX_CONSTEXPR bitset() _GLIBCXX_NOEXCEPT { } /// Initial bits bitwise-copied from a single word (others set to zero). #if __cplusplus >= 201103L constexpr bitset(unsigned long long __val) noexcept : _Base(_Sanitize_val<_Nb>::_S_do_sanitize_val(__val)) { } #else bitset(unsigned long __val) : _Base(__val) { _M_do_sanitize(); } #endif /** * Use a subset of a string. * @param __s A string of @a 0 and @a 1 characters. * @param __position Index of the first character in @a __s to use; * defaults to zero. * @throw std::out_of_range If @a pos is bigger the size of @a __s. * @throw std::invalid_argument If a character appears in the string * which is neither @a 0 nor @a 1. */ template explicit bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s, size_t __position = 0) : _Base() { _M_check_initial_position(__s, __position); _M_copy_from_string(__s, __position, std::basic_string<_CharT, _Traits, _Alloc>::npos, _CharT('0'), _CharT('1')); } /** * Use a subset of a string. * @param __s A string of @a 0 and @a 1 characters. * @param __position Index of the first character in @a __s to use. * @param __n The number of characters to copy. * @throw std::out_of_range If @a __position is bigger the size * of @a __s. * @throw std::invalid_argument If a character appears in the string * which is neither @a 0 nor @a 1. */ template bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s, size_t __position, size_t __n) : _Base() { _M_check_initial_position(__s, __position); _M_copy_from_string(__s, __position, __n, _CharT('0'), _CharT('1')); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. template bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __s, size_t __position, size_t __n, _CharT __zero, _CharT __one = _CharT('1')) : _Base() { _M_check_initial_position(__s, __position); _M_copy_from_string(__s, __position, __n, __zero, __one); } #if __cplusplus >= 201103L /** * Construct from a character %array. * @param __str An %array of characters @a zero and @a one. * @param __n The number of characters to use. * @param __zero The character corresponding to the value 0. * @param __one The character corresponding to the value 1. * @throw std::invalid_argument If a character appears in the string * which is neither @a __zero nor @a __one. */ template explicit bitset(const _CharT* __str, typename std::basic_string<_CharT>::size_type __n = std::basic_string<_CharT>::npos, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1')) : _Base() { if (!__str) __throw_logic_error(__N("bitset::bitset(const _CharT*, ...)")); if (__n == std::basic_string<_CharT>::npos) __n = std::char_traits<_CharT>::length(__str); _M_copy_from_ptr<_CharT, std::char_traits<_CharT>>(__str, __n, 0, __n, __zero, __one); } #endif // 23.3.5.2 bitset operations: //@{ /** * Operations on bitsets. * @param __rhs A same-sized bitset. * * These should be self-explanatory. */ bitset<_Nb>& operator&=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { this->_M_do_and(__rhs); return *this; } bitset<_Nb>& operator|=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { this->_M_do_or(__rhs); return *this; } bitset<_Nb>& operator^=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { this->_M_do_xor(__rhs); return *this; } //@} //@{ /** * Operations on bitsets. * @param __position The number of places to shift. * * These should be self-explanatory. */ bitset<_Nb>& operator<<=(size_t __position) _GLIBCXX_NOEXCEPT { if (__builtin_expect(__position < _Nb, 1)) { this->_M_do_left_shift(__position); this->_M_do_sanitize(); } else this->_M_do_reset(); return *this; } bitset<_Nb>& operator>>=(size_t __position) _GLIBCXX_NOEXCEPT { if (__builtin_expect(__position < _Nb, 1)) { this->_M_do_right_shift(__position); this->_M_do_sanitize(); } else this->_M_do_reset(); return *this; } //@} //@{ /** * These versions of single-bit set, reset, flip, and test are * extensions from the SGI version. They do no range checking. * @ingroup SGIextensions */ bitset<_Nb>& _Unchecked_set(size_t __pos) _GLIBCXX_NOEXCEPT { this->_M_getword(__pos) |= _Base::_S_maskbit(__pos); return *this; } bitset<_Nb>& _Unchecked_set(size_t __pos, int __val) _GLIBCXX_NOEXCEPT { if (__val) this->_M_getword(__pos) |= _Base::_S_maskbit(__pos); else this->_M_getword(__pos) &= ~_Base::_S_maskbit(__pos); return *this; } bitset<_Nb>& _Unchecked_reset(size_t __pos) _GLIBCXX_NOEXCEPT { this->_M_getword(__pos) &= ~_Base::_S_maskbit(__pos); return *this; } bitset<_Nb>& _Unchecked_flip(size_t __pos) _GLIBCXX_NOEXCEPT { this->_M_getword(__pos) ^= _Base::_S_maskbit(__pos); return *this; } _GLIBCXX_CONSTEXPR bool _Unchecked_test(size_t __pos) const _GLIBCXX_NOEXCEPT { return ((this->_M_getword(__pos) & _Base::_S_maskbit(__pos)) != static_cast<_WordT>(0)); } //@} // Set, reset, and flip. /** * @brief Sets every bit to true. */ bitset<_Nb>& set() _GLIBCXX_NOEXCEPT { this->_M_do_set(); this->_M_do_sanitize(); return *this; } /** * @brief Sets a given bit to a particular value. * @param __position The index of the bit. * @param __val Either true or false, defaults to true. * @throw std::out_of_range If @a pos is bigger the size of the %set. */ bitset<_Nb>& set(size_t __position, bool __val = true) { this->_M_check(__position, __N("bitset::set")); return _Unchecked_set(__position, __val); } /** * @brief Sets every bit to false. */ bitset<_Nb>& reset() _GLIBCXX_NOEXCEPT { this->_M_do_reset(); return *this; } /** * @brief Sets a given bit to false. * @param __position The index of the bit. * @throw std::out_of_range If @a pos is bigger the size of the %set. * * Same as writing @c set(pos,false). */ bitset<_Nb>& reset(size_t __position) { this->_M_check(__position, __N("bitset::reset")); return _Unchecked_reset(__position); } /** * @brief Toggles every bit to its opposite value. */ bitset<_Nb>& flip() _GLIBCXX_NOEXCEPT { this->_M_do_flip(); this->_M_do_sanitize(); return *this; } /** * @brief Toggles a given bit to its opposite value. * @param __position The index of the bit. * @throw std::out_of_range If @a pos is bigger the size of the %set. */ bitset<_Nb>& flip(size_t __position) { this->_M_check(__position, __N("bitset::flip")); return _Unchecked_flip(__position); } /// See the no-argument flip(). bitset<_Nb> operator~() const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(*this).flip(); } //@{ /** * @brief Array-indexing support. * @param __position Index into the %bitset. * @return A bool for a const %bitset. For non-const * bitsets, an instance of the reference proxy class. * @note These operators do no range checking and throw no exceptions, * as required by DR 11 to the standard. * * _GLIBCXX_RESOLVE_LIB_DEFECTS Note that this implementation already * resolves DR 11 (items 1 and 2), but does not do the range-checking * required by that DR's resolution. -pme * The DR has since been changed: range-checking is a precondition * (users' responsibility), and these functions must not throw. -pme */ reference operator[](size_t __position) { return reference(*this, __position); } _GLIBCXX_CONSTEXPR bool operator[](size_t __position) const { return _Unchecked_test(__position); } //@} /** * @brief Returns a numerical interpretation of the %bitset. * @return The integral equivalent of the bits. * @throw std::overflow_error If there are too many bits to be * represented in an @c unsigned @c long. */ unsigned long to_ulong() const { return this->_M_do_to_ulong(); } #if __cplusplus >= 201103L unsigned long long to_ullong() const { return this->_M_do_to_ullong(); } #endif /** * @brief Returns a character interpretation of the %bitset. * @return The string equivalent of the bits. * * Note the ordering of the bits: decreasing character positions * correspond to increasing bit positions (see the main class notes for * an example). */ template std::basic_string<_CharT, _Traits, _Alloc> to_string() const { std::basic_string<_CharT, _Traits, _Alloc> __result; _M_copy_to_string(__result, _CharT('0'), _CharT('1')); return __result; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. template std::basic_string<_CharT, _Traits, _Alloc> to_string(_CharT __zero, _CharT __one = _CharT('1')) const { std::basic_string<_CharT, _Traits, _Alloc> __result; _M_copy_to_string(__result, __zero, __one); return __result; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 434. bitset::to_string() hard to use. template std::basic_string<_CharT, _Traits, std::allocator<_CharT> > to_string() const { return to_string<_CharT, _Traits, std::allocator<_CharT> >(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 853. to_string needs updating with zero and one. template std::basic_string<_CharT, _Traits, std::allocator<_CharT> > to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return to_string<_CharT, _Traits, std::allocator<_CharT> >(__zero, __one); } template std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> > to_string() const { return to_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >(); } template std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> > to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return to_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >(__zero, __one); } std::basic_string, std::allocator > to_string() const { return to_string, std::allocator >(); } std::basic_string, std::allocator > to_string(char __zero, char __one = '1') const { return to_string, std::allocator >(__zero, __one); } // Helper functions for string operations. template void _M_copy_from_ptr(const _CharT*, size_t, size_t, size_t, _CharT, _CharT); template void _M_copy_from_string(const std::basic_string<_CharT, _Traits, _Alloc>& __s, size_t __pos, size_t __n, _CharT __zero, _CharT __one) { _M_copy_from_ptr<_CharT, _Traits>(__s.data(), __s.size(), __pos, __n, __zero, __one); } template void _M_copy_to_string(std::basic_string<_CharT, _Traits, _Alloc>&, _CharT, _CharT) const; // NB: Backward compat. template void _M_copy_from_string(const std::basic_string<_CharT, _Traits, _Alloc>& __s, size_t __pos, size_t __n) { _M_copy_from_string(__s, __pos, __n, _CharT('0'), _CharT('1')); } template void _M_copy_to_string(std::basic_string<_CharT, _Traits,_Alloc>& __s) const { _M_copy_to_string(__s, _CharT('0'), _CharT('1')); } /// Returns the number of bits which are set. size_t count() const _GLIBCXX_NOEXCEPT { return this->_M_do_count(); } /// Returns the total number of bits. _GLIBCXX_CONSTEXPR size_t size() const _GLIBCXX_NOEXCEPT { return _Nb; } //@{ /// These comparisons for equality/inequality are, well, @e bitwise. bool operator==(const bitset<_Nb>& __rhs) const _GLIBCXX_NOEXCEPT { return this->_M_is_equal(__rhs); } bool operator!=(const bitset<_Nb>& __rhs) const _GLIBCXX_NOEXCEPT { return !this->_M_is_equal(__rhs); } //@} /** * @brief Tests the value of a bit. * @param __position The index of a bit. * @return The value at @a pos. * @throw std::out_of_range If @a pos is bigger the size of the %set. */ bool test(size_t __position) const { this->_M_check(__position, __N("bitset::test")); return _Unchecked_test(__position); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 693. std::bitset::all() missing. /** * @brief Tests whether all the bits are on. * @return True if all the bits are set. */ bool all() const _GLIBCXX_NOEXCEPT { return this->template _M_are_all<_Nb>(); } /** * @brief Tests whether any of the bits are on. * @return True if at least one bit is set. */ bool any() const _GLIBCXX_NOEXCEPT { return this->_M_is_any(); } /** * @brief Tests whether any of the bits are on. * @return True if none of the bits are set. */ bool none() const _GLIBCXX_NOEXCEPT { return !this->_M_is_any(); } //@{ /// Self-explanatory. bitset<_Nb> operator<<(size_t __position) const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(*this) <<= __position; } bitset<_Nb> operator>>(size_t __position) const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(*this) >>= __position; } //@} /** * @brief Finds the index of the first "on" bit. * @return The index of the first bit set, or size() if not found. * @ingroup SGIextensions * @sa _Find_next */ size_t _Find_first() const _GLIBCXX_NOEXCEPT { return this->_M_do_find_first(_Nb); } /** * @brief Finds the index of the next "on" bit after prev. * @return The index of the next bit set, or size() if not found. * @param __prev Where to start searching. * @ingroup SGIextensions * @sa _Find_first */ size_t _Find_next(size_t __prev) const _GLIBCXX_NOEXCEPT { return this->_M_do_find_next(__prev, _Nb); } }; // Definitions of non-inline member functions. template template void bitset<_Nb>:: _M_copy_from_ptr(const _CharT* __s, size_t __len, size_t __pos, size_t __n, _CharT __zero, _CharT __one) { reset(); const size_t __nbits = std::min(_Nb, std::min(__n, size_t(__len - __pos))); for (size_t __i = __nbits; __i > 0; --__i) { const _CharT __c = __s[__pos + __nbits - __i]; if (_Traits::eq(__c, __zero)) ; else if (_Traits::eq(__c, __one)) _Unchecked_set(__i - 1); else __throw_invalid_argument(__N("bitset::_M_copy_from_ptr")); } } template template void bitset<_Nb>:: _M_copy_to_string(std::basic_string<_CharT, _Traits, _Alloc>& __s, _CharT __zero, _CharT __one) const { __s.assign(_Nb, __zero); for (size_t __i = _Nb; __i > 0; --__i) if (_Unchecked_test(__i - 1)) _Traits::assign(__s[_Nb - __i], __one); } // 23.3.5.3 bitset operations: //@{ /** * @brief Global bitwise operations on bitsets. * @param __x A bitset. * @param __y A bitset of the same size as @a __x. * @return A new bitset. * * These should be self-explanatory. */ template inline bitset<_Nb> operator&(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { bitset<_Nb> __result(__x); __result &= __y; return __result; } template inline bitset<_Nb> operator|(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { bitset<_Nb> __result(__x); __result |= __y; return __result; } template inline bitset<_Nb> operator^(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { bitset<_Nb> __result(__x); __result ^= __y; return __result; } //@} //@{ /** * @brief Global I/O operators for bitsets. * * Direct I/O between streams and bitsets is supported. Output is * straightforward. Input will skip whitespace, only accept @a 0 and @a 1 * characters, and will only extract as many digits as the %bitset will * hold. */ template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, bitset<_Nb>& __x) { typedef typename _Traits::char_type char_type; typedef std::basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::ios_base __ios_base; std::basic_string<_CharT, _Traits> __tmp; __tmp.reserve(_Nb); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 303. Bitset input operator underspecified const char_type __zero = __is.widen('0'); const char_type __one = __is.widen('1'); typename __ios_base::iostate __state = __ios_base::goodbit; typename __istream_type::sentry __sentry(__is); if (__sentry) { __try { for (size_t __i = _Nb; __i > 0; --__i) { static typename _Traits::int_type __eof = _Traits::eof(); typename _Traits::int_type __c1 = __is.rdbuf()->sbumpc(); if (_Traits::eq_int_type(__c1, __eof)) { __state |= __ios_base::eofbit; break; } else { const char_type __c2 = _Traits::to_char_type(__c1); if (_Traits::eq(__c2, __zero)) __tmp.push_back(__zero); else if (_Traits::eq(__c2, __one)) __tmp.push_back(__one); else if (_Traits:: eq_int_type(__is.rdbuf()->sputbackc(__c2), __eof)) { __state |= __ios_base::failbit; break; } } } } __catch(__cxxabiv1::__forced_unwind&) { __is._M_setstate(__ios_base::badbit); __throw_exception_again; } __catch(...) { __is._M_setstate(__ios_base::badbit); } } if (__tmp.empty() && _Nb) __state |= __ios_base::failbit; else __x._M_copy_from_string(__tmp, static_cast(0), _Nb, __zero, __one); if (__state) __is.setstate(__state); return __is; } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const bitset<_Nb>& __x) { std::basic_string<_CharT, _Traits> __tmp; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. const ctype<_CharT>& __ct = use_facet >(__os.getloc()); __x._M_copy_to_string(__tmp, __ct.widen('0'), __ct.widen('1')); return __os << __tmp; } //@} _GLIBCXX_END_NAMESPACE_CONTAINER } // namespace std #undef _GLIBCXX_BITSET_WORDS #undef _GLIBCXX_BITSET_BITS_PER_WORD #undef _GLIBCXX_BITSET_BITS_PER_ULL #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. /// std::hash specialization for bitset. template struct hash<_GLIBCXX_STD_C::bitset<_Nb>> : public __hash_base> { size_t operator()(const _GLIBCXX_STD_C::bitset<_Nb>& __b) const noexcept { const size_t __clength = (_Nb + __CHAR_BIT__ - 1) / __CHAR_BIT__; return std::_Hash_impl::hash(__b._M_getdata(), __clength); } }; template<> struct hash<_GLIBCXX_STD_C::bitset<0>> : public __hash_base> { size_t operator()(const _GLIBCXX_STD_C::bitset<0>&) const noexcept { return 0; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_BITSET */ c++/8/stack000064400000004527151027430570006327 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/stack * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_STACK #define _GLIBCXX_STACK 1 #pragma GCC system_header #include #include #endif /* _GLIBCXX_STACK */ c++/8/map000064400000004777151027430570006006 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/map * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_MAP #define _GLIBCXX_MAP 1 #pragma GCC system_header #include #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_MAP */ c++/8/cstddef000064400000014450151027430570006632 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file cstddef * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c stddef.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 18.1 Types // #ifndef _GLIBCXX_CSTDDEF #define _GLIBCXX_CSTDDEF 1 #pragma GCC system_header #undef __need_wchar_t #undef __need_ptrdiff_t #undef __need_size_t #undef __need_NULL #undef __need_wint_t #include #include #if __cplusplus >= 201103L namespace std { // We handle size_t, ptrdiff_t, and nullptr_t in c++config.h. using ::max_align_t; } #endif #if __cplusplus >= 201703L namespace std { #define __cpp_lib_byte 201603 /// std::byte enum class byte : unsigned char {}; template struct __byte_operand { }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #ifdef _GLIBCXX_USE_WCHAR_T template<> struct __byte_operand { using __type = byte; }; #endif template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #if defined(__GLIBCXX_TYPE_INT_N_0) template<> struct __byte_operand<__GLIBCXX_TYPE_INT_N_0> { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #endif #if defined(__GLIBCXX_TYPE_INT_N_1) template<> struct __byte_operand<__GLIBCXX_TYPE_INT_N_1> { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #endif #if defined(__GLIBCXX_TYPE_INT_N_2) template<> struct __byte_operand<__GLIBCXX_TYPE_INT_N_2> { using __type = byte; }; template<> struct __byte_operand { using __type = byte; }; #endif template struct __byte_operand : __byte_operand<_IntegerType> { }; template struct __byte_operand : __byte_operand<_IntegerType> { }; template struct __byte_operand : __byte_operand<_IntegerType> { }; template using __byte_op_t = typename __byte_operand<_IntegerType>::__type; template constexpr __byte_op_t<_IntegerType>& operator<<=(byte& __b, _IntegerType __shift) noexcept { return __b = byte(static_cast(__b) << __shift); } template constexpr __byte_op_t<_IntegerType> operator<<(byte __b, _IntegerType __shift) noexcept { return byte(static_cast(__b) << __shift); } template constexpr __byte_op_t<_IntegerType>& operator>>=(byte& __b, _IntegerType __shift) noexcept { return __b = byte(static_cast(__b) >> __shift); } template constexpr __byte_op_t<_IntegerType> operator>>(byte __b, _IntegerType __shift) noexcept { return byte(static_cast(__b) >> __shift); } constexpr byte& operator|=(byte& __l, byte __r) noexcept { return __l = byte(static_cast(__l) | static_cast(__r)); } constexpr byte operator|(byte __l, byte __r) noexcept { return byte(static_cast(__l) | static_cast(__r)); } constexpr byte& operator&=(byte& __l, byte __r) noexcept { return __l = byte(static_cast(__l) & static_cast(__r)); } constexpr byte operator&(byte __l, byte __r) noexcept { return byte(static_cast(__l) & static_cast(__r)); } constexpr byte& operator^=(byte& __l, byte __r) noexcept { return __l = byte(static_cast(__l) ^ static_cast(__r)); } constexpr byte operator^(byte __l, byte __r) noexcept { return byte(static_cast(__l) ^ static_cast(__r)); } constexpr byte operator~(byte __b) noexcept { return byte(~static_cast(__b)); } template constexpr _IntegerType to_integer(__byte_op_t<_IntegerType> __b) noexcept { return _IntegerType(__b); } } // namespace std #endif #endif // _GLIBCXX_CSTDDEF c++/8/vector000064400000005273151027430570006523 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/vector * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_VECTOR #define _GLIBCXX_VECTOR 1 #pragma GCC system_header #include #include #include #include #include #include #include #ifndef _GLIBCXX_EXPORT_TEMPLATE # include #endif #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_VECTOR */ c++/8/any000064400000044254151027430570006012 0ustar00// -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/any * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_ANY #define _GLIBCXX_ANY 1 #pragma GCC system_header #if __cplusplus >= 201703L #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ /** * @brief Exception class thrown by a failed @c any_cast * @ingroup exceptions */ class bad_any_cast : public bad_cast { public: virtual const char* what() const noexcept { return "bad any_cast"; } }; [[gnu::noreturn]] inline void __throw_bad_any_cast() { #if __cpp_exceptions throw bad_any_cast{}; #else __builtin_abort(); #endif } #define __cpp_lib_any 201606L /** * @brief A type-safe container of any type. * * An @c any object's state is either empty or it stores a contained object * of CopyConstructible type. */ class any { // Holds either pointer to a heap object or the contained object itself. union _Storage { constexpr _Storage() : _M_ptr{nullptr} {} // Prevent trivial copies of this type, buffer might hold a non-POD. _Storage(const _Storage&) = delete; _Storage& operator=(const _Storage&) = delete; void* _M_ptr; aligned_storage::type _M_buffer; }; template, bool _Fits = (sizeof(_Tp) <= sizeof(_Storage)) && (alignof(_Tp) <= alignof(_Storage))> using _Internal = std::integral_constant; template struct _Manager_internal; // uses small-object optimization template struct _Manager_external; // creates contained object on the heap template using _Manager = conditional_t<_Internal<_Tp>::value, _Manager_internal<_Tp>, _Manager_external<_Tp>>; template> using _Decay = enable_if_t::value, _Decayed>; /// Emplace with an object created from @p __args as the contained object. template > void __do_emplace(_Args&&... __args) { reset(); _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...); _M_manager = &_Mgr::_S_manage; } /// Emplace with an object created from @p __il and @p __args as /// the contained object. template > void __do_emplace(initializer_list<_Up> __il, _Args&&... __args) { reset(); _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...); _M_manager = &_Mgr::_S_manage; } public: // construct/destruct /// Default constructor, creates an empty object. constexpr any() noexcept : _M_manager(nullptr) { } /// Copy constructor, copies the state of @p __other any(const any& __other) { if (!__other.has_value()) _M_manager = nullptr; else { _Arg __arg; __arg._M_any = this; __other._M_manager(_Op_clone, &__other, &__arg); } } /** * @brief Move constructor, transfer the state from @p __other * * @post @c !__other.has_value() (this postcondition is a GNU extension) */ any(any&& __other) noexcept { if (!__other.has_value()) _M_manager = nullptr; else { _Arg __arg; __arg._M_any = this; __other._M_manager(_Op_xfer, &__other, &__arg); } } template using __any_constructible = enable_if<__and_, is_constructible<_Tp, _Args...>>::value, _Res>; template using __any_constructible_t = typename __any_constructible::type; /// Construct with a copy of @p __value as the contained object. template , typename _Mgr = _Manager<_Tp>, __any_constructible_t<_Tp, _ValueType&&> = true, enable_if_t::value, bool> = true> any(_ValueType&& __value) : _M_manager(&_Mgr::_S_manage) { _Mgr::_S_create(_M_storage, std::forward<_ValueType>(__value)); } /// Construct with a copy of @p __value as the contained object. template , typename _Mgr = _Manager<_Tp>, enable_if_t<__and_, __not_>, __not_<__is_in_place_type<_Tp>>>::value, bool> = false> any(_ValueType&& __value) : _M_manager(&_Mgr::_S_manage) { _Mgr::_S_create(_M_storage, __value); } /// Construct with an object created from @p __args as the contained object. template , typename _Mgr = _Manager<_Tp>, __any_constructible_t<_Tp, _Args&&...> = false> explicit any(in_place_type_t<_ValueType>, _Args&&... __args) : _M_manager(&_Mgr::_S_manage) { _Mgr::_S_create(_M_storage, std::forward<_Args>(__args)...); } /// Construct with an object created from @p __il and @p __args as /// the contained object. template , typename _Mgr = _Manager<_Tp>, __any_constructible_t<_Tp, initializer_list<_Up>, _Args&&...> = false> explicit any(in_place_type_t<_ValueType>, initializer_list<_Up> __il, _Args&&... __args) : _M_manager(&_Mgr::_S_manage) { _Mgr::_S_create(_M_storage, __il, std::forward<_Args>(__args)...); } /// Destructor, calls @c reset() ~any() { reset(); } // assignments /// Copy the state of another object. any& operator=(const any& __rhs) { *this = any(__rhs); return *this; } /** * @brief Move assignment operator * * @post @c !__rhs.has_value() (not guaranteed for other implementations) */ any& operator=(any&& __rhs) noexcept { if (!__rhs.has_value()) reset(); else if (this != &__rhs) { reset(); _Arg __arg; __arg._M_any = this; __rhs._M_manager(_Op_xfer, &__rhs, &__arg); } return *this; } /// Store a copy of @p __rhs as the contained object. template enable_if_t>::value, any&> operator=(_ValueType&& __rhs) { *this = any(std::forward<_ValueType>(__rhs)); return *this; } /// Emplace with an object created from @p __args as the contained object. template typename __any_constructible<_Decay<_ValueType>&, _Decay<_ValueType>, _Args&&...>::type emplace(_Args&&... __args) { __do_emplace<_Decay<_ValueType>>(std::forward<_Args>(__args)...); any::_Arg __arg; this->_M_manager(any::_Op_access, this, &__arg); return *static_cast<_Decay<_ValueType>*>(__arg._M_obj); } /// Emplace with an object created from @p __il and @p __args as /// the contained object. template typename __any_constructible<_Decay<_ValueType>&, _Decay<_ValueType>, initializer_list<_Up>, _Args&&...>::type emplace(initializer_list<_Up> __il, _Args&&... __args) { __do_emplace<_Decay<_ValueType>, _Up>(__il, std::forward<_Args>(__args)...); any::_Arg __arg; this->_M_manager(any::_Op_access, this, &__arg); return *static_cast<_Decay<_ValueType>*>(__arg._M_obj); } // modifiers /// If not empty, destroy the contained object. void reset() noexcept { if (has_value()) { _M_manager(_Op_destroy, this, nullptr); _M_manager = nullptr; } } /// Exchange state with another object. void swap(any& __rhs) noexcept { if (!has_value() && !__rhs.has_value()) return; if (has_value() && __rhs.has_value()) { if (this == &__rhs) return; any __tmp; _Arg __arg; __arg._M_any = &__tmp; __rhs._M_manager(_Op_xfer, &__rhs, &__arg); __arg._M_any = &__rhs; _M_manager(_Op_xfer, this, &__arg); __arg._M_any = this; __tmp._M_manager(_Op_xfer, &__tmp, &__arg); } else { any* __empty = !has_value() ? this : &__rhs; any* __full = !has_value() ? &__rhs : this; _Arg __arg; __arg._M_any = __empty; __full->_M_manager(_Op_xfer, __full, &__arg); } } // observers /// Reports whether there is a contained object or not. bool has_value() const noexcept { return _M_manager != nullptr; } #if __cpp_rtti /// The @c typeid of the contained object, or @c typeid(void) if empty. const type_info& type() const noexcept { if (!has_value()) return typeid(void); _Arg __arg; _M_manager(_Op_get_type_info, this, &__arg); return *__arg._M_typeinfo; } #endif template static constexpr bool __is_valid_cast() { return __or_, is_copy_constructible<_Tp>>::value; } private: enum _Op { _Op_access, _Op_get_type_info, _Op_clone, _Op_destroy, _Op_xfer }; union _Arg { void* _M_obj; const std::type_info* _M_typeinfo; any* _M_any; }; void (*_M_manager)(_Op, const any*, _Arg*); _Storage _M_storage; template friend void* __any_caster(const any* __any); // Manage in-place contained object. template struct _Manager_internal { static void _S_manage(_Op __which, const any* __anyp, _Arg* __arg); template static void _S_create(_Storage& __storage, _Up&& __value) { void* __addr = &__storage._M_buffer; ::new (__addr) _Tp(std::forward<_Up>(__value)); } template static void _S_create(_Storage& __storage, _Args&&... __args) { void* __addr = &__storage._M_buffer; ::new (__addr) _Tp(std::forward<_Args>(__args)...); } }; // Manage external contained object. template struct _Manager_external { static void _S_manage(_Op __which, const any* __anyp, _Arg* __arg); template static void _S_create(_Storage& __storage, _Up&& __value) { __storage._M_ptr = new _Tp(std::forward<_Up>(__value)); } template static void _S_create(_Storage& __storage, _Args&&... __args) { __storage._M_ptr = new _Tp(std::forward<_Args>(__args)...); } }; }; /// Exchange the states of two @c any objects. inline void swap(any& __x, any& __y) noexcept { __x.swap(__y); } /// Create an any holding a @c _Tp constructed from @c __args. template any make_any(_Args&&... __args) { return any(in_place_type<_Tp>, std::forward<_Args>(__args)...); } /// Create an any holding a @c _Tp constructed from @c __il and @c __args. template any make_any(initializer_list<_Up> __il, _Args&&... __args) { return any(in_place_type<_Tp>, __il, std::forward<_Args>(__args)...); } /** * @brief Access the contained object. * * @tparam _ValueType A const-reference or CopyConstructible type. * @param __any The object to access. * @return The contained object. * @throw bad_any_cast If * __any.type() != typeid(remove_reference_t<_ValueType>) * */ template inline _ValueType any_cast(const any& __any) { using _Up = remove_cv_t>; static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); static_assert(is_constructible_v<_ValueType, const _Up&>, "Template argument must be constructible from a const value."); auto __p = any_cast<_Up>(&__any); if (__p) return static_cast<_ValueType>(*__p); __throw_bad_any_cast(); } /** * @brief Access the contained object. * * @tparam _ValueType A reference or CopyConstructible type. * @param __any The object to access. * @return The contained object. * @throw bad_any_cast If * __any.type() != typeid(remove_reference_t<_ValueType>) * * * @{ */ template inline _ValueType any_cast(any& __any) { using _Up = remove_cv_t>; static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); static_assert(is_constructible_v<_ValueType, _Up&>, "Template argument must be constructible from an lvalue."); auto __p = any_cast<_Up>(&__any); if (__p) return static_cast<_ValueType>(*__p); __throw_bad_any_cast(); } template inline _ValueType any_cast(any&& __any) { using _Up = remove_cv_t>; static_assert(any::__is_valid_cast<_ValueType>(), "Template argument must be a reference or CopyConstructible type"); static_assert(is_constructible_v<_ValueType, _Up>, "Template argument must be constructible from an rvalue."); auto __p = any_cast<_Up>(&__any); if (__p) return static_cast<_ValueType>(std::move(*__p)); __throw_bad_any_cast(); } // @} /// @cond undocumented template void* __any_caster(const any* __any) { // any_cast returns non-null if __any->type() == typeid(T) and // typeid(T) ignores cv-qualifiers so remove them: using _Up = remove_cv_t<_Tp>; // The contained value has a decayed type, so if decay_t is not U, // then it's not possible to have a contained value of type U: if constexpr (!is_same_v, _Up>) return nullptr; // Only copy constructible types can be used for contained values: else if constexpr (!is_copy_constructible_v<_Up>) return nullptr; // First try comparing function addresses, which works without RTTI else if (__any->_M_manager == &any::_Manager<_Up>::_S_manage #if __cpp_rtti || __any->type() == typeid(_Tp) #endif ) { any::_Arg __arg; __any->_M_manager(any::_Op_access, __any, &__arg); return __arg._M_obj; } return nullptr; } /// @endcond /** * @brief Access the contained object. * * @tparam _ValueType The type of the contained object. * @param __any A pointer to the object to access. * @return The address of the contained object if * __any != nullptr && __any.type() == typeid(_ValueType) * , otherwise a null pointer. * * @{ */ template inline const _ValueType* any_cast(const any* __any) noexcept { if constexpr (is_object_v<_ValueType>) if (__any) return static_cast<_ValueType*>(__any_caster<_ValueType>(__any)); return nullptr; } template inline _ValueType* any_cast(any* __any) noexcept { if constexpr (is_object_v<_ValueType>) if (__any) return static_cast<_ValueType*>(__any_caster<_ValueType>(__any)); return nullptr; } // @} template void any::_Manager_internal<_Tp>:: _S_manage(_Op __which, const any* __any, _Arg* __arg) { // The contained object is in _M_storage._M_buffer auto __ptr = reinterpret_cast(&__any->_M_storage._M_buffer); switch (__which) { case _Op_access: __arg->_M_obj = const_cast<_Tp*>(__ptr); break; case _Op_get_type_info: #if __cpp_rtti __arg->_M_typeinfo = &typeid(_Tp); #endif break; case _Op_clone: ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp(*__ptr); __arg->_M_any->_M_manager = __any->_M_manager; break; case _Op_destroy: __ptr->~_Tp(); break; case _Op_xfer: ::new(&__arg->_M_any->_M_storage._M_buffer) _Tp (std::move(*const_cast<_Tp*>(__ptr))); __ptr->~_Tp(); __arg->_M_any->_M_manager = __any->_M_manager; const_cast(__any)->_M_manager = nullptr; break; } } template void any::_Manager_external<_Tp>:: _S_manage(_Op __which, const any* __any, _Arg* __arg) { // The contained object is *_M_storage._M_ptr auto __ptr = static_cast(__any->_M_storage._M_ptr); switch (__which) { case _Op_access: __arg->_M_obj = const_cast<_Tp*>(__ptr); break; case _Op_get_type_info: #if __cpp_rtti __arg->_M_typeinfo = &typeid(_Tp); #endif break; case _Op_clone: __arg->_M_any->_M_storage._M_ptr = new _Tp(*__ptr); __arg->_M_any->_M_manager = __any->_M_manager; break; case _Op_destroy: delete __ptr; break; case _Op_xfer: __arg->_M_any->_M_storage._M_ptr = __any->_M_storage._M_ptr; __arg->_M_any->_M_manager = __any->_M_manager; const_cast(__any)->_M_manager = nullptr; break; } } /// @} _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++14 #endif // _GLIBCXX_ANY c++/8/tuple000064400000165676151027430570006370 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/tuple * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_TUPLE #define _GLIBCXX_TUPLE 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup utilities * @{ */ template class tuple; template struct __is_empty_non_tuple : is_empty<_Tp> { }; // Using EBO for elements that are tuples causes ambiguous base errors. template struct __is_empty_non_tuple> : false_type { }; // Use the Empty Base-class Optimization for empty, non-final types. template using __empty_not_final = typename conditional<__is_final(_Tp), false_type, __is_empty_non_tuple<_Tp>>::type; template::value> struct _Head_base; template struct _Head_base<_Idx, _Head, true> : public _Head { constexpr _Head_base() : _Head() { } constexpr _Head_base(const _Head& __h) : _Head(__h) { } constexpr _Head_base(const _Head_base&) = default; constexpr _Head_base(_Head_base&&) = default; template constexpr _Head_base(_UHead&& __h) : _Head(std::forward<_UHead>(__h)) { } _Head_base(allocator_arg_t, __uses_alloc0) : _Head() { } template _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a) : _Head(allocator_arg, *__a._M_a) { } template _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a) : _Head(*__a._M_a) { } template _Head_base(__uses_alloc0, _UHead&& __uhead) : _Head(std::forward<_UHead>(__uhead)) { } template _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead) : _Head(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead)) { } template _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead) : _Head(std::forward<_UHead>(__uhead), *__a._M_a) { } static constexpr _Head& _M_head(_Head_base& __b) noexcept { return __b; } static constexpr const _Head& _M_head(const _Head_base& __b) noexcept { return __b; } }; template struct _Head_base<_Idx, _Head, false> { constexpr _Head_base() : _M_head_impl() { } constexpr _Head_base(const _Head& __h) : _M_head_impl(__h) { } constexpr _Head_base(const _Head_base&) = default; constexpr _Head_base(_Head_base&&) = default; template constexpr _Head_base(_UHead&& __h) : _M_head_impl(std::forward<_UHead>(__h)) { } _Head_base(allocator_arg_t, __uses_alloc0) : _M_head_impl() { } template _Head_base(allocator_arg_t, __uses_alloc1<_Alloc> __a) : _M_head_impl(allocator_arg, *__a._M_a) { } template _Head_base(allocator_arg_t, __uses_alloc2<_Alloc> __a) : _M_head_impl(*__a._M_a) { } template _Head_base(__uses_alloc0, _UHead&& __uhead) : _M_head_impl(std::forward<_UHead>(__uhead)) { } template _Head_base(__uses_alloc1<_Alloc> __a, _UHead&& __uhead) : _M_head_impl(allocator_arg, *__a._M_a, std::forward<_UHead>(__uhead)) { } template _Head_base(__uses_alloc2<_Alloc> __a, _UHead&& __uhead) : _M_head_impl(std::forward<_UHead>(__uhead), *__a._M_a) { } static constexpr _Head& _M_head(_Head_base& __b) noexcept { return __b._M_head_impl; } static constexpr const _Head& _M_head(const _Head_base& __b) noexcept { return __b._M_head_impl; } _Head _M_head_impl; }; /** * Contains the actual implementation of the @c tuple template, stored * as a recursive inheritance hierarchy from the first element (most * derived class) to the last (least derived class). The @c Idx * parameter gives the 0-based index of the element stored at this * point in the hierarchy; we use it to implement a constant-time * get() operation. */ template struct _Tuple_impl; /** * Recursive tuple implementation. Here we store the @c Head element * and derive from a @c Tuple_impl containing the remaining elements * (which contains the @c Tail). */ template struct _Tuple_impl<_Idx, _Head, _Tail...> : public _Tuple_impl<_Idx + 1, _Tail...>, private _Head_base<_Idx, _Head> { template friend class _Tuple_impl; typedef _Tuple_impl<_Idx + 1, _Tail...> _Inherited; typedef _Head_base<_Idx, _Head> _Base; static constexpr _Head& _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); } static constexpr const _Head& _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); } static constexpr _Inherited& _M_tail(_Tuple_impl& __t) noexcept { return __t; } static constexpr const _Inherited& _M_tail(const _Tuple_impl& __t) noexcept { return __t; } constexpr _Tuple_impl() : _Inherited(), _Base() { } explicit constexpr _Tuple_impl(const _Head& __head, const _Tail&... __tail) : _Inherited(__tail...), _Base(__head) { } template::type> explicit constexpr _Tuple_impl(_UHead&& __head, _UTail&&... __tail) : _Inherited(std::forward<_UTail>(__tail)...), _Base(std::forward<_UHead>(__head)) { } constexpr _Tuple_impl(const _Tuple_impl&) = default; constexpr _Tuple_impl(_Tuple_impl&& __in) noexcept(__and_, is_nothrow_move_constructible<_Inherited>>::value) : _Inherited(std::move(_M_tail(__in))), _Base(std::forward<_Head>(_M_head(__in))) { } template constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UElements...>& __in) : _Inherited(_Tuple_impl<_Idx, _UElements...>::_M_tail(__in)), _Base(_Tuple_impl<_Idx, _UElements...>::_M_head(__in)) { } template constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in) : _Inherited(std::move (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))), _Base(std::forward<_UHead> (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a) : _Inherited(__tag, __a), _Base(__tag, __use_alloc<_Head>(__a)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, const _Head& __head, const _Tail&... __tail) : _Inherited(__tag, __a, __tail...), _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { } template::type> _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, _UHead&& __head, _UTail&&... __tail) : _Inherited(__tag, __a, std::forward<_UTail>(__tail)...), _Base(__use_alloc<_Head, _Alloc, _UHead>(__a), std::forward<_UHead>(__head)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, const _Tuple_impl& __in) : _Inherited(__tag, __a, _M_tail(__in)), _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, _Tuple_impl&& __in) : _Inherited(__tag, __a, std::move(_M_tail(__in))), _Base(__use_alloc<_Head, _Alloc, _Head>(__a), std::forward<_Head>(_M_head(__in))) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, const _Tuple_impl<_Idx, _UHead, _UTails...>& __in) : _Inherited(__tag, __a, _Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in)), _Base(__use_alloc<_Head, _Alloc, const _UHead&>(__a), _Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, _Tuple_impl<_Idx, _UHead, _UTails...>&& __in) : _Inherited(__tag, __a, std::move (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in))), _Base(__use_alloc<_Head, _Alloc, _UHead>(__a), std::forward<_UHead> (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in))) { } _Tuple_impl& operator=(const _Tuple_impl& __in) { _M_head(*this) = _M_head(__in); _M_tail(*this) = _M_tail(__in); return *this; } _Tuple_impl& operator=(_Tuple_impl&& __in) noexcept(__and_, is_nothrow_move_assignable<_Inherited>>::value) { _M_head(*this) = std::forward<_Head>(_M_head(__in)); _M_tail(*this) = std::move(_M_tail(__in)); return *this; } template _Tuple_impl& operator=(const _Tuple_impl<_Idx, _UElements...>& __in) { _M_head(*this) = _Tuple_impl<_Idx, _UElements...>::_M_head(__in); _M_tail(*this) = _Tuple_impl<_Idx, _UElements...>::_M_tail(__in); return *this; } template _Tuple_impl& operator=(_Tuple_impl<_Idx, _UHead, _UTails...>&& __in) { _M_head(*this) = std::forward<_UHead> (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_head(__in)); _M_tail(*this) = std::move (_Tuple_impl<_Idx, _UHead, _UTails...>::_M_tail(__in)); return *this; } protected: void _M_swap(_Tuple_impl& __in) noexcept(__is_nothrow_swappable<_Head>::value && noexcept(_M_tail(__in)._M_swap(_M_tail(__in)))) { using std::swap; swap(_M_head(*this), _M_head(__in)); _Inherited::_M_swap(_M_tail(__in)); } }; // Basis case of inheritance recursion. template struct _Tuple_impl<_Idx, _Head> : private _Head_base<_Idx, _Head> { template friend class _Tuple_impl; typedef _Head_base<_Idx, _Head> _Base; static constexpr _Head& _M_head(_Tuple_impl& __t) noexcept { return _Base::_M_head(__t); } static constexpr const _Head& _M_head(const _Tuple_impl& __t) noexcept { return _Base::_M_head(__t); } constexpr _Tuple_impl() : _Base() { } explicit constexpr _Tuple_impl(const _Head& __head) : _Base(__head) { } template explicit constexpr _Tuple_impl(_UHead&& __head) : _Base(std::forward<_UHead>(__head)) { } constexpr _Tuple_impl(const _Tuple_impl&) = default; constexpr _Tuple_impl(_Tuple_impl&& __in) noexcept(is_nothrow_move_constructible<_Head>::value) : _Base(std::forward<_Head>(_M_head(__in))) { } template constexpr _Tuple_impl(const _Tuple_impl<_Idx, _UHead>& __in) : _Base(_Tuple_impl<_Idx, _UHead>::_M_head(__in)) { } template constexpr _Tuple_impl(_Tuple_impl<_Idx, _UHead>&& __in) : _Base(std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in))) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a) : _Base(__tag, __use_alloc<_Head>(__a)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, const _Head& __head) : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), __head) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, _UHead&& __head) : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a), std::forward<_UHead>(__head)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, const _Tuple_impl& __in) : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), _M_head(__in)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, _Tuple_impl&& __in) : _Base(__use_alloc<_Head, _Alloc, _Head>(__a), std::forward<_Head>(_M_head(__in))) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, const _Tuple_impl<_Idx, _UHead>& __in) : _Base(__use_alloc<_Head, _Alloc, const _UHead&>(__a), _Tuple_impl<_Idx, _UHead>::_M_head(__in)) { } template _Tuple_impl(allocator_arg_t __tag, const _Alloc& __a, _Tuple_impl<_Idx, _UHead>&& __in) : _Base(__use_alloc<_Head, _Alloc, _UHead>(__a), std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in))) { } _Tuple_impl& operator=(const _Tuple_impl& __in) { _M_head(*this) = _M_head(__in); return *this; } _Tuple_impl& operator=(_Tuple_impl&& __in) noexcept(is_nothrow_move_assignable<_Head>::value) { _M_head(*this) = std::forward<_Head>(_M_head(__in)); return *this; } template _Tuple_impl& operator=(const _Tuple_impl<_Idx, _UHead>& __in) { _M_head(*this) = _Tuple_impl<_Idx, _UHead>::_M_head(__in); return *this; } template _Tuple_impl& operator=(_Tuple_impl<_Idx, _UHead>&& __in) { _M_head(*this) = std::forward<_UHead>(_Tuple_impl<_Idx, _UHead>::_M_head(__in)); return *this; } protected: void _M_swap(_Tuple_impl& __in) noexcept(__is_nothrow_swappable<_Head>::value) { using std::swap; swap(_M_head(*this), _M_head(__in)); } }; // Concept utility functions, reused in conditionally-explicit // constructors. template struct _TC { template static constexpr bool _ConstructibleTuple() { return __and_...>::value; } template static constexpr bool _ImplicitlyConvertibleTuple() { return __and_...>::value; } template static constexpr bool _MoveConstructibleTuple() { return __and_...>::value; } template static constexpr bool _ImplicitlyMoveConvertibleTuple() { return __and_...>::value; } template static constexpr bool _NonNestedTuple() { return __and_<__not_, typename remove_cv< typename remove_reference<_SrcTuple>::type >::type>>, __not_>, __not_> >::value; } template static constexpr bool _NotSameTuple() { return __not_, typename remove_const< typename remove_reference<_UElements...>::type >::type>>::value; } }; template struct _TC { template static constexpr bool _ConstructibleTuple() { return false; } template static constexpr bool _ImplicitlyConvertibleTuple() { return false; } template static constexpr bool _MoveConstructibleTuple() { return false; } template static constexpr bool _ImplicitlyMoveConvertibleTuple() { return false; } template static constexpr bool _NonNestedTuple() { return true; } template static constexpr bool _NotSameTuple() { return true; } }; /// Primary class template, tuple template class tuple : public _Tuple_impl<0, _Elements...> { typedef _Tuple_impl<0, _Elements...> _Inherited; // Used for constraining the default constructor so // that it becomes dependent on the constraints. template struct _TC2 { static constexpr bool _DefaultConstructibleTuple() { return __and_...>::value; } static constexpr bool _ImplicitlyDefaultConstructibleTuple() { return __and_<__is_implicitly_default_constructible<_Elements>...> ::value; } }; public: template:: _ImplicitlyDefaultConstructibleTuple(), bool>::type = true> constexpr tuple() : _Inherited() { } template:: _DefaultConstructibleTuple() && !_TC2<_Dummy>:: _ImplicitlyDefaultConstructibleTuple(), bool>::type = false> explicit constexpr tuple() : _Inherited() { } // Shortcut for the cases where constructors taking _Elements... // need to be constrained. template using _TCC = _TC::value, _Elements...>; template::template _ConstructibleTuple<_Elements...>() && _TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_Elements...>() && (sizeof...(_Elements) >= 1), bool>::type=true> constexpr tuple(const _Elements&... __elements) : _Inherited(__elements...) { } template::template _ConstructibleTuple<_Elements...>() && !_TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_Elements...>() && (sizeof...(_Elements) >= 1), bool>::type=false> explicit constexpr tuple(const _Elements&... __elements) : _Inherited(__elements...) { } // Shortcut for the cases where constructors taking _UElements... // need to be constrained. template using _TMC = _TC<(sizeof...(_Elements) == sizeof...(_UElements)) && (_TC<(sizeof...(_UElements)==1), _Elements...>:: template _NotSameTuple<_UElements...>()), _Elements...>; // Shortcut for the cases where constructors taking tuple<_UElements...> // need to be constrained. template using _TMCT = _TC<(sizeof...(_Elements) == sizeof...(_UElements)) && !is_same, tuple<_UElements...>>::value, _Elements...>; template::template _MoveConstructibleTuple<_UElements...>() && _TMC<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>() && (sizeof...(_Elements) >= 1), bool>::type=true> constexpr tuple(_UElements&&... __elements) : _Inherited(std::forward<_UElements>(__elements)...) { } template::template _MoveConstructibleTuple<_UElements...>() && !_TMC<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>() && (sizeof...(_Elements) >= 1), bool>::type=false> explicit constexpr tuple(_UElements&&... __elements) : _Inherited(std::forward<_UElements>(__elements)...) { } constexpr tuple(const tuple&) = default; constexpr tuple(tuple&&) = default; // Shortcut for the cases where constructors taking tuples // must avoid creating temporaries. template using _TNTC = _TC::value && sizeof...(_Elements) == 1, _Elements...>; template::template _ConstructibleTuple<_UElements...>() && _TMCT<_UElements...>::template _ImplicitlyConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&>(), bool>::type=true> constexpr tuple(const tuple<_UElements...>& __in) : _Inherited(static_cast&>(__in)) { } template::template _ConstructibleTuple<_UElements...>() && !_TMCT<_UElements...>::template _ImplicitlyConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&>(), bool>::type=false> explicit constexpr tuple(const tuple<_UElements...>& __in) : _Inherited(static_cast&>(__in)) { } template::template _MoveConstructibleTuple<_UElements...>() && _TMCT<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&&>(), bool>::type=true> constexpr tuple(tuple<_UElements...>&& __in) : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { } template::template _MoveConstructibleTuple<_UElements...>() && !_TMCT<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&&>(), bool>::type=false> explicit constexpr tuple(tuple<_UElements...>&& __in) : _Inherited(static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { } // Allocator-extended constructors. template tuple(allocator_arg_t __tag, const _Alloc& __a) : _Inherited(__tag, __a) { } template::template _ConstructibleTuple<_Elements...>() && _TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_Elements...>(), bool>::type=true> tuple(allocator_arg_t __tag, const _Alloc& __a, const _Elements&... __elements) : _Inherited(__tag, __a, __elements...) { } template::template _ConstructibleTuple<_Elements...>() && !_TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_Elements...>(), bool>::type=false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, const _Elements&... __elements) : _Inherited(__tag, __a, __elements...) { } template::template _MoveConstructibleTuple<_UElements...>() && _TMC<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>(), bool>::type=true> tuple(allocator_arg_t __tag, const _Alloc& __a, _UElements&&... __elements) : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...) { } template::template _MoveConstructibleTuple<_UElements...>() && !_TMC<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>(), bool>::type=false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, _UElements&&... __elements) : _Inherited(__tag, __a, std::forward<_UElements>(__elements)...) { } template tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in) : _Inherited(__tag, __a, static_cast(__in)) { } template tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in) : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { } template::template _ConstructibleTuple<_UElements...>() && _TMCT<_UElements...>::template _ImplicitlyConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&&>(), bool>::type=true> tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple<_UElements...>& __in) : _Inherited(__tag, __a, static_cast&>(__in)) { } template::template _ConstructibleTuple<_UElements...>() && !_TMCT<_UElements...>::template _ImplicitlyConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&&>(), bool>::type=false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple<_UElements...>& __in) : _Inherited(__tag, __a, static_cast&>(__in)) { } template::template _MoveConstructibleTuple<_UElements...>() && _TMCT<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&&>(), bool>::type=true> tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_UElements...>&& __in) : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { } template::template _MoveConstructibleTuple<_UElements...>() && !_TMCT<_UElements...>::template _ImplicitlyMoveConvertibleTuple<_UElements...>() && _TNTC<_Dummy>::template _NonNestedTuple&&>(), bool>::type=false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_UElements...>&& __in) : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _UElements...>&&>(__in)) { } tuple& operator=(const tuple& __in) { static_cast<_Inherited&>(*this) = __in; return *this; } tuple& operator=(tuple&& __in) noexcept(is_nothrow_move_assignable<_Inherited>::value) { static_cast<_Inherited&>(*this) = std::move(__in); return *this; } template typename enable_if::type operator=(const tuple<_UElements...>& __in) { static_cast<_Inherited&>(*this) = __in; return *this; } template typename enable_if::type operator=(tuple<_UElements...>&& __in) { static_cast<_Inherited&>(*this) = std::move(__in); return *this; } void swap(tuple& __in) noexcept(noexcept(__in._M_swap(__in))) { _Inherited::_M_swap(__in); } }; #if __cpp_deduction_guides >= 201606 template tuple(_UTypes...) -> tuple<_UTypes...>; template tuple(pair<_T1, _T2>) -> tuple<_T1, _T2>; template tuple(allocator_arg_t, _Alloc, _UTypes...) -> tuple<_UTypes...>; template tuple(allocator_arg_t, _Alloc, pair<_T1, _T2>) -> tuple<_T1, _T2>; template tuple(allocator_arg_t, _Alloc, tuple<_UTypes...>) -> tuple<_UTypes...>; #endif // Explicit specialization, zero-element tuple. template<> class tuple<> { public: void swap(tuple&) noexcept { /* no-op */ } // We need the default since we're going to define no-op // allocator constructors. tuple() = default; // No-op allocator constructors. template tuple(allocator_arg_t, const _Alloc&) { } template tuple(allocator_arg_t, const _Alloc&, const tuple&) { } }; /// Partial specialization, 2-element tuple. /// Includes construction and assignment from a pair. template class tuple<_T1, _T2> : public _Tuple_impl<0, _T1, _T2> { typedef _Tuple_impl<0, _T1, _T2> _Inherited; public: template , __is_implicitly_default_constructible<_U2>> ::value, bool>::type = true> constexpr tuple() : _Inherited() { } template , is_default_constructible<_U2>, __not_< __and_<__is_implicitly_default_constructible<_U1>, __is_implicitly_default_constructible<_U2>>>> ::value, bool>::type = false> explicit constexpr tuple() : _Inherited() { } // Shortcut for the cases where constructors taking _T1, _T2 // need to be constrained. template using _TCC = _TC::value, _T1, _T2>; template::template _ConstructibleTuple<_T1, _T2>() && _TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_T1, _T2>(), bool>::type = true> constexpr tuple(const _T1& __a1, const _T2& __a2) : _Inherited(__a1, __a2) { } template::template _ConstructibleTuple<_T1, _T2>() && !_TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_T1, _T2>(), bool>::type = false> explicit constexpr tuple(const _T1& __a1, const _T2& __a2) : _Inherited(__a1, __a2) { } // Shortcut for the cases where constructors taking _U1, _U2 // need to be constrained. using _TMC = _TC; template() && _TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>() && !is_same::type, allocator_arg_t>::value, bool>::type = true> constexpr tuple(_U1&& __a1, _U2&& __a2) : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { } template() && !_TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>() && !is_same::type, allocator_arg_t>::value, bool>::type = false> explicit constexpr tuple(_U1&& __a1, _U2&& __a2) : _Inherited(std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { } constexpr tuple(const tuple&) = default; constexpr tuple(tuple&&) = default; template() && _TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = true> constexpr tuple(const tuple<_U1, _U2>& __in) : _Inherited(static_cast&>(__in)) { } template() && !_TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit constexpr tuple(const tuple<_U1, _U2>& __in) : _Inherited(static_cast&>(__in)) { } template() && _TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = true> constexpr tuple(tuple<_U1, _U2>&& __in) : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { } template() && !_TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit constexpr tuple(tuple<_U1, _U2>&& __in) : _Inherited(static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { } template() && _TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = true> constexpr tuple(const pair<_U1, _U2>& __in) : _Inherited(__in.first, __in.second) { } template() && !_TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit constexpr tuple(const pair<_U1, _U2>& __in) : _Inherited(__in.first, __in.second) { } template() && _TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = true> constexpr tuple(pair<_U1, _U2>&& __in) : _Inherited(std::forward<_U1>(__in.first), std::forward<_U2>(__in.second)) { } template() && !_TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit constexpr tuple(pair<_U1, _U2>&& __in) : _Inherited(std::forward<_U1>(__in.first), std::forward<_U2>(__in.second)) { } // Allocator-extended constructors. template tuple(allocator_arg_t __tag, const _Alloc& __a) : _Inherited(__tag, __a) { } template::template _ConstructibleTuple<_T1, _T2>() && _TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_T1, _T2>(), bool>::type=true> tuple(allocator_arg_t __tag, const _Alloc& __a, const _T1& __a1, const _T2& __a2) : _Inherited(__tag, __a, __a1, __a2) { } template::template _ConstructibleTuple<_T1, _T2>() && !_TCC<_Dummy>::template _ImplicitlyConvertibleTuple<_T1, _T2>(), bool>::type=false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, const _T1& __a1, const _T2& __a2) : _Inherited(__tag, __a, __a1, __a2) { } template() && _TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = true> tuple(allocator_arg_t __tag, const _Alloc& __a, _U1&& __a1, _U2&& __a2) : _Inherited(__tag, __a, std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { } template() && !_TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, _U1&& __a1, _U2&& __a2) : _Inherited(__tag, __a, std::forward<_U1>(__a1), std::forward<_U2>(__a2)) { } template tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple& __in) : _Inherited(__tag, __a, static_cast(__in)) { } template tuple(allocator_arg_t __tag, const _Alloc& __a, tuple&& __in) : _Inherited(__tag, __a, static_cast<_Inherited&&>(__in)) { } template() && _TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = true> tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple<_U1, _U2>& __in) : _Inherited(__tag, __a, static_cast&>(__in)) { } template() && !_TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, const tuple<_U1, _U2>& __in) : _Inherited(__tag, __a, static_cast&>(__in)) { } template() && _TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = true> tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_U1, _U2>&& __in) : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { } template() && !_TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, tuple<_U1, _U2>&& __in) : _Inherited(__tag, __a, static_cast<_Tuple_impl<0, _U1, _U2>&&>(__in)) { } template() && _TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = true> tuple(allocator_arg_t __tag, const _Alloc& __a, const pair<_U1, _U2>& __in) : _Inherited(__tag, __a, __in.first, __in.second) { } template() && !_TMC::template _ImplicitlyConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, const pair<_U1, _U2>& __in) : _Inherited(__tag, __a, __in.first, __in.second) { } template() && _TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = true> tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in) : _Inherited(__tag, __a, std::forward<_U1>(__in.first), std::forward<_U2>(__in.second)) { } template() && !_TMC::template _ImplicitlyMoveConvertibleTuple<_U1, _U2>(), bool>::type = false> explicit tuple(allocator_arg_t __tag, const _Alloc& __a, pair<_U1, _U2>&& __in) : _Inherited(__tag, __a, std::forward<_U1>(__in.first), std::forward<_U2>(__in.second)) { } tuple& operator=(const tuple& __in) { static_cast<_Inherited&>(*this) = __in; return *this; } tuple& operator=(tuple&& __in) noexcept(is_nothrow_move_assignable<_Inherited>::value) { static_cast<_Inherited&>(*this) = std::move(__in); return *this; } template tuple& operator=(const tuple<_U1, _U2>& __in) { static_cast<_Inherited&>(*this) = __in; return *this; } template tuple& operator=(tuple<_U1, _U2>&& __in) { static_cast<_Inherited&>(*this) = std::move(__in); return *this; } template tuple& operator=(const pair<_U1, _U2>& __in) { this->_M_head(*this) = __in.first; this->_M_tail(*this)._M_head(*this) = __in.second; return *this; } template tuple& operator=(pair<_U1, _U2>&& __in) { this->_M_head(*this) = std::forward<_U1>(__in.first); this->_M_tail(*this)._M_head(*this) = std::forward<_U2>(__in.second); return *this; } void swap(tuple& __in) noexcept(noexcept(__in._M_swap(__in))) { _Inherited::_M_swap(__in); } }; /// class tuple_size template struct tuple_size> : public integral_constant { }; #if __cplusplus > 201402L template inline constexpr size_t tuple_size_v = tuple_size<_Tp>::value; #endif /** * Recursive case for tuple_element: strip off the first element in * the tuple and retrieve the (i-1)th element of the remaining tuple. */ template struct tuple_element<__i, tuple<_Head, _Tail...> > : tuple_element<__i - 1, tuple<_Tail...> > { }; /** * Basis case for tuple_element: The first element is the one we're seeking. */ template struct tuple_element<0, tuple<_Head, _Tail...> > { typedef _Head type; }; /** * Error case for tuple_element: invalid index. */ template struct tuple_element<__i, tuple<>> { static_assert(__i < tuple_size>::value, "tuple index is in range"); }; template constexpr _Head& __get_helper(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); } template constexpr const _Head& __get_helper(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); } /// Return a reference to the ith element of a tuple. template constexpr __tuple_element_t<__i, tuple<_Elements...>>& get(tuple<_Elements...>& __t) noexcept { return std::__get_helper<__i>(__t); } /// Return a const reference to the ith element of a const tuple. template constexpr const __tuple_element_t<__i, tuple<_Elements...>>& get(const tuple<_Elements...>& __t) noexcept { return std::__get_helper<__i>(__t); } /// Return an rvalue reference to the ith element of a tuple rvalue. template constexpr __tuple_element_t<__i, tuple<_Elements...>>&& get(tuple<_Elements...>&& __t) noexcept { typedef __tuple_element_t<__i, tuple<_Elements...>> __element_type; return std::forward<__element_type&&>(std::get<__i>(__t)); } /// Return a const rvalue reference to the ith element of a const tuple rvalue. template constexpr const __tuple_element_t<__i, tuple<_Elements...>>&& get(const tuple<_Elements...>&& __t) noexcept { typedef __tuple_element_t<__i, tuple<_Elements...>> __element_type; return std::forward(std::get<__i>(__t)); } #if __cplusplus > 201103L #define __cpp_lib_tuples_by_type 201304 template constexpr _Head& __get_helper2(_Tuple_impl<__i, _Head, _Tail...>& __t) noexcept { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); } template constexpr const _Head& __get_helper2(const _Tuple_impl<__i, _Head, _Tail...>& __t) noexcept { return _Tuple_impl<__i, _Head, _Tail...>::_M_head(__t); } /// Return a reference to the unique element of type _Tp of a tuple. template constexpr _Tp& get(tuple<_Types...>& __t) noexcept { return std::__get_helper2<_Tp>(__t); } /// Return a reference to the unique element of type _Tp of a tuple rvalue. template constexpr _Tp&& get(tuple<_Types...>&& __t) noexcept { return std::forward<_Tp&&>(std::__get_helper2<_Tp>(__t)); } /// Return a const reference to the unique element of type _Tp of a tuple. template constexpr const _Tp& get(const tuple<_Types...>& __t) noexcept { return std::__get_helper2<_Tp>(__t); } /// Return a const reference to the unique element of type _Tp of /// a const tuple rvalue. template constexpr const _Tp&& get(const tuple<_Types...>&& __t) noexcept { return std::forward(std::__get_helper2<_Tp>(__t)); } #endif // This class performs the comparison operations on tuples template struct __tuple_compare { static constexpr bool __eq(const _Tp& __t, const _Up& __u) { return bool(std::get<__i>(__t) == std::get<__i>(__u)) && __tuple_compare<_Tp, _Up, __i + 1, __size>::__eq(__t, __u); } static constexpr bool __less(const _Tp& __t, const _Up& __u) { return bool(std::get<__i>(__t) < std::get<__i>(__u)) || (!bool(std::get<__i>(__u) < std::get<__i>(__t)) && __tuple_compare<_Tp, _Up, __i + 1, __size>::__less(__t, __u)); } }; template struct __tuple_compare<_Tp, _Up, __size, __size> { static constexpr bool __eq(const _Tp&, const _Up&) { return true; } static constexpr bool __less(const _Tp&, const _Up&) { return false; } }; template constexpr bool operator==(const tuple<_TElements...>& __t, const tuple<_UElements...>& __u) { static_assert(sizeof...(_TElements) == sizeof...(_UElements), "tuple objects can only be compared if they have equal sizes."); using __compare = __tuple_compare, tuple<_UElements...>, 0, sizeof...(_TElements)>; return __compare::__eq(__t, __u); } template constexpr bool operator<(const tuple<_TElements...>& __t, const tuple<_UElements...>& __u) { static_assert(sizeof...(_TElements) == sizeof...(_UElements), "tuple objects can only be compared if they have equal sizes."); using __compare = __tuple_compare, tuple<_UElements...>, 0, sizeof...(_TElements)>; return __compare::__less(__t, __u); } template constexpr bool operator!=(const tuple<_TElements...>& __t, const tuple<_UElements...>& __u) { return !(__t == __u); } template constexpr bool operator>(const tuple<_TElements...>& __t, const tuple<_UElements...>& __u) { return __u < __t; } template constexpr bool operator<=(const tuple<_TElements...>& __t, const tuple<_UElements...>& __u) { return !(__u < __t); } template constexpr bool operator>=(const tuple<_TElements...>& __t, const tuple<_UElements...>& __u) { return !(__t < __u); } // NB: DR 705. template constexpr tuple::__type...> make_tuple(_Elements&&... __args) { typedef tuple::__type...> __result_type; return __result_type(std::forward<_Elements>(__args)...); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2275. Why is forward_as_tuple not constexpr? template constexpr tuple<_Elements&&...> forward_as_tuple(_Elements&&... __args) noexcept { return tuple<_Elements&&...>(std::forward<_Elements>(__args)...); } template struct __make_tuple_impl; template struct __make_tuple_impl<_Idx, tuple<_Tp...>, _Tuple, _Nm> : __make_tuple_impl<_Idx + 1, tuple<_Tp..., __tuple_element_t<_Idx, _Tuple>>, _Tuple, _Nm> { }; template struct __make_tuple_impl<_Nm, tuple<_Tp...>, _Tuple, _Nm> { typedef tuple<_Tp...> __type; }; template struct __do_make_tuple : __make_tuple_impl<0, tuple<>, _Tuple, std::tuple_size<_Tuple>::value> { }; // Returns the std::tuple equivalent of a tuple-like type. template struct __make_tuple : public __do_make_tuple::type>::type> { }; // Combines several std::tuple's into a single one. template struct __combine_tuples; template<> struct __combine_tuples<> { typedef tuple<> __type; }; template struct __combine_tuples> { typedef tuple<_Ts...> __type; }; template struct __combine_tuples, tuple<_T2s...>, _Rem...> { typedef typename __combine_tuples, _Rem...>::__type __type; }; // Computes the result type of tuple_cat given a set of tuple-like types. template struct __tuple_cat_result { typedef typename __combine_tuples ::__type...>::__type __type; }; // Helper to determine the index set for the first tuple-like // type of a given set. template struct __make_1st_indices; template<> struct __make_1st_indices<> { typedef std::_Index_tuple<> __type; }; template struct __make_1st_indices<_Tp, _Tpls...> { typedef typename std::_Build_index_tuple::type>::value>::__type __type; }; // Performs the actual concatenation by step-wise expanding tuple-like // objects into the elements, which are finally forwarded into the // result tuple. template struct __tuple_concater; template struct __tuple_concater<_Ret, std::_Index_tuple<_Is...>, _Tp, _Tpls...> { template static constexpr _Ret _S_do(_Tp&& __tp, _Tpls&&... __tps, _Us&&... __us) { typedef typename __make_1st_indices<_Tpls...>::__type __idx; typedef __tuple_concater<_Ret, __idx, _Tpls...> __next; return __next::_S_do(std::forward<_Tpls>(__tps)..., std::forward<_Us>(__us)..., std::get<_Is>(std::forward<_Tp>(__tp))...); } }; template struct __tuple_concater<_Ret, std::_Index_tuple<>> { template static constexpr _Ret _S_do(_Us&&... __us) { return _Ret(std::forward<_Us>(__us)...); } }; /// tuple_cat template...>::value>::type> constexpr auto tuple_cat(_Tpls&&... __tpls) -> typename __tuple_cat_result<_Tpls...>::__type { typedef typename __tuple_cat_result<_Tpls...>::__type __ret; typedef typename __make_1st_indices<_Tpls...>::__type __idx; typedef __tuple_concater<__ret, __idx, _Tpls...> __concater; return __concater::_S_do(std::forward<_Tpls>(__tpls)...); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2301. Why is tie not constexpr? /// tie template constexpr tuple<_Elements&...> tie(_Elements&... __args) noexcept { return tuple<_Elements&...>(__args...); } /// swap template inline #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 // Constrained free swap overload, see p0185r1 typename enable_if<__and_<__is_swappable<_Elements>...>::value >::type #else void #endif swap(tuple<_Elements...>& __x, tuple<_Elements...>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if...>::value>::type swap(tuple<_Elements...>&, tuple<_Elements...>&) = delete; #endif // A class (and instance) which can be used in 'tie' when an element // of a tuple is not required. // _GLIBCXX14_CONSTEXPR // 2933. PR for LWG 2773 could be clearer struct _Swallow_assign { template _GLIBCXX14_CONSTEXPR const _Swallow_assign& operator=(const _Tp&) const { return *this; } }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2773. Making std::ignore constexpr _GLIBCXX17_INLINE constexpr _Swallow_assign ignore{}; /// Partial specialization for tuples template struct uses_allocator, _Alloc> : true_type { }; // See stl_pair.h... template template inline pair<_T1, _T2>:: pair(piecewise_construct_t, tuple<_Args1...> __first, tuple<_Args2...> __second) : pair(__first, __second, typename _Build_index_tuple::__type(), typename _Build_index_tuple::__type()) { } template template inline pair<_T1, _T2>:: pair(tuple<_Args1...>& __tuple1, tuple<_Args2...>& __tuple2, _Index_tuple<_Indexes1...>, _Index_tuple<_Indexes2...>) : first(std::forward<_Args1>(std::get<_Indexes1>(__tuple1))...), second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...) { } #if __cplusplus > 201402L # define __cpp_lib_apply 201603 template constexpr decltype(auto) __apply_impl(_Fn&& __f, _Tuple&& __t, index_sequence<_Idx...>) { return std::__invoke(std::forward<_Fn>(__f), std::get<_Idx>(std::forward<_Tuple>(__t))...); } template constexpr decltype(auto) apply(_Fn&& __f, _Tuple&& __t) { using _Indices = make_index_sequence>>; return std::__apply_impl(std::forward<_Fn>(__f), std::forward<_Tuple>(__t), _Indices{}); } #define __cpp_lib_make_from_tuple 201606 template constexpr _Tp __make_from_tuple_impl(_Tuple&& __t, index_sequence<_Idx...>) { return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...); } template constexpr _Tp make_from_tuple(_Tuple&& __t) { return __make_from_tuple_impl<_Tp>( std::forward<_Tuple>(__t), make_index_sequence>>{}); } #endif // C++17 /// @} _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++11 #endif // _GLIBCXX_TUPLE c++/8/thread000064400000024427151027430570006472 0ustar00// -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/thread * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_THREAD #define _GLIBCXX_THREAD 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include #include #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup threads Threads * @ingroup concurrency * * Classes for thread support. * @{ */ /// thread class thread { public: // Abstract base class for types that wrap arbitrary functors to be // invoked in the new thread of execution. struct _State { virtual ~_State(); virtual void _M_run() = 0; }; using _State_ptr = unique_ptr<_State>; typedef __gthread_t native_handle_type; /// thread::id class id { native_handle_type _M_thread; public: id() noexcept : _M_thread() { } explicit id(native_handle_type __id) : _M_thread(__id) { } private: friend class thread; friend class hash; friend bool operator==(thread::id __x, thread::id __y) noexcept; friend bool operator<(thread::id __x, thread::id __y) noexcept; template friend basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id); }; private: id _M_id; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2097. packaged_task constructors should be constrained template using __not_same = __not_::type>::type, thread>>; public: thread() noexcept = default; template>> explicit thread(_Callable&& __f, _Args&&... __args) { static_assert( __is_invocable::type, typename decay<_Args>::type...>::value, "std::thread arguments must be invocable after conversion to rvalues" ); #ifdef GTHR_ACTIVE_PROXY // Create a reference to pthread_create, not just the gthr weak symbol. auto __depend = reinterpret_cast(&pthread_create); #else auto __depend = nullptr; #endif _M_start_thread(_S_make_state( __make_invoker(std::forward<_Callable>(__f), std::forward<_Args>(__args)...)), __depend); } ~thread() { if (joinable()) std::terminate(); } thread(const thread&) = delete; thread(thread&& __t) noexcept { swap(__t); } thread& operator=(const thread&) = delete; thread& operator=(thread&& __t) noexcept { if (joinable()) std::terminate(); swap(__t); return *this; } void swap(thread& __t) noexcept { std::swap(_M_id, __t._M_id); } bool joinable() const noexcept { return !(_M_id == id()); } void join(); void detach(); thread::id get_id() const noexcept { return _M_id; } /** @pre thread is joinable */ native_handle_type native_handle() { return _M_id._M_thread; } // Returns a value that hints at the number of hardware thread contexts. static unsigned int hardware_concurrency() noexcept; private: template struct _State_impl : public _State { _Callable _M_func; _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f)) { } void _M_run() { _M_func(); } }; void _M_start_thread(_State_ptr, void (*)()); template static _State_ptr _S_make_state(_Callable&& __f) { using _Impl = _State_impl<_Callable>; return _State_ptr{new _Impl{std::forward<_Callable>(__f)}}; } #if _GLIBCXX_THREAD_ABI_COMPAT public: struct _Impl_base; typedef shared_ptr<_Impl_base> __shared_base_type; struct _Impl_base { __shared_base_type _M_this_ptr; virtual ~_Impl_base() = default; virtual void _M_run() = 0; }; private: void _M_start_thread(__shared_base_type, void (*)()); void _M_start_thread(__shared_base_type); #endif private: // A call wrapper that does INVOKE(forwarded tuple elements...) template struct _Invoker { _Tuple _M_t; template static __tuple_element_t<_Index, _Tuple>&& _S_declval(); template auto _M_invoke(_Index_tuple<_Ind...>) noexcept(noexcept(std::__invoke(_S_declval<_Ind>()...))) -> decltype(std::__invoke(_S_declval<_Ind>()...)) { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); } using _Indices = typename _Build_index_tuple::value>::__type; auto operator()() noexcept(noexcept(std::declval<_Invoker&>()._M_invoke(_Indices()))) -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices())) { return _M_invoke(_Indices()); } }; template using __decayed_tuple = tuple::type...>; public: // Returns a call wrapper that stores // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}. template static _Invoker<__decayed_tuple<_Callable, _Args...>> __make_invoker(_Callable&& __callable, _Args&&... __args) { return { __decayed_tuple<_Callable, _Args...>{ std::forward<_Callable>(__callable), std::forward<_Args>(__args)... } }; } }; inline void swap(thread& __x, thread& __y) noexcept { __x.swap(__y); } inline bool operator==(thread::id __x, thread::id __y) noexcept { // pthread_equal is undefined if either thread ID is not valid, so we // can't safely use __gthread_equal on default-constructed values (nor // the non-zero value returned by this_thread::get_id() for // single-threaded programs using GNU libc). Assume EqualityComparable. return __x._M_thread == __y._M_thread; } inline bool operator!=(thread::id __x, thread::id __y) noexcept { return !(__x == __y); } inline bool operator<(thread::id __x, thread::id __y) noexcept { // Pthreads doesn't define any way to do this, so we just have to // assume native_handle_type is LessThanComparable. return __x._M_thread < __y._M_thread; } inline bool operator<=(thread::id __x, thread::id __y) noexcept { return !(__y < __x); } inline bool operator>(thread::id __x, thread::id __y) noexcept { return __y < __x; } inline bool operator>=(thread::id __x, thread::id __y) noexcept { return !(__x < __y); } // DR 889. /// std::hash specialization for thread::id. template<> struct hash : public __hash_base { size_t operator()(const thread::id& __id) const noexcept { return std::_Hash_impl::hash(__id._M_thread); } }; template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id) { if (__id == thread::id()) return __out << "thread::id of a non-executing thread"; else return __out << __id._M_thread; } /** @namespace std::this_thread * @brief ISO C++ 2011 entities sub-namespace for thread. * 30.3.2 Namespace this_thread. */ namespace this_thread { /// get_id inline thread::id get_id() noexcept { #ifdef __GLIBC__ // For the GNU C library pthread_self() is usable without linking to // libpthread.so but returns 0, so we cannot use it in single-threaded // programs, because this_thread::get_id() != thread::id{} must be true. // We know that pthread_t is an integral type in the GNU C library. if (!__gthread_active_p()) return thread::id(1); #endif return thread::id(__gthread_self()); } /// yield inline void yield() noexcept { #ifdef _GLIBCXX_USE_SCHED_YIELD __gthread_yield(); #endif } void __sleep_for(chrono::seconds, chrono::nanoseconds); /// sleep_for template inline void sleep_for(const chrono::duration<_Rep, _Period>& __rtime) { if (__rtime <= __rtime.zero()) return; auto __s = chrono::duration_cast(__rtime); auto __ns = chrono::duration_cast(__rtime - __s); #ifdef _GLIBCXX_USE_NANOSLEEP __gthread_time_t __ts = { static_cast(__s.count()), static_cast(__ns.count()) }; while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR) { } #else __sleep_for(__s, __ns); #endif } /// sleep_until template inline void sleep_until(const chrono::time_point<_Clock, _Duration>& __atime) { auto __now = _Clock::now(); if (_Clock::is_steady) { if (__now < __atime) sleep_for(__atime - __now); return; } while (__now < __atime) { sleep_for(__atime - __now); __now = _Clock::now(); } } } // @} group threads _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1 #endif // C++11 #endif // _GLIBCXX_THREAD c++/8/ctime000064400000004115151027430570006314 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/ctime * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c time.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.5 Date and time // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CTIME #define _GLIBCXX_CTIME 1 // Get rid of those macros defined in in lieu of real functions. #undef clock #undef difftime #undef mktime #undef time #undef asctime #undef ctime #undef gmtime #undef localtime #undef strftime namespace std { using ::clock_t; using ::time_t; using ::tm; using ::clock; using ::difftime; using ::mktime; using ::time; using ::asctime; using ::ctime; using ::gmtime; using ::localtime; using ::strftime; } // namespace #endif c++/8/cstdlib000064400000014265151027430570006646 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cstdlib * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c stdlib.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #ifndef _GLIBCXX_CSTDLIB #define _GLIBCXX_CSTDLIB 1 #if !_GLIBCXX_HOSTED // The C standard does not require a freestanding implementation to // provide . However, the C++ standard does still require // -- but only the functionality mentioned in // [lib.support.start.term]. #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 namespace std { extern "C" void abort(void) throw () _GLIBCXX_NORETURN; extern "C" int atexit(void (*)(void)) throw (); extern "C" void exit(int) throw () _GLIBCXX_NORETURN; #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT extern "C" int at_quick_exit(void (*)(void)) throw (); # endif # ifdef _GLIBCXX_HAVE_QUICK_EXIT extern "C" void quick_exit(int) throw() _GLIBCXX_NORETURN; # endif #endif } // namespace std #else // Need to ensure this finds the C library's not a libstdc++ // wrapper that might already be installed later in the include search path. #define _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include_next #undef _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include // Get rid of those macros defined in in lieu of real functions. #undef abort #if __cplusplus >= 201703L && defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) # undef aligned_alloc #endif #undef atexit #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT # undef at_quick_exit # endif #endif #undef atof #undef atoi #undef atol #undef bsearch #undef calloc #undef div #undef exit #undef free #undef getenv #undef labs #undef ldiv #undef malloc #undef mblen #undef mbstowcs #undef mbtowc #undef qsort #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_QUICK_EXIT # undef quick_exit # endif #endif #undef rand #undef realloc #undef srand #undef strtod #undef strtol #undef strtoul #undef system #undef wcstombs #undef wctomb extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::div_t; using ::ldiv_t; using ::abort; #if __cplusplus >= 201703L && defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) using ::aligned_alloc; #endif using ::atexit; #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT using ::at_quick_exit; # endif #endif using ::atof; using ::atoi; using ::atol; using ::bsearch; using ::calloc; using ::div; using ::exit; using ::free; using ::getenv; using ::labs; using ::ldiv; using ::malloc; #ifdef _GLIBCXX_HAVE_MBSTATE_T using ::mblen; using ::mbstowcs; using ::mbtowc; #endif // _GLIBCXX_HAVE_MBSTATE_T using ::qsort; #if __cplusplus >= 201103L # ifdef _GLIBCXX_HAVE_QUICK_EXIT using ::quick_exit; # endif #endif using ::rand; using ::realloc; using ::srand; using ::strtod; using ::strtol; using ::strtoul; using ::system; #ifdef _GLIBCXX_USE_WCHAR_T using ::wcstombs; using ::wctomb; #endif // _GLIBCXX_USE_WCHAR_T #ifndef __CORRECT_ISO_CPP_STDLIB_H_PROTO inline ldiv_t div(long __i, long __j) { return ldiv(__i, __j); } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if _GLIBCXX_USE_C99_STDLIB #undef _Exit #undef llabs #undef lldiv #undef atoll #undef strtoll #undef strtoull #undef strtof #undef strtold namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::lldiv_t; #endif #if _GLIBCXX_USE_C99_CHECK || _GLIBCXX_USE_C99_DYNAMIC extern "C" void (_Exit)(int) throw () _GLIBCXX_NORETURN; #endif #if !_GLIBCXX_USE_C99_DYNAMIC using ::_Exit; #endif #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::llabs; inline lldiv_t div(long long __n, long long __d) { lldiv_t __q; __q.quot = __n / __d; __q.rem = __n % __d; return __q; } using ::lldiv; #endif #if _GLIBCXX_USE_C99_LONG_LONG_CHECK || _GLIBCXX_USE_C99_LONG_LONG_DYNAMIC extern "C" long long int (atoll)(const char *) throw (); extern "C" long long int (strtoll)(const char * __restrict, char ** __restrict, int) throw (); extern "C" unsigned long long int (strtoull)(const char * __restrict, char ** __restrict, int) throw (); #endif #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::atoll; using ::strtoll; using ::strtoull; #endif using ::strtof; using ::strtold; _GLIBCXX_END_NAMESPACE_VERSION } // namespace __gnu_cxx namespace std { #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::__gnu_cxx::lldiv_t; #endif using ::__gnu_cxx::_Exit; #if !_GLIBCXX_USE_C99_LONG_LONG_DYNAMIC using ::__gnu_cxx::llabs; using ::__gnu_cxx::div; using ::__gnu_cxx::lldiv; #endif using ::__gnu_cxx::atoll; using ::__gnu_cxx::strtof; using ::__gnu_cxx::strtoll; using ::__gnu_cxx::strtoull; using ::__gnu_cxx::strtold; } // namespace std #endif // _GLIBCXX_USE_C99_STDLIB } // extern "C++" #endif // !_GLIBCXX_HOSTED #endif c++/8/iostream000064400000005207151027430570007041 0ustar00// Standard iostream objects -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/iostream * This is a Standard C++ Library header. */ // // ISO C++ 14882: 27.3 Standard iostream objects // #ifndef _GLIBCXX_IOSTREAM #define _GLIBCXX_IOSTREAM 1 #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @name Standard Stream Objects * * The <iostream> header declares the eight standard stream * objects. For other declarations, see * http://gcc.gnu.org/onlinedocs/libstdc++/manual/io.html * and the @link iosfwd I/O forward declarations @endlink * * They are required by default to cooperate with the global C * library's @c FILE streams, and to be available during program * startup and termination. For more information, see the section of the * manual linked to above. */ //@{ extern istream cin; /// Linked to standard input extern ostream cout; /// Linked to standard output extern ostream cerr; /// Linked to standard error (unbuffered) extern ostream clog; /// Linked to standard error (buffered) #ifdef _GLIBCXX_USE_WCHAR_T extern wistream wcin; /// Linked to standard input extern wostream wcout; /// Linked to standard output extern wostream wcerr; /// Linked to standard error (unbuffered) extern wostream wclog; /// Linked to standard error (buffered) #endif //@} // For construction of filebuffers for cout, cin, cerr, clog et. al. static ios_base::Init __ioinit; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GLIBCXX_IOSTREAM */ c++/8/iomanip000064400000040243151027430570006651 0ustar00// Standard stream manipulators -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/iomanip * This is a Standard C++ Library header. */ // // ISO C++ 14882: 27.6.3 Standard manipulators // #ifndef _GLIBCXX_IOMANIP #define _GLIBCXX_IOMANIP 1 #pragma GCC system_header #include #include #include #if __cplusplus >= 201103L #include #if __cplusplus > 201103L #include #endif #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // [27.6.3] standard manipulators // Also see DR 183. struct _Resetiosflags { ios_base::fmtflags _M_mask; }; /** * @brief Manipulator for @c setf. * @param __mask A format flags mask. * * Sent to a stream object, this manipulator resets the specified flags, * via @e stream.setf(0,__mask). */ inline _Resetiosflags resetiosflags(ios_base::fmtflags __mask) { return { __mask }; } template inline basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Resetiosflags __f) { __is.setf(ios_base::fmtflags(0), __f._M_mask); return __is; } template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Resetiosflags __f) { __os.setf(ios_base::fmtflags(0), __f._M_mask); return __os; } struct _Setiosflags { ios_base::fmtflags _M_mask; }; /** * @brief Manipulator for @c setf. * @param __mask A format flags mask. * * Sent to a stream object, this manipulator sets the format flags * to @a __mask. */ inline _Setiosflags setiosflags(ios_base::fmtflags __mask) { return { __mask }; } template inline basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Setiosflags __f) { __is.setf(__f._M_mask); return __is; } template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Setiosflags __f) { __os.setf(__f._M_mask); return __os; } struct _Setbase { int _M_base; }; /** * @brief Manipulator for @c setf. * @param __base A numeric base. * * Sent to a stream object, this manipulator changes the * @c ios_base::basefield flags to @c oct, @c dec, or @c hex when @a base * is 8, 10, or 16, accordingly, and to 0 if @a __base is any other value. */ inline _Setbase setbase(int __base) { return { __base }; } template inline basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Setbase __f) { __is.setf(__f._M_base == 8 ? ios_base::oct : __f._M_base == 10 ? ios_base::dec : __f._M_base == 16 ? ios_base::hex : ios_base::fmtflags(0), ios_base::basefield); return __is; } template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Setbase __f) { __os.setf(__f._M_base == 8 ? ios_base::oct : __f._M_base == 10 ? ios_base::dec : __f._M_base == 16 ? ios_base::hex : ios_base::fmtflags(0), ios_base::basefield); return __os; } template struct _Setfill { _CharT _M_c; }; /** * @brief Manipulator for @c fill. * @param __c The new fill character. * * Sent to a stream object, this manipulator calls @c fill(__c) for that * object. */ template inline _Setfill<_CharT> setfill(_CharT __c) { return { __c }; } template inline basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Setfill<_CharT> __f) { __is.fill(__f._M_c); return __is; } template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Setfill<_CharT> __f) { __os.fill(__f._M_c); return __os; } struct _Setprecision { int _M_n; }; /** * @brief Manipulator for @c precision. * @param __n The new precision. * * Sent to a stream object, this manipulator calls @c precision(__n) for * that object. */ inline _Setprecision setprecision(int __n) { return { __n }; } template inline basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Setprecision __f) { __is.precision(__f._M_n); return __is; } template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Setprecision __f) { __os.precision(__f._M_n); return __os; } struct _Setw { int _M_n; }; /** * @brief Manipulator for @c width. * @param __n The new width. * * Sent to a stream object, this manipulator calls @c width(__n) for * that object. */ inline _Setw setw(int __n) { return { __n }; } template inline basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Setw __f) { __is.width(__f._M_n); return __is; } template inline basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Setw __f) { __os.width(__f._M_n); return __os; } #if __cplusplus >= 201103L template struct _Get_money { _MoneyT& _M_mon; bool _M_intl; }; /** * @brief Extended manipulator for extracting money. * @param __mon Either long double or a specialization of @c basic_string. * @param __intl A bool indicating whether international format * is to be used. * * Sent to a stream object, this manipulator extracts @a __mon. */ template inline _Get_money<_MoneyT> get_money(_MoneyT& __mon, bool __intl = false) { return { __mon, __intl }; } template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Get_money<_MoneyT> __f) { typename basic_istream<_CharT, _Traits>::sentry __cerb(__is, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { typedef istreambuf_iterator<_CharT, _Traits> _Iter; typedef money_get<_CharT, _Iter> _MoneyGet; const _MoneyGet& __mg = use_facet<_MoneyGet>(__is.getloc()); __mg.get(_Iter(__is.rdbuf()), _Iter(), __f._M_intl, __is, __err, __f._M_mon); } __catch(__cxxabiv1::__forced_unwind&) { __is._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __is._M_setstate(ios_base::badbit); } if (__err) __is.setstate(__err); } return __is; } template struct _Put_money { const _MoneyT& _M_mon; bool _M_intl; }; /** * @brief Extended manipulator for inserting money. * @param __mon Either long double or a specialization of @c basic_string. * @param __intl A bool indicating whether international format * is to be used. * * Sent to a stream object, this manipulator inserts @a __mon. */ template inline _Put_money<_MoneyT> put_money(const _MoneyT& __mon, bool __intl = false) { return { __mon, __intl }; } template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Put_money<_MoneyT> __f) { typename basic_ostream<_CharT, _Traits>::sentry __cerb(__os); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { typedef ostreambuf_iterator<_CharT, _Traits> _Iter; typedef money_put<_CharT, _Iter> _MoneyPut; const _MoneyPut& __mp = use_facet<_MoneyPut>(__os.getloc()); if (__mp.put(_Iter(__os.rdbuf()), __f._M_intl, __os, __os.fill(), __f._M_mon).failed()) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { __os._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __os._M_setstate(ios_base::badbit); } if (__err) __os.setstate(__err); } return __os; } template struct _Put_time { const std::tm* _M_tmb; const _CharT* _M_fmt; }; /** * @brief Extended manipulator for formatting time. * * This manipulator uses time_put::put to format time. * [ext.manip] * * @param __tmb struct tm time data to format. * @param __fmt format string. */ template inline _Put_time<_CharT> put_time(const std::tm* __tmb, const _CharT* __fmt) { return { __tmb, __fmt }; } template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, _Put_time<_CharT> __f) { typename basic_ostream<_CharT, _Traits>::sentry __cerb(__os); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { typedef ostreambuf_iterator<_CharT, _Traits> _Iter; typedef time_put<_CharT, _Iter> _TimePut; const _CharT* const __fmt_end = __f._M_fmt + _Traits::length(__f._M_fmt); const _TimePut& __mp = use_facet<_TimePut>(__os.getloc()); if (__mp.put(_Iter(__os.rdbuf()), __os, __os.fill(), __f._M_tmb, __f._M_fmt, __fmt_end).failed()) __err |= ios_base::badbit; } __catch(__cxxabiv1::__forced_unwind&) { __os._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __os._M_setstate(ios_base::badbit); } if (__err) __os.setstate(__err); } return __os; } template struct _Get_time { std::tm* _M_tmb; const _CharT* _M_fmt; }; /** * @brief Extended manipulator for extracting time. * * This manipulator uses time_get::get to extract time. * [ext.manip] * * @param __tmb struct to extract the time data to. * @param __fmt format string. */ template inline _Get_time<_CharT> get_time(std::tm* __tmb, const _CharT* __fmt) { return { __tmb, __fmt }; } template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, _Get_time<_CharT> __f) { typename basic_istream<_CharT, _Traits>::sentry __cerb(__is, false); if (__cerb) { ios_base::iostate __err = ios_base::goodbit; __try { typedef istreambuf_iterator<_CharT, _Traits> _Iter; typedef time_get<_CharT, _Iter> _TimeGet; const _CharT* const __fmt_end = __f._M_fmt + _Traits::length(__f._M_fmt); const _TimeGet& __mg = use_facet<_TimeGet>(__is.getloc()); __mg.get(_Iter(__is.rdbuf()), _Iter(), __is, __err, __f._M_tmb, __f._M_fmt, __fmt_end); } __catch(__cxxabiv1::__forced_unwind&) { __is._M_setstate(ios_base::badbit); __throw_exception_again; } __catch(...) { __is._M_setstate(ios_base::badbit); } if (__err) __is.setstate(__err); } return __is; } #if __cplusplus >= 201402L #define __cpp_lib_quoted_string_io 201304 /** * @brief Manipulator for quoted strings. * @param __string String to quote. * @param __delim Character to quote string with. * @param __escape Escape character to escape itself or quote character. */ template inline auto quoted(const _CharT* __string, _CharT __delim = _CharT('"'), _CharT __escape = _CharT('\\')) { return __detail::_Quoted_string(__string, __delim, __escape); } template inline auto quoted(const basic_string<_CharT, _Traits, _Alloc>& __string, _CharT __delim = _CharT('"'), _CharT __escape = _CharT('\\')) { return __detail::_Quoted_string< const basic_string<_CharT, _Traits, _Alloc>&, _CharT>( __string, __delim, __escape); } template inline auto quoted(basic_string<_CharT, _Traits, _Alloc>& __string, _CharT __delim = _CharT('"'), _CharT __escape = _CharT('\\')) { return __detail::_Quoted_string< basic_string<_CharT, _Traits, _Alloc>&, _CharT>( __string, __delim, __escape); } #if __cplusplus >= 201703L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2785. quoted should work with basic_string_view template inline auto quoted(basic_string_view<_CharT, _Traits> __sv, _CharT __delim = _CharT('"'), _CharT __escape = _CharT('\\')) { return __detail::_Quoted_string< basic_string_view<_CharT, _Traits>, _CharT>(__sv, __delim, __escape); } #endif // C++17 #endif // C++14 #endif // __cplusplus >= 201103L // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. // NB: This syntax is a GNU extension. #if _GLIBCXX_EXTERN_TEMPLATE extern template ostream& operator<<(ostream&, _Setfill); extern template ostream& operator<<(ostream&, _Setiosflags); extern template ostream& operator<<(ostream&, _Resetiosflags); extern template ostream& operator<<(ostream&, _Setbase); extern template ostream& operator<<(ostream&, _Setprecision); extern template ostream& operator<<(ostream&, _Setw); extern template istream& operator>>(istream&, _Setfill); extern template istream& operator>>(istream&, _Setiosflags); extern template istream& operator>>(istream&, _Resetiosflags); extern template istream& operator>>(istream&, _Setbase); extern template istream& operator>>(istream&, _Setprecision); extern template istream& operator>>(istream&, _Setw); #ifdef _GLIBCXX_USE_WCHAR_T extern template wostream& operator<<(wostream&, _Setfill); extern template wostream& operator<<(wostream&, _Setiosflags); extern template wostream& operator<<(wostream&, _Resetiosflags); extern template wostream& operator<<(wostream&, _Setbase); extern template wostream& operator<<(wostream&, _Setprecision); extern template wostream& operator<<(wostream&, _Setw); extern template wistream& operator>>(wistream&, _Setfill); extern template wistream& operator>>(wistream&, _Setiosflags); extern template wistream& operator>>(wistream&, _Resetiosflags); extern template wistream& operator>>(wistream&, _Setbase); extern template wistream& operator>>(wistream&, _Setprecision); extern template wistream& operator>>(wistream&, _Setw); #endif #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _GLIBCXX_IOMANIP */ c++/8/shared_mutex000064400000045721151027430570007713 0ustar00// -*- C++ -*- // Copyright (C) 2013-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/shared_mutex * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_SHARED_MUTEX #define _GLIBCXX_SHARED_MUTEX 1 #pragma GCC system_header #if __cplusplus >= 201402L #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @ingroup mutexes * @{ */ #ifdef _GLIBCXX_USE_C99_STDINT_TR1 #ifdef _GLIBCXX_HAS_GTHREADS #if __cplusplus >= 201703L #define __cpp_lib_shared_mutex 201505 class shared_mutex; #endif #define __cpp_lib_shared_timed_mutex 201402 class shared_timed_mutex; #if _GLIBCXX_USE_PTHREAD_RWLOCK_T /// A shared mutex type implemented using pthread_rwlock_t. class __shared_mutex_pthread { friend class shared_timed_mutex; #ifdef PTHREAD_RWLOCK_INITIALIZER pthread_rwlock_t _M_rwlock = PTHREAD_RWLOCK_INITIALIZER; public: __shared_mutex_pthread() = default; ~__shared_mutex_pthread() = default; #else pthread_rwlock_t _M_rwlock; public: __shared_mutex_pthread() { int __ret = pthread_rwlock_init(&_M_rwlock, NULL); if (__ret == ENOMEM) __throw_bad_alloc(); else if (__ret == EAGAIN) __throw_system_error(int(errc::resource_unavailable_try_again)); else if (__ret == EPERM) __throw_system_error(int(errc::operation_not_permitted)); // Errors not handled: EBUSY, EINVAL __glibcxx_assert(__ret == 0); } ~__shared_mutex_pthread() { int __ret __attribute((__unused__)) = pthread_rwlock_destroy(&_M_rwlock); // Errors not handled: EBUSY, EINVAL __glibcxx_assert(__ret == 0); } #endif __shared_mutex_pthread(const __shared_mutex_pthread&) = delete; __shared_mutex_pthread& operator=(const __shared_mutex_pthread&) = delete; void lock() { int __ret = pthread_rwlock_wrlock(&_M_rwlock); if (__ret == EDEADLK) __throw_system_error(int(errc::resource_deadlock_would_occur)); // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); } bool try_lock() { int __ret = pthread_rwlock_trywrlock(&_M_rwlock); if (__ret == EBUSY) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } void unlock() { int __ret __attribute((__unused__)) = pthread_rwlock_unlock(&_M_rwlock); // Errors not handled: EPERM, EBUSY, EINVAL __glibcxx_assert(__ret == 0); } // Shared ownership void lock_shared() { int __ret; // We retry if we exceeded the maximum number of read locks supported by // the POSIX implementation; this can result in busy-waiting, but this // is okay based on the current specification of forward progress // guarantees by the standard. do __ret = pthread_rwlock_rdlock(&_M_rwlock); while (__ret == EAGAIN); if (__ret == EDEADLK) __throw_system_error(int(errc::resource_deadlock_would_occur)); // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); } bool try_lock_shared() { int __ret = pthread_rwlock_tryrdlock(&_M_rwlock); // If the maximum number of read locks has been exceeded, we just fail // to acquire the lock. Unlike for lock(), we are not allowed to throw // an exception. if (__ret == EBUSY || __ret == EAGAIN) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } void unlock_shared() { unlock(); } void* native_handle() { return &_M_rwlock; } }; #endif #if ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK) /// A shared mutex type implemented using std::condition_variable. class __shared_mutex_cv { friend class shared_timed_mutex; // Based on Howard Hinnant's reference implementation from N2406. // The high bit of _M_state is the write-entered flag which is set to // indicate a writer has taken the lock or is queuing to take the lock. // The remaining bits are the count of reader locks. // // To take a reader lock, block on gate1 while the write-entered flag is // set or the maximum number of reader locks is held, then increment the // reader lock count. // To release, decrement the count, then if the write-entered flag is set // and the count is zero then signal gate2 to wake a queued writer, // otherwise if the maximum number of reader locks was held signal gate1 // to wake a reader. // // To take a writer lock, block on gate1 while the write-entered flag is // set, then set the write-entered flag to start queueing, then block on // gate2 while the number of reader locks is non-zero. // To release, unset the write-entered flag and signal gate1 to wake all // blocked readers and writers. // // This means that when no reader locks are held readers and writers get // equal priority. When one or more reader locks is held a writer gets // priority and no more reader locks can be taken while the writer is // queued. // Only locked when accessing _M_state or waiting on condition variables. mutex _M_mut; // Used to block while write-entered is set or reader count at maximum. condition_variable _M_gate1; // Used to block queued writers while reader count is non-zero. condition_variable _M_gate2; // The write-entered flag and reader count. unsigned _M_state; static constexpr unsigned _S_write_entered = 1U << (sizeof(unsigned)*__CHAR_BIT__ - 1); static constexpr unsigned _S_max_readers = ~_S_write_entered; // Test whether the write-entered flag is set. _M_mut must be locked. bool _M_write_entered() const { return _M_state & _S_write_entered; } // The number of reader locks currently held. _M_mut must be locked. unsigned _M_readers() const { return _M_state & _S_max_readers; } public: __shared_mutex_cv() : _M_state(0) {} ~__shared_mutex_cv() { __glibcxx_assert( _M_state == 0 ); } __shared_mutex_cv(const __shared_mutex_cv&) = delete; __shared_mutex_cv& operator=(const __shared_mutex_cv&) = delete; // Exclusive ownership void lock() { unique_lock __lk(_M_mut); // Wait until we can set the write-entered flag. _M_gate1.wait(__lk, [=]{ return !_M_write_entered(); }); _M_state |= _S_write_entered; // Then wait until there are no more readers. _M_gate2.wait(__lk, [=]{ return _M_readers() == 0; }); } bool try_lock() { unique_lock __lk(_M_mut, try_to_lock); if (__lk.owns_lock() && _M_state == 0) { _M_state = _S_write_entered; return true; } return false; } void unlock() { lock_guard __lk(_M_mut); __glibcxx_assert( _M_write_entered() ); _M_state = 0; // call notify_all() while mutex is held so that another thread can't // lock and unlock the mutex then destroy *this before we make the call. _M_gate1.notify_all(); } // Shared ownership void lock_shared() { unique_lock __lk(_M_mut); _M_gate1.wait(__lk, [=]{ return _M_state < _S_max_readers; }); ++_M_state; } bool try_lock_shared() { unique_lock __lk(_M_mut, try_to_lock); if (!__lk.owns_lock()) return false; if (_M_state < _S_max_readers) { ++_M_state; return true; } return false; } void unlock_shared() { lock_guard __lk(_M_mut); __glibcxx_assert( _M_readers() > 0 ); auto __prev = _M_state--; if (_M_write_entered()) { // Wake the queued writer if there are no more readers. if (_M_readers() == 0) _M_gate2.notify_one(); // No need to notify gate1 because we give priority to the queued // writer, and that writer will eventually notify gate1 after it // clears the write-entered flag. } else { // Wake any thread that was blocked on reader overflow. if (__prev == _S_max_readers) _M_gate1.notify_one(); } } }; #endif #if __cplusplus > 201402L /// The standard shared mutex type. class shared_mutex { public: shared_mutex() = default; ~shared_mutex() = default; shared_mutex(const shared_mutex&) = delete; shared_mutex& operator=(const shared_mutex&) = delete; // Exclusive ownership void lock() { _M_impl.lock(); } bool try_lock() { return _M_impl.try_lock(); } void unlock() { _M_impl.unlock(); } // Shared ownership void lock_shared() { _M_impl.lock_shared(); } bool try_lock_shared() { return _M_impl.try_lock_shared(); } void unlock_shared() { _M_impl.unlock_shared(); } #if _GLIBCXX_USE_PTHREAD_RWLOCK_T typedef void* native_handle_type; native_handle_type native_handle() { return _M_impl.native_handle(); } private: __shared_mutex_pthread _M_impl; #else private: __shared_mutex_cv _M_impl; #endif }; #endif // C++17 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK using __shared_timed_mutex_base = __shared_mutex_pthread; #else using __shared_timed_mutex_base = __shared_mutex_cv; #endif /// The standard shared timed mutex type. class shared_timed_mutex : private __shared_timed_mutex_base { using _Base = __shared_timed_mutex_base; // Must use the same clock as condition_variable for __shared_mutex_cv. typedef chrono::system_clock __clock_t; public: shared_timed_mutex() = default; ~shared_timed_mutex() = default; shared_timed_mutex(const shared_timed_mutex&) = delete; shared_timed_mutex& operator=(const shared_timed_mutex&) = delete; // Exclusive ownership void lock() { _Base::lock(); } bool try_lock() { return _Base::try_lock(); } void unlock() { _Base::unlock(); } template bool try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time) { return try_lock_until(__clock_t::now() + __rel_time); } // Shared ownership void lock_shared() { _Base::lock_shared(); } bool try_lock_shared() { return _Base::try_lock_shared(); } void unlock_shared() { _Base::unlock_shared(); } template bool try_lock_shared_for(const chrono::duration<_Rep, _Period>& __rel_time) { return try_lock_shared_until(__clock_t::now() + __rel_time); } #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK // Exclusive ownership template bool try_lock_until(const chrono::time_point<__clock_t, _Duration>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); __gthread_time_t __ts = { static_cast(__s.time_since_epoch().count()), static_cast(__ns.count()) }; int __ret = pthread_rwlock_timedwrlock(&_M_rwlock, &__ts); // On self-deadlock, we just fail to acquire the lock. Technically, // the program violated the precondition. if (__ret == ETIMEDOUT || __ret == EDEADLK) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __abs_time - __c_entry; const auto __s_atime = __s_entry + __delta; return try_lock_until(__s_atime); } // Shared ownership template bool try_lock_shared_until(const chrono::time_point<__clock_t, _Duration>& __atime) { auto __s = chrono::time_point_cast(__atime); auto __ns = chrono::duration_cast(__atime - __s); __gthread_time_t __ts = { static_cast(__s.time_since_epoch().count()), static_cast(__ns.count()) }; int __ret; // Unlike for lock(), we are not allowed to throw an exception so if // the maximum number of read locks has been exceeded, or we would // deadlock, we just try to acquire the lock again (and will time out // eventually). // In cases where we would exceed the maximum number of read locks // throughout the whole time until the timeout, we will fail to // acquire the lock even if it would be logically free; however, this // is allowed by the standard, and we made a "strong effort" // (see C++14 30.4.1.4p26). // For cases where the implementation detects a deadlock we // intentionally block and timeout so that an early return isn't // mistaken for a spurious failure, which might help users realise // there is a deadlock. do __ret = pthread_rwlock_timedrdlock(&_M_rwlock, &__ts); while (__ret == EAGAIN || __ret == EDEADLK); if (__ret == ETIMEDOUT) return false; // Errors not handled: EINVAL __glibcxx_assert(__ret == 0); return true; } template bool try_lock_shared_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { // DR 887 - Sync unknown clock to known clock. const typename _Clock::time_point __c_entry = _Clock::now(); const __clock_t::time_point __s_entry = __clock_t::now(); const auto __delta = __abs_time - __c_entry; const auto __s_atime = __s_entry + __delta; return try_lock_shared_until(__s_atime); } #else // ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK) // Exclusive ownership template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { unique_lock __lk(_M_mut); if (!_M_gate1.wait_until(__lk, __abs_time, [=]{ return !_M_write_entered(); })) { return false; } _M_state |= _S_write_entered; if (!_M_gate2.wait_until(__lk, __abs_time, [=]{ return _M_readers() == 0; })) { _M_state ^= _S_write_entered; // Wake all threads blocked while the write-entered flag was set. _M_gate1.notify_all(); return false; } return true; } // Shared ownership template bool try_lock_shared_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { unique_lock __lk(_M_mut); if (!_M_gate1.wait_until(__lk, __abs_time, [=]{ return _M_state < _S_max_readers; })) { return false; } ++_M_state; return true; } #endif // _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK }; #endif // _GLIBCXX_HAS_GTHREADS /// shared_lock template class shared_lock { public: typedef _Mutex mutex_type; // Shared locking shared_lock() noexcept : _M_pm(nullptr), _M_owns(false) { } explicit shared_lock(mutex_type& __m) : _M_pm(std::__addressof(__m)), _M_owns(true) { __m.lock_shared(); } shared_lock(mutex_type& __m, defer_lock_t) noexcept : _M_pm(std::__addressof(__m)), _M_owns(false) { } shared_lock(mutex_type& __m, try_to_lock_t) : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared()) { } shared_lock(mutex_type& __m, adopt_lock_t) : _M_pm(std::__addressof(__m)), _M_owns(true) { } template shared_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __abs_time) : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared_until(__abs_time)) { } template shared_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __rel_time) : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared_for(__rel_time)) { } ~shared_lock() { if (_M_owns) _M_pm->unlock_shared(); } shared_lock(shared_lock const&) = delete; shared_lock& operator=(shared_lock const&) = delete; shared_lock(shared_lock&& __sl) noexcept : shared_lock() { swap(__sl); } shared_lock& operator=(shared_lock&& __sl) noexcept { shared_lock(std::move(__sl)).swap(*this); return *this; } void lock() { _M_lockable(); _M_pm->lock_shared(); _M_owns = true; } bool try_lock() { _M_lockable(); return _M_owns = _M_pm->try_lock_shared(); } template bool try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time) { _M_lockable(); return _M_owns = _M_pm->try_lock_shared_for(__rel_time); } template bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) { _M_lockable(); return _M_owns = _M_pm->try_lock_shared_until(__abs_time); } void unlock() { if (!_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); _M_pm->unlock_shared(); _M_owns = false; } // Setters void swap(shared_lock& __u) noexcept { std::swap(_M_pm, __u._M_pm); std::swap(_M_owns, __u._M_owns); } mutex_type* release() noexcept { _M_owns = false; return std::exchange(_M_pm, nullptr); } // Getters bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return _M_owns; } mutex_type* mutex() const noexcept { return _M_pm; } private: void _M_lockable() const { if (_M_pm == nullptr) __throw_system_error(int(errc::operation_not_permitted)); if (_M_owns) __throw_system_error(int(errc::resource_deadlock_would_occur)); } mutex_type* _M_pm; bool _M_owns; }; /// Swap specialization for shared_lock template void swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) noexcept { __x.swap(__y); } #endif // _GLIBCXX_USE_C99_STDINT_TR1 // @} group mutexes _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++14 #endif // _GLIBCXX_SHARED_MUTEX c++/8/future000064400000142766151027430570006544 0ustar00// -*- C++ -*- // Copyright (C) 2009-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/future * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_FUTURE #define _GLIBCXX_FUTURE 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup futures Futures * @ingroup concurrency * * Classes for futures support. * @{ */ /// Error code for futures enum class future_errc { future_already_retrieved = 1, promise_already_satisfied, no_state, broken_promise }; /// Specialization. template<> struct is_error_code_enum : public true_type { }; /// Points to a statically-allocated object derived from error_category. const error_category& future_category() noexcept; /// Overload for make_error_code. inline error_code make_error_code(future_errc __errc) noexcept { return error_code(static_cast(__errc), future_category()); } /// Overload for make_error_condition. inline error_condition make_error_condition(future_errc __errc) noexcept { return error_condition(static_cast(__errc), future_category()); } /** * @brief Exception type thrown by futures. * @ingroup exceptions */ class future_error : public logic_error { public: explicit future_error(future_errc __errc) : future_error(std::make_error_code(__errc)) { } virtual ~future_error() noexcept; virtual const char* what() const noexcept; const error_code& code() const noexcept { return _M_code; } private: explicit future_error(error_code __ec) : logic_error("std::future_error: " + __ec.message()), _M_code(__ec) { } friend void __throw_future_error(int); error_code _M_code; }; // Forward declarations. template class future; template class shared_future; template class packaged_task; template class promise; /// Launch code for futures enum class launch { async = 1, deferred = 2 }; constexpr launch operator&(launch __x, launch __y) { return static_cast( static_cast(__x) & static_cast(__y)); } constexpr launch operator|(launch __x, launch __y) { return static_cast( static_cast(__x) | static_cast(__y)); } constexpr launch operator^(launch __x, launch __y) { return static_cast( static_cast(__x) ^ static_cast(__y)); } constexpr launch operator~(launch __x) { return static_cast(~static_cast(__x)); } inline launch& operator&=(launch& __x, launch __y) { return __x = __x & __y; } inline launch& operator|=(launch& __x, launch __y) { return __x = __x | __y; } inline launch& operator^=(launch& __x, launch __y) { return __x = __x ^ __y; } /// Status code for futures enum class future_status { ready, timeout, deferred }; // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2021. Further incorrect usages of result_of template using __async_result_of = typename result_of< typename decay<_Fn>::type(typename decay<_Args>::type...)>::type; template future<__async_result_of<_Fn, _Args...>> async(launch __policy, _Fn&& __fn, _Args&&... __args); template future<__async_result_of<_Fn, _Args...>> async(_Fn&& __fn, _Args&&... __args); #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) /// Base class and enclosing scope. struct __future_base { /// Base class for results. struct _Result_base { exception_ptr _M_error; _Result_base(const _Result_base&) = delete; _Result_base& operator=(const _Result_base&) = delete; // _M_destroy() allows derived classes to control deallocation virtual void _M_destroy() = 0; struct _Deleter { void operator()(_Result_base* __fr) const { __fr->_M_destroy(); } }; protected: _Result_base(); virtual ~_Result_base(); }; /// A unique_ptr for result objects. template using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>; /// A result object that has storage for an object of type _Res. template struct _Result : _Result_base { private: __gnu_cxx::__aligned_buffer<_Res> _M_storage; bool _M_initialized; public: typedef _Res result_type; _Result() noexcept : _M_initialized() { } ~_Result() { if (_M_initialized) _M_value().~_Res(); } // Return lvalue, future will add const or rvalue-reference _Res& _M_value() noexcept { return *_M_storage._M_ptr(); } void _M_set(const _Res& __res) { ::new (_M_storage._M_addr()) _Res(__res); _M_initialized = true; } void _M_set(_Res&& __res) { ::new (_M_storage._M_addr()) _Res(std::move(__res)); _M_initialized = true; } private: void _M_destroy() { delete this; } }; /// A result object that uses an allocator. template struct _Result_alloc final : _Result<_Res>, _Alloc { using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>; explicit _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a) { } private: void _M_destroy() { __allocator_type __a(*this); __allocated_ptr<__allocator_type> __guard_ptr{ __a, this }; this->~_Result_alloc(); } }; // Create a result object that uses an allocator. template static _Ptr<_Result_alloc<_Res, _Allocator>> _S_allocate_result(const _Allocator& __a) { using __result_type = _Result_alloc<_Res, _Allocator>; typename __result_type::__allocator_type __a2(__a); auto __guard = std::__allocate_guarded(__a2); __result_type* __p = ::new((void*)__guard.get()) __result_type{__a}; __guard = nullptr; return _Ptr<__result_type>(__p); } // Keep it simple for std::allocator. template static _Ptr<_Result<_Res>> _S_allocate_result(const std::allocator<_Tp>& __a) { return _Ptr<_Result<_Res>>(new _Result<_Res>); } // Base class for various types of shared state created by an // asynchronous provider (such as a std::promise) and shared with one // or more associated futures. class _State_baseV2 { typedef _Ptr<_Result_base> _Ptr_type; enum _Status : unsigned { __not_ready, __ready }; _Ptr_type _M_result; __atomic_futex_unsigned<> _M_status; atomic_flag _M_retrieved = ATOMIC_FLAG_INIT; once_flag _M_once; public: _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready) { } _State_baseV2(const _State_baseV2&) = delete; _State_baseV2& operator=(const _State_baseV2&) = delete; virtual ~_State_baseV2() = default; _Result_base& wait() { // Run any deferred function or join any asynchronous thread: _M_complete_async(); // Acquire MO makes sure this synchronizes with the thread that made // the future ready. _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire); return *_M_result; } template future_status wait_for(const chrono::duration<_Rep, _Period>& __rel) { // First, check if the future has been made ready. Use acquire MO // to synchronize with the thread that made it ready. if (_M_status._M_load(memory_order_acquire) == _Status::__ready) return future_status::ready; if (_M_is_deferred_future()) return future_status::deferred; if (_M_status._M_load_when_equal_for(_Status::__ready, memory_order_acquire, __rel)) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2100. timed waiting functions must also join // This call is a no-op by default except on an async future, // in which case the async thread is joined. It's also not a // no-op for a deferred future, but such a future will never // reach this point because it returns future_status::deferred // instead of waiting for the future to become ready (see // above). Async futures synchronize in this call, so we need // no further synchronization here. _M_complete_async(); return future_status::ready; } return future_status::timeout; } template future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs) { // First, check if the future has been made ready. Use acquire MO // to synchronize with the thread that made it ready. if (_M_status._M_load(memory_order_acquire) == _Status::__ready) return future_status::ready; if (_M_is_deferred_future()) return future_status::deferred; if (_M_status._M_load_when_equal_until(_Status::__ready, memory_order_acquire, __abs)) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2100. timed waiting functions must also join // See wait_for(...) above. _M_complete_async(); return future_status::ready; } return future_status::timeout; } // Provide a result to the shared state and make it ready. // Calls at most once: _M_result = __res(); void _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false) { bool __did_set = false; // all calls to this function are serialized, // side-effects of invoking __res only happen once call_once(_M_once, &_State_baseV2::_M_do_set, this, std::__addressof(__res), std::__addressof(__did_set)); if (__did_set) // Use release MO to synchronize with observers of the ready state. _M_status._M_store_notify_all(_Status::__ready, memory_order_release); else if (!__ignore_failure) __throw_future_error(int(future_errc::promise_already_satisfied)); } // Provide a result to the shared state but delay making it ready // until the calling thread exits. // Calls at most once: _M_result = __res(); void _M_set_delayed_result(function<_Ptr_type()> __res, weak_ptr<_State_baseV2> __self) { bool __did_set = false; unique_ptr<_Make_ready> __mr{new _Make_ready}; // all calls to this function are serialized, // side-effects of invoking __res only happen once call_once(_M_once, &_State_baseV2::_M_do_set, this, std::__addressof(__res), std::__addressof(__did_set)); if (!__did_set) __throw_future_error(int(future_errc::promise_already_satisfied)); __mr->_M_shared_state = std::move(__self); __mr->_M_set(); __mr.release(); } // Abandon this shared state. void _M_break_promise(_Ptr_type __res) { if (static_cast(__res)) { __res->_M_error = make_exception_ptr(future_error(future_errc::broken_promise)); // This function is only called when the last asynchronous result // provider is abandoning this shared state, so noone can be // trying to make the shared state ready at the same time, and // we can access _M_result directly instead of through call_once. _M_result.swap(__res); // Use release MO to synchronize with observers of the ready state. _M_status._M_store_notify_all(_Status::__ready, memory_order_release); } } // Called when this object is first passed to a future. void _M_set_retrieved_flag() { if (_M_retrieved.test_and_set()) __throw_future_error(int(future_errc::future_already_retrieved)); } template struct _Setter; // set lvalues template struct _Setter<_Res, _Arg&> { // check this is only used by promise::set_value(const R&) // or promise::set_value(R&) static_assert(is_same<_Res, _Arg&>::value // promise || is_same::value, // promise "Invalid specialisation"); // Used by std::promise to copy construct the result. typename promise<_Res>::_Ptr_type operator()() const { _M_promise->_M_storage->_M_set(*_M_arg); return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; _Arg* _M_arg; }; // set rvalues template struct _Setter<_Res, _Res&&> { // Used by std::promise to move construct the result. typename promise<_Res>::_Ptr_type operator()() const { _M_promise->_M_storage->_M_set(std::move(*_M_arg)); return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; _Res* _M_arg; }; // set void template struct _Setter<_Res, void> { static_assert(is_void<_Res>::value, "Only used for promise"); typename promise<_Res>::_Ptr_type operator()() const { return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; }; struct __exception_ptr_tag { }; // set exceptions template struct _Setter<_Res, __exception_ptr_tag> { // Used by std::promise to store an exception as the result. typename promise<_Res>::_Ptr_type operator()() const { _M_promise->_M_storage->_M_error = *_M_ex; return std::move(_M_promise->_M_storage); } promise<_Res>* _M_promise; exception_ptr* _M_ex; }; template static _Setter<_Res, _Arg&&> __setter(promise<_Res>* __prom, _Arg&& __arg) { _S_check(__prom->_M_future); return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) }; } template static _Setter<_Res, __exception_ptr_tag> __setter(exception_ptr& __ex, promise<_Res>* __prom) { _S_check(__prom->_M_future); return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex }; } template static _Setter<_Res, void> __setter(promise<_Res>* __prom) { _S_check(__prom->_M_future); return _Setter<_Res, void>{ __prom }; } template static void _S_check(const shared_ptr<_Tp>& __p) { if (!static_cast(__p)) __throw_future_error((int)future_errc::no_state); } private: // The function invoked with std::call_once(_M_once, ...). void _M_do_set(function<_Ptr_type()>* __f, bool* __did_set) { _Ptr_type __res = (*__f)(); // Notify the caller that we did try to set; if we do not throw an // exception, the caller will be aware that it did set (e.g., see // _M_set_result). *__did_set = true; _M_result.swap(__res); // nothrow } // Wait for completion of async function. virtual void _M_complete_async() { } // Return true if state corresponds to a deferred function. virtual bool _M_is_deferred_future() const { return false; } struct _Make_ready final : __at_thread_exit_elt { weak_ptr<_State_baseV2> _M_shared_state; static void _S_run(void*); void _M_set(); }; }; #ifdef _GLIBCXX_ASYNC_ABI_COMPAT class _State_base; class _Async_state_common; #else using _State_base = _State_baseV2; class _Async_state_commonV2; #endif template()())> class _Deferred_state; template()())> class _Async_state_impl; template class _Task_state_base; template class _Task_state; template static std::shared_ptr<_State_base> _S_make_deferred_state(_BoundFn&& __fn); template static std::shared_ptr<_State_base> _S_make_async_state(_BoundFn&& __fn); template struct _Task_setter; template static _Task_setter<_Res_ptr, _BoundFn> _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call) { return { std::__addressof(__ptr), std::__addressof(__call) }; } }; /// Partial specialization for reference types. template struct __future_base::_Result<_Res&> : __future_base::_Result_base { typedef _Res& result_type; _Result() noexcept : _M_value_ptr() { } void _M_set(_Res& __res) noexcept { _M_value_ptr = std::addressof(__res); } _Res& _M_get() noexcept { return *_M_value_ptr; } private: _Res* _M_value_ptr; void _M_destroy() { delete this; } }; /// Explicit specialization for void. template<> struct __future_base::_Result : __future_base::_Result_base { typedef void result_type; private: void _M_destroy() { delete this; } }; #ifndef _GLIBCXX_ASYNC_ABI_COMPAT // Allow _Setter objects to be stored locally in std::function template struct __is_location_invariant <__future_base::_State_base::_Setter<_Res, _Arg>> : true_type { }; // Allow _Task_setter objects to be stored locally in std::function template struct __is_location_invariant <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>> : true_type { }; /// Common implementation for future and shared_future. template class __basic_future : public __future_base { protected: typedef shared_ptr<_State_base> __state_type; typedef __future_base::_Result<_Res>& __result_type; private: __state_type _M_state; public: // Disable copying. __basic_future(const __basic_future&) = delete; __basic_future& operator=(const __basic_future&) = delete; bool valid() const noexcept { return static_cast(_M_state); } void wait() const { _State_base::_S_check(_M_state); _M_state->wait(); } template future_status wait_for(const chrono::duration<_Rep, _Period>& __rel) const { _State_base::_S_check(_M_state); return _M_state->wait_for(__rel); } template future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const { _State_base::_S_check(_M_state); return _M_state->wait_until(__abs); } protected: /// Wait for the state to be ready and rethrow any stored exception __result_type _M_get_result() const { _State_base::_S_check(_M_state); _Result_base& __res = _M_state->wait(); if (!(__res._M_error == 0)) rethrow_exception(__res._M_error); return static_cast<__result_type>(__res); } void _M_swap(__basic_future& __that) noexcept { _M_state.swap(__that._M_state); } // Construction of a future by promise::get_future() explicit __basic_future(const __state_type& __state) : _M_state(__state) { _State_base::_S_check(_M_state); _M_state->_M_set_retrieved_flag(); } // Copy construction from a shared_future explicit __basic_future(const shared_future<_Res>&) noexcept; // Move construction from a shared_future explicit __basic_future(shared_future<_Res>&&) noexcept; // Move construction from a future explicit __basic_future(future<_Res>&&) noexcept; constexpr __basic_future() noexcept : _M_state() { } struct _Reset { explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { } ~_Reset() { _M_fut._M_state.reset(); } __basic_future& _M_fut; }; }; /// Primary template for future. template class future : public __basic_future<_Res> { friend class promise<_Res>; template friend class packaged_task; template friend future<__async_result_of<_Fn, _Args...>> async(launch, _Fn&&, _Args&&...); typedef __basic_future<_Res> _Base_type; typedef typename _Base_type::__state_type __state_type; explicit future(const __state_type& __state) : _Base_type(__state) { } public: constexpr future() noexcept : _Base_type() { } /// Move constructor future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } // Disable copying future(const future&) = delete; future& operator=(const future&) = delete; future& operator=(future&& __fut) noexcept { future(std::move(__fut))._M_swap(*this); return *this; } /// Retrieving the value _Res get() { typename _Base_type::_Reset __reset(*this); return std::move(this->_M_get_result()._M_value()); } shared_future<_Res> share() noexcept; }; /// Partial specialization for future template class future<_Res&> : public __basic_future<_Res&> { friend class promise<_Res&>; template friend class packaged_task; template friend future<__async_result_of<_Fn, _Args...>> async(launch, _Fn&&, _Args&&...); typedef __basic_future<_Res&> _Base_type; typedef typename _Base_type::__state_type __state_type; explicit future(const __state_type& __state) : _Base_type(__state) { } public: constexpr future() noexcept : _Base_type() { } /// Move constructor future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } // Disable copying future(const future&) = delete; future& operator=(const future&) = delete; future& operator=(future&& __fut) noexcept { future(std::move(__fut))._M_swap(*this); return *this; } /// Retrieving the value _Res& get() { typename _Base_type::_Reset __reset(*this); return this->_M_get_result()._M_get(); } shared_future<_Res&> share() noexcept; }; /// Explicit specialization for future template<> class future : public __basic_future { friend class promise; template friend class packaged_task; template friend future<__async_result_of<_Fn, _Args...>> async(launch, _Fn&&, _Args&&...); typedef __basic_future _Base_type; typedef typename _Base_type::__state_type __state_type; explicit future(const __state_type& __state) : _Base_type(__state) { } public: constexpr future() noexcept : _Base_type() { } /// Move constructor future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } // Disable copying future(const future&) = delete; future& operator=(const future&) = delete; future& operator=(future&& __fut) noexcept { future(std::move(__fut))._M_swap(*this); return *this; } /// Retrieving the value void get() { typename _Base_type::_Reset __reset(*this); this->_M_get_result(); } shared_future share() noexcept; }; /// Primary template for shared_future. template class shared_future : public __basic_future<_Res> { typedef __basic_future<_Res> _Base_type; public: constexpr shared_future() noexcept : _Base_type() { } /// Copy constructor shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { } /// Construct from a future rvalue shared_future(future<_Res>&& __uf) noexcept : _Base_type(std::move(__uf)) { } /// Construct from a shared_future rvalue shared_future(shared_future&& __sf) noexcept : _Base_type(std::move(__sf)) { } shared_future& operator=(const shared_future& __sf) noexcept { shared_future(__sf)._M_swap(*this); return *this; } shared_future& operator=(shared_future&& __sf) noexcept { shared_future(std::move(__sf))._M_swap(*this); return *this; } /// Retrieving the value const _Res& get() const { return this->_M_get_result()._M_value(); } }; /// Partial specialization for shared_future template class shared_future<_Res&> : public __basic_future<_Res&> { typedef __basic_future<_Res&> _Base_type; public: constexpr shared_future() noexcept : _Base_type() { } /// Copy constructor shared_future(const shared_future& __sf) : _Base_type(__sf) { } /// Construct from a future rvalue shared_future(future<_Res&>&& __uf) noexcept : _Base_type(std::move(__uf)) { } /// Construct from a shared_future rvalue shared_future(shared_future&& __sf) noexcept : _Base_type(std::move(__sf)) { } shared_future& operator=(const shared_future& __sf) { shared_future(__sf)._M_swap(*this); return *this; } shared_future& operator=(shared_future&& __sf) noexcept { shared_future(std::move(__sf))._M_swap(*this); return *this; } /// Retrieving the value _Res& get() const { return this->_M_get_result()._M_get(); } }; /// Explicit specialization for shared_future template<> class shared_future : public __basic_future { typedef __basic_future _Base_type; public: constexpr shared_future() noexcept : _Base_type() { } /// Copy constructor shared_future(const shared_future& __sf) : _Base_type(__sf) { } /// Construct from a future rvalue shared_future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { } /// Construct from a shared_future rvalue shared_future(shared_future&& __sf) noexcept : _Base_type(std::move(__sf)) { } shared_future& operator=(const shared_future& __sf) { shared_future(__sf)._M_swap(*this); return *this; } shared_future& operator=(shared_future&& __sf) noexcept { shared_future(std::move(__sf))._M_swap(*this); return *this; } // Retrieving the value void get() const { this->_M_get_result(); } }; // Now we can define the protected __basic_future constructors. template inline __basic_future<_Res>:: __basic_future(const shared_future<_Res>& __sf) noexcept : _M_state(__sf._M_state) { } template inline __basic_future<_Res>:: __basic_future(shared_future<_Res>&& __sf) noexcept : _M_state(std::move(__sf._M_state)) { } template inline __basic_future<_Res>:: __basic_future(future<_Res>&& __uf) noexcept : _M_state(std::move(__uf._M_state)) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2556. Wide contract for future::share() template inline shared_future<_Res> future<_Res>::share() noexcept { return shared_future<_Res>(std::move(*this)); } template inline shared_future<_Res&> future<_Res&>::share() noexcept { return shared_future<_Res&>(std::move(*this)); } inline shared_future future::share() noexcept { return shared_future(std::move(*this)); } /// Primary template for promise template class promise { typedef __future_base::_State_base _State; typedef __future_base::_Result<_Res> _Res_type; typedef __future_base::_Ptr<_Res_type> _Ptr_type; template friend class _State::_Setter; friend _State; shared_ptr<_State> _M_future; _Ptr_type _M_storage; public: promise() : _M_future(std::make_shared<_State>()), _M_storage(new _Res_type()) { } promise(promise&& __rhs) noexcept : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } template promise(allocator_arg_t, const _Allocator& __a) : _M_future(std::allocate_shared<_State>(__a)), _M_storage(__future_base::_S_allocate_result<_Res>(__a)) { } template promise(allocator_arg_t, const _Allocator&, promise&& __rhs) : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } promise(const promise&) = delete; ~promise() { if (static_cast(_M_future) && !_M_future.unique()) _M_future->_M_break_promise(std::move(_M_storage)); } // Assignment promise& operator=(promise&& __rhs) noexcept { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise&) = delete; void swap(promise& __rhs) noexcept { _M_future.swap(__rhs._M_future); _M_storage.swap(__rhs._M_storage); } // Retrieving the result future<_Res> get_future() { return future<_Res>(_M_future); } // Setting the result void set_value(const _Res& __r) { _M_future->_M_set_result(_State::__setter(this, __r)); } void set_value(_Res&& __r) { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); } void set_exception(exception_ptr __p) { _M_future->_M_set_result(_State::__setter(__p, this)); } void set_value_at_thread_exit(const _Res& __r) { _M_future->_M_set_delayed_result(_State::__setter(this, __r), _M_future); } void set_value_at_thread_exit(_Res&& __r) { _M_future->_M_set_delayed_result( _State::__setter(this, std::move(__r)), _M_future); } void set_exception_at_thread_exit(exception_ptr __p) { _M_future->_M_set_delayed_result(_State::__setter(__p, this), _M_future); } }; template inline void swap(promise<_Res>& __x, promise<_Res>& __y) noexcept { __x.swap(__y); } template struct uses_allocator, _Alloc> : public true_type { }; /// Partial specialization for promise template class promise<_Res&> { typedef __future_base::_State_base _State; typedef __future_base::_Result<_Res&> _Res_type; typedef __future_base::_Ptr<_Res_type> _Ptr_type; template friend class _State::_Setter; friend _State; shared_ptr<_State> _M_future; _Ptr_type _M_storage; public: promise() : _M_future(std::make_shared<_State>()), _M_storage(new _Res_type()) { } promise(promise&& __rhs) noexcept : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } template promise(allocator_arg_t, const _Allocator& __a) : _M_future(std::allocate_shared<_State>(__a)), _M_storage(__future_base::_S_allocate_result<_Res&>(__a)) { } template promise(allocator_arg_t, const _Allocator&, promise&& __rhs) : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } promise(const promise&) = delete; ~promise() { if (static_cast(_M_future) && !_M_future.unique()) _M_future->_M_break_promise(std::move(_M_storage)); } // Assignment promise& operator=(promise&& __rhs) noexcept { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise&) = delete; void swap(promise& __rhs) noexcept { _M_future.swap(__rhs._M_future); _M_storage.swap(__rhs._M_storage); } // Retrieving the result future<_Res&> get_future() { return future<_Res&>(_M_future); } // Setting the result void set_value(_Res& __r) { _M_future->_M_set_result(_State::__setter(this, __r)); } void set_exception(exception_ptr __p) { _M_future->_M_set_result(_State::__setter(__p, this)); } void set_value_at_thread_exit(_Res& __r) { _M_future->_M_set_delayed_result(_State::__setter(this, __r), _M_future); } void set_exception_at_thread_exit(exception_ptr __p) { _M_future->_M_set_delayed_result(_State::__setter(__p, this), _M_future); } }; /// Explicit specialization for promise template<> class promise { typedef __future_base::_State_base _State; typedef __future_base::_Result _Res_type; typedef __future_base::_Ptr<_Res_type> _Ptr_type; template friend class _State::_Setter; friend _State; shared_ptr<_State> _M_future; _Ptr_type _M_storage; public: promise() : _M_future(std::make_shared<_State>()), _M_storage(new _Res_type()) { } promise(promise&& __rhs) noexcept : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } template promise(allocator_arg_t, const _Allocator& __a) : _M_future(std::allocate_shared<_State>(__a)), _M_storage(__future_base::_S_allocate_result(__a)) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2095. missing constructors needed for uses-allocator construction template promise(allocator_arg_t, const _Allocator&, promise&& __rhs) : _M_future(std::move(__rhs._M_future)), _M_storage(std::move(__rhs._M_storage)) { } promise(const promise&) = delete; ~promise() { if (static_cast(_M_future) && !_M_future.unique()) _M_future->_M_break_promise(std::move(_M_storage)); } // Assignment promise& operator=(promise&& __rhs) noexcept { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise&) = delete; void swap(promise& __rhs) noexcept { _M_future.swap(__rhs._M_future); _M_storage.swap(__rhs._M_storage); } // Retrieving the result future get_future() { return future(_M_future); } // Setting the result void set_value() { _M_future->_M_set_result(_State::__setter(this)); } void set_exception(exception_ptr __p) { _M_future->_M_set_result(_State::__setter(__p, this)); } void set_value_at_thread_exit() { _M_future->_M_set_delayed_result(_State::__setter(this), _M_future); } void set_exception_at_thread_exit(exception_ptr __p) { _M_future->_M_set_delayed_result(_State::__setter(__p, this), _M_future); } }; template struct __future_base::_Task_setter { // Invoke the function and provide the result to the caller. _Ptr_type operator()() const { __try { (*_M_result)->_M_set((*_M_fn)()); } __catch(const __cxxabiv1::__forced_unwind&) { __throw_exception_again; // will cause broken_promise } __catch(...) { (*_M_result)->_M_error = current_exception(); } return std::move(*_M_result); } _Ptr_type* _M_result; _Fn* _M_fn; }; template struct __future_base::_Task_setter<_Ptr_type, _Fn, void> { _Ptr_type operator()() const { __try { (*_M_fn)(); } __catch(const __cxxabiv1::__forced_unwind&) { __throw_exception_again; // will cause broken_promise } __catch(...) { (*_M_result)->_M_error = current_exception(); } return std::move(*_M_result); } _Ptr_type* _M_result; _Fn* _M_fn; }; // Holds storage for a packaged_task's result. template struct __future_base::_Task_state_base<_Res(_Args...)> : __future_base::_State_base { typedef _Res _Res_type; template _Task_state_base(const _Alloc& __a) : _M_result(_S_allocate_result<_Res>(__a)) { } // Invoke the stored task and make the state ready. virtual void _M_run(_Args&&... __args) = 0; // Invoke the stored task and make the state ready at thread exit. virtual void _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0; virtual shared_ptr<_Task_state_base> _M_reset() = 0; typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type; _Ptr_type _M_result; }; // Holds a packaged_task's stored task. template struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final : __future_base::_Task_state_base<_Res(_Args...)> { template _Task_state(_Fn2&& __fn, const _Alloc& __a) : _Task_state_base<_Res(_Args...)>(__a), _M_impl(std::forward<_Fn2>(__fn), __a) { } private: virtual void _M_run(_Args&&... __args) { auto __boundfn = [&] () -> typename result_of<_Fn&(_Args&&...)>::type { return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...); }; this->_M_set_result(_S_task_setter(this->_M_result, __boundfn)); } virtual void _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self) { auto __boundfn = [&] () -> typename result_of<_Fn&(_Args&&...)>::type { return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...); }; this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn), std::move(__self)); } virtual shared_ptr<_Task_state_base<_Res(_Args...)>> _M_reset(); struct _Impl : _Alloc { template _Impl(_Fn2&& __fn, const _Alloc& __a) : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { } _Fn _M_fn; } _M_impl; }; template static shared_ptr<__future_base::_Task_state_base<_Signature>> __create_task_state(_Fn&& __fn, const _Alloc& __a) { typedef typename decay<_Fn>::type _Fn2; typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State; return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a); } template shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>> __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset() { return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn), static_cast<_Alloc&>(_M_impl)); } template::type>::value> struct __constrain_pkgdtask { typedef void __type; }; template struct __constrain_pkgdtask<_Task, _Fn, true> { }; /// packaged_task template class packaged_task<_Res(_ArgTypes...)> { typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type; shared_ptr<_State_type> _M_state; public: // Construction and destruction packaged_task() noexcept { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2095. missing constructors needed for uses-allocator construction template packaged_task(allocator_arg_t, const _Allocator& __a) noexcept { } template::__type> explicit packaged_task(_Fn&& __fn) : packaged_task(allocator_arg, std::allocator(), std::forward<_Fn>(__fn)) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2097. packaged_task constructors should be constrained // 2407. [this constructor should not be] explicit template::__type> packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn) : _M_state(__create_task_state<_Res(_ArgTypes...)>( std::forward<_Fn>(__fn), __a)) { } ~packaged_task() { if (static_cast(_M_state) && !_M_state.unique()) _M_state->_M_break_promise(std::move(_M_state->_M_result)); } // No copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; template packaged_task(allocator_arg_t, const _Allocator&, const packaged_task&) = delete; // Move support packaged_task(packaged_task&& __other) noexcept { this->swap(__other); } template packaged_task(allocator_arg_t, const _Allocator&, packaged_task&& __other) noexcept { this->swap(__other); } packaged_task& operator=(packaged_task&& __other) noexcept { packaged_task(std::move(__other)).swap(*this); return *this; } void swap(packaged_task& __other) noexcept { _M_state.swap(__other._M_state); } bool valid() const noexcept { return static_cast(_M_state); } // Result retrieval future<_Res> get_future() { return future<_Res>(_M_state); } // Execution void operator()(_ArgTypes... __args) { __future_base::_State_base::_S_check(_M_state); _M_state->_M_run(std::forward<_ArgTypes>(__args)...); } void make_ready_at_thread_exit(_ArgTypes... __args) { __future_base::_State_base::_S_check(_M_state); _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state); } void reset() { __future_base::_State_base::_S_check(_M_state); packaged_task __tmp; __tmp._M_state = _M_state; _M_state = _M_state->_M_reset(); } }; /// swap template inline void swap(packaged_task<_Res(_ArgTypes...)>& __x, packaged_task<_Res(_ArgTypes...)>& __y) noexcept { __x.swap(__y); } template struct uses_allocator, _Alloc> : public true_type { }; // Shared state created by std::async(). // Holds a deferred function and storage for its result. template class __future_base::_Deferred_state final : public __future_base::_State_base { public: explicit _Deferred_state(_BoundFn&& __fn) : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn)) { } private: typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type; _Ptr_type _M_result; _BoundFn _M_fn; // Run the deferred function. virtual void _M_complete_async() { // Multiple threads can call a waiting function on the future and // reach this point at the same time. The call_once in _M_set_result // ensures only the first one run the deferred function, stores the // result in _M_result, swaps that with the base _M_result and makes // the state ready. Tell _M_set_result to ignore failure so all later // calls do nothing. _M_set_result(_S_task_setter(_M_result, _M_fn), true); } // Caller should check whether the state is ready first, because this // function will return true even after the deferred function has run. virtual bool _M_is_deferred_future() const { return true; } }; // Common functionality hoisted out of the _Async_state_impl template. class __future_base::_Async_state_commonV2 : public __future_base::_State_base { protected: ~_Async_state_commonV2() = default; // Make waiting functions block until the thread completes, as if joined. // // This function is used by wait() to satisfy the first requirement below // and by wait_for() / wait_until() to satisfy the second. // // [futures.async]: // // — a call to a waiting function on an asynchronous return object that // shares the shared state created by this async call shall block until // the associated thread has completed, as if joined, or else time out. // // — the associated thread completion synchronizes with the return from // the first function that successfully detects the ready status of the // shared state or with the return from the last function that releases // the shared state, whichever happens first. virtual void _M_complete_async() { _M_join(); } void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); } thread _M_thread; once_flag _M_once; }; // Shared state created by std::async(). // Starts a new thread that runs a function and makes the shared state ready. template class __future_base::_Async_state_impl final : public __future_base::_Async_state_commonV2 { public: explicit _Async_state_impl(_BoundFn&& __fn) : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn)) { _M_thread = std::thread{ [this] { __try { _M_set_result(_S_task_setter(_M_result, _M_fn)); } __catch (const __cxxabiv1::__forced_unwind&) { // make the shared state ready on thread cancellation if (static_cast(_M_result)) this->_M_break_promise(std::move(_M_result)); __throw_exception_again; } } }; } // Must not destroy _M_result and _M_fn until the thread finishes. // Call join() directly rather than through _M_join() because no other // thread can be referring to this state if it is being destroyed. ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); } private: typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type; _Ptr_type _M_result; _BoundFn _M_fn; }; template inline std::shared_ptr<__future_base::_State_base> __future_base::_S_make_deferred_state(_BoundFn&& __fn) { typedef typename remove_reference<_BoundFn>::type __fn_type; typedef _Deferred_state<__fn_type> __state_type; return std::make_shared<__state_type>(std::move(__fn)); } template inline std::shared_ptr<__future_base::_State_base> __future_base::_S_make_async_state(_BoundFn&& __fn) { typedef typename remove_reference<_BoundFn>::type __fn_type; typedef _Async_state_impl<__fn_type> __state_type; return std::make_shared<__state_type>(std::move(__fn)); } /// async template future<__async_result_of<_Fn, _Args...>> async(launch __policy, _Fn&& __fn, _Args&&... __args) { std::shared_ptr<__future_base::_State_base> __state; if ((__policy & launch::async) == launch::async) { __try { __state = __future_base::_S_make_async_state( std::thread::__make_invoker(std::forward<_Fn>(__fn), std::forward<_Args>(__args)...) ); } #if __cpp_exceptions catch(const system_error& __e) { if (__e.code() != errc::resource_unavailable_try_again || (__policy & launch::deferred) != launch::deferred) throw; } #endif } if (!__state) { __state = __future_base::_S_make_deferred_state( std::thread::__make_invoker(std::forward<_Fn>(__fn), std::forward<_Args>(__args)...)); } return future<__async_result_of<_Fn, _Args...>>(__state); } /// async, potential overload template inline future<__async_result_of<_Fn, _Args...>> async(_Fn&& __fn, _Args&&... __args) { return std::async(launch::async|launch::deferred, std::forward<_Fn>(__fn), std::forward<_Args>(__args)...); } #endif // _GLIBCXX_ASYNC_ABI_COMPAT #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1 // @} group futures _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif // _GLIBCXX_FUTURE c++/8/new000064400000016541151027430570006012 0ustar00// The -*- C++ -*- dynamic memory management header. // Copyright (C) 1994-2018 Free Software Foundation, Inc. // This file is part of GCC. // // GCC is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3, or (at your option) // any later version. // // GCC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file new * This is a Standard C++ Library header. * * The header @c new defines several functions to manage dynamic memory and * handling memory allocation errors; see * http://gcc.gnu.org/onlinedocs/libstdc++/18_support/howto.html#4 for more. */ #ifndef _NEW #define _NEW #pragma GCC system_header #include #include #pragma GCC visibility push(default) extern "C++" { namespace std { /** * @brief Exception possibly thrown by @c new. * @ingroup exceptions * * @c bad_alloc (or classes derived from it) is used to report allocation * errors from the throwing forms of @c new. */ class bad_alloc : public exception { public: bad_alloc() throw() { } // This declaration is not useless: // http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_6.html#SEC118 virtual ~bad_alloc() throw(); // See comment in eh_exception.cc. virtual const char* what() const throw(); }; #if __cplusplus >= 201103L class bad_array_new_length : public bad_alloc { public: bad_array_new_length() throw() { } // This declaration is not useless: // http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_6.html#SEC118 virtual ~bad_array_new_length() throw(); // See comment in eh_exception.cc. virtual const char* what() const throw(); }; #endif #if __cpp_aligned_new enum class align_val_t: size_t {}; #endif struct nothrow_t { #if __cplusplus >= 201103L explicit nothrow_t() = default; #endif }; extern const nothrow_t nothrow; /** If you write your own error handler to be called by @c new, it must * be of this type. */ typedef void (*new_handler)(); /// Takes a replacement handler as the argument, returns the /// previous handler. new_handler set_new_handler(new_handler) throw(); #if __cplusplus >= 201103L /// Return the current new handler. new_handler get_new_handler() noexcept; #endif } // namespace std //@{ /** These are replaceable signatures: * - normal single new and delete (no arguments, throw @c bad_alloc on error) * - normal array new and delete (same) * - @c nothrow single new and delete (take a @c nothrow argument, return * @c NULL on error) * - @c nothrow array new and delete (same) * * Placement new and delete signatures (take a memory address argument, * does nothing) may not be replaced by a user's program. */ void* operator new(std::size_t) _GLIBCXX_THROW (std::bad_alloc) __attribute__((__externally_visible__)); void* operator new[](std::size_t) _GLIBCXX_THROW (std::bad_alloc) __attribute__((__externally_visible__)); void operator delete(void*) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete[](void*) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); #if __cpp_sized_deallocation void operator delete(void*, std::size_t) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete[](void*, std::size_t) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); #endif void* operator new(std::size_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void* operator new[](std::size_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete(void*, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete[](void*, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); #if __cpp_aligned_new void* operator new(std::size_t, std::align_val_t) __attribute__((__externally_visible__)); void* operator new(std::size_t, std::align_val_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete(void*, std::align_val_t) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete(void*, std::align_val_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void* operator new[](std::size_t, std::align_val_t) __attribute__((__externally_visible__)); void* operator new[](std::size_t, std::align_val_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete[](void*, std::align_val_t) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete[](void*, std::align_val_t, const std::nothrow_t&) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); #if __cpp_sized_deallocation void operator delete(void*, std::size_t, std::align_val_t) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); void operator delete[](void*, std::size_t, std::align_val_t) _GLIBCXX_USE_NOEXCEPT __attribute__((__externally_visible__)); #endif // __cpp_sized_deallocation #endif // __cpp_aligned_new // Default placement versions of operator new. inline void* operator new(std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT { return __p; } inline void* operator new[](std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT { return __p; } // Default placement versions of operator delete. inline void operator delete (void*, void*) _GLIBCXX_USE_NOEXCEPT { } inline void operator delete[](void*, void*) _GLIBCXX_USE_NOEXCEPT { } //@} } // extern "C++" #if __cplusplus >= 201703L #if __GNUC__ >= 7 # define _GLIBCXX_HAVE_BUILTIN_LAUNDER 1 #elif defined __has_builtin // For non-GNU compilers: # if __has_builtin(__builtin_launder) # define _GLIBCXX_HAVE_BUILTIN_LAUNDER 1 # endif #endif #ifdef _GLIBCXX_HAVE_BUILTIN_LAUNDER namespace std { #define __cpp_lib_launder 201606 /// Pointer optimization barrier [ptr.launder] template [[nodiscard]] constexpr _Tp* launder(_Tp* __p) noexcept { return __builtin_launder(__p); } // The program is ill-formed if T is a function type or // (possibly cv-qualified) void. template void launder(_Ret (*)(_Args...) _GLIBCXX_NOEXCEPT_QUAL) = delete; template void launder(_Ret (*)(_Args......) _GLIBCXX_NOEXCEPT_QUAL) = delete; void launder(void*) = delete; void launder(const void*) = delete; void launder(volatile void*) = delete; void launder(const volatile void*) = delete; } #endif // _GLIBCXX_HAVE_BUILTIN_LAUNDER #undef _GLIBCXX_HAVE_BUILTIN_LAUNDER #endif // C++17 #pragma GCC visibility pop #endif c++/8/iterator000064400000005124151027430570007045 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/iterator * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_ITERATOR #define _GLIBCXX_ITERATOR 1 #pragma GCC system_header #include #include #include #include #include #include #include #include #include #endif /* _GLIBCXX_ITERATOR */ c++/8/system_error000064400000026402151027430570007753 0ustar00// -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/system_error * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_SYSTEM_ERROR #define _GLIBCXX_SYSTEM_ERROR 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION class error_code; class error_condition; class system_error; /// is_error_code_enum template struct is_error_code_enum : public false_type { }; /// is_error_condition_enum template struct is_error_condition_enum : public false_type { }; template<> struct is_error_condition_enum : public true_type { }; #if __cplusplus > 201402L template inline constexpr bool is_error_code_enum_v = is_error_code_enum<_Tp>::value; template inline constexpr bool is_error_condition_enum_v = is_error_condition_enum<_Tp>::value; #endif // C++17 inline namespace _V2 { /// error_category class error_category { public: constexpr error_category() noexcept = default; virtual ~error_category(); error_category(const error_category&) = delete; error_category& operator=(const error_category&) = delete; virtual const char* name() const noexcept = 0; // We need two different virtual functions here, one returning a // COW string and one returning an SSO string. Their positions in the // vtable must be consistent for dynamic dispatch to work, but which one // the name "message()" finds depends on which ABI the caller is using. #if _GLIBCXX_USE_CXX11_ABI private: _GLIBCXX_DEFAULT_ABI_TAG virtual __cow_string _M_message(int) const; public: _GLIBCXX_DEFAULT_ABI_TAG virtual string message(int) const = 0; #else virtual string message(int) const = 0; private: virtual __sso_string _M_message(int) const; #endif public: virtual error_condition default_error_condition(int __i) const noexcept; virtual bool equivalent(int __i, const error_condition& __cond) const noexcept; virtual bool equivalent(const error_code& __code, int __i) const noexcept; bool operator<(const error_category& __other) const noexcept { return less()(this, &__other); } bool operator==(const error_category& __other) const noexcept { return this == &__other; } bool operator!=(const error_category& __other) const noexcept { return this != &__other; } }; // DR 890. _GLIBCXX_CONST const error_category& system_category() noexcept; _GLIBCXX_CONST const error_category& generic_category() noexcept; } // end inline namespace error_code make_error_code(errc) noexcept; template struct hash; /// error_code // Implementation-specific error identification struct error_code { error_code() noexcept : _M_value(0), _M_cat(&system_category()) { } error_code(int __v, const error_category& __cat) noexcept : _M_value(__v), _M_cat(&__cat) { } template::value>::type> error_code(_ErrorCodeEnum __e) noexcept { *this = make_error_code(__e); } void assign(int __v, const error_category& __cat) noexcept { _M_value = __v; _M_cat = &__cat; } void clear() noexcept { assign(0, system_category()); } // DR 804. template typename enable_if::value, error_code&>::type operator=(_ErrorCodeEnum __e) noexcept { return *this = make_error_code(__e); } int value() const noexcept { return _M_value; } const error_category& category() const noexcept { return *_M_cat; } error_condition default_error_condition() const noexcept; _GLIBCXX_DEFAULT_ABI_TAG string message() const { return category().message(value()); } explicit operator bool() const noexcept { return _M_value != 0; } // DR 804. private: friend class hash; int _M_value; const error_category* _M_cat; }; // 19.4.2.6 non-member functions inline error_code make_error_code(errc __e) noexcept { return error_code(static_cast(__e), generic_category()); } inline bool operator<(const error_code& __lhs, const error_code& __rhs) noexcept { return (__lhs.category() < __rhs.category() || (__lhs.category() == __rhs.category() && __lhs.value() < __rhs.value())); } template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const error_code& __e) { return (__os << __e.category().name() << ':' << __e.value()); } error_condition make_error_condition(errc) noexcept; /// error_condition // Portable error identification struct error_condition { error_condition() noexcept : _M_value(0), _M_cat(&generic_category()) { } error_condition(int __v, const error_category& __cat) noexcept : _M_value(__v), _M_cat(&__cat) { } template::value>::type> error_condition(_ErrorConditionEnum __e) noexcept { *this = make_error_condition(__e); } void assign(int __v, const error_category& __cat) noexcept { _M_value = __v; _M_cat = &__cat; } // DR 804. template typename enable_if::value, error_condition&>::type operator=(_ErrorConditionEnum __e) noexcept { return *this = make_error_condition(__e); } void clear() noexcept { assign(0, generic_category()); } // 19.4.3.4 observers int value() const noexcept { return _M_value; } const error_category& category() const noexcept { return *_M_cat; } _GLIBCXX_DEFAULT_ABI_TAG string message() const { return category().message(value()); } explicit operator bool() const noexcept { return _M_value != 0; } // DR 804. private: int _M_value; const error_category* _M_cat; }; // 19.4.3.6 non-member functions inline error_condition make_error_condition(errc __e) noexcept { return error_condition(static_cast(__e), generic_category()); } inline bool operator<(const error_condition& __lhs, const error_condition& __rhs) noexcept { return (__lhs.category() < __rhs.category() || (__lhs.category() == __rhs.category() && __lhs.value() < __rhs.value())); } // 19.4.4 Comparison operators inline bool operator==(const error_code& __lhs, const error_code& __rhs) noexcept { return (__lhs.category() == __rhs.category() && __lhs.value() == __rhs.value()); } inline bool operator==(const error_code& __lhs, const error_condition& __rhs) noexcept { return (__lhs.category().equivalent(__lhs.value(), __rhs) || __rhs.category().equivalent(__lhs, __rhs.value())); } inline bool operator==(const error_condition& __lhs, const error_code& __rhs) noexcept { return (__rhs.category().equivalent(__rhs.value(), __lhs) || __lhs.category().equivalent(__rhs, __lhs.value())); } inline bool operator==(const error_condition& __lhs, const error_condition& __rhs) noexcept { return (__lhs.category() == __rhs.category() && __lhs.value() == __rhs.value()); } inline bool operator!=(const error_code& __lhs, const error_code& __rhs) noexcept { return !(__lhs == __rhs); } inline bool operator!=(const error_code& __lhs, const error_condition& __rhs) noexcept { return !(__lhs == __rhs); } inline bool operator!=(const error_condition& __lhs, const error_code& __rhs) noexcept { return !(__lhs == __rhs); } inline bool operator!=(const error_condition& __lhs, const error_condition& __rhs) noexcept { return !(__lhs == __rhs); } /** * @brief Thrown to indicate error code of underlying system. * * @ingroup exceptions */ class system_error : public std::runtime_error { private: error_code _M_code; public: system_error(error_code __ec = error_code()) : runtime_error(__ec.message()), _M_code(__ec) { } system_error(error_code __ec, const string& __what) : runtime_error(__what + ": " + __ec.message()), _M_code(__ec) { } system_error(error_code __ec, const char* __what) : runtime_error(__what + (": " + __ec.message())), _M_code(__ec) { } system_error(int __v, const error_category& __ecat, const char* __what) : system_error(error_code(__v, __ecat), __what) { } system_error(int __v, const error_category& __ecat) : runtime_error(error_code(__v, __ecat).message()), _M_code(__v, __ecat) { } system_error(int __v, const error_category& __ecat, const string& __what) : runtime_error(__what + ": " + error_code(__v, __ecat).message()), _M_code(__v, __ecat) { } virtual ~system_error() noexcept; const error_code& code() const noexcept { return _M_code; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #ifndef _GLIBCXX_COMPATIBILITY_CXX0X // DR 1182. /// std::hash specialization for error_code. template<> struct hash : public __hash_base { size_t operator()(const error_code& __e) const noexcept { const size_t __tmp = std::_Hash_impl::hash(__e._M_value); return std::_Hash_impl::__hash_combine(__e._M_cat, __tmp); } }; #endif // _GLIBCXX_COMPATIBILITY_CXX0X #if __cplusplus > 201402L // DR 2686. /// std::hash specialization for error_condition. template<> struct hash : public __hash_base { size_t operator()(const error_condition& __e) const noexcept { const size_t __tmp = std::_Hash_impl::hash(__e.value()); return std::_Hash_impl::__hash_combine(__e.category(), __tmp); } }; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif // _GLIBCXX_SYSTEM_ERROR c++/8/set000064400000004777151027430570006024 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/set * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_SET #define _GLIBCXX_SET 1 #pragma GCC system_header #include #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_SET */ c++/8/complex000064400000152411151027430570006665 0ustar00// The template and inlines for the -*- C++ -*- complex number classes. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/complex * This is a Standard C++ Library header. */ // // ISO C++ 14882: 26.2 Complex Numbers // Note: this is not a conforming implementation. // Initially implemented by Ulrich Drepper // Improved by Gabriel Dos Reis // #ifndef _GLIBCXX_COMPLEX #define _GLIBCXX_COMPLEX 1 #pragma GCC system_header #include #include #include #include #include // Get rid of a macro possibly defined in #undef complex namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup complex_numbers Complex Numbers * @ingroup numerics * * Classes and functions for complex numbers. * @{ */ // Forward declarations. template class complex; template<> class complex; template<> class complex; template<> class complex; /// Return magnitude of @a z. template _Tp abs(const complex<_Tp>&); /// Return phase angle of @a z. template _Tp arg(const complex<_Tp>&); /// Return @a z magnitude squared. template _Tp norm(const complex<_Tp>&); /// Return complex conjugate of @a z. template complex<_Tp> conj(const complex<_Tp>&); /// Return complex with magnitude @a rho and angle @a theta. template complex<_Tp> polar(const _Tp&, const _Tp& = 0); // Transcendentals: /// Return complex cosine of @a z. template complex<_Tp> cos(const complex<_Tp>&); /// Return complex hyperbolic cosine of @a z. template complex<_Tp> cosh(const complex<_Tp>&); /// Return complex base e exponential of @a z. template complex<_Tp> exp(const complex<_Tp>&); /// Return complex natural logarithm of @a z. template complex<_Tp> log(const complex<_Tp>&); /// Return complex base 10 logarithm of @a z. template complex<_Tp> log10(const complex<_Tp>&); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const complex<_Tp>&, int); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const complex<_Tp>&, const _Tp&); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const complex<_Tp>&, const complex<_Tp>&); /// Return @a x to the @a y'th power. template complex<_Tp> pow(const _Tp&, const complex<_Tp>&); /// Return complex sine of @a z. template complex<_Tp> sin(const complex<_Tp>&); /// Return complex hyperbolic sine of @a z. template complex<_Tp> sinh(const complex<_Tp>&); /// Return complex square root of @a z. template complex<_Tp> sqrt(const complex<_Tp>&); /// Return complex tangent of @a z. template complex<_Tp> tan(const complex<_Tp>&); /// Return complex hyperbolic tangent of @a z. template complex<_Tp> tanh(const complex<_Tp>&); // 26.2.2 Primary template class complex /** * Template to represent complex numbers. * * Specializations for float, double, and long double are part of the * library. Results with any other type are not guaranteed. * * @param Tp Type of real and imaginary values. */ template struct complex { /// Value typedef. typedef _Tp value_type; /// Default constructor. First parameter is x, second parameter is y. /// Unspecified parameters default to 0. _GLIBCXX_CONSTEXPR complex(const _Tp& __r = _Tp(), const _Tp& __i = _Tp()) : _M_real(__r), _M_imag(__i) { } // Let the compiler synthesize the copy constructor #if __cplusplus >= 201103L constexpr complex(const complex&) = default; #endif /// Converting constructor. template _GLIBCXX_CONSTEXPR complex(const complex<_Up>& __z) : _M_real(__z.real()), _M_imag(__z.imag()) { } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. _GLIBCXX_ABI_TAG_CXX11 constexpr _Tp real() const { return _M_real; } _GLIBCXX_ABI_TAG_CXX11 constexpr _Tp imag() const { return _M_imag; } #else /// Return real part of complex number. _Tp& real() { return _M_real; } /// Return real part of complex number. const _Tp& real() const { return _M_real; } /// Return imaginary part of complex number. _Tp& imag() { return _M_imag; } /// Return imaginary part of complex number. const _Tp& imag() const { return _M_imag; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(_Tp __val) { _M_real = __val; } void imag(_Tp __val) { _M_imag = __val; } /// Assign a scalar to this complex number. complex<_Tp>& operator=(const _Tp&); /// Add a scalar to this complex number. // 26.2.5/1 complex<_Tp>& operator+=(const _Tp& __t) { _M_real += __t; return *this; } /// Subtract a scalar from this complex number. // 26.2.5/3 complex<_Tp>& operator-=(const _Tp& __t) { _M_real -= __t; return *this; } /// Multiply this complex number by a scalar. complex<_Tp>& operator*=(const _Tp&); /// Divide this complex number by a scalar. complex<_Tp>& operator/=(const _Tp&); // Let the compiler synthesize the copy assignment operator #if __cplusplus >= 201103L complex& operator=(const complex&) = default; #endif /// Assign another complex number to this one. template complex<_Tp>& operator=(const complex<_Up>&); /// Add another complex number to this one. template complex<_Tp>& operator+=(const complex<_Up>&); /// Subtract another complex number from this one. template complex<_Tp>& operator-=(const complex<_Up>&); /// Multiply this complex number by another. template complex<_Tp>& operator*=(const complex<_Up>&); /// Divide this complex number by another. template complex<_Tp>& operator/=(const complex<_Up>&); _GLIBCXX_CONSTEXPR complex __rep() const { return *this; } private: _Tp _M_real; _Tp _M_imag; }; template complex<_Tp>& complex<_Tp>::operator=(const _Tp& __t) { _M_real = __t; _M_imag = _Tp(); return *this; } // 26.2.5/5 template complex<_Tp>& complex<_Tp>::operator*=(const _Tp& __t) { _M_real *= __t; _M_imag *= __t; return *this; } // 26.2.5/7 template complex<_Tp>& complex<_Tp>::operator/=(const _Tp& __t) { _M_real /= __t; _M_imag /= __t; return *this; } template template complex<_Tp>& complex<_Tp>::operator=(const complex<_Up>& __z) { _M_real = __z.real(); _M_imag = __z.imag(); return *this; } // 26.2.5/9 template template complex<_Tp>& complex<_Tp>::operator+=(const complex<_Up>& __z) { _M_real += __z.real(); _M_imag += __z.imag(); return *this; } // 26.2.5/11 template template complex<_Tp>& complex<_Tp>::operator-=(const complex<_Up>& __z) { _M_real -= __z.real(); _M_imag -= __z.imag(); return *this; } // 26.2.5/13 // XXX: This is a grammar school implementation. template template complex<_Tp>& complex<_Tp>::operator*=(const complex<_Up>& __z) { const _Tp __r = _M_real * __z.real() - _M_imag * __z.imag(); _M_imag = _M_real * __z.imag() + _M_imag * __z.real(); _M_real = __r; return *this; } // 26.2.5/15 // XXX: This is a grammar school implementation. template template complex<_Tp>& complex<_Tp>::operator/=(const complex<_Up>& __z) { const _Tp __r = _M_real * __z.real() + _M_imag * __z.imag(); const _Tp __n = std::norm(__z); _M_imag = (_M_imag * __z.real() - _M_real * __z.imag()) / __n; _M_real = __r / __n; return *this; } // Operators: //@{ /// Return new complex value @a x plus @a y. template inline complex<_Tp> operator+(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r += __y; return __r; } template inline complex<_Tp> operator+(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r += __y; return __r; } template inline complex<_Tp> operator+(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __y; __r += __x; return __r; } //@} //@{ /// Return new complex value @a x minus @a y. template inline complex<_Tp> operator-(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r -= __y; return __r; } template inline complex<_Tp> operator-(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r -= __y; return __r; } template inline complex<_Tp> operator-(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r(__x, -__y.imag()); __r -= __y.real(); return __r; } //@} //@{ /// Return new complex value @a x times @a y. template inline complex<_Tp> operator*(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r *= __y; return __r; } template inline complex<_Tp> operator*(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r *= __y; return __r; } template inline complex<_Tp> operator*(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __y; __r *= __x; return __r; } //@} //@{ /// Return new complex value @a x divided by @a y. template inline complex<_Tp> operator/(const complex<_Tp>& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r /= __y; return __r; } template inline complex<_Tp> operator/(const complex<_Tp>& __x, const _Tp& __y) { complex<_Tp> __r = __x; __r /= __y; return __r; } template inline complex<_Tp> operator/(const _Tp& __x, const complex<_Tp>& __y) { complex<_Tp> __r = __x; __r /= __y; return __r; } //@} /// Return @a x. template inline complex<_Tp> operator+(const complex<_Tp>& __x) { return __x; } /// Return complex negation of @a x. template inline complex<_Tp> operator-(const complex<_Tp>& __x) { return complex<_Tp>(-__x.real(), -__x.imag()); } //@{ /// Return true if @a x is equal to @a y. template inline _GLIBCXX_CONSTEXPR bool operator==(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __x.real() == __y.real() && __x.imag() == __y.imag(); } template inline _GLIBCXX_CONSTEXPR bool operator==(const complex<_Tp>& __x, const _Tp& __y) { return __x.real() == __y && __x.imag() == _Tp(); } template inline _GLIBCXX_CONSTEXPR bool operator==(const _Tp& __x, const complex<_Tp>& __y) { return __x == __y.real() && _Tp() == __y.imag(); } //@} //@{ /// Return false if @a x is equal to @a y. template inline _GLIBCXX_CONSTEXPR bool operator!=(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __x.real() != __y.real() || __x.imag() != __y.imag(); } template inline _GLIBCXX_CONSTEXPR bool operator!=(const complex<_Tp>& __x, const _Tp& __y) { return __x.real() != __y || __x.imag() != _Tp(); } template inline _GLIBCXX_CONSTEXPR bool operator!=(const _Tp& __x, const complex<_Tp>& __y) { return __x != __y.real() || _Tp() != __y.imag(); } //@} /// Extraction operator for complex values. template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __is, complex<_Tp>& __x) { bool __fail = true; _CharT __ch; if (__is >> __ch) { if (_Traits::eq(__ch, __is.widen('('))) { _Tp __u; if (__is >> __u >> __ch) { const _CharT __rparen = __is.widen(')'); if (_Traits::eq(__ch, __rparen)) { __x = __u; __fail = false; } else if (_Traits::eq(__ch, __is.widen(','))) { _Tp __v; if (__is >> __v >> __ch) { if (_Traits::eq(__ch, __rparen)) { __x = complex<_Tp>(__u, __v); __fail = false; } else __is.putback(__ch); } } else __is.putback(__ch); } } else { __is.putback(__ch); _Tp __u; if (__is >> __u) { __x = __u; __fail = false; } } } if (__fail) __is.setstate(ios_base::failbit); return __is; } /// Insertion operator for complex values. template basic_ostream<_CharT, _Traits>& operator<<(basic_ostream<_CharT, _Traits>& __os, const complex<_Tp>& __x) { basic_ostringstream<_CharT, _Traits> __s; __s.flags(__os.flags()); __s.imbue(__os.getloc()); __s.precision(__os.precision()); __s << '(' << __x.real() << ',' << __x.imag() << ')'; return __os << __s.str(); } // Values #if __cplusplus >= 201103L template constexpr _Tp real(const complex<_Tp>& __z) { return __z.real(); } template constexpr _Tp imag(const complex<_Tp>& __z) { return __z.imag(); } #else template inline _Tp& real(complex<_Tp>& __z) { return __z.real(); } template inline const _Tp& real(const complex<_Tp>& __z) { return __z.real(); } template inline _Tp& imag(complex<_Tp>& __z) { return __z.imag(); } template inline const _Tp& imag(const complex<_Tp>& __z) { return __z.imag(); } #endif // 26.2.7/3 abs(__z): Returns the magnitude of __z. template inline _Tp __complex_abs(const complex<_Tp>& __z) { _Tp __x = __z.real(); _Tp __y = __z.imag(); const _Tp __s = std::max(abs(__x), abs(__y)); if (__s == _Tp()) // well ... return __s; __x /= __s; __y /= __s; return __s * sqrt(__x * __x + __y * __y); } #if _GLIBCXX_USE_C99_COMPLEX inline float __complex_abs(__complex__ float __z) { return __builtin_cabsf(__z); } inline double __complex_abs(__complex__ double __z) { return __builtin_cabs(__z); } inline long double __complex_abs(const __complex__ long double& __z) { return __builtin_cabsl(__z); } template inline _Tp abs(const complex<_Tp>& __z) { return __complex_abs(__z.__rep()); } #else template inline _Tp abs(const complex<_Tp>& __z) { return __complex_abs(__z); } #endif // 26.2.7/4: arg(__z): Returns the phase angle of __z. template inline _Tp __complex_arg(const complex<_Tp>& __z) { return atan2(__z.imag(), __z.real()); } #if _GLIBCXX_USE_C99_COMPLEX inline float __complex_arg(__complex__ float __z) { return __builtin_cargf(__z); } inline double __complex_arg(__complex__ double __z) { return __builtin_carg(__z); } inline long double __complex_arg(const __complex__ long double& __z) { return __builtin_cargl(__z); } template inline _Tp arg(const complex<_Tp>& __z) { return __complex_arg(__z.__rep()); } #else template inline _Tp arg(const complex<_Tp>& __z) { return __complex_arg(__z); } #endif // 26.2.7/5: norm(__z) returns the squared magnitude of __z. // As defined, norm() is -not- a norm is the common mathematical // sense used in numerics. The helper class _Norm_helper<> tries to // distinguish between builtin floating point and the rest, so as // to deliver an answer as close as possible to the real value. template struct _Norm_helper { template static inline _Tp _S_do_it(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return __x * __x + __y * __y; } }; template<> struct _Norm_helper { template static inline _Tp _S_do_it(const complex<_Tp>& __z) { _Tp __res = std::abs(__z); return __res * __res; } }; template inline _Tp norm(const complex<_Tp>& __z) { return _Norm_helper<__is_floating<_Tp>::__value && !_GLIBCXX_FAST_MATH>::_S_do_it(__z); } template inline complex<_Tp> polar(const _Tp& __rho, const _Tp& __theta) { __glibcxx_assert( __rho >= 0 ); return complex<_Tp>(__rho * cos(__theta), __rho * sin(__theta)); } template inline complex<_Tp> conj(const complex<_Tp>& __z) { return complex<_Tp>(__z.real(), -__z.imag()); } // Transcendentals // 26.2.8/1 cos(__z): Returns the cosine of __z. template inline complex<_Tp> __complex_cos(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(cos(__x) * cosh(__y), -sin(__x) * sinh(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_cos(__complex__ float __z) { return __builtin_ccosf(__z); } inline __complex__ double __complex_cos(__complex__ double __z) { return __builtin_ccos(__z); } inline __complex__ long double __complex_cos(const __complex__ long double& __z) { return __builtin_ccosl(__z); } template inline complex<_Tp> cos(const complex<_Tp>& __z) { return __complex_cos(__z.__rep()); } #else template inline complex<_Tp> cos(const complex<_Tp>& __z) { return __complex_cos(__z); } #endif // 26.2.8/2 cosh(__z): Returns the hyperbolic cosine of __z. template inline complex<_Tp> __complex_cosh(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(cosh(__x) * cos(__y), sinh(__x) * sin(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_cosh(__complex__ float __z) { return __builtin_ccoshf(__z); } inline __complex__ double __complex_cosh(__complex__ double __z) { return __builtin_ccosh(__z); } inline __complex__ long double __complex_cosh(const __complex__ long double& __z) { return __builtin_ccoshl(__z); } template inline complex<_Tp> cosh(const complex<_Tp>& __z) { return __complex_cosh(__z.__rep()); } #else template inline complex<_Tp> cosh(const complex<_Tp>& __z) { return __complex_cosh(__z); } #endif // 26.2.8/3 exp(__z): Returns the complex base e exponential of x template inline complex<_Tp> __complex_exp(const complex<_Tp>& __z) { return std::polar<_Tp>(exp(__z.real()), __z.imag()); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_exp(__complex__ float __z) { return __builtin_cexpf(__z); } inline __complex__ double __complex_exp(__complex__ double __z) { return __builtin_cexp(__z); } inline __complex__ long double __complex_exp(const __complex__ long double& __z) { return __builtin_cexpl(__z); } template inline complex<_Tp> exp(const complex<_Tp>& __z) { return __complex_exp(__z.__rep()); } #else template inline complex<_Tp> exp(const complex<_Tp>& __z) { return __complex_exp(__z); } #endif // 26.2.8/5 log(__z): Returns the natural complex logarithm of __z. // The branch cut is along the negative axis. template inline complex<_Tp> __complex_log(const complex<_Tp>& __z) { return complex<_Tp>(log(std::abs(__z)), std::arg(__z)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_log(__complex__ float __z) { return __builtin_clogf(__z); } inline __complex__ double __complex_log(__complex__ double __z) { return __builtin_clog(__z); } inline __complex__ long double __complex_log(const __complex__ long double& __z) { return __builtin_clogl(__z); } template inline complex<_Tp> log(const complex<_Tp>& __z) { return __complex_log(__z.__rep()); } #else template inline complex<_Tp> log(const complex<_Tp>& __z) { return __complex_log(__z); } #endif template inline complex<_Tp> log10(const complex<_Tp>& __z) { return std::log(__z) / log(_Tp(10.0)); } // 26.2.8/10 sin(__z): Returns the sine of __z. template inline complex<_Tp> __complex_sin(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(sin(__x) * cosh(__y), cos(__x) * sinh(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_sin(__complex__ float __z) { return __builtin_csinf(__z); } inline __complex__ double __complex_sin(__complex__ double __z) { return __builtin_csin(__z); } inline __complex__ long double __complex_sin(const __complex__ long double& __z) { return __builtin_csinl(__z); } template inline complex<_Tp> sin(const complex<_Tp>& __z) { return __complex_sin(__z.__rep()); } #else template inline complex<_Tp> sin(const complex<_Tp>& __z) { return __complex_sin(__z); } #endif // 26.2.8/11 sinh(__z): Returns the hyperbolic sine of __z. template inline complex<_Tp> __complex_sinh(const complex<_Tp>& __z) { const _Tp __x = __z.real(); const _Tp __y = __z.imag(); return complex<_Tp>(sinh(__x) * cos(__y), cosh(__x) * sin(__y)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_sinh(__complex__ float __z) { return __builtin_csinhf(__z); } inline __complex__ double __complex_sinh(__complex__ double __z) { return __builtin_csinh(__z); } inline __complex__ long double __complex_sinh(const __complex__ long double& __z) { return __builtin_csinhl(__z); } template inline complex<_Tp> sinh(const complex<_Tp>& __z) { return __complex_sinh(__z.__rep()); } #else template inline complex<_Tp> sinh(const complex<_Tp>& __z) { return __complex_sinh(__z); } #endif // 26.2.8/13 sqrt(__z): Returns the complex square root of __z. // The branch cut is on the negative axis. template complex<_Tp> __complex_sqrt(const complex<_Tp>& __z) { _Tp __x = __z.real(); _Tp __y = __z.imag(); if (__x == _Tp()) { _Tp __t = sqrt(abs(__y) / 2); return complex<_Tp>(__t, __y < _Tp() ? -__t : __t); } else { _Tp __t = sqrt(2 * (std::abs(__z) + abs(__x))); _Tp __u = __t / 2; return __x > _Tp() ? complex<_Tp>(__u, __y / __t) : complex<_Tp>(abs(__y) / __t, __y < _Tp() ? -__u : __u); } } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_sqrt(__complex__ float __z) { return __builtin_csqrtf(__z); } inline __complex__ double __complex_sqrt(__complex__ double __z) { return __builtin_csqrt(__z); } inline __complex__ long double __complex_sqrt(const __complex__ long double& __z) { return __builtin_csqrtl(__z); } template inline complex<_Tp> sqrt(const complex<_Tp>& __z) { return __complex_sqrt(__z.__rep()); } #else template inline complex<_Tp> sqrt(const complex<_Tp>& __z) { return __complex_sqrt(__z); } #endif // 26.2.8/14 tan(__z): Return the complex tangent of __z. template inline complex<_Tp> __complex_tan(const complex<_Tp>& __z) { return std::sin(__z) / std::cos(__z); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_tan(__complex__ float __z) { return __builtin_ctanf(__z); } inline __complex__ double __complex_tan(__complex__ double __z) { return __builtin_ctan(__z); } inline __complex__ long double __complex_tan(const __complex__ long double& __z) { return __builtin_ctanl(__z); } template inline complex<_Tp> tan(const complex<_Tp>& __z) { return __complex_tan(__z.__rep()); } #else template inline complex<_Tp> tan(const complex<_Tp>& __z) { return __complex_tan(__z); } #endif // 26.2.8/15 tanh(__z): Returns the hyperbolic tangent of __z. template inline complex<_Tp> __complex_tanh(const complex<_Tp>& __z) { return std::sinh(__z) / std::cosh(__z); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_tanh(__complex__ float __z) { return __builtin_ctanhf(__z); } inline __complex__ double __complex_tanh(__complex__ double __z) { return __builtin_ctanh(__z); } inline __complex__ long double __complex_tanh(const __complex__ long double& __z) { return __builtin_ctanhl(__z); } template inline complex<_Tp> tanh(const complex<_Tp>& __z) { return __complex_tanh(__z.__rep()); } #else template inline complex<_Tp> tanh(const complex<_Tp>& __z) { return __complex_tanh(__z); } #endif // 26.2.8/9 pow(__x, __y): Returns the complex power base of __x // raised to the __y-th power. The branch // cut is on the negative axis. template complex<_Tp> __complex_pow_unsigned(complex<_Tp> __x, unsigned __n) { complex<_Tp> __y = __n % 2 ? __x : complex<_Tp>(1); while (__n >>= 1) { __x *= __x; if (__n % 2) __y *= __x; } return __y; } // In C++11 mode we used to implement the resolution of // DR 844. complex pow return type is ambiguous. // thus the following overload was disabled in that mode. However, doing // that causes all sorts of issues, see, for example: // http://gcc.gnu.org/ml/libstdc++/2013-01/msg00058.html // and also PR57974. template inline complex<_Tp> pow(const complex<_Tp>& __z, int __n) { return __n < 0 ? complex<_Tp>(1) / std::__complex_pow_unsigned(__z, -(unsigned)__n) : std::__complex_pow_unsigned(__z, __n); } template complex<_Tp> pow(const complex<_Tp>& __x, const _Tp& __y) { #if ! _GLIBCXX_USE_C99_COMPLEX if (__x == _Tp()) return _Tp(); #endif if (__x.imag() == _Tp() && __x.real() > _Tp()) return pow(__x.real(), __y); complex<_Tp> __t = std::log(__x); return std::polar<_Tp>(exp(__y * __t.real()), __y * __t.imag()); } template inline complex<_Tp> __complex_pow(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __x == _Tp() ? _Tp() : std::exp(__y * std::log(__x)); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_pow(__complex__ float __x, __complex__ float __y) { return __builtin_cpowf(__x, __y); } inline __complex__ double __complex_pow(__complex__ double __x, __complex__ double __y) { return __builtin_cpow(__x, __y); } inline __complex__ long double __complex_pow(const __complex__ long double& __x, const __complex__ long double& __y) { return __builtin_cpowl(__x, __y); } template inline complex<_Tp> pow(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __complex_pow(__x.__rep(), __y.__rep()); } #else template inline complex<_Tp> pow(const complex<_Tp>& __x, const complex<_Tp>& __y) { return __complex_pow(__x, __y); } #endif template inline complex<_Tp> pow(const _Tp& __x, const complex<_Tp>& __y) { return __x > _Tp() ? std::polar<_Tp>(pow(__x, __y.real()), __y.imag() * log(__x)) : std::pow(complex<_Tp>(__x), __y); } /// 26.2.3 complex specializations /// complex specialization template<> struct complex { typedef float value_type; typedef __complex__ float _ComplexT; _GLIBCXX_CONSTEXPR complex(_ComplexT __z) : _M_value(__z) { } _GLIBCXX_CONSTEXPR complex(float __r = 0.0f, float __i = 0.0f) #if __cplusplus >= 201103L : _M_value{ __r, __i } { } #else { __real__ _M_value = __r; __imag__ _M_value = __i; } #endif explicit _GLIBCXX_CONSTEXPR complex(const complex&); explicit _GLIBCXX_CONSTEXPR complex(const complex&); #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. __attribute ((__abi_tag__ ("cxx11"))) constexpr float real() const { return __real__ _M_value; } __attribute ((__abi_tag__ ("cxx11"))) constexpr float imag() const { return __imag__ _M_value; } #else float& real() { return __real__ _M_value; } const float& real() const { return __real__ _M_value; } float& imag() { return __imag__ _M_value; } const float& imag() const { return __imag__ _M_value; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(float __val) { __real__ _M_value = __val; } void imag(float __val) { __imag__ _M_value = __val; } complex& operator=(float __f) { _M_value = __f; return *this; } complex& operator+=(float __f) { _M_value += __f; return *this; } complex& operator-=(float __f) { _M_value -= __f; return *this; } complex& operator*=(float __f) { _M_value *= __f; return *this; } complex& operator/=(float __f) { _M_value /= __f; return *this; } // Let the compiler synthesize the copy and assignment // operator. It always does a pretty good job. // complex& operator=(const complex&); template complex& operator=(const complex<_Tp>& __z) { __real__ _M_value = __z.real(); __imag__ _M_value = __z.imag(); return *this; } template complex& operator+=(const complex<_Tp>& __z) { __real__ _M_value += __z.real(); __imag__ _M_value += __z.imag(); return *this; } template complex& operator-=(const complex<_Tp>& __z) { __real__ _M_value -= __z.real(); __imag__ _M_value -= __z.imag(); return *this; } template complex& operator*=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value *= __t; return *this; } template complex& operator/=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value /= __t; return *this; } _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; } private: _ComplexT _M_value; }; /// 26.2.3 complex specializations /// complex specialization template<> struct complex { typedef double value_type; typedef __complex__ double _ComplexT; _GLIBCXX_CONSTEXPR complex(_ComplexT __z) : _M_value(__z) { } _GLIBCXX_CONSTEXPR complex(double __r = 0.0, double __i = 0.0) #if __cplusplus >= 201103L : _M_value{ __r, __i } { } #else { __real__ _M_value = __r; __imag__ _M_value = __i; } #endif _GLIBCXX_CONSTEXPR complex(const complex& __z) : _M_value(__z.__rep()) { } explicit _GLIBCXX_CONSTEXPR complex(const complex&); #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. __attribute ((__abi_tag__ ("cxx11"))) constexpr double real() const { return __real__ _M_value; } __attribute ((__abi_tag__ ("cxx11"))) constexpr double imag() const { return __imag__ _M_value; } #else double& real() { return __real__ _M_value; } const double& real() const { return __real__ _M_value; } double& imag() { return __imag__ _M_value; } const double& imag() const { return __imag__ _M_value; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(double __val) { __real__ _M_value = __val; } void imag(double __val) { __imag__ _M_value = __val; } complex& operator=(double __d) { _M_value = __d; return *this; } complex& operator+=(double __d) { _M_value += __d; return *this; } complex& operator-=(double __d) { _M_value -= __d; return *this; } complex& operator*=(double __d) { _M_value *= __d; return *this; } complex& operator/=(double __d) { _M_value /= __d; return *this; } // The compiler will synthesize this, efficiently. // complex& operator=(const complex&); template complex& operator=(const complex<_Tp>& __z) { __real__ _M_value = __z.real(); __imag__ _M_value = __z.imag(); return *this; } template complex& operator+=(const complex<_Tp>& __z) { __real__ _M_value += __z.real(); __imag__ _M_value += __z.imag(); return *this; } template complex& operator-=(const complex<_Tp>& __z) { __real__ _M_value -= __z.real(); __imag__ _M_value -= __z.imag(); return *this; } template complex& operator*=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value *= __t; return *this; } template complex& operator/=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value /= __t; return *this; } _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; } private: _ComplexT _M_value; }; /// 26.2.3 complex specializations /// complex specialization template<> struct complex { typedef long double value_type; typedef __complex__ long double _ComplexT; _GLIBCXX_CONSTEXPR complex(_ComplexT __z) : _M_value(__z) { } _GLIBCXX_CONSTEXPR complex(long double __r = 0.0L, long double __i = 0.0L) #if __cplusplus >= 201103L : _M_value{ __r, __i } { } #else { __real__ _M_value = __r; __imag__ _M_value = __i; } #endif _GLIBCXX_CONSTEXPR complex(const complex& __z) : _M_value(__z.__rep()) { } _GLIBCXX_CONSTEXPR complex(const complex& __z) : _M_value(__z.__rep()) { } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. __attribute ((__abi_tag__ ("cxx11"))) constexpr long double real() const { return __real__ _M_value; } __attribute ((__abi_tag__ ("cxx11"))) constexpr long double imag() const { return __imag__ _M_value; } #else long double& real() { return __real__ _M_value; } const long double& real() const { return __real__ _M_value; } long double& imag() { return __imag__ _M_value; } const long double& imag() const { return __imag__ _M_value; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 387. std::complex over-encapsulated. void real(long double __val) { __real__ _M_value = __val; } void imag(long double __val) { __imag__ _M_value = __val; } complex& operator=(long double __r) { _M_value = __r; return *this; } complex& operator+=(long double __r) { _M_value += __r; return *this; } complex& operator-=(long double __r) { _M_value -= __r; return *this; } complex& operator*=(long double __r) { _M_value *= __r; return *this; } complex& operator/=(long double __r) { _M_value /= __r; return *this; } // The compiler knows how to do this efficiently // complex& operator=(const complex&); template complex& operator=(const complex<_Tp>& __z) { __real__ _M_value = __z.real(); __imag__ _M_value = __z.imag(); return *this; } template complex& operator+=(const complex<_Tp>& __z) { __real__ _M_value += __z.real(); __imag__ _M_value += __z.imag(); return *this; } template complex& operator-=(const complex<_Tp>& __z) { __real__ _M_value -= __z.real(); __imag__ _M_value -= __z.imag(); return *this; } template complex& operator*=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value *= __t; return *this; } template complex& operator/=(const complex<_Tp>& __z) { _ComplexT __t; __real__ __t = __z.real(); __imag__ __t = __z.imag(); _M_value /= __t; return *this; } _GLIBCXX_CONSTEXPR _ComplexT __rep() const { return _M_value; } private: _ComplexT _M_value; }; // These bits have to be at the end of this file, so that the // specializations have all been defined. inline _GLIBCXX_CONSTEXPR complex::complex(const complex& __z) : _M_value(__z.__rep()) { } inline _GLIBCXX_CONSTEXPR complex::complex(const complex& __z) : _M_value(__z.__rep()) { } inline _GLIBCXX_CONSTEXPR complex::complex(const complex& __z) : _M_value(__z.__rep()) { } // Inhibit implicit instantiations for required instantiations, // which are defined via explicit instantiations elsewhere. // NB: This syntax is a GNU extension. #if _GLIBCXX_EXTERN_TEMPLATE extern template istream& operator>>(istream&, complex&); extern template ostream& operator<<(ostream&, const complex&); extern template istream& operator>>(istream&, complex&); extern template ostream& operator<<(ostream&, const complex&); extern template istream& operator>>(istream&, complex&); extern template ostream& operator<<(ostream&, const complex&); #ifdef _GLIBCXX_USE_WCHAR_T extern template wistream& operator>>(wistream&, complex&); extern template wostream& operator<<(wostream&, const complex&); extern template wistream& operator>>(wistream&, complex&); extern template wostream& operator<<(wostream&, const complex&); extern template wistream& operator>>(wistream&, complex&); extern template wostream& operator<<(wostream&, const complex&); #endif #endif // @} group complex_numbers _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // See ext/type_traits.h for the primary template. template struct __promote_2, _Up> { public: typedef std::complex::__type> __type; }; template struct __promote_2<_Tp, std::complex<_Up> > { public: typedef std::complex::__type> __type; }; template struct __promote_2, std::complex<_Up> > { public: typedef std::complex::__type> __type; }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if __cplusplus >= 201103L namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Forward declarations. template std::complex<_Tp> acos(const std::complex<_Tp>&); template std::complex<_Tp> asin(const std::complex<_Tp>&); template std::complex<_Tp> atan(const std::complex<_Tp>&); template std::complex<_Tp> acosh(const std::complex<_Tp>&); template std::complex<_Tp> asinh(const std::complex<_Tp>&); template std::complex<_Tp> atanh(const std::complex<_Tp>&); // DR 595. template _Tp fabs(const std::complex<_Tp>&); template inline std::complex<_Tp> __complex_acos(const std::complex<_Tp>& __z) { const std::complex<_Tp> __t = std::asin(__z); const _Tp __pi_2 = 1.5707963267948966192313216916397514L; return std::complex<_Tp>(__pi_2 - __t.real(), -__t.imag()); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_acos(__complex__ float __z) { return __builtin_cacosf(__z); } inline __complex__ double __complex_acos(__complex__ double __z) { return __builtin_cacos(__z); } inline __complex__ long double __complex_acos(const __complex__ long double& __z) { return __builtin_cacosl(__z); } template inline std::complex<_Tp> acos(const std::complex<_Tp>& __z) { return __complex_acos(__z.__rep()); } #else /// acos(__z) [8.1.2]. // Effects: Behaves the same as C99 function cacos, defined // in subclause 7.3.5.1. template inline std::complex<_Tp> acos(const std::complex<_Tp>& __z) { return __complex_acos(__z); } #endif template inline std::complex<_Tp> __complex_asin(const std::complex<_Tp>& __z) { std::complex<_Tp> __t(-__z.imag(), __z.real()); __t = std::asinh(__t); return std::complex<_Tp>(__t.imag(), -__t.real()); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_asin(__complex__ float __z) { return __builtin_casinf(__z); } inline __complex__ double __complex_asin(__complex__ double __z) { return __builtin_casin(__z); } inline __complex__ long double __complex_asin(const __complex__ long double& __z) { return __builtin_casinl(__z); } template inline std::complex<_Tp> asin(const std::complex<_Tp>& __z) { return __complex_asin(__z.__rep()); } #else /// asin(__z) [8.1.3]. // Effects: Behaves the same as C99 function casin, defined // in subclause 7.3.5.2. template inline std::complex<_Tp> asin(const std::complex<_Tp>& __z) { return __complex_asin(__z); } #endif template std::complex<_Tp> __complex_atan(const std::complex<_Tp>& __z) { const _Tp __r2 = __z.real() * __z.real(); const _Tp __x = _Tp(1.0) - __r2 - __z.imag() * __z.imag(); _Tp __num = __z.imag() + _Tp(1.0); _Tp __den = __z.imag() - _Tp(1.0); __num = __r2 + __num * __num; __den = __r2 + __den * __den; return std::complex<_Tp>(_Tp(0.5) * atan2(_Tp(2.0) * __z.real(), __x), _Tp(0.25) * log(__num / __den)); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_atan(__complex__ float __z) { return __builtin_catanf(__z); } inline __complex__ double __complex_atan(__complex__ double __z) { return __builtin_catan(__z); } inline __complex__ long double __complex_atan(const __complex__ long double& __z) { return __builtin_catanl(__z); } template inline std::complex<_Tp> atan(const std::complex<_Tp>& __z) { return __complex_atan(__z.__rep()); } #else /// atan(__z) [8.1.4]. // Effects: Behaves the same as C99 function catan, defined // in subclause 7.3.5.3. template inline std::complex<_Tp> atan(const std::complex<_Tp>& __z) { return __complex_atan(__z); } #endif template std::complex<_Tp> __complex_acosh(const std::complex<_Tp>& __z) { // Kahan's formula. return _Tp(2.0) * std::log(std::sqrt(_Tp(0.5) * (__z + _Tp(1.0))) + std::sqrt(_Tp(0.5) * (__z - _Tp(1.0)))); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_acosh(__complex__ float __z) { return __builtin_cacoshf(__z); } inline __complex__ double __complex_acosh(__complex__ double __z) { return __builtin_cacosh(__z); } inline __complex__ long double __complex_acosh(const __complex__ long double& __z) { return __builtin_cacoshl(__z); } template inline std::complex<_Tp> acosh(const std::complex<_Tp>& __z) { return __complex_acosh(__z.__rep()); } #else /// acosh(__z) [8.1.5]. // Effects: Behaves the same as C99 function cacosh, defined // in subclause 7.3.6.1. template inline std::complex<_Tp> acosh(const std::complex<_Tp>& __z) { return __complex_acosh(__z); } #endif template std::complex<_Tp> __complex_asinh(const std::complex<_Tp>& __z) { std::complex<_Tp> __t((__z.real() - __z.imag()) * (__z.real() + __z.imag()) + _Tp(1.0), _Tp(2.0) * __z.real() * __z.imag()); __t = std::sqrt(__t); return std::log(__t + __z); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_asinh(__complex__ float __z) { return __builtin_casinhf(__z); } inline __complex__ double __complex_asinh(__complex__ double __z) { return __builtin_casinh(__z); } inline __complex__ long double __complex_asinh(const __complex__ long double& __z) { return __builtin_casinhl(__z); } template inline std::complex<_Tp> asinh(const std::complex<_Tp>& __z) { return __complex_asinh(__z.__rep()); } #else /// asinh(__z) [8.1.6]. // Effects: Behaves the same as C99 function casin, defined // in subclause 7.3.6.2. template inline std::complex<_Tp> asinh(const std::complex<_Tp>& __z) { return __complex_asinh(__z); } #endif template std::complex<_Tp> __complex_atanh(const std::complex<_Tp>& __z) { const _Tp __i2 = __z.imag() * __z.imag(); const _Tp __x = _Tp(1.0) - __i2 - __z.real() * __z.real(); _Tp __num = _Tp(1.0) + __z.real(); _Tp __den = _Tp(1.0) - __z.real(); __num = __i2 + __num * __num; __den = __i2 + __den * __den; return std::complex<_Tp>(_Tp(0.25) * (log(__num) - log(__den)), _Tp(0.5) * atan2(_Tp(2.0) * __z.imag(), __x)); } #if _GLIBCXX_USE_C99_COMPLEX_TR1 inline __complex__ float __complex_atanh(__complex__ float __z) { return __builtin_catanhf(__z); } inline __complex__ double __complex_atanh(__complex__ double __z) { return __builtin_catanh(__z); } inline __complex__ long double __complex_atanh(const __complex__ long double& __z) { return __builtin_catanhl(__z); } template inline std::complex<_Tp> atanh(const std::complex<_Tp>& __z) { return __complex_atanh(__z.__rep()); } #else /// atanh(__z) [8.1.7]. // Effects: Behaves the same as C99 function catanh, defined // in subclause 7.3.6.3. template inline std::complex<_Tp> atanh(const std::complex<_Tp>& __z) { return __complex_atanh(__z); } #endif template inline _Tp /// fabs(__z) [8.1.8]. // Effects: Behaves the same as C99 function cabs, defined // in subclause 7.3.8.1. fabs(const std::complex<_Tp>& __z) { return std::abs(__z); } /// Additional overloads [8.1.9]. template inline typename __gnu_cxx::__promote<_Tp>::__type arg(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; #if (_GLIBCXX11_USE_C99_MATH && !_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC) return std::signbit(__x) ? __type(3.1415926535897932384626433832795029L) : __type(); #else return std::arg(std::complex<__type>(__x)); #endif } template _GLIBCXX_CONSTEXPR inline typename __gnu_cxx::__promote<_Tp>::__type imag(_Tp) { return _Tp(); } template inline typename __gnu_cxx::__promote<_Tp>::__type norm(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __type(__x) * __type(__x); } template _GLIBCXX_CONSTEXPR inline typename __gnu_cxx::__promote<_Tp>::__type real(_Tp __x) { return __x; } template inline std::complex::__type> pow(const std::complex<_Tp>& __x, const _Up& __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return std::pow(std::complex<__type>(__x), __type(__y)); } template inline std::complex::__type> pow(const _Tp& __x, const std::complex<_Up>& __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return std::pow(__type(__x), std::complex<__type>(__y)); } template inline std::complex::__type> pow(const std::complex<_Tp>& __x, const std::complex<_Up>& __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return std::pow(std::complex<__type>(__x), std::complex<__type>(__y)); } // Forward declarations. // DR 781. template std::complex<_Tp> proj(const std::complex<_Tp>&); template std::complex<_Tp> __complex_proj(const std::complex<_Tp>& __z) { const _Tp __den = (__z.real() * __z.real() + __z.imag() * __z.imag() + _Tp(1.0)); return std::complex<_Tp>((_Tp(2.0) * __z.real()) / __den, (_Tp(2.0) * __z.imag()) / __den); } #if _GLIBCXX_USE_C99_COMPLEX inline __complex__ float __complex_proj(__complex__ float __z) { return __builtin_cprojf(__z); } inline __complex__ double __complex_proj(__complex__ double __z) { return __builtin_cproj(__z); } inline __complex__ long double __complex_proj(const __complex__ long double& __z) { return __builtin_cprojl(__z); } template inline std::complex<_Tp> proj(const std::complex<_Tp>& __z) { return __complex_proj(__z.__rep()); } #else template inline std::complex<_Tp> proj(const std::complex<_Tp>& __z) { return __complex_proj(__z); } #endif template inline std::complex::__type> proj(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return std::proj(std::complex<__type>(__x)); } template inline std::complex::__type> conj(_Tp __x) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return std::complex<__type>(__x, -__type()); } #if __cplusplus > 201103L inline namespace literals { inline namespace complex_literals { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wliteral-suffix" #define __cpp_lib_complex_udls 201309 constexpr std::complex operator""if(long double __num) { return std::complex{0.0F, static_cast(__num)}; } constexpr std::complex operator""if(unsigned long long __num) { return std::complex{0.0F, static_cast(__num)}; } constexpr std::complex operator""i(long double __num) { return std::complex{0.0, static_cast(__num)}; } constexpr std::complex operator""i(unsigned long long __num) { return std::complex{0.0, static_cast(__num)}; } constexpr std::complex operator""il(long double __num) { return std::complex{0.0L, __num}; } constexpr std::complex operator""il(unsigned long long __num) { return std::complex{0.0L, static_cast(__num)}; } #pragma GCC diagnostic pop } // inline namespace complex_literals } // inline namespace literals #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif /* _GLIBCXX_COMPLEX */ c++/8/math.h000064400000010417151027430570006374 0ustar00// -*- C++ -*- compatibility header. // Copyright (C) 2002-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file math.h * This is a Standard C++ Library header. */ #if !defined __cplusplus || defined _GLIBCXX_INCLUDE_NEXT_C_HEADERS # include_next #else #ifndef _GLIBCXX_MATH_H #define _GLIBCXX_MATH_H 1 # include using std::abs; using std::acos; using std::asin; using std::atan; using std::atan2; using std::cos; using std::sin; using std::tan; using std::cosh; using std::sinh; using std::tanh; using std::exp; using std::frexp; using std::ldexp; using std::log; using std::log10; using std::modf; using std::pow; using std::sqrt; using std::ceil; using std::fabs; using std::floor; using std::fmod; #if _GLIBCXX_USE_C99_MATH using std::fpclassify; using std::isfinite; using std::isinf; using std::isnan; using std::isnormal; using std::signbit; using std::isgreater; using std::isgreaterequal; using std::isless; using std::islessequal; using std::islessgreater; using std::isunordered; #endif #if __cplusplus >= 201103L && defined(_GLIBCXX_USE_C99_MATH_TR1) using std::acosh; using std::asinh; using std::atanh; using std::cbrt; using std::copysign; using std::erf; using std::erfc; using std::exp2; using std::expm1; using std::fdim; using std::fma; using std::fmax; using std::fmin; using std::hypot; using std::ilogb; using std::lgamma; using std::llrint; using std::llround; using std::log1p; using std::log2; using std::logb; using std::lrint; using std::lround; using std::nearbyint; using std::nextafter; using std::nexttoward; using std::remainder; using std::remquo; using std::rint; using std::round; using std::scalbln; using std::scalbn; using std::tgamma; using std::trunc; #endif // C++11 && _GLIBCXX_USE_C99_MATH_TR1 #if _GLIBCXX_USE_STD_SPEC_FUNCS using std::assoc_laguerref; using std::assoc_laguerrel; using std::assoc_laguerre; using std::assoc_legendref; using std::assoc_legendrel; using std::assoc_legendre; using std::betaf; using std::betal; using std::beta; using std::comp_ellint_1f; using std::comp_ellint_1l; using std::comp_ellint_1; using std::comp_ellint_2f; using std::comp_ellint_2l; using std::comp_ellint_2; using std::comp_ellint_3f; using std::comp_ellint_3l; using std::comp_ellint_3; using std::cyl_bessel_if; using std::cyl_bessel_il; using std::cyl_bessel_i; using std::cyl_bessel_jf; using std::cyl_bessel_jl; using std::cyl_bessel_j; using std::cyl_bessel_kf; using std::cyl_bessel_kl; using std::cyl_bessel_k; using std::cyl_neumannf; using std::cyl_neumannl; using std::cyl_neumann; using std::ellint_1f; using std::ellint_1l; using std::ellint_1; using std::ellint_2f; using std::ellint_2l; using std::ellint_2; using std::ellint_3f; using std::ellint_3l; using std::ellint_3; using std::expintf; using std::expintl; using std::expint; using std::hermitef; using std::hermitel; using std::hermite; using std::laguerref; using std::laguerrel; using std::laguerre; using std::legendref; using std::legendrel; using std::legendre; using std::riemann_zetaf; using std::riemann_zetal; using std::riemann_zeta; using std::sph_besself; using std::sph_bessell; using std::sph_bessel; using std::sph_legendref; using std::sph_legendrel; using std::sph_legendre; using std::sph_neumannf; using std::sph_neumannl; using std::sph_neumann; #endif // _GLIBCXX_USE_STD_SPEC_FUNCS #endif // _GLIBCXX_MATH_H #endif // __cplusplus c++/8/variant000064400000136162151027430570006667 0ustar00// -*- C++ -*- // Copyright (C) 2016-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file variant * This is the C++ Library header. */ #ifndef _GLIBCXX_VARIANT #define _GLIBCXX_VARIANT 1 #pragma GCC system_header #if __cplusplus >= 201703L #include #include #include #include #include #include #include #include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { namespace __variant { template struct _Nth_type; template struct _Nth_type<_Np, _First, _Rest...> : _Nth_type<_Np-1, _Rest...> { }; template struct _Nth_type<0, _First, _Rest...> { using type = _First; }; } // namespace __variant } // namespace __detail #define __cpp_lib_variant 201606L template class tuple; template class variant; template struct hash; template struct variant_size; template struct variant_size : variant_size<_Variant> {}; template struct variant_size : variant_size<_Variant> {}; template struct variant_size : variant_size<_Variant> {}; template struct variant_size> : std::integral_constant {}; template inline constexpr size_t variant_size_v = variant_size<_Variant>::value; template struct variant_alternative; template struct variant_alternative<_Np, variant<_First, _Rest...>> : variant_alternative<_Np-1, variant<_Rest...>> {}; template struct variant_alternative<0, variant<_First, _Rest...>> { using type = _First; }; template using variant_alternative_t = typename variant_alternative<_Np, _Variant>::type; template struct variant_alternative<_Np, const _Variant> { using type = add_const_t>; }; template struct variant_alternative<_Np, volatile _Variant> { using type = add_volatile_t>; }; template struct variant_alternative<_Np, const volatile _Variant> { using type = add_cv_t>; }; inline constexpr size_t variant_npos = -1; template constexpr variant_alternative_t<_Np, variant<_Types...>>& get(variant<_Types...>&); template constexpr variant_alternative_t<_Np, variant<_Types...>>&& get(variant<_Types...>&&); template constexpr variant_alternative_t<_Np, variant<_Types...>> const& get(const variant<_Types...>&); template constexpr variant_alternative_t<_Np, variant<_Types...>> const&& get(const variant<_Types...>&&); namespace __detail { namespace __variant { // Returns the first apparence of _Tp in _Types. // Returns sizeof...(_Types) if _Tp is not in _Types. template struct __index_of : std::integral_constant {}; template inline constexpr size_t __index_of_v = __index_of<_Tp, _Types...>::value; template struct __index_of<_Tp, _First, _Rest...> : std::integral_constant ? 0 : __index_of_v<_Tp, _Rest...> + 1> {}; // _Uninitialized is guaranteed to be a literal type, even if T is not. // We have to do this, because [basic.types]p10.5.3 (n4606) is not implemented // yet. When it's implemented, _Uninitialized can be changed to the alias // to T, therefore equivalent to being removed entirely. // // Another reason we may not want to remove _Uninitialzied may be that, we // want _Uninitialized to be trivially destructible, no matter whether T // is; but we will see. template> struct _Uninitialized; template struct _Uninitialized<_Type, true> { template constexpr _Uninitialized(in_place_index_t<0>, _Args&&... __args) : _M_storage(std::forward<_Args>(__args)...) { } constexpr const _Type& _M_get() const & { return _M_storage; } constexpr _Type& _M_get() & { return _M_storage; } constexpr const _Type&& _M_get() const && { return std::move(_M_storage); } constexpr _Type&& _M_get() && { return std::move(_M_storage); } _Type _M_storage; }; template struct _Uninitialized<_Type, false> { template constexpr _Uninitialized(in_place_index_t<0>, _Args&&... __args) { ::new (&_M_storage) _Type(std::forward<_Args>(__args)...); } const _Type& _M_get() const & { return *_M_storage._M_ptr(); } _Type& _M_get() & { return *_M_storage._M_ptr(); } const _Type&& _M_get() const && { return std::move(*_M_storage._M_ptr()); } _Type&& _M_get() && { return std::move(*_M_storage._M_ptr()); } __gnu_cxx::__aligned_membuf<_Type> _M_storage; }; template _Ref __ref_cast(void* __ptr) { return static_cast<_Ref>(*static_cast*>(__ptr)); } template constexpr decltype(auto) __get(in_place_index_t<0>, _Union&& __u) { return std::forward<_Union>(__u)._M_first._M_get(); } template constexpr decltype(auto) __get(in_place_index_t<_Np>, _Union&& __u) { return __variant::__get(in_place_index<_Np-1>, std::forward<_Union>(__u)._M_rest); } // Returns the typed storage for __v. template constexpr decltype(auto) __get(_Variant&& __v) { return __variant::__get(std::in_place_index<_Np>, std::forward<_Variant>(__v)._M_u); } // Various functions as "vtable" entries, where those vtables are used by // polymorphic operations. template void __erased_ctor(void* __lhs, void* __rhs) { using _Type = remove_reference_t<_Lhs>; ::new (__lhs) _Type(__variant::__ref_cast<_Rhs>(__rhs)); } template void __erased_dtor(_Variant&& __v) { std::_Destroy(std::__addressof(__variant::__get<_Np>(__v))); } template void __erased_assign(void* __lhs, void* __rhs) { __variant::__ref_cast<_Lhs>(__lhs) = __variant::__ref_cast<_Rhs>(__rhs); } template void __erased_swap(void* __lhs, void* __rhs) { using std::swap; swap(__variant::__ref_cast<_Lhs>(__lhs), __variant::__ref_cast<_Rhs>(__rhs)); } #define _VARIANT_RELATION_FUNCTION_TEMPLATE(__OP, __NAME) \ template \ constexpr bool \ __erased_##__NAME(const _Variant& __lhs, const _Variant& __rhs) \ { \ return __variant::__get<_Np>(std::forward<_Variant>(__lhs)) \ __OP __variant::__get<_Np>(std::forward<_Variant>(__rhs)); \ } _VARIANT_RELATION_FUNCTION_TEMPLATE(<, less) _VARIANT_RELATION_FUNCTION_TEMPLATE(<=, less_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(==, equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(!=, not_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(>=, greater_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(>, greater) #undef _VARIANT_RELATION_FUNCTION_TEMPLATE template size_t __erased_hash(void* __t) { return std::hash>>{}( __variant::__ref_cast<_Tp>(__t)); } template struct _Traits { static constexpr bool _S_default_ctor = is_default_constructible_v::type>; static constexpr bool _S_copy_ctor = (is_copy_constructible_v<_Types> && ...); static constexpr bool _S_move_ctor = (is_move_constructible_v<_Types> && ...); static constexpr bool _S_copy_assign = _S_copy_ctor && _S_move_ctor && (is_copy_assignable_v<_Types> && ...); static constexpr bool _S_move_assign = _S_move_ctor && (is_move_assignable_v<_Types> && ...); static constexpr bool _S_trivial_dtor = (is_trivially_destructible_v<_Types> && ...); static constexpr bool _S_trivial_copy_ctor = (is_trivially_copy_constructible_v<_Types> && ...); static constexpr bool _S_trivial_move_ctor = (is_trivially_move_constructible_v<_Types> && ...); static constexpr bool _S_trivial_copy_assign = _S_trivial_dtor && (is_trivially_copy_assignable_v<_Types> && ...); static constexpr bool _S_trivial_move_assign = _S_trivial_dtor && (is_trivially_move_assignable_v<_Types> && ...); // The following nothrow traits are for non-trivial SMFs. Trivial SMFs // are always nothrow. static constexpr bool _S_nothrow_default_ctor = is_nothrow_default_constructible_v< typename _Nth_type<0, _Types...>::type>; static constexpr bool _S_nothrow_copy_ctor = false; static constexpr bool _S_nothrow_move_ctor = (is_nothrow_move_constructible_v<_Types> && ...); static constexpr bool _S_nothrow_copy_assign = false; static constexpr bool _S_nothrow_move_assign = _S_nothrow_move_ctor && (is_nothrow_move_assignable_v<_Types> && ...); }; // Defines members and ctors. template union _Variadic_union { }; template union _Variadic_union<_First, _Rest...> { constexpr _Variadic_union() : _M_rest() { } template constexpr _Variadic_union(in_place_index_t<0>, _Args&&... __args) : _M_first(in_place_index<0>, std::forward<_Args>(__args)...) { } template constexpr _Variadic_union(in_place_index_t<_Np>, _Args&&... __args) : _M_rest(in_place_index<_Np-1>, std::forward<_Args>(__args)...) { } _Uninitialized<_First> _M_first; _Variadic_union<_Rest...> _M_rest; }; // Defines index and the dtor, possibly trivial. template struct _Variant_storage; template using __select_index = typename __select_int::_Select_int_base::type::value_type; template struct _Variant_storage { template static constexpr void (*_S_vtable[])(const _Variant_storage&) = { &__erased_dtor... }; constexpr _Variant_storage() : _M_index(variant_npos) { } template constexpr _Variant_storage(in_place_index_t<_Np>, _Args&&... __args) : _M_u(in_place_index<_Np>, std::forward<_Args>(__args)...), _M_index(_Np) { } template constexpr void _M_reset_impl(std::index_sequence<__indices...>) { if (_M_index != __index_type(variant_npos)) _S_vtable<__indices...>[_M_index](*this); } void _M_reset() { _M_reset_impl(std::index_sequence_for<_Types...>{}); _M_index = variant_npos; } ~_Variant_storage() { _M_reset(); } void* _M_storage() const { return const_cast(static_cast( std::addressof(_M_u))); } constexpr bool _M_valid() const noexcept { return this->_M_index != __index_type(variant_npos); } _Variadic_union<_Types...> _M_u; using __index_type = __select_index<_Types...>; __index_type _M_index; }; template struct _Variant_storage { constexpr _Variant_storage() : _M_index(variant_npos) { } template constexpr _Variant_storage(in_place_index_t<_Np>, _Args&&... __args) : _M_u(in_place_index<_Np>, std::forward<_Args>(__args)...), _M_index(_Np) { } void _M_reset() { _M_index = variant_npos; } void* _M_storage() const { return const_cast(static_cast( std::addressof(_M_u))); } constexpr bool _M_valid() const noexcept { return this->_M_index != __index_type(variant_npos); } _Variadic_union<_Types...> _M_u; using __index_type = __select_index<_Types...>; __index_type _M_index; }; template using _Variant_storage_alias = _Variant_storage<_Traits<_Types...>::_S_trivial_dtor, _Types...>; // The following are (Copy|Move) (ctor|assign) layers for forwarding // triviality and handling non-trivial SMF behaviors. template struct _Copy_ctor_base : _Variant_storage_alias<_Types...> { using _Base = _Variant_storage_alias<_Types...>; using _Base::_Base; _Copy_ctor_base(const _Copy_ctor_base& __rhs) noexcept(_Traits<_Types...>::_S_nothrow_copy_ctor) { if (__rhs._M_valid()) { static constexpr void (*_S_vtable[])(void*, void*) = { &__erased_ctor<_Types&, const _Types&>... }; _S_vtable[__rhs._M_index](this->_M_storage(), __rhs._M_storage()); this->_M_index = __rhs._M_index; } } _Copy_ctor_base(_Copy_ctor_base&&) = default; _Copy_ctor_base& operator=(const _Copy_ctor_base&) = default; _Copy_ctor_base& operator=(_Copy_ctor_base&&) = default; }; template struct _Copy_ctor_base : _Variant_storage_alias<_Types...> { using _Base = _Variant_storage_alias<_Types...>; using _Base::_Base; }; template using _Copy_ctor_alias = _Copy_ctor_base<_Traits<_Types...>::_S_trivial_copy_ctor, _Types...>; template struct _Move_ctor_base : _Copy_ctor_alias<_Types...> { using _Base = _Copy_ctor_alias<_Types...>; using _Base::_Base; _Move_ctor_base(_Move_ctor_base&& __rhs) noexcept(_Traits<_Types...>::_S_nothrow_move_ctor) { if (__rhs._M_valid()) { static constexpr void (*_S_vtable[])(void*, void*) = { &__erased_ctor<_Types&, _Types&&>... }; _S_vtable[__rhs._M_index](this->_M_storage(), __rhs._M_storage()); this->_M_index = __rhs._M_index; } } void _M_destructive_move(_Move_ctor_base&& __rhs) { this->~_Move_ctor_base(); __try { ::new (this) _Move_ctor_base(std::move(__rhs)); } __catch (...) { this->_M_index = variant_npos; __throw_exception_again; } } _Move_ctor_base(const _Move_ctor_base&) = default; _Move_ctor_base& operator=(const _Move_ctor_base&) = default; _Move_ctor_base& operator=(_Move_ctor_base&&) = default; }; template struct _Move_ctor_base : _Copy_ctor_alias<_Types...> { using _Base = _Copy_ctor_alias<_Types...>; using _Base::_Base; void _M_destructive_move(_Move_ctor_base&& __rhs) { this->~_Move_ctor_base(); ::new (this) _Move_ctor_base(std::move(__rhs)); } }; template using _Move_ctor_alias = _Move_ctor_base<_Traits<_Types...>::_S_trivial_move_ctor, _Types...>; template struct _Copy_assign_base : _Move_ctor_alias<_Types...> { using _Base = _Move_ctor_alias<_Types...>; using _Base::_Base; _Copy_assign_base& operator=(const _Copy_assign_base& __rhs) noexcept(_Traits<_Types...>::_S_nothrow_copy_assign) { if (this->_M_index == __rhs._M_index) { if (__rhs._M_valid()) { static constexpr void (*_S_vtable[])(void*, void*) = { &__erased_assign<_Types&, const _Types&>... }; _S_vtable[__rhs._M_index](this->_M_storage(), __rhs._M_storage()); } } else { _Copy_assign_base __tmp(__rhs); this->_M_destructive_move(std::move(__tmp)); } __glibcxx_assert(this->_M_index == __rhs._M_index); return *this; } _Copy_assign_base(const _Copy_assign_base&) = default; _Copy_assign_base(_Copy_assign_base&&) = default; _Copy_assign_base& operator=(_Copy_assign_base&&) = default; }; template struct _Copy_assign_base : _Move_ctor_alias<_Types...> { using _Base = _Move_ctor_alias<_Types...>; using _Base::_Base; }; template using _Copy_assign_alias = _Copy_assign_base<_Traits<_Types...>::_S_trivial_copy_assign, _Types...>; template struct _Move_assign_base : _Copy_assign_alias<_Types...> { using _Base = _Copy_assign_alias<_Types...>; using _Base::_Base; _Move_assign_base& operator=(_Move_assign_base&& __rhs) noexcept(_Traits<_Types...>::_S_nothrow_move_assign) { if (this->_M_index == __rhs._M_index) { if (__rhs._M_valid()) { static constexpr void (*_S_vtable[])(void*, void*) = { &__erased_assign<_Types&, _Types&&>... }; _S_vtable[__rhs._M_index] (this->_M_storage(), __rhs._M_storage()); } } else { _Move_assign_base __tmp(std::move(__rhs)); this->_M_destructive_move(std::move(__tmp)); } __glibcxx_assert(this->_M_index == __rhs._M_index); return *this; } _Move_assign_base(const _Move_assign_base&) = default; _Move_assign_base(_Move_assign_base&&) = default; _Move_assign_base& operator=(const _Move_assign_base&) = default; }; template struct _Move_assign_base : _Copy_assign_alias<_Types...> { using _Base = _Copy_assign_alias<_Types...>; using _Base::_Base; }; template using _Move_assign_alias = _Move_assign_base<_Traits<_Types...>::_S_trivial_move_assign, _Types...>; template struct _Variant_base : _Move_assign_alias<_Types...> { using _Base = _Move_assign_alias<_Types...>; constexpr _Variant_base() noexcept(_Traits<_Types...>::_S_nothrow_default_ctor) : _Variant_base(in_place_index<0>) { } template constexpr explicit _Variant_base(in_place_index_t<_Np> __i, _Args&&... __args) : _Base(__i, std::forward<_Args>(__args)...) { } _Variant_base(const _Variant_base&) = default; _Variant_base(_Variant_base&&) = default; _Variant_base& operator=(const _Variant_base&) = default; _Variant_base& operator=(_Variant_base&&) = default; }; // For how many times does _Tp appear in _Tuple? template struct __tuple_count; template inline constexpr size_t __tuple_count_v = __tuple_count<_Tp, _Tuple>::value; template struct __tuple_count<_Tp, tuple<_Types...>> : integral_constant { }; template struct __tuple_count<_Tp, tuple<_First, _Rest...>> : integral_constant< size_t, __tuple_count_v<_Tp, tuple<_Rest...>> + is_same_v<_Tp, _First>> { }; // TODO: Reuse this in ? template inline constexpr bool __exactly_once = __tuple_count_v<_Tp, tuple<_Types...>> == 1; // Takes _Types and create an overloaded _S_fun for each type. // If a type appears more than once in _Types, create only one overload. template struct __overload_set { static void _S_fun(); }; template struct __overload_set<_First, _Rest...> : __overload_set<_Rest...> { using __overload_set<_Rest...>::_S_fun; static integral_constant _S_fun(_First); }; template struct __overload_set : __overload_set<_Rest...> { using __overload_set<_Rest...>::_S_fun; }; // Helper for variant(_Tp&&) and variant::operator=(_Tp&&). // __accepted_index maps the arbitrary _Tp to an alternative type in _Variant. template struct __accepted_index { static constexpr size_t value = variant_npos; }; template struct __accepted_index< _Tp, variant<_Types...>, decltype(__overload_set<_Types...>::_S_fun(std::declval<_Tp>()), std::declval())> { static constexpr size_t value = sizeof...(_Types) - 1 - decltype(__overload_set<_Types...>:: _S_fun(std::declval<_Tp>()))::value; }; // Returns the raw storage for __v. template void* __get_storage(_Variant&& __v) { return __v._M_storage(); } // Used for storing multi-dimensional vtable. template struct _Multi_array { constexpr const _Tp& _M_access() const { return _M_data; } _Tp _M_data; }; template struct _Multi_array<_Tp, __first, __rest...> { template constexpr const _Tp& _M_access(size_t __first_index, _Args... __rest_indices) const { return _M_arr[__first_index]._M_access(__rest_indices...); } _Multi_array<_Tp, __rest...> _M_arr[__first]; }; // Creates a multi-dimensional vtable recursively. // // For example, // visit([](auto, auto){}, // variant(), // typedef'ed as V1 // variant()) // typedef'ed as V2 // will trigger instantiations of: // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<0>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<0, 0>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<0, 1>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<0, 2>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<1>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<1, 0>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<1, 1>> // __gen_vtable_impl<_Multi_array, // tuple, std::index_sequence<1, 2>> // The returned multi-dimensional vtable can be fast accessed by the visitor // using index calculation. template struct __gen_vtable_impl; template struct __gen_vtable_impl< _Multi_array<_Result_type (*)(_Visitor, _Variants...), __dimensions...>, tuple<_Variants...>, std::index_sequence<__indices...>> { using _Next = remove_reference_t::type>; using _Array_type = _Multi_array<_Result_type (*)(_Visitor, _Variants...), __dimensions...>; static constexpr _Array_type _S_apply() { _Array_type __vtable{}; _S_apply_all_alts( __vtable, make_index_sequence>()); return __vtable; } template static constexpr void _S_apply_all_alts(_Array_type& __vtable, std::index_sequence<__var_indices...>) { (_S_apply_single_alt<__var_indices>( __vtable._M_arr[__var_indices]), ...); } template static constexpr void _S_apply_single_alt(_Tp& __element) { using _Alternative = variant_alternative_t<__index, _Next>; __element = __gen_vtable_impl< remove_reference_t, tuple<_Variants...>, std::index_sequence<__indices..., __index>>::_S_apply(); } }; template struct __gen_vtable_impl< _Multi_array<_Result_type (*)(_Visitor, _Variants...)>, tuple<_Variants...>, std::index_sequence<__indices...>> { using _Array_type = _Multi_array<_Result_type (*)(_Visitor&&, _Variants...)>; static constexpr decltype(auto) __visit_invoke(_Visitor&& __visitor, _Variants... __vars) { return std::__invoke(std::forward<_Visitor>(__visitor), __variant::__get<__indices>(std::forward<_Variants>(__vars))...); } static constexpr auto _S_apply() { return _Array_type{&__visit_invoke}; } }; template struct __gen_vtable { using _Func_ptr = _Result_type (*)(_Visitor&&, _Variants...); using _Array_type = _Multi_array<_Func_ptr, variant_size_v>...>; static constexpr _Array_type _S_apply() { return __gen_vtable_impl<_Array_type, tuple<_Variants...>, std::index_sequence<>>::_S_apply(); } static constexpr auto _S_vtable = _S_apply(); }; template struct _Base_dedup : public _Tp { }; template struct _Variant_hash_base; template struct _Variant_hash_base, std::index_sequence<__indices...>> : _Base_dedup<__indices, __poison_hash>>... { }; } // namespace __variant } // namespace __detail template constexpr bool holds_alternative(const variant<_Types...>& __v) noexcept { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); return __v.index() == __detail::__variant::__index_of_v<_Tp, _Types...>; } template constexpr _Tp& get(variant<_Types...>& __v) { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); static_assert(!is_void_v<_Tp>, "_Tp should not be void"); return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>(__v); } template constexpr _Tp&& get(variant<_Types...>&& __v) { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); static_assert(!is_void_v<_Tp>, "_Tp should not be void"); return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>( std::move(__v)); } template constexpr const _Tp& get(const variant<_Types...>& __v) { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); static_assert(!is_void_v<_Tp>, "_Tp should not be void"); return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>(__v); } template constexpr const _Tp&& get(const variant<_Types...>&& __v) { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); static_assert(!is_void_v<_Tp>, "_Tp should not be void"); return std::get<__detail::__variant::__index_of_v<_Tp, _Types...>>( std::move(__v)); } template constexpr add_pointer_t>> get_if(variant<_Types...>* __ptr) noexcept { using _Alternative_type = variant_alternative_t<_Np, variant<_Types...>>; static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); static_assert(!is_void_v<_Alternative_type>, "_Tp should not be void"); if (__ptr && __ptr->index() == _Np) return &__detail::__variant::__get<_Np>(*__ptr); return nullptr; } template constexpr add_pointer_t>> get_if(const variant<_Types...>* __ptr) noexcept { using _Alternative_type = variant_alternative_t<_Np, variant<_Types...>>; static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); static_assert(!is_void_v<_Alternative_type>, "_Tp should not be void"); if (__ptr && __ptr->index() == _Np) return &__detail::__variant::__get<_Np>(*__ptr); return nullptr; } template constexpr add_pointer_t<_Tp> get_if(variant<_Types...>* __ptr) noexcept { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); static_assert(!is_void_v<_Tp>, "_Tp should not be void"); return std::get_if<__detail::__variant::__index_of_v<_Tp, _Types...>>( __ptr); } template constexpr add_pointer_t get_if(const variant<_Types...>* __ptr) noexcept { static_assert(__detail::__variant::__exactly_once<_Tp, _Types...>, "T should occur for exactly once in alternatives"); static_assert(!is_void_v<_Tp>, "_Tp should not be void"); return std::get_if<__detail::__variant::__index_of_v<_Tp, _Types...>>( __ptr); } struct monostate { }; #define _VARIANT_RELATION_FUNCTION_TEMPLATE(__OP, __NAME) \ template \ constexpr bool operator __OP(const variant<_Types...>& __lhs, \ const variant<_Types...>& __rhs) \ { \ return __lhs._M_##__NAME(__rhs, std::index_sequence_for<_Types...>{}); \ } \ \ constexpr bool operator __OP(monostate, monostate) noexcept \ { return 0 __OP 0; } _VARIANT_RELATION_FUNCTION_TEMPLATE(<, less) _VARIANT_RELATION_FUNCTION_TEMPLATE(<=, less_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(==, equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(!=, not_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(>=, greater_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(>, greater) #undef _VARIANT_RELATION_FUNCTION_TEMPLATE template constexpr decltype(auto) visit(_Visitor&&, _Variants&&...); template inline enable_if_t<(is_move_constructible_v<_Types> && ...) && (is_swappable_v<_Types> && ...)> swap(variant<_Types...>& __lhs, variant<_Types...>& __rhs) noexcept(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } template enable_if_t && ...) && (is_swappable_v<_Types> && ...))> swap(variant<_Types...>&, variant<_Types...>&) = delete; class bad_variant_access : public exception { public: bad_variant_access() noexcept : _M_reason("Unknown reason") { } const char* what() const noexcept override { return _M_reason; } private: bad_variant_access(const char* __reason) : _M_reason(__reason) { } const char* _M_reason; friend void __throw_bad_variant_access(const char* __what); }; inline void __throw_bad_variant_access(const char* __what) { _GLIBCXX_THROW_OR_ABORT(bad_variant_access(__what)); } template class variant : private __detail::__variant::_Variant_base<_Types...>, private _Enable_default_constructor< __detail::__variant::_Traits<_Types...>::_S_default_ctor, variant<_Types...>>, private _Enable_copy_move< __detail::__variant::_Traits<_Types...>::_S_copy_ctor, __detail::__variant::_Traits<_Types...>::_S_copy_assign, __detail::__variant::_Traits<_Types...>::_S_move_ctor, __detail::__variant::_Traits<_Types...>::_S_move_assign, variant<_Types...>> { private: static_assert(sizeof...(_Types) > 0, "variant must have at least one alternative"); static_assert(!(std::is_reference_v<_Types> || ...), "variant must have no reference alternative"); static_assert(!(std::is_void_v<_Types> || ...), "variant must have no void alternative"); using _Base = __detail::__variant::_Variant_base<_Types...>; using _Default_ctor_enabler = _Enable_default_constructor< __detail::__variant::_Traits<_Types...>::_S_default_ctor, variant<_Types...>>; template static constexpr bool __exactly_once = __detail::__variant::__exactly_once<_Tp, _Types...>; template static constexpr size_t __accepted_index = __detail::__variant::__accepted_index<_Tp&&, variant>::value; template struct __to_type_impl; template struct __to_type_impl<_Np, true> { using type = variant_alternative_t<_Np, variant>; }; template using __to_type = typename __to_type_impl<_Np>::type; template using __accepted_type = __to_type<__accepted_index<_Tp>>; template static constexpr size_t __index_of = __detail::__variant::__index_of_v<_Tp, _Types...>; using _Traits = __detail::__variant::_Traits<_Types...>; template struct __is_in_place_tag : false_type { }; template struct __is_in_place_tag> : true_type { }; template struct __is_in_place_tag> : true_type { }; template static constexpr bool __not_in_place_tag = !__is_in_place_tag>::value; public: variant() = default; variant(const variant& __rhs) = default; variant(variant&&) = default; variant& operator=(const variant&) = default; variant& operator=(variant&&) = default; ~variant() = default; template, variant>>, typename = enable_if_t<(sizeof...(_Types)>0)>, typename = enable_if_t<__not_in_place_tag<_Tp>>, typename = enable_if_t<__exactly_once<__accepted_type<_Tp&&>> && is_constructible_v<__accepted_type<_Tp&&>, _Tp&&>>> constexpr variant(_Tp&& __t) noexcept(is_nothrow_constructible_v<__accepted_type<_Tp&&>, _Tp&&>) : variant(in_place_index<__accepted_index<_Tp&&>>, std::forward<_Tp>(__t)) { __glibcxx_assert(holds_alternative<__accepted_type<_Tp&&>>(*this)); } template && is_constructible_v<_Tp, _Args&&...>>> constexpr explicit variant(in_place_type_t<_Tp>, _Args&&... __args) : variant(in_place_index<__index_of<_Tp>>, std::forward<_Args>(__args)...) { __glibcxx_assert(holds_alternative<_Tp>(*this)); } template && is_constructible_v< _Tp, initializer_list<_Up>&, _Args&&...>>> constexpr explicit variant(in_place_type_t<_Tp>, initializer_list<_Up> __il, _Args&&... __args) : variant(in_place_index<__index_of<_Tp>>, __il, std::forward<_Args>(__args)...) { __glibcxx_assert(holds_alternative<_Tp>(*this)); } template, _Args&&...>>> constexpr explicit variant(in_place_index_t<_Np>, _Args&&... __args) : _Base(in_place_index<_Np>, std::forward<_Args>(__args)...), _Default_ctor_enabler(_Enable_default_constructor_tag{}) { __glibcxx_assert(index() == _Np); } template, initializer_list<_Up>&, _Args&&...>>> constexpr explicit variant(in_place_index_t<_Np>, initializer_list<_Up> __il, _Args&&... __args) : _Base(in_place_index<_Np>, __il, std::forward<_Args>(__args)...), _Default_ctor_enabler(_Enable_default_constructor_tag{}) { __glibcxx_assert(index() == _Np); } template enable_if_t<__exactly_once<__accepted_type<_Tp&&>> && is_constructible_v<__accepted_type<_Tp&&>, _Tp&&> && is_assignable_v<__accepted_type<_Tp&&>&, _Tp&&> && !is_same_v, variant>, variant&> operator=(_Tp&& __rhs) noexcept(is_nothrow_assignable_v<__accepted_type<_Tp&&>&, _Tp&&> && is_nothrow_constructible_v<__accepted_type<_Tp&&>, _Tp&&>) { constexpr auto __index = __accepted_index<_Tp&&>; if (index() == __index) std::get<__index>(*this) = std::forward<_Tp>(__rhs); else this->emplace<__index>(std::forward<_Tp>(__rhs)); __glibcxx_assert(holds_alternative<__accepted_type<_Tp&&>>(*this)); return *this; } template enable_if_t && __exactly_once<_Tp>, _Tp&> emplace(_Args&&... __args) { auto& ret = this->emplace<__index_of<_Tp>>(std::forward<_Args>(__args)...); __glibcxx_assert(holds_alternative<_Tp>(*this)); return ret; } template enable_if_t&, _Args...> && __exactly_once<_Tp>, _Tp&> emplace(initializer_list<_Up> __il, _Args&&... __args) { auto& ret = this->emplace<__index_of<_Tp>>(__il, std::forward<_Args>(__args)...); __glibcxx_assert(holds_alternative<_Tp>(*this)); return ret; } template enable_if_t, _Args...>, variant_alternative_t<_Np, variant>&> emplace(_Args&&... __args) { static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); this->~variant(); __try { ::new (this) variant(in_place_index<_Np>, std::forward<_Args>(__args)...); } __catch (...) { this->_M_index = variant_npos; __throw_exception_again; } __glibcxx_assert(index() == _Np); return std::get<_Np>(*this); } template enable_if_t, initializer_list<_Up>&, _Args...>, variant_alternative_t<_Np, variant>&> emplace(initializer_list<_Up> __il, _Args&&... __args) { static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); this->~variant(); __try { ::new (this) variant(in_place_index<_Np>, __il, std::forward<_Args>(__args)...); } __catch (...) { this->_M_index = variant_npos; __throw_exception_again; } __glibcxx_assert(index() == _Np); return std::get<_Np>(*this); } constexpr bool valueless_by_exception() const noexcept { return !this->_M_valid(); } constexpr size_t index() const noexcept { if (this->_M_index == typename _Base::__index_type(variant_npos)) return variant_npos; return this->_M_index; } void swap(variant& __rhs) noexcept((__is_nothrow_swappable<_Types>::value && ...) && is_nothrow_move_constructible_v) { if (this->index() == __rhs.index()) { if (this->_M_valid()) { static constexpr void (*_S_vtable[])(void*, void*) = { &__detail::__variant::__erased_swap<_Types&, _Types&>... }; _S_vtable[__rhs._M_index](this->_M_storage(), __rhs._M_storage()); } } else if (!this->_M_valid()) { this->_M_destructive_move(std::move(__rhs)); __rhs._M_reset(); } else if (!__rhs._M_valid()) { __rhs._M_destructive_move(std::move(*this)); this->_M_reset(); } else { auto __tmp = std::move(__rhs); __rhs._M_destructive_move(std::move(*this)); this->_M_destructive_move(std::move(__tmp)); } } private: #define _VARIANT_RELATION_FUNCTION_TEMPLATE(__OP, __NAME) \ template \ static constexpr bool \ (*_S_erased_##__NAME[])(const variant&, const variant&) = \ { &__detail::__variant::__erased_##__NAME< \ const variant&, __indices>... }; \ template \ constexpr bool \ _M_##__NAME(const variant& __rhs, \ std::index_sequence<__indices...>) const \ { \ auto __lhs_index = this->index(); \ auto __rhs_index = __rhs.index(); \ if (__lhs_index != __rhs_index || valueless_by_exception()) \ /* Modulo addition. */ \ return __lhs_index + 1 __OP __rhs_index + 1; \ return _S_erased_##__NAME<__indices...>[__lhs_index](*this, __rhs); \ } _VARIANT_RELATION_FUNCTION_TEMPLATE(<, less) _VARIANT_RELATION_FUNCTION_TEMPLATE(<=, less_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(==, equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(!=, not_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(>=, greater_equal) _VARIANT_RELATION_FUNCTION_TEMPLATE(>, greater) #undef _VARIANT_RELATION_FUNCTION_TEMPLATE #ifdef __clang__ public: using _Base::_M_u; // See https://bugs.llvm.org/show_bug.cgi?id=31852 private: #endif template friend constexpr decltype(auto) __detail::__variant::__get(_Vp&& __v); template friend void* __detail::__variant::__get_storage(_Vp&& __v); #define _VARIANT_RELATION_FUNCTION_TEMPLATE(__OP) \ template \ friend constexpr bool \ operator __OP(const variant<_Tp...>& __lhs, \ const variant<_Tp...>& __rhs); _VARIANT_RELATION_FUNCTION_TEMPLATE(<) _VARIANT_RELATION_FUNCTION_TEMPLATE(<=) _VARIANT_RELATION_FUNCTION_TEMPLATE(==) _VARIANT_RELATION_FUNCTION_TEMPLATE(!=) _VARIANT_RELATION_FUNCTION_TEMPLATE(>=) _VARIANT_RELATION_FUNCTION_TEMPLATE(>) #undef _VARIANT_RELATION_FUNCTION_TEMPLATE }; template constexpr variant_alternative_t<_Np, variant<_Types...>>& get(variant<_Types...>& __v) { static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); if (__v.index() != _Np) __throw_bad_variant_access("Unexpected index"); return __detail::__variant::__get<_Np>(__v); } template constexpr variant_alternative_t<_Np, variant<_Types...>>&& get(variant<_Types...>&& __v) { static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); if (__v.index() != _Np) __throw_bad_variant_access("Unexpected index"); return __detail::__variant::__get<_Np>(std::move(__v)); } template constexpr const variant_alternative_t<_Np, variant<_Types...>>& get(const variant<_Types...>& __v) { static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); if (__v.index() != _Np) __throw_bad_variant_access("Unexpected index"); return __detail::__variant::__get<_Np>(__v); } template constexpr const variant_alternative_t<_Np, variant<_Types...>>&& get(const variant<_Types...>&& __v) { static_assert(_Np < sizeof...(_Types), "The index should be in [0, number of alternatives)"); if (__v.index() != _Np) __throw_bad_variant_access("Unexpected index"); return __detail::__variant::__get<_Np>(std::move(__v)); } template constexpr decltype(auto) visit(_Visitor&& __visitor, _Variants&&... __variants) { if ((__variants.valueless_by_exception() || ...)) __throw_bad_variant_access("Unexpected index"); using _Result_type = decltype(std::forward<_Visitor>(__visitor)( std::get<0>(std::forward<_Variants>(__variants))...)); constexpr auto& __vtable = __detail::__variant::__gen_vtable< _Result_type, _Visitor&&, _Variants&&...>::_S_vtable; auto __func_ptr = __vtable._M_access(__variants.index()...); return (*__func_ptr)(std::forward<_Visitor>(__visitor), std::forward<_Variants>(__variants)...); } template struct __variant_hash_call_base_impl { size_t operator()(const variant<_Types...>& __t) const noexcept((is_nothrow_invocable_v>, _Types> && ...)) { if (!__t.valueless_by_exception()) { namespace __edv = __detail::__variant; static constexpr size_t (*_S_vtable[])(void*) = { &__edv::__erased_hash... }; return hash{}(__t.index()) + _S_vtable[__t.index()](__edv::__get_storage(__t)); } return hash{}(__t.index()); } }; template struct __variant_hash_call_base_impl {}; template using __variant_hash_call_base = __variant_hash_call_base_impl<(__poison_hash>:: __enable_hash_call &&...), _Types...>; template struct hash> : private __detail::__variant::_Variant_hash_base< variant<_Types...>, std::index_sequence_for<_Types...>>, public __variant_hash_call_base<_Types...> { using result_type [[__deprecated__]] = size_t; using argument_type [[__deprecated__]] = variant<_Types...>; }; template<> struct hash { using result_type [[__deprecated__]] = size_t; using argument_type [[__deprecated__]] = monostate; size_t operator()(const monostate& __t) const noexcept { constexpr size_t __magic_monostate_hash = -7777; return __magic_monostate_hash; } }; template struct __is_fast_hash>> : bool_constant<(__is_fast_hash<_Types>::value && ...)> { }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // C++17 #endif // _GLIBCXX_VARIANT c++/8/list000064400000005042151027430570006166 0ustar00// -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file include/list * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_LIST #define _GLIBCXX_LIST 1 #pragma GCC system_header #include #include #include #include #include #ifdef _GLIBCXX_DEBUG # include #endif #ifdef _GLIBCXX_PROFILE # include #endif #endif /* _GLIBCXX_LIST */ c++/8/csetjmp000064400000003635151027430570006666 0ustar00// -*- C++ -*- forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file csetjmp * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c setjmp.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 20.4.6 C library // #pragma GCC system_header #include #include #ifndef _GLIBCXX_CSETJMP #define _GLIBCXX_CSETJMP 1 // Get rid of those macros defined in in lieu of real functions. #undef longjmp // Adhere to section 17.4.1.2 clause 5 of ISO 14882:1998 #ifndef setjmp #define setjmp(env) setjmp (env) #endif namespace std { using ::jmp_buf; using ::longjmp; } // namespace std #endif c++/8/istream000064400000100113151027430570006652 0ustar00// Input streams -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // // ISO C++ 14882: 27.6.1 Input streams // /** @file include/istream * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_ISTREAM #define _GLIBCXX_ISTREAM 1 #pragma GCC system_header #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Template class basic_istream. * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * This is the base class for all input streams. It provides text * formatting of all builtin types, and communicates with any class * derived from basic_streambuf to do the actual input. */ template class basic_istream : virtual public basic_ios<_CharT, _Traits> { public: // Types (inherited from basic_ios (27.4.4)): typedef _CharT char_type; typedef typename _Traits::int_type int_type; typedef typename _Traits::pos_type pos_type; typedef typename _Traits::off_type off_type; typedef _Traits traits_type; // Non-standard Types: typedef basic_streambuf<_CharT, _Traits> __streambuf_type; typedef basic_ios<_CharT, _Traits> __ios_type; typedef basic_istream<_CharT, _Traits> __istream_type; typedef num_get<_CharT, istreambuf_iterator<_CharT, _Traits> > __num_get_type; typedef ctype<_CharT> __ctype_type; protected: // Data Members: /** * The number of characters extracted in the previous unformatted * function; see gcount(). */ streamsize _M_gcount; public: /** * @brief Base constructor. * * This ctor is almost never called by the user directly, rather from * derived classes' initialization lists, which pass a pointer to * their own stream buffer. */ explicit basic_istream(__streambuf_type* __sb) : _M_gcount(streamsize(0)) { this->init(__sb); } /** * @brief Base destructor. * * This does very little apart from providing a virtual base dtor. */ virtual ~basic_istream() { _M_gcount = streamsize(0); } /// Safe prefix/suffix operations. class sentry; friend class sentry; //@{ /** * @brief Interface for manipulators. * * Manipulators such as @c std::ws and @c std::dec use these * functions in constructs like * std::cin >> std::ws. * For more information, see the iomanip header. */ __istream_type& operator>>(__istream_type& (*__pf)(__istream_type&)) { return __pf(*this); } __istream_type& operator>>(__ios_type& (*__pf)(__ios_type&)) { __pf(*this); return *this; } __istream_type& operator>>(ios_base& (*__pf)(ios_base&)) { __pf(*this); return *this; } //@} //@{ /** * @name Extractors * * All the @c operator>> functions (aka formatted input * functions) have some common behavior. Each starts by * constructing a temporary object of type std::basic_istream::sentry * with the second argument (noskipws) set to false. This has several * effects, concluding with the setting of a status flag; see the * sentry documentation for more. * * If the sentry status is good, the function tries to extract * whatever data is appropriate for the type of the argument. * * If an exception is thrown during extraction, ios_base::badbit * will be turned on in the stream's error state (without causing an * ios_base::failure to be thrown) and the original exception will * be rethrown if badbit is set in the exceptions mask. */ //@{ /** * @brief Integer arithmetic extractors * @param __n A variable of builtin integral type. * @return @c *this if successful * * These functions use the stream's current locale (specifically, the * @c num_get facet) to parse the input data. */ __istream_type& operator>>(bool& __n) { return _M_extract(__n); } __istream_type& operator>>(short& __n); __istream_type& operator>>(unsigned short& __n) { return _M_extract(__n); } __istream_type& operator>>(int& __n); __istream_type& operator>>(unsigned int& __n) { return _M_extract(__n); } __istream_type& operator>>(long& __n) { return _M_extract(__n); } __istream_type& operator>>(unsigned long& __n) { return _M_extract(__n); } #ifdef _GLIBCXX_USE_LONG_LONG __istream_type& operator>>(long long& __n) { return _M_extract(__n); } __istream_type& operator>>(unsigned long long& __n) { return _M_extract(__n); } #endif //@} //@{ /** * @brief Floating point arithmetic extractors * @param __f A variable of builtin floating point type. * @return @c *this if successful * * These functions use the stream's current locale (specifically, the * @c num_get facet) to parse the input data. */ __istream_type& operator>>(float& __f) { return _M_extract(__f); } __istream_type& operator>>(double& __f) { return _M_extract(__f); } __istream_type& operator>>(long double& __f) { return _M_extract(__f); } //@} /** * @brief Basic arithmetic extractors * @param __p A variable of pointer type. * @return @c *this if successful * * These functions use the stream's current locale (specifically, the * @c num_get facet) to parse the input data. */ __istream_type& operator>>(void*& __p) { return _M_extract(__p); } /** * @brief Extracting into another streambuf. * @param __sb A pointer to a streambuf * * This function behaves like one of the basic arithmetic extractors, * in that it also constructs a sentry object and has the same error * handling behavior. * * If @p __sb is NULL, the stream will set failbit in its error state. * * Characters are extracted from this stream and inserted into the * @p __sb streambuf until one of the following occurs: * * - the input stream reaches end-of-file, * - insertion into the output buffer fails (in this case, the * character that would have been inserted is not extracted), or * - an exception occurs (and in this case is caught) * * If the function inserts no characters, failbit is set. */ __istream_type& operator>>(__streambuf_type* __sb); //@} // [27.6.1.3] unformatted input /** * @brief Character counting * @return The number of characters extracted by the previous * unformatted input function dispatched for this stream. */ streamsize gcount() const { return _M_gcount; } //@{ /** * @name Unformatted Input Functions * * All the unformatted input functions have some common behavior. * Each starts by constructing a temporary object of type * std::basic_istream::sentry with the second argument (noskipws) * set to true. This has several effects, concluding with the * setting of a status flag; see the sentry documentation for more. * * If the sentry status is good, the function tries to extract * whatever data is appropriate for the type of the argument. * * The number of characters extracted is stored for later retrieval * by gcount(). * * If an exception is thrown during extraction, ios_base::badbit * will be turned on in the stream's error state (without causing an * ios_base::failure to be thrown) and the original exception will * be rethrown if badbit is set in the exceptions mask. */ /** * @brief Simple extraction. * @return A character, or eof(). * * Tries to extract a character. If none are available, sets failbit * and returns traits::eof(). */ int_type get(); /** * @brief Simple extraction. * @param __c The character in which to store data. * @return *this * * Tries to extract a character and store it in @a __c. If none are * available, sets failbit and returns traits::eof(). * * @note This function is not overloaded on signed char and * unsigned char. */ __istream_type& get(char_type& __c); /** * @brief Simple multiple-character extraction. * @param __s Pointer to an array. * @param __n Maximum number of characters to store in @a __s. * @param __delim A "stop" character. * @return *this * * Characters are extracted and stored into @a __s until one of the * following happens: * * - @c __n-1 characters are stored * - the input sequence reaches EOF * - the next character equals @a __delim, in which case the character * is not extracted * * If no characters are stored, failbit is set in the stream's error * state. * * In any case, a null character is stored into the next location in * the array. * * @note This function is not overloaded on signed char and * unsigned char. */ __istream_type& get(char_type* __s, streamsize __n, char_type __delim); /** * @brief Simple multiple-character extraction. * @param __s Pointer to an array. * @param __n Maximum number of characters to store in @a s. * @return *this * * Returns @c get(__s,__n,widen('\\n')). */ __istream_type& get(char_type* __s, streamsize __n) { return this->get(__s, __n, this->widen('\n')); } /** * @brief Extraction into another streambuf. * @param __sb A streambuf in which to store data. * @param __delim A "stop" character. * @return *this * * Characters are extracted and inserted into @a __sb until one of the * following happens: * * - the input sequence reaches EOF * - insertion into the output buffer fails (in this case, the * character that would have been inserted is not extracted) * - the next character equals @a __delim (in this case, the character * is not extracted) * - an exception occurs (and in this case is caught) * * If no characters are stored, failbit is set in the stream's error * state. */ __istream_type& get(__streambuf_type& __sb, char_type __delim); /** * @brief Extraction into another streambuf. * @param __sb A streambuf in which to store data. * @return *this * * Returns @c get(__sb,widen('\\n')). */ __istream_type& get(__streambuf_type& __sb) { return this->get(__sb, this->widen('\n')); } /** * @brief String extraction. * @param __s A character array in which to store the data. * @param __n Maximum number of characters to extract. * @param __delim A "stop" character. * @return *this * * Extracts and stores characters into @a __s until one of the * following happens. Note that these criteria are required to be * tested in the order listed here, to allow an input line to exactly * fill the @a __s array without setting failbit. * * -# the input sequence reaches end-of-file, in which case eofbit * is set in the stream error state * -# the next character equals @c __delim, in which case the character * is extracted (and therefore counted in @c gcount()) but not stored * -# @c __n-1 characters are stored, in which case failbit is set * in the stream error state * * If no characters are extracted, failbit is set. (An empty line of * input should therefore not cause failbit to be set.) * * In any case, a null character is stored in the next location in * the array. */ __istream_type& getline(char_type* __s, streamsize __n, char_type __delim); /** * @brief String extraction. * @param __s A character array in which to store the data. * @param __n Maximum number of characters to extract. * @return *this * * Returns @c getline(__s,__n,widen('\\n')). */ __istream_type& getline(char_type* __s, streamsize __n) { return this->getline(__s, __n, this->widen('\n')); } /** * @brief Discarding characters * @param __n Number of characters to discard. * @param __delim A "stop" character. * @return *this * * Extracts characters and throws them away until one of the * following happens: * - if @a __n @c != @c std::numeric_limits::max(), @a __n * characters are extracted * - the input sequence reaches end-of-file * - the next character equals @a __delim (in this case, the character * is extracted); note that this condition will never occur if * @a __delim equals @c traits::eof(). * * NB: Provide three overloads, instead of the single function * (with defaults) mandated by the Standard: this leads to a * better performing implementation, while still conforming to * the Standard. */ __istream_type& ignore(streamsize __n, int_type __delim); __istream_type& ignore(streamsize __n); __istream_type& ignore(); /** * @brief Looking ahead in the stream * @return The next character, or eof(). * * If, after constructing the sentry object, @c good() is false, * returns @c traits::eof(). Otherwise reads but does not extract * the next input character. */ int_type peek(); /** * @brief Extraction without delimiters. * @param __s A character array. * @param __n Maximum number of characters to store. * @return *this * * If the stream state is @c good(), extracts characters and stores * them into @a __s until one of the following happens: * - @a __n characters are stored * - the input sequence reaches end-of-file, in which case the error * state is set to @c failbit|eofbit. * * @note This function is not overloaded on signed char and * unsigned char. */ __istream_type& read(char_type* __s, streamsize __n); /** * @brief Extraction until the buffer is exhausted, but no more. * @param __s A character array. * @param __n Maximum number of characters to store. * @return The number of characters extracted. * * Extracts characters and stores them into @a __s depending on the * number of characters remaining in the streambuf's buffer, * @c rdbuf()->in_avail(), called @c A here: * - if @c A @c == @c -1, sets eofbit and extracts no characters * - if @c A @c == @c 0, extracts no characters * - if @c A @c > @c 0, extracts @c min(A,n) * * The goal is to empty the current buffer, and to not request any * more from the external input sequence controlled by the streambuf. */ streamsize readsome(char_type* __s, streamsize __n); /** * @brief Unextracting a single character. * @param __c The character to push back into the input stream. * @return *this * * If @c rdbuf() is not null, calls @c rdbuf()->sputbackc(c). * * If @c rdbuf() is null or if @c sputbackc() fails, sets badbit in * the error state. * * @note This function first clears eofbit. Since no characters * are extracted, the next call to @c gcount() will return 0, * as required by DR 60. */ __istream_type& putback(char_type __c); /** * @brief Unextracting the previous character. * @return *this * * If @c rdbuf() is not null, calls @c rdbuf()->sungetc(c). * * If @c rdbuf() is null or if @c sungetc() fails, sets badbit in * the error state. * * @note This function first clears eofbit. Since no characters * are extracted, the next call to @c gcount() will return 0, * as required by DR 60. */ __istream_type& unget(); /** * @brief Synchronizing the stream buffer. * @return 0 on success, -1 on failure * * If @c rdbuf() is a null pointer, returns -1. * * Otherwise, calls @c rdbuf()->pubsync(), and if that returns -1, * sets badbit and returns -1. * * Otherwise, returns 0. * * @note This function does not count the number of characters * extracted, if any, and therefore does not affect the next * call to @c gcount(). */ int sync(); /** * @brief Getting the current read position. * @return A file position object. * * If @c fail() is not false, returns @c pos_type(-1) to indicate * failure. Otherwise returns @c rdbuf()->pubseekoff(0,cur,in). * * @note This function does not count the number of characters * extracted, if any, and therefore does not affect the next * call to @c gcount(). At variance with putback, unget and * seekg, eofbit is not cleared first. */ pos_type tellg(); /** * @brief Changing the current read position. * @param __pos A file position object. * @return *this * * If @c fail() is not true, calls @c rdbuf()->pubseekpos(__pos). If * that function fails, sets failbit. * * @note This function first clears eofbit. It does not count the * number of characters extracted, if any, and therefore does * not affect the next call to @c gcount(). */ __istream_type& seekg(pos_type); /** * @brief Changing the current read position. * @param __off A file offset object. * @param __dir The direction in which to seek. * @return *this * * If @c fail() is not true, calls @c rdbuf()->pubseekoff(__off,__dir). * If that function fails, sets failbit. * * @note This function first clears eofbit. It does not count the * number of characters extracted, if any, and therefore does * not affect the next call to @c gcount(). */ __istream_type& seekg(off_type, ios_base::seekdir); //@} protected: basic_istream() : _M_gcount(streamsize(0)) { this->init(0); } #if __cplusplus >= 201103L basic_istream(const basic_istream&) = delete; basic_istream(basic_istream&& __rhs) : __ios_type(), _M_gcount(__rhs._M_gcount) { __ios_type::move(__rhs); __rhs._M_gcount = 0; } // 27.7.3.3 Assign/swap basic_istream& operator=(const basic_istream&) = delete; basic_istream& operator=(basic_istream&& __rhs) { swap(__rhs); return *this; } void swap(basic_istream& __rhs) { __ios_type::swap(__rhs); std::swap(_M_gcount, __rhs._M_gcount); } #endif template __istream_type& _M_extract(_ValueT& __v); }; /// Explicit specialization declarations, defined in src/istream.cc. template<> basic_istream& basic_istream:: getline(char_type* __s, streamsize __n, char_type __delim); template<> basic_istream& basic_istream:: ignore(streamsize __n); template<> basic_istream& basic_istream:: ignore(streamsize __n, int_type __delim); #ifdef _GLIBCXX_USE_WCHAR_T template<> basic_istream& basic_istream:: getline(char_type* __s, streamsize __n, char_type __delim); template<> basic_istream& basic_istream:: ignore(streamsize __n); template<> basic_istream& basic_istream:: ignore(streamsize __n, int_type __delim); #endif /** * @brief Performs setup work for input streams. * * Objects of this class are created before all of the standard * extractors are run. It is responsible for exception-safe * prefix and suffix operations, although only prefix actions * are currently required by the standard. */ template class basic_istream<_CharT, _Traits>::sentry { // Data Members. bool _M_ok; public: /// Easy access to dependent types. typedef _Traits traits_type; typedef basic_streambuf<_CharT, _Traits> __streambuf_type; typedef basic_istream<_CharT, _Traits> __istream_type; typedef typename __istream_type::__ctype_type __ctype_type; typedef typename _Traits::int_type __int_type; /** * @brief The constructor performs all the work. * @param __is The input stream to guard. * @param __noskipws Whether to consume whitespace or not. * * If the stream state is good (@a __is.good() is true), then the * following actions are performed, otherwise the sentry state * is false (not okay) and failbit is set in the * stream state. * * The sentry's preparatory actions are: * * -# if the stream is tied to an output stream, @c is.tie()->flush() * is called to synchronize the output sequence * -# if @a __noskipws is false, and @c ios_base::skipws is set in * @c is.flags(), the sentry extracts and discards whitespace * characters from the stream. The currently imbued locale is * used to determine whether each character is whitespace. * * If the stream state is still good, then the sentry state becomes * true (@a okay). */ explicit sentry(basic_istream<_CharT, _Traits>& __is, bool __noskipws = false); /** * @brief Quick status checking. * @return The sentry state. * * For ease of use, sentries may be converted to booleans. The * return value is that of the sentry state (true == okay). */ #if __cplusplus >= 201103L explicit #endif operator bool() const { return _M_ok; } }; //@{ /** * @brief Character extractors * @param __in An input stream. * @param __c A character reference. * @return in * * Behaves like one of the formatted arithmetic extractors described in * std::basic_istream. After constructing a sentry object with good * status, this function extracts a character (if one is available) and * stores it in @a __c. Otherwise, sets failbit in the input stream. */ template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, _CharT& __c); template inline basic_istream& operator>>(basic_istream& __in, unsigned char& __c) { return (__in >> reinterpret_cast(__c)); } template inline basic_istream& operator>>(basic_istream& __in, signed char& __c) { return (__in >> reinterpret_cast(__c)); } //@} //@{ /** * @brief Character string extractors * @param __in An input stream. * @param __s A pointer to a character array. * @return __in * * Behaves like one of the formatted arithmetic extractors described in * std::basic_istream. After constructing a sentry object with good * status, this function extracts up to @c n characters and stores them * into the array starting at @a __s. @c n is defined as: * * - if @c width() is greater than zero, @c n is width() otherwise * - @c n is the number of elements of the largest array of * * - @c char_type that can store a terminating @c eos. * - [27.6.1.2.3]/6 * * Characters are extracted and stored until one of the following happens: * - @c n-1 characters are stored * - EOF is reached * - the next character is whitespace according to the current locale * - the next character is a null byte (i.e., @c charT() ) * * @c width(0) is then called for the input stream. * * If no characters are extracted, sets failbit. */ template basic_istream<_CharT, _Traits>& operator>>(basic_istream<_CharT, _Traits>& __in, _CharT* __s); // Explicit specialization declaration, defined in src/istream.cc. template<> basic_istream& operator>>(basic_istream& __in, char* __s); template inline basic_istream& operator>>(basic_istream& __in, unsigned char* __s) { return (__in >> reinterpret_cast(__s)); } template inline basic_istream& operator>>(basic_istream& __in, signed char* __s) { return (__in >> reinterpret_cast(__s)); } //@} /** * @brief Template class basic_iostream * @ingroup io * * @tparam _CharT Type of character stream. * @tparam _Traits Traits for character type, defaults to * char_traits<_CharT>. * * This class multiply inherits from the input and output stream classes * simply to provide a single interface. */ template class basic_iostream : public basic_istream<_CharT, _Traits>, public basic_ostream<_CharT, _Traits> { public: // _GLIBCXX_RESOLVE_LIB_DEFECTS // 271. basic_iostream missing typedefs // Types (inherited): typedef _CharT char_type; typedef typename _Traits::int_type int_type; typedef typename _Traits::pos_type pos_type; typedef typename _Traits::off_type off_type; typedef _Traits traits_type; // Non-standard Types: typedef basic_istream<_CharT, _Traits> __istream_type; typedef basic_ostream<_CharT, _Traits> __ostream_type; /** * @brief Constructor does nothing. * * Both of the parent classes are initialized with the same * streambuf pointer passed to this constructor. */ explicit basic_iostream(basic_streambuf<_CharT, _Traits>* __sb) : __istream_type(__sb), __ostream_type(__sb) { } /** * @brief Destructor does nothing. */ virtual ~basic_iostream() { } protected: basic_iostream() : __istream_type(), __ostream_type() { } #if __cplusplus >= 201103L basic_iostream(const basic_iostream&) = delete; basic_iostream(basic_iostream&& __rhs) : __istream_type(std::move(__rhs)), __ostream_type(*this) { } // 27.7.3.3 Assign/swap basic_iostream& operator=(const basic_iostream&) = delete; basic_iostream& operator=(basic_iostream&& __rhs) { swap(__rhs); return *this; } void swap(basic_iostream& __rhs) { __istream_type::swap(__rhs); } #endif }; /** * @brief Quick and easy way to eat whitespace * * This manipulator extracts whitespace characters, stopping when the * next character is non-whitespace, or when the input sequence is empty. * If the sequence is empty, @c eofbit is set in the stream, but not * @c failbit. * * The current locale is used to distinguish whitespace characters. * * Example: * @code * MyClass mc; * * std::cin >> std::ws >> mc; * @endcode * will skip leading whitespace before calling operator>> on cin and your * object. Note that the same effect can be achieved by creating a * std::basic_istream::sentry inside your definition of operator>>. */ template basic_istream<_CharT, _Traits>& ws(basic_istream<_CharT, _Traits>& __is); #if __cplusplus >= 201103L template basic_istream<_Ch, _Up>& __is_convertible_to_basic_istream_test(basic_istream<_Ch, _Up>*); template struct __is_convertible_to_basic_istream_impl { using __istream_type = void; }; template using __do_is_convertible_to_basic_istream_impl = decltype(__is_convertible_to_basic_istream_test (declval::type*>())); template struct __is_convertible_to_basic_istream_impl <_Tp, __void_t<__do_is_convertible_to_basic_istream_impl<_Tp>>> { using __istream_type = __do_is_convertible_to_basic_istream_impl<_Tp>; }; template struct __is_convertible_to_basic_istream : __is_convertible_to_basic_istream_impl<_Tp> { public: using type = __not_::__istream_type>>; constexpr static bool value = type::value; }; template struct __is_extractable : false_type {}; template struct __is_extractable<_Istream, _Tp, __void_t() >> declval<_Tp>())>> : true_type {}; template using __rvalue_istream_type = typename __is_convertible_to_basic_istream< _Istream>::__istream_type; // [27.7.1.6] Rvalue stream extraction // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2328. Rvalue stream extraction should use perfect forwarding /** * @brief Generic extractor for rvalue stream * @param __is An input stream. * @param __x A reference to the extraction target. * @return is * * This is just a forwarding function to allow extraction from * rvalue streams since they won't bind to the extractor functions * that take an lvalue reference. */ template inline typename enable_if<__and_<__not_>, __is_convertible_to_basic_istream<_Istream>, __is_extractable< __rvalue_istream_type<_Istream>, _Tp&&>>::value, __rvalue_istream_type<_Istream>>::type operator>>(_Istream&& __is, _Tp&& __x) { __rvalue_istream_type<_Istream> __ret_is = __is; __ret_is >> std::forward<_Tp>(__x); return __ret_is; } #endif // C++11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #include #endif /* _GLIBCXX_ISTREAM */ c++/8/cmath000064400000136016151027430570006315 0ustar00// -*- C++ -*- C forwarding header. // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file include/cmath * This is a Standard C++ Library file. You should @c \#include this file * in your programs, rather than any of the @a *.h implementation files. * * This is the C++ version of the Standard C Library header @c math.h, * and its contents are (mostly) the same as that header, but are all * contained in the namespace @c std (except for names which are defined * as macros in C). */ // // ISO C++ 14882: 26.5 C library // #pragma GCC system_header #include #include #include #define _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include_next #undef _GLIBCXX_INCLUDE_NEXT_C_HEADERS #include #ifndef _GLIBCXX_CMATH #define _GLIBCXX_CMATH 1 // Get rid of those macros defined in in lieu of real functions. #undef div #undef acos #undef asin #undef atan #undef atan2 #undef ceil #undef cos #undef cosh #undef exp #undef fabs #undef floor #undef fmod #undef frexp #undef ldexp #undef log #undef log10 #undef modf #undef pow #undef sin #undef sinh #undef sqrt #undef tan #undef tanh extern "C++" { namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using ::acos; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float acos(float __x) { return __builtin_acosf(__x); } inline _GLIBCXX_CONSTEXPR long double acos(long double __x) { return __builtin_acosl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type acos(_Tp __x) { return __builtin_acos(__x); } using ::asin; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float asin(float __x) { return __builtin_asinf(__x); } inline _GLIBCXX_CONSTEXPR long double asin(long double __x) { return __builtin_asinl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type asin(_Tp __x) { return __builtin_asin(__x); } using ::atan; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float atan(float __x) { return __builtin_atanf(__x); } inline _GLIBCXX_CONSTEXPR long double atan(long double __x) { return __builtin_atanl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type atan(_Tp __x) { return __builtin_atan(__x); } using ::atan2; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float atan2(float __y, float __x) { return __builtin_atan2f(__y, __x); } inline _GLIBCXX_CONSTEXPR long double atan2(long double __y, long double __x) { return __builtin_atan2l(__y, __x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__promote_2<_Tp, _Up>::__type atan2(_Tp __y, _Up __x) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return atan2(__type(__y), __type(__x)); } using ::ceil; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float ceil(float __x) { return __builtin_ceilf(__x); } inline _GLIBCXX_CONSTEXPR long double ceil(long double __x) { return __builtin_ceill(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type ceil(_Tp __x) { return __builtin_ceil(__x); } using ::cos; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float cos(float __x) { return __builtin_cosf(__x); } inline _GLIBCXX_CONSTEXPR long double cos(long double __x) { return __builtin_cosl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type cos(_Tp __x) { return __builtin_cos(__x); } using ::cosh; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float cosh(float __x) { return __builtin_coshf(__x); } inline _GLIBCXX_CONSTEXPR long double cosh(long double __x) { return __builtin_coshl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type cosh(_Tp __x) { return __builtin_cosh(__x); } using ::exp; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float exp(float __x) { return __builtin_expf(__x); } inline _GLIBCXX_CONSTEXPR long double exp(long double __x) { return __builtin_expl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type exp(_Tp __x) { return __builtin_exp(__x); } using ::fabs; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float fabs(float __x) { return __builtin_fabsf(__x); } inline _GLIBCXX_CONSTEXPR long double fabs(long double __x) { return __builtin_fabsl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type fabs(_Tp __x) { return __builtin_fabs(__x); } using ::floor; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float floor(float __x) { return __builtin_floorf(__x); } inline _GLIBCXX_CONSTEXPR long double floor(long double __x) { return __builtin_floorl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type floor(_Tp __x) { return __builtin_floor(__x); } using ::fmod; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float fmod(float __x, float __y) { return __builtin_fmodf(__x, __y); } inline _GLIBCXX_CONSTEXPR long double fmod(long double __x, long double __y) { return __builtin_fmodl(__x, __y); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__promote_2<_Tp, _Up>::__type fmod(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return fmod(__type(__x), __type(__y)); } using ::frexp; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline float frexp(float __x, int* __exp) { return __builtin_frexpf(__x, __exp); } inline long double frexp(long double __x, int* __exp) { return __builtin_frexpl(__x, __exp); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type frexp(_Tp __x, int* __exp) { return __builtin_frexp(__x, __exp); } using ::ldexp; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float ldexp(float __x, int __exp) { return __builtin_ldexpf(__x, __exp); } inline _GLIBCXX_CONSTEXPR long double ldexp(long double __x, int __exp) { return __builtin_ldexpl(__x, __exp); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type ldexp(_Tp __x, int __exp) { return __builtin_ldexp(__x, __exp); } using ::log; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float log(float __x) { return __builtin_logf(__x); } inline _GLIBCXX_CONSTEXPR long double log(long double __x) { return __builtin_logl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type log(_Tp __x) { return __builtin_log(__x); } using ::log10; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float log10(float __x) { return __builtin_log10f(__x); } inline _GLIBCXX_CONSTEXPR long double log10(long double __x) { return __builtin_log10l(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type log10(_Tp __x) { return __builtin_log10(__x); } using ::modf; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline float modf(float __x, float* __iptr) { return __builtin_modff(__x, __iptr); } inline long double modf(long double __x, long double* __iptr) { return __builtin_modfl(__x, __iptr); } #endif using ::pow; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float pow(float __x, float __y) { return __builtin_powf(__x, __y); } inline _GLIBCXX_CONSTEXPR long double pow(long double __x, long double __y) { return __builtin_powl(__x, __y); } #if __cplusplus < 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 550. What should the return type of pow(float,int) be? inline double pow(double __x, int __i) { return __builtin_powi(__x, __i); } inline float pow(float __x, int __n) { return __builtin_powif(__x, __n); } inline long double pow(long double __x, int __n) { return __builtin_powil(__x, __n); } #endif #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__promote_2<_Tp, _Up>::__type pow(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return pow(__type(__x), __type(__y)); } using ::sin; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float sin(float __x) { return __builtin_sinf(__x); } inline _GLIBCXX_CONSTEXPR long double sin(long double __x) { return __builtin_sinl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type sin(_Tp __x) { return __builtin_sin(__x); } using ::sinh; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float sinh(float __x) { return __builtin_sinhf(__x); } inline _GLIBCXX_CONSTEXPR long double sinh(long double __x) { return __builtin_sinhl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type sinh(_Tp __x) { return __builtin_sinh(__x); } using ::sqrt; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float sqrt(float __x) { return __builtin_sqrtf(__x); } inline _GLIBCXX_CONSTEXPR long double sqrt(long double __x) { return __builtin_sqrtl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type sqrt(_Tp __x) { return __builtin_sqrt(__x); } using ::tan; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float tan(float __x) { return __builtin_tanf(__x); } inline _GLIBCXX_CONSTEXPR long double tan(long double __x) { return __builtin_tanl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type tan(_Tp __x) { return __builtin_tan(__x); } using ::tanh; #ifndef __CORRECT_ISO_CPP_MATH_H_PROTO inline _GLIBCXX_CONSTEXPR float tanh(float __x) { return __builtin_tanhf(__x); } inline _GLIBCXX_CONSTEXPR long double tanh(long double __x) { return __builtin_tanhl(__x); } #endif template inline _GLIBCXX_CONSTEXPR typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type tanh(_Tp __x) { return __builtin_tanh(__x); } #if _GLIBCXX_USE_C99_MATH #if !_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC // These are possible macros imported from C99-land. #undef fpclassify #undef isfinite #undef isinf #undef isnan #undef isnormal #undef signbit #undef isgreater #undef isgreaterequal #undef isless #undef islessequal #undef islessgreater #undef isunordered #if __cplusplus >= 201103L #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr int fpclassify(float __x) { return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL, FP_SUBNORMAL, FP_ZERO, __x); } constexpr int fpclassify(double __x) { return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL, FP_SUBNORMAL, FP_ZERO, __x); } constexpr int fpclassify(long double __x) { return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL, FP_SUBNORMAL, FP_ZERO, __x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, int>::__type fpclassify(_Tp __x) { return __x != 0 ? FP_NORMAL : FP_ZERO; } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isfinite(float __x) { return __builtin_isfinite(__x); } constexpr bool isfinite(double __x) { return __builtin_isfinite(__x); } constexpr bool isfinite(long double __x) { return __builtin_isfinite(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, bool>::__type isfinite(_Tp __x) { return true; } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isinf(float __x) { return __builtin_isinf(__x); } #if _GLIBCXX_HAVE_OBSOLETE_ISINF \ && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC using ::isinf; #else constexpr bool isinf(double __x) { return __builtin_isinf(__x); } #endif constexpr bool isinf(long double __x) { return __builtin_isinf(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, bool>::__type isinf(_Tp __x) { return false; } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isnan(float __x) { return __builtin_isnan(__x); } #if _GLIBCXX_HAVE_OBSOLETE_ISNAN \ && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC using ::isnan; #else constexpr bool isnan(double __x) { return __builtin_isnan(__x); } #endif constexpr bool isnan(long double __x) { return __builtin_isnan(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, bool>::__type isnan(_Tp __x) { return false; } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isnormal(float __x) { return __builtin_isnormal(__x); } constexpr bool isnormal(double __x) { return __builtin_isnormal(__x); } constexpr bool isnormal(long double __x) { return __builtin_isnormal(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, bool>::__type isnormal(_Tp __x) { return __x != 0 ? true : false; } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP // Note: middle-end/36757 is fixed, __builtin_signbit is type-generic. constexpr bool signbit(float __x) { return __builtin_signbit(__x); } constexpr bool signbit(double __x) { return __builtin_signbit(__x); } constexpr bool signbit(long double __x) { return __builtin_signbit(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, bool>::__type signbit(_Tp __x) { return __x < 0 ? true : false; } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isgreater(float __x, float __y) { return __builtin_isgreater(__x, __y); } constexpr bool isgreater(double __x, double __y) { return __builtin_isgreater(__x, __y); } constexpr bool isgreater(long double __x, long double __y) { return __builtin_isgreater(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value && __is_arithmetic<_Up>::__value), bool>::__type isgreater(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return __builtin_isgreater(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isgreaterequal(float __x, float __y) { return __builtin_isgreaterequal(__x, __y); } constexpr bool isgreaterequal(double __x, double __y) { return __builtin_isgreaterequal(__x, __y); } constexpr bool isgreaterequal(long double __x, long double __y) { return __builtin_isgreaterequal(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value && __is_arithmetic<_Up>::__value), bool>::__type isgreaterequal(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return __builtin_isgreaterequal(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isless(float __x, float __y) { return __builtin_isless(__x, __y); } constexpr bool isless(double __x, double __y) { return __builtin_isless(__x, __y); } constexpr bool isless(long double __x, long double __y) { return __builtin_isless(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value && __is_arithmetic<_Up>::__value), bool>::__type isless(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return __builtin_isless(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool islessequal(float __x, float __y) { return __builtin_islessequal(__x, __y); } constexpr bool islessequal(double __x, double __y) { return __builtin_islessequal(__x, __y); } constexpr bool islessequal(long double __x, long double __y) { return __builtin_islessequal(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value && __is_arithmetic<_Up>::__value), bool>::__type islessequal(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return __builtin_islessequal(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool islessgreater(float __x, float __y) { return __builtin_islessgreater(__x, __y); } constexpr bool islessgreater(double __x, double __y) { return __builtin_islessgreater(__x, __y); } constexpr bool islessgreater(long double __x, long double __y) { return __builtin_islessgreater(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value && __is_arithmetic<_Up>::__value), bool>::__type islessgreater(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return __builtin_islessgreater(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr bool isunordered(float __x, float __y) { return __builtin_isunordered(__x, __y); } constexpr bool isunordered(double __x, double __y) { return __builtin_isunordered(__x, __y); } constexpr bool isunordered(long double __x, long double __y) { return __builtin_isunordered(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value && __is_arithmetic<_Up>::__value), bool>::__type isunordered(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return __builtin_isunordered(__type(__x), __type(__y)); } #endif #else template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type fpclassify(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL, FP_SUBNORMAL, FP_ZERO, __type(__f)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isfinite(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isfinite(__type(__f)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isinf(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isinf(__type(__f)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isnan(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isnan(__type(__f)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isnormal(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isnormal(__type(__f)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type signbit(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_signbit(__type(__f)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isgreater(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isgreater(__type(__f1), __type(__f2)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isgreaterequal(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isgreaterequal(__type(__f1), __type(__f2)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isless(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isless(__type(__f1), __type(__f2)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type islessequal(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_islessequal(__type(__f1), __type(__f2)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type islessgreater(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_islessgreater(__type(__f1), __type(__f2)); } template inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isunordered(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isunordered(__type(__f1), __type(__f2)); } #endif // C++11 #endif /* _GLIBCXX_USE_C99_FP_MACROS_DYNAMIC */ #endif /* _GLIBCXX_USE_C99_MATH */ #if __cplusplus >= 201103L #ifdef _GLIBCXX_USE_C99_MATH_TR1 #undef acosh #undef acoshf #undef acoshl #undef asinh #undef asinhf #undef asinhl #undef atanh #undef atanhf #undef atanhl #undef cbrt #undef cbrtf #undef cbrtl #undef copysign #undef copysignf #undef copysignl #undef erf #undef erff #undef erfl #undef erfc #undef erfcf #undef erfcl #undef exp2 #undef exp2f #undef exp2l #undef expm1 #undef expm1f #undef expm1l #undef fdim #undef fdimf #undef fdiml #undef fma #undef fmaf #undef fmal #undef fmax #undef fmaxf #undef fmaxl #undef fmin #undef fminf #undef fminl #undef hypot #undef hypotf #undef hypotl #undef ilogb #undef ilogbf #undef ilogbl #undef lgamma #undef lgammaf #undef lgammal #ifndef _GLIBCXX_NO_C99_ROUNDING_FUNCS #undef llrint #undef llrintf #undef llrintl #undef llround #undef llroundf #undef llroundl #endif #undef log1p #undef log1pf #undef log1pl #undef log2 #undef log2f #undef log2l #undef logb #undef logbf #undef logbl #undef lrint #undef lrintf #undef lrintl #undef lround #undef lroundf #undef lroundl #undef nan #undef nanf #undef nanl #undef nearbyint #undef nearbyintf #undef nearbyintl #undef nextafter #undef nextafterf #undef nextafterl #undef nexttoward #undef nexttowardf #undef nexttowardl #undef remainder #undef remainderf #undef remainderl #undef remquo #undef remquof #undef remquol #undef rint #undef rintf #undef rintl #undef round #undef roundf #undef roundl #undef scalbln #undef scalblnf #undef scalblnl #undef scalbn #undef scalbnf #undef scalbnl #undef tgamma #undef tgammaf #undef tgammal #undef trunc #undef truncf #undef truncl // types using ::double_t; using ::float_t; // functions using ::acosh; using ::acoshf; using ::acoshl; using ::asinh; using ::asinhf; using ::asinhl; using ::atanh; using ::atanhf; using ::atanhl; using ::cbrt; using ::cbrtf; using ::cbrtl; using ::copysign; using ::copysignf; using ::copysignl; using ::erf; using ::erff; using ::erfl; using ::erfc; using ::erfcf; using ::erfcl; using ::exp2; using ::exp2f; using ::exp2l; using ::expm1; using ::expm1f; using ::expm1l; using ::fdim; using ::fdimf; using ::fdiml; using ::fma; using ::fmaf; using ::fmal; using ::fmax; using ::fmaxf; using ::fmaxl; using ::fmin; using ::fminf; using ::fminl; using ::hypot; using ::hypotf; using ::hypotl; using ::ilogb; using ::ilogbf; using ::ilogbl; using ::lgamma; using ::lgammaf; using ::lgammal; #ifndef _GLIBCXX_NO_C99_ROUNDING_FUNCS using ::llrint; using ::llrintf; using ::llrintl; using ::llround; using ::llroundf; using ::llroundl; #endif using ::log1p; using ::log1pf; using ::log1pl; using ::log2; using ::log2f; using ::log2l; using ::logb; using ::logbf; using ::logbl; using ::lrint; using ::lrintf; using ::lrintl; using ::lround; using ::lroundf; using ::lroundl; using ::nan; using ::nanf; using ::nanl; using ::nearbyint; using ::nearbyintf; using ::nearbyintl; using ::nextafter; using ::nextafterf; using ::nextafterl; using ::nexttoward; using ::nexttowardf; using ::nexttowardl; using ::remainder; using ::remainderf; using ::remainderl; using ::remquo; using ::remquof; using ::remquol; using ::rint; using ::rintf; using ::rintl; using ::round; using ::roundf; using ::roundl; using ::scalbln; using ::scalblnf; using ::scalblnl; using ::scalbn; using ::scalbnf; using ::scalbnl; using ::tgamma; using ::tgammaf; using ::tgammal; using ::trunc; using ::truncf; using ::truncl; /// Additional overloads. #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float acosh(float __x) { return __builtin_acoshf(__x); } constexpr long double acosh(long double __x) { return __builtin_acoshl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type acosh(_Tp __x) { return __builtin_acosh(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float asinh(float __x) { return __builtin_asinhf(__x); } constexpr long double asinh(long double __x) { return __builtin_asinhl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type asinh(_Tp __x) { return __builtin_asinh(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float atanh(float __x) { return __builtin_atanhf(__x); } constexpr long double atanh(long double __x) { return __builtin_atanhl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type atanh(_Tp __x) { return __builtin_atanh(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float cbrt(float __x) { return __builtin_cbrtf(__x); } constexpr long double cbrt(long double __x) { return __builtin_cbrtl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type cbrt(_Tp __x) { return __builtin_cbrt(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float copysign(float __x, float __y) { return __builtin_copysignf(__x, __y); } constexpr long double copysign(long double __x, long double __y) { return __builtin_copysignl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type copysign(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return copysign(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float erf(float __x) { return __builtin_erff(__x); } constexpr long double erf(long double __x) { return __builtin_erfl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type erf(_Tp __x) { return __builtin_erf(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float erfc(float __x) { return __builtin_erfcf(__x); } constexpr long double erfc(long double __x) { return __builtin_erfcl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type erfc(_Tp __x) { return __builtin_erfc(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float exp2(float __x) { return __builtin_exp2f(__x); } constexpr long double exp2(long double __x) { return __builtin_exp2l(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type exp2(_Tp __x) { return __builtin_exp2(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float expm1(float __x) { return __builtin_expm1f(__x); } constexpr long double expm1(long double __x) { return __builtin_expm1l(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type expm1(_Tp __x) { return __builtin_expm1(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float fdim(float __x, float __y) { return __builtin_fdimf(__x, __y); } constexpr long double fdim(long double __x, long double __y) { return __builtin_fdiml(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type fdim(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return fdim(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float fma(float __x, float __y, float __z) { return __builtin_fmaf(__x, __y, __z); } constexpr long double fma(long double __x, long double __y, long double __z) { return __builtin_fmal(__x, __y, __z); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type fma(_Tp __x, _Up __y, _Vp __z) { typedef typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type __type; return fma(__type(__x), __type(__y), __type(__z)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float fmax(float __x, float __y) { return __builtin_fmaxf(__x, __y); } constexpr long double fmax(long double __x, long double __y) { return __builtin_fmaxl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type fmax(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return fmax(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float fmin(float __x, float __y) { return __builtin_fminf(__x, __y); } constexpr long double fmin(long double __x, long double __y) { return __builtin_fminl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type fmin(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return fmin(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float hypot(float __x, float __y) { return __builtin_hypotf(__x, __y); } constexpr long double hypot(long double __x, long double __y) { return __builtin_hypotl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type hypot(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return hypot(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr int ilogb(float __x) { return __builtin_ilogbf(__x); } constexpr int ilogb(long double __x) { return __builtin_ilogbl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, int>::__type ilogb(_Tp __x) { return __builtin_ilogb(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float lgamma(float __x) { return __builtin_lgammaf(__x); } constexpr long double lgamma(long double __x) { return __builtin_lgammal(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type lgamma(_Tp __x) { return __builtin_lgamma(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr long long llrint(float __x) { return __builtin_llrintf(__x); } constexpr long long llrint(long double __x) { return __builtin_llrintl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, long long>::__type llrint(_Tp __x) { return __builtin_llrint(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr long long llround(float __x) { return __builtin_llroundf(__x); } constexpr long long llround(long double __x) { return __builtin_llroundl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, long long>::__type llround(_Tp __x) { return __builtin_llround(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float log1p(float __x) { return __builtin_log1pf(__x); } constexpr long double log1p(long double __x) { return __builtin_log1pl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type log1p(_Tp __x) { return __builtin_log1p(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP // DR 568. constexpr float log2(float __x) { return __builtin_log2f(__x); } constexpr long double log2(long double __x) { return __builtin_log2l(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type log2(_Tp __x) { return __builtin_log2(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float logb(float __x) { return __builtin_logbf(__x); } constexpr long double logb(long double __x) { return __builtin_logbl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type logb(_Tp __x) { return __builtin_logb(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr long lrint(float __x) { return __builtin_lrintf(__x); } constexpr long lrint(long double __x) { return __builtin_lrintl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, long>::__type lrint(_Tp __x) { return __builtin_lrint(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr long lround(float __x) { return __builtin_lroundf(__x); } constexpr long lround(long double __x) { return __builtin_lroundl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, long>::__type lround(_Tp __x) { return __builtin_lround(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float nearbyint(float __x) { return __builtin_nearbyintf(__x); } constexpr long double nearbyint(long double __x) { return __builtin_nearbyintl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type nearbyint(_Tp __x) { return __builtin_nearbyint(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float nextafter(float __x, float __y) { return __builtin_nextafterf(__x, __y); } constexpr long double nextafter(long double __x, long double __y) { return __builtin_nextafterl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type nextafter(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return nextafter(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float nexttoward(float __x, long double __y) { return __builtin_nexttowardf(__x, __y); } constexpr long double nexttoward(long double __x, long double __y) { return __builtin_nexttowardl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type nexttoward(_Tp __x, long double __y) { return __builtin_nexttoward(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float remainder(float __x, float __y) { return __builtin_remainderf(__x, __y); } constexpr long double remainder(long double __x, long double __y) { return __builtin_remainderl(__x, __y); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type remainder(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return remainder(__type(__x), __type(__y)); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP inline float remquo(float __x, float __y, int* __pquo) { return __builtin_remquof(__x, __y, __pquo); } inline long double remquo(long double __x, long double __y, int* __pquo) { return __builtin_remquol(__x, __y, __pquo); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template inline typename __gnu_cxx::__promote_2<_Tp, _Up>::__type remquo(_Tp __x, _Up __y, int* __pquo) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return remquo(__type(__x), __type(__y), __pquo); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float rint(float __x) { return __builtin_rintf(__x); } constexpr long double rint(long double __x) { return __builtin_rintl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type rint(_Tp __x) { return __builtin_rint(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float round(float __x) { return __builtin_roundf(__x); } constexpr long double round(long double __x) { return __builtin_roundl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type round(_Tp __x) { return __builtin_round(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float scalbln(float __x, long __ex) { return __builtin_scalblnf(__x, __ex); } constexpr long double scalbln(long double __x, long __ex) { return __builtin_scalblnl(__x, __ex); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type scalbln(_Tp __x, long __ex) { return __builtin_scalbln(__x, __ex); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float scalbn(float __x, int __ex) { return __builtin_scalbnf(__x, __ex); } constexpr long double scalbn(long double __x, int __ex) { return __builtin_scalbnl(__x, __ex); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type scalbn(_Tp __x, int __ex) { return __builtin_scalbn(__x, __ex); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float tgamma(float __x) { return __builtin_tgammaf(__x); } constexpr long double tgamma(long double __x) { return __builtin_tgammal(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type tgamma(_Tp __x) { return __builtin_tgamma(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP constexpr float trunc(float __x) { return __builtin_truncf(__x); } constexpr long double trunc(long double __x) { return __builtin_truncl(__x); } #endif #ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT template constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type trunc(_Tp __x) { return __builtin_trunc(__x); } #endif #endif // _GLIBCXX_USE_C99_MATH_TR1 #endif // C++11 #if __cplusplus > 201402L // [c.math.hypot3], three-dimensional hypotenuse #define __cpp_lib_hypot 201603 template inline _Tp __hypot3(_Tp __x, _Tp __y, _Tp __z) { __x = std::abs(__x); __y = std::abs(__y); __z = std::abs(__z); if (_Tp __a = __x < __y ? __y < __z ? __z : __y : __x < __z ? __z : __x) return __a * std::sqrt((__x / __a) * (__x / __a) + (__y / __a) * (__y / __a) + (__z / __a) * (__z / __a)); else return {}; } inline float hypot(float __x, float __y, float __z) { return std::__hypot3(__x, __y, __z); } inline double hypot(double __x, double __y, double __z) { return std::__hypot3(__x, __y, __z); } inline long double hypot(long double __x, long double __y, long double __z) { return std::__hypot3(__x, __y, __z); } template typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type hypot(_Tp __x, _Up __y, _Vp __z) { using __type = typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type; return std::__hypot3<__type>(__x, __y, __z); } #endif // C++17 _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if _GLIBCXX_USE_STD_SPEC_FUNCS # include #endif } // extern "C++" #endif c++/8/debug/unordered_map000064400000122112151027430570011123 0ustar00// Debugging unordered_map/unordered_multimap implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/unordered_map * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_UNORDERED_MAP #define _GLIBCXX_DEBUG_UNORDERED_MAP 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else # include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::unordered_map with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator > > class unordered_map : public __gnu_debug::_Safe_container< unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_map> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_map> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_map> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_map> const_local_iterator; unordered_map() = default; explicit unordered_map(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_map(const unordered_map&) = default; unordered_map(const _Base& __x) : _Base(__x) { } unordered_map(unordered_map&&) = default; explicit unordered_map(const allocator_type& __a) : _Base(__a) { } unordered_map(const unordered_map& __umap, const allocator_type& __a) : _Base(__umap, __a) { } unordered_map(unordered_map&& __umap, const allocator_type& __a) : _Safe(std::move(__umap._M_safe()), __a), _Base(std::move(__umap._M_base()), __a) { } unordered_map(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_map(size_type __n, const allocator_type& __a) : unordered_map(__n, hasher(), key_equal(), __a) { } unordered_map(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__n, __hf, key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_map(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_map(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__first, __last, __n, __hf, key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_map(__l, __n, hasher(), key_equal(), __a) { } unordered_map(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_map(__l, __n, __hf, key_equal(), __a) { } ~unordered_map() = default; unordered_map& operator=(const unordered_map&) = default; unordered_map& operator=(unordered_map&&) = default; unordered_map& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_map& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template std::pair emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } std::pair insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); auto __res = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return { iterator(__res.first, this), __res.second }; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { size_type __bucket_count = this->bucket_count(); auto __res = _Base::insert(std::move(__x)); _M_check_rehashed(__bucket_count); return { iterator(__res.first, this), __res.second }; } template::value>::type> std::pair insert(_Pair&& __obj) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::insert(std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); auto __it = _Base::insert(__hint.base(), std::move(__x)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template::value>::type> iterator insert(const_iterator __hint, _Pair&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { size_type __bucket_count = this->bucket_count(); _Base::insert(__l); _M_check_rehashed(__bucket_count); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L template pair try_emplace(const key_type& __k, _Args&&... __args) { auto __res = _Base::try_emplace(__k, std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template pair try_emplace(key_type&& __k, _Args&&... __args) { auto __res = _Base::try_emplace(std::move(__k), std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), __k, std::forward<_Args>(__args)...), this); } template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), std::move(__k), std::forward<_Args>(__args)...), this); } template pair insert_or_assign(const key_type& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(__k, std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template pair insert_or_assign(key_type&& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(std::move(__k), std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), __k, std::forward<_Obj>(__obj)), this); } template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), std::move(__k), std::forward<_Obj>(__obj)), this); } #endif // C++17 #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); _Base_iterator __victim(_Base::find(__key)); if (__victim != _Base::end()) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base::erase(__victim); _M_check_rehashed(__bucket_count); __ret = 1; } return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__it.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if([__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__first.base(), __last.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_map(initializer_list>, typename unordered_map::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_map<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_map(_InputIterator, _InputIterator, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, _Allocator) -> unordered_map<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_map(initializer_list>, typename unordered_map::size_type, _Hash, _Allocator) -> unordered_map<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif template inline void swap(unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } /// Class std::unordered_multimap with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator > > class unordered_multimap : public __gnu_debug::_Safe_container< unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_multimap> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_multimap> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_multimap> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_multimap> const_local_iterator; unordered_multimap() = default; explicit unordered_multimap(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_multimap(const unordered_multimap&) = default; unordered_multimap(const _Base& __x) : _Base(__x) { } unordered_multimap(unordered_multimap&&) = default; explicit unordered_multimap(const allocator_type& __a) : _Base(__a) { } unordered_multimap(const unordered_multimap& __umap, const allocator_type& __a) : _Base(__umap, __a) { } unordered_multimap(unordered_multimap&& __umap, const allocator_type& __a) : _Safe(std::move(__umap._M_safe()), __a), _Base(std::move(__umap._M_base()), __a) { } unordered_multimap(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_multimap(size_type __n, const allocator_type& __a) : unordered_multimap(__n, hasher(), key_equal(), __a) { } unordered_multimap(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__n, __hf, key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multimap(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multimap(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multimap(__l, __n, hasher(), key_equal(), __a) { } unordered_multimap(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multimap(__l, __n, __hf, key_equal(), __a) { } ~unordered_multimap() = default; unordered_multimap& operator=(const unordered_multimap&) = default; unordered_multimap& operator=(unordered_multimap&&) = default; unordered_multimap& operator=(initializer_list __l) { this->_M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_multimap& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template iterator emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(value_type&& __x) { size_type __bucket_count = this->bucket_count(); auto __it = _Base::insert(std::move(__x)); _M_check_rehashed(__bucket_count); return { __it, this }; } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __hint, value_type&& __x) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); auto __it = _Base::insert(__hint.base(), std::move(__x)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template::value>::type> iterator insert(_Pair&& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template::value>::type> iterator insert(const_iterator __hint, _Pair&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::forward<_Pair>(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { _Base::insert(__l); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, _Base_iterator> __pair = _Base::equal_range(__key); for (_Base_iterator __victim = __pair.first; __victim != __pair.second;) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); _Base::erase(__victim++); ++__ret; } _M_check_rehashed(__bucket_count); return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__it.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if([__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__first.base(), __last.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template>, typename _Pred = equal_to<__iter_key_t<_InputIterator>>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Key>, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> unordered_multimap(initializer_list>, unordered_multimap::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multimap<_Key, _Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, hash<__iter_key_t<_InputIterator>>, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multimap(_InputIterator, _InputIterator, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Hash, equal_to<__iter_key_t<_InputIterator>>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, _Allocator) -> unordered_multimap<_Key, _Tp, hash<_Key>, equal_to<_Key>, _Allocator>; template> unordered_multimap(initializer_list>, unordered_multimap::size_type, _Hash, _Allocator) -> unordered_multimap<_Key, _Tp, _Hash, equal_to<_Key>, _Allocator>; #endif template inline void swap(unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x, const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } } // namespace __debug } // namespace std #endif // C++11 #endif c++/8/debug/safe_base.h000064400000022077151027430570010446 0ustar00// Safe sequence/iterator base implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_base.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_BASE_H #define _GLIBCXX_DEBUG_SAFE_BASE_H 1 #include namespace __gnu_debug { class _Safe_sequence_base; /** \brief Basic functionality for a @a safe iterator. * * The %_Safe_iterator_base base class implements the functionality * of a safe iterator that is not specific to a particular iterator * type. It contains a pointer back to the sequence it references * along with iterator version information and pointers to form a * doubly-linked list of iterators referenced by the container. * * This class must not perform any operations that can throw an * exception, or the exception guarantees of derived iterators will * be broken. */ class _Safe_iterator_base { friend class _Safe_sequence_base; public: /** The sequence this iterator references; may be NULL to indicate a singular iterator. */ _Safe_sequence_base* _M_sequence; /** The version number of this iterator. The sentinel value 0 is * used to indicate an invalidated iterator (i.e., one that is * singular because of an operation on the container). This * version number must equal the version number in the sequence * referenced by _M_sequence for the iterator to be * non-singular. */ unsigned int _M_version; /** Pointer to the previous iterator in the sequence's list of iterators. Only valid when _M_sequence != NULL. */ _Safe_iterator_base* _M_prior; /** Pointer to the next iterator in the sequence's list of iterators. Only valid when _M_sequence != NULL. */ _Safe_iterator_base* _M_next; protected: /** Initializes the iterator and makes it singular. */ _Safe_iterator_base() : _M_sequence(0), _M_version(0), _M_prior(0), _M_next(0) { } /** Initialize the iterator to reference the sequence pointed to * by @p __seq. @p __constant is true when we are initializing a * constant iterator, and false if it is a mutable iterator. Note * that @p __seq may be NULL, in which case the iterator will be * singular. Otherwise, the iterator will reference @p __seq and * be nonsingular. */ _Safe_iterator_base(const _Safe_sequence_base* __seq, bool __constant) : _M_sequence(0), _M_version(0), _M_prior(0), _M_next(0) { this->_M_attach(const_cast<_Safe_sequence_base*>(__seq), __constant); } /** Initializes the iterator to reference the same sequence that @p __x does. @p __constant is true if this is a constant iterator, and false if it is mutable. */ _Safe_iterator_base(const _Safe_iterator_base& __x, bool __constant) : _M_sequence(0), _M_version(0), _M_prior(0), _M_next(0) { this->_M_attach(__x._M_sequence, __constant); } ~_Safe_iterator_base() { this->_M_detach(); } /** For use in _Safe_iterator. */ __gnu_cxx::__mutex& _M_get_mutex() throw (); /** Attaches this iterator to the given sequence, detaching it * from whatever sequence it was attached to originally. If the * new sequence is the NULL pointer, the iterator is left * unattached. */ void _M_attach(_Safe_sequence_base* __seq, bool __constant); /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq, bool __constant) throw (); /** Detach the iterator for whatever sequence it is attached to, * if any. */ void _M_detach(); public: /** Likewise, but not thread-safe. */ void _M_detach_single() throw (); /** Determines if we are attached to the given sequence. */ bool _M_attached_to(const _Safe_sequence_base* __seq) const { return _M_sequence == __seq; } /** Is this iterator singular? */ _GLIBCXX_PURE bool _M_singular() const throw (); /** Can we compare this iterator to the given iterator @p __x? Returns true if both iterators are nonsingular and reference the same sequence. */ _GLIBCXX_PURE bool _M_can_compare(const _Safe_iterator_base& __x) const throw (); /** Invalidate the iterator, making it singular. */ void _M_invalidate() { _M_version = 0; } /** Reset all member variables */ void _M_reset() throw (); /** Unlink itself */ void _M_unlink() throw () { if (_M_prior) _M_prior->_M_next = _M_next; if (_M_next) _M_next->_M_prior = _M_prior; } }; /** Iterators that derive from _Safe_iterator_base can be determined singular * or non-singular. **/ inline bool __check_singular_aux(const _Safe_iterator_base* __x) { return __x->_M_singular(); } /** * @brief Base class that supports tracking of iterators that * reference a sequence. * * The %_Safe_sequence_base class provides basic support for * tracking iterators into a sequence. Sequences that track * iterators must derived from %_Safe_sequence_base publicly, so * that safe iterators (which inherit _Safe_iterator_base) can * attach to them. This class contains two linked lists of * iterators, one for constant iterators and one for mutable * iterators, and a version number that allows very fast * invalidation of all iterators that reference the container. * * This class must ensure that no operation on it may throw an * exception, otherwise @a safe sequences may fail to provide the * exception-safety guarantees required by the C++ standard. */ class _Safe_sequence_base { friend class _Safe_iterator_base; public: /// The list of mutable iterators that reference this container _Safe_iterator_base* _M_iterators; /// The list of constant iterators that reference this container _Safe_iterator_base* _M_const_iterators; /// The container version number. This number may never be 0. mutable unsigned int _M_version; protected: // Initialize with a version number of 1 and no iterators _Safe_sequence_base() _GLIBCXX_NOEXCEPT : _M_iterators(0), _M_const_iterators(0), _M_version(1) { } #if __cplusplus >= 201103L _Safe_sequence_base(const _Safe_sequence_base&) noexcept : _Safe_sequence_base() { } // Move constructor swap iterators. _Safe_sequence_base(_Safe_sequence_base&& __seq) noexcept : _Safe_sequence_base() { _M_swap(__seq); } #endif /** Notify all iterators that reference this sequence that the sequence is being destroyed. */ ~_Safe_sequence_base() { this->_M_detach_all(); } /** Detach all iterators, leaving them singular. */ void _M_detach_all(); /** Detach all singular iterators. * @post for all iterators i attached to this sequence, * i->_M_version == _M_version. */ void _M_detach_singular(); /** Revalidates all attached singular iterators. This method may * be used to validate iterators that were invalidated before * (but for some reason, such as an exception, need to become * valid again). */ void _M_revalidate_singular(); /** Swap this sequence with the given sequence. This operation * also swaps ownership of the iterators, so that when the * operation is complete all iterators that originally referenced * one container now reference the other container. */ void _M_swap(_Safe_sequence_base& __x) _GLIBCXX_USE_NOEXCEPT; /** For use in _Safe_sequence. */ __gnu_cxx::__mutex& _M_get_mutex() throw (); /** Invalidates all iterators. */ void _M_invalidate_all() const { if (++_M_version == 0) _M_version = 1; } private: /** Attach an iterator to this sequence. */ void _M_attach(_Safe_iterator_base* __it, bool __constant); /** Likewise but not thread safe. */ void _M_attach_single(_Safe_iterator_base* __it, bool __constant) throw (); /** Detach an iterator from this sequence */ void _M_detach(_Safe_iterator_base* __it); /** Likewise but not thread safe. */ void _M_detach_single(_Safe_iterator_base* __it) throw (); }; } // namespace __gnu_debug #endif c++/8/debug/safe_unordered_base.h000064400000015357151027430570012520 0ustar00// Safe container/iterator base implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_unordered_base.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_UNORDERED_BASE_H #define _GLIBCXX_DEBUG_SAFE_UNORDERED_BASE_H 1 #include namespace __gnu_debug { class _Safe_unordered_container_base; /** \brief Basic functionality for a @a safe iterator. * * The %_Safe_local_iterator_base base class implements the functionality * of a safe local iterator that is not specific to a particular iterator * type. It contains a pointer back to the container it references * along with iterator version information and pointers to form a * doubly-linked list of local iterators referenced by the container. * * This class must not perform any operations that can throw an * exception, or the exception guarantees of derived iterators will * be broken. */ class _Safe_local_iterator_base : public _Safe_iterator_base { protected: /** Initializes the iterator and makes it singular. */ _Safe_local_iterator_base() { } /** Initialize the iterator to reference the container pointed to * by @p __seq. @p __constant is true when we are initializing a * constant local iterator, and false if it is a mutable local iterator. * Note that @p __seq may be NULL, in which case the iterator will be * singular. Otherwise, the iterator will reference @p __seq and * be nonsingular. */ _Safe_local_iterator_base(const _Safe_sequence_base* __seq, bool __constant) { this->_M_attach(const_cast<_Safe_sequence_base*>(__seq), __constant); } /** Initializes the iterator to reference the same container that @p __x does. @p __constant is true if this is a constant iterator, and false if it is mutable. */ _Safe_local_iterator_base(const _Safe_local_iterator_base& __x, bool __constant) { this->_M_attach(__x._M_sequence, __constant); } ~_Safe_local_iterator_base() { this->_M_detach(); } _Safe_unordered_container_base* _M_get_container() const noexcept; /** Attaches this iterator to the given container, detaching it * from whatever container it was attached to originally. If the * new container is the NULL pointer, the iterator is left * unattached. */ void _M_attach(_Safe_sequence_base* __seq, bool __constant); /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq, bool __constant) throw (); /** Detach the iterator for whatever container it is attached to, * if any. */ void _M_detach(); /** Likewise, but not thread-safe. */ void _M_detach_single() throw (); }; /** * @brief Base class that supports tracking of local iterators that * reference an unordered container. * * The %_Safe_unordered_container_base class provides basic support for * tracking iterators into an unordered container. Containers that track * iterators must derived from %_Safe_unordered_container_base publicly, so * that safe iterators (which inherit _Safe_iterator_base) can * attach to them. This class contains four linked lists of * iterators, one for constant iterators, one for mutable * iterators, one for constant local iterators, one for mutable local * iterators and a version number that allows very fast * invalidation of all iterators that reference the container. * * This class must ensure that no operation on it may throw an * exception, otherwise @a safe containers may fail to provide the * exception-safety guarantees required by the C++ standard. */ class _Safe_unordered_container_base : public _Safe_sequence_base { friend class _Safe_local_iterator_base; typedef _Safe_sequence_base _Base; public: /// The list of mutable local iterators that reference this container _Safe_iterator_base* _M_local_iterators; /// The list of constant local iterators that reference this container _Safe_iterator_base* _M_const_local_iterators; protected: // Initialize with a version number of 1 and no iterators _Safe_unordered_container_base() noexcept : _M_local_iterators(nullptr), _M_const_local_iterators(nullptr) { } // Copy constructor does not copy iterators. _Safe_unordered_container_base(const _Safe_unordered_container_base&) noexcept : _Safe_unordered_container_base() { } // When moved unordered containers iterators are swapped. _Safe_unordered_container_base(_Safe_unordered_container_base&& __x) noexcept : _Safe_unordered_container_base() { this->_M_swap(__x); } /** Notify all iterators that reference this container that the container is being destroyed. */ ~_Safe_unordered_container_base() noexcept { this->_M_detach_all(); } /** Detach all iterators, leaving them singular. */ void _M_detach_all(); /** Swap this container with the given container. This operation * also swaps ownership of the iterators, so that when the * operation is complete all iterators that originally referenced * one container now reference the other container. */ void _M_swap(_Safe_unordered_container_base& __x) noexcept; private: /** Attach an iterator to this container. */ void _M_attach_local(_Safe_iterator_base* __it, bool __constant); /** Likewise but not thread safe. */ void _M_attach_local_single(_Safe_iterator_base* __it, bool __constant) throw (); /** Detach an iterator from this container */ void _M_detach_local(_Safe_iterator_base* __it); /** Likewise but not thread safe. */ void _M_detach_local_single(_Safe_iterator_base* __it) throw (); }; } // namespace __gnu_debug #endif c++/8/debug/forward_list000064400000062105151027430570011003 0ustar00// -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/forward_list * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_FORWARD_LIST #define _GLIBCXX_DEBUG_FORWARD_LIST 1 #pragma GCC system_header #include #include #include #include // Special validity check for forward_list ranges. #define __glibcxx_check_valid_fl_range(_First,_Last,_Dist) \ _GLIBCXX_DEBUG_VERIFY(_First._M_valid_range(_Last, _Dist, false), \ _M_message(__gnu_debug::__msg_valid_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) namespace __gnu_debug { /// Special iterators swap and invalidation for forward_list because of the /// before_begin iterator. template class _Safe_forward_list : public _Safe_sequence<_SafeSequence> { _SafeSequence& _M_this() noexcept { return *static_cast<_SafeSequence*>(this); } static void _M_swap_aux(_Safe_sequence_base& __lhs, _Safe_iterator_base*& __lhs_iterators, _Safe_sequence_base& __rhs, _Safe_iterator_base*& __rhs_iterators); void _M_swap_single(_Safe_sequence_base&) noexcept; protected: void _M_invalidate_all() { using _Base_const_iterator = __decltype(_M_this()._M_base().cend()); this->_M_invalidate_if([this](_Base_const_iterator __it) { return __it != _M_this()._M_base().cbefore_begin() && __it != _M_this()._M_base().cend(); }); } void _M_swap(_Safe_sequence_base&) noexcept; }; template void _Safe_forward_list<_SafeSequence>:: _M_swap_aux(_Safe_sequence_base& __lhs, _Safe_iterator_base*& __lhs_iterators, _Safe_sequence_base& __rhs, _Safe_iterator_base*& __rhs_iterators) { using const_iterator = typename _SafeSequence::const_iterator; _Safe_iterator_base* __bbegin_its = 0; _Safe_iterator_base* __last_bbegin = 0; _SafeSequence& __rseq = static_cast<_SafeSequence&>(__rhs); for (_Safe_iterator_base* __iter = __lhs_iterators; __iter;) { // Even iterator is cast to const_iterator, not a problem. _Safe_iterator_base* __victim_base = __iter; const_iterator* __victim = static_cast(__victim_base); __iter = __iter->_M_next; if (__victim->base() == __rseq._M_base().cbefore_begin()) { __victim->_M_unlink(); if (__lhs_iterators == __victim_base) __lhs_iterators = __victim_base->_M_next; if (__bbegin_its) { __victim_base->_M_next = __bbegin_its; __bbegin_its->_M_prior = __victim_base; } else __last_bbegin = __victim_base; __bbegin_its = __victim_base; } else __victim_base->_M_sequence = std::__addressof(__lhs); } if (__bbegin_its) { if (__rhs_iterators) { __rhs_iterators->_M_prior = __last_bbegin; __last_bbegin->_M_next = __rhs_iterators; } __rhs_iterators = __bbegin_its; } } template void _Safe_forward_list<_SafeSequence>:: _M_swap_single(_Safe_sequence_base& __other) noexcept { std::swap(_M_this()._M_iterators, __other._M_iterators); std::swap(_M_this()._M_const_iterators, __other._M_const_iterators); // Useless, always 1 on forward_list //std::swap(_M_this()_M_version, __other._M_version); _Safe_iterator_base* __this_its = _M_this()._M_iterators; _M_swap_aux(__other, __other._M_iterators, _M_this(), _M_this()._M_iterators); _Safe_iterator_base* __this_const_its = _M_this()._M_const_iterators; _M_swap_aux(__other, __other._M_const_iterators, _M_this(), _M_this()._M_const_iterators); _M_swap_aux(_M_this(), __this_its, __other, __other._M_iterators); _M_swap_aux(_M_this(), __this_const_its, __other, __other._M_const_iterators); } /* Special forward_list _M_swap version that does not swap the * before-begin ownership.*/ template void _Safe_forward_list<_SafeSequence>:: _M_swap(_Safe_sequence_base& __other) noexcept { // We need to lock both sequences to swap using namespace __gnu_cxx; __mutex *__this_mutex = &_M_this()._M_get_mutex(); __mutex *__other_mutex = &static_cast<_SafeSequence&>(__other)._M_get_mutex(); if (__this_mutex == __other_mutex) { __scoped_lock __lock(*__this_mutex); _M_swap_single(__other); } else { __scoped_lock __l1(__this_mutex < __other_mutex ? *__this_mutex : *__other_mutex); __scoped_lock __l2(__this_mutex < __other_mutex ? *__other_mutex : *__this_mutex); _M_swap_single(__other); } } } namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::forward_list with safety/checking/debug instrumentation. template > class forward_list : public __gnu_debug::_Safe_container< forward_list<_Tp, _Alloc>, _Alloc, __gnu_debug::_Safe_forward_list>, public _GLIBCXX_STD_C::forward_list<_Tp, _Alloc> { typedef _GLIBCXX_STD_C::forward_list<_Tp, _Alloc> _Base; typedef __gnu_debug::_Safe_container< forward_list, _Alloc, __gnu_debug::_Safe_forward_list> _Safe; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator< _Base_iterator, forward_list> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, forward_list> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; // 23.2.3.1 construct/copy/destroy: forward_list() = default; explicit forward_list(const allocator_type& __al) noexcept : _Base(__al) { } forward_list(const forward_list& __list, const allocator_type& __al) : _Base(__list, __al) { } forward_list(forward_list&& __list, const allocator_type& __al) : _Safe(std::move(__list._M_safe()), __al), _Base(std::move(__list._M_base()), __al) { } explicit forward_list(size_type __n, const allocator_type& __al = allocator_type()) : _Base(__n, __al) { } forward_list(size_type __n, const _Tp& __value, const allocator_type& __al = allocator_type()) : _Base(__n, __value, __al) { } template> forward_list(_InputIterator __first, _InputIterator __last, const allocator_type& __al = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __al) { } forward_list(const forward_list&) = default; forward_list(forward_list&&) = default; forward_list(std::initializer_list<_Tp> __il, const allocator_type& __al = allocator_type()) : _Base(__il, __al) { } ~forward_list() = default; forward_list& operator=(const forward_list&) = default; forward_list& operator=(forward_list&&) = default; forward_list& operator=(std::initializer_list<_Tp> __il) { _M_base() = __il; this->_M_invalidate_all(); return *this; } template> void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); } void assign(size_type __n, const _Tp& __val) { _Base::assign(__n, __val); this->_M_invalidate_all(); } void assign(std::initializer_list<_Tp> __il) { _Base::assign(__il); this->_M_invalidate_all(); } using _Base::get_allocator; // iterators: iterator before_begin() noexcept { return iterator(_Base::before_begin(), this); } const_iterator before_begin() const noexcept { return const_iterator(_Base::before_begin(), this); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::cbegin(), this); } const_iterator cbefore_begin() const noexcept { return const_iterator(_Base::cbefore_begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::cend(), this); } using _Base::empty; using _Base::max_size; // element access: reference front() { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const { __glibcxx_check_nonempty(); return _Base::front(); } // modifiers: using _Base::emplace_front; using _Base::push_front; void pop_front() { __glibcxx_check_nonempty(); this->_M_invalidate_if([this](_Base_const_iterator __it) { return __it == this->_M_base().cbegin(); }); _Base::pop_front(); } template iterator emplace_after(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert_after(__pos); return iterator(_Base::emplace_after(__pos.base(), std::forward<_Args>(__args)...), this); } iterator insert_after(const_iterator __pos, const _Tp& __val) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), __val), this); } iterator insert_after(const_iterator __pos, _Tp&& __val) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), std::move(__val)), this); } iterator insert_after(const_iterator __pos, size_type __n, const _Tp& __val) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), __n, __val), this); } template> iterator insert_after(const_iterator __pos, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range_after(__pos, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) return { _Base::insert_after(__pos.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)), this }; else return { _Base::insert_after(__pos.base(), __first, __last), this }; } iterator insert_after(const_iterator __pos, std::initializer_list<_Tp> __il) { __glibcxx_check_insert_after(__pos); return iterator(_Base::insert_after(__pos.base(), __il), this); } private: _Base_iterator _M_erase_after(_Base_const_iterator __pos) { _Base_const_iterator __next = std::next(__pos); this->_M_invalidate_if([__next](_Base_const_iterator __it) { return __it == __next; }); return _Base::erase_after(__pos); } public: iterator erase_after(const_iterator __pos) { __glibcxx_check_erase_after(__pos); return iterator(_M_erase_after(__pos.base()), this); } iterator erase_after(const_iterator __pos, const_iterator __last) { __glibcxx_check_erase_range_after(__pos, __last); for (_Base_const_iterator __victim = std::next(__pos.base()); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(*this, "this") ._M_iterator(__pos, "pos") ._M_iterator(__last, "last")); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); } return iterator(_Base::erase_after(__pos.base(), __last.base()), this); } void swap(forward_list& __list) noexcept( noexcept(declval<_Base&>().swap(__list)) ) { _Safe::_M_swap(__list); _Base::swap(__list); } void resize(size_type __sz) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin+__sz, end() _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); } __try { _Base::resize(__sz); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } void resize(size_type __sz, const value_type& __val) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin+__sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); } __try { _Base::resize(__sz, __val); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } // 23.2.3.5 forward_list operations: void splice_after(const_iterator __pos, forward_list&& __list) { __glibcxx_check_insert_after(__pos); _GLIBCXX_DEBUG_VERIFY(std::__addressof(__list) != this, _M_message(__gnu_debug::__msg_self_splice) ._M_sequence(*this, "this")); _GLIBCXX_DEBUG_VERIFY(__list.get_allocator() == this->get_allocator(), _M_message(__gnu_debug::__msg_splice_alloc) ._M_sequence(*this) ._M_sequence(__list, "__list")); this->_M_transfer_from_if(__list, [&__list](_Base_const_iterator __it) { return __it != __list._M_base().cbefore_begin() && __it != __list._M_base().end(); }); _Base::splice_after(__pos.base(), std::move(__list._M_base())); } void splice_after(const_iterator __pos, forward_list& __list) { splice_after(__pos, std::move(__list)); } void splice_after(const_iterator __pos, forward_list&& __list, const_iterator __i) { __glibcxx_check_insert_after(__pos); _GLIBCXX_DEBUG_VERIFY(__i._M_before_dereferenceable(), _M_message(__gnu_debug::__msg_splice_bad) ._M_iterator(__i, "__i")); _GLIBCXX_DEBUG_VERIFY(__i._M_attached_to(std::__addressof(__list)), _M_message(__gnu_debug::__msg_splice_other) ._M_iterator(__i, "__i") ._M_sequence(__list, "__list")); _GLIBCXX_DEBUG_VERIFY(__list.get_allocator() == this->get_allocator(), _M_message(__gnu_debug::__msg_splice_alloc) ._M_sequence(*this) ._M_sequence(__list, "__list")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators _Base_const_iterator __next = std::next(__i.base()); this->_M_transfer_from_if(__list, [__next](_Base_const_iterator __it) { return __it == __next; }); _Base::splice_after(__pos.base(), std::move(__list._M_base()), __i.base()); } void splice_after(const_iterator __pos, forward_list& __list, const_iterator __i) { splice_after(__pos, std::move(__list), __i); } void splice_after(const_iterator __pos, forward_list&& __list, const_iterator __before, const_iterator __last) { typename __gnu_debug::_Distance_traits::__type __dist; auto __listptr = std::__addressof(__list); __glibcxx_check_insert_after(__pos); __glibcxx_check_valid_fl_range(__before, __last, __dist); _GLIBCXX_DEBUG_VERIFY(__before._M_attached_to(__listptr), _M_message(__gnu_debug::__msg_splice_other) ._M_sequence(__list, "list") ._M_iterator(__before, "before")); _GLIBCXX_DEBUG_VERIFY(__before._M_dereferenceable() || __before._M_is_before_begin(), _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(__list, "list") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(__before != __last, _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(__list, "list") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(__list.get_allocator() == this->get_allocator(), _M_message(__gnu_debug::__msg_splice_alloc) ._M_sequence(*this) ._M_sequence(__list, "__list")); for (_Base_const_iterator __tmp = std::next(__before.base()); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != __list._M_base().end(), _M_message(__gnu_debug::__msg_valid_range2) ._M_sequence(__list, "list") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(__listptr != this || __tmp != __pos.base(), _M_message(__gnu_debug::__msg_splice_overlap) ._M_iterator(__tmp, "position") ._M_iterator(__before, "before") ._M_iterator(__last, "last")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators this->_M_transfer_from_if(__list, [__tmp](_Base_const_iterator __it) { return __it == __tmp; }); } _Base::splice_after(__pos.base(), std::move(__list._M_base()), __before.base(), __last.base()); } void splice_after(const_iterator __pos, forward_list& __list, const_iterator __before, const_iterator __last) { splice_after(__pos, std::move(__list), __before, __last); } void remove(const _Tp& __val) { _Base_iterator __x = _Base::before_begin(); _Base_iterator __old = __x++; while (__x != _Base::end()) { if (*__x == __val) __x = _M_erase_after(__old); else __old = __x++; } } template void remove_if(_Pred __pred) { _Base_iterator __x = _Base::before_begin(); _Base_iterator __old = __x++; while (__x != _Base::end()) { if (__pred(*__x)) __x = _M_erase_after(__old); else __old = __x++; } } void unique() { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = std::next(__first); while (__next != __last) { if (*__first == *__next) __next = _M_erase_after(__first); else __first = __next++; } } template void unique(_BinPred __binary_pred) { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = std::next(__first); while (__next != __last) { if (__binary_pred(*__first, *__next)) __next = _M_erase_after(__first); else __first = __next++; } } void merge(forward_list&& __list) { if (this != std::__addressof(__list)) { __glibcxx_check_sorted(_Base::begin(), _Base::end()); __glibcxx_check_sorted(__list._M_base().begin(), __list._M_base().end()); this->_M_transfer_from_if(__list, [&__list](_Base_const_iterator __it) { return __it != __list._M_base().cbefore_begin() && __it != __list._M_base().cend(); }); _Base::merge(std::move(__list._M_base())); } } void merge(forward_list& __list) { merge(std::move(__list)); } template void merge(forward_list&& __list, _Comp __comp) { if (this != std::__addressof(__list)) { __glibcxx_check_sorted_pred(_Base::begin(), _Base::end(), __comp); __glibcxx_check_sorted_pred(__list._M_base().begin(), __list._M_base().end(), __comp); this->_M_transfer_from_if(__list, [&__list](_Base_const_iterator __it) { return __it != __list._M_base().cbefore_begin() && __it != __list._M_base().cend(); }); _Base::merge(std::move(__list._M_base()), __comp); } } template void merge(forward_list& __list, _Comp __comp) { merge(std::move(__list), __comp); } using _Base::sort; using _Base::reverse; _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> forward_list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> forward_list<_ValT, _Allocator>; #endif template bool operator==(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return __lx._M_base() == __ly._M_base(); } template inline bool operator<(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return __lx._M_base() < __ly._M_base(); } template inline bool operator!=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx == __ly); } /// Based on operator< template inline bool operator>(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return (__ly < __lx); } /// Based on operator< template inline bool operator>=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__lx < __ly); } /// Based on operator< template inline bool operator<=(const forward_list<_Tp, _Alloc>& __lx, const forward_list<_Tp, _Alloc>& __ly) { return !(__ly < __lx); } /// See std::forward_list::swap(). template inline void swap(forward_list<_Tp, _Alloc>& __lx, forward_list<_Tp, _Alloc>& __ly) noexcept(noexcept(__lx.swap(__ly))) { __lx.swap(__ly); } } // namespace __debug } // namespace std namespace __gnu_debug { template struct _BeforeBeginHelper > { typedef std::__debug::forward_list<_Tp, _Alloc> _Sequence; template static bool _S_Is(const _Safe_iterator<_Iterator, _Sequence>& __it) { return __it.base() == __it._M_get_sequence()->_M_base().before_begin(); } template static bool _S_Is_Beginnest(const _Safe_iterator<_Iterator, _Sequence>& __it) { return _S_Is(__it); } }; template struct _Sequence_traits > { typedef typename std::__debug::forward_list<_Tp, _Alloc>::iterator _It; static typename _Distance_traits<_It>::__type _S_size(const std::__debug::forward_list<_Tp, _Alloc>& __seq) { return __seq.empty() ? std::make_pair(0, __dp_exact) : std::make_pair(1, __dp_equality); } }; #ifndef _GLIBCXX_DEBUG_PEDANTIC template struct _Insert_range_from_self_is_safe< std::__debug::forward_list<_Tp, _Alloc> > { enum { __value = 1 }; }; #endif } #endif c++/8/debug/assertions.h000064400000004553151027430570010727 0ustar00// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/assertions.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_ASSERTIONS_H #define _GLIBCXX_DEBUG_ASSERTIONS_H 1 #ifndef _GLIBCXX_DEBUG # define _GLIBCXX_DEBUG_ASSERT(_Condition) # define _GLIBCXX_DEBUG_PEDASSERT(_Condition) # define _GLIBCXX_DEBUG_ONLY(_Statement) #endif #ifndef _GLIBCXX_ASSERTIONS # define __glibcxx_requires_non_empty_range(_First,_Last) # define __glibcxx_requires_nonempty() # define __glibcxx_requires_subscript(_N) #else // Verify that [_First, _Last) forms a non-empty iterator range. # define __glibcxx_requires_non_empty_range(_First,_Last) \ __glibcxx_assert(__builtin_expect(_First != _Last, true)) # define __glibcxx_requires_subscript(_N) \ __glibcxx_assert(__builtin_expect(_N < this->size(), true)) // Verify that the container is nonempty # define __glibcxx_requires_nonempty() \ __glibcxx_assert(__builtin_expect(!this->empty(), true)) #endif #ifdef _GLIBCXX_DEBUG # define _GLIBCXX_DEBUG_ASSERT(_Condition) __glibcxx_assert(_Condition) # ifdef _GLIBCXX_DEBUG_PEDANTIC # define _GLIBCXX_DEBUG_PEDASSERT(_Condition) _GLIBCXX_DEBUG_ASSERT(_Condition) # else # define _GLIBCXX_DEBUG_PEDASSERT(_Condition) # endif # define _GLIBCXX_DEBUG_ONLY(_Statement) _Statement #endif #endif // _GLIBCXX_DEBUG_ASSERTIONS c++/8/debug/formatter.h000064400000033705151027430570010541 0ustar00// Debug-mode error formatting implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/formatter.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_FORMATTER_H #define _GLIBCXX_DEBUG_FORMATTER_H 1 #include #include #if __cpp_rtti # include # define _GLIBCXX_TYPEID(_Type) &typeid(_Type) #else namespace std { class type_info; } # define _GLIBCXX_TYPEID(_Type) 0 #endif namespace __gnu_debug { using std::type_info; template bool __check_singular(const _Iterator&); class _Safe_sequence_base; template class _Safe_iterator; template class _Safe_local_iterator; template class _Safe_sequence; enum _Debug_msg_id { // General checks __msg_valid_range, __msg_insert_singular, __msg_insert_different, __msg_erase_bad, __msg_erase_different, __msg_subscript_oob, __msg_empty, __msg_unpartitioned, __msg_unpartitioned_pred, __msg_unsorted, __msg_unsorted_pred, __msg_not_heap, __msg_not_heap_pred, // std::bitset checks __msg_bad_bitset_write, __msg_bad_bitset_read, __msg_bad_bitset_flip, // std::list checks __msg_self_splice, __msg_splice_alloc, __msg_splice_bad, __msg_splice_other, __msg_splice_overlap, // iterator checks __msg_init_singular, __msg_init_copy_singular, __msg_init_const_singular, __msg_copy_singular, __msg_bad_deref, __msg_bad_inc, __msg_bad_dec, __msg_iter_subscript_oob, __msg_advance_oob, __msg_retreat_oob, __msg_iter_compare_bad, __msg_compare_different, __msg_iter_order_bad, __msg_order_different, __msg_distance_bad, __msg_distance_different, // istream_iterator __msg_deref_istream, __msg_inc_istream, // ostream_iterator __msg_output_ostream, // istreambuf_iterator __msg_deref_istreambuf, __msg_inc_istreambuf, // forward_list __msg_insert_after_end, __msg_erase_after_bad, __msg_valid_range2, // unordered container local iterators __msg_local_iter_compare_bad, __msg_non_empty_range, // self move assign __msg_self_move_assign, // unordered container buckets __msg_bucket_index_oob, __msg_valid_load_factor, // others __msg_equal_allocs, __msg_insert_range_from_self, __msg_irreflexive_ordering }; class _Error_formatter { // Tags denoting the type of parameter for construction struct _Is_iterator { }; struct _Is_iterator_value_type { }; struct _Is_sequence { }; struct _Is_instance { }; public: /// Whether an iterator is constant, mutable, or unknown enum _Constness { __unknown_constness, __const_iterator, __mutable_iterator, __last_constness }; // The state of the iterator (fine-grained), if we know it. enum _Iterator_state { __unknown_state, __singular, // singular, may still be attached to a sequence __begin, // dereferenceable, and at the beginning __middle, // dereferenceable, not at the beginning __end, // past-the-end, may be at beginning if sequence empty __before_begin, // before begin __last_state }; // A parameter that may be referenced by an error message struct _Parameter { enum { __unused_param, __iterator, __sequence, __integer, __string, __instance, __iterator_value_type } _M_kind; struct _Type { const char* _M_name; const type_info* _M_type; }; struct _Instance : _Type { const void* _M_address; }; union { // When _M_kind == __iterator struct : _Instance { _Constness _M_constness; _Iterator_state _M_state; const void* _M_sequence; const type_info* _M_seq_type; } _M_iterator; // When _M_kind == __sequence _Instance _M_sequence; // When _M_kind == __integer struct { const char* _M_name; long _M_value; } _M_integer; // When _M_kind == __string struct { const char* _M_name; const char* _M_value; } _M_string; // When _M_kind == __instance _Instance _M_instance; // When _M_kind == __iterator_value_type _Type _M_iterator_value_type; } _M_variant; _Parameter() : _M_kind(__unused_param), _M_variant() { } _Parameter(long __value, const char* __name) : _M_kind(__integer), _M_variant() { _M_variant._M_integer._M_name = __name; _M_variant._M_integer._M_value = __value; } _Parameter(const char* __value, const char* __name) : _M_kind(__string), _M_variant() { _M_variant._M_string._M_name = __name; _M_variant._M_string._M_value = __value; } template _Parameter(_Safe_iterator<_Iterator, _Sequence> const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = std::__are_same<_Safe_iterator<_Iterator, _Sequence>, typename _Sequence::iterator>:: __value ? __mutable_iterator : __const_iterator; _M_variant._M_iterator._M_sequence = __it._M_get_sequence(); _M_variant._M_iterator._M_seq_type = _GLIBCXX_TYPEID(_Sequence); if (__it._M_singular()) _M_variant._M_iterator._M_state = __singular; else { if (__it._M_is_before_begin()) _M_variant._M_iterator._M_state = __before_begin; else if (__it._M_is_end()) _M_variant._M_iterator._M_state = __end; else if (__it._M_is_begin()) _M_variant._M_iterator._M_state = __begin; else _M_variant._M_iterator._M_state = __middle; } } template _Parameter(_Safe_local_iterator<_Iterator, _Sequence> const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = std::__are_same<_Safe_local_iterator<_Iterator, _Sequence>, typename _Sequence::local_iterator>:: __value ? __mutable_iterator : __const_iterator; _M_variant._M_iterator._M_sequence = __it._M_get_sequence(); _M_variant._M_iterator._M_seq_type = _GLIBCXX_TYPEID(_Sequence); if (__it._M_singular()) _M_variant._M_iterator._M_state = __singular; else { if (__it._M_is_end()) _M_variant._M_iterator._M_state = __end; else if (__it._M_is_begin()) _M_variant._M_iterator._M_state = __begin; else _M_variant._M_iterator._M_state = __middle; } } template _Parameter(const _Type* const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = __const_iterator; _M_variant._M_iterator._M_state = __it ? __unknown_state : __singular; _M_variant._M_iterator._M_sequence = 0; _M_variant._M_iterator._M_seq_type = 0; } template _Parameter(_Type* const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = __mutable_iterator; _M_variant._M_iterator._M_state = __it ? __unknown_state : __singular; _M_variant._M_iterator._M_sequence = 0; _M_variant._M_iterator._M_seq_type = 0; } template _Parameter(_Iterator const& __it, const char* __name, _Is_iterator) : _M_kind(__iterator), _M_variant() { _M_variant._M_iterator._M_name = __name; _M_variant._M_iterator._M_address = std::__addressof(__it); _M_variant._M_iterator._M_type = _GLIBCXX_TYPEID(__it); _M_variant._M_iterator._M_constness = __unknown_constness; _M_variant._M_iterator._M_state = __gnu_debug::__check_singular(__it) ? __singular : __unknown_state; _M_variant._M_iterator._M_sequence = 0; _M_variant._M_iterator._M_seq_type = 0; } template _Parameter(const _Safe_sequence<_Sequence>& __seq, const char* __name, _Is_sequence) : _M_kind(__sequence), _M_variant() { _M_variant._M_sequence._M_name = __name; _M_variant._M_sequence._M_address = static_cast(std::__addressof(__seq)); _M_variant._M_sequence._M_type = _GLIBCXX_TYPEID(_Sequence); } template _Parameter(const _Sequence& __seq, const char* __name, _Is_sequence) : _M_kind(__sequence), _M_variant() { _M_variant._M_sequence._M_name = __name; _M_variant._M_sequence._M_address = std::__addressof(__seq); _M_variant._M_sequence._M_type = _GLIBCXX_TYPEID(_Sequence); } template _Parameter(const _Iterator& __it, const char* __name, _Is_iterator_value_type) : _M_kind(__iterator_value_type), _M_variant() { _M_variant._M_iterator_value_type._M_name = __name; _M_variant._M_iterator_value_type._M_type = _GLIBCXX_TYPEID(typename std::iterator_traits<_Iterator>::value_type); } template _Parameter(const _Type& __inst, const char* __name, _Is_instance) : _M_kind(__instance), _M_variant() { _M_variant._M_instance._M_name = __name; _M_variant._M_instance._M_address = &__inst; _M_variant._M_instance._M_type = _GLIBCXX_TYPEID(_Type); } #if !_GLIBCXX_INLINE_VERSION void _M_print_field(const _Error_formatter* __formatter, const char* __name) const _GLIBCXX_DEPRECATED; void _M_print_description(const _Error_formatter* __formatter) const _GLIBCXX_DEPRECATED; #endif }; template _Error_formatter& _M_iterator(const _Iterator& __it, const char* __name = 0) { if (_M_num_parameters < std::size_t(__max_parameters)) _M_parameters[_M_num_parameters++] = _Parameter(__it, __name, _Is_iterator()); return *this; } template _Error_formatter& _M_iterator_value_type(const _Iterator& __it, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__it, __name, _Is_iterator_value_type()); return *this; } _Error_formatter& _M_integer(long __value, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__value, __name); return *this; } _Error_formatter& _M_string(const char* __value, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__value, __name); return *this; } template _Error_formatter& _M_sequence(const _Sequence& __seq, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__seq, __name, _Is_sequence()); return *this; } template _Error_formatter& _M_instance(const _Type& __inst, const char* __name = 0) { if (_M_num_parameters < __max_parameters) _M_parameters[_M_num_parameters++] = _Parameter(__inst, __name, _Is_instance()); return *this; } _Error_formatter& _M_message(const char* __text) { _M_text = __text; return *this; } // Kept const qualifier for backward compatibility, to keep the same // exported symbol. _Error_formatter& _M_message(_Debug_msg_id __id) const throw (); _GLIBCXX_NORETURN void _M_error() const; #if !_GLIBCXX_INLINE_VERSION template void _M_format_word(char*, int, const char*, _Tp) const throw () _GLIBCXX_DEPRECATED; void _M_print_word(const char* __word) const _GLIBCXX_DEPRECATED; void _M_print_string(const char* __string) const _GLIBCXX_DEPRECATED; #endif private: _Error_formatter(const char* __file, unsigned int __line) : _M_file(__file), _M_line(__line), _M_num_parameters(0), _M_text(0) { } #if !_GLIBCXX_INLINE_VERSION void _M_get_max_length() const throw () _GLIBCXX_DEPRECATED; #endif enum { __max_parameters = 9 }; const char* _M_file; unsigned int _M_line; _Parameter _M_parameters[__max_parameters]; unsigned int _M_num_parameters; const char* _M_text; public: static _Error_formatter& _M_at(const char* __file, unsigned int __line) { static _Error_formatter __formatter(__file, __line); return __formatter; } }; } // namespace __gnu_debug #undef _GLIBCXX_TYPEID #endif c++/8/debug/multimap.h000064400000046403151027430570010365 0ustar00// Debugging multimap implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/multimap.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MULTIMAP_H #define _GLIBCXX_DEBUG_MULTIMAP_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::multimap with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator > > class multimap : public __gnu_debug::_Safe_container< multimap<_Key, _Tp, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::multimap<_Key, _Tp, _Compare, _Allocator> { typedef _GLIBCXX_STD_C::multimap< _Key, _Tp, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< multimap, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, multimap> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, multimap> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.1.1 construct/copy/destroy: #if __cplusplus < 201103L multimap() : _Base() { } multimap(const multimap& __x) : _Base(__x) { } ~multimap() { } #else multimap() = default; multimap(const multimap&) = default; multimap(multimap&&) = default; multimap(initializer_list __l, const _Compare& __c = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __c, __a) { } explicit multimap(const allocator_type& __a) : _Base(__a) { } multimap(const multimap& __m, const allocator_type& __a) : _Base(__m, __a) { } multimap(multimap&& __m, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__m._M_base()), __a)) ) : _Safe(std::move(__m._M_safe()), __a), _Base(std::move(__m._M_base()), __a) { } multimap(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template multimap(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~multimap() = default; #endif explicit multimap(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template multimap(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } multimap(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L multimap& operator=(const multimap& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else multimap& operator=(const multimap&) = default; multimap& operator=(multimap&&) = default; multimap& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // modifiers: #if __cplusplus >= 201103L template iterator emplace(_Args&&... __args) { return iterator(_Base::emplace(std::forward<_Args>(__args)...), this); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif iterator insert(const value_type& __x) { return iterator(_Base::insert(__x), this); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(value_type&& __x) { return { _Base::insert(std::move(__x)), this }; } template::value>::type> iterator insert(_Pair&& __x) { return iterator(_Base::insert(std::forward<_Pair>(__x)), this); } #endif #if __cplusplus >= 201103L void insert(std::initializer_list __list) { _Base::insert(__list); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return { _Base::insert(__position.base(), std::move(__x)), this }; } template::value>::type> iterator insert(const_iterator __position, _Pair&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::forward<_Pair>(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } iterator erase(iterator __position) { return erase(const_iterator(__position)); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __victims = _Base::equal_range(__x); size_type __count = 0; _Base_iterator __victim = __victims.first; while (__victim != __victims.second) { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim++); ++__count; } return __count; } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(multimap& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // 23.3.1.3 multimap operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } #endif const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } #endif const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } #endif const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> multimap(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> multimap<_Key, _Tp, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multimap(_InputIterator, _InputIterator, _Allocator) -> multimap<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> multimap(initializer_list>, _Allocator) -> multimap<_Key, _Tp, less<_Key>, _Allocator>; #endif template inline bool operator==(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, const multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(multimap<_Key, _Tp, _Compare, _Allocator>& __lhs, multimap<_Key, _Tp, _Compare, _Allocator>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std #endif c++/8/debug/set.h000064400000044427151027430570007334 0ustar00// Debugging set implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/set.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SET_H #define _GLIBCXX_DEBUG_SET_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::set with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator<_Key> > class set : public __gnu_debug::_Safe_container< set<_Key, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::set<_Key,_Compare,_Allocator> { typedef _GLIBCXX_STD_C::set<_Key, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< set, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, set> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, set> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.3.1 construct/copy/destroy: #if __cplusplus < 201103L set() : _Base() { } set(const set& __x) : _Base(__x) { } ~set() { } #else set() = default; set(const set&) = default; set(set&&) = default; set(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __comp, __a) { } explicit set(const allocator_type& __a) : _Base(__a) { } set(const set& __x, const allocator_type& __a) : _Base(__x, __a) { } set(set&& __x, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__x._M_base()), __a)) ) : _Safe(std::move(__x._M_safe()), __a), _Base(std::move(__x._M_base()), __a) { } set(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template set(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~set() = default; #endif explicit set(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template set(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } set(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L set& operator=(const set& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else set& operator=(const set&) = default; set& operator=(set&&) = default; set& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // modifiers: #if __cplusplus >= 201103L template std::pair emplace(_Args&&... __args) { auto __res = _Base::emplace(std::forward<_Args>(__args)...); return std::pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif std::pair insert(const value_type& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(__x); return std::pair(iterator(__res.first, this), __res.second); } #if __cplusplus >= 201103L std::pair insert(value_type&& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(std::move(__x)); return std::pair(iterator(__res.first, this), __res.second); } #endif iterator insert(const_iterator __position, const value_type& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::move(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus >= 201103L void insert(initializer_list __l) { _Base::insert(__l); } #endif #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { _Base_iterator __victim = _Base::find(__x); if (__victim == _Base::end()) return 0; else { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim); return 1; } } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(set& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // set operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> set::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> set(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> set<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> set(_InputIterator, _InputIterator, _Allocator) -> set::value_type, less::value_type>, _Allocator>; template> set(initializer_list<_Key>, _Allocator) -> set<_Key, less<_Key>, _Allocator>; #endif template inline bool operator==(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const set<_Key, _Compare, _Allocator>& __lhs, const set<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template void swap(set<_Key, _Compare, _Allocator>& __x, set<_Key, _Compare, _Allocator>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { return __x.swap(__y); } } // namespace __debug } // namespace std #endif c++/8/debug/string000064400000101565151027430570007616 0ustar00// Debugging string implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/string * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_STRING #define _GLIBCXX_DEBUG_STRING 1 #pragma GCC system_header #include #include #include #include namespace __gnu_debug { /// Class std::basic_string with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator<_CharT> > class basic_string : public __gnu_debug::_Safe_container< basic_string<_CharT, _Traits, _Allocator>, _Allocator, _Safe_sequence, bool(_GLIBCXX_USE_CXX11_ABI)>, public std::basic_string<_CharT, _Traits, _Allocator> { typedef std::basic_string<_CharT, _Traits, _Allocator> _Base; typedef __gnu_debug::_Safe_container< basic_string, _Allocator, _Safe_sequence, bool(_GLIBCXX_USE_CXX11_ABI)> _Safe; public: // types: typedef _Traits traits_type; typedef typename _Traits::char_type value_type; typedef _Allocator allocator_type; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef __gnu_debug::_Safe_iterator< typename _Base::iterator, basic_string> iterator; typedef __gnu_debug::_Safe_iterator< typename _Base::const_iterator, basic_string> const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; using _Base::npos; basic_string() _GLIBCXX_NOEXCEPT_IF(std::is_nothrow_default_constructible<_Base>::value) : _Base() { } // 21.3.1 construct/copy/destroy: explicit basic_string(const _Allocator& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus < 201103L basic_string(const basic_string& __str) : _Base(__str) { } ~basic_string() { } #else basic_string(const basic_string&) = default; basic_string(basic_string&&) = default; basic_string(std::initializer_list<_CharT> __l, const _Allocator& __a = _Allocator()) : _Base(__l, __a) { } #if _GLIBCXX_USE_CXX11_ABI basic_string(const basic_string& __s, const _Allocator& __a) : _Base(__s, __a) { } basic_string(basic_string&& __s, const _Allocator& __a) : _Base(std::move(__s), __a) { } #endif ~basic_string() = default; // Provides conversion from a normal-mode string to a debug-mode string basic_string(_Base&& __base) noexcept : _Base(std::move(__base)) { } #endif // C++11 // Provides conversion from a normal-mode string to a debug-mode string basic_string(const _Base& __base) : _Base(__base) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 42. string ctors specify wrong default allocator basic_string(const basic_string& __str, size_type __pos, size_type __n = _Base::npos, const _Allocator& __a = _Allocator()) : _Base(__str, __pos, __n, __a) { } basic_string(const _CharT* __s, size_type __n, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__check_string(__s, __n), __n, __a) { } basic_string(const _CharT* __s, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__check_string(__s), __a) { this->assign(__s); } basic_string(size_type __n, _CharT __c, const _Allocator& __a = _Allocator()) : _Base(__n, __c, __a) { } template basic_string(_InputIterator __begin, _InputIterator __end, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__begin, __end)), __gnu_debug::__base(__end), __a) { } #if __cplusplus < 201103L basic_string& operator=(const basic_string& __str) { this->_M_safe() = __str; _M_base() = __str; return *this; } #else basic_string& operator=(const basic_string&) = default; basic_string& operator=(basic_string&&) = default; #endif basic_string& operator=(const _CharT* __s) { __glibcxx_check_string(__s); _M_base() = __s; this->_M_invalidate_all(); return *this; } basic_string& operator=(_CharT __c) { _M_base() = __c; this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& operator=(std::initializer_list<_CharT> __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif // C++11 // 21.3.2 iterators: iterator begin() // _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() // _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() // _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() // _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // 21.3.3 capacity: using _Base::size; using _Base::length; using _Base::max_size; void resize(size_type __n, _CharT __c) { _Base::resize(__n, __c); this->_M_invalidate_all(); } void resize(size_type __n) { this->resize(__n, _CharT()); } #if __cplusplus >= 201103L void shrink_to_fit() noexcept { if (capacity() > size()) { __try { reserve(0); this->_M_invalidate_all(); } __catch(...) { } } } #endif using _Base::capacity; using _Base::reserve; void clear() // _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } using _Base::empty; // 21.3.4 element access: const_reference operator[](size_type __pos) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(__pos <= this->size(), _M_message(__gnu_debug::__msg_subscript_oob) ._M_sequence(*this, "this") ._M_integer(__pos, "__pos") ._M_integer(this->size(), "size")); return _M_base()[__pos]; } reference operator[](size_type __pos) // _GLIBCXX_NOEXCEPT { #if __cplusplus < 201103L && defined(_GLIBCXX_DEBUG_PEDANTIC) __glibcxx_check_subscript(__pos); #else // as an extension v3 allows s[s.size()] when s is non-const. _GLIBCXX_DEBUG_VERIFY(__pos <= this->size(), _M_message(__gnu_debug::__msg_subscript_oob) ._M_sequence(*this, "this") ._M_integer(__pos, "__pos") ._M_integer(this->size(), "size")); #endif return _M_base()[__pos]; } using _Base::at; #if __cplusplus >= 201103L using _Base::front; using _Base::back; #endif // 21.3.5 modifiers: basic_string& operator+=(const basic_string& __str) { _M_base() += __str; this->_M_invalidate_all(); return *this; } basic_string& operator+=(const _CharT* __s) { __glibcxx_check_string(__s); _M_base() += __s; this->_M_invalidate_all(); return *this; } basic_string& operator+=(_CharT __c) { _M_base() += __c; this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& operator+=(std::initializer_list<_CharT> __l) { _M_base() += __l; this->_M_invalidate_all(); return *this; } #endif // C++11 basic_string& append(const basic_string& __str) { _Base::append(__str); this->_M_invalidate_all(); return *this; } basic_string& append(const basic_string& __str, size_type __pos, size_type __n) { _Base::append(__str, __pos, __n); this->_M_invalidate_all(); return *this; } basic_string& append(const _CharT* __s, size_type __n) { __glibcxx_check_string_len(__s, __n); _Base::append(__s, __n); this->_M_invalidate_all(); return *this; } basic_string& append(const _CharT* __s) { __glibcxx_check_string(__s); _Base::append(__s); this->_M_invalidate_all(); return *this; } basic_string& append(size_type __n, _CharT __c) { _Base::append(__n, __c); this->_M_invalidate_all(); return *this; } template basic_string& append(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __dp_sign) _Base::append(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::append(__first, __last); this->_M_invalidate_all(); return *this; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 7. string clause minor problems void push_back(_CharT __c) { _Base::push_back(__c); this->_M_invalidate_all(); } basic_string& assign(const basic_string& __x) { _Base::assign(__x); this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& assign(basic_string&& __x) noexcept(noexcept(std::declval<_Base&>().assign(std::move(__x)))) { _Base::assign(std::move(__x)); this->_M_invalidate_all(); return *this; } #endif // C++11 basic_string& assign(const basic_string& __str, size_type __pos, size_type __n) { _Base::assign(__str, __pos, __n); this->_M_invalidate_all(); return *this; } basic_string& assign(const _CharT* __s, size_type __n) { __glibcxx_check_string_len(__s, __n); _Base::assign(__s, __n); this->_M_invalidate_all(); return *this; } basic_string& assign(const _CharT* __s) { __glibcxx_check_string(__s); _Base::assign(__s); this->_M_invalidate_all(); return *this; } basic_string& assign(size_type __n, _CharT __c) { _Base::assign(__n, __c); this->_M_invalidate_all(); return *this; } template basic_string& assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& assign(std::initializer_list<_CharT> __l) { _Base::assign(__l); this->_M_invalidate_all(); return *this; } #endif // C++11 basic_string& insert(size_type __pos1, const basic_string& __str) { _Base::insert(__pos1, __str); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos1, const basic_string& __str, size_type __pos2, size_type __n) { _Base::insert(__pos1, __str, __pos2, __n); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos, const _CharT* __s, size_type __n) { __glibcxx_check_string(__s); _Base::insert(__pos, __s, __n); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos, const _CharT* __s) { __glibcxx_check_string(__s); _Base::insert(__pos, __s); this->_M_invalidate_all(); return *this; } basic_string& insert(size_type __pos, size_type __n, _CharT __c) { _Base::insert(__pos, __n, __c); this->_M_invalidate_all(); return *this; } iterator insert(iterator __p, _CharT __c) { __glibcxx_check_insert(__p); typename _Base::iterator __res = _Base::insert(__p.base(), __c); this->_M_invalidate_all(); return iterator(__res, this); } void insert(iterator __p, size_type __n, _CharT __c) { __glibcxx_check_insert(__p); _Base::insert(__p.base(), __n, __c); this->_M_invalidate_all(); } template void insert(iterator __p, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__p, __first, __last, __dist); if (__dist.second >= __dp_sign) _Base::insert(__p.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__p.base(), __first, __last); this->_M_invalidate_all(); } #if __cplusplus >= 201103L void insert(iterator __p, std::initializer_list<_CharT> __l) { __glibcxx_check_insert(__p); _Base::insert(__p.base(), __l); this->_M_invalidate_all(); } #endif // C++11 basic_string& erase(size_type __pos = 0, size_type __n = _Base::npos) { _Base::erase(__pos, __n); this->_M_invalidate_all(); return *this; } iterator erase(iterator __position) { __glibcxx_check_erase(__position); typename _Base::iterator __res = _Base::erase(__position.base()); this->_M_invalidate_all(); return iterator(__res, this); } iterator erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); typename _Base::iterator __res = _Base::erase(__first.base(), __last.base()); this->_M_invalidate_all(); return iterator(__res, this); } #if __cplusplus >= 201103L void pop_back() // noexcept { __glibcxx_check_nonempty(); _Base::pop_back(); this->_M_invalidate_all(); } #endif // C++11 basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str) { _Base::replace(__pos1, __n1, __str); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2) { _Base::replace(__pos1, __n1, __str, __pos2, __n2); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) { __glibcxx_check_string_len(__s, __n2); _Base::replace(__pos, __n1, __s, __n2); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos, size_type __n1, const _CharT* __s) { __glibcxx_check_string(__s); _Base::replace(__pos, __n1, __s); this->_M_invalidate_all(); return *this; } basic_string& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) { _Base::replace(__pos, __n1, __n2, __c); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, const basic_string& __str) { __glibcxx_check_erase_range(__i1, __i2); _Base::replace(__i1.base(), __i2.base(), __str); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s, size_type __n) { __glibcxx_check_erase_range(__i1, __i2); __glibcxx_check_string_len(__s, __n); _Base::replace(__i1.base(), __i2.base(), __s, __n); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, const _CharT* __s) { __glibcxx_check_erase_range(__i1, __i2); __glibcxx_check_string(__s); _Base::replace(__i1.base(), __i2.base(), __s); this->_M_invalidate_all(); return *this; } basic_string& replace(iterator __i1, iterator __i2, size_type __n, _CharT __c) { __glibcxx_check_erase_range(__i1, __i2); _Base::replace(__i1.base(), __i2.base(), __n, __c); this->_M_invalidate_all(); return *this; } template basic_string& replace(iterator __i1, iterator __i2, _InputIterator __j1, _InputIterator __j2) { __glibcxx_check_erase_range(__i1, __i2); typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__j1, __j2, __dist); if (__dist.second >= __dp_sign) _Base::replace(__i1.base(), __i2.base(), __gnu_debug::__unsafe(__j1), __gnu_debug::__unsafe(__j2)); else _Base::replace(__i1.base(), __i2.base(), __j1, __j2); this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L basic_string& replace(iterator __i1, iterator __i2, std::initializer_list<_CharT> __l) { __glibcxx_check_erase_range(__i1, __i2); _Base::replace(__i1.base(), __i2.base(), __l); this->_M_invalidate_all(); return *this; } #endif // C++11 size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const { __glibcxx_check_string_len(__s, __n); return _Base::copy(__s, __n, __pos); } void swap(basic_string& __x) _GLIBCXX_NOEXCEPT_IF(std::__is_nothrow_swappable<_Base>::value) { _Safe::_M_swap(__x); _Base::swap(__x); } // 21.3.6 string operations: const _CharT* c_str() const _GLIBCXX_NOEXCEPT { const _CharT* __res = _Base::c_str(); this->_M_invalidate_all(); return __res; } const _CharT* data() const _GLIBCXX_NOEXCEPT { const _CharT* __res = _Base::data(); this->_M_invalidate_all(); return __res; } using _Base::get_allocator; size_type find(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find(__str, __pos); } size_type find(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find(__s, __pos, __n); } size_type find(const _CharT* __s, size_type __pos = 0) const { __glibcxx_check_string(__s); return _Base::find(__s, __pos); } size_type find(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find(__c, __pos); } size_type rfind(const basic_string& __str, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::rfind(__str, __pos); } size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string_len(__s, __n); return _Base::rfind(__s, __pos, __n); } size_type rfind(const _CharT* __s, size_type __pos = _Base::npos) const { __glibcxx_check_string(__s); return _Base::rfind(__s, __pos); } size_type rfind(_CharT __c, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::rfind(__c, __pos); } size_type find_first_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_of(__str, __pos); } size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find_first_of(__s, __pos, __n); } size_type find_first_of(const _CharT* __s, size_type __pos = 0) const { __glibcxx_check_string(__s); return _Base::find_first_of(__s, __pos); } size_type find_first_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_of(__c, __pos); } size_type find_last_of(const basic_string& __str, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_of(__str, __pos); } size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find_last_of(__s, __pos, __n); } size_type find_last_of(const _CharT* __s, size_type __pos = _Base::npos) const { __glibcxx_check_string(__s); return _Base::find_last_of(__s, __pos); } size_type find_last_of(_CharT __c, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_of(__c, __pos); } size_type find_first_not_of(const basic_string& __str, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_not_of(__str, __pos); } size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string_len(__s, __n); return _Base::find_first_not_of(__s, __pos, __n); } size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const { __glibcxx_check_string(__s); return _Base::find_first_not_of(__s, __pos); } size_type find_first_not_of(_CharT __c, size_type __pos = 0) const _GLIBCXX_NOEXCEPT { return _Base::find_first_not_of(__c, __pos); } size_type find_last_not_of(const basic_string& __str, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_not_of(__str, __pos); } size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const { __glibcxx_check_string(__s); return _Base::find_last_not_of(__s, __pos, __n); } size_type find_last_not_of(const _CharT* __s, size_type __pos = _Base::npos) const { __glibcxx_check_string(__s); return _Base::find_last_not_of(__s, __pos); } size_type find_last_not_of(_CharT __c, size_type __pos = _Base::npos) const _GLIBCXX_NOEXCEPT { return _Base::find_last_not_of(__c, __pos); } basic_string substr(size_type __pos = 0, size_type __n = _Base::npos) const { return basic_string(_Base::substr(__pos, __n)); } int compare(const basic_string& __str) const { return _Base::compare(__str); } int compare(size_type __pos1, size_type __n1, const basic_string& __str) const { return _Base::compare(__pos1, __n1, __str); } int compare(size_type __pos1, size_type __n1, const basic_string& __str, size_type __pos2, size_type __n2) const { return _Base::compare(__pos1, __n1, __str, __pos2, __n2); } int compare(const _CharT* __s) const { __glibcxx_check_string(__s); return _Base::compare(__s); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5. string::compare specification questionable int compare(size_type __pos1, size_type __n1, const _CharT* __s) const { __glibcxx_check_string(__s); return _Base::compare(__pos1, __n1, __s); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 5. string::compare specification questionable int compare(size_type __pos1, size_type __n1,const _CharT* __s, size_type __n2) const { __glibcxx_check_string_len(__s, __n2); return _Base::compare(__pos1, __n1, __s, __n2); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } using _Safe::_M_invalidate_all; }; template inline basic_string<_CharT,_Traits,_Allocator> operator+(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(_CharT __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return basic_string<_CharT,_Traits,_Allocator>(1, __lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline basic_string<_CharT,_Traits,_Allocator> operator+(const basic_string<_CharT,_Traits,_Allocator>& __lhs, _CharT __rhs) { return basic_string<_CharT,_Traits,_Allocator>(__lhs) += __rhs; } template inline bool operator==(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator==(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs == __rhs._M_base(); } template inline bool operator==(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() == __rhs; } template inline bool operator!=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator!=(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs != __rhs._M_base(); } template inline bool operator!=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() != __rhs; } template inline bool operator<(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs < __rhs._M_base(); } template inline bool operator<(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() < __rhs; } template inline bool operator<=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator<=(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs <= __rhs._M_base(); } template inline bool operator<=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() <= __rhs; } template inline bool operator>=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>=(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs >= __rhs._M_base(); } template inline bool operator>=(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() >= __rhs; } template inline bool operator>(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline bool operator>(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Allocator>& __rhs) { __glibcxx_check_string(__lhs); return __lhs > __rhs._M_base(); } template inline bool operator>(const basic_string<_CharT,_Traits,_Allocator>& __lhs, const _CharT* __rhs) { __glibcxx_check_string(__rhs); return __lhs._M_base() > __rhs; } // 21.3.7.8: template inline void swap(basic_string<_CharT,_Traits,_Allocator>& __lhs, basic_string<_CharT,_Traits,_Allocator>& __rhs) { __lhs.swap(__rhs); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const basic_string<_CharT, _Traits, _Allocator>& __str) { return __os << __str._M_base(); } template std::basic_istream<_CharT,_Traits>& operator>>(std::basic_istream<_CharT,_Traits>& __is, basic_string<_CharT,_Traits,_Allocator>& __str) { std::basic_istream<_CharT,_Traits>& __res = __is >> __str._M_base(); __str._M_invalidate_all(); return __res; } template std::basic_istream<_CharT,_Traits>& getline(std::basic_istream<_CharT,_Traits>& __is, basic_string<_CharT,_Traits,_Allocator>& __str, _CharT __delim) { std::basic_istream<_CharT,_Traits>& __res = getline(__is, __str._M_base(), __delim); __str._M_invalidate_all(); return __res; } template std::basic_istream<_CharT,_Traits>& getline(std::basic_istream<_CharT,_Traits>& __is, basic_string<_CharT,_Traits,_Allocator>& __str) { std::basic_istream<_CharT,_Traits>& __res = getline(__is, __str._M_base()); __str._M_invalidate_all(); return __res; } typedef basic_string string; #ifdef _GLIBCXX_USE_WCHAR_T typedef basic_string wstring; #endif template struct _Insert_range_from_self_is_safe< __gnu_debug::basic_string<_CharT, _Traits, _Allocator> > { enum { __value = 1 }; }; } // namespace __gnu_debug #endif c++/8/debug/safe_local_iterator.h000064400000037545151027430570012545 0ustar00// Safe iterator implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_local_iterator.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_H #define _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_H 1 #include namespace __gnu_debug { /** \brief Safe iterator wrapper. * * The class template %_Safe_local_iterator is a wrapper around an * iterator that tracks the iterator's movement among sequences and * checks that operations performed on the "safe" iterator are * legal. In additional to the basic iterator operations (which are * validated, and then passed to the underlying iterator), * %_Safe_local_iterator has member functions for iterator invalidation, * attaching/detaching the iterator from sequences, and querying * the iterator's state. */ template class _Safe_local_iterator : private _Iterator , public _Safe_local_iterator_base { typedef _Iterator _Iter_base; typedef _Safe_local_iterator_base _Safe_base; typedef typename _Sequence::const_local_iterator _Const_local_iterator; typedef typename _Sequence::size_type size_type; /// Determine if this is a constant iterator. bool _M_constant() const { return std::__are_same<_Const_local_iterator, _Safe_local_iterator>::__value; } typedef std::iterator_traits<_Iterator> _Traits; struct _Attach_single { }; _Safe_local_iterator(const _Iterator& __i, _Safe_sequence_base* __cont, _Attach_single) noexcept : _Iter_base(__i) { _M_attach_single(__cont); } public: typedef _Iterator iterator_type; typedef typename _Traits::iterator_category iterator_category; typedef typename _Traits::value_type value_type; typedef typename _Traits::difference_type difference_type; typedef typename _Traits::reference reference; typedef typename _Traits::pointer pointer; /// @post the iterator is singular and unattached _Safe_local_iterator() noexcept : _Iter_base() { } /** * @brief Safe iterator construction from an unsafe iterator and * its sequence. * * @pre @p seq is not NULL * @post this is not singular */ _Safe_local_iterator(const _Iterator& __i, const _Safe_sequence_base* __cont) : _Iter_base(__i), _Safe_base(__cont, _M_constant()) { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__msg_init_singular) ._M_iterator(*this, "this")); } /** * @brief Copy construction. */ _Safe_local_iterator(const _Safe_local_iterator& __x) noexcept : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } /** * @brief Move construction. * @post __x is singular and unattached */ _Safe_local_iterator(_Safe_local_iterator&& __x) noexcept : _Iter_base() { _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); auto __cont = __x._M_sequence; __x._M_detach(); std::swap(base(), __x.base()); _M_attach(__cont); } /** * @brief Converting constructor from a mutable iterator to a * constant iterator. */ template _Safe_local_iterator( const _Safe_local_iterator<_MutableIterator, typename __gnu_cxx::__enable_if::__value, _Sequence>::__type>& __x) : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_const_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } /** * @brief Copy assignment. */ _Safe_local_iterator& operator=(const _Safe_local_iterator& __x) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } return *this; } /** * @brief Move assignment. * @post __x is singular and unattached */ _Safe_local_iterator& operator=(_Safe_local_iterator&& __x) noexcept { _GLIBCXX_DEBUG_VERIFY(this != &__x, _M_message(__msg_self_move_assign) ._M_iterator(*this, "this")); _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } __x._M_detach(); __x.base() = _Iterator(); return *this; } /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ reference operator*() const { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return *base(); } /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ pointer operator->() const { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return base().operator->(); } // ------ Input iterator requirements ------ /** * @brief Iterator preincrement * @pre iterator is incrementable */ _Safe_local_iterator& operator++() { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); ++base(); return *this; } /** * @brief Iterator postincrement * @pre iterator is incrementable */ _Safe_local_iterator operator++(int) { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); return _Safe_local_iterator(base()++, this->_M_sequence, _Attach_single()); } // ------ Utilities ------ /** * @brief Return the underlying iterator */ _Iterator& base() noexcept { return *this; } const _Iterator& base() const noexcept { return *this; } /** * @brief Return the bucket */ size_type bucket() const { return base()._M_get_bucket(); } /** * @brief Conversion to underlying non-debug iterator to allow * better interaction with non-debug containers. */ operator _Iterator() const { return *this; } /** Attach iterator to the given sequence. */ void _M_attach(_Safe_sequence_base* __seq) { _Safe_base::_M_attach(__seq, _M_constant()); } /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq) { _Safe_base::_M_attach_single(__seq, _M_constant()); } /// Is the iterator dereferenceable? bool _M_dereferenceable() const { return !this->_M_singular() && !_M_is_end(); } /// Is the iterator incrementable? bool _M_incrementable() const { return !this->_M_singular() && !_M_is_end(); } // Is the iterator range [*this, __rhs) valid? bool _M_valid_range(const _Safe_local_iterator& __rhs, std::pair& __dist_info) const; // The sequence this iterator references. typename __gnu_cxx::__conditional_type::__value, const _Sequence*, _Sequence*>::__type _M_get_sequence() const { return static_cast<_Sequence*>(_M_sequence); } /// Is this iterator equal to the sequence's begin(bucket) iterator? bool _M_is_begin() const { return base() == _M_get_sequence()->_M_base().begin(bucket()); } /// Is this iterator equal to the sequence's end(bucket) iterator? bool _M_is_end() const { return base() == _M_get_sequence()->_M_base().end(bucket()); } /// Is this iterator part of the same bucket as the other one? template bool _M_in_same_bucket(const _Safe_local_iterator<_Other, _Sequence>& __other) const { return bucket() == __other.bucket(); } }; template inline bool operator==(const _Safe_local_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_local_iterator<_IteratorR, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(!__lhs._M_singular() && !__rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator==(const _Safe_local_iterator<_Iterator, _Sequence>& __lhs, const _Safe_local_iterator<_Iterator, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(!__lhs._M_singular() && !__rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator!=(const _Safe_local_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_local_iterator<_IteratorR, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } template inline bool operator!=(const _Safe_local_iterator<_Iterator, _Sequence>& __lhs, const _Safe_local_iterator<_Iterator, _Sequence>& __rhs) { _GLIBCXX_DEBUG_VERIFY(!__lhs._M_singular() && !__rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_in_same_bucket(__rhs), _M_message(__msg_local_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } /** Safe local iterators know if they are dereferenceable. */ template inline bool __check_dereferenceable(const _Safe_local_iterator<_Iterator, _Sequence>& __x) { return __x._M_dereferenceable(); } /** Safe local iterators know how to check if they form a valid range. */ template inline bool __valid_range(const _Safe_local_iterator<_Iterator, _Sequence>& __first, const _Safe_local_iterator<_Iterator, _Sequence>& __last, typename _Distance_traits<_Iterator>::__type& __dist_info) { return __first._M_valid_range(__last, __dist_info); } /** Safe local iterators need a special method to get distance between each other. */ template inline std::pair::difference_type, _Distance_precision> __get_distance(const _Safe_local_iterator<_Iterator, _Sequence>& __first, const _Safe_local_iterator<_Iterator, _Sequence>& __last, std::input_iterator_tag) { if (__first.base() == __last.base()) return { 0, __dp_exact }; if (__first._M_is_begin()) { if (__last._M_is_end()) return { __first._M_get_sequence()->bucket_size(__first.bucket()), __dp_exact }; return { 1, __dp_sign }; } if (__first._M_is_end()) { if (__last._M_is_begin()) return { -__first._M_get_sequence()->bucket_size(__first.bucket()), __dp_exact }; return { -1, __dp_sign }; } if (__last._M_is_begin()) return { -1, __dp_sign }; if (__last._M_is_end()) return { 1, __dp_sign }; return { 1, __dp_equality }; } #if __cplusplus < 201103L template struct _Unsafe_type<_Safe_local_iterator<_Iterator, _Sequence> > { typedef _Iterator _Type; }; #endif template inline _Iterator __unsafe(const _Safe_local_iterator<_Iterator, _Sequence>& __it) { return __it.base(); } } // namespace __gnu_debug #include #endif c++/8/debug/map.h000064400000054000151027430570007302 0ustar00// Debugging map implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/map.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MAP_H #define _GLIBCXX_DEBUG_MAP_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::map with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator > > class map : public __gnu_debug::_Safe_container< map<_Key, _Tp, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::map<_Key, _Tp, _Compare, _Allocator> { typedef _GLIBCXX_STD_C::map< _Key, _Tp, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< map, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Tp mapped_type; typedef std::pair value_type; typedef _Compare key_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, map> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, map> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.1.1 construct/copy/destroy: #if __cplusplus < 201103L map() : _Base() { } map(const map& __x) : _Base(__x) { } ~map() { } #else map() = default; map(const map&) = default; map(map&&) = default; map(initializer_list __l, const _Compare& __c = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __c, __a) { } explicit map(const allocator_type& __a) : _Base(__a) { } map(const map& __m, const allocator_type& __a) : _Base(__m, __a) { } map(map&& __m, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__m._M_base()), __a)) ) : _Safe(std::move(__m._M_safe()), __a), _Base(std::move(__m._M_base()), __a) { } map(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template map(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~map() = default; #endif map(const _Base& __x) : _Base(__x) { } explicit map(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template map(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } #if __cplusplus < 201103L map& operator=(const map& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else map& operator=(const map&) = default; map& operator=(map&&) = default; map& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif // _GLIBCXX_RESOLVE_LIB_DEFECTS // 133. map missing get_allocator() using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // 23.3.1.2 element access: using _Base::operator[]; // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. using _Base::at; // modifiers: #if __cplusplus >= 201103L template std::pair emplace(_Args&&... __args) { auto __res = _Base::emplace(std::forward<_Args>(__args)...); return std::pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif std::pair insert(const value_type& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(__x); return std::pair(iterator(__res.first, this), __res.second); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init std::pair insert(value_type&& __x) { auto __res = _Base::insert(std::move(__x)); return { iterator(__res.first, this), __res.second }; } template::value>::type> std::pair insert(_Pair&& __x) { std::pair<_Base_iterator, bool> __res = _Base::insert(std::forward<_Pair>(__x)); return std::pair(iterator(__res.first, this), __res.second); } #endif #if __cplusplus >= 201103L void insert(std::initializer_list __list) { _Base::insert(__list); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const value_type& __x) #else insert(iterator __position, const value_type& __x) #endif { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2354. Unnecessary copying when inserting into maps with braced-init iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return { _Base::insert(__position.base(), std::move(__x)), this }; } template::value>::type> iterator insert(const_iterator __position, _Pair&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::forward<_Pair>(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus > 201402L template pair try_emplace(const key_type& __k, _Args&&... __args) { auto __res = _Base::try_emplace(__k, std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template pair try_emplace(key_type&& __k, _Args&&... __args) { auto __res = _Base::try_emplace(std::move(__k), std::forward<_Args>(__args)...); return { iterator(__res.first, this), __res.second }; } template iterator try_emplace(const_iterator __hint, const key_type& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), __k, std::forward<_Args>(__args)...), this); } template iterator try_emplace(const_iterator __hint, key_type&& __k, _Args&&... __args) { __glibcxx_check_insert(__hint); return iterator(_Base::try_emplace(__hint.base(), std::move(__k), std::forward<_Args>(__args)...), this); } template std::pair insert_or_assign(const key_type& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(__k, std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template std::pair insert_or_assign(key_type&& __k, _Obj&& __obj) { auto __res = _Base::insert_or_assign(std::move(__k), std::forward<_Obj>(__obj)); return { iterator(__res.first, this), __res.second }; } template iterator insert_or_assign(const_iterator __hint, const key_type& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), __k, std::forward<_Obj>(__obj)), this); } template iterator insert_or_assign(const_iterator __hint, key_type&& __k, _Obj&& __obj) { __glibcxx_check_insert(__hint); return iterator(_Base::insert_or_assign(__hint.base(), std::move(__k), std::forward<_Obj>(__obj)), this); } #endif // C++17 #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } iterator erase(iterator __position) { return erase(const_iterator(__position)); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { _Base_iterator __victim = _Base::find(__x); if (__victim == _Base::end()) return 0; else { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim); return 1; } } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(map& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // 23.3.1.3 map operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } #endif const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } #endif const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } #endif const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template>, typename _Allocator = allocator<__iter_to_alloc_t<_InputIterator>>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, _Compare, _Allocator>; template, typename _Allocator = allocator>, typename = _RequireAllocator<_Allocator>> map(initializer_list>, _Compare = _Compare(), _Allocator = _Allocator()) -> map<_Key, _Tp, _Compare, _Allocator>; template , typename = _RequireAllocator<_Allocator>> map(_InputIterator, _InputIterator, _Allocator) -> map<__iter_key_t<_InputIterator>, __iter_val_t<_InputIterator>, less<__iter_key_t<_InputIterator>>, _Allocator>; template> map(initializer_list>, _Allocator) -> map<_Key, _Tp, less<_Key>, _Allocator>; #endif template inline bool operator==(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const map<_Key, _Tp, _Compare, _Allocator>& __lhs, const map<_Key, _Tp, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(map<_Key, _Tp, _Compare, _Allocator>& __lhs, map<_Key, _Tp, _Compare, _Allocator>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std #endif c++/8/debug/safe_unordered_container.tcc000064400000006277151027430570014113 0ustar00// Safe container implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_unordered_container.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_TCC #define _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_TCC 1 namespace __gnu_debug { template template void _Safe_unordered_container<_Container>:: _M_invalidate_if(_Predicate __pred) { typedef typename _Container::iterator iterator; typedef typename _Container::const_iterator const_iterator; __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); for (_Safe_iterator_base* __iter = _M_iterators; __iter;) { iterator* __victim = static_cast(__iter); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } for (_Safe_iterator_base* __iter2 = _M_const_iterators; __iter2;) { const_iterator* __victim = static_cast(__iter2); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } } template template void _Safe_unordered_container<_Container>:: _M_invalidate_local_if(_Predicate __pred) { typedef typename _Container::local_iterator local_iterator; typedef typename _Container::const_local_iterator const_local_iterator; __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); for (_Safe_iterator_base* __iter = _M_local_iterators; __iter;) { local_iterator* __victim = static_cast(__iter); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } for (_Safe_iterator_base* __iter2 = _M_const_local_iterators; __iter2;) { const_local_iterator* __victim = static_cast(__iter2); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } } } // namespace __gnu_debug #endif c++/8/debug/safe_sequence.h000064400000011750151027430570011340 0ustar00// Safe sequence implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_sequence.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_SEQUENCE_H #define _GLIBCXX_DEBUG_SAFE_SEQUENCE_H 1 #include #include #include #include namespace __gnu_debug { /** A simple function object that returns true if the passed-in * value is not equal to the stored value. It saves typing over * using both bind1st and not_equal. */ template class _Not_equal_to { _Type __value; public: explicit _Not_equal_to(const _Type& __v) : __value(__v) { } bool operator()(const _Type& __x) const { return __value != __x; } }; /** A simple function object that returns true if the passed-in * value is equal to the stored value. */ template class _Equal_to { _Type __value; public: explicit _Equal_to(const _Type& __v) : __value(__v) { } bool operator()(const _Type& __x) const { return __value == __x; } }; /** A function object that returns true when the given random access iterator is at least @c n steps away from the given iterator. */ template class _After_nth_from { typedef typename std::iterator_traits<_Iterator>::difference_type difference_type; _Iterator _M_base; difference_type _M_n; public: _After_nth_from(const difference_type& __n, const _Iterator& __base) : _M_base(__base), _M_n(__n) { } bool operator()(const _Iterator& __x) const { return __x - _M_base >= _M_n; } }; /** * @brief Base class for constructing a @a safe sequence type that * tracks iterators that reference it. * * The class template %_Safe_sequence simplifies the construction of * @a safe sequences that track the iterators that reference the * sequence, so that the iterators are notified of changes in the * sequence that may affect their operation, e.g., if the container * invalidates its iterators or is destructed. This class template * may only be used by deriving from it and passing the name of the * derived class as its template parameter via the curiously * recurring template pattern. The derived class must have @c * iterator and @c const_iterator types that are instantiations of * class template _Safe_iterator for this sequence. Iterators will * then be tracked automatically. */ template class _Safe_sequence : public _Safe_sequence_base { public: /** Invalidates all iterators @c x that reference this sequence, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal iterators nested in the safe ones. */ template void _M_invalidate_if(_Predicate __pred); /** Transfers all iterators @c x that reference @c from sequence, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal iterators nested in the safe ones. */ template void _M_transfer_from_if(_Safe_sequence& __from, _Predicate __pred); }; /// Like _Safe_sequence but with a special _M_invalidate_all implementation /// not invalidating past-the-end iterators. Used by node based sequence. template class _Safe_node_sequence : public _Safe_sequence<_Sequence> { protected: void _M_invalidate_all() { typedef typename _Sequence::const_iterator _Const_iterator; typedef typename _Const_iterator::iterator_type _Base_const_iterator; typedef __gnu_debug::_Not_equal_to<_Base_const_iterator> _Not_equal; const _Sequence& __seq = *static_cast<_Sequence*>(this); this->_M_invalidate_if(_Not_equal(__seq._M_base().end())); } }; } // namespace __gnu_debug #include #endif c++/8/debug/safe_iterator.tcc000064400000005617151027430570011710 0ustar00// Debugging iterator implementation (out of line) -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_iterator.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_ITERATOR_TCC #define _GLIBCXX_DEBUG_SAFE_ITERATOR_TCC 1 namespace __gnu_debug { template bool _Safe_iterator<_Iterator, _Sequence>:: _M_can_advance(const difference_type& __n) const { if (this->_M_singular()) return false; if (__n == 0) return true; if (__n < 0) { std::pair __dist = __get_distance_from_begin(*this); bool __ok = ((__dist.second == __dp_exact && __dist.first >= -__n) || (__dist.second != __dp_exact && __dist.first > 0)); return __ok; } else { std::pair __dist = __get_distance_to_end(*this); bool __ok = ((__dist.second == __dp_exact && __dist.first >= __n) || (__dist.second != __dp_exact && __dist.first > 0)); return __ok; } } template bool _Safe_iterator<_Iterator, _Sequence>:: _M_valid_range(const _Safe_iterator& __rhs, std::pair& __dist, bool __check_dereferenceable) const { if (!_M_can_compare(__rhs)) return false; /* Determine iterators order */ __dist = __get_distance(*this, __rhs); switch (__dist.second) { case __dp_equality: if (__dist.first == 0) return true; break; case __dp_sign: case __dp_exact: // If range is not empty first iterator must be dereferenceable. if (__dist.first > 0) return !__check_dereferenceable || _M_dereferenceable(); return __dist.first == 0; } // Assume that this is a valid range; we can't check anything else. return true; } } // namespace __gnu_debug #endif c++/8/debug/stl_iterator.h000064400000010264151027430570011244 0ustar00// Debugging support implementation -*- C++ -*- // Copyright (C) 2015-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/stl_iterator.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_STL_ITERATOR_H #define _GLIBCXX_DEBUG_STL_ITERATOR_H 1 #include namespace __gnu_debug { // Help Debug mode to see through reverse_iterator. template inline bool __valid_range(const std::reverse_iterator<_Iterator>& __first, const std::reverse_iterator<_Iterator>& __last, typename _Distance_traits<_Iterator>::__type& __dist) { return __valid_range(__last.base(), __first.base(), __dist); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const std::reverse_iterator<_Iterator>& __first, const std::reverse_iterator<_Iterator>& __last) { return __get_distance(__last.base(), __first.base()); } #if __cplusplus < 201103L template struct __is_safe_random_iterator > : __is_safe_random_iterator<_Iterator> { }; template struct _Unsafe_type > { typedef typename _Unsafe_type<_Iterator>::_Type _UnsafeType; typedef std::reverse_iterator<_UnsafeType> _Type; }; template inline std::reverse_iterator::_Type> __unsafe(const std::reverse_iterator<_Iterator>& __it) { typedef typename _Unsafe_type<_Iterator>::_Type _UnsafeType; return std::reverse_iterator<_UnsafeType>(__unsafe(__it.base())); } #else template inline auto __base(const std::reverse_iterator<_Iterator>& __it) -> decltype(std::__make_reverse_iterator(__base(__it.base()))) { return std::__make_reverse_iterator(__base(__it.base())); } template inline auto __unsafe(const std::reverse_iterator<_Iterator>& __it) -> decltype(std::__make_reverse_iterator(__unsafe(__it.base()))) { return std::__make_reverse_iterator(__unsafe(__it.base())); } #endif #if __cplusplus >= 201103L // Help Debug mode to see through move_iterator. template inline bool __valid_range(const std::move_iterator<_Iterator>& __first, const std::move_iterator<_Iterator>& __last, typename _Distance_traits<_Iterator>::__type& __dist) { return __valid_range(__first.base(), __last.base(), __dist); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const std::move_iterator<_Iterator>& __first, const std::move_iterator<_Iterator>& __last) { return __get_distance(__first.base(), __last.base()); } template inline auto __unsafe(const std::move_iterator<_Iterator>& __it) -> decltype(std::make_move_iterator(__unsafe(__it.base()))) { return std::make_move_iterator(__unsafe(__it.base())); } template inline auto __base(const std::move_iterator<_Iterator>& __it) -> decltype(std::make_move_iterator(__base(__it.base()))) { return std::make_move_iterator(__base(__it.base())); } #endif } #endif c++/8/debug/safe_unordered_container.h000064400000007471151027430570013566 0ustar00// Safe container implementation -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_unordered_container.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_H #define _GLIBCXX_DEBUG_SAFE_UNORDERED_CONTAINER_H 1 #include #include #include #include namespace __gnu_debug { /** * @brief Base class for constructing a @a safe unordered container type * that tracks iterators that reference it. * * The class template %_Safe_unordered_container simplifies the * construction of @a safe unordered containers that track the iterators * that reference the container, so that the iterators are notified of * changes in the container that may affect their operation, e.g., if * the container invalidates its iterators or is destructed. This class * template may only be used by deriving from it and passing the name * of the derived class as its template parameter via the curiously * recurring template pattern. The derived class must have @c * iterator and @c const_iterator types that are instantiations of * class template _Safe_iterator for this container and @c local_iterator * and @c const_local_iterator types that are instantiations of class * template _Safe_local_iterator for this container. Iterators will * then be tracked automatically. */ template class _Safe_unordered_container : public _Safe_unordered_container_base { private: _Container& _M_cont() noexcept { return *static_cast<_Container*>(this); } protected: void _M_invalidate_locals() { auto __local_end = _M_cont()._M_base().end(0); this->_M_invalidate_local_if( [__local_end](__decltype(_M_cont()._M_base().cend(0)) __it) { return __it != __local_end; }); } void _M_invalidate_all() { auto __end = _M_cont()._M_base().end(); this->_M_invalidate_if( [__end](__decltype(_M_cont()._M_base().cend()) __it) { return __it != __end; }); _M_invalidate_locals(); } /** Invalidates all iterators @c x that reference this container, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal iterators nested in the safe ones. */ template void _M_invalidate_if(_Predicate __pred); /** Invalidates all local iterators @c x that reference this container, are not singular, and for which @c __pred(x) returns @c true. @c __pred will be invoked with the normal ilocal iterators nested in the safe ones. */ template void _M_invalidate_local_if(_Predicate __pred); }; } // namespace __gnu_debug #include #endif c++/8/debug/safe_iterator.h000064400000073050151027430570011362 0ustar00// Safe iterator implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_iterator.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_ITERATOR_H #define _GLIBCXX_DEBUG_SAFE_ITERATOR_H 1 #include #include #include #include #include #include namespace __gnu_debug { /** Helper struct to deal with sequence offering a before_begin * iterator. **/ template struct _BeforeBeginHelper { template static bool _S_Is(const _Safe_iterator<_Iterator, _Sequence>&) { return false; } template static bool _S_Is_Beginnest(const _Safe_iterator<_Iterator, _Sequence>& __it) { return __it.base() == __it._M_get_sequence()->_M_base().begin(); } }; /** Sequence traits giving the size of a container if possible. */ template struct _Sequence_traits { typedef _Distance_traits _DistTraits; static typename _DistTraits::__type _S_size(const _Sequence& __seq) { return std::make_pair(__seq.size(), __dp_exact); } }; /** \brief Safe iterator wrapper. * * The class template %_Safe_iterator is a wrapper around an * iterator that tracks the iterator's movement among sequences and * checks that operations performed on the "safe" iterator are * legal. In additional to the basic iterator operations (which are * validated, and then passed to the underlying iterator), * %_Safe_iterator has member functions for iterator invalidation, * attaching/detaching the iterator from sequences, and querying * the iterator's state. * * Note that _Iterator must be the first base class so that it gets * initialized before the iterator is being attached to the container's list * of iterators and it is being detached before _Iterator get * destroyed. Otherwise it would result in a data race. */ template class _Safe_iterator : private _Iterator, public _Safe_iterator_base { typedef _Iterator _Iter_base; typedef _Safe_iterator_base _Safe_base; typedef typename _Sequence::const_iterator _Const_iterator; /// Determine if this is a constant iterator. bool _M_constant() const { return std::__are_same<_Const_iterator, _Safe_iterator>::__value; } typedef std::iterator_traits<_Iterator> _Traits; struct _Attach_single { }; _Safe_iterator(const _Iterator& __i, _Safe_sequence_base* __seq, _Attach_single) _GLIBCXX_NOEXCEPT : _Iter_base(__i) { _M_attach_single(__seq); } public: typedef _Iterator iterator_type; typedef typename _Traits::iterator_category iterator_category; typedef typename _Traits::value_type value_type; typedef typename _Traits::difference_type difference_type; typedef typename _Traits::reference reference; typedef typename _Traits::pointer pointer; /// @post the iterator is singular and unattached _Safe_iterator() _GLIBCXX_NOEXCEPT : _Iter_base() { } /** * @brief Safe iterator construction from an unsafe iterator and * its sequence. * * @pre @p seq is not NULL * @post this is not singular */ _Safe_iterator(const _Iterator& __i, const _Safe_sequence_base* __seq) _GLIBCXX_NOEXCEPT : _Iter_base(__i), _Safe_base(__seq, _M_constant()) { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__msg_init_singular) ._M_iterator(*this, "this")); } /** * @brief Copy construction. */ _Safe_iterator(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } #if __cplusplus >= 201103L /** * @brief Move construction. * @post __x is singular and unattached */ _Safe_iterator(_Safe_iterator&& __x) noexcept : _Iter_base() { _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _Safe_sequence_base* __seq = __x._M_sequence; __x._M_detach(); std::swap(base(), __x.base()); _M_attach(__seq); } #endif /** * @brief Converting constructor from a mutable iterator to a * constant iterator. */ template _Safe_iterator( const _Safe_iterator<_MutableIterator, typename __gnu_cxx::__enable_if<(std::__are_same<_MutableIterator, typename _Sequence::iterator::iterator_type>::__value), _Sequence>::__type>& __x) _GLIBCXX_NOEXCEPT : _Iter_base(__x.base()) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_init_const_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); _M_attach(__x._M_sequence); } /** * @brief Copy assignment. */ _Safe_iterator& operator=(const _Safe_iterator& __x) _GLIBCXX_NOEXCEPT { // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 408. Is vector > forbidden? _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } return *this; } #if __cplusplus >= 201103L /** * @brief Move assignment. * @post __x is singular and unattached */ _Safe_iterator& operator=(_Safe_iterator&& __x) noexcept { _GLIBCXX_DEBUG_VERIFY(this != &__x, _M_message(__msg_self_move_assign) ._M_iterator(*this, "this")); _GLIBCXX_DEBUG_VERIFY(!__x._M_singular() || __x.base() == _Iterator(), _M_message(__msg_copy_singular) ._M_iterator(*this, "this") ._M_iterator(__x, "other")); if (this->_M_sequence && this->_M_sequence == __x._M_sequence) { __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() = __x.base(); _M_version = __x._M_sequence->_M_version; } else { _M_detach(); base() = __x.base(); _M_attach(__x._M_sequence); } __x._M_detach(); __x.base() = _Iterator(); return *this; } #endif /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ reference operator*() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return *base(); } /** * @brief Iterator dereference. * @pre iterator is dereferenceable */ pointer operator->() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_dereferenceable(), _M_message(__msg_bad_deref) ._M_iterator(*this, "this")); return base().operator->(); } // ------ Input iterator requirements ------ /** * @brief Iterator preincrement * @pre iterator is incrementable */ _Safe_iterator& operator++() _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); ++base(); return *this; } /** * @brief Iterator postincrement * @pre iterator is incrementable */ _Safe_iterator operator++(int) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_incrementable(), _M_message(__msg_bad_inc) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); return _Safe_iterator(base()++, this->_M_sequence, _Attach_single()); } // ------ Bidirectional iterator requirements ------ /** * @brief Iterator predecrement * @pre iterator is decrementable */ _Safe_iterator& operator--() _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_decrementable(), _M_message(__msg_bad_dec) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); --base(); return *this; } /** * @brief Iterator postdecrement * @pre iterator is decrementable */ _Safe_iterator operator--(int) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_decrementable(), _M_message(__msg_bad_dec) ._M_iterator(*this, "this")); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); return _Safe_iterator(base()--, this->_M_sequence, _Attach_single()); } // ------ Random access iterator requirements ------ reference operator[](const difference_type& __n) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(__n) && this->_M_can_advance(__n+1), _M_message(__msg_iter_subscript_oob) ._M_iterator(*this)._M_integer(__n)); return base()[__n]; } _Safe_iterator& operator+=(const difference_type& __n) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(__n), _M_message(__msg_advance_oob) ._M_iterator(*this)._M_integer(__n)); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() += __n; return *this; } _Safe_iterator operator+(const difference_type& __n) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(__n), _M_message(__msg_advance_oob) ._M_iterator(*this)._M_integer(__n)); return _Safe_iterator(base() + __n, this->_M_sequence); } _Safe_iterator& operator-=(const difference_type& __n) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(-__n), _M_message(__msg_retreat_oob) ._M_iterator(*this)._M_integer(__n)); __gnu_cxx::__scoped_lock __l(this->_M_get_mutex()); base() -= __n; return *this; } _Safe_iterator operator-(const difference_type& __n) const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(this->_M_can_advance(-__n), _M_message(__msg_retreat_oob) ._M_iterator(*this)._M_integer(__n)); return _Safe_iterator(base() - __n, this->_M_sequence); } // ------ Utilities ------ /** * @brief Return the underlying iterator */ _Iterator& base() _GLIBCXX_NOEXCEPT { return *this; } const _Iterator& base() const _GLIBCXX_NOEXCEPT { return *this; } /** * @brief Conversion to underlying non-debug iterator to allow * better interaction with non-debug containers. */ operator _Iterator() const _GLIBCXX_NOEXCEPT { return *this; } /** Attach iterator to the given sequence. */ void _M_attach(_Safe_sequence_base* __seq) { _Safe_base::_M_attach(__seq, _M_constant()); } /** Likewise, but not thread-safe. */ void _M_attach_single(_Safe_sequence_base* __seq) { _Safe_base::_M_attach_single(__seq, _M_constant()); } /// Is the iterator dereferenceable? bool _M_dereferenceable() const { return !this->_M_singular() && !_M_is_end() && !_M_is_before_begin(); } /// Is the iterator before a dereferenceable one? bool _M_before_dereferenceable() const { if (this->_M_incrementable()) { _Iterator __base = base(); return ++__base != _M_get_sequence()->_M_base().end(); } return false; } /// Is the iterator incrementable? bool _M_incrementable() const { return !this->_M_singular() && !_M_is_end(); } // Is the iterator decrementable? bool _M_decrementable() const { return !_M_singular() && !_M_is_begin(); } // Can we advance the iterator @p __n steps (@p __n may be negative) bool _M_can_advance(const difference_type& __n) const; // Is the iterator range [*this, __rhs) valid? bool _M_valid_range(const _Safe_iterator& __rhs, std::pair& __dist, bool __check_dereferenceable = true) const; // The sequence this iterator references. typename __gnu_cxx::__conditional_type::__value, const _Sequence*, _Sequence*>::__type _M_get_sequence() const { return static_cast<_Sequence*>(_M_sequence); } /// Is this iterator equal to the sequence's begin() iterator? bool _M_is_begin() const { return base() == _M_get_sequence()->_M_base().begin(); } /// Is this iterator equal to the sequence's end() iterator? bool _M_is_end() const { return base() == _M_get_sequence()->_M_base().end(); } /// Is this iterator equal to the sequence's before_begin() iterator if /// any? bool _M_is_before_begin() const { return _BeforeBeginHelper<_Sequence>::_S_Is(*this); } /// Is this iterator equal to the sequence's before_begin() iterator if /// any or begin() otherwise? bool _M_is_beginnest() const { return _BeforeBeginHelper<_Sequence>::_S_Is_Beginnest(*this); } }; template inline bool operator==(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator==(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() == __rhs.base(); } template inline bool operator!=(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } template inline bool operator!=(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_compare_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_compare_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() != __rhs.base(); } template inline bool operator<(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() < __rhs.base(); } template inline bool operator<(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() < __rhs.base(); } template inline bool operator<=(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() <= __rhs.base(); } template inline bool operator<=(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() <= __rhs.base(); } template inline bool operator>(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() > __rhs.base(); } template inline bool operator>(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() > __rhs.base(); } template inline bool operator>=(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() >= __rhs.base(); } template inline bool operator>=(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_iter_order_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_order_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() >= __rhs.base(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR179 not only the various comparison // operators but also operator- must accept mixed iterator/const_iterator // parameters. template inline typename _Safe_iterator<_IteratorL, _Sequence>::difference_type operator-(const _Safe_iterator<_IteratorL, _Sequence>& __lhs, const _Safe_iterator<_IteratorR, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_distance_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_distance_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() - __rhs.base(); } template inline typename _Safe_iterator<_Iterator, _Sequence>::difference_type operator-(const _Safe_iterator<_Iterator, _Sequence>& __lhs, const _Safe_iterator<_Iterator, _Sequence>& __rhs) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(! __lhs._M_singular() && ! __rhs._M_singular(), _M_message(__msg_distance_bad) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); _GLIBCXX_DEBUG_VERIFY(__lhs._M_can_compare(__rhs), _M_message(__msg_distance_different) ._M_iterator(__lhs, "lhs") ._M_iterator(__rhs, "rhs")); return __lhs.base() - __rhs.base(); } template inline _Safe_iterator<_Iterator, _Sequence> operator+(typename _Safe_iterator<_Iterator,_Sequence>::difference_type __n, const _Safe_iterator<_Iterator, _Sequence>& __i) _GLIBCXX_NOEXCEPT { return __i + __n; } /** Safe iterators know if they are dereferenceable. */ template inline bool __check_dereferenceable(const _Safe_iterator<_Iterator, _Sequence>& __x) { return __x._M_dereferenceable(); } /** Safe iterators know how to check if they form a valid range. */ template inline bool __valid_range(const _Safe_iterator<_Iterator, _Sequence>& __first, const _Safe_iterator<_Iterator, _Sequence>& __last, typename _Distance_traits<_Iterator>::__type& __dist) { return __first._M_valid_range(__last, __dist); } /** Safe iterators can help to get better distance knowledge. */ template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Safe_iterator<_Iterator, _Sequence>& __first, const _Safe_iterator<_Iterator, _Sequence>& __last, std::random_access_iterator_tag) { return std::make_pair(__last.base() - __first.base(), __dp_exact); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Safe_iterator<_Iterator, _Sequence>& __first, const _Safe_iterator<_Iterator, _Sequence>& __last, std::input_iterator_tag) { typedef typename _Distance_traits<_Iterator>::__type _Diff; typedef _Sequence_traits<_Sequence> _SeqTraits; if (__first.base() == __last.base()) return std::make_pair(0, __dp_exact); if (__first._M_is_before_begin()) { if (__last._M_is_begin()) return std::make_pair(1, __dp_exact); return std::make_pair(1, __dp_sign); } if (__first._M_is_begin()) { if (__last._M_is_before_begin()) return std::make_pair(-1, __dp_exact); if (__last._M_is_end()) return _SeqTraits::_S_size(*__first._M_get_sequence()); return std::make_pair(1, __dp_sign); } if (__first._M_is_end()) { if (__last._M_is_before_begin()) return std::make_pair(-1, __dp_exact); if (__last._M_is_begin()) { _Diff __diff = _SeqTraits::_S_size(*__first._M_get_sequence()); return std::make_pair(-__diff.first, __diff.second); } return std::make_pair(-1, __dp_sign); } if (__last._M_is_before_begin() || __last._M_is_begin()) return std::make_pair(-1, __dp_sign); if (__last._M_is_end()) return std::make_pair(1, __dp_sign); return std::make_pair(1, __dp_equality); } // Get distance from sequence begin to specified iterator. template inline typename _Distance_traits<_Iterator>::__type __get_distance_from_begin(const _Safe_iterator<_Iterator, _Sequence>& __it) { typedef _Sequence_traits<_Sequence> _SeqTraits; // No need to consider before_begin as this function is only used in // _M_can_advance which won't be used for forward_list iterators. if (__it._M_is_begin()) return std::make_pair(0, __dp_exact); if (__it._M_is_end()) return _SeqTraits::_S_size(*__it._M_get_sequence()); typename _Distance_traits<_Iterator>::__type __res = __get_distance(__it._M_get_sequence()->_M_base().begin(), __it.base()); if (__res.second == __dp_equality) return std::make_pair(1, __dp_sign); return __res; } // Get distance from specified iterator to sequence end. template inline typename _Distance_traits<_Iterator>::__type __get_distance_to_end(const _Safe_iterator<_Iterator, _Sequence>& __it) { typedef _Sequence_traits<_Sequence> _SeqTraits; // No need to consider before_begin as this function is only used in // _M_can_advance which won't be used for forward_list iterators. if (__it._M_is_begin()) return _SeqTraits::_S_size(*__it._M_get_sequence()); if (__it._M_is_end()) return std::make_pair(0, __dp_exact); typename _Distance_traits<_Iterator>::__type __res = __get_distance(__it.base(), __it._M_get_sequence()->_M_base().end()); if (__res.second == __dp_equality) return std::make_pair(1, __dp_sign); return __res; } #if __cplusplus < 201103L template struct __is_safe_random_iterator<_Safe_iterator<_Iterator, _Sequence> > : std::__are_same:: iterator_category> { }; #else template _Iterator __base(const _Safe_iterator<_Iterator, _Sequence>& __it, std::random_access_iterator_tag) { return __it.base(); } template const _Safe_iterator<_Iterator, _Sequence>& __base(const _Safe_iterator<_Iterator, _Sequence>& __it, std::input_iterator_tag) { return __it; } template auto __base(const _Safe_iterator<_Iterator, _Sequence>& __it) -> decltype(__base(__it, std::__iterator_category(__it))) { return __base(__it, std::__iterator_category(__it)); } #endif #if __cplusplus < 201103L template struct _Unsafe_type<_Safe_iterator<_Iterator, _Sequence> > { typedef _Iterator _Type; }; #endif template inline _Iterator __unsafe(const _Safe_iterator<_Iterator, _Sequence>& __it) { return __it.base(); } } // namespace __gnu_debug #include #endif c++/8/debug/unordered_set000064400000105735151027430570011155 0ustar00// Debugging unordered_set/unordered_multiset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/unordered_set * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_UNORDERED_SET #define _GLIBCXX_DEBUG_UNORDERED_SET 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else # include #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::unordered_set with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value> > class unordered_set : public __gnu_debug::_Safe_container< unordered_set<_Value, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_set<_Value, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_set< _Value, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container< unordered_set, _Alloc, __gnu_debug::_Safe_unordered_container> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_set> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_set> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_set> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_set> const_local_iterator; unordered_set() = default; explicit unordered_set(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_set(const unordered_set&) = default; unordered_set(const _Base& __x) : _Base(__x) { } unordered_set(unordered_set&&) = default; explicit unordered_set(const allocator_type& __a) : _Base(__a) { } unordered_set(const unordered_set& __uset, const allocator_type& __a) : _Base(__uset, __a) { } unordered_set(unordered_set&& __uset, const allocator_type& __a) : _Safe(std::move(__uset._M_safe()), __a), _Base(std::move(__uset._M_base()), __a) { } unordered_set(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_set(size_type __n, const allocator_type& __a) : unordered_set(__n, hasher(), key_equal(), __a) { } unordered_set(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__n, __hf, key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_set(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_set(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__first, __last, __n, __hf, key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_set(__l, __n, hasher(), key_equal(), __a) { } unordered_set(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_set(__l, __n, __hf, key_equal(), __a) { } ~unordered_set() = default; unordered_set& operator=(const unordered_set&) = default; unordered_set& operator=(unordered_set&&) = default; unordered_set& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_set& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template std::pair emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } std::pair insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } std::pair insert(value_type&& __obj) { size_type __bucket_count = this->bucket_count(); std::pair<_Base_iterator, bool> __res = _Base::insert(std::move(__obj)); _M_check_rehashed(__bucket_count); return std::make_pair(iterator(__res.first, this), __res.second); } iterator insert(const_iterator __hint, value_type&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::move(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { size_type __bucket_count = this->bucket_count(); _Base::insert(__l); _M_check_rehashed(__bucket_count); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; using insert_return_type = _Node_insert_return; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } insert_return_type insert(node_type&& __nh) { auto __ret = _Base::insert(std::move(__nh)); iterator __pos = iterator(__ret.position, this); return { __pos, __ret.inserted, std::move(__ret.node) }; } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); _Base_iterator __victim(_Base::find(__key)); if (__victim != _Base::end()) { this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base::erase(__victim); _M_check_rehashed(__bucket_count); __ret = 1; } return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__it.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if( [__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } size_type __bucket_count = this->bucket_count(); _Base_iterator __next = _Base::erase(__first.base(), __last.base()); _M_check_rehashed(__bucket_count); return iterator(__next, this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_set(initializer_list<_Tp>, unordered_set::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_set<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Allocator) -> unordered_set::value_type, hash< typename iterator_traits<_InputIterator>::value_type>, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_set(_InputIterator, _InputIterator, unordered_set::size_type, _Hash, _Allocator) -> unordered_set::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Allocator) -> unordered_set<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_set(initializer_list<_Tp>, unordered_set::size_type, _Hash, _Allocator) -> unordered_set<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif template inline void swap(unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_set<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_set<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } /// Class std::unordered_multiset with safety/checking/debug instrumentation. template, typename _Pred = std::equal_to<_Value>, typename _Alloc = std::allocator<_Value> > class unordered_multiset : public __gnu_debug::_Safe_container< unordered_multiset<_Value, _Hash, _Pred, _Alloc>, _Alloc, __gnu_debug::_Safe_unordered_container>, public _GLIBCXX_STD_C::unordered_multiset<_Value, _Hash, _Pred, _Alloc> { typedef _GLIBCXX_STD_C::unordered_multiset< _Value, _Hash, _Pred, _Alloc> _Base; typedef __gnu_debug::_Safe_container _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_local_iterator _Base_const_local_iterator; typedef typename _Base::local_iterator _Base_local_iterator; public: typedef typename _Base::size_type size_type; typedef typename _Base::hasher hasher; typedef typename _Base::key_equal key_equal; typedef typename _Base::allocator_type allocator_type; typedef typename _Base::key_type key_type; typedef typename _Base::value_type value_type; typedef __gnu_debug::_Safe_iterator< _Base_iterator, unordered_multiset> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, unordered_multiset> const_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_local_iterator, unordered_multiset> local_iterator; typedef __gnu_debug::_Safe_local_iterator< _Base_const_local_iterator, unordered_multiset> const_local_iterator; unordered_multiset() = default; explicit unordered_multiset(size_type __n, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__n, __hf, __eql, __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __n, __hf, __eql, __a) { } unordered_multiset(const unordered_multiset&) = default; unordered_multiset(const _Base& __x) : _Base(__x) { } unordered_multiset(unordered_multiset&&) = default; explicit unordered_multiset(const allocator_type& __a) : _Base(__a) { } unordered_multiset(const unordered_multiset& __uset, const allocator_type& __a) : _Base(__uset, __a) { } unordered_multiset(unordered_multiset&& __uset, const allocator_type& __a) : _Safe(std::move(__uset._M_safe()), __a), _Base(std::move(__uset._M_base()), __a) { } unordered_multiset(initializer_list __l, size_type __n = 0, const hasher& __hf = hasher(), const key_equal& __eql = key_equal(), const allocator_type& __a = allocator_type()) : _Base(__l, __n, __hf, __eql, __a) { } unordered_multiset(size_type __n, const allocator_type& __a) : unordered_multiset(__n, hasher(), key_equal(), __a) { } unordered_multiset(size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__n, __hf, key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const allocator_type& __a) : unordered_multiset(__first, __last, __n, hasher(), key_equal(), __a) { } template unordered_multiset(_InputIterator __first, _InputIterator __last, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__first, __last, __n, __hf, key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const allocator_type& __a) : unordered_multiset(__l, __n, hasher(), key_equal(), __a) { } unordered_multiset(initializer_list __l, size_type __n, const hasher& __hf, const allocator_type& __a) : unordered_multiset(__l, __n, __hf, key_equal(), __a) { } ~unordered_multiset() = default; unordered_multiset& operator=(const unordered_multiset&) = default; unordered_multiset& operator=(unordered_multiset&&) = default; unordered_multiset& operator=(initializer_list __l) { this->_M_base() = __l; this->_M_invalidate_all(); return *this; } void swap(unordered_multiset& __x) noexcept( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() noexcept { _Base::clear(); this->_M_invalidate_all(); } iterator begin() noexcept { return iterator(_Base::begin(), this); } const_iterator begin() const noexcept { return const_iterator(_Base::begin(), this); } iterator end() noexcept { return iterator(_Base::end(), this); } const_iterator end() const noexcept { return const_iterator(_Base::end(), this); } const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } // local versions local_iterator begin(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::begin(__b), this); } local_iterator end(size_type __b) { __glibcxx_check_bucket_index(__b); return local_iterator(_Base::end(__b), this); } const_local_iterator begin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::begin(__b), this); } const_local_iterator end(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::end(__b), this); } const_local_iterator cbegin(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cbegin(__b), this); } const_local_iterator cend(size_type __b) const { __glibcxx_check_bucket_index(__b); return const_local_iterator(_Base::cend(__b), this); } size_type bucket_size(size_type __b) const { __glibcxx_check_bucket_index(__b); return _Base::bucket_size(__b); } float max_load_factor() const noexcept { return _Base::max_load_factor(); } void max_load_factor(float __f) { __glibcxx_check_max_load_factor(__f); _Base::max_load_factor(__f); } template iterator emplace(_Args&&... __args) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace(std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } template iterator emplace_hint(const_iterator __hint, _Args&&... __args) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::emplace_hint(__hint.base(), std::forward<_Args>(__args)...); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const value_type& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const_iterator __hint, const value_type& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), __obj); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(value_type&& __obj) { size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(std::move(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } iterator insert(const_iterator __hint, value_type&& __obj) { __glibcxx_check_insert(__hint); size_type __bucket_count = this->bucket_count(); _Base_iterator __it = _Base::insert(__hint.base(), std::move(__obj)); _M_check_rehashed(__bucket_count); return iterator(__it, this); } void insert(std::initializer_list __l) { size_type __bucket_count = this->bucket_count(); _Base::insert(__l); _M_check_rehashed(__bucket_count); } template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); size_type __bucket_count = this->bucket_count(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); _M_check_rehashed(__bucket_count); } #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); _Base_const_iterator __victim = __position.base(); this->_M_invalidate_if( [__victim](_Base_const_iterator __it) { return __it == __victim; } ); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 iterator find(const key_type& __key) { return iterator(_Base::find(__key), this); } const_iterator find(const key_type& __key) const { return const_iterator(_Base::find(__key), this); } std::pair equal_range(const key_type& __key) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__key); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } std::pair equal_range(const key_type& __key) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__key); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } size_type erase(const key_type& __key) { size_type __ret(0); std::pair<_Base_iterator, _Base_iterator> __pair = _Base::equal_range(__key); for (_Base_iterator __victim = __pair.first; __victim != __pair.second;) { this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); _Base::erase(__victim++); ++__ret; } return __ret; } iterator erase(const_iterator __it) { __glibcxx_check_erase(__it); _Base_const_iterator __victim = __it.base(); this->_M_invalidate_if([__victim](_Base_const_iterator __it) { return __it == __victim; }); this->_M_invalidate_local_if( [__victim](_Base_const_local_iterator __it) { return __it._M_curr() == __victim._M_cur; }); return iterator(_Base::erase(__it.base()), this); } iterator erase(iterator __it) { return erase(const_iterator(__it)); } iterator erase(const_iterator __first, const_iterator __last) { __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if([__tmp](_Base_const_iterator __it) { return __it == __tmp; }); this->_M_invalidate_local_if( [__tmp](_Base_const_local_iterator __it) { return __it._M_curr() == __tmp._M_cur; }); } return iterator(_Base::erase(__first.base(), __last.base()), this); } _Base& _M_base() noexcept { return *this; } const _Base& _M_base() const noexcept { return *this; } private: void _M_check_rehashed(size_type __prev_count) { if (__prev_count != this->bucket_count()) this->_M_invalidate_locals(); } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Pred = equal_to::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset::value_type, _Hash, _Pred, _Allocator>; template, typename _Pred = equal_to<_Tp>, typename _Allocator = allocator<_Tp>, typename = _RequireAllocator<_Allocator>> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type = {}, _Hash = _Hash(), _Pred = _Pred(), _Allocator = _Allocator()) -> unordered_multiset<_Tp, _Hash, _Pred, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Allocator) -> unordered_multiset::value_type, hash::value_type>, equal_to::value_type>, _Allocator>; template, typename = _RequireAllocator<_Allocator>> unordered_multiset(_InputIterator, _InputIterator, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset::value_type, _Hash, equal_to< typename iterator_traits<_InputIterator>::value_type>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Allocator) -> unordered_multiset<_Tp, hash<_Tp>, equal_to<_Tp>, _Allocator>; template> unordered_multiset(initializer_list<_Tp>, unordered_multiset::size_type, _Hash, _Allocator) -> unordered_multiset<_Tp, _Hash, equal_to<_Tp>, _Allocator>; #endif template inline void swap(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) noexcept(noexcept(__x.swap(__y))) { __x.swap(__y); } template inline bool operator==(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return __x._M_base() == __y._M_base(); } template inline bool operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x, const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __y) { return !(__x == __y); } } // namespace __debug } // namespace std #endif // C++11 #endif c++/8/debug/array000064400000024213151027430570007420 0ustar00// Debugging array implementation -*- C++ -*- // Copyright (C) 2012-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/array * This is a Standard C++ Library header. */ #ifndef _GLIBCXX_DEBUG_ARRAY #define _GLIBCXX_DEBUG_ARRAY 1 #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { template struct array { typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef value_type* iterator; typedef const value_type* const_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // Support for zero-sized arrays mandatory. typedef _GLIBCXX_STD_C::__array_traits<_Tp, _Nm> _AT_Type; typename _AT_Type::_Type _M_elems; template struct _Array_check_subscript { std::size_t size() { return _Size; } _Array_check_subscript(std::size_t __index) { __glibcxx_check_subscript(__index); } }; template struct _Array_check_nonempty { bool empty() { return _Size == 0; } _Array_check_nonempty() { __glibcxx_check_nonempty(); } }; // No explicit construct/copy/destroy for aggregate type. // DR 776. void fill(const value_type& __u) { std::fill_n(begin(), size(), __u); } void swap(array& __other) noexcept(_AT_Type::_Is_nothrow_swappable::value) { std::swap_ranges(begin(), end(), __other.begin()); } // Iterators. _GLIBCXX17_CONSTEXPR iterator begin() noexcept { return iterator(data()); } _GLIBCXX17_CONSTEXPR const_iterator begin() const noexcept { return const_iterator(data()); } _GLIBCXX17_CONSTEXPR iterator end() noexcept { return iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR const_iterator end() const noexcept { return const_iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR reverse_iterator rend() noexcept { return reverse_iterator(begin()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); } _GLIBCXX17_CONSTEXPR const_iterator cbegin() const noexcept { return const_iterator(data()); } _GLIBCXX17_CONSTEXPR const_iterator cend() const noexcept { return const_iterator(data() + _Nm); } _GLIBCXX17_CONSTEXPR const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } _GLIBCXX17_CONSTEXPR const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } // Capacity. constexpr size_type size() const noexcept { return _Nm; } constexpr size_type max_size() const noexcept { return _Nm; } constexpr bool empty() const noexcept { return size() == 0; } // Element access. _GLIBCXX17_CONSTEXPR reference operator[](size_type __n) noexcept { __glibcxx_check_subscript(__n); return _AT_Type::_S_ref(_M_elems, __n); } constexpr const_reference operator[](size_type __n) const noexcept { return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n) : (_GLIBCXX_THROW_OR_ABORT(_Array_check_subscript<_Nm>(__n)), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference at(size_type __n) { if (__n >= _Nm) std::__throw_out_of_range_fmt(__N("array::at: __n (which is %zu) " ">= _Nm (which is %zu)"), __n, _Nm); return _AT_Type::_S_ref(_M_elems, __n); } constexpr const_reference at(size_type __n) const { // Result of conditional expression must be an lvalue so use // boolean ? lvalue : (throw-expr, lvalue) return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n) : (std::__throw_out_of_range_fmt(__N("array::at: __n (which is %zu) " ">= _Nm (which is %zu)"), __n, _Nm), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference front() noexcept { __glibcxx_check_nonempty(); return *begin(); } constexpr const_reference front() const noexcept { return _Nm ? _AT_Type::_S_ref(_M_elems, 0) : (_GLIBCXX_THROW_OR_ABORT(_Array_check_nonempty<_Nm>()), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR reference back() noexcept { __glibcxx_check_nonempty(); return _Nm ? *(end() - 1) : *end(); } constexpr const_reference back() const noexcept { return _Nm ? _AT_Type::_S_ref(_M_elems, _Nm - 1) : (_GLIBCXX_THROW_OR_ABORT(_Array_check_nonempty<_Nm>()), _AT_Type::_S_ref(_M_elems, 0)); } _GLIBCXX17_CONSTEXPR pointer data() noexcept { return _AT_Type::_S_ptr(_M_elems); } _GLIBCXX17_CONSTEXPR const_pointer data() const noexcept { return _AT_Type::_S_ptr(_M_elems); } }; #if __cpp_deduction_guides >= 201606 template array(_Tp, _Up...) -> array && ...), _Tp>, 1 + sizeof...(_Up)>; #endif // Array comparisons. template inline bool operator==(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return std::equal(__one.begin(), __one.end(), __two.begin()); } template inline bool operator!=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one == __two); } template inline bool operator<(const array<_Tp, _Nm>& __a, const array<_Tp, _Nm>& __b) { return std::lexicographical_compare(__a.begin(), __a.end(), __b.begin(), __b.end()); } template inline bool operator>(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return __two < __one; } template inline bool operator<=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one > __two); } template inline bool operator>=(const array<_Tp, _Nm>& __one, const array<_Tp, _Nm>& __two) { return !(__one < __two); } // Specialized algorithms. #if __cplusplus > 201402L || !defined(__STRICT_ANSI__) // c++1z or gnu++11 template typename enable_if< !_GLIBCXX_STD_C::__array_traits<_Tp, _Nm>::_Is_swappable::value>::type swap(array<_Tp, _Nm>&, array<_Tp, _Nm>&) = delete; #endif template inline void swap(array<_Tp, _Nm>& __one, array<_Tp, _Nm>& __two) noexcept(noexcept(__one.swap(__two))) { __one.swap(__two); } template constexpr _Tp& get(array<_Tp, _Nm>& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>:: _S_ref(__arr._M_elems, _Int); } template constexpr _Tp&& get(array<_Tp, _Nm>&& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return std::move(__debug::get<_Int>(__arr)); } template constexpr const _Tp& get(const array<_Tp, _Nm>& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return _GLIBCXX_STD_C::__array_traits<_Tp, _Nm>:: _S_ref(__arr._M_elems, _Int); } template constexpr const _Tp&& get(const array<_Tp, _Nm>&& __arr) noexcept { static_assert(_Int < _Nm, "index is out of bounds"); return std::move(__debug::get<_Int>(__arr)); } } // namespace __debug _GLIBCXX_BEGIN_NAMESPACE_VERSION // Tuple interface to class template array. /// tuple_size template struct tuple_size> : public integral_constant { }; /// tuple_element template struct tuple_element<_Int, std::__debug::array<_Tp, _Nm>> { static_assert(_Int < _Nm, "index is out of bounds"); typedef _Tp type; }; template struct __is_tuple_like_impl> : true_type { }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace std #endif // _GLIBCXX_DEBUG_ARRAY c++/8/debug/deque000064400000041776151027430570007422 0ustar00// Debugging deque implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/deque * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_DEQUE #define _GLIBCXX_DEBUG_DEQUE 1 #pragma GCC system_header #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::deque with safety/checking/debug instrumentation. template > class deque : public __gnu_debug::_Safe_container< deque<_Tp, _Allocator>, _Allocator, __gnu_debug::_Safe_sequence>, public _GLIBCXX_STD_C::deque<_Tp, _Allocator> { typedef _GLIBCXX_STD_C::deque<_Tp, _Allocator> _Base; typedef __gnu_debug::_Safe_container< deque, _Allocator, __gnu_debug::_Safe_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, deque> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, deque> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef _Allocator allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.2.1.1 construct/copy/destroy: #if __cplusplus < 201103L deque() : _Base() { } deque(const deque& __x) : _Base(__x) { } ~deque() { } #else deque() = default; deque(const deque&) = default; deque(deque&&) = default; deque(const deque& __d, const _Allocator& __a) : _Base(__d, __a) { } deque(deque&& __d, const _Allocator& __a) : _Safe(std::move(__d)), _Base(std::move(__d), __a) { } deque(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__l, __a) { } ~deque() = default; #endif explicit deque(const _Allocator& __a) : _Base(__a) { } #if __cplusplus >= 201103L explicit deque(size_type __n, const _Allocator& __a = _Allocator()) : _Base(__n, __a) { } deque(size_type __n, const _Tp& __value, const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #else explicit deque(size_type __n, const _Tp& __value = _Tp(), const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #endif #if __cplusplus >= 201103L template> #else template #endif deque(_InputIterator __first, _InputIterator __last, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } deque(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L deque& operator=(const deque& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else deque& operator=(const deque&) = default; deque& operator=(deque&&) = default; deque& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif #if __cplusplus >= 201103L template> #else template #endif void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); } void assign(size_type __n, const _Tp& __t) { _Base::assign(__n, __t); this->_M_invalidate_all(); } #if __cplusplus >= 201103L void assign(initializer_list __l) { _Base::assign(__l); this->_M_invalidate_all(); } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif private: void _M_invalidate_after_nth(difference_type __n) { typedef __gnu_debug::_After_nth_from<_Base_const_iterator> _After_nth; this->_M_invalidate_if(_After_nth(__n, _Base::begin())); } public: // 23.2.1.2 capacity: using _Base::size; using _Base::max_size; #if __cplusplus >= 201103L void resize(size_type __sz) { bool __invalidate_all = __sz > this->size(); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz); if (__invalidate_all) this->_M_invalidate_all(); } void resize(size_type __sz, const _Tp& __c) { bool __invalidate_all = __sz > this->size(); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__invalidate_all) this->_M_invalidate_all(); } #else void resize(size_type __sz, _Tp __c = _Tp()) { bool __invalidate_all = __sz > this->size(); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__invalidate_all) this->_M_invalidate_all(); } #endif #if __cplusplus >= 201103L void shrink_to_fit() noexcept { if (_Base::_M_shrink_to_fit()) this->_M_invalidate_all(); } #endif using _Base::empty; // element access: reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } using _Base::at; reference front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } reference back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } // 23.2.1.3 modifiers: void push_front(const _Tp& __x) { _Base::push_front(__x); this->_M_invalidate_all(); } void push_back(const _Tp& __x) { _Base::push_back(__x); this->_M_invalidate_all(); } #if __cplusplus >= 201103L void push_front(_Tp&& __x) { emplace_front(std::move(__x)); } void push_back(_Tp&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_front(_Args&&... __args) { _Base::emplace_front(std::forward<_Args>(__args)...); this->_M_invalidate_all(); #if __cplusplus > 201402L return front(); #endif } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { _Base::emplace_back(std::forward<_Args>(__args)...); this->_M_invalidate_all(); #if __cplusplus > 201402L return back(); #endif } template iterator emplace(const_iterator __position, _Args&&... __args) { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::emplace(__position.base(), std::forward<_Args>(__args)...); this->_M_invalidate_all(); return iterator(__res, this); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const _Tp& __x) #else insert(iterator __position, const _Tp& __x) #endif { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::insert(__position.base(), __x); this->_M_invalidate_all(); return iterator(__res, this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, _Tp&& __x) { return emplace(__position, std::move(__x)); } iterator insert(const_iterator __position, initializer_list __l) { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::insert(__position.base(), __l); this->_M_invalidate_all(); return iterator(__res, this); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); _Base_iterator __res = _Base::insert(__position.base(), __n, __x); this->_M_invalidate_all(); return iterator(__res, this); } #else void insert(iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); _Base::insert(__position.base(), __n, __x); this->_M_invalidate_all(); } #endif #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); _Base_iterator __res; if (__dist.second >= __gnu_debug::__dp_sign) __res = _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else __res = _Base::insert(__position.base(), __first, __last); this->_M_invalidate_all(); return iterator(__res, this); } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__position.base(), __first, __last); this->_M_invalidate_all(); } #endif void pop_front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(_Base::begin())); _Base::pop_front(); } void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(--_Base::end())); _Base::pop_back(); } iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { __glibcxx_check_erase(__position); #if __cplusplus >= 201103L _Base_const_iterator __victim = __position.base(); #else _Base_iterator __victim = __position.base(); #endif if (__victim == _Base::begin() || __victim == _Base::end() - 1) { this->_M_invalidate_if(_Equal(__victim)); return iterator(_Base::erase(__victim), this); } else { _Base_iterator __res = _Base::erase(__victim); this->_M_invalidate_all(); return iterator(__res, this); } } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); if (__first.base() == __last.base()) #if __cplusplus >= 201103L return iterator(__first.base()._M_const_cast(), this); #else return __first; #endif else if (__first.base() == _Base::begin() || __last.base() == _Base::end()) { this->_M_detach_singular(); for (_Base_const_iterator __position = __first.base(); __position != __last.base(); ++__position) { this->_M_invalidate_if(_Equal(__position)); } __try { return iterator(_Base::erase(__first.base(), __last.base()), this); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } else { _Base_iterator __res = _Base::erase(__first.base(), __last.base()); this->_M_invalidate_all(); return iterator(__res, this); } } void swap(deque& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> deque(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> deque<_ValT, _Allocator>; #endif template inline bool operator==(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const deque<_Tp, _Alloc>& __lhs, const deque<_Tp, _Alloc>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(deque<_Tp, _Alloc>& __lhs, deque<_Tp, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std #endif c++/8/debug/safe_container.h000064400000006525151027430570011516 0ustar00// Safe container implementation -*- C++ -*- // Copyright (C) 2014-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_container.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_CONTAINER_H #define _GLIBCXX_DEBUG_SAFE_CONTAINER_H 1 #include namespace __gnu_debug { /// Safe class dealing with some allocator dependent operations. template class _SafeBase, bool _IsCxx11AllocatorAware = true> class _Safe_container : public _SafeBase<_SafeContainer> { typedef _SafeBase<_SafeContainer> _Base; _SafeContainer& _M_cont() _GLIBCXX_NOEXCEPT { return *static_cast<_SafeContainer*>(this); } protected: _Safe_container& _M_safe() _GLIBCXX_NOEXCEPT { return *this; } #if __cplusplus >= 201103L _Safe_container() = default; _Safe_container(const _Safe_container&) = default; _Safe_container(_Safe_container&&) = default; _Safe_container(_Safe_container&& __x, const _Alloc& __a) : _Safe_container() { if (__x._M_cont().get_allocator() == __a) _Base::_M_swap(__x); else __x._M_invalidate_all(); } #endif public: // Copy assignment invalidate all iterators. _Safe_container& operator=(const _Safe_container&) _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); return *this; } #if __cplusplus >= 201103L _Safe_container& operator=(_Safe_container&& __x) noexcept { __glibcxx_check_self_move_assign(__x); if (_IsCxx11AllocatorAware) { typedef __gnu_cxx::__alloc_traits<_Alloc> _Alloc_traits; bool __xfer_memory = _Alloc_traits::_S_propagate_on_move_assign() || _M_cont().get_allocator() == __x._M_cont().get_allocator(); if (__xfer_memory) _Base::_M_swap(__x); else this->_M_invalidate_all(); } else _Base::_M_swap(__x); __x._M_invalidate_all(); return *this; } void _M_swap(_Safe_container& __x) noexcept { if (_IsCxx11AllocatorAware) { typedef __gnu_cxx::__alloc_traits<_Alloc> _Alloc_traits; if (!_Alloc_traits::_S_propagate_on_swap()) __glibcxx_check_equal_allocs(this->_M_cont()._M_base(), __x._M_cont()._M_base()); } _Base::_M_swap(__x); } #endif }; } // namespace __gnu_debug #endif c++/8/debug/helper_functions.h000064400000015235151027430570012103 0ustar00// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/helper_functions.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_HELPER_FUNCTIONS_H #define _GLIBCXX_DEBUG_HELPER_FUNCTIONS_H 1 #include // for iterator_traits, // categories and _Iter_base #include // for __is_integer #include // for pair namespace __gnu_debug { /** The precision to which we can calculate the distance between * two iterators. */ enum _Distance_precision { __dp_none, // Not even an iterator type __dp_equality, //< Can compare iterator equality, only __dp_sign, //< Can determine equality and ordering __dp_exact //< Can determine distance precisely }; template::__type> struct _Distance_traits { private: typedef typename std::iterator_traits<_Iterator>::difference_type _ItDiffType; template::__type> struct _DiffTraits { typedef _DiffType __type; }; template struct _DiffTraits<_DiffType, std::__true_type> { typedef std::ptrdiff_t __type; }; typedef typename _DiffTraits<_ItDiffType>::__type _DiffType; public: typedef std::pair<_DiffType, _Distance_precision> __type; }; template struct _Distance_traits<_Integral, std::__true_type> { typedef std::pair __type; }; /** Determine the distance between two iterators with some known * precision. */ template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Iterator& __lhs, const _Iterator& __rhs, std::random_access_iterator_tag) { return std::make_pair(__rhs - __lhs, __dp_exact); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Iterator& __lhs, const _Iterator& __rhs, std::input_iterator_tag) { if (__lhs == __rhs) return std::make_pair(0, __dp_exact); return std::make_pair(1, __dp_equality); } template inline typename _Distance_traits<_Iterator>::__type __get_distance(const _Iterator& __lhs, const _Iterator& __rhs) { return __get_distance(__lhs, __rhs, std::__iterator_category(__lhs)); } /** We say that integral types for a valid range, and defer to other * routines to realize what to do with integral types instead of * iterators. */ template inline bool __valid_range_aux(const _Integral&, const _Integral&, typename _Distance_traits<_Integral>::__type& __dist, std::__true_type) { __dist = std::make_pair(0, __dp_none); return true; } /** We have iterators, so figure out what kind of iterators that are * to see if we can check the range ahead of time. */ template inline bool __valid_range_aux(const _InputIterator& __first, const _InputIterator& __last, typename _Distance_traits<_InputIterator>::__type& __dist, std::__false_type) { __dist = __get_distance(__first, __last); switch (__dist.second) { case __dp_none: break; case __dp_equality: if (__dist.first == 0) return true; break; case __dp_sign: case __dp_exact: return __dist.first >= 0; } // Can't tell so assume it is fine. return true; } /** Don't know what these iterators are, or if they are even * iterators (we may get an integral type for InputIterator), so * see if they are integral and pass them on to the next phase * otherwise. */ template inline bool __valid_range(const _InputIterator& __first, const _InputIterator& __last, typename _Distance_traits<_InputIterator>::__type& __dist) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; return __valid_range_aux(__first, __last, __dist, _Integral()); } template inline bool __valid_range(const _InputIterator& __first, const _InputIterator& __last) { typename _Distance_traits<_InputIterator>::__type __dist; return __valid_range(__first, __last, __dist); } #if __cplusplus < 201103L // Helper struct to detect random access safe iterators. template struct __is_safe_random_iterator { enum { __value = 0 }; typedef std::__false_type __type; }; template struct _Siter_base : std::_Iter_base<_Iterator, __is_safe_random_iterator<_Iterator>::__value> { }; /** Helper function to extract base iterator of random access safe iterator in order to reduce performance impact of debug mode. Limited to random access iterator because it is the only category for which it is possible to check for correct iterators order in the __valid_range function thanks to the < operator. */ template inline typename _Siter_base<_Iterator>::iterator_type __base(_Iterator __it) { return _Siter_base<_Iterator>::_S_base(__it); } #else template inline _Iterator __base(_Iterator __it) { return __it; } #endif #if __cplusplus < 201103L template struct _Unsafe_type { typedef _Iterator _Type; }; #endif /* Remove debug mode safe iterator layer, if any. */ template inline _Iterator __unsafe(_Iterator __it) { return __it; } } #endif c++/8/debug/bitset000064400000027177151027430570007610 0ustar00// Debugging bitset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/bitset * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_BITSET #define _GLIBCXX_DEBUG_BITSET #pragma GCC system_header #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::bitset with additional safety/checking/debug instrumentation. template class bitset : public _GLIBCXX_STD_C::bitset<_Nb> #if __cplusplus < 201103L , public __gnu_debug::_Safe_sequence_base #endif { typedef _GLIBCXX_STD_C::bitset<_Nb> _Base; public: // In C++11 we rely on normal reference type to preserve the property // of bitset to be use as a literal. // TODO: Find another solution. #if __cplusplus >= 201103L typedef typename _Base::reference reference; #else // bit reference: class reference : private _Base::reference , public __gnu_debug::_Safe_iterator_base { typedef typename _Base::reference _Base_ref; friend class bitset; reference(); reference(const _Base_ref& __base, bitset* __seq) _GLIBCXX_NOEXCEPT : _Base_ref(__base) , _Safe_iterator_base(__seq, false) { } public: reference(const reference& __x) _GLIBCXX_NOEXCEPT : _Base_ref(__x) , _Safe_iterator_base(__x, false) { } reference& operator=(bool __x) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_write) ._M_iterator(*this)); *static_cast<_Base_ref*>(this) = __x; return *this; } reference& operator=(const reference& __x) _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!__x._M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_read) ._M_iterator(__x)); _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_write) ._M_iterator(*this)); *static_cast<_Base_ref*>(this) = __x; return *this; } bool operator~() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_read) ._M_iterator(*this)); return ~(*static_cast(this)); } operator bool() const _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_read) ._M_iterator(*this)); return *static_cast(this); } reference& flip() _GLIBCXX_NOEXCEPT { _GLIBCXX_DEBUG_VERIFY(!this->_M_singular(), _M_message(__gnu_debug::__msg_bad_bitset_flip) ._M_iterator(*this)); _Base_ref::flip(); return *this; } }; #endif // 23.3.5.1 constructors: _GLIBCXX_CONSTEXPR bitset() _GLIBCXX_NOEXCEPT : _Base() { } #if __cplusplus >= 201103L constexpr bitset(unsigned long long __val) noexcept #else bitset(unsigned long __val) #endif : _Base(__val) { } template explicit bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __str, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __pos = 0, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __n = (std::basic_string<_CharT, _Traits, _Alloc>::npos)) : _Base(__str, __pos, __n) { } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. template bitset(const std::basic_string<_CharT, _Traits, _Alloc>& __str, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __pos, typename std::basic_string<_CharT, _Traits, _Alloc>::size_type __n, _CharT __zero, _CharT __one = _CharT('1')) : _Base(__str, __pos, __n, __zero, __one) { } bitset(const _Base& __x) : _Base(__x) { } #if __cplusplus >= 201103L template explicit bitset(const _CharT* __str, typename std::basic_string<_CharT>::size_type __n = std::basic_string<_CharT>::npos, _CharT __zero = _CharT('0'), _CharT __one = _CharT('1')) : _Base(__str, __n, __zero, __one) { } #endif // 23.3.5.2 bitset operations: bitset<_Nb>& operator&=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { _M_base() &= __rhs; return *this; } bitset<_Nb>& operator|=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { _M_base() |= __rhs; return *this; } bitset<_Nb>& operator^=(const bitset<_Nb>& __rhs) _GLIBCXX_NOEXCEPT { _M_base() ^= __rhs; return *this; } bitset<_Nb>& operator<<=(size_t __pos) _GLIBCXX_NOEXCEPT { _M_base() <<= __pos; return *this; } bitset<_Nb>& operator>>=(size_t __pos) _GLIBCXX_NOEXCEPT { _M_base() >>= __pos; return *this; } bitset<_Nb>& set() _GLIBCXX_NOEXCEPT { _Base::set(); return *this; } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 186. bitset::set() second parameter should be bool bitset<_Nb>& set(size_t __pos, bool __val = true) { _Base::set(__pos, __val); return *this; } bitset<_Nb>& reset() _GLIBCXX_NOEXCEPT { _Base::reset(); return *this; } bitset<_Nb>& reset(size_t __pos) { _Base::reset(__pos); return *this; } bitset<_Nb> operator~() const _GLIBCXX_NOEXCEPT { return bitset(~_M_base()); } bitset<_Nb>& flip() _GLIBCXX_NOEXCEPT { _Base::flip(); return *this; } bitset<_Nb>& flip(size_t __pos) { _Base::flip(__pos); return *this; } // element access: // _GLIBCXX_RESOLVE_LIB_DEFECTS // 11. Bitset minor problems reference operator[](size_t __pos) { __glibcxx_check_subscript(__pos); #if __cplusplus >= 201103L return _M_base()[__pos]; #else return reference(_M_base()[__pos], this); #endif } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 11. Bitset minor problems _GLIBCXX_CONSTEXPR bool operator[](size_t __pos) const { #if __cplusplus < 201103L // TODO: Check in debug-mode too. __glibcxx_check_subscript(__pos); #endif return _Base::operator[](__pos); } using _Base::to_ulong; #if __cplusplus >= 201103L using _Base::to_ullong; #endif template std::basic_string<_CharT, _Traits, _Alloc> to_string() const { return _M_base().template to_string<_CharT, _Traits, _Alloc>(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 396. what are characters zero and one. template std::basic_string<_CharT, _Traits, _Alloc> to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return _M_base().template to_string<_CharT, _Traits, _Alloc>(__zero, __one); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 434. bitset::to_string() hard to use. template std::basic_string<_CharT, _Traits, std::allocator<_CharT> > to_string() const { return to_string<_CharT, _Traits, std::allocator<_CharT> >(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 853. to_string needs updating with zero and one. template std::basic_string<_CharT, _Traits, std::allocator<_CharT> > to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return to_string<_CharT, _Traits, std::allocator<_CharT> >(__zero, __one); } template std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> > to_string() const { return to_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >(); } template std::basic_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> > to_string(_CharT __zero, _CharT __one = _CharT('1')) const { return to_string<_CharT, std::char_traits<_CharT>, std::allocator<_CharT> >(__zero, __one); } std::basic_string, std::allocator > to_string() const { return to_string,std::allocator >(); } std::basic_string, std::allocator > to_string(char __zero, char __one = '1') const { return to_string, std::allocator >(__zero, __one); } using _Base::count; using _Base::size; bool operator==(const bitset<_Nb>& __rhs) const _GLIBCXX_NOEXCEPT { return _M_base() == __rhs; } bool operator!=(const bitset<_Nb>& __rhs) const _GLIBCXX_NOEXCEPT { return _M_base() != __rhs; } using _Base::test; using _Base::all; using _Base::any; using _Base::none; bitset<_Nb> operator<<(size_t __pos) const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(_M_base() << __pos); } bitset<_Nb> operator>>(size_t __pos) const _GLIBCXX_NOEXCEPT { return bitset<_Nb>(_M_base() >> __pos); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; template bitset<_Nb> operator&(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { return bitset<_Nb>(__x) &= __y; } template bitset<_Nb> operator|(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { return bitset<_Nb>(__x) |= __y; } template bitset<_Nb> operator^(const bitset<_Nb>& __x, const bitset<_Nb>& __y) _GLIBCXX_NOEXCEPT { return bitset<_Nb>(__x) ^= __y; } template std::basic_istream<_CharT, _Traits>& operator>>(std::basic_istream<_CharT, _Traits>& __is, bitset<_Nb>& __x) { return __is >> __x._M_base(); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __os, const bitset<_Nb>& __x) { return __os << __x._M_base(); } } // namespace __debug #if __cplusplus >= 201103L // DR 1182. /// std::hash specialization for bitset. template struct hash<__debug::bitset<_Nb>> : public __hash_base> { size_t operator()(const __debug::bitset<_Nb>& __b) const noexcept { return std::hash<_GLIBCXX_STD_C::bitset<_Nb>>()(__b._M_base()); } }; #endif } // namespace std #endif c++/8/debug/map000064400000002501151027430570007053 0ustar00// Debugging map/multimap implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/map * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MAP #define _GLIBCXX_DEBUG_MAP 1 #pragma GCC system_header #include #include #include #endif c++/8/debug/functions.h000064400000040317151027430570010543 0ustar00// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/functions.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_FUNCTIONS_H #define _GLIBCXX_DEBUG_FUNCTIONS_H 1 #include // for __addressof #include // for less #if __cplusplus >= 201103L # include // for is_lvalue_reference and conditional. #endif #include #include namespace __gnu_debug { template class _Safe_iterator; template struct _Insert_range_from_self_is_safe { enum { __value = 0 }; }; template struct _Is_contiguous_sequence : std::__false_type { }; // An arbitrary iterator pointer is not singular. inline bool __check_singular_aux(const void*) { return false; } // We may have an iterator that derives from _Safe_iterator_base but isn't // a _Safe_iterator. template inline bool __check_singular(const _Iterator& __x) { return __check_singular_aux(std::__addressof(__x)); } /** Non-NULL pointers are nonsingular. */ template inline bool __check_singular(const _Tp* __ptr) { return __ptr == 0; } /** Assume that some arbitrary iterator is dereferenceable, because we can't prove that it isn't. */ template inline bool __check_dereferenceable(const _Iterator&) { return true; } /** Non-NULL pointers are dereferenceable. */ template inline bool __check_dereferenceable(const _Tp* __ptr) { return __ptr; } /* Checks that [first, last) is a valid range, and then returns * __first. This routine is useful when we can't use a separate * assertion statement because, e.g., we are in a constructor. */ template inline _InputIterator __check_valid_range(const _InputIterator& __first, const _InputIterator& __last __attribute__((__unused__))) { __glibcxx_check_valid_range(__first, __last); return __first; } /* Handle the case where __other is a pointer to _Sequence::value_type. */ template inline bool __foreign_iterator_aux4(const _Safe_iterator<_Iterator, _Sequence>& __it, const typename _Sequence::value_type* __other) { typedef const typename _Sequence::value_type* _PointerType; typedef std::less<_PointerType> _Less; #if __cplusplus >= 201103L constexpr _Less __l{}; #else const _Less __l = _Less(); #endif const _Sequence* __seq = __it._M_get_sequence(); const _PointerType __begin = std::__addressof(*__seq->_M_base().begin()); const _PointerType __end = std::__addressof(*(__seq->_M_base().end()-1)); // Check whether __other points within the contiguous storage. return __l(__other, __begin) || __l(__end, __other); } /* Fallback overload for when we can't tell, assume it is valid. */ template inline bool __foreign_iterator_aux4(const _Safe_iterator<_Iterator, _Sequence>&, ...) { return true; } /* Handle sequences with contiguous storage */ template inline bool __foreign_iterator_aux3(const _Safe_iterator<_Iterator, _Sequence>& __it, const _InputIterator& __other, const _InputIterator& __other_end, std::__true_type) { if (__other == __other_end) return true; // inserting nothing is safe even if not foreign iters if (__it._M_get_sequence()->begin() == __it._M_get_sequence()->end()) return true; // can't be self-inserting if self is empty return __foreign_iterator_aux4(__it, std::__addressof(*__other)); } /* Handle non-contiguous containers, assume it is valid. */ template inline bool __foreign_iterator_aux3(const _Safe_iterator<_Iterator, _Sequence>&, const _InputIterator&, const _InputIterator&, std::__false_type) { return true; } /** Handle debug iterators from the same type of container. */ template inline bool __foreign_iterator_aux2(const _Safe_iterator<_Iterator, _Sequence>& __it, const _Safe_iterator<_OtherIterator, _Sequence>& __other, const _Safe_iterator<_OtherIterator, _Sequence>&) { return __it._M_get_sequence() != __other._M_get_sequence(); } /** Handle debug iterators from different types of container. */ template inline bool __foreign_iterator_aux2(const _Safe_iterator<_Iterator, _Sequence>& __it, const _Safe_iterator<_OtherIterator, _OtherSequence>&, const _Safe_iterator<_OtherIterator, _OtherSequence>&) { return true; } /* Handle non-debug iterators. */ template inline bool __foreign_iterator_aux2(const _Safe_iterator<_Iterator, _Sequence>& __it, const _InputIterator& __other, const _InputIterator& __other_end) { #if __cplusplus < 201103L typedef _Is_contiguous_sequence<_Sequence> __tag; #else using __lvalref = std::is_lvalue_reference< typename std::iterator_traits<_InputIterator>::reference>; using __contiguous = _Is_contiguous_sequence<_Sequence>; using __tag = typename std::conditional<__lvalref::value, __contiguous, std::__false_type>::type; #endif return __foreign_iterator_aux3(__it, __other, __other_end, __tag()); } /* Handle the case where we aren't really inserting a range after all */ template inline bool __foreign_iterator_aux(const _Safe_iterator<_Iterator, _Sequence>&, _Integral, _Integral, std::__true_type) { return true; } /* Handle all iterators. */ template inline bool __foreign_iterator_aux(const _Safe_iterator<_Iterator, _Sequence>& __it, _InputIterator __other, _InputIterator __other_end, std::__false_type) { return _Insert_range_from_self_is_safe<_Sequence>::__value || __foreign_iterator_aux2(__it, std::__miter_base(__other), std::__miter_base(__other_end)); } template inline bool __foreign_iterator(const _Safe_iterator<_Iterator, _Sequence>& __it, _InputIterator __other, _InputIterator __other_end) { typedef typename std::__is_integer<_InputIterator>::__type _Integral; return __foreign_iterator_aux(__it, __other, __other_end, _Integral()); } /** Checks that __s is non-NULL or __n == 0, and then returns __s. */ template inline const _CharT* __check_string(const _CharT* __s, const _Integer& __n __attribute__((__unused__))) { #ifdef _GLIBCXX_DEBUG_PEDANTIC __glibcxx_assert(__s != 0 || __n == 0); #endif return __s; } /** Checks that __s is non-NULL and then returns __s. */ template inline const _CharT* __check_string(const _CharT* __s) { #ifdef _GLIBCXX_DEBUG_PEDANTIC __glibcxx_assert(__s != 0); #endif return __s; } // Can't check if an input iterator sequence is sorted, because we // can't step through the sequence. template inline bool __check_sorted_aux(const _InputIterator&, const _InputIterator&, std::input_iterator_tag) { return true; } // Can verify if a forward iterator sequence is in fact sorted using // std::__is_sorted template inline bool __check_sorted_aux(_ForwardIterator __first, _ForwardIterator __last, std::forward_iterator_tag) { if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, (void)++__next) if (*__next < *__first) return false; return true; } // Can't check if an input iterator sequence is sorted, because we can't step // through the sequence. template inline bool __check_sorted_aux(const _InputIterator&, const _InputIterator&, _Predicate, std::input_iterator_tag) { return true; } // Can verify if a forward iterator sequence is in fact sorted using // std::__is_sorted template inline bool __check_sorted_aux(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, std::forward_iterator_tag) { if (__first == __last) return true; _ForwardIterator __next = __first; for (++__next; __next != __last; __first = __next, (void)++__next) if (__pred(*__next, *__first)) return false; return true; } // Determine if a sequence is sorted. template inline bool __check_sorted(const _InputIterator& __first, const _InputIterator& __last) { // Verify that the < operator for elements in the sequence is a // StrictWeakOrdering by checking that it is irreflexive. __glibcxx_assert(__first == __last || !(*__first < *__first)); return __check_sorted_aux(__first, __last, std::__iterator_category(__first)); } template inline bool __check_sorted(const _InputIterator& __first, const _InputIterator& __last, _Predicate __pred) { // Verify that the predicate is StrictWeakOrdering by checking that it // is irreflexive. __glibcxx_assert(__first == __last || !__pred(*__first, *__first)); return __check_sorted_aux(__first, __last, __pred, std::__iterator_category(__first)); } template inline bool __check_sorted_set_aux(const _InputIterator& __first, const _InputIterator& __last, std::__true_type) { return __check_sorted(__first, __last); } template inline bool __check_sorted_set_aux(const _InputIterator&, const _InputIterator&, std::__false_type) { return true; } template inline bool __check_sorted_set_aux(const _InputIterator& __first, const _InputIterator& __last, _Predicate __pred, std::__true_type) { return __check_sorted(__first, __last, __pred); } template inline bool __check_sorted_set_aux(const _InputIterator&, const _InputIterator&, _Predicate, std::__false_type) { return true; } // ... special variant used in std::merge, std::includes, std::set_*. template inline bool __check_sorted_set(const _InputIterator1& __first, const _InputIterator1& __last, const _InputIterator2&) { typedef typename std::iterator_traits<_InputIterator1>::value_type _ValueType1; typedef typename std::iterator_traits<_InputIterator2>::value_type _ValueType2; typedef typename std::__are_same<_ValueType1, _ValueType2>::__type _SameType; return __check_sorted_set_aux(__first, __last, _SameType()); } template inline bool __check_sorted_set(const _InputIterator1& __first, const _InputIterator1& __last, const _InputIterator2&, _Predicate __pred) { typedef typename std::iterator_traits<_InputIterator1>::value_type _ValueType1; typedef typename std::iterator_traits<_InputIterator2>::value_type _ValueType2; typedef typename std::__are_same<_ValueType1, _ValueType2>::__type _SameType; return __check_sorted_set_aux(__first, __last, __pred, _SameType()); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 270. Binary search requirements overly strict // Determine if a sequence is partitioned w.r.t. this element. template inline bool __check_partitioned_lower(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { while (__first != __last && *__first < __value) ++__first; if (__first != __last) { ++__first; while (__first != __last && !(*__first < __value)) ++__first; } return __first == __last; } template inline bool __check_partitioned_upper(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) { while (__first != __last && !(__value < *__first)) ++__first; if (__first != __last) { ++__first; while (__first != __last && __value < *__first) ++__first; } return __first == __last; } // Determine if a sequence is partitioned w.r.t. this element. template inline bool __check_partitioned_lower(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Pred __pred) { while (__first != __last && bool(__pred(*__first, __value))) ++__first; if (__first != __last) { ++__first; while (__first != __last && !bool(__pred(*__first, __value))) ++__first; } return __first == __last; } template inline bool __check_partitioned_upper(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value, _Pred __pred) { while (__first != __last && !bool(__pred(__value, *__first))) ++__first; if (__first != __last) { ++__first; while (__first != __last && bool(__pred(__value, *__first))) ++__first; } return __first == __last; } #if __cplusplus >= 201103L struct _Irreflexive_checker { template static typename std::iterator_traits<_It>::reference __ref(); template() < __ref<_It>())> static bool _S_is_valid(_It __it) { return !(*__it < *__it); } // Fallback method if operator doesn't exist. template static bool _S_is_valid(_Args...) { return true; } template()(__ref<_It>(), __ref<_It>()))> static bool _S_is_valid_pred(_It __it, _Pred __pred) { return !__pred(*__it, *__it); } // Fallback method if predicate can't be invoked. template static bool _S_is_valid_pred(_Args...) { return true; } }; template inline bool __is_irreflexive(_Iterator __it) { return _Irreflexive_checker::_S_is_valid(__it); } template inline bool __is_irreflexive_pred(_Iterator __it, _Pred __pred) { return _Irreflexive_checker::_S_is_valid_pred(__it, __pred); } #endif } // namespace __gnu_debug #endif c++/8/debug/vector000064400000053474151027430570007617 0ustar00// Debugging vector implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/vector * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_VECTOR #define _GLIBCXX_DEBUG_VECTOR 1 #pragma GCC system_header #include #include #include #include #include namespace __gnu_debug { /** @brief Base class for Debug Mode vector. * * Adds information about the guaranteed capacity, which is useful for * detecting code which relies on non-portable implementation details of * the libstdc++ reallocation policy. */ template class _Safe_vector { typedef typename _BaseSequence::size_type size_type; const _SafeSequence& _M_seq() const { return *static_cast(this); } protected: _Safe_vector() _GLIBCXX_NOEXCEPT : _M_guaranteed_capacity(0) { _M_update_guaranteed_capacity(); } _Safe_vector(const _Safe_vector&) _GLIBCXX_NOEXCEPT : _M_guaranteed_capacity(0) { _M_update_guaranteed_capacity(); } _Safe_vector(size_type __n) _GLIBCXX_NOEXCEPT : _M_guaranteed_capacity(__n) { } #if __cplusplus >= 201103L _Safe_vector(_Safe_vector&& __x) noexcept : _Safe_vector() { __x._M_guaranteed_capacity = 0; } _Safe_vector& operator=(const _Safe_vector&) noexcept { _M_update_guaranteed_capacity(); return *this; } _Safe_vector& operator=(_Safe_vector&& __x) noexcept { _M_update_guaranteed_capacity(); __x._M_guaranteed_capacity = 0; return *this; } #endif size_type _M_guaranteed_capacity; bool _M_requires_reallocation(size_type __elements) const _GLIBCXX_NOEXCEPT { return __elements > _M_seq().capacity(); } void _M_update_guaranteed_capacity() _GLIBCXX_NOEXCEPT { if (_M_seq().size() > _M_guaranteed_capacity) _M_guaranteed_capacity = _M_seq().size(); } }; } namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::vector with safety/checking/debug instrumentation. template > class vector : public __gnu_debug::_Safe_container< vector<_Tp, _Allocator>, _Allocator, __gnu_debug::_Safe_sequence>, public _GLIBCXX_STD_C::vector<_Tp, _Allocator>, public __gnu_debug::_Safe_vector< vector<_Tp, _Allocator>, _GLIBCXX_STD_C::vector<_Tp, _Allocator> > { typedef _GLIBCXX_STD_C::vector<_Tp, _Allocator> _Base; typedef __gnu_debug::_Safe_container< vector, _Allocator, __gnu_debug::_Safe_sequence> _Safe; typedef __gnu_debug::_Safe_vector _Safe_vector; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator< _Base_iterator, vector> iterator; typedef __gnu_debug::_Safe_iterator< _Base_const_iterator, vector> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef _Allocator allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.2.4.1 construct/copy/destroy: #if __cplusplus < 201103L vector() _GLIBCXX_NOEXCEPT : _Base() { } #else vector() = default; #endif explicit vector(const _Allocator& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus >= 201103L explicit vector(size_type __n, const _Allocator& __a = _Allocator()) : _Base(__n, __a), _Safe_vector(__n) { } vector(size_type __n, const _Tp& __value, const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #else explicit vector(size_type __n, const _Tp& __value = _Tp(), const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #endif #if __cplusplus >= 201103L template> #else template #endif vector(_InputIterator __first, _InputIterator __last, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } #if __cplusplus < 201103L vector(const vector& __x) : _Base(__x) { } ~vector() _GLIBCXX_NOEXCEPT { } #else vector(const vector&) = default; vector(vector&&) = default; vector(const vector& __x, const allocator_type& __a) : _Base(__x, __a) { } vector(vector&& __x, const allocator_type& __a) : _Safe(std::move(__x._M_safe()), __a), _Base(std::move(__x._M_base()), __a), _Safe_vector(std::move(__x)) { } vector(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__l, __a) { } ~vector() = default; #endif /// Construction from a normal-mode vector vector(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L vector& operator=(const vector& __x) { this->_M_safe() = __x; _M_base() = __x; this->_M_update_guaranteed_capacity(); return *this; } #else vector& operator=(const vector&) = default; vector& operator=(vector&&) = default; vector& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); return *this; } #endif #if __cplusplus >= 201103L template> #else template #endif void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } void assign(size_type __n, const _Tp& __u) { _Base::assign(__n, __u); this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #if __cplusplus >= 201103L void assign(initializer_list __l) { _Base::assign(__l); this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // 23.2.4.2 capacity: using _Base::size; using _Base::max_size; #if __cplusplus >= 201103L void resize(size_type __sz) { bool __realloc = this->_M_requires_reallocation(__sz); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } void resize(size_type __sz, const _Tp& __c) { bool __realloc = this->_M_requires_reallocation(__sz); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #else void resize(size_type __sz, _Tp __c = _Tp()) { bool __realloc = this->_M_requires_reallocation(__sz); if (__sz < this->size()) this->_M_invalidate_after_nth(__sz); _Base::resize(__sz, __c); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #endif #if __cplusplus >= 201103L void shrink_to_fit() { if (_Base::_M_shrink_to_fit()) { this->_M_guaranteed_capacity = _Base::capacity(); this->_M_invalidate_all(); } } #endif size_type capacity() const _GLIBCXX_NOEXCEPT { #ifdef _GLIBCXX_DEBUG_PEDANTIC return this->_M_guaranteed_capacity; #else return _Base::capacity(); #endif } using _Base::empty; void reserve(size_type __n) { bool __realloc = this->_M_requires_reallocation(__n); _Base::reserve(__n); if (__n > this->_M_guaranteed_capacity) this->_M_guaranteed_capacity = __n; if (__realloc) this->_M_invalidate_all(); } // element access: reference operator[](size_type __n) _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } const_reference operator[](size_type __n) const _GLIBCXX_NOEXCEPT { __glibcxx_check_subscript(__n); return _M_base()[__n]; } using _Base::at; reference front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } reference back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // DR 464. Suggestion for new member functions in standard containers. using _Base::data; // 23.2.4.3 modifiers: void push_back(const _Tp& __x) { bool __realloc = this->_M_requires_reallocation(this->size() + 1); _Base::push_back(__x); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); } #if __cplusplus >= 201103L template typename __gnu_cxx::__enable_if::__value, void>::__type push_back(_Tp&& __x) { emplace_back(std::move(__x)); } template #if __cplusplus > 201402L reference #else void #endif emplace_back(_Args&&... __args) { bool __realloc = this->_M_requires_reallocation(this->size() + 1); _Base::emplace_back(std::forward<_Args>(__args)...); if (__realloc) this->_M_invalidate_all(); this->_M_update_guaranteed_capacity(); #if __cplusplus > 201402L return back(); #endif } #endif void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(--_Base::end())); _Base::pop_back(); } #if __cplusplus >= 201103L template iterator emplace(const_iterator __position, _Args&&... __args) { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + 1); difference_type __offset = __position.base() - _Base::begin(); _Base_iterator __res = _Base::emplace(__position.base(), std::forward<_Args>(__args)...); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const _Tp& __x) #else insert(iterator __position, const _Tp& __x) #endif { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + 1); difference_type __offset = __position.base() - _Base::begin(); _Base_iterator __res = _Base::insert(__position.base(), __x); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #if __cplusplus >= 201103L template typename __gnu_cxx::__enable_if::__value, iterator>::__type insert(const_iterator __position, _Tp&& __x) { return emplace(__position, std::move(__x)); } iterator insert(const_iterator __position, initializer_list __l) { return this->insert(__position, __l.begin(), __l.end()); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + __n); difference_type __offset = __position.base() - _Base::cbegin(); _Base_iterator __res = _Base::insert(__position.base(), __n, __x); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #else void insert(iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); bool __realloc = this->_M_requires_reallocation(this->size() + __n); difference_type __offset = __position.base() - _Base::begin(); _Base::insert(__position.base(), __n, __x); if (__realloc) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); } #endif #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); /* Hard to guess if invalidation will occur, because __last - __first can't be calculated in all cases, so we just punt here by checking if it did occur. */ _Base_iterator __old_begin = _M_base().begin(); difference_type __offset = __position.base() - _Base::cbegin(); _Base_iterator __res; if (__dist.second >= __gnu_debug::__dp_sign) __res = _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else __res = _Base::insert(__position.base(), __first, __last); if (_M_base().begin() != __old_begin) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); return iterator(__res, this); } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); /* Hard to guess if invalidation will occur, because __last - __first can't be calculated in all cases, so we just punt here by checking if it did occur. */ _Base_iterator __old_begin = _M_base().begin(); difference_type __offset = __position.base() - _Base::begin(); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__position.base(), __first, __last); if (_M_base().begin() != __old_begin) this->_M_invalidate_all(); else this->_M_invalidate_after_nth(__offset); this->_M_update_guaranteed_capacity(); } #endif iterator #if __cplusplus >= 201103L erase(const_iterator __position) #else erase(iterator __position) #endif { __glibcxx_check_erase(__position); difference_type __offset = __position.base() - _Base::begin(); _Base_iterator __res = _Base::erase(__position.base()); this->_M_invalidate_after_nth(__offset); return iterator(__res, this); } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) #else erase(iterator __first, iterator __last) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); if (__first.base() != __last.base()) { difference_type __offset = __first.base() - _Base::begin(); _Base_iterator __res = _Base::erase(__first.base(), __last.base()); this->_M_invalidate_after_nth(__offset); return iterator(__res, this); } else #if __cplusplus >= 201103L return begin() + (__first.base() - cbegin().base()); #else return __first; #endif } void swap(vector& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); std::swap(this->_M_guaranteed_capacity, __x._M_guaranteed_capacity); } void clear() _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } private: void _M_invalidate_after_nth(difference_type __n) _GLIBCXX_NOEXCEPT { typedef __gnu_debug::_After_nth_from<_Base_const_iterator> _After_nth; this->_M_invalidate_if(_After_nth(__n, _Base::begin())); } }; template inline bool operator==(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const vector<_Tp, _Alloc>& __lhs, const vector<_Tp, _Alloc>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(vector<_Tp, _Alloc>& __lhs, vector<_Tp, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> vector(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> vector<_ValT, _Allocator>; #endif } // namespace __debug #if __cplusplus >= 201103L _GLIBCXX_BEGIN_NAMESPACE_VERSION // DR 1182. /// std::hash specialization for vector. template struct hash<__debug::vector> : public __hash_base> { size_t operator()(const __debug::vector& __b) const noexcept { return std::hash<_GLIBCXX_STD_C::vector>()(__b); } }; _GLIBCXX_END_NAMESPACE_VERSION #endif } // namespace std namespace __gnu_debug { template struct _Is_contiguous_sequence > : std::__true_type { }; template struct _Is_contiguous_sequence > : std::__false_type { }; } #endif c++/8/debug/safe_sequence.tcc000064400000011575151027430570011667 0ustar00// Safe sequence implementation -*- C++ -*- // Copyright (C) 2010-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_sequence.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_SEQUENCE_TCC #define _GLIBCXX_DEBUG_SAFE_SEQUENCE_TCC 1 namespace __gnu_debug { template template void _Safe_sequence<_Sequence>:: _M_invalidate_if(_Predicate __pred) { typedef typename _Sequence::iterator iterator; typedef typename _Sequence::const_iterator const_iterator; __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); for (_Safe_iterator_base* __iter = _M_iterators; __iter;) { iterator* __victim = static_cast(__iter); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } for (_Safe_iterator_base* __iter2 = _M_const_iterators; __iter2;) { const_iterator* __victim = static_cast(__iter2); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_invalidate(); } } } template template void _Safe_sequence<_Sequence>:: _M_transfer_from_if(_Safe_sequence& __from, _Predicate __pred) { typedef typename _Sequence::iterator iterator; typedef typename _Sequence::const_iterator const_iterator; _Safe_iterator_base* __transfered_iterators = 0; _Safe_iterator_base* __transfered_const_iterators = 0; _Safe_iterator_base* __last_iterator = 0; _Safe_iterator_base* __last_const_iterator = 0; { // We lock __from first and detach iterator(s) to transfer __gnu_cxx::__scoped_lock sentry(__from._M_get_mutex()); for (_Safe_iterator_base* __iter = __from._M_iterators; __iter;) { _Safe_iterator_base* __victim_base = __iter; iterator* __victim = static_cast(__victim_base); __iter = __iter->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_detach_single(); if (__transfered_iterators) { __victim_base->_M_next = __transfered_iterators; __transfered_iterators->_M_prior = __victim_base; } else __last_iterator = __victim_base; __victim_base->_M_sequence = this; __victim_base->_M_version = this->_M_version; __transfered_iterators = __victim_base; } } for (_Safe_iterator_base* __iter2 = __from._M_const_iterators; __iter2;) { _Safe_iterator_base* __victim_base = __iter2; const_iterator* __victim = static_cast(__victim_base); __iter2 = __iter2->_M_next; if (!__victim->_M_singular() && __pred(__victim->base())) { __victim->_M_detach_single(); if (__transfered_const_iterators) { __victim_base->_M_next = __transfered_const_iterators; __transfered_const_iterators->_M_prior = __victim_base; } else __last_const_iterator = __victim; __victim_base->_M_sequence = this; __victim_base->_M_version = this->_M_version; __transfered_const_iterators = __victim_base; } } } // Now we can lock *this and add the transfered iterators if any if (__last_iterator || __last_const_iterator) { __gnu_cxx::__scoped_lock sentry(this->_M_get_mutex()); if (__last_iterator) { if (this->_M_iterators) { this->_M_iterators->_M_prior = __last_iterator; __last_iterator->_M_next = this->_M_iterators; } this->_M_iterators = __transfered_iterators; } if (__last_const_iterator) { if (this->_M_const_iterators) { this->_M_const_iterators->_M_prior = __last_const_iterator; __last_const_iterator->_M_next = this->_M_const_iterators; } this->_M_const_iterators = __transfered_const_iterators; } } } } // namespace __gnu_debug #endif c++/8/debug/multiset.h000064400000044310151027430570010376 0ustar00// Debugging multiset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/multiset.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MULTISET_H #define _GLIBCXX_DEBUG_MULTISET_H 1 #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::multiset with safety/checking/debug instrumentation. template, typename _Allocator = std::allocator<_Key> > class multiset : public __gnu_debug::_Safe_container< multiset<_Key, _Compare, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::multiset<_Key, _Compare, _Allocator> { typedef _GLIBCXX_STD_C::multiset<_Key, _Compare, _Allocator> _Base; typedef __gnu_debug::_Safe_container< multiset, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::const_iterator _Base_const_iterator; typedef typename _Base::iterator _Base_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; public: // types: typedef _Key key_type; typedef _Key value_type; typedef _Compare key_compare; typedef _Compare value_compare; typedef _Allocator allocator_type; typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, multiset> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, multiset> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.3.3.1 construct/copy/destroy: #if __cplusplus < 201103L multiset() : _Base() { } multiset(const multiset& __x) : _Base(__x) { } ~multiset() { } #else multiset() = default; multiset(const multiset&) = default; multiset(multiset&&) = default; multiset(initializer_list __l, const _Compare& __comp = _Compare(), const allocator_type& __a = allocator_type()) : _Base(__l, __comp, __a) { } explicit multiset(const allocator_type& __a) : _Base(__a) { } multiset(const multiset& __m, const allocator_type& __a) : _Base(__m, __a) { } multiset(multiset&& __m, const allocator_type& __a) noexcept( noexcept(_Base(std::move(__m._M_base()), __a)) ) : _Safe(std::move(__m._M_safe()), __a), _Base(std::move(__m._M_base()), __a) { } multiset(initializer_list __l, const allocator_type& __a) : _Base(__l, __a) { } template multiset(_InputIterator __first, _InputIterator __last, const allocator_type& __a) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } ~multiset() = default; #endif explicit multiset(const _Compare& __comp, const _Allocator& __a = _Allocator()) : _Base(__comp, __a) { } template multiset(_InputIterator __first, _InputIterator __last, const _Compare& __comp = _Compare(), const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __comp, __a) { } multiset(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L multiset& operator=(const multiset& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else multiset& operator=(const multiset&) = default; multiset& operator=(multiset&&) = default; multiset& operator=(initializer_list __l) { _M_base() = __l; this->_M_invalidate_all(); return *this; } #endif using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // capacity: using _Base::empty; using _Base::size; using _Base::max_size; // modifiers: #if __cplusplus >= 201103L template iterator emplace(_Args&&... __args) { return iterator(_Base::emplace(std::forward<_Args>(__args)...), this); } template iterator emplace_hint(const_iterator __pos, _Args&&... __args) { __glibcxx_check_insert(__pos); return iterator(_Base::emplace_hint(__pos.base(), std::forward<_Args>(__args)...), this); } #endif iterator insert(const value_type& __x) { return iterator(_Base::insert(__x), this); } #if __cplusplus >= 201103L iterator insert(value_type&& __x) { return iterator(_Base::insert(std::move(__x)), this); } #endif iterator insert(const_iterator __position, const value_type& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, value_type&& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), std::move(__x)), this); } #endif template void insert(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__first, __last); } #if __cplusplus >= 201103L void insert(initializer_list __l) { _Base::insert(__l); } #endif #if __cplusplus > 201402L using node_type = typename _Base::node_type; node_type extract(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return _Base::extract(__position.base()); } node_type extract(const key_type& __key) { const auto __position = find(__key); if (__position != end()) return extract(__position); return {}; } iterator insert(node_type&& __nh) { return iterator(_Base::insert(std::move(__nh)), this); } iterator insert(const_iterator __hint, node_type&& __nh) { __glibcxx_check_insert(__hint); return iterator(_Base::insert(__hint.base(), std::move(__nh)), this); } using _Base::merge; #endif // C++17 #if __cplusplus >= 201103L iterator erase(const_iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); return iterator(_Base::erase(__position.base()), this); } #else void erase(iterator __position) { __glibcxx_check_erase(__position); this->_M_invalidate_if(_Equal(__position.base())); _Base::erase(__position.base()); } #endif size_type erase(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __victims = _Base::equal_range(__x); size_type __count = 0; _Base_iterator __victim = __victims.first; while (__victim != __victims.second) { this->_M_invalidate_if(_Equal(__victim)); _Base::erase(__victim++); ++__count; } return __count; } #if __cplusplus >= 201103L iterator erase(const_iterator __first, const_iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } #else void erase(iterator __first, iterator __last) { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } _Base::erase(__first.base(), __last.base()); } #endif void swap(multiset& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { this->_M_invalidate_all(); _Base::clear(); } // observers: using _Base::key_comp; using _Base::value_comp; // multiset operations: iterator find(const key_type& __x) { return iterator(_Base::find(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator find(const key_type& __x) const { return const_iterator(_Base::find(__x), this); } #if __cplusplus > 201103L template::type> iterator find(const _Kt& __x) { return { _Base::find(__x), this }; } template::type> const_iterator find(const _Kt& __x) const { return { _Base::find(__x), this }; } #endif using _Base::count; iterator lower_bound(const key_type& __x) { return iterator(_Base::lower_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator lower_bound(const key_type& __x) const { return const_iterator(_Base::lower_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator lower_bound(const _Kt& __x) { return { _Base::lower_bound(__x), this }; } template::type> const_iterator lower_bound(const _Kt& __x) const { return { _Base::lower_bound(__x), this }; } #endif iterator upper_bound(const key_type& __x) { return iterator(_Base::upper_bound(__x), this); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload const_iterator upper_bound(const key_type& __x) const { return const_iterator(_Base::upper_bound(__x), this); } #if __cplusplus > 201103L template::type> iterator upper_bound(const _Kt& __x) { return { _Base::upper_bound(__x), this }; } template::type> const_iterator upper_bound(const _Kt& __x) const { return { _Base::upper_bound(__x), this }; } #endif std::pair equal_range(const key_type& __x) { std::pair<_Base_iterator, _Base_iterator> __res = _Base::equal_range(__x); return std::make_pair(iterator(__res.first, this), iterator(__res.second, this)); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 214. set::find() missing const overload std::pair equal_range(const key_type& __x) const { std::pair<_Base_const_iterator, _Base_const_iterator> __res = _Base::equal_range(__x); return std::make_pair(const_iterator(__res.first, this), const_iterator(__res.second, this)); } #if __cplusplus > 201103L template::type> std::pair equal_range(const _Kt& __x) { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } template::type> std::pair equal_range(const _Kt& __x) const { auto __res = _Base::equal_range(__x); return { { __res.first, this }, { __res.second, this } }; } #endif _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type>, typename _Allocator = allocator::value_type>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset::value_type, _Compare, _Allocator>; template, typename _Allocator = allocator<_Key>, typename = _RequireAllocator<_Allocator>> multiset(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator()) -> multiset<_Key, _Compare, _Allocator>; template, typename = _RequireAllocator<_Allocator>> multiset(_InputIterator, _InputIterator, _Allocator) -> multiset::value_type, less::value_type>, _Allocator>; template> multiset(initializer_list<_Key>, _Allocator) -> multiset<_Key, less<_Key>, _Allocator>; #endif template inline bool operator==(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const multiset<_Key, _Compare, _Allocator>& __lhs, const multiset<_Key, _Compare, _Allocator>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template void swap(multiset<_Key, _Compare, _Allocator>& __x, multiset<_Key, _Compare, _Allocator>& __y) _GLIBCXX_NOEXCEPT_IF(noexcept(__x.swap(__y))) { return __x.swap(__y); } } // namespace __debug } // namespace std #endif c++/8/debug/set000064400000002501151027430570007071 0ustar00// Debugging set/multiset implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/set * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SET #define _GLIBCXX_DEBUG_SET 1 #pragma GCC system_header #include #include #include #endif c++/8/debug/safe_local_iterator.tcc000064400000004106151027430570013052 0ustar00// Debugging iterator implementation (out of line) -*- C++ -*- // Copyright (C) 2011-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/safe_local_iterator.tcc * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_TCC #define _GLIBCXX_DEBUG_SAFE_LOCAL_ITERATOR_TCC 1 namespace __gnu_debug { template bool _Safe_local_iterator<_Iterator, _Sequence>:: _M_valid_range(const _Safe_local_iterator& __rhs, std::pair& __dist) const { if (!_M_can_compare(__rhs)) return false; if (bucket() != __rhs.bucket()) return false; /* Determine if we can order the iterators without the help of the container */ __dist = __get_distance(*this, __rhs); switch (__dist.second) { case __dp_equality: if (__dist.first == 0) return true; break; case __dp_sign: case __dp_exact: return __dist.first >= 0; } // Assume that this is a valid range; we can't check anything else return true; } } // namespace __gnu_debug #endif c++/8/debug/list000064400000054426151027430570007266 0ustar00// Debugging list implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/list * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_LIST #define _GLIBCXX_DEBUG_LIST 1 #pragma GCC system_header #include #include #include #include namespace std _GLIBCXX_VISIBILITY(default) { namespace __debug { /// Class std::list with safety/checking/debug instrumentation. template > class list : public __gnu_debug::_Safe_container< list<_Tp, _Allocator>, _Allocator, __gnu_debug::_Safe_node_sequence>, public _GLIBCXX_STD_C::list<_Tp, _Allocator> { typedef _GLIBCXX_STD_C::list<_Tp, _Allocator> _Base; typedef __gnu_debug::_Safe_container< list, _Allocator, __gnu_debug::_Safe_node_sequence> _Safe; typedef typename _Base::iterator _Base_iterator; typedef typename _Base::const_iterator _Base_const_iterator; typedef __gnu_debug::_Equal_to<_Base_const_iterator> _Equal; typedef __gnu_debug::_Not_equal_to<_Base_const_iterator> _Not_equal; public: typedef typename _Base::reference reference; typedef typename _Base::const_reference const_reference; typedef __gnu_debug::_Safe_iterator<_Base_iterator, list> iterator; typedef __gnu_debug::_Safe_iterator<_Base_const_iterator, list> const_iterator; typedef typename _Base::size_type size_type; typedef typename _Base::difference_type difference_type; typedef _Tp value_type; typedef _Allocator allocator_type; typedef typename _Base::pointer pointer; typedef typename _Base::const_pointer const_pointer; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; // 23.2.2.1 construct/copy/destroy: #if __cplusplus < 201103L list() : _Base() { } list(const list& __x) : _Base(__x) { } ~list() { } #else list() = default; list(const list&) = default; list(list&&) = default; list(initializer_list __l, const allocator_type& __a = allocator_type()) : _Base(__l, __a) { } ~list() = default; list(const list& __x, const allocator_type& __a) : _Base(__x, __a) { } list(list&& __x, const allocator_type& __a) : _Base(std::move(__x), __a) { } #endif explicit list(const _Allocator& __a) _GLIBCXX_NOEXCEPT : _Base(__a) { } #if __cplusplus >= 201103L explicit list(size_type __n, const allocator_type& __a = allocator_type()) : _Base(__n, __a) { } list(size_type __n, const _Tp& __value, const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #else explicit list(size_type __n, const _Tp& __value = _Tp(), const _Allocator& __a = _Allocator()) : _Base(__n, __value, __a) { } #endif #if __cplusplus >= 201103L template> #else template #endif list(_InputIterator __first, _InputIterator __last, const _Allocator& __a = _Allocator()) : _Base(__gnu_debug::__base(__gnu_debug::__check_valid_range(__first, __last)), __gnu_debug::__base(__last), __a) { } list(const _Base& __x) : _Base(__x) { } #if __cplusplus < 201103L list& operator=(const list& __x) { this->_M_safe() = __x; _M_base() = __x; return *this; } #else list& operator=(const list&) = default; list& operator=(list&&) = default; list& operator=(initializer_list __l) { this->_M_invalidate_all(); _M_base() = __l; return *this; } void assign(initializer_list __l) { _Base::assign(__l); this->_M_invalidate_all(); } #endif #if __cplusplus >= 201103L template> #else template #endif void assign(_InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_valid_range2(__first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::assign(__gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::assign(__first, __last); this->_M_invalidate_all(); } void assign(size_type __n, const _Tp& __t) { _Base::assign(__n, __t); this->_M_invalidate_all(); } using _Base::get_allocator; // iterators: iterator begin() _GLIBCXX_NOEXCEPT { return iterator(_Base::begin(), this); } const_iterator begin() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::begin(), this); } iterator end() _GLIBCXX_NOEXCEPT { return iterator(_Base::end(), this); } const_iterator end() const _GLIBCXX_NOEXCEPT { return const_iterator(_Base::end(), this); } reverse_iterator rbegin() _GLIBCXX_NOEXCEPT { return reverse_iterator(end()); } const_reverse_iterator rbegin() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(end()); } reverse_iterator rend() _GLIBCXX_NOEXCEPT { return reverse_iterator(begin()); } const_reverse_iterator rend() const _GLIBCXX_NOEXCEPT { return const_reverse_iterator(begin()); } #if __cplusplus >= 201103L const_iterator cbegin() const noexcept { return const_iterator(_Base::begin(), this); } const_iterator cend() const noexcept { return const_iterator(_Base::end(), this); } const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } #endif // 23.2.2.2 capacity: using _Base::empty; using _Base::size; using _Base::max_size; #if __cplusplus >= 201103L void resize(size_type __sz) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin + __sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) this->_M_invalidate_if(_Equal(__victim)); __try { _Base::resize(__sz); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } void resize(size_type __sz, const _Tp& __c) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin + __sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) this->_M_invalidate_if(_Equal(__victim)); __try { _Base::resize(__sz, __c); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } #else void resize(size_type __sz, _Tp __c = _Tp()) { this->_M_detach_singular(); // if __sz < size(), invalidate all iterators in [begin + __sz, end()) _Base_iterator __victim = _Base::begin(); _Base_iterator __end = _Base::end(); for (size_type __i = __sz; __victim != __end && __i > 0; --__i) ++__victim; for (; __victim != __end; ++__victim) this->_M_invalidate_if(_Equal(__victim)); __try { _Base::resize(__sz, __c); } __catch(...) { this->_M_revalidate_singular(); __throw_exception_again; } } #endif // element access: reference front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } const_reference front() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::front(); } reference back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } const_reference back() const _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); return _Base::back(); } // 23.2.2.3 modifiers: using _Base::push_front; #if __cplusplus >= 201103L using _Base::emplace_front; #endif void pop_front() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(_Base::begin())); _Base::pop_front(); } using _Base::push_back; #if __cplusplus >= 201103L using _Base::emplace_back; #endif void pop_back() _GLIBCXX_NOEXCEPT { __glibcxx_check_nonempty(); this->_M_invalidate_if(_Equal(--_Base::end())); _Base::pop_back(); } #if __cplusplus >= 201103L template iterator emplace(const_iterator __position, _Args&&... __args) { __glibcxx_check_insert(__position); return iterator(_Base::emplace(__position.base(), std::forward<_Args>(__args)...), this); } #endif iterator #if __cplusplus >= 201103L insert(const_iterator __position, const _Tp& __x) #else insert(iterator __position, const _Tp& __x) #endif { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __x), this); } #if __cplusplus >= 201103L iterator insert(const_iterator __position, _Tp&& __x) { return emplace(__position, std::move(__x)); } iterator insert(const_iterator __p, initializer_list __l) { __glibcxx_check_insert(__p); return iterator(_Base::insert(__p.base(), __l), this); } #endif #if __cplusplus >= 201103L iterator insert(const_iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); return iterator(_Base::insert(__position.base(), __n, __x), this); } #else void insert(iterator __position, size_type __n, const _Tp& __x) { __glibcxx_check_insert(__position); _Base::insert(__position.base(), __n, __x); } #endif #if __cplusplus >= 201103L template> iterator insert(const_iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) return { _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)), this }; else return { _Base::insert(__position.base(), __first, __last), this }; } #else template void insert(iterator __position, _InputIterator __first, _InputIterator __last) { typename __gnu_debug::_Distance_traits<_InputIterator>::__type __dist; __glibcxx_check_insert_range(__position, __first, __last, __dist); if (__dist.second >= __gnu_debug::__dp_sign) _Base::insert(__position.base(), __gnu_debug::__unsafe(__first), __gnu_debug::__unsafe(__last)); else _Base::insert(__position.base(), __first, __last); } #endif private: _Base_iterator #if __cplusplus >= 201103L _M_erase(_Base_const_iterator __position) noexcept #else _M_erase(_Base_iterator __position) #endif { this->_M_invalidate_if(_Equal(__position)); return _Base::erase(__position); } public: iterator #if __cplusplus >= 201103L erase(const_iterator __position) noexcept #else erase(iterator __position) #endif { __glibcxx_check_erase(__position); return iterator(_M_erase(__position.base()), this); } iterator #if __cplusplus >= 201103L erase(const_iterator __first, const_iterator __last) noexcept #else erase(iterator __first, iterator __last) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 151. can't currently clear() empty container __glibcxx_check_erase_range(__first, __last); for (_Base_const_iterator __victim = __first.base(); __victim != __last.base(); ++__victim) { _GLIBCXX_DEBUG_VERIFY(__victim != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "position") ._M_iterator(__last, "last")); this->_M_invalidate_if(_Equal(__victim)); } return iterator(_Base::erase(__first.base(), __last.base()), this); } void swap(list& __x) _GLIBCXX_NOEXCEPT_IF( noexcept(declval<_Base&>().swap(__x)) ) { _Safe::_M_swap(__x); _Base::swap(__x); } void clear() _GLIBCXX_NOEXCEPT { _Base::clear(); this->_M_invalidate_all(); } // 23.2.2.4 list operations: void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x) noexcept #else splice(iterator __position, list& __x) #endif { _GLIBCXX_DEBUG_VERIFY(std::__addressof(__x) != this, _M_message(__gnu_debug::__msg_self_splice) ._M_sequence(*this, "this")); this->_M_transfer_from_if(__x, _Not_equal(__x._M_base().end())); _Base::splice(__position.base(), _GLIBCXX_MOVE(__x._M_base())); } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x) noexcept { splice(__position, std::move(__x)); } #endif void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x, const_iterator __i) noexcept #else splice(iterator __position, list& __x, iterator __i) #endif { __glibcxx_check_insert(__position); // We used to perform the splice_alloc check: not anymore, redundant // after implementing the relevant bits of N1599. _GLIBCXX_DEBUG_VERIFY(__i._M_dereferenceable(), _M_message(__gnu_debug::__msg_splice_bad) ._M_iterator(__i, "__i")); _GLIBCXX_DEBUG_VERIFY(__i._M_attached_to(std::__addressof(__x)), _M_message(__gnu_debug::__msg_splice_other) ._M_iterator(__i, "__i")._M_sequence(__x, "__x")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators this->_M_transfer_from_if(__x, _Equal(__i.base())); _Base::splice(__position.base(), _GLIBCXX_MOVE(__x._M_base()), __i.base()); } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x, const_iterator __i) noexcept { splice(__position, std::move(__x), __i); } #endif void #if __cplusplus >= 201103L splice(const_iterator __position, list&& __x, const_iterator __first, const_iterator __last) noexcept #else splice(iterator __position, list& __x, iterator __first, iterator __last) #endif { __glibcxx_check_insert(__position); __glibcxx_check_valid_range(__first, __last); _GLIBCXX_DEBUG_VERIFY(__first._M_attached_to(std::__addressof(__x)), _M_message(__gnu_debug::__msg_splice_other) ._M_sequence(__x, "x") ._M_iterator(__first, "first")); // We used to perform the splice_alloc check: not anymore, redundant // after implementing the relevant bits of N1599. for (_Base_const_iterator __tmp = __first.base(); __tmp != __last.base(); ++__tmp) { _GLIBCXX_DEBUG_VERIFY(__tmp != _Base::end(), _M_message(__gnu_debug::__msg_valid_range) ._M_iterator(__first, "first") ._M_iterator(__last, "last")); _GLIBCXX_DEBUG_VERIFY(std::__addressof(__x) != this || __tmp != __position.base(), _M_message(__gnu_debug::__msg_splice_overlap) ._M_iterator(__tmp, "position") ._M_iterator(__first, "first") ._M_iterator(__last, "last")); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 250. splicing invalidates iterators this->_M_transfer_from_if(__x, _Equal(__tmp)); } _Base::splice(__position.base(), _GLIBCXX_MOVE(__x._M_base()), __first.base(), __last.base()); } #if __cplusplus >= 201103L void splice(const_iterator __position, list& __x, const_iterator __first, const_iterator __last) noexcept { splice(__position, std::move(__x), __first, __last); } #endif void remove(const _Tp& __value) { for (_Base_iterator __x = _Base::begin(); __x != _Base::end(); ) { if (*__x == __value) __x = _M_erase(__x); else ++__x; } } template void remove_if(_Predicate __pred) { for (_Base_iterator __x = _Base::begin(); __x != _Base::end(); ) { if (__pred(*__x)) __x = _M_erase(__x); else ++__x; } } void unique() { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = __first; ++__next; while (__next != __last) { if (*__first == *__next) __next = _M_erase(__next); else __first = __next++; } } template void unique(_BinaryPredicate __binary_pred) { _Base_iterator __first = _Base::begin(); _Base_iterator __last = _Base::end(); if (__first == __last) return; _Base_iterator __next = __first; ++__next; while (__next != __last) { if (__binary_pred(*__first, *__next)) __next = _M_erase(__next); else __first = __next++; } } void #if __cplusplus >= 201103L merge(list&& __x) #else merge(list& __x) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { __glibcxx_check_sorted(_Base::begin(), _Base::end()); __glibcxx_check_sorted(__x.begin().base(), __x.end().base()); this->_M_transfer_from_if(__x, _Not_equal(__x._M_base().end())); _Base::merge(_GLIBCXX_MOVE(__x._M_base())); } } #if __cplusplus >= 201103L void merge(list& __x) { merge(std::move(__x)); } #endif template void #if __cplusplus >= 201103L merge(list&& __x, _Compare __comp) #else merge(list& __x, _Compare __comp) #endif { // _GLIBCXX_RESOLVE_LIB_DEFECTS // 300. list::merge() specification incomplete if (this != std::__addressof(__x)) { __glibcxx_check_sorted_pred(_Base::begin(), _Base::end(), __comp); __glibcxx_check_sorted_pred(__x.begin().base(), __x.end().base(), __comp); this->_M_transfer_from_if(__x, _Not_equal(__x._M_base().end())); _Base::merge(_GLIBCXX_MOVE(__x._M_base()), __comp); } } #if __cplusplus >= 201103L template void merge(list& __x, _Compare __comp) { merge(std::move(__x), __comp); } #endif void sort() { _Base::sort(); } template void sort(_StrictWeakOrdering __pred) { _Base::sort(__pred); } using _Base::reverse; _Base& _M_base() _GLIBCXX_NOEXCEPT { return *this; } const _Base& _M_base() const _GLIBCXX_NOEXCEPT { return *this; } }; #if __cpp_deduction_guides >= 201606 template::value_type, typename _Allocator = allocator<_ValT>, typename = _RequireInputIter<_InputIterator>, typename = _RequireAllocator<_Allocator>> list(_InputIterator, _InputIterator, _Allocator = _Allocator()) -> list<_ValT, _Allocator>; #endif template inline bool operator==(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() == __rhs._M_base(); } template inline bool operator!=(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() != __rhs._M_base(); } template inline bool operator<(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() < __rhs._M_base(); } template inline bool operator<=(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() <= __rhs._M_base(); } template inline bool operator>=(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() >= __rhs._M_base(); } template inline bool operator>(const list<_Tp, _Alloc>& __lhs, const list<_Tp, _Alloc>& __rhs) { return __lhs._M_base() > __rhs._M_base(); } template inline void swap(list<_Tp, _Alloc>& __lhs, list<_Tp, _Alloc>& __rhs) _GLIBCXX_NOEXCEPT_IF(noexcept(__lhs.swap(__rhs))) { __lhs.swap(__rhs); } } // namespace __debug } // namespace std namespace __gnu_debug { #ifndef _GLIBCXX_USE_CXX11_ABI // If not using C++11 list::size() is not in O(1) so we do not use it. template struct _Sequence_traits > { typedef typename std::__debug::list<_Tp, _Alloc>::iterator _It; static typename _Distance_traits<_It>::__type _S_size(const std::__debug::list<_Tp, _Alloc>& __seq) { return __seq.empty() ? std::make_pair(0, __dp_exact) : std::make_pair(1, __dp_equality); } }; #endif #ifndef _GLIBCXX_DEBUG_PEDANTIC template struct _Insert_range_from_self_is_safe > { enum { __value = 1 }; }; #endif } #endif c++/8/debug/macros.h000064400000042720151027430570010017 0ustar00// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/macros.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MACROS_H #define _GLIBCXX_DEBUG_MACROS_H 1 /** * Macros used by the implementation to verify certain * properties. These macros may only be used directly by the debug * wrappers. Note that these are macros (instead of the more obviously * @a correct choice of making them functions) because we need line and * file information at the call site, to minimize the distance between * the user error and where the error is reported. * */ #define _GLIBCXX_DEBUG_VERIFY_AT(_Condition,_ErrorMessage,_File,_Line) \ do \ { \ if (! (_Condition)) \ __gnu_debug::_Error_formatter::_M_at(_File, _Line) \ ._ErrorMessage._M_error(); \ } while (false) #define _GLIBCXX_DEBUG_VERIFY(_Condition,_ErrorMessage) \ _GLIBCXX_DEBUG_VERIFY_AT(_Condition,_ErrorMessage,__FILE__,__LINE__) // Verify that [_First, _Last) forms a valid iterator range. #define __glibcxx_check_valid_range(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__valid_range(_First, _Last), \ _M_message(__gnu_debug::__msg_valid_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) #define __glibcxx_check_valid_range2(_First,_Last,_Dist) \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__valid_range(_First, _Last, _Dist), \ _M_message(__gnu_debug::__msg_valid_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) // Verify that [_First, _Last) forms a non-empty iterator range. #define __glibcxx_check_non_empty_range(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First != _Last, \ _M_message(__gnu_debug::__msg_non_empty_range) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that we can insert into *this with the iterator _Position. * Insertion into a container at a specific position requires that * the iterator be nonsingular, either dereferenceable or past-the-end, * and that it reference the sequence we are inserting into. Note that * this macro is only valid when the container is a_Safe_sequence and * the iterator is a _Safe_iterator. */ #define __glibcxx_check_insert(_Position) \ _GLIBCXX_DEBUG_VERIFY(!_Position._M_singular(), \ _M_message(__gnu_debug::__msg_insert_singular) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)); \ _GLIBCXX_DEBUG_VERIFY(_Position._M_attached_to(this), \ _M_message(__gnu_debug::__msg_insert_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can insert into *this after the iterator _Position. * Insertion into a container after a specific position requires that * the iterator be nonsingular, either dereferenceable or before-begin, * and that it reference the sequence we are inserting into. Note that * this macro is only valid when the container is a_Safe_sequence and * the iterator is a _Safe_iterator. */ #define __glibcxx_check_insert_after(_Position) \ __glibcxx_check_insert(_Position); \ _GLIBCXX_DEBUG_VERIFY(!_Position._M_is_end(), \ _M_message(__gnu_debug::__msg_insert_after_end) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can insert the values in the iterator range * [_First, _Last) into *this with the iterator _Position. Insertion * into a container at a specific position requires that the iterator * be nonsingular (i.e., either dereferenceable or past-the-end), * that it reference the sequence we are inserting into, and that the * iterator range [_First, _Last) is a valid (possibly empty) * range which does not reference the sequence we are inserting into. * Note that this macro is only valid when the container is a * _Safe_sequence and the _Position iterator is a _Safe_iterator. */ #define __glibcxx_check_insert_range(_Position,_First,_Last,_Dist) \ __glibcxx_check_valid_range2(_First,_Last,_Dist); \ __glibcxx_check_insert(_Position); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__foreign_iterator(_Position,_First,_Last),\ _M_message(__gnu_debug::__msg_insert_range_from_self)\ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_sequence(*this, "this")) /** Verify that we can insert the values in the iterator range * [_First, _Last) into *this after the iterator _Position. Insertion * into a container after a specific position requires that the iterator * be nonsingular (i.e., either dereferenceable or past-the-end), * that it reference the sequence we are inserting into, and that the * iterator range [_First, _Last) is a valid (possibly empty) * range which does not reference the sequence we are inserting into. * Note that this macro is only valid when the container is a * _Safe_sequence and the _Position iterator is a _Safe_iterator. */ #define __glibcxx_check_insert_range_after(_Position,_First,_Last,_Dist)\ __glibcxx_check_valid_range2(_First,_Last,_Dist); \ __glibcxx_check_insert_after(_Position); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__foreign_iterator(_Position,_First,_Last),\ _M_message(__gnu_debug::__msg_insert_range_from_self)\ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_sequence(*this, "this")) /** Verify that we can erase the element referenced by the iterator * _Position. We can erase the element if the _Position iterator is * dereferenceable and references this sequence. */ #define __glibcxx_check_erase(_Position) \ _GLIBCXX_DEBUG_VERIFY(_Position._M_dereferenceable(), \ _M_message(__gnu_debug::__msg_erase_bad) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)); \ _GLIBCXX_DEBUG_VERIFY(_Position._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can erase the element after the iterator * _Position. We can erase the element if the _Position iterator is * before a dereferenceable one and references this sequence. */ #define __glibcxx_check_erase_after(_Position) \ _GLIBCXX_DEBUG_VERIFY(_Position._M_before_dereferenceable(), \ _M_message(__gnu_debug::__msg_erase_after_bad) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)); \ _GLIBCXX_DEBUG_VERIFY(_Position._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_Position, #_Position)) /** Verify that we can erase the elements in the iterator range * [_First, _Last). We can erase the elements if [_First, _Last) is a * valid iterator range within this sequence. */ #define __glibcxx_check_erase_range(_First,_Last) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(_First._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that we can erase the elements in the iterator range * (_First, _Last). We can erase the elements if (_First, _Last) is a * valid iterator range within this sequence. */ #define __glibcxx_check_erase_range_after(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First._M_can_compare(_Last), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)); \ _GLIBCXX_DEBUG_VERIFY(_First._M_attached_to(this), \ _M_message(__gnu_debug::__msg_erase_different) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First)); \ _GLIBCXX_DEBUG_VERIFY(_First != _Last, \ _M_message(__gnu_debug::__msg_valid_range2) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)); \ _GLIBCXX_DEBUG_VERIFY(_First._M_incrementable(), \ _M_message(__gnu_debug::__msg_valid_range2) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)); \ _GLIBCXX_DEBUG_VERIFY(!_Last._M_is_before_begin(), \ _M_message(__gnu_debug::__msg_valid_range2) \ ._M_sequence(*this, "this") \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) \ // Verify that the subscript _N is less than the container's size. #define __glibcxx_check_subscript(_N) \ _GLIBCXX_DEBUG_VERIFY(_N < this->size(), \ _M_message(__gnu_debug::__msg_subscript_oob) \ ._M_sequence(*this, "this") \ ._M_integer(_N, #_N) \ ._M_integer(this->size(), "size")) // Verify that the bucket _N is less than the container's buckets count. #define __glibcxx_check_bucket_index(_N) \ _GLIBCXX_DEBUG_VERIFY(_N < this->bucket_count(), \ _M_message(__gnu_debug::__msg_bucket_index_oob) \ ._M_sequence(*this, "this") \ ._M_integer(_N, #_N) \ ._M_integer(this->bucket_count(), "size")) // Verify that the container is nonempty #define __glibcxx_check_nonempty() \ _GLIBCXX_DEBUG_VERIFY(! this->empty(), \ _M_message(__gnu_debug::__msg_empty) \ ._M_sequence(*this, "this")) // Verify that the iterator range [_First, _Last) is sorted #define __glibcxx_check_sorted(_First,_Last) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_sorted( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last)), \ _M_message(__gnu_debug::__msg_unsorted) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that the iterator range [_First, _Last) is sorted by the predicate _Pred. */ #define __glibcxx_check_sorted_pred(_First,_Last,_Pred) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_sorted( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Pred), \ _M_message(__gnu_debug::__msg_unsorted_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred)) // Special variant for std::merge, std::includes, std::set_* #define __glibcxx_check_sorted_set(_First1,_Last1,_First2) \ __glibcxx_check_valid_range(_First1,_Last1); \ _GLIBCXX_DEBUG_VERIFY( \ __gnu_debug::__check_sorted_set(__gnu_debug::__base(_First1), \ __gnu_debug::__base(_Last1), _First2),\ _M_message(__gnu_debug::__msg_unsorted) \ ._M_iterator(_First1, #_First1) \ ._M_iterator(_Last1, #_Last1)) // Likewise with a _Pred. #define __glibcxx_check_sorted_set_pred(_First1,_Last1,_First2,_Pred) \ __glibcxx_check_valid_range(_First1,_Last1); \ _GLIBCXX_DEBUG_VERIFY( \ __gnu_debug::__check_sorted_set(__gnu_debug::__base(_First1), \ __gnu_debug::__base(_Last1), \ _First2, _Pred), \ _M_message(__gnu_debug::__msg_unsorted_pred) \ ._M_iterator(_First1, #_First1) \ ._M_iterator(_Last1, #_Last1) \ ._M_string(#_Pred)) /** Verify that the iterator range [_First, _Last) is partitioned w.r.t. the value _Value. */ #define __glibcxx_check_partitioned_lower(_First,_Last,_Value) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_lower( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value), \ _M_message(__gnu_debug::__msg_unpartitioned) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Value)) #define __glibcxx_check_partitioned_upper(_First,_Last,_Value) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_upper( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value), \ _M_message(__gnu_debug::__msg_unpartitioned) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Value)) /** Verify that the iterator range [_First, _Last) is partitioned w.r.t. the value _Value and predicate _Pred. */ #define __glibcxx_check_partitioned_lower_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_lower( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value, _Pred), \ _M_message(__gnu_debug::__msg_unpartitioned_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred) \ ._M_string(#_Value)) /** Verify that the iterator range [_First, _Last) is partitioned w.r.t. the value _Value and predicate _Pred. */ #define __glibcxx_check_partitioned_upper_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_valid_range(_First,_Last); \ _GLIBCXX_DEBUG_VERIFY(__gnu_debug::__check_partitioned_upper( \ __gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), _Value, _Pred), \ _M_message(__gnu_debug::__msg_unpartitioned_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred) \ ._M_string(#_Value)) // Verify that the iterator range [_First, _Last) is a heap #define __glibcxx_check_heap(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(std::__is_heap(__gnu_debug::__base(_First), \ __gnu_debug::__base(_Last)), \ _M_message(__gnu_debug::__msg_not_heap) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last)) /** Verify that the iterator range [_First, _Last) is a heap w.r.t. the predicate _Pred. */ #define __glibcxx_check_heap_pred(_First,_Last,_Pred) \ _GLIBCXX_DEBUG_VERIFY(std::__is_heap(__gnu_debug::__base(_First), \ __gnu_debug::__base(_Last), \ _Pred), \ _M_message(__gnu_debug::__msg_not_heap_pred) \ ._M_iterator(_First, #_First) \ ._M_iterator(_Last, #_Last) \ ._M_string(#_Pred)) // Verify that the container is not self move assigned #define __glibcxx_check_self_move_assign(_Other) \ _GLIBCXX_DEBUG_VERIFY(this != &_Other, \ _M_message(__gnu_debug::__msg_self_move_assign) \ ._M_sequence(*this, "this")) // Verify that load factor is positive #define __glibcxx_check_max_load_factor(_F) \ _GLIBCXX_DEBUG_VERIFY(_F > 0.0f, \ _M_message(__gnu_debug::__msg_valid_load_factor) \ ._M_sequence(*this, "this")) #define __glibcxx_check_equal_allocs(_This, _Other) \ _GLIBCXX_DEBUG_VERIFY(_This.get_allocator() == _Other.get_allocator(), \ _M_message(__gnu_debug::__msg_equal_allocs) \ ._M_sequence(_This, "this")) #define __glibcxx_check_string(_String) _GLIBCXX_DEBUG_PEDASSERT(_String != 0) #define __glibcxx_check_string_len(_String,_Len) \ _GLIBCXX_DEBUG_PEDASSERT(_String != 0 || _Len == 0) // Verify that a predicate is irreflexive #define __glibcxx_check_irreflexive(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last || !(*_First < *_First), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_iterator_value_type(_First, "< operator type")) #if __cplusplus >= 201103L # define __glibcxx_check_irreflexive2(_First,_Last) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last \ || __gnu_debug::__is_irreflexive(_First), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_iterator_value_type(_First, "< operator type")) #else # define __glibcxx_check_irreflexive2(_First,_Last) #endif #define __glibcxx_check_irreflexive_pred(_First,_Last,_Pred) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last || !_Pred(*_First, *_First), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_instance(_Pred, "functor") \ ._M_iterator_value_type(_First, "ordered type")) #if __cplusplus >= 201103L # define __glibcxx_check_irreflexive_pred2(_First,_Last,_Pred) \ _GLIBCXX_DEBUG_VERIFY(_First == _Last \ ||__gnu_debug::__is_irreflexive_pred(_First, _Pred), \ _M_message(__gnu_debug::__msg_irreflexive_ordering) \ ._M_instance(_Pred, "functor") \ ._M_iterator_value_type(_First, "ordered type")) #else # define __glibcxx_check_irreflexive_pred2(_First,_Last,_Pred) #endif #endif c++/8/debug/debug.h000064400000012145151027430570007617 0ustar00// Debugging support implementation -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file debug/debug.h * This file is a GNU debug extension to the Standard C++ Library. */ #ifndef _GLIBCXX_DEBUG_MACRO_SWITCH_H #define _GLIBCXX_DEBUG_MACRO_SWITCH_H 1 /** Macros and namespaces used by the implementation outside of debug * wrappers to verify certain properties. The __glibcxx_requires_xxx * macros are merely wrappers around the __glibcxx_check_xxx wrappers * when we are compiling with debug mode, but disappear when we are * in release mode so that there is no checking performed in, e.g., * the standard library algorithms. */ #include // Debug mode namespaces. /** * @namespace std::__debug * @brief GNU debug code, replaces standard behavior with debug behavior. */ namespace std { namespace __debug { } } /** @namespace __gnu_debug * @brief GNU debug classes for public use. */ namespace __gnu_debug { using namespace std::__debug; } #ifndef _GLIBCXX_DEBUG # define __glibcxx_requires_cond(_Cond,_Msg) # define __glibcxx_requires_valid_range(_First,_Last) # define __glibcxx_requires_sorted(_First,_Last) # define __glibcxx_requires_sorted_pred(_First,_Last,_Pred) # define __glibcxx_requires_sorted_set(_First1,_Last1,_First2) # define __glibcxx_requires_sorted_set_pred(_First1,_Last1,_First2,_Pred) # define __glibcxx_requires_partitioned_lower(_First,_Last,_Value) # define __glibcxx_requires_partitioned_upper(_First,_Last,_Value) # define __glibcxx_requires_partitioned_lower_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_partitioned_upper_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_heap(_First,_Last) # define __glibcxx_requires_heap_pred(_First,_Last,_Pred) # define __glibcxx_requires_string(_String) # define __glibcxx_requires_string_len(_String,_Len) # define __glibcxx_requires_irreflexive(_First,_Last) # define __glibcxx_requires_irreflexive2(_First,_Last) # define __glibcxx_requires_irreflexive_pred(_First,_Last,_Pred) # define __glibcxx_requires_irreflexive_pred2(_First,_Last,_Pred) #else # include # define __glibcxx_requires_cond(_Cond,_Msg) _GLIBCXX_DEBUG_VERIFY(_Cond,_Msg) # define __glibcxx_requires_valid_range(_First,_Last) \ __glibcxx_check_valid_range(_First,_Last) # define __glibcxx_requires_sorted(_First,_Last) \ __glibcxx_check_sorted(_First,_Last) # define __glibcxx_requires_sorted_pred(_First,_Last,_Pred) \ __glibcxx_check_sorted_pred(_First,_Last,_Pred) # define __glibcxx_requires_sorted_set(_First1,_Last1,_First2) \ __glibcxx_check_sorted_set(_First1,_Last1,_First2) # define __glibcxx_requires_sorted_set_pred(_First1,_Last1,_First2,_Pred) \ __glibcxx_check_sorted_set_pred(_First1,_Last1,_First2,_Pred) # define __glibcxx_requires_partitioned_lower(_First,_Last,_Value) \ __glibcxx_check_partitioned_lower(_First,_Last,_Value) # define __glibcxx_requires_partitioned_upper(_First,_Last,_Value) \ __glibcxx_check_partitioned_upper(_First,_Last,_Value) # define __glibcxx_requires_partitioned_lower_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_partitioned_lower_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_partitioned_upper_pred(_First,_Last,_Value,_Pred) \ __glibcxx_check_partitioned_upper_pred(_First,_Last,_Value,_Pred) # define __glibcxx_requires_heap(_First,_Last) \ __glibcxx_check_heap(_First,_Last) # define __glibcxx_requires_heap_pred(_First,_Last,_Pred) \ __glibcxx_check_heap_pred(_First,_Last,_Pred) # define __glibcxx_requires_string(_String) __glibcxx_check_string(_String) # define __glibcxx_requires_string_len(_String,_Len) \ __glibcxx_check_string_len(_String,_Len) # define __glibcxx_requires_irreflexive(_First,_Last) \ __glibcxx_check_irreflexive(_First,_Last) # define __glibcxx_requires_irreflexive2(_First,_Last) \ __glibcxx_check_irreflexive2(_First,_Last) # define __glibcxx_requires_irreflexive_pred(_First,_Last,_Pred) \ __glibcxx_check_irreflexive_pred(_First,_Last,_Pred) # define __glibcxx_requires_irreflexive_pred2(_First,_Last,_Pred) \ __glibcxx_check_irreflexive_pred2(_First,_Last,_Pred) # include #endif #endif // _GLIBCXX_DEBUG_MACRO_SWITCH_H c++/8/x86_64-redhat-linux/bits/stdc++.h000064400000005607151027430570013034 0ustar00// C++ includes used for precompiling -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file stdc++.h * This is an implementation file for a precompiled header. */ // 17.4.1.2 Headers // C #ifndef _GLIBCXX_NO_ASSERT #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L #include #include #include #include #include #include #include #include #include #include #endif // C++ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif #if __cplusplus >= 201402L #include #endif #if __cplusplus >= 201703L #include #include #endif c++/8/x86_64-redhat-linux/bits/c++io.h000064400000003110151027430570012634 0ustar00// Underlying io library details -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++io.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ // c_io_stdio.h - Defines for using "C" stdio.h #ifndef _GLIBCXX_CXX_IO_H #define _GLIBCXX_CXX_IO_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION typedef __gthread_mutex_t __c_lock; // for basic_file.h typedef FILE __c_file; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/bits/gthr-posix.h000064400000057255151027430570014063 0ustar00/* Threads compatibility routines for libgcc2 and libobjc. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_POSIX_H #define _GLIBCXX_GCC_GTHR_POSIX_H /* POSIX threads specific definitions. Easy, since the interface is just one-to-one mapping. */ #define __GTHREADS 1 #define __GTHREADS_CXX0X 1 #include #if ((defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)) \ || !defined(_GTHREAD_USE_MUTEX_TIMEDLOCK)) # include # if defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS >= 0 # define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 # else # define _GTHREAD_USE_MUTEX_TIMEDLOCK 0 # endif #endif typedef pthread_t __gthread_t; typedef pthread_key_t __gthread_key_t; typedef pthread_once_t __gthread_once_t; typedef pthread_mutex_t __gthread_mutex_t; typedef pthread_mutex_t __gthread_recursive_mutex_t; typedef pthread_cond_t __gthread_cond_t; typedef struct timespec __gthread_time_t; /* POSIX like conditional variables are supported. Please look at comments in gthr.h for details. */ #define __GTHREAD_HAS_COND 1 #define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER #define __GTHREAD_MUTEX_INIT_FUNCTION __gthread_mutex_init_function #define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT #if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER #elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #else #define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #define __GTHREAD_COND_INIT PTHREAD_COND_INITIALIZER #define __GTHREAD_TIME_INIT {0,0} #ifdef _GTHREAD_USE_MUTEX_INIT_FUNC # undef __GTHREAD_MUTEX_INIT #endif #ifdef _GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC # undef __GTHREAD_RECURSIVE_MUTEX_INIT # undef __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION # define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #ifdef _GTHREAD_USE_COND_INIT_FUNC # undef __GTHREAD_COND_INIT # define __GTHREAD_COND_INIT_FUNCTION __gthread_cond_init_function #endif #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK # ifndef __gthrw_pragma # define __gthrw_pragma(pragma) # endif # define __gthrw2(name,name2,type) \ static __typeof(type) name __attribute__ ((__weakref__(#name2))); \ __gthrw_pragma(weak type) # define __gthrw_(name) __gthrw_ ## name #else # define __gthrw2(name,name2,type) # define __gthrw_(name) name #endif /* Typically, __gthrw_foo is a weak reference to symbol foo. */ #define __gthrw(name) __gthrw2(__gthrw_ ## name,name,name) __gthrw(pthread_once) __gthrw(pthread_getspecific) __gthrw(pthread_setspecific) __gthrw(pthread_create) __gthrw(pthread_join) __gthrw(pthread_equal) __gthrw(pthread_self) __gthrw(pthread_detach) #ifndef __BIONIC__ __gthrw(pthread_cancel) #endif __gthrw(sched_yield) __gthrw(pthread_mutex_lock) __gthrw(pthread_mutex_trylock) #if _GTHREAD_USE_MUTEX_TIMEDLOCK __gthrw(pthread_mutex_timedlock) #endif __gthrw(pthread_mutex_unlock) __gthrw(pthread_mutex_init) __gthrw(pthread_mutex_destroy) __gthrw(pthread_cond_init) __gthrw(pthread_cond_broadcast) __gthrw(pthread_cond_signal) __gthrw(pthread_cond_wait) __gthrw(pthread_cond_timedwait) __gthrw(pthread_cond_destroy) __gthrw(pthread_key_create) __gthrw(pthread_key_delete) __gthrw(pthread_mutexattr_init) __gthrw(pthread_mutexattr_settype) __gthrw(pthread_mutexattr_destroy) #if defined(_LIBOBJC) || defined(_LIBOBJC_WEAK) /* Objective-C. */ __gthrw(pthread_exit) #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(sched_get_priority_max) __gthrw(sched_get_priority_min) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ __gthrw(pthread_attr_destroy) __gthrw(pthread_attr_init) __gthrw(pthread_attr_setdetachstate) #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(pthread_getschedparam) __gthrw(pthread_setschedparam) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _LIBOBJC || _LIBOBJC_WEAK */ #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK /* On Solaris 2.6 up to 9, the libc exposes a POSIX threads interface even if -pthreads is not specified. The functions are dummies and most return an error value. However pthread_once returns 0 without invoking the routine it is passed so we cannot pretend that the interface is active if -pthreads is not specified. On Solaris 2.5.1, the interface is not exposed at all so we need to play the usual game with weak symbols. On Solaris 10 and up, a working interface is always exposed. On FreeBSD 6 and later, libc also exposes a dummy POSIX threads interface, similar to what Solaris 2.6 up to 9 does. FreeBSD >= 700014 even provides a pthread_cancel stub in libc, which means the alternate __gthread_active_p below cannot be used there. */ #if defined(__FreeBSD__) || (defined(__sun) && defined(__svr4__)) static volatile int __gthread_active = -1; static void __gthread_trigger (void) { __gthread_active = 1; } static inline int __gthread_active_p (void) { static pthread_mutex_t __gthread_active_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t __gthread_active_once = PTHREAD_ONCE_INIT; /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; /* This test is not protected to avoid taking a lock on the main code path so every update of __gthread_active in a threaded program must be atomic with regard to the result of the test. */ if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { if (__gthrw_(pthread_once)) { /* If this really is a threaded program, then we must ensure that __gthread_active has been set to 1 before exiting this block. */ __gthrw_(pthread_mutex_lock) (&__gthread_active_mutex); __gthrw_(pthread_once) (&__gthread_active_once, __gthread_trigger); __gthrw_(pthread_mutex_unlock) (&__gthread_active_mutex); } /* Make sure we'll never enter this block again. */ if (__gthread_active < 0) __gthread_active = 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* neither FreeBSD nor Solaris */ /* For a program to be multi-threaded the only thing that it certainly must be using is pthread_create. However, there may be other libraries that intercept pthread_create with their own definitions to wrap pthreads functionality for some purpose. In those cases, pthread_create being defined might not necessarily mean that libpthread is actually linked in. For the GNU C library, we can use a known internal name. This is always available in the ABI, but no other library would define it. That is ideal, since any public pthread function might be intercepted just as pthread_create might be. __pthread_key_create is an "internal" implementation symbol, but it is part of the public exported ABI. Also, it's among the symbols that the static libpthread.a always links in whenever pthread_create is used, so there is no danger of a false negative result in any statically-linked, multi-threaded program. For others, we choose pthread_cancel as a function that seems unlikely to be redefined by an interceptor library. The bionic (Android) C library does not provide pthread_cancel, so we do use pthread_create there (and interceptor libraries lose). */ #ifdef __GLIBC__ __gthrw2(__gthrw_(__pthread_key_create), __pthread_key_create, pthread_key_create) # define GTHR_ACTIVE_PROXY __gthrw_(__pthread_key_create) #elif defined (__BIONIC__) # define GTHR_ACTIVE_PROXY __gthrw_(pthread_create) #else # define GTHR_ACTIVE_PROXY __gthrw_(pthread_cancel) #endif static inline int __gthread_active_p (void) { static void *const __gthread_active_ptr = __extension__ (void *) >HR_ACTIVE_PROXY; return __gthread_active_ptr != 0; } #endif /* FreeBSD or Solaris */ #else /* not __GXX_WEAK__ */ /* Similar to Solaris, HP-UX 11 for PA-RISC provides stubs for pthread calls in shared flavors of the HP-UX C library. Most of the stubs have no functionality. The details are described in the "libc cumulative patch" for each subversion of HP-UX 11. There are two special interfaces provided for checking whether an application is linked to a shared pthread library or not. However, these interfaces aren't available in early libpthread libraries. We also need a test that works for archive libraries. We can't use pthread_once as some libc versions call the init function. We also can't use pthread_create or pthread_attr_init as these create a thread and thereby prevent changing the default stack size. The function pthread_default_stacksize_np is available in both the archive and shared versions of libpthread. It can be used to determine the default pthread stack size. There is a stub in some shared libc versions which returns a zero size if pthreads are not active. We provide an equivalent stub to handle cases where libc doesn't provide one. */ #if defined(__hppa__) && defined(__hpux__) static volatile int __gthread_active = -1; static inline int __gthread_active_p (void) { /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; size_t __s; if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { pthread_default_stacksize_np (0, &__s); __gthread_active = __s ? 1 : 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* not hppa-hpux */ static inline int __gthread_active_p (void) { return 1; } #endif /* hppa-hpux */ #endif /* __GXX_WEAK__ */ #ifdef _LIBOBJC /* This is the config.h file in libobjc/ */ #include #ifdef HAVE_SCHED_H # include #endif /* Key structure for maintaining thread specific storage */ static pthread_key_t _objc_thread_storage; static pthread_attr_t _objc_thread_attribs; /* Thread local storage for a single thread */ static void *thread_local_storage = NULL; /* Backend initialization functions */ /* Initialize the threads subsystem. */ static inline int __gthread_objc_init_thread_system (void) { if (__gthread_active_p ()) { /* Initialize the thread storage key. */ if (__gthrw_(pthread_key_create) (&_objc_thread_storage, NULL) == 0) { /* The normal default detach state for threads is * PTHREAD_CREATE_JOINABLE which causes threads to not die * when you think they should. */ if (__gthrw_(pthread_attr_init) (&_objc_thread_attribs) == 0 && __gthrw_(pthread_attr_setdetachstate) (&_objc_thread_attribs, PTHREAD_CREATE_DETACHED) == 0) return 0; } } return -1; } /* Close the threads subsystem. */ static inline int __gthread_objc_close_thread_system (void) { if (__gthread_active_p () && __gthrw_(pthread_key_delete) (_objc_thread_storage) == 0 && __gthrw_(pthread_attr_destroy) (&_objc_thread_attribs) == 0) return 0; return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ static inline objc_thread_t __gthread_objc_thread_detach (void (*func)(void *), void *arg) { objc_thread_t thread_id; pthread_t new_thread_handle; if (!__gthread_active_p ()) return NULL; if (!(__gthrw_(pthread_create) (&new_thread_handle, &_objc_thread_attribs, (void *) func, arg))) thread_id = (objc_thread_t) new_thread_handle; else thread_id = NULL; return thread_id; } /* Set the current thread's priority. */ static inline int __gthread_objc_thread_set_priority (int priority) { if (!__gthread_active_p ()) return -1; else { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING pthread_t thread_id = __gthrw_(pthread_self) (); int policy; struct sched_param params; int priority_min, priority_max; if (__gthrw_(pthread_getschedparam) (thread_id, &policy, ¶ms) == 0) { if ((priority_max = __gthrw_(sched_get_priority_max) (policy)) == -1) return -1; if ((priority_min = __gthrw_(sched_get_priority_min) (policy)) == -1) return -1; if (priority > priority_max) priority = priority_max; else if (priority < priority_min) priority = priority_min; params.sched_priority = priority; /* * The solaris 7 and several other man pages incorrectly state that * this should be a pointer to policy but pthread.h is universally * at odds with this. */ if (__gthrw_(pthread_setschedparam) (thread_id, policy, ¶ms) == 0) return 0; } #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return -1; } } /* Return the current thread's priority. */ static inline int __gthread_objc_thread_get_priority (void) { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING if (__gthread_active_p ()) { int policy; struct sched_param params; if (__gthrw_(pthread_getschedparam) (__gthrw_(pthread_self) (), &policy, ¶ms) == 0) return params.sched_priority; else return -1; } else #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return OBJC_THREAD_INTERACTIVE_PRIORITY; } /* Yield our process time to another thread. */ static inline void __gthread_objc_thread_yield (void) { if (__gthread_active_p ()) __gthrw_(sched_yield) (); } /* Terminate the current thread. */ static inline int __gthread_objc_thread_exit (void) { if (__gthread_active_p ()) /* exit the thread */ __gthrw_(pthread_exit) (&__objc_thread_exit_status); /* Failed if we reached here */ return -1; } /* Returns an integer value which uniquely describes a thread. */ static inline objc_thread_t __gthread_objc_thread_id (void) { if (__gthread_active_p ()) return (objc_thread_t) __gthrw_(pthread_self) (); else return (objc_thread_t) 1; } /* Sets the thread's local storage pointer. */ static inline int __gthread_objc_thread_set_data (void *value) { if (__gthread_active_p ()) return __gthrw_(pthread_setspecific) (_objc_thread_storage, value); else { thread_local_storage = value; return 0; } } /* Returns the thread's local storage pointer. */ static inline void * __gthread_objc_thread_get_data (void) { if (__gthread_active_p ()) return __gthrw_(pthread_getspecific) (_objc_thread_storage); else return thread_local_storage; } /* Backend mutex functions */ /* Allocate a mutex. */ static inline int __gthread_objc_mutex_allocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { mutex->backend = objc_malloc (sizeof (pthread_mutex_t)); if (__gthrw_(pthread_mutex_init) ((pthread_mutex_t *) mutex->backend, NULL)) { objc_free (mutex->backend); mutex->backend = NULL; return -1; } } return 0; } /* Deallocate a mutex. */ static inline int __gthread_objc_mutex_deallocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { int count; /* * Posix Threads specifically require that the thread be unlocked * for __gthrw_(pthread_mutex_destroy) to work. */ do { count = __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend); if (count < 0) return -1; } while (count); if (__gthrw_(pthread_mutex_destroy) ((pthread_mutex_t *) mutex->backend)) return -1; objc_free (mutex->backend); mutex->backend = NULL; } return 0; } /* Grab a lock on a mutex. */ static inline int __gthread_objc_mutex_lock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_lock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Try to grab a lock on a mutex. */ static inline int __gthread_objc_mutex_trylock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_trylock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Unlock the mutex */ static inline int __gthread_objc_mutex_unlock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Backend condition mutex functions */ /* Allocate a condition. */ static inline int __gthread_objc_condition_allocate (objc_condition_t condition) { if (__gthread_active_p ()) { condition->backend = objc_malloc (sizeof (pthread_cond_t)); if (__gthrw_(pthread_cond_init) ((pthread_cond_t *) condition->backend, NULL)) { objc_free (condition->backend); condition->backend = NULL; return -1; } } return 0; } /* Deallocate a condition. */ static inline int __gthread_objc_condition_deallocate (objc_condition_t condition) { if (__gthread_active_p ()) { if (__gthrw_(pthread_cond_destroy) ((pthread_cond_t *) condition->backend)) return -1; objc_free (condition->backend); condition->backend = NULL; } return 0; } /* Wait on the condition */ static inline int __gthread_objc_condition_wait (objc_condition_t condition, objc_mutex_t mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_wait) ((pthread_cond_t *) condition->backend, (pthread_mutex_t *) mutex->backend); else return 0; } /* Wake up all threads waiting on this condition. */ static inline int __gthread_objc_condition_broadcast (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_broadcast) ((pthread_cond_t *) condition->backend); else return 0; } /* Wake up one thread waiting on this condition. */ static inline int __gthread_objc_condition_signal (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_signal) ((pthread_cond_t *) condition->backend); else return 0; } #else /* _LIBOBJC */ static inline int __gthread_create (__gthread_t *__threadid, void *(*__func) (void*), void *__args) { return __gthrw_(pthread_create) (__threadid, NULL, __func, __args); } static inline int __gthread_join (__gthread_t __threadid, void **__value_ptr) { return __gthrw_(pthread_join) (__threadid, __value_ptr); } static inline int __gthread_detach (__gthread_t __threadid) { return __gthrw_(pthread_detach) (__threadid); } static inline int __gthread_equal (__gthread_t __t1, __gthread_t __t2) { return __gthrw_(pthread_equal) (__t1, __t2); } static inline __gthread_t __gthread_self (void) { return __gthrw_(pthread_self) (); } static inline int __gthread_yield (void) { return __gthrw_(sched_yield) (); } static inline int __gthread_once (__gthread_once_t *__once, void (*__func) (void)) { if (__gthread_active_p ()) return __gthrw_(pthread_once) (__once, __func); else return -1; } static inline int __gthread_key_create (__gthread_key_t *__key, void (*__dtor) (void *)) { return __gthrw_(pthread_key_create) (__key, __dtor); } static inline int __gthread_key_delete (__gthread_key_t __key) { return __gthrw_(pthread_key_delete) (__key); } static inline void * __gthread_getspecific (__gthread_key_t __key) { return __gthrw_(pthread_getspecific) (__key); } static inline int __gthread_setspecific (__gthread_key_t __key, const void *__ptr) { return __gthrw_(pthread_setspecific) (__key, __ptr); } static inline void __gthread_mutex_init_function (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) __gthrw_(pthread_mutex_init) (__mutex, NULL); } static inline int __gthread_mutex_destroy (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_destroy) (__mutex); else return 0; } static inline int __gthread_mutex_lock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_lock) (__mutex); else return 0; } static inline int __gthread_mutex_trylock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_trylock) (__mutex); else return 0; } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_mutex_timedlock (__gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_timedlock) (__mutex, __abs_timeout); else return 0; } #endif static inline int __gthread_mutex_unlock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_unlock) (__mutex); else return 0; } #if !defined( PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) \ || defined(_GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC) static inline int __gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *__mutex) { if (__gthread_active_p ()) { pthread_mutexattr_t __attr; int __r; __r = __gthrw_(pthread_mutexattr_init) (&__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_settype) (&__attr, PTHREAD_MUTEX_RECURSIVE); if (!__r) __r = __gthrw_(pthread_mutex_init) (__mutex, &__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_destroy) (&__attr); return __r; } return 0; } #endif static inline int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_lock (__mutex); } static inline int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_trylock (__mutex); } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthread_mutex_timedlock (__mutex, __abs_timeout); } #endif static inline int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_unlock (__mutex); } static inline int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_destroy (__mutex); } #ifdef _GTHREAD_USE_COND_INIT_FUNC static inline void __gthread_cond_init_function (__gthread_cond_t *__cond) { if (__gthread_active_p ()) __gthrw_(pthread_cond_init) (__cond, NULL); } #endif static inline int __gthread_cond_broadcast (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_broadcast) (__cond); } static inline int __gthread_cond_signal (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_signal) (__cond); } static inline int __gthread_cond_wait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex) { return __gthrw_(pthread_cond_wait) (__cond, __mutex); } static inline int __gthread_cond_timedwait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthrw_(pthread_cond_timedwait) (__cond, __mutex, __abs_timeout); } static inline int __gthread_cond_wait_recursive (__gthread_cond_t *__cond, __gthread_recursive_mutex_t *__mutex) { return __gthread_cond_wait (__cond, __mutex); } static inline int __gthread_cond_destroy (__gthread_cond_t* __cond) { return __gthrw_(pthread_cond_destroy) (__cond); } #endif /* _LIBOBJC */ #endif /* ! _GLIBCXX_GCC_GTHR_POSIX_H */ c++/8/x86_64-redhat-linux/bits/c++config.h000064400000341407151027430570013510 0ustar00#ifndef _CPP_CPPCONFIG_WRAPPER #define _CPP_CPPCONFIG_WRAPPER 1 #include #if __WORDSIZE == 32 // Predefined symbols and macros -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++config.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_CXX_CONFIG_H #define _GLIBCXX_CXX_CONFIG_H 1 // The major release number for the GCC release the C++ library belongs to. #define _GLIBCXX_RELEASE 8 // The datestamp of the C++ library in compressed ISO date format. #define __GLIBCXX__ 20210514 // Macros for various attributes. // _GLIBCXX_PURE // _GLIBCXX_CONST // _GLIBCXX_NORETURN // _GLIBCXX_NOTHROW // _GLIBCXX_VISIBILITY #ifndef _GLIBCXX_PURE # define _GLIBCXX_PURE __attribute__ ((__pure__)) #endif #ifndef _GLIBCXX_CONST # define _GLIBCXX_CONST __attribute__ ((__const__)) #endif #ifndef _GLIBCXX_NORETURN # define _GLIBCXX_NORETURN __attribute__ ((__noreturn__)) #endif // See below for C++ #ifndef _GLIBCXX_NOTHROW # ifndef __cplusplus # define _GLIBCXX_NOTHROW __attribute__((__nothrow__)) # endif #endif // Macros for visibility attributes. // _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY // _GLIBCXX_VISIBILITY # define _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY 1 #if _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY # define _GLIBCXX_VISIBILITY(V) __attribute__ ((__visibility__ (#V))) #else // If this is not supplied by the OS-specific or CPU-specific // headers included below, it will be defined to an empty default. # define _GLIBCXX_VISIBILITY(V) _GLIBCXX_PSEUDO_VISIBILITY(V) #endif // Macros for deprecated attributes. // _GLIBCXX_USE_DEPRECATED // _GLIBCXX_DEPRECATED // _GLIBCXX17_DEPRECATED #ifndef _GLIBCXX_USE_DEPRECATED # define _GLIBCXX_USE_DEPRECATED 1 #endif #if defined(__DEPRECATED) && (__cplusplus >= 201103L) # define _GLIBCXX_DEPRECATED __attribute__ ((__deprecated__)) #else # define _GLIBCXX_DEPRECATED #endif #if defined(__DEPRECATED) && (__cplusplus >= 201703L) # define _GLIBCXX17_DEPRECATED [[__deprecated__]] #else # define _GLIBCXX17_DEPRECATED #endif // Macros for ABI tag attributes. #ifndef _GLIBCXX_ABI_TAG_CXX11 # define _GLIBCXX_ABI_TAG_CXX11 __attribute ((__abi_tag__ ("cxx11"))) #endif // Macro to warn about unused results. #if __cplusplus >= 201703L # define _GLIBCXX_NODISCARD [[__nodiscard__]] #else # define _GLIBCXX_NODISCARD #endif #if __cplusplus // Macro for constexpr, to support in mixed 03/0x mode. #ifndef _GLIBCXX_CONSTEXPR # if __cplusplus >= 201103L # define _GLIBCXX_CONSTEXPR constexpr # define _GLIBCXX_USE_CONSTEXPR constexpr # else # define _GLIBCXX_CONSTEXPR # define _GLIBCXX_USE_CONSTEXPR const # endif #endif #ifndef _GLIBCXX14_CONSTEXPR # if __cplusplus >= 201402L # define _GLIBCXX14_CONSTEXPR constexpr # else # define _GLIBCXX14_CONSTEXPR # endif #endif #ifndef _GLIBCXX17_CONSTEXPR # if __cplusplus > 201402L # define _GLIBCXX17_CONSTEXPR constexpr # else # define _GLIBCXX17_CONSTEXPR # endif #endif #ifndef _GLIBCXX17_INLINE # if __cplusplus > 201402L # define _GLIBCXX17_INLINE inline # else # define _GLIBCXX17_INLINE # endif #endif // Macro for noexcept, to support in mixed 03/0x mode. #ifndef _GLIBCXX_NOEXCEPT # if __cplusplus >= 201103L # define _GLIBCXX_NOEXCEPT noexcept # define _GLIBCXX_NOEXCEPT_IF(_COND) noexcept(_COND) # define _GLIBCXX_USE_NOEXCEPT noexcept # define _GLIBCXX_THROW(_EXC) # else # define _GLIBCXX_NOEXCEPT # define _GLIBCXX_NOEXCEPT_IF(_COND) # define _GLIBCXX_USE_NOEXCEPT throw() # define _GLIBCXX_THROW(_EXC) throw(_EXC) # endif #endif #ifndef _GLIBCXX_NOTHROW # define _GLIBCXX_NOTHROW _GLIBCXX_USE_NOEXCEPT #endif #ifndef _GLIBCXX_THROW_OR_ABORT # if __cpp_exceptions # define _GLIBCXX_THROW_OR_ABORT(_EXC) (throw (_EXC)) # else # define _GLIBCXX_THROW_OR_ABORT(_EXC) (__builtin_abort()) # endif #endif #if __cpp_noexcept_function_type #define _GLIBCXX_NOEXCEPT_PARM , bool _NE #define _GLIBCXX_NOEXCEPT_QUAL noexcept (_NE) #else #define _GLIBCXX_NOEXCEPT_PARM #define _GLIBCXX_NOEXCEPT_QUAL #endif // Macro for extern template, ie controlling template linkage via use // of extern keyword on template declaration. As documented in the g++ // manual, it inhibits all implicit instantiations and is used // throughout the library to avoid multiple weak definitions for // required types that are already explicitly instantiated in the // library binary. This substantially reduces the binary size of // resulting executables. // Special case: _GLIBCXX_EXTERN_TEMPLATE == -1 disallows extern // templates only in basic_string, thus activating its debug-mode // checks even at -O0. # define _GLIBCXX_EXTERN_TEMPLATE 1 /* Outline of libstdc++ namespaces. namespace std { namespace __debug { } namespace __parallel { } namespace __profile { } namespace __cxx1998 { } namespace __detail { namespace __variant { } // C++17 } namespace rel_ops { } namespace tr1 { namespace placeholders { } namespace regex_constants { } namespace __detail { } } namespace tr2 { } namespace decimal { } namespace chrono { } // C++11 namespace placeholders { } // C++11 namespace regex_constants { } // C++11 namespace this_thread { } // C++11 inline namespace literals { // C++14 inline namespace chrono_literals { } // C++14 inline namespace complex_literals { } // C++14 inline namespace string_literals { } // C++14 inline namespace string_view_literals { } // C++17 } } namespace abi { } namespace __gnu_cxx { namespace __detail { } } For full details see: http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespaces.html */ namespace std { typedef __SIZE_TYPE__ size_t; typedef __PTRDIFF_TYPE__ ptrdiff_t; #if __cplusplus >= 201103L typedef decltype(nullptr) nullptr_t; #endif } # define _GLIBCXX_USE_DUAL_ABI 1 #if ! _GLIBCXX_USE_DUAL_ABI // Ignore any pre-defined value of _GLIBCXX_USE_CXX11_ABI # undef _GLIBCXX_USE_CXX11_ABI #endif #ifndef _GLIBCXX_USE_CXX11_ABI # define _GLIBCXX_USE_CXX11_ABI 1 #endif #if _GLIBCXX_USE_CXX11_ABI namespace std { inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } } namespace __gnu_cxx { inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } } # define _GLIBCXX_NAMESPACE_CXX11 __cxx11:: # define _GLIBCXX_BEGIN_NAMESPACE_CXX11 namespace __cxx11 { # define _GLIBCXX_END_NAMESPACE_CXX11 } # define _GLIBCXX_DEFAULT_ABI_TAG _GLIBCXX_ABI_TAG_CXX11 #else # define _GLIBCXX_NAMESPACE_CXX11 # define _GLIBCXX_BEGIN_NAMESPACE_CXX11 # define _GLIBCXX_END_NAMESPACE_CXX11 # define _GLIBCXX_DEFAULT_ABI_TAG #endif // Defined if inline namespaces are used for versioning. # define _GLIBCXX_INLINE_VERSION 0 // Inline namespace for symbol versioning. #if _GLIBCXX_INLINE_VERSION # define _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __8 { # define _GLIBCXX_END_NAMESPACE_VERSION } namespace std { inline _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus >= 201402L inline namespace literals { inline namespace chrono_literals { } inline namespace complex_literals { } inline namespace string_literals { } #if __cplusplus > 201402L inline namespace string_view_literals { } #endif // C++17 } #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } namespace __gnu_cxx { inline _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_END_NAMESPACE_VERSION } #else # define _GLIBCXX_BEGIN_NAMESPACE_VERSION # define _GLIBCXX_END_NAMESPACE_VERSION #endif // Inline namespaces for special modes: debug, parallel, profile. #if defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PARALLEL) \ || defined(_GLIBCXX_PROFILE) namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Non-inline namespace for components replaced by alternates in active mode. namespace __cxx1998 { # if _GLIBCXX_USE_CXX11_ABI inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } # endif } _GLIBCXX_END_NAMESPACE_VERSION // Inline namespace for debug mode. # ifdef _GLIBCXX_DEBUG inline namespace __debug { } # endif // Inline namespaces for parallel mode. # ifdef _GLIBCXX_PARALLEL inline namespace __parallel { } # endif // Inline namespaces for profile mode # ifdef _GLIBCXX_PROFILE inline namespace __profile { } # endif } // Check for invalid usage and unsupported mixed-mode use. # if defined(_GLIBCXX_DEBUG) && defined(_GLIBCXX_PARALLEL) # error illegal use of multiple inlined namespaces # endif # if defined(_GLIBCXX_PROFILE) && defined(_GLIBCXX_DEBUG) # error illegal use of multiple inlined namespaces # endif # if defined(_GLIBCXX_PROFILE) && defined(_GLIBCXX_PARALLEL) # error illegal use of multiple inlined namespaces # endif // Check for invalid use due to lack for weak symbols. # if __NO_INLINE__ && !__GXX_WEAK__ # warning currently using inlined namespace mode which may fail \ without inlining due to lack of weak symbols # endif #endif // Macros for namespace scope. Either namespace std:: or the name // of some nested namespace within it corresponding to the active mode. // _GLIBCXX_STD_A // _GLIBCXX_STD_C // // Macros for opening/closing conditional namespaces. // _GLIBCXX_BEGIN_NAMESPACE_ALGO // _GLIBCXX_END_NAMESPACE_ALGO // _GLIBCXX_BEGIN_NAMESPACE_CONTAINER // _GLIBCXX_END_NAMESPACE_CONTAINER #if defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PROFILE) # define _GLIBCXX_STD_C __cxx1998 # define _GLIBCXX_BEGIN_NAMESPACE_CONTAINER \ namespace _GLIBCXX_STD_C { # define _GLIBCXX_END_NAMESPACE_CONTAINER } #else # define _GLIBCXX_STD_C std # define _GLIBCXX_BEGIN_NAMESPACE_CONTAINER # define _GLIBCXX_END_NAMESPACE_CONTAINER #endif #ifdef _GLIBCXX_PARALLEL # define _GLIBCXX_STD_A __cxx1998 # define _GLIBCXX_BEGIN_NAMESPACE_ALGO \ namespace _GLIBCXX_STD_A { # define _GLIBCXX_END_NAMESPACE_ALGO } #else # define _GLIBCXX_STD_A std # define _GLIBCXX_BEGIN_NAMESPACE_ALGO # define _GLIBCXX_END_NAMESPACE_ALGO #endif // GLIBCXX_ABI Deprecated // Define if compatibility should be provided for -mlong-double-64. #undef _GLIBCXX_LONG_DOUBLE_COMPAT // Inline namespace for long double 128 mode. #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ namespace std { inline namespace __gnu_cxx_ldbl128 { } } # define _GLIBCXX_NAMESPACE_LDBL __gnu_cxx_ldbl128:: # define _GLIBCXX_BEGIN_NAMESPACE_LDBL namespace __gnu_cxx_ldbl128 { # define _GLIBCXX_END_NAMESPACE_LDBL } #else # define _GLIBCXX_NAMESPACE_LDBL # define _GLIBCXX_BEGIN_NAMESPACE_LDBL # define _GLIBCXX_END_NAMESPACE_LDBL #endif #if _GLIBCXX_USE_CXX11_ABI # define _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_NAMESPACE_CXX11 # define _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_CXX11 # define _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_END_NAMESPACE_CXX11 #else # define _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_NAMESPACE_LDBL # define _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_LDBL # define _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_END_NAMESPACE_LDBL #endif // Debug Mode implies checking assertions. #if defined(_GLIBCXX_DEBUG) && !defined(_GLIBCXX_ASSERTIONS) # define _GLIBCXX_ASSERTIONS 1 #endif // Disable std::string explicit instantiation declarations in order to assert. #ifdef _GLIBCXX_ASSERTIONS # undef _GLIBCXX_EXTERN_TEMPLATE # define _GLIBCXX_EXTERN_TEMPLATE -1 #endif // Assert. #if defined(_GLIBCXX_ASSERTIONS) \ || defined(_GLIBCXX_PARALLEL) || defined(_GLIBCXX_PARALLEL_ASSERTIONS) namespace std { // Avoid the use of assert, because we're trying to keep the // include out of the mix. inline void __replacement_assert(const char* __file, int __line, const char* __function, const char* __condition) { __builtin_printf("%s:%d: %s: Assertion '%s' failed.\n", __file, __line, __function, __condition); __builtin_abort(); } } #define __glibcxx_assert_impl(_Condition) \ do \ { \ if (! (_Condition)) \ std::__replacement_assert(__FILE__, __LINE__, __PRETTY_FUNCTION__, \ #_Condition); \ } while (false) #endif #if defined(_GLIBCXX_ASSERTIONS) # define __glibcxx_assert(_Condition) __glibcxx_assert_impl(_Condition) #else # define __glibcxx_assert(_Condition) #endif // Macros for race detectors. // _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) and // _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) should be used to explain // atomic (lock-free) synchronization to race detectors: // the race detector will infer a happens-before arc from the former to the // latter when they share the same argument pointer. // // The most frequent use case for these macros (and the only case in the // current implementation of the library) is atomic reference counting: // void _M_remove_reference() // { // _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&this->_M_refcount); // if (__gnu_cxx::__exchange_and_add_dispatch(&this->_M_refcount, -1) <= 0) // { // _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&this->_M_refcount); // _M_destroy(__a); // } // } // The annotations in this example tell the race detector that all memory // accesses occurred when the refcount was positive do not race with // memory accesses which occurred after the refcount became zero. #ifndef _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE # define _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) #endif #ifndef _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER # define _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) #endif // Macros for C linkage: define extern "C" linkage only when using C++. # define _GLIBCXX_BEGIN_EXTERN_C extern "C" { # define _GLIBCXX_END_EXTERN_C } # define _GLIBCXX_USE_ALLOCATOR_NEW 1 #else // !__cplusplus # define _GLIBCXX_BEGIN_EXTERN_C # define _GLIBCXX_END_EXTERN_C #endif // First includes. // Pick up any OS-specific definitions. #include // Pick up any CPU-specific definitions. #include // If platform uses neither visibility nor psuedo-visibility, // specify empty default for namespace annotation macros. #ifndef _GLIBCXX_PSEUDO_VISIBILITY # define _GLIBCXX_PSEUDO_VISIBILITY(V) #endif // Certain function definitions that are meant to be overridable from // user code are decorated with this macro. For some targets, this // macro causes these definitions to be weak. #ifndef _GLIBCXX_WEAK_DEFINITION # define _GLIBCXX_WEAK_DEFINITION #endif // By default, we assume that __GXX_WEAK__ also means that there is support // for declaring functions as weak while not defining such functions. This // allows for referring to functions provided by other libraries (e.g., // libitm) without depending on them if the respective features are not used. #ifndef _GLIBCXX_USE_WEAK_REF # define _GLIBCXX_USE_WEAK_REF __GXX_WEAK__ #endif // Conditionally enable annotations for the Transactional Memory TS on C++11. // Most of the following conditions are due to limitations in the current // implementation. #if __cplusplus >= 201103L && _GLIBCXX_USE_CXX11_ABI \ && _GLIBCXX_USE_DUAL_ABI && __cpp_transactional_memory >= 201505L \ && !_GLIBCXX_FULLY_DYNAMIC_STRING && _GLIBCXX_USE_WEAK_REF \ && _GLIBCXX_USE_ALLOCATOR_NEW #define _GLIBCXX_TXN_SAFE transaction_safe #define _GLIBCXX_TXN_SAFE_DYN transaction_safe_dynamic #else #define _GLIBCXX_TXN_SAFE #define _GLIBCXX_TXN_SAFE_DYN #endif #if __cplusplus > 201402L // In C++17 mathematical special functions are in namespace std. # define _GLIBCXX_USE_STD_SPEC_FUNCS 1 #elif __cplusplus >= 201103L && __STDCPP_WANT_MATH_SPEC_FUNCS__ != 0 // For C++11 and C++14 they are in namespace std when requested. # define _GLIBCXX_USE_STD_SPEC_FUNCS 1 #endif // The remainder of the prewritten config is automatic; all the // user hooks are listed above. // Create a boolean flag to be used to determine if --fast-math is set. #ifdef __FAST_MATH__ # define _GLIBCXX_FAST_MATH 1 #else # define _GLIBCXX_FAST_MATH 0 #endif // This marks string literals in header files to be extracted for eventual // translation. It is primarily used for messages in thrown exceptions; see // src/functexcept.cc. We use __N because the more traditional _N is used // for something else under certain OSes (see BADNAMES). #define __N(msgid) (msgid) // For example, is known to #define min and max as macros... #undef min #undef max // N.B. these _GLIBCXX_USE_C99_XXX macros are defined unconditionally // so they should be tested with #if not with #ifdef. #if __cplusplus >= 201103L # ifndef _GLIBCXX_USE_C99_MATH # define _GLIBCXX_USE_C99_MATH _GLIBCXX11_USE_C99_MATH # endif # ifndef _GLIBCXX_USE_C99_COMPLEX # define _GLIBCXX_USE_C99_COMPLEX _GLIBCXX11_USE_C99_COMPLEX # endif # ifndef _GLIBCXX_USE_C99_STDIO # define _GLIBCXX_USE_C99_STDIO _GLIBCXX11_USE_C99_STDIO # endif # ifndef _GLIBCXX_USE_C99_STDLIB # define _GLIBCXX_USE_C99_STDLIB _GLIBCXX11_USE_C99_STDLIB # endif # ifndef _GLIBCXX_USE_C99_WCHAR # define _GLIBCXX_USE_C99_WCHAR _GLIBCXX11_USE_C99_WCHAR # endif #else # ifndef _GLIBCXX_USE_C99_MATH # define _GLIBCXX_USE_C99_MATH _GLIBCXX98_USE_C99_MATH # endif # ifndef _GLIBCXX_USE_C99_COMPLEX # define _GLIBCXX_USE_C99_COMPLEX _GLIBCXX98_USE_C99_COMPLEX # endif # ifndef _GLIBCXX_USE_C99_STDIO # define _GLIBCXX_USE_C99_STDIO _GLIBCXX98_USE_C99_STDIO # endif # ifndef _GLIBCXX_USE_C99_STDLIB # define _GLIBCXX_USE_C99_STDLIB _GLIBCXX98_USE_C99_STDLIB # endif # ifndef _GLIBCXX_USE_C99_WCHAR # define _GLIBCXX_USE_C99_WCHAR _GLIBCXX98_USE_C99_WCHAR # endif #endif /* Define if __float128 is supported on this host. */ #if defined(__FLOAT128__) || defined(__SIZEOF_FLOAT128__) #define _GLIBCXX_USE_FLOAT128 1 #endif // End of prewritten config; the settings discovered at configure time follow. /* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the `acosf' function. */ #define _GLIBCXX_HAVE_ACOSF 1 /* Define to 1 if you have the `acosl' function. */ #define _GLIBCXX_HAVE_ACOSL 1 /* Define to 1 if you have the `aligned_alloc' function. */ #define _GLIBCXX_HAVE_ALIGNED_ALLOC 1 /* Define to 1 if you have the `asinf' function. */ #define _GLIBCXX_HAVE_ASINF 1 /* Define to 1 if you have the `asinl' function. */ #define _GLIBCXX_HAVE_ASINL 1 /* Define to 1 if the target assembler supports .symver directive. */ #define _GLIBCXX_HAVE_AS_SYMVER_DIRECTIVE 1 /* Define to 1 if you have the `atan2f' function. */ #define _GLIBCXX_HAVE_ATAN2F 1 /* Define to 1 if you have the `atan2l' function. */ #define _GLIBCXX_HAVE_ATAN2L 1 /* Define to 1 if you have the `atanf' function. */ #define _GLIBCXX_HAVE_ATANF 1 /* Define to 1 if you have the `atanl' function. */ #define _GLIBCXX_HAVE_ATANL 1 /* Define to 1 if you have the `at_quick_exit' function. */ #define _GLIBCXX_HAVE_AT_QUICK_EXIT 1 /* Define to 1 if the target assembler supports thread-local storage. */ /* #undef _GLIBCXX_HAVE_CC_TLS */ /* Define to 1 if you have the `ceilf' function. */ #define _GLIBCXX_HAVE_CEILF 1 /* Define to 1 if you have the `ceill' function. */ #define _GLIBCXX_HAVE_CEILL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_COMPLEX_H 1 /* Define to 1 if you have the `cosf' function. */ #define _GLIBCXX_HAVE_COSF 1 /* Define to 1 if you have the `coshf' function. */ #define _GLIBCXX_HAVE_COSHF 1 /* Define to 1 if you have the `coshl' function. */ #define _GLIBCXX_HAVE_COSHL 1 /* Define to 1 if you have the `cosl' function. */ #define _GLIBCXX_HAVE_COSL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_DIRENT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_DLFCN_H 1 /* Define if EBADMSG exists. */ #define _GLIBCXX_HAVE_EBADMSG 1 /* Define if ECANCELED exists. */ #define _GLIBCXX_HAVE_ECANCELED 1 /* Define if ECHILD exists. */ #define _GLIBCXX_HAVE_ECHILD 1 /* Define if EIDRM exists. */ #define _GLIBCXX_HAVE_EIDRM 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_ENDIAN_H 1 /* Define if ENODATA exists. */ #define _GLIBCXX_HAVE_ENODATA 1 /* Define if ENOLINK exists. */ #define _GLIBCXX_HAVE_ENOLINK 1 /* Define if ENOSPC exists. */ #define _GLIBCXX_HAVE_ENOSPC 1 /* Define if ENOSR exists. */ #define _GLIBCXX_HAVE_ENOSR 1 /* Define if ENOSTR exists. */ #define _GLIBCXX_HAVE_ENOSTR 1 /* Define if ENOTRECOVERABLE exists. */ #define _GLIBCXX_HAVE_ENOTRECOVERABLE 1 /* Define if ENOTSUP exists. */ #define _GLIBCXX_HAVE_ENOTSUP 1 /* Define if EOVERFLOW exists. */ #define _GLIBCXX_HAVE_EOVERFLOW 1 /* Define if EOWNERDEAD exists. */ #define _GLIBCXX_HAVE_EOWNERDEAD 1 /* Define if EPERM exists. */ #define _GLIBCXX_HAVE_EPERM 1 /* Define if EPROTO exists. */ #define _GLIBCXX_HAVE_EPROTO 1 /* Define if ETIME exists. */ #define _GLIBCXX_HAVE_ETIME 1 /* Define if ETIMEDOUT exists. */ #define _GLIBCXX_HAVE_ETIMEDOUT 1 /* Define if ETXTBSY exists. */ #define _GLIBCXX_HAVE_ETXTBSY 1 /* Define if EWOULDBLOCK exists. */ #define _GLIBCXX_HAVE_EWOULDBLOCK 1 /* Define to 1 if GCC 4.6 supported std::exception_ptr for the target */ #define _GLIBCXX_HAVE_EXCEPTION_PTR_SINCE_GCC46 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_EXECINFO_H 1 /* Define to 1 if you have the `expf' function. */ #define _GLIBCXX_HAVE_EXPF 1 /* Define to 1 if you have the `expl' function. */ #define _GLIBCXX_HAVE_EXPL 1 /* Define to 1 if you have the `fabsf' function. */ #define _GLIBCXX_HAVE_FABSF 1 /* Define to 1 if you have the `fabsl' function. */ #define _GLIBCXX_HAVE_FABSL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FCNTL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FENV_H 1 /* Define to 1 if you have the `finite' function. */ #define _GLIBCXX_HAVE_FINITE 1 /* Define to 1 if you have the `finitef' function. */ #define _GLIBCXX_HAVE_FINITEF 1 /* Define to 1 if you have the `finitel' function. */ #define _GLIBCXX_HAVE_FINITEL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FLOAT_H 1 /* Define to 1 if you have the `floorf' function. */ #define _GLIBCXX_HAVE_FLOORF 1 /* Define to 1 if you have the `floorl' function. */ #define _GLIBCXX_HAVE_FLOORL 1 /* Define to 1 if you have the `fmodf' function. */ #define _GLIBCXX_HAVE_FMODF 1 /* Define to 1 if you have the `fmodl' function. */ #define _GLIBCXX_HAVE_FMODL 1 /* Define to 1 if you have the `fpclass' function. */ /* #undef _GLIBCXX_HAVE_FPCLASS */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_FP_H */ /* Define to 1 if you have the `frexpf' function. */ #define _GLIBCXX_HAVE_FREXPF 1 /* Define to 1 if you have the `frexpl' function. */ #define _GLIBCXX_HAVE_FREXPL 1 /* Define if _Unwind_GetIPInfo is available. */ #define _GLIBCXX_HAVE_GETIPINFO 1 /* Define if gets is available in before C++14. */ #define _GLIBCXX_HAVE_GETS 1 /* Define to 1 if you have the `hypot' function. */ #define _GLIBCXX_HAVE_HYPOT 1 /* Define to 1 if you have the `hypotf' function. */ #define _GLIBCXX_HAVE_HYPOTF 1 /* Define to 1 if you have the `hypotl' function. */ #define _GLIBCXX_HAVE_HYPOTL 1 /* Define if you have the iconv() function. */ #define _GLIBCXX_HAVE_ICONV 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_IEEEFP_H */ /* Define if int64_t is available in . */ #define _GLIBCXX_HAVE_INT64_T 1 /* Define if int64_t is a long. */ /* #undef _GLIBCXX_HAVE_INT64_T_LONG */ /* Define if int64_t is a long long. */ #define _GLIBCXX_HAVE_INT64_T_LONG_LONG 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_INTTYPES_H 1 /* Define to 1 if you have the `isinf' function. */ /* #undef _GLIBCXX_HAVE_ISINF */ /* Define to 1 if you have the `isinff' function. */ #define _GLIBCXX_HAVE_ISINFF 1 /* Define to 1 if you have the `isinfl' function. */ #define _GLIBCXX_HAVE_ISINFL 1 /* Define to 1 if you have the `isnan' function. */ /* #undef _GLIBCXX_HAVE_ISNAN */ /* Define to 1 if you have the `isnanf' function. */ #define _GLIBCXX_HAVE_ISNANF 1 /* Define to 1 if you have the `isnanl' function. */ #define _GLIBCXX_HAVE_ISNANL 1 /* Defined if iswblank exists. */ #define _GLIBCXX_HAVE_ISWBLANK 1 /* Define if LC_MESSAGES is available in . */ #define _GLIBCXX_HAVE_LC_MESSAGES 1 /* Define to 1 if you have the `ldexpf' function. */ #define _GLIBCXX_HAVE_LDEXPF 1 /* Define to 1 if you have the `ldexpl' function. */ #define _GLIBCXX_HAVE_LDEXPL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LIBINTL_H 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_AS 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_DATA 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_FSIZE 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_RSS 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_VMEM 0 /* Define if futex syscall is available. */ #define _GLIBCXX_HAVE_LINUX_FUTEX 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LINUX_RANDOM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LINUX_TYPES_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LOCALE_H 1 /* Define to 1 if you have the `log10f' function. */ #define _GLIBCXX_HAVE_LOG10F 1 /* Define to 1 if you have the `log10l' function. */ #define _GLIBCXX_HAVE_LOG10L 1 /* Define to 1 if you have the `logf' function. */ #define _GLIBCXX_HAVE_LOGF 1 /* Define to 1 if you have the `logl' function. */ #define _GLIBCXX_HAVE_LOGL 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_MACHINE_ENDIAN_H */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_MACHINE_PARAM_H */ /* Define if mbstate_t exists in wchar.h. */ #define _GLIBCXX_HAVE_MBSTATE_T 1 /* Define to 1 if you have the `memalign' function. */ #define _GLIBCXX_HAVE_MEMALIGN 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_MEMORY_H 1 /* Define to 1 if you have the `modf' function. */ #define _GLIBCXX_HAVE_MODF 1 /* Define to 1 if you have the `modff' function. */ #define _GLIBCXX_HAVE_MODFF 1 /* Define to 1 if you have the `modfl' function. */ #define _GLIBCXX_HAVE_MODFL 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_NAN_H */ /* Define if defines obsolete isinf function. */ /* #undef _GLIBCXX_HAVE_OBSOLETE_ISINF */ /* Define if defines obsolete isnan function. */ /* #undef _GLIBCXX_HAVE_OBSOLETE_ISNAN */ /* Define if poll is available in . */ #define _GLIBCXX_HAVE_POLL 1 /* Define to 1 if you have the `posix_memalign' function. */ #define _GLIBCXX_HAVE_POSIX_MEMALIGN 1 /* Define to 1 if you have the `powf' function. */ #define _GLIBCXX_HAVE_POWF 1 /* Define to 1 if you have the `powl' function. */ #define _GLIBCXX_HAVE_POWL 1 /* Define to 1 if you have the `qfpclass' function. */ /* #undef _GLIBCXX_HAVE_QFPCLASS */ /* Define to 1 if you have the `quick_exit' function. */ #define _GLIBCXX_HAVE_QUICK_EXIT 1 /* Define to 1 if you have the `setenv' function. */ #define _GLIBCXX_HAVE_SETENV 1 /* Define to 1 if you have the `sincos' function. */ #define _GLIBCXX_HAVE_SINCOS 1 /* Define to 1 if you have the `sincosf' function. */ #define _GLIBCXX_HAVE_SINCOSF 1 /* Define to 1 if you have the `sincosl' function. */ #define _GLIBCXX_HAVE_SINCOSL 1 /* Define to 1 if you have the `sinf' function. */ #define _GLIBCXX_HAVE_SINF 1 /* Define to 1 if you have the `sinhf' function. */ #define _GLIBCXX_HAVE_SINHF 1 /* Define to 1 if you have the `sinhl' function. */ #define _GLIBCXX_HAVE_SINHL 1 /* Define to 1 if you have the `sinl' function. */ #define _GLIBCXX_HAVE_SINL 1 /* Defined if sleep exists. */ /* #undef _GLIBCXX_HAVE_SLEEP */ /* Define to 1 if you have the `sqrtf' function. */ #define _GLIBCXX_HAVE_SQRTF 1 /* Define to 1 if you have the `sqrtl' function. */ #define _GLIBCXX_HAVE_SQRTL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDALIGN_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDBOOL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDLIB_H 1 /* Define if strerror_l is available in . */ #define _GLIBCXX_HAVE_STRERROR_L 1 /* Define if strerror_r is available in . */ #define _GLIBCXX_HAVE_STRERROR_R 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STRING_H 1 /* Define to 1 if you have the `strtof' function. */ #define _GLIBCXX_HAVE_STRTOF 1 /* Define to 1 if you have the `strtold' function. */ #define _GLIBCXX_HAVE_STRTOLD 1 /* Define to 1 if `d_type' is a member of `struct dirent'. */ #define _GLIBCXX_HAVE_STRUCT_DIRENT_D_TYPE 1 /* Define if strxfrm_l is available in . */ #define _GLIBCXX_HAVE_STRXFRM_L 1 /* Define to 1 if the target runtime linker supports binding the same symbol to different versions. */ #define _GLIBCXX_HAVE_SYMVER_SYMBOL_RENAMING_RUNTIME_SUPPORT 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_FILIO_H */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_IPC_H 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_ISA_DEFS_H */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_MACHINE_H */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_PARAM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_RESOURCE_H 1 /* Define to 1 if you have a suitable header file */ #define _GLIBCXX_HAVE_SYS_SDT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_SEM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_STATVFS_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_SYSINFO_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_TIME_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_UIO_H 1 /* Define if S_IFREG is available in . */ /* #undef _GLIBCXX_HAVE_S_IFREG */ /* Define if S_ISREG is available in . */ #define _GLIBCXX_HAVE_S_ISREG 1 /* Define to 1 if you have the `tanf' function. */ #define _GLIBCXX_HAVE_TANF 1 /* Define to 1 if you have the `tanhf' function. */ #define _GLIBCXX_HAVE_TANHF 1 /* Define to 1 if you have the `tanhl' function. */ #define _GLIBCXX_HAVE_TANHL 1 /* Define to 1 if you have the `tanl' function. */ #define _GLIBCXX_HAVE_TANL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_TGMATH_H 1 /* Define to 1 if the target supports thread-local storage. */ #define _GLIBCXX_HAVE_TLS 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UCHAR_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UNISTD_H 1 /* Defined if usleep exists. */ /* #undef _GLIBCXX_HAVE_USLEEP */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UTIME_H 1 /* Defined if vfwscanf exists. */ #define _GLIBCXX_HAVE_VFWSCANF 1 /* Defined if vswscanf exists. */ #define _GLIBCXX_HAVE_VSWSCANF 1 /* Defined if vwscanf exists. */ #define _GLIBCXX_HAVE_VWSCANF 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_WCHAR_H 1 /* Defined if wcstof exists. */ #define _GLIBCXX_HAVE_WCSTOF 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_WCTYPE_H 1 /* Defined if Sleep exists. */ /* #undef _GLIBCXX_HAVE_WIN32_SLEEP */ /* Define if writev is available in . */ #define _GLIBCXX_HAVE_WRITEV 1 /* Define to 1 if you have the `_acosf' function. */ /* #undef _GLIBCXX_HAVE__ACOSF */ /* Define to 1 if you have the `_acosl' function. */ /* #undef _GLIBCXX_HAVE__ACOSL */ /* Define to 1 if you have the `_aligned_malloc' function. */ /* #undef _GLIBCXX_HAVE__ALIGNED_MALLOC */ /* Define to 1 if you have the `_asinf' function. */ /* #undef _GLIBCXX_HAVE__ASINF */ /* Define to 1 if you have the `_asinl' function. */ /* #undef _GLIBCXX_HAVE__ASINL */ /* Define to 1 if you have the `_atan2f' function. */ /* #undef _GLIBCXX_HAVE__ATAN2F */ /* Define to 1 if you have the `_atan2l' function. */ /* #undef _GLIBCXX_HAVE__ATAN2L */ /* Define to 1 if you have the `_atanf' function. */ /* #undef _GLIBCXX_HAVE__ATANF */ /* Define to 1 if you have the `_atanl' function. */ /* #undef _GLIBCXX_HAVE__ATANL */ /* Define to 1 if you have the `_ceilf' function. */ /* #undef _GLIBCXX_HAVE__CEILF */ /* Define to 1 if you have the `_ceill' function. */ /* #undef _GLIBCXX_HAVE__CEILL */ /* Define to 1 if you have the `_cosf' function. */ /* #undef _GLIBCXX_HAVE__COSF */ /* Define to 1 if you have the `_coshf' function. */ /* #undef _GLIBCXX_HAVE__COSHF */ /* Define to 1 if you have the `_coshl' function. */ /* #undef _GLIBCXX_HAVE__COSHL */ /* Define to 1 if you have the `_cosl' function. */ /* #undef _GLIBCXX_HAVE__COSL */ /* Define to 1 if you have the `_expf' function. */ /* #undef _GLIBCXX_HAVE__EXPF */ /* Define to 1 if you have the `_expl' function. */ /* #undef _GLIBCXX_HAVE__EXPL */ /* Define to 1 if you have the `_fabsf' function. */ /* #undef _GLIBCXX_HAVE__FABSF */ /* Define to 1 if you have the `_fabsl' function. */ /* #undef _GLIBCXX_HAVE__FABSL */ /* Define to 1 if you have the `_finite' function. */ /* #undef _GLIBCXX_HAVE__FINITE */ /* Define to 1 if you have the `_finitef' function. */ /* #undef _GLIBCXX_HAVE__FINITEF */ /* Define to 1 if you have the `_finitel' function. */ /* #undef _GLIBCXX_HAVE__FINITEL */ /* Define to 1 if you have the `_floorf' function. */ /* #undef _GLIBCXX_HAVE__FLOORF */ /* Define to 1 if you have the `_floorl' function. */ /* #undef _GLIBCXX_HAVE__FLOORL */ /* Define to 1 if you have the `_fmodf' function. */ /* #undef _GLIBCXX_HAVE__FMODF */ /* Define to 1 if you have the `_fmodl' function. */ /* #undef _GLIBCXX_HAVE__FMODL */ /* Define to 1 if you have the `_fpclass' function. */ /* #undef _GLIBCXX_HAVE__FPCLASS */ /* Define to 1 if you have the `_frexpf' function. */ /* #undef _GLIBCXX_HAVE__FREXPF */ /* Define to 1 if you have the `_frexpl' function. */ /* #undef _GLIBCXX_HAVE__FREXPL */ /* Define to 1 if you have the `_hypot' function. */ /* #undef _GLIBCXX_HAVE__HYPOT */ /* Define to 1 if you have the `_hypotf' function. */ /* #undef _GLIBCXX_HAVE__HYPOTF */ /* Define to 1 if you have the `_hypotl' function. */ /* #undef _GLIBCXX_HAVE__HYPOTL */ /* Define to 1 if you have the `_isinf' function. */ /* #undef _GLIBCXX_HAVE__ISINF */ /* Define to 1 if you have the `_isinff' function. */ /* #undef _GLIBCXX_HAVE__ISINFF */ /* Define to 1 if you have the `_isinfl' function. */ /* #undef _GLIBCXX_HAVE__ISINFL */ /* Define to 1 if you have the `_isnan' function. */ /* #undef _GLIBCXX_HAVE__ISNAN */ /* Define to 1 if you have the `_isnanf' function. */ /* #undef _GLIBCXX_HAVE__ISNANF */ /* Define to 1 if you have the `_isnanl' function. */ /* #undef _GLIBCXX_HAVE__ISNANL */ /* Define to 1 if you have the `_ldexpf' function. */ /* #undef _GLIBCXX_HAVE__LDEXPF */ /* Define to 1 if you have the `_ldexpl' function. */ /* #undef _GLIBCXX_HAVE__LDEXPL */ /* Define to 1 if you have the `_log10f' function. */ /* #undef _GLIBCXX_HAVE__LOG10F */ /* Define to 1 if you have the `_log10l' function. */ /* #undef _GLIBCXX_HAVE__LOG10L */ /* Define to 1 if you have the `_logf' function. */ /* #undef _GLIBCXX_HAVE__LOGF */ /* Define to 1 if you have the `_logl' function. */ /* #undef _GLIBCXX_HAVE__LOGL */ /* Define to 1 if you have the `_modf' function. */ /* #undef _GLIBCXX_HAVE__MODF */ /* Define to 1 if you have the `_modff' function. */ /* #undef _GLIBCXX_HAVE__MODFF */ /* Define to 1 if you have the `_modfl' function. */ /* #undef _GLIBCXX_HAVE__MODFL */ /* Define to 1 if you have the `_powf' function. */ /* #undef _GLIBCXX_HAVE__POWF */ /* Define to 1 if you have the `_powl' function. */ /* #undef _GLIBCXX_HAVE__POWL */ /* Define to 1 if you have the `_qfpclass' function. */ /* #undef _GLIBCXX_HAVE__QFPCLASS */ /* Define to 1 if you have the `_sincos' function. */ /* #undef _GLIBCXX_HAVE__SINCOS */ /* Define to 1 if you have the `_sincosf' function. */ /* #undef _GLIBCXX_HAVE__SINCOSF */ /* Define to 1 if you have the `_sincosl' function. */ /* #undef _GLIBCXX_HAVE__SINCOSL */ /* Define to 1 if you have the `_sinf' function. */ /* #undef _GLIBCXX_HAVE__SINF */ /* Define to 1 if you have the `_sinhf' function. */ /* #undef _GLIBCXX_HAVE__SINHF */ /* Define to 1 if you have the `_sinhl' function. */ /* #undef _GLIBCXX_HAVE__SINHL */ /* Define to 1 if you have the `_sinl' function. */ /* #undef _GLIBCXX_HAVE__SINL */ /* Define to 1 if you have the `_sqrtf' function. */ /* #undef _GLIBCXX_HAVE__SQRTF */ /* Define to 1 if you have the `_sqrtl' function. */ /* #undef _GLIBCXX_HAVE__SQRTL */ /* Define to 1 if you have the `_tanf' function. */ /* #undef _GLIBCXX_HAVE__TANF */ /* Define to 1 if you have the `_tanhf' function. */ /* #undef _GLIBCXX_HAVE__TANHF */ /* Define to 1 if you have the `_tanhl' function. */ /* #undef _GLIBCXX_HAVE__TANHL */ /* Define to 1 if you have the `_tanl' function. */ /* #undef _GLIBCXX_HAVE__TANL */ /* Define to 1 if you have the `__cxa_thread_atexit' function. */ /* #undef _GLIBCXX_HAVE___CXA_THREAD_ATEXIT */ /* Define to 1 if you have the `__cxa_thread_atexit_impl' function. */ #define _GLIBCXX_HAVE___CXA_THREAD_ATEXIT_IMPL 1 /* Define as const if the declaration of iconv() needs const. */ #define _GLIBCXX_ICONV_CONST /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Name of package */ /* #undef _GLIBCXX_PACKAGE */ /* Define to the address where bug reports for this package should be sent. */ #define _GLIBCXX_PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define _GLIBCXX_PACKAGE_NAME "package-unused" /* Define to the full name and version of this package. */ #define _GLIBCXX_PACKAGE_STRING "package-unused version-unused" /* Define to the one symbol short name of this package. */ #define _GLIBCXX_PACKAGE_TARNAME "libstdc++" /* Define to the home page for this package. */ #define _GLIBCXX_PACKAGE_URL "" /* Define to the version of this package. */ #define _GLIBCXX_PACKAGE__GLIBCXX_VERSION "version-unused" /* The size of `char', as computed by sizeof. */ /* #undef SIZEOF_CHAR */ /* The size of `int', as computed by sizeof. */ /* #undef SIZEOF_INT */ /* The size of `long', as computed by sizeof. */ /* #undef SIZEOF_LONG */ /* The size of `short', as computed by sizeof. */ /* #undef SIZEOF_SHORT */ /* The size of `void *', as computed by sizeof. */ /* #undef SIZEOF_VOID_P */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ /* #undef _GLIBCXX_VERSION */ /* Number of bits in a file offset, on hosts where this is settable. */ #define _GLIBCXX_FILE_OFFSET_BITS 64 /* Define if C99 functions in should be used in for C++11. Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX11_USE_C99_COMPLEX 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_MATH 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_STDIO 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_STDLIB 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_WCHAR 1 /* Define if C99 functions in should be used in for C++98. Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX98_USE_C99_COMPLEX 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_MATH 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_STDIO 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_STDLIB 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_WCHAR 1 /* Define if the compiler supports C++11 atomics. */ #define _GLIBCXX_ATOMIC_BUILTINS 1 /* Define to use concept checking code from the boost libraries. */ /* #undef _GLIBCXX_CONCEPT_CHECKS */ /* Define to 1 if a fully dynamic basic_string is wanted, 0 to disable, undefined for platform defaults */ #define _GLIBCXX_FULLY_DYNAMIC_STRING 0 /* Define if gthreads library is available. */ #define _GLIBCXX_HAS_GTHREADS 1 /* Define to 1 if a full hosted library is built, or 0 if freestanding. */ #define _GLIBCXX_HOSTED 1 /* Define if compatibility should be provided for -mlong-double-64. */ /* Define to the letter to which size_t is mangled. */ #define _GLIBCXX_MANGLE_SIZE_T j /* Define if C99 llrint and llround functions are missing from . */ /* #undef _GLIBCXX_NO_C99_ROUNDING_FUNCS */ /* Define if ptrdiff_t is int. */ #define _GLIBCXX_PTRDIFF_T_IS_INT 1 /* Define if using setrlimit to set resource limits during "make check" */ #define _GLIBCXX_RES_LIMITS 1 /* Define if size_t is unsigned int. */ #define _GLIBCXX_SIZE_T_IS_UINT 1 /* Define to the value of the EOF integer constant. */ #define _GLIBCXX_STDIO_EOF -1 /* Define to the value of the SEEK_CUR integer constant. */ #define _GLIBCXX_STDIO_SEEK_CUR 1 /* Define to the value of the SEEK_END integer constant. */ #define _GLIBCXX_STDIO_SEEK_END 2 /* Define to use symbol versioning in the shared library. */ #define _GLIBCXX_SYMVER 1 /* Define to use darwin versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_DARWIN */ /* Define to use GNU versioning in the shared library. */ #define _GLIBCXX_SYMVER_GNU 1 /* Define to use GNU namespace versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_GNU_NAMESPACE */ /* Define to use Sun versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_SUN */ /* Define if C11 functions in should be imported into namespace std in . */ #define _GLIBCXX_USE_C11_UCHAR_CXX11 1 /* Define if C99 functions or macros from , , , , and can be used or exposed. */ #define _GLIBCXX_USE_C99 1 /* Define if C99 functions in should be used in . Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX_USE_C99_COMPLEX_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_CTYPE_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_FENV_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_INTTYPES_TR1 1 /* Define if wchar_t C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_INTTYPES_WCHAR_T_TR1 1 /* Define if C99 functions or macros in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_MATH_TR1 1 /* Define if C99 types in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_STDINT_TR1 1 /* Defined if clock_gettime syscall has monotonic and realtime clock support. */ /* #undef _GLIBCXX_USE_CLOCK_GETTIME_SYSCALL */ /* Defined if clock_gettime has monotonic clock support. */ #define _GLIBCXX_USE_CLOCK_MONOTONIC 1 /* Defined if clock_gettime has realtime clock support. */ #define _GLIBCXX_USE_CLOCK_REALTIME 1 /* Define if ISO/IEC TR 24733 decimal floating point types are supported on this host. */ #define _GLIBCXX_USE_DECIMAL_FLOAT 1 /* Define if fchmod is available in . */ #define _GLIBCXX_USE_FCHMOD 1 /* Define if fchmodat is available in . */ #define _GLIBCXX_USE_FCHMODAT 1 /* Defined if gettimeofday is available. */ #define _GLIBCXX_USE_GETTIMEOFDAY 1 /* Define if get_nprocs is available in . */ #define _GLIBCXX_USE_GET_NPROCS 1 /* Define if __int128 is supported on this host. */ /* #undef _GLIBCXX_USE_INT128 */ /* Define if LFS support is available. */ #define _GLIBCXX_USE_LFS 1 /* Define if code specialized for long long should be used. */ #define _GLIBCXX_USE_LONG_LONG 1 /* Defined if nanosleep is available. */ #define _GLIBCXX_USE_NANOSLEEP 1 /* Define if NLS translations are to be used. */ #define _GLIBCXX_USE_NLS 1 /* Define if pthreads_num_processors_np is available in . */ /* #undef _GLIBCXX_USE_PTHREADS_NUM_PROCESSORS_NP */ /* Define if POSIX read/write locks are available in . */ #define _GLIBCXX_USE_PTHREAD_RWLOCK_T 1 /* Define if /dev/random and /dev/urandom are available for the random_device of TR1 (Chapter 5.1). */ #define _GLIBCXX_USE_RANDOM_TR1 1 /* Define if usable realpath is available in . */ #define _GLIBCXX_USE_REALPATH 1 /* Defined if sched_yield is available. */ #define _GLIBCXX_USE_SCHED_YIELD 1 /* Define if _SC_NPROCESSORS_ONLN is available in . */ #define _GLIBCXX_USE_SC_NPROCESSORS_ONLN 1 /* Define if _SC_NPROC_ONLN is available in . */ /* #undef _GLIBCXX_USE_SC_NPROC_ONLN */ /* Define if sendfile is available in . */ #define _GLIBCXX_USE_SENDFILE 1 /* Define if struct stat has timespec members. */ #define _GLIBCXX_USE_ST_MTIM 1 /* Define if sysctl(), CTL_HW and HW_NCPU are available in . */ /* #undef _GLIBCXX_USE_SYSCTL_HW_NCPU */ /* Define if obsolescent tmpnam is available in . */ #define _GLIBCXX_USE_TMPNAM 1 /* Define if utimensat and UTIME_OMIT are available in and AT_FDCWD in . */ #define _GLIBCXX_USE_UTIMENSAT 1 /* Define if code specialized for wchar_t should be used. */ #define _GLIBCXX_USE_WCHAR_T 1 /* Define to 1 if a verbose library is built, or 0 otherwise. */ #define _GLIBCXX_VERBOSE 1 /* Defined if as can handle rdrand. */ #define _GLIBCXX_X86_RDRAND 1 /* Define to 1 if mutex_timedlock is available. */ #define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 /* Define for large files, on AIX-style hosts. */ /* #undef _GLIBCXX_LARGE_FILES */ /* Define if all C++11 floating point overloads are available in . */ #if __cplusplus >= 201103L /* #undef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP */ #endif /* Define if all C++11 integral type overloads are available in . */ #if __cplusplus >= 201103L /* #undef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT */ #endif #if defined (_GLIBCXX_HAVE__ACOSF) && ! defined (_GLIBCXX_HAVE_ACOSF) # define _GLIBCXX_HAVE_ACOSF 1 # define acosf _acosf #endif #if defined (_GLIBCXX_HAVE__ACOSL) && ! defined (_GLIBCXX_HAVE_ACOSL) # define _GLIBCXX_HAVE_ACOSL 1 # define acosl _acosl #endif #if defined (_GLIBCXX_HAVE__ASINF) && ! defined (_GLIBCXX_HAVE_ASINF) # define _GLIBCXX_HAVE_ASINF 1 # define asinf _asinf #endif #if defined (_GLIBCXX_HAVE__ASINL) && ! defined (_GLIBCXX_HAVE_ASINL) # define _GLIBCXX_HAVE_ASINL 1 # define asinl _asinl #endif #if defined (_GLIBCXX_HAVE__ATAN2F) && ! defined (_GLIBCXX_HAVE_ATAN2F) # define _GLIBCXX_HAVE_ATAN2F 1 # define atan2f _atan2f #endif #if defined (_GLIBCXX_HAVE__ATAN2L) && ! defined (_GLIBCXX_HAVE_ATAN2L) # define _GLIBCXX_HAVE_ATAN2L 1 # define atan2l _atan2l #endif #if defined (_GLIBCXX_HAVE__ATANF) && ! defined (_GLIBCXX_HAVE_ATANF) # define _GLIBCXX_HAVE_ATANF 1 # define atanf _atanf #endif #if defined (_GLIBCXX_HAVE__ATANL) && ! defined (_GLIBCXX_HAVE_ATANL) # define _GLIBCXX_HAVE_ATANL 1 # define atanl _atanl #endif #if defined (_GLIBCXX_HAVE__CEILF) && ! defined (_GLIBCXX_HAVE_CEILF) # define _GLIBCXX_HAVE_CEILF 1 # define ceilf _ceilf #endif #if defined (_GLIBCXX_HAVE__CEILL) && ! defined (_GLIBCXX_HAVE_CEILL) # define _GLIBCXX_HAVE_CEILL 1 # define ceill _ceill #endif #if defined (_GLIBCXX_HAVE__COSF) && ! defined (_GLIBCXX_HAVE_COSF) # define _GLIBCXX_HAVE_COSF 1 # define cosf _cosf #endif #if defined (_GLIBCXX_HAVE__COSHF) && ! defined (_GLIBCXX_HAVE_COSHF) # define _GLIBCXX_HAVE_COSHF 1 # define coshf _coshf #endif #if defined (_GLIBCXX_HAVE__COSHL) && ! defined (_GLIBCXX_HAVE_COSHL) # define _GLIBCXX_HAVE_COSHL 1 # define coshl _coshl #endif #if defined (_GLIBCXX_HAVE__COSL) && ! defined (_GLIBCXX_HAVE_COSL) # define _GLIBCXX_HAVE_COSL 1 # define cosl _cosl #endif #if defined (_GLIBCXX_HAVE__EXPF) && ! defined (_GLIBCXX_HAVE_EXPF) # define _GLIBCXX_HAVE_EXPF 1 # define expf _expf #endif #if defined (_GLIBCXX_HAVE__EXPL) && ! defined (_GLIBCXX_HAVE_EXPL) # define _GLIBCXX_HAVE_EXPL 1 # define expl _expl #endif #if defined (_GLIBCXX_HAVE__FABSF) && ! defined (_GLIBCXX_HAVE_FABSF) # define _GLIBCXX_HAVE_FABSF 1 # define fabsf _fabsf #endif #if defined (_GLIBCXX_HAVE__FABSL) && ! defined (_GLIBCXX_HAVE_FABSL) # define _GLIBCXX_HAVE_FABSL 1 # define fabsl _fabsl #endif #if defined (_GLIBCXX_HAVE__FINITE) && ! defined (_GLIBCXX_HAVE_FINITE) # define _GLIBCXX_HAVE_FINITE 1 # define finite _finite #endif #if defined (_GLIBCXX_HAVE__FINITEF) && ! defined (_GLIBCXX_HAVE_FINITEF) # define _GLIBCXX_HAVE_FINITEF 1 # define finitef _finitef #endif #if defined (_GLIBCXX_HAVE__FINITEL) && ! defined (_GLIBCXX_HAVE_FINITEL) # define _GLIBCXX_HAVE_FINITEL 1 # define finitel _finitel #endif #if defined (_GLIBCXX_HAVE__FLOORF) && ! defined (_GLIBCXX_HAVE_FLOORF) # define _GLIBCXX_HAVE_FLOORF 1 # define floorf _floorf #endif #if defined (_GLIBCXX_HAVE__FLOORL) && ! defined (_GLIBCXX_HAVE_FLOORL) # define _GLIBCXX_HAVE_FLOORL 1 # define floorl _floorl #endif #if defined (_GLIBCXX_HAVE__FMODF) && ! defined (_GLIBCXX_HAVE_FMODF) # define _GLIBCXX_HAVE_FMODF 1 # define fmodf _fmodf #endif #if defined (_GLIBCXX_HAVE__FMODL) && ! defined (_GLIBCXX_HAVE_FMODL) # define _GLIBCXX_HAVE_FMODL 1 # define fmodl _fmodl #endif #if defined (_GLIBCXX_HAVE__FPCLASS) && ! defined (_GLIBCXX_HAVE_FPCLASS) # define _GLIBCXX_HAVE_FPCLASS 1 # define fpclass _fpclass #endif #if defined (_GLIBCXX_HAVE__FREXPF) && ! defined (_GLIBCXX_HAVE_FREXPF) # define _GLIBCXX_HAVE_FREXPF 1 # define frexpf _frexpf #endif #if defined (_GLIBCXX_HAVE__FREXPL) && ! defined (_GLIBCXX_HAVE_FREXPL) # define _GLIBCXX_HAVE_FREXPL 1 # define frexpl _frexpl #endif #if defined (_GLIBCXX_HAVE__HYPOT) && ! defined (_GLIBCXX_HAVE_HYPOT) # define _GLIBCXX_HAVE_HYPOT 1 # define hypot _hypot #endif #if defined (_GLIBCXX_HAVE__HYPOTF) && ! defined (_GLIBCXX_HAVE_HYPOTF) # define _GLIBCXX_HAVE_HYPOTF 1 # define hypotf _hypotf #endif #if defined (_GLIBCXX_HAVE__HYPOTL) && ! defined (_GLIBCXX_HAVE_HYPOTL) # define _GLIBCXX_HAVE_HYPOTL 1 # define hypotl _hypotl #endif #if defined (_GLIBCXX_HAVE__ISINF) && ! defined (_GLIBCXX_HAVE_ISINF) # define _GLIBCXX_HAVE_ISINF 1 # define isinf _isinf #endif #if defined (_GLIBCXX_HAVE__ISINFF) && ! defined (_GLIBCXX_HAVE_ISINFF) # define _GLIBCXX_HAVE_ISINFF 1 # define isinff _isinff #endif #if defined (_GLIBCXX_HAVE__ISINFL) && ! defined (_GLIBCXX_HAVE_ISINFL) # define _GLIBCXX_HAVE_ISINFL 1 # define isinfl _isinfl #endif #if defined (_GLIBCXX_HAVE__ISNAN) && ! defined (_GLIBCXX_HAVE_ISNAN) # define _GLIBCXX_HAVE_ISNAN 1 # define isnan _isnan #endif #if defined (_GLIBCXX_HAVE__ISNANF) && ! defined (_GLIBCXX_HAVE_ISNANF) # define _GLIBCXX_HAVE_ISNANF 1 # define isnanf _isnanf #endif #if defined (_GLIBCXX_HAVE__ISNANL) && ! defined (_GLIBCXX_HAVE_ISNANL) # define _GLIBCXX_HAVE_ISNANL 1 # define isnanl _isnanl #endif #if defined (_GLIBCXX_HAVE__LDEXPF) && ! defined (_GLIBCXX_HAVE_LDEXPF) # define _GLIBCXX_HAVE_LDEXPF 1 # define ldexpf _ldexpf #endif #if defined (_GLIBCXX_HAVE__LDEXPL) && ! defined (_GLIBCXX_HAVE_LDEXPL) # define _GLIBCXX_HAVE_LDEXPL 1 # define ldexpl _ldexpl #endif #if defined (_GLIBCXX_HAVE__LOG10F) && ! defined (_GLIBCXX_HAVE_LOG10F) # define _GLIBCXX_HAVE_LOG10F 1 # define log10f _log10f #endif #if defined (_GLIBCXX_HAVE__LOG10L) && ! defined (_GLIBCXX_HAVE_LOG10L) # define _GLIBCXX_HAVE_LOG10L 1 # define log10l _log10l #endif #if defined (_GLIBCXX_HAVE__LOGF) && ! defined (_GLIBCXX_HAVE_LOGF) # define _GLIBCXX_HAVE_LOGF 1 # define logf _logf #endif #if defined (_GLIBCXX_HAVE__LOGL) && ! defined (_GLIBCXX_HAVE_LOGL) # define _GLIBCXX_HAVE_LOGL 1 # define logl _logl #endif #if defined (_GLIBCXX_HAVE__MODF) && ! defined (_GLIBCXX_HAVE_MODF) # define _GLIBCXX_HAVE_MODF 1 # define modf _modf #endif #if defined (_GLIBCXX_HAVE__MODFF) && ! defined (_GLIBCXX_HAVE_MODFF) # define _GLIBCXX_HAVE_MODFF 1 # define modff _modff #endif #if defined (_GLIBCXX_HAVE__MODFL) && ! defined (_GLIBCXX_HAVE_MODFL) # define _GLIBCXX_HAVE_MODFL 1 # define modfl _modfl #endif #if defined (_GLIBCXX_HAVE__POWF) && ! defined (_GLIBCXX_HAVE_POWF) # define _GLIBCXX_HAVE_POWF 1 # define powf _powf #endif #if defined (_GLIBCXX_HAVE__POWL) && ! defined (_GLIBCXX_HAVE_POWL) # define _GLIBCXX_HAVE_POWL 1 # define powl _powl #endif #if defined (_GLIBCXX_HAVE__QFPCLASS) && ! defined (_GLIBCXX_HAVE_QFPCLASS) # define _GLIBCXX_HAVE_QFPCLASS 1 # define qfpclass _qfpclass #endif #if defined (_GLIBCXX_HAVE__SINCOS) && ! defined (_GLIBCXX_HAVE_SINCOS) # define _GLIBCXX_HAVE_SINCOS 1 # define sincos _sincos #endif #if defined (_GLIBCXX_HAVE__SINCOSF) && ! defined (_GLIBCXX_HAVE_SINCOSF) # define _GLIBCXX_HAVE_SINCOSF 1 # define sincosf _sincosf #endif #if defined (_GLIBCXX_HAVE__SINCOSL) && ! defined (_GLIBCXX_HAVE_SINCOSL) # define _GLIBCXX_HAVE_SINCOSL 1 # define sincosl _sincosl #endif #if defined (_GLIBCXX_HAVE__SINF) && ! defined (_GLIBCXX_HAVE_SINF) # define _GLIBCXX_HAVE_SINF 1 # define sinf _sinf #endif #if defined (_GLIBCXX_HAVE__SINHF) && ! defined (_GLIBCXX_HAVE_SINHF) # define _GLIBCXX_HAVE_SINHF 1 # define sinhf _sinhf #endif #if defined (_GLIBCXX_HAVE__SINHL) && ! defined (_GLIBCXX_HAVE_SINHL) # define _GLIBCXX_HAVE_SINHL 1 # define sinhl _sinhl #endif #if defined (_GLIBCXX_HAVE__SINL) && ! defined (_GLIBCXX_HAVE_SINL) # define _GLIBCXX_HAVE_SINL 1 # define sinl _sinl #endif #if defined (_GLIBCXX_HAVE__SQRTF) && ! defined (_GLIBCXX_HAVE_SQRTF) # define _GLIBCXX_HAVE_SQRTF 1 # define sqrtf _sqrtf #endif #if defined (_GLIBCXX_HAVE__SQRTL) && ! defined (_GLIBCXX_HAVE_SQRTL) # define _GLIBCXX_HAVE_SQRTL 1 # define sqrtl _sqrtl #endif #if defined (_GLIBCXX_HAVE__STRTOF) && ! defined (_GLIBCXX_HAVE_STRTOF) # define _GLIBCXX_HAVE_STRTOF 1 # define strtof _strtof #endif #if defined (_GLIBCXX_HAVE__STRTOLD) && ! defined (_GLIBCXX_HAVE_STRTOLD) # define _GLIBCXX_HAVE_STRTOLD 1 # define strtold _strtold #endif #if defined (_GLIBCXX_HAVE__TANF) && ! defined (_GLIBCXX_HAVE_TANF) # define _GLIBCXX_HAVE_TANF 1 # define tanf _tanf #endif #if defined (_GLIBCXX_HAVE__TANHF) && ! defined (_GLIBCXX_HAVE_TANHF) # define _GLIBCXX_HAVE_TANHF 1 # define tanhf _tanhf #endif #if defined (_GLIBCXX_HAVE__TANHL) && ! defined (_GLIBCXX_HAVE_TANHL) # define _GLIBCXX_HAVE_TANHL 1 # define tanhl _tanhl #endif #if defined (_GLIBCXX_HAVE__TANL) && ! defined (_GLIBCXX_HAVE_TANL) # define _GLIBCXX_HAVE_TANL 1 # define tanl _tanl #endif #endif // _GLIBCXX_CXX_CONFIG_H #else // Predefined symbols and macros -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++config.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_CXX_CONFIG_H #define _GLIBCXX_CXX_CONFIG_H 1 // The major release number for the GCC release the C++ library belongs to. #define _GLIBCXX_RELEASE 8 // The datestamp of the C++ library in compressed ISO date format. #define __GLIBCXX__ 20210514 // Macros for various attributes. // _GLIBCXX_PURE // _GLIBCXX_CONST // _GLIBCXX_NORETURN // _GLIBCXX_NOTHROW // _GLIBCXX_VISIBILITY #ifndef _GLIBCXX_PURE # define _GLIBCXX_PURE __attribute__ ((__pure__)) #endif #ifndef _GLIBCXX_CONST # define _GLIBCXX_CONST __attribute__ ((__const__)) #endif #ifndef _GLIBCXX_NORETURN # define _GLIBCXX_NORETURN __attribute__ ((__noreturn__)) #endif // See below for C++ #ifndef _GLIBCXX_NOTHROW # ifndef __cplusplus # define _GLIBCXX_NOTHROW __attribute__((__nothrow__)) # endif #endif // Macros for visibility attributes. // _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY // _GLIBCXX_VISIBILITY # define _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY 1 #if _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY # define _GLIBCXX_VISIBILITY(V) __attribute__ ((__visibility__ (#V))) #else // If this is not supplied by the OS-specific or CPU-specific // headers included below, it will be defined to an empty default. # define _GLIBCXX_VISIBILITY(V) _GLIBCXX_PSEUDO_VISIBILITY(V) #endif // Macros for deprecated attributes. // _GLIBCXX_USE_DEPRECATED // _GLIBCXX_DEPRECATED // _GLIBCXX17_DEPRECATED #ifndef _GLIBCXX_USE_DEPRECATED # define _GLIBCXX_USE_DEPRECATED 1 #endif #if defined(__DEPRECATED) && (__cplusplus >= 201103L) # define _GLIBCXX_DEPRECATED __attribute__ ((__deprecated__)) #else # define _GLIBCXX_DEPRECATED #endif #if defined(__DEPRECATED) && (__cplusplus >= 201703L) # define _GLIBCXX17_DEPRECATED [[__deprecated__]] #else # define _GLIBCXX17_DEPRECATED #endif // Macros for ABI tag attributes. #ifndef _GLIBCXX_ABI_TAG_CXX11 # define _GLIBCXX_ABI_TAG_CXX11 __attribute ((__abi_tag__ ("cxx11"))) #endif // Macro to warn about unused results. #if __cplusplus >= 201703L # define _GLIBCXX_NODISCARD [[__nodiscard__]] #else # define _GLIBCXX_NODISCARD #endif #if __cplusplus // Macro for constexpr, to support in mixed 03/0x mode. #ifndef _GLIBCXX_CONSTEXPR # if __cplusplus >= 201103L # define _GLIBCXX_CONSTEXPR constexpr # define _GLIBCXX_USE_CONSTEXPR constexpr # else # define _GLIBCXX_CONSTEXPR # define _GLIBCXX_USE_CONSTEXPR const # endif #endif #ifndef _GLIBCXX14_CONSTEXPR # if __cplusplus >= 201402L # define _GLIBCXX14_CONSTEXPR constexpr # else # define _GLIBCXX14_CONSTEXPR # endif #endif #ifndef _GLIBCXX17_CONSTEXPR # if __cplusplus > 201402L # define _GLIBCXX17_CONSTEXPR constexpr # else # define _GLIBCXX17_CONSTEXPR # endif #endif #ifndef _GLIBCXX17_INLINE # if __cplusplus > 201402L # define _GLIBCXX17_INLINE inline # else # define _GLIBCXX17_INLINE # endif #endif // Macro for noexcept, to support in mixed 03/0x mode. #ifndef _GLIBCXX_NOEXCEPT # if __cplusplus >= 201103L # define _GLIBCXX_NOEXCEPT noexcept # define _GLIBCXX_NOEXCEPT_IF(_COND) noexcept(_COND) # define _GLIBCXX_USE_NOEXCEPT noexcept # define _GLIBCXX_THROW(_EXC) # else # define _GLIBCXX_NOEXCEPT # define _GLIBCXX_NOEXCEPT_IF(_COND) # define _GLIBCXX_USE_NOEXCEPT throw() # define _GLIBCXX_THROW(_EXC) throw(_EXC) # endif #endif #ifndef _GLIBCXX_NOTHROW # define _GLIBCXX_NOTHROW _GLIBCXX_USE_NOEXCEPT #endif #ifndef _GLIBCXX_THROW_OR_ABORT # if __cpp_exceptions # define _GLIBCXX_THROW_OR_ABORT(_EXC) (throw (_EXC)) # else # define _GLIBCXX_THROW_OR_ABORT(_EXC) (__builtin_abort()) # endif #endif #if __cpp_noexcept_function_type #define _GLIBCXX_NOEXCEPT_PARM , bool _NE #define _GLIBCXX_NOEXCEPT_QUAL noexcept (_NE) #else #define _GLIBCXX_NOEXCEPT_PARM #define _GLIBCXX_NOEXCEPT_QUAL #endif // Macro for extern template, ie controlling template linkage via use // of extern keyword on template declaration. As documented in the g++ // manual, it inhibits all implicit instantiations and is used // throughout the library to avoid multiple weak definitions for // required types that are already explicitly instantiated in the // library binary. This substantially reduces the binary size of // resulting executables. // Special case: _GLIBCXX_EXTERN_TEMPLATE == -1 disallows extern // templates only in basic_string, thus activating its debug-mode // checks even at -O0. # define _GLIBCXX_EXTERN_TEMPLATE 1 /* Outline of libstdc++ namespaces. namespace std { namespace __debug { } namespace __parallel { } namespace __profile { } namespace __cxx1998 { } namespace __detail { namespace __variant { } // C++17 } namespace rel_ops { } namespace tr1 { namespace placeholders { } namespace regex_constants { } namespace __detail { } } namespace tr2 { } namespace decimal { } namespace chrono { } // C++11 namespace placeholders { } // C++11 namespace regex_constants { } // C++11 namespace this_thread { } // C++11 inline namespace literals { // C++14 inline namespace chrono_literals { } // C++14 inline namespace complex_literals { } // C++14 inline namespace string_literals { } // C++14 inline namespace string_view_literals { } // C++17 } } namespace abi { } namespace __gnu_cxx { namespace __detail { } } For full details see: http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespaces.html */ namespace std { typedef __SIZE_TYPE__ size_t; typedef __PTRDIFF_TYPE__ ptrdiff_t; #if __cplusplus >= 201103L typedef decltype(nullptr) nullptr_t; #endif } # define _GLIBCXX_USE_DUAL_ABI 1 #if ! _GLIBCXX_USE_DUAL_ABI // Ignore any pre-defined value of _GLIBCXX_USE_CXX11_ABI # undef _GLIBCXX_USE_CXX11_ABI #endif #ifndef _GLIBCXX_USE_CXX11_ABI # define _GLIBCXX_USE_CXX11_ABI 1 #endif #if _GLIBCXX_USE_CXX11_ABI namespace std { inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } } namespace __gnu_cxx { inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } } # define _GLIBCXX_NAMESPACE_CXX11 __cxx11:: # define _GLIBCXX_BEGIN_NAMESPACE_CXX11 namespace __cxx11 { # define _GLIBCXX_END_NAMESPACE_CXX11 } # define _GLIBCXX_DEFAULT_ABI_TAG _GLIBCXX_ABI_TAG_CXX11 #else # define _GLIBCXX_NAMESPACE_CXX11 # define _GLIBCXX_BEGIN_NAMESPACE_CXX11 # define _GLIBCXX_END_NAMESPACE_CXX11 # define _GLIBCXX_DEFAULT_ABI_TAG #endif // Defined if inline namespaces are used for versioning. # define _GLIBCXX_INLINE_VERSION 0 // Inline namespace for symbol versioning. #if _GLIBCXX_INLINE_VERSION # define _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __8 { # define _GLIBCXX_END_NAMESPACE_VERSION } namespace std { inline _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus >= 201402L inline namespace literals { inline namespace chrono_literals { } inline namespace complex_literals { } inline namespace string_literals { } #if __cplusplus > 201402L inline namespace string_view_literals { } #endif // C++17 } #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } namespace __gnu_cxx { inline _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_END_NAMESPACE_VERSION } #else # define _GLIBCXX_BEGIN_NAMESPACE_VERSION # define _GLIBCXX_END_NAMESPACE_VERSION #endif // Inline namespaces for special modes: debug, parallel, profile. #if defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PARALLEL) \ || defined(_GLIBCXX_PROFILE) namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Non-inline namespace for components replaced by alternates in active mode. namespace __cxx1998 { # if _GLIBCXX_USE_CXX11_ABI inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } # endif } _GLIBCXX_END_NAMESPACE_VERSION // Inline namespace for debug mode. # ifdef _GLIBCXX_DEBUG inline namespace __debug { } # endif // Inline namespaces for parallel mode. # ifdef _GLIBCXX_PARALLEL inline namespace __parallel { } # endif // Inline namespaces for profile mode # ifdef _GLIBCXX_PROFILE inline namespace __profile { } # endif } // Check for invalid usage and unsupported mixed-mode use. # if defined(_GLIBCXX_DEBUG) && defined(_GLIBCXX_PARALLEL) # error illegal use of multiple inlined namespaces # endif # if defined(_GLIBCXX_PROFILE) && defined(_GLIBCXX_DEBUG) # error illegal use of multiple inlined namespaces # endif # if defined(_GLIBCXX_PROFILE) && defined(_GLIBCXX_PARALLEL) # error illegal use of multiple inlined namespaces # endif // Check for invalid use due to lack for weak symbols. # if __NO_INLINE__ && !__GXX_WEAK__ # warning currently using inlined namespace mode which may fail \ without inlining due to lack of weak symbols # endif #endif // Macros for namespace scope. Either namespace std:: or the name // of some nested namespace within it corresponding to the active mode. // _GLIBCXX_STD_A // _GLIBCXX_STD_C // // Macros for opening/closing conditional namespaces. // _GLIBCXX_BEGIN_NAMESPACE_ALGO // _GLIBCXX_END_NAMESPACE_ALGO // _GLIBCXX_BEGIN_NAMESPACE_CONTAINER // _GLIBCXX_END_NAMESPACE_CONTAINER #if defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PROFILE) # define _GLIBCXX_STD_C __cxx1998 # define _GLIBCXX_BEGIN_NAMESPACE_CONTAINER \ namespace _GLIBCXX_STD_C { # define _GLIBCXX_END_NAMESPACE_CONTAINER } #else # define _GLIBCXX_STD_C std # define _GLIBCXX_BEGIN_NAMESPACE_CONTAINER # define _GLIBCXX_END_NAMESPACE_CONTAINER #endif #ifdef _GLIBCXX_PARALLEL # define _GLIBCXX_STD_A __cxx1998 # define _GLIBCXX_BEGIN_NAMESPACE_ALGO \ namespace _GLIBCXX_STD_A { # define _GLIBCXX_END_NAMESPACE_ALGO } #else # define _GLIBCXX_STD_A std # define _GLIBCXX_BEGIN_NAMESPACE_ALGO # define _GLIBCXX_END_NAMESPACE_ALGO #endif // GLIBCXX_ABI Deprecated // Define if compatibility should be provided for -mlong-double-64. #undef _GLIBCXX_LONG_DOUBLE_COMPAT // Inline namespace for long double 128 mode. #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ namespace std { inline namespace __gnu_cxx_ldbl128 { } } # define _GLIBCXX_NAMESPACE_LDBL __gnu_cxx_ldbl128:: # define _GLIBCXX_BEGIN_NAMESPACE_LDBL namespace __gnu_cxx_ldbl128 { # define _GLIBCXX_END_NAMESPACE_LDBL } #else # define _GLIBCXX_NAMESPACE_LDBL # define _GLIBCXX_BEGIN_NAMESPACE_LDBL # define _GLIBCXX_END_NAMESPACE_LDBL #endif #if _GLIBCXX_USE_CXX11_ABI # define _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_NAMESPACE_CXX11 # define _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_CXX11 # define _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_END_NAMESPACE_CXX11 #else # define _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_NAMESPACE_LDBL # define _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_LDBL # define _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_END_NAMESPACE_LDBL #endif // Debug Mode implies checking assertions. #if defined(_GLIBCXX_DEBUG) && !defined(_GLIBCXX_ASSERTIONS) # define _GLIBCXX_ASSERTIONS 1 #endif // Disable std::string explicit instantiation declarations in order to assert. #ifdef _GLIBCXX_ASSERTIONS # undef _GLIBCXX_EXTERN_TEMPLATE # define _GLIBCXX_EXTERN_TEMPLATE -1 #endif // Assert. #if defined(_GLIBCXX_ASSERTIONS) \ || defined(_GLIBCXX_PARALLEL) || defined(_GLIBCXX_PARALLEL_ASSERTIONS) namespace std { // Avoid the use of assert, because we're trying to keep the // include out of the mix. inline void __replacement_assert(const char* __file, int __line, const char* __function, const char* __condition) { __builtin_printf("%s:%d: %s: Assertion '%s' failed.\n", __file, __line, __function, __condition); __builtin_abort(); } } #define __glibcxx_assert_impl(_Condition) \ do \ { \ if (! (_Condition)) \ std::__replacement_assert(__FILE__, __LINE__, __PRETTY_FUNCTION__, \ #_Condition); \ } while (false) #endif #if defined(_GLIBCXX_ASSERTIONS) # define __glibcxx_assert(_Condition) __glibcxx_assert_impl(_Condition) #else # define __glibcxx_assert(_Condition) #endif // Macros for race detectors. // _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) and // _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) should be used to explain // atomic (lock-free) synchronization to race detectors: // the race detector will infer a happens-before arc from the former to the // latter when they share the same argument pointer. // // The most frequent use case for these macros (and the only case in the // current implementation of the library) is atomic reference counting: // void _M_remove_reference() // { // _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&this->_M_refcount); // if (__gnu_cxx::__exchange_and_add_dispatch(&this->_M_refcount, -1) <= 0) // { // _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&this->_M_refcount); // _M_destroy(__a); // } // } // The annotations in this example tell the race detector that all memory // accesses occurred when the refcount was positive do not race with // memory accesses which occurred after the refcount became zero. #ifndef _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE # define _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) #endif #ifndef _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER # define _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) #endif // Macros for C linkage: define extern "C" linkage only when using C++. # define _GLIBCXX_BEGIN_EXTERN_C extern "C" { # define _GLIBCXX_END_EXTERN_C } # define _GLIBCXX_USE_ALLOCATOR_NEW 1 #else // !__cplusplus # define _GLIBCXX_BEGIN_EXTERN_C # define _GLIBCXX_END_EXTERN_C #endif // First includes. // Pick up any OS-specific definitions. #include // Pick up any CPU-specific definitions. #include // If platform uses neither visibility nor psuedo-visibility, // specify empty default for namespace annotation macros. #ifndef _GLIBCXX_PSEUDO_VISIBILITY # define _GLIBCXX_PSEUDO_VISIBILITY(V) #endif // Certain function definitions that are meant to be overridable from // user code are decorated with this macro. For some targets, this // macro causes these definitions to be weak. #ifndef _GLIBCXX_WEAK_DEFINITION # define _GLIBCXX_WEAK_DEFINITION #endif // By default, we assume that __GXX_WEAK__ also means that there is support // for declaring functions as weak while not defining such functions. This // allows for referring to functions provided by other libraries (e.g., // libitm) without depending on them if the respective features are not used. #ifndef _GLIBCXX_USE_WEAK_REF # define _GLIBCXX_USE_WEAK_REF __GXX_WEAK__ #endif // Conditionally enable annotations for the Transactional Memory TS on C++11. // Most of the following conditions are due to limitations in the current // implementation. #if __cplusplus >= 201103L && _GLIBCXX_USE_CXX11_ABI \ && _GLIBCXX_USE_DUAL_ABI && __cpp_transactional_memory >= 201505L \ && !_GLIBCXX_FULLY_DYNAMIC_STRING && _GLIBCXX_USE_WEAK_REF \ && _GLIBCXX_USE_ALLOCATOR_NEW #define _GLIBCXX_TXN_SAFE transaction_safe #define _GLIBCXX_TXN_SAFE_DYN transaction_safe_dynamic #else #define _GLIBCXX_TXN_SAFE #define _GLIBCXX_TXN_SAFE_DYN #endif #if __cplusplus > 201402L // In C++17 mathematical special functions are in namespace std. # define _GLIBCXX_USE_STD_SPEC_FUNCS 1 #elif __cplusplus >= 201103L && __STDCPP_WANT_MATH_SPEC_FUNCS__ != 0 // For C++11 and C++14 they are in namespace std when requested. # define _GLIBCXX_USE_STD_SPEC_FUNCS 1 #endif // The remainder of the prewritten config is automatic; all the // user hooks are listed above. // Create a boolean flag to be used to determine if --fast-math is set. #ifdef __FAST_MATH__ # define _GLIBCXX_FAST_MATH 1 #else # define _GLIBCXX_FAST_MATH 0 #endif // This marks string literals in header files to be extracted for eventual // translation. It is primarily used for messages in thrown exceptions; see // src/functexcept.cc. We use __N because the more traditional _N is used // for something else under certain OSes (see BADNAMES). #define __N(msgid) (msgid) // For example, is known to #define min and max as macros... #undef min #undef max // N.B. these _GLIBCXX_USE_C99_XXX macros are defined unconditionally // so they should be tested with #if not with #ifdef. #if __cplusplus >= 201103L # ifndef _GLIBCXX_USE_C99_MATH # define _GLIBCXX_USE_C99_MATH _GLIBCXX11_USE_C99_MATH # endif # ifndef _GLIBCXX_USE_C99_COMPLEX # define _GLIBCXX_USE_C99_COMPLEX _GLIBCXX11_USE_C99_COMPLEX # endif # ifndef _GLIBCXX_USE_C99_STDIO # define _GLIBCXX_USE_C99_STDIO _GLIBCXX11_USE_C99_STDIO # endif # ifndef _GLIBCXX_USE_C99_STDLIB # define _GLIBCXX_USE_C99_STDLIB _GLIBCXX11_USE_C99_STDLIB # endif # ifndef _GLIBCXX_USE_C99_WCHAR # define _GLIBCXX_USE_C99_WCHAR _GLIBCXX11_USE_C99_WCHAR # endif #else # ifndef _GLIBCXX_USE_C99_MATH # define _GLIBCXX_USE_C99_MATH _GLIBCXX98_USE_C99_MATH # endif # ifndef _GLIBCXX_USE_C99_COMPLEX # define _GLIBCXX_USE_C99_COMPLEX _GLIBCXX98_USE_C99_COMPLEX # endif # ifndef _GLIBCXX_USE_C99_STDIO # define _GLIBCXX_USE_C99_STDIO _GLIBCXX98_USE_C99_STDIO # endif # ifndef _GLIBCXX_USE_C99_STDLIB # define _GLIBCXX_USE_C99_STDLIB _GLIBCXX98_USE_C99_STDLIB # endif # ifndef _GLIBCXX_USE_C99_WCHAR # define _GLIBCXX_USE_C99_WCHAR _GLIBCXX98_USE_C99_WCHAR # endif #endif /* Define if __float128 is supported on this host. */ #if defined(__FLOAT128__) || defined(__SIZEOF_FLOAT128__) #define _GLIBCXX_USE_FLOAT128 1 #endif // End of prewritten config; the settings discovered at configure time follow. /* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the `acosf' function. */ #define _GLIBCXX_HAVE_ACOSF 1 /* Define to 1 if you have the `acosl' function. */ #define _GLIBCXX_HAVE_ACOSL 1 /* Define to 1 if you have the `aligned_alloc' function. */ #define _GLIBCXX_HAVE_ALIGNED_ALLOC 1 /* Define to 1 if you have the `asinf' function. */ #define _GLIBCXX_HAVE_ASINF 1 /* Define to 1 if you have the `asinl' function. */ #define _GLIBCXX_HAVE_ASINL 1 /* Define to 1 if the target assembler supports .symver directive. */ #define _GLIBCXX_HAVE_AS_SYMVER_DIRECTIVE 1 /* Define to 1 if you have the `atan2f' function. */ #define _GLIBCXX_HAVE_ATAN2F 1 /* Define to 1 if you have the `atan2l' function. */ #define _GLIBCXX_HAVE_ATAN2L 1 /* Define to 1 if you have the `atanf' function. */ #define _GLIBCXX_HAVE_ATANF 1 /* Define to 1 if you have the `atanl' function. */ #define _GLIBCXX_HAVE_ATANL 1 /* Define to 1 if you have the `at_quick_exit' function. */ #define _GLIBCXX_HAVE_AT_QUICK_EXIT 1 /* Define to 1 if the target assembler supports thread-local storage. */ /* #undef _GLIBCXX_HAVE_CC_TLS */ /* Define to 1 if you have the `ceilf' function. */ #define _GLIBCXX_HAVE_CEILF 1 /* Define to 1 if you have the `ceill' function. */ #define _GLIBCXX_HAVE_CEILL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_COMPLEX_H 1 /* Define to 1 if you have the `cosf' function. */ #define _GLIBCXX_HAVE_COSF 1 /* Define to 1 if you have the `coshf' function. */ #define _GLIBCXX_HAVE_COSHF 1 /* Define to 1 if you have the `coshl' function. */ #define _GLIBCXX_HAVE_COSHL 1 /* Define to 1 if you have the `cosl' function. */ #define _GLIBCXX_HAVE_COSL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_DIRENT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_DLFCN_H 1 /* Define if EBADMSG exists. */ #define _GLIBCXX_HAVE_EBADMSG 1 /* Define if ECANCELED exists. */ #define _GLIBCXX_HAVE_ECANCELED 1 /* Define if ECHILD exists. */ #define _GLIBCXX_HAVE_ECHILD 1 /* Define if EIDRM exists. */ #define _GLIBCXX_HAVE_EIDRM 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_ENDIAN_H 1 /* Define if ENODATA exists. */ #define _GLIBCXX_HAVE_ENODATA 1 /* Define if ENOLINK exists. */ #define _GLIBCXX_HAVE_ENOLINK 1 /* Define if ENOSPC exists. */ #define _GLIBCXX_HAVE_ENOSPC 1 /* Define if ENOSR exists. */ #define _GLIBCXX_HAVE_ENOSR 1 /* Define if ENOSTR exists. */ #define _GLIBCXX_HAVE_ENOSTR 1 /* Define if ENOTRECOVERABLE exists. */ #define _GLIBCXX_HAVE_ENOTRECOVERABLE 1 /* Define if ENOTSUP exists. */ #define _GLIBCXX_HAVE_ENOTSUP 1 /* Define if EOVERFLOW exists. */ #define _GLIBCXX_HAVE_EOVERFLOW 1 /* Define if EOWNERDEAD exists. */ #define _GLIBCXX_HAVE_EOWNERDEAD 1 /* Define if EPERM exists. */ #define _GLIBCXX_HAVE_EPERM 1 /* Define if EPROTO exists. */ #define _GLIBCXX_HAVE_EPROTO 1 /* Define if ETIME exists. */ #define _GLIBCXX_HAVE_ETIME 1 /* Define if ETIMEDOUT exists. */ #define _GLIBCXX_HAVE_ETIMEDOUT 1 /* Define if ETXTBSY exists. */ #define _GLIBCXX_HAVE_ETXTBSY 1 /* Define if EWOULDBLOCK exists. */ #define _GLIBCXX_HAVE_EWOULDBLOCK 1 /* Define to 1 if GCC 4.6 supported std::exception_ptr for the target */ #define _GLIBCXX_HAVE_EXCEPTION_PTR_SINCE_GCC46 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_EXECINFO_H 1 /* Define to 1 if you have the `expf' function. */ #define _GLIBCXX_HAVE_EXPF 1 /* Define to 1 if you have the `expl' function. */ #define _GLIBCXX_HAVE_EXPL 1 /* Define to 1 if you have the `fabsf' function. */ #define _GLIBCXX_HAVE_FABSF 1 /* Define to 1 if you have the `fabsl' function. */ #define _GLIBCXX_HAVE_FABSL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FCNTL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FENV_H 1 /* Define to 1 if you have the `finite' function. */ #define _GLIBCXX_HAVE_FINITE 1 /* Define to 1 if you have the `finitef' function. */ #define _GLIBCXX_HAVE_FINITEF 1 /* Define to 1 if you have the `finitel' function. */ #define _GLIBCXX_HAVE_FINITEL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FLOAT_H 1 /* Define to 1 if you have the `floorf' function. */ #define _GLIBCXX_HAVE_FLOORF 1 /* Define to 1 if you have the `floorl' function. */ #define _GLIBCXX_HAVE_FLOORL 1 /* Define to 1 if you have the `fmodf' function. */ #define _GLIBCXX_HAVE_FMODF 1 /* Define to 1 if you have the `fmodl' function. */ #define _GLIBCXX_HAVE_FMODL 1 /* Define to 1 if you have the `fpclass' function. */ /* #undef _GLIBCXX_HAVE_FPCLASS */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_FP_H */ /* Define to 1 if you have the `frexpf' function. */ #define _GLIBCXX_HAVE_FREXPF 1 /* Define to 1 if you have the `frexpl' function. */ #define _GLIBCXX_HAVE_FREXPL 1 /* Define if _Unwind_GetIPInfo is available. */ #define _GLIBCXX_HAVE_GETIPINFO 1 /* Define if gets is available in before C++14. */ #define _GLIBCXX_HAVE_GETS 1 /* Define to 1 if you have the `hypot' function. */ #define _GLIBCXX_HAVE_HYPOT 1 /* Define to 1 if you have the `hypotf' function. */ #define _GLIBCXX_HAVE_HYPOTF 1 /* Define to 1 if you have the `hypotl' function. */ #define _GLIBCXX_HAVE_HYPOTL 1 /* Define if you have the iconv() function. */ #define _GLIBCXX_HAVE_ICONV 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_IEEEFP_H */ /* Define if int64_t is available in . */ #define _GLIBCXX_HAVE_INT64_T 1 /* Define if int64_t is a long. */ #define _GLIBCXX_HAVE_INT64_T_LONG 1 /* Define if int64_t is a long long. */ /* #undef _GLIBCXX_HAVE_INT64_T_LONG_LONG */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_INTTYPES_H 1 /* Define to 1 if you have the `isinf' function. */ /* #undef _GLIBCXX_HAVE_ISINF */ /* Define to 1 if you have the `isinff' function. */ #define _GLIBCXX_HAVE_ISINFF 1 /* Define to 1 if you have the `isinfl' function. */ #define _GLIBCXX_HAVE_ISINFL 1 /* Define to 1 if you have the `isnan' function. */ /* #undef _GLIBCXX_HAVE_ISNAN */ /* Define to 1 if you have the `isnanf' function. */ #define _GLIBCXX_HAVE_ISNANF 1 /* Define to 1 if you have the `isnanl' function. */ #define _GLIBCXX_HAVE_ISNANL 1 /* Defined if iswblank exists. */ #define _GLIBCXX_HAVE_ISWBLANK 1 /* Define if LC_MESSAGES is available in . */ #define _GLIBCXX_HAVE_LC_MESSAGES 1 /* Define to 1 if you have the `ldexpf' function. */ #define _GLIBCXX_HAVE_LDEXPF 1 /* Define to 1 if you have the `ldexpl' function. */ #define _GLIBCXX_HAVE_LDEXPL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LIBINTL_H 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_AS 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_DATA 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_FSIZE 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_RSS 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_VMEM 0 /* Define if futex syscall is available. */ #define _GLIBCXX_HAVE_LINUX_FUTEX 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LINUX_RANDOM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LINUX_TYPES_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LOCALE_H 1 /* Define to 1 if you have the `log10f' function. */ #define _GLIBCXX_HAVE_LOG10F 1 /* Define to 1 if you have the `log10l' function. */ #define _GLIBCXX_HAVE_LOG10L 1 /* Define to 1 if you have the `logf' function. */ #define _GLIBCXX_HAVE_LOGF 1 /* Define to 1 if you have the `logl' function. */ #define _GLIBCXX_HAVE_LOGL 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_MACHINE_ENDIAN_H */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_MACHINE_PARAM_H */ /* Define if mbstate_t exists in wchar.h. */ #define _GLIBCXX_HAVE_MBSTATE_T 1 /* Define to 1 if you have the `memalign' function. */ #define _GLIBCXX_HAVE_MEMALIGN 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_MEMORY_H 1 /* Define to 1 if you have the `modf' function. */ #define _GLIBCXX_HAVE_MODF 1 /* Define to 1 if you have the `modff' function. */ #define _GLIBCXX_HAVE_MODFF 1 /* Define to 1 if you have the `modfl' function. */ #define _GLIBCXX_HAVE_MODFL 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_NAN_H */ /* Define if defines obsolete isinf function. */ /* #undef _GLIBCXX_HAVE_OBSOLETE_ISINF */ /* Define if defines obsolete isnan function. */ /* #undef _GLIBCXX_HAVE_OBSOLETE_ISNAN */ /* Define if poll is available in . */ #define _GLIBCXX_HAVE_POLL 1 /* Define to 1 if you have the `posix_memalign' function. */ #define _GLIBCXX_HAVE_POSIX_MEMALIGN 1 /* Define to 1 if you have the `powf' function. */ #define _GLIBCXX_HAVE_POWF 1 /* Define to 1 if you have the `powl' function. */ #define _GLIBCXX_HAVE_POWL 1 /* Define to 1 if you have the `qfpclass' function. */ /* #undef _GLIBCXX_HAVE_QFPCLASS */ /* Define to 1 if you have the `quick_exit' function. */ #define _GLIBCXX_HAVE_QUICK_EXIT 1 /* Define to 1 if you have the `setenv' function. */ #define _GLIBCXX_HAVE_SETENV 1 /* Define to 1 if you have the `sincos' function. */ #define _GLIBCXX_HAVE_SINCOS 1 /* Define to 1 if you have the `sincosf' function. */ #define _GLIBCXX_HAVE_SINCOSF 1 /* Define to 1 if you have the `sincosl' function. */ #define _GLIBCXX_HAVE_SINCOSL 1 /* Define to 1 if you have the `sinf' function. */ #define _GLIBCXX_HAVE_SINF 1 /* Define to 1 if you have the `sinhf' function. */ #define _GLIBCXX_HAVE_SINHF 1 /* Define to 1 if you have the `sinhl' function. */ #define _GLIBCXX_HAVE_SINHL 1 /* Define to 1 if you have the `sinl' function. */ #define _GLIBCXX_HAVE_SINL 1 /* Defined if sleep exists. */ /* #undef _GLIBCXX_HAVE_SLEEP */ /* Define to 1 if you have the `sqrtf' function. */ #define _GLIBCXX_HAVE_SQRTF 1 /* Define to 1 if you have the `sqrtl' function. */ #define _GLIBCXX_HAVE_SQRTL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDALIGN_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDBOOL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDLIB_H 1 /* Define if strerror_l is available in . */ #define _GLIBCXX_HAVE_STRERROR_L 1 /* Define if strerror_r is available in . */ #define _GLIBCXX_HAVE_STRERROR_R 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STRING_H 1 /* Define to 1 if you have the `strtof' function. */ #define _GLIBCXX_HAVE_STRTOF 1 /* Define to 1 if you have the `strtold' function. */ #define _GLIBCXX_HAVE_STRTOLD 1 /* Define to 1 if `d_type' is a member of `struct dirent'. */ #define _GLIBCXX_HAVE_STRUCT_DIRENT_D_TYPE 1 /* Define if strxfrm_l is available in . */ #define _GLIBCXX_HAVE_STRXFRM_L 1 /* Define to 1 if the target runtime linker supports binding the same symbol to different versions. */ #define _GLIBCXX_HAVE_SYMVER_SYMBOL_RENAMING_RUNTIME_SUPPORT 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_FILIO_H */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_IPC_H 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_ISA_DEFS_H */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_MACHINE_H */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_PARAM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_RESOURCE_H 1 /* Define to 1 if you have a suitable header file */ #define _GLIBCXX_HAVE_SYS_SDT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_SEM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_STATVFS_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_SYSINFO_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_TIME_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_UIO_H 1 /* Define if S_IFREG is available in . */ /* #undef _GLIBCXX_HAVE_S_IFREG */ /* Define if S_ISREG is available in . */ #define _GLIBCXX_HAVE_S_ISREG 1 /* Define to 1 if you have the `tanf' function. */ #define _GLIBCXX_HAVE_TANF 1 /* Define to 1 if you have the `tanhf' function. */ #define _GLIBCXX_HAVE_TANHF 1 /* Define to 1 if you have the `tanhl' function. */ #define _GLIBCXX_HAVE_TANHL 1 /* Define to 1 if you have the `tanl' function. */ #define _GLIBCXX_HAVE_TANL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_TGMATH_H 1 /* Define to 1 if the target supports thread-local storage. */ #define _GLIBCXX_HAVE_TLS 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UCHAR_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UNISTD_H 1 /* Defined if usleep exists. */ /* #undef _GLIBCXX_HAVE_USLEEP */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UTIME_H 1 /* Defined if vfwscanf exists. */ #define _GLIBCXX_HAVE_VFWSCANF 1 /* Defined if vswscanf exists. */ #define _GLIBCXX_HAVE_VSWSCANF 1 /* Defined if vwscanf exists. */ #define _GLIBCXX_HAVE_VWSCANF 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_WCHAR_H 1 /* Defined if wcstof exists. */ #define _GLIBCXX_HAVE_WCSTOF 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_WCTYPE_H 1 /* Defined if Sleep exists. */ /* #undef _GLIBCXX_HAVE_WIN32_SLEEP */ /* Define if writev is available in . */ #define _GLIBCXX_HAVE_WRITEV 1 /* Define to 1 if you have the `_acosf' function. */ /* #undef _GLIBCXX_HAVE__ACOSF */ /* Define to 1 if you have the `_acosl' function. */ /* #undef _GLIBCXX_HAVE__ACOSL */ /* Define to 1 if you have the `_aligned_malloc' function. */ /* #undef _GLIBCXX_HAVE__ALIGNED_MALLOC */ /* Define to 1 if you have the `_asinf' function. */ /* #undef _GLIBCXX_HAVE__ASINF */ /* Define to 1 if you have the `_asinl' function. */ /* #undef _GLIBCXX_HAVE__ASINL */ /* Define to 1 if you have the `_atan2f' function. */ /* #undef _GLIBCXX_HAVE__ATAN2F */ /* Define to 1 if you have the `_atan2l' function. */ /* #undef _GLIBCXX_HAVE__ATAN2L */ /* Define to 1 if you have the `_atanf' function. */ /* #undef _GLIBCXX_HAVE__ATANF */ /* Define to 1 if you have the `_atanl' function. */ /* #undef _GLIBCXX_HAVE__ATANL */ /* Define to 1 if you have the `_ceilf' function. */ /* #undef _GLIBCXX_HAVE__CEILF */ /* Define to 1 if you have the `_ceill' function. */ /* #undef _GLIBCXX_HAVE__CEILL */ /* Define to 1 if you have the `_cosf' function. */ /* #undef _GLIBCXX_HAVE__COSF */ /* Define to 1 if you have the `_coshf' function. */ /* #undef _GLIBCXX_HAVE__COSHF */ /* Define to 1 if you have the `_coshl' function. */ /* #undef _GLIBCXX_HAVE__COSHL */ /* Define to 1 if you have the `_cosl' function. */ /* #undef _GLIBCXX_HAVE__COSL */ /* Define to 1 if you have the `_expf' function. */ /* #undef _GLIBCXX_HAVE__EXPF */ /* Define to 1 if you have the `_expl' function. */ /* #undef _GLIBCXX_HAVE__EXPL */ /* Define to 1 if you have the `_fabsf' function. */ /* #undef _GLIBCXX_HAVE__FABSF */ /* Define to 1 if you have the `_fabsl' function. */ /* #undef _GLIBCXX_HAVE__FABSL */ /* Define to 1 if you have the `_finite' function. */ /* #undef _GLIBCXX_HAVE__FINITE */ /* Define to 1 if you have the `_finitef' function. */ /* #undef _GLIBCXX_HAVE__FINITEF */ /* Define to 1 if you have the `_finitel' function. */ /* #undef _GLIBCXX_HAVE__FINITEL */ /* Define to 1 if you have the `_floorf' function. */ /* #undef _GLIBCXX_HAVE__FLOORF */ /* Define to 1 if you have the `_floorl' function. */ /* #undef _GLIBCXX_HAVE__FLOORL */ /* Define to 1 if you have the `_fmodf' function. */ /* #undef _GLIBCXX_HAVE__FMODF */ /* Define to 1 if you have the `_fmodl' function. */ /* #undef _GLIBCXX_HAVE__FMODL */ /* Define to 1 if you have the `_fpclass' function. */ /* #undef _GLIBCXX_HAVE__FPCLASS */ /* Define to 1 if you have the `_frexpf' function. */ /* #undef _GLIBCXX_HAVE__FREXPF */ /* Define to 1 if you have the `_frexpl' function. */ /* #undef _GLIBCXX_HAVE__FREXPL */ /* Define to 1 if you have the `_hypot' function. */ /* #undef _GLIBCXX_HAVE__HYPOT */ /* Define to 1 if you have the `_hypotf' function. */ /* #undef _GLIBCXX_HAVE__HYPOTF */ /* Define to 1 if you have the `_hypotl' function. */ /* #undef _GLIBCXX_HAVE__HYPOTL */ /* Define to 1 if you have the `_isinf' function. */ /* #undef _GLIBCXX_HAVE__ISINF */ /* Define to 1 if you have the `_isinff' function. */ /* #undef _GLIBCXX_HAVE__ISINFF */ /* Define to 1 if you have the `_isinfl' function. */ /* #undef _GLIBCXX_HAVE__ISINFL */ /* Define to 1 if you have the `_isnan' function. */ /* #undef _GLIBCXX_HAVE__ISNAN */ /* Define to 1 if you have the `_isnanf' function. */ /* #undef _GLIBCXX_HAVE__ISNANF */ /* Define to 1 if you have the `_isnanl' function. */ /* #undef _GLIBCXX_HAVE__ISNANL */ /* Define to 1 if you have the `_ldexpf' function. */ /* #undef _GLIBCXX_HAVE__LDEXPF */ /* Define to 1 if you have the `_ldexpl' function. */ /* #undef _GLIBCXX_HAVE__LDEXPL */ /* Define to 1 if you have the `_log10f' function. */ /* #undef _GLIBCXX_HAVE__LOG10F */ /* Define to 1 if you have the `_log10l' function. */ /* #undef _GLIBCXX_HAVE__LOG10L */ /* Define to 1 if you have the `_logf' function. */ /* #undef _GLIBCXX_HAVE__LOGF */ /* Define to 1 if you have the `_logl' function. */ /* #undef _GLIBCXX_HAVE__LOGL */ /* Define to 1 if you have the `_modf' function. */ /* #undef _GLIBCXX_HAVE__MODF */ /* Define to 1 if you have the `_modff' function. */ /* #undef _GLIBCXX_HAVE__MODFF */ /* Define to 1 if you have the `_modfl' function. */ /* #undef _GLIBCXX_HAVE__MODFL */ /* Define to 1 if you have the `_powf' function. */ /* #undef _GLIBCXX_HAVE__POWF */ /* Define to 1 if you have the `_powl' function. */ /* #undef _GLIBCXX_HAVE__POWL */ /* Define to 1 if you have the `_qfpclass' function. */ /* #undef _GLIBCXX_HAVE__QFPCLASS */ /* Define to 1 if you have the `_sincos' function. */ /* #undef _GLIBCXX_HAVE__SINCOS */ /* Define to 1 if you have the `_sincosf' function. */ /* #undef _GLIBCXX_HAVE__SINCOSF */ /* Define to 1 if you have the `_sincosl' function. */ /* #undef _GLIBCXX_HAVE__SINCOSL */ /* Define to 1 if you have the `_sinf' function. */ /* #undef _GLIBCXX_HAVE__SINF */ /* Define to 1 if you have the `_sinhf' function. */ /* #undef _GLIBCXX_HAVE__SINHF */ /* Define to 1 if you have the `_sinhl' function. */ /* #undef _GLIBCXX_HAVE__SINHL */ /* Define to 1 if you have the `_sinl' function. */ /* #undef _GLIBCXX_HAVE__SINL */ /* Define to 1 if you have the `_sqrtf' function. */ /* #undef _GLIBCXX_HAVE__SQRTF */ /* Define to 1 if you have the `_sqrtl' function. */ /* #undef _GLIBCXX_HAVE__SQRTL */ /* Define to 1 if you have the `_tanf' function. */ /* #undef _GLIBCXX_HAVE__TANF */ /* Define to 1 if you have the `_tanhf' function. */ /* #undef _GLIBCXX_HAVE__TANHF */ /* Define to 1 if you have the `_tanhl' function. */ /* #undef _GLIBCXX_HAVE__TANHL */ /* Define to 1 if you have the `_tanl' function. */ /* #undef _GLIBCXX_HAVE__TANL */ /* Define to 1 if you have the `__cxa_thread_atexit' function. */ /* #undef _GLIBCXX_HAVE___CXA_THREAD_ATEXIT */ /* Define to 1 if you have the `__cxa_thread_atexit_impl' function. */ #define _GLIBCXX_HAVE___CXA_THREAD_ATEXIT_IMPL 1 /* Define as const if the declaration of iconv() needs const. */ #define _GLIBCXX_ICONV_CONST /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Name of package */ /* #undef _GLIBCXX_PACKAGE */ /* Define to the address where bug reports for this package should be sent. */ #define _GLIBCXX_PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define _GLIBCXX_PACKAGE_NAME "package-unused" /* Define to the full name and version of this package. */ #define _GLIBCXX_PACKAGE_STRING "package-unused version-unused" /* Define to the one symbol short name of this package. */ #define _GLIBCXX_PACKAGE_TARNAME "libstdc++" /* Define to the home page for this package. */ #define _GLIBCXX_PACKAGE_URL "" /* Define to the version of this package. */ #define _GLIBCXX_PACKAGE__GLIBCXX_VERSION "version-unused" /* The size of `char', as computed by sizeof. */ /* #undef SIZEOF_CHAR */ /* The size of `int', as computed by sizeof. */ /* #undef SIZEOF_INT */ /* The size of `long', as computed by sizeof. */ /* #undef SIZEOF_LONG */ /* The size of `short', as computed by sizeof. */ /* #undef SIZEOF_SHORT */ /* The size of `void *', as computed by sizeof. */ /* #undef SIZEOF_VOID_P */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ /* #undef _GLIBCXX_VERSION */ /* Number of bits in a file offset, on hosts where this is settable. */ /* #undef _GLIBCXX_FILE_OFFSET_BITS */ /* Define if C99 functions in should be used in for C++11. Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX11_USE_C99_COMPLEX 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_MATH 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_STDIO 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_STDLIB 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_WCHAR 1 /* Define if C99 functions in should be used in for C++98. Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX98_USE_C99_COMPLEX 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_MATH 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_STDIO 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_STDLIB 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_WCHAR 1 /* Define if the compiler supports C++11 atomics. */ #define _GLIBCXX_ATOMIC_BUILTINS 1 /* Define to use concept checking code from the boost libraries. */ /* #undef _GLIBCXX_CONCEPT_CHECKS */ /* Define to 1 if a fully dynamic basic_string is wanted, 0 to disable, undefined for platform defaults */ #define _GLIBCXX_FULLY_DYNAMIC_STRING 0 /* Define if gthreads library is available. */ #define _GLIBCXX_HAS_GTHREADS 1 /* Define to 1 if a full hosted library is built, or 0 if freestanding. */ #define _GLIBCXX_HOSTED 1 /* Define if compatibility should be provided for -mlong-double-64. */ /* Define to the letter to which size_t is mangled. */ #define _GLIBCXX_MANGLE_SIZE_T m /* Define if C99 llrint and llround functions are missing from . */ /* #undef _GLIBCXX_NO_C99_ROUNDING_FUNCS */ /* Define if ptrdiff_t is int. */ /* #undef _GLIBCXX_PTRDIFF_T_IS_INT */ /* Define if using setrlimit to set resource limits during "make check" */ #define _GLIBCXX_RES_LIMITS 1 /* Define if size_t is unsigned int. */ /* #undef _GLIBCXX_SIZE_T_IS_UINT */ /* Define to the value of the EOF integer constant. */ #define _GLIBCXX_STDIO_EOF -1 /* Define to the value of the SEEK_CUR integer constant. */ #define _GLIBCXX_STDIO_SEEK_CUR 1 /* Define to the value of the SEEK_END integer constant. */ #define _GLIBCXX_STDIO_SEEK_END 2 /* Define to use symbol versioning in the shared library. */ #define _GLIBCXX_SYMVER 1 /* Define to use darwin versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_DARWIN */ /* Define to use GNU versioning in the shared library. */ #define _GLIBCXX_SYMVER_GNU 1 /* Define to use GNU namespace versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_GNU_NAMESPACE */ /* Define to use Sun versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_SUN */ /* Define if C11 functions in should be imported into namespace std in . */ #define _GLIBCXX_USE_C11_UCHAR_CXX11 1 /* Define if C99 functions or macros from , , , , and can be used or exposed. */ #define _GLIBCXX_USE_C99 1 /* Define if C99 functions in should be used in . Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX_USE_C99_COMPLEX_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_CTYPE_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_FENV_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_INTTYPES_TR1 1 /* Define if wchar_t C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_INTTYPES_WCHAR_T_TR1 1 /* Define if C99 functions or macros in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_MATH_TR1 1 /* Define if C99 types in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_STDINT_TR1 1 /* Defined if clock_gettime syscall has monotonic and realtime clock support. */ /* #undef _GLIBCXX_USE_CLOCK_GETTIME_SYSCALL */ /* Defined if clock_gettime has monotonic clock support. */ #define _GLIBCXX_USE_CLOCK_MONOTONIC 1 /* Defined if clock_gettime has realtime clock support. */ #define _GLIBCXX_USE_CLOCK_REALTIME 1 /* Define if ISO/IEC TR 24733 decimal floating point types are supported on this host. */ #define _GLIBCXX_USE_DECIMAL_FLOAT 1 /* Define if fchmod is available in . */ #define _GLIBCXX_USE_FCHMOD 1 /* Define if fchmodat is available in . */ #define _GLIBCXX_USE_FCHMODAT 1 /* Defined if gettimeofday is available. */ #define _GLIBCXX_USE_GETTIMEOFDAY 1 /* Define if get_nprocs is available in . */ #define _GLIBCXX_USE_GET_NPROCS 1 /* Define if __int128 is supported on this host. */ #define _GLIBCXX_USE_INT128 1 /* Define if LFS support is available. */ #define _GLIBCXX_USE_LFS 1 /* Define if code specialized for long long should be used. */ #define _GLIBCXX_USE_LONG_LONG 1 /* Defined if nanosleep is available. */ #define _GLIBCXX_USE_NANOSLEEP 1 /* Define if NLS translations are to be used. */ #define _GLIBCXX_USE_NLS 1 /* Define if pthreads_num_processors_np is available in . */ /* #undef _GLIBCXX_USE_PTHREADS_NUM_PROCESSORS_NP */ /* Define if POSIX read/write locks are available in . */ #define _GLIBCXX_USE_PTHREAD_RWLOCK_T 1 /* Define if /dev/random and /dev/urandom are available for the random_device of TR1 (Chapter 5.1). */ #define _GLIBCXX_USE_RANDOM_TR1 1 /* Define if usable realpath is available in . */ #define _GLIBCXX_USE_REALPATH 1 /* Defined if sched_yield is available. */ #define _GLIBCXX_USE_SCHED_YIELD 1 /* Define if _SC_NPROCESSORS_ONLN is available in . */ #define _GLIBCXX_USE_SC_NPROCESSORS_ONLN 1 /* Define if _SC_NPROC_ONLN is available in . */ /* #undef _GLIBCXX_USE_SC_NPROC_ONLN */ /* Define if sendfile is available in . */ #define _GLIBCXX_USE_SENDFILE 1 /* Define if struct stat has timespec members. */ #define _GLIBCXX_USE_ST_MTIM 1 /* Define if sysctl(), CTL_HW and HW_NCPU are available in . */ /* #undef _GLIBCXX_USE_SYSCTL_HW_NCPU */ /* Define if obsolescent tmpnam is available in . */ #define _GLIBCXX_USE_TMPNAM 1 /* Define if utimensat and UTIME_OMIT are available in and AT_FDCWD in . */ #define _GLIBCXX_USE_UTIMENSAT 1 /* Define if code specialized for wchar_t should be used. */ #define _GLIBCXX_USE_WCHAR_T 1 /* Define to 1 if a verbose library is built, or 0 otherwise. */ #define _GLIBCXX_VERBOSE 1 /* Defined if as can handle rdrand. */ #define _GLIBCXX_X86_RDRAND 1 /* Define to 1 if mutex_timedlock is available. */ #define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 /* Define for large files, on AIX-style hosts. */ /* #undef _GLIBCXX_LARGE_FILES */ /* Define if all C++11 floating point overloads are available in . */ #if __cplusplus >= 201103L /* #undef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP */ #endif /* Define if all C++11 integral type overloads are available in . */ #if __cplusplus >= 201103L /* #undef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT */ #endif #if defined (_GLIBCXX_HAVE__ACOSF) && ! defined (_GLIBCXX_HAVE_ACOSF) # define _GLIBCXX_HAVE_ACOSF 1 # define acosf _acosf #endif #if defined (_GLIBCXX_HAVE__ACOSL) && ! defined (_GLIBCXX_HAVE_ACOSL) # define _GLIBCXX_HAVE_ACOSL 1 # define acosl _acosl #endif #if defined (_GLIBCXX_HAVE__ASINF) && ! defined (_GLIBCXX_HAVE_ASINF) # define _GLIBCXX_HAVE_ASINF 1 # define asinf _asinf #endif #if defined (_GLIBCXX_HAVE__ASINL) && ! defined (_GLIBCXX_HAVE_ASINL) # define _GLIBCXX_HAVE_ASINL 1 # define asinl _asinl #endif #if defined (_GLIBCXX_HAVE__ATAN2F) && ! defined (_GLIBCXX_HAVE_ATAN2F) # define _GLIBCXX_HAVE_ATAN2F 1 # define atan2f _atan2f #endif #if defined (_GLIBCXX_HAVE__ATAN2L) && ! defined (_GLIBCXX_HAVE_ATAN2L) # define _GLIBCXX_HAVE_ATAN2L 1 # define atan2l _atan2l #endif #if defined (_GLIBCXX_HAVE__ATANF) && ! defined (_GLIBCXX_HAVE_ATANF) # define _GLIBCXX_HAVE_ATANF 1 # define atanf _atanf #endif #if defined (_GLIBCXX_HAVE__ATANL) && ! defined (_GLIBCXX_HAVE_ATANL) # define _GLIBCXX_HAVE_ATANL 1 # define atanl _atanl #endif #if defined (_GLIBCXX_HAVE__CEILF) && ! defined (_GLIBCXX_HAVE_CEILF) # define _GLIBCXX_HAVE_CEILF 1 # define ceilf _ceilf #endif #if defined (_GLIBCXX_HAVE__CEILL) && ! defined (_GLIBCXX_HAVE_CEILL) # define _GLIBCXX_HAVE_CEILL 1 # define ceill _ceill #endif #if defined (_GLIBCXX_HAVE__COSF) && ! defined (_GLIBCXX_HAVE_COSF) # define _GLIBCXX_HAVE_COSF 1 # define cosf _cosf #endif #if defined (_GLIBCXX_HAVE__COSHF) && ! defined (_GLIBCXX_HAVE_COSHF) # define _GLIBCXX_HAVE_COSHF 1 # define coshf _coshf #endif #if defined (_GLIBCXX_HAVE__COSHL) && ! defined (_GLIBCXX_HAVE_COSHL) # define _GLIBCXX_HAVE_COSHL 1 # define coshl _coshl #endif #if defined (_GLIBCXX_HAVE__COSL) && ! defined (_GLIBCXX_HAVE_COSL) # define _GLIBCXX_HAVE_COSL 1 # define cosl _cosl #endif #if defined (_GLIBCXX_HAVE__EXPF) && ! defined (_GLIBCXX_HAVE_EXPF) # define _GLIBCXX_HAVE_EXPF 1 # define expf _expf #endif #if defined (_GLIBCXX_HAVE__EXPL) && ! defined (_GLIBCXX_HAVE_EXPL) # define _GLIBCXX_HAVE_EXPL 1 # define expl _expl #endif #if defined (_GLIBCXX_HAVE__FABSF) && ! defined (_GLIBCXX_HAVE_FABSF) # define _GLIBCXX_HAVE_FABSF 1 # define fabsf _fabsf #endif #if defined (_GLIBCXX_HAVE__FABSL) && ! defined (_GLIBCXX_HAVE_FABSL) # define _GLIBCXX_HAVE_FABSL 1 # define fabsl _fabsl #endif #if defined (_GLIBCXX_HAVE__FINITE) && ! defined (_GLIBCXX_HAVE_FINITE) # define _GLIBCXX_HAVE_FINITE 1 # define finite _finite #endif #if defined (_GLIBCXX_HAVE__FINITEF) && ! defined (_GLIBCXX_HAVE_FINITEF) # define _GLIBCXX_HAVE_FINITEF 1 # define finitef _finitef #endif #if defined (_GLIBCXX_HAVE__FINITEL) && ! defined (_GLIBCXX_HAVE_FINITEL) # define _GLIBCXX_HAVE_FINITEL 1 # define finitel _finitel #endif #if defined (_GLIBCXX_HAVE__FLOORF) && ! defined (_GLIBCXX_HAVE_FLOORF) # define _GLIBCXX_HAVE_FLOORF 1 # define floorf _floorf #endif #if defined (_GLIBCXX_HAVE__FLOORL) && ! defined (_GLIBCXX_HAVE_FLOORL) # define _GLIBCXX_HAVE_FLOORL 1 # define floorl _floorl #endif #if defined (_GLIBCXX_HAVE__FMODF) && ! defined (_GLIBCXX_HAVE_FMODF) # define _GLIBCXX_HAVE_FMODF 1 # define fmodf _fmodf #endif #if defined (_GLIBCXX_HAVE__FMODL) && ! defined (_GLIBCXX_HAVE_FMODL) # define _GLIBCXX_HAVE_FMODL 1 # define fmodl _fmodl #endif #if defined (_GLIBCXX_HAVE__FPCLASS) && ! defined (_GLIBCXX_HAVE_FPCLASS) # define _GLIBCXX_HAVE_FPCLASS 1 # define fpclass _fpclass #endif #if defined (_GLIBCXX_HAVE__FREXPF) && ! defined (_GLIBCXX_HAVE_FREXPF) # define _GLIBCXX_HAVE_FREXPF 1 # define frexpf _frexpf #endif #if defined (_GLIBCXX_HAVE__FREXPL) && ! defined (_GLIBCXX_HAVE_FREXPL) # define _GLIBCXX_HAVE_FREXPL 1 # define frexpl _frexpl #endif #if defined (_GLIBCXX_HAVE__HYPOT) && ! defined (_GLIBCXX_HAVE_HYPOT) # define _GLIBCXX_HAVE_HYPOT 1 # define hypot _hypot #endif #if defined (_GLIBCXX_HAVE__HYPOTF) && ! defined (_GLIBCXX_HAVE_HYPOTF) # define _GLIBCXX_HAVE_HYPOTF 1 # define hypotf _hypotf #endif #if defined (_GLIBCXX_HAVE__HYPOTL) && ! defined (_GLIBCXX_HAVE_HYPOTL) # define _GLIBCXX_HAVE_HYPOTL 1 # define hypotl _hypotl #endif #if defined (_GLIBCXX_HAVE__ISINF) && ! defined (_GLIBCXX_HAVE_ISINF) # define _GLIBCXX_HAVE_ISINF 1 # define isinf _isinf #endif #if defined (_GLIBCXX_HAVE__ISINFF) && ! defined (_GLIBCXX_HAVE_ISINFF) # define _GLIBCXX_HAVE_ISINFF 1 # define isinff _isinff #endif #if defined (_GLIBCXX_HAVE__ISINFL) && ! defined (_GLIBCXX_HAVE_ISINFL) # define _GLIBCXX_HAVE_ISINFL 1 # define isinfl _isinfl #endif #if defined (_GLIBCXX_HAVE__ISNAN) && ! defined (_GLIBCXX_HAVE_ISNAN) # define _GLIBCXX_HAVE_ISNAN 1 # define isnan _isnan #endif #if defined (_GLIBCXX_HAVE__ISNANF) && ! defined (_GLIBCXX_HAVE_ISNANF) # define _GLIBCXX_HAVE_ISNANF 1 # define isnanf _isnanf #endif #if defined (_GLIBCXX_HAVE__ISNANL) && ! defined (_GLIBCXX_HAVE_ISNANL) # define _GLIBCXX_HAVE_ISNANL 1 # define isnanl _isnanl #endif #if defined (_GLIBCXX_HAVE__LDEXPF) && ! defined (_GLIBCXX_HAVE_LDEXPF) # define _GLIBCXX_HAVE_LDEXPF 1 # define ldexpf _ldexpf #endif #if defined (_GLIBCXX_HAVE__LDEXPL) && ! defined (_GLIBCXX_HAVE_LDEXPL) # define _GLIBCXX_HAVE_LDEXPL 1 # define ldexpl _ldexpl #endif #if defined (_GLIBCXX_HAVE__LOG10F) && ! defined (_GLIBCXX_HAVE_LOG10F) # define _GLIBCXX_HAVE_LOG10F 1 # define log10f _log10f #endif #if defined (_GLIBCXX_HAVE__LOG10L) && ! defined (_GLIBCXX_HAVE_LOG10L) # define _GLIBCXX_HAVE_LOG10L 1 # define log10l _log10l #endif #if defined (_GLIBCXX_HAVE__LOGF) && ! defined (_GLIBCXX_HAVE_LOGF) # define _GLIBCXX_HAVE_LOGF 1 # define logf _logf #endif #if defined (_GLIBCXX_HAVE__LOGL) && ! defined (_GLIBCXX_HAVE_LOGL) # define _GLIBCXX_HAVE_LOGL 1 # define logl _logl #endif #if defined (_GLIBCXX_HAVE__MODF) && ! defined (_GLIBCXX_HAVE_MODF) # define _GLIBCXX_HAVE_MODF 1 # define modf _modf #endif #if defined (_GLIBCXX_HAVE__MODFF) && ! defined (_GLIBCXX_HAVE_MODFF) # define _GLIBCXX_HAVE_MODFF 1 # define modff _modff #endif #if defined (_GLIBCXX_HAVE__MODFL) && ! defined (_GLIBCXX_HAVE_MODFL) # define _GLIBCXX_HAVE_MODFL 1 # define modfl _modfl #endif #if defined (_GLIBCXX_HAVE__POWF) && ! defined (_GLIBCXX_HAVE_POWF) # define _GLIBCXX_HAVE_POWF 1 # define powf _powf #endif #if defined (_GLIBCXX_HAVE__POWL) && ! defined (_GLIBCXX_HAVE_POWL) # define _GLIBCXX_HAVE_POWL 1 # define powl _powl #endif #if defined (_GLIBCXX_HAVE__QFPCLASS) && ! defined (_GLIBCXX_HAVE_QFPCLASS) # define _GLIBCXX_HAVE_QFPCLASS 1 # define qfpclass _qfpclass #endif #if defined (_GLIBCXX_HAVE__SINCOS) && ! defined (_GLIBCXX_HAVE_SINCOS) # define _GLIBCXX_HAVE_SINCOS 1 # define sincos _sincos #endif #if defined (_GLIBCXX_HAVE__SINCOSF) && ! defined (_GLIBCXX_HAVE_SINCOSF) # define _GLIBCXX_HAVE_SINCOSF 1 # define sincosf _sincosf #endif #if defined (_GLIBCXX_HAVE__SINCOSL) && ! defined (_GLIBCXX_HAVE_SINCOSL) # define _GLIBCXX_HAVE_SINCOSL 1 # define sincosl _sincosl #endif #if defined (_GLIBCXX_HAVE__SINF) && ! defined (_GLIBCXX_HAVE_SINF) # define _GLIBCXX_HAVE_SINF 1 # define sinf _sinf #endif #if defined (_GLIBCXX_HAVE__SINHF) && ! defined (_GLIBCXX_HAVE_SINHF) # define _GLIBCXX_HAVE_SINHF 1 # define sinhf _sinhf #endif #if defined (_GLIBCXX_HAVE__SINHL) && ! defined (_GLIBCXX_HAVE_SINHL) # define _GLIBCXX_HAVE_SINHL 1 # define sinhl _sinhl #endif #if defined (_GLIBCXX_HAVE__SINL) && ! defined (_GLIBCXX_HAVE_SINL) # define _GLIBCXX_HAVE_SINL 1 # define sinl _sinl #endif #if defined (_GLIBCXX_HAVE__SQRTF) && ! defined (_GLIBCXX_HAVE_SQRTF) # define _GLIBCXX_HAVE_SQRTF 1 # define sqrtf _sqrtf #endif #if defined (_GLIBCXX_HAVE__SQRTL) && ! defined (_GLIBCXX_HAVE_SQRTL) # define _GLIBCXX_HAVE_SQRTL 1 # define sqrtl _sqrtl #endif #if defined (_GLIBCXX_HAVE__STRTOF) && ! defined (_GLIBCXX_HAVE_STRTOF) # define _GLIBCXX_HAVE_STRTOF 1 # define strtof _strtof #endif #if defined (_GLIBCXX_HAVE__STRTOLD) && ! defined (_GLIBCXX_HAVE_STRTOLD) # define _GLIBCXX_HAVE_STRTOLD 1 # define strtold _strtold #endif #if defined (_GLIBCXX_HAVE__TANF) && ! defined (_GLIBCXX_HAVE_TANF) # define _GLIBCXX_HAVE_TANF 1 # define tanf _tanf #endif #if defined (_GLIBCXX_HAVE__TANHF) && ! defined (_GLIBCXX_HAVE_TANHF) # define _GLIBCXX_HAVE_TANHF 1 # define tanhf _tanhf #endif #if defined (_GLIBCXX_HAVE__TANHL) && ! defined (_GLIBCXX_HAVE_TANHL) # define _GLIBCXX_HAVE_TANHL 1 # define tanhl _tanhl #endif #if defined (_GLIBCXX_HAVE__TANL) && ! defined (_GLIBCXX_HAVE_TANL) # define _GLIBCXX_HAVE_TANL 1 # define tanl _tanl #endif #endif // _GLIBCXX_CXX_CONFIG_H #endif #endif c++/8/x86_64-redhat-linux/bits/ctype_inline.h000064400000004354151027430570014431 0ustar00// Locale support -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ctype_inline.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // // ctype bits to be inlined go here. Non-inlinable (ie virtual do_*) // functions go in ctype.cc namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION bool ctype:: is(mask __m, char __c) const { return _M_table[static_cast(__c)] & __m; } const char* ctype:: is(const char* __low, const char* __high, mask* __vec) const { while (__low < __high) *__vec++ = _M_table[static_cast(*__low++)]; return __high; } const char* ctype:: scan_is(mask __m, const char* __low, const char* __high) const { while (__low < __high && !(_M_table[static_cast(*__low)] & __m)) ++__low; return __low; } const char* ctype:: scan_not(mask __m, const char* __low, const char* __high) const { while (__low < __high && (_M_table[static_cast(*__low)] & __m) != 0) ++__low; return __low; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/bits/gthr-single.h000064400000015230151027430570014165 0ustar00/* Threads compatibility routines for libgcc2 and libobjc. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_SINGLE_H #define _GLIBCXX_GCC_GTHR_SINGLE_H /* Just provide compatibility for mutex handling. */ typedef int __gthread_key_t; typedef int __gthread_once_t; typedef int __gthread_mutex_t; typedef int __gthread_recursive_mutex_t; #define __GTHREAD_ONCE_INIT 0 #define __GTHREAD_MUTEX_INIT 0 #define __GTHREAD_MUTEX_INIT_FUNCTION(mx) do {} while (0) #define __GTHREAD_RECURSIVE_MUTEX_INIT 0 #define _GLIBCXX_UNUSED __attribute__((__unused__)) #ifdef _LIBOBJC /* Thread local storage for a single thread */ static void *thread_local_storage = NULL; /* Backend initialization functions */ /* Initialize the threads subsystem. */ static inline int __gthread_objc_init_thread_system (void) { /* No thread support available */ return -1; } /* Close the threads subsystem. */ static inline int __gthread_objc_close_thread_system (void) { /* No thread support available */ return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ static inline objc_thread_t __gthread_objc_thread_detach (void (* func)(void *), void * arg _GLIBCXX_UNUSED) { /* No thread support available */ return NULL; } /* Set the current thread's priority. */ static inline int __gthread_objc_thread_set_priority (int priority _GLIBCXX_UNUSED) { /* No thread support available */ return -1; } /* Return the current thread's priority. */ static inline int __gthread_objc_thread_get_priority (void) { return OBJC_THREAD_INTERACTIVE_PRIORITY; } /* Yield our process time to another thread. */ static inline void __gthread_objc_thread_yield (void) { return; } /* Terminate the current thread. */ static inline int __gthread_objc_thread_exit (void) { /* No thread support available */ /* Should we really exit the program */ /* exit (&__objc_thread_exit_status); */ return -1; } /* Returns an integer value which uniquely describes a thread. */ static inline objc_thread_t __gthread_objc_thread_id (void) { /* No thread support, use 1. */ return (objc_thread_t) 1; } /* Sets the thread's local storage pointer. */ static inline int __gthread_objc_thread_set_data (void *value) { thread_local_storage = value; return 0; } /* Returns the thread's local storage pointer. */ static inline void * __gthread_objc_thread_get_data (void) { return thread_local_storage; } /* Backend mutex functions */ /* Allocate a mutex. */ static inline int __gthread_objc_mutex_allocate (objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Deallocate a mutex. */ static inline int __gthread_objc_mutex_deallocate (objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Grab a lock on a mutex. */ static inline int __gthread_objc_mutex_lock (objc_mutex_t mutex _GLIBCXX_UNUSED) { /* There can only be one thread, so we always get the lock */ return 0; } /* Try to grab a lock on a mutex. */ static inline int __gthread_objc_mutex_trylock (objc_mutex_t mutex _GLIBCXX_UNUSED) { /* There can only be one thread, so we always get the lock */ return 0; } /* Unlock the mutex */ static inline int __gthread_objc_mutex_unlock (objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Backend condition mutex functions */ /* Allocate a condition. */ static inline int __gthread_objc_condition_allocate (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } /* Deallocate a condition. */ static inline int __gthread_objc_condition_deallocate (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } /* Wait on the condition */ static inline int __gthread_objc_condition_wait (objc_condition_t condition _GLIBCXX_UNUSED, objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Wake up all threads waiting on this condition. */ static inline int __gthread_objc_condition_broadcast (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } /* Wake up one thread waiting on this condition. */ static inline int __gthread_objc_condition_signal (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } #else /* _LIBOBJC */ static inline int __gthread_active_p (void) { return 0; } static inline int __gthread_once (__gthread_once_t *__once _GLIBCXX_UNUSED, void (*__func) (void) _GLIBCXX_UNUSED) { return 0; } static inline int _GLIBCXX_UNUSED __gthread_key_create (__gthread_key_t *__key _GLIBCXX_UNUSED, void (*__func) (void *) _GLIBCXX_UNUSED) { return 0; } static int _GLIBCXX_UNUSED __gthread_key_delete (__gthread_key_t __key _GLIBCXX_UNUSED) { return 0; } static inline void * __gthread_getspecific (__gthread_key_t __key _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_setspecific (__gthread_key_t __key _GLIBCXX_UNUSED, const void *__v _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_destroy (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_lock (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_trylock (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_unlock (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_lock (__mutex); } static inline int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_trylock (__mutex); } static inline int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_unlock (__mutex); } static inline int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_destroy (__mutex); } #endif /* _LIBOBJC */ #undef _GLIBCXX_UNUSED #endif /* ! _GLIBCXX_GCC_GTHR_SINGLE_H */ c++/8/x86_64-redhat-linux/bits/c++allocator.h000064400000003673151027430570014223 0ustar00// Base to std::allocator -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++allocator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _GLIBCXX_CXX_ALLOCATOR_H #define _GLIBCXX_CXX_ALLOCATOR_H 1 #include #if __cplusplus >= 201103L namespace std { /** * @brief An alias to the base class for std::allocator. * @ingroup allocators * * Used to set the std::allocator base class to * __gnu_cxx::new_allocator. * * @tparam _Tp Type of allocated object. */ template using __allocator_base = __gnu_cxx::new_allocator<_Tp>; } #else // Define new_allocator as the base class to std::allocator. # define __allocator_base __gnu_cxx::new_allocator #endif #if defined(__SANITIZE_ADDRESS__) && !defined(_GLIBCXX_SANITIZE_STD_ALLOCATOR) # define _GLIBCXX_SANITIZE_STD_ALLOCATOR 1 #endif #endif c++/8/x86_64-redhat-linux/bits/messages_members.h000064400000010644151027430570015267 0ustar00// std::messages implementation details, GNU version -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/messages_members.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.2.7.1.2 messages functions // // Written by Benjamin Kosnik #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Non-virtual member functions. template messages<_CharT>::messages(size_t __refs) : facet(__refs), _M_c_locale_messages(_S_get_c_locale()), _M_name_messages(_S_get_c_name()) { } template messages<_CharT>::messages(__c_locale __cloc, const char* __s, size_t __refs) : facet(__refs), _M_c_locale_messages(0), _M_name_messages(0) { if (__builtin_strcmp(__s, _S_get_c_name()) != 0) { const size_t __len = __builtin_strlen(__s) + 1; char* __tmp = new char[__len]; __builtin_memcpy(__tmp, __s, __len); _M_name_messages = __tmp; } else _M_name_messages = _S_get_c_name(); // Last to avoid leaking memory if new throws. _M_c_locale_messages = _S_clone_c_locale(__cloc); } template typename messages<_CharT>::catalog messages<_CharT>::open(const basic_string& __s, const locale& __loc, const char* __dir) const { bindtextdomain(__s.c_str(), __dir); return this->do_open(__s, __loc); } // Virtual member functions. template messages<_CharT>::~messages() { if (_M_name_messages != _S_get_c_name()) delete [] _M_name_messages; _S_destroy_c_locale(_M_c_locale_messages); } template typename messages<_CharT>::catalog messages<_CharT>::do_open(const basic_string& __s, const locale&) const { // No error checking is done, assume the catalog exists and can // be used. textdomain(__s.c_str()); return 0; } template void messages<_CharT>::do_close(catalog) const { } // messages_byname template messages_byname<_CharT>::messages_byname(const char* __s, size_t __refs) : messages<_CharT>(__refs) { if (this->_M_name_messages != locale::facet::_S_get_c_name()) { delete [] this->_M_name_messages; if (__builtin_strcmp(__s, locale::facet::_S_get_c_name()) != 0) { const size_t __len = __builtin_strlen(__s) + 1; char* __tmp = new char[__len]; __builtin_memcpy(__tmp, __s, __len); this->_M_name_messages = __tmp; } else this->_M_name_messages = locale::facet::_S_get_c_name(); } if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { this->_S_destroy_c_locale(this->_M_c_locale_messages); this->_S_create_c_locale(this->_M_c_locale_messages, __s); } } //Specializations. template<> typename messages::catalog messages::do_open(const basic_string&, const locale&) const; template<> void messages::do_close(catalog) const; #ifdef _GLIBCXX_USE_WCHAR_T template<> typename messages::catalog messages::do_open(const basic_string&, const locale&) const; template<> void messages::do_close(catalog) const; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/bits/cxxabi_tweaks.h000064400000004060151027430570014575 0ustar00// Control various target specific ABI tweaks. Generic version. // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cxxabi_tweaks.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cxxabi.h} */ #ifndef _CXXABI_TWEAKS_H #define _CXXABI_TWEAKS_H 1 #ifdef __cplusplus namespace __cxxabiv1 { extern "C" { #endif // The generic ABI uses the first byte of a 64-bit guard variable. #define _GLIBCXX_GUARD_TEST(x) (*(char *) (x) != 0) #define _GLIBCXX_GUARD_SET(x) *(char *) (x) = 1 #define _GLIBCXX_GUARD_BIT __guard_test_bit (0, 1) #define _GLIBCXX_GUARD_PENDING_BIT __guard_test_bit (1, 1) #define _GLIBCXX_GUARD_WAITING_BIT __guard_test_bit (2, 1) __extension__ typedef int __guard __attribute__((mode (__DI__))); // __cxa_vec_ctor has void return type. typedef void __cxa_vec_ctor_return_type; #define _GLIBCXX_CXA_VEC_CTOR_RETURN(x) return // Constructors and destructors do not return a value. typedef void __cxa_cdtor_return_type; #ifdef __cplusplus } } // namespace __cxxabiv1 #endif #endif c++/8/x86_64-redhat-linux/bits/cpu_defines.h000064400000002465151027430570014234 0ustar00// Specific definitions for generic platforms -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cpu_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_CPU_DEFINES #define _GLIBCXX_CPU_DEFINES 1 #endif c++/8/x86_64-redhat-linux/bits/gthr-default.h000064400000057255151027430570014345 0ustar00/* Threads compatibility routines for libgcc2 and libobjc. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_POSIX_H #define _GLIBCXX_GCC_GTHR_POSIX_H /* POSIX threads specific definitions. Easy, since the interface is just one-to-one mapping. */ #define __GTHREADS 1 #define __GTHREADS_CXX0X 1 #include #if ((defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)) \ || !defined(_GTHREAD_USE_MUTEX_TIMEDLOCK)) # include # if defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS >= 0 # define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 # else # define _GTHREAD_USE_MUTEX_TIMEDLOCK 0 # endif #endif typedef pthread_t __gthread_t; typedef pthread_key_t __gthread_key_t; typedef pthread_once_t __gthread_once_t; typedef pthread_mutex_t __gthread_mutex_t; typedef pthread_mutex_t __gthread_recursive_mutex_t; typedef pthread_cond_t __gthread_cond_t; typedef struct timespec __gthread_time_t; /* POSIX like conditional variables are supported. Please look at comments in gthr.h for details. */ #define __GTHREAD_HAS_COND 1 #define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER #define __GTHREAD_MUTEX_INIT_FUNCTION __gthread_mutex_init_function #define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT #if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER #elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #else #define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #define __GTHREAD_COND_INIT PTHREAD_COND_INITIALIZER #define __GTHREAD_TIME_INIT {0,0} #ifdef _GTHREAD_USE_MUTEX_INIT_FUNC # undef __GTHREAD_MUTEX_INIT #endif #ifdef _GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC # undef __GTHREAD_RECURSIVE_MUTEX_INIT # undef __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION # define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #ifdef _GTHREAD_USE_COND_INIT_FUNC # undef __GTHREAD_COND_INIT # define __GTHREAD_COND_INIT_FUNCTION __gthread_cond_init_function #endif #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK # ifndef __gthrw_pragma # define __gthrw_pragma(pragma) # endif # define __gthrw2(name,name2,type) \ static __typeof(type) name __attribute__ ((__weakref__(#name2))); \ __gthrw_pragma(weak type) # define __gthrw_(name) __gthrw_ ## name #else # define __gthrw2(name,name2,type) # define __gthrw_(name) name #endif /* Typically, __gthrw_foo is a weak reference to symbol foo. */ #define __gthrw(name) __gthrw2(__gthrw_ ## name,name,name) __gthrw(pthread_once) __gthrw(pthread_getspecific) __gthrw(pthread_setspecific) __gthrw(pthread_create) __gthrw(pthread_join) __gthrw(pthread_equal) __gthrw(pthread_self) __gthrw(pthread_detach) #ifndef __BIONIC__ __gthrw(pthread_cancel) #endif __gthrw(sched_yield) __gthrw(pthread_mutex_lock) __gthrw(pthread_mutex_trylock) #if _GTHREAD_USE_MUTEX_TIMEDLOCK __gthrw(pthread_mutex_timedlock) #endif __gthrw(pthread_mutex_unlock) __gthrw(pthread_mutex_init) __gthrw(pthread_mutex_destroy) __gthrw(pthread_cond_init) __gthrw(pthread_cond_broadcast) __gthrw(pthread_cond_signal) __gthrw(pthread_cond_wait) __gthrw(pthread_cond_timedwait) __gthrw(pthread_cond_destroy) __gthrw(pthread_key_create) __gthrw(pthread_key_delete) __gthrw(pthread_mutexattr_init) __gthrw(pthread_mutexattr_settype) __gthrw(pthread_mutexattr_destroy) #if defined(_LIBOBJC) || defined(_LIBOBJC_WEAK) /* Objective-C. */ __gthrw(pthread_exit) #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(sched_get_priority_max) __gthrw(sched_get_priority_min) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ __gthrw(pthread_attr_destroy) __gthrw(pthread_attr_init) __gthrw(pthread_attr_setdetachstate) #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(pthread_getschedparam) __gthrw(pthread_setschedparam) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _LIBOBJC || _LIBOBJC_WEAK */ #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK /* On Solaris 2.6 up to 9, the libc exposes a POSIX threads interface even if -pthreads is not specified. The functions are dummies and most return an error value. However pthread_once returns 0 without invoking the routine it is passed so we cannot pretend that the interface is active if -pthreads is not specified. On Solaris 2.5.1, the interface is not exposed at all so we need to play the usual game with weak symbols. On Solaris 10 and up, a working interface is always exposed. On FreeBSD 6 and later, libc also exposes a dummy POSIX threads interface, similar to what Solaris 2.6 up to 9 does. FreeBSD >= 700014 even provides a pthread_cancel stub in libc, which means the alternate __gthread_active_p below cannot be used there. */ #if defined(__FreeBSD__) || (defined(__sun) && defined(__svr4__)) static volatile int __gthread_active = -1; static void __gthread_trigger (void) { __gthread_active = 1; } static inline int __gthread_active_p (void) { static pthread_mutex_t __gthread_active_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t __gthread_active_once = PTHREAD_ONCE_INIT; /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; /* This test is not protected to avoid taking a lock on the main code path so every update of __gthread_active in a threaded program must be atomic with regard to the result of the test. */ if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { if (__gthrw_(pthread_once)) { /* If this really is a threaded program, then we must ensure that __gthread_active has been set to 1 before exiting this block. */ __gthrw_(pthread_mutex_lock) (&__gthread_active_mutex); __gthrw_(pthread_once) (&__gthread_active_once, __gthread_trigger); __gthrw_(pthread_mutex_unlock) (&__gthread_active_mutex); } /* Make sure we'll never enter this block again. */ if (__gthread_active < 0) __gthread_active = 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* neither FreeBSD nor Solaris */ /* For a program to be multi-threaded the only thing that it certainly must be using is pthread_create. However, there may be other libraries that intercept pthread_create with their own definitions to wrap pthreads functionality for some purpose. In those cases, pthread_create being defined might not necessarily mean that libpthread is actually linked in. For the GNU C library, we can use a known internal name. This is always available in the ABI, but no other library would define it. That is ideal, since any public pthread function might be intercepted just as pthread_create might be. __pthread_key_create is an "internal" implementation symbol, but it is part of the public exported ABI. Also, it's among the symbols that the static libpthread.a always links in whenever pthread_create is used, so there is no danger of a false negative result in any statically-linked, multi-threaded program. For others, we choose pthread_cancel as a function that seems unlikely to be redefined by an interceptor library. The bionic (Android) C library does not provide pthread_cancel, so we do use pthread_create there (and interceptor libraries lose). */ #ifdef __GLIBC__ __gthrw2(__gthrw_(__pthread_key_create), __pthread_key_create, pthread_key_create) # define GTHR_ACTIVE_PROXY __gthrw_(__pthread_key_create) #elif defined (__BIONIC__) # define GTHR_ACTIVE_PROXY __gthrw_(pthread_create) #else # define GTHR_ACTIVE_PROXY __gthrw_(pthread_cancel) #endif static inline int __gthread_active_p (void) { static void *const __gthread_active_ptr = __extension__ (void *) >HR_ACTIVE_PROXY; return __gthread_active_ptr != 0; } #endif /* FreeBSD or Solaris */ #else /* not __GXX_WEAK__ */ /* Similar to Solaris, HP-UX 11 for PA-RISC provides stubs for pthread calls in shared flavors of the HP-UX C library. Most of the stubs have no functionality. The details are described in the "libc cumulative patch" for each subversion of HP-UX 11. There are two special interfaces provided for checking whether an application is linked to a shared pthread library or not. However, these interfaces aren't available in early libpthread libraries. We also need a test that works for archive libraries. We can't use pthread_once as some libc versions call the init function. We also can't use pthread_create or pthread_attr_init as these create a thread and thereby prevent changing the default stack size. The function pthread_default_stacksize_np is available in both the archive and shared versions of libpthread. It can be used to determine the default pthread stack size. There is a stub in some shared libc versions which returns a zero size if pthreads are not active. We provide an equivalent stub to handle cases where libc doesn't provide one. */ #if defined(__hppa__) && defined(__hpux__) static volatile int __gthread_active = -1; static inline int __gthread_active_p (void) { /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; size_t __s; if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { pthread_default_stacksize_np (0, &__s); __gthread_active = __s ? 1 : 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* not hppa-hpux */ static inline int __gthread_active_p (void) { return 1; } #endif /* hppa-hpux */ #endif /* __GXX_WEAK__ */ #ifdef _LIBOBJC /* This is the config.h file in libobjc/ */ #include #ifdef HAVE_SCHED_H # include #endif /* Key structure for maintaining thread specific storage */ static pthread_key_t _objc_thread_storage; static pthread_attr_t _objc_thread_attribs; /* Thread local storage for a single thread */ static void *thread_local_storage = NULL; /* Backend initialization functions */ /* Initialize the threads subsystem. */ static inline int __gthread_objc_init_thread_system (void) { if (__gthread_active_p ()) { /* Initialize the thread storage key. */ if (__gthrw_(pthread_key_create) (&_objc_thread_storage, NULL) == 0) { /* The normal default detach state for threads is * PTHREAD_CREATE_JOINABLE which causes threads to not die * when you think they should. */ if (__gthrw_(pthread_attr_init) (&_objc_thread_attribs) == 0 && __gthrw_(pthread_attr_setdetachstate) (&_objc_thread_attribs, PTHREAD_CREATE_DETACHED) == 0) return 0; } } return -1; } /* Close the threads subsystem. */ static inline int __gthread_objc_close_thread_system (void) { if (__gthread_active_p () && __gthrw_(pthread_key_delete) (_objc_thread_storage) == 0 && __gthrw_(pthread_attr_destroy) (&_objc_thread_attribs) == 0) return 0; return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ static inline objc_thread_t __gthread_objc_thread_detach (void (*func)(void *), void *arg) { objc_thread_t thread_id; pthread_t new_thread_handle; if (!__gthread_active_p ()) return NULL; if (!(__gthrw_(pthread_create) (&new_thread_handle, &_objc_thread_attribs, (void *) func, arg))) thread_id = (objc_thread_t) new_thread_handle; else thread_id = NULL; return thread_id; } /* Set the current thread's priority. */ static inline int __gthread_objc_thread_set_priority (int priority) { if (!__gthread_active_p ()) return -1; else { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING pthread_t thread_id = __gthrw_(pthread_self) (); int policy; struct sched_param params; int priority_min, priority_max; if (__gthrw_(pthread_getschedparam) (thread_id, &policy, ¶ms) == 0) { if ((priority_max = __gthrw_(sched_get_priority_max) (policy)) == -1) return -1; if ((priority_min = __gthrw_(sched_get_priority_min) (policy)) == -1) return -1; if (priority > priority_max) priority = priority_max; else if (priority < priority_min) priority = priority_min; params.sched_priority = priority; /* * The solaris 7 and several other man pages incorrectly state that * this should be a pointer to policy but pthread.h is universally * at odds with this. */ if (__gthrw_(pthread_setschedparam) (thread_id, policy, ¶ms) == 0) return 0; } #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return -1; } } /* Return the current thread's priority. */ static inline int __gthread_objc_thread_get_priority (void) { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING if (__gthread_active_p ()) { int policy; struct sched_param params; if (__gthrw_(pthread_getschedparam) (__gthrw_(pthread_self) (), &policy, ¶ms) == 0) return params.sched_priority; else return -1; } else #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return OBJC_THREAD_INTERACTIVE_PRIORITY; } /* Yield our process time to another thread. */ static inline void __gthread_objc_thread_yield (void) { if (__gthread_active_p ()) __gthrw_(sched_yield) (); } /* Terminate the current thread. */ static inline int __gthread_objc_thread_exit (void) { if (__gthread_active_p ()) /* exit the thread */ __gthrw_(pthread_exit) (&__objc_thread_exit_status); /* Failed if we reached here */ return -1; } /* Returns an integer value which uniquely describes a thread. */ static inline objc_thread_t __gthread_objc_thread_id (void) { if (__gthread_active_p ()) return (objc_thread_t) __gthrw_(pthread_self) (); else return (objc_thread_t) 1; } /* Sets the thread's local storage pointer. */ static inline int __gthread_objc_thread_set_data (void *value) { if (__gthread_active_p ()) return __gthrw_(pthread_setspecific) (_objc_thread_storage, value); else { thread_local_storage = value; return 0; } } /* Returns the thread's local storage pointer. */ static inline void * __gthread_objc_thread_get_data (void) { if (__gthread_active_p ()) return __gthrw_(pthread_getspecific) (_objc_thread_storage); else return thread_local_storage; } /* Backend mutex functions */ /* Allocate a mutex. */ static inline int __gthread_objc_mutex_allocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { mutex->backend = objc_malloc (sizeof (pthread_mutex_t)); if (__gthrw_(pthread_mutex_init) ((pthread_mutex_t *) mutex->backend, NULL)) { objc_free (mutex->backend); mutex->backend = NULL; return -1; } } return 0; } /* Deallocate a mutex. */ static inline int __gthread_objc_mutex_deallocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { int count; /* * Posix Threads specifically require that the thread be unlocked * for __gthrw_(pthread_mutex_destroy) to work. */ do { count = __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend); if (count < 0) return -1; } while (count); if (__gthrw_(pthread_mutex_destroy) ((pthread_mutex_t *) mutex->backend)) return -1; objc_free (mutex->backend); mutex->backend = NULL; } return 0; } /* Grab a lock on a mutex. */ static inline int __gthread_objc_mutex_lock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_lock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Try to grab a lock on a mutex. */ static inline int __gthread_objc_mutex_trylock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_trylock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Unlock the mutex */ static inline int __gthread_objc_mutex_unlock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Backend condition mutex functions */ /* Allocate a condition. */ static inline int __gthread_objc_condition_allocate (objc_condition_t condition) { if (__gthread_active_p ()) { condition->backend = objc_malloc (sizeof (pthread_cond_t)); if (__gthrw_(pthread_cond_init) ((pthread_cond_t *) condition->backend, NULL)) { objc_free (condition->backend); condition->backend = NULL; return -1; } } return 0; } /* Deallocate a condition. */ static inline int __gthread_objc_condition_deallocate (objc_condition_t condition) { if (__gthread_active_p ()) { if (__gthrw_(pthread_cond_destroy) ((pthread_cond_t *) condition->backend)) return -1; objc_free (condition->backend); condition->backend = NULL; } return 0; } /* Wait on the condition */ static inline int __gthread_objc_condition_wait (objc_condition_t condition, objc_mutex_t mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_wait) ((pthread_cond_t *) condition->backend, (pthread_mutex_t *) mutex->backend); else return 0; } /* Wake up all threads waiting on this condition. */ static inline int __gthread_objc_condition_broadcast (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_broadcast) ((pthread_cond_t *) condition->backend); else return 0; } /* Wake up one thread waiting on this condition. */ static inline int __gthread_objc_condition_signal (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_signal) ((pthread_cond_t *) condition->backend); else return 0; } #else /* _LIBOBJC */ static inline int __gthread_create (__gthread_t *__threadid, void *(*__func) (void*), void *__args) { return __gthrw_(pthread_create) (__threadid, NULL, __func, __args); } static inline int __gthread_join (__gthread_t __threadid, void **__value_ptr) { return __gthrw_(pthread_join) (__threadid, __value_ptr); } static inline int __gthread_detach (__gthread_t __threadid) { return __gthrw_(pthread_detach) (__threadid); } static inline int __gthread_equal (__gthread_t __t1, __gthread_t __t2) { return __gthrw_(pthread_equal) (__t1, __t2); } static inline __gthread_t __gthread_self (void) { return __gthrw_(pthread_self) (); } static inline int __gthread_yield (void) { return __gthrw_(sched_yield) (); } static inline int __gthread_once (__gthread_once_t *__once, void (*__func) (void)) { if (__gthread_active_p ()) return __gthrw_(pthread_once) (__once, __func); else return -1; } static inline int __gthread_key_create (__gthread_key_t *__key, void (*__dtor) (void *)) { return __gthrw_(pthread_key_create) (__key, __dtor); } static inline int __gthread_key_delete (__gthread_key_t __key) { return __gthrw_(pthread_key_delete) (__key); } static inline void * __gthread_getspecific (__gthread_key_t __key) { return __gthrw_(pthread_getspecific) (__key); } static inline int __gthread_setspecific (__gthread_key_t __key, const void *__ptr) { return __gthrw_(pthread_setspecific) (__key, __ptr); } static inline void __gthread_mutex_init_function (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) __gthrw_(pthread_mutex_init) (__mutex, NULL); } static inline int __gthread_mutex_destroy (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_destroy) (__mutex); else return 0; } static inline int __gthread_mutex_lock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_lock) (__mutex); else return 0; } static inline int __gthread_mutex_trylock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_trylock) (__mutex); else return 0; } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_mutex_timedlock (__gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_timedlock) (__mutex, __abs_timeout); else return 0; } #endif static inline int __gthread_mutex_unlock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_unlock) (__mutex); else return 0; } #if !defined( PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) \ || defined(_GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC) static inline int __gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *__mutex) { if (__gthread_active_p ()) { pthread_mutexattr_t __attr; int __r; __r = __gthrw_(pthread_mutexattr_init) (&__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_settype) (&__attr, PTHREAD_MUTEX_RECURSIVE); if (!__r) __r = __gthrw_(pthread_mutex_init) (__mutex, &__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_destroy) (&__attr); return __r; } return 0; } #endif static inline int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_lock (__mutex); } static inline int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_trylock (__mutex); } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthread_mutex_timedlock (__mutex, __abs_timeout); } #endif static inline int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_unlock (__mutex); } static inline int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_destroy (__mutex); } #ifdef _GTHREAD_USE_COND_INIT_FUNC static inline void __gthread_cond_init_function (__gthread_cond_t *__cond) { if (__gthread_active_p ()) __gthrw_(pthread_cond_init) (__cond, NULL); } #endif static inline int __gthread_cond_broadcast (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_broadcast) (__cond); } static inline int __gthread_cond_signal (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_signal) (__cond); } static inline int __gthread_cond_wait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex) { return __gthrw_(pthread_cond_wait) (__cond, __mutex); } static inline int __gthread_cond_timedwait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthrw_(pthread_cond_timedwait) (__cond, __mutex, __abs_timeout); } static inline int __gthread_cond_wait_recursive (__gthread_cond_t *__cond, __gthread_recursive_mutex_t *__mutex) { return __gthread_cond_wait (__cond, __mutex); } static inline int __gthread_cond_destroy (__gthread_cond_t* __cond) { return __gthrw_(pthread_cond_destroy) (__cond); } #endif /* _LIBOBJC */ #endif /* ! _GLIBCXX_GCC_GTHR_POSIX_H */ c++/8/x86_64-redhat-linux/bits/gthr.h000064400000012750151027430570012712 0ustar00/* Threads compatibility routines for libgcc2. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_H #define _GLIBCXX_GCC_GTHR_H #ifndef _GLIBCXX_HIDE_EXPORTS #pragma GCC visibility push(default) #endif /* If this file is compiled with threads support, it must #define __GTHREADS 1 to indicate that threads support is present. Also it has define function int __gthread_active_p () that returns 1 if thread system is active, 0 if not. The threads interface must define the following types: __gthread_key_t __gthread_once_t __gthread_mutex_t __gthread_recursive_mutex_t The threads interface must define the following macros: __GTHREAD_ONCE_INIT to initialize __gthread_once_t __GTHREAD_MUTEX_INIT to initialize __gthread_mutex_t to get a fast non-recursive mutex. __GTHREAD_MUTEX_INIT_FUNCTION to initialize __gthread_mutex_t to get a fast non-recursive mutex. Define this to a function which looks like this: void __GTHREAD_MUTEX_INIT_FUNCTION (__gthread_mutex_t *) Some systems can't initialize a mutex without a function call. Don't define __GTHREAD_MUTEX_INIT in this case. __GTHREAD_RECURSIVE_MUTEX_INIT __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION as above, but for a recursive mutex. The threads interface must define the following static functions: int __gthread_once (__gthread_once_t *once, void (*func) ()) int __gthread_key_create (__gthread_key_t *keyp, void (*dtor) (void *)) int __gthread_key_delete (__gthread_key_t key) void *__gthread_getspecific (__gthread_key_t key) int __gthread_setspecific (__gthread_key_t key, const void *ptr) int __gthread_mutex_destroy (__gthread_mutex_t *mutex); int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *mutex); int __gthread_mutex_lock (__gthread_mutex_t *mutex); int __gthread_mutex_trylock (__gthread_mutex_t *mutex); int __gthread_mutex_unlock (__gthread_mutex_t *mutex); int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *mutex); int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *mutex); int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *mutex); The following are supported in POSIX threads only. They are required to fix a deadlock in static initialization inside libsupc++. The header file gthr-posix.h defines a symbol __GTHREAD_HAS_COND to signify that these extra features are supported. Types: __gthread_cond_t Macros: __GTHREAD_COND_INIT __GTHREAD_COND_INIT_FUNCTION Interface: int __gthread_cond_broadcast (__gthread_cond_t *cond); int __gthread_cond_wait (__gthread_cond_t *cond, __gthread_mutex_t *mutex); int __gthread_cond_wait_recursive (__gthread_cond_t *cond, __gthread_recursive_mutex_t *mutex); All functions returning int should return zero on success or the error number. If the operation is not supported, -1 is returned. If the following are also defined, you should #define __GTHREADS_CXX0X 1 to enable the c++0x thread library. Types: __gthread_t __gthread_time_t Interface: int __gthread_create (__gthread_t *thread, void *(*func) (void*), void *args); int __gthread_join (__gthread_t thread, void **value_ptr); int __gthread_detach (__gthread_t thread); int __gthread_equal (__gthread_t t1, __gthread_t t2); __gthread_t __gthread_self (void); int __gthread_yield (void); int __gthread_mutex_timedlock (__gthread_mutex_t *m, const __gthread_time_t *abs_timeout); int __gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *m, const __gthread_time_t *abs_time); int __gthread_cond_signal (__gthread_cond_t *cond); int __gthread_cond_timedwait (__gthread_cond_t *cond, __gthread_mutex_t *mutex, const __gthread_time_t *abs_timeout); */ #if __GXX_WEAK__ /* The pe-coff weak support isn't fully compatible to ELF's weak. For static libraries it might would work, but as we need to deal with shared versions too, we disable it for mingw-targets. */ #ifdef __MINGW32__ #undef _GLIBCXX_GTHREAD_USE_WEAK #define _GLIBCXX_GTHREAD_USE_WEAK 0 #endif #ifndef _GLIBCXX_GTHREAD_USE_WEAK #define _GLIBCXX_GTHREAD_USE_WEAK 1 #endif #endif #include #ifndef _GLIBCXX_HIDE_EXPORTS #pragma GCC visibility pop #endif #endif /* ! _GLIBCXX_GCC_GTHR_H */ c++/8/x86_64-redhat-linux/bits/extc++.h000064400000005145151027430570013037 0ustar00// C++ includes used for precompiling extensions -*- C++ -*- // Copyright (C) 2006-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file extc++.h * This is an implementation file for a precompiled header. */ #if __cplusplus < 201103L #include #else #include #endif #include #if __cplusplus >= 201103L # include #endif #include #include #include #include #include #if __cplusplus >= 201103L # include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L # include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _GLIBCXX_HAVE_ICONV #include #include #endif c++/8/x86_64-redhat-linux/bits/time_members.h000064400000005554151027430570014422 0ustar00// std::time_get, std::time_put implementation, GNU version -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/time_members.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.2.5.1.2 - time_get functions // ISO C++ 14882: 22.2.5.3.2 - time_put functions // // Written by Benjamin Kosnik namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template __timepunct<_CharT>::__timepunct(size_t __refs) : facet(__refs), _M_data(0), _M_c_locale_timepunct(0), _M_name_timepunct(_S_get_c_name()) { _M_initialize_timepunct(); } template __timepunct<_CharT>::__timepunct(__cache_type* __cache, size_t __refs) : facet(__refs), _M_data(__cache), _M_c_locale_timepunct(0), _M_name_timepunct(_S_get_c_name()) { _M_initialize_timepunct(); } template __timepunct<_CharT>::__timepunct(__c_locale __cloc, const char* __s, size_t __refs) : facet(__refs), _M_data(0), _M_c_locale_timepunct(0), _M_name_timepunct(0) { if (__builtin_strcmp(__s, _S_get_c_name()) != 0) { const size_t __len = __builtin_strlen(__s) + 1; char* __tmp = new char[__len]; __builtin_memcpy(__tmp, __s, __len); _M_name_timepunct = __tmp; } else _M_name_timepunct = _S_get_c_name(); __try { _M_initialize_timepunct(__cloc); } __catch(...) { if (_M_name_timepunct != _S_get_c_name()) delete [] _M_name_timepunct; __throw_exception_again; } } template __timepunct<_CharT>::~__timepunct() { if (_M_name_timepunct != _S_get_c_name()) delete [] _M_name_timepunct; delete _M_data; _S_destroy_c_locale(_M_c_locale_timepunct); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/bits/atomic_word.h000064400000002756151027430570014262 0ustar00// Low-level type for atomic operations -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file atomic_word.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _GLIBCXX_ATOMIC_WORD_H #define _GLIBCXX_ATOMIC_WORD_H 1 typedef int _Atomic_word; // This is a memory order acquire fence. #define _GLIBCXX_READ_MEM_BARRIER __atomic_thread_fence (__ATOMIC_ACQUIRE) // This is a memory order release fence. #define _GLIBCXX_WRITE_MEM_BARRIER __atomic_thread_fence (__ATOMIC_RELEASE) #endif c++/8/x86_64-redhat-linux/bits/opt_random.h000064400000014062151027430570014106 0ustar00// Optimizations for random number functions, x86 version -*- C++ -*- // Copyright (C) 2012-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/opt_random.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _BITS_OPT_RANDOM_H #define _BITS_OPT_RANDOM_H 1 #ifdef __SSE3__ #include #endif #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #ifdef __SSE3__ template<> template void normal_distribution:: __generate(typename normal_distribution::result_type* __f, typename normal_distribution::result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { typedef uint64_t __uctype; if (__f == __t) return; if (_M_saved_available) { _M_saved_available = false; *__f++ = _M_saved * __param.stddev() + __param.mean(); if (__f == __t) return; } constexpr uint64_t __maskval = 0xfffffffffffffull; static const __m128i __mask = _mm_set1_epi64x(__maskval); static const __m128i __two = _mm_set1_epi64x(0x4000000000000000ull); static const __m128d __three = _mm_set1_pd(3.0); const __m128d __av = _mm_set1_pd(__param.mean()); const __uctype __urngmin = __urng.min(); const __uctype __urngmax = __urng.max(); const __uctype __urngrange = __urngmax - __urngmin; const __uctype __uerngrange = __urngrange + 1; while (__f + 1 < __t) { double __le; __m128d __x; do { union { __m128i __i; __m128d __d; } __v; if (__urngrange > __maskval) { if (__detail::_Power_of_2(__uerngrange)) __v.__i = _mm_and_si128(_mm_set_epi64x(__urng(), __urng()), __mask); else { const __uctype __uerange = __maskval + 1; const __uctype __scaling = __urngrange / __uerange; const __uctype __past = __uerange * __scaling; uint64_t __v1; do __v1 = __uctype(__urng()) - __urngmin; while (__v1 >= __past); __v1 /= __scaling; uint64_t __v2; do __v2 = __uctype(__urng()) - __urngmin; while (__v2 >= __past); __v2 /= __scaling; __v.__i = _mm_set_epi64x(__v1, __v2); } } else if (__urngrange == __maskval) __v.__i = _mm_set_epi64x(__urng(), __urng()); else if ((__urngrange + 2) * __urngrange >= __maskval && __detail::_Power_of_2(__uerngrange)) { uint64_t __v1 = __urng() * __uerngrange + __urng(); uint64_t __v2 = __urng() * __uerngrange + __urng(); __v.__i = _mm_and_si128(_mm_set_epi64x(__v1, __v2), __mask); } else { size_t __nrng = 2; __uctype __high = __maskval / __uerngrange / __uerngrange; while (__high > __uerngrange) { ++__nrng; __high /= __uerngrange; } const __uctype __highrange = __high + 1; const __uctype __scaling = __urngrange / __highrange; const __uctype __past = __highrange * __scaling; __uctype __tmp; uint64_t __v1; do { do __tmp = __uctype(__urng()) - __urngmin; while (__tmp >= __past); __v1 = __tmp / __scaling; for (size_t __cnt = 0; __cnt < __nrng; ++__cnt) { __tmp = __v1; __v1 *= __uerngrange; __v1 += __uctype(__urng()) - __urngmin; } } while (__v1 > __maskval || __v1 < __tmp); uint64_t __v2; do { do __tmp = __uctype(__urng()) - __urngmin; while (__tmp >= __past); __v2 = __tmp / __scaling; for (size_t __cnt = 0; __cnt < __nrng; ++__cnt) { __tmp = __v2; __v2 *= __uerngrange; __v2 += __uctype(__urng()) - __urngmin; } } while (__v2 > __maskval || __v2 < __tmp); __v.__i = _mm_set_epi64x(__v1, __v2); } __v.__i = _mm_or_si128(__v.__i, __two); __x = _mm_sub_pd(__v.__d, __three); __m128d __m = _mm_mul_pd(__x, __x); __le = _mm_cvtsd_f64(_mm_hadd_pd (__m, __m)); } while (__le == 0.0 || __le >= 1.0); double __mult = (std::sqrt(-2.0 * std::log(__le) / __le) * __param.stddev()); __x = _mm_add_pd(_mm_mul_pd(__x, _mm_set1_pd(__mult)), __av); _mm_storeu_pd(__f, __x); __f += 2; } if (__f != __t) { result_type __x, __y, __r2; __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); _M_saved = __x * __mult; _M_saved_available = true; *__f = __y * __mult * __param.stddev() + __param.mean(); } } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _BITS_OPT_RANDOM_H c++/8/x86_64-redhat-linux/bits/c++locale.h000064400000006353151027430570013500 0ustar00// Wrapper for underlying C-language localization -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++locale.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.8 Standard locale categories. // // Written by Benjamin Kosnik #ifndef _GLIBCXX_CXX_LOCALE_H #define _GLIBCXX_CXX_LOCALE_H 1 #pragma GCC system_header #include #define _GLIBCXX_C_LOCALE_GNU 1 #define _GLIBCXX_NUM_CATEGORIES 6 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION extern "C" __typeof(uselocale) __uselocale; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION typedef __locale_t __c_locale; // Convert numeric value of type double and long double to string and // return length of string. If vsnprintf is available use it, otherwise // fall back to the unsafe vsprintf which, in general, can be dangerous // and should be avoided. inline int __convert_from_v(const __c_locale& __cloc __attribute__ ((__unused__)), char* __out, const int __size __attribute__ ((__unused__)), const char* __fmt, ...) { #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) __c_locale __old = __gnu_cxx::__uselocale(__cloc); #else char* __old = std::setlocale(LC_NUMERIC, 0); char* __sav = 0; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); std::setlocale(LC_NUMERIC, "C"); } #endif __builtin_va_list __args; __builtin_va_start(__args, __fmt); #if _GLIBCXX_USE_C99_STDIO const int __ret = __builtin_vsnprintf(__out, __size, __fmt, __args); #else const int __ret = __builtin_vsprintf(__out, __fmt, __args); #endif __builtin_va_end(__args); #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) __gnu_cxx::__uselocale(__old); #else if (__sav) { std::setlocale(LC_NUMERIC, __sav); delete [] __sav; } #endif return __ret; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/bits/error_constants.h000064400000012067151027430570015174 0ustar00// Specific definitions for generic platforms -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/error_constants.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{system_error} */ #ifndef _GLIBCXX_ERROR_CONSTANTS #define _GLIBCXX_ERROR_CONSTANTS 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION enum class errc { address_family_not_supported = EAFNOSUPPORT, address_in_use = EADDRINUSE, address_not_available = EADDRNOTAVAIL, already_connected = EISCONN, argument_list_too_long = E2BIG, argument_out_of_domain = EDOM, bad_address = EFAULT, bad_file_descriptor = EBADF, #ifdef _GLIBCXX_HAVE_EBADMSG bad_message = EBADMSG, #endif broken_pipe = EPIPE, connection_aborted = ECONNABORTED, connection_already_in_progress = EALREADY, connection_refused = ECONNREFUSED, connection_reset = ECONNRESET, cross_device_link = EXDEV, destination_address_required = EDESTADDRREQ, device_or_resource_busy = EBUSY, directory_not_empty = ENOTEMPTY, executable_format_error = ENOEXEC, file_exists = EEXIST, file_too_large = EFBIG, filename_too_long = ENAMETOOLONG, function_not_supported = ENOSYS, host_unreachable = EHOSTUNREACH, #ifdef _GLIBCXX_HAVE_EIDRM identifier_removed = EIDRM, #endif illegal_byte_sequence = EILSEQ, inappropriate_io_control_operation = ENOTTY, interrupted = EINTR, invalid_argument = EINVAL, invalid_seek = ESPIPE, io_error = EIO, is_a_directory = EISDIR, message_size = EMSGSIZE, network_down = ENETDOWN, network_reset = ENETRESET, network_unreachable = ENETUNREACH, no_buffer_space = ENOBUFS, no_child_process = ECHILD, #ifdef _GLIBCXX_HAVE_ENOLINK no_link = ENOLINK, #endif no_lock_available = ENOLCK, #ifdef _GLIBCXX_HAVE_ENODATA no_message_available = ENODATA, #endif no_message = ENOMSG, no_protocol_option = ENOPROTOOPT, no_space_on_device = ENOSPC, #ifdef _GLIBCXX_HAVE_ENOSR no_stream_resources = ENOSR, #endif no_such_device_or_address = ENXIO, no_such_device = ENODEV, no_such_file_or_directory = ENOENT, no_such_process = ESRCH, not_a_directory = ENOTDIR, not_a_socket = ENOTSOCK, #ifdef _GLIBCXX_HAVE_ENOSTR not_a_stream = ENOSTR, #endif not_connected = ENOTCONN, not_enough_memory = ENOMEM, #ifdef _GLIBCXX_HAVE_ENOTSUP not_supported = ENOTSUP, #endif #ifdef _GLIBCXX_HAVE_ECANCELED operation_canceled = ECANCELED, #endif operation_in_progress = EINPROGRESS, operation_not_permitted = EPERM, operation_not_supported = EOPNOTSUPP, operation_would_block = EWOULDBLOCK, #ifdef _GLIBCXX_HAVE_EOWNERDEAD owner_dead = EOWNERDEAD, #endif permission_denied = EACCES, #ifdef _GLIBCXX_HAVE_EPROTO protocol_error = EPROTO, #endif protocol_not_supported = EPROTONOSUPPORT, read_only_file_system = EROFS, resource_deadlock_would_occur = EDEADLK, resource_unavailable_try_again = EAGAIN, result_out_of_range = ERANGE, #ifdef _GLIBCXX_HAVE_ENOTRECOVERABLE state_not_recoverable = ENOTRECOVERABLE, #endif #ifdef _GLIBCXX_HAVE_ETIME stream_timeout = ETIME, #endif #ifdef _GLIBCXX_HAVE_ETXTBSY text_file_busy = ETXTBSY, #endif timed_out = ETIMEDOUT, too_many_files_open_in_system = ENFILE, too_many_files_open = EMFILE, too_many_links = EMLINK, too_many_symbolic_link_levels = ELOOP, #ifdef _GLIBCXX_HAVE_EOVERFLOW value_too_large = EOVERFLOW, #endif wrong_protocol_type = EPROTOTYPE }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/bits/os_defines.h000064400000003727151027430570014070 0ustar00// Specific definitions for GNU/Linux -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/os_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_OS_DEFINES #define _GLIBCXX_OS_DEFINES 1 // System-specific #define, typedefs, corrections, etc, go here. This // file will come before all others. // This keeps isanum, et al from being propagated as macros. #define __NO_CTYPE 1 #include // Provide a declaration for the possibly deprecated gets function, as // glibc 2.15 and later does not declare gets for ISO C11 when // __GNU_SOURCE is defined. #if __GLIBC_PREREQ(2,15) && defined(_GNU_SOURCE) # undef _GLIBCXX_HAVE_GETS #endif // Glibc 2.23 removed the obsolete isinf and isnan declarations. Check the // version dynamically in case it has changed since libstdc++ was configured. #define _GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC __GLIBC_PREREQ(2,23) #endif c++/8/x86_64-redhat-linux/bits/ctype_base.h000064400000004414151027430570014062 0ustar00// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ctype_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // // Information as gleaned from /usr/include/ctype.h namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// @brief Base class for ctype. struct ctype_base { // Non-standard typedefs. typedef const int* __to_type; // NB: Offsets into ctype::_M_table force a particular size // on the mask type. Because of this, we don't use an enum. typedef unsigned short mask; static const mask upper = _ISupper; static const mask lower = _ISlower; static const mask alpha = _ISalpha; static const mask digit = _ISdigit; static const mask xdigit = _ISxdigit; static const mask space = _ISspace; static const mask print = _ISprint; static const mask graph = _ISalpha | _ISdigit | _ISpunct; static const mask cntrl = _IScntrl; static const mask punct = _ISpunct; static const mask alnum = _ISalpha | _ISdigit; #if __cplusplus >= 201103L static const mask blank = _ISblank; #endif }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/bits/basic_file.h000064400000006553151027430570014032 0ustar00// Wrapper of C-language FILE struct -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // // ISO C++ 14882: 27.8 File-based streams // /** @file bits/basic_file.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ #ifndef _GLIBCXX_BASIC_FILE_STDIO_H #define _GLIBCXX_BASIC_FILE_STDIO_H 1 #pragma GCC system_header #include #include // for __c_lock and __c_file #include // for swap #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Generic declaration. template class __basic_file; // Specialization. template<> class __basic_file { // Underlying data source/sink. __c_file* _M_cfile; // True iff we opened _M_cfile, and thus must close it ourselves. bool _M_cfile_created; public: __basic_file(__c_lock* __lock = 0) throw (); #if __cplusplus >= 201103L __basic_file(__basic_file&& __rv, __c_lock* = 0) noexcept : _M_cfile(__rv._M_cfile), _M_cfile_created(__rv._M_cfile_created) { __rv._M_cfile = nullptr; __rv._M_cfile_created = false; } __basic_file& operator=(const __basic_file&) = delete; __basic_file& operator=(__basic_file&&) = delete; void swap(__basic_file& __f) noexcept { std::swap(_M_cfile, __f._M_cfile); std::swap(_M_cfile_created, __f._M_cfile_created); } #endif __basic_file* open(const char* __name, ios_base::openmode __mode, int __prot = 0664); __basic_file* sys_open(__c_file* __file, ios_base::openmode); __basic_file* sys_open(int __fd, ios_base::openmode __mode) throw (); __basic_file* close(); _GLIBCXX_PURE bool is_open() const throw (); _GLIBCXX_PURE int fd() throw (); _GLIBCXX_PURE __c_file* file() throw (); ~__basic_file(); streamsize xsputn(const char* __s, streamsize __n); streamsize xsputn_2(const char* __s1, streamsize __n1, const char* __s2, streamsize __n2); streamsize xsgetn(char* __s, streamsize __n); streamoff seekoff(streamoff __off, ios_base::seekdir __way) throw (); int sync(); streamsize showmanyc(); }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/bits/stdtr1c++.h000064400000003315151027430570013455 0ustar00// C++ includes used for precompiling TR1 -*- C++ -*- // Copyright (C) 2006-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file stdtr1c++.h * This is an implementation file for a precompiled header. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include c++/8/x86_64-redhat-linux/32/bits/stdc++.h000064400000005607151027430570013260 0ustar00// C++ includes used for precompiling -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file stdc++.h * This is an implementation file for a precompiled header. */ // 17.4.1.2 Headers // C #ifndef _GLIBCXX_NO_ASSERT #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L #include #include #include #include #include #include #include #include #include #include #endif // C++ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif #if __cplusplus >= 201402L #include #endif #if __cplusplus >= 201703L #include #include #endif c++/8/x86_64-redhat-linux/32/bits/c++io.h000064400000003110151027430570013060 0ustar00// Underlying io library details -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++io.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ // c_io_stdio.h - Defines for using "C" stdio.h #ifndef _GLIBCXX_CXX_IO_H #define _GLIBCXX_CXX_IO_H 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION typedef __gthread_mutex_t __c_lock; // for basic_file.h typedef FILE __c_file; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/32/bits/gthr-posix.h000064400000057255151027430570014307 0ustar00/* Threads compatibility routines for libgcc2 and libobjc. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_POSIX_H #define _GLIBCXX_GCC_GTHR_POSIX_H /* POSIX threads specific definitions. Easy, since the interface is just one-to-one mapping. */ #define __GTHREADS 1 #define __GTHREADS_CXX0X 1 #include #if ((defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)) \ || !defined(_GTHREAD_USE_MUTEX_TIMEDLOCK)) # include # if defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS >= 0 # define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 # else # define _GTHREAD_USE_MUTEX_TIMEDLOCK 0 # endif #endif typedef pthread_t __gthread_t; typedef pthread_key_t __gthread_key_t; typedef pthread_once_t __gthread_once_t; typedef pthread_mutex_t __gthread_mutex_t; typedef pthread_mutex_t __gthread_recursive_mutex_t; typedef pthread_cond_t __gthread_cond_t; typedef struct timespec __gthread_time_t; /* POSIX like conditional variables are supported. Please look at comments in gthr.h for details. */ #define __GTHREAD_HAS_COND 1 #define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER #define __GTHREAD_MUTEX_INIT_FUNCTION __gthread_mutex_init_function #define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT #if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER #elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #else #define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #define __GTHREAD_COND_INIT PTHREAD_COND_INITIALIZER #define __GTHREAD_TIME_INIT {0,0} #ifdef _GTHREAD_USE_MUTEX_INIT_FUNC # undef __GTHREAD_MUTEX_INIT #endif #ifdef _GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC # undef __GTHREAD_RECURSIVE_MUTEX_INIT # undef __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION # define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #ifdef _GTHREAD_USE_COND_INIT_FUNC # undef __GTHREAD_COND_INIT # define __GTHREAD_COND_INIT_FUNCTION __gthread_cond_init_function #endif #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK # ifndef __gthrw_pragma # define __gthrw_pragma(pragma) # endif # define __gthrw2(name,name2,type) \ static __typeof(type) name __attribute__ ((__weakref__(#name2))); \ __gthrw_pragma(weak type) # define __gthrw_(name) __gthrw_ ## name #else # define __gthrw2(name,name2,type) # define __gthrw_(name) name #endif /* Typically, __gthrw_foo is a weak reference to symbol foo. */ #define __gthrw(name) __gthrw2(__gthrw_ ## name,name,name) __gthrw(pthread_once) __gthrw(pthread_getspecific) __gthrw(pthread_setspecific) __gthrw(pthread_create) __gthrw(pthread_join) __gthrw(pthread_equal) __gthrw(pthread_self) __gthrw(pthread_detach) #ifndef __BIONIC__ __gthrw(pthread_cancel) #endif __gthrw(sched_yield) __gthrw(pthread_mutex_lock) __gthrw(pthread_mutex_trylock) #if _GTHREAD_USE_MUTEX_TIMEDLOCK __gthrw(pthread_mutex_timedlock) #endif __gthrw(pthread_mutex_unlock) __gthrw(pthread_mutex_init) __gthrw(pthread_mutex_destroy) __gthrw(pthread_cond_init) __gthrw(pthread_cond_broadcast) __gthrw(pthread_cond_signal) __gthrw(pthread_cond_wait) __gthrw(pthread_cond_timedwait) __gthrw(pthread_cond_destroy) __gthrw(pthread_key_create) __gthrw(pthread_key_delete) __gthrw(pthread_mutexattr_init) __gthrw(pthread_mutexattr_settype) __gthrw(pthread_mutexattr_destroy) #if defined(_LIBOBJC) || defined(_LIBOBJC_WEAK) /* Objective-C. */ __gthrw(pthread_exit) #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(sched_get_priority_max) __gthrw(sched_get_priority_min) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ __gthrw(pthread_attr_destroy) __gthrw(pthread_attr_init) __gthrw(pthread_attr_setdetachstate) #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(pthread_getschedparam) __gthrw(pthread_setschedparam) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _LIBOBJC || _LIBOBJC_WEAK */ #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK /* On Solaris 2.6 up to 9, the libc exposes a POSIX threads interface even if -pthreads is not specified. The functions are dummies and most return an error value. However pthread_once returns 0 without invoking the routine it is passed so we cannot pretend that the interface is active if -pthreads is not specified. On Solaris 2.5.1, the interface is not exposed at all so we need to play the usual game with weak symbols. On Solaris 10 and up, a working interface is always exposed. On FreeBSD 6 and later, libc also exposes a dummy POSIX threads interface, similar to what Solaris 2.6 up to 9 does. FreeBSD >= 700014 even provides a pthread_cancel stub in libc, which means the alternate __gthread_active_p below cannot be used there. */ #if defined(__FreeBSD__) || (defined(__sun) && defined(__svr4__)) static volatile int __gthread_active = -1; static void __gthread_trigger (void) { __gthread_active = 1; } static inline int __gthread_active_p (void) { static pthread_mutex_t __gthread_active_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t __gthread_active_once = PTHREAD_ONCE_INIT; /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; /* This test is not protected to avoid taking a lock on the main code path so every update of __gthread_active in a threaded program must be atomic with regard to the result of the test. */ if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { if (__gthrw_(pthread_once)) { /* If this really is a threaded program, then we must ensure that __gthread_active has been set to 1 before exiting this block. */ __gthrw_(pthread_mutex_lock) (&__gthread_active_mutex); __gthrw_(pthread_once) (&__gthread_active_once, __gthread_trigger); __gthrw_(pthread_mutex_unlock) (&__gthread_active_mutex); } /* Make sure we'll never enter this block again. */ if (__gthread_active < 0) __gthread_active = 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* neither FreeBSD nor Solaris */ /* For a program to be multi-threaded the only thing that it certainly must be using is pthread_create. However, there may be other libraries that intercept pthread_create with their own definitions to wrap pthreads functionality for some purpose. In those cases, pthread_create being defined might not necessarily mean that libpthread is actually linked in. For the GNU C library, we can use a known internal name. This is always available in the ABI, but no other library would define it. That is ideal, since any public pthread function might be intercepted just as pthread_create might be. __pthread_key_create is an "internal" implementation symbol, but it is part of the public exported ABI. Also, it's among the symbols that the static libpthread.a always links in whenever pthread_create is used, so there is no danger of a false negative result in any statically-linked, multi-threaded program. For others, we choose pthread_cancel as a function that seems unlikely to be redefined by an interceptor library. The bionic (Android) C library does not provide pthread_cancel, so we do use pthread_create there (and interceptor libraries lose). */ #ifdef __GLIBC__ __gthrw2(__gthrw_(__pthread_key_create), __pthread_key_create, pthread_key_create) # define GTHR_ACTIVE_PROXY __gthrw_(__pthread_key_create) #elif defined (__BIONIC__) # define GTHR_ACTIVE_PROXY __gthrw_(pthread_create) #else # define GTHR_ACTIVE_PROXY __gthrw_(pthread_cancel) #endif static inline int __gthread_active_p (void) { static void *const __gthread_active_ptr = __extension__ (void *) >HR_ACTIVE_PROXY; return __gthread_active_ptr != 0; } #endif /* FreeBSD or Solaris */ #else /* not __GXX_WEAK__ */ /* Similar to Solaris, HP-UX 11 for PA-RISC provides stubs for pthread calls in shared flavors of the HP-UX C library. Most of the stubs have no functionality. The details are described in the "libc cumulative patch" for each subversion of HP-UX 11. There are two special interfaces provided for checking whether an application is linked to a shared pthread library or not. However, these interfaces aren't available in early libpthread libraries. We also need a test that works for archive libraries. We can't use pthread_once as some libc versions call the init function. We also can't use pthread_create or pthread_attr_init as these create a thread and thereby prevent changing the default stack size. The function pthread_default_stacksize_np is available in both the archive and shared versions of libpthread. It can be used to determine the default pthread stack size. There is a stub in some shared libc versions which returns a zero size if pthreads are not active. We provide an equivalent stub to handle cases where libc doesn't provide one. */ #if defined(__hppa__) && defined(__hpux__) static volatile int __gthread_active = -1; static inline int __gthread_active_p (void) { /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; size_t __s; if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { pthread_default_stacksize_np (0, &__s); __gthread_active = __s ? 1 : 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* not hppa-hpux */ static inline int __gthread_active_p (void) { return 1; } #endif /* hppa-hpux */ #endif /* __GXX_WEAK__ */ #ifdef _LIBOBJC /* This is the config.h file in libobjc/ */ #include #ifdef HAVE_SCHED_H # include #endif /* Key structure for maintaining thread specific storage */ static pthread_key_t _objc_thread_storage; static pthread_attr_t _objc_thread_attribs; /* Thread local storage for a single thread */ static void *thread_local_storage = NULL; /* Backend initialization functions */ /* Initialize the threads subsystem. */ static inline int __gthread_objc_init_thread_system (void) { if (__gthread_active_p ()) { /* Initialize the thread storage key. */ if (__gthrw_(pthread_key_create) (&_objc_thread_storage, NULL) == 0) { /* The normal default detach state for threads is * PTHREAD_CREATE_JOINABLE which causes threads to not die * when you think they should. */ if (__gthrw_(pthread_attr_init) (&_objc_thread_attribs) == 0 && __gthrw_(pthread_attr_setdetachstate) (&_objc_thread_attribs, PTHREAD_CREATE_DETACHED) == 0) return 0; } } return -1; } /* Close the threads subsystem. */ static inline int __gthread_objc_close_thread_system (void) { if (__gthread_active_p () && __gthrw_(pthread_key_delete) (_objc_thread_storage) == 0 && __gthrw_(pthread_attr_destroy) (&_objc_thread_attribs) == 0) return 0; return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ static inline objc_thread_t __gthread_objc_thread_detach (void (*func)(void *), void *arg) { objc_thread_t thread_id; pthread_t new_thread_handle; if (!__gthread_active_p ()) return NULL; if (!(__gthrw_(pthread_create) (&new_thread_handle, &_objc_thread_attribs, (void *) func, arg))) thread_id = (objc_thread_t) new_thread_handle; else thread_id = NULL; return thread_id; } /* Set the current thread's priority. */ static inline int __gthread_objc_thread_set_priority (int priority) { if (!__gthread_active_p ()) return -1; else { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING pthread_t thread_id = __gthrw_(pthread_self) (); int policy; struct sched_param params; int priority_min, priority_max; if (__gthrw_(pthread_getschedparam) (thread_id, &policy, ¶ms) == 0) { if ((priority_max = __gthrw_(sched_get_priority_max) (policy)) == -1) return -1; if ((priority_min = __gthrw_(sched_get_priority_min) (policy)) == -1) return -1; if (priority > priority_max) priority = priority_max; else if (priority < priority_min) priority = priority_min; params.sched_priority = priority; /* * The solaris 7 and several other man pages incorrectly state that * this should be a pointer to policy but pthread.h is universally * at odds with this. */ if (__gthrw_(pthread_setschedparam) (thread_id, policy, ¶ms) == 0) return 0; } #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return -1; } } /* Return the current thread's priority. */ static inline int __gthread_objc_thread_get_priority (void) { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING if (__gthread_active_p ()) { int policy; struct sched_param params; if (__gthrw_(pthread_getschedparam) (__gthrw_(pthread_self) (), &policy, ¶ms) == 0) return params.sched_priority; else return -1; } else #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return OBJC_THREAD_INTERACTIVE_PRIORITY; } /* Yield our process time to another thread. */ static inline void __gthread_objc_thread_yield (void) { if (__gthread_active_p ()) __gthrw_(sched_yield) (); } /* Terminate the current thread. */ static inline int __gthread_objc_thread_exit (void) { if (__gthread_active_p ()) /* exit the thread */ __gthrw_(pthread_exit) (&__objc_thread_exit_status); /* Failed if we reached here */ return -1; } /* Returns an integer value which uniquely describes a thread. */ static inline objc_thread_t __gthread_objc_thread_id (void) { if (__gthread_active_p ()) return (objc_thread_t) __gthrw_(pthread_self) (); else return (objc_thread_t) 1; } /* Sets the thread's local storage pointer. */ static inline int __gthread_objc_thread_set_data (void *value) { if (__gthread_active_p ()) return __gthrw_(pthread_setspecific) (_objc_thread_storage, value); else { thread_local_storage = value; return 0; } } /* Returns the thread's local storage pointer. */ static inline void * __gthread_objc_thread_get_data (void) { if (__gthread_active_p ()) return __gthrw_(pthread_getspecific) (_objc_thread_storage); else return thread_local_storage; } /* Backend mutex functions */ /* Allocate a mutex. */ static inline int __gthread_objc_mutex_allocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { mutex->backend = objc_malloc (sizeof (pthread_mutex_t)); if (__gthrw_(pthread_mutex_init) ((pthread_mutex_t *) mutex->backend, NULL)) { objc_free (mutex->backend); mutex->backend = NULL; return -1; } } return 0; } /* Deallocate a mutex. */ static inline int __gthread_objc_mutex_deallocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { int count; /* * Posix Threads specifically require that the thread be unlocked * for __gthrw_(pthread_mutex_destroy) to work. */ do { count = __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend); if (count < 0) return -1; } while (count); if (__gthrw_(pthread_mutex_destroy) ((pthread_mutex_t *) mutex->backend)) return -1; objc_free (mutex->backend); mutex->backend = NULL; } return 0; } /* Grab a lock on a mutex. */ static inline int __gthread_objc_mutex_lock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_lock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Try to grab a lock on a mutex. */ static inline int __gthread_objc_mutex_trylock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_trylock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Unlock the mutex */ static inline int __gthread_objc_mutex_unlock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Backend condition mutex functions */ /* Allocate a condition. */ static inline int __gthread_objc_condition_allocate (objc_condition_t condition) { if (__gthread_active_p ()) { condition->backend = objc_malloc (sizeof (pthread_cond_t)); if (__gthrw_(pthread_cond_init) ((pthread_cond_t *) condition->backend, NULL)) { objc_free (condition->backend); condition->backend = NULL; return -1; } } return 0; } /* Deallocate a condition. */ static inline int __gthread_objc_condition_deallocate (objc_condition_t condition) { if (__gthread_active_p ()) { if (__gthrw_(pthread_cond_destroy) ((pthread_cond_t *) condition->backend)) return -1; objc_free (condition->backend); condition->backend = NULL; } return 0; } /* Wait on the condition */ static inline int __gthread_objc_condition_wait (objc_condition_t condition, objc_mutex_t mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_wait) ((pthread_cond_t *) condition->backend, (pthread_mutex_t *) mutex->backend); else return 0; } /* Wake up all threads waiting on this condition. */ static inline int __gthread_objc_condition_broadcast (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_broadcast) ((pthread_cond_t *) condition->backend); else return 0; } /* Wake up one thread waiting on this condition. */ static inline int __gthread_objc_condition_signal (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_signal) ((pthread_cond_t *) condition->backend); else return 0; } #else /* _LIBOBJC */ static inline int __gthread_create (__gthread_t *__threadid, void *(*__func) (void*), void *__args) { return __gthrw_(pthread_create) (__threadid, NULL, __func, __args); } static inline int __gthread_join (__gthread_t __threadid, void **__value_ptr) { return __gthrw_(pthread_join) (__threadid, __value_ptr); } static inline int __gthread_detach (__gthread_t __threadid) { return __gthrw_(pthread_detach) (__threadid); } static inline int __gthread_equal (__gthread_t __t1, __gthread_t __t2) { return __gthrw_(pthread_equal) (__t1, __t2); } static inline __gthread_t __gthread_self (void) { return __gthrw_(pthread_self) (); } static inline int __gthread_yield (void) { return __gthrw_(sched_yield) (); } static inline int __gthread_once (__gthread_once_t *__once, void (*__func) (void)) { if (__gthread_active_p ()) return __gthrw_(pthread_once) (__once, __func); else return -1; } static inline int __gthread_key_create (__gthread_key_t *__key, void (*__dtor) (void *)) { return __gthrw_(pthread_key_create) (__key, __dtor); } static inline int __gthread_key_delete (__gthread_key_t __key) { return __gthrw_(pthread_key_delete) (__key); } static inline void * __gthread_getspecific (__gthread_key_t __key) { return __gthrw_(pthread_getspecific) (__key); } static inline int __gthread_setspecific (__gthread_key_t __key, const void *__ptr) { return __gthrw_(pthread_setspecific) (__key, __ptr); } static inline void __gthread_mutex_init_function (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) __gthrw_(pthread_mutex_init) (__mutex, NULL); } static inline int __gthread_mutex_destroy (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_destroy) (__mutex); else return 0; } static inline int __gthread_mutex_lock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_lock) (__mutex); else return 0; } static inline int __gthread_mutex_trylock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_trylock) (__mutex); else return 0; } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_mutex_timedlock (__gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_timedlock) (__mutex, __abs_timeout); else return 0; } #endif static inline int __gthread_mutex_unlock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_unlock) (__mutex); else return 0; } #if !defined( PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) \ || defined(_GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC) static inline int __gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *__mutex) { if (__gthread_active_p ()) { pthread_mutexattr_t __attr; int __r; __r = __gthrw_(pthread_mutexattr_init) (&__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_settype) (&__attr, PTHREAD_MUTEX_RECURSIVE); if (!__r) __r = __gthrw_(pthread_mutex_init) (__mutex, &__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_destroy) (&__attr); return __r; } return 0; } #endif static inline int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_lock (__mutex); } static inline int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_trylock (__mutex); } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthread_mutex_timedlock (__mutex, __abs_timeout); } #endif static inline int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_unlock (__mutex); } static inline int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_destroy (__mutex); } #ifdef _GTHREAD_USE_COND_INIT_FUNC static inline void __gthread_cond_init_function (__gthread_cond_t *__cond) { if (__gthread_active_p ()) __gthrw_(pthread_cond_init) (__cond, NULL); } #endif static inline int __gthread_cond_broadcast (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_broadcast) (__cond); } static inline int __gthread_cond_signal (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_signal) (__cond); } static inline int __gthread_cond_wait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex) { return __gthrw_(pthread_cond_wait) (__cond, __mutex); } static inline int __gthread_cond_timedwait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthrw_(pthread_cond_timedwait) (__cond, __mutex, __abs_timeout); } static inline int __gthread_cond_wait_recursive (__gthread_cond_t *__cond, __gthread_recursive_mutex_t *__mutex) { return __gthread_cond_wait (__cond, __mutex); } static inline int __gthread_cond_destroy (__gthread_cond_t* __cond) { return __gthrw_(pthread_cond_destroy) (__cond); } #endif /* _LIBOBJC */ #endif /* ! _GLIBCXX_GCC_GTHR_POSIX_H */ c++/8/x86_64-redhat-linux/32/bits/c++config.h000064400000160477151027430570013742 0ustar00// Predefined symbols and macros -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++config.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_CXX_CONFIG_H #define _GLIBCXX_CXX_CONFIG_H 1 // The major release number for the GCC release the C++ library belongs to. #define _GLIBCXX_RELEASE 8 // The datestamp of the C++ library in compressed ISO date format. #define __GLIBCXX__ 20210514 // Macros for various attributes. // _GLIBCXX_PURE // _GLIBCXX_CONST // _GLIBCXX_NORETURN // _GLIBCXX_NOTHROW // _GLIBCXX_VISIBILITY #ifndef _GLIBCXX_PURE # define _GLIBCXX_PURE __attribute__ ((__pure__)) #endif #ifndef _GLIBCXX_CONST # define _GLIBCXX_CONST __attribute__ ((__const__)) #endif #ifndef _GLIBCXX_NORETURN # define _GLIBCXX_NORETURN __attribute__ ((__noreturn__)) #endif // See below for C++ #ifndef _GLIBCXX_NOTHROW # ifndef __cplusplus # define _GLIBCXX_NOTHROW __attribute__((__nothrow__)) # endif #endif // Macros for visibility attributes. // _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY // _GLIBCXX_VISIBILITY # define _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY 1 #if _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY # define _GLIBCXX_VISIBILITY(V) __attribute__ ((__visibility__ (#V))) #else // If this is not supplied by the OS-specific or CPU-specific // headers included below, it will be defined to an empty default. # define _GLIBCXX_VISIBILITY(V) _GLIBCXX_PSEUDO_VISIBILITY(V) #endif // Macros for deprecated attributes. // _GLIBCXX_USE_DEPRECATED // _GLIBCXX_DEPRECATED // _GLIBCXX17_DEPRECATED #ifndef _GLIBCXX_USE_DEPRECATED # define _GLIBCXX_USE_DEPRECATED 1 #endif #if defined(__DEPRECATED) && (__cplusplus >= 201103L) # define _GLIBCXX_DEPRECATED __attribute__ ((__deprecated__)) #else # define _GLIBCXX_DEPRECATED #endif #if defined(__DEPRECATED) && (__cplusplus >= 201703L) # define _GLIBCXX17_DEPRECATED [[__deprecated__]] #else # define _GLIBCXX17_DEPRECATED #endif // Macros for ABI tag attributes. #ifndef _GLIBCXX_ABI_TAG_CXX11 # define _GLIBCXX_ABI_TAG_CXX11 __attribute ((__abi_tag__ ("cxx11"))) #endif // Macro to warn about unused results. #if __cplusplus >= 201703L # define _GLIBCXX_NODISCARD [[__nodiscard__]] #else # define _GLIBCXX_NODISCARD #endif #if __cplusplus // Macro for constexpr, to support in mixed 03/0x mode. #ifndef _GLIBCXX_CONSTEXPR # if __cplusplus >= 201103L # define _GLIBCXX_CONSTEXPR constexpr # define _GLIBCXX_USE_CONSTEXPR constexpr # else # define _GLIBCXX_CONSTEXPR # define _GLIBCXX_USE_CONSTEXPR const # endif #endif #ifndef _GLIBCXX14_CONSTEXPR # if __cplusplus >= 201402L # define _GLIBCXX14_CONSTEXPR constexpr # else # define _GLIBCXX14_CONSTEXPR # endif #endif #ifndef _GLIBCXX17_CONSTEXPR # if __cplusplus > 201402L # define _GLIBCXX17_CONSTEXPR constexpr # else # define _GLIBCXX17_CONSTEXPR # endif #endif #ifndef _GLIBCXX17_INLINE # if __cplusplus > 201402L # define _GLIBCXX17_INLINE inline # else # define _GLIBCXX17_INLINE # endif #endif // Macro for noexcept, to support in mixed 03/0x mode. #ifndef _GLIBCXX_NOEXCEPT # if __cplusplus >= 201103L # define _GLIBCXX_NOEXCEPT noexcept # define _GLIBCXX_NOEXCEPT_IF(_COND) noexcept(_COND) # define _GLIBCXX_USE_NOEXCEPT noexcept # define _GLIBCXX_THROW(_EXC) # else # define _GLIBCXX_NOEXCEPT # define _GLIBCXX_NOEXCEPT_IF(_COND) # define _GLIBCXX_USE_NOEXCEPT throw() # define _GLIBCXX_THROW(_EXC) throw(_EXC) # endif #endif #ifndef _GLIBCXX_NOTHROW # define _GLIBCXX_NOTHROW _GLIBCXX_USE_NOEXCEPT #endif #ifndef _GLIBCXX_THROW_OR_ABORT # if __cpp_exceptions # define _GLIBCXX_THROW_OR_ABORT(_EXC) (throw (_EXC)) # else # define _GLIBCXX_THROW_OR_ABORT(_EXC) (__builtin_abort()) # endif #endif #if __cpp_noexcept_function_type #define _GLIBCXX_NOEXCEPT_PARM , bool _NE #define _GLIBCXX_NOEXCEPT_QUAL noexcept (_NE) #else #define _GLIBCXX_NOEXCEPT_PARM #define _GLIBCXX_NOEXCEPT_QUAL #endif // Macro for extern template, ie controlling template linkage via use // of extern keyword on template declaration. As documented in the g++ // manual, it inhibits all implicit instantiations and is used // throughout the library to avoid multiple weak definitions for // required types that are already explicitly instantiated in the // library binary. This substantially reduces the binary size of // resulting executables. // Special case: _GLIBCXX_EXTERN_TEMPLATE == -1 disallows extern // templates only in basic_string, thus activating its debug-mode // checks even at -O0. # define _GLIBCXX_EXTERN_TEMPLATE 1 /* Outline of libstdc++ namespaces. namespace std { namespace __debug { } namespace __parallel { } namespace __profile { } namespace __cxx1998 { } namespace __detail { namespace __variant { } // C++17 } namespace rel_ops { } namespace tr1 { namespace placeholders { } namespace regex_constants { } namespace __detail { } } namespace tr2 { } namespace decimal { } namespace chrono { } // C++11 namespace placeholders { } // C++11 namespace regex_constants { } // C++11 namespace this_thread { } // C++11 inline namespace literals { // C++14 inline namespace chrono_literals { } // C++14 inline namespace complex_literals { } // C++14 inline namespace string_literals { } // C++14 inline namespace string_view_literals { } // C++17 } } namespace abi { } namespace __gnu_cxx { namespace __detail { } } For full details see: http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespaces.html */ namespace std { typedef __SIZE_TYPE__ size_t; typedef __PTRDIFF_TYPE__ ptrdiff_t; #if __cplusplus >= 201103L typedef decltype(nullptr) nullptr_t; #endif } # define _GLIBCXX_USE_DUAL_ABI 1 #if ! _GLIBCXX_USE_DUAL_ABI // Ignore any pre-defined value of _GLIBCXX_USE_CXX11_ABI # undef _GLIBCXX_USE_CXX11_ABI #endif #ifndef _GLIBCXX_USE_CXX11_ABI # define _GLIBCXX_USE_CXX11_ABI 1 #endif #if _GLIBCXX_USE_CXX11_ABI namespace std { inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } } namespace __gnu_cxx { inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } } # define _GLIBCXX_NAMESPACE_CXX11 __cxx11:: # define _GLIBCXX_BEGIN_NAMESPACE_CXX11 namespace __cxx11 { # define _GLIBCXX_END_NAMESPACE_CXX11 } # define _GLIBCXX_DEFAULT_ABI_TAG _GLIBCXX_ABI_TAG_CXX11 #else # define _GLIBCXX_NAMESPACE_CXX11 # define _GLIBCXX_BEGIN_NAMESPACE_CXX11 # define _GLIBCXX_END_NAMESPACE_CXX11 # define _GLIBCXX_DEFAULT_ABI_TAG #endif // Defined if inline namespaces are used for versioning. # define _GLIBCXX_INLINE_VERSION 0 // Inline namespace for symbol versioning. #if _GLIBCXX_INLINE_VERSION # define _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __8 { # define _GLIBCXX_END_NAMESPACE_VERSION } namespace std { inline _GLIBCXX_BEGIN_NAMESPACE_VERSION #if __cplusplus >= 201402L inline namespace literals { inline namespace chrono_literals { } inline namespace complex_literals { } inline namespace string_literals { } #if __cplusplus > 201402L inline namespace string_view_literals { } #endif // C++17 } #endif // C++14 _GLIBCXX_END_NAMESPACE_VERSION } namespace __gnu_cxx { inline _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_END_NAMESPACE_VERSION } #else # define _GLIBCXX_BEGIN_NAMESPACE_VERSION # define _GLIBCXX_END_NAMESPACE_VERSION #endif // Inline namespaces for special modes: debug, parallel, profile. #if defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PARALLEL) \ || defined(_GLIBCXX_PROFILE) namespace std { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Non-inline namespace for components replaced by alternates in active mode. namespace __cxx1998 { # if _GLIBCXX_USE_CXX11_ABI inline namespace __cxx11 __attribute__((__abi_tag__ ("cxx11"))) { } # endif } _GLIBCXX_END_NAMESPACE_VERSION // Inline namespace for debug mode. # ifdef _GLIBCXX_DEBUG inline namespace __debug { } # endif // Inline namespaces for parallel mode. # ifdef _GLIBCXX_PARALLEL inline namespace __parallel { } # endif // Inline namespaces for profile mode # ifdef _GLIBCXX_PROFILE inline namespace __profile { } # endif } // Check for invalid usage and unsupported mixed-mode use. # if defined(_GLIBCXX_DEBUG) && defined(_GLIBCXX_PARALLEL) # error illegal use of multiple inlined namespaces # endif # if defined(_GLIBCXX_PROFILE) && defined(_GLIBCXX_DEBUG) # error illegal use of multiple inlined namespaces # endif # if defined(_GLIBCXX_PROFILE) && defined(_GLIBCXX_PARALLEL) # error illegal use of multiple inlined namespaces # endif // Check for invalid use due to lack for weak symbols. # if __NO_INLINE__ && !__GXX_WEAK__ # warning currently using inlined namespace mode which may fail \ without inlining due to lack of weak symbols # endif #endif // Macros for namespace scope. Either namespace std:: or the name // of some nested namespace within it corresponding to the active mode. // _GLIBCXX_STD_A // _GLIBCXX_STD_C // // Macros for opening/closing conditional namespaces. // _GLIBCXX_BEGIN_NAMESPACE_ALGO // _GLIBCXX_END_NAMESPACE_ALGO // _GLIBCXX_BEGIN_NAMESPACE_CONTAINER // _GLIBCXX_END_NAMESPACE_CONTAINER #if defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_PROFILE) # define _GLIBCXX_STD_C __cxx1998 # define _GLIBCXX_BEGIN_NAMESPACE_CONTAINER \ namespace _GLIBCXX_STD_C { # define _GLIBCXX_END_NAMESPACE_CONTAINER } #else # define _GLIBCXX_STD_C std # define _GLIBCXX_BEGIN_NAMESPACE_CONTAINER # define _GLIBCXX_END_NAMESPACE_CONTAINER #endif #ifdef _GLIBCXX_PARALLEL # define _GLIBCXX_STD_A __cxx1998 # define _GLIBCXX_BEGIN_NAMESPACE_ALGO \ namespace _GLIBCXX_STD_A { # define _GLIBCXX_END_NAMESPACE_ALGO } #else # define _GLIBCXX_STD_A std # define _GLIBCXX_BEGIN_NAMESPACE_ALGO # define _GLIBCXX_END_NAMESPACE_ALGO #endif // GLIBCXX_ABI Deprecated // Define if compatibility should be provided for -mlong-double-64. #undef _GLIBCXX_LONG_DOUBLE_COMPAT // Inline namespace for long double 128 mode. #if defined _GLIBCXX_LONG_DOUBLE_COMPAT && defined __LONG_DOUBLE_128__ namespace std { inline namespace __gnu_cxx_ldbl128 { } } # define _GLIBCXX_NAMESPACE_LDBL __gnu_cxx_ldbl128:: # define _GLIBCXX_BEGIN_NAMESPACE_LDBL namespace __gnu_cxx_ldbl128 { # define _GLIBCXX_END_NAMESPACE_LDBL } #else # define _GLIBCXX_NAMESPACE_LDBL # define _GLIBCXX_BEGIN_NAMESPACE_LDBL # define _GLIBCXX_END_NAMESPACE_LDBL #endif #if _GLIBCXX_USE_CXX11_ABI # define _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_NAMESPACE_CXX11 # define _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_CXX11 # define _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_END_NAMESPACE_CXX11 #else # define _GLIBCXX_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_NAMESPACE_LDBL # define _GLIBCXX_BEGIN_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_BEGIN_NAMESPACE_LDBL # define _GLIBCXX_END_NAMESPACE_LDBL_OR_CXX11 _GLIBCXX_END_NAMESPACE_LDBL #endif // Debug Mode implies checking assertions. #if defined(_GLIBCXX_DEBUG) && !defined(_GLIBCXX_ASSERTIONS) # define _GLIBCXX_ASSERTIONS 1 #endif // Disable std::string explicit instantiation declarations in order to assert. #ifdef _GLIBCXX_ASSERTIONS # undef _GLIBCXX_EXTERN_TEMPLATE # define _GLIBCXX_EXTERN_TEMPLATE -1 #endif // Assert. #if defined(_GLIBCXX_ASSERTIONS) \ || defined(_GLIBCXX_PARALLEL) || defined(_GLIBCXX_PARALLEL_ASSERTIONS) namespace std { // Avoid the use of assert, because we're trying to keep the // include out of the mix. inline void __replacement_assert(const char* __file, int __line, const char* __function, const char* __condition) { __builtin_printf("%s:%d: %s: Assertion '%s' failed.\n", __file, __line, __function, __condition); __builtin_abort(); } } #define __glibcxx_assert_impl(_Condition) \ do \ { \ if (! (_Condition)) \ std::__replacement_assert(__FILE__, __LINE__, __PRETTY_FUNCTION__, \ #_Condition); \ } while (false) #endif #if defined(_GLIBCXX_ASSERTIONS) # define __glibcxx_assert(_Condition) __glibcxx_assert_impl(_Condition) #else # define __glibcxx_assert(_Condition) #endif // Macros for race detectors. // _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) and // _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) should be used to explain // atomic (lock-free) synchronization to race detectors: // the race detector will infer a happens-before arc from the former to the // latter when they share the same argument pointer. // // The most frequent use case for these macros (and the only case in the // current implementation of the library) is atomic reference counting: // void _M_remove_reference() // { // _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&this->_M_refcount); // if (__gnu_cxx::__exchange_and_add_dispatch(&this->_M_refcount, -1) <= 0) // { // _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&this->_M_refcount); // _M_destroy(__a); // } // } // The annotations in this example tell the race detector that all memory // accesses occurred when the refcount was positive do not race with // memory accesses which occurred after the refcount became zero. #ifndef _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE # define _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) #endif #ifndef _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER # define _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) #endif // Macros for C linkage: define extern "C" linkage only when using C++. # define _GLIBCXX_BEGIN_EXTERN_C extern "C" { # define _GLIBCXX_END_EXTERN_C } # define _GLIBCXX_USE_ALLOCATOR_NEW 1 #else // !__cplusplus # define _GLIBCXX_BEGIN_EXTERN_C # define _GLIBCXX_END_EXTERN_C #endif // First includes. // Pick up any OS-specific definitions. #include // Pick up any CPU-specific definitions. #include // If platform uses neither visibility nor psuedo-visibility, // specify empty default for namespace annotation macros. #ifndef _GLIBCXX_PSEUDO_VISIBILITY # define _GLIBCXX_PSEUDO_VISIBILITY(V) #endif // Certain function definitions that are meant to be overridable from // user code are decorated with this macro. For some targets, this // macro causes these definitions to be weak. #ifndef _GLIBCXX_WEAK_DEFINITION # define _GLIBCXX_WEAK_DEFINITION #endif // By default, we assume that __GXX_WEAK__ also means that there is support // for declaring functions as weak while not defining such functions. This // allows for referring to functions provided by other libraries (e.g., // libitm) without depending on them if the respective features are not used. #ifndef _GLIBCXX_USE_WEAK_REF # define _GLIBCXX_USE_WEAK_REF __GXX_WEAK__ #endif // Conditionally enable annotations for the Transactional Memory TS on C++11. // Most of the following conditions are due to limitations in the current // implementation. #if __cplusplus >= 201103L && _GLIBCXX_USE_CXX11_ABI \ && _GLIBCXX_USE_DUAL_ABI && __cpp_transactional_memory >= 201505L \ && !_GLIBCXX_FULLY_DYNAMIC_STRING && _GLIBCXX_USE_WEAK_REF \ && _GLIBCXX_USE_ALLOCATOR_NEW #define _GLIBCXX_TXN_SAFE transaction_safe #define _GLIBCXX_TXN_SAFE_DYN transaction_safe_dynamic #else #define _GLIBCXX_TXN_SAFE #define _GLIBCXX_TXN_SAFE_DYN #endif #if __cplusplus > 201402L // In C++17 mathematical special functions are in namespace std. # define _GLIBCXX_USE_STD_SPEC_FUNCS 1 #elif __cplusplus >= 201103L && __STDCPP_WANT_MATH_SPEC_FUNCS__ != 0 // For C++11 and C++14 they are in namespace std when requested. # define _GLIBCXX_USE_STD_SPEC_FUNCS 1 #endif // The remainder of the prewritten config is automatic; all the // user hooks are listed above. // Create a boolean flag to be used to determine if --fast-math is set. #ifdef __FAST_MATH__ # define _GLIBCXX_FAST_MATH 1 #else # define _GLIBCXX_FAST_MATH 0 #endif // This marks string literals in header files to be extracted for eventual // translation. It is primarily used for messages in thrown exceptions; see // src/functexcept.cc. We use __N because the more traditional _N is used // for something else under certain OSes (see BADNAMES). #define __N(msgid) (msgid) // For example, is known to #define min and max as macros... #undef min #undef max // N.B. these _GLIBCXX_USE_C99_XXX macros are defined unconditionally // so they should be tested with #if not with #ifdef. #if __cplusplus >= 201103L # ifndef _GLIBCXX_USE_C99_MATH # define _GLIBCXX_USE_C99_MATH _GLIBCXX11_USE_C99_MATH # endif # ifndef _GLIBCXX_USE_C99_COMPLEX # define _GLIBCXX_USE_C99_COMPLEX _GLIBCXX11_USE_C99_COMPLEX # endif # ifndef _GLIBCXX_USE_C99_STDIO # define _GLIBCXX_USE_C99_STDIO _GLIBCXX11_USE_C99_STDIO # endif # ifndef _GLIBCXX_USE_C99_STDLIB # define _GLIBCXX_USE_C99_STDLIB _GLIBCXX11_USE_C99_STDLIB # endif # ifndef _GLIBCXX_USE_C99_WCHAR # define _GLIBCXX_USE_C99_WCHAR _GLIBCXX11_USE_C99_WCHAR # endif #else # ifndef _GLIBCXX_USE_C99_MATH # define _GLIBCXX_USE_C99_MATH _GLIBCXX98_USE_C99_MATH # endif # ifndef _GLIBCXX_USE_C99_COMPLEX # define _GLIBCXX_USE_C99_COMPLEX _GLIBCXX98_USE_C99_COMPLEX # endif # ifndef _GLIBCXX_USE_C99_STDIO # define _GLIBCXX_USE_C99_STDIO _GLIBCXX98_USE_C99_STDIO # endif # ifndef _GLIBCXX_USE_C99_STDLIB # define _GLIBCXX_USE_C99_STDLIB _GLIBCXX98_USE_C99_STDLIB # endif # ifndef _GLIBCXX_USE_C99_WCHAR # define _GLIBCXX_USE_C99_WCHAR _GLIBCXX98_USE_C99_WCHAR # endif #endif /* Define if __float128 is supported on this host. */ #if defined(__FLOAT128__) || defined(__SIZEOF_FLOAT128__) #define _GLIBCXX_USE_FLOAT128 1 #endif // End of prewritten config; the settings discovered at configure time follow. /* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the `acosf' function. */ #define _GLIBCXX_HAVE_ACOSF 1 /* Define to 1 if you have the `acosl' function. */ #define _GLIBCXX_HAVE_ACOSL 1 /* Define to 1 if you have the `aligned_alloc' function. */ #define _GLIBCXX_HAVE_ALIGNED_ALLOC 1 /* Define to 1 if you have the `asinf' function. */ #define _GLIBCXX_HAVE_ASINF 1 /* Define to 1 if you have the `asinl' function. */ #define _GLIBCXX_HAVE_ASINL 1 /* Define to 1 if the target assembler supports .symver directive. */ #define _GLIBCXX_HAVE_AS_SYMVER_DIRECTIVE 1 /* Define to 1 if you have the `atan2f' function. */ #define _GLIBCXX_HAVE_ATAN2F 1 /* Define to 1 if you have the `atan2l' function. */ #define _GLIBCXX_HAVE_ATAN2L 1 /* Define to 1 if you have the `atanf' function. */ #define _GLIBCXX_HAVE_ATANF 1 /* Define to 1 if you have the `atanl' function. */ #define _GLIBCXX_HAVE_ATANL 1 /* Define to 1 if you have the `at_quick_exit' function. */ #define _GLIBCXX_HAVE_AT_QUICK_EXIT 1 /* Define to 1 if the target assembler supports thread-local storage. */ /* #undef _GLIBCXX_HAVE_CC_TLS */ /* Define to 1 if you have the `ceilf' function. */ #define _GLIBCXX_HAVE_CEILF 1 /* Define to 1 if you have the `ceill' function. */ #define _GLIBCXX_HAVE_CEILL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_COMPLEX_H 1 /* Define to 1 if you have the `cosf' function. */ #define _GLIBCXX_HAVE_COSF 1 /* Define to 1 if you have the `coshf' function. */ #define _GLIBCXX_HAVE_COSHF 1 /* Define to 1 if you have the `coshl' function. */ #define _GLIBCXX_HAVE_COSHL 1 /* Define to 1 if you have the `cosl' function. */ #define _GLIBCXX_HAVE_COSL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_DIRENT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_DLFCN_H 1 /* Define if EBADMSG exists. */ #define _GLIBCXX_HAVE_EBADMSG 1 /* Define if ECANCELED exists. */ #define _GLIBCXX_HAVE_ECANCELED 1 /* Define if ECHILD exists. */ #define _GLIBCXX_HAVE_ECHILD 1 /* Define if EIDRM exists. */ #define _GLIBCXX_HAVE_EIDRM 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_ENDIAN_H 1 /* Define if ENODATA exists. */ #define _GLIBCXX_HAVE_ENODATA 1 /* Define if ENOLINK exists. */ #define _GLIBCXX_HAVE_ENOLINK 1 /* Define if ENOSPC exists. */ #define _GLIBCXX_HAVE_ENOSPC 1 /* Define if ENOSR exists. */ #define _GLIBCXX_HAVE_ENOSR 1 /* Define if ENOSTR exists. */ #define _GLIBCXX_HAVE_ENOSTR 1 /* Define if ENOTRECOVERABLE exists. */ #define _GLIBCXX_HAVE_ENOTRECOVERABLE 1 /* Define if ENOTSUP exists. */ #define _GLIBCXX_HAVE_ENOTSUP 1 /* Define if EOVERFLOW exists. */ #define _GLIBCXX_HAVE_EOVERFLOW 1 /* Define if EOWNERDEAD exists. */ #define _GLIBCXX_HAVE_EOWNERDEAD 1 /* Define if EPERM exists. */ #define _GLIBCXX_HAVE_EPERM 1 /* Define if EPROTO exists. */ #define _GLIBCXX_HAVE_EPROTO 1 /* Define if ETIME exists. */ #define _GLIBCXX_HAVE_ETIME 1 /* Define if ETIMEDOUT exists. */ #define _GLIBCXX_HAVE_ETIMEDOUT 1 /* Define if ETXTBSY exists. */ #define _GLIBCXX_HAVE_ETXTBSY 1 /* Define if EWOULDBLOCK exists. */ #define _GLIBCXX_HAVE_EWOULDBLOCK 1 /* Define to 1 if GCC 4.6 supported std::exception_ptr for the target */ #define _GLIBCXX_HAVE_EXCEPTION_PTR_SINCE_GCC46 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_EXECINFO_H 1 /* Define to 1 if you have the `expf' function. */ #define _GLIBCXX_HAVE_EXPF 1 /* Define to 1 if you have the `expl' function. */ #define _GLIBCXX_HAVE_EXPL 1 /* Define to 1 if you have the `fabsf' function. */ #define _GLIBCXX_HAVE_FABSF 1 /* Define to 1 if you have the `fabsl' function. */ #define _GLIBCXX_HAVE_FABSL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FCNTL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FENV_H 1 /* Define to 1 if you have the `finite' function. */ #define _GLIBCXX_HAVE_FINITE 1 /* Define to 1 if you have the `finitef' function. */ #define _GLIBCXX_HAVE_FINITEF 1 /* Define to 1 if you have the `finitel' function. */ #define _GLIBCXX_HAVE_FINITEL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_FLOAT_H 1 /* Define to 1 if you have the `floorf' function. */ #define _GLIBCXX_HAVE_FLOORF 1 /* Define to 1 if you have the `floorl' function. */ #define _GLIBCXX_HAVE_FLOORL 1 /* Define to 1 if you have the `fmodf' function. */ #define _GLIBCXX_HAVE_FMODF 1 /* Define to 1 if you have the `fmodl' function. */ #define _GLIBCXX_HAVE_FMODL 1 /* Define to 1 if you have the `fpclass' function. */ /* #undef _GLIBCXX_HAVE_FPCLASS */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_FP_H */ /* Define to 1 if you have the `frexpf' function. */ #define _GLIBCXX_HAVE_FREXPF 1 /* Define to 1 if you have the `frexpl' function. */ #define _GLIBCXX_HAVE_FREXPL 1 /* Define if _Unwind_GetIPInfo is available. */ #define _GLIBCXX_HAVE_GETIPINFO 1 /* Define if gets is available in before C++14. */ #define _GLIBCXX_HAVE_GETS 1 /* Define to 1 if you have the `hypot' function. */ #define _GLIBCXX_HAVE_HYPOT 1 /* Define to 1 if you have the `hypotf' function. */ #define _GLIBCXX_HAVE_HYPOTF 1 /* Define to 1 if you have the `hypotl' function. */ #define _GLIBCXX_HAVE_HYPOTL 1 /* Define if you have the iconv() function. */ #define _GLIBCXX_HAVE_ICONV 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_IEEEFP_H */ /* Define if int64_t is available in . */ #define _GLIBCXX_HAVE_INT64_T 1 /* Define if int64_t is a long. */ /* #undef _GLIBCXX_HAVE_INT64_T_LONG */ /* Define if int64_t is a long long. */ #define _GLIBCXX_HAVE_INT64_T_LONG_LONG 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_INTTYPES_H 1 /* Define to 1 if you have the `isinf' function. */ /* #undef _GLIBCXX_HAVE_ISINF */ /* Define to 1 if you have the `isinff' function. */ #define _GLIBCXX_HAVE_ISINFF 1 /* Define to 1 if you have the `isinfl' function. */ #define _GLIBCXX_HAVE_ISINFL 1 /* Define to 1 if you have the `isnan' function. */ /* #undef _GLIBCXX_HAVE_ISNAN */ /* Define to 1 if you have the `isnanf' function. */ #define _GLIBCXX_HAVE_ISNANF 1 /* Define to 1 if you have the `isnanl' function. */ #define _GLIBCXX_HAVE_ISNANL 1 /* Defined if iswblank exists. */ #define _GLIBCXX_HAVE_ISWBLANK 1 /* Define if LC_MESSAGES is available in . */ #define _GLIBCXX_HAVE_LC_MESSAGES 1 /* Define to 1 if you have the `ldexpf' function. */ #define _GLIBCXX_HAVE_LDEXPF 1 /* Define to 1 if you have the `ldexpl' function. */ #define _GLIBCXX_HAVE_LDEXPL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LIBINTL_H 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_AS 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_DATA 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_FSIZE 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_RSS 1 /* Only used in build directory testsuite_hooks.h. */ #define _GLIBCXX_HAVE_LIMIT_VMEM 0 /* Define if futex syscall is available. */ #define _GLIBCXX_HAVE_LINUX_FUTEX 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LINUX_RANDOM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LINUX_TYPES_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_LOCALE_H 1 /* Define to 1 if you have the `log10f' function. */ #define _GLIBCXX_HAVE_LOG10F 1 /* Define to 1 if you have the `log10l' function. */ #define _GLIBCXX_HAVE_LOG10L 1 /* Define to 1 if you have the `logf' function. */ #define _GLIBCXX_HAVE_LOGF 1 /* Define to 1 if you have the `logl' function. */ #define _GLIBCXX_HAVE_LOGL 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_MACHINE_ENDIAN_H */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_MACHINE_PARAM_H */ /* Define if mbstate_t exists in wchar.h. */ #define _GLIBCXX_HAVE_MBSTATE_T 1 /* Define to 1 if you have the `memalign' function. */ #define _GLIBCXX_HAVE_MEMALIGN 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_MEMORY_H 1 /* Define to 1 if you have the `modf' function. */ #define _GLIBCXX_HAVE_MODF 1 /* Define to 1 if you have the `modff' function. */ #define _GLIBCXX_HAVE_MODFF 1 /* Define to 1 if you have the `modfl' function. */ #define _GLIBCXX_HAVE_MODFL 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_NAN_H */ /* Define if defines obsolete isinf function. */ /* #undef _GLIBCXX_HAVE_OBSOLETE_ISINF */ /* Define if defines obsolete isnan function. */ /* #undef _GLIBCXX_HAVE_OBSOLETE_ISNAN */ /* Define if poll is available in . */ #define _GLIBCXX_HAVE_POLL 1 /* Define to 1 if you have the `posix_memalign' function. */ #define _GLIBCXX_HAVE_POSIX_MEMALIGN 1 /* Define to 1 if you have the `powf' function. */ #define _GLIBCXX_HAVE_POWF 1 /* Define to 1 if you have the `powl' function. */ #define _GLIBCXX_HAVE_POWL 1 /* Define to 1 if you have the `qfpclass' function. */ /* #undef _GLIBCXX_HAVE_QFPCLASS */ /* Define to 1 if you have the `quick_exit' function. */ #define _GLIBCXX_HAVE_QUICK_EXIT 1 /* Define to 1 if you have the `setenv' function. */ #define _GLIBCXX_HAVE_SETENV 1 /* Define to 1 if you have the `sincos' function. */ #define _GLIBCXX_HAVE_SINCOS 1 /* Define to 1 if you have the `sincosf' function. */ #define _GLIBCXX_HAVE_SINCOSF 1 /* Define to 1 if you have the `sincosl' function. */ #define _GLIBCXX_HAVE_SINCOSL 1 /* Define to 1 if you have the `sinf' function. */ #define _GLIBCXX_HAVE_SINF 1 /* Define to 1 if you have the `sinhf' function. */ #define _GLIBCXX_HAVE_SINHF 1 /* Define to 1 if you have the `sinhl' function. */ #define _GLIBCXX_HAVE_SINHL 1 /* Define to 1 if you have the `sinl' function. */ #define _GLIBCXX_HAVE_SINL 1 /* Defined if sleep exists. */ /* #undef _GLIBCXX_HAVE_SLEEP */ /* Define to 1 if you have the `sqrtf' function. */ #define _GLIBCXX_HAVE_SQRTF 1 /* Define to 1 if you have the `sqrtl' function. */ #define _GLIBCXX_HAVE_SQRTL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDALIGN_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDBOOL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STDLIB_H 1 /* Define if strerror_l is available in . */ #define _GLIBCXX_HAVE_STRERROR_L 1 /* Define if strerror_r is available in . */ #define _GLIBCXX_HAVE_STRERROR_R 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_STRING_H 1 /* Define to 1 if you have the `strtof' function. */ #define _GLIBCXX_HAVE_STRTOF 1 /* Define to 1 if you have the `strtold' function. */ #define _GLIBCXX_HAVE_STRTOLD 1 /* Define to 1 if `d_type' is a member of `struct dirent'. */ #define _GLIBCXX_HAVE_STRUCT_DIRENT_D_TYPE 1 /* Define if strxfrm_l is available in . */ #define _GLIBCXX_HAVE_STRXFRM_L 1 /* Define to 1 if the target runtime linker supports binding the same symbol to different versions. */ #define _GLIBCXX_HAVE_SYMVER_SYMBOL_RENAMING_RUNTIME_SUPPORT 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_FILIO_H */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_IOCTL_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_IPC_H 1 /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_ISA_DEFS_H */ /* Define to 1 if you have the header file. */ /* #undef _GLIBCXX_HAVE_SYS_MACHINE_H */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_PARAM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_RESOURCE_H 1 /* Define to 1 if you have a suitable header file */ #define _GLIBCXX_HAVE_SYS_SDT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_SEM_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_STATVFS_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_SYSINFO_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_TIME_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_SYS_UIO_H 1 /* Define if S_IFREG is available in . */ /* #undef _GLIBCXX_HAVE_S_IFREG */ /* Define if S_ISREG is available in . */ #define _GLIBCXX_HAVE_S_ISREG 1 /* Define to 1 if you have the `tanf' function. */ #define _GLIBCXX_HAVE_TANF 1 /* Define to 1 if you have the `tanhf' function. */ #define _GLIBCXX_HAVE_TANHF 1 /* Define to 1 if you have the `tanhl' function. */ #define _GLIBCXX_HAVE_TANHL 1 /* Define to 1 if you have the `tanl' function. */ #define _GLIBCXX_HAVE_TANL 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_TGMATH_H 1 /* Define to 1 if the target supports thread-local storage. */ #define _GLIBCXX_HAVE_TLS 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UCHAR_H 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UNISTD_H 1 /* Defined if usleep exists. */ /* #undef _GLIBCXX_HAVE_USLEEP */ /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_UTIME_H 1 /* Defined if vfwscanf exists. */ #define _GLIBCXX_HAVE_VFWSCANF 1 /* Defined if vswscanf exists. */ #define _GLIBCXX_HAVE_VSWSCANF 1 /* Defined if vwscanf exists. */ #define _GLIBCXX_HAVE_VWSCANF 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_WCHAR_H 1 /* Defined if wcstof exists. */ #define _GLIBCXX_HAVE_WCSTOF 1 /* Define to 1 if you have the header file. */ #define _GLIBCXX_HAVE_WCTYPE_H 1 /* Defined if Sleep exists. */ /* #undef _GLIBCXX_HAVE_WIN32_SLEEP */ /* Define if writev is available in . */ #define _GLIBCXX_HAVE_WRITEV 1 /* Define to 1 if you have the `_acosf' function. */ /* #undef _GLIBCXX_HAVE__ACOSF */ /* Define to 1 if you have the `_acosl' function. */ /* #undef _GLIBCXX_HAVE__ACOSL */ /* Define to 1 if you have the `_aligned_malloc' function. */ /* #undef _GLIBCXX_HAVE__ALIGNED_MALLOC */ /* Define to 1 if you have the `_asinf' function. */ /* #undef _GLIBCXX_HAVE__ASINF */ /* Define to 1 if you have the `_asinl' function. */ /* #undef _GLIBCXX_HAVE__ASINL */ /* Define to 1 if you have the `_atan2f' function. */ /* #undef _GLIBCXX_HAVE__ATAN2F */ /* Define to 1 if you have the `_atan2l' function. */ /* #undef _GLIBCXX_HAVE__ATAN2L */ /* Define to 1 if you have the `_atanf' function. */ /* #undef _GLIBCXX_HAVE__ATANF */ /* Define to 1 if you have the `_atanl' function. */ /* #undef _GLIBCXX_HAVE__ATANL */ /* Define to 1 if you have the `_ceilf' function. */ /* #undef _GLIBCXX_HAVE__CEILF */ /* Define to 1 if you have the `_ceill' function. */ /* #undef _GLIBCXX_HAVE__CEILL */ /* Define to 1 if you have the `_cosf' function. */ /* #undef _GLIBCXX_HAVE__COSF */ /* Define to 1 if you have the `_coshf' function. */ /* #undef _GLIBCXX_HAVE__COSHF */ /* Define to 1 if you have the `_coshl' function. */ /* #undef _GLIBCXX_HAVE__COSHL */ /* Define to 1 if you have the `_cosl' function. */ /* #undef _GLIBCXX_HAVE__COSL */ /* Define to 1 if you have the `_expf' function. */ /* #undef _GLIBCXX_HAVE__EXPF */ /* Define to 1 if you have the `_expl' function. */ /* #undef _GLIBCXX_HAVE__EXPL */ /* Define to 1 if you have the `_fabsf' function. */ /* #undef _GLIBCXX_HAVE__FABSF */ /* Define to 1 if you have the `_fabsl' function. */ /* #undef _GLIBCXX_HAVE__FABSL */ /* Define to 1 if you have the `_finite' function. */ /* #undef _GLIBCXX_HAVE__FINITE */ /* Define to 1 if you have the `_finitef' function. */ /* #undef _GLIBCXX_HAVE__FINITEF */ /* Define to 1 if you have the `_finitel' function. */ /* #undef _GLIBCXX_HAVE__FINITEL */ /* Define to 1 if you have the `_floorf' function. */ /* #undef _GLIBCXX_HAVE__FLOORF */ /* Define to 1 if you have the `_floorl' function. */ /* #undef _GLIBCXX_HAVE__FLOORL */ /* Define to 1 if you have the `_fmodf' function. */ /* #undef _GLIBCXX_HAVE__FMODF */ /* Define to 1 if you have the `_fmodl' function. */ /* #undef _GLIBCXX_HAVE__FMODL */ /* Define to 1 if you have the `_fpclass' function. */ /* #undef _GLIBCXX_HAVE__FPCLASS */ /* Define to 1 if you have the `_frexpf' function. */ /* #undef _GLIBCXX_HAVE__FREXPF */ /* Define to 1 if you have the `_frexpl' function. */ /* #undef _GLIBCXX_HAVE__FREXPL */ /* Define to 1 if you have the `_hypot' function. */ /* #undef _GLIBCXX_HAVE__HYPOT */ /* Define to 1 if you have the `_hypotf' function. */ /* #undef _GLIBCXX_HAVE__HYPOTF */ /* Define to 1 if you have the `_hypotl' function. */ /* #undef _GLIBCXX_HAVE__HYPOTL */ /* Define to 1 if you have the `_isinf' function. */ /* #undef _GLIBCXX_HAVE__ISINF */ /* Define to 1 if you have the `_isinff' function. */ /* #undef _GLIBCXX_HAVE__ISINFF */ /* Define to 1 if you have the `_isinfl' function. */ /* #undef _GLIBCXX_HAVE__ISINFL */ /* Define to 1 if you have the `_isnan' function. */ /* #undef _GLIBCXX_HAVE__ISNAN */ /* Define to 1 if you have the `_isnanf' function. */ /* #undef _GLIBCXX_HAVE__ISNANF */ /* Define to 1 if you have the `_isnanl' function. */ /* #undef _GLIBCXX_HAVE__ISNANL */ /* Define to 1 if you have the `_ldexpf' function. */ /* #undef _GLIBCXX_HAVE__LDEXPF */ /* Define to 1 if you have the `_ldexpl' function. */ /* #undef _GLIBCXX_HAVE__LDEXPL */ /* Define to 1 if you have the `_log10f' function. */ /* #undef _GLIBCXX_HAVE__LOG10F */ /* Define to 1 if you have the `_log10l' function. */ /* #undef _GLIBCXX_HAVE__LOG10L */ /* Define to 1 if you have the `_logf' function. */ /* #undef _GLIBCXX_HAVE__LOGF */ /* Define to 1 if you have the `_logl' function. */ /* #undef _GLIBCXX_HAVE__LOGL */ /* Define to 1 if you have the `_modf' function. */ /* #undef _GLIBCXX_HAVE__MODF */ /* Define to 1 if you have the `_modff' function. */ /* #undef _GLIBCXX_HAVE__MODFF */ /* Define to 1 if you have the `_modfl' function. */ /* #undef _GLIBCXX_HAVE__MODFL */ /* Define to 1 if you have the `_powf' function. */ /* #undef _GLIBCXX_HAVE__POWF */ /* Define to 1 if you have the `_powl' function. */ /* #undef _GLIBCXX_HAVE__POWL */ /* Define to 1 if you have the `_qfpclass' function. */ /* #undef _GLIBCXX_HAVE__QFPCLASS */ /* Define to 1 if you have the `_sincos' function. */ /* #undef _GLIBCXX_HAVE__SINCOS */ /* Define to 1 if you have the `_sincosf' function. */ /* #undef _GLIBCXX_HAVE__SINCOSF */ /* Define to 1 if you have the `_sincosl' function. */ /* #undef _GLIBCXX_HAVE__SINCOSL */ /* Define to 1 if you have the `_sinf' function. */ /* #undef _GLIBCXX_HAVE__SINF */ /* Define to 1 if you have the `_sinhf' function. */ /* #undef _GLIBCXX_HAVE__SINHF */ /* Define to 1 if you have the `_sinhl' function. */ /* #undef _GLIBCXX_HAVE__SINHL */ /* Define to 1 if you have the `_sinl' function. */ /* #undef _GLIBCXX_HAVE__SINL */ /* Define to 1 if you have the `_sqrtf' function. */ /* #undef _GLIBCXX_HAVE__SQRTF */ /* Define to 1 if you have the `_sqrtl' function. */ /* #undef _GLIBCXX_HAVE__SQRTL */ /* Define to 1 if you have the `_tanf' function. */ /* #undef _GLIBCXX_HAVE__TANF */ /* Define to 1 if you have the `_tanhf' function. */ /* #undef _GLIBCXX_HAVE__TANHF */ /* Define to 1 if you have the `_tanhl' function. */ /* #undef _GLIBCXX_HAVE__TANHL */ /* Define to 1 if you have the `_tanl' function. */ /* #undef _GLIBCXX_HAVE__TANL */ /* Define to 1 if you have the `__cxa_thread_atexit' function. */ /* #undef _GLIBCXX_HAVE___CXA_THREAD_ATEXIT */ /* Define to 1 if you have the `__cxa_thread_atexit_impl' function. */ #define _GLIBCXX_HAVE___CXA_THREAD_ATEXIT_IMPL 1 /* Define as const if the declaration of iconv() needs const. */ #define _GLIBCXX_ICONV_CONST /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Name of package */ /* #undef _GLIBCXX_PACKAGE */ /* Define to the address where bug reports for this package should be sent. */ #define _GLIBCXX_PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define _GLIBCXX_PACKAGE_NAME "package-unused" /* Define to the full name and version of this package. */ #define _GLIBCXX_PACKAGE_STRING "package-unused version-unused" /* Define to the one symbol short name of this package. */ #define _GLIBCXX_PACKAGE_TARNAME "libstdc++" /* Define to the home page for this package. */ #define _GLIBCXX_PACKAGE_URL "" /* Define to the version of this package. */ #define _GLIBCXX_PACKAGE__GLIBCXX_VERSION "version-unused" /* The size of `char', as computed by sizeof. */ /* #undef SIZEOF_CHAR */ /* The size of `int', as computed by sizeof. */ /* #undef SIZEOF_INT */ /* The size of `long', as computed by sizeof. */ /* #undef SIZEOF_LONG */ /* The size of `short', as computed by sizeof. */ /* #undef SIZEOF_SHORT */ /* The size of `void *', as computed by sizeof. */ /* #undef SIZEOF_VOID_P */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ /* #undef _GLIBCXX_VERSION */ /* Number of bits in a file offset, on hosts where this is settable. */ #define _GLIBCXX_FILE_OFFSET_BITS 64 /* Define if C99 functions in should be used in for C++11. Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX11_USE_C99_COMPLEX 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_MATH 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_STDIO 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_STDLIB 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++11. */ #define _GLIBCXX11_USE_C99_WCHAR 1 /* Define if C99 functions in should be used in for C++98. Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX98_USE_C99_COMPLEX 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_MATH 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_STDIO 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_STDLIB 1 /* Define if C99 functions or macros in should be imported in in namespace std for C++98. */ #define _GLIBCXX98_USE_C99_WCHAR 1 /* Define if the compiler supports C++11 atomics. */ #define _GLIBCXX_ATOMIC_BUILTINS 1 /* Define to use concept checking code from the boost libraries. */ /* #undef _GLIBCXX_CONCEPT_CHECKS */ /* Define to 1 if a fully dynamic basic_string is wanted, 0 to disable, undefined for platform defaults */ #define _GLIBCXX_FULLY_DYNAMIC_STRING 0 /* Define if gthreads library is available. */ #define _GLIBCXX_HAS_GTHREADS 1 /* Define to 1 if a full hosted library is built, or 0 if freestanding. */ #define _GLIBCXX_HOSTED 1 /* Define if compatibility should be provided for -mlong-double-64. */ /* Define to the letter to which size_t is mangled. */ #define _GLIBCXX_MANGLE_SIZE_T j /* Define if C99 llrint and llround functions are missing from . */ /* #undef _GLIBCXX_NO_C99_ROUNDING_FUNCS */ /* Define if ptrdiff_t is int. */ #define _GLIBCXX_PTRDIFF_T_IS_INT 1 /* Define if using setrlimit to set resource limits during "make check" */ #define _GLIBCXX_RES_LIMITS 1 /* Define if size_t is unsigned int. */ #define _GLIBCXX_SIZE_T_IS_UINT 1 /* Define to the value of the EOF integer constant. */ #define _GLIBCXX_STDIO_EOF -1 /* Define to the value of the SEEK_CUR integer constant. */ #define _GLIBCXX_STDIO_SEEK_CUR 1 /* Define to the value of the SEEK_END integer constant. */ #define _GLIBCXX_STDIO_SEEK_END 2 /* Define to use symbol versioning in the shared library. */ #define _GLIBCXX_SYMVER 1 /* Define to use darwin versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_DARWIN */ /* Define to use GNU versioning in the shared library. */ #define _GLIBCXX_SYMVER_GNU 1 /* Define to use GNU namespace versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_GNU_NAMESPACE */ /* Define to use Sun versioning in the shared library. */ /* #undef _GLIBCXX_SYMVER_SUN */ /* Define if C11 functions in should be imported into namespace std in . */ #define _GLIBCXX_USE_C11_UCHAR_CXX11 1 /* Define if C99 functions or macros from , , , , and can be used or exposed. */ #define _GLIBCXX_USE_C99 1 /* Define if C99 functions in should be used in . Using compiler builtins for these functions requires corresponding C99 library functions to be present. */ #define _GLIBCXX_USE_C99_COMPLEX_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_CTYPE_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_FENV_TR1 1 /* Define if C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_INTTYPES_TR1 1 /* Define if wchar_t C99 functions in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_INTTYPES_WCHAR_T_TR1 1 /* Define if C99 functions or macros in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_MATH_TR1 1 /* Define if C99 types in should be imported in in namespace std::tr1. */ #define _GLIBCXX_USE_C99_STDINT_TR1 1 /* Defined if clock_gettime syscall has monotonic and realtime clock support. */ /* #undef _GLIBCXX_USE_CLOCK_GETTIME_SYSCALL */ /* Defined if clock_gettime has monotonic clock support. */ #define _GLIBCXX_USE_CLOCK_MONOTONIC 1 /* Defined if clock_gettime has realtime clock support. */ #define _GLIBCXX_USE_CLOCK_REALTIME 1 /* Define if ISO/IEC TR 24733 decimal floating point types are supported on this host. */ #define _GLIBCXX_USE_DECIMAL_FLOAT 1 /* Define if fchmod is available in . */ #define _GLIBCXX_USE_FCHMOD 1 /* Define if fchmodat is available in . */ #define _GLIBCXX_USE_FCHMODAT 1 /* Defined if gettimeofday is available. */ #define _GLIBCXX_USE_GETTIMEOFDAY 1 /* Define if get_nprocs is available in . */ #define _GLIBCXX_USE_GET_NPROCS 1 /* Define if __int128 is supported on this host. */ /* #undef _GLIBCXX_USE_INT128 */ /* Define if LFS support is available. */ #define _GLIBCXX_USE_LFS 1 /* Define if code specialized for long long should be used. */ #define _GLIBCXX_USE_LONG_LONG 1 /* Defined if nanosleep is available. */ #define _GLIBCXX_USE_NANOSLEEP 1 /* Define if NLS translations are to be used. */ #define _GLIBCXX_USE_NLS 1 /* Define if pthreads_num_processors_np is available in . */ /* #undef _GLIBCXX_USE_PTHREADS_NUM_PROCESSORS_NP */ /* Define if POSIX read/write locks are available in . */ #define _GLIBCXX_USE_PTHREAD_RWLOCK_T 1 /* Define if /dev/random and /dev/urandom are available for the random_device of TR1 (Chapter 5.1). */ #define _GLIBCXX_USE_RANDOM_TR1 1 /* Define if usable realpath is available in . */ #define _GLIBCXX_USE_REALPATH 1 /* Defined if sched_yield is available. */ #define _GLIBCXX_USE_SCHED_YIELD 1 /* Define if _SC_NPROCESSORS_ONLN is available in . */ #define _GLIBCXX_USE_SC_NPROCESSORS_ONLN 1 /* Define if _SC_NPROC_ONLN is available in . */ /* #undef _GLIBCXX_USE_SC_NPROC_ONLN */ /* Define if sendfile is available in . */ #define _GLIBCXX_USE_SENDFILE 1 /* Define if struct stat has timespec members. */ #define _GLIBCXX_USE_ST_MTIM 1 /* Define if sysctl(), CTL_HW and HW_NCPU are available in . */ /* #undef _GLIBCXX_USE_SYSCTL_HW_NCPU */ /* Define if obsolescent tmpnam is available in . */ #define _GLIBCXX_USE_TMPNAM 1 /* Define if utimensat and UTIME_OMIT are available in and AT_FDCWD in . */ #define _GLIBCXX_USE_UTIMENSAT 1 /* Define if code specialized for wchar_t should be used. */ #define _GLIBCXX_USE_WCHAR_T 1 /* Define to 1 if a verbose library is built, or 0 otherwise. */ #define _GLIBCXX_VERBOSE 1 /* Defined if as can handle rdrand. */ #define _GLIBCXX_X86_RDRAND 1 /* Define to 1 if mutex_timedlock is available. */ #define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 /* Define for large files, on AIX-style hosts. */ /* #undef _GLIBCXX_LARGE_FILES */ /* Define if all C++11 floating point overloads are available in . */ #if __cplusplus >= 201103L /* #undef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP */ #endif /* Define if all C++11 integral type overloads are available in . */ #if __cplusplus >= 201103L /* #undef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT */ #endif #if defined (_GLIBCXX_HAVE__ACOSF) && ! defined (_GLIBCXX_HAVE_ACOSF) # define _GLIBCXX_HAVE_ACOSF 1 # define acosf _acosf #endif #if defined (_GLIBCXX_HAVE__ACOSL) && ! defined (_GLIBCXX_HAVE_ACOSL) # define _GLIBCXX_HAVE_ACOSL 1 # define acosl _acosl #endif #if defined (_GLIBCXX_HAVE__ASINF) && ! defined (_GLIBCXX_HAVE_ASINF) # define _GLIBCXX_HAVE_ASINF 1 # define asinf _asinf #endif #if defined (_GLIBCXX_HAVE__ASINL) && ! defined (_GLIBCXX_HAVE_ASINL) # define _GLIBCXX_HAVE_ASINL 1 # define asinl _asinl #endif #if defined (_GLIBCXX_HAVE__ATAN2F) && ! defined (_GLIBCXX_HAVE_ATAN2F) # define _GLIBCXX_HAVE_ATAN2F 1 # define atan2f _atan2f #endif #if defined (_GLIBCXX_HAVE__ATAN2L) && ! defined (_GLIBCXX_HAVE_ATAN2L) # define _GLIBCXX_HAVE_ATAN2L 1 # define atan2l _atan2l #endif #if defined (_GLIBCXX_HAVE__ATANF) && ! defined (_GLIBCXX_HAVE_ATANF) # define _GLIBCXX_HAVE_ATANF 1 # define atanf _atanf #endif #if defined (_GLIBCXX_HAVE__ATANL) && ! defined (_GLIBCXX_HAVE_ATANL) # define _GLIBCXX_HAVE_ATANL 1 # define atanl _atanl #endif #if defined (_GLIBCXX_HAVE__CEILF) && ! defined (_GLIBCXX_HAVE_CEILF) # define _GLIBCXX_HAVE_CEILF 1 # define ceilf _ceilf #endif #if defined (_GLIBCXX_HAVE__CEILL) && ! defined (_GLIBCXX_HAVE_CEILL) # define _GLIBCXX_HAVE_CEILL 1 # define ceill _ceill #endif #if defined (_GLIBCXX_HAVE__COSF) && ! defined (_GLIBCXX_HAVE_COSF) # define _GLIBCXX_HAVE_COSF 1 # define cosf _cosf #endif #if defined (_GLIBCXX_HAVE__COSHF) && ! defined (_GLIBCXX_HAVE_COSHF) # define _GLIBCXX_HAVE_COSHF 1 # define coshf _coshf #endif #if defined (_GLIBCXX_HAVE__COSHL) && ! defined (_GLIBCXX_HAVE_COSHL) # define _GLIBCXX_HAVE_COSHL 1 # define coshl _coshl #endif #if defined (_GLIBCXX_HAVE__COSL) && ! defined (_GLIBCXX_HAVE_COSL) # define _GLIBCXX_HAVE_COSL 1 # define cosl _cosl #endif #if defined (_GLIBCXX_HAVE__EXPF) && ! defined (_GLIBCXX_HAVE_EXPF) # define _GLIBCXX_HAVE_EXPF 1 # define expf _expf #endif #if defined (_GLIBCXX_HAVE__EXPL) && ! defined (_GLIBCXX_HAVE_EXPL) # define _GLIBCXX_HAVE_EXPL 1 # define expl _expl #endif #if defined (_GLIBCXX_HAVE__FABSF) && ! defined (_GLIBCXX_HAVE_FABSF) # define _GLIBCXX_HAVE_FABSF 1 # define fabsf _fabsf #endif #if defined (_GLIBCXX_HAVE__FABSL) && ! defined (_GLIBCXX_HAVE_FABSL) # define _GLIBCXX_HAVE_FABSL 1 # define fabsl _fabsl #endif #if defined (_GLIBCXX_HAVE__FINITE) && ! defined (_GLIBCXX_HAVE_FINITE) # define _GLIBCXX_HAVE_FINITE 1 # define finite _finite #endif #if defined (_GLIBCXX_HAVE__FINITEF) && ! defined (_GLIBCXX_HAVE_FINITEF) # define _GLIBCXX_HAVE_FINITEF 1 # define finitef _finitef #endif #if defined (_GLIBCXX_HAVE__FINITEL) && ! defined (_GLIBCXX_HAVE_FINITEL) # define _GLIBCXX_HAVE_FINITEL 1 # define finitel _finitel #endif #if defined (_GLIBCXX_HAVE__FLOORF) && ! defined (_GLIBCXX_HAVE_FLOORF) # define _GLIBCXX_HAVE_FLOORF 1 # define floorf _floorf #endif #if defined (_GLIBCXX_HAVE__FLOORL) && ! defined (_GLIBCXX_HAVE_FLOORL) # define _GLIBCXX_HAVE_FLOORL 1 # define floorl _floorl #endif #if defined (_GLIBCXX_HAVE__FMODF) && ! defined (_GLIBCXX_HAVE_FMODF) # define _GLIBCXX_HAVE_FMODF 1 # define fmodf _fmodf #endif #if defined (_GLIBCXX_HAVE__FMODL) && ! defined (_GLIBCXX_HAVE_FMODL) # define _GLIBCXX_HAVE_FMODL 1 # define fmodl _fmodl #endif #if defined (_GLIBCXX_HAVE__FPCLASS) && ! defined (_GLIBCXX_HAVE_FPCLASS) # define _GLIBCXX_HAVE_FPCLASS 1 # define fpclass _fpclass #endif #if defined (_GLIBCXX_HAVE__FREXPF) && ! defined (_GLIBCXX_HAVE_FREXPF) # define _GLIBCXX_HAVE_FREXPF 1 # define frexpf _frexpf #endif #if defined (_GLIBCXX_HAVE__FREXPL) && ! defined (_GLIBCXX_HAVE_FREXPL) # define _GLIBCXX_HAVE_FREXPL 1 # define frexpl _frexpl #endif #if defined (_GLIBCXX_HAVE__HYPOT) && ! defined (_GLIBCXX_HAVE_HYPOT) # define _GLIBCXX_HAVE_HYPOT 1 # define hypot _hypot #endif #if defined (_GLIBCXX_HAVE__HYPOTF) && ! defined (_GLIBCXX_HAVE_HYPOTF) # define _GLIBCXX_HAVE_HYPOTF 1 # define hypotf _hypotf #endif #if defined (_GLIBCXX_HAVE__HYPOTL) && ! defined (_GLIBCXX_HAVE_HYPOTL) # define _GLIBCXX_HAVE_HYPOTL 1 # define hypotl _hypotl #endif #if defined (_GLIBCXX_HAVE__ISINF) && ! defined (_GLIBCXX_HAVE_ISINF) # define _GLIBCXX_HAVE_ISINF 1 # define isinf _isinf #endif #if defined (_GLIBCXX_HAVE__ISINFF) && ! defined (_GLIBCXX_HAVE_ISINFF) # define _GLIBCXX_HAVE_ISINFF 1 # define isinff _isinff #endif #if defined (_GLIBCXX_HAVE__ISINFL) && ! defined (_GLIBCXX_HAVE_ISINFL) # define _GLIBCXX_HAVE_ISINFL 1 # define isinfl _isinfl #endif #if defined (_GLIBCXX_HAVE__ISNAN) && ! defined (_GLIBCXX_HAVE_ISNAN) # define _GLIBCXX_HAVE_ISNAN 1 # define isnan _isnan #endif #if defined (_GLIBCXX_HAVE__ISNANF) && ! defined (_GLIBCXX_HAVE_ISNANF) # define _GLIBCXX_HAVE_ISNANF 1 # define isnanf _isnanf #endif #if defined (_GLIBCXX_HAVE__ISNANL) && ! defined (_GLIBCXX_HAVE_ISNANL) # define _GLIBCXX_HAVE_ISNANL 1 # define isnanl _isnanl #endif #if defined (_GLIBCXX_HAVE__LDEXPF) && ! defined (_GLIBCXX_HAVE_LDEXPF) # define _GLIBCXX_HAVE_LDEXPF 1 # define ldexpf _ldexpf #endif #if defined (_GLIBCXX_HAVE__LDEXPL) && ! defined (_GLIBCXX_HAVE_LDEXPL) # define _GLIBCXX_HAVE_LDEXPL 1 # define ldexpl _ldexpl #endif #if defined (_GLIBCXX_HAVE__LOG10F) && ! defined (_GLIBCXX_HAVE_LOG10F) # define _GLIBCXX_HAVE_LOG10F 1 # define log10f _log10f #endif #if defined (_GLIBCXX_HAVE__LOG10L) && ! defined (_GLIBCXX_HAVE_LOG10L) # define _GLIBCXX_HAVE_LOG10L 1 # define log10l _log10l #endif #if defined (_GLIBCXX_HAVE__LOGF) && ! defined (_GLIBCXX_HAVE_LOGF) # define _GLIBCXX_HAVE_LOGF 1 # define logf _logf #endif #if defined (_GLIBCXX_HAVE__LOGL) && ! defined (_GLIBCXX_HAVE_LOGL) # define _GLIBCXX_HAVE_LOGL 1 # define logl _logl #endif #if defined (_GLIBCXX_HAVE__MODF) && ! defined (_GLIBCXX_HAVE_MODF) # define _GLIBCXX_HAVE_MODF 1 # define modf _modf #endif #if defined (_GLIBCXX_HAVE__MODFF) && ! defined (_GLIBCXX_HAVE_MODFF) # define _GLIBCXX_HAVE_MODFF 1 # define modff _modff #endif #if defined (_GLIBCXX_HAVE__MODFL) && ! defined (_GLIBCXX_HAVE_MODFL) # define _GLIBCXX_HAVE_MODFL 1 # define modfl _modfl #endif #if defined (_GLIBCXX_HAVE__POWF) && ! defined (_GLIBCXX_HAVE_POWF) # define _GLIBCXX_HAVE_POWF 1 # define powf _powf #endif #if defined (_GLIBCXX_HAVE__POWL) && ! defined (_GLIBCXX_HAVE_POWL) # define _GLIBCXX_HAVE_POWL 1 # define powl _powl #endif #if defined (_GLIBCXX_HAVE__QFPCLASS) && ! defined (_GLIBCXX_HAVE_QFPCLASS) # define _GLIBCXX_HAVE_QFPCLASS 1 # define qfpclass _qfpclass #endif #if defined (_GLIBCXX_HAVE__SINCOS) && ! defined (_GLIBCXX_HAVE_SINCOS) # define _GLIBCXX_HAVE_SINCOS 1 # define sincos _sincos #endif #if defined (_GLIBCXX_HAVE__SINCOSF) && ! defined (_GLIBCXX_HAVE_SINCOSF) # define _GLIBCXX_HAVE_SINCOSF 1 # define sincosf _sincosf #endif #if defined (_GLIBCXX_HAVE__SINCOSL) && ! defined (_GLIBCXX_HAVE_SINCOSL) # define _GLIBCXX_HAVE_SINCOSL 1 # define sincosl _sincosl #endif #if defined (_GLIBCXX_HAVE__SINF) && ! defined (_GLIBCXX_HAVE_SINF) # define _GLIBCXX_HAVE_SINF 1 # define sinf _sinf #endif #if defined (_GLIBCXX_HAVE__SINHF) && ! defined (_GLIBCXX_HAVE_SINHF) # define _GLIBCXX_HAVE_SINHF 1 # define sinhf _sinhf #endif #if defined (_GLIBCXX_HAVE__SINHL) && ! defined (_GLIBCXX_HAVE_SINHL) # define _GLIBCXX_HAVE_SINHL 1 # define sinhl _sinhl #endif #if defined (_GLIBCXX_HAVE__SINL) && ! defined (_GLIBCXX_HAVE_SINL) # define _GLIBCXX_HAVE_SINL 1 # define sinl _sinl #endif #if defined (_GLIBCXX_HAVE__SQRTF) && ! defined (_GLIBCXX_HAVE_SQRTF) # define _GLIBCXX_HAVE_SQRTF 1 # define sqrtf _sqrtf #endif #if defined (_GLIBCXX_HAVE__SQRTL) && ! defined (_GLIBCXX_HAVE_SQRTL) # define _GLIBCXX_HAVE_SQRTL 1 # define sqrtl _sqrtl #endif #if defined (_GLIBCXX_HAVE__STRTOF) && ! defined (_GLIBCXX_HAVE_STRTOF) # define _GLIBCXX_HAVE_STRTOF 1 # define strtof _strtof #endif #if defined (_GLIBCXX_HAVE__STRTOLD) && ! defined (_GLIBCXX_HAVE_STRTOLD) # define _GLIBCXX_HAVE_STRTOLD 1 # define strtold _strtold #endif #if defined (_GLIBCXX_HAVE__TANF) && ! defined (_GLIBCXX_HAVE_TANF) # define _GLIBCXX_HAVE_TANF 1 # define tanf _tanf #endif #if defined (_GLIBCXX_HAVE__TANHF) && ! defined (_GLIBCXX_HAVE_TANHF) # define _GLIBCXX_HAVE_TANHF 1 # define tanhf _tanhf #endif #if defined (_GLIBCXX_HAVE__TANHL) && ! defined (_GLIBCXX_HAVE_TANHL) # define _GLIBCXX_HAVE_TANHL 1 # define tanhl _tanhl #endif #if defined (_GLIBCXX_HAVE__TANL) && ! defined (_GLIBCXX_HAVE_TANL) # define _GLIBCXX_HAVE_TANL 1 # define tanl _tanl #endif #endif // _GLIBCXX_CXX_CONFIG_H c++/8/x86_64-redhat-linux/32/bits/ctype_inline.h000064400000004354151027430570014655 0ustar00// Locale support -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ctype_inline.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // // ctype bits to be inlined go here. Non-inlinable (ie virtual do_*) // functions go in ctype.cc namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION bool ctype:: is(mask __m, char __c) const { return _M_table[static_cast(__c)] & __m; } const char* ctype:: is(const char* __low, const char* __high, mask* __vec) const { while (__low < __high) *__vec++ = _M_table[static_cast(*__low++)]; return __high; } const char* ctype:: scan_is(mask __m, const char* __low, const char* __high) const { while (__low < __high && !(_M_table[static_cast(*__low)] & __m)) ++__low; return __low; } const char* ctype:: scan_not(mask __m, const char* __low, const char* __high) const { while (__low < __high && (_M_table[static_cast(*__low)] & __m) != 0) ++__low; return __low; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/32/bits/gthr-single.h000064400000015230151027430570014411 0ustar00/* Threads compatibility routines for libgcc2 and libobjc. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_SINGLE_H #define _GLIBCXX_GCC_GTHR_SINGLE_H /* Just provide compatibility for mutex handling. */ typedef int __gthread_key_t; typedef int __gthread_once_t; typedef int __gthread_mutex_t; typedef int __gthread_recursive_mutex_t; #define __GTHREAD_ONCE_INIT 0 #define __GTHREAD_MUTEX_INIT 0 #define __GTHREAD_MUTEX_INIT_FUNCTION(mx) do {} while (0) #define __GTHREAD_RECURSIVE_MUTEX_INIT 0 #define _GLIBCXX_UNUSED __attribute__((__unused__)) #ifdef _LIBOBJC /* Thread local storage for a single thread */ static void *thread_local_storage = NULL; /* Backend initialization functions */ /* Initialize the threads subsystem. */ static inline int __gthread_objc_init_thread_system (void) { /* No thread support available */ return -1; } /* Close the threads subsystem. */ static inline int __gthread_objc_close_thread_system (void) { /* No thread support available */ return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ static inline objc_thread_t __gthread_objc_thread_detach (void (* func)(void *), void * arg _GLIBCXX_UNUSED) { /* No thread support available */ return NULL; } /* Set the current thread's priority. */ static inline int __gthread_objc_thread_set_priority (int priority _GLIBCXX_UNUSED) { /* No thread support available */ return -1; } /* Return the current thread's priority. */ static inline int __gthread_objc_thread_get_priority (void) { return OBJC_THREAD_INTERACTIVE_PRIORITY; } /* Yield our process time to another thread. */ static inline void __gthread_objc_thread_yield (void) { return; } /* Terminate the current thread. */ static inline int __gthread_objc_thread_exit (void) { /* No thread support available */ /* Should we really exit the program */ /* exit (&__objc_thread_exit_status); */ return -1; } /* Returns an integer value which uniquely describes a thread. */ static inline objc_thread_t __gthread_objc_thread_id (void) { /* No thread support, use 1. */ return (objc_thread_t) 1; } /* Sets the thread's local storage pointer. */ static inline int __gthread_objc_thread_set_data (void *value) { thread_local_storage = value; return 0; } /* Returns the thread's local storage pointer. */ static inline void * __gthread_objc_thread_get_data (void) { return thread_local_storage; } /* Backend mutex functions */ /* Allocate a mutex. */ static inline int __gthread_objc_mutex_allocate (objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Deallocate a mutex. */ static inline int __gthread_objc_mutex_deallocate (objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Grab a lock on a mutex. */ static inline int __gthread_objc_mutex_lock (objc_mutex_t mutex _GLIBCXX_UNUSED) { /* There can only be one thread, so we always get the lock */ return 0; } /* Try to grab a lock on a mutex. */ static inline int __gthread_objc_mutex_trylock (objc_mutex_t mutex _GLIBCXX_UNUSED) { /* There can only be one thread, so we always get the lock */ return 0; } /* Unlock the mutex */ static inline int __gthread_objc_mutex_unlock (objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Backend condition mutex functions */ /* Allocate a condition. */ static inline int __gthread_objc_condition_allocate (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } /* Deallocate a condition. */ static inline int __gthread_objc_condition_deallocate (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } /* Wait on the condition */ static inline int __gthread_objc_condition_wait (objc_condition_t condition _GLIBCXX_UNUSED, objc_mutex_t mutex _GLIBCXX_UNUSED) { return 0; } /* Wake up all threads waiting on this condition. */ static inline int __gthread_objc_condition_broadcast (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } /* Wake up one thread waiting on this condition. */ static inline int __gthread_objc_condition_signal (objc_condition_t condition _GLIBCXX_UNUSED) { return 0; } #else /* _LIBOBJC */ static inline int __gthread_active_p (void) { return 0; } static inline int __gthread_once (__gthread_once_t *__once _GLIBCXX_UNUSED, void (*__func) (void) _GLIBCXX_UNUSED) { return 0; } static inline int _GLIBCXX_UNUSED __gthread_key_create (__gthread_key_t *__key _GLIBCXX_UNUSED, void (*__func) (void *) _GLIBCXX_UNUSED) { return 0; } static int _GLIBCXX_UNUSED __gthread_key_delete (__gthread_key_t __key _GLIBCXX_UNUSED) { return 0; } static inline void * __gthread_getspecific (__gthread_key_t __key _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_setspecific (__gthread_key_t __key _GLIBCXX_UNUSED, const void *__v _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_destroy (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_lock (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_trylock (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_mutex_unlock (__gthread_mutex_t *__mutex _GLIBCXX_UNUSED) { return 0; } static inline int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_lock (__mutex); } static inline int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_trylock (__mutex); } static inline int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_unlock (__mutex); } static inline int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_destroy (__mutex); } #endif /* _LIBOBJC */ #undef _GLIBCXX_UNUSED #endif /* ! _GLIBCXX_GCC_GTHR_SINGLE_H */ c++/8/x86_64-redhat-linux/32/bits/c++allocator.h000064400000003673151027430570014447 0ustar00// Base to std::allocator -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++allocator.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _GLIBCXX_CXX_ALLOCATOR_H #define _GLIBCXX_CXX_ALLOCATOR_H 1 #include #if __cplusplus >= 201103L namespace std { /** * @brief An alias to the base class for std::allocator. * @ingroup allocators * * Used to set the std::allocator base class to * __gnu_cxx::new_allocator. * * @tparam _Tp Type of allocated object. */ template using __allocator_base = __gnu_cxx::new_allocator<_Tp>; } #else // Define new_allocator as the base class to std::allocator. # define __allocator_base __gnu_cxx::new_allocator #endif #if defined(__SANITIZE_ADDRESS__) && !defined(_GLIBCXX_SANITIZE_STD_ALLOCATOR) # define _GLIBCXX_SANITIZE_STD_ALLOCATOR 1 #endif #endif c++/8/x86_64-redhat-linux/32/bits/messages_members.h000064400000010644151027430570015513 0ustar00// std::messages implementation details, GNU version -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/messages_members.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.2.7.1.2 messages functions // // Written by Benjamin Kosnik #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Non-virtual member functions. template messages<_CharT>::messages(size_t __refs) : facet(__refs), _M_c_locale_messages(_S_get_c_locale()), _M_name_messages(_S_get_c_name()) { } template messages<_CharT>::messages(__c_locale __cloc, const char* __s, size_t __refs) : facet(__refs), _M_c_locale_messages(0), _M_name_messages(0) { if (__builtin_strcmp(__s, _S_get_c_name()) != 0) { const size_t __len = __builtin_strlen(__s) + 1; char* __tmp = new char[__len]; __builtin_memcpy(__tmp, __s, __len); _M_name_messages = __tmp; } else _M_name_messages = _S_get_c_name(); // Last to avoid leaking memory if new throws. _M_c_locale_messages = _S_clone_c_locale(__cloc); } template typename messages<_CharT>::catalog messages<_CharT>::open(const basic_string& __s, const locale& __loc, const char* __dir) const { bindtextdomain(__s.c_str(), __dir); return this->do_open(__s, __loc); } // Virtual member functions. template messages<_CharT>::~messages() { if (_M_name_messages != _S_get_c_name()) delete [] _M_name_messages; _S_destroy_c_locale(_M_c_locale_messages); } template typename messages<_CharT>::catalog messages<_CharT>::do_open(const basic_string& __s, const locale&) const { // No error checking is done, assume the catalog exists and can // be used. textdomain(__s.c_str()); return 0; } template void messages<_CharT>::do_close(catalog) const { } // messages_byname template messages_byname<_CharT>::messages_byname(const char* __s, size_t __refs) : messages<_CharT>(__refs) { if (this->_M_name_messages != locale::facet::_S_get_c_name()) { delete [] this->_M_name_messages; if (__builtin_strcmp(__s, locale::facet::_S_get_c_name()) != 0) { const size_t __len = __builtin_strlen(__s) + 1; char* __tmp = new char[__len]; __builtin_memcpy(__tmp, __s, __len); this->_M_name_messages = __tmp; } else this->_M_name_messages = locale::facet::_S_get_c_name(); } if (__builtin_strcmp(__s, "C") != 0 && __builtin_strcmp(__s, "POSIX") != 0) { this->_S_destroy_c_locale(this->_M_c_locale_messages); this->_S_create_c_locale(this->_M_c_locale_messages, __s); } } //Specializations. template<> typename messages::catalog messages::do_open(const basic_string&, const locale&) const; template<> void messages::do_close(catalog) const; #ifdef _GLIBCXX_USE_WCHAR_T template<> typename messages::catalog messages::do_open(const basic_string&, const locale&) const; template<> void messages::do_close(catalog) const; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/32/bits/cxxabi_tweaks.h000064400000004060151027430570015021 0ustar00// Control various target specific ABI tweaks. Generic version. // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cxxabi_tweaks.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{cxxabi.h} */ #ifndef _CXXABI_TWEAKS_H #define _CXXABI_TWEAKS_H 1 #ifdef __cplusplus namespace __cxxabiv1 { extern "C" { #endif // The generic ABI uses the first byte of a 64-bit guard variable. #define _GLIBCXX_GUARD_TEST(x) (*(char *) (x) != 0) #define _GLIBCXX_GUARD_SET(x) *(char *) (x) = 1 #define _GLIBCXX_GUARD_BIT __guard_test_bit (0, 1) #define _GLIBCXX_GUARD_PENDING_BIT __guard_test_bit (1, 1) #define _GLIBCXX_GUARD_WAITING_BIT __guard_test_bit (2, 1) __extension__ typedef int __guard __attribute__((mode (__DI__))); // __cxa_vec_ctor has void return type. typedef void __cxa_vec_ctor_return_type; #define _GLIBCXX_CXA_VEC_CTOR_RETURN(x) return // Constructors and destructors do not return a value. typedef void __cxa_cdtor_return_type; #ifdef __cplusplus } } // namespace __cxxabiv1 #endif #endif c++/8/x86_64-redhat-linux/32/bits/cpu_defines.h000064400000002465151027430570014460 0ustar00// Specific definitions for generic platforms -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/cpu_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_CPU_DEFINES #define _GLIBCXX_CPU_DEFINES 1 #endif c++/8/x86_64-redhat-linux/32/bits/gthr-default.h000064400000057255151027430570014571 0ustar00/* Threads compatibility routines for libgcc2 and libobjc. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_POSIX_H #define _GLIBCXX_GCC_GTHR_POSIX_H /* POSIX threads specific definitions. Easy, since the interface is just one-to-one mapping. */ #define __GTHREADS 1 #define __GTHREADS_CXX0X 1 #include #if ((defined(_LIBOBJC) || defined(_LIBOBJC_WEAK)) \ || !defined(_GTHREAD_USE_MUTEX_TIMEDLOCK)) # include # if defined(_POSIX_TIMEOUTS) && _POSIX_TIMEOUTS >= 0 # define _GTHREAD_USE_MUTEX_TIMEDLOCK 1 # else # define _GTHREAD_USE_MUTEX_TIMEDLOCK 0 # endif #endif typedef pthread_t __gthread_t; typedef pthread_key_t __gthread_key_t; typedef pthread_once_t __gthread_once_t; typedef pthread_mutex_t __gthread_mutex_t; typedef pthread_mutex_t __gthread_recursive_mutex_t; typedef pthread_cond_t __gthread_cond_t; typedef struct timespec __gthread_time_t; /* POSIX like conditional variables are supported. Please look at comments in gthr.h for details. */ #define __GTHREAD_HAS_COND 1 #define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER #define __GTHREAD_MUTEX_INIT_FUNCTION __gthread_mutex_init_function #define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT #if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER #elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) #define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP #else #define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #define __GTHREAD_COND_INIT PTHREAD_COND_INITIALIZER #define __GTHREAD_TIME_INIT {0,0} #ifdef _GTHREAD_USE_MUTEX_INIT_FUNC # undef __GTHREAD_MUTEX_INIT #endif #ifdef _GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC # undef __GTHREAD_RECURSIVE_MUTEX_INIT # undef __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION # define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function #endif #ifdef _GTHREAD_USE_COND_INIT_FUNC # undef __GTHREAD_COND_INIT # define __GTHREAD_COND_INIT_FUNCTION __gthread_cond_init_function #endif #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK # ifndef __gthrw_pragma # define __gthrw_pragma(pragma) # endif # define __gthrw2(name,name2,type) \ static __typeof(type) name __attribute__ ((__weakref__(#name2))); \ __gthrw_pragma(weak type) # define __gthrw_(name) __gthrw_ ## name #else # define __gthrw2(name,name2,type) # define __gthrw_(name) name #endif /* Typically, __gthrw_foo is a weak reference to symbol foo. */ #define __gthrw(name) __gthrw2(__gthrw_ ## name,name,name) __gthrw(pthread_once) __gthrw(pthread_getspecific) __gthrw(pthread_setspecific) __gthrw(pthread_create) __gthrw(pthread_join) __gthrw(pthread_equal) __gthrw(pthread_self) __gthrw(pthread_detach) #ifndef __BIONIC__ __gthrw(pthread_cancel) #endif __gthrw(sched_yield) __gthrw(pthread_mutex_lock) __gthrw(pthread_mutex_trylock) #if _GTHREAD_USE_MUTEX_TIMEDLOCK __gthrw(pthread_mutex_timedlock) #endif __gthrw(pthread_mutex_unlock) __gthrw(pthread_mutex_init) __gthrw(pthread_mutex_destroy) __gthrw(pthread_cond_init) __gthrw(pthread_cond_broadcast) __gthrw(pthread_cond_signal) __gthrw(pthread_cond_wait) __gthrw(pthread_cond_timedwait) __gthrw(pthread_cond_destroy) __gthrw(pthread_key_create) __gthrw(pthread_key_delete) __gthrw(pthread_mutexattr_init) __gthrw(pthread_mutexattr_settype) __gthrw(pthread_mutexattr_destroy) #if defined(_LIBOBJC) || defined(_LIBOBJC_WEAK) /* Objective-C. */ __gthrw(pthread_exit) #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(sched_get_priority_max) __gthrw(sched_get_priority_min) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ __gthrw(pthread_attr_destroy) __gthrw(pthread_attr_init) __gthrw(pthread_attr_setdetachstate) #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING __gthrw(pthread_getschedparam) __gthrw(pthread_setschedparam) #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _LIBOBJC || _LIBOBJC_WEAK */ #if __GXX_WEAK__ && _GLIBCXX_GTHREAD_USE_WEAK /* On Solaris 2.6 up to 9, the libc exposes a POSIX threads interface even if -pthreads is not specified. The functions are dummies and most return an error value. However pthread_once returns 0 without invoking the routine it is passed so we cannot pretend that the interface is active if -pthreads is not specified. On Solaris 2.5.1, the interface is not exposed at all so we need to play the usual game with weak symbols. On Solaris 10 and up, a working interface is always exposed. On FreeBSD 6 and later, libc also exposes a dummy POSIX threads interface, similar to what Solaris 2.6 up to 9 does. FreeBSD >= 700014 even provides a pthread_cancel stub in libc, which means the alternate __gthread_active_p below cannot be used there. */ #if defined(__FreeBSD__) || (defined(__sun) && defined(__svr4__)) static volatile int __gthread_active = -1; static void __gthread_trigger (void) { __gthread_active = 1; } static inline int __gthread_active_p (void) { static pthread_mutex_t __gthread_active_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t __gthread_active_once = PTHREAD_ONCE_INIT; /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; /* This test is not protected to avoid taking a lock on the main code path so every update of __gthread_active in a threaded program must be atomic with regard to the result of the test. */ if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { if (__gthrw_(pthread_once)) { /* If this really is a threaded program, then we must ensure that __gthread_active has been set to 1 before exiting this block. */ __gthrw_(pthread_mutex_lock) (&__gthread_active_mutex); __gthrw_(pthread_once) (&__gthread_active_once, __gthread_trigger); __gthrw_(pthread_mutex_unlock) (&__gthread_active_mutex); } /* Make sure we'll never enter this block again. */ if (__gthread_active < 0) __gthread_active = 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* neither FreeBSD nor Solaris */ /* For a program to be multi-threaded the only thing that it certainly must be using is pthread_create. However, there may be other libraries that intercept pthread_create with their own definitions to wrap pthreads functionality for some purpose. In those cases, pthread_create being defined might not necessarily mean that libpthread is actually linked in. For the GNU C library, we can use a known internal name. This is always available in the ABI, but no other library would define it. That is ideal, since any public pthread function might be intercepted just as pthread_create might be. __pthread_key_create is an "internal" implementation symbol, but it is part of the public exported ABI. Also, it's among the symbols that the static libpthread.a always links in whenever pthread_create is used, so there is no danger of a false negative result in any statically-linked, multi-threaded program. For others, we choose pthread_cancel as a function that seems unlikely to be redefined by an interceptor library. The bionic (Android) C library does not provide pthread_cancel, so we do use pthread_create there (and interceptor libraries lose). */ #ifdef __GLIBC__ __gthrw2(__gthrw_(__pthread_key_create), __pthread_key_create, pthread_key_create) # define GTHR_ACTIVE_PROXY __gthrw_(__pthread_key_create) #elif defined (__BIONIC__) # define GTHR_ACTIVE_PROXY __gthrw_(pthread_create) #else # define GTHR_ACTIVE_PROXY __gthrw_(pthread_cancel) #endif static inline int __gthread_active_p (void) { static void *const __gthread_active_ptr = __extension__ (void *) >HR_ACTIVE_PROXY; return __gthread_active_ptr != 0; } #endif /* FreeBSD or Solaris */ #else /* not __GXX_WEAK__ */ /* Similar to Solaris, HP-UX 11 for PA-RISC provides stubs for pthread calls in shared flavors of the HP-UX C library. Most of the stubs have no functionality. The details are described in the "libc cumulative patch" for each subversion of HP-UX 11. There are two special interfaces provided for checking whether an application is linked to a shared pthread library or not. However, these interfaces aren't available in early libpthread libraries. We also need a test that works for archive libraries. We can't use pthread_once as some libc versions call the init function. We also can't use pthread_create or pthread_attr_init as these create a thread and thereby prevent changing the default stack size. The function pthread_default_stacksize_np is available in both the archive and shared versions of libpthread. It can be used to determine the default pthread stack size. There is a stub in some shared libc versions which returns a zero size if pthreads are not active. We provide an equivalent stub to handle cases where libc doesn't provide one. */ #if defined(__hppa__) && defined(__hpux__) static volatile int __gthread_active = -1; static inline int __gthread_active_p (void) { /* Avoid reading __gthread_active twice on the main code path. */ int __gthread_active_latest_value = __gthread_active; size_t __s; if (__builtin_expect (__gthread_active_latest_value < 0, 0)) { pthread_default_stacksize_np (0, &__s); __gthread_active = __s ? 1 : 0; __gthread_active_latest_value = __gthread_active; } return __gthread_active_latest_value != 0; } #else /* not hppa-hpux */ static inline int __gthread_active_p (void) { return 1; } #endif /* hppa-hpux */ #endif /* __GXX_WEAK__ */ #ifdef _LIBOBJC /* This is the config.h file in libobjc/ */ #include #ifdef HAVE_SCHED_H # include #endif /* Key structure for maintaining thread specific storage */ static pthread_key_t _objc_thread_storage; static pthread_attr_t _objc_thread_attribs; /* Thread local storage for a single thread */ static void *thread_local_storage = NULL; /* Backend initialization functions */ /* Initialize the threads subsystem. */ static inline int __gthread_objc_init_thread_system (void) { if (__gthread_active_p ()) { /* Initialize the thread storage key. */ if (__gthrw_(pthread_key_create) (&_objc_thread_storage, NULL) == 0) { /* The normal default detach state for threads is * PTHREAD_CREATE_JOINABLE which causes threads to not die * when you think they should. */ if (__gthrw_(pthread_attr_init) (&_objc_thread_attribs) == 0 && __gthrw_(pthread_attr_setdetachstate) (&_objc_thread_attribs, PTHREAD_CREATE_DETACHED) == 0) return 0; } } return -1; } /* Close the threads subsystem. */ static inline int __gthread_objc_close_thread_system (void) { if (__gthread_active_p () && __gthrw_(pthread_key_delete) (_objc_thread_storage) == 0 && __gthrw_(pthread_attr_destroy) (&_objc_thread_attribs) == 0) return 0; return -1; } /* Backend thread functions */ /* Create a new thread of execution. */ static inline objc_thread_t __gthread_objc_thread_detach (void (*func)(void *), void *arg) { objc_thread_t thread_id; pthread_t new_thread_handle; if (!__gthread_active_p ()) return NULL; if (!(__gthrw_(pthread_create) (&new_thread_handle, &_objc_thread_attribs, (void *) func, arg))) thread_id = (objc_thread_t) new_thread_handle; else thread_id = NULL; return thread_id; } /* Set the current thread's priority. */ static inline int __gthread_objc_thread_set_priority (int priority) { if (!__gthread_active_p ()) return -1; else { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING pthread_t thread_id = __gthrw_(pthread_self) (); int policy; struct sched_param params; int priority_min, priority_max; if (__gthrw_(pthread_getschedparam) (thread_id, &policy, ¶ms) == 0) { if ((priority_max = __gthrw_(sched_get_priority_max) (policy)) == -1) return -1; if ((priority_min = __gthrw_(sched_get_priority_min) (policy)) == -1) return -1; if (priority > priority_max) priority = priority_max; else if (priority < priority_min) priority = priority_min; params.sched_priority = priority; /* * The solaris 7 and several other man pages incorrectly state that * this should be a pointer to policy but pthread.h is universally * at odds with this. */ if (__gthrw_(pthread_setschedparam) (thread_id, policy, ¶ms) == 0) return 0; } #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return -1; } } /* Return the current thread's priority. */ static inline int __gthread_objc_thread_get_priority (void) { #ifdef _POSIX_PRIORITY_SCHEDULING #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING if (__gthread_active_p ()) { int policy; struct sched_param params; if (__gthrw_(pthread_getschedparam) (__gthrw_(pthread_self) (), &policy, ¶ms) == 0) return params.sched_priority; else return -1; } else #endif /* _POSIX_THREAD_PRIORITY_SCHEDULING */ #endif /* _POSIX_PRIORITY_SCHEDULING */ return OBJC_THREAD_INTERACTIVE_PRIORITY; } /* Yield our process time to another thread. */ static inline void __gthread_objc_thread_yield (void) { if (__gthread_active_p ()) __gthrw_(sched_yield) (); } /* Terminate the current thread. */ static inline int __gthread_objc_thread_exit (void) { if (__gthread_active_p ()) /* exit the thread */ __gthrw_(pthread_exit) (&__objc_thread_exit_status); /* Failed if we reached here */ return -1; } /* Returns an integer value which uniquely describes a thread. */ static inline objc_thread_t __gthread_objc_thread_id (void) { if (__gthread_active_p ()) return (objc_thread_t) __gthrw_(pthread_self) (); else return (objc_thread_t) 1; } /* Sets the thread's local storage pointer. */ static inline int __gthread_objc_thread_set_data (void *value) { if (__gthread_active_p ()) return __gthrw_(pthread_setspecific) (_objc_thread_storage, value); else { thread_local_storage = value; return 0; } } /* Returns the thread's local storage pointer. */ static inline void * __gthread_objc_thread_get_data (void) { if (__gthread_active_p ()) return __gthrw_(pthread_getspecific) (_objc_thread_storage); else return thread_local_storage; } /* Backend mutex functions */ /* Allocate a mutex. */ static inline int __gthread_objc_mutex_allocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { mutex->backend = objc_malloc (sizeof (pthread_mutex_t)); if (__gthrw_(pthread_mutex_init) ((pthread_mutex_t *) mutex->backend, NULL)) { objc_free (mutex->backend); mutex->backend = NULL; return -1; } } return 0; } /* Deallocate a mutex. */ static inline int __gthread_objc_mutex_deallocate (objc_mutex_t mutex) { if (__gthread_active_p ()) { int count; /* * Posix Threads specifically require that the thread be unlocked * for __gthrw_(pthread_mutex_destroy) to work. */ do { count = __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend); if (count < 0) return -1; } while (count); if (__gthrw_(pthread_mutex_destroy) ((pthread_mutex_t *) mutex->backend)) return -1; objc_free (mutex->backend); mutex->backend = NULL; } return 0; } /* Grab a lock on a mutex. */ static inline int __gthread_objc_mutex_lock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_lock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Try to grab a lock on a mutex. */ static inline int __gthread_objc_mutex_trylock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_trylock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Unlock the mutex */ static inline int __gthread_objc_mutex_unlock (objc_mutex_t mutex) { if (__gthread_active_p () && __gthrw_(pthread_mutex_unlock) ((pthread_mutex_t *) mutex->backend) != 0) { return -1; } return 0; } /* Backend condition mutex functions */ /* Allocate a condition. */ static inline int __gthread_objc_condition_allocate (objc_condition_t condition) { if (__gthread_active_p ()) { condition->backend = objc_malloc (sizeof (pthread_cond_t)); if (__gthrw_(pthread_cond_init) ((pthread_cond_t *) condition->backend, NULL)) { objc_free (condition->backend); condition->backend = NULL; return -1; } } return 0; } /* Deallocate a condition. */ static inline int __gthread_objc_condition_deallocate (objc_condition_t condition) { if (__gthread_active_p ()) { if (__gthrw_(pthread_cond_destroy) ((pthread_cond_t *) condition->backend)) return -1; objc_free (condition->backend); condition->backend = NULL; } return 0; } /* Wait on the condition */ static inline int __gthread_objc_condition_wait (objc_condition_t condition, objc_mutex_t mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_wait) ((pthread_cond_t *) condition->backend, (pthread_mutex_t *) mutex->backend); else return 0; } /* Wake up all threads waiting on this condition. */ static inline int __gthread_objc_condition_broadcast (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_broadcast) ((pthread_cond_t *) condition->backend); else return 0; } /* Wake up one thread waiting on this condition. */ static inline int __gthread_objc_condition_signal (objc_condition_t condition) { if (__gthread_active_p ()) return __gthrw_(pthread_cond_signal) ((pthread_cond_t *) condition->backend); else return 0; } #else /* _LIBOBJC */ static inline int __gthread_create (__gthread_t *__threadid, void *(*__func) (void*), void *__args) { return __gthrw_(pthread_create) (__threadid, NULL, __func, __args); } static inline int __gthread_join (__gthread_t __threadid, void **__value_ptr) { return __gthrw_(pthread_join) (__threadid, __value_ptr); } static inline int __gthread_detach (__gthread_t __threadid) { return __gthrw_(pthread_detach) (__threadid); } static inline int __gthread_equal (__gthread_t __t1, __gthread_t __t2) { return __gthrw_(pthread_equal) (__t1, __t2); } static inline __gthread_t __gthread_self (void) { return __gthrw_(pthread_self) (); } static inline int __gthread_yield (void) { return __gthrw_(sched_yield) (); } static inline int __gthread_once (__gthread_once_t *__once, void (*__func) (void)) { if (__gthread_active_p ()) return __gthrw_(pthread_once) (__once, __func); else return -1; } static inline int __gthread_key_create (__gthread_key_t *__key, void (*__dtor) (void *)) { return __gthrw_(pthread_key_create) (__key, __dtor); } static inline int __gthread_key_delete (__gthread_key_t __key) { return __gthrw_(pthread_key_delete) (__key); } static inline void * __gthread_getspecific (__gthread_key_t __key) { return __gthrw_(pthread_getspecific) (__key); } static inline int __gthread_setspecific (__gthread_key_t __key, const void *__ptr) { return __gthrw_(pthread_setspecific) (__key, __ptr); } static inline void __gthread_mutex_init_function (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) __gthrw_(pthread_mutex_init) (__mutex, NULL); } static inline int __gthread_mutex_destroy (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_destroy) (__mutex); else return 0; } static inline int __gthread_mutex_lock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_lock) (__mutex); else return 0; } static inline int __gthread_mutex_trylock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_trylock) (__mutex); else return 0; } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_mutex_timedlock (__gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_timedlock) (__mutex, __abs_timeout); else return 0; } #endif static inline int __gthread_mutex_unlock (__gthread_mutex_t *__mutex) { if (__gthread_active_p ()) return __gthrw_(pthread_mutex_unlock) (__mutex); else return 0; } #if !defined( PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) \ || defined(_GTHREAD_USE_RECURSIVE_MUTEX_INIT_FUNC) static inline int __gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *__mutex) { if (__gthread_active_p ()) { pthread_mutexattr_t __attr; int __r; __r = __gthrw_(pthread_mutexattr_init) (&__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_settype) (&__attr, PTHREAD_MUTEX_RECURSIVE); if (!__r) __r = __gthrw_(pthread_mutex_init) (__mutex, &__attr); if (!__r) __r = __gthrw_(pthread_mutexattr_destroy) (&__attr); return __r; } return 0; } #endif static inline int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_lock (__mutex); } static inline int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_trylock (__mutex); } #if _GTHREAD_USE_MUTEX_TIMEDLOCK static inline int __gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthread_mutex_timedlock (__mutex, __abs_timeout); } #endif static inline int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_unlock (__mutex); } static inline int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *__mutex) { return __gthread_mutex_destroy (__mutex); } #ifdef _GTHREAD_USE_COND_INIT_FUNC static inline void __gthread_cond_init_function (__gthread_cond_t *__cond) { if (__gthread_active_p ()) __gthrw_(pthread_cond_init) (__cond, NULL); } #endif static inline int __gthread_cond_broadcast (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_broadcast) (__cond); } static inline int __gthread_cond_signal (__gthread_cond_t *__cond) { return __gthrw_(pthread_cond_signal) (__cond); } static inline int __gthread_cond_wait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex) { return __gthrw_(pthread_cond_wait) (__cond, __mutex); } static inline int __gthread_cond_timedwait (__gthread_cond_t *__cond, __gthread_mutex_t *__mutex, const __gthread_time_t *__abs_timeout) { return __gthrw_(pthread_cond_timedwait) (__cond, __mutex, __abs_timeout); } static inline int __gthread_cond_wait_recursive (__gthread_cond_t *__cond, __gthread_recursive_mutex_t *__mutex) { return __gthread_cond_wait (__cond, __mutex); } static inline int __gthread_cond_destroy (__gthread_cond_t* __cond) { return __gthrw_(pthread_cond_destroy) (__cond); } #endif /* _LIBOBJC */ #endif /* ! _GLIBCXX_GCC_GTHR_POSIX_H */ c++/8/x86_64-redhat-linux/32/bits/gthr.h000064400000012750151027430570013136 0ustar00/* Threads compatibility routines for libgcc2. */ /* Compile this one with gcc. */ /* Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see . */ #ifndef _GLIBCXX_GCC_GTHR_H #define _GLIBCXX_GCC_GTHR_H #ifndef _GLIBCXX_HIDE_EXPORTS #pragma GCC visibility push(default) #endif /* If this file is compiled with threads support, it must #define __GTHREADS 1 to indicate that threads support is present. Also it has define function int __gthread_active_p () that returns 1 if thread system is active, 0 if not. The threads interface must define the following types: __gthread_key_t __gthread_once_t __gthread_mutex_t __gthread_recursive_mutex_t The threads interface must define the following macros: __GTHREAD_ONCE_INIT to initialize __gthread_once_t __GTHREAD_MUTEX_INIT to initialize __gthread_mutex_t to get a fast non-recursive mutex. __GTHREAD_MUTEX_INIT_FUNCTION to initialize __gthread_mutex_t to get a fast non-recursive mutex. Define this to a function which looks like this: void __GTHREAD_MUTEX_INIT_FUNCTION (__gthread_mutex_t *) Some systems can't initialize a mutex without a function call. Don't define __GTHREAD_MUTEX_INIT in this case. __GTHREAD_RECURSIVE_MUTEX_INIT __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION as above, but for a recursive mutex. The threads interface must define the following static functions: int __gthread_once (__gthread_once_t *once, void (*func) ()) int __gthread_key_create (__gthread_key_t *keyp, void (*dtor) (void *)) int __gthread_key_delete (__gthread_key_t key) void *__gthread_getspecific (__gthread_key_t key) int __gthread_setspecific (__gthread_key_t key, const void *ptr) int __gthread_mutex_destroy (__gthread_mutex_t *mutex); int __gthread_recursive_mutex_destroy (__gthread_recursive_mutex_t *mutex); int __gthread_mutex_lock (__gthread_mutex_t *mutex); int __gthread_mutex_trylock (__gthread_mutex_t *mutex); int __gthread_mutex_unlock (__gthread_mutex_t *mutex); int __gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *mutex); int __gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *mutex); int __gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *mutex); The following are supported in POSIX threads only. They are required to fix a deadlock in static initialization inside libsupc++. The header file gthr-posix.h defines a symbol __GTHREAD_HAS_COND to signify that these extra features are supported. Types: __gthread_cond_t Macros: __GTHREAD_COND_INIT __GTHREAD_COND_INIT_FUNCTION Interface: int __gthread_cond_broadcast (__gthread_cond_t *cond); int __gthread_cond_wait (__gthread_cond_t *cond, __gthread_mutex_t *mutex); int __gthread_cond_wait_recursive (__gthread_cond_t *cond, __gthread_recursive_mutex_t *mutex); All functions returning int should return zero on success or the error number. If the operation is not supported, -1 is returned. If the following are also defined, you should #define __GTHREADS_CXX0X 1 to enable the c++0x thread library. Types: __gthread_t __gthread_time_t Interface: int __gthread_create (__gthread_t *thread, void *(*func) (void*), void *args); int __gthread_join (__gthread_t thread, void **value_ptr); int __gthread_detach (__gthread_t thread); int __gthread_equal (__gthread_t t1, __gthread_t t2); __gthread_t __gthread_self (void); int __gthread_yield (void); int __gthread_mutex_timedlock (__gthread_mutex_t *m, const __gthread_time_t *abs_timeout); int __gthread_recursive_mutex_timedlock (__gthread_recursive_mutex_t *m, const __gthread_time_t *abs_time); int __gthread_cond_signal (__gthread_cond_t *cond); int __gthread_cond_timedwait (__gthread_cond_t *cond, __gthread_mutex_t *mutex, const __gthread_time_t *abs_timeout); */ #if __GXX_WEAK__ /* The pe-coff weak support isn't fully compatible to ELF's weak. For static libraries it might would work, but as we need to deal with shared versions too, we disable it for mingw-targets. */ #ifdef __MINGW32__ #undef _GLIBCXX_GTHREAD_USE_WEAK #define _GLIBCXX_GTHREAD_USE_WEAK 0 #endif #ifndef _GLIBCXX_GTHREAD_USE_WEAK #define _GLIBCXX_GTHREAD_USE_WEAK 1 #endif #endif #include #ifndef _GLIBCXX_HIDE_EXPORTS #pragma GCC visibility pop #endif #endif /* ! _GLIBCXX_GCC_GTHR_H */ c++/8/x86_64-redhat-linux/32/bits/extc++.h000064400000005145151027430570013263 0ustar00// C++ includes used for precompiling extensions -*- C++ -*- // Copyright (C) 2006-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file extc++.h * This is an implementation file for a precompiled header. */ #if __cplusplus < 201103L #include #else #include #endif #include #if __cplusplus >= 201103L # include #endif #include #include #include #include #include #if __cplusplus >= 201103L # include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L # include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _GLIBCXX_HAVE_ICONV #include #include #endif c++/8/x86_64-redhat-linux/32/bits/time_members.h000064400000005554151027430570014646 0ustar00// std::time_get, std::time_put implementation, GNU version -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/time_members.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.2.5.1.2 - time_get functions // ISO C++ 14882: 22.2.5.3.2 - time_put functions // // Written by Benjamin Kosnik namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template __timepunct<_CharT>::__timepunct(size_t __refs) : facet(__refs), _M_data(0), _M_c_locale_timepunct(0), _M_name_timepunct(_S_get_c_name()) { _M_initialize_timepunct(); } template __timepunct<_CharT>::__timepunct(__cache_type* __cache, size_t __refs) : facet(__refs), _M_data(__cache), _M_c_locale_timepunct(0), _M_name_timepunct(_S_get_c_name()) { _M_initialize_timepunct(); } template __timepunct<_CharT>::__timepunct(__c_locale __cloc, const char* __s, size_t __refs) : facet(__refs), _M_data(0), _M_c_locale_timepunct(0), _M_name_timepunct(0) { if (__builtin_strcmp(__s, _S_get_c_name()) != 0) { const size_t __len = __builtin_strlen(__s) + 1; char* __tmp = new char[__len]; __builtin_memcpy(__tmp, __s, __len); _M_name_timepunct = __tmp; } else _M_name_timepunct = _S_get_c_name(); __try { _M_initialize_timepunct(__cloc); } __catch(...) { if (_M_name_timepunct != _S_get_c_name()) delete [] _M_name_timepunct; __throw_exception_again; } } template __timepunct<_CharT>::~__timepunct() { if (_M_name_timepunct != _S_get_c_name()) delete [] _M_name_timepunct; delete _M_data; _S_destroy_c_locale(_M_c_locale_timepunct); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/32/bits/atomic_word.h000064400000002756151027430570014506 0ustar00// Low-level type for atomic operations -*- C++ -*- // Copyright (C) 2004-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file atomic_word.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _GLIBCXX_ATOMIC_WORD_H #define _GLIBCXX_ATOMIC_WORD_H 1 typedef int _Atomic_word; // This is a memory order acquire fence. #define _GLIBCXX_READ_MEM_BARRIER __atomic_thread_fence (__ATOMIC_ACQUIRE) // This is a memory order release fence. #define _GLIBCXX_WRITE_MEM_BARRIER __atomic_thread_fence (__ATOMIC_RELEASE) #endif c++/8/x86_64-redhat-linux/32/bits/opt_random.h000064400000014062151027430570014332 0ustar00// Optimizations for random number functions, x86 version -*- C++ -*- // Copyright (C) 2012-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/opt_random.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{random} */ #ifndef _BITS_OPT_RANDOM_H #define _BITS_OPT_RANDOM_H 1 #ifdef __SSE3__ #include #endif #pragma GCC system_header namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION #ifdef __SSE3__ template<> template void normal_distribution:: __generate(typename normal_distribution::result_type* __f, typename normal_distribution::result_type* __t, _UniformRandomNumberGenerator& __urng, const param_type& __param) { typedef uint64_t __uctype; if (__f == __t) return; if (_M_saved_available) { _M_saved_available = false; *__f++ = _M_saved * __param.stddev() + __param.mean(); if (__f == __t) return; } constexpr uint64_t __maskval = 0xfffffffffffffull; static const __m128i __mask = _mm_set1_epi64x(__maskval); static const __m128i __two = _mm_set1_epi64x(0x4000000000000000ull); static const __m128d __three = _mm_set1_pd(3.0); const __m128d __av = _mm_set1_pd(__param.mean()); const __uctype __urngmin = __urng.min(); const __uctype __urngmax = __urng.max(); const __uctype __urngrange = __urngmax - __urngmin; const __uctype __uerngrange = __urngrange + 1; while (__f + 1 < __t) { double __le; __m128d __x; do { union { __m128i __i; __m128d __d; } __v; if (__urngrange > __maskval) { if (__detail::_Power_of_2(__uerngrange)) __v.__i = _mm_and_si128(_mm_set_epi64x(__urng(), __urng()), __mask); else { const __uctype __uerange = __maskval + 1; const __uctype __scaling = __urngrange / __uerange; const __uctype __past = __uerange * __scaling; uint64_t __v1; do __v1 = __uctype(__urng()) - __urngmin; while (__v1 >= __past); __v1 /= __scaling; uint64_t __v2; do __v2 = __uctype(__urng()) - __urngmin; while (__v2 >= __past); __v2 /= __scaling; __v.__i = _mm_set_epi64x(__v1, __v2); } } else if (__urngrange == __maskval) __v.__i = _mm_set_epi64x(__urng(), __urng()); else if ((__urngrange + 2) * __urngrange >= __maskval && __detail::_Power_of_2(__uerngrange)) { uint64_t __v1 = __urng() * __uerngrange + __urng(); uint64_t __v2 = __urng() * __uerngrange + __urng(); __v.__i = _mm_and_si128(_mm_set_epi64x(__v1, __v2), __mask); } else { size_t __nrng = 2; __uctype __high = __maskval / __uerngrange / __uerngrange; while (__high > __uerngrange) { ++__nrng; __high /= __uerngrange; } const __uctype __highrange = __high + 1; const __uctype __scaling = __urngrange / __highrange; const __uctype __past = __highrange * __scaling; __uctype __tmp; uint64_t __v1; do { do __tmp = __uctype(__urng()) - __urngmin; while (__tmp >= __past); __v1 = __tmp / __scaling; for (size_t __cnt = 0; __cnt < __nrng; ++__cnt) { __tmp = __v1; __v1 *= __uerngrange; __v1 += __uctype(__urng()) - __urngmin; } } while (__v1 > __maskval || __v1 < __tmp); uint64_t __v2; do { do __tmp = __uctype(__urng()) - __urngmin; while (__tmp >= __past); __v2 = __tmp / __scaling; for (size_t __cnt = 0; __cnt < __nrng; ++__cnt) { __tmp = __v2; __v2 *= __uerngrange; __v2 += __uctype(__urng()) - __urngmin; } } while (__v2 > __maskval || __v2 < __tmp); __v.__i = _mm_set_epi64x(__v1, __v2); } __v.__i = _mm_or_si128(__v.__i, __two); __x = _mm_sub_pd(__v.__d, __three); __m128d __m = _mm_mul_pd(__x, __x); __le = _mm_cvtsd_f64(_mm_hadd_pd (__m, __m)); } while (__le == 0.0 || __le >= 1.0); double __mult = (std::sqrt(-2.0 * std::log(__le) / __le) * __param.stddev()); __x = _mm_add_pd(_mm_mul_pd(__x, _mm_set1_pd(__mult)), __av); _mm_storeu_pd(__f, __x); __f += 2; } if (__f != __t) { result_type __x, __y, __r2; __detail::_Adaptor<_UniformRandomNumberGenerator, result_type> __aurng(__urng); do { __x = result_type(2.0) * __aurng() - 1.0; __y = result_type(2.0) * __aurng() - 1.0; __r2 = __x * __x + __y * __y; } while (__r2 > 1.0 || __r2 == 0.0); const result_type __mult = std::sqrt(-2 * std::log(__r2) / __r2); _M_saved = __x * __mult; _M_saved_available = true; *__f = __y * __mult * __param.stddev() + __param.mean(); } } #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _BITS_OPT_RANDOM_H c++/8/x86_64-redhat-linux/32/bits/c++locale.h000064400000006353151027430570013724 0ustar00// Wrapper for underlying C-language localization -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/c++locale.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.8 Standard locale categories. // // Written by Benjamin Kosnik #ifndef _GLIBCXX_CXX_LOCALE_H #define _GLIBCXX_CXX_LOCALE_H 1 #pragma GCC system_header #include #define _GLIBCXX_C_LOCALE_GNU 1 #define _GLIBCXX_NUM_CATEGORIES 6 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION extern "C" __typeof(uselocale) __uselocale; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION typedef __locale_t __c_locale; // Convert numeric value of type double and long double to string and // return length of string. If vsnprintf is available use it, otherwise // fall back to the unsafe vsprintf which, in general, can be dangerous // and should be avoided. inline int __convert_from_v(const __c_locale& __cloc __attribute__ ((__unused__)), char* __out, const int __size __attribute__ ((__unused__)), const char* __fmt, ...) { #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) __c_locale __old = __gnu_cxx::__uselocale(__cloc); #else char* __old = std::setlocale(LC_NUMERIC, 0); char* __sav = 0; if (__builtin_strcmp(__old, "C")) { const size_t __len = __builtin_strlen(__old) + 1; __sav = new char[__len]; __builtin_memcpy(__sav, __old, __len); std::setlocale(LC_NUMERIC, "C"); } #endif __builtin_va_list __args; __builtin_va_start(__args, __fmt); #if _GLIBCXX_USE_C99_STDIO const int __ret = __builtin_vsnprintf(__out, __size, __fmt, __args); #else const int __ret = __builtin_vsprintf(__out, __fmt, __args); #endif __builtin_va_end(__args); #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) __gnu_cxx::__uselocale(__old); #else if (__sav) { std::setlocale(LC_NUMERIC, __sav); delete [] __sav; } #endif return __ret; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/32/bits/error_constants.h000064400000012067151027430570015420 0ustar00// Specific definitions for generic platforms -*- C++ -*- // Copyright (C) 2007-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/error_constants.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{system_error} */ #ifndef _GLIBCXX_ERROR_CONSTANTS #define _GLIBCXX_ERROR_CONSTANTS 1 #include #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION enum class errc { address_family_not_supported = EAFNOSUPPORT, address_in_use = EADDRINUSE, address_not_available = EADDRNOTAVAIL, already_connected = EISCONN, argument_list_too_long = E2BIG, argument_out_of_domain = EDOM, bad_address = EFAULT, bad_file_descriptor = EBADF, #ifdef _GLIBCXX_HAVE_EBADMSG bad_message = EBADMSG, #endif broken_pipe = EPIPE, connection_aborted = ECONNABORTED, connection_already_in_progress = EALREADY, connection_refused = ECONNREFUSED, connection_reset = ECONNRESET, cross_device_link = EXDEV, destination_address_required = EDESTADDRREQ, device_or_resource_busy = EBUSY, directory_not_empty = ENOTEMPTY, executable_format_error = ENOEXEC, file_exists = EEXIST, file_too_large = EFBIG, filename_too_long = ENAMETOOLONG, function_not_supported = ENOSYS, host_unreachable = EHOSTUNREACH, #ifdef _GLIBCXX_HAVE_EIDRM identifier_removed = EIDRM, #endif illegal_byte_sequence = EILSEQ, inappropriate_io_control_operation = ENOTTY, interrupted = EINTR, invalid_argument = EINVAL, invalid_seek = ESPIPE, io_error = EIO, is_a_directory = EISDIR, message_size = EMSGSIZE, network_down = ENETDOWN, network_reset = ENETRESET, network_unreachable = ENETUNREACH, no_buffer_space = ENOBUFS, no_child_process = ECHILD, #ifdef _GLIBCXX_HAVE_ENOLINK no_link = ENOLINK, #endif no_lock_available = ENOLCK, #ifdef _GLIBCXX_HAVE_ENODATA no_message_available = ENODATA, #endif no_message = ENOMSG, no_protocol_option = ENOPROTOOPT, no_space_on_device = ENOSPC, #ifdef _GLIBCXX_HAVE_ENOSR no_stream_resources = ENOSR, #endif no_such_device_or_address = ENXIO, no_such_device = ENODEV, no_such_file_or_directory = ENOENT, no_such_process = ESRCH, not_a_directory = ENOTDIR, not_a_socket = ENOTSOCK, #ifdef _GLIBCXX_HAVE_ENOSTR not_a_stream = ENOSTR, #endif not_connected = ENOTCONN, not_enough_memory = ENOMEM, #ifdef _GLIBCXX_HAVE_ENOTSUP not_supported = ENOTSUP, #endif #ifdef _GLIBCXX_HAVE_ECANCELED operation_canceled = ECANCELED, #endif operation_in_progress = EINPROGRESS, operation_not_permitted = EPERM, operation_not_supported = EOPNOTSUPP, operation_would_block = EWOULDBLOCK, #ifdef _GLIBCXX_HAVE_EOWNERDEAD owner_dead = EOWNERDEAD, #endif permission_denied = EACCES, #ifdef _GLIBCXX_HAVE_EPROTO protocol_error = EPROTO, #endif protocol_not_supported = EPROTONOSUPPORT, read_only_file_system = EROFS, resource_deadlock_would_occur = EDEADLK, resource_unavailable_try_again = EAGAIN, result_out_of_range = ERANGE, #ifdef _GLIBCXX_HAVE_ENOTRECOVERABLE state_not_recoverable = ENOTRECOVERABLE, #endif #ifdef _GLIBCXX_HAVE_ETIME stream_timeout = ETIME, #endif #ifdef _GLIBCXX_HAVE_ETXTBSY text_file_busy = ETXTBSY, #endif timed_out = ETIMEDOUT, too_many_files_open_in_system = ENFILE, too_many_files_open = EMFILE, too_many_links = EMLINK, too_many_symbolic_link_levels = ELOOP, #ifdef _GLIBCXX_HAVE_EOVERFLOW value_too_large = EOVERFLOW, #endif wrong_protocol_type = EPROTOTYPE }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/32/bits/os_defines.h000064400000003727151027430570014314 0ustar00// Specific definitions for GNU/Linux -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/os_defines.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{iosfwd} */ #ifndef _GLIBCXX_OS_DEFINES #define _GLIBCXX_OS_DEFINES 1 // System-specific #define, typedefs, corrections, etc, go here. This // file will come before all others. // This keeps isanum, et al from being propagated as macros. #define __NO_CTYPE 1 #include // Provide a declaration for the possibly deprecated gets function, as // glibc 2.15 and later does not declare gets for ISO C11 when // __GNU_SOURCE is defined. #if __GLIBC_PREREQ(2,15) && defined(_GNU_SOURCE) # undef _GLIBCXX_HAVE_GETS #endif // Glibc 2.23 removed the obsolete isinf and isnan declarations. Check the // version dynamically in case it has changed since libstdc++ was configured. #define _GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC __GLIBC_PREREQ(2,23) #endif c++/8/x86_64-redhat-linux/32/bits/ctype_base.h000064400000004414151027430570014306 0ustar00// Locale support -*- C++ -*- // Copyright (C) 1997-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file bits/ctype_base.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{locale} */ // // ISO C++ 14882: 22.1 Locales // // Information as gleaned from /usr/include/ctype.h namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// @brief Base class for ctype. struct ctype_base { // Non-standard typedefs. typedef const int* __to_type; // NB: Offsets into ctype::_M_table force a particular size // on the mask type. Because of this, we don't use an enum. typedef unsigned short mask; static const mask upper = _ISupper; static const mask lower = _ISlower; static const mask alpha = _ISalpha; static const mask digit = _ISdigit; static const mask xdigit = _ISxdigit; static const mask space = _ISspace; static const mask print = _ISprint; static const mask graph = _ISalpha | _ISdigit | _ISpunct; static const mask cntrl = _IScntrl; static const mask punct = _ISpunct; static const mask alnum = _ISalpha | _ISdigit; #if __cplusplus >= 201103L static const mask blank = _ISblank; #endif }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace c++/8/x86_64-redhat-linux/32/bits/basic_file.h000064400000006553151027430570014256 0ustar00// Wrapper of C-language FILE struct -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // // ISO C++ 14882: 27.8 File-based streams // /** @file bits/basic_file.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ios} */ #ifndef _GLIBCXX_BASIC_FILE_STDIO_H #define _GLIBCXX_BASIC_FILE_STDIO_H 1 #pragma GCC system_header #include #include // for __c_lock and __c_file #include // for swap #include namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Generic declaration. template class __basic_file; // Specialization. template<> class __basic_file { // Underlying data source/sink. __c_file* _M_cfile; // True iff we opened _M_cfile, and thus must close it ourselves. bool _M_cfile_created; public: __basic_file(__c_lock* __lock = 0) throw (); #if __cplusplus >= 201103L __basic_file(__basic_file&& __rv, __c_lock* = 0) noexcept : _M_cfile(__rv._M_cfile), _M_cfile_created(__rv._M_cfile_created) { __rv._M_cfile = nullptr; __rv._M_cfile_created = false; } __basic_file& operator=(const __basic_file&) = delete; __basic_file& operator=(__basic_file&&) = delete; void swap(__basic_file& __f) noexcept { std::swap(_M_cfile, __f._M_cfile); std::swap(_M_cfile_created, __f._M_cfile_created); } #endif __basic_file* open(const char* __name, ios_base::openmode __mode, int __prot = 0664); __basic_file* sys_open(__c_file* __file, ios_base::openmode); __basic_file* sys_open(int __fd, ios_base::openmode __mode) throw (); __basic_file* close(); _GLIBCXX_PURE bool is_open() const throw (); _GLIBCXX_PURE int fd() throw (); _GLIBCXX_PURE __c_file* file() throw (); ~__basic_file(); streamsize xsputn(const char* __s, streamsize __n); streamsize xsputn_2(const char* __s1, streamsize __n1, const char* __s2, streamsize __n2); streamsize xsgetn(char* __s, streamsize __n); streamoff seekoff(streamoff __off, ios_base::seekdir __way) throw (); int sync(); streamsize showmanyc(); }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/x86_64-redhat-linux/32/bits/stdtr1c++.h000064400000003315151027430570013701 0ustar00// C++ includes used for precompiling TR1 -*- C++ -*- // Copyright (C) 2006-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file stdtr1c++.h * This is an implementation file for a precompiled header. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include c++/8/x86_64-redhat-linux/32/ext/opt_random.h000064400000011224151027430570014166 0ustar00// Optimizations for random number extensions, x86 version -*- C++ -*- // Copyright (C) 2012-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/random.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/random} */ #ifndef _EXT_OPT_RANDOM_H #define _EXT_OPT_RANDOM_H 1 #pragma GCC system_header #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #ifdef __SSE2__ namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace { template inline __m128i __sse2_recursion(__m128i __a, __m128i __b, __m128i __c, __m128i __d) { __m128i __y = _mm_srli_epi32(__b, __sr1); __m128i __z = _mm_srli_si128(__c, __sr2); __m128i __v = _mm_slli_epi32(__d, __sl1); __z = _mm_xor_si128(__z, __a); __z = _mm_xor_si128(__z, __v); __m128i __x = _mm_slli_si128(__a, __sl2); __y = _mm_and_si128(__y, _mm_set_epi32(__msk4, __msk3, __msk2, __msk1)); __z = _mm_xor_si128(__z, __x); return _mm_xor_si128(__z, __y); } } #define _GLIBCXX_OPT_HAVE_RANDOM_SFMT_GEN_READ 1 template void simd_fast_mersenne_twister_engine<_UIntType, __m, __pos1, __sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4, __parity1, __parity2, __parity3, __parity4>:: _M_gen_rand(void) { __m128i __r1 = _mm_load_si128(&_M_state[_M_nstate - 2]); __m128i __r2 = _mm_load_si128(&_M_state[_M_nstate - 1]); size_t __i; for (__i = 0; __i < _M_nstate - __pos1; ++__i) { __m128i __r = __sse2_recursion<__sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4> (_M_state[__i], _M_state[__i + __pos1], __r1, __r2); _mm_store_si128(&_M_state[__i], __r); __r1 = __r2; __r2 = __r; } for (; __i < _M_nstate; ++__i) { __m128i __r = __sse2_recursion<__sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4> (_M_state[__i], _M_state[__i + __pos1 - _M_nstate], __r1, __r2); _mm_store_si128(&_M_state[__i], __r); __r1 = __r2; __r2 = __r; } _M_pos = 0; } #define _GLIBCXX_OPT_HAVE_RANDOM_SFMT_OPERATOREQUAL 1 template bool operator==(const __gnu_cxx::simd_fast_mersenne_twister_engine<_UIntType, __m, __pos1, __sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4, __parity1, __parity2, __parity3, __parity4>& __lhs, const __gnu_cxx::simd_fast_mersenne_twister_engine<_UIntType, __m, __pos1, __sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4, __parity1, __parity2, __parity3, __parity4>& __rhs) { __m128i __res = _mm_cmpeq_epi8(__lhs._M_state[0], __rhs._M_state[0]); for (size_t __i = 1; __i < __lhs._M_nstate; ++__i) __res = _mm_and_si128(__res, _mm_cmpeq_epi8(__lhs._M_state[__i], __rhs._M_state[__i])); return (_mm_movemask_epi8(__res) == 0xffff && __lhs._M_pos == __rhs._M_pos); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // __SSE2__ #endif // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #endif // _EXT_OPT_RANDOM_H c++/8/x86_64-redhat-linux/ext/opt_random.h000064400000011224151027430570013742 0ustar00// Optimizations for random number extensions, x86 version -*- C++ -*- // Copyright (C) 2012-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/random.tcc * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/random} */ #ifndef _EXT_OPT_RANDOM_H #define _EXT_OPT_RANDOM_H 1 #pragma GCC system_header #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #ifdef __SSE2__ namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace { template inline __m128i __sse2_recursion(__m128i __a, __m128i __b, __m128i __c, __m128i __d) { __m128i __y = _mm_srli_epi32(__b, __sr1); __m128i __z = _mm_srli_si128(__c, __sr2); __m128i __v = _mm_slli_epi32(__d, __sl1); __z = _mm_xor_si128(__z, __a); __z = _mm_xor_si128(__z, __v); __m128i __x = _mm_slli_si128(__a, __sl2); __y = _mm_and_si128(__y, _mm_set_epi32(__msk4, __msk3, __msk2, __msk1)); __z = _mm_xor_si128(__z, __x); return _mm_xor_si128(__z, __y); } } #define _GLIBCXX_OPT_HAVE_RANDOM_SFMT_GEN_READ 1 template void simd_fast_mersenne_twister_engine<_UIntType, __m, __pos1, __sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4, __parity1, __parity2, __parity3, __parity4>:: _M_gen_rand(void) { __m128i __r1 = _mm_load_si128(&_M_state[_M_nstate - 2]); __m128i __r2 = _mm_load_si128(&_M_state[_M_nstate - 1]); size_t __i; for (__i = 0; __i < _M_nstate - __pos1; ++__i) { __m128i __r = __sse2_recursion<__sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4> (_M_state[__i], _M_state[__i + __pos1], __r1, __r2); _mm_store_si128(&_M_state[__i], __r); __r1 = __r2; __r2 = __r; } for (; __i < _M_nstate; ++__i) { __m128i __r = __sse2_recursion<__sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4> (_M_state[__i], _M_state[__i + __pos1 - _M_nstate], __r1, __r2); _mm_store_si128(&_M_state[__i], __r); __r1 = __r2; __r2 = __r; } _M_pos = 0; } #define _GLIBCXX_OPT_HAVE_RANDOM_SFMT_OPERATOREQUAL 1 template bool operator==(const __gnu_cxx::simd_fast_mersenne_twister_engine<_UIntType, __m, __pos1, __sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4, __parity1, __parity2, __parity3, __parity4>& __lhs, const __gnu_cxx::simd_fast_mersenne_twister_engine<_UIntType, __m, __pos1, __sl1, __sl2, __sr1, __sr2, __msk1, __msk2, __msk3, __msk4, __parity1, __parity2, __parity3, __parity4>& __rhs) { __m128i __res = _mm_cmpeq_epi8(__lhs._M_state[0], __rhs._M_state[0]); for (size_t __i = 1; __i < __lhs._M_nstate; ++__i) __res = _mm_and_si128(__res, _mm_cmpeq_epi8(__lhs._M_state[__i], __rhs._M_state[__i])); return (_mm_movemask_epi8(__res) == 0xffff && __lhs._M_pos == __rhs._M_pos); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // __SSE2__ #endif // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #endif // _EXT_OPT_RANDOM_H c++/8/ext/throw_allocator.h000064400000057731151027430570011460 0ustar00// -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** @file ext/throw_allocator.h * This file is a GNU extension to the Standard C++ Library. * * Contains two exception-generating types (throw_value, throw_allocator) * intended to be used as value and allocator types while testing * exception safety in templatized containers and algorithms. The * allocator has additional log and debug features. The exception * generated is of type forced_exception_error. */ #ifndef _THROW_ALLOCATOR_H #define _THROW_ALLOCATOR_H 1 #include #include #include #include #include #include #include #include #include #if __cplusplus >= 201103L # include # include #else # include # include #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @brief Thown by exception safety machinery. * @ingroup exceptions */ struct forced_error : public std::exception { }; // Substitute for forced_error object when -fno-exceptions. inline void __throw_forced_error() { _GLIBCXX_THROW_OR_ABORT(forced_error()); } /** * @brief Base class for checking address and label information * about allocations. Create a std::map between the allocated * address (void*) and a datum for annotations, which are a pair of * numbers corresponding to label and allocated size. */ struct annotate_base { annotate_base() { label(); map_alloc(); } static void set_label(size_t l) { label() = l; } static size_t get_label() { return label(); } void insert(void* p, size_t size) { if (!p) { std::string error("annotate_base::insert null insert!\n"); log_to_string(error, make_entry(p, size)); std::__throw_logic_error(error.c_str()); } const_iterator found = map_alloc().find(p); if (found != map_alloc().end()) { std::string error("annotate_base::insert double insert!\n"); log_to_string(error, make_entry(p, size)); log_to_string(error, *found); std::__throw_logic_error(error.c_str()); } map_alloc().insert(make_entry(p, size)); } void erase(void* p, size_t size) { check_allocated(p, size); map_alloc().erase(p); } #if __cplusplus >= 201103L void insert_construct(void* p) { if (!p) { std::string error("annotate_base::insert_construct null!\n"); std::__throw_logic_error(error.c_str()); } auto found = map_construct().find(p); if (found != map_construct().end()) { std::string error("annotate_base::insert_construct double insert!\n"); log_to_string(error, std::make_pair(p, get_label())); log_to_string(error, *found); std::__throw_logic_error(error.c_str()); } map_construct().insert(std::make_pair(p, get_label())); } void erase_construct(void* p) { check_constructed(p); map_construct().erase(p); } #endif // See if a particular address and allocation size has been saved. inline void check_allocated(void* p, size_t size) { const_iterator found = map_alloc().find(p); if (found == map_alloc().end()) { std::string error("annotate_base::check_allocated by value " "null erase!\n"); log_to_string(error, make_entry(p, size)); std::__throw_logic_error(error.c_str()); } if (found->second.second != size) { std::string error("annotate_base::check_allocated by value " "wrong-size erase!\n"); log_to_string(error, make_entry(p, size)); log_to_string(error, *found); std::__throw_logic_error(error.c_str()); } } // See if a given label has been allocated. inline void check(size_t label) { std::string found; { const_iterator beg = map_alloc().begin(); const_iterator end = map_alloc().end(); while (beg != end) { if (beg->second.first == label) log_to_string(found, *beg); ++beg; } } #if __cplusplus >= 201103L { auto beg = map_construct().begin(); auto end = map_construct().end(); while (beg != end) { if (beg->second == label) log_to_string(found, *beg); ++beg; } } #endif if (!found.empty()) { std::string error("annotate_base::check by label\n"); error += found; std::__throw_logic_error(error.c_str()); } } // See if there is anything left allocated or constructed. inline static void check() { std::string found; { const_iterator beg = map_alloc().begin(); const_iterator end = map_alloc().end(); while (beg != end) { log_to_string(found, *beg); ++beg; } } #if __cplusplus >= 201103L { auto beg = map_construct().begin(); auto end = map_construct().end(); while (beg != end) { log_to_string(found, *beg); ++beg; } } #endif if (!found.empty()) { std::string error("annotate_base::check \n"); error += found; std::__throw_logic_error(error.c_str()); } } #if __cplusplus >= 201103L inline void check_constructed(void* p) { auto found = map_construct().find(p); if (found == map_construct().end()) { std::string error("annotate_base::check_constructed not " "constructed!\n"); log_to_string(error, std::make_pair(p, get_label())); std::__throw_logic_error(error.c_str()); } } inline void check_constructed(size_t label) { auto beg = map_construct().begin(); auto end = map_construct().end(); std::string found; while (beg != end) { if (beg->second == label) log_to_string(found, *beg); ++beg; } if (!found.empty()) { std::string error("annotate_base::check_constructed by label\n"); error += found; std::__throw_logic_error(error.c_str()); } } #endif private: typedef std::pair data_type; typedef std::map map_alloc_type; typedef map_alloc_type::value_type entry_type; typedef map_alloc_type::const_iterator const_iterator; typedef map_alloc_type::const_reference const_reference; #if __cplusplus >= 201103L typedef std::map map_construct_type; #endif friend std::ostream& operator<<(std::ostream&, const annotate_base&); entry_type make_entry(void* p, size_t size) { return std::make_pair(p, data_type(get_label(), size)); } static void log_to_string(std::string& s, const_reference ref) { char buf[40]; const char tab('\t'); s += "label: "; unsigned long l = static_cast(ref.second.first); __builtin_sprintf(buf, "%lu", l); s += buf; s += tab; s += "size: "; l = static_cast(ref.second.second); __builtin_sprintf(buf, "%lu", l); s += buf; s += tab; s += "address: "; __builtin_sprintf(buf, "%p", ref.first); s += buf; s += '\n'; } #if __cplusplus >= 201103L static void log_to_string(std::string& s, const std::pair& ref) { char buf[40]; const char tab('\t'); s += "label: "; unsigned long l = static_cast(ref.second); __builtin_sprintf(buf, "%lu", l); s += buf; s += tab; s += "address: "; __builtin_sprintf(buf, "%p", ref.first); s += buf; s += '\n'; } #endif static size_t& label() { static size_t _S_label(std::numeric_limits::max()); return _S_label; } static map_alloc_type& map_alloc() { static map_alloc_type _S_map; return _S_map; } #if __cplusplus >= 201103L static map_construct_type& map_construct() { static map_construct_type _S_map; return _S_map; } #endif }; inline std::ostream& operator<<(std::ostream& os, const annotate_base& __b) { std::string error; typedef annotate_base base_type; { base_type::const_iterator beg = __b.map_alloc().begin(); base_type::const_iterator end = __b.map_alloc().end(); for (; beg != end; ++beg) __b.log_to_string(error, *beg); } #if __cplusplus >= 201103L { auto beg = __b.map_construct().begin(); auto end = __b.map_construct().end(); for (; beg != end; ++beg) __b.log_to_string(error, *beg); } #endif return os << error; } /** * @brief Base struct for condition policy. * * Requires a public member function with the signature * void throw_conditionally() */ struct condition_base { virtual ~condition_base() { }; }; /** * @brief Base class for incremental control and throw. */ struct limit_condition : public condition_base { // Scope-level adjustor objects: set limit for throw at the // beginning of a scope block, and restores to previous limit when // object is destroyed on exiting the block. struct adjustor_base { private: const size_t _M_orig; public: adjustor_base() : _M_orig(limit()) { } virtual ~adjustor_base() { set_limit(_M_orig); } }; /// Never enter the condition. struct never_adjustor : public adjustor_base { never_adjustor() { set_limit(std::numeric_limits::max()); } }; /// Always enter the condition. struct always_adjustor : public adjustor_base { always_adjustor() { set_limit(count()); } }; /// Enter the nth condition. struct limit_adjustor : public adjustor_base { limit_adjustor(const size_t __l) { set_limit(__l); } }; // Increment _S_count every time called. // If _S_count matches the limit count, throw. static void throw_conditionally() { if (count() == limit()) __throw_forced_error(); ++count(); } static size_t& count() { static size_t _S_count(0); return _S_count; } static size_t& limit() { static size_t _S_limit(std::numeric_limits::max()); return _S_limit; } // Zero the throw counter, set limit to argument. static void set_limit(const size_t __l) { limit() = __l; count() = 0; } }; /** * @brief Base class for random probability control and throw. */ struct random_condition : public condition_base { // Scope-level adjustor objects: set probability for throw at the // beginning of a scope block, and restores to previous // probability when object is destroyed on exiting the block. struct adjustor_base { private: const double _M_orig; public: adjustor_base() : _M_orig(probability()) { } virtual ~adjustor_base() { set_probability(_M_orig); } }; /// Group condition. struct group_adjustor : public adjustor_base { group_adjustor(size_t size) { set_probability(1 - std::pow(double(1 - probability()), double(0.5 / (size + 1)))); } }; /// Never enter the condition. struct never_adjustor : public adjustor_base { never_adjustor() { set_probability(0); } }; /// Always enter the condition. struct always_adjustor : public adjustor_base { always_adjustor() { set_probability(1); } }; random_condition() { probability(); engine(); } static void set_probability(double __p) { probability() = __p; } static void throw_conditionally() { if (generate() < probability()) __throw_forced_error(); } void seed(unsigned long __s) { engine().seed(__s); } private: #if __cplusplus >= 201103L typedef std::uniform_real_distribution distribution_type; typedef std::mt19937 engine_type; #else typedef std::tr1::uniform_real distribution_type; typedef std::tr1::mt19937 engine_type; #endif static double generate() { #if __cplusplus >= 201103L const distribution_type distribution(0, 1); static auto generator = std::bind(distribution, engine()); #else // Use variate_generator to get normalized results. typedef std::tr1::variate_generator gen_t; distribution_type distribution(0, 1); static gen_t generator(engine(), distribution); #endif double random = generator(); if (random < distribution.min() || random > distribution.max()) { std::string __s("random_condition::generate"); __s += "\n"; __s += "random number generated is: "; char buf[40]; __builtin_sprintf(buf, "%f", random); __s += buf; std::__throw_out_of_range(__s.c_str()); } return random; } static double& probability() { static double _S_p; return _S_p; } static engine_type& engine() { static engine_type _S_e; return _S_e; } }; /** * @brief Class with exception generation control. Intended to be * used as a value_type in templatized code. * * Note: Destructor not allowed to throw. */ template struct throw_value_base : public _Cond { typedef _Cond condition_type; using condition_type::throw_conditionally; std::size_t _M_i; #ifndef _GLIBCXX_IS_AGGREGATE throw_value_base() : _M_i(0) { throw_conditionally(); } throw_value_base(const throw_value_base& __v) : _M_i(__v._M_i) { throw_conditionally(); } #if __cplusplus >= 201103L // Shall not throw. throw_value_base(throw_value_base&&) = default; #endif explicit throw_value_base(const std::size_t __i) : _M_i(__i) { throw_conditionally(); } #endif throw_value_base& operator=(const throw_value_base& __v) { throw_conditionally(); _M_i = __v._M_i; return *this; } #if __cplusplus >= 201103L // Shall not throw. throw_value_base& operator=(throw_value_base&&) = default; #endif throw_value_base& operator++() { throw_conditionally(); ++_M_i; return *this; } }; template inline void swap(throw_value_base<_Cond>& __a, throw_value_base<_Cond>& __b) { typedef throw_value_base<_Cond> throw_value; throw_value::throw_conditionally(); throw_value orig(__a); __a = __b; __b = orig; } // General instantiable types requirements. template inline bool operator==(const throw_value_base<_Cond>& __a, const throw_value_base<_Cond>& __b) { typedef throw_value_base<_Cond> throw_value; throw_value::throw_conditionally(); bool __ret = __a._M_i == __b._M_i; return __ret; } template inline bool operator<(const throw_value_base<_Cond>& __a, const throw_value_base<_Cond>& __b) { typedef throw_value_base<_Cond> throw_value; throw_value::throw_conditionally(); bool __ret = __a._M_i < __b._M_i; return __ret; } // Numeric algorithms instantiable types requirements. template inline throw_value_base<_Cond> operator+(const throw_value_base<_Cond>& __a, const throw_value_base<_Cond>& __b) { typedef throw_value_base<_Cond> throw_value; throw_value::throw_conditionally(); throw_value __ret(__a._M_i + __b._M_i); return __ret; } template inline throw_value_base<_Cond> operator-(const throw_value_base<_Cond>& __a, const throw_value_base<_Cond>& __b) { typedef throw_value_base<_Cond> throw_value; throw_value::throw_conditionally(); throw_value __ret(__a._M_i - __b._M_i); return __ret; } template inline throw_value_base<_Cond> operator*(const throw_value_base<_Cond>& __a, const throw_value_base<_Cond>& __b) { typedef throw_value_base<_Cond> throw_value; throw_value::throw_conditionally(); throw_value __ret(__a._M_i * __b._M_i); return __ret; } /// Type throwing via limit condition. struct throw_value_limit : public throw_value_base { typedef throw_value_base base_type; #ifndef _GLIBCXX_IS_AGGREGATE throw_value_limit() { } throw_value_limit(const throw_value_limit& __other) : base_type(__other._M_i) { } #if __cplusplus >= 201103L throw_value_limit(throw_value_limit&&) = default; #endif explicit throw_value_limit(const std::size_t __i) : base_type(__i) { } #endif throw_value_limit& operator=(const throw_value_limit& __other) { base_type::operator=(__other); return *this; } #if __cplusplus >= 201103L throw_value_limit& operator=(throw_value_limit&&) = default; #endif }; /// Type throwing via random condition. struct throw_value_random : public throw_value_base { typedef throw_value_base base_type; #ifndef _GLIBCXX_IS_AGGREGATE throw_value_random() { } throw_value_random(const throw_value_random& __other) : base_type(__other._M_i) { } #if __cplusplus >= 201103L throw_value_random(throw_value_random&&) = default; #endif explicit throw_value_random(const std::size_t __i) : base_type(__i) { } #endif throw_value_random& operator=(const throw_value_random& __other) { base_type::operator=(__other); return *this; } #if __cplusplus >= 201103L throw_value_random& operator=(throw_value_random&&) = default; #endif }; /** * @brief Allocator class with logging and exception generation control. * Intended to be used as an allocator_type in templatized code. * @ingroup allocators * * Note: Deallocate not allowed to throw. */ template class throw_allocator_base : public annotate_base, public _Cond { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; #if __cplusplus >= 201103L // _GLIBCXX_RESOLVE_LIB_DEFECTS // 2103. std::allocator propagate_on_container_move_assignment typedef std::true_type propagate_on_container_move_assignment; #endif private: typedef _Cond condition_type; std::allocator _M_allocator; using condition_type::throw_conditionally; public: size_type max_size() const _GLIBCXX_USE_NOEXCEPT { return _M_allocator.max_size(); } pointer address(reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } const_pointer address(const_reference __x) const _GLIBCXX_NOEXCEPT { return std::__addressof(__x); } pointer allocate(size_type __n, std::allocator::const_pointer hint = 0) { if (__n > this->max_size()) std::__throw_bad_alloc(); throw_conditionally(); pointer const a = _M_allocator.allocate(__n, hint); insert(a, sizeof(value_type) * __n); return a; } #if __cplusplus >= 201103L template void construct(_Up* __p, _Args&&... __args) { _M_allocator.construct(__p, std::forward<_Args>(__args)...); insert_construct(__p); } template void destroy(_Up* __p) { erase_construct(__p); _M_allocator.destroy(__p); } #else void construct(pointer __p, const value_type& val) { return _M_allocator.construct(__p, val); } void destroy(pointer __p) { _M_allocator.destroy(__p); } #endif void deallocate(pointer __p, size_type __n) { erase(__p, sizeof(value_type) * __n); _M_allocator.deallocate(__p, __n); } void check_allocated(pointer __p, size_type __n) { size_type __t = sizeof(value_type) * __n; annotate_base::check_allocated(__p, __t); } void check(size_type __n) { annotate_base::check(__n); } }; template inline bool operator==(const throw_allocator_base<_Tp, _Cond>&, const throw_allocator_base<_Tp, _Cond>&) { return true; } template inline bool operator!=(const throw_allocator_base<_Tp, _Cond>&, const throw_allocator_base<_Tp, _Cond>&) { return false; } /// Allocator throwing via limit condition. template struct throw_allocator_limit : public throw_allocator_base<_Tp, limit_condition> { template struct rebind { typedef throw_allocator_limit<_Tp1> other; }; throw_allocator_limit() _GLIBCXX_USE_NOEXCEPT { } throw_allocator_limit(const throw_allocator_limit&) _GLIBCXX_USE_NOEXCEPT { } template throw_allocator_limit(const throw_allocator_limit<_Tp1>&) _GLIBCXX_USE_NOEXCEPT { } ~throw_allocator_limit() _GLIBCXX_USE_NOEXCEPT { } }; /// Allocator throwing via random condition. template struct throw_allocator_random : public throw_allocator_base<_Tp, random_condition> { template struct rebind { typedef throw_allocator_random<_Tp1> other; }; throw_allocator_random() _GLIBCXX_USE_NOEXCEPT { } throw_allocator_random(const throw_allocator_random&) _GLIBCXX_USE_NOEXCEPT { } template throw_allocator_random(const throw_allocator_random<_Tp1>&) _GLIBCXX_USE_NOEXCEPT { } ~throw_allocator_random() _GLIBCXX_USE_NOEXCEPT { } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #if __cplusplus >= 201103L # include namespace std _GLIBCXX_VISIBILITY(default) { /// Explicit specialization of std::hash for __gnu_cxx::throw_value_limit. template<> struct hash<__gnu_cxx::throw_value_limit> : public std::unary_function<__gnu_cxx::throw_value_limit, size_t> { size_t operator()(const __gnu_cxx::throw_value_limit& __val) const { __gnu_cxx::throw_value_limit::throw_conditionally(); std::hash __h; size_t __result = __h(__val._M_i); return __result; } }; /// Explicit specialization of std::hash for __gnu_cxx::throw_value_random. template<> struct hash<__gnu_cxx::throw_value_random> : public std::unary_function<__gnu_cxx::throw_value_random, size_t> { size_t operator()(const __gnu_cxx::throw_value_random& __val) const { __gnu_cxx::throw_value_random::throw_conditionally(); std::hash __h; size_t __result = __h(__val._M_i); return __result; } }; } // end namespace std #endif #endif c++/8/ext/vstring_fwd.h000064400000006226151027430570010602 0ustar00// Forward declarations -*- C++ -*- // Copyright (C) 2005-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/vstring_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/vstring.h} */ #ifndef _VSTRING_FWD_H #define _VSTRING_FWD_H 1 #pragma GCC system_header #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template class __sso_string_base; template class __rc_string_base; template, typename _Alloc = std::allocator<_CharT>, template class _Base = __sso_string_base> class __versa_string; typedef __versa_string __vstring; typedef __vstring __sso_string; typedef __versa_string, std::allocator, __rc_string_base> __rc_string; #ifdef _GLIBCXX_USE_WCHAR_T typedef __versa_string __wvstring; typedef __wvstring __wsso_string; typedef __versa_string, std::allocator, __rc_string_base> __wrc_string; #endif #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) typedef __versa_string __u16vstring; typedef __u16vstring __u16sso_string; typedef __versa_string, std::allocator, __rc_string_base> __u16rc_string; typedef __versa_string __u32vstring; typedef __u32vstring __u32sso_string; typedef __versa_string, std::allocator, __rc_string_base> __u32rc_string; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _VSTRING_FWD_H */ c++/8/ext/string_conversions.h000064400000007015151027430570012201 0ustar00// String Conversions -*- C++ -*- // Copyright (C) 2008-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/string_conversions.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _STRING_CONVERSIONS_H #define _STRING_CONVERSIONS_H 1 #pragma GCC system_header #if __cplusplus < 201103L # include #else #include #include #include #include #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // Helper for all the sto* functions. template _Ret __stoa(_TRet (*__convf) (const _CharT*, _CharT**, _Base...), const char* __name, const _CharT* __str, std::size_t* __idx, _Base... __base) { _Ret __ret; _CharT* __endptr; struct _Save_errno { _Save_errno() : _M_errno(errno) { errno = 0; } ~_Save_errno() { if (errno == 0) errno = _M_errno; } int _M_errno; } const __save_errno; struct _Range_chk { static bool _S_chk(_TRet, std::false_type) { return false; } static bool _S_chk(_TRet __val, std::true_type) // only called when _Ret is int { return __val < _TRet(__numeric_traits::__min) || __val > _TRet(__numeric_traits::__max); } }; const _TRet __tmp = __convf(__str, &__endptr, __base...); if (__endptr == __str) std::__throw_invalid_argument(__name); else if (errno == ERANGE || _Range_chk::_S_chk(__tmp, std::is_same<_Ret, int>{})) std::__throw_out_of_range(__name); else __ret = __tmp; if (__idx) *__idx = __endptr - __str; return __ret; } // Helper for the to_string / to_wstring functions. template _String __to_xstring(int (*__convf) (_CharT*, std::size_t, const _CharT*, __builtin_va_list), std::size_t __n, const _CharT* __fmt, ...) { // XXX Eventually the result should be constructed in-place in // the __cxx11 string, likely with the help of internal hooks. _CharT* __s = static_cast<_CharT*>(__builtin_alloca(sizeof(_CharT) * __n)); __builtin_va_list __args; __builtin_va_start(__args, __fmt); const int __len = __convf(__s, __n, __fmt, __args); __builtin_va_end(__args); return _String(__s, __s + __len); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // C++11 #endif // _STRING_CONVERSIONS_H c++/8/ext/rope000064400000253125151027430570006767 0ustar00// SGI's rope class -*- C++ -*- // Copyright (C) 2001-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /* * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. */ /** @file ext/rope * This file is a GNU extension to the Standard C++ Library (possibly * containing extensions from the HP/SGI STL subset). */ #ifndef _ROPE #define _ROPE 1 #pragma GCC system_header #include #include #include #include #include #include #include #include #include # ifdef __GC # define __GC_CONST const # else # define __GC_CONST // constant except for deallocation # endif #include // For uninitialized_copy_n namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace __detail { enum { _S_max_rope_depth = 45 }; enum _Tag {_S_leaf, _S_concat, _S_substringfn, _S_function}; } // namespace __detail using std::size_t; using std::ptrdiff_t; using std::allocator; using std::_Destroy; // See libstdc++/36832. template void _Destroy_const(_ForwardIterator __first, _ForwardIterator __last, _Allocator __alloc) { for (; __first != __last; ++__first) __alloc.destroy(&*__first); } template inline void _Destroy_const(_ForwardIterator __first, _ForwardIterator __last, allocator<_Tp>) { _Destroy(__first, __last); } // The _S_eos function is used for those functions that // convert to/from C-like strings to detect the end of the string. // The end-of-C-string character. // This is what the draft standard says it should be. template inline _CharT _S_eos(_CharT*) { return _CharT(); } // Test for basic character types. // For basic character types leaves having a trailing eos. template inline bool _S_is_basic_char_type(_CharT*) { return false; } template inline bool _S_is_one_byte_char_type(_CharT*) { return false; } inline bool _S_is_basic_char_type(char*) { return true; } inline bool _S_is_one_byte_char_type(char*) { return true; } inline bool _S_is_basic_char_type(wchar_t*) { return true; } // Store an eos iff _CharT is a basic character type. // Do not reference _S_eos if it isn't. template inline void _S_cond_store_eos(_CharT&) { } inline void _S_cond_store_eos(char& __c) { __c = 0; } inline void _S_cond_store_eos(wchar_t& __c) { __c = 0; } // char_producers are logically functions that generate a section of // a string. These can be converted to ropes. The resulting rope // invokes the char_producer on demand. This allows, for example, // files to be viewed as ropes without reading the entire file. template class char_producer { public: virtual ~char_producer() { } virtual void operator()(size_t __start_pos, size_t __len, _CharT* __buffer) = 0; // Buffer should really be an arbitrary output iterator. // That way we could flatten directly into an ostream, etc. // This is thoroughly impossible, since iterator types don't // have runtime descriptions. }; // Sequence buffers: // // Sequence must provide an append operation that appends an // array to the sequence. Sequence buffers are useful only if // appending an entire array is cheaper than appending element by element. // This is true for many string representations. // This should perhaps inherit from ostream // and be implemented correspondingly, so that they can be used // for formatted. For the sake of portability, we don't do this yet. // // For now, sequence buffers behave as output iterators. But they also // behave a little like basic_ostringstream and a // little like containers. template class sequence_buffer : public std::iterator { public: typedef typename _Sequence::value_type value_type; protected: _Sequence* _M_prefix; value_type _M_buffer[_Buf_sz]; size_t _M_buf_count; public: void flush() { _M_prefix->append(_M_buffer, _M_buffer + _M_buf_count); _M_buf_count = 0; } ~sequence_buffer() { flush(); } sequence_buffer() : _M_prefix(0), _M_buf_count(0) { } sequence_buffer(const sequence_buffer& __x) { _M_prefix = __x._M_prefix; _M_buf_count = __x._M_buf_count; std::copy(__x._M_buffer, __x._M_buffer + __x._M_buf_count, _M_buffer); } sequence_buffer(sequence_buffer& __x) { __x.flush(); _M_prefix = __x._M_prefix; _M_buf_count = 0; } sequence_buffer(_Sequence& __s) : _M_prefix(&__s), _M_buf_count(0) { } sequence_buffer& operator=(sequence_buffer& __x) { __x.flush(); _M_prefix = __x._M_prefix; _M_buf_count = 0; return *this; } sequence_buffer& operator=(const sequence_buffer& __x) { _M_prefix = __x._M_prefix; _M_buf_count = __x._M_buf_count; std::copy(__x._M_buffer, __x._M_buffer + __x._M_buf_count, _M_buffer); return *this; } void push_back(value_type __x) { if (_M_buf_count < _Buf_sz) { _M_buffer[_M_buf_count] = __x; ++_M_buf_count; } else { flush(); _M_buffer[0] = __x; _M_buf_count = 1; } } void append(value_type* __s, size_t __len) { if (__len + _M_buf_count <= _Buf_sz) { size_t __i = _M_buf_count; for (size_t __j = 0; __j < __len; __i++, __j++) _M_buffer[__i] = __s[__j]; _M_buf_count += __len; } else if (0 == _M_buf_count) _M_prefix->append(__s, __s + __len); else { flush(); append(__s, __len); } } sequence_buffer& write(value_type* __s, size_t __len) { append(__s, __len); return *this; } sequence_buffer& put(value_type __x) { push_back(__x); return *this; } sequence_buffer& operator=(const value_type& __rhs) { push_back(__rhs); return *this; } sequence_buffer& operator*() { return *this; } sequence_buffer& operator++() { return *this; } sequence_buffer operator++(int) { return *this; } }; // The following should be treated as private, at least for now. template class _Rope_char_consumer { public: // If we had member templates, these should not be virtual. // For now we need to use run-time parametrization where // compile-time would do. Hence this should all be private // for now. // The symmetry with char_producer is accidental and temporary. virtual ~_Rope_char_consumer() { } virtual bool operator()(const _CharT* __buffer, size_t __len) = 0; }; // First a lot of forward declarations. The standard seems to require // much stricter "declaration before use" than many of the implementations // that preceded it. template > class rope; template struct _Rope_RopeConcatenation; template struct _Rope_RopeLeaf; template struct _Rope_RopeFunction; template struct _Rope_RopeSubstring; template class _Rope_iterator; template class _Rope_const_iterator; template class _Rope_char_ref_proxy; template class _Rope_char_ptr_proxy; template bool operator==(const _Rope_char_ptr_proxy<_CharT, _Alloc>& __x, const _Rope_char_ptr_proxy<_CharT, _Alloc>& __y); template _Rope_const_iterator<_CharT, _Alloc> operator-(const _Rope_const_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n); template _Rope_const_iterator<_CharT, _Alloc> operator+(const _Rope_const_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n); template _Rope_const_iterator<_CharT, _Alloc> operator+(ptrdiff_t __n, const _Rope_const_iterator<_CharT, _Alloc>& __x); template bool operator==(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y); template bool operator<(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y); template ptrdiff_t operator-(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y); template _Rope_iterator<_CharT, _Alloc> operator-(const _Rope_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n); template _Rope_iterator<_CharT, _Alloc> operator+(const _Rope_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n); template _Rope_iterator<_CharT, _Alloc> operator+(ptrdiff_t __n, const _Rope_iterator<_CharT, _Alloc>& __x); template bool operator==(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y); template bool operator<(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y); template ptrdiff_t operator-(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y); template rope<_CharT, _Alloc> operator+(const rope<_CharT, _Alloc>& __left, const rope<_CharT, _Alloc>& __right); template rope<_CharT, _Alloc> operator+(const rope<_CharT, _Alloc>& __left, const _CharT* __right); template rope<_CharT, _Alloc> operator+(const rope<_CharT, _Alloc>& __left, _CharT __right); // Some helpers, so we can use power on ropes. // See below for why this isn't local to the implementation. // This uses a nonstandard refcount convention. // The result has refcount 0. template struct _Rope_Concat_fn : public std::binary_function, rope<_CharT, _Alloc>, rope<_CharT, _Alloc> > { rope<_CharT, _Alloc> operator()(const rope<_CharT, _Alloc>& __x, const rope<_CharT, _Alloc>& __y) { return __x + __y; } }; template inline rope<_CharT, _Alloc> identity_element(_Rope_Concat_fn<_CharT, _Alloc>) { return rope<_CharT, _Alloc>(); } // Class _Refcount_Base provides a type, _RC_t, a data member, // _M_ref_count, and member functions _M_incr and _M_decr, which perform // atomic preincrement/predecrement. The constructor initializes // _M_ref_count. struct _Refcount_Base { // The type _RC_t typedef size_t _RC_t; // The data member _M_ref_count volatile _RC_t _M_ref_count; // Constructor #ifdef __GTHREAD_MUTEX_INIT __gthread_mutex_t _M_ref_count_lock = __GTHREAD_MUTEX_INIT; #else __gthread_mutex_t _M_ref_count_lock; #endif _Refcount_Base(_RC_t __n) : _M_ref_count(__n) { #ifndef __GTHREAD_MUTEX_INIT #ifdef __GTHREAD_MUTEX_INIT_FUNCTION __GTHREAD_MUTEX_INIT_FUNCTION (&_M_ref_count_lock); #else #error __GTHREAD_MUTEX_INIT or __GTHREAD_MUTEX_INIT_FUNCTION should be defined by gthr.h abstraction layer, report problem to libstdc++@gcc.gnu.org. #endif #endif } #ifndef __GTHREAD_MUTEX_INIT ~_Refcount_Base() { __gthread_mutex_destroy(&_M_ref_count_lock); } #endif void _M_incr() { __gthread_mutex_lock(&_M_ref_count_lock); ++_M_ref_count; __gthread_mutex_unlock(&_M_ref_count_lock); } _RC_t _M_decr() { __gthread_mutex_lock(&_M_ref_count_lock); volatile _RC_t __tmp = --_M_ref_count; __gthread_mutex_unlock(&_M_ref_count_lock); return __tmp; } }; // // What follows should really be local to rope. Unfortunately, // that doesn't work, since it makes it impossible to define generic // equality on rope iterators. According to the draft standard, the // template parameters for such an equality operator cannot be inferred // from the occurrence of a member class as a parameter. // (SGI compilers in fact allow this, but the __result wouldn't be // portable.) // Similarly, some of the static member functions are member functions // only to avoid polluting the global namespace, and to circumvent // restrictions on type inference for template functions. // // // The internal data structure for representing a rope. This is // private to the implementation. A rope is really just a pointer // to one of these. // // A few basic functions for manipulating this data structure // are members of _RopeRep. Most of the more complex algorithms // are implemented as rope members. // // Some of the static member functions of _RopeRep have identically // named functions in rope that simply invoke the _RopeRep versions. #define __ROPE_DEFINE_ALLOCS(__a) \ __ROPE_DEFINE_ALLOC(_CharT,_Data) /* character data */ \ typedef _Rope_RopeConcatenation<_CharT,__a> __C; \ __ROPE_DEFINE_ALLOC(__C,_C) \ typedef _Rope_RopeLeaf<_CharT,__a> __L; \ __ROPE_DEFINE_ALLOC(__L,_L) \ typedef _Rope_RopeFunction<_CharT,__a> __F; \ __ROPE_DEFINE_ALLOC(__F,_F) \ typedef _Rope_RopeSubstring<_CharT,__a> __S; \ __ROPE_DEFINE_ALLOC(__S,_S) // Internal rope nodes potentially store a copy of the allocator // instance used to allocate them. This is mostly redundant. // But the alternative would be to pass allocator instances around // in some form to nearly all internal functions, since any pointer // assignment may result in a zero reference count and thus require // deallocation. #define __STATIC_IF_SGI_ALLOC /* not static */ template struct _Rope_rep_base : public _Alloc { typedef _Alloc allocator_type; allocator_type get_allocator() const { return *static_cast(this); } allocator_type& _M_get_allocator() { return *static_cast<_Alloc*>(this); } const allocator_type& _M_get_allocator() const { return *static_cast(this); } _Rope_rep_base(size_t __size, const allocator_type&) : _M_size(__size) { } size_t _M_size; # define __ROPE_DEFINE_ALLOC(_Tp, __name) \ typedef typename \ _Alloc::template rebind<_Tp>::other __name##Alloc; \ static _Tp* __name##_allocate(size_t __n) \ { return __name##Alloc().allocate(__n); } \ static void __name##_deallocate(_Tp *__p, size_t __n) \ { __name##Alloc().deallocate(__p, __n); } __ROPE_DEFINE_ALLOCS(_Alloc) # undef __ROPE_DEFINE_ALLOC }; template struct _Rope_RopeRep : public _Rope_rep_base<_CharT, _Alloc> # ifndef __GC , _Refcount_Base # endif { public: __detail::_Tag _M_tag:8; bool _M_is_balanced:8; unsigned char _M_depth; __GC_CONST _CharT* _M_c_string; #ifdef __GTHREAD_MUTEX_INIT __gthread_mutex_t _M_c_string_lock = __GTHREAD_MUTEX_INIT; #else __gthread_mutex_t _M_c_string_lock; #endif /* Flattened version of string, if needed. */ /* typically 0. */ /* If it's not 0, then the memory is owned */ /* by this node. */ /* In the case of a leaf, this may point to */ /* the same memory as the data field. */ typedef typename _Rope_rep_base<_CharT, _Alloc>::allocator_type allocator_type; using _Rope_rep_base<_CharT, _Alloc>::get_allocator; using _Rope_rep_base<_CharT, _Alloc>::_M_get_allocator; _Rope_RopeRep(__detail::_Tag __t, int __d, bool __b, size_t __size, const allocator_type& __a) : _Rope_rep_base<_CharT, _Alloc>(__size, __a), #ifndef __GC _Refcount_Base(1), #endif _M_tag(__t), _M_is_balanced(__b), _M_depth(__d), _M_c_string(0) #ifdef __GTHREAD_MUTEX_INIT { } #else { __GTHREAD_MUTEX_INIT_FUNCTION (&_M_c_string_lock); } ~_Rope_RopeRep() { __gthread_mutex_destroy (&_M_c_string_lock); } #endif #ifdef __GC void _M_incr () { } #endif static void _S_free_string(__GC_CONST _CharT*, size_t __len, allocator_type& __a); #define __STL_FREE_STRING(__s, __l, __a) _S_free_string(__s, __l, __a); // Deallocate data section of a leaf. // This shouldn't be a member function. // But its hard to do anything else at the // moment, because it's templatized w.r.t. // an allocator. // Does nothing if __GC is defined. #ifndef __GC void _M_free_c_string(); void _M_free_tree(); // Deallocate t. Assumes t is not 0. void _M_unref_nonnil() { if (0 == _M_decr()) _M_free_tree(); } void _M_ref_nonnil() { _M_incr(); } static void _S_unref(_Rope_RopeRep* __t) { if (0 != __t) __t->_M_unref_nonnil(); } static void _S_ref(_Rope_RopeRep* __t) { if (0 != __t) __t->_M_incr(); } static void _S_free_if_unref(_Rope_RopeRep* __t) { if (0 != __t && 0 == __t->_M_ref_count) __t->_M_free_tree(); } # else /* __GC */ void _M_unref_nonnil() { } void _M_ref_nonnil() { } static void _S_unref(_Rope_RopeRep*) { } static void _S_ref(_Rope_RopeRep*) { } static void _S_free_if_unref(_Rope_RopeRep*) { } # endif protected: _Rope_RopeRep& operator=(const _Rope_RopeRep&); _Rope_RopeRep(const _Rope_RopeRep&); }; template struct _Rope_RopeLeaf : public _Rope_RopeRep<_CharT, _Alloc> { public: // Apparently needed by VC++ // The data fields of leaves are allocated with some // extra space, to accommodate future growth and for basic // character types, to hold a trailing eos character. enum { _S_alloc_granularity = 8 }; static size_t _S_rounded_up_size(size_t __n) { size_t __size_with_eos; if (_S_is_basic_char_type((_CharT*)0)) __size_with_eos = __n + 1; else __size_with_eos = __n; #ifdef __GC return __size_with_eos; #else // Allow slop for in-place expansion. return ((__size_with_eos + size_t(_S_alloc_granularity) - 1) &~ (size_t(_S_alloc_granularity) - 1)); #endif } __GC_CONST _CharT* _M_data; /* Not necessarily 0 terminated. */ /* The allocated size is */ /* _S_rounded_up_size(size), except */ /* in the GC case, in which it */ /* doesn't matter. */ typedef typename _Rope_rep_base<_CharT,_Alloc>::allocator_type allocator_type; _Rope_RopeLeaf(__GC_CONST _CharT* __d, size_t __size, const allocator_type& __a) : _Rope_RopeRep<_CharT, _Alloc>(__detail::_S_leaf, 0, true, __size, __a), _M_data(__d) { if (_S_is_basic_char_type((_CharT *)0)) { // already eos terminated. this->_M_c_string = __d; } } // The constructor assumes that d has been allocated with // the proper allocator and the properly padded size. // In contrast, the destructor deallocates the data: #ifndef __GC ~_Rope_RopeLeaf() throw() { if (_M_data != this->_M_c_string) this->_M_free_c_string(); this->__STL_FREE_STRING(_M_data, this->_M_size, this->_M_get_allocator()); } #endif protected: _Rope_RopeLeaf& operator=(const _Rope_RopeLeaf&); _Rope_RopeLeaf(const _Rope_RopeLeaf&); }; template struct _Rope_RopeConcatenation : public _Rope_RopeRep<_CharT, _Alloc> { public: _Rope_RopeRep<_CharT, _Alloc>* _M_left; _Rope_RopeRep<_CharT, _Alloc>* _M_right; typedef typename _Rope_rep_base<_CharT, _Alloc>::allocator_type allocator_type; _Rope_RopeConcatenation(_Rope_RopeRep<_CharT, _Alloc>* __l, _Rope_RopeRep<_CharT, _Alloc>* __r, const allocator_type& __a) : _Rope_RopeRep<_CharT, _Alloc>(__detail::_S_concat, std::max(__l->_M_depth, __r->_M_depth) + 1, false, __l->_M_size + __r->_M_size, __a), _M_left(__l), _M_right(__r) { } #ifndef __GC ~_Rope_RopeConcatenation() throw() { this->_M_free_c_string(); _M_left->_M_unref_nonnil(); _M_right->_M_unref_nonnil(); } #endif protected: _Rope_RopeConcatenation& operator=(const _Rope_RopeConcatenation&); _Rope_RopeConcatenation(const _Rope_RopeConcatenation&); }; template struct _Rope_RopeFunction : public _Rope_RopeRep<_CharT, _Alloc> { public: char_producer<_CharT>* _M_fn; #ifndef __GC bool _M_delete_when_done; // Char_producer is owned by the // rope and should be explicitly // deleted when the rope becomes // inaccessible. #else // In the GC case, we either register the rope for // finalization, or not. Thus the field is unnecessary; // the information is stored in the collector data structures. // We do need a finalization procedure to be invoked by the // collector. static void _S_fn_finalization_proc(void * __tree, void *) { delete ((_Rope_RopeFunction *)__tree) -> _M_fn; } #endif typedef typename _Rope_rep_base<_CharT, _Alloc>::allocator_type allocator_type; _Rope_RopeFunction(char_producer<_CharT>* __f, size_t __size, bool __d, const allocator_type& __a) : _Rope_RopeRep<_CharT, _Alloc>(__detail::_S_function, 0, true, __size, __a) , _M_fn(__f) #ifndef __GC , _M_delete_when_done(__d) #endif { #ifdef __GC if (__d) { GC_REGISTER_FINALIZER(this, _Rope_RopeFunction:: _S_fn_finalization_proc, 0, 0, 0); } #endif } #ifndef __GC ~_Rope_RopeFunction() throw() { this->_M_free_c_string(); if (_M_delete_when_done) delete _M_fn; } # endif protected: _Rope_RopeFunction& operator=(const _Rope_RopeFunction&); _Rope_RopeFunction(const _Rope_RopeFunction&); }; // Substring results are usually represented using just // concatenation nodes. But in the case of very long flat ropes // or ropes with a functional representation that isn't practical. // In that case, we represent the __result as a special case of // RopeFunction, whose char_producer points back to the rope itself. // In all cases except repeated substring operations and // deallocation, we treat the __result as a RopeFunction. template struct _Rope_RopeSubstring : public _Rope_RopeFunction<_CharT, _Alloc>, public char_producer<_CharT> { public: // XXX this whole class should be rewritten. _Rope_RopeRep<_CharT,_Alloc>* _M_base; // not 0 size_t _M_start; virtual void operator()(size_t __start_pos, size_t __req_len, _CharT* __buffer) { switch(_M_base->_M_tag) { case __detail::_S_function: case __detail::_S_substringfn: { char_producer<_CharT>* __fn = ((_Rope_RopeFunction<_CharT,_Alloc>*)_M_base)->_M_fn; (*__fn)(__start_pos + _M_start, __req_len, __buffer); } break; case __detail::_S_leaf: { __GC_CONST _CharT* __s = ((_Rope_RopeLeaf<_CharT,_Alloc>*)_M_base)->_M_data; uninitialized_copy_n(__s + __start_pos + _M_start, __req_len, __buffer); } break; default: break; } } typedef typename _Rope_rep_base<_CharT, _Alloc>::allocator_type allocator_type; _Rope_RopeSubstring(_Rope_RopeRep<_CharT, _Alloc>* __b, size_t __s, size_t __l, const allocator_type& __a) : _Rope_RopeFunction<_CharT, _Alloc>(this, __l, false, __a), char_producer<_CharT>(), _M_base(__b), _M_start(__s) { #ifndef __GC _M_base->_M_ref_nonnil(); #endif this->_M_tag = __detail::_S_substringfn; } virtual ~_Rope_RopeSubstring() throw() { #ifndef __GC _M_base->_M_unref_nonnil(); // _M_free_c_string(); -- done by parent class #endif } }; // Self-destructing pointers to Rope_rep. // These are not conventional smart pointers. Their // only purpose in life is to ensure that unref is called // on the pointer either at normal exit or if an exception // is raised. It is the caller's responsibility to // adjust reference counts when these pointers are initialized // or assigned to. (This convention significantly reduces // the number of potentially expensive reference count // updates.) #ifndef __GC template struct _Rope_self_destruct_ptr { _Rope_RopeRep<_CharT, _Alloc>* _M_ptr; ~_Rope_self_destruct_ptr() { _Rope_RopeRep<_CharT, _Alloc>::_S_unref(_M_ptr); } #if __cpp_exceptions _Rope_self_destruct_ptr() : _M_ptr(0) { } #else _Rope_self_destruct_ptr() { } #endif _Rope_self_destruct_ptr(_Rope_RopeRep<_CharT, _Alloc>* __p) : _M_ptr(__p) { } _Rope_RopeRep<_CharT, _Alloc>& operator*() { return *_M_ptr; } _Rope_RopeRep<_CharT, _Alloc>* operator->() { return _M_ptr; } operator _Rope_RopeRep<_CharT, _Alloc>*() { return _M_ptr; } _Rope_self_destruct_ptr& operator=(_Rope_RopeRep<_CharT, _Alloc>* __x) { _M_ptr = __x; return *this; } }; #endif // Dereferencing a nonconst iterator has to return something // that behaves almost like a reference. It's not possible to // return an actual reference since assignment requires extra // work. And we would get into the same problems as with the // CD2 version of basic_string. template class _Rope_char_ref_proxy { friend class rope<_CharT, _Alloc>; friend class _Rope_iterator<_CharT, _Alloc>; friend class _Rope_char_ptr_proxy<_CharT, _Alloc>; #ifdef __GC typedef _Rope_RopeRep<_CharT, _Alloc>* _Self_destruct_ptr; #else typedef _Rope_self_destruct_ptr<_CharT, _Alloc> _Self_destruct_ptr; #endif typedef _Rope_RopeRep<_CharT, _Alloc> _RopeRep; typedef rope<_CharT, _Alloc> _My_rope; size_t _M_pos; _CharT _M_current; bool _M_current_valid; _My_rope* _M_root; // The whole rope. public: _Rope_char_ref_proxy(_My_rope* __r, size_t __p) : _M_pos(__p), _M_current(), _M_current_valid(false), _M_root(__r) { } _Rope_char_ref_proxy(const _Rope_char_ref_proxy& __x) : _M_pos(__x._M_pos), _M_current(__x._M_current), _M_current_valid(false), _M_root(__x._M_root) { } // Don't preserve cache if the reference can outlive the // expression. We claim that's not possible without calling // a copy constructor or generating reference to a proxy // reference. We declare the latter to have undefined semantics. _Rope_char_ref_proxy(_My_rope* __r, size_t __p, _CharT __c) : _M_pos(__p), _M_current(__c), _M_current_valid(true), _M_root(__r) { } inline operator _CharT () const; _Rope_char_ref_proxy& operator=(_CharT __c); _Rope_char_ptr_proxy<_CharT, _Alloc> operator&() const; _Rope_char_ref_proxy& operator=(const _Rope_char_ref_proxy& __c) { return operator=((_CharT)__c); } }; template inline void swap(_Rope_char_ref_proxy <_CharT, __Alloc > __a, _Rope_char_ref_proxy <_CharT, __Alloc > __b) { _CharT __tmp = __a; __a = __b; __b = __tmp; } template class _Rope_char_ptr_proxy { // XXX this class should be rewritten. friend class _Rope_char_ref_proxy<_CharT, _Alloc>; size_t _M_pos; rope<_CharT,_Alloc>* _M_root; // The whole rope. public: _Rope_char_ptr_proxy(const _Rope_char_ref_proxy<_CharT,_Alloc>& __x) : _M_pos(__x._M_pos), _M_root(__x._M_root) { } _Rope_char_ptr_proxy(const _Rope_char_ptr_proxy& __x) : _M_pos(__x._M_pos), _M_root(__x._M_root) { } _Rope_char_ptr_proxy() { } _Rope_char_ptr_proxy(_CharT* __x) : _M_root(0), _M_pos(0) { } _Rope_char_ptr_proxy& operator=(const _Rope_char_ptr_proxy& __x) { _M_pos = __x._M_pos; _M_root = __x._M_root; return *this; } template friend bool operator==(const _Rope_char_ptr_proxy<_CharT2, _Alloc2>& __x, const _Rope_char_ptr_proxy<_CharT2, _Alloc2>& __y); _Rope_char_ref_proxy<_CharT, _Alloc> operator*() const { return _Rope_char_ref_proxy<_CharT, _Alloc>(_M_root, _M_pos); } }; // Rope iterators: // Unlike in the C version, we cache only part of the stack // for rope iterators, since they must be efficiently copyable. // When we run out of cache, we have to reconstruct the iterator // value. // Pointers from iterators are not included in reference counts. // Iterators are assumed to be thread private. Ropes can // be shared. template class _Rope_iterator_base : public std::iterator { friend class rope<_CharT, _Alloc>; public: typedef _Alloc _allocator_type; // used in _Rope_rotate, VC++ workaround typedef _Rope_RopeRep<_CharT, _Alloc> _RopeRep; // Borland doesn't want this to be protected. protected: enum { _S_path_cache_len = 4 }; // Must be <= 9. enum { _S_iterator_buf_len = 15 }; size_t _M_current_pos; _RopeRep* _M_root; // The whole rope. size_t _M_leaf_pos; // Starting position for current leaf __GC_CONST _CharT* _M_buf_start; // Buffer possibly // containing current char. __GC_CONST _CharT* _M_buf_ptr; // Pointer to current char in buffer. // != 0 ==> buffer valid. __GC_CONST _CharT* _M_buf_end; // One past __last valid char in buffer. // What follows is the path cache. We go out of our // way to make this compact. // Path_end contains the bottom section of the path from // the root to the current leaf. const _RopeRep* _M_path_end[_S_path_cache_len]; int _M_leaf_index; // Last valid __pos in path_end; // _M_path_end[0] ... _M_path_end[leaf_index-1] // point to concatenation nodes. unsigned char _M_path_directions; // (path_directions >> __i) & 1 is 1 // iff we got from _M_path_end[leaf_index - __i - 1] // to _M_path_end[leaf_index - __i] by going to the // __right. Assumes path_cache_len <= 9. _CharT _M_tmp_buf[_S_iterator_buf_len]; // Short buffer for surrounding chars. // This is useful primarily for // RopeFunctions. We put the buffer // here to avoid locking in the // multithreaded case. // The cached path is generally assumed to be valid // only if the buffer is valid. static void _S_setbuf(_Rope_iterator_base& __x); // Set buffer contents given // path cache. static void _S_setcache(_Rope_iterator_base& __x); // Set buffer contents and // path cache. static void _S_setcache_for_incr(_Rope_iterator_base& __x); // As above, but assumes path // cache is valid for previous posn. _Rope_iterator_base() { } _Rope_iterator_base(_RopeRep* __root, size_t __pos) : _M_current_pos(__pos), _M_root(__root), _M_buf_ptr(0) { } void _M_incr(size_t __n); void _M_decr(size_t __n); public: size_t index() const { return _M_current_pos; } _Rope_iterator_base(const _Rope_iterator_base& __x) { if (0 != __x._M_buf_ptr) *this = __x; else { _M_current_pos = __x._M_current_pos; _M_root = __x._M_root; _M_buf_ptr = 0; } } }; template class _Rope_iterator; template class _Rope_const_iterator : public _Rope_iterator_base<_CharT, _Alloc> { friend class rope<_CharT, _Alloc>; protected: typedef _Rope_RopeRep<_CharT, _Alloc> _RopeRep; // The one from the base class may not be directly visible. _Rope_const_iterator(const _RopeRep* __root, size_t __pos) : _Rope_iterator_base<_CharT, _Alloc>(const_cast<_RopeRep*>(__root), __pos) // Only nonconst iterators modify root ref count { } public: typedef _CharT reference; // Really a value. Returning a reference // Would be a mess, since it would have // to be included in refcount. typedef const _CharT* pointer; public: _Rope_const_iterator() { } _Rope_const_iterator(const _Rope_const_iterator& __x) : _Rope_iterator_base<_CharT,_Alloc>(__x) { } _Rope_const_iterator(const _Rope_iterator<_CharT,_Alloc>& __x); _Rope_const_iterator(const rope<_CharT, _Alloc>& __r, size_t __pos) : _Rope_iterator_base<_CharT,_Alloc>(__r._M_tree_ptr, __pos) { } _Rope_const_iterator& operator=(const _Rope_const_iterator& __x) { if (0 != __x._M_buf_ptr) *(static_cast<_Rope_iterator_base<_CharT, _Alloc>*>(this)) = __x; else { this->_M_current_pos = __x._M_current_pos; this->_M_root = __x._M_root; this->_M_buf_ptr = 0; } return(*this); } reference operator*() { if (0 == this->_M_buf_ptr) this->_S_setcache(*this); return *this->_M_buf_ptr; } // Without this const version, Rope iterators do not meet the // requirements of an Input Iterator. reference operator*() const { return *const_cast<_Rope_const_iterator&>(*this); } _Rope_const_iterator& operator++() { __GC_CONST _CharT* __next; if (0 != this->_M_buf_ptr && (__next = this->_M_buf_ptr + 1) < this->_M_buf_end) { this->_M_buf_ptr = __next; ++this->_M_current_pos; } else this->_M_incr(1); return *this; } _Rope_const_iterator& operator+=(ptrdiff_t __n) { if (__n >= 0) this->_M_incr(__n); else this->_M_decr(-__n); return *this; } _Rope_const_iterator& operator--() { this->_M_decr(1); return *this; } _Rope_const_iterator& operator-=(ptrdiff_t __n) { if (__n >= 0) this->_M_decr(__n); else this->_M_incr(-__n); return *this; } _Rope_const_iterator operator++(int) { size_t __old_pos = this->_M_current_pos; this->_M_incr(1); return _Rope_const_iterator<_CharT,_Alloc>(this->_M_root, __old_pos); // This makes a subsequent dereference expensive. // Perhaps we should instead copy the iterator // if it has a valid cache? } _Rope_const_iterator operator--(int) { size_t __old_pos = this->_M_current_pos; this->_M_decr(1); return _Rope_const_iterator<_CharT,_Alloc>(this->_M_root, __old_pos); } template friend _Rope_const_iterator<_CharT2, _Alloc2> operator-(const _Rope_const_iterator<_CharT2, _Alloc2>& __x, ptrdiff_t __n); template friend _Rope_const_iterator<_CharT2, _Alloc2> operator+(const _Rope_const_iterator<_CharT2, _Alloc2>& __x, ptrdiff_t __n); template friend _Rope_const_iterator<_CharT2, _Alloc2> operator+(ptrdiff_t __n, const _Rope_const_iterator<_CharT2, _Alloc2>& __x); reference operator[](size_t __n) { return rope<_CharT, _Alloc>::_S_fetch(this->_M_root, this->_M_current_pos + __n); } template friend bool operator==(const _Rope_const_iterator<_CharT2, _Alloc2>& __x, const _Rope_const_iterator<_CharT2, _Alloc2>& __y); template friend bool operator<(const _Rope_const_iterator<_CharT2, _Alloc2>& __x, const _Rope_const_iterator<_CharT2, _Alloc2>& __y); template friend ptrdiff_t operator-(const _Rope_const_iterator<_CharT2, _Alloc2>& __x, const _Rope_const_iterator<_CharT2, _Alloc2>& __y); }; template class _Rope_iterator : public _Rope_iterator_base<_CharT, _Alloc> { friend class rope<_CharT, _Alloc>; protected: typedef typename _Rope_iterator_base<_CharT, _Alloc>::_RopeRep _RopeRep; rope<_CharT, _Alloc>* _M_root_rope; // root is treated as a cached version of this, and is used to // detect changes to the underlying rope. // Root is included in the reference count. This is necessary // so that we can detect changes reliably. Unfortunately, it // requires careful bookkeeping for the nonGC case. _Rope_iterator(rope<_CharT, _Alloc>* __r, size_t __pos) : _Rope_iterator_base<_CharT, _Alloc>(__r->_M_tree_ptr, __pos), _M_root_rope(__r) { _RopeRep::_S_ref(this->_M_root); if (!(__r -> empty())) this->_S_setcache(*this); } void _M_check(); public: typedef _Rope_char_ref_proxy<_CharT, _Alloc> reference; typedef _Rope_char_ref_proxy<_CharT, _Alloc>* pointer; rope<_CharT, _Alloc>& container() { return *_M_root_rope; } _Rope_iterator() { this->_M_root = 0; // Needed for reference counting. } _Rope_iterator(const _Rope_iterator& __x) : _Rope_iterator_base<_CharT, _Alloc>(__x) { _M_root_rope = __x._M_root_rope; _RopeRep::_S_ref(this->_M_root); } _Rope_iterator(rope<_CharT, _Alloc>& __r, size_t __pos); ~_Rope_iterator() { _RopeRep::_S_unref(this->_M_root); } _Rope_iterator& operator=(const _Rope_iterator& __x) { _RopeRep* __old = this->_M_root; _RopeRep::_S_ref(__x._M_root); if (0 != __x._M_buf_ptr) { _M_root_rope = __x._M_root_rope; *(static_cast<_Rope_iterator_base<_CharT, _Alloc>*>(this)) = __x; } else { this->_M_current_pos = __x._M_current_pos; this->_M_root = __x._M_root; _M_root_rope = __x._M_root_rope; this->_M_buf_ptr = 0; } _RopeRep::_S_unref(__old); return(*this); } reference operator*() { _M_check(); if (0 == this->_M_buf_ptr) return _Rope_char_ref_proxy<_CharT, _Alloc>(_M_root_rope, this->_M_current_pos); else return _Rope_char_ref_proxy<_CharT, _Alloc>(_M_root_rope, this->_M_current_pos, *this->_M_buf_ptr); } // See above comment. reference operator*() const { return *const_cast<_Rope_iterator&>(*this); } _Rope_iterator& operator++() { this->_M_incr(1); return *this; } _Rope_iterator& operator+=(ptrdiff_t __n) { if (__n >= 0) this->_M_incr(__n); else this->_M_decr(-__n); return *this; } _Rope_iterator& operator--() { this->_M_decr(1); return *this; } _Rope_iterator& operator-=(ptrdiff_t __n) { if (__n >= 0) this->_M_decr(__n); else this->_M_incr(-__n); return *this; } _Rope_iterator operator++(int) { size_t __old_pos = this->_M_current_pos; this->_M_incr(1); return _Rope_iterator<_CharT,_Alloc>(_M_root_rope, __old_pos); } _Rope_iterator operator--(int) { size_t __old_pos = this->_M_current_pos; this->_M_decr(1); return _Rope_iterator<_CharT,_Alloc>(_M_root_rope, __old_pos); } reference operator[](ptrdiff_t __n) { return _Rope_char_ref_proxy<_CharT, _Alloc>(_M_root_rope, this->_M_current_pos + __n); } template friend bool operator==(const _Rope_iterator<_CharT2, _Alloc2>& __x, const _Rope_iterator<_CharT2, _Alloc2>& __y); template friend bool operator<(const _Rope_iterator<_CharT2, _Alloc2>& __x, const _Rope_iterator<_CharT2, _Alloc2>& __y); template friend ptrdiff_t operator-(const _Rope_iterator<_CharT2, _Alloc2>& __x, const _Rope_iterator<_CharT2, _Alloc2>& __y); template friend _Rope_iterator<_CharT2, _Alloc2> operator-(const _Rope_iterator<_CharT2, _Alloc2>& __x, ptrdiff_t __n); template friend _Rope_iterator<_CharT2, _Alloc2> operator+(const _Rope_iterator<_CharT2, _Alloc2>& __x, ptrdiff_t __n); template friend _Rope_iterator<_CharT2, _Alloc2> operator+(ptrdiff_t __n, const _Rope_iterator<_CharT2, _Alloc2>& __x); }; template struct _Rope_base : public _Alloc { typedef _Alloc allocator_type; allocator_type get_allocator() const { return *static_cast(this); } allocator_type& _M_get_allocator() { return *static_cast<_Alloc*>(this); } const allocator_type& _M_get_allocator() const { return *static_cast(this); } typedef _Rope_RopeRep<_CharT, _Alloc> _RopeRep; // The one in _Base may not be visible due to template rules. _Rope_base(_RopeRep* __t, const allocator_type&) : _M_tree_ptr(__t) { } _Rope_base(const allocator_type&) { } // The only data member of a rope: _RopeRep *_M_tree_ptr; #define __ROPE_DEFINE_ALLOC(_Tp, __name) \ typedef typename \ _Alloc::template rebind<_Tp>::other __name##Alloc; \ static _Tp* __name##_allocate(size_t __n) \ { return __name##Alloc().allocate(__n); } \ static void __name##_deallocate(_Tp *__p, size_t __n) \ { __name##Alloc().deallocate(__p, __n); } __ROPE_DEFINE_ALLOCS(_Alloc) #undef __ROPE_DEFINE_ALLOC protected: _Rope_base& operator=(const _Rope_base&); _Rope_base(const _Rope_base&); }; /** * This is an SGI extension. * @ingroup SGIextensions * @doctodo */ template class rope : public _Rope_base<_CharT, _Alloc> { public: typedef _CharT value_type; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef _CharT const_reference; typedef const _CharT* const_pointer; typedef _Rope_iterator<_CharT, _Alloc> iterator; typedef _Rope_const_iterator<_CharT, _Alloc> const_iterator; typedef _Rope_char_ref_proxy<_CharT, _Alloc> reference; typedef _Rope_char_ptr_proxy<_CharT, _Alloc> pointer; friend class _Rope_iterator<_CharT, _Alloc>; friend class _Rope_const_iterator<_CharT, _Alloc>; friend struct _Rope_RopeRep<_CharT, _Alloc>; friend class _Rope_iterator_base<_CharT, _Alloc>; friend class _Rope_char_ptr_proxy<_CharT, _Alloc>; friend class _Rope_char_ref_proxy<_CharT, _Alloc>; friend struct _Rope_RopeSubstring<_CharT, _Alloc>; protected: typedef _Rope_base<_CharT, _Alloc> _Base; typedef typename _Base::allocator_type allocator_type; using _Base::_M_tree_ptr; using _Base::get_allocator; using _Base::_M_get_allocator; typedef __GC_CONST _CharT* _Cstrptr; static _CharT _S_empty_c_str[1]; static bool _S_is0(_CharT __c) { return __c == _S_eos((_CharT*)0); } enum { _S_copy_max = 23 }; // For strings shorter than _S_copy_max, we copy to // concatenate. typedef _Rope_RopeRep<_CharT, _Alloc> _RopeRep; typedef _Rope_RopeConcatenation<_CharT, _Alloc> _RopeConcatenation; typedef _Rope_RopeLeaf<_CharT, _Alloc> _RopeLeaf; typedef _Rope_RopeFunction<_CharT, _Alloc> _RopeFunction; typedef _Rope_RopeSubstring<_CharT, _Alloc> _RopeSubstring; // Retrieve a character at the indicated position. static _CharT _S_fetch(_RopeRep* __r, size_type __pos); #ifndef __GC // Obtain a pointer to the character at the indicated position. // The pointer can be used to change the character. // If such a pointer cannot be produced, as is frequently the // case, 0 is returned instead. // (Returns nonzero only if all nodes in the path have a refcount // of 1.) static _CharT* _S_fetch_ptr(_RopeRep* __r, size_type __pos); #endif static bool _S_apply_to_pieces(// should be template parameter _Rope_char_consumer<_CharT>& __c, const _RopeRep* __r, size_t __begin, size_t __end); // begin and end are assumed to be in range. #ifndef __GC static void _S_unref(_RopeRep* __t) { _RopeRep::_S_unref(__t); } static void _S_ref(_RopeRep* __t) { _RopeRep::_S_ref(__t); } #else /* __GC */ static void _S_unref(_RopeRep*) { } static void _S_ref(_RopeRep*) { } #endif #ifdef __GC typedef _Rope_RopeRep<_CharT, _Alloc>* _Self_destruct_ptr; #else typedef _Rope_self_destruct_ptr<_CharT, _Alloc> _Self_destruct_ptr; #endif // _Result is counted in refcount. static _RopeRep* _S_substring(_RopeRep* __base, size_t __start, size_t __endp1); static _RopeRep* _S_concat_char_iter(_RopeRep* __r, const _CharT* __iter, size_t __slen); // Concatenate rope and char ptr, copying __s. // Should really take an arbitrary iterator. // Result is counted in refcount. static _RopeRep* _S_destr_concat_char_iter(_RopeRep* __r, const _CharT* __iter, size_t __slen) // As above, but one reference to __r is about to be // destroyed. Thus the pieces may be recycled if all // relevant reference counts are 1. #ifdef __GC // We can't really do anything since refcounts are unavailable. { return _S_concat_char_iter(__r, __iter, __slen); } #else ; #endif static _RopeRep* _S_concat(_RopeRep* __left, _RopeRep* __right); // General concatenation on _RopeRep. _Result // has refcount of 1. Adjusts argument refcounts. public: void apply_to_pieces(size_t __begin, size_t __end, _Rope_char_consumer<_CharT>& __c) const { _S_apply_to_pieces(__c, this->_M_tree_ptr, __begin, __end); } protected: static size_t _S_rounded_up_size(size_t __n) { return _RopeLeaf::_S_rounded_up_size(__n); } static size_t _S_allocated_capacity(size_t __n) { if (_S_is_basic_char_type((_CharT*)0)) return _S_rounded_up_size(__n) - 1; else return _S_rounded_up_size(__n); } // Allocate and construct a RopeLeaf using the supplied allocator // Takes ownership of s instead of copying. static _RopeLeaf* _S_new_RopeLeaf(__GC_CONST _CharT *__s, size_t __size, allocator_type& __a) { _RopeLeaf* __space = typename _Base::_LAlloc(__a).allocate(1); return new(__space) _RopeLeaf(__s, __size, __a); } static _RopeConcatenation* _S_new_RopeConcatenation(_RopeRep* __left, _RopeRep* __right, allocator_type& __a) { _RopeConcatenation* __space = typename _Base::_CAlloc(__a).allocate(1); return new(__space) _RopeConcatenation(__left, __right, __a); } static _RopeFunction* _S_new_RopeFunction(char_producer<_CharT>* __f, size_t __size, bool __d, allocator_type& __a) { _RopeFunction* __space = typename _Base::_FAlloc(__a).allocate(1); return new(__space) _RopeFunction(__f, __size, __d, __a); } static _RopeSubstring* _S_new_RopeSubstring(_Rope_RopeRep<_CharT,_Alloc>* __b, size_t __s, size_t __l, allocator_type& __a) { _RopeSubstring* __space = typename _Base::_SAlloc(__a).allocate(1); return new(__space) _RopeSubstring(__b, __s, __l, __a); } static _RopeLeaf* _S_RopeLeaf_from_unowned_char_ptr(const _CharT *__s, size_t __size, allocator_type& __a) #define __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __size, __a) \ _S_RopeLeaf_from_unowned_char_ptr(__s, __size, __a) { if (0 == __size) return 0; _CharT* __buf = __a.allocate(_S_rounded_up_size(__size)); __uninitialized_copy_n_a(__s, __size, __buf, __a); _S_cond_store_eos(__buf[__size]); __try { return _S_new_RopeLeaf(__buf, __size, __a); } __catch(...) { _RopeRep::__STL_FREE_STRING(__buf, __size, __a); __throw_exception_again; } } // Concatenation of nonempty strings. // Always builds a concatenation node. // Rebalances if the result is too deep. // Result has refcount 1. // Does not increment left and right ref counts even though // they are referenced. static _RopeRep* _S_tree_concat(_RopeRep* __left, _RopeRep* __right); // Concatenation helper functions static _RopeLeaf* _S_leaf_concat_char_iter(_RopeLeaf* __r, const _CharT* __iter, size_t __slen); // Concatenate by copying leaf. // should take an arbitrary iterator // result has refcount 1. #ifndef __GC static _RopeLeaf* _S_destr_leaf_concat_char_iter(_RopeLeaf* __r, const _CharT* __iter, size_t __slen); // A version that potentially clobbers __r if __r->_M_ref_count == 1. #endif private: static size_t _S_char_ptr_len(const _CharT* __s); // slightly generalized strlen rope(_RopeRep* __t, const allocator_type& __a = allocator_type()) : _Base(__t, __a) { } // Copy __r to the _CharT buffer. // Returns __buffer + __r->_M_size. // Assumes that buffer is uninitialized. static _CharT* _S_flatten(_RopeRep* __r, _CharT* __buffer); // Again, with explicit starting position and length. // Assumes that buffer is uninitialized. static _CharT* _S_flatten(_RopeRep* __r, size_t __start, size_t __len, _CharT* __buffer); static const unsigned long _S_min_len[__detail::_S_max_rope_depth + 1]; static bool _S_is_balanced(_RopeRep* __r) { return (__r->_M_size >= _S_min_len[__r->_M_depth]); } static bool _S_is_almost_balanced(_RopeRep* __r) { return (__r->_M_depth == 0 || __r->_M_size >= _S_min_len[__r->_M_depth - 1]); } static bool _S_is_roughly_balanced(_RopeRep* __r) { return (__r->_M_depth <= 1 || __r->_M_size >= _S_min_len[__r->_M_depth - 2]); } // Assumes the result is not empty. static _RopeRep* _S_concat_and_set_balanced(_RopeRep* __left, _RopeRep* __right) { _RopeRep* __result = _S_concat(__left, __right); if (_S_is_balanced(__result)) __result->_M_is_balanced = true; return __result; } // The basic rebalancing operation. Logically copies the // rope. The result has refcount of 1. The client will // usually decrement the reference count of __r. // The result is within height 2 of balanced by the above // definition. static _RopeRep* _S_balance(_RopeRep* __r); // Add all unbalanced subtrees to the forest of balanced trees. // Used only by balance. static void _S_add_to_forest(_RopeRep*__r, _RopeRep** __forest); // Add __r to forest, assuming __r is already balanced. static void _S_add_leaf_to_forest(_RopeRep* __r, _RopeRep** __forest); // Print to stdout, exposing structure static void _S_dump(_RopeRep* __r, int __indent = 0); // Return -1, 0, or 1 if __x < __y, __x == __y, or __x > __y resp. static int _S_compare(const _RopeRep* __x, const _RopeRep* __y); public: bool empty() const { return 0 == this->_M_tree_ptr; } // Comparison member function. This is public only for those // clients that need a ternary comparison. Others // should use the comparison operators below. int compare(const rope& __y) const { return _S_compare(this->_M_tree_ptr, __y._M_tree_ptr); } rope(const _CharT* __s, const allocator_type& __a = allocator_type()) : _Base(__a) { this->_M_tree_ptr = __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, _S_char_ptr_len(__s), _M_get_allocator()); } rope(const _CharT* __s, size_t __len, const allocator_type& __a = allocator_type()) : _Base(__a) { this->_M_tree_ptr = __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __len, _M_get_allocator()); } // Should perhaps be templatized with respect to the iterator type // and use Sequence_buffer. (It should perhaps use sequence_buffer // even now.) rope(const _CharT* __s, const _CharT* __e, const allocator_type& __a = allocator_type()) : _Base(__a) { this->_M_tree_ptr = __STL_ROPE_FROM_UNOWNED_CHAR_PTR(__s, __e - __s, _M_get_allocator()); } rope(const const_iterator& __s, const const_iterator& __e, const allocator_type& __a = allocator_type()) : _Base(_S_substring(__s._M_root, __s._M_current_pos, __e._M_current_pos), __a) { } rope(const iterator& __s, const iterator& __e, const allocator_type& __a = allocator_type()) : _Base(_S_substring(__s._M_root, __s._M_current_pos, __e._M_current_pos), __a) { } rope(_CharT __c, const allocator_type& __a = allocator_type()) : _Base(__a) { _CharT* __buf = this->_Data_allocate(_S_rounded_up_size(1)); _M_get_allocator().construct(__buf, __c); __try { this->_M_tree_ptr = _S_new_RopeLeaf(__buf, 1, _M_get_allocator()); } __catch(...) { _RopeRep::__STL_FREE_STRING(__buf, 1, _M_get_allocator()); __throw_exception_again; } } rope(size_t __n, _CharT __c, const allocator_type& __a = allocator_type()); rope(const allocator_type& __a = allocator_type()) : _Base(0, __a) { } // Construct a rope from a function that can compute its members rope(char_producer<_CharT> *__fn, size_t __len, bool __delete_fn, const allocator_type& __a = allocator_type()) : _Base(__a) { this->_M_tree_ptr = (0 == __len) ? 0 : _S_new_RopeFunction(__fn, __len, __delete_fn, _M_get_allocator()); } rope(const rope& __x, const allocator_type& __a = allocator_type()) : _Base(__x._M_tree_ptr, __a) { _S_ref(this->_M_tree_ptr); } ~rope() throw() { _S_unref(this->_M_tree_ptr); } rope& operator=(const rope& __x) { _RopeRep* __old = this->_M_tree_ptr; this->_M_tree_ptr = __x._M_tree_ptr; _S_ref(this->_M_tree_ptr); _S_unref(__old); return *this; } void clear() { _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = 0; } void push_back(_CharT __x) { _RopeRep* __old = this->_M_tree_ptr; this->_M_tree_ptr = _S_destr_concat_char_iter(this->_M_tree_ptr, &__x, 1); _S_unref(__old); } void pop_back() { _RopeRep* __old = this->_M_tree_ptr; this->_M_tree_ptr = _S_substring(this->_M_tree_ptr, 0, this->_M_tree_ptr->_M_size - 1); _S_unref(__old); } _CharT back() const { return _S_fetch(this->_M_tree_ptr, this->_M_tree_ptr->_M_size - 1); } void push_front(_CharT __x) { _RopeRep* __old = this->_M_tree_ptr; _RopeRep* __left = __STL_ROPE_FROM_UNOWNED_CHAR_PTR(&__x, 1, _M_get_allocator()); __try { this->_M_tree_ptr = _S_concat(__left, this->_M_tree_ptr); _S_unref(__old); _S_unref(__left); } __catch(...) { _S_unref(__left); __throw_exception_again; } } void pop_front() { _RopeRep* __old = this->_M_tree_ptr; this->_M_tree_ptr = _S_substring(this->_M_tree_ptr, 1, this->_M_tree_ptr->_M_size); _S_unref(__old); } _CharT front() const { return _S_fetch(this->_M_tree_ptr, 0); } void balance() { _RopeRep* __old = this->_M_tree_ptr; this->_M_tree_ptr = _S_balance(this->_M_tree_ptr); _S_unref(__old); } void copy(_CharT* __buffer) const { _Destroy_const(__buffer, __buffer + size(), _M_get_allocator()); _S_flatten(this->_M_tree_ptr, __buffer); } // This is the copy function from the standard, but // with the arguments reordered to make it consistent with the // rest of the interface. // Note that this guaranteed not to compile if the draft standard // order is assumed. size_type copy(size_type __pos, size_type __n, _CharT* __buffer) const { size_t __size = size(); size_t __len = (__pos + __n > __size? __size - __pos : __n); _Destroy_const(__buffer, __buffer + __len, _M_get_allocator()); _S_flatten(this->_M_tree_ptr, __pos, __len, __buffer); return __len; } // Print to stdout, exposing structure. May be useful for // performance debugging. void dump() { _S_dump(this->_M_tree_ptr); } // Convert to 0 terminated string in new allocated memory. // Embedded 0s in the input do not terminate the copy. const _CharT* c_str() const; // As above, but also use the flattened representation as // the new rope representation. const _CharT* replace_with_c_str(); // Reclaim memory for the c_str generated flattened string. // Intentionally undocumented, since it's hard to say when this // is safe for multiple threads. void delete_c_str () { if (0 == this->_M_tree_ptr) return; if (__detail::_S_leaf == this->_M_tree_ptr->_M_tag && ((_RopeLeaf*)this->_M_tree_ptr)->_M_data == this->_M_tree_ptr->_M_c_string) { // Representation shared return; } #ifndef __GC this->_M_tree_ptr->_M_free_c_string(); #endif this->_M_tree_ptr->_M_c_string = 0; } _CharT operator[] (size_type __pos) const { return _S_fetch(this->_M_tree_ptr, __pos); } _CharT at(size_type __pos) const { // if (__pos >= size()) throw out_of_range; // XXX return (*this)[__pos]; } const_iterator begin() const { return(const_iterator(this->_M_tree_ptr, 0)); } // An easy way to get a const iterator from a non-const container. const_iterator const_begin() const { return(const_iterator(this->_M_tree_ptr, 0)); } const_iterator end() const { return(const_iterator(this->_M_tree_ptr, size())); } const_iterator const_end() const { return(const_iterator(this->_M_tree_ptr, size())); } size_type size() const { return(0 == this->_M_tree_ptr? 0 : this->_M_tree_ptr->_M_size); } size_type length() const { return size(); } size_type max_size() const { return _S_min_len[int(__detail::_S_max_rope_depth) - 1] - 1; // Guarantees that the result can be sufficiently // balanced. Longer ropes will probably still work, // but it's harder to make guarantees. } typedef std::reverse_iterator const_reverse_iterator; const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator const_rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } const_reverse_iterator const_rend() const { return const_reverse_iterator(begin()); } template friend rope<_CharT2, _Alloc2> operator+(const rope<_CharT2, _Alloc2>& __left, const rope<_CharT2, _Alloc2>& __right); template friend rope<_CharT2, _Alloc2> operator+(const rope<_CharT2, _Alloc2>& __left, const _CharT2* __right); template friend rope<_CharT2, _Alloc2> operator+(const rope<_CharT2, _Alloc2>& __left, _CharT2 __right); // The symmetric cases are intentionally omitted, since they're // presumed to be less common, and we don't handle them as well. // The following should really be templatized. The first // argument should be an input iterator or forward iterator with // value_type _CharT. rope& append(const _CharT* __iter, size_t __n) { _RopeRep* __result = _S_destr_concat_char_iter(this->_M_tree_ptr, __iter, __n); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; return *this; } rope& append(const _CharT* __c_string) { size_t __len = _S_char_ptr_len(__c_string); append(__c_string, __len); return(*this); } rope& append(const _CharT* __s, const _CharT* __e) { _RopeRep* __result = _S_destr_concat_char_iter(this->_M_tree_ptr, __s, __e - __s); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; return *this; } rope& append(const_iterator __s, const_iterator __e) { _Self_destruct_ptr __appendee(_S_substring(__s._M_root, __s._M_current_pos, __e._M_current_pos)); _RopeRep* __result = _S_concat(this->_M_tree_ptr, (_RopeRep*)__appendee); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; return *this; } rope& append(_CharT __c) { _RopeRep* __result = _S_destr_concat_char_iter(this->_M_tree_ptr, &__c, 1); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; return *this; } rope& append() { return append(_CharT()); } // XXX why? rope& append(const rope& __y) { _RopeRep* __result = _S_concat(this->_M_tree_ptr, __y._M_tree_ptr); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; return *this; } rope& append(size_t __n, _CharT __c) { rope<_CharT,_Alloc> __last(__n, __c); return append(__last); } void swap(rope& __b) { _RopeRep* __tmp = this->_M_tree_ptr; this->_M_tree_ptr = __b._M_tree_ptr; __b._M_tree_ptr = __tmp; } protected: // Result is included in refcount. static _RopeRep* replace(_RopeRep* __old, size_t __pos1, size_t __pos2, _RopeRep* __r) { if (0 == __old) { _S_ref(__r); return __r; } _Self_destruct_ptr __left(_S_substring(__old, 0, __pos1)); _Self_destruct_ptr __right(_S_substring(__old, __pos2, __old->_M_size)); _RopeRep* __result; if (0 == __r) __result = _S_concat(__left, __right); else { _Self_destruct_ptr __left_result(_S_concat(__left, __r)); __result = _S_concat(__left_result, __right); } return __result; } public: void insert(size_t __p, const rope& __r) { _RopeRep* __result = replace(this->_M_tree_ptr, __p, __p, __r._M_tree_ptr); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; } void insert(size_t __p, size_t __n, _CharT __c) { rope<_CharT,_Alloc> __r(__n,__c); insert(__p, __r); } void insert(size_t __p, const _CharT* __i, size_t __n) { _Self_destruct_ptr __left(_S_substring(this->_M_tree_ptr, 0, __p)); _Self_destruct_ptr __right(_S_substring(this->_M_tree_ptr, __p, size())); _Self_destruct_ptr __left_result(_S_concat_char_iter(__left, __i, __n)); // _S_ destr_concat_char_iter should be safe here. // But as it stands it's probably not a win, since __left // is likely to have additional references. _RopeRep* __result = _S_concat(__left_result, __right); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; } void insert(size_t __p, const _CharT* __c_string) { insert(__p, __c_string, _S_char_ptr_len(__c_string)); } void insert(size_t __p, _CharT __c) { insert(__p, &__c, 1); } void insert(size_t __p) { _CharT __c = _CharT(); insert(__p, &__c, 1); } void insert(size_t __p, const _CharT* __i, const _CharT* __j) { rope __r(__i, __j); insert(__p, __r); } void insert(size_t __p, const const_iterator& __i, const const_iterator& __j) { rope __r(__i, __j); insert(__p, __r); } void insert(size_t __p, const iterator& __i, const iterator& __j) { rope __r(__i, __j); insert(__p, __r); } // (position, length) versions of replace operations: void replace(size_t __p, size_t __n, const rope& __r) { _RopeRep* __result = replace(this->_M_tree_ptr, __p, __p + __n, __r._M_tree_ptr); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; } void replace(size_t __p, size_t __n, const _CharT* __i, size_t __i_len) { rope __r(__i, __i_len); replace(__p, __n, __r); } void replace(size_t __p, size_t __n, _CharT __c) { rope __r(__c); replace(__p, __n, __r); } void replace(size_t __p, size_t __n, const _CharT* __c_string) { rope __r(__c_string); replace(__p, __n, __r); } void replace(size_t __p, size_t __n, const _CharT* __i, const _CharT* __j) { rope __r(__i, __j); replace(__p, __n, __r); } void replace(size_t __p, size_t __n, const const_iterator& __i, const const_iterator& __j) { rope __r(__i, __j); replace(__p, __n, __r); } void replace(size_t __p, size_t __n, const iterator& __i, const iterator& __j) { rope __r(__i, __j); replace(__p, __n, __r); } // Single character variants: void replace(size_t __p, _CharT __c) { iterator __i(this, __p); *__i = __c; } void replace(size_t __p, const rope& __r) { replace(__p, 1, __r); } void replace(size_t __p, const _CharT* __i, size_t __i_len) { replace(__p, 1, __i, __i_len); } void replace(size_t __p, const _CharT* __c_string) { replace(__p, 1, __c_string); } void replace(size_t __p, const _CharT* __i, const _CharT* __j) { replace(__p, 1, __i, __j); } void replace(size_t __p, const const_iterator& __i, const const_iterator& __j) { replace(__p, 1, __i, __j); } void replace(size_t __p, const iterator& __i, const iterator& __j) { replace(__p, 1, __i, __j); } // Erase, (position, size) variant. void erase(size_t __p, size_t __n) { _RopeRep* __result = replace(this->_M_tree_ptr, __p, __p + __n, 0); _S_unref(this->_M_tree_ptr); this->_M_tree_ptr = __result; } // Erase, single character void erase(size_t __p) { erase(__p, __p + 1); } // Insert, iterator variants. iterator insert(const iterator& __p, const rope& __r) { insert(__p.index(), __r); return __p; } iterator insert(const iterator& __p, size_t __n, _CharT __c) { insert(__p.index(), __n, __c); return __p; } iterator insert(const iterator& __p, _CharT __c) { insert(__p.index(), __c); return __p; } iterator insert(const iterator& __p ) { insert(__p.index()); return __p; } iterator insert(const iterator& __p, const _CharT* c_string) { insert(__p.index(), c_string); return __p; } iterator insert(const iterator& __p, const _CharT* __i, size_t __n) { insert(__p.index(), __i, __n); return __p; } iterator insert(const iterator& __p, const _CharT* __i, const _CharT* __j) { insert(__p.index(), __i, __j); return __p; } iterator insert(const iterator& __p, const const_iterator& __i, const const_iterator& __j) { insert(__p.index(), __i, __j); return __p; } iterator insert(const iterator& __p, const iterator& __i, const iterator& __j) { insert(__p.index(), __i, __j); return __p; } // Replace, range variants. void replace(const iterator& __p, const iterator& __q, const rope& __r) { replace(__p.index(), __q.index() - __p.index(), __r); } void replace(const iterator& __p, const iterator& __q, _CharT __c) { replace(__p.index(), __q.index() - __p.index(), __c); } void replace(const iterator& __p, const iterator& __q, const _CharT* __c_string) { replace(__p.index(), __q.index() - __p.index(), __c_string); } void replace(const iterator& __p, const iterator& __q, const _CharT* __i, size_t __n) { replace(__p.index(), __q.index() - __p.index(), __i, __n); } void replace(const iterator& __p, const iterator& __q, const _CharT* __i, const _CharT* __j) { replace(__p.index(), __q.index() - __p.index(), __i, __j); } void replace(const iterator& __p, const iterator& __q, const const_iterator& __i, const const_iterator& __j) { replace(__p.index(), __q.index() - __p.index(), __i, __j); } void replace(const iterator& __p, const iterator& __q, const iterator& __i, const iterator& __j) { replace(__p.index(), __q.index() - __p.index(), __i, __j); } // Replace, iterator variants. void replace(const iterator& __p, const rope& __r) { replace(__p.index(), __r); } void replace(const iterator& __p, _CharT __c) { replace(__p.index(), __c); } void replace(const iterator& __p, const _CharT* __c_string) { replace(__p.index(), __c_string); } void replace(const iterator& __p, const _CharT* __i, size_t __n) { replace(__p.index(), __i, __n); } void replace(const iterator& __p, const _CharT* __i, const _CharT* __j) { replace(__p.index(), __i, __j); } void replace(const iterator& __p, const_iterator __i, const_iterator __j) { replace(__p.index(), __i, __j); } void replace(const iterator& __p, iterator __i, iterator __j) { replace(__p.index(), __i, __j); } // Iterator and range variants of erase iterator erase(const iterator& __p, const iterator& __q) { size_t __p_index = __p.index(); erase(__p_index, __q.index() - __p_index); return iterator(this, __p_index); } iterator erase(const iterator& __p) { size_t __p_index = __p.index(); erase(__p_index, 1); return iterator(this, __p_index); } rope substr(size_t __start, size_t __len = 1) const { return rope<_CharT, _Alloc>(_S_substring(this->_M_tree_ptr, __start, __start + __len)); } rope substr(iterator __start, iterator __end) const { return rope<_CharT, _Alloc>(_S_substring(this->_M_tree_ptr, __start.index(), __end.index())); } rope substr(iterator __start) const { size_t __pos = __start.index(); return rope<_CharT, _Alloc>(_S_substring(this->_M_tree_ptr, __pos, __pos + 1)); } rope substr(const_iterator __start, const_iterator __end) const { // This might eventually take advantage of the cache in the // iterator. return rope<_CharT, _Alloc>(_S_substring(this->_M_tree_ptr, __start.index(), __end.index())); } rope<_CharT, _Alloc> substr(const_iterator __start) { size_t __pos = __start.index(); return rope<_CharT, _Alloc>(_S_substring(this->_M_tree_ptr, __pos, __pos + 1)); } static const size_type npos; size_type find(_CharT __c, size_type __pos = 0) const; size_type find(const _CharT* __s, size_type __pos = 0) const { size_type __result_pos; const_iterator __result = std::search(const_begin() + __pos, const_end(), __s, __s + _S_char_ptr_len(__s)); __result_pos = __result.index(); #ifndef __STL_OLD_ROPE_SEMANTICS if (__result_pos == size()) __result_pos = npos; #endif return __result_pos; } iterator mutable_begin() { return(iterator(this, 0)); } iterator mutable_end() { return(iterator(this, size())); } typedef std::reverse_iterator reverse_iterator; reverse_iterator mutable_rbegin() { return reverse_iterator(mutable_end()); } reverse_iterator mutable_rend() { return reverse_iterator(mutable_begin()); } reference mutable_reference_at(size_type __pos) { return reference(this, __pos); } #ifdef __STD_STUFF reference operator[] (size_type __pos) { return _char_ref_proxy(this, __pos); } reference at(size_type __pos) { // if (__pos >= size()) throw out_of_range; // XXX return (*this)[__pos]; } void resize(size_type __n, _CharT __c) { } void resize(size_type __n) { } void reserve(size_type __res_arg = 0) { } size_type capacity() const { return max_size(); } // Stuff below this line is dangerous because it's error prone. // I would really like to get rid of it. // copy function with funny arg ordering. size_type copy(_CharT* __buffer, size_type __n, size_type __pos = 0) const { return copy(__pos, __n, __buffer); } iterator end() { return mutable_end(); } iterator begin() { return mutable_begin(); } reverse_iterator rend() { return mutable_rend(); } reverse_iterator rbegin() { return mutable_rbegin(); } #else const_iterator end() { return const_end(); } const_iterator begin() { return const_begin(); } const_reverse_iterator rend() { return const_rend(); } const_reverse_iterator rbegin() { return const_rbegin(); } #endif }; template const typename rope<_CharT, _Alloc>::size_type rope<_CharT, _Alloc>::npos = (size_type)(-1); template inline bool operator==(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return (__x._M_current_pos == __y._M_current_pos && __x._M_root == __y._M_root); } template inline bool operator<(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return (__x._M_current_pos < __y._M_current_pos); } template inline bool operator!=(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return !(__x == __y); } template inline bool operator>(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return __y < __x; } template inline bool operator<=(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return !(__y < __x); } template inline bool operator>=(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return !(__x < __y); } template inline ptrdiff_t operator-(const _Rope_const_iterator<_CharT, _Alloc>& __x, const _Rope_const_iterator<_CharT, _Alloc>& __y) { return (ptrdiff_t)__x._M_current_pos - (ptrdiff_t)__y._M_current_pos; } template inline _Rope_const_iterator<_CharT, _Alloc> operator-(const _Rope_const_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n) { return _Rope_const_iterator<_CharT, _Alloc>(__x._M_root, __x._M_current_pos - __n); } template inline _Rope_const_iterator<_CharT, _Alloc> operator+(const _Rope_const_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n) { return _Rope_const_iterator<_CharT, _Alloc>(__x._M_root, __x._M_current_pos + __n); } template inline _Rope_const_iterator<_CharT, _Alloc> operator+(ptrdiff_t __n, const _Rope_const_iterator<_CharT, _Alloc>& __x) { return _Rope_const_iterator<_CharT, _Alloc>(__x._M_root, __x._M_current_pos + __n); } template inline bool operator==(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) {return (__x._M_current_pos == __y._M_current_pos && __x._M_root_rope == __y._M_root_rope); } template inline bool operator<(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) { return (__x._M_current_pos < __y._M_current_pos); } template inline bool operator!=(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) { return !(__x == __y); } template inline bool operator>(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) { return __y < __x; } template inline bool operator<=(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) { return !(__y < __x); } template inline bool operator>=(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) { return !(__x < __y); } template inline ptrdiff_t operator-(const _Rope_iterator<_CharT, _Alloc>& __x, const _Rope_iterator<_CharT, _Alloc>& __y) { return ((ptrdiff_t)__x._M_current_pos - (ptrdiff_t)__y._M_current_pos); } template inline _Rope_iterator<_CharT, _Alloc> operator-(const _Rope_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n) { return _Rope_iterator<_CharT, _Alloc>(__x._M_root_rope, __x._M_current_pos - __n); } template inline _Rope_iterator<_CharT, _Alloc> operator+(const _Rope_iterator<_CharT, _Alloc>& __x, ptrdiff_t __n) { return _Rope_iterator<_CharT, _Alloc>(__x._M_root_rope, __x._M_current_pos + __n); } template inline _Rope_iterator<_CharT, _Alloc> operator+(ptrdiff_t __n, const _Rope_iterator<_CharT, _Alloc>& __x) { return _Rope_iterator<_CharT, _Alloc>(__x._M_root_rope, __x._M_current_pos + __n); } template inline rope<_CharT, _Alloc> operator+(const rope<_CharT, _Alloc>& __left, const rope<_CharT, _Alloc>& __right) { // Inlining this should make it possible to keep __left and // __right in registers. typedef rope<_CharT, _Alloc> rope_type; return rope_type(rope_type::_S_concat(__left._M_tree_ptr, __right._M_tree_ptr)); } template inline rope<_CharT, _Alloc>& operator+=(rope<_CharT, _Alloc>& __left, const rope<_CharT, _Alloc>& __right) { __left.append(__right); return __left; } template inline rope<_CharT, _Alloc> operator+(const rope<_CharT, _Alloc>& __left, const _CharT* __right) { typedef rope<_CharT, _Alloc> rope_type; size_t __rlen = rope_type::_S_char_ptr_len(__right); return rope_type(rope_type::_S_concat_char_iter(__left._M_tree_ptr, __right, __rlen)); } template inline rope<_CharT, _Alloc>& operator+=(rope<_CharT, _Alloc>& __left, const _CharT* __right) { __left.append(__right); return __left; } template inline rope<_CharT, _Alloc> operator+(const rope<_CharT, _Alloc>& __left, _CharT __right) { typedef rope<_CharT, _Alloc> rope_type; return rope_type(rope_type::_S_concat_char_iter(__left._M_tree_ptr, &__right, 1)); } template inline rope<_CharT, _Alloc>& operator+=(rope<_CharT, _Alloc>& __left, _CharT __right) { __left.append(__right); return __left; } template bool operator<(const rope<_CharT, _Alloc>& __left, const rope<_CharT, _Alloc>& __right) { return __left.compare(__right) < 0; } template bool operator==(const rope<_CharT, _Alloc>& __left, const rope<_CharT, _Alloc>& __right) { return __left.compare(__right) == 0; } template inline bool operator==(const _Rope_char_ptr_proxy<_CharT, _Alloc>& __x, const _Rope_char_ptr_proxy<_CharT, _Alloc>& __y) { return (__x._M_pos == __y._M_pos && __x._M_root == __y._M_root); } template inline bool operator!=(const rope<_CharT, _Alloc>& __x, const rope<_CharT, _Alloc>& __y) { return !(__x == __y); } template inline bool operator>(const rope<_CharT, _Alloc>& __x, const rope<_CharT, _Alloc>& __y) { return __y < __x; } template inline bool operator<=(const rope<_CharT, _Alloc>& __x, const rope<_CharT, _Alloc>& __y) { return !(__y < __x); } template inline bool operator>=(const rope<_CharT, _Alloc>& __x, const rope<_CharT, _Alloc>& __y) { return !(__x < __y); } template inline bool operator!=(const _Rope_char_ptr_proxy<_CharT, _Alloc>& __x, const _Rope_char_ptr_proxy<_CharT, _Alloc>& __y) { return !(__x == __y); } template std::basic_ostream<_CharT, _Traits>& operator<<(std::basic_ostream<_CharT, _Traits>& __o, const rope<_CharT, _Alloc>& __r); typedef rope crope; typedef rope wrope; inline crope::reference __mutable_reference_at(crope& __c, size_t __i) { return __c.mutable_reference_at(__i); } inline wrope::reference __mutable_reference_at(wrope& __c, size_t __i) { return __c.mutable_reference_at(__i); } template inline void swap(rope<_CharT, _Alloc>& __x, rope<_CharT, _Alloc>& __y) { __x.swap(__y); } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION namespace tr1 { template<> struct hash<__gnu_cxx::crope> { size_t operator()(const __gnu_cxx::crope& __str) const { size_t __size = __str.size(); if (0 == __size) return 0; return 13 * __str[0] + 5 * __str[__size - 1] + __size; } }; template<> struct hash<__gnu_cxx::wrope> { size_t operator()(const __gnu_cxx::wrope& __str) const { size_t __size = __str.size(); if (0 == __size) return 0; return 13 * __str[0] + 5 * __str[__size - 1] + __size; } }; } // namespace tr1 _GLIBCXX_END_NAMESPACE_VERSION } // namespace std # include #endif c++/8/ext/pod_char_traits.h000064400000012664151027430570011416 0ustar00// POD character, std::char_traits specialization -*- C++ -*- // Copyright (C) 2002-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/pod_char_traits.h * This file is a GNU extension to the Standard C++ Library. */ // Gabriel Dos Reis // Benjamin Kosnik #ifndef _POD_CHAR_TRAITS_H #define _POD_CHAR_TRAITS_H 1 #pragma GCC system_header #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION // POD character abstraction. // NB: The char_type parameter is a subset of int_type, as to allow // int_type to properly hold the full range of char_type values as // well as EOF. /// @brief A POD class that serves as a character abstraction class. template struct character { typedef _Value value_type; typedef _Int int_type; typedef _St state_type; typedef character<_Value, _Int, _St> char_type; value_type value; template static char_type from(const V2& v) { char_type ret = { static_cast(v) }; return ret; } template static V2 to(const char_type& c) { V2 ret = { static_cast(c.value) }; return ret; } }; template inline bool operator==(const character<_Value, _Int, _St>& lhs, const character<_Value, _Int, _St>& rhs) { return lhs.value == rhs.value; } template inline bool operator<(const character<_Value, _Int, _St>& lhs, const character<_Value, _Int, _St>& rhs) { return lhs.value < rhs.value; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /// char_traits<__gnu_cxx::character> specialization. template struct char_traits<__gnu_cxx::character<_Value, _Int, _St> > { typedef __gnu_cxx::character<_Value, _Int, _St> char_type; typedef typename char_type::int_type int_type; typedef typename char_type::state_type state_type; typedef fpos pos_type; typedef streamoff off_type; static void assign(char_type& __c1, const char_type& __c2) { __c1 = __c2; } static bool eq(const char_type& __c1, const char_type& __c2) { return __c1 == __c2; } static bool lt(const char_type& __c1, const char_type& __c2) { return __c1 < __c2; } static int compare(const char_type* __s1, const char_type* __s2, size_t __n) { for (size_t __i = 0; __i < __n; ++__i) if (!eq(__s1[__i], __s2[__i])) return lt(__s1[__i], __s2[__i]) ? -1 : 1; return 0; } static size_t length(const char_type* __s) { const char_type* __p = __s; while (__p->value) ++__p; return (__p - __s); } static const char_type* find(const char_type* __s, size_t __n, const char_type& __a) { for (const char_type* __p = __s; size_t(__p - __s) < __n; ++__p) if (*__p == __a) return __p; return 0; } static char_type* move(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; return static_cast (__builtin_memmove(__s1, __s2, __n * sizeof(char_type))); } static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n) { if (__n == 0) return __s1; std::copy(__s2, __s2 + __n, __s1); return __s1; } static char_type* assign(char_type* __s, size_t __n, char_type __a) { std::fill_n(__s, __n, __a); return __s; } static char_type to_char_type(const int_type& __i) { return char_type::template from(__i); } static int_type to_int_type(const char_type& __c) { return char_type::template to(__c); } static bool eq_int_type(const int_type& __c1, const int_type& __c2) { return __c1 == __c2; } static int_type eof() { int_type __r = { static_cast::__value, int_type, int>::__type>(-1) }; return __r; } static int_type not_eof(const int_type& __c) { return eq_int_type(__c, eof()) ? int_type() : __c; } }; _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/ext/codecvt_specializations.h000064400000037741151027430570013164 0ustar00// Locale support (codecvt) -*- C++ -*- // Copyright (C) 2000-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . // // ISO C++ 14882: 22.2.1.5 Template class codecvt // // Written by Benjamin Kosnik /** @file ext/codecvt_specializations.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _EXT_CODECVT_SPECIALIZATIONS_H #define _EXT_CODECVT_SPECIALIZATIONS_H 1 #include #include #include namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION _GLIBCXX_BEGIN_NAMESPACE_CXX11 /// Extension to use iconv for dealing with character encodings. // This includes conversions and comparisons between various character // sets. This object encapsulates data that may need to be shared between // char_traits, codecvt and ctype. class encoding_state { public: // Types: // NB: A conversion descriptor subsumes and enhances the // functionality of a simple state type such as mbstate_t. typedef iconv_t descriptor_type; protected: // Name of internal character set encoding. std::string _M_int_enc; // Name of external character set encoding. std::string _M_ext_enc; // Conversion descriptor between external encoding to internal encoding. descriptor_type _M_in_desc; // Conversion descriptor between internal encoding to external encoding. descriptor_type _M_out_desc; // The byte-order marker for the external encoding, if necessary. int _M_ext_bom; // The byte-order marker for the internal encoding, if necessary. int _M_int_bom; // Number of external bytes needed to construct one complete // character in the internal encoding. // NB: -1 indicates variable, or stateful, encodings. int _M_bytes; public: explicit encoding_state() : _M_in_desc(0), _M_out_desc(0), _M_ext_bom(0), _M_int_bom(0), _M_bytes(0) { } explicit encoding_state(const char* __int, const char* __ext, int __ibom = 0, int __ebom = 0, int __bytes = 1) : _M_int_enc(__int), _M_ext_enc(__ext), _M_in_desc(0), _M_out_desc(0), _M_ext_bom(__ebom), _M_int_bom(__ibom), _M_bytes(__bytes) { init(); } // 21.1.2 traits typedefs // p4 // typedef STATE_T state_type // requires: state_type shall meet the requirements of // CopyConstructible types (20.1.3) // NB: This does not preserve the actual state of the conversion // descriptor member, but it does duplicate the encoding // information. encoding_state(const encoding_state& __obj) : _M_in_desc(0), _M_out_desc(0) { construct(__obj); } // Need assignment operator as well. encoding_state& operator=(const encoding_state& __obj) { construct(__obj); return *this; } ~encoding_state() { destroy(); } bool good() const throw() { const descriptor_type __err = (iconv_t)(-1); bool __test = _M_in_desc && _M_in_desc != __err; __test &= _M_out_desc && _M_out_desc != __err; return __test; } int character_ratio() const { return _M_bytes; } const std::string internal_encoding() const { return _M_int_enc; } int internal_bom() const { return _M_int_bom; } const std::string external_encoding() const { return _M_ext_enc; } int external_bom() const { return _M_ext_bom; } const descriptor_type& in_descriptor() const { return _M_in_desc; } const descriptor_type& out_descriptor() const { return _M_out_desc; } protected: void init() { const descriptor_type __err = (iconv_t)(-1); const bool __have_encodings = _M_int_enc.size() && _M_ext_enc.size(); if (!_M_in_desc && __have_encodings) { _M_in_desc = iconv_open(_M_int_enc.c_str(), _M_ext_enc.c_str()); if (_M_in_desc == __err) std::__throw_runtime_error(__N("encoding_state::_M_init " "creating iconv input descriptor failed")); } if (!_M_out_desc && __have_encodings) { _M_out_desc = iconv_open(_M_ext_enc.c_str(), _M_int_enc.c_str()); if (_M_out_desc == __err) std::__throw_runtime_error(__N("encoding_state::_M_init " "creating iconv output descriptor failed")); } } void construct(const encoding_state& __obj) { destroy(); _M_int_enc = __obj._M_int_enc; _M_ext_enc = __obj._M_ext_enc; _M_ext_bom = __obj._M_ext_bom; _M_int_bom = __obj._M_int_bom; _M_bytes = __obj._M_bytes; init(); } void destroy() throw() { const descriptor_type __err = (iconv_t)(-1); if (_M_in_desc && _M_in_desc != __err) { iconv_close(_M_in_desc); _M_in_desc = 0; } if (_M_out_desc && _M_out_desc != __err) { iconv_close(_M_out_desc); _M_out_desc = 0; } } }; /// encoding_char_traits // Custom traits type with encoding_state for the state type, and the // associated fpos for the position type, all other // bits equivalent to the required char_traits instantiations. template struct encoding_char_traits : public std::char_traits<_CharT> { typedef encoding_state state_type; typedef typename std::fpos pos_type; }; _GLIBCXX_END_NAMESPACE_CXX11 _GLIBCXX_END_NAMESPACE_VERSION } // namespace namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using __gnu_cxx::encoding_state; /// codecvt specialization. // This partial specialization takes advantage of iconv to provide // code conversions between a large number of character encodings. template class codecvt<_InternT, _ExternT, encoding_state> : public __codecvt_abstract_base<_InternT, _ExternT, encoding_state> { public: // Types: typedef codecvt_base::result result; typedef _InternT intern_type; typedef _ExternT extern_type; typedef __gnu_cxx::encoding_state state_type; typedef state_type::descriptor_type descriptor_type; // Data Members: static locale::id id; explicit codecvt(size_t __refs = 0) : __codecvt_abstract_base(__refs) { } explicit codecvt(state_type& __enc, size_t __refs = 0) : __codecvt_abstract_base(__refs) { } protected: virtual ~codecvt() { } virtual result do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const; virtual result do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const; virtual int do_max_length() const throw(); }; template locale::id codecvt<_InternT, _ExternT, encoding_state>::id; // This adaptor works around the signature problems of the second // argument to iconv(): SUSv2 and others use 'const char**', but glibc 2.2 // uses 'char**', which matches the POSIX 1003.1-2001 standard. // Using this adaptor, g++ will do the work for us. template inline size_t __iconv_adaptor(size_t(*__func)(iconv_t, _Tp, size_t*, char**, size_t*), iconv_t __cd, char** __inbuf, size_t* __inbytes, char** __outbuf, size_t* __outbytes) { return __func(__cd, (_Tp)__inbuf, __inbytes, __outbuf, __outbytes); } template codecvt_base::result codecvt<_InternT, _ExternT, encoding_state>:: do_out(state_type& __state, const intern_type* __from, const intern_type* __from_end, const intern_type*& __from_next, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { result __ret = codecvt_base::error; if (__state.good()) { const descriptor_type& __desc = __state.out_descriptor(); const size_t __fmultiple = sizeof(intern_type); size_t __fbytes = __fmultiple * (__from_end - __from); const size_t __tmultiple = sizeof(extern_type); size_t __tbytes = __tmultiple * (__to_end - __to); // Argument list for iconv specifies a byte sequence. Thus, // all to/from arrays must be brutally casted to char*. char* __cto = reinterpret_cast(__to); char* __cfrom; size_t __conv; // Some encodings need a byte order marker as the first item // in the byte stream, to designate endian-ness. The default // value for the byte order marker is NULL, so if this is // the case, it's not necessary and we can just go on our // merry way. int __int_bom = __state.internal_bom(); if (__int_bom) { size_t __size = __from_end - __from; intern_type* __cfixed = static_cast (__builtin_alloca(sizeof(intern_type) * (__size + 1))); __cfixed[0] = static_cast(__int_bom); char_traits::copy(__cfixed + 1, __from, __size); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__fbytes, &__cto, &__tbytes); } else { intern_type* __cfixed = const_cast(__from); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__fbytes, &__cto, &__tbytes); } if (__conv != size_t(-1)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::ok; } else { if (__fbytes < __fmultiple * (__from_end - __from)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::partial; } else __ret = codecvt_base::error; } } return __ret; } template codecvt_base::result codecvt<_InternT, _ExternT, encoding_state>:: do_unshift(state_type& __state, extern_type* __to, extern_type* __to_end, extern_type*& __to_next) const { result __ret = codecvt_base::error; if (__state.good()) { const descriptor_type& __desc = __state.in_descriptor(); const size_t __tmultiple = sizeof(intern_type); size_t __tlen = __tmultiple * (__to_end - __to); // Argument list for iconv specifies a byte sequence. Thus, // all to/from arrays must be brutally casted to char*. char* __cto = reinterpret_cast(__to); size_t __conv = __iconv_adaptor(iconv,__desc, 0, 0, &__cto, &__tlen); if (__conv != size_t(-1)) { __to_next = reinterpret_cast(__cto); if (__tlen == __tmultiple * (__to_end - __to)) __ret = codecvt_base::noconv; else if (__tlen == 0) __ret = codecvt_base::ok; else __ret = codecvt_base::partial; } else __ret = codecvt_base::error; } return __ret; } template codecvt_base::result codecvt<_InternT, _ExternT, encoding_state>:: do_in(state_type& __state, const extern_type* __from, const extern_type* __from_end, const extern_type*& __from_next, intern_type* __to, intern_type* __to_end, intern_type*& __to_next) const { result __ret = codecvt_base::error; if (__state.good()) { const descriptor_type& __desc = __state.in_descriptor(); const size_t __fmultiple = sizeof(extern_type); size_t __flen = __fmultiple * (__from_end - __from); const size_t __tmultiple = sizeof(intern_type); size_t __tlen = __tmultiple * (__to_end - __to); // Argument list for iconv specifies a byte sequence. Thus, // all to/from arrays must be brutally casted to char*. char* __cto = reinterpret_cast(__to); char* __cfrom; size_t __conv; // Some encodings need a byte order marker as the first item // in the byte stream, to designate endian-ness. The default // value for the byte order marker is NULL, so if this is // the case, it's not necessary and we can just go on our // merry way. int __ext_bom = __state.external_bom(); if (__ext_bom) { size_t __size = __from_end - __from; extern_type* __cfixed = static_cast (__builtin_alloca(sizeof(extern_type) * (__size + 1))); __cfixed[0] = static_cast(__ext_bom); char_traits::copy(__cfixed + 1, __from, __size); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__flen, &__cto, &__tlen); } else { extern_type* __cfixed = const_cast(__from); __cfrom = reinterpret_cast(__cfixed); __conv = __iconv_adaptor(iconv, __desc, &__cfrom, &__flen, &__cto, &__tlen); } if (__conv != size_t(-1)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::ok; } else { if (__flen < static_cast(__from_end - __from)) { __from_next = reinterpret_cast(__cfrom); __to_next = reinterpret_cast(__cto); __ret = codecvt_base::partial; } else __ret = codecvt_base::error; } } return __ret; } template int codecvt<_InternT, _ExternT, encoding_state>:: do_encoding() const throw() { int __ret = 0; if (sizeof(_ExternT) <= sizeof(_InternT)) __ret = sizeof(_InternT) / sizeof(_ExternT); return __ret; } template bool codecvt<_InternT, _ExternT, encoding_state>:: do_always_noconv() const throw() { return false; } template int codecvt<_InternT, _ExternT, encoding_state>:: do_length(state_type&, const extern_type* __from, const extern_type* __end, size_t __max) const { return std::min(__max, static_cast(__end - __from)); } // _GLIBCXX_RESOLVE_LIB_DEFECTS // 74. Garbled text for codecvt::do_max_length template int codecvt<_InternT, _ExternT, encoding_state>:: do_max_length() const throw() { return 1; } _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif c++/8/ext/mt_allocator.h000064400000055723151027430570010734 0ustar00// MT-optimized allocator -*- C++ -*- // Copyright (C) 2003-2018 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // . /** @file ext/mt_allocator.h * This file is a GNU extension to the Standard C++ Library. */ #ifndef _MT_ALLOCATOR_H #define _MT_ALLOCATOR_H 1 #include #include #include #include #include #if __cplusplus >= 201103L #include #endif namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION using std::size_t; using std::ptrdiff_t; typedef void (*__destroy_handler)(void*); /// Base class for pool object. struct __pool_base { // Using short int as type for the binmap implies we are never // caching blocks larger than 32768 with this allocator. typedef unsigned short int _Binmap_type; // Variables used to configure the behavior of the allocator, // assigned and explained in detail below. struct _Tune { // Compile time constants for the default _Tune values. enum { _S_align = 8 }; enum { _S_max_bytes = 128 }; enum { _S_min_bin = 8 }; enum { _S_chunk_size = 4096 - 4 * sizeof(void*) }; enum { _S_max_threads = 4096 }; enum { _S_freelist_headroom = 10 }; // Alignment needed. // NB: In any case must be >= sizeof(_Block_record), that // is 4 on 32 bit machines and 8 on 64 bit machines. size_t _M_align; // Allocation requests (after round-up to power of 2) below // this value will be handled by the allocator. A raw new/ // call will be used for requests larger than this value. // NB: Must be much smaller than _M_chunk_size and in any // case <= 32768. size_t _M_max_bytes; // Size in bytes of the smallest bin. // NB: Must be a power of 2 and >= _M_align (and of course // much smaller than _M_max_bytes). size_t _M_min_bin; // In order to avoid fragmenting and minimize the number of // new() calls we always request new memory using this // value. Based on previous discussions on the libstdc++ // mailing list we have chosen the value below. // See http://gcc.gnu.org/ml/libstdc++/2001-07/msg00077.html // NB: At least one order of magnitude > _M_max_bytes. size_t _M_chunk_size; // The maximum number of supported threads. For // single-threaded operation, use one. Maximum values will // vary depending on details of the underlying system. (For // instance, Linux 2.4.18 reports 4070 in // /proc/sys/kernel/threads-max, while Linux 2.6.6 reports // 65534) size_t _M_max_threads; // Each time a deallocation occurs in a threaded application // we make sure that there are no more than // _M_freelist_headroom % of used memory on the freelist. If // the number of additional records is more than // _M_freelist_headroom % of the freelist, we move these // records back to the global pool. size_t _M_freelist_headroom; // Set to true forces all allocations to use new(). bool _M_force_new; explicit _Tune() : _M_align(_S_align), _M_max_bytes(_S_max_bytes), _M_min_bin(_S_min_bin), _M_chunk_size(_S_chunk_size), _M_max_threads(_S_max_threads), _M_freelist_headroom(_S_freelist_headroom), _M_force_new(std::getenv("GLIBCXX_FORCE_NEW") ? true : false) { } explicit _Tune(size_t __align, size_t __maxb, size_t __minbin, size_t __chunk, size_t __maxthreads, size_t __headroom, bool __force) : _M_align(__align), _M_max_bytes(__maxb), _M_min_bin(__minbin), _M_chunk_size(__chunk), _M_max_threads(__maxthreads), _M_freelist_headroom(__headroom), _M_force_new(__force) { } }; struct _Block_address { void* _M_initial; _Block_address* _M_next; }; const _Tune& _M_get_options() const { return _M_options; } void _M_set_options(_Tune __t) { if (!_M_init) _M_options = __t; } bool _M_check_threshold(size_t __bytes) { return __bytes > _M_options._M_max_bytes || _M_options._M_force_new; } size_t _M_get_binmap(size_t __bytes) { return _M_binmap[__bytes]; } size_t _M_get_align() { return _M_options._M_align; } explicit __pool_base() : _M_options(_Tune()), _M_binmap(0), _M_init(false) { } explicit __pool_base(const _Tune& __options) : _M_options(__options), _M_binmap(0), _M_init(false) { } private: explicit __pool_base(const __pool_base&); __pool_base& operator=(const __pool_base&); protected: // Configuration options. _Tune _M_options; _Binmap_type* _M_binmap; // Configuration of the pool object via _M_options can happen // after construction but before initialization. After // initialization is complete, this variable is set to true. bool _M_init; }; /** * @brief Data describing the underlying memory pool, parameterized on * threading support. */ template class __pool; /// Specialization for single thread. template<> class __pool : public __pool_base { public: union _Block_record { // Points to the block_record of the next free block. _Block_record* _M_next; }; struct _Bin_record { // An "array" of pointers to the first free block. _Block_record** _M_first; // A list of the initial addresses of all allocated blocks. _Block_address* _M_address; }; void _M_initialize_once() { if (__builtin_expect(_M_init == false, false)) _M_initialize(); } void _M_destroy() throw(); char* _M_reserve_block(size_t __bytes, const size_t __thread_id); void _M_reclaim_block(char* __p, size_t __bytes) throw (); size_t _M_get_thread_id() { return 0; } const _Bin_record& _M_get_bin(size_t __which) { return _M_bin[__which]; } void _M_adjust_freelist(const _Bin_record&, _Block_record*, size_t) { } explicit __pool() : _M_bin(0), _M_bin_size(1) { } explicit __pool(const __pool_base::_Tune& __tune) : __pool_base(__tune), _M_bin(0), _M_bin_size(1) { } private: // An "array" of bin_records each of which represents a specific // power of 2 size. Memory to this "array" is allocated in // _M_initialize(). _Bin_record* _M_bin; // Actual value calculated in _M_initialize(). size_t _M_bin_size; void _M_initialize(); }; #ifdef __GTHREADS /// Specialization for thread enabled, via gthreads.h. template<> class __pool : public __pool_base { public: // Each requesting thread is assigned an id ranging from 1 to // _S_max_threads. Thread id 0 is used as a global memory pool. // In order to get constant performance on the thread assignment // routine, we keep a list of free ids. When a thread first // requests memory we remove the first record in this list and // stores the address in a __gthread_key. When initializing the // __gthread_key we specify a destructor. When this destructor // (i.e. the thread dies) is called, we return the thread id to // the front of this list. struct _Thread_record { // Points to next free thread id record. NULL if last record in list. _Thread_record* _M_next; // Thread id ranging from 1 to _S_max_threads. size_t _M_id; }; union _Block_record { // Points to the block_record of the next free block. _Block_record* _M_next; // The thread id of the thread which has requested this block. size_t _M_thread_id; }; struct _Bin_record { // An "array" of pointers to the first free block for each // thread id. Memory to this "array" is allocated in // _S_initialize() for _S_max_threads + global pool 0. _Block_record** _M_first; // A list of the initial addresses of all allocated blocks. _Block_address* _M_address; // An "array" of counters used to keep track of the amount of // blocks that are on the freelist/used for each thread id. // - Note that the second part of the allocated _M_used "array" // actually hosts (atomic) counters of reclaimed blocks: in // _M_reserve_block and in _M_reclaim_block those numbers are // subtracted from the first ones to obtain the actual size // of the "working set" of the given thread. // - Memory to these "arrays" is allocated in _S_initialize() // for _S_max_threads + global pool 0. size_t* _M_free; size_t* _M_used; // Each bin has its own mutex which is used to ensure data // integrity while changing "ownership" on a block. The mutex // is initialized in _S_initialize(). __gthread_mutex_t* _M_mutex; }; // XXX GLIBCXX_ABI Deprecated void _M_initialize(__destroy_handler); void _M_initialize_once() { if (__builtin_expect(_M_init == false, false)) _M_initialize(); } void _M_destroy() throw(); char* _M_reserve_block(size_t __bytes, const size_t __thread_id); void _M_reclaim_block(char* __p, size_t __bytes) throw (); const _Bin_record& _M_get_bin(size_t __which) { return _M_bin[__which]; } void _M_adjust_freelist(const _Bin_record& __bin, _Block_record* __block, size_t __thread_id) { if (__gthread_active_p()) { __block->_M_thread_id = __thread_id; --__bin._M_free[__thread_id]; ++__bin._M_used[__thread_id]; } } // XXX GLIBCXX_ABI Deprecated void _M_destroy_thread_key(void*) throw (); size_t _M_get_thread_id(); explicit __pool() : _M_bin(0), _M_bin_size(1), _M_thread_freelist(0) { } explicit __pool(const __pool_base::_Tune& __tune) : __pool_base(__tune), _M_bin(0), _M_bin_size(1), _M_thread_freelist(0) { } private: // An "array" of bin_records each of which represents a specific // power of 2 size. Memory to this "array" is allocated in // _M_initialize(). _Bin_record* _M_bin; // Actual value calculated in _M_initialize(). size_t _M_bin_size; _Thread_record* _M_thread_freelist; void* _M_thread_freelist_initial; void _M_initialize(); }; #endif template